{"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.\nFrom sflib Require 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\n\nModule Label.\n  Inductive t :=\n  | read (ex:bool) (ord:OrdR.t) (loc:Loc.t) (val:Val.t)\n  | write (ex:bool) (ord:OrdW.t) (loc:Loc.t) (val:Val.t)\n  | barrier (b:Barrier.t)\n  | ctrl\n  .\n  #[global]\n  Hint Constructors t: core.\n\n  Definition is_ex (label:t): bool :=\n    match label with\n    | read ex _ _ _ => ex\n    | write ex _ _ _ => ex\n    | _ => false\n    end.\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_acquire_pc (label:t): bool :=\n    match label with\n    | read _ ord _ _ => OrdR.ge ord OrdR.acquire_pc\n    | _ => false\n    end.\n\n  Definition is_acquire (label:t): bool :=\n    match label with\n    | read _ ord _ _ => OrdR.ge ord OrdR.acquire\n    | _ => false\n    end.\n\n  Definition is_release_pc (label:t): bool :=\n    match label with\n    | write _ ord _ _ => OrdW.ge ord OrdW.release_pc\n    | _ => false\n    end.\n\n  Definition is_release (label:t): bool :=\n    match label with\n    | write _ ord _ _ => OrdW.ge ord OrdW.release\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 (loc:Loc.t) (label:t): bool :=\n    match label with\n    | write _ _ loc' _ => 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    | _ => 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    | _ => false\n    end.\n\n  Definition is_ctrl (label:t): bool :=\n    match label with\n    | ctrl => true\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  Lemma read_is_reading ex ord loc val:\n    is_reading loc (read ex ord loc val).\n  Proof.\n    s. destruct (equiv_dec loc loc); ss. exfalso. apply c. ss.\n  Qed.\n\n  Lemma write_is_writing ex ord loc val:\n    is_writing loc (write ex ord loc val).\n  Proof.\n    s. destruct (equiv_dec loc loc); ss. exfalso. apply c. ss.\n  Qed.\n\n  Lemma read_is_accessing ex ord loc val:\n    is_accessing loc (read ex ord loc val).\n  Proof.\n    s. destruct (equiv_dec loc loc); ss. exfalso. apply c. ss.\n  Qed.\n\n  Lemma write_is_accessing ex ord loc val:\n    is_accessing loc (write ex ord loc val).\n  Proof.\n    s. destruct (equiv_dec loc loc); ss. exfalso. apply c. ss.\n  Qed.\n\n  Lemma is_writing_inv\n        loc l\n        (WRITING: is_writing loc l):\n    exists ex ord val,\n      l = write ex ord loc val.\n  Proof.\n    destruct l; ss. destruct (equiv_dec loc0 loc); ss. inv e. eauto.\n  Qed.\n\n  Lemma is_reading_inv\n        loc l\n        (READING: is_reading loc l):\n    exists ex ord val,\n      l = read ex ord loc val.\n  Proof.\n    destruct l; ss. destruct (equiv_dec loc0 loc); ss. inv e. eauto.\n  Qed.\nEnd Label.\n\nModule ALocal.\n  Inductive t := mk {\n    labels: list Label.t;\n    addr: relation nat;\n    data: relation nat;\n    ctrl: relation nat;\n    rmw: relation nat;\n    exbank: option nat;\n  }.\n  #[global]\n  Hint Constructors t: core.\n\n  Definition init: t := mk [] bot bot bot bot None.\n\n  Definition next_eid (eu:t): nat :=\n    List.length eu.(labels).\n\n  Inductive step (event:Event.t (A:=nat -> Prop)) (alocal1:t) (alocal2:t): Prop :=\n  | step_internal\n      (EVENT: event = Event.internal)\n      (ALOCAL: alocal2 =\n               mk\n                 alocal1.(labels)\n                 alocal1.(addr)\n                 alocal1.(data)\n                 alocal1.(ctrl)\n                 alocal1.(rmw)\n                 alocal1.(exbank))\n  | step_read\n      ex ord vloc res\n      (EVENT: event = Event.read ex ord vloc (ValA.mk _ res (eq (next_eid alocal1))))\n      (ALOCAL: alocal2 =\n               mk\n                 (alocal1.(labels) ++ [Label.read ex ord vloc.(ValA.val) res])\n                 (alocal1.(addr) ∪ (vloc.(ValA.annot) × (eq (next_eid alocal1))))\n                 alocal1.(data)\n                 alocal1.(ctrl)\n                 alocal1.(rmw)\n                 (if ex then Some (next_eid alocal1) else alocal1.(exbank)))\n  | step_write\n      ex ord vloc vval\n      (EVENT: event = Event.write ex ord vloc vval (ValA.mk _ 0 (ifc (ex && (arch == riscv)) (eq (next_eid alocal1)))))\n      (EX: ex -> exists n,\n           alocal1.(exbank) = Some n /\\\n           opt_pred (fun l => Label.is_read l /\\ Label.is_ex l) (List.nth_error alocal1.(labels) n))\n      (ALOCAL: alocal2 =\n               mk\n                 (alocal1.(labels) ++ [Label.write ex ord vloc.(ValA.val) vval.(ValA.val)])\n                 (alocal1.(addr) ∪ (vloc.(ValA.annot) × (eq (next_eid alocal1))))\n                 (alocal1.(data) ∪ (vval.(ValA.annot) × (eq (next_eid alocal1))))\n                 alocal1.(ctrl)\n                 (alocal1.(rmw) ∪ (if ex then (fun n => alocal1.(exbank) = Some n) × (eq (next_eid alocal1)) else bot))\n                 (if ex then None else alocal1.(exbank)))\n  | step_write_failure\n      ord vloc vval\n      (EVENT: event = Event.write true ord vloc vval (ValA.mk _ 1 bot))\n      (ALOCAL: alocal2 =\n               mk\n                 alocal1.(labels)\n                 alocal1.(addr)\n                 alocal1.(data)\n                 alocal1.(ctrl)\n                 alocal1.(rmw)\n                 None)\n  | step_barrier\n      b\n      (EVENT: event = Event.barrier b)\n      (ALOCAL: alocal2 =\n               mk\n                 (alocal1.(labels) ++ [Label.barrier b])\n                 alocal1.(addr)\n                 alocal1.(data)\n                 alocal1.(ctrl)\n                 alocal1.(rmw)\n                 alocal1.(exbank))\n  | step_control\n      ctrl_e\n      (EVENT: event = (Event.control ctrl_e))\n      (ALOCAL: alocal2 =\n               mk\n                 (alocal1.(labels) ++ [Label.ctrl])\n                 alocal1.(addr)\n                 alocal1.(data)\n                 (alocal1.(ctrl) ∪ (ctrl_e × (eq (next_eid alocal1))))\n                 alocal1.(rmw)\n                 alocal1.(exbank))\n  .\n  #[global]\n  Hint Constructors step: core.\n\n  Inductive le (alocal1 alocal2:t): Prop :=\n  | le_intro\n      (LABELS: exists l, alocal2.(labels) = alocal1.(labels) ++ l)\n      (ADDR: alocal1.(addr) ⊆ alocal2.(addr))\n      (DATA: alocal1.(data) ⊆ alocal2.(data))\n      (CTRL: alocal1.(ctrl) ⊆ alocal2.(ctrl))\n      (RMW: alocal1.(rmw) ⊆ alocal2.(rmw))\n  .\n  #[global]\n  Hint Constructors le: core.\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:=nat -> Prop);\n    local: ALocal.t;\n  }.\n  #[global]\n  Hint Constructors t: core.\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  #[global]\n  Hint Constructors step: core.\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  #[global]\n  Hint Constructors label_is: core.\n\n  Definition wf_rmap (rmap: RMap.t (A:=nat -> Prop)) (labels:list Label.t): Prop :=\n    forall r n\n      (N: (RMap.find r rmap).(ValA.annot) n),\n      label_is labels Label.is_access n.\n  #[global]\n  Hint Unfold wf_rmap: core.\n\n  Lemma wf_rmap_expr\n        rmap labels e n\n        (WF: wf_rmap rmap labels)\n        (N: (sem_expr rmap e).(ValA.annot) n):\n    label_is labels Label.is_access n.\n  Proof.\n    revert n N. induction e; ss.\n    - i. eapply WF. eauto.\n    - i. inv N; eauto.\n  Qed.\n\n  Inductive wf (aeu:t): Prop :=\n  | wf_intro\n      (REG: wf_rmap aeu.(state).(State.rmap) aeu.(local).(ALocal.labels))\n      (ADDR: aeu.(local).(ALocal.addr) ⊆ lt)\n      (ADDR_LIMIT: forall e1 e2 (REL: aeu.(local).(ALocal.addr) e1 e2), e2 < List.length aeu.(local).(ALocal.labels))\n      (ADDR_LABEL: aeu.(local).(ALocal.addr) ⊆ (label_is aeu.(local).(ALocal.labels) Label.is_access) × (label_is aeu.(local).(ALocal.labels) Label.is_access))\n      (DATA: aeu.(local).(ALocal.data) ⊆ lt)\n      (DATA_LIMIT: forall e1 e2 (REL: aeu.(local).(ALocal.data) e1 e2), e2 < List.length aeu.(local).(ALocal.labels))\n      (DATA_LABEL: aeu.(local).(ALocal.data) ⊆ (label_is aeu.(local).(ALocal.labels) Label.is_access) × (label_is aeu.(local).(ALocal.labels) Label.is_write))\n      (CTRL: aeu.(local).(ALocal.ctrl) ⊆ lt)\n      (CTRL_LIMIT: forall e1 e2 (REL: aeu.(local).(ALocal.ctrl) e1 e2), e2 < List.length aeu.(local).(ALocal.labels))\n      (CTRL_LABEL: aeu.(local).(ALocal.ctrl) ⊆ (label_is aeu.(local).(ALocal.labels) Label.is_access) × (label_is aeu.(local).(ALocal.labels) Label.is_ctrl))\n      (RMW: aeu.(local).(ALocal.rmw) ⊆ lt)\n      (RMW_LIMIT: forall e1 e2 (REL: aeu.(local).(ALocal.rmw) e1 e2), e2 < List.length aeu.(local).(ALocal.labels))\n      (RMW1: forall n ord loc val\n               (LABEL: List.nth_error aeu.(local).(ALocal.labels) n = Some (Label.write true ord loc val)),\n          codom_rel aeu.(local).(ALocal.rmw) n)\n      (RMW2: forall a b\n               (RMW: aeu.(local).(ALocal.rmw) a b),\n          exists ord1 loc1 val1 ord2 loc2 val2,\n            <<LABEL1: List.nth_error aeu.(local).(ALocal.labels) a = Some (Label.read true ord1 loc1 val1)>> /\\\n            <<LABEL2: List.nth_error aeu.(local).(ALocal.labels) b = Some (Label.write true ord2 loc2 val2)>> /\\\n            <<BETWEEN: forall c ord3 loc3 val3 (C: a < c < b), List.nth_error aeu.(local).(ALocal.labels) c <> Some (Label.read true ord3 loc3 val3)>>)\n      (EXBANK': forall eb (EB: aeu.(local).(ALocal.exbank) = Some eb),\n          eb < List.length aeu.(local).(ALocal.labels))\n      (EXBANK: forall eb c ord3 loc3 val3\n                 (EB: aeu.(local).(ALocal.exbank) = Some eb)\n                 (C: eb < c),\n          List.nth_error aeu.(local).(ALocal.labels) c <> Some (Label.read true ord3 loc3 val3))\n  .\n  #[global]\n  Hint Constructors wf: core.\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    - ii. unfold RMap.find, RMap.init in *. rewrite IdMap.gempty in *. inv N.\n    - i. destruct n; 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        ii. revert N. unfold RMap.find, RMap.add. rewrite IdMap.add_spec. condtac; eauto.\n        inversion e. subst. apply wf_rmap_expr. ss.\n      + destruct local1. refl.\n    - splits.\n      + inv WF. econs; ss.\n        all: try rewrite List.app_length; s.\n        all: unfold ALocal.next_eid in *.\n        * ii. revert N. unfold RMap.find, RMap.add. rewrite IdMap.add_spec. condtac.\n          { inversion e. subst. i. inv N.\n            econs.\n            - unfold ALocal.next_eid. rewrite List.nth_error_app2, Nat.sub_diag; ss.\n            - ss.\n          }\n          { i. apply label_is_mon. exploit REG; eauto. }\n        * ii. inv H.\n          { exploit ADDR_LIMIT; eauto. }\n          { inv H0. splits; eauto using label_is_lt, wf_rmap_expr. }\n        * i. inv REL.\n          { exploit ADDR_LIMIT; eauto. lia. }\n          { inv H. lia. }\n        * ii. inv H.\n          { eapply times_mon; [| |by apply ADDR_LABEL].\n            - apply label_is_mon.\n            - i. apply label_is_mon. ss.\n          }\n          { inv H0. econs.\n            - apply label_is_mon. eapply wf_rmap_expr; eauto.\n            - econs.\n              + unfold ALocal.next_eid. rewrite List.nth_error_app2, Nat.sub_diag; ss.\n              + ss.\n          }\n        * ii. exploit DATA_LIMIT; eauto. lia.\n        * ii. eapply times_mon; [| |by apply DATA_LABEL].\n          { apply label_is_mon. }\n          { apply label_is_mon. }\n        * ii. exploit CTRL_LIMIT; eauto. lia.\n        * ii. econs; ss.\n          { apply label_is_mon. eapply CTRL_LABEL. eauto. }\n          { apply label_is_mon. eapply CTRL_LABEL. eauto. }\n        * ii. exploit RMW_LIMIT; eauto. lia.\n        * i. apply nth_error_snoc_inv in LABEL. des; ss.\n          eapply RMW1. eauto.\n        * i. exploit RMW2; eauto. i. des. esplits; eauto using nth_error_app_mon.\n          i. rewrite List.nth_error_app1; eauto. etrans; [apply C|]. apply List.nth_error_Some. congr.\n        * i. destruct ex0; ss.\n          { inv EB. lia. }\n          { exploit EXBANK'; eauto. lia. }\n        * ii. apply nth_error_snoc_inv in H. des; ss.\n          { destruct ex0.\n            { inv EB. unfold ALocal.next_eid in *. lia. }\n            eapply EXBANK; eauto.\n          }\n          { subst. inv H0. inv EB. unfold ALocal.next_eid in *. lia. }\n      + econs; ss.\n        * esplits; eauto.\n        * left. ss.\n    - splits.\n      + inv WF. econs; ss.\n        all: try rewrite List.app_length; s.\n        all: unfold ALocal.next_eid in *.\n        * ii. revert N. unfold RMap.find, RMap.add. rewrite IdMap.add_spec. condtac.\n          { inversion e. subst. s. unfold ifc. condtac; ss. i. subst. econs.\n            - unfold ALocal.next_eid. rewrite List.nth_error_app2, Nat.sub_diag; ss.\n            - ss.\n          }\n          { i. apply label_is_mon. exploit REG; eauto. }\n        * ii. inv H.\n          { exploit ADDR_LIMIT; eauto. }\n          { inv H0. splits; eauto using label_is_lt, wf_rmap_expr. }\n        * i. inv REL.\n          { exploit ADDR_LIMIT; eauto. lia. }\n          { inv H. lia. }\n        * ii. inv H.\n          { eapply times_mon; [| |by apply ADDR_LABEL].\n            - apply label_is_mon.\n            - apply label_is_mon.\n          }\n          { inv H0. econs.\n            - apply label_is_mon. eapply wf_rmap_expr; eauto.\n            - econs.\n              + unfold ALocal.next_eid. rewrite List.nth_error_app2, Nat.sub_diag; ss.\n              + ss.\n          }\n        * ii. inv H.\n          { exploit DATA_LIMIT; eauto. }\n          { inv H0. splits; eauto using label_is_lt, wf_rmap_expr. }\n        * i. inv REL.\n          { exploit DATA_LIMIT; eauto. lia. }\n          { inv H. lia. }\n        * ii. inv H.\n          { eapply times_mon; [| |by apply DATA_LABEL].\n            - apply label_is_mon.\n            - apply label_is_mon.\n          }\n          { inv H0. econs.\n            - apply label_is_mon. eapply wf_rmap_expr; eauto.\n            - econs.\n              + unfold ALocal.next_eid. rewrite List.nth_error_app2, Nat.sub_diag; ss.\n              + ss.\n          }\n        * i. exploit CTRL_LIMIT; eauto. lia.\n        * ii. econs; ss.\n          { apply label_is_mon. eapply CTRL_LABEL. eauto. }\n          { apply label_is_mon. eapply CTRL_LABEL. eauto. }\n        * ii. inv H.\n          { exploit RMW_LIMIT; eauto. }\n          { destruct ex0; ss. inv H0. splits; eauto using label_is_lt, wf_rmap_expr. }\n        * i. inv REL.\n          { exploit RMW_LIMIT; eauto. lia. }\n          { destruct ex0; ss. inv H. lia. }\n        * i. apply nth_error_snoc_inv in LABEL. des.\n          { exploit RMW1; eauto. intro x. inv x. econs. left. eauto. }\n          { subst. inv LABEL0. exploit EX; eauto. i. des. econs. right. econs; eauto. }\n        * i. inv RMW0.\n          { exploit RMW2; eauto. i. des. esplits.\n            - apply nth_error_app_mon. eauto.\n            - apply nth_error_app_mon. eauto.\n            - i. rewrite List.nth_error_app1; eauto. etrans; [apply C|]. apply List.nth_error_Some. congr.\n          }\n          { destruct ex0; ss. inv H. exploit EX; eauto. intro x. des. inv x0. des.\n            destruct a0; ss. destruct ex; ss.\n            rewrite H0 in x. inv x. symmetry in H1.\n            esplits.\n            - apply nth_error_app_mon. eauto.\n            - rewrite List.nth_error_app2, Nat.sub_diag; ss.\n            - ii. apply nth_error_snoc_inv in H. des.\n              + eapply EXBANK; eauto.\n              + unfold ALocal.next_eid in *. lia.\n          }\n        * i. destruct ex0; ss. exploit EXBANK'; eauto. lia.\n        * ii. destruct ex0; ss. apply nth_error_snoc_inv in H. des; ss.\n          eapply EXBANK; eauto.\n      + econs; ss.\n        * esplits; eauto.\n        * left. ss.\n        * left. ss.\n        * left. ss.\n    - splits.\n      + inv WF. econs; ss.\n        ii. revert N. unfold RMap.find, RMap.add. rewrite IdMap.add_spec. condtac; eauto.\n        inversion e. subst. i. inv N.\n      + econs; ss. eexists. rewrite List.app_nil_r. ss.\n    - splits.\n      + inv WF. econs; ss.\n        all: try rewrite List.app_length; s.\n        all: unfold ALocal.next_eid in *.\n        * ii. apply label_is_mon. exploit REG; eauto.\n        * i. exploit ADDR_LIMIT; eauto. lia.\n        * ii. eapply times_mon; [| |by apply ADDR_LABEL].\n          { apply label_is_mon. }\n          { apply label_is_mon. }\n        * i. exploit DATA_LIMIT; eauto. lia.\n        * ii. eapply times_mon; [| |by apply DATA_LABEL].\n          { apply label_is_mon. }\n          { apply label_is_mon. }\n        * i. exploit CTRL_LIMIT; eauto. lia.\n        * ii. econs; ss.\n          { apply label_is_mon. eapply CTRL_LABEL. eauto. }\n          { apply label_is_mon. eapply CTRL_LABEL. eauto. }\n        * i. exploit RMW_LIMIT; eauto. lia.\n        * i. apply nth_error_snoc_inv in LABEL. des; eauto. inv LABEL0.\n        * i. exploit RMW2; eauto. i. des. esplits.\n          { apply nth_error_app_mon. eauto. }\n          { apply nth_error_app_mon. eauto. }\n          { i. rewrite List.nth_error_app1; eauto. etrans; [apply C|]. apply List.nth_error_Some. congr. }\n        * i. exploit EXBANK'; eauto. lia.\n        * ii. apply nth_error_snoc_inv in H. des; ss.\n          eapply EXBANK; eauto.\n      + econs; ss. eexists; eauto.\n    - splits.\n      + inv WF. econs; ss.\n        all: try rewrite List.app_length; s.\n        all: unfold ALocal.next_eid in *.\n        * ii. apply label_is_mon. exploit REG; eauto.\n        * i. exploit ADDR_LIMIT; eauto. lia.\n        * ii. eapply times_mon; [| |by apply ADDR_LABEL].\n          { apply label_is_mon. }\n          { apply label_is_mon. }\n        * i. exploit DATA_LIMIT; eauto. lia.\n        * ii. eapply times_mon; [| |by apply DATA_LABEL].\n          { apply label_is_mon. }\n          { apply label_is_mon. }\n        * ii. inv H.\n          { exploit CTRL_LIMIT; eauto. }\n          { inv H0. splits; eauto using label_is_lt, wf_rmap_expr. }\n        * i. inv REL.\n          { exploit CTRL_LIMIT; eauto. lia. }\n          { inv H. lia. }\n        * ii. inv H.\n          { eapply times_mon; [| |by apply CTRL_LABEL].\n            - apply label_is_mon.\n            - apply label_is_mon.\n          }\n          { inv H0. econs.\n            - apply label_is_mon. eapply wf_rmap_expr; eauto.\n            - econs.\n              + unfold ALocal.next_eid. rewrite List.nth_error_app2, Nat.sub_diag; ss.\n              + ss.\n          }\n        * i. exploit RMW_LIMIT; eauto. lia.\n        * i. apply nth_error_snoc_inv in LABEL. des; eauto. inv LABEL0.\n        * i. exploit RMW2; eauto. i. des. esplits.\n          { apply nth_error_app_mon. eauto. }\n          { apply nth_error_app_mon. eauto. }\n          { i. rewrite List.nth_error_app1; eauto. etrans; [apply C|]. apply List.nth_error_Some. congr. }\n        * i. exploit EXBANK'; eauto. lia.\n        * ii. apply nth_error_snoc_inv in H. des; ss.\n          eapply EXBANK; eauto.\n      + econs; ss; eauto. left. ss.\n    - splits.\n      + inv WF. econs; ss.\n      + destruct local1. refl.\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    addr: relation eidT;\n    data: relation eidT;\n    ctrl0: relation eidT;\n    rmw: relation eidT;\n    co: relation eidT;\n    rf: relation eidT;\n  }.\n  #[global]\n  Hint Constructors t: core.\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  #[global]\n  Hint Constructors label_is: core.\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  #[global]\n  Hint Constructors label_rel: core.\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  #[global]\n  Hint Constructors label_is_rel: core.\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  #[global]\n  Hint Constructors label_loc: core.\n\n  (* let obs = rfe | fr | co *)\n\n  (* let dob = *)\n  (* \t| (addr | data); rfi? *)\n  (* \t| (ctrl | (addr; po)); ([W] | [ISB]; po; [R]) *)\n\n  (* let aob = [range(rmw)]; rfi; [A | Q] *)\n\n  (* let bob = *)\n  (* \t| [R|W]; po; [dmb.full]; po; [R|W] *)\n  (* \t| [L]; po; [A] *)\n  (* \t| [R]; po; [dmb.ld]; po; [R|W] *)\n  (* \t| [A | Q]; po; [R|W] *)\n  (* \t| [W]; po; [dmb.st]; po; [W] *)\n  (* \t| [R|W]; po; [L] *)\n\n  (* let ob = obs | dob | aob | bob *)\n\n  (* acyclic po-loc | fr | co | rf as internal *)\n  (* acyclic ob as external *)\n  (* empty rmw & (fre; coe) as atomic *)\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  #[global]\n  Hint Constructors po: core.\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  #[global]\n  Hint Constructors po_adj: core.\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.\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  #[global]\n  Hint Constructors i: core.\n\n  Inductive e (eid1 eid2:eidT): Prop :=\n  | e_intro\n      (TID: fst eid1 <> fst eid2)\n  .\n  #[global]\n  Hint Constructors e: core.\n\n\n  Definition ctrl (ex: t): relation eidT := ex.(ctrl0) ⨾ po.\n  Definition po_loc (ex:t): relation eidT := po ∩ ex.(label_rel) label_loc.\n  Definition fr (ex:t): relation eidT :=\n    (ex.(rf)⁻¹ ⨾ ex.(co)) ∪\n    ((ex.(label_rel) label_loc) ∩\n     ((ex.(label_is) Label.is_read) \\₁ codom_rel ex.(rf)) × (ex.(label_is) Label.is_write)).\n  Definition rfi (ex:t): relation eidT := ex.(rf) ∩ i.\n  Definition rfe (ex:t): relation eidT := ex.(rf) ∩ e.\n  Definition fre (ex:t): relation eidT := (fr ex) ∩ e.\n  Definition coe (ex:t): relation eidT := ex.(co) ∩ e.\n\n  Definition internal (ex:t): relation eidT := (po_loc ex) ∪ (fr ex) ∪ ex.(co) ∪ ex.(rf).\n\n  Definition obs (ex:t): relation eidT := (rfe ex) ∪ (fr ex) ∪ ex.(co).\n\n  Definition dob (ex:t): relation eidT :=\n    ((ex.(addr) ∪ ex.(data)) ⨾ (rfi ex)^?) ∪\n    (((ctrl ex) ∪ (ex.(addr) ⨾ po)) ⨾\n     (⦗ex.(label_is) Label.is_write⦘ ∪\n      (⦗ex.(label_is) (eq (Label.barrier Barrier.isb))⦘ ⨾ po ⨾ ⦗ex.(label_is) Label.is_read⦘))).\n\n  Definition aob (ex:t): relation eidT :=\n    ⦗codom_rel ex.(rmw)⦘ ⨾ (rfi ex) ⨾ ⦗fun eid => arch = riscv \\/ ex.(label_is) Label.is_acquire_pc eid⦘.\n\n  Definition bob (ex:t): relation eidT :=\n    (⦗ex.(label_is) Label.is_read⦘ ⨾\n     po ⨾\n     ⦗ex.(label_is) (Label.is_barrier_c Barrier.is_dmb_rr)⦘ ⨾\n     po ⨾\n     ⦗ex.(label_is) Label.is_read⦘) ∪\n\n    (⦗ex.(label_is) Label.is_read⦘ ⨾\n     po ⨾\n     ⦗ex.(label_is) (Label.is_barrier_c Barrier.is_dmb_rw)⦘ ⨾\n     po ⨾\n     ⦗ex.(label_is) Label.is_write⦘) ∪\n\n    (⦗ex.(label_is) Label.is_write⦘ ⨾\n     po ⨾\n     ⦗ex.(label_is) (Label.is_barrier_c Barrier.is_dmb_wr)⦘ ⨾\n     po ⨾\n     ⦗ex.(label_is) Label.is_read⦘) ∪\n\n    (⦗ex.(label_is) Label.is_write⦘ ⨾\n     po ⨾\n     ⦗ex.(label_is) (Label.is_barrier_c Barrier.is_dmb_ww)⦘ ⨾\n     po ⨾\n     ⦗ex.(label_is) Label.is_write⦘) ∪\n\n    (⦗ex.(label_is) Label.is_release⦘ ⨾\n     po ⨾\n     ⦗ex.(label_is) Label.is_acquire⦘) ∪\n\n    (⦗ex.(label_is) Label.is_acquire_pc⦘ ⨾\n     po) ∪\n\n    (po ⨾\n     ⦗ex.(label_is) Label.is_release_pc⦘) ∪\n\n    (ifc (arch == riscv) ex.(rmw)).\n\n  Definition ob (ex:t): relation eidT :=\n    (obs ex) ∪ (dob ex) ∪ (aob ex) ∪ (bob ex).\nEnd Execution.\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.\n#[export]\nHint Constructors tid_lift: core.\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.\n#[export]\nHint Constructors tid_join: core.\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    ADDR: ex.(Execution.addr) = tid_join (IdMap.map (fun aeu => aeu.(AExecUnit.local).(ALocal.addr)) aeus);\n    DATA: ex.(Execution.data) = tid_join (IdMap.map (fun aeu => aeu.(AExecUnit.local).(ALocal.data)) aeus);\n    CTRL: ex.(Execution.ctrl0) = tid_join (IdMap.map (fun aeu => aeu.(AExecUnit.local).(ALocal.ctrl)) aeus);\n    RMW: ex.(Execution.rmw) = tid_join (IdMap.map (fun aeu => aeu.(AExecUnit.local).(ALocal.rmw)) aeus);\n  }.\n  #[global]\n  Hint Constructors pre_ex: core.\n\n  Definition co1 (ex: Execution.t) :=\n    forall eid1 eid2,\n      (exists loc\n          ex1 ord1 val1\n          ex2 ord2 val2,\n          <<LABEL: Execution.label eid1 ex = Some (Label.write ex1 ord1 loc val1)>> /\\\n          <<LABEL: Execution.label eid2 ex = Some (Label.write ex2 ord2 loc val2)>>) ->\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         ex1 ord1 val1\n         ex2 ord2 val2,\n        <<LABEL: Execution.label eid1 ex = Some (Label.write ex1 ord1 loc val1)>> /\\\n        <<LABEL: Execution.label eid2 ex = Some (Label.write ex2 ord2 loc val2)>>.\n\n  Definition rf1 (ex: Execution.t) :=\n    forall eid1 ex1 ord1 loc val\n       (LABEL: Execution.label eid1 ex = Some (Label.read ex1 ord1 loc val)),\n      (<<NORF: ~ codom_rel ex.(Execution.rf) eid1>> /\\ <<VAL: val = Val.default>>) \\/\n      (exists eid2 ex2 ord2,\n          <<LABEL: Execution.label eid2 ex = Some (Label.write ex2 ord2 loc val)>> /\\\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 ex1 ex2 ord1 ord2 loc val,\n      <<READ: Execution.label eid1 ex = Some (Label.read ex1 ord1 loc val)>> /\\\n      <<WRITE: Execution.label eid2 ex = Some (Label.write ex2 ord2 loc val)>>.\n\n  Definition rf_wf (ex: Execution.t) := functional (ex.(Execution.rf))⁻¹.\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    INTERNAL: acyclic (Execution.internal ex);\n    EXTERNAL: acyclic (Execution.ob ex);\n    ATOMIC: le (ex.(Execution.rmw) ∩ ((Execution.fre ex) ⨾ (Execution.coe ex))) bot;\n  }.\n  #[global]\n  Hint Constructors ex: core.\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 data_is_po\n        p exec\n        (EX: pre_ex p exec):\n    exec.(Execution.data) ⊆ Execution.po.\n  Proof.\n    rewrite EX.(DATA).\n    ii. inv H. inv REL. destruct x, y. ss. subst. rewrite IdMap.map_spec in RELS.\n    destruct (IdMap.find t EX.(aeus)) eqn:LOCAL; ss. inv RELS.\n    generalize (EX.(AEUS) t). rewrite LOCAL. intro X. inv X. des.\n    exploit AExecUnit.rtc_step_future; eauto.\n    { apply AExecUnit.wf_init. }\n    s. i. des. econs; ss.\n    inv WF. apply DATA0. ss.\n  Qed.\n\n  Lemma ctrl0_is_po\n        p exec\n        (EX: pre_ex p exec):\n    exec.(Execution.ctrl0) ⊆ Execution.po.\n  Proof.\n    rewrite EX.(CTRL).\n    ii. inv H. inv REL. destruct x, y. ss. subst. rewrite IdMap.map_spec in RELS.\n    destruct (IdMap.find t EX.(aeus)) eqn:LOCAL; ss. inv RELS.\n    generalize (EX.(AEUS) t). rewrite LOCAL. intro X. inv X. des.\n    exploit AExecUnit.rtc_step_future; eauto.\n    { apply AExecUnit.wf_init. }\n    s. i. des. econs; ss.\n    inv WF. apply CTRL0. ss.\n  Qed.\n\n  Lemma ctrl_is_po\n        p exec\n        (EX: pre_ex p exec):\n    Execution.ctrl exec ⊆ Execution.po.\n  Proof.\n    ii. inv H. des. etrans; eauto.\n    eapply ctrl0_is_po; eauto.\n  Qed.\n\n  Lemma addr_is_po\n        p exec\n        (EX: pre_ex p exec):\n    exec.(Execution.addr) ⊆ Execution.po.\n  Proof.\n    rewrite EX.(ADDR).\n    ii. inv H. inv REL. destruct x, y. ss. subst. rewrite IdMap.map_spec in RELS.\n    destruct (IdMap.find t EX.(aeus)) eqn:LOCAL; ss. inv RELS.\n    generalize (EX.(AEUS) t). rewrite LOCAL. intro X. inv X. des.\n    exploit AExecUnit.rtc_step_future; eauto.\n    { apply AExecUnit.wf_init. }\n    s. i. des. econs; ss.\n    inv WF. apply ADDR0. ss.\n  Qed.\n\n  Lemma rmw_is_po\n        p exec\n        (EX: pre_ex p exec):\n    exec.(Execution.rmw) ⊆ Execution.po.\n  Proof.\n    rewrite EX.(RMW).\n    ii. inv H. inv REL. destruct x, y. ss. subst. rewrite IdMap.map_spec in RELS.\n    destruct (IdMap.find t EX.(aeus)) eqn:LOCAL; ss. inv RELS.\n    generalize (EX.(AEUS) t). rewrite LOCAL. intro X. inv X. des.\n    exploit AExecUnit.rtc_step_future; eauto.\n    { apply AExecUnit.wf_init. }\n    s. i. des. econs; ss.\n    inv WF. apply RMW0. ss.\n  Qed.\n\n  Lemma write_ex_codom_rmw\n        p exec\n        (EX: pre_ex p exec)\n        eid\n        (WRITE: exec.(Execution.label_is) (fun l => Label.is_write l /\\ Label.is_ex l) eid):\n    codom_rel exec.(Execution.rmw) eid.\n  Proof.\n    destruct eid as [tid n]. rewrite EX.(RMW).\n    inv WRITE. des. destruct l; ss. destruct ex0; ss. revert EID. unfold Execution.label.\n    rewrite EX.(LABELS), IdMap.map_spec. s.\n    destruct (IdMap.find tid EX.(aeus)) eqn:LOCAL; ss. i.\n    generalize (EX.(AEUS) tid). rewrite LOCAL. intro X. inv X. des.\n    exploit AExecUnit.rtc_step_future; eauto.\n    { apply AExecUnit.wf_init. }\n    s. i. des. inv WF. exploit RMW1; eauto. intro X. inv X.\n    econs. econs.\n    - rewrite IdMap.map_spec, LOCAL. ss.\n    - instantiate (1 := (_, _)). econs; ss; eauto.\n  Qed.\n\n  Lemma rmw_spec\n        p exec eid1 eid2\n        (EX: pre_ex p exec)\n        (RMW: exec.(Execution.rmw) eid1 eid2):\n    <<PO: Execution.po eid1 eid2>> /\\\n    <<LABEL1: exec.(Execution.label_is) (fun l => Label.is_read l /\\ Label.is_ex l) eid1>> /\\\n    <<LABEL2: exec.(Execution.label_is) (fun l => Label.is_write l /\\ Label.is_ex l) eid2>> /\\\n    <<BETWEEN: forall eid3 (AC: Execution.po eid1 eid3) (AC: Execution.po eid3 eid2),\n        ~ exec.(Execution.label_is) (fun l => Label.is_read l /\\ Label.is_ex l) eid3>>.\n  Proof.\n    revert RMW. rewrite EX.(RMW).\n    i. inv RMW0. inv REL. destruct eid1, eid2. ss. subst. rewrite IdMap.map_spec in RELS.\n    destruct (IdMap.find t EX.(aeus)) eqn:LOCAL; ss. inv RELS.\n    generalize (EX.(AEUS) t). rewrite LOCAL. intro X. inv X. des.\n    exploit AExecUnit.rtc_step_future; eauto.\n    { apply AExecUnit.wf_init. }\n    s. i. des. inv WF. exploit RMW2; eauto. i. des. splits; eauto.\n    - econs.\n      + unfold Execution.label. rewrite EX.(LABELS), IdMap.map_spec. s. rewrite LOCAL. eauto.\n      + ss.\n    - econs.\n      + unfold Execution.label. rewrite EX.(LABELS), IdMap.map_spec. s. rewrite LOCAL. eauto.\n      + ss.\n    - ii. inv AC. inv AC0. ss. subst. inv H. revert EID.\n      unfold Execution.label. rewrite EX.(LABELS), IdMap.map_spec, LOCAL. s. i.\n      des. destruct l; ss. destruct ex0; ss.\n      eapply BETWEEN; eauto.\n  Qed.\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 coherence_rw\n        p exec\n        eid1 eid2 eid3 loc\n        (EX: ex p exec)\n        (EID1: exec.(Execution.label_is) (Label.is_reading loc) eid1)\n        (EID2: exec.(Execution.label_is) (Label.is_writing loc) eid2)\n        (EID3: exec.(Execution.label_is) (Label.is_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. apply Label.is_reading_inv in LABEL. des. subst.\n    inv EID2. apply Label.is_writing_inv in LABEL. des. subst.\n    inv EID3. apply Label.is_writing_inv in LABEL. des. subst.\n    exploit EX.(CO1).\n    { rewrite EID0, EID1. esplits; eauto. }\n    i. des.\n    - subst. exfalso. eapply EX.(INTERNAL). econs 2; econs.\n      + left. left. left. econs; eauto. econs; eauto.\n        econs; eauto using Label.read_is_accessing, Label.write_is_accessing.\n      + right. eauto.\n    - exfalso. eapply EX.(INTERNAL). econs 2; [econs|econs 2; econs].\n      + left. left. left. econs; eauto. econs; eauto.\n        econs; eauto using Label.read_is_accessing, Label.write_is_accessing.\n      + left. right. eauto.\n      + right. eauto.\n    - ss.\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_writing loc) eid1)\n        (EID2: exec.(Execution.label_is) (Label.is_writing loc) eid2)\n        (PO: Execution.po eid1 eid2):\n    exec.(Execution.co) eid1 eid2.\n  Proof.\n    inv EID1. apply Label.is_writing_inv in LABEL. des. subst.\n    inv EID2. apply Label.is_writing_inv in LABEL. des. subst.\n    exploit EX.(CO1).\n    { rewrite EID, EID0. esplits; eauto. }\n    i. des.\n    - subst. inv PO. lia.\n    - ss.\n    - exfalso. eapply EX.(INTERNAL). econs 2; econs.\n      + left. left. left. econs; eauto. econs; eauto.\n        econs; eauto using Label.read_is_accessing, Label.write_is_accessing.\n      + left. right. 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_reading loc) eid1)\n        (EID2: exec.(Execution.label_is) (Label.is_reading loc) eid2)\n        (EID3: exec.(Execution.label_is) (Label.is_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. apply Label.is_reading_inv in LABEL. des. subst.\n    inv EID2. apply Label.is_reading_inv in LABEL. des. subst.\n    inv EID3. apply Label.is_writing_inv in LABEL. des. subst.\n    exploit EX.(RF1); eauto. i. des.\n    { exfalso. eapply EX.(INTERNAL). econs 2; [econs|econs 2; econs].\n      - left. left. right. econs 2. econs; cycle 1.\n        + econs; eauto. econs; eauto.\n        + econs; eauto. econs; eauto using Label.read_is_accessing, Label.write_is_accessing.\n      - right. eauto.\n      - left. left. left. econs; eauto. econs; eauto.\n        econs; eauto using Label.read_is_accessing, Label.write_is_accessing.\n    }\n    esplits; eauto.\n    exploit EX.(CO1).\n    { rewrite EID1, LABEL. esplits; eauto. }\n    i. des.\n    - subst. eauto.\n    - econs 2. ss.\n    - exfalso. eapply EX.(INTERNAL). econs 2; [econs|econs 2; econs].\n      + left. left. left. econs; eauto. econs; eauto.\n        econs; eauto using Label.read_is_accessing, Label.write_is_accessing.\n      + left. left. right. left. econs; eauto.\n      + right. ss.\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_writing loc) eid1)\n        (EID2: exec.(Execution.label_is) (Label.is_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. apply Label.is_writing_inv in LABEL. des. subst.\n    inv EID2. apply Label.is_reading_inv in LABEL. des. subst.\n    exploit EX.(RF1); eauto. i. des.\n    { exfalso. eapply EX.(INTERNAL). econs 2; econs.\n      - left. left. right. econs 2. econs; cycle 1.\n        + econs; eauto. econs; eauto.\n        + econs; eauto. econs; eauto using Label.read_is_accessing, Label.write_is_accessing.\n      - left. left. left. econs; eauto. econs; eauto.\n        econs; eauto using Label.read_is_accessing, Label.write_is_accessing.\n    }\n    esplits; eauto.\n    exploit EX.(CO1).\n    { rewrite EID, LABEL. esplits; eauto. }\n    i. des.\n    - subst. eauto.\n    - econs 2. ss.\n    - exfalso. eapply EX.(INTERNAL). econs 2; econs.\n      + left. left. left. econs; eauto. econs; eauto.\n        econs; eauto using Label.read_is_accessing, Label.write_is_accessing.\n      + left. left. right. left. econs; eauto.\n  Qed.\n\n  Lemma rf_inv_write\n        p exec\n        eid1 eid2 ex1 ord1 loc val\n        (EX: ex p exec)\n        (EID2: Execution.label eid2 exec = Some (Label.read ex1 ord1 loc val))\n        (RF3: exec.(Execution.rf) eid1 eid2):\n    exists ex2 ord2,\n      <<LABEL: Execution.label eid1 exec = Some (Label.write ex2 ord2 loc val)>>.\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  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.aob _ _ _ |- _] => inv H\n           | [H: Execution.bob _ _ _ |- _] => inv H\n           | [H: Execution.fr _ _ _ |- _] => inv H\n           | [H: Execution.rfe _ _ _ |- _] => inv H\n           | [H: Execution.rfi _ _ _ |- _] => 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           end;\n       des).\n\n\n  Lemma addr_label\n        p exec\n        eid1 eid2\n        (EX: pre_ex p exec)\n        (ADDR: exec.(Execution.addr) eid1 eid2):\n    <<EID1: Execution.label_is exec (Label.is_access) eid1>> /\\\n    <<EID2: Execution.label_is exec (Label.is_access) eid2>>.\n  Proof.\n    rewrite EX.(Valid.ADDR) in ADDR. inv ADDR.\n    destruct eid1 as [tid1 iid1].\n    destruct eid2 as [tid2 iid2].\n    inv REL. ss. subst.\n    rewrite IdMap.map_spec in RELS.\n    destruct (IdMap.find tid1 EX.(aeus)) eqn:LOCAL; ss. inv RELS.\n    generalize (EX.(AEUS) tid1). rewrite LOCAL. intro X. inv X.\n    exploit AExecUnit.rtc_step_future; eauto.\n    { apply AExecUnit.wf_init. }\n    s. i. des.\n    inv WF. exploit ADDR_LABEL; eauto. intro X. inv X.\n    esplits.\n    - inv H. econs; eauto.\n      unfold Execution.label. s.\n      rewrite EX.(LABELS), IdMap.map_spec, LOCAL. ss.\n    - inv H1. econs; eauto. unfold Execution.label. s. rewrite EX.(LABELS), IdMap.map_spec, LOCAL. ss.\n  Qed.\n\n  Lemma data_label\n        p exec\n        eid1 eid2\n        (EX: pre_ex p exec)\n        (DATA: exec.(Execution.data) eid1 eid2):\n    <<EID1: Execution.label_is exec (Label.is_access) eid1>> /\\\n    <<EID2: Execution.label_is exec (Label.is_write) eid2>>.\n  Proof.\n    rewrite EX.(Valid.DATA) in DATA. inv DATA.\n    destruct eid1 as [tid1 iid1].\n    destruct eid2 as [tid2 iid2].\n    inv REL. ss. subst.\n    rewrite IdMap.map_spec in RELS.\n    destruct (IdMap.find tid1 EX.(aeus)) eqn:LOCAL; ss. inv RELS.\n    generalize (EX.(AEUS) tid1). rewrite LOCAL. intro X. inv X.\n    exploit AExecUnit.rtc_step_future; eauto.\n    { apply AExecUnit.wf_init. }\n    s. i. des.\n    inv WF. exploit DATA_LABEL; eauto. intro X. inv X.\n    esplits.\n    - inv H. econs; eauto.\n      unfold Execution.label. s.\n      rewrite EX.(LABELS), IdMap.map_spec, LOCAL. ss.\n    - inv H1. econs; eauto.\n      unfold Execution.label. s.\n      rewrite EX.(LABELS), IdMap.map_spec, LOCAL. ss.\n  Qed.\n\n  Lemma ctrl0_label\n        p exec\n        eid1 eid2\n        (EX: pre_ex p exec)\n        (CTRL: exec.(Execution.ctrl0) eid1 eid2):\n    <<EID1: Execution.label_is exec (Label.is_access) eid1>> /\\\n    <<EID2: Execution.label_is exec (Label.is_ctrl) eid2>>.\n  Proof.\n    rewrite EX.(Valid.CTRL) in CTRL. inv CTRL.\n    destruct eid1 as [tid1 iid1].\n    destruct eid2 as [tid2 iid2].\n    inv REL. ss. subst.\n    rewrite IdMap.map_spec in RELS.\n    destruct (IdMap.find tid1 EX.(aeus)) eqn:LOCAL; ss. inv RELS.\n    generalize (EX.(AEUS) tid1). rewrite LOCAL. intro X. inv X.\n    exploit AExecUnit.rtc_step_future; eauto.\n    { apply AExecUnit.wf_init. }\n    s. i. des.\n    inv WF. exploit CTRL_LABEL; eauto. intro X. inv X.\n    splits.\n    - inv H. econs; eauto.\n      unfold Execution.label. s.\n      rewrite EX.(LABELS), IdMap.map_spec, LOCAL. ss.\n    - inv H1. econs; eauto.\n      unfold Execution.label. s.\n      rewrite EX.(LABELS), IdMap.map_spec, LOCAL. ss.\n  Qed.\n\n  Lemma ctrl_label\n        p exec\n        eid1 eid2\n        (EX: pre_ex p exec)\n        (CTRL: Execution.ctrl exec eid1 eid2):\n    <<EID1: Execution.label_is exec (Label.is_access) eid1>>.\n  Proof.\n    inv CTRL. des. exploit ctrl0_label; eauto. i. des. auto.\n  Qed.\n\n  Lemma barrier_ob_po\n        p exec\n        eid1 eid2\n        (EX: pre_ex p exec)\n        (CO2: co2 exec)\n        (RF2: rf2 exec)\n        (EID1: Execution.label_is exec Label.is_barrier eid1)\n        (OB: Execution.ob exec eid1 eid2):\n    Execution.po eid1 eid2.\n  Proof.\n    inv EID1. destruct l; ss. unfold co2, rf2 in *.\n    obtac; ss.\n    all: try by etrans; eauto.\n    - exploit RF2; eauto. i. des. congr.\n    - exploit RF2; eauto. i. des. congr.\n    - destruct l1; try congr; ss.\n    - exploit CO2; eauto. i. des. congr.\n    - eapply addr_label in H1; eauto. des. inv EID1. destruct l; ss; congr.\n    - eapply data_label in H1; eauto. des. inv EID1. destruct l; ss; congr.\n    - eapply ctrl_is_po; eauto.\n    - etrans; eauto. eapply addr_is_po; eauto.\n    - etrans; eauto. eapply ctrl_is_po; eauto.\n    - etrans; eauto. etrans; eauto. eapply addr_is_po; eauto.\n    - exploit RF2; eauto. i. des. congr.\n    - exploit RF2; eauto. i. des. congr.\n    - revert H0. unfold ifc. condtac; ss. eapply rmw_spec. eauto.\n  Qed.\n\n  Lemma ob_barrier_ob\n        p exec\n        eid1 eid2 eid3\n        (PRE: pre_ex p exec)\n        (CO2: co2 exec)\n        (RF2: rf2 exec)\n        (EID2: Execution.label_is exec Label.is_barrier eid2)\n        (OB1: Execution.ob exec eid1 eid2)\n        (OB2: Execution.ob exec eid2 eid3):\n    <<OB: Execution.ob exec eid1 eid3>>.\n  Proof.\n    inv EID2. destruct l; ss. exploit barrier_ob_po; eauto. i.\n    unfold co2, rf2 in *. clear OB2.\n    obtac.\n    all: try by rewrite EID in EID1; inv EID1; ss.\n    all: try by rewrite EID in EID2; inv EID2; ss.\n    all: try by destruct l; try congr; ss.\n    - exploit RF2; eauto. i. des. congr.\n    - exploit CO2; eauto. i. des. congr.\n    - exploit CO2; eauto. i. des. congr.\n    - inv H0.\n      + eapply addr_label in H1; eauto. des. inv EID2. destruct l; ss; try congr.\n      + inv H. exploit RF2; eauto. i. des. congr.\n    - inv H0.\n      + eapply data_label in H1; eauto. des. inv EID2. destruct l; ss. congr.\n      + inv H. exploit RF2; eauto. i. des. congr.\n    - exploit RF2; eauto. i. des. congr.\n    - right. left. left. right. econs. splits; [by econs; eauto|]. etrans; eauto.\n    - revert H0. unfold ifc. condtac; ss. i. exploit rmw_spec; eauto. i. des.\n      inv LABEL2. rewrite EID in EID0. inv EID0. des. ss.\n  Qed.\n\n  Lemma ctrl_ob_po\n        p exec\n        eid1 eid2\n        (EX: pre_ex p exec)\n        (CO2: co2 exec)\n        (RF2: rf2 exec)\n        (EID1: Execution.label_is exec Label.is_ctrl eid1)\n        (OB: Execution.ob exec eid1 eid2):\n    Execution.po eid1 eid2.\n  Proof.\n    inv EID1. destruct l; ss. unfold co2, rf2 in *.\n    obtac; ss.\n    all: try by etrans; eauto.\n    - exploit RF2; eauto. i. des. congr.\n    - exploit RF2; eauto. i. des. congr.\n    - destruct l1; try congr; ss.\n    - exploit CO2; eauto. i. des. congr.\n    - eapply addr_label in H1; eauto. des. inv EID1. destruct l; ss; congr.\n    - eapply data_label in H1; eauto. des. inv EID1. destruct l; ss; congr.\n    - eapply ctrl_is_po; eauto.\n    - etrans; eauto. eapply addr_is_po; eauto.\n    - etrans; eauto. eapply ctrl_is_po; eauto.\n    - etrans; eauto. etrans; eauto. eapply addr_is_po; eauto.\n    - exploit RF2; eauto. i. des. congr.\n    - exploit RF2; eauto. i. des. congr.\n    - revert H0. unfold ifc. condtac; ss. eapply rmw_spec. eauto.\n  Qed.\n\n  Lemma ob_ctrl_ob\n        p exec\n        eid1 eid2 eid3\n        (PRE: pre_ex p exec)\n        (CO2: co2 exec)\n        (RF2: rf2 exec)\n        (EID2: Execution.label_is exec Label.is_ctrl eid2)\n        (OB1: Execution.ob exec eid1 eid2)\n        (OB2: Execution.ob exec eid2 eid3):\n    <<OB: Execution.ob exec eid1 eid3>>.\n  Proof.\n    inv EID2. destruct l; ss. exploit ctrl_ob_po; eauto. i.\n    unfold co2, rf2 in *. clear OB2.\n    obtac.\n    all: try by rewrite EID in EID1; inv EID1; ss.\n    all: try by rewrite EID in EID2; inv EID2; ss.\n    all: try by destruct l; try congr; ss.\n    - exploit RF2; eauto. i. des. congr.\n    - exploit CO2; eauto. i. des. congr.\n    - exploit CO2; eauto. i. des. congr.\n    - inv H0.\n      + eapply addr_label in H1; eauto. des. inv EID2. destruct l; ss; try congr.\n      + inv H. exploit RF2; eauto. i. des. congr.\n    - inv H0.\n      + eapply data_label in H1; eauto. des. inv EID2. destruct l; ss. congr.\n      + inv H. exploit RF2; eauto. i. des. congr.\n    - exploit RF2; eauto. i. des. congr.\n    - right. left. left. right. econs. splits; [by econs; eauto|]. etrans; eauto.\n    - revert H0. unfold ifc. condtac; ss. i. exploit rmw_spec; eauto. i. des.\n      inv LABEL2. rewrite EID in EID0. inv EID0. des. ss.\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        (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    all: try by exploit RF2; eauto; i; des; congr.\n    all: try by exploit CO2; eauto; i; des; congr.\n    - exploit addr_label; eauto. i. des. inv EID0. congr.\n    - exploit data_label; eauto. i. des. inv EID0. congr.\n    - exploit ctrl_label; eauto. i. des. inv x0. congr.\n    - exploit addr_label; eauto. i. des. inv EID0. congr.\n    - exploit ctrl_label; eauto. i. des. inv x1. congr.\n    - exploit addr_label; eauto. i. des. inv EID2. congr.\n    - exploit po_label_pre; try exact EID; eauto. i. des. congr.\n    - revert H0. unfold ifc. condtac; ss. i. exploit rmw_spec; eauto. i. des. inv LABEL1. 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        (CYCLE: (Execution.ob exec)⁺ eid eid):\n    exists eid_nb,\n      (Execution.ob exec ∩ (Execution.label_is_rel exec Label.is_access))⁺ eid_nb eid_nb.\n  Proof.\n    exploit minimalize_cycle; eauto.\n    { instantiate (1 := Execution.label_is exec Label.is_access).\n      i. destruct (Execution.label b exec) eqn:LABEL.\n      - destruct t; try by contradict H1; econs; eauto.\n        + eapply ob_barrier_ob; eauto.\n        + eapply ob_ctrl_ob; eauto.\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        * exploit barrier_ob_po; eauto. i. inv x2. lia.\n        * exploit ctrl_ob_po; eauto. i. inv x2. lia.\n      + exfalso. eapply ob_label; eauto.\n  Qed.\n\n  Lemma internal_rw\n        p ex\n        eid1 eid2\n        (PRE: pre_ex p ex)\n        (CO2: co2 ex)\n        (RF2: rf2 ex)\n        (INTERNAL: Execution.internal ex eid1 eid2):\n    <<EID1: ex.(Execution.label_is) Label.is_access eid1>> /\\\n    <<EID2: ex.(Execution.label_is) Label.is_access eid2>>.\n  Proof.\n    unfold Execution.internal in *. obtac.\n    - inv H. inv H1. inv LABEL. splits.\n      + destruct l1; ss; econs; eauto.\n      + destruct l2; ss; econs; eauto.\n    - exploit CO2; eauto. i. des.\n      exploit RF2; eauto. i. des.\n      splits; econs; eauto.\n    - splits.\n      + destruct l1; ss; econs; eauto.\n      + destruct l2; ss; econs; eauto.\n    - exploit CO2; eauto. i. des.\n      splits; econs; eauto.\n    - exploit RF2; eauto. i. des.\n      splits; econs; eauto.\n  Qed.\n\n  Lemma internal_read_read_po\n        p ex\n        eid1 eid2\n        (PRE: pre_ex p ex)\n        (CO2: co2 ex)\n        (RF2: rf2 ex)\n        (INTERNAL: Execution.internal 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    unfold Execution.internal in *. obtac.\n    - inv H. ss.\n    - exploit CO2; eauto. i. des.\n      destruct l; ss. congr.\n    - rewrite EID in EID0. inv EID0. destruct l0; ss.\n    - exploit CO2; eauto. i. des.\n      destruct l; ss. congr.\n    - exploit RF2; eauto. i. des.\n      destruct l0; ss. congr.\n  Qed.\n\n  Lemma ob_read_read_po\n        p ex\n        eid1 eid2\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        (INTERNAL: acyclic (Execution.internal 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. destruct l; ss. destruct l0; ss.\n    unfold Execution.ob in *. obtac; try congr.\n    all: try by etrans; eauto.\n    all: try by exploit RF2; eauto; i; des; congr.\n    all: try by exploit CO2; eauto; i; des; congr.\n    - inv H0. rewrite EID0 in EID1. inv EID1. inv LABEL1.\n    - exploit addr_is_po; eauto. i. inv H0; ss. etrans; eauto.\n      cut (Execution.po x eid2 \\/ Execution.po eid2 x).\n      { i. inv H. des; auto.\n        exfalso. eapply INTERNAL. econs 2.\n        - econs. right. eauto.\n        - exploit RF2; eauto. i. des.\n          econs. repeat left. repeat (econs; eauto); ss.\n          + instantiate (1 := loc1).\n            unfold equiv_dec. unfold Z_eqdec. unfold proj_sumbool.\n            des_ifs; ss.\n          + unfold equiv_dec. unfold Z_eqdec. unfold proj_sumbool.\n            des_ifs; ss. }\n      inv H. inv H2. destruct x as [t1 e1], eid2 as [t2 e2]. ss.\n      exploit RF2; eauto. i. des.\n      generalize (Nat.lt_trichotomy e1 e2). i. des; try congr.\n      + left. econs; eauto.\n      + right. econs; eauto.\n    - exploit data_is_po; eauto. i. inv H0; ss. etrans; eauto.\n      cut (Execution.po x eid2 \\/ Execution.po eid2 x).\n      { i. inv H. des; auto.\n        exfalso. eapply INTERNAL. econs 2.\n        - econs. right. eauto.\n        - exploit RF2; eauto. i. des.\n          econs. repeat left. repeat (econs; eauto); ss.\n          + instantiate (1 := loc1).\n            unfold equiv_dec. unfold Z_eqdec. unfold proj_sumbool.\n            des_ifs; ss.\n          + unfold equiv_dec. unfold Z_eqdec. unfold proj_sumbool.\n            des_ifs; ss. }\n      inv H. inv H2. destruct x as [t1 e1], eid2 as [t2 e2]. ss.\n      exploit RF2; eauto. i. des.\n      generalize (Nat.lt_trichotomy e1 e2). i. des; try congr.\n      + left. econs; eauto.\n      + right. econs; eauto.\n    - eapply ctrl_is_po; eauto.\n    - etrans; eauto. eapply addr_is_po; eauto.\n    - rewrite <- H2. eapply ctrl_is_po; eauto.\n    - rewrite <- H2, <- H0. eapply addr_is_po; eauto.\n    - revert H0. unfold ifc. condtac; ss. eapply rmw_spec. eauto.\n  Qed.\n\n  Lemma rfi_is_po\n        ex eid1 eid2\n        (RF2: Valid.rf2 ex)\n        (INTERNAL: acyclic (Execution.internal ex))\n        (RFI: Execution.rfi ex eid1 eid2):\n    Execution.po eid1 eid2.\n  Proof.\n    destruct eid1 as [tid1 eid1], eid2 as [tid2 eid2].\n    inv RFI. inv H0. ss. subst.\n    exploit RF2; eauto. i. des.\n    generalize (Nat.lt_trichotomy eid1 eid2). i. des.\n    - econs; ss.\n    - subst. congr.\n    - exfalso. eapply INTERNAL. econs 2.\n      + econs 1. right. eauto.\n      + econs 1. left. left. left. econs; eauto.\n        econs; eauto. econs; unfold Label.is_accessing; eauto.\n        * instantiate (1 := loc).\n          destruct (equiv_dec loc loc); ss.\n          exfalso. apply c. ss.\n        * destruct (equiv_dec loc loc); ss.\n          exfalso. apply c. ss.\n  Qed.\n\n  Lemma po_loc_write_is_co\n        ex eid1 eid2 loc\n        (CO1: Valid.co1 ex)\n        (INTERNAL: acyclic (Execution.internal ex))\n        (PO: Execution.po eid1 eid2)\n        (LABEL1: ex.(Execution.label_is) (Label.is_writing loc) eid1)\n        (LABEL2: ex.(Execution.label_is) (Label.is_writing loc) eid2):\n    ex.(Execution.co) eid1 eid2.\n  Proof.\n    destruct eid1 as [tid1 eid1], eid2 as [tid2 eid2].\n    inv LABEL1. inv LABEL2. destruct l, l0; ss.\n    destruct (equiv_dec loc0 loc) eqn:Heq1; ss.\n    destruct (equiv_dec loc1 loc) eqn:Heq2; ss.\n    rewrite e, e0 in *.\n    exploit CO1; eauto.\n    { esplits; [exact EID|exact EID0]. }\n    intro x. des; eauto.\n    - inv x. inv PO. ss. lia.\n    - exfalso. eapply INTERNAL. econs 2.\n      + econs 1. left. left. left. econs; eauto.\n        econs; eauto. econs; unfold Label.is_accessing; eauto.\n        * instantiate (1 := loc).\n          destruct (equiv_dec loc loc); ss.\n        * destruct (equiv_dec loc loc); ss.\n      + econs 1. left. right. eauto.\n  Qed.\nEnd Valid.\n\nCoercion Valid.PRE: Valid.ex >-> Valid.pre_ex.\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/axiomatic/Axiomatic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.29997489744818634}}
{"text": "From mathcomp Require Import all_ssreflect.\nFrom mathcomp Require Import finmap multiset.\nFrom Coq Require Import Reals Relation_Definitions Relation_Operators Lra.\nFrom mathcomp Require Import boolp Rstruct.\nFrom Algorand Require Import fmap_ext algorand_model safety_helpers quorums safety.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nOpen Scope mset_scope.\nOpen Scope fmap_scope.\nOpen Scope fset_scope.\n\n(** NOTE: This is only an initial attempt at specifying liveness \nproperties for the transition system. This part is still \nwork-in-progress and thus the file contains incomplete \n(admitted) proofs. *)\n\nDefinition users_at ix path : {fmap UserId -> UState} :=\n  match drop ix path with\n  | g1 :: _ => g1.(users)\n  | _ => [fmap]\n  end.\n\nDefinition user_stv_val (uid:UserId) (g:GState) (p:nat) (stv':option Value) : bool :=\n  if g.(users).[? uid] is Some ustate then ustate.(stv).[? p] == stv' else false.\n\nDefinition user_stv_val_at ix path uid p stv : bool :=\n  match drop ix path with\n  | g1 :: _ => user_stv_val uid g1 p stv\n  | _ => false\n  end.\n\n(** ** Sensible states *)\n\n(** This notion specifies what states can be considered valid states. The idea\nis that we only consider execution traces that begin at sensible states,\nsince sensibility is preserved by the transition system (to be shown), the\nset of reachable states will also be sensible (to be shown). This means that\nit is not important which specific state is assumed as the initial state as\nlong as the state is sensible.\nNote: the traditional operational notion of an initial state is a now a\nspecial case of sensibility. *)\nDefinition sensible_ustate (us : UState) : Prop :=\n  (us.(p_start) >= 0)%R /\\\n  (0 <= us.(timer) <= us.(deadline))%R .\n\nDefinition sensible_gstate (gs : GState) : Prop :=\n  (gs.(now) >= 0)%R /\\\n  ~ gs.(users) = [fmap] /\\\n  domf gs.(msg_in_transit) `<=` domf gs.(users) /\\ (* needed? *)\n  forall uid (k:uid \\in gs.(users)), sensible_ustate gs.(users).[k].\n  (* more constraints if we add corrupt users map and total message history *)\n\nLemma step_later_deadlines : forall s,\n    s > 3 -> next_deadline s = (lambda + big_lambda + (INR s - 3) * L)%R.\nProof.\n  intros s H_s; clear -H_s.\n  unfold next_deadline.\n  do 3 (destruct s;[exfalso;apply not_false_is_true;assumption|]).\n  reflexivity.\nQed.\n\n(** The user transition relation preserves sensibility of user states. *)\nLemma utr_msg_preserves_sensibility : forall uid us us' m ms,\n  sensible_ustate us -> uid # us ; m ~> (us', ms) ->\n  sensible_ustate us'.\nProof.\n  intros uid us us' m ms H_sensible Hstep;\n  remember (us',ms) as ustep_output eqn:H_output;\n  destruct Hstep; injection H_output; intros; subst;\n  match goal with\n  | [H_sensible : sensible_ustate ?s |- _] => is_var s;\n     destruct s;unfold sensible_ustate in * |- *;\n     decompose record H_sensible;clear H_sensible;simpl in * |- *\n  end;\n  autounfold with utransition_unfold in * |- *;\n  match goal with\n  | [H : context C [valid_rps] |- _] => unfold valid_rps in H;simpl in H;decompose record H\n  | _ => idtac\n  end;\n  try by intuition lra.\n  (* deliver nonvote msg needs some custom steps *)\n  clear H_output.\n  destruct msg as [mtype ex_val ? ? ?];\n    destruct ex_val;simpl;[destruct mtype;simpl|..];intuition lra.\nQed.\n\nLemma utr_nomsg_preserves_sensibility : forall uid us us' ms,\n  sensible_ustate us -> uid # us ~> (us', ms) ->\n  sensible_ustate us'.\nProof.\n  let use_hyp H := (unfold valid_rps in H;simpl in H; decompose record H) in\n  let tidy _ :=\n  (match goal with\n    | [ |- context C [ next_deadline (?s + 1 - 1) ] ] =>\n      replace (s + 1 - 1) with s by (rewrite addn1;rewrite subn1;symmetry;apply Nat.pred_succ)\n    | [ H : is_true (3 < ?s) |- context C [next_deadline ?s] ] =>\n      rewrite (step_later_deadlines H)\n  end) in\n  intros uid us us' ms H_sensible Hstep;\n  remember (us',ms) as ustep_output eqn:H_output;\n  destruct Hstep; injection H_output; intros; subst;\n  match goal with\n  | [H_sensible : sensible_ustate ?s |- _] => is_var s;\n     destruct s;unfold sensible_ustate in * |- *;\n     decompose record H_sensible;clear H_sensible;simpl in * |- *\n  end;\n  try (\n    match goal with\n    | [H: propose_ok _ _ _ _ _ _ |- _] => unfold propose_ok in H; use_hyp H\n    | [H: repropose_ok _ _ _ _ _ |- _] => unfold repropose_ok in H; use_hyp H\n    | [H: no_propose_ok _ _ _ _ |- _] => unfold no_propose_ok in H; use_hyp H\n    | [H: softvote_new_ok _ _ _ _ _ |- _] => unfold softvote_new_ok in H; use_hyp H\n    | [H: softvote_repr_ok _ _ _ _ _ |- _] => unfold softvote_repr_ok in H; use_hyp H\n    | [H: no_softvote_ok _ _ _ _ |- _] => unfold no_softvote_ok in H; use_hyp H\n    | [H: certvote_ok _ _ _ _ _ _ |- _] => unfold certvote_ok in H; use_hyp H\n    | [H: no_certvote_ok _ _ _ _ |- _] => unfold no_certvote_ok in H; use_hyp H\n    | [H: nextvote_val_ok _ _ _ _ _ _ _ |- _] => unfold nextvote_val_ok in H; use_hyp H\n    | [H: nextvote_open_ok _ _ _ _ _ _ _ |- _] => unfold nextvote_open_ok in H; use_hyp H\n    | [H: nextvote_stv_ok _ _ _ _ _ _ _ /\\ _ |- _] => destruct H as [H Hs]; unfold nextvote_stv_ok in H; use_hyp H\n    | [H: no_nextvote_ok _ _ _ _ _ |- _] => unfold no_nextvote_ok in H; use_hyp H\n    | [H: set_softvotes _ _ _ _ |- _] => unfold set_softvotes in H; use_hyp H\n    | [H: certvote_timeout_ok _ _ _ _ |- _] => unfold timout_ok in H; use_hyp H\n    | _ => idtac\n    end;\n    repeat (tidy ());intuition lra).\n   - split => //; split => //.\n     by admit.\n   - split => //; split => //.\n     by admit.\n   - split => //; split => //.\n     by admit.\n   - split => //; split => //.\n     by admit.\nAdmitted.\n\n(** The global transition relation preserves sensibility of global states. *)\nLemma gtr_preserves_sensibility : forall gs gs',\n  sensible_gstate gs -> GTransition gs gs' ->\n  sensible_gstate gs'.\nProof.\n  let use_hyp H := (unfold valid_rps in H;simpl in H; decompose record H) in\n  intros gs gs' H_sensible Hstep;\n  destruct Hstep.\n\n  * destruct pre. unfold tick_update, tick_users. simpl.\n    admit.\n  * apply utr_msg_preserves_sensibility in H1;\n      [|unfold sensible_gstate in H_sensible;decompose record H_sensible;done].\n    destruct pre;unfold sensible_gstate in * |- *.\n    unfold delivery_result;simpl in * |- *.\n    { intuition.\n      * move :H5. clear.\n        move/(f_equal (fun f => uid \\in f)).\n        change (uid \\in ?f) with (uid \\in domf f).\n          by rewrite dom_setf fset1U1 in_fset0.\n      * admit.\n      * rewrite ffunE. simpl.\n        set test := (uid0 == uid);destruct test eqn:H_eq;subst test.\n        assumption.\n        change (uid0 \\in ?f) with (uid0 \\in domf f) in k.\n        rewrite dom_setf in_fset1U H_eq /= in k.\n        by rewrite in_fnd;apply H6.\n    }\n  * apply utr_nomsg_preserves_sensibility in H0;\n      [|unfold sensible_gstate in H_sensible;decompose record H_sensible;done].\n    destruct pre;unfold sensible_gstate in * |- *.\n    unfold step_result;simpl in * |- *.\n    { intuition.\n      * move:H4; clear.\n        move/(f_equal (fun f => uid \\in f)).\n        change (uid \\in ?f) with (uid \\in domf f).\n          by rewrite dom_setf fset1U1 in_fset0.\n      * admit.\n      * rewrite ffunE. simpl.\n        set test := (uid0 == uid);destruct test eqn:H_eq;subst test.\n        assumption.\n        change (uid0 \\in ?f) with (uid0 \\in domf f) in k.\n        rewrite dom_setf in_fset1U H_eq /= in k.\n        by rewrite in_fnd;apply H5.\n    }\n  * (* recover from partition *)\n    admit.\n  * (* make partitioned *)\n    admit.\n  * (* corrupt user *)\n    admit.\n  * (* replay message *)\n    admit.\n  * (* forge message *)\nAdmitted.\n\n(* Generalization of preservation of sensibility to paths *)\nLemma greachable_preserves_sensibility : forall g0 g,\n  greachable g0 g -> sensible_gstate g0 -> sensible_gstate g.\nProof.\n  move => g0 g [p Hp] Hg.\n  destruct p. inversion Hp.\n  unfold is_trace in Hp.\n  destruct Hp as [Hg' Hpath].\n  subst g1.\n  elim: p g0 g Hg Hpath => /= [g g0 Hg|]; first by rewrite Hg.\n  move => g p IH g1 g0 Hl.\n  move/andP => [Ht Hp] Hs.\n  move/IH: Hp => Hp.\n  move/Hp: Hl; apply.\n  move: Ht.\n  move/asboolP.\n  exact: gtr_preserves_sensibility.\nQed.\n\nLemma at_most_one_certval_in_p\n      g0 trace (H_path: is_trace g0 trace)\n      r0 (H_start: state_before_round r0 g0):\n  forall ix g, onth trace ix = Some g ->\n  forall uid u, g.(users).[? uid] = Some u ->\n  forall r, r0 <= r ->\n  forall p v1 v2,\n    v1 \\in certvals u r p -> v2 \\in certvals u r p -> v1 = v2.\nProof.\n  clear -H_path H_start.\n  move => ix g H_onth uid u H_lookup r H_round p v1 v2.\n  unfold certvals, vote_values, soft_weight.\n  rewrite !mem_filter.\n  move => /andP [Hv1_q Hv1in].\n  move => /andP [Hv2_q Hv2in].\n  have H_votes_checked := (softvote_credentials_checked H_path H_start H_onth H_lookup H_round).\n\n  have Hq := quorums_s_honest_overlap trace.\n  specialize (Hq r p 2 _ _ (H_votes_checked _ _) Hv1_q (H_votes_checked _ _) Hv2_q).\n\n  move: Hq => [softvoter [H_voted_v1 [H_voted_v2 H_softvoter_honest]]].\n  assert (softvoted_in_path trace softvoter r p v1) as H_sent_v1. {\n  apply (softvotes_sent H_path H_start H_onth H_lookup H_round).\n  move:H_voted_v1 => /imfsetP /= [] x /andP [H_x_in].\n  unfold matchValue. destruct x. move => /eqP ? /= ?;subst.\n  assumption.\n  assumption.\n  }\n  assert (softvoted_in_path trace softvoter r p v2) as H_sent_v2. {\n  apply (softvotes_sent H_path H_start H_onth H_lookup H_round).\n  move:H_voted_v2 => /imfsetP /= [] x /andP [H_x_in].\n  unfold matchValue. destruct x. move => /eqP ? /= ?;subst.\n  assumption.\n  assumption.\n  }\n  move: H_sent_v1 => [ix_v1 H_sent_v1].\n  move: H_sent_v2 => [ix_v2 H_sent_v2].\n\n  by case:(no_two_softvotes_in_p H_path H_sent_v1 H_sent_v2).\nQed.\n\n(** A user has (re-)proposed a value/block for a given round/period\nalong a given path. *)\nDefinition proposed_in_path_at ix path uid r p v b : Prop :=\n  exists g1 g2, step_in_path_at g1 g2 ix path /\\\n    (user_sent uid (mkMsg Proposal (val v) r p uid) g1 g2 /\\\n     user_sent uid (mkMsg Block (val b) r p uid) g1 g2 \\/\n     user_sent uid (mkMsg Reproposal (repr_val v uid p) r p uid) g1 g2).\n\n(** A block proposer (potential leader) for a given round/period along a path. *)\nDefinition block_proposer_in_path_at ix path uid r p v b : Prop :=\n  uid \\in committee r p 1 /\\\n  valid_block_and_hash b v /\\\n  proposed_in_path_at ix path uid r p v b.\n\n(** The block proposer (the leader) for a given round/period along a path. *)\nDefinition leader_in_path_at ix path uid r p v b : Prop :=\n  block_proposer_in_path_at ix path uid r p v b /\\\n  forall id, id \\in committee r p 1 /\\ id <> uid ->\n    (credential uid r p 1 < credential id r p 1)%O.\n\n(** A trace is partition-free if it is either empty or it is a valid trace that\nstarts at an unparitioned state and does not involve a partitioning\ntransition -- Note: not compatible with [is_trace] above. *)\n\nDefinition partition_free g0 trace : Prop :=\n  is_trace g0 trace /\\\n  is_unpartitioned g0 /\\\n  forall n, ~ step_at trace n lbl_enter_partition.\n\nLemma partition_state : forall g,\n  is_unpartitioned g ->\n  is_partitioned (make_partitioned g).\nProof.\n  intros g unp_H.\n  unfold is_unpartitioned,is_partitioned in unp_H.\n  unfold is_partitioned, make_partitioned, flip_partition_flag.\n  simpl. assumption.\nQed.\n\n(** [is_partitioned] as a proposition. *)\nLemma is_partitionedP : forall g : GState,\n  reflect\n    (g.(network_partition) = true)\n    (is_partitioned g).\nAdmitted.\n\nLemma partition_free_step : forall g0 g1,\n  is_unpartitioned g0 -> GTransition g0 g1 ->\n  ~ related_by lbl_enter_partition g0 g1 ->\n  is_unpartitioned g1.\nProof.\nintros g0 g1 g0unp_H g0g1step_H notpstep_H.\nunfold related_by in notpstep_H. intuition.\nunfold make_partitioned in H0. unfold flip_partition_flag in H0. simpl in * |- *.\n(* almost all cases are straightforward *)\ndestruct g0g1step_H ; auto.\n(* except recover_from_partitioned, which is handled separately *)\n  unfold is_unpartitioned in g0unp_H. rewrite H in g0unp_H. auto.\nQed.\n\nLemma partition_free_prefix : forall g0 n trace,\n  n > 0 ->\n  partition_free g0 trace ->\n  partition_free g0 (take n trace).\nProof.\nAdmitted.\n\nLemma partition_free_suffix : forall g0 n trace,\n  n < size trace ->\n  partition_free g0 trace ->\n  partition_free g0 (drop n trace).\nProof.\nAdmitted.\n\n(* Whether the effect of a message is recored in the user state *)\nDefinition message_recorded ustate msg : Prop :=\nmatch msg_type msg, msg_ev msg with\n| Block, val b =>\n  let: r := msg_round msg in\n  b \\in ustate.(blocks) r\n| Proposal, val v =>\n  let: uid := msg_sender msg in\n  let: r := msg_round msg in\n  let: p := msg_period msg in\n  exists c, (uid, c, v, true) \\in ustate.(proposals) (r, p)\n| Reproposal, repr_val v uid' p' =>\n  let: uid := msg_sender msg in\n  let: r := msg_round msg in\n  let: p := msg_period msg in\n  exists c, (uid, c, v, false) \\in ustate.(proposals) (r, p)\n| Softvote, val v =>\n  let: uid := msg_sender msg in\n  let: r := msg_round msg in\n  let: p := msg_period msg in\n  (uid, v) \\in ustate.(softvotes) (r, p)\n| Certvote, val v =>\n  let: uid := msg_sender msg in\n  let: r := msg_round msg in\n  let: p := msg_period msg in\n  (uid, v) \\in ustate.(certvotes) (r, p)\n| Nextvote_Open, step_val s =>\n  let: uid := msg_sender msg in\n  let: r := msg_round msg in\n  let: p := msg_period msg in\n  uid \\in ustate.(nextvotes_open) (r, p, s)\n| Nextvote_Val, next_val v s =>\n  let: uid := msg_sender msg in\n  let: r := msg_round msg in\n  let: p := msg_period msg in\n  (uid, v) \\in ustate.(nextvotes_val) (r, p, s)\n| _, _ => True\nend.\n\n(** The effect of the message is recorded in the state of the target user on or\nbefore the message's deadline. *)\nDefinition msg_timely_delivered msg deadline gstate target : Prop :=\n  Rle gstate.(now) deadline /\\\n  exists ustate, gstate.(users).[? target] = Some ustate /\\\n  message_recorded ustate msg.\n\n(** If a message is sent along a partition-free trace, and the trace is long enough,\n   then the message is received by all honest users in a timely fashion. *)\n(* Note: this probably needs revision *)\nLemma sent_msg_timely_received : forall sender msg g0 g1 trace,\n  let deadline := msg_deadline msg g0.(now) in\n    user_sent sender msg g0 g1 ->\n    path gtransition g0 (g1 :: trace) ->\n    partition_free g0 (g1 :: trace) ->\n    Rle deadline (last g0 (g1 :: trace)).(now) ->\n    exists ix g, ohead (drop ix (g1 :: trace)) = Some g\n      /\\ (forall target, target \\in honest_users g.(users) ->\n            msg_timely_delivered msg deadline g target).\nProof.\nAdmitted.\n\n\n(** If the block proposer of period [r,1] is honest, then a certificate for round [r]\nis produced at period [r,1]. *)\n(* Need the assumption of no partition?? *)\nLemma prop_a : forall g0 g1 trace uid r v b,\n  path gtransition g0 (g1 :: trace) ->\n  partition_free g0 (g0 :: g1 :: trace) ->\n  leader_in_path_at 0 (g0 :: g1 :: trace) uid r 1 v b ->\n  user_honest_at 0 (g0 :: g1 :: trace) uid ->\n  certified_in_period trace r 1 v.\nProof.\nintros g0 g1 trace sender r v b tr_H pfree_tr_H leader_H honest_H.\ndestruct leader_H as [proposer_H crommitte_H].\ndestruct proposer_H as [poleader_H [vb_H proposed_H]].\ndestruct proposed_H as [g' prop_sent_H].\ndestruct prop_sent_H as [g'' [prop_step_H prop_sent_H]]. destruct prop_step_H. subst.\n  (* Need to identify: - the step and state at which the message is received\n                      - the user who is receiving the message *)\ndestruct prop_sent_H as [propsent_H | repropsent_H].\n  destruct propsent_H as [propsent_H blocksent_H].\n  pose proof (@sent_msg_timely_received sender (mkMsg Proposal (val v) r 1 sender) g' g'' trace). simpl in * |- *.\nAdmitted.\n\n\n(** If some period [r,p] for [p >= 2] is reached with unique starting value bot and the\nleader is honest, then the leader’s proposal is certified. *)\n(* TODO: all users need starting value bot or just leader? *)\nLemma prop_c : forall ix path uid r p v b,\n  p >= 2 ->\n  all (fun u => user_stv_val_at ix path u p None) (domf (users_at ix path)) ->\n  leader_in_path_at ix path uid r 1 v b ->\n  user_honest_at ix path uid ->\n  certified_in_period path r p v.\nProof.\nAdmitted.\n\n(** Softvote quorum of all honest users implies certvote quorum. *)\nLemma honest_softvote_quorum_implies_certvote : forall (softvote_quorum : {fset UserId}) ix path r p v,\n  (forall voter : UserId, voter \\in softvote_quorum ->\n                                    voter \\in domf (honest_users (users_at ix path))) ->\n  softvote_quorum `<=` committee r p 3 ->\n  tau_c <= #|softvote_quorum| ->\n  (forall voter : UserId, voter \\in softvote_quorum\n                                    -> softvoted_in_path_at ix path voter r p v) ->\n  (forall voter : UserId, voter \\in softvote_quorum\n                                    -> certvoted_in_path path voter r p v).\nProof.\nAbort.\n\n(** Honest user softvotes starting value. *)\nLemma stv_not_bot_softvote : forall ix path r p v uid,\n  uid \\in domf (honest_users (users_at ix path)) ->\n  user_stv_val_at ix path uid p (Some v) ->\n  softvoted_in_path_at ix path uid r p v.\nProof.\nAbort.\n\n(** If some period [r,p] with [p >= 2] is reached, and all honest users have starting\nvalue [H(B)], then a certificate for [H(B)] that period is produced by the honest users. *)\n(* TODO: need to say quorum for certificate is only *honest* users? *)\nLemma prop_e : forall ix path r p v b,\n  p >= 2 ->\n  all (fun u => user_stv_val_at ix path u p (Some v))\n      (domf (honest_users (users_at ix path))) ->\n  valid_block_and_hash b v ->\n  certified_in_period path r p v.\nProof.\n  intros.\n  exists (domf (honest_users (users_at ix path))).\n  (* quorum subset of committee at step 3 *)\n  assert (domf (honest_users (users_at ix path)) `<=` committee r p 3) by admit.\n  (* at least t_H honest users *)\n  assert (tau_c <= #|domf (honest_users (users_at ix path))|) by admit.\n  repeat split; try assumption.\nAdmitted.\n\n(** If any honest user is in period [r,p] with starting value bottom, then within\ntime [(2*lambda+Lambda)], every honest user in period [r,p] will either certify a\nvalue (i.e., will get a certificate) or move to the next period. *)\nLemma prop_f : forall r p g0 g1 g2 path_seq uid,\n    path gtransition g0 path_seq ->\n    g2 = last g0 path_seq ->\n    g1 = last g0 (drop 1 path_seq) ->\n    user_honest uid g1 ->\n    user_stv_val uid g1 p None ->\n    (exists v, certvoted_in_path path_seq uid r p v \\/\n      period_advance_at 1 path_seq uid r p g1 g2).\nProof.\nAdmitted.\n", "meta": {"author": "runtimeverification", "repo": "algorand-verification", "sha": "389c5b44d3101508c9fcb023c6ea47874c4e89af", "save_path": "github-repos/coq/runtimeverification-algorand-verification", "path": "github-repos/coq/runtimeverification-algorand-verification/algorand-verification-389c5b44d3101508c9fcb023c6ea47874c4e89af/theories/liveness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.2999522970559613}}
{"text": "(*\nFrom Coq Require Import Strings.String.\nFrom Coq Require Import Strings.Ascii.\nFrom Coq Require Import Lists.List. Import ListNotations.\n\n*)\nFrom Coq Require Import Strings.String.\n\nInductive SP : Type :=\n  | ALL \n  | NONE.\n \nInductive ASP : Type :=\n  | CPY\n  | SIG\n  | HSH\n  | ASPC (ASP_ID : nat) (Arg : string).\n\n\nInductive T : Type :=\n  | ASPT (a : ASP)\n  | AT (Pl : nat) (t : T)\n  | LN (t1 t2 : T)\n  | BRS (s1 s2 : SP) (t1 t2 : T)\n  | BRP (s1 s2 : SP) (t1 t2 : T).\n\n\nDelimit Scope string_scope with string.\nLocal Open Scope string_scope.\n\nCheck ASPT (CPY).\nCheck AT (123) (AT 45 (ASPT CPY)).\nCheck BRP ALL ALL (ASPT CPY) (ASPT HSH).\nCheck AT 2 (AT 3 (BRS NONE ALL (ASPT (ASPC 11 bank)) (ASPT SIG))).\nCheck AT 1 (AT 2 (BRS NONE ALL (ASPT HSH) (LN (ASPT SIG) (AT 3 (ASPT CPY))))).", "meta": {"author": "ku-sldg", "repo": "copland-parser", "sha": "37fc6b72939b887086edf0a7908b9f604c32a4bf", "save_path": "github-repos/coq/ku-sldg-copland-parser", "path": "github-repos/coq/ku-sldg-copland-parser/copland-parser-37fc6b72939b887086edf0a7908b9f604c32a4bf/CopLang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.2997314506075493}}
{"text": "From BF Require Import Base Byte RelVM VM Token.\n\nInductive ast : Type :=\n  | ARight (a : ast)\n  | ALeft (a : ast)\n  | AInc (a : ast)\n  | ADec (a : ast)\n  | AOutput (a : ast)\n  | AInput (a : ast)\n  | ALoop (body : ast) (a : ast)\n  | AEnd.\n\nInductive execute : ast -> vm -> vm -> Prop :=\n  | E_ARight a v v'' :\n      execute a (VM.shift_right v) v'' ->\n      execute (ARight a) v v''\n  | E_ALeft a v v' v'' :\n      VM.shift_left v = Some v' ->\n      execute a v' v'' ->\n      execute (ALeft a) v v''\n  | E_AInc a v v'' :\n      execute a (VM.add_cell #01 v) v'' ->\n      execute (AInc a) v v''\n  | E_ADec a v v'' :\n      execute a (VM.add_cell #ff v) v'' ->\n      execute (ADec a) (v) v''\n  | E_AOutput a v v'' :\n      execute a (VM.output v) v'' ->\n      execute (AOutput a) v v''\n  | E_AInput a v v' v'' :\n      VM.input v = Some v' ->\n      execute a v' v'' ->\n      execute (AInput a) v v''\n  | E_ALoop body a v v' v'' :\n      v.(cell) =? #00 = false ->\n      execute body v v' ->\n      execute (ALoop body a) v' v'' ->\n      execute (ALoop body a) v v''\n  | E_ALoop_0 body a v v' :\n      v.(cell) =? #00 = true ->\n      execute a v v' ->\n      execute (ALoop body a) v v'\n  | E_AEnd v v' :\n      VM.eq v v' = true ->\n      execute AEnd v v'.\n\nInductive execute_rel : ast -> RelVM.vm -> RelVM.vm -> Prop :=\n  | ER_ARight a v v' v'' :\n      RelVM.move 1 v = Some v' ->\n      execute_rel a v' v'' ->\n      execute_rel (ARight a) v v''\n  | ER_ALeft a v v' v'' :\n      RelVM.move (-1) v = Some v' ->\n      execute_rel a v' v'' ->\n      execute_rel (ALeft a) v v''\n  | ER_AInc a v v' v'' :\n      RelVM.add_cell #01 0 v = Some v' ->\n      execute_rel a v' v'' ->\n      execute_rel (AInc a) v v''\n  | ER_ADec a v v' v'' :\n      RelVM.add_cell #ff 0 v = Some v' ->\n      execute_rel a v' v'' ->\n      execute_rel (ADec a) (v) v''\n  | ER_AOutput a v v' v'' :\n      RelVM.output 0 v = Some v' ->\n      execute_rel a v' v'' ->\n      execute_rel (AOutput a) v v''\n  | ER_AInput a v v' v'' :\n      RelVM.input 0 v = Some v' ->\n      execute_rel a v' v'' ->\n      execute_rel (AInput a) v v''\n  | ER_ALoop body a v v' v'' :\n      RelVM.cell v =? #00 = false ->\n      execute_rel body v v' ->\n      execute_rel (ALoop body a) v' v'' ->\n      execute_rel (ALoop body a) v v''\n  | ER_ALoop_0 body a v v' :\n      RelVM.cell v =? #00 = true ->\n      execute_rel a v v' ->\n      execute_rel (ALoop body a) v v'\n  | ER_AEnd v v' :\n      RelVM.eq v v' = true ->\n      execute_rel AEnd v v'.\n\nDefinition equiv (a1 a2 : ast) : Prop := forall v v',\n  execute a1 v v' <-> execute a2 v v'.\n\nDefinition transform_sound (trans : ast -> ast) : Prop := forall a,\n  equiv a (trans a).\n\nFixpoint parse' (ts : list token) : ast * list ast :=\n  match ts with\n  | t :: ts' =>\n      let (body, next) := parse' ts' in\n      match t with\n      | TRight => (ARight body, next)\n      | TLeft => (ALeft body, next)\n      | TInc => (AInc body, next)\n      | TDec => (ADec body, next)\n      | TOutput => (AOutput body, next)\n      | TInput => (AInput body, next)\n      | THead => match next with\n                 | next :: next' => (ALoop body next, next')\n                 | [] => (AEnd, [AEnd]) (* unclosed loop *)\n                 end\n      | TTail => (AEnd, body :: next)\n      end\n  | [] => (AEnd, [])\n  end.\n\nDefinition parse (ts : list token) : option ast :=\n  match parse' ts with\n  | (prog, []) => Some prog\n  | _ => None\n  end.\n\nFixpoint flatten (a : ast) : list token :=\n  match a with\n  | ARight a' => TRight :: flatten a'\n  | ALeft a' => TLeft :: flatten a'\n  | AInc a' => TInc :: flatten a'\n  | ADec a' => TDec :: flatten a'\n  | AOutput a' => TOutput :: flatten a'\n  | AInput a' => TInput :: flatten a'\n  | ALoop body a' => THead :: flatten body ++ TTail :: flatten a'\n  | AEnd => []\n  end.\n\nTheorem flatten_parse : forall ts a,\n  parse ts = Some a ->\n  flatten a = ts.\nProof. Admitted.\n\nTheorem parse_flatten : forall a,\n  parse (flatten a) = Some a.\nProof. Admitted.\n\nDefinition cons_right (n : positive) (a : ast) : ast :=\n  repeat_apply ARight (Pos.to_nat n) a.\n\nDefinition cons_left (n : positive) (a : ast) : ast :=\n  repeat_apply ALeft (Pos.to_nat n) a.\n\nDefinition cons_add (n : byte) (a : ast) : ast :=\n  match Integers.Byte.signed n with\n  | Z0 => a\n  | Zpos p => repeat_apply AInc (Pos.to_nat p) a\n  | Zneg p => repeat_apply ADec (Pos.to_nat p) a\n  end.\n\nExample test_execute : forall a,\n  parse (lex \",>+++[-<++>]<-.\") = Some a ->\n  execute a (VM.make [#02]) (VM [] #07 [] [#07] [] VM.norm_nil).\nProof.\n  intros. inversion H; subst; clear H.\n  repeat (apply E_ARight\n       || (eapply E_ALeft; [reflexivity |])\n       || apply E_AInc\n       || apply E_ADec\n       || apply E_AOutput\n       || (eapply E_AInput; [reflexivity |])\n       || (eapply E_ALoop; [reflexivity | |])\n       || (eapply E_ALoop_0; [reflexivity |])\n       || (apply E_AEnd; apply VM.eq_refl)).\n  apply E_AEnd. reflexivity.\nQed.\n", "meta": {"author": "thaliaarchi", "repo": "bfcoq", "sha": "3341805a20a990e8650437b7a4fe9937858950aa", "save_path": "github-repos/coq/thaliaarchi-bfcoq", "path": "github-repos/coq/thaliaarchi-bfcoq/bfcoq-3341805a20a990e8650437b7a4fe9937858950aa/AST.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.2997314506075493}}
{"text": "Require Export SystemFR.ErasedArrow.\nRequire Export SystemFR.ErasedSingleton.\nRequire Export SystemFR.ReducibilitySubtype.\n\nOpaque reducible_values.\n\nInductive widen: tree -> tree -> Prop :=\n| WidenSingleton:\n    forall ty1 ty2 f,\n      is_erased_term f ->\n      is_erased_type ty2 ->\n      wf f 0 ->\n      widen\n        (T_singleton (T_arrow ty1 ty2) f)\n        (T_arrow ty1 (T_singleton ty2 (app f (lvar 0 term_var))))\n| WidenSingleton2:\n    forall ty f ty',\n      widen ty ty' ->\n      widen (T_singleton ty f) ty'\n| WidenRefl:\n    forall ty, widen ty ty\n.\n\nLemma reducible_equiv:\n  forall ρ t1 t2,\n    [ t1 ≡ t2 ] ->\n    [ ρ ⊨ uu : T_equiv t1 t2 ].\nProof.\n  intros; unfold reduces_to; repeat step || exists uu || simp_red; t_closer.\nQed.\n\nLemma widen_singleton_arrow:\n  forall Θ Γ ty1 ty2 f,\n    is_erased_term f ->\n    is_erased_type ty2 ->\n    wf f 0 ->\n    [Θ; Γ ⊨ T_singleton (T_arrow ty1 ty2) f <:\n            T_arrow ty1 (T_singleton ty2 (app f (lvar 0 term_var))) ].\nProof.\n  unfold open_subtype;\n    repeat step || simp_red || open_none || apply reducible_type_refine with uu ||\n           (rewrite shift_nothing2 in * by eauto with wf) || list_utils ||\n           apply reducible_equiv || t_instantiate_reducible ||\n           apply equivalent_app ||\n           rewrite reducibility_rewrite in *;\n    eauto with wf fv erased;\n    eauto using reducible_values_closed;\n    try solve [ apply equivalent_refl; eauto with wf fv erased ].\nQed.\n\nLemma singleton_subtype:\n  forall Θ Γ ty f,\n    [ Θ; Γ ⊨ T_singleton ty f <: ty ].\nProof.\n  unfold open_subtype; repeat step || simp_red.\nQed.\n\nLemma widen_singleton:\n  forall Θ Γ ty ty' f,\n    [Θ; Γ ⊨ ty <: ty'] ->\n    [Θ; Γ ⊨ T_singleton ty f <: ty'].\nProof.\n  eauto using open_subtype_trans, singleton_subtype.\nQed.\n\nLemma widen_open_subtype:\n  forall Θ Γ ty1 ty2,\n    widen ty1 ty2 ->\n    [ Θ; Γ ⊨ ty1 <: ty2 ].\nProof.\n  induction 1; repeat step;\n    eauto using widen_singleton_arrow;\n    eauto using widen_singleton.\nQed.\n\nLemma open_tapp_helper:\n  forall Θ Γ t1 t2 S T U,\n    is_erased_type T ->\n    wf T 1 ->\n    subset (fv T) (support Γ) ->\n    [ Θ; Γ ⊨ t1 : U ] ->\n    widen U (T_arrow S T) ->\n    [ Θ; Γ ⊨ t2 : S ] ->\n    [ Θ; Γ ⊨ app t1 t2 : open 0 T t2 ].\nProof.\n  intros; eapply open_reducible_app; eauto.\n  eauto using widen_open_subtype, open_subtype_reducible.\nQed.\n\nLemma open_tapp:\n  forall Γ t1 t2 S T U,\n    is_erased_type T ->\n    wf T 1 ->\n    subset (fv T) (support Γ) ->\n    [ Γ ⊫ t1 : U ] ->\n    widen U (T_arrow S T) ->\n    [ Γ ⊫ t2 : S ] ->\n    [ Γ ⊫ app t1 t2 : open 0 T t2 ].\nProof.\n  eauto using open_tapp_helper.\nQed.\n\nLemma open_tlet_helper:\n  forall Θ Γ t1 t2 T1 T2 x,\n    is_erased_type T2 ->\n    is_erased_term t2 ->\n    wf T1 0 ->\n    wf T2 1 ->\n    wf t2 1 ->\n    subset (fv T1) (support Γ) ->\n    subset (fv T2) (support Γ) ->\n    subset (fv t2) (support Γ) ->\n    subset (pfv_context Γ term_var) (support Γ) ->\n    ~ x ∈ support Γ ->\n    [ Θ; Γ ⊨ t1 : T1 ] ->\n    [ Θ; (x, T1) :: Γ ⊨ open 0 t2 (fvar x term_var) : open 0 T2 (fvar x term_var) ] ->\n    [ Θ; Γ ⊨ let' t1 t2 : open 0 T2 t1 ].\nProof.\n  unfold let'; intros.\n  apply open_tapp_helper with T1 (T_arrow T1 T2); steps.\n  apply open_reducible_lambda with x; steps; eauto with wf erased fv.\nQed.\n\nLemma open_tlet:\n  forall Γ t1 t2 T1 T2 x,\n    is_erased_type T2 ->\n    is_erased_term t1 ->\n    is_erased_term t2 ->\n    wf T1 0 ->\n    wf T2 1 ->\n    wf t1 0 ->\n    wf t2 1 ->\n    subset (fv T1) (support Γ) ->\n    subset (fv T2) (support Γ) ->\n    subset (fv t1) (support Γ) ->\n    subset (fv t2) (support Γ) ->\n    subset (pfv_context Γ term_var) (support Γ) ->\n    ~ x ∈ support Γ ->\n    [ Γ ⊫ t1 : T1 ] ->\n    [ (x, T1) :: Γ ⊫ open 0 t2 (fvar x term_var) : open 0 T2 (fvar x term_var) ] ->\n    [ Γ ⊫ let' t1 t2 : T_singleton (open 0 T2 t1) (let' t1 t2) ].\nProof.\n  intros.\n  apply open_reducible_singleton; repeat step || sets || simp_red;\n    eauto using open_tlet_helper.\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/InferApp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2997249254562815}}
{"text": "\n(* ************************************************************************** *)\n(*                                                                            *)\n(* Verified Flash Translation Layer                                           *)\n(*                                                                            *)\n(*                                                                            *)\n(*   Author: Yu Guo <aciclo@gmail.com>                                        *)\n(*                                        Computer Science Department, USTC   *)\n(*                                                                            *)\n(*           Hui Zhang <sa512073@mail.ustc.edu.cn>                            *)\n(*                                     School of Software Engineering, USTC   *)\n(*                                                                            *)\n(* ************************************************************************** *)\n\nRequire Export bnat.\nRequire Import LibEx.\nRequire Import ListEx.\nRequire Import Monad.\nRequire Import Data.\nRequire Import Params.\n\n(* NAND hardware interface *)\n\n(* Definition oob := list int. *)\n\nDefinition page_off := nat.\n\nDefinition block_no := nat.\n\nDefinition page_off_of_nat (n: nat) : page_off := n.\n\n(* Definition page_no := prod block_no page_off. *)\n\nDefinition page_no := nat.\n\nDefinition page_oob_nat := option (prod nat nat).\n\nInductive page_status : Set :=\n  | ps_free\n  | ps_programmed.\n\nInductive block_status : Set :=\n  | bs_free\n  | bs_programmed.\n\nRecord page : Set := \n  mkpage {\n      page_data : data;\n      page_oob :  page_oob_nat;\n      page_state : page_status\n      (* data_size: length (page_data) = PAGE_DATA_SIZE; *)\n      (* oob_size: length (page_data) = PAGE_SPAREAREA_SIZE *)\n    }.\n\nRecord block : Set := \n  mkblock {\n      block_pages : list page;\n      next_page : page_off;\n      block_erase_count: nat;\n      block_state : block_status\n      (* pages_size: length block_pages = PAGES_PER_BLOCK *)\n    }.\n\nRecord chip : Set := \n  mkchip {\n      chip_blocks: list block\n      (* blocks_size : length chip_blocks = BLOCKS *)\n    }. \n\n(********* Initialization of the Nand Chip ****************)\n\n(*Just init single page's content,including the page content and oob*)\nDefinition init_page_data : data :=\n  metabyte (list_repeat_list PAGE_DATA_SIZE c_ff).\n\n(* Definition init_page_oob : data := *)\n(*   metabyte (list_repeat_list PAGE_SPARE_AREA_SIZE c_ff). *)\n\n(*The Initialization oob is 0 *)\nDefinition init_page : page :=\n  mkpage init_page_data None  ps_free.\n\nDefinition init_block : block :=\n  mkblock (list_repeat_list PAGES_PER_BLOCK init_page) 0 0 bs_free.\n\nDefinition erased_block (ec: nat): block :=\n  mkblock (list_repeat_list PAGES_PER_BLOCK init_page) 0 (S ec) bs_free.\n\nDefinition bvalid_block_no (pbn: block_no) : bool := \n  (blt_nat pbn BLOCKS).\n\nDefinition bvalid_page_no (ppn:page_no) : bool :=\n  (blt_nat ppn (BLOCKS * PAGES_PER_BLOCK)).\n\nDefinition bvalid_page_off (off: page_off) : bool := \n  (blt_nat off PAGES_PER_BLOCK).\n\n(********* Nand chip Operations ***************)\nDefinition nand_init : chip :=\n  mkchip (list_repeat_list BLOCKS init_block). \n\n(* written by zhanghui, generate the content of 'oob' according to the\ndata stored in this page. *)\n(* TEMP: now just return a list of null *)\n(* Definition make_oob (d : data) : data := *)\n(*   list_repeat_list PAGE_SPARE_AREA_SIZE c_null. *)\n\nDefinition page_set__oob (p:page)(oob:page_oob_nat) :=\n  ret (mkpage (page_data p) oob (page_state p) ).\n\nDefinition page_get_oob (p:page) :page_oob_nat :=\n  page_oob p.\n\nDefinition chip_get_block (c: chip) (pbn: block_no): option block :=\n  list_get (chip_blocks c) pbn.\n\nDefinition chip_set_block (c: chip) (pbn: block_no) (b: block) : option chip :=\n  test bvalid_block_no pbn;\n  do nbl <-- list_set (chip_blocks c) pbn b;\n  ret (mkchip nbl).\n\nDefinition block_get_page (b: block) (off: page_off) : option page :=\n  test (bvalid_page_off off);\n  do p <-- (list_get (block_pages b) off);\n  ret p.\n \nDefinition block_set_page (b: block) (off: page_off) (p: page) : option block :=\n  test bvalid_page_off off;\n  do npl <-- list_set (block_pages b) off p;\n  ret (mkblock npl (next_page b) (block_erase_count b) bs_programmed).\n\nDefinition block_set_next_page (b: block) (off: page_off) : option block :=\n  ret (mkblock (block_pages b) (off) (block_erase_count b) (block_state b)).\n\nDefinition chip_get_page (c: chip) (bln: block_no) (poff: page_off) : option page :=\n  match chip_get_block c bln with\n    | None => None\n    | Some b =>\n      block_get_page b poff\n  end.\n\nDefinition page_get_data (p: page) : option data :=\n  match page_state p with\n    | ps_free => None (* This is an empty page, no data. *)\n    | ps_programmed => Some (page_data p)\n  end.\n\nDefinition check_page_state_is_free (ps : page_status) : bool :=\n  match ps with\n    | ps_free => true\n    | _ => false\n  end.\n\n(*It donesn't need a state,if it is invaild,it will be set to trans_empty.*)\nDefinition data_get_record_list(pagedata:data)(lpn:page_no) : option meta_trans_record_list :=\n  match pagedata with\n      | metabyte _  => None\n      | metarecord l => Some l\n  end.\n\nFixpoint recordlist_get_record(l:meta_trans_record_list)(lpn:page_no) :option trans_record :=\n  match l with\n      | nil => None\n      | cons a l' =>match a with \n                        | trans_empty => recordlist_get_record l' lpn\n                        | trans_data lpn' ppn' offset => if beq_nat lpn lpn' then Some a else recordlist_get_record l' lpn \n                    end\nend.\n\n(*It's can't exist,because the page must write in once*)\n\n(* Fixpoint recordlist_set_record(l:meta_trans_record_list)(lpn:page_no) :option meta_trans_record_list := *)\n(*   match l with *)\n(*       | nil => None *)\n(*       | cons a l' =>match a with  *)\n(*                         | trans_empty => recordlist_get_record l' lpn *)\n(*                         | trans_data lpn' ppn'=> if beq_nat lpn lpn' then Some a else recordlist_get_record l' lpn  *)\n(*                     end *)\n(* end. *)\n \n(********* Nand chip Operations ***************)\nDefinition nand_read_page (c: chip) (pbn: block_no) (poff: page_off) : option (prod data page_oob_nat) :=\n  test (bvalid_block_no pbn);\n  do b <-- chip_get_block c pbn;\n  test (bvalid_page_off poff);\n  do p <-- block_get_page b poff;\n  ret (page_data p, page_oob p).\n\nDefinition nand_write_page (c: chip) (pbn: block_no) (off: page_off) (d: data) (oob: page_oob_nat): option chip :=\n  test (bvalid_block_no pbn);\n  do b <-- chip_get_block c pbn;\n  test (bvalid_page_off off);\n  test (ble_nat (next_page b) off);\n  do p <-- block_get_page b off;\n  test (check_page_state_is_free (page_state p));\n  do b' <-- block_set_page b off (mkpage d oob ps_programmed);\n  do b'' <-- block_set_next_page b' (S off);\n  do c' <-- chip_set_block c pbn b'';\n  ret c'.\n                 \nDefinition nand_erase_block (c: chip) (pbn: block_no) : option chip :=\n  test (bvalid_block_no pbn);\n  do b <-- chip_get_block c pbn;\n  let b' := erased_block (block_erase_count b) in \n  do c' <-- chip_set_block c pbn b';\n  ret c'.\n", "meta": {"author": "zbh24", "repo": "DFTL", "sha": "685ac48f010e0fc2621e04defbeb57caee34186a", "save_path": "github-repos/coq/zbh24-DFTL", "path": "github-repos/coq/zbh24-DFTL/DFTL-685ac48f010e0fc2621e04defbeb57caee34186a/Nand.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.2997249186457951}}
{"text": "Require Import GHC.Base.\nRequire Import Fix.\n\nRequire Import Adverb.Composable.Purely.\nRequire Import Adverb.Composable.Streamingly.\nRequire Import Adverb.Composable.Statically.\nRequire Import Adverb.Composable.Dynamically.\n\nRequire Import ProofAlgebra.ProofAlgebra.\nRequire Import ProofAlgebra.Composable.\nRequire Import UP.Fix.\n\nFrom Coq Require Import\n     FunctionalExtensionality\n.\n\nSection UPs.\n\n  Variable F : (Set -> Set) -> Set -> Set.\n  Context `{Functor1 F} `{PurelyAdv -≪ F}.\n  Context `{@WFFunctor1 PurelyAdv F Functor1__PurelyAdv _ _}.\n\n  Lemma pure_UP : forall (A : Set) (a : A),\n      UP1 F (@inF1 _ _ _ (inj1 (Pure a))).\n  Proof.\n    intros. constructor. intros.\n    rewrite H2. unfold inF1. unfold foldFix1.\n    rewrite !wf_functor. reflexivity.\n  Qed.\n\n  Global Instance ProofAlg_PurelyAdv_UP1 : ProofAlg1 PurelyAdv (@UP1 F _) :=\n    Pure_ProofAlgebra _ _ pure_UP.\n\n  Definition pure' {A : Set} (a : A) : {e : Fix1 F A | UP1 F e} :=\n    inF'1 (HP:=ProofAlg_PurelyAdv_UP1) (Pure a).\n\n  Section Functor.\n\n    Context `{StreaminglyAdv -≪ F}.\n    Context `{@WFFunctor1 StreaminglyAdv F Functor1__StreaminglyAdv _ _}.\n\n    Lemma fmap_UP : forall (A B : Set) (g : A -> B) f,\n        UP1 F f -> UP1 F (fmap g f).\n    Proof.\n      intros. constructor. intros.\n      unfold fmap. cbn. unfold fmap_ff.\n      specialize (H5 _ (inj1 (FMap g f))) as Hmap.\n      rewrite H5. unfold inF1. rewrite !wf_functor. cbn.\n      destruct H4. erewrite -> UP1_implies_fold. 2: { intros; apply H5. }\n      reflexivity.\n    Qed.\n\n    Global Instance ProofAlg_StreaminglyAdv_UP1 : ProofAlg1 StreaminglyAdv (@UP1 F _) :=\n      FunctorT_ProofAlgebra _ _ fmap_UP.\n\n    Definition fmap' {A B : Set} (f : A -> B) (a : {e : Fix1 F A | UP1 F e})\n      : {e : Fix1 F B | UP1 F e} :=\n      inF'1 (HP:=ProofAlg_StreaminglyAdv_UP1) (FMap f a).\n\n    Global Instance Functor_StreaminglyAdv' :\n      Functor (fun A => {e : Fix1 F A | UP1 F e }) :=\n      fun _ k => k {| fmap__      := fun {a} {b} => fmap' ;\n                   op_zlzd____ := fun {a} {b} => fmap' ∘ const |}.\n  End Functor.\n\n  Section Applicative.\n\n    Context `{StaticallyAdv -≪ F}.\n    Context `{@WFFunctor1 StaticallyAdv F Functor1__StaticallyAdv _ _}.\n\n    Lemma liftA2_UP : forall (A B C : Set) (f : A -> B -> C) a b,\n        UP1 F a -> UP1 F b -> UP1 F (liftA2 f a b).\n    Proof.\n      intros. constructor. intros.\n      unfold liftA2. cbn. unfold liftA2_fa.\n      rewrite H6. unfold inF1. rewrite !wf_functor. cbn.\n      destruct H4. erewrite -> UP1_implies_fold.\n      2: { intros. apply H6. }\n      destruct H5. erewrite -> UP1_implies_fold0.\n      2: { intros. apply H6. }\n      reflexivity.\n    Qed.\n\n    Global Instance ProofAlg_StaticallyAdv_UP1 : ProofAlg1 StaticallyAdv (@UP1 F _) :=\n      ApT_ProofAlgebra _ _ liftA2_UP.\n\n    Definition liftA2' {A B C : Set}\n               (f : A -> B -> C)\n               (a : {e : Fix1 F A | UP1 F e})\n               (b : {e : Fix1 F B | UP1 F e})\n      : {e : Fix1 F C | UP1 F e} :=\n      inF'1 (HP:=ProofAlg_StaticallyAdv_UP1) (LiftA2 f a b).\n\n    Definition fmap'A {A B : Set} (f : A -> B)\n               (a : {e : Fix1 F A | UP1 F e}) : {e : Fix1 F B | UP1 F e} :=\n      liftA2' id (pure' f) a.\n\n    Global Instance Functor_StaticallyAdv' :\n      Functor (fun A => {e : Fix1 F A | UP1 F e }) :=\n      fun _ k => k {| fmap__      := fun {a} {b} => fmap'A ;\n                   op_zlzd____ := fun {a} {b} => fmap'A ∘ const |}.\n\n    Global Instance Applicative_StaticallyAdv' :\n      Applicative (fun A => {e : Fix1 F A | UP1 F e }) :=\n      fun _ k => k {| liftA2__ := fun {a b c} => liftA2' ;\n               op_zlztzg____ := fun {a b} => liftA2' id ;\n               op_ztzg____ := fun {a b} fa => liftA2' id (id <$ fa) ;\n               pure__ := fun {a} => pure' |}.\n\n  End Applicative.\n\n  Section Monad.\n\n    Context `{DynamicallyAdv -≪ F}.\n    Context `{@WFFunctor1 DynamicallyAdv F Functor1__DynamicallyAdv _ _}.\n\n    Lemma ret_UP : forall (A : Set) (a : A),\n        UP1 F (return_ a).\n    Proof.\n      exact pure_UP.\n    Qed.\n\n    Lemma bind_UP : forall (A B : Set) (g : A -> Fix1 F B) m,\n        UP1 F m -> (forall a, UP1 F (g a)) -> UP1 F (m >>= g).\n    Proof.\n      intros. constructor. intros.\n      unfold \">>=\". cbn. unfold bind_fm.\n      rewrite H6. unfold inF1. rewrite !wf_functor. cbn.\n      destruct H4. erewrite -> UP1_implies_fold.\n      2: { intros. apply H6. }\n      replace (fun x : A => h B (g x))\n        with (fun x : A => foldFix1 alg (g x)).\n      2: { apply functional_extensionality.\n           intro a. specialize (H5 a).\n           destruct H5. erewrite -> UP1_implies_fold0.\n           reflexivity. intros. apply H6. }\n      reflexivity.\n    Qed.\n\n    Global Instance ProofAlg_DynamicallyAdv_UP1 : ProofAlg1 DynamicallyAdv (@UP1 F _) :=\n      MonadT_ProofAlgebra _ _ bind_UP.\n\n\n    Definition return_' {A : Set} (a : A) : {e : Fix1 F A | UP1 F e} :=\n      pure' a.\n\n    Definition bind' {A B : Set}\n               (m : {e : Fix1 F A | UP1 F e})\n               (k : A -> {e : Fix1 F B | UP1 F e}) : {e : Fix1 F B | UP1 F e} :=\n      inF'1 (HP:=ProofAlg_DynamicallyAdv_UP1) (Bind m k).\n\n    Definition fmap'M {A B : Set} (f : A -> B)\n               (a : {e : Fix1 F A | UP1 F e}) : {e : Fix1 F B | UP1 F e} :=\n      bind' a (return_' ∘ f).\n\n    Definition ap'M {A B : Set}\n               (f : {e : Fix1 F (A -> B) | UP1 F e})\n               (a : {e : Fix1 F A | UP1 F e}) : {e : Fix1 F B | UP1 F e} :=\n      bind' f (fun f => bind' a (fun a => return_' (f a))).\n\n    Global Instance Functor_DynamicallyAdv' :\n      Functor (fun A => {e : Fix1 F A | UP1 F e }) :=\n      fun _ k => k {| fmap__      := fun {a} {b} => fmap'M ;\n                   op_zlzd____ := fun {a} {b} => fmap'M ∘ const |}.\n\n    Global Instance Applicative_DynamicallyAdv' :\n      Applicative (fun A => {e : Fix1 F A | UP1 F e }) :=\n      fun _ k => k {| liftA2__ := fun {a b c} g fa fb => ap'M (fmap'M g fa) fb ;\n               op_zlztzg____ := fun {a b} => ap'M ;\n               op_ztzg____ := fun {a b} fa => ap'M (id <$ fa) ;\n               pure__ := fun {a} => return_' |}.\n\n    Global Instance Monad_FMonaT' :\n      Monad (fun A => {e : Fix1 F A | UP1 F e }) :=\n      fun _ k => k {| op_zgzg____ := fun {a} {b} m k => bind' m (fun _ => k) ;\n                   op_zgzgze____ := fun {a} {b} => bind' ;\n                   return___ := fun {a} => return_' |}.\n  End Monad.\n\nEnd UPs.\n", "meta": {"author": "lastland", "repo": "ProgramAdverbs", "sha": "1f8086d379d1fc0eb896539adae66cd9f7d8ec04", "save_path": "github-repos/coq/lastland-ProgramAdverbs", "path": "github-repos/coq/lastland-ProgramAdverbs/ProgramAdverbs-1f8086d379d1fc0eb896539adae66cd9f7d8ec04/UP/Composable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.29972491864579504}}
{"text": "From stdpp Require Import namespaces finite.\nFrom iris.base_logic Require Import invariants na_invariants.\nFrom self.prob_lang Require Import notation proofmode primitive_laws spec_rules spec_tactics.\nFrom self.logrel Require Import model rel_rules rel_tactics.\nFrom iris.algebra Require Import auth gmap excl frac agree.\nFrom self.prelude Require Import base.\nFrom self.examples Require Import hash.\n\nSet Default Proof Using \"Type*\".\n\n(* A wrapper around the tape hash that gives an interface where the hashing function now takes as input\n   a key k and a value v to be hashed. Different keys yield different hashes, and the library\n   splits up ownership along keys.\n\n   This is implemented by actually just having a single hash function,\n   and on input k and v, we convert the pair (k, v) to a single integer that is then\n   hashed.\n\n *)\n\n\nSection keyed_hash.\n\n  (* we assume the key space / value space are integers in the range\n  {0, ..., 2^n_k - 1} and {0, ..., 2^n_v} for some natural numbers n_k\n  and n_v. *)\n\n  Context (MAX_KEYS_POW : nat).\n  Context (MAX_VALS_POW : nat).\n\n  Definition MAX_KEYS : nat := (Nat.pow 2 MAX_KEYS_POW) - 1.\n  Definition MAX_VALS : nat := (Nat.pow 2 MAX_VALS_POW) - 1.\n  Definition MAX_KEYS_Z : Z := (Z.pow 2 MAX_KEYS_POW) - 1.\n  Definition MAX_VALS_Z : Z := (Z.pow 2 MAX_VALS_POW) - 1.\n\n  Definition MAX_HASH_DOM : nat := ((Nat.pow 2 (MAX_KEYS_POW + MAX_VALS_POW)) - 1).\n\n  Definition enc : val :=\n    λ: \"k\" \"v\", (\"k\" ≪ #MAX_VALS_POW) + \"v\".\n\n  Definition enc_gallina (k : nat) (v: nat) : nat :=\n    (Nat.shiftl k MAX_VALS_POW) + v.\n\n  Definition val_of_enc_gallina (x: nat) : nat :=\n    x `mod` (Nat.pow 2 MAX_VALS_POW).\n\n  Definition key_of_enc_gallina (x: nat) : nat :=\n    (Nat.shiftr (x - val_of_enc_gallina x) MAX_VALS_POW).\n\n  Lemma pow2_nonzero: ∀ x, 0 < 2 ^ x.\n  Proof.\n    intros x. induction x => /=; try lia.\n  Qed.\n\n  Definition not_in_key x k : Prop := (¬ ∃ v, enc_gallina k v = x).\n\n  Lemma val_of_enc_gallina_spec1 k v :\n    v <= MAX_VALS →\n    val_of_enc_gallina (enc_gallina k v) = v.\n  Proof.\n    rewrite /val_of_enc_gallina /enc_gallina/MAX_VALS.\n    rewrite ?Nat.shiftr_div_pow2 ?Nat.shiftl_mul_pow2.\n    intros Hv.\n    specialize (pow2_nonzero MAX_VALS_POW) => ?.\n    rewrite Nat.add_comm Nat.mod_add; last lia.\n    rewrite Nat.mod_small; lia.\n  Qed.\n\n  Lemma val_of_enc_gallina_spec2 (x : nat) :\n    val_of_enc_gallina x <= MAX_VALS.\n  Proof.\n    specialize (pow2_nonzero MAX_VALS_POW) => ?.\n    cut (x `mod` (Nat.pow 2 MAX_VALS_POW) < Nat.pow 2 MAX_VALS_POW).\n    { rewrite /val_of_enc_gallina/MAX_VALS. lia. }\n    apply Nat.mod_upper_bound. lia.\n  Qed.\n\n  Lemma key_of_enc_gallina_spec1 (x : nat) k v :\n    v <= MAX_VALS →\n    key_of_enc_gallina (enc_gallina k v) = k.\n  Proof.\n    intros Hle.\n    rewrite /key_of_enc_gallina val_of_enc_gallina_spec1 //.\n    rewrite /enc_gallina/MAX_VALS.\n    rewrite Nat.add_sub.\n    rewrite Nat.shiftr_shiftl_r //.\n    assert (MAX_VALS_POW - MAX_VALS_POW = 0) as -> by lia.\n    rewrite Nat.shiftr_0_r //.\n  Qed.\n\n  Lemma Nat_div_sub_mod x k :\n   0 < k ->\n   x `div` k = (x - x `mod` k) `div` k.\n  Proof.\n    intros Hlt.\n    rewrite Nat.mod_eq; last by lia.\n    replace (x - (x - k * x `div` k)) with (k * x `div` k); last first.\n    { remember (x `div` k) as y. cut (k * y <= x); try lia.\n      rewrite Heqy. apply Nat.mul_div_le; lia. }\n    rewrite Nat.mul_comm Nat.div_mul; lia.\n  Qed.\n\n  Lemma enc_gallina_inv x :\n    enc_gallina (key_of_enc_gallina x) (val_of_enc_gallina x) = x.\n  Proof.\n    rewrite /enc_gallina/key_of_enc_gallina/val_of_enc_gallina.\n    rewrite ?Nat.shiftr_div_pow2 ?Nat.shiftl_mul_pow2.\n    symmetry.\n    rewrite {1}(Nat.div_mod_eq x (Nat.pow 2 MAX_VALS_POW)).\n    f_equal.\n    rewrite Nat.mul_comm.\n    rewrite Nat_div_sub_mod //. apply pow2_nonzero.\n  Qed.\n\n  Lemma enc_gallina_mono1 k1 k2 v1 v2:\n    k1 < k2 -> v1 <= v2 -> enc_gallina k1 v1 < enc_gallina k2 v2.\n  Proof.\n    intros Hlt Hle.\n    rewrite /enc_gallina.\n    rewrite ?Nat.shiftr_div_pow2 ?Nat.shiftl_mul_pow2.\n    specialize (pow2_nonzero MAX_VALS_POW) => Hnz.\n    remember (2 ^ MAX_VALS_POW) as z.\n    cut (k1 * z < k2 * z); first by lia.\n    apply Mult.mult_lt_compat_r_stt; auto.\n  Qed.\n\n  Lemma enc_gallina_mono2 k1 k2 v1 v2:\n    k1 < k2 -> v1 <= MAX_VALS -> v2 <= MAX_VALS -> enc_gallina k1 v1 < enc_gallina k2 v2.\n  Proof.\n    intros Hlt Hle1 Hle2.\n    rewrite /enc_gallina.\n    specialize (pow2_nonzero MAX_VALS_POW) => Hnz.\n    rewrite ?Nat.shiftr_div_pow2 ?Nat.shiftl_mul_pow2.\n    apply (Nat.lt_le_trans _ (k2 * 2 ^ MAX_VALS_POW)); last by lia.\n    apply (Nat.lt_le_trans _ ((k1 + 1) * 2 ^ MAX_VALS_POW)); last first.\n    { apply Nat.mul_le_mono_r; lia. }\n    ring_simplify.\n    rewrite /MAX_VALS in Hle1. lia.\n  Qed.\n\n  Lemma enc_gallina_mono2_inv k1 k2 v1 v2:\n    enc_gallina k1 v1 <= enc_gallina k2 v2 ->\n    v1 <= MAX_VALS ->\n    v2 <= MAX_VALS ->\n    k1 <= k2.\n  Proof.\n    intros Henc Hle1 Hle2.\n    destruct (decide (k2 < k1)) as [Hlt|]; try lia.\n    specialize (enc_gallina_mono2 _ _ _ _ Hlt Hle2 Hle1). lia.\n  Qed.\n\n  Lemma enc_gallina_inj k1 k2 v1 v2:\n    enc_gallina k1 v1 = enc_gallina k2 v2 ->\n    v1 <= MAX_VALS ->\n    v2 <= MAX_VALS ->\n    k1 = k2 /\\ v1 = v2.\n  Proof.\n    intros Henc Hle1 Hle2.\n    assert (k1 = k2) as ->.\n    {\n      apply Nat.le_antisymm.\n      * eapply (enc_gallina_mono2_inv k1 k2 v1 v2); eauto; lia.\n      * eapply (enc_gallina_mono2_inv k2 k1 v2 v1); eauto; lia.\n    }\n    split; auto.\n    rewrite /enc_gallina in Henc. lia.\n  Qed.\n\n  Lemma enc_hits_max :\n    enc_gallina MAX_KEYS MAX_VALS = MAX_HASH_DOM.\n  Proof.\n    rewrite /enc_gallina/MAX_HASH_DOM/MAX_KEYS/MAX_VALS.\n    rewrite ?Nat.shiftr_div_pow2 ?Nat.shiftl_mul_pow2.\n    rewrite Nat.pow_add_r.\n    specialize (pow2_nonzero MAX_VALS_POW) => ?.\n    specialize (pow2_nonzero MAX_KEYS_POW) => ?.\n    assert (2 ^ MAX_KEYS_POW = (2 ^ MAX_KEYS_POW - 1) + 1) as Hsub1 by lia.\n    lia.\n  Qed.\n\n  Lemma key_of_enc_gallina_spec2 (x : nat) :\n    x <= MAX_HASH_DOM →\n    key_of_enc_gallina x <= MAX_KEYS.\n  Proof.\n    intros.\n    eapply (enc_gallina_mono2_inv _ _ (val_of_enc_gallina x) (MAX_VALS));\n      auto using val_of_enc_gallina_spec2.\n    rewrite enc_gallina_inv enc_hits_max //.\n  Qed.\n\n  Lemma enc_gallina_range k v :\n    k < S MAX_KEYS →\n    v < S MAX_VALS →\n    enc_gallina k v < S MAX_HASH_DOM.\n  Proof.\n    rewrite /enc_gallina/MAX_KEYS/MAX_VALS/MAX_HASH_DOM.\n    rewrite ?Nat.shiftl_mul_pow2.\n    assert (Hsub_le: ∀ a b, 0 < b -> a < S (b - 1) → a <= b - 1).\n    { intros. lia. }\n    assert (Hsub: ∀ x, 0 < x -> S (x - 1) = x).\n    { intros. lia. }\n    intros Hlt1 Hlt2.\n    specialize (pow2_nonzero MAX_VALS_POW) => ?.\n    specialize (pow2_nonzero MAX_KEYS_POW) => ?.\n    apply Hsub_le in Hlt1; auto.\n    apply Hsub_le in Hlt2; auto.\n    rewrite ?Hsub; try (apply pow2_nonzero).\n    rewrite Nat.pow_add_r.\n    apply (Nat.le_lt_trans _ ((2 ^ MAX_KEYS_POW - 1) * 2 ^ MAX_VALS_POW + (2 ^ MAX_VALS_POW - 1))).\n    { assert (Hcompat: ∀ a b c d, a <= b → c <= d → a + c <= b + d) by lia.\n      apply Hcompat; try lia.\n      apply Nat.mul_le_mono_r; auto.\n    }\n    assert (2 ^ MAX_KEYS_POW = (2 ^ MAX_KEYS_POW - 1) + 1) as Hsub1 by lia.\n    lia.\n  Qed.\n\n  Definition init_keyed_hash : val :=\n    λ: \"_\",\n      let: \"f\" := init_hash #MAX_HASH_DOM in\n      (λ: \"k\" \"v\", \"f\" (enc \"k\" \"v\")).\n\n  Context `{!prelogrelGS Σ}.\n\n  Lemma wp_enc_spec (k v : nat) E :\n    {{{ ⌜ k <= MAX_KEYS ∧ v ≤ MAX_VALS ⌝ }}}\n      enc #k #v @ E\n    {{{ (n: nat), RET #n; ⌜ n = enc_gallina k v ⌝ }}}.\n  Proof.\n    rewrite /enc. iIntros (Φ) \"%Hdom HΦ\". wp_pures.\n    rewrite Z.shiftl_mul_pow2; last by lia.\n    iSpecialize (\"HΦ\" $! (Z.to_nat (Z.of_nat (enc_gallina k v)))).\n    rewrite /enc_gallina Nat.shiftl_mul_pow2.\n    rewrite Nat2Z.id Nat2Z.inj_add Nat2Z.inj_mul Nat2Z.inj_pow.\n    iApply \"HΦ\". auto.\n  Qed.\n\n\n  Definition fin_hash_dom_space : Type := fin (S (MAX_HASH_DOM)).\n  Definition fin_key_space : Type := fin (S (MAX_KEYS)).\n  Definition fin_val_space : Type := fin (S (MAX_VALS)).\n\n  (*\n  Instance finite_fin_val_space : Finite (fin_val_space).\n  Proof. apply _. Qed.\n  Instance finite_fin_key_space : Finite (fin_key_space).\n  Proof. apply _. Qed.\n  Instance finite_fin_hash_dom_space : Finite (fin_hash_dom_space).\n  Proof. apply _. Qed.\n   *)\n\n  Context {GHOST_MAP: ghost_mapG Σ fin_hash_dom_space (option bool)}.\n\n  Lemma fin_to_nat_S_le n (i: fin (S n)) : i <= n.\n  Proof. specialize (fin_to_nat_lt i). lia. Qed.\n\n  Definition enc_gallina_fin (k : fin_key_space) (v: fin_val_space) : fin_hash_dom_space.\n    refine (@nat_to_fin (enc_gallina (fin_to_nat k) (fin_to_nat v)) _ _).\n    abstract (apply (enc_gallina_range); apply fin_to_nat_lt).\n  Defined.\n\n  Definition key_of_enc_gallina_fin (x: fin_hash_dom_space) : fin_key_space.\n  refine (@nat_to_fin (key_of_enc_gallina x) _ _).\n  { abstract (cut (key_of_enc_gallina x <= MAX_KEYS); first lia;\n              apply key_of_enc_gallina_spec2; specialize (fin_to_nat_lt x); lia; auto). }\n  Defined.\n\n  Definition val_of_enc_gallina_fin (x: fin_hash_dom_space) : fin_val_space.\n  refine (@nat_to_fin (val_of_enc_gallina x) _ _).\n  { abstract (cut (val_of_enc_gallina x <= MAX_VALS); first lia;\n              apply val_of_enc_gallina_spec2; lia; auto). }\n  Defined.\n\n  Lemma enc_gallina_fin_inv x :\n    enc_gallina_fin (key_of_enc_gallina_fin x) (val_of_enc_gallina_fin x) = x.\n  Proof.\n    rewrite /enc_gallina_fin/key_of_enc_gallina_fin/val_of_enc_gallina_fin/=.\n    apply (inj fin_to_nat).\n    rewrite ?fin_to_nat_to_fin enc_gallina_inv //.\n  Qed.\n\n  Lemma enc_gallina_fin_inj k1 k2 v1 v2 :\n    enc_gallina_fin k1 v1 = enc_gallina_fin k2 v2 ->\n    k1 = k2 /\\ v1 = v2.\n  Proof.\n    rewrite /enc_gallina_fin.\n    intros Hfeq%(f_equal fin_to_nat).\n    rewrite ?fin_to_nat_to_fin in Hfeq.\n    apply enc_gallina_inj in Hfeq; auto using fin_to_nat_S_le.\n    split; apply (inj fin_to_nat); intuition auto.\n  Qed.\n\n  Definition khashN := nroot.@\"khash\".\n\n  Definition ghost_phys_dom (mphys : gmap nat bool) (mghost : gmap fin_hash_dom_space (option bool)) :=\n      (∀ x b, mphys !! (fin_to_nat x) = Some b → mghost !! x = Some (Some b)) ∧\n      (∀ x, mphys !! (fin_to_nat x) = None → mghost !! x = Some (None)).\n\n  Definition keyed_hash_auth_pure f f0 (mphys : gmap nat bool) (mghost : gmap fin_hash_dom_space (option bool))\n    : iProp Σ :=\n      ⌜ f = (λ: \"k\" \"v\", f0 (enc \"k\" \"v\"))%V ⌝ ∗\n      ⌜ ghost_phys_dom mphys mghost ⌝.\n\n  Definition keyed_hash_auth (γ : gname) (f : val) : iProp Σ :=\n    ∃ (f0 : val) (mphys : gmap nat bool) (mghost : gmap fin_hash_dom_space (option bool)),\n      keyed_hash_auth_pure f f0 mphys mghost ∗\n      ghost_map_auth γ 1 mghost ∗\n      hashfun MAX_HASH_DOM f0 mphys.\n\n  Definition skeyed_hash_auth (γ : gname) (f : val) : iProp Σ :=\n    ∃ (f0 : val) (mphys : gmap nat bool) (mghost : gmap fin_hash_dom_space (option bool)),\n      keyed_hash_auth_pure f f0 mphys mghost ∗\n      ghost_map_auth γ 1 mghost ∗\n      shashfun MAX_HASH_DOM f0 mphys.\n\n  Section timeless_spec.\n    Existing Instance timeless_shashfun.\n    Lemma timeless_skeyed_hash_auth γ f :\n      Timeless (skeyed_hash_auth γ f).\n    Proof. apply _. Qed.\n  End timeless_spec.\n\n  Existing Instance timeless_hashfun.\n  #[global] Instance timeless_keyed_hash_auth γ f :\n    Timeless (keyed_hash_auth γ f).\n  Proof. apply _. Qed.\n\n\n  (*\n  Definition is_keyed_hash γ f :=\n    inv khashN (keyed_hash_auth γ f).\n   *)\n\n  (* This encoding is annoying to work with because we don't have good lemmas for\n     \"set products\" and big_sepS over such products. *)\n  (*\n  Definition khashfun_own γ k (m : gmap nat bool) : iProp Σ :=\n    ⌜ ∀ x, x ∈ dom m → x <= MAX_VALS ⌝ ∗\n    [∗ set] v ∈ fin_to_set (fin_val_space), (enc_gallina_fin k v) ↪[γ] (m !! (fin_to_nat v)).\n   *)\n\n  Definition not_in_key_fin x k : Prop := (¬ ∃ v, enc_gallina_fin k v = x).\n\n  Lemma not_in_key_fin_spec x k :\n    k ≠ key_of_enc_gallina_fin x →\n    not_in_key_fin x k.\n  Proof.\n    intros Hneq (v&Henc). apply Hneq.\n    rewrite -Henc.\n    rewrite /enc_gallina_fin/key_of_enc_gallina_fin/val_of_enc_gallina_fin/=.\n    apply (inj fin_to_nat).\n    rewrite ?fin_to_nat_to_fin.\n    rewrite key_of_enc_gallina_spec1 //.\n    specialize (fin_to_nat_lt v); lia.\n  Qed.\n\n  (* This encoding is equivalent to the above in some sense but ends up being more workable\n     in the absence of the above lemmas; I learned this trick from an encoding Upamanyu Sharma used\n     used for representing \"shards\" of a key value store's key space, which is essentially equivalent\n     to the problem here. *)\n  Definition khashfun_own γ k (m : gmap nat bool) : iProp Σ :=\n    ⌜ ∀ x, x ∈ dom m → x <= MAX_VALS ⌝ ∗\n    [∗ set] kv ∈ fin_to_set (fin_hash_dom_space),\n      (∃ v, ⌜ enc_gallina_fin k v = kv ⌝ ∗ kv ↪[γ] (m !! (fin_to_nat v))) ∨ ⌜ not_in_key_fin kv k ⌝.\n\n  Lemma keyed_hash_ghost_init_split γ :\n   ([∗ map] k↦v ∈ gset_to_gmap None (fin_to_set fin_hash_dom_space), k ↪[γ] v) -∗\n   [∗ set] k ∈ fin_to_set fin_key_space, khashfun_own γ k ∅.\n  Proof.\n    rewrite /khashfun_own.\n    iIntros \"Hfrags\".\n    iApply big_sepS_sep.\n    iSplit.\n    { iPureIntro. rewrite /set_Forall. intros ???. rewrite dom_empty_L. set_solver. }\n    iApply big_sepS_sepS.\n    (* This proof is similar to one Ralf Jung developed for the above mentioned kv store's\n       ghost state initialization *)\n    iAssert ([∗ map] k↦v ∈ gset_to_gmap None (fin_to_set fin_hash_dom_space), k ↪[γ] None)%I with \"[Hfrags]\"\n      as \"H\".\n    { iApply (big_sepM_impl with \"Hfrags\"). iIntros \"!>\" (k x Hlookup).\n      rewrite lookup_gset_to_gmap_Some in Hlookup.\n      destruct Hlookup as (?&->). auto.\n    }\n    iDestruct (big_sepM_dom with \"H\") as \"H\".\n    rewrite dom_gset_to_gmap.\n    iApply (big_sepS_impl with \"H\").\n    iIntros \"!>\" (x Hin) \"Hx\".\n    rewrite (big_sepS_delete _ _ (key_of_enc_gallina_fin x)); last first.\n    { apply elem_of_fin_to_set. }\n    iSplitL \"Hx\".\n    - iLeft. iExists (val_of_enc_gallina_fin x). rewrite lookup_empty //. iFrame.\n      iPureIntro. rewrite enc_gallina_fin_inv //.\n    - iApply big_sepS_intro.\n      iIntros \"!#\" (k [Hk Hne]%elem_of_difference).\n      iRight.\n      iPureIntro.\n      set_unfold.\n      apply not_in_key_fin_spec; auto.\n  Qed.\n\n  Lemma ghost_phys_dom_init :\n    ghost_phys_dom ∅ (gset_to_gmap None (fin_to_set fin_hash_dom_space)).\n  Proof.\n    split.\n    - intros ??; rewrite lookup_empty; inversion 1.\n    - intros ? _.\n     rewrite lookup_gset_to_gmap_Some; split; auto.\n     apply elem_of_fin_to_set.\n  Qed.\n\n  Lemma wp_init_keyed_hash E :\n    {{{ True }}}\n      init_keyed_hash #() @ E\n    {{{ (f: val), RET f; ∃ γ, keyed_hash_auth γ f ∗\n                              [∗ set] k ∈ fin_to_set (fin_key_space), khashfun_own γ k ∅ }}}.\n  Proof.\n    iIntros (Φ) \"_ HΦ\".\n    rewrite /init_keyed_hash.\n    wp_pures.\n    wp_apply (wp_init_hash with \"[//]\").\n    iIntros (f0) \"Hf0\".\n    wp_pures. iApply \"HΦ\".\n    set (m := gset_to_gmap None (fin_to_set (fin_hash_dom_space)) : gmap _ (option bool)).\n    iMod (ghost_map_alloc m) as (γ) \"(Hauth&Hfrags)\".\n    iExists γ.\n    iSplitL \"Hf0 Hauth\".\n    { iExists _, _, _. iFrame. iPureIntro; split_and!; eauto using ghost_phys_dom_init. }\n    { iApply keyed_hash_ghost_init_split. auto. }\n  Qed.\n\n  Lemma spec_init_keyed_hash E K :\n    ↑specN ⊆ E →\n    refines_right K (init_keyed_hash #()) ={E}=∗\n    ∃ f γ, refines_right K (of_val f) ∗ skeyed_hash_auth γ f ∗\n           [∗ set] k ∈ fin_to_set (fin_key_space), khashfun_own γ k ∅.\n  Proof.\n    iIntros (?) \"HK\".\n    rewrite /init_keyed_hash.\n    tp_pures.\n    tp_bind (init_hash _).\n    rewrite refines_right_bind.\n    iMod (spec_init_hash with \"[$]\") as (f0) \"(HK&Hf0)\"; first done.\n    rewrite -refines_right_bind /=.\n    tp_pures.\n    set (m := gset_to_gmap None (fin_to_set (fin_hash_dom_space)) : gmap _ (option bool)).\n    iMod (ghost_map_alloc m) as (γ) \"(Hauth&Hfrags)\".\n    iExists _, γ. iFrame \"HK\".\n    iSplitL \"Hf0 Hauth\".\n    { iExists _, _, _. iFrame. iPureIntro; split_and!; eauto using ghost_phys_dom_init. }\n    { iApply keyed_hash_ghost_init_split. auto. }\n  Qed.\n\n  Lemma khashfun_own_acc_assign_hash γ k v m :\n    khashfun_own γ k m -∗\n    (enc_gallina_fin k v) ↪[γ] (m !! (fin_to_nat v)) ∗\n    (∀ b, (enc_gallina_fin k v) ↪[γ] (Some b) -∗ khashfun_own γ k (<[fin_to_nat v := b]>m)).\n  Proof.\n    iIntros \"(%Hdom&Hk)\".\n    rewrite (big_sepS_delete _ _ (enc_gallina_fin k v)); last first.\n    { apply elem_of_fin_to_set. }\n    iDestruct \"Hk\" as \"(Hkv&Hrest)\".\n    iSplitL \"Hkv\".\n    { iDestruct \"Hkv\" as \"[Hleft|%Hbad]\".\n      { iDestruct \"Hleft\" as (? Heq) \"H\". apply enc_gallina_fin_inj in Heq as (Heq1&Heq2). subst. auto. }\n      iExFalso. iPureIntro. apply Hbad. eexists; eauto.\n    }\n    iIntros (b) \"Hkv\". iSplit.\n    { iPureIntro. set_unfold. intros ? [?|?]; auto. subst.\n      apply fin_to_nat_S_le. }\n    iApply (big_sepS_delete _ _ (enc_gallina_fin k v)).\n    { apply elem_of_fin_to_set. }\n    iSplitL \"Hkv\".\n    { iLeft. iExists _. iSplit; first eauto. rewrite lookup_insert //. }\n    iApply (big_sepS_mono with \"Hrest\").\n    { iIntros (x [Hx Hne]%elem_of_difference).\n      set_unfold. iIntros \"H\".\n      iDestruct \"H\" as \"[Hleft|Hright]\"; last by (iRight; eauto).\n      iDestruct \"Hleft\" as (? Heq) \"Hx\". iLeft. iExists _; iSplit; first done.\n      rewrite lookup_insert_ne //. subst. intros Heq.\n      apply (inj fin_to_nat) in Heq. congruence.\n    }\n  Qed.\n\n  Lemma khashfun_own_acc_lookup γ k v m :\n    khashfun_own γ k m -∗\n    (enc_gallina_fin k v) ↪[γ] (m !! (fin_to_nat v)) ∗\n    ((enc_gallina_fin k v) ↪[γ] (m !! (fin_to_nat v)) -∗ khashfun_own γ k m).\n  Proof.\n    iIntros \"(%Hdom&Hk)\".\n    rewrite (big_sepS_delete _ _ (enc_gallina_fin k v)); last first.\n    { apply elem_of_fin_to_set. }\n    iDestruct \"Hk\" as \"(Hkv&Hrest)\".\n    iSplitL \"Hkv\".\n    { iDestruct \"Hkv\" as \"[Hleft|%Hbad]\".\n      { iDestruct \"Hleft\" as (? Heq) \"H\". apply enc_gallina_fin_inj in Heq as (Heq1&Heq2). subst. auto. }\n      iExFalso. iPureIntro. apply Hbad. eexists; eauto.\n    }\n    iIntros \"Hkv\". iSplit; auto. iApply big_sepS_delete; first by apply elem_of_fin_to_set. iFrame.\n    iLeft. eauto.\n  Qed.\n\n (* TODO: move *)\n  Lemma impl_couplable_wand (P Q: bool → iProp Σ) :\n    impl_couplable P -∗\n    (∀ b, P b -∗ Q b) -∗\n    impl_couplable Q.\n  Proof.\n    rewrite /impl_couplable.\n    iDestruct 1 as (α bs) \"(Hα&HP)\".\n    iIntros \"HPQ\".\n    iExists α, bs. iFrame. iIntros (?) \"H\". iApply \"HPQ\".\n    iApply \"HP\". auto.\n  Qed.\n\n (* TODO: move *)\n  Lemma spec_couplable_wand (P Q: bool → iProp Σ) :\n    spec_couplable P -∗\n    (∀ b, P b -∗ Q b) -∗\n    spec_couplable Q.\n  Proof.\n    iDestruct 1 as (α bs) \"(Hα&HP)\".\n    iIntros \"HPQ\".\n    iExists α, bs. iFrame. iIntros (?) \"H\". iApply \"HPQ\".\n    iApply \"HP\". auto.\n  Qed.\n\n  Lemma ghost_phys_dom_insert x b mphys mghost :\n    ghost_phys_dom mphys mghost →\n    ghost_phys_dom (<[fin_to_nat x :=b]> mphys) (<[x :=Some b]> mghost).\n  Proof.\n    intros (?&?).\n    split.\n  - intros x' b'. destruct (decide (x = x')).\n    { subst. rewrite ?lookup_insert // => -> //. }\n    rewrite ?lookup_insert_ne //; eauto. intros ?%(inj fin_to_nat); congruence.\n  - intros x'. destruct (decide (x = x')).\n    { subst. rewrite ?lookup_insert // => -> //. }\n    rewrite ?lookup_insert_ne //; eauto. intros ?%(inj fin_to_nat); congruence.\n  Qed.\n\n  Lemma ghost_phys_dom_rev mphys mghost x ob :\n    ghost_phys_dom mphys mghost →\n    mghost !! x = Some ob →\n    mphys !! (fin_to_nat x) = ob.\n  Proof.\n    intros (Hdom1&Hdom2) Hlook_ghost.\n    destruct ob as [b'|] eqn:Hob.\n    - destruct (mphys !! (fin_to_nat x)) as [b|] eqn:Hlook_phys; last first.\n      { exfalso. apply Hdom2 in Hlook_phys. rewrite Hlook_phys in Hlook_ghost. inversion Hlook_ghost. }\n      { apply Hdom1 in Hlook_phys. congruence. }\n    - destruct (mphys !! (fin_to_nat x)) as [b|] eqn:Hlook_phys.\n      { exfalso. apply Hdom1 in Hlook_phys. rewrite Hlook_phys in Hlook_ghost. inversion Hlook_ghost. }\n      { apply Hdom2 in Hlook_phys. congruence. }\n  Qed.\n\n  Lemma khashfun_own_couplable γ k f m v:\n    v <= MAX_VALS →\n    m !! v = None →\n    keyed_hash_auth γ f -∗\n    khashfun_own γ k m -∗ impl_couplable (λ b, |==> keyed_hash_auth γ f ∗ khashfun_own γ k (<[v:=b]>m)).\n  Proof.\n    iIntros (Hmax Hlookup) \"Hhash Hk\".\n    assert (Hmax': v < S MAX_VALS) by lia.\n    set (v' := nat_to_fin Hmax' : fin_val_space).\n    iDestruct \"Hhash\" as (??? (Heq1&Hdom1&Hdom2)) \"(Hauth&H)\".\n    set (x := enc_gallina_fin k v').\n    iDestruct (khashfun_own_acc_assign_hash _ _ v' with \"Hk\") as \"(Hpts&Hclo')\".\n    iDestruct (ghost_map_lookup with \"[$] [$]\") as %Hlook.\n    assert (m !! fin_to_nat v' = None) as Hnone.\n    { rewrite fin_to_nat_to_fin //. }\n    rewrite Hnone in Hlook.\n    iDestruct (hashfun_couplable (enc_gallina_fin k v') with \"H\") as \"H\".\n    { apply fin_to_nat_S_le. }\n    { eapply ghost_phys_dom_rev; eauto. split; auto. }\n    iApply (impl_couplable_wand with \"H\").\n    iIntros (b) \"Hhash\".\n    iMod (ghost_map_update (Some b) with \"[$] [$]\") as \"(Hauth&Hpts)\".\n    iDestruct (\"Hclo'\" with \"[$]\") as \"Hk\".\n    iModIntro.\n    iSplitL \"Hhash Hauth\".\n    { iExists _, _, _.\n      iFrame. iPureIntro; split_and!; eauto.\n      apply ghost_phys_dom_insert. split; auto.\n    }\n    rewrite /v' fin_to_nat_to_fin //.\n  Qed.\n\n  Lemma khashfun_own_spec_couplable γ k f m v:\n    v <= MAX_VALS →\n    m !! v = None →\n    skeyed_hash_auth γ f -∗\n    khashfun_own γ k m -∗ spec_couplable (λ b, |==> skeyed_hash_auth γ f ∗ khashfun_own γ k (<[v:=b]>m)).\n  Proof.\n    iIntros (Hmax Hlookup) \"Hhash Hk\".\n    assert (Hmax': v < S MAX_VALS) by lia.\n    set (v' := nat_to_fin Hmax' : fin_val_space).\n    iDestruct \"Hhash\" as (??? (Heq1&Hdom1&Hdom2)) \"(Hauth&H)\".\n    set (x := enc_gallina_fin k v').\n    iDestruct (khashfun_own_acc_assign_hash _ _ v' with \"Hk\") as \"(Hpts&Hclo')\".\n    iDestruct (ghost_map_lookup with \"[$] [$]\") as %Hlook.\n    assert (m !! fin_to_nat v' = None) as Hnone.\n    { rewrite fin_to_nat_to_fin //. }\n    rewrite Hnone in Hlook.\n    iDestruct (shashfun_couplable (enc_gallina_fin k v') with \"H\") as \"H\".\n    { apply fin_to_nat_S_le. }\n    { eapply ghost_phys_dom_rev; eauto. split; auto. }\n    iApply (spec_couplable_wand with \"H\").\n    iIntros (b) \"Hhash\".\n    iMod (ghost_map_update (Some b) with \"[$] [$]\") as \"(Hauth&Hpts)\".\n    iDestruct (\"Hclo'\" with \"[$]\") as \"Hk\".\n    iModIntro.\n    iSplitL \"Hhash Hauth\".\n    { iExists _, _, _.\n      iFrame. iPureIntro; split_and!; eauto.\n      apply ghost_phys_dom_insert. split; auto.\n    }\n    rewrite /v' fin_to_nat_to_fin //.\n  Qed.\n\n  Lemma wp_khashfun_prev E f m k (v : nat) γ (b : bool) :\n    m !! v = Some b →\n    {{{ keyed_hash_auth γ f ∗ khashfun_own γ k m }}}\n      f #k #v @ E\n    {{{ RET #b; keyed_hash_auth γ f ∗ khashfun_own γ k m }}}.\n  Proof.\n    iIntros (Hlookup Φ) \"(H&Hown) HΦ\".\n    iDestruct \"H\" as (??? (Heq1&Hdom1&Hdom2)) \"(Hauth&H)\".\n    rewrite Heq1. rewrite /enc. wp_pures.\n    iAssert (⌜ v < S MAX_VALS ⌝)%I as \"%Hmax'\".\n    { iDestruct \"Hown\" as \"(%Hdom&_)\". iPureIntro. apply elem_of_dom_2 in Hlookup.\n      apply Hdom in Hlookup. lia. }\n    set (v' := nat_to_fin Hmax' : fin_val_space).\n    replace (#(k ≪ MAX_VALS_POW + v)) with #(fin_to_nat (enc_gallina_fin k v')); last first.\n    { f_equal. rewrite /enc_gallina_fin ?fin_to_nat_to_fin /enc_gallina.\n      rewrite /enc_gallina Nat.shiftl_mul_pow2 Z.shiftl_mul_pow2; last by lia.\n      rewrite Nat2Z.inj_add Nat2Z.inj_mul Nat2Z.inj_pow //.\n    }\n    iDestruct (khashfun_own_acc_lookup _ _ v' with \"Hown\") as \"(Hkv&Hclo)\".\n    iDestruct (ghost_map_lookup with \"[$] [$]\") as %Hlook.\n    eapply ghost_phys_dom_rev in Hlook; last by (split; eauto).\n    wp_apply (wp_hashfun_prev with \"H\").\n    { rewrite Hlook. rewrite ?fin_to_nat_to_fin //. }\n    iIntros \"H\".\n    iApply \"HΦ\". iSplitL \"Hauth H\".\n    { iExists _, _, _. iFrame. eauto. }\n    iApply \"Hclo\". eauto.\n  Qed.\n\n  Lemma spec_khashfun_prev E K f m k (v : nat) γ (b : bool) :\n    m !! v = Some b →\n    ↑specN ⊆ E →\n    skeyed_hash_auth γ f -∗\n    khashfun_own γ k m -∗\n    refines_right K (f #k #v) ={E}=∗\n    refines_right K (of_val #b) ∗ skeyed_hash_auth γ f ∗ khashfun_own γ k m.\n  Proof.\n    iIntros (Hlookup ?) \"Hauth Hown HK\".\n    iDestruct \"Hauth\" as (??? (Heq1&Hdom1&Hdom2)) \"(Hauth&H)\".\n    rewrite Heq1. rewrite /enc. tp_pures.\n    iAssert (⌜ v < S MAX_VALS ⌝)%I as \"%Hmax'\".\n    { iDestruct \"Hown\" as \"(%Hdom&_)\". iPureIntro. apply elem_of_dom_2 in Hlookup.\n      apply Hdom in Hlookup. lia. }\n    set (v' := nat_to_fin Hmax' : fin_val_space).\n    replace (#(k ≪ MAX_VALS_POW + v)) with #(fin_to_nat (enc_gallina_fin k v')); last first.\n    { f_equal. rewrite /enc_gallina_fin ?fin_to_nat_to_fin /enc_gallina.\n      rewrite /enc_gallina Nat.shiftl_mul_pow2 Z.shiftl_mul_pow2; last by lia.\n      rewrite Nat2Z.inj_add Nat2Z.inj_mul Nat2Z.inj_pow //.\n    }\n    iDestruct (khashfun_own_acc_lookup _ _ v' with \"Hown\") as \"(Hkv&Hclo)\".\n    iDestruct (ghost_map_lookup with \"[$] [$]\") as %Hlook.\n    eapply ghost_phys_dom_rev in Hlook; last by (split; eauto).\n    iMod (spec_hashfun_prev with \"H HK\") as \"(HK&H)\".\n    { rewrite Hlook. rewrite ?fin_to_nat_to_fin //. }\n    { done. }\n    iFrame.\n    iModIntro.\n    iSplitL \"Hauth H\".\n    { iExists _, _, _. iFrame. eauto. }\n    iApply \"Hclo\". eauto.\n  Qed.\n\n  (* Actually this is not true: if v is out of range it can be as if\n     you're hashing a differnt value with some other key! *)\n  Lemma wp_khashfun_out_of_range E f k m (v : Z) γ :\n    (v < 0 ∨ MAX_VALS < v)%Z →\n    {{{ keyed_hash_auth γ f ∗ khashfun_own γ k m }}}\n      f #k #v @ E\n    {{{ RET #false; keyed_hash_auth γ f ∗ khashfun_own γ k m }}}.\n  Proof.\n  Abort.\n\nEnd keyed_hash.\n", "meta": {"author": "logsem", "repo": "clutch", "sha": "35144f9b1fe9c913b4bd24106a12ac7f02b20ec5", "save_path": "github-repos/coq/logsem-clutch", "path": "github-repos/coq/logsem-clutch/clutch-35144f9b1fe9c913b4bd24106a12ac7f02b20ec5/theories/examples/keyed_hash.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2996068632054748}}
{"text": "(**\nCoLoR, a Coq library on rewriting and termination.\nSee the COPYRIGHTS and LICENSE files.\n\n- Adam Koprowski, 2004-09-06\n\nThis file provides an implementation of finite multisets using list\nrepresentation.\n*)\n\nSet Implicit Arguments.\n\nRequire Import LogicUtil RelExtras MultisetCore Permutation Multiset List\n  ListExtras PermutSetoid Omega.\n\nModule MultisetList (ES : Eqset_dec) <: MultisetCore with Module Sid := ES.\n\n  Module Export Sid := ES.\n\nSection Operations.\n\n  Definition Multiset := list A.\n\n  Definition empty : Multiset := nil.\n  Definition singleton a : Multiset := a :: nil.\n  Definition union := app (A:=A).\n  Definition meq := permutation eqA eqA_dec.\n\n  Definition mult := countIn eqA eqA_dec.\n  Definition rem := removeElem eqA eqA_dec.\n  Definition diff := removeAll eqA eqA_dec.\n\n  Definition intersection := inter_as_diff diff.\n\n  Definition fold_left := fun T : Type => List.fold_left (A := T) (B := A).\n\nEnd Operations.\n\n  Infix \"=mul=\" := meq (at level 70) : msets_scope.\n  Notation \"X <>mul Y\" := (~meq X Y) (at level 50) : msets_scope.\n  Notation \"{{ x }}\" := (singleton x) (at level 5) : msets_scope.\n  Infix \"+\" := union : msets_scope.\n  Infix \"-\" := diff : msets_scope.\n  Infix \"#\" := intersection (at level 50, left associativity) : msets_scope.\n  Infix \"/\" := mult : msets_scope.\n\n  Delimit Scope msets_scope with msets.\n  Open Scope msets_scope.\n  Bind Scope msets_scope with Multiset.\n\nSection ImplLemmas.\n\n  Lemma empty_empty : forall M, (forall x, x / M = 0) -> M = empty.\n\n  Proof.\n    intros M mulM; destruct M.\n    trivial.\n    absurd (a / (a::M) = 0).\n    simpl; case (eqA_dec a a); auto with sets.\n    auto.\n  Qed.\n\nEnd ImplLemmas.\n\nSection SpecConformation.\n\n  Lemma mult_eqA_compat : forall M x y, x =A= y -> x / M = y / M.\n\n  Proof.\n     induction M.\n     auto.\n     intros; simpl.\n     case (eqA_dec x a); case (eqA_dec y a); intros;\n       solve [ absurd (y =A= a); eauto with sets\n             | assert (x / M = y / M); auto ].\n  Qed.\n\n  Lemma mult_comp : forall l a,\n    a / l = multiplicity (list_contents eqA eqA_dec l) a.\n\n  Proof.\n    induction l.\n    auto.\n    intro a0; simpl.\n    case (eqA_dec a0 a); intro a0_a; case (eqA_dec a a0); intro a_a0;\n      solve [ absurd (a0 =A= a); auto with sets \n            | rewrite (IHl a0); trivial].\n  Qed.\n\n  Lemma multeq_meq : forall M N, (forall x, x / M = x / N) -> M =mul= N.\n\n  Proof.\n    unfold meq. intros M N mult_MN x. rewrite <- !mult_comp. exact (mult_MN x).\n  Qed.\n\n  Lemma meq_multeq : forall M N, M =mul= N -> forall x, x / M = x / N.\n\n  Proof.\n    unfold meq, permutation, Multiset.meq.\n    intros M N eqMN x. rewrite !mult_comp. exact (eqMN x).\n  Qed.\n\n  Lemma empty_mult : forall x, mult x empty = 0.\n\n  Proof. auto. Qed.\n\n  Lemma union_mult : forall M N x, x / ((M + N))%msets = ((mult x  M)+ (mult x  N))%nat.\n\n  Proof.\n    induction M; auto.\n    intros; simpl; case (eqA_dec x a); intro; auto.\n    replace (x / (M + N)) with ((mult x M) + (mult x  N))%nat; \n      solve [auto | apply IHM].\n  Qed.\n\n  Lemma diff_empty_l : forall M, empty - M = empty.\n\n  Proof.\n    induction M; auto.\n  Qed.\n\n  Lemma diff_empty_r : forall M, M - empty = M.\n\n  Proof.\n    induction M; auto.\n  Qed.\n\n  Lemma mult_remove_in : forall x a M,\n    x =A= a -> x / (rem a M) = ((mult x M) - 1)%nat.\n\n  Proof.\n    induction M.\n    auto.\n    intro x_a.\n    simpl; case (eqA_dec x a0); case (eqA_dec a a0); \n      simpl; intros; try solve [absurd (x =A= a); eauto with sets].\n    auto with arith.\n    destruct (eqA_dec x a0).\n    contr.\n    auto.\n  Qed.\n\n  Lemma mult_remove_not_in : forall M a x,\n    ~ x =A= a -> x / (rem a M) = x / M.\n\n  Proof.\n    induction M; intros.\n    auto.\n    simpl; case (eqA_dec a0 a); intro a0_a.\n    case (eqA_dec x a); intro x_a; \n      solve [absurd (x =A= a); eauto with sets | trivial].\n    simpl; case (eqA_dec x a); intro x_a.\n    rewrite (IHM a0 x); trivial.\n    apply IHM; trivial.\n  Qed.\n\n  Lemma remove_perm_single : forall x a b M,\n   x / (rem a (rem b M)) = x / (rem b (rem a M)).\n\n  Proof.\n    intros x a b M.\n    case (eqA_dec x a); case (eqA_dec x b); intros x_b x_a.\n     (* x=b,  x=a *)\n    rewrite !mult_remove_in; trivial.\n     (* x<>b, x=a *)\n    rewrite mult_remove_in; trivial.\n    do 2 (rewrite mult_remove_not_in; trivial).\n    rewrite mult_remove_in; trivial.\n     (* x=b,  x<>a *)\n    rewrite mult_remove_not_in; trivial.\n    do 2 (rewrite mult_remove_in; trivial).\n    rewrite mult_remove_not_in; trivial.\n     (* x<>b, x<>a *)\n    rewrite !mult_remove_not_in; trivial.\n  Qed.\n\n  Lemma diff_mult_comp : forall x N M M',\n    M =mul= M' -> x / (M - N) = x / (M' - N).\n\n  Proof.\n    induction N.\n    intros; apply meq_multeq; trivial.\n    intros M M' MM'.\n    simpl.\n    apply IHN.\n    apply multeq_meq.\n    intro x'.\n    case (eqA_dec x' a).\n    intro xa; rewrite !mult_remove_in; trivial.\n    rewrite (meq_multeq MM'); trivial.\n    intro xna; rewrite !mult_remove_not_in; trivial.\n    apply meq_multeq; trivial.\n  Qed.\n\n  Lemma diff_perm_single : forall x a b M N, \n    x / (M - (a::b::N)) = x / (M - (b::a::N)).\n\n  Proof.\n    intros x a b M N.\n    simpl; apply diff_mult_comp.\n    apply multeq_meq.\n    intro x'; apply remove_perm_single.\n  Qed.\n\n  Lemma diff_perm : forall M N a x,\n    x / ((rem a M) - N) = x / (rem a (M - N)).\n\n  Proof.\n    intros M N; gen M; clear M.\n    induction N.\n    auto.\n    intros M b x.\n    change (rem b M - (a::N)) with (M - (b::a::N)).\n    rewrite diff_perm_single.\n    simpl; apply IHN.\n  Qed.\n\n  Lemma diff_mult_step_eq : forall M N a x,\n    x =A= a -> x / (rem a M - N) = (mult x  (M - N)%msets - 1)%nat.\n\n  Proof.\n    intros M N a x x_a.\n    rewrite diff_perm.\n    rewrite mult_remove_in; trivial.\n  Qed.\n\n  Lemma diff_mult_step_neq : forall M N a x,\n    ~ x =A= a -> x / (rem a M - N) = x / (M - N).\n\n  Proof.\n    intros M N a x x_a.\n    rewrite diff_perm.\n    rewrite mult_remove_not_in; trivial.\n  Qed.\n \n  Lemma diff_mult : forall M N x, x / (M - N) = ((mult x  M) - (mult x N))%nat.\n\n  Proof.\n    induction N.\n     (* induction base *)\n    simpl; intros; omega.\n     (* induction step *)\n    intro x; simpl.\n    case (eqA_dec x a); intro x_a; simpl.\n     (* x = a *)\n    fold rem.\n    rewrite (diff_mult_step_eq M N x_a).\n    rewrite (IHN x).\n    omega.\n     (* x <> a *)\n    fold rem.\n    rewrite (diff_mult_step_neq M N x_a).\n    exact (IHN x).\n  Qed.\n\n  Definition intersection_mult := inter_as_diff_ok mult diff diff_mult.\n\n  Lemma singleton_mult_in : forall x y, x =A= y -> x / {{y}} = 1.\n\n  Proof.\n    intros; compute.\n    case (eqA_dec x y); [trivial | contr].\n  Qed.\n  \n  Lemma singleton_mult_notin : forall x y, ~x =A= y -> x / {{y}} = 0.\n\n  Proof.\n    intros; compute.\n    case (eqA_dec x y); [contr | trivial].\n  Qed.\n\n  Lemma rev_list_ind_type : forall P : Multiset -> Type,\n    P nil -> (forall a l, P (rev l) -> P (rev (a :: l))) -> forall l, P (rev l).\n\n  Proof.\n    induction l; auto.\n  Defined.\n\n  Lemma rev_ind_type : forall P : Multiset -> Type,\n    P nil -> (forall x l, P l -> P (l ++ x :: nil)) -> forall l, P l.\n\n  Proof.\n    intros.\n    gen (rev_involutive l).\n    intros E; rewrite <- E.\n    apply (rev_list_ind_type P).\n    auto.\n    simpl in |- *.\n    intros.\n    apply (X0 a (rev l0)).\n    auto.\n  Defined.\n\n  Lemma mset_ind_type : forall P : Multiset -> Type,\n    P empty -> (forall M a, P M -> P (union M {{a}})) -> forall M, P M.\n\n  Proof.\n    induction M as [| x M] using rev_ind_type.\n    exact X.\n    exact (X0 M x IHM).\n  Defined.\n \nEnd SpecConformation.\n\n  Hint Unfold meq \n\t      empty\n              singleton\n              mult\n              union\n              diff : multisets.\n\n  Hint Resolve mult_eqA_compat \n               meq_multeq\n               multeq_meq\n               empty_mult\n               union_mult\n               diff_mult\n               intersection_mult\n               singleton_mult_in\n               singleton_mult_notin : multisets.\n\n  Hint Rewrite empty_mult\n               union_mult\n\t       diff_mult\n\t       intersection_mult using trivial : multisets.\n\nEnd MultisetList.\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/CoLoR/Coq8.6/MultisetList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2996068561325053}}
{"text": "Require Import VST.floyd.base.\n\nLtac make_ground_PTree a :=\n let a := eval hnf in a in\n match a with\n | PTree.Leaf => constr:(a)\n | PTree.Node ?l ?o ?r => \n    let l := make_ground_PTree l in\n    let r := make_ground_PTree r in\n    let o := eval hnf in o in \n    constr:(PTree.Node l o r)\n end.\n\nLtac simpl_PTree_get_old :=\n  repeat match goal with\n         | |- context [PTree.get ?i' ?t] =>\n           let i'' := eval hnf in i' in\n               change (PTree.get i' t) with\n               ((fix get (A : Type) (i : positive) (m : PTree.t A) {struct i} : option A :=\n                 match m with\n                 | PTree.Leaf => None\n                 | PTree.Node l o r =>\n                     match i with\n                     | (ii~1)%positive => get A ii r\n                     | (ii~0)%positive => get A ii l\n                     | 1%positive => o\n                     end\n                 end) _ i'' t)\n         end;\n  cbv iota zeta beta.\n\nLtac simpl_PTree_get :=\n  repeat match goal with\n         | |- context [PTree.get ?i' ?t] =>\n           let g := constr:(PTree.get i' t) in \n           let g := eval hnf in g in\n           change (PTree.get i' t) with g\n         end;\n  cbv iota zeta beta.\n\nLtac simpl_eqb_type :=\n  repeat\n  match goal with\n  | |- context [eqb_type ?t1 ?t2] =>\n    let b := eval hnf in (eqb_type t1 t2) in\n    change (eqb_type t1 t2) with b;\n    cbv beta iota zeta\n  end.\n\nLtac simpl_temp_types_get :=\n  repeat\n  match goal with\n  | |- context [(temp_types ?Delta) ! ?i] =>\n          let ret := eval hnf in ((temp_types Delta) ! i) in\n          change ((temp_types Delta) ! i) with ret\n  end.\n\nLtac pos_eqb_tac :=\n  let H := fresh \"H\" in\n  match goal with\n  | |- context [Pos.eqb ?i ?j] => destruct (Pos.eqb i j) eqn:H; [apply Pos.eqb_eq in H | apply Pos.eqb_neq in H]\n  end.\n\n\nDefinition VST_floyd_map {A B : Type} (f: A -> B): list A -> list B :=\n  fix map (l : list A) : list B := match l with\n                                   | nil => nil\n                                   | a :: t => f a :: map t\n                                   end.\n\nDefinition VST_floyd_app {A: Type}: list A -> list A -> list A :=\n  fix app (l m : list A) {struct l} : list A :=\n  match l with\n  | nil => m\n  | a :: l1 => a :: app l1 m\n  end.\n\nDefinition VST_floyd_concat {A: Type}: list (list A) -> list A :=\n  fix concat (l : list (list A)) : list A :=\n  match l with\n  | nil => nil\n  | x :: l0 => VST_floyd_app x (concat l0)\n  end.\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/computable_functions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.29960685613250526}}
{"text": "From Coq Require Import\n     Program\n     Setoid\n     Morphisms\n     Relations.\n\n\n\nFrom ITree Require Import\n     Basics.Basics\n     Basics.Tacs\n     Basics.HeterogeneousRelations\n .\n\nFrom EnTree Require Import\n     Basics.HeterogeneousRelations\n     Core.EnTreeDefinition\n     Eq.Eqit\n.\n\nFrom Paco Require Import paco.\n\nLocal Open Scope entree_scope.\n\nSection padded.\nContext {E : Type} `{EncodingType E} {R : Type}.\n\nVariant paddedF (F : entree E R -> Prop) : entree' E R -> Prop :=\n  | paddedF_Ret r : paddedF F (RetF r)\n  | paddedF_Tau t : F t -> paddedF F (TauF t)\n  | paddedF_Vis e (k : encodes e -> entree E R) :\n    (forall a, F (k a)) -> paddedF F (VisF e (fun a => (Tau (k a))))\n.\nHint Constructors paddedF : entree_spec.\n\nDefinition padded_ sim := fun t => paddedF sim (observe t).\n\nLemma padded_monotone_ : monotone1 padded_.\nProof with eauto with entree_spec. \n  red. unfold padded_. intros. \n  induction IN...\nQed.\n\nHint Resolve padded_monotone_ : entree_spec.\n\nDefinition padded := paco1 padded_ bot1.\n\nLemma padded_VisF_inv e k F : paddedF F (VisF e k) -> exists k', forall a, k a ≅ Tau (k' a).\nProof with eauto with entree_spec.\n  intros. dependent destruction H0... eexists. reflexivity.\nQed.\n\n\nCoFixpoint pad' (ot : entree' E R) : entree E R :=\n  match ot with\n  | RetF r => Ret r\n  | TauF t => Tau (pad' (observe t))\n  | VisF e k => Vis e (fun x => Tau (pad' (observe (k x)))) \n  end.\n\nDefinition pad t := pad' (observe t).\n\nLemma pad_ret r : pad (Ret r) ≅ Ret r.\nProof.\n  pstep. constructor. auto.\nQed.\n\nLemma pad_tau t : pad (Tau t) ≅ Tau (pad t).\nProof.\n  pstep. red. cbn. constructor. left. enough (pad t ≅ pad t). auto.\n  reflexivity.\nQed.\n\nLemma pad_vis e k : pad (Vis e k) ≅ Vis e (fun x => Tau (pad (k x))).\nProof.\n  pstep. red. cbn. constructor. left.  pstep. constructor.\n  left. enough (pad (k a) ≅ pad (k a)). auto. reflexivity.\nQed.\n\nEnd padded.\n\nTheorem pad_is_padded {E : Type} `{EncodingType E} {R : Type} : forall t : entree E R, padded (pad t).\nProof with eauto with entree_spec.\n  pcofix CIH. intros. pstep. unfold pad.\n  destruct (observe t); eauto. constructor. constructor. right. eauto.\n  econstructor. intros. eauto.\nQed.\n#[global] Hint Resolve padded_monotone_ : paco.\n#[global] Hint Resolve padded_monotone_ : entree_spec.\n#[global] Hint Resolve pad_is_padded : entree_spec.\n\nTheorem pad_eutt {E : Type} `{EncodingType E} {R : Type} : forall t : entree E R, t ≈ pad t.\nProof with eauto with entree_spec.\n  ginit. gcofix CIH. intros.\n  unfold pad.\n  destruct (observe t) eqn : Ht; symmetry in Ht; apply simpobs in Ht.\n  - rewrite <- Ht. gstep. constructor. auto.\n  - rewrite <- Ht. gstep. red. cbn. constructor.\n    gfinal. eauto.\n  - rewrite <- Ht. gstep. red. cbn.\n    constructor. intros. red.\n    rewrite tau_euttge.\n    gfinal. eauto.\nQed.\n\nGlobal Instance pad_Proper {b1 b2 E R} `{EncodingType E} : Proper (eqit eq b1 b2 ==> eqit eq b1 b2) (@pad E _ R).\nProof.\n  pcofix CIH.\n  intros t1 t2 Ht12. pstep. red. unfold pad.\n  punfold Ht12. red in Ht12. hinduction Ht12 before r;\n    intros; cbn; eauto.\n  - constructor. auto.\n  - constructor. pclearbot. right. eapply CIH; eauto.\n  - constructor. left. pstep. constructor. pclearbot. right.\n    eapply CIH; eauto. apply REL.\n  - constructor; auto.\n  - constructor; auto.\nQed.\n\nTheorem pad_bind {E : Type} `{EncodingType E} {R S: Type} : forall (t : entree E R) (k : R -> entree E S),\n    pad (EnTree.bind t k) ≅ EnTree.bind (pad t) (fun x => pad (k x)).\nProof.\n  ginit. gcofix CIH. intros t k.\n  destruct (observe t) eqn : Heq; symmetry in Heq; apply simpobs in Heq.\n  - rewrite <- Heq. rewrite pad_ret. repeat rewrite bind_ret_l.\n    apply Reflexive_eqit_gen. auto.\n  - repeat rewrite <- Heq. rewrite pad_tau. repeat rewrite bind_tau. gstep. constructor.\n    gfinal. eauto.\n  - repeat rewrite <- Heq. rewrite pad_vis. repeat rewrite bind_vis. rewrite pad_vis.\n    gstep. constructor. intros. unfold id. gstep. constructor. gfinal. left. eapply CIH.\nQed.\n\nTheorem pad_iter E `{EncodingType E} R S (body : R -> entree E (R + S)):\n  forall r, pad (EnTree.iter body r) ≅ EnTree.iter (fun r => pad (body r)) r.\nProof.\n  ginit. gcofix CIH.\n  intros. setoid_rewrite unfold_iter. rewrite pad_bind.\n  guclo eqit_clo_bind. econstructor.\n  reflexivity. intros. subst. destruct u2.\n  - rewrite pad_tau. gstep. constructor. gfinal. left. eauto.\n  - rewrite pad_ret. gstep. constructor. auto.\nQed.\n\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/Padded.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.2996068561325052}}
{"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\nRequire Import Classical.\nRequire Import ClassicalEpsilon.\nRequire Import Coqlib.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Integers.\nRequire Import Smallstep.\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\n(** [CompCertX:test-compcert-param-final] We parameterize the semantics\nover the type of final return value. For whole programs, this shall be\n[int]. *)\n\nInductive program_behavior (RETVAL: Type): Type :=\n  | Terminates: trace -> RETVAL -> program_behavior RETVAL\n  | Diverges: trace -> program_behavior RETVAL\n  | Reacts: traceinf -> program_behavior RETVAL\n  | Goes_wrong: trace -> program_behavior RETVAL.\nArguments Diverges [_] _.\nArguments Reacts [_] _.\nArguments Goes_wrong [_] _.\n\n(** Operations and relations on behaviors *)\n\nDefinition not_wrong (RETVAL: Type) (beh: program_behavior RETVAL) : Prop :=\n  match beh with\n  | Terminates _ _ => True\n  | Diverges _ => True\n  | Reacts _ => True\n  | Goes_wrong _ => False\n  end.\n\nDefinition behavior_app (RETVAL: Type) (t: trace) (beh: program_behavior RETVAL): program_behavior RETVAL :=\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 (RETVAL: Type) t1 t2 (beh: _ RETVAL),\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 (RETVAL: Type) (beh: _ RETVAL), behavior_app E0 beh = beh.\nProof.\n  destruct beh; auto.\nQed.\n\nDefinition behavior_prefix (RETVAL: Type) (t: trace) (beh: program_behavior RETVAL) : Prop :=\n  exists beh', beh = behavior_app t beh'.\n\nDefinition behavior_improves (RETVAL: Type) (beh1 beh2: program_behavior RETVAL) : Prop :=\n  beh1 = beh2 \\/ exists t, beh1 = Goes_wrong t /\\ behavior_prefix t beh2.\n\nLemma behavior_improves_refl:\n  forall (RETVAL: Type) (beh: _ RETVAL), behavior_improves beh beh.\nProof.\n  intros; red; auto.\nQed.\n\nLemma behavior_improves_trans:\n  forall (RETVAL: Type) (beh1 beh2 beh3: _ RETVAL), \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 (RETVAL: Type) (beh: _ RETVAL), 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 (RETVAL: Type) t (beh1 beh2: _ RETVAL),\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 RETVAL: Type.\nVariable L: semantics RETVAL.\n\nInductive state_behaves (s: state L): program_behavior RETVAL -> 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 RETVAL -> 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 accepts 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 RETVAL: Type.\nVariable L1: semantics RETVAL.\nVariable L2: semantics RETVAL.\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 (RETVAL := RETVAL) t) with (behavior_app t (Goes_wrong (RETVAL := RETVAL) 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 RETVAL: Type.\nVariable L1: semantics RETVAL.\nVariable L2: semantics RETVAL.\nVariable S: backward_simulation L1 L2.\n\nDefinition safe_along_behavior (s: state L1) (b: program_behavior RETVAL) : 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 (RETVAL := RETVAL) 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 (RETVAL := RETVAL) 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 RETVAL: Type.\nVariable L: semantics RETVAL.\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 -> Plus (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 RETVAL: Type.\nVariable B: bigstep_semantics RETVAL.\nVariable L: semantics RETVAL.\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": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/compcert/common/Behaviors.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.29960684905953566}}
{"text": "(* Generated by Frama-C WP *)\n\nGoal typed_cast_memset_loop_invariant_3_established.\nHint established,memset.\nProof.\n  Require Import Lia.\n  intros.\n  unfold x_1.\n  unfold land.\n  simpl.\n  unfold x.\n\n  assert ((land 3 (to_uint32 (- int_of_addr a))) <= 3)%Z. {\n    apply uint_land_range; lia.\n  }\n\n  assert (i - land 3 (to_uint32 (- int_of_addr a)) >= 0)%Z. {\n    auto with zarith.\n  }\n\n  assert (i - land 3 (to_uint32 (- int_of_addr a)) <= i)%Z. {\n    apply Z.le_sub_nonneg.\n    apply uint_land_range.\n    lia.\n  }\n\n  assert  (Zbits.land (i - land 3 (to_uint32 (- int_of_addr a))) 4294967292 <=\n          (i - land 3 (to_uint32 (- int_of_addr a))))%Z. {\n    apply Zbits.uint_land_range.\n    auto with zarith.\n  }\n\n  assert (is_uint32 (i - land 3 (to_uint32 (- int_of_addr a)))). {\n    unfold is_uint32 in *.\n    lia.\n  }\n\n  split.\n  + rewrite id_uint32. { rewrite land_commut; try lia. } auto.\n  + rewrite id_uint32. { apply Zbits.uint_land_range; lia.  } auto.\n(* auto with zarith. *)\nQed.\n\nGoal typed_cast_memset_loop_invariant_established.\nHint established,memset.\nProof.\n  Require Import Lia.\n  intros.\n  unfold x_1.\n  unfold land.\n  simpl.\n  unfold x.\n\n  assert ((land 3 (to_uint32 (- int_of_addr a))) <= 3)%Z. {\n    apply uint_land_range; lia.\n  }\n\n  assert (i - land 3 (to_uint32 (- int_of_addr a)) >= 0)%Z. {\n    auto with zarith.\n  }\n\n  assert (i - land 3 (to_uint32 (- int_of_addr a)) <= i)%Z. {\n    apply Z.le_sub_nonneg.\n    apply uint_land_range.\n    lia.\n  }\n\n  assert  (Zbits.land (i - land 3 (to_uint32 (- int_of_addr a))) 4294967292 <=\n          (i - land 3 (to_uint32 (- int_of_addr a))))%Z. {\n    apply Zbits.uint_land_range.\n    auto with zarith.\n  }\n\n  assert (is_uint32 (i - land 3 (to_uint32 (- int_of_addr a)))). {\n    unfold is_uint32 in *.\n    lia.\n  }\n\n  split.\n  + rewrite id_uint32. { rewrite land_commut; try lia. } auto.\n  + rewrite id_uint32. { apply Zbits.uint_land_range; lia.  } auto.\nQed.\n\n\n", "meta": {"author": "VladYagl", "repo": "C-library-verification", "sha": "9d28d1edaf8f3e6e23d60825f53a9893c07ee5ef", "save_path": "github-repos/coq/VladYagl-C-library-verification", "path": "github-repos/coq/VladYagl-C-library-verification/C-library-verification-9d28d1edaf8f3e6e23d60825f53a9893c07ee5ef/memset.c.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2995638701961429}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.ZArith.BinInt.\nRequire Import Coq.Lists.SetoidList.\n\nRequire Import Aniceto.Graphs.Graph.\nRequire Import Aniceto.Pair.\nRequire Import Aniceto.List.\n\nRequire Import HJ.Phasers.Lang.\nRequire Import HJ.Phasers.TransDiff.\nRequire Import HJ.Phasers.PhaseDiff.\nRequire Import HJ.Phasers.Typesystem.\nRequire Import HJ.Vars.\nRequire Import HJ.Tid.\n\nSection SR.\n\n\nDefinition tid_eq_sig x y := if TID.eq_dec x y then 1%Z else 0%Z.\n\nDefinition wait_delta t e := ((tid_eq_sig (snd e) t) - (tid_eq_sig (fst e) t)) % Z.\n\nLemma wait_delta_refl:\n  forall t t',\n  wait_delta t (t', t') = 0%Z.\nProof.\n  intros.\n  unfold wait_delta, tid_eq_sig.\n  simpl.\n  destruct (TID.eq_dec t' t); intuition.\nQed.\n\nLemma wait_delta_left:\n  forall t t',\n  t <> t' ->\n  wait_delta t (t, t') = (- 1)%Z.\nProof.\n  intros.\n  unfold wait_delta, tid_eq_sig.\n  simpl.\n  destruct (TID.eq_dec t' t), (TID.eq_dec t t);\n  rewrite tid_eq_rw in *; subst; intuition.\nQed.\n\nLemma wait_delta_right:\n  forall t t',\n  t <> t' ->\n  wait_delta t (t', t) = 1%Z.\nProof.\n  intros.\n  unfold wait_delta, tid_eq_sig.\n  simpl.\n  destruct (TID.eq_dec t' t), (TID.eq_dec t t);\n  rewrite tid_eq_rw in *; subst; intuition.\nQed.\n\nLemma wait_delta_neq:\n  forall t t1 t2,\n  t <> t1 ->\n  t <> t2 ->\n  wait_delta t (t1, t2) = 0%Z.\nProof.\n  intros.\n  unfold wait_delta, tid_eq_sig.\n  simpl.\n  destruct (TID.eq_dec t1 t), (TID.eq_dec t2 t);\n  rewrite tid_eq_rw in *; subst; intuition.\nQed.\n\nLemma wait_phase_wait:\n  forall v,\n  wait_phase (Taskview.wait v) = S (wait_phase v).\nProof.\n  intros.\n  unfold wait.\n  simpl.\n  intuition.\nQed.\n\nLemma Z_add_to_succ:\n  forall p,\n  Pos.add p xH = Pos.succ p.\nProof.\n  intros.\n  destruct p; repeat auto.\nQed.\n\nLemma Z_of_nat_succ:\n  forall (n:nat),\n  Z.of_nat (S n) = ((Z.of_nat n) + 1) % Z.\nProof.\n intros.\n unfold Z.of_nat.\n destruct n.\n - auto.\n - simpl.\n   rewrite Z_add_to_succ.\n   trivial.\nQed.\n\nLemma ph_diff_add_wait:\n  forall t t1 t2 z v ph,\n  ph_diff (Map_TID.add t (Taskview.wait v) ph) (t1, t2) z ->\n  Map_TID.MapsTo t v ph ->\n  ph_diff ph (t1, t2) (z + wait_delta t (t1, t2)).\nProof.\n  intros.\n    inversion H; subst; clear H.\n    rewrite Map_TID_Facts.add_mapsto_iff in *.\n    destruct H3 as [(?,?)|(?,?)].\n    + destruct H5 as [(?,?)|(?,?)].\n      * subst.\n        subst.\n        rewrite wait_delta_refl.\n        remember (Z.of_nat (wait_phase (Taskview.wait v))) as z.\n        assert (Heq: ((z - z + 0 = 0) %Z)). {\n          intuition.\n        }\n        rewrite Heq.\n        eauto using Map_TID_Extra.mapsto_to_in, ph_diff_refl.\n      * subst.\n        rewrite wait_delta_left; auto.\n        rewrite wait_phase_wait.\n        rewrite Z_of_nat_succ.\n        assert (Heq:\n          (Z.of_nat (wait_phase v) + 1 - Z.of_nat (wait_phase v2) + -1 =\n          (Z.of_nat (wait_phase v) - Z.of_nat (wait_phase v2))) % Z). {\n          intuition.\n        }\n        rewrite Heq.\n        auto using ph_diff_def.\n    + destruct H5 as [(?,?)|(?,?)].\n      * subst.\n        rewrite wait_delta_right; auto.\n        rewrite wait_phase_wait.\n        rewrite Z_of_nat_succ.\n        assert (Heq: (\n          (Z.of_nat (wait_phase v1) - (Z.of_nat (wait_phase v) + 1) + 1) =\n          (Z.of_nat (wait_phase v1) - (Z.of_nat (wait_phase v)))) % Z). {\n          intuition.\n        }\n        rewrite Heq.\n        auto using ph_diff_def.\n      * rewrite wait_delta_neq; repeat auto.\n        assert (Heq: (\n          (Z.of_nat (wait_phase v1) - Z.of_nat (wait_phase v2) + 0) =\n          (Z.of_nat (wait_phase v1) - Z.of_nat (wait_phase v2))) % Z). {\n          intuition.\n        }\n        rewrite Heq; auto using ph_diff.\nQed.\n\nLemma in_neq:\n  forall t t1 ph,\n  ~ Map_TID.In (elt:=taskview) t ph ->\n  Map_TID.In (elt:=taskview) t1 ph ->\n  t <> t1.\nProof.\n  intros.\n  destruct (TID.eq_dec t t1); repeat auto.\n  subst.\n  contradiction.\nQed.\n\nLemma ph_wait_in:\n  forall t t' ph,\n  Map_TID.In t (wait t' ph) ->\n  Map_TID.In t ph.\nProof.\n  intros.\n  apply Map_TID_Extra.in_to_mapsto in H.\n  destruct H as (v, mt).\n  unfold wait, Phaser.update in *.\n  remember (Map_TID.find _ _).\n  symmetry in Heqo.\n  destruct o as [v'|].\n  - apply Map_TID_Facts.add_mapsto_iff in mt.\n    rewrite <- Map_TID_Facts.find_mapsto_iff in Heqo.\n    destruct mt.\n    + destruct H.\n      subst.\n      eauto using Map_TID_Extra.mapsto_to_in.\n    + destruct H; eauto using Map_TID_Extra.mapsto_to_in.\n  - eauto using Map_TID_Extra.mapsto_to_in.\nQed.\n\nLemma ph_diff_apply_wait:\n  forall t t1 t2 z ph,\n  ph_diff (wait t ph) (t1, t2) z ->\n  ph_diff ph (t1, t2) (z + wait_delta t (t1, t2)).\nProof.\n  intros.\n  remember (Map_TID.find t ph).\n  symmetry in Heqo.\n  destruct o as [v|].\n  - apply Map_TID_Facts.find_mapsto_iff in Heqo.\n    assert (R:=Heqo).\n    apply wait_rw in R; rewrite R in *.\n    eauto using ph_diff_add_wait.\n - unfold wait, Phaser.update in *.\n   rewrite Heqo in *.\n   rewrite <- Map_TID_Facts.not_find_in_iff in Heqo.\n   assert (t <> t1). {\n     apply ph_diff_inv_left in H.\n     intuition; subst.\n     contradiction.\n   }\n   assert (t <> t2). {\n     apply ph_diff_inv_right in H.\n     intuition; subst.\n     contradiction.\n   }\n   rewrite wait_delta_neq; repeat auto.\n   assert (Heq: ((z + 0 = z) % Z)); intuition.\n   rewrite Heq.\n   assumption.\nQed.\n\nLemma pm_diff_wait_all:\n  forall t e z pm,\n  pm_diff (wait_all t pm) e z ->\n  pm_diff pm e (z + wait_delta t e).\nProof.\n  intros.\n  destruct e as (t1, t2).\n  inversion H; subst; clear H.\n  unfold foreach in *.\n  apply Map_PHID_Facts.mapi_inv in H0.\n  destruct H0 as (ph', (p', (?, (?, ?)))).\n  subst.\n  rename ph' into ph.\n  eauto using ph_diff_apply_wait, pm_diff_def.\nQed.\n\nLemma walk2_wait_all:\n  forall t pm t1 t2 w,\n  Walk2 (HasDiff (pm_diff (wait_all t pm))) t1 t2 w ->\n  Walk2 (HasDiff (pm_diff pm)) t1 t2 w.\nProof.\n  intros.\n  apply walk2_impl with (E:=HasDiff (pm_diff (wait_all t pm))); repeat auto.\n  intros.\n  unfold HasDiff in *.\n  destruct e as (ta, tb).\n  destruct H0 as (z, ?).\n  eauto using pm_diff_wait_all.\nQed.\n\nLemma pm_diff_mapi_sig:\n  forall t t1 t2 pm z,\n  pm_diff (wait_all t pm) (t1, t2) z ->\n  pm_diff pm (t1, t2) (z - (tid_eq_sig t1 t) + (tid_eq_sig t2 t)).\nProof.\n  intros.\n  assert (Heq: ((z - tid_eq_sig t1 t + tid_eq_sig t2 t) = (z + wait_delta t (t1, t2))) %Z). {\n    unfold wait_delta.\n    simpl.\n    intuition.\n  }\n  rewrite Heq.\n  eauto using pm_diff_wait_all.\nQed.\n\nLemma diff_sum_wait_all:\n  forall w t t1 tn pm z,\n  DiffSum (pm_diff (wait_all t pm)) w z ->\n  StartsWith w t1 ->\n  EndsWith w tn ->\n  DiffSum (pm_diff pm) w (z - (tid_eq_sig t1 t) + (tid_eq_sig tn t)).\nProof.\n  intros w.\n  induction w.\n  { (* absurd case *)\n    intros.\n    inversion H; subst.\n    apply ends_with_nil_inv in H1.\n    inversion H1.\n  }\n  intros.\n  destruct a as (t1', t2).\n  assert (t1' = t1). { eauto using starts_with_eq. }\n  destruct w.\n  - subst.\n    inversion H.\n    subst.\n    assert (t2 = tn). {\n      eauto using ends_with_eq.\n    }\n    subst.\n    apply pm_diff_mapi_sig in H5.\n    auto using diff_sum_pair.\n  - subst.\n    destruct p as (t2', t3).\n    inversion H; subst; clear H.\n    rename t2' into t2.\n    assert (StartsWith ((t2, t3) :: w) t2). {\n      eauto using starts_with_def.\n    }\n    apply ends_with_inv in H1.\n    assert ( DiffSum (pm_diff pm) ((t2, t3) :: w) (s - tid_eq_sig t2 t + tid_eq_sig tn t)). {\n      apply IHw; repeat auto.\n    }\n    apply pm_diff_mapi_sig in H9. (* invert diff_mapi *)\n    simpl in *.\n    assert (Heq: ((z0 + s - tid_eq_sig t1 t + tid_eq_sig tn t) =\n          (z0 - tid_eq_sig t1 t + tid_eq_sig t2 t) +\n          (s - tid_eq_sig t2 t + tid_eq_sig tn t)) % Z). { intuition. }\n    rewrite Heq.\n    auto using diff_sum_cons.\nQed.\n\nLemma transdiff_wait_all:\n  forall t pm t1 t2 z,\n  TransDiff (pm_diff (wait_all t pm)) t1 t2 z ->\n  TransDiff (pm_diff pm) t1 t2 (z - (tid_eq_sig t1 t) + (tid_eq_sig t2 t)).\nProof.\n  intros.\n  inversion H; subst; clear H.\n  apply walk2_wait_all in H1.\n  inversion H1; subst.\n  apply diff_sum_wait_all with (t1:=t1) (tn:=t2) in H0; repeat auto.\n  eauto using trans_diff_def.\nQed.\n\nLemma sr_wait_all:\n  forall pm t,\n  Valid pm ->\n  Valid (wait_all t pm).\nProof.\n  unfold Valid in *.\n  unfold TransDiffFun in *.\n  intros.\n  apply transdiff_wait_all in H0.\n  apply transdiff_wait_all in H1.\n  assert (Hx := H _ _ _ _ H0 H1).\n  intuition.\nQed.\n\nSection PreservesDiff.\n  Variable f : phasermap -> phasermap.\n(*\n  Variable preserves_ph_diff:\n    forall p ph pm z t1 t2,\n    ph_diff ph t1 t2 z ->\n    Map_PHID.MapsTo p ph (f pm) ->\n    exists ph', Map_PHID.MapsTo p ph' pm /\\ ph_diff ph' t1 t2 z.\n*)\n(*\n  Let preserves_pm_diff:\n    forall t1 t2 z pm,\n    pm_diff (f pm) t1 t2 z ->\n    pm_diff pm t1 t2 z.\n  Proof.\n    intros.\n    inversion H; subst; clear H.\n    apply preserves_ph_diff with (z:=z) (t1:=t1) (t2:=t2) in H0; auto.\n    destruct H0 as (ph', (mt, d)).\n    eauto using pm_diff_def.\n  Qed.\n*)\n  Variable preserves_diff:\n    forall e z pm,\n    pm_diff (f pm) e z ->\n    pm_diff pm e z.\n\n  Lemma preserves_walk2:\n    forall pm t1 t2 w,\n    Walk2 (HasDiff (pm_diff (f pm))) t1 t2 w ->\n    Walk2 (HasDiff (pm_diff pm)) t1 t2 w.\n  Proof.\n    intros.\n    apply walk2_impl with (E:=HasDiff (pm_diff (f pm))); repeat auto.\n    intros.\n    unfold HasDiff in *.\n    destruct e as (ta, tb).\n    destruct H0 as (z, ?).\n    eauto using preserves_diff.\n  Qed.\n\n  Let preserves_diff_sum:\n    forall w t1 tn pm z,\n    DiffSum (pm_diff (f pm)) w z ->\n    StartsWith w t1 ->\n    EndsWith w tn ->\n    DiffSum (pm_diff pm) w z.\n  Proof.\n    intros w.\n    induction w.\n    { (* absurd case *)\n      intros.\n      inversion H; subst.\n      apply ends_with_nil_inv in H1.\n      inversion H1.\n    }\n    intros.\n    destruct a as (t1', t2).\n    assert (t1' = t1) by eauto using starts_with_eq.\n    destruct w; subst.\n    - inversion H.\n      assert (t2 = tn) by eauto using ends_with_eq.\n      subst.\n      auto using preserves_diff, diff_sum_pair.\n    - destruct p as (t2', t3).\n      inversion H; subst; clear H.\n      rename t2' into t2.\n      assert (StartsWith ((t2, t3) :: w) t2). {\n        eauto using starts_with_def.\n      }\n      apply ends_with_inv in H1.\n      assert ( DiffSum (pm_diff pm) ((t2, t3) :: w) s) by eauto.\n      apply preserves_diff in H9. (* invert diff_mapi *)\n      simpl in *.\n      auto using diff_sum_cons.\n  Qed.\n\n  Let preserves_transdiff:\n    forall pm t1 t2 z,\n    TransDiff (pm_diff (f pm)) t1 t2 z ->\n    TransDiff (pm_diff pm) t1 t2 z.\n  Proof.\n    intros.\n    inversion H; subst; clear H.\n    apply preserves_walk2 in H1.\n    inversion H1; subst.\n    eauto using trans_diff_def, preserves_diff_sum.\n  Qed.\n\n  Lemma preserves_diff_sr:\n    forall pm,\n    Valid pm ->\n    Valid (f pm).\n  Proof.\n    unfold Valid in *.\n    unfold TransDiffFun in *.\n    intros.\n    eauto using preserves_transdiff.\n  Qed.\n\n\nEnd PreservesDiff.\n\nSection Drop.\n  Let ph_diff_apply_drop:\n    forall t e z ph,\n    ph_diff (drop t ph) e z ->\n    ph_diff ph e z.\n  Proof.\n    intros.\n    inversion H; subst.\n    apply drop_mapsto_inv in H0.\n    apply drop_mapsto_inv in H1.\n    destruct H0; destruct H1.\n    auto using ph_diff_def.\n  Qed.\n\n  Let ph_diff_drop_all:\n    forall t e z pm,\n    pm_diff (drop_all t pm) e z ->\n    pm_diff pm e z.\n  Proof.\n    intros.\n    unfold drop_all, foreach in *.\n    inversion H; subst; clear H.\n    inversion H1; subst; clear H1.\n    apply Map_PHID_Facts.mapi_inv in H0.\n    destruct H0 as (ph', (p', (?, (?, ?)))).\n    subst.\n    eauto using pm_diff_def, ph_diff_def.\n  Qed.\n\n  Lemma sr_drop_all:\n    forall pm t,\n    Valid pm ->\n    Valid (drop_all t pm).\n  Proof.\n    intros.\n    eauto using preserves_diff_sr, ph_diff_drop_all.\n  Qed.\n\n  Let pm_diff_preserves_drop:\n    forall p t pm e z,\n    pm_diff (ph_drop p t pm) e z ->\n    pm_diff pm e z.\n  Proof.\n    intros.\n    inversion H; subst; clear H.\n    unfold ph_drop, update in *.\n    remember (Map_PHID.find  _ _).\n    symmetry in Heqo.\n    destruct o as [ph'|].\n    - rewrite <- Map_PHID_Facts.find_mapsto_iff in Heqo.\n      apply Map_PHID_Facts.add_mapsto_iff in H0.\n      destruct H0.\n      + destruct H.\n        subst.\n        eauto using pm_diff_def, ph_diff_def.\n      + destruct H.\n        eauto using pm_diff_def, ph_diff_def.\n    - eauto using pm_diff_def, ph_diff_def.\n  Qed.\n\n  Lemma sr_ph_drop:\n    forall pm p t,\n    Valid pm ->\n    Valid (ph_drop p t pm).\n  Proof.\n    intros.\n    eauto using preserves_diff_sr.\n  Qed.\n\nEnd Drop.\n\nSection Signal.\n  Let ph_diff_signal:\n    forall t e z ph,\n    ph_diff (signal t ph) e z ->\n    ph_diff ph e z.\n  Proof.\n    intros.\n    inversion H; subst.\n    apply signal_mapsto_inv in H0.\n    apply signal_mapsto_inv in H1.\n    destruct H0.\n    - destruct H1.\n      + destruct a as (?, (?,(?,?))).\n        destruct a0 as (?, (?,(?,?))).\n        subst.\n        repeat rewrite signal_preserves_wait_phase in *.\n        auto using ph_diff_def.\n      + destruct a as (?, (?,(?,?))).\n        destruct a0 as (?, ?).\n        subst.\n        repeat rewrite signal_preserves_wait_phase in *.\n        auto using ph_diff_def.\n    - destruct H1.\n      + destruct a0 as (?, (?,(?,?))).\n        destruct a as (?, ?).\n        subst.\n        repeat rewrite signal_preserves_wait_phase in *.\n        auto using ph_diff_def.\n      + destruct a0 as (?, ?).\n        destruct a as (?, ?).\n        subst.\n        repeat rewrite signal_preserves_wait_phase in *.\n        auto using ph_diff_def.\n  Qed.\n\n  Let ph_diff_try_signal:\n    forall t e z ph,\n    ph_diff (try_signal t ph) e z ->\n    ph_diff ph e z.\n  Proof.\n    intros.\n    inversion H; subst.\n    apply try_signal_mapsto_inv in H0.\n    apply try_signal_mapsto_inv in H1.\n    destruct H0.\n    - destruct H1.\n      + destruct a as (?, (?,(?,?))).\n        destruct a0 as (?, (?,(?,?))).\n        subst.\n        repeat rewrite try_signal_preserves_wait_phase in *.\n        auto using ph_diff_def.\n      + destruct a as (?, (?,(?,?))).\n        destruct a0 as (?, ?).\n        subst.\n        repeat rewrite try_signal_preserves_wait_phase in *.\n        auto using ph_diff_def.\n    - destruct H1.\n      + destruct a0 as (?, (?,(?,?))).\n        destruct a as (?, ?).\n        subst.\n        repeat rewrite try_signal_preserves_wait_phase in *.\n        auto using ph_diff_def.\n      + destruct a0 as (?, ?).\n        destruct a as (?, ?).\n        subst.\n        repeat rewrite try_signal_preserves_wait_phase in *.\n        auto using ph_diff_def.\n  Qed.\n\n  Let pm_diff_signal_all:\n    forall t e z pm,\n    pm_diff (signal_all t pm) e z ->\n    pm_diff pm e z.\n  Proof.\n    intros.\n    unfold signal_all, foreach in *.\n    inversion H; subst; clear H.\n    apply Map_PHID_Facts.mapi_inv in H0.\n    destruct H0 as (ph', (p', (?, (?, ?)))).\n    subst.\n    eauto using pm_diff_def, ph_diff_def, ph_diff_try_signal.\n  Qed.\n\n  Lemma sr_signal_all:\n    forall pm t,\n    Valid pm ->\n    Valid (signal_all t pm).\n  Proof.\n    eauto using preserves_diff_sr, pm_diff_signal_all.\n  Qed.\n\n  Let pm_diff_ph_signal:\n    forall p' t e z pm,\n    pm_diff (ph_signal p' t pm) e z ->\n    pm_diff pm e z.\n  Proof.\n    intros.\n    inversion H; subst; clear H.\n    unfold ph_signal, update in *.\n    remember (Map_PHID.find  _ _).\n    symmetry in Heqo.\n    destruct o as [ph'|].\n    - rewrite <- Map_PHID_Facts.find_mapsto_iff in Heqo.\n      apply Map_PHID_Facts.add_mapsto_iff in H0.\n      destruct H0.\n      + destruct H.\n        subst.\n        eauto using pm_diff_def, ph_diff_def.\n      + destruct H.\n        eauto using pm_diff_def, ph_diff_def.\n    - eauto using pm_diff_def, ph_diff_def.\n  Qed.\n\n  Lemma sr_ph_signal:\n    forall pm p t,\n    Valid pm ->\n    Valid (ph_signal p t pm).\n  Proof.\n    intros.\n    eauto using preserves_diff_sr, pm_diff_ph_signal.\n  Qed.\n\nEnd Signal.\n\n\n  Let DiffSumEx E (m:phasermap) t1 t2 w z :=\n    DiffSum (pm_diff m) w z /\\ Walk2 E t1 t2 w.\n\n  Let diff_sum_ex_cons:\n    forall (E:(tid*tid)->Prop) m t1 t2 tn l s z,\n    E (t1, t2) ->\n    pm_diff m (t1, t2) z ->\n    DiffSumEx E m t2 tn l s ->\n    DiffSumEx E m t1 tn ((t1, t2) :: l) (z + s).\n  Proof.\n    intros.\n    unfold DiffSumEx in *.\n    destruct H1.\n    split.\n    - destruct l. {\n        inversion H2.\n        subst.\n        apply ends_with_nil_inv in H4.\n        inversion H4.\n      }\n      destruct p.\n      inversion H2.\n      subst.\n      assert (t = t2). {\n        eauto using starts_with_eq.\n      }\n      subst.\n      auto using diff_sum_cons.\n    - auto using walk2_cons.\n  Qed.\n\nSection PhNew.\n  (**\n    The gist of the proof is on taking a diff sum on [ph_new p t pm]\n    and creating a new diff sum with the same result on [pm].\n    The difficulty in doing this translation is that the path in the\n    diff sum mentions phaser [p], then [p] is not in [pm]. But\n    we also know that if [p] is mentioned in the original diff sum,\n    then it can only be a self loop where we are comparing [t] with\n    itself via [p] and the diff is zero, in which case we can discard\n    any edge (t, t) and obtain a diff sum on [pm] with the same result. *)\n\n\n  Let pm_diff_ph_new:\n    forall p t t1 t2 z pm,\n    (t1 <> t \\/ t2 <> t) ->\n    pm_diff (ph_new p t pm) (t1, t2) z ->\n    pm_diff pm (t1, t2) z.\n  Proof.\n    intros.\n    unfold ph_new in *.\n    inversion H0; subst.\n    apply Map_PHID_Facts.add_mapsto_iff in H1.\n    destruct H1.\n    - destruct H1.\n      subst.\n      inversion H2; subst; clear H2.\n      apply make_mapsto in H4.\n      apply make_mapsto in H6.\n      destruct H4, H6.\n      repeat subst.\n      destruct H;\n      contradiction H; trivial.\n    - destruct H1.\n      eauto using pm_diff_def.\n  Qed.\n\n  (* Removes all self links *)\n\n  Variable t:tid.\n\n  Let skip_self p := if pair_eq_dec TID.eq_dec (t,t) p then false else true.\n\n  Let skip_self_inv_false:\n    forall x y,\n    skip_self (x, y) = false ->\n    x = t /\\ y = t.\n  Proof.\n    unfold skip_self.\n    intros.\n    remember (pair_eq_dec _ _ _).\n    destruct s.\n    - inversion e; auto.\n    - inversion H.\n  Qed.\n\n  Let skip_self_inv_true:\n    forall x y,\n    skip_self (x, y) = true ->\n    x <> t \\/ y <> t.\n  Proof.\n    unfold skip_self.\n    intros.\n    remember (pair_eq_dec _ _ _).\n    destruct s.\n    - inversion H.\n    - destruct (TID.eq_dec x t). {\n        subst.\n        right.\n        destruct (TID.eq_dec y t). {\n          subst.\n          contradiction n.\n          trivial.\n        }\n        auto.\n      }\n      intuition.\n  Qed.\n\n  Let linked_filter_self:\n    forall a w,\n    Linked a w ->\n    Connected w ->\n    Linked a (filter skip_self w).\n  Proof.\n    intros.\n    induction w as [|e].\n    - auto.\n    - destruct a as (x, y).\n      destruct e as (y', z).\n      assert (Hx:= H).\n      apply linked_inv in H.\n      subst.\n      simpl.\n      remember (skip_self (y, z)).\n      symmetry in Heqb.\n      destruct b; auto using linked_eq.\n      apply skip_self_inv_false in Heqb.\n      destruct Heqb.\n      subst.\n      inversion H0; subst.\n      assert (Linked (x, t) w) by auto.\n      auto.\n  Qed.\n\n  Let walk_filter_self:\n    forall E w,\n    Walk E w ->\n    Walk E (filter skip_self w).\n  Proof.\n    intros.\n    induction w.\n    - simpl in *.\n      auto.\n    - simpl.\n      remember (skip_self a).\n      symmetry in Heqb.\n      destruct b.\n      + inversion H; subst.\n        assert (Hx := H2).\n        apply walk_inv in H2; destruct H2.\n        auto using walk_cons.\n      + destruct a as (x,y).\n        apply skip_self_inv_false in Heqb.\n        destruct Heqb.\n        subst.\n        inversion H; auto.\n  Qed.\n\n  Let filter_skip_inv_cons_eq_nil:\n    forall w p,\n    filter skip_self (p :: w) = nil ->\n    p = (t, t).\n  Proof.\n    intros.\n    simpl in H.\n    remember (skip_self p).\n    symmetry in Heqb.\n    destruct b. {\n      inversion H.\n    }\n    destruct p.\n    apply skip_self_inv_false in Heqb.\n    destruct Heqb.\n    subst.\n    trivial.\n  Qed.\n\n  Let filter_skip_inv_ends_with:\n    forall w p,\n    filter skip_self (p :: w) = nil ->\n    EndsWith (p::w) t.\n  Proof.\n    induction w; intros.\n    - apply filter_skip_inv_cons_eq_nil in H.\n      subst.\n      auto using ends_with_edge.\n    - apply ends_with_cons.\n      apply IHw.\n      simpl in *.\n      destruct (skip_self p).\n      + inversion H.\n      + auto.\n  Qed.\n\n  Let filter_skip_ends_with:\n    forall E w x,\n    Walk E w ->\n    EndsWith w x ->\n    filter skip_self w = nil \\/\n    EndsWith (filter skip_self w) x.\n  Proof.\n    induction w; intros. {\n      apply ends_with_nil_inv in H0.\n      inversion H0.\n    }\n    simpl.\n    remember (skip_self a).\n    symmetry in Heqb.\n    destruct w. {\n      destruct a as (y,x').\n      apply ends_with_inv_cons_nil in H0.\n      destruct b. {\n        right.\n        subst.\n        simpl.\n        auto using ends_with_edge.\n      }\n      apply skip_self_inv_false in Heqb.\n      destruct Heqb.\n      repeat subst.\n      intuition.\n    }\n    assert (ew : EndsWith (p :: w) x) by eauto using ends_with_inv.\n    assert (W:  Walk E (p :: w)) by (inversion H; auto).\n    apply IHw in ew; auto.\n    destruct b. {\n      right.\n      destruct ew as [ew|ew]. {\n        rewrite ew.\n        assert (Hx := ew).\n        apply filter_skip_inv_cons_eq_nil in ew.\n        apply filter_skip_inv_ends_with in Hx.\n        subst.\n        inversion H.\n        subst.\n        destruct a as (a, t').\n        apply linked_inv in H5.\n        rewrite <- H5 in *.\n        apply ends_with_inv in H0.\n        assert (x = t). {\n          eauto using ends_with_fun.\n        }\n        rewrite H1.\n        auto using ends_with_edge.\n      }\n      auto using ends_with_cons.\n    }\n    intuition.\n  Qed.\n\n  Let ends_with_filter_skip:\n    forall E t1 t2 tn l,\n    Walk E ((t1, t2) :: l) ->\n    EndsWith ((t1, t2) :: l) tn ->\n    filter skip_self l = nil ->\n    EndsWith ((t1, t2) :: nil) tn.\n  Proof.\n    intros.\n    destruct l. {\n      assumption.\n    }\n    apply ends_with_inv in H0.\n    assert (tn = t). {\n      apply filter_skip_inv_ends_with in H1.\n      eauto using ends_with_fun.\n    }\n    subst.\n    assert (t2 = t). {\n      assert (R: p = (t, t)). {\n        assert (List.In p (p :: l)) by auto using in_eq.\n        assert (R: ~ List.In p (filter skip_self (p :: l))). {\n          rewrite H1.\n          intuition.\n        }\n        apply filter_notin_to_false in R; auto.\n        destruct p.\n        apply skip_self_inv_false in R.\n        destruct R.\n        subst; auto.\n      }\n      subst.\n      inversion H.\n      subst.\n      eauto using linked_inv.\n    }\n    subst; auto using ends_with_edge.\n  Qed.\n\n  Let filter_skip_walk2_aux_1:\n    forall p w E t1 t2 tn,\n    filter skip_self (p :: w) = nil ->\n    Walk2 E t2 tn (p :: w) ->\n    EndsWith ((t1,t2) :: filter skip_self (p :: w)) tn.\n  Proof.\n    intros.\n    assert (Hx := H0).\n    inversion Hx.\n            subst.\n            assert (tn = t). {\n              eauto using filter_skip_inv_ends_with, ends_with_fun.\n            }\n            apply walk2_inv_cons in Hx.\n            destruct Hx as (?, (?,?)).\n            rewrite H.\n            subst.\n            assert (R: t2 = t). {\n              assert (Hy : List.In (t2, x) ((t2,x) :: w)) by auto using in_eq.\n              apply filter_notin_to_false with (f:=skip_self) in Hy.\n              - apply skip_self_inv_false in Hy.\n                destruct Hy; auto.\n              - rewrite H.\n                intuition.\n            }\n            subst.\n            auto using ends_with_edge.\n  Qed.\n\n  Let filter_skip_walk2:\n    forall E tn w t1,\n    Walk2 E t1 tn w ->\n    filter skip_self w = nil \\/\n    Walk2 E t1 tn (filter skip_self w).\n  Proof.\n    induction w; intros. {\n      intuition.\n    }\n    simpl in *.\n    remember (skip_self a).\n    symmetry in Heqb.\n    destruct w.\n    - simpl in *.\n      destruct b. {\n        auto.\n      }\n      intuition.\n    - apply walk2_inv in H.\n      destruct H as (t2,(?,(?,?))).\n      destruct b. {\n        right.\n        assert (Hx:=H1).\n        apply IHw in H1.\n        destruct H1.\n        - apply walk2_def.\n          + subst; auto using starts_with_def.\n          + rewrite H in *.\n            apply filter_skip_walk2_aux_1 with (E:=E) (t1:=t1) (t2:=t2) (tn:=tn) in H1; auto.\n          + rewrite H1.\n            subst.\n            auto using edge_to_walk.\n        - subst.\n          auto using walk2_cons.\n      }\n      destruct a as (x, y).\n      apply skip_self_inv_false in Heqb.\n      inversion H; subst; clear H.\n      destruct Heqb; subst.\n      subst.\n      apply IHw in H1.\n      destruct H1; auto.\n  Qed.\n\n  Let diff_sum_2_sieve:\n    forall E m tn w t1 z,\n    DiffSumEx E m t1 tn w z ->\n    ((filter skip_self w = nil /\\ z = 0%Z)\n    \\/ (filter skip_self w <> nil /\\ DiffSumEx E m t1 tn (filter skip_self w) z)).\n  Proof.\n    induction w; intros. {\n      destruct H as (?, ?).\n      inversion H.\n      left.\n      intuition.\n    }\n    destruct H as (?, ?).\n    destruct a as (t1', t2).\n    inversion H0; subst.\n    assert (t1' = t1) by\n    eauto using starts_with_eq; subst.\n    simpl.\n    remember (skip_self (t1, t2)).\n    symmetry in Heqb.\n    destruct b. {\n      right.\n      inversion H; subst.\n      - simpl.\n        split; try split; auto with *.\n      - rename w0 into w.\n        assert (D: DiffSumEx E m t2 tn ((t2,t4)::w) s). {\n          unfold DiffSumEx.\n          apply walk2_inv_2 in H0.\n          intuition.\n        }\n        apply IHw in D.\n        split; auto with *.\n        destruct D as [(R1,?)|?]. {\n          assert (R2: (z0 + s = z0)%Z) by\n          intuition.\n          rewrite R1.\n          rewrite R2.\n          split.\n          - inversion H3.\n            auto using diff_sum_pair.\n          - apply filter_skip_walk2 in H0.\n            remember ((t2,t4)::_) as l.\n            destruct H0. {\n              assert (R3: (t1,t2)::filter skip_self l = filter skip_self ((t1, t2) :: l)). {\n              simpl.\n              rewrite Heqb.\n              trivial.\n            }\n            rewrite R1 in R3.\n            rewrite <- R3 in H0.\n            inversion H0.\n          }\n          rewrite <- R1.\n          simpl in H0.\n          rewrite Heqb in *.\n          assumption.\n        }\n        destruct H4.\n        apply diff_sum_ex_cons.\n        + inversion H3; auto.\n        + inversion H; auto.\n        + auto.\n      }\n      apply skip_self_inv_false in Heqb.\n      destruct Heqb; subst.\n      destruct w. {\n        left.\n        inversion H.\n        subst.\n        simpl in *.\n        apply pm_diff_refl_inv in H7.\n        intuition.\n      }\n      destruct p as (t', t1).\n      assert (t' = t). {\n        inversion H3.\n        subst.\n        eauto using linked_inv.\n      }\n      subst.\n      assert (DiffSumEx E m t tn ((t,t1)::w) z). {\n        apply walk2_inv_2 in H0.\n        split.\n        - inversion H; subst.\n          assert (z0 = 0%Z) by eauto using pm_diff_refl_inv.\n          subst.\n          inversion H.\n          subst.\n          assert ((0 + s = s)%Z). {\n            intuition.\n          }\n          rewrite H4 in *.\n          rewrite H6.\n          apply pm_diff_refl_inv in H14.\n          subst.\n          assert (R: (0 + s0 = s0)%Z) by intuition.\n          rewrite R.\n          assumption.\n        - assumption.\n      }\n      auto.\n  Qed.\n\n  Let transdiff_diff_sum_ex:\n    forall m tn t1 z,\n    TransDiff (pm_diff m) t1 tn z ->\n    ((t1 = t /\\ tn = t /\\ z = 0%Z)\n    \\/ exists w, w <> nil /\\ DiffSumEx (HasDiff (pm_diff m)) m t1 tn (filter skip_self w) z).\n  Proof.\n    intros.\n    inversion H.\n    subst.\n    assert (DiffSumEx (HasDiff (pm_diff m)) m t1  tn w z). {\n      split; auto.\n    }\n    apply diff_sum_2_sieve in H2.\n    destruct H2.\n    - left.\n      inversion H1.\n      subst.\n      destruct w. {\n        apply ends_with_nil_inv in H4.\n        inversion H4.\n      }\n      destruct p as (t1', ?).\n      assert (t1' = t1). {\n       eauto using starts_with_eq.\n      }\n      subst.\n      destruct H2.\n      assert (t1 = t). {\n        assert (Hx : ~ List.In (t1, t0) (filter skip_self ((t1, t0) :: w))). {\n          rewrite H2.\n          intuition.\n        }\n        apply filter_notin_to_false in Hx.\n        - apply skip_self_inv_false in Hx; destruct Hx; subst; auto.\n        - auto using in_eq.\n      }\n      assert (tn = t). {\n        eauto using ends_with_fun, filter_skip_inv_ends_with.\n      }\n      intuition.\n    - right.\n      destruct H2.\n      exists w.\n      split.\n      + intuition.\n        subst.\n        auto.\n      + auto.\n  Qed.\n\n  Let in_pm_diff:\n    forall p m w e z,\n    List.In e (filter skip_self w) ->\n    pm_diff (ph_new p t m) e z ->\n    pm_diff m e z.\n  Proof.\n    intros.\n    destruct e as (ti, tj).\n    rewrite filter_In in H.\n    destruct H.\n    apply skip_self_inv_true in H1.\n    eauto using pm_diff_ph_new.\n  Qed.\n\n\n  Let has_diff_trans:\n    forall p t1 tn m z w,\n    DiffSumEx (HasDiff (pm_diff (ph_new p t m))) (ph_new p t m) t1 tn (filter skip_self w) z ->\n    DiffSumEx (HasDiff (pm_diff m)) m t1 tn (filter skip_self w) z.\n  Proof.\n    intros.\n    destruct H.\n    split.\n    - eauto using diff_sum_impl_weak.\n    - apply walk2_impl_weak with (E:=(HasDiff (pm_diff (ph_new p t m)))); auto.\n      intros.\n      inversion H2.\n      unfold HasDiff.\n      eauto.\n  Qed.\n\n  Let transdiff_fin:\n    forall p m tn t1 z,\n    TransDiff (pm_diff (ph_new p t m)) t1 tn z ->\n    ((t1 = t /\\ tn = t /\\ z = 0%Z)\n    \\/ TransDiff (pm_diff m) t1 tn z).\n  Proof.\n    intros.\n    apply transdiff_diff_sum_ex in H.\n    destruct H. {\n      intuition.\n    }\n    right.\n    destruct H as (w, (Hn, Hd)).\n    apply has_diff_trans in Hd.\n    inversion Hd.\n    eauto using trans_diff_def.\n  Qed.\n\n  Lemma pm_diff_to_refl_left:\n    forall t1 t2 z pm,\n    pm_diff pm (t1, t2) z ->\n    pm_diff pm (t1, t1) 0%Z.\n  Proof.\n    intros.\n    inversion H.\n    apply ph_diff_inv_left in H1.\n    eauto using pm_diff_refl.\n  Qed.\n\n  Lemma trans_diff_inv_refl:\n    forall t pm z,\n    TransDiff (pm_diff pm) t t z ->\n    TransDiff (pm_diff pm) t t 0%Z.\n  Proof.\n    intros.\n    inversion H.\n    subst.\n    inversion H0; subst; auto.\n    - assert (t1 = t0). {\n        inversion H1; eauto using starts_with_eq.\n      }\n      subst.\n      assert (pm_diff pm (t0, t0) 0%Z). {\n        eauto using pm_diff_to_refl_left.\n      }\n      apply trans_diff_def with ((t0,t0)::nil).\n      auto using diff_sum_pair.\n      apply edge_to_walk2.\n      unfold HasDiff.\n      eauto.\n    - assert (t1 = t0). {\n        inversion H1; eauto using starts_with_eq.\n      }\n      subst.\n      assert (pm_diff pm (t0, t0) 0%Z). {\n        eauto using pm_diff_to_refl_left.\n      }\n      apply trans_diff_def with ((t0,t0)::nil).\n      auto using diff_sum_pair.\n      apply edge_to_walk2.\n      unfold HasDiff.\n      eauto.\n  Qed.\n\n  Lemma sr_ph_new:\n    forall p pm,\n    Valid pm ->\n    Valid (ph_new p t pm).\n  Proof.\n    unfold Valid in *.\n    unfold TransDiffFun in *.\n    intros.\n    apply transdiff_fin in H0.\n    apply transdiff_fin in H1.\n    destruct H0, H1.\n    - intuition.\n    - destruct H0 as (?,(?,?)).\n      subst.\n      eauto using trans_diff_inv_refl.\n    - destruct H1 as (?,(?,?)).\n      subst.\n      eauto using trans_diff_inv_refl.\n    - eauto.\n  Qed.\n\n\nEnd PhNew.\n\nSection Async.\n\n  (**\n    The idea behind the proof of subject reduction for async is that given a\n    phasermap [async ps t m], for any diff-sum ranging from [t1] to task [t2]\n    with path [w] and a sum of [s], you define [sigma] as replacing [t'] by [t]\n    and then create a diff-sum from [sigma t1] to [sigma t2] with a path of\n    [map sigma w] that also has a sum of [s].\n  *)\n\n  Variable t:tid.\n(*\n  Variable p : phid.\n*)\n  Variable pm : phasermap.\n\n  Variable ps : phased.\n\n  Let chg_tid t' := if TID.eq_dec t' (get_new_task ps) then t else t'.\n\n  Let chg_edge (e:tid * tid) := match e with (x,y) => (chg_tid x, chg_tid y) end.\n\n  Variable pre: AsyncPre ps t pm.\n\n  Notation pm' := (async ps t pm).\n\n  Let chg_edge_inv:\n    forall pi ph ti v,\n    Map_PHID.MapsTo pi ph pm' ->\n    Map_TID.MapsTo ti v ph ->\n    (exists ph' v', Map_PHID.MapsTo pi ph' pm /\\ Map_TID.MapsTo t v' ph' /\\ wait_phase v = wait_phase v') \\/\n    (exists ph' v', Map_PHID.MapsTo pi ph' pm /\\ Map_TID.MapsTo ti v' ph' /\\ wait_phase v = wait_phase v').\n  Proof.\n    intros.\n    apply async_mapsto_rw in H.\n    destruct H as (ph', (R, mt)).\n    rewrite R in *; clear R.\n    destruct (async_1_rw ps t pi ph').\n    - destruct e as (r, (i, R)).\n      rewrite R in *; clear R.\n      apply register_inv_mapsto in H0.\n      destruct H0 as [mt2|(?, (v', (mt2, R)))].\n      + right; eauto.\n      + left.\n        subst.\n        exists ph'.\n        exists v'.\n        intuition.\n   - destruct a as (R, Hx).\n     right.\n     rewrite R in *; clear R.\n     eauto.\n  Qed.\n\n  Let chg_tid_impl:\n    forall p ph x v,\n    Map_PHID.MapsTo p ph pm' ->\n    Map_TID.MapsTo x v ph ->\n    exists ph' v',\n    Map_PHID.MapsTo p ph' pm /\\ \n    Map_TID.MapsTo (chg_tid x) v' ph' /\\\n    wait_phase v = wait_phase v'.\n  Proof.\n    intros.\n    destruct (Map_PHID_Extra.in_dec phid_eq_rw p (get_args ps)). {\n      apply Map_PHID_Extra.in_to_mapsto in i.\n      rewrite async_mapsto_rw in H.\n      destruct H as  (ph', (R, mt)).\n      rewrite R in *; clear R.\n      unfold chg_tid.\n      destruct i as (r, ?).\n      destruct (TID.eq_dec x (get_new_task ps)). {\n        subst.\n        assert (Map_TID.In t ph') by eauto using async_pre_to_in_ph.\n        apply async_1_mapsto_eq with (r:=r) in H0; auto.\n        destruct H0 as (v1', (mt1, R1)).\n        subst.\n        eauto.\n      }\n      apply async_1_mapsto_neq in H0; auto; clear n.\n      eauto.\n    }\n    rewrite async_mapsto_rw in H.\n    destruct H as  (ph', (R, mt)).\n    subst.\n    apply async_1_mapsto in H0.\n    destruct H0 as [?|(v',(r,(?,(?,mt'))))]. {\n      unfold chg_tid.\n      destruct (TID.eq_dec x (get_new_task ps)). {\n        subst.\n        inversion pre.\n        contradiction H1.\n        eapply in_def; eauto using Map_TID_Extra.mapsto_to_in.\n      }\n      eauto.\n    }\n    subst.\n    contradiction n.\n    eauto using Map_PHID_Extra.mapsto_to_in.\n  Qed.\n\n  Let chg_edge_ph_impl:\n    forall p ph e z,\n    Map_PHID.MapsTo p ph pm' ->\n    ph_diff ph e z ->\n    exists ph',\n    Map_PHID.MapsTo p ph' pm /\\ ph_diff ph' (chg_edge e) z.\n  Proof.\n    intros.\n    destruct e as (x,y).\n    simpl in *.\n    inversion H0; subst; clear H0.\n    apply chg_tid_impl with (p:=p) in H3; auto.\n    destruct H3 as (ph1, (v1', (mt1, (mt2, R1)))).\n    rewrite R1; clear R1.\n    apply chg_tid_impl with (p:=p) in H5; auto.\n    destruct H5 as (ph2, (v2', (mt3, (mt4, R2)))).\n    rewrite R2; clear R2.\n    assert (ph2 = ph1) by eauto using Map_PHID_Facts.MapsTo_fun; subst.\n    eauto using ph_diff_def.\n  Qed.\n\n  Let chg_edge_impl:\n    forall p ph e z,\n    Map_PHID.MapsTo p ph pm' ->\n    ph_diff ph e z ->\n    pm_diff pm (chg_edge e) z.\n  Proof.\n    intros.\n    destruct e as (x,y).\n    simpl in *.\n    eapply chg_edge_ph_impl in H0; eauto.\n    destruct H0 as (?, (?,?)).\n    eauto using pm_diff_def.\n  Qed.\n\n  Let edge_impl:\n    forall e z,\n    pm_diff pm' e z ->\n    pm_diff pm (chg_edge e) z.\n  Proof.\n    intros.\n    inversion H; clear H.\n    inversion pre; clear pre.\n    eauto.\n  Qed.\n\n  Let walk_chg_edge:\n    forall w,\n    Walk (HasDiff (pm_diff pm')) w ->\n    Walk (HasDiff (pm_diff pm)) (map chg_edge w).\n  Proof.\n    intros.\n    apply walk_map_impl with (E:=(HasDiff (pm_diff pm'))); intros; auto.\n    - destruct H0.\n      unfold HasDiff.\n      exists x.\n      eauto.\n    - destruct w0.\n      + apply linked_nil.\n      + destruct p as (x, y).\n        simpl.\n        destruct a as (a,b).\n        apply linked_inv in H0.\n        simpl in *.\n        subst.\n        apply linked_eq.\n  Qed.\n\n  Let starts_with_chg_edge:\n    forall w x,\n    StartsWith w x ->\n    StartsWith (map chg_edge w) (chg_tid x).\n  Proof.\n    destruct w; intros. {\n      apply starts_with_inv_nil in H.\n      inversion H.\n    }\n    destruct p as (a,b).\n    simpl.\n    apply starts_with_eq in H.\n    subst.\n    auto using starts_with_def.\n  Qed.\n\n  Let ends_with_chg_edge:\n    forall w x,\n    EndsWith w x ->\n    EndsWith (map chg_edge w) (chg_tid x).\n  Proof.\n    induction w; intros. {\n      apply ends_with_nil_inv in H.\n      inversion H.\n    }\n    destruct a as (a,b).\n    destruct w. {\n      simpl.\n      apply ends_with_eq in H; subst.\n      eauto using ends_with_edge.\n    }\n    simpl in *.\n    apply ends_with_inv in H.\n    eauto using ends_with_cons.\n  Qed.\n\n  Let walk2_chg_edge:\n    forall t1 t2 w,\n    Walk2 (HasDiff (pm_diff pm')) t1 t2 w ->\n    Walk2 (HasDiff (pm_diff pm)) (chg_tid t1) (chg_tid t2) (map chg_edge w).\n  Proof.\n    intros.\n    inversion H.\n    subst.\n    eauto using walk2_def.\n  Qed.\n\n  Let diff_sum_chg_edge:\n    forall w z,\n    DiffSum (pm_diff pm') w z ->\n    DiffSum (pm_diff pm) (map chg_edge w) z.\n  Proof.\n    induction w; intros.\n    - simpl.\n      inversion H.\n      subst.\n      auto using diff_sum_nil.\n    - inversion H; subst.\n      + inversion H.\n        subst.\n        simpl.\n        apply edge_impl in H4.\n        simpl in *.\n        auto using diff_sum_pair.\n      + apply edge_impl in H4.\n        simpl in *.\n        auto using diff_sum_cons.\n  Qed.\n\n  Let trans_diff_chg:\n    forall t1 t2 z,\n    TransDiff (pm_diff pm') t1 t2 z ->\n    TransDiff (pm_diff pm) (chg_tid t1) (chg_tid t2) z.\n  Proof.\n    intros.\n    inversion H.\n    subst.\n    eauto using trans_diff_def.\n  Qed.\n\n  Lemma sr_async:\n    Valid pm ->\n    Valid pm'.\n  Proof.\n    intros.\n    unfold Valid in *.\n    unfold TransDiffFun in *.\n    intros.\n    eauto.\n  Qed.\n\nEnd Async.\n\n  Lemma subject_reduction:\n    forall m t o m',\n    Valid m ->\n    Reduces m t o m' ->\n    Valid m'.\n  Proof.\n    intros.\n    destruct H0.\n    destruct o; simpl in *.\n    - auto using sr_ph_new.\n    - auto using sr_ph_signal.\n    - auto using sr_ph_drop.\n    - auto using sr_signal_all.\n    - auto using sr_wait_all.\n    - auto using sr_drop_all.\n    - auto using sr_async.\n  Qed.\n(*\n  Lemma diff_sum_absurd_make:\n    forall w z,\n    ~ DiffSum (pm_diff make) w z.\n  Proof.\n    unfold not,make; intros.\n    inversion H; subst; clear H.\n    - \n  Qed.\n*)\n\n  Lemma pm_diff_absurd_empty:\n    forall v1 v2 z,\n    ~ pm_diff make (v1, v2) z.\n  Proof.\n    unfold not, make; intros.\n    inversion H; subst; clear H.\n    apply Map_PHID_Facts.empty_mapsto_iff in H0.\n    assumption.\n  Qed.\n\n  Lemma trans_diff_absurd_empty:\n    forall t1 t2 z,\n    ~ TransDiff (pm_diff make) t1 t2 z.\n  Proof.\n    unfold not; intros.\n    inversion H; subst; clear H.\n    assert (exists e, List.In e w). {\n      destruct w. {\n        apply walk2_nil_inv in H1.\n        contradiction.\n      }\n      eauto using in_eq.\n    }\n    destruct H as ((v1,v2), Hi).\n    eapply walk2_to_edge in Hi; eauto.\n    inversion Hi; subst; clear Hi.\n    apply pm_diff_absurd_empty in H.\n    assumption.\n  Qed.\n\n  Lemma valid_make:\n    Valid make.\n  Proof.\n    unfold Valid, TransDiffFun.\n    intros.\n    apply trans_diff_absurd_empty in H.\n    contradiction.\n  Qed.\n\n  Lemma reduces_n_to_valid:\n    forall l pm,\n    Trace.ReducesN pm l ->\n    Valid pm.\n  Proof.\n    induction l; intros. {\n      inversion H; subst.\n      auto using valid_make.\n    }\n    inversion H; subst; clear H.\n    eauto using Trace.reduces_n_cons, subject_reduction.\n  Qed.\nEnd SR.\n\n\n", "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/SubjectReduction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2995458159134361}}
{"text": "Set Implicit Arguments.\nRecord prod A B := pair { fst : A ; snd : B }.\nDefinition idS := Set.\nGoal forall x y : prod Set Set, forall H : fst x = fst y, fst x = fst y.\n  intros.\n  change (@fst _ _ ?z) with (@fst Set idS z) at 2.\n  apply H.\nQed.\n  \n(* Toplevel input, characters 20-58:\nError: Failed to get enough information from the left-hand side to type the\nright-hand side. *)\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/3590.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.29954363517796573}}
{"text": "From idt Require Import all.\nFrom oadt.lang_oadt Require Import\n     base syntax semantics typing infrastructure\n     equivalence values head preservation.\nImport syntax.notations typing.notations.\n\nLtac tsf_pared ctor mpared :=\n  let H := fresh in\n  pose proof ctor as H;\n  repeat\n    lazymatch type of H with\n    | lc _ -> ?T' => specialize_any H\n    | ?T -> ?T' =>\n        let P := subst_pattern T pared (fun Σ => rtc (pared Σ)) in\n        refine (P -> _ : Prop); specialize_any H\n    | forall e : ?T, _ =>\n        refine (forall e : T, _ : Prop); specialize (H e)\n    | ?Σ ⊢ ?e ⇛ ?e' => exact (mpared Σ e e')\n    end.\n\nMetaCoq Run (tsf_ind_gen_from\n               pared \"mpared\"\n               ltac:(tsf_ctors pared (append \"M\") tsf_pared)).\n\nSection fix_gctx.\n\nImplicit Types (b : bool) (x X y Y : atom) (L : aset).\n\n#[local]\nCoercion EFVar : atom >-> expr.\n\nContext (Σ : gctx).\nContext (Hwf : gctx_wf Σ).\n\n#[local]\nSet Default Proof Using \"All\".\n\nLemma mpared_lc e e' :\n  lc e ->\n  e ⇛* e' ->\n  lc e'.\nProof.\n  eapply rtc_preserve; eauto using pared_lc2.\nQed.\n\nLemma mpared_preservation Γ e l e' τ :\n  Γ ⊢ e :{l} τ ->\n  e ⇛* e' ->\n  Γ ⊢ e' :{l} τ.\nProof.\n  eapply rtc_preserve with (P := fun e => Γ ⊢ e :{l} τ).\n  eauto using pared_preservation.\nQed.\n\nLemma mpared_woval ω τ :\n  woval ω ->\n  ω ⇛* τ ->\n  woval τ.\nProof.\n  eapply rtc_preserve; eauto using pared_woval.\nQed.\n\nLemma mpared_body e e' L :\n  body e ->\n  (forall x, x ∉ L -> <{ e^x }> ⇛* <{ e'^x }>) ->\n  body e'.\nProof.\n  unfold body.\n  intros. simp_hyps. eexists. simpl_cofin. eauto using mpared_lc.\nQed.\n\nLemma mpared_subst1 e s s' x :\n  s ⇛* s' ->\n  lc e ->\n  <{ {x↦s}e }> ⇛* <{ {x↦s'}e }>.\nProof.\n  induction 1; try reflexivity.\n  econstructor; eauto using pared_subst1.\nQed.\n\n(** Similar to [mpared_subst1], but for the cases when the substitution is a\n[body]. The whole proof strategy for [mpared_sound] using this lemma is not\nparticularly elegant. *)\nLemma mpared_subst_body1 e s s' x L :\n  (* This condition may be provable with some side conditions, but it is too\n  much work. *)\n  (forall s s' L,\n      (forall x, x ∉ L -> <{ s^x }> ⇛ <{ s'^x }>) ->\n      <{ {x↦s}e }> ⇛ <{ {x↦s'}e }>) ->\n  (forall x, x ∉ L -> <{ s^x }> ⇛* <{ s'^x }>) ->\n  <{ {x↦s}e }> ⇛* <{ {x↦s'}e }>.\nProof.\n  intros Hp H.\n  simpl_cofin.\n  match type of H with\n  | ?s ⇛* ?s' => remember s; remember s'\n  end.\n  revert dependent s.\n  induction H; intros; subst.\n  - select (<{ _^_ }> = <{ _^_ }>) (fun H => apply open_inj in H).\n    subst; reflexivity. fast_set_solver!!.\n  - match goal with\n    | H : <{ ?s^(fvar ?x) }> ⇛ ?e |- _ =>\n        is_var e;\n        assert (lc e) by eauto using pared_lc2;\n        assert (e = open x (close x e)) by (by rewrite open_close)\n    end.\n    eapply rtc_l; [ | auto_apply ]; try set_shelve; eauto.\n\n    eapply Hp.\n    simpl_cofin.\n    eapply pared_rename; try set_shelve; eauto. qauto.\n\n  Unshelve.\n  all: rewrite ?close_fv by auto; fast_set_solver!!.\nQed.\n\nLemma mpared_sound e1 e2 :\n  mpared Σ e1 e2 ->\n  lc e1 ->\n  Σ ⊢ e1 ⇛* e2.\nProof.\n  destruct 1; intros;\n    repeat lc_inv;\n    (* Generate [lc] and [woval] hypotheses from [⇛*] relation. *)\n    do_hyps (fun H =>\n               try lazymatch type of H with\n                   | _ ⇛* _ =>\n                       dup_hyp H (fun H =>\n                                    apply mpared_lc in H; [ | solve [ eauto ] ])\n                   | forall _, _ -> _ ⇛* _ =>\n                       dup_hyp H (fun H =>\n                                    eapply mpared_body in H;\n                                    [ destruct H\n                                    | solve [ eauto using body_intro ] ])\n                   | woval _ =>\n                       dup_hyp H (fun H =>\n                                    eapply mpared_woval in H; [ | solve [ eauto ] ])\n                   end);\n    (* Consecutively apply [transitivity] such that any adjacent configurations\n    differ in only one subexpression. *)\n    let sol s s' e e' tac :=\n      match eval pattern s in e with\n      | ?f _ =>\n          transitivity (f s'); [\n            let x := fresh \"x\" in\n            let H := fresh in\n            pick_fresh as x;\n            assert (forall s, f s = <{ {x↦s},(f x) }>) as H\n                by (intros; simpl; rewrite ?decide_True by reflexivity;\n                    rewrite ?subst_fresh by eauto; reflexivity);\n            hnf in H;\n            rewrite (H s);\n            rewrite (H s');\n            solve [ tac H ]\n          | ]\n      end in\n    let rec go :=\n      lazymatch goal with\n      | H : ?s ⇛* ?s' |- ?e ⇛* ?e' =>\n          sol s s' e e' ltac:(fun H => eapply mpared_subst1; eauto using lc);\n          clear H; go\n      | H : forall _, _ -> <{ ?s^_ }> ⇛* <{ ?s'^_ }> |- ?e ⇛* ?e' =>\n          sol s s' e e' ltac:(fun H => eapply mpared_subst_body1; eauto;\n                                     intros; rewrite <- ?H;\n                                     eauto 10 using pared, lc);\n          clear H; go\n      (* Solve the last step. *)\n      | |- _ => try reflexivity; apply rtc_once; eauto 10 using pared\n      end in go.\nQed.\n\nLemma mpared_ocase b ω1 ω2 v e1 e2 e1' e2' L1 L2 :\n  oval v ->\n  otval ω1 -> otval ω2 ->\n  body e1 -> body e2 ->\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 }> ⇛* <{ ite b (e1'^v) (e2'^v) }>.\nProof.\n  intros.\n  select! (otval _) (fun H => use (ovalty_inhabited _ H)).\n  select! (forall x, _ -> _ ⇛* _)\n        (fun H => dup_hyp H (fun H => apply mpared_body in H; eauto)).\n  select! (body _) (fun H => destruct H).\n  etrans.\n  - apply mpared_sound; eauto using lc, otval.\n    econstructor; eauto using mpared.\n  - case_split;\n      (etrans; [ apply mpared_sound; eauto 10 using body_open_lc with lc;\n                 econstructor; try reflexivity\n               | reflexivity ]).\nQed.\n\nLemma mpared_tape v :\n  oval v ->\n  <{ tape v }> ⇛* v.\nProof.\n  intros. eauto 10 using mpared_sound, mpared with lc.\nQed.\n\nEnd fix_gctx.\n\nCreate HintDb mpared discriminated.\n#[export]\nHint Resolve mpared_sound : mpared.\n#[export]\nHint Constructors mpared : mpared.\n#[export]\nHint Resolve mpared_ocase : mpared.\n#[export]\nHint Resolve mpared_tape : mpared.\n\nLtac relax_mpared :=\n  match goal with\n  | |- mpared ?Σ ?e _ =>\n    refine (eq_ind _ (fun e' => mpared Σ e e') _ _ _)\n  end.\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/mpared.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.29954362932771317}}
{"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.Numbers.DecimalString.\nRequire Import Coq.NArith.NArith.\nRequire Import Coq.Strings.String.\nRequire Import Cava.Util.List.\n\nInductive type :=\n| Unit : type\n| Nat : type\n| Pair : type -> type -> type\n.\n\nFixpoint denote_type (t: type) :=\n  match t with\n  | Unit => unit\n  | Nat => nat\n  | Pair x y => (denote_type x * denote_type y)%type\n  end.\n\nFixpoint absorb_any (x y: type) :=\n  match x, y with\n  | Unit, x => x\n  | x, Unit => x\n  | _, _ => Pair x y\n  end.\n\nFixpoint absorb_right (x y: type) :=\n  match x, y with\n  | x, Unit => x\n  | _, _ => Pair x y\n  end.\n\nDeclare Scope circuit_type_scope.\nDelimit Scope circuit_type_scope with circuit_type.\nOpen Scope circuit_type_scope.\nNotation \"[ ]\" := Unit (format \"[ ]\") : circuit_type_scope.\nNotation \"[ x ]\" := (Pair x Unit) : circuit_type_scope.\nNotation \"[ x ; y ; .. ; z ]\" := (Pair x (Pair y .. (Pair z Unit) ..)) : circuit_type_scope.\nNotation \"x ** y\" := (Pair x y)(at level 60, right associativity) : circuit_type_scope.\nNotation \"x ++ y\" := (absorb_any x y) (at level 60, right associativity): circuit_type_scope.\n\nDefinition tvar : Type := type -> Type.\nExisting Class tvar.\n\nSection Vars.\n  Inductive Circuit {var: tvar}: type -> type -> type -> Type :=\n  | Var : forall {x},     var x -> Circuit [] [] x\n  | Abs : forall {s x y z}, (var x -> Circuit s y z) -> Circuit s (x ** y) z\n  | App : forall {s1 s2 x y z}, Circuit s1 (x ** y) z -> Circuit s2 [] x -> Circuit (s1 ++ s2) y z\n\n  | Let: forall {x y z s1 s2}, Circuit s1 [] x -> (var x -> Circuit s2 y z) -> Circuit (s1++s2) y z\n  (* slightly different fomualtion, but equivalent to loop delay *)\n  | LetDelay : forall {x y z s1 s2}, denote_type x\n    -> (var x -> Circuit s1 [] x)\n    -> (var x -> Circuit s2 y z)\n    -> Circuit (x ++ s1 ++ s2) y z\n\n  | Delay: forall {x}, denote_type x -> Circuit x [x] x\n\n  | AddMod : nat -> Circuit [] [Nat; Nat] Nat\n\n  | DestructTuple: forall {x y z s}, Circuit [] [] (x**y) -> (var x -> var y -> Circuit s y z) -> Circuit s y z\n  | MakeTuple: forall {x y}, Circuit [] [x;y] (x**y)\n  .\nEnd Vars.\n\nDefinition split_absorbed_denotation {x y}\n  : denote_type (x ++ y) -> denote_type x * denote_type y :=\n  match x, y with\n  | [],_ => fun x => (tt,x)\n  | _,[] => fun x => (x, tt)\n  | _, _ => fun x => x\n  end.\n\nDefinition combine_absorbed_denotation {x y}\n  : denote_type x -> denote_type y -> denote_type (x ++ y) :=\n  match x,y with\n  | [], _ => fun _ y => y\n  | _, [] => fun x _ => x\n  | _, _ => fun x y => (x,y)\n  end.\n\nFixpoint step {i s o} (c : Circuit s i o)\n  : denote_type s -> denote_type i -> denote_type s * denote_type o :=\n  match c in Circuit s i o return denote_type s -> denote_type i -> denote_type s * denote_type o with\n  | Var x => fun _ _ => (tt, x)\n  | Abs f => fun s '(i1,i2) =>\n    step (f i1) s i2\n  | App f x => fun s i =>\n    let '(sf, sx) := split_absorbed_denotation s in\n    let '(nsx, x) := step x sx tt in\n    let '(nsf, o) := step f sf (x, i) in\n    (combine_absorbed_denotation nsf nsx, o)\n  | Delay _ => fun s '(i,tt) => (i, s)\n  | AddMod n => fun _ '(a,(b,_)) => (tt, (a + b) mod (2 ^ n))\n  | Let x f => fun s i =>\n    let '(sx, sf) := split_absorbed_denotation s in\n    let '(nsx, x) := step x sx tt in\n    let '(nsf, o) := step (f x) sf i in\n    (combine_absorbed_denotation nsx nsf, o)\n  | LetDelay _ x f => fun s i =>\n    let '(sx, s12) := split_absorbed_denotation s in\n    let '(s1, s2) := split_absorbed_denotation s12 in\n\n    let '(ns1, x) := step (x sx) s1 tt in\n    let '(ns2, o) := step (f x) s2 i in\n\n    (combine_absorbed_denotation x (combine_absorbed_denotation ns1 ns2), o)\n\n  | DestructTuple tup f => fun s i =>\n    let '(x,y) := (snd (step tup tt tt)) in\n    let '(ns, o) := step (f x y) s i in\n    (ns, o)\n  | MakeTuple => fun _ '(x,(y,_)) =>\n    (tt, (x, y))\n  end.\n\nFixpoint default {t: type} : denote_type t :=\n  match t with\n  | Unit => tt\n  | Nat => 0\n  | Pair x y => (@default x, @default y)\n  end.\n\nFixpoint reset_state {i s o} (c : Circuit (var:=denote_type) s i o) : denote_type s :=\n  match c in Circuit s i o return denote_type s with\n  | Var _ => tt\n  | Abs f => reset_state (f default)\n  | App f x => combine_absorbed_denotation (reset_state f) (reset_state x)\n  | Let x f => combine_absorbed_denotation (reset_state x) (reset_state (f default))\n  | LetDelay initial x f =>\n    combine_absorbed_denotation initial\n      (combine_absorbed_denotation (reset_state (x default)) (reset_state (f default)))\n  | Delay initial => initial\n  | AddMod _ => tt\n  | MakeTuple => tt\n  | DestructTuple tup f => combine_absorbed_denotation (reset_state tup) (reset_state (f default default))\n  end.\n\nDefinition simulate {s i o} (c : Circuit (var:=denote_type) s i o) (input : list (denote_type i)) : list (denote_type o) :=\n  fold_left_accumulate (step c) input (reset_state c).\n\nDeclare Scope expr_scope.\nDeclare Custom Entry expr.\nDelimit Scope expr_scope with expr.\n\nNotation \"{{ x }}\" := (x)%expr  (at level 1, x custom expr at level 99).\nNotation \"f x\" := (App f x) (in custom expr at level 3, left associativity) : expr_scope.\nNotation \"x\" := (Var x) (in custom expr, x ident) : expr_scope.\nNotation \"[[ x ]]\" := (x)(in custom expr at level 2, x constr at level 99) : expr_scope.\nNotation \"'fun' x .. y => e\" := ( (Abs (fun x => .. (Abs (fun y => e)) ..) )%expr\n ) (in custom expr at level 1, x binder, y binder, e custom expr at level 1) : expr_scope.\n\nNotation \"'let' x := a 'in' e\" := (Let a (fun x => e))\n  (in custom expr at level 1, x pattern at level 4, e at level 7, a at level 1) : expr_scope.\nNotation \"'let/delay' x := a 'initially' v 'in' b\" := (LetDelay v (fun x => a) (fun x => b))\n  (in custom expr at level 1, x pattern at level 4, v constr at level 99, b at level 7, a at level 1) : expr_scope.\nNotation \"'delay' x 'initially' v\" := (App (Delay v) x)\n  (in custom expr at level 1, x at level 4, v constr at level 7) : expr_scope.\n\n(* Custom entry means we either need to add primitives as explicit notation or\n * provide escaping *)\nNotation \"'addmod' v\" := (AddMod v)\n  (in custom expr at level 1, v constr at level 7) : expr_scope.\n\nNotation \"( x , y )\" := (App (App MakeTuple x) y)\n  (in custom expr, x at level 4, y at level 4) : expr_scope.\n\nSection Var.\n  Context {var : tvar}.\n\n  Definition test {A} : Circuit [] [A] A := {{\n    fun a => let b := a in a\n  }}.\n\n  Definition fork2 {A} : Circuit [] [A] (A ** A) := {{\n    fun a => (a, a)\n  }}.\n\n  (* I've used 'initially' to separate initial values that aren't part of the\n   * bind/app phoas structure. e.g.*)\n  (* delay _ initially _ *)\n  (* (self referenceing binder equivalent to loop) =*)\n  (* let/delay _ := _ initially _ *)\n  Definition fibonacci {sz: nat}: Circuit (Nat ** Nat) [] Nat := {{\n    let/delay r1 :=\n      let r2 := delay r1 initially (2^sz-1:denote_type Nat) in\n      addmod sz r1 r2\n      initially (1:denote_type Nat) in\n    r1\n  }}.\nEnd Var.\n\n\nRequire Import Coq.Lists.List.\nRequire Import Coq.micromega.Lia.\nRequire Import coqutil.Tactics.Tactics.\nRequire Import Cava.Util.List.\nRequire Import Cava.Util.Tactics.\n\nFixpoint fibonacci_nat (n : nat) :=\n  match n with\n  | 0 => 0\n  | S m =>\n    let f_m := fibonacci_nat m in\n    match m with\n    | 0 => 1\n    | S p => fibonacci_nat p + f_m\n    end\n  end.\n\nDefinition spec_of_fibonacci (sz : nat) (input : list unit) : list nat\n  := map (fun n => fibonacci_nat n mod (2 ^ sz)) (seq 0 (List.length input)).\n\nLemma fork2_step A state input : step (fork2 (A:=A)) state (input, tt) = (tt, (input, input)).\nProof. reflexivity. Qed.\n\nLemma fibonacci_step sz state input :\n  step (fibonacci (sz:=sz)) state input\n  = let sum := (fst state + snd state) mod (2 ^ sz) in\n    (sum, fst state, sum).\nProof.\n  intros; cbn [step fibonacci ].\n  repeat (destruct_pair_let; cbn [split_absorbed_denotation combine_absorbed_denotation List.app absorb_any fst snd]).\n  reflexivity.\nQed.\n\nDefinition fibonacci_invariant {sz}\n           (t : nat) (loop_state : nat * nat)\n           (output_accumulator : list nat) : Prop :=\n  let r1 := fst loop_state in\n  let r2 := snd loop_state in\n  (* at timestep t... *)\n  (* ...r1 holds fibonacci_nat (t-1), or 1 if t=0 *)\n  r1 = match t with\n       | 0 => 1\n       | S t_minus1 => (fibonacci_nat t_minus1) mod (2 ^ sz)\n       end\n  (* ... and r2 holds fibonacci_nat (t-2), or 1 if t=1, 2^sz-1 if t=0 *)\n  /\\ r2 = match t with\n         | 0 => 2 ^ sz - 1\n         | 1 => 1\n         | S (S t_minus2) =>(fibonacci_nat t_minus2) mod (2 ^ sz)\n         end\n  (* ... and the output accumulator matches the circuit spec for the\n     inputs so far *)\n  /\\ output_accumulator = spec_of_fibonacci sz (repeat tt t).\n\n(* Helper lemma for fibonacci_correct *)\nLemma fibonacci_nat_step n :\n  fibonacci_nat (S (S n)) = fibonacci_nat (S n) + fibonacci_nat n.\nProof. cbn [fibonacci_nat]. lia. Qed.\n\nLemma fibonacci_correct sz input :\n  simulate (fibonacci (sz:=sz)) input = spec_of_fibonacci sz input.\nProof.\n  cbv [simulate]. rewrite fold_left_accumulate_to_seq with (default:=tt).\n  assert (2 ^ sz <> 0) by (apply Nat.pow_nonzero; lia).\n  apply fold_left_accumulate_invariant_seq with (I:=fibonacci_invariant (sz:=sz)).\n  { cbv [fibonacci_invariant]. ssplit; reflexivity. }\n  { cbv [fibonacci_invariant].\n    intros; destruct_products; cbn [fst snd] in *; subst; cbn [fst snd].\n    rewrite fibonacci_step. cbn [fst snd].\n    repeat destruct_one_match.\n    { (* t = 0 case *)\n      cbn. rewrite Nat.sub_1_r, Nat.succ_pred by lia.\n      rewrite Nat.mod_same, Nat.mod_0_l by lia.\n      ssplit; reflexivity. }\n    { (* t = 1 case *)\n      cbn. rewrite Nat.mod_0_l by lia.\n      ssplit; reflexivity. }\n    { (* t > 1 case *)\n      rewrite Nat.add_mod_idemp_r, Nat.add_mod_idemp_l by lia.\n      ssplit.\n      { cbn [fibonacci_nat]. f_equal; lia. }\n      { reflexivity. }\n      { cbv [spec_of_fibonacci].\n        autorewrite with push_length.\n        rewrite seq_S with (len:=S (S _)).\n        autorewrite with natsimpl. rewrite map_app.\n        cbn [map]. rewrite fibonacci_nat_step.\n        reflexivity. } } }\n  { cbv [fibonacci_invariant]. intros.\n    logical_simplify; subst.\n    autorewrite with push_length.\n    erewrite <-list_unit_equiv. reflexivity. }\nQed.\n\nInductive FCircuit : nat -> type -> type -> Type :=\n| FVar : forall {s x}, nat -> FCircuit s [] x\n| FAbs : forall {s x y z}, FCircuit (S s) y z -> FCircuit s (x ** y) z\n| FApp : forall {s x y z}, FCircuit s (x ** y) z -> FCircuit s [] x -> FCircuit s y z\n\n| FLet: forall {s x y z }, FCircuit s [] x -> FCircuit (S s) y z -> FCircuit s y z\n| FLetDelay : forall {s x y z}, denote_type x\n  -> FCircuit (S s) [] x\n  -> FCircuit (S s) y z\n  -> FCircuit s y z\n\n| FDelay: forall {s x}, denote_type x -> FCircuit s [x] x\n\n| FAddMod : forall {s}, nat -> FCircuit s [Nat; Nat] Nat\n\n| FDestructTuple: forall {s x y z}, FCircuit s [] (x**y) -> FCircuit (S (S s)) y z -> FCircuit s y z\n| FMakeTuple: forall {s x y}, FCircuit s [x;y] (x**y)\n.\n\nFixpoint to_first_order {i s o} n (c : Circuit (var:=fun _ => nat) s i o)\n  : FCircuit n i o :=\n  match c in Circuit _ i o return FCircuit n i o with\n  | Var x => FVar x\n  | Abs f => FAbs (to_first_order (S n) (f n))\n  | App f x => FApp (to_first_order n f) (to_first_order n x)\n  | Delay v => FDelay v\n  | AddMod n => FAddMod n\n  | Let x f => FLet (to_first_order n x) (to_first_order (S n) (f n))\n  | LetDelay v x f => FLetDelay v (to_first_order (S n) (x n)) (to_first_order (S n) (f n))\n  | DestructTuple tup f =>\n    FDestructTuple (to_first_order n tup)\n    (to_first_order (S (S n)) (f n (S n)))\n  | MakeTuple => FMakeTuple\n  end.\n\nClose Scope list_scope.\n\nFixpoint fo_state {n i o} (c: FCircuit n i o) : type :=\n  match c with\n  | FVar _ => Unit\n  | FAbs f => fo_state f\n  | FApp f x => (fo_state f ++ fo_state x)\n  | FLet x f => (fo_state f ++ fo_state x)\n  | @FLetDelay _ X _ _ t x f => X ++ (fo_state f ++ fo_state x)\n  | @FDelay _ X _ => X\n  | FAddMod _ => Unit\n  | FDestructTuple tup f => (fo_state tup ++ fo_state f)\n  | FMakeTuple => Unit\n  end.\n\nDefinition fib_fo {sz} := to_first_order 0 (fibonacci (sz:=sz)).\n\nDefinition get_phoas_state {i o s var} (_: Circuit (var:=var) s i o) := s.\n\nCompute (fib_fo (sz:=12)).\nCompute fo_state (fib_fo (sz:=12)).\n\nGoal forall sz, get_phoas_state (var:=fun _ => nat) (fibonacci (sz:=sz)) = fo_state (fib_fo (sz:=sz)).\n  intros.\n  cbn [ fo_state fib_fo to_first_order fibonacci absorb_any].\n  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/investigations/ast/AST2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2995037328812037}}
{"text": "(**************************************************************************)\n(*  This is part of EXCEPTIONS-PL, it is distributed under the terms of   *)\n(*         the GNU Lesser General Public License version 3                *)\n(*              (see file LICENSE for more details)                       *)\n(*                                                                        *)\n(*       Copyright 2015: Jean-Guillaume Dumas, Dominique Duval            *)\n(*\t\t\t Burak Ekici, Damien Pous.                        *)\n(**************************************************************************)\n\nRequire Import Relations Morphisms Bool.\nRequire Import Program.\nRequire Prerequistes Terms.\nSet Implicit Arguments.\n\nModule Make(Import M: Prerequistes.T).\n  Module Export DecorationsExp := Terms.Make(M). \n\n Inductive kindpl := pl_epure | pl_ppg.\n\n Inductive is_pl: kindpl -> forall X Y, termpl X Y -> Prop :=\n | is_pl_tpure: forall X Y (f: X -> Y), is_pl pl_epure (@pl_tpure X Y f)\n | is_pl_comp: forall k X Y Z (f: termpl X Y) (g: termpl Y Z), is_pl k f -> is_pl k g -> is_pl k (f O g)\n | is_throw: forall X (e: EName), is_pl pl_ppg (@throw X e)\n | is_try_catch: forall X Y (e: EName) (a: termpl Y X) (b: termpl Y (Val e)), is_pl pl_ppg (@try_catch _ _ e a b)\n | is_pl_pure_ppg: forall X Y (f: termpl X Y), is_pl pl_epure f -> is_pl pl_ppg f.\n\n Hint Constructors is_pl.\n\n Ltac pl_edecorate :=  solve[\n                          repeat (apply is_pl_comp)\n                            ||\n\t\t                 (apply is_pl_tpure || apply is_throw || apply is_try_catch || apply is_pl_pure_ppg || assumption)\n\t\t\t    || \n                                 (apply is_pl_pure_ppg)\n                        ].\n Class PL_EPURE {A B: Type} (f: termpl A B) := isplp : is_pl pl_epure f.\n Class PL_PPG {A B: Type} (f: termpl A B) := isplthrw : is_pl pl_ppg f.\n\n Fixpoint fix_has_no_propagator X Y (f: termpl X Y): bool :=\n   match f with\n     | throw _ _         => false\n     | try_catch _ _ _ _ _   => false\n     | pl_comp _ _ _ f g => fix_has_no_propagator f && fix_has_no_propagator g\n     | _ => true\n   end.\n\n Definition has_no_propogator X Y (f : termpl X Y) : Prop := fix_has_no_propagator f = true.\n Definition has_only_pure X Y (f : termpl X Y) : Prop := fix_has_no_propagator f = true.\n\n\n Lemma onlypurecomp : forall X Y Z (f: termpl Y X) (g: termpl Z Y), \n      has_only_pure f /\\ has_only_pure g -> has_only_pure (g O f).\n Proof.\n  intros. unfold has_only_pure. simpl. rewrite andb_true_iff.\n  split; apply H.\n Qed.\n\n Lemma no_untag_tag_ispure : forall X Y (g: termpl X Y), \n\t(has_only_pure g) -> PL_EPURE g.\n Proof.\n    intros. unfold has_only_pure in H. induction g. \n    (* tpure *)\n    apply is_pl_tpure.\n    (* comp *) \n    apply is_pl_comp. simpl in H.\n    rewrite ?andb_true_iff in H.\n    destruct H. destruct H. destruct H0.\n    apply IHg1. reflexivity.\n    simpl in H.\n    rewrite ?andb_true_iff in H.\n    destruct H. destruct H. destruct H0.\n    apply IHg2. reflexivity.  \n    (* throw *)\n    simpl in H. contradict H. auto.\n    (* try/catch *)\n    simpl in H. contradict H. auto.\n Qed.\n\n\nEnd Make.\n", "meta": {"author": "ekiciburak", "repo": "hpc", "sha": "08fa1a35542ca4de7239692b37926f81bf51327d", "save_path": "github-repos/coq/ekiciburak-hpc", "path": "github-repos/coq/ekiciburak-hpc/hpc-08fa1a35542ca4de7239692b37926f81bf51327d/exc_pl-hp/Decorations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.29950372757082566}}
{"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 Bool.\nRequire Import String.\nRequire Import List.\nRequire Import Eqdep_dec.\nRequire Import RelationClasses.\nRequire Import Utils.\nRequire Import ForeignType.\nRequire Import RType.\nRequire Import BrandRelation.\n\nSection RSubtype.\n\n  Context {ftype:foreign_type}.\n  Context {br:brand_relation}.\n  \nInductive subtype : rtype -> rtype -> Prop :=\n  | STop r : subtype r ⊤\n  | SBottom r : subtype ⊥ r\n  | SRefl r : subtype r r\n  | SColl r1 r2 : subtype r1 r2 -> subtype (Coll r1) (Coll r2)\n  (** Allow width subtyping of open records and depth subtyping of both types of records. Also, a closed record can be a subtype of an open record (but not vice versa) *)\n  | SRec k1 k2 rl1 rl2 pf1 pf2 : (forall s r',\n                      lookup string_dec rl2 s = Some r' -> \n                      exists r, lookup string_dec rl1 s = Some r /\\\n                                subtype r r') ->\n                                (k2 = Closed -> k1 = Closed /\\ \n                                 (forall s, In s (domain rl1) -> In s (domain rl2))) ->\n                                subtype (Rec k1 rl1 pf1) (Rec k2 rl2 pf2)\n  | SEither l1 l2 r1 r2 :\n      subtype l1 l2 ->\n      subtype r1 r2 ->\n      subtype (Either l1 r1) (Either l2 r2)\n  | SArrow in1 in2 out1 out2:\n      subtype in2 in1 ->\n      subtype out1 out2 ->\n      subtype (Arrow in1 out1) (Arrow in2 out2)\n  | SBrand b1 b2 : sub_brands brand_relation_brands b1 b2 -> subtype (Brand b1) (Brand b2)\n  | SForeign ft1 ft2 :\n      foreign_type_sub ft1 ft2 ->\n      subtype (Foreign ft1) (Foreign ft2)\n.\n\nLemma SRec_open k1 rl1 rl2 pf1 pf2 :\n  (forall s r',\n     lookup string_dec rl2 s = Some r' -> \n     exists r, lookup string_dec rl1 s = Some r /\\\n               subtype r r') ->\n  subtype (Rec k1 rl1 pf1) (Rec Open rl2 pf2).\nProof.\n  intros; constructor; intuition; discriminate.\nQed.\n\nLemma SRec_closed_in_domain {k1 k2 rl1 rl2 pf1 pf2} :\n  subtype (Rec k1 rl1 pf1) (Rec k2 rl2 pf2) ->\n  (forall x, In x (domain rl2) -> In x (domain rl1)).\nProof.\n  inversion 1; rtype_equalizer; subst; intuition.\n  destruct (in_dom_lookup string_dec H0).\n  destruct (H3 _ _ H1) as [? [inn ?]].\n  apply lookup_in in inn.\n  apply in_dom in inn.\n  trivial.\nQed.\n\nLemma SRec_closed_equiv_domain {k1 rl1 rl2 pf1 pf2} :\n  subtype (Rec k1 rl1 pf1) (Rec Closed rl2 pf2) ->\n  (forall x, In x (domain rl1) <-> In x (domain rl2)).\nProof.\n  inversion 1; rtype_equalizer; subst; intuition.\n  eapply SRec_closed_in_domain; eauto.\nQed.\n\n  Lemma UIP_refl_dec \n        {A:Type}\n        (dec:forall x y:A, {x = y} + {x <> y}) \n        {x:A} \n        (p1:x = x) : p1 = eq_refl x.\n  Proof.\n    intros. apply (UIP_dec); auto.\n  Qed.\n\n  (** This follows trivially from the consistency of join and subtype.\n      However, this version should have better computational properties.*)\n\n  Hint Constructors subtype : qcert.\n  \n  Lemma subtype_both_dec x y :\n    (prod ({subtype x y} + {~ subtype x y}) ({subtype y x} + {~ subtype y x})).\n  Proof.\n    Ltac simp := match goal with\n            | [H:(@eq bool ?x ?x) |- _ ] => generalize (UIP_refl_dec bool_dec H); intro; subst H\n          end.\n    destruct x.\n    revert y; induction x\n    ; intros y; destruct y as [y pfy]; destruct y; constructor;\n    try solve[right; inversion 1 | left; simpl in *; repeat simp; eauto with qcert ].\n    - destruct (IHx e (exist _ y pfy)) as [[?|?]_].\n      + left. repeat rewrite (Coll_canon).\n        auto with qcert.\n      + right. intro ss; apply n. inversion ss; subst.\n         * erewrite (rtype_ext); eauto with qcert.\n         * destruct r1; destruct r2; simpl in *.\n           erewrite (rtype_ext e); erewrite (rtype_ext pfy); eauto.\n    - destruct (IHx e (exist _ y pfy)) as [_[?|?]].\n      + left. repeat rewrite (Coll_canon).\n        auto with qcert.\n      + right. intro ss; apply n. inversion ss; subst.\n         * erewrite (rtype_ext); eauto with qcert.\n         * destruct r1; destruct r2; simpl in *.\n           erewrite (rtype_ext e); erewrite (rtype_ext pfy); eauto.\n    - rename srl into srl0; rename r into srl.\n      assert (sub:{forall s r' pf',\n      lookup string_dec srl0 s = Some r' -> \n      exists r pf, lookup string_dec srl s = Some r /\\\n                subtype (exist _ r pf) (exist _ r' pf')} + {~ (forall s r' pf',\n      lookup string_dec srl0 s = Some r' -> \n      exists r pf, lookup string_dec srl s = Some r /\\\n                subtype (exist _ r pf) (exist _ r' pf'))}).\n      + induction srl0; simpl; [left; intros; discriminate | ].\n         destruct a.\n         case_eq (lookup string_dec srl s).\n        * intros ? inn.\n          assert (wfr:wf_rtype₀ r = true)\n                 by (eapply (wf_rtype₀_Rec_In pfy); simpl; left; reflexivity).\n          destruct (Forallt_In H _ (lookup_in string_dec _ inn) (wf_rtype₀_Rec_In e _ _ ((lookup_in string_dec _ inn))) (exist _ r wfr)) as [[?|?]_].\n          \n            destruct (IHsrl0 (wf_rtype₀_cons_tail pfy)).\n              left. intros ? ? ? eqq. match_destr_in eqq; subst; eauto 2.\n                inversion eqq; subst.\n                rewrite (rtype_ext pf' wfr); eauto.\n              right; intro nin. apply n; intros ss rr rrpf sin.\n              specialize (nin ss rr). \n              match_destr_in nin; [| intuition ].\n              subst.\n              apply wf_rtype₀_cons_nin in pfy.\n              congruence.\n          right; intro nin. specialize (nin s r).\n          match_destr_in nin; [| intuition ].\n          destruct (nin wfr (eq_refl _)) as [? [?[??]]]; simpl in *.\n          rewrite inn in H0. inversion H0; subst.\n          apply n.\n          rewrite (rtype_ext _ x0). trivial.\n        * right; intro nin. specialize (nin s r).\n          match_destr_in nin; [| intuition ].\n          assert (wfr:wf_rtype₀ r = true)\n                 by (eapply (wf_rtype₀_Rec_In pfy); simpl; left; reflexivity).\n          destruct (nin wfr (eq_refl _)) as [? [?[??]]].\n          congruence.\n      + destruct sub.\n        * destruct k0.\n          left.\n          destruct (from_Rec₀ srl e) as [? [?[??]]]; subst.\n          rewrite <- H1.\n          destruct (from_Rec₀ _ pfy) as [? [?[??]]]; subst.\n          rewrite <- H2.\n          econstructor; try discriminate.\n          intros ? ? lo. destruct r'.\n          apply lookup_map_some' in lo.\n          destruct (e0 _ _ e1 lo) as [?[?[??]]].\n          rewrite <- (lookup_map_some' _ _ _ x5) in H0.\n          exists (exist _ x4 x5). intuition.\n          destruct k.\n             right; inversion 1; intuition; discriminate.\n           destruct (incl_list_dec string_dec (domain srl) (domain srl0)).\n             left.\n             destruct (from_Rec₀ srl e) as [? [?[??]]]; subst.\n             rewrite <- H1.\n             destruct (from_Rec₀ _ pfy) as [? [?[??]]]; subst.\n             rewrite <- H2.\n             constructor; intros.\n               destruct r'.\n               rewrite (lookup_map_some' _ _ _ e1) in H0.\n               destruct (e0 _ _ e1 H0) as [?[?[??]]].\n               rewrite <- (lookup_map_some' _ _ _ x5) in H3.\n               exists (exist _ x4 x5). intuition.\n               intuition.\n                 specialize (i s).\n                 unfold domain in i; repeat rewrite map_map in i.\n                 simpl in i.\n                 auto.\n             right; inversion 1; rtype_equalizer; subst; eauto 2.\n             intuition.  apply n.\n             intros ? .\n             unfold domain; repeat rewrite map_map.\n             simpl.\n             auto.\n        * right; inversion 1; apply n; rtype_equalizer; subst; eauto with qcert.\n          intros.\n          rewrite <- (lookup_map_some' _ _ _ pf') in H1.\n          destruct (H4 _ _ H1) as [? [??]].\n          destruct x.\n          exists x; exists e0.\n          rewrite <- (lookup_map_some' _ _ _ e0).\n          intuition.\n    - rename srl into srl0; rename r into srl.\n      assert (sub:{forall s r' pf',\n      lookup string_dec srl s = Some r' -> \n      exists r pf, lookup string_dec srl0 s = Some r /\\\n                subtype (exist _ r pf) (exist _ r' pf')} + {~ (forall s r' pf',\n      lookup string_dec srl s = Some r' -> \n      exists r pf, lookup string_dec srl0 s = Some r /\\\n                   subtype (exist _ r pf) (exist _ r' pf'))}).\n      + induction srl; simpl; [left; intros; discriminate | ].\n        destruct a.\n        case_eq (lookup string_dec srl0 s).\n        * intros ? inn.\n          assert (wfr0:wf_rtype₀ r0 = true)\n            by (eapply (wf_rtype₀_Rec_In pfy); eapply lookup_in; eauto).\n          assert (wfr:wf_rtype₀ r = true)\n            by (eapply (wf_rtype₀_Rec_In e); simpl; left; reflexivity).\n          invcs H.\n          simpl in H2.\n          destruct (H2 wfr (exist _ r0 wfr0)) as [_ issub].\n          { destruct issub.\n            - destruct (IHsrl H3 (wf_rtype₀_cons_tail e)).\n              + left; intros ? ? ? eqq.\n                match_destr_in eqq; subst; eauto 2.\n                inversion eqq; subst.\n                rewrite (rtype_ext pf' wfr); eauto.\n              + right; intro nin. apply n; intros ss rr rrpf sin.\n                specialize (nin ss rr). \n                match_destr_in nin; [| intuition ].\n                subst.\n                apply wf_rtype₀_cons_nin in e.\n                congruence.\n            - right; intro nin. specialize (nin s r).\n              match_destr_in nin; [| intuition ].\n              destruct (nin wfr (eq_refl _)) as [? [?[??]]]; simpl in *.\n              rewrite inn in H. inversion H; subst.\n              apply n.\n              rewrite (rtype_ext _ x0). trivial.\n          } \n        * right; intro nin. specialize (nin s r).\n          match_destr_in nin; [| intuition ].\n          assert (wfr:wf_rtype₀ r = true)\n            by (eapply (wf_rtype₀_Rec_In e); simpl; left; reflexivity).\n          destruct (nin wfr (eq_refl _)) as [? [?[??]]].\n          congruence.\n      + destruct sub.\n        * {destruct k.\n           - left.\n             destruct (from_Rec₀ srl e) as [? [?[??]]]; subst.\n             rewrite <- H1.\n             destruct (from_Rec₀ _ pfy) as [? [?[??]]]; subst.\n             rewrite <- H2.\n             econstructor; try discriminate.\n             intros ? ? lo. destruct r'.\n             apply lookup_map_some' in lo.\n             destruct (e0 _ _ e1 lo) as [?[?[??]]].\n             rewrite <- (lookup_map_some' _ _ _ x5) in H0.\n             exists (exist _ x4 x5). intuition.\n           - destruct k0.\n             + right.\n               inversion 1; subst.\n               intuition; discriminate.\n             + destruct (incl_list_dec string_dec (domain srl0) (domain srl)).\n               * left.\n                 destruct (from_Rec₀ srl e) as [? [?[??]]]; subst.\n                 rewrite <- H1.\n                 destruct (from_Rec₀ _ pfy) as [? [?[??]]]; subst.\n                 rewrite <- H2.\n                 { constructor; intros.\n                   - destruct r'.\n                     rewrite (lookup_map_some' _ _ _ e1) in H0.\n                     destruct (e0 _ _ e1 H0) as [?[?[??]]].\n                     rewrite <- (lookup_map_some' _ _ _ x5) in H3.\n                     exists (exist _ x4 x5). intuition.\n                   - intuition.\n                     specialize (i s).\n                     unfold domain in i; repeat rewrite map_map in i.\n                     simpl in i.\n                     auto.\n                 } \n               * right; inversion 1; rtype_equalizer; subst; eauto 2.\n                 intuition.  apply n.\n                 intros ? .\n                 unfold domain; repeat rewrite map_map.\n                 simpl.\n                 auto.\n          } \n        * right; inversion 1; apply n; rtype_equalizer; subst; eauto with qcert.\n          intros.\n          rewrite <- (lookup_map_some' _ _ _ pf') in H1.\n          destruct (H4 _ _ H1) as [? [??]].\n          destruct x.\n          exists x; exists e0.\n          rewrite <- (lookup_map_some' _ _ _ e0).\n          intuition.\n    - destruct (Either₀_wf_inv e) as [pfl1 pfr1].\n      destruct (Either₀_wf_inv pfy) as [pfl2 pfr2].\n      destruct (IHx1 pfl1 (exist _ _ pfl2)) as [[?|?]_].\n      + destruct (IHx2 pfr1 (exist _ _ pfr2)) as [[?|?]_].\n        * left.\n          rewrite (Either_canon _ _ _ pfl1 pfr1).\n          rewrite (Either_canon _ _ _ pfl2 pfr2).\n          eauto with qcert.\n        * right; inversion 1; subst.\n            apply n. rewrite (rtype_ext pfr1 pfr2). eauto with qcert.\n            rewrite (Either_canon _ _ _ pfl1 pfr1) in H.\n            rewrite (Either_canon _ _ _ pfl2 pfr2) in H.\n            apply n.\n            inversion H; rtype_equalizer; subst.\n              rewrite (rtype_ext pfr1 pfr2). eauto with qcert.\n              subst.\n              rewrite (rtype_ext pfr1 (proj2_sig r1)).\n              rewrite (rtype_ext pfr2 (proj2_sig r2)).\n              destruct r1; destruct r2. simpl in *.\n              trivial.\n      + right; inversion 1; subst.\n         apply n. rewrite (rtype_ext pfl1 pfl2). eauto with qcert.\n            rewrite (Either_canon _ _ _ pfl1 pfr1) in H.\n            rewrite (Either_canon _ _ _ pfl2 pfr2) in H.\n            apply n.\n            inversion H. rtype_equalizer.\n              subst. rewrite (rtype_ext pfl1 pfl2). eauto with qcert.\n\n            subst.\n            rewrite (rtype_ext pfl1 (proj2_sig l1)).\n            rewrite (rtype_ext pfl2 (proj2_sig l2)).\n            destruct l1; destruct l2. simpl in *.\n            trivial.\n    - destruct (Either₀_wf_inv e) as [pfl1 pfr1].\n      destruct (Either₀_wf_inv pfy) as [pfl2 pfr2].\n      destruct (IHx1 pfl1 (exist _ _ pfl2)) as [_[?|?]].\n      + destruct (IHx2 pfr1 (exist _ _ pfr2)) as [_[?|?]].\n        * left.\n          rewrite (Either_canon _ _ _ pfl1 pfr1).\n          rewrite (Either_canon _ _ _ pfl2 pfr2).\n          eauto with qcert.\n        * right; inversion 1; subst.\n            apply n. rewrite (rtype_ext pfr1 pfr2). eauto with qcert.\n            rewrite (Either_canon _ _ _ pfl1 pfr1) in H.\n            rewrite (Either_canon _ _ _ pfl2 pfr2) in H.\n            apply n.\n            { inversion H; rtype_equalizer; subst.\n              - rewrite (rtype_ext pfr1 pfr2). eauto with qcert.\n              - subst.\n              rewrite (rtype_ext pfr2 (proj2_sig r1)).\n              rewrite (rtype_ext pfr1 (proj2_sig r2)).\n              destruct r1; destruct r2. simpl in *.\n              trivial.\n            } \n      + right; inversion 1; subst.\n         apply n. rewrite (rtype_ext pfl1 pfl2). eauto with qcert.\n            rewrite (Either_canon _ _ _ pfl1 pfr1) in H.\n            rewrite (Either_canon _ _ _ pfl2 pfr2) in H.\n            apply n.\n            inversion H. rtype_equalizer.\n              subst. rewrite (rtype_ext pfl1 pfl2). eauto with qcert.\n\n            subst.\n            rewrite (rtype_ext pfl2 (proj2_sig l1)).\n            rewrite (rtype_ext pfl1 (proj2_sig l2)).\n            destruct l1; destruct l2. simpl in *.\n            trivial.\n    - destruct (Arrow₀_wf_inv e) as [pfl1 pfr1].\n      destruct (Arrow₀_wf_inv pfy) as [pfl2 pfr2].\n      destruct (IHx1 pfl1 (exist _ _ pfl2)) as [?[?|?]].\n      + destruct (IHx2 pfr1 (exist _ _ pfr2)) as [[?|?]?].\n        * left.\n          rewrite (Arrow_canon _ _ _ pfl1 pfr1).\n          rewrite (Arrow_canon _ _ _ pfl2 pfr2).\n          econstructor; eauto.\n        * right; inversion 1; subst.\n            apply n. rewrite (rtype_ext pfr1 pfr2). eauto with qcert.\n            rewrite (Arrow_canon _ _ _ pfl1 pfr1) in H.\n            rewrite (Arrow_canon _ _ _ pfl2 pfr2) in H.\n            apply n.\n            inversion H; rtype_equalizer; subst.\n              rewrite (rtype_ext pfr1 pfr2). eauto with qcert.\n              subst.\n              rewrite (rtype_ext pfr1 (proj2_sig out1)).\n              rewrite (rtype_ext pfr2 (proj2_sig out2)).\n              destruct out1; destruct out2. simpl in *.\n              trivial.\n      + right; inversion 1; subst.\n         apply n. rewrite (rtype_ext pfl1 pfl2). eauto with qcert.\n            rewrite (Arrow_canon _ _ _ pfl1 pfr1) in H.\n            rewrite (Arrow_canon _ _ _ pfl2 pfr2) in H.\n            apply n.\n            inversion H. rtype_equalizer.\n            subst. rewrite (rtype_ext pfl1 pfl2). eauto with qcert.\n            rtype_equalizer.\n            subst.\n            rewrite (rtype_ext pfl1 (proj2_sig in1)).\n            rewrite (rtype_ext pfl2 (proj2_sig in2)).\n            destruct in1; destruct in2. simpl in *.\n              trivial.\n    - destruct (Arrow₀_wf_inv e) as [pfl1 pfr1].\n      destruct (Arrow₀_wf_inv pfy) as [pfl2 pfr2].\n      destruct (IHx1 pfl1 (exist _ _ pfl2)) as [[?|?]?].\n      + destruct (IHx2 pfr1 (exist _ _ pfr2)) as [?[?|?]].\n        * left.\n          rewrite (Arrow_canon _ _ _ pfl1 pfr1).\n          rewrite (Arrow_canon _ _ _ pfl2 pfr2).\n          econstructor; eauto.\n        * right; inversion 1; subst.\n            apply n. rewrite (rtype_ext pfr1 pfr2). eauto with qcert.\n            rewrite (Arrow_canon _ _ _ pfl1 pfr1) in H.\n            rewrite (Arrow_canon _ _ _ pfl2 pfr2) in H.\n            apply n.\n            inversion H; rtype_equalizer; subst.\n              rewrite (rtype_ext pfr1 pfr2). eauto with qcert.\n              subst.\n              rewrite (rtype_ext pfr1 (proj2_sig out2)).\n              rewrite (rtype_ext pfr2 (proj2_sig out1)).\n              destruct out1; destruct out2. simpl in *.\n              trivial.\n      + right; inversion 1; subst.\n         apply n. rewrite (rtype_ext pfl1 pfl2). eauto with qcert.\n            rewrite (Arrow_canon _ _ _ pfl1 pfr1) in H.\n            rewrite (Arrow_canon _ _ _ pfl2 pfr2) in H.\n            apply n.\n            inversion H. rtype_equalizer.\n            subst. rewrite (rtype_ext pfl1 pfl2). eauto with qcert.\n            rtype_equalizer.\n            subst.\n            rewrite (rtype_ext pfl1 (proj2_sig in2)).\n            rewrite (rtype_ext pfl2 (proj2_sig in1)).\n            destruct in1; destruct in2. simpl in *.\n              trivial.\n    - destruct (sub_brands_dec brand_relation_brands b b0).\n      + left; repeat rewrite Brand_canon; eauto with qcert.\n      + right. inversion 1; subst; eauto 2.\n        * intuition.\n        * apply n.\n          repeat rewrite (canon_brands_equiv).\n          trivial.\n    - destruct (sub_brands_dec brand_relation_brands b0 b).\n      + left; repeat rewrite Brand_canon; eauto with qcert.\n      + right. inversion 1; subst; eauto 2.\n        * intuition.\n        * apply n.\n          repeat rewrite (canon_brands_equiv).\n          trivial.\n    - destruct (foreign_type_sub_dec ft ft0).\n      + left. repeat rewrite Foreign_canon.\n        apply SForeign; trivial.\n      + right; intros sub.\n        invcs sub.\n        * apply n; reflexivity.\n        * intuition.\n    - destruct (foreign_type_sub_dec ft0 ft).\n      + left. repeat rewrite Foreign_canon.\n        apply SForeign; trivial.\n      + right; intros sub.\n        invcs sub.\n        * apply n; reflexivity.\n        * intuition.\n  Defined.\n  \n  Theorem subtype_dec x y : {subtype x y} + {~ subtype x y}.\n  Proof.\n    destruct (subtype_both_dec x y) as [? _].\n    trivial.\n  Defined.\n\nEnd RSubtype.\n\nSection Misc.\n  Context  {ftype:foreign_type}.\n  Context  {br:brand_relation}.\n\n  Lemma subtype_ext {a b pfa pfb} :\n    subtype (exist _ a pfa) (exist _ b pfb) ->\n    forall pfa' pfb',\n      subtype (exist _ a pfa') (exist _ b pfb').\n  Proof.\n    intros.\n    rewrite (rtype_ext pfa' pfa).\n    rewrite (rtype_ext pfb' pfb).\n    trivial.\n  Qed.\n\n  Lemma subtype_Either_inv {τl τr τl' τr'} :\n    subtype (Either τl τr) (Either τl' τr') ->\n    subtype τl τl'  /\\\n    subtype τr τr'.\n  Proof.\n    inversion 1; rtype_equalizer; subst.\n    - subst; split; econstructor.\n    - subst. intuition.\n  Qed.\n\n  Lemma subtype_Arrow_inv {τl τr τl' τr'} :\n    subtype (Arrow τl τr) (Arrow τl' τr') ->\n    subtype τl' τl  /\\\n    subtype τr τr'.\n  Proof.\n    inversion 1; rtype_equalizer; subst.\n    - subst; split; econstructor.\n    - subst. intuition.\n  Qed.\n\n  Definition check_subtype_pairs (l:list (rtype*rtype)) : bool\n    := forallb (fun τs => if subtype_dec (fst τs) (snd τs) then true else false) l.\n\n  Definition enforce_unary_op_schema (ts1:rtype*rtype) (tr:rtype)\n    : option (rtype*rtype)\n    := if check_subtype_pairs (ts1::nil)\n       then Some (tr, (snd ts1))\n       else None.\n\n  Definition enforce_binary_op_schema (ts1:rtype*rtype) (ts2:rtype*rtype) (tr:rtype)\n    : option (rtype*rtype*rtype)\n    := if check_subtype_pairs (ts1::ts2::nil)\n       then Some (tr, (snd ts1), (snd ts2))\n       else None.\n\nEnd Misc.\n\nNotation \"r1 <: r2\" := (subtype r1 r2) (at level 70).\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/TypeSystem/RSubtype.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442250928250376, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.299501257972527}}
{"text": "Require Import LanguageUtil.\nRequire Import BasicProperties.\nRequire Import Properties.\nRequire Import KindProperties.\n\nLemma wf_never_bind_box : forall Γ x,\n    ⊢ Γ -> not (x : BOX ∈ Γ).\nProof.\n  intros. intro.\n  apply binds_inversion in H0 as (Γ1 & Γ2 & E). subst.\n  apply wf_ctx_type_correct in H as (k & Sub).\n  eapply box_never_welltype. eassumption.\nQed.\n\nLtac box_welltype_contradiction :=\n  repeat progress\n    match goal with\n    | H : _ ⊢ BOX <: BOX : _ |- _ => contradict H; apply box_never_welltype\n    | H : _ : BOX ∈ _ |- _ => contradict H; apply wf_never_bind_box; eauto\n    | H : _ ⊢ BOX <: _ : _ |- _ => apply reflexivity_l in H\n    | H : _ ⊢ _ <: BOX : _ |- _ => apply reflexivity_r in H\n    end\n.\n\nLemma open_is_box_rec : forall e1 e2 n,\n    e1 <n> ^^ e2 = BOX -> e1 = BOX \\/ e2 = BOX.\nProof.\n  induction e1; simpl; intros; try solve [inversion H]; auto.\n  - destruct (n0 == n); eauto.\nQed.\n\nLemma open_is_box : forall e1 e2,\n    e1 ^^ e2 = BOX -> e1 = BOX \\/ e2 = BOX.\nProof.\n  intros. eapply open_is_box_rec. eauto.\nQed.\n\nLemma open_var_is_box : forall e x,\n    e ^` x = BOX -> e = BOX.\nProof.\n  intros. apply open_is_box in H. destruct H. auto. inversion H.\nQed.\n\nLemma head_kind_box_impossible : forall Γ e1 e2 A n,\n    Γ ⊢ e1 <: e2 : A -> head_kind A k_box n -> A = BOX \\/ False.\nProof.\n  intros.\n  apply type_correctness in H.\n  destruct H as [E | (k & Sub)].\n  + auto.\n  + eauto using head_kind_box_never_welltype.\nQed.\n\nLemma pi_head_box_impossible : forall Γ e1 e2 A,\n    not (Γ ⊢ e1 <: e2 : e_pi A BOX).\nProof.\n  intros. intro. eapply head_kind_box_impossible in H.\n  - destruct H. inversion H. auto.\n  - constructor. apply h_kind. Unshelve. exact 0.\nQed.\n\nLtac solve_open_is_box :=\n  repeat\n    match goal with\n    | H : _ ^^ _ = BOX |- _ => apply open_is_box in H as [|]; subst\n    | H : _ ⊢ _ <: _ : e_pi _ BOX |- _ => contradict H; apply pi_head_box_impossible\n    | _ => solve [box_welltype_contradiction]\n    end\n.\n\nLemma box_only_head_kind_star : forall Γ e,\n    Γ ⊢ e : BOX -> exists n, head_kind e k_star n.\nProof.\n  intros.\n  dependent induction H; box_welltype_contradiction; instantiate_cofinites.\n  (* star *)\n  - exists 0. eauto.\n  (* pi *)\n  - instantiate_trivial_equals.\n    destruct H1. apply head_kind_invert_subst_var in H1. eauto.\n  (* app impossible *)\n  - solve_open_is_box.\nQed.\n\nLemma box_never_reduce : forall Γ e,\n    Γ ⊢ e : BOX -> forall e', not (e ⟶ e').\nProof.\n  intros * Sub.\n  dependent induction Sub; intros; intro R;\n    try solve [inversion R | box_welltype_contradiction].\n  (* r_app *)\n  - solve_open_is_box.\nQed.\n\nLemma castup_box_never_welltype : forall Γ A B,\n    not (Γ ⊢ e_castup A BOX : B).\nProof.\n  intros. intro.\n  dependent induction H.\n  - box_welltype_contradiction.\n  - eauto.\nQed.\n\nLemma app_box_never_welltype : forall Γ f1 f2 A,\n    not (Γ ⊢ e_app f1 BOX <: e_app f2 BOX : A).\nProof.\n  intros. intro.\n  dependent induction H.\n  - box_welltype_contradiction.\n  - eauto.\nQed.\n\nLemma lambda_box_never_welltype : forall Γ A B,\n    not (Γ ⊢ e_abs A BOX : B).\nProof.\n  intros. intro.\n  dependent induction H.\n  - instantiate_cofinites. unfold open_expr_wrt_expr in *. simpl in *.\n    box_welltype_contradiction.\n  - eauto.\nQed.\n\nLemma app_of_box_impossible : forall Γ e1 e2 e,\n    not (Γ ⊢ e_app e1 e <: e_app e2 e : BOX).\nProof.\n  intros. intro.\n  inversion H; subst.\n  - solve_open_is_box.\n  - box_welltype_contradiction.\nQed.\n\nLemma castdn_of_box_impossible : forall Γ e1 e2,\n    not (Γ ⊢ e_castdn e1 <: e_castdn e2 : BOX).\nProof.\n  intros. intro.\n  inversion H; box_welltype_contradiction.\nQed.\n\nLtac find_typing_refl_of e H1 :=\n  match goal with\n  | H : _ ⊢ e : _ |- _ => rename H into H1\n  | H : _ ⊢ e <: _ : _ |- _ =>\n    pose proof H as H1; apply reflexivity_l in H1\n  | H : _ ⊢ _ <: e : _ |- _ =>\n    pose proof H as H1; apply reflexivity_r in H1\n  end\n.\n\nLtac conclude_head_kind_of e H := repeat\n  match goal with\n  | _ : head_kind  e _ _ |- _ => fail 1\n  | _ : head_kind' e _   |- _ => fail 1\n  | _ =>\n    match goal with\n    | H1 : _ ⊢ e : BOX |- _ =>\n      let n := fresh \"n\" in\n      apply box_only_head_kind_star in H1 as [n H]\n    | H1 : _ ⊢ e <: _ : BOX |- _ =>\n      pose proof H1 as H; apply reflexivity_l in H\n    | H1 : _ ⊢ _ <: e : BOX |- _ =>\n      pose proof H1 as H; apply reflexivity_r in H\n    end\n  end\n.\n\nHint Resolve head_kind_box_never_welltype : box.\n\n\nLtac box_reasoning :=\n  repeat\n    progress match goal with\n    (* base cases *)\n    | _ =>\n      solve [box_welltype_contradiction | eauto 3 with box]\n    | H : _ ⊢ _ <: _ : e_pi BOX _ |- _ =>\n      apply pi_box_impossible in H; contradiction\n    | H : _ ⊢ e_app ?e1 ?e <: e_app ?e2 ?e : BOX |- _ =>\n      apply app_of_box_impossible in H; contradiction\n    | H : _ ⊢ e_castup _ BOX : _ |- _ =>\n      apply castup_box_never_welltype in H; contradiction\n    | H : _ ⊢ e_app _ BOX <: e_app _ BOX : _ |- _ =>\n      apply app_box_never_welltype in H; contradiction\n    | H : _ ⊢ e_abs _ BOX : _ |- _ =>\n      apply lambda_box_never_welltype in H; contradiction\n    | H : _ ⊢ e_castdn _ <: e_castdn _ : BOX |- _ =>\n      apply castdn_of_box_impossible in H; contradiction\n    (* reasoning *)\n    | H1 : head_kind ?e _ _ |- _ =>\n      match goal with\n      (* if hypothesis exists in the form of binded expression *)\n      | _ : _ ⊢ e ^` _ : BOX |- _ => fail 1\n      | _ : _ ⊢ e ^` ?x : _ |- _ => apply head_kind_subst_var with (x := x) in H1\n      end\n    | H1 : head_kind ?e k_star _ |- _ =>\n      match goal with\n      | _ : _ ⊢ e      : BOX |- _ => fail 1\n      | _ : _ ⊢ e : ?A |- _ =>\n        let E := fresh \"E\" in\n        assert (E : A = BOX) by eauto using head_kind_star_of_box;\n        discharge_equality E\n      | H : _ ⊢ e <: _ : _ |- _ => apply reflexivity_l in H\n      | H : _ ⊢ _ <: e : _ |- _ => apply reflexivity_r in H\n      end\n    | H1 : head_kind ?e k_box _ |- _ =>\n      let H2 := fresh H1 in\n      find_typing_refl_of e H2;\n      eapply head_kind_box_never_welltype in H2; [easy | eauto]\n    | H : head_kind (?e1 ^^ ?e2) _ _ |- _ =>\n      apply head_kind_invert_subst in H as [H | H]; try solve [inversion H]\n    | E : ?e ^` _ = BOX |- _ =>\n      apply open_var_is_box in E; discharge_equality E\n    | E : ?e1 ^^ ?e2 = BOX |- _ =>\n      apply open_is_box in E as [E | E]; discharge_equality E\n    | H : _ ⊢ ?e : BOX |- _ => conclude_head_kind_of e H\n    | H : _ ⊢ ?e1 <: ?e2 : BOX |- _ =>\n      match goal with\n      | _ =>\n        let H1 := fresh \"H\" in\n        let H2 := fresh \"H\" in\n        conclude_head_kind_of e1 H1; conclude_head_kind_of e2 H2\n      end\n    end\n.\n\nLemma app_head_kind_impossible : forall Γ f1 f2 e A,\n    Γ ⊢ e_app f1 e <: e_app f2 e : A -> forall n k, head_kind e k n -> False.\nProof.\n  intros.\n  dependent induction H.\n  - destruct k; box_reasoning.\n  - eauto 2.\nQed.\n\nLemma lambda_head_kind_impossible : forall Γ A e B,\n    Γ ⊢ e_abs A e : B -> forall n k, head_kind e k n -> False.\nProof.\n  intros.\n  dependent induction H.\n  - instantiate_cofinites.\n    destruct k; box_reasoning.\n  - eauto 2.\nQed.\n\nLemma mu_head_kind_impossible : forall Γ A e B,\n    Γ ⊢ e_mu A e : B -> forall n k, head_kind e k n -> False.\nProof.\n  intros.\n  dependent induction H.\n  - instantiate_cofinites. destruct k0; box_reasoning.\n  - eauto 2.\nQed.\n\nLemma castup_head_kind_box_impossible : forall Γ A e B,\n    Γ ⊢ e_castup A e : B -> forall n, head_kind e k_box n -> False.\nProof.\n  intros.\n  dependent induction H.\n  - eauto using head_kind_box_never_welltype.\n  - eauto.\nQed.\n\nHint Resolve app_head_kind_impossible : box.\nHint Resolve lambda_head_kind_impossible : box.\nHint Resolve castup_head_kind_box_impossible : box.\nHint Resolve mu_head_kind_impossible : box.\n\nLemma box_never_be_reduced : forall e e',\n    e ⟶ e' -> forall n, head_kind e' k_box n -> forall Γ A, Γ ⊢ e : A -> False.\nProof with eauto 2 with box.\n  intros * R.\n  dependent induction R; intros.\n  (* r_app *)\n  - inversion H0.\n  (* r_beta *)\n  - box_reasoning.\n    + dependent induction H3...\n  (* r_inst *)\n  - inversion H3.\n  (* r_mu *)\n  - box_reasoning.\n  (* r_castdn *)\n  - inversion H.\n  (* r_cast_inst *)\n  - inversion H2.\n  (* r_cast_elim *)\n  - dependent induction H2...\nQed.\n\nHint Resolve box_never_be_reduced : box.\n\nLemma expr_of_box_never_be_reduced' : forall e' e,\n    e' ⟶ e -> forall Γ A, Γ ⊢ e : BOX -> forall Γ', Γ' ⊢ e' : A -> False.\nProof.\n  intros * R.\n  induction R; intros.\n  (* r_app *)\n  - box_reasoning.\n  (* r_beta *)\n  - dependent induction H3; box_reasoning.\n  (* r_inst *)\n  - box_reasoning.\n  (* r_mu *)\n  - box_reasoning.\n  (* r_castdn *)\n  - box_reasoning.\n  (* r_inst *)\n  - box_reasoning.\n  (* r_cast_elim *)\n  - dependent induction H2.\n    + clear IHusub1 IHusub2 H2.\n      dependent induction H2_0; box_reasoning.\n      Unshelve. exact 0.\n    + eauto 2.\nQed.\n\nHint Resolve expr_of_box_never_be_reduced' : box.\n", "meta": {"author": "VinaLx", "repo": "dependent-polymorphic-subtyping", "sha": "1a00b61a07e0198d417cf12727067bb1cf7187eb", "save_path": "github-repos/coq/VinaLx-dependent-polymorphic-subtyping", "path": "github-repos/coq/VinaLx-dependent-polymorphic-subtyping/dependent-polymorphic-subtyping-1a00b61a07e0198d417cf12727067bb1cf7187eb/src/proofs/BoxReasoning.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.29940597603736574}}
{"text": "Require Import Coq.Strings.String Coq.Numbers.Natural.Peano.NPeano Coq.NArith.BinNat Coq.omega.Omega Coq.Setoids.Setoid Coq.Classes.RelationPairs Coq.Lists.SetoidList.\nRequire Export PrefixSerializableDefinitions.\nRequire Import Common.\n\nSet Implicit Arguments.\n\nLocal Open Scope list_scope.\nLocal Open Scope bool_scope.\nLocal Open Scope string_scope.\n\nLemma from_to_string_append_1 {A R} `{PrefixSerializable A R} x s : option_lift_relation R (fst (from_string (to_string x ++ s))) (Some x).\nProof.\n  apply prefix_closed_1.\n  apply from_to_string_1.\nQed.\n\nLemma from_to_string_append_2 {A R} `{PrefixSerializable A R} x s : snd (from_string (to_string x ++ s)) = s.\nProof.\n  erewrite prefix_closed_2 by apply from_to_string_1.\n  rewrite from_to_string_2; reflexivity.\nQed.\n\nLemma from_to_string_append_1_eq {A} `{PrefixSerializable A eq} x s\n: fst (from_string (to_string x ++ s)) = Some x.\nProof.\n  apply prefix_closed_1_eq.\n  apply from_to_string_1_eq.\nQed.\n\nLocal Arguments Ascii.ascii_dec !_ !_ / .\n\nInstance Serializable_bool : Serializable bool\n  := {| to_string b := if b : bool then \"1\" else \"0\" |}.\nInstance Deserializable_bool : Deserializable bool\n  := {| from_string x := match x with\n                           | \"\" => (None, \"\")\n                           | String a s' => if Ascii.ascii_dec a \"1\"\n                                            then (Some true, s')\n                                            else if Ascii.ascii_dec a \"0\"\n                                                 then (Some false, s')\n                                                 else (None, x)\n                         end |}.\n\nInstance PrefixSerializable_bool {R} `{Reflexive bool R}\n: PrefixSerializable bool R\n  := {| serialize := _; deserialize := _ |}.\nProof.\n  intros []; split; reflexivity.\n  abstract (\n      intro s1; induction s1; intros;\n      repeat match goal with\n               | _ => progress cleanup\n               | [ b : bool |- _ ] => destruct b\n               | _ => progress simpl in *\n               | _ => progress unfold from_string, to_string in *\n               | [ |- appcontext[prefix _ ?s] ] => (atomic s; destruct s)\n               | [ H : appcontext[prefix _ ?s] |- _ ] => (atomic s; destruct s)\n               | [ |- appcontext[Ascii.ascii_dec ?a ?b] ] => destruct (Ascii.ascii_dec a b)\n               | [ H : appcontext[Ascii.ascii_dec ?a ?b] |- _ ] => destruct (Ascii.ascii_dec a b)\n             end\n    ).\nDefined.\n\nLocal Opaque Serializable_bool.\nLocal Opaque Deserializable_bool.\n\nFixpoint string_of_Npositive (n : positive) : string :=\n  match n with\n    | xH => \"1\"\n    | xI n' => string_of_Npositive n' ++ \"1\"\n    | xO n' => string_of_Npositive n' ++ \"0\"\n  end.\n\nDefinition string_of_N (n : N) : string :=\n  match n with\n    | N0 => \"0 \"\n    | Npos n' => string_of_Npositive n' ++ \" \"\n  end.\n\nFixpoint N_of_string_helper (s : string) (so_far : N) (acc : string) : option N * string :=\n  match s with\n    | \"\" => (None, acc)\n    | String a s' => if Ascii.ascii_dec a \" \"\n                     then (Some so_far, s')\n                     else if Ascii.ascii_dec a \"0\"\n                          then N_of_string_helper s' (2 * so_far) (acc ++ String a \"\")\n                          else if Ascii.ascii_dec a \"1\"\n                               then N_of_string_helper s' (1 + 2 * so_far) (acc ++ String a \"\")\n                               else (None, acc ++ String a s')\n  end.\n\nDefinition N_of_string (s : string) : option N * string := N_of_string_helper s 0 \"\".\n\nArguments string_of_N !n / .\nArguments N_of_string !s / .\nArguments N_of_string_helper !s so_far acc / .\n\nLemma string_append_assoc (s1 s2 s3 : string) : (s1 ++ s2) ++ s3 = s1 ++ (s2 ++ s3).\nProof.\n  revert s2 s3.\n  induction s1; simpl; trivial.\n  intros; f_equal; eauto.\nQed.\n\nLocal Ltac N_str_append_t IH :=\n  repeat match goal with\n           | _ => progress simpl in *\n           | _ => progress cleanup\n           | _ => progress subst\n           | _ => intro\n           | [ |- appcontext[Ascii.ascii_dec ?a ?b] ] => destruct (Ascii.ascii_dec a b)\n           | [ H : appcontext[Ascii.ascii_dec ?a ?b] |- _ ] => destruct (Ascii.ascii_dec a b)\n           | [ H : _ |- _ ] => rewrite H by assumption\n           | [ |- appcontext[match ?E with _ => _ end] ] => atomic E; destruct E\n           | _ => rewrite !string_append_assoc\n           | _ => rewrite IH; clear IH\n         end.\n\nLemma N_of_string_append0 (s1 : string) (n1 : N) so_far acc\n      (H1 : N_of_string_helper (s1 ++ \" \") so_far acc = (Some n1, \"\"))\n      (H1' : N_of_string_helper s1 so_far acc = (None, acc ++ s1))\n: N_of_string_helper (s1 ++ \"0 \") so_far acc = (Some (2 * n1)%N, \"\").\nProof.\n  generalize dependent so_far; generalize dependent acc.\n  induction s1; simpl in *;\n  N_str_append_t IHs1.\nQed.\n\nLemma N_of_string_append1 (s1 : string) (n1 : N) so_far acc\n      (H1 : N_of_string_helper (s1 ++ \" \") so_far acc = (Some n1, \"\"))\n      (H1' : N_of_string_helper s1 so_far acc = (None, acc ++ s1))\n: N_of_string_helper (s1 ++ \"1 \") so_far acc = (Some (1 + 2 * n1)%N, \"\").\nProof.\n  generalize dependent so_far; generalize acc;\n  induction s1; simpl in *;\n  N_str_append_t IHs1.\nQed.\n\nDelimit Scope char_scope with char.\nBind Scope char_scope with Ascii.ascii.\n\nFixpoint string_contains_ascii (s : string) (a : Ascii.ascii) : bool :=\n  match s with\n    | \"\" => false\n    | String a' s' => if Ascii.ascii_dec a a'\n                      then true\n                      else string_contains_ascii s' a\n  end.\n\nLemma string_contains_ascii_append s1 s2 a\n: string_contains_ascii (s1 ++ s2) a = string_contains_ascii s1 a || string_contains_ascii s2 a.\nProof.\n  induction s1; simpl; trivial.\n  rewrite IHs1; clear IHs1.\n  edestruct Ascii.ascii_dec; trivial.\nQed.\n\nLemma string_append_empty s : s ++ \"\" = s.\nProof.\n  induction s; eauto; simpl.\n  rewrite IHs; trivial.\nQed.\n\nLemma N_of_string_of_string_of_N_None s so_far acc\n: string_contains_ascii s \" \" = false\n  -> N_of_string_helper s so_far acc = (None, acc ++ s).\nProof.\n  revert so_far acc.\n  induction s; simpl; trivial; intros;\n  repeat match goal with\n           | _ => progress cleanup\n           | _ => progress simpl in *\n           | [ |- appcontext[Ascii.ascii_dec ?a ?b] ] => destruct (Ascii.ascii_dec a b)\n           | [ H : appcontext[Ascii.ascii_dec ?a ?b] |- _ ] => destruct (Ascii.ascii_dec a b)\n           | _ => rewrite !string_append_assoc\n           | _ => rewrite !string_append_empty\n           | _ => rewrite IHs; clear IHs\n           | _ => solve [ auto ]\n         end.\nQed.\n\nLemma N_of_string_helper_string_of_Npositive n so_far acc\n: N_of_string_helper (string_of_Npositive n) so_far acc = (None, acc ++ string_of_Npositive n).\nProof.\n  apply N_of_string_of_string_of_N_None.\n  induction n; simpl; rewrite ?string_contains_ascii_append; try rewrite IHn; reflexivity.\nQed.\n\nLemma N_of_string_of_string_of_N_helper n acc\n: N_of_string_helper (string_of_N n) 0 acc = (Some n, \"\").\nProof.\n  revert n.\n  repeat match goal with\n           | _ => progress simpl in *\n           | _ => reflexivity\n           | [ |- forall s : string, _ ] => intro\n           | [ |- forall n : N, _ ] => intros []\n           | [ |- forall p : positive, _ ] => let p := fresh in intro p; induction p\n           | _ => rewrite string_append_assoc; progress simpl\n           | _ => erewrite N_of_string_append1 by first [ eassumption | apply N_of_string_helper_string_of_Npositive ]\n           | _ => erewrite N_of_string_append0 by first [ eassumption | apply N_of_string_helper_string_of_Npositive ]\n         end.\nQed.\n\nLemma N_of_string_of_string_of_N n\n: N_of_string (string_of_N n) = (Some n, \"\").\nProof.\n  apply N_of_string_of_string_of_N_helper.\nQed.\n\nLemma N_of_string_of_string_of_N'' n acc\n: N_of_string_helper (string_of_Npositive n ++ \" \") 0 acc = (Some (N.pos n), \"\").\nProof.\n  apply (N_of_string_of_string_of_N_helper (N.pos n)).\nQed.\n\nLemma N_of_string_of_string_of_N' n\n: N_of_string (string_of_Npositive n ++ \" \") = (Some (N.pos n), \"\").\nProof.\n  apply (N_of_string_of_string_of_N_helper (N.pos n)).\nQed.\n\nInstance Serializable_N : Serializable N\n  := {| to_string := string_of_N |}.\nInstance Deserializable_N : Deserializable N\n  := {| from_string := N_of_string |}.\n\nInstance PrefixSerializable_N {R} `{Reflexive N R} : PrefixSerializable N R\n  := {| serialize := _; deserialize := _ |}.\nProof.\n  abstract (intros; simpl; rewrite N_of_string_of_string_of_N; split; reflexivity).\n  abstract (\n      unfold to_string, from_string; simpl; unfold N_of_string;\n      intro s1; set (so_far := 0%N); set (acc := \"\"); generalize so_far; generalize acc; clear; induction s1;\n      repeat match goal with\n               | _ => progress simpl in *\n               | _ => intro\n               | _ => progress cleanup\n               | [ |- appcontext[Ascii.ascii_dec ?a ?b] ] => destruct (Ascii.ascii_dec a b)\n               | [ H : appcontext[Ascii.ascii_dec ?a ?b] |- _ ] => destruct (Ascii.ascii_dec a b)\n               | _ => solve [ eauto ]\n             end\n    ).\nDefined.\n\nLocal Opaque Serializable_N.\nLocal Opaque Deserializable_N.\n\nExisting Instance eq_Reflexive. (* we want this, not [N.divide_reflexive] *)\n\nDefinition prod_map {A A' B B'} (f : A -> A') (g : B -> B') : A * B -> A' * B'\n  := fun xy => (f (fst xy), g (snd xy)).\n\nArguments prod_map / .\n\nInstance Serializable_nat : Serializable nat\n  := {| to_string x := to_string (N.of_nat x) |}.\nInstance Deserializable_nat : Deserializable nat\n  := {| from_string x := prod_map (option_map N.to_nat) (fun x => x) (from_string x) |}.\n\nInstance PrefixSerializable_nat {R} `{Reflexive nat R} : PrefixSerializable nat R\n  := {| serialize := _; deserialize := _ |}.\nProof.\n  abstract (\n      intro;\n      simpl rewrite (@from_to_string_1_eq N _);\n      simpl rewrite (@from_to_string_2 N _ _);\n      simpl; rewrite Nnat.Nat2N.id;\n      split; reflexivity\n    ).\n  abstract (\n      set (R' := fun a b => R (N.to_nat a) (N.to_nat b));\n      assert (Reflexive R') by (repeat intro; hnf; reflexivity);\n      simpl; intros s1 s2 x H1;\n      pose proof (prefix_closed_1 (R := R') s1 s2 (N.of_nat x)) as H';\n      pose proof (prefix_closed_2 (R := R') s1 s2 (N.of_nat x)) as H'';\n      repeat match goal with\n               | _ => progress simpl in *\n               | _ => progress cleanup\n               | _ => progress unfold R', option_lift_relation, option_map in *\n               | [ H : _ |- _ ] => rewrite !Nnat.Nat2N.id in H\n               | [ H : appcontext[match fst (from_string (A := ?A) ?s1) with _ => _ end] |- _ ]\n                 => revert H; case_eq (fst (from_string (A := A) s1)); intros\n             end\n    ).\nDefined.\n\nLocal Opaque Serializable_nat.\nLocal Opaque Deserializable_nat.\n\nLemma leb_xx x : x <=? x = true.\nProof.\n  induction x; trivial.\nQed.\n\nLemma substring_length x : substring 0 (String.length x) x = x.\nProof.\n  induction x; trivial; simpl.\n  rewrite IHx; trivial.\nQed.\n\nLemma substring_length' x n : substring (String.length x) n x = \"\".\nProof.\n  induction x; trivial; simpl.\n  destruct n; trivial.\nQed.\n\nLemma string_length_append s1 s2 : String.length (s1 ++ s2) = String.length s1 + String.length s2.\nProof.\n  revert s2.\n  induction s1; simpl; trivial; eauto.\nQed.\n\nLemma substring_length_append s1 s2 : substring 0 (String.length s1) (s1 ++ s2) = s1.\nProof.\n  induction s1; simpl.\n  { destruct s2; trivial. }\n  { f_equal; eauto. }\nQed.\n\nFixpoint string_drop n (s : string) : string :=\n  match n, s with\n    | 0, s => s\n    | S n', String _ s' => string_drop n' s'\n    | _, \"\" => \"\"\n  end.\n\nLemma string_drop_le_append n s1 s2 (H : n <= String.length s1)\n: string_drop n (s1 ++ s2) = string_drop n s1 ++ s2.\nProof.\n  revert n s2 H.\n  induction s1; intros; simpl; trivial.\n  { destruct n; simpl; trivial; inversion H. }\n  { destruct n; simpl in *; trivial.\n    apply le_S_n in H.\n    apply IHs1; auto. }\nQed.\n\nLemma substring_le s s' a b (H : a + b <= String.length s) : substring a b (s ++ s') = substring a b s.\nProof.\n  revert a b s' H; induction s; intros; simpl in *.\n  { destruct a, b, s'; simpl in *; trivial;\n    omega. }\n  { repeat match goal with\n             | [ |- appcontext[match ?E with _ => _ end] ] => atomic E; destruct E\n             | _ => reflexivity\n             | _ => progress simpl in *\n             | [ H : S _ <= S _ |- _ ] => apply le_S_n in H\n           end;\n    try (rewrite IHs; clear IHs);\n    simpl; trivial. }\nQed.\n\nInstance Serializable_string : Serializable string\n  := {| to_string x := to_string (String.length x) ++ x |}.\nInstance Deserializable_string : Deserializable string\n  := {| from_string x := let nx := from_string (A := nat) x in\n                         match fst nx with\n                           | Some n => if (n <=? String.length (snd nx))\n                                       then (Some (substring 0 n (snd nx)), string_drop n (snd nx))\n                                       else (None, x)\n                           | None => (None, (snd nx))\n                         end |}.\n\nInstance PrefixSerializable_string {R} `{Reflexive string R} : PrefixSerializable string R\n  := {| serialize := _; deserialize := _ |}.\nProof.\n  abstract (\n      intro x; induction x; trivial;\n      repeat match goal with\n               | [ H : _ |- _ ] => progress rewrite ?substring_length in H |- *\n               | [ H : _ |- _ ] => progress rewrite ?substring_length' in H |- *\n               | [ H : _ |- _ ] => progress rewrite ?leb_xx in H |- *\n               | [ H : _ |- _ ] => simpl rewrite from_to_string_append_1_eq in H\n               | [ H : _ |- _ ] => simpl rewrite from_to_string_append_2 in H\n               | _ => simpl rewrite from_to_string_append_1_eq\n               | _ => simpl rewrite from_to_string_append_2\n               | _ => progress simpl in *\n               | _ => progress cleanup\n             end\n    ).\n  abstract (\n      cbv zeta; intros;\n      repeat match goal with\n               | [ H : appcontext[match ?E with None => _ | _ => _ end] |- _ ]\n                 => (let H' := fresh in\n                     case_eq E;\n                     [ intros ? H'; rewrite H' in H\n                     | intro H'; rewrite H' in H ])\n               | _ => (simpl rewrite (@prefix_closed_1_eq _ _ _ _ _); [ | eassumption ])\n               | _ => (simpl rewrite (@prefix_closed_2_refl _ _ _ _ _ _ _); [ | eassumption ])\n               | _ => progress cleanup\n               | _ => rewrite string_length_append\n               | _ => progress simpl in *\n               | _ => intro\n               | [ H : (_ <=? _) = true |- _ ] => apply leb_le in H\n               | [ H : appcontext[if ?E then _ else _] |- _ ] => (revert H; case_eq E)\n               | [ H : _ <= _ |- _ ] => rewrite (proj2 (@leb_le _ _) (Plus.le_plus_trans _ _ _ H))\n               | _ => rewrite substring_le by assumption\n               | _ => rewrite string_drop_le_append by assumption\n             end\n    ).\nDefined.\n\nLocal Opaque Serializable_string.\nLocal Opaque Deserializable_string.\n\nInstance Serializable_unit : Serializable unit\n  := {| to_string x := \"\" |}.\nInstance Deserializable_unit : Deserializable unit\n  := {| from_string s := (Some tt, s) |}.\nInstance PrefixSerializable_unit {R} `{Reflexive unit R}\n: PrefixSerializable unit R\n  := {| serialize := _; deserialize := _ |}.\nProof.\n  intros []; split; reflexivity.\n  intros ? ? []; split; reflexivity.\nDefined.\n\nInstance Serializable_True : Serializable True\n  := {| to_string x := \"\" |}.\nInstance Deserializable_True : Deserializable True\n  := {| from_string s := (Some I, s) |}.\nInstance PrefixSerializable_True {R} `{Reflexive True R}\n: PrefixSerializable True R\n  := {| serialize := _; deserialize := _ |}.\nProof.\n  intros []; split; reflexivity.\n  intros ? ? []; split; reflexivity.\nDefined.\n\nInstance Serializable_Empty_set : Serializable Empty_set\n  := {| to_string x := \"\" |}.\nInstance Deserializable_Empty_set : Deserializable Empty_set\n  := {| from_string s := (None, s) |}.\nInstance PrefixSerializable_Empty_set {R}\n: PrefixSerializable Empty_set R\n  := {| serialize := _; deserialize := _ |}.\nProof.\n  intros [].\n  intros ? ? [].\nDefined.\n\n\nInstance Serializable_False : Serializable False\n  := {| to_string x := \"\" |}.\nInstance Deserializable_False : Deserializable False\n  := {| from_string s := (None, s) |}.\nInstance PrefixSerializable_False {R}\n: PrefixSerializable False R\n  := {| serialize := _; deserialize := _ |}.\nProof.\n  intros [].\n  intros ? ? [].\nDefined.\n\n\nDefinition Serializable_sum {A B} `{Serializable A, Serializable B} : Serializable (A + B)\n  := {| to_string x := match x with\n                         | inl x' => \"L\" ++ to_string x'\n                         | inr x' => \"R\" ++ to_string x'\n                       end |}.\n\nDefinition Deserializable_sum {A B} `{Deserializable A, Deserializable B} : Deserializable (A + B)\n  := {| from_string s := match s with\n                           | \"\" => (None, \"\")\n                           | String a s' => if Ascii.ascii_dec a \"L\"\n                                            then prod_map (option_map (@inl _ _)) id (from_string s')\n                                            else if Ascii.ascii_dec a \"R\"\n                                                 then prod_map (option_map (@inr _ _)) id (from_string s')\n                                                 else (None, String a s')\n                         end |}.\n\nHint Extern 2 (Deserializable (sum _ _)) => apply Deserializable_sum : typeclass_instances.\nHint Extern 2 (Serializable (sum _ _)) => apply Serializable_sum : typeclass_instances.\n\nSection RelSum.\n  Context {A B}\n          (RA : relation A) (RB : relation B).\n\n  Definition RelSum : relation (A + B)\n    := fun x y => match x, y with\n                    | inl x', inl y' => RA x' y'\n                    | inr x', inr y' => RB x' y'\n                    | _, _ => False\n                  end.\n\n  Global Instance RelSum_Reflexive `{Reflexive A RA, Reflexive B RB}\n  : Reflexive RelSum.\n  Proof. lazy; intros [|]; reflexivity. Qed.\n\n  Global Instance RelSum_Symmetry `{Symmetric A RA, Symmetric B RB}\n  : Symmetric RelSum.\n  Proof. lazy; intros [|] [|]; auto. Qed.\n\n  Global Instance RelSum_Transitive `{Transitive A RA, Transitive B RB}\n  : Transitive RelSum.\n  Proof. lazy; intros [|] [|] [|]; eauto; tauto. Qed.\nEnd RelSum.\n\nDefinition PrefixSerializable_sum {A B RA RB} `{Reflexive A RA, Reflexive B RB}\n           `{PrefixSerializable A RA, PrefixSerializable B RB}\n: PrefixSerializable (A + B) (RelSum RA RB).\nProof.\n  refine {| serialize := _; deserialize := _ |}.\n  abstract (\n      intros [x|x]; simpl; rewrite from_to_string_2;\n      repeat match goal with\n               | _ => progress unfold option_map\n               | _ => intro\n               | [ R : relation ?A |- appcontext[match fst (from_string (A := ?A) (to_string ?x)) with _ => _ end] ]\n                 => (generalize (@from_to_string_1 A R _ x);\n                     case_eq (fst (from_string (A := A) (to_string x))))\n               | _ => progress simpl in *\n               | _ => progress cleanup\n             end\n    ).\n  abstract (\n      intros [|a s1] ? [x|x]; simpl; intros;\n      repeat match goal with\n               | _ => progress cleanup\n               | _ => progress simpl in *\n               | [ |- appcontext[Ascii.ascii_dec ?a ?b] ] => destruct (Ascii.ascii_dec a b)\n               | [ H : appcontext[Ascii.ascii_dec ?a ?b] |- _ ] => destruct (Ascii.ascii_dec a b)\n               | _ => progress unfold option_map in *\n               | [ H : appcontext[match ?E with None => _ | _ => _ end] |- _ ]\n                 => (revert H; case_eq E; intros)\n               | [ |- appcontext[match ?E with None => _ | _ => _ end] ]\n                 => (case_eq E; intros)\n               | _ => (simpl rewrite (@prefix_closed_1 _ _ _ _ _ _); [ | eassumption ])\n               | _ => erewrite prefix_closed_2_refl by eassumption\n               | [ H : appcontext[from_string (A := ?A) (?s1 ++ ?s2)] |- _ ]\n                 => (let H' := fresh in\n                     assert (H' := @prefix_closed_1 A _ _ s1 s2);\n                     unfold option_lift_relation in H';\n                     cleanup;\n                     solve [ eauto ])\n             end\n    ).\nDefined.\n\nHint Extern 2 (PrefixSerializable (sum _ _) _) => apply PrefixSerializable_sum : typeclass_instances.\n\nLocal Opaque Serializable_sum.\nLocal Opaque Deserializable_sum.\n\nDefinition Serializable_option {A} `{Serializable A} : Serializable (option A)\n  := {| to_string x := to_string (match x return A + unit with\n                                    | Some x' => inl x'\n                                    | None => inr tt\n                                  end) |}.\n\nDefinition Deserializable_option {A} `{Deserializable A} : Deserializable (option A)\n  := {| from_string x := let fs := from_string x in\n                         (match fst fs with\n                            | Some (inl s) => Some (Some s)\n                            | Some (inr tt) => Some None\n                            | None => None\n                          end,\n                          snd fs) |}.\n\nHint Extern 1 (Deserializable (option _)) => apply Deserializable_option : typeclass_instances.\nHint Extern 1 (Serializable (option _)) => apply Serializable_option : typeclass_instances.\n\nDefinition PrefixSerializable_option {A RA} `{Reflexive A RA}\n           `{PrefixSerializable A RA}\n: PrefixSerializable (option A) (option_lift_relation RA).\nProof.\n  refine {| serialize := _; deserialize := _ |}.\n  abstract (\n      intros [x|]; simpl; simpl rewrite (@from_to_string_2 (A + unit) _ _);\n      repeat match goal with\n               | _ => progress unfold option_lift_relation\n               | _ => intro\n               | [ |- appcontext[match fst (from_string (A := ?A) (to_string ?x)) with _ => _ end] ]\n                 => (generalize (@from_to_string_1 A _ _ x);\n                     case_eq (fst (from_string (A := A) (to_string x))))\n               | _ => progress destruct_head sum\n               | _ => progress simpl in *\n               | _ => progress cleanup\n             end\n    ).\n  abstract (\n      repeat match goal with\n               | _ => intro\n               | _ => progress cleanup\n               | _ => progress simpl in *\n               | _ => progress destruct_head option\n               | _ => progress destruct_head sum\n               | [ |- appcontext[match fst (from_string (A := ?A) ?s) with _ => _ end] ]\n                 => case_eq (fst (from_string (A := A) s))\n               | [ H : appcontext[match fst (from_string (A := ?A) ?s) with _ => _ end] |- _ ]\n                 => case_eq (fst (from_string (A := A) s))\n               | [ |- appcontext[from_string (A := ?A) _] ]\n                 => (simpl rewrite (@prefix_closed_2_refl A _ _ _ _ _ _); [ | eassumption ])\n               | _ => erewrite prefix_closed_2_refl by eassumption\n               | [ H : appcontext[from_string (A := ?A) (?s1 ++ ?s2)] |- _ ]\n                 => (let H' := fresh in\n                     assert (H' := fun x => @prefix_closed_1 A _ _ s1 s2 (inl x));\n                     let H'' := fresh in\n                     assert (H'' := fun x => @prefix_closed_1 A _ _ s1 s2 (inr x));\n                     unfold option_lift_relation, RelSum in H', H'';\n                     simpl in *;\n                       cleanup;\n                     solve [ eauto ])\n             end\n    ).\nDefined.\n\nHint Extern 1 (PrefixSerializable (option _) _) => apply PrefixSerializable_option : typeclass_instances.\n\nLocal Opaque Serializable_option.\nLocal Opaque Deserializable_option.\n\nDefinition Serializable_prod {A B} `{Serializable A, Serializable B}\n: Serializable (A * B)\n  := {| to_string x := to_string (fst x) ++ to_string (snd x) |}.\n\nDefinition Deserializable_prod {A B} `{Deserializable A, Deserializable B}\n: Deserializable (A * B)\n  := {| from_string x := let fs := from_string x in\n                         let fs' := from_string (snd fs) in\n                         match fst fs, fst fs' with\n                           | Some a, Some b => (Some (a, b), snd fs')\n                           | _, _ => (None, x)\n                         end |}.\n\nHint Extern 2 (Deserializable (prod _ _)) => apply Deserializable_prod : typeclass_instances.\nHint Extern 2 (Serializable (prod _ _)) => apply Serializable_prod : typeclass_instances.\n\nDefinition PrefixSerializable_prod {A B RA RB}\n           `{Reflexive A RA, Reflexive B RB}\n           `{PrefixSerializable A RA, PrefixSerializable B RB}\n: PrefixSerializable (A * B) (RelProd RA RB).\nProof.\n  refine {| serialize := _; deserialize := _ |}.\n  abstract (\n      repeat match goal with\n               | _ => progress unfold option_lift_relation\n               | _ => intro\n               | _ => progress destruct_head prod\n               | _ => progress unfold RelProd, relation_conjunction, predicate_intersection in *\n               | _ => progress simpl in *\n               | _ => progress cleanup\n               | _ => rewrite from_to_string_append_2\n               | _ => rewrite from_to_string_2\n               | [ |- appcontext[match fst (from_string (A := ?A) (to_string ?x ++ ?y)) with _ => _ end] ]\n                 => (generalize (@from_to_string_append_1 A _ _ x y);\n                     case_eq (fst (from_string (A := A) (to_string x ++ y))))\n               | [ |- appcontext[match fst (from_string (A := ?A) (to_string ?x)) with _ => _ end] ]\n                 => (generalize (@from_to_string_1 A _ _ x);\n                     case_eq (fst (from_string (A := A) (to_string x))))\n\n             end\n    ).\n  abstract (\n      simpl; intros s1 s2;\n      repeat match goal with\n               | _ => intro\n               | _ => progress cleanup\n               | _ => progress simpl in *\n               | _ => progress unfold RelProd, RelCompFun, relation_conjunction, predicate_intersection, option_lift_relation in *\n               | _ => erewrite prefix_closed_2_refl by eassumption\n               | [ H : _ |- _ ] => erewrite prefix_closed_2_refl in H by eassumption\n               | [ |- appcontext[match fst (from_string (A := ?A) ?s) with _ => _ end] ]\n                 => (case_eq (fst (from_string (A := A) s)))\n               | [ H : appcontext[match fst (from_string (A := ?A) ?s) with _ => _ end] |- _ ]\n                 => (revert H; case_eq (fst (from_string (A := A) s)))\n               | [ H : appcontext[from_string (A := ?A) (?s1 ++ ?s2)] |- _ ]\n                 => (let H' := fresh in\n                     assert (H' := @prefix_closed_1 A _ _ s1 s2);\n                     unfold option_lift_relation in H';\n                     simpl in *;\n                       cleanup;\n                     solve [ eauto\n                           | exfalso; eauto ])\n             end).\nDefined.\n\nHint Extern 2 (PrefixSerializable (prod _ _) _) => apply PrefixSerializable_prod : typeclass_instances.\n\nLocal Opaque Serializable_prod.\nLocal Opaque Deserializable_prod.\n\nFixpoint list_to_string_helper {A} `{Serializable A} (ls : list A) : string :=\n  match ls with\n    | nil => \"\"\n    | x::xs => to_string x ++ list_to_string_helper xs\n  end.\n\nDefinition list_to_string {A} `{Serializable A} (ls : list A) : string :=\n  to_string (List.length ls) ++ list_to_string_helper ls.\n\nFixpoint list_from_string_helper {A} `{Deserializable A} n (s : string) : option (list A) * string :=\n  match n with\n    | 0 => (Some nil, s)\n    | S n' => let fs := from_string s in\n              let fs' := list_from_string_helper n' (snd fs) in\n              match fst fs, fst fs' with\n                | Some x, Some xs => (Some (x::xs), snd fs')\n                | _, _ => (None, s)\n              end\n  end.\n\nLemma list_from_string_helper_append_1 {A R} `{Reflexive A R}\n      `{PrefixSerializable A R} n (s1 s2 : string) x\n: option_lift_relation (eqlistA R) (fst (list_from_string_helper n s1)) (Some x)\n  -> option_lift_relation (eqlistA R) (fst (list_from_string_helper n (s1 ++ s2))) (Some x).\nProof.\n  revert s1 s2 x.\n  induction n;\n    intro s1;\n    case_eq (fst (from_string (A := A) s1));\n    repeat match goal with\n             | _ => intro\n             | _ => progress cleanup\n             | _ => progress simpl in *\n             | _ => erewrite prefix_closed_2_refl by eassumption\n             | [ |- appcontext[fst (list_from_string_helper _ (?s1 ++ ?s2))] ]\n               => specialize (IHn s1 s2)\n             | _ => progress unfold option_lift_relation in *\n             | _ => erewrite prefix_closed by eassumption\n             | [ H : appcontext[match ?E with None => _ | _ => _ end] |- _ ]\n               => (revert H; case_eq E)\n             | [ |- appcontext[match ?E with None => _ | _ => _ end] ]\n               => case_eq E\n             | _ => erewrite IHn by eassumption\n             | [ H : fst (from_string (A := ?A) (?s1 ++ ?s2)) = _ |- _ ]\n               => (pose proof (@prefix_closed_1 A _ _ s1 s2);\n                   simpl in *; cleanup;\n                   simpl in *;\n                     solve [ eauto ])\n           end.\nQed.\n\nInstance eqlistA_Reflexive {A R} `{Reflexive A R} : Reflexive (eqlistA R).\nProof.\n  intro ls; induction ls; constructor; auto.\nQed.\n\nInstance eqlistA_Symmetric {A R} `{Symmetric A R} : Symmetric (eqlistA R).\nProof.\n  intro ls; induction ls; intros ls' H'; inversion H'; subst; constructor;\n  eauto.\nQed.\n\nInstance eqlistA_Transitive {A R} `{Transitive A R} : Transitive (eqlistA R).\nProof.\n  intro ls; induction ls; intros ls' ls'' H' H'';\n  inversion H'; subst; inversion H'';\n  subst; try constructor;\n  eauto;\n  try congruence.\nQed.\n\nLemma list_from_string_helper_append_2 {A R} `{Reflexive A R}\n      `{PrefixSerializable A R} n (s1 s2 : string) x\n: option_lift_relation (eqlistA R) (fst (list_from_string_helper n s1)) (Some x)\n  -> snd (list_from_string_helper (A := A) n (s1 ++ s2)) = snd (list_from_string_helper (A := A) n s1) ++ s2.\nProof.\n  revert s1 s2 x; induction n;\n  repeat match goal with\n           | _ => intro\n           | _ => progress cleanup\n           | _ => progress simpl in *\n           | [ H : _ |- _ ] => erewrite prefix_closed_2_refl in H by eassumption\n           | _ => erewrite prefix_closed_2_refl by eassumption\n           | [ H : appcontext[match ?E with None => _ | _ => _ end] |- _ ]\n             => (revert H; case_eq E)\n           | [ |- appcontext[match ?E with None => _ | _ => _ end] ]\n             => case_eq E\n           | _ => erewrite IHn\n           | [ H : fst (from_string (A := ?A) (?s1 ++ ?s2)) = _ |- _ ]\n             => (pose proof (@prefix_closed_1 A _ _ s1 s2);\n                 simpl in *; cleanup;\n                 simpl in *;\n                   solve [ eauto ])\n           | [ H : fst (list_from_string_helper (A := ?A) ?n (?s1 ++ ?s2)) = None |- _ ]\n             => (pose proof (@list_from_string_helper_append_1 A _ _ _ n s1 s2);\n                 simpl in *; cleanup;\n                 simpl in *; cleanup;\n                 solve [ exfalso; eauto ])\n           | [ H : fst (from_string (A := ?A) (?s1 ++ ?s2)) = None |- _ ]\n             => (pose proof (@prefix_closed_1 A _ _ s1 s2);\n                 simpl in *; cleanup;\n                 simpl in *; cleanup;\n                 solve [ exfalso; eauto ])\n           | [ H : _ |- _ ] => rewrite H; reflexivity\n         end.\nQed.\n\nDefinition list_from_string {A} `{Deserializable A} (s : string) : option (list A) * string :=\n  let fs := from_string (A := nat) s in\n  match fst fs with\n    | Some n => list_from_string_helper n (snd fs)\n    | None => (None, s)\n  end.\n\nArguments list_from_string / .\nArguments list_to_string / .\n\nDefinition Serializable_list {A} `{Serializable A} : Serializable (list A)\n  := {| to_string x := list_to_string x |}.\n\nDefinition Deserializable_list {A} `{Deserializable A} : Deserializable (list A)\n  := {| from_string x := list_from_string x |}.\n\nHint Extern 1 (Deserializable (list _)) => apply Deserializable_list : typeclass_instances.\nHint Extern 1 (Serializable (list _)) => apply Serializable_list : typeclass_instances.\n\nDefinition PrefixSerializable_list {A R} `{Reflexive A R}\n           `{PrefixSerializable A R}\n: PrefixSerializable (list A) (eqlistA R).\nProof.\n  refine {| serialize := _ |}.\n  unfold to_string, from_string; simpl; unfold list_from_string, list_to_string.\n  abstract (\n      intro x; induction x; trivial;\n      repeat match goal with\n               | _ => intro\n               | _ => progress cleanup\n               | [ H : _ |- _ ] => simpl rewrite (@from_to_string_append_1_eq nat _) in H\n               | [ H : _ |- _ ] => simpl rewrite (@from_to_string_append_2 nat _ _) in H\n               | _ => progress simpl in *\n               | _ => progress unfold option_lift_relation in *\n               | [ H : _ |- _ ] => (rewrite H; reflexivity)\n               | [ |- appcontext[match fst (from_string (A := ?A) (to_string ?x ++ ?y)) with _ => _ end] ]\n                 => (generalize (@from_to_string_append_1 A _ _ x y);\n                     case_eq (fst (from_string (A := A) (to_string x ++ y))))\n               | [ |- appcontext[match fst (from_string (A := ?A) (to_string ?x)) with _ => _ end] ]\n                 => (generalize (@from_to_string_1 A _ _ x);\n                     case_eq (fst (from_string (A := A) (to_string x))))\n               | [ |- appcontext[snd (from_string (A := ?A) (to_string ?x ++ ?y))] ]\n                 => simpl rewrite (@from_to_string_append_2 A _ _)\n               | [ H : appcontext[match ?E with None => _ | _ => _ end] |- _ ]\n                 => (revert H; case_eq E)\n               | _ => solve [ eauto ]\n             end\n    ).\n  unfold to_string, from_string; simpl; unfold list_from_string, list_to_string.\n  abstract (\n      intro s1;\n      case_eq (fst (from_string (A := nat) s1));\n      repeat match goal with\n               | _ => intro\n               | _ => progress cleanup\n               | _ => progress simpl in *\n               | [ H : appcontext[from_string (A := ?A) _] |- _ ]\n                 => (simpl rewrite (@prefix_closed_2_refl A _ _ _ _ _ _) in H; [ | eassumption ])\n               | [ H : _ |- _ ] => erewrite prefix_closed_2_refl in H by eassumption\n               | [ H : _ |- _ ] => simpl rewrite (@prefix_closed_1_eq nat _ _ _ _) in H; [ | eassumption ]\n               | _ => erewrite prefix_closed_2_refl by eassumption\n               | _ => simpl rewrite (@prefix_closed_2_refl nat _ _ _ _ _ _); [ | eassumption ]\n               | _ => apply list_from_string_helper_append\n               | _ => progress unfold option_lift_relation in *\n               | [ H : appcontext[match ?E with None => _ | _ => _ end] |- _ ]\n                 => (revert H; case_eq E)\n               | [ |- appcontext[match ?E with None => _ | _ => _ end] ]\n                 => (revert H; case_eq E)\n               | [ H : fst (list_from_string_helper (A := ?A) ?n (?s0 ++ ?s1)) = _ |- _ ]\n                 => (pose proof (@list_from_string_helper_append_1 A _ _ _ n s0 s1);\n                     simpl in *; cleanup;\n                     simpl in *; solve [ eauto ])\n               | [ |- _ ] => eapply list_from_string_helper_append_2\n               | [ H : _ |- _ ] => rewrite H; reflexivity\n             end\n    ).\nDefined.\n\nHint Extern 1 (PrefixSerializable (list _) _) => apply PrefixSerializable_list : typeclass_instances.\n\nLocal Opaque Serializable_list.\nLocal Opaque Deserializable_list.\n", "meta": {"author": "JasonGross", "repo": "apps", "sha": "906b9ca6f3f53e3a37a9a487a9289959f5167ba2", "save_path": "github-repos/coq/JasonGross-apps", "path": "github-repos/coq/JasonGross-apps/apps-906b9ca6f3f53e3a37a9a487a9289959f5167ba2/PrefixSerializable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2994059686330864}}
{"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 list.\nRequire Export per_props.\nRequire Export continuity_defs.\nRequire Export stronger_continuity_defs0.\nRequire Export cequiv_props.\nRequire Export terms_pi.\n\nLemma fresh_in_product {o} :\n  forall lib v (t1 t2 : @CVTerm o [v]) A x B,\n    equality lib (mkc_fresh v (mkcv_pi1 [v] t1)) (mkc_fresh v (mkcv_pi2 [v] t2)) A\n    -> equality\n         lib\n         (mkc_fresh v (mkcv_pi2 [v] t1))\n         (mkc_fresh v (mkcv_pi2 [v] t2))\n         (substc (mkc_fresh v (mkcv_pi1 [v] t1)) x B)\n    -> (forall a1 a2,\n          equality lib a1 a2 A\n          -> tequality lib (substc a1 x B) (substc a2 x B))\n    -> equality lib (mkc_fresh v t1) (mkc_fresh v t2) (mkc_product A x B).\nProof.\n  introv ea eb tb.\n  apply equality_in_product.\n  dands; auto.\n  { eapply inhabited_implies_tequality; eauto. }\n\n  Check computes_to_pair_eta_c.\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_props2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.63341027751814, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.29940257210438764}}
{"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 Import trajectory_const.\nRequire Import rrho.\nRequire Import constants.\nRequire Import Omega.\n\n(* Verifiable in MuPAD *)\nAxiom\n  Math_prop_alarm_1 :\n    forall (a l : R) (T : TimeT),\n    (MinDistance T <= l)%R ->\n    (l <= MaxDistance T)%R ->\n    (0 <= a)%R ->\n    (a <= MinBeta)%R ->\n    (Rsqr (l * cos a - v V * T) + Rsqr (l * sin a) <= Rsqr AlertRange)%R.\n\n(* Verifiable in MuPAD *)\nAxiom\n  Math_prop_no_conflict_1 :\n    forall (a l x y : R) (T : TimeT),\n    (MinDistance T <= l)%R ->\n    (l <= MaxDistance T)%R ->\n    (MinBeta <= a)%R ->\n    (a <= PI / 2)%R ->\n    (l * sin a + r_V * (cos (rho_V * T) - 1) <= y)%R ->\n    (r_V * sin (rho_V * T) - l * cos a <= x)%R ->\n    (Rsqr ConflictRange < Rsqr x + Rsqr y)%R.\n\n(**********)\nLemma MinBeta_pos : (0 < MinBeta)%R.\nunfold MinBeta in |- *; unfold Rdiv in |- *.\napply Rmult_lt_0_compat; [ prove_sup | apply Rinv_0_lt_compat; prove_sup ].\nQed.\n\n(**********)\nLemma Math_prop_y_a_PI2 :\n forall (a l : R) (T : TimeT),\n (MinBeta <= a)%R ->\n (a <= PI / 2)%R ->\n (0 <= l)%R ->\n (l * sin MinBeta + r_V * (cos (rho_V * T) - 1) <=\n  l * sin a + r_V * (cos (rho_V * T) - 1))%R. \nintros; apply Rplus_le_compat_r; apply Rmult_le_compat_l;\n [ assumption\n | apply sin_incr_1;\n    [ left; apply Rlt_trans with 0%R;\n       [ apply _PI2_RLT_0 | apply MinBeta_pos ]\n    | apply Rle_trans with a; assumption\n    | left; apply Rlt_trans with 0%R;\n       [ apply _PI2_RLT_0\n       | apply Rlt_le_trans with MinBeta; [ apply MinBeta_pos | assumption ] ]\n    | assumption\n    | assumption ] ].\nQed.\n\n(**********)\nLemma Math_prop_approx_y_a_PI2 :\n forall (a l1 l2 : R) (T : TimeT),\n (0 <= a)%R ->\n (a <= PI / 2)%R ->\n (0 <= l1)%R ->\n (l1 <= l2)%R ->\n (l1 * sin_lb a + r_ub V * (cos_lb (rho_ub V * MaxT) - 1) <=\n  l2 * sin a + r_V * (cos (rho_V * T) - 1))%R.\nintros; apply Rplus_le_compat.\napply Rle_trans with (l1 * sin a)%R.\napply Rmult_le_compat_l.\nassumption.\ngeneralize (SIN a H (Rlt_le a PI (Rle_lt_trans a (PI / 2) PI H0 PI2_Rlt_PI)));\n intro; elim H3; intros; assumption.\napply Rmult_le_compat_r.\napply (sin_ge_0 a H (Rlt_le a PI (Rle_lt_trans a (PI / 2) PI H0 PI2_Rlt_PI))).\nassumption.\nrewrite <- (Ropp_involutive (r_ub V * (cos_lb (rho_ub V * MaxT) - 1)));\n rewrite <- (Ropp_involutive (r_V * (cos (rho_V * T) - 1)));\n apply Ropp_ge_le_contravar; apply Rle_ge;\n replace (- (r_V * (cos (rho_V * T) - 1)))%R with\n  (r_V * (1 - cos (rho_V * T)))%R.\nreplace (- (r_ub V * (cos_lb (rho_ub V * MaxT) - 1)))%R with\n (r_ub V * (1 - cos_lb (rho_ub V * MaxT)))%R.\napply Rmult_le_compat.\nleft; apply r_V_is_pos.\napply Rplus_le_reg_l with (cos (rho_V * T)); rewrite Rplus_0_r;\n rewrite Rplus_comm; unfold Rminus in |- *; repeat rewrite Rplus_assoc;\n rewrite Rplus_opp_l; rewrite Rplus_0_r; generalize (COS_bound (rho_V * T));\n intro; elim H3; intros; assumption.\nunfold r_V in |- *; left; apply r_ub_0.\napply Rplus_le_reg_l with (Ropp 1); unfold Rminus in |- *;\n repeat rewrite <- Rplus_assoc; repeat rewrite Rplus_opp_l;\n repeat rewrite Rplus_0_l; apply Ropp_ge_le_contravar; \n apply Rle_ge; apply Rle_trans with (cos (rho_ub V * MaxT)).\ncut (- PI / 2 <= rho_ub V * MaxT <= PI / 2)%R.\nintro; elim H3; intros; generalize (COS (rho_ub V * MaxT) H4 H5); intro;\n elim H6; intros; assumption.\nsplit.\nleft; apply Rlt_le_trans with 0%R.\nreplace (- PI / 2)%R with (- (PI / 2))%R.\napply _PI2_RLT_0.\nunfold Rdiv in |- *; symmetry  in |- *; apply Ropp_mult_distr_l_reverse.\napply Rmult_le_pos.\nleft; apply rho_ub_pos.\nleft; unfold MaxT in |- *.\nprove_sup.\ncut (MaxT <= MaxT)%R.\nintro; left; apply (rho_ub_t_PI2 V (mkTimeT MaxT MinT_MaxT H3)).\nright; reflexivity.\napply cos_decr_1.\nleft; apply Rmult_lt_0_compat.\napply rho_V_is_pos.\napply Rlt_le_trans with MinT.\napply MinT_is_pos.\napply (cond_1 T).\nleft; apply Rlt_trans with (PI / 2)%R.\napply (rho_t_PI2 T). \napply PI2_Rlt_PI.\nleft; apply Rmult_lt_0_compat.\napply rho_ub_pos.\nunfold MaxT in |- *; prove_sup.\nleft; apply Rlt_trans with (PI / 2)%R.\ncut (MaxT <= MaxT)%R.\nintro; apply (rho_ub_t_PI2 V (mkTimeT MaxT MinT_MaxT H3)).\nright; reflexivity.\napply PI2_Rlt_PI.\napply Rmult_le_compat.\nleft; apply rho_V_is_pos.\nleft; apply Rlt_le_trans with MinT; [ apply MinT_is_pos | apply (cond_1 T) ].\nleft; unfold rho_V in |- *; apply rho_ub_0.\napply (cond_2 T).\nring.\nring.\nQed.\n\n(**********)\nLemma Math_prop_x_a_PI2 :\n forall (a l : R) (T : TimeT),\n (MinBeta <= a)%R ->\n (a <= PI / 2)%R ->\n (0 <= l)%R ->\n (r_V * sin (rho_V * T) - l * cos MinBeta <=\n  r_V * sin (rho_V * T) - l * cos a)%R.\nintros; unfold Rminus in |- *; apply Rplus_le_compat_l;\n apply Ropp_ge_le_contravar; apply Rle_ge; apply Rmult_le_compat_l;\n [ assumption\n | apply cos_decr_1;\n    [ left; apply MinBeta_pos\n    | apply Rle_trans with a;\n       [ assumption\n       | left; apply Rle_lt_trans with (PI / 2)%R;\n          [ assumption | apply PI2_Rlt_PI ] ]\n    | left; apply Rlt_le_trans with MinBeta;\n       [ apply MinBeta_pos | assumption ]\n    | left; apply Rle_lt_trans with (PI / 2)%R;\n       [ assumption | apply PI2_Rlt_PI ]\n    | assumption ] ].\nQed.\n\n(**********)\nLemma Math_prop_approx_x_a_PI2 :\n forall (a l1 l2 : R) (T : TimeT),\n (0 <= a)%R ->\n (a <= PI / 2)%R ->\n (0 <= l1)%R ->\n (l1 <= l2)%R ->\n (r_lb V * sin_lb (rho_lb V * MinT) - l2 * cos_ub a <=\n  r_V * sin (rho_V * T) - l1 * cos a)%R.\nintros; unfold Rminus in |- *; apply Rplus_le_compat.\napply Rmult_le_compat.\nleft; unfold r_lb in |- *; unfold Rdiv in |- *; apply Rmult_lt_0_compat;\n [ apply TypeSpeed_pos | apply Rinv_0_lt_compat; apply rho_ub_pos ].\napply sin_lb_ge_0.\nleft; apply Rmult_lt_0_compat; [ apply rho_lb_pos | apply MinT_is_pos ].\napply Rle_trans with (rho_V * MinT)%R.\napply Rmult_le_compat_r.\nleft; apply MinT_is_pos.\nunfold rho_V in |- *; left; apply rho_lb_0.\ncut (MinT <= MinT)%R.\nintro; left; apply (rho_t_PI2 (mkTimeT MinT H3 MinT_MaxT)).\nright; reflexivity.\nunfold r_V in |- *; left; apply r_lb_0.\napply Rle_trans with (sin (rho_lb V * MinT)).\ncut (0 <= rho_lb V * MinT <= PI)%R.\nintro; elim H3; intros.\ngeneralize (SIN (rho_lb V * MinT) H4 H5); intro; elim H6; intros; assumption.\nsplit.\nleft; apply Rmult_lt_0_compat.\napply rho_lb_pos.\napply MinT_is_pos.\nleft; apply Rle_lt_trans with (PI / 2)%R.\napply Rle_trans with (rho_V * MinT)%R.\napply Rmult_le_compat_r.\nleft; apply MinT_is_pos.\nunfold rho_V in |- *; left; apply rho_lb_0.\ncut (MinT <= MinT)%R.\nintro; left; apply (rho_t_PI2 (mkTimeT MinT H3 MinT_MaxT)).\nright; reflexivity.\napply PI2_Rlt_PI.\napply sin_incr_1.\nleft; apply Rlt_trans with 0%R.\napply _PI2_RLT_0.\napply Rmult_lt_0_compat.\napply rho_lb_pos.\napply MinT_is_pos.\napply Rle_trans with (rho_V * MinT)%R.\napply Rmult_le_compat_r.\nleft; apply MinT_is_pos.\nunfold rho_V in |- *; left; apply rho_lb_0.\ncut (MinT <= MinT)%R.\nintro; left; apply (rho_t_PI2 (mkTimeT MinT H3 MinT_MaxT)).\nright; reflexivity.\nleft; apply Rlt_trans with 0%R.\napply _PI2_RLT_0.\napply Rmult_lt_0_compat.\napply rho_V_is_pos.\napply Rlt_le_trans with MinT.\napply MinT_is_pos.\napply (cond_1 T).\nleft; apply (rho_t_PI2 T).\napply Rmult_le_compat.\nleft; apply rho_lb_pos.\nleft; apply MinT_is_pos.\nleft; unfold rho_V in |- *; apply rho_lb_0.\napply (cond_1 T).\napply Ropp_ge_le_contravar; apply Rle_ge.\napply Rmult_le_compat.\nassumption.\napply cos_ge_0.\nleft; apply Rlt_le_trans with 0%R.\napply _PI2_RLT_0.\nassumption.\nassumption.\nassumption.\ncut (- PI / 2 <= a)%R.\nintro; generalize (COS a H3 H0); intro; elim H4; intros; assumption.\nleft; apply Rlt_le_trans with 0%R.\nreplace (- PI / 2)%R with (- (PI / 2))%R.\napply _PI2_RLT_0.\nunfold Rdiv in |- *; symmetry  in |- *; apply Ropp_mult_distr_l_reverse.\nassumption.\nQed.\n\n(**********)\nLemma Math_prop_no_conflict_2 :\n forall (a l x y : R) (T : TimeT),\n (MinDistance T <= l)%R ->\n (l <= MaxDistance T)%R ->\n (3 * (PI / 2) <= a)%R ->\n (a <= 2 * PI - MinBeta)%R ->\n (y <= l * sin a - r_V * (cos (rho_V * T) - 1))%R ->\n (r_V * sin (rho_V * T) - l * cos a <= x)%R ->\n (Rsqr ConflictRange < Rsqr x + Rsqr y)%R.\nintros.\ncut (MinBeta <= 2 * PI - a)%R.\ncut (2 * PI - a <= PI / 2)%R.\ncut (l * sin (2 * PI - a) + r_V * (cos (rho_V * T) - 1) <= - y)%R.\nintros; rewrite (Rsqr_neg y);\n apply (Math_prop_no_conflict_1 (2 * PI - a) l x (- y) T H H0 H7 H6 H5).\nreplace (2 * PI - a)%R with (- a + 2 * INR 1 * PI)%R;\n [ rewrite (cos_period (- a) 1); rewrite cos_neg; assumption | simpl; ring ].\nreplace (2 * PI - a)%R with (- a + 2 * INR 1 * PI)%R;\n [ rewrite (sin_period (- a) 1); rewrite sin_neg;\n    replace (l * - sin a + r_V * (cos (rho_V * T) - 1))%R with\n     (- (l * sin a - r_V * (cos (rho_V * T) - 1)))%R;\n    [ apply Ropp_ge_le_contravar; apply Rle_ge; assumption | simpl; ring ]\n | simpl; ring ].\ngeneralize (Rplus_le_compat_l (PI / 2 - a) (3 * (PI / 2)) a H1);\n replace (PI / 2 - a + 3 * (PI / 2))%R with (2 * PI - a)%R.\nreplace (PI / 2 - a + a)%R with (PI / 2)%R.\nintro; assumption.\nunfold Rminus in |- *; rewrite Rplus_assoc; rewrite Rplus_opp_l;\n rewrite Rplus_0_r; reflexivity. \nrewrite double.\npattern PI at 1 2 in |- *; rewrite double_var.\nring.\ngeneralize (Rplus_le_compat_l (MinBeta - a) a (2 * PI - MinBeta) H2);\n replace (MinBeta - a + (2 * PI - MinBeta))%R with (2 * PI - a)%R;\n [ replace (MinBeta - a + a)%R with MinBeta; [ intro; assumption | ring ]\n | ring ].\nQed.\n\n(**********)\nLemma Math_prop_alarm_2 :\n forall (a l : R) (T : TimeT),\n (MinDistance T <= l)%R ->\n (l <= MaxDistance T)%R ->\n (2 * PI - MinBeta <= a)%R ->\n (a <= 2 * PI)%R ->\n (Rsqr (l * cos a - v V * T) + Rsqr (l * sin a) <= Rsqr AlertRange)%R.\nintros.\ncut (0 <= 2 * PI - a)%R.\ncut (2 * PI - a <= MinBeta)%R.\ncut (cos (2 * PI - a) = cos a).\ncut (sin (2 * PI - a) = (- sin a)%R).\nintros; rewrite Rsqr_mult; rewrite (Rsqr_neg (sin a)); rewrite <- H3;\n rewrite <- H4; rewrite <- Rsqr_mult;\n apply (Math_prop_alarm_1 (2 * PI - a) l T H H0 H6 H5).\nreplace (2 * PI - a)%R with (- a + 2 * INR 1 * PI)%R;\n [ rewrite (sin_period (- a) 1); apply sin_neg | simpl; ring ].\nreplace (2 * PI - a)%R with (- a + 2 * INR 1 * PI)%R;\n [ rewrite (cos_period (- a) 1); apply cos_neg | simpl; ring ].\ngeneralize (Rplus_le_compat_l (MinBeta - a) (2 * PI - MinBeta) a H1);\n replace (MinBeta - a + (2 * PI - MinBeta))%R with (2 * PI - a)%R;\n [ replace (MinBeta - a + a)%R with MinBeta; [ intro; assumption | ring ]\n | ring ].\ngeneralize (Rplus_le_compat_r (- a) a (2 * PI) H2); rewrite Rplus_opp_r;\n intro; assumption.\nQed.\n", "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/math_prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.29940255902022544}}
{"text": "Require Import Classical List Relations Peano_dec.\nRequire Import Hahn.\n\nRequire Import Basic.\n\nSet Implicit Arguments.\nRemove Hints plus_n_O.\n\nLemma step_dom A (r: relation A) d e \n  (E: r ⊆ (⦗d⦘ ∪ ⦗e⦘) ⨾ r ⨾ (⦗d⦘ ∪ ⦗e⦘))\n  dd (DD: dd = ⦗d⦘ ⨾ r ⨾ ⦗d⦘)\n  de (DE: de = ⦗d⦘ ⨾ r ⨾ ⦗e⦘)\n  ed (ED: ed = ⦗e⦘ ⨾ r ⨾ ⦗d⦘)\n  ee (EE: ee = ⦗e⦘ ⨾ r ⨾ ⦗e⦘) :\n  r ⊆ dd ∪ de ∪ ed ∪ ee.\nProof.\nrewrite E; subst; basic_solver 8.\nQed.\n\nLemma path_dom A (r: relation A) d e \n  (E1: r ⊆ (⦗d⦘ ∪ ⦗e⦘) ⨾ r ⨾ (⦗d⦘ ∪ ⦗e⦘))\n  (E2: ⦗d⦘ ⨾ ⦗e⦘ ⊆ ∅₂)\n  dd (DD: dd = ⦗d⦘ ⨾ r ⨾ ⦗d⦘)\n  de (DE: de = ⦗d⦘ ⨾ r ⨾ ⦗e⦘)\n  ed (ED: ed = ⦗e⦘ ⨾ r ⨾ ⦗d⦘)\n  ee (EE: ee = ⦗e⦘ ⨾ r ⨾ ⦗e⦘) : \n   r⁺ ⊆ (dd⁺ ∪ (dd^* ⨾ de ⨾ ee^* ⨾ ed)⁺ ⨾ dd^* ) ∪\n  (ee⁺ ∪ (ee^* ⨾ ed ⨾ dd^* ⨾ de)⁺ ⨾ ee^* ) ∪\n  (ee^* ⨾ ed ⨾ dd^* ⨾ de)^* ⨾ ee^* ⨾ ed ⨾ dd^* ∪\n  (dd^* ⨾ de ⨾ ee^* ⨾ ed)^* ⨾ dd^* ⨾ de ⨾ ee^*.\nProof. \n  apply inclusion_t_ind_right.\n- rewrite step_dom with (r:=r) (d:=d) (e:=e) at 1; try eassumption.\nrepeat apply inclusion_union_l; rewrite ?seqA.\n1,4: sin_rewrite !ct_end.\nall: try (repeat (apply inclusion_union_r; constructor); basic_solver 14).\n- rewrite step_dom with (r:=r) (d:=d) (e:=e) at 1; try eassumption.\nrelsf.\nassert (E2': ⦗e⦘ ⨾ ⦗d⦘ ⊆ (fun _ _ : A => False)).\n  by rewrite seq_eqvC in E2.\n\nassert (X17: ed ⨾ ed ⊆ ∅₂).\n  by rewrite ?DD, ?ED, ?DE, ?EE; generalize E2; basic_solver.\nassert (X18: ed ⨾ ee ⊆ ∅₂).\n  by rewrite ?DD, ?ED, ?DE, ?EE; generalize E2; basic_solver.\nassert (X19: de ⨾ dd ⊆ ∅₂).\n  by rewrite ?DD, ?ED, ?DE, ?EE; generalize E2; basic_solver.\nassert (X20: de ⨾ de ⊆ ∅₂).\n  by rewrite ?DD, ?ED, ?DE, ?EE; generalize E2; basic_solver.\nassert (X1: dd ^* ⨾ ed ⊆ ed).\n  by rewrite ?rtE; relsf; rewrite ct_end, ?seqA, ?DD, ?ED, ?DE, ?EE, ?seqA; \n    try sin_rewrite E2; try sin_rewrite E2'; relsf.\nassert (X2: dd ^* ⨾ dd ⊆ dd^* ).\n  by rewrite rt_end at 2; relsf.\nassert (X3: dd ^* ⨾ ee ⊆ ee).\n  by rewrite ?rtE; relsf; rewrite ct_end, ?seqA, ?DD, ?ED, ?DE, ?EE, ?seqA; \n    try sin_rewrite E2; try sin_rewrite E2'; relsf.\nassert (X4: ee ^* ⨾ de ⊆ de).\n  by rewrite ?rtE; relsf; rewrite ct_end, ?seqA, ?DD, ?ED, ?DE, ?EE, ?seqA; \n    try sin_rewrite E2; try sin_rewrite E2'; relsf.\nassert (X5: ee ^* ⨾ ee ⊆ ee^* ).\n  by rewrite rt_end at 2; relsf.\nassert (X6: ee ^* ⨾ dd ⊆ dd).\n  by rewrite ?rtE; relsf; rewrite ct_end, ?seqA, ?DD, ?ED, ?DE, ?EE, ?seqA; \n    try sin_rewrite E2; try sin_rewrite E2'; relsf.\nassert (X7: dd ⁺ ⨾ dd ⊆ dd⁺).\n  by rewrite ct_end at 2; rewrite inclusion_t_rt.\nassert (X8: dd ⁺ ⨾ ed ⊆ ∅₂).\n  by rewrite ?rtE; relsf; rewrite ct_end, ?seqA, ?DD, ?ED, ?DE, ?EE, ?seqA; \n    try sin_rewrite E2; try sin_rewrite E2'; relsf.\nassert (X9: dd ⁺ ⨾ ee ⊆ ∅₂).\n  by rewrite ?rtE; relsf; rewrite ct_end, ?seqA, ?DD, ?ED, ?DE, ?EE, ?seqA; \n    try sin_rewrite E2; try sin_rewrite E2'; relsf.\nassert (X10: (dd ^* ⨾ de ⨾ ee ^* ⨾ ed) ⁺ ⨾ ed ⊆ ∅₂).\n  by rewrite ct_end, ?seqA, ?DD, ?ED, ?DE, ?EE, ?seqA; \n    try sin_rewrite E2; try sin_rewrite E2'; relsf.\nassert (X11: (dd ^* ⨾ de ⨾ ee ^* ⨾ ed) ⁺ ⨾ ee ⊆ ∅₂).\n   by rewrite ct_end, ?seqA, ?DD, ?ED, ?DE, ?EE, ?seqA;\n    try sin_rewrite E2; try sin_rewrite E2'; relsf.\nassert (X12: ee ⁺ ⨾ dd ⊆ ∅₂).\n  by rewrite ?rtE; relsf; rewrite ct_end, ?seqA, ?DD, ?ED, ?DE, ?EE, ?seqA; \n    try sin_rewrite E2; try sin_rewrite E2'; relsf.\nassert (X13: ee ⁺ ⨾ de ⊆ ∅₂).\n  by rewrite ?rtE; relsf; rewrite ct_end, ?seqA, ?DD, ?ED, ?DE, ?EE, ?seqA; \n    try sin_rewrite E2; try sin_rewrite E2'; relsf.\nassert (X14: ee ⁺ ⨾ ee ⊆ ee⁺).\n  by rewrite ct_end at 2; rewrite inclusion_t_rt.\nassert (X15: (ee ^* ⨾ ed ⨾ dd ^* ⨾ de) ⁺ ⨾ dd ⊆ ∅₂).\n  by rewrite ct_end, ?seqA, ?DD, ?ED, ?DE, ?EE, ?seqA; \n    try sin_rewrite E2; try sin_rewrite E2'; relsf.\nassert (X16: (ee ^* ⨾ ed ⨾ dd ^* ⨾ de) ⁺ ⨾ de ⊆ ∅₂).\n  by rewrite ct_end, ?seqA, ?DD, ?ED, ?DE, ?EE, ?seqA; \n    try sin_rewrite E2; try sin_rewrite E2'; relsf.\n\nrepeat apply inclusion_union_l; rewrite ?seqA.\nall: rewrite ?X1, ?X2, ?X3, ?X4, ?X5, ?X6, ?X7, ?X8, ?X9, ?X10,\n     ?X11, ?X12, ?X13, ?X14, ?X15, ?X16, ?X17, ?X18, ?X19, ?X20.\nall: rels.\nall: try (repeat (apply inclusion_union_r; constructor); basic_solver 5).\nall: try (repeat (apply inclusion_union_r; constructor); basic_solver 20).\nQed.\n\nLemma path_dom_same A (r: relation A) d e \n  (E1: r ⊆ (⦗d⦘ ∪ ⦗e⦘) ⨾ r ⨾ (⦗d⦘ ∪ ⦗e⦘))\n  (E2: ⦗d⦘ ⨾ ⦗e⦘ ⊆ ∅₂)\n  dd (DD: dd = ⦗d⦘ ⨾ r ⨾ ⦗d⦘)\n  de (DE: de = ⦗d⦘ ⨾ r ⨾ ⦗e⦘)\n  ed (ED: ed = ⦗e⦘ ⨾ r ⨾ ⦗d⦘)\n  ee (EE: ee = ⦗e⦘ ⨾ r ⨾ ⦗e⦘) : \n  ⦗d⦘ ⨾ r⁺ ⨾ ⦗d⦘ ⊆ dd⁺ ∪ (dd^* ⨾ de ⨾ ee^* ⨾ ed)⁺ ⨾ dd^*.\nProof.\nrewrite path_dom; try edone.\nrelsf; repeat apply inclusion_union_l; rewrite ?seqA.\nall: try by rewrite inclusion_seq_eqv_l, inclusion_seq_eqv_r; relsf.\n- by rewrite ct_begin, EE, ?seqA; sin_rewrite E2; relsf.\n- rewrite ct_begin at 1; rewrite EE at 1; rewrite ED at 1;\n  rewrite rtE at 1; relsf.\n  rewrite ?seqA. \n  repeat apply inclusion_union_l; rewrite ?seqA.\n  by sin_rewrite E2; relsf.\n  by rewrite ct_begin, EE, ?seqA; sin_rewrite E2; relsf.\n- rewrite rtE at 1; relsf.\n  rewrite rtE at 1; relsf.\n  repeat apply inclusion_union_l; rewrite ?seqA.\n  by rewrite ED, ?seqA; sin_rewrite E2; relsf.\n  by rewrite ct_begin, EE, ?seqA; sin_rewrite E2; relsf.\n  rewrite ct_begin at 1; rewrite ?seqA.\n  rewrite rtE at 1; relsf.\n  rewrite ED, ?seqA; sin_rewrite E2; relsf.\n  by rewrite ct_begin, EE, ?seqA; sin_rewrite E2; relsf.\n- rewrite ?seqA.\n  arewrite (⦗d⦘ ⨾ (dd ^* ⨾ de ⨾ ee ^* ⨾ ed) ^* ⨾ dd ^* ⊆ fun _ _ => True).\n  rewrite rtE at 1; relsf.\n  rewrite DE, ?seqA.\n  arewrite (⦗e⦘ ⨾ ⦗d⦘ ⊆ (fun _ _ : A => False)).\n    by rewrite seq_eqvC in E2.\n  relsf.\n  rewrite ct_end at 1; rewrite ?seqA.\n  rewrite EE, ?seqA.\n  arewrite (⦗e⦘ ⨾ ⦗d⦘ ⊆ (fun _ _ : A => False)).\n    by rewrite seq_eqvC in E2.\n  by relsf.\nQed.\n\nLemma irr_dom A (r: relation A) d e\n  (E1: r ⊆ (⦗d⦘ ∪ ⦗e⦘) ⨾ r ⨾ (⦗d⦘ ∪ ⦗e⦘))\n  (E2: ⦗d⦘ ⨾ ⦗e⦘ ⊆ ∅₂)\n  (IRRd: irreflexive (⦗d⦘ ⨾ r ⨾ ⦗d⦘)) \n  (IRRe: irreflexive (⦗e⦘ ⨾ r ⨾ ⦗e⦘)) :\n  irreflexive r.\nProof.\n  rewrite step_dom; try edone.\n  repeat rewrite irreflexive_union; splits; try done; \n  generalize E2; basic_solver 8.\nQed.\n\n\nLemma acyc_dom A (r: relation A) d e\n  (E1: r ⊆ (⦗d⦘ ∪ ⦗e⦘) ⨾ r ⨾ (⦗d⦘ ∪ ⦗e⦘))\n  (E2: ⦗d⦘ ⨾ ⦗e⦘ ⊆ ∅₂)\n  dd (DD: dd = ⦗d⦘ ⨾ r ⨾ ⦗d⦘)\n  de (DE: de = ⦗d⦘ ⨾ r ⨾ ⦗e⦘)\n  ed (ED: ed = ⦗e⦘ ⨾ r ⨾ ⦗d⦘)\n  ee (EE: ee = ⦗e⦘ ⨾ r ⨾ ⦗e⦘) \n  (ACYCd: acyclic dd) \n  (ACYCe: acyclic ee) \n  (ACYCed: acyclic (ed ⨾ dd^* ⨾ de ⨾ ee^*)) :\n  acyclic r.\nProof.\nred.\neapply irr_dom; try edone.\n- arewrite (⦗d⦘ ∪ ⦗e⦘ ≡ ⦗fun x => d x \\/ e x⦘).\n    by basic_solver.\n  apply domab_helper; split.\n  apply ct_doma; eapply domab_helper with (d':= fun x => d x \\/ e x).\n  rewrite E1 at 1; basic_solver.\n  apply ct_domb; eapply domab_helper with (d := fun x => d x \\/ e x).\n  rewrite E1 at 1; basic_solver.\n- sin_rewrite path_dom_same; try edone.\n  repeat rewrite irreflexive_union; splits; try done.\n  rewrite irreflexive_seqC.\n  arewrite( dd^* ⨾ (dd ^* ⨾ de ⨾ ee ^* ⨾ ed) ⁺ ⊆ (dd ^* ⨾ de ⨾ ee ^* ⨾ ed) ⁺).\n    by rewrite ct_begin; rewrite !seqA; rels.\n  assert (acyclic (dd ^* ⨾ de ⨾ ee ^* ⨾ ed)); try done. (*?*)\n  rewrite acyclic_seqC; rewrite !seqA. \n  rewrite acyclic_seqC; rewrite !seqA. \n  rewrite acyclic_seqC; rewrite !seqA. \n  done.\n- rewrite unionC in E1.\n  sin_rewrite path_dom_same; try edone; try by rewrite seq_eqvC.\n  repeat rewrite irreflexive_union; splits; try done.\n  rewrite irreflexive_seqC.\n  arewrite( ee^* ⨾ (ee ^* ⨾ ed ⨾ dd ^* ⨾ de) ⁺  ⊆ (ee ^* ⨾ ed ⨾ dd ^* ⨾ de) ⁺).\n    by rewrite ct_begin; rewrite !seqA; rels.\n  assert (acyclic(ee ^* ⨾ ed ⨾ dd ^* ⨾ de)); try done. (*?*)\n  rewrite acyclic_seqC; rewrite !seqA. \n  done.\nQed.", "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/Dom.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2993646228142094}}
{"text": "Require Import Coq.Lists.List Coq.Arith.Arith Coq.Bool.Bool.\nRequire Import Bedrock.Expr Bedrock.Env.\nRequire Import Coq.Classes.EquivDec Bedrock.EqdepClass.\nRequire Import Bedrock.DepList.\nRequire Import Bedrock.Word Bedrock.Prover.\nRequire Import Bedrock.provers.ReflexivityProver Bedrock.sep.Locals.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\n(** * The Word Prover **)\n\nRequire Import Coq.Arith.Arith Bedrock.ILEnv Bedrock.Memory.\n\nSection LocalsProver.\n  Variable types' : list type.\n  Definition types := Locals.types types'.\n  Variable funcs' : functions types.\n  Definition funcs := Locals.funcs funcs'.\n\n  Definition localsSimplify (e : expr types) : expr types :=\n    match e with\n      | Func 11 (vs :: Const t nm :: nil) =>\n        match t return tvarD types t -> _ with\n          | tvType 6 => fun nm => sym_sel vs nm\n          | _ => fun _ => e\n        end nm\n      | _ => e\n    end.\n\n  Definition localsProve (_ : unit) (goal : expr types) :=\n    match goal with\n      | Equal _ x y => expr_seq_dec (localsSimplify x) (localsSimplify y)\n      | _ => false\n    end.\n\n  Lemma localsSimplify_correct : forall uvars vars (e : expr types) t v,\n    exprD funcs uvars vars e t = Some v\n    -> exprD funcs uvars vars (localsSimplify e) t = Some v.\n    destruct e; simpl; intuition idtac.\n    do 12 (destruct f; try assumption).\n    do 2 (destruct l; try assumption).\n    destruct e0; try assumption.\n    destruct l; try assumption.\n    destruct t0; try assumption.\n    do 7 (destruct n; try assumption).\n    simpl in *.\n    destruct (equiv_dec (tvType 0) t); try discriminate.\n    hnf in e0; subst.\n    generalize (sym_sel_correct funcs' uvars vars t1 e).\n    unfold funcs in *.\n    match type of H with\n      | match ?E with Some _ => _ | _ => _ end _ _ = _ => destruct E; try discriminate\n    end.\n    injection H; clear H; intros; subst.\n    auto.\n  Qed.\n\n  Theorem localsProveCorrect : ProverCorrect funcs reflexivityValid localsProve.\n    unfold localsProve; hnf; simpl; intros.\n\n    destruct goal; try discriminate.\n    destruct H1.\n    apply expr_seq_dec_correct in H0.\n    hnf.\n    simpl in *.\n    generalize (localsSimplify_correct uvars vars goal1 t).\n    generalize (localsSimplify_correct uvars vars goal2 t).\n    destruct (exprD funcs uvars vars goal1 t); try discriminate.\n    destruct (exprD funcs uvars vars goal2 t); try discriminate.\n    intros.\n    specialize (H2 _ (refl_equal _)).\n    specialize (H3 _ (refl_equal _)).\n    congruence.\n  Qed.\n\n  Definition localsProver : ProverT types :=\n    {| Facts := unit\n      ; Summarize := reflexivitySummarize\n      ; Learn := reflexivityLearn\n      ; Prove := localsProve |}.\n\n  Definition localsProver_correct : ProverT_correct localsProver funcs.\n    eapply Build_ProverT_correct with (Valid := reflexivityValid : _ -> _ -> Facts localsProver -> Prop); unfold reflexivityValid; eauto.\n    apply localsProveCorrect.\n  Qed.\n\nEnd LocalsProver.\n\nDefinition LocalsProver : ProverPackage :=\n{| ProverTypes := Locals.types_r\n ; ProverFuncs := Locals.funcs_r\n ; Prover_correct := localsProver_correct\n|}.\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/provers/LocalsProver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2993646228142094}}
{"text": "Require Import ProofIrrelevance.\nRequire Import FunctionalExtensionality.\nRequire Import List.\n\nRequire Import ProofAutomation.\nRequire Import Ordering.\nRequire Import Helpers.ListStuff.\nRequire Import Helpers.Maps.\nRequire Import Helpers.Instances.\nRequire Import Spec.ConcurExec.\nRequire Import Spec.Equiv.\nRequire Import Spec.Patterns.\nRequire Import Spec.Abstraction.\nRequire Import Spec.Movers.\nRequire Import Spec.Compile.\nRequire Import Spec.CompileLoop.\nRequire Import Spec.Protocol.\n\nRequire Import Coq.Program.Equality.\n\n\nImport ListNotations.\n\nGlobal Set Implicit Arguments.\nGlobal Generalizable All Variables.\n\n\nSection HorizontalComposition.\n\n  Variable indexT : Type.\n  Context {cmp : Ordering indexT}.\n  Variable indexValid : indexT -> Prop.\n\n  Variable sliceOpT : Type -> Type.\n  Variable sliceState : Type.\n  Variable sliceStep : OpSemantics sliceOpT sliceState.\n  Variable initP : sliceState -> Prop.\n\n  Definition validIndexT := { i : indexT | indexValid i }.\n\n  Inductive CheckResult :=\n  | Missing\n  | Present : validIndexT -> CheckResult\n  .\n\n  Inductive horizOpT : Type -> Type :=\n  | Slice : forall (i : validIndexT) T (op : sliceOpT T), horizOpT T\n  | CheckSlice : forall (i : indexT), horizOpT CheckResult\n  .\n\n  Record horizState := mk_horizState {\n    HSMap : FMap.t indexT sliceState;\n    HSValid : forall i, indexValid i -> FMap.In i HSMap;\n  }.\n\n  Definition hget (S : horizState) (i : validIndexT) : sliceState.\n    destruct S.\n    destruct i.\n    eapply HSValid0 in i.\n    eapply FMap.in_mapsto_get in i.\n    destruct i.\n    exact x0.\n  Defined.\n\n  Definition hadd (i : validIndexT) (s : sliceState) (S : horizState) : horizState.\n    destruct S.\n    destruct i.\n    refine (mk_horizState (FMap.add x s HSMap0) _).\n    intros.\n    eapply FMap.add_incr; eauto.\n  Defined.\n\n  Theorem hget_mapsto :\n    forall i m,\n      FMap.MapsTo (proj1_sig i) (hget m i) (HSMap m).\n  Proof.\n    destruct m.\n    destruct i.\n    simpl in *.\n    destruct (FMap.in_mapsto_get x HSMap0 (HSValid0 x i)).\n    eauto.\n  Qed.\n\n  Theorem hget_mapsto' :\n    forall i m P,\n      FMap.MapsTo i (hget m (exist _ i P)) (HSMap m).\n  Proof.\n    destruct m; simpl; intros.\n    destruct (FMap.in_mapsto_get i HSMap0 (HSValid0 i P)).\n    eauto.\n  Qed.\n\n  Opaque FMap.add.\n\n  Theorem hget_hadd_eq : forall S s i H0 H1,\n    hget (hadd (exist _ i H0) s S) (exist _ i H1) = s.\n  Proof.\n    destruct S; simpl; intros.\n    match goal with\n    | |- context[FMap.in_mapsto_get ?a ?b ?c] => destruct (FMap.in_mapsto_get a b c)\n    end.\n    eapply FMap.mapsto_add in m; eauto.\n  Qed.\n\n  Local Theorem hget_hadd_eq_general : forall i s s',\n      hget (hadd i s s') i = s.\n  Proof.\n    destruct i; intros.\n    apply hget_hadd_eq.\n  Qed.\n\n  Local Theorem hget_hadd_ne : forall S s i i' H0 H1,\n    i <> i' ->\n    hget (hadd (exist _ i H0) s S) (exist _ i' H1) = hget S (exist _ i' H1).\n  Proof.\n    destruct S; simpl; intros.\n    repeat match goal with\n    | |- context[FMap.in_mapsto_get ?a ?b ?c] => destruct (FMap.in_mapsto_get a b c)\n    end.\n    eapply FMap.mapsto_add_ne in m; eauto.\n    FMap.mapsto_unique; auto.\n  Qed.\n\n  Local Theorem hget_hadd_ne_general : forall i i' s S,\n      i <> i' ->\n      hget (hadd i s S) i' = hget S i'.\n  Proof.\n    intros.\n    destruct i, i'.\n    destruct (x == x0); subst.\n    exfalso.\n    apply H.\n    f_equal; auto using proof_irrelevance.\n    apply hget_hadd_ne; auto.\n  Qed.\n\n  Theorem hadd_hget_eq : forall S i H0 H1,\n    hadd (exist _ i H0) (hget S (exist _ i H1)) S = S.\n  Proof.\n    destruct S; simpl; intros.\n    repeat match goal with\n    | |- context[FMap.in_mapsto_get ?a ?b ?c] => destruct (FMap.in_mapsto_get a b c)\n    end.\n    match goal with\n    | |- {| HSMap := ?m ; HSValid := ?v |} = _ =>\n      generalize v; remember m\n    end.\n    rewrite FMap.mapsto_add_nilpotent in Heqt; eauto.\n    subst; intros.\n    f_equal.\n    apply proof_irrelevance.\n  Qed.\n\n  Local Theorem hadd_hadd_eq : forall S s s' i H0 H1,\n    hadd (exist _ i H0) s (hadd (exist _ i H1) s' S) = hadd (exist _ i H0) s S.\n  Proof.\n    destruct S; simpl; intros.\n    match goal with\n    | |- {| HSMap := ?m ; HSValid := ?v |} = _ =>\n      generalize v; remember m\n    end.\n    rewrite FMap.add_add in Heqt.\n    subst; intros.\n    f_equal.\n    apply proof_irrelevance.\n  Qed.\n\n  Local Theorem hadd_hadd_ne : forall S s s' i i' H0 H1,\n    i <> i' ->\n    hadd (exist _ i H0) s (hadd (exist _ i' H1) s' S) =\n    hadd (exist _ i' H1) s' (hadd (exist _ i H0) s S).\n  Proof.\n    destruct S; simpl; intros.\n    match goal with\n    | |- {| HSMap := ?m ; HSValid := ?v |} = _ =>\n      generalize v; remember m\n    end.\n    rewrite FMap.add_add_ne in Heqt; eauto.\n    subst; intros.\n    f_equal.\n    apply proof_irrelevance.\n  Qed.\n\n  Inductive sameSlice : CheckResult -> indexT -> Prop :=\n  | SameSliceMissing : forall i,\n    sameSlice Missing i\n  | SameSlicePresent : forall i P,\n    sameSlice (Present (exist _ i P)) i\n  .\n\n  Inductive horizStep :\n      forall T, horizOpT T -> nat -> horizState -> T -> horizState -> list event -> Prop :=\n  | StepSlice :\n    forall tid idx (S : horizState) `(op : sliceOpT T) r s' evs,\n      sliceStep op tid (hget S idx) r s' evs ->\n      horizStep (Slice idx op) tid S r (hadd idx s' S) evs\n  | StepCheckSlice :\n    forall tid idx (S : horizState) r,\n      sameSlice r idx ->\n      horizStep (CheckSlice idx) tid S r S nil\n  .\n\n  Definition horizInitP (S : horizState) :=\n    forall i,\n      indexValid i ->\n      exists s,\n        FMap.MapsTo i s (HSMap S) /\\\n        initP s.\n\n  Definition SliceProc (i : validIndexT) `(p : proc sliceOpT T) : proc horizOpT T :=\n    Compile.compile (fun T (op : sliceOpT T) => Call (Slice i op)) p.\n\n  Theorem SliceProc_eq : forall i T (p p': proc _ T),\n      SliceProc i p = SliceProc i p' ->\n      p = p'.\n  Proof.\n    induction p; intros;\n      try solve [ destruct p'; simpl in *; try congruence; invert H; auto ].\n    - destruct p'; simpl in *; try congruence.\n      invert H0; eauto.\n      f_equal; eauto.\n      extensionality r.\n      invert H0.\n      apply equal_f with r in H5.\n      eauto.\n    - destruct p'; simpl in *; try congruence.\n      invert H0.\n      f_equal.\n      extensionality x.\n      apply equal_f with x in H3.\n      eauto.\n    - destruct p'; simpl in *; try congruence.\n      invert H.\n      f_equal.\n      eauto.\n    - dependent destruction p'; simpl in *; try congruence.\n      invert H.\n      erewrite IHp; eauto.\n  Qed.\n\nEnd HorizontalComposition.\n\nArguments horizState indexT {cmp} indexValid sliceState.\nArguments horizStep indexT {cmp} indexValid {sliceOpT sliceState} sliceStep.\nArguments Slice {indexT indexValid sliceOpT} i {T}.\nArguments CheckSlice {indexT indexValid sliceOpT} i.\nArguments Missing {indexT indexValid}.\n\n\nLtac destruct_horizState :=\n  match goal with\n  | x : horizState _ _ _ |- _ => destruct x; simpl in *\n  end.\n\nLtac destruct_validIndex :=\n  match goal with\n  | x : validIndexT _ |- _ => destruct x; simpl in *\n  end.\n\n\nSection HorizontalCompositionAbs.\n\n  Variable indexT : Type.\n  Context {cmp : Ordering indexT}.\n  Variable indexValid : indexT -> Prop.\n\n  Variable sliceOpT : Type -> Type.\n\n  Variable sliceState1 : Type.\n  Variable sliceStep1 : OpSemantics sliceOpT sliceState1.\n\n  Variable sliceState2 : Type.\n  Variable sliceStep2 : OpSemantics sliceOpT sliceState2.\n\n\n  Variable absR : sliceState1 -> sliceState2 -> Prop.\n\n  Definition horizAbsR (S1 : horizState indexT indexValid sliceState1)\n                       (S2 : horizState indexT indexValid sliceState2) : Prop :=\n    forall (i : indexT),\n      indexValid i ->\n      ( forall s1,\n          FMap.MapsTo i s1 (HSMap S1) ->\n            exists s2, FMap.MapsTo i s2 (HSMap S2) /\\ absR s1 s2 ) /\\\n      ( forall s2,\n          FMap.MapsTo i s2 (HSMap S2) ->\n            exists s1, FMap.MapsTo i s1 (HSMap S1) /\\ absR s1 s2 ).\n\n  Hint Resolve FMap.add_mapsto.\n  Hint Resolve FMap.mapsto_add_ne'.\n  Hint Resolve FMap.mapsto_in.\n\n  Theorem horizAbsR_ok :\n    op_abs absR sliceStep1 sliceStep2 ->\n    op_abs horizAbsR (horizStep indexT indexValid sliceStep1) (horizStep indexT indexValid sliceStep2).\n  Proof.\n    unfold op_abs, horizAbsR; intros.\n    inversion H1; clear H1; subst; repeat sigT_eq.\n    {\n      eapply H in H7; repeat deex.\n      {\n        eexists; split; [ | econstructor; eauto ].\n        intros.\n        repeat destruct_horizState.\n        repeat destruct_validIndex.\n        destruct (i == x); subst.\n        - split; intros.\n          + eapply FMap.mapsto_add_eq in H4; subst; eauto.\n          + eapply FMap.mapsto_add_eq in H4; subst; eauto.\n        - specialize (H0 i); intuition idtac.\n          + eapply FMap.mapsto_add_ne in H4; eauto.\n            specialize (H0 _ H4); propositional; eauto.\n          + eapply FMap.mapsto_add_ne in H4; eauto.\n            specialize (H5 _ H4); propositional; eauto.\n      }\n      {\n        pose proof (@hget_mapsto _ _ _ _ idx s1).\n        pose proof (@hget_mapsto _ _ _ _ idx s2).\n        specialize (H0 (proj1_sig idx) (proj2_sig idx)).\n        eapply H0 in H1; deex.\n        FMap.mapsto_unique; eauto.\n      }\n    }\n    {\n      eexists.\n      split.\n      eassumption.\n      constructor.\n      intuition idtac.\n    }\n  Qed.\n\n\n  Variable initP1 : sliceState1 -> Prop.\n  Variable initP2 : sliceState2 -> Prop.\n\n  (* this is like the normal absInitP but strengthens it to provide an explicit\n  function for the witness - this is needed to construct the horizontal abstract\n  state *)\n  Variable initP_map : sliceState1 -> sliceState2.\n  Variable initP_ok :\n    forall s1,\n      initP1 s1 ->\n      absR s1 (initP_map s1) /\\\n      initP2 (initP_map s1).\n\n  Hint Resolve FMap.mapsto_in.\n  Hint Resolve FMap.map_values_MapsTo.\n\n  Theorem horizAbsR_initP_ok :\n    forall s1,\n      horizInitP initP1 s1 ->\n      exists s2, horizAbsR s1 s2 /\\\n            horizInitP initP2 s2.\n  Proof.\n    unfold horizInitP; intros.\n\n    unshelve eexists {| HSMap := FMap.map_values initP_map s1.(HSMap) |};\n      simpl;\n      intuition idtac.\n    - intros.\n      specialize (H i); propositional.\n      rewrite <- FMap.map_values_in; eauto.\n    - unfold horizAbsR; simpl; intros.\n      specialize (H _ H0); propositional.\n      eapply initP_ok in H1; propositional.\n      split; intros.\n      + FMap.mapsto_unique; eauto.\n      + eapply FMap.map_values_MapsTo_general in H3; propositional.\n        FMap.mapsto_unique; eauto.\n    - specialize (H i); propositional.\n      apply initP_ok in H1; propositional.\n      eauto.\n  Qed.\n\nEnd HorizontalCompositionAbs.\n\nArguments horizAbsR indexT {cmp indexValid sliceState1 sliceState2} absR.\n\n\nSection HorizontalCompositionMovers.\n\n  Variable indexT : Type.\n  Context {cmp : Ordering indexT}.\n  Variable indexValid : indexT -> Prop.\n\n  Variable sliceOpT : Type -> Type.\n  Variable sliceState : Type.\n  Variable sliceStep : OpSemantics sliceOpT sliceState.\n\n  Hint Resolve FMap.add_mapsto.\n  Hint Resolve FMap.mapsto_add_ne'.\n  Hint Resolve FMap.mapsto_in.\n  Hint Resolve FMap.add_in_in.\n  Hint Resolve FMap.add_incr.\n  Hint Constructors horizStep.\n  Hint Extern 1 (horizStep _ _ _ _ _ _ _ _ _) => econstructor.\n\n  Opaque hget.\n  Opaque hadd.\n\n  Local Theorem horiz_right_mover_ok :\n    forall `(op : sliceOpT T),\n      right_mover sliceStep op ->\n      forall i,\n        right_mover (horizStep indexT indexValid sliceStep) (Slice i op).\n  Proof.\n    intros.\n    unfold right_mover; intros.\n    inversion H0; clear H0; subst; repeat sigT_eq.\n    eapply H in H9 as H'; intuition subst.\n    inversion H3; clear H3; subst; repeat sigT_eq.\n    {\n      repeat destruct_horizState.\n      repeat destruct_validIndex.\n      destruct (x == x0); subst.\n      - rewrite hget_hadd_eq in *.\n        eapply H1 in H8; eauto; deex.\n        eexists; split.\n        + econstructor; eauto.\n          replace i0 with i by apply proof_irrelevance; eauto.\n        + rewrite hadd_hadd_eq.\n          erewrite <- hadd_hadd_eq with (s := s'0).\n          replace i0 with i by apply proof_irrelevance; eauto.\n          econstructor; eauto.\n          rewrite hget_hadd_eq; eauto.\n      - rewrite hget_hadd_ne in * by eauto.\n        eexists; split.\n        + econstructor; eauto.\n        + rewrite hadd_hadd_ne by eauto.\n          econstructor; eauto.\n          rewrite hget_hadd_ne by eauto.\n          eauto.\n    }\n    {\n      eexists; split; eauto.\n    }\n  Qed.\n\n  Theorem horiz_enabled_stable :\n    forall `(op : sliceOpT T),\n      enabled_stable sliceStep T op ->\n      forall i,\n        enabled_stable (horizStep indexT indexValid sliceStep) T (Slice i op).\n  Proof.\n    intros.\n    unfold enabled_stable; intros.\n    unfold enabled_in in *; repeat deex.\n    inversion H1; clear H1; subst; repeat sigT_eq.\n    inversion H2; clear H2; subst; repeat sigT_eq; eauto.\n    repeat destruct_validIndex.\n    destruct (x == x0); subst.\n    - edestruct H.\n      eassumption.\n      unfold enabled_in; eauto.\n      replace i0 with i in * by apply proof_irrelevance; eauto.\n      repeat deex.\n      do 3 eexists. econstructor; eauto.\n      rewrite hget_hadd_eq; eauto.\n    - do 3 eexists. econstructor; eauto.\n      rewrite hget_hadd_ne; eauto.\n  Qed.\n\n  Local Theorem horiz_left_mover_ok :\n    forall `(op : sliceOpT T),\n      left_mover sliceStep op ->\n      forall i,\n        left_mover (horizStep indexT indexValid sliceStep) (Slice i op).\n  Proof.\n    intros.\n    split; intros.\n    - eapply horiz_enabled_stable.\n      destruct H; eauto.\n    - inversion H0; clear H0; subst; repeat sigT_eq.\n      eapply H in H9 as H'; intuition subst.\n      inversion H3; clear H3; subst; repeat sigT_eq.\n      {\n        repeat destruct_validIndex.\n        destruct (x == x0); subst.\n        * rewrite hget_hadd_eq in *.\n          replace i0 with i in * by apply proof_irrelevance; eauto.\n          eapply H1 in H8; eauto; deex.\n          eexists; split.\n          + econstructor; eauto.\n          + rewrite hadd_hadd_eq.\n            erewrite <- hadd_hadd_eq with (s := s').\n            econstructor; eauto.\n            rewrite hget_hadd_eq; eauto.\n        * rewrite hget_hadd_ne in * by eauto.\n          eexists; split.\n          + econstructor; eauto.\n          + rewrite hadd_hadd_ne by eauto.\n            econstructor; eauto.\n            rewrite hget_hadd_ne by eauto.\n            eauto.\n      }\n      {\n        eexists; split; eauto.\n      }\n  Qed.\n\n  Local Theorem horiz_left_mover_pred_ok :\n    forall `(op : sliceOpT T) P,\n      left_mover_pred sliceStep op P ->\n      forall i,\n        left_mover_pred (horizStep indexT indexValid sliceStep) (Slice i op)\n          (fun tid S => P tid (hget S i)).\n  Proof.\n    intros.\n    split; intros.\n    - eapply horiz_enabled_stable.\n      destruct H; eauto.\n    - inversion H0; clear H0; subst; repeat sigT_eq.\n      eapply H in H9 as H'; intuition subst.\n      inversion H4; clear H4; subst; repeat sigT_eq.\n      {\n        repeat destruct_validIndex.\n        destruct (x == x0); subst.\n        * rewrite hget_hadd_eq in *.\n          replace i0 with i in * by apply proof_irrelevance; eauto.\n          eapply H1 in H10; eauto; deex.\n          eexists; split.\n          + econstructor; eauto.\n          + rewrite hadd_hadd_eq.\n            erewrite <- hadd_hadd_eq with (s := s').\n            econstructor; eauto.\n            rewrite hget_hadd_eq; eauto.\n        * rewrite hget_hadd_ne in * by eauto.\n          eexists; split.\n          + econstructor; eauto.\n          + rewrite hadd_hadd_ne by eauto.\n            econstructor; eauto.\n            rewrite hget_hadd_ne by eauto.\n            eauto.\n      }\n      {\n        eexists; split; eauto.\n      }\n  Qed.\n\n  Hint Resolve horiz_right_mover_ok.\n  Hint Resolve horiz_left_mover_ok.\n  Hint Resolve horiz_left_mover_pred_ok.\n\n\n  Lemma atomic_exec_horizStep : forall `(p0 : proc _ T) i tid S v S' evs,\n    atomic_exec (horizStep indexT indexValid sliceStep) p0 tid S v S' evs ->\n      forall p,\n        p0 = SliceProc i p ->\n        exists s',\n          atomic_exec sliceStep p tid (hget S i) v s' evs /\\\n          S' = hadd i s' S.\n  Proof.\n    induction 1; simpl; intros.\n    - destruct p; simpl in *; try congruence.\n      inversion H; clear H; subst; repeat sigT_eq.\n      eexists; split; eauto.\n      destruct_validIndex.\n      rewrite hadd_hget_eq; eauto.\n    - destruct p; simpl in *; try congruence.\n      inversion H1; clear H1; subst; repeat sigT_eq.\n      edestruct IHatomic_exec1; eauto.\n      edestruct IHatomic_exec2; eauto.\n      intuition subst.\n      destruct_validIndex.\n      rewrite hget_hadd_eq in *.\n      eexists; split; eauto.\n      rewrite hadd_hadd_eq; eauto.\n    - destruct p; simpl in *; try congruence.\n      inversion H0; clear H0; subst; repeat sigT_eq.\n      inversion H; clear H; subst; repeat sigT_eq.\n      eauto.\n    - destruct p0; simpl in *; try congruence.\n      inversion H0; clear H0; subst; repeat sigT_eq.\n      edestruct IHatomic_exec.\n      + unfold until1.\n        instantiate (1 := Bind (p0 v0) (fun x => if (c0 x) then Ret x else Until c0 (fun x0 => p0 x0) (Some x))).\n        simpl; f_equal.\n        eapply functional_extensionality; intros.\n        destruct (c0 x); reflexivity.\n      + intuition subst.\n        eexists; split; eauto.\n  Qed.\n\n  Local Lemma hadd_hget_eq' : forall (i: validIndexT indexValid) (s: horizState _ _ sliceState),\n      s = hadd i (hget s i) s.\n  Proof.\n    intros.\n    destruct_validIndex.\n    rewrite hadd_hget_eq; auto.\n  Qed.\n\n  Hint Resolve hadd_hget_eq'.\n\n  Local Lemma exec_tid_slice :\n    forall S1 S2 tid `(p : proc _ T) r spawned evs,\n      exec_tid (horizStep indexT indexValid sliceStep) tid S1 p S2 r spawned evs ->\n      forall `(p' : proc _ T) i,\n        p = SliceProc i p' ->\n        exists spawned' s' r',\n        spawned = match spawned' with\n                  | Proc p => Proc (SliceProc i p)\n                  | NoProc => NoProc\n                  end /\\\n          exec_tid sliceStep tid (hget S1 i) p' s' r' spawned' evs /\\\n          S2 = hadd i s' S1 /\\\n          match r with\n          | inl v => r' = inl v\n          | inr rx => exists rx', r' = inr rx' /\\ rx = SliceProc i rx'\n          end.\n  Proof.\n    induction 1; intros; subst.\n    - exists NoProc; simpl.\n      destruct p'; simpl in *; try congruence.\n      invert H.\n      descend; simpl; intuition eauto.\n    - exists NoProc; simpl.\n      destruct p'; simpl in *; try congruence.\n      invert H0.\n      invert H.\n      eauto 10.\n    - exists NoProc; simpl.\n      destruct p'; simpl in *; try congruence.\n      inversion H0; clear H0; subst; repeat sigT_eq.\n      eapply atomic_exec_horizStep in H; eauto; deex.\n      eauto 10.\n    - destruct p'; simpl in *; try congruence.\n      inversion H0; clear H0; subst; repeat sigT_eq.\n      edestruct IHexec_tid; eauto; repeat deex.\n      descend; intuition eauto.\n      destruct result; subst; eauto.\n      deex; eauto.\n    - exists NoProc; simpl.\n      destruct p'; simpl in *; try congruence.\n      invert H.\n      descend; intuition eauto.\n      descend; intuition eauto.\n      unfold until1; simpl.\n      f_equal.\n      extensionality x.\n      destruct matches.\n    - dependent destruction p'; simpl in *; try congruence.\n      invert H.\n      eexists (Proc _).\n      descend; intuition eauto.\n  Qed.\n\n  Local Lemma exec_any_slice :\n    forall S1 S2 tid `(p : proc _ T) r,\n      exec_any (horizStep indexT indexValid sliceStep) tid S1 p r S2 ->\n      forall `(p' : proc _ T) i,\n        p = SliceProc i p' ->\n        exec_any sliceStep tid (hget S1 i) p' r (hget S2 i).\n  Proof.\n    induction 1; intros; subst.\n    - inversion H0; clear H0; subst; repeat sigT_eq; eauto.\n      repeat destruct_validIndex.\n      destruct (x == x0); subst; eauto.\n      + replace i0 with i in * by apply proof_irrelevance.\n        eapply ExecAnyOther.\n        eassumption.\n        2: eauto.\n        rewrite hget_hadd_eq in *.\n        eauto.\n      + specialize (IHexec_any _ _ eq_refl).\n        rewrite hget_hadd_ne in * by eauto.\n        eauto.\n    - eapply exec_tid_slice in H; eauto; repeat deex.\n      destruct_validIndex.\n      rewrite hget_hadd_eq; eauto.\n    - eapply exec_tid_slice in H; eauto; repeat deex.\n      eapply ExecAnyThisMore; eauto.\n      specialize (IHexec_any _ _ eq_refl).\n      destruct_validIndex.\n      rewrite hget_hadd_eq in *.\n      eapply IHexec_any.\n  Qed.\n\n  Local Lemma exec_others_slice :\n    forall S1 S2 tid,\n      exec_others (horizStep indexT indexValid sliceStep) tid S1 S2 ->\n      forall i,\n        exec_others sliceStep tid (hget S1 i) (hget S2 i).\n  Proof.\n    induction 1; intros; eauto.\n    repeat deex.\n    inversion H1; clear H1; subst; repeat sigT_eq; eauto.\n    repeat destruct_validIndex.\n    destruct (x0 == x1); subst; eauto.\n    * replace i0 with i in * by apply proof_irrelevance.\n      econstructor; [ | apply IHclos_refl_trans_1n ].\n      do 5 eexists; split; eauto.\n      rewrite hget_hadd_eq; eauto.\n    * specialize (IHclos_refl_trans_1n (exist _ x0 i)).\n      rewrite hget_hadd_ne in * by eauto.\n      eauto.\n  Unshelve.\n    all: try exact (Ret tt).\n  Qed.\n\n  Hint Resolve exec_any_slice.\n  Hint Resolve exec_others_slice.\n\n  Local Lemma horiz_left_movers :\n    forall `(p : proc _ T) P,\n      left_movers sliceStep P p ->\n      forall i,\n        left_movers (horizStep indexT indexValid sliceStep)\n          (fun tid S => P tid (hget S i))\n          (SliceProc i p).\n  Proof.\n    induction 1; simpl; intros; eauto.\n    econstructor; intros.\n    - eauto.\n    - eapply H0 in H3.\n      edestruct H3; repeat deex.\n      do 3 eexists.\n      constructor.\n      eauto.\n    - eapply left_movers_impl; eauto.\n      simpl; intros; repeat deex.\n\n      do 2 eexists.\n      intuition eauto.\n  Qed.\n\n\n  Local Theorem horiz_ysa_movers :\n    forall `(p : proc _ T),\n      ysa_movers sliceStep p ->\n      forall i,\n        ysa_movers (horizStep indexT indexValid sliceStep) (SliceProc i p).\n  Proof.\n    unfold ysa_movers; intros.\n    eapply right_movers_impl with\n      (P1 := fun tid S => any tid (hget S i));\n      [ | firstorder ].\n    generalize dependent H.\n    generalize (@any sliceState).\n    intros.\n    induction H.\n    {\n      simpl.\n      econstructor; eauto; intros.\n      eapply right_movers_impl; eauto.\n      simpl; intros; repeat deex.\n\n      do 2 eexists.\n      intuition eauto.\n    }\n\n    eapply RightMoversDone.\n    inversion H; clear H; subst; repeat sigT_eq.\n    {\n      eapply ZeroNonMovers.\n      eapply horiz_left_movers; eauto.\n    }\n\n    simpl.\n    eapply OneNonMover.\n    {\n      intros.\n      eapply left_movers_impl.\n      eapply horiz_left_movers; eauto.\n      simpl; intros; repeat deex.\n\n      do 2 eexists.\n      intuition eauto.\n    }\n\n    eapply OneFinalNonMover.\n  Qed.\n\nEnd HorizontalCompositionMovers.\n\n\n(** Module structures for horizontal composition *)\n\nModule Type HIndex.\n  Axiom indexT : Type.\n  Axiom indexValid : indexT -> Prop.\n  Axiom indexCmp : Ordering indexT.\nEnd HIndex.\n\nModule HOps (o : Ops) (i : HIndex) <: Ops.\n  Definition Op := horizOpT i.indexValid o.Op.\nEnd HOps.\n\nModule HState (s : State) (i : HIndex) <: State.\n  Definition State := @horizState i.indexT i.indexCmp i.indexValid s.State.\nEnd HState.\n\nModule HLayer (o : Ops) (s : State) (l : Layer o s) (i : HIndex).\n  Definition step := @horizStep i.indexT i.indexCmp i.indexValid _ _ l.step.\n  Definition initP : @horizState i.indexT i.indexCmp i.indexValid s.State -> Prop :=\n    horizInitP l.initP.\nEnd HLayer.\n\nModule HProtocol (o : Ops) (s : State) (p : Protocol o s) (i : HIndex).\n  Module ho := HOps o i.\n  Module hs := HState s i.\n  Definition step_allow T (hop : ho.Op T) (tid : nat) (S : hs.State) : Prop :=\n    match hop with\n    | Slice i op =>\n      p.step_allow op tid (hget S i)\n    | CheckSlice i =>\n      True\n    end.\nEnd HProtocol.\n\nModule Type HLayerImplAbsT\n       (o:Ops)\n       (s1: State) (l1: Layer o s1)\n       (s2: State) (l2: Layer o s2).\n  Parameter absR : s1.State -> s2.State -> Prop.\n  Parameter absR_ok : op_abs absR l1.step l2.step.\n\n  Parameter initP_map: forall (s1:s1.State), {s2:s2.State | l1.initP s1 -> absR s1 s2 /\\ l2.initP s2}.\n\nEnd HLayerImplAbsT.\n\nModule LayerImplAbsT_from_H\n       (o:Ops)\n       (s1:State) (l1:Layer o s1)\n       (s2:State) (l2:Layer o s2)\n       (a: HLayerImplAbsT o s1 l1 s2 l2) <: LayerImplAbsT o s1 l1 s2 l2.\n  Include a.\n\n  Theorem absInitP : forall s1,\n      l1.initP s1 ->\n      exists s2, absR s1 s2 /\\\n            l2.initP s2.\n  Proof.\n    intros.\n    destruct (initP_map s1); eauto.\n  Qed.\n\nEnd LayerImplAbsT_from_H.\n\nModule HLayerImplAbs\n       (o:Ops)\n       (s1:State) (l1:Layer o s1)\n       (s2:State) (l2:Layer o s2)\n       (a: HLayerImplAbsT o s1 l1 s2 l2).\n  Module a' := LayerImplAbsT_from_H o s1 l1 s2 l2 a.\n  Include (LayerImplAbs o s1 l1 s2 l2 a').\nEnd HLayerImplAbs.\n\nModule LayerImplAbsHT\n  (o : Ops)\n  (s1 : State) (l1 : Layer o s1)\n  (s2 : State) (l2 : Layer o s2)\n  (a : HLayerImplAbsT o s1 l1 s2 l2)\n  (i : HIndex).\n\n  Module ho := HOps o i.\n  Module hs1 := HState s1 i.\n  Module hs2 := HState s2 i.\n  Module hl1 := HLayer o s1 l1 i.\n  Module hl2 := HLayer o s2 l2 i.\n\n  Definition absR :=\n    @horizAbsR i.indexT i.indexCmp i.indexValid _ _ a.absR.\n\n  Theorem absInitP :\n    forall s1,\n      hl1.initP s1 ->\n      exists s2, absR s1 s2 /\\\n      hl2.initP s2.\n  Proof.\n    intros.\n    eapply horizAbsR_initP_ok\n      with (initP_map := fun s1 => proj1_sig (a.initP_map s1)) in H;\n      propositional; eauto.\n    pose proof (proj2_sig (a.initP_map s0));\n      simpl in *; propositional; eauto.\n  Qed.\n\n  Theorem absR_ok :\n    op_abs absR hl1.step hl2.step.\n  Proof.\n    eapply horizAbsR_ok.\n    apply a.absR_ok.\n  Qed.\n\nEnd LayerImplAbsHT.\n\n\nModule LayerImplMoversProtocolHT\n  (s : State)\n  (o1 : Ops) (l1raw : Layer o1 s) (l1 : Layer o1 s)\n  (o2 : Ops) (l2 : Layer o2 s)\n  (p : Protocol o1 s)\n  (a : LayerImplMoversProtocolT s o1 l1raw l1 o2 l2 p)\n  (i : HIndex).\n\n  Module hs := HState s i.\n  Module ho1 := HOps o1 i.\n  Module ho2 := HOps o2 i.\n  Module hl1raw := HLayer o1 s l1raw i.\n  Module hl1 := HLayer o1 s l1 i.\n  Module hl2 := HLayer o2 s l2 i.\n  Module hp := HProtocol o1 s p i.\n\n  Definition compile_op T (op : ho2.Op T) : proc ho1.Op T :=\n    match op with\n    | Slice i op => SliceProc i (a.compile_op op)\n    | CheckSlice i => Call (CheckSlice i)\n    end.\n\n  Theorem compile_op_no_atomics : forall T (op : ho2.Op T),\n    no_atomics (compile_op op).\n  Proof.\n    destruct op; simpl; eauto.\n    pose proof (a.compile_op_no_atomics op).\n    generalize dependent H.\n    generalize (a.compile_op op).\n    clear.\n    induction 1; simpl; eauto.\n  Qed.\n\n  Theorem ysa_movers : forall T (op : ho2.Op T),\n    ysa_movers hl1.step (compile_op op).\n  Proof.\n    destruct op; simpl; eauto.\n    eapply horiz_ysa_movers.\n    eapply a.ysa_movers.\n  Qed.\n\n  Theorem compile_correct :\n    compile_correct compile_op hl1.step hl2.step.\n  Proof.\n    intro; intros.\n    destruct op; simpl in *.\n    - eapply atomic_exec_horizStep in H; eauto; deex.\n      eapply a.compile_correct in H.\n      econstructor; eauto.\n    - repeat atomic_exec_inv.\n      inversion H5; clear H5; subst; repeat sigT_eq.\n      econstructor; eauto.\n  Qed.\n\n  Existing Instance i.indexCmp.\n\n  Hint Rewrite hget_hadd_eq_general : h.\n  Hint Rewrite hget_hadd_ne_general using solve [ auto ] : h.\n\n  Lemma step_high_to_step_low :\n    forall s s' (i: validIndexT i.indexValid) T (op: hp.ho.Op T) tid r evs,\n      restricted_step hl1raw.step hp.step_allow op tid s r s' evs ->\n      (exists (op': o1.Op T) r' evs',\n          restricted_step l1raw.step p.step_allow op' tid (hget s i) r' (hget s' i) evs') \\/\n      hget s i = hget s' i.\n  Proof.\n    intros.\n    unfold restricted_step in *; propositional.\n    unfold hp.step_allow, hl1raw.step in *.\n    invert H0; clear H0.\n    - destruct (i == idx); subst;\n        autorewrite with h;\n        eauto 10.\n    - eauto.\n  Qed.\n\n  Lemma exec_ops_high : forall s s' (i: validIndexT i.indexValid),\n      exec_ops (restricted_step hl1raw.step hp.step_allow) s s' ->\n      exec_ops (restricted_step l1raw.step p.step_allow) (hget s i) (hget s' i).\n  Proof.\n    unfold exec_ops; intros.\n    induction H; propositional.\n    reflexivity.\n\n    transitivity (hget y i); auto.\n    eapply step_high_to_step_low with (i:=i) in H;\n      (intuition propositional);\n      eauto.\n    - econstructor; [ | reflexivity ].\n      descend; eauto.\n    - replace (hget y i).\n      reflexivity.\n  Qed.\n\n  Theorem op_follows_protocol : forall tid s `(op : ho2.Op T),\n    follows_protocol_proc hl1raw.step hp.step_allow tid s (compile_op op).\n  Proof.\n    destruct op; simpl.\n    - pose proof (a.op_follows_protocol tid (hget s i) op).\n      generalize dependent (a.compile_op op); intros; clear dependent op.\n      remember (hget s i).\n      generalize dependent s.\n      generalize dependent i.\n      induction H; intros; subst; simpl.\n      + constructor. eauto.\n      + constructor. eauto.\n        intros.\n        eapply H1; eauto.\n        eapply exec_any_slice; eauto.\n        eapply exec_any_impl; try eassumption.\n\n        clear.\n        unfold restricted_step; intuition idtac.\n        inversion H1; clear H1; subst; repeat sigT_eq; simpl in *.\n        * econstructor; eauto.\n        * econstructor; eauto.\n      + constructor; intros.\n        eapply H0; eauto.\n      + constructor.\n      + constructor; intros.\n        assert (forall tid', tid <> tid' ->\n                        follows_protocol_proc hl1raw.step hp.step_allow\n                                              tid' s0 (SliceProc i p)).\n        eauto.\n        rename H into Hspawn.\n        unfold spawn_follows_protocol; intros.\n        specialize (H1 tid' ltac:(auto)).\n        specialize (H0 tid' ltac:(auto)).\n        specialize (Hspawn tid' ltac:(auto)).\n\n        assert (exec_ops (restricted_step l1raw.step p.step_allow)\n                         (hget s0 i) (hget s' i)).\n        eapply exec_ops_high; eauto.\n        eauto.\n    - constructor; constructor.\n  Qed.\n\n  Theorem allowed_stable :\n    forall `(op : ho1.Op T) `(op' : ho1.Op T') tid tid' s s' r evs,\n      tid <> tid' ->\n      hp.step_allow op tid s ->\n      hl1.step op' tid' s r s' evs ->\n      hp.step_allow op tid s'.\n  Proof.\n    destruct op, op'; eauto.\n    {\n      intros.\n      simpl in *.\n      inversion H1; clear H1; subst; repeat sigT_eq.\n      pose (i.indexCmp).\n      repeat destruct_validIndex.\n      destruct (x == x0); subst.\n      - replace i0 with i in * by apply proof_irrelevance.\n        rewrite hget_hadd_eq.\n        eapply a.allowed_stable; eauto.\n      - rewrite hget_hadd_ne in * by eauto.\n        eauto.\n    }\n    {\n      intros.\n      inversion H1; subst; eauto.\n    }\n  Qed.\n\n  Theorem raw_step_ok :\n    forall `(op : ho1.Op T) tid s r s' evs,\n      restricted_step hl1raw.step hp.step_allow op tid s r s' evs ->\n      hl1.step op tid s r s' evs.\n  Proof.\n    destruct op.\n    - unfold restricted_step; intuition idtac.\n      inversion H1; clear H1; subst; repeat sigT_eq.\n      econstructor; eauto.\n      eapply a.raw_step_ok.\n      constructor; eauto.\n    - unfold restricted_step; intuition idtac.\n      inversion H1; clear H1; subst; repeat sigT_eq.\n      econstructor; eauto.\n  Qed.\n\n  Theorem initP_compat : forall s, hl1.initP s -> hl2.initP s.\n  Proof.\n    unfold hl1.initP, hl2.initP, horizInitP; intros.\n    specialize (H i); propositional.\n    eauto using a.initP_compat.\n  Qed.\n\n  Theorem raw_initP_compat : forall s, hl1raw.initP s -> hl1.initP s.\n  Proof.\n    unfold hl1raw.initP, hl1.initP, horizInitP; intros.\n    specialize (H i); propositional.\n    eauto using a.raw_initP_compat.\n  Qed.\n\nEnd LayerImplMoversProtocolHT.\n\n\nModule LayerImplMoversHT\n  (s : State)\n  (o1 : Ops) (l1 : Layer o1 s)\n  (o2 : Ops) (l2 : Layer o2 s)\n  (a : LayerImplMoversT s o1 l1 o2 l2)\n  (i : HIndex).\n\n  Module hs := HState s i.\n  Module ho1 := HOps o1 i.\n  Module ho2 := HOps o2 i.\n  Module hl1 := HLayer o1 s l1 i.\n  Module hl2 := HLayer o2 s l2 i.\n\n  Definition compile_op T (op : ho2.Op T) : proc ho1.Op T :=\n    match op with\n    | Slice i op => SliceProc i (a.compile_op op)\n    | CheckSlice i => Call (CheckSlice i)\n    end.\n\n  Theorem compile_op_no_atomics : forall T (op : ho2.Op T),\n    no_atomics (compile_op op).\n  Proof.\n    destruct op; simpl; eauto.\n    pose proof (a.compile_op_no_atomics op).\n    generalize dependent H.\n    generalize (a.compile_op op).\n    clear.\n    induction 1; simpl; eauto.\n  Qed.\n\n  Theorem ysa_movers : forall T (op : ho2.Op T),\n    ysa_movers hl1.step (compile_op op).\n  Proof.\n    destruct op; simpl; eauto.\n    eapply horiz_ysa_movers.\n    eapply a.ysa_movers.\n  Qed.\n\n  Theorem compile_correct :\n    compile_correct compile_op hl1.step hl2.step.\n  Proof.\n    intro; intros.\n    destruct op; simpl in *.\n    - eapply atomic_exec_horizStep in H; eauto; deex.\n      eapply a.compile_correct in H.\n      econstructor; eauto.\n    - repeat atomic_exec_inv.\n      inversion H5; clear H5; subst; repeat sigT_eq.\n      econstructor; eauto.\n  Qed.\n\n  Theorem initP_compat :\n    forall s, hl1.initP s -> hl2.initP s.\n  Proof.\n    unfold hl1.initP, hl2.initP.\n    unfold horizInitP; intros.\n    specialize (H i); propositional.\n    eauto using a.initP_compat.\n  Qed.\n\nEnd LayerImplMoversHT.\n\n\nModule LayerImplLoopHT\n  (s : State)\n  (o1 : Ops) (l1 : Layer o1 s)\n  (o2 : Ops) (l2 : Layer o2 s)\n  (a : LayerImplLoopT s o1 l1 o2 l2)\n  (i : HIndex).\n\n  Module hs := HState s i.\n  Module ho1 := HOps o1 i.\n  Module ho2 := HOps o2 i.\n  Module hl1 := HLayer o1 s l1 i.\n  Module hl2 := HLayer o2 s l2 i.\n\n  Definition compile_op T (op : ho2.Op T) :\n    (option T -> ho1.Op T) * (T -> bool) * option T :=\n    match op with\n    | Slice idx op' =>\n      let '(p, cond, i) := a.compile_op op' in\n        ((fun x => Slice idx (p x)), cond, i)\n    | CheckSlice idx =>\n      ((fun x => CheckSlice idx),\n        fun _ => true,\n        None)\n    end.\n\n  Theorem noop_or_success :\n    noop_or_success compile_op hl1.step hl2.step.\n  Proof.\n    intro; intros.\n    destruct opM; simpl in *.\n    {\n      destruct (a.compile_op op) eqn:He.\n      destruct p.\n      inversion H; clear H; subst.\n      inversion H0; clear H0; subst; repeat sigT_eq.\n      edestruct a.noop_or_success; eauto.\n      - left. intuition idtac.\n        subst.\n        destruct_validIndex.\n        rewrite hadd_hget_eq; eauto.\n      - right. intuition idtac.\n        econstructor; eauto.\n    }\n    {\n      inversion H; clear H; subst.\n      inversion H0; clear H0; subst; repeat sigT_eq.\n      right; intuition eauto.\n      econstructor; eauto.\n    }\n  Qed.\n\n  Theorem initP_compat :\n    forall s, hl1.initP s -> hl2.initP s.\n  Proof.\n    unfold hl1.initP, hl2.initP.\n    unfold horizInitP; intros.\n    specialize (H i); propositional.\n    eauto using a.initP_compat.\n  Qed.\n\nEnd LayerImplLoopHT.\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/Horizontal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2991458557302717}}
{"text": "(** A completely interactive command with variable amount of obligations **)\n\nRequire Import MetaCoq.Template.All.\n\nRequire Import List String.\nImport ListNotations MonadNotation Nat.\n\nFixpoint printer (n:nat) :=\nmatch n with \n| O => tmMsg \"All Done\";;\n       tmReturn 0\n| S m => \n  name <- tmFreshName \"tmp\";;\n  a <- tmLemma name nat;;\n  ssum <- (printer m);;\n  tmReturn (ssum + a)\nend.\n\n\nMetaCoq Run (n <- tmLemma \"t1\" nat;; \nn' <- tmEval all n;;\nsum <- printer n';;\nsumR <- tmEval all sum;;\ntmPrint sumR).\nNext Obligation.\n  exact 2.\nDefined.\nNext Obligation.\n  exact 3.\nDefined.\nNext Obligation.\n  exact 4.\nDefined.\n", "meta": {"author": "uds-psl", "repo": "metacoq-nested-induction", "sha": "0c523566290fe99da46a3e74da8652f02d7a3dd6", "save_path": "github-repos/coq/uds-psl-metacoq-nested-induction", "path": "github-repos/coq/uds-psl-metacoq-nested-induction/metacoq-nested-induction-0c523566290fe99da46a3e74da8652f02d7a3dd6/source/interactive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2990846027062401}}
{"text": "Require Import Cosa.Lib.Header.\nRequire Import Cosa.Lib.Relation.\nRequire Import Cosa.Interaction.Transition.\n\n(** Interaction structures, due to Peter Hancock, are an intentional\n    representation of transition systems with disjunctive (angelic)\n    and conjunctive (demonic) non-determinism. They are a very generic\n    kind of data and therefore can be used in various way. One of the\n    most important way is that it can be used to represent an\n    interface, where capabilities (in form of command) are provided by\n    an implementer, and a user can issue commands to advance the\n    internal state. They can also be used as proof inference systems,\n    which we shall leverage for certificate checking.\n\n    The definition of interaction structures given here is expanded,\n    but an alternative definition is [A -> Fam (Fam B)], where\n    [Fam X = { i:Type & I -> X}] is the type of families on [X] with\n    an arbitrary index. *)\n\nRecord Interaction {A B:Type} := {\n  Com : A -> Type; (** Issuable commands *)\n  Resp : forall {a:A}, Com a -> Type; (** Responses *)\n  Output : forall {a:A} {c:Com a}, Resp c -> B (** Output state *)\n}.\nArguments Interaction _ _ : clear implicits.\n\nDefinition Interface (A:Type) := Interaction A A.\n\n(** Predicate transformers *)\n\n(** For any complete lattice Ω, interaction structures act on\n    \"predicates\" mapping into Ω. Mapping commands to a join and\n    responses to a meet. *)\nDefinition Angelic {A B} Γ (i:Interaction A B) : (B->rel Γ) -> (A->rel Γ) :=\n  fun X a => Join (fun c:i.(Com) a => Meet (fun x:i.(Resp) c => X(i.(Output) x)))\n.\n\nInstance angelic_increasing {A B} Γ (i:Interaction A B) :\n  Proper (@sub (B::Γ) ==> @sub (A::Γ)) (Angelic Γ i)\n.\nProof.\n  unfold Proper, respectful, Subset, Angelic.\n  intros p q p_sub_q;simpl; intros a.\n  apply Join_increasing; simpl; intros c.\n  apply Meet_increasing; simpl.\n  eauto.\nQed.\n  \n(** Dually, we can map commands to a meet and responses to a join. *)\nDefinition Demonic {A B} Γ (i:Interaction A B) : (B->rel Γ) -> (A->rel Γ) :=\n  fun X a => Meet (fun c:i.(Com) a => Join (fun x:i.(Resp) c => X(i.(Output) x)))\n.\n\nInstance demonic_increasing {A B} Γ (i:Interaction A B) :\n  Proper (@sub (B::Γ) ==> @sub (A::Γ)) (Demonic Γ i)\n.\nProof.\n  unfold Proper, respectful, Subset, Demonic.\n  intros p q p_sub_q; simpl; intros a.\n  apply Meet_increasing; simpl; intros c.\n  apply Join_increasing; simpl.\n  eauto.\nQed.\n\n(** Sequence *)\n\nDefinition skip {S} : Interface S := {|\n  Com s := unit ;\n  Resp s c := unit ;\n  Output s c x := s\n|}.\n\nDefinition seq {S T U} (i:Interaction S T) (j:Interaction T U) : Interaction S U := {|\n  Com s := { c₁ : i.(Com) s & forall x₁:i.(Resp) c₁, j.(Com) (i.(Output) x₁) } ;\n  Resp s c := { x₁ : i.(Resp) (projT1 c) & j.(Resp) (projT2 c x₁) };\n  Output s c x := j.(Output) (projT2 x)\n|}.\n\n(** \"Monadic\" unit and bind *)\nDefinition munit {S A} (a:A) : Interaction S (A*S) := {|\n  Com s := unit ;\n  Resp s c := unit ;\n  Output s c x := (a,s)\n|}.\n\nDefinition curry {A S T} (i:A->Interaction S T) : Interaction (A*S) T := {|\n  Com s := (i (fst s)).(Com) (snd s);\n  Resp s c := (i (fst s)).(Resp) c;\n  Output s c x := (i (fst s)).(Output) x\n|}.\n\nDefinition bind {S T U A} (i:Interaction S (A*T)) (j:A->Interaction T U) : Interaction S U :=\n  seq i (curry j)\n.\n\n(** Cartesian product *)\n\nDefinition pi {A S T} (i:A->Interaction S T) : Interaction S T := {|\n  Com s := forall a:A, (i a).(Com) s ;\n  Resp s c := { a:A & (i a).(Resp) (c a) } ;\n  Output s c x := (i (projT1 x)).(Output) (projT2 x)\n|}.\n\n(** Sum *)\n\nDefinition sigma {A S T} (i:A->Interaction S T) : Interaction S T := {|\n  Com s := { a:A & (i a).(Com) s } ;\n  Resp s c := (i (projT1 c)).(Resp) (projT2 c) ;\n  Output s c x := (i (projT1 c)).(Output) x\n|}.\n\n(** Tensor product *)\n\nDefinition tensor {S₁ T₁ S₂ T₂} (i:Interaction S₁ T₁) (j:Interaction S₂ T₂) : Interaction (S₁*S₂) (T₁*T₂) := {|\n  Com s := (i.(Com) (fst s) * j.(Com) (snd s))%type ;\n  Resp s c := (i.(Resp) (fst c) * j.(Resp) (snd c))%type ;\n  Output s c x := (i.(Output) (fst x) , j.(Output) (snd x))\n|}.\n\n(** Angelic iteration *)\n\nInductive Prog {S} {i:Interface S} {s:S} : Type:=\n | ret : Prog\n | issue (c:i.(Com) s) (k:forall (x:i.(Resp) c), @Prog S i (i.(Output) x)) : Prog\n.\nArguments Prog {S} i _ : clear implicits.\n\n(* arnaud: TProg et RProg sont assez mystérieux avec tous ces arguments implicites. Il vaudrait peut-être bien de les expliquer un peu mieux, ou peut-être de rendre plus d'arguments explicites… *)\nFixpoint TProg {S} {i:Interface S} {s} (p:Prog i s) : Type :=\n  match p with\n  | ret => unit\n  | issue c k => { x:i.(Resp) c & TProg (k x) }\n  end\n.\n\nFixpoint RProg {S} {i:Interface S} {s} {p:Prog i s} (x:TProg p) : S :=\n  match p return TProg p -> S with\n  | ret => fun _ => s\n  | issue c k => fun x => RProg (projT2 x)\n  end x\n.\n\nDefinition angelic_iteration {S} (i:Interface S) : Interface S := {|\n  Com s := Prog i s ;\n  Resp s c := TProg c ;\n  Output s c x := RProg x\n|}.\n\n(*** Demonic iteration ***)\n\n(* TODO *)\n\n(*** Angelic extension of transition structure. ***)\nDefinition angelic_extension {S T} (t:Transition S T) : Interaction S T := {|\n  Com := t.(trans) ;\n  Resp s c := unit ;\n  Output s c x := t.(next) s c\n|}.\n\n(*** Demonic extension of transition structure. ***)\nDefinition demonic_extension {S T} (t:Transition S T) : Interaction S T := {|\n  Com s := unit ; \n  Resp s c := t.(trans) s ;\n  Output s c x := t.(next) s x\n|}.\n\n(** Extension of a function *)\nDefinition functional_extension {S T} (f:S->T) : Interaction S T := {|\n  Com s := unit ;\n  Resp s c := unit ;\n  Output s c x := f s\n|}.\n\n(*** Interaction structures as proof systems ***)\n\n(* Interfaces are seen as a set of inference rules, where the states\n   are the goals or judgement to be proved.\n\n   The type of proofs for a given set of inference rules is just like\n   the type of programs except there is no way to return the current\n   goal: the proof is finished when there are no goals left to prove,\n   i.e. when issuing a command whose return type is the empty type. *)\nInductive Proof_of {S} {i:Interface S} {s:S} : Type:=\n | rule (c:i.(Com) s) (k:forall (x:i.(Resp) c), @Proof_of S i (i.(Output) x)) : Proof_of\n.\nArguments Proof_of {S} i _ : clear implicits.", "meta": {"author": "aspiwack", "repo": "cosa", "sha": "2d808236e71f2289033dff6b74a3f57311df9a14", "save_path": "github-repos/coq/aspiwack-cosa", "path": "github-repos/coq/aspiwack-cosa/cosa-2d808236e71f2289033dff6b74a3f57311df9a14/Interaction/Interaction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2990846027062401}}
{"text": "Require Import Coq.Sets.Ensembles Bedrock.Platform.AutoSep Bedrock.Platform.Malloc.\nRequire Import Bedrock.Platform.Facade.examples.FiatADTs.\n\nInfix \"===\" := (@Same_set W).\n\nDefinition empty := Empty_set W.\nNotation \"%0\" := empty.\n\n(* Who knows why this wrapper is necessary to keep the tactics happy.... *)\nModule Type HAS.\n  Parameter has : Ensemble W -> W -> Prop.\n  Axiom has_eq : has = Ensembles.In _.\nEnd HAS.\n\nModule Has : HAS.\n  Definition has := Ensembles.In W.\n  Theorem has_eq : has = Ensembles.In _.\n    auto.\n  Qed.\nEnd Has.\n\nImport Has.\nExport Has.\n\nInfix \"%has\" := has (at level 70).\n\nDefinition add := Ensembles.Add W.\nInfix \"%+\" := add (at level 50).\n\nDefinition sub := Subtract W.\nInfix \"%-\" := sub (at level 50).\n\nSection adt.\n  Variable P : Ensemble W -> W -> HProp.\n  Variable res : nat.\n\n  Definition newS := SPEC(\"extra_stack\") reserving res\n    PRE[_] mallocHeap 0\n    POST[R] P %0 R * mallocHeap 0.\n\n  Definition deleteS := SPEC(\"extra_stack\", \"self\") reserving res\n    Al s,\n    PRE[V] P s (V \"self\") * mallocHeap 0\n    POST[R] [| R = $0 |] * mallocHeap 0.\n\n  Definition memS := SPEC(\"extra_stack\", \"self\", \"n\") reserving res\n    Al s,\n    PRE[V] P s (V \"self\") * mallocHeap 0\n    POST[R] [| s %has V \"n\" \\is R |] * P s (V \"self\") * mallocHeap 0.\n\n  Definition addS := SPEC(\"extra_stack\", \"self\", \"n\") reserving res\n    Al s,\n    PRE[V] P s (V \"self\") * mallocHeap 0\n    POST[R] [| R = $0 |] * P (s %+ V \"n\") (V \"self\") * mallocHeap 0.\n\n  Definition removeS := SPEC(\"extra_stack\", \"self\", \"n\") reserving res\n    Al s,\n    PRE[V] P s (V \"self\") * mallocHeap 0\n    POST[R] [| R = $0 |] * P (s %- V \"n\") (V \"self\") * mallocHeap 0.\n\n  Definition cardinal_is (s : Ensemble W) (R : W) :=\n    exists n, cardinal _ s n /\\ R = natToWord _ n.\n\n  Definition sizeS := SPEC(\"extra_stack\", \"self\") reserving res\n    Al s,\n    PRE[V] P s (V \"self\") * mallocHeap 0\n    POST[R] [| cardinal_is s R |] * P s (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/FiniteSetF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.4921881357207955, "lm_q1q2_score": 0.29908460270624004}}
{"text": "(** * K(A), the naive homotopy category of C(A) *)\n(** ** Contents\n- Definition of K(A)\n*)\nRequire Import UniMath.Foundations.UnivalenceAxiom.\nRequire Import UniMath.Foundations.PartD.\nRequire Import UniMath.Foundations.Propositions.\nRequire Import UniMath.Foundations.Sets.\nRequire Import UniMath.Foundations.NaturalNumbers.\n\nRequire Import UniMath.MoreFoundations.Tactics.\n\nRequire Import UniMath.Algebra.BinaryOperations.\nRequire Import UniMath.Algebra.Monoids.\nRequire Import UniMath.Algebra.Groups.\n\nRequire Import UniMath.NumberSystems.Integers.\n\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.TransportMorphisms.\nRequire Import UniMath.CategoryTheory.limits.zero.\nRequire Import UniMath.CategoryTheory.limits.binproducts.\nRequire Import UniMath.CategoryTheory.limits.bincoproducts.\nRequire Import UniMath.CategoryTheory.limits.equalizers.\nRequire Import UniMath.CategoryTheory.limits.coequalizers.\nRequire Import UniMath.CategoryTheory.limits.kernels.\nRequire Import UniMath.CategoryTheory.limits.cokernels.\nRequire Import UniMath.CategoryTheory.limits.pushouts.\nRequire Import UniMath.CategoryTheory.limits.pullbacks.\nRequire Import UniMath.CategoryTheory.limits.BinDirectSums.\nRequire Import UniMath.CategoryTheory.Monics.\nRequire Import UniMath.CategoryTheory.Epis.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.Equivalences.Core.\n\nRequire Import UniMath.CategoryTheory.CategoriesWithBinOps.\nRequire Import UniMath.CategoryTheory.PrecategoriesWithAbgrops.\nRequire Import UniMath.CategoryTheory.PreAdditive.\nRequire Import UniMath.CategoryTheory.Additive.\nRequire Import UniMath.CategoryTheory.Abelian.\nRequire Import UniMath.CategoryTheory.AbelianToAdditive.\nRequire Import UniMath.CategoryTheory.AdditiveFunctors.\n\nRequire Import UniMath.HomologicalAlgebra.Complexes.\n\nLocal Open Scope cat.\n\nUnset Kernel Term Sharing.\nGlobal Opaque hz.\n\nLocal Open Scope hz_scope.\nOpaque hz isdecrelhzeq hzplus hzminus hzone hzzero iscommringops ZeroArrow ishinh.\n\n(** * Homotopies of complexes and K(A), the naive homotopy category of A. *)\n(** ** Introduction\n   We define homotopy of complexes and the naive homotopy category K(A). A homotopy χ from complex\n   X to a complex Y is a family of morphisms χ^i : X^i --> Y^{i-1}. Note that a homotopy χ induces\n   a morphism of complexes h : X --> Y by setting\n                      # h^i = χ^i · d^{i-1}_Y + d^i_X · χ^{i+1}. #\n                      $ h^i = χ^i · d^{i-1}_Y + d^i_X · χ^{i+1}. $\n   The subset of morphisms in Mor(X, Y) which are of the form h form an abelian subgroup of\n   Mor(X, Y). Also, if f : Z_1 --> X and g : Y --> Z_2 are morphisms of complexes, then f · h and\n   h · g have paths to morphisms induced by homotopies. These are given (f^i · χ^i) and\n   (χ^i · g^{i-1}), respectively.\n\n   These are the properties that are enough to form the quotient category of C(A) using\n   [Quotcategory_Additive]. We call the resulting category the naive homotopy category of A, and\n   denote it by K(A). The objects of K(A) are objects of C(A) and Mor_{K(A)}(X, Y) =\n   Mor_{C(A)}(X, Y) / (the subgroup of null-homotopic morphisms, [ComplexHomotSubgrp]).\n\n   Homotopies are defined in [ComplexHomot]. The induced morphisms of a homotopy is constructed in\n   [ComplexHomotMorphism]. The subgroup of morphisms coming from homotopies is defined in\n   [ComplexHomotSubgrp]. Pre- and postcomposition of morphisms coming from homotopies are morphisms\n   coming from homotopies are proven in [ComplexHomotSubgrop_comp_right] and\n   [ComplexHomotSubgrop_comp_left]. The naive homotopy category K(A) is constructed in\n   [ComplexHomot_Additive].\n*)\nSection complexes_homotopies.\n\n  Variable A : CategoryWithAdditiveStructure.\n\n  Definition ComplexHomot (C1 C2 : Complex A) : UU := ∏ (i : hz), A⟦C1 i, C2 (i - 1)⟧.\n\n  (** This lemma shows that the squares of the morphism map, defined by the homotopy H, commute. *)\n  Local Lemma ComplexHomotMorphism_comm {C1 C2 : Complex A} (H : ComplexHomot C1 C2) (i : hz) :\n    to_binop (C1 i) (C2 i)\n             (transportf (precategory_morphisms (C1 i)) (maponpaths C2 (hzrminusplus i 1))\n                         (H i · Diff C2 (i - 1)))\n             (transportf (precategory_morphisms (C1 i)) (maponpaths C2 (hzrplusminus i 1))\n                         (Diff C1 i · H (i + 1))) ·\n             Diff C2 i =\n    Diff C1 i · to_binop (C1 (i + 1)) (C2 (i + 1))\n         (transportf (precategory_morphisms (C1 (i + 1))) (maponpaths C2 (hzrminusplus (i + 1) 1))\n                     (H (i + 1) · Diff C2 (i + 1 - 1)))\n         (transportf (precategory_morphisms (C1 (i + 1))) (maponpaths C2 (hzrplusminus (i + 1) 1))\n                     (Diff C1 (i + 1) · H (i + 1 + 1))).\n  Proof.\n    (* First we get rid of the ZeroArrows *)\n    rewrite to_postmor_linear'. rewrite to_premor_linear'.\n    assert (e0 : (transportf (precategory_morphisms (C1 i)) (maponpaths C2 (hzrminusplus i 1))\n                             (H i · Diff C2 (i - 1)) ·\n                             Diff C2 i) = ZeroArrow (Additive.to_Zero A) _ _).\n    {\n      induction (hzrminusplus i 1). cbn. rewrite <- assoc.\n      rewrite (@DSq A C2 (i - 1)). apply ZeroArrow_comp_right.\n    }\n    rewrite e0. clear e0.\n    assert (e1 : (Diff C1 i · transportf (precategory_morphisms (C1 (i + 1)))\n                       (maponpaths\n                          C2 (hzrplusminus (i + 1) 1)) (Diff C1 (i + 1) · H (i + 1 + 1))) =\n                 ZeroArrow (Additive.to_Zero A) _ _).\n    {\n      rewrite <- transport_target_postcompose. rewrite assoc. rewrite (@DSq A C1 i).\n      rewrite ZeroArrow_comp_left. apply transport_target_ZeroArrow.\n    }\n    rewrite e1. clear e1.\n    rewrite <- PreAdditive_unel_zero. rewrite to_lunax'. rewrite to_runax'.\n    (* Here the idea is to apply cancel_precomposition *)\n    rewrite transport_target_postcompose. rewrite <- assoc. apply cancel_precomposition.\n    (* Other application of cancel_precomposition *)\n    rewrite transport_compose. rewrite transport_target_postcompose. apply cancel_precomposition.\n    (* Follows frm transport of differentials *)\n    apply pathsinv0. rewrite <- maponpathsinv0.\n    use (pathscomp0 _ (transport_hz_section A C2 1 (Diff C2) _ _ (hzrplusminus i 1))).\n    use transportf_paths. apply maponpaths. apply isasethz.\n  Qed.\n\n  (** Every homotopy H of complexes induces a morphism of complexes. The morphism is defined by\n      taking the map C1 i --> C2 i to be the sum\n                         (H i) · (Diff C2 (i - 1)) + (Diff C1 i) · (H (i + 1)).\n      Note that we need to use transportf because the targets are not definitionally equal. The\n      target of the first is C2 (i - 1 + 1) and the second target is C2 (i + 1 - 1). We transport\n      these to C2 i. *)\n  Definition ComplexHomotMorphism {C1 C2 : Complex A} (H : ComplexHomot C1 C2) : Morphism C1 C2.\n  Proof.\n    use make_Morphism.\n    - intros i.\n      use (@to_binop A (C1 i) (C2 i)).\n      + exact (transportf _ (maponpaths C2 (hzrminusplus i 1)) ((H i) · (Diff C2 (i - 1)))).\n      + exact (transportf _ (maponpaths C2 (hzrplusminus i 1)) ((Diff C1 i) · (H (i + 1)))).\n    - intros i. exact (ComplexHomotMorphism_comm H i).\n  Defined.\n\n  (** For all complexes C1 and C2, we define a subset of C1 --> C2 to consist of all the morphisms\n      which have a path to a morphism induced by a homotopy H by [ComplexHomotMorphism]. Our goal is\n      to show that this subset is an abelian subgroup, and thus we can form the quotient group. *)\n  Definition ComplexHomotSubset (C1 C2 : Complex A) :\n    @hsubtype ((ComplexPreCat_Additive A)⟦C1, C2⟧) :=\n    (fun (f : ((ComplexPreCat_Additive A)⟦C1, C2⟧)) =>\n       ∃ (H : ComplexHomot C1 C2), ComplexHomotMorphism H = f).\n\n  (** This lemma shows that the subset [ComplexHomotSubset] satisfies the axioms of a subgroup. *)\n  Lemma ComplexHomotisSubgrop (C1 C2 : Complex A) :\n    @issubgr (@to_abgr (ComplexPreCat_Additive A) C1 C2) (ComplexHomotSubset C1 C2).\n  Proof.\n    use tpair.\n    - use tpair.\n      + intros f g. induction f as [f1 f2]. induction g as [g1 g2].\n        use (squash_to_prop f2).\n        { apply propproperty. }\n        intros f3.\n        use (squash_to_prop g2).\n        { apply propproperty. }\n        intros g3.\n        induction f3 as [f3 f4].\n        induction g3 as [g3 g4].\n        use hinhpr. cbn.\n        use tpair.\n        * intros i.\n          use to_binop.\n          -- exact (f3 i).\n          -- exact (g3 i).\n        * cbn.\n          rewrite <- f4. rewrite <- g4.\n          use MorphismEq.\n          intros i. cbn.\n          rewrite to_postmor_linear'.\n          rewrite to_premor_linear'.\n          assert (e0 : (transportf (precategory_morphisms (C1 i)) (maponpaths C2 (hzrplusminus i 1))\n                                   (to_binop (C1 i) (C2 (i + 1 - 1)) (Diff C1 i · f3 (i + 1))\n                                             (Diff C1 i · g3 (i + 1)))) =\n                       to_binop (C1 i) (C2 i)\n                                (transportf (precategory_morphisms (C1 i))\n                                            (maponpaths C2 (hzrplusminus i 1))\n                                            (Diff C1 i · f3 (i + 1)))\n                                (transportf (precategory_morphisms (C1 i))\n                                            (maponpaths C2 (hzrplusminus i 1))\n                                            (Diff C1 i · g3 (i + 1)))).\n          {\n            induction (hzrplusminus i 1). apply idpath.\n          }\n          cbn in e0. rewrite e0. clear e0.\n          assert (e1 : (transportf (precategory_morphisms (C1 i)) (maponpaths C2 (hzrminusplus i 1))\n                                   (to_binop (C1 i) (C2 (i - 1 + 1)) (f3 i · Diff C2 (i - 1))\n                                             (g3 i · Diff C2 (i - 1)))) =\n                       to_binop (C1 i) (C2 i)\n                                (transportf (precategory_morphisms (C1 i))\n                                            (maponpaths C2 (hzrminusplus i 1))\n                                            (f3 i · Diff C2 (i - 1)))\n                                (transportf (precategory_morphisms (C1 i))\n                                            (maponpaths C2 (hzrminusplus i 1))\n                                            (g3 i · Diff C2 (i - 1)))).\n          {\n            induction (hzrminusplus i 1). apply idpath.\n          }\n          cbn in e1. rewrite e1. clear e1.\n          set (tmp := @assocax (@to_abgr A (C1 i) (C2 i))). cbn in tmp.\n          rewrite tmp. rewrite tmp. apply maponpaths.\n          rewrite <- tmp. rewrite <- tmp.\n          set (tmp' := @commax (@to_abgr A (C1 i) (C2 i))). cbn in tmp'.\n          rewrite tmp'.\n          rewrite (tmp' _ (transportf (precategory_morphisms (C1 i))\n                                      (maponpaths C2 (hzrplusminus i 1))\n                                      (Diff C1 i · g3 (i + 1)))).\n          apply maponpaths.\n          apply tmp'.\n      (* ZeroMorphisms *)\n      + use hinhpr.\n        use tpair.\n        * intros i. exact (ZeroArrow (Additive.to_Zero A) _ _).\n        * cbn. use MorphismEq. intros i. cbn. rewrite ZeroArrow_comp_left.\n          rewrite transport_target_ZeroArrow.\n          rewrite ZeroArrow_comp_right. rewrite transport_target_ZeroArrow.\n          rewrite <- PreAdditive_unel_zero. rewrite to_lunax'. apply idpath.\n    - intros f H. use (squash_to_prop H).\n      { apply propproperty. }\n      intros H'. clear H.\n      induction H' as [homot eq]. use hinhpr.\n      use tpair.\n      + intros i. exact (grinv (to_abgr (C1 i) (C2 (i - 1))) (homot i)).\n      + cbn. rewrite <- eq. use MorphismEq. intros i. cbn.\n        set (tmp := @PreAdditive_invrcomp A _ _ _ (Diff C1 i) (homot (i + 1))).\n        unfold to_inv in tmp. cbn in tmp. cbn. rewrite <- tmp. clear tmp.\n        assert (e0 : (transportf (precategory_morphisms (C1 i))\n                                 (maponpaths C2 (hzrplusminus i 1))\n                                 (grinv (to_abgr (C1 i) (C2 (i + 1 - 1)))\n                                        (Diff C1 i · homot (i + 1)))) =\n                     to_inv (transportf (precategory_morphisms (C1 i))\n                                        (maponpaths C2 (hzrplusminus i 1))\n                                        (Diff C1 i · homot (i + 1)))).\n        {\n          unfold to_inv. cbn. induction (hzrplusminus i 1). apply idpath.\n        }\n        cbn in e0. rewrite e0. clear e0.\n        assert (e1 : (transportf (precategory_morphisms (C1 i)) (maponpaths C2 (hzrminusplus i 1))\n                                 (grinv (to_abgr (C1 i) (C2 (i - 1)))\n                                        (homot i) · Diff C2 (i - 1))) =\n                     to_inv (transportf (precategory_morphisms (C1 i))\n                                        (maponpaths C2 (hzrminusplus i 1))\n                                        (homot i · Diff C2 (i - 1)))).\n        {\n          unfold to_inv. cbn. induction (hzrminusplus i 1). cbn.\n          set (tmp := @PreAdditive_invlcomp A (C1 i) (C2 (i - 1)) (C2 (i - 1 + 1))\n                                            (homot i) (Diff C2 (i - 1))).\n          apply pathsinv0. unfold to_inv in tmp.\n          apply tmp.\n        }\n        cbn in e1. rewrite e1. clear e1.\n        set (tmp' := @commax (@to_abgr A (C1 i) (C2 i))). cbn in tmp'. rewrite tmp'. clear tmp'.\n        set (tmp := @grinvop (@to_abgr A (C1 i) (C2 i))). cbn in tmp. unfold to_inv.\n        apply pathsinv0.\n        apply tmp.\n  Qed.\n\n  Definition ComplexHomotSubgrp (C1 C2 : Complex A) :\n    @subabgr (@to_abgr (ComplexPreCat_Additive A) C1 C2).\n  Proof.\n    use subgrconstr.\n    - exact (ComplexHomotSubset C1 C2).\n    - exact (ComplexHomotisSubgrop C1 C2).\n  Defined.\n\n  (** Pre- and postcomposition with morphisms in ComplexHomotSubset is in ComplexHomotSubset. *)\n  Lemma ComplexHomotSubgrop_comp_left (C1 : Complex A) {C2 C3 : Complex A}\n        (f : ((ComplexPreCat_Additive A)⟦C2, C3⟧)) (H : ComplexHomotSubset C2 C3 f) :\n    ∏ (g : ((ComplexPreCat_Additive A)⟦C1, C2⟧)), ComplexHomotSubset C1 C3 (g · f).\n  Proof.\n    intros g.\n    use (squash_to_prop H).\n    { apply propproperty. }\n    intros HH.\n    use hinhpr.\n    induction HH as [homot eq].\n    use tpair.\n    - intros i. exact ((MMor g i) · (homot i)).\n    - cbn. rewrite <- eq. use MorphismEq. intros i. cbn. rewrite assoc.\n      rewrite <- (MComm g i). rewrite transport_target_postcompose.\n      rewrite transport_target_postcompose.\n      rewrite <- assoc. rewrite <- assoc. rewrite <- to_premor_linear'.\n      rewrite <- transport_target_postcompose. rewrite <- transport_target_postcompose.\n      apply idpath.\n  Qed.\n\n  Lemma ComplexHomotSubgrop_comp_right {C1 C2 : Complex A} (C3 : Complex A)\n        (f : ((ComplexPreCat_Additive A)⟦C1, C2⟧)) (H : ComplexHomotSubset C1 C2 f) :\n    ∏ (g : ((ComplexPreCat_Additive A)⟦C2, C3⟧)), ComplexHomotSubset C1 C3 (f · g).\n  Proof.\n    intros g.\n    use (squash_to_prop H).\n    { apply propproperty. }\n    intros HH.\n    use hinhpr.\n    induction HH as [homot eq].\n    use tpair.\n    - intros i. exact ((homot i) · (MMor g (i - 1))).\n    - cbn. rewrite <- eq. use MorphismEq. intros i. cbn. rewrite <- assoc.\n      rewrite (MComm g (i - 1)). rewrite assoc. rewrite assoc.\n      assert (e0 : (transportf (precategory_morphisms (C1 i)) (maponpaths C3 (hzrminusplus i 1))\n                               (homot i · Diff C2 (i - 1) · MMor g (i - 1 + 1))) =\n                   (transportf (precategory_morphisms (C1 i)) (maponpaths C2 (hzrminusplus i 1))\n                               (homot i · Diff C2 (i - 1))) · (MMor g i)).\n      {\n        induction (hzrminusplus i 1). apply idpath.\n      }\n      cbn in e0. rewrite e0. clear e0.\n      assert (e1 : (transportf (precategory_morphisms (C1 i)) (maponpaths C3 (hzrplusminus i 1))\n                               (Diff C1 i · homot (i + 1) · MMor g (i + 1 - 1))) =\n                   (transportf (precategory_morphisms (C1 i)) (maponpaths C2 (hzrplusminus i 1))\n                               (Diff C1 i · homot (i + 1))) · (MMor g i)).\n      {\n        induction (hzrplusminus i 1). apply idpath.\n      }\n      cbn in e1. rewrite e1. clear e1.\n      rewrite <- to_postmor_linear'. apply idpath.\n  Qed.\n\n\n  (** ** Naive homotopy category\n     We know that the homotopies from C1 to C2 form an abelian subgroup of the abelian group of all\n     morphisms from C1 to C2, by [ComplexHomotSubgrp]. We also know that composition of a morphism\n     with a morphism coming from a homotopy, is a morphism which comes from a homotopy, by\n     [ComplexHomotSubgrop_comp_left] and [ComplexHomotSubgrop_comp_right]. This is enough to\n     invoke our abstract construction Quotcategory_Additive, to construct the naive homotopy\n     category. *)\n  Local Lemma ComplexHomot_Additive_Comp :\n    PreAdditiveComps (ComplexPreCat_Additive A)\n                     (λ C1 C2 : ComplexPreCat_Additive A, ComplexHomotSubgrp C1 C2).\n  Proof.\n    intros C1 C2. split.\n    - intros C3 f H g.\n      apply ComplexHomotSubgrop_comp_right. apply H.\n    - intros C3 f g H.\n      apply ComplexHomotSubgrop_comp_left. apply H.\n  Qed.\n\n  (** Here we construct K(A). *)\n  Definition ComplexHomot_Additive : CategoryWithAdditiveStructure :=\n    Quotcategory_Additive\n      (ComplexPreCat_Additive A) ComplexHomotSubgrp ComplexHomot_Additive_Comp.\n\n  Definition ComplexHomotFunctor :\n    AdditiveFunctor (ComplexPreCat_Additive A) ComplexHomot_Additive :=\n    QuotcategoryAdditiveFunctor\n      (ComplexPreCat_Additive A) ComplexHomotSubgrp ComplexHomot_Additive_Comp.\n  Arguments ComplexHomotFunctor : simpl never.\n\n  Lemma ComplexHomotFunctor_issurj {C1 C2 : ComplexPreCat_Additive A}\n        (f : ComplexHomot_Additive⟦C1, C2⟧) : ∥ hfiber (# ComplexHomotFunctor) f ∥.\n  Proof.\n    apply issurjsetquotpr.\n  Qed.\n\n  Lemma ComplexHomotFunctor_rel_mor {C1 C2 : ComplexPreCat_Additive A}\n        (f g : (ComplexPreCat_Additive A)⟦C1, C2⟧) (H : subgrhrel (ComplexHomotSubgrp C1 C2) f g) :\n    # ComplexHomotFunctor f = # ComplexHomotFunctor g.\n  Proof.\n    apply abgrquotpr_rel_image. apply H.\n  Qed.\n\n  Lemma ComplexHomotFunctor_rel_mor' {C1 C2 : ComplexPreCat_Additive A}\n        (f g : (ComplexPreCat_Additive A)⟦C1, C2⟧) (H : ComplexHomot C1 C2)\n        (H' : to_binop _ _ f (to_inv g) = ComplexHomotMorphism H) :\n    # ComplexHomotFunctor f = # ComplexHomotFunctor g.\n  Proof.\n    apply ComplexHomotFunctor_rel_mor.\n    use hinhpr.\n    use tpair.\n    - cbn. use tpair.\n      + exact (ComplexHomotMorphism H).\n      + use hinhpr.\n        use tpair.\n        * exact H.\n        * apply idpath.\n    - exact (! H').\n  Qed.\n\n  Lemma ComplexHomotFunctor_mor_rel {C1 C2 : ComplexPreCat_Additive A}\n        (f g : (ComplexPreCat_Additive A)⟦C1, C2⟧)\n        (H : # ComplexHomotFunctor f = # ComplexHomotFunctor g) :\n    subgrhrel (ComplexHomotSubgrp C1 C2) f g.\n  Proof.\n    use (@abgrquotpr_rel_paths _ (binopeqrel_subgr_eqrel (ComplexHomotSubgrp C1 C2))).\n    apply H.\n  Qed.\n\n  Lemma ComplexHomotFunctor_im_to_homot {C1 C2 : ComplexPreCat_Additive A}\n        (f g : (ComplexPreCat_Additive A)⟦C1, C2⟧)\n        (H : # ComplexHomotFunctor f = # ComplexHomotFunctor g) :\n    ∥ ∑ h : ComplexHomot C1 C2, ComplexHomotMorphism h = to_binop _ _ f (to_inv g) ∥.\n  Proof.\n    use (squash_to_prop (ComplexHomotFunctor_mor_rel f g H) (propproperty _)). intros h.\n    induction h as [b hh]. cbn in b. unfold ComplexHomotSubset in b.\n    use (squash_to_prop (pr2 b) (propproperty _)). intros hhh.\n    induction hhh as [H1 H2]. cbn in hh. cbn in H2.\n    use hinhpr.\n    use tpair.\n    - exact H1.\n    - exact (H2 @ hh).\n  Qed.\n\n  Lemma ComplexHomotPreCompHomot {C1 C2 C3 : ComplexPreCat_Additive A}\n        (f1 : (ComplexPreCat_Additive A)⟦C1, C2⟧) (f2 f3 : (ComplexPreCat_Additive A)⟦C2, C3⟧)\n        (H : # ComplexHomotFunctor f2 = # ComplexHomotFunctor f3) :\n    ∥ ∑ (h : ComplexHomot C1 C3),\n    ComplexHomotMorphism h = to_binop _ _ (f1 · f2) (to_inv (f1 · f3)) ∥.\n  Proof.\n    assert (e : # ComplexHomotFunctor (f1 · f2) = # ComplexHomotFunctor (f1 · f3)).\n    {\n      rewrite functor_comp. rewrite H. rewrite functor_comp. apply idpath.\n    }\n    exact (ComplexHomotFunctor_im_to_homot (f1 · f2) (f1 · f3) e).\n  Qed.\n\n  Lemma ComplexHomotPostCompHomot {C1 C2 C3 : ComplexPreCat_Additive A}\n        (f1 f2 : (ComplexPreCat_Additive A)⟦C1, C2⟧) (f3 : (ComplexPreCat_Additive A)⟦C2, C3⟧)\n        (H : # ComplexHomotFunctor f1 = # ComplexHomotFunctor f2) :\n    ∥ ∑ (h : ComplexHomot C1 C3),\n    ComplexHomotMorphism h = to_binop _ _ (f1 · f3) (to_inv (f2 · f3)) ∥.\n  Proof.\n    assert (e : # ComplexHomotFunctor (f1 · f3) = # ComplexHomotFunctor (f2 · f3)).\n    {\n      rewrite functor_comp. rewrite H. rewrite functor_comp. apply idpath.\n    }\n    exact (ComplexHomotFunctor_im_to_homot (f1 · f3) (f2 · f3) e).\n  Qed.\n\n  (** Commutativity of squares *)\n\n  Lemma ComplexHomotComm2 {C1 C2 C3 C4 : ob ComplexHomot_Additive}\n        {f1 : C1 --> C2} {f2 : C2 --> C4} {g1 : C1 --> C3} {g2 : C3 --> C4}\n        (f1' : hfiber (# ComplexHomotFunctor) f1) (f2' : hfiber (# ComplexHomotFunctor) f2)\n        (g1' : hfiber (# ComplexHomotFunctor) g1) (g2' : hfiber (# ComplexHomotFunctor) g2)\n        (H : f1 · f2 = g1 · g2) :\n    # ComplexHomotFunctor ((hfiberpr1 _ _ f1') · (hfiberpr1 _ _ f2')) =\n    # ComplexHomotFunctor ((hfiberpr1 _ _ g1') · (hfiberpr1 _ _ g2')).\n  Proof.\n    rewrite functor_comp. rewrite functor_comp.\n    rewrite (hfiberpr2 _ _ f1'). rewrite (hfiberpr2 _ _ f2').\n    rewrite (hfiberpr2 _ _ g1'). rewrite (hfiberpr2 _ _ g2').\n    exact H.\n  Qed.\n\n  Lemma ComplexHomotComm3 {C1 C2 C3 C4 C5 C6 : ob ComplexHomot_Additive}\n        {f1 : C1 --> C2} {f2 : C2 --> C3} {f3 : C3 --> C6}\n        {g1 : C1 --> C4} {g2 : C4 --> C5} {g3 : C5 --> C6}\n        (f1' : hfiber (# ComplexHomotFunctor) f1) (f2' : hfiber (# ComplexHomotFunctor) f2)\n        (f3' : hfiber (# ComplexHomotFunctor) f3)\n        (g1' : hfiber (# ComplexHomotFunctor) g1) (g2' : hfiber (# ComplexHomotFunctor) g2)\n        (g3' : hfiber (# ComplexHomotFunctor) g3)\n        (H : f1 · f2 · f3 = g1 · g2 · g3 ) :\n    # ComplexHomotFunctor ((hfiberpr1 _ _ f1') · (hfiberpr1 _ _ f2') · (hfiberpr1 _ _ f3')) =\n    # ComplexHomotFunctor ((hfiberpr1 _ _ g1') · (hfiberpr1 _ _ g2') · (hfiberpr1 _ _ g3')).\n  Proof.\n    rewrite functor_comp. rewrite functor_comp. rewrite functor_comp. rewrite functor_comp.\n    rewrite (hfiberpr2 _ _ f1'). rewrite (hfiberpr2 _ _ f2'). rewrite (hfiberpr2 _ _ f3').\n    rewrite (hfiberpr2 _ _ g1'). rewrite (hfiberpr2 _ _ g2'). rewrite (hfiberpr2 _ _ g3').\n    exact H.\n  Qed.\n\n  Lemma ComplexHomotComm4 {C1 C2 C3 C4 C5 C6 C7 C8 : ob ComplexHomot_Additive}\n        {f1 : C1 --> C2} {f2 : C2 --> C3} {f3 : C3 --> C4} {f4 : C4 --> C8}\n        {g1 : C1 --> C5} {g2 : C5 --> C6} {g3 : C6 --> C7} {g4 : C7 --> C8}\n        (f1' : hfiber (# ComplexHomotFunctor) f1) (f2' : hfiber (# ComplexHomotFunctor) f2)\n        (f3' : hfiber (# ComplexHomotFunctor) f3) (f4' : hfiber (# ComplexHomotFunctor) f4)\n        (g1' : hfiber (# ComplexHomotFunctor) g1) (g2' : hfiber (# ComplexHomotFunctor) g2)\n        (g3' : hfiber (# ComplexHomotFunctor) g3) (g4' : hfiber (# ComplexHomotFunctor) g4)\n        (H : f1 · f2 · f3 · f4 = g1 · g2 · g3 · g4) :\n    # ComplexHomotFunctor ((hfiberpr1 _ _ f1') · (hfiberpr1 _ _ f2') · (hfiberpr1 _ _ f3')\n                                               · (hfiberpr1 _ _ f4')) =\n    # ComplexHomotFunctor ((hfiberpr1 _ _ g1') · (hfiberpr1 _ _ g2') · (hfiberpr1 _ _ g3')\n                                               · (hfiberpr1 _ _ g4')).\n  Proof.\n    rewrite functor_comp. rewrite functor_comp. rewrite functor_comp. rewrite functor_comp.\n    rewrite functor_comp. rewrite functor_comp.\n    rewrite (hfiberpr2 _ _ f1'). rewrite (hfiberpr2 _ _ f2'). rewrite (hfiberpr2 _ _ f3').\n    rewrite (hfiberpr2 _ _ f4').\n    rewrite (hfiberpr2 _ _ g1'). rewrite (hfiberpr2 _ _ g2'). rewrite (hfiberpr2 _ _ g3').\n    rewrite (hfiberpr2 _ _ g4').\n    exact H.\n  Qed.\n\nEnd complexes_homotopies.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/HomologicalAlgebra/KA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.2990784433246665}}
{"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.\nRequire Export Cyclone_Canonical_Forms_Proof.\nClose Scope list_scope.\nImport LibEnvNotations.\nImport LVPE.LibVarPathEnvNotations.\n\n(* Try and formulate these, due to the value cases it's a bit funny. *)\nLemma A_14_Term_Progress_1:\n  forall u g h,\n    htyp u g h g ->\n    refp h u ->\n    forall e t,\n      ltyp empty u g e t ->\n      (exists x p, e = (p_e x p)) \\/\n      (exists h' e', L h (e_s e) h' e').\nProof.\n  (* try one with a bad induction to get a feel. *)\n  introv htypd refpd ltypd.\n  induction ltypd.\n  left.\n  exists* (fevar x) p.\n  right.\n  destruct(classicT(Value e)).\n  (* apply A_9_Canonical_Forms_4. *)\n  admit. (* canonical forms lemma *)\n  \nAdmitted.\n\nLemma A_14_Term_Progress_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      Value e \\/\n      (exists h' e', R h (e_s e) h' e').\nAdmitted.\n\nLemma A_14_Term_Progress_3:\n  forall u g h,\n    htyp u g h g ->\n    refp h u ->\n    forall s t,\n      styp empty u g s t ->\n      (exists v, Value v /\\ s = (retn v)) \\/\n      (exists v, Value v /\\ s = (e_s v)) \\/\n      (exists h' s', S h s h' s').\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_Term_Progress_Proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.29907843659445144}}
{"text": "\nRequire Import mathcomp.ssreflect.all_ssreflect.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nSet Bullet Behavior \"Strict Subproofs\".\n\n\nFrom Ltac2 Require Import Ltac2.\nSet Default Proof Mode \"Classic\".\nFrom Utils Require Import Utils.\nFrom Named Require Import Exp ARule.\nFrom Named Require Import ImCore Pf.\nFrom Named Require Import SimpleSubst.\nImport Exp.Notations ARule.Notations.\nRequire Import String.\n\nSet Default Proof Mode \"Classic\".\n\nDefinition stlc :=\n  [::[:> \"G\" : #\"env\", \"A\" : #\"ty\", \"B\" : #\"ty\",\n      \"e\" : #\"el\" (#\"ext\" %\"G\" %\"A\") %\"B\",\n      \"G'\" : #\"env\",\n      \"g\" : #\"sub\" %\"G'\" %\"G\"\n      ----------------------------------------------- (\"lambda_subst\")\n      #\"el_subst\" %\"g\" (#\"lambda\" %\"A\" %\"e\")\n      = #\"lambda\" %\"A\" (#\"el_subst\" (#\"snoc\" (#\"cmp\" #\"wkn\" %\"g\") #\"hd\") %\"e\")\n      : #\"el\" %\"G'\" (#\"->\" %\"A\" %\"B\")\n  ];\n  [:> \"G\" : #\"env\", \"A\" : #\"ty\", \"B\" : #\"ty\",\n      \"e\" : #\"el\"%\"G\" (#\"->\" %\"A\" %\"B\"),\n      \"e'\" : #\"el\" %\"G\" %\"A\",\n      \"G'\" : #\"env\",\n      \"g\" : #\"sub\" %\"G'\" %\"G\"\n      ----------------------------------------------- (\"app_subst\")\n      #\"el_subst\" %\"g\" (#\"app\" %\"e\" %\"e'\")\n      = #\"app\" (#\"el_subst\" %\"g\" %\"e\") (#\"el_subst\" %\"g\" %\"e'\")\n      : #\"el\" %\"G'\" %\"B\"\n  ];\n  [:> \"G\" : #\"env\",\n      \"A\" : #\"ty\",\n      \"B\" : #\"ty\",\n      \"e\" : #\"el\" (#\"ext\" %\"G\" %\"A\") %\"B\",\n      \"e'\" : #\"el\" %\"G\" %\"A\"\n      ----------------------------------------------- (\"STLC_beta\")\n      #\"app\" (#\"lambda\" %\"A\" %\"e\") %\"e'\"\n      = #\"el_subst\" (#\"snoc\" #\"id\" %\"e'\") %\"e\"\n      : #\"el\" %\"G\" %\"B\"\n  ];\n  [:| \"G\" : #\"env\",\n       \"A\" : #\"ty\",\n       \"B\" : #\"ty\",\n       \"e\" : #\"el\" %\"G\" (#\"->\" %\"A\" %\"B\"),\n       \"e'\" : #\"el\" %\"G\" %\"A\"\n       -----------------------------------------------\n       #\"app\" \"e\" \"e'\" : #\"el\" %\"G\" %\"B\"\n  ];\n  [:| \"G\" : #\"env\",\n       \"A\" : #\"ty\",\n       \"B\" : #\"ty\",\n       \"e\" : #\"el\" (#\"ext\" %\"G\" %\"A\") %\"B\"\n       -----------------------------------------------\n       #\"lambda\" \"A\" \"e\" : #\"el\" %\"G\" (#\"->\" %\"A\" %\"B\")\n  ];\n  [:| \"t\" : #\"ty\", \"t'\": #\"ty\"\n      -----------------------------------------------\n      #\"->\" \"t\" \"t'\" : #\"ty\"\n  ]]%arule++subst_lang.\n\nImport OptionMonad.\nDefinition simple_subst_to_pf_ty (e:exp) : option pf :=\n  match e with\n  | var x => Some (pvar x)\n  | con \"->\" [:: B; A] =>\n    do pA <- simple_subst_to_pf_ty A;\n       pB <- simple_subst_to_pf_ty B;\n       ret (pcon \"->\" [:: pB; pA])\n  | _ => None\n  end.\n\n\nFixpoint simple_subst_to_pf_env (e:exp) : option pf :=\n  match e with\n  | var x => Some (pvar x)\n  | con \"emp\" [::] => Some (pcon \"emp\" [::])\n  | con \"ext\" [:: A; G] =>\n    do pa <- simple_subst_to_pf_ty A;\n       pG <- simple_subst_to_pf_env G;\n       ret (pcon \"ext\" [:: pa; pG])\n  | _ => None\n  end.\n\nDefinition simple_subst_to_pf_sort (t:sort) : option pf :=\n  match t with\n  | scon \"env\" [::] => Some (pcon \"env\" [::])\n  | scon \"ty\" [::] => Some (pcon \"ty\" [::])\n  | scon \"sub\" [:: G'; G] =>\n    do pG' <- simple_subst_to_pf_env G';\n       pG <- simple_subst_to_pf_env G;\n       ret (pcon \"sub\" [:: pG'; pG])\n  | scon \"el\" [:: A; G] =>\n    do pa <- simple_subst_to_pf_ty A;\n       pG <- simple_subst_to_pf_env G;\n       ret (pcon \"el\" [:: pa; pG])\n  | _ => None\n  end.\n\nFixpoint simple_subst_to_pf_sub (c : pf_ctx) (e :exp) G_l : option (pf * pf) :=\n  match e with\n  | var x =>\n    do (pcon \"sub\" [:: G_r;_]) <- named_list_lookup_err c x;\n       ret (pvar x, G_r)\n  | con \"id\" [::] =>\n    do ret (pcon \"id\" [:: G_l], G_l)\n  | con \"cmp\" [:: g; f] =>\n    do (p_f,G_fr) <- simple_subst_to_pf_sub c f G_l;\n       (p_g, G_gr) <- simple_subst_to_pf_sub c g G_fr;\n       ret (pcon \"cmp\" [:: p_g; p_f; G_gr; G_fr; G_l], G_gr)\n  | con \"forget\" [::] =>\n    do ret (pcon \"forget\" [:: G_l], pcon \"emp\" [::])\n  | con \"snoc\" [:: e; f] =>\n    do (p_f,G_fr) <- simple_subst_to_pf_sub c f G_l;\n       (p_e, pA) <- simple_subst_to_pf_el c e G_l;\n       ret (pcon \"snoc\" [:: p_e; p_f; pA; G_fr; G_l], pcon \"ext\" [:: pA; G_fr])\n  | con \"wkn\" [::] =>\n    do (pcon \"ext\" [:: A; G]) <- Some G_l;\n       ret (pcon \"wkn\" [:: A; G], G)\n  | _ => None\n  end\nwith simple_subst_to_pf_el c e G : option (pf * pf) :=\n       match e with\n       | var x =>\n         do (pcon \"el\" [:: A; _]) <- named_list_lookup_err c x;\n         ret (pvar x, A)\n       | con \"el_subst\" [:: e; f] =>\n         do (p_f,G_fr) <- simple_subst_to_pf_sub c f G;\n            (p_e, pA) <- simple_subst_to_pf_el c e G_fr;\n            ret (pcon \"el_subst\" [:: p_e; pA; p_f; G_fr; G], pA)\n      | con \"hd\" [::] =>\n        do (pcon \"ext\" [:: A; G]) <- Some G;\n           ret (pcon \"hd\" [:: A; G], A)\n       | con \"lambda\" [:: e; A] =>\n         do pA <- simple_subst_to_pf_ty A;\n            (p_e, pB) <- simple_subst_to_pf_el c e (pcon \"ext\" [:: pA; G]);\n            ret (pcon \"lambda\" [:: p_e; pB; pA; G], pcon \"->\" [:: pB; pA])\n       | con \"app\" [:: e'; e] =>\n         do (p_e, pcon \"->\" [:: pB; pA]) <- simple_subst_to_pf_el c e G;\n            (p_e', _) <- simple_subst_to_pf_el c e' G;\n            ret (pcon \"app\" [:: p_e'; p_e; pB; pA; G], pB)\n       | _ => None\n       end.\n\n\nDefinition simple_subst_to_pf_term (c : pf_ctx) (e :exp) t : option pf :=\n  match t with\n  | pcon \"env\" [::] => simple_subst_to_pf_env e\n  | pcon \"ty\" [::] => simple_subst_to_pf_ty e\n  | pcon \"sub\" [:: _ ; G_l] =>\n    do (p,_) <- simple_subst_to_pf_sub c e G_l;\n       ret p\n  | pcon \"el\" [:: _ ; G] =>\n    do (p,_) <- simple_subst_to_pf_el c e G;\n       ret p\n  | _ => None\n  end.\n\nFixpoint simple_subst_to_pf_ctx (c : ctx) : option pf_ctx :=\n  match c with\n  | [::] => do ret [::]\n  | (n,t)::c' =>\n    do pc' <- simple_subst_to_pf_ctx c';\n       pt <- simple_subst_to_pf_sort t;\n       ret (n,pt)::pc'\n  end.\n\nDefinition simple_subst_to_pf_rule (r : rule) : option rule_pf :=\n  match r with\n  | sort_rule c args =>\n    do pc <- simple_subst_to_pf_ctx c;\n    ret sort_rule_pf pc args\n  | term_rule c args t =>\n    do pt <- simple_subst_to_pf_sort t;\n       pc <- simple_subst_to_pf_ctx c;\n    ret term_rule_pf pc args pt\n  | sort_le c t1 t2 =>\n    do pt1 <- simple_subst_to_pf_sort t1;\n       pt2 <- simple_subst_to_pf_sort t2;\n       pc <- simple_subst_to_pf_ctx c;\n    ret sort_le_pf pc pt1 pt2\n  | term_le c e1 e2 t =>\n    do pt <- simple_subst_to_pf_sort t;\n       pc <- simple_subst_to_pf_ctx c;\n       pe1 <- simple_subst_to_pf_term pc e1 pt;\n       pe2 <- simple_subst_to_pf_term pc e2 pt;\n    ret term_le_pf pc pe1 pe2 pt\nend.\n\nFixpoint simple_subst_to_pf_lang (l : lang) : option pf_lang :=\n  match l with\n  | [::] => do ret [::]\n  | (n,r)::l' =>\n    do pl' <- simple_subst_to_pf_lang l';\n       pr <- simple_subst_to_pf_rule r;\n       ret (n,pr)::pl'\n  end.\n\nLemma simple_stlc_wf : wf_lang stlc.\nProof.\n  prove_wf_with_fn simple_subst_to_pf_lang.\nQed.\n\nDerive elab_stlc\n       SuchThat (Some elab_stlc = simple_subst_to_pf_lang stlc)\n  As elab_stlc_pf.\nProof.\n  compute; reflexivity.\nQed.\n", "meta": {"author": "DIJamner", "repo": "pyrosome", "sha": "a8d7f0aa3141b35a3c59d8d72aadf47a3b0c5df6", "save_path": "github-repos/coq/DIJamner-pyrosome", "path": "github-repos/coq/DIJamner-pyrosome/pyrosome-a8d7f0aa3141b35a3c59d8d72aadf47a3b0c5df6/WIP/SimpleSTLC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.2990784365944514}}
{"text": "Require Import Verdi.GhostSimulations.\n\nRequire Import VerdiRaft.Raft.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nRequire Import VerdiRaft.CommonTheorems.\nRequire Import VerdiRaft.StateMachineSafetyInterface.\nRequire Import VerdiRaft.SortedInterface.\nRequire Import VerdiRaft.UniqueIndicesInterface.\nRequire Import VerdiRaft.LogMatchingInterface.\nRequire Import VerdiRaft.MaxIndexSanityInterface.\nRequire Import VerdiRaft.CommitRecordedCommittedInterface.\nRequire Import VerdiRaft.LeaderCompletenessInterface.\nRequire Import VerdiRaft.LastAppliedCommitIndexMatchingInterface.\n\nRequire Import VerdiRaft.SpecLemmas.\n\nRequire Import VerdiRaft.AppliedEntriesMonotonicInterface.\n\nSection AppliedEntriesMonotonicProof.\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 {si : sorted_interface}.\n  Context {lmi : log_matching_interface}.\n  Context {uii : unique_indices_interface}.\n  Context {smsi : state_machine_safety_interface}.\n  Context {misi : max_index_sanity_interface}.\n  Context {crci : commit_recorded_committed_interface}.\n  Context {lci : leader_completeness_interface}.\n  Context {lacimi : lastApplied_commitIndex_match_interface}.\n  \n  Lemma findAtIndex_max_thing :\n    forall net h e i,\n      raft_intermediate_reachable net ->\n      In e (log (nwState net h)) ->\n      eIndex e > i ->\n      1 <= i ->\n      exists e',\n        findAtIndex (log (nwState net h)) i = Some e'.\n  Proof using lmi si. \n    intros.\n    find_copy_apply_lem_hyp logs_sorted_invariant.\n    pose proof log_matching_invariant.\n    eapply_prop_hyp raft_intermediate_reachable raft_intermediate_reachable.\n    unfold log_matching, log_matching_hosts, logs_sorted in *.\n    intuition.\n    match goal with\n      | H : forall _ _, _ <= _ <= _ -> _ |- _ =>\n        specialize (H h i);\n          conclude H ltac:(intuition; find_apply_lem_hyp maxIndex_is_max; eauto; omega)\n    end.\n    break_exists_exists. intuition. apply findAtIndex_intro; eauto using sorted_uniqueIndices.\n  Qed.\n  \n  Lemma entries_max_thing :\n    forall net p es,\n      raft_intermediate_reachable net ->\n      In p (nwPackets net) ->\n      mEntries (pBody p) = Some es ->\n      es <> nil ->\n      1 <= maxIndex es.\n  Proof using lmi. \n    intros.\n    find_apply_lem_hyp maxIndex_non_empty.\n    break_exists; intuition; find_rewrite.\n    find_apply_lem_hyp log_matching_invariant.\n    unfold log_matching, log_matching_nw in *.\n    intuition. destruct (pBody p) eqn:?; simpl in *; try congruence.\n    find_apply_hyp_hyp. intuition. find_inversion.\n    find_apply_hyp_hyp. omega.\n  Qed.\n\n  Lemma deghost_snd :\n    forall net h,\n      snd (nwState net h) = nwState (deghost net) h.\n  Proof using. \n    intros. unfold deghost in *. simpl.\n    repeat break_match; subst; simpl.\n    repeat find_rewrite. reflexivity.\n  Qed.\n\n  Lemma lt_committed_committed :\n    forall net e e' t h,\n      log_matching (deghost net) ->\n      committed net e t ->\n      eIndex e' <= eIndex e ->\n      In e (log (snd (nwState net h))) ->\n      In e' (log (snd (nwState net h))) ->\n      committed net e' t.\n  Proof using. \n    intros.\n    unfold committed in *.\n    break_exists_exists. intuition.\n    unfold log_matching, log_matching_hosts in *.\n    intuition. unfold entries_match in *.\n    rewrite deghost_snd in *.\n    match goal with\n      | H : forall _ _ _ _ _, _  |- In _ (_ (_ _ ?x)) =>\n        specialize (H h x e e e')\n    end; intuition eauto.\n  Qed.\n\n  Lemma logs_contiguous :\n    forall net h,\n      raft_intermediate_reachable net ->\n      contiguous_range_exact_lo (log (nwState net h)) 0.\n  Proof using lmi. \n    intros.\n    find_apply_lem_hyp log_matching_invariant.\n    unfold log_matching, log_matching_hosts in *.\n    intuition.\n    unfold contiguous_range_exact_lo.\n    intuition eauto.\n    find_apply_hyp_hyp. intuition.\n  Qed.\n\n  Lemma entries_gt_0 :\n    forall net p es e,\n      raft_intermediate_reachable net ->\n      In p (nwPackets net) ->\n      mEntries (pBody p) = Some es ->\n      In e es ->\n      0 < eIndex e.\n  Proof using lmi. \n    intros.\n    find_apply_lem_hyp log_matching_invariant.\n    unfold log_matching, log_matching_nw in *.\n    intuition. destruct (pBody p) eqn:?; simpl in *; try congruence.\n    find_inversion.\n    find_apply_hyp_hyp. intuition.\n    find_apply_hyp_hyp. omega.\n  Qed.\n\n  Lemma entries_gt_pli :\n    forall net p e t n pli plt es ci,\n      raft_intermediate_reachable net ->\n      In p (nwPackets net) ->\n      pBody p = AppendEntries t n pli plt es ci ->\n      In e es ->\n      pli < eIndex e.\n  Proof using lmi. \n    intros.\n    find_apply_lem_hyp log_matching_invariant.\n    unfold log_matching, log_matching_nw in *.\n    intuition. destruct (pBody p) eqn:?; simpl in *; try congruence.\n    find_inversion.\n    find_apply_hyp_hyp. intuition.\n  Qed.\n  \n  Lemma sorted_app :\n    forall l l',\n      sorted (l ++ l') ->\n      sorted l.\n  Proof using. \n    induction l; simpl in *; intros; intuition eauto.\n    - apply H0. intuition.\n    - apply H0. intuition.\n  Qed.\n  \n  Lemma handleMessage_applied_entries :\n    forall net h h' m st' ms,\n      raft_intermediate_reachable net ->\n      In {| pBody := m; pDst := h; pSrc := h' |} (nwPackets net) ->\n      handleMessage h' h m (nwState net h) = (st', ms) ->\n      applied_entries (nwState net) = applied_entries (update name_eq_dec (nwState net) h st').\n  Proof using misi smsi uii lmi si. \n    intros. symmetry.\n    unfold handleMessage in *. break_match; repeat break_let; repeat find_inversion.\n    - apply applied_entries_log_lastApplied_update_same;\n      eauto using handleRequestVote_same_log, handleRequestVote_same_lastApplied.\n    - apply applied_entries_log_lastApplied_update_same;\n      eauto using handleRequestVoteReply_same_log, handleRequestVoteReply_same_lastApplied.\n    - find_copy_eapply_lem_hyp handleAppendEntries_logs_sorted;\n      eauto using logs_sorted_invariant.\n      apply applied_entries_safe_update; eauto using handleAppendEntries_same_lastApplied.\n      find_apply_lem_hyp handleAppendEntries_log_detailed. intuition.\n      + repeat find_rewrite. auto.\n      + subst.\n        find_copy_apply_lem_hyp state_machine_safety_invariant.\n        unfold state_machine_safety in *. intuition.\n        find_copy_apply_lem_hyp max_index_sanity_invariant. intuition.\n        find_copy_apply_lem_hyp logs_sorted_invariant.\n        unfold logs_sorted, maxIndex_sanity in *. intuition.\n        apply removeAfterIndex_same_sufficient; eauto.\n        * intros.\n          copy_eapply_prop_hyp state_machine_safety_nw In;\n            unfold commit_recorded in *.\n            simpl in *; repeat (forwards; eauto; concludes).\n            intuition; try omega;\n            exfalso;\n            find_eapply_lem_hyp findAtIndex_max_thing; eauto; try break_exists; try congruence;\n            eauto using entries_max_thing;\n            find_apply_lem_hyp logs_contiguous; auto; omega.\n        * intros.\n          find_copy_apply_lem_hyp log_matching_invariant.\n          unfold log_matching, log_matching_hosts in *. intuition.\n          match goal with\n            | H : forall _ _, _ <= _ <= _ -> _ |- _ => specialize (H h (eIndex e));\n                forward H\n          end;\n            copy_eapply_prop_hyp log_matching_nw AppendEntries; eauto;\n            repeat (forwards; [intuition eauto; omega|]; concludes);\n            intuition; [eapply le_trans; eauto|].\n          match goal with\n            | H : exists _, _ |- _ => destruct H as [e']\n          end.\n          intuition.\n          copy_eapply_prop_hyp state_machine_safety_nw In;\n            unfold commit_recorded in *;\n            simpl in *; repeat (forwards; [intuition eauto; omega|]; concludes).\n          match goal with H : _ /\\ (_ \\/ _) |- _ => clear H end.\n          intuition; try omega;\n          [|find_copy_apply_lem_hyp UniqueIndices_invariant;\n             unfold UniqueIndices in *; intuition;\n             eapply rachet; [symmetry|idtac|idtac|idtac|idtac]; eauto].\n          exfalso.\n          find_eapply_lem_hyp findAtIndex_max_thing; eauto; try break_exists; try congruence;\n          eauto using entries_max_thing.\n      + repeat find_rewrite.\n        find_copy_apply_lem_hyp state_machine_safety_invariant.\n        find_copy_apply_lem_hyp max_index_sanity_invariant.\n        unfold state_machine_safety, maxIndex_sanity in *. intuition.\n        find_copy_apply_lem_hyp logs_sorted_invariant.\n        unfold logs_sorted in *. intuition.\n        eapply removeAfterIndex_same_sufficient'; eauto using logs_contiguous.\n        * intros. eapply entries_gt_0; intuition eauto.\n        * intros.\n          copy_eapply_prop_hyp state_machine_safety_nw In;\n            unfold commit_recorded in *;\n            simpl in *; repeat (forwards; [intuition eauto; omega|]; concludes).\n          match goal with H : _ /\\ (_ \\/ _) |- _ => clear H end.\n          intuition; try omega; try solve [find_apply_lem_hyp logs_contiguous; auto; omega].\n          exfalso.\n          subst.\n          break_exists. intuition.\n          find_false.\n          find_apply_lem_hyp maxIndex_non_empty.\n          break_exists. intuition. repeat find_rewrite.\n          f_equal.\n          find_apply_lem_hyp findAtIndex_elim. intuition.\n          eapply uniqueIndices_elim_eq with (xs := log st'); eauto using sorted_uniqueIndices.\n          unfold state_machine_safety_nw in *.\n          eapply_prop_hyp commit_recorded In; intuition; eauto; try omega;\n          try solve [find_apply_lem_hyp logs_contiguous; auto; omega].\n          unfold commit_recorded. intuition.\n      + repeat find_rewrite.\n        find_copy_apply_lem_hyp logs_sorted_invariant.\n        unfold logs_sorted in *. intuition.\n        eapply removeAfterIndex_same_sufficient'; eauto using logs_contiguous.\n        * { intros. do_in_app. intuition.\n            - eapply entries_gt_0; eauto. reflexivity.\n            - find_apply_lem_hyp removeAfterIndex_in.\n              find_apply_lem_hyp logs_contiguous; eauto.\n          }\n        * find_apply_lem_hyp max_index_sanity_invariant.\n          unfold maxIndex_sanity in *. intuition.\n        * intros.\n          find_copy_apply_lem_hyp state_machine_safety_invariant.\n          unfold state_machine_safety in *. break_and.\n          copy_eapply_prop_hyp state_machine_safety_nw In; eauto.\n          simpl in *. intuition eauto. forwards; eauto. concludes.\n          forwards; [unfold commit_recorded in *; intuition eauto|].\n          concludes.\n          intuition; apply in_app_iff;\n          try solve [right; eapply removeAfterIndex_le_In; eauto; omega];\n          exfalso.\n          find_eapply_lem_hyp findAtIndex_max_thing; eauto using entries_max_thing.\n          break_exists; congruence.\n      + break_exists. intuition. subst.\n        repeat find_rewrite.\n        find_copy_apply_lem_hyp logs_sorted_invariant.\n        unfold logs_sorted in *. intuition.\n        eapply removeAfterIndex_same_sufficient'; eauto using logs_contiguous.\n        * { intros. do_in_app. intuition.\n            - eapply entries_gt_0; eauto. reflexivity.\n            - find_apply_lem_hyp removeAfterIndex_in.\n              find_apply_lem_hyp logs_contiguous; eauto.\n          }\n        * find_apply_lem_hyp max_index_sanity_invariant.\n          unfold maxIndex_sanity in *. intuition.\n        * {\n            intros.\n            find_copy_apply_lem_hyp state_machine_safety_invariant.\n            unfold state_machine_safety in *. break_and.\n            copy_eapply_prop_hyp state_machine_safety_nw In; eauto.\n            simpl in *. intuition eauto. forwards; eauto. concludes.\n            forwards; [unfold commit_recorded in *; intuition eauto|].\n            concludes.\n            intuition; apply in_app_iff;\n            try solve [right; eapply removeAfterIndex_le_In; eauto; omega].\n            subst.\n            find_apply_lem_hyp maxIndex_non_empty.\n            break_exists. intuition. repeat find_rewrite.\n            find_apply_lem_hyp findAtIndex_elim. intuition.\n            find_false. f_equal.\n            eapply uniqueIndices_elim_eq with (xs := log (nwState net h));\n              eauto using sorted_uniqueIndices.\n            unfold state_machine_safety_nw in *.\n            eapply rachet; eauto using sorted_app, sorted_uniqueIndices.\n            copy_eapply_prop_hyp commit_recorded In; intuition; eauto; try omega;\n            unfold commit_recorded; intuition.\n            - exfalso.\n              pose proof entries_gt_pli.\n              eapply_prop_hyp AppendEntries AppendEntries;\n                [|idtac|simpl; eauto|]; eauto. omega.\n            -  exfalso.\n              pose proof entries_gt_pli.\n              eapply_prop_hyp AppendEntries AppendEntries;\n                [|idtac|simpl; eauto|]; eauto. omega.\n          }\n    - apply applied_entries_log_lastApplied_update_same;\n      eauto using handleAppendEntriesReply_same_log, handleAppendEntriesReply_same_lastApplied.\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  Lemma handleInput_applied_entries :\n    forall net h inp os st' ms,\n      raft_intermediate_reachable net ->\n      handleInput h inp (nwState net h) = (os, st', ms) ->\n      applied_entries (nwState net) = applied_entries (update name_eq_dec (nwState net) h st').\n  Proof using misi. \n    intros. symmetry.\n    unfold handleInput in *. break_match; repeat break_let; repeat find_inversion.\n    - apply applied_entries_log_lastApplied_update_same;\n      eauto using handleTimeout_log, handleTimeout_lastApplied.\n    - apply applied_entries_safe_update; eauto using handleClientRequest_lastApplied.\n\n      destruct (log st') using (handleClientRequest_log_ind ltac:(eauto)); auto.\n\n      simpl in *. break_if; auto.\n      exfalso.\n      do_bool.\n      find_apply_lem_hyp max_index_sanity_invariant.\n      unfold maxIndex_sanity, maxIndex_lastApplied in *.\n      intuition.\n      match goal with\n        | H : forall _, _ |- _ => specialize (H h)\n      end. omega.\n  Qed.\n\n  Lemma doGenericServer_applied_entries :\n    forall ps h sigma os st' ms,\n      raft_intermediate_reachable (mkNetwork ps sigma) ->\n      doGenericServer h (sigma h) = (os, st', ms) ->\n      exists es, applied_entries (update name_eq_dec sigma h st') = (applied_entries sigma) ++ es.\n  Proof using lacimi si. \n    intros.\n    unfold doGenericServer in *. break_let. find_inversion.\n    use_applyEntries_spec. subst. simpl in *. unfold raft_data in *.\n    simpl in *.\n    break_if; [|rewrite applied_entries_safe_update; simpl in *; eauto using app_nil_r].\n    do_bool.\n    match goal with\n      | |- context [update _ ?sigma ?h ?st] => pose proof applied_entries_update sigma h st\n    end.\n    simpl in *.\n    assert (commitIndex (sigma h) >= lastApplied (sigma h)) by omega.\n    concludes. intuition.\n    - find_rewrite. eauto using app_nil_r.\n    - pose proof applied_entries_cases sigma.\n      intuition; repeat find_rewrite; eauto.\n      match goal with | H : exists _, _ |- _ => destruct H as [h'] end.\n      repeat find_rewrite.\n      find_apply_lem_hyp argmax_elim. intuition.\n      match goal with\n        | H : forall _: name, _ |- _ =>\n          specialize (H h'); conclude H ltac:(eauto using all_fin_all)\n      end.\n      rewrite_update. simpl in *.\n      update_destruct_hyp; subst; rewrite_update; simpl in *.\n      + apply rev_exists.\n        erewrite removeAfterIndex_le with (i := lastApplied (sigma h')) (j := commitIndex (sigma h')); [|omega].\n        eauto using removeAfterIndex_partition.\n      + apply rev_exists.\n        match goal with\n          | _ : ?h <> ?h' |- exists _, removeAfterIndex ?l (commitIndex (?sigma ?h)) = _ =>\n            pose proof removeAfterIndex_partition (removeAfterIndex l (commitIndex (sigma h)))\n                 (lastApplied (sigma h'))\n        end. break_exists_exists.\n        repeat match goal with | H : applied_entries _ = _ |- _ => clear H end.\n        find_rewrite. f_equal.\n        erewrite <- removeAfterIndex_le; eauto.\n        find_copy_apply_lem_hyp logs_sorted_invariant. unfold logs_sorted in *.\n        intuition. find_copy_apply_lem_hyp lastApplied_commitIndex_match_invariant.\n        eapply removeAfterIndex_same_sufficient; eauto;\n        intros;\n        eapply_prop_hyp lastApplied_commitIndex_match le; intuition eauto.\n  Qed.\n\n  Theorem applied_entries_monotonic' :\n    forall failed net failed' net' os,\n      raft_intermediate_reachable net ->\n      (@step_failure _ _ failure_params (failed, net) (failed', net') os) ->\n      exists es,\n        applied_entries (nwState net') = applied_entries (nwState net) ++ es.\n  Proof using lacimi misi smsi uii lmi si. \n    intros. match goal with H : step_failure _ _ _ |- _ => invcs H end.\n    - unfold RaftNetHandler in *. repeat break_let. subst.\n      find_inversion.\n      match goal with\n        | Hdl : doLeader ?st ?h = _,\n          Hdgs : doGenericServer ?h ?st' = _ |- context [update _ (nwState ?net) ?h ?st''] =>\n          replace st with (update name_eq_dec (nwState net) h st h) in Hdl by eauto using update_eq;\n            replace st' with (update name_eq_dec (update name_eq_dec (nwState net) h st) h st' h) in Hdgs by eauto using update_eq;\n            let H := fresh \"H\" in\n            assert (update name_eq_dec (nwState net) h st'' =\n                    update name_eq_dec (update name_eq_dec (update name_eq_dec (nwState net) h st) h st') h st'') by (repeat rewrite update_overwrite; auto); unfold data in *; simpl in *; rewrite H; clear H\n      end.\n      find_copy_apply_lem_hyp doLeader_appliedEntries.\n      find_copy_eapply_lem_hyp RIR_handleMessage; eauto.\n      find_eapply_lem_hyp RIR_doLeader; simpl in *; eauto.\n      find_apply_lem_hyp handleMessage_applied_entries; auto; [|destruct p; find_rewrite; in_crush].\n      unfold raft_data in *. simpl in *. unfold raft_data in *. simpl in *.\n      match goal with\n        | H : applied_entries (update _ (update _ _ _ _) _ _) =\n              applied_entries (update _ _ _ _) |- _ =>\n          symmetry in H\n      end.\n      repeat find_rewrite.\n      repeat match goal with H : applied_entries _ = applied_entries _ |- _ => clear H end.\n      eauto using doGenericServer_applied_entries.\n    - unfold RaftInputHandler in *. repeat break_let. subst.\n      find_inversion.\n      match goal with\n        | Hdgs : doGenericServer ?h ?st' = _,\n          Hdl : doLeader ?st ?h = _ |- context [update _ (nwState ?net) ?h ?st''] =>\n          replace st with (update name_eq_dec (nwState net) h st h) in Hdl by eauto using update_eq;\n            replace st' with (update name_eq_dec (update name_eq_dec (nwState net) h st) h st' h) in Hdgs by eauto using update_eq;\n            let H := fresh \"H\" in\n            assert (update name_eq_dec (nwState net) h st'' =\n                    update name_eq_dec (update name_eq_dec (update name_eq_dec (nwState net) h st) h st') h st'') by (repeat rewrite update_overwrite; auto); unfold data in *; simpl in *; rewrite H; clear H\n      end.\n      find_copy_apply_lem_hyp doLeader_appliedEntries.\n      find_copy_eapply_lem_hyp RIR_handleInput; eauto.\n      find_eapply_lem_hyp RIR_doLeader; simpl in *; eauto.      \n      find_apply_lem_hyp handleInput_applied_entries; auto.\n      unfold raft_data in *. simpl in *. unfold raft_data in *. simpl in *.\n      match goal with\n        | H : applied_entries (update _ (update _ _ _ _) _ _) =\n              applied_entries (update _ _ _ _) |- _ =>\n          symmetry in H\n      end.\n      repeat find_rewrite.\n      repeat match goal with H : applied_entries _ = applied_entries _ |- _ => clear H end.\n      eauto using doGenericServer_applied_entries.\n    - exists nil; intuition.\n    - exists nil; intuition.\n    - exists nil; intuition.\n    - exists nil.\n      rewrite app_nil_r.\n      apply applied_entries_log_lastApplied_same;\n        intros; unfold reboot in *; update_destruct_max_simplify; auto.\n  Qed.\n\n  Theorem applied_entries_monotonic :\n    forall e failed net failed' net' os,\n      raft_intermediate_reachable net ->\n      (@step_failure _ _ failure_params (failed, net) (failed', net') os) ->\n      In e (applied_entries (nwState net)) ->\n      In e (applied_entries (nwState net')).\n  Proof using lacimi misi smsi uii lmi si. \n    intros. find_eapply_lem_hyp applied_entries_monotonic'; eauto.\n    break_exists. find_rewrite. in_crush.\n  Qed.\n\n  Instance aemi : applied_entries_monotonic_interface.\n  Proof.\n    split;\n    eauto using applied_entries_monotonic,\n                applied_entries_monotonic'.\n  Qed.\n\nEnd AppliedEntriesMonotonicProof.\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/AppliedEntriesMonotonicProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593171945416, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2990784298642362}}
{"text": "(* ssreflect *)\n\nFrom mathcomp.ssreflect Require Import ssreflect ssrbool ssrnat ssrfun eqtype seq fintype finfun.\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nRequire Import Bool.\nRequire Import Zbool.\nRequire Import BinPos.\n\nRequire Import concurrency.compcert_imports. Import CompcertCommon.\n\nRequire Import msl.Axioms.\n\nRequire Import concurrency.sepcomp. Import SepComp.\n\nRequire Import concurrency.pred_lemmas.\nRequire Import concurrency.seq_lemmas.\nRequire Import concurrency.inj_lemmas.\n\n(* The following variation of [join] is appropriate for shared resources  *)\n(* like extern injections: each core must have a consistent mapping on    *)\n(* extern blocks but the domains of the mappings are not necessarily      *)\n(* disjoint.                                                              *)\n\nDefinition join2 (j  k : Values.meminj) b :=\n  match j b with\n    | Some (b1,d1) =>\n      match k b with\n        | Some (b2,d2) =>\n            if [&& Pos.eqb b1 b2 & Zeq_bool d1 d2]\n            then Some (b1,d1) else None\n        | None => None\n      end\n    | None => None\n  end.\n\nLemma join2P j k b1 b2 d2 :\n  join2 j k b1 = Some (b2,d2) <->\n  [/\\ j b1 = Some (b2,d2) & k b1 = Some (b2,d2)].\nProof.\nrewrite/join2; split.\ncase A: (j b1)=> // [[x y]]; case B: (k b1)=> // [[x' y']].\ncase H: (_ && _)=> //; move: H; move/andP=> [].\nby move/Peqb_true_eq=> <-; move/Zeq_bool_eq=> <-; case=> -> ->.\nmove=> []-> ->; case H: (_ && _)=> //; move: H; move/andP=> []; split.\nby rewrite/is_true Pos.eqb_eq.\nby rewrite/is_true -Zeq_is_eq_bool.\nQed.\n\n(* Why is this lemma not in ZArith?!? *)\n\nLemma Zeq_bool_refl x : Zeq_bool x x.\nProof. by case: (Zeq_is_eq_bool x x)=> A _; apply: A. Qed.\n\nLemma Zeq_bool_sym x y : Zeq_bool x y = Zeq_bool y x.\nProof.\ncase e: (Zeq_bool x y).\nrewrite (Zeq_bool_eq _ _ e).\nby rewrite Zeq_bool_refl.\nmove: (Zeq_bool_neq _ _ e)=> neq.\ncase f: (Zeq_bool y x)=> //.\nmove: (Zeq_bool_eq _ _ f)=> eq.\nby subst x; elimtype False; apply: neq.\nQed.\n\nLemma join2_inject_incr j k :\n  inject_incr j k ->\n  join2 j k = j.\nProof.\nmove=> incr; rewrite /join2; extensionality b.\ncase jj: (j b)=> //[[x y]].\nmove: (incr _ _ _ jj).\ncase kk: (k b)=> [[x' y']|//].\ncase=> -> ->.\nby rewrite Pos.eqb_refl Zeq_bool_refl.\nQed.\n\nLemma join2C j k : join2 j k = join2 k j.\nProof.\nrewrite /join2; extensionality b.\ncase: (j b)=> [[x y]|].\ncase: (k b)=> [[x' y']|].\nrewrite Pos.eqb_sym.\nrewrite Zeq_bool_sym.\ncase e: (_ && _)=> //.\ncase: (andP e).\nmove/Peqb_true_eq=> ->.\nby move/Zeq_bool_eq=> ->.\nby [].\nby case: (k b)=> [[? ?]|].\nQed.\n\nLemma join2A j k l : join2 j (join2 k l) = join2 (join2 j k) l.\nProof.\nrewrite /join2; extensionality b.\ncase: (j b)=> [[x y]|] //.\ncase: (k b)=> [[x' y']|] //.\ncase: (l b)=> [[x'' y'']|] //.\nrewrite Pos.eqb_sym.\nrewrite Zeq_bool_sym.\ncase e: (_ && _)=> //.\ncase: (andP e).\nmove/Peqb_true_eq=> ->.\nmove/Zeq_bool_eq=> ->.\nrewrite Pos.eqb_sym.\nrewrite Zeq_bool_sym.\ncase f: (_ && _)=> //.\ncase: (andP f).\nmove/Peqb_true_eq=> ->.\nmove/Zeq_bool_eq=> ->.\nby rewrite Pos.eqb_refl Zeq_bool_refl.\ncase f: (_ && _)=> //.\ncase: (andP f).\nmove/Peqb_true_eq=> ->.\nmove/Zeq_bool_eq=> ->.\ncase g: (_ && _)=> //.\ncase: (andP g).\nmove/Peqb_true_eq=> A.\nmove/Zeq_bool_eq=> B.\nmove: e; rewrite andb_false_iff; case.\nby rewrite A Pos.eqb_refl.\nby rewrite B Zeq_bool_refl.\nby case e: (_ && _).\nQed.\n\n(* [join_sm mu1 mu2] is a union operator on structured injections. If     *)\n(* we have struct. injections                                             *)\n(*                                                                        *)\n(*   mu1 = LOC1, locof1, EXT1, extof1                                     *)\n(*   mu2 = LOC2, locof2, EXT2, extof2                                     *)\n(*                                                                        *)\n(* then [join_sm mu1 mu2 = mu12] is equal to                              *)\n(*                                                                        *)\n(*   LOC1 \\cup LOC2, join locof1 locof2,                                  *)\n(*   EXT1 \\cap EXT2, join2 extof1 extof2                                  *)\n(*                                                                        *)\n(* w/ PUB12 = \\emptyset, FRGN12 = FRGN1 \\cap FRGN2.                       *)\n(*                                                                        *)\n(* While conceptually, LOC1 \\cup LOC2 is disjoint union, in practice we   *)\n(* make [join_sm] a total operation.  However, [mu12] is only             *)\n(* well-defined if                                                        *)\n(*                                                                        *)\n(*   1) LOC1 \\cap \\LOC2 = \\emptyset; and                                  *)\n(*   2) extof1 and extof2 are \"consistent\"                                *)\n(*                                                                        *)\n(* We say that two injections [j],[k] are consistent when the following   *)\n(* condition holds:                                                       *)\n\nDefinition consistent (j k : Values.meminj) :=\n  forall b1 b2 b2' d2 d2',\n  j b1 = Some (b2,d2) -> k b1 = Some (b2',d2') -> [/\\ b2=b2' & d2=d2'].\n\nDefinition DisjointLS :=\n  [fun mu mu' => Disjoint (locBlocksSrc mu) (locBlocksSrc mu')].\n\nDefinition DisjointLT :=\n  [fun mu mu' => Disjoint (locBlocksTgt mu) (locBlocksTgt mu')].\n\nDefinition Consistent :=\n  [fun mu mu' => consistent (as_inj mu) (as_inj mu')].\n\nDefinition join_sm mu1 mu2 : SM_Injection :=\n  Build_SM_Injection\n    [predU (locBlocksSrc mu1) & locBlocksSrc mu2]\n    [predU (locBlocksTgt mu1) & locBlocksTgt mu2]\n    pred0\n    pred0\n    (join (local_of mu1) (local_of mu2))\n    [predI (extBlocksSrc mu1) & extBlocksSrc mu2]\n    [predI (extBlocksTgt mu1) & extBlocksTgt mu2]\n    [predI (frgnBlocksSrc mu1) & frgnBlocksSrc mu2]\n    [predI (frgnBlocksTgt mu1) & frgnBlocksTgt mu2]\n    (join2 (extern_of mu1) (extern_of mu2)).\n\nLemma consistent_incr: forall mu0 mu mu',\n                         inject_incr (as_inj mu0) (as_inj mu) ->\n                         inject_incr (as_inj mu) (as_inj mu') ->\n                         Consistent mu0 mu'.\nProof.\n  clear.\n  move => mu0 mu mu'.\n  rewrite /Consistent /consistent => //=.\n  move => incr incr' b1 b2 b2' d2 d2'.\n  move/incr /incr' => map1.\n  rewrite map1.\n  case => //=.\nQed.\n\nLemma join_sm_wd (mu1 : Inj.t) (mu2 : Inj.t) :\n  DisjointLS mu1 mu2 ->\n  DisjointLT mu1 mu2 ->\n  Consistent mu1 mu2 ->\n  SM_wd (join_sm mu1 mu2).\nProof.\nmove=> D1 D2 C12; apply: Build_SM_wd; rewrite/join_sm/=/in_mem/=/in_mem/=.\nmove=> b; move: (Inj_DisjointLES mu1); move/DisjointP/(_ b).\nmove: (Inj_DisjointLES mu2); move/DisjointP/(_ b).\nby case: (locBlocksSrc mu1 b); case: (locBlocksSrc mu2 b);\n   case: (extBlocksSrc mu1 b); case: (extBlocksSrc mu2 b)=>//=;\n   solve[by left|by right|by case|by move=> _; case].\nmove=> b; move: (Inj_DisjointLET mu1); move/DisjointP/(_ b).\nmove: (Inj_DisjointLET mu2); move/DisjointP/(_ b).\nrewrite/join_sm/=/in_mem/=/in_mem/=.\nby case: (locBlocksTgt mu1 b); case: (locBlocksTgt mu2 b);\n   case: (extBlocksTgt mu1 b); case: (extBlocksTgt mu2 b)=>//=;\n   solve[by left|by right|by case|by move=> _; case].\nrewrite/join=> b1 b2 z.\ncase H: (local_of _ _)=> [[? ?]|]=> A; move: A H. case=> -> ->.\nby move/local_DomRng; move/(_ (Inj_wd mu1))=> []-> ->.\nmove/local_DomRng; move/(_ (Inj_wd mu2))=> []-> -> _.\nby split; apply/orP; right.\nmove=> b1 b2 z; move/join2P=> [].\nmove/(extern_DomRng _ (Inj_wd mu1))=> []-> -> /=.\nby move/(extern_DomRng _ (Inj_wd mu2))=> []-> -> /=.\nby [].\nmove=> b1; move/andP=> []; rewrite/join2.\nmove=> A B.\nmove: (frgnSrcAx _ (Inj_wd _) _ A)=> []b2 []d2 []A0 A'.\nmove: (frgnSrcAx _ (Inj_wd _) _ B)=> []b2' []d2' []B0 B'.\nexists b2,d2; move: A' B'; rewrite A0 B0; case H: (_ && _).\nby move: H; move/andP=> []; move/Peqb_true_eq=> <- _ -> ->.\nhave A0': as_inj mu1 b1 = Some (b2,d2).\n  by rewrite /as_inj /join A0.\nhave B0': as_inj mu2 b1 = Some (b2',d2').\n  by rewrite /as_inj /join B0.\nmove: (C12 _ _ _ _ _ A0' B0') H; case=> <- <-; move/andP=> []; split.\nby rewrite/is_true Pos.eqb_eq.\nby rewrite/is_true -Zeq_is_eq_bool.\nby [].\nmove=> b; move/andP=> [].\nmove/frgntgt_sub_exttgt; rewrite/in_mem/= => ->.\nby move/frgntgt_sub_exttgt; rewrite/in_mem/= => ->.\nQed.\n\n(* The following definitions/lemmas extend [join2] to nonempty sequences  *)\n(* of struct. injections.                                                 *)\n\nDefinition AllDisjoint (proj : SM_Injection -> Values.block -> bool) :=\n  All2 (fun mu mu' => Disjoint (proj mu) (proj mu')).\n\nDefinition AllConsistent :=\n  All2 (fun mu mu' => consistent (as_inj mu) (as_inj mu')).\n\nFixpoint join_all (mu0 : Inj.t) (mus : seq Inj.t) : SM_Injection :=\n  if mus is [:: mu & mus] then join_sm mu (join_all mu0 mus)\n  else mu0.\n\nLemma join_all_cons mu0 mu mus :\n  join_all mu0 (mu :: mus) = join_sm mu (join_all mu0 mus).\nProof. by []. Qed.\n\nLemma join_all_frgnS_cons mu0 mu mus :\n  frgnBlocksSrc (join_all mu0 (mu :: mus))\n  = [predI (frgnBlocksSrc mu) & frgnBlocksSrc (join_all mu0 mus)].\nProof. by rewrite join_all_cons. Qed.\n\nLemma join_all_frgnT_cons mu0 mu mus :\n  frgnBlocksTgt (join_all mu0 (mu :: mus))\n  = [predI (frgnBlocksTgt mu) & frgnBlocksTgt (join_all mu0 mus)].\nProof. by rewrite join_all_cons. Qed.\n\nLemma join_all_extS_cons mu0 mu mus :\n  extBlocksSrc (join_all mu0 (mu :: mus))\n  = [predI (extBlocksSrc mu) & extBlocksSrc (join_all mu0 mus)].\nProof. by rewrite join_all_cons. Qed.\n\nLemma join_all_extT_cons mu0 mu mus :\n  extBlocksTgt (join_all mu0 (mu :: mus))\n  = [predI (extBlocksTgt mu) & extBlocksTgt (join_all mu0 mus)].\nProof. by rewrite join_all_cons. Qed.\n\nLemma join_all_disjoint_src mu0 (mu : Inj.t) mus :\n  All (fun mu' => Disjoint (locBlocksSrc mu0) (locBlocksSrc mu'))\n    (map Inj.mu (mu :: mus)) ->\n  Disjoint (locBlocksSrc mu0) (locBlocksSrc (join_all mu mus)).\nProof.\nelim: mus=> //=; first by move=> [].\nby move=> mu' mus' IH []A []B C; move: (IH (conj A C))=> D; apply: DisjointInU.\nQed.\n\nLemma join_all_disjoint_tgt mu0 (mu : Inj.t) mus :\n  All (fun mu' => Disjoint (locBlocksTgt mu0) (locBlocksTgt mu'))\n    (map Inj.mu (mu :: mus)) ->\n  Disjoint (locBlocksTgt mu0) (locBlocksTgt (join_all mu mus)).\nProof.\nelim: mus=> //=; first by move=> [].\nby move=> mu' mus' IH []A []B C; move: (IH (conj A C))=> D; apply: DisjointInU.\nQed.\n\nLemma join2_consistent j k k' :\n  consistent j k ->\n  consistent j k' ->\n  consistent j (join2 k k').\nProof.\nrewrite/consistent=> A B b1 b2 b2' d2 d2' C.\nby move/join2P=> []D E; case: (A _ _ _ _ _ C D).\nQed.\n\nLemma local_some_extern_none (mu : Inj.t) b1 b2 d2 :\n  local_of mu b1 = Some (b2,d2) ->\n  extern_of mu b1 = None.\nProof.\ncase/local_DomRng; first by apply Inj_wd.\nmove/locBlocksSrc_externNone=> -> //.\nby apply: Inj_wd.\nQed.\n\nLemma locof_extof_False (mu : Inj.t) (mus : seq Inj.t) b1 b2 d2 b2' d2' :\n  local_of (join_all mu mus) b1 = Some (b2, d2) ->\n  extern_of (join_all mu mus) b1 = Some (b2', d2') ->\n  False.\nProof.\nelim: mus=> //; first by move/local_some_extern_none=> ->.\nmove=> mu0 mus' IH /=; rewrite /join.\ncase e: (local_of mu0 b1)=> [[b' ofs']|].\ncase=> e1 e2; rewrite e1 e2 in e.\nby move/join2P=> []; move: (local_some_extern_none e)=> ->.\nmove=> A; move/join2P=> []B C.\napply: (IH A C).\nQed.\n\nLemma join_sm_consistent mu0 (mu1 mu2 : Inj.t) :\n  Consistent mu0 mu1 ->\n  Consistent mu0 mu2 ->\n  Consistent mu0 (join_sm mu1 mu2).\nProof.\nmove=> A B b1 b2 b2' d2 d2' E /=; rewrite /join_sm /as_inj /join /=.\ncase e: (join2 _ _ _)=> // [[b' ofs']|].\ncase=> e1 e2; rewrite e1 e2 in e.\nmove: e; move/join2P=> []E1 E2.\nhave E1': as_inj mu1 b1 = Some (b2',d2').\n  by rewrite /as_inj /join E1.\nby apply: (A _ _ _ _ _ E E1').\ncase f: (local_of _ _)=> // [[b' ofs']|].\ncase=> e1 e2.\nrewrite e1 e2 in f.\nhave F: extern_of mu1 b1 = None.\n  by apply: (local_some_extern_none f).\nhave G: as_inj mu1 b1 = Some (b2',d2').\n  by rewrite /as_inj /join F f.\nby apply: (A _ _ _ _ _ E G).\nmove=> F.\nhave G: as_inj mu2 b1 = Some (b2',d2').\n  rewrite /as_inj /join F.\n  case G: (extern_of _ _)=> //[[b' ofs']].\n  by rewrite (local_some_extern_none F) in G.\nby apply: (B _ _ _ _ _ E G).\nQed.\n\nLemma join_sm_consistent' mu0 (mu1 mu2 : Inj.t) (mus : seq Inj.t) :\n  Consistent mu0 mu1 ->\n  Consistent mu0 (join_all mu2 mus) ->\n  Consistent mu0 (join_sm mu1 (join_all mu2 mus)).\nProof.\nmove=> A B b1 b2 b2' d2 d2' E /=; rewrite /join_sm /as_inj /join /=.\ncase e: (join2 _ _ _)=> // [[b' ofs']|].\ncase=> e1 e2; rewrite e1 e2 in e.\nmove: e; move/join2P=> []E1 E2.\nhave E1': as_inj mu1 b1 = Some (b2',d2').\n  by rewrite /as_inj /join E1.\nby apply: (A _ _ _ _ _ E E1').\ncase f: (local_of _ _)=> // [[b' ofs']|].\ncase=> e1 e2.\nrewrite e1 e2 in f.\nhave F: extern_of mu1 b1 = None.\n  by apply: (local_some_extern_none f).\nhave G: as_inj mu1 b1 = Some (b2',d2').\n  by rewrite /as_inj /join F f.\nby apply: (A _ _ _ _ _ E G).\nmove=> F.\nhave G: as_inj (join_all mu2 mus) b1 = Some (b2',d2').\n  rewrite /as_inj /join F.\n  case G: (extern_of _ _)=> //[[b' ofs']].\n  by elimtype False; apply: (locof_extof_False F G).\nby apply: (B _ _ _ _ _ E G).\nQed.\n\nLemma join_all_consistent mu0 (mu : Inj.t) mus :\n  All (fun mu' => consistent (as_inj mu0) (as_inj mu'))\n    (map Inj.mu (mu :: mus)) ->\n  consistent (as_inj mu0) (as_inj (join_all mu mus)).\nProof.\nelim: mus=> //=; first by move=> [].\nmove=> mu' mus' IH []A []B C; move: (IH (conj A C))=> D.\nby apply: join_sm_consistent'.\nQed.\n\nLemma join2P' (j k : SM_Injection) b1 :\n  Consistent j k ->\n  (join2 (extern_of j) (extern_of k) b1 = None <->\n   [\\/ extern_of j b1 = None | extern_of k b1 = None]).\nProof.\nrewrite /=/consistent=> C.\nrewrite/join2; split.\ncase A: (extern_of j b1)=> // [[x y]|].\ncase B: (extern_of k b1)=> // [[x' y']|].\nhave A': as_inj j b1 = Some (x,y) by rewrite /as_inj /join A.\nhave B': as_inj k b1 = Some (x',y') by rewrite /as_inj /join B.\ncase: (C _ _ _ _ _ A' B')=> -> ->.\nby rewrite Pos.eqb_refl Zeq_bool_refl /=.\nby right.\nby left.\ncase=> ->; first by [].\nby case: (extern_of j b1)=> // [[? ?]].\nQed.\n\nLemma Disjoint_locSrcC mu mu' : DisjointLS mu mu' -> DisjointLS mu' mu.\nProof. by rewrite /= DisjointC. Qed.\n\nLemma Disjoint_locTgtC mu mu' : DisjointLT mu mu' -> DisjointLT mu' mu.\nProof. by rewrite /= DisjointC. Qed.\n\nLemma consistentC mu mu' : Consistent mu mu' -> Consistent mu' mu.\nProof.\nrewrite /= /consistent=> A b1 b2 b2' d2 d2' B C.\nby case: (A _ _ _ _ _ C B)=> -> ->.\nQed.\n\nLemma join_all_wd mu (mus : seq Inj.t) :\n  AllDisjoint locBlocksSrc $ map Inj.mu (mu :: mus) ->\n  AllDisjoint locBlocksTgt $ map Inj.mu (mu :: mus) ->\n  AllConsistent $ map Inj.mu (mu :: mus) ->\n  SM_wd (join_all mu mus).\nProof.\nelim: mus=> /=; first by move=> _ _ _; apply: (Inj_wd mu).\nmove=> mu0 mus IH A B C.\nmove: {A B C}\n  (All2C A Disjoint_locSrcC) (All2C B Disjoint_locTgtC)\n  (All2C C consistentC).\nmove/All2_cons=> []A B.\nmove/All2_cons=> []C D.\nmove/All2_cons=> []E F.\nhave wd: SM_wd (join_all mu mus) by apply IH.\nchange (SM_wd (join_sm mu0 (Inj.mk wd))).\napply: join_sm_wd=> /=.\nby apply: join_all_disjoint_src.\nby apply: join_all_disjoint_tgt.\nby apply join_all_consistent.\nQed.\n\nLemma join_sm_frgn (mu1 mu2 : Inj.t) b :\n  frgnBlocksSrc mu1 b ->\n  frgnBlocksSrc mu2 b ->\n  frgnBlocksSrc (join_sm mu1 mu2) b.\nProof. by rewrite/join_sm/= => A B; apply/andP; split. Qed.\n\nDefinition assimilated mu0 mu := join_sm mu0 mu = mu.\n\nLemma assimilated_sub_locSrc mu0 mu :\n  assimilated mu0 mu -> {subset (locBlocksSrc mu0) <= locBlocksSrc mu}.\nProof. by rewrite/assimilated/join_sm=> <- b /= => A; apply/orP; left. Qed.\n\nLemma assimilated_sub_locTgt mu0 mu :\n  assimilated mu0 mu -> {subset (locBlocksTgt mu0) <= locBlocksTgt mu}.\nProof. by rewrite/assimilated/join_sm=> <- b /= => A; apply/orP; left. Qed.\n\nLemma assimilated_sub_extSrc mu0 mu :\n  assimilated mu0 mu -> {subset (locBlocksSrc mu0) <= locBlocksSrc mu}.\nProof. by rewrite/assimilated/join_sm=> <- b /= => A; apply/orP; left. Qed.\n\nLemma join_sm_extSrc mu1 mu2 :\n  extBlocksSrc (join_sm mu1 mu2)\n  = [predI (extBlocksSrc mu1) & extBlocksSrc mu2].\nProof. by []. Qed.\n\nLemma join_sm_extTgt mu1 mu2 :\n  extBlocksTgt (join_sm mu1 mu2)\n  = [predI (extBlocksTgt mu1) & extBlocksTgt mu2].\nProof. by []. Qed.\n\nLemma join_sm_frgnSrc mu1 mu2 :\n  frgnBlocksSrc (join_sm mu1 mu2)\n  = [predI (frgnBlocksSrc mu1) & frgnBlocksSrc mu2].\nProof. by []. Qed.\n\nLemma join_sm_frgnTgt mu1 mu2 :\n  frgnBlocksTgt (join_sm mu1 mu2)\n  = [predI (frgnBlocksTgt mu1) & frgnBlocksTgt mu2].\nProof. by []. Qed.\n\nLemma join_sm_preserves_globals F V (ge : Genv.t F V) (mu1 mu2 : Inj.t) :\n  Events.meminj_preserves_globals ge (extern_of mu1) ->\n  Events.meminj_preserves_globals ge (extern_of mu2) ->\n  Events.meminj_preserves_globals ge (extern_of (join_sm mu1 mu2)).\nProof.\nmove=> []A []B C []D []E G; rewrite /join_sm /= /join2; split.\n+ move=> id b H.\n  rewrite (A _ _ H) (D _ _ H).\n  by case: (@andP _ _)=> // [][]; rewrite /is_true Pos.eqb_eq -Zeq_is_eq_bool.\nsplit.\n+ move=> b gv H; rewrite (B _ _ H) (E _ _ H).\n  by case: (@andP _ _)=> // [][]; rewrite /is_true Pos.eqb_eq -Zeq_is_eq_bool.\n+ move=> b1 b2 d gv H.\n  case H1: (extern_of _ _)=> // [[? ?]]; case H2: (extern_of _ _)=> // [[? ?]].\n  case: (@andP _ _)=> //; case.\n  rewrite /is_true Pos.eqb_eq -Zeq_is_eq_bool=> X Y; case=> Z W.\n  by move: X Y Z W H1 H2=> -> -> -> -> //; move/(C _ _ _ _ H)=> <-.\nQed.\n\nLemma join_sm_isGlob F V (ge : Genv.t F V) (mu1 mu2 : Inj.t) :\n (forall b, isGlobalBlock ge b -> frgnBlocksSrc mu1 b) ->\n (forall b, isGlobalBlock ge b -> frgnBlocksSrc mu2 b) ->\n forall b, isGlobalBlock ge b -> frgnBlocksSrc (join_sm mu1 mu2) b.\nProof.\nrewrite/join_sm /= => A B b C; move: (A _ C) (B _ C)=> ? ?.\nby apply/andP; split.\nQed.\n\nLemma join_all_id mu : join_all mu [::] = mu.\nProof. by []. Qed.\n\nLemma join_all_preserves_globals\n      F V (ge : Genv.t F V) (mu : Inj.t) (mus : seq Inj.t) :\n  Events.meminj_preserves_globals ge (extern_of mu) ->\n  (AllDisjoint locBlocksSrc \\o map Inj.mu) (mu :: mus) ->\n  (AllDisjoint locBlocksTgt \\o map Inj.mu) (mu :: mus) ->\n  (AllConsistent \\o map Inj.mu) (mu :: mus) ->\n  All (Events.meminj_preserves_globals ge \\o extern_of \\o Inj.mu) mus ->\n  Events.meminj_preserves_globals ge (extern_of (join_all mu mus)).\nProof.\nelim: mus=> //= mu' mus' IH PRES A B C.\nmove: {A B C}\n  (All2C A Disjoint_locSrcC) (All2C B Disjoint_locTgtC)\n  (All2C C consistentC).\nmove/All2_cons=> []B C.\nmove/All2_cons=> []D E.\nmove/All2_cons=> []G H.\nhave wd: SM_wd (join_all mu mus') by apply: join_all_wd.\nmove=> []I J.\nchange (Events.meminj_preserves_globals ge\n  (extern_of (join_sm mu' (Inj.mk wd)))).\napply: join_sm_preserves_globals=> //.\nby apply: IH.\nQed.\n\nLemma join_all_isGlob F V (ge : Genv.t F V) (mu : Inj.t) (mus : seq Inj.t) :\n (forall b, isGlobalBlock ge b -> frgnBlocksSrc mu b) ->\n All (fun mu => forall b, isGlobalBlock ge b -> frgnBlocksSrc mu b)\n     (map Inj.mu mus) ->\n forall b, isGlobalBlock ge b -> frgnBlocksSrc (join_all mu mus) b.\nProof.\nelim: mus mu=> // mu' mus' IH mu A /= []B C b D; apply/andP; split=> //.\nby apply: (B _ D).\nby apply: IH.\nQed.\n\nLemma join_sm_valid mu1 mu2 m1 m2 :\n  sm_valid mu1 m1 m2 ->\n  sm_valid mu2 m1 m2 ->\n  sm_valid (join_sm mu1 mu2) m1 m2.\nProof.\nrewrite/join_sm/sm_valid/DOM/RNG/DomSrc/DomTgt /= => [][]A B []C D; split.\nmove=> b1; move/orP; case.\nmove/orP; case=> E.\nby apply: A; apply/orP; left.\nby apply: C; apply/orP; left.\nmove/andP=> []E F.\nby apply: A; apply/orP; right.\nmove=> b2; move/orP; case.\nmove/orP; case=> E.\nby apply: B; apply/orP; left.\nby apply: D; apply/orP; left.\nmove/andP=> []E F.\nby apply: D; apply/orP; right.\nQed.\n\nLemma join_smvalid_src mu1 mu2 m1 :\n  smvalid_src mu1 m1 ->\n  smvalid_src mu2 m1 ->\n  smvalid_src (join_sm mu1 mu2) m1.\nProof.\nrewrite/join_sm/smvalid_src/DOM/RNG/DomSrc/DomTgt /= => []A B.\nmove=> b1; move/orP; case.\nmove/orP; case=> E.\nby apply: A; apply/orP; left.\nby apply: B; apply/orP; left.\nmove/andP=> []E F.\nby apply: A; apply/orP; right.\nQed.\n\nLemma join_all_valid (mu : Inj.t) mus m1 m2 :\n  sm_valid mu m1 m2 ->\n  All (fun mu0 => sm_valid (Inj.mu mu0) m1 m2) mus ->\n  sm_valid (join_all mu mus) m1 m2.\nProof.\nmove: mu m1 m2; elim: mus=> // mu' mus' IH mu m1 m2 A /= []B C.\nby apply: join_sm_valid=> //; apply: IH.\nQed.\n\nLemma join_all_valid_src (mu : Inj.t) mus m1 :\n  smvalid_src mu m1 ->\n  All (fun mu0 => smvalid_src (Inj.mu mu0) m1) mus ->\n  smvalid_src (join_all mu mus) m1.\nProof.\nmove: mu m1; elim: mus=> // mu' mus' IH mu m1 A /= []B C.\nby apply: join_smvalid_src=> //; apply: IH.\nQed.\n\nLemma DisjointLS_restrict mu1 mu2 X Y :\n  DisjointLS mu1 mu2 ->\n  DisjointLS (restrict_sm mu1 X) (restrict_sm mu2 Y).\nProof. by case: mu1; case: mu2. Qed.\n\nLemma DisjointLT_restrict mu1 mu2 X Y :\n  DisjointLT mu1 mu2 ->\n  DisjointLT (restrict_sm mu1 X) (restrict_sm mu2 Y).\nProof. by case: mu1; case: mu2. Qed.\n\nLemma DisjointLS_E1 mu1 mu2 b :\n  DisjointLS mu1 mu2 ->\n  locBlocksSrc mu1 b ->\n  locBlocksSrc mu2 b=false.\nProof.\nmove/DisjointP; move/(_ b); case; first by contradiction.\nby case: (locBlocksSrc mu2 b).\nQed.\n\nLemma DisjointLS_E2 mu1 mu2 b :\n  DisjointLS mu1 mu2 ->\n  locBlocksSrc mu2 b ->\n  locBlocksSrc mu1 b=false.\nProof.\nmove/DisjointP; move/(_ b); case; first by case: (locBlocksSrc mu1 b).\nby contradiction.\nQed.\n\nLemma DisjointLT_E1 mu1 mu2 b :\n  DisjointLT mu1 mu2 ->\n  locBlocksTgt mu1 b ->\n  locBlocksTgt mu2 b=false.\nProof.\nmove/DisjointP; move/(_ b); case; first by contradiction.\nby case: (locBlocksTgt mu2 b).\nQed.\n\nLemma DisjointLT_E2 mu1 mu2 b :\n  DisjointLT mu1 mu2 ->\n  locBlocksTgt mu2 b ->\n  locBlocksTgt mu1 b=false.\nProof.\nmove/DisjointP; move/(_ b); case; first by case: (locBlocksTgt mu1 b).\nby contradiction.\nQed.\n\nLemma DisjointLS_incr mu1 mu1' mu2 m1 m2 m1' m2' :\n  DisjointLS mu1 mu2 ->\n  intern_incr mu1 mu1' ->\n  sm_inject_separated mu1 mu1' m1 m2 ->\n  sm_locally_allocated mu1 mu1' m1 m2 m1' m2' ->\n  sm_valid mu2 m1 m2 ->\n  DisjointLS mu1' mu2.\nProof.\nmove/DisjointP=> A B C D E /=; rewrite DisjointP=> b; move: (A b).\ncase=> // F.\ncase G: (locBlocksSrc mu2 b); last by right. left=> H.\nhave F': locBlocksSrc mu1 b = false by move: F; case: (locBlocksSrc mu1 b).\ncase: (sm_inject_separated_intern_MYB _ _ _ _ _ _ C D); move/(_ b F' H)=> I _.\nby case: E; move/(_ b); rewrite/DOM/DomSrc G=> J _; apply: I; apply: J.\nby right.\nQed.\n\nLemma DisjointLT_incr mu1 mu1' mu2 m1 m2 m1' m2' :\n  DisjointLT mu1 mu2 ->\n  intern_incr mu1 mu1' ->\n  sm_inject_separated mu1 mu1' m1 m2 ->\n  sm_locally_allocated mu1 mu1' m1 m2 m1' m2' ->\n  sm_valid mu2 m1 m2 ->\n  DisjointLT mu1' mu2.\nProof.\nmove/DisjointP=> A B C D E /=; rewrite DisjointP=> b; move: (A b).\ncase=> // F.\ncase G: (locBlocksTgt mu2 b); last by right. left=> H.\nhave F': locBlocksTgt mu1 b = false by move: F; case: (locBlocksTgt mu1 b).\ncase: (sm_inject_separated_intern_MYB _ _ _ _ _ _ C D)=> _; move/(_ b F' H)=> I.\nby case: E=> _; move/(_ b); rewrite/RNG/DomTgt G => J; apply: I; apply: J.\nby right.\nQed.\n\nLemma AllDisjointLS_incr mu1 mu1' mus m1 m2 m1' m2' :\n  All (fun mu0 => DisjointLS mu1 mu0) mus ->\n  intern_incr mu1 mu1' ->\n  sm_inject_separated mu1 mu1' m1 m2 ->\n  sm_locally_allocated mu1 mu1' m1 m2 m1' m2' ->\n  All (fun mu0 => sm_valid mu0 m1 m2) mus ->\n  All (fun mu0 => DisjointLS mu1' mu0) mus.\nProof.\nelim: mus=> // mu0 mus' IH /= []A B C D E []F G.\nsplit; first by apply: (DisjointLS_incr A C D E F).\nby apply: IH.\nQed.\n\nLemma AllDisjointLT_incr mu1 mu1' mus m1 m2 m1' m2' :\n  All (fun mu0 => DisjointLT mu1 mu0) mus ->\n  intern_incr mu1 mu1' ->\n  sm_inject_separated mu1 mu1' m1 m2 ->\n  sm_locally_allocated mu1 mu1' m1 m2 m1' m2' ->\n  All (fun mu0 => sm_valid mu0 m1 m2) mus ->\n  All (fun mu0 => DisjointLT mu1' mu0) mus.\nProof.\nelim: mus=> // mu0 mus' IH /= []A B C D E []F G.\nsplit; first by apply: (DisjointLT_incr A C D E F).\nby apply: IH.\nQed.\n\nLemma vis_join_sm mu1 mu2 :\n  vis (join_sm mu1 mu2)\n  = [predU [predU (locBlocksSrc mu1) & locBlocksSrc mu2]\n         & [predI (frgnBlocksSrc mu1) & frgnBlocksSrc mu2]].\nProof.\nby rewrite/vis/join_sm/=; extensionality b=> /=; rewrite/predU.\nQed.\n\nLemma locBlocksSrc_vis mu : {subset (locBlocksSrc mu) <= vis mu}.\nProof. by rewrite/vis=> b; rewrite/in_mem/= => A; apply/orP; left. Qed.\n\nLemma frgnBlocksSrc_vis mu : {subset (frgnBlocksSrc mu) <= vis mu}.\nProof. by rewrite/vis=> b; rewrite/in_mem/= => A; apply/orP; right. Qed.\n\nLemma join_sm_incr mu1 mu1' mu2 mu2' :\n  disjoint (local_of mu1') (local_of mu2') ->\n  intern_incr mu1 mu1' ->\n  intern_incr mu2 mu2' ->\n  intern_incr (join_sm mu1 mu2) (join_sm mu1' mu2').\nProof.\nrewrite/intern_incr/join_sm/= => disj.\nmove=> []incr1 []<- []A []B []? []? []<- []<- []<- <-.\nmove=> []incr2 []<- []C []D []? []? []<- []<- []<- <-.\nsplit=> //.\napply: inject_incr_join=> //.\nsplit=> //.\nsplit=> //.\nmove=> b; move/orP; case=> H.\nby rewrite/in_mem/= (A _ H).\nby rewrite/in_mem/= (C _ H); apply/orP; right.\nsplit=> //.\nmove=> b; move/orP; case=> H.\nby rewrite/in_mem/= (B _ H).\nby rewrite/in_mem/= (D _ H); apply/orP; right.\nQed.\n\nLemma join_all_incr (mu_trash mu mu' : Inj.t) (mus : seq Inj.t) :\n  disjoint (local_of mu') (local_of (join_all mu_trash mus)) ->\n  intern_incr mu mu' ->\n  intern_incr (join_all mu_trash (mu :: mus))\n              (join_all mu_trash (mu':: mus)).\nProof. by move=> /= A B; apply: join_sm_incr. Qed.\n\nLemma joinP j k b1 b2 d :\n  join j k b1 = Some (b2,d) <->\n  j b1 = Some (b2,d) \\/ (j b1 = None /\\ k b1 = Some (b2,d)).\nProof.\nrewrite/join; split.\ncase: (j b1)=> // [[? ?]|->]; first by case=> -> ->; left.\nby right. case=> A; first by rewrite A.\nby case: A=> ->.\nQed.\n\nLemma joinP' j k b1 :\n  join j k b1 = None <-> j b1 = None /\\ k b1 = None.\nProof.\nrewrite/join; split; first by case: (j b1)=> //; first by case.\nby move=> []-> ->.\nQed.\n\nLemma as_injE mu b1 b2 d :\n  as_inj mu b1 = Some (b2,d) ->\n  [\\/ local_of mu b1 = Some (b2,d) | extern_of mu b1 = Some (b2,d)].\nProof.\nrewrite/as_inj/join; case: (extern_of mu b1)=> // [[? ?]|].\nby case=> -> ->; right.\nby left.\nQed.\n\nLemma as_injE' mu b1 :\n  as_inj mu b1 = None ->\n  [/\\ local_of mu b1 = None & extern_of mu b1 = None].\nProof.\nrewrite/as_inj/join; case: (extern_of mu b1)=> // [[? ?]].\nby discriminate.\nQed.\n\nLemma local_of_join_smE mu1 mu2 b1 b2 d :\n  local_of (join_sm mu1 mu2) b1 = Some (b2,d) ->\n  [\\/ local_of mu1 b1 = Some (b2,d)\n    | [/\\ local_of mu1 b1 = None & local_of mu2 b1 = Some (b2,d)]].\nProof. by rewrite/join_sm/=; move/joinP. Qed.\n\nLemma local_of_join_smE' mu1 mu2 b1 :\n  local_of (join_sm mu1 mu2) b1 = None ->\n  [/\\ local_of mu1 b1 = None & local_of mu2 b1 = None].\nProof. by rewrite/join_sm/=; move/joinP'. Qed.\n\nLemma extern_of_join_smE mu1 mu2 b1 b2 d :\n  extern_of (join_sm mu1 mu2) b1 = Some (b2,d) ->\n  [/\\ extern_of mu1 b1 = Some (b2,d)\n    & extern_of mu2 b1 = Some (b2,d)].\nProof. by rewrite/join_sm/=; move/join2P. Qed.\n\nLemma extern_of_join_smE' mu1 mu2 b1 :\n  Consistent mu1 mu2 ->\n  extern_of (join_sm mu1 mu2) b1 = None ->\n  [\\/ extern_of mu1 b1 = None\n    | extern_of mu2 b1 = None].\nProof. by rewrite/join_sm/=; move/(join2P' b1)=> ->. Qed.\n\nLemma join2_restrict j k X :\n  join2 (restrict j X) (restrict k X) = restrict (join2 j k) X.\nProof.\nextensionality b.\ncase A: (join2 _ _ b)=> [[b' ofs]|].\nmove: A; move/join2P=> [].\nmove/restrictD_Some=> []A B; move/restrictD_Some=> []C _.\nby rewrite/join2/restrict B A C Pos.eqb_refl Zeq_bool_refl.\nmove: A; rewrite/join2.\ncase A: (restrict j X b)=> [[b' ofs]|].\ncase B: (restrict k X b)=> [[b'' ofs']|].\ncase C: (Pos.eqb b' b'') A B.\ncase D: (Zeq_bool ofs ofs')=> //=.\nby rewrite/restrict; case E: (X b)=> //; move=> -> ->; rewrite C D.\nby rewrite/restrict; case E: (X b)=> //; move=> -> ->; rewrite C.\nmove: A; move/restrictD_Some=> []C D; rewrite/restrict D C.\nmove: B; move/restrictD_None; case: (k b)=> // [[b'' ofs']].\nby move/(_ b'' ofs' erefl); move: D=> ->.\nrewrite/restrict; case B: (j b)=> // [[b' ofs]|].\nby move: A; move/restrictD_None; move/(_ b' ofs B)=> ->.\nby case: (X b).\nQed.\n\nLemma join_sm_restrict mu1 mu2 X :\n  restrict_sm (join_sm mu1 mu2) X\n  = join_sm (restrict_sm mu1 X) (restrict_sm mu2 X).\nProof.\nrewrite/join_sm/=; f_equal.\nby rewrite !restrict_sm_locBlocksSrc.\nby rewrite !restrict_sm_locBlocksTgt.\nby rewrite -!join_restrict !restrict_sm_local.\nby rewrite !restrict_sm_extBlocksSrc.\nby rewrite !restrict_sm_extBlocksTgt.\nby rewrite !restrict_sm_frgnBlocksSrc.\nby rewrite !restrict_sm_frgnBlocksTgt.\nby rewrite -!join2_restrict !restrict_sm_extern.\nQed.\n\nLemma disjoint_restrict j k X :\n  disjoint j k ->\n  disjoint (restrict j X) (restrict k X).\nProof. by rewrite/disjoint/restrict=> A b; case: (X b)=> //; left. Qed.\n\nLemma restrict_incr' j j' X X' :\n  {subset X <= X'} ->\n  Values.inject_incr j j' ->\n  Values.inject_incr (restrict j X) (restrict j' X').\nProof.\nmove=> A; rewrite/Values.inject_incr=> B b b' ofs.\nmove/restrictD_Some=> []C; move/A; rewrite/in_mem/= => D.\nby rewrite/restrict D; apply: (B _ _ _ C).\nQed.\n\nLemma restrict_disj j X X' :\n  {subset X <= X'} ->\n  (forall b b' ofs, j b = Some (b',ofs) -> ~~ [predD X' & X] b) ->\n  restrict j X = restrict j X'.\nProof.\nmove=> A B; rewrite/restrict; extensionality b.\ncase C: (X b); first by move: (A b C); rewrite/in_mem/= => ->.\ncase D: (X' b)=> //.\ncase E: (j b)=> // [[b' ofs]].\nmove: (B _ _ _ E).\nrewrite notin_predD; move/orP; case.\nby rewrite/in_mem/= D.\nby rewrite/in_mem/= C.\nQed.\n\nLemma intern_incr_restrict mu mu' X X' :\n  intern_incr mu mu' ->\n  {subset X <= X'} ->\n  (forall b b' ofs, extern_of mu' b = Some (b',ofs) -> ~~ [predD X' & X] b) ->\n  intern_incr (restrict_sm mu X) (restrict_sm mu' X').\nProof.\ncase=> A []B []C []D []E []F []G []H []I J K; split=> //.\nby rewrite 2!restrict_sm_local; apply: restrict_incr'.\nsplit; first by rewrite 2!restrict_sm_extern; rewrite B; apply: restrict_disj.\nsplit; first by rewrite 2!restrict_sm_locBlocksSrc; apply: C.\nsplit; first by rewrite 2!restrict_sm_locBlocksTgt; apply: D.\nsplit; first by rewrite 2!restrict_sm_pubBlocksSrc E.\nsplit; first by rewrite 2!restrict_sm_pubBlocksTgt F.\nsplit; first by rewrite 2!restrict_sm_frgnBlocksSrc G.\nsplit; first by rewrite 2!restrict_sm_frgnBlocksTgt H.\nsplit; first by rewrite 2!restrict_sm_extBlocksSrc I.\nby rewrite 2!restrict_sm_extBlocksTgt J.\nQed.\n\nLemma join_sm_vis_loc mu1 (mu1' : Inj.t) mu2 b :\n  intern_incr mu1 mu1' ->\n  vis (join_sm mu1 mu2) b=false ->\n  vis (join_sm mu1' mu2) b ->\n  locBlocksSrc mu1 b=false /\\ locBlocksSrc mu1' b.\nProof.\nrewrite 2!vis_join_sm /=/in_mem/=/in_mem/=.\nmove=> incr D E.\nhave F: locBlocksSrc mu1 b=false by move: D; case: (locBlocksSrc mu1 b).\nrewrite F in D; move: D=> /= => D.\nhave G: locBlocksSrc mu2 b=false by move: D; case: (locBlocksSrc mu2 b).\nrewrite G in D; move: D=> /= => D.\nhave H: (frgnBlocksSrc mu1 b=false \\/ frgnBlocksSrc mu2 b=false).\n  move: D; case: (frgnBlocksSrc mu1 b); case: (frgnBlocksSrc mu2 b)=> //=.\n  by right. by left. by right.\nhave I: (frgnBlocksSrc mu1' b && frgnBlocksSrc mu2 b = false).\n  move: H; case: incr=> _ []_ []_ []_ []_ []_ []<- []_ _.\n  case: (frgnBlocksSrc mu1 b)=> //.\n  case: (frgnBlocksSrc mu2 b)=> //.\n  by case.\nhave J: locBlocksSrc mu1' b.\n  by move: E; rewrite G I=> /=; move/orP; case=> //; move/orP; case.\nby split.\nQed.\n\nLemma join_sm_vis_dom mu1 (mu1' : Inj.t) mu2 b :\n  intern_incr mu1 mu1' ->\n  vis (join_sm mu1 mu2) b=false ->\n  vis (join_sm mu1' mu2) b ->\n  DOM mu1 b=false /\\ DOM mu1' b.\nProof.\nrewrite 2!vis_join_sm /=/in_mem/=/in_mem/=.\nmove=> incr D E.\nhave F: locBlocksSrc mu1 b=false by move: D; case: (locBlocksSrc mu1 b).\nrewrite F in D; move: D=> /= => D.\nhave G: locBlocksSrc mu2 b=false by move: D; case: (locBlocksSrc mu2 b).\nrewrite G in D; move: D=> /= => D.\nhave H: (frgnBlocksSrc mu1 b=false \\/ frgnBlocksSrc mu2 b=false).\n  move: D; case: (frgnBlocksSrc mu1 b); case: (frgnBlocksSrc mu2 b)=> //=.\n  by right. by left. by right.\nhave I: (frgnBlocksSrc mu1' b && frgnBlocksSrc mu2 b = false).\n  move: H; case: incr=> _ []_ []_ []_ []_ []_ []<- []_ _.\n  case: (frgnBlocksSrc mu1 b)=> //.\n  case: (frgnBlocksSrc mu2 b)=> //.\n  by case.\nhave J: locBlocksSrc mu1' b.\n  by move: E; rewrite G I=> /=; move/orP; case=> //; move/orP; case.\nhave K: extBlocksSrc mu1' b=false.\n  by apply: (locBlocksSrc_extBlocksSrc _ (Inj_wd mu1') _ J).\nhave L: extBlocksSrc mu1 b=false.\n  by move: H; case: incr=> _ []_ []_ []_ []_ []_ []_ []_ []->.\nby rewrite/DOM/DomSrc F J K L.\nQed.\n\nLemma join_sm_vis_extBlocksSrc mu1 mu1' mu2 :\n  intern_incr mu1 mu1' ->\n  extBlocksSrc (join_sm mu1 mu2) = extBlocksSrc (join_sm mu1' mu2).\nProof.\nrewrite 2!join_sm_extSrc.\nby case=> _ []_ []_ []_ []_ []_ []_ []_ []->.\nQed.\n\nLemma join_sm_restrict_incr mu1 (mu1' mu2 : Inj.t) m1 m2 :\n  disjoint (local_of mu1') (local_of mu2) ->\n  intern_incr mu1 mu1' ->\n  sm_inject_separated mu1 mu1' m1 m2 ->\n  sm_valid mu2 m1 m2 ->\n  let mu12  := join_sm mu1 mu2 in\n  let mu12' := join_sm mu1' mu2 in\n  intern_incr (restrict_sm mu12 (vis mu12)) (restrict_sm mu12' (vis mu12')).\nProof.\nmove=> A B sep val mu12 mu12'; rewrite 2!join_sm_restrict.\nhave S: {subset vis mu12 <= vis mu12'}.\n  { move=> b; rewrite 2!vis_join_sm /in_mem/=/in_mem/=/in_mem/=.\n    move/orP; case=> D; apply/orP.\n    left; case: (orP D)=> E; apply/orP; last by right.\n    by case: B=> _ []_ []F _; left; apply: (F _ E).\n    move: (andP D)=> []E F; right; apply/andP; split=> //.\n    by case: B=> _ []_ []_ []_ []_ []_ []<-. }\napply: join_sm_incr=> //.\nby rewrite 2!restrict_sm_local; apply: (disjoint_restrict _ A).\nhave C: forall b b' ofs,\n  extern_of mu1' b = Some (b',ofs) -> ~~[predD (vis mu12') & (vis mu12)] b.\n  { move=> b b' ofs; rewrite/mu12'/= => C; apply/negP; move/andP=> []E F.\n    cut (locBlocksSrc mu1' b = true).\n    by move/(locBlocksSrc_externNone _ (Inj_wd _)); rewrite C.\n    move: E F; rewrite/mu12/vis/in_mem/=; move/negP; rewrite/in_mem/=.\n    case: B=> _ []_ []_ []_ []_ []_ []<- []_ []_ _.\n    case: (locBlocksSrc mu1 b)=> //; case: (locBlocksSrc mu2 b)=> //.\n    by case: (locBlocksSrc mu1' b). }\nby apply: (intern_incr_restrict B).\nhave C: forall b b' ofs,\n  extern_of mu2 b = Some (b',ofs) -> ~~[predD (vis mu12') & (vis mu12)] b.\n  { move=> b b' ofs; rewrite/mu12'/= => C; apply/negP; move/andP=> []E F.\n    have G: DOM mu1 b=false /\\ DOM mu1' b.\n      have E': vis mu12 b = false.\n        by move: E; rewrite/in_mem/=; case: (vis mu12 b).\n      have F': vis mu12' b by apply: F.\n      by apply (join_sm_vis_dom B E' F').\n    rewrite/DOM in G; case: G=> G H; case: sep=> []_ [].\n    have G': DomSrc mu1 b=false.\n      move: G; case: (DomSrc mu1 b)=> //.\n    have H': (is_true false) <-> False by split.\n    by move=> I; elimtype False; rewrite -H' -I.\n    move/(_ b G' H).\n    case: val; rewrite/DOM/DomSrc; move/(_ b).\n    case: (extern_DomRng _ (Inj_wd mu2) _ _ _ C)=> -> _ I _ J _.\n    by apply: J; apply: I; apply/orP; right. }\nby apply: intern_incr_restrict.\nQed.\n\nLemma join_sm_inject_separated (mu1 mu1' mu2 : Inj.t) m1 m2 m1' m2' :\n  Consistent mu1 mu2 ->\n  intern_incr mu1 mu1' ->\n  sm_inject_separated mu1 mu1' m1 m2 ->\n  sm_locally_allocated mu1 mu1' m1 m2 m1' m2' ->\n  sm_valid mu1 m1 m2 ->\n  sm_valid mu2 m1 m2 ->\n  sm_inject_separated (join_sm mu1 mu2) (join_sm mu1' mu2) m1 m2.\nProof.\nmove=> consistent A []B []C D E val F.\nrewrite ->sm_locally_allocatedChar in E.\ncase: E=> E1 []E2 []E3 []E4 []E5 E6.\nsplit.\nmove=> b1 b2 d.\nrewrite/join_sm/DomSrc/DomTgt/as_inj/in_mem/=/in_mem/=.\nmove/joinP'=> []G. move/joinP'=> []H I.\nmove/joinP=> J.\nrewrite ->join2P' in G=> //.\ncase: J.\nmove/join2P=> []J K.\ncase: G=> L.\ncase: (B b1 b2 d).\nby rewrite/as_inj/join L H.\nby rewrite/as_inj/join J.\nmove=> M N.\nsplit.\nmove: M N; rewrite/DomSrc/DomTgt.\ncase: (locBlocksSrc mu1 b1)=> //.\ncase: (extBlocksSrc mu1 b1)=> //.\ncase: (locBlocksTgt mu1 b2)=> //=.\ncase: (extern_DomRng _ (Inj_wd _) _ _ _ K)=> _ M.\nhave ->: locBlocksSrc mu2 b1 = false.\n  case: (extern_DomRng _ (Inj_wd _) _ _ _ K).\n  by move/(extBlocksSrc_locBlocksSrc _ (Inj_wd _))=> ->.\nby [].\nmove: M N; rewrite/DomSrc/DomTgt.\ncase: (locBlocksSrc mu1 b1)=> //.\ncase: (extBlocksSrc mu1 b1)=> //.\ncase: (locBlocksTgt mu1 b2)=> //=.\ncase: (extBlocksTgt mu1 b2)=> //=.\ncase: (extern_DomRng _ (Inj_wd _) _ _ _ K)=> M N.\nhave ->: locBlocksTgt mu2 b2 = false.\n  case: (extern_DomRng _ (Inj_wd _) _ _ _ K)=> _.\n  by move/(extBlocksTgt_locBlocksTgt _ (Inj_wd _))=> ->.\nby [].\nrewrite K in L; congruence.\nmove=> []. move/join2P'=> J.\nmove/joinP=> K.\ncase: K. move=> K.\ncase: G=> G.\ncase: (B b1 b2 d).\nby rewrite/as_inj/join G H.\nrewrite/as_inj/join.\nhave ->: extern_of mu1' b1=None.\n  case X: (extern_of mu1' b1)=> // [[? ?]].\n  case: (extern_DomRng _ (Inj_wd _) _ _ _ X)=> Y _.\n  case: (local_DomRng _ (Inj_wd _) _ _ _ K)=> Z _.\n  by move: Y Z; move/(extBlocksSrc_locBlocksSrc _ (Inj_wd _))=> ->.\nby [].\nmove=> M N.\nsplit.\nmove: M N; rewrite/DomSrc/DomTgt.\ncase X: (locBlocksSrc mu1 b1)=> //.\ncase Y: (extBlocksSrc mu1 b1)=> //.\ncase: (locBlocksTgt mu1 b2)=> //.\ncase: (extBlocksTgt mu1 b2)=> //.\nsimpl.\nhave L: ~Memory.Mem.valid_block m1 b1.\n  apply: C.\n  by rewrite/DomSrc X Y.\n  case: (local_DomRng _ (Inj_wd _) _ _ _ K).\n  rewrite/DomSrc.\n  by move=> ->.\ncase M: (locBlocksSrc mu2 b1)=> //.\ncase: F; move/(_ b1)=> N.\nelimtype False.\napply: L; apply: N.\nby rewrite/DOM/DomSrc M.\nmove: M N; rewrite/DomSrc/DomTgt.\ncase: (locBlocksSrc mu1 b1)=> //.\ncase: (extBlocksSrc mu1 b1)=> //.\ncase X: (locBlocksTgt mu1 b2)=> //.\ncase Y: (extBlocksTgt mu1 b2)=> //.\nsimpl.\nhave L: ~Memory.Mem.valid_block m2 b2.\n  apply: D.\n  by rewrite/DomTgt X Y.\n  case: (local_DomRng _ (Inj_wd _) _ _ _ K).\n  rewrite/DomTgt.\n  by move=> _ ->.\ncase M: (locBlocksTgt mu2 b2)=> //.\ncase: F=> _; move/(_ b2)=> N.\nelimtype False.\napply: L; apply: N.\nby rewrite/RNG/DomTgt M.\ncase: (local_DomRng _ (Inj_wd _) _ _ _ K)=> M N.\nrewrite E3 in M.\nrewrite E4 in N.\nhave O: extern_of mu1 b1=None.\n  case X: (extern_of mu1 b1)=> // [[? ?]].\n  case: (extern_DomRng _ (Inj_wd _) _ _ _ X)=> O P.\n  case: val; move/(_ b1)=> Q.\n  move: M; case Y: (locBlocksSrc mu1 b1)=> //=.\n  rewrite extBlocksSrc_locBlocksSrc in Y=> //.\n  by apply: Inj_wd.\n  rewrite freshloc_charT=> [][]Z W _.\n  elimtype False.\n  apply: W.\n  apply: Q.\n  by rewrite/DOM/DomSrc O; apply/orP; right.\ncase: (B b1 b2 d).\nby rewrite/as_inj/join O H.\nrewrite/as_inj/join.\nhave ->: extern_of mu1' b1=None.\n  case P: (extern_of mu1' b1)=> // [[? ?]].\n  case: (extern_DomRng _ (Inj_wd _) _ _ _ P)=> Q R.\n  case: (local_DomRng _ (Inj_wd _) _ _ _ K)=> S T.\n  rewrite extBlocksSrc_locBlocksSrc in S=> //.\n  by apply: Inj_wd.\nby [].\nmove=> P Q.\nsplit.\nmove: P; rewrite/DomSrc.\ncase X: (locBlocksSrc mu1 b1)=> //.\ncase Y: (extBlocksSrc mu1 b1)=> //.\nsimpl.\ncase Z: (locBlocksSrc mu2 b1)=> //.\nhave L: ~Memory.Mem.valid_block m1 b1.\n  apply: C.\n  by rewrite/DomSrc X Y.\n  case: (local_DomRng _ (Inj_wd _) _ _ _ K).\n  rewrite/DomSrc.\n  by move=> ->.\ncase R: (locBlocksSrc mu2 b1)=> //.\ncase: F; move/(_ b1)=> S.\nelimtype False.\napply: L; apply: S.\nby rewrite/DOM/DomSrc Z.\nrewrite Z in R.\ncongruence.\nmove: Q; rewrite/DomTgt.\ncase X: (locBlocksTgt mu1 b2)=> //.\ncase Y: (extBlocksTgt mu1 b2)=> //.\nsimpl.\ncase Z: (locBlocksTgt mu2 b2)=> //.\nhave L: ~Memory.Mem.valid_block m2 b2.\n  apply: D.\n  by rewrite/DomTgt X Y.\n  case: (local_DomRng _ (Inj_wd _) _ _ _ K).\n  rewrite/DomTgt.\n  by move=> _ ->.\ncase R: (locBlocksTgt mu2 b2)=> //.\ncase: F=> _; move/(_ b2)=> S.\nelimtype False.\napply: L; apply: S.\nby rewrite/RNG/DomTgt Z.\nrewrite Z in R.\ncongruence.\nby rewrite I=> [][].\nsplit.\n{ move=> b1.\nrewrite/DomSrc/join_sm/=/in_mem/=.\nmove=> G H.\nhave G1: locBlocksSrc mu1 b1=false.\n  move: G.\n  by case: (locBlocksSrc mu1 b1).\nhave G2: locBlocksSrc mu2 b1=false.\n  move: G.\n  rewrite G1.\n  by case: (locBlocksSrc mu2 b1).\nhave G3: (extBlocksSrc mu1 b1 && extBlocksSrc mu2 b1)=false.\n  move: G.\n  case: (extBlocksSrc mu1 b1 && extBlocksSrc mu2 b1)=> //.\n  case/orP.\n  by right.\nhave H1: locBlocksSrc mu1' b1=true.\n  move: H.\n  rewrite G2.\n  rewrite E5.\n  rewrite G3=> /=.\n  by case: (locBlocksSrc mu1' b1).\nhave G4: extBlocksSrc mu1 b1=false.\n  rewrite -E5.\n  apply locBlocksSrc_extBlocksSrc in H1=> //.\n  by apply: Inj_wd.\napply: C.\nby rewrite/DomSrc G1 G4.\nby rewrite/DomSrc H1. }\n{ move=> b1.\nrewrite/DomTgt/join_sm/=/in_mem/=.\nmove=> G H.\nhave G1: locBlocksTgt mu1 b1=false.\n  move: G.\n  by case: (locBlocksTgt mu1 b1).\nhave G2: locBlocksTgt mu2 b1=false.\n  move: G.\n  rewrite G1.\n  by case: (locBlocksTgt mu2 b1).\nhave G3: (extBlocksTgt mu1 b1 && extBlocksTgt mu2 b1)=false.\n  move: G.\n  case: (extBlocksTgt mu1 b1 && extBlocksTgt mu2 b1)=> //.\n  case/orP.\n  by right.\nhave H1: locBlocksTgt mu1' b1=true.\n  move: H.\n  rewrite G2.\n  rewrite E6.\n  rewrite G3=> /=.\n  by case: (locBlocksTgt mu1' b1).\nhave G4: extBlocksTgt mu1 b1=false.\n  rewrite -E6.\n  apply locBlocksTgt_extBlocksTgt in H1=> //.\n  by apply: Inj_wd.\napply: D.\nby rewrite/DomTgt G1 G4.\nby rewrite/DomTgt H1. }\nQed.\n\nLemma join_all_sm_inject_separated\n    (mu_trash : Inj.t) (mu1 mu1' : Inj.t) (mus : seq Inj.t) m1 m2 m1' m2' :\n  All (fun mu0 => Consistent mu1 mu0) [seq Inj.mu x | x <- mus] ->\n  All (fun mu0 => sm_valid mu0 m1 m2) [seq Inj.mu x | x <- mus] ->\n  SM_wd (join_all mu_trash $ mus) ->\n  Consistent mu1 mu_trash ->\n  intern_incr mu1 mu1' ->\n  sm_inject_separated mu1 mu1' m1 m2 ->\n  sm_locally_allocated mu1 mu1' m1 m2 m1' m2' ->\n  sm_valid mu1 m1 m2 ->\n  sm_valid mu_trash m1 m2 ->\n  sm_inject_separated\n    (join_all mu_trash $ mu1 :: mus) (join_all mu_trash $ mu1' :: mus) m1 m2.\nProof.\nelim: mus; first by move=> _ _ _; apply: join_sm_inject_separated.\nmove=> mu0 mus' IH cons1 /=.\nmove=> []val1 allval wd cons2 incr sep localloc val2 valtr.\nhave B': All [eta Consistent mu1] [seq Inj.mu x | x <- mu_trash :: mus'].\n  by move=> /=; split=> //; move: cons1=> /= [].\nmove: (join_all_consistent B')=> G.\nchange (sm_inject_separated (join_sm mu1 (Inj.mk wd))\n                            (join_sm mu1' (Inj.mk wd)) m1 m2).\napply join_sm_inject_separated with (m1':=m1') (m2':=m2')=> //.\nmove: cons1=> /= []H I.\nhave J: Consistent mu1 (join_all mu_trash mus').\n  by apply: join_all_consistent.\nby apply: (join_sm_consistent' H J).\napply: join_sm_valid=> //; apply: join_all_valid=> //; move: allval.\nby rewrite -All_comp.\nQed.\n\nLemma join_sm_DomSrc mu1 mu2 :\n  DomSrc (join_sm mu1 mu2)\n  = (fun b => locBlocksSrc mu1 b || locBlocksSrc mu2 b\n           || extBlocksSrc mu1 b && extBlocksSrc mu2 b).\nProof. by []. Qed.\n\nLemma join_sm_DomTgt mu1 mu2 :\n  DomTgt (join_sm mu1 mu2)\n  = (fun b => locBlocksTgt mu1 b || locBlocksTgt mu2 b\n           || extBlocksTgt mu1 b && extBlocksTgt mu2 b).\nProof. by []. Qed.\n\nLemma join_sm_locBlocksSrc mu1 mu2 :\n  locBlocksSrc (join_sm mu1 mu2)\n  = (fun b => locBlocksSrc mu1 b || locBlocksSrc mu2 b).\nProof. by []. Qed.\n\nLemma join_sm_locBlocksTgt mu1 mu2 :\n  locBlocksTgt (join_sm mu1 mu2)\n  = (fun b => locBlocksTgt mu1 b || locBlocksTgt mu2 b).\nProof. by []. Qed.\n\nLemma join_sm_extBlocksSrc mu1 mu2 :\n  extBlocksSrc (join_sm mu1 mu2)\n  = (fun b => extBlocksSrc mu1 b && extBlocksSrc mu2 b).\nProof. by []. Qed.\n\nLemma join_sm_extBlocksTgt mu1 mu2 :\n  extBlocksTgt (join_sm mu1 mu2)\n  = (fun b => extBlocksTgt mu1 b && extBlocksTgt mu2 b).\nProof. by []. Qed.\n\nLemma join_sm_locally_allocated mu1 mu1' mu2 m1 m2 m1' m2' :\n  sm_locally_allocated mu1 mu1' m1 m2 m1' m2' ->\n  sm_locally_allocated (join_sm mu1 mu2) (join_sm mu1' mu2) m1 m2 m1' m2'.\nProof.\nrewrite 2!sm_locally_allocatedChar.\nmove=> []A []B []C []D []E F.\nrewrite !join_sm_DomSrc !join_sm_DomTgt.\nrewrite !join_sm_locBlocksSrc !join_sm_locBlocksTgt.\nrewrite !join_sm_extBlocksSrc !join_sm_extBlocksTgt.\nsplit.\nextensionality b; rewrite C E -(orb_comm (freshloc _ _ _)) -!orb_assoc.\nby rewrite (orb_comm (freshloc _ _ _)) !orb_assoc.\nsplit.\nextensionality b; rewrite D F -(orb_comm (freshloc _ _ _)) -!orb_assoc.\nby rewrite (orb_comm (freshloc _ _ _)) !orb_assoc.\nsplit.\nby extensionality b; rewrite C -orb_assoc (orb_comm (freshloc _ _ _)) orb_assoc.\nsplit.\nextensionality b; rewrite D.\nby rewrite -orb_assoc (orb_comm (freshloc _ _ _)) orb_assoc.\nsplit; extensionality b; first by rewrite E.\nby rewrite F.\nQed.\n\nLemma join_all_locally_allocated mu_trash (mu mu' : Inj.t) mus m1 m2 m1' m2' :\n  sm_locally_allocated mu mu' m1 m2 m1' m2' ->\n  sm_locally_allocated\n    (join_all mu_trash (mu :: mus))\n    (join_all mu_trash (mu' :: mus)) m1 m2 m1' m2'.\nProof.\nelim: mus; first by rewrite !join_all_cons; apply: join_sm_locally_allocated.\nmove=> mu0 mus' IH A; rewrite 2!join_all_cons.\nby apply: join_sm_locally_allocated.\nQed.\n\nLemma All_disjoint (mu_trash : Inj.t) (mu : Inj.t) mus :\n  disjoint (local_of mu) (local_of mu_trash) ->\n  All (fun mu2 : Inj.t => disjoint (local_of mu) (local_of mu2)) mus ->\n  disjoint (local_of mu) (local_of (join_all mu_trash mus)).\nProof.\nelim: mus=> // mu0 mus' IH A /= []B C.\nrewrite disjoint_com; apply: join_disjoint; first by rewrite disjoint_com.\nby rewrite disjoint_com; apply: IH.\nQed.\n\nLemma DisjointLS_disjoint (mu mu' : Inj.t) :\n  DisjointLS mu mu' -> disjoint (local_of mu) (local_of mu').\nProof.\nmove=> A b.\ncase B: (local_of mu b)=> [[? ?]|].\ncase: (local_DomRng _ (Inj_wd _) _ _ _ B)=> C _.\ncase E: (local_of mu' b)=> [[? ?]|].\ncase: (local_DomRng _ (Inj_wd _) _ _ _ E)=> D _.\nby move: D; move: (DisjointLS_E1 A C)=> ->.\nby right.\nby left.\nQed.\n\nLemma join_all_restrict_incr (mu_trash mu mu' : Inj.t) (mus : seq Inj.t) m1 m2 :\n  All (fun mu2 : Inj.t => disjoint (local_of mu') (local_of mu2)) mus ->\n  All (DisjointLS mu_trash) $ map Inj.mu mus ->\n  All (DisjointLT mu_trash) $ map Inj.mu mus ->\n  All (fun mu2 => Consistent mu_trash mu2) $ map Inj.mu mus ->\n  disjoint (local_of mu') (local_of mu_trash) ->\n  AllDisjoint locBlocksSrc \\o map Inj.mu $ mus ->\n  AllDisjoint locBlocksTgt \\o map Inj.mu $ mus ->\n  AllConsistent \\o map Inj.mu $ mus ->\n  All (fun mu2 => sm_valid (Inj.mu mu2) m1 m2) mus ->\n  intern_incr mu mu' ->\n  sm_inject_separated mu mu' m1 m2 ->\n  sm_valid (Inj.mu mu_trash) m1 m2 ->\n  let mu_tot  := join_all mu_trash (mu :: mus) in\n  let mu_tot' := join_all mu_trash (mu' :: mus) in\n  intern_incr (restrict_sm mu_tot (vis mu_tot)) (restrict_sm mu_tot' (vis mu_tot')).\nProof.\nmove=> A disj_S disj_T consist disj_trash allS allT allC B C D E top top'.\nrewrite/top/top' 2!join_all_cons.\nhave G: SM_wd (join_all mu_trash mus) by apply: join_all_wd.\nhave H: sm_valid (Inj.mk G) m1 m2 by apply: join_all_valid.\nhave I: disjoint (local_of mu') (local_of (Inj.mk G)).\n  by apply: All_disjoint.\nby apply: (join_sm_restrict_incr I C D H).\nQed.\n\nLemma join_all_restrict_sep\n    (mu_trash : Inj.t) (mu1 mu1' : Inj.t) (mus : seq Inj.t) m1 m2 m1' m2' :\n  All (fun mu0 => Consistent mu1 mu0) [seq Inj.mu x | x <- mus] ->\n  All (fun mu0 => sm_valid mu0 m1 m2) [seq Inj.mu x | x <- mus] ->\n  Consistent mu1 mu_trash ->\n  sm_valid mu_trash m1 m2 ->\n  sm_valid mu1 m1 m2 ->\n  intern_incr mu1 mu1' ->\n  sm_inject_separated mu1 mu1' m1 m2 ->\n  sm_locally_allocated mu1 mu1' m1 m2 m1' m2' ->\n  let mu_tot  := join_all mu_trash (mu1 :: mus) in\n  let mu_tot' := join_all mu_trash (mu1' :: mus) in\n  sm_valid mu_tot m1 m2 ->\n  SM_wd (join_all mu_trash mus) ->\n  SM_wd mu_tot ->\n  sm_inject_separated\n    (restrict_sm mu_tot (vis mu_tot))\n    (restrict_sm mu_tot' (vis mu_tot')) m1 m2.\nProof.\nmove=> A B C D val incr E loc_alloc mu_tot mu_tot' F tot'_wd tot_wd.\nhave Cut: sm_inject_separated mu_tot mu_tot' m1 m2.\n  by eapply (join_all_sm_inject_separated (m1':=m1')); eauto.\nset mu_tot2 := Inj.mk tot_wd.\nchange (sm_inject_separated\n         (restrict_sm mu_tot2 (vis mu_tot2))\n         (restrict_sm mu_tot' (vis mu_tot')) m1 m2).\n  apply: sm_sep_restrict2=> //.\nmove=> b Y Z.\nhave [G H]: [/\\ locBlocksSrc mu1 b=false & locBlocksSrc mu1' b=true].\n  by apply (join_sm_vis_loc incr Y Z).\napply sm_locally_allocatedChar in loc_alloc.\ncase loc_alloc=> A1 []A2 []A3 []A4 []A5 A6.\nrewrite A3 G /= in H.\nrewrite ->freshloc_charT in H.\nby case: H.\nQed.\n\nLemma join_absorb f g : join f (join f g) = join f g.\nProof.\nby rewrite /join; extensionality a; case: (f a).\nQed.\n\nLemma join_absorb' f' f g :\n  inject_incr f' f ->\n  join f' (join f g) = join f g.\nProof.\nmove=> A; rewrite /join; extensionality a.\nby case e: (f' a)=> // [[b ofs]]; rewrite (A _ _ _ e).\nQed.\n\nLemma join_sm_absorb mu1 mu2 :\n  join_sm mu1 (join_sm mu1 mu2) = join_sm mu1 mu2.\nProof.\ncase: mu1=> ? ? ? ? ? ? ? ? ? ?; rewrite /join_sm /join2 /=; f_equal.\nby rewrite predU_absorb.\nby rewrite predU_absorb.\nby rewrite join_absorb.\nby rewrite predI_absorb.\nby rewrite predI_absorb.\nby rewrite predI_absorb.\nby rewrite predI_absorb.\nextensionality a.\ncase: (_ a)=> //.\nmove=> [b ofs].\ncase: (extern_of _ _)=> //.\nmove=> [b' ofs'].\ncase: (_ && _)=> //.\nby rewrite Pos.eqb_refl Zeq_bool_refl.\nQed.\n\nLemma join_sm_absorb' mu0 mu1 mu2 :\n  inject_incr (local_of mu0) (local_of mu1) ->\n  inject_incr (extern_of mu1) (extern_of mu0) ->\n  {subset (locBlocksSrc mu0) <= locBlocksSrc mu1} ->\n  {subset (locBlocksTgt mu0) <= locBlocksTgt mu1} ->\n  {subset (extBlocksSrc mu1) <= extBlocksSrc mu0} ->\n  {subset (extBlocksTgt mu1) <= extBlocksTgt mu0} ->\n  {subset (frgnBlocksSrc mu1) <= frgnBlocksSrc mu0} ->\n  {subset (frgnBlocksTgt mu1) <= frgnBlocksTgt mu0} ->\n  join_sm mu0 (join_sm mu1 mu2) = join_sm mu1 mu2.\nProof.\ncase: mu0=> ? ? ? ? ? ex0s ex0t fr0s fr0t ef0.\ncase: mu1=> ? ? ? ? ? ex1s ex1t fr1s fr1t ef1; rewrite /join_sm /join2 /=.\nmove=> A B C D E F G H; f_equal.\nby rewrite predU_absorb'.\nby rewrite predU_absorb'.\nby rewrite join_absorb'.\nby rewrite -predI_absorb_sub.\nby rewrite -predI_absorb_sub.\nby rewrite -predI_absorb_sub.\nby rewrite -predI_absorb_sub.\nextensionality a.\ncase e0: (ef0 a)=> // [[b ofs]|].\ncase e1: (ef1 a)=> // [[b' ofs']].\ncase e2: (extern_of _ _)=> // [[b'' ofs'']].\ncase f: (_ && _)=> //.\ncase: (andP f).\nmove/Peqb_true_eq=> ->.\nmove/Zeq_bool_eq=> ->.\ncase g: (_ && _)=> //.\ncase: (andP g).\nmove/Peqb_true_eq=> ->.\nby move/Zeq_bool_eq=> ->.\nmove: (B _ _ _ e1); rewrite e0; case.\ncase: (andP f).\nmove/Peqb_true_eq=> ->.\nmove/Zeq_bool_eq=> ->.\nmove=> eq1 eq2.\nrewrite eq1 eq2 Pos.eqb_refl Zeq_bool_refl /= in g.\ncongruence.\ncase e1: (ef1 a)=> // [[b ofs]].\nmove: (B _ _ _ e1); rewrite e0; congruence.\nQed.\n\nLemma join_all_absorb' mu_trash (mu0 mu1 : Inj.t) (mus : seq Inj.t) :\n  inject_incr (local_of mu0) (local_of mu1) ->\n  inject_incr (extern_of mu1) (extern_of mu0) ->\n  {subset (locBlocksSrc mu0) <= locBlocksSrc mu1} ->\n  {subset (locBlocksTgt mu0) <= locBlocksTgt mu1} ->\n  {subset (extBlocksSrc mu1) <= extBlocksSrc mu0} ->\n  {subset (extBlocksTgt mu1) <= extBlocksTgt mu0} ->\n  {subset (frgnBlocksSrc mu1) <= frgnBlocksSrc mu0} ->\n  {subset (frgnBlocksTgt mu1) <= frgnBlocksTgt mu0} ->\n  join_all mu_trash [:: mu0, mu1 & mus] = join_all mu_trash [:: mu1 & mus].\nProof.\nby move=> A B C D E F G H /=; rewrite join_sm_absorb'.\nQed.\n\nLemma join_all_locBlocksSrc mu mus b :\n  locBlocksSrc (join_all mu mus) b\n  <-> locBlocksSrc mu b\n      \\/ (exists mu0, List.In mu0 mus /\\ locBlocksSrc mu0 b).\nProof.\nelim: mus mu=> //=; split=> H1; first by left.\nby case: H1=> //; move=> []? [].\ncase: (orP H1); rewrite /in_mem /= => H2.\nby right; exists a; split; first by left.\nmove: H2; rewrite H; case; first by left.\nby case=> x []H2 H3; right; exists x; split=> //; right.\ncase: H1=> [H1|[x [H2 H3]]]; apply/orP; rewrite /in_mem /=.\nby rewrite H; right; left.\ncase: H2; first by move=> ->; left.\nby move=> H4; right; rewrite H; right; exists x; split.\nQed.\n\nLemma join_all_locBlocksTgt mu mus b :\n  locBlocksTgt (join_all mu mus) b\n  <-> locBlocksTgt mu b\n      \\/ (exists mu0, List.In mu0 mus /\\ locBlocksTgt mu0 b).\nProof.\nelim: mus mu=> //=; split=> H1; first by left.\nby case: H1=> //; move=> []? [].\ncase: (orP H1); rewrite /in_mem /= => H2.\nby right; exists a; split; first by left.\nmove: H2; rewrite H; case; first by left.\nby case=> x []H2 H3; right; exists x; split=> //; right.\ncase: H1=> [H1|[x [H2 H3]]]; apply/orP; rewrite /in_mem /=.\nby rewrite H; right; left.\ncase: H2; first by move=> ->; left.\nby move=> H4; right; rewrite H; right; exists x; split.\nQed.\n\nLemma join_all_extBlocksSrc mu mus b :\n  extBlocksSrc (join_all mu mus) b\n  <-> extBlocksSrc mu b\n      /\\ (forall mu0, List.In mu0 mus -> extBlocksSrc mu0 b).\nProof.\nelim: mus mu=> //=; split=> H1; first by split.\nby case: H1=> //; move=> []? [].\ncase: (andP H1); rewrite /in_mem /= => H2; rewrite H; case=> H3 H4.\nsplit=> //; move=> mu0; case; first by move=> <-.\nby move=> H5; apply: (H4 _ H5).\ncase: H1=> H1 H2.\napply/andP; rewrite /in_mem /=; split.\nby apply: H2; left.\nby rewrite H; split=> //; move=> mu0 H3; apply: H2; right.\nQed.\n\nLemma join_all_frgnBlocksSrc mu mus b :\n  frgnBlocksSrc (join_all mu mus) b\n  <-> frgnBlocksSrc mu b\n      /\\ (forall mu0, List.In mu0 mus -> frgnBlocksSrc mu0 b).\nProof.\nelim: mus mu=> //=; split=> H1; first by split.\nby case: H1=> //; move=> []? [].\ncase: (andP H1); rewrite /in_mem /= => H2; rewrite H; case=> H3 H4.\nsplit=> //; move=> mu0; case; first by move=> <-.\nby move=> H5; apply: (H4 _ H5).\ncase: H1=> H1 H2.\napply/andP; rewrite /in_mem /=; split.\nby apply: H2; left.\nby rewrite H; split=> //; move=> mu0 H3; apply: H2; right.\nQed.\n\nLemma join_all_extBlocksTgt mu mus b :\n  extBlocksTgt (join_all mu mus) b\n  <-> extBlocksTgt mu b\n      /\\ (forall mu0, List.In mu0 mus -> extBlocksTgt mu0 b).\nProof.\nelim: mus mu=> //=; split=> H1; first by split.\nby case: H1=> //; move=> []? [].\ncase: (andP H1); rewrite /in_mem /= => H2; rewrite H; case=> H3 H4.\nsplit=> //; move=> mu0; case; first by move=> <-.\nby move=> H5; apply: (H4 _ H5).\ncase: H1=> H1 H2.\napply/andP; rewrite /in_mem /=; split.\nby apply: H2; left.\nby rewrite H; split=> //; move=> mu0 H3; apply: H2; right.\nQed.\n\nLemma join_all_frgnBlocksTgt mu mus b :\n  frgnBlocksTgt (join_all mu mus) b\n  <-> frgnBlocksTgt mu b\n      /\\ (forall mu0, List.In mu0 mus -> frgnBlocksTgt mu0 b).\nProof.\nelim: mus mu=> //=; split=> H1; first by split.\nby case: H1=> //; move=> []? [].\ncase: (andP H1); rewrite /in_mem /= => H2; rewrite H; case=> H3 H4.\nsplit=> //; move=> mu0; case; first by move=> <-.\nby move=> H5; apply: (H4 _ H5).\ncase: H1=> H1 H2.\napply/andP; rewrite /in_mem /=; split.\nby apply: H2; left.\nby rewrite H; split=> //; move=> mu0 H3; apply: H2; right.\nQed.\n\nLemma join_all_local_of (mu mu0 : Inj.t) mus :\n  AllDisjoint locBlocksSrc [seq Inj.mu x | x <- [:: mu, mu0 & mus]] ->\n  local_of (join_all mu [:: mu0 & mus])\n  = join (local_of mu) (local_of (join_all mu0 mus)).\nProof.\nelim: mus mu0 mu=> //=.\nmove=> mu0 mu /= D; rewrite join_com=> //.\nmove: D=> /=; case=> /=; case.\nby move/DisjointLS_disjoint; rewrite disjoint_com.\nmove=> a mus' IH mu0 mu /= D.\nsymmetry.\nrewrite join_assoc.\nrewrite (join_com (local_of mu)).\nrewrite -join_assoc.\nrewrite -(IH mu0 mu).\nrewrite join_assoc.\nrewrite (join_com (local_of a)).\nby rewrite -join_assoc.\ncase: D=> /= [][]_ []_ H [][]; move/DisjointLS_disjoint.\nby rewrite disjoint_com.\ncase: D=> /= [][]H1 []H2 H3 [][]H4 H5 []H6 H7.\nby split=> //.\ncase: D=> /= [][]H1 []H2 H3 [][]H4 H5 []H6 H7.\nby apply: (DisjointLS_disjoint H2).\nQed.\n\nLemma DisjointLS_local_of_contra (mu mu' : Inj.t) b b' d' b'' d'' :\n  local_of mu b = Some (b',d') ->\n  local_of mu' b = Some (b'',d'') ->\n  DisjointLS mu mu' ->\n  False.\nProof.\nby move=> L1 L2; move/DisjointLS_disjoint; move/(_ b); rewrite L1 L2; case.\nQed.\n\nSection join_all_shift.\n\nVariables mu0 mu1 mu_trash : Inj.t.\n\nVariable mus : seq Inj.t.\n\nLet mu_trash'' := join_sm mu0 mu_trash.\n\nVariable mu_trash''_wd : SM_wd mu_trash''.\n\nLet mu_trash' := Inj.mk mu_trash''_wd.\n\nLemma join_all_shift_locBlocksSrcE :\n  locBlocksSrc (join_all mu_trash' mus)\n  = [predU (locBlocksSrc mu0)\n    & locBlocksSrc (join_all mu_trash mus)].\nProof.\nrewrite /= /predU; f_equal; extensionality b; rewrite /in_mem /= /in_mem /=.\ncase lOf0: (locBlocksSrc mu0)=> /=.\nhave H: locBlocksSrc (join_all mu_trash' mus) b.\n{ rewrite join_all_locBlocksSrc; left; rewrite /mu_trash' /=.\n  by apply/orP; rewrite /in_mem /=; left. }\nby [].\nhave H:\n      is_true (locBlocksSrc (join_all mu_trash mus) b)\n  <-> is_true (locBlocksSrc (join_all mu_trash' mus) b).\n{ by rewrite 2!join_all_locBlocksSrc /mu_trash' /= /in_mem /= lOf0. }\nhave H2:\n    locBlocksSrc (join_all mu_trash mus) b\n  = locBlocksSrc (join_all mu_trash' mus) b.\n{ move: H; case: (locBlocksSrc (join_all mu_trash mus) b).\n  by case=> H1 H2; rewrite H1.\n  case: (locBlocksSrc (join_all mu_trash' mus) b)=> //.\n  by case=> //_; move/(_ erefl). }\nby rewrite H2.\nQed.\n\nLemma join_all_shift_locBlocksSrc :\n    [predU (locBlocksSrc mu0)\n    & locBlocksSrc (join_all mu_trash [:: mu1 & mus])]\n  = [predU (locBlocksSrc mu1)\n    & locBlocksSrc (join_all mu_trash' mus)].\nProof.\nrewrite join_all_shift_locBlocksSrcE /=.\nby rewrite predUA predUC -predUA.\nQed.\n\nLemma join_all_shift_locBlocksTgtE :\n  locBlocksTgt (join_all mu_trash' mus)\n  = [predU (locBlocksTgt mu0)\n    & locBlocksTgt (join_all mu_trash mus)].\nProof.\nrewrite /= /predU; f_equal; extensionality b; rewrite /in_mem /= /in_mem /=.\ncase lOf0: (locBlocksTgt mu0)=> /=.\nhave H: locBlocksTgt (join_all mu_trash' mus) b.\n{ rewrite join_all_locBlocksTgt; left; rewrite /mu_trash' /=.\n  by apply/orP; rewrite /in_mem /=; left. }\nby [].\nhave H:\n      is_true (locBlocksTgt (join_all mu_trash mus) b)\n  <-> is_true (locBlocksTgt (join_all mu_trash' mus) b).\n{ by rewrite 2!join_all_locBlocksTgt /mu_trash' /= /in_mem /= lOf0. }\nhave H2:\n    locBlocksTgt (join_all mu_trash mus) b\n  = locBlocksTgt (join_all mu_trash' mus) b.\n{ move: H; case: (locBlocksTgt (join_all mu_trash mus) b).\n  by case=> H1 H2; rewrite H1.\n  case: (locBlocksTgt (join_all mu_trash' mus) b)=> //.\n  by case=> //_; move/(_ erefl). }\nby rewrite H2.\nQed.\n\nLemma join_all_shift_locBlocksTgt :\n    [predU (locBlocksTgt mu0)\n    & locBlocksTgt (join_all mu_trash [:: mu1 & mus])]\n  = [predU (locBlocksTgt mu1)\n    & locBlocksTgt (join_all mu_trash' mus)].\nProof.\nrewrite join_all_shift_locBlocksTgtE /=.\nby rewrite predUA predUC -predUA.\nQed.\n\nLemma join_all_shift_extBlocksSrcE :\n  extBlocksSrc (join_all mu_trash' mus)\n  = [predI (extBlocksSrc mu0)\n    & extBlocksSrc (join_all mu_trash mus)].\nProof.\nrewrite /= /predI; f_equal; extensionality b; rewrite /in_mem /= /in_mem /=.\ncase eOf0: (extBlocksSrc mu0)=> /=.\ncut (extBlocksSrc (join_all mu_trash mus) b\n <-> extBlocksSrc (join_all mu_trash' mus) b).\ncase: (extBlocksSrc mu1 b)=> //.\ncase: (extBlocksSrc _ _)=> //.\ncase: (extBlocksSrc _ _)=> //.\ncase. by move/(_ erefl). case.\ncase: (extBlocksSrc _ _)=> //.\ncase: (extBlocksSrc _ _)=> //.\nby move=> _; move/(_ erefl).\nby move=> _; move/(_ erefl).\ncase.\ncase: (extBlocksSrc _ _)=> //.\ncase: (extBlocksSrc _ _)=> //.\nby move/(_ erefl).\ncase: (extBlocksSrc _ _)=> //.\ncase: (extBlocksSrc _ _)=> //.\nby move=> _; move/(_ erefl).\nby move=> _; move/(_ erefl).\nrewrite 2!join_all_extBlocksSrc.\nhave H: (extBlocksSrc mu_trash b = extBlocksSrc mu_trash' b).\n{ by rewrite /mu_trash' /= /in_mem /= eOf0. }\nby rewrite -H.\ncut (false\n <-> extBlocksSrc (join_all mu_trash' mus) b).\ncase: (extBlocksSrc _ _)=> //.\nby case=> _; move/(_ erefl).\nrewrite join_all_extBlocksSrc /mu_trash' /= /in_mem /= eOf0 /=.\nby split=> //; last by case.\nQed.\n\nLemma join_all_shift_extBlocksSrc :\n    [predI (extBlocksSrc mu0)\n    & extBlocksSrc (join_all mu_trash [:: mu1 & mus])]\n  = [predI (extBlocksSrc mu1)\n    & extBlocksSrc (join_all mu_trash' mus)].\nProof.\nrewrite join_all_shift_extBlocksSrcE /=.\nby rewrite predIA predIC -predIA.\nQed.\n\nLemma join_all_shift_frgnBlocksSrcE :\n  frgnBlocksSrc (join_all mu_trash' mus)\n  = [predI (frgnBlocksSrc mu0)\n    & frgnBlocksSrc (join_all mu_trash mus)].\nProof.\nrewrite /= /predI; f_equal; extensionality b; rewrite /in_mem /= /in_mem /=.\ncase eOf0: (frgnBlocksSrc mu0)=> /=.\ncut (frgnBlocksSrc (join_all mu_trash mus) b\n <-> frgnBlocksSrc (join_all mu_trash' mus) b).\ncase: (frgnBlocksSrc mu1 b)=> //.\ncase: (frgnBlocksSrc _ _)=> //.\ncase: (frgnBlocksSrc _ _)=> //.\ncase. by move/(_ erefl). case.\ncase: (frgnBlocksSrc _ _)=> //.\ncase: (frgnBlocksSrc _ _)=> //.\nby move=> _; move/(_ erefl).\nby move=> _; move/(_ erefl).\ncase.\ncase: (frgnBlocksSrc _ _)=> //.\ncase: (frgnBlocksSrc _ _)=> //.\nby move/(_ erefl).\ncase: (frgnBlocksSrc _ _)=> //.\ncase: (frgnBlocksSrc _ _)=> //.\nby move=> _; move/(_ erefl).\nby move=> _; move/(_ erefl).\nrewrite 2!join_all_frgnBlocksSrc.\nhave H: (frgnBlocksSrc mu_trash b = frgnBlocksSrc mu_trash' b).\n{ by rewrite /mu_trash' /= /in_mem /= eOf0. }\nby rewrite -H.\ncut (false\n <-> frgnBlocksSrc (join_all mu_trash' mus) b).\ncase: (frgnBlocksSrc _ _)=> //.\nby case=> _; move/(_ erefl).\nrewrite join_all_frgnBlocksSrc /mu_trash' /= /in_mem /= eOf0 /=.\nby split=> //; last by case.\nQed.\n\nLemma join_all_shift_extBlocksTgtE :\n  extBlocksTgt (join_all mu_trash' mus)\n  = [predI (extBlocksTgt mu0)\n    & extBlocksTgt (join_all mu_trash mus)].\nProof.\nrewrite /= /predI; f_equal; extensionality b; rewrite /in_mem /= /in_mem /=.\ncase eOf0: (extBlocksTgt mu0)=> /=.\ncut (extBlocksTgt (join_all mu_trash mus) b\n <-> extBlocksTgt (join_all mu_trash' mus) b).\ncase: (extBlocksTgt mu1 b)=> //.\ncase: (extBlocksTgt _ _)=> //.\ncase: (extBlocksTgt _ _)=> //.\ncase. by move/(_ erefl). case.\ncase: (extBlocksTgt _ _)=> //.\ncase: (extBlocksTgt _ _)=> //.\nby move=> _; move/(_ erefl).\nby move=> _; move/(_ erefl).\ncase.\ncase: (extBlocksTgt _ _)=> //.\ncase: (extBlocksTgt _ _)=> //.\nby move/(_ erefl).\ncase: (extBlocksTgt _ _)=> //.\ncase: (extBlocksTgt _ _)=> //.\nby move=> _; move/(_ erefl).\nby move=> _; move/(_ erefl).\nrewrite 2!join_all_extBlocksTgt.\nhave H: (extBlocksTgt mu_trash b = extBlocksTgt mu_trash' b).\n{ by rewrite /mu_trash' /= /in_mem /= eOf0. }\nby rewrite -H.\ncut (false\n <-> extBlocksTgt (join_all mu_trash' mus) b).\ncase: (extBlocksTgt _ _)=> //.\nby case=> _; move/(_ erefl).\nrewrite join_all_extBlocksTgt /mu_trash' /= /in_mem /= eOf0 /=.\nby split=> //; last by case.\nQed.\n\nLemma join_all_shift_extBlocksTgt :\n    [predI (extBlocksTgt mu0)\n    & extBlocksTgt (join_all mu_trash [:: mu1 & mus])]\n  = [predI (extBlocksTgt mu1)\n    & extBlocksTgt (join_all mu_trash' mus)].\nProof.\nrewrite join_all_shift_extBlocksTgtE /=.\nby rewrite predIA predIC -predIA.\nQed.\n\nLemma join_all_shift_frgnBlocksTgtE :\n  frgnBlocksTgt (join_all mu_trash' mus)\n  = [predI (frgnBlocksTgt mu0)\n    & frgnBlocksTgt (join_all mu_trash mus)].\nProof.\nrewrite /= /predI; f_equal; extensionality b; rewrite /in_mem /= /in_mem /=.\ncase eOf0: (frgnBlocksTgt mu0)=> /=.\ncut (frgnBlocksTgt (join_all mu_trash mus) b\n <-> frgnBlocksTgt (join_all mu_trash' mus) b).\ncase: (frgnBlocksTgt mu1 b)=> //.\ncase: (frgnBlocksTgt _ _)=> //.\ncase: (frgnBlocksTgt _ _)=> //.\ncase. by move/(_ erefl). case.\ncase: (frgnBlocksTgt _ _)=> //.\ncase: (frgnBlocksTgt _ _)=> //.\nby move=> _; move/(_ erefl).\nby move=> _; move/(_ erefl).\ncase.\ncase: (frgnBlocksTgt _ _)=> //.\ncase: (frgnBlocksTgt _ _)=> //.\nby move/(_ erefl).\ncase: (frgnBlocksTgt _ _)=> //.\ncase: (frgnBlocksTgt _ _)=> //.\nby move=> _; move/(_ erefl).\nby move=> _; move/(_ erefl).\nrewrite 2!join_all_frgnBlocksTgt.\nhave H: (frgnBlocksTgt mu_trash b = frgnBlocksTgt mu_trash' b).\n{ by rewrite /mu_trash' /= /in_mem /= eOf0. }\nby rewrite -H.\ncut (false\n <-> frgnBlocksTgt (join_all mu_trash' mus) b).\ncase: (frgnBlocksTgt _ _)=> //.\nby case=> _; move/(_ erefl).\nrewrite join_all_frgnBlocksTgt /mu_trash' /= /in_mem /= eOf0 /=.\nby split=> //; last by case.\nQed.\n\nLemma join_all_shift_local_ofE :\n  All (fun mu1 => DisjointLS mu0 mu1) [seq Inj.mu x | x <- mus] ->\n  local_of (join_all mu_trash' mus)\n  = join (local_of mu0) (local_of (join_all mu_trash mus)).\nProof.\nmove=> D; elim: mus D=> // a mus' IH /= []D E.\nrewrite IH // join_assoc (join_com (local_of a)).\nby rewrite -join_assoc.\nby rewrite disjoint_com; apply: DisjointLS_disjoint D.\nQed.\n\nLemma join_all_shift_local_of :\n  AllDisjoint locBlocksSrc [seq Inj.mu x | x <- [:: mu_trash, mu0, mu1 & mus]] ->\n    join (local_of mu0) (local_of (join_all mu_trash [:: mu1 & mus]))\n  = join (local_of mu1) (local_of (join_all mu_trash' mus)).\nProof.\nmove=> D; rewrite /join join_all_local_of=> //.\nextensionality b.\ncase lOf0: (local_of mu0 b)=> [[x y]|].\ncase lOf1: (local_of mu1 b)=> [[x' y']|].\nelimtype False; apply: (DisjointLS_local_of_contra lOf0 lOf1).\nby case: D=> /= [][]H1 []H2 H3 [][]H4 H5 []H6 H7.\nelim: mus D=> //=.\nby rewrite /join lOf0.\nmove=> a mus' IH D; rewrite /join.\ncase lOfa: (local_of a b)=> [[x' y']|].\nelimtype False; apply: (DisjointLS_local_of_contra lOf0 lOfa).\nby case: D=> /= [][]H1 []H2 H3 [][]H4 []H5.\napply: IH.\ncase: D=> /= [][]H1 []H2 []H3 H4 [][]H5 []H6 H7 [][]H8 H9 []H10 H11.\nby split.\nrewrite /join.\ncase lOf1: (local_of mu1 b)=> [[x y]|].\ncase lOftr: (local_of mu_trash b)=> [[x' y']|].\nelimtype False; apply: (DisjointLS_local_of_contra lOf1 lOftr).\nby case: D=> /= [][]H1 []H2 H3 [][]H4 H5 []H6 H7; rewrite DisjointC.\nelim: mus D=> //a mus' IH D /=; rewrite /join.\ncase lOfa: (local_of a b)=> [[x' y']|].\nelimtype False; apply: (DisjointLS_local_of_contra lOf1 lOfa).\nby case: D=> /= [][]H1 []H2 []H3 H4 [][]H5 []H6 H7 [][]H8 H9 []H10 H11.\napply: IH.\nby case: D=> /= [][]H1 []H2 []H3 H4 [][]H5 []H6 H7 [][]H8 H9 []H10 H11.\ncase lOftr: (local_of mu_trash b)=> [[x y]|].\nelim: mus D; first by move=> D /=; rewrite /join lOf0 lOftr.\nmove=> a mus' IH D /=; rewrite /join.\ncase lOfa: (local_of a b)=> [[x' y']|].\nelimtype False; apply: (DisjointLS_local_of_contra lOftr lOfa).\nby case: D=> /= [][]H1 []H2 []H3 H4 [][]H5 []H6 H7 [][]H8 H9 []H10 H11.\napply: IH.\nby case: D=> /= [][]H1 []H2 []H3 H4 [][]H5 []H6 H7 [][]H8 H9 []H10 H11; split.\nelim: mus D; first by rewrite /= /join lOf0 lOf1 lOftr.\nmove=> a mus' IH D /=; rewrite /join.\ncase: (local_of a b)=> //.\napply: IH.\nby case: D=> /= [][]H1 []H2 []H3 H4 [][]H5 []H6 H7 [][]H8 H9 []H10 H11; split.\nby case: D=> /= [][]H1 []H2 H3 [][]H4 H5 []H6 H7; split.\nQed.\n\nLemma join_all_shift_extern_ofE :\n  extern_of (join_all mu_trash' mus)\n  = join2 (extern_of mu0) (extern_of (join_all mu_trash mus)).\nProof.\nelim: mus=> // a mus' IH /=.\nrewrite IH //.\nby rewrite join2A (join2C (extern_of a)) -join2A.\nQed.\n\nEnd join_all_shift.\n\nDefinition replace_externs' (mu : SM_Injection) (eSrc' eTgt' : block -> bool) :=\n  match mu with\n    | {| locBlocksSrc := locBSrc; locBlocksTgt := locBTgt; pubBlocksSrc := pSrc;\n      pubBlocksTgt := pTgt; local_of := local; frgnBlocksSrc := frgnBSrc;\n      frgnBlocksTgt := frgnBTgt; extern_of := extern |} =>\n      {| locBlocksSrc := locBSrc;\n         locBlocksTgt := locBTgt;\n         pubBlocksSrc := pSrc;\n         pubBlocksTgt := pTgt;\n         local_of := local;\n         extBlocksSrc := eSrc';\n         extBlocksTgt := eTgt';\n         frgnBlocksSrc := frgnBSrc;\n         frgnBlocksTgt := frgnBTgt;\n         extern_of := restrict extern eSrc' |}\n  end.\n\nLemma replace_externs'_locBlocksSrc mu eSrc' eTgt' :\n  locBlocksSrc (replace_externs' mu eSrc' eTgt')\n  = locBlocksSrc mu.\nProof. by case: mu. Qed.\n\nLemma replace_externs'_locBlocksTgt mu eSrc' eTgt' :\n  locBlocksTgt (replace_externs' mu eSrc' eTgt')\n  = locBlocksTgt mu.\nProof. by case: mu. Qed.\n\nLemma replace_externs'_extBlocksSrc mu eSrc' eTgt' :\n  extBlocksSrc (replace_externs' mu eSrc' eTgt')\n  = eSrc'.\nProof. by case: mu. Qed.\n\nLemma replace_externs'_extBlocksTgt mu eSrc' eTgt' :\n  extBlocksTgt (replace_externs' mu eSrc' eTgt')\n  = eTgt'.\nProof. by case: mu. Qed.\n\nLemma replace_externs'_local_of mu eSrc' eTgt' :\n  local_of (replace_externs' mu eSrc' eTgt')\n  = local_of mu.\nProof. by case: mu. Qed.\n\nLemma replace_externs'_extern_of mu eSrc' eTgt' :\n  extern_of (replace_externs' mu eSrc' eTgt')\n  = restrict (extern_of mu) eSrc'.\nProof. by case: mu. Qed.\n\nLemma replace_externs'_wd (mu : Inj.t) eSrc' eTgt' :\n  (forall b, locBlocksSrc mu b = false \\/ eSrc' b = false) ->\n  (forall b, locBlocksTgt mu b = false \\/ eTgt' b = false) ->\n  (forall b, frgnBlocksSrc mu b -> eSrc' b) ->\n  (forall b, frgnBlocksTgt mu b -> eTgt' b) ->\n  SM_wd (replace_externs' mu eSrc' eTgt').\nProof.\nmove=> H1 H2 S1 S2; apply: Build_SM_wd.\nrewrite replace_externs'_locBlocksSrc.\nby rewrite replace_externs'_extBlocksSrc.\nrewrite replace_externs'_locBlocksTgt.\nby rewrite replace_externs'_extBlocksTgt.\nrewrite replace_externs'_local_of.\nmove=> b1 b2 z lOf.\ncase: (Inj_wd mu)=> _ _ H3 _ _ _ _ _.\ncase: (H3 _ _ _ lOf).\nrewrite replace_externs'_locBlocksSrc.\nrewrite replace_externs'_locBlocksTgt.\nby move=> ? ?; split.\nrewrite replace_externs'_extern_of.\nrewrite replace_externs'_extBlocksSrc.\nrewrite replace_externs'_extBlocksTgt.\nAbort. (*FIXME*)\n\nLemma vis_restrict_sm mu X : vis (restrict_sm mu X) = vis mu.\nProof.\nby extensionality b; case: mu.\nQed.\n\nLemma sm_locally_allocated_refl mu m1 m2 :\n  sm_locally_allocated mu mu m1 m2 m1 m2.\nProof.\ncase: mu=> // ? ? ? ? ? ? ? ? ? ? /=; split=> //.\nby extensionality b; rewrite freshloc_irrefl orb_false_r.\nsplit; first by extensionality b; rewrite freshloc_irrefl orb_false_r.\nby split.\nQed.\n\nLemma inject_incr_empty j : inject_incr (fun _ => None) j.\nProof.\nby move=> b b' ofs; discriminate.\nQed.\n\nImport structured_injections.\n\nLemma sharedTgt_DomTgt (mu : Inj.t) :\n  forall b, sharedTgt mu b -> DomTgt mu b.\nProof.\nrewrite /sharedTgt /DomTgt=> b; move/orP; case.\nby move/(frgnBlocksExternTgt _ (Inj_wd _) _)=> ->; apply/orP; right.\nby move/(pubBlocksLocalTgt _ (Inj_wd _) _)=> ->; apply/orP; left.\nQed.\n\nSection getBlocks_lems.\n\nContext args1 args2 j (vinj : Val.inject_list j args1 args2).\n\nLemma getBlocks_tail v vs b :\n  getBlocks vs b ->\n  getBlocks (v :: vs) b.\nProof.\nby case: v=> //? ? ?; rewrite getBlocksD; apply/orP; right.\nQed.\n\nLemma vals_def_getBlocksTS b' :\n  vals_def args1 ->\n  getBlocks args2 b' ->\n  exists b d', [/\\ getBlocks args1 b & j b = Some (b',d')].\nProof.\nmove=> H1 H2.\nelim: args2 args1 vinj H1 H2=> //.\nmove=> a2 args2' IH args1' vinj' H1 H2.\nmove: H2 vinj' H1; rewrite getBlocksD.\ncase: args1'; first by move=> ?; inversion 1.\nmove=> a1 args1' /=; case: a2=> //.\nmove=> A; inversion 1; subst; move/andP=> []C D.\ncase: (IH _ H4 D A)=> x []y []? ?; exists x,y; split=> //.\nby apply: getBlocks_tail.\nmove=> i A; inversion 1; subst; move/andP=> []C D.\ncase: (IH _ H4 D A)=> x []y []? ?; exists x,y; split=> //.\nby apply: getBlocks_tail.\nmove=> i A; inversion 1; subst; move/andP=> []C D.\ncase: (IH _ H4 D A)=> x []y []? ?; exists x,y; split=> //.\nby apply: getBlocks_tail.\nmove=> i A; inversion 1; subst; move/andP=> []C D.\ncase: (IH _ H4 D A)=> x []y []? ?; exists x,y; split=> //.\nby apply: getBlocks_tail.\nmove=> i A; inversion 1; subst; move/andP=> []C D.\ncase: (IH _ H4 D A)=> x []y []? ?; exists x,y; split=> //.\nby apply: getBlocks_tail.\nmove=> b i; case/orP.\nmove/Coqlib.proj_sumbool_true=> eq; subst b'.\ninversion 1; subst; move/andP=> []H5 H6.\ninversion H2; subst=> //.\nexists b1,delta; split=> //.\nrewrite getBlocksD; apply/orP; left.\nby apply: Coqlib.proj_sumbool_is_true.\nmove=> A; inversion 1; subst; case/andP=> B C.\ncase: (IH _ H4 C A)=> x []y []? ?; exists x,y; split=> //.\nby apply: getBlocks_tail.\nQed.\n\nEnd getBlocks_lems.\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/join_sm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593171945416, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.29907842986423616}}
{"text": "(*\nCopyright © 2008 Russell O’Connor\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis proof and associated documentation files (the \"Proof\"), to deal in\nthe Proof without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Proof, and to permit persons to whom the Proof is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Proof.\n\nTHE PROOF IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE PROOF OR THE USE OR OTHER DEALINGS IN THE PROOF.\n*)\nRequire Import CoRN.algebra.RSetoid.\nRequire Import CoRN.metric2.Metric.\nRequire Import CoRN.metric2.UniformContinuity.\nRequire Export CoRN.reals.fast.RasterQ.\nRequire Import CoRN.reals.fast.Interval.\nRequire Import CoRN.logic.Classic.\nRequire Import CoRN.model.totalorder.QposMinMax.\nRequire Import Coq.QArith.Qabs.\nRequire Import Coq.QArith.Qround.\n\nLocal Open Scope Q_scope.\n\nSet Implicit Arguments.\n\n(**\n** Rasterization\nRasterization takes finite enumeration of points in [Q2] and moves them\naround a little so that they lie on a raster.  Thus rasterization produces\na raster object that when interpreted as a finite enumeration of [Q2] is\nclose to the original enumeration of points.  How close depends on how\nfine a raster is chosen.\n\nThere is a choice as to how to treat points that lie outside of the bound\nof a chosen rectangle for rasterization.  In this implemenation I choose\nto push all points inside the raster.  In typical applications a rectangle\nis chosen that contains all the points, so that this doesn't matter. *)\n\n(* [Rasterize Point] adds a single point [p] into a raster.\nThe raster is inside the rectanle t l b r, meaning top, left, bottom and right.\nIt has n points horizontally and m points vertically. The indexes (0,0)\ncorrespond to the point (l,t) ie the top left corner. That yields the correct\nprinting order of the raster, which is a vector of lines. *)\nDefinition rasterize2 (n m:positive) (t l b r:Q) (p:Q*Q) : Z*Z\n  := pair (Zpos m -1 - (Z.min (Zpos m -1) (Z.max 0 (rasterize1 b t m (snd p)))))%Z\n          (Z.min (Zpos n -1) (Z.max 0 (rasterize1 l r n (fst p)))).\n           \nLemma rasterize2_bound :\n  forall n z, (0 <= Z.min (Zpos n -1) (Z.max 0 z) < Zpos n)%Z.\nProof.\n  split.\n  - apply Z.min_case.\n    apply Z.le_0_sub, Pos.le_1_l.\n    apply Z.le_max_l.\n  - apply (Z.le_lt_trans _ _ _ (Z.le_min_l _ _)).\n    rewrite <- (Z.add_0_r (Z.pos n)) at 2.\n    apply Z.add_lt_mono_l. reflexivity.\nQed. \n\nLemma rasterize1_origin : forall l r n, rasterize1 l r n l = 0%Z.\nProof.\n  intros.\n  unfold rasterize1.\n  unfold Qminus.\n  rewrite Qplus_opp_r, Qmult_0_r.\n  unfold Qdiv. rewrite Qmult_0_l.\n  reflexivity.\nQed.\n\nLemma rasterize2_origin\n  : forall n m (t l b r : Q),\n    b < t -> rasterize2 n m t l b r (pair l t) = pair 0%Z 0%Z.\nProof.\n  assert (forall n:positive, 0 <= Zpos n -1)%Z.\n  { intro n.\n    change 0%Z with (1-1)%Z.\n    apply Z.add_le_mono_r.\n    apply Pos.le_1_l. }\n  intros. unfold rasterize2, fst, snd.\n  rewrite rasterize1_origin.\n  replace (rasterize1 b t m t) with (Zpos m)%Z.\n  change (Z.max 0 0) with 0%Z.\n  rewrite Z.max_r. 2: discriminate.\n  rewrite Z.min_l.\n  rewrite Z.min_r.\n  rewrite Z.sub_diag. reflexivity.\n  apply H.\n  rewrite <- (Z.add_0_r (Zpos m)) at 2.\n  apply Z.add_le_mono_l. discriminate.\n  unfold rasterize1.\n  unfold Qdiv.\n  rewrite <- Qmult_assoc, Qmult_inv_r, Qmult_1_r.\n  rewrite Qfloor_Z. reflexivity.\n  intro abs. apply Qlt_minus_iff in H0.\n  unfold Qminus in abs. rewrite abs in H0.\n  exact (Qlt_irrefl 0 H0).\nQed.\n\n(* Adding a point to a raster preserves all the points that were\n   already in it. *)\nLemma setRaster_carry : forall l r n m (bm:raster n m) i j,\n    raster_well_formed bm\n    -> Is_true (RasterIndex bm i j)\n    -> Is_true (RasterIndex (setRaster bm true l r) i j).\nProof.\n intros l r m n bm i j rWf H.\n destruct (le_lt_dec (Pos.to_nat n) l).\n  rewrite setRaster_overflow; auto.\n destruct (le_lt_dec (Pos.to_nat m) r).\n  rewrite setRaster_overflow; auto.\n destruct (eq_nat_dec i l).\n  destruct (eq_nat_dec j r).\n   rewrite e, e0.\n   rewrite setRaster_correct1; try constructor; congruence.\n  rewrite setRaster_correct2; auto.\n rewrite setRaster_correct2; auto.\nQed.\n\nLemma setRaster_uncarry : forall n m (r:raster n m) i j ax ay,\n    raster_well_formed r\n    -> Is_true (RasterIndex (setRaster r true ax ay) i j)\n    -> (Is_true (RasterIndex r i j) \\/ (ax, ay) = (i,j)).\nProof.\n  intros.\n  destruct (Nat.eq_dec ax i).\n  - destruct (Nat.eq_dec ay j).\n    right. f_equal; assumption.\n    left.\n    rewrite (setRaster_correct2 r) in H0.\n    exact H0. exact H.\n    right. intro abs. subst j. contradiction.\n  - left.\n    rewrite (setRaster_correct2 r) in H0.\n    exact H0. exact H.\n    left. intro abs. subst i. contradiction.\nQed.\n\n(* Sparse rasters are faster than boolean matrices when the number of\n   points to plot is small with respect to the total number of pixels.\n   Each lit pixel of a sparse raster stores 2 positive numbers. For\n   a 1000x1000 image that's 20 allocations per pixel instead of 1\n   allocation for boolean matrices. *)\nVariant sparse_raster (columns lines : positive) : Set :=\n| sparse_raster_data : list (Z*Z) -> sparse_raster columns lines. \n\n(** This function is slow to compute in Coq.\n    It is faster to plot a sparse raster with DumpGrayMap. *)\nDefinition PixelizeQ2 {columns lines:positive} (points:sparse_raster columns lines)\n  : raster columns lines :=\n  fold_left (fun (rast:raster columns lines) (p:Z*Z)\n             => setRaster rast true (Z.to_nat (fst p)) (Z.to_nat (snd p)))\n            (let (p) := points in p)\n            (emptyRaster columns lines).\n\nDefinition RasterizeQ2 (points:list Q2) (n m:positive) (t l b r:Q)\n  : sparse_raster n m :=\n  sparse_raster_data n m (map (fun p => rasterize2 n m t l b r p) points).\n\nLemma RasterizeQ2_wf : forall points n m t l b r,\n    raster_well_formed (PixelizeQ2 (RasterizeQ2 points n m t l b r)).\nProof.\n  intros. unfold PixelizeQ2, RasterizeQ2.\n  pose proof (emptyRaster_wf n m).\n  revert H. generalize (emptyRaster n m).\n  induction points.\n  - intros. exact H.\n  - intros. simpl. apply IHpoints.\n    apply setRaster_wf, H.\nQed.\n\nLemma RasterizeQ2_in : forall points (i j : Z) n m (r:raster n m),\n    In (i,j) points\n    -> raster_well_formed r\n    -> (Z.to_nat i < Pos.to_nat m)%nat\n    -> (Z.to_nat j < Pos.to_nat n)%nat\n    -> Is_true (RasterIndex\n                 (fold_left (fun (rast:raster n m) (p:Z*Z)\n                 => setRaster rast true (Z.to_nat (fst p)) (Z.to_nat (snd p)))\n                points r)\n                 (Z.to_nat i) (Z.to_nat j)).\nProof.\n  assert (forall points i j n m (r:raster n m),\n    Is_true (RasterIndex r (Z.to_nat i) (Z.to_nat j))\n    -> raster_well_formed r\n    -> Is_true (RasterIndex\n                 (fold_left (fun (rast:raster n m) (p:Z*Z)\n                 => setRaster rast true (Z.to_nat (fst p)) (Z.to_nat (snd p)))\n                points r)\n                 (Z.to_nat i) (Z.to_nat j))).\n  { induction points.\n    - intros. exact H.\n    - intros. simpl. apply IHpoints.\n      apply setRaster_carry. exact H0. exact H.\n      apply setRaster_wf, H0. }\n  induction points.\n  - intros. exfalso. inversion H0.\n  - intros. simpl. destruct H0.\n    + subst a. simpl.\n      apply H. apply Is_true_eq_left, setRaster_correct1.\n      exact H1. exact H2. exact H3.\n      apply setRaster_wf, H1.\n    + apply IHpoints. exact H0.\n      apply setRaster_wf, H1.\n      exact H2. exact H3.\nQed.\n\nLemma RasterizeQ2_in_recip : forall (points : list (Z*Z)) (i j : nat) n m (r:raster n m),\n    raster_well_formed r\n    -> Is_true (RasterIndex\n                 (fold_left (fun (rast:raster n m) (p:Z*Z)\n                 => setRaster rast true (Z.to_nat (fst p)) (Z.to_nat (snd p)))\n                points r) i j)\n    -> (In (i, j) (map (fun p => (Z.to_nat (fst p), Z.to_nat (snd p))) points)\n       \\/ Is_true (RasterIndex r i j)).\nProof.\n  induction points as [|[ax ay] points].\n  - intros. right. exact H0.\n  - intros. simpl in H0.\n    destruct (RasterIndex r i j) eqn:des.\n    right. reflexivity. left.\n    destruct (IHpoints i j n m\n                         (setRaster r true (Z.to_nat ax) (Z.to_nat ay)) ).\n    apply setRaster_wf, H.\n    exact H0.\n    right. exact H1.\n    destruct (Nat.eq_dec (Z.to_nat ax) i).\n    + destruct (Nat.eq_dec (Z.to_nat ay) j). \n      left. f_equal; assumption.\n      exfalso. apply setRaster_uncarry in H1.\n      destruct H1. unfold Is_true in H1.\n      rewrite des in H1. contradiction.\n      inversion H1. contradiction. exact H.\n    + exfalso. apply setRaster_uncarry in H1.\n      destruct H1. unfold Is_true in H1.\n      rewrite des in H1. contradiction.\n      inversion H1. contradiction. exact H.\nQed. \n\nLemma InFinEnumC_Qepsilon : forall (x y : Q) points,\n    @InFinEnumC (ProductMS _ _) (x,y) points\n    -> exists q, In q points /\\ msp_eq q (x,y).\nProof.\n  intros. induction points as [|[i j] points].\n  - exfalso. unfold InFinEnumC, FinSubset_ball in H.\n    contradict H; intros [z [H _]]. inversion H.\n  - destruct (Qeq_dec x i).\n    + destruct (Qeq_dec y j).\n      exists (i,j). split. left. reflexivity.\n      split; apply Qball_0; symmetry; assumption.\n      destruct IHpoints. \n      intro abs.\n      unfold InFinEnumC, FinSubset_ball in H.\n      contradict H; intros [z [zin H0]].\n      destruct zin. subst z.\n      destruct H0. simpl in H0.\n      apply Qball_0 in H0. contradiction.\n      contradict abs. exists z. split.\n      exact H. exact H0.\n      exists x0. split. right. apply H0. apply H0.\n    + destruct IHpoints.\n      intro abs.\n      unfold InFinEnumC, FinSubset_ball in H.\n      contradict H; intros [z [zin H0]].\n      destruct zin. subst z.\n      destruct H0. simpl in H.\n      apply Qball_0 in H. contradiction.\n      contradict abs. exists z. split.\n      exact H. exact H0.\n      exists x0. split. right. apply H0. apply H0.\nQed.\n\n(* end hide *)\nSection RasterizeCorrect.\n\n(* Middles of the horizontal subdivision of the segment [[l, r]].\nInstead of l, l + (r-l)/n, ...\nit is l + (r-l)/2n, l + (r-l)*3/2n, ... *)\nLet C : Q -> Q -> positive -> Z -> Q\n  := fun l r (n:positive) (i:Z) => l + (r - l) * (2 * i + 1 # 1) / (2 * Z.pos n # 1).\n\n(* rasterize1 is used in both horizontally and vertically,\n   so it will be called for left,width and also for bottom,height. *)\nLemma rasterize1_error : forall l (w:Qpos) n x,\n(l <= x <= l + proj1_sig w) ->\nQball ((1 #2*n) * proj1_sig w)\n      (C l (l + proj1_sig w) n (Z.min (Z.pos n -1)\n                  (Z.max 0 (rasterize1 l (l+proj1_sig w) n x))))\n      x.\nProof.\n clear - C.\n intros l w n x H0.\n destruct (Qlt_le_dec x (l+proj1_sig w)).\n - replace (Z.min (Z.pos n -1)\n          (Z.max 0 (rasterize1 l (l + proj1_sig w) n x)))\n    with (rasterize1 l (l + proj1_sig w) n x).\n   + apply ball_sym.\n   simpl.\n   rewrite -> Qball_Qabs.\n   assert (l < l + proj1_sig w).\n   { rewrite -> Qlt_minus_iff.\n    ring_simplify.\n    exact (Qpos_ispos w). }\n   eapply Qle_trans.\n    unfold C.\n    apply (rasterize1_close H).\n    setoid_replace (l + proj1_sig w - l) with (proj1_sig w) \n     by (unfold canonical_names.equiv, stdlib_rationals.Q_eq; simpl; ring).\n    unfold Qdiv. rewrite Qmult_comm.\n    apply Qmult_le_compat_r. apply Qle_refl.\n    apply Qpos_nonneg.\n   + rewrite Z.max_r.\n   apply Z.min_case_strong.\n    intros H.\n    apply Zle_antisym; auto.\n    apply Zlt_succ_le.\n    rewrite <- Z.add_1_r.\n    replace (Z.pos n - 1 + 1)%Z with (Z.pos n) by ring.\n    apply rasterize1_boundR; auto.\n    rewrite -> Qle_minus_iff.\n    ring_simplify.\n    exact (Qpos_nonneg w).\n   reflexivity.\n  destruct H0.\n  apply rasterize1_boundL; auto.\n  apply Qle_trans with x; auto.\n - rewrite Z.min_l.\n  setoid_replace x with (l + proj1_sig w).\n   apply ball_sym.\n   rewrite ->  Qball_Qabs.\n   unfold C.\n   rewrite <- (Qmult_comm (proj1_sig w)).\n   change (1 # 2*n) with (/((2#1)*inject_Z (Z.pos n))).\n   change (2*Z.pos n #1) with ((2#1)*inject_Z (Z.pos n)).\n   replace (2 * (Z.pos n - 1) + 1)%Z with (2*Z.pos n + - 1)%Z by ring.\n   change (2*Z.pos n + -1#1) with (inject_Z (2*Z.pos n + - 1)).\n   rewrite -> Q.Zplus_Qplus.\n   rewrite -> Q.Zmult_Qmult.\n   change (inject_Z 2) with (2#1).\n   change (inject_Z (-1)) with (-1#1)%Q.\n   setoid_replace (l + proj1_sig w - (l + (l + proj1_sig w - l) * ((2#1) * inject_Z (Z.pos n) + (-1#1)) / ((2#1) * (inject_Z (Z.pos n)))))\n     with ((proj1_sig w / ((2#1) * (inject_Z (Z.pos n)))))\n     by (unfold canonical_names.equiv, stdlib_rationals.Q_eq; simpl; field; unfold Qeq; simpl; auto with *).\n   rewrite -> Qabs_pos;[apply Qle_refl|].\n   apply Qle_shift_div_l.\n   rewrite <- (Qmult_0_r (2#1)). apply Qmult_lt_l. reflexivity.\n   simpl; auto with *; unfold Qlt; simpl; auto with *.\n   rewrite Qmult_0_l.\n   exact (Qpos_nonneg w).\n  destruct H0.\n  apply Qle_antisym; auto.\n eapply Z.le_trans;[|apply Z.le_max_r].\n unfold rasterize1.\n rewrite <- (Qfloor_Z (Z.pos n -1)).\n apply Qfloor_resp_le.\n setoid_replace x with (l+proj1_sig w).\n setoid_replace (l + proj1_sig w - l) with (proj1_sig w)\n   by (unfold canonical_names.equiv, stdlib_rationals.Q_eq; simpl; ring).\n unfold Qdiv.\n rewrite <- Qmult_assoc, Qmult_inv_r, Qmult_1_r.\n 2: apply Qpos_nonzero.\n rewrite <- Zle_Qle.\n rewrite <- (Z.add_0_r (Z.pos n)) at 2.\n apply Z.add_le_mono_l. discriminate.\n  apply Qle_antisym.\n  apply H0. exact q.\nQed.\n\n(* Strange, we should always have b <= t in rasterize1. *)\nLemma switch_line_interp : forall (t b : Q) (m : positive) (j : Z),\n     (j < Z.pos m)%Z\n     -> C t b m (Z.pos m - 1- j) == C b t m j.\nProof.\n intros t b m j H.\n unfold C.\n replace (2 * (Z.pos m -1 - j) + 1)%Z with (2 * (Z.pos m - j) - 1)%Z by ring.\n change (2 * (Z.pos m - j) - 1 # 1)\n   with (inject_Z (2 * (Z.pos m - j) + - 1)%Z).\n change (2*Z.pos m#1) with ((2#1)*inject_Z (Z.pos m)).\n change ((2*j +1)#1) with (inject_Z (2*j+1)%Z).\n do 2 rewrite -> Q.Zplus_Qplus.\n rewrite -> Q.Zmult_Qmult.\n change (inject_Z (-1)) with (-1#1).\n rewrite -> Q.Zmult_Qmult.\n change (inject_Z 2) with (2#1).\n unfold Zminus.\n rewrite -> Q.Zplus_Qplus.\n change (inject_Z (-j)) with (-inject_Z j).\n field.\n apply Q.positive_nonzero_in_Q.\nQed.\n\nVariable b l:Q.\nVariable w h:Qpos.\n\nLet r:=l+proj1_sig w.\nLet t:=b+proj1_sig h.\n\nVariable points:FinEnum Q2.\n\nVariable n m : positive.\n\nLet errX : Qpos := ((1#2*n)*w)%Qpos.\nLet errY : Qpos := ((1#2*m)*h)%Qpos.\nLet err : Qpos := Qpos_max errX errY.\n\nHypothesis Hf : forall (x y : Q), InFinEnumC ((x,y):ProductMS _ _) points ->\n (l<= x <= r) /\\ (b <= y <= t).\n\n \n(** The Rasterization is close to the original enumeration,\nie each one is approximately included in the other,\nwithin error err (Hausdorff distance).\nTo measure closeness, we use the product metric on Q2, which has\nsquare balls aligned with the 2 axes. *)\nLemma RasterizeQ2_correct1 : forall (x y:Q),\n    @InFinEnumC (ProductMS _ _) (x,y) points ->\n    exists p, In p (CentersOfPixels (PixelizeQ2 (RasterizeQ2 points n m t l b r))\n                               (l,t) (r,b))\n         /\\ ball (proj1_sig err) p (x,y).\nProof.\n  intros x y H.\n  pose proof (Hf H) as xybound.\n  apply InFinEnumC_Qepsilon in H.\n  destruct H as [q [H H0]].\n  assert (let (i,j) := rasterize2 n m t l b r q in\n          Is_true (RasterIndex (PixelizeQ2 (RasterizeQ2 points n m t l b r))\n                               (Z.to_nat i) (Z.to_nat j))).\n  { apply RasterizeQ2_in.\n    apply (in_map (fun p : Q * Q => rasterize2 n m t l b r p) points).\n    exact H. apply emptyRaster_wf.\n    apply Nat2Z.inj_lt.\n    rewrite positive_nat_Z, Z2Nat.id.\n    apply Z.lt_0_sub. ring_simplify.\n    apply (Z.lt_le_trans _ (0+1)).\n    reflexivity.\n    apply Z.add_le_mono_r.\n    apply rasterize2_bound.\n    apply Z.le_0_sub. apply Z.le_min_l.\n    apply Nat2Z.inj_lt.\n    rewrite positive_nat_Z, Z2Nat.id.\n    apply rasterize2_bound. \n    apply rasterize2_bound. }\n  pose (Z.pos m - 1 - Z.min (Z.pos m - 1) (Z.max 0 (rasterize1 b t m (snd q))))%Z\n    as i.\n  pose (Z.min (Z.pos n - 1) (Z.max 0 (rasterize1 l r n (fst q)))) as j.\n  exists ((fun (l r : Q) (n : positive) (i : Z) =>\n           l + (r - l) * (2 * i + 1 # 1) / (2 * Z.pos n # 1)) l r n\n            (Z.of_nat (Z.to_nat j)),\n         (fun (l r : Q) (n : positive) (i : Z) =>\n          l + (r - l) * (2 * i + 1 # 1) / (2 * Z.pos n # 1)) t b m\n           (Z.of_nat (Z.to_nat i))).\n  split. apply InterpRaster_correct1.\n  apply RasterizeQ2_wf. exact H1.\n  rewrite Z2Nat.id.\n  rewrite Z2Nat.id.\n  destruct H0, q.\n  split.\n  - unfold fst. \n    destruct xybound.\n    apply Qball_0 in H0.\n    unfold fst in H0. clear H2.\n    rewrite <- H0 in H3.\n    unfold j, r. rewrite <- H0. unfold fst.\n    apply ball_weak_le with (e:=((1 # 2 * n) * proj1_sig w)).\n    apply (Qpos_max_ub_l errX errY).\n    apply (@rasterize1_error l w n _ H3).\n  - unfold snd.\n    destruct xybound.\n    apply Qball_0 in H2.\n    unfold snd in H2. clear H0.\n    rewrite <- H2 in H4.\n    unfold i, t. rewrite <- H2. unfold snd.\n    apply ball_weak_le with (e:=((1 # 2 * m) * proj1_sig h)).\n    apply (Qpos_max_ub_r errX errY).\n    pose proof (@rasterize1_error b h m _ H4).\n    rewrite <- switch_line_interp in H0.\n    apply H0.\n    apply rasterize2_bound.\n  - unfold i. apply Z.le_0_sub.\n    apply Z.le_min_l.\n  - apply rasterize2_bound.\nQed.\n\nLemma RasterizeQ2_correct2 : forall (x y : Q),\n    @InFinEnumC (ProductMS _ _) (x,y)\n                (CentersOfPixels (PixelizeQ2 (RasterizeQ2 points n m t l b r))\n                                 (l,t) (r,b))\n    -> exists p, In p points /\\ ball (proj1_sig err) p (x,y).\nProof.\n  intros x y H.\n  apply InFinEnumC_Qepsilon in H.\n  destruct H as [q [qin qeq]].\n  destruct q as [qx qy].\n  destruct (InterpRaster_correct2\n             _ _ _ _ _ _ _ (RasterizeQ2_wf points n m t l b r) qin)\n   as [[j i] [Hij [Hx' Hy']]].\n  unfold fst, snd in Hij.\n  apply RasterizeQ2_in_recip in Hij.\n  2: apply emptyRaster_wf.\n  destruct Hij.\n  2: unfold Is_true in H; rewrite (emptyRasterEmpty n m j i) in H; contradiction.\n  unfold RasterizeQ2 in H.\n  rewrite map_map in H.\n  apply In_nth with (d:=(fun x : Q * Q =>\n            (Z.to_nat (fst (rasterize2 n m t l b r x)),\n            Z.to_nat (snd (rasterize2 n m t l b r x))))(0,0)) in H.\n  destruct H as [k [kin H]].\n  rewrite map_length in kin.\n  rewrite (map_nth (fun x : Q * Q =>\n            (Z.to_nat (fst (rasterize2 n m t l b r x)),\n            Z.to_nat (snd (rasterize2 n m t l b r x))))) in H.\n  exists (nth k points (0,0)). split.\n  apply nth_In. exact kin.\n  unfold snd in Hx'.\n  unfold fst in Hy'.\n  assert (Z.to_nat (fst (rasterize2 n m t l b r (nth k points (0, 0)))) = j\n          /\\ Z.to_nat (snd (rasterize2 n m t l b r (nth k points (0, 0)))) = i).\n  { inversion H. split; reflexivity. }\n  clear H. destruct H0.\n  rewrite <- qeq. clear qeq x y.\n  specialize (@Hf (fst (nth k points (0,0))) (snd (nth k points (0,0)))). \n  rewrite <- surjective_pairing in Hf.\n  specialize (@Hf (InFinEnumC_weaken _ _ points (nth_In _ _ kin))).\n  split.\n  - unfold rasterize2, snd in H0. clear H.\n    simpl (fst (qx,qy)).\n    rewrite Hx', <- H0.\n    rewrite Z2Nat.id.\n    apply ball_weak_le with (e:=((1 # 2 * n) * proj1_sig w)).\n    apply (Qpos_max_ub_l errX errY). \n    apply ball_sym.\n    apply rasterize1_error.\n    apply Hf. apply rasterize2_bound.\n  - unfold rasterize2, fst in H. clear H0 Hx'.\n    simpl (snd (qx,qy)).\n    rewrite Hy', <- H.\n    apply ball_weak_le with (e:=((1 # 2 * m) * proj1_sig h)).\n    apply (Qpos_max_ub_r errX errY).\n    pose proof (@rasterize1_error b h m _ (proj2 Hf)).\n    rewrite <- switch_line_interp in H0.\n    apply ball_sym.\n    rewrite Z2Nat.id.\n    apply H0.\n    apply Z.le_0_sub, Z.le_min_l.\n    apply (Z.le_lt_trans _ _ _ (Z.le_min_l _ _)).\n    rewrite <- (Z.add_0_r (Z.pos m)) at 2.\n    apply Z.add_lt_mono_l. reflexivity. \nQed.\n\nLemma RasterizeQ2_correct :\n  ball (proj1_sig err)\n       (CentersOfPixels (PixelizeQ2 (RasterizeQ2 points n m t l b r)) (l,t) (r,b))\n       points.\nProof.\n  split. apply Qpos_nonneg.\n  split; intros [x y] Hx.\n  - pose proof (RasterizeQ2_correct2 Hx).\n    intro abs.\n    contradict H; intros [z [Hz0 Hz1]].\n    specialize (abs z). contradict abs.\n    split.\n    apply InFinEnumC_weaken, Hz0.\n    apply ball_sym, Hz1.\n  - intro abs.\n    pose proof (RasterizeQ2_correct1 Hx).\n    contradict H; intros [z [Hz0 Hz1]].\n    specialize (abs z). contradict abs.\n    split.\n    apply InFinEnumC_weaken, Hz0.\n    apply ball_sym, Hz1.\nQed.\n\nEnd RasterizeCorrect.\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/fast/RasterizeQ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5888891307678319, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.29904488734897294}}
{"text": "(* Uncomputablity in the definition of R function *)\n(* For convenience's sake, we focus on real numbers in [0,1] *) \n(* All definitions are copied from Coq standard library Rdefinitions.v Rpow_def.v Raxioms.v*)\nSet Warnings \"-notation-overridden,-parsing\".\nFrom Coq Require Import Bool.Bool.\nFrom Coq Require Import Logic.Classical.\nFrom Coq Require Import Init.Nat.\nFrom Coq Require Import Arith.Arith.\nFrom Coq Require Import Arith.EqNat.\nFrom Coq Require Import Lists.List.\nFrom Coq Require Import Strings.String.\nFrom Coq Require Import Classes.Morphisms.\nFrom Coq Require Import Classes.RelationClasses.\nFrom Coq Require Import Classes.Equivalence.\nFrom Coq Require Export ZArith.ZArith_base.\nFrom Coq Require Import QArith.QArith_base.\nFrom Coq Require Import QArith.Qabs.\nFrom Coq Require Import QArith.Qminmax.\nFrom Coq Require Import QArith.Qround.\nFrom Coq Require Import Logic.Classical.\nFrom Coq Require Import Logic.FunctionalExtensionality.\nFrom Coq Require Import Logic.PropExtensionality.\nFrom Coq Require Import Logic.ProofIrrelevance.\nFrom Coq Require Import setoid_ring.Ring_theory.\nFrom Coq Require Import setoid_ring.Ring.\nFrom Coq Require Import setoid_ring.Field.\nFrom Coq Require Import omega.Omega.\nFrom Coq Require Import micromega.Psatz.\nImport ListNotations.\nFrom CReal Require Import Countable.\nFrom CReal Require Import QArith_base_ext.\nFrom CReal Require Import Uncomputable.SingleLemmas.\n\nModule Type VIR_R.\n  Parameter R : Type.\n  Delimit Scope R_scope with R.\n  Bind Scope R_scope with R.\n  Local Open Scope R_scope.\n  Parameter R0 : R.\n  Parameter R1 : R.\n  Parameter Rplus : R -> R -> R.\n  Parameter Rmult : R -> R -> R.\n  Parameter Ropp : R -> R.\n  Parameter Rinv : R -> R.\n  Parameter Rlt : R -> R -> Prop.\n  Parameter Req : R -> R -> Prop.\n  \n  Infix \"==\" := Req : R_scope.\n  Infix \"+\" := Rplus : R_scope.\n  Infix \"*\" := Rmult : R_scope.\n  Notation \"- x\" := (Ropp x) : R_scope.\n  Notation \"/ x\" := (Rinv x) : R_scope.\n  Infix \"<\" := Rlt : R_scope.\n  \n  Definition Rgt (r1 r2:R) : Prop := r2 < r1.\n  \n  Definition Rle (r1 r2:R) : Prop := Rlt r1 r2 \\/ r1 ==r2.\n  \n  Definition Rge (r1 r2:R) : Prop := Rgt r1 r2 \\/ r1 == r2.\n  \n  Definition Rminus (r1 r2:R) : R := r1 + - r2.\n  \n  Definition Rdiv (r1 r2 :R) : R := r1 * / r2.\n  \n  Infix \"-\" := Rminus : R_scope.\n  Infix \"/\" := Rdiv : R_scope.\n  Infix \"<=\" := Rle : R_scope.\n  Infix \">=\" := Rge : R_scope.\n  Infix \">\"  := Rgt : R_scope.\n  Notation \"x <= y <= z\" := (x <= y /\\ y <= z) : R_scope.\n  Notation \"x <= y < z\"  := (x <= y /\\ y <  z) : R_scope.\n  Notation \"x < y < z\"   := (x <  y /\\ y <  z) : R_scope.\n  Notation \"x < y <= z\"  := (x <  y /\\ y <= z) : R_scope.\n  Notation \"0\" := R0 : R_scope.\n  Notation \"1\" := R1 : R_scope.\n  Notation \"2\" := (1+1) : R_scope.\n  \n  (* Definitions copied from Rdefinitions.v *)\n  (* Delete the definition of up *)\n  \n  Parameter Req_refl : forall x : R ,  x == x.\n  \n  Parameter Req_sym : forall x y : R , x == y -> y == x.\n\n  Parameter Req_trans : forall x y z : R , x == y -> y == z -> x == z.\n\n  Hint Immediate Req_sym : real.\n  Hint Resolve Req_refl Req_trans : real.\n\n  Instance R_Setoid : Equivalence Req.\n  Proof. split; red; eauto with real. Qed.\n  \n  Axiom Rplus_comp : Proper (Req==>Req==>Req) Rplus.\n  Existing Instance Rplus_comp .\n  \n  Axiom Ropp_comp : Proper (Req==>Req) Ropp.\n  Existing Instance Ropp_comp .\n  \n  Axiom Rmult_comp : Proper (Req==>Req==>Req) Rmult.\n  Existing Instance Rmult_comp .\n  \n  Axiom Rinv_comp : Proper (Req==>Req) Rinv.\n  Existing Instance Rinv_comp .\n  \n  Axiom Rle_comp : Proper (Req==>Req==>iff) Rle.\n  Existing Instance Rle_comp .\n  \n  Axiom Rlt_comp : Proper (Req==>Req==>iff) Rlt.\n  Existing Instance Rlt_comp .\n  \n  Instance Rminus_comp : Proper (Req==>Req==>Req) Rminus.\n  Proof. hnf ; red ; intros. unfold Rminus. rewrite H , H0. reflexivity. Qed.\n  \n  Instance Rdiv_comp : Proper (Req==>Req==>Req) Rdiv.\n  Proof. hnf ; red ; intros. unfold Rdiv. rewrite H , H0. reflexivity. Qed.\n  \n  Instance Rgt_comp : Proper (Req==>Req==>iff) Rgt.\n  Proof. hnf ; red ; intros. unfold Rgt. rewrite H , H0. reflexivity. Qed.\n  \n  Instance Rge_comp : Proper (Req==>Req==>iff) Rge.\n  Proof. hnf ; red ; intros. unfold Rge. rewrite H , H0. reflexivity. Qed.\n  \n  (* Complementary definition of Real Equivalence. *)\n  \n  Fixpoint pow (r:R) (n:nat) : R :=\n    match n with\n      | O => 1\n      | S n => Rmult r (pow r n)\n    end.\n  \n  Instance Rpow_comp : Proper (Req ==> eq ==> Req) pow.\n  Proof. \n    hnf ; red; intros. rewrite H0. clear H0.\n    induction y0.\n    - simpl. reflexivity.\n    - simpl. rewrite IHy0. rewrite H. reflexivity.\n  Qed.\n  \n  (* Definition copied from Rpow_def.v *)\n  \n  Fixpoint IPR_2 (p:positive) : R :=\n    match p with\n    | xH => R1 + R1\n    | xO p => (R1 + R1) * IPR_2 p\n    | xI p => (R1 + R1) * (R1 + IPR_2 p)\n    end.\n\n  Definition IPR (p:positive) : R :=\n    match p with\n    | xH => R1\n    | xO p => IPR_2 p\n    | xI p => R1 + IPR_2 p\n    end.\n  Arguments IPR p%positive : simpl never.\n\n  (**********)\n  Definition IZR (z:Z) : R :=\n    match z with\n    | Z0 => R0\n    | Zpos n => IPR n\n    | Zneg n => - IPR n\n    end.\n  Arguments IZR z%Z : simpl never.\n  \n  (* Definitions copied from Rdefinitions.v *)\n  \n  Fixpoint INR (n:nat) : R :=\n    match n with\n    | O => 0\n    | S O => 1\n    | S n => INR n + 1\n    end.\n  Arguments INR n%nat.\n  \n  (* Definition copied from Raxioms.v *)\n  \n  Definition IQR(q : Q) : R :=\n    match q with\n    | p # q => IZR p / IPR q\n    end.\n  Arguments IQR q%Q.\n \n  (* Complementary definition of Injection from Q to R. *)\n  \n  (* Definition of Vir_R *)\n  \n  Axiom Rplus_comm : forall r1 r2:R, r1 + r2 == r2 + r1.\n  Hint Resolve Rplus_comm: real.\n  Axiom Rplus_assoc : forall r1 r2 r3:R, r1 + r2 + r3 == r1 + (r2 + r3).\n  Hint Resolve Rplus_assoc: real.\n  Axiom Rplus_opp_r : forall r:R, r + - r == 0.\n  Hint Resolve Rplus_opp_r: real.\n  Axiom Rplus_0_l : forall r:R, 0 + r == r.\n  Hint Resolve Rplus_0_l: real.\n  Axiom Rmult_comm : forall r1 r2:R, r1 * r2 == r2 * r1.\n  Hint Resolve Rmult_comm: real.\n  Axiom Rmult_assoc : forall r1 r2 r3:R, r1 * r2 * r3 == r1 * (r2 * r3).\n  Hint Resolve Rmult_assoc: real.\n  Axiom Rinv_l : forall r:R, ~ r == 0 -> / r * r == 1.\n  Hint Resolve Rinv_l: real.\n  Axiom Rmult_1_l : forall r:R, 1 * r == r.\n  Hint Resolve Rmult_1_l: real.\n  Axiom\n    Rmult_plus_distr_l : forall r1 r2 r3:R, r1 * (r2 + r3) == r1 * r2 + r1 * r3.\n  Hint Resolve Rmult_plus_distr_l: real.\n\n  Axiom total_order_T : forall r1 r2:R, r1 < r2 \\/ r1 == r2 \\/ r1 > r2.\n  Axiom Rlt_asym : forall r1 r2:R, r1 < r2 -> ~ r2 < r1.\n  Axiom Rlt_trans : forall r1 r2 r3:R, r1 < r2 -> r2 < r3 -> r1 < r3.\n  Axiom R1_gt_R0 : 0 < 1.\n  Hint Resolve R1_gt_R0: real.\n  \n  Axiom Rplus_lt_compat_l : forall r r1 r2:R, r1 < r2 -> r + r1 < r + r2.\n  Axiom\n    Rmult_lt_compat_l : forall r r1 r2:R, 0 < r -> r1 < r2 -> r * r1 < r * r2.\n  Hint Resolve Rlt_asym Rplus_lt_compat_l Rmult_lt_compat_l: real.\n  (* Axioms copied from Raxioms.v *)\n  (* Change { | } -> exists , sumbool to or *)\n  (* Change eq -> Req *)\n  \n  (* Axioms of Vir_R *)\nEnd VIR_R.\n\nModule Type VIR_R_COMPLETE (VirR : VIR_R).\n  Import VirR.\n  Local Open Scope R_scope.\n  Axiom archimed : forall r:R, exists z : Z , IZR z > r /\\ IZR z - r <= 1.\n\n  Definition is_upper_bound (E:R -> Prop) (m:R) := forall x:R, E x -> x <= m.\n\n  Definition bound (E:R -> Prop) := exists m : R, is_upper_bound E m.\n\n  Definition is_lub (E:R -> Prop) (m:R) :=\n  is_upper_bound E m /\\ (forall b:R, is_upper_bound E b -> m <= b).\n\n  Axiom\n  completeness :\n    forall E:R -> Prop,\n      bound E -> (exists x : R, E x) -> exists m:R , is_lub E m .\n \n  (* Completeness axioms copied from Raxioms.v *)\n  (* Change { | } -> exists , sumbool to or *)\nEnd VIR_R_COMPLETE.\n\nModule Type VIR_R_SINGLETON (VirR : VIR_R).\n  Import VirR.\n  Local Open Scope R_scope.\n  Definition P_singlefun (X : R -> Prop) := (forall x1 x2, X x1 -> X x2 -> x1 == x2)\n         /\\ (exists x, X x) /\\ Proper (Req ==> iff) X.\n  Parameter Rsinglefun : {X: R -> Prop | P_singlefun X} -> R.\n  Axiom Rsinglefun_correct: forall X H, X (Rsinglefun (exist _ X H)).\nEnd VIR_R_SINGLETON.\n\nModule VirRSingletonLemmas (VirR: VIR_R) (VirRSingleton: VIR_R_SINGLETON VirR).\n  Import VirR.\n  Import VirRSingleton.\n  Local Open Scope R_scope.\n\n  Module RSS <: R_SINGLE_SIMPLE.\n    Definition R := VirR.R.\n    Definition Req := VirR.Req.\n    Definition R_Setoid := VirR.R_Setoid.\n    Definition P_singlefun := VirRSingleton.P_singlefun.\n    Definition Rsinglefun := VirRSingleton.Rsinglefun.\n    Definition Rsinglefun_correct  := VirRSingleton.Rsinglefun_correct.\n  End RSS.\n\n  Module RL := RSignleLemmas RSS.\n  \n  Definition Rif: Prop -> R -> R -> R := RL.Rif. \n  \n  Instance Rif_comp : Proper (eq(A:=Prop) ==> Req ==> Req ==> Req) Rif :=\n    RL.Rif_comp.\n  \n  Definition Rif_left : forall (P:Prop) (x y:R), P -> Rif P x y == x :=\n    RL.Rif_left.\n  \n  Definition Rif_right : forall (P:Prop) (x y:R), ~ P -> Rif P x y == y :=\n    RL.Rif_right.\n  \n  Definition Rif_rich: forall (P : Prop) (x: P -> R) (y: ~ P -> R)\n                              {_: Proper ((fun _ _ : P => True) ==> Req) x}\n                              {_: Proper ((fun _ _ : ~ P => True) ==> Req) y}, R :=\n    RL.Rif_rich.\n\n  Definition Rif_rich_left: forall (P : Prop) (x: P -> R) (y: ~ P -> R)\n                              {Px: Proper ((fun _ _ : P => True) ==> Req) x}\n                              {Py: Proper ((fun _ _ : ~ P => True) ==> Req) y},\n    P -> exists H : P, @Rif_rich P x y Px Py == x H\n  := RL.Rif_rich_left.\n  \n  Definition Rif_rich_right: forall (P : Prop) (x: P -> R) (y: ~ P -> R)\n                              {Px: Proper ((fun _ _ : P => True) ==> Req) x}\n                              {Py: Proper ((fun _ _ : ~ P => True) ==> Req) y},\n    ~ P -> exists H : ~ P,Rif_rich P x y == y H\n  := RL.Rif_rich_right.\nEnd VirRSingletonLemmas.\n\nModule Type VIR_R_ALL.\n\nInclude VIR_R.\nInclude VIR_R_SINGLETON.\nInclude VIR_R_COMPLETE.\n\nEnd VIR_R_ALL.\n", "meta": {"author": "QinxiangCao", "repo": "ClassicalReal", "sha": "60860e58d1ca98251ce7fdd01a7175bb8c560dd8", "save_path": "github-repos/coq/QinxiangCao-ClassicalReal", "path": "github-repos/coq/QinxiangCao-ClassicalReal/ClassicalReal-60860e58d1ca98251ce7fdd01a7175bb8c560dd8/Uncomputable/ComRealBase.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.29904488002114193}}
{"text": "Require Import ZArith.\nRequire Import divsteps_base.\n\nLemma example60 : ZMap.Empty (N.iter 60 (processDivstep 0x25f260) state0).\nProof.\napply ZMap.is_empty_2.\nvm_cast_no_check (refl_equal true).\nTime Qed.\n\nLemma example70 : ZMap.Empty (N.iter 70 (processDivstep 0x1b6e641) state0).\nProof.\napply ZMap.is_empty_2.\nvm_cast_no_check (refl_equal true).\nTime Qed.\n\nLemma example80 : ZMap.Empty (N.iter 80 (processDivstep 0x13ff9d11) state0).\nProof.\napply ZMap.is_empty_2.\nvm_cast_no_check (refl_equal true).\nTime Qed.\n\nLemma example90 : ZMap.Empty (N.iter 90 (processDivstep 0xe5ffa818) state0).\nProof.\napply ZMap.is_empty_2.\nvm_cast_no_check (refl_equal true).\nTime Qed.\n\nLemma example100 : ZMap.Empty (N.iter 100 (processDivstep 0xa83fbaca2) state0).\nProof.\napply ZMap.is_empty_2.\nvm_cast_no_check (refl_equal true).\nTime Qed.\n\nLemma example120 : ZMap.Empty (N.iter 120 (processDivstep 0x5815434ee53) state0).\nProof.\napply ZMap.is_empty_2.\nvm_cast_no_check (refl_equal true).\nTime Qed.\n\nLemma example140 : ZMap.Empty (N.iter 140 (processDivstep 0x2e1e235b5b050) state0).\nProof.\napply ZMap.is_empty_2.\nvm_cast_no_check (refl_equal true).\nTime Qed.\n\nLemma example160 : ZMap.Empty (N.iter 160 (processDivstep 0x182ad45d1c9ceb3) state0).\nProof.\napply ZMap.is_empty_2.\nvm_cast_no_check (refl_equal true).\nTime Qed.\n\nLemma example180 : ZMap.Empty (N.iter 180 (processDivstep 0xcb846e4b7123c2e6) state0).\nProof.\napply ZMap.is_empty_2.\nvm_cast_no_check (refl_equal true).\nTime Qed.\n\nLemma example200 : ZMap.Empty (N.iter 200 (processDivstep 0x6b3e8fa3a7bf045de8) state0).\nProof.\napply ZMap.is_empty_2.\nvm_cast_no_check (refl_equal true).\nTime Qed.\n\nLemma example250 : ZMap.Empty (N.iter 250 (processDivstep 0x15627f2692a0950931661a2) state0).\nProof.\napply ZMap.is_empty_2.\nvm_cast_no_check (refl_equal true).\nTime Qed.\n\nLemma example300 : ZMap.Empty (N.iter 300 (processDivstep 0x444ef1442ed062b8a839c3f73b7) state0).\nProof.\napply ZMap.is_empty_2.\nvm_cast_no_check (refl_equal true).\nTime Qed.\n\nLemma example350 : ZMap.Empty (N.iter 350 (processDivstep 0xdb25c1822a251f32e577049b3ae0534) state0).\nProof.\napply ZMap.is_empty_2.\nvm_cast_no_check (refl_equal true).\nTime Qed.\n\nLemma example400 : ZMap.Empty (N.iter 400 (processDivstep 0x2bfb19d6f6a3c2c9f7958b69b1c1b4599b89) state0).\nProof.\napply ZMap.is_empty_2.\nvm_cast_no_check (refl_equal true).\nTime Qed.\n\nLemma example450 : ZMap.Empty (N.iter 450 (processDivstep 0x8d398ceaaafb27cf5dee5af890ad7f76079d8d94) state0).\nProof.\napply ZMap.is_empty_2.\nvm_cast_no_check (refl_equal true).\nTime Qed.\n\nLemma example500 : ZMap.Empty (N.iter 500 (processDivstep 0x1c37b0f2a381c18fcb128b22b449e871a7b2e91dd4597) state0).\nProof.\napply ZMap.is_empty_2.\nvm_cast_no_check (refl_equal true).\nTime Qed.\n\nLemma example600 : ZMap.Empty (N.iter 600 (processDivstep 0x11f38fa0335f159c3a401217b46582758aa53084bfe4fe57a7dbd9) state0).\nProof.\napply ZMap.is_empty_2.\nvm_cast_no_check (refl_equal true).\nTime Qed.", "meta": {"author": "sipa", "repo": "safegcd-bounds", "sha": "afab8eda5b7e526b0069c4b132609e9fd09404bf", "save_path": "github-repos/coq/sipa-safegcd-bounds", "path": "github-repos/coq/sipa-safegcd-bounds/safegcd-bounds-afab8eda5b7e526b0069c4b132609e9fd09404bf/coq/divsteps/divsteps_examples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.29903140293236136}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.progs.evenodd.\nLocal Open Scope logic.\n\nInductive repr : Z -> val -> Prop :=\n| mk_repr : forall z, z >= 0 -> repr z (Vint (Int.repr z)).\n\nLemma repr0_not_odd z n :\n  repr z (Vint n) -> Int.eq n (Int.repr 0) = true -> Z.odd z = false.\nProof.\ninversion 1; subst; intros A.\nsymmetry in A; apply binop_lemmas.int_eq_true in A.\nrewrite A in H; inv H.\nrewrite Int.Z_mod_modulus_eq, Zmod_divides in H0.\ndestruct H0 as [c H0]; rewrite H0, Z.odd_mul; auto.\nunfold Int.modulus; simpl; intro Contra; inv Contra.\nQed.\n\nLemma repr0_even z n :\n  repr z (Vint n) -> Int.eq n (Int.repr 0) = true -> Z.even z = true.\nProof.\ninversion 1; subst; intros A.\nsymmetry in A; apply binop_lemmas.int_eq_true in A.\nrewrite A in H; inv H.\nrewrite Int.Z_mod_modulus_eq, Zmod_divides in H0.\ndestruct H0 as [c H0]; rewrite H0, Z.even_mul; auto.\nunfold Int.modulus; simpl; intro Contra; inv Contra.\nQed.\n\nLemma repr_eq0_not0 z :\n  Int.eq (Int.repr z) (Int.repr 0) = false -> z <> 0.\nProof.\nintros H; generalize (Int.eq_spec (Int.repr z) (Int.repr 0)); rewrite H.\nintros H2 H3; rewrite H3 in H2; apply H2; auto.\nQed.\n\nDefinition odd_spec :=\n DECLARE _odd\n  WITH sh : share, z : Z, v : val\n  PRE [ _n OF tuint] PROP(repr z v) LOCAL (`(eq v) (eval_id _n)) SEP ()\n  POST [ tint ] local (`(eq (Vint (if Z.odd z then Int.one else Int.zero))) retval).\n\nDefinition even_spec :=\n DECLARE _even\n  WITH z : Z, v : val\n  PRE [ _n OF tuint] PROP(repr z v) LOCAL (`(eq v) (eval_id _n)) SEP ()\n  POST [ tint ] local (`(eq (Vint (if Z.even z then Int.one else Int.zero))) retval).\n\nDefinition main_spec :=\n DECLARE _main\n  WITH z : Z, v : val\n  PRE [ ] PROP(repr 42 v) LOCAL () SEP ()\n  POST [ tint ] local (`(eq (Vint (if Z.even 42 then Int.one else Int.zero))) retval).\n\nDefinition Vprog : varspecs := nil.\n\nDefinition Gprog : funspecs :=\n     ltac:(with_library prog [ odd_spec; even_spec; main_spec]).\n\nLemma body_odd : semax_body Vprog Gprog f_odd odd_spec.\nProof.\nstart_function.\nname n _n.\nforward_if (PROP (repr z v /\\ z > 0) LOCAL (`(eq v) (eval_id _n)) SEP ()).\n* forward; eapply repr0_not_odd in H0; eauto; rewrite H0; entailer.\n* forward; entailer; inv H.\n  assert (z <> 0) by (apply repr_eq0_not0; auto); entailer.\n* forward_call (z-1,Vint (Int.sub (Int.repr z) (Int.repr 1))).\n  entailer; inversion H; subst z0; rewrite <-H5 in H2; inversion H2; subst n.\n  entailer.\n  assert (repr (z - 1) (Vint (Int.repr (z - 1)))).\n  { clear -H H1. inv H. constructor. lia. }\n  entailer!.\n  after_call; forward.\n  rewrite Z.even_sub; simpl.\n  case_eq (Z.odd z); rewrite Zodd_even_bool;\n   destruct (Z.even z); simpl; congruence.\nQed.\n\nLemma body_even : semax_body Vprog Gprog f_even even_spec.\nProof.\nstart_function.\nname n _n.\nforward_if (PROP (repr z v /\\ z > 0) LOCAL (`(eq v) (eval_id _n)) SEP ()).\n* forward. eapply repr0_even in H0; eauto; rewrite H0; entailer.\n* forward; entailer; inv H.\n  assert (z <> 0) by (apply repr_eq0_not0; auto); entailer.\n* forward_call (Share.top,z-1,Vint (Int.sub (Int.repr z) (Int.repr 1))).\n  entailer; inversion H; subst z0; rewrite <-H5 in H2; inversion H2; subst n.\n  entailer.\n  assert (repr (z - 1) (Vint (Int.repr (z - 1)))).\n  { clear -H H1. inv H. constructor. lia. }\n  entailer!.\n  after_call; forward.\n  rewrite Z.odd_sub; simpl.\n  case_eq (Z.odd z); rewrite Zodd_even_bool;\n   destruct (Z.even z); simpl; congruence.\nQed.\n\nLemma body_main : semax_body Vprog Gprog f_main main_spec.\nProof with (try solve[entailer!|entailer!; constructor; lia]).\nstart_function.\nforward_call (42,Vint (Int.repr 42))... after_call.\nforward.\nQed.\n\nLemma prog_correct:\n  semax_prog prog tt Vprog Gprog.\nProof.\nprove_semax_prog.\nsemax_func_cons body_odd.\nsemax_func_cons body_even.\nsemax_func_cons body_main.\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_evenodd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.2990306039958985}}
{"text": "(* Distributed under the terms of the MIT license. *)\nFrom MetaCoq.Utils Require Import utils.\nFrom MetaCoq.Common Require Import uGraph Reflect.\nFrom MetaCoq.PCUIC Require Import PCUICAst PCUICSize.\n\nRequire Import ssreflect.\nFrom Equations Require Import Equations.\nSet Equations Transparent.\n\nLemma eqb_annot_reflect {A} na na' : reflect (@eq_binder_annot A A na na') (eqb_binder_annot na na').\nProof.\n  unfold eqb_binder_annot, eq_binder_annot.\n  destruct Classes.eq_dec; constructor; auto.\nQed.\n\nDefinition string_of_aname (b : binder_annot name) :=\n  string_of_name b.(binder_name).\n\nFixpoint string_of_term (t : term) :=\n  match t with\n  | tRel n => \"Rel(\" ^ string_of_nat n ^ \")\"\n  | tVar n => \"Var(\" ^ n ^ \")\"\n  | tEvar ev args => \"Evar(\" ^ string_of_nat ev ^ \",\" ^ string_of_list string_of_term args ^ \")\"\n  | tSort s => \"Sort(\" ^ string_of_sort s ^ \")\"\n  | tProd na b t => \"Prod(\" ^ string_of_aname na ^ \",\" ^\n                            string_of_term b ^ \",\" ^ string_of_term t ^ \")\"\n  | tLambda na b t => \"Lambda(\" ^ string_of_aname na ^ \",\" ^ string_of_term b\n                                ^ \",\" ^ string_of_term t ^ \")\"\n  | tLetIn na b t' t => \"LetIn(\" ^ string_of_aname na ^ \",\" ^ string_of_term b\n                                 ^ \",\" ^ string_of_term t' ^ \",\" ^ string_of_term t ^ \")\"\n  | tApp f l => \"App(\" ^ string_of_term f ^ \",\" ^ string_of_term l ^ \")\"\n  | tConst c u => \"Const(\" ^ string_of_kername c ^ \",\" ^ string_of_universe_instance u ^ \")\"\n  | tInd i u => \"Ind(\" ^ string_of_inductive i ^ \",\" ^ string_of_universe_instance u ^ \")\"\n  | tConstruct i n u => \"Construct(\" ^ string_of_inductive i ^ \",\" ^ string_of_nat n ^ \",\"\n                                    ^ string_of_universe_instance u ^ \")\"\n  | tCase ci p t brs =>\n    \"Case(\" ^ string_of_case_info ci ^ \",\" ^ string_of_term t ^ \",\"\n            ^ string_of_predicate string_of_term p ^ \",\" ^ string_of_list (string_of_branch string_of_term) brs ^ \")\"\n  | tProj p c =>\n    \"Proj(\" ^ string_of_inductive p.(proj_ind) ^ \",\" ^ string_of_nat p.(proj_npars) ^ \",\" ^ string_of_nat p.(proj_arg) ^ \",\"\n            ^ string_of_term c ^ \")\"\n  | tFix l n => \"Fix(\" ^ (string_of_list (string_of_def string_of_term) l) ^ \",\" ^ string_of_nat n ^ \")\"\n  | tCoFix l n => \"CoFix(\" ^ (string_of_list (string_of_def string_of_term) l) ^ \",\" ^ string_of_nat n ^ \")\"\n  | tPrim i => \"Int(\" ^ string_of_prim string_of_term i ^ \")\"\n  end.\n\nLtac change_Sk :=\n  repeat match goal with\n    | |- context [S (?x + ?y)] => progress change (S (x + y)) with (S x + y)\n    | |- context [#|?l| + (?x + ?y)] => progress replace (#|l| + (x + y)) with ((#|l| + x) + y) by now rewrite Nat.add_assoc\n  end.\n\nLtac solve_all_one :=\n  try lazymatch goal with\n  | H: tCasePredProp _ _ _ |- _ => destruct H as [? [? ?]]\n  end;\n  unfold tCaseBrsProp, tFixProp in *;\n  autorewrite with map;\n  rtoProp;\n  try (\n    apply map_predicate_eq_spec ||\n    apply map_predicate_k_eq_spec ||\n    apply map_predicate_id_spec ||\n    apply map_predicate_k_id_spec ||\n    apply map_branch_k_eq_spec ||\n    apply map_branch_k_id_spec ||\n    apply map_def_eq_spec ||\n    apply map_def_id_spec ||\n    apply map_branch_eq_spec ||\n    apply map_branch_id_spec ||\n    (eapply All_forallb_eq_forallb; [eassumption|]) ||\n    (eapply mapi_context_eqP_test_id_spec; [eassumption|eassumption|]) ||\n    (eapply mapi_context_eqP_spec; [eassumption|]) ||\n    (eapply mapi_context_eqP_id_spec; [eassumption|]) ||\n    (eapply onctx_test; [eassumption|eassumption|]) ||\n    (eapply test_context_k_eqP_id_spec; [eassumption|eassumption|]) ||\n    (eapply test_context_k_eqP_eq_spec; [eassumption|]) ||\n    (eapply map_context_eq_spec; [eassumption|]));\n  repeat toAll; try All_map; try close_Forall;\n  change_Sk; auto with all;\n  intuition eauto 4 with all.\n\nLtac solve_all := repeat (progress solve_all_one).\n#[global] Hint Extern 10 => rewrite !map_branch_map_branch : all.\n#[global] Hint Extern 10 => rewrite !map_predicate_map_predicate : all.\n\nLemma lookup_env_nil c s : lookup_global [] c = Some s -> False.\nProof.\n  induction c; simpl; auto => //.\nQed.\n\nLemma lookup_env_cons {kn d Σ kn' d'} : lookup_global ((kn, d) :: Σ) kn' = Some d' ->\n  (kn = kn' /\\ d = d') \\/ (kn <> kn' /\\ lookup_global Σ kn' = Some d').\nProof.\n  simpl.\n  epose proof (ReflectEq.eqb_spec (A:=kername) kn' kn). simpl in H.\n  elim: H. intros -> [= <-]; intuition auto.\n  intros diff look. intuition auto.\nQed.\n\nLemma lookup_env_cons_fresh {kn d Σ kn'} :\n  kn <> kn' ->\n  lookup_global ((kn, d) :: Σ) kn' = lookup_global Σ kn'.\nProof.\n  simpl.\n  epose proof (ReflectEq.eqb_spec (A:=kername) kn' kn). simpl in H.\n  elim: H. intros -> => //. auto.\nQed.\n\nFixpoint decompose_app_rec (t : term) l :=\n  match t with\n  | tApp f a => decompose_app_rec f (a :: l)\n  | _ => (t, l)\n  end.\n\nDefinition decompose_app t := decompose_app_rec t [].\n\nLemma mkApps_tApp f a l : mkApps (tApp f a) l = mkApps f (a :: l).\nProof. reflexivity. Qed.\n\nLemma tApp_mkApps f a : tApp f a = mkApps f [a].\nProof. reflexivity. Qed.\n\nDefinition mkApps_decompose_app_rec t l :\n  mkApps t l = mkApps (fst (decompose_app_rec t l)) (snd (decompose_app_rec t l)).\nProof.\n  revert l; induction t; try reflexivity.\n  intro l; cbn in *.\n  transitivity (mkApps t1 ((t2 ::l))). reflexivity.\n  now rewrite IHt1.\nQed.\n\nDefinition mkApps_decompose_app t :\n  t = mkApps (fst (decompose_app t)) (snd (decompose_app t))\n  := mkApps_decompose_app_rec t [].\n\nLemma decompose_app_rec_mkApps f l l' : decompose_app_rec (mkApps f l) l' =\n                                    decompose_app_rec f (l ++ l').\nProof.\n  induction l in f, l' |- *; simpl; auto; rewrite IHl ?app_nil_r; auto.\nQed.\n\nRequire Import ssrbool.\n\nLemma decompose_app_mkApps f l :\n  ~~ isApp f -> decompose_app (mkApps f l) = (f, l).\nProof.\n  intros Hf. rewrite /decompose_app decompose_app_rec_mkApps. rewrite app_nil_r.\n  destruct f; simpl in *; (discriminate || reflexivity).\nQed.\n\nLemma mkApps_app f l l' : mkApps f (l ++ l') = mkApps (mkApps f l) l'.\nProof.\n  induction l in f, l' |- *; destruct l'; simpl; rewrite ?app_nil_r; auto.\n  rewrite IHl //.\nQed.\n\n\nLemma mkApps_tApp_inj fn args t u :\n  ~~ isApp fn ->\n  mkApps fn args = tApp t u ->\n  t = mkApps fn (removelast args) /\\ u = last args t.\nProof.\n  intros napp eqapp.\n  destruct args using rev_case => //.\n  simpl in eqapp. subst fn => //.\n  rewrite mkApps_app in eqapp. noconf eqapp.\n  now rewrite removelast_app // last_app // /= app_nil_r.\nQed.\n\nLemma removelast_length {A} (args : list A) : #|removelast args| = Nat.pred #|args|.\nProof.\n  induction args => //. destruct args => //.\n  now rewrite (removelast_app [_]) // app_length IHargs /=.\nQed.\n\nLemma nth_error_removelast {A} {args : list A} {n arg} :\n  nth_error (removelast args) n = Some arg ->\n  nth_error args n = Some arg.\nProof.\n  intros h. rewrite nth_error_removelast //.\n  apply nth_error_Some_length in h.\n  now rewrite removelast_length in h.\nQed.\n\nLemma mkApps_discr f args t :\n  args <> [] ->\n  mkApps f args = t ->\n  ~~ isApp t -> False.\nProof.\n  intros.\n  destruct args using rev_case => //.\n  rewrite mkApps_app in H0. destruct t => //.\nQed.\n\nFixpoint decompose_prod (t : term) : (list aname) * (list term) * term :=\n  match t with\n  | tProd n A B => let (nAs, B) := decompose_prod B in\n                  let (ns, As) := nAs in\n                  (n :: ns, A :: As, B)\n  | _ => ([], [], t)\n  end.\n\nFixpoint remove_arity (n : nat) (t : term) : term :=\n  match n with\n  | O => t\n  | S n => match t with\n          | tProd _ _ B => remove_arity n B\n          | _ => t (* TODO *)\n          end\n  end.\n\nDefinition isConstruct_app t :=\n  match fst (decompose_app t) with\n  | tConstruct _ _ _ => true\n  | _ => false\n  end.\n\n(* was mind_decl_to_entry *)\nDefinition mind_body_to_entry (decl : mutual_inductive_body)\n  : mutual_inductive_entry.\nProof.\n  refine {| mind_entry_record := None; (* not a record *)\n            mind_entry_finite := Finite; (* inductive *)\n            mind_entry_params := _;\n            mind_entry_inds := _;\n            mind_entry_universes := decl.(ind_universes);\n            mind_entry_private := None |}.\n  - refine (match List.hd_error decl.(ind_bodies) with\n            | Some i0 => _\n            | None => nil (* assert false: at least one inductive in a mutual block *)\n            end).\n    pose (typ := decompose_prod i0.(ind_type)).\n    destruct typ as [[names types] _].\n    apply (List.firstn decl.(ind_npars)) in names.\n    apply (List.firstn decl.(ind_npars)) in types.\n    refine (map (fun '(x, ty) => vass x ty) (combine names types)).\n  - refine (List.map _ decl.(ind_bodies)).\n    intros [].\n    refine {| mind_entry_typename := ind_name0;\n              mind_entry_arity := remove_arity decl.(ind_npars) ind_type0;\n              mind_entry_template := false;\n              mind_entry_consnames := _;\n              mind_entry_lc := _;\n            |}.\n    refine (List.map (fun x => cstr_name x) ind_ctors0).\n    refine (List.map (fun x => remove_arity decl.(ind_npars)\n                                                (cstr_type x)) ind_ctors0).\nDefined.\n\nFixpoint decompose_prod_assum (Γ : context) (t : term) : context * term :=\n  match t with\n  | tProd n A B => decompose_prod_assum (Γ ,, vass n A) B\n  | tLetIn na b bty b' => decompose_prod_assum (Γ ,, vdef na b bty) b'\n  | _ => (Γ, t)\n  end.\n\nLemma decompose_prod_assum_ctx ctx t : decompose_prod_assum ctx t =\n  let (ctx', t') := decompose_prod_assum [] t in\n  (ctx ,,, ctx', t').\nProof.\n  induction t in ctx |- *; simpl; auto.\n  - simpl. rewrite IHt2.\n    rewrite (IHt2 ([] ,, vass _ _)).\n    destruct (decompose_prod_assum [] t2). simpl.\n    unfold snoc. now rewrite app_context_assoc.\n  - simpl. rewrite IHt3.\n    rewrite (IHt3 ([] ,, vdef _ _ _)).\n    destruct (decompose_prod_assum [] t3). simpl.\n    unfold snoc. now rewrite app_context_assoc.\nQed.\n\nFixpoint decompose_prod_n_assum (Γ : context) n (t : term) : option (context * term) :=\n  match n with\n  | 0 => Some (Γ, t)\n  | S n =>\n    match t with\n    | tProd na A B => decompose_prod_n_assum (Γ ,, vass na A) n B\n    | tLetIn na b bty b' => decompose_prod_n_assum (Γ ,, vdef na b bty) n b'\n    | _ => None\n    end\n  end.\n\n(* TODO move *)\nLemma it_mkLambda_or_LetIn_app l l' t :\n  it_mkLambda_or_LetIn (l ++ l') t = it_mkLambda_or_LetIn l' (it_mkLambda_or_LetIn l t).\nProof. induction l in l', t |- *; simpl; auto. Qed.\n\nLemma decompose_prod_n_assum_it_mkProd ctx ctx' ty :\n  decompose_prod_n_assum ctx #|ctx'| (it_mkProd_or_LetIn ctx' ty) = Some (ctx' ++ ctx, ty).\nProof.\n  revert ctx ty. induction ctx' using rev_ind; move=> // ctx ty.\n  rewrite app_length /= it_mkProd_or_LetIn_app /=.\n  destruct x as [na [body|] ty'] => /=;\n  now rewrite !Nat.add_1_r /= IHctx' -app_assoc.\nQed.\n\nDefinition is_ind_app_head t :=\n  let (f, l) := decompose_app t in\n  match f with\n  | tInd _ _ => true\n  | _ => false\n  end.\n\nLemma is_ind_app_head_mkApps ind u l : is_ind_app_head (mkApps (tInd ind u) l).\nProof.\n  unfold is_ind_app_head.\n  unfold decompose_app. rewrite decompose_app_rec_mkApps. now simpl; trivial.\nQed.\n\nLemma decompose_prod_assum_it_mkProd ctx ctx' ty :\n  is_ind_app_head ty ->\n  decompose_prod_assum ctx (it_mkProd_or_LetIn ctx' ty) = (ctx' ++ ctx, ty).\nProof.\n  revert ctx ty. induction ctx' using rev_ind; move=> // ctx ty /=.\n  destruct ty; unfold is_ind_app_head; simpl; try (congruence || reflexivity).\n  move=> Hty. rewrite it_mkProd_or_LetIn_app /=.\n  case: x => [na [body|] ty'] /=; by rewrite IHctx' // /snoc -app_assoc.\nQed.\n\nLemma reln_length Γ Γ' n : #|reln Γ n Γ'| = #|Γ| + context_assumptions Γ'.\nProof.\n  induction Γ' in n, Γ |- *; simpl; auto.\n  destruct a as [? [b|] ?]; simpl; auto.\n  rewrite Nat.add_1_r. simpl. rewrite IHΓ' => /= //.\nQed.\n\nLemma to_extended_list_k_length Γ n : #|to_extended_list_k Γ n| = context_assumptions Γ.\nProof.\n  now rewrite /to_extended_list_k reln_length.\nQed.\n\nLemma reln_list_lift_above l p Γ :\n  Forall (fun x => exists n, x = tRel n /\\ p <= n /\\ n < p + length Γ) l ->\n  Forall (fun x => exists n, x = tRel n /\\ p <= n /\\ n < p + length Γ) (reln l p Γ).\nProof.\n  generalize (Nat.le_refl p).\n  generalize p at 1 3 5.\n  induction Γ in p, l |- *. simpl. auto.\n  intros. destruct a. destruct decl_body. simpl.\n  assert(p0 <= S p) by lia.\n  specialize (IHΓ l (S p) p0 H1). rewrite <- Nat.add_succ_comm, Nat.add_1_r.\n  simpl in *. rewrite <- Nat.add_succ_comm in H0. eauto.\n  simpl in *.\n  specialize (IHΓ (tRel p :: l) (S p) p0 ltac:(lia)). rewrite <- Nat.add_succ_comm, Nat.add_1_r.\n  eapply IHΓ. simpl in *. rewrite <- Nat.add_succ_comm in H0. auto.\n  simpl in *.\n  constructor. exists p. intuition lia. auto.\nQed.\n\nLemma to_extended_list_k_spec Γ k :\n  Forall (fun x => exists n, x = tRel n /\\ k <= n /\\ n < k + length Γ) (to_extended_list_k Γ k).\nProof.\n  pose (reln_list_lift_above [] k Γ).\n  unfold to_extended_list_k.\n  forward f. constructor. apply f.\nQed.\n\nLemma to_extended_list_lift_above Γ :\n  Forall (fun x => exists n, x = tRel n /\\ n < length Γ) (to_extended_list Γ).\nProof.\n  pose (reln_list_lift_above [] 0 Γ).\n  unfold to_extended_list.\n  forward f. constructor. eapply Forall_impl; eauto. intros.\n  destruct H; eexists; intuition eauto.\nQed.\n\nFixpoint reln_alt p (Γ : context) :=\n  match Γ with\n  | [] => []\n  | {| decl_body := Some _ |} :: Γ => reln_alt (p + 1) Γ\n  | {| decl_body := None |} :: Γ => tRel p :: reln_alt (p + 1) Γ\n  end.\n\nLemma reln_alt_eq l Γ k : reln l k Γ = List.rev (reln_alt k Γ) ++ l.\nProof.\n  induction Γ in l, k |- *; simpl; auto.\n  destruct a as [na [body|] ty]; simpl.\n  now rewrite IHΓ.\n  now rewrite IHΓ -app_assoc.\nQed.\n\nLemma to_extended_list_k_cons d Γ k :\n  to_extended_list_k (d :: Γ) k =\n  match d.(decl_body) with\n  | None => to_extended_list_k Γ (S k) ++ [tRel k]\n  | Some b => to_extended_list_k Γ (S k)\n  end.\nProof.\n  rewrite /to_extended_list_k reln_alt_eq. simpl.\n  destruct d as [na [body|] ty]. simpl.\n  now rewrite reln_alt_eq Nat.add_1_r.\n  simpl. rewrite reln_alt_eq.\n  now rewrite -app_assoc !app_nil_r Nat.add_1_r.\nQed.\n\nLtac merge_All :=\n  unfold tFixProp, tCaseBrsProp in *;\n  repeat toAll.\n\n#[global]\nHint Rewrite @map_def_id @map_id : map.\n\n(* TODO move *)\nLtac close_All :=\n  match goal with\n  | H : Forall _ _ |- Forall _ _ => apply (Forall_impl H); clear H; simpl\n  | H : All _ _ |- All _ _ => apply (All_impl H); clear H; simpl\n  | H : OnOne2 _ _ _ |- OnOne2 _ _ _ => apply (OnOne2_impl H); clear H; simpl\n  | H : All2 _ _ _ |- All2 _ _ _ => apply (All2_impl H); clear H; simpl\n  | H : Forall2 _ _ _ |- Forall2 _ _ _ => apply (Forall2_impl H); clear H; simpl\n  | H : All _ _ |- All2 _ _ _ =>\n    apply (All_All2 H); clear H; simpl\n  | H : All2 _ _ _ |- All _ _ =>\n    (apply (All2_All_left H) || apply (All2_All_right H)); clear H; simpl\n  end.\n\nLemma mkApps_inj :\n  forall u v l,\n    mkApps u l = mkApps v l ->\n    u = v.\nProof.\n  intros u v l eq.\n  revert u v eq.\n  induction l ; intros u v eq.\n  - cbn in eq. assumption.\n  - cbn in eq. apply IHl in eq.\n    inversion eq. reflexivity.\nQed.\n\nLemma isApp_mkApps :\n  forall u l,\n    isApp u ->\n    isApp (mkApps u l).\nProof.\n  intros u l h.\n  induction l in u, h |- *.\n  - cbn. assumption.\n  - cbn. apply IHl. reflexivity.\nQed.\n\nLemma decompose_app_rec_notApp :\n  forall t l u l',\n    decompose_app_rec t l = (u, l') ->\n    isApp u = false.\nProof.\n  intros t l u l' e.\n  induction t in l, u, l', e |- *.\n  all: try (cbn in e ; inversion e ; reflexivity).\n  cbn in e. eapply IHt1. eassumption.\nQed.\n\nLemma decompose_app_notApp :\n  forall t u l,\n    decompose_app t = (u, l) ->\n    isApp u = false.\nProof.\n  intros t u l e.\n  eapply decompose_app_rec_notApp. eassumption.\nQed.\n\nLemma decompose_app_rec_inv {t l' f l} :\n  decompose_app_rec t l' = (f, l) ->\n  mkApps t l' = mkApps f l.\nProof.\n  induction t in f, l', l |- *; try intros [= <- <-]; try reflexivity.\n  simpl. apply/IHt1.\nQed.\n\nLemma decompose_app_inv {t f l} :\n  decompose_app t = (f, l) -> t = mkApps f l.\nProof. by apply/decompose_app_rec_inv. Qed.\n\nLemma decompose_app_nonnil t f l :\n  isApp t ->\n  decompose_app t = (f, l) -> l <> [].\nProof.\n  intros isApp.\n  destruct t; simpl => //.\n  intros da.\n  pose proof (decompose_app_notApp _ _ _ da).\n  apply decompose_app_inv in da.\n  destruct l using rev_ind.\n  unfold decompose_app => /=.\n  destruct f => //.\n  destruct l => //.\nQed.\n\nFixpoint nApp t :=\n  match t with\n  | tApp u _ => S (nApp u)\n  | _ => 0\n  end.\n\nLemma isApp_false_nApp :\n  forall u,\n    isApp u = false ->\n    nApp u = 0.\nProof.\n  intros u h.\n  destruct u.\n  all: try reflexivity.\n  discriminate.\nQed.\n\nLemma nApp_mkApps :\n  forall t l,\n    nApp (mkApps t l) = nApp t + #|l|.\nProof.\n  intros t l.\n  induction l in t |- *.\n  - simpl. lia.\n  - simpl. rewrite IHl. cbn. lia.\nQed.\n\nLemma decompose_app_eq_mkApps :\n  forall t u l l',\n    decompose_app t = (mkApps u l', l) ->\n    l' = [].\nProof.\n  intros t u l l' e.\n  apply decompose_app_notApp in e.\n  apply isApp_false_nApp in e.\n  rewrite nApp_mkApps in e.\n  destruct l' ; cbn in e ; try lia.\n  reflexivity.\nQed.\n\nLemma mkApps_nApp_inj :\n  forall u u' l l',\n    nApp u = nApp u' ->\n    mkApps u l = mkApps u' l' ->\n    u = u' /\\ l = l'.\nProof.\n  intros u u' l l' h e.\n  induction l in u, u', l', h, e |- *.\n  - cbn in e. subst.\n    destruct l' ; auto.\n    exfalso.\n    rewrite nApp_mkApps in h. cbn in h. lia.\n  - destruct l'.\n    + cbn in e. subst. exfalso.\n      rewrite nApp_mkApps in h. cbn in h. lia.\n    + cbn in e. apply IHl in e.\n      * destruct e as [e1 e2].\n        inversion e1. subst. auto.\n      * cbn. f_equal. auto.\nQed.\n\nLemma mkApps_notApp_inj :\n  forall u u' l l',\n    isApp u = false ->\n    isApp u' = false ->\n    mkApps u l = mkApps u' l' ->\n    u = u' /\\ l = l'.\nProof.\n  intros u u' l l' h h' e.\n  eapply mkApps_nApp_inj.\n  - rewrite -> 2!isApp_false_nApp by assumption. reflexivity.\n  - assumption.\nQed.\n\nDefinition head x := (decompose_app x).1.\nDefinition arguments x := (decompose_app x).2.\n\nLemma head_arguments x : mkApps (head x) (arguments x) = x.\nProof.\n  unfold head, arguments, decompose_app.\n  remember (decompose_app_rec x []).\n  destruct p as [f l].\n  symmetry in Heqp.\n  eapply decompose_app_rec_inv in Heqp.\n  now simpl in *.\nQed.\n\nLemma fst_decompose_app_rec t l : fst (decompose_app_rec t l) = fst (decompose_app t).\nProof.\n  induction t in l |- *; simpl; auto. rewrite IHt1.\n  unfold decompose_app. simpl. now rewrite (IHt1 [t2]).\nQed.\n\nLemma decompose_app_rec_head t l f : fst (decompose_app_rec t l) = f ->\n  negb (isApp f).\nProof.\n  induction t; unfold isApp; simpl; try intros [= <-]; auto.\n  intros. apply IHt1. now rewrite !fst_decompose_app_rec.\nQed.\n\nLemma head_nApp x : negb (isApp (head x)).\nProof.\n  unfold head.\n  eapply decompose_app_rec_head. reflexivity.\nQed.\n\nLemma head_tapp t1 t2 : head (tApp t1 t2) = head t1.\nProof. rewrite /head /decompose_app /= fst_decompose_app_rec //. Qed.\n\nLemma mkApps_Fix_spec mfix idx args t : mkApps (tFix mfix idx) args = t ->\n                                        match decompose_app t with\n                                        | (tFix mfix idx, args') => args' = args\n                                        | _ => False\n                                        end.\nProof.\n  intros H; apply (f_equal decompose_app) in H.\n  rewrite decompose_app_mkApps in H. reflexivity.\n  destruct t; noconf H. rewrite <- H. reflexivity.\n  simpl. reflexivity.\nQed.\n\nLemma decompose_app_rec_tFix mfix idx args t l :\n  decompose_app_rec t l = (tFix mfix idx, args) -> mkApps t l = mkApps (tFix mfix idx) args.\nProof.\n  unfold decompose_app.\n  revert l args.\n  induction t; intros args l' H; noconf H. simpl in H.\n  now specialize (IHt1 _ _ H).\n  reflexivity.\nQed.\n\nLemma decompose_app_tFix mfix idx args t :\n  decompose_app t = (tFix mfix idx, args) -> t = mkApps (tFix mfix idx) args.\nProof. apply decompose_app_rec_tFix. Qed.\n\nLemma mkApps_eq_head {x l} : mkApps x l = x -> l = [].\nProof.\n  assert (WF : WellFounded (precompose lt PCUICSize.size))\n    by apply wf_precompose, lt_wf.\n  induction l. simpl. constructor.\n  apply apply_noCycle_right. simpl. red. rewrite size_mkApps. simpl. lia.\nQed.\n\nLemma mkApps_eq_inv {x y l} : x = mkApps y l -> size y <= size x.\nProof.\n  assert (WF : WellFounded (precompose lt size))\n    by apply wf_precompose, lt_wf.\n  induction l in x, y |- *. simpl. intros -> ; constructor.\n  simpl. intros. specialize (IHl _ _ H). simpl in IHl. lia.\nQed.\n\nLemma mkApps_eq_left x y l : mkApps x l = mkApps y l -> x = y.\nProof.\n  induction l in x, y |- *; simpl. auto.\n  intros. simpl in *. specialize (IHl _ _ H). now noconf IHl.\nQed.\n\nLemma decompose_app_eq_right t l l' : decompose_app_rec t l = decompose_app_rec t l' -> l = l'.\nProof.\n  induction t in l, l' |- *; simpl; intros [=]; auto.\n  specialize (IHt1 _ _ H0). now noconf IHt1.\nQed.\n\nLemma mkApps_eq_right t l l' : mkApps t l = mkApps t l' -> l = l'.\nProof.\n  intros. eapply (f_equal decompose_app) in H. unfold decompose_app in H.\n  rewrite !decompose_app_rec_mkApps in H. apply decompose_app_eq_right in H.\n  now rewrite !app_nil_r in H.\nQed.\n\nLemma atom_decompose_app t l : ~~ isApp t -> decompose_app_rec t l = pair t l.\nProof. destruct t; simpl; congruence. Qed.\n\nLemma mkApps_eq_inj {t t' l l'} :\n  mkApps t l = mkApps t' l' ->\n  ~~ isApp t -> ~~ isApp t' -> t = t' /\\ l = l'.\nProof.\n  intros Happ Ht Ht'. eapply (f_equal decompose_app) in Happ. unfold decompose_app in Happ.\n  rewrite !decompose_app_rec_mkApps in Happ. rewrite !atom_decompose_app in Happ; auto.\n  rewrite !app_nil_r in Happ. intuition congruence.\nQed.\n\nLtac solve_discr' :=\n  match goal with\n    H : mkApps _ _ = mkApps ?f ?l |- _ =>\n    eapply mkApps_eq_inj in H as [? ?]; [|easy|easy]; subst; try intuition congruence\n  | H : ?t = mkApps ?f ?l |- _ =>\n    change t with (mkApps t []) in H ;\n    eapply mkApps_eq_inj in H as [? ?]; [|easy|easy]; subst; try intuition congruence\n  | H : mkApps ?f ?l = ?t |- _ =>\n    change t with (mkApps t []) in H ;\n    eapply mkApps_eq_inj in H as [? ?]; [|easy|easy]; subst; try intuition congruence\n  end.\n\nLemma mkApps_eq_decompose_app {t t' l l'} :\n  mkApps t l = mkApps t' l' ->\n  decompose_app_rec t l = decompose_app_rec t' l'.\nProof.\n  induction l in t, t', l' |- *; simpl.\n  - intros ->. rewrite !decompose_app_rec_mkApps.\n    now rewrite app_nil_r.\n  - intros H. apply (IHl _ _ _ H).\nQed.\n\nLemma mkApps_eq_decompose {f args t} :\n  mkApps f args = t ->\n  ~~ isApp f ->\n  fst (decompose_app t) = f.\nProof.\n  intros H Happ; apply (f_equal decompose_app) in H.\n  rewrite decompose_app_mkApps in H. auto. rewrite <- H. reflexivity.\nQed.\n\nLtac finish_discr :=\n  repeat match goal with\n         | [ H : ?x = ?x |- _ ] => clear H\n         | [ H : mkApps _ _ = mkApps _ _ |- _ ] =>\n           let H0 := fresh in let H1 := fresh in\n                              specialize (mkApps_eq_inj H eq_refl eq_refl) as [H0 H1];\n                              clear H;\n                              try (congruence || (noconf H0; noconf H1))\n         | [ H : mkApps _ _ = _ |- _ ] => apply mkApps_eq_head in H\n         end.\n\nLtac prepare_discr :=\n  repeat match goal with\n         | [ H : mkApps ?f ?l = tApp ?y ?r |- _ ] => change (mkApps f l = mkApps y [r]) in H\n         | [ H : tApp ?f ?l = mkApps ?y ?r |- _ ] => change (mkApps f [l] = mkApps y r) in H\n         | [ H : mkApps ?x ?l = ?y |- _ ] =>\n           match y with\n           | mkApps _ _ => fail 1\n           | _ => change (mkApps x l = mkApps y []) in H\n           end\n         | [ H : ?x = mkApps ?y ?l |- _ ] =>\n           match x with\n           | mkApps _ _ => fail 1\n           | _ => change (mkApps x [] = mkApps y l) in H\n           end\n         end.\n\n\nInductive mkApps_spec : term -> list term -> term -> list term -> term -> Type :=\n| mkApps_intro f l n :\n    ~~ isApp f ->\n    mkApps_spec f l (mkApps f (firstn n l)) (skipn n l) (mkApps f l).\n\nLemma decompose_app_rec_eq f l :\n  ~~ isApp f ->\n  decompose_app_rec f l = (f, l).\nProof.\n  destruct f; simpl; try discriminate; congruence.\nQed.\n\nLemma decompose_app_rec_inv' f l hd args :\n  decompose_app_rec f l = (hd, args) ->\n  ∑ n, ~~ isApp hd /\\ l = skipn n args /\\ f = mkApps hd (firstn n args).\nProof.\n  destruct (isApp f) eqn:Heq.\n  revert l args hd.\n  induction f; try discriminate. intros.\n  simpl in H.\n  destruct (isApp f1) eqn:Hf1.\n  2:{ rewrite decompose_app_rec_eq in H => //. now apply negbT.\n      revert Hf1.\n      inv H. exists 1. simpl. intuition auto. now eapply negbT. }\n  destruct (IHf1 eq_refl _ _ _ H).\n  clear IHf1.\n  exists (S x); intuition auto. eapply (f_equal (skipn 1)) in H2.\n  rewrite [l]H2. now rewrite skipn_skipn Nat.add_1_r.\n  rewrite -Nat.add_1_r firstn_add H3 -H2.\n  now rewrite -[tApp _ _](mkApps_app hd _ [f2]).\n  rewrite decompose_app_rec_eq; auto. now apply negbT.\n  move=> [] H ->. subst f. exists 0. intuition auto.\n  now apply negbT.\nQed.\n\nLemma mkApps_elim_rec t l l' :\n  let app' := decompose_app_rec (mkApps t l) l' in\n  mkApps_spec app'.1 app'.2 t (l ++ l') (mkApps t (l ++ l')).\nProof.\n  destruct app' as [hd args] eqn:Heq.\n  subst app'.\n  rewrite decompose_app_rec_mkApps in Heq.\n  have H := decompose_app_rec_inv' _ _ _ _ Heq.\n  destruct H. simpl. destruct a as [isapp [Hl' Hl]].\n  subst t.\n  have H' := mkApps_intro hd args x. rewrite Hl'.\n  rewrite -mkApps_app. now rewrite firstn_skipn.\nQed.\n\nLemma mkApps_elim t l  :\n  let app' := decompose_app (mkApps t l) in\n  mkApps_spec app'.1 app'.2 t l (mkApps t l).\nProof.\n  have H := @mkApps_elim_rec t l [].\n  now rewrite app_nil_r in H.\nQed.\n\nLemma nisApp_mkApps {t l} : ~~ isApp (mkApps t l) -> ~~ isApp t /\\ l = [].\nProof.\n  induction l in t |- *; simpl; auto.\n  intros. destruct (IHl _ H). discriminate.\nQed.\n\nLemma mkApps_nisApp {t t' l} : mkApps t l = t' -> ~~ isApp t' -> t = t' /\\ l = [].\nProof.\n  induction l in t |- *; simpl; auto.\n  intros. destruct (IHl _ H). auto. subst. simpl in H0. discriminate.\nQed.\n\nLemma tApp_mkApps_inj f a f' l :\n  tApp f a = mkApps f' l -> l <> [] ->\n  f = mkApps f' (removelast l) /\\ (a = last l a).\nProof.\n  induction l in f' |- *; simpl; intros H. noconf H. intros Hf. congruence.\n  intros . destruct l; simpl in *. now noconf H.\n  specialize (IHl _ H). forward IHl by congruence.\n  apply IHl.\nQed.\n\nDefinition application_atom t :=\n  match t with\n  | tVar _\n  | tSort _\n  | tInd _ _\n  | tConstruct _ _ _\n  | tLambda _ _ _ => true\n  | _ => false\n  end.\n\nLemma application_atom_mkApps {t l} : application_atom (mkApps t l) -> application_atom t /\\ l = [].\nProof.\n  induction l in t |- *; simpl; auto.\n  intros. destruct (IHl _ H). discriminate.\nQed.\n\nLtac solve_discr :=\n  (try (progress (prepare_discr; finish_discr; cbn [mkApps] in * )));\n  (try (match goal with\n        | [ H : is_true (application_atom _) |- _ ] => discriminate\n        | [ H : is_true (application_atom (mkApps _ _)) |- _ ] =>\n          destruct (application_atom_mkApps H); subst; try discriminate\n        end)).\n\n(** Use a coercion for this common projection of the global context. *)\nDefinition fst_ctx : global_env_ext -> global_env := fst.\nCoercion fst_ctx : global_env_ext >-> global_env.\n\nDefinition empty_ext (Σ : global_env) : global_env_ext\n  := (Σ, Monomorphic_ctx).\n\n\nLemma destArity_app_aux {Γ Γ' t}\n  : destArity (Γ ,,, Γ') t = option_map (fun '(ctx, s) => (Γ ,,, ctx, s))\n                                        (destArity Γ' t).\nProof.\n  revert Γ'.\n  induction t; cbn; intro Γ'; try reflexivity.\n  - rewrite <- app_context_cons. now eapply IHt2.\n  - rewrite <- app_context_cons. now eapply IHt3.\nQed.\n\nLemma destArity_app {Γ t}\n  : destArity Γ t = option_map (fun '(ctx, s) => (Γ ,,, ctx, s))\n                               (destArity [] t).\nProof.\n  exact (@destArity_app_aux Γ [] t).\nQed.\n\nLemma destArity_app_Some {Γ t ctx s}\n  : destArity Γ t = Some (ctx, s)\n    -> ∑ ctx', destArity [] t = Some (ctx', s) /\\ ctx = Γ ,,, ctx'.\nProof.\n  intros H. rewrite destArity_app in H.\n  destruct (destArity [] t) as [[ctx' s']|]; cbn in *.\n  exists ctx'. inversion H. now subst.\n  discriminate H.\nQed.\n\nLemma destArity_it_mkProd_or_LetIn ctx ctx' t :\n  destArity ctx (it_mkProd_or_LetIn ctx' t) =\n  destArity (ctx ,,, ctx') t.\nProof.\n  induction ctx' in ctx, t |- *; simpl; auto.\n  rewrite IHctx'. destruct a as [na [b|] ty]; reflexivity.\nQed.\n\nLemma mkApps_nonempty f l :\n  l <> [] -> mkApps f l = tApp (mkApps f (removelast l)) (last l f).\nProof.\n  destruct l using rev_ind. intros; congruence.\n  intros. rewrite mkApps_app. simpl. f_equal.\n  rewrite removelast_app. congruence. simpl. now rewrite app_nil_r.\n  rewrite last_app. congruence.\n  reflexivity.\nQed.\n\nLemma destArity_tFix {mfix idx args} :\n  destArity [] (mkApps (tFix mfix idx) args) = None.\nProof.\n  induction args. reflexivity.\n  rewrite mkApps_nonempty.\n  intros e; discriminate e.\n  reflexivity.\nQed.\n\nLemma destArity_tApp {t u l} :\n  destArity [] (mkApps (tApp t u) l) = None.\nProof.\n  induction l. reflexivity.\n  rewrite mkApps_nonempty.\n  intros e; discriminate e.\n  reflexivity.\nQed.\n\nLemma destArity_tInd {t u l} :\n  destArity [] (mkApps (tInd t u) l) = None.\nProof.\n  induction l. reflexivity.\n  rewrite mkApps_nonempty.\n  intros e; discriminate e.\n  reflexivity.\nQed.\n\nLemma destArity_mkApps_None ctx t l :\n  destArity ctx t = None -> destArity ctx (mkApps t l) = None.\nProof.\n  induction l in t |- *. trivial.\n  intros H. cbn. apply IHl. reflexivity.\nQed.\n\nLemma destArity_mkApps_Ind ctx ind u l :\n  destArity ctx (mkApps (tInd ind u) l) = None.\nProof.\n  apply destArity_mkApps_None. reflexivity.\nQed.\n\n(* Helper for nested recursive functions on well-typed terms *)\n\nSection MapInP.\n  Context {A B : Type}.\n  Context {P : A -> Type}.\n  Context (f : forall (x : A), P x -> B).\n\n  Equations map_InP (l : list A) (H : forall x, In x l -> P x) : list B :=\n  map_InP nil _ := nil;\n  map_InP (cons x xs) H := cons (f x (H x (or_introl eq_refl))) (map_InP xs (fun x inx => H x _)).\nEnd MapInP.\n\nLemma map_InP_spec {A B : Type} {P : A -> Type} (f : A -> B) (l : list A) (H : forall x, In x l -> P x) :\n  map_InP (fun (x : A) (_ : P x) => f x) l H = List.map f l.\nProof.\n  remember (fun (x : A) (_ : P x) => f x) as g.\n  funelim (map_InP g l H) => //; simpl. f_equal.\n  now rewrite H0.\nQed.\n\nLemma nth_error_map_InP {A B : Type} {P : A -> Type} (f : forall x : A, P x -> B) (l : list A) (H : forall x, In x l -> P x) n x :\n  nth_error (map_InP f l H) n = Some x ->\n  ∑ a, (nth_error l n = Some a) *\n  ∑ p : P a, x = f a p.\nProof.\n  induction l in n, H |- *. simpl. rewrite nth_error_nil => //.\n  destruct n; simpl; intros [=].\n  subst x.\n  eexists; intuition eauto.\n  eapply IHl. eapply H1.\nQed.\n\nLemma map_InP_length {A B : Type} {P : A -> Type} (f : forall x : A, P x -> B) (l : list A) (H : forall x, In x l -> P x) :\n  #|map_InP f l H| = #|l|.\nProof.\n  induction l; simpl; auto.\nQed.\n#[global]\nHint Rewrite @map_InP_length : len.\n\n(** Views *)\n\nDefinition isSort T :=\n  match T with\n  | tSort u => true\n  | _ => false\n  end.\n\nInductive view_sort : term -> Type :=\n| view_sort_sort s : view_sort (tSort s)\n| view_sort_other t : ~ isSort t -> view_sort t.\n\nEquations view_sortc (t : term) : view_sort t :=\n  view_sortc (tSort s) := view_sort_sort s;\n  view_sortc t := view_sort_other t _.\n\nDefinition isProd t :=\n  match t with\n  | tProd na A B => true\n  | _ => false\n  end.\n\nInductive view_prod : term -> Type :=\n| view_prod_prod na A b : view_prod (tProd na A b)\n| view_prod_other t : ~ isProd t -> view_prod t.\n\nEquations view_prodc (t : term) : view_prod t :=\n  view_prodc (tProd na A b) := view_prod_prod na A b;\n  view_prodc t := view_prod_other t _.\n\nDefinition isInd (t : term) : bool :=\n  match t with\n  | tInd _ _ => true\n  | _ => false\n  end.\n\nInductive view_ind : term -> Type :=\n| view_ind_tInd ind u : view_ind (tInd ind u)\n| view_ind_other t : negb (isInd t) -> view_ind t.\n\nEquations view_indc (t : term) : view_ind t :=\n  view_indc (tInd ind u) => view_ind_tInd ind u;\n  view_indc t => view_ind_other t _.\n\nInductive view_prod_sort : term -> Type :=\n| view_prod_sort_prod na A B : view_prod_sort (tProd na A B)\n| view_prod_sort_sort u : view_prod_sort (tSort u)\n| view_prod_sort_other t :\n    ~isProd t ->\n    ~isSort t ->\n    view_prod_sort t.\n\nEquations view_prod_sortc (t : term) : view_prod_sort t := {\n  | tProd na A B => view_prod_sort_prod na A B;\n  | tSort u => view_prod_sort_sort u;\n  | t => view_prod_sort_other t _ _\n  }.\n\n\n\nLemma nth_error_ass_subst_context s k Γ :\n  (forall n d, nth_error Γ n = Some d -> decl_body d = None) ->\n  forall n d, nth_error (subst_context s k Γ) n = Some d -> decl_body d = None.\nProof.\n  induction Γ as [|[? [] ?] ?] in |- *; simpl; auto;\n  intros; destruct n; simpl in *; rewrite ?subst_context_snoc in H0; simpl in H0.\n  - noconf H0; simpl.\n    specialize (H 0 _ eq_refl). simpl in H; discriminate.\n  - specialize (H 0 _ eq_refl). simpl in H; discriminate.\n  - noconf H0; simpl. auto.\n  - eapply IHΓ; intros; eauto.\n    now specialize (H (S n0) d0 H1).\nQed.\n\nLemma nth_error_smash_context Γ Δ :\n  (forall n d, nth_error Δ n = Some d -> decl_body d = None) ->\n  forall n d, nth_error (smash_context Δ Γ) n = Some d -> decl_body d = None.\nProof.\n  induction Γ as [|[? [] ?] ?] in Δ |- *; simpl; auto.\n  - intros. eapply (IHΓ (subst_context [t] 0 Δ)); tea.\n    now apply nth_error_ass_subst_context.\n  - intros. eapply IHΓ. 2:eauto.\n    intros.\n    pose proof (nth_error_Some_length H1). autorewrite with len in H2. simpl in H2.\n    destruct (eq_dec n0 #|Δ|).\n    * subst.\n      rewrite nth_error_app_ge in H1; try lia.\n      rewrite Nat.sub_diag /= in H1. noconf H1.\n      reflexivity.\n    * rewrite nth_error_app_lt in H1; try lia. eauto.\nQed.\n\n\nLemma context_assumptions_smash_context Δ Γ :\n  context_assumptions (smash_context Δ Γ) =\n  context_assumptions Δ + context_assumptions Γ.\nProof.\n  induction Γ as [|[? [] ?] ?] in Δ |- *; simpl; auto;\n  rewrite IHΓ.\n  - now rewrite context_assumptions_fold.\n  - rewrite context_assumptions_app /=. lia.\nQed.\n\nLemma context_assumptions_expand_lets_ctx Γ Δ :\n  context_assumptions (expand_lets_ctx Γ Δ) = context_assumptions Δ.\nProof. now rewrite /expand_lets_ctx /expand_lets_k_ctx; len. Qed.\n#[global]\nHint Rewrite context_assumptions_expand_lets_ctx : len.\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/utils/PCUICAstUtils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.2989226068355507}}
{"text": "Require Import TM.Prelim TM.TM.\n\n(** * 0-tape Turing machine that does nothing. *)\n\nSection Mono_Nop.\n\n  Variable sig : finType.\n\n  Definition NullTM : mTM sig 0 :=\n    {|\n      trans := fun '(q, s) => (q, Vector.nil _);\n      start := tt;\n      halt _ := true;\n    |}.\n\n  Definition Null : pTM sig unit 0 := (NullTM; fun _ => tt).\n\n  Definition Null_Rel : pRel sig unit 0 :=\n    ignoreParam (fun t t' => True).\n\n  Lemma Null_Sem: Null ⊨c(0) Null_Rel.\n  Proof. intros t. cbn. unfold initc; cbn. eexists (mk_mconfig _ _); cbn; eauto. Qed.\n\nEnd Mono_Nop.\n\nArguments Null : simpl never.\nArguments Null {sig}.\nArguments Null_Rel { sig } x y / : rename.\n\n\n(** ** Tactic Support *)\n\nLtac smpl_TM_Null :=\n  lazymatch goal with\n  | [ |- Null ⊨ _] => eapply RealiseIn_Realise; eapply Null_Sem\n  | [ |- Null ⊨c(_) _] => eapply Null_Sem\n  | [ |- projT1 (Null) ↓ _] => eapply RealiseIn_TerminatesIn; eapply Null_Sem\n  end.\n\nSmpl Add smpl_TM_Null : 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/Null.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.2989045221934243}}
{"text": "(** * Leaves of an Interaction Tree *)\n\n(* begin hide *)\nFrom ITree Require Import\n     Basics.Tacs\n     Basics.HeterogeneousRelations\n     ITree\n     Eq.Shallow\n     Eq.Eqit\n     Interp.InterpFacts\n     Events.State\n     Events.StateFacts\n     Props.HasPost.\n\nFrom Paco Require Import paco.\nFrom Coq Require Import Morphisms Basics Program.Equality.\nImport ITree.\nImport ITreeNotations.\n(* end hide *)\n\n(** ** Leaves of itrees *)\n\n(** The [Leaf a t] predicate expresses that [t] has a [Ret] leaf with\n    value [a].\n\n    We provide the elementary structural lemmas to work with this\n    predicate, and one main useful result relying on [Leaf]: the\n    up-to bind closure [eqit_bind_clo] can be refined such that\n    continuations need only be related over the leaves of the\n    first operand of [bind].\n    *)\n\nInductive Leaf {E} {A: Type} (a: A) : itree E A -> Prop :=\n | LeafRet: forall t,\n   observe t = RetF a ->\n   Leaf a t\n | LeafTau: forall t u,\n   observe t = TauF u ->\n   Leaf a u ->\n   Leaf a t\n | LeafVis: forall {X} (e: E X) t k x,\n   observe t = VisF e k ->\n   Leaf a (k x) ->\n   Leaf a t\n.\n#[global] Hint Constructors Leaf : itree.\n\nModule LeafNotations.\n  Notation \"a ∈ t\" := (Leaf a t) (at level 70).\nEnd LeafNotations.\n\nImport LeafNotations.\n\n(** Smart constructors *)\n\nLemma Leaf_Ret : forall E R a,\n  a ∈ (Ret a : itree E R).\nProof.\n  intros; econstructor; reflexivity.\nQed.\n\nLemma Leaf_Tau : forall E R a t,\n  a ∈ (t : itree E R) ->\n  a ∈ Tau t.\nProof.\n  intros; econstructor; [reflexivity | eauto].\nQed.\n\nLemma Leaf_Vis : forall E X Y (e : E X) (k : _ -> itree E Y) b x,\n  b ∈ (k x) ->\n  b ∈ (Vis e k).\nProof.\n  intros * IN; econstructor 3; [reflexivity | eauto].\nQed.\n\n(** Inversion lemmas *)\nLemma Leaf_Ret_inv : forall E R (a b : R),\n  Leaf (E := E) b (Ret a) ->\n  b = a.\nProof.\n  intros * IN; inv IN; cbn in *; try congruence.\nQed.\n\nLemma Leaf_Tau_inv : forall E R (u : itree E R) b,\n  b ∈ Tau u ->\n  b ∈ u.\nProof.\n  intros * IN; inv IN; cbn in *; try congruence.\nQed.\n\nLemma Leaf_Vis_inv : forall E X Y (e : E X) (k : _ -> itree E Y) b,\n  b ∈ Vis e k ->\n  exists x, b ∈ k x.\nProof.\n  intros * IN *; inv IN; cbn in *; try congruence.\n  revert x H0.\n  refine (match H in _ = u return match u with VisF e0 k0 => _ | RetF _ | TauF _ => False end with eq_refl => _ end).\n  eauto.\nQed.\n\n(** Closure under [eutt]\n\n  General asymmetric lemmas for [eutt R], where we naturally get\n  a different point related by [R], and [Proper] instances for\n  [eutt eq]. *)\n\nLemma Leaf_eutt_l {E A B R}:\n  forall (t : itree E A) (u : itree E B) (a : A),\n  eutt R t u ->\n  a ∈ t ->\n  exists b, b ∈ u /\\ R a b.\nProof.\n  intros * EQ FIN;\n  revert u EQ.\n  induction FIN; intros u2 EQ.\n  - punfold EQ.\n    red in EQ; rewrite H in EQ; clear H t.\n    remember (RetF a); genobs u2 ou.\n    hinduction EQ before R; intros; try now discriminate.\n    + inv Heqi; eauto with itree.\n    + edestruct IHEQ as (b & IN & HR); eauto with itree.\n  - punfold EQ; red in EQ; rewrite H in EQ; clear H t.\n    remember (TauF u); genobs u2 ou2.\n    hinduction EQ before R; intros; try discriminate; pclearbot; inv Heqi.\n    + edestruct IHFIN as (? & ? & ?); [ .. | eexists ]; eauto with itree.\n    + eauto with itree.\n    + edestruct IHEQ as (? & ? & ?); [ .. | eexists ]; eauto with itree.\n  - punfold EQ; red in EQ; rewrite H in EQ; clear H t.\n    remember (VisF e k); genobs u2 ou2.\n    hinduction EQ before R; intros; try discriminate; pclearbot.\n    + revert x FIN IHFIN.\n      refine (match Heqi in _ = u return match u with VisF e0 k0 => _ | RetF _ | TauF _ => False end with eq_refl => _ end).\n      intros. edestruct IHFIN as (? & ? & ?); [ | eexists ]; eauto with itree.\n    + edestruct IHEQ as (? & ? & ?); [.. | exists x0 ]; eauto with itree.\nQed.\n\nLemma Leaf_eutt_r {E A B R}:\n  forall (t : itree E A) (u : itree E B) (b : B),\n  eutt R t u ->\n  b ∈ u ->\n  exists a, a ∈ t /\\ R a b.\nProof.\n  intros * EQ FIN.\n  apply eqit_flip in EQ.\n  revert EQ FIN.\n  apply @Leaf_eutt_l.\nQed.\n\n#[global] Instance Leaf_eutt {E A}:\n  Proper (eq ==> eutt eq ==> iff) (@Leaf E A).\nProof.\n  apply proper_sym_impl_iff_2; [ exact _ .. | ].\n  unfold Proper, respectful, impl. intros; subst.\n  edestruct @Leaf_eutt_l as [? []]; try eassumption; subst; assumption.\nQed.\n\n(** Compatibility with [bind], forward and backward *)\n\nLemma Leaf_bind : forall {E R S}\n  (t : itree E R) (k : R -> itree E S) a b,\n  b ∈ t ->\n  a ∈ k b ->\n  a ∈ t >>= k.\nProof.\n  intros * INt INk; induction INt.\n  - rewrite (itree_eta t), H, bind_ret_l; auto.\n  - rewrite (itree_eta t), H, tau_eutt; auto.\n  - rewrite (itree_eta t), H, bind_vis.\n    apply Leaf_Vis with x; auto.\nQed.\n\nLemma Leaf_bind_inv : forall {E R S}\n  (t : itree E R) (k : R -> itree E S) a,\n  a ∈ t >>= k ->\n  exists b, b ∈ t /\\ a ∈ k b.\nProof.\n  intros * FIN;\n  remember (ITree.bind t k) as u.\n  revert t k Hequ.\n  induction FIN; intros t' k' ->; rename t' into t.\n  - unfold observe in H; cbn in H.\n    desobs t EQ; cbn in *; try congruence.\n    exists r; auto with itree.\n  - unfold observe in H; cbn in H.\n    desobs t EQ; cbn in *; try congruence; [ eexists; eauto with itree | ].\n    inversion H; clear H; symmetry in H1.\n    edestruct IHFIN as (? & ? & ?); [ eauto | eexists; eauto with itree ].\n  - unfold observe in H; cbn in H.\n    desobs t EQ; cbn in *; try congruence; [ eexists; eauto with itree | ].\n    revert x FIN IHFIN.\n    refine (match H in _ = u return match u with VisF e0 k0 => _ | RetF _ | TauF _ => False end with eq_refl => _ end).\n    intros.\n    edestruct IHFIN as (? & ? & ?); [ reflexivity | eexists; eauto with itree ].\nQed.\n\n(** Leaf-aware up-to bind closure\n    This construction generalizes [eqit_bind_clo]: one can\n    indeed provide an arbitrary cut at the relational\n    redicate [RU] of one's choice, but the continuations\n    are only required to be related pointwise at the intersection\n    of [RU] with the respective leaves of the prefixes.\n  *)\nSection LeafBind.\n\n  Context {E : Type -> Type} {R S : Type}.\n\n  Local Open Scope itree.\n\n  Inductive eqit_Leaf_bind_clo b1 b2 (r : itree E R -> itree E S -> Prop) :\n    itree E R -> itree E S -> Prop :=\n  | pbc_intro_h U1 U2 (RU : U1 -> U2 -> Prop)\n                (t1 : itree E U1) (t2 : itree E U2)\n                 (k1 : U1 -> itree E R) (k2 : U2 -> itree E S)\n                (EQV: eqit RU b1 b2 t1 t2)\n                (REL: forall u1 u2,\n                      u1 ∈ t1 -> u2 ∈ t2 -> RU u1 u2 ->\n                      r (k1 u1) (k2 u2))\n      : eqit_Leaf_bind_clo b1 b2 r\n            (ITree.bind t1 k1) (ITree.bind t2 k2)\n    .\n  Hint Constructors eqit_Leaf_bind_clo : itree.\n\n  Lemma eqit_Leaf_clo_bind  (RS : R -> S -> Prop) b1 b2 vclo\n        (MON: monotone2 vclo)\n        (CMP: compose (eqitC RS b1 b2) vclo <3= compose vclo (eqitC RS b1 b2))\n        (ID: id <3= vclo):\n    eqit_Leaf_bind_clo b1 b2 <3= gupaco2 (eqit_ RS b1 b2 vclo) (eqitC RS b1 b2).\n  Proof.\n    gcofix CIH. intros. destruct PR.\n    guclo eqit_clo_trans.\n    econstructor; auto_ctrans_eq; try (rewrite (itree_eta (x <- _;; _ x)), unfold_bind; reflexivity).\n    punfold EQV. unfold_eqit.\n    genobs t1 ot1.\n    genobs t2 ot2.\n    hinduction EQV before CIH; intros; pclearbot.\n    - guclo eqit_clo_trans.\n      econstructor; auto_ctrans_eq; try (rewrite <- !itree_eta; reflexivity).\n      gbase; cbn.\n      apply REL0; auto with itree.\n    - gstep. econstructor.\n      gbase.\n      apply CIH.\n      econstructor; eauto with itree.\n    - gstep. econstructor.\n      intros; apply ID; unfold id.\n      gbase.\n      apply CIH.\n      econstructor; eauto with itree.\n    - destruct b1; try discriminate.\n      guclo eqit_clo_trans.\n      econstructor.\n      3:{ eapply IHEQV; eauto with itree. }\n      3,4:auto_ctrans_eq.\n      2: reflexivity.\n      eapply eqit_Tau_l. rewrite unfold_bind, <-itree_eta. reflexivity.\n    - destruct b2; try discriminate.\n      guclo eqit_clo_trans.\n      econstructor; auto_ctrans_eq; eauto with itree; try reflexivity.\n      eapply eqit_Tau_l. rewrite unfold_bind, <-itree_eta. reflexivity.\n  Qed.\n\nEnd LeafBind.\n\n(** General cut rule for [eqit]\n    This result generalizes [eqit_clo_bind].  *)\nLemma eqit_clo_bind_gen :\n  forall {E} {R1 R2} (RR : R1 -> R2 -> Prop) {U1 U2} {UU : U1 -> U2 -> Prop}\n          b1 b2\n           (t1 : itree E U1) (t2 : itree E U2)\n          (k1 : U1 -> itree E R1) (k2 : U2 -> itree E R2),\n    eqit UU b1 b2 t1 t2 ->\n    (forall (u1 : U1) (u2 : U2),\n      u1 ∈ t1 -> u2 ∈ t2 -> UU u1 u2 ->\n      eqit RR b1 b2 (k1 u1) (k2 u2)) ->\n    eqit RR b1 b2 (x <- t1;; k1 x) (x <- t2;; k2 x).\nProof.\n    intros.\n    ginit. guclo (@eqit_Leaf_clo_bind E R1 R2).\n    econstructor; eauto.\n    intros * IN1 IN2 HR.\n    gfinal; right.\n    apply H0; auto.\nQed.\n\n(** Specialization of the cut rule to [eutt] *)\nLemma eutt_clo_bind_gen :\n  forall {E} {R1 R2} (RR : R1 -> R2 -> Prop) {U1 U2} {UU : U1 -> U2 -> Prop}\n           (t1 : itree E U1) (t2 : itree E U2)\n          (k1 : U1 -> itree E R1) (k2 : U2 -> itree E R2),\n    eutt UU t1 t2 ->\n    (forall (u1 : U1) (u2 : U2),\n      u1 ∈ t1 -> u2 ∈ t2 -> UU u1 u2 ->\n      eutt RR (k1 u1) (k2 u2)) ->\n    eutt RR (x <- t1;; k1 x) (x <- t2;; k2 x).\nProof.\n  intros *; apply eqit_clo_bind_gen.\nQed.\n\n(** Often useful particular case of identical prefixes *)\nLemma eutt_eq_bind_gen {E R S T} (RS : R -> S -> Prop)\n      (t: itree E T) (k1: T -> itree E R) (k2 : T -> itree E S) :\n    (forall u, u ∈ t -> eutt RS (k1 u) (k2 u)) ->\n    eutt RS (t >>= k1) (t >>= k2).\nProof.\n  intros; eapply eutt_clo_bind_gen.\n  reflexivity.\n  intros * IN _ <-; eauto.\nQed.\n\nLemma eqit_bind_Leaf_inv {E} {R S T} (RS : R -> S -> Prop)\n      (t : itree E T)  (k1: T -> itree E R) (k2 : T -> itree E S) :\n  (eutt RS  (ITree.bind t k1) (ITree.bind t k2)) ->\n  (forall r, Leaf r t -> eutt RS (k1 r) (k2 r)).\nProof.\n  intros EQIT r HRET.\n  revert k1 k2 EQIT.\n  induction HRET; intros;\n    rewrite 2 unfold_bind, H in EQIT.\n  - assumption.\n  - rewrite 2 tau_eutt in EQIT. auto.\n  - apply IHHRET. eapply eqit_inv_Vis in EQIT; eauto.\nQed.\n\n(** Correspondence with has_post *)\n\nLemma has_post_Leaf {E R} (t: itree E R) Q r:\n  has_post t Q -> r ∈ t -> Q r.\nProof.\n  intros Hcond Himage.\n  rewrite has_post_post_strong in Hcond.\n  destruct (Leaf_eutt_l t t r Hcond Himage).\n  intuition; now subst.\nQed.\n\nLemma has_post_Leaf_equiv {E R} (t: itree E R) Q:\n  has_post t Q <-> (forall r, r ∈ t -> Q r).\nProof.\n  intuition. eapply has_post_Leaf; eauto.\n  revert t H. pcofix CIH; intros t Hpost. pstep; red.\n  setoid_rewrite (itree_eta t) in Hpost.\n  desobs t Ht; clear t Ht.\n  - constructor. apply Hpost, Leaf_Ret.\n  - constructor. right; apply CIH. intros. apply Hpost, Leaf_Tau, H.\n  - constructor. intros. right. apply CIH. intros. eapply Hpost, Leaf_Vis, H.\nQed.\n\n(** Leaf-based inversion principles for iter *)\n\n(* Inverts [r ∈ ITree.iter body entry] into any post-condition on r which is\n   satisfied by terminating iterations of the body. *)\nLemma Leaf_iter_inv {E R I}:\n  forall (body: I -> itree E (I + R)) (entry: I) (Inv: I -> Prop) (Q: R -> Prop),\n  (forall i r, Inv i -> r ∈ body i -> sum_pred Inv Q r) ->\n  Inv entry ->\n  forall r, r ∈ (ITree.iter body entry) -> Q r.\nProof.\n  intros * Hinv Hentry.\n  rewrite <- has_post_Leaf_equiv.\n  eapply has_post_iter_strong; eauto.\n  setoid_rewrite has_post_Leaf_equiv. eauto.\nQed.\n\nLemma Leaf_interp_iter_inv {E F R I} (h: E ~> itree F):\n  forall (body: I -> itree E (I + R)) (entry: I) (Inv: I -> Prop) (Q: R -> Prop),\n  (forall i r, Inv i -> r ∈ interp h (body i) -> sum_pred Inv Q r) ->\n  Inv entry ->\n  forall r, r ∈ interp h (ITree.iter body entry) -> Q r.\nProof.\n  intros * Hbody Hentry r Hr.\n  apply (Leaf_iter_inv (fun i => interp h (body i)) entry Inv); auto.\n  rewrite (interp_iter'  _ _ (fun i => interp h (body i))) in Hr.\n  apply Hr. reflexivity.\nQed.\n\n(* Inverts [sr' ∈ interp_state h (ITree.iter body i)] into a post-condition on\n   both retun value and state, like Leaf_iter_inv. *)\nLemma Leaf_interp_state_iter_inv {E F S R I}:\n  forall (h: E ~> Monads.stateT S (itree F)) (body: I -> itree E (I + R))\n         (RS: S -> Prop) (RI: I -> Prop) (RR: R -> Prop) (s: S) (i: I),\n  (forall s i, RS s -> RI i -> (forall sx', sx' ∈ interp_state h (body i) s ->\n                    prod_pred RS (sum_pred RI RR) sx')) ->\n  RS s -> RI i ->\n  forall sr', sr' ∈ interp_state h (ITree.iter body i) s -> prod_pred RS RR sr'.\nProof.\n  setoid_rewrite <- has_post_Leaf_equiv.\n  setoid_rewrite has_post_post_strong.\n  intros * Hinv Hentrys Hentryi.\n  set (eRI := fun (i1 i2: I) => i1 = i2 /\\ RI i1).\n  set (eRR := fun (r1 r2: R) => r1 = r2 /\\ RR r1).\n  set (eRS := fun (s1 s2: S) => s1 = s2 /\\ RS s1).\n\n  set (R1 := (fun x y : S * R => x = y /\\ prod_pred RS RR x)).\n  set (R2 := (fun a b : S * R => eRS (fst a) (fst b) /\\ eRR (snd a) (snd b))).\n  assert (HR1R2: eq_rel R1 R2) by (compute; intuition; subst; now try destruct y).\n  unfold has_post_strong; fold R1; rewrite (eutt_equiv _ _ HR1R2).\n\n  unshelve eapply (eutt_interp_state_iter eRI eRR eRS h body body _ i i s s _ _);\n  [| subst eRS; intuition | subst eRI; intuition].\n  intros i1 ? s1 ? [<- Hs1] [<- Hi1].\n\n  set (R3 := (fun x y : S * (I + R) => x = y /\\ prod_pred RS (sum_pred RI RR) x)).\n  set (R4 := (prod_rel eRS (sum_rel eRI eRR))).\n  assert (HR3R4: eq_rel R3 R4).\n  { split; intros [? [|]] [? [|]]; compute.\n    1-4: intros [[]]; dintuition; cbn; intuition.\n    all: intros [[[=->] ?] HZ]; inversion HZ; intuition now subst. }\n\n  rewrite <- (eutt_equiv _ _ HR3R4).\n  now apply Hinv.\nQed.\n\n(** Inversion of Leaf through interp.\n    Since interp does not change leaves, we have [x ∈ interp h t -> x ∈ t].\n    However this is not easy to see from the Leaf predicate; we must use t. *)\n\nModule Subtree.\n\nInductive subtree {E R}: itree E R -> itree E R -> Prop :=\n  | SubtreeRefl u t:\n      u ≅ t -> subtree u t\n  | SubtreeTau u t:\n      subtree (Tau u) t -> subtree u t\n  | SubtreeVis {T} u (e: E T) k x t:\n      u ≅ k x -> subtree (Vis e k) t -> subtree u t.\n\n#[global] Instance subtree_cong_eqitree {E R}:\n  Proper (eq_itree eq ==> eq_itree eq ==> flip impl) (@subtree E R).\nProof.\n  intros t t' Ht u u' Hu Hsub.\n  revert t Ht u Hu; induction Hsub; intros.\n  - apply SubtreeRefl. now rewrite Ht, Hu.\n  - apply SubtreeTau, IHHsub; auto. apply eqit_Tau, Ht.\n  - eapply SubtreeVis. now rewrite Ht, H. apply IHHsub; auto. reflexivity.\nQed.\n\nLemma subtree_image {E R} (t u: itree E R) x:\n  subtree u t -> x ∈ u -> x ∈ t.\nProof.\n  intros * Hsub. induction Hsub; intros.\n  - intros. rewrite <- H; auto.\n  - apply IHHsub, Leaf_Tau, H.\n  - eapply IHHsub, Leaf_Vis. rewrite H in H0; eauto.\nQed.\n\nLemma Leaf_interp_subtree_inv {E F R} (h: E ~> itree F) (t u: itree E R):\n  subtree u t -> has_post (interp h u) (fun x : R => x ∈ t).\nProof.\n  revert t u. ginit. gcofix CIH; intros * Hsub.\n  rewrite (itree_eta u) in Hsub.\n  rewrite ! unfold_interp.\n  desobs u Hu; clear u Hu; cbn.\n  - gstep; red. constructor. eapply subtree_image; eauto. apply Leaf_Ret.\n  - gstep; red. constructor. gfinal; left. apply CIH. apply SubtreeTau, Hsub.\n  - guclo eqit_clo_bind; econstructor. reflexivity. intros u _ <-.\n    gstep; red. constructor. gfinal; left. apply CIH. eapply SubtreeVis, Hsub.\n    reflexivity.\nQed.\n\nLemma Leaf_interp_state_subtree_inv {E F S R} (h: E ~> Monads.stateT S (itree F))\n  (t u: itree E R) (s: S):\n  subtree u t -> has_post (interp_state h u s) (fun x => snd x ∈ t).\nProof.\n  revert t u s. ginit. gcofix CIH; intros * Hsub.\n  rewrite (itree_eta u) in Hsub.\n  rewrite ! unfold_interp_state.\n  desobs u Hu; clear u Hu; cbn.\n  - gstep; red. constructor. eapply subtree_image; eauto. apply Leaf_Ret.\n  - gstep; red. constructor. gfinal; left. apply CIH. apply SubtreeTau, Hsub.\n  - guclo eqit_clo_bind; econstructor. reflexivity. intros [u1 u2] _ <-; cbn.\n    gstep; red. constructor. gfinal; left. apply CIH. eapply SubtreeVis, Hsub.\n    reflexivity.\nQed.\n\nEnd Subtree.\nImport Subtree.\n\nLemma Leaf_interp_inv {E F R} (h: E ~> itree F) (t: itree E R) x:\n  x ∈ interp h t -> x ∈ t.\nProof.\n  intros Hleaf. apply (has_post_Leaf (interp h t) (fun x => x ∈ t)); auto.\n  apply Leaf_interp_subtree_inv. apply SubtreeRefl; reflexivity.\nQed.\n\nLemma Leaf_interp_state_inv {E F S R} (h: E ~> Monads.stateT S (itree F))\n  (t: itree E R) s x:\n  x ∈ interp_state h t s -> snd x ∈ t.\nProof.\n  intros Hleaf.\n  apply (has_post_Leaf (interp_state h t s) (fun x => snd x ∈ t)); auto.\n  apply Leaf_interp_state_subtree_inv. apply SubtreeRefl; reflexivity.\nQed.\n\n(** Inversion through translate. *)\n\nLemma Leaf_translate_inv {E F R} `{Inj: E -< F}: forall (t: itree E R) v,\n  v ∈ translate (@subevent E F _) t -> v ∈ t.\nProof.\n  intros. rewrite translate_to_interp in H.\n  eapply Leaf_interp_inv; eauto.\nQed.\n", "meta": {"author": "DeepSpec", "repo": "InteractionTrees", "sha": "8e28e2ee08496c696e03916a22d93c39559a9715", "save_path": "github-repos/coq/DeepSpec-InteractionTrees", "path": "github-repos/coq/DeepSpec-InteractionTrees/InteractionTrees-8e28e2ee08496c696e03916a22d93c39559a9715/theories/Props/Leaf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5506073655352403, "lm_q1q2_score": 0.2989045221934242}}
{"text": "(**\nThis file is part of the Coquelicot formalization of real\nanalysis in Coq: http://coquelicot.saclay.inria.fr/\n\nCopyright (C) 2011-2015 Sylvie Boldo\n#<br />#\nCopyright (C) 2011-2015 Catherine Lelay\n#<br />#\nCopyright (C) 2011-2015 Guillaume Melquiond\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 3 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nCOPYING file for more details.\n*)\n\nRequire Import Reals Psatz.\nRequire Import mathcomp.ssreflect.ssreflect Rbar.\nRequire Import Rcomplements.\nRequire Import Lim_seq Continuity Derive Series.\nRequire Import Lub Hierarchy.\n\n(** This file describes sequences of functions and results about\ntheir convergence. *)\n\nOpen Scope R_scope.\n\n(** * Sequence of functions *)\n\n(** ** Definitions *)\n\nDefinition CVS_dom (fn : nat -> R -> R) (D : R -> Prop) :=\n  forall x : R, D x -> ex_finite_lim_seq (fun n => fn n x).\n\nDefinition CVU_dom (fn : nat -> R -> R) (D : R -> Prop) :=\n  forall eps : posreal, eventually (fun n => forall x : R,\n    D x -> Rabs ((fn n x) - real (Lim_seq (fun n => fn n x))) < eps).\nDefinition CVU_cauchy (fn : nat -> R -> R) (D : R -> Prop) :=\n  forall eps : posreal, exists N : nat,\n  forall (n m : nat) (x : R), D x -> (N <= n)%nat -> (N <= m)%nat\n    -> Rabs (fn n x - fn m x) < eps.\n\n(** Equivalence with standard library *)\n\nLemma CVU_dom_Reals (fn : nat -> R -> R) (f : R -> R) (x : R) (r : posreal) :\n  (forall y, (Boule x r y) -> (Finite (f y)) = Lim_seq (fun n => fn n y)) ->\n  (CVU fn f x r <-> CVU_dom fn (Boule x r)).\nProof.\n  split ; move => Hcvu.\n  have Hf : forall y, Boule x r y -> is_lim_seq (fun n => fn n y) (f y).\n    move => y Hy.\n    apply is_lim_seq_spec.\n    move => [e He] /=.\n    case: (Hcvu e He) => {Hcvu} N Hcvu.\n    exists N => n Hn.\n    rewrite -Ropp_minus_distr' Rabs_Ropp.\n    by apply Hcvu.\n  move => [e He] /=.\n  case: (Hcvu e He) => {Hcvu} N Hcvu.\n  exists N => n Hn y Hy.\n  rewrite (is_lim_seq_unique (fun n0 : nat => fn n0 y) _ (Hf y Hy)).\n  simpl.\n  rewrite -/(Rminus (fn n y) (f y)) -Ropp_minus_distr' Rabs_Ropp.\n  by apply Hcvu.\n\n  move => e He ; set eps := mkposreal e He.\n  case: (Hcvu eps) => {Hcvu} N Hcvu.\n  exists N => n y Hn Hy.\n  move: (Hcvu n Hn y Hy).\n  rewrite -(H y Hy) /=.\n  by rewrite -Ropp_minus_distr' Rabs_Ropp.\nQed.\n\n(** Various inclusions and equivalences between definitions *)\n\nLemma CVU_CVS_dom (fn : nat -> R -> R) (D : R -> Prop) :\n  CVU_dom fn D -> CVS_dom fn D.\nProof.\n  move => Hcvu x Hx.\n  exists (real (Lim_seq (fun n => fn n x))).\n  apply is_lim_seq_spec.\n  intros eps.\n  case: (Hcvu eps) => {Hcvu} N Hcvu.\n  exists N => n Hn.\n  by apply Hcvu.\nQed.\nLemma CVU_dom_cauchy (fn : nat -> R -> R) (D : R -> Prop) :\n  CVU_dom fn D <-> CVU_cauchy fn D.\nProof.\n  split => H eps.\n(* CVU_dom -> CVU_cauchy *)\n  case: (H (pos_div_2 eps)) => {H} N /= H.\n  exists N => n m x Hx Hn Hm.\n  rewrite (double_var eps).\n  replace (fn n x - fn m x)\n    with ((fn n x - real (Lim_seq (fun n0 : nat => fn n0 x)))\n      - (fn m x - real (Lim_seq (fun n0 : nat => fn n0 x))))\n    by ring.\n  apply Rle_lt_trans with (1 := Rabs_triang _ _) ; rewrite Rabs_Ropp.\n  apply Rplus_lt_compat ; by apply H.\n(* CVU_cauchy -> CVU_dom *)\n  rewrite /Lim_seq.\n  case: (H (pos_div_2 eps)) => {H} N /= H.\n  exists N => n Hn x Hx.\n  rewrite /LimSup_seq ; case: ex_LimSup_seq ; case => [ls | | ] /= Hls.\n  rewrite /LimInf_seq ; case: ex_LimInf_seq ; case => [li | | ] /= Hli.\n  replace (fn n x - (ls + li) / 2)\n    with (((fn n x - ls) + (fn n x - li))/2)\n    by field.\n  rewrite Rabs_div ; [ | by apply Rgt_not_eq, Rlt_R0_R2].\n  rewrite (Rabs_pos_eq 2) ; [ | by apply Rlt_le, Rlt_R0_R2].\n  rewrite Rlt_div_l ; [ | by apply Rlt_R0_R2].\n  apply Rle_lt_trans with (1 := Rabs_triang _ _).\n  replace (eps * 2) with (eps + eps) by ring.\n  apply Rplus_lt_compat ; apply Rabs_lt_between'.\n  case: (Hls (pos_div_2 eps)) => {Hls Hli} /= H0 [N0 H1] ; split.\n  case: (H0 N) => {H0} m [Hm H0].\n  apply Rlt_trans with (fn m x - eps/2).\n  replace (ls - eps)\n    with ((ls - eps / 2) - eps/2)\n    by field.\n  by apply Rplus_lt_compat_r.\n  replace (fn n x) with (eps/2 + (fn n x - eps/2)) by ring.\n  replace (fn m x - eps / 2) with ((fn m x - fn n x) + (fn n x - eps/2)) by ring.\n  apply Rplus_lt_compat_r.\n  apply Rle_lt_trans with (1 := Rle_abs _) ; by apply H.\n  apply Rlt_trans with (fn (n+N0)%nat x + eps/2).\n  replace (fn n x) with (fn (n + N0)%nat x + (fn n x - fn (n+N0)%nat x)) by ring.\n  apply Rplus_lt_compat_l.\n  apply Rle_lt_trans with (1 := Rle_abs _).\n  apply H ; by intuition.\n  replace (ls + eps) with ((ls + eps/2) + eps/2) by field.\n  apply Rplus_lt_compat_r.\n  apply H1 ; by intuition.\n  case: (Hli (pos_div_2 eps)) => {Hls Hli} /= H0 [N0 H1] ; split.\n  apply Rlt_trans with (fn (n+N0)%nat x - eps/2).\n  replace (li - eps) with ((li - eps/2) - eps/2) by field.\n  apply Rplus_lt_compat_r.\n  apply H1 ; by intuition.\n  replace (fn n x) with (eps/2 + (fn n x - eps/2)) by ring.\n  replace (fn (n + N0)%nat x - eps / 2)\n    with ((fn (n + N0)%nat x - fn n x) + (fn n x - eps/2))\n    by ring.\n  apply Rplus_lt_compat_r.\n  apply Rle_lt_trans with (1 := Rle_abs _).\n  apply H ; by intuition.\n  case: (H0 N) => {H0} m [Hm H0].\n  apply Rlt_trans with (fn m x + eps/2).\n  replace (fn n x) with (fn m x + (fn n x - fn m x)) by ring.\n  apply Rplus_lt_compat_l.\n  apply Rle_lt_trans with (1 := Rle_abs _) ; by apply H.\n  replace (li + eps)\n    with ((li + eps / 2) + eps/2)\n    by field.\n  by apply Rplus_lt_compat_r.\n  case: (Hli (fn n x + eps / 2)) => {Hls Hli} N0 H0.\n  move: (H0 _ (le_plus_r N N0)) => {H0} H0 ; contradict H0.\n  apply Rle_not_lt, Rlt_le.\n  replace (fn (N + N0)%nat x)\n    with (fn n x + (fn (N + N0)%nat x - fn n x))\n    by ring.\n  apply Rplus_lt_compat_l.\n  apply Rle_lt_trans with (1 := Rle_abs _).\n  apply H ; by intuition.\n  case: (Hli (fn n x - eps / 2) N) => {Hls Hli} m [Hm H0].\n  contradict H0.\n  apply Rle_not_lt, Rlt_le.\n  replace (fn m x) with (eps/2 + (fn m x - eps/2)) by ring.\n  replace (fn n x - eps / 2)\n    with ((fn n x - fn m x) + (fn m x - eps/2)) by ring.\n  apply Rplus_lt_compat_r, Rle_lt_trans with (1 := Rle_abs _) ; by apply H.\n  case: (Hls (fn n x + eps / 2) N) => {Hls} m [Hm H0].\n  contradict H0.\n  apply Rle_not_lt, Rlt_le.\n  replace (fn m x) with (fn n x + (fn m x - fn n x)) by ring.\n  apply Rplus_lt_compat_l, Rle_lt_trans with (1 := Rle_abs _) ; by apply H.\n  case: (Hls (fn n x - eps / 2)) => {Hls} N0 H0.\n  move: (H0 _ (le_plus_r N N0)) => {H0} H0 ; contradict H0.\n  apply Rle_not_lt, Rlt_le.\n  replace (fn (N + N0)%nat x)\n    with (eps/2 + (fn (N + N0)%nat x - eps/2))\n    by ring.\n  replace (fn n x - eps / 2)\n    with ((fn n x - fn (N+N0)%nat x) + (fn (N+N0)%nat x - eps/2)) by ring.\n  apply Rplus_lt_compat_r.\n  apply Rle_lt_trans with (1 := Rle_abs _).\n  apply H ; by intuition.\nQed.\n\nLemma CVU_dom_include (fn : nat -> R -> R) (D1 D2 : R -> Prop) :\n  (forall y, D2 y -> D1 y) -> CVU_dom fn D1 -> CVU_dom fn D2.\nProof.\n  move => H H1 eps.\n  case: (H1 eps) => {H1} N H1.\n  exists N => n Hn x Hx.\n  apply H1.\n  exact Hn.\n  by apply H.\nQed.\n\n(** ** Limits, integrals and differentiability *)\n\nDefinition is_connected (D : R -> Prop) :=\n  forall a b x, D a -> D b -> a <= x <= b -> D x.\n\nLemma CVU_limits_open (fn : nat -> R -> R) (D : R -> Prop) :\n  open D\n  -> CVU_dom fn D\n  -> (forall x n, D x -> ex_finite_lim (fn n) x)\n  -> forall x, D x -> ex_finite_lim_seq (fun n => real (Lim (fn n) x))\n    /\\ ex_finite_lim (fun y => real (Lim_seq (fun n => fn n y))) x\n    /\\ real (Lim_seq (fun n => real (Lim (fn n) x)))\n      = real (Lim (fun y => real (Lim_seq (fun n => fn n y))) x).\nProof.\n  move => Ho Hfn Hex x Hx.\n  have H : ex_finite_lim_seq (fun n : nat => real (Lim (fn n) x)).\n    apply CVU_dom_cauchy in Hfn.\n    apply ex_lim_seq_cauchy_corr => eps.\n    case: (Hfn (pos_div_2 eps)) => {Hfn} /= N Hfn.\n    exists N => n m Hn Hm.\n    case: (Hex x n Hx) => ln Hex_n ;\n    rewrite (is_lim_unique _ _ _ Hex_n).\n    case: (Hex x m Hx) => {Hex} lm Hex_m ;\n    rewrite (is_lim_unique _ _ _ Hex_m).\n    apply is_lim_spec in Hex_n.\n    apply is_lim_spec in Hex_m.\n    case: (Hex_n (pos_div_2 (pos_div_2 eps))) => {Hex_n} /= dn Hex_n.\n    case: (Hex_m (pos_div_2 (pos_div_2 eps))) => {Hex_m} /= dm Hex_m.\n    case: (Ho x Hx) => {Ho} d0 Ho.\n    set y := x + Rmin (Rmin dn dm) d0 / 2.\n    have Hd : 0 < Rmin (Rmin dn dm) d0 / 2.\n      apply Rdiv_lt_0_compat.\n      apply Rmin_case ; [ | by apply d0].\n      apply Rmin_case ; [ by apply dn | by apply dm].\n      exact: Rlt_R0_R2.\n    have Hy : Rabs (y - x) < d0.\n      rewrite /y ; ring_simplify ((x + Rmin (Rmin dn dm) d0 / 2) - x).\n      rewrite (Rabs_pos_eq _ (Rlt_le _ _ Hd)).\n      generalize (Rmin_r (Rmin dn dm) d0).\n      lra.\n    move : (Ho y Hy) => {Ho Hy} Hy.\n    replace (ln - lm)\n      with (- (fn n y - ln) + (fn m y - lm) + (fn n y - fn m y))\n      by ring.\n    rewrite (double_var eps) ;\n    apply Rle_lt_trans with (1 := Rabs_triang _ _), Rplus_lt_compat.\n    rewrite (double_var (eps/2)) ;\n    apply Rle_lt_trans with (1 := Rabs_triang _ _), Rplus_lt_compat.\n    rewrite Rabs_Ropp ; apply Hex_n.\n    rewrite /y /ball /= /AbsRing_ball /= /minus /plus /opp /abs /=.\n    ring_simplify ((x + Rmin (Rmin dn dm) d0 / 2) + - x).\n    rewrite (Rabs_pos_eq _ (Rlt_le _ _ Hd)).\n    generalize (Rmin_l (Rmin dn dm) d0) (Rmin_l dn dm).\n    lra.\n    apply Rgt_not_eq, Rlt_gt, Rminus_lt_0.\n    rewrite /y ; by ring_simplify ((x + Rmin (Rmin dn dm) d0 / 2) - x).\n    apply Hex_m.\n    rewrite /y /ball /= /AbsRing_ball /= /minus /plus /opp /abs /=.\n    ring_simplify ((x + Rmin (Rmin dn dm) d0 / 2) + - x).\n    rewrite (Rabs_pos_eq _ (Rlt_le _ _ Hd)).\n    generalize (Rmin_l (Rmin dn dm) d0) (Rmin_r dn dm).\n    lra.\n    apply Rgt_not_eq, Rlt_gt, Rminus_lt_0.\n    rewrite /y ; by ring_simplify ((x + Rmin (Rmin dn dm) d0 / 2) - x).\n    by apply Hfn.\n  split.\n  exact: H.\n  apply Lim_seq_correct' in H.\n  move: (real (Lim_seq (fun n : nat => real (Lim (fn n) x)))) H => l H.\n  have H0 : is_lim (fun y : R => real (Lim_seq (fun n : nat => fn n y))) x l.\n    apply is_lim_spec.\n    move => eps.\n    apply is_lim_seq_spec in H.\n    case: (Hfn (pos_div_2 (pos_div_2 eps))) => {Hfn} /= n1 Hfn.\n    case: (H (pos_div_2 (pos_div_2 eps))) => {H} /= n2 H.\n    set n := (n1 + n2)%nat.\n    move: (fun y Hy => Hfn n (le_plus_l _ _) y Hy) => {Hfn} Hfn.\n    move: (H n (le_plus_r _ _)) => {H} H.\n    move: (Hex x n Hx) => {Hex} Hex.\n    apply Lim_correct' in Hex.\n    apply is_lim_spec in Hex.\n    case: (Hex (pos_div_2 eps)) => {Hex} /= d1 Hex.\n    case: (Ho x Hx) => {Ho} /= d0 Ho.\n    have Hd : 0 < Rmin d0 d1.\n      apply Rmin_case ; [by apply d0 | by apply d1].\n    exists (mkposreal _ Hd) => /= y Hy Hxy.\n    replace (real (Lim_seq (fun n0 : nat => fn n0 y)) - l)\n      with ((real (Lim (fn n) x) - l)\n            - (fn n y - real (Lim_seq (fun n : nat => fn n y)))\n            + (fn n y - real (Lim (fn n) x)))\n      by ring.\n    rewrite (double_var eps) ;\n    apply Rle_lt_trans with (1 := Rabs_triang _ _), Rplus_lt_compat.\n    rewrite (double_var (eps/2)) ;\n    apply Rle_lt_trans with (1 := Rabs_triang _ _), Rplus_lt_compat.\n    exact: H.\n    rewrite Rabs_Ropp ; apply Hfn.\n    by apply Ho, Rlt_le_trans with (1 := Hy), Rmin_l.\n    apply Hex.\n    by apply Rlt_le_trans with (1 := Hy), Rmin_r.\n    exact: Hxy.\n  split.\n  by exists l.\n  replace l with (real l) by auto.\n  by apply sym_eq, (f_equal real), is_lim_unique.\nQed.\nLemma CVU_cont_open (fn : nat -> R -> R) (D : R -> Prop) :\n  open D ->\n  CVU_dom fn D ->\n  (forall n, forall x, D x -> continuity_pt (fn n) x)\n    -> forall x, D x -> continuity_pt (fun y => real (Lim_seq (fun n => fn n y))) x.\nProof.\n  move => Ho Hfn Hc x Hx.\n  case: (fun H => CVU_limits_open fn D Ho Hfn H x Hx)\n    => [{x Hx} x n Hx | Hex_s [Hex_f Heq]].\n  exists (fn n x).\n  apply is_lim_spec.\n  intros eps.\n  case: (Hc n x Hx eps (cond_pos eps)) => {Hc} d [Hd Hc].\n  exists (mkposreal d Hd) => /= y Hy Hxy.\n  apply (Hc y).\n  split.\n  split.\n  exact: I.\n  by apply sym_not_eq, Hxy.\n  exact: Hy.\n  apply Lim_correct' in Hex_f.\n  rewrite -Heq in Hex_f => {Heq}.\n  replace (Lim_seq (fun n : nat => real (Lim (fn n) x)))\n    with (Lim_seq (fun n : nat => (fn n) x)) in Hex_f.\n  move => e He.\n  apply is_lim_spec in Hex_f.\n  case: (Hex_f (mkposreal e He)) => {Hex_f} /= delta Hex_f.\n  exists delta ; split => [ | y [[_ Hxy] Hy]].\n  by apply delta.\n  apply Hex_f.\n  exact: Hy.\n  by apply sym_not_eq.\n  apply Lim_seq_ext => n.\n  replace (fn n x) with (real (fn n x)) by auto.\n  apply sym_eq, f_equal, is_lim_unique.\n  apply is_lim_spec.\n  move => eps.\n  case: (Hc n x Hx eps (cond_pos eps)) => {Hc} d [Hd Hc].\n  exists (mkposreal d Hd) => /= y Hy Hxy.\n  apply (Hc y).\n  split.\n  split.\n  exact: I.\n  by apply sym_not_eq, Hxy.\n  exact: Hy.\nQed.\n\nLemma CVU_Derive (fn : nat -> R -> R) (D : R -> Prop) :\n  open D -> is_connected D\n  -> CVU_dom fn D\n  -> (forall n x, D x -> ex_derive (fn n) x)\n  -> (forall n x, D x -> continuity_pt (Derive (fn n)) x)\n  -> CVU_dom (fun n x => Derive (fn n) x) D\n  -> (forall x , D x ->\n       (is_derive (fun y => real (Lim_seq (fun n => fn n y))) x\n         (real (Lim_seq (fun n => Derive (fn n) x))))).\nProof.\n  move => Ho Hc Hfn Edn Cdn Hdn.\n\n  set rn := fun x n h => match (Req_EM_T h 0) with\n    | left _ => Derive (fn n) x\n    | right _ => (fn n (x+h) - fn n x)/h\n  end.\n\n  assert (Ho' : forall x : R, open (fun h : R => D (x + h))).\n    intros x.\n    apply open_comp with (2 := Ho).\n    intros t _.\n    eapply (filterlim_comp_2 (F := locally t)).\n    apply filterlim_const.\n    apply filterlim_id.\n    apply: filterlim_plus.\n\n  have Crn : forall x, D x -> forall n h, D (x+h) -> is_lim (rn x n) h (rn x n h).\n    move => x Hx n h Hh.\n    rewrite {2}/rn ; case: (Req_EM_T h 0) => [-> | Hh0].\n    apply is_lim_spec.\n    move => eps.\n    cut (locally 0 (fun y : R => y <> 0 ->\n      Rabs ((fn n (x + y) - fn n x) / y - Derive (fn n) x) < eps)).\n    case => d H.\n    exists d => y Hy Hxy.\n    rewrite /rn ; case: Req_EM_T => // _ ; by apply H.\n    move: (Edn n x Hx) => {Edn} Edn.\n    apply Derive_correct in Edn.\n    apply is_derive_Reals in Edn.\n    case: (Edn eps (cond_pos eps)) => {Edn} delta Edn.\n    exists delta => y Hy Hxy.\n    rewrite /ball /= /AbsRing_ball /= /minus /plus /opp /= in Hy.\n    rewrite -/(Rminus _ _) Rminus_0_r in Hy.\n    by apply Edn.\n\n    have H : continuity_pt (fun h => ((fn n (x + h) - fn n x) / h)) h.\n      apply derivable_continuous_pt.\n      apply derivable_pt_div.\n      apply derivable_pt_minus.\n      apply derivable_pt_comp.\n      apply (derivable_pt_plus (fun _ => x) (fun h => h) h).\n      exact: derivable_pt_const.\n      exact: derivable_pt_id.\n      exists (Derive (fn n) (x + h)) ; by apply is_derive_Reals, Derive_correct, Edn.\n      exact: derivable_pt_const.\n      exact: derivable_pt_id.\n      exact: Hh0.\n\n    apply is_lim_spec.\n    move => eps.\n    case: (H eps (cond_pos eps)) => {H} d [Hd H].\n    have Hd0 : 0 < Rmin d (Rabs h).\n      apply Rmin_case.\n      exact: Hd.\n      by apply Rabs_pos_lt.\n    exists (mkposreal _ Hd0) => /= y Hy Hhy.\n    rewrite /rn ; case: Req_EM_T => /= Hy'.\n    contradict Hy.\n    apply Rle_not_lt.\n    rewrite /abs /minus /plus /opp /=.\n    rewrite Hy' -/(Rminus _ _) Rminus_0_l Rabs_Ropp ; by apply Rmin_r.\n    apply (H y) ; split.\n    split.\n    exact: I.\n    by apply sym_not_eq.\n    by apply Rlt_le_trans with (1 := Hy), Rmin_l.\n\n\n  have Hrn : forall x, D x -> CVU_dom (rn x) (fun h : R => D (x + h)).\n    move => x Hx.\n    apply CVU_dom_cauchy => eps.\n    apply CVU_dom_cauchy in Hdn.\n    case: (Hdn eps) => {Hdn} /= N Hdn.\n    exists N => n m h Hh Hn Hm.\n    rewrite /rn ; case: Req_EM_T => Hh0.\n    exact: (Hdn n m x Hx Hn Hm).\n    replace ((fn n (x + h) - fn n x) / h - (fn m (x + h) - fn m x) / h)\n      with (((fn n (x + h) - fn m (x + h)) - (fn n x - fn m x))/h)\n      by (field ; auto).\n    case: (MVT_gen (fun x => (fn n x - fn m x)) x (x+h) (Derive (fun x => fn n x - fn m x))) => [y Hy | y Hy | z [Hz ->]].\n    apply Derive_correct.\n    apply: ex_derive_minus ; apply Edn, (Hc (Rmin x (x + h)) (Rmax x (x + h))).\n    apply Rmin_case ; [by apply Hx | by apply Hh].\n    apply Rmax_case ; [by apply Hx | by apply Hh].\n    split ; apply Rlt_le ; by apply Hy.\n    apply Rmin_case ; [by apply Hx | by apply Hh].\n    apply Rmax_case ; [by apply Hx | by apply Hh].\n    split ; apply Rlt_le ; by apply Hy.\n    apply derivable_continuous_pt, derivable_pt_minus.\n    exists (Derive (fn n) y) ; apply is_derive_Reals, Derive_correct, Edn, (Hc (Rmin x (x + h)) (Rmax x (x + h))).\n    apply Rmin_case ; [by apply Hx | by apply Hh].\n    apply Rmax_case ; [by apply Hx | by apply Hh].\n    by apply Hy.\n    exists (Derive (fn m) y) ; apply is_derive_Reals, Derive_correct, Edn, (Hc (Rmin x (x + h)) (Rmax x (x + h))).\n    apply Rmin_case ; [by apply Hx | by apply Hh].\n    apply Rmax_case ; [by apply Hx | by apply Hh].\n    by apply Hy.\n    replace (Derive (fun x1 : R => fn n x1 - fn m x1) z * (x + h - x) / h)\n      with (Derive (fun x1 : R => fn n x1 - fn m x1) z)\n      by (field ; auto).\n    rewrite Derive_minus.\n    apply (Hdn n m z).\n    apply (Hc (Rmin x (x + h)) (Rmax x (x + h))).\n    apply Rmin_case ; [by apply Hx | by apply Hh].\n    apply Rmax_case ; [by apply Hx | by apply Hh].\n    by apply Hz.\n    exact: Hn.\n    exact: Hm.\n    apply Edn, (Hc (Rmin x (x + h)) (Rmax x (x + h))).\n    apply Rmin_case ; [by apply Hx | by apply Hh].\n    apply Rmax_case ; [by apply Hx | by apply Hh].\n    by apply Hz.\n    apply Edn, (Hc (Rmin x (x + h)) (Rmax x (x + h))).\n    apply Rmin_case ; [by apply Hx | by apply Hh].\n    apply Rmax_case ; [by apply Hx | by apply Hh].\n    by apply Hz.\n\n  have Lrn : forall x, D x -> (forall (y : R) (n : nat),\n    (fun h : R => D (x + h)) y -> ex_finite_lim (rn x n) y).\n    intros ; exists (rn x n y) ; by intuition.\n\n  move => x Hx.\n\n  case: (CVU_limits_open (rn x) _ (Ho' x) (Hrn x Hx) (Lrn x Hx) 0) => [ | H [H0 H1]].\n  by rewrite Rplus_0_r.\n\n  have : ex_derive (fun y : R => real (Lim_seq (fun n : nat => fn n y))) x\n    /\\ Derive (fun y : R => real (Lim_seq (fun n : nat => fn n y))) x\n      = real (Lim_seq (fun n : nat => Derive (fn n) x)).\n\n  split.\n  case: H0 => df H0.\n  exists df.\n  apply is_derive_Reals => e He.\n  apply is_lim_spec in H0.\n  case: (H0 (mkposreal e He)) => {H0} /= delta H0.\n  destruct (Ho x Hx) as [dx Hd].\n  have H2 : 0 < Rmin delta dx.\n    apply Rmin_case ; [by apply delta | by apply dx].\n  exists (mkposreal _ H2) => /= h Hh0 Hh.\n  replace (real (Lim_seq (fun n : nat => fn n (x + h))) -\n    real (Lim_seq (fun n : nat => fn n x))) with\n    (real (Rbar_minus (Lim_seq (fun n : nat => fn n (x + h))) (Lim_seq (fun n : nat => fn n x)))).\n  rewrite -Lim_seq_minus.\n  replace (real (Lim_seq (fun n : nat => fn n (x + h) - fn n x)) / h)\n  with (real (Rbar_mult (/h) (Lim_seq (fun n : nat => fn n (x + h) - fn n x)))).\n  rewrite -Lim_seq_scal_l.\n  replace (Lim_seq (fun n : nat => / h * (fn n (x + h) - fn n x)))\n    with (Lim_seq (fun n : nat => rn x n h)).\n  apply H0.\n  rewrite /ball /= /AbsRing_ball /= /minus /plus /opp /=.\n  rewrite -/(Rminus _ _) Rminus_0_r ; apply Rlt_le_trans with (1 := Hh), Rmin_l.\n  exact: Hh0.\n  apply Lim_seq_ext => n.\n  rewrite /rn /Rdiv ; case: Req_EM_T => // _ ; exact: Rmult_comm.\n  case: (Lim_seq (fun n : nat => fn n (x + h) - fn n x))\n    => [l | | ] //=.\n    by field.\n    rewrite /Rdiv Rmult_0_l.\n    case: Rle_dec => // Hh1.\n    case: Rle_lt_or_eq_dec => //.\n    rewrite /Rdiv Rmult_0_l.\n    case: Rle_dec => // Hh1.\n    case: Rle_lt_or_eq_dec => //.\n\n  apply ex_finite_lim_seq_correct, CVU_CVS_dom with D.\n  exact: Hfn.\n  apply Hd.\n  simpl.\n  rewrite /ball /= /AbsRing_ball /= /minus /plus /opp /=.\n  ring_simplify (x + h + - x) ; apply Rlt_le_trans with (1 := Hh), Rmin_r.\n  apply ex_finite_lim_seq_correct, CVU_CVS_dom with D.\n  exact: Hfn.\n  apply Hd.\n  apply ball_center.\n  apply (CVU_CVS_dom fn D) in Hfn ; rewrite /CVS_dom in Hfn.\n  move: (fun H => Lim_seq_correct' _ (Hfn (x+h) (Hd _ H))) => F.\n  move: (fun H => Lim_seq_correct' _ (Hfn (x) (Hd _ H))) => F0.\n  rewrite (is_lim_seq_unique _ (real (Lim_seq (fun n : nat => fn n (x + h))))).\n  rewrite (is_lim_seq_unique  (fun n : nat => fn n (x)) (real (Lim_seq (fun n : nat => fn n (x))))).\n  easy.\n  apply F0.\n  apply ball_center.\n  apply F.\n  rewrite /ball /= /AbsRing_ball /= /minus /plus /opp /=.\n  ring_simplify (x + h + - x).\n  apply Rlt_le_trans with (1 := Hh), Rmin_r.\n  apply (CVU_CVS_dom fn D) in Hfn ; rewrite /CVS_dom in Hfn.\n  move: (fun H => Lim_seq_correct' _ (Hfn (x+h) (Hd _ H))) => F.\n  move: (fun H => Lim_seq_correct' _ (Hfn (x) (Hd _ H))) => F0.\n  rewrite (is_lim_seq_unique _ (real (Lim_seq (fun n : nat => fn n (x + h))))).\n  rewrite (is_lim_seq_unique  (fun n : nat => fn n (x)) (real (Lim_seq (fun n : nat => fn n (x))))).\n  by [].\n  apply F0.\n  apply ball_center.\n  apply F.\n  rewrite /ball /= /AbsRing_ball /= /minus /plus /opp /=.\n  ring_simplify (x + h + - x).\n  apply Rlt_le_trans with (1 := Hh), Rmin_r.\n\n  rewrite /Derive.\n  replace (Lim_seq (fun n : nat => real (Lim (fun h : R => (fn n (x + h) - fn n x) / h) 0)))\n    with (Lim_seq (fun n : nat => real (Lim (rn x n) 0))).\n  rewrite H1.\n  case: H0 => drn H0.\n  rewrite (is_lim_unique _ _ _ H0).\n  apply f_equal, is_lim_unique.\n  apply is_lim_spec.\n  intros eps.\n  apply is_lim_spec in H0.\n  case: (H0 eps) => {H0} delta H0.\n  destruct (Ho x Hx) as [dx Hd].\n  have H2 : 0 < Rmin delta dx.\n    apply Rmin_case ; [by apply delta | by apply dx].\n  exists (mkposreal _ H2) => /= h Hh0 Hh.\n  replace (real (Lim_seq (fun n : nat => fn n (x + h))) -\n    real (Lim_seq (fun n : nat => fn n x))) with\n    (real (Rbar_minus (Lim_seq (fun n : nat => fn n (x + h))) (Lim_seq (fun n : nat => fn n x)))).\n  rewrite -Lim_seq_minus.\n  replace (real (Lim_seq (fun n : nat => fn n (x + h) - fn n x)) / h)\n  with (real (Rbar_mult (/h) (Lim_seq (fun n : nat => fn n (x + h) - fn n x)))).\n  rewrite -Lim_seq_scal_l.\n  replace (Lim_seq (fun n : nat => / h * (fn n (x + h) - fn n x)))\n    with (Lim_seq (fun n : nat => rn x n h)).\n  apply H0.\n  apply Rlt_le_trans with (1 := Hh0), Rmin_l.\n  exact: Hh.\n  apply Lim_seq_ext => n.\n  rewrite /rn /Rdiv ; case: Req_EM_T => // _ ; exact: Rmult_comm.\n  case: (Lim_seq (fun n : nat => fn n (x + h) - fn n x))\n    => [l | | ] //=.\n    by field.\n    rewrite /Rdiv Rmult_0_l.\n    case: Rle_dec => // Hh1.\n    case: Rle_lt_or_eq_dec => //.\n    rewrite /Rdiv Rmult_0_l.\n    case: Rle_dec => // Hh1.\n    case: Rle_lt_or_eq_dec => //.\n\n  apply ex_finite_lim_seq_correct, CVU_CVS_dom with D.\n  exact: Hfn.\n  apply Hd.\n  rewrite /ball /= /AbsRing_ball /= /minus /plus /opp /=.\n  ring_simplify (x + h + - x) ; rewrite -(Rminus_0_r h) ;\n  apply Rlt_le_trans with (1 := Hh0), Rmin_r.\n  apply ex_finite_lim_seq_correct, CVU_CVS_dom with D.\n  exact: Hfn.\n  apply Hd.\n  apply ball_center.\n  apply (CVU_CVS_dom fn D) in Hfn ; rewrite /CVS_dom in Hfn.\n  move: (fun H => Lim_seq_correct' _ (Hfn (x+h) (Hd _ H))) => F.\n  move: (fun H => Lim_seq_correct' _ (Hfn (x) (Hd _ H))) => F0.\n  rewrite (is_lim_seq_unique _ (real (Lim_seq (fun n : nat => fn n (x + h))))).\n  rewrite (is_lim_seq_unique  (fun n : nat => fn n (x)) (real (Lim_seq (fun n : nat => fn n (x))))).\n  easy.\n  apply F0.\n  apply ball_center.\n  apply F.\n  rewrite /ball /= /AbsRing_ball /= /minus /plus /opp /=.\n  ring_simplify (x + h + - x).\n  rewrite /ball /= /AbsRing_ball /= /minus /plus /opp /= in Hh0.\n  rewrite -/(Rminus _ _) Rminus_0_r in Hh0.\n  apply Rlt_le_trans with (1 := Hh0), Rmin_r.\n  apply (CVU_CVS_dom fn D) in Hfn ; rewrite /CVS_dom in Hfn.\n  move: (fun H => Lim_seq_correct' _ (Hfn (x+h) (Hd _ H))) => F.\n  move: (fun H => Lim_seq_correct' _ (Hfn (x) (Hd _ H))) => F0.\n  rewrite (is_lim_seq_unique _ (real (Lim_seq (fun n : nat => fn n (x + h))))).\n  rewrite (is_lim_seq_unique  (fun n : nat => fn n (x)) (real (Lim_seq (fun n : nat => fn n (x))))).\n  by [].\n  apply F0.\n  apply ball_center.\n  apply F.\n  rewrite /ball /= /AbsRing_ball /= /minus /plus /opp /=.\n  ring_simplify (x + h + - x).\n  rewrite /ball /= /AbsRing_ball /= /minus /plus /opp /= in Hh0.\n  rewrite -/(Rminus _ _) Rminus_0_r in Hh0.\n  apply Rlt_le_trans with (1 := Hh0), Rmin_r.\n\n  apply Lim_seq_ext => n.\n  apply sym_eq, f_equal, is_lim_unique.\n  have Hx' : D (x + 0).\n    by rewrite Rplus_0_r.\n  rewrite (is_lim_unique _ _ _ (Crn x Hx n 0 Hx')).\n  apply is_lim_spec.\n  move: (Crn x Hx n 0 Hx') => H2 eps.\n  apply is_lim_spec in H2.\n  case: (H2 eps) => {H2} delta H2.\n  exists delta => y Hy Hy0.\n  move: (H2 y Hy Hy0).\n  rewrite {1}/rn ; by case: Req_EM_T.\n\n  case => H2 H3.\n  rewrite -H3.\n  by apply Derive_correct.\nQed.\n\n(** ** Dini's theorem *)\n\nLemma Dini (fn : nat -> R -> R) (a b : R) :\n  a < b -> CVS_dom fn (fun x => a <= x <= b)\n  -> (forall (n : nat) (x : R), a <= x <= b -> continuity_pt (fn n) x)\n  -> (forall (x : R), a <= x <= b -> continuity_pt (fun y => Lim_seq (fun n => fn n y)) x)\n  -> (forall (n : nat) (x y : R), a <= x -> x <= y -> y <= b -> fn n x <= fn n y)\n  -> CVU_dom fn (fun x => a <= x <= b).\nProof.\n  set AB := fun x => a <= x <= b.\n  set f : R -> R := (fun y : R => Lim_seq (fun n : nat => fn n y)).\n  move => Hab Hcvs Cfn Cf Hfn.\n\n  have CUf : uniform_continuity f AB.\n    apply Heine.\n    by apply compact_P3.\n    by apply Cf.\n  suff H : forall eps : posreal, exists N : nat,\n    forall n : nat, (N <= n)%nat -> forall x : R, AB x ->\n    Rabs (fn n x - Lim_seq (fun n0 : nat => fn n0 x)) < 5 * eps.\n    move => eps.\n    replace (pos eps) with (5 * (eps / 5)) by field.\n    suff He : 0 < eps / 5.\n    by apply (H (mkposreal _ He)).\n    apply Rdiv_lt_0_compat.\n    by apply eps.\n    repeat (apply Rplus_lt_0_compat || apply Rmult_lt_0_compat) ; apply Rlt_0_1.\n\n  move => eps.\n  case: (CUf eps) => {CUf} eta CUf.\n  move: (interval_finite_subdiv_between  a b (pos_div_2 eta) (Rlt_le _ _ Hab)).\n  case: (interval_finite_subdiv a b (pos_div_2 eta) (Rlt_le _ _ Hab)) =>\n    a_ Ha_ /= Ha_0.\n  have : exists N, forall n i, (N <= n)%nat -> (i < seq.size a_)%nat\n    -> Rabs (fn n (seq.nth 0 a_ i) - f (seq.nth 0 a_ i)) < eps.\n    case: a_ Ha_ Ha_0 => [ | a0 a_] Ha_ /= Ha_0.\n    contradict Hab.\n    rewrite -(proj1 Ha_) -(proj1 (proj2 Ha_)).\n    by apply Rlt_irrefl.\n    elim: (a_) (a0) Ha_0 => /= [ | x1 l IH] x0 Hl.\n    move: (Hcvs x0 (Hl O (lt_n_Sn _))) ;\n    move/Lim_seq_correct' => {Hcvs} Hcvs.\n    apply is_lim_seq_spec in Hcvs.\n    case: (Hcvs eps) => {Hcvs} N Hcvs.\n    exists N => n i Hn Hi.\n    case: i Hi => /= [ | i] Hi.\n    by apply Hcvs.\n    by apply lt_S_n, lt_n_O in Hi.\n    case: (IH x1).\n    move => i Hi.\n    by apply (Hl (S i)), lt_n_S.\n    move => N0 HN0.\n    move: (Hcvs x0 (Hl O (lt_O_Sn _))) ;\n    move/Lim_seq_correct' => {Hcvs} Hcvs.\n    apply is_lim_seq_spec in Hcvs.\n    case: (Hcvs eps) => {Hcvs} N Hcvs.\n    exists (N + N0)%nat => n i Hn Hi.\n    case: i Hi => /= [ | i ] Hi.\n    apply Hcvs ; by intuition.\n    apply HN0 ; by intuition.\n  case => N HN.\n  exists N => n Hn x Hx.\n  have : exists i, (S i < seq.size a_)%nat /\\ seq.nth 0 a_ i <= x <= seq.nth 0 a_ (S i).\n    case: a_ Ha_ Ha_0 {HN} => [ | a0 a_] Ha_ /= Ha_0.\n    contradict Hab.\n    rewrite -(proj1 Ha_) -(proj1 (proj2 Ha_)).\n    by apply Rlt_irrefl.\n    case: a_ Ha_ Ha_0 => [ | a1 a_] Ha_ /= Ha_0.\n    contradict Hab.\n    rewrite -(proj1 Ha_) -(proj1 (proj2 Ha_)).\n    by apply Rlt_irrefl.\n    rewrite -(proj1 Ha_) in AB Hcvs CUf Hx Hab Cfn Cf Hfn Ha_0 |- * ; case: Ha_ => {a} _ Ha_.\n    rewrite -(proj1 Ha_) in AB Hcvs CUf Hx Hab Cfn Cf Hfn Ha_0 |- * ; case: Ha_ => {b} _ Ha_.\n    clear Hcvs CUf ;\n    revert AB Hx ;\n    elim: (a_) (a0) (a1) => /= [ | x2 l IH] x0 x1 Hx.\n    exists O ; split => /=.\n    by apply lt_n_Sn.\n    by apply Hx.\n    case: (Rlt_le_dec x x1) => Hx'.\n    exists O ; split => /=.\n    by apply lt_n_S, lt_O_Sn.\n    split ; intuition.\n    case: (IH x1 x2).\n    by intuition.\n    move => i [Hi Hx0].\n    exists (S i) ; by intuition.\n  case => i [Hi Hx'].\n  replace (fn n x - Lim_seq (fun n0 : nat => fn n0 x))\n    with ((f (seq.nth 0 a_ i) - f x) + (fn n x - f (seq.nth 0 a_ i)))\n    by (rewrite /f ; ring).\n  replace (5 * eps) with (eps + 4 * eps) by ring.\n  apply Rle_lt_trans with (1 := Rabs_triang _ _).\n  apply Rplus_lt_compat.\n  apply CUf.\n  apply Ha_0 ; by intuition.\n  by apply Hx.\n  rewrite -Rabs_Ropp Ropp_minus_distr' Rabs_pos_eq.\n  apply Rle_lt_trans with (seq.nth 0 a_ (S i) - seq.nth 0 a_ i).\n  apply Rplus_le_compat_r.\n  by apply Hx'.\n  apply Rle_lt_trans with (eta/2).\n  apply Rle_minus_l.\n  rewrite Rplus_comm.\n  by apply Ha_.\n  apply Rminus_lt_0 ; field_simplify ; rewrite Rdiv_1.\n  by apply is_pos_div_2.\n  apply Rle_minus_r ; rewrite Rplus_0_l.\n  by apply Hx'.\n  replace (fn n x - f (seq.nth 0 a_ i))\n    with ((fn n (seq.nth 0 a_ i) - f (seq.nth 0 a_ i)) + (fn n x - fn n (seq.nth 0 a_ i)))\n    by ring.\n  replace (4 * eps) with (eps + 3 * eps) by ring.\n  apply Rle_lt_trans with (1 := Rabs_triang _ _).\n  apply Rplus_lt_compat.\n  apply HN ; by intuition.\n  rewrite Rabs_pos_eq.\n  apply Rle_lt_trans with (fn n (seq.nth 0 a_ (S i)) - fn n (seq.nth 0 a_ i)).\n  apply Rplus_le_compat_r.\n  apply Hfn.\n  by apply Hx.\n  by apply Hx'.\n  by apply Ha_0.\n  replace (fn n (seq.nth 0 a_ (S i)) - fn n (seq.nth 0 a_ i))\n    with ((fn n (seq.nth 0 a_ (S i)) - f (seq.nth 0 a_ (S i)))\n      - (fn n (seq.nth 0 a_ i) - f (seq.nth 0 a_ i))\n      + (f (seq.nth 0 a_ (S i)) - f (seq.nth 0 a_ i)))\n    by ring.\n  replace (3 * eps) with ((eps + eps) + eps) by ring.\n  apply Rle_lt_trans with (1 := Rle_abs _).\n  apply Rle_lt_trans with (1 := Rabs_triang _ _).\n  apply Rplus_lt_compat.\n  apply Rle_lt_trans with (1 := Rabs_triang _ _).\n  apply Rplus_lt_compat.\n  apply HN ; by intuition.\n  rewrite Rabs_Ropp.\n  apply HN ; by intuition.\n  apply CUf.\n  apply Ha_0 ; by intuition.\n  apply Ha_0 ; by intuition.\n  rewrite Rabs_pos_eq.\n  apply Rle_lt_trans with (eta/2).\n  apply Rle_minus_l.\n  rewrite Rplus_comm.\n  by apply Ha_.\n  apply Rminus_lt_0 ; field_simplify ; rewrite Rdiv_1.\n  by apply is_pos_div_2.\n  apply Rle_minus_r ; rewrite Rplus_0_l.\n  apply Rle_trans with x ; apply Hx'.\n  apply Rle_minus_r ; rewrite Rplus_0_l.\n  apply Hfn.\n  apply Ha_0 ; by intuition.\n  by apply Hx'.\n  by apply Hx.\nQed.\n\n(** ** Series of functions *)\n\nLemma CVN_CVU_r (fn : nat -> R -> R) (r : posreal) :\n  CVN_r fn r -> forall x, (Rabs x < r) -> exists e : posreal,\n    CVU (fun n => SP fn n) (fun x => Series (fun n => fn n x)) x e.\nProof.\n  case => An [l [H H0]] x Hx.\n  assert (H1 : ex_series An).\n    apply ex_series_Reals_1.\n    exists l => e He.\n    case: (H e He) => {H} N H.\n    exists N => n Hn.\n    replace (sum_f_R0 An n) with (sum_f_R0 (fun k : nat => Rabs (An k)) n).\n    by apply H.\n    elim: n {Hn} => /= [ | n IH].\n    apply Rabs_pos_eq.\n    apply Rle_trans with (Rabs (fn O 0)).\n    by apply Rabs_pos.\n    apply H0 ; rewrite /Boule Rminus_0_r Rabs_R0 ; by apply r.\n    rewrite IH Rabs_pos_eq.\n    by [].\n    apply Rle_trans with (Rabs (fn (S n) 0)).\n    by apply Rabs_pos.\n    apply H0 ; rewrite /Boule Rminus_0_r Rabs_R0 ; by apply r.\n\n  have H2 : is_lim_seq (fun n => Series (fun k => An (n + k)%nat)) 0.\n    apply is_lim_seq_incr_1.\n    apply is_lim_seq_ext with (fun n => Series An - sum_f_R0 An n).\n    move => n ; rewrite (Series_incr_n An (S n)) /=.\n    ring.\n    by apply lt_O_Sn.\n    by apply H1.\n    replace (Finite 0) with (Rbar_plus (Series An) (- Series An))\n      by (simpl ; apply Rbar_finite_eq ; ring).\n    apply (is_lim_seq_plus _ _ (Series An) (-Series An)).\n    by apply is_lim_seq_const.\n    replace (Finite (-Series An)) with (Rbar_opp (Series An))\n      by (simpl ; apply Rbar_finite_eq ; ring).\n    apply -> is_lim_seq_opp.\n    rewrite /Series ;\n    apply (is_lim_seq_ext (sum_n (fun k => An k))).\n    elim => /= [ | n IH].\n    by rewrite sum_O.\n    by rewrite sum_Sn IH.\n    apply is_lim_seq_ext with (sum_n An).\n    move => n ; by rewrite sum_n_Reals.\n    apply Lim_seq_correct', H1.\n    easy.\n\n  assert (H3 : forall y, Boule 0 r y -> ex_series (fun n => Rabs (fn n y))).\n  move => y Hy.\n  move: H1 ; apply @ex_series_le.\n  move => n.\n  rewrite /norm /= /abs /= Rabs_Rabsolu.\n  by apply H0.\n\n  apply Rminus_lt_0 in Hx.\n  set r0 := mkposreal _ Hx.\n  exists r0 => e He ; set eps := mkposreal e He.\n  apply is_lim_seq_spec in H2.\n  case: (H2 eps) => {H2} N H2.\n  exists N => n y Hn Hy.\n\n  have H4 : Boule 0 r y.\n  rewrite /Boule /= in Hy |- *.\n  apply Rle_lt_trans with (1 := Rabs_triang_inv _ _) in Hy.\n  rewrite /Rminus ?(Rplus_comm _ (-Rabs x)) in Hy.\n  apply Rplus_lt_reg_l in Hy.\n  by rewrite Rminus_0_r.\n\n  apply Rle_lt_trans with (2 := H2 (S n) (le_trans _ _ _ (le_n_Sn _) (le_n_S _ _ Hn))).\n  rewrite Rminus_0_r /SP.\n  rewrite (Series_incr_n (fun k : nat => fn k y) (S n)) /=.\n  ring_simplify (sum_f_R0 (fun k : nat => fn k y) n +\n    Series (fun k : nat => fn (S (n + k)) y) -\n    sum_f_R0 (fun k : nat => fn k y) n).\n\n  apply Rle_trans with (2 := Rle_abs _).\n  apply Rle_trans with (Series (fun k : nat => Rabs (fn (S (n + k)) y))).\n  apply Series_Rabs.\n  apply ex_series_ext with (fun n0 : nat => Rabs (fn (S (n) + n0)%nat y)).\n    move => n0 ; by rewrite plus_Sn_m.\n  apply (ex_series_incr_n (fun n => Rabs (fn n y))).\n  by apply H3.\n  apply Series_le.\n  move => k ; split.\n  by apply Rabs_pos.\n  by apply H0.\n  apply ex_series_ext with (fun k : nat => An (S n + k)%nat).\n  move => k ; by rewrite plus_Sn_m.\n  by apply ex_series_incr_n.\n  by apply lt_O_Sn.\n  apply ex_series_Rabs.\n  by apply H3.\nQed.\n", "meta": {"author": "CohenCyril", "repo": "coquelicot", "sha": "680ca5870fc96442b01c0b61e57ca8238634739d", "save_path": "github-repos/coq/CohenCyril-coquelicot", "path": "github-repos/coq/CohenCyril-coquelicot/coquelicot-680ca5870fc96442b01c0b61e57ca8238634739d/theories/Seq_fct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.2988502849167261}}
{"text": "Require Import Rewriter.Util.FixCoqMistakes.\nRequire Import Coq.Classes.Morphisms Coq.Relations.Relation_Definitions.\nRequire Import Rewriter.Util.Tactics.GetGoal.\nRequire Import Rewriter.Util.Notations.\n\nDefinition Let_In {A P} (x : A) (f : forall a : A, P a) : P x := let y := x in f y.\nDefinition Let_In_pf {A P} (x : A) (f : forall a : A, a = x -> P a) : P x := let y := x in f y eq_refl.\nNotation \"'dlet_nd' x .. y := v 'in' f\" := (Let_In (P:=fun _ => _) v (fun x => .. (fun y => f) .. )) (only parsing).\nNotation \"'dlet' x .. y := v 'in' f\" := (Let_In v (fun x => .. (fun y => f) .. )).\nNotation \"'pflet' x , pf := y 'in' f\" := (Let_In_pf y (fun x pf => f)).\n\nStrategy 100 [Let_In Let_In_pf].\n\nModule Bug5107WorkAround.\n  Notation \"'dlet' x .. y := v 'in' f\" := (Let_In (P:=fun _ => _) v (fun x => .. (fun y => f) .. )).\nEnd Bug5107WorkAround.\n\nGlobal Instance Proper_Let_In_nd_changebody {A P R} {Reflexive_R:@Reflexive P R}\n  : Proper (eq ==> pointwise_relation _ R ==> R) (@Let_In A (fun _ => P)).\nProof. lazy; intros; subst; auto; congruence. Qed.\n\nGlobal Instance Proper_Let_In_nd_changevalue {A B} (RA:relation A) {RB:relation B}\n  : Proper (RA ==> (RA ==> RB) ==> RB) (Let_In (P:=fun _=>B)).\nProof. cbv; intuition. Qed.\n\nLemma Proper_Let_In_nd_changebody_eq {A P R} {Reflexive_R:@Reflexive P R} {x}\n  : Proper ((fun f g => forall a, x = a -> R (f a) (g a)) ==> R) (@Let_In A (fun _ => P) x).\nProof. lazy; intros; subst; auto; congruence. Qed.\n\nGlobal Instance Proper_Let_In_nd_changevalue_forall {A B} {RB:relation B}\n  : Proper (eq ==> (forall_relation (fun _ => RB)) ==> RB) (Let_In (P:=fun _:A=>B)).\nProof. cbv; intuition (subst; eauto). Qed.\n\n(* Strangely needed in some cases where we have [(fun _ => foo) ...] messing up dependency calculation *)\n#[global] Hint Extern 1 (Proper _ (@Let_In _ _)) => progress cbv beta : typeclass_instances.\n\nDefinition app_Let_In_nd {A B T} (f:B->T) (e:A) (C:A->B)\n  : f (Let_In e C) = Let_In e (fun v => f (C v)) := eq_refl.\n\nDefinition Let_app_In_nd {A B T} (f:A->B) (e:A) (C:B->T)\n  : Let_In (f e) C = Let_In e (fun v => C (f v)) := eq_refl.\n\nLemma unfold_Let_In {A B} v f : @Let_In A B v f = f v.\nProof. reflexivity. Qed.\n\nClass _call_let_in_to_Let_In {T} (e:T) := _let_in_to_Let_In_return : T.\n(* : forall T, gallina T -> gallina T, structurally recursive in the argument *)\nLtac let_in_to_Let_In e :=\n  lazymatch e with\n  | let x := ?ex in @?eC x =>\n    let ex := let_in_to_Let_In ex in\n    let eC := let_in_to_Let_In eC in\n    constr:(Let_In ex eC)\n  | ?f ?x =>\n    let f := let_in_to_Let_In f in\n    let x := let_in_to_Let_In x in\n    constr:(f x)\n  | (fun x : ?T => ?C) =>\n    lazymatch constr:(fun (x : T) => (_ : _call_let_in_to_Let_In C))\n                       (* [C] here above is an open term that references \"x\" by name *)\n    with fun x => @?C x => C end (* match drops the type cast *)\n  | ?x => x\n  end.\n#[global] Hint Extern 0 (_call_let_in_to_Let_In ?e) => (\n  let e := let_in_to_Let_In e in eexact e\n) : typeclass_instances.\nLtac change_let_in_with_Let_In :=\n  let g := get_goal in\n  let g' := let_in_to_Let_In g in\n  change g'.\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/LetIn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.2988502849167261}}
{"text": "(* Optimisation on syntax *)\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 Conversion\nITyping ITypingInversions ITypingLemmata ITypingAdmissible DecideConversion.\nImport ListNotations.\n\nSection Optim.\n\nContext `{Sort_notion : Sorts.notion}.\n\n(* For optimisation, we remark that we can decide whenever an heterogenous\n   equality is reflexivity.\n *)\nInductive isHeqRefl : sterm -> Type :=\n| is_HeqRefl A u : isHeqRefl (sHeqRefl A u).\n\nDefinition decHeqRefl t : dec (isHeqRefl t).\n  refine (\n    match t with\n    | sHeqRefl A u => inleft (is_HeqRefl A u)\n    | _ => inright (fun e => _)\n    end\n  ). all: inversion e.\nDefined.\n\n\n\nDefinition optHeqSym p :=\n  match p with\n  | sHeqRefl A u => sHeqRefl A u\n  | _ => sHeqSym p\n  end.\n\nLemma opt_HeqSym :\n  forall {Σ Γ A a B b p},\n    type_glob Σ ->\n    Σ ;;; Γ |-i p : sHeq A a B b ->\n    Σ ;;; Γ |-i optHeqSym p : sHeq B b A a.\nProof.\n  intros Σ Γ A a B b p hg h.\n  case (decHeqRefl p).\n  - intros i. destruct i as [C c].\n    simpl.\n    ttinv h. destruct (heq_conv_inv h3) as [eA [eu [eA' ev]]].\n    destruct (istype_type hg h) as [z heq]. ttinv heq.\n    eapply type_conv.\n    + eapply type_HeqRefl' ; eassumption.\n    + eapply type_Heq ; eassumption.\n    + apply cong_Heq ; assumption.\n  - intros e. destruct p.\n    16: exfalso ; apply e ; constructor.\n    all: simpl ; apply type_HeqSym' ; assumption.\nDefined.\n\nDefinition optHeqTrans p q :=\n  match p,q with\n  | sHeqRefl A u,  sHeqRefl _ _ => sHeqRefl A u\n  | sHeqRefl A u, _ => q\n  | _, sHeqRefl A u => p\n  | _,_ => sHeqTrans p q\n  end.\n\nLemma opt_HeqTrans :\n  forall {Σ Γ A a B b C c p q},\n    type_glob Σ ->\n    Σ ;;; Γ |-i p : sHeq A a B b ->\n    Σ ;;; Γ |-i q : sHeq B b C c ->\n    Σ ;;; Γ |-i optHeqTrans p q : sHeq A a C c.\nProof.\n  intros Σ Γ A a B b C c p q hg hp hq.\n  assert (hT : isType Σ Γ (sHeq A a C c)).\n  { eapply istype_type ; try assumption.\n    eapply type_HeqTrans' ; eassumption.\n  }\n  destruct hT.\n  case (decHeqRefl p) ; case (decHeqRefl q).\n  - intros iq ip. destruct ip as [D d], iq as [E e].\n    simpl.\n    ttinv hp. destruct (heq_conv_inv h2) as [DA [da [DB db]]].\n    ttinv hq. destruct (heq_conv_inv h5) as [EB [eb [EC ec]]].\n    eapply type_conv.\n    + eapply type_HeqRefl' ; eassumption.\n    + eassumption.\n    + conv rewrite <- EC, ec.\n      conv rewrite EB, eb.\n      conv rewrite <- DA, da.\n      apply cong_Heq ; try apply conv_refl ; assumption.\n  - intros bot ip. destruct ip as [D d].\n    replace (optHeqTrans (sHeqRefl D d) q) with q.\n    + ttinv hp. destruct (heq_conv_inv h2) as [DA [da [DB db]]].\n      eapply type_conv ; try eassumption.\n      conv rewrite <- DA, da. apply conv_sym.\n      apply cong_Heq ; try apply conv_refl ; assumption.\n    + destruct q. all: try reflexivity.\n      exfalso. apply bot. constructor.\n  - intros iq bot. destruct iq as [E e].\n    replace (optHeqTrans p (sHeqRefl E e)) with p.\n    + ttinv hq. destruct (heq_conv_inv h2) as [EB [eb [EC ec]]].\n      eapply type_conv ; try eassumption.\n      conv rewrite <- EB, eb.\n      apply cong_Heq ; try apply conv_refl ; assumption.\n    + destruct p. all: reflexivity.\n  - intros bq bp.\n    destruct p ; try (exfalso ; apply bp ; constructor).\n    all: destruct q ; try (exfalso ; apply bq ; constructor).\n    all: try (simpl ; eapply type_HeqTrans' ; eassumption).\nDefined.\n\nDefinition optTransport A B p t :=\n  (* if Equality.eq_term A B then t else sTransport A B p t. *)\n  if isconv (2^18) A B then t else sTransport A B p t.\n\nLemma opt_Transport :\n  forall {Σ Γ s A B p t},\n    type_glob Σ ->\n    Σ ;;; Γ |-i p : sEq (sSort s) A B ->\n    Σ ;;; Γ |-i t : A ->\n    Σ ;;; Γ |-i optTransport A B p t : B.\nProof.\n  intros Σ Γ s A B p t hg hp ht.\n  unfold optTransport.\n  case_eq (isconv (2 ^ 18) A B).\n  - intro h.\n    destruct (istype_type hg hp) as [z hT].\n    ttinv hT.\n    eapply type_conv ; try eassumption.\n    eapply isconv_sound. eassumption.\n  - intros _. eapply type_Transport' ; eassumption.\nDefined.\n\nDefinition optHeqToEq p :=\n  match p with\n  | sHeqRefl A a => sRefl A a\n  | sEqToHeq e => e\n  | _ => sHeqToEq p\n  end.\n\nLemma opt_HeqToEq :\n  forall {Σ Γ A u v p},\n    type_glob Σ ->\n    Σ ;;; Γ |-i p : sHeq A u A v ->\n    Σ ;;; Γ |-i optHeqToEq p : sEq A u v.\nProof.\n  intros Σ Γ A u v p hg h.\n  assert (hT : isType Σ Γ (sEq A u v)).\n  { eapply istype_type ; try assumption.\n    eapply type_HeqToEq' ; eassumption.\n  }\n  destruct hT.\n  destruct p.\n  all: try (simpl ; eapply type_HeqToEq' ; eassumption).\n  - simpl. rename p1 into B, p2 into b.\n    ttinv h. destruct (heq_conv_inv h3) as [BA [bu [_ bv]]].\n    eapply type_conv ; try eassumption.\n    + eapply type_Refl' ; eassumption.\n    + apply cong_Eq ; assumption.\n  - simpl. ttinv h. rename A0 into B, u0 into a, v0 into b.\n    destruct (heq_conv_inv h5) as [BA [au [_ bv]]].\n    eapply type_conv ; try eassumption.\n    apply cong_Eq ; assumption.\nDefined.\n\nFact opt_sort_heq :\n  forall {Σ Γ s1 s2 A B e},\n    type_glob Σ ->\n    Σ ;;; Γ |-i e : sHeq (sSort s1) A (sSort s2) B ->\n    Σ ;;; Γ |-i optHeqToEq e : sEq (sSort s1) A B.\nProof.\n  intros Σ Γ s1 s2 A B e hg h.\n  destruct (istype_type hg h) as [? hty].\n  ttinv hty.\n  eapply opt_HeqToEq ; try assumption.\n  eapply heq_sort ; eassumption.\nDefined.\n\nCorollary opt_sort_heq_ex :\n  forall {Σ Γ s1 s2 A B e},\n    type_glob Σ ->\n    Σ ;;; Γ |-i e : sHeq (sSort s1) A (sSort s2) B ->\n    ∑ p, Σ ;;; Γ |-i p : sEq (sSort s1) A B.\nProof.\n  intros Σ Γ s A B e hg h.\n  eexists. now eapply opt_sort_heq.\nDefined.\n\nDefinition optHeqTransport p t :=\n  match p with\n  | sRefl s A => sHeqRefl A t\n  | _ => sHeqTransport p t\n  end.\n\nLemma opt_HeqTransport :\n  forall {Σ Γ s A B p t},\n    type_glob Σ ->\n    Σ ;;; Γ |-i t : A ->\n    Σ ;;; Γ |-i p : sEq (sSort s) A B ->\n    Σ ;;; Γ |-i optHeqTransport p t : sHeq A t B (sTransport A B p t).\nProof.\n  intros Σ Γ s A B p t hg ht hp.\n  destruct p.\n  all: try (simpl ; eapply type_HeqTransport' ; eassumption).\n  simpl.\n  ttinv hp. destruct (eq_conv_inv h2) as [? [eA eB]].\n  destruct (istype_type hg hp) as [? hT].\n  ttinv hT.\n  eapply type_conv.\n  - econstructor.\n    + econstructor ; eassumption.\n    + apply conv_sym in eA.\n      econstructor ; try eassumption.\n      econstructor ; eassumption.\n  - econstructor ; try eassumption.\n    econstructor ; eassumption.\n  - apply cong_Heq ; try assumption ; try apply conv_refl.\n    eapply conv_red_r ; econstructor. reflexivity.\nDefined.\n\nDefinition optEqToHeq p :=\n  match p with\n  | sRefl A x => sHeqRefl A x\n  | _ => sEqToHeq p\n  end.\n\nLemma opt_EqToHeq :\n  forall {Σ Γ A u v p},\n    type_glob Σ ->\n    Σ ;;; Γ |-i p : sEq A u v ->\n    Σ ;;; Γ |-i optEqToHeq p : sHeq A u A v.\nProof.\n  intros Σ Γ A u v p hg h.\n  destruct p.\n  all: try (simpl ; eapply type_EqToHeq' ; eassumption).\n  simpl.\n  ttinv h. destruct (eq_conv_inv h3) as [eA [eu ev]].\n  destruct (istype_type hg h) as [? hT].\n  ttinv hT.\n  econstructor.\n  - econstructor ; eassumption.\n  - econstructor ; eassumption.\n  - apply cong_Heq ; assumption.\nDefined.\n\n(* Tests if t does not depend on variable i *)\nFixpoint notdepi (t : sterm) (i : nat) {struct t} : bool :=\n  match t with\n  | sRel j => negb (i =? j)\n  | sSort _ => true\n  | sProd _ A B => notdepi A i && notdepi B (S i)\n  | sLambda _ A B t => notdepi A i && notdepi B (S i) && notdepi t (S i)\n  | sApp u A B v => notdepi A i && notdepi B (S i) && notdepi u i && notdepi v i\n  | sSum _ A B => notdepi A i && notdepi B (S i)\n  | sPair A B u v => notdepi A i && notdepi B (S i) && notdepi u i && notdepi v i\n  | sPi1 A B p => notdepi A i && notdepi B (S i) && notdepi p i\n  | sPi2 A B p => notdepi A i && notdepi B (S i) && notdepi p i\n  | sEq A u v => notdepi A i && notdepi u i && notdepi v i\n  | sRefl A u => notdepi A i && notdepi u i\n  (* | sJ *)\n  | sTransport A B p t =>\n    notdepi A i && notdepi B i && notdepi p i && notdepi t i\n  | sHeq A a B b => notdepi A i && notdepi a i && notdepi B i && notdepi b i\n  | sHeqToEq p => notdepi p i\n  | sHeqRefl A u => notdepi A i && notdepi u i\n  | sHeqSym p => notdepi p i\n  | sHeqTrans p q => notdepi p i && notdepi q i\n  | sHeqTransport p t => notdepi p i && notdepi t i\n  | sCongProd B1 B2 pA pB =>\n    notdepi B1 (S i) && notdepi B2 (S i) && notdepi pA i && notdepi pB (S i)\n  | sCongLambda B1 B2 t1 t2 pA pB pt =>\n    notdepi B1 (S i) && notdepi B2 (S i) &&\n    notdepi t1 (S i) && notdepi t2 (S i) &&\n    notdepi pA i && notdepi pB (S i) && notdepi pt (S i)\n  | sCongApp B1 B2 pu pA pB pv =>\n    notdepi B1 (S i) && notdepi B2 (S i) &&\n    notdepi pA i && notdepi pB (S i) &&\n    notdepi pu i && notdepi pv i\n  | sCongSum B1 B2 pA pB =>\n    notdepi B1 (S i) && notdepi B2 (S i) && notdepi pA i && notdepi pB (S i)\n  (* | sCongPair TODO *)\n  (* | sCongPi1 TODO *)\n  (* | sCongPi2 TODO *)\n  | sCongEq pA pu pv => notdepi pA i && notdepi pu i && notdepi pv i\n  | sCongRefl pA pu => notdepi pA i && notdepi pu i\n  | sEqToHeq p => notdepi p i\n  | sHeqTypeEq A B p => notdepi A i && notdepi B i && notdepi p i\n  | sPack A B => notdepi A i && notdepi B i\n  | sProjT1 p => notdepi p i\n  | sProjT2 p => notdepi p i\n  | sProjTe p => notdepi p i\n  | sAx _ => true\n  | _ => false\n  end.\n\nDefinition notdep t := notdepi t 0.\n\nLemma notdepi_lift :\n  forall {t i},\n    notdepi t i = true ->\n    lift 1 (S i) t = lift 1 i t.\nProof.\n  intro t. induction t ; intros i h.\n  all: try (cbn in h ; discriminate h).\n  all: try (cbn in h ; repeat destruct_andb ;\n            cbn ; f_equal ;\n            rewrite_assumption ; (reflexivity || assumption)).\n  revert h. cbn - [Nat.leb]. ncase (i =? n).\n  - cbn. discriminate.\n  - intros _. nat_case.\n    + nat_case. reflexivity.\n    + nat_case. reflexivity.\nDefined.\n\nCorollary notdep_lift :\n  forall {t},\n    notdep t = true ->\n    lift 1 1 t = lift0 1 t.\nProof.\n  intros t h.\n  apply notdepi_lift. assumption.\nDefined.\n\nDefinition optCongProd B1 B2 pA pB :=\n  match pA, pB with\n  | sHeqRefl (sSort s) A, sHeqRefl (sSort z) B =>\n    if notdep B1 && notdep B2 then\n      sHeqRefl (sSort (prod_sort s z)) (sProd nAnon A B1)\n    else sCongProd B1 B2 pA pB\n  | _,_ => sCongProd B1 B2 pA pB\n  end.\n\nLemma opt_CongProd :\n  forall {Σ Γ s1 s2 z1 z2 nx ny A1 A2 B1 B2 pA pB},\n    type_glob Σ ->\n    Σ;;; Γ |-i pA : sHeq (sSort s1) A1 (sSort s2) A2 ->\n    Σ;;; Γ,, sPack A1 A2 |-i\n    pB : sHeq (sSort z1)\n              ((lift 1 1 B1) {0 := sProjT1 (sRel 0)})\n              (sSort z2)\n              ((lift 1 1 B2) {0 := sProjT2 (sRel 0)}) ->\n    Σ;;; Γ,, A1 |-i B1 : sSort z1 ->\n    Σ;;; Γ,, A2 |-i B2 : sSort z2 ->\n    Σ;;; Γ |-i optCongProd B1 B2 pA pB\n    : sHeq (sSort (prod_sort s1 z1)) (sProd nx A1 B1)\n           (sSort (prod_sort s2 z2)) (sProd ny A2 B2).\nProof.\n  intros Σ Γ s1 s2 z1 z2 nx ny A1 A2 B1 B2 pA pB hg hpA hpB hB1 hB2.\n  destruct pA.\n  all: try (simpl ; eapply type_CongProd' ; eassumption).\n  destruct pA1.\n  all: try (simpl ; eapply type_CongProd' ; eassumption).\n  destruct pB.\n  all: try (simpl ; eapply type_CongProd' ; eassumption).\n  destruct pB1.\n  all: try (simpl ; eapply type_CongProd' ; eassumption).\n  simpl.\n  case_eq (notdep B1) ; try (intro ; simpl ; eapply type_CongProd' ; eassumption).\n  case_eq (notdep B2) ; try (intros ; simpl ; eapply type_CongProd' ; eassumption).\n  intros nd2 nd1. simpl.\n  ttinv hpA. ttinv hpB.\n  destruct (istype_type hg hpA) as [? hTA]. ttinv hTA.\n  destruct (istype_type hg hpB) as [? hTB]. ttinv hTB.\n  destruct (heq_conv_inv h2) as [es1 [? [es2 ?]]].\n  destruct (heq_conv_inv h5) as [es3 [eB1 [es4 eB2]]].\n  pose proof (sort_conv_inv h10).\n  pose proof (sort_conv_inv h15).\n  pose proof (sort_conv_inv es1).\n  pose proof (sort_conv_inv es2).\n  pose proof (sort_conv_inv es3).\n  pose proof (sort_conv_inv es4).\n  subst.\n  econstructor.\n  - econstructor ; try eassumption.\n    + econstructor ; try eassumption. eapply typing_wf. eassumption.\n    + econstructor ; try eassumption.\n      eapply ContextConversion.type_ctxconv ; try eassumption.\n      * econstructor ; try eassumption.\n        eapply typing_wf. eassumption.\n      * constructor.\n        -- apply ContextConversion.ctxconv_refl.\n        -- apply conv_sym. assumption.\n  - econstructor.\n    + econstructor ; try eassumption.\n      eapply typing_wf. eassumption.\n    + econstructor ; try eassumption.\n      eapply typing_wf. eassumption.\n    + econstructor ; eassumption.\n    + econstructor ; eassumption.\n  - apply cong_Heq ; try apply conv_refl.\n    + apply cong_Prod ; try apply conv_refl. assumption.\n    + apply cong_Prod ; try assumption.\n      rewrite notdep_lift, lift_subst in eB1 by assumption.\n      rewrite notdep_lift, lift_subst in eB2 by assumption.\n      eapply conv_trans ; try eassumption.\n      apply conv_sym. assumption.\nDefined.\n\nDefinition optCongLambda B1 B2 t1 t2 pA pB pt :=\n  match pA, pB, pt with\n  | sHeqRefl _ A, sHeqRefl _ _, sHeqRefl _ _ =>\n    if notdep B1 && notdep B2 && notdep t1 && notdep t2 then\n      sHeqRefl (sProd nAnon A B1) (sLambda nAnon A B1 t1)\n    else sCongLambda B1 B2 t1 t2 pA pB pt\n  | _,_,_ => sCongLambda B1 B2 t1 t2 pA pB pt\n  end.\n\nLemma opt_CongLambda :\n  forall {Σ Γ s1 s2 z1 z2 nx ny A1 A2 B1 B2 t1 t2 pA pB pt},\n    type_glob Σ ->\n    Σ;;; Γ |-i pA : sHeq (sSort s1) A1 (sSort s2) A2 ->\n    Σ;;; Γ,, sPack A1 A2 |-i pB\n    : sHeq (sSort z1) ((lift 1 1 B1) {0 := sProjT1 (sRel 0)})\n           (sSort z2) ((lift 1 1 B2) {0 := sProjT2 (sRel 0)}) ->\n    Σ;;; Γ,, sPack A1 A2 |-i pt\n    : sHeq ((lift 1 1 B1) {0 := sProjT1 (sRel 0)})\n           ((lift 1 1 t1) {0 := sProjT1 (sRel 0)})\n           ((lift 1 1 B2) {0 := sProjT2 (sRel 0)})\n           ((lift 1 1 t2) {0 := sProjT2 (sRel 0)}) ->\n    Σ;;; Γ,, A1 |-i B1 : sSort z1 ->\n    Σ;;; Γ,, A2 |-i B2 : sSort z2 ->\n    Σ;;; Γ,, A1 |-i t1 : B1 ->\n    Σ;;; Γ,, A2 |-i t2 : B2 ->\n    Σ;;; Γ |-i optCongLambda B1 B2 t1 t2 pA pB pt\n    : sHeq (sProd nx A1 B1) (sLambda nx A1 B1 t1)\n           (sProd ny A2 B2) (sLambda ny A2 B2 t2).\nProof.\n  intros Σ Γ s1 s2 z1 z2 nx ny A1 A2 B1 B2 t1 t2 pA pB pt\n         hg hpA hpB hpt hB1 hB2 ht1 ht2.\n  destruct pA.\n  all: try (simpl ; eapply type_CongLambda' ; eassumption).\n  destruct pB.\n  all: try (simpl ; eapply type_CongLambda' ; eassumption).\n  destruct pt.\n  all: try (simpl ; eapply type_CongLambda' ; eassumption).\n  simpl.\n  case_eq (notdep B1) ; try (intro ; simpl ; eapply type_CongLambda' ; eassumption).\n  case_eq (notdep B2) ; try (intros ; simpl ; eapply type_CongLambda' ; eassumption).\n  case_eq (notdep t1) ; try (intros ; simpl ; eapply type_CongLambda' ; eassumption).\n  case_eq (notdep t2) ; try (intros ; simpl ; eapply type_CongLambda' ; eassumption).\n  intros ndt2 ndt1 ndB2 ndB1. simpl.\n  ttinv hpA. ttinv hpB. ttinv hpt.\n  destruct (istype_type hg hpA) as [? hTA]. ttinv hTA.\n  destruct (istype_type hg hpB) as [? hTB]. ttinv hTB.\n  destruct (istype_type hg hpt) as [? hTt]. ttinv hTt.\n  destruct (heq_conv_inv h2) as [es1 [? [es2 ?]]].\n  destruct (heq_conv_inv h5) as [es3 [eB1 [es4 eB2]]].\n  destruct (heq_conv_inv h8) as [_ [et1 [_ et2]]].\n  assert (sSort s1 ≡ sSort s2).\n  { eapply conv_trans ; try eassumption.\n    apply conv_sym. assumption.\n  }\n  assert (sSort z1 ≡ sSort z2).\n  { eapply conv_trans ; try eassumption.\n    apply conv_sym. assumption.\n  }\n  repeat match goal with\n  | h : sSort _ ≡ sSort _ |- _ =>\n    pose proof (sort_conv_inv h) ; clear h\n  end.\n  subst.\n  assert (Σ;;; Γ |-i pA2 : sSort s2).\n  { econstructor ; eassumption. }\n  assert (wf Σ Γ).\n  { eapply typing_wf. eassumption. }\n  econstructor.\n  - eapply type_HeqRefl' ; try eassumption.\n    eapply type_Lambda ; try eassumption.\n    + eapply ContextConversion.type_ctxconv ; try eassumption.\n      * econstructor ; eassumption.\n      * econstructor ; try apply ContextConversion.ctxconv_refl.\n        apply conv_sym. assumption.\n    + eapply ContextConversion.type_ctxconv ; try eassumption.\n      * econstructor ; eassumption.\n      * econstructor ; try apply ContextConversion.ctxconv_refl.\n        apply conv_sym. assumption.\n  - econstructor.\n    + econstructor ; eassumption.\n    + econstructor ; eassumption.\n    + econstructor ; eassumption.\n    + econstructor ; eassumption.\n  - apply cong_Heq.\n    + apply cong_Prod ; try apply conv_refl. assumption.\n    + apply cong_Lambda ; try apply conv_refl. assumption.\n    + apply cong_Prod ; try apply conv_refl. assumption.\n      rewrite notdep_lift, lift_subst in eB1 by assumption.\n      rewrite notdep_lift, lift_subst in eB2 by assumption.\n      eapply conv_trans ; try eassumption.\n      apply conv_sym. assumption.\n    + apply cong_Lambda ; try apply conv_refl. assumption.\n      * rewrite notdep_lift, lift_subst in eB1 by assumption.\n        rewrite notdep_lift, lift_subst in eB2 by assumption.\n        eapply conv_trans ; try eassumption.\n        apply conv_sym. assumption.\n      * rewrite notdep_lift, lift_subst in et1 by assumption.\n        rewrite notdep_lift, lift_subst in et2 by assumption.\n        eapply conv_trans ; try eassumption.\n        apply conv_sym. assumption.\nDefined.\n\nDefinition optCongApp B1 B2 pu pA pB pv :=\n  match pA, pB, pu, pv with\n  | sHeqRefl _ A, sHeqRefl _ _, sHeqRefl _ u, sHeqRefl _ v =>\n    if notdep B1 && notdep B2 then\n      sHeqRefl (B1{ 0 := v }) (sApp u A B1 v)\n    else sCongApp B1 B2 pu pA pB pv\n  | _,_,_,_ => sCongApp B1 B2 pu pA pB pv\n  end.\n\nLemma opt_CongApp :\n  forall {Σ Γ s1 s2 z1 z2 nx ny A1 A2 B1 B2 u1 u2 v1 v2 pA pB pu pv},\n    type_glob Σ ->\n    Σ;;; Γ |-i pA : sHeq (sSort s1) A1 (sSort s2) A2 ->\n    Σ;;; Γ,, sPack A1 A2 |-i pB\n    : sHeq (sSort z1) ((lift 1 1 B1) {0 := sProjT1 (sRel 0)})\n           (sSort z2) ((lift 1 1 B2) {0 := sProjT2 (sRel 0)}) ->\n    Σ;;; Γ |-i pu : sHeq (sProd nx A1 B1) u1 (sProd ny A2 B2) u2 ->\n    Σ;;; Γ |-i pv : sHeq A1 v1 A2 v2 ->\n    Σ;;; Γ,, A1 |-i B1 : sSort z1 ->\n    Σ;;; Γ,, A2 |-i B2 : sSort z2 ->\n    Σ;;; Γ |-i optCongApp B1 B2 pu pA pB pv\n    : sHeq (B1 {0 := v1}) (sApp u1 A1 B1 v1) (B2 {0 := v2}) (sApp u2 A2 B2 v2).\nProof.\n  intros Σ Γ s1 s2 z1 z2 nx ny A1 A2 B1 B2 u1 u2 v1 v2 pA pB pu pv\n         hg hpA hpB hpu hpv hB1 hB2.\n  destruct pA.\n  all: try (simpl ; eapply type_CongApp' ; eassumption).\n  destruct pB.\n  all: try (simpl ; eapply type_CongApp' ; eassumption).\n  destruct pu.\n  all: try (simpl ; eapply type_CongApp' ; eassumption).\n  destruct pv.\n  all: try (simpl ; eapply type_CongApp' ; eassumption).\n  simpl.\n  case_eq (notdep B1) ; try (intro ; simpl ; eapply type_CongApp' ; eassumption).\n  case_eq (notdep B2) ; try (intros ; simpl ; eapply type_CongApp' ; eassumption).\n  intros ndB2 ndB1. simpl.\n  ttinv hpA. ttinv hpB. ttinv hpu. ttinv hpv.\n  destruct (istype_type hg hpA) as [? hTA]. ttinv hTA.\n  destruct (istype_type hg hpB) as [? hTB]. ttinv hTB.\n  destruct (istype_type hg hpu) as [? hTu]. ttinv hTu.\n  destruct (istype_type hg hpv) as [? hTv]. ttinv hTv.\n  destruct (heq_conv_inv h2) as [es1 [? [es2 ?]]].\n  destruct (heq_conv_inv h5) as [es3 [eB1 [es4 eB2]]].\n  destruct (heq_conv_inv h8) as [? [eu1 [? eu2]]].\n  destruct (heq_conv_inv h11) as [? [ev1 [? ev2]]].\n  assert (sSort s1 ≡ sSort s2).\n  { eapply conv_trans ; try eassumption.\n    apply conv_sym. assumption.\n  }\n  assert (sSort z1 ≡ sSort z2).\n  { eapply conv_trans ; try eassumption.\n    apply conv_sym. assumption.\n  }\n  repeat match goal with\n  | h : sSort _ ≡ sSort _ |- _ =>\n    pose proof (sort_conv_inv h) ; clear h\n  end.\n  subst.\n  assert (Σ;;; Γ |-i pA2 : sSort s2).\n  { econstructor ; eassumption. }\n  assert (wf Σ Γ).\n  { eapply typing_wf. eassumption. }\n  assert (Σ;;; Γ,, pA2 |-i B1 : sSort z2).\n  { eapply ContextConversion.type_ctxconv ; try eassumption.\n    - econstructor ; eassumption.\n    - econstructor ; try apply ContextConversion.ctxconv_refl.\n      apply conv_sym. assumption.\n  }\n  assert (B1 ≡ B2).\n  { rewrite notdep_lift, lift_subst in eB1 by assumption.\n    rewrite notdep_lift, lift_subst in eB2 by assumption.\n    eapply conv_trans ; try eassumption.\n    apply conv_sym. assumption.\n  }\n  assert (pv1 ≡ pA2).\n  { eapply conv_trans ; try eassumption.\n    apply conv_sym. assumption.\n  }\n  assert (A1 ≡ pA2).\n  { eapply conv_trans ; try eassumption.\n    apply conv_sym. assumption.\n  }\n  econstructor.\n  - econstructor.\n    + ContextConversion.lift_sort. eapply typing_subst ; try eassumption.\n      econstructor ; eassumption.\n    + econstructor ; try eassumption.\n      * econstructor ; try eassumption.\n        -- econstructor ; eassumption.\n        -- eapply conv_trans ; try eassumption.\n           apply conv_sym. apply cong_Prod ; assumption.\n      * econstructor ; eassumption.\n  - econstructor.\n    + ContextConversion.lift_sort. eapply typing_subst ; try eassumption.\n      econstructor ; eassumption.\n    + ContextConversion.lift_sort. eapply typing_subst ; eassumption.\n    + econstructor ; eassumption.\n    + econstructor ; eassumption.\n  - apply cong_Heq.\n    + apply substs_conv. assumption.\n    + apply cong_App ; try apply conv_refl ; assumption.\n    + apply cong_subst ; assumption.\n    + apply cong_App ; try apply conv_refl ; assumption.\n  Unshelve. exact nAnon.\nDefined.\n\n(* TODO congSum, congPair, congPi1, congPi2 *)\n\nDefinition optCongEq pA pu pv :=\n  match pA, pu, pv with\n  | sHeqRefl (sSort s) A, sHeqRefl _ u, sHeqRefl _ v =>\n    sHeqRefl (sSort (eq_sort s)) (sEq A u v)\n  | _,_,_ => sCongEq pA pu pv\n  end.\n\nLemma opt_CongEq :\n  forall {Σ Γ s1 s2 A1 A2 u1 u2 v1 v2 pA pu pv},\n    type_glob Σ ->\n    Σ;;; Γ |-i pA : sHeq (sSort s1) A1 (sSort s2) A2 ->\n    Σ;;; Γ |-i pu : sHeq A1 u1 A2 u2 ->\n    Σ;;; Γ |-i pv : sHeq A1 v1 A2 v2 ->\n    Σ;;; Γ |-i optCongEq pA pu pv :\n              sHeq (sSort (eq_sort s1)) (sEq A1 u1 v1)\n                   (sSort (eq_sort s2)) (sEq A2 u2 v2).\nProof.\n  intros Σ Γ s1 s2 A1 A2 u1 u2 v1 v2 pA pu pv hg hpA hpu hpv.\n  destruct pA.\n  all: try (simpl ; eapply type_CongEq' ; eassumption).\n  destruct pA1.\n  all: try (simpl ; eapply type_CongEq' ; eassumption).\n  destruct pu.\n  all: try (simpl ; eapply type_CongEq' ; eassumption).\n  destruct pv.\n  all: try (simpl ; eapply type_CongEq' ; eassumption).\n  simpl.\n  ttinv hpA. ttinv hpu. ttinv hpv.\n  destruct (istype_type hg hpA) as [? hTA]. ttinv hTA.\n  destruct (istype_type hg hpu) as [? hTu]. ttinv hTu.\n  destruct (istype_type hg hpv) as [? hTv]. ttinv hTv.\n  destruct (heq_conv_inv h2) as [es1 [? [es2 ?]]].\n  destruct (heq_conv_inv h5) as [es3 [? [es4 ?]]].\n  destruct (heq_conv_inv h8) as [es5 [? [es6 ?]]].\n  repeat match goal with\n  | h : sSort _ ≡ sSort _ |- _ =>\n    pose proof (sort_conv_inv h) ; clear h\n  end.\n  subst.\n  econstructor.\n  - econstructor ; try eassumption.\n    + econstructor. eapply typing_wf. eassumption.\n    + econstructor ; try eassumption.\n      * econstructor ; try eassumption.\n        eapply conv_trans ; try eassumption.\n        apply conv_sym. assumption.\n      * econstructor ; try eassumption.\n        eapply conv_trans ; try eassumption.\n        apply conv_sym. assumption.\n  - econstructor.\n    + econstructor. eapply typing_wf. eassumption.\n    + econstructor. eapply typing_wf. eassumption.\n    + econstructor ; eassumption.\n    + econstructor ; eassumption.\n  - apply cong_Heq ; try apply conv_refl.\n    + apply cong_Eq ; assumption.\n    + apply cong_Eq ; assumption.\nDefined.\n\nDefinition optCongRefl pA pu :=\n  match pA, pu with\n  | sHeqRefl _ A, sHeqRefl _ u =>\n    sHeqRefl (sEq A u u) (sRefl A u)\n  | _,_ => sCongRefl pA pu\n  end.\n\nLemma opt_CongRefl :\n  forall {Σ Γ s1 s2 A1 A2 u1 u2 pA pu},\n    type_glob Σ ->\n    Σ;;; Γ |-i pA : sHeq (sSort s1) A1 (sSort s2) A2 ->\n    Σ;;; Γ |-i pu : sHeq A1 u1 A2 u2 ->\n    Σ;;; Γ |-i optCongRefl pA pu : sHeq (sEq A1 u1 u1) (sRefl A1 u1)\n                                       (sEq A2 u2 u2) (sRefl A2 u2).\nProof.\n  intros Σ Γ s1 s2 A1 A2 u1 u2 pA pu hg hpA hpu.\n  destruct pA.\n  all: try (simpl ; eapply type_CongRefl' ; eassumption).\n  destruct pu.\n  all: try (simpl ; eapply type_CongRefl' ; eassumption).\n  simpl.\n  ttinv hpA. ttinv hpu.\n  destruct (istype_type hg hpA) as [? hTA]. ttinv hTA.\n  destruct (istype_type hg hpu) as [? hTu]. ttinv hTu.\n  destruct (heq_conv_inv h2) as [es1 [? [es2 ?]]].\n  destruct (heq_conv_inv h5) as [es3 [? [es4 ?]]].\n  repeat match goal with\n  | h : sSort _ ≡ sSort _ |- _ =>\n    pose proof (sort_conv_inv h) ; clear h\n  end.\n  subst.\n  assert (Σ ;;; Γ |-i pA2 : sSort s1).\n  { econstructor ; eassumption. }\n  econstructor.\n  - econstructor.\n    + econstructor ; try eassumption.\n      * econstructor ; try eassumption.\n        eapply conv_trans ; try eassumption.\n        apply conv_sym. assumption.\n      * econstructor ; try eassumption.\n        eapply conv_trans ; try eassumption.\n        apply conv_sym. assumption.\n    + econstructor ; try eassumption.\n      econstructor ; try eassumption.\n      eapply conv_trans ; try eassumption.\n      apply conv_sym. assumption.\n  - econstructor.\n    + econstructor ; eassumption.\n    + econstructor ; eassumption.\n    + econstructor ; eassumption.\n    + econstructor ; eassumption.\n  - apply cong_Heq.\n    + apply cong_Eq ; assumption.\n    + apply cong_Refl ; assumption.\n    + apply cong_Eq ; assumption.\n    + apply cong_Refl ; assumption.\nDefined.\n\nEnd Optim.\n", "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/Optim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704796847395, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.29885028491672605}}
{"text": "Require Export Primitives.\nRequire Import String.\n\n(**\n\n* Overview\n\nIn this module we define syntax elements of CoqDVM\n\n* Definitions\n\n*)\n\n(**\n\n** Location and Name Definitions\n\n*)\n\nDefinition Location := nat.\n\nDefinition Name := string.\n\nDefinition Register := Location.\n\nDefinition ProgramCounter := Location.\n\nDefinition ClassLocation := Location.\nDefinition FieldLocation := Location.\nDefinition MethodLocation := Location.\nDefinition ObjectLocation := Location.\nDefinition Cursor := Location.\n\nDefinition ClassName := Name.\nDefinition FieldName := Name.\nDefinition MethodName := Name.\n\n(**\n\n** Constant Definition\n\n*)\n\nInductive Constant : Type :=\n  | cnat : nat -> Constant\n(*  | cstr : Name -> Constant  \n    for later purpose*)\n  | ctrue : Constant\n  | cfalse : Constant\n  | cnull : Constant.\n\n(**\n\n** \"type\" definition\n\n*)\n\nInductive type : Type :=\n  | p : PrimType -> type\n  | r : RefType -> type\n  | v : type\nwith RefType : Type :=\n  | c : ClassLocation -> RefType\n  | a : type -> RefType\n  | sizeda : type -> nat -> RefType.\n\n(**\n\n** lhs and rhs for simple expression\n\n*)\n\nInductive lhs : Type :=\n  | reg : Register -> lhs\n  | acc : Register -> Register -> lhs\n  | ifield : Register -> FieldLocation -> lhs\n  | sfield : FieldLocation -> lhs\nwith rhs : Type :=\n  | l : lhs -> rhs\n  | cs : Constant -> rhs.\n\n(**\n\n** Instruction Definition\n\n*)\n\nInductive Instruction : Type :=\n  | nop : Instruction\n  | ret : Instruction\n  | retTo : Register -> Instruction\n  | invokes : list rhs -> MethodLocation -> Instruction\n  | invokei : Register -> list rhs -> MethodLocation -> Instruction\n  | goto : ProgramCounter -> Instruction\n  | branch : rhs -> BinaryCompOperator -> rhs -> ProgramCounter -> Instruction\n  | move : Register -> rhs -> Instruction\n  | update : rhs -> rhs -> Instruction\n  | unary : Register -> UnaryOperator -> rhs -> Instruction\n  | binaryArith : Register -> rhs -> BinaryArithOperator -> rhs -> Instruction\n  | new : Register -> ClassLocation -> Instruction\n  | newarr : Register -> type -> rhs -> Instruction\n  | cast : Register -> type -> rhs -> Instruction\n  | read : Register -> Instruction\n  | print : rhs -> Instruction\n  | hlt : Instruction.\n\n(**\n\n** Class related final definitions\n\n*)\n\nInductive MethodSig : Type := ms (am:nat) (mn:MethodName) (ret:type) (regs:nat) (args:list (type*Name)).\nInductive MethodBody : Type := mb (insts:list (ProgramCounter*Instruction)).\n\nInductive Method : Type := mtd (ml:MethodLocation) (mb:MethodBody).\n\nInductive Field : Type := fld (am:nat) (fn:FieldName) (ft:type).\n\nInductive Class : Type :=\n  | top : Class\n  | class : nat -> ClassLocation -> list FieldLocation -> list MethodLocation -> Class.\n\n(** Accessmodifier then superclass then fields then methods *)\n\n(**\n\n** Val (Values in CoqDVM) Definition\n\n*)\n\nInductive Ref : Type :=\n  | lRef : Location -> Ref\n  | null : Ref.\n\nInductive Val : Type :=\n  | prim : Prim -> Val\n  | ref : Ref -> Val.\n\n(** \n\n** Object & Array Definitions\n\nAn Object either is instance of Top class, or it made of current Class Location (Used in Casting),\nOriginal Class Location, Field Value Pairs, or it is deletedObject which comes into play during Garbage Collection.\n\n*)\n\nInductive Object : Type :=\n  | topObj : Object\n  | obj : ClassLocation -> ClassLocation -> list (FieldLocation * Val) -> Object\n  | dobj : Object.\n\nInductive Array : Type :=\n  | arr : nat -> list Val -> Array.\n\nInductive arrOrObj : Type :=\n  | ar : Array -> arrOrObj\n  | dob : Object -> arrOrObj.\n\nInductive ValOrRef : Type :=\n  | vl : Val -> ValOrRef\n  | rf : arrOrObj -> ValOrRef.\n\n(**\n\n** Program : Where all definitions meet\n\n*)\n\nInductive Program : Type := prog (cnl:list ClassName) (mnl:list MethodSig) (cl:list Class) (fl:list Field) (ml:list Method).\n", "meta": {"author": "hckkid", "repo": "DVM", "sha": "a7756cd3a2397aa3c764e98affdd600314761c70", "save_path": "github-repos/coq/hckkid-DVM", "path": "github-repos/coq/hckkid-DVM/DVM-a7756cd3a2397aa3c764e98affdd600314761c70/Defs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.2988502769805688}}
{"text": "From Undecidability.L Require Export Util.L_facts.\nFrom Undecidability.L.Tactics Require Import Lproc Lbeta Lrewrite Reflection mixedTactics.\nRequire Import ListTactics.\nImport L_Notations.\n\nLocal Ltac wLsimpl' _n := intros;try reflexivity';try standardizeGoal _n ; try reflexivity'.\nLocal Ltac wLsimpl := wLsimpl' 100.\n\n(* Lsimpl' uses correctnes lemmas and wLsimpl*)\nLtac Lsimpl' :=\n  match goal with\n  | |- eval ?s _ => assert (lambda s) by Lproc;split;[ (exact (starR _ _);fail 1)|Lproc]\n  | |- eval ?s _ => (progress (eapply eval_helper;[Lsimpl';reflexivity|]))\n\n  | _ => try Lrewrite;try wLsimpl' 100\n  end.\n\nLtac Lreduce :=\n  repeat progress (try Lrewrite;try Lbeta). \n           \n\n(*Lsimpl that uses correctnes lemmas*)\nLtac Lsimpl :=intros(*;repeat foldLocalInts*);\n  once lazymatch goal with\n  | |- _ >(<= _ ) _ => Lreduce;try Lreflexivity\n  | |- _ ⇓(_ ) _ => repeat progress Lbeta;try Lreflexivity\n  | |- _ ⇓(<= _ ) _ => Lreduce;try Lreflexivity\n  | |- _ >(_) _ => repeat progress Lbeta;try Lreflexivity\n  | |- _ >* _ => Lreduce;try Lreflexivity (* test *)\n  | |- eval _ _ => Lreduce;try Lreflexivity (* test *) \n  (*| |- _ >* _  => repeat Lsimpl';try reflexivity'\n  | |- eval _ _  => repeat Lsimpl';try reflexivity'*)\n  | |- _ == _  => repeat Lsimpl';try reflexivity'\n  end.\n\nLtac LsimplHypo := standardizeHypo 100.\n\n\n\nTactic Notation \"closedRewrite\" :=\n  match goal with\n    | [ |- context[subst ?s _ _] ] =>\n      let cl := fresh \"cl\" in assert (cl:closed s);[Lproc|rewrite !cl;clear cl]\n                                                     \n  end.\n\nTactic Notation \"closedRewrite\" \"in\" hyp(h):=\n  match type of h with\n    | context[subst ?s _ _] =>\n      let cl := fresh \"cl\" in assert (cl:closed s);[Lproc|rewrite !cl in h;clear cl]\n  end.\n\nTactic Notation \"redStep\" \"at\" integer(pos) := rewrite step_Lproc at pos;[simpl;try closedRewrite|Lproc].\n\nTactic Notation \"redStep\" \"in\" hyp(h) \"at\" integer(pos) := rewrite step_Lproc in h at pos;[simpl in h;try closedRewrite in h|Lproc].\n(*\nTactic Notation \"redStep\" := redStep at 1.\n*)\nTactic Notation \"redStep\" \"in\" hyp(h) := redStep in h at 1.\n\n(* register needed lemmas:*)\n\nLemma rho_correct s t : proc s -> lambda t -> rho s t >* s (rho s) t.\nProof.\n  intros. unfold rho,r. redStep at 1. apply star_trans_l. Lsimpl.\nQed.\n\nLemma rho_correctPow s t : proc s -> lambda t -> rho s t >(3) s (rho s) t.\nProof.\n  intros. unfold rho,r. change 3 with (1+2). apply pow_add.\n  eexists;split. apply (rcomp_1 step). now inv H0.\n  cbn. closedRewrite. apply pow_step_congL;[|reflexivity]. now Lbeta.  \nQed.\n\nHint Resolve rho_correct : Lrewrite.\n\n\nLemma rho_inj s t: rho s = rho t -> s = t.\nProof.\n  unfold rho,r. congruence.\nQed.\n\n\nHint Resolve rho_lambda rho_cls : LProc.\n\nTactic Notation \"recStep\" constr(P) \"at\" integer(i):=\n  match eval lazy [P] in P with\n      | rho ?rP => unfold P;rewrite rho_correct at i;[|Lproc..];fold P;try unfold rP\n  end.\n\nTactic Notation \"recStep\" constr(P) :=\n  intros;recStep P at 1.\n\n(*\nLemma rClosed_closed s: recProc s -> proc s.\n  intros [? [? ?]]. subst. split; auto with LProc.\nQed.\n\nHint Resolve rClosed_closed : LProc cbv.\n *)\n\nLemma I_proc : proc I.\n  fLproc.\nQed.\n\nLemma K_proc : proc K.\n  fLproc.\nQed.\n\nLemma omega_proc : proc omega.\n  fLproc.\nQed.\n\nLemma Omega_closed : closed Omega.\n  fLproc. \nQed.\n\nHint Resolve I_proc K_proc omega_proc Omega_closed: LProc.\n\nHint Extern 0 (I >(_) _)=> unfold I;reflexivity : Lrewrite.\nHint Extern 0 (K >(_) _)=> unfold K;reflexivity : Lrewrite.\n\n\nLemma Omega_diverge t: ~ eval Omega t.\nProof.\n  intros (?&?). remember Omega as s eqn:HO. induction H;subst.\n  -inv H0. easy.\n  -unfold Omega in H. inv H. cbn in *. eauto. all:easy.\nQed.\n\n", "meta": {"author": "uds-psl", "repo": "constructive-and-synthetic-reducibility-in-coq", "sha": "3bd7c2e7c311d17bb93a9edcd55e39fc1ad9aa9d", "save_path": "github-repos/coq/uds-psl-constructive-and-synthetic-reducibility-in-coq", "path": "github-repos/coq/uds-psl-constructive-and-synthetic-reducibility-in-coq/constructive-and-synthetic-reducibility-in-coq-3bd7c2e7c311d17bb93a9edcd55e39fc1ad9aa9d/L/Tactics/Lsimpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.2988502769805688}}
{"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 continuity_defs.\nRequire Export atoms2.\n\n\nInductive differ3 {o} (b : nat) (a : get_patom_set o) (f g : NTerm)\n: @NTerm o -> @NTerm o -> Type :=\n| differ3_force_int :\n    forall t1 t2 v fa ga,\n      !LIn v (free_vars f)\n      -> !LIn v (free_vars g)\n      -> differ3 b a f g t1 t2\n      -> alpha_eq f fa\n      -> alpha_eq g ga\n      -> differ3\n           b a f g\n           (force_int_bound_app v b t1 fa (uexc a))\n           (force_int_bound_app v b t2 ga (uexc a))\n| differ3_var :\n    forall v, differ3 b a f g (mk_var v) (mk_var v)\n| differ3_oterm :\n    forall op bs1 bs2,\n      !LIn a (get_utokens_o op)\n      -> length bs1 = length bs2\n      -> (forall b1 b2, LIn (b1,b2) (combine bs1 bs2) -> differ3_b b a f g b1 b2)\n      -> differ3 b a f g (oterm op bs1) (oterm op bs2)\nwith differ3_b {o} (b : nat) (a : get_patom_set o) (f g : NTerm)\n     : @BTerm o -> @BTerm o -> Type :=\n     | differ3_bterm :\n         forall vs t1 t2,\n           disjoint vs (free_vars f)\n           -> disjoint vs (free_vars g)\n           -> differ3 b a f g t1 t2\n           -> differ3_b b a f g (bterm vs t1) (bterm vs t2).\nHint Constructors differ3 differ3_b.\n\nDefinition differ3_alpha {o} b a f g (t1 t2 : @NTerm o) :=\n  {u1 : NTerm\n   & {u2 : NTerm\n      & alpha_eq t1 u1\n      # alpha_eq t2 u2\n      # differ3 b a f g u1 u2}}.\n\nDefinition differ3_implies_differ3_alpha {o} :\n  forall b a f g (t1 t2 : @NTerm o),\n    differ3 b a f g t1 t2 -> differ3_alpha b a f g t1 t2.\nProof.\n  introv d.\n  exists t1 t2; auto.\nQed.\nHint Resolve differ3_implies_differ3_alpha : slow.\n\nInductive differ3_subs {o} b a f g : @Sub o -> @Sub o -> Type :=\n| dsub3_nil : differ3_subs b a f g [] []\n| dsub3_cons :\n    forall v t1 t2 sub1 sub2,\n      differ3 b a f g t1 t2\n      -> differ3_subs b a f g sub1 sub2\n      -> differ3_subs b a f g ((v,t1) :: sub1) ((v,t2) :: sub2).\nHint Constructors differ3_subs.\n\nDefinition differ3_bterms {o} b a f g (bs1 bs2 : list (@BTerm o)) :=\n  br_bterms (differ3_b b a f g) bs1 bs2.\n\nLemma differ3_subs_sub_find_some {o} :\n  forall b a f g (sub1 sub2 : @Sub o) v t,\n    differ3_subs b a f g sub1 sub2\n    -> sub_find sub1 v = Some t\n    -> {u : NTerm & sub_find sub2 v = Some u # differ3 b a f g t u}.\nProof.\n  induction sub1; destruct sub2; introv d fs; allsimpl; tcsp;\n  inversion d; subst.\n  boolvar; cpx.\n  eexists; eauto.\nQed.\n\nLemma differ3_subs_sub_find_none {o} :\n  forall b a f g (sub1 sub2 : @Sub o) v,\n    differ3_subs b a f g sub1 sub2\n    -> sub_find sub1 v = None\n    -> sub_find sub2 v = None.\nProof.\n  induction sub1; destruct sub2; introv d fn; allsimpl; tcsp;\n  inversion d; subst.\n  boolvar; cpx.\nQed.\n\nLemma differ3_subs_filter {o} :\n  forall b a f g (sub1 sub2 : @Sub o) l,\n    differ3_subs b a f g sub1 sub2\n    -> differ3_subs b a f g (sub_filter sub1 l) (sub_filter sub2 l).\nProof.\n  induction sub1; destruct sub2; introv d; allsimpl; inversion d; auto.\n  boolvar; sp.\nQed.\n\nLemma differ3_force_int_bound {o} :\n  forall b a f g v b' (t1 t2 : @NTerm o) e1 e2,\n    !LIn v (free_vars f)\n    -> !LIn v (free_vars g)\n    -> differ3 b a f g t1 t2\n    -> differ3 b a f g e1 e2\n    -> differ3 b a f g\n               (force_int_bound v b' t1 e1)\n               (force_int_bound v b' t2 e2).\nProof.\n  introv nif nig d1 d2.\n  apply differ3_oterm; simpl; tcsp.\n  introv i; repndors; cpx; tcsp.\n  - constructor; auto.\n  - constructor; allrw disjoint_singleton_l; auto.\n    constructor; simpl; tcsp.\n    introv i; repndors; cpx; tcsp.\n    + constructor; allsimpl; auto.\n      constructor; simpl; tcsp.\n      introv i; repndors; cpx; tcsp.\n      * constructor; auto.\n      * constructor; auto.\n        constructor; simpl; tcsp.\n      * constructor; auto.\n        constructor; simpl; tcsp.\n        introv i; repndors; cpx; tcsp.\n        constructor; auto; constructor.\n      * constructor; auto; constructor.\n    + constructor; auto; constructor; simpl; tcsp.\n    + constructor; auto; constructor.\n    + constructor; auto.\nQed.\nHint Resolve differ3_force_int_bound : slow.\n\nLemma alpha_eq_force_int_bound_app {o} :\n  forall b v1 v2 (t1 t2 f1 f2 e1 e2 : @NTerm o),\n    !LIn v1 (free_vars e1)\n    -> !LIn v2 (free_vars e2)\n    -> !LIn v1 (free_vars f1)\n    -> !LIn v2 (free_vars f2)\n    -> alpha_eq t1 t2\n    -> alpha_eq e1 e2\n    -> alpha_eq f1 f2\n    -> alpha_eq\n         (force_int_bound_app v1 b t1 f1 e1)\n         (force_int_bound_app v2 b t2 f2 e2).\nProof.\n  introv ni1 ni2 ni3 ni4 aeq1 aeq2 aeq3.\n  unfold force_int_bound_app, mk_cbv, mk_less.\n  prove_alpha_eq4.\n  introv i.\n  destruct n;[|destruct n]; try omega.\n\n  - apply alphaeqbt_nilv2; auto.\n    apply alpha_eq_force_int_bound; auto.\n\n  - pose proof (ex_fresh_var\n                  ([v1,v2]\n                     ++ all_vars f1\n                     ++ all_vars f2\n               )) as h; exrepnd.\n    allunfold @all_vars; allsimpl.\n    allsimpl; allrw app_nil_r; allrw remove_nvars_nil_l.\n    allrw in_app_iff; allsimpl; allrw in_app_iff.\n    allrw not_over_or; repnd; GC.\n\n    apply (al_bterm _ _ [v]); simpl; auto.\n\n    + unfold all_vars; simpl.\n      allrw remove_nvars_nil_l; allrw app_nil_r.\n      rw disjoint_singleton_l; simpl.\n      allrw in_app_iff; simpl; allrw in_app_iff; sp.\n\n    + unfold lsubst; simpl; boolvar; allrw app_nil_r;\n      allrw disjoint_singleton_r; tcsp.\n      prove_alpha_eq4.\n      introv j.\n      destruct n;[|destruct n;[|destruct n;[|destruct n]]];\n      try omega; eauto with slow.\n\n      apply alphaeqbt_nilv2; auto.\n      repeat (rw @lsubst_aux_trivial_cl_term); auto; simpl;\n      allrw disjoint_singleton_r; auto.\nQed.\n\nLemma differ3_lsubst_aux {o} :\n  forall b a f g (t1 t2 : @NTerm o) sub1 sub2,\n    disjoint (free_vars f) (dom_sub sub1)\n    -> disjoint (free_vars g) (dom_sub sub2)\n    -> differ3 b a f g t1 t2\n    -> differ3_subs b a f g sub1 sub2\n    -> disjoint (bound_vars t1) (sub_free_vars sub1)\n    -> disjoint (bound_vars t2) (sub_free_vars sub2)\n    -> differ3 b a f g (lsubst_aux t1 sub1) (lsubst_aux t2 sub2).\nProof.\n  nterm_ind1s t1 as [v|op bs ind] Case;\n  introv clf clg dt ds disj1 disj2; allsimpl.\n\n  - Case \"vterm\".\n    inversion dt; subst; allsimpl.\n    remember (sub_find sub1 v) as f1; symmetry in Heqf1; destruct f1.\n\n    + applydup (differ3_subs_sub_find_some b a f g sub1 sub2) in Heqf1; auto.\n      exrepnd; allrw; auto.\n\n    + applydup (differ3_subs_sub_find_none b a f g sub1 sub2) in Heqf1; auto.\n      allrw; auto.\n\n  - Case \"oterm\".\n    inversion dt as [? ? ? ? ? ni1 ni2 d1 aeq1 aeq2|?|? ? ? ni len imp]; subst; allsimpl.\n\n    + allrw @sub_filter_nil_r.\n      allrw app_nil_r.\n      allrw disjoint_app_l; allrw disjoint_cons_l; allrw disjoint_app_l; repnd; GC.\n      allrw @sub_find_sub_filter; tcsp.\n      fold_terms.\n      apply differ3_force_int; auto.\n\n      * apply (ind (force_int_bound v b t1 (uexc a)) t1 []); simpl; auto; try omega.\n\n      * rw @lsubst_aux_trivial_cl_term; auto.\n        apply alphaeq_preserves_free_vars in aeq1; rw <- aeq1; auto.\n        rw <- @dom_sub_sub_filter.\n        eapply subvars_disjoint_r;[|exact clf].\n        apply subvars_remove_nvars; apply subvars_app_weak_l; auto.\n\n      * rw @lsubst_aux_trivial_cl_term; auto.\n        apply alphaeq_preserves_free_vars in aeq2; rw <- aeq2; auto.\n        rw <- @dom_sub_sub_filter.\n        eapply subvars_disjoint_r;[|exact clg].\n        apply subvars_remove_nvars; apply subvars_app_weak_l; auto.\n\n    + apply differ3_oterm; allrw map_length; auto.\n\n      introv i.\n      rw <- @map_combine in i.\n      rw in_map_iff in i; exrepnd; cpx; allsimpl.\n      applydup imp in i1.\n      destruct a1 as [l1 t1].\n      destruct a0 as [l2 t2].\n      applydup in_combine in i1; repnd.\n      allsimpl.\n      inversion i0 as [? ? ? df dg d]; subst; clear i0.\n      constructor; auto.\n      apply (ind t1 t1 l2); auto.\n\n      * rw <- @dom_sub_sub_filter.\n        eapply subvars_disjoint_r;[|exact clf].\n        apply subvars_remove_nvars; apply subvars_app_weak_l; auto.\n\n      * rw <- @dom_sub_sub_filter.\n        eapply subvars_disjoint_r;[|exact clg].\n        apply subvars_remove_nvars; apply subvars_app_weak_l; auto.\n\n      * apply differ3_subs_filter; auto.\n\n      * pose proof (subvars_sub_free_vars_sub_filter sub1 l2) as sv.\n        disj_flat_map.\n        allsimpl; allrw disjoint_app_l; repnd.\n        eapply subvars_disjoint_r; eauto.\n\n      * pose proof (subvars_sub_free_vars_sub_filter sub2 l2) as sv.\n        disj_flat_map.\n        allsimpl; allrw disjoint_app_l; repnd.\n        eapply subvars_disjoint_r; eauto.\nQed.\n\nLemma differ3_refl {o} :\n  forall b a f g (t : @NTerm o),\n    !LIn a (get_utokens t)\n    -> disjoint (bound_vars t) (free_vars f)\n    -> disjoint (bound_vars t) (free_vars g)\n    -> differ3 b a f g t t.\nProof.\n  nterm_ind t as [v|op bs ind] Case; introv ni df dg; allsimpl; auto.\n\n  Case \"oterm\".\n  allrw in_app_iff; allrw not_over_or; repnd.\n  apply differ3_oterm; auto.\n  introv i.\n  rw in_combine_same in i; repnd; subst.\n  destruct b2 as [l t].\n  disj_flat_map; allsimpl; allrw disjoint_app_l; repnd.\n  constructor; auto.\n  eapply ind; eauto.\n  intro k.\n  destruct ni.\n  rw lin_flat_map; eexists; eauto.\nQed.\nHint Resolve differ3_refl : slow.\n\nLemma differ3_subs_refl {o} :\n  forall b a f g (sub : @Sub o),\n    !LIn a (get_utokens_sub sub)\n    -> disjoint (sub_bound_vars sub) (free_vars f)\n    -> disjoint (sub_bound_vars sub) (free_vars g)\n    -> differ3_subs b a f g sub sub.\nProof.\n  induction sub; introv df dg ni; allsimpl; auto.\n  destruct a0; allrw @get_utokens_sub_cons; allrw in_app_iff; allrw not_over_or; repnd.\n  allrw disjoint_app_l; repnd.\n  constructor; eauto with slow.\nQed.\nHint Resolve differ3_subs_refl : slow.\n\nLemma differ3_change_bound_vars {o} :\n  forall b a f g vs (t1 t2 : @NTerm o),\n    differ3 b a f g t1 t2\n    -> {u1 : NTerm\n        & {u2 : NTerm\n           & differ3 b a f g u1 u2\n           # alpha_eq t1 u1\n           # alpha_eq t2 u2\n           # disjoint (bound_vars u1) vs\n           # disjoint (bound_vars u2) vs}}.\nProof.\n  nterm_ind1s t1 as [v|op bs ind] Case; introv (*clf clg*) d.\n\n  - Case \"vterm\".\n    inversion d; subst.\n    exists (@mk_var o v) (@mk_var o v); simpl; dands; eauto with slow.\n\n  - Case \"oterm\".\n    inversion d as [? ? ? ? ? ni1 ni2 d1 a1 a2|?|? ? ? ni len imp]; subst; simphyps; cpx; ginv; clear d.\n\n    + pose proof (ex_fresh_var (vs ++ free_vars f ++ free_vars g)) as h; exrepnd.\n      allrw in_app_iff; allrw not_over_or; repnd.\n      pose proof (ind (force_int_bound v b t1 (uexc a)) t1 []) as h; clear ind.\n      repeat (autodimp h hyp).\n      { simpl; omega. }\n      pose proof (h t0 (*clf clg*) d1) as k; clear h.\n      exrepnd.\n\n      fold_terms.\n\n      pose proof (change_bvars_alpha_spec fa vs) as p1.\n      remember (change_bvars_alpha vs fa) as fa1; clear Heqfa1; simpl in p1.\n      pose proof (change_bvars_alpha_spec ga vs) as p2.\n      remember (change_bvars_alpha vs ga) as ga1; clear Heqga1; simpl in p2.\n      repnd.\n\n      exists\n        (force_int_bound_app v0 b u1 fa1 (uexc a))\n        (force_int_bound_app v0 b u2 ga1 (uexc a)).\n      dands; eauto with slow.\n\n      * apply alpha_eq_force_int_bound_app; simpl; tcsp.\n        { apply alphaeq_preserves_free_vars in a1; rw <- a1; auto. }\n        { apply alphaeq_preserves_free_vars in p1; rw <- p1; auto.\n          apply alphaeq_preserves_free_vars in a1; rw <- a1; auto. }\n\n      * apply alpha_eq_force_int_bound_app; simpl; tcsp.\n        { apply alphaeq_preserves_free_vars in a2; rw <- a2; auto. }\n        { apply alphaeq_preserves_free_vars in p2; rw <- p2; auto.\n          apply alphaeq_preserves_free_vars in a2; rw <- a2; auto. }\n\n      * simpl; allrw app_nil_r.\n        rw disjoint_app_l; rw disjoint_cons_l; rw disjoint_app_l; rw disjoint_singleton_l.\n        dands; eauto with slow.\n\n      * simpl; allrw app_nil_r.\n        rw disjoint_app_l; rw disjoint_cons_l; rw disjoint_app_l; rw disjoint_singleton_l.\n        dands; eauto with slow.\n\n    + assert ({bs' : list BTerm\n               & {bs2' : list BTerm\n                  & alpha_eq_bterms bs bs'\n                  # alpha_eq_bterms bs2 bs2'\n                  # differ3_bterms b a f g bs' bs2'\n                  # disjoint (flat_map bound_vars_bterm bs') vs\n                  # disjoint (flat_map bound_vars_bterm bs2') vs}}) as h.\n\n      { revert dependent bs2.\n        induction bs; destruct bs2; introv len imp; allsimpl; ginv.\n        - exists ([] : list (@BTerm o)) ([] : list (@BTerm o));\n            dands; simpl; eauto with slow; try (apply br_bterms_nil).\n        - cpx.\n          destruct a0 as [l1 t1].\n          destruct b0 as [l2 t2].\n          pose proof (imp (bterm l1 t1) (bterm l2 t2)) as h; autodimp h hyp.\n          inversion h as [? ? ? df dg d1]; subst; clear h.\n          pose proof (ind t1 t1 l2) as h; repeat (autodimp h hyp).\n          pose proof (h t2 (*clf clg*) d1) as k; clear h.\n          exrepnd.\n\n          autodimp IHbs hyp.\n          { introv i d; eapply ind; eauto. }\n          pose proof (IHbs bs2) as k.\n          repeat (autodimp k hyp).\n          exrepnd.\n\n          pose proof (fresh_vars\n                        (length l2)\n                        (vs\n                           ++ l2\n                           ++ all_vars t1\n                           ++ all_vars t2\n                           ++ all_vars u1\n                           ++ all_vars u2\n                           ++ all_vars f\n                           ++ all_vars g\n                        )) as fv; exrepnd.\n          allrw disjoint_app_r; repnd.\n\n          exists ((bterm lvn (lsubst_aux u1 (var_ren l2 lvn))) :: bs')\n                 ((bterm lvn (lsubst_aux u2 (var_ren l2 lvn))) :: bs2');\n            dands; simpl;\n            try (apply br_bterms_cons);\n            try (apply alpha_eq_bterm_congr);\n            tcsp.\n          { apply alpha_bterm_change_aux; eauto with slow.\n            allrw disjoint_app_l; dands; eauto with slow. }\n          { apply alpha_bterm_change_aux; eauto with slow.\n            allrw disjoint_app_l; dands; eauto with slow. }\n          { apply differ3_bterm; auto.\n            apply differ3_lsubst_aux; eauto with slow;\n            try (rw @sub_free_vars_var_ren; eauto with slow);\n            try (rw @dom_sub_var_ren; eauto with slow).\n            apply differ3_subs_refl; simpl;\n            try (rw @sub_bound_vars_var_ren; auto).\n            rw @get_utokens_sub_var_ren; simpl; tcsp. }\n          { allrw disjoint_app_l; dands; eauto with slow.\n            pose proof (subvars_bound_vars_lsubst_aux\n                          u1 (var_ren l2 lvn)) as sv.\n            eapply subvars_disjoint_l;[exact sv|].\n            apply disjoint_app_l; dands; auto.\n            rw @sub_bound_vars_var_ren; auto. }\n          { allrw disjoint_app_l; dands; eauto with slow.\n            pose proof (subvars_bound_vars_lsubst_aux\n                          u2 (var_ren l2 lvn)) as sv.\n            eapply subvars_disjoint_l;[exact sv|].\n            apply disjoint_app_l; dands; auto.\n            rw @sub_bound_vars_var_ren; auto. }\n      }\n\n      exrepnd.\n      allunfold @alpha_eq_bterms.\n      allunfold @differ3_bterms.\n      allunfold @br_bterms.\n      allunfold @br_list; repnd.\n      exists (oterm op bs') (oterm op bs2'); dands; eauto with slow.\n\n      * apply alpha_eq_oterm_combine; dands; auto.\n\n      * apply alpha_eq_oterm_combine; dands; auto.\nQed.\n\nLemma differ3_subst {o} :\n  forall b a f g (t1 t2 : @NTerm o) sub1 sub2,\n    disjoint (free_vars f) (dom_sub sub1)\n    -> disjoint (free_vars g) (dom_sub sub2)\n    -> differ3 b a f g t1 t2\n    -> differ3_subs b a f g sub1 sub2\n    -> differ3_alpha b a f g (lsubst t1 sub1) (lsubst t2 sub2).\nProof.\n  introv clf clg dt ds.\n\n  pose proof (unfold_lsubst sub1 t1) as h; exrepnd.\n  pose proof (unfold_lsubst sub2 t2) as k; exrepnd.\n  rw h0; rw k0.\n\n  pose proof (differ3_change_bound_vars\n                b a f g (sub_free_vars sub1 ++ sub_free_vars sub2)\n                t1 t2 dt) as d; exrepnd.\n  allrw disjoint_app_r; repnd.\n\n  exists (lsubst_aux u1 sub1) (lsubst_aux u2 sub2); dands; auto.\n\n  - apply lsubst_aux_alpha_congr2; eauto with slow.\n\n  - apply lsubst_aux_alpha_congr2; eauto with slow.\n\n  - apply differ3_lsubst_aux; auto.\nQed.\nHint Resolve differ3_subst : slow.\n\nLemma differ3_bterms_implies_eq_map_num_bvars {o} :\n  forall b a f g (bs1 bs2 : list (@BTerm o)),\n    differ3_bterms b a f g bs1 bs2\n    -> map num_bvars bs1 = map num_bvars bs2.\nProof.\n  induction bs1; destruct bs2; introv d; allsimpl; auto;\n  allunfold @differ3_bterms; allunfold @br_bterms; allunfold @br_list;\n  allsimpl; repnd; cpx.\n  pose proof (d a0 b0) as h; autodimp h hyp.\n  inversion h; subst.\n  f_equal.\n  unfold num_bvars; simpl; auto.\nQed.\n\nDefinition differ3_sk {o} b a f g (sk1 sk2 : @sosub_kind o) :=\n  differ3_b b a f g (sk2bterm sk1) (sk2bterm sk2).\n\nInductive differ3_sosubs {o} b a f g : @SOSub o -> @SOSub o -> Type :=\n| dsosub3_nil : differ3_sosubs b a f g [] []\n| dsosub3_cons :\n    forall v sk1 sk2 sub1 sub2,\n      differ3_sk b a f g sk1 sk2\n      -> differ3_sosubs b a f g sub1 sub2\n      -> differ3_sosubs b a f g ((v,sk1) :: sub1) ((v,sk2) :: sub2).\nHint Constructors differ3_sosubs.\n\nLemma differ3_bterms_cons {o} :\n  forall b a f g (b1 b2 : @BTerm o) bs1 bs2,\n    differ3_bterms b a f g (b1 :: bs1) (b2 :: bs2)\n    <=> (differ3_b b a f g b1 b2 # differ3_bterms b a f g bs1 bs2).\nProof.\n  unfold differ3_bterms; introv.\n  rw @br_bterms_cons_iff; sp.\nQed.\n\nLemma differ3_mk_abs_substs {o} :\n  forall b a f g (bs1 bs2 : list (@BTerm o)) vars,\n    differ3_bterms b a f g bs1 bs2\n    -> length vars = length bs1\n    -> differ3_sosubs b a f g (mk_abs_subst vars bs1) (mk_abs_subst vars bs2).\nProof.\n  induction bs1; destruct bs2; destruct vars; introv d m; allsimpl; cpx; tcsp.\n  - provefalse.\n    apply differ3_bterms_implies_eq_map_num_bvars in d; allsimpl; cpx.\n  - apply differ3_bterms_cons in d; repnd.\n    destruct s, a0, b0.\n    inversion d0; subst.\n    boolvar; auto.\nQed.\n\nLemma differ3_b_change_bound_vars {o} :\n  forall b a f g vs (b1 b2 : @BTerm o),\n    differ3_b b a f g b1 b2\n    -> {u1 : BTerm\n        & {u2 : BTerm\n           & differ3_b b a f g u1 u2\n           # alpha_eq_bterm b1 u1\n           # alpha_eq_bterm b2 u2\n           # disjoint (bound_vars_bterm u1) vs\n           # disjoint (bound_vars_bterm u2) vs}}.\nProof.\n  introv d.\n  pose proof (differ3_change_bound_vars\n                b a f g vs (oterm (Exc None) [b1]) (oterm (Exc None) [b2])) as h.\n  repeat (autodimp h hyp).\n  - apply differ3_oterm; simpl; tcsp.\n    introv i; dorn i; tcsp; cpx.\n  - exrepnd.\n    inversion h2 as [|? ? ? len1 imp1]; subst; allsimpl; cpx.\n    inversion h3 as [|? ? ? len2 imp2]; subst; allsimpl; cpx.\n    pose proof (imp1 0) as k1; autodimp k1 hyp; allsimpl; clear imp1.\n    pose proof (imp2 0) as k2; autodimp k2 hyp; allsimpl; clear imp2.\n    allunfold @selectbt; allsimpl.\n    allrw app_nil_r.\n    exists x x0; dands; auto.\n    inversion h0 as [|?|? ? ? ? ? i]; subst; allsimpl; GC.\n    apply i; sp.\nQed.\n\nLemma differ3_sk_change_bound_vars {o} :\n  forall b a f g vs (sk1 sk2 : @sosub_kind o),\n    differ3_sk b a f g sk1 sk2\n    -> {u1 : sosub_kind\n        & {u2 : sosub_kind\n           & differ3_sk b a f g u1 u2\n           # alphaeq_sk sk1 u1\n           # alphaeq_sk sk2 u2\n           # disjoint (bound_vars_sk u1) vs\n           # disjoint (bound_vars_sk u2) vs}}.\nProof.\n  introv d.\n  unfold differ3_sk in d.\n  apply (differ3_b_change_bound_vars b a f g vs) in d; exrepnd; allsimpl; auto.\n  exists (bterm2sk u1) (bterm2sk u2).\n  destruct u1, u2, sk1, sk2; allsimpl; dands; auto;\n  apply alphaeq_sk_iff_alphaeq_bterm2; simpl; auto.\nQed.\n\nLemma differ3_sosubs_change_bound_vars {o} :\n  forall b a f g vs (sub1 sub2 : @SOSub o),\n    differ3_sosubs b a f g sub1 sub2\n    -> {sub1' : SOSub\n        & {sub2' : SOSub\n           & differ3_sosubs b a f g sub1' sub2'\n           # alphaeq_sosub sub1 sub1'\n           # alphaeq_sosub sub2 sub2'\n           # disjoint (bound_vars_sosub sub1') vs\n           # disjoint (bound_vars_sosub sub2') vs}}.\nProof.\n  induction sub1; destruct sub2; introv d.\n  - exists ([] : @SOSub o) ([] : @SOSub o); dands; simpl; tcsp.\n  - inversion d.\n  - inversion d.\n  - inversion d as [|? ? ? ? ? dsk dso]; subst; clear d.\n    apply IHsub1 in dso; exrepnd; auto.\n    apply (differ3_sk_change_bound_vars b a f g vs) in dsk; exrepnd; auto.\n    exists ((v,u1) :: sub1') ((v,u2) :: sub2'); dands; simpl; auto;\n    allrw disjoint_app_l; dands; eauto with slow.\nQed.\n\nLemma sosub_find_some_if_differ3_sosubs {o} :\n  forall b a f g (sub1 sub2 : @SOSub o) v sk,\n    differ3_sosubs b a f g sub1 sub2\n    -> sosub_find sub1 v = Some sk\n    -> {sk' : sosub_kind\n        & differ3_sk b a f g sk sk'\n        # sosub_find sub2 v = Some sk'}.\nProof.\n  induction sub1; destruct sub2; introv aeq sf; allsimpl; tcsp.\n  - inversion aeq.\n  - destruct a0, p; destruct s, s0.\n    inversion aeq as [|? ? ? ? ? dsk dso]; subst; clear aeq.\n    boolvar; subst; cpx; tcsp.\n    + eexists; dands; eauto.\n    + inversion dsk; subst; tcsp.\n    + inversion dsk; subst; tcsp.\nQed.\n\nLemma sosub_find_none_if_differ3_sosubs {o} :\n  forall b a f g (sub1 sub2 : @SOSub o) v,\n    differ3_sosubs b a f g sub1 sub2\n    -> sosub_find sub1 v = None\n    -> sosub_find sub2 v = None.\nProof.\n  induction sub1; destruct sub2; introv aeq sf; allsimpl; tcsp.\n  - inversion aeq.\n  - destruct a0, p; destruct s, s0.\n    inversion aeq as [|? ? ? ? ? dsk dso]; subst; clear aeq.\n    boolvar; subst; cpx; tcsp.\n    inversion dsk; subst; tcsp.\nQed.\n\nLemma differ3_subs_combine {o} :\n  forall b a f g (ts1 ts2 : list (@NTerm o)) vs,\n    length ts1 = length ts2\n    -> (forall t1 t2,\n          LIn (t1,t2) (combine ts1 ts2)\n          -> differ3 b a f g t1 t2)\n    -> differ3_subs b a f g (combine vs ts1) (combine vs ts2).\nProof.\n  induction ts1; destruct ts2; destruct vs; introv len imp; allsimpl; cpx; tcsp.\nQed.\n\nLemma differ3_apply_list {o} :\n  forall b a f g (ts1 ts2 : list (@NTerm o)) t1 t2,\n    differ3 b a f g t1 t2\n    -> length ts1 = length ts2\n    -> (forall x y, LIn (x,y) (combine ts1 ts2) -> differ3 b a f g x y)\n    -> differ3 b a f g (apply_list t1 ts1) (apply_list t2 ts2).\nProof.\n  induction ts1; destruct ts2; introv d l i; allsimpl; cpx.\n  apply IHts1; auto.\n  apply differ3_oterm; simpl; auto; tcsp.\n  introv k; repndors; cpx; tcsp; constructor; auto.\nQed.\n\nLemma differ3_sosub_filter {o} :\n  forall b a f g (sub1 sub2 : @SOSub o) vs,\n    differ3_sosubs b a f g sub1 sub2\n    -> differ3_sosubs b a f g (sosub_filter sub1 vs) (sosub_filter sub2 vs).\nProof.\n  induction sub1; destruct sub2; introv d;\n  inversion d as [|? ? ? ? ? dsk dso]; subst; auto.\n  destruct sk1, sk2; allsimpl.\n  inversion dsk; subst.\n  boolvar; tcsp.\nQed.\nHint Resolve differ3_sosub_filter : slow.\n\nLemma no_utokens_sovar {o} :\n  forall v (ts : list (@SOTerm o)),\n    no_utokens (sovar v ts) <=> (forall t, LIn t ts -> no_utokens t).\nProof.\n  introv.\n  unfold no_utokens; simpl.\n  induction ts; simpl; split; intro k; tcsp.\n  - introv i; repndors; subst; tcsp.\n    + rw app_eq_nil_iff in k; sp.\n    + rw app_eq_nil_iff in k; repnd.\n      rw IHts in k; sp.\n  - rw app_eq_nil_iff; dands; tcsp.\n    apply IHts; tcsp.\nQed.\n\nDefinition no_utokens_op {o} (op : @Opid o) :=\n  get_utokens_o op = [].\n\nLemma no_utokens_soterm {o} :\n  forall op (bs : list (@SOBTerm o)),\n    no_utokens (soterm op bs)\n    <=>\n    (no_utokens_op op # (forall vs t, LIn (sobterm vs t) bs -> no_utokens t)).\nProof.\n  introv; unfold cover_so_vars; simpl; split; intro k; repnd; dands; tcsp.\n  - allunfold @no_utokens; allsimpl.\n    rw app_eq_nil_iff in k; repnd; auto.\n  - introv i.\n    allunfold @no_utokens; allsimpl.\n    rw app_eq_nil_iff in k; repnd; auto.\n    rw flat_map_empty in k.\n    apply k in i; allsimpl; auto.\n  - allunfold @no_utokens; simpl.\n    rw app_eq_nil_iff; dands; auto.\n    rw flat_map_empty; introv i.\n    destruct a; apply k in i; allsimpl; auto.\nQed.\n\nLemma differ3_sosub_aux {o} :\n  forall b a f g (t : @SOTerm o) sub1 sub2,\n    no_utokens t\n    -> disjoint (fo_bound_vars t) (free_vars f)\n    -> disjoint (fo_bound_vars t) (free_vars g)\n    -> differ3_sosubs b a f g sub1 sub2\n    -> disjoint (fo_bound_vars t) (free_vars_sosub sub1)\n    -> disjoint (free_vars_sosub sub1) (bound_vars_sosub sub1)\n    -> disjoint (all_fo_vars t) (bound_vars_sosub sub1)\n    -> disjoint (fo_bound_vars t) (free_vars_sosub sub2)\n    -> disjoint (free_vars_sosub sub2) (bound_vars_sosub sub2)\n    -> disjoint (all_fo_vars t) (bound_vars_sosub sub2)\n    -> cover_so_vars t sub1\n    -> cover_so_vars t sub2\n    -> differ3 b a f g (sosub_aux sub1 t) (sosub_aux sub2 t).\nProof.\n  soterm_ind t as [v ts ind|op bs ind] Case;\n  introv nut df dg ds;\n  introv disj1 disj2 disj3 disj4 disj5 disj6 cov1 cov2; allsimpl.\n\n  - Case \"sovar\".\n    allrw @cover_so_vars_sovar; repnd.\n    allrw @no_utokens_sovar.\n    allrw disjoint_cons_l; repnd.\n    remember (sosub_find sub1 (v, length ts)) as f1; symmetry in Heqf1.\n    destruct f1.\n\n    + applydup (sosub_find_some_if_differ3_sosubs b a f g sub1 sub2) in Heqf1; auto.\n      exrepnd.\n      rw Heqf2.\n      destruct s as [l1 t1].\n      destruct sk' as [l2 t2].\n      inversion Heqf0; subst.\n      apply differ3_lsubst_aux; auto.\n\n      * apply sosub_find_some in Heqf2; repnd.\n        rw @dom_sub_combine; allrw map_length; eauto with slow.\n\n      * apply sosub_find_some in Heqf2; repnd.\n        rw @dom_sub_combine; allrw map_length; eauto with slow.\n\n      * apply differ3_subs_combine; allrw map_length; 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; allsimpl.\n        disj_flat_map.\n        apply ind; auto.\n\n      * apply sosub_find_some in Heqf1; repnd.\n        rw @sub_free_vars_combine; allrw map_length; auto.\n        rw flat_map_map; unfold compose.\n        eapply disjoint_bound_vars_prop3; eauto with slow.\n        eapply subvars_disjoint_r;[|apply disjoint_sym;eauto].\n        apply subvars_flat_map2; introv i.\n        apply fovars_subvars_all_fo_vars.\n\n      * apply sosub_find_some in Heqf2; repnd.\n        rw @sub_free_vars_combine; allrw map_length; auto.\n        rw flat_map_map; unfold compose.\n        eapply disjoint_bound_vars_prop3; eauto with slow.\n        eapply subvars_disjoint_r;[|apply disjoint_sym;eauto].\n        apply subvars_flat_map2; introv i.\n        apply fovars_subvars_all_fo_vars.\n\n    + applydup (sosub_find_none_if_differ3_sosubs b a f g sub1 sub2) in Heqf1; auto.\n      rw Heqf0.\n      apply differ3_apply_list; allrw map_length; auto.\n      introv i.\n      rw <- @map_combine in i; rw in_map_iff in i; exrepnd; cpx.\n      apply in_combine_same in i1; repnd; subst; allsimpl.\n      disj_flat_map.\n      apply ind; auto.\n\n  - Case \"soterm\".\n    allrw @cover_so_vars_soterm.\n    allrw @no_utokens_soterm; repnd.\n    apply differ3_oterm; allrw map_length; tcsp; try (complete (rw nut0; sp)).\n    introv i.\n    rw <- @map_combine in i; rw in_map_iff in i; exrepnd; cpx.\n    apply in_combine_same in i1; repnd; subst; allsimpl.\n    destruct a0 as [l t].\n    disj_flat_map.\n    allsimpl; allrw disjoint_app_l; repnd.\n    disj_flat_map; allsimpl; allrw disjoint_app_l; repnd.\n    constructor; auto.\n    eapply ind; eauto with slow.\n\n    + pose proof (subvars_free_vars_sosub_sosub_filter sub1 (vars2sovars l)) as sv.\n      eapply subvars_disjoint_r;[exact sv|]; auto.\n\n    + pose proof (subvars_free_vars_sosub_sosub_filter sub1 (vars2sovars l)) as sv1.\n      pose proof (subvars_bound_vars_sosub_filter sub1 (vars2sovars l)) as sv2.\n      eapply subvars_disjoint_r;[exact sv2|]; auto.\n      eapply subvars_disjoint_l;[exact sv1|]; auto.\n\n    + pose proof (subvars_bound_vars_sosub_filter sub1 (vars2sovars l)) as sv1.\n      eapply subvars_disjoint_r;[exact sv1|]; auto.\n\n    + pose proof (subvars_free_vars_sosub_sosub_filter sub2 (vars2sovars l)) as sv1.\n      eapply subvars_disjoint_r;[exact sv1|]; auto.\n\n    + pose proof (subvars_free_vars_sosub_sosub_filter sub2 (vars2sovars l)) as sv1.\n      pose proof (subvars_bound_vars_sosub_filter sub2 (vars2sovars l)) as sv2.\n      eapply subvars_disjoint_r;[exact sv2|]; auto.\n      eapply subvars_disjoint_l;[exact sv1|]; auto.\n\n    + pose proof (subvars_bound_vars_sosub_filter sub2 (vars2sovars l)) as sv1.\n      eapply subvars_disjoint_r;[exact sv1|]; auto.\n\n    + discover.\n      apply cover_so_vars_sosub_filter; auto.\n\n    + discover.\n      apply cover_so_vars_sosub_filter; auto.\nQed.\n\nLemma differ3_sosub {o} :\n  forall b a f g (t : @SOTerm o) (sub1 sub2 : SOSub),\n    no_utokens t\n    -> differ3_sosubs b a f g sub1 sub2\n    -> cover_so_vars t sub1\n    -> cover_so_vars t sub2\n    -> differ3_alpha b a f g (sosub sub1 t) (sosub sub2 t).\nProof.\n  introv nut d c1 c2.\n  pose proof (unfold_sosub sub1 t) as h.\n  destruct h as [sub1' h]; destruct h as [t1 h]; repnd; rw h.\n  pose proof (unfold_sosub sub2 t) as k.\n  destruct k as [sub2' k]; destruct k as [t2 k]; repnd; rw k.\n\n  pose proof (differ3_sosubs_change_bound_vars\n                b a\n                f g\n                (all_fo_vars t1\n                             ++ all_fo_vars t2\n                             ++ free_vars_sosub sub1\n                             ++ free_vars_sosub sub2\n                )\n                sub1 sub2\n                d) as e.\n  destruct e as [sub1'' e]; destruct e as [sub2'' e]; repnd.\n\n  pose proof (fo_change_bvars_alpha_spec\n                (free_vars_sosub sub1''\n                                 ++ free_vars_sosub sub2''\n                                 ++ bound_vars_sosub sub1''\n                                 ++ bound_vars_sosub sub2''\n                                 ++ free_vars f\n                                 ++ free_vars g\n                )\n                t) as q.\n  revert q.\n  fo_change t0; simpl; intro q; repnd; GC.\n\n  allrw disjoint_app_l; allrw disjoint_app_r; repnd.\n\n  assert (so_alphaeq t1 t0) as a1 by eauto with slow.\n  assert (so_alphaeq t2 t0) as a2 by eauto with slow.\n\n  pose proof (fovars_subvars_all_fo_vars t1) as sv1.\n  pose proof (fovars_subvars_all_fo_vars t2) as sv2.\n  pose proof (alphaeq_sosub_preserves_free_vars sub1 sub1'') as ev1; autodimp ev1 hyp.\n  pose proof (alphaeq_sosub_preserves_free_vars sub2 sub2'') as ev2; autodimp ev2 hyp.\n  pose proof (fovars_subvars_all_fo_vars t0) as sv3.\n  pose proof (all_fo_vars_eqvars t0) as ev3.\n  pose proof (all_fo_vars_eqvars t1) as ev4.\n  pose proof (so_alphaeq_preserves_free_vars t1 t0 a1) as efv1.\n  pose proof (so_alphaeq_preserves_free_vars t2 t0 a2) as efv2.\n  applydup eqvars_app_r_implies_subvars in ev4 as ev; destruct ev as [ev5 ev6].\n\n  assert (disjoint (fo_bound_vars t0) (free_vars_sosub sub1'')\n          # disjoint (free_vars_sosub sub1'') (bound_vars_sosub sub1'')\n          # disjoint (all_fo_vars t0) (bound_vars_sosub sub1'')\n          # disjoint (fo_bound_vars t0) (free_vars_sosub sub2'')\n          # disjoint (free_vars_sosub sub2'') (bound_vars_sosub sub2'')\n          # disjoint (all_fo_vars t0) (bound_vars_sosub sub2'')) as disj.\n\n  { dands; eauto with slow.\n    - rw <- ev1; eauto with slow.\n    - eapply eqvars_disjoint;[apply eqvars_sym; exact ev3|].\n      apply disjoint_app_l; dands; eauto with slow.\n      rw <- efv1.\n      eapply subvars_disjoint_l;[exact ev6|]; eauto with slow.\n    - rw <- ev2; eauto with slow.\n    - eapply eqvars_disjoint;[apply eqvars_sym; exact ev3|].\n      apply disjoint_app_l; dands; eauto with slow.\n      rw <- efv1.\n      eapply subvars_disjoint_l;[exact ev6|]; eauto with slow. }\n\n  repnd.\n\n  pose proof (sosub_aux_alpha_congr2\n                t1 t0 sub1' sub1'') as aeq1.\n  repeat (autodimp aeq1 hyp); eauto with slow.\n\n  { rw disjoint_app_r; dands; eauto with slow.\n    eapply subvars_disjoint_r;[exact sv1|]; eauto with slow. }\n\n  { rw disjoint_app_r; dands; eauto with slow.\n    eapply subvars_disjoint_r;[exact sv3|].\n    eapply eqvars_disjoint_r;[apply eqvars_sym; exact ev3|].\n    apply disjoint_app_r; dands; eauto with slow.\n    rw <- efv1.\n    eapply subvars_disjoint_r;[exact ev6|]; auto. }\n\n  pose proof (sosub_aux_alpha_congr2\n                t2 t0 sub2' sub2'') as aeq2.\n  repeat (autodimp aeq2 hyp); eauto with slow.\n\n  { rw disjoint_app_r; dands; eauto with slow.\n    eapply subvars_disjoint_r;[exact sv2|]; eauto with slow. }\n\n  { rw disjoint_app_r; dands; eauto with slow.\n    eapply subvars_disjoint_r;[exact sv3|].\n    eapply eqvars_disjoint_r;[apply eqvars_sym; exact ev3|].\n    apply disjoint_app_r; dands; eauto with slow.\n    rw <- efv1.\n    eapply subvars_disjoint_r;[exact ev6|]; auto. }\n\n  exists (sosub_aux sub1'' t0) (sosub_aux sub2'' t0); dands;\n  try (apply alphaeq_eq; complete auto).\n\n  apply differ3_sosub_aux; eauto with slow.\n\n  { allapply @get_utokens_so_soalphaeq.\n    unfold no_utokens; rw <- h5; auto. }\nQed.\n\nLemma differ3_mk_instance {o} :\n  forall b a f g (t : @SOTerm o) vars bs1 bs2,\n    no_utokens t\n    -> matching_bterms vars bs1\n    -> matching_bterms vars bs2\n    -> socovered t vars\n    -> socovered t vars\n    -> differ3_bterms b a f g bs1 bs2\n    -> differ3_alpha b a f g (mk_instance vars bs1 t) (mk_instance vars bs2 t).\nProof.\n  introv nut m1 m2 sc1 sc2 dbs.\n  unfold mk_instance.\n  applydup @matching_bterms_implies_eq_length in m1.\n  applydup (@differ3_mk_abs_substs o b a f g bs1 bs2 vars) in dbs; auto.\n\n  apply differ3_sosub; auto;\n  apply socovered_implies_cover_so_vars; auto.\nQed.\n\nLemma exists_compute_step_if_reduces_to {o} :\n  forall lib (t1 t2 : @NTerm o),\n    reduces_to lib t1 t2\n    -> isvalue_like t2\n    -> {u : NTerm\n        & compute_step lib t1 = csuccess u\n        # reduces_to lib u t2}.\nProof.\n  introv r isv.\n  unfold reduces_to in r; exrepnd.\n  destruct k.\n  - allrw @reduces_in_atmost_k_steps_0; subst.\n    unfold isvalue_like in isv; repndors.\n    + apply iscan_implies in isv; exrepnd; subst; simpl.\n      eexists; eauto with slow.\n    + apply isexc_implies2 in isv; exrepnd; subst; simpl.\n      eexists; eauto with slow.\n    + apply ismrk_implies2 in isv; exrepnd; subst; simpl.\n      eexists; eauto with slow.\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    eexists; dands; eauto with slow.\n    exists k; auto.\nQed.\n\nDefinition red_to_can {p} lib (t : @NTerm p) :=\n  {u : NTerm\n   & reduces_to lib t u\n   # iscan u}.\n\nLemma if_red_to_can_ncompop_can1 {o} :\n  forall lib c can bs (t : @NTerm o) l,\n    red_to_can\n      lib\n      (oterm (NCan (NCompOp c))\n             (bterm [] (oterm (Can can) bs)\n                    :: bterm [] t\n                    :: l))\n    -> red_to_can lib t.\nProof.\n  introv hv.\n  unfold red_to_can in hv; exrepnd.\n\n  pose proof (converges_to_value_like_ncompop lib c can bs t l) as h.\n  autodimp h hyp.\n\n  { unfold converges_to_value_like; exists u; sp. }\n\n  repndors; exrepnd.\n\n  - exists (@mk_integer o i); dands.\n    + unfold computes_to_value in h0; sp.\n    + unfold isvalue_like; simpl; sp.\n\n  - exists (@mk_token o s); dands.\n    + unfold computes_to_value in h0; sp.\n    + unfold isvalue_like; simpl; sp.\n\n  - provefalse.\n    apply isexc_implies2 in h0; exrepnd; subst.\n    pose proof (compose_reduces_to_primarg_ncompop\n                  lib c can bs t (oterm (Exc a) l0) u l) as h.\n    repeat (autodimp h hyp); tcsp.\n    apply iscan_implies in hv0; exrepnd; subst.\n    apply reduces_to_split2 in h; dorn h; simpl in h; ginv.\n    exrepnd; ginv.\n    apply reduces_to_if_isvalue_like in h0; tcsp; ginv.\nQed.\n\nLemma if_red_to_can_narithop_can1 {o} :\n  forall lib c can bs (t : @NTerm o) l,\n    red_to_can\n      lib\n      (oterm (NCan (NArithOp c))\n             (bterm [] (oterm (Can can) bs)\n                    :: bterm [] t\n                    :: l))\n    -> red_to_can lib t.\nProof.\n  introv hv.\n  unfold red_to_can in hv; exrepnd.\n\n  pose proof (converges_to_value_like_narithop lib c can bs t l) as h.\n  autodimp h hyp.\n\n  { unfold converges_to_value_like; exists u; sp. }\n\n  repndors; exrepnd.\n\n  - exists (@mk_integer o i); dands.\n    + unfold computes_to_value in h0; sp.\n    + unfold isvalue_like; simpl; sp.\n\n  - provefalse.\n    apply isexc_implies2 in h0; exrepnd; subst.\n    pose proof (compose_reduces_to_primarg_arithop\n                  lib c can bs t (oterm (Exc a) l0) u l) as h.\n    repeat (autodimp h hyp); tcsp.\n    apply iscan_implies in hv0; exrepnd; subst.\n    apply reduces_to_split2 in h; dorn h; simpl in h; ginv.\n    exrepnd; ginv.\n    apply reduces_to_if_isvalue_like in h0; tcsp; ginv.\nQed.\n\nDefinition red_to_can_k {p} lib k (t : @NTerm p) :=\n  {u : NTerm\n   & reduces_in_atmost_k_steps lib t u k\n   # iscan u}.\n\nLemma red_to_can_0 {o} :\n  forall lib (t : @NTerm o),\n    red_to_can_k lib 0 t <=> iscan t.\nProof.\n  introv; unfold red_to_can_k; split; intro k; exrepnd.\n  - allrw @reduces_in_atmost_k_steps_0; subst; auto.\n  - exists t; allrw @reduces_in_atmost_k_steps_0; auto.\nQed.\n\nLemma red_to_can_S {o} :\n  forall lib k (t : @NTerm o),\n    red_to_can_k lib (S k) t\n    <=> {u : NTerm\n         & compute_step lib t = csuccess u\n         # red_to_can_k lib k u}.\nProof.\n  introv; unfold red_to_can_k; split; intro h; exrepnd.\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    eexists; eauto.\n  - exists u0; dands; auto.\n    allrw @reduces_in_atmost_k_steps_S.\n    eexists; eauto.\nQed.\n\nLemma if_red_to_can_k_ncompop_can1 {o} :\n  forall lib c can bs k (t : @NTerm o) l,\n    red_to_can_k\n      lib k\n      (oterm (NCan (NCompOp c))\n             (bterm [] (oterm (Can can) bs)\n                    :: bterm [] t\n                    :: l))\n    -> {j : nat & j < k # red_to_can_k lib j t}.\nProof.\n  induction k; introv r.\n  - allrw @red_to_can_0; inversion r.\n  - allrw @red_to_can_S; exrepnd.\n    destruct t as [v|op bs1]; try (complete (allsimpl; ginv)).\n    dopid op as [can2|ncan2|exc2|mrk2|abs2] Case.\n    + exists 0; dands; try omega.\n      rw @red_to_can_0; auto.\n    + rw @compute_step_ncompop_ncan2 in r1.\n      remember (compute_step lib (oterm (NCan ncan2) bs1)) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @red_to_can_S.\n      exists n; tcsp.\n    + simpl in r1; ginv.\n      provefalse.\n      unfold red_to_can_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in r0; subst; tcsp.\n    + allsimpl; ginv.\n    + simpl in r1.\n      unfold on_success in r1.\n      remember (compute_step_lib lib abs2 bs1) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @red_to_can_S.\n      exists n; tcsp.\nQed.\n\nLemma if_red_to_can_k_narithop_can1 {o} :\n  forall lib c can bs k (t : @NTerm o) l,\n    red_to_can_k\n      lib k\n      (oterm (NCan (NArithOp c))\n             (bterm [] (oterm (Can can) bs)\n                    :: bterm [] t\n                    :: l))\n    -> {j : nat & j < k # red_to_can_k lib j t}.\nProof.\n  induction k; introv r.\n  - allrw @red_to_can_0; inversion r.\n  - allrw @red_to_can_S; exrepnd.\n    destruct t as [v|op bs1]; try (complete (allsimpl; ginv)).\n    dopid op as [can2|ncan2|exc2|mrk2|abs2] Case.\n    + exists 0; dands; try omega.\n      rw @red_to_can_0; auto.\n    + rw @compute_step_narithop_ncan2 in r1.\n      remember (compute_step lib (oterm (NCan ncan2) bs1)) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @red_to_can_S.\n      exists n; tcsp.\n    + simpl in r1; ginv.\n      provefalse.\n      unfold red_to_can_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in r0; subst; tcsp.\n    + allsimpl; ginv.\n    + simpl in r1.\n      unfold on_success in r1.\n      remember (compute_step_lib lib abs2 bs1) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @red_to_can_S.\n      exists n; tcsp.\nQed.\n\nLemma red_to_can_k_lt {o} :\n  forall lib k1 k2 (t : @NTerm o),\n    red_to_can_k lib k1 t\n    -> k1 < k2\n    -> red_to_can_k lib k2 t.\nProof.\n  unfold red_to_can_k; introv r l; exrepnd.\n  exists u; dands; auto.\n  pose proof (no_change_after_value_like lib t k1 u) as h.\n  repeat (autodimp h hyp); tcsp.\n  pose proof (h (k2 - k1)) as hh.\n  assert (k2 - k1 + k1 = k2) as e by omega.\n  rw e in hh; auto.\nQed.\n\nLemma if_red_to_can_k_cbv_primarg {o} :\n  forall lib k (t : @NTerm o) bs,\n    red_to_can_k lib k (oterm (NCan NCbv) (bterm [] t :: bs))\n    -> {j : nat & j < k # red_to_can_k lib j t}.\nProof.\n  induction k; introv r.\n\n  - allrw @red_to_can_0; subst.\n    inversion r.\n\n  - allrw @red_to_can_S; exrepnd.\n    destruct t as [v|op l].\n\n    { simpl in r1; ginv. }\n\n    dopid op as [can1|ncan1|exc1|mrk1|abs1] Case.\n\n    + Case \"Can\".\n      exists 0; dands; try omega.\n      rw @red_to_can_0; auto.\n\n    + Case \"NCan\".\n      rw @compute_step_ncan_ncan in r1.\n      remember (compute_step lib (oterm (NCan ncan1) l)) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @red_to_can_S; exists n; sp.\n\n    + Case \"Exc\".\n      allsimpl; ginv.\n      unfold red_to_can_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in r0; subst; tcsp.\n      inversion r1.\n\n    + Case \"Mrk\".\n      allsimpl; ginv.\n      unfold red_to_can_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_primarg_marker in r0; subst.\n      inversion r1.\n\n    + Case \"Abs\".\n      allsimpl.\n      unfold on_success in r1.\n      remember (compute_step_lib lib abs1 l) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @red_to_can_S; exists n; sp.\nQed.\n\nLemma if_red_to_can_k_force_int_bound {o} :\n  forall lib a v b k (t : @NTerm o),\n    red_to_can_k\n      lib k\n      (force_int_bound v b t (uexc a))\n    -> {j : nat\n        & {z : Z\n        & reduces_in_atmost_k_steps lib t (mk_integer z) j\n        # S (S j) < k\n        # Z.abs_nat z < b}}.\nProof.\n  induction k; introv r.\n  - allrw @red_to_can_0; inversion r.\n  - allrw @red_to_can_S; exrepnd.\n    destruct t as [v1|op1 bs1].\n    { simpl in r1; ginv. }\n    dopid op1 as [can1|ncan1|exc1|mrk1|abs1] Case.\n\n    + Case \"Can\".\n      simpl in r1; ginv.\n      unfold apply_bterm, lsubst in r0; allsimpl.\n      boolvar; fold_terms.\n      destruct k.\n\n      { allrw @red_to_can_0; inversion r0. }\n\n      allrw @red_to_can_S; exrepnd; allsimpl.\n      unfold on_success in r0.\n      fold_terms.\n      match goal with\n        | [ H : context[compute_step_comp ?a1 ?a2 ?a3 ?a4 ?a5 ?a6 ?a7] |- _ ] =>\n          remember (compute_step_comp a1 a2 a3 a4 a5 a6 a7)  as comp\n      end.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply compute_step_compop_success_can_can in Heqcomp.\n      exrepnd; subst; allsimpl; cpx; GC.\n      repndors; exrepnd; ginv.\n      allapply @get_int_from_cop_some; subst.\n\n      destruct k.\n\n      { allrw @red_to_can_0; inversion r1. }\n\n      allrw @red_to_can_S; exrepnd.\n      boolvar; allsimpl; ginv.\n\n      * destruct k.\n\n        { allrw @red_to_can_0; inversion r0. }\n\n        allrw @red_to_can_S; exrepnd.\n        allsimpl.\n        unfold compute_step_comp in r0; allsimpl; boolvar; ginv.\n\n        { exists 0 n1; dands; try omega; eauto with slow.\n          - rw @reduces_in_atmost_k_steps_0; auto.\n          - apply abs_of_neg; auto. }\n\n        { unfold red_to_can_k in r1; exrepnd.\n          apply reduces_in_atmost_k_steps_if_isvalue_like in r1; subst; tcsp.\n          inversion r0. }\n\n      * unfold compute_step_comp in r1; allsimpl; boolvar; ginv.\n\n        { exists 0 n1; dands; try omega; eauto with slow.\n          - rw @reduces_in_atmost_k_steps_0; auto.\n          - apply abs_of_pos; auto. }\n\n        { unfold red_to_can_k in r0; exrepnd.\n          apply reduces_in_atmost_k_steps_if_isvalue_like in r0; subst; tcsp.\n          inversion r1. }\n\n    + Case \"NCan\".\n      unfold force_int_bound in r1.\n      rw @compute_step_mk_cbv_ncan in r1.\n      remember (compute_step lib (oterm (NCan ncan1) bs1)) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n\n      apply IHk in r0; auto; exrepnd.\n\n      exists (S j) z; dands; auto; try omega.\n      rw @reduces_in_atmost_k_steps_S; eexists; eauto.\n\n    + Case \"Exc\".\n      allsimpl; ginv.\n      unfold red_to_can_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in r0; subst; tcsp.\n      inversion r1.\n\n    + Case \"Mrk\".\n      allsimpl; ginv.\n      unfold red_to_can_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_primarg_marker in r0; subst.\n      inversion r1.\n\n    + Case \"Abs\".\n      simpl in r1; unfold on_success in r1.\n      remember (compute_step_lib lib abs1 bs1) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n\n      apply IHk in r0; auto; exrepnd.\n\n      exists (S j) z; dands; auto; try omega.\n      rw @reduces_in_atmost_k_steps_S; eexists; eauto.\nQed.\n\nDefinition isvalue_like_except {o} a (t : @NTerm o) :=\n  isvalue_like t # !isnexc (Some a) t.\n\nDefinition has_value_like_except_k {p} lib a k (t : @NTerm p) :=\n  {u : NTerm\n   & reduces_in_atmost_k_steps lib t u k\n   # isvalue_like_except a u}.\n\nLemma has_value_like_except_0 {o} :\n  forall lib a (t : @NTerm o),\n    has_value_like_except_k lib a 0 t <=> isvalue_like_except a t.\nProof.\n  introv; unfold has_value_like_except_k; split; intro k; exrepnd.\n  - allrw @reduces_in_atmost_k_steps_0; subst; auto.\n  - exists t; allrw @reduces_in_atmost_k_steps_0; auto.\nQed.\n\nLemma has_value_like_except_S {o} :\n  forall lib k a (t : @NTerm o),\n    has_value_like_except_k lib a (S k) t\n    <=> {u : NTerm\n         & compute_step lib t = csuccess u\n         # has_value_like_except_k lib a k u}.\nProof.\n  introv; unfold has_value_like_except_k; split; intro h; exrepnd.\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    eexists; eauto.\n  - exists u0; dands; auto.\n    allrw @reduces_in_atmost_k_steps_S.\n    eexists; eauto.\nQed.\n\nLemma if_has_value_like_except_k_ncompop_can1 {o} :\n  forall lib c can bs a k (t : @NTerm o) l,\n    has_value_like_except_k\n      lib a k\n      (oterm (NCan (NCompOp c))\n             (bterm [] (oterm (Can can) bs)\n                    :: bterm [] t\n                    :: l))\n    -> {j : nat & j < k # has_value_like_except_k lib a j t}.\nProof.\n  induction k; introv r.\n  - allrw @has_value_like_except_0; repnd.\n    unfold isvalue_like_except in r; repnd.\n    inversion r0; sp.\n  - allrw @has_value_like_except_S; exrepnd.\n    destruct t as [v|op bs1]; try (complete (allsimpl; ginv)).\n    dopid op as [can2|ncan2|exc2|mrk2|abs2] Case.\n    + exists 0; dands; try omega.\n      rw @has_value_like_except_0; dands; eauto with slow.\n      unfold isvalue_like_except; simpl; sp.\n    + rw @compute_step_ncompop_ncan2 in r1.\n      remember (compute_step lib (oterm (NCan ncan2) bs1)) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @has_value_like_except_S.\n      exists n; tcsp.\n    + simpl in r1; ginv.\n      exists k; sp.\n    + allsimpl; ginv.\n    + simpl in r1.\n      unfold on_success in r1.\n      remember (compute_step_lib lib abs2 bs1) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @has_value_like_except_S.\n      exists n; tcsp.\nQed.\n\nLemma if_has_value_like_except_k_narithop_can1 {o} :\n  forall lib c can bs a k (t : @NTerm o) l,\n    has_value_like_except_k\n      lib a k\n      (oterm (NCan (NArithOp c))\n             (bterm [] (oterm (Can can) bs)\n                    :: bterm [] t\n                    :: l))\n    -> {j : nat & j < k # has_value_like_except_k lib a j t}.\nProof.\n  induction k; introv r.\n  - allrw @has_value_like_except_0; repnd.\n    unfold isvalue_like_except in r; repnd.\n    inversion r0; sp.\n  - allrw @has_value_like_except_S; exrepnd.\n    destruct t as [v|op bs1]; try (complete (allsimpl; ginv)).\n    dopid op as [can2|ncan2|exc2|mrk2|abs2] Case.\n    + exists 0; dands; try omega.\n      rw @has_value_like_except_0; dands; eauto with slow.\n      unfold isvalue_like_except; simpl; sp.\n    + rw @compute_step_narithop_ncan2 in r1.\n      remember (compute_step lib (oterm (NCan ncan2) bs1)) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @has_value_like_except_S.\n      exists n; tcsp.\n    + simpl in r1; ginv.\n      exists k; sp.\n    + allsimpl; ginv.\n    + simpl in r1.\n      unfold on_success in r1.\n      remember (compute_step_lib lib abs2 bs1) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @has_value_like_except_S.\n      exists n; tcsp.\nQed.\n\nLemma has_value_like_except_k_lt {o} :\n  forall lib a k1 k2 (t : @NTerm o),\n    has_value_like_except_k lib a k1 t\n    -> k1 < k2\n    -> has_value_like_except_k lib a k2 t.\nProof.\n  unfold has_value_like_except_k; introv r l; exrepnd.\n  exists u; dands; auto.\n  pose proof (no_change_after_value_like lib t k1 u) as h.\n  repeat (autodimp h hyp); tcsp.\n  { unfold isvalue_like_except in r0; sp. }\n  pose proof (h (k2 - k1)) as hh.\n  assert (k2 - k1 + k1 = k2) as e by omega.\n  rw e in hh; auto.\nQed.\n\nLemma if_has_value_like_except_k_cbv_primarg {o} :\n  forall lib a k (t : @NTerm o) bs,\n    has_value_like_except_k lib a k (oterm (NCan NCbv) (bterm [] t :: bs))\n    -> {j : nat & j < k # has_value_like_except_k lib a j t}.\nProof.\n  induction k; introv r.\n\n  - allrw @has_value_like_except_0; repnd.\n    unfold isvalue_like_except in r; repnd.\n    inversion r0; sp.\n\n  - allrw @has_value_like_except_S; exrepnd.\n    destruct t as [v|op l].\n\n    { simpl in r1; ginv. }\n\n    dopid op as [can1|ncan1|exc1|mrk1|abs1] Case.\n\n    + Case \"Can\".\n      exists 0; dands; try omega.\n      rw @has_value_like_except_0; dands; eauto with slow; simpl; sp.\n      unfold isvalue_like_except; simpl; dands; eauto with slow; sp.\n\n    + Case \"NCan\".\n      rw @compute_step_ncan_ncan in r1.\n      remember (compute_step lib (oterm (NCan ncan1) l)) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @has_value_like_except_S; exists n; sp.\n\n    + Case \"Exc\".\n      allsimpl; ginv.\n      unfold has_value_like_except_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in r0; subst; tcsp.\n      exists 0; dands; try omega.\n      rw @has_value_like_except_0; dands; eauto with slow.\n\n    + Case \"Mrk\".\n      allsimpl; ginv.\n      unfold has_value_like_except_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_primarg_marker in r0; subst.\n      unfold isvalue_like_except in r1; repnd.\n      inversion r0; tcsp.\n\n    + Case \"Abs\".\n      allsimpl.\n      unfold on_success in r1.\n      remember (compute_step_lib lib abs1 l) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @has_value_like_except_S; exists n; sp.\nQed.\n\nLemma isvalue_like_except_integer {o} :\n  forall a z, @isvalue_like_except o a (mk_integer z).\nProof.\n  introv; unfold isvalue_like_except; simpl; sp; eauto with slow.\nQed.\nHint Resolve isvalue_like_except_integer : slow.\n\nLemma isvalue_like_except_uni {o} :\n  forall a n, @isvalue_like_except o a (mk_uni n).\nProof.\n  introv; unfold isvalue_like_except; simpl; sp; eauto with slow.\nQed.\nHint Resolve isvalue_like_except_uni : slow.\n\nLemma if_has_value_like_except_k_force_int_bound {o} :\n  forall lib a v b k (t : @NTerm o),\n    has_value_like_except_k\n      lib a k\n      (force_int_bound v b t (uexc a))\n    -> {j : nat\n        & {u : NTerm\n           & reduces_in_atmost_k_steps lib t u j\n           # j < k\n           # isvalue_like_except a u\n           # ({z : Z & u = mk_integer z # Z.abs_nat z < b}[+]isexc u)\n       }}.\nProof.\n  induction k; introv r.\n\n  - allrw @has_value_like_except_0; repnd.\n    unfold isvalue_like_except in r; repnd.\n    inversion r0; sp.\n\n  - allrw @has_value_like_except_S; exrepnd.\n    destruct t as [v1|op1 bs1].\n    { simpl in r1; ginv. }\n    dopid op1 as [can1|ncan1|exc1|mrk1|abs1] Case.\n\n    + Case \"Can\".\n      simpl in r1; ginv.\n      unfold apply_bterm, lsubst in r0; allsimpl.\n      boolvar; fold_terms.\n      destruct k.\n\n      { allrw @has_value_like_except_0; repnd.\n        unfold isvalue_like_except in r0; repnd.\n        inversion r1; sp. }\n\n      allrw @has_value_like_except_S; exrepnd; allsimpl.\n      unfold on_success in r0.\n      fold_terms.\n      match goal with\n        | [ H : context[compute_step_comp ?a1 ?a2 ?a3 ?a4 ?a5 ?a6 ?a7] |- _ ] =>\n          remember (compute_step_comp a1 a2 a3 a4 a5 a6 a7)  as comp\n      end.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply compute_step_compop_success_can_can in Heqcomp.\n      exrepnd; subst; allsimpl; cpx; GC.\n      repndors; exrepnd; ginv.\n      allapply @get_int_from_cop_some; subst.\n\n      destruct k.\n\n      { allrw @has_value_like_except_0; repnd.\n        unfold isvalue_like_except in r1; repnd.\n        inversion r0; sp. }\n\n      allrw @has_value_like_except_S; exrepnd.\n      boolvar; allsimpl; ginv.\n\n      * destruct k.\n\n        { allrw @has_value_like_except_0; repnd.\n          unfold isvalue_like_except in r0; repnd.\n          inversion r1; sp. }\n\n        allrw @has_value_like_except_S; exrepnd.\n        allsimpl.\n        unfold compute_step_comp in r0; allsimpl; boolvar; ginv.\n\n        { exists 0 (@mk_integer o n1); dands; try omega; eauto with slow.\n          - rw @reduces_in_atmost_k_steps_0; auto.\n          - left; exists n1; dands; auto; apply abs_of_neg; auto. }\n\n        { unfold has_value_like_except_k in r1; exrepnd.\n          apply reduces_in_atmost_k_steps_if_isvalue_like in r1; subst; tcsp.\n          unfold isvalue_like_except in r0; repnd; allsimpl; boolvar; allsimpl; ginv; tcsp.\n          destruct r0; sp. }\n\n      * unfold compute_step_comp in r1; allsimpl; boolvar; ginv.\n\n        { exists 0 (@mk_integer o n1); dands; try omega; eauto with slow.\n          - rw @reduces_in_atmost_k_steps_0; auto.\n          - left; exists n1; dands; auto; apply abs_of_pos; auto. }\n\n        { unfold has_value_like_except_k in r0; exrepnd.\n          apply reduces_in_atmost_k_steps_if_isvalue_like in r0; subst; tcsp.\n          unfold isvalue_like_except in r1; repnd; allsimpl; boolvar; allsimpl; ginv; tcsp.\n          destruct r1; sp. }\n\n    + Case \"NCan\".\n      unfold force_int_bound in r1.\n      rw @compute_step_mk_cbv_ncan in r1.\n      remember (compute_step lib (oterm (NCan ncan1) bs1)) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n\n      apply IHk in r0; auto; exrepnd.\n\n      exists (S j) u; dands; auto; try omega.\n      rw @reduces_in_atmost_k_steps_S; eexists; eauto.\n\n    + Case \"Exc\".\n      allsimpl; ginv.\n      unfold has_value_like_except_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in r0; subst; tcsp.\n      allsimpl; boolvar; subst; try (complete (destruct r1; sp)); GC.\n      exists 0 (oterm (Exc exc1) bs1); dands; eauto with slow; try omega.\n      rw @reduces_in_atmost_k_steps_0; auto.\n\n    + Case \"Mrk\".\n      allsimpl; ginv.\n      unfold has_value_like_except_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_primarg_marker in r0; subst.\n      unfold isvalue_like_except in r1; repnd.\n      inversion r0; sp.\n\n    + Case \"Abs\".\n      simpl in r1; unfold on_success in r1.\n      remember (compute_step_lib lib abs1 bs1) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n\n      apply IHk in r0; auto; exrepnd.\n      exists (S j) u; dands; auto; try omega.\n      rw @reduces_in_atmost_k_steps_S; eexists; eauto.\nQed.\n\n\nLemma compute_step_force_int_bound {o} :\n  forall lib v b a z k (t u : @NTerm o),\n    compute_step lib (force_int_bound v b t (uexc a)) = csuccess u\n    -> reduces_in_atmost_k_steps lib t (mk_integer z) k\n    -> Z.abs_nat z < b\n    -> reduces_to lib u (mk_integer z).\nProof.\n  destruct t as [v1|op1 bs1];[allsimpl; ginv|];\n  introv comp r l; ginv.\n  dopid op1 as [can1|ncan2|exc1|mrk1|abs1] Case.\n\n  - Case \"Can\".\n    simpl in comp; ginv.\n    apply reduces_in_atmost_k_steps_if_isvalue_like in r; tcsp.\n    inversion r; subst.\n    unfold apply_bterm, lsubst; simpl; boolvar; fold_terms; GC.\n    destruct (Z_lt_le_dec z 0) as [i|i].\n    + apply (reduces_to_if_split2\n               _ _ (mk_less\n                      (mk_minus (mk_integer z))\n                      (mk_nat b)\n                      (mk_integer z)\n                      (uexc a)));\n      simpl; boolvar; tcsp; try omega.\n      apply (reduces_to_if_split2\n               _ _ (mk_less\n                      (mk_integer (- z))\n                      (mk_nat b)\n                      (mk_integer z)\n                      (uexc a)));\n        simpl; boolvar; tcsp; try omega.\n      apply reduces_to_if_step.\n      simpl.\n      unfold compute_step_comp; simpl; boolvar; auto.\n      provefalse.\n      pose proof (Zabs.Zabs_nat_le (Z.of_nat b) (-z)) as kk.\n      autodimp kk hyp; try omega.\n      allrw Znat.Zabs2Nat.id.\n      destruct z; allsimpl; try omega.\n    + apply (reduces_to_if_split2\n               _ _ (mk_less\n                      (mk_integer z)\n                      (mk_nat b)\n                      (mk_integer z)\n                      (uexc a)));\n      simpl; boolvar; tcsp; try omega.\n      apply reduces_to_if_step.\n      simpl.\n      unfold compute_step_comp; simpl; boolvar; auto.\n      provefalse.\n      pose proof (Zabs.Zabs_nat_le (Z.of_nat b) z) as kk.\n      autodimp kk hyp; try omega.\n      allrw Znat.Zabs2Nat.id.\n      destruct z; allsimpl; try omega.\n\n  - Case \"NCan\".\n    destruct k.\n    + allrw @reduces_in_atmost_k_steps_0; ginv.\n    + allrw @reduces_in_atmost_k_steps_S; exrepnd.\n      unfold force_int_bound in comp.\n      rw @compute_step_mk_cbv_ncan in comp.\n      rw r1 in comp; ginv; clear r1.\n      pose proof (reduces_to_prinarg\n                    lib NCbv u0 (mk_integer z)\n                    [bterm [v] (less_bound b (mk_var v) (uexc a))]) as h.\n      repeat (autodimp h hyp); eauto with slow.\n      eapply reduces_to_trans;[exact h|].\n      apply (reduces_to_if_split2\n               _ _ (less_bound b (mk_integer z) (uexc a))).\n      { simpl; unfold apply_bterm, lsubst; simpl; boolvar; tcsp. }\n      destruct (Z_lt_le_dec z 0) as [i|i].\n      * apply (reduces_to_if_split2\n                 _ _ (mk_less\n                        (mk_minus (mk_integer z))\n                        (mk_nat b)\n                        (mk_integer z)\n                        (uexc a)));\n        simpl; boolvar; tcsp; try omega.\n        apply (reduces_to_if_split2\n                 _ _ (mk_less\n                        (mk_integer (- z))\n                        (mk_nat b)\n                        (mk_integer z)\n                        (uexc a)));\n          simpl; boolvar; tcsp; try omega.\n        apply reduces_to_if_step.\n        simpl.\n        unfold compute_step_comp; simpl; boolvar; auto.\n        provefalse.\n        pose proof (Zabs.Zabs_nat_le (Z.of_nat b) (-z)) as kk.\n        autodimp kk hyp; try omega.\n        allrw Znat.Zabs2Nat.id.\n        destruct z; allsimpl; try omega.\n      * apply (reduces_to_if_split2\n                 _ _ (mk_less\n                        (mk_integer z)\n                        (mk_nat b)\n                        (mk_integer z)\n                        (uexc a)));\n        simpl; boolvar; tcsp; try omega.\n        apply reduces_to_if_step.\n        simpl.\n        unfold compute_step_comp; simpl; boolvar; auto.\n        provefalse.\n        pose proof (Zabs.Zabs_nat_le (Z.of_nat b) z) as kk.\n        autodimp kk hyp; try omega.\n        allrw Znat.Zabs2Nat.id.\n        destruct z; allsimpl; try omega.\n\n  - Case \"Exc\".\n    allsimpl; ginv.\n    apply reduces_in_atmost_k_steps_if_isvalue_like in r; tcsp; ginv.\n\n  - Case \"Mrk\".\n    allsimpl; ginv.\n    apply reduces_in_atmost_k_steps_if_isvalue_like in r; tcsp; ginv.\n\n  - Case \"Abs\".\n    destruct k.\n    + allrw @reduces_in_atmost_k_steps_0; ginv.\n    + allrw @reduces_in_atmost_k_steps_S; exrepnd.\n      unfold force_int_bound in comp.\n      rw @compute_step_mk_cbv_abs in comp.\n      rw r1 in comp; ginv; clear r1.\n      pose proof (reduces_to_prinarg\n                    lib NCbv u0 (mk_integer z)\n                    [bterm [v] (less_bound b (mk_var v) (uexc a))]) as h.\n      repeat (autodimp h hyp); eauto with slow.\n      eapply reduces_to_trans;[exact h|].\n      apply (reduces_to_if_split2\n               _ _ (less_bound b (mk_integer z) (uexc a))).\n      { simpl; unfold apply_bterm, lsubst; simpl; boolvar; tcsp. }\n      destruct (Z_lt_le_dec z 0) as [i|i].\n      * apply (reduces_to_if_split2\n                 _ _ (mk_less\n                        (mk_minus (mk_integer z))\n                        (mk_nat b)\n                        (mk_integer z)\n                        (uexc a)));\n        simpl; boolvar; tcsp; try omega.\n        apply (reduces_to_if_split2\n                 _ _ (mk_less\n                        (mk_integer (- z))\n                        (mk_nat b)\n                        (mk_integer z)\n                        (uexc a)));\n          simpl; boolvar; tcsp; try omega.\n        apply reduces_to_if_step.\n        simpl.\n        unfold compute_step_comp; simpl; boolvar; auto.\n        provefalse.\n        pose proof (Zabs.Zabs_nat_le (Z.of_nat b) (-z)) as kk.\n        autodimp kk hyp; try omega.\n        allrw Znat.Zabs2Nat.id.\n        destruct z; allsimpl; try omega.\n      * apply (reduces_to_if_split2\n                 _ _ (mk_less\n                        (mk_integer z)\n                        (mk_nat b)\n                        (mk_integer z)\n                        (uexc a)));\n        simpl; boolvar; tcsp; try omega.\n        apply reduces_to_if_step.\n        simpl.\n        unfold compute_step_comp; simpl; boolvar; auto.\n        provefalse.\n        pose proof (Zabs.Zabs_nat_le (Z.of_nat b) z) as kk.\n        autodimp kk hyp; try omega.\n        allrw Znat.Zabs2Nat.id.\n        destruct z; allsimpl; try omega.\nQed.\n\nLemma compute_step_force_int_bound_exc {o} :\n  forall lib v b a (t u e : @NTerm o),\n    compute_step lib (force_int_bound v b t (uexc a)) = csuccess u\n    -> reduces_to lib t e\n    -> isexc e\n    -> reduces_to lib u e.\nProof.\n  destruct t as [v1|op1 bs1];[allsimpl; ginv|];\n  introv comp r l; ginv.\n  dopid op1 as [can1|ncan2|exc1|mrk1|abs1] Case.\n\n  - Case \"Can\".\n    apply reduces_to_if_isvalue_like in r; eauto with slow; subst.\n    inversion l.\n\n  - Case \"NCan\".\n    apply reduces_to_split2 in r; dorn r; subst.\n    + inversion l.\n    + exrepnd.\n      unfold force_int_bound in comp.\n      rw @compute_step_mk_cbv_ncan in comp.\n      rw r1 in comp; ginv; clear r1.\n      pose proof (reduces_to_prinarg\n                    lib NCbv v0 e\n                    [bterm [v] (less_bound b (mk_var v) (uexc a))]) as h.\n      repeat (autodimp h hyp); eauto with slow.\n      eapply reduces_to_trans;[exact h|].\n      apply isexc_implies2 in l; exrepnd; subst; eauto with slow.\n\n  - Case \"Exc\".\n    allsimpl; ginv; auto.\n\n  - Case \"Mrk\".\n    allsimpl; ginv.\n    apply reduces_to_if_isvalue_like in r; subst; eauto with slow.\n    inversion l.\n\n  - Case \"Abs\".\n    apply reduces_to_split2 in r; dorn r; subst.\n    + inversion l.\n    + exrepnd.\n      unfold force_int_bound in comp.\n      rw @compute_step_mk_cbv_abs in comp.\n      rw r1 in comp; ginv; clear r1.\n      pose proof (reduces_to_prinarg\n                    lib NCbv v0 e\n                    [bterm [v] (less_bound b (mk_var v) (uexc a))]) as h.\n      repeat (autodimp h hyp); eauto with slow.\n      eapply reduces_to_trans;[exact h|].\n      apply isexc_implies2 in l; exrepnd; subst; eauto with slow.\nQed.\n\nLemma lsubst_aux_vterm_single {o} :\n  forall v (t : @NTerm o),\n    lsubst_aux (vterm v) [(v, t)] = t.\nProof.\n  introv; simpl; boolvar; auto.\nQed.\n\n(*\nLemma compute_step_lsubst_aux_int {o} :\n  forall lib (t u : @NTerm o) v arg z,\n    reduces_to lib arg (mk_integer z)\n    -> compute_step lib (lsubst_aux t [(v, arg)]) = csuccess u\n    -> red_to_can lib u\n    -> {t' : NTerm\n        & {x : NVar\n        & !LIn x (bound_vars t)\n        # alpha_eq t (lsubst_aux t' [(x,mk_var v)])\n        # reduces_to\n            lib u\n            (lsubst_aux (lsubst_aux t' [(x,mk_integer z)]) [(v,arg)]) }}.\nProof.\n  nterm_ind t as [y|op bs ind] Case; introv r comp rtc.\n\n  - Case \"vterm\".\n    allsimpl; boolvar; allsimpl; ginv.\n    apply reduces_to_split2 in r; dorn r; subst; allsimpl; ginv.\n\n    + exists (@mk_var o y) y; dands; simpl; boolvar; simpl; eauto with slow; tcsp.\n\n    + exrepnd.\n      rw r1 in comp; ginv.\n      exists (@mk_var o y) y; dands; simpl; boolvar; simpl; eauto with slow; tcsp.\n\n  - Case \"oterm\".\n    dopid op as [can|ncan|exc|mrk|abs] SCase.\n\n    + SCase \"Can\".\n      allsimpl; ginv.\n      pose proof (ex_fresh_var (all_vars (oterm (Can can) bs))) as f; exrepnd.\n      unfold all_vars in f0; allsimpl; allrw in_app_iff; allrw not_over_or; repnd.\n      exists (oterm (Can can) bs) v0; dands; auto.\n\n      * rw @lsubst_aux_trivial_cl_term; auto; simpl.\n        rw disjoint_singleton_r; auto.\n\n      * rw (lsubst_aux_trivial_cl_term (oterm (Can can) bs)); eauto with slow; simpl.\n        rw disjoint_singleton_r; auto.\n\n    + SCase \"NCan\".\n      destruct bs as [|b bs]; try (complete (allsimpl; ginv)).\n      destruct b as [l t].\n      destruct l; try (complete (allsimpl; ginv)).\n      destruct t as [v1|op1 bs1]; try (complete (allsimpl; ginv)).\n\n      * destruct (deq_nvar v1 v) as [i|i]; subst;\n        [|simpl in comp; boolvar; tcsp; ginv].\n        allrw @lsubst_aux_oterm.\n        allrw map_cons.\n        allrw @lsubst_aux_bterm_nil.\n        allrw @lsubst_aux_vterm_single.\n\n        destruct arg as [va|opa bsa]; try (complete (allsimpl; ginv)).\n        dopid opa as [cana|ncana|exca|mrka|absa] SSCase.\n\n        { SSCase \"Can\".\n          apply reduces_to_if_isvalue_like in r; eauto with slow.\n          inversion r; subst; fold_terms; GC.\n          dopid_noncan ncan SSSCase; try (complete (allsimpl; ginv)).\n\n          - SSSCase \"NFix\".\n            allsimpl.\n            apply compute_step_fix_success in comp; repnd; subst.\n            unfold red_to_can in rtc; exrepnd.\n            apply iscan_implies in rtc0; exrepnd; subst.\n            apply reduces_to_split2 in rtc1; dorn rtc1; exrepnd; allsimpl; ginv.\n\n          - SSSCase \"NCbv\".\n            allsimpl.\n            apply compute_step_cbv_success in comp; exrepnd; subst.\n            destruct bs; allsimpl; ginv; boolvar.\n            destruct bs; allsimpl; ginv; boolvar.\n            destruct b as [l t]; allsimpl; boolvar; ginv; allsimpl; repdors; tcsp; subst.\n\n            * pose proof (ex_fresh_var (v :: bound_vars t ++ free_vars t)) as h; exrepnd.\n              allsimpl; allrw app_nil_r; allrw in_app_iff; allrw not_over_or; repnd.\n              exists (oterm (NCan NCbv) [nobnd (mk_var v0), bterm [v] t]) v0; dands; auto.\n\n              { allrw not_over_or; sp. }\n\n              { simpl; boolvar; repndors; tcsp; subst.\n                allrw not_over_or; repnd; GC.\n                rw @lsubst_aux_trivial_cl_term; auto; simpl.\n                rw disjoint_singleton_r; auto. }\n\n              { simpl; boolvar; repndors; tcsp; subst; GC; allrw not_over_or; repnd; tcsp; GC.\n                allsimpl.\n                rw (lsubst_aux_trivial_cl_term t); simpl; tcsp.\n                rw (lsubst_aux_trivial_cl_term t); simpl; tcsp;\n                [|allrw disjoint_singleton_r; auto].\n\n            *\nAbort.\n*)\n\nLemma reduces_to_lsubst_aux_int {o} :\n  forall lib z1 z2 (b : @NTerm o) v arg,\n    disjoint (bound_vars b) (free_vars arg)\n    -> reduces_to lib arg (mk_integer z1)\n    -> reduces_to lib (lsubst_aux b [(v,arg)]) (mk_integer z2)\n    -> reduces_to lib (lsubst_aux b [(v,mk_integer z1)]) (mk_integer z2).\nProof.\n  introv d r1 r2.\n  unfold reduces_to in r2; exrepnd.\n  revert dependent arg.\n  revert dependent v.\n  revert dependent b.\n  induction k; introv d compa compf.\n\n  - allrw @reduces_in_atmost_k_steps_0; ginv.\n    destruct b as [x|op bs].\n\n    + allsimpl; boolvar; ginv.\n      apply reduces_to_if_isvalue_like in compa; eauto with slow; ginv; eauto with slow.\n\n    + allsimpl; boolvar; inversion compf;\n      subst; destruct bs; allsimpl; ginv; fold_terms; GC;\n      eauto with slow.\n\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n\n(*\n    nterm_ind b as [x|op bs indb] Case; ginv.\n\n    + allsimpl; boolvar; allsimpl;\n      unfold subst, lsubst; simpl; boolvar; ginv.\n      assert (reduces_to lib arg (mk_integer z2)) as r.\n      { eapply reduces_to_if_split2; eauto with slow. }\n      pose proof (reduces_to_eq_val_like lib arg (mk_integer z1) (mk_integer z2)) as h.\n      repeat (autodimp h hyp); eauto with slow; ginv; eauto with slow.\n\n    + dopid op as [can|ncan|exc|mrk|abs] Case.\n\n      * Case \"Can\".\n        allsimpl; ginv.\n        apply reduces_in_atmost_k_steps_if_isvalue_like in compf0; eauto with slow.\n        inversion compf0; subst; destruct bs; allsimpl; ginv; eauto with slow.\n\n      * Case \"NCan\".\n        destruct bs as [|b bs]; try (complete (allsimpl; ginv)).\n        destruct b as [l t].\n        destruct l; try (complete (allsimpl; ginv)).\n\n        destruct t as [x|op1 bs1]; try (complete (allsimpl; ginv)).\n\n        { destruct (deq_nvar x v) as [i|i]; subst;\n          [|simpl in compf1; boolvar; tcsp; ginv].\n          rw @lsubst_aux_oterm in compf1.\n          rw map_cons in compf1.\n          rw @lsubst_aux_bterm_nil in compf1.\n          rw @lsubst_aux_vterm_single in compf1.\n\n          destruct arg as [y|opa bsa]; try (complete (allsimpl; ginv)).\n          dopid opa as [cana|ncana|exca|mrka|absa] SCase.\n\n          - SCase \"Can\".\n            apply reduces_to_if_isvalue_like in compa; eauto with slow.\n            inversion compa; subst; fold_terms; GC.\n            dopid_noncan ncan SSCase; try (complete (allsimpl; ginv)).\n\n            + SSCase \"NFix\".\n              allsimpl.\n              apply compute_step_fix_success in compf1; repnd; subst.\n              provefalse.\n              apply reduces_in_atmost_k_steps_implies_reduces_to in compf0.\n              apply reduces_to_split2 in compf0; dorn compf0; exrepnd; allsimpl; ginv.\n\n            + SSCase \"NCbv\".\n              simpl in compf1.\n              apply compute_step_cbv_success in compf1; exrepnd; subst.\n              destruct bs; allsimpl; ginv; boolvar.\n              destruct bs; allsimpl; ginv; boolvar.\n              destruct b as [l t]; allsimpl; boolvar; ginv; allsimpl; repdors; tcsp; subst.\n\n              * apply (reduces_to_if_split2\n                         _ _ (subst (lsubst_aux t []) v (mk_integer z1)));\n                eauto with slow.\n\n              * allrw not_over_or; repnd; GC.\n                apply (reduces_to_if_split2\n                         _ _ (subst (lsubst_aux t [(v, mk_integer z1)]) v0 (mk_integer z1)));\n                  eauto with slow.\n\n            + SSCase \"NSleep\".\n              allsimpl.\n              apply compute_step_sleep_success in compf1; exrepnd; subst.\n              apply reduces_in_atmost_k_steps_implies_reduces_to in compf0.\n              apply reduces_to_if_isvalue_like in compf0; eauto with slow; ginv.\n\n            + SSCase \"NTUni\".\n              allsimpl.\n              apply compute_step_tuni_success in compf1; exrepnd; subst.\n              apply reduces_in_atmost_k_steps_implies_reduces_to in compf0.\n              apply reduces_to_if_isvalue_like in compf0; eauto with slow; ginv.\n\n            + SSCase \"NMinus\".\n              allsimpl.\n              apply compute_step_minus_success in compf1; exrepnd; subst; ginv.\n              apply reduces_in_atmost_k_steps_implies_reduces_to in compf0.\n              apply reduces_to_if_isvalue_like in compf0; eauto with slow; ginv.\n              destruct bs; allsimpl; ginv; fold_terms; GC; ginv.\n              boolvar; eauto with slow.\n\n            + SSCase \"NTryCatch\".\n              allsimpl.\n              apply compute_step_try_success in compf1; exrepnd; subst; allsimpl.\n              apply reduces_in_atmost_k_steps_implies_reduces_to in compf0.\n              apply reduces_to_if_isvalue_like in compf0; eauto with slow; ginv.\n              inversion compf0; subst; fold_terms; GC.\n              boolvar.\n              destruct bs; allsimpl; ginv.\n              destruct bs; allsimpl; ginv.\n              destruct b; allsimpl.\n              destruct l; allsimpl; cpx; allsimpl.\n              boolvar; allsimpl; ginv; repndors; tcsp; subst; eauto with slow.\n\n            + SSCase \"NCompOp\".\n              destruct bs; try (complete (allsimpl; ginv)).\n              destruct b as [l t].\n              destruct l; destruct t as [v1|op1 bs1]; try (complete (allsimpl; ginv)).\n\n              * destruct (deq_nvar v1 v) as [i|i]; subst;\n                [|allsimpl; boolvar; tcsp; complete ginv].\n                rw map_cons in compf1.\n                rw @lsubst_aux_bterm_nil in compf1.\n                rw @lsubst_aux_vterm_single in compf1.\n                simpl in compf1.\n                apply compute_step_compop_success_can_can in compf1; exrepnd; GC.\n                destruct bs; try (complete (allsimpl; ginv)).\n                destruct bs; try (complete (allsimpl; ginv)).\n                destruct bs; try (complete (allsimpl; ginv)).\n                allsimpl; cpx; boolvar.\n                destruct b as [l3 t3]; allsimpl; ginv.\n                destruct l3; allsimpl; ginv.\n                destruct b0 as [l4 t4]; allsimpl; ginv.\n                destruct l4; allsimpl; ginv.\n                cpx; fold_terms; GC.\n                apply reduces_in_atmost_k_steps_implies_reduces_to in compf0.\n                repndors; exrepnd; subst; ginv; eauto with slow.\n\n                { eapply reduces_to_if_split2; eauto; simpl.\n                  unfold compute_step_comp; simpl; auto. }\n\n                { eapply reduces_to_if_split2; eauto; simpl.\n                  unfold compute_step_comp; simpl; auto. }\n\n              * allrw map_cons.\n                allrw @lsubst_aux_bterm_nil.\n                dopid op1 as [can1|ncan1|exc1|mrk1|abs1] SSSSCase.\n\n                { SSSSCase \"Can\".\n                  simpl in compf1.\n                  apply compute_step_compop_success_can_can in compf1; exrepnd; GC.\n                  destruct bs1; allsimpl; cpx; GC.\n                  destruct bs; allsimpl; cpx; GC.\n                  destruct bs; allsimpl; cpx; GC.\n                  destruct bs; allsimpl; cpx; GC.\n                  allsimpl; cpx; boolvar.\n                  destruct b as [l3 t3]; allsimpl; ginv.\n                  destruct l3; allsimpl; ginv.\n                  destruct b0 as [l4 t4]; allsimpl; ginv.\n                  destruct l4; allsimpl; ginv.\n                  cpx; fold_terms; ginv; GC.\n                  apply reduces_in_atmost_k_steps_implies_reduces_to in compf0.\n                  repndors; exrepnd; subst; ginv; eauto with slow.\n\n                  { eapply reduces_to_if_split2; eauto; simpl.\n                    allapply @get_int_from_cop_some; subst; allsimpl.\n                    unfold compute_step_comp; simpl; auto. }\n\n                  { eapply reduces_to_if_split2; eauto; simpl.\n                    allapply @get_int_from_cop_some; subst; allsimpl.\n                    unfold compute_step_comp; simpl; auto. }\n                }\n\n                { SSSSCase \"NCan\".\n                  rw @lsubst_aux_oterm in compf1.\n                  unfold_all_mk; allunfold @mk_integer.\n                  rw @compute_step_ncompop_ncan2 in compf1.\n                  match goal with\n                    | [ H : context[compute_step ?a1 ?a2] |- _ ] =>\n                      remember (compute_step a1 a2) as comp\n                  end.\n                  symmetry in Heqcomp; destruct comp; ginv.\n*)\n\nAbort.\n\nLemma reduces_to_apply_int {o} :\n  forall lib z1 z2 (f arg : @NTerm o),\n    reduces_to lib arg (mk_integer z1)\n    -> reduces_to lib (mk_apply f arg) (mk_integer z2)\n    -> reduces_to lib (mk_apply f (mk_integer z1)) (mk_integer z2).\nProof.\n  introv r1 r2.\n  unfold reduces_to in r2; exrepnd.\n  revert dependent arg.\n  revert dependent f.\n  induction k; introv compa compf.\n\n  - allrw @reduces_in_atmost_k_steps_0; ginv.\n\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    simpl in compf1.\n    destruct f as [v|op bs]; ginv.\n    dopid op as [can|ncan|exc|mrk|abs] Case.\n\n    + Case \"Can\".\n      apply compute_step_apply_success in compf1; exrepnd; subst.\n      fold_terms; ginv.\n\nAbort.\n\nLemma reduces_to_force_int_bound_app_z {o} :\n  forall lib v b a z (t f : @NTerm o),\n    !LIn v (free_vars f)\n    -> Z.abs_nat z < b\n    -> reduces_to lib t (mk_integer z)\n    -> reduces_to lib (force_int_bound_app v b t f (uexc a))\n                  (mk_apply f (mk_integer z)).\nProof.\n  introv ni l r.\n  pose proof (reduces_to_prinarg\n                lib NCbv\n                (force_int_bound v b t (uexc a))\n                (mk_integer z)\n                [bterm [v] (mk_apply f (mk_var v))]) as h.\n  fold_terms.\n  autodimp h hyp.\n\n  - pose proof (reduces_to_prinarg\n                  lib NCbv\n                  t\n                  (mk_integer z)\n                  [bterm [v] (less_bound b (mk_var v) (uexc a))]) as h.\n    fold_terms.\n    autodimp h hyp.\n\n    + eapply reduces_to_trans; eauto.\n      apply (reduces_to_if_split2\n               _ _ (less_bound b (mk_integer z) (uexc a))).\n\n      * simpl; unfold apply_bterm, lsubst; simpl; boolvar; auto.\n\n      * destruct (Z_lt_le_dec z 0).\n\n        { apply (reduces_to_if_split2\n                   _ _ (mk_less (mk_minus (mk_integer z))\n                                (mk_nat b)\n                                (mk_integer z)\n                                (uexc a))); auto;\n          [simpl; boolvar; tcsp; try omega|].\n\n          apply (reduces_to_if_split2\n                   _ _ (mk_less (mk_integer (- z))\n                                (mk_nat b)\n                                (mk_integer z)\n                                (uexc a))); auto.\n          apply reduces_to_if_step; simpl.\n          unfold compute_step_comp; simpl; boolvar; tcsp.\n          pose proof (Zabs.Zabs_nat_le (Z.of_nat b) (- z)) as k.\n          autodimp k hyp; try omega.\n          allrw Znat.Zabs2Nat.id.\n          destruct z; allsimpl; try omega. }\n\n        { apply (reduces_to_if_split2\n                   _ _ (mk_less (mk_integer z)\n                                (mk_nat b)\n                                (mk_integer z)\n                                (uexc a))); auto;\n          [simpl; boolvar; tcsp; try omega|].\n          apply reduces_to_if_step; simpl.\n          unfold compute_step_comp; simpl; boolvar; tcsp.\n          pose proof (Zabs.Zabs_nat_le (Z.of_nat b) z) as k.\n          autodimp k hyp; try omega.\n          allrw Znat.Zabs2Nat.id.\n          destruct z; allsimpl; try omega. }\n\n  - eapply reduces_to_trans; eauto.\n    apply reduces_to_if_step; simpl.\n    unfold apply_bterm, lsubst; simpl; boolvar; tcsp;\n    try (complete (provefalse; sp)).\n\n    rw @lsubst_aux_trivial_cl_term; auto; simpl.\n    rw disjoint_singleton_r; auto.\nQed.\n\nLemma differ3_alpha_integer {o} :\n  forall b a f g z (t : @NTerm o),\n    differ3_alpha b a f g (mk_integer z) t\n    -> t = mk_integer z.\nProof.\n  introv d.\n  unfold differ3_alpha in d; exrepnd.\n  inversion d0; subst; allsimpl; cpx; fold_terms.\n  inversion d1; subst; allsimpl; cpx.\n  inversion d2; allsimpl; cpx.\nQed.\n\nLemma differ3_alpha_exc {o} :\n  forall x b a f g (e t : @NTerm o),\n    differ3_alpha b a f g e t\n    -> isnexc x e\n    -> isnexc x t.\nProof.\n  introv d i.\n  unfold differ3_alpha in d; exrepnd.\n  apply isnexc_implies in i; exrepnd; subst.\n  inversion d0; subst; allsimpl; cpx; fold_terms.\n  inversion d1; subst; allsimpl; cpx.\n  inversion d2; allsimpl; subst; boolvar; subst; tcsp.\nQed.\n\nLemma isvalue_like_except_can {o} :\n  forall a c (bs : list (@BTerm o)), @isvalue_like_except o a (oterm (Can c) bs).\nProof.\n  introv; unfold isvalue_like_except; simpl; sp; eauto with slow.\nQed.\nHint Resolve isvalue_like_except_can : slow.\n\nLemma isvalue_like_except_exc {o} :\n  forall a e (bs : list (@BTerm o)),\n    !LIn a (get_utokens_en e)\n    -> isvalue_like_except a (oterm (Exc e) bs).\nProof.\n  introv; unfold isvalue_like_except; simpl; sp; eauto with slow.\n  boolvar; tcsp.\n  destruct e; ginv; allsimpl; tcsp.\nQed.\nHint Resolve isvalue_like_except_exc : slow.\n\nLemma if_has_value_like_except_k_ncan_primarg {o} :\n  forall lib a ncan k (t : @NTerm o) bs,\n    !LIn a (get_utokens_nc ncan)\n    -> has_value_like_except_k lib a k (oterm (NCan ncan) (bterm [] t :: bs))\n    -> {j : nat & j < k # has_value_like_except_k lib a j t}.\nProof.\n  induction k; introv ni r.\n\n  - allrw @has_value_like_except_0.\n    unfold isvalue_like_except in r; repnd.\n    inversion r0; tcsp.\n\n  - allrw @has_value_like_except_S; exrepnd.\n    destruct t as [v|op l].\n\n    { simpl in r1; ginv. }\n\n    dopid op as [can1|ncan1|exc1|mrk1|abs1] Case.\n\n    + Case \"Can\".\n      exists 0; dands; try omega.\n      rw @has_value_like_except_0; eauto with slow.\n\n    + Case \"NCan\".\n      rw @compute_step_ncan_ncan in r1.\n      remember (compute_step lib (oterm (NCan ncan1) l)) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply IHk in r0; exrepnd; auto.\n      exists (S j); dands; try omega.\n      rw @has_value_like_except_S.\n      exists n; sp.\n\n    + Case \"Exc\".\n      allsimpl.\n      apply compute_step_catch_success in r1.\n      dorn r1; exrepnd; subst; allsimpl.\n\n      * exists 0; dands; try omega.\n        rw @has_value_like_except_0; eauto with slow.\n\n      * exists 0; dands; try omega.\n        unfold has_value_like_except_k in r0; exrepnd.\n        apply reduces_in_atmost_k_steps_if_isvalue_like in r0; eauto with slow; subst.\n        unfold isvalue_like_except in r1; repnd; allsimpl; boolvar; tcsp;\n        try (complete (destruct r1; sp)); GC.\n        rw @has_value_like_except_0; eauto with slow.\n        apply isvalue_like_except_exc; simpl.\n        destruct exc1; allsimpl; tcsp.\n        intro j; dorn j; tcsp; subst; sp.\n\n    + Case \"Mrk\".\n      allsimpl; ginv.\n      unfold has_value_like_except_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_primarg_marker in r0; subst.\n      unfold isvalue_like_except in r1; repnd.\n      inversion r0; sp.\n\n    + Case \"Abs\".\n      allsimpl.\n      unfold on_success in r1.\n      remember (compute_step_lib lib abs1 l) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply IHk in r0; exrepnd; auto.\n      exists (S j); dands; try omega.\n      rw @has_value_like_except_S.\n      exists n; sp.\nQed.\n\nLemma comp_force_int_step3 {o} :\n  forall lib b a f g (t1 t2 : @NTerm o) kk u,\n    !LIn a (get_utokens f)\n    -> !LIn a (get_utokens g)\n    -> agree_upto_b lib b f g\n    -> differ3 b a f g t1 t2\n    -> compute_step lib t1 = csuccess u\n    -> has_value_like_except_k lib a kk u\n    -> (forall t1 t2 v m, (* induction hypothesis *)\n          m < S kk\n          -> isvalue_like_except a v\n          -> reduces_in_atmost_k_steps lib t1 v m\n          -> differ3 b a f g t1 t2\n          -> {v' : NTerm & reduces_to lib t2 v' # differ3_alpha b a f g v v'})\n    -> {t : NTerm\n        & {u' : NTerm\n           & reduces_to lib t2 t\n           # reduces_to lib u u'\n           # differ3_alpha b a f g u' t}}.\nProof.\n  nterm_ind1s t1 as [v|op bs ind] Case;\n  introv nif nig agree d comp hv compind.\n\n  - Case \"vterm\".\n    simpl.\n    inversion d; subst; allsimpl; ginv.\n\n  - Case \"oterm\".\n    dopid op as [can|ncan|exc|mrk|abs] SCase; ginv.\n\n    + SCase \"Can\".\n      inversion d; subst.\n      allsimpl; ginv.\n      exists (oterm (Can can) bs2) (oterm (Can can) bs); dands; eauto with slow.\n\n    + SCase \"NCan\".\n      destruct bs as [|b1 bs];\n        try (complete (allsimpl; ginv));[].\n\n      destruct b1 as [l1 t1].\n      destruct l1; try (complete (simpl in comp; ginv)).\n\n      destruct t1 as [v1|op1 bs1].\n\n      * destruct t2 as [v2|op2 bs2]; try (complete (inversion d));[].\n\n        inversion d as [? ? ? ? d1|?|? ? ? len imp]; subst; simphyps; cpx; ginv.\n\n      * (* Now destruct op2 *)\n        dopid op1 as [can1|ncan1|exc1|mrk1|abs1] SSCase; ginv.\n\n        { SSCase \"Can\".\n\n          (* Because the principal argument is canonical we can destruct ncan *)\n          dopid_noncan ncan SSSCase.\n\n          - SSSCase \"NApply\".\n            allsimpl.\n            apply compute_step_apply_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [?|?|? ? ? ni len imp]; subst; allsimpl; GC; clear d.\n            destruct bs2; allsimpl; cpx.\n            cpx; allsimpl.\n\n            pose proof (imp (bterm [] (oterm (Can NLambda) [bterm [v] b0])) b1) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [] arg) x) as d2.\n            autodimp d2 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n            inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n\n            inversion d3 as [?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; GC; clear d3.\n            destruct bs2; allsimpl; cpx.\n            cpx.\n\n            pose proof (imp1 (bterm [v] b0) b1) as d1.\n            autodimp d1 hyp.\n            clear imp1.\n            inversion d1 as [? ? ? df2 dg2 d2]; subst; clear d1.\n\n            exists (subst t2 v t0) (subst b0 v arg); dands; eauto with slow.\n\n            apply differ3_subst; simpl; eauto with slow.\n\n          - SSSCase \"NFix\".\n            allsimpl.\n            apply compute_step_fix_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [?|?|? ? ? ni len imp]; subst; allsimpl; GC; clear d.\n            destruct bs2; allsimpl; cpx.\n            destruct bs2; allsimpl; cpx.\n            cpx; GC.\n\n            pose proof (imp (bterm [] (oterm (Can can1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n\n            inversion d3 as [?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; GC; clear d3.\n\n            exists (mk_apply (oterm (Can can1) bs2)\n                             (mk_fix (oterm (Can can1) bs2)))\n                   (mk_apply (oterm (Can can1) bs1)\n                             (mk_fix (oterm (Can can1) bs1))).\n            dands; eauto with slow.\n\n            apply differ3_implies_differ3_alpha.\n            apply differ3_oterm; simpl; tcsp.\n            introv j; repndors; cpx; tcsp.\n\n            { constructor; auto ; constructor; allsimpl; auto. }\n\n            { constructor; auto; constructor; simpl; tcsp.\n              introv j; repndors; cpx; tcsp. }\n\n          - SSSCase \"NSpread\".\n            allsimpl.\n            apply compute_step_spread_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [?|?|? ? ? ni len imp]; subst; allsimpl; GC; clear d.\n            destruct bs2; allsimpl; cpx.\n            cpx; allsimpl.\n\n            pose proof (imp (bterm [] (oterm (Can NPair) [bterm [] a0, bterm [] b0])) b1) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [va,vb] arg) x) as d2.\n            autodimp d2 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n            inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n\n            inversion d3 as [?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; GC; clear d3.\n            destruct bs2; allsimpl; cpx.\n            cpx; allsimpl.\n\n            pose proof (imp1 (bterm [] a0) b1) as d1.\n            autodimp d1 hyp.\n            pose proof (imp1 (bterm [] b0) x) as d2.\n            autodimp d2 hyp.\n            clear imp1.\n            inversion d1 as [? ? ? df5 dg5 d5]; subst; clear d1.\n            inversion d2 as [? ? ? df6 dg6 d6]; subst; clear d2.\n\n            exists (lsubst t0 [(va,t2),(vb,t3)]) (lsubst arg [(va,a0),(vb,b0)]); dands; eauto with slow.\n            apply differ3_subst; simpl; eauto with slow.\n\n          - SSSCase \"NDsup\".\n            allsimpl.\n            apply compute_step_dsup_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [?|?|? ? ? ni len imp]; subst; allsimpl; GC; clear d.\n            destruct bs2; allsimpl; cpx.\n            cpx; allsimpl.\n\n            pose proof (imp (bterm [] (oterm (Can NSup) [bterm [] a0, bterm [] b0])) b1) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [va,vb] arg) x) as d2.\n            autodimp d2 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n            inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n\n            inversion d3 as [?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; GC; clear d3.\n            destruct bs2; allsimpl; cpx.\n            cpx; allsimpl.\n\n            pose proof (imp1 (bterm [] a0) b1) as d1.\n            autodimp d1 hyp.\n            pose proof (imp1 (bterm [] b0) x) as d2.\n            autodimp d2 hyp.\n            clear imp1.\n            inversion d1 as [? ? ? df5 dg5 d5]; subst; clear d1.\n            inversion d2 as [? ? ? df6 dg6 d6]; subst; clear d2.\n\n            exists (lsubst t0 [(va,t2),(vb,t3)]) (lsubst arg [(va,a0),(vb,b0)]); dands; eauto with slow.\n            apply differ3_subst; simpl; eauto with slow.\n\n          - SSSCase \"NDecide\".\n            allsimpl.\n            apply compute_step_decide_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [?|?|? ? ? ni len imp]; subst; allsimpl; GC; clear d.\n            destruct bs2; allsimpl; cpx.\n            destruct bs2; allsimpl; cpx.\n            cpx; allsimpl.\n\n            pose proof (imp (bterm [] (oterm (Can can1) [bterm [] d0])) b0) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [v1] t1) b1) as d2.\n            autodimp d2 hyp.\n            pose proof (imp (bterm [v2] t0) x) as d3.\n            autodimp d3 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df4 dg4 d4]; subst; clear d1.\n            inversion d2 as [? ? ? df5 dg5 d5]; subst; clear d2.\n            inversion d3 as [? ? ? df6 dg6 d6]; subst; clear d3.\n\n            inversion d4 as [?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; GC; clear d4.\n            cpx; allsimpl.\n\n            pose proof (imp1 (bterm [] d0) x) as d1.\n            autodimp d1 hyp.\n            clear imp1.\n            inversion d1 as [? ? ? df2 dg2 d2]; subst; clear d1.\n\n            dorn comp0; repnd; subst.\n\n            + exists (subst t4 v1 t3) (subst t1 v1 d0); dands; eauto with slow.\n              apply differ3_subst; simpl; eauto with slow.\n\n            + exists (subst t5 v2 t3) (subst t0 v2 d0); dands; eauto with slow.\n              apply differ3_subst; simpl; eauto with slow.\n\n          - SSSCase \"NCbv\".\n            allsimpl.\n            apply compute_step_cbv_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [?|?|? ? ? ni len imp]; subst; allsimpl; GC; clear d.\n            destruct bs2; allsimpl; cpx.\n            cpx; allsimpl.\n\n            pose proof (imp (bterm [] (oterm (Can can1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [v] x) x0) as d2.\n            autodimp d2 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n            inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n\n            inversion d3 as [?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; GC; clear d3.\n\n            exists (subst t0 v (oterm (Can can1) bs2))\n                   (subst x v (oterm (Can can1) bs1)); dands; eauto with slow.\n            apply differ3_subst; simpl; eauto with slow.\n\n          - SSSCase \"NSleep\".\n            allsimpl.\n            apply compute_step_sleep_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [?|?|? ? ? ni len imp]; subst; allsimpl; GC; clear d.\n            cpx; allsimpl.\n\n            pose proof (imp (bterm [] (oterm (Can (Nint z)) [])) x) as d1.\n            autodimp d1 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df2 sg2 d2]; subst; clear d1.\n\n            inversion d2 as [?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; GC; clear d2.\n            cpx; allsimpl.\n\n            exists (@mk_axiom o)\n                   (@mk_axiom o).\n            dands; eauto with slow.\n            apply differ3_implies_differ3_alpha; auto.\n            apply differ3_refl; simpl; tcsp.\n\n          - SSSCase \"NTUni\".\n            allsimpl.\n            apply compute_step_tuni_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [?|?|? ? ? ni len imp]; subst; allsimpl; GC; clear d.\n            cpx; allsimpl.\n\n            pose proof (imp (bterm [] (oterm (Can (Nint (Z.of_nat n))) [])) x) as d1.\n            autodimp d1 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df2 dg2 d2]; subst; clear d1.\n\n            inversion d2 as [?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; GC; clear d2.\n            cpx; allsimpl.\n\n            exists (@mk_uni o n)\n                   (@mk_uni o n).\n            dands; eauto with slow.\n            { apply reduces_to_if_step; simpl.\n              unfold compute_step_tuni; simpl; boolvar; try omega.\n              rw Znat.Nat2Z.id; auto. }\n\n            apply differ3_implies_differ3_alpha; auto.\n            apply differ3_refl; simpl; tcsp.\n\n          - SSSCase \"NMinus\".\n            allsimpl.\n            apply compute_step_minus_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [?|?|? ? ? ni len imp]; subst; allsimpl; GC; clear d.\n            cpx; allsimpl.\n\n            pose proof (imp (bterm [] (oterm (Can (Nint z)) [])) x) as d1.\n            autodimp d1 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df2 dg2 d2]; subst; clear d1.\n\n            inversion d2 as [?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; GC; clear d2.\n            cpx; allsimpl.\n\n            exists (@mk_integer o (- z))\n                   (@mk_integer o (- z)).\n            dands; eauto with slow.\n\n            apply differ3_implies_differ3_alpha; auto.\n            apply differ3_refl; simpl; tcsp.\n\n          - SSSCase \"NTryCatch\".\n            allsimpl.\n            apply compute_step_try_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [?|?|? ? ? ni len imp]; subst; allsimpl; GC; clear d.\n            destruct bs2; allsimpl; cpx.\n            cpx; allsimpl.\n\n            pose proof (imp (bterm [] (oterm (Can can1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [v] x) x0) as d2.\n            autodimp d2 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n            inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n\n            inversion d3 as [?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; GC; clear d3.\n\n            exists (oterm (Can can1) bs2)\n                   (oterm (Can can1) bs1).\n            dands; eauto with slow.\n\n          - SSSCase \"NCompOp\".\n            destruct bs; try (complete (allsimpl; ginv)).\n            destruct b0 as [l t].\n            destruct l; destruct t as [v|op bs2]; try (complete (allsimpl; ginv)).\n\n            inversion d as [?|?|? ? ? ni len imp]; subst; clear d.\n            simpl in len, ni; GC.\n\n            destruct bs3; simpl in len; cpx.\n            destruct bs3; simpl in len; cpx.\n            simpl in imp.\n\n            pose proof (imp (bterm [] (oterm (Can can1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [] (oterm op bs2)) b1) as d2.\n            autodimp d2 hyp.\n\n            inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n            inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n\n            inversion d3 as [|?|? ? ? ni1 len1 imp1]; subst; clear d3; cpx.\n\n            dopid op as [can3|ncan3|exc3|mrk3|abs3] SSSSCase.\n\n            + SSSSCase \"Can\".\n              simpl in comp.\n\n              inversion d4 as [|?|? ? ? ni2 len2 imp2]; subst; clear d4; cpx.\n\n              apply compute_step_compop_success_can_can in comp.\n              exrepnd; subst.\n\n              allsimpl; cpx.\n              destruct bs3; allsimpl; cpx.\n              destruct bs3; allsimpl; cpx.\n              destruct bs3; allsimpl; cpx.\n              GC.\n              clear imp2.\n\n              pose proof (imp (nobnd t1) b0) as d1.\n              autodimp d1 hyp.\n              pose proof (imp (nobnd t2) b1) as d2.\n              autodimp d2 hyp.\n              clear imp.\n\n              inversion d1 as [? ? ? df33 dg33 d3]; subst; clear d1.\n              inversion d2 as [? ? ? df44 dg44 d4]; subst; clear d2.\n\n              dorn comp1;[|dorn comp1]; exrepnd; subst.\n\n              * allapply @get_int_from_cop_some; subst; allsimpl.\n                exists (if Z_lt_le_dec n1 n2 then t3 else t4)\n                       (if Z_lt_le_dec n1 n2 then t1 else t2);\n                  dands; eauto with slow.\n                boolvar; eauto with slow.\n\n              * allapply @get_int_from_cop_some; subst; allsimpl.\n                exists (if Z.eq_dec n1 n2 then t3 else t4)\n                       (if Z.eq_dec n1 n2 then t1 else t2);\n                  dands; eauto with slow.\n                boolvar; eauto with slow.\n\n              * allapply @get_str_from_cop_some; subst; allsimpl.\n                exists (if String.string_dec s1 s2 then t3 else t4)\n                       (if String.string_dec s1 s2 then t1 else t2);\n                  dands; eauto with slow.\n                boolvar; eauto with slow.\n\n            + SSSSCase \"NCan\".\n              rw @compute_step_ncompop_ncan2 in comp.\n              remember (compute_step lib (oterm (NCan ncan3) bs2)) as comp1;\n                symmetry in Heqcomp1.\n              destruct comp1; ginv.\n\n              pose proof (ind (oterm (NCan ncan3) bs2) (oterm (NCan ncan3) bs2) []) as h; clear ind.\n              repeat (autodimp h hyp); tcsp.\n\n              pose proof (h t0 kk n) as k; clear h.\n              repeat (autodimp k hyp).\n\n              { apply if_has_value_like_except_k_ncompop_can1 in hv; exrepnd.\n                apply (has_value_like_except_k_lt lib a j kk) in hv0; auto. }\n\n              exrepnd.\n\n              exists (oterm (NCan (NCompOp c))\n                            (bterm [] (oterm (Can can1) bs4)\n                                   :: bterm [] t\n                                   :: bs3))\n                     (oterm (NCan (NCompOp c))\n                            (bterm [] (oterm (Can can1) bs1)\n                                   :: bterm [] u'\n                                   :: bs)).\n              dands; eauto with slow.\n\n              * apply reduce_to_prinargs_comp2; eauto with slow; sp.\n\n              * apply reduce_to_prinargs_comp2; eauto with slow; sp.\n\n              * unfold differ3_alpha in k1; exrepnd.\n                exists (oterm (NCan (NCompOp c))\n                              (bterm [] (oterm (Can can1) bs1)\n                                     :: bterm [] u1\n                                     :: bs))\n                       (oterm (NCan (NCompOp c))\n                              (bterm [] (oterm (Can can1) bs4)\n                                     :: bterm [] u2\n                                     :: bs3)).\n                dands.\n\n                { prove_alpha_eq4.\n                  introv j; destruct n0;[|destruct n0]; try omega; cpx.\n                  apply alphaeqbt_nilv2; auto. }\n\n                { prove_alpha_eq4.\n                  introv j; destruct n0;[|destruct n0]; try omega; cpx.\n                  apply alphaeqbt_nilv2; auto. }\n\n                { apply differ3_oterm; simpl; tcsp.\n                  introv j; repndors; cpx. }\n\n            + SSSSCase \"Exc\".\n              allsimpl; ginv.\n              inversion d4 as [|?|? ? ? len2 imp2]; subst; clear d4; cpx.\n              exists (oterm (Exc exc3) bs5) (oterm (Exc exc3) bs2); dands; eauto with slow.\n\n            + SSSSCase \"Mrk\".\n              allsimpl; ginv.\n\n            + SSSSCase \"Abs\".\n              allsimpl.\n              unfold on_success in comp.\n              remember (compute_step_lib lib abs3 bs2) as comp1.\n              symmetry in Heqcomp1; destruct comp1; ginv.\n              apply compute_step_lib_success in Heqcomp1; exrepnd; subst.\n\n              inversion d4 as [|?|? ? ? ni2 len2 imp2]; subst; simphyps; clear d4.\n\n              assert (differ3_bterms b a f g bs2 bs5) as dbs.\n              { unfold differ3_bterms, br_bterms, br_list; auto. }\n\n              pose proof (found_entry_change_bs abs3 oa2 vars rhs lib bs2 correct bs5) as fe2.\n              repeat (autodimp fe2 hyp).\n\n              { apply differ3_bterms_implies_eq_map_num_bvars in dbs; auto. }\n\n              exists (oterm (NCan (NCompOp c))\n                            (bterm [] (oterm (Can can1) bs4)\n                                   :: bterm [] (mk_instance vars bs5 rhs)\n                                   :: bs3))\n              (oterm (NCan (NCompOp c))\n                     (bterm [] (oterm (Can can1) bs1)\n                            :: bterm [] (mk_instance vars bs2 rhs)\n                            :: bs)).\n\n             dands; eauto with slow.\n\n             * apply reduces_to_if_step.\n               simpl; unfold on_success.\n               applydup @compute_step_lib_if_found_entry in fe2.\n               rw fe0; auto.\n\n             * pose proof (differ3_mk_instance b a f g rhs vars bs2 bs5) as h.\n               repeat (autodimp h hyp); tcsp; GC.\n               { unfold correct_abs in correct; sp. }\n               { allapply @found_entry_implies_matching_entry.\n                 allunfold @matching_entry; sp. }\n               { allapply @found_entry_implies_matching_entry.\n                 allunfold @matching_entry; sp. }\n               { allunfold @correct_abs; sp. }\n               { allunfold @correct_abs; sp. }\n               unfold differ3_alpha in h.\n               exrepnd.\n\n               exists\n                 (oterm (NCan (NCompOp c))\n                        (bterm [] (oterm (Can can1) bs1)\n                               :: bterm [] u1\n                               :: bs))\n                 (oterm (NCan (NCompOp c))\n                        (bterm [] (oterm (Can can1) bs4)\n                               :: bterm [] u2\n                               :: bs3)).\n               dands.\n\n               { prove_alpha_eq4.\n                 introv j; destruct n;[|destruct n]; try omega; cpx.\n                 apply alphaeqbt_nilv2; auto. }\n\n               { prove_alpha_eq4.\n                 introv j; destruct n;[|destruct n]; try omega; cpx.\n                 apply alphaeqbt_nilv2; auto. }\n\n               { apply differ3_oterm; allsimpl; tcsp.\n                 introv j; repndors; cpx. }\n\n          - SSSCase \"NArithOp\".\n            destruct bs; try (complete (allsimpl; ginv)).\n            destruct b0 as [l t].\n            destruct l; destruct t as [v|op bs2]; try (complete (allsimpl; ginv)).\n\n            inversion d as [?|?|? ? ? ni len imp]; subst; clear d.\n            simpl in len, ni; GC.\n\n            destruct bs3; simpl in len; cpx.\n            destruct bs3; simpl in len; cpx.\n            simpl in imp.\n\n            pose proof (imp (bterm [] (oterm (Can can1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [] (oterm op bs2)) b1) as d2.\n            autodimp d2 hyp.\n\n            inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n            inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n\n            inversion d3 as [|?|? ? ? ni1 len1 imp1]; subst; clear d3; cpx.\n\n            dopid op as [can3|ncan3|exc3|mrk3|abs3] SSSSCase.\n\n            + SSSSCase \"Can\".\n              simpl in comp.\n\n              inversion d4 as [|?|? ? ? ni2 len2 imp2]; subst; clear d4; cpx.\n\n              apply compute_step_arithop_success_can_can in comp.\n              exrepnd; subst.\n\n              allsimpl; cpx.\n\n              allapply @get_int_from_cop_some; subst; allsimpl; GC.\n              exists (@oterm o (Can (Nint (get_arith_op a0 n1 n2))) [])\n                     (@oterm o (Can (Nint (get_arith_op a0 n1 n2))) []);\n                dands; eauto with slow.\n\n              apply differ3_implies_differ3_alpha.\n              apply differ3_refl; simpl; tcsp.\n\n            + SSSSCase \"NCan\".\n              rw @compute_step_narithop_ncan2 in comp.\n              remember (compute_step lib (oterm (NCan ncan3) bs2)) as comp1;\n                symmetry in Heqcomp1.\n              destruct comp1; ginv.\n\n              pose proof (ind (oterm (NCan ncan3) bs2) (oterm (NCan ncan3) bs2) []) as h; clear ind.\n              repeat (autodimp h hyp); tcsp.\n\n              pose proof (h t0 kk n) as k; clear h.\n              repeat (autodimp k hyp).\n\n              { apply if_has_value_like_except_k_narithop_can1 in hv; exrepnd.\n                apply (has_value_like_except_k_lt lib a j kk) in hv0; auto. }\n\n              exrepnd.\n\n              exists (oterm (NCan (NArithOp a0))\n                            (bterm [] (oterm (Can can1) bs4)\n                                   :: bterm [] t\n                                   :: bs3))\n                     (oterm (NCan (NArithOp a0))\n                            (bterm [] (oterm (Can can1) bs1)\n                                   :: bterm [] u'\n                                   :: bs)).\n              dands; eauto with slow.\n\n              * apply reduce_to_prinargs_arith2; eauto with slow; sp.\n\n              * apply reduce_to_prinargs_arith2; eauto with slow; sp.\n\n              * unfold differ3_alpha in k1; exrepnd.\n                exists (oterm (NCan (NArithOp a0))\n                              (bterm [] (oterm (Can can1) bs1)\n                                     :: bterm [] u1\n                                     :: bs))\n                       (oterm (NCan (NArithOp a0))\n                              (bterm [] (oterm (Can can1) bs4)\n                                     :: bterm [] u2\n                                     :: bs3)).\n                dands.\n\n                { prove_alpha_eq4.\n                  introv j; destruct n0;[|destruct n0]; try omega; cpx.\n                  apply alphaeqbt_nilv2; auto. }\n\n                { prove_alpha_eq4.\n                  introv j; destruct n0;[|destruct n0]; try omega; cpx.\n                  apply alphaeqbt_nilv2; auto. }\n\n                { apply differ3_oterm; simpl; tcsp.\n                  introv j; repndors; cpx. }\n\n            + SSSSCase \"Exc\".\n              allsimpl; ginv.\n              inversion d4 as [|?|? ? ? len2 imp2]; subst; clear d4; cpx.\n              exists (oterm (Exc exc3) bs5) (oterm (Exc exc3) bs2); dands; eauto with slow.\n\n            + SSSSCase \"Mrk\".\n              allsimpl; ginv.\n\n            + SSSSCase \"Abs\".\n              allsimpl.\n              unfold on_success in comp.\n              remember (compute_step_lib lib abs3 bs2) as comp1.\n              symmetry in Heqcomp1; destruct comp1; ginv.\n              apply compute_step_lib_success in Heqcomp1; exrepnd; subst.\n\n              inversion d4 as [|?|? ? ? ni2 len2 imp2]; subst; simphyps; clear d4.\n\n              assert (differ3_bterms b a f g bs2 bs5) as dbs.\n              { unfold differ3_bterms, br_bterms, br_list; auto. }\n\n              pose proof (found_entry_change_bs abs3 oa2 vars rhs lib bs2 correct bs5) as fe2.\n              repeat (autodimp fe2 hyp).\n\n              { apply differ3_bterms_implies_eq_map_num_bvars in dbs; auto. }\n\n              exists (oterm (NCan (NArithOp a0))\n                            (bterm [] (oterm (Can can1) bs4)\n                                   :: bterm [] (mk_instance vars bs5 rhs)\n                                   :: bs3))\n              (oterm (NCan (NArithOp a0))\n                     (bterm [] (oterm (Can can1) bs1)\n                            :: bterm [] (mk_instance vars bs2 rhs)\n                            :: bs)).\n\n             dands; eauto with slow.\n\n             * apply reduces_to_if_step.\n               simpl; unfold on_success.\n               applydup @compute_step_lib_if_found_entry in fe2.\n               rw fe0; auto.\n\n             * pose proof (differ3_mk_instance b a f g rhs vars bs2 bs5) as h.\n               repeat (autodimp h hyp); tcsp; GC.\n               { unfold correct_abs in correct; sp. }\n               { allapply @found_entry_implies_matching_entry.\n                 allunfold @matching_entry; sp. }\n               { allapply @found_entry_implies_matching_entry.\n                 allunfold @matching_entry; sp. }\n               { allunfold @correct_abs; sp. }\n               { allunfold @correct_abs; sp. }\n               unfold differ3_alpha in h.\n               exrepnd.\n\n               exists\n                 (oterm (NCan (NArithOp a0))\n                        (bterm [] (oterm (Can can1) bs1)\n                               :: bterm [] u1\n                               :: bs))\n                 (oterm (NCan (NArithOp a0))\n                        (bterm [] (oterm (Can can1) bs4)\n                               :: bterm [] u2\n                               :: bs3)).\n               dands.\n\n               { prove_alpha_eq4.\n                 introv j; destruct n;[|destruct n]; try omega; cpx.\n                 apply alphaeqbt_nilv2; auto. }\n\n               { prove_alpha_eq4.\n                 introv j; destruct n;[|destruct n]; try omega; cpx.\n                 apply alphaeqbt_nilv2; auto. }\n\n               { apply differ3_oterm; allsimpl; tcsp.\n                 introv j; repndors; cpx. }\n\n          - SSSCase \"NCanTest\".\n            allsimpl.\n            apply compute_step_can_test_success in comp; exrepnd; subst; allsimpl.\n            inversion d as [?|?|? ? ? ni len imp]; subst; allsimpl; clear d.\n            destruct bs2; allsimpl; cpx.\n            destruct bs2; allsimpl; cpx.\n            cpx; allsimpl; GC.\n\n            pose proof (imp (bterm [] (oterm (Can can1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [] arg2nt) b1) as d2.\n            autodimp d2 hyp.\n            pose proof (imp (bterm [] arg3nt) x) as d3.\n            autodimp d3 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df4 dg4 d4]; subst; clear d1.\n            inversion d2 as [? ? ? df5 dg5 d5]; subst; clear d2.\n            inversion d3 as [? ? ? df6 dg6 d6]; subst; clear d3.\n\n            inversion d4 as [?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; clear d4.\n\n            exists (if canonical_form_test_for c can1 then t0 else t3)\n                   (if canonical_form_test_for c can1 then arg2nt else arg3nt).\n            dands; eauto with slow.\n            destruct (canonical_form_test_for c can1); eauto with slow.\n        }\n\n        { SSCase \"NCan\".\n          rw @compute_step_ncan_ncan in comp.\n          remember (compute_step lib (oterm (NCan ncan1) bs1)) as comp1;\n            symmetry in Heqcomp1.\n          destruct comp1; ginv.\n\n          inversion d as [? ? ? ? ? ni1 ni2 d1 aeq1 aeq2|?|? ? ? ni len imp];\n            subst; clear d.\n\n          - (* let's prove that t1 computes to an integer in less than kk steps *)\n            fold_terms; fold (force_int_bound v b t1 (uexc a)) in Heqcomp1.\n            applydup @if_has_value_like_except_k_cbv_primarg in hv; simpl; tcsp; exrepnd.\n            assert (has_value_like_except_k lib a (S j) (force_int_bound v b t1 (uexc a))) as hvf.\n            { rw @has_value_like_except_S; eexists; eauto. }\n            apply if_has_value_like_except_k_force_int_bound in hvf; exrepnd.\n\n            pose proof (compind t1 t0 u j0) as r.\n            repeat (autodimp r hyp); try omega; exrepnd.\n\n            dorn hvf1; exrepnd; subst.\n\n            { apply differ3_alpha_integer in r0; subst.\n              pose proof (agree z) as ag.\n              repeat (autodimp ag hyp); eauto with slow.\n              exrepnd.\n\n              pose proof (compute_step_force_int_bound lib v b a z j0 t1 n) as rz.\n              repeat (autodimp rz hyp).\n\n              exists (@mk_integer o z0) (@mk_integer o z0); dands.\n\n              + pose proof (reduces_to_force_int_bound_app_z\n                              lib v b a z t0 ga) as h.\n                repeat (autodimp h hyp); tcsp.\n                { apply alphaeq_preserves_free_vars in aeq2; rw <- aeq2; auto. }\n                eapply reduces_to_trans;[exact h|].\n\n                pose proof (reduces_to_alpha\n                              lib\n                              (mk_apply g (mk_integer z))\n                              (mk_apply ga (mk_integer z))\n                              (mk_integer z0)) as k.\n                repeat (autodimp k hyp).\n\n                { prove_alpha_eq4.\n                  introv q; destruct n0;[|destruct n0]; cpx.\n                  apply alphaeqbt_nilv2; auto. }\n\n                exrepnd.\n                inversion k0; subst; allsimpl; cpx.\n\n              + pose proof (reduces_to_prinarg\n                              lib NCbv\n                              n\n                              (mk_integer z)\n                              [bterm [v] (mk_apply fa (mk_var v))]) as h.\n                fold_terms.\n                autodimp h hyp.\n                eapply reduces_to_trans;[exact h|].\n                apply (reduces_to_if_split2\n                         _ _ (mk_apply fa (mk_integer z))).\n\n                { simpl; unfold apply_bterm, lsubst; simpl; boolvar;\n                  try (complete (provefalse; sp)).\n                  rw @lsubst_aux_trivial_cl_term; auto; simpl.\n                  rw disjoint_singleton_r; auto.\n                  apply alphaeq_preserves_free_vars in aeq1; rw <- aeq1; auto. }\n\n                pose proof (reduces_to_alpha\n                              lib\n                              (mk_apply f (mk_integer z))\n                              (mk_apply fa (mk_integer z))\n                              (mk_integer z0)) as k.\n                repeat (autodimp k hyp).\n\n                { prove_alpha_eq4.\n                  introv q; destruct n0;[|destruct n0]; cpx.\n                  apply alphaeqbt_nilv2; auto. }\n\n                exrepnd.\n                inversion k0; subst; allsimpl; cpx.\n\n              + apply differ3_implies_differ3_alpha.\n                apply differ3_refl; simpl; tcsp.\n            }\n\n            { apply isexc_implies2 in hvf1; exrepnd; subst.\n              applydup (@differ3_alpha_exc o a0) in r0; eauto with slow;\n              try (complete (simpl; boolvar; tcsp)).\n              apply isnexc_implies in r2; exrepnd; subst.\n\n              pose proof (compute_step_force_int_bound_exc\n                            lib v b a t1 n (oterm (Exc a0) l)) as r.\n              repeat (autodimp r hyp); eauto with slow.\n\n              exists (oterm (Exc a0) l0) (oterm (Exc a0) l); dands; auto.\n\n              - pose proof (reduces_to_prinarg\n                              lib NCbv\n                              (force_int_bound v b t0 (uexc a))\n                              (oterm (Exc a0) l0)\n                              [bterm [v] (mk_apply ga (mk_var v))]) as h.\n                fold_terms.\n                autodimp h hyp.\n                { pose proof (reduces_to_prinarg\n                              lib NCbv\n                              t0\n                              (oterm (Exc a0) l0)\n                              [bterm [v] (less_bound b (mk_var v) (uexc a))]) as h.\n                  fold_terms.\n                  autodimp h hyp.\n                  eapply reduces_to_trans; eauto with slow. }\n                eapply reduces_to_trans; eauto with slow.\n\n              - pose proof (reduces_to_prinarg\n                              lib NCbv\n                              n\n                              (oterm (Exc a0) l)\n                              [bterm [v] (mk_apply fa (mk_var v))]) as h.\n                fold_terms.\n                autodimp h hyp.\n                eapply reduces_to_trans; eauto with slow.\n            }\n\n          - simpl in len, ni.\n            destruct bs2; simpl in len; cpx.\n            simpl in imp.\n            pose proof (imp (bterm [] (oterm (NCan ncan1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            inversion d1 as [? ? ? df2 dg2 d2]; subst; clear d1.\n\n            pose proof (ind (oterm (NCan ncan1) bs1) (oterm (NCan ncan1) bs1) []) as h; clear ind.\n            repeat (autodimp h hyp); tcsp.\n\n            pose proof (h t2 kk n) as k; clear h.\n            repeat (autodimp k hyp); tcsp.\n\n            { apply if_has_value_like_except_k_ncan_primarg in hv; auto.\n              exrepnd.\n              apply (has_value_like_except_k_lt lib a j kk); auto. }\n\n            exrepnd.\n\n            exists (oterm (NCan ncan) (bterm [] t :: bs2))\n                   (oterm (NCan ncan) (bterm [] u' :: bs));\n              dands; eauto with slow.\n\n            + apply reduces_to_prinarg; auto.\n            + apply reduces_to_prinarg; auto.\n\n            + unfold differ3_alpha in k1; exrepnd.\n              exists (oterm (NCan ncan) (bterm [] u1 :: bs))\n                     (oterm (NCan ncan) (bterm [] u2 :: bs2));\n                dands.\n\n              * prove_alpha_eq4.\n                introv j; destruct n0; eauto with slow.\n\n              * prove_alpha_eq4.\n                introv j; destruct n0; eauto with slow.\n\n              * apply differ3_oterm; simpl; auto.\n                introv j; dorn j; cpx.\n        }\n\n        { SSCase \"Exc\".\n          allsimpl.\n          apply compute_step_catch_success in comp.\n\n          inversion d as [?|?|? ? ? ni len imp]; subst; allsimpl; cpx; clear d.\n          destruct bs2; allsimpl; cpx.\n          pose proof (imp (bterm [] (oterm (Exc exc1) bs1)) b0) as d1.\n          autodimp d1 hyp.\n          inversion d1 as [? ? ? df2 dg2 d2]; subst; clear d1.\n          inversion d2 as [?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; cpx; clear d2.\n\n          dorn comp; exrepnd; subst; allsimpl; cpx; allsimpl.\n\n          - pose proof (imp (bterm [v] b0) x) as d1; clear imp.\n            autodimp d1 hyp.\n            inversion d1 as [? ? ? df22 dg22 d2]; subst; clear d1.\n            pose proof (imp1 (bterm [] e) x0) as d1; clear imp1.\n            autodimp d1 hyp.\n            inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n\n            exists (subst t2 v t0) (subst b0 v e); dands; eauto with slow.\n\n            + apply reduces_to_if_step.\n              simpl; boolvar; tcsp.\n\n            + apply differ3_subst; simpl; eauto with slow.\n\n          - exists (oterm (Exc exc1) bs3) (oterm (Exc exc1) bs1); dands; eauto with slow.\n\n            apply reduces_to_if_step; simpl.\n            unfold compute_step_catch; destruct ncan; tcsp.\n            boolvar; subst; tcsp.\n        }\n\n        { SSCase \"Mrk\".\n          allsimpl; ginv.\n          provefalse.\n          unfold has_value_like_except_k in hv; exrepnd.\n          apply reduces_in_atmost_k_steps_primarg_marker in hv1; subst.\n          unfold isvalue_like_except in hv0; repnd.\n          inversion hv1; tcsp.\n        }\n\n        { SSCase \"Abs\".\n          allsimpl.\n          unfold on_success in comp.\n          remember (compute_step_lib lib abs1 bs1) as comp1;\n            symmetry in Heqcomp1.\n          destruct comp1; ginv.\n\n          inversion d as [?|?|? ? ? ni len imp]; subst; clear d.\n          destruct bs2; allsimpl; cpx.\n          pose proof (imp (bterm [] (oterm (Abs abs1) bs1)) b0) as d1.\n          autodimp d1 hyp.\n          inversion d1 as [? ? ? df2 sg2 d2]; subst; clear d1.\n          inversion d2 as [?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; cpx; clear d2.\n\n          apply compute_step_lib_success in Heqcomp1; exrepnd; subst.\n\n          assert (differ3_bterms b a f g bs1 bs3) as dbs.\n          { unfold differ3_bterms, br_bterms, br_list; auto. }\n\n          pose proof (found_entry_change_bs abs1 oa2 vars rhs lib bs1 correct bs3) as fe2.\n          repeat (autodimp fe2 hyp).\n\n          { apply differ3_bterms_implies_eq_map_num_bvars in dbs; auto. }\n\n          exists\n          (oterm (NCan ncan)\n                 (bterm [] (mk_instance vars bs3 rhs)\n                        :: bs2))\n          (oterm (NCan ncan)\n                 (bterm [] (mk_instance vars bs1 rhs)\n                        :: bs)).\n\n          dands; eauto with slow.\n\n          * apply reduces_to_prinarg.\n            apply reduces_to_if_step.\n            simpl; unfold on_success.\n            applydup @compute_step_lib_if_found_entry in fe2.\n            rw fe0; auto.\n\n          * pose proof (differ3_mk_instance b a f g rhs vars bs1 bs3) as h.\n            repeat (autodimp h hyp); tcsp; GC.\n            { unfold correct_abs in correct; sp. }\n            { allapply @found_entry_implies_matching_entry.\n              allunfold @matching_entry; sp. }\n            { allapply @found_entry_implies_matching_entry.\n              allunfold @matching_entry; sp. }\n            { allunfold @correct_abs; sp. }\n            { allunfold @correct_abs; sp. }\n            unfold differ3_alpha in h.\n            exrepnd.\n\n            exists\n              (oterm (NCan ncan) (bterm [] u1 :: bs))\n              (oterm (NCan ncan) (bterm [] u2 :: bs2)).\n            dands.\n\n            { prove_alpha_eq4.\n              introv j; destruct n;[|destruct n]; try omega; cpx.\n              apply alphaeqbt_nilv2; auto. }\n\n            { prove_alpha_eq4.\n              introv j; destruct n;[|destruct n]; try omega; cpx.\n              apply alphaeqbt_nilv2; auto. }\n\n            { apply differ3_oterm; allsimpl; tcsp.\n              introv j; repndors; cpx. }\n        }\n\n    + SCase \"Exc\".\n      allsimpl; ginv.\n\n      inversion d as [?|?|? ? ? ni len imp]; subst; allsimpl; cpx; clear d.\n\n      exists (oterm (Exc exc) bs2) (oterm (Exc exc) bs); dands; eauto with slow.\n\n    + SCase \"Mrk\".\n      allsimpl; ginv.\n\n      inversion d as [?|?|? ? ? ni len imp]; subst; allsimpl; cpx; clear d.\n\n      exists (oterm (Mrk mrk) bs2) (oterm (Mrk mrk) bs); dands; eauto with slow.\n\n    + SCase \"Abs\".\n      allsimpl.\n\n      inversion d as [?|?|? ? ? ni len imp]; subst; clear d.\n\n      apply compute_step_lib_success in comp; exrepnd; subst.\n\n      assert (differ3_bterms b a f g bs bs2) as dbs.\n      { unfold differ3_bterms, br_bterms, br_list; auto. }\n\n      pose proof (found_entry_change_bs abs oa2 vars rhs lib bs correct bs2) as fe2.\n      repeat (autodimp fe2 hyp).\n\n      { apply differ3_bterms_implies_eq_map_num_bvars in dbs; auto. }\n\n      exists (mk_instance vars bs2 rhs) (mk_instance vars bs rhs).\n\n      dands; eauto with slow.\n\n      * apply reduces_to_if_step.\n        simpl; unfold on_success.\n        applydup @compute_step_lib_if_found_entry in fe2.\n        rw fe0; auto.\n\n      * pose proof (differ3_mk_instance b a f g rhs vars bs bs2) as h.\n        repeat (autodimp h hyp); tcsp; GC.\n        { unfold correct_abs in correct; sp. }\n        { allapply @found_entry_implies_matching_entry.\n          allunfold @matching_entry; sp. }\n        { allapply @found_entry_implies_matching_entry.\n          allunfold @matching_entry; sp. }\n        { allunfold @correct_abs; sp. }\n        { allunfold @correct_abs; sp. }\nQed.\n\nLemma isvalue_like_except_implies_isvalue_like {o} :\n  forall a (t : @NTerm o),\n    isvalue_like_except a t\n    -> isvalue_like t.\nProof.\n  introv isv.\n  unfold isvalue_like_except in isv; sp.\nQed.\nHint Resolve isvalue_like_except_implies_isvalue_like : slow.\n\nLemma alpha_eq_preserves_isvalue_like_except {o} :\n  forall a (t1 t2 : @NTerm o),\n    alpha_eq t1 t2\n    -> isvalue_like_except a t1\n    -> isvalue_like_except a t2.\nProof.\n  introv aeq isv.\n  allunfold @isvalue_like_except; repnd.\n  applydup @alpha_eq_preserves_isvalue_like in aeq; auto.\n  dands; auto.\n  intro k.\n  apply isnexc_implies in k; exrepnd; subst.\n  inversion aeq; subst; allsimpl; boolvar; ginv; tcsp.\nQed.\n\nLemma comp_force_int3_aux {o} :\n  forall lib a f g (t1 t2 : @NTerm o) b u,\n    !LIn a (get_utokens f)\n    -> !LIn a (get_utokens g)\n    -> agree_upto_b lib b f g\n    -> differ3 b a f g t1 t2\n    -> isvalue_like_except a u\n    -> reduces_to lib t1 u\n    -> {v : NTerm & reduces_to lib t2 v # differ3_alpha b a f g u v}.\nProof.\n  introv nif nig agree d isv comp.\n  unfold reduces_to in comp; exrepnd.\n  revert dependent u.\n  revert dependent t2.\n  revert dependent t1.\n  induction k as [n ind] using comp_ind_type; introv r isv d.\n  destruct n as [|k]; allsimpl.\n\n  - allrw @reduces_in_atmost_k_steps_0; subst.\n    exists t2; dands; eauto with slow.\n\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n\n    pose proof (comp_force_int_step3 lib b a f g t1 t2 k u0) as h.\n    repeat (autodimp h hyp).\n\n    { unfold has_value_like_except_k.\n      exists u; dands; auto. }\n\n    { introv l' i' r' d'.\n      eapply ind; eauto. }\n\n    exrepnd.\n\n    pose proof (reduces_in_atmost_k_steps_if_reduces_to\n                  lib k u0 u' u) as h'.\n    repeat (autodimp h' hyp); eauto with slow.\n    exrepnd.\n\n    unfold differ3_alpha in h1; exrepnd.\n\n    pose proof (reduces_in_atmost_k_steps_alpha\n                  lib u' u1) as h''.\n    autodimp h'' hyp.\n\n    pose proof (h'' k' u) as h'''; clear h''.\n    autodimp h''' hyp; exrepnd.\n\n    pose proof (ind k') as h.\n    autodimp h hyp;[omega|].\n    pose proof (h u1 u2) as r'; clear h.\n    autodimp r' hyp.\n\n    pose proof (r' t2') as h; clear r'; repeat (autodimp h hyp).\n\n    { eapply alpha_eq_preserves_isvalue_like_except in h'''0; eauto. }\n\n    exrepnd.\n\n    pose proof (reduces_to_steps_alpha lib u2 t v) as r'.\n    repeat (autodimp r' hyp); eauto with slow.\n    exrepnd.\n    exists u3; dands; eauto with slow.\n\n    { eapply reduces_to_trans; eauto. }\n\n    { unfold differ3_alpha in h5; exrepnd.\n      exists u4 u5; dands; eauto with slow. }\nQed.\n\nLemma comp_force_int3 {o} :\n  forall lib a f g (t1 t2 : @NTerm o) b z,\n    !LIn a (get_utokens f)\n    -> !LIn a (get_utokens g)\n    -> agree_upto_b lib b f g\n    -> differ3 b a f g t1 t2\n    -> reduces_to lib t1 (mk_integer z)\n    -> reduces_to lib t2 (mk_integer z).\nProof.\n  introv nif nig agree d comp.\n  pose proof (comp_force_int3_aux lib a f g t1 t2 b (mk_integer z)) as h.\n  repeat (autodimp h hyp); eauto with slow.\n\n  exrepnd.\n  apply differ3_alpha_integer in h0; subst; auto.\nQed.\n\nLemma differ_app_F3 {o} :\n  forall b a (F : @NTerm o) x f g,\n    !LIn a (get_utokens F)\n    -> !LIn x (free_vars f)\n    -> !LIn x (free_vars g)\n    -> disjoint (bound_vars F) (free_vars f)\n    -> disjoint (bound_vars F) (free_vars g)\n    -> differ3\n         b a\n         f g\n         (force_int_bound_F x b F f (uexc a))\n         (force_int_bound_F x b F g (uexc a)).\nProof.\n  introv ni1 ni2 ni3 df dg.\n  constructor; simpl; tcsp.\n  introv i; dorn i;[|dorn i]; cpx.\n  - constructor; eauto with slow.\n  - constructor; auto; constructor; simpl; tcsp.\n    introv i; dorn i; cpx.\n    constructor; allrw disjoint_singleton_l; auto; constructor; simpl; auto.\nQed.\n\nLemma comp_force_int_app_F3 {o} :\n  forall lib a (F f g : @NTerm o) x z b,\n    !LIn a (get_utokens F)\n    -> !LIn a (get_utokens f)\n    -> !LIn a (get_utokens g)\n    -> !LIn x (free_vars f)\n    -> !LIn x (free_vars g)\n    -> disjoint (bound_vars F) (free_vars f)\n    -> disjoint (bound_vars F) (free_vars g)\n    -> agree_upto_b lib b f g\n    -> reduces_to\n         lib\n         (force_int_bound_F x b F f (uexc a))\n         (mk_integer z)\n    -> reduces_to\n         lib\n         (force_int_bound_F x b F g (uexc a))\n         (mk_integer z).\nProof.\n  introv ni1 ni2 ni3 ni4 ni5 df dg agree r.\n\n  apply (comp_force_int3 _ a f g (force_int_bound_F x b F f (uexc a)) _ b); auto.\n\n  apply differ_app_F3; auto; allrw; 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/continuity3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.2988502690444114}}
{"text": "(* ---------------------------------------------------------------------\n\n   This file is part of a repository containing the definitions and \n   proof scripts related to the formalization of the Chomsky Normal\n   Form for context-free grammars in Coq. Specifically, the following \n   results were obtained:\n   \n   (i) context-free grammar simplification \n   (i) context-free grammar Chomsky normalization and \n   \n   More information can be found in the paper \"Formalization of \n   the Chomsky Normal Form for Context-Free Grammars\", submitted \n   to SBMF 2019.\n   \n   The file README.md describes the contents of each file and \n   provides instructions on how to compile them.\n   \n   Marcus Vinícius Midena Ramos\n   mvmramos@gmail.com\n\n   --------------------------------------------------------------------- *)\n\n(* --------------------------------------------------------------------- *)\n(* SIMPLIFICATION                                                        *)\n(* --------------------------------------------------------------------- *)\n\nRequire Import List.\nRequire Import Ring.\nRequire Import Omega.\n\nRequire Import misc_arith.\nRequire Import misc_list.\nRequire Import cfg.\nRequire Import useless.\nRequire Import inaccessible.\nRequire Import unitrules.\nRequire Import emptyrules.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport ListNotations.\nOpen Scope list_scope.\n\n(* --------------------------------------------------------------------- *)\n(* SIMPLIFICATION - INITIAL THEOREMS                                     *)\n(* --------------------------------------------------------------------- *)\n\nSection Simplification.\n\nVariables terminal non_terminal: Type.\nNotation sf := (list (non_terminal + terminal)).\nNotation sentence := (list terminal).\nNotation term_lift:= ((terminal_lift non_terminal) terminal).\nNotation term_lift':= ((terminal_lift non_terminal') terminal).\n\nTheorem no_useless_symbols:\nforall g: cfg terminal non_terminal,\nnon_empty g ->\nexists g': cfg terminal non_terminal,\ng_equiv g' g /\\\nhas_no_useless_symbols g'.\nProof.\nintros g.\nexists (g_use g).\napply g_use_correct.\nexact H.\nQed.\n\nTheorem no_inaccessible_symbols:\nforall g: cfg terminal non_terminal,\nexists g': cfg terminal non_terminal,\ng_equiv g' g /\\\nhas_no_inaccessible_symbols g'.\nProof.\nintros g.\nexists (g_acc g).\napply g_acc_correct.\nQed.\n\nTheorem no_unit_rules:\nforall g: cfg terminal non_terminal,\nexists g': cfg terminal non_terminal,\ng_equiv g' g /\\\nhas_no_unit_rules g'.\nProof.\nintros g.\nexists (g_unit g).\napply g_unit_correct.\nQed.\n\nTheorem no_empty_rules:\nforall g: cfg non_terminal terminal,\nexists g': cfg (non_terminal' non_terminal) terminal,\ng_equiv g' g /\\\n(generates_empty g -> has_one_empty_rule g') /\\ \n(~ generates_empty g -> has_no_empty_rules g') /\\\nstart_symbol_not_in_rhs g'.\nProof.\nintros g.\nexists (g_emp' g).\napply g_emp'_correct.\nQed.\n\n(* --------------------------------------------------------------------- *)\n(* SIMPLIFICATION - INACCESSIBLE AND USELESS SYMBOLS                     *)\n(* --------------------------------------------------------------------- *)\n\nLemma g_acc_preserves_use:\nforall g: cfg _ _,\nforall s: non_terminal + terminal,\nuseful g s -> \naccessible g s ->\nuseful (g_acc g) s.\nProof.\nintros g s H1 H2.\ndestruct s.\n- unfold useful in H1.\n  unfold useful.\n  destruct H1 as [s H3].\n  exists s.\n  apply derives_sflist in H3.\n  destruct H3 as [l [H4 [H5 H6]]].\n  assert (H7: length l >= 2 \\/ length l < 2) by omega.\n  destruct H7 as [H7 | H7].\n  + assert (H7':=H7). \n    apply sflist_rules with (g:=g) in H7.\n    destruct H7 as [H7 _].\n    specialize (H7 H4).\n    apply derives_sflist.\n    exists l.\n    split.\n    * {\n      apply sflist_rules.\n      - exact H7'.\n      - intros i H8.\n        specialize (H7 i H8).\n        destruct H7 as [left [right [s0 [s' [H10 [H11 H12]]]]]].\n        exists left, right, s0, s'.\n        split.\n        + exact H10.\n        + split.\n          * exact H11.\n          * simpl.\n            {\n            apply Lift_acc.\n            - exact H12.\n            - unfold accessible in H2.\n              destruct H2 as [s2 [s3 H13]].\n              assert (H20: derives g [inl n] (s0 ++ inl left :: s')).\n                {\n                apply derives_sflist.\n                rewrite <- (firstn_skipn (S i) l) in H4.\n                apply sflist_app_r in H4.\n                exists (firstn (S i) l).\n                split. \n                - exact H4.\n                - split.\n                  + rewrite hd_first.\n                    * exact H5.\n                    * omega. \n                  + rewrite <- H10.\n                    apply last_first_nth.\n                    omega.\n                }\n              assert (H21: derives g [inl (start_symbol g)] (s2++s0++inl left::s'++s3)).\n                {\n                replace (s2 ++ inl n :: s3) with (s2 ++ [inl n] ++ s3) in H13.\n                - apply derives_subs with (g:=g) (s1:=[inl (start_symbol g)]) (s2:=s2) (s3:=[inl n]) (s3':=(s0 ++ inl left :: s')) (s4:=s3) in H13.\n                  + rewrite <- app_assoc in H13. \n                    exact H13.\n                  + exact H20.\n                - simpl. \n                  reflexivity.\n                }\n              exists (s2++s0), (s'++s3).\n              rewrite <- app_assoc.\n              exact H21.\n            }\n      }\n    * {\n      split.\n      - exact H5.\n      - exact H6.\n      }\n  + destruct l as [| s0 l].\n    * simpl in H5.\n      inversion H5.\n    * {\n      replace (s0::l) with ([s0]++l) in H7.\n      - rewrite app_length in H7.\n        simpl in H7.\n        assert (H8: length l = 0) by omega.\n        apply length_zero in H8.\n        subst. \n        simpl in H5.\n        rewrite H5 in H6.\n        simpl in H6.\n        destruct s.\n        + simpl in H6.\n          inversion H6.\n        + replace (t::s) with ([t]++s) in H6. \n          * rewrite map_app in H6.\n            inversion H6.\n          * simpl. \n            reflexivity.\n      - simpl. \n        reflexivity.\n      }\n- simpl. \n  auto.\nQed.\n\nLemma acc_appears:\nforall g: cfg _ terminal,\nforall n: non_terminal,\nuseful g (inl (start_symbol g)) -> \naccessible g (inl n) -> \nappears g (inl n).\nProof.\nintros g n H10 H.\nunfold accessible in H.\ndestruct H as [s1 [s2 H2]].\napply exists_rule' in H2.\ndestruct H2 as [H2 | H2].\n- destruct H2 as [H2 [_ _]].\n  inversion H2.\n  apply (useful_exists).\n  exact H10.\n- destruct H2 as [left [right [H3 H4]]].\n  exists left, right.\n  split.\n  + exact H3.\n  + right.\n    exact H4.\nQed.\n\nLemma in_g_use_acc_is_use:\nforall g: cfg non_terminal terminal,\nforall n: non_terminal,\nuseful g (inl (start_symbol g)) ->\naccessible (g_use g) (inl n) ->\nuseful (g_use g) (inl n).\nProof.\nintros g n H99 H.\nunfold accessible in H.\nunfold useful.\ndestruct H as [s1 [s2 H2]].\napply exists_rule' in H2.\ndestruct H2 as [H2 | H2]. \n- apply useful_g_use.\n  simpl in H2.\n  destruct H2 as [H2 [_ _]].\n  rewrite H2.  \n  apply acc_appears.\n  + simpl. \n    apply useful_g_g_use. \n    exact H99.\n  + unfold accessible.\n    exists [], [].\n    constructor.\n- destruct H2 as [left [right [H3 H4]]].\n  simpl in H3.\n  inversion H3.\n  subst.\n  specialize (H1 (inl n) H4).\n  unfold useful in H1.\n  destruct H1 as [s0 H7].\n  exists s0.\n  apply derives_sflist in H7.\n  destruct H7 as [l [H10 [H11 H12]]].\n  apply derives_sflist.\n  exists l.\n  split.\n  + assert (H6: length l >= 2 \\/ length l < 2) by omega.\n    destruct H6 as [H6 | H6].\n    * assert (H6':=H6).\n      apply sflist_rules with (g:=g) in H6.\n      destruct H6 as [H6 _].\n      specialize (H6 H10).\n      {\n      apply sflist_rules.\n      - exact H6'.\n      - intros i H7.\n        specialize (H6 i H7).\n        destruct H6 as [left0 [right0 [s3 [s' [H20 [H21 H22]]]]]].\n        exists left0, right0, s3, s'.\n        split.\n        + exact H20.\n        + split.\n          * exact H21.\n          * simpl.\n            {\n            apply Lift_use.\n            - exact H22.\n            - assert (H30: derives g (s3 ++ inl left0 :: s') (map term_lift s0)).\n                {\n                apply derives_sflist.\n                rewrite <- (firstn_skipn i l) in H10.\n                apply sflist_app_l in H10.\n                exists (skipn i l).\n                split.\n                + exact H10.\n                + split.\n                  * rewrite hd_skip.\n                    exact H20.\n                  * {\n                    rewrite last_skip.\n                    - exact H12.\n                    - omega.\n                    }\n                }\n              apply derives_split in H30.\n              destruct H30 as [s1' [s2' [H31 [H32 H33]]]].\n              symmetry in H31.\n              apply map_expand in H31.\n              destruct H31 as [_ [s2'0 [_ [_ H34]]]].\n              rewrite <- H34 in H33.\n              replace (inl left0 :: s') with ([inl left0] ++ s') in H33.\n              + apply derives_split in H33.\n                destruct H33 as [s1'0 [s2'1 [H35 [H36 _]]]].\n                symmetry in H35.\n                apply map_expand in H35.\n                destruct H35 as [s1'1 [_ [_ [H37 _]]]].\n                rewrite <- H37 in H36.\n                unfold useful.\n                exists s1'1.\n                exact H36.\n              + simpl.\n                reflexivity.\n            - assert (H30: derives g (s3 ++ right0 ++ s') (map term_lift s0)).\n                {\n                apply derives_sflist.\n                rewrite <- (firstn_skipn (S i) l) in H10.\n                apply sflist_app_l in H10.\n                exists (skipn (S i) l).\n                split.\n                + exact H10.\n                + split.\n                  * rewrite hd_skip.\n                    exact H21.\n                  * {\n                    rewrite last_skip.\n                    - exact H12.\n                    - omega.\n                    }\n                } \n              apply derives_split in H30.\n              destruct H30 as [s1' [s2' [H31 [H32 H33]]]].\n              symmetry in H31.\n              apply map_expand in H31.\n              destruct H31 as [_ [s2'0 [_ [_ H34]]]].\n              rewrite <- H34 in H33.\n              apply derives_split in H33.\n              destruct H33 as [s1'0 [s2'1 [H35 [H36 _]]]].\n              symmetry in H35.\n              apply map_expand in H35.\n              destruct H35 as [s1'1 [_ [_ [H37 _]]]].\n              rewrite <- H37 in H36.\n              intros s4 H40.\n              destruct s4. \n              + unfold useful.\n                apply in_split in H40.\n                destruct H40 as [l1 [l2 H41]].\n                rewrite H41 in H36.\n                apply derives_nt_sentence in H36.\n                destruct H36 as [s'0 H42].\n                exists s'0.\n                exact H42.\n              + simpl.\n                auto. \n            }\n      }\n    * apply lt2_sflist.\n      exact H6.\n  + split.\n    * exact H11.\n    * exact H12.\nQed. \n\nEnd Simplification.\n\nSection Simplification_2.\n\nVariables non_terminal terminal: Type.\n\nLemma no_useless_no_inaccessible_symbols_v1:\nforall g: cfg non_terminal terminal,\nnon_empty g ->\ng_equiv (g_acc (g_use g)) g /\\\nhas_no_inaccessible_symbols (g_acc (g_use g)) /\\\nhas_no_useless_symbols (g_acc (g_use g)).\nProof.\nintros g H'.\nsplit.\n- assert (H1: g_equiv (g_use g) g).\n    {\n    apply g_equiv_use.\n    exact H'.\n    }\n  assert (H2: g_equiv (g_acc (g_use g)) (g_use g)).\n    {\n    apply g_equiv_acc.\n    }\n  apply g_equiv_trans with (g2:= g_use g).\n  split.\n  + exact H2.\n  + exact H1.\n- split.\n  + intros s H.\n    destruct s. \n    * inversion H.\n      destruct H0 as [right [H1 H2]].\n      {\n      destruct H2 as [H2 | H2].\n      - subst.\n        simpl in H1.\n        inversion H1.\n        subst.\n        apply accessible_g_g_acc.\n        exact H2.\n      - simpl in H1.\n        inversion H1.\n        subst.\n        apply accessible_g_g_acc.\n        apply acc_step with (s:=inl n) (right:=right) in H3.\n        + exact H3.\n        + exact H0.\n        + exact H2.\n      }\n    * inversion H.\n      destruct H0 as [right [H1 H2]].\n      inversion H1.\n      subst.\n      apply accessible_g_g_acc.\n      simpl in H1.\n      inversion H1.\n      subst.\n      {\n      apply acc_step with (s:=inr t) (right:=right) in H3.\n      - exact H3.\n      - exact H0.\n      - exact H2.\n      }\n  + intros s H.\n    inversion H.\n    destruct H0 as [right [H1 H2]].\n    destruct H2 as [H2 | H2].\n    * simpl in H1.\n      inversion H1.\n      subst.\n      assert (H4:= H3).\n      {\n      apply in_g_use_acc_is_use in H3.\n      - apply g_acc_preserves_use.\n        + exact H3.\n        + exact H4.\n      - exact H'.\n      }\n    * inversion H1. \n      subst.\n      {\n      apply acc_step with (s:=inl s) (right:=right) in H3.\n      - assert (H4:=H3). \n        apply in_g_use_acc_is_use in H3.\n        + apply g_acc_preserves_use.\n          * exact H3.\n          * exact H4.\n        + exact H'.\n      - exact H0.\n      - exact H2.   \n      }\nQed.\n\nLemma no_useless_no_inaccessible_symbols_v2:\nforall g: cfg non_terminal terminal,\nnon_empty g ->\nexists g': cfg non_terminal terminal,\ng_equiv g' g /\\\nhas_no_inaccessible_symbols g' /\\\nhas_no_useless_symbols g'.\nProof.\nintros g H'.\nexists (g_acc (g_use g)).\napply no_useless_no_inaccessible_symbols_v1.\nexact H'.\nQed.\n\nEnd Simplification_2.\n\n(* --------------------------------------------------------------------- *)\n(* SIMPLIFICATION - EMPTY AND UNIT RULES                                 *)\n(* --------------------------------------------------------------------- *)\n\nSection Simplification_3.\n\nVariables non_terminal terminal: Type.\n\nNotation sentence:= (list terminal).\nNotation term_lift:= ((terminal_lift non_terminal) terminal).\n\nLemma New_ss_not_in_unit_v1:\nforall g: cfg non_terminal terminal,\nforall n: non_terminal' non_terminal,\n~ unit (g_emp' g) n (start_symbol (g_emp' g)).\nProof.\nintros g n H.\nremember (start_symbol (g_emp' g)) as w.\ninduction H.\n- rewrite Heqw in H. \n  apply New_ss_not_in_right_g_emp'_v2 in H.\n  simpl in H.\n  unfold New_ss_not_in_sf in H.\n  simpl in H.\n  apply H.\n  left.\n  reflexivity.\n- apply IHunit2.\n  exact Heqw.\nQed.\n\nLemma New_ss_not_in_unit_v2:\nforall g: cfg non_terminal terminal,\nforall n1 n2: non_terminal' non_terminal,\nunit (g_emp' g) n1 n2 -> n2 <> (start_symbol (g_emp' g)).\nProof.\nintros g n1 n2 H1.\nassert (H2: n2 = start_symbol (g_emp' g) \\/ n2 <> start_symbol (g_emp' g)).\n  {\n  destruct n2. \n  - right. \n    simpl. \n    discriminate. \n  - left. \n    simpl. \n    reflexivity.\n  }\ndestruct H2 as [H2 | H2].\n- rewrite H2 in H1.\n  apply New_ss_not_in_unit_v1 in H1.\n  contradiction.\n- exact H2.\nQed.\n\nLemma g_unit_preserves_one_empty_rule:\nforall g: cfg (non_terminal' non_terminal) terminal,\n(forall n1 n2: non_terminal' non_terminal, unit g n1 n2 -> n2 <> (start_symbol g)) ->\nhas_one_empty_rule g ->\nhas_one_empty_rule (g_unit g).\nProof.\nintros g H0 H1.\nunfold has_one_empty_rule.\nintros left right H2.\ninversion H2.\n- subst.\n  specialize (H1 left right H3).\n  destruct H1 as [H1 | H1].\n  + left.\n    simpl.\n    exact H1.\n  + right.\n    exact H1.\n- clear H2. \n  subst.\n  simpl.\n  specialize (H1 b right H3).\n  destruct H1 as [H1 | H1].\n  + specialize (H0 left b H).\n    destruct H1 as [H1 _].\n    contradiction.\n  + right.\n    exact H1.\nQed.\n\nLemma g_unit_preserves_no_empty_rules:\nforall g: cfg non_terminal terminal,\nhas_no_empty_rules g ->\nhas_no_empty_rules (g_unit g).\nProof.\nunfold has_no_empty_rules.\nintros g H1.\nintros left right H2.\ninversion H2.\n- subst. \n  apply H1 with (left:= left).\n  exact H0.\n- subst.\n  apply H1 with (left:= b).\n  exact H0.\nQed.\n\nEnd Simplification_3.\n\nSection Simplification_4.\n\nVariables non_terminal terminal: Type.\n\nNotation sentence:= (list terminal).\n\nLemma no_empty_no_unit_rules_v1:\nforall g: cfg non_terminal terminal,\ng_equiv (g_unit (g_emp' g)) g /\\\n(generates_empty g -> has_one_empty_rule (g_unit (g_emp' g))) /\\ \n(~ generates_empty g -> has_no_empty_rules (g_unit (g_emp' g))) /\\\nhas_no_unit_rules (g_unit (g_emp' g)).\nProof.\nintros g.\nsplit.\n- assert (H1: g_equiv (g_unit (g_emp' g)) (g_emp' g)).\n    {\n    apply g_unit_correct.\n    }\n  assert (H2: g_equiv (g_emp' g) g).\n    {\n    apply g_emp'_correct.\n    }\n  apply g_equiv_trans with (g2:= (g_emp' g)).\n  split.\n  + exact H1.\n  + exact H2.\n- split.\n  + intros H1.\n    assert (H2: has_one_empty_rule (g_emp' g)).\n      {\n      apply g_emp'_has_one_empty_rule.\n      exact H1.\n      }\n    apply g_unit_preserves_one_empty_rule.\n    * apply New_ss_not_in_unit_v2.\n    * exact H2.\n  + split.\n    * intros H1.\n      assert (H2: has_no_empty_rules (g_emp' g)).\n        {\n        apply g_emp'_has_no_empty_rules.\n        exact H1.\n        }\n      apply g_unit_preserves_no_empty_rules.\n      exact H2.\n    * apply g_unit_has_no_unit_rules.\nQed.\n\nLemma no_empty_no_unit_rules_v2:\nforall g: cfg non_terminal terminal,\ng_equiv_without_empty (g_unit (g_emp g)) g /\\\nhas_no_empty_rules (g_unit (g_emp g)) /\\\nhas_no_unit_rules (g_unit (g_emp g)).\nProof.\nintros g.\nsplit.\n- assert (H1: g_equiv (g_unit (g_emp g)) (g_emp g)).\n    {\n    apply g_unit_correct.\n    }\n  assert (H2: g_equiv_without_empty (g_emp g) g).\n    {\n    apply g_emp_correct.\n    }\n  apply g_equiv_without_empty_trans with (g2:= (g_emp g)).\n  split.\n  + apply remove_empty in H1. \n    exact H1.\n  + exact H2.\n- split.\n  + assert (H2: has_no_empty_rules (g_emp g)).\n      {\n      apply g_emp_has_no_empty_rules.\n      }\n    apply g_unit_preserves_no_empty_rules.\n    exact H2.\n  + apply g_unit_has_no_unit_rules.\nQed.\n\nLemma no_empty_no_unit_rules_v3:\nforall g: cfg non_terminal terminal,\nexists g': cfg  (non_terminal' non_terminal) terminal,\ng_equiv g' g /\\\n(generates_empty g -> has_one_empty_rule g') /\\ \n(~ generates_empty g -> has_no_empty_rules g') /\\\nhas_no_unit_rules g'.\nProof.\nintros g.\nexists (g_unit (g_emp' g)).\napply no_empty_no_unit_rules_v1.\nQed.\n\nEnd Simplification_4.\n\n(* --------------------------------------------------------------------- *)\n(* SIMPLIFICATION - FINAL THEOREM                                        *)\n(* --------------------------------------------------------------------- *)\n\nSection Simplification_5.\n\nVariables non_terminal terminal: Type.\n\nNotation sentence:= (list terminal).\n\nLemma g_acc_g_use_preserves_rules:\nforall g: cfg non_terminal terminal,\nforall left: _,\nforall right: _,\nrules (g_acc (g_use g)) left right -> rules g left right.\nProof.\nintros g left right H.\ninversion H.\nclear H.\nsubst.\ninversion H0.\nclear H0.\nsubst.\nexact H.\nQed.\n\nLemma g_acc_g_use_preserves_empty_rule:\nforall g: cfg (non_terminal' non_terminal) terminal,\nrules g (start_symbol g) [] ->\nrules (g_acc (g_use g)) (start_symbol (g_acc (g_use g))) [].\nProof.\nintros g H.\nsimpl. \napply Lift_acc.\n- apply Lift_use.\n  + exact H.\n  + unfold useful.\n    exists [].\n    apply derives_start.\n    simpl. \n    exact H.\n  + intros s H1.\n    simpl in H1.\n    contradiction.\n- exists [], [].\n  simpl.\n  apply derives_refl. \nQed.\n\nLemma g_emp_preserves_non_empty:\nforall g: cfg non_terminal terminal,\n(exists s: sentence, produces g s /\\ s <> []) ->\nnon_empty (g_emp g).\nProof.\nintros g H0.\nunfold non_empty.\nunfold produces in H0.\nunfold generates in H0.\nunfold useful.\ndestruct H0 as [s [H0 H1]].\nassert (H3: g_equiv_without_empty (g_emp g) g).\n  {\n  apply g_emp_correct.\n  }\nunfold g_equiv_without_empty in H3.\nspecialize (H3 s H1).\ndestruct H3 as [_ H3].\nspecialize (H3 H0).\nexists s.\nexact H3.\nQed.\n\nLemma g_emp'_preserves_non_empty:\nforall g: cfg non_terminal terminal,\nnon_empty g ->\nnon_empty (g_emp' g).\nProof.\nunfold non_empty.\nintros g H0.\nunfold useful in H0.\ndestruct H0 as [s H0].\nassert (H1: g_equiv (g_emp' g) g).\n  {\n  apply g_emp'_correct.\n  }\nunfold g_equiv in H1.\nspecialize (H1 s).\ndestruct H1 as [_ H1].\nspecialize (H1 H0).\nunfold useful. \nexists s.\nexact H1.\nQed.\n\nLemma g_unit_preserves_non_empty:\nforall g: cfg non_terminal terminal,\nnon_empty g ->\nnon_empty (g_unit g).\nProof.\nunfold non_empty.\nintros g H0.\nsimpl.\nunfold useful in H0. \ndestruct H0 as [s H0].\nexists s.\nassert (H2: g_equiv (g_unit g) g).\n  {\n  apply g_unit_correct.\n  }\nunfold g_equiv in H2.\nspecialize (H2 s).\ndestruct H2 as [_ H2].\nunfold produces in H2.\nunfold generates in H2.\napply H2.\nexact H0.\nQed.\n\nLemma g_unit_preserves_start:\nforall g: cfg (non_terminal' non_terminal) terminal,\nstart_symbol_not_in_rhs g ->\nstart_symbol_not_in_rhs (g_unit g).\nProof.\nintros g H1 left right H2 H3.\nunfold start_symbol_not_in_rhs in H1.\ninversion H2.\n- subst.\n  specialize (H1 left right H0).\n  apply H1.\n  simpl in H3.\n  exact H3.\n- specialize (H1 b right H0).\n  apply H1.\n  simpl in H3.\n  exact H3.\nQed.\n\nLemma g_use_preserves_start:\nforall g: cfg (non_terminal' non_terminal) terminal,\nstart_symbol_not_in_rhs g ->\nstart_symbol_not_in_rhs (g_use g).\nProof.\nintros g H1 left right H2 H3.\nunfold start_symbol_not_in_rhs in H1.\ninversion H2.\nsubst.\nspecialize (H1 left right H).\napply H1.\nsimpl in H3.\nexact H3.\nQed.\n\nLemma g_acc_preserves_start:\nforall g: cfg (non_terminal' non_terminal) terminal,\nstart_symbol_not_in_rhs g ->\nstart_symbol_not_in_rhs (g_acc g).\nProof.\nintros g H1 left right H2 H3.\nunfold start_symbol_not_in_rhs in H1.\ninversion H2.\nsubst.\nspecialize (H1 left right H).\napply H1.\nsimpl in H3.\nexact H3.\nQed.\n\nEnd Simplification_5.\n\nSection Simplification_6.\n\nVariables non_terminal terminal: Type.\n\nNotation sentence:= (list terminal).\n\nTheorem g_simpl_exists_v1:\nforall g: cfg non_terminal terminal,\n non_empty g ->\n exists g': cfg (non_terminal' non_terminal) terminal,\n g_equiv g' g /\\\n has_no_inaccessible_symbols g' /\\\n has_no_useless_symbols g' /\\\n(produces_empty g -> has_one_empty_rule g') /\\ \n(~ produces_empty g -> has_no_empty_rules g') /\\\n has_no_unit_rules g' /\\\n start_symbol_not_in_rhs g'.\nProof.\nintros g H.\nexists (g_acc (g_use (g_unit (g_emp' g)))).\nsplit.\n- assert (H3: g_equiv (g_acc (g_use (g_unit (g_emp' g)))) (g_unit (g_emp' g))).\n    {\n    apply no_useless_no_inaccessible_symbols_v1.\n    apply g_emp'_preserves_non_empty in H.\n    apply g_unit_preserves_non_empty in H.\n    exact H.\n    }\n  apply g_equiv_trans with (g2:= (g_unit (g_emp' g))).\n  split.\n  + exact H3.\n  + apply no_empty_no_unit_rules_v1.\n- split.\n  + apply g_acc_has_no_inaccessible_symbols.\n  + split. \n    * apply no_useless_no_inaccessible_symbols_v1.\n      {\n      apply g_emp'_preserves_non_empty in H.\n      apply g_unit_preserves_non_empty in H.\n      exact H.\n      }\n    * {\n      split. \n      - intros H1'.\n        assert (H2': has_one_empty_rule (g_unit (g_emp' g))).\n          {\n          apply no_empty_no_unit_rules_v1. \n          exact H1'.\n          }    \n        unfold has_one_empty_rule.\n        remember (g_unit (g_emp' g)) as g'.\n        intros left right HH.\n        simpl in HH.\n        inversion HH.\n        clear HH.\n        subst.\n        simpl.\n        simpl in H0.\n        inversion H0.\n        clear H0.\n        subst.\n        specialize (H2' left right H2).\n        destruct H2' as [H2' | H2'].\n        + simpl in H2'.\n          left.\n          exact H2'.\n        + right.\n          exact H2'.\n      - split.\n        + intros H1'.\n          unfold has_no_empty_rules.\n          intros left right H2'.\n          apply g_acc_g_use_preserves_rules in H2'.\n          apply g_emp'_has_no_empty_rules in H1'.\n          apply g_unit_preserves_no_empty_rules in H1'.\n          unfold has_no_empty_rules in H1'.\n          specialize (H1' left right H2').\n          exact H1'.\n        + split.\n          * unfold has_no_unit_rules.\n            intros left n right H1'.\n            apply g_acc_g_use_preserves_rules in H1'.\n            {\n            inversion H1'.\n            clear H1'.\n            - subst. \n              specialize (H0 n).\n              exact H0.\n            - subst.\n              specialize (H2 n).\n              exact H2.\n            }\n          * assert (H1: start_symbol_not_in_rhs (g_emp' g)).\n              {\n              apply start_symbol_not_in_rhs_g_emp'.\n              }\n            apply g_unit_preserves_start in H1.\n            apply g_use_preserves_start in H1.\n            apply g_acc_preserves_start in H1.\n            exact H1. \n      }\nQed.\n\nTheorem g_simpl_exists_v2:\nforall g: cfg non_terminal terminal,\n(exists s: sentence, produces g s /\\ s <> [] ) ->\n exists g': cfg (non_terminal' non_terminal) terminal,\n g_equiv_without_empty g' g /\\\n has_no_inaccessible_symbols g' /\\\n has_no_useless_symbols g' /\\\n has_no_empty_rules g' /\\\n has_no_unit_rules g' /\\\n start_symbol_not_in_rhs g'.\nProof.\nintros g H.\nexists (g_acc (g_use (g_unit (g_emp g)))).\nsplit.\n- assert (H3: g_equiv (g_acc (g_use (g_unit (g_emp g)))) (g_unit (g_emp g))).\n    {\n    apply no_useless_no_inaccessible_symbols_v1.\n    apply g_emp_preserves_non_empty in H.\n    apply g_unit_preserves_non_empty in H.\n    exact H.\n    }\n  apply g_equiv_without_empty_trans with (g2:= (g_unit (g_emp g))).\n  split.\n  + apply remove_empty in H3. \n    exact H3.\n  + apply no_empty_no_unit_rules_v2.\n- split.\n  + apply g_acc_has_no_inaccessible_symbols.\n  + split. \n    * apply no_useless_no_inaccessible_symbols_v1.\n      {\n      apply g_emp_preserves_non_empty in H.\n      apply g_unit_preserves_non_empty in H.\n      exact H.\n      }\n    * {\n      split. \n      - unfold has_no_empty_rules.\n        intros left right H2'.\n        apply g_acc_g_use_preserves_rules in H2'.\n        apply g_unit_preserves_no_empty_rules in H2'.\n        exact H2'.\n        apply g_emp_has_no_empty_rules.\n      - split.\n        + unfold has_no_unit_rules.\n          intros left n right H1'.\n          apply g_acc_g_use_preserves_rules in H1'.\n          inversion H1'.\n          clear H1'.\n          * subst. \n            specialize (H0 n).\n            exact H0.\n          * subst.\n            specialize (H2 n).\n            exact H2.\n        + assert (H1: start_symbol_not_in_rhs (g_emp g)).\n            {\n            apply start_symbol_not_in_rhs_g_emp.\n            }\n          apply g_unit_preserves_start in H1.\n          apply g_use_preserves_start in H1.\n          apply g_acc_preserves_start in H1.\n          exact H1. \n      }\nQed.\n\nEnd Simplification_6.\n", "meta": {"author": "mvmramos", "repo": "chomsky", "sha": "5601fdd3d6845c8bb1a750469747b6e0bc73b679", "save_path": "github-repos/coq/mvmramos-chomsky", "path": "github-repos/coq/mvmramos-chomsky/chomsky-5601fdd3d6845c8bb1a750469747b6e0bc73b679/simplification.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.2988502687685393}}
{"text": "Require Import LibTactics.\nRequire Import Metalib.Metatheory.\nRequire Import Logic. Import Decidable.\nRequire Import\n        syntax_ott\n        syntaxb_ott\n        rules_inf\n        Typing\n        Infrastructure.\n\nRequire Import Strings.String.\n\nLemma BA_AB: forall B A,\n  sim A B -> sim B A.\nProof.\n  introv H.\n  induction* H.\nQed.\n\n\nLemma flike_not_ground: forall v,\n value v ->\n FLike (principal_type v) ->\n not(Ground (principal_type v)).\nProof.\n  introv val fl.\n  inductions val; simpl in *; try solve[inverts* fl;\n  inverts* H0;inverts* H2];\n  try solve[unfold not; intros nt; inverts* nt].\n  inverts* fl. inverts H1.\n  unfold not; intros nt; inverts* nt.  \nQed.\n\n\n\nLemma TypedReduce_unique: forall v r1 r2 (A: typ) B p b,\n    value v -> Typing nil v Chk B -> TypedReduce v p b A r1 -> TypedReduce v p b A r2 -> r1 = r2.\nProof.\n  introv Val H R1 R2. \n  gen r2 B.\n  lets R1': R1.\n  inductions R1; introv R2 typ;\n    try solve [inverts* R2].\n  - inverts* R2; try solve[inverts* H0].\n  - inverts* R2; try solve[inverts H].\n    inverts* Val; inverts* H0. inverts* H2. inverts H3.\n    inverts H; simpl in *. inverts H4. \n    exfalso. apply H; auto.\n    inverts* H. inverts* H.\n  - inverts* R2; try solve[ inverts* H7];try solve[inverts* H0];\n    try solve[inverts* H3].\n    inverts Val. rewrite H6 in H2; inverts H2.\n    exfalso.\n    apply H7.\n    eauto.\n  - inverts* R2;\n    try solve[forwards*: flike_not_ground H];\n    try solve[inverts* H].\n  - inverts* R2;\n    try solve[inverts* H];\n    try solve[inverts* H0];\n    try solve[inverts* H1];\n    try solve[inverts H9].\n  -\n    inverts* R2;\n    try solve[inverts* H6];\n    try solve[inverts* H5];\n    try solve[inverts* H].\n    inverts H8; simpl;eauto.\n    inverts H0.\n    exfalso; apply H1; simpl;eauto.\n    inverts H8.\n    exfalso; apply H6; simpl;eauto.\n  - inverts* R2;\n    try solve[inverts H3];\n    try solve[inverts* H1];\n    try solve[inverts* H].\n    inverts* Val.\n    forwards*: flike_not_ground H.\n    exfalso.\n    apply H9.\n    apply BA_AB; auto.\n  - inverts* R2; try solve[inverts* H5];\n    try solve[inverts* H4];\n    try solve[inverts* H7];\n    try solve[inverts* H].\n    inverts* Val.\n    rewrite <- H6 in H2. inverts H2.\n    inverts* Val.\n    forwards*: flike_not_ground H3.\n    exfalso; apply H7;\n    apply sim_refl.\n  -\n  inverts* R2; simpl in *;try solve[inverts* H7];\n  try solve[inverts* H1];\n  try solve[inverts* H0].\n  exfalso; apply H; eauto.\n  exfalso; apply H;simpl; eauto.\n  exfalso.\n  apply H.\n  apply BA_AB; auto.\n  exfalso; apply H;\n  apply sim_refl.\nQed.\n\n\nLemma fill_auxi: forall E1 E0 e0 e1 r2 r1,\n fill E0 e0 = fill E1 e1 ->\n wellformed E0 ->\n wellformed E1 ->\n step e0 r1 ->\n step e1 r2 ->\n (E1 = E0)/\\ (e0 = e1).\nProof.\n  introv eq wf1 wf2 red1 red2. gen E1 e0 e1 r1 r2.\n  inductions E0; unfold fill in *;  intros. \n  - inductions E1; unfold fill in *; inverts* eq.\n    inverts wf2.\n    forwards*: step_not_value red1.\n  - inductions E1; unfold fill in *; inverts* eq.\n    inverts wf1.\n    forwards*: step_not_value red2.\n  - inductions E1; unfold fill in *; inverts* eq.    \n  - inductions E1; unfold fill in *; inverts* eq.\n    inverts wf2.\n    forwards*: step_not_value red1.\n  - inductions E1; unfold fill in *; inverts* eq.\n    inverts wf1.\n    forwards*: step_not_value red2.\nQed.\n\nLemma fill_typ: forall E e1 A,\n wellformed E ->\n Typing nil (fill E e1) Chk A ->\n exists B, Typing nil e1 Chk B.\nProof.\n  introv wf Typ. gen e1 A. \n  inductions E; intros.\n  - simpl in *.\n    inverts Typ. inverts H. \n    inverts wf.\n    forwards*: Typing_chk H9.\n  - unfold fill in *.\n    inverts Typ.\n    inverts* H.\n  - unfold fill in *.\n    inverts Typ.\n    inverts* H. \n    - simpl in *.\n    inverts Typ. inverts H. \n    inverts wf.\n    forwards*: Typing_chk H4.\n  - unfold fill in *.\n    inverts Typ.\n    inverts* H.\nQed.\n\n\nTheorem step_unique: forall A e r1 r2,\n    Typing nil e Chk A -> step e r1 -> step e r2 -> r1 = r2.\nProof.\n  introv Typ Red1.\n  gen A r2.\n  lets Red1' : Red1.\n  induction Red1;\n    introv Typ Red2.\n  - inverts* Red2;\n    try solve[destruct E; unfold fill in H0; inverts* H0;\n    forwards*: step_not_value Red1;\n    forwards*: step_not_value Red1];\n    try solve[destruct E; unfold fill in H0; inverts* H0;\n    forwards*: step_not_value Red1;eapply value_fanno;eauto;reflexivity;\n    forwards*: step_not_value Red1;eapply value_fanno;eauto;reflexivity];\n    try solve[destruct E; unfold fill in H1; inverts* H1;\n    forwards*: step_not_value Red1;\n    forwards*: step_not_value Red1].\n    forwards*: fill_auxi H0. inverts H3. \n    forwards*: fill_typ Typ. inverts H3.\n    forwards*: IHRed1 Red1 H2. congruence.\n    forwards*: fill_auxi H0. inverts H3. \n    forwards*: fill_typ Typ. inverts H3.\n    forwards*: IHRed1 Red1 H2. congruence.\n    destruct E; unfold fill in *; inverts* H0;\n    try solve[forwards*: step_not_value Red1].\n    inverts H. inverts* H4.\n  - inverts* Red2;\n    try solve[destruct E; unfold fill in H0; inverts* H0;\n    forwards*: step_not_value Red1;\n    forwards*: step_not_value Red1];\n    try solve[destruct E; unfold fill in H1; inverts* H1;\n    forwards*: step_not_value Red1;\n    forwards*: step_not_value Red1];\n    try solve[destruct E; unfold fill in H0; inverts* H0;\n    forwards*: step_not_value Red1;eapply value_fanno;eauto;reflexivity;\n    forwards*: step_not_value Red1;eapply value_fanno;eauto;reflexivity].\n    forwards*: fill_auxi H0. inverts H3. \n    forwards*: fill_typ Typ. inverts H3.\n    forwards*: IHRed1 Red1 H2. congruence.\n    forwards*: fill_auxi H0. inverts H3. \n    forwards*: fill_typ Typ. inverts H3.\n    forwards*: IHRed1 Red1 H2.\n    destruct E; unfold fill in *; inverts* H0;\n    try solve[forwards*: step_not_value Red1].\n    inverts H. inverts* H4.\n  - inverts* Red2;\n    try solve[destruct E; unfold fill in H1; inverts* H1;\n    forwards*: step_not_value H3;eapply value_fanno;eauto;reflexivity;\n    forwards*: step_not_value H3];\n    try solve[inverts* H9];\n    try solve[inverts* H0].\n  - inverts* Red2;\n    try solve[destruct E; unfold fill in H3; inverts* H3;\n    forwards*: step_not_value H5;\n    forwards*: step_not_value H5];\n    try solve[inverts* H1].\n    rewrite H10 in *. inverts H1.\n    inverts Typ. inverts H1.\n    forwards*: TypedReduce_unique H2 H11.\n    congruence.\n  - inverts* Red2;\n    try solve[destruct E; unfold fill in H2; inverts* H2;\n    forwards*: step_not_value H4;\n    forwards*: step_not_value H4];\n    try solve[inverts* H8];\n    try solve[inverts* H0].\n    inverts Typ.\n    inverts H2.\n    forwards*: TypedReduce_unique H0 H8.\n  - inverts* Red2;\n    try solve[destruct E; unfold fill in H3; inverts* H3;\n    forwards*: step_not_value H5;\n    forwards*: step_not_value H5];\n    try solve[inverts H0].\n    rewrite H2 in *. inverts* H13.\n  - inverts* Red2;\n    try solve[destruct E; unfold fill in H3; inverts* H3;\n    forwards*: step_not_value H5;\n    forwards*: step_not_value H5];\n    try solve[inverts* H1].\n    rewrite H10 in *.\n    inverts H1.\n    inverts Typ.\n    inverts H1.\n    forwards*: TypedReduce_unique H2 H11.\n    congruence.\n    rewrite H10 in *.\n    inverts H1.\n    inverts Typ.\n    inverts H1.\n    forwards*: TypedReduce_unique H2 H11.\n    congruence.\n  - inverts* Red2;\n    try solve[destruct E; unfold fill in H1; inverts* H1;\n    forwards*: step_not_value H3;\n    forwards*: step_not_value H3];\n    try solve[inverts* H8];\n    try solve[inverts* H0];\n    try solve[inverts* H5].\n    destruct E; unfold fill in H1; inverts* H1;\n    try solve[forwards*: step_not_value H3].\n    inverts H2. inverts H5.\n    destruct E; unfold fill in H1; inverts* H1;\n    try solve[forwards*: step_not_value H3].\n    inverts H2. inverts H5.\n  -\n    inverts* Red2;\n    try solve[destruct E; unfold fill in H; inverts* H;\n    forwards*: step_not_value H1;eapply value_fanno;eauto;reflexivity;\n    forwards*: step_not_value H1].\n  -\n    inverts* Red2;\n    try solve[destruct E; unfold fill in H; inverts* H;\n    forwards*: step_not_value H1;eapply value_fanno;eauto;reflexivity;\n    forwards*: step_not_value H1].\n  -\n    inverts* Red2;\n    try solve[destruct E; unfold fill in H1; inverts* H1;\n    forwards*: step_not_value H3;eapply value_fanno;eauto;reflexivity;\n    forwards*: step_not_value H3].\nQed.\n\n\n", "meta": {"author": "YeWenjia", "repo": "TypedDirectedGradualTypingWithBlame", "sha": "99210b5208555d4ea729738ea4a959c59b0646d0", "save_path": "github-repos/coq/YeWenjia-TypedDirectedGradualTypingWithBlame", "path": "github-repos/coq/YeWenjia-TypedDirectedGradualTypingWithBlame/TypedDirectedGradualTypingWithBlame-99210b5208555d4ea729738ea4a959c59b0646d0/JFP-Artifact/\\Bg(label)/coq/Deterministic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.29875989732867786}}
{"text": "(*\n * Copyright © 2013 http://io7m.com\n *\n * Permission to use, copy, modify, and/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *)\nRequire SetWeak.\n\n(** A trivial and extremely inefficient implementation of the [SetWeak]\ninterface implemented with lists. *)\nModule Make (P : SetWeak.Parameters) : SetWeak.Signature with Definition e := P.t.\n\nDefinition e := P.t.\n\nDefinition t := list e.\n\nDefinition singleton (x : e) := cons x nil.\n\nFixpoint is_in\n  (x : e)\n  (s : t)\n: Prop :=\n  match s with\n  | nil       => False\n  | cons y ys => (x = y) \\/ (x <> y /\\ is_in x ys)\n  end.\n\nTheorem is_in_decidable : forall (x : e) (s : t),\n  {is_in x s}+{~is_in x s}.\nProof.\n  induction s as [|sh sr].\n    right; auto.\n    destruct IHsr as [IHL|IHR].\n      destruct (P.t_eq_decidable x sh) as [H_eq|H_neq].\n        rewrite H_eq.\n        left; left; reflexivity.\n        simpl; auto.\n      destruct (P.t_eq_decidable x sh) as [H_eq|H_neq].\n        rewrite H_eq.\n        left; left; reflexivity.\n        simpl in *; intuition.\nQed.\n\nFixpoint remove\n  (x : e)\n  (s : t)\n: t :=\n  match s with\n  | nil       => nil\n  | cons y ys =>\n    match P.t_eq_decidable x y with\n    | left _  => remove x ys\n    | right _ => cons y (remove x ys)\n    end\n  end.\n\nFixpoint insert\n  (x : e)\n  (s : t)\n: t := cons x (remove x s).\n\nDefinition empty := @nil e.\n\nTheorem remove_is_in_false : forall (x : e) (s : t),\n  ~is_in x (remove x s).\nProof.\n  intros x s.\n  induction s as [|y ys].\n    (* s = nil *)\n    simpl; auto.\n    (* s = y :: ys *)\n    simpl; destruct (P.t_eq_decidable x y) as [H_xy_eq|H_xy_neq].\n      (* x = y *)\n      assumption.\n      (* x <> y *)\n      simpl.\n      unfold not.\n      intros H_contra_goal.\n      destruct H_contra_goal as [H_cg_L|H_cg_R].\n        contradict H_xy_neq; assumption.\n        destruct H_cg_R as [H_cg_RL H_cg_RR].\n          auto.\nQed.\n\nTheorem remove_preserves_is_in : forall (x0 x1 : e) (s : t),\n  x0 <> x1 -> (is_in x0 (remove x1 s) <-> is_in x0 s).\nProof.\n  intros x0 x1 s H_x0x1_neq.\n  apply conj.\n    intros H_in_remove.\n    induction s as [|y ys].\n      (* s = nil *)\n      simpl; auto.\n      (* s = y :: ys *)\n      simpl in *. destruct (P.t_eq_decidable x1 y) as [H_x1y_eq|H_x1y_neq].\n        (* x1 = y *)\n        right; apply conj.\n          rewrite H_x1y_eq in H_x0x1_neq.\n          assumption.\n          apply (IHys H_in_remove).\n        (* x1 <> y *)\n        destruct H_in_remove as [H_in_remove_L|H_in_remove_R].\n          left; assumption.\n          right; apply conj.\n            destruct H_in_remove_R as [H_in_remove_RL H_in_remove_RR].\n              assumption.\n            destruct H_in_remove_R as [H_in_remove_RL H_in_remove_RR].\n              apply (IHys H_in_remove_RR).\n\n    intros H_in_remove.\n    induction s as [|y ys].\n      (* s = nil *)\n      simpl; auto.\n      (* s = y :: ys *)\n      simpl in *. destruct (P.t_eq_decidable x1 y) as [H_x1y_eq|H_x1y_neq].\n        (* x1 = y *)\n        destruct H_in_remove as [H_in_remove_L|H_in_remove_R].\n          contradict H_x0x1_neq.\n            rewrite H_in_remove_L.\n            rewrite H_x1y_eq.\n            reflexivity.\n          destruct H_in_remove_R as [H_in_remove_RL H_in_remove_RR].\n            apply (IHys H_in_remove_RR).\n        (* x1 <> y *)\n        simpl; destruct H_in_remove as [H_in_remove_L|H_in_remove_R].\n          left; assumption.\n          right; apply conj.\n            destruct H_in_remove_R as [H_in_remove_RL H_in_remove_RR].\n              assumption.\n            destruct H_in_remove_R as [H_in_remove_RL H_in_remove_RR].\n              apply (IHys H_in_remove_RR).\nQed.\n\nLemma not_in_cons_0 : forall (x0 x1 : e) (s : t),\n  x0 <> x1 -> ~is_in x0 (cons x1 s) -> ~is_in x0 s.\nProof.\n  intros x0 x1 s H_neq H_not_in.\n  simpl in *; intuition.\nQed.\n\nLemma not_in_cons_1 : forall (x0 x1 : e) (s : t),\n  x0 <> x1 -> ~is_in x0 s -> ~is_in x0 (cons x1 s).\nProof.\n  intros x0 x1 s H_neq H_not_in.\n  simpl in *; intuition.\nQed.\n\nLemma remove_preserves_is_in_false : forall (x0 x1 : e) (s : t),\n  ~is_in x0 s -> ~is_in x0 (remove x1 s).\nProof.\n  intros x0 x1 s H_not_in.\n  destruct (P.t_eq_decidable x0 x1) as [H_x0x1_eq|H_x0x1_neq].\n    rewrite H_x0x1_eq.\n    apply remove_is_in_false.\n    induction s as [|sh sr].\n      auto.\n      simpl; destruct (P.t_eq_decidable x1 sh) as [H_x1sh_eq|H_x1sh_neq].\n        rewrite <- H_x1sh_eq in H_not_in.\n        assert (~is_in x0 sr) as H_not_in_rest.\n          apply (not_in_cons_0 x0 x1 sr H_x0x1_neq H_not_in).\n        apply (IHsr H_not_in_rest).\n        simpl in *.\n        intuition.\nQed.\n\nTheorem remove_preserves_is_in_false_alt : forall (x0 x1 : e) (s : t),\n  x0 <> x1 -> ~is_in x0 (remove x1 s) -> ~is_in x0 s.\nProof.\n  intros x0 x1 s H_neq H_not_in.\n  induction s as [|sh sr].\n    simpl; auto.\n    simpl in H_not_in.\n    destruct (P.t_eq_decidable x1 sh) as [H_x1sh_eq|H_x1sh_neq].\n      assert (~is_in x0 sr) by (apply (IHsr H_not_in)).\n      rewrite <- H_x1sh_eq.\n      apply (not_in_cons_1 x0 x1 sr H_neq H).\n      simpl in *; intuition.\nQed.\n\nTheorem is_in_empty_false : forall (x : e), ~is_in x empty.\nProof.\n  intros x.\n  compute; auto.\nQed.\n\nTheorem insert_is_in : forall (x : e) (s : t),\n  is_in x (insert x s).\nProof.\n  intros x s.\n  induction s as [|y ys].\n    (* s = nil *)\n    simpl; auto.\n    (* s = y :: ys *)\n    simpl; left; reflexivity.\nQed.\n\nTheorem insert_preserves_is_in : forall (x0 x1 : e) (s : t),\n  x0 <> x1 -> is_in x0 s -> is_in x0 (insert x1 s).\nProof.\n  intros x0 x1 s H_x0x1_neq H_x0_in.\n  induction s as [|y ys].\n    (* s = nil *)\n    simpl; auto.\n    (* s = y :: ys *)\n    simpl in *; destruct H_x0_in as [H_x0_in_L|H_x0_in_R].\n      right; apply conj.\n        assumption.\n        destruct (P.t_eq_decidable x1 y) as [H_x1y_eq|H_x1y_neq].\n          (* x1 = y *)\n          contradict H_x0x1_neq.\n            rewrite H_x0_in_L.\n            rewrite H_x1y_eq.\n            reflexivity.\n          (* x1 <> y *)\n          left; assumption.\n      right; apply conj.\n        assumption.\n        destruct (P.t_eq_decidable x1 y) as [H_x1y_eq|H_x1y_neq].\n          (* x1 = y *)\n          destruct (remove_preserves_is_in x0 x1 ys H_x0x1_neq).\n            destruct H_x0_in_R as [H_x0_in_RL H_x0_in_RR].\n              auto.\n          (* x1 <> y *)\n          right; apply conj.\n            destruct H_x0_in_R as [H_x0_in_RL H_x0_in_RR].\n              assumption.\n            destruct (remove_preserves_is_in x0 x1 ys H_x0x1_neq).\n              destruct H_x0_in_R as [H_x0_in_RL H_x0_in_RR].\n                auto.\nQed.\n\nTheorem insert_preserves_is_in_false : forall (x0 x1 : e) (s : t),\n  x0 <> x1 -> (~is_in x0 (insert x1 s) <-> ~is_in x0 s).\nProof.\n  intros x0 x1 s H_x0x1_neq.\n  apply conj.\n    intros H_not_in.\n    induction s as [|y ys].\n      (* s = nil *)\n      simpl; auto.\n      (* s = y :: ys *)\n      simpl in *; destruct (P.t_eq_decidable x1 y) as [H_x1y_eq|H_x1y_neq].\n        (* x1 = y *)\n        unfold not.\n        intros H_contra_goal.\n        destruct H_not_in.\n          destruct H_contra_goal as [H_cg_L|H_cg_R].\n            contradict H_x0x1_neq.\n              rewrite H_x1y_eq.\n              rewrite H_cg_L.\n              reflexivity.\n            right; apply conj.\n              assumption.\n              destruct H_cg_R as [H_cg_RL H_cg_RR].\n                destruct (remove_preserves_is_in x0 x1 ys H_x0x1_neq).\n                  auto.\n        (* x1 <> y *)\n        unfold not.\n        intros H_contra_goal.\n        destruct H_not_in.\n          destruct H_contra_goal as [H_cg_L|H_cg_R].\n            right; apply conj.\n              assumption.\n              left; assumption.\n            right; apply conj.\n              assumption.\n              right; apply conj.\n                destruct H_cg_R as [H_cg_RL H_cg_RR].\n                  auto.\n                destruct H_cg_R as [H_cg_RL H_cg_RR].\n                  destruct (remove_preserves_is_in x0 x1 ys H_x0x1_neq).\n                    auto.\n\n    intros H_not_in.\n    induction s as [|y ys].\n      (* s = nil *)\n      simpl in *.\n      unfold not.\n      intros H_contra_goal.\n      destruct H_contra_goal as [H_cg_L|H_cg_R].\n        contradict H_x0x1_neq.\n          assumption.\n        tauto.\n      (* s = y :: ys *)\n      simpl in *; destruct (P.t_eq_decidable x1 y) as [H_x1y_eq|H_x1y_neq].\n        (* x1 = y *)\n        unfold not.\n        intros H_contra_goal.\n        destruct H_contra_goal as [H_cg_L|H_cg_R].\n          contradict H_x0x1_neq.\n            assumption.\n          destruct H_not_in.\n            right; apply conj.\n              rewrite <- H_x1y_eq.\n              assumption.\n              destruct H_cg_R as [H_cg_RL H_cg_RR].\n                destruct (remove_preserves_is_in x0 x1 ys H_x0x1_neq).\n                  auto.\n        (* x1 <> y *)\n        unfold not.\n        intros H_contra_goal.\n        destruct H_not_in.\n          simpl in *. destruct H_contra_goal as [H_cg_L|H_cg_R].\n            contradict H_x0x1_neq.\n              assumption.\n            destruct H_cg_R as [H_cg_RL H_cg_RR].\n              destruct H_cg_RR as [H_cg_RRL|H_cg_RRR].\n                left; assumption.\n                right; apply conj.\n                  destruct H_cg_RRR as [H_cg_RRRL H_cg_RRRR].\n                    assumption.\n                  destruct H_cg_RRR as [H_cg_RRRL H_cg_RRRR].\n                    destruct (remove_preserves_is_in x0 x1 ys H_x0x1_neq).\n                      auto.\nQed.\n\nTheorem singleton_eq : forall (x : e),\n  singleton x = insert x empty.\nProof.\n  reflexivity.\nQed.\n\nEnd Make.", "meta": {"author": "io7m", "repo": "jvvfs-model2", "sha": "9093a5653a8f3e0b6209af01075f0aa30b6733d5", "save_path": "github-repos/coq/io7m-jvvfs-model2", "path": "github-repos/coq/io7m-jvvfs-model2/jvvfs-model2-9093a5653a8f3e0b6209af01075f0aa30b6733d5/ListSetWeak.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.2987598894635957}}
{"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 liblayers.lib.Functor.\nRequire Import liblayers.lib.Monad.\nRequire Import liblayers.lib.Lens.\nRequire Export liblayers.lib.Lift.\n\n(** * Prerequisites *)\n\n(** We're going to lift the memory operations and theorems from a base\n  type [bmem] to a \"richer\" type [mem], which contains [bmem] as a\n  component. Formally, this means that we have a [Lens mem bmem] which\n  provides us with well-behaved accessors to the [bmem] component\n  inside of [mem]. While this is enough to lift most of the memory\n  operations and theorems, we also need to know the value of\n  the empty memory state of the richer type [mem]; indeed there's no\n  way we would be able to construct that just from [empty : bmem].\n  However, the simpler memory state contained within this empty [mem]\n  should correspond to the empty [bmem] from the base memory states. *)\n\nClass LiftMemoryModelOps {mem bmem: Type} (π: mem -> bmem)\n  `{bmem_ops: Mem.MemoryModelOps bmem}\n  `{bmem_set: !LensOps π} :=\n{\n  liftmem_empty: mem\n}.\n\nClass LiftMemoryModel {mem bmem: Type} (π: mem -> bmem)\n  `{mem_liftops: LiftMemoryModelOps mem bmem π}: Prop :=\n{\n  liftmem_lens :> Lens π;\n  liftmem_get_empty: π liftmem_empty = Mem.empty\n}.\n\n(** Using all of this, we can build a set of memory operations on the\n  source type [mem] from the operations on the view type [bmem]. *)\n\nSection LIFTOPS.\n  Global Instance liftmem_ops `{mem_liftops: LiftMemoryModelOps}:\n    Mem.MemoryModelOps mem :=\n  {\n    empty :=\n      liftmem_empty;\n    alloc wm lo hi :=\n      lift π (fun m => Mem.alloc m lo hi) wm;\n    nextblock wm :=\n      lift π Mem.nextblock wm;\n    free wm b lo hi :=\n      lift π (fun m => Mem.free m b lo hi) wm;\n    load chunk wm b ofs :=\n      lift π (fun m => Mem.load chunk m b ofs) wm;\n    store chunk wm b ofs v :=\n      lift π (fun m => Mem.store chunk m b ofs v) wm;\n    loadbytes wm b ofs n :=\n      lift π (fun m => Mem.loadbytes m b ofs n) wm;\n    storebytes wm b ofs vs :=\n      lift π (fun m => Mem.storebytes m b ofs vs) wm;\n    perm wm b ofs k p :=\n      lift π (fun m => Mem.perm m b ofs k p) wm;\n    valid_pointer wm b ofs :=\n      lift π (fun m => Mem.valid_pointer m b ofs) wm;\n    drop_perm wm b lo hi p :=\n      lift π (fun m => Mem.drop_perm m b lo hi p) wm;\n    extends wm1 wm2 :=\n      lift π Mem.extends wm1 wm2;\n    inject f wm1 wm2 :=\n      lift π (Mem.inject f) wm1 wm2;\n    inject_neutral thr wm :=\n      lift π (Mem.inject_neutral thr) wm;\n    unchanged_on P wm1 wm2 :=\n      Mem.unchanged_on P (π wm1) (π wm2)\n  }.\nEnd LIFTOPS.\n\n(** ** Properties of the [inject_incr] relation *)\n\n(** Those are needed to enable rewriting using [liftmem_inject_same_context]. *)\n\nGlobal Instance: Reflexive inject_incr.\nProof.\n  firstorder.\nQed.\n\nGlobal Instance: Transitive inject_incr.\nProof.\n  firstorder.\nQed.\n\n(** * Lifting the properties *)\n\nSection LIFTDERIVED.\n  Context `{HW: LiftMemoryModel}.\n\n  (** Show that the operations derived from the [Mem.MemoryBaseOps]\n    instance above are equivalent to lifting the operations derived\n    from the original [Mem.MemoryBaseOps]. *)\n\n  Theorem lift_loadv chunk wm addr:\n    Mem.loadv chunk wm addr =\n    lift π (fun m => Mem.loadv chunk m addr) wm.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Theorem lift_storev chunk a v wm:\n    Mem.storev chunk wm a v =\n    lift π (fun m => Mem.storev chunk m a v) wm.\n  Proof.\n    unfold Mem.storev.\n    destruct a; reflexivity.\n  Qed.\n\n  Theorem lift_free_list l wm:\n    Mem.free_list wm l =\n    lift π (fun m => Mem.free_list m l) wm.\n  Proof with lift_auto.\n    revert wm.\n    induction l as [ | [[b lo] hi] l IHl]; intros...\n    destruct (Mem.free (π wm) b lo hi)...\n    rewrite IHl...\n    destruct (Mem.free_list b0 l)...\n  Qed.\n\n  Theorem lift_valid_block (wm: mem) (b: block):\n    Mem.valid_block wm b <->\n    lift π (fun m => Mem.valid_block m b) wm.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Theorem lift_range_perm (wm: mem) b lo hi k p:\n    Mem.range_perm wm b lo hi k p <->\n    lift π (fun m => Mem.range_perm m b lo hi k p) wm.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Theorem lift_valid_access (wm: mem) chunk b ofs p:\n    Mem.valid_access wm chunk b ofs p <->\n    lift π (fun m => Mem.valid_access m chunk b ofs p) wm.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Theorem lift_weak_valid_pointer (wm: mem) b ofs:\n    Mem.weak_valid_pointer wm b ofs =\n    lift π (fun m => Mem.weak_valid_pointer m b ofs) wm.\n  Proof.\n    reflexivity.\n  Qed.\nEnd LIFTDERIVED.\n\nHint Rewrite\n  @lift_loadv\n  @lift_storev\n  @lift_free_list\n  @lift_valid_block\n  @lift_range_perm\n  @lift_valid_access\n  @lift_weak_valid_pointer\n  using typeclasses eauto : lift.\n\n(** Replace [(get Mem.empty)] by the underlying [Mem.empty]. *)\nHint Rewrite\n  @liftmem_get_empty\n  using typeclasses eauto: lens.\n\nSection LIFTMEM.\n  Context mem bmem `{Hmem: LiftMemoryModel mem bmem}.\n\n  Local Arguments fmap : simpl never.\n\n  Global Instance liftmem_spec:\n    Mem.MemoryModel bmem -> Mem.MemoryModel mem.\n  Proof.\n    intro Hbmem; esplit.\n    lift π Mem.valid_not_valid_diff.\n    lift π Mem.perm_implies.\n    lift π Mem.perm_cur_max.\n    lift π Mem.perm_cur.\n    lift π Mem.perm_max.\n    lift π Mem.perm_valid_block.\n    lift π Mem.range_perm_implies.\n    lift π Mem.range_perm_cur.\n    lift π Mem.range_perm_max.\n    lift π Mem.valid_access_implies.\n    lift π Mem.valid_access_valid_block.\n    lift π Mem.valid_access_perm.\n    lift π Mem.valid_pointer_nonempty_perm.\n    lift π Mem.valid_pointer_valid_access.\n    lift π Mem.weak_valid_pointer_spec.\n    lift π Mem.valid_pointer_implies.\n    lift π Mem.nextblock_empty.\n    lift π Mem.perm_empty.\n    lift π Mem.valid_access_empty.\n    lift π Mem.valid_access_load.\n    lift π Mem.load_valid_access.\n    lift π Mem.load_type.\n    lift π Mem.load_cast.\n    lift π Mem.load_int8_signed_unsigned.\n    lift π Mem.load_int16_signed_unsigned.\n    lift π Mem.loadv_int64_split.\n    lift π Mem.range_perm_loadbytes.\n    lift π Mem.loadbytes_range_perm.\n    lift π Mem.loadbytes_load.\n    lift π Mem.load_loadbytes.\n    lift π Mem.loadbytes_length.\n    lift π Mem.loadbytes_empty.\n    lift π Mem.loadbytes_concat.\n    lift π Mem.loadbytes_split.\n    lift π Mem.nextblock_store.\n    lift π Mem.store_valid_block_1.\n    lift π Mem.store_valid_block_2.\n    lift π Mem.perm_store_1.\n    lift π Mem.perm_store_2.\n    lift π Mem.store_valid_access_1.\n    lift π Mem.store_valid_access_2.\n    lift π Mem.store_valid_access_3.\n    lift π Mem.valid_access_store.\n    lift π Mem.load_store_similar.\n    lift π Mem.load_store_similar_2.\n    lift π Mem.load_store_same.\n    lift π Mem.load_store_other.\n    lift π Mem.load_store_pointer_overlap.\n    lift π Mem.load_store_pointer_mismatch.\n    lift π Mem.load_pointer_store.\n    lift π Mem.loadbytes_store_same.\n    lift π Mem.loadbytes_store_other.\n    lift π Mem.store_signed_unsigned_8.\n    lift π Mem.store_signed_unsigned_16.\n    lift π Mem.store_int8_zero_ext.\n    lift π Mem.store_int8_sign_ext.\n    lift π Mem.store_int16_zero_ext.\n    lift π Mem.store_int16_sign_ext.\n    lift π Mem.store_float32_truncate.\n    lift π Mem.storev_int64_split.\n    lift π Mem.storebytes_range_perm.\n    lift π Mem.perm_storebytes_1.\n    lift π Mem.perm_storebytes_2.\n    lift π Mem.storebytes_valid_access_1.\n    lift π Mem.storebytes_valid_access_2.\n    lift π Mem.nextblock_storebytes.\n    lift π Mem.storebytes_valid_block_1.\n    lift π Mem.storebytes_valid_block_2.\n    lift π Mem.range_perm_storebytes.\n    lift π Mem.storebytes_store.\n    lift π Mem.store_storebytes.\n    lift π Mem.loadbytes_storebytes_same.\n    lift π Mem.loadbytes_storebytes_other.\n    lift π Mem.load_storebytes_other.\n    lift π Mem.loadbytes_storebytes_disjoint.\n    lift π Mem.storebytes_concat.\n    lift π Mem.storebytes_split.\n    lift π Mem.alloc_result.\n    lift π Mem.nextblock_alloc.\n    lift π Mem.valid_block_alloc.\n    lift π Mem.fresh_block_alloc.\n    lift π Mem.valid_new_block.\n    lift π Mem.valid_block_alloc_inv.\n    lift π Mem.perm_alloc_1.\n    lift π Mem.perm_alloc_2.\n    lift π Mem.perm_alloc_3.\n    lift π Mem.perm_alloc_4.\n    lift π Mem.perm_alloc_inv.\n    lift π Mem.valid_access_alloc_other.\n    lift π Mem.valid_access_alloc_same.\n    lift π Mem.valid_access_alloc_inv.\n    lift π Mem.load_alloc_unchanged.\n    lift π Mem.load_alloc_other.\n    lift π Mem.load_alloc_same.\n    lift π Mem.load_alloc_same'.\n    lift π Mem.loadbytes_alloc_unchanged.\n    lift π Mem.loadbytes_alloc_same.\n    lift π Mem.free_range_perm.\n    lift π Mem.range_perm_free.\n    lift π Mem.nextblock_free.\n    lift π Mem.valid_block_free_1.\n    lift π Mem.valid_block_free_2.\n    lift π Mem.perm_free_1.\n    lift π Mem.perm_free_2.\n    lift π Mem.perm_free_3.\n    lift π Mem.perm_free_list.\n    lift π Mem.valid_access_free_1.\n    lift π Mem.valid_access_free_2.\n    lift π Mem.valid_access_free_inv_1.\n    lift π Mem.valid_access_free_inv_2.\n    lift π Mem.load_free.\n    lift π Mem.loadbytes_free.\n    lift π Mem.loadbytes_free_2.\n    lift π Mem.nextblock_drop.\n    lift π Mem.drop_perm_valid_block_1.\n    lift π Mem.drop_perm_valid_block_2.\n    lift π Mem.range_perm_drop_1.\n    lift π Mem.range_perm_drop_2.\n    lift π Mem.perm_drop_1.\n    lift π Mem.perm_drop_2.\n    lift π Mem.perm_drop_3.\n    lift π Mem.perm_drop_4.\n    lift π Mem.load_drop.\n    lift π Mem.loadbytes_drop.\n    lift π Mem.mext_next.\n    lift π Mem.extends_refl.\n    lift π Mem.load_extends.\n    lift π Mem.loadv_extends.\n    lift π Mem.loadbytes_extends.\n    lift π Mem.store_within_extends.\n    lift π Mem.store_outside_extends.\n    lift π Mem.storev_extends.\n    lift π Mem.storebytes_within_extends.\n    lift π Mem.storebytes_outside_extends.\n    lift π Mem.alloc_extends.\n    lift π Mem.free_left_extends.\n    lift π Mem.free_right_extends.\n    lift π Mem.free_parallel_extends.\n    lift π Mem.valid_block_extends.\n    lift π Mem.perm_extends.\n    lift π Mem.valid_access_extends.\n    lift π Mem.valid_pointer_extends.\n    lift π Mem.weak_valid_pointer_extends.\n    lift π Mem.mi_freeblocks.\n    lift π Mem.mi_mappedblocks.\n    lift π Mem.mi_no_overlap.\n    lift π Mem.valid_block_inject_1.\n    lift π Mem.valid_block_inject_2.\n    lift π Mem.perm_inject.\n    lift π Mem.range_perm_inject.\n    lift π Mem.valid_access_inject.\n    lift π Mem.valid_pointer_inject.\n    lift π Mem.weak_valid_pointer_inject.\n    lift π Mem.address_inject.\n    lift π Mem.valid_pointer_inject_no_overflow.\n    lift π Mem.weak_valid_pointer_inject_no_overflow.\n    lift π Mem.valid_pointer_inject_val.\n    lift π Mem.weak_valid_pointer_inject_val.\n    lift π Mem.inject_no_overlap.\n    lift π Mem.different_pointers_inject.\n    lift π Mem.disjoint_or_equal_inject.\n    lift π Mem.aligned_area_inject.\n    lift π Mem.load_inject.\n    lift π Mem.loadv_inject.\n    lift π Mem.loadbytes_inject.\n    lift π Mem.store_mapped_inject.\n    lift π Mem.store_unmapped_inject.\n    lift π Mem.store_outside_inject.\n    lift π Mem.storev_mapped_inject.\n    lift π Mem.storebytes_mapped_inject.\n    lift π Mem.storebytes_unmapped_inject.\n    lift π Mem.storebytes_outside_inject.\n    lift π Mem.storebytes_empty_inject.\n    lift π Mem.alloc_right_inject.\n    lift π Mem.alloc_left_unmapped_inject.\n    lift π Mem.alloc_left_mapped_inject.\n    lift π Mem.alloc_parallel_inject.\n    lift π Mem.free_inject.\n    lift π Mem.free_left_inject.\n    lift π Mem.free_list_left_inject.\n    lift π Mem.free_right_inject.\n    lift π Mem.drop_outside_inject.\n    lift π Mem.neutral_inject.\n    lift π Mem.empty_inject_neutral.\n    lift π Mem.alloc_inject_neutral.\n    lift π Mem.store_inject_neutral.\n    lift π Mem.drop_inject_neutral.\n    lift π Mem.unchanged_on_refl.\n    lift π Mem.perm_unchanged_on.\n    lift π Mem.perm_unchanged_on_2.\n    lift π Mem.loadbytes_unchanged_on_1.\n    lift π Mem.loadbytes_unchanged_on.\n    lift π Mem.load_unchanged_on_1.\n    lift π Mem.load_unchanged_on.\n    lift π Mem.store_unchanged_on.\n    lift π Mem.storebytes_unchanged_on.\n    lift π Mem.alloc_unchanged_on.\n    lift π Mem.free_unchanged_on.\n    lift π Mem.unchanged_on_empty.\n    lift π Mem.unchanged_on_trans.\n    lift π Mem.unchanged_on_weak.\n    lift π Mem.unchanged_on_or.\n    lift π Mem.unchanged_on_exists.\n  Qed.\nEnd LIFTMEM.\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/LiftMem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.5039061705290806, "lm_q1q2_score": 0.29864835678334584}}
{"text": "(* coq-prelude\n * Copyright (C) 2018 ANSSI\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 Coq Require Import Equivalence Setoid Morphisms.\nFrom Prelude Require Export Equality.\n\nSet Universe Polymorphism.\n\nDeclare Scope monad_scope.\nDelimit Scope monad_scope with monad.\n\n#[local]\nOpen Scope prelude_scope.\n\nDefinition compose {a b c} (g : b -> c) (f : a -> b) : a -> c :=\n  fun (x: a) => g (f x).\n\nDefinition id {a : Type} (x : a) : a := x.\n\nNotation \"f <<< g\" := (compose f g) (at level 50) : function_scope.\nNotation \"f >>> g\" := (compose g f) (at level 50) : function_scope.\n\nNotation \"'fun*' x .. z '=>' p\" := (fun x => .. (fun z => p%monad) ..)\n  (x binder, z binder, at level 200, only parsing) : function_scope.\n\nNotation \"f $ x\" :=\n  (f x) (only parsing, at level 99, right associativity) : prelude_scope.\n\n(** * Functor *)\n\nClass Functor (f : Type -> Type) : Type :=\n  { functor_has_eq :> forall {a} `{Equality a}, Equality (f a)\n  ; map {a b : Type} : (a -> b) -> f a -> f b\n  ; functor_identity {a} `{Equality a} (x : f a) : map id x == id x\n  ; functor_map_identity {a b c} `{Equality c} (u : b -> c) (v : a -> b) (x : f a)\n    : map (u <<< v) x == map u (map v x)\n  }.\n\nArguments map [f _ a b] (_ _%monad).\nArguments functor_identity [f _ a _] (x).\nArguments functor_map_identity [f _ a b c _] (u v x).\n\nDefinition fconst {f a b} `{Functor f} (x : a) (ft : f b) : f a :=\n  map (fun _ => x) ft.\n\nArguments fconst [f a b _] x ft%monad.\n\nNotation \"f <$> g\" := (map f g) (at level 27, left associativity) : monad_scope.\nNotation \"f <$ g\" := (fconst f g) (at level 27, left associativity) : monad_scope.\n\n#[local]\nOpen Scope monad_scope.\n\n(** * Applicative *)\n\nReserved Notation \"f <*> g\" (at level 28, left associativity).\n\nClass Applicative (f : Type -> Type) : Type :=\n  { applicative_is_functor :> Functor f\n  ; pure {a} : a -> f a\n  ; apply {a b} : f (a -> b) -> f a -> f b\n    where \"f <*> g\" := (apply f g)\n  ; applicative_identity {a} `{Equality a} (v : f a) : pure id <*> v == v\n  ; applicative_composition {a b c} `{Equality c} (u : f (b -> c)) (v : f (a -> b)) (w : f a)\n    : pure compose <*> u <*> v <*> w == u <*> (v <*> w)\n  ; applicative_homomorphism {a b} `{Equality b} (v : a -> b) (x : a)\n    : (pure v) <*> (pure x) == pure (v x)\n  ; applicative_interchange {a b} `{Equality b} (u : f (a -> b)) (y : a)\n    : u <*> (pure y) == (pure (fun z => z y)) <*> u\n  ; applicative_pure_map {a b} `{Equality b} (g : a -> b) (x : f a)\n    : g <$> x == pure g <*> x\n  }.\n\nArguments pure [f _ a] (x).\nArguments apply [f _ a b] (_%monad _%monad).\nArguments applicative_identity [f _ a _] (v).\nArguments applicative_composition [f _ a b c _] (u v w).\nArguments applicative_homomorphism [f _ a b _] (v x).\nArguments applicative_interchange [f _ a b _] (u y).\nArguments applicative_pure_map [f _ a b _] (g x).\n\nNotation \"f <*> g\" := (apply f g) (at level 28, left associativity) : monad_scope.\n\nDefinition liftA2 {f a b c} `{Applicative f} (g : a -> b -> c) (x : f a) (y : f b) : f c :=\n  apply (map g x) y.\n\nArguments liftA2 [f a b c _] (g x%monad y%monad).\n\nDefinition rseq {f a b} `{Applicative f} (x : f a) (y : f b) : f b :=\n  (id <$ x) <*> y.\n\nArguments rseq [f a b _] (x%monad y%monad).\n\nNotation \"f *> g\" := (rseq f g) (at level 28, left associativity) : monad_scope.\n\nDefinition lseq {f a b} `{Applicative f} (x : f a) (y : f b) : f a :=\n  liftA2 (fun x _ => x) x y.\n\nArguments lseq [f a b _] (x%monad y%monad).\n\nNotation \"f <* g\" := (lseq f g) (at level 28, left associativity) : monad_scope.\n\n(** * Monad *)\n\nReserved Notation \"f >>= g\" (at level 20, left associativity).\n\nClass Monad (m:  Type -> Type) :=\n  { monad_is_apply :> Applicative m\n  ; bind {a b} : m a -> (a -> m b) -> m b\n    where \"f >>= g\" := (bind f g)\n  ; bind_left_identity {a b} `{Equality b} (x : a) (f : a -> m b)\n    : pure x >>= f == f x\n  ; bind_right_identity {a} `{Equality a} (x : m a)\n    : x >>= (fun y => pure y) == x\n  ; bind_associativity {a b c} `{Equality c} (f : m a) (g : a -> m b) (h : b -> m c)\n    : (f >>= g) >>= h == f >>= (fun x => (g x) >>= h)\n  ; bind_morphism {a b} `{Equality b} (x : m a) (f f' : a -> m b)\n    : f == f' -> bind x f == bind x f'\n  ; bind_map {a b} `{Equality b} (x : m a) (f : a -> b)\n    : f <$> x == (x >>= (fun y => pure (f y)))\n  }.\n\nNotation \"f >>= g\" := (bind f g) (at level 20, left associativity) : monad_scope.\n\nArguments bind [m _ a b] (f%monad g%monad).\nArguments bind_left_identity [m _ a b _] (x f).\nArguments bind_right_identity [m _ a _] (x).\nArguments bind_associativity [m _ a b c _] (f g h).\nArguments bind_morphism [m _ a b _] (x f f').\nArguments bind_map [m _ a b _] (x f).\n\n#[local]\nOpen Scope signature_scope.\n\n#[program]\nInstance bind_Proper (m : Type -> Type) `{Monad m} (a b : Type) `{Equality b}\n  : Proper (@eq (m a) ==> @equal (a -> m b) _ ==> @equal (m b) functor_has_eq) (@bind m _ _ _).\n\nNext Obligation.\n  add_morphism_tactic.\n  intros x f g equ.\n  apply bind_morphism.\n  exact equ.\nQed.\n\nDefinition join {m a} `{Monad m} (x : m (m a)) : m a :=\n  x >>= id.\n\nArguments join [m a _] (x%monad).\n\nDefinition void {m a} `{Monad m} (x : m a) : m unit :=\n  x >>= fun _ => pure tt.\n\nArguments void [m a _] (x%monad).\n\nDefinition when {m a} `{Monad m} (cond : bool) (x : m a) : m unit :=\n  if cond then void x else pure tt.\n\nArguments when [m a _] (cond x%monad).\n\nDeclare Custom Entry monad.\n\nNotation \"'do' p 'end'\" := p (p custom monad at level 10) : prelude_scope.\n\nNotation \"p ';' q\" := (bind p%monad (fun _ => q%monad))\n  (in custom monad at level 10, q at level 10, right associativity, only parsing).\n\nNotation \"'let*' a ':=' p 'in' q\" := (bind p%monad (fun a => q%monad))\n  (in custom monad at level 0, a ident, p constr, q at level 10, right associativity, only parsing).\n\nNotation \"'let' a ':=' p 'in' q\" := (let a := p in q%monad)\n  (in custom monad at level 5, a ident, p constr, q at level 10, right associativity, only parsing).\n\nNotation \"x\" := x%monad (in custom monad at level 0, x constr at level 200, only parsing).\n\n#[local]\nDefinition test_monad_notation {m} `{Monad m}\n  (compute : nat -> m nat) (p : m unit) (q : nat -> m bool) : nat -> m bool := fun* _ => do\n    p >>= (fun _ => q 2%nat);\n    p;\n    let z := 3 in\n    let* x := id <$> compute 3 in\n    let* y := compute 4 in\n    q (x + y + z)\n  end.\n", "meta": {"author": "ANSSI-FR", "repo": "coq-prelude", "sha": "49fce426082fca3c3e429bad1be0c40f8f4ba865", "save_path": "github-repos/coq/ANSSI-FR-coq-prelude", "path": "github-repos/coq/ANSSI-FR-coq-prelude/coq-prelude-49fce426082fca3c3e429bad1be0c40f8f4ba865/theories/Control.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.29864835678334584}}
{"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(** * doTriplets\n\nPierre Letouzey & Laurent Thery\n\nPropagation as transitive closure of the one step propagation\n*)\n\nFrom Stalmarck Require Export doTriplet.\nFrom Stalmarck Require Import PolyListAux.\n\n(** Reflexive transitive closure of doTriplet *)\nInductive doTripletsP : State -> list triplet -> State -> Prop :=\n  | doTripletsRef :\n      forall (S1 S2 : State) (L : list triplet),\n      eqState S1 S2 -> doTripletsP S1 L S2\n  | doTripletsTrans :\n      forall (S1 S2 S3 : State) (L : list triplet) (t : triplet),\n      In t L ->\n      doTripletP S1 t S2 -> doTripletsP S2 L S3 -> doTripletsP S1 L S3.\n\n#[export] Hint Resolve doTripletsRef : stalmarck.\n\n(** It is compatible *)\nTheorem doTripletsComp :\n forall (S1 S2 S3 S4 : State) (L : list triplet),\n doTripletsP S1 L S2 -> eqState S3 S1 -> eqState S4 S2 -> doTripletsP S3 L S4.\nProof.\nintros S1 S2 S3 S4 L H'; generalize S3 S4; elim H'; clear H' L S1 S2 S3 S4;\n auto with stalmarck.\nintros S1 S2 L H' S3 S4 H'0 H'1.\napply doTripletsRef; auto with stalmarck.\napply eqStateTrans with (S2 := S1); auto with stalmarck.\napply eqStateTrans with (S2 := S2); auto with stalmarck.\nintros S1 S2 S3 L t H' H'0 H'1 H'2 S0 S4 H'3 H'4.\nelim (doTripletEqCompEx S1 S2 S0 t);\n [ intros S6 E; Elimc E; intros H'11 H'12 | idtac | idtac ]; \n auto with stalmarck.\napply doTripletsTrans with (S2 := S6) (t := t); auto with stalmarck.\nQed.\n\n(** Transitive *)\nTheorem doTripletsRTrans :\n forall (S1 S2 S3 : State) (L : list triplet),\n doTripletsP S1 L S2 -> doTripletsP S2 L S3 -> doTripletsP S1 L S3.\nProof.\nintros S1 S2 S3 L H'; elim H'; auto with stalmarck.\nintros S4 S5 L0 H'0 H'1.\napply doTripletsComp with (S1 := S5) (S2 := S3); auto with stalmarck.\nintros S4 S5 S0 L0 t H'0 H'1 H'2 H'3 H'4.\napply doTripletsTrans with (S2 := S5) (t := t); auto with stalmarck.\nQed.\n\n(** We only add equation *)\nTheorem doTripletsUnionEx :\n forall (S1 S2 : State) (L : list triplet),\n doTripletsP S1 L S2 -> exists S3 : State, eqState S2 (unionState S3 S1).\nProof.\nintros S1 S2 L H'; elim H'; auto with stalmarck.\nintros S3 S4 H'0 H'1; exists S3; auto with stalmarck.\napply eqStateTrans with (S2 := S3); auto with stalmarck.\nred in |- *; split; auto with stalmarck.\nintros S3 S4 S5 L0 t H'0 H'1 H'2 H'3.\nelim (doTripletUnionEx S3 S4 t); [ intros S6 E | idtac ]; auto with stalmarck.\nelim H'3; intros S7 E0.\nexists (unionState S7 S6).\napply eqStateTrans with (S2 := unionState S7 S4); auto with stalmarck.\nrewrite E; auto with stalmarck.\napply unionStateAssoc; auto with stalmarck.\nQed.\n\n(** The state always grows *)\nTheorem doTripletsIncl :\n forall (S1 S2 : State) (L : list triplet),\n doTripletsP S1 L S2 -> inclState S1 S2.\nProof.\nintros S1 S2 L H'.\nelim (doTripletsUnionEx S1 S2 L); [ intros S3 E | idtac ]; auto with stalmarck.\napply inclStateEqStateComp with (S1 := S1) (S3 := unionState S3 S1); auto with stalmarck.\nQed.\n\n(** It is a congruence *)\nTheorem doTripletCongruent :\n forall (S1 S2 S3 : State) (L : list triplet),\n doTripletsP S1 L S2 -> doTripletsP (unionState S3 S1) L (unionState S3 S2).\nProof.\nintros S1 S2 S3 L H'; Elimc H'; clear S1 S2 L; auto with stalmarck.\nintros S1 S2 S0 L t H' H'0 H'1 H'2.\napply doTripletsRTrans with (S2 := unionState S3 S2); auto with stalmarck.\nelim (doTripletCongruentEx S1 S2 S3 t);\n [ intros S4 E; Elimc E; intros H'8 H'9 | idtac ]; \n auto with stalmarck.\napply doTripletsRTrans with (S2 := S4); auto with stalmarck.\napply doTripletsTrans with (S2 := S4) (t := t); auto with stalmarck.\nQed.\n\n(** It is monotone *)\nTheorem doTripletsMonotoneEx :\n forall (S1 S2 S3 : State) (L : list triplet),\n doTripletsP S1 L S3 ->\n inclState S1 S2 -> exists S4 : State, doTripletsP S2 L S4 /\\ inclState S3 S4.\nProof.\nintros S1 S2 S3 L H' H'0.\nlapply (doTripletCongruent S1 S3 S2 L); [ intros H'5 | idtac ]; auto with stalmarck.\nexists (unionState S2 S3); split; auto with stalmarck.\napply doTripletsComp with (S1 := unionState S2 S1) (S2 := unionState S2 S3);\n auto with stalmarck.\nred in |- *; split; auto with stalmarck.\nQed.\n\n(** It is confluent *)\nTheorem doTripletsConftEx :\n forall (L : list triplet) (S1 S2 S3 : State),\n doTripletsP S1 L S2 ->\n doTripletsP S1 L S3 ->\n exists S4 : State, doTripletsP S2 L S4 /\\ doTripletsP S3 L S4.\nProof.\nintros L S1 S2 S3 H' H'0.\nelim (doTripletsUnionEx S1 S2 L); [ intros S4 E | idtac ]; auto with stalmarck.\nelim (doTripletsUnionEx S1 S3 L); [ intros S5 E0 | idtac ]; auto with stalmarck.\nexists (unionState S5 S2); split; auto with stalmarck.\napply doTripletsComp with (S1 := unionState S4 S1) (S2 := unionState S4 S3);\n auto with stalmarck.\napply doTripletCongruent; auto with stalmarck.\napply eqStateTrans with (S2 := unionState S5 (unionState S4 S1)); auto with stalmarck.\napply eqStateTrans with (S2 := unionState (unionState S5 S4) S1); auto with stalmarck.\napply unionStateAssoc; auto with stalmarck.\napply eqStateTrans with (S2 := unionState (unionState S4 S5) S1); auto with stalmarck.\napply eqStateTrans with (S2 := unionState S4 (unionState S5 S1)); auto with stalmarck.\napply eqStateTrans with (S2 := unionState (unionState S4 S5) S1); auto with stalmarck.\napply eqStateSym; auto with stalmarck.\napply unionStateAssoc; auto with stalmarck.\napply doTripletsComp with (S1 := unionState S5 S1) (S2 := unionState S5 S2);\n auto with stalmarck.\napply doTripletCongruent; auto with stalmarck.\nQed.\n\n(** We don't lose realizability of memories if the triplets are realized *)\nTheorem doTripletsRealizeStateEval :\n forall (f : rNat -> bool) (S1 S2 : State) (L : list triplet),\n realizeState f S1 ->\n doTripletsP S1 L S2 ->\n realizeTriplets f L -> f zero = true -> realizeState f S2.\nProof.\nintros f S1 S2 L H' H'0; generalize H'; elim H'0; auto with stalmarck.\nintros S3 S4 L0 H'1 H'2 H'3 H'4.\napply realizeStateIncl with (S1 := S3); auto with stalmarck; inversion H'1; auto with stalmarck.\nintros S3 S4 S5 L0 t H'1 H'2 H'3 H'4 H'5 H'6 H'7.\napply H'4; auto with stalmarck.\napply realizeStateEval with (2 := H'2); auto with stalmarck.\nQed.\n\nTheorem doTripletsTermExAux :\n forall (L : list triplet) (S1 S2 : State),\n doTripletsP S1 L S2 ->\n forall t : triplet,\n In t L ->\n doTripletsP S1 (rem _ tripletDec t L) S2 \\/\n (exists S3 : State,\n    (exists S4 : State,\n       doTripletsP S1 (rem _ tripletDec t L) S3 /\\\n       doTripletP S3 t S4 /\\ doTripletsP S4 (rem _ tripletDec t L) S2)).\nProof.\nintros L S1 S2 H'; Elimc H'; clear L S1 S2; auto with stalmarck.\nintros S1 S2 S3 L t H' H'0 H'1 H'2 t0 H'3.\ncase (tripletDec t t0); intros H.\nelim (H'2 t);\n [ intros H'6\n | intros H'6; Elimc H'6; intros S0 E; Elimc E; intros S4 E; Elimc E;\n    intros H'6 H'7; Elimc H'7; intros H'7 H'8\n | idtac ]; auto with stalmarck.\nright; exists S1; exists S2; split; auto with stalmarck; split; auto with stalmarck.\nrewrite <- H; auto with stalmarck.\nrewrite <- H; auto with stalmarck.\nright; exists S1; exists S2; split; auto with stalmarck; split; auto with stalmarck.\nrewrite <- H; auto with stalmarck.\napply doTripletsRTrans with (S2 := S0); auto with stalmarck.\nrewrite <- H; auto with stalmarck.\napply doTripletsComp with (S1 := S4) (S2 := S3); auto with stalmarck.\nrewrite <- H; auto with stalmarck.\napply doTripletInvol with (t := t) (S1 := S1) (S2 := S2); auto with stalmarck.\napply doTripletsIncl with (L := rem triplet tripletDec t L); auto with stalmarck.\nelim (H'2 t0);\n [ intros H'6\n | intros H'6; Elimc H'6; intros S0 E; Elimc E; intros S4 E; Elimc E;\n    intros H'6 H'7; Elimc H'7; intros H'7 H'8\n | idtac ]; auto with stalmarck.\nleft.\napply doTripletsTrans with (S2 := S2) (t := t); auto with stalmarck.\nright; exists S0; exists S4; split; [ idtac | split ]; auto with stalmarck.\napply doTripletsTrans with (S2 := S2) (t := t); auto with stalmarck.\nQed.\n\n(** Once we have used  a triplet we can do without *)\nTheorem doTripletsTermEx :\n forall (L : list triplet) (S1 S2 : State),\n doTripletsP S1 L S2 ->\n eqState S1 S2 \\/\n (exists t : triplet,\n    (exists S3 : State,\n       In t L /\\\n       doTripletP S1 t S3 /\\ doTripletsP S3 (rem _ tripletDec t L) S2)).\nProof.\nintros L S1 S2 H'; inversion H'; auto with stalmarck.\nright; exists t; exists S3; split; try split; auto with stalmarck.\nlapply (doTripletsTermExAux L S3 S2);\n [ intros H'3; elim (H'3 t);\n    [ intros H'6\n    | intros H'6; Elimc H'6; intros S5 E; Elimc E; intros S6 E; Elimc E;\n       intros H'6 H'7; Elimc H'7; intros H'7 H'8\n    | idtac ]\n | idtac ]; auto with stalmarck.\napply doTripletsRTrans with (S2 := S5); auto with stalmarck.\napply doTripletsComp with (S1 := S6) (S2 := S2); auto with stalmarck.\napply doTripletInvol with (t := t) (S1 := S1) (S2 := S3); auto with stalmarck.\napply doTripletsIncl with (L := rem triplet tripletDec t L); auto with stalmarck.\nQed.\n\n(** The more we have triplets the more we can do *)\nTheorem doTripletsInclList :\n forall (L1 L2 : list triplet) (S1 S2 : State),\n incl L1 L2 -> doTripletsP S1 L1 S2 -> doTripletsP S1 L2 S2.\nProof.\nintros L1 L2 S1 S2 H' H'0; generalize L2 H'; elim H'0; clear H'0 H' L2; auto with stalmarck.\nintros S3 S4 S5 L0 t H' H'0 H'1 H'2 L2 H'3.\napply doTripletsTrans with (S2 := S4) (t := t); auto with datatypes stalmarck.\nQed.\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/doTriplets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.2986483567833458}}
{"text": "From stdpp Require Export sets gmultiset countable.\nFrom iris.algebra Require Export cmra.\nFrom iris.algebra Require Import updates local_updates big_op.\nFrom iris.prelude Require Import options.\n\n(* The multiset union CMRA *)\nSection gmultiset.\n  Context `{Countable K}.\n  Implicit Types X Y : gmultiset K.\n\n  Canonical Structure gmultisetO := discreteO (gmultiset K).\n\n  Local Instance gmultiset_valid_instance : Valid (gmultiset K) := λ _, True.\n  Local Instance gmultiset_validN_instance : ValidN (gmultiset K) := λ _ _, True.\n  Local Instance gmultiset_unit_instance : Unit (gmultiset K) := (∅ : gmultiset K).\n  Local Instance gmultiset_op_instance : Op (gmultiset K) := disj_union.\n  Local Instance gmultiset_pcore_instance : PCore (gmultiset K) := λ X, Some ∅.\n\n  Lemma gmultiset_op X Y : X ⋅ Y = X ⊎ Y.\n  Proof. done. Qed.\n  Lemma gmultiset_core X : core X = ∅.\n  Proof. done. Qed.\n  Lemma gmultiset_included X Y : X ≼ Y ↔ X ⊆ Y.\n  Proof.\n    split.\n    - intros [Z ->%leibniz_equiv].\n      rewrite gmultiset_op. apply gmultiset_disj_union_subseteq_l.\n    - intros ->%gmultiset_disj_union_difference. by exists (Y ∖ X).\n  Qed.\n\n  Lemma gmultiset_ra_mixin : RAMixin (gmultiset K).\n  Proof.\n    apply ra_total_mixin; eauto.\n    - by intros X Y Z ->%leibniz_equiv.\n    - by intros X Y ->%leibniz_equiv.\n    - solve_proper.\n    - intros X1 X2 X3. by rewrite !gmultiset_op assoc_L.\n    - intros X1 X2. by rewrite !gmultiset_op comm_L.\n    - intros X. by rewrite gmultiset_core left_id.\n    - intros X1 X2 HX. rewrite !gmultiset_core. exists ∅.\n      by rewrite left_id.\n  Qed.\n\n  Canonical Structure gmultisetR := discreteR (gmultiset K) gmultiset_ra_mixin.\n\n  Global Instance gmultiset_cmra_discrete : CmraDiscrete gmultisetR.\n  Proof. apply discrete_cmra_discrete. Qed.\n\n  Lemma gmultiset_ucmra_mixin : UcmraMixin (gmultiset K).\n  Proof.\n    split; [done | | done]. intros X.\n    by rewrite gmultiset_op left_id_L.\n  Qed.\n  Canonical Structure gmultisetUR := Ucmra (gmultiset K) gmultiset_ucmra_mixin.\n\n  Global Instance gmultiset_cancelable X : Cancelable X.\n  Proof.\n    apply: discrete_cancelable=> Y Z _ ?. fold_leibniz. by apply (inj (X ⊎.)).\n  Qed.\n\n  Lemma gmultiset_opM X mY : X ⋅? mY = X ⊎ default ∅ mY.\n  Proof. destruct mY; by rewrite /= ?right_id_L. Qed.\n\n  Lemma gmultiset_update X Y : X ~~> Y.\n  Proof. done. Qed.\n\n  Lemma gmultiset_local_update X Y X' Y' : X ⊎ Y' = X' ⊎ Y → (X,Y) ~l~> (X', Y').\n  Proof.\n    intros HXY. rewrite local_update_unital_discrete=> Z' _. intros ->%leibniz_equiv.\n    split; first done. apply leibniz_equiv_iff, (inj (.⊎ Y)).\n    rewrite -HXY !gmultiset_op.\n    by rewrite -(comm_L _ Y) (comm_L _ Y') assoc_L.\n  Qed.\n\n  Lemma gmultiset_local_update_alloc X Y X' : (X,Y) ~l~> (X ⊎ X', Y ⊎ X').\n  Proof. apply gmultiset_local_update. by rewrite (comm_L _ Y) assoc_L. Qed.\n\n  Lemma gmultiset_local_update_dealloc X Y X' :\n    X' ⊆ Y → (X,Y) ~l~> (X ∖ X', Y ∖ X').\n  Proof.\n    intros ->%gmultiset_disj_union_difference. apply local_update_total_valid.\n    intros _ _ ->%gmultiset_included%gmultiset_disj_union_difference.\n    apply gmultiset_local_update. apply gmultiset_eq=> x.\n    repeat (rewrite multiplicity_difference || rewrite multiplicity_disj_union).\n    lia.\n  Qed.\n\n  Lemma big_opMS_singletons X :\n    ([^op mset] x ∈ X, {[+ x +]}) = X.\n  Proof.\n    induction X as [|x X IH] using gmultiset_ind.\n    - rewrite big_opMS_empty. done.\n    - unfold_leibniz. rewrite big_opMS_disj_union // big_opMS_singleton IH //.\n  Qed.\n\nEnd gmultiset.\n\nGlobal Arguments gmultisetO _ {_ _}.\nGlobal Arguments gmultisetR _ {_ _}.\nGlobal Arguments gmultisetUR _ {_ _}.\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/gmultiset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982315512488, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.29864585435397056}}
{"text": "(* generated by Ott 0.27, locally-nameless lngen from: DOT.ott *)\nRequire Import Metalib.Metatheory.\n(** syntax *)\nDefinition termvar := var.\nDefinition trmlabel := atom.\nDefinition typlabel := atom.\n\nInductive varref : Set := \n | var_termvar_b (_:nat)\n | var_termvar_f (x:termvar).\n\nInductive typ : Set := \n | typ_all (T1:typ) (T2:typ)\n | typ_bnd (T:typ)\n | typ_dec (dec5:dec)\n | typ_sel (v:varref) (A:typlabel)\n | typ_and (T1:typ) (T2:typ)\n | typ_top : typ\n | typ_bot : typ\nwith dec : Set := \n | dec_trm (a:trmlabel) (T:typ)\n | dec_typ (A:typlabel) (T1:typ) (T2:typ).\n\nInductive trm : Set := \n | trm_var (v:varref)\n | trm_val (val5:val)\n | trm_sel (v:varref) (a:trmlabel)\n | trm_app (v1:varref) (v2:varref)\n | trm_let (t1:trm) (t2:trm)\nwith val : Set := \n | val_new (T:typ) (defs5:defs)\n | val_lambda (T:typ) (t:trm)\nwith defs : Set := \n | defs_nil : defs\n | defs_cons (d:def) (defs5:defs)\nwith def : Set := \n | def_trm (a:trmlabel) (t:trm)\n | def_typ (A:typlabel) (T:typ).\n\nDefinition ctx : Set := list (atom*typ).\n\nDefinition stack : Set := list (atom*trm).\n\n(* EXPERIMENTAL *)\n(** auxiliary functions on the new list types *)\n(** library functions *)\n(** subrules *)\n(** arities *)\n(** opening up abstractions *)\nDefinition open_varref_wrt_varref_rec (k:nat) (v5:varref) (v_6:varref) : varref :=\n  match v_6 with\n  | (var_termvar_b nat) => \n      match lt_eq_lt_dec nat k with\n        | inleft (left _) => var_termvar_b nat\n        | inleft (right _) => v5\n        | inright _ => var_termvar_b (nat - 1)\n      end\n  | (var_termvar_f x) => var_termvar_f x\nend.\n\nFixpoint open_dec_wrt_varref_rec (k:nat) (v5:varref) (dec5:dec) : dec :=\n  match dec5 with\n  | (dec_trm a T) => dec_trm a (open_typ_wrt_varref_rec k v5 T)\n  | (dec_typ A T1 T2) => dec_typ A (open_typ_wrt_varref_rec k v5 T1) (open_typ_wrt_varref_rec k v5 T2)\nend\nwith open_typ_wrt_varref_rec (k:nat) (v5:varref) (T_5:typ) {struct T_5}: typ :=\n  match T_5 with\n  | (typ_all T1 T2) => typ_all (open_typ_wrt_varref_rec k v5 T1) (open_typ_wrt_varref_rec (S k) v5 T2)\n  | (typ_bnd T) => typ_bnd (open_typ_wrt_varref_rec (S k) v5 T)\n  | (typ_dec dec5) => typ_dec (open_dec_wrt_varref_rec k v5 dec5)\n  | (typ_sel v A) => typ_sel (open_varref_wrt_varref_rec k v5 v) A\n  | (typ_and T1 T2) => typ_and (open_typ_wrt_varref_rec k v5 T1) (open_typ_wrt_varref_rec k v5 T2)\n  | typ_top => typ_top \n  | typ_bot => typ_bot \nend.\n\nFixpoint open_def_wrt_varref_rec (k:nat) (v5:varref) (d5:def) : def :=\n  match d5 with\n  | (def_trm a t) => def_trm a (open_trm_wrt_varref_rec k v5 t)\n  | (def_typ A T) => def_typ A (open_typ_wrt_varref_rec k v5 T)\nend\nwith open_defs_wrt_varref_rec (k:nat) (v5:varref) (defs_6:defs) {struct defs_6}: defs :=\n  match defs_6 with\n  | defs_nil => defs_nil \n  | (defs_cons d defs5) => defs_cons (open_def_wrt_varref_rec k v5 d) (open_defs_wrt_varref_rec k v5 defs5)\nend\nwith open_val_wrt_varref_rec (k:nat) (v5:varref) (val5:val) : val :=\n  match val5 with\n  | (val_new T defs5) => val_new (open_typ_wrt_varref_rec k v5 T) (open_defs_wrt_varref_rec (S k) v5 defs5)\n  | (val_lambda T t) => val_lambda (open_typ_wrt_varref_rec k v5 T) (open_trm_wrt_varref_rec (S k) v5 t)\nend\nwith open_trm_wrt_varref_rec (k:nat) (v_5:varref) (t_5:trm) {struct t_5}: trm :=\n  match t_5 with\n  | (trm_var v) => trm_var (open_varref_wrt_varref_rec k v_5 v)\n  | (trm_val val5) => trm_val (open_val_wrt_varref_rec k v_5 val5)\n  | (trm_sel v a) => trm_sel (open_varref_wrt_varref_rec k v_5 v) a\n  | (trm_app v1 v2) => trm_app (open_varref_wrt_varref_rec k v_5 v1) (open_varref_wrt_varref_rec k v_5 v2)\n  | (trm_let t1 t2) => trm_let (open_trm_wrt_varref_rec k v_5 t1) (open_trm_wrt_varref_rec (S k) v_5 t2)\nend.\n\nDefinition open_def_wrt_varref v5 d5 := open_def_wrt_varref_rec 0 d5 v5.\n\nDefinition open_val_wrt_varref v5 val5 := open_val_wrt_varref_rec 0 val5 v5.\n\nDefinition open_defs_wrt_varref v5 defs_6 := open_defs_wrt_varref_rec 0 defs_6 v5.\n\nDefinition open_dec_wrt_varref v5 dec5 := open_dec_wrt_varref_rec 0 dec5 v5.\n\nDefinition open_varref_wrt_varref v5 v_6 := open_varref_wrt_varref_rec 0 v_6 v5.\n\nDefinition open_typ_wrt_varref v5 T_5 := open_typ_wrt_varref_rec 0 T_5 v5.\n\nDefinition open_trm_wrt_varref v_5 t_5 := open_trm_wrt_varref_rec 0 t_5 v_5.\n\n(** terms are locally-closed pre-terms *)\n(** definitions *)\n\n(* defns LC_varref *)\nInductive lc_varref : varref -> Prop :=    (* defn lc_varref *)\n | lc_var_termvar_f : forall (x:termvar),\n     (lc_varref (var_termvar_f x)).\n\n(* defns LC_dec_typ *)\nInductive lc_dec : dec -> Prop :=    (* defn lc_dec *)\n | lc_dec_trm : forall (a:trmlabel) (T:typ),\n     (lc_typ T) ->\n     (lc_dec (dec_trm a T))\n | lc_dec_typ : forall (A:typlabel) (T1 T2:typ),\n     (lc_typ T1) ->\n     (lc_typ T2) ->\n     (lc_dec (dec_typ A T1 T2))\nwith lc_typ : typ -> Prop :=    (* defn lc_typ *)\n | lc_typ_all : forall (T1 T2:typ),\n     (lc_typ T1) ->\n      ( forall x , lc_typ  ( open_typ_wrt_varref T2 (var_termvar_f x) )  )  ->\n     (lc_typ (typ_all T1 T2))\n | lc_typ_bnd : forall (T:typ),\n      ( forall x , lc_typ  ( open_typ_wrt_varref T (var_termvar_f x) )  )  ->\n     (lc_typ (typ_bnd T))\n | lc_typ_dec : forall (dec5:dec),\n     (lc_dec dec5) ->\n     (lc_typ (typ_dec dec5))\n | lc_typ_sel : forall (v:varref) (A:typlabel),\n     (lc_varref v) ->\n     (lc_typ (typ_sel v A))\n | lc_typ_and : forall (T1 T2:typ),\n     (lc_typ T1) ->\n     (lc_typ T2) ->\n     (lc_typ (typ_and T1 T2))\n | lc_typ_top : \n     (lc_typ typ_top)\n | lc_typ_bot : \n     (lc_typ typ_bot).\n\n(* defns LC_def_defs_val_trm *)\nInductive lc_def : def -> Prop :=    (* defn lc_def *)\n | lc_def_trm : forall (a:trmlabel) (t:trm),\n     (lc_trm t) ->\n     (lc_def (def_trm a t))\n | lc_def_typ : forall (A:typlabel) (T:typ),\n     (lc_typ T) ->\n     (lc_def (def_typ A T))\nwith lc_defs : defs -> Prop :=    (* defn lc_defs *)\n | lc_defs_nil : \n     (lc_defs defs_nil)\n | lc_defs_cons : forall (d:def) (defs5:defs),\n     (lc_def d) ->\n     (lc_defs defs5) ->\n     (lc_defs (defs_cons d defs5))\nwith lc_val : val -> Prop :=    (* defn lc_val *)\n | lc_val_new : forall (T:typ) (defs5:defs),\n     (lc_typ T) ->\n      ( forall x , lc_defs  ( open_defs_wrt_varref defs5 (var_termvar_f x) )  )  ->\n     (lc_val (val_new T defs5))\n | lc_val_lambda : forall (T:typ) (t:trm),\n     (lc_typ T) ->\n      ( forall x , lc_trm  ( open_trm_wrt_varref t (var_termvar_f x) )  )  ->\n     (lc_val (val_lambda T t))\nwith lc_trm : trm -> Prop :=    (* defn lc_trm *)\n | lc_trm_var : forall (v:varref),\n     (lc_varref v) ->\n     (lc_trm (trm_var v))\n | lc_trm_val : forall (val5:val),\n     (lc_val val5) ->\n     (lc_trm (trm_val val5))\n | lc_trm_sel : forall (v:varref) (a:trmlabel),\n     (lc_varref v) ->\n     (lc_trm (trm_sel v a))\n | lc_trm_app : forall (v1 v2:varref),\n     (lc_varref v1) ->\n     (lc_varref v2) ->\n     (lc_trm (trm_app v1 v2))\n | lc_trm_let : forall (t1 t2:trm),\n     (lc_trm t1) ->\n      ( forall x , lc_trm  ( open_trm_wrt_varref t2 (var_termvar_f x) )  )  ->\n     (lc_trm (trm_let t1 t2)).\n(** free variables *)\nDefinition fv_varref (v5:varref) : vars :=\n  match v5 with\n  | (var_termvar_b nat) => {}\n  | (var_termvar_f x) => {{x}}\nend.\n\nFixpoint fv_dec (dec5:dec) : vars :=\n  match dec5 with\n  | (dec_trm a T) => (fv_typ T)\n  | (dec_typ A T1 T2) => (fv_typ T1) \\u (fv_typ T2)\nend\nwith fv_typ (T_5:typ) : vars :=\n  match T_5 with\n  | (typ_all T1 T2) => (fv_typ T1) \\u (fv_typ T2)\n  | (typ_bnd T) => (fv_typ T)\n  | (typ_dec dec5) => (fv_dec dec5)\n  | (typ_sel v A) => (fv_varref v)\n  | (typ_and T1 T2) => (fv_typ T1) \\u (fv_typ T2)\n  | typ_top => {}\n  | typ_bot => {}\nend.\n\nFixpoint fv_def (d5:def) : vars :=\n  match d5 with\n  | (def_trm a t) => (fv_trm t)\n  | (def_typ A T) => (fv_typ T)\nend\nwith fv_defs (defs_6:defs) : vars :=\n  match defs_6 with\n  | defs_nil => {}\n  | (defs_cons d defs5) => (fv_def d) \\u (fv_defs defs5)\nend\nwith fv_val (val5:val) : vars :=\n  match val5 with\n  | (val_new T defs5) => (fv_typ T) \\u (fv_defs defs5)\n  | (val_lambda T t) => (fv_typ T) \\u (fv_trm t)\nend\nwith fv_trm (t_5:trm) : vars :=\n  match t_5 with\n  | (trm_var v) => (fv_varref v)\n  | (trm_val val5) => (fv_val val5)\n  | (trm_sel v a) => (fv_varref v)\n  | (trm_app v1 v2) => (fv_varref v1) \\u (fv_varref v2)\n  | (trm_let t1 t2) => (fv_trm t1) \\u (fv_trm t2)\nend.\n\n(** substitutions *)\nDefinition subst_varref (v5:varref) (x5:termvar) (v_6:varref) : varref :=\n  match v_6 with\n  | (var_termvar_b nat) => var_termvar_b nat\n  | (var_termvar_f x) => (if eq_var x x5 then v5 else (var_termvar_f x))\nend.\n\nFixpoint subst_dec (v5:varref) (x5:termvar) (dec5:dec) {struct dec5} : dec :=\n  match dec5 with\n  | (dec_trm a T) => dec_trm a (subst_typ v5 x5 T)\n  | (dec_typ A T1 T2) => dec_typ A (subst_typ v5 x5 T1) (subst_typ v5 x5 T2)\nend\nwith subst_typ (v5:varref) (x5:termvar) (T_5:typ) {struct T_5} : typ :=\n  match T_5 with\n  | (typ_all T1 T2) => typ_all (subst_typ v5 x5 T1) (subst_typ v5 x5 T2)\n  | (typ_bnd T) => typ_bnd (subst_typ v5 x5 T)\n  | (typ_dec dec5) => typ_dec (subst_dec v5 x5 dec5)\n  | (typ_sel v A) => typ_sel (subst_varref v5 x5 v) A\n  | (typ_and T1 T2) => typ_and (subst_typ v5 x5 T1) (subst_typ v5 x5 T2)\n  | typ_top => typ_top \n  | typ_bot => typ_bot \nend.\n\nFixpoint subst_def (v5:varref) (x5:termvar) (d5:def) {struct d5} : def :=\n  match d5 with\n  | (def_trm a t) => def_trm a (subst_trm v5 x5 t)\n  | (def_typ A T) => def_typ A (subst_typ v5 x5 T)\nend\nwith subst_defs (v5:varref) (x5:termvar) (defs_6:defs) {struct defs_6} : defs :=\n  match defs_6 with\n  | defs_nil => defs_nil \n  | (defs_cons d defs5) => defs_cons (subst_def v5 x5 d) (subst_defs v5 x5 defs5)\nend\nwith subst_val (v5:varref) (x5:termvar) (val5:val) {struct val5} : val :=\n  match val5 with\n  | (val_new T defs5) => val_new (subst_typ v5 x5 T) (subst_defs v5 x5 defs5)\n  | (val_lambda T t) => val_lambda (subst_typ v5 x5 T) (subst_trm v5 x5 t)\nend\nwith subst_trm (v_5:varref) (x5:termvar) (t_5:trm) {struct t_5} : trm :=\n  match t_5 with\n  | (trm_var v) => trm_var (subst_varref v_5 x5 v)\n  | (trm_val val5) => trm_val (subst_val v_5 x5 val5)\n  | (trm_sel v a) => trm_sel (subst_varref v_5 x5 v) a\n  | (trm_app v1 v2) => trm_app (subst_varref v_5 x5 v1) (subst_varref v_5 x5 v2)\n  | (trm_let t1 t2) => trm_let (subst_trm v_5 x5 t1) (subst_trm v_5 x5 t2)\nend.\n\n\nFixpoint defs_has (ds: defs) (d: def) : Prop :=\n  match ds with\n  | defs_nil => False\n  | defs_cons d' ds' =>\n      d' = d \\/ defs_has ds' d\n  end.\n\nFixpoint type_labels (T: typ) : atoms :=\n  match T with\n  | typ_dec (dec_trm a _) => singleton a\n  | typ_dec (dec_typ A _ _) => singleton A\n  | typ_and T1 T2 => type_labels T1 \\u type_labels T2\n  | _ => empty\n  end.\n\n\n(** definitions *)\n\n(* defns Typing *)\nInductive ty_trm : ctx -> trm -> typ -> Prop :=    (* defn ty_trm *)\n | ty_var : forall (G:ctx) (x:termvar) (T:typ),\n      (binds ( x ) ( T ) ( G ))  ->\n     ty_trm G (trm_var (var_termvar_f x)) T\n | ty_all_intro : forall (L:vars) (G:ctx) (T1:typ) (t:trm) (T2:typ),\n      ( forall x , x \\notin  L  -> ty_trm  ( x ~ T1  ++  G )   ( open_trm_wrt_varref t (var_termvar_f x) )   ( open_typ_wrt_varref T2 (var_termvar_f x) )  )  ->\n     ty_trm G (trm_val (val_lambda T1 t)) (typ_all T1 T2)\n | ty_all_elim : forall (G:ctx) (x y:termvar) (T2 T1:typ),\n     ty_trm G (trm_var (var_termvar_f x)) (typ_all T1 T2) ->\n     ty_trm G (trm_var (var_termvar_f y)) T1 ->\n     ty_trm G (trm_app (var_termvar_f x) (var_termvar_f y))  (open_typ_wrt_varref  T2   (var_termvar_f y) ) \n | ty_new_intro : forall (L:vars) (G:ctx) (T:typ) (defs5:defs),\n      ( forall x , x \\notin  L  -> ty_defs  ( x ~  ( open_typ_wrt_varref T (var_termvar_f x) )   ++  G )   ( open_defs_wrt_varref defs5 (var_termvar_f x) )   ( open_typ_wrt_varref T (var_termvar_f x) )  )  ->\n      ( forall x , x \\notin  L  -> ty_trm G (trm_val (val_new  ( open_typ_wrt_varref T (var_termvar_f x) )  defs5)) (typ_bnd T) ) \n | ty_new_elim : forall (G:ctx) (x:termvar) (a:trmlabel) (T:typ),\n     ty_trm G (trm_var (var_termvar_f x)) (typ_dec (dec_trm a T)) ->\n     ty_trm G (trm_sel (var_termvar_f x) a) T\n | ty_let : forall (L:vars) (G:ctx) (t1 t2:trm) (T2 T1:typ),\n     ty_trm G t1 T1 ->\n      ( forall x , x \\notin  L  -> ty_trm  ( x ~ T1  ++  G )   ( open_trm_wrt_varref t2 (var_termvar_f x) )  T2 )  ->\n     ty_trm G (trm_let t1 t2) T2\n | ty_rec_intro : forall (L:vars) (G:ctx) (x:termvar) (T:typ),\n      ( forall z , z \\notin  L  -> ty_trm G (trm_var (var_termvar_f x))  ( open_typ_wrt_varref T (var_termvar_f z) )  )  ->\n     ty_trm G (trm_var (var_termvar_f x)) (typ_bnd T)\n | ty_rec_elim : forall (G:ctx) (x:termvar) (T:typ),\n     ty_trm G (trm_var (var_termvar_f x)) (typ_bnd T) ->\n     ty_trm G (trm_var (var_termvar_f x))  (open_typ_wrt_varref  T   (var_termvar_f x) ) \n | ty_and_intro : forall (G:ctx) (x:termvar) (T1 T2:typ),\n     ty_trm G (trm_var (var_termvar_f x)) T1 ->\n     ty_trm G (trm_var (var_termvar_f x)) T2 ->\n     ty_trm G (trm_var (var_termvar_f x)) (typ_and T1 T2)\n | ty_sub : forall (G:ctx) (t:trm) (T2 T1:typ),\n     ty_trm G t T1 ->\n     subtyp G T1 T2 ->\n     ty_trm G t T2\nwith ty_def : ctx -> def -> typ -> Prop :=    (* defn ty_def *)\n | ty_def_trm : forall (G:ctx) (a:trmlabel) (t:trm) (T:typ),\n     ty_trm G t T ->\n     ty_def G (def_trm a t) (typ_dec (dec_trm a T))\n | ty_def_typ : forall (G:ctx) (A:typlabel) (T:typ),\n     lc_typ T ->\n     ty_def G (def_typ A T) (typ_dec (dec_typ A T T))\nwith ty_defs : ctx -> defs -> typ -> Prop :=    (* defn ty_defs *)\n | ty_defs_one : forall (G:ctx) (d:def) (T:typ),\n     ty_def G d T ->\n     ty_defs G (defs_cons d defs_nil) T\n | ty_defs_cons : forall (G:ctx) (d:def) (defs5:defs) (T1 T2:typ),\n     ty_def G d T1 ->\n     ty_defs G defs5 T2 ->\n     ty_defs G (defs_cons d defs5) (typ_and T1 T2)\nwith subtyp : ctx -> typ -> typ -> Prop :=    (* defn subtyp *)\n | subtyp_top : forall (G:ctx) (T:typ),\n     lc_typ T ->\n     subtyp G T typ_top\n | subtyp_bot : forall (G:ctx) (T:typ),\n     lc_typ T ->\n     subtyp G typ_bot T\n | subtyp_refl : forall (G:ctx) (T:typ),\n     lc_typ T ->\n     subtyp G T T\n | subtyp_trans : forall (G:ctx) (T1 T3 T2:typ),\n     subtyp G T1 T2 ->\n     subtyp G T2 T3 ->\n     subtyp G T1 T3\n | subtyp_and11 : forall (G:ctx) (T1 T2:typ),\n     lc_typ T2 ->\n     lc_typ T1 ->\n     subtyp G (typ_and T1 T2) T1\n | subtyp_and12 : forall (G:ctx) (T1 T2:typ),\n     lc_typ T1 ->\n     lc_typ T2 ->\n     subtyp G (typ_and T1 T2) T2\n | subtyp_and2 : forall (G:ctx) (T1 T2 T3:typ),\n     subtyp G T1 T2 ->\n     subtyp G T1 T3 ->\n     subtyp G T1 (typ_and T2 T3)\n | subtyp_fld : forall (G:ctx) (a:trmlabel) (T1 T2:typ),\n     subtyp G T1 T2 ->\n     subtyp G (typ_dec (dec_trm a T1)) (typ_dec (dec_trm a T2))\n | subtyp_typ : forall (G:ctx) (A:typlabel) (T2 T3 T1 T4:typ),\n     subtyp G T1 T2 ->\n     subtyp G T3 T4 ->\n     subtyp G (typ_dec (dec_typ A T2 T3)) (typ_dec (dec_typ A T1 T4))\n | subtyp_sel1 : forall (G:ctx) (x:termvar) (A:typlabel) (T2 T1:typ),\n     ty_trm G (trm_var (var_termvar_f x)) (typ_dec (dec_typ A T1 T2)) ->\n     subtyp G (typ_sel (var_termvar_f x) A) T2\n | subtyp_sel2 : forall (G:ctx) (T1:typ) (x:termvar) (A:typlabel) (T2:typ),\n     ty_trm G (trm_var (var_termvar_f x)) (typ_dec (dec_typ A T1 T2)) ->\n     subtyp G T1 (typ_sel (var_termvar_f x) A)\n | subtyp_all : forall (L:vars) (G:ctx) (T1 T2 T3 T4:typ),\n     subtyp G T3 T1 ->\n      ( forall x , x \\notin  L  -> subtyp  ( x ~ T1  ++  G )   ( open_typ_wrt_varref T2 (var_termvar_f x) )   ( open_typ_wrt_varref T4 (var_termvar_f x) )  )  ->\n     subtyp G (typ_all T1 T2) (typ_all T3 T4).\n\n(* defns Inert *)\nInductive record_type : typ -> Prop :=    (* defn record_type *)\n | rt_one_trm : forall (a:trmlabel) (T:typ),\n     lc_typ T ->\n     record_type (typ_dec (dec_trm a T))\n | rt_one_typ : forall (A:typlabel) (T:typ),\n     lc_typ T ->\n     record_type (typ_dec (dec_typ A T T))\n | rt_and_trm : forall (T1:typ) (a:trmlabel) (T2:typ),\n     lc_typ T2 ->\n     record_type T1 ->\n      ( a  \\notin type_labels  T1 )  ->\n     record_type (typ_and T1 (typ_dec (dec_trm a T2)))\n | rt_and_typ : forall (T1:typ) (A:typlabel) (T2:typ),\n     lc_typ T2 ->\n     record_type T1 ->\n      ( A  \\notin type_labels  T1 )  ->\n     record_type (typ_and T1 (typ_dec (dec_typ A T2 T2)))\nwith inert_typ : typ -> Prop :=    (* defn inert_typ *)\n | inert_typ_all : forall (T1 T2:typ),\n     lc_typ T1 ->\n     lc_typ (typ_all T1 T2) ->\n     inert_typ (typ_all T1 T2)\n | inert_typ_bnd : forall (L:vars) (T:typ),\n      ( forall x , x \\notin  L  -> record_type  ( open_typ_wrt_varref T (var_termvar_f x) )  )  ->\n     inert_typ (typ_bnd T)\nwith inert_ctx : ctx -> Prop :=    (* defn inert_ctx *)\n | inert_empty : \n     inert_ctx  nil \n | inert_all : forall (G:ctx) (x:termvar) (T:typ),\n     inert_ctx G ->\n     inert_typ T ->\n      ( x  \\notin dom  G )  ->\n     inert_ctx  ( x ~ T  ++  G ) .\n\n(* defns PreciseTyping *)\nInductive ty_val_p : ctx -> val -> typ -> Prop :=    (* defn ty_val_p *)\n | ty_all_intro_p : forall (L:vars) (G:ctx) (T1:typ) (t:trm) (T2:typ),\n      ( forall x , x \\notin  L  -> ty_trm  ( x ~ T1  ++  G )   ( open_trm_wrt_varref t (var_termvar_f x) )   ( open_typ_wrt_varref T2 (var_termvar_f x) )  )  ->\n     ty_val_p G (val_lambda T1 t) (typ_all T1 T2)\n | ty_new_intro_p : forall (L:vars) (G:ctx) (T:typ) (defs5:defs),\n      ( forall x , x \\notin  L  -> ty_defs  ( x ~  ( open_typ_wrt_varref T (var_termvar_f x) )   ++  G )   ( open_defs_wrt_varref defs5 (var_termvar_f x) )   ( open_typ_wrt_varref T (var_termvar_f x) )  )  ->\n      ( forall x , x \\notin  L  -> ty_val_p G (val_new  ( open_typ_wrt_varref T (var_termvar_f x) )  defs5) (typ_bnd T) ) \nwith precise_flow : ctx -> termvar -> typ -> typ -> Prop :=    (* defn precise_flow *)\n | pf_bind : forall (G:ctx) (x:termvar) (T:typ),\n      (binds ( x ) ( T ) ( G ))  ->\n     precise_flow G x T T\n | pf_open : forall (G:ctx) (x:termvar) (T1 T2:typ),\n     precise_flow G x T1 (typ_bnd T2) ->\n     precise_flow G x T1  (open_typ_wrt_varref  T2   (var_termvar_f x) ) \n | pf_and1 : forall (G:ctx) (x:termvar) (T1 T2 T3:typ),\n     precise_flow G x T1 (typ_and T2 T3) ->\n     precise_flow G x T1 T2\n | pf_and2 : forall (G:ctx) (x:termvar) (T1 T3 T2:typ),\n     precise_flow G x T1 (typ_and T2 T3) ->\n     precise_flow G x T1 T3.\n\n(* defns TightTyping *)\nInductive ty_trm_t : ctx -> trm -> typ -> Prop :=    (* defn ty_trm_t *)\n | ty_var_t : forall (G:ctx) (x:termvar) (T:typ),\n      (binds ( x ) ( T ) ( G ))  ->\n     ty_trm_t G (trm_var (var_termvar_f x)) T\n | ty_all_intro_t : forall (L:vars) (G:ctx) (T1:typ) (t:trm) (T2:typ),\n      ( forall x , x \\notin  L  -> ty_trm  ( x ~ T1  ++  G )   ( open_trm_wrt_varref t (var_termvar_f x) )   ( open_typ_wrt_varref T2 (var_termvar_f x) )  )  ->\n     ty_trm_t G (trm_val (val_lambda T1 t)) (typ_all T1 T2)\n | ty_all_elim_t : forall (G:ctx) (x y:termvar) (T2 T1:typ),\n     ty_trm_t G (trm_var (var_termvar_f x)) (typ_all T1 T2) ->\n     ty_trm_t G (trm_var (var_termvar_f y)) T1 ->\n     ty_trm_t G (trm_app (var_termvar_f x) (var_termvar_f y))  (open_typ_wrt_varref  T2   (var_termvar_f y) ) \n | ty_new_intro_t : forall (L:vars) (G:ctx) (T:typ) (defs5:defs),\n      ( forall x , x \\notin  L  -> ty_defs  ( x ~  ( open_typ_wrt_varref T (var_termvar_f x) )   ++  G )   ( open_defs_wrt_varref defs5 (var_termvar_f x) )   ( open_typ_wrt_varref T (var_termvar_f x) )  )  ->\n      ( forall x , x \\notin  L  -> ty_trm_t G (trm_val (val_new  ( open_typ_wrt_varref T (var_termvar_f x) )  defs5)) (typ_bnd T) ) \n | ty_new_elim_t : forall (G:ctx) (x:termvar) (a:trmlabel) (T:typ),\n     ty_trm_t G (trm_var (var_termvar_f x)) (typ_dec (dec_trm a T)) ->\n     ty_trm_t G (trm_sel (var_termvar_f x) a) T\n | ty_let_t : forall (L:vars) (G:ctx) (t1 t2:trm) (T2 T1 T:typ),\n     ty_trm_t G t1 T1 ->\n      ( forall x , x \\notin  L  -> ty_trm  ( x ~ T  ++  G )   ( open_trm_wrt_varref t2 (var_termvar_f x) )  T2 )  ->\n     ty_trm_t G (trm_let t1 t2) T2\n | ty_rec_intro_t : forall (L:vars) (G:ctx) (x:termvar) (T:typ),\n      ( forall z , z \\notin  L  -> ty_trm_t G (trm_var (var_termvar_f x))  ( open_typ_wrt_varref T (var_termvar_f z) )  )  ->\n     ty_trm_t G (trm_var (var_termvar_f x)) (typ_bnd T)\n | ty_rec_elim_t : forall (G:ctx) (x:termvar) (T:typ),\n     ty_trm_t G (trm_var (var_termvar_f x)) (typ_bnd T) ->\n     ty_trm_t G (trm_var (var_termvar_f x))  (open_typ_wrt_varref  T   (var_termvar_f x) ) \n | ty_and_intro_t : forall (G:ctx) (x:termvar) (T1 T2:typ),\n     ty_trm_t G (trm_var (var_termvar_f x)) T1 ->\n     ty_trm_t G (trm_var (var_termvar_f x)) T2 ->\n     ty_trm_t G (trm_var (var_termvar_f x)) (typ_and T1 T2)\n | ty_sub_t : forall (G:ctx) (t:trm) (T2 T1:typ),\n     ty_trm_t G t T1 ->\n     subtyp_t G T1 T2 ->\n     ty_trm_t G t T2\nwith subtyp_t : ctx -> typ -> typ -> Prop :=    (* defn subtyp_t *)\n | subtyp_top_t : forall (G:ctx) (T:typ),\n     lc_typ T ->\n     subtyp_t G T typ_top\n | subtyp_bot_t : forall (G:ctx) (T:typ),\n     lc_typ T ->\n     subtyp_t G typ_bot T\n | subtyp_refl_t : forall (G:ctx) (T:typ),\n     lc_typ T ->\n     subtyp_t G T T\n | subtyp_trans_t : forall (G:ctx) (T1 T3 T2:typ),\n     subtyp_t G T1 T2 ->\n     subtyp_t G T2 T3 ->\n     subtyp_t G T1 T3\n | subtyp_and11_t : forall (G:ctx) (T1 T2:typ),\n     lc_typ T2 ->\n     lc_typ T1 ->\n     subtyp_t G (typ_and T1 T2) T1\n | subtyp_and12_t : forall (G:ctx) (T1 T2:typ),\n     lc_typ T1 ->\n     lc_typ T2 ->\n     subtyp_t G (typ_and T1 T2) T2\n | subtyp_and2_t : forall (G:ctx) (T1 T2 T3:typ),\n     subtyp_t G T1 T2 ->\n     subtyp_t G T1 T3 ->\n     subtyp_t G T1 (typ_and T2 T3)\n | subtyp_fld_t : forall (G:ctx) (a:trmlabel) (T1 T2:typ),\n     subtyp_t G T1 T2 ->\n     subtyp_t G (typ_dec (dec_trm a T1)) (typ_dec (dec_trm a T2))\n | subtyp_typ_t : forall (G:ctx) (A:typlabel) (T2 T3 T1 T4:typ),\n     subtyp_t G T1 T2 ->\n     subtyp_t G T3 T4 ->\n     subtyp_t G (typ_dec (dec_typ A T2 T3)) (typ_dec (dec_typ A T1 T4))\n | subtyp_sel1_t : forall (G:ctx) (x:termvar) (A:typlabel) (T2 T1:typ),\n     precise_flow G x T1 (typ_dec (dec_typ A T2 T2)) ->\n     subtyp_t G (typ_sel (var_termvar_f x) A) T2\n | subtyp_sel2_t : forall (G:ctx) (T2:typ) (x:termvar) (A:typlabel) (T1:typ),\n     precise_flow G x T1 (typ_dec (dec_typ A T2 T2)) ->\n     subtyp_t G T2 (typ_sel (var_termvar_f x) A)\n | subtyp_all_t : forall (L:vars) (G:ctx) (T1 T2 T3 T4:typ),\n     subtyp_t G T3 T1 ->\n      ( forall x , x \\notin  L  -> subtyp  ( x ~ T1  ++  G )   ( open_typ_wrt_varref T2 (var_termvar_f x) )   ( open_typ_wrt_varref T4 (var_termvar_f x) )  )  ->\n     subtyp_t G (typ_all T1 T2) (typ_all T3 T4).\n\n(* defns InvertibleTyping *)\nInductive ty_var_inv : ctx -> termvar -> typ -> Prop :=    (* defn ty_var_inv *)\n | ty_precise_inv : forall (G:ctx) (x:termvar) (T2 T1:typ),\n     precise_flow G x T1 T2 ->\n     ty_var_inv G x T2\n | ty_dec_trm_inv : forall (G:ctx) (x:termvar) (a:trmlabel) (T2 T1:typ),\n     ty_var_inv G x (typ_dec (dec_trm a T1)) ->\n     subtyp_t G T1 T2 ->\n     ty_var_inv G x (typ_dec (dec_trm a T2))\n | ty_dec_typ_inv : forall (G:ctx) (x:termvar) (A:typlabel) (T1 T4 T2 T3:typ),\n     ty_var_inv G x (typ_dec (dec_typ A T2 T3)) ->\n     subtyp_t G T1 T2 ->\n     subtyp_t G T3 T4 ->\n     ty_var_inv G x (typ_dec (dec_typ A T1 T4))\n | ty_bnd_inv : forall (G:ctx) (x:termvar) (T:typ),\n     ty_var_inv G x  (open_typ_wrt_varref  T   (var_termvar_f x) )  ->\n     ty_var_inv G x (typ_bnd T)\n | ty_all_inv : forall (L:vars) (G:ctx) (x:termvar) (T1 T4 T2 T3:typ),\n     ty_var_inv G x (typ_all T2 T3) ->\n     subtyp_t G T1 T2 ->\n      ( forall z , z \\notin  L  -> subtyp  ( z ~ T1  ++  G )   ( open_typ_wrt_varref T3 (var_termvar_f z) )   ( open_typ_wrt_varref T4 (var_termvar_f z) )  )  ->\n     ty_var_inv G x (typ_all T1 T4)\n | ty_and_inv : forall (G:ctx) (x:termvar) (T1 T2:typ),\n     ty_var_inv G x T1 ->\n     ty_var_inv G x T2 ->\n     ty_var_inv G x (typ_and T1 T2)\n | ty_sel_inv : forall (G:ctx) (x y:termvar) (A:typlabel) (T1 T2:typ),\n     ty_var_inv G x T1 ->\n     precise_flow G y T2 (typ_dec (dec_typ A T1 T1)) ->\n     ty_var_inv G x (typ_sel (var_termvar_f y) A)\n | ty_top_inv : forall (G:ctx) (x:termvar) (T:typ),\n     ty_var_inv G x T ->\n     ty_var_inv G x typ_top\nwith ty_val_inv : ctx -> val -> typ -> Prop :=    (* defn ty_val_inv *)\n | ty_precise_inv_v : forall (G:ctx) (val5:val) (T:typ),\n     ty_val_p G val5 T ->\n     ty_val_inv G val5 T\n | ty_all_inv_v : forall (L:vars) (G:ctx) (val5:val) (T1 T4 T2 T3:typ),\n     ty_val_inv G val5 (typ_all T2 T3) ->\n     subtyp_t G T1 T2 ->\n      ( forall z , z \\notin  L  -> subtyp  ( z ~ T1  ++  G )   ( open_typ_wrt_varref T3 (var_termvar_f z) )   ( open_typ_wrt_varref T4 (var_termvar_f z) )  )  ->\n     ty_val_inv G val5 (typ_all T1 T4)\n | ty_and_inv_v : forall (G:ctx) (val5:val) (T1 T2:typ),\n     ty_val_inv G val5 T1 ->\n     ty_val_inv G val5 T2 ->\n     ty_val_inv G val5 (typ_and T1 T2)\n | ty_sel_inv_v : forall (G:ctx) (val5:val) (y:termvar) (A:typlabel) (T1 T2:typ),\n     ty_val_inv G val5 T1 ->\n     precise_flow G y T2 (typ_dec (dec_typ A T1 T1)) ->\n     ty_val_inv G val5 (typ_sel (var_termvar_f y) A)\n | ty_top_inv_v : forall (G:ctx) (val5:val) (T:typ),\n     ty_val_inv G val5 T ->\n     ty_val_inv G val5 typ_top.\n\n(* defns OperationalSemantics *)\nInductive red : stack -> trm -> stack -> trm -> Prop :=    (* defn red *)\n | red_sel : forall (s:stack) (x:termvar) (a:trmlabel) (t:trm) (T:typ) (defs5:defs),\n      (binds ( x ) ( (trm_val (val_new T defs5)) ) ( s ))  ->\n      (defs_has   (open_defs_wrt_varref  defs5   (var_termvar_f x) )    (def_trm a t) )  ->\n     red s (trm_sel (var_termvar_f x) a) s t\n | red_app : forall (s:stack) (x y:termvar) (t:trm) (T1:typ),\n      (binds ( x ) ( (trm_val (val_lambda T1 t)) ) ( s ))  ->\n     red s (trm_app (var_termvar_f x) (var_termvar_f y)) s  (open_trm_wrt_varref  t   (var_termvar_f y) ) \n | red_let_val : forall (L:vars) (s:stack) (val5:val) (t:trm),\n     lc_trm (trm_let (trm_val val5) t) ->\n     lc_val val5 ->\n      ( forall x , x \\notin  L  -> red s (trm_let (trm_val val5) t)  ( x ~ (trm_val val5)  ++  s )   ( open_trm_wrt_varref t (var_termvar_f x) )  ) \n | red_let_var : forall (s:stack) (y:termvar) (t:trm),\n     lc_trm (trm_let (trm_var (var_termvar_f y)) t) ->\n     red s (trm_let (trm_var (var_termvar_f y)) t) s  (open_trm_wrt_varref  t   (var_termvar_f y) ) \n | red_let_tgt : forall (s1:stack) (t1 t3:trm) (s2:stack) (t2:trm),\n     lc_trm (trm_let t1 t3) ->\n     red s1 t1 s2 t2 ->\n     red s1 (trm_let t1 t3) s2 (trm_let t2 t3).\n\n\n(** infrastructure *)\nHint Constructors ty_trm ty_def ty_defs subtyp record_type inert_typ inert_ctx ty_val_p precise_flow ty_trm_t subtyp_t ty_var_inv ty_val_inv red lc_varref lc_dec lc_typ lc_def lc_defs lc_val lc_trm.\n\n\n", "meta": {"author": "jqyu", "repo": "dot-ott", "sha": "baa8e9cb0e25a008896d6c4287404ccfa150a6c4", "save_path": "github-repos/coq/jqyu-dot-ott", "path": "github-repos/coq/jqyu-dot-ott/dot-ott-baa8e9cb0e25a008896d6c4287404ccfa150a6c4/Definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2986340717855163}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.Lists.List.\nRequire Import compcert.common.AST. (* For ident. *)\nRequire Import liblayers.compcertx.ErrorMonad.\nRequire Import liblayers.lib.OptionMonad.\nRequire Import liblayers.lib.Decision.\nRequire Import liblayers.logic.PseudoJoin.\nRequire Import liblayers.logic.OptionOrders.\nRequire Import liblayers.logic.PTrees.\nRequire Import liblayers.logic.Modules.\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.GlobalVars.\n\n(** Total maps between two PTreeModules. *)\n\nSection WITHMAP.\n\n  Context\n    {F_from F_to V_from V_to}\n    {gvar_from_ops: GlobalVarsOps V_from}\n    {gvar_from_to: GlobalVarsOps V_to}\n    (ff: ident -> F_from -> F_to)\n    (fv: ident -> V_from -> V_to)\n  .\n\n  Definition map (M: ptree_module F_from V_from): ptree_module F_to V_to :=\n    (PTree.map (fun i => fmap (ff i)) (fst M), PTree.map (fun i => fmap (fv i)) (snd M)).\n\n  Existing Instance ptree_module_ops.\n\n  Lemma get_module_function_map i (M: ptree_module F_from V_from):\n    get_module_function i (map M) = fmap (option_map (ff i)) (get_module_function i M).\n  Proof.\n    simpl.\n    unfold get_module_function.\n    Local Transparent ptree_module_ops.\n    unfold ptree_module_ops.\n    unfold ptree_module_function.\n    simpl.\n    rewrite PTree.gmap.\n    destruct (PTree.get i (fst M)); simpl; auto.\n    destruct r; simpl; auto.\n  Qed.\n\n  Lemma get_module_variable_map i (M: ptree_module F_from V_from):\n    get_module_variable i (map M) = fmap (option_map (fv i)) (get_module_variable i M).\n  Proof.\n    simpl.\n    unfold get_module_variable.\n    Local Transparent ptree_module_ops.\n    unfold ptree_module_ops.\n    unfold ptree_module_variable.\n    simpl.\n    rewrite PTree.gmap.\n    destruct (PTree.get i (snd M)); simpl; auto.\n    destruct r; simpl; auto.\n  Qed.\n\nEnd WITHMAP.\n\nSection WITHMAPERROR.\n\n  Context\n    {F_from F_to V_from V_to}\n    {gvar_from_ops: GlobalVarsOps V_from}\n    {gvar_from_to: GlobalVarsOps V_to}\n    (ff: ident -> F_from -> res F_to)\n    (fv: ident -> V_from -> res V_to)\n  .\n\n  Definition map_error (M: ptree_module F_from V_from): ptree_module F_to V_to :=\n    (PTree.map (fun i x => Errors.bind x (ff i)) (fst M), PTree.map (fun i x => Errors.bind x (fv i)) (snd M)).\n\n  Existing Instance ptree_module_ops.\n\n  Lemma get_module_function_map_error i (M: ptree_module F_from V_from):\n    get_module_function i (map_error M) = option_res_flip (option_map (fun x => Errors.bind x (ff i)) (res_option_flip (get_module_function i M))).\n  Proof.\n    simpl.\n    unfold get_module_function.\n    Local Transparent ptree_module_ops.\n    unfold ptree_module_ops.\n    unfold ptree_module_function.\n    simpl.\n    rewrite PTree.gmap.\n    rewrite option_res_flip_inv.\n    reflexivity.\n  Qed.\n\n  Lemma get_module_variable_map_error i (M: ptree_module F_from V_from):\n    get_module_variable i (map_error M) = option_res_flip (option_map (fun x => Errors.bind x (fv i)) (res_option_flip (get_module_variable i M))).\n  Proof.\n    simpl.\n    unfold get_module_variable.\n    Local Transparent ptree_module_ops.\n    unfold ptree_module_ops.\n    unfold ptree_module_variable.\n    simpl.\n    rewrite PTree.gmap.\n    rewrite option_res_flip_inv.\n    reflexivity.\n  Qed.\n\nEnd WITHMAPERROR.\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/logic/PTreeModuleMap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2986340653246728}}
{"text": "From mathcomp Require Import\n  ssreflect ssrfun ssrbool eqtype ssrnat seq choice fintype div ssrint ssralg\n  intdiv.\nFrom extructures Require Import ord fmap.\nFrom CoqUtils Require Import word.\n\nRequire Import lib.utils common.types.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection Relocation.\n\nContext {mt : machine_types}\n        {ops : machine_ops mt}.\n\n(* The type of relocatable memory segments.  The first nat specifies\n   the segment's size.  The argument type specifies what kind of\n   relocation information is needed (e.g., nothing for constant\n   segments; just one word for relocatable code; a pair of words for\n   relocatable code that also needs access to a shared data area).\n\n   TODO: One issue is that we need the resulting list to always be of\n   the specified size, but the type does not demand this at the\n   moment.  One way to deal with this is to add a proof component that\n   certifies that the resulting list always has the specified length.\n   Is there a better way?  (This seems not too bad: our structured\n   code combinators can build these certificates pretty easily.) *)\n\nDefinition relocatable_segment :=\n  fun Args => fun Cell => (nat * (mword mt -> Args -> seq Cell))%type.\n\nDefinition empty_relocatable_segment (Args Cell : Type) : relocatable_segment Args Cell :=\n  (0, fun (base : mword mt) (rest : Args) => [::]).\n\n(* Concatenates list of relocatable segments into one, returning a\n   list of offsets (relative to the base address). *)\nDefinition concat_and_measure_relocatable_segments\n             (Args Cell : Type)\n             (segs : seq (relocatable_segment Args Cell))\n           : relocatable_segment Args Cell * seq nat :=\n  foldl\n    (fun (p : relocatable_segment Args Cell * seq nat)\n         (seg : relocatable_segment Args Cell) =>\n       let: (acc,addrs) := p in\n       let (l1,gen1) := acc in\n       let (l2,gen2) := seg in\n       let gen := fun (base : mword mt) (rest : Args) =>\n                       gen1 base rest\n                    ++ gen2 (addw base (as_word l1)) rest in\n       let newseg := (l1+l2, gen) in\n       (newseg, addrs ++ [:: l1]))\n    (empty_relocatable_segment _ _, [::])\n    segs.\n\nDefinition concat_relocatable_segments\n             (Args Cell : Type)\n             (segs : seq (relocatable_segment Args Cell))\n           : relocatable_segment Args Cell :=\n  fst (concat_and_measure_relocatable_segments segs).\n\nDefinition map_relocatable_segment\n             (Args Cell Cell' : Type)\n             (f : Cell -> Cell')\n             (seg : relocatable_segment Args Cell)\n           : relocatable_segment Args Cell' :=\n  let (l,gen) := seg in\n  let gen' := fun (base : mword mt) (rest : Args) => map f (gen base rest) in\n  (l, gen').\n\nDefinition relocate_ignore_args\n             (Args Cell : Type)\n             (seg : relocatable_segment unit Cell)\n           : relocatable_segment Args Cell :=\n  let (l,gen) := seg in\n  let gen' := fun (base : mword mt) (rest : Args) => gen base tt in\n  (l, gen').\n\nEnd Relocation.\n\nLtac current_instr_opcode :=\n  match goal with\n  | H : decode_instr _ = Some ?instr |- _ =>\n    let op := (eval compute in (opcode_of instr)) in\n    op\n  end.\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/common/segment.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2986340653246728}}
{"text": "From Cat Require Import Imports Category Preorder Monoid Poset Isomorphism Terminal Dual Initial Product CoProduct Exponential CCC.\n\n\nLocal Open Scope list_scope.\n\nInductive IPL: Type :=\n | pi   : IPL\n | truth: IPL\n | conju: IPL -> IPL -> IPL\n | impli: IPL -> IPL -> IPL.\n\nDefinition ctx := list (IPL)%type.\n\nDefinition extend (c: ctx) (x: IPL) := x :: c.\n\nFixpoint recI (P: PreOrder) (h1: top P) (h2: hasPOBM P) (h3: hasPOHI P h2) (l: list IPL) (M: IPL -> (@obj (@uc (PreOrderDetCatisCCC P h1 h2 h3)))): \n  (@obj (@uc (PreOrderDetCatisCCC P h1 h2 h3))) := \n  match l with\n    | nil     => @tobj (@uc (PreOrderDetCatisCCC P h1 h2 h3)) \n                       (@hasT (@uc (PreOrderDetCatisCCC P h1 h2 h3)) \n                       (@uobs (PreOrderDetCatisCCC P h1 h2 h3)))\n    | x :: xs => @pobj (@uc (PreOrderDetCatisCCC P h1 h2 h3)) \n                       (@hasP (@uc (PreOrderDetCatisCCC P h1 h2 h3)) (@uobs (PreOrderDetCatisCCC P h1 h2 h3))) \n                       (M x) (recI P h1 h2 h3 xs M)\n   end.\n\nClass interp (P: PreOrder) (h1: top P) (h2: hasPOBM P) (h3: hasPOHI P h2): Type :=\n{\n   M : IPL -> (@obj (@uc (PreOrderDetCatisCCC P h1 h2 h3)));\n   i1: { p: (@obj (@uc (PreOrderDetCatisCCC P h1 h2 h3))) | M pi = p };\n   i2: M truth = @tobj (@uc (PreOrderDetCatisCCC P h1 h2 h3)) \n                       (@hasT (@uc (PreOrderDetCatisCCC P h1 h2 h3)) \n                       (@uobs (PreOrderDetCatisCCC P h1 h2 h3)));\n   i3: forall p q, M (conju p q) = @pobj (@uc (PreOrderDetCatisCCC P h1 h2 h3)) \n                                         (@hasP (@uc (PreOrderDetCatisCCC P h1 h2 h3)) (@uobs (PreOrderDetCatisCCC P h1 h2 h3))) (M p) (M q);\n   i4: forall p q, M (impli p q) = @eobj (@uc (PreOrderDetCatisCCC P h1 h2 h3)) \n                                         (@hasP (@uc (PreOrderDetCatisCCC P h1 h2 h3)) (@uobs (PreOrderDetCatisCCC P h1 h2 h3)))\n                                         (@hasE (@uc (PreOrderDetCatisCCC P h1 h2 h3)) (@uobs (PreOrderDetCatisCCC P h1 h2 h3))) (M p) (M q);\n   ML: ctx -> (@obj (@uc (PreOrderDetCatisCCC P h1 h2 h3)));\n   i5: forall (l: ctx), ML l = recI P h1 h2 h3 l M\n}.\n\nLemma listc: forall (c: ctx) (x: IPL) (P: PreOrder) (h1: top P) (h2: hasPOBM P) (h3: hasPOHI P h2) (i: interp P h1 h2 h3),\n ((@ML P h1 h2 h3 i) (x :: c)) = @pobj (@uc (PreOrderDetCatisCCC P h1 h2 h3)) \n                                       (@hasP (@uc (PreOrderDetCatisCCC P h1 h2 h3)) (@uobs (PreOrderDetCatisCCC P h1 h2 h3))) \n                                       ((@M P h1 h2 h3 i) x) ((@ML P h1 h2 h3 i) c) .\nProof. intro c.\n       induction c; intros.\n       - destruct i.\n         simpl in *.\n         destruct h2 as (h2).\n         destruct h1.\n         compute. rewrite !i10.\n         simpl. compute. easy.\n       - rewrite IHc.\n         destruct i.\n         destruct h2 as (h2).\n         destruct h3 as (h3).\n         destruct h1.\n         simpl in *.\n         rewrite !i10. easy.\nQed.\n\n(** one can decude the IPL formula x in the context [x]; namely [x] |- x *)\nLemma soundR: forall (x: IPL) (P: PreOrder) (h1: top P) (h2: hasPOBM P) (h3: hasPOHI P h2) (i: interp P h1 h2 h3),\n  @pohrel P ((@ML P h1 h2 h3 i) (x :: nil))  ((@M P h1 h2 h3 i) x) = true.\nProof. intros.\n       simpl.\n       destruct i.\n       simpl in *. \n       specialize (i10 (x :: nil)).\n       rewrite i10. \n       destruct h2 as (h2).\n       destruct h1.\n       simpl in *.\n       destruct (h2 (M0 x) ptop).\n       simpl.\n       clear i10.\n       exact pobmpi1.\nQed.\n\nLemma soundRc: forall (c: ctx) (x: IPL) (P: PreOrder) (h1: top P) (h2: hasPOBM P) (h3: hasPOHI P h2) (i: interp P h1 h2 h3),\n  @pohrel P ((@ML P h1 h2 h3 i) (x :: c))  ((@M P h1 h2 h3 i) x) = true.\nProof. intro c.\n       induction c; intros.\n       - apply soundR.\n       - simpl in *.\n         rewrite listc.\n         simpl.\n         specialize (IHc x P h1 h2 h3 i).\n         destruct i.\n         simpl in *.\n         destruct h2 as (h2).\n         destruct h1.\n         destruct P.\n         simpl in *.\n         compute.\n         destruct (h2 (M0 x) (ML0 (a :: c))).\n         exact pobmpi1.\nQed.\n\nLemma soundR2: forall (x y: IPL) (P: PreOrder) (h1: top P) (h2: hasPOBM P) (h3: hasPOHI P h2) (i: interp P h1 h2 h3),\n  @pohrel P ((@ML P h1 h2 h3 i) (x :: y :: nil)) ((@M P h1 h2 h3 i) x) = true.\nProof. intros.\n       apply soundRc.\nQed.\n\nInductive IPLE: ctx -> IPL -> Prop :=\n  | ax1: forall (c: ctx) (p: IPL), IPLE (p :: c) p\n  | ax2: forall (c: ctx) (p q: IPL), IPLE c p -> IPLE (q :: c) p\n  | ax3: forall (c: ctx) (p q: IPL), IPLE c p -> IPLE (p :: c) q -> IPLE c q\n  | ax4: forall (c: ctx), IPLE c truth\n  | ax5: forall (c: ctx) (p q: IPL), IPLE c p -> IPLE c q -> IPLE c (conju p q)\n  | ax6: forall (c: ctx) (p q: IPL), IPLE (p :: c) q -> IPLE c (impli p q) \n  | ax7: forall (c: ctx) (p q: IPL), IPLE c (conju p q) -> IPLE c p\n  | ax8: forall (c: ctx) (p q: IPL), IPLE c (conju p q) -> IPLE c q\n  | ax9: forall (c: ctx) (p q: IPL), IPLE c (impli p q) -> IPLE c p -> IPLE c q.\n\nExample IPLExample_woCut: forall (phi psi theta: IPL),\n  IPLE ((impli phi psi) :: (impli psi theta) :: nil)\n       (impli phi theta).\nProof. intros. \n       apply ax6.\n       apply ax9 with (p := psi).\n       - apply ax2.\n         apply ax2.\n         apply ax1.\n       - apply ax9 with (p := phi).\n         + apply ax2. \n           apply ax1. \n         + apply ax1.\nQed.\n\nLemma PO_POIC_l: forall (P: PreOrder) (x y: @pos P) (C := PreOrderDetCat P),\n  @pohrel P x y = true -> @arrow C y x.\nProof. intros (P, R, r, t) x y C H.\n       unfold PreOrderDetCat in C.\n       simpl in *.\n       destruct C.\n       unfold PreOrderICMap.\n       simpl.\n       rewrite H.\n       exact tt.\nQed.\n\nLemma PO_POIC_r: forall (P: PreOrder) (x y: @pos P) (C := PreOrderDetCat P),\n   @arrow C y x -> @pohrel P x y = true.\nProof. intros (P, R, r, t) x y C H.\n       unfold PreOrderDetCat in C.\n       simpl in *.\n       destruct C.\n       unfold PreOrderICMap in H.\n       simpl in H.\n       case_eq (R x y); intro HH.\n       - easy.\n       - rewrite HH in H. easy.\nQed.\n\nLemma soundnessIPL_CCP: forall (x: IPL) (c: ctx) (P: PreOrder) (h1: top P) (h2: hasPOBM P) (h3: hasPOHI P h2) (i: interp P h1 h2 h3)\n  (C := PreOrderDetCat P),\n  IPLE c x ->\n  @arrow C ((@M P h1 h2 h3 i) x) ((@ML P h1 h2 h3 i) c).\nProof. intros x c P h1 h2 h3 i C H.\n       apply PO_POIC_l.\n       revert P h1 h2 h3 C i.\n       induction H; intros.\n       - apply soundRc.\n       - simpl.\n         rewrite listc.\n         specialize (IHIPLE P h1 h2 h3 i).\n         simpl in *.\n         destruct i.\n         simpl in *.\n         specialize (i10 (q :: c)).\n         destruct h2 as (h2).\n         destruct h1.\n         destruct P.\n         compute.\n         destruct (h2 (M0 q) (ML0 c)).\n         simpl in *.\n         assert (pohrel pobm (ML0 c) = true /\\ pohrel (ML0 c) (M0 p) = true) by easy.\n         clear h2 h3 i8 i9 i10 C.\n         specialize (potrans _ _ _ H0). easy.\n       - simpl in *.\n         specialize (IHIPLE1 P h1 h2 h3 i).\n         specialize (IHIPLE2 P h1 h2 h3 i).\n         rewrite listc in IHIPLE2.\n         simpl in IHIPLE2.\n         destruct i.\n         simpl in *.\n         destruct h2 as (h2).\n         destruct h1.\n         destruct P.\n         simpl in *.\n         compute in IHIPLE2.\n         destruct (h2 (M0 p) (ML0 c)).\n         simpl in *.\n         specialize (pobmuni (ML0 c)).\n         assert (pohrel (ML0 c) (M0 p) = true /\\ pohrel (ML0 c) (ML0 c) = true) by easy.\n         apply pobmuni in H1.\n         assert (pohrel (ML0 c) pobm = true /\\ pohrel pobm (M0 q) = true) by easy.\n         clear h2 h3 i8 i9 i10 C.\n         specialize (potrans _ _ _ H2). easy.\n       - simpl in *.\n         destruct i.\n         simpl in *.\n         destruct h2 as (h2).\n         destruct h1.\n         simpl in *.\n         rewrite i7, potob.\n         easy.\n       - specialize (IHIPLE1 P h1 h2 h3 i).\n         specialize (IHIPLE2 P h1 h2 h3 i).\n         destruct i as (M, i1, i2, i3, i4, ML, recI).\n         simpl in *.\n         destruct h2 as (h2).\n         destruct h1.\n         simpl in *.\n         specialize (i3 p q).\n         rewrite i3.\n         destruct (h2 (M p) (M q)).\n         simpl in *.\n         specialize (pobmuni (ML c)).\n         rewrite pobmuni.\n         easy.\n       - simpl in *.\n         specialize (IHIPLE P h1 h2 h3 i).\n         rewrite listc in IHIPLE.\n         destruct i as (M, i1, i2, i3, i4, ML, recI).\n         destruct h2 as (h2).\n         destruct h3 as (h3).\n         destruct h1.\n         simpl in *.\n         specialize (i4 p q).\n         destruct (h3 (M p) (M q)).\n         simpl in *.\n         specialize (hiob (ML c)).\n         destruct (h2 (ML c) (M p)).\n         destruct hiob.\n         simpl in *.\n         destruct (h2 (M p) (ML c)).\n         destruct (h2 hi (M p)).\n         simpl in *.\n         rewrite i4.\n\n         apply H1.\n         specialize (pobmuni1 pobm0).\n         assert (pohrel pobm (M p) = true /\\ pohrel pobm (ML c) = true) by easy.\n         apply pobmuni0 in H2.\n         assert (pohrel pobm pobm0 = true /\\ pohrel pobm0 (M q) = true) by easy .\n         clear h2 h3 i2 i3 i4 recI.\n         specialize (potrans _ _ _ H3). easy.\n       - simpl in *.\n         specialize (IHIPLE P h1 h2 h3 i).\n         destruct i.\n         simpl in *.\n         destruct h2 as (h2).\n         destruct h3 as (h3).\n         destruct h1.\n         destruct P.\n         compute.\n         compute in IHIPLE.\n         specialize (i8 p q).\n         compute in i8.\n         destruct (h2 (M0 p) (M0 q)).\n         simpl in *.\n         rewrite i8 in IHIPLE.\n         assert (pohrel (ML0 c) pobm = true /\\ pohrel pobm (M0 p) = true) by easy.\n         clear h2 h3 i8 i9 i10 C.\n         specialize (potrans _ _ _ H0). easy.\n       - simpl in *.\n         specialize (IHIPLE P h1 h2 h3 i).\n         destruct i.\n         simpl in *.\n         destruct h2 as (h2).\n         destruct h3 as (h3).\n         destruct h1.\n         destruct P.\n         compute.\n         compute in IHIPLE.\n         specialize (i8 p q).\n         compute in i8.\n         destruct (h2 (M0 p) (M0 q)).\n         simpl in *.\n         rewrite i8 in IHIPLE.\n         assert (pohrel (ML0 c) pobm = true /\\ pohrel pobm (M0 q) = true) by easy.\n         clear h2 h3 i8 i9 i10 C.\n         specialize (potrans _ _ _ H0). easy.\n       - simpl in *.\n         specialize (IHIPLE1 P h1 h2 h3 i).\n         specialize (IHIPLE2 P h1 h2 h3 i).\n         destruct i.\n         simpl in *.\n         destruct h2 as (h2).\n         destruct h3 as (h3).\n         destruct h1.\n         destruct P.\n         specialize (i9 p q).\n         compute in i9.\n         destruct (h3 (M0 p) (M0 q)).\n         simpl in *.\n         rewrite i9 in IHIPLE1.\n         compute in hiapp.\n         destruct (h2 hi (M0 p)).\n         simpl in *.\n         specialize (pobmuni (ML0 c)).\n         assert ( pohrel (ML0 c) hi = true /\\ pohrel (ML0 c) (M0 p) = true) by easy.\n         apply pobmuni in H1.\n         assert (pohrel (ML0 c) pobm = true /\\ pohrel pobm (M0 q) = true) by easy.\n         clear h2 h3 i8 i9 i10 hiob C.\n         specialize (potrans _ _ _ H2). easy.\nQed.\n\n\n", "meta": {"author": "ekiciburak", "repo": "CatTheo", "sha": "f80ac2700ca09eaff5c1bd6addcbf9ca2fdbb2fd", "save_path": "github-repos/coq/ekiciburak-CatTheo", "path": "github-repos/coq/ekiciburak-CatTheo/CatTheo-f80ac2700ca09eaff5c1bd6addcbf9ca2fdbb2fd/IPL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307806984445, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2986340588638291}}
{"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\n(** This module contains lemmas related to tight typing [G ⊢# t: T] *)\n\nSet Implicit Arguments.\n\nRequire Import Definitions PreciseTyping.\n\n(** * Tight typing [G |-# t: T] *)\n\nReserved Notation \"G '⊢#' t ':' T\" (at level 40, t at level 59).\nReserved Notation \"G '⊢#' T '<:' U\" (at level 40, T at level 59).\n\n(** *** Tight term typing [G ⊢# t: T] *)\n(** Tight typing is very similar to general typing, and could be obtained by replacing\n    all occurrences of [⊢] with [⊢#], except for the following:\n    - in the type selection subtyping rules Sel-<: and <:-Sel ([subtyp_sel1] and [subtyp_sel2]),\n      the premise is precise typing of a type declaration with equal bounds;\n    - whenever a typing judgement in a premise extends the environment (for example, [ty_all_intro_t]),\n      it is typed under general typing [⊢] and not tight typing [⊢#]. *)\n\nInductive ty_trm_t : ctx -> trm -> typ -> Prop :=\n\n(** [G(x) = T]   #<br>#\n    [――――――――――] #<br>#\n    [G ⊢# x: T]  *)\n| ty_var_t : forall G x T,\n    binds x T G ->\n    G ⊢# trm_var (avar_f x) : T\n\n(** [G, x: T ⊢ t^x: U^x]       #<br>#\n    [x fresh]                  #<br>#\n    [――――――――――――――――――――――――] #<br>#\n    [G ⊢# lambda(T)t: forall(T)U]     *)\n| ty_all_intro_t : forall L G T t U,\n    (forall x, x \\notin L ->\n      G & x ~ T ⊢ open_trm x t : open_typ x U) ->\n    G ⊢# trm_val (val_lambda T t) : typ_all T U\n\n(** [G ⊢# x: forall(S)T] #<br>#\n    [G ⊢# z: S]     #<br>#\n    [――――――――――――――] #<br>#\n    [G ⊢# x z: T^z]     *)\n| ty_all_elim_t : forall G x z S T,\n    G ⊢# trm_var (avar_f x) : typ_all S T ->\n    G ⊢# trm_var (avar_f z) : S ->\n    G ⊢# trm_app (avar_f x) (avar_f z) : open_typ z T\n\n(** [G, x: T^x ⊢ ds^x :: T^x]    #<br>#\n    [x fresh]                    #<br>#\n    [―――――――――――――――――――――――]    #<br>#\n    [G ⊢# nu(T)ds :: mu(T)]         *)\n| ty_new_intro_t : forall L G T ds,\n    (forall x, x \\notin L ->\n      G & (x ~ open_typ x T) /- open_defs x ds :: open_typ x T) ->\n    G ⊢# trm_val (val_new T ds) : typ_bnd T\n\n(** [G ⊢# x: {a: T}] #<br>#\n    [―――――――――――――――] #<br>#\n    [G ⊢# x.a: T]        *)\n| ty_new_elim_t : forall G x a T,\n    G ⊢# trm_var (avar_f x) : typ_rcd (dec_trm a T) ->\n    G ⊢# trm_sel (avar_f x) a : T\n\n(** [G ⊢# t: T]             #<br>#\n    [G, x: T ⊢ u^x: U]       #<br>#\n    [x fresh]                #<br>#\n    [――――――――――――――――]       #<br>#\n    [G ⊢# let t in u: U]        *)\n| ty_let_t : forall L G t u T U,\n    G ⊢# t : T ->\n    (forall x, x \\notin L ->\n      G & x ~ T ⊢ open_trm x u : U) ->\n    G ⊢# trm_let t u : U\n\n(** [G ⊢# x: T^x]   #<br>#\n    [――――――――――――――] #<br>#\n    [G ⊢# x: mu(T)] *)\n| ty_rec_intro_t : forall G x T,\n    G ⊢# trm_var (avar_f x) : open_typ x T ->\n    G ⊢# trm_var (avar_f x) : typ_bnd T\n\n(** [G ⊢# x: mu(T)] #<br>#\n    [――――――――――――――] #<br>#\n    [G ⊢# x: T^x]       *)\n| ty_rec_elim_t : forall G x T,\n    G ⊢# trm_var (avar_f x) : typ_bnd T ->\n    G ⊢# trm_var (avar_f x) : open_typ x T\n\n(** [G ⊢# x: T]      #<br>#\n    [G ⊢# x: U]      #<br>#\n    [―――――――――――――]   #<br>#\n    [G ⊢# x: T /\\ U]      *)\n| ty_and_intro_t : forall G x T U,\n    G ⊢# trm_var (avar_f x) : T ->\n    G ⊢# trm_var (avar_f x) : U ->\n    G ⊢# trm_var (avar_f x) : typ_and T U\n\n(** [G ⊢# t: T]    #<br>#\n    [G ⊢# T <: U]  #<br>#\n    [―――――――――――――] #<br>#\n    [G ⊢# t: U]        *)\n| ty_sub_t : forall G t T U,\n    G ⊢# t : T ->\n    G ⊢# T <: U ->\n    G ⊢# t : U\nwhere \"G '⊢#' t ':' T\" := (ty_trm_t G t T)\n\n(** *** Tight subtyping [G ⊢# T <: U] *)\nwith subtyp_t : ctx -> typ -> typ -> Prop :=\n\n(** [G ⊢# T <: top] *)\n| subtyp_top_t: forall G T,\n    G ⊢# T <: typ_top\n\n(** [G ⊢# bot <: T] *)\n| subtyp_bot_t: forall G T,\n    G ⊢# typ_bot <: T\n\n(** [G ⊢# T <: T] *)\n| subtyp_refl_t: forall G T,\n    G ⊢# T <: T\n\n(** [G ⊢# S <: T]     #<br>#\n    [G ⊢# T <: U]     #<br>#\n    [―――――――――――――]    #<br>#\n    [G ⊢# S <: U]         *)\n| subtyp_trans_t: forall G S T U,\n    G ⊢# S <: T ->\n    G ⊢# T <: U ->\n    G ⊢# S <: U\n\n(** [G ⊢# T /\\ U <: T] *)\n| subtyp_and11_t: forall G T U,\n    G ⊢# typ_and T U <: T\n\n(** [G ⊢# T /\\ U <: U] *)\n| subtyp_and12_t: forall G T U,\n    G ⊢# typ_and T U <: U\n\n(** [G ⊢# S <: T]       #<br>#\n    [G ⊢# S <: U]       #<br>#\n    [――――――――――――――――]   #<br>#\n    [G ⊢# S <: T /\\ U]       *)\n| subtyp_and2_t: forall G S T U,\n    G ⊢# S <: T ->\n    G ⊢# S <: U ->\n    G ⊢# S <: typ_and T U\n\n(** [G ⊢# T <: U]           #<br>#\n    [――――――――――――――――――――――] #<br>#\n    [G ⊢# {a: T} <: {a: U}]     *)\n| subtyp_fld_t: forall G a T U,\n    G ⊢# T <: U ->\n    G ⊢# typ_rcd (dec_trm a T) <: typ_rcd (dec_trm a U)\n\n(** [G ⊢# S2 <: S1]                   #<br>#\n    [G ⊢# T1 <: T2]                   #<br>#\n    [――――――――――――――――――――――――――――――――] #<br>#\n    [G ⊢# {A: S1..T1} <: {A: S2..T2}]     *)\n| subtyp_typ_t: forall G A S1 T1 S2 T2,\n    G ⊢# S2 <: S1 ->\n    G ⊢# T1 <: T2 ->\n    G ⊢# typ_rcd (dec_typ A S1 T1) <: typ_rcd (dec_typ A S2 T2)\n\n(** [G ⊢! x: {A: T..T}] #<br>#\n    [――――――――――――――――――] #<br>#\n    [G ⊢# T <: x.A]         *)\n| subtyp_sel2_t: forall G x A T U,\n    G ⊢! x : U ⪼ typ_rcd (dec_typ A T T) ->\n    G ⊢# T <: typ_sel (avar_f x) A\n\n(** [G ⊢! x: {A: T..T}] #<br>#\n    [――――――――――――――――――] #<br>#\n    [G ⊢# x.A <: T]         *)\n| subtyp_sel1_t: forall G x A T U,\n    G ⊢! x : U ⪼ typ_rcd (dec_typ A T T) ->\n    G ⊢# typ_sel (avar_f x) A <: T\n\n(** [G ⊢# S2 <: S1]                #<br>#\n    [G, x: S2 ⊢ T1^x <: T2^x]       #<br>#\n    [x fresh]                       #<br>#\n    [――――――――――――――――――――――――]      #<br>#\n    [G ⊢# forall(S1)T1 <: forall(S2)T2]          *)\n| subtyp_all_t: forall L G S1 T1 S2 T2,\n    G ⊢# S2 <: S1 ->\n    (forall x, x \\notin L ->\n       G & x ~ S2 ⊢ open_typ x T1 <: open_typ x T2) ->\n    G ⊢# typ_all S1 T1 <: typ_all S2 T2\nwhere \"G '⊢#' T '<:' U\" := (subtyp_t G T U).\n\nHint Constructors ty_trm_t subtyp_t.\n\nScheme ts_ty_trm_t_mut := Induction for ty_trm_t Sort Prop\nwith   ts_subtyp_t     := Induction for subtyp_t Sort Prop.\nCombined Scheme ts_t_mutind from ts_ty_trm_t_mut, ts_subtyp_t.\n\n(** Tight typing implies general typing. *)\nLemma tight_to_general:\n  (forall G t T,\n     G ⊢# t : T ->\n     G ⊢ t : T) /\\\n  (forall G S U,\n     G ⊢# S <: U ->\n     G ⊢ S <: U).\nProof.\n  apply ts_t_mutind; intros; subst; eauto using precise_to_general.\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/TightTyping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.29863342676099575}}
{"text": "Require Import Verdi.\nRequire Import HandlerMonad.\n\nRequire Import UpdateLemmas.\nLocal Arguments update {_} {_} {_} _ _ _ _ : simpl never.\n\nSet Implicit Arguments.\n\nSection Counter.\n  Inductive Name := primary | backup.\n  Definition Name_eq_dec : forall x y : Name, {x = y} + {x <> y}.\n    decide equality.\n  Defined.\n\n  Inductive Msg := inc | ack.\n  Definition Msg_eq_dec : forall x y : Msg, {x = y} + {x <> y}.\n    decide equality.\n  Defined.\n\n  Inductive Input := request_inc.\n  Definition Input_eq_dec : forall x y : Input, {x = y} + {x <> y}.\n    destruct x,y. auto.\n  Defined.\n\n  Inductive Output := inc_executed.\n  Definition Output_eq_dec : forall x y : Output, {x = y} + {x <> y}.\n    destruct x,y. auto.\n  Defined.\n\n  Definition Data := nat.\n\n  Definition init_Data := 0.\n\n  Definition Handler (S : Type) := GenHandler (Name * Msg) S Output unit.\n\n  Definition PrimaryNetHandler (m : Msg) : Handler Data :=\n    match m with\n    | ack => write_output inc_executed\n    | _ => nop\n    end.\n\n  Definition PrimaryInputHandler (i : Input) : Handler Data :=\n    match i with\n    | request_inc => modify S ;; send (backup, inc)\n    end.\n\n  Definition BackupNetHandler (m : Msg) : Handler Data :=\n    match m with\n    | inc => modify S ;; send (primary, ack)\n    | _ => nop\n    end.\n\n  Definition BackupInputHandler (i : Input) : Handler Data := nop.\n\n  Definition NetHandler (me : Name) (m : Msg) : Handler Data :=\n    match me with\n    | primary => PrimaryNetHandler m\n    | backup => BackupNetHandler m\n    end.\n\n  Definition InputHandler (me : Name) (i : Input) : Handler Data :=\n    match me with\n    | primary => PrimaryInputHandler i\n    | backup => BackupInputHandler i\n    end.\n\n  Instance Counter_BaseParams : BaseParams :=\n    {\n      data := Data;\n      input := Input;\n      output := Output\n    }.\n\n  Definition Nodes : list Name := [primary; backup].\n\n  Lemma all_Names_Nodes : forall n, In n Nodes.\n  Proof using. \n    destruct n; simpl; auto.\n  Qed.\n\n  Lemma NoDup_Nodes : NoDup Nodes.\n  Proof using. \n    repeat constructor; simpl; intuition discriminate.\n  Qed.\n\n  Instance Counter_MultiParams : MultiParams Counter_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 := fun _ => init_Data;\n      net_handlers := fun dst src msg s =>\n                        runGenHandler_ignore s (NetHandler dst msg);\n      input_handlers := fun nm i s =>\n                        runGenHandler_ignore s (InputHandler nm i)\n    }.\n\n\n  Lemma net_handlers_NetHandler :\n    forall h src m d os d' ms,\n      net_handlers h src m d = (os, d', ms) ->\n      NetHandler h m d = (tt, os, d', ms).\n  Proof using. \n    intros.\n    simpl in *.\n    monad_unfold.\n    repeat break_let.\n    find_inversion.\n    destruct u. auto.\n  Qed.\n\n  Lemma input_handlers_InputHandlers :\n    forall h i d os d' ms,\n      input_handlers h i d = (os, d', ms) ->\n      InputHandler h i d = (tt, os, d', ms).\n  Proof using. \n    intros.\n    simpl in *.\n    monad_unfold.\n    repeat break_let.\n    find_inversion.\n    destruct u. auto.\n  Qed.\n\n  Lemma PrimaryNetHandler_no_msgs :\n    forall m d ms d' o u,\n      PrimaryNetHandler m d = (u, o, d', ms) ->\n      ms = [].\n  Proof using. \n    unfold PrimaryNetHandler.\n    intros. monad_unfold.\n    break_match; find_inversion; auto.\n  Qed.\n\n  Definition inc_in_flight_to_backup (l : list packet) : nat :=\n    length (filterMap\n              (fun p => if msg_eq_dec (pBody p) inc\n                     then if name_eq_dec (pDst p) backup\n                          then Some tt else None\n                     else None)\n              l).\n\n  Lemma inc_in_flight_to_backup_app :\n    forall xs ys,\n      inc_in_flight_to_backup (xs ++ ys) = inc_in_flight_to_backup xs + inc_in_flight_to_backup ys.\n  Proof using. \n    intros.\n    unfold inc_in_flight_to_backup.\n    rewrite filterMap_app.\n    rewrite app_length.\n    auto.\n  Qed.\n\n  Lemma inc_in_flight_to_backup_cons_primary_dst :\n    forall p,\n      pDst p = primary ->\n      inc_in_flight_to_backup [p] = 0.\n  Proof using. \n    intros.\n    unfold inc_in_flight_to_backup.\n    simpl.\n    repeat break_match; try congruence; auto.\n  Qed.\n\n  Lemma inc_in_flight_to_backup_nil :\n    inc_in_flight_to_backup [] = 0.\n  Proof using. \n    reflexivity.\n  Qed.\n\n  Lemma InputHandler_inc_in_flight_to_backup_preserved :\n    forall h i d u o d' l,\n      InputHandler h i d = (u, o, d', l) ->\n      d' = d + inc_in_flight_to_backup (send_packets h l).\n  Proof using. \n    unfold InputHandler, PrimaryInputHandler, BackupInputHandler.\n    simpl.\n    intros.\n    monad_unfold.\n    repeat break_match; find_inversion; compute; auto.\n    rewrite plus_comm. auto.\n  Qed.\n\n  Lemma NetHandler_inc_in_flight_to_backup_preserved :\n    forall p d u o d' l,\n      NetHandler (pDst p) (pBody p) d = (u, o, d', l) ->\n      d' + inc_in_flight_to_backup (send_packets (pDst p) l) = d + inc_in_flight_to_backup [p].\n  Proof using. \n    unfold NetHandler, PrimaryNetHandler, BackupNetHandler.\n    intros.\n    monad_unfold.\n    destruct p. simpl in *.\n    repeat break_match; find_inversion; simpl; try rewrite inc_in_flight_to_backup_nil;\n    unfold Data in *; compute;\n    auto with *.\n  Qed.\n\n  Lemma InputHandler_backup_no_msgs :\n    forall i d u o d' l,\n      InputHandler backup i d = (u, o, d', l) ->\n      l = [].\n  Proof using. \n    simpl. unfold BackupInputHandler.\n    intros.\n    monad_unfold.\n    find_inversion.\n    auto.\n  Qed.\n\n  Lemma cons_is_app :\n    forall A (x : A) xs,\n      x :: xs = [x] ++ xs.\n  Proof using. \n    auto.\n  Qed.\n\n  Lemma backup_plus_network_eq_primary :\n    forall net tr,\n      step_m_star (params := Counter_MultiParams) step_m_init net tr ->\n      nwState net backup + inc_in_flight_to_backup (nwPackets net) = nwState net primary.\n  Proof using. \n    intros.\n    remember step_m_init as y in *.\n    revert Heqy.\n    induction H using refl_trans_1n_trace_n1_ind; intros; subst.\n    - reflexivity.\n    - concludes.\n      match goal with\n      | [ H : step_m _ _ _ |- _ ] => invc H\n      end; simpl.\n      + find_apply_lem_hyp net_handlers_NetHandler.\n        find_copy_apply_lem_hyp NetHandler_inc_in_flight_to_backup_preserved.\n        repeat find_rewrite.\n        rewrite cons_is_app in IHrefl_trans_1n_trace1.\n        repeat rewrite inc_in_flight_to_backup_app in *.\n        destruct (pDst p) eqn:?;\n                 try rewrite update_same;\n          try rewrite update_diff by congruence;\n          unfold send_packets in *; simpl in *.\n        * erewrite PrimaryNetHandler_no_msgs with (ms := l) in * by eauto.\n          rewrite inc_in_flight_to_backup_cons_primary_dst in * by auto.\n          simpl in *. rewrite inc_in_flight_to_backup_nil in *. auto with *.\n        * omega.\n      + find_apply_lem_hyp input_handlers_InputHandlers.\n        find_copy_apply_lem_hyp InputHandler_inc_in_flight_to_backup_preserved.\n        unfold send_packets in *. simpl in *.\n        rewrite inc_in_flight_to_backup_app. subst.\n        destruct h eqn:?;\n                 try rewrite update_same;\n          try rewrite update_diff by congruence.\n        * omega.\n        * erewrite InputHandler_backup_no_msgs with (l := l) by eauto.\n          simpl. rewrite inc_in_flight_to_backup_nil. omega.\n  Qed.\n\n  Theorem primary_ge_backup :\n    forall net tr,\n      step_m_star (params := Counter_MultiParams) step_m_init net tr ->\n      nwState net backup <= nwState net primary.\n  Proof using. \n    intros.\n    apply backup_plus_network_eq_primary in H.\n    auto with *.\n  Qed.\n\n  Definition trace_inputs (tr : list (name * (input + list output))) : nat :=\n    length (filterMap (fun e => match e with\n                             | (primary, inl i) => Some i\n                             | _ => None\n                             end) tr).\n  Lemma trace_inputs_app :\n    forall tr1 tr2,\n      trace_inputs (tr1 ++ tr2) = trace_inputs tr1 + trace_inputs tr2.\n  Proof using. \n    unfold trace_inputs.\n    intros.\n    rewrite filterMap_app.\n    rewrite app_length. auto.\n  Qed.\n\n  Definition trace_outputs (tr : list (name * (input + list output))) : nat :=\n    length (filterMap (fun e => match e with\n                             | (primary, inr [o]) => Some o\n                             | _ => None\n                             end) tr).\n\n  Lemma trace_outputs_app :\n    forall tr1 tr2,\n      trace_outputs (tr1 ++ tr2) = trace_outputs tr1 + trace_outputs tr2.\n  Proof using. \n    unfold trace_outputs.\n    intros.\n    rewrite filterMap_app.\n    rewrite app_length. auto.\n  Qed.\n\n  Definition ack_in_flight_to_primary (l : list packet) : nat :=\n    length (filterMap\n              (fun p => if msg_eq_dec (pBody p) ack\n                     then if name_eq_dec (pDst p) primary\n                          then Some tt else None\n                     else None)\n              l).\n\n  Lemma ack_in_flight_to_primary_app :\n    forall xs ys,\n      ack_in_flight_to_primary (xs ++ ys) = ack_in_flight_to_primary xs + ack_in_flight_to_primary ys.\n  Proof using. \n    unfold ack_in_flight_to_primary.\n    intros.\n    rewrite filterMap_app.\n    rewrite app_length. auto.\n  Qed.\n\n  Lemma ack_in_flight_to_primary_backup :\n    forall p,\n      pDst p = backup ->\n      ack_in_flight_to_primary [p] = 0.\n  Proof using. \n    intros.\n    unfold ack_in_flight_to_primary.\n    simpl.\n    repeat break_match; try congruence; auto.\n  Qed.\n\n\n  Lemma InputHandler_trace_preserved :\n    forall h i d u o d' l,\n      InputHandler h i d = (u, o, d', l) ->\n      trace_inputs [(h, inl i)] =\n      trace_outputs [(h, inr o)] +\n      inc_in_flight_to_backup (send_packets h l) +\n      ack_in_flight_to_primary (send_packets h l).\n  Proof using. \n    unfold InputHandler, PrimaryInputHandler, BackupInputHandler.\n    simpl.\n    intros.\n    monad_unfold.\n    repeat break_match; find_inversion; compute; auto.\n  Qed.\n\n  Lemma NetHandler_trace_preserved :\n    forall p d u o d' l,\n      NetHandler (pDst p) (pBody p) d = (u, o, d', l) ->\n      inc_in_flight_to_backup [p] +\n      ack_in_flight_to_primary [p] =\n      trace_outputs [((pDst p), inr o)] +\n      inc_in_flight_to_backup (send_packets (pDst p) l) +\n      ack_in_flight_to_primary (send_packets (pDst p) l).\n  Proof using. \n    unfold NetHandler, PrimaryNetHandler, BackupNetHandler.\n    intros.\n    monad_unfold.\n    destruct p. simpl in *.\n    repeat break_match; find_inversion; simpl; try rewrite inc_in_flight_to_backup_nil;\n    unfold Data in *; compute;\n    auto with *.\n  Qed.\n\n  Lemma trace_inputs_output :\n    forall h os,\n      trace_inputs [(h, inr os)] = 0.\n  Proof using. \n    intros.\n    unfold trace_inputs.\n    simpl. repeat break_match; simpl; congruence.\n  Qed.\n\n  Lemma trace_outputs_input :\n    forall h i,\n      trace_outputs [(h, inl i)] = 0.\n  Proof using. \n    intros.\n    unfold trace_outputs.\n    simpl. repeat break_match; simpl; congruence.\n  Qed.\n\n  Lemma trace_outputs_backup :\n    forall e,\n      trace_outputs [(backup, e)] = 0.\n  Proof using. \n    auto.\n  Qed.\n\n  Lemma inputs_eq_outputs_plus_inc_plus_ack :\n    forall net tr,\n      step_m_star (params := Counter_MultiParams) step_m_init net tr ->\n      trace_inputs tr = trace_outputs tr +\n                        inc_in_flight_to_backup (nwPackets net) +\n                        ack_in_flight_to_primary (nwPackets net).\n  Proof using. \n    intros.\n    remember step_m_init as y in *.\n    revert Heqy.\n    induction H using refl_trans_1n_trace_n1_ind; intros; subst.\n    - reflexivity.\n    - concludes.\n      match goal with\n      | [ H : step_m _ _ _ |- _ ] => invc H\n      end; simpl.\n      + find_apply_lem_hyp net_handlers_NetHandler.\n        repeat find_rewrite.\n        rewrite trace_inputs_app.\n        rewrite trace_outputs_app.\n        rewrite cons_is_app with (x := p) in *.\n        repeat rewrite inc_in_flight_to_backup_app in *.\n        repeat rewrite ack_in_flight_to_primary_app in *.\n        find_apply_lem_hyp NetHandler_trace_preserved.\n        destruct (pDst p) eqn:?.\n        * erewrite inc_in_flight_to_backup_cons_primary_dst in * by eauto.\n          rewrite trace_inputs_output in *. simpl in  *. omega.\n        * rewrite ack_in_flight_to_primary_backup in * by auto.\n          rewrite trace_outputs_backup in *. unfold send_packets in *.\n          simpl in *. rewrite <- plus_n_O in *. omega.\n      + find_apply_lem_hyp input_handlers_InputHandlers.\n        find_apply_lem_hyp InputHandler_trace_preserved.\n        rewrite cons_is_app.\n        repeat rewrite trace_inputs_app.\n        repeat rewrite trace_outputs_app.\n        repeat rewrite inc_in_flight_to_backup_app in *.\n        repeat rewrite ack_in_flight_to_primary_app in *.\n        rewrite trace_outputs_input.\n        rewrite trace_inputs_output.\n        unfold send_packets in *. simpl in *. omega.\n  Qed.\n\n  Theorem inputs_ge_outputs :\n    forall net tr,\n      step_m_star (params := Counter_MultiParams) step_m_init net tr ->\n      trace_outputs tr <= trace_inputs tr.\n  Proof using. \n    intros.\n    apply inputs_eq_outputs_plus_inc_plus_ack in H.\n    omega.\n  Qed.\nEnd Counter.", "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/systems/Counter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2985276657427354}}
{"text": "\n\n\nLtac eval1 := \nunfold sf_red; \nmatch goal with \n| |- multi_step sf_red1  (App (App (App (App _ _) _) _) _) _ =>  \neapply transitive_red; [eapply preserves_app_sf_red ; [eval1 |]|]\n| |- multi_step sf_red1  (App (App (App (Op Node) (Op Node)) _) _) _ => \n  eapply succ_red; [eapply2 k_red |]\n| |- multi_step sf_red1  (App (App (App (Op Node) (App (Op Node) _)) _) _) _ => \n  eapply succ_red; [eapply2 s_red |]\n| |- multi_step sf_red1  (App (App (App (Op Node) (App (App (Op Node) _) _)) _) _) _ => \n  eapply succ_red; [eapply2 f_red |]\n| |- multi_step sf_red1  (App (App (Op Node) _) _) _ => eapply transitive_red; [eapply preserves_app_sf_red ; eval1 |]\n| |- multi_step sf_red1  (App (Op Node) _) _ => eapply transitive_red; [eapply preserves_app_sf_red ; [auto|eval1 ]|]\n| _ => auto\nend.\n\nDefinition s_op := \nstar (star (star (App (App (Ref 2) (Ref 0)) \n                                  (App (Ref 1) (Ref 0))))).\n\n(* s_opt rule takes 11 steps *) \n\nLemma s_op_rule : forall M N P, sf_red (App (App (App s_op M) N) P) (App (App M P) (App N P)).\nProof.\nintros; unfold s_op; simpl; unfold_op; simpl.  \neval1. eval1. eval1. auto.  eval1. eval1. auto. eval1. eval1. eval1. auto.  eval1. eval1. auto.  eval1. eval1. eval1. \n auto. eval1. eval1. auto.  eval1. eval1. eval1. auto. eval1. auto. auto.  eval1. eval1. auto.  eval1.\nauto.  auto. auto. auto. \n eval1. eval1. eval1. auto. \neval1. eval1. auto.  eval1. eval1. eval1. auto. eval1. auto. auto.  eval1. auto. auto. auto. auto. \n  eval1. eval1. eval1. auto. eval1. auto. auto. eval1. auto. auto. auto. auto. auto. auto.   \neval1. eval1. auto.  eval1. eval1. eval1. auto. eval1. auto. auto.  eval1. auto. auto. \n eval1. auto.  eval1. eval1. auto.  eval1.  eval1. eval1. auto.  eval1. eval1. auto. eval1. eval1. eval1. auto. eval1. \neval1. auto. eval1. eval1. eval1. auto. eval1. eval1. auto. eval1. eval1. eval1. auto.  eval1. \nauto. auto. eval1. auto. auto. auto. auto.  eval1. eval1. eval1. auto. eval1. auto. auto.  eval1. auto. \nauto. auto. auto. auto.  eval1.  eval1. eval1. auto.  eval1. eval1. auto.  eval1. eval1.  eval1.  auto.   \neval1. eval1. auto.  eval1. eval1.  eval1. auto. eval1. auto. auto.  eval1. auto. auto. auto. auto. \n eval1. eval1. eval1. auto.  eval1. all: auto. \n eval1. eval1. eval1.  eval1. auto. eval1. eval1. auto. eval1. eval1. eval1. auto.\n(* 100 steps *) \n eval1. eval1. auto.  eval1. eval1. eval1. auto.  eval1.\neval1. auto. eval1. eval1. eval1. auto.  eval1. eval1. auto. eval1. eval1. eval1. auto. eval1. eval1. auto.\neval1. all: auto.\n eval1. eval1. eval1. eval1. auto. eval1. all:auto.\n eval1. eval1. auto. eval1. eval1.\neval1. eval1. auto. eval1. all: auto. \n(* 1 *) \neapply transitive_red; [eapply preserves_app_sf_red ; [eval1 |]|].\neval1. auto.  eval1. eval1.  eval1. eval1. auto. eval1. eval1. auto. \neval1. eval1. eval1. auto. eval1. eval1. auto. eval1. eval1. eval1. auto. \neval1. eval1. all: auto. \n eval1. eval1. eval1. auto. eval1. eval1. eval1. eval1. all: auto. \neval1. eval1. eval1. eval1. eval1. auto. eval1. all: auto. \neval1. eval1. eval1. auto. eval1. eval1. eval1. eval1. all: auto.\n(* 68 steps *) \n(* 1 *) \neapply transitive_red. \neapply preserves_app_sf_red. \neapply preserves_app_sf_red. \neapply preserves_app_sf_red. \neapply preserves_app_sf_red. auto. \neval1. eval1. eval1. eval1. eval1. eval1. auto.  eval1. auto. auto. eval1. auto. auto. auto.   \neval1. auto.  eval1. eval1. eval1. auto.  eval1. auto. auto.  auto. eval1. eval1. auto. \neval1. auto. auto. auto. eval1. auto. eval1. auto. eval1. auto. eval1. auto. eval1. auto. eval1.\nauto.  eval1. auto. \neapply transitive_red. \neapply preserves_app_sf_red. \neapply preserves_app_sf_red. \neapply preserves_app_sf_red. \neapply preserves_app_sf_red. auto. \neval1. auto.  eval1. auto. auto. auto.  eval1. auto. auto. auto.  eval1. eval1. eval1. auto.\n  eval1. auto. auto. eval1. auto. auto. auto.\neapply transitive_red. \neapply preserves_app_sf_red. \neapply preserves_app_sf_red. \neapply preserves_app_sf_red. auto. \neval1. eval1. eval1. eval1. eval1. auto. eval1. eval1. auto. eval1. eval1. eval1. auto. \neval1. eval1. auto.  eval1. eval1.  eval1.  auto. eval1.  auto.  auto. eval1. auto. auto. auto. \nauto.  eval1. eval1. eval1. auto. eval1. auto. auto. eval1. all: auto. \neval1. eval1. auto. eval1. eval1. auto. auto. eval1.\neapply2 preserves_app_sf_red. \neapply transitive_red. \neapply preserves_app_sf_red. \neapply preserves_app_sf_red. \neapply preserves_app_sf_red. auto. \neval1. eval1. eval1. eval1. eval1. auto. eval1. auto. auto.  eval1. auto. auto. auto.  eval1. auto. eval1.\n eval1. auto. eval1. auto. auto. auto.  eval1. eval1. eval1. auto.  eval1. eval1.  auto. eval1.\neval1. eval1. auto. eval1. auto. auto. eval1. auto. auto. auto. auto.\neval1. eval1. eval1. auto. eval1. auto. auto. eval1. auto. auto. auto. auto. \neval1. eval1.  auto. eval1. auto. auto. auto.\neapply transitive_red. \neapply preserves_app_sf_red. \neapply preserves_app_sf_red. \neapply preserves_app_sf_red.\neapply preserves_app_sf_red. auto. \neval1. auto.  eval1. auto. auto. auto. eval1. auto. auto. auto. eval1. eval1. eval1.\neval1. auto. eval1. eval1. auto. eval1. eval1. eval1. auto. eval1. all: auto. \n(* 100 steps *) \neval1. eval1. eval1. eval1. eval1. auto. eval1. auto. auto. eval1. auto. auto. auto.  \neval1. auto. eval1. eval1. auto. auto. eval1. eval1.\neval1. auto.  eval1. all: auto. \neval1. eval1. auto.  eval1. eval1. auto. auto.\n(* 18 steps *) \nQed. \n\n\n\nDefinition s_opt := \nstar_opt (star_opt (star_opt (App (App (Ref 2) (Ref 0)) \n                                  (App (Ref 1) (Ref 0))))).\n\n(* s_opt rule takes 11 steps *) \n\nLemma s_opt_rule : forall M N P, sf_red (App (App (App s_opt M) N) P) (App (App M P) (App N P)).\nProof.\nintros; unfold s_opt. simpl. unfold_op; unfold subst; simpl.\neapply succ_red. eapply app_sf_red.  eapply app_sf_red.  eapply2 s_red. auto. auto.  \neapply succ_red. eapply app_sf_red. eapply app_sf_red.  eapply app_sf_red.  eapply2 s_red.\neapply2 k_red.  auto.  auto. auto.\neapply succ_red. eapply app_sf_red. eapply app_sf_red. eapply app_sf_red.  eapply app_sf_red.  eapply2 k_red.\neapply2 s_red.  auto. auto. auto. \neapply succ_red. eapply app_sf_red.  eapply app_sf_red.  eapply app_sf_red.  eapply app_sf_red.   auto.  eapply app_sf_red.  eapply2 k_red. auto. auto. auto. auto.\neapply succ_red. eapply app_sf_red.  eapply2 s_red. auto. \neapply succ_red. eapply app_sf_red.  eapply app_sf_red.  eapply s_red. auto. auto. auto. \neapply2 k_red. auto.\neapply succ_red.   eapply app_sf_red.  eapply app_sf_red. eapply app_sf_red.   eapply2 k_red. auto. auto. auto.\neapply succ_red.  eapply s_red. all: auto. \nQed. \n\n  \n\n\nLemma maxvar_occurs: forall M, maxvar M = 1 -> occurs 0 M >0. \nProof.\ninduction M; split_all.\ngen_case H n.  omega.\nassert(maxvar M1 = 1 \\/ maxvar M2 = 1). \ngen_case H (maxvar M1).\ngen_case H (maxvar M2).\nassert (max n n0 >= n) by eapply2 max_is_max.\nleft; omega. \ninversion H0. \nassert(occurs 0 M1 >0) by eapply2 IHM1. omega. \nassert(occurs 0 M2 >0) by eapply2 IHM2. omega. \nQed.  \n\n\n(*\n(* A4 *) \n\n\nDefinition A41 M := (star_opt (app_comb (A_k 3) (app_comb (lift 1 M) (Ref 0)))).\n\n\nLemma A4_red1: forall M, sf_red (App (A_k 4) M) (A41 M).\nProof.\nintros. \nreplace (A_k 4) with (star_opt (star_opt (app_comb (A_k 3) (app_comb (Ref 1) (Ref 0)))))\nby (unfold A_k; auto).\neapply transitive_red. \neapply2 star_opt_beta. \nunfold subst. \nrewrite subst_rec_preserves_star_opt.\nrewrite ! subst_rec_preserves_app_comb.\nrewrite subst_rec_closed. \n2: rewrite A_k_closed; split_all.\nunfold subst_rec.  insert_Ref_out. \neapply2 zero_red. \nQed. \n\n\nDefinition A42 M N := app_comb (A_k 3) (app_comb M N).\n \nLemma A4_red2: forall M N, sf_red (App (A41 M) N) (A42 M N).\nProof.\nintros; unfold A41.  \neapply transitive_red. \neapply2 star_opt_beta.\nunfold subst; rewrite ! subst_rec_preserves_app_comb.\nunfold lift; \nrewrite subst_rec_lift_rec; try omega.\nrewrite subst_rec_ref. \nrewrite subst_rec_closed. \n2: rewrite A_k_closed; auto. \ninsert_Ref_out. \nunfold lift; rewrite ! lift_rec_null.\neapply2 zero_red.\nQed. \n\n \nDefinition A43 M N P :=  A32 (app_comb M N) P. \n\nLemma A4_red3: forall M N P, sf_red (App (A42 M N) P) (A43 M N P).\nProof.\nintros; unfold A42.\neapply transitive_red.\neapply2 app_comb_red. \neapply transitive_red. \neapply preserves_app_sf_red.\neapply2 A3_red1. auto. \neapply2 A3_red2.   \nQed. \n\n  \nDefinition A44 M N P Q := A33 (app_comb M N) P Q.\n\nLemma A4_red4 : forall M N P Q, \nsf_red (App (A43 M N P) Q) (A44 M N P Q). \nProof. \nintros. unfold A43. \neapply2 A3_red3. \nQed. \n\nLemma A4_red5 : forall M N P Q R, \nsf_red (App (A44 M N P Q) R) (App (App (App (App M N) P) Q) R).\nProof. \nintros. unfold A44.\neapply transitive_red.\neapply2 A3_red4.  \neapply transitive_red. eapply preserves_app_sf_red. eapply preserves_app_sf_red. \neapply2 app_comb_red. auto. auto. auto. \nQed. \n\nLemma A5_red: forall M N P Q R, \nsf_red (App (App (App (App (App (A_k 5) M) N) P) Q) R) (App (App (App (App M N) P) Q) R) .\nProof. \nintros. \neapply transitive_red. \neapply preserves_app_sf_red. \neapply preserves_app_sf_red. \neapply preserves_app_sf_red. \ninstantiate(1:= app_comb (A_k 4) (app_comb M N)).\nunfold A_k; auto.\neapply transitive_red.  \neapply star_opt_beta2. \nunfold subst; \nrewrite ! subst_rec_preserves_app_comb.\nrewrite ! subst_rec_preserves_star_opt.\nrewrite ! subst_rec_preserves_app_comb.\nrewrite ! subst_rec_preserves_star_opt.\nrewrite ! subst_rec_preserves_app_comb.\nunfold subst_rec; fold subst_rec. \ninsert_Ref_out. \nunfold subst_rec; fold subst_rec. \ninsert_Ref_out. \nunfold lift; rewrite ! lift_rec_null. \nrewrite subst_rec_lift_rec; try omega. \nrewrite ! subst_rec_closed. \n2: unfold_op; simpl; auto. \n2: unfold_op; simpl; auto. \nall: auto. \nrewrite lift_rec_null. auto. \n(* 1 *) \neapply transitive_red. \neapply preserves_app_sf_red. \neapply preserves_app_sf_red. \neapply2 app_comb_red. \nall: auto. \neapply transitive_red. \neapply preserves_app_sf_red. \neapply preserves_app_sf_red. \neapply preserves_app_sf_red. \neapply2 A4_red1.\nall: auto. \neapply transitive_red. \neapply preserves_app_sf_red. \neapply preserves_app_sf_red. \neapply2 A4_red2.\nall: auto. \neapply transitive_red. \neapply preserves_app_sf_red. \neapply2 A4_red3.  all: auto. \neapply transitive_red.\n eapply2 A4_red4.\nunfold A44. unfold A33.  preserves_app_sf_red. \ninstantiate(1:= app_comb (A_k 4) (app_comb M N)).\nunfold A_k; auto.\neapply transitive_red.  \neapply star_opt_beta2. \nunfold subst; \nrewrite ! subst_rec_preserves_app_comb.\nrewrite ! subst_rec_preserves_star_opt.\nrewrite ! subst_rec_preserves_app_comb.\nrewrite ! subst_rec_preserves_star_opt.\nrewrite ! subst_rec_preserves_app_comb.\nunfold subst_rec; fold subst_rec. \ninsert_Ref_out. \nunfold subst_rec; fold subst_rec. \ninsert_Ref_out. \nunfold lift; rewrite ! lift_rec_null. \nrewrite subst_rec_lift_rec; try omega. \nrewrite ! subst_rec_closed. \n2: unfold_op; simpl; auto. \n2: unfold_op; simpl; auto. \nall: auto. \nrewrite lift_rec_null. auto. \n\n\n\n\nunfold A_k; fold A_k. \n\n*) \n(* \nLemma aux :\n  forall M N, occurs 0 M >0 -> maxvar N = 0 -> S (size(subst M N)) >= size M + size N.\nProof.\n  induction M; split_all.\n  gen_case H n. unfold subst; simpl. insert_Ref_out.\n  unfold lift; rewrite lift_rec_null. omega. omega. omega. \n  assert(occurs 0 M1 >0 \\/ occurs 0 M2 >0) by omega.\n  inversion H1.\n  assert(S(size (subst M1 N)) >= size M1 + size N) by eapply2 IHM1.   \n  unfold subst in *.\nassert(size (subst_rec M2 N 0) >= size M2). apply size_subst. ga.   \n*) \n\n\n(* restore ? \nLemma star_bigger: \nforall M, maxvar M = 0 -> \nstar_opt\n  (star_opt\n     (App (Ref 0)\n        (app_comb (app_comb (app_comb M (Ref 1)) (Ref 1)) (Ref 0)))) <>\nM. \nProof.\n  intros. \n  replace (star_opt (star_opt (App (Ref 0) (app_comb (app_comb (app_comb M (Ref 1)) (Ref 1)) (Ref 0)))))\n  with\n    (subst (star_opt (star_opt (App (Ref 0) (app_comb (app_comb (app_comb (Ref 2) (Ref 1)) (Ref 1)) (Ref 0))))) M) .\n  intro. \nelim(size_subst_star_opt (star_opt\n               (App (Ref 0)\n                  (app_comb (app_comb (app_comb (Ref 2) (Ref 1)) (Ref 1)) (Ref 0)))) M); intros; auto. \n\n  unfold app_comb, star_opt; unfold_op; unfold occurs, eqnat; simpl. \nintro.\nomega. intro.\n\n\n  \nintros. \nrewrite star_opt_occurs_true. \n2: cbv. 2: omega.\n2: discriminate . \nunfold star_opt at 3.\nunfold app_comb.\nrewrite  (star_opt_occurs_true (App (Op Node) (App (Op Node) i_op))). \n2: unfold app_comb; simpl; auto. 2: omega. \n2: discriminate . \n rewrite  (star_opt_occurs_true (App (Op Node) (App (Op Node) (App k_op (Ref 0))))). \n2: unfold app_comb; simpl; auto. 2: omega. \n2: discriminate .\nrewrite (star_opt_occurs_false (App k_op _)). \n2: simpl; auto. 2: eapply2 occurs_closed; auto.\nsubst_tac.\nrewrite subst_rec_closed. 2: omega. \nrewrite star_opt_occurs_true. \n2: simpl; auto. 2: omega. 2: discriminate.\nrewrite star_opt_closed. 2: cbv; omega.\nrewrite star_opt_occurs_true.\n2: unfold app_comb; simpl; auto. 2: omega. \n2: discriminate .\nrewrite star_opt_occurs_true.\n2: unfold app_comb; simpl; auto.\n2: discriminate .\nrewrite star_opt_occurs_true.\n2: unfold app_comb; simpl; auto.\n2: discriminate .\nrewrite star_opt_closed.\n2: cbv; auto. \nrewrite star_opt_occurs_true.\n2: unfold app_comb; simpl; auto.\n2: discriminate .\nrewrite star_opt_occurs_true.\n2: unfold app_comb; simpl; auto.\n2: discriminate .\nrewrite star_opt_occurs_true.\n2: unfold app_comb; simpl; auto.\n2: discriminate .\nrewrite star_opt_closed.\n2: cbv; auto. \nrewrite star_opt_occurs_true.\n2: unfold app_comb; simpl; auto.\n2: discriminate .\nrewrite star_opt_occurs_true.\n2: unfold app_comb; simpl; auto.\n2: discriminate .\nrewrite star_opt_occurs_true.\n2: unfold app_comb; simpl; auto.\n2: discriminate .\nrewrite star_opt_occurs_true.\n2: unfold app_comb; simpl; auto.\n2: discriminate .\nrewrite star_opt_occurs_true.\n2: unfold app_comb; simpl; auto.\n2: discriminate .\nrewrite star_opt_occurs_true.\n2: unfold app_comb; simpl; auto.\n2: discriminate .\nrewrite star_opt_occurs_true.\n2: unfold app_comb; simpl; auto.\n2: discriminate .\nrewrite star_opt_occurs_true.\n2: unfold app_comb; simpl; auto.\n2: discriminate .\nrewrite star_opt_occurs_true.\n2: unfold app_comb; simpl; auto.\n2: discriminate .\nrewrite star_opt_closed.\n2: cbv; auto. \nintro. clear H.  \nmatch goal with \n| H: ?M = ?N |- _ => assert(size M = size N) by congruence \nend.\nclear H0.\ngeneralize H. clear H. unfold_op; unfold star_opt, occurs, size; fold size.\nrewrite ! orb_false_l. \nunfold_op; unfold subst, subst_rec, size; fold size. \nintro; omega.\nQed. \n *)\n\n(* \nLemma star_opt_app_comb2:\n  forall M N, maxvar M = 0 -> occurs 0 N = true -> occurs 1 N = true -> \n              star_opt (star_opt (app_comb M  N)) = k_op.\nProof.\n  intros.\n  rewrite star_opt_app_comb1; auto.   \n  rewrite star_opt_occurs_true. \n  2: simpl; rewrite H0; auto.\n  2: rewrite ! orb_false_r.\n  2: replace (match N with\n      | Ref 0 => subst k_op (Op Node)\n      | _ =>\n          App (App (Op Node) (App (Op Node) (star_opt N)))\n            (App k_op (subst (App node node) (Op Node)))\n      end)\n    with (App (App (Op Node) (App (Op Node) (star_opt N)))\n              (App k_op (subst (App node node) (Op Node)))).\n  all: cycle 1.\n  simpl. \n  rewrite occurs_star_opt.\n  rewrite H1; auto. simpl. \n  rewrite orb_true_r.   auto.\n  2: discriminate.\n  gen2_case H0 H1 N.\n  assert False.\n  gen2_case H0 H1 n; discriminate. omega. \n  (* 1 *)\n  assert (match N with\n      | Ref 0 => subst k_op (Op Node)\n      | _ =>\n          App (App (Op Node) (App (Op Node) (star_opt N)))\n            (App k_op (subst (App node node) (Op Node)))\n          end =\n          App (App (Op Node) (App (Op Node) (star_opt N)))\n              (App k_op (subst (App node node) (Op Node)))).\n  gen2_case H0 H1 N.\n  assert False.\n  gen2_case H0 H1 n; discriminate. omega. \n  rewrite star_opt_closed. \n  2: cbv; auto.\n  rewrite star_opt_occurs_true. \n  2: simpl; rewrite H0; auto.\n  2: rewrite ! orb_false_r.\n  2: rewrite H2.  \n  2: simpl; auto. \n  all: cycle 1.\nrewrite occurs_star_opt.   \nrewrite H1.   simpl. rewrite orb_true_r. auto.\ndiscriminate.\n  rewrite star_opt_occurs_true. \n  2: simpl; rewrite H0; auto.\n  2: rewrite ! orb_false_r.\n  2: rewrite H2.  \n  2: simpl; auto. \n  all: cycle 1.\nrewrite occurs_star_opt.   \nrewrite H1.   simpl. rewrite orb_true_r. auto.\ndiscriminate.\n  rewrite star_opt_occurs_true. \n  2: simpl; rewrite H0; auto.\n  2: rewrite ! orb_false_r.\n  2: rewrite H2.  \n  2: simpl; auto. \n  all: cycle 1.\nrewrite occurs_star_opt.   \nrewrite H1.   simpl. rewrite orb_true_r. auto.\ndiscriminate.\n  rewrite star_opt_occurs_true. \n  2: simpl; rewrite H0; auto.\n  2: rewrite ! orb_false_r.\n  2: rewrite H2.  \n  2: simpl; auto. \n  all: cycle 1.\nrewrite occurs_star_opt.   \nrewrite H1. auto.    \ndiscriminate.\nrewrite star_opt_closed. \n2: cbv; auto.\nrewrite star_opt_occurs_true.\n2: rewrite ! occurs_app. \n2: rewrite ! occurs_op.\n2: rewrite occurs_star_opt. \n2: rewrite ! occurs_app. 2: rewrite H1. 2: cbv; auto. 2: discriminate.\nrewrite star_opt_occurs_true.\n2: rewrite ! occurs_app. \n2: rewrite ! occurs_op.\n2: rewrite occurs_star_opt. \n2: rewrite ! occurs_app. 2: rewrite H1. 2: cbv; auto. 2: discriminate.\n\n\n\nsimpl2: rewrite H2. cbv; auto. 2: discriminate. \n  2: simpl; rewrite H0; auto.\n  2: rewrite ! orb_false_r.\n  2: rewrite H2.  \n  2: simpl; auto. \n  all: cycle 1.\nrewrite occurs_star_opt.   \nrewrite H1.   simpl. rewrite orb_true_r. auto.\ndiscriminate.\n  rewrite star_opt_occurs_true. \n  2: simpl; rewrite H0; auto.\n  2: rewrite ! orb_false_r.\n  2: rewrite H2.  \n  2: simpl; auto. \n  all: cycle 1.\nrewrite occurs_star_opt.   \nrewrite H1.   simpl. rewrite orb_true_r. auto.\ndiscriminate.\n  rewrite star_opt_occurs_true. \n  2: simpl; rewrite H0; auto.\n  2: rewrite ! orb_false_r.\n  2: rewrite H2.  \n  2: simpl; auto. \n  all: cycle 1.\nrewrite occurs_star_opt.   \nrewrite H1.   simpl. rewrite orb_true_r. auto.\ndiscriminate.\n\n\n\nassert False.\n  gen2_case H0 H1 n; discriminate. omega. \n\n\n  2: rewrite ! orb_false_r.\n\n\n\n  all: try discriminate.\n  rewrite H0.  rewrite occurs_closed. simpl. \n  unfold eqnat in *.\n\n  2: congruence. \n  rewrite star_opt_occurs_true. \n  2: simpl; rewrite H0; auto. 2: congruence. \n  rewrite star_opt_closed. \n  2: cbv; auto.\n  rewrite star_opt_occurs_true. \n  2: simpl; rewrite H0; auto. 2: congruence. \n  rewrite star_opt_occurs_true. \n  2: simpl; rewrite H0; auto. 2: congruence. \n  rewrite (star_opt_closed  (App (Op Node) (App (Op Node) i_op))).\n  2: cbv; auto.\n  rewrite ! (star_opt_closed (Op Node)).\n  2: cbv; auto. auto. \nQed.\n\n\n(* \n\n  Lemma star_opt_app_comb:\n  forall M1 N1 M2 N2, maxvar M1 = 0 -> maxvar M2 = 0 -> occurs 0 N1 = occurs 0 N2 ->\n                      star_opt (app_comb M1 N1) = star_opt (app_comb M2 N2) ->\n                      M1 = M2 /\\ star_opt N1 = star_opt N2.\nProof.\n  intros.\n  assert (occurs 0 N1 = false \\/ occurs 0 N1 <> false) by decide equality.  \n  inversion H3.\n  (* 2 *) \nrewrite ! star_opt_occurs_false in *. \ninversion H2. split.  rewrite ! subst_rec_closed in H7. auto. omega. omega. congruence. \nunfold app_comb; simpl.   rewrite H4 in *. rewrite <- H1. rewrite occurs_closed.\nauto. auto. congruence.\nunfold app_comb; simpl.   rewrite H4 in *. rewrite occurs_closed.\nauto. auto. congruence.\n(* 1 *)\ngeneralize H2; clear H2.  unfold app_comb. \n  rewrite star_opt_occurs_true at 1.   \n  rewrite star_opt_occurs_true at 1.   \n  2: unfold_op; simpl.\n  2: gen_case H4 (occurs 0 N1). 2: congruence. 2: unfold_op; simpl.\n  2: gen_case H4 (occurs 0 N1). 2: congruence. \n  rewrite star_opt_closed at 1. 2: simpl; auto. \n  rewrite star_opt_occurs_true at 1.   \n  2: unfold_op; simpl.\n  2: gen_case H4 (occurs 0 N1). 2: congruence.\n  rewrite star_opt_occurs_true at 1.   \n  2: unfold_op; simpl.\n  2: gen_case H4 (occurs 0 N1). 2: congruence.\n  unfold star_opt at 2 3.\n  rewrite (star_opt_closed (App (Op Node) _)). \n  2: cbv; auto.\n\n  intro. \nassert(star_opt\n         (App (App (Op Node) (App (Op Node) i_op))\n              (App (App (Op Node) (App (Op Node) (App k_op N2))) (App k_op M2))) =\n        App\n         (App (Op Node)\n            (App (Op Node)\n               (App (App (Op Node) (App (Op Node) (App k_op (App k_op M1))))\n                  (App\n                     (App (Op Node)\n                        (App (Op Node)\n                           (App (App (Op Node) (App (Op Node) (star_opt (App k_op N1))))\n                              (App k_op (Op Node))))) (App k_op (Op Node))))))\n         (App k_op (App (Op Node) (App (Op Node) i_op))) )\n     by auto.   \ngeneralize H5; clear H2 H5.\nassert(occurs 0 N2 = true). gen2_case H4 H1 (occurs 0 N1). \nrewrite star_opt_occurs_true at 1.   \n  rewrite star_opt_occurs_true at 1.   \n  2: unfold_op; simpl.\n  2:  rewrite H2; auto. 2:congruence. 2: unfold_op; simpl.\n  2: rewrite H2; auto. 2: congruence. \n  rewrite star_opt_closed at 1. 2: simpl; auto. \n  rewrite star_opt_occurs_true at 1.   \n  2: unfold_op; simpl.\n  2: auto.  2: congruence.\n  rewrite star_opt_occurs_true at 1.   \n  2: unfold_op; simpl.\n  2: auto. 2: congruence.\n  unfold star_opt at 2 3.\n  rewrite (star_opt_closed (App (Op Node) _)). \n  2: cbv; auto.\n\n  intro. inversion H5; subst.\n  rewrite H2 in *.\n  assert(occurs 0 N1 = true) by (gen_case H4 (occurs 0 N1)). \n  rewrite H6 in *. \n  split; auto. \n  clear - H2 H6 H8.\n  gen2_case H2 H8 N2. \n  gen2_case H2 H8 n.\n  gen2_case H6 H8 N1. \n  gen2_case H6 H8 n0.\n  all: try discriminate.   \n  gen2_case H6 H8 N1. \n  gen2_case H6 H8 n.\n  gen2_case H2 H8 (occurs 0 t).\nall: try (inversion H8; fail).   \nall: try discriminate. \ninversion H8; subst. auto. \nQed.\n *) \n *)\n", "meta": {"author": "Barry-Jay", "repo": "Intensional-computation", "sha": "de09d3e646c1ea50127c5033b46576d8b4773259", "save_path": "github-repos/coq/Barry-Jay-Intensional-computation", "path": "github-repos/coq/Barry-Jay-Intensional-computation/Intensional-computation-de09d3e646c1ea50127c5033b46576d8b4773259/Tree_calculus/offcuts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.29852766574273537}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Lists.SetoidList.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.Arith.Peano_dec.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Classes.Morphisms.\nRequire Import Coq.Numbers.Natural.Peano.NPeano.\nRequire Import Crypto.Util.NatUtil.\nRequire Import Crypto.Util.Pointed.\nRequire Import Crypto.Util.Prod.\nRequire Import Crypto.Util.Decidable.\nRequire Crypto.Util.Option.\nRequire Export Crypto.Util.FixCoqMistakes.\nRequire Export Crypto.Util.Tactics.BreakMatch.\nRequire Export Crypto.Util.Tactics.DestructHead.\nRequire Import Crypto.Util.Tactics.SpecializeBy.\nRequire Import Crypto.Util.Tactics.RewriteHyp.\nRequire Import Crypto.Util.Tactics.ConstrFail.\nRequire Import Crypto.Util.Tactics.SplitInContext.\nImport ListNotations.\nLocal Open Scope list_scope.\n\nScheme Equality for list.\n\nDefinition list_case\n           {A} (P : list A -> Type) (N : P nil) (C : forall x xs, P (cons x xs))\n           (ls : list A)\n  : P ls\n  := match ls return P ls with\n     | nil => N\n     | cons x xs => C x xs\n     end.\n\nDefinition list_case_nodep\n           {A} (P : Type) (N : P) (C : A -> list A -> P)\n           (ls : list A)\n  : P\n  := match ls with\n     | nil => N\n     | cons x xs => C x xs\n     end.\n\n\nGlobal Instance list_rect_Proper_dep_gen {A P} (RP : forall x : list A, P x -> P x -> Prop)\n  : Proper (RP nil ==> forall_relation (fun x => forall_relation (fun xs => RP xs ==> RP (cons x xs))) ==> forall_relation RP) (@list_rect A P) | 10.\nProof.\n  cbv [forall_relation respectful]; intros N N' HN C C' HC ls.\n  induction ls as [|l ls IHls]; cbn [list_rect];\n    repeat first [ apply IHls | apply HC | apply HN | progress intros | reflexivity ].\nQed.\nGlobal Instance list_rect_Proper_dep {A P} : Proper (eq ==> forall_relation (fun _ => forall_relation (fun _ => forall_relation (fun _ => eq))) ==> forall_relation (fun _ => eq)) (@list_rect A P) | 1.\nProof.\n  cbv [forall_relation respectful Proper]; intros; eapply (@list_rect_Proper_dep_gen A P (fun _ => eq)); cbv [forall_relation respectful]; intros; subst; eauto.\nQed.\nGlobal Instance list_rect_arrow_Proper_dep {A P Q} : Proper ((eq ==> eq) ==> forall_relation (fun _ => forall_relation (fun _ => (eq ==> eq) ==> (eq ==> eq))) ==> forall_relation (fun _ => eq ==> eq)) (@list_rect A (fun x => P x -> Q x)) | 10.\nProof.\n  cbv [forall_relation respectful Proper]; intros; eapply (@list_rect_Proper_dep_gen A (fun x => P x -> Q x) (fun _ => eq ==> eq)%signature); intros; subst; eauto.\nQed.\nGlobal Instance list_case_Proper_dep {A P} : Proper (eq ==> forall_relation (fun _ => forall_relation (fun _ => eq)) ==> forall_relation (fun _ => eq)) (@list_case A P) | 1.\nProof.\n  cbv [forall_relation]; intros N N' ? C C' HC ls; subst N'; revert N; destruct ls; eauto.\nQed.\nGlobal Instance list_rect_Proper_gen {A P} R\n  : Proper (R ==> (eq ==> eq ==> R ==> R) ==> eq ==> R) (@list_rect A (fun _ => P)) | 10.\nProof. repeat intro; subst; apply (@list_rect_Proper_dep_gen A (fun _ => P) (fun _ => R)); cbv [forall_relation respectful] in *; eauto. Qed.\nGlobal Instance list_rect_Proper {A P} : Proper (eq ==> pointwise_relation _ (pointwise_relation _ (pointwise_relation _ eq)) ==> eq ==> eq) (@list_rect A (fun _ => P)).\nProof. repeat intro; subst; apply (@list_rect_Proper_dep A (fun _ => P)); eauto. Qed.\nGlobal Instance list_rect_arrow_Proper {A P Q}\n  : Proper ((eq ==> eq) ==> (eq ==> eq ==> (eq ==> eq) ==> eq ==> eq) ==> eq ==> eq ==> eq)\n           (@list_rect A (fun _ => P -> Q)) | 10.\nProof. eapply list_rect_Proper_gen. Qed.\nGlobal Instance list_case_Proper {A P} : Proper (eq ==> pointwise_relation _ (pointwise_relation _ eq) ==> eq ==> eq) (@list_case A (fun _ => P)).\nProof. repeat intro; subst; apply (@list_case_Proper_dep A (fun _ => P)); eauto. Qed.\n\nCreate HintDb distr_length discriminated.\nCreate HintDb simpl_set_nth discriminated.\nCreate HintDb simpl_update_nth discriminated.\nCreate HintDb simpl_nth_default discriminated.\nCreate HintDb simpl_nth_error discriminated.\nCreate HintDb simpl_firstn discriminated.\nCreate HintDb simpl_skipn discriminated.\nCreate HintDb simpl_fold_right discriminated.\nCreate HintDb simpl_fold_left discriminated.\nCreate HintDb simpl_sum_firstn discriminated.\nCreate HintDb push_map discriminated.\nCreate HintDb push_combine discriminated.\nCreate HintDb push_flat_map discriminated.\nCreate HintDb push_rev discriminated.\nCreate HintDb push_fold_right discriminated.\nCreate HintDb push_fold_left discriminated.\nCreate HintDb push_partition discriminated.\nCreate HintDb pull_nth_error discriminated.\nCreate HintDb push_nth_error discriminated.\nCreate HintDb pull_nth_default discriminated.\nCreate HintDb push_nth_default discriminated.\nCreate HintDb pull_firstn discriminated.\nCreate HintDb push_firstn discriminated.\nCreate HintDb pull_skipn discriminated.\nCreate HintDb push_skipn discriminated.\nCreate HintDb push_sum discriminated.\nCreate HintDb pull_update_nth discriminated.\nCreate HintDb push_update_nth discriminated.\nCreate HintDb znonzero discriminated.\n\n#[global]\nHint Rewrite\n  @app_length\n  @rev_length\n  @map_length\n  @seq_length\n  @fold_left_length\n  @split_length_l\n  @split_length_r\n  @firstn_length\n  @combine_length\n  @prod_length\n  : distr_length.\n\n#[global]\nHint Rewrite\n     rev_involutive\n  : push_rev.\n\nGlobal Hint Extern 1 => progress autorewrite with distr_length in * : distr_length.\nLtac distr_length := autorewrite with distr_length in *;\n  try solve [simpl in *; intros; (idtac + exfalso); lia].\n\nModule Export List.\n  Local Set Implicit Arguments.\n  Import ListNotations.\n  (** From the 8.6 Standard Library *)\n\n  Section Elts.\n    Variable A : Type.\n\n    (** Results about [nth_error] *)\n\n    Lemma nth_error_In l n (x : A) : nth_error l n = Some x -> In x l.\n    Proof using Type.\n      revert n. induction l as [|a l IH]; intros [|n]; simpl; try easy.\n      - injection 1; auto.\n      - eauto.\n    Qed.\n  End Elts.\n\n  Section Map.\n    Variables (A : Type) (B : Type).\n    Variable f : A -> B.\n\n    Lemma map_nil : forall A B (f : A -> B), map f nil = nil.\n    Proof using Type. reflexivity. Qed.\n    Lemma map_cons (x:A)(l:list A) : map f (x::l) = (f x) :: (map f l).\n    Proof using Type.\n      reflexivity.\n    Qed.\n    Lemma map_repeat x n : map f (List.repeat x n) = List.repeat (f x) n.\n    Proof using Type. induction n; simpl List.repeat; simpl map; congruence. Qed.\n  End Map.\n#[global]\n  Hint Rewrite @map_cons @map_nil @map_repeat : push_map.\n#[global]\n  Hint Rewrite @map_app : push_map.\n\n  Section FlatMap.\n    Lemma flat_map_nil {A B} (f:A->list B) : List.flat_map f (@nil A) = nil.\n    Proof. reflexivity. Qed.\n    Lemma flat_map_cons {A B} (f:A->list B) x xs :\n      (List.flat_map f (x::xs) = (f x++List.flat_map f xs))%list.\n    Proof. reflexivity. Qed.\n  End FlatMap.\n#[global]\n  Hint Rewrite @flat_map_cons @flat_map_nil : push_flat_map.\n\n  Lemma rev_cons {A} x ls : @rev A (x :: ls) = rev ls ++ [x]. Proof. reflexivity. Qed.\n#[global]\n  Hint Rewrite @rev_cons : list.\n\n  Section FoldRight.\n    Context {A B} (f:B->A->A).\n    Lemma fold_right_nil : forall {A B} (f:B->A->A) a,\n        List.fold_right f a nil = a.\n    Proof using Type. reflexivity. Qed.\n    Lemma fold_right_cons : forall a b bs,\n      fold_right f a (b::bs) = f b (fold_right f a bs).\n    Proof using Type. reflexivity. Qed.\n    Lemma fold_right_snoc a x ls:\n      @fold_right A B f a (ls ++ [x]) = fold_right f (f x a) ls.\n    Proof using Type.\n      rewrite <-(rev_involutive ls), <-rev_cons.\n      rewrite !fold_left_rev_right; reflexivity.\n    Qed.\n  End FoldRight.\n#[global]\n  Hint Rewrite @fold_right_nil @fold_right_cons @fold_right_snoc : simpl_fold_right push_fold_right.\n\n  Section Partition.\n    Lemma partition_nil {A} (f:A->_) : partition f nil = (nil, nil).\n    Proof. reflexivity.                                         Qed.\n    Lemma partition_cons {A} (f:A->_) x xs : partition f (x::xs) =\n                                             if f x\n                                             then (x :: (fst (partition f xs)), (snd (partition f xs)))\n                                             else ((fst (partition f xs)), x :: (snd (partition f xs))).\n    Proof. cbv [partition]; break_match; reflexivity.           Qed.\n  End Partition.\n#[global]\n  Hint Rewrite @partition_nil @partition_cons : push_partition.\n\n  Lemma in_seq len start n :\n    In n (seq start len) <-> start <= n < start+len.\n  Proof.\n   revert start. induction len as [|len IHlen]; simpl; intros.\n   - rewrite <- plus_n_O. split;[easy|].\n     intros (H,H'). apply (Lt.lt_irrefl _ (Lt.le_lt_trans _ _ _ H H')).\n   - rewrite IHlen, <- plus_n_Sm; simpl; split.\n     * intros [H|H]; subst; intuition auto with arith.\n     * intros (H,H'). destruct (Lt.le_lt_or_eq _ _ H); intuition.\n  Qed.\n\n  Section Facts.\n\n    Variable A : Type.\n\n    Theorem length_zero_iff_nil (l : list A):\n      length l = 0 <-> l=[].\n    Proof using Type.\n      split; [now destruct l | now intros ->].\n    Qed.\n  End Facts.\n\n  Section Cutting.\n\n    Variable A : Type.\n\n    Local Notation firstn := (@firstn A).\n\n    Lemma firstn_nil n: firstn n [] = [].\n    Proof using Type. induction n; now simpl. Qed.\n\n    Lemma firstn_cons n a l: firstn (S n) (a::l) = a :: (firstn n l).\n    Proof using Type. now simpl. Qed.\n\n    Lemma firstn_all l: firstn (length l) l = l.\n    Proof using Type. induction l as [| ? ? H]; simpl; [reflexivity | now rewrite H]. Qed.\n\n    Lemma firstn_all2 n: forall (l:list A), (length l) <= n -> firstn n l = l.\n    Proof using Type. induction n as [|k iHk].\n           - intro l. inversion 1 as [H1|?].\n             rewrite (length_zero_iff_nil l) in H1. subst. now simpl.\n           - destruct l as [|x xs]; simpl.\n             * now reflexivity.\n             * simpl. intro H. apply Peano.le_S_n in H. f_equal. apply iHk, H.\n    Qed.\n\n    Lemma firstn_O l: firstn 0 l = [].\n    Proof using Type. now simpl. Qed.\n\n    Lemma firstn_le_length n: forall l:list A, length (firstn n l) <= n.\n    Proof using Type.\n      induction n as [|k iHk]; simpl; [auto | destruct l as [|x xs]; simpl].\n      - auto with arith.\n      - apply le_n_S, iHk.\n    Qed.\n\n    Lemma firstn_length_le: forall l:list A, forall n:nat,\n          n <= length l -> length (firstn n l) = n.\n    Proof using Type. induction l as [|x xs Hrec].\n           - simpl. intros n H. apply le_n_0_eq in H. rewrite <- H. now simpl.\n           - destruct n as [|n].\n             * now simpl.\n             * simpl. intro H. apply le_S_n in H. now rewrite (Hrec n H).\n    Qed.\n\n    Lemma firstn_app n:\n      forall l1 l2,\n        firstn n (l1 ++ l2) = (firstn n l1) ++ (firstn (n - length l1) l2).\n    Proof using Type. induction n as [|k iHk]; intros l1 l2.\n           - now simpl.\n           - destruct l1 as [|x xs].\n             * unfold List.firstn at 2, length. now rewrite 2!app_nil_l, <- minus_n_O.\n             * rewrite <- app_comm_cons. simpl. f_equal. apply iHk.\n    Qed.\n\n    Lemma firstn_app_2 n:\n      forall l1 l2,\n        firstn ((length l1) + n) (l1 ++ l2) = l1 ++ firstn n l2.\n    Proof using Type. induction n as [| k iHk];intros l1 l2.\n           - unfold List.firstn at 2. rewrite <- plus_n_O, app_nil_r.\n             rewrite firstn_app. rewrite <- minus_diag_reverse.\n             unfold List.firstn at 2. rewrite app_nil_r. apply firstn_all.\n           - destruct l2 as [|x xs].\n             * simpl. rewrite app_nil_r. apply firstn_all2. auto with arith.\n             * rewrite firstn_app. assert (H0 : (length l1 + S k - length l1) = S k).\n               auto with arith.\n               rewrite H0, firstn_all2; [reflexivity | auto with arith].\n    Qed.\n\n    Lemma firstn_firstn:\n      forall l:list A,\n      forall i j : nat,\n        firstn i (firstn j l) = firstn (min i j) l.\n    Proof using Type. induction l as [|x xs Hl].\n           - intros. simpl. now rewrite ?firstn_nil.\n           - destruct i.\n             * intro. now simpl.\n             * destruct j.\n             + now simpl.\n             + simpl. f_equal. apply Hl.\n    Qed.\n\n  End Cutting.\n\n  Lemma fold_right_rev_left A B (f : B -> A -> B) (l : list A) (i : B)\n    : fold_left f (rev l) i = fold_right (fun x y => f y x) i l.\n  Proof.\n    now rewrite <- fold_left_rev_right, rev_involutive.\n  Qed.\n\n\n  Section FoldLeft.\n    Context {A B} (f:A->B->A).\n    Lemma fold_left_nil : forall {A B} (f:A->B->A) a,\n        List.fold_left f nil a = a.\n    Proof using Type. reflexivity. Qed.\n    Lemma fold_left_cons : forall a b bs,\n      fold_left f (b::bs) a = fold_left f bs (f a b).\n    Proof using Type. reflexivity. Qed.\n    Lemma fold_left_snoc a x ls:\n      @fold_left A B f (ls ++ [x]) a = f (fold_left f ls a) x.\n    Proof using Type.\n      rewrite <-(rev_involutive ls), <-rev_cons.\n      rewrite !fold_right_rev_left; reflexivity.\n    Qed.\n  End FoldLeft.\n#[global]\n  Hint Rewrite @fold_left_nil @fold_left_cons @fold_left_snoc : simpl_fold_left push_fold_left.\n\n  (** new operations *)\n  Definition enumerate {A} (ls : list A) : list (nat * A)\n    := combine (seq 0 (length ls)) ls.\nEnd List.\n\n#[global]\nHint Rewrite @firstn_skipn : simpl_firstn.\n#[global]\nHint Rewrite @firstn_skipn : simpl_skipn.\n#[global]\nHint Rewrite @firstn_nil @firstn_cons @List.firstn_all @firstn_O @firstn_app_2 @List.firstn_firstn : push_firstn.\n#[global]\nHint Rewrite @firstn_nil @firstn_cons @List.firstn_all @firstn_O @firstn_app_2 @List.firstn_firstn : simpl_firstn.\n#[global]\nHint Rewrite @firstn_app : push_firstn.\n#[global]\nHint Rewrite <- @firstn_cons @firstn_app @List.firstn_firstn : pull_firstn.\n#[global]\nHint Rewrite @firstn_all2 @removelast_firstn @firstn_removelast using lia : push_firstn.\n#[global]\nHint Rewrite @firstn_all2 @removelast_firstn @firstn_removelast using lia : simpl_firstn.\n\nLocal Arguments value / _ _.\nLocal Arguments error / _.\n\nDefinition list_beq_hetero {A B} (f : A -> B -> bool)\n  := fix list_beq_hetero (l1 : list A) (l2 : list B) : bool\n       := match l1, l2 with\n          | [], [] => true\n          | [], _ | _, [] => false\n          | x :: xs, y :: ys => f x y && list_beq_hetero xs ys\n          end%bool.\n\nDefinition sum_firstn l n := fold_right Z.add 0%Z (firstn n l).\n\nDefinition sum xs := sum_firstn xs (length xs).\n\nSection map2.\n  Context {A B C}\n          (f : A -> B -> C).\n\n  Fixpoint map2 (la : list A) (lb : list B) : list C :=\n    match la, lb with\n    | nil, _ => nil\n    | _, nil => nil\n    | a :: la', b :: lb'\n      => f a b :: map2 la' lb'\n    end.\nEnd map2.\n\n(* xs[n] := f xs[n] *)\nFixpoint update_nth {T} n f (xs:list T) {struct n} :=\n        match n with\n        | O => match xs with\n                                 | nil => nil\n                                 | x'::xs' => f x'::xs'\n                                 end\n        | S n' =>  match xs with\n                                 | nil => nil\n                                 | x'::xs' => x'::update_nth n' f xs'\n                                 end\n  end.\n\n(* xs[n] := x *)\nDefinition set_nth {T} n x (xs:list T)\n  := update_nth n (fun _ => x) xs.\n\nDefinition splice_nth {T} n (x:T) xs := firstn n xs ++ x :: skipn (S n) xs.\n#[global]\nHint Unfold splice_nth : core.\n\nFixpoint take_while {T} (f : T -> bool) (ls : list T) : list T\n  := match ls with\n     | nil => nil\n     | cons x xs => if f x then x :: @take_while T f xs else nil\n     end.\n\nFixpoint drop_while {T} (f : T -> bool) (ls : list T) : list T\n  := match ls with\n     | nil => nil\n     | cons x xs => if f x then @drop_while T f xs else x :: xs\n     end.\nLtac boring :=\n  simpl; intuition auto with zarith datatypes;\n  repeat match goal with\n           | [ H : _ |- _ ] => rewrite H; clear H\n           | [ |- context[match ?pf with end] ] => solve [ case pf ]\n           | _ => progress autounfold in *\n           | _ => progress autorewrite with core\n           | _ => progress simpl in *\n           | _ => progress intuition auto with zarith datatypes\n         end; eauto.\n\nLtac boring_list :=\n  repeat match goal with\n         | _ => progress boring\n         | _ => progress autorewrite with distr_length simpl_nth_default simpl_update_nth simpl_set_nth simpl_nth_error in *\n         end.\n\nSection Relations.\n  Fixpoint list_eq {A B} eq (x : list A) (y : list B) :=\n    match x, y with\n    | [], [] => True\n    | [], _ | _, [] => False\n    | x :: xs, y :: ys => eq x y /\\ list_eq eq xs ys\n    end.\n\n  Local Ltac t :=\n    repeat first [ progress cbn in *\n                 | progress break_match\n                 | intro\n                 | intuition congruence\n                 | progress destruct_head'_and\n                 | solve [ apply reflexivity\n                         | apply symmetry; eassumption\n                         | eapply transitivity; eassumption\n                         | eauto ] ].\n\n  Fixpoint list_eq_refl {T} {R} {Reflexive_R:@Reflexive T R} (ls : list T) : list_eq R ls ls.\n  Proof. destruct ls; cbn; repeat split; auto. Defined.\n  Global Instance Reflexive_list_eq {T} {R} {Reflexive_R:@Reflexive T R}\n    : Reflexive (list_eq R) | 1\n    := list_eq_refl.\n\n  Lemma list_eq_sym {A B} {R1 R2 : _ -> _ -> Prop} (HR : forall v1 v2, R1 v1 v2 -> R2 v2 v1)\n    : forall v1 v2, @list_eq A B R1 v1 v2 -> list_eq R2 v2 v1.\n  Proof. induction v1; t. Qed.\n\n  Lemma list_eq_trans {A B C} {R1 R2 R3 : _ -> _ -> Prop}\n        (HR : forall v1 v2 v3, R1 v1 v2 -> R2 v2 v3 -> R3 v1 v3)\n    : forall v1 v2 v3, @list_eq A B R1 v1 v2 -> @list_eq B C R2 v2 v3 -> @list_eq A C R3 v1 v3.\n  Proof. induction v1; t. Qed.\n\n  Global Instance Transitive_list_eq {T} {R} {Transitive_R:@Transitive T R}\n    : Transitive (list_eq R) | 1 := list_eq_trans Transitive_R.\n\n  Global Instance Symmetric_list_eq {T} {R} {Symmetric_R:@Symmetric T R}\n    : Symmetric (list_eq R) | 1 := list_eq_sym Symmetric_R.\n\n  Global Instance Equivalence_list_eq {T} {R} {Equivalence_R:@Equivalence T R}\n    : Equivalence (list_eq R). Proof. split; exact _. Qed.\nEnd Relations.\n\nDefinition list_leq_to_eq {A} {x y : list A} : x = y -> list_eq eq x y.\nProof. destruct 1; reflexivity. Defined.\n\nFixpoint list_eq_to_leq {A} {x y : list A} {struct x} : list_eq eq x y -> x = y.\nProof.\n  destruct x, y; cbn; try reflexivity; destruct 1; try apply f_equal2; eauto.\nDefined.\n\nLemma list_leq_to_eq_refl {A x} : @list_leq_to_eq A x x eq_refl = reflexivity _.\nProof. destruct x; cbn; reflexivity. Qed.\n\nLemma list_eq_to_leq_refl {A x} : @list_eq_to_leq A x x (reflexivity _) = eq_refl.\nProof.\n  induction x as [|x xs IH]; cbn; rewrite ?IH; try reflexivity.\nQed.\n\nLemma list_leq_to_eq_to_leq {A x y} v : @list_eq_to_leq A x y (@list_leq_to_eq A x y v) = v.\nProof.\n  now subst; rewrite list_leq_to_eq_refl, list_eq_to_leq_refl.\nQed.\n\nLemma list_eq_to_leq_to_eq {A x y} v : @list_leq_to_eq A x y (@list_eq_to_leq A x y v) = v.\nProof.\n  revert y v.\n  induction x as [|x xs IH], y as [|y ys]; try specialize (IH ys); cbn.\n  1-3: intro H; destruct H; reflexivity.\n  intro H; destruct H as [? H]; subst; specialize (IH H).\n  cbv [list_leq_to_eq] in *; subst.\n  break_innermost_match_hyps; subst; reflexivity.\nQed.\n\nLemma UIP_nil {A} (p q : @nil A = @nil A) : p = q.\nProof.\n  rewrite <- (list_leq_to_eq_to_leq p), <- (list_leq_to_eq_to_leq q); simpl; reflexivity.\nQed.\n\nLemma invert_list_eq {A x y} (p : @list_eq A A eq x y) : { pf : x = y | list_leq_to_eq pf = p }.\nProof. eexists; apply list_eq_to_leq_to_eq. Qed.\n\nLemma invert_eq_list {A x y} (p : x = y) : { pf : @list_eq A A eq x y | list_eq_to_leq pf = p }.\nProof. eexists; apply list_leq_to_eq_to_leq. Qed.\n\nLtac destr_list_eq H :=\n  lazymatch type of H with\n  | True => first [ clear H | destruct H ]\n  | False => destruct H\n  | _ = _ /\\ _\n    => let H' := fresh in\n       destruct H as [H' H];\n       destr_list_eq H\n  | list_eq eq _ _\n    => first [ apply list_eq_to_leq in H\n             | let H' := fresh in\n               rename H into H';\n               destruct (invert_list_eq H') as [H ?]; subst H' ]\n  end.\nLtac inversion_list_step :=\n  match goal with\n  | [ H : nil = nil |- _ ] => clear H\n  | [ H : cons _ _ = nil |- _ ] => solve [ inversion H ]\n  | [ H : nil = cons _ _ |- _ ] => solve [ inversion H ]\n  | [ H : nil = nil |- _ ]\n    => assert (eq_refl = H) by apply UIP_nil; subst H\n  | [ H : cons _ _ = cons _ _ |- _ ]\n    => apply list_leq_to_eq in H; cbn [list_eq] in H;\n       destr_list_eq H\n  | [ H : cons _ _ = cons _ _ |- _ ]\n    => let H' := fresh in\n       rename H into H';\n       destruct (invert_eq_list H') as [H ?]; subst H';\n       cbn [list_eq] in H; destr_list_eq H\n  end.\n\nLtac inversion_list := repeat inversion_list_step.\n\nLemma list_bl_hetero {A B} {AB_beq : A -> B -> bool} {AB_R : A -> B -> Prop}\n      (AB_bl : forall x y, AB_beq x y = true -> AB_R x y)\n  : forall {x y},\n    list_beq_hetero AB_beq x y = true -> list_eq AB_R x y.\nProof using Type.\n  induction x, y; cbn in *; eauto; try congruence.\n  rewrite Bool.andb_true_iff; intuition eauto.\nQed.\n\nLemma list_lb_hetero {A B} {AB_beq : A -> B -> bool} {AB_R : A -> B -> Prop}\n      (AB_lb : forall x y, AB_R x y -> AB_beq x y = true)\n  : forall {x y},\n    list_eq AB_R x y -> list_beq_hetero AB_beq x y = true.\nProof using Type.\n  induction x, y; cbn in *; rewrite ?Bool.andb_true_iff; intuition (congruence || eauto).\nQed.\n\nLemma list_beq_hetero_uniform {A : Type} A_beq {x y}\n  : list_beq_hetero A_beq x y = @list_beq A A_beq x y.\nProof. destruct x, y; cbn; reflexivity. Qed.\n\nLemma list_bl_hetero_eq {A}\n      {A_beq : A -> A -> bool}\n      (A_bl : forall x y, A_beq x y = true -> x = y)\n      {x y}\n  : list_beq_hetero A_beq x y = true -> x = y.\nProof using Type. rewrite list_beq_hetero_uniform; now apply internal_list_dec_bl. Qed.\n\nLemma list_lb_hetero_eq {A}\n      {A_beq : A -> A -> bool}\n      (A_lb : forall x y, x = y -> A_beq x y = true)\n      {x y}\n  : x = y -> list_beq_hetero A_beq x y = true.\nProof using Type. rewrite list_beq_hetero_uniform; now apply internal_list_dec_lb. Qed.\n\nLemma eqlistA_bl {A eqA} {R : relation A}\n      (H : forall x y : A, eqA x y = true -> R x y)\n  : forall x y, list_beq A eqA x y = true -> eqlistA R x y.\nProof.\n  induction x, y; cbn; auto; try discriminate; constructor.\n  all: rewrite Bool.andb_true_iff in *; destruct_head'_and; eauto.\nQed.\n\nLemma eqlistA_lb {A eqA} {R : relation A}\n      (H : forall x y : A, R x y -> eqA x y = true)\n  : forall x y, eqlistA R x y -> list_beq A eqA x y = true.\nProof.\n  induction x, y; cbn; auto; try discriminate; inversion 1; subst.\n  all: rewrite Bool.andb_true_iff; eauto.\nQed.\n\nLemma nth_default_cons : forall {T} (x u0 : T) us, nth_default x (u0 :: us) 0 = u0.\nProof. auto. Qed.\n\n#[global]\nHint Rewrite @nth_default_cons : simpl_nth_default.\n#[global]\nHint Rewrite @nth_default_cons : push_nth_default.\n\nLemma nth_default_cons_S : forall {A} us (u0 : A) n d,\n  nth_default d (u0 :: us) (S n) = nth_default d us n.\nProof. boring. Qed.\n\n#[global]\nHint Rewrite @nth_default_cons_S : simpl_nth_default.\n#[global]\nHint Rewrite @nth_default_cons_S : push_nth_default.\n\nLemma nth_default_nil : forall {T} n (d : T), nth_default d nil n = d.\nProof. induction n; boring. Qed.\n\n#[global]\nHint Rewrite @nth_default_nil : simpl_nth_default.\n#[global]\nHint Rewrite @nth_default_nil : push_nth_default.\n\nLemma nth_error_nil_error : forall {A} n, nth_error (@nil A) n = None.\nProof. induction n; boring. Qed.\n\n#[global]\nHint Rewrite @nth_error_nil_error : simpl_nth_error.\n\nLtac nth_tac' :=\n  intros; simpl in *; unfold error,value in *; repeat progress (match goal with\n    | [  |- context[nth_error nil ?n] ] => rewrite nth_error_nil_error\n    | [ H: ?x = Some _  |- context[match ?x with Some _ => ?a | None => ?a end ] ] => destruct x\n    | [ H: ?x = None _  |- context[match ?x with Some _ => ?a | None => ?a end ] ] => destruct x\n    | [  |- context[match ?x with Some _ => ?a | None => ?a end ] ] => destruct x\n    | [  |- context[match nth_error ?xs ?i with Some _ => _ | None => _ end ] ] => case_eq (nth_error xs i); intros\n    | [ |- context[(if lt_dec ?a ?b then _ else _) = _] ] => destruct (lt_dec a b)\n    | [ |- context[_ = (if lt_dec ?a ?b then _ else _)] ] => destruct (lt_dec a b)\n    | [ H: context[(if lt_dec ?a ?b then _ else _) = _] |- _ ] => destruct (lt_dec a b)\n    | [ H: context[_ = (if lt_dec ?a ?b then _ else _)] |- _ ] => destruct (lt_dec a b)\n    | [ H: _ /\\ _ |- _ ] => destruct H\n    | [ H: Some _ = Some _ |- _ ] => injection H; clear H; intros; subst\n    | [ H: None = Some _  |- _ ] => inversion H\n    | [ H: Some _ = None |- _ ] => inversion H\n    | [ |- Some _ = Some _ ] => apply f_equal\n  end); eauto; try (autorewrite with list in *); try lia; eauto.\nLemma nth_error_map {A B f n l}\n  : nth_error (@map A B f l) n = option_map f (nth_error l n).\nProof. revert n; induction l, n; nth_tac'. Qed.\nLemma nth_error_map_ex : forall A B (f:A->B) i xs y,\n  nth_error (map f xs) i = Some y ->\n  exists x, nth_error xs i = Some x /\\ f x = y.\nProof. intros *; rewrite nth_error_map; edestruct nth_error; nth_tac'. Qed.\n\nLemma nth_error_seq : forall i start len,\n  nth_error (seq start len) i =\n  if lt_dec i len\n  then Some (start + i)\n  else None.\n  induction i as [|? IHi]; destruct len; nth_tac'; erewrite IHi; nth_tac'.\nQed.\n\nLemma nth_error_error_length : forall A i (xs:list A), nth_error xs i = None ->\n  i >= length xs.\nProof.\n  induction i as [|? IHi]; destruct xs; nth_tac'; try match goal with H : _ |- _ => specialize (IHi _ H) end; lia.\nQed.\n\nLemma nth_error_value_length : forall A i (xs:list A) x, nth_error xs i = Some x ->\n  i < length xs.\nProof.\n  induction i as [|? IHi]; destruct xs; nth_tac'; try match goal with H : _ |- _ => specialize (IHi _ _ H) end; lia.\nQed.\n\nLemma nth_error_length_error : forall A i (xs:list A),\n  i >= length xs ->\n  nth_error xs i = None.\nProof.\n  induction i as [|? IHi]; destruct xs; nth_tac'; rewrite IHi by lia; auto.\nQed.\nGlobal Hint Resolve nth_error_length_error : core.\n#[global]\nHint Rewrite @nth_error_length_error using lia : simpl_nth_error.\n\nLemma map_nth_default : forall (A B : Type) (f : A -> B) n x y l,\n  (n < length l) -> nth_default y (map f l) n = f (nth_default x l n).\nProof.\n  intros A B f n x y l H.\n  unfold nth_default.\n  erewrite map_nth_error.\n  reflexivity.\n  nth_tac'.\n  let H0 := match goal with H0 : _ = None |- _ => H0 end in\n  pose proof (nth_error_error_length A n l H0).\n  lia.\nQed.\n\n#[global]\nHint Rewrite @map_nth_default using lia : push_nth_default.\n\nLtac nth_tac :=\n  repeat progress (try nth_tac'; try (match goal with\n    | [ H: nth_error (map _ _) _ = Some _ |- _ ] => destruct (nth_error_map_ex _ _ _ _ _ _ H); clear H\n    | [ H: nth_error (seq _ _) _ = Some _ |- _ ] => rewrite nth_error_seq in H\n    | [H: nth_error _ _ = None |- _ ] => specialize (nth_error_error_length _ _ _ H); intro; clear H\n  end)).\n\nLemma app_cons_app_app : forall T xs (y:T) ys, xs ++ y :: ys = (xs ++ (y::nil)) ++ ys.\nProof. induction xs; boring. Qed.\n\nLemma unfold_set_nth {T} n x\n  : forall xs,\n    @set_nth T n x xs\n    = match n with\n      | O => match xs with\n             | nil => nil\n             | x'::xs' => x::xs'\n             end\n      | S n' =>  match xs with\n                 | nil => nil\n                 | x'::xs' => x'::set_nth n' x xs'\n                 end\n      end.\nProof.\n  induction n; destruct xs; reflexivity.\nQed.\n\nLemma simpl_set_nth_0 {T} x\n  : forall xs,\n    @set_nth T 0 x xs\n    = match xs with\n      | nil => nil\n      | x'::xs' => x::xs'\n      end.\nProof. intro; rewrite unfold_set_nth; reflexivity. Qed.\n\nLemma simpl_set_nth_S {T} x n\n  : forall xs,\n    @set_nth T (S n) x xs\n    = match xs with\n      | nil => nil\n      | x'::xs' => x'::set_nth n x xs'\n      end.\nProof. intro; rewrite unfold_set_nth; reflexivity. Qed.\n\n#[global]\nHint Rewrite @simpl_set_nth_S @simpl_set_nth_0 : simpl_set_nth.\n\nLemma update_nth_ext {T} f g n\n  : forall xs, (forall x, nth_error xs n = Some x -> f x = g x)\n               -> @update_nth T n f xs = @update_nth T n g xs.\nProof.\n  induction n as [|n IHn]; destruct xs; simpl; intros H;\n    try rewrite IHn; try rewrite H;\n      try congruence; trivial.\nQed.\n\nGlobal Instance update_nth_Proper {T}\n  : Proper (eq ==> pointwise_relation _ eq ==> eq ==> eq) (@update_nth T).\nProof. repeat intro; subst; apply update_nth_ext; trivial. Qed.\n\nGlobal Instance update_nth_Proper_eq {A} : Proper (eq ==> (eq ==> eq) ==> eq ==> eq) (@update_nth A) | 1.\nProof. repeat intro; subst; apply update_nth_Proper; repeat intro; eauto. Qed.\n\nLemma update_nth_id_eq_specific {T} f n\n  : forall (xs : list T) (H : forall x, nth_error xs n = Some x -> f x = x),\n    update_nth n f xs = xs.\nProof.\n  induction n as [|n IHn]; destruct xs; simpl; intros H;\n    try rewrite IHn; try rewrite H; unfold value in *;\n      try congruence; assumption.\nQed.\n\n#[global]\nHint Rewrite @update_nth_id_eq_specific using congruence : simpl_update_nth.\n\nLemma update_nth_id_eq : forall {T} f (H : forall x, f x = x) n (xs : list T),\n    update_nth n f xs = xs.\nProof. intros; apply update_nth_id_eq_specific; trivial. Qed.\n\n#[global]\nHint Rewrite @update_nth_id_eq using congruence : simpl_update_nth.\n\nLemma update_nth_id : forall {T} n (xs : list T),\n    update_nth n (fun x => x) xs = xs.\nProof. intros; apply update_nth_id_eq; trivial. Qed.\n\n#[global]\nHint Rewrite @update_nth_id : simpl_update_nth.\n\nLemma nth_update_nth : forall m {T} (xs:list T) (n:nat) (f:T -> T),\n  nth_error (update_nth m f xs) n =\n  if eq_nat_dec n m\n  then option_map f (nth_error xs n)\n  else nth_error xs n.\nProof.\n  induction m as [|? IHm].\n  { destruct n, xs; auto. }\n  { destruct xs, n; intros; simpl; auto;\n      [ | rewrite IHm ]; clear IHm;\n        edestruct eq_nat_dec; reflexivity. }\nQed.\n\n#[global]\nHint Rewrite @nth_update_nth : push_nth_error.\n#[global]\nHint Rewrite <- @nth_update_nth : pull_nth_error.\n\nLemma length_update_nth : forall {T} i f (xs:list T), length (update_nth i f xs) = length xs.\nProof.\n  induction i, xs; boring.\nQed.\n\n#[global]\nHint Rewrite @length_update_nth : distr_length.\n\nLemma nth_set_nth : forall m {T} (xs:list T) (n:nat) x,\n  nth_error (set_nth m x xs) n =\n  if eq_nat_dec n m\n  then (if lt_dec n (length xs) then Some x else None)\n  else nth_error xs n.\nProof.\n  intros m T xs n x; unfold set_nth; rewrite nth_update_nth.\n  destruct (nth_error xs n) eqn:?, (lt_dec n (length xs)) as [p|p];\n    rewrite <- nth_error_Some in p;\n    solve [ reflexivity\n          | exfalso; apply p; congruence ].\nQed.\n\n#[global]\nHint Rewrite @nth_set_nth : push_nth_error.\n\nLemma length_set_nth : forall {T} i x (xs:list T), length (set_nth i x xs) = length xs.\nProof. intros; apply length_update_nth. Qed.\n\n#[global]\nHint Rewrite @length_set_nth : distr_length.\n\nLemma nth_error_length_exists_value : forall {A} (i : nat) (xs : list A),\n  (i < length xs)%nat -> exists x, nth_error xs i = Some x.\nProof.\n  induction i, xs; boring; try lia.\nQed.\n\nLemma nth_error_length_not_error : forall {A} (i : nat) (xs : list A),\n  nth_error xs i = None -> (i < length xs)%nat -> False.\nProof.\n  intros A i xs H H0.\n  destruct (nth_error_length_exists_value i xs); intuition; congruence.\nQed.\n\nLemma nth_error_value_eq_nth_default : forall {T} i (x : T) xs,\n  nth_error xs i = Some x -> forall d, nth_default d xs i = x.\nProof.\n  unfold nth_default; boring.\nQed.\n\n#[global]\nHint Rewrite @nth_error_value_eq_nth_default using eassumption : simpl_nth_default.\n\nLemma skipn0 : forall {T} (xs:list T), skipn 0 xs = xs.\nProof. auto. Qed.\n\nLemma destruct_repeat : forall {A} xs y, (forall x : A, In x xs -> x = y) ->\n  xs = nil \\/ exists xs', xs = y :: xs' /\\ (forall x : A, In x xs' -> x = y).\nProof.\n  destruct xs as [|? xs]; intros; try tauto.\n  right.\n  exists xs; split.\n  + f_equal; auto using in_eq.\n  + intros; auto using in_cons.\nQed.\n\nLemma splice_nth_equiv_update_nth : forall {T} n f d (xs:list T),\n  splice_nth n (f (nth_default d xs n)) xs =\n  if lt_dec n (length xs)\n  then update_nth n f xs\n  else xs ++ (f d)::nil.\nProof.\n  induction n, xs; boring_list; break_match; auto; lia.\nQed.\n\nLemma splice_nth_equiv_update_nth_update : forall {T} n f d (xs:list T),\n  n < length xs ->\n  splice_nth n (f (nth_default d xs n)) xs = update_nth n f xs.\nProof.\n  intros.\n  rewrite splice_nth_equiv_update_nth; break_match; auto; lia.\nQed.\n\nLemma splice_nth_equiv_update_nth_snoc : forall {T} n f d (xs:list T),\n  n >= length xs ->\n  splice_nth n (f (nth_default d xs n)) xs = xs ++ (f d)::nil.\nProof.\n  intros.\n  rewrite splice_nth_equiv_update_nth; break_match; auto; lia.\nQed.\n\nDefinition IMPOSSIBLE {T} : list T. exact nil. Qed.\n\nLtac remove_nth_error :=\n  repeat match goal with\n         | _ => exfalso; solve [ eauto using @nth_error_length_not_error ]\n         | [ |- context[match nth_error ?ls ?n with _ => _ end] ]\n           => destruct (nth_error ls n) eqn:?\n         end.\n\nLemma update_nth_equiv_splice_nth: forall {T} n f (xs:list T),\n  update_nth n f xs =\n  if lt_dec n (length xs)\n  then match nth_error xs n with\n       | Some v => splice_nth n (f v) xs\n       | None => IMPOSSIBLE\n       end\n  else xs.\nProof.\n  induction n as [|? IHn]; destruct xs; intros;\n    autorewrite with simpl_update_nth simpl_nth_default in *; simpl in *;\n      try (erewrite IHn; clear IHn); auto.\n  repeat break_match; remove_nth_error; try reflexivity; try lia.\nQed.\n\nLemma splice_nth_equiv_set_nth : forall {T} n x (xs:list T),\n  splice_nth n x xs =\n  if lt_dec n (length xs)\n  then set_nth n x xs\n  else xs ++ x::nil.\nProof. intros T n x xs; rewrite splice_nth_equiv_update_nth with (f := fun _ => x); auto. Qed.\n\nLemma splice_nth_equiv_set_nth_set : forall {T} n x (xs:list T),\n  n < length xs ->\n  splice_nth n x xs = set_nth n x xs.\nProof. intros T n x xs H; rewrite splice_nth_equiv_update_nth_update with (f := fun _ => x); auto. Qed.\n\nLemma splice_nth_equiv_set_nth_snoc : forall {T} n x (xs:list T),\n  n >= length xs ->\n  splice_nth n x xs = xs ++ x::nil.\nProof. intros T n x xs H; rewrite splice_nth_equiv_update_nth_snoc with (f := fun _ => x); auto. Qed.\n\nLemma set_nth_equiv_splice_nth: forall {T} n x (xs:list T),\n  set_nth n x xs =\n  if lt_dec n (length xs)\n  then splice_nth n x xs\n  else xs.\nProof.\n  intros T n x xs; unfold set_nth; rewrite update_nth_equiv_splice_nth with (f := fun _ => x); auto.\n  repeat break_match; remove_nth_error; trivial.\nQed.\n\nLemma combine_update_nth : forall {A B} n f g (xs:list A) (ys:list B),\n  combine (update_nth n f xs) (update_nth n g ys) =\n  update_nth n (fun xy => (f (fst xy), g (snd xy))) (combine xs ys).\nProof.\n  induction n as [|? IHn]; destruct xs, ys; simpl; try rewrite IHn; reflexivity.\nQed.\n\n(* grumble, grumble, [rewrite] is bad at inferring the identity function, and constant functions *)\nLtac rewrite_rev_combine_update_nth :=\n  let lem := match goal with\n             | [ |- context[update_nth ?n (fun xy => (@?f xy, @?g xy)) (combine ?xs ?ys)] ]\n               => let f := match (eval cbv [fst] in (fun y x => f (x, y))) with\n                           | fun _ => ?f => f\n                           end in\n                  let g := match (eval cbv [snd] in (fun x y => g (x, y))) with\n                           | fun _ => ?g => g\n                           end in\n                  constr:(@combine_update_nth _ _ n f g xs ys)\n             end in\n  rewrite <- lem.\n\nLemma combine_update_nth_l : forall {A B} n (f : A -> A) xs (ys:list B),\n  combine (update_nth n f xs) ys =\n  update_nth n (fun xy => (f (fst xy), snd xy)) (combine xs ys).\nProof.\n  intros ??? f xs ys.\n  etransitivity; [ | apply combine_update_nth with (g := fun x => x) ].\n  rewrite update_nth_id; reflexivity.\nQed.\n\nLemma combine_update_nth_r : forall {A B} n (g : B -> B) (xs:list A) (ys:list B),\n  combine xs (update_nth n g ys) =\n  update_nth n (fun xy => (fst xy, g (snd xy))) (combine xs ys).\nProof.\n  intros ??? g xs ys.\n  etransitivity; [ | apply combine_update_nth with (f := fun x => x) ].\n  rewrite update_nth_id; reflexivity.\nQed.\n\nLemma combine_set_nth : forall {A B} n (x:A) xs (ys:list B),\n  combine (set_nth n x xs) ys =\n    match nth_error ys n with\n    | None => combine xs ys\n    | Some y => set_nth n (x,y) (combine xs ys)\n    end.\nProof.\n  intros A B n x xs ys; unfold set_nth; rewrite combine_update_nth_l.\n  nth_tac;\n    [ repeat rewrite_rev_combine_update_nth; apply f_equal2\n    | assert (nth_error (combine xs ys) n = None)\n      by (apply nth_error_None; rewrite combine_length; lia * ) ];\n    autorewrite with simpl_update_nth; reflexivity.\nQed.\n\nLemma nth_error_value_In : forall {T} n xs (x:T),\n  nth_error xs n = Some x -> In x xs.\nProof.\n  induction n; destruct xs; nth_tac.\nQed.\n\nLemma In_nth_error_value : forall {T} xs (x:T),\n  In x xs -> exists n, nth_error xs n = Some x.\nProof.\n  induction xs as [|?? IHxs]; nth_tac; destruct_head or; subst.\n  - exists 0; reflexivity.\n  - edestruct IHxs as [x0]; eauto. exists (S x0). eauto.\nQed.\n\nLemma nth_value_index : forall {T} i xs (x:T),\n  nth_error xs i = Some x -> In i (seq 0 (length xs)).\nProof.\n  induction i as [|? IHi]; destruct xs; nth_tac; right.\n  rewrite <- seq_shift; apply in_map; eapply IHi; eauto.\nQed.\n\nLemma nth_error_app : forall {T} n (xs ys:list T), nth_error (xs ++ ys) n =\n  if lt_dec n (length xs)\n  then nth_error xs n\n  else nth_error ys (n - length xs).\nProof.\n  induction n as [|n IHn]; destruct xs as [|? xs]; nth_tac;\n    rewrite IHn; destruct (lt_dec n (length xs)); trivial; lia.\nQed.\n\nLemma nth_default_app : forall {T} n x (xs ys:list T), nth_default x (xs ++ ys) n =\n  if lt_dec n (length xs)\n  then nth_default x xs n\n  else nth_default x ys (n - length xs).\nProof.\n  intros T n x xs ys.\n  unfold nth_default.\n  rewrite nth_error_app.\n  destruct (lt_dec n (length xs)); auto.\nQed.\n\n#[global]\nHint Rewrite @nth_default_app : push_nth_default.\n\nLemma combine_truncate_r : forall {A B} (xs : list A) (ys : list B),\n  combine xs ys = combine xs (firstn (length xs) ys).\nProof.\n  induction xs; destruct ys; boring.\nQed.\n\nLemma combine_truncate_l : forall {A B} (xs : list A) (ys : list B),\n  combine xs ys = combine (firstn (length ys) xs) ys.\nProof.\n  induction xs; destruct ys; boring.\nQed.\n\nLemma combine_app_samelength : forall {A B} (xs xs':list A) (ys ys':list B),\n  length xs = length ys ->\n  combine (xs ++ xs') (ys ++ ys') = combine xs ys ++ combine xs' ys'.\nProof.\n  induction xs, xs', ys, ys'; boring; lia.\nQed.\n\nLemma map_fst_combine {A B} (xs:list A) (ys:list B) : List.map fst (List.combine xs ys) = List.firstn (length ys) xs.\nProof.\n  revert xs; induction ys; destruct xs; simpl; solve [ trivial | congruence ].\nQed.\n\nLemma map_snd_combine {A B} (xs:list A) (ys:list B) : List.map snd (List.combine xs ys) = List.firstn (length xs) ys.\nProof.\n  revert xs; induction ys; destruct xs; simpl; solve [ trivial | congruence ].\nQed.\n#[global]\nHint Rewrite @map_fst_combine @map_snd_combine : push_map.\n\nLemma skipn_nil : forall {A} n, skipn n nil = @nil A.\nProof. destruct n; auto. Qed.\n\n#[global]\nHint Rewrite @skipn_nil : simpl_skipn.\n#[global]\nHint Rewrite @skipn_nil : push_skipn.\n\nLemma skipn_0 : forall {A} xs, @skipn A 0 xs = xs.\nProof. reflexivity. Qed.\n\n#[global]\nHint Rewrite @skipn_0 : simpl_skipn.\n#[global]\nHint Rewrite @skipn_0 : push_skipn.\n\nLemma skipn_cons_S : forall {A} n x xs, @skipn A (S n) (x::xs) = @skipn A n xs.\nProof. reflexivity. Qed.\n\n#[global]\nHint Rewrite @skipn_cons_S : simpl_skipn.\n#[global]\nHint Rewrite @skipn_cons_S : push_skipn.\n\nLemma skipn_app : forall {A} n (xs ys : list A),\n  skipn n (xs ++ ys) = skipn n xs ++ skipn (n - length xs) ys.\nProof.\n  induction n, xs, ys; boring.\nQed.\n\n#[global]\nHint Rewrite @skipn_app : push_skipn.\n\nLemma skipn_skipn {A} n1 n2 (ls : list A)\n  : skipn n2 (skipn n1 ls) = skipn (n1 + n2) ls.\nProof.\n  revert n2 ls; induction n1, ls;\n    simpl; autorewrite with simpl_skipn;\n      boring.\nQed.\n\n#[global]\nHint Rewrite @skipn_skipn : simpl_skipn.\n#[global]\nHint Rewrite <- @skipn_skipn : push_skipn.\n#[global]\nHint Rewrite @skipn_skipn : pull_skipn.\n\nLemma skipn_firstn {A} (ls : list A) n m\n  : skipn n (firstn m ls) = firstn (m - n) (skipn n ls).\nProof.\n  revert n m; induction ls, m, n; simpl; autorewrite with simpl_skipn simpl_firstn; boring_list.\nQed.\nLemma firstn_skipn_add {A} (ls : list A) n m\n  : firstn n (skipn m ls) = skipn m (firstn (m + n) ls).\nProof.\n  revert n m; induction ls, m; simpl; autorewrite with simpl_skipn simpl_firstn; boring_list.\nQed.\nLemma firstn_skipn_add' {A} (ls : list A) n m\n  : firstn n (skipn m ls) = skipn m (firstn (n + m) ls).\nProof. rewrite firstn_skipn_add; do 2 f_equal; auto with arith. Qed.\n#[global]\nHint Rewrite <- @firstn_skipn_add @firstn_skipn_add' : simpl_firstn.\n#[global]\nHint Rewrite <- @firstn_skipn_add @firstn_skipn_add' : simpl_skipn.\n\nLemma firstn_app_inleft : forall {A} n (xs ys : list A), (n <= length xs)%nat ->\n  firstn n (xs ++ ys) = firstn n xs.\nProof.\n  induction n, xs, ys; boring; try lia.\nQed.\n\n#[global]\nHint Rewrite @firstn_app_inleft using solve [ distr_length ] : simpl_firstn.\n#[global]\nHint Rewrite @firstn_app_inleft using solve [ distr_length ] : push_firstn.\n\nLemma skipn_app_inleft : forall {A} n (xs ys : list A), (n <= length xs)%nat ->\n  skipn n (xs ++ ys) = skipn n xs ++ ys.\nProof.\n  induction n, xs, ys; boring; try lia.\nQed.\n\n#[global]\nHint Rewrite @skipn_app_inleft using solve [ distr_length ] : push_skipn.\n\nLemma firstn_map : forall {A B} (f : A -> B) n (xs : list A), firstn n (map f xs) = map f (firstn n xs).\nProof. induction n, xs; boring. Qed.\n\n#[global]\nHint Rewrite @firstn_map : push_firstn.\n#[global]\nHint Rewrite <- @firstn_map : pull_firstn.\n\nLemma skipn_map : forall {A B} (f : A -> B) n (xs : list A), skipn n (map f xs) = map f (skipn n xs).\nProof. induction n, xs; boring. Qed.\n\n#[global]\nHint Rewrite @skipn_map : push_skipn.\n#[global]\nHint Rewrite <- @skipn_map : pull_skipn.\n\nLemma firstn_all : forall {A} n (xs:list A), n = length xs -> firstn n xs = xs.\nProof.\n  induction n, xs; boring; lia.\nQed.\n\n#[global]\nHint Rewrite @firstn_all using solve [ distr_length ] : simpl_firstn.\n#[global]\nHint Rewrite @firstn_all using solve [ distr_length ] : push_firstn.\n\nLemma skipn_all : forall {T} n (xs:list T),\n  (n >= length xs)%nat ->\n  skipn n xs = nil.\nProof.\n  induction n, xs; boring; lia.\nQed.\n\n#[global]\nHint Rewrite @skipn_all using solve [ distr_length ] : simpl_skipn.\n#[global]\nHint Rewrite @skipn_all using solve [ distr_length ] : push_skipn.\n\nLemma firstn_app_sharp : forall {A} n (l l': list A),\n  length l = n ->\n  firstn n (l ++ l') = l.\nProof.\n  intros.\n  rewrite firstn_app_inleft; auto using firstn_all; lia.\nQed.\n\n#[global]\nHint Rewrite @firstn_app_sharp using solve [ distr_length ] : simpl_firstn.\n#[global]\nHint Rewrite @firstn_app_sharp using solve [ distr_length ] : push_firstn.\n\nLemma skipn_app_sharp : forall {A} n (l l': list A),\n  length l = n ->\n  skipn n (l ++ l') = l'.\nProof.\n  intros.\n  rewrite skipn_app_inleft; try rewrite skipn_all; auto; lia.\nQed.\n\n#[global]\nHint Rewrite @skipn_app_sharp using solve [ distr_length ] : simpl_skipn.\n#[global]\nHint Rewrite @skipn_app_sharp using solve [ distr_length ] : push_skipn.\n\nLemma skipn_length : forall {A} n (xs : list A),\n  length (skipn n xs) = (length xs - n)%nat.\nProof.\n  induction n, xs; boring.\nQed.\n\n#[global]\nHint Rewrite @skipn_length : distr_length.\n\nLemma length_cons : forall {T} (x:T) xs, length (x::xs) = S (length xs).\n  reflexivity.\nQed.\n\n#[global]\nHint Rewrite @length_cons : distr_length.\n\nLemma length_cons_full {T} n (x:list T) (t:T) (H: length (t :: x) = S n)\n  : length x = n.\nProof. distr_length. Qed.\n\nLemma cons_length : forall A (xs : list A) a, length (a :: xs) = S (length xs).\nProof.\n  auto.\nQed.\n\nLemma length0_nil : forall {A} (xs : list A), length xs = 0%nat -> xs = nil.\nProof.\n  induction xs; boring; discriminate.\nQed.\n\nLemma length_tl {A} ls : length (@tl A ls) = (length ls - 1)%nat.\nProof. destruct ls; cbn [tl length]; lia. Qed.\n#[global]\nHint Rewrite @length_tl : distr_length.\n\nLemma length_snoc {A : Type} (l : list A) a : length (l ++ [a]) = S (length l).\nProof. simpl_list; boring. Qed.\n\n#[global]\nHint Rewrite @length_snoc : distr_length.\n\nLemma combine_cons : forall {A B} a b (xs:list A) (ys:list B),\n  combine (a :: xs) (b :: ys) = (a,b) :: combine xs ys.\nProof. reflexivity. Qed.\n#[global]\nHint Rewrite @combine_cons : push_combine.\n\nLemma firstn_combine : forall {A B} n (xs:list A) (ys:list B),\n  firstn n (combine xs ys) = combine (firstn n xs) (firstn n ys).\nProof.\n  induction n, xs, ys; boring.\nQed.\n\n#[global]\nHint Rewrite @firstn_combine : push_firstn.\n#[global]\nHint Rewrite <- @firstn_combine : pull_firstn.\n\nLemma combine_nil_r : forall {A B} (xs:list A),\n  combine xs (@nil B) = nil.\nProof.\n  induction xs; boring.\nQed.\n#[global]\nHint Rewrite @combine_nil_r : push_combine.\n\nLemma combine_snoc {A B} xs : forall ys x y,\n    length xs = length ys ->\n    @combine A B (xs ++ (x :: nil)) (ys ++ (y :: nil)) = combine xs ys ++ ((x, y) :: nil).\nProof.\n  induction xs; intros; destruct ys; distr_length; cbn;\n    try rewrite IHxs by lia; reflexivity.\nQed.\n#[global]\nHint Rewrite @combine_snoc using (solve [distr_length]) : push_combine.\n\nLemma skipn_combine : forall {A B} n (xs:list A) (ys:list B),\n  skipn n (combine xs ys) = combine (skipn n xs) (skipn n ys).\nProof.\n  induction n, xs, ys; boring.\n  rewrite combine_nil_r; reflexivity.\nQed.\n\n#[global]\nHint Rewrite @skipn_combine : push_skipn.\n#[global]\nHint Rewrite <- @skipn_combine : pull_skipn.\n\nLemma break_list_last: forall {T} (xs:list T),\n  xs = nil \\/ exists xs' y, xs = xs' ++ y :: nil.\nProof.\n  destruct xs using rev_ind; auto.\n  right; do 2 eexists; auto.\nQed.\n\nLemma break_list_first: forall {T} (xs:list T),\n  xs = nil \\/ exists x xs', xs = x :: xs'.\nProof.\n  destruct xs; auto.\n  right; do 2 eexists; auto.\nQed.\n\nLemma list012 : forall {T} (xs:list T),\n  xs = nil\n  \\/ (exists x, xs = x::nil)\n  \\/ (exists x xs' y, xs = x::xs'++y::nil).\nProof.\n  destruct xs as [|? xs]; auto.\n  right.\n  destruct xs using rev_ind. {\n    left; eexists; auto.\n  } {\n    right; repeat eexists; auto.\n  }\nQed.\n\nLemma nil_length0 : forall {T}, length (@nil T) = 0%nat.\nProof.\n  auto.\nQed.\n\n#[global]\nHint Rewrite @nil_length0 : distr_length.\n\nLemma nth_error_Some_nth_default : forall {T} i x (l : list T), (i < length l)%nat ->\n  nth_error l i = Some (nth_default x l i).\nProof.\n  intros ? ? ? ? i_lt_length.\n  destruct (nth_error_length_exists_value _ _ i_lt_length) as [k nth_err_k].\n  unfold nth_default.\n  rewrite nth_err_k.\n  reflexivity.\nQed.\n\nLemma update_nth_cons : forall {T} f (u0 : T) us, update_nth 0 f (u0 :: us) = (f u0) :: us.\nProof. reflexivity. Qed.\n\n#[global]\nHint Rewrite @update_nth_cons : simpl_update_nth.\n\nLemma set_nth_cons : forall {T} (x u0 : T) us, set_nth 0 x (u0 :: us) = x :: us.\nProof. intros; apply update_nth_cons. Qed.\n\n#[global]\nHint Rewrite @set_nth_cons : simpl_set_nth.\n\nLemma cons_update_nth : forall {T} n f (y : T) us,\n  y :: update_nth n f us = update_nth (S n) f (y :: us).\nProof.\n  induction n; boring.\nQed.\n\n#[global]\nHint Rewrite <- @cons_update_nth : simpl_update_nth.\n\nLemma update_nth_nil : forall {T} n f, update_nth n f (@nil T) = @nil T.\nProof.\n  induction n; boring.\nQed.\n\n#[global]\nHint Rewrite @update_nth_nil : simpl_update_nth.\n\nLemma cons_set_nth : forall {T} n (x y : T) us,\n  y :: set_nth n x us = set_nth (S n) x (y :: us).\nProof. intros; apply cons_update_nth. Qed.\n\n#[global]\nHint Rewrite <- @cons_set_nth : simpl_set_nth.\n\nLemma set_nth_nil : forall {T} n (x : T), set_nth n x nil = nil.\nProof. intros; apply update_nth_nil. Qed.\n\n#[global]\nHint Rewrite @set_nth_nil : simpl_set_nth.\n\nLemma skipn_nth_default : forall {T} n us (d : T), (n < length us)%nat ->\n skipn n us = nth_default d us n :: skipn (S n) us.\nProof.\n  induction n as [|n IHn]; destruct us as [|? us]; intros d H; nth_tac.\n  rewrite (IHn us d) at 1 by lia.\n  nth_tac.\nQed.\n\nLemma nth_default_out_of_bounds : forall {T} n us (d : T), (n >= length us)%nat ->\n  nth_default d us n = d.\nProof.\n  induction n as [|n IHn]; unfold nth_default; nth_tac;\n    let us' := match goal with us : list _ |- _ => us end in\n    destruct us' as [|? us]; nth_tac.\n  assert (n >= length us)%nat by lia.\n  pose proof (nth_error_length_error _ n us).\n  specialize_by_assumption.\n  rewrite_hyp * in *.\n  congruence.\nQed.\n\n#[global]\nHint Rewrite @nth_default_out_of_bounds using lia : simpl_nth_default.\n\nLtac nth_error_inbounds :=\n  match goal with\n  | [ |- context[match nth_error ?xs ?i with Some _ => _ | None => _ end ] ] =>\n    case_eq (nth_error xs i);\n    match goal with\n      | [ |- forall _, nth_error xs i = Some _ -> _ ] =>\n          let x := fresh \"x\" in\n          let H := fresh \"H\" in\n          intros x H;\n          repeat progress erewrite H;\n          repeat progress erewrite (nth_error_value_eq_nth_default i xs x); auto\n      | [ |- nth_error xs i = None -> _ ] =>\n          let H := fresh \"H\" in\n          intros H;\n          destruct (nth_error_length_not_error _ _ H);\n          try solve [distr_length]\n    end;\n    idtac\n  end.\nLtac set_nth_inbounds :=\n  match goal with\n  | [ |- context[set_nth ?i ?x ?xs] ] =>\n    rewrite (set_nth_equiv_splice_nth i x xs);\n    destruct (lt_dec i (length xs));\n    match goal with\n    | [ H : ~ (i < (length xs))%nat |- _ ] => destruct H\n    | [ H :   (i < (length xs))%nat |- _ ] => try solve [distr_length]\n    end\n  end.\nLtac update_nth_inbounds :=\n  match goal with\n  | [ |- context[update_nth ?i ?f ?xs] ] =>\n    rewrite (update_nth_equiv_splice_nth i f xs);\n    destruct (lt_dec i (length xs));\n    match goal with\n    | [ H : ~ (i < (length xs))%nat |- _ ] => destruct H\n    | [ H :   (i < (length xs))%nat |- _ ] => remove_nth_error; try solve [distr_length]\n    end\n  end.\n\nLtac nth_inbounds := nth_error_inbounds || set_nth_inbounds || update_nth_inbounds.\n\nDefinition nth_dep {A} (ls : list A) (n : nat) (pf : n < length ls) : A.\nProof.\n  refine (match nth_error ls n as v return nth_error ls n = v -> A with\n          | Some v => fun _ => v\n          | None => fun bad => match _ : False with end\n          end eq_refl).\n  apply (proj1 (@nth_error_None _ _ _)) in bad; generalize dependent (length ls); clear.\n  abstract (intros; lia).\nDefined.\n\nLemma nth_error_nth_dep {A} ls n pf : nth_error ls n = Some (@nth_dep A ls n pf).\nProof.\n  unfold nth_dep.\n  generalize dependent (@nth_error_None A ls n).\n  edestruct nth_error; boring.\nQed.\n\nLemma nth_default_nth_dep {A} d ls n pf : nth_default d ls n = @nth_dep A ls n pf.\nProof.\n  unfold nth_dep.\n  generalize dependent (@nth_error_None A ls n).\n  destruct (nth_error ls n) eqn:?; boring.\n  erewrite nth_error_value_eq_nth_default by eassumption; reflexivity.\nQed.\n\nLemma nth_default_in_bounds : forall {T} (d' d : T) n us, (n < length us)%nat ->\n  nth_default d us n = nth_default d' us n.\nProof.\n  intros; now unshelve erewrite !nth_default_nth_dep.\nQed.\n\nGlobal Hint Resolve nth_default_in_bounds : simpl_nth_default.\n\nLemma cons_eq_head : forall {T} (x y:T) xs ys, x::xs = y::ys -> x=y.\nProof.\n  intros; congruence.\nQed.\nLemma cons_eq_tail : forall {T} (x y:T) xs ys, x::xs = y::ys -> xs=ys.\nProof.\n  intros; congruence.\nQed.\n\nLemma map_nth_default_always {A B} (f : A -> B) (n : nat) (x : A) (l : list A)\n  : nth_default (f x) (map f l) n = f (nth_default x l n).\nProof.\n  revert n; induction l; simpl; intro n; destruct n; [ try reflexivity.. ].\n  nth_tac.\nQed.\n\n#[global]\nHint Rewrite @map_nth_default_always : push_nth_default.\n\nLemma map_S_seq {A} (f:nat->A) len : forall start,\n  List.map (fun i => f (S i)) (seq start len) = List.map f (seq (S start) len).\nProof. induction len as [|len IHlen]; intros; simpl; rewrite ?IHlen; reflexivity. Qed.\n\nLemma seq_snoc len : forall start, seq start (S len) = seq start len ++ ((start + len)%nat :: nil).\nProof.\n  induction len; intros.\n  { cbv [seq app]. autorewrite with natsimplify; reflexivity. }\n  { remember (S len); simpl seq.\n      rewrite (IHlen (S start)); subst; simpl seq.\n      rewrite Nat.add_succ_r; reflexivity. }\nQed.\n\nLemma seq_len_0 a : seq a 0 = nil. Proof. reflexivity. Qed.\nLemma seq_add start a b : seq start (a + b) = seq start a ++ seq (start + a) b.\nProof.\n  revert start b; induction a as [|a IHa]; cbn; intros start b.\n  { f_equal; lia. }\n  { rewrite IHa; do 3 f_equal; lia. }\nQed.\n\nLemma map_seq_ext {A} (f g : nat -> A) (n m k : nat)\n      (H : forall i : nat, n <= i <= m + k -> f i = g (i + (m - n))%nat)\n      (Hnm : n <= m) :\n  map f (seq n k) = map g (seq m k).\nProof.\n  generalize dependent m; generalize dependent n; induction k as [|k IHk]; intros; simpl.\n  - reflexivity.\n  - simpl; rewrite H by lia; replace (n + (m - n))%nat with m by lia.\n    rewrite (IHk (S n) (S m)); [reflexivity| |lia].\n    intros; rewrite Nat.sub_succ; apply H; lia. Qed.\n\nLemma map_seq_pred n m :\n  seq n m = map (fun i => (i - 1)%nat) (seq (S n) m).\nProof. rewrite <- map_id at 1; apply map_seq_ext; intros; lia. Qed.\n\nLemma map_seq_succ n m :\n  seq (S n) m = map (fun i => (i + 1)%nat) (seq n m).\nProof. rewrite <- map_id at 1; symmetry; apply map_seq_ext; intros; lia. Qed.\n\nLemma fold_right_and_Truth_forall_In_iff : forall {T} (l : list T) (P : T -> Prop) (Tr : Prop),\n    (Tr /\\ forall x, In x l -> P x) <-> fold_right and Tr (map P l).\nProof.\n  induction l as [|?? IHl]; intros; simpl; try tauto.\n  rewrite <- IHl by assumption.\n  intuition (subst; auto).\nQed.\n\nLemma fold_right_and_True_forall_In_iff : forall {T} (l : list T) (P : T -> Prop),\n  (forall x, In x l -> P x) <-> fold_right and True (map P l).\nProof.\n  intros; rewrite <- fold_right_and_Truth_forall_In_iff; tauto.\nQed.\n\nLemma fold_right_invariant : forall {A B} P (f: A -> B -> B) l x,\n  P x -> (forall y, In y l -> forall z, P z -> P (f y z)) ->\n  P (fold_right f x l).\nProof.\n  induction l as [|a l IHl]; intros ? ? step; auto.\n  simpl.\n  apply step; try apply in_eq.\n  apply IHl; auto.\n  intros y in_y_l.\n  apply (in_cons a) in in_y_l.\n  auto.\nQed.\n\nLemma fold_left_and_Truth_forall_In_iff : forall {T} (l : list T) (P : T -> Prop) (Tr : Prop),\n    (Tr /\\ forall x, In x l -> P x) <-> fold_left and (map P l) Tr.\nProof.\n  induction l as [|?? IHl]; intros; simpl; try tauto.\n  rewrite <- IHl.\n  intuition (subst; auto).\nQed.\n\nLemma fold_left_and_True_forall_In_iff : forall {T} (l : list T) (P : T -> Prop),\n  (forall x, In x l -> P x) <-> fold_left and (map P l) True.\nProof.\n  intros; rewrite <- fold_left_and_Truth_forall_In_iff; tauto.\nQed.\n\nLemma fold_left_invariant : forall {A B} P (f: B -> A -> B) l x,\n  P x -> (forall y, In y l -> forall z, P z -> P (f z y)) ->\n  P (fold_left f l x).\nProof.\n  pose proof in_rev.\n  split_iff.\n  intros; rewrite <- fold_left_rev_right; eapply fold_right_invariant;\n    eauto.\nQed.\n\nLemma In_firstn : forall {T} n l (x : T), In x (firstn n l) -> In x l.\nProof.\n  induction n; destruct l; boring.\nQed.\n\nLemma In_skipn : forall {T} n l (x : T), In x (skipn n l) -> In x l.\nProof.\n  induction n; destruct l; boring.\nQed.\n\nLemma In_firstn_skipn_split {T} n (x : T)\n  : forall l, In x l <-> In x (firstn n l) \\/ In x (skipn n l).\nProof.\n  intro l; split; revert l; induction n; destruct l; boring.\n  match goal with\n  | [ IH : forall l, In ?x l -> _ \\/ _, H' : In ?x ?ls |- _ ]\n    => destruct (IH _ H')\n  end; auto.\nQed.\n\nLemma firstn_firstn_min : forall {A} m n (l : list A),\n    firstn n (firstn m l) = firstn (min n m) l.\nProof.\n  induction m as [|? IHm]; destruct n; intros l; try lia; auto.\n  destruct l; auto.\n  simpl.\n  f_equal.\n  apply IHm; lia.\nQed.\n\nLemma firstn_firstn : forall {A} m n (l : list A), (n <= m)%nat ->\n  firstn n (firstn m l) = firstn n l.\nProof.\n  intros A m n l H; rewrite firstn_firstn_min.\n  apply Min.min_case_strong; intro; [ reflexivity | ].\n  assert (n = m) by lia; subst; reflexivity.\nQed.\n\n#[global]\nHint Rewrite @firstn_firstn using lia : push_firstn.\n\nLemma firstn_succ : forall {A} (d : A) n l, (n < length l)%nat ->\n  firstn (S n) l = (firstn n l) ++ nth_default d l n :: nil.\nProof.\n  intros A d; induction n as [|? IHn]; destruct l; rewrite ?(@nil_length0 A); intros; try lia.\n  + rewrite nth_default_cons; auto.\n  + simpl.\n    rewrite nth_default_cons_S.\n    rewrite <-IHn by (rewrite cons_length in *; lia).\n    reflexivity.\nQed.\n\nLemma firstn_seq k a b\n  : firstn k (seq a b) = seq a (min k b).\nProof.\n  revert k a; induction b as [|? IHb], k; simpl; try reflexivity.\n  intros; rewrite IHb; reflexivity.\nQed.\n#[global]\nHint Rewrite @firstn_seq : push_firstn.\n\nLemma skipn_seq k a b\n  : skipn k (seq a b) = seq (k + a) (b - k).\nProof.\n  revert k a; induction b as [|? IHb], k; simpl; try reflexivity.\n  intros; rewrite IHb; simpl; f_equal; lia.\nQed.\n\nLemma update_nth_out_of_bounds : forall {A} n f xs, n >= length xs -> @update_nth A n f xs = xs.\nProof.\n  induction n as [|n IHn]; destruct xs; simpl; try congruence; try lia; intros.\n  rewrite IHn by lia; reflexivity.\nQed.\n\n#[global]\nHint Rewrite @update_nth_out_of_bounds using lia : simpl_update_nth.\n\n\nLemma update_nth_nth_default_full : forall {A} (d:A) n f l i,\n  nth_default d (update_nth n f l) i =\n  if lt_dec i (length l) then\n    if (eq_nat_dec i n) then f (nth_default d l i)\n    else nth_default d l i\n  else d.\nProof.\n  induction n as [|n IHn]; (destruct l; simpl in *; [ intros i **; destruct i; simpl; try reflexivity; lia | ]);\n    intros i **; repeat break_match; subst; try destruct i;\n      repeat first [ progress break_match\n                   | progress subst\n                   | progress boring\n                   | progress autorewrite with simpl_nth_default\n                   | lia ].\nQed.\n\n#[global]\nHint Rewrite @update_nth_nth_default_full : push_nth_default.\n\nLemma update_nth_nth_default : forall {A} (d:A) n f l i, (0 <= i < length l)%nat ->\n  nth_default d (update_nth n f l) i =\n  if (eq_nat_dec i n) then f (nth_default d l i) else nth_default d l i.\nProof. intros; rewrite update_nth_nth_default_full; repeat break_match; boring. Qed.\n\n#[global]\nHint Rewrite @update_nth_nth_default using (lia || distr_length; lia) : push_nth_default.\n\nLemma set_nth_nth_default_full : forall {A} (d:A) n v l i,\n  nth_default d (set_nth n v l) i =\n  if lt_dec i (length l) then\n    if (eq_nat_dec i n) then v\n    else nth_default d l i\n  else d.\nProof. intros; apply update_nth_nth_default_full; assumption. Qed.\n\n#[global]\nHint Rewrite @set_nth_nth_default_full : push_nth_default.\n\nLemma set_nth_nth_default : forall {A} (d:A) n x l i, (0 <= i < length l)%nat ->\n  nth_default d (set_nth n x l) i =\n  if (eq_nat_dec i n) then x else nth_default d l i.\nProof. intros; apply update_nth_nth_default; assumption. Qed.\n\n#[global]\nHint Rewrite @set_nth_nth_default using (lia || distr_length; lia) : push_nth_default.\n\nLemma nth_default_preserves_properties : forall {A} (P : A -> Prop) l n d,\n  (forall x, In x l -> P x) -> P d -> P (nth_default d l n).\nProof.\n  intros A P l n d H H0; rewrite nth_default_eq.\n  destruct (nth_in_or_default n l d); auto.\n  congruence.\nQed.\n\nLemma nth_default_preserves_properties_length_dep :\n  forall {A} (P : A -> Prop) l n d,\n  (forall x, In x l -> n < (length l) -> P x) -> ((~ n < length l) -> P d) -> P (nth_default d l n).\nProof.\n  intros A P l n d H H0.\n  destruct (lt_dec n (length l)).\n  + rewrite nth_default_eq; auto using nth_In.\n  + rewrite nth_default_out_of_bounds by lia.\n    auto.\nQed.\n\nLemma nth_error_first : forall {T} (a b : T) l,\n  nth_error (a :: l) 0 = Some b -> a = b.\nProof.\n  intros; simpl in *.\n  unfold value in *.\n  congruence.\nQed.\n\nLemma nth_error_exists_first : forall {T} l (x : T) (H : nth_error l 0 = Some x),\n  exists l', l = x :: l'.\nProof.\n  induction l; try discriminate; intros x H; eexists.\n  apply nth_error_first in H.\n  subst; eauto.\nQed.\n\nLemma list_elementwise_eq : forall {T} (l1 l2 : list T),\n  (forall i, nth_error l1 i = nth_error l2 i) -> l1 = l2.\nProof.\n  induction l1, l2; intros H; try reflexivity;\n    pose proof (H 0%nat) as Hfirst; simpl in Hfirst; inversion Hfirst.\n  f_equal.\n  apply IHl1.\n  intros i; specialize (H (S i)).\n  boring.\nQed.\n\nLemma sum_firstn_all_succ : forall n l, (length l <= n)%nat ->\n  sum_firstn l (S n) = sum_firstn l n.\nProof.\n  unfold sum_firstn; intros.\n  autorewrite with push_firstn; reflexivity.\nQed.\n\n#[global]\nHint Rewrite @sum_firstn_all_succ using lia : simpl_sum_firstn.\n\nLemma sum_firstn_all : forall n l, (length l <= n)%nat ->\n  sum_firstn l n = sum_firstn l (length l).\nProof.\n  unfold sum_firstn; intros.\n  autorewrite with push_firstn; reflexivity.\nQed.\n\n#[global]\nHint Rewrite @sum_firstn_all using lia : simpl_sum_firstn.\n\nLemma sum_firstn_succ_default : forall l i,\n  sum_firstn l (S i) = (nth_default 0 l i + sum_firstn l i)%Z.\nProof.\n  unfold sum_firstn; induction l as [|a l IHl], i;\n    intros; autorewrite with simpl_nth_default simpl_firstn simpl_fold_right in *;\n      try reflexivity.\n  rewrite IHl; lia.\nQed.\n\n#[global]\nHint Rewrite @sum_firstn_succ_default : simpl_sum_firstn.\n\nLemma sum_firstn_0 : forall xs,\n  sum_firstn xs 0 = 0%Z.\nProof.\n  destruct xs; reflexivity.\nQed.\n\n#[global]\nHint Rewrite @sum_firstn_0 : simpl_sum_firstn.\n\nLemma sum_firstn_succ : forall l i x,\n  nth_error l i = Some x ->\n  sum_firstn l (S i) = (x + sum_firstn l i)%Z.\nProof.\n  intros; rewrite sum_firstn_succ_default.\n  erewrite nth_error_value_eq_nth_default by eassumption; reflexivity.\nQed.\n\n#[global]\nHint Rewrite @sum_firstn_succ using congruence : simpl_sum_firstn.\n\nLemma sum_firstn_succ_cons : forall x xs i,\n  sum_firstn (x :: xs) (S i) = (x + sum_firstn xs i)%Z.\nProof.\n  unfold sum_firstn; simpl; reflexivity.\nQed.\n\n#[global]\nHint Rewrite @sum_firstn_succ_cons : simpl_sum_firstn.\n\nLemma sum_firstn_nil : forall i,\n  sum_firstn nil i = 0%Z.\nProof. destruct i; reflexivity. Qed.\n\n#[global]\nHint Rewrite @sum_firstn_nil : simpl_sum_firstn.\n\nLemma sum_firstn_succ_default_rev : forall l i,\n  sum_firstn l i = (sum_firstn l (S i) - nth_default 0 l i)%Z.\nProof.\n  intros; rewrite sum_firstn_succ_default; lia.\nQed.\n\nLemma sum_firstn_succ_rev : forall l i x,\n  nth_error l i = Some x ->\n  sum_firstn l i = (sum_firstn l (S i) - x)%Z.\nProof.\n  intros; erewrite sum_firstn_succ by eassumption; lia.\nQed.\n\nLemma sum_firstn_nonnegative : forall n l, (forall x, In x l -> 0 <= x)%Z\n                                       -> (0 <= sum_firstn l n)%Z.\nProof.\n  induction n as [|n IHn]; destruct l as [|? l]; autorewrite with simpl_sum_firstn; simpl; try lia.\n  { specialize (IHn l).\n    destruct n; simpl; autorewrite with simpl_sum_firstn simpl_nth_default in *;\n      intuition auto with zarith. }\nQed.\n\nGlobal Hint Resolve sum_firstn_nonnegative : znonzero.\n\nLemma sum_firstn_app : forall xs ys n,\n  sum_firstn (xs ++ ys) n = (sum_firstn xs n + sum_firstn ys (n - length xs))%Z.\nProof.\n  induction xs as [|a xs IHxs]; simpl.\n  { intros ys n; autorewrite with simpl_sum_firstn; simpl.\n    f_equal; lia. }\n  { intros ys [|n]; autorewrite with simpl_sum_firstn; simpl; [ reflexivity | ].\n    rewrite IHxs; lia. }\nQed.\n\nLemma sum_firstn_app_sum : forall xs ys n,\n  sum_firstn (xs ++ ys) (length xs + n) = (sum_firstn xs (length xs) + sum_firstn ys n)%Z.\nProof.\n  intros; rewrite sum_firstn_app; autorewrite with simpl_sum_firstn.\n  do 2 f_equal; lia.\nQed.\n#[global]\nHint Rewrite @sum_firstn_app_sum : simpl_sum_firstn.\n\nLemma sum_cons xs x : sum (x :: xs) = (x + sum xs)%Z.\nProof. reflexivity. Qed.\n#[global]\nHint Rewrite sum_cons : push_sum.\n\nLemma sum_nil : sum nil = 0%Z.\nProof. reflexivity. Qed.\n#[global]\nHint Rewrite sum_nil : push_sum.\n\nLemma sum_app x y : sum (x ++ y) = (sum x + sum y)%Z.\nProof. induction x; rewrite ?app_nil_l, <-?app_comm_cons; autorewrite with push_sum; lia. Qed.\n#[global]\nHint Rewrite sum_app : push_sum.\n\nLemma sum_rev x : sum (rev x) = sum x.\nProof. induction x; cbn [rev]; autorewrite with push_sum; lia. Qed.\n#[global]\nHint Rewrite sum_rev : push_sum.\n\nLemma nth_error_skipn : forall {A} n (l : list A) m,\nnth_error (skipn n l) m = nth_error l (n + m).\nProof.\ninduction n as [|n IHn]; destruct l; boring.\napply nth_error_nil_error.\nQed.\n#[global]\nHint Rewrite @nth_error_skipn : push_nth_error.\n\nLemma nth_default_skipn : forall {A} (l : list A) d n m, nth_default d (skipn n l) m = nth_default d l (n + m).\nProof.\ncbv [nth_default]; intros.\nrewrite nth_error_skipn.\nreflexivity.\nQed.\n#[global]\nHint Rewrite @nth_default_skipn : push_nth_default.\n\nLemma sum_firstn_skipn : forall l n m, sum_firstn l (n + m) = (sum_firstn l n + sum_firstn (skipn n l) m)%Z.\nProof.\ninduction m; intros.\n+ rewrite sum_firstn_0. autorewrite with natsimplify. lia.\n+ rewrite <-plus_n_Sm, !sum_firstn_succ_default.\n    rewrite nth_default_skipn.\n    lia.\nQed.\n\nLemma nth_default_seq_inbounds d s n i (H:(i < n)%nat) :\n  List.nth_default d (List.seq s n) i = (s+i)%nat.\nProof.\n  progress cbv [List.nth_default].\n  rewrite nth_error_seq.\n  break_innermost_match; solve [ trivial | lia ].\nQed.\n#[global]\nHint Rewrite @nth_default_seq_inbounds using lia : push_nth_default.\n\nLemma sum_firstn_prefix_le' : forall l n m, (forall x, In x l -> (0 <= x)%Z) ->\n                                            (sum_firstn l n <= sum_firstn l (n + m))%Z.\nProof.\nintros l n m H.\nrewrite sum_firstn_skipn.\npose proof (sum_firstn_nonnegative m (skipn n l)) as Hskipn_nonneg.\nmatch type of Hskipn_nonneg with\n  ?P -> _ => assert P as Q; [ | specialize (Hskipn_nonneg Q); lia ] end.\nintros x HIn_skipn.\napply In_skipn in HIn_skipn.\nauto.\nQed.\n\nLemma sum_firstn_prefix_le : forall l n m, (forall x, In x l -> (0 <= x)%Z) ->\n                                            (n <= m)%nat ->\n                                            (sum_firstn l n <= sum_firstn l m)%Z.\nProof.\nintros l n m H H0.\nreplace m with (n + (m - n))%nat by lia.\nauto using sum_firstn_prefix_le'.\nQed.\n\nLemma sum_firstn_pos_lt_succ : forall l n m, (forall x, In x l -> (0 <= x)%Z) ->\n                                        (n < length l)%nat ->\n                                        (sum_firstn l n < sum_firstn l (S m))%Z ->\n                                        (n <= m)%nat.\nProof.\nintros l n m H H0 H1.\ndestruct (le_dec n m); auto.\nreplace n with (m + (n - m))%nat in H1 by lia.\nrewrite sum_firstn_skipn in H1.\nrewrite sum_firstn_succ_default in *.\nmatch goal with H : (?a + ?b < ?c + ?a)%Z |- _ => assert (H2 : (b < c)%Z) by lia end.\ndestruct (lt_dec m (length l)). {\n    rewrite skipn_nth_default with (d := 0%Z) in H2 by assumption.\n    replace (n - m)%nat with (S (n - S m))%nat in H2 by lia.\n    rewrite sum_firstn_succ_cons in H2.\n    pose proof (sum_firstn_nonnegative (n - S m) (skipn (S m) l)) as H3.\n    match type of H3 with\n      ?P -> _ => assert P as Q; [ | specialize (H3 Q); lia ] end.\n    intros ? A.\n    apply In_skipn in A.\n    apply H in A.\n    lia.\n} {\n    rewrite skipn_all, nth_default_out_of_bounds in H2 by lia.\n    rewrite sum_firstn_nil in H2; lia.\n}\nQed.\n\nDefinition NotSum {T} (xs : list T) (v : nat) := True.\n\nLtac NotSum :=\n  lazymatch goal with\n  | [ |- NotSum ?xs (length ?xs + _)%nat ] => fail\n  | [ |- NotSum _ _ ] => exact I\n  end.\n\nLemma sum_firstn_app_hint : forall xs ys n, NotSum xs n ->\n  sum_firstn (xs ++ ys) n = (sum_firstn xs n + sum_firstn ys (n - length xs))%Z.\nProof. auto using sum_firstn_app. Qed.\n\n#[global]\nHint Rewrite sum_firstn_app_hint using solve [ NotSum ] : simpl_sum_firstn.\n\n\nLemma nth_default_map2 : forall {A B C} (f : A -> B -> C) ls1 ls2 i d d1 d2,\n  nth_default d (map2 f ls1 ls2) i =\n    if lt_dec i (min (length ls1) (length ls2))\n    then f (nth_default d1 ls1 i) (nth_default d2 ls2 i)\n    else d.\nProof.\n  induction ls1 as [|a ls1 IHls1], ls2.\n  + cbv [map2 length min].\n    intros.\n    break_match; try lia.\n    apply nth_default_nil.\n  + cbv [map2 length min].\n    intros.\n    break_match; try lia.\n    apply nth_default_nil.\n  + cbv [map2 length min].\n    intros.\n    break_match; try lia.\n    apply nth_default_nil.\n  + simpl.\n    destruct i.\n    - intros. rewrite !nth_default_cons.\n      break_match; auto; lia.\n    - intros d d1 d2. rewrite !nth_default_cons_S.\n      rewrite IHls1 with (d1 := d1) (d2 := d2).\n      repeat break_match; auto; lia.\nQed.\n\nLemma map2_cons : forall A B C (f : A -> B -> C) ls1 ls2 a b,\n  map2 f (a :: ls1) (b :: ls2) = f a b :: map2 f ls1 ls2.\nProof.\n  reflexivity.\nQed.\n\nLemma map2_nil_l : forall A B C (f : A -> B -> C) ls2,\n  map2 f nil ls2 = nil.\nProof.\n  reflexivity.\nQed.\n\nLemma map2_nil_r : forall A B C (f : A -> B -> C) ls1,\n  map2 f ls1 nil = nil.\nProof.\n  destruct ls1; reflexivity.\nQed.\nLocal Hint Resolve map2_nil_r map2_nil_l : core.\n\nLtac simpl_list_lengths := repeat match goal with\n                                  | H : context[length (@nil ?A)] |- _ => rewrite (@nil_length0 A) in H\n                                  | H : context[length (_ :: _)] |- _ => rewrite length_cons in H\n                                  | |- context[length (@nil ?A)] => rewrite (@nil_length0 A)\n                                  | |- context[length (_ :: _)] => rewrite length_cons\n                                  end.\n\nSection OpaqueMap2.\n  Local Opaque map2.\n\n  Lemma map2_length : forall A B C (f : A -> B -> C) ls1 ls2,\n      length (map2 f ls1 ls2) = min (length ls1) (length ls2).\n  Proof.\n    induction ls1 as [|a ls1 IHls1], ls2; intros; try solve [cbv; auto].\n    rewrite map2_cons, !length_cons, IHls1.\n    auto.\n  Qed.\n  Hint Rewrite @map2_length : distr_length.\n\n\n  Lemma map2_app : forall A B C (f : A -> B -> C) ls1 ls2 ls1' ls2',\n      (length ls1 = length ls2) ->\n      map2 f (ls1 ++ ls1') (ls2 ++ ls2') = map2 f ls1 ls2 ++ map2 f ls1' ls2'.\n  Proof.\n    induction ls1 as [|a ls1 IHls1], ls2; intros; rewrite ?map2_nil_r, ?app_nil_l; try congruence;\n      simpl_list_lengths; try lia.\n    rewrite <-!app_comm_cons, !map2_cons.\n    rewrite IHls1; auto.\n  Qed.\nEnd OpaqueMap2.\n#[global]\nHint Rewrite @map2_length : distr_length.\n\nLemma firstn_update_nth {A}\n  : forall f m n (xs : list A), firstn m (update_nth n f xs) = update_nth n f (firstn m xs).\nProof.\n  induction m; destruct n, xs;\n    autorewrite with simpl_firstn simpl_update_nth;\n    congruence.\nQed.\n\n#[global]\nHint Rewrite @firstn_update_nth : push_firstn.\n#[global]\nHint Rewrite @firstn_update_nth : pull_update_nth.\n#[global]\nHint Rewrite <- @firstn_update_nth : pull_firstn.\n#[global]\nHint Rewrite <- @firstn_update_nth : push_update_nth.\n\nGlobal Instance fold_right_Proper {A B} : Proper (pointwise_relation _ (pointwise_relation _ eq) ==> eq ==> eq ==> eq) (@fold_right A B) | 1.\nProof.\n  cbv [pointwise_relation]; intros f g Hfg x y ? ls ls' ?; subst y ls'; revert x.\n  induction ls as [|l ls IHls]; cbn [fold_right]; intro; rewrite ?IHls, ?Hfg; reflexivity.\nQed.\nGlobal Instance fold_right_Proper_eq {A B} : Proper ((eq ==> eq ==> eq) ==> eq ==> eq ==> eq) (@fold_right A B) | 1.\nProof. cbv [respectful]; repeat intro; subst; apply fold_right_Proper; repeat intro; eauto. Qed.\n\nGlobal Instance fold_left_Proper {A B} : Proper (pointwise_relation _ (pointwise_relation _ eq) ==> eq ==> eq ==> eq) (@fold_left A B) | 1.\nProof.\n  repeat intro; rewrite <- !fold_left_rev_right; apply fold_right_Proper; cbv [pointwise_relation] in *; eauto; congruence.\nQed.\nGlobal Instance fold_left_Proper_eq {A B} : Proper ((eq ==> eq ==> eq) ==> eq ==> eq ==> eq) (@fold_left A B) | 1.\nProof. cbv [respectful]; repeat intro; subst; apply fold_left_Proper; repeat intro; eauto. Qed.\n\nRequire Import Coq.Lists.SetoidList.\nGlobal Instance Proper_nth_default : forall A eq,\n  Proper (eq==>eqlistA eq==>Logic.eq==>eq) (nth_default (A:=A)).\nProof.\n  intros A ee x y H; subst; induction 1.\n  + repeat intro; rewrite !nth_default_nil; assumption.\n  + intros x1 y0 H2; subst; destruct y0; rewrite ?nth_default_cons, ?nth_default_cons_S; auto.\nQed.\n\nLemma fold_right_andb_true_map_iff A (ls : list A) f\n  : List.fold_right andb true (List.map f ls) = true <-> forall i, List.In i ls -> f i = true.\nProof.\n  induction ls as [|a ls IHls]; simpl; [ | rewrite Bool.andb_true_iff, IHls ]; try tauto.\n  intuition (congruence || eauto).\nQed.\n\nLemma fold_right_andb_true_iff_fold_right_and_True (ls : list bool)\n  : List.fold_right andb true ls = true <-> List.fold_right and True (List.map (fun b => b = true) ls).\nProof.\n  rewrite <- (map_id ls) at 1.\n  rewrite fold_right_andb_true_map_iff, fold_right_and_True_forall_In_iff; reflexivity.\nQed.\n\nLemma fold_left_andb_true_map_iff A (ls : list A) f\n  : List.fold_left andb (List.map f ls) true = true <-> forall i, List.In i ls -> f i = true.\nProof.\n  rewrite <- fold_left_rev_right, <- map_rev; setoid_rewrite Bool.andb_comm.\n  rewrite fold_right_andb_true_map_iff.\n  setoid_rewrite <- in_rev; reflexivity.\nQed.\n\nLemma fold_left_andb_true_iff_fold_left_and_True (ls : list bool)\n  : List.fold_left andb ls true = true <-> List.fold_left and (List.map (fun b => b = true) ls) True.\nProof.\n  rewrite <- (map_id ls) at 1.\n  rewrite fold_left_andb_true_map_iff, fold_left_and_True_forall_In_iff; reflexivity.\nQed.\n\nLemma fold_right_andb_truth_map_iff A (ls : list A) f t\n  : List.fold_right andb t (List.map f ls) = true <-> (t = true /\\ forall i, List.In i ls -> f i = true).\nProof.\n  induction ls as [|a ls IHls]; simpl; [ | rewrite Bool.andb_true_iff, IHls ]; try tauto.\n  intuition (congruence || eauto).\nQed.\n\nLemma fold_right_andb_truth_iff_fold_right_and_Truth (ls : list bool) t\n  : List.fold_right andb t ls = true <-> List.fold_right and (t = true) (List.map (fun b => b = true) ls).\nProof.\n  rewrite <- (map_id ls) at 1.\n  rewrite fold_right_andb_truth_map_iff, fold_right_and_Truth_forall_In_iff; reflexivity.\nQed.\n\nLemma fold_left_andb_truth_map_iff A (ls : list A) f t\n  : List.fold_left andb (List.map f ls) t = true <-> (t = true /\\ forall i, List.In i ls -> f i = true).\nProof.\n  rewrite <- fold_left_rev_right, <- map_rev; setoid_rewrite Bool.andb_comm.\n  rewrite fold_right_andb_truth_map_iff.\n  setoid_rewrite <- in_rev; reflexivity.\nQed.\n\nLemma fold_left_andb_truth_iff_fold_left_and_Truth (ls : list bool) t\n  : List.fold_left andb ls t = true <-> List.fold_left and (List.map (fun b => b = true) ls) (t = true).\nProof.\n  rewrite <- (map_id ls) at 1.\n  rewrite fold_left_andb_truth_map_iff, fold_left_and_Truth_forall_In_iff; reflexivity.\nQed.\n\nLemma Forall2_forall_iff : forall {A B} (R : A -> B -> Prop) (xs : list A) (ys : list B) d1 d2, length xs = length ys ->\n  (Forall2 R xs ys <-> (forall i, (i < length xs)%nat -> R (nth_default d1 xs i) (nth_default d2 ys i))).\nProof.\n  intros A B R xs ys d1 d2 H; split; [ intros H0 i H1 | intros H0 ].\n\n  + revert xs ys H H0 H1.\n    induction i as [|i IHi]; intros xs ys H H0 H1; destruct H0; distr_length; autorewrite with push_nth_default; auto.\n    eapply IHi; auto. lia.\n  + revert xs ys H H0; induction xs as [|a xs IHxs]; intros ys H H0; destruct ys; distr_length; econstructor.\n    - specialize (H0 0%nat).\n      autorewrite with push_nth_default in *; auto.\n      apply H0; lia.\n    - apply IHxs; try lia.\n      intros i H1.\n      specialize (H0 (S i)).\n      autorewrite with push_nth_default in *; auto.\n      apply H0; lia.\nQed.\n\nLemma Forall2_forall_iff' : forall {A} R (xs ys : list A) d, length xs = length ys ->\n  (Forall2 R xs ys <-> (forall i, (i < length xs)%nat -> R (nth_default d xs i) (nth_default d ys i))).\nProof. intros; apply Forall2_forall_iff; assumption. Qed.\n\nLemma nth_default_firstn : forall {A} (d : A) l i n,\n  nth_default d (firstn n l) i = if le_dec n (length l)\n                                 then if lt_dec i n then nth_default d l i else d\n                                 else nth_default d l i.\nProof.\n  intros A d l i; induction n as [|n IHn]; break_match; autorewrite with push_nth_default; auto; try lia.\n  + rewrite (firstn_succ d) by lia.\n    autorewrite with push_nth_default; repeat (break_match_hyps; break_match; distr_length);\n      rewrite Min.min_l in * by lia; try lia.\n    - apply IHn; lia.\n    - replace i with n in * by lia.\n      rewrite Nat.sub_diag.\n      autorewrite with push_nth_default; auto.\n  + rewrite nth_default_out_of_bounds; break_match_hyps; distr_length; auto; lia.\n  + rewrite firstn_all2 by lia.\n    auto.\nQed.\n#[global]\nHint Rewrite @nth_default_firstn : push_nth_default.\n\nLemma nth_error_repeat {T} x n i v : nth_error (@repeat T x n) i = Some v -> v = x.\nProof.\n  revert n x v; induction i as [|i IHi]; destruct n; simpl in *; eauto; congruence.\nQed.\n\n#[global]\nHint Rewrite repeat_length : distr_length.\n\nLemma repeat_spec_iff : forall {A} (ls : list A) x n,\n    (length ls = n /\\ forall y, In y ls -> y = x) <-> ls = repeat x n.\nProof.\n  intros A ls x n; split; [ revert A ls x n | intro; subst; eauto using repeat_length, repeat_spec ].\n  induction ls as [|a ls IHls], n; simpl; intros; intuition try congruence.\n  f_equal; auto.\nQed.\n\nLemma repeat_spec_eq : forall {A} (ls : list A) x n,\n    length ls = n\n    -> (forall y, In y ls -> y = x)\n    -> ls = repeat x n.\nProof.\n  intros; apply repeat_spec_iff; auto.\nQed.\n\nLemma tl_repeat {A} x n : tl (@repeat A x n) = repeat x (pred n).\nProof. destruct n; reflexivity. Qed.\n\nLemma firstn_repeat : forall {A} x n k, firstn k (@repeat A x n) = repeat x (min k n).\nProof. induction n, k; boring. Qed.\n\n#[global]\nHint Rewrite @firstn_repeat : push_firstn.\n\nLemma skipn_repeat : forall {A} x n k, skipn k (@repeat A x n) = repeat x (n - k).\nProof. induction n, k; boring. Qed.\n\n#[global]\nHint Rewrite @skipn_repeat : push_skipn.\n\nGlobal Instance Proper_map {A B} {RA RB} {Equivalence_RB:Equivalence RB}\n  : Proper ((RA==>RB) ==> eqlistA RA ==> eqlistA RB) (@List.map A B).\nProof.\n  repeat intro.\n  match goal with [H:eqlistA _ _ _ |- _ ] => induction H end; [reflexivity|].\n  cbv [respectful] in *; econstructor; eauto.\nQed.\n\nLemma pointwise_map {A B} : Proper ((pointwise_relation _ eq) ==> eq ==> eq) (@List.map A B).\nProof.\n  repeat intro; cbv [pointwise_relation] in *; subst.\n  match goal with [H:list _ |- _ ] => induction H as [|? IH IHIH] end; [reflexivity|].\n  simpl. rewrite IHIH. congruence.\nQed.\n\nLemma map_map2 {A B C D} (f:A -> B -> C) (g:C -> D) (xs:list A) (ys:list B) : List.map g (map2 f xs ys) = map2 (fun (a : A) (b : B) => g (f a b)) xs ys.\nProof.\n  revert ys; induction xs as [|a xs IHxs]; intros ys; [reflexivity|].\n  destruct ys; [reflexivity|].\n  simpl. rewrite IHxs. reflexivity.\nQed.\n\nLemma map2_fst {A B C} (f:A -> C) (xs:list A) : forall (ys:list B), length xs = length ys ->\n  map2 (fun (a : A) (_ : B) => f a) xs ys = List.map f xs.\nProof.\n  induction xs as [|a xs IHxs]; intros ys **; [reflexivity|].\n  destruct ys; [simpl in *; discriminate|].\n  simpl. rewrite IHxs by eauto. reflexivity.\nQed.\n\nLemma map2_flip {A B C} (f:A -> B -> C) (xs:list A) : forall (ys: list B),\n   map2 (fun b a => f a b) ys xs = map2 f xs ys.\nProof.\n  induction xs as [|a xs IHxs]; destruct ys; try reflexivity; [].\n  simpl. rewrite IHxs. reflexivity.\nQed.\n\nLemma map2_snd {A B C} (f:B -> C) (xs:list A) : forall (ys:list B), length xs = length ys ->\n  map2 (fun (_ : A) (b : B) => f b) xs ys = List.map f ys.\nProof. intros. rewrite map2_flip. eauto using map2_fst. Qed.\n\nLemma map2_map {A B C A' B'} (f:A -> B -> C) (g:A' -> A) (h:B' -> B) (xs:list A') (ys:list B')\n  : map2 f (List.map g xs) (List.map h ys) = map2 (fun a b => f (g a) (h b)) xs ys.\nProof.\n  revert ys; induction xs as [|a xs IHxs]; destruct ys; intros; try reflexivity; [].\n  simpl. rewrite IHxs. reflexivity.\nQed.\n\nDefinition 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 (List.nth_default default ls idx) (rec_call (S idx)))\n       n\n       idx.\nDefinition expand_list {A} (default : A) (ls : list A) (n : nat) : list A\n  := expand_list_helper default ls n 0.\n\nLemma expand_list_helper_correct {A} (default : A) (ls : list A) (n idx : nat) (H : (idx + n <= length ls)%nat)\n  : expand_list_helper default ls n idx\n    = List.firstn n (List.skipn idx ls).\nProof.\n  cbv [expand_list_helper]; revert idx H.\n  induction n as [|n IHn]; cbn; intros.\n  { reflexivity. }\n  { rewrite IHn by lia.\n    erewrite (@skipn_nth_default _ idx ls) by lia.\n    reflexivity. }\nQed.\n\nLemma expand_list_correct (n : nat) {A} (default : A) (ls : list A) (H : List.length ls = n)\n  : expand_list default ls n = ls.\nProof.\n  subst; cbv [expand_list]; rewrite expand_list_helper_correct by reflexivity.\n  rewrite skipn_0, firstn_all; reflexivity.\nQed.\n\nLtac expand_lists _ :=\n  let default_for A :=\n      match goal with\n      | _ => (eval lazy in (_ : pointed A))\n      | _ => constr_fail_with ltac:(fun _ => idtac \"Warning: could not infer a default value for list type\" A)\n      end in\n  let T := lazymatch goal with |- _ = _ :> ?T => T end in\n  let v := fresh in\n  evar (v : T); transitivity v;\n  [ subst v\n  | repeat match goal with\n           | [ H : @List.length ?A ?f = ?n |- context[?f] ]\n             => let v := default_for A in\n                rewrite <- (@expand_list_correct n A v f H);\n                clear H\n           end;\n    lazymatch goal with\n    | [ H : List.length ?f = _ |- context[?f] ]\n      => fail 0 \"Could not expand list\" f\n    | _ => idtac\n    end;\n    subst v; reflexivity ].\n\nLemma single_list_rect_to_match A (P:list A -> Type) (Pnil: P nil) (PS: forall a tl, P (a :: tl)) ls :\n  @list_rect A P Pnil (fun a tl _ => PS a tl) ls = match ls with\n                                                   | cons a tl => PS a tl\n                                                   | nil => Pnil\n                                                   end.\nProof. destruct ls; reflexivity. Qed.\n\nLemma partition_app A (f : A -> bool) (a b : list A)\n  : partition f (a ++ b) = (fst (partition f a) ++ fst (partition f b),\n                            snd (partition f a) ++ snd (partition f b)).\nProof.\n  revert b; induction a, b; cbn; rewrite ?app_nil_r; eta_expand; try reflexivity.\n  rewrite !IHa; cbn; break_match; reflexivity.\nQed.\n\nLemma flat_map_map A B C (f : A -> B) (g : B -> list C) (xs : list A)\n  : flat_map g (map f xs) = flat_map (fun x => g (f x)) xs.\nProof. induction xs; cbn; congruence. Qed.\nLemma flat_map_singleton A B (f : A -> B) (xs : list A)\n  : flat_map (fun x => cons (f x) nil) xs = map f xs.\nProof. induction xs; cbn; congruence. Qed.\nLemma flat_map_ext A B (f g : A -> list B) xs (H : forall x, In x xs -> f x = g x)\n  : flat_map f xs = flat_map g xs.\nProof. induction xs; cbn in *; [ reflexivity | rewrite IHxs; f_equal ]; intros; intuition auto. Qed.\nGlobal Instance flat_map_Proper A B : Proper (pointwise_relation _ eq ==> eq ==> eq) (@flat_map A B).\nProof. repeat intro; subst; apply flat_map_ext; auto. Qed.\n\nGlobal Instance map_Proper_eq {A B} : Proper ((eq ==> eq) ==> eq ==> eq) (@List.map A B) | 1.\nProof. repeat intro; subst; apply pointwise_map; repeat intro; eauto. Qed.\nGlobal Instance flat_map_Proper_eq {A B} : Proper ((eq ==> eq) ==> eq ==> eq) (@List.flat_map A B) | 1.\nProof. repeat intro; subst; apply flat_map_Proper; repeat intro; eauto. Qed.\nGlobal Instance partition_Proper {A} : Proper (pointwise_relation _ eq ==> eq ==> eq) (@List.partition A).\nProof.\n  cbv [pointwise_relation]; intros f g Hfg ls ls' ?; subst ls'.\n  induction ls as [|l ls IHls]; cbn [partition]; rewrite ?IHls, ?Hfg; reflexivity.\nQed.\nGlobal Instance partition_Proper_eq {A} : Proper ((eq ==> eq) ==> eq ==> eq) (@List.partition A) | 1.\nProof. repeat intro; subst; apply partition_Proper; repeat intro; eauto. Qed.\n\nLemma partition_map A B (f : B -> bool) (g : A -> B) xs\n  : partition f (map g xs) = (map g (fst (partition (fun x => f (g x)) xs)),\n                              map g (snd (partition (fun x => f (g x)) xs))).\nProof. induction xs; cbn; [ | rewrite !IHxs ]; break_match; reflexivity. Qed.\nLemma map_fst_partition A B (f : B -> bool) (g : A -> B) xs\n  : map g (fst (partition (fun x => f (g x)) xs)) = fst (partition f (map g xs)).\nProof. rewrite partition_map; reflexivity. Qed.\nLemma map_snd_partition A B (f : B -> bool) (g : A -> B) xs\n  : map g (snd (partition (fun x => f (g x)) xs)) = snd (partition f (map g xs)).\nProof. rewrite partition_map; reflexivity. Qed.\nLemma partition_In A (f:A -> bool) xs : forall x, @In A x xs <-> @In A x (if f x then fst (partition f xs) else snd (partition f xs)).\nProof.\n  intro x; destruct (f x) eqn:?; split; intros; repeat apply conj; revert dependent x;\n    (induction xs as [|x' xs IHxs]; cbn; [ | destruct (f x') eqn:?, (partition f xs) ]; cbn in *; subst; intuition (subst; auto));\n    congruence.\nQed.\nLemma fst_partition_In A f xs : forall x, @In A x (fst (partition f xs)) <-> f x = true /\\ @In A x xs.\nProof.\n  intro x; split; intros; repeat apply conj; revert dependent x;\n    (induction xs as [|x' xs IHxs]; cbn; [ | destruct (f x') eqn:?, (partition f xs) ]; cbn in *; subst; intuition (subst; auto));\n    congruence.\nQed.\nLemma snd_partition_In A f xs : forall x, @In A x (snd (partition f xs)) <-> f x = false /\\ @In A x xs.\nProof.\n  intro x; split; intros; repeat apply conj; revert dependent x;\n    (induction xs as [|x' xs IHxs]; cbn; [ | destruct (f x') eqn:?, (partition f xs) ]; cbn in *; subst; intuition (subst; auto));\n    congruence.\nQed.\n\nLemma list_rect_map A B P (f : A -> B) N C ls\n  : @list_rect B P N C (map f ls) = @list_rect A (fun ls => P (map f ls)) N (fun x xs rest => C (f x) (map f xs) rest) ls.\nProof. induction ls as [|x xs IHxs]; cbn; [ | rewrite IHxs ]; reflexivity. Qed.\nLemma flat_map_app A B (f : A -> list B) xs ys\n  : flat_map f (xs ++ ys) = flat_map f xs ++ flat_map f ys.\nProof. induction xs as [|x xs IHxs]; cbn; rewrite ?IHxs, <- ?app_assoc; reflexivity. Qed.\n#[global]\nHint Rewrite flat_map_app : push_flat_map.\nLemma map_flat_map A B C (f : A -> list B) (g : B -> C) xs\n  : map g (flat_map f xs) = flat_map (fun x => map g (f x)) xs.\nProof. induction xs as [|x xs IHxs]; cbn; rewrite ?map_app; congruence. Qed.\n\nLemma flat_map_rev A B (f : A -> list B) xs\n  : flat_map f (rev xs) = rev (flat_map (fun x => rev (f x)) xs).\nProof.\n  induction xs as [|x xs IHxs]; cbn; autorewrite with push_flat_map; rewrite ?rev_app_distr, ?IHxs, ?rev_involutive, ?app_nil_r; reflexivity.\nQed.\n#[global]\nHint Rewrite flat_map_rev : push_flat_map.\n\nLemma rev_flat_map A B (f : A -> list B) xs\n  : rev (flat_map f xs) = flat_map (fun x => rev (f x)) (rev xs).\nProof. rewrite flat_map_rev; setoid_rewrite rev_involutive; reflexivity. Qed.\n#[global]\nHint Rewrite rev_flat_map : push_rev.\n\nLemma combine_map_map A B C D (f : A -> B) (g : C -> D) xs ys\n  : combine (map f xs) (map g ys) = map (fun ab => (f (fst ab), g (snd ab))) (combine xs ys).\nProof. revert ys; induction xs, ys; cbn; congruence. Qed.\nLemma combine_map_l A B C (f : A -> B) xs ys\n  : @combine B C (map f xs) ys = map (fun ab => (f (fst ab), snd ab)) (combine xs ys).\nProof. rewrite <- combine_map_map with (f:=f) (g:=fun x => x), map_id; reflexivity. Qed.\nLemma combine_map_r A B C (f : B -> C) xs ys\n  : @combine A C xs (map f ys) = map (fun ab => (fst ab, f (snd ab))) (combine xs ys).\nProof. rewrite <- combine_map_map with (g:=f) (f:=fun x => x), map_id; reflexivity. Qed.\nLemma combine_same A xs\n  : @combine A A xs xs = map (fun x => (x, x)) xs.\nProof. induction xs; cbn; congruence. Qed.\nLemma if_singleton A (b:bool) (x y : A) : (if b then x::nil else y::nil) = (if b then x else y)::nil.\nProof. now case b. Qed.\nLemma flat_map_if_In A B (b : A -> bool) (f g : A -> list B) xs (b' : bool)\n  : (forall v, In v xs -> b v = b') -> flat_map (fun x => if b x then f x else g x) xs = if b' then flat_map f xs else flat_map g xs.\nProof. induction xs as [|x xs IHxs]; cbn; [ | intro H; rewrite IHxs, H by eauto ]; case b'; reflexivity. Qed.\nLemma flat_map_if_In_sumbool A B X Y (b : forall a : A, sumbool (X a) (Y a)) (f g : A -> list B) xs (b' : bool)\n  : (forall v, In v xs -> (if b v then true else false) = b') -> flat_map (fun x => if b x then f x else g x) xs = if b' then flat_map f xs else flat_map g xs.\nProof.\n  intro H; erewrite <- flat_map_if_In by refine H.\n  apply flat_map_Proper; [ intro | reflexivity ]; break_innermost_match; reflexivity.\nQed.\nLemma map_if_In A B (b : A -> bool) (f g : A -> B) xs (b' : bool)\n  : (forall v, In v xs -> b v = b') -> map (fun x => if b x then f x else g x) xs = if b' then map f xs else map g xs.\nProof. induction xs as [|x xs IHxs]; cbn; [ | intro H; rewrite IHxs, H by eauto ]; case b'; reflexivity. Qed.\nLemma map_if_In_sumbool A B X Y (b : forall a : A, sumbool (X a) (Y a)) (f g : A -> B) xs (b' : bool)\n  : (forall v, In v xs -> (if b v then true else false) = b') -> map (fun x => if b x then f x else g x) xs = if b' then map f xs else map g xs.\nProof.\n  intro H; erewrite <- map_if_In by refine H.\n  apply map_ext_in; intro; break_innermost_match; reflexivity.\nQed.\nLemma fold_right_map A B C (f : A -> B) xs (F : _ -> _ -> C) v\n  : fold_right F v (map f xs) = fold_right (fun x y => F (f x) y) v xs.\nProof. revert v; induction xs; cbn; intros; congruence. Qed.\nLemma fold_right_flat_map A B C (f : A -> list B) xs (F : _ -> _ -> C) v\n  : fold_right F v (flat_map f xs) = fold_right (fun x y => fold_right F y (f x)) v xs.\nProof. revert v; induction xs; cbn; intros; rewrite ?fold_right_app; congruence. Qed.\n\nLemma fold_right_ext_in A B f g v xs : (forall x y, List.In x xs -> f x y = g x y) -> @fold_right A B f v xs = fold_right g v xs.\nProof. induction xs; cbn; intro H; rewrite ?H, ?IHxs; auto. Qed.\nLemma fold_right_ext A B f g v xs : (forall x y, f x y = g x y) -> @fold_right A B f v xs = fold_right g v xs.\nProof. intros; apply fold_right_ext_in; eauto. Qed.\n\nLemma fold_right_id_ext A B f v xs : (forall x y, f x y = y) -> @fold_right A B f v xs = v.\nProof. induction xs; cbn; intro H; rewrite ?H; auto. Qed.\nLemma fold_left_map A B C f f' l a\n  : @fold_left A B f (@List.map C _ f' l) a = fold_left (fun x y => f x (f' y)) l a.\nProof. revert a; induction l; cbn [List.map List.fold_left]; auto. Qed.\nLemma fold_left_flat_map A B C (f : A -> list B) xs (F : _ -> _ -> C) v\n  : fold_left F (flat_map f xs) v = fold_left (fun x y => fold_left F (f y) x) xs v.\nProof. revert v; induction xs; cbn; intros; rewrite ?fold_left_app; congruence. Qed.\n\nLemma fold_left_ext_in A B f g v xs : (forall x y, List.In y xs -> f x y = g x y) -> @fold_left A B f xs v = fold_left g xs v.\nProof. intros; rewrite <- !fold_left_rev_right; apply fold_right_ext_in; intros *; rewrite <- in_rev; eauto. Qed.\nLemma fold_left_ext A B f g v xs : (forall x y, f x y = g x y) -> @fold_left A B f v xs = fold_left g v xs.\nProof. intros; apply fold_left_ext_in; eauto. Qed.\n\nLemma fold_left_id_ext A B f v xs : (forall x y, f x y = x) -> @fold_left A B f xs v = v.\nProof. induction xs; cbn; intro H; rewrite ?H; auto. Qed.\nLemma nth_error_repeat_alt {A} (v : A) n i\n  : nth_error (repeat v n) i = if dec (i < n)%nat then Some v else None.\nProof.\n  revert i; induction n as [|n IHn], i; cbn; try reflexivity.\n  cbn [nth_error]; rewrite IHn; do 2 edestruct dec; try reflexivity; lia.\nQed.\nLemma nth_default_repeat A (v:A) n (d:A) i : nth_default d (repeat v n) i = if dec (i < n)%nat then v else d.\nProof.\n  cbv [nth_default]; rewrite nth_error_repeat_alt; now break_innermost_match.\nQed.\n#[global]\nHint Rewrite nth_default_repeat : push_nth_default simpl_nth_default.\nLemma fold_right_if_dec_eq_seq A start len i f (x v : A)\n  : ((start <= i < start + len)%nat -> f i v = x)\n    -> (forall j v, (i <> j)%nat -> f j v = v)\n    -> fold_right f v (seq start len) = if dec (start <= i < start + len)%nat then x else v.\nProof.\n  revert start v; induction len as [|len IHlen]; intros start v H H'; [ | rewrite seq_snoc, fold_right_app; cbn [fold_right] ].\n  { edestruct dec; try reflexivity; lia. }\n  { destruct (dec (i = (start + len)%nat)); subst; [ | rewrite H' by lia ];\n      rewrite IHlen; eauto; intros; clear IHlen;\n        repeat match goal with\n               | _ => reflexivity\n               | _ => lia\n               | _ => progress subst\n               | _ => progress specialize_by lia\n               | [ H : context[dec ?P] |- _ ] => destruct (dec P)\n               | [ |- context[dec ?P] ] => destruct (dec P)\n               | [ H : f _ _ = _ |- _ ] => rewrite H\n               | [ H : forall j, f j ?v = _ |- context[f _ ?v] ] => rewrite H\n               end. }\nQed.\n\nLemma fold_left_if_dec_eq_seq A start len i f (x v : A)\n  : ((start <= i < start + len)%nat -> f v i = x)\n    -> (forall j v, (i <> j)%nat -> f v j = v)\n    -> fold_left f (seq start len) v = if dec (start <= i < start + len)%nat then x else v.\nProof.\n  revert start v; induction len as [|len IHlen]; intros start v H H'; [ | rewrite seq_snoc, fold_left_app; cbn [fold_left] ].\n  { edestruct dec; try reflexivity; lia. }\n  { destruct (dec (i = (start + len)%nat)); subst; [ | rewrite H' by lia ];\n      rewrite IHlen; eauto; intros; clear IHlen;\n        repeat match goal with\n               | _ => reflexivity\n               | _ => lia\n               | _ => progress subst\n               | _ => progress specialize_by lia\n               | [ H : context[dec ?P] |- _ ] => destruct (dec P)\n               | [ |- context[dec ?P] ] => destruct (dec P)\n               | [ H : f _ _ = _ |- _ ] => rewrite H\n               | [ H : forall j, f j ?v = _ |- context[f _ ?v] ] => rewrite H\n               end. }\nQed.\n\nLemma fold_left_push A (x y : A) (f : A -> A -> A)\n      (f_assoc : forall x y z, f (f x y) z = f x (f y z))\n      ls\n  : f x (fold_left f ls y) = fold_left f ls (f x y).\nProof.\n  revert x y; induction ls as [|l ls IHls]; cbn; [ reflexivity | ].\n  intros; rewrite IHls; f_equal; auto.\nQed.\n\nLemma fold_right_push A (x y : A) (f : A -> A -> A)\n      (f_assoc : forall x y z, f (f x y) z = f x (f y z))\n      ls\n  : f (fold_right f x ls) y = fold_right f (f x y) ls.\nProof.\n  rewrite <- (rev_involutive ls), !fold_left_rev_right, fold_left_push with (f:=fun x y => f y x); auto.\nQed.\n\nLemma nth_error_combine {A B} n (ls1 : list A) (ls2 : list B)\n  : nth_error (combine ls1 ls2) n = match nth_error ls1 n, nth_error ls2 n with\n                                    | Some v1, Some v2 => Some (v1, v2)\n                                    | _, _ => None\n                                    end.\nProof.\n  revert ls2 n; induction ls1 as [|l1 ls1 IHls1], ls2, n; cbn [combine nth_error]; try reflexivity; auto.\n  edestruct nth_error; reflexivity.\nQed.\n\nLemma combine_repeat {A B} (a : A) (b : B) n : combine (repeat a n) (repeat b n) = repeat (a, b) n.\nProof. induction n; cbn; congruence. Qed.\n\nLemma combine_rev_rev_samelength {A B} ls1 ls2 : length ls1 = length ls2 -> @combine A B (rev ls1) (rev ls2) = rev (combine ls1 ls2).\nProof.\n  revert ls2; induction ls1 as [|? ? IHls1], ls2; cbn in *; try congruence; intros.\n  rewrite combine_app_samelength, IHls1 by (rewrite ?rev_length; congruence); cbn [combine].\n  reflexivity.\nQed.\n\nLemma map_nth_default_seq {A} (d:A) n ls\n  : length ls = n -> List.map (List.nth_default d ls) (List.seq 0 n) = ls.\nProof.\n  intro; subst.\n  rewrite <- (List.rev_involutive ls); generalize (List.rev ls); clear ls; intro ls.\n  rewrite List.rev_length.\n  induction ls; cbn [length List.rev]; [ reflexivity | ].\n  rewrite seq_snoc, List.map_app.\n  apply f_equal2; [ | cbn; rewrite nth_default_app, List.rev_length, Nat.sub_diag ];\n    [ etransitivity; [ | eassumption ]; apply List.map_ext_in; intro; rewrite Lists.List.in_seq;\n      rewrite nth_default_app, List.rev_length; intros\n    | ].\n  all: edestruct lt_dec; try (exfalso; lia).\n  all: reflexivity.\nQed.\n\nLemma nth_error_firstn A ls n i\n  : List.nth_error (@List.firstn A n ls) i = if lt_dec i n then List.nth_error ls i else None.\nProof.\n  revert ls i; induction n, ls, i; cbn; try reflexivity; destruct lt_dec; try reflexivity; rewrite IHn.\n  all: destruct lt_dec; try reflexivity; lia.\nQed.\n\nLemma nth_error_rev A n ls : List.nth_error (@List.rev A ls) n = if lt_dec n (length ls) then List.nth_error ls (length ls - S n) else None.\nProof.\n  destruct lt_dec; [ | rewrite nth_error_length_error; rewrite ?List.rev_length; try reflexivity; lia ].\n  revert dependent n; induction ls as [|x xs IHxs]; cbn [length List.rev]; try reflexivity; intros; try lia.\n  { rewrite nth_error_app, List.rev_length, Nat.sub_succ.\n    destruct lt_dec.\n    { rewrite IHxs by lia.\n      rewrite <- (Nat.succ_pred_pos (length xs - n)) by lia.\n      cbn [List.nth_error].\n      f_equal; lia. }\n    { assert (n = length xs) by lia; subst.\n      rewrite Nat.sub_diag.\n      reflexivity. } }\nQed.\n\nLemma concat_fold_right_app A ls\n  : @List.concat A ls = List.fold_right (@List.app A) nil ls.\nProof. induction ls; cbn; eauto. Qed.\n\nLemma map_update_nth_ext {A B n} f1 f2 f3 ls1 ls2\n  : map f3 ls1 = ls2\n    -> (forall x, List.In x ls1 -> f3 (f2 x) = f1 (f3 x))\n    -> map f3 (@update_nth A n f2 ls1) = @update_nth B n f1 ls2.\nProof.\n  revert ls1 ls2; induction n as [|n IHn], ls1 as [|x1 xs1], ls2 as [|x2 xs2]; cbn; intros H0 H1; try discriminate; try reflexivity.\n  all: inversion H0; clear H0; subst.\n  all: f_equal; eauto using or_introl.\nQed.\n\nLemma push_f_list_rect {P P'} (f : P -> P') {A} Pnil Pcons Pcons' ls\n      (Hcons : forall x xs rec, f (Pcons x xs rec)\n                                = Pcons' x xs (f rec))\n  : f (list_rect (fun _ : list A => P) Pnil Pcons ls)\n    = list_rect\n        (fun _ => _)\n        (f Pnil)\n        Pcons'\n        ls.\nProof.\n  induction ls as [|x xs IHxs]; cbn [list_rect]; [ reflexivity | ].\n  rewrite Hcons, IHxs; reflexivity.\nQed.\n\nLemma eq_app_list_rect {A} (ls1 ls2 : list A)\n  : List.app ls1 ls2 = list_rect _ ls2 (fun x _ rec => x :: rec) ls1.\nProof. revert ls2; induction ls1, ls2; cbn; f_equal; eauto. Qed.\nLemma eq_flat_map_list_rect {A B} f (ls : list A)\n  : @flat_map A B f ls = list_rect _ nil (fun x _ rec => f x ++ rec) ls.\nProof. induction ls; cbn; eauto. Qed.\nLemma eq_partition_list_rect {A} f (ls : list A)\n  : @partition A f ls = list_rect _ (nil, nil) (fun x _ '(a, b) => bool_rect (fun _ => _) (x :: a, b) (a, x :: b) (f x)) ls.\nProof. induction ls; cbn; eauto. Qed.\nLemma eq_fold_right_list_rect {A B} f v (ls : list _)\n  : @fold_right A B f v ls = list_rect _ v (fun x _ rec => f x rec) ls.\nProof. induction ls; cbn; eauto. Qed.\nLemma eq_fold_left_list_rect {A B} f v (ls : list _)\n  : @fold_left A B f ls v = list_rect _ (fun v => v) (fun x _ rec v => rec (f v x)) ls v.\nProof. revert f v; induction ls; cbn; eauto. Qed.\nLemma eq_map_list_rect {A B} f (ls : list _)\n  : @List.map A B f ls = list_rect _ nil (fun x _ rec => f x :: rec) ls.\nProof. induction ls; cbn; eauto. Qed.\nLemma eq_flat_map_fold_right {A B} f (ls : list A)\n  : @flat_map A B f ls = fold_right (fun x y => f x ++ y) nil ls.\nProof. induction ls; cbn; eauto. Qed.\nLemma eq_flat_map_fold_left_gen {A B} f (ls : list A) ls'\n  : fold_left (fun x y => x ++ f y) ls ls' = ls' ++ @flat_map A B f ls.\nProof. revert ls'; induction ls; cbn; intros; rewrite ?app_nil_r, ?IHls, ?app_assoc; eauto. Qed.\nLemma eq_flat_map_fold_left {A B} f (ls : list A)\n  : @flat_map A B f ls = fold_left (fun x y => x ++ f y) ls nil.\nProof. rewrite eq_flat_map_fold_left_gen; reflexivity. Qed.\n\nLemma map_repeat {A B} (f : A -> B) v k\n  : List.map f (List.repeat v k) = List.repeat (f v) k.\nProof. induction k; cbn; f_equal; assumption. Qed.\nLemma map_const {A B} (v : B) (ls : list A)\n  : List.map (fun _ => v) ls = List.repeat v (List.length ls).\nProof. induction ls; cbn; f_equal; assumption. Qed.\n\nLemma Forall2_rev {A B R ls1 ls2}\n  : @List.Forall2 A B R ls1 ls2\n    -> List.Forall2 R (rev ls1) (rev ls2).\nProof using Type.\n  induction 1; cbn [rev]; [ constructor | ].\n  apply Forall2_app; auto.\nQed.\n\nLemma Forall2_update_nth {A B f g n R ls1 ls2}\n  : @List.Forall2 A B R ls1 ls2\n    -> (forall v1, nth_error ls1 n = Some v1 -> forall v2, nth_error ls2 n = Some v2 -> R v1 v2 -> R (f v1) (g v2))\n    -> @List.Forall2 A B R (update_nth n f ls1) (update_nth n g ls2).\nProof using Type.\n  intro H; revert n; induction H, n; cbn [nth_error update_nth].\n  all: repeat first [ progress intros\n                    | progress specialize_by_assumption\n                    | assumption\n                    | match goal with\n                      | [ |- List.Forall2 _ _ _ ] => constructor\n                      | [ H : forall x, Some _ = Some x -> _ |- _ ] => specialize (H _ eq_refl)\n                      | [ IH : forall n : nat, _, H : forall v1, nth_error ?l ?n = Some v1 -> _ |- _ ] => specialize (IH n H)\n                      end ].\nQed.\n\nFixpoint remove_duplicates' {A} (beq : A -> A -> bool) (ls : list A) : list A\n  := match ls with\n     | nil => nil\n     | cons x xs => if existsb (beq x) xs\n                    then @remove_duplicates' A beq xs\n                    else x :: @remove_duplicates' A beq xs\n     end.\nDefinition remove_duplicates {A} (beq : A -> A -> bool) (ls : list A) : list A\n  := List.rev (remove_duplicates' beq (List.rev ls)).\nFixpoint find_duplicates' {A} (beq : A -> A -> bool) (ls : list A) : list A\n  := match ls with\n     | nil => nil\n     | cons x xs => if existsb (beq x) xs\n                    then x :: @find_duplicates' A beq xs\n                    else @find_duplicates' A beq xs\n     end.\nDefinition find_duplicates {A} (beq : A -> A -> bool) (ls : list A) : list A\n  := remove_duplicates beq (find_duplicates' beq ls).\n\nLemma InA_remove_duplicates'\n      {A} (A_beq : A -> A -> bool)\n      (R : A -> A -> Prop)\n      {R_Transitive : Transitive R}\n      (A_bl : forall x y, A_beq x y = true -> R x y)\n      (ls : list A)\n  : forall x, InA R x (remove_duplicates' A_beq ls) <-> InA R x ls.\nProof using Type.\n  induction ls as [|x xs IHxs]; intro y; [ reflexivity | ].\n  cbn [remove_duplicates']; break_innermost_match;\n    rewrite ?InA_cons, IHxs; [ | reflexivity ].\n  split; [ now auto | ].\n  intros [?|?]; subst; auto; [].\n  rewrite existsb_exists in *.\n  destruct_head'_ex; destruct_head'_and.\n  match goal with H : _ |- _ => apply A_bl in H end.\n  rewrite InA_alt.\n  eexists; split; [ | eassumption ].\n  etransitivity; eassumption.\nQed.\n\nLemma InA_remove_duplicates\n      {A} (A_beq : A -> A -> bool)\n      (R : A -> A -> Prop)\n      {R_Transitive : Transitive R}\n      (A_bl : forall x y, A_beq x y = true -> R x y)\n      (ls : list A)\n  : forall x, InA R x (remove_duplicates A_beq ls) <-> InA R x ls.\nProof using Type.\n  cbv [remove_duplicates]; intro.\n  rewrite InA_rev, InA_remove_duplicates', InA_rev; auto; reflexivity.\nQed.\n\nLemma InA_eq_In_iff {A} x ls\n  : InA eq x ls <-> @List.In A x ls.\nProof using Type.\n  rewrite InA_alt.\n  repeat first [ progress destruct_head'_and\n               | progress destruct_head'_ex\n               | progress subst\n               | solve [ eauto ]\n               | apply conj\n               | progress intros ].\nQed.\n\nLemma NoDupA_eq_NoDup {A} ls\n  : @NoDupA A eq ls <-> NoDup ls.\nProof using Type.\n  split; intro H; induction H; constructor; eauto;\n    (idtac + rewrite <- InA_eq_In_iff + rewrite InA_eq_In_iff); assumption.\nQed.\n\nLemma in_remove_duplicates'\n      {A} (A_beq : A -> A -> bool) (A_bl : forall x y, A_beq x y = true -> x = y)\n      (ls : list A)\n  : forall x, List.In x (remove_duplicates' A_beq ls) <-> List.In x ls.\nProof using Type.\n  intro x; rewrite <- !InA_eq_In_iff; apply InA_remove_duplicates'; eauto; exact _.\nQed.\n\nLemma in_remove_duplicates\n      {A} (A_beq : A -> A -> bool) (A_bl : forall x y, A_beq x y = true -> x = y)\n      (ls : list A)\n  : forall x, List.In x (remove_duplicates A_beq ls) <-> List.In x ls.\nProof using Type.\n  intro x; rewrite <- !InA_eq_In_iff; apply InA_remove_duplicates; eauto; exact _.\nQed.\n\nLemma NoDupA_remove_duplicates' {A} (A_beq : A -> A -> bool)\n      (R : A -> A -> Prop)\n      {R_Transitive : Transitive R}\n      (A_lb : forall x y, A_beq x y = true -> R x y)\n      (A_bl : forall x y, R x y -> A_beq x y = true)\n      (ls : list A)\n  : NoDupA R (remove_duplicates' A_beq ls).\nProof using Type.\n  induction ls as [|x xs IHxs]; [ now constructor | ].\n  cbn [remove_duplicates']; break_innermost_match; [ assumption | constructor; auto ]; [].\n  intro H'.\n  cut (false = true); [ discriminate | ].\n  match goal with H : _ = false |- _ => rewrite <- H end.\n  rewrite existsb_exists in *.\n  rewrite InA_remove_duplicates' in H' by eauto.\n  rewrite InA_alt in H'.\n  destruct_head'_ex; destruct_head'_and.\n  eauto.\nQed.\n\nLemma NoDupA_remove_duplicates {A} (A_beq : A -> A -> bool)\n      (R : A -> A -> Prop)\n      {R_Equivalence : Equivalence R}\n      (A_lb : forall x y, A_beq x y = true -> R x y)\n      (A_bl : forall x y, R x y -> A_beq x y = true)\n      (ls : list A)\n  : NoDupA R (remove_duplicates A_beq ls).\nProof using Type.\n  cbv [remove_duplicates].\n  apply NoDupA_rev; [ assumption | ].\n  apply NoDupA_remove_duplicates'; auto; exact _.\nQed.\n\nLemma NoDup_remove_duplicates' {A} (A_beq : A -> A -> bool)\n      (R : A -> A -> Prop)\n      (A_lb : forall x y, A_beq x y = true -> x = y)\n      (A_bl : forall x y, x = y -> A_beq x y = true)\n      (ls : list A)\n  : NoDup (remove_duplicates' A_beq ls).\nProof using Type.\n  apply NoDupA_eq_NoDup, NoDupA_remove_duplicates'; auto; exact _.\nQed.\n\nLemma NoDup_remove_duplicates {A} (A_beq : A -> A -> bool)\n      (A_lb : forall x y, A_beq x y = true -> x = y)\n      (A_bl : forall x y, x = y -> A_beq x y = true)\n      (ls : list A)\n  : NoDup (remove_duplicates A_beq ls).\nProof using Type.\n  apply NoDupA_eq_NoDup, NoDupA_remove_duplicates; auto; exact _.\nQed.\n\nLemma remove_duplicates'_eq_NoDupA {A} (A_beq : A -> A -> bool)\n      (R : A -> A -> Prop)\n      (A_lb : forall x y, A_beq x y = true -> R x y)\n      (ls : list A)\n  : NoDupA R ls -> remove_duplicates' A_beq ls = ls.\nProof using Type.\n  intro H; induction H as [|x xs H0 H1 IHxs]; [ reflexivity | ].\n  cbn [remove_duplicates'].\n  rewrite IHxs.\n  repeat first [ break_innermost_match_step\n               | reflexivity\n               | progress destruct_head'_ex\n               | progress destruct_head'_and\n               | progress rewrite existsb_exists in *\n               | progress rewrite InA_alt in *\n               | match goal with\n                 | [ H : ~(exists x, and _ _) |- _ ]\n                   => specialize (fun x H0 H1 => H (ex_intro _ x (conj H0 H1)))\n                 end\n               | solve [ exfalso; eauto ] ].\nQed.\n\nLemma remove_duplicates_eq_NoDupA {A} (A_beq : A -> A -> bool)\n      (R : A -> A -> Prop)\n      {R_equiv : Equivalence R}\n      (A_lb : forall x y, A_beq x y = true -> R x y)\n      (ls : list A)\n  : NoDupA R ls -> remove_duplicates A_beq ls = ls.\nProof using Type.\n  cbv [remove_duplicates]; intro.\n  erewrite remove_duplicates'_eq_NoDupA by (eauto + apply NoDupA_rev; eauto).\n  rewrite rev_involutive; reflexivity.\nQed.\n\nLemma remove_duplicates'_eq_NoDup {A} (A_beq : A -> A -> bool)\n      (A_lb : forall x y, A_beq x y = true -> x = y)\n      (ls : list A)\n  : NoDup ls -> remove_duplicates' A_beq ls = ls.\nProof using Type.\n  intro H; apply remove_duplicates'_eq_NoDupA with (R:=eq); eauto.\n  now apply NoDupA_eq_NoDup.\nQed.\n\nLemma remove_duplicates_eq_NoDup {A} (A_beq : A -> A -> bool)\n      (A_lb : forall x y, A_beq x y = true -> x = y)\n      (ls : list A)\n  : NoDup ls -> remove_duplicates A_beq ls = ls.\nProof using Type.\n  intro H; apply remove_duplicates_eq_NoDupA with (R:=eq); eauto; try exact _.\n  now apply NoDupA_eq_NoDup.\nQed.\n\nLemma eq_repeat_nat_rect {A} x n\n  : @List.repeat A x n\n    = nat_rect _ nil (fun k repeat_k => x :: repeat_k) n.\nProof using Type. induction n; cbn; f_equal; assumption. Qed.\n\nLemma eq_firstn_nat_rect {A} n ls\n  : @List.firstn A n ls\n    = nat_rect\n        _\n        (fun _ => nil)\n        (fun n' firstn_n' ls\n         => match ls with\n            | nil => nil\n            | cons x xs => x :: firstn_n' xs\n            end)\n        n ls.\nProof using Type. revert ls; induction n, ls; cbn; f_equal; auto. Qed.\n\nLemma eq_skipn_nat_rect {A} n ls\n  : @List.skipn A n ls\n    = nat_rect\n        _\n        (fun ls => ls)\n        (fun n' skipn_n' ls\n         => match ls with\n            | nil => nil\n            | cons x xs => skipn_n' xs\n            end)\n        n ls.\nProof using Type. revert ls; induction n, ls; cbn; f_equal; auto. Qed.\n\nLemma eq_combine_list_rect {A B} xs ys\n  : @List.combine A B xs ys\n    = list_rect\n        _\n        (fun _ => nil)\n        (fun x xs combine_xs ys\n         => match ys with\n            | nil => nil\n            | y :: ys => (x, y) :: combine_xs ys\n            end)\n        xs ys.\nProof using Type. revert ys; induction xs, ys; cbn; f_equal; auto. Qed.\n\nLemma eq_length_list_rect {A} xs\n  : @List.length A xs\n    = (list_rect _)\n        0%nat\n        (fun _ xs length_xs => S length_xs)\n        xs.\nProof using Type. induction xs; cbn; f_equal; auto. Qed.\n\nLemma eq_rev_list_rect {A} xs\n  : @List.rev A xs\n    = (list_rect _)\n        nil\n        (fun x xs rev_xs => rev_xs ++ [x])\n        xs.\nProof using Type. induction xs; cbn; f_equal; auto. Qed.\n\nLemma eq_update_nth_nat_rect {A} n f xs\n  : @update_nth A n f xs\n    = (nat_rect _)\n        (fun xs => match xs with\n                   | nil => nil\n                   | x' :: xs' => f x' :: xs'\n                   end)\n        (fun n' update_nth_n' xs\n         => match xs with\n            | nil => nil\n            | x' :: xs' => x' :: update_nth_n' xs'\n            end)\n        n\n        xs.\nProof using Type. revert xs; induction n, xs; cbn; f_equal; auto. Qed.\n\nLemma flat_map_const_nil {A B} ls : @flat_map A B (fun _ => nil) ls = nil.\nProof using Type. induction ls; cbn; auto. Qed.\n\nLemma Forall_map_iff {A B} (f : A -> B) ls P\n  : Forall P (List.map f ls) <-> Forall (fun x => P (f x)) ls.\nProof.\n  induction ls as [|?? IH]; cbn [List.map]; split; intro H; inversion_clear H; constructor; split_iff; auto.\nQed.\n\nLemma ForallOrdPairs_map_iff {A B} (f : A -> B) ls P\n  : ForallOrdPairs P (List.map f ls) <-> ForallOrdPairs (fun x y => P (f x) (f y)) ls.\nProof.\n  pose proof (@Forall_map_iff A B f) as HF.\n  induction ls as [|?? IH]; cbn [List.map]; split; intro H; inversion_clear H; constructor; split_iff; auto.\nQed.\n\nLemma HdRel_map_iff {A B} (f : A -> B) R x xs\n  : HdRel R (f x) (List.map f xs) <-> HdRel (fun x y => R (f x) (f y)) x xs.\nProof.\n  destruct xs; split; intro H; inversion_clear H; constructor; auto.\nQed.\n\nLemma Sorted_map_iff {A B} (f : A -> B) R ls\n  : Sorted R (List.map f ls) <-> Sorted (fun x y => R (f x) (f y)) ls.\nProof.\n  induction ls as [|?? IH]; cbn [List.map]; split; intro H; inversion_clear H;\n    constructor; split_iff; auto; now apply HdRel_map_iff.\nQed.\n\nLemma In_nth_error_iff {A l x}\n  : In x l <-> exists n : nat, @nth_error A l n = Some x.\nProof.\n  split; [ now apply In_nth_error | intros [? ?]; eapply nth_error_In; eassumption ].\nQed.\n\nLemma fold_right_fun_apply {A B C} (ls : list B) (f : B -> C -> (A -> C)) init x\n  : fold_right (fun b F a => f b (F a) a) init ls x = fold_right (fun b c => f b c x) (init x) ls.\nProof. induction ls as [|?? IH]; cbn; now f_equal. Qed.\n\nLtac make_fold_right_fun_apply ty :=\n  multimatch ty with\n  | context[@fold_right ?AC ?B ?f ?init ?ls ?x]\n    => let fv := fresh in\n       let b := fresh \"b\" in\n       let F := fresh \"F\" in\n       let a := fresh \"a\" in\n       let f := lazymatch\n             constr:(\n               fun b F a\n               => match f b F a return _ with\n                  | fv\n                    => ltac:(let fv := (eval cbv [fv] in fv) in\n                             lazymatch (eval pattern a, (F a), b in fv) with\n                             | ?f _ _ _ => refine (fun x y z => f z y x)\n                             end)\n                  end) with\n           | fun _ _ _ => ?f => (eval cbv beta in f)\n           | ?f => idtac \"failed to eliminate the functional dependencies of\" f;\n                   fail 0 \"failed to eliminate the functional dependencies of\" f\n           end in\n       constr:(@fold_right_fun_apply _ _ _ ls f init x)\n  end.\n\nLtac rewrite_fold_right_fun_apply :=\n  match goal with\n  | [ H : ?T |- _ ] => let pf := make_fold_right_fun_apply T in\n                       rewrite pf in H\n  | [ |- ?T ] => let pf := make_fold_right_fun_apply T in\n                 rewrite pf\n  end.\n\nLemma fold_left_fun_apply {A B C} (ls : list B) (f : C -> B -> (A -> C)) init x\n  : fold_left (fun F b a => f (F a) b a) ls init x = fold_left (fun b c => f b c x) ls (init x).\nProof. rewrite <- !fold_left_rev_right; now rewrite_fold_right_fun_apply. Qed.\n\nLtac make_fold_left_fun_apply ty :=\n  multimatch ty with\n  | context[@fold_left ?AC ?B ?f ?ls ?init ?x]\n    => let fv := fresh in\n       let b := fresh \"b\" in\n       let F := fresh \"F\" in\n       let a := fresh \"a\" in\n       let f := lazymatch\n             constr:(\n               fun F b a\n               => match f F b a return _ with\n                  | fv\n                    => ltac:(let fv := (eval cbv [fv] in fv) in\n                             lazymatch (eval pattern a, b, (F a) in fv) with\n                             | ?f _ _ _ => refine (fun x y z => f z y x)\n                             end)\n                  end) with\n           | fun _ _ _ => ?f => (eval cbv beta in f)\n           | ?f => idtac \"failed to eliminate the functional dependencies of\" f;\n                   fail 0 \"failed to eliminate the functional dependencies of\" f\n           end in\n       constr:(@fold_left_fun_apply _ _ _ ls f init x)\n  end.\n\nLtac rewrite_fold_left_fun_apply :=\n  match goal with\n  | [ H : ?T |- _ ] => let pf := make_fold_left_fun_apply T in\n                       rewrite pf in H\n  | [ |- ?T ] => let pf := make_fold_left_fun_apply T in\n                 rewrite pf\n  end.\n\nDefinition span_cps' {A} (f : A -> bool) {T} (k : list A * list A -> T)\n  := fix span_cps' (ls : list A) (prefix : list A) : T\n    := match ls with\n       | nil => k (List.rev prefix, ls)\n       | x :: xs => if f x then span_cps' xs (x :: prefix) else k (List.rev prefix, ls)\n       end.\n\nDefinition span_cps {A} (f : A -> bool) (ls : list A) {T} (k : list A * list A -> T) : T\n  := span_cps' f k ls [].\n\nDefinition span {A} (f : A -> bool) (ls : list A) : list A * list A\n  := span_cps f ls id.\nDefinition takeWhile {A} (f : A -> bool) (ls : list A) : list A := fst (span f ls).\nDefinition dropWhile {A} (f : A -> bool) (ls : list A) : list A := snd (span f ls).\n\nLemma span_cps'_id A f xs T k prefix\n  : @span_cps' A f T k xs prefix = k (List.rev prefix ++ fst (span f xs), snd (span f xs)).\nProof.\n  revert T k prefix; induction xs as [|?? IH]; intros; cbn; try (rewrite !IH; clear IH); cbv [id]; break_innermost_match; cbn [List.rev fst snd List.app]; rewrite ?List.app_nil_l, ?List.app_nil_r, <- ?List.app_assoc; try reflexivity.\nQed.\n\nLemma span_cps_id A f xs T k\n  : @span_cps A f xs T k = k (span f xs).\nProof. cbv [span_cps]; rewrite span_cps'_id; destruct span; reflexivity. Qed.\n\nLemma span_nil A f : @span A f nil = (nil, nil).\nProof. reflexivity. Qed.\nLemma span_cons A f x xs : @span A f (x :: xs) = if f x then let '(xs, ys) := span f xs in (x :: xs, ys) else (nil, x :: xs).\nProof. cbv [span span_cps]; cbn; rewrite !span_cps'_id; cbv [id]; reflexivity. Qed.\n\nLemma span_app {A} f xs\n  : fst (@span A f xs) ++ snd (@span A f xs) = xs.\nProof. induction xs; rewrite ?span_nil, ?span_cons; break_innermost_match; boring. Qed.\n\nLemma takeWhile_app_dropWhile {A} f xs\n  : @takeWhile A f xs ++ @dropWhile A f xs = xs.\nProof. apply span_app. Qed.\n\nLemma filter_fst_span {A} f xs\n  : filter f (fst (@span A f xs)) = fst (@span A f xs).\nProof. induction xs; rewrite ?span_nil, ?span_cons; break_innermost_match; boring. Qed.\n\nLemma filter_takeWhile {A} f xs\n  : filter f (@takeWhile A f xs) = @takeWhile A f xs.\nProof. apply filter_fst_span. Qed.\n\nLemma hd_not_snd_span {A} f xs x\n      (H : nth_error (snd (@span A f xs)) 0 = Some x)\n  : f x = false.\nProof.\n  induction xs.\n  all: repeat first [ rewrite !span_nil in *\n                    | rewrite !span_cons in *\n                    | progress cbn in *\n                    | progress cbv [fst snd] in *\n                    | congruence\n                    | solve [ auto ]\n                    | break_innermost_match_hyps_step ].\nQed.\n\n\nDefinition groupBy' {A} (f : A -> A -> bool)\n  := fix groupBy' (ls : list A) (prefix : list A) : list (list A)\n    := match ls with\n       | [] => []\n       | x :: xs => span_cps'\n                      (f x) (fun '(xs, ys)\n                             => (x :: xs) :: match ys with\n                                             | [] => []\n                                             | _ => groupBy' ys []\n                                             end)\n                      xs prefix\n       end.\nDefinition groupBy {A} (f : A -> A -> bool) (ls : list A) : list (list A)\n  := groupBy' f ls [].\n\nDefinition span_cps'_rect A (f : A -> bool) T (k : list A * list A -> T)\n           (P : list A -> list A -> T -> Type)\n           (Pnil : forall prefix, P nil prefix (k (List.rev prefix, nil)))\n           (Pcons_true : forall x xs prefix rv, f x = true -> P xs (x :: prefix) rv -> P (x :: xs) prefix rv)\n           (Pcons_false : forall x ls prefix xs, f x = false -> ls = x :: xs -> P ls prefix (k (List.rev prefix, ls)))\n  : forall (ls : list A) (prefix : list A), P ls prefix (@span_cps' A f T k ls prefix).\nProof.\n  fix span_cps'_rect 1.\n  intro ls.\n  case_eq ls; [ | intros x xs ]; intros H prefix; cbn [span_cps'].\n  { apply Pnil. }\n  { destruct (f x) eqn:H'.\n    { apply Pcons_true; [ apply H' | apply span_cps'_rect ]. }\n    { generalize (Pcons_false x ls prefix xs H' H).\n      clear -H; subst ls; exact id. } }\nDefined.\n\nFixpoint concat_groupBy' {A f} ls prefix {struct ls}\n  : match ls with\n    | nil => List.concat (@groupBy' A f ls prefix) = nil\n    | x :: xs\n      => List.concat (@groupBy' A f ls prefix) = x :: List.rev prefix ++ xs\n    end.\nProof.\n  specialize (concat_groupBy' A f).\n  destruct ls as [|x xs].\n  { reflexivity. }\n  { cbn [groupBy'].\n    apply span_cps'_rect; cbn [concat List.rev List.app]; clear xs prefix.\n    { intros; rewrite ?List.app_nil_l, ?List.app_nil_r; split; reflexivity. }\n    { intros *; rewrite ?app_comm_cons, <- ?List.app_assoc; cbn [List.app]; trivial. }\n    { intros x' ls xs' prefix' H H'.\n      specialize (concat_groupBy' ls); cbv beta iota in *.\n      subst ls.\n      rewrite concat_groupBy'; cbn.\n      reflexivity. } }\nQed.\n\nLemma concat_groupBy A f ls\n  : List.concat (@groupBy A f ls) = ls.\nProof.\n  cbv [groupBy]; destruct ls as [|x xs]; [ reflexivity | apply (concat_groupBy' (x :: xs)) ].\nQed.\n\nLemma eq_filter_nil_Forall_iff {A} f (xs : list A)\n  : filter f xs = nil <-> Forall (fun x => f x = false) xs.\nProof. induction xs; cbn; break_innermost_match; boring; inversion_list; inversion_one_head Forall; congruence. Qed.\n\nDefinition is_nil {A} (x : list A) : bool\n  := match x with\n     | nil => true\n     | _ => false\n     end.\n\nLemma is_nil_eq_nil_iff {A x} : @is_nil A x = true <-> x = nil.\nProof. destruct x; cbv; split; congruence. Qed.\n\nLemma find_none_iff {A} (f : A -> bool) (xs : list A) : find f xs = None <-> forall x, In x xs -> f x = false.\nProof.\n  split; try apply find_none.\n  pose proof (find_some f xs) as H.\n  edestruct find; [ specialize (H _ eq_refl) | reflexivity ].\n  destruct H as [H1 H2].\n  intro H'; specialize (H' _ H1); congruence.\nQed.\n\nLemma find_none_iff_nth_error {A} (f : A -> bool) (xs : list A) : find f xs = None <-> forall n a, nth_error xs n = Some a -> f a = false.\nProof.\n  rewrite find_none_iff.\n  setoid_rewrite In_nth_error_iff.\n  intuition (destruct_head'_ex; eauto).\nQed.\n\nLemma find_some_iff {A} (f : A -> bool) (xs : list A) x\n  : find f xs = Some x\n    <-> exists n, nth_error xs n = Some x /\\ f x = true /\\ forall n', n' < n -> forall a, nth_error xs n' = Some a -> f a = false.\nProof.\n  induction xs as [|y xs IHxs]; cbn [find].\n  all: repeat first [ apply conj\n                    | progress intros\n                    | progress destruct_head'_ex\n                    | progress destruct_head'_and\n                    | progress Option.inversion_option\n                    | progress break_innermost_match_hyps\n                    | progress subst\n                    | progress cbn in *\n                    | assumption\n                    | exists 0; cbn; repeat split; try assumption; (idtac + (intros; exfalso)); lia\n                    | progress break_innermost_match\n                    | reflexivity\n                    | congruence\n                    | match goal with\n                      | [ H : nth_error nil ?i = _ |- _ ] => is_var i; destruct i\n                      | [ H : nth_error (cons _ _) ?i = _ |- _ ] => is_var i; destruct i\n                      | [ H : ?T <-> _, H' : ?T |- _ ] => destruct H as [H _]; specialize (H H')\n                      | [ H : S ?x < S ?y |- _ ] => assert (x < y) by lia; clear H\n                      | [ H : forall a, Some _ = Some a -> _ |- _ ] => specialize (H _ eq_refl)\n                      | [ H : forall a, Some a = Some _ -> _ |- _ ] => specialize (H _ eq_refl)\n                      | [ H : forall n, n < S ?v -> @?P n |- _ ]\n                        => assert (forall n, n < v -> P (S n)) by (intros ? ?; apply H; lia);\n                           specialize (H 0 ltac:(lia))\n                      end\n                    | eexists (S _); cbn; repeat apply conj; [ eassumption | .. ]; try assumption; intros [|?]\n                    | progress split_iff\n                    | solve [ eauto with nocore ]\n                    | progress specialize_by eauto ].\nQed.\n\nSection find_index.\n  Context {A} (f : A -> bool).\n\n  Definition find_index (xs : list A) : option nat\n    := option_map (@fst _ _) (find (fun v => f (snd v)) (enumerate xs)).\n\n  Lemma find_index_none_iff xs\n    : find_index xs = None <-> forall i a, nth_error xs i = Some a -> f a = false.\n  Proof using Type.\n    cbv [find_index enumerate].\n    edestruct find eqn:H; cbn; [ split; [ congruence | ] | split; [ intros _ | reflexivity ] ].\n    { rewrite find_some_iff in H.\n      destruct H as [n H]; intro H'; specialize (H' n).\n      rewrite nth_error_combine, nth_error_seq in H.\n      break_innermost_match_hyps; destruct_head'_and; Option.inversion_option; subst; cbn in *.\n      specialize (H' _ eq_refl); congruence. }\n    { rewrite find_none_iff_nth_error in H.\n      intros n a; specialize (H n (n, a)).\n      rewrite nth_error_combine, nth_error_seq in H.\n      edestruct lt_dec; [ | rewrite nth_error_length_error by lia; congruence ].\n      edestruct nth_error eqn:?; intros; Option.inversion_option; subst; specialize (H eq_refl); assumption. }\n  Qed.\n\n  Lemma find_index_some_iff xs n\n    : find_index xs = Some n\n      <-> ((exists x, nth_error xs n = Some x /\\ f x = true) /\\ forall n', n' < n -> forall a, nth_error xs n' = Some a -> f a = false).\n  Proof using Type.\n    cbv [find_index enumerate].\n    edestruct find eqn:H; cbn; [ | split; [ congruence | ] ].\n    { rewrite find_some_iff in H.\n      destruct H as [n' H].\n      rewrite nth_error_combine, nth_error_seq in H.\n      setoid_rewrite nth_error_combine in H.\n      setoid_rewrite nth_error_seq in H.\n      break_innermost_match_hyps; split; intro H'; destruct_head'_and; Option.inversion_option; subst; cbn in *.\n      all: repeat apply conj; eauto.\n      { let H := match goal with H : forall n, n < _ -> _ |- _ => H end in\n        intros i H' a' H''; specialize (H i H' (i, a'));\n          rewrite H'' in H;\n          break_innermost_match_hyps; [ specialize (H eq_refl); assumption | ].\n        rewrite nth_error_length_error in H'' by lia; congruence. }\n      { match goal with |- Some ?n = Some ?m => destruct (lt_eq_lt_dec n m) end; destruct_head' sumbool; subst; try reflexivity.\n        all: match goal with H : forall n', n' < _ -> _ |- _ => specialize (H _ ltac:(eassumption)) end.\n        { match goal with H : forall a, nth_error _ _ = Some _ -> _ |- _ => specialize (H _ ltac:(eassumption)); congruence end. }\n        { destruct_head'_ex; destruct_head'_and.\n          break_innermost_match_hyps; try congruence; try lia.\n          Option.inversion_option; subst.\n          match goal with H : forall x, Some _ = Some x -> _ |- _ => specialize (H _ eq_refl) end.\n          cbn in *.\n          congruence. } } }\n    { rewrite find_none_iff_nth_error in H.\n      intros [ [a [H0 H1]] ?]; specialize (H n (n, a)).\n      rewrite nth_error_combine, nth_error_seq, H0 in H.\n      break_innermost_match_hyps; [ | rewrite nth_error_length_error in H0 by lia; congruence ].\n      specialize (H eq_refl); cbn in *.\n      congruence. }\n  Qed.\nEnd find_index.\n\nLemma fold_left_id {A B} init ls\n  : @fold_left A B (fun x _ => x) ls init = init.\nProof.\n  revert init; induction ls as [|x xs IHxs]; cbn [fold_left]; eauto.\nQed.\n\nLemma fold_left_cons {B} init ls\n  : @fold_left _ B (fun xs x => cons x xs) ls init = List.rev ls ++ init.\nProof.\n  revert init; induction ls as [|x xs IHxs]; cbn [fold_left List.rev];\n    intros; rewrite ?IHxs, ?List.app_nil_l, ?List.app_nil_r, <- ?List.app_assoc;\n    cbn [List.app]; reflexivity.\nQed.\n\nLemma map_swap_combine {A B} ls1 ls2\n  : List.map (fun xy => (snd xy, fst xy)) (List.combine ls2 ls1)\n    = @List.combine A B ls1 ls2.\nProof.\n  revert ls2; induction ls1 as [|x xs IHxs], ls2 as [|y ys]; cbn [List.combine List.map fst snd]; congruence.\nQed.\n\nLemma fold_right_higher_order A B C f a ls (F : _ -> C)\n  : fold_right (fun x acc a => acc (f x a)) F ls a\n    = F (@fold_right A B f a (List.rev ls)).\nProof.\n  revert F a; induction ls; cbn; try reflexivity; intros.\n  rewrite IHls, fold_right_app; cbn.\n  reflexivity.\nQed.\n\nLemma fold_right_rev_higher_order A B f a ls\n  : @fold_right A B f a (List.rev ls)\n    = fold_right (fun x acc a => acc (f x a)) id ls a.\nProof. symmetry; apply fold_right_higher_order. Qed.\n\nLemma fold_left_higher_order A B C f a ls (F : _ -> C)\n  : fold_left (fun acc x a => acc (f a x)) ls F a\n    = F (@fold_left A B f (List.rev ls) a).\nProof.\n  revert F a; induction ls; cbn; try reflexivity; intros.\n  rewrite IHls, fold_left_app; cbn.\n  reflexivity.\nQed.\n\nLemma fold_left_rev_higher_order A B f a ls\n  : @fold_left A B f (List.rev ls) a\n    = fold_left (fun acc x a => acc (f a x)) ls id a.\nProof. symmetry; apply fold_left_higher_order. Qed.\n\n(* This module is here because the equivalent standard library functions fail to be \"reified by unfolding\". *)\n\nModule Reifiable.\n  Section __.\n    Context {X : Type}\n            (eqb : X -> X -> bool)\n            (eqb_eq : forall x1 x2, eqb x1 x2 = true <-> x1 = x2).\n\n    Definition existsb (f : X -> bool) (l : list X) : bool :=\n      fold_right (fun x found => orb (f x) found) false l.\n\n    Lemma reifiable_existsb_is_existsb : forall (f : X -> bool) (l : list X),\n      existsb f l = List.existsb f l.\n    Proof. reflexivity. Qed.\n\n    Lemma existsb_eqb_true_iff : forall x l, existsb (eqb x) l = true <-> In x l.\n    Proof.\n      intros x l. rewrite reifiable_existsb_is_existsb. rewrite existsb_exists. split.\n      - intros [x0 [H1 H2]]. rewrite eqb_eq in H2. subst. assumption.\n      - intros H. exists x. split.\n        + assumption.\n        + apply eqb_eq. reflexivity.\n    Qed.\n\n    Lemma existsb_eqb_false_iff : forall x l, existsb (eqb x) l = false <-> ~In x l.\n    Proof.\n      intros. rewrite <- existsb_eqb_true_iff. split.\n      - intros H. rewrite H. auto.\n      - intros H. destruct (existsb (eqb x) l).\n        + exfalso. apply H. reflexivity.\n        + reflexivity.\n    Qed.\n\n    Definition nodupb (l : list X) :=\n      fold_right (fun x l' => if (existsb (eqb x) l') then l' else (x :: l')) [] l.\n\n    Lemma nodupb_in_iff (x : X) (l : list X) : In x l <-> In x (nodupb l).\n    Proof.\n      induction l as [|x' l' IHl'].\n      - reflexivity.\n      - simpl. destruct (existsb (eqb x') (nodupb l')) eqn:E.\n        + rewrite existsb_eqb_true_iff in E. split.\n          -- intros [H|H].\n            ++ rewrite <- H. apply E.\n            ++ rewrite <- IHl'. apply H.\n          -- intros H. right. rewrite IHl'. apply H.\n        + rewrite existsb_eqb_false_iff in E. split.\n          -- intros [H|H].\n            ++ rewrite H. simpl. left. reflexivity.\n            ++ simpl. right. rewrite <- IHl'. apply H.\n          -- simpl. intros [H|H].\n            ++ left. apply H.\n            ++ right. rewrite IHl'. apply H.\n    Qed.\n\n    Lemma nodupb_split (x : X) (l : list X) : In x l ->\n      exists l1 l2, nodupb l = l1 ++ [x] ++ l2 /\\ ~ In x l1 /\\ ~ In x l2.\n    Proof.\n      intros H. induction l as [| x' l'].\n      - simpl in H. destruct H.\n      - simpl in H. destruct H as [H|H].\n        + rewrite H. clear H. simpl. destruct (existsb (eqb x) (nodupb l')) eqn:E. \n          -- rewrite existsb_eqb_true_iff in E. rewrite <- nodupb_in_iff in E.\n             apply IHl' in E. apply E.\n          -- exists []. exists (nodupb l'). split.\n            ++ rewrite app_nil_l. reflexivity.\n            ++ split.\n              --- auto.\n              --- rewrite <- existsb_eqb_false_iff. apply E.\n        + apply IHl' in H. clear IHl'. simpl. destruct (existsb (eqb x') (nodupb l')) eqn:E.\n          -- apply H.\n          -- destruct H as [l1 [l2 [H1 [H2 H3] ] ] ]. exists (x' :: l1). exists l2. split.\n            ++ rewrite H1. reflexivity.\n            ++ split.\n              --- simpl. intros [H|H].\n                +++ rewrite H in *. rewrite H1 in E. apply existsb_eqb_false_iff in E. apply E.\n                    repeat rewrite in_app_iff. right. left. simpl. left. reflexivity.\n                +++ apply H2. apply H.\n              --- apply H3.\n    Qed.\n  End __.\nEnd Reifiable.\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/ListUtil.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819591324418, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.29852765882780785}}
{"text": "(** * Implementation of [ϕ] (aka SplitBody) *)\n\nRequire Import TM.Code.ProgrammingTools.\nRequire Import TM.LM.Semantics TM.LM.Alphabets.\nRequire Import TM.LM.CaseCom.\nRequire Import TM.Code.ListTM TM.Code.CaseList TM.Code.CaseNat.\n\nLocal Arguments plus : simpl never.\nLocal Arguments mult : simpl never.\n\n\n(** The [JumpTarget] machine only operates on programs. Thus we define [JumpTarget] on the alphabet [sigPro^+]. *)\n\n(** This is the only way we can encode [nat] on [sigPro]: as a variable token. *)\nDefinition retr_nat_prog : Retract sigNat sigPro := Retract_sigList_X _.\n\n\n(** append a token to the token list *)\nDefinition App_Comens : pTM sigPro^+ (FinType(EqType unit)) 2 :=\n  App' _ @ [|Fin0; Fin1|];;\n  MoveValue _ @ [|Fin1; Fin0|].\n\nDefinition App_Comens_Rel : pRel sigPro^+ (FinType(EqType unit)) 2 :=\n  ignoreParam (\n      fun tin tout =>\n        forall (Q Q' : list Com),\n          tin[@Fin0] ≃ Q ->\n          tin[@Fin1] ≃ Q' ->\n          tout[@Fin0] ≃ Q ++ Q' /\\\n          isRight tout[@Fin1]\n    ).\n\nLemma App_Comens_Realise : App_Comens ⊨ App_Comens_Rel.\nProof.\n  eapply Realise_monotone.\n  { unfold App_Comens. TM_Correct.\n    - apply App'_Realise with (X := Com).\n    - apply MoveValue_Realise with (X := Pro).\n  }\n  {\n    intros tin ((), tout) H. intros Q Q' HEncQ HEncQ'.\n    TMSimp. modpon H. modpon H0. auto.\n  }\nQed.\n\n\nDefinition App_Comens_steps (Q Q': Pro) := 1 + App'_steps _ Q + MoveValue_steps _ _ (Q ++ Q') Q.\n\nDefinition App_Comens_T : tRel sigPro^+ 2 :=\n  fun tin k => exists (Q Q' : list Com), tin[@Fin0] ≃ Q /\\ tin[@Fin1] ≃ Q' /\\ App_Comens_steps Q Q' <= k.\n\nLemma App_Comens_Terminates : projT1 App_Comens ↓ App_Comens_T.\nProof.\n  eapply TerminatesIn_monotone.\n  { unfold App_Comens. TM_Correct.\n    - apply App'_Realise with (X := Com).\n    - apply App'_Terminates with (X := Com).\n    - apply MoveValue_Terminates with (X := Pro) (Y := Pro).\n  }\n  {\n    intros tin k (Q&Q'&HEncQ&HEncQ'&Hk).\n    exists (App'_steps _ Q), (MoveValue_steps _ _ (Q++Q') Q); cbn; repeat split; try omega.\n    hnf; cbn. eauto. now rewrite Hk.\n    intros tmid () (HApp&HInjApp); TMSimp. modpon HApp.\n    exists (Q++Q'), Q. repeat split; eauto.\n  }\nQed.\n\n\n(** append a token to the token list *)\nDefinition App_ACom (t : ACom) : pTM sigPro^+ unit 2 :=\n  WriteValue (encode [ACom2Com t]) @ [|Fin1|];;\n  App_Comens.\n\nDefinition App_ACom_Rel (t : ACom) : pRel sigPro^+ unit 2 :=\n  ignoreParam (\n      fun tin tout =>\n        forall (Q : list Com),\n          tin[@Fin0] ≃ Q ->\n          isRight tin[@Fin1] ->\n          tout[@Fin0] ≃ Q ++ [ACom2Com t] /\\\n          isRight tout[@Fin1]\n    ).\n\nLemma App_ACom_Realise t : App_ACom t ⊨ App_ACom_Rel t.\nProof.\n  eapply Realise_monotone.\n  { unfold App_ACom. TM_Correct.\n    - apply App_Comens_Realise.\n  }\n  {\n    intros tin ((), tout) H. intros Q HENcQ HRight1.\n    TMSimp. specialize (H [ACom2Com t] eq_refl). modpon H. modpon H0. auto.\n  }\nQed.\n\nDefinition App_ACom_steps (Q: Pro) (t: ACom) := 1 + WriteValue_steps (size _ [ACom2Com t]) + App_Comens_steps Q [ACom2Com t].\n\nDefinition App_ACom_T (t: ACom) : tRel sigPro^+ 2 :=\n  fun tin k => exists (Q: list Com), tin[@Fin0] ≃ Q /\\ isRight tin[@Fin1] /\\ App_ACom_steps Q t <= k.\n\nLemma App_ACom_Terminates (t: ACom) : projT1 (App_ACom t) ↓ App_ACom_T t.\nProof.\n  eapply TerminatesIn_monotone.\n  { unfold App_ACom. TM_Correct.\n    - apply App_Comens_Terminates.\n  }\n  {\n    intros tin k. intros (Q&HEncQ&HRight&Hk).\n    exists (WriteValue_steps (size _ [ACom2Com t])), (App_Comens_steps Q [ACom2Com t]). cbn; repeat split; try omega.\n    now rewrite Hk.\n    intros tmid () (HWrite&HInjWrite); hnf; cbn; TMSimp. specialize (HWrite [ACom2Com t] eq_refl). modpon HWrite. eauto.\n  }\nQed.\n\n\n\n(** Add a singleton list of tokes to [Q] *)\nDefinition App_Com : pTM sigPro^+ (FinType(EqType unit)) 3 :=\n  Constr_nil _ @ [|Fin2|];;\n  Constr_cons _@ [|Fin2; Fin1|];;\n  App_Comens @ [|Fin0; Fin2|];;\n  Reset _ @ [|Fin1|].\n\nDefinition App_Com_Rel : pRel sigPro^+ (FinType(EqType unit)) 3 :=\n  ignoreParam (\n      fun tin tout =>\n        forall (Q : list Com) (t : Com),\n          tin[@Fin0] ≃ Q ->\n          tin[@Fin1] ≃ t ->\n          isRight tin[@Fin2] ->\n          tout[@Fin0] ≃ Q ++ [t] /\\\n          isRight tout[@Fin1] /\\\n          isRight tout[@Fin2]\n    ).\n\n\nLemma App_Com_Realise : App_Com ⊨ App_Com_Rel.\nProof.\n  eapply Realise_monotone.\n  { unfold App_Com. TM_Correct.\n    - apply App_Comens_Realise.\n    - apply Reset_Realise with (X := Com).\n  }\n  { intros tin ((), tout) H. cbn. intros Q t HEncQ HEncT HRight.\n    unfold sigPro, sigCom in *. TMSimp.\n    rename H into HNil, H0 into HCons, H1 into HApp, H2 into HReset.\n    modpon HNil. modpon HCons. modpon HApp. modpon HReset. repeat split; auto.\n  }\nQed.\n\nDefinition App_Com_steps (Q: Pro) (t:Com) :=\n  3 + Constr_nil_steps + Constr_cons_steps _ t + App_Comens_steps Q [t] + Reset_steps _ t.\n\nDefinition App_Com_T : tRel sigPro^+ 3 :=\n  fun tin k => exists (Q: list Com) (t: Com), tin[@Fin0] ≃ Q /\\ tin[@Fin1] ≃ t /\\ isRight tin[@Fin2] /\\ App_Com_steps Q t <= k.\n\nLemma App_Com_Terminates : projT1 App_Com ↓ App_Com_T.\nProof.\n  eapply TerminatesIn_monotone.\n  { unfold App_Com. TM_Correct.\n    - apply App_Comens_Realise.\n    - apply App_Comens_Terminates.\n    - apply Reset_Terminates with (X := Com).\n  }\n  {\n    intros tin k (Q&t&HEncQ&HEncT&HRight&Hk). unfold App_Com_steps in Hk.\n    exists (Constr_nil_steps), (1 + Constr_cons_steps _ t + 1 + App_Comens_steps Q [t] + Reset_steps _ t). cbn. repeat split; try omega.\n    intros tmid () (HNil&HInjNil); TMSimp. modpon HNil.\n    exists (Constr_cons_steps _ t), (1 + App_Comens_steps Q [t] + Reset_steps _ t). cbn. repeat split; try omega.\n    eauto. now rewrite !Nat.add_assoc.\n    unfold sigPro in *. intros tmid0 () (HCons&HInjCons); TMSimp. modpon HCons.\n    exists (App_Comens_steps Q [t]), (Reset_steps _ t). cbn. repeat split; try omega.\n    hnf; cbn. do 2 eexists; repeat split; eauto. reflexivity.\n    intros tmid1 _ (HApp&HInjApp); TMSimp. modpon HApp.\n    eexists. split; eauto. now setoid_rewrite Reset_steps_comp.\n  }\nQed.\n\n\n\nDefinition JumpTarget_Step : pTM sigPro^+ (option bool) 5 :=\n  If (CaseList sigCom_fin @ [|Fin0; Fin3|])\n     (Switch (ChangeAlphabet CaseCom _ @ [|Fin3|])\n             (fun t : option ACom =>\n                match t with\n                | Some retAT =>\n                  If (CaseNat ⇑ retr_nat_prog @ [|Fin2|])\n                     (Return (App_ACom retAT @ [|Fin1; Fin4|]) None) (* continue *)\n                     (Return (ResetEmpty1 _ @ [|Fin2|]) (Some true)) (* return true *)\n                | Some lamAT =>\n                  Return (Constr_S ⇑ retr_nat_prog @ [|Fin2|];;\n                          App_ACom lamAT @ [|Fin1; Fin4|])\n                         None (* continue *)\n                | Some appAT =>\n                  Return (App_ACom appAT @ [|Fin1;Fin4|])\n                         None (* continue *)\n                | None => (* Variable *)\n                  Return (Constr_varT ⇑ _ @ [|Fin3|];;\n                          App_Com @ [|Fin1; Fin3; Fin4|])\n                         None (* continue *)\n                end))\n     (Return Nop (Some false)) (* return false *)\n.\n\n\nDefinition JumpTarget_Step_Rel : pRel sigPro^+ (option bool) 5 :=\n  fun tin '(yout, tout) =>\n    forall (P Q : Pro) (k : nat),\n      tin[@Fin0] ≃ P ->\n      tin[@Fin1] ≃ Q ->\n      tin[@Fin2] ≃ k ->\n      isRight tin[@Fin3] -> isRight tin[@Fin4] ->\n      match yout, P with\n      | _, retT :: P =>\n        match yout, k with\n        | Some true, O => (* return true *)\n          tout[@Fin0] ≃ P /\\\n          tout[@Fin1] ≃ Q /\\\n          isRight tout[@Fin2]\n        | None, S k' => (* continue *)\n          tout[@Fin0] ≃ P /\\\n          tout[@Fin1] ≃ Q ++ [retT] /\\\n          tout[@Fin2] ≃ k'\n        | _, _ => False (* not the case *)\n        end\n      | None, lamT :: P => (* continue *)\n        tout[@Fin0] ≃ P /\\\n        tout[@Fin1] ≃ Q ++ [lamT] /\\\n        tout[@Fin2] ≃ S k\n      | None, t :: P => (* continue *)\n        tout[@Fin0] ≃ P /\\\n        tout[@Fin1] ≃ Q ++ [t] /\\\n        tout[@Fin2] ≃ k\n      | Some false, nil => (* return false *)\n        (*\n        tout[@Fin0] ≃ nil /\\\n        tout[@Fin1] ≃ Q /\\\n        tout[@Fin2] ≃ k\n         *)\n        True\n      | _, _ => False (* not the case *)\n      end /\\\n      isRight tout[@Fin3] /\\\n      isRight tout[@Fin4].\n\n\nLemma JumpTarget_Step_Realise : JumpTarget_Step ⊨ JumpTarget_Step_Rel.\nProof.\n  eapply Realise_monotone.\n  { unfold JumpTarget_Step. TM_Correct.\n    - eapply RealiseIn_Realise. apply CaseCom_Sem.\n    - apply App_ACom_Realise.\n    - eapply RealiseIn_Realise. apply ResetEmpty1_Sem with (X := nat).\n    - apply App_ACom_Realise.\n    - apply App_ACom_Realise.\n    - eapply RealiseIn_Realise. apply Constr_varT_Sem.\n    - apply App_Com_Realise.\n  }\n  {\n    intros tin (yout, tout) H. cbn. intros P Q k HEncP HEncQ HEncK HInt3 HInt4.\n    unfold sigPro in *. rename H into HIf.\n    destruct HIf; TMSimp.\n    { (* Then of [CaseList], i.e. P = t :: P' *) rename H into HCaseList, H0 into HCaseCom, H1 into HCase.\n      modpon HCaseList. destruct P as [ | t P']; auto; modpon HCaseList.\n      modpon HCaseCom.\n      destruct ymid as [ [ | | ] | ]; try destruct t; auto; simpl_surject; TMSimp.\n      { (* t = retT *)\n        destruct HCase; TMSimp.\n        { (* k = S k' *) rename H into HCaseNat, H0 into HApp.\n          modpon HCaseNat. destruct k as [ | k']; auto; modpon HCaseNat.\n          modpon HApp.\n          repeat split; auto.\n        }\n        { (* k = 0 *) rename H into HCaseNat. rename H0 into HReset.\n          modpon HCaseNat. destruct k as [ | k']; auto; modpon HCaseNat. modpon HReset .\n          repeat split; auto.\n        }\n      }\n      { (* t = lamT *) rename H into HS, H0 into HApp.\n        modpon HS.\n        modpon HApp.\n        repeat split; auto.\n      }\n      { (* t = appT *) rename H into HApp.\n        modpon HApp.\n        repeat split; auto.\n      }\n      { (* t = varT *) rename H into HVar, H0 into HApp.\n        modpon HVar.\n        modpon HApp.\n        repeat split; auto.\n      }\n    }\n    { (* Else of [CaseList], i.e. P = nil *)\n      modpon H. destruct P; auto; modpon H; auto.\n    }\n  }\nQed.\n\n\n(* Steps after the [CaseCom], depending on [t] *)\nLocal Definition JumpTarget_Step_steps_CaseCom (Q: Pro) (k: nat) (t: Com) :=\n  match t with\n  | retT =>\n    match k with\n    | S _ => 1 + CaseNat_steps + App_ACom_steps Q retAT\n    | 0 => 2 + CaseNat_steps + ResetEmpty1_steps\n    end\n  | lamT => 1 + Constr_S_steps + App_ACom_steps Q lamAT\n  | appT => App_ACom_steps Q appAT\n  | varT n => 1 + Constr_varT_steps + App_Com_steps Q t\n  end.\n\n(* Steps after the [CaseList] *)\nLocal Definition JumpTarget_Step_steps_CaseList (P Q : Pro) (k: nat) :=\n  match P with\n  | t :: P' => 1 + CaseCom_steps + JumpTarget_Step_steps_CaseCom Q k t\n  | nil => 0\n  end.\n\n(* Total steps *)\nDefinition JumpTarget_Step_steps (P Q: Pro) (k: nat) :=\n  1 + CaseList_steps _ P + JumpTarget_Step_steps_CaseList P Q k.\n\n\nDefinition JumpTarget_Step_T : tRel sigPro^+ 5 :=\n  fun tin steps => (* Warning: I have to use another variable for the steps, since [k] is used. *)\n    exists (P Q : Pro) (k : nat),\n      tin[@Fin0] ≃ P /\\\n      tin[@Fin1] ≃ Q /\\\n      tin[@Fin2] ≃ k /\\\n      isRight tin[@Fin3] /\\ isRight tin[@Fin4] /\\\n      JumpTarget_Step_steps P Q k <= steps.\n\nLemma JumpTarget_Step_Terminates : projT1 JumpTarget_Step ↓ JumpTarget_Step_T.\nProof.\n  eapply TerminatesIn_monotone.\n  { unfold JumpTarget_Step. TM_Correct.\n    - eapply RealiseIn_Realise. apply CaseCom_Sem.\n    - eapply RealiseIn_TerminatesIn. apply CaseCom_Sem.\n    - apply App_ACom_Terminates.\n    - eapply RealiseIn_TerminatesIn. apply ResetEmpty1_Sem with (X := nat).\n    - apply App_ACom_Terminates.\n    - apply App_ACom_Terminates.\n    - eapply RealiseIn_Realise. apply Constr_varT_Sem.\n    - eapply RealiseIn_TerminatesIn. apply Constr_varT_Sem.\n    - apply App_Com_Terminates.\n  }\n  {\n    intros tin steps (P&Q&k&HEncP&HEncQ&HEncK&HRight3&HRight4&Hk). unfold JumpTarget_Step_steps in Hk. cbn in *.\n    unfold sigPro in *.\n    exists (CaseList_steps _ P), (JumpTarget_Step_steps_CaseList P Q k). cbn; repeat split; try omega. eauto.\n    intros tmid bmatchlist (HCaseList&HCaseListInj); TMSimp. modpon HCaseList.\n    destruct bmatchlist, P as [ | t P']; auto; modpon HCaseList.\n    { (* P = t :: P' (* other case is done by auto *) *)\n      exists (CaseCom_steps), (JumpTarget_Step_steps_CaseCom Q k t). cbn; repeat split; try omega.\n      intros tmid1 ytok (HCaseCom&HCaseComInj); TMSimp. modpon HCaseCom.\n      destruct ytok as [ [ | | ] | ]; destruct t; auto; simpl_surject; TMSimp.\n      { (* t = retT *)\n        exists CaseNat_steps.\n        destruct k as [ | k'].\n        - (* k = 0 *)\n          exists ResetEmpty1_steps. repeat split; try omega.\n          intros tmid2 bCaseNat (HCaseNat&HCaseNatInj); TMSimp. modpon HCaseNat. destruct bCaseNat; auto.\n        - (* k = S k' *)\n          exists (App_ACom_steps Q retAT). repeat split; try omega.\n          intros tmid2 bCaseNat (HCaseNat&HCaseNatInj); TMSimp. modpon HCaseNat. destruct bCaseNat; auto. hnf; cbn. eauto.\n      }\n      { (* t = lamT *)\n        exists (Constr_S_steps), (App_ACom_steps Q lamAT). repeat split; try omega.\n        intros tmid2 () (HS&HSInj); TMSimp. modpon HS. hnf; cbn. eauto.\n      }\n      { (* t = appT *) hnf; cbn; eauto. }\n      { (* t = varT n *)\n        exists (Constr_varT_steps), (App_Com_steps Q (varT n)). repeat split; try omega.\n        intros tmid2 H (HVarT&HVarTInj); TMSimp. modpon HVarT. hnf; cbn. eauto 6.\n      }\n    }\n  }\nQed.\n\n\n\nFixpoint jumpTarget_k (k:nat) (P:Pro) : nat :=\n  match P with\n  | retT :: P' => match k with\n                 | 0 => 0\n                 | S k' => jumpTarget_k k' P'\n                 end\n  | lamT :: P' => jumpTarget_k (S k) P'\n  | t :: P'    => jumpTarget_k k P' (* either [varT n] or [appT] *)\n  | []         => k\n  end.\n\nGoal forall k P, jumpTarget_k k P <= k + |P|.\nProof.\n  intros k P. revert k. induction P as [ | t P IH]; intros; cbn in *.\n  - omega.\n  - destruct t; cbn.\n    + rewrite IH. omega.\n    + rewrite IH. omega.\n    + rewrite IH. omega.\n    + destruct k. omega. rewrite IH. omega.\nQed.\n\n\nDefinition JumpTarget_Loop := While JumpTarget_Step.\n\n\nDefinition JumpTarget_Loop_Rel : pRel sigPro^+ bool 5 :=\n  fun tin '(yout, tout) =>\n    forall (P Q : Pro) (k : nat),\n      tin[@Fin0] ≃ P ->\n      tin[@Fin1] ≃ Q ->\n      tin[@Fin2] ≃ k ->\n      isRight tin[@Fin3] -> isRight tin[@Fin4] ->\n      match yout with\n      | true =>\n        exists (P' Q' : Pro),\n        jumpTarget k Q P = Some (Q', P') /\\\n        tout[@Fin0] ≃ P' /\\\n        tout[@Fin1] ≃ Q' /\\\n        isRight tout[@Fin2] /\\\n        isRight tout[@Fin3] /\\ isRight tout[@Fin4]\n      | false =>\n        jumpTarget k Q P = None\n      end.\n\n\n\nLemma JumpTarget_Loop_Realise : JumpTarget_Loop ⊨ JumpTarget_Loop_Rel.\nProof.\n  eapply Realise_monotone.\n  { unfold JumpTarget_Loop. TM_Correct.\n    - apply JumpTarget_Step_Realise.\n  }\n  {\n    apply WhileInduction; intros; intros P Q k HEncP HEncQ HEncK HRight3 HRight4; cbn in *.\n    {\n      modpon HLastStep. destruct yout, P as [ | [ | | | ] P']; auto. destruct k; auto. modpon HLastStep.\n      cbn. eauto 10.\n    }\n    {\n      modpon HStar.\n      destruct P as [ | [ | | | ] P']; auto; modpon HStar.\n      - (* P = varT n :: P' *) modpon HLastStep. destruct yout; auto.\n      - (* P = appT :: P' *) modpon HLastStep. destruct yout; auto.\n      - (* P = lamT :: P' *) modpon HLastStep. destruct yout; auto.\n      - (* P = varT k :: P', k = S k' *) destruct k as [ | k']; auto; modpon HStar. modpon HLastStep. destruct yout; auto.\n    }\n  }\nQed.\n\n\nFixpoint JumpTarget_Loop_steps (P Q: Pro) (k: nat) : nat :=\n  match P with\n  | nil => JumpTarget_Step_steps P Q k\n  | t :: P' =>\n    match t with\n    | retT =>\n      match k with\n      | S k' => 1 + JumpTarget_Step_steps P Q k + JumpTarget_Loop_steps P' (Q++[t]) k'\n      | 0 =>        JumpTarget_Step_steps P Q k (* terminal case *)\n      end\n    | lamT =>   1 + JumpTarget_Step_steps P Q k + JumpTarget_Loop_steps P' (Q++[t]) (S k)\n    | appT =>   1 + JumpTarget_Step_steps P Q k + JumpTarget_Loop_steps P' (Q++[t]) k\n    | varT n => 1 + JumpTarget_Step_steps P Q k + JumpTarget_Loop_steps P' (Q++[t]) k\n    end\n  end.\n\nDefinition JumpTarget_Loop_T : tRel sigPro^+ 5 :=\n  fun tin steps =>\n    exists (P Q : Pro) (k : nat),\n      tin[@Fin0] ≃ P /\\\n      tin[@Fin1] ≃ Q /\\\n      tin[@Fin2] ≃ k /\\\n      isRight tin[@Fin3] /\\ isRight tin[@Fin4] /\\\n      JumpTarget_Loop_steps P Q k <= steps.\n\n\nLemma JumpTarget_Loop_Terminates : projT1 JumpTarget_Loop ↓ JumpTarget_Loop_T.\nProof.\n  eapply TerminatesIn_monotone.\n  { unfold JumpTarget_Loop. TM_Correct.\n    - apply JumpTarget_Step_Realise.\n    - apply JumpTarget_Step_Terminates. }\n  {\n    apply WhileCoInduction. intros tin steps. intros (P&Q&k&HEncP&HEncQ&HEncK&HRight3&HRight4&Hk).\n    exists (JumpTarget_Step_steps P Q k). repeat split. hnf; cbn; eauto 10.\n    intros ymid tmid HStep. cbn in HStep. modpon HStep. destruct ymid as [ [ | ] | ].\n    { (* [Some true], i.e. [P = retT :: P'] and [k = 0] *)\n      destruct P as [ | [ | | | ] ]; auto. destruct k; auto.\n    }\n    { (* [Some false], i.e. [P = nil] *)\n      destruct P as [ | [ | | | ] ]; auto.\n    }\n    { (* recursion cases *)\n      destruct P as [ | t P ]; auto.\n      destruct t; modpon HStep.\n      - (* t = varT n *)\n        exists (JumpTarget_Loop_steps P (Q++[varT n]) k). split.\n        + hnf. do 3 eexists; repeat split; eauto.\n        + assumption.\n      - (* t = appT *)\n        exists (JumpTarget_Loop_steps P (Q++[appT]) k). split.\n        + hnf. do 3 eexists; repeat split; eauto.\n        + assumption.\n      - (* t = lamT *)\n        exists (JumpTarget_Loop_steps P (Q++[lamT]) (S k)). split.\n        + hnf. do 3 eexists; repeat split; eauto.\n        + assumption.\n      - (* t = retT, k = S k' *)\n        destruct k as [ | k']; auto; modpon HStep.\n        exists (JumpTarget_Loop_steps P (Q++[retT]) k'). split.\n        + hnf. do 3 eexists; repeat split; eauto.\n        + assumption.\n    }\n  }\nQed.\n\n\nDefinition JumpTarget : pTM sigPro^+ bool 5 :=\n  Constr_nil _ @ [|Fin1|];;\n  Constr_O ⇑ _ @ [|Fin2|];;\n  JumpTarget_Loop.\n\n\nDefinition JumpTarget_Rel : pRel sigPro^+ bool 5 :=\n  fun tin '(yout, tout) =>\n    forall (P : Pro),\n      tin[@Fin0] ≃ P ->\n      isRight tin[@Fin1] ->\n      (forall i : Fin.t 3, isRight tin[@FinR 2 i : Fin.t 5]) ->\n      match yout with\n      | true =>\n        exists (P' Q' : Pro),\n        jumpTarget 0 nil P = Some (Q', P') /\\\n        tout[@Fin0] ≃ P' /\\\n        tout[@Fin1] ≃ Q' /\\\n        (forall i : Fin.t 3, isRight tout[@FinR 2 i : Fin.t 5])\n      | false =>\n        jumpTarget 0 nil P = None\n      end.\n\n\nLemma JumpTarget_Realise : JumpTarget ⊨ JumpTarget_Rel.\nProof.\n  eapply Realise_monotone.\n  { unfold JumpTarget. TM_Correct.\n    - apply JumpTarget_Loop_Realise.\n  }\n  {\n    intros tin (yout, tout) H. cbn. intros P HEncP HOut HInt.\n    TMSimp ( unfold sigPro, sigCom in * ). rename H into HWriteNil, H0 into HWriteO, H1 into HLoop.\n    modpon HWriteNil. modpon HWriteO. modpon HLoop.\n    destruct yout.\n    - destruct HLoop as (P'&Q'&HLoop); modpon HLoop. do 2 eexists; repeat split; eauto.\n      intros i; destruct_fin i; TMSimp_goal; auto.\n    - eauto.\n  }\nQed.\n\n\nDefinition JumpTarget_steps (P : Pro) :=\n  3 + Constr_nil_steps + Constr_O_steps + JumpTarget_Loop_steps P nil 0.\n\n\nDefinition JumpTarget_T : tRel sigPro^+ 5 :=\n  fun tin k =>\n    exists (P : Pro),\n      tin[@Fin0] ≃ P /\\\n      isRight tin[@Fin1] /\\\n      (forall i : Fin.t 3, isRight tin[@Fin.R 2 i]) /\\\n      JumpTarget_steps P <= k.\n\n\nLemma JumpTarget_Terminates : projT1 JumpTarget ↓ JumpTarget_T.\nProof.\n  eapply TerminatesIn_monotone.\n  { unfold JumpTarget. TM_Correct.\n    - apply JumpTarget_Loop_Terminates.\n  }\n  {\n    intros tin k (P&HEncP&Hout&HInt&Hk). unfold JumpTarget_steps in Hk.\n    exists (Constr_nil_steps), (1 + Constr_O_steps + 1 + JumpTarget_Loop_steps P nil 0).\n    cbn; repeat split; try omega.\n    intros tmid () (HWrite&HWriteInj); TMSimp. modpon HWrite.\n    exists (Constr_O_steps), (1 + JumpTarget_Loop_steps P nil 0).\n    cbn; repeat split; try omega.\n    cbn in *. unfold sigPro in *. intros tmid1 () (HWrite'&HWriteInj'); TMSimp. modpon HWrite'.\n    hnf. do 3 eexists; repeat split; cbn in *; unfold sigPro in *; cbn in *; TMSimp_goal; eauto.\n  }\nQed.\n", "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/LM/JumpTargetTM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.29847092614800347}}
{"text": "From TLC Require Import LibLN.\nRequire Import DeclDef DeclInfra DeclProp.\nRequire Import Translation.\nRequire Import PBCDef PBCInfra PBCProp.\nRequire Import DeclTyping DeclSub DeclEnvSub.\nRequire Import OLDef.\n\n(** * Conservative Extension *)\n\nHint Constructors dtyping otyping.\nHint Resolve denv_static_dokt otyping_regular.\n\nLemma conservative_extension: forall E e T,\n    denv_static E ->\n    dterm_static e ->\n    dtyp_static T ->\n    otyping E e T ->\n    exists A, dtyping E e A /\\ dsub E A T.\nProof.\n  introv Hen Htm Htyp.\n\n  introv Ht.\n  inductions Ht; autos ~;\n     try(solve[exists~ T; splits~]).\n\n  exists ~ T. splits~. apply~ dsub_refl.\n  apply* dwft_from_env_has_typ.\n\n  exists ~ (dtyp_nat).\n\n  pick_fresh y.\n  forwards ~ : H1 y.\n  constructor~. inversions~ Htyp.\n  forwards ~ : H0 y.\n  lets ~ [? [? ?]]: otyping_regular H2.\n  apply denv_static_dokt in H3.\n  apply* dokt_push_typ_inv.\n  forwards ~ : H0 y.\n  lets ~ [? [? ?]]: otyping_regular H2.\n  forwards ~ : H0 y.\n  lets ~ [? [? [? ?]]]: otyping_regular H2.\n  destruct H2 as (C & [? ?]).\n  apply dtyping_dtyping' in H2.\n  assert (dtyping' E (dtrm_absann A e) (dtyp_arrow A C)).\n  apply dtyping'_absann with y; auto.\n  lets [_ [? _]]: dsub_regular H3.\n  assert (dwft E C).\n  apply_empty~ dwft_strengthen_typ.\n  assert (y \\notin dfv_tt C).\n  apply (dwft_notin_env H6); auto.\n  auto.\n  lets ~ : dtyping'_dtyping H4.\n  exists ~ (dtyp_arrow A C). splits~. constructor~.\n  apply* dsub_refl.\n  apply_empty* dsub_strengthen_typ.\n\n  pick_fresh y.\n  forwards ~ : H1 y.\n  constructor~. inversions~ Htyp.\n  forwards ~ : H0 y.\n  lets ~ [? [? ?]]: otyping_regular H2.\n  apply denv_static_dokt in H3.\n  apply* dokt_push_typ_inv.\n  forwards ~ : H0 y.\n  lets ~ [? [? ?]]: otyping_regular H2.\n  forwards ~ : H0 y.\n  lets ~ [? [? [? ?]]]: otyping_regular H2.\n  destruct H2 as (C & [? ?]).\n  apply dtyping_dtyping' in H2.\n  assert (dtyping' E (dtrm_abs e) (dtyp_arrow A C)).\n  apply dtyping'_abs with y; auto.\n  lets [_ [? _]]: dsub_regular H3.\n  assert (dwft E C).\n  apply_empty~ dwft_strengthen_typ.\n  assert (y \\notin dfv_tt C).\n  apply (dwft_notin_env H6); auto.\n  auto.\n  lets ~ : dtyping'_dtyping H4.\n  exists ~ (dtyp_arrow A C). splits~. constructor~.\n  apply* dsub_refl.\n  apply_empty* dsub_strengthen_typ.\n\n  forwards ~ (B1 & [? ?]) : IHHt1.\n    lets~ [? [? [? ?]]] : otyping_regular Ht1.\n    lets~ [? [? [? ?]]] : otyping_regular Ht1.\n  forwards ~ (B2 & [? ?]) : IHHt2.\n    lets~ [? [? [? ?]]] : otyping_regular Ht2.\n    lets~ [? [? [? ?]]] : otyping_regular Ht2.\n  forwards ~ (C1 & C2 & [? ?]): dsub_match_arrow H0.\n  inversions H4.\n  exists ~ C2. splits~.\n  apply* dtyping_app.\n  apply dsub_consub.\n  apply dsub_trans with A1; auto.\n\n  forwards ~ (A0 & [? ?]) : IHHt.\n  lets~ [? [? [? ?]]] : otyping_regular Ht.\n  exists ~ A0. splits~.\n  apply dsub_trans with A; auto.\n\n  inversions Htyp.\n  pick_fresh y.\n  forwards ~ : H0 y.\n  destruct H1 as (C & [? ?]).\n  apply dtyping_dtyping' in H1.\n  assert (dtyping' E e (dtyp_all (dclose_tt y C))).\n  apply dtyping'_gen with y; auto.\n  assert (y \\notin dfv_tt (dclose_tt y C)).\n    apply dclose_tt_fresh.\n  auto.\n  rewrite~ <- dclose_tt_open_var.\n  lets~ [_ [? _]]: dsub_regular H3.\n  exists ~ (dtyp_all (dclose_tt y C)).\n  splits~.\n  apply* dtyping'_dtyping.\n  apply dsub'_dsub.\n  apply dsub'_allR with y; auto.\n  assert (y \\notin dfv_tt (dtyp_all (dclose_tt y C))).\n  simpls. apply dclose_tt_fresh.\n  auto.\n  apply dsub'_allL with (dtyp_fvar y); auto.\n  rewrite~ <- dclose_tt_open_var.\n  apply~ dsub_dsub'.\n  lets~ [? [? _]]: dsub_regular H3.\n\n  inversions Htm.\n  apply otyping_regular in Ht. destructs Ht.\n  forwards ~ : IHHt. destruct H7 as (A0 & [I1 I2]).\n  pick_fresh y.\n  forwards ~ (C & [? ?]) : H0 y. clear H0 IHHt.\n  assert (I3 : dsub (E & y ~: A) A0 A).\n    apply~ dsub_push.\n  lets ~ (T & [? ?]) : dtyping_bind_strengthen H7 I3.\n  exists T. splits~.\n  apply dtyping'_dtyping.\n  apply dtyping'_let with y A0; auto.\n  apply~ dtyping_dtyping'.\n  apply~ dtyping_dtyping'.\n  apply dsub_strengthen_typ_push in H9.\n  apply dsub_strengthen_typ_push in H8.\n  lets~ : dsub_trans H9 H8.\nQed.\n\nLemma conserv_extension_b: forall E e T,\n    denv_static E ->\n    dterm_static e ->\n    dtyp_static T ->\n    dtyping E e T ->\n    otyping E e T.\nProof.\n  introv Hen Htm Htyp.\n\n  introv Ht.\n  inductions Ht; autos ~.\n\n  inversions Htyp.\n  inversions Htm.\n  apply_fresh otyping_absann as x; auto.\n  apply~ H1.\n  apply~ denv_static_typ.\n  forwards ~ : H0 x.\n  lets ~ [? [_ _]]: dtyping_regular H2.\n  apply dokt_push_typ_inv in H3. auto.\n\n  inversions~ Htm.\n  forwards ~ : IHHt1.\n  apply* dtyping_static_preserve.\n  forwards ~ : IHHt2.\n  apply* dtyping_static_preserve.\n  apply* otyping_app.\n  apply otyping_sub with A; auto.\n  apply dsub_trans with (dtyp_arrow A1 A2); auto.\n  apply~ dmatch_static_sub.\n  apply* dtyping_static_preserve.\n  constructor~.\n  apply~ dconsub_static_sub.\n  apply* dtyping_static_preserve.\n  lets ~ [? ?] : dmatch_static_preserve H.\n  apply* dtyping_static_preserve.\n  apply~ dsub_refl.\n  lets~ [? ?] : dmatch_regular H.\n\n  inversions Htyp.\n  inversions Htm.\n  apply_fresh otyping_abs as x; auto.\n  apply~ H1.\n  constructor~.\n  forwards ~ : H0 x.\n  lets ~ [? [_ _]]: dtyping_regular H2.\n  apply dokt_push_typ_inv in H6. auto.\n\n  inversions Htyp.\n  apply_fresh otyping_gen as x; auto.\n\n  inversions Htm.\n  apply_fresh otyping_let as x; auto.\n  apply~ IHHt.\n  apply* dtyping_static_preserve.\n  apply~ H0.\n  constructor~.\n  apply* dtyping_static_preserve.\nQed.\n\n(** * Monotonicity w.r.t. precision *)\n\nLemma monotonicity_precision': forall E F e s A,\n    dtyping E e A ->\n    denv_less_precise F E ->\n    dterm_less_precise s e ->\n    exists B, dtyping' F s B /\\ dtyp_less_precise B A.\nProof.\n  introv ty. gen F s.\n  inductions ty; introv less_env less_tm.\n\n  (* var *)\n  inversions less_tm.\n  forwards ~ (B & [? ?]) : denv_less_precise_binds H0 less_env.\n  exists B. splits~.\n  constructor~.\n  apply* denv_less_precise_dokt_l.\n\n  (* nat *)\n  inversions less_tm.\n  exists ~ dtyp_nat. splits~. constructor~. apply* denv_less_precise_dokt_l.\n\n  (* absann *)\n  inversions~ less_tm.\n  pick_fresh y.\n  assert (I1: denv_less_precise (F & y ~: A1) (E & y ~: A)). constructor~.\n    apply dwft_denv_less_precise with E; auto.\n    apply dwft_dtyp_less_precise with A; auto.\n    forwards ~ : H0 y.\n    lets ~ [? _] : dtyping_regular H2.\n    apply* dokt_push_typ_inv.\n    forwards ~ : H0 y.\n    lets ~ [? _] : dtyping_regular H2.\n    apply* dokt_push_typ_inv.\n  assert (I2: dterm_less_precise (e1 dopen_ee_var y) (e dopen_ee_var y)). auto.\n  forwards ~ (C & [? ?]) : H1 I1 I2.\n  exists (dtyp_arrow A1 C). split~.\n  apply dtyping'_absann with y; auto.\n  apply dwft_dtyp_less_precise with A; auto.\n\n  (* app *)\n  inversions less_tm.\n  forwards ~ (B & [? ?]): IHty1 less_env H4. clear IHty1.\n  forwards ~ (C & [? ?]): IHty2 less_env H5. clear IHty2.\n  forwards ~ (B1 & B2 & [? [? ?]]) : dmatch_less_precise_input H H2.\n  exists ~ B2. splits~.\n  apply dtyping'_app with (A:= B) (A1:= B1) (A3:=C); auto.\n  lets ~ : dmatch_denv_less_precise H7 less_env.\n  lets ~ : dconsub_dtyp_less_precise H0 H6 H8.\n  lets ~ : dconsub_denv_less_precise H10 less_env.\n\n  (* abs *)\n  inversions~ less_tm.\n  pick_fresh y.\n  assert (I1: denv_less_precise (F & y ~: A) (E & y ~: A)). constructor~.\n    apply dtyp_less_precise_refl.\n    apply~ dtyp_mono_dtype.\n    apply dwft_denv_less_precise with E; auto.\n    forwards ~ : H0 y.\n    lets ~ [? _] : dtyping_regular H2.\n    apply* dokt_push_typ_inv.\n    forwards ~ : H0 y.\n    lets ~ [? _] : dtyping_regular H2.\n    apply* dokt_push_typ_inv.\n  assert (I2: dterm_less_precise (e1 dopen_ee_var y) (e dopen_ee_var y)). auto.\n  forwards ~ (C & [? ?]) : H1 I1 I2.\n  exists (dtyp_arrow A C). split~.\n  apply dtyping'_abs with y; auto.\n  assert (dwft F C).\n    lets : dtyping'_dtyping H2.\n    lets [_ [_ ?]] : dtyping_regular H5.\n    apply_empty* dwft_strengthen_typ.\n  assert (y \\notin dfv_tt C).\n    apply (dwft_notin_env H5); auto.\n  auto.\n  constructor~.\n    apply dtyp_less_precise_refl.\n    apply~ dtyp_mono_dtype.\n\n  (* gen *)\n  pick_fresh y.\n  assert (I1: denv_less_precise (F & y ~tvar ) (E & y ~tvar)). constructor~.\n  forwards ~ (C & [? ?]) : H0 I1 less_tm.\n  exists (dtyp_all (dclose_tt y C)). split~.\n  apply dtyping'_gen with y; auto.\n  assert (y \\notin dfv_tt (dclose_tt y C)).\n    apply dclose_tt_fresh; auto.\n  auto.\n  rewrite~ <- dclose_tt_open_var.\n    lets : dtyping'_dtyping H1.\n    lets [_ [_ ?]] : dtyping_regular H4.\n    auto.\n    apply dtyp_less_precise'_precise.\n    apply dtyp_less_precise'_all with y.\n      assert (y \\notin dfv_tt (dclose_tt y C)).\n        apply dclose_tt_fresh; auto.\n      auto.\n  rewrite~ <- dclose_tt_open_var.\n  apply~ dtyp_less_precise_precise'.\n    lets : dtyping'_dtyping H1.\n    lets [_ [_ ?]] : dtyping_regular H3.\n    auto.\n\n  (* let *)\n  inversions~ less_tm.\n  pick_fresh y.\n  forwards ~ (D & [I1 I2]) : IHty less_env H4.\n  assert (I3: denv_less_precise (F & y ~: D) (E & y ~: A)) by constructor~.\n  assert (I4: dterm_less_precise (e4 dopen_ee_var y) (e2 dopen_ee_var y))\n         by auto.\n  forwards ~ (C & [? ?]) : H0 I3 I4.\n  clear H0 IHty.\n  exists C. split~.\n  apply dtyping'_let with y D; auto.\nQed.\n\nLemma monotonicity_precision: forall E F e s A,\n    dtyping E e A ->\n    denv_less_precise F E ->\n    dterm_less_precise s e ->\n    exists B, dtyping F s B /\\ dtyp_less_precise B A.\nProof.\n  intros.\n  forwards ~ (B & [? ?]): monotonicity_precision' H H0 H1.\n  exists~ B. splits~.\n  apply* dtyping'_dtyping.\nQed.\n\n(** * Monotonicity of cast insertion *)\n\nLemma monotonicity_cast_insertion': forall E F e1 e2 s1 A,\n    d2ptyping E e1 A s1 ->\n    denv_less_precise F E ->\n    dterm_less_precise e2 e1 ->\n    exists s2 B, d2ptyping' F e2 B s2 /\\\n    dtyp_less_precise' B A /\\\n    pterm_less_precise s2 s1.\nProof.\n  introv ty1. gen F e2.\n  inductions ty1; introv less_env less_tm.\n\n  (* var *)\n  forwards ~ (C & [? ?]) : denv_less_precise_binds H0 less_env.\n  inversions less_tm.\n  exists (ptrm_fvar x) C. splits~.\n  constructor~.\n  lets~ : denv_less_precise_dokt_l less_env.\n  apply* dtyp_less_precise_precise'.\n  apply* pterm_less_precise_var.\n  lets~ : denv_less_precise_dokt_l less_env.\n\n  (* nat *)\n  inversions less_tm.\n  exists (ptrm_nat i) dtyp_nat. splits~.\n  constructor~.\n\n  (* absann *)\n  inversions~ less_tm.\n  pick_fresh y.\n  forwards~ : H6 y. clear H6.\n  forwards~ (s2 & B0 & [? [? ?]]): H1 y (F & y ~: A1) H2.\n  constructor~.\n  apply dwft_denv_less_precise with E; auto.\n  apply dwft_dtyp_less_precise with A; auto.\n  forwards~ : H0 y.\n  lets~ [? [? ?]]: d2ptyping_regular H3.\n  apply* dokt_push_typ_inv.\n  forwards~ : H0 y.\n  lets~ [? [? ?]]: d2ptyping_regular H3.\n  apply* dokt_push_typ_inv.\n  exists ~ (ptrm_absann A1 (pclose_ee y s2)) (dtyp_arrow A1 B0).\n  splits~.\n  apply d2ptyping'_absann with y; auto.\n  apply dwft_dtyp_less_precise with A; auto.\n  assert (y \\notin pfv_ee (pclose_ee y s2)).\n    apply pclose_ee_fresh.\n  auto.\n  rewrite~ <- pclose_ee_open.\n  lets ~ : d2ptyping'_d2ptyping H3.\n  lets ~ : d2ptyping_term H7.\n  constructor~.\n  apply~ dtyp_less_precise_precise'.\n  apply pterm_less_precise_absann with y; auto.\n  assert (y \\notin pfv_ee (pclose_ee y s2)).\n    apply pclose_ee_fresh.\n  auto.\n  rewrite~ <- pclose_ee_open.\n  lets ~ : d2ptyping'_d2ptyping H3.\n  lets ~ : d2ptyping_term H7.\n\n  (* app *)\n  inversions less_tm.\n  forwards ~ (s3 & C1 & [? [? ?]]) : IHty1_1 less_env H4.\n  forwards ~ (s4 & C2 & [? [? ?]]) : IHty1_2 less_env H5.\n  clear IHty1_1 IHty1_2.\n  lets : dtyp_less_precise'_precise H2.\n  forwards ~ (D1 & D2 & [? [? ?]]) : dmatch_less_precise_input H H9.\n  lets : dmatch_denv_less_precise H10 less_env. clear H10.\n  exists~ (ptrm_app (ptrm_cast C1 (dtyp_arrow D1 D2) s3)\n               (ptrm_cast C2 D1 s4))\n   D2.\n  splits~.\n  apply~ d2ptyping'_app.\n  lets I1 : dtyp_less_precise'_precise H7.\n  lets~ : dconsub_dtyp_less_precise H0 I1 H11.\n  lets~ : dconsub_denv_less_precise H10 less_env.\n  apply* dtyp_less_precise_precise'.\n  apply~ pterm_less_precise_app.\n  apply~ pterm_less_precise_cast.\n  apply~ pterm_less_precise_cast.\n  apply* dtyp_less_precise'_precise.\n\n  (* abs *)\n  inversions~ less_tm.\n  pick_fresh y.\n  forwards~ : H4 y. clear H4.\n  forwards~ (s2 & B0 & [? [? ?]]): H1 y (F & y ~: A) H2.\n  constructor~.\n  apply~ dtyp_less_precise_refl.\n    forwards~ : H0 y.\n    lets~ [? [? ?]]: d2ptyping_regular H3.\n    apply dokt_push_typ_inv in H4. auto.\n  apply dwft_denv_less_precise with E; auto.\n  forwards~ : H0 y.\n  lets~ [? [? ?]]: d2ptyping_regular H3.\n  apply* dokt_push_typ_inv.\n  forwards~ : H0 y.\n  lets~ [? [? ?]]: d2ptyping_regular H3.\n  apply* dokt_push_typ_inv.\n  exists ~ (ptrm_absann A (pclose_ee y s2)) (dtyp_arrow A B0).\n  splits~.\n  apply d2ptyping'_abs with y; auto.\n  assert (y \\notin pfv_ee (pclose_ee y s2)).\n    apply pclose_ee_fresh.\n  auto.\n  rewrite~ <- pclose_ee_open.\n  lets ~ : d2ptyping'_d2ptyping H3.\n  lets ~ : d2ptyping_term H6.\n  constructor~.\n  apply~ dtyp_less_precise'_refl.\n    forwards~ : H0 y.\n    lets~ [? [? ?]]: d2ptyping_regular H6.\n    apply dokt_push_typ_inv in H7. auto.\n  apply pterm_less_precise_absann with y; auto.\n  assert (y \\notin pfv_ee (pclose_ee y s2)).\n    apply pclose_ee_fresh.\n  auto.\n  apply* dtyp_less_precise'_precise.\n  rewrite~ <- pclose_ee_open.\n  lets ~ : d2ptyping'_d2ptyping H3.\n  lets ~ : d2ptyping_term H6.\n\n  (* all *)\n  pick_fresh y.\n  forwards~ : H y. clear H.\n  forwards~ (s2 & B0 & [? [? ?]]): H0 y (F & y ~tvar) less_tm.\n  constructor~.\n  exists ~ (ptrm_tabs (pclose_te y s2)) (dtyp_all (dclose_tt y B0)).\n  splits~.\n  apply d2ptyping'_gen with y; auto.\n  assert (y \\notin dfv_tt (dclose_tt y B0)).\n    apply dclose_tt_fresh.\n  assert (y \\notin pfv_te (pclose_te y s2)).\n    apply pclose_te_fresh.\n  auto.\n  rewrite~ <- dclose_tt_open_var.\n  rewrite~ <- pclose_te_open.\n  lets ~ : d2ptyping'_d2ptyping H.\n  lets ~ : d2ptyping_term H4.\n  lets ~ : d2ptyping'_d2ptyping H.\n  lets ~ [_ [_ ?]]: d2ptyping_regular H4.\n  apply dtyp_less_precise'_all with y.\n    assert (y \\notin dfv_tt (dclose_tt y B0)).\n      apply dclose_tt_fresh.\n    auto.\n  rewrite~ <- dclose_tt_open_var.\n    lets ~ : d2ptyping'_d2ptyping H.\n    lets ~ [_ [_ ?]]: d2ptyping_regular H4.\n  apply pterm_less_precise_tabs with y.\n  assert (y \\notin pfv_te (pclose_te y s2)).\n    apply pclose_te_fresh.\n  auto.\n  rewrite~ <- pclose_te_open.\n  lets ~ : d2ptyping'_d2ptyping H.\n  lets ~ : d2ptyping_term H4.\n\n  (* let *)\n  inversions~ less_tm.\n  pick_fresh y.\n  forwards~ : H5 y. clear H5.\n  forwards ~ (s4 & C0 & [I1 [I2 I3]]) : IHty1 less_env H4.\n  forwards~ (s3 & B0 & [I4 [I5 I6]]): H0 y (F & y ~: C0) H1.\n  constructor~.\n  apply~ dtyp_less_precise'_precise.\n  clear IHty1 H0.\n  exists (ptrm_app (ptrm_absann C0 (pclose_ee y s3)) (s4)) B0.\n  splits~.\n  apply d2ptyping'_let with y; auto.\n  assert (y \\notin pfv_ee (pclose_ee y s3)).\n    apply pclose_ee_fresh.\n  auto.\n  rewrite~ <- pclose_ee_open.\n  lets ~ : d2ptyping'_regular I4. destructs~ H0.\n  apply~ pterm_less_precise_app.\n  apply pterm_less_precise_absann with y; auto.\n  assert (y \\notin pfv_ee (pclose_ee y s3)).\n    apply pclose_ee_fresh.\n  assert (y \\notin dfv_tt C0).\n    apply dwft_notin_env with F; auto.\n  auto.\n  apply~ dtyp_less_precise'_precise.\n  rewrite~ <- pclose_ee_open.\n  lets ~ : d2ptyping'_regular I4. destructs~ H0.\nQed.\n\nLemma monotonicity_cast_insertion: forall E F e1 e2 s1 A,\n    d2ptyping E e1 A s1 ->\n    denv_less_precise F E ->\n    dterm_less_precise e2 e1 ->\n    exists s2 B, d2ptyping F e2 B s2 /\\\n    dtyp_less_precise B A /\\\n    pterm_less_precise s2 s1.\nProof.\n  introv H1 H2 H3.\n  forwards ~ (s2 & B & [? [? ?]]): monotonicity_cast_insertion' H1 H2 H3.\n  exists ~ s2 B.\n  splits~.\n  apply* d2ptyping'_d2ptyping.\n  apply* dtyp_less_precise'_precise.\nQed.\n", "meta": {"author": "xnning", "repo": "Consistent-Subtyping-for-All", "sha": "1bf23ed3906f2e244d081c75be90f3a54899e375", "save_path": "github-repos/coq/xnning-Consistent-Subtyping-for-All", "path": "github-repos/coq/xnning-Consistent-Subtyping-for-All/Consistent-Subtyping-for-All-1bf23ed3906f2e244d081c75be90f3a54899e375/coq/decl-higher-rank/Criteria.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.29847092614800336}}
{"text": "(* This file is generated by Why3's Coq-realize 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 list.Append.\n\n(* This file is generated by Why3's Coq-realize 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 list.Append.\n\n(* Why3 goal *)\nLemma reverse_def : forall {a:Type} {a_WT:WhyType a}, forall (l:(list a)),\n  ((Lists.List.rev l) = match l with\n  | Init.Datatypes.nil => Init.Datatypes.nil\n  | (Init.Datatypes.cons x r) =>\n      (Init.Datatypes.app (Lists.List.rev r) (Init.Datatypes.cons x Init.Datatypes.nil))\n  end).\nProof.\nnow intros a a_WT [|x l].\nQed.\n\n(* Why3 goal *)\nLemma reverse_append : forall {a:Type} {a_WT:WhyType a}, forall (l1:(list a))\n  (l2:(list a)) (x:a),\n  ((Init.Datatypes.app (Lists.List.rev (Init.Datatypes.cons x l1)) l2) = (Init.Datatypes.app (Lists.List.rev l1) (Init.Datatypes.cons x l2))).\nProof.\nintros a a_WT l1 l2 x.\nsimpl.\nnow rewrite <- List.app_assoc.\nQed.\n\n(* Why3 goal *)\nLemma reverse_cons : forall {a:Type} {a_WT:WhyType a}, forall (l:(list a))\n  (x:a),\n  ((Lists.List.rev (Init.Datatypes.cons x l)) = (Init.Datatypes.app (Lists.List.rev l) (Init.Datatypes.cons x Init.Datatypes.nil))).\nintros a a_WT l x.\nsimpl.\nauto.\nQed.\n\n(* Why3 goal *)\nLemma cons_reverse : forall {a:Type} {a_WT:WhyType a}, forall (l:(list a))\n  (x:a),\n  ((Init.Datatypes.cons x (Lists.List.rev l)) = (Lists.List.rev (Init.Datatypes.app l (Init.Datatypes.cons x Init.Datatypes.nil)))).\nintros a a_WT l x.\nnow rewrite List.rev_unit.\nQed.\n\n(* Why3 goal *)\nLemma reverse_reverse : forall {a:Type} {a_WT:WhyType a},\n  forall (l:(list a)), ((Lists.List.rev (Lists.List.rev l)) = l).\nProof.\nintros a a_WT l.\napply List.rev_involutive.\nQed.\n\n(* Why3 goal *)\nLemma reverse_mem : forall {a:Type} {a_WT:WhyType a}, forall (l:(list a))\n  (x:a), (list.Mem.mem x l) <-> (list.Mem.mem x (Lists.List.rev l)).\nintros a a_WT l x.\ninduction l; simpl; intuition.\nrewrite Append.mem_append.\nright; simpl; now intuition.\nrewrite Append.mem_append.\nnow auto.\nassert (Mem.mem x (List.rev l) \\/ Mem.mem x (a0 :: nil))%list.\nrewrite <- Append.mem_append; assumption.\nintuition; simpl in *.\nintuition.\nQed.\n\n(* Why3 goal *)\nLemma Reverse_length : forall {a:Type} {a_WT:WhyType a}, forall (l:(list a)),\n  ((list.Length.length (Lists.List.rev l)) = (list.Length.length l)).\nProof.\nintros a a_WT l.\nrewrite 2!Length.length_std.\nnow rewrite List.rev_length.\nQed.\n\n", "meta": {"author": "schrodibear", "repo": "why3", "sha": "9f8eb767380987a28e43b81729ae1d682363bb49", "save_path": "github-repos/coq/schrodibear-why3", "path": "github-repos/coq/schrodibear-why3/why3-9f8eb767380987a28e43b81729ae1d682363bb49/lib/coq/list/Reverse.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.29847092614800336}}
{"text": "Module CoStack.\n\tCoInductive stack (t : Type) :=\n\t\t  Empty \n\t\t| Push (top : t) (pop : stack t).\n\n\n\tDefinition isEmpty {t: Type} (__input : stack t) : Prop :=\n\t\tmatch __input with\n\t\t\t  Empty  => True\n\t\t\t| _ => False\n\t\tend.\n\n\n\tDefinition isPush {t: Type} (__input : stack t) : Prop :=\n\t\tmatch __input with\n\t\t\t  Push _ _ => True\n\t\t\t| _ => False\n\t\tend.\n\n\n\t\n\n\n\tDefinition getPushTop {t: Type} (__input : stack t) : isPush __input -> t :=\n\t\tmatch __input with\n\t\t\t  Push top _ => fun __precondition => top\n\t\t\t| _ => fun __precondition => match __precondition with end\n\t\tend.\n\n\n\tDefinition getPushPop {t: Type} (__input : stack t) : isPush __input -> stack t :=\n\t\tmatch __input with\n\t\t\t  Push _ pop => fun __precondition => pop\n\t\t\t| _ => fun __precondition => match __precondition with end\n\t\tend.\nEnd CoStack.\n\n\n\n\n\nModule Stack.\n\tParameter Label : Type.\n\n\tCoInductive stack (t : Type) :=\n\t\t  Empty \n\t\t| Push (top : t) (pop : stack t)\n\t\t| Labeled (__tag : Label) (__data : stack t)\n\t\t| Reference (__tag : Label).\n\n\n\tDefinition isEmpty {t: Type} (__input : stack t) : Prop :=\n\t\tmatch __input with\n\t\t\t  Empty  => True\n\t\t\t| _ => False\n\t\tend.\n\n\n\tDefinition isPush {t: Type} (__input : stack t) : Prop :=\n\t\tmatch __input with\n\t\t\t  Push _ _ => True\n\t\t\t| _ => False\n\t\tend.\n\n\n\tDefinition isLabeled {t: Type} (__input : stack t) : Prop :=\n\t\tmatch __input with\n\t\t\t  Labeled _ _ => True\n\t\t\t| _ => False\n\t\tend.\n\n\n\tDefinition isReference {t: Type} (__input : stack t) : Prop :=\n\t\tmatch __input with\n\t\t\t  Reference _ => True\n\t\t\t| _ => False\n\t\tend.\n\n\n\t\n\n\n\tDefinition getPushTop {t: Type} (__input : stack t) : isPush __input -> t :=\n\t\tmatch __input with\n\t\t\t  Push top _ => fun __precondition => top\n\t\t\t| _ => fun __precondition => match __precondition with end\n\t\tend.\n\n\n\tDefinition getPushPop {t: Type} (__input : stack t) : isPush __input -> stack t :=\n\t\tmatch __input with\n\t\t\t  Push _ pop => fun __precondition => pop\n\t\t\t| _ => fun __precondition => match __precondition with end\n\t\tend.\n\n\n\tDefinition getLabeled__tag {t: Type} (__input : stack t) : isLabeled __input -> Label :=\n\t\tmatch __input with\n\t\t\t  Labeled __tag _ => fun __precondition => __tag\n\t\t\t| _ => fun __precondition => match __precondition with end\n\t\tend.\n\n\n\tDefinition getLabeled__data {t: Type} (__input : stack t) : isLabeled __input -> stack t :=\n\t\tmatch __input with\n\t\t\t  Labeled _ __data => fun __precondition => __data\n\t\t\t| _ => fun __precondition => match __precondition with end\n\t\tend.\n\n\n\tDefinition getReference__tag {t: Type} (__input : stack t) : isReference __input -> Label :=\n\t\tmatch __input with\n\t\t\t  Reference __tag => fun __precondition => __tag\n\t\t\t| _ => fun __precondition => match __precondition with end\n\t\tend.\n\n\n\tInductive subterm {t: Type} (__root : stack t) : stack t -> Type :=\n\t\t  SubRoot : subterm __root __root\n\t\t| SubLabeled : forall __tag __data, subterm __root (Labeled t __tag __data) -> subterm __root __data\n\t\t| SubPushPop : forall top pop, subterm __root (Push t top pop) -> subterm __root pop.\nEnd Stack.", "meta": {"author": "joasyannick", "repo": "in-school", "sha": "ca07ac4ca65509b60e8b7772b9e2b55d716016ab", "save_path": "github-repos/coq/joasyannick-in-school", "path": "github-repos/coq/joasyannick-in-school/in-school-ca07ac4ca65509b60e8b7772b9e2b55d716016ab/inductive-type-generator/test/stack.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.29847092614800336}}
{"text": "From Undecidability.L Require Import Tactics.LTactics.\nFrom Undecidability.L.Datatypes Require Import Lists LVector.\nFrom Complexity.Libs Require Import PSLCompat.\nFrom Complexity.Complexity Require Import NP Definitions Monotonic.\nFrom Undecidability.TM Require Import TM_facts.\nFrom Complexity.L.AbstractMachines Require Import FlatPro.Computable.LPro.\nFrom Undecidability.L.AbstractMachines Require Import FlatPro.Programs.\nFrom Complexity.NP Require Import LMGenNP TMGenNP_fixed_mTM M_LM2TM.\n\nFrom Undecidability.TM.L Require M_LHeapInterpreter.\n\nSet Default Proof Using \"Type\".\n\n(* Check LMtoTM.M. *)\n\nFrom Undecidability Require Import LSum.\nFrom Complexity Require Import L.TM.CompCode.\n\nFrom Undecidability Require Import Alphabets.\n\nImport ProgrammingTools.\n\nModule TrueOrDiverge.\n  Import TM.TM ProgrammingTools CaseList CaseBool Code.Decode Code.DecodeList.\n\n  Section sec.\n    Variable (n:nat) (sig : finType) (M' : pTM sig bool n).\n\n    Definition M := If M' Nop Diverge.\n\n    Lemma Realise R' (H' : M' ⊨ R'):\n      M ⊨ (fun tin out => R' tin (true,snd out)).\n    Proof.\n      eapply Realise_monotone.\n      { eapply If_Realise. eassumption. now TM_Correct. now apply Diverge_Realise. }\n      hnf. intros x [[] y]. intros [H|H].\n      -cbn in H. destruct H as (?&?&<-). easy.\n      -exfalso. cbn in H. firstorder.\n    Qed.\n\n    Import TM.\n\n    Lemma Terminates R' (HR' : M' ⊨ R') T' (HT' : projT1 M' ↓ T'):\n      projT1 M ↓ (fun tin k => T' tin (k-1) /\\ 0 < k /\\ forall tout, ~ R' tin (false,tout)).\n    Proof.\n      eapply TerminatesIn_monotone.\n      { eapply If_TerminatesIn. 1,2:eassumption. now TM_Correct. now apply Canonical_TerminatesIn. }\n      intros tin [] (HTtin&Hfalse). easy.\n      do 2 eexists;repeat simple apply conj. eassumption.\n      2:{ intros ? ? ?. destruct b. reflexivity. now exfalso. }\n      nia.\n    Qed.\n  End sec.\nEnd TrueOrDiverge.\n\n\nArguments LMtoTM.M : clear implicits.\n\n\n(*move*)\nLemma initValue_sizeOfTape (sig sigX X : Type) (cX : codable sigX X) (I : Retract sigX sig) (x : X):\n  sizeOfTape (initValue cX I x) = size x + 2.\nProof.\n  cbn. autorewrite with list. cbn. now unfold size.\nQed.\n\n\nLemma initRight_sizeOfTape sig :\n  sizeOfTape (initRight sig) = 1.\nProof.\n  cbn. nia.\nQed.\n\nModule M.\n  Section M.\n    Arguments LMtoTM.M : clear implicits.\n    Definition sig := (finType_CS (M_LHeapInterpreter.sigStep + sigList bool)).\n\n    Definition sig__reg : encodable sig := LFinType.encodable_finType.\n\n    Definition Retr1 : Retract _ sig := (Retract_inl _ (Retract_id _)).\n    Definition Retr2 : Retract _ sig := (Retract_inr _ (Retract_id _)).\n\n    Let n := 11.\n    Definition M : pTM _ _ n := TrueOrDiverge.M (LMtoTM.M sig Retr1 Retr2).\n    Definition ts__start : Pro -> tapes (sig^+) (n-1) :=\n      (fun P => CodeTM.initValue _ (@LMtoTM.retr__pro _ Retr1) P ::: Vector.const (CodeTM.initRight _) (n-2)).\n\n    Definition Rel : pRel (sig ^+) unit 11 :=\n      fun tin _ =>\n        forall P t__cert, tin = t__cert:::ts__start P\n                   -> exists bs : list bool,\n            t__cert ≃(Retr2) bs /\\\n            (exists (sigma' : LM_heap_def.state) (k : nat), evaluatesIn LM_heap_def.step k (initLMGen P (compile (enc (rev bs)))) sigma').\n\n\n    Definition Realise :\n      M ⊨\n        (fun tin _ =>\n           forall P t__cert, tin = t__cert:::ts__start P\n                      -> exists bs : list bool,\n               t__cert ≃(Retr2) bs /\\\n               (exists (sigma' : LM_heap_def.state) (k : nat), evaluatesIn LM_heap_def.step k (initLMGen P (compile (enc (rev bs)))) sigma')).\n    Proof.\n      unfold M. eapply Realise_monotone.\n      1:now eapply TrueOrDiverge.Realise, LMtoTM.Realise.\n      intros ? out H P t__cert ->. hnf in H|-*. specialize (H P).\n      apply H.\n      -apply CodeTM.initValue_contains.\n      -intros ?. cbn - [Vector.const]. rewrite Vector.const_nth. now apply CodeTM.initRight_isVoid.\n    Qed.\n\n    Definition time := @f__UpToC _ _ (projT1 (@LMtoTM._Terminates sig Retr1 Retr2)).\n\n    Definition Terminates :\n      projT1 M ↓ (fun tin k => 0 < k /\\\n                            exists P k__LM t__cert (bs : list bool),\n                              tin = t__cert ::: ts__start P\n                              /\\ t__cert ≃(Retr2) bs\n                              /\\ (exists sigma' : LM_heap_def.state, evaluatesIn LM_heap_def.step k__LM (initLMGen P (compile (enc (rev bs)))) sigma')\n                              /\\ time (k__LM, sizeOfmTapes tin) <= k-1).\n    Proof.\n      unfold M. eapply TerminatesIn_monotone.\n      {eapply TrueOrDiverge.Terminates. now apply LMtoTM.Realise. apply LMtoTM.Terminates. }\n      intros tin k (HkPos&P&k__LM&t__cert&bs&->&Ht__cert&HLM&Htime). unfold LMtoTM.Ter.\n      split.\n      2:{ split. easy. unfold LMtoTM.Rel. intros _ H. eapply (H P).\n          -apply CodeTM.initValue_contains.\n          -intros ?. cbn - [Vector.const]. rewrite Vector.const_nth. now apply CodeTM.initRight_isVoid.\n          -eauto.\n      }\n      exists P,k__LM.\n      repeat simple apply conj.\n      -apply CodeTM.initValue_contains.\n      -intros ?. cbn - [Vector.const]. rewrite Vector.const_nth. now apply CodeTM.initRight_isVoid.\n      -right. exists bs;split. all:easy.\n      -eassumption.\n    Qed.\n  End M.\n\n    \n  Lemma sizeStart t__cert P:\n    sizeOfmTapes (t__cert ::: M.ts__start P)\n    = max (sizeOfTape t__cert) (size P + 2).\n  Proof.\n    unfold sizeOfmTapes. rewrite Vector.fold_left_right_assoc_eq. 2:nia. cbn - [Vector.const initValue initRight].\n    rewrite <- Vector.fold_left_right_assoc_eq.  2:nia.\n    set (tmp:= VectorDef.const _ _). change (VectorDef.fold_left _ _ _) with (sizeOfmTapes tmp).\n    rewrite initValue_sizeOfTape.\n    replace (sizeOfmTapes tmp) with 1. nia.\n    subst tmp. clear.\n    unfold sizeOfmTapes. rewrite Vector.fold_left_right_assoc_eq. 2:nia.\n    generalize 8 as x. induction x.\n    -reflexivity.\n    -cbn in *. now rewrite <- IHx.\n  Qed.\n    \n    \nEnd M.\n\n\nFrom Complexity Require Import PolyTimeComputable.\n\n(*REMOVE?*)\nImport GenericNary UpToCNary.\nFrom Coq Require Import CRelationClasses CMorphisms.\n\n(* TODO MOVE :tidy up *)\nLemma pTC_length X `{encodable X}: polyTimeComputable (@length X).\nProof.\n  evar (time:nat -> nat).\n  eexists time.\n  { eapply computableTime_timeLeq. 2:exact _.\n    solverec. rewrite size_list_enc_r. set (n:=L_facts.size _). [time]:refine (fun n => _). unfold time. reflexivity.\n  }\n  1,2:unfold time;now smpl_inO.\n  eexists (fun n => _). \n  {intros. rewrite !LNat.size_nat_enc, size_list_enc_r. set (n:= L_facts.size _). reflexivity. }\n    1,2:unfold time;now smpl_inO.\nQed.\n\nSmpl Add 1 simple apply pTC_length : polyTimeComputable.\n\n\nLemma pTC_Code_size X sig `{encodable X} `{encodable sig}  (cX : codable sig X):\n  polyTimeComputable cX -> polyTimeComputable (@Code.size sig X cX).\nProof.\n  intros. \n  unfold size. repeat smpl polyTimeComputable.\nQed.\nSmpl Add 5 simple eapply pTC_Code_size : polyTimeComputable.\n\n\nSection cons.\n\n  Lemma pTC_cons X Y `{regX:encodable X} `{regY:encodable Y} f (g : X -> list Y):\n    polyTimeComputable f -> polyTimeComputable g -> polyTimeComputable (fun (x:X) => f x :: g x).\n  Proof.\n    intros. specialize termT_cons with (X:=Y) as H.\n    eapply polyTimeComputable_composition2. 1,2:easy.\n    evar (c:nat). eexists (fun _ => c).\n    { extract. solverec. now unfold c. }\n    1,2:now smpl_inO.\n    eexists (fun n => n + 1). 2,3:now smpl_inO.\n    {intros. rewrite size_list_cons. rewrite !LProd.size_prod. unfold c__listsizeCons. nia. \n    }\n  Qed.\nEnd cons.\n\nSmpl Add 5 lazymatch goal with\n             |- polyTimeComputable (fun X => _ :: _) => apply pTC_cons\n           end: polyTimeComputable.\n\nSection Vcons.\n  Import Undecidability.Shared.Libs.PSL.Vectors.Vectors.\n  Import Vector.\n  Local Arguments VectorDef.to_list : simpl never.\n  Global Instance termT_cons n X {regX : encodable X} : computableTime' (fun x => @Vector.cons X x n) (fun a aT => (1,fun A AT => (4,tt))).\n  Proof. \n    computable_casted_result.\n    change (fun (x : X) (x0 : Vector.t X n) => VectorDef.to_list (x ::: x0)) with (fun (x : X) (x0 : Vector.t X n) => x :: Vector.to_list x0).\n    extract. solverec.\n  Qed.\n\n  Lemma pTC_Vector_cons X Y `{regX:encodable X} `{regY:encodable Y} n f (g : X -> Vector.t Y n):\n    polyTimeComputable f -> polyTimeComputable g -> polyTimeComputable (fun (x:X) => f x ::: g x).\n  Proof.\n    intros. specialize termT_cons with (n:=n) (X:=Y) as H.\n    set (cons := (fun (x :Y) => @Vector.cons _ x n)) in H.\n    change (polyTimeComputable (fun x : X => cons (f x) (g x))).\n    eapply polyTimeComputable_composition2. 1,2:easy.\n    fold cons in H.\n    evar (c:nat).\n    eexists (fun _ => c).\n    { extract. solverec. now unfold c. }\n    1,2:now smpl_inO.\n    eexists (fun n => n + 1). 2,3:now smpl_inO.\n    {intros. unfold cons. rewrite enc_vector_eq.\n     change (to_list (fst x ::: snd x)) with (fst x :: to_list (snd x)).\n     rewrite size_list_cons. rewrite !LProd.size_prod.  rewrite <- enc_vector_eq.\n     set (L_facts.size (enc (fst x))). set (L_facts.size (enc (snd x))). unfold c__listsizeCons. nia.\n    }\n  Qed.\nEnd Vcons.\nSmpl Add 5 lazymatch goal with\n             |- polyTimeComputable (fun X => _ ::: _) => apply pTC_Vector_cons\n           end: polyTimeComputable.\n\n\nLemma mono_map_time X `{encodable X} (f: nat -> nat) (xs: list X):\n  monotonic f\n  -> sumn (map (fun x => f (L_facts.size (enc x))) xs) <= length xs * f (L_facts.size (enc xs)).\nProof.\n  intros Hf. \n  induction xs. reflexivity.\n  cbn. rewrite size_list_cons,IHxs. hnf in Hf.\n  rewrite (Hf (L_facts.size (enc a)) (L_facts.size (enc a) + L_facts.size (enc xs) + 5)). 2:nia.\n  rewrite (Hf (L_facts.size (enc xs)) (L_facts.size (enc a) + L_facts.size (enc xs) + 5)). 2:nia. reflexivity.\nQed.\n\nLemma pTC_map X Y `{encodable X} `{encodable Y} (f:X -> Y):\n  polyTimeComputable f -> polyTimeComputable (map f).\nProof.\n  intros Hf.\n  evar (time:nat -> nat). exists time. set (map f). extract.\n  {solverec. rewrite (correct__leUpToC (mapTime_upTo _)).\n   rewrite mono_map_time. 2:now apply mono__polyTC. set (L_facts.size _) as n.\n   unshelve erewrite (_ : length x <= n). now apply size_list_enc_r.\n   [time]:intro. unfold time. reflexivity.\n  }\n  1,2:now unfold time;smpl_inO.\n  evar (size:nat -> nat). exists size. \n  {intros x. rewrite size_list,sumn_map_add,sumn_map_c,map_map,map_length.\n   rewrite sumn_map_le_pointwise.\n   2:{ intros ? _. apply (bounds__rSP Hf). }\n   rewrite mono_map_time. 2:eapply mono__rSP.\n   set (L_facts.size _) as n.\n   unshelve erewrite (_ : length x <= n). now apply size_list_enc_r.\n   [size]:intro. unfold size. reflexivity.\n  }\n  1,2:now unfold size;smpl_inO.\nQed.\n\n\nLemma pTC_concat X Y `{encodable X} `{encodable Y} (f:X -> list (list Y)):\n  polyTimeComputable f -> polyTimeComputable (fun x => concat (f x)).\nProof.\n  intros Hf.\n  evar (time:nat -> nat). exists time. extract.\n  {solverec. rewrite UpToC_le.\n   rewrite sumn_map_le_pointwise.\n   2:{ intros ? ?. apply size_list_enc_r. }\n   setoid_rewrite mono_map_time with (f:=fun x => x). 2:now hnf.\n   rewrite !size_list_enc_r.\n\n   rewrite ! (bounds__rSP Hf).\n   set (n:=L_facts.size _).\n   [time]:intro. unfold time. reflexivity.\n  }\n  1,2:now unfold time;smpl_inO.\n  evar (size:nat -> nat). exists size. \n  {intros x.\n   rewrite size_list, sumn_map_add,sumn_map_c.\n   rewrite concat_map,sumn_concat.\n   rewrite length_concat.\n   rewrite map_map.\n   rewrite sumn_le_bound with (c:= length (concat (f x)) * resSize__rSP Hf (L_facts.size (enc x))). \n   2:{ intros ? (?&<-&HIn)%in_map_iff. rewrite sumn_le_bound with (c:=L_facts.size (enc x0)).\n       2:{  intros ? (?&<-&?)%in_map_iff. now apply size_list_In. }\n       rewrite map_length,length_concat. rewrite <- bounds__rSP.\n       rewrite size_list_In. 2:eassumption.\n       apply Nat.mul_le_mono. 2:reflexivity.\n       eapply sumn_le_in. now apply in_map_iff.\n   }\n   rewrite length_concat,map_length.\n   unshelve erewrite (_ : (sumn (map (length (A:=Y)) (f x)) <= resSize__rSP Hf (L_facts.size (enc x)))).\n   { rewrite <- bounds__rSP,size_list.\n     rewrite <- sumn_map_le_pointwise with (f2:=(fun x0 : list Y => L_facts.size (enc x0) + 5)) (f1:= @length _).\n     2: now intros; rewrite <- size_list_enc_r. nia.\n   }\n    unshelve erewrite (_ : length (f x) <= resSize__rSP Hf (L_facts.size (enc x))).\n   { rewrite <- bounds__rSP,size_list. rewrite sumn_map_add,sumn_map_c. unfold c__listsizeNil, c__listsizeCons. nia.\n   }\n   set (L_facts.size _). [size]:intros n. unfold size. reflexivity.\n  }\n  1,2:unfold size;smpl_inO.\nQed.\n\nLemma pTC_app X Y `{encodable X} `{encodable Y} (f1 f2:X -> list Y):\n  polyTimeComputable f1 -> polyTimeComputable f2 -> polyTimeComputable (fun x => f1 x ++ f2 x).\nProof.\n  intros Hf1 Hf2.\n  eapply polyTimeComputable_composition2. 1,2:eauto.\n  evar (time : nat -> nat). exists time. extract.\n     {solverec.\n      unshelve erewrite (_: |a| <= L_facts.size (enc (a,b))).\n      { rewrite LProd.size_prod,size_list_enc_r;cbn. nia. }\n      set (L_facts.size _). [time]:intro. now unfold time.\n     }\n     1,2:now unfold time;smpl_inO.\n     { evar (size : nat -> nat). exists size.\n       {\n         intros [a b]. rewrite LProd.size_prod, !size_list,map_app,sumn_app,!sumn_map_add,!sumn_map_c.\n         cbn [fst snd].\n         [size]:exact (fun x => x + 4). unfold size. lia.\n       }\n       all:unfold size;smpl_inO.\n     }\nQed.\n  \n\nLemma pTC_initValue X  sig tau `{encodable X} `{encodable sig} `{encodable tau} (cX : codable sig X) (r:Retract sig tau) :\n  polyTimeComputable cX -> polyTimeComputable (Retr_f (Retract:=r)) ->  polyTimeComputable (initValue cX r).\nProof.\n  unfold initValue. intros cX_pTC r_pTC. \n  eapply polyTimeComputable_composition.\n  2:{ refine (_ : polyTimeComputable (fun x => (midtape [] (inl START)) x)).\n      exists (fun _ => 5). extract.\n      Unshelve. solverec. 1,2:now smpl_inO.\n      evar (size : nat -> nat). exists size. unfold enc at 1;cbn;intros x.\n      set (n0:=L_facts.size (enc x)). [size]:intros n0. repeat (unfold enc,size; cbn). reflexivity.\n      all:unfold size. all:smpl_inO.\n  }\n  eapply pTC_app.\n  2:now apply pTC_cnst.\n  eapply polyTimeComputable_composition.\n  2:{ eapply pTC_map. exists (fun _ => 4). extract. solverec.  1,2:now smpl_inO.\n      exists (fun x => x+4).\n      {intros. now setoid_rewrite size_sum. }\n      all:smpl_inO.\n  }\n  unfold Encode_map. cbn.\n  eapply polyTimeComputable_composition. eassumption.\n  eapply pTC_map. eassumption.\nQed.\nSmpl Add 5 unshelve simple eapply pTC_initValue : polyTimeComputable.\n\n\n\nImport M_LHeapInterpreter.\n\nFrom Complexity Require Import PolyTimeComputable.\n\nLemma pTC_Encode_Com : polyTimeComputable (Encode_Com).\nProof.\n  unfold Encode_Com;cbn. unfold Com_to_sum.\n  change (fun x1 : sigNat => sigSum_X x1) with (@sigSum_X sigNat ACom).\n  eexists (fun x => x*(11 + c__app + c__map) + 16 + c__app + c__map).\n  {extract. solverec. rewrite map_time_const,app_length,!repeat_length,size_Tok_enc. cbn [length]. \n    nia. }\n  1,2:now smpl_inO.\n  eexists (fun x => x*5 + 33).\n  { intros [];cbn. 2-4:now cbv.\n    rewrite size_list;unfold enc;cbn - [\"+\"].\n    rewrite map_app,map_repeat,sumn_map_add,sumn_map_c,map_app,sumn_app,map_repeat,map_map,app_length,repeat_length,map_length,sumn_repeat.\n    unfold enc. cbn;ring_simplify. rewrite LNat.size_nat_enc. unfold LNat.c__natsizeS, LNat.c__natsizeO, c__listsizeNil, c__listsizeCons.\n nia.\n  }\n  1,2:now smpl_inO.\nQed.\n\nLemma pTC_Encode_Prog : polyTimeComputable (Alphabets.Encode_Prog).\nProof.\n  unfold Alphabets.Encode_Prog,Encode_list. cbn.\n  eapply polyTimeComputable_proper_eq_flip. hnf. now setoid_rewrite encode_list_concat at 1.\n  eapply pTC_app. 2:now apply pTC_cnst.\n  eapply pTC_concat,pTC_map,polyTimeComputable_composition2.\n  now apply pTC_cnst.\n  eapply polyTimeComputable_composition.\n  exact pTC_Encode_Com. eapply pTC_map.\n  {eexists (fun x => _). eapply term_sigList_X. 1,2:now smpl_inO.\n   eexists (fun x => _). intros x. rewrite size_sigList. set (L_facts.size _). reflexivity. all:smpl_inO.\n  }\n  repeat smpl polyTimeComputable.\nQed.\n\nSmpl Add 1 simple eapply pTC_Encode_Prog : polyTimeComputable.\n\nLemma pTC_inl X Y `{encodable X} `{encodable Y} : polyTimeComputable (@inl X Y). \nProof. \n  eexists (fun x => _). eapply term_inl. 1, 2: smpl_inO. \n  eexists (fun x => _). intros x. rewrite size_sum. set (L_facts.size (enc x)). reflexivity. \n  all: smpl_inO. \nQed.\nSmpl Add 1 eapply pTC_inl : polyTimeComputable. \n\nFrom Complexity.Complexity Require Import Subtypes.\nImport Datatypes.Lists Datatypes.LBool.\nLemma LMGenNP_to_TMGenNP_mTM:\n  LMGenNP (list bool) ⪯p mTMGenNP_fixed (projT1 M.M).\nProof.\n  evar (f__size:nat -> nat).\n  enough (Hcert_f__size : forall maxSize (bs : list bool) sig R, size (enc bs) <= maxSize -> sizeOfTape (initValue (sig:=sig) _ R bs) <= f__size maxSize).\n\n  \n  evar (f__steps:nat * Pro * nat -> nat).\n  enough (Hf__steps : forall steps P maxSize t__cert k__LM,\n             sizeOfTape t__cert <= f__size maxSize\n             -> k__LM <= steps ->\n             M.time (k__LM, sizeOfmTapes (t__cert ::: M.ts__start P)) <= f__steps (steps,P,maxSize)).\n\n  \n  \n  eapply @reducesPolyMO_intro_restrictBy_both with\n      (f:=fun '(P,maxSize,steps) => (M.ts__start P,f__size maxSize,S (f__steps (steps,P,maxSize)))).\n  2:intros [[P maxSize] steps] H; split.\n  2:{ hnf in H|-*. destruct H as ((s&->&s__proc)&HsmallCert&Hk).\n      intros t__cert' k res' HM.\n      specialize (M.Realise HM) as H'. hnf in H'. specialize H' with (1:=eq_refl) as (bs'&Hbs'&(sigma'&k__LM'&HbsRed')).\n      specialize HsmallCert with (1:=HbsRed') as (bs&res__LM&Hbs&HbsRed&Hter__LM). clear HM k res' t__cert' bs' Hbs' sigma' k__LM' HbsRed'.\n      apply star_pow in HbsRed as (k__LM&HbsRed).\n      assert (Hk__LM : k__LM <= steps).\n      { eapply Hk. exact Hbs. split. all:eassumption. }\n      edestruct M.Terminates as (conf'&eq).\n      2:{ eexists (initValue _ _ (rev bs)),_. split. 2:eassumption. eapply Hcert_f__size. rewrite size_rev. easy. }\n      split. now clear;Lia.nia.\n      eexists _,_,_,(rev bs).\n      repeat simple apply conj.\n      1:now reflexivity.\n      1:now apply initValue_contains.\n      2:{\n        unshelve erewrite (_ : forall x, S x - 1 = x). 1:now clear;nia.\n        apply Hf__steps. 2:eassumption. eapply Hcert_f__size.  rewrite size_rev. easy.\n      }\n      rewrite rev_involutive. unfold evaluatesIn;eauto.\n  }\n  3:{ intros steps P maxSize t__cert k__LM Hsize Hk__LM.\n      rewrite M.sizeStart.\n      unfold M.time.\n      rewrite UpToC_le.\n      rewrite !Hk__LM. clear Hk__LM k__LM.\n      rewrite !Hsize. clear Hsize t__cert.\n      [f__steps]:refine (fun '(steps,P,maxSize) => _). unfold f__steps. reflexivity.\n  }\n  3:{ intros maxSize bs sig R Hsize. rewrite initValue_sizeOfTape. \n      \n      specialize @correct__leUpToC with (l:=BoollistEnc.boollist_size) (x:=bs) as ->.\n      rewrite <- size_list_enc_r in Hsize. rewrite Hsize. \n      [f__size]:refine (fun n => _). subst f__size;cbn beta. reflexivity.\n  }\n\n  2:{\n    destruct H as ((s&->&s__proc)&HsmallCert&Hsmallk).\n    unfold LMGenNP, mTMGenNP_fixed.\n    split.\n    -intros (cert' & HcertSize' & sigma'' & k' &Hk' &HR').\n     edestruct M.Terminates with (k:= S (f__steps (steps,compile s,maxSize))) as (tout&Hout).\n     { split. easy. eexists _,_,_,(rev cert'). rewrite rev_involutive. repeat simple apply conj.\n       1:reflexivity.\n       2:eexists;exact HR'.\n       1:now apply initValue_contains.\n       { unshelve erewrite (_ : forall x, S x - 1 = x). 1:now clear;nia.\n         apply Hf__steps. 2:eassumption.\n         eapply Hcert_f__size. now rewrite size_rev.\n       }\n     }\n     do 2 eexists.\n     2:{\n       eexists. eassumption. }\n     eapply Hcert_f__size. now rewrite size_rev.\n    -intros (t__cert&Hsize_t__cert&(res&Hres)).\n     specialize (M.Realise Hres) as H'. hnf in H'. specialize H' with (1:=eq_refl) as (bs'&Hbs'&(sigma'&k__LM'&HbsRed')).\n      specialize HsmallCert with (1:=HbsRed') as (bs&res__LM&Hbs&HbsRed&Hter__LM). clear Hres bs' Hbs' sigma' k__LM' HbsRed'.\n      apply star_pow in HbsRed as (k__LM&HbsRed).\n      assert (Hk__LM : k__LM <= steps).\n      { eapply Hsmallk. exact Hbs. split. all:eassumption. }\n      exists bs. repeat simple apply conj. 1:easy. unfold evaluatesIn; eauto 10.\n  }\n  {\n    clear Hf__steps Hcert_f__size.\n\n    nary apply pTC_destructuringToProj.\n(*     specialize pTC_destructuringToProj with (domain:=[nat;nat;list Tok]) as h. cbn in h. refine ( h _ _ _ _ _). *)\n    enough (polyTimeComputable f__size).\n    enough (polyTimeComputable f__steps).\n    repeat smpl polyTimeComputable.\n    -unfold M.ts__start. \n    unfold Alphabets.Encode_Prog.\n    \n    repeat smpl polyTimeComputable.\n    {\n      unfold Retr_f. cbn. unfold retr_comp_f,retract_inl_f.\n      eapply polyTimeComputable_composition.\n      eapply polyTimeComputable_composition.\n      eapply polyTimeComputable_composition.\n      eapply polyTimeComputable_composition.\n      \n      now eapply pTC_id. 3, 4: smpl polyTimeComputable. \n      2:{ eexists (fun x => _). eapply term_sigList_X. 1,2:now smpl_inO.\n          eexists (fun x => _). intros x. rewrite size_sigList. set (size _). reflexivity. all:smpl_inO.\n      }\n      { eexists (fun x' => _). now apply (term_sigPair_Y).  1,2:now smpl_inO.\n        eexists (fun x => 4 + _). intros x. unfold enc;cbn. set (size _). reflexivity. all:smpl_inO.\n      }\n    }\n    -unfold f__steps. nary apply pTC_destructuringToProj.\n    (*     specialize pTC_destructuringToProj with (domain:=[nat;nat;list Tok]) as h. cbn in h. refine ( h _ _ _ _ _). *)\n     repeat smpl polyTimeComputable.\n    -unfold f__size.\n     repeat smpl polyTimeComputable.\n  }\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/NP/TM/LM_to_mTM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.29846698822199286}}
{"text": "From Coq Require Import Cyclic31.\nFrom Coq Require Import List.\nFrom Coq Require Import Znumtheory.\nFrom ConCert.Utils Require Import Extras.\nFrom ConCert.Execution Require Import Blockchain.\nFrom ConCert.Execution Require Import BoundedN.\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 ContractCommon. Import AddressMap.\nFrom ConCert.Execution.Test Require Import LocalBlockchain.\nFrom ConCert.Examples.BoardroomVoting Require Import BoardroomMath.\nFrom ConCert.Examples.BoardroomVoting Require Import BoardroomVoting.\n\nImport ListNotations.\n\n\nLocal Open Scope Z.\nLocal Open Scope broom.\n\n(*\nDefinition modulus : bigZ := 1552518092300708935130918131258481755631334049434514313202351194902966239949102107258669453876591642442910007680288864229150803718918046342632727613031282983744380820890196288509170691316593175367469551763119843371637221007210577919.\nDefinition generator : bigZ := 2.\n*)\nDefinition modulus : Z := 201697267445741585806196628073.\nDefinition four := 4%nat.\nDefinition seven := 7%nat.\nDefinition _1234583932 := 1234583932.\nDefinition _23241 := 23241.\nDefinition _159338231 := 159338231.\n\n\n(* Definition modulus : Z := 13. *)\nDefinition generator : Z := 3.\n\nAxiom modulus_prime : prime modulus.\nImport Lia.\nModule ZAxiomParams <: BoardroomAxiomsZParams.\n  Definition p := modulus.\n  Definition isprime := modulus_prime.\n  Program Definition prime_ge_2 : p >= 2.\n  Proof. easy. Defined.\nEnd ZAxiomParams.\nModule BVZAxioms := BoardroomAxiomsZ ZAxiomParams. Import BVZAxioms.\n\n#[local]\nExisting Instance boardroom_axioms_Z.\n\nLemma generator_nonzero : generator !== 0.\nProof. discriminate. Qed.\n\nAxiom generator_is_generator :\n  forall z,\n    ~(z == 0) ->\n    exists! (e : Z), (0 <= e < order - 1)%Z /\\ pow generator e == z.\n\n#[local]\nInstance generator_instance : Generator boardroom_axioms_Z :=\n  {| BoardroomMath.generator := generator;\n     BoardroomMath.generator_nonzero := generator_nonzero;\n     generator_generates := generator_is_generator; |}.\n\nDefinition num_parties : nat := seven.\nDefinition votes_for : nat := four.\n\n(* a pseudo-random generator for secret keys *)\nDefinition sk n := (Z.of_nat n + _1234583932) * (modulus - _23241)^_159338231.\n\n(* Make a list of secret keys, here starting at i=7 *)\nDefinition sks : list Z := map sk (seq seven num_parties).\n\n(* Make a list of votes for each party *)\nDefinition svs : list bool :=\n  Eval compute in map (fun _ => true)\n                      (seq 0 votes_for)\n                  ++ map (fun _ => false)\n                         (seq 0 (num_parties - votes_for)).\n\n(* Compute the public keys for each party *)\nTime Definition pks : list Z :=\n  Eval vm_compute in map compute_public_key sks.\n\nDefinition rks : list Z :=\n  Eval vm_compute in map (reconstructed_key pks) (seq 0 (length pks)).\n\n(* In this example we just use xor for the hash function, which is\n   obviously not cryptographically secure. *)\nDefinition oneN : N := 1%N.\n\nDefinition hash_func (l : list positive) : positive :=\n  N.succ_pos (fold_left (fun a p => N.lxor (Npos p) a) l oneN).\n\n\nDefinition AddrSize := (2^128)%N.\n#[local]\nInstance Base : ChainBase := LocalChainBase AddrSize.\n#[local]\nInstance ChainBuilder : ChainBuilderType := LocalChainBuilderImpl AddrSize true.\n\nModule Params <: BoardroomParams.\n  Definition A : Type := Z.\n  Definition H : list positive -> positive := hash_func.\n  Definition ser : Serializable A := _.\n  Definition axioms : BoardroomAxioms A := _.\n  Definition gen : Generator axioms := _.\n  Axiom d : DiscreteLog axioms gen.\n  Definition discr_log : DiscreteLog axioms gen := d.\n  Definition Base := Base.\nEnd Params.\n\nModule BV := BoardroomVoting Params. Import BV.\n\n(* Compute the signup messages that would be sent by each party.\n   We just use the public key as the chosen randomness here. *)\nDefinition _3 := 3%nat.\nDefinition _5 := 5.\nDefinition _11 := 11.\n\nTime Definition signups : list Msg :=\n  Eval vm_compute in map (fun '(sk, pk, i) => make_signup_msg sk _5 i)\n                             (zip (zip sks pks) (seq 0 (length sks))).\n\n(* Compute the submit_vote messages that would be sent by each party *)\n(* Our functional correctness proof assumes that the votes were computed\n   using the make_vote_msg function provided by the contract.\n   In this example we just use the secret key as the random parameters. *)\nDefinition votes : list Msg :=\n  Eval vm_compute in map (fun '(i, sk, sv, rk) => make_vote_msg pks i sk sv sk sk sk)\n                             (zip (zip (zip (seq 0 (length pks)) sks) svs) rks).\n\nDefinition A a :=\n  BoundedN.of_Z_const AddrSize a.\n\nLocal Open Scope nat.\nDefinition addrs : list Address.\nProof.\n  let rec add_addr z n :=\n    match n with\n    | O => constr:(@nil Address)\n    | S ?n => let tail := add_addr (z + 1)%Z n in\n              constr:(cons (A z) tail)\n    end in\n  let num := eval compute in num_parties in\n  let tm := add_addr _11%Z num in\n  let tm := eval vm_compute in tm in\n  exact tm.\nDefined.\n\nDefinition voters_map : AddrMap unit := AddressMap.of_list (map (fun a => (a, tt)) addrs).\n\nDefinition five := 5%nat.\n\nDefinition deploy_setup :=\n  {| eligible_voters := voters_map;\n     finish_registration_by := _3;\n     finish_commit_by := None;\n     finish_vote_by := five;\n     registration_deposit := 0; |}.\n\nLocal Open Scope list.\nDefinition boardroom_example : option nat :=\n  let chain : ChainBuilder := builder_initial in\n  let creator : Address := A 10 in\n  let add_block (chain : ChainBuilder) (acts : list Action) :=\n      let next_header :=\n          {| block_height := S (chain_height chain);\n             block_slot := S (current_slot chain);\n             block_finalized_height := finalized_height chain;\n             block_creator := creator;\n             block_reward := 50; |} in\n      option_of_result (builder_add_block chain next_header acts) in\n  do chain <- add_block chain [];\n  let dep := build_act creator creator (create_deployment 0 boardroom_voting deploy_setup) in\n  do chain <- add_block chain [dep];\n  do caddr <- hd_error (AddressMap.keys (lc_contracts (lcb_lc chain)));\n  let send addr m := build_act addr addr (act_call caddr 0 (serialize m)) in\n  let calls := map (fun '(addr, m) => send addr m) (zip addrs signups) in\n  do chain <- add_block chain calls;\n  let votes := map (fun '(addr, m) => send addr m) (zip addrs votes) in\n  do chain <- add_block chain votes;\n  let tally := build_act creator creator (act_call caddr 0 (serialize tally_votes)) in\n  do chain <- add_block chain [tally];\n  do state <- contract_state (lcb_lc chain) caddr;\n  BV.tally state.\n\nCheck (@eq_refl (option nat) (Some votes_for)) <: boardroom_example = Some votes_for.\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/boardroomVoting/BoardroomVotingTest.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.29846698822199286}}
{"text": "Require Import Framework File FileDiskLayer FileDiskNoninterference FileDiskRefinement.\nRequire Import FunctionalExtensionality Lia Language SameRetType TSCommon InodeTS.\n\nLemma inode_allocations_are_same_2:\nforall u im1 im2 fm1 fm2 bm1 bm2 s1 s2 inum ex,\nInode.inode_rep im1 s1 ->\nInode.inode_rep im2 s2 ->\nfile_map_rep fm1 im1 bm1 ->\nfile_map_rep fm2 im2 bm2 ->\nsame_for_user_except u ex fm1 fm2 ->\ninum < Inode.InodeAllocatorParams.num_of_blocks ->\nnth_error\n(value_to_bits\n  (s1 Inode.InodeAllocatorParams.bitmap_addr))\ninum =\nnth_error\n  (value_to_bits (s2 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 (im1 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 (im2 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 H15.\n      cleanup; split_ors; cleanup; try congruence.\n      rewrite H13, H7 in D; simpl in *; congruence.\n      rewrite nth_seln_eq in H.\n      repeat erewrite nth_error_nth'.\n\n      eapply Inode.InodeAllocator.valid_bits_extract with (n:= inum) in H10.\n      cleanup; split_ors; cleanup; try congruence.\n      rewrite H8, H18 in D1; simpl in *; congruence.\n      rewrite nth_seln_eq in H15, H0.\n      rewrite H0, H15; 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 H3; edestruct H2; exfalso.\n      apply H12; eauto.\n      eapply H7; eauto; congruence.\n    }\n    {\n      cleanup.\n    }\n  }\n  {\n    eapply_fresh FileInnerSpecs.inode_missing_then_file_missing in D; eauto.\n    cleanup.\n    destruct_fresh (fm1 inum).\n    {\n      congruence.\n    }\n    destruct_fresh (im2 inum).\n    {\n      unfold file_map_rep in *; cleanup.\n      edestruct H1; edestruct H3; exfalso.\n      eapply H9; eauto.\n      eapply H12; eauto.\n      eapply H2; 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 H14.\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 H9.\n      cleanup; split_ors; cleanup; try congruence.\n      rewrite nth_seln_eq in H17.\n      rewrite H0, H17; eauto.\n      rewrite H7, H18 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 H12, H14 in D; simpl in *; congruence.\n    }\n  }\nQed.\n\nLemma TS_free_all_blocks:\nforall bnl1 bnl2 o s1 s2 ret1 u dm1 dm2,\nDiskAllocator.block_allocator_rep dm1 (fst (snd s1)) ->\nDiskAllocator.block_allocator_rep dm2 (fst (snd s2)) ->\nexec (TransactionalDiskLayer.TDLang FSParameters.data_length) u o s1 (free_all_blocks bnl1) ret1 ->\nlength bnl1 = length bnl2 ->\nForall (fun a => a < DiskAllocatorParams.num_of_blocks) bnl1 ->\nForall (fun a => a < DiskAllocatorParams.num_of_blocks) bnl2 ->\nForall (fun a => nth_error (value_to_bits (fst (snd s1) DiskAllocatorParams.bitmap_addr)) a = Some true) bnl1 ->\nForall (fun a => nth_error (value_to_bits (fst (snd s2) DiskAllocatorParams.bitmap_addr)) a = Some true) bnl2 ->\nNoDup bnl1 ->\nNoDup bnl2 ->\nexists ret2, \nexec (TransactionalDiskLayer.TDLang FSParameters.data_length) u o s2 (free_all_blocks bnl2) ret2 /\\\n(extract_ret ret1 = None <-> extract_ret ret2 = None).\nProof.\n  induction bnl1; simpl; intros; eauto.\n  {\n    invert_exec;\n    destruct bnl2; simpl in *; try lia.\n    eexists; split.\n    repeat econstructor.\n    simpl; intuition.\n\n    eexists; split.\n    repeat econstructor.\n    simpl; intuition.\n  }\n  {\n   invert_exec;\n   destruct bnl2; simpl in *; try lia.\n   {\n   eapply_fresh TS_free in H1.\n   cleanup.\n   destruct x2; simpl in *; try solve [intuition congruence].\n   eapply_fresh DiskAllocator.free_finished_oracle_eq in H1; eauto.\n   destruct o; simpl in *; try solve [intuition congruence].\n   eapply_fresh DiskAllocator.free_finished in H1; eauto.\n   cleanup; split_ors; cleanup.\n   eapply_fresh DiskAllocator.free_finished in H10; only 2: apply H0; eauto.\n   cleanup; split_ors; cleanup.\n\n   eapply IHbnl1 in H9.\n   cleanup.\n   destruct x2; simpl in *; try solve [intuition congruence].\n  exists (Finished s3 o); split.\n  econstructor.\n  eauto.\n  simpl; eauto.\n  simpl; intuition congruence.\n  eauto.\n  eauto.\n  eauto.\n  inversion H3; eauto.\n  inversion H4; eauto.\n  {\n    inversion H3; eauto.\n    inversion H5; eauto; cleanup.\n    inversion H7; subst.\n    repeat cleanup_pairs.\n    unfold DiskAllocator.block_allocator_rep in *; cleanup.\n    eapply Forall_forall; intros.\n    eapply Forall_forall in H22; eauto.\n    eapply DiskAllocator.valid_bits_extract with (n:= x1) in H32.\n    cleanup.\n    eapply DiskAllocator.valid_bits_extract with (n:= x1) in H20.\n    cleanup.\n    repeat rewrite nth_seln_eq in *.\n    eapply Forall_forall in H26; eauto.\n    eapply nth_error_nth with (d:= false) in H26.\n    setoid_rewrite H26 in H12.\n    setoid_rewrite Mem.delete_ne in H20; eauto.\n    repeat split_ors; cleanup; try congruence; eauto.\n    erewrite nth_error_nth'. \n    setoid_rewrite H20; eauto.\n    all: try rewrite value_to_bits_length;\n    pose proof DiskAllocatorParams.num_of_blocks_in_bounds;\n    unfold DiskAllocatorParams.num_of_blocks in *; try lia.\n    all: intros Hx; subst; intuition.\n  }\n  {\n    inversion H4; eauto.\n    inversion H6; eauto; cleanup.\n    inversion H8; subst.\n    repeat cleanup_pairs.\n    unfold DiskAllocator.block_allocator_rep in *; cleanup.\n    eapply Forall_forall; intros.\n    eapply Forall_forall in H22; eauto.\n    eapply DiskAllocator.valid_bits_extract with (n:= x1) in H29.\n    cleanup.\n    eapply DiskAllocator.valid_bits_extract with (n:= x1) in H15.\n    cleanup.\n    repeat rewrite nth_seln_eq in *.\n    eapply Forall_forall in H26; eauto.\n    eapply nth_error_nth with (d:= false) in H26.\n    setoid_rewrite H26 in H12.\n    setoid_rewrite Mem.delete_ne in H15; eauto.\n    repeat split_ors; cleanup; try congruence; eauto.\n    erewrite nth_error_nth'. \n    setoid_rewrite H15; eauto.\n    all: try rewrite value_to_bits_length;\n    pose proof DiskAllocatorParams.num_of_blocks_in_bounds;\n    unfold DiskAllocatorParams.num_of_blocks in *; try lia.\n    all: intros Hx; subst; intuition.\n  }\n  inversion H7; eauto.\n  inversion H8; eauto.\n  inversion H3; inversion H4; subst.\n  intuition.\n  inversion H5; inversion H6; \n  subst; eauto.\n  setoid_rewrite H16; eauto.\n   }\n   {\n     invert_step.\n    eapply_fresh TS_free in H1.\n    cleanup.\n    destruct x0; simpl in *; try solve [intuition congruence].\n    eapply_fresh DiskAllocator.free_finished_oracle_eq in H1; eauto.\n    destruct o; simpl in *; try solve [intuition congruence].\n   exists (Finished s0 None); split.\n   econstructor.\n   eauto.\n   simpl; eauto.\n   repeat econstructor.\n   simpl; intuition congruence.\n   inversion H3; inversion H4; subst.\n  intuition.\n  inversion H5; inversion H6; \n  subst; eauto.\n  setoid_rewrite H15; eauto.\n   }\n   {\n     repeat invert_step_crash.\n     {\n        eapply_fresh TS_free in H1.\n        cleanup.\n        destruct x; simpl in *; try solve [intuition congruence].\n\n        exists (Crashed s0); split.\n        eapply ExecBindCrash.\n        eauto.\n        simpl; intuition congruence.\n        inversion H3; inversion H4; subst.\n        intuition.\n        inversion H5; inversion H6; \n        subst; eauto.\n        setoid_rewrite H15; eauto.\n      }\n      {\n        eapply_fresh TS_free in H9.\n        logic_clean.\n        destruct x3; simpl in *; try solve [intuition congruence].\n        eapply_fresh DiskAllocator.free_finished_oracle_eq in H9; eauto.\n      eapply_fresh DiskAllocator.free_finished in H1; eauto.\n      eapply_fresh DiskAllocator.free_finished in H9; only 2: apply H; eauto.\n      cleanup; repeat split_ors; cleanup; simpl in *; try solve [intuition congruence].\n      {\n        eapply IHbnl1 in H10.\n   cleanup.\n   destruct x0; simpl in *; try solve [intuition congruence].\n  exists (Crashed s3); split.\n  econstructor.\n  eauto.\n  simpl; eauto.\n  simpl; intuition congruence.\n  eauto.\n  eauto.\n  eauto.\n  inversion H3; eauto.\n  inversion H4; eauto.\n  {\n    inversion H3; eauto.\n    inversion H5; eauto; cleanup.\n    inversion H7; subst.\n    repeat cleanup_pairs.\n    unfold DiskAllocator.block_allocator_rep in *; cleanup.\n    eapply Forall_forall; intros.\n    eapply Forall_forall in H22; eauto.\n    eapply DiskAllocator.valid_bits_extract with (n:= x) in H32.\n    cleanup.\n    eapply DiskAllocator.valid_bits_extract with (n:= x) in H15.\n    cleanup.\n    repeat rewrite nth_seln_eq in *.\n    eapply Forall_forall in H26; eauto.\n    eapply nth_error_nth with (d:= false) in H26.\n    setoid_rewrite H26 in H12.\n    setoid_rewrite Mem.delete_ne in H15; eauto.\n    repeat split_ors; cleanup; try congruence; eauto.\n    erewrite nth_error_nth'. \n    setoid_rewrite H15; eauto.\n    all: try rewrite value_to_bits_length;\n    pose proof DiskAllocatorParams.num_of_blocks_in_bounds;\n    unfold DiskAllocatorParams.num_of_blocks in *; try lia.\n    all: intros Hx; subst; intuition.\n  }\n  {\n    inversion H4; eauto.\n    inversion H6; eauto; cleanup.\n    inversion H8; subst.\n    repeat cleanup_pairs.\n    unfold DiskAllocator.block_allocator_rep in *; cleanup.\n    eapply Forall_forall; intros.\n    eapply Forall_forall in H22; eauto.\n    eapply DiskAllocator.valid_bits_extract with (n:= x) in H29.\n    cleanup.\n    eapply DiskAllocator.valid_bits_extract with (n:= x) in H20.\n    cleanup.\n    repeat rewrite nth_seln_eq in *.\n    eapply Forall_forall in H26; eauto.\n    eapply nth_error_nth with (d:= false) in H26.\n    setoid_rewrite H26 in H12.\n    setoid_rewrite Mem.delete_ne in H20; eauto.\n    repeat split_ors; cleanup; try congruence; eauto.\n    erewrite nth_error_nth'. \n    setoid_rewrite H20; eauto.\n    all: try rewrite value_to_bits_length;\n    pose proof DiskAllocatorParams.num_of_blocks_in_bounds;\n    unfold DiskAllocatorParams.num_of_blocks in *; try lia.\n    all: intros Hx; subst; intuition.\n  }\n  inversion H7; eauto.\n  inversion H8; eauto.\n  }\n  {\n    invert_step.\n   exists (Crashed s0); split.\n   econstructor.\n   eauto.\n   simpl; eauto.\n\n   repeat econstructor.\n   simpl; intuition congruence.\n  }\n  inversion H3; inversion H4; subst.\n  intuition.\n  inversion H5; inversion H6; \n  subst; eauto.\n  setoid_rewrite H16; eauto.\n  }\n  }\n}\nUnshelve.\nall: eauto.\nQed.\n\nLemma TS_delete_inner:\nforall o ex fm1 fm2 s1 s2 inum ret1 u u',\nsame_for_user_except u' ex fm1 fm2 ->\nfiles_inner_rep fm1 (fst (snd s1)) ->\nfiles_inner_rep fm2 (fst (snd s2)) ->\nexec (TransactionalDiskLayer.TDLang FSParameters.data_length) u o s1 (delete_inner inum) ret1 ->\nexists ret2, \nexec (TransactionalDiskLayer.TDLang FSParameters.data_length) u o s2 (delete_inner inum) ret2 /\\\n(extract_ret ret1 = None <-> extract_ret ret2 = None).\nProof. \nTransparent delete_inner.  \nunfold delete_inner; intros.\ninvert_step.\n{\n  eapply_fresh TS_get_all_block_numbers in H2; eauto.\n  cleanup.\n  destruct x0; simpl in *; try solve [intuition congruence].\n  eapply_fresh Inode.get_all_block_numbers_finished_oracle_eq in H2; eauto.\n  destruct o; simpl in *; try solve [intuition congruence].\n  unfold files_inner_rep in *; cleanup.\n  eapply_fresh Inode.get_all_block_numbers_finished in H2; eauto.\n  eapply_fresh Inode.get_all_block_numbers_finished in H5; eauto.\n  cleanup; repeat split_ors; cleanup.\n\n  eapply_fresh TS_free_all_blocks in H3.\n  cleanup.\n  destruct x10; simpl in *; try solve [intuition congruence].\n  eapply_fresh free_all_blocks_finished_oracle_eq in H3.\n  2: apply H7.\n  destruct o; simpl in *; try solve [intuition congruence].\n  eapply_fresh FileInnerSpecs.free_all_blocks_finished in H3; eauto.\n  eapply_fresh FileInnerSpecs.free_all_blocks_finished in H7.\n  cleanup; repeat split_ors; cleanup.\n\n  eapply_fresh TS_free_inode in H4.\n  cleanup.\n  destruct x12; simpl in *; try solve [intuition congruence].\n  eapply_fresh Inode.free_finished_oracle_eq in H4; eauto.\n\n  exists (Finished s4 o); split.\n  econstructor; eauto.\n  simpl; econstructor; eauto.\n  simpl; eauto.\n  simpl; intuition congruence.\n  intuition.\n  all: eauto.\n  all: try solve[ \n  eapply DiskAllocator.block_allocator_rep_inbounds_eq; \n  eauto; intros; repeat solve_bounds].\n  {\n    \n    eapply inode_allocations_are_same_2.\n    5: eauto.\n    all: eauto.\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      unfold Inode.inode_rep in *; cleanup.\n      eexists; split.\n      eapply Inode.InodeAllocator.block_allocator_rep_inbounds_eq.\n      apply b0.\n      intros; repeat solve_bounds.\n      eauto.\n    }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      unfold Inode.inode_rep in *; cleanup.\n      eexists; split.\n      eapply Inode.InodeAllocator.block_allocator_rep_inbounds_eq.\n      apply b.\n      intros; repeat solve_bounds.\n      eauto.\n    }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      unfold Inode.inode_rep, \n      Inode.InodeAllocator.block_allocator_rep,\n      Inode.inode_map_rep in *; cleanup.\n      destruct (Compare_dec.lt_dec inum Inode.InodeAllocatorParams.num_of_blocks); eauto.\n      rewrite e5, e8 in H23; simpl in *; try lia; try congruence.\n    }\n  }\n  {\n    eapply DiskAllocator.block_allocator_rep_inbounds_eq.\n    2: intros; repeat solve_bounds.\n    eauto.\n  }\n  {\n    eapply SameRetType.all_block_numbers_in_bound.\n    2: eauto.\n    all: eauto.\n  }\n  {\n    eapply SameRetType.all_block_numbers_in_bound.\n    4: eauto.\n    all: eauto.\n    eapply File.DiskAllocator.block_allocator_rep_inbounds_eq; eauto.\n    intros; FileInnerSpecs.solve_bounds.\n  }\n    {\n    eapply DiskAllocator.block_allocator_rep_inbounds_eq.\n    2: intros; repeat solve_bounds.\n    eauto.\n    }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in H22; eauto.\n      eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in H23; eauto.\n      cleanup.\n      unfold same_for_user_except in *; cleanup.\n      eapply_fresh H17 in H7; eauto; cleanup.\n      unfold file_map_rep, file_rep in *; cleanup.\n      eapply_fresh H25 in H23; eauto; cleanup.\n      eapply_fresh H24 in H22; eauto; cleanup.\n      eauto.\n    }\n    {\n    eapply SameRetType.all_block_numbers_in_bound.\n    4: eauto.\n    all: eauto.\n    eapply File.DiskAllocator.block_allocator_rep_inbounds_eq; eauto.\n    intros; FileInnerSpecs.solve_bounds.\n  }\n  {\n    eapply SameRetType.all_block_numbers_in_bound.\n    4: eauto.\n    all: eauto.\n    eapply File.DiskAllocator.block_allocator_rep_inbounds_eq; eauto.\n    intros; FileInnerSpecs.solve_bounds.\n  }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in H23; eauto.\n      cleanup.\n      unfold file_map_rep, file_rep in *; cleanup.\n      eapply_fresh H16 in H23; eauto; cleanup.\n      eapply Forall_forall; eauto; intros.\n      eapply In_nth in H24; cleanup.\n      eapply nth_error_Some in H24.\n      destruct_fresh (nth_error (Inode.block_numbers x9) x11); try congruence.\n      eapply_fresh H21 in D; cleanup.\n      unfold DiskAllocator.block_allocator_rep in *; cleanup.\n      eapply nth_error_nth in D.\n      rewrite H25 in D; subst.\n      eapply DiskAllocator.valid_bits_extract with (n:= a) in v0; eauto; cleanup.\n      split_ors; cleanup.\n      rewrite nth_seln_eq in H11; erewrite nth_error_nth'; eauto.\n      rewrite H19, H11; eauto.\n      all: try rewrite value_to_bits_length;\n      unfold DiskAllocatorParams.num_of_blocks in *;\n      pose proof DiskAllocatorParams.num_of_blocks_in_bounds; try lia.\n      destruct (Compare_dec.lt_dec a FSParameters.file_blocks_count); try lia.\n      rewrite e4 in H27; try congruence; try lia.\n      destruct (Compare_dec.lt_dec a FSParameters.file_blocks_count); try lia.\n      rewrite e4 in H27; try congruence; try lia.\n      setoid_rewrite D in H24; intuition.\n    }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in H22; eauto.\n      cleanup.\n      unfold file_map_rep, file_rep in *; cleanup.\n      eapply_fresh H15 in H22; eauto; cleanup.\n      eapply Forall_forall; eauto; intros.\n      eapply In_nth in H24; cleanup.\n      eapply nth_error_Some in H24.\n      destruct_fresh (nth_error (Inode.block_numbers x8) x11); try congruence.\n      eapply_fresh H21 in D; cleanup.\n      unfold DiskAllocator.block_allocator_rep in *; cleanup.\n      eapply nth_error_nth in D.\n      rewrite H25 in D; subst.\n      eapply DiskAllocator.valid_bits_extract with (n:= a) in v; eauto; cleanup.\n      split_ors; cleanup.\n      rewrite nth_seln_eq in H11; erewrite nth_error_nth'; eauto.\n      rewrite H14, H11; eauto.\n      all: try rewrite value_to_bits_length;\n      unfold DiskAllocatorParams.num_of_blocks in *;\n      pose proof DiskAllocatorParams.num_of_blocks_in_bounds; try lia.\n      destruct (Compare_dec.lt_dec a FSParameters.file_blocks_count); try lia.\n      rewrite e1 in H27; try congruence; try lia.\n      destruct (Compare_dec.lt_dec a FSParameters.file_blocks_count); try lia.\n      rewrite e1 in H27; try congruence; try lia.\n      setoid_rewrite D in H24; intuition.\n    }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      unfold Inode.inode_rep, file_map_rep, file_rep, Inode.inode_map_rep in *; cleanup.\n      unfold Inode.inode_map_valid, Inode.inode_valid in *; cleanup.\n      eapply H24 in H23; cleanup; eauto.\n    }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      unfold Inode.inode_rep, file_map_rep, file_rep, Inode.inode_map_rep in *; cleanup.\n      unfold Inode.inode_map_valid, Inode.inode_valid in *; cleanup.\n      eapply H16 in H22; cleanup; eauto.\n    }\n}\n{\n  eapply_fresh TS_get_all_block_numbers in H2; eauto.\n  cleanup.\n  destruct x0; simpl in *; try solve [intuition congruence].\n  eapply_fresh Inode.get_all_block_numbers_finished_oracle_eq in H2; eauto.\n  destruct o; simpl in *; try solve [intuition congruence].\n  unfold files_inner_rep in *; cleanup.\n  eapply_fresh Inode.get_all_block_numbers_finished in H2; eauto.\n  eapply_fresh Inode.get_all_block_numbers_finished in H4; eauto.\n  cleanup; repeat split_ors; cleanup.\n\n  eapply_fresh TS_free_all_blocks in H3.\n  cleanup.\n  destruct x8; simpl in *; try solve [intuition congruence].\n  eapply_fresh free_all_blocks_finished_oracle_eq in H3.\n  2: apply H6.\n  destruct o; simpl in *; try solve [intuition congruence].\n  eapply_fresh FileInnerSpecs.free_all_blocks_finished in H3; eauto.\n  eapply_fresh FileInnerSpecs.free_all_blocks_finished in H6.\n  cleanup; repeat split_ors; cleanup.\n\n  exists (Finished s3 None); split.\n  econstructor; eauto.\n  simpl; econstructor; eauto.\n  simpl; eauto.\n  repeat econstructor.\n  simpl; intuition congruence.\n  all: eauto.\n  all: try solve[ \n  eapply DiskAllocator.block_allocator_rep_inbounds_eq; \n  eauto; intros; repeat solve_bounds].\n  {\n    eapply DiskAllocator.block_allocator_rep_inbounds_eq.\n    2: intros; repeat solve_bounds.\n    eauto.\n  }\n  {\n    eapply SameRetType.all_block_numbers_in_bound.\n    4: eauto.\n    all: eauto.\n    eapply File.DiskAllocator.block_allocator_rep_inbounds_eq; eauto.\n    intros; FileInnerSpecs.solve_bounds.\n  }\n  {\n    eapply SameRetType.all_block_numbers_in_bound.\n    4: eauto.\n    all: eauto.\n    eapply File.DiskAllocator.block_allocator_rep_inbounds_eq; eauto.\n    intros; FileInnerSpecs.solve_bounds.\n  }\n    {\n    eapply DiskAllocator.block_allocator_rep_inbounds_eq.\n    2: intros; repeat solve_bounds.\n    eauto.\n    }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in H22; eauto.\n      eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in H21; eauto.\n      cleanup.\n      unfold same_for_user_except in *; cleanup.\n      eapply_fresh H16 in H6; eauto; cleanup.\n      unfold file_map_rep, file_rep in *; cleanup.\n      eapply_fresh H24 in H22; eauto; cleanup.\n      eapply_fresh H23 in H21; eauto; cleanup.\n      eauto.\n    }\n    \n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      unfold Inode.inode_rep, file_map_rep, file_rep, Inode.inode_map_rep in *; cleanup.\n      unfold Inode.inode_map_valid, Inode.inode_valid in *; cleanup.\n      eapply H23 in H22; cleanup; eauto.\n    }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      unfold Inode.inode_rep, file_map_rep, file_rep, Inode.inode_map_rep in *; cleanup.\n      unfold Inode.inode_map_valid, Inode.inode_valid in *; cleanup.\n      eapply H15 in H21; cleanup; eauto.\n  }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in H22; eauto.\n      cleanup.\n      unfold file_map_rep, file_rep in *; cleanup.\n      eapply_fresh H15 in H22; eauto; cleanup.\n      eapply Forall_forall; eauto; intros.\n      eapply In_nth in H23; cleanup.\n      eapply nth_error_Some in H23.\n      destruct_fresh (nth_error (Inode.block_numbers x7) x9); try congruence.\n      eapply_fresh H20 in D; cleanup.\n      unfold DiskAllocator.block_allocator_rep in *; cleanup.\n      eapply nth_error_nth in D.\n      rewrite H24 in D; subst.\n      eapply DiskAllocator.valid_bits_extract with (n:= a) in v0; eauto; cleanup.\n      split_ors; cleanup.\n      rewrite nth_seln_eq in H10; erewrite nth_error_nth'; eauto.\n      rewrite H18, H10; eauto.\n      all: try rewrite value_to_bits_length;\n      unfold DiskAllocatorParams.num_of_blocks in *;\n      pose proof DiskAllocatorParams.num_of_blocks_in_bounds; try lia.\n      destruct (Compare_dec.lt_dec a FSParameters.file_blocks_count); try lia.\n      rewrite e4 in H26; try congruence; try lia.\n      destruct (Compare_dec.lt_dec a FSParameters.file_blocks_count); try lia.\n      rewrite e4 in H26; try congruence; try lia.\n      setoid_rewrite D in H23; intuition.\n    }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in H21; eauto.\n      cleanup.\n      unfold file_map_rep, file_rep in *; cleanup.\n      eapply_fresh H14 in H21; eauto; cleanup.\n      eapply Forall_forall; eauto; intros.\n      eapply In_nth in H23; cleanup.\n      eapply nth_error_Some in H23.\n      destruct_fresh (nth_error (Inode.block_numbers x6) x9); try congruence.\n      eapply_fresh H20 in D; cleanup.\n      unfold DiskAllocator.block_allocator_rep in *; cleanup.\n      eapply nth_error_nth in D.\n      rewrite H24 in D; subst.\n      eapply DiskAllocator.valid_bits_extract with (n:= a) in v; eauto; cleanup.\n      split_ors; cleanup.\n      rewrite nth_seln_eq in H10; erewrite nth_error_nth'; eauto.\n      rewrite H13, H10; eauto.\n      all: try rewrite value_to_bits_length;\n      unfold DiskAllocatorParams.num_of_blocks in *;\n      pose proof DiskAllocatorParams.num_of_blocks_in_bounds; try lia.\n      destruct (Compare_dec.lt_dec a FSParameters.file_blocks_count); try lia.\n      rewrite e1 in H26; try congruence; try lia.\n      destruct (Compare_dec.lt_dec a FSParameters.file_blocks_count); try lia.\n      rewrite e1 in H26; try congruence; try lia.\n      setoid_rewrite D in H23; intuition.\n    }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      unfold Inode.inode_rep, file_map_rep, file_rep, Inode.inode_map_rep in *; cleanup.\n      unfold Inode.inode_map_valid, Inode.inode_valid in *; cleanup.\n      eapply H23 in H22; cleanup; eauto.\n    }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      unfold Inode.inode_rep, file_map_rep, file_rep, Inode.inode_map_rep in *; cleanup.\n      unfold Inode.inode_map_valid, Inode.inode_valid in *; cleanup.\n      eapply H15 in H21; cleanup; eauto.\n    }\n}\n{\n  eapply_fresh TS_get_all_block_numbers in H2; eauto.\n  cleanup.\n  destruct x0; simpl in *; try solve [intuition congruence].\n  eapply_fresh Inode.get_all_block_numbers_finished_oracle_eq in H2; eauto.\n  destruct o; simpl in *; try solve [intuition congruence].\n  \n  exists (Finished s0 None); split.\n  econstructor; eauto.\n  simpl; econstructor; eauto.\n  simpl; intuition congruence.\n}\n{\n  repeat invert_step_crash.\n  {\n    eapply_fresh TS_get_all_block_numbers in H2; eauto.\n    cleanup.\n    destruct x; simpl in *; try solve [intuition congruence].\n    \n    exists (Crashed s0); split.\n    eapply ExecBindCrash; eauto.\n    simpl; intuition congruence.\n  }\n  {\n    eapply_fresh TS_get_all_block_numbers in H3; eauto.\n    logic_clean.\n    destruct x3; simpl in *; try solve [intuition congruence].\n    eapply_fresh Inode.get_all_block_numbers_finished_oracle_eq in H3; eauto.\n    unfold files_inner_rep in *; logic_clean.\n    eapply_fresh Inode.get_all_block_numbers_finished in H3; eauto.\n    eapply_fresh Inode.get_all_block_numbers_finished in H2; eauto.\n    cleanup; repeat split_ors; cleanup; try solve [intuition congruence].\n    {\n      repeat invert_step_crash.\n      {\n        eapply_fresh TS_free_all_blocks in H4.\n        cleanup.\n        destruct x8; simpl in *; try solve [intuition congruence].\n\n        exists (Crashed s3); split.\n        econstructor; eauto.\n        simpl;\n        eapply ExecBindCrash; eauto.\n        simpl; intuition congruence.\n\n        all: eauto.\n        all: try solve[ \n        eapply DiskAllocator.block_allocator_rep_inbounds_eq; \n        eauto; intros; repeat solve_bounds].\n        {\n    eapply DiskAllocator.block_allocator_rep_inbounds_eq.\n    2: intros; repeat solve_bounds.\n    eauto.\n  }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in H22; eauto.\n      eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in H17; eauto.\n      cleanup.\n      unfold same_for_user_except in *; cleanup.\n      eapply_fresh H16 in H6; eauto; cleanup.\n      unfold file_map_rep, file_rep in *; cleanup.\n      eapply_fresh H24 in H22; eauto; cleanup.\n      eapply_fresh H23 in H17; eauto; cleanup.\n      eauto.\n    }\n    \n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      unfold Inode.inode_rep, file_map_rep, file_rep, Inode.inode_map_rep in *; cleanup.\n      unfold Inode.inode_map_valid, Inode.inode_valid in *; cleanup.\n      eapply H23 in H22; cleanup; eauto.\n    }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      unfold Inode.inode_rep, file_map_rep, file_rep, Inode.inode_map_rep in *; cleanup.\n      unfold Inode.inode_map_valid, Inode.inode_valid in *; cleanup.\n      eapply H15 in H17; cleanup; eauto.\n  }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in H22 ; eauto.\n      cleanup.\n      unfold file_map_rep, file_rep in *; cleanup.\n      eapply_fresh H15 in H22; eauto; cleanup.\n      eapply Forall_forall; eauto; intros.\n      eapply In_nth in H23; cleanup.\n      eapply nth_error_Some in H23.\n      destruct_fresh (nth_error (Inode.block_numbers x7) x9); try congruence.\n      eapply_fresh H21 in D; cleanup.\n      unfold DiskAllocator.block_allocator_rep in *; cleanup.\n      eapply nth_error_nth in D.\n      rewrite H24 in D; subst.\n      eapply DiskAllocator.valid_bits_extract with (n:= a) in v0; eauto; cleanup.\n      split_ors; cleanup.\n      rewrite nth_seln_eq in H10; erewrite nth_error_nth'; eauto.\n      rewrite H19, H10; eauto.\n      all: try rewrite value_to_bits_length;\n      unfold DiskAllocatorParams.num_of_blocks in *;\n      pose proof DiskAllocatorParams.num_of_blocks_in_bounds; try lia.\n      destruct (Compare_dec.lt_dec a FSParameters.file_blocks_count); try lia.\n      rewrite e4 in H26; try congruence; try lia.\n      destruct (Compare_dec.lt_dec a FSParameters.file_blocks_count); try lia.\n      rewrite e4 in H26; try congruence; try lia.\n      setoid_rewrite D in H23; intuition.\n    }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in H17; eauto.\n      cleanup.\n      unfold file_map_rep, file_rep in *; cleanup.\n      eapply_fresh H12 in H17; eauto; cleanup.\n      eapply Forall_forall; eauto; intros.\n      eapply In_nth in H23; cleanup.\n      eapply nth_error_Some in H23.\n      destruct_fresh (nth_error (Inode.block_numbers x0) x9); try congruence.\n      eapply_fresh H21 in D; cleanup.\n      unfold DiskAllocator.block_allocator_rep in *; cleanup.\n      eapply nth_error_nth in D.\n      rewrite H24 in D; subst.\n      eapply DiskAllocator.valid_bits_extract with (n:= a) in v; eauto; cleanup.\n      split_ors; cleanup.\n      rewrite nth_seln_eq in H10; erewrite nth_error_nth'; eauto.\n      rewrite H14, H10; eauto.\n      all: try rewrite value_to_bits_length;\n      unfold DiskAllocatorParams.num_of_blocks in *;\n      pose proof DiskAllocatorParams.num_of_blocks_in_bounds; try lia.\n      destruct (Compare_dec.lt_dec a FSParameters.file_blocks_count); try lia.\n      rewrite e1 in H26; try congruence; try lia.\n      destruct (Compare_dec.lt_dec a FSParameters.file_blocks_count); try lia.\n      rewrite e1 in H26; try congruence; try lia.\n      setoid_rewrite D in H23; intuition.\n    }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      unfold Inode.inode_rep, file_map_rep, file_rep, Inode.inode_map_rep in *; cleanup.\n      unfold Inode.inode_map_valid, Inode.inode_valid in *; cleanup.\n      eapply H23 in H22; cleanup; eauto.\n    }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      unfold Inode.inode_rep, file_map_rep, file_rep, Inode.inode_map_rep in *; cleanup.\n      unfold Inode.inode_map_valid, Inode.inode_valid in *; cleanup.\n      eapply H15 in H17; cleanup; eauto.\n    }\n      }\n      {\n        eapply_fresh TS_free_all_blocks in H6.\n        logic_clean.\n        destruct x2; simpl in *; try solve [intuition congruence].\n        eapply_fresh free_all_blocks_finished_oracle_eq in H6.\n        2: apply H4.\n        eapply_fresh FileInnerSpecs.free_all_blocks_finished in H6; eauto.\n        eapply_fresh FileInnerSpecs.free_all_blocks_finished in H4.\n        cleanup; repeat split_ors; cleanup; try solve [intuition congruence].\n        {\n          eapply_fresh TS_free_inode in H12.\n          cleanup.\n          destruct x9; simpl in *; try solve [intuition congruence].\n          exists (Crashed s4); split.\n          repeat (econstructor; simpl; eauto).\n          simpl; eauto.\n          simpl; intuition congruence.\n          intuition.\n          {\n    \n    eapply inode_allocations_are_same_2.\n    5: eauto.\n    all: eauto.\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      unfold Inode.inode_rep in *; cleanup.\n      eexists; split.\n      eapply Inode.InodeAllocator.block_allocator_rep_inbounds_eq.\n      apply b0.\n      intros; repeat solve_bounds.\n      eauto.\n    }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      unfold Inode.inode_rep in *; cleanup.\n      eexists; split.\n      eapply Inode.InodeAllocator.block_allocator_rep_inbounds_eq.\n      apply b.\n      intros; repeat solve_bounds.\n      eauto.\n    }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      unfold Inode.inode_rep, \n      Inode.InodeAllocator.block_allocator_rep,\n      Inode.inode_map_rep in *; cleanup.\n      destruct (Compare_dec.lt_dec inum Inode.InodeAllocatorParams.num_of_blocks); eauto.\n      rewrite e5, e8 in H22; simpl in *; try lia; try congruence.\n    }\n  }\n        }\n        {\n          invert_exec.\n          exists (Crashed s3); split.\n          repeat (econstructor; simpl; eauto).\n          simpl; intuition congruence.\n        }\n        all: eauto.\n        all: try solve[ \n        eapply DiskAllocator.block_allocator_rep_inbounds_eq; \n        eauto; intros; repeat solve_bounds].\n        {\n    eapply DiskAllocator.block_allocator_rep_inbounds_eq.\n    2: intros; repeat solve_bounds.\n    eauto.\n  }\n  {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      unfold Inode.inode_rep, file_map_rep, file_rep, Inode.inode_map_rep in *; logic_clean.\n      unfold Inode.inode_map_valid, Inode.inode_valid in *; logic_clean.\n      eapply H18 in H17; cleanup; eauto.\n    }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      unfold Inode.inode_rep, file_map_rep, file_rep, Inode.inode_map_rep in *; logic_clean.\n      unfold Inode.inode_map_valid, Inode.inode_valid in *; logic_clean.\n      eapply H21 in H22; logic_clean; eauto.\n  }\n  {\n    eapply DiskAllocator.block_allocator_rep_inbounds_eq.\n    2: intros; repeat solve_bounds.\n    eauto.\n  }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in H22; eauto.\n      eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in H17 ; eauto.\n      logic_clean.\n      clear H6.\n      unfold same_for_user_except in *; cleanup_no_match.\n      eapply_fresh H16 in H15; eauto; cleanup_no_match.\n      unfold file_map_rep, file_rep in *; cleanup_no_match.\n      eapply_fresh H24 in H22; eauto; cleanup_no_match.\n      eapply_fresh H23 in H17; eauto; cleanup_no_match.\n      eauto.\n    }\n    \n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      clear H5.\n      unfold Inode.inode_rep, file_map_rep, file_rep, Inode.inode_map_rep in *; cleanup_no_match.\n      unfold Inode.inode_map_valid, Inode.inode_valid in *; cleanup_no_match.\n      eapply H23 in H22; cleanup; eauto.\n    }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      clear H6.\n      unfold Inode.inode_rep, file_map_rep, file_rep, Inode.inode_map_rep in *; cleanup_no_match.\n      unfold Inode.inode_map_valid, Inode.inode_valid in *; cleanup_no_match.\n      eapply H15 in H17; cleanup; eauto.\n  }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      clear H6.\n      eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in H22; eauto.\n      cleanup_no_match.\n      unfold file_map_rep, file_rep in *; cleanup_no_match.\n      eapply_fresh H15 in H22; eauto; cleanup_no_match.\n      eapply Forall_forall; eauto; intros.\n      eapply In_nth in H23; cleanup_no_match.\n      eapply nth_error_Some in H23.\n      destruct_fresh (nth_error (Inode.block_numbers x7) x10); try congruence.\n      eapply_fresh H21 in D; cleanup_no_match.\n      unfold DiskAllocator.block_allocator_rep in *; cleanup_no_match.\n      eapply nth_error_nth in D.\n      rewrite H24 in D; subst.\n      eapply DiskAllocator.valid_bits_extract with (n:= a) in v0; eauto; cleanup_no_match.\n      split_ors; cleanup_no_match.\n      rewrite nth_seln_eq in H10; erewrite nth_error_nth'; eauto.\n      rewrite H19, H10; eauto.\n      all: try rewrite value_to_bits_length;\n      unfold DiskAllocatorParams.num_of_blocks in *;\n      pose proof DiskAllocatorParams.num_of_blocks_in_bounds; try lia.\n      destruct (Compare_dec.lt_dec a FSParameters.file_blocks_count); try lia.\n      rewrite e4 in H26; try congruence; try lia.\n      destruct (Compare_dec.lt_dec a FSParameters.file_blocks_count); try lia.\n      rewrite e4 in H26; try congruence; try lia.\n      setoid_rewrite D in H23; intuition.\n    }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      clear H6.\n      eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in H17; eauto.\n      cleanup_no_match.\n      unfold file_map_rep, file_rep in *; cleanup_no_match.\n      eapply_fresh H9 in H17; eauto; cleanup_no_match.\n      eapply Forall_forall; eauto; intros.\n      eapply In_nth in H23; cleanup_no_match.\n      eapply nth_error_Some in H23.\n      destruct_fresh (nth_error (Inode.block_numbers x0) x10); try congruence.\n      eapply_fresh H21 in D; cleanup_no_match.\n      unfold DiskAllocator.block_allocator_rep in *; cleanup_no_match.\n      eapply nth_error_nth in D.\n      rewrite H24 in D; subst.\n      eapply DiskAllocator.valid_bits_extract with (n:= a) in v; eauto; cleanup_no_match.\n      split_ors; cleanup_no_match.\n      rewrite nth_seln_eq in H10; erewrite nth_error_nth'; eauto.\n      rewrite H14, H10; eauto.\n      all: try rewrite value_to_bits_length;\n      unfold DiskAllocatorParams.num_of_blocks in *;\n      pose proof DiskAllocatorParams.num_of_blocks_in_bounds; try lia.\n      destruct (Compare_dec.lt_dec a FSParameters.file_blocks_count); try lia.\n      rewrite e1 in H26; try congruence; try lia.\n      destruct (Compare_dec.lt_dec a FSParameters.file_blocks_count); try lia.\n      rewrite e1 in H26; try congruence; try lia.\n      setoid_rewrite D in H23; intuition.\n    }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      clear H6.\n      unfold Inode.inode_rep, file_map_rep, file_rep, Inode.inode_map_rep in *; cleanup_no_match.\n      unfold Inode.inode_map_valid, Inode.inode_valid in *; cleanup_no_match.\n      eapply H23 in H22; cleanup; eauto.\n    }\n    {\n      repeat cleanup_pairs;\n      repeat unify_invariants.\n      clear H6.\n      unfold Inode.inode_rep, file_map_rep, file_rep, Inode.inode_map_rep in *; cleanup_no_match.\n      unfold Inode.inode_map_valid, Inode.inode_valid in *; cleanup_no_match.\n      eapply H15 in H17; cleanup; eauto.\n    }\n      }\n    }\n    {\n      invert_exec.\n      eapply_fresh TS_get_all_block_numbers in H3; eauto.\n      logic_clean.\n      destruct x; simpl in *; try solve [intuition congruence].\n      eapply_fresh Inode.get_all_block_numbers_finished_oracle_eq in H3; eauto.\n      destruct o; simpl in *; try solve [intuition congruence].\n\n      exists (Crashed s3); split.\n      repeat (econstructor; simpl; eauto).\n      simpl; intuition congruence.\n\n      unfold files_inner_rep; eexists; eauto.\n      unfold files_inner_rep; eexists; eauto.\n    }\n  }\n}\nUnshelve.\nall: eauto.\nQed. \nOpaque delete_inner.\n\n\nTheorem Termination_Sensitive_delete:\n  forall u u' m inum ex,\n    Termination_Sensitive\n      u (delete inum) (delete inum) recover\n      AD_valid_state (AD_related_states u' ex)\n      (authenticated_disk_reboot_list m).\nProof.\n  Opaque change_owner_inner.\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  delete;\n  intros; cleanup; simpl in *.\n  destruct m; simpl in *.\n  {(**write finished **)\n   invert_exec.\n   eapply TS_auth_then_exec in H11; eauto.\n   {\n     cleanup.\n     destruct x1; simpl in *; try solve [intuition congruence].\n     eexists; econstructor_recovery.\n     eauto.\n   }\n   {\n     intros.\n     eapply_fresh TS_delete_inner in H7.\n     3: eauto.\n     3: eauto.\n     cleanup.\n     destruct ret1, x1; simpl in * ; try solve [intuition congruence].\n     {\n      eapply SameRetType.delete_inner_finished_oracle_eq in H7; eauto.\n      cleanup.\n      eexists.\n      intuition eauto; cleanup; eauto.\n     }\n     {\n      eexists.\n      intuition eauto; cleanup; eauto.\n     }\n     eauto.\n   }\n  }\n  {\n    invert_exec.\n    eapply_fresh TS_auth_then_exec in H14; eauto.\n   {\n     cleanup.\n     destruct x1; simpl in *; try solve [intuition congruence].\n     eapply_fresh FileSpecs.delete_crashed in H14; eauto.\n    eapply_fresh FileSpecs.delete_crashed in H1; eauto.\n    repeat split_ors; cleanup.\n    {\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 s, (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: eexists; econstructor_recovery; [|eauto]; eauto.\n     {\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   {\n      exfalso; eapply delete_crashed_exfalso; eauto.\n   }\n   {\n      exfalso; eapply delete_crashed_exfalso.\n      eapply same_for_user_except_symmetry. eauto.\n      all: eauto.\n   }\n   {\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 s, (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: eexists; econstructor_recovery; [|eauto]; eauto.\n     {\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         unfold same_for_user_except in *; cleanup.\n         split; intros. \n         unfold addrs_match_exactly in *; intros.\n         destruct (addr_dec a1 inum);\n         [repeat rewrite Mem.delete_eq; eauto; intuition congruence\n         |repeat rewrite Mem.delete_ne; eauto; intuition congruence].\n         split; intros.\n         {\n          destruct (addr_dec inum0 inum);\n          [rewrite Mem.delete_eq in H5, H16; eauto; cleanup\n         |rewrite Mem.delete_ne in H5, H16; eauto; cleanup].\n         }\n         {\n          destruct (addr_dec inum0 inum);\n          [rewrite Mem.delete_eq in H5, H4; eauto; cleanup\n         |rewrite Mem.delete_ne in H5, H4; eauto; cleanup].\n         }\n       }\n     }\n   }\n  }\n  {\n     intros.\n     eapply_fresh TS_delete_inner in H7; eauto.\n     cleanup.\n     destruct ret1, x1; simpl in * ; try solve [intuition congruence].\n     {\n      eapply SameRetType.delete_inner_finished_oracle_eq in H7; eauto.\n      cleanup.\n      eexists.\n      intuition eauto; cleanup; eauto.\n     }\n     {\n      eexists.\n      intuition eauto; cleanup; eauto.\n     }\n  }\n}\nUnshelve.\nall: eauto.\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/Storage/TerminationSensivitiy/FD_TS/TSDelete.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.29846698245383924}}
{"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 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  | Osingleconst: float32 -> 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  | Oaddsymbol: ident -> int -> 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 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\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_condition (x y: condition) : {x=y} + {x<>y}.\nProof.\n  generalize Int.eq_dec; intro.\n  assert (forall (x y: comparison), {x=y}+{x<>y}). decide equality.\n  decide equality.\nDefined.\n\n\nDefinition eq_operation (x y: operation): {x=y} + {x<>y}.\nProof.\n  generalize Int.eq_dec; intro.\n  generalize Float.eq_dec Float32.eq_dec; intros.\n  assert (forall (x y: ident), {x=y}+{x<>y}). exact peq.\n  generalize eq_condition; intro.\n  decide equality.\nDefined.\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.\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  | _, _ => 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.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  | 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  | 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  | _, _ => 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.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 _ => _ | 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  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  | 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  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  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  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... \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  repeat (destruct vl; auto). \n  repeat (destruct vl; auto). destruct (Val.maskzero_bool v i) as [[]|]; 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(** 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: int) : option addressing :=\n  match addr with\n  | Aindexed n => Some(Aindexed (Int.add n delta))\n  | Aindexed2 => None\n  | Aglobal s n => Some(Aglobal s (Int.add n delta))\n  | Abased s n => Some(Abased s (Int.add n delta))\n  | Ainstack n => Some(Ainstack (Int.add n 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 delta)).\nProof.\n  intros. 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. \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. auto. \n  rewrite Val.add_assoc. 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 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(** * 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 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 (Genv.symbol_address genv id ofs) (Genv.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 weak_valid_pointer_inj:\n  forall b1 ofs b2 delta,\n  f b1 = Some(b2, delta) ->\n  Mem.weak_valid_pointer m1 b1 (Int.unsigned ofs) = true ->\n  Mem.weak_valid_pointer m2 b2 (Int.unsigned (Int.add ofs (Int.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 (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 _ (Vsingle _) _ |- _ ] =>\n      inv H; InvInject\n  | [ H: val_inject _ (Vptr _ _) _ |- _ ] =>\n      inv H; InvInject\n  | [ H: Forall2 (val_inject _) nil _ |- _ ] =>\n      inv H; InvInject\n  | [ H: Forall2 (val_inject _) (_ :: _) _ |- _ ] =>\n      inv H; InvInject\n  | _ => idtac\n  end.\n\nLemma eval_condition_inj:\n  forall cond vl1 vl2 b,\n  Forall2 (val_inject 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.\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  Forall2 (val_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 Values.val_add_inject; auto.\n  apply Values.val_add_inject; auto.\n  apply Values.val_add_inject; auto.\n  inv H4; inv H2; simpl; auto. econstructor; eauto. \n    rewrite Int.sub_add_l. auto.\n    destruct (eq_block b1 b0); auto. subst. rewrite H1 in H0. inv H0. rewrite dec_eq_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 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; 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.\nQed.\n\nLemma eval_addressing_inj:\n  forall addr sp1 vl1 sp2 vl2 v1,\n  val_inject f sp1 sp2 ->\n  Forall2 (val_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    auto using Values.val_add_inject.\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 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 (Int.unsigned ofs) = true ->\n  Mem.weak_valid_pointer m2 b2 (Int.unsigned (Int.add ofs (Int.repr delta))) = true.\nProof.\n  intros. inv H0. rewrite Int.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 (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  Forall2 Val.lessdef 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_list_inject_lessdef. eauto. auto.\nQed.\n\nLemma eval_operation_lessdef:\n  forall sp op vl1 vl2 v1 m1 m2,\n  Forall2 Val.lessdef 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 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_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  Forall2 Val.lessdef 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 (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 meminj_preserves_symbol; 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  Forall2 (val_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.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  Forall2 (val_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  Forall2 (val_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.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\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      is_rlw_mask_rec m (rlw_transition s (Z.odd x)) (Z.div2 x)\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": "robbertkrebbers", "repo": "compcert", "sha": "524c26591e884a3676a5fbef77d8c79193955b82", "save_path": "github-repos/coq/robbertkrebbers-compcert", "path": "github-repos/coq/robbertkrebbers-compcert/compcert-524c26591e884a3676a5fbef77d8c79193955b82/powerpc/Op.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.29846698245383924}}
{"text": "Require Import Coq.Sets.Constructive_sets.\nRequire Import Definitions.\nRequire Import Operational_Semantics.\nRequire Import Contracts_Subst.\n\n\n\n\n\n\n\n(*---Well-Formedness of Executions *)\nAxiom FW: forall (Ex:Exec), (WF1 Ex) ->(WF2 Ex) ->(WF3 Ex) ->(WF4 Ex) ->(WF5 Ex) ->(WF6 Ex)-> (WF7 Ex) ->(WF Ex). \nAxiom WFhelp: forall (Ex:Exec), (WF Ex)->(WF1 Ex)/\\(WF2 Ex)/\\(WF3 Ex)/\\(WF4 Ex)/\\(WF5 Ex)/\\(WF6 Ex)/\\(WF7 Ex).\n\n\n\n(*---Freshness of the Newly Generated Effect *)\nAxiom Freshness: forall (Θ:Store)(ex1 ex2:Exec) (opk:op_key)(eff:Effect)(r:ReplID),  \n                   [Θ|-ex1, opk ~r~> ex2, eff] -> forall r, (dom Θ r)-> ~ (Θ r) eff.\nAxiom CorrectFreshness: forall(Θ:Store)(ex1 ex2:Exec)(opk:op_key)(eff:Effect)(r:ReplID), \n                          [Θ|-ex1, opk ~r~> ex2, eff] -> ~ (ex1-A) eff.\n\n\n(*---The Definition of Equality of two Session Soups *)\nAxiom  Sess_Equal : forall (S S':SessSoup), S=S' <-> forall (I:Soup_Ing), (In Soup_Ing S I <-> In Soup_Ing S' I).\n\n\n(*---Trivial Facts About Relations*)\nAxiom sameobj_trans: forall (Ex:Exec)(a b c: Effect), Ex-sameobj a b -> Ex-sameobj b c -> Ex-sameobj a c.\nAxiom Sameobj_Def: forall  (Θ:Store) (Ex Ex':Exec)(opk:op_key) (η:Effect) (r:ReplID) (a b: Effect),\n                     [Θ |- Ex, opk ~r~> Ex', η] -> Ex-A a -> Ex-A b -> Ex-sameobj a b.\nAxiom SO_Seq_General : forall (Ex:Exec) (a b:Effect), (Ex-so a b) <-> (lt (seq a) (seq b)). \n\n\n\n(*---Relating Domain of the Relations to the Universe of Effects*)\nAxiom So_Domain :      forall (Ex:Exec)(a:Effect), ((Rel_dom Ex-so a)      -> (Ex-A a)).\nAxiom Vis_Domain :     forall (Ex:Exec)(a:Effect), ((Rel_dom Ex-vis a)     -> (Ex-A a)).\nAxiom Hbo_Domain :     forall (Ex:Exec)(a:Effect), ((Rel_dom Ex-hbo a)     -> (Ex-A a)).\nAxiom Sameobj_Domain : forall (Ex:Exec)(a:Effect), ((Rel_dom Ex-sameobj a) -> (Ex-A a)).\n\n(*---The Conclusion from Equality of Soup Ingredients*)\nAxiom Seq_Uniq : forall (i i': SeqNo)(s s': SessID)(σ σ' : session), (<<s , i , σ >>) = (<<s', i' , σ' >>) -> i=i'.\n\n\n(*--- So only relates effects from the same session*)\nAxiom SO_SameSession : forall (Ex:Exec)(eff eff':Effect), Ex-so eff eff' -> (eff.(sess) = eff'.(sess)).\n\n(*---Decidability of Membership of a Soup *)\nAxiom Soup_comp : forall (Ex:Exec)(eff:Effect), (Ex-A eff)\\/(~ Ex-A eff).\n\n\n(*---Claimed in the Paper *)\n(*3 equal statements to the acyclicity of hb*)\nAxiom PaperH8: forall (Ex:Exec)(eff:Effect), ~ (Ex-hb eff eff)-> ((~Ex-vis eff eff) /\\ (~ Ex-so eff eff)).\n\nAxiom PaperH8II : forall (Ex:Exec)(eff eff': Effect), ~((Ex-vis eff eff')/\\ (Ex-so eff' eff)).\n\nAxiom PaperH8III : forall (Ex:Exec), \n                     (forall (eff:Effect), Ex-A eff -> ~ Ex-vis eff eff) ->\n                     (forall (eff:Effect), Ex-A eff -> ~ Ex-so  eff eff) ->\n                     (forall (eff eff':Effect),Ex-A eff -> Ex-A eff' ->  ~((Ex-vis eff eff')/\\ (Ex-so eff' eff))) ->\n                     (forall (eff:Effect),~(Ex-hb eff eff)).\n\n\n(*---Equality if Effect Variables is Reflexive*)\nAxiom  Eff_Equi_refl : forall a,  Eff_Equi a a.\n\n(*---Relating Error term, to the domain of the Stores*)\nAxiom error_not_domain: forall (r:ReplID)(t:Store),  (t r = St_Dom_Error) <-> (~(dom t) r).\n\n(*---Equaility of ReplIDs is decidable*)\nAxiom ReplID_Equality_Decidable: forall (r r':ReplID), (r=r') \\/ (r<>r').\n\n\n\n(*************************************************************************************************************************)\n(*=============================These Were Axioms Before, But Now Are Replaced with Other Axioms and Are Trivially Proved *)\n\nLemma  SO_NewEff: forall (Θ: Store)(Ex Ex':Exec) (opk:op_key)(η:Effect)(r:ReplID),\n                    [Θ|-Ex, opk ~r~> Ex', η] -> (forall a:Effect, Θ r a -> ~ Ex-so η a).\nProof. intuition. apply CorrectFreshness in H. apply WF_Relation with (a:= η) (b:=a) in H1; destruct H1.\n       apply So_Domain in H1; auto.\nQed.\n\nRequire Import Omega.\n\nLemma SessionOrder : forall (Ex:Exec)(eff eff':Effect), Ex-so eff eff' -> ((eff.(sess) = eff'.(sess))/\\ ((eff.(seq))+1 <= (eff'.(seq)))).\nProof.\n  intros Ex a b Hso. split.\n  apply SO_SameSession in Hso; auto. apply SO_Seq_General in Hso. intuition.\nQed.\n\nLemma  SO_Seq : forall (Ex:Exec)(a b c:Effect), Ex-so a b -> seq b = seq c - 1 -> Ex-so a c.\nProof.\n  intros Ex a b c. intros Hso Heq. apply SO_Seq_General. apply SO_Seq_General in Hso. intuition.\nQed.\n\nLemma SO_SeqII' : forall (Ex:Exec)(a b :Effect), (seq b>0)->seq a = seq b -1  -> Ex-so a b.\nProof.\n  intros. apply SO_Seq_General. omega.\nQed.\n\nLemma Eneq_nat_cont : forall i:SeqNo, (i>0)->(i=i-1)\\/(i=i+1) -> False.\nProof. intros. omega.\nQed.\n\nLemma natSeq: forall ss:SeqNo, ~(ss+1 <= (ss-1)).\nProof.\n  intros. omega.\nQed.\n\nLemma  SO_SeqIII : forall (Ex:Exec)(a b c:Effect), Ex-so a b -> Ex-so b c  -> Ex-so a c.\nProof.\n  intros.\n  apply SO_Seq_General. apply SO_Seq_General in H. apply SO_Seq_General in H0. omega.\nQed.\n\n\nLemma Relation_Dom : forall (Ex:Exec) (eff:Effect), (~Ex-A eff ) -> (~Ex-so eff eff).\n  Proof.\n    intuition. apply WF_Relation with (a:=eff)(b:=eff)(r:=Ex-so) in H0. destruct H0.\n    apply So_Domain in H1; auto.\nQed.\n\n", "meta": {"author": "Kiarahmani", "repo": "Quelea_Coq_Imp", "sha": "8b668004d60bcd7e9bc46da7de3157897a58bdf9", "save_path": "github-repos/coq/Kiarahmani-Quelea_Coq_Imp", "path": "github-repos/coq/Kiarahmani-Quelea_Coq_Imp/Quelea_Coq_Imp-8b668004d60bcd7e9bc46da7de3157897a58bdf9/Axioms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.29846698245383924}}
{"text": "Require Import List.\nRequire Import PeanoNat.\nRequire Import Orders.\nRequire Import MSetList.\n\nRequire Import sflib.\n\nRequire Import DataStructure.\nRequire Import Basic.\nRequire Import Loc.\n\nSet Implicit Arguments.\n\nRequire Import Integers. \nModule Const := Int.\n\nLemma const_neq_sym:\n  forall (x y:Const.t),\n    x <> y <-> y <> x.\nProof. \n  intros.\n  split.\n  - intro. intro. rewrite H0 in H. contradiction. \n  - intro. intro. rewrite H0 in H. contradiction. \nQed.\n\nLemma loc_neq_sym:\n  forall (x y:Loc.t),\n    x <> y <-> y <> x.\nProof. \n  intros.\n  split.\n  - intro. intro. rewrite H0 in H. contradiction. \n  - intro. intro. rewrite H0 in H. contradiction. \nQed.\n\nModule Ordering.\n  Inductive t :=\n  | plain\n  | relaxed\n  | strong_relaxed\n  | acqrel\n  | seqcst\n  .\n\n  (* loc's access atomicity *)\n  Inductive atomicity := \n  | atomic \n  | nonatomic\n  .\n\n  Definition mem_ord_match (ord: t) (o: atomicity): Prop := \n    match o with \n    | nonatomic => ord = plain \n    | atomic => (ord = acqrel) \\/ (ord = relaxed) \\/ (ord = strong_relaxed)\n    end\n  .\n\n  (** [LocOrdMap]: records predefined atomicity for each location. \n      atomic: allow relaxed or stronger access.\n      nonatomic: allow plain access. \n  *)\n  Definition LocOrdMap := Loc.t -> atomicity.\n\n  Definition le (lhs rhs:t): bool :=\n    match lhs, rhs with\n    | plain, _ => true\n    | _, plain => false\n\n    | relaxed, _ => true\n    | _, relaxed => false\n\n    | strong_relaxed, _ => true\n    | _, strong_relaxed => false\n\n    | acqrel, _ => true\n    | _, acqrel => false\n\n    | seqcst, seqcst => true\n    end.\n  Global Opaque le.\n\n  Global Program Instance le_PreOrder: PreOrder le.\n  Next Obligation.\n    ii. destruct x; auto.\n  Qed.\n  Next Obligation.\n    ii. destruct x, y, z; auto.\n  Qed.\n  Hint Resolve le_PreOrder_obligation_2.\n\n  Definition join (lhs rhs:t): t :=\n    match lhs, rhs with\n    | plain, _ => rhs\n    | _, plain => lhs\n\n    | relaxed, _ => rhs\n    | _, relaxed => lhs\n\n    | strong_relaxed, _ => rhs\n    | _, strong_relaxed => lhs\n\n    | acqrel, _ => rhs\n    | _, acqrel => lhs\n\n    | seqcst, _ => rhs\n    end.\n  \n  Lemma join_comm lhs rhs: join lhs rhs = join rhs lhs.\n  Proof. destruct lhs, rhs; ss. Qed.\n\n  Lemma join_assoc a b c: join (join a b) c = join a (join b c).\n  Proof. destruct a, b, c; ss. Qed.\n\n  Lemma join_l lhs rhs:\n    le lhs (join lhs rhs).\n  Proof. destruct lhs, rhs; ss. Qed.\n\n  Lemma join_r lhs rhs:\n    le rhs (join lhs rhs).\n  Proof. destruct lhs, rhs; ss. Qed.\n\n  Lemma join_spec lhs rhs o\n        (LHS: le lhs o)\n        (RHS: le rhs o):\n    le (join lhs rhs) o.\n  Proof. destruct lhs, rhs; ss. Qed.\n\n  Lemma join_cases lhs rhs:\n    join lhs rhs = lhs \\/ join lhs rhs = rhs.\n  Proof. destruct lhs, rhs; auto. Qed.\nEnd Ordering.\n\n\n(* NOTE (syscall): In fact, syscalls may change the memory, on the\n * contrary to what is currently defined.\n *)\n(* NOTE (syscall): we disallow syscalls in the validation of the\n * consistency check, as syscall's results are not predictable.\n *)\nModule Event.\n  Structure t := mk {\n    output: Const.t;\n    (* inputs: list Const.t;   *)\n  }.\nEnd Event.\n\n(** ** Observable event *)\n(** Observable event includes:\n    - [output]: for system call;\n    - [abort]: for program abort;\n    - [done]: for program done. *)\nModule VisibleEvent.\n  Inductive t :=\n  | out (e: Event.t)\n  | abort \n  | done.\nEnd VisibleEvent.\n\nModule AuxEvent. \n  Inductive t := \n  | na \n  | prc \n  | atm\n  | out (e: Event.t)\n  | sw\n  | tterm \n  .\nEnd AuxEvent.\n\n(** ** Program transition event (or machine evet) *)\n(** Program transition event includes:\n    - [silent]: silent step;\n    - [switch]: thread switching;\n    - [syscall]: system call (observable event). *)\nModule MachineEvent.\n  Inductive t :=\n  | silent\n  | switch\n  | syscall (e: Event.t)\n  .\nEnd MachineEvent.\n\n\nModule ProgramEvent.\n  Inductive t :=\n  | silent\n  | read (loc:Loc.t) (val:Const.t) (ord:Ordering.t)\n  | write (loc:Loc.t) (val:Const.t) (ord:Ordering.t)\n  | update (loc:Loc.t) (valr valw:Const.t) (ordr ordw:Ordering.t)\n  | fence (ordr ordw:Ordering.t)\n  | syscall (e:Event.t)\n  .\n\n  Definition is_reading (e:t): option (Loc.t * Const.t * Ordering.t) :=\n    match e with\n    | read loc val ord => Some (loc, val, ord)\n    | update loc valr _ ordr _ => Some (loc, valr, ordr)\n    | _ => None\n    end.\n\n  Definition is_writing (e:t): option (Loc.t * Const.t * Ordering.t) :=\n    match e with\n    | write loc val ord => Some (loc, val, ord)\n    | update loc _ valw _ ordw => Some (loc, valw, ordw)\n    | _ => None\n    end.\n\n  Definition is_updating (e:t): option (Loc.t * Const.t * Ordering.t) :=\n    match e with\n    | update loc valr _ ordr _ => Some (loc, valr, ordr)\n    | _ => None\n    end.\n\nEnd ProgramEvent.\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/lang/Event.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757645879592641, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2984669766856854}}
{"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 Reals.\nRequire Import trajectory_const.\nRequire Import trajectory_def.\nRequire Import constants.\nRequire Import ycngftys.\nRequire Import ycngstys.\nRequire Import ails_def.\nRequire Import math_prop.\nRequire Import tau.\nRequire Import ails.\nRequire Import trajectory.\nRequire Import measure2state.\nRequire Import ails_trajectory.\n\nUnset Standard Proposition Elimination Names.\n\nLemma AlertRange_pos : (0 < AlertRange)%R.\nunfold AlertRange in |- *; prove_sup.\nQed.\n\nLemma conflict_beta_theta :\n forall (intr : Trajectory) (evad : EvaderTrajectory) (T : TimeT),\n h intr = V ->\n (MinDistance T <= l intr evad T)%R ->\n (l intr evad T <= MaxDistance T)%R ->\n Omega (beta intr evad T + thetat intr 0) = false ->\n conflict intr evad T = true ->\n (beta intr evad T + thetat intr 0 <= MinBeta)%R \\/\n (2 * PI - MinBeta < beta intr evad T + thetat intr 0)%R.\nProof with trivial.\nintros intr evad T hyp_intr; intros; set (beta_p := beta intr evad T) in H1;\n set (thetat_p := thetat intr) in H1; set (l_p := l intr evad T) in H, H0;\n set (conflict_p := conflict intr evad) in H2;\nassert (hyp1 : r_V = r_vi intr)...\nunfold r_V, r_vi in |- *; unfold vi in |- *; rewrite hyp_intr...\nassert (hyp2 : rho_V = rho_vi intr)...\nunfold rho_V, rho_vi in |- *; unfold vi in |- *; rewrite hyp_intr...\ncase (Rtotal_order (beta_p + thetat_p 0%R) MinBeta); intro...\nleft; left...\nelim H3; intro...\nleft; right...\ncase (Rlt_le_dec (2 * PI - MinBeta) (beta_p + thetat_p 0%R)); intro...\nright...\nassert (H5 := conflict_T_e_0 intr evad T H2)...\ncut (0 <= e intr evad T T)%R...\ncut (0 <= ConflictRange)%R...\nintros; assert (H8 := Rsqr_incr_1 (e intr evad T T) ConflictRange H5 H7 H6);\n unfold e in H8; rewrite isometric_evader in H8; rewrite Rsqr_sqrt in H8...\nchange (MinBeta < beta_p + thetat_p 0)%R in H4;\n cut\n  ((beta_p + thetat_p 0 < PI / 2)%R \\/ (3 * (PI / 2) < beta_p + thetat_p 0)%R)...\nintro; elim H9; intro...\ncut\n (l_p * sin (beta_p + thetat_p 0) + r_V * (cos (rho_V * T) - 1) <=\n  yp intr evad T T)%R...\ncut\n (r_V * sin (rho_V * T) - l_p * cos (beta_p + thetat_p 0) <= xp intr evad T T)%R...\nintros;\n generalize\n  (Math_prop_no_conflict_1 (beta_p + thetat_p 0%R) l_p \n     (xp intr evad T T) (yp intr evad T T) T H H0\n     (Rlt_le MinBeta (beta_p + thetat_p 0%R) H4)\n     (Rlt_le (beta_p + thetat_p 0%R) (PI / 2) H10) H12 H11); \n intro;\n generalize\n  (Rlt_le_trans (Rsqr ConflictRange)\n     (Rsqr (xp intr evad T T) + Rsqr (yp intr evad T T)) \n     (Rsqr ConflictRange) H13 H8); intro;\n elim (Rlt_irrefl (Rsqr ConflictRange) H14)...\nrewrite hyp1; rewrite hyp2...\napply (xpt_PI intr evad T)...\nleft; apply Rlt_le_trans with MinT; [ apply MinT_is_pos | apply (cond_1 T) ]...\nrewrite <- hyp2; left; apply Rlt_trans with (PI / 2)%R...\napply rho_t_PI2...\napply PI2_Rlt_PI...\nrewrite hyp1; rewrite hyp2; cut (0 <= T)%R...\ncut (rho_vi intr * T <= PI / 2)%R...\nintros; generalize (ypt_PI2 intr evad T T H12 H11); intro...\nelim H13; intros...\nrewrite <- hyp2; left; apply rho_t_PI2...\nleft; apply Rlt_le_trans with MinT; [ apply MinT_is_pos | apply (cond_1 T) ]...\ncut\n (yp intr evad T T <=\n  l_p * sin (beta_p + thetat_p 0) - r_V * (cos (rho_V * T) - 1))%R...\ncut\n (r_V * sin (rho_V * T) - l_p * cos (beta_p + thetat_p 0) <= xp intr evad T T)%R...\nintros;\n generalize\n  (Math_prop_no_conflict_2 (beta_p + thetat_p 0%R) l_p \n     (xp intr evad T T) (yp intr evad T T) T H H0\n     (Rlt_le (3 * (PI / 2)) (beta_p + thetat_p 0%R) H10) r H12 H11); \n intro...\nelim\n (Rlt_irrefl (Rsqr ConflictRange)\n    (Rlt_le_trans (Rsqr ConflictRange)\n       (Rsqr (xp intr evad T T) + Rsqr (yp intr evad T T))\n       (Rsqr ConflictRange) H13 H8))...\nrewrite hyp1; rewrite hyp2; apply (xpt_PI intr evad T)...\nleft; apply Rlt_le_trans with MinT; [ apply MinT_is_pos | apply (cond_1 T) ]...\nrewrite <- hyp2; left; apply Rlt_trans with (PI / 2)%R...\napply rho_t_PI2...\napply PI2_Rlt_PI...\nrewrite hyp1; rewrite hyp2; cut (0 <= T)%R...\ncut (rho_vi intr * T <= PI / 2)%R...\nintros; generalize (ypt_PI2 intr evad T T H12 H11); intro; elim H13; intros...\nrewrite <- hyp2; left; apply rho_t_PI2...\nleft; apply Rlt_le_trans with MinT; [ apply MinT_is_pos | apply (cond_1 T) ]...\ncut (Omega (beta_p + thetat_p 0%R) = false)...\nunfold Omega in |- *; case (Rle_dec (PI / 2) (beta_p + thetat_p 0%R)); intro...\ncase (Rle_dec (beta_p + thetat_p 0%R) (3 * (PI / 2))); intros...\nelim diff_true_false...\nright; auto with real...\nintro; left; auto with real...\napply Rplus_le_le_0_compat; apply Rle_0_sqr...\nunfold ConflictRange in |- *; left; prove_sup...\nunfold e in |- *; apply sqrt_positivity; apply Rsqr_evader_distance_pos...\nQed.\n\nLemma alarm_NOT_Omega_T :\n forall (intr : Trajectory) (evad : EvaderTrajectory) (T : TimeT),\n h intr = V ->\n h (tr evad) = V ->\n (MinDistance T <= l intr evad T)%R ->\n (l intr evad T <= MaxDistance T)%R ->\n Omega (beta intr evad T + thetat intr 0) = false ->\n conflict intr evad T = true ->\n (RR (measure2state intr 0) (measure2state (tr evad) 0) T <= AlertRange)%R.\nProof with trivial.\nintros intr evad T hyp_intr hyp_evad; intros; apply Rsqr_incr_0_var...\nrewrite R_T...\ngeneralize (conflict_beta_theta intr evad T hyp_intr H H0 H1 H2); intro;\n elim H3; intro...\ncut (0 <= beta intr evad T + thetat intr 0)%R...\nintro;\n apply\n  (Math_prop_alarm_1 (beta intr evad T + thetat intr 0) \n     (l intr evad T) T H H0 H5 H4)...\ngeneralize (beta_def intr evad T); intro; decompose [and] H5; intros...\ncut (beta intr evad T + thetat intr 0 <= 2 * PI)%R...\nintro;\n apply\n  (Math_prop_alarm_2 (beta intr evad T + thetat intr 0) \n     (l intr evad T) T H H0\n     (Rlt_le (2 * PI - MinBeta) (beta intr evad T + thetat intr 0) H4))...\ngeneralize (beta_def intr evad T); intro; decompose [and] H5; intros; left...\n(*Rewrite hyp_evad.*)\nleft; apply AlertRange_pos...\nQed.\n\nLemma alarm_NOT_Omega_tau :\n forall (intr : Trajectory) (evad : EvaderTrajectory) (T : TimeT),\n h intr = V ->\n h (tr evad) = V ->\n (MinDistance T <= l intr evad T)%R ->\n (l intr evad T <= MaxDistance T)%R ->\n Omega (beta intr evad T + thetat intr 0) = false ->\n conflict intr evad T = true ->\n (0 < tau (measure2state intr 0) (measure2state (tr evad) 0) 0)%R ->\n (RR (measure2state intr 0) (measure2state (tr evad) 0)\n    (tau (measure2state intr 0) (measure2state (tr evad) 0) 0) <= AlertRange)%R.\nProof with trivial.\nintros intr evad T hyp_intr hyp_evad; intros;\n apply\n  Rle_trans with (RR (measure2state intr 0) (measure2state (tr evad) 0) T)...\ngeneralize\n (derivative_eq_zero_min (measure2state intr 0) (measure2state (tr evad) 0) 0\n    T); repeat rewrite Rplus_0_l; intro...\napply (alarm_NOT_Omega_T intr evad T hyp_intr hyp_evad H H0 H1 H2)...\nQed.\n\nLemma alarm_NOT_Omega_AlertTime :\n forall (intr : Trajectory) (evad : EvaderTrajectory) (T : TimeT),\n h intr = V ->\n h (tr evad) = V ->\n (MinDistance T <= l intr evad T)%R ->\n (l intr evad T <= MaxDistance T)%R ->\n Omega (beta intr evad T + thetat intr 0) = false ->\n conflict intr evad T = true ->\n (AlertTime < tau (measure2state intr 0) (measure2state (tr evad) 0) 0)%R ->\n (RR (measure2state intr 0) (measure2state (tr evad) 0) AlertTime <=\n  AlertRange)%R.\nProof with trivial.\nintros intr evad T hyp_intr hyp_evad; intros;\n apply\n  Rle_trans with (RR (measure2state intr 0) (measure2state (tr evad) 0) T)...\nrewrite <- (Rplus_0_l AlertTime); rewrite <- (Rplus_0_l T);\n apply asymptotic_decrease_tau...\nleft...\nunfold AlertTime in |- *; apply Rle_trans with MaxT...\napply (cond_2 T)...\nunfold MaxT in |- *; left; prove_sup...\napply (alarm_NOT_Omega_T _ _ _ hyp_intr hyp_evad H H0 H1 H2)...\nQed.\n\nLemma chktrack_NOT_Omega_trkrate_eq_0 :\n forall (intr : Trajectory) (evad : EvaderTrajectory) (T : TimeT),\n h intr = V ->\n h (tr evad) = V ->\n (MinDistance T <= l intr evad T)%R ->\n (l intr evad T <= MaxDistance T)%R ->\n Omega (beta intr evad T + thetat intr 0) = false ->\n conflict intr evad T = true ->\n (0 < tau (measure2state intr 0) (measure2state (tr evad) 0) 0)%R ->\n chktrack (measure2state intr 0) (measure2state (tr evad) 0) 0.\nProof with trivial.\nintros intr evad T hyp_intr hyp_evad; intros; unfold chktrack in |- *;\n case (Rle_dec (tau (measure2state intr 0) (measure2state (tr evad) 0) 0) 0);\n intro...\nelim\n (Rlt_irrefl 0\n    (Rlt_le_trans 0\n       (tau (measure2state intr 0) (measure2state (tr evad) 0) 0) 0 H3 r))...\nrewrite Rplus_0_l;\n case\n  (Rlt_dec AlertTime\n     (tau (measure2state intr 0) (measure2state (tr evad) 0) 0)); \n intro...\napply (alarm_NOT_Omega_AlertTime intr evad T)...\napply (alarm_NOT_Omega_tau intr evad T)...\nQed.\n\n(**************************************************************)\n(************************** THEOREM ***************************)\n(**************************************************************)\n\nTheorem ails_alarm_tau_gt0 :\n forall (intr : Trajectory) (evad : EvaderTrajectory) (T : TimeT),\n h intr = V ->\n h (tr evad) = V ->\n (MinDistance T <= l intr evad T)%R ->\n (l intr evad T <= MaxDistance T)%R ->\n Omega (beta intr evad T + thetat intr 0) = false ->\n (0 < tau (measure2state intr 0) (measure2state (tr evad) 0) 0)%R ->\n conflict intr evad T = true ->\n ails_alert (measure2state intr 0) (measure2state (tr evad) 0).\nProof with trivial.\nintros intr evad T hyp_intr hyp_evad; intros; unfold ails_alert in |- *;\n case (Req_EM_var (trkrate (bank (measure2state intr 0))) 0); \n intro...\napply (chktrack_NOT_Omega_trkrate_eq_0 intr evad T)...\ncase (Rle_dec 3 (trkrate (bank (measure2state intr 0)))); intro...\nunfold arc_loop in |- *; rewrite mod_eq_0...\ncase (Rlt_le_dec 0 (trkrate (bank (measure2state intr 0)))); intro...\nunfold INR in |- *; repeat rewrite Rmult_0_l; repeat rewrite Rmult_0_r;\n repeat rewrite Rplus_0_r; unfold intruderSpeed in |- *;\n replace (v V) with 250%R...\ncut\n (let z := 250%R in\n  mkState\n    (xt (measure2state intr 0) +\n     Rsqr z / (g * tand (bank (measure2state intr 0))) *\n     (sind (heading (measure2state intr 0)) -\n      sind (heading (measure2state intr 0))))\n    (yt (measure2state intr 0) +\n     Rsqr z / (g * tand (bank (measure2state intr 0))) *\n     (cosd (heading (measure2state intr 0)) -\n      cosd (heading (measure2state intr 0))))\n    (heading (measure2state intr 0)) (bank (measure2state intr 0)) =\n  measure2state intr 0)...\nintro; rewrite H4...\ncut\n (mkState (xt (measure2state (tr evad) 0)) (yt (measure2state (tr evad) 0))\n    (heading (measure2state (tr evad) 0)) (bank (measure2state (tr evad) 0)) =\n  measure2state (tr evad) 0)...\nintro; rewrite H5...\napply (chktrack_NOT_Omega_trkrate_eq_0 intr evad T)...\nunfold Rminus in |- *; repeat rewrite Rplus_opp_r; repeat rewrite Rmult_0_r;\n repeat rewrite Rplus_0_r...\nunfold INR in |- *; repeat rewrite Rmult_0_l; repeat rewrite Rmult_0_r;\n repeat rewrite Rplus_0_r; unfold Rminus in |- *; repeat rewrite Rplus_opp_r;\n unfold Rdiv in |- *; repeat rewrite Rmult_0_r; repeat rewrite Rplus_0_r;\n apply (chktrack_NOT_Omega_trkrate_eq_0 intr evad T)...\ncase (Rle_dec (3 / 2) (trkrate (bank (measure2state intr 0)))); intro...\nunfold arc_loop in |- *; rewrite mod_eq_0;\n case (Rlt_le_dec 0 (trkrate (bank (measure2state intr 0)))); \n intro...\nrepeat rewrite Rmult_0_l; repeat rewrite Rmult_0_r; repeat rewrite Rplus_0_r;\n unfold Rminus in |- *; repeat rewrite Rplus_opp_r; \n unfold Rdiv in |- *; repeat rewrite Rmult_0_r; repeat rewrite Rplus_0_r;\n apply (chktrack_NOT_Omega_trkrate_eq_0 intr evad T)...\nrepeat rewrite Rmult_0_l; repeat rewrite Rmult_0_r; repeat rewrite Rplus_0_r;\n unfold Rminus in |- *; repeat rewrite Rplus_opp_r; \n unfold Rdiv in |- *; repeat rewrite Rmult_0_r; repeat rewrite Rplus_0_r;\n apply (chktrack_NOT_Omega_trkrate_eq_0 intr evad T)...\ncase (Rle_dec (3 / 4) (trkrate (bank (measure2state intr 0)))); intro...\nunfold arc_loop in |- *; rewrite mod_eq_0;\n case (Rlt_le_dec 0 (trkrate (bank (measure2state intr 0)))); \n intro...\nrepeat rewrite Rmult_0_l; repeat rewrite Rmult_0_r; repeat rewrite Rplus_0_r;\n unfold Rminus in |- *; repeat rewrite Rplus_opp_r; \n unfold Rdiv in |- *; repeat rewrite Rmult_0_r; repeat rewrite Rplus_0_r;\n apply (chktrack_NOT_Omega_trkrate_eq_0 intr evad T)...\nrepeat rewrite Rmult_0_l; repeat rewrite Rmult_0_r; repeat rewrite Rplus_0_r;\n unfold Rminus in |- *; repeat rewrite Rplus_opp_r; \n unfold Rdiv in |- *; repeat rewrite Rmult_0_r; repeat rewrite Rplus_0_r;\n apply (chktrack_NOT_Omega_trkrate_eq_0 intr evad T)...\nunfold arc_loop in |- *; rewrite mod_eq_0;\n case (Rlt_le_dec 0 (trkrate (bank (measure2state intr 0)))); \n intro...\nrepeat rewrite Rmult_0_l; repeat rewrite Rmult_0_r; repeat rewrite Rplus_0_r;\n unfold Rminus in |- *; repeat rewrite Rplus_opp_r; \n unfold Rdiv in |- *; repeat rewrite Rmult_0_r; repeat rewrite Rplus_0_r;\n apply (chktrack_NOT_Omega_trkrate_eq_0 intr evad T)...\nrepeat rewrite Rmult_0_l; repeat rewrite Rmult_0_r; repeat rewrite Rplus_0_r;\n unfold Rminus in |- *; repeat rewrite Rplus_opp_r; \n unfold Rdiv in |- *; repeat rewrite Rmult_0_r; repeat rewrite Rplus_0_r;\n apply (chktrack_NOT_Omega_trkrate_eq_0 intr evad T)...\nQed.\n", "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/alarm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.29843553914637855}}
{"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 Unknown *)\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 Acq := unknown_set \"Acq\".\nDefinition AcqRel := unknown_set \"AcqRel\".\nDefinition Fence_r_r := unknown_set \"Fence.r.r\".\nDefinition Fence_r_rw := unknown_set \"Fence.r.rw\".\nDefinition Fence_r_w := unknown_set \"Fence.r.w\".\nDefinition Fence_rw_r := unknown_set \"Fence.rw.r\".\nDefinition Fence_rw_rw := unknown_set \"Fence.rw.rw\".\nDefinition Fence_rw_w := unknown_set \"Fence.rw.w\".\nDefinition Fence_tso := unknown_set \"Fence.tso\".\nDefinition Fence_w_r := unknown_set \"Fence.w.r\".\nDefinition Fence_w_rw := unknown_set \"Fence.w.rw\".\nDefinition Fence_w_w := unknown_set \"Fence.w.w\".\nDefinition Rel := unknown_set \"Rel\".\nDefinition Sc := unknown_set \"Sc\".\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 fence_r_r := [R] ⋅ (fencerel Fence_r_r ⋅ [R]).\nDefinition fence_r_w := [R] ⋅ (fencerel Fence_r_w ⋅ [W]).\nDefinition fence_r_rw := [R] ⋅ (fencerel Fence_r_rw ⋅ [M]).\nDefinition fence_w_r := [W] ⋅ (fencerel Fence_w_r ⋅ [R]).\nDefinition fence_w_w := [W] ⋅ (fencerel Fence_w_w ⋅ [W]).\nDefinition fence_w_rw := [W] ⋅ (fencerel Fence_w_rw ⋅ [M]).\nDefinition fence_rw_r := [M] ⋅ (fencerel Fence_rw_r ⋅ [R]).\nDefinition fence_rw_w := [M] ⋅ (fencerel Fence_rw_w ⋅ [W]).\nDefinition fence_rw_rw := [M] ⋅ (fencerel Fence_rw_rw ⋅ [M]).\nDefinition fence_tso := let f := fencerel Fence_tso in [W] ⋅ (f ⋅ [W]) ⊔ [R] ⋅ (f ⋅ [M]).\nDefinition fence := fence_r_r ⊔ (fence_r_w ⊔ (fence_r_rw ⊔ (fence_w_r ⊔ (fence_w_w ⊔ (fence_w_rw ⊔ (fence_rw_r ⊔ (fence_rw_w ⊔ (fence_rw_rw ⊔ fence_tso)))))))).\nDefinition po_loc_no_w := po_loc ⊓ !((po_loc ⊔ 1) ⋅ ([W] ⋅ po_loc)).\nDefinition rsw := rf° ⋅ rf.\nDefinition AcqRel_0 := AcqRel ⊔ Sc.\nDefinition AQ := Acq ⊔ AcqRel_0.\nDefinition RL := Rel ⊔ AcqRel_0.\nDefinition AMO := (*failed: try AMO with R ⊓ W*) R ⊓ W.\nDefinition RCsc := (Acq ⊔ (Rel ⊔ AcqRel_0)) ⊓ (AMO ⊔ X).\nDefinition r1 := [M] ⋅ (po_loc ⋅ [W]).\nDefinition r2 := [R] ⋅ (po_loc_no_w ⋅ [R]) ⊓ !rsw.\nDefinition r3 := [(AMO ⊔ X)] ⋅ (rfi ⋅ [R]).\nDefinition r4 := fence.\nDefinition r5 := [AQ] ⋅ (po ⋅ [M]).\nDefinition r6 := [M] ⋅ (po ⋅ [RL]).\nDefinition r7 := [RCsc] ⋅ (po ⋅ [RCsc]).\nDefinition r8 := rmw.\nDefinition r9 := [M] ⋅ (addr ⋅ [M]).\nDefinition r10 := [M] ⋅ (data ⋅ [W]).\nDefinition r11 := [M] ⋅ (ctrl ⋅ [W]).\nDefinition r12 := [M] ⋅ ((addr ⊔ data) ⋅ ([W] ⋅ (rfi ⋅ [R]))).\nDefinition r13 := [M] ⋅ (addr ⋅ ([M] ⋅ (po ⋅ [W]))).\nDefinition ppo := r1 ⊔ (r2 ⊔ (r3 ⊔ (r4 ⊔ (r5 ⊔ (r6 ⊔ (r7 ⊔ (r8 ⊔ (r9 ⊔ (r10 ⊔ (r11 ⊔ (r12 ⊔ r13))))))))))).\nDefinition witness_conditions := True.\nDefinition model_conditions := True.\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 Acq AcqRel Fence_r_r Fence_r_rw Fence_r_w Fence_rw_r Fence_rw_rw Fence_rw_w Fence_tso Fence_w_r Fence_w_rw Fence_w_w Rel Sc X tag2events emptyset_0 partition tag2instrs po_loc rfe rfi co0 toid fencerel ctrlcfence imply nodetour singlestep LKW fence_r_r fence_r_w fence_r_rw fence_w_r fence_w_w fence_w_rw fence_rw_r fence_rw_w fence_rw_rw fence_tso fence po_loc_no_w rsw AcqRel_0 AQ RL AMO RCsc r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 ppo witness_conditions model_conditions : cat.\n\nDefinition valid (c : candidate) := True.\n\n(* End of translation of model Unknown *)\n", "meta": {"author": "jmadiot", "repo": "cats", "sha": "d3d6cae610dbd41c8a00d8cbdc0374cb02d6de95", "save_path": "github-repos/coq/jmadiot-cats", "path": "github-repos/coq/jmadiot-cats/cats-d3d6cae610dbd41c8a00d8cbdc0374cb02d6de95/models/riscv_defs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.29843553307025994}}
{"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 A B C D Aprime Bprime Cprime Dprime X Y E Z Eprime : Universe, ((wd_ X A /\\ (wd_ X Aprime /\\ (wd_ X C /\\ (wd_ X Cprime /\\ (wd_ Y B /\\ (wd_ Y Bprime /\\ (wd_ Y D /\\ (wd_ Y Dprime /\\ (wd_ A C /\\ (wd_ B D /\\ (wd_ A Aprime /\\ (wd_ B Bprime /\\ (wd_ C Cprime /\\ (wd_ D Dprime /\\ (wd_ Aprime Cprime /\\ (wd_ Bprime Dprime /\\ (wd_ A E /\\ (wd_ Aprime Eprime /\\ (wd_ B E /\\ (wd_ Bprime Eprime /\\ (wd_ Y A /\\ (wd_ A B /\\ (wd_ X B /\\ (wd_ Aprime Dprime /\\ (wd_ Dprime Eprime /\\ (wd_ A D /\\ (wd_ D E /\\ (wd_ A Eprime /\\ (wd_ E Aprime /\\ (wd_ E Eprime /\\ (wd_ Y E /\\ (wd_ Y Z /\\ (wd_ B Z /\\ (wd_ E Z /\\ (wd_ X E /\\ (wd_ X Z /\\ (wd_ A Z /\\ (wd_ X Y /\\ (wd_ B C /\\ (wd_ Bprime Cprime /\\ (wd_ Aprime Bprime /\\ (col_ X A C /\\ (col_ X A Aprime /\\ (col_ X A Cprime /\\ (col_ Y B D /\\ (col_ Y B Bprime /\\ (col_ Y B Dprime /\\ (col_ E A B /\\ (col_ E C D /\\ (col_ Eprime Aprime Bprime /\\ (col_ Eprime E Z /\\ col_ B C E))))))))))))))))))))))))))))))))))))))))))))))))))) -> col_ B A 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_1140.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.2983150550235631}}
{"text": "From iris.program_logic Require Export total_weakestpre.\nFrom iris.bi Require Export big_op.\nFrom iris.proofmode Require Import tactics.\nSet Default Proof Using \"Type\".\n\nSection lifting.\nContext `{irisG Λ Σ}.\nImplicit Types v : val Λ.\nImplicit Types e : expr Λ.\nImplicit Types σ : state Λ.\nImplicit Types P Q : iProp Σ.\nImplicit Types Φ : val Λ → iProp Σ.\n\nHint Resolve reducible_no_obs_reducible.\n\nLemma twp_lift_step s E Φ e1 :\n  to_val e1 = None →\n  (∀ σ1 κs 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 e2 @ s; E [{ Φ }] ∗\n      [∗ list] ef ∈ efs, WP ef @ s; ⊤ [{ fork_post }])\n  ⊢ WP e1 @ s; E [{ Φ }].\nProof. by rewrite twp_unfold /twp_pre=> ->. Qed.\n\n(** Derived lifting lemmas. *)\nLemma twp_lift_pure_step_no_fork `{Inhabited (state Λ)} s E Φ e1 :\n  (∀ σ1, reducible_no_obs e1 σ1) →\n  (∀ σ1 κ e2 σ2 efs, prim_step e1 σ1 κ e2 σ2 efs → κ = [] ∧ σ2 = σ1 ∧ efs = []) →\n  (|={E}=> ∀ κ e2 efs σ, ⌜prim_step e1 σ κ e2 σ efs⌝ → WP e2 @ s; E [{ Φ }])\n  ⊢ WP e1 @ s; E [{ Φ }].\nProof.\n  iIntros (Hsafe Hstep) \">H\". iApply twp_lift_step.\n  { eapply reducible_not_val, reducible_no_obs_reducible, (Hsafe inhabitant). }\n  iIntros (σ1 κs n) \"Hσ\".\n  iMod fupd_intro_mask' as \"Hclose\"; last iModIntro; first by set_solver. iSplit.\n  { iPureIntro. destruct s; auto. }\n  iIntros (κ e2 σ2 efs ?). destruct (Hstep σ1 κ e2 σ2 efs) as (->&<-&->); auto.\n  iMod \"Hclose\" as \"_\". iModIntro.\n  iDestruct (\"H\" with \"[//]\") as \"H\". simpl. by iFrame.\nQed.\n\n(* Atomic steps don't need any mask-changing business here, one can\n   use the generic lemmas here. *)\nLemma twp_lift_atomic_step {s E Φ} e1 :\n  to_val e1 = None →\n  (∀ σ1 κs 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      from_option Φ False (to_val e2) ∗\n      [∗ list] ef ∈ efs, WP ef @ s; ⊤ [{ fork_post }])\n  ⊢ WP e1 @ s; E [{ Φ }].\nProof.\n  iIntros (?) \"H\".\n  iApply (twp_lift_step _ E _ e1)=>//; iIntros (σ1 κs n) \"Hσ1\".\n  iMod (\"H\" $! σ1 with \"Hσ1\") as \"[$ H]\".\n  iMod (fupd_intro_mask' E ∅) as \"Hclose\"; first set_solver.\n  iIntros \"!>\" (κ e2 σ2 efs) \"%\". iMod \"Hclose\" as \"_\".\n  iMod (\"H\" $! κ e2 σ2 efs with \"[#]\") as \"($ & $ & HΦ & $)\"; first by eauto.\n  destruct (to_val e2) eqn:?; last by iExFalso.\n  iApply twp_value; last done. by apply of_to_val.\nQed.\n\nLemma twp_lift_pure_det_step_no_fork `{Inhabited (state Λ)} {s E Φ} e1 e2 :\n  (∀ σ1, reducible_no_obs e1 σ1) →\n  (∀ σ1 κ e2' σ2 efs', prim_step e1 σ1 κ e2' σ2 efs' →\n    κ = [] ∧ σ2 = σ1 ∧ e2' = e2 ∧ efs' = []) →\n  (|={E}=> WP e2 @ s; E [{ Φ }]) ⊢ WP e1 @ s; E [{ Φ }].\nProof.\n  iIntros (? Hpuredet) \">H\". iApply (twp_lift_pure_step_no_fork s E); try done.\n  { naive_solver. }\n  iIntros \"!>\" (κ' e' efs' σ (_&_&->&->)%Hpuredet); auto.\nQed.\n\nLemma twp_pure_step `{Inhabited (state Λ)} s E e1 e2 φ n Φ :\n  PureExec φ n e1 e2 →\n  φ →\n  WP e2 @ s; E [{ Φ }] ⊢ WP e1 @ s; E [{ Φ }].\nProof.\n  iIntros (Hexec Hφ) \"Hwp\". specialize (Hexec Hφ).\n  iInduction Hexec as [e|n e1 e2 e3 [Hsafe ?]] \"IH\"; simpl; first done.\n  iApply twp_lift_pure_det_step_no_fork; [done|naive_solver|].\n  iModIntro. by iApply \"IH\".\nQed.\nEnd lifting.\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_lifting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5698526660244837, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.2982724812928298}}
{"text": "(* -*- mode: coq; coq-prog-args: (\"-nois\") -*- *)\n\n(* in Coq 8.8.0 *)\n\n(** * Pre\n\n    事前に定義すべきもの。\n\n    第一に、表記法を事前に定義する。\n    これらは実際に何を意味するか定義されていないが\n    優先順位や結合性は定義されている。\n    最初から [_ + _] を自然数同士の足し算を意味すると決めたりすると\n    それを整数同士の足し算と解釈したいときに困ってしまうし、\n    それぞれの単塊 (Module) で表記法を定義すると\n    [2 + 3 + 4 * 0] という式が\n    どの単塊に書かれているかによって\n    [(2 + 3) + (4 * 0)] と解釈されたり\n    [((2 + 3) + 4) * 0] と解釈されたりして\n    読みづらくなってしまうことがあり得るため、\n    両方の間を取っている。\n    ちなみに書かれている場所によってどの解釈を選ぶかは\n    視野 (scope) の仕組みによる。\n\n    第二に、視野 (scope) を定義する。\n    例えば [(Empty + Unit)%type] という式があったとする。\n    このとき、百分率記号は右側の式が解釈されるときに\n    その式の内部の表記法の意味が [type] という視野の中から探されることを示す。\n    どの表記法がどの視野に入るかは表記法の意味を定義するときに一緒に定義できる。\n    同じ表記法でも視野によって意味が異なることがある。\n    式を読み取る何某から見える「視野」をイメージしてほしい。\n    百分率記号で直接的に指定しなくとも型によって視野が選ばれることもある。\n\n    第三に、戦略 (tactic) を使用するための設定をする。\n    戦略 (tactic) は一気に定義を書き上げることが出来ない場合に有用な道具である。\n    この部分の記述は Stack Overflow で Tej Chajed 氏に教えていただいた。\n    さらに、 Coq の標準文庫 (library) の内部にある\n    Coq.Init.Notations の記述も参考にした。\n\n    第四に、設定旗 (flag) を操作する。\n    HoTT の内部にある HoTT.Basics.Overture の記述に依った。\n\n*)\n\nModule Pre.\n\n (** ** 述語論理の記号\n\n     これらのいずれも Coq.Init.Notations を参考にした。\n     含意記号は右側のみ優先順位が低いため、\n     [P -> _] と書かれた時に [_] の部分が分けられて認識されることはない。\n\n *)\n\n Reserved Notation \"x -> y\" (at level 99, right associativity, y at level 200).\n Reserved Notation \"x <-> y\" (at level 95, no associativity).\n Reserved Notation \"x /\\ y\" (at level 80, right associativity).\n Reserved Notation \"x \\/ y\" (at level 85, right associativity).\n Reserved Notation \"~ x\" (at level 75, right associativity).\n\n (** ** 等号及び不等号、大小関係 *)\n\n Reserved Notation \"x = y :> T\" (at level 70, y at next level, no associativity).\n Reserved Notation \"x = y\" (at level 70, no associativity).\n\n Reserved Notation \"x <> y :> T\"(at level 70, y at next level, no associativity).\n Reserved Notation \"x <> y\" (at level 70, no associativity).\n\n Reserved Notation \"x <= y\" (at level 70, no associativity).\n Reserved Notation \"x < y\" (at level 70, no associativity).\n Reserved Notation \"x >= y\" (at level 70, no associativity).\n Reserved Notation \"x > y\" (at level 70, no associativity).\n\n (** ** 算術演算子 *)\n\n Reserved Notation \"x + y\" (at level 50, left associativity).\n Reserved Notation \"x - y\" (at level 50, left associativity).\n Reserved Notation \"x * y\" (at level 40, left associativity).\n Reserved Notation \"x / y\" (at level 40, left associativity).\n Reserved Notation \"x ^ y\" (at level 30, right associativity).\n\n Reserved Notation \"- x\" (at level 35, right associativity).\n Reserved Notation \"/ x\" (at level 35, right associativity).\n\n (** ** 視野 (scope) *)\n\n Delimit Scope type_scope with type.\n Delimit Scope function_scope with function.\n Delimit Scope core_scope with core.\n\n Bind Scope type_scope with Sortclass.\n Bind Scope function_scope with Funclass.\n\n Open Scope core_scope.\n Open Scope function_scope.\n Open Scope type_scope.\n\n (** ** 戦略 (tactic) の設定 *)\n\n Declare ML Module \"ltac_plugin\".\n\n Export Set Default Proof Mode \"Classic\".\n\n (** ** 設定旗 (flag) の操作 *)\n\n Export Unset Bracketing Last Introduction Pattern.\n\n Export Set Typeclasses Strict Resolution.\n\n Export Unset Elimination Schemes.\n\n Export Set Keyed Unification.\n\n Export Unset Refine Instance Mode.\n\n Export Unset Strict Universe Declaration.\n\n Export Unset Universe Minimization ToSet.\n\nEnd Pre.\n\n(** * Predicate\n\n    命題論理、述語論理についての定義。\n    論理式はカリー・ハワード対応に従って型へ翻訳される。\n    この小単位はそれらを定義するものである。\n    ただ、これらは命題 (Prop) ではなく 型 (Type) であることに注意すること。\n\n*)\n\nModule Predicate.\n\n Export Pre.\n\n (** ** 関数 *)\n\n Definition arrow (A B : Type) : Type := forall (_ : A), B.\n\n Notation \"A -> B\" := (forall (_ : A), B) : type_scope.\n\n (** 汎用関数 *)\n\n Definition id {A : Type} : A -> A := fun x => x.\n\n Definition const {A B : Type} : A -> B -> A := fun x _ => x.\n\n Definition compose {A B C : Type} : (A -> B) -> (C -> A) -> C -> B := fun f g x => f (g x).\n\n Definition flip {A B C : Type} : (A -> B -> C) -> B -> A -> C := fun f x y => f y x.\n\n Definition apply {A B : Type} : (A -> B) -> A -> B := id.\n\n (** ** Empty *)\n\n (** 偽、矛盾、空の型、空の空間。 *)\n\n Inductive Empty : Type :=\n .\n\n Scheme Empty_ind := Induction for Empty Sort Type.\n Scheme Empty_rec := Minimality for Empty Sort Type.\n Definition Empty_rect := Empty_ind.\n\n Arguments Empty_rec {P} _.\n\n Definition not (A : Type) : Type := A -> Empty.\n\n Notation \"~ x\" := (not x) : type_scope.\n\n (** ** Unit *)\n\n (** 真、点の空間、ユニット。 *)\n\n Inductive Unit : Type :=\n | tt : Unit\n .\n\n Scheme Unit_ind := Induction for Unit Sort Type.\n Scheme Unit_rec := Minimality for Unit Sort Type.\n Definition Unit_rect := Unit_ind.\n\n Arguments Unit_rec {P} _ _.\n\n (** ** and *)\n\n (** 論理積、二つ組、対、ダブル、2-タプル、ペア。 *)\n\n Inductive and (A B : Type) : Type :=\n | pair : A -> B -> A /\\ B\n where\n   \"A /\\ B\" := (and A B) : type_scope\n .\n\n Arguments pair {A B} _ _.\n\n Scheme and_ind := Induction for and Sort Type.\n Scheme and_rec := Minimality for and Sort Type.\n Definition and_rect := and_ind.\n\n Arguments and_ind {A B} _ _ _.\n Arguments and_rec {A B P} _ _.\n Arguments and_rect {A B} _ _ _.\n\n Definition first {A B : Type} : A /\\ B -> A :=\n  fun x => match x with pair xL _ => xL end\n .\n\n Definition second {A B : Type} : A /\\ B -> B :=\n  fun x => match x with pair _ xR => xR end\n .\n\n Definition and_proj1 {A B : Type} := @first A B.\n Definition and_proj2 {A B : Type} := @second A B.\n\n (** ** or *)\n\n (** 論理和。 *)\n\n Inductive or (A B : Type) : Type :=\n | left : A -> A \\/ B\n | right : B -> A \\/ B\n where\n   \"A \\/ B\" := (or A B) : type_scope\n .\n\n Arguments left {A B} _.\n Arguments right {A B} _.\n\n Scheme or_ind := Induction for or Sort Type.\n Scheme or_rec := Minimality for or Sort Type.\n Definition or_rect := or_ind.\n\n Arguments or_ind {A B} _ _ _ _.\n Arguments or_rec {A B P} _ _ _.\n Arguments or_rect {A B} _ _ _ _.\n\n (** 写像。 *)\n\n Theorem and_map_l {A B C : Type} : (A -> B) -> A /\\ C -> B /\\ C.\n Proof.\n  intros f [xl xr]; refine (pair (f xl) xr).\n Defined.\n\n Theorem and_map_r {A B C : Type} : (A -> B) -> C /\\ A -> C /\\ B.\n Proof.\n  intros f [xl xr]; refine (pair xl (f xr)).\n Defined.\n\n Theorem or_map_l {A B C : Type} : (A -> B) -> A \\/ C -> B \\/ C.\n Proof.\n  intros f [xl | xr]; [> refine (left (f xl)) | refine (right xr) ].\n Defined.\n\n Theorem or_map_r {A B C : Type} : (A -> B) -> C \\/ A -> C \\/ B.\n Proof.\n  intros f [xl | xr]; [> refine (left xl) | refine (right (f xr)) ].\n Defined.\n\n Theorem imp_map_l {A B C : Type} : (A -> B) -> (B -> C) -> (A -> C).\n Proof.\n  intros f g; refine (compose g f).\n Defined.\n\n Theorem imp_map_r {A B C : Type} : (A -> B) -> (C -> A) -> (C -> B).\n Proof.\n  intros f g; refine (compose f g).\n Defined.\n\n Theorem not_map {A B : Type} : (A -> B) -> ~ B -> ~ A.\n Proof.\n  intros f x; refine (compose x f).\n Defined.\n\n (** ** 命題論理の定理 *)\n\n Definition exfalso {A : Type} : Empty -> A := Empty_rec.\n\n Definition unit_const {A : Type} : A -> Unit := const tt.\n\n Theorem and_fanout {A B C : Type} : (A -> B) -> (A -> C) -> A -> B /\\ C.\n Proof.\n  intros f g x; refine (pair (f x) (g x)).\n Defined.\n\n Theorem or_fanin {A B C : Type} : (A -> B) -> (C -> B) -> A \\/ C -> B.\n Proof.\n  intros f g [xl | xr]; [> refine (f xl) | refine (g xr) ].\n Defined.\n\n Theorem double_not {A : Type} : A -> ~ ~ A.\n Proof.\n  intros a na.\n  apply na.\n  apply a.\n Defined.\n\n (** ** iff *)\n\n (** 同値。 *)\n\n Definition iff (A B : Type) : Type := (A -> B) /\\ (B -> A).\n\n Notation \"A <-> B\" := (iff A B) : type_scope.\n\n (** iffの基本性質 *)\n\n Theorem iff_refl {A : Type} : A <-> A.\n Proof.\n  refine (pair id id).\n Defined.\n\n Theorem iff_sym {A B : Type} : (A <-> B) -> (B <-> A).\n Proof.\n  intros x.\n  refine (pair (second x) (first x)).\n Defined.\n\n Theorem iff_trans {A B C : Type} :  (A <-> B) -> (C <-> A) -> (C <-> B).\n Proof.\n  intros x y.\n  apply pair.\n  -\n   refine (compose (first x) (first y)).\n  -\n   refine (compose (second y) (second x)).\n Defined.\n\n (** 双方向の写像 *)\n\n Theorem and_iff_map_l {A B C : Type} : (A <-> B) -> (A /\\ C <-> B /\\ C).\n Proof.\n  intros [xl xr]; refine (pair (and_map_l xl) (and_map_l xr)).\n Defined.\n\n Theorem and_iff_map_r {A B C : Type} : (A <-> B) -> (C /\\ A <-> C /\\ B).\n Proof.\n  intros [xl xr]; refine (pair (and_map_r xl) (and_map_r xr)).\n Defined.\n\n Theorem or_iff_map_l {A B C : Type} : (A <-> B) -> (A \\/ C <-> B \\/ C).\n Proof.\n  intros [xl xr]; refine (pair (or_map_l xl) (or_map_l xr)).\n Defined.\n\n Theorem or_iff_map_r {A B C : Type} : (A <-> B) -> (C \\/ A <-> C \\/ B).\n Proof.\n  intros [xl xr]; refine (pair (or_map_r xl) (or_map_r xr)).\n Defined.\n\n Theorem imp_iff_map_l {A B C : Type} : (A <-> B) -> ((A -> C) <-> (B -> C)).\n Proof.\n  intros [xl xr]; refine (pair (imp_map_l xr) (imp_map_l xl)).\n Defined.\n\n Theorem imp_iff_map_r {A B C : Type} : (A <-> B) -> ((C -> A) <-> (C -> B)).\n Proof.\n  intros [xl xr]; refine (pair (imp_map_r xl) (imp_map_r xr)).\n Defined.\n\n Theorem not_iff_map {A B C : Type} : (A <-> B) -> (~ A <-> ~B).\n Proof.\n  intros [xl xr]; refine (pair (not_map xr) (not_map xl)).\n Defined.\n\n (** ** 重要な同値関係 *)\n\n Theorem neg_false {A : Type} : ~ A <-> (A <-> Empty).\n Proof.\n  apply pair.\n  -\n   intros nx.\n   refine (pair nx exfalso).\n  -\n   apply first.\n Defined.\n\n Theorem and_comm {A B : Type} : A /\\ B <-> B /\\ A.\n Proof.\n  assert (comm : forall A B, A /\\ B -> B /\\ A).\n  -\n   intros gA gB [xl xr]; refine (pair xr xl).\n  -\n   apply pair.\n   +\n    apply comm.\n   +\n    apply comm.\n Defined.\n\n Theorem and_assoc {A B C : Type} : (A /\\ B) /\\ C <-> A /\\ B /\\ C.\n Proof.\n  apply pair.\n  -\n   refine (and_fanout _ _).\n   +\n    refine (compose first first).\n   +\n    refine (and_fanout _ _).\n    *\n     refine (compose second first).\n    *\n     refine second.\n  -\n   refine (and_fanout _ _).\n   +\n    refine (and_fanout _ _).\n    *\n     refine first.\n    *\n     refine (compose first second).\n   +\n    refine (compose second second).\n Defined.\n\n Theorem and_unit_l {A : Type} : A /\\ Unit <-> A.\n Proof.\n  apply pair.\n  -\n   apply first.\n  -\n   refine (and_fanout id unit_const).\n Defined.\n\n Theorem and_unit_r {A : Type} : Unit /\\ A <-> A.\n Proof.\n  apply pair.\n  -\n   apply second.\n  -\n   refine (and_fanout unit_const id).\n Defined.\n\n Theorem or_comm {A B : Type} : (A \\/ B) <-> (B \\/ A).\n Proof.\n  assert (comm : forall A B, A \\/ B -> B \\/ A).\n  -\n   intros gA gB [xl | xr]; [> refine (right xl) | refine (left xr) ].\n  -\n   apply pair.\n   +\n    apply comm.\n   +\n    apply comm.\n Defined.\n\n Theorem or_assoc {A B C : Type} : (A \\/ B) \\/ C <-> A \\/ B \\/ C.\n Proof.\n  apply pair.\n  -\n   refine (or_fanin _ _).\n   +\n    refine (or_fanin _ _).\n    *\n     refine left.\n    *\n     refine (compose right left).\n   +\n    refine (compose right right).\n  -\n   refine (or_fanin _ _).\n   +\n    refine (compose left left).\n   +\n    refine (or_fanin _ _).\n    *\n     refine (compose left right).\n    *\n     refine right.\n Defined.\n\n Theorem or_empty_l {A : Type} : A \\/ Empty <-> A.\n Proof.\n  apply pair.\n  -\n   apply or_fanin.\n   +\n    apply id.\n   +\n    apply exfalso.\n  -\n   apply left.\n Defined.\n\n Theorem or_empty_r {A : Type} : Empty \\/ A <-> A.\n Proof.\n  apply pair.\n  -\n   apply or_fanin.\n   +\n    apply exfalso.\n   +\n    apply id.\n  -\n   apply right.\n Defined.\n\n Theorem iff_double_not {A : Type} : ~ ~ ~ A <-> ~ A.\n Proof.\n  apply pair.\n  -\n   apply not_map.\n   apply double_not.\n  -\n   apply double_not.\n Defined.\n\n Theorem de_morgan {A B : Type} : ~ (A \\/ B) <-> ~ A /\\ ~ B.\n Proof.\n  apply pair.\n  -\n   apply and_fanout.\n   +\n    apply not_map.\n    apply left.\n   +\n    apply not_map.\n    apply right.\n  -\n   intros [xl xr].\n   refine (or_rec xl xr).\n Defined.\n\n (** ** 量化子 *)\n\n Inductive ex (A : Type) (P : A -> Type) : Type :=\n | ex_pair : forall x : A, P x -> ex A P\n .\n\n Notation \"'exists' x .. y , p\"\n   :=\n     (ex _ (fun x => .. (ex _ (fun y => p)) ..))\n   (\n     at level 200,\n     x binder,\n     right associativity,\n     format \"'[' 'exists'  '/  ' x  ..  y ,  '/  ' p ']'\")\n   :\n     type_scope.\n\n Arguments ex {A} _.\n Arguments ex_pair {A} _ _ _.\n\n Scheme ex_ind := Induction for ex Sort Type.\n Scheme ex_rec := Minimality for ex Sort Type.\n Definition ex_rect := ex_ind.\n\n Arguments ex_ind {A P} _ _ _.\n Arguments ex_rec {A P P0} _ _.\n Arguments ex_rect {A P} _ _ _.\n\n Definition ex_proj1 {A : Type} {P : A -> Type} : ex P -> A.\n Proof.\n  intros x.\n  case x.\n  intros x1 x2.\n  apply x1.\n Defined.\n\n Definition ex_proj2 {A : Type} {P : A -> Type} : forall (x : ex P), P (ex_proj1 x).\n Proof.\n  intros x.\n  case x.\n  intros x1 x2.\n  apply x2.\n Defined.\n\n Definition all {A : Type} (P : A -> Type) : Type := forall x, P x.\n\n (** 量化子に関する重要な同値関係 *)\n\n Theorem quant_de_morgan {A : Type} {P : A -> Type} : ~ (exists x, P x) <-> forall x, ~ P x.\n Proof.\n  apply pair.\n  -\n   intros H x xH.\n   apply H.\n   apply ex_pair with x.\n   apply xH.\n  -\n   intros H [x xH].\n   apply H with x.\n   apply xH.\n Defined.\n\nEnd Predicate.\n\n(** * Equality *)\n\n(** 等号について。 *)\n\nModule Equality.\n\n Export Predicate.\n\n (** ** eq *)\n\n Inductive eq (A : Type) (x : A) : A -> Type :=\n | eq_refl : x = x :> A\n where\n   \"x = y :> A\" := (eq A x y) : type_scope\n .\n\n Notation \"x = y\" := (x = y :> _) : type_scope.\n Notation \"x <> y :> T\" := (~ x = y :> T) : type_scope.\n Notation \"x <> y\" := (x <> y :> _) : type_scope.\n\n Arguments eq {A} _ _.\n Arguments eq_refl {A x}, [A] x.\n\n Scheme eq_ind := Induction for eq Sort Type.\n Scheme eq_rec := Minimality for eq Sort Type.\n Definition eq_rect := eq_ind.\n\n Arguments eq_ind [A] _ _ _ _ _.\n Arguments eq_rec [A] _ _ _ _ _.\n Arguments eq_rect [A] _ _ _ _ _.\n\n (** eqの基本性質 *)\n\n Definition eq_sym {A : Type} {x y : A} : x = y -> y = x.\n Proof.\n  intros [].\n  apply eq_refl.\n Defined.\n\n Definition eq_trans {A : Type} {x y z : A} : x = y -> z = x -> y = z.\n Proof.\n  intros [] [].\n  apply eq_refl.\n Defined.\n\n (** eqの汎用関数 *)\n\n Definition eq_ind'\n     : forall (A : Type) (P : forall a b : A, a = b -> Type),\n         (forall a : A, P a a eq_refl) -> forall (a b : A) (p : a = b), P a b p.\n Proof.\n  intros A P H a b [].\n  apply H.\n Defined.\n\n Definition eq_rec'\n     : forall (A : Type) (P : A -> A -> Type),\n         (forall a : A, P a a) -> forall a b : A, a = b -> P a b.\n Proof.\n  intros A P H a b [].\n  apply H.\n Defined.\n\n Definition eq_rect' := eq_ind'.\n\n Definition eq_rec_r\n     : forall (A : Type) (x : A) (P : A -> Type), P x -> forall (y : A), y = x -> P y.\n Proof.\n  intros A x P H y p.\n  apply (eq_rec x P H y).\n  apply eq_sym.\n  apply p.\n Defined.\n\n Arguments eq_ind' [A] _ _ _ _ _.\n Arguments eq_rec' [A] _ _ _ _ _.\n Arguments eq_rect' [A] _ _ _ _ _.\n Arguments eq_rec_r [A] _ _ _ _ _.\n\n Definition f_equal {A B : Type} (f : A -> B) {x y : A} : x = y -> f x = f y.\n Proof.\n  intros [].\n  apply eq_refl.\n Defined.\n\n Definition rew {A : Type} (P : A -> Type) {x y : A} : x = y -> P x -> P y.\n Proof.\n  intros [].\n  apply id.\n Defined.\n\nEnd Equality.\n\nModule Peano.\n Export Predicate Equality.\n\n Inductive nat : Type :=\n | O : nat\n | S : nat -> nat\n .\n\n Scheme nat_ind := Induction for nat Sort Type.\n Scheme nat_rec := Minimality for nat Sort Type.\n Definition nat_rect := nat_ind.\n\n Definition not_eq_O_S : forall n, O <> S n.\n Proof.\n  intros n p.\n  refine (\n   match p in _ = x' return (match x' with O => Unit | S xp => Empty end) with\n   | eq_refl _ _ => _\n   end\n  ).\n  apply tt.\n Defined.\n\n Definition pred : nat -> nat :=\n  fun x =>\n   match x with\n   | O => O\n   | S xp => xp\n   end\n .\n\n Inductive le (m : nat) : nat -> Type :=\n | le_n : le m m\n | le_S : forall n, le m n -> le m (S n)\n .\n\n Definition le_rect_simple : forall (m : nat) (P : nat -> Type),\n   P m -> (forall n, le m n -> P n -> P (S n)) -> forall n, le m n -> P n.\n Proof.\n  intros m P cN cS.\n  apply le_rect.\n  -\n   apply cN.\n  -\n   apply cS.\n Defined.\n\n Definition le_ind_simple : forall (m : nat) (P : nat -> Prop),\n   P m -> (forall n, le m n -> P n -> P (S n)) -> forall n, le m n -> P n.\n Proof.\n  intros m P cN cS.\n  apply le_rect.\n  -\n   apply cN.\n  -\n   apply cS.\n Defined.\n\n Definition le_rec_simple : forall (m : nat) (P : nat -> Set),\n   P m -> (forall n, le m n -> P n -> P (S n)) -> forall n, le m n -> P n.\n Proof.\n  intros m P.\n  apply le_rect_simple.\n Defined.\n\n Definition le_0_n : forall n : nat, le O n.\n Proof.\n  intros n.\n  induction n as [ | n IHn ].\n  -\n   apply le_n.\n  -\n   apply le_S.\n   apply IHn.\n Defined.\n\n Definition le_n_S : forall m n : nat, le m n -> le (S m) (S n).\n Proof.\n  intros m.\n  apply le_rect_simple.\n  -\n   apply le_n.\n  -\n   intros n nH H.\n   apply le_S.\n   apply H.\n Defined.\n\n Definition le_pred : forall m n : nat, le m n -> le (pred m) (pred n).\n Proof.\n  intros m.\n  apply le_rect_simple.\n  -\n   apply le_n.\n  -\n   intros [ | np ] nH H.\n   +\n    apply H.\n   +\n    cut (forall k, S (pred (S k)) = pred (S (S k))).\n    *\n     intros Lem.\n     case (Lem np).\n     apply le_S.\n     apply H.\n    *\n     intros k.\n     apply eq_refl.\n Defined.\n\n Definition le_S_n : forall m n : nat, le (S m) (S n) -> le m n.\n Proof.\n  intros m n H.\n  apply (le_pred (S m) (S n)).\n  apply H.\n Defined.\n\n Definition le_trans : forall m n o, le m n -> le n o -> le m o.\n Proof.\n  intros m n o H.\n  revert o.\n  apply le_rect_simple.\n  -\n   apply H.\n  -\n   intros o oH IH.\n   apply le_S.\n   apply IH.\n Defined.\n\n Definition lt m n := le (S m) n.\n\n Definition not_lt_n_0 : forall n, ~ lt n O.\n Proof.\n  intros n nH.\n  cut (O = O).\n  -\n   refine (\n    match nH in le _ o' return O <> o' with\n    | le_n _ => _\n    | le_S _ o pH => _\n    end\n   ).\n   +\n    apply not_eq_O_S.\n   +\n    apply not_eq_O_S.\n  -\n   apply eq_refl.\n Defined.\nEnd Peano.\n\nExport Peano. *)\n\nModule Path.\n Export Equality.\n\n Definition paths := @eq.\n\n Definition idpath := @eq_refl.\n\n Definition inverse := eq_sym.\n\n Definition concat := fun (A : Type) (x y z : A) => flip (@eq_trans A y z x).\n\n Definition transport := rew.\n\n Definition ap := f_equal.\n\n (** apKN\n\n<<\nap00 :=\n  fun (f   : A -> B)                       (x   : A)                => (_ : B)\nap01 :=\n  fun (f   : A -> B)                       (x y : A) (p : eq A x y) => (_ : eq B (f x) (f y))\nap10 :=\n  fun (f g : A -> B) (p : eq (A -> B) f g) (x   : A)                => (_ : eq B (f x) (g x))\nap11 :=\n  fun (f g : A -> B) (p : eq (A -> B) f g) (x y : A) (q : eq A x y) => (_ : eq B (f x) (g y))\n>>\n\n *)\n\n Definition ap00 := apply.\n\n Definition ap01 := ap.\n\n Definition ap10 : forall (A B : Type) (f g : A -> B), f = g -> forall (x : A), f x = g x.\n Proof.\n  intros A B f g p x.\n  case p.\n  apply idpath.\n Defined.\n\n Definition ap11\n     : forall (A B : Type) (f g : A -> B), f = g -> forall (x y : A), x = y -> f x = g y.\n Proof.\n  intros A B f g p x y q.\n  case p.\n  case q.\n  apply idpath.\n Defined.\n\n Definition pw_paths (A : Type) (P : A -> Type) (f g : forall x, P x) := forall x, f x = g x.\n\n Definition pw_idpath : forall (A : Type) (P : A -> Type) (f : forall x, P x), pw_paths P f f.\n Proof.\n  intros A P f x.\n  apply idpath.\n Defined.\n\n Definition pw_whiskerL (A B C : Type) (f : A -> B) (g h : B -> C)\n     : pw_paths (fun _ => C) g h -> pw_paths (fun _ => C) (compose g f) (compose h f).\n Proof.\n  intros p x.\n  apply p.\n Defined.\n\n Definition pw_whiskerR (A B C : Type) (f g : A -> B) (h : B -> C)\n     : pw_paths (fun _ => B) f g -> pw_paths (fun _ => C) (compose h f) (compose h g).\n Proof.\n  intros p x.\n  apply ap with (f := h).\n  apply p.\n Defined.\n\n Definition pw_pw_paths\n     (A : Type) (P : A -> Type) (f g : forall x, P x) (pw_p pw_q : pw_paths P f g)\n   := forall x, pw_p x = pw_q x.\n\n Definition sect (A B : Type) (s : A -> B) (r : B -> A)\n     := pw_paths (fun _ => A) (compose r s) id.\n\n Definition equiv (A B : Type)\n     := exists (f : A -> B) (g : B -> A) (es : sect g f) (er : sect f g),\n         pw_pw_paths (fun _ => B) (compose f (compose g f)) f\n             (pw_whiskerL f (compose f g) id es)\n             (pw_whiskerR (compose g f) id f er).\n\nEnd Path.\n\nModule Relation.\n Export Predicate.\n\n Definition relation (A : Type) := A -> A -> Type.\n\n Definition mere (A : Type) (R : relation A) := forall x y : A, forall p q : R x y, p = q.\n\n Section Classes.\n  Variable A : Type.\n  Variable R : relation A.\n\n  Class Reflexive : Type :=\n    reflexivity : forall x, R x x.\n\n  Class Irreflexive :=\n    irreflexivity : forall x, ~ R x x.\n\n  Class Symmetric :=\n    symmetry : forall x y, R x y -> R y x.\n\n  Class Asymmetric :=\n    asymmetry : forall x y, R x y -> ~ R y x.\n\n  Class Antisymmetric :=\n    antisymmetry : forall x y, R x y -> R y x -> x = y.\n\n  Class Transitive :=\n    transitivity : forall x y z, R x y -> R y z -> R x z.\n\n  Class Well_Founded :=\n    well_foundness : forall P, (forall x, (forall y, R y x -> P y) -> P x) -> (forall x, P x).\n\n  Class Trichotomous :=\n    trichotomy : forall x y, x = y \\/ R x y \\/ R y x.\n\n  Class Extensional :=\n    extensionality : forall x y, (forall a, R a x <-> R a y) -> x = y.\n\n  Theorem th_0 `{WF : Well_Founded} : Irreflexive.\n  Proof.\n   unfold Irreflexive.\n   apply well_foundness.\n   intros x IH H.\n   apply IH with x.\n   -\n    apply H.\n   -\n    apply H.\n  Defined.\n\n  Theorem th_1 `{WF : Well_Founded} : Asymmetric.\n  Proof.\n   unfold Asymmetric.\n   apply (@well_foundness _ (fun x => forall y, R x y -> ~ R y x)).\n   intros x IH y Hl Hr.\n   apply IH with y x.\n   -\n    apply Hr.\n   -\n    apply Hr.\n   -\n    apply Hl.\n  Defined.\n\n  Theorem th_2 `{IR : Irreflexive} `{T : Trichotomous} : Extensional.\n  Proof.\n   unfold Extensional.\n   intros x y H.\n   destruct (@trichotomy _ x y) as [both | [left | right]].\n   -\n    apply both.\n   -\n    apply exfalso.\n    apply irreflexivity with x.\n    apply (second (H _)).\n    apply left.\n   -\n    apply exfalso.\n    apply irreflexivity with y.\n    apply (first (H _)).\n    apply right.\n  Defined.\n\n  Theorem th_3 `{WF : Well_Founded} `{T : Trichotomous} : Transitive.\n  Proof.\n   unfold Transitive.\n   intros x y z Hl Hr.\n   destruct (@trichotomy _ x z) as [both | [left | right]].\n   -\n    apply exfalso.\n    assert (AS : Asymmetric).\n    +\n     apply th_1.\n    +\n     apply asymmetry with y z.\n     *\n      apply Hr.\n     *\n      case both.\n      apply Hl.\n  -\n   apply left.\n  -\n   assert (tri_loop : forall x y z, R x y -> R y z -> R z x -> Empty).\n   +\n    clear x y z Hl Hr right.\n    apply (@well_foundness _ (fun x => forall y z, R x y -> R y z -> R z x -> Empty)).\n    intros x IH y z Hx Hy Hz.\n    apply IH with z x y.\n    *\n     apply Hz.\n    *\n     apply Hz.\n    *\n     apply Hx.\n    *\n     apply Hy.\n   +\n    apply exfalso.\n    apply tri_loop with x y z.\n    *\n     apply Hl.\n    *\n     apply Hr.\n    *\n     apply right.\n  Defined.\n End Classes.\n\nModule Type Ord.\n Parameter ord : Type.\n Parameter lt : ord -> ord -> Type.\nEnd Ord.\n\nModule Ord_Defs (Export Model : Ord).\n Definition le : ord -> ord -> Type := fun a b => lt a b \\/ a = b.\n\n Definition le_lt : forall a b, lt a b -> le a b.\n Proof.\n  intros a b H.\n  apply left.\n  apply H.\n Defined.\n\n Definition le_eq : forall a b, a = b -> le a b.\n Proof.\n  intros a b H.\n  apply right.\n  apply H.\n Defined.\n\n Definition le_refl : forall a, le a a.\n Proof.\n  intros a.\n  apply le_eq.\n  apply eq_refl.\n Defined.\nEnd Ord_Defs.\n\nModule Type Induction (Export Model : Ord).\n Axiom ind\n   : forall p : ord -> Type, (forall a, (forall x, lt x a -> p x) -> p a) -> forall a, p a.\nEnd Induction.\n\nModule Induction_Defs (Model : Ord) (Export IndModel : Induction Model).\n Module Model_Ord_Defs := Ord_Defs Model.\n Export Model_Ord_Defs.\n\n Definition not_lt_refl : forall a, ~ lt a a.\n Proof.\n  apply (ind (fun a => ~ lt a a)).\n  intros a IHa H.\n  apply IHa with a.\n  -\n   apply H.\n  -\n   apply H.\n Defined.\n\n Definition not_lt_sym : forall a b, lt a b -> ~ lt b a.\n Proof.\n  apply (ind (fun a => forall b, lt a b -> ~ lt b a)).\n  intros a IHa b Ha Hb.\n  apply IHa with b a.\n  -\n   apply Hb.\n  -\n   apply Hb.\n  -\n   apply Ha.\n Defined.\n\n Definition not_lt_sym_and : forall a b, ~ (lt a b /\\ lt b a).\n Proof.\n  intros a b.\n  apply not_and_then.\n  apply not_lt_sym.\n Defined.\n\n Definition not_lt_inf_dec_chain : forall f, ~ (forall n, lt (f (S n)) (f n)).\n Proof.\n  intros f inf_dec_chain.\n  cut (forall a x, f x <> a).\n  -\n   intros H.\n   apply H with (f O) O.\n   apply eq_refl.\n  -\n   apply (ind (fun a => forall x, f x <> a)).\n   intros a IHa x H.\n   apply IHa with (f (S x)) (S x).\n   +\n    case H.\n    apply inf_dec_chain.\n   +\n    apply eq_refl.\n Defined.\n\n Definition not_le_lt : forall a b, lt a b -> ~ le b a.\n Proof.\n  intros a b H [L | R].\n  -\n   apply not_lt_sym with a b.\n   +\n    apply H.\n   +\n    apply L.\n  -\n   revert H.\n   case R.\n   apply not_lt_refl.\n Defined.\n\n Definition not_and_lt_le : forall a b, ~ (lt a b /\\ le b a).\n Proof.\n  intros a b.\n  apply not_and_then.\n  apply not_le_lt.\n Defined.\n\n Definition not_lt_le : forall a b, le a b -> ~ lt b a.\n Proof.\n  intros a b.\n  apply not_then_then.\n  apply not_le_lt.\n Defined.\nEnd Induction_Defs.\n\nModule Type Extensionality (Export Model : Ord).\n Axiom extension : forall a b, (forall x, lt x a <-> lt x b) -> a = b.\nEnd Extensionality.\n\nModule Extensionality_Defs (Model : Ord) (Export ExModel : Extensionality Model).\nEnd Extensionality_Defs.\n\nModule Type Transitivity (Export Model : Ord).\n Axiom transition : forall a b c, lt a b -> lt b c -> lt a c.\nEnd Transitivity.\n\nModule Transitivity_Defs (Model : Ord) (Export TransModel : Transitivity Model).\nEnd Transitivity_Defs.\n\nModule IndExTrans_Defs\n  (Model : Ord)\n  (Export IndModel : Induction Model)\n  (Export ExModel : Extensionality Model)\n  (Export TransModel : Transitivity Model).\n\n Module IndDefs := Induction_Defs Model IndModel.\n Export IndDefs.\n\n Module ExDefs := Extensionality_Defs Model ExModel.\n Export ExDefs.\n\n Module TransDefs := Transitivity_Defs Model TransModel.\n Export TransDefs.\n\n (*\n  double-negation translated [forall x y, x = y \\/ lt x y \\/ lt y x] (Gödel–Gentzen translation)\n *)\n Definition trichotomy : forall x y, ~ (~ ~ ~ x = y /\\ ~ ~ (~ ~ ~ lt x y /\\ ~ ~ ~ lt y x)).\n Proof.\n  intros x y H.\n  case H.\n  intros HL HR.\n  apply HL.\n  intros HL'.\n  apply HR.\n  intros HR'.\n  case HR'.\n  intros HR'L HR'R.\n  apply HR'L.\n\nModule Nat_Ord <: Ord.\n Definition ord : Type := nat.\n Definition lt : ord -> ord -> Type := lt.\nEnd Nat_Ord.\n\nModule Nat_Induction <: Induction Nat_Ord.\n Export Nat_Ord.\n\n Definition ind\n   : forall p : ord -> Type, (forall a, (forall x, lt x a -> p x) -> p a) -> forall a, p a.\n Proof.\n  intros p f.\n  cut (forall n k, lt k n -> p k).\n  -\n   intros Lem a.\n   apply f.\n   apply Lem.\n  -\n   apply (nat_rect (fun n => forall k, lt k n -> p k)).\n   +\n    intros k kH.\n    apply Empty_rect.\n    apply not_lt_n_0 with k.\n    apply kH.\n   +\n    intros n IHn k kH.\n    apply f.\n    intros x xH.\n    apply IHn.\n    apply le_trans with k.\n    *\n     apply xH.\n    *\n     apply le_S_n.\n     apply kH.\n Defined.\nEnd Nat_Induction.\n", "meta": {"author": "Hexirp", "repo": "progra-gist", "sha": "c2f3c7eebd1a465517af912e740f6864d9280486", "save_path": "github-repos/coq/Hexirp-progra-gist", "path": "github-repos/coq/Hexirp-progra-gist/progra-gist-c2f3c7eebd1a465517af912e740f6864d9280486/ord.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.2982724736454876}}
{"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(** Defining recursive functions by Noetherian induction.  This is a simplified\n  interface to the [Wf] module of Coq's standard library, where the functions\n  to be defined have non-dependent types, and function extensionality is assumed. *)\n\nRequire Import Axioms.\nRequire Import Wf.\nRequire Import Wf_nat.\n\nSet Implicit Arguments.\n\nSection FIX.\n\nVariables A B: Type.\nVariable R: A -> A -> Prop.\nHypothesis Rwf: well_founded R.\nVariable F: forall (x: A), (forall (y: A), R y x -> B) -> B.\n\nDefinition Fix (x: A) : B := Wf.Fix Rwf (fun (x: A) => B) F x.\n\nTheorem unroll_Fix:\n  forall x, Fix x = F (fun (y: A) (P: R y x) => Fix y).\nProof.\n  unfold Fix; intros. apply Wf.Fix_eq with (P := fun (x: A) => B). \n  intros. assert (f = g). apply functional_extensionality_dep; intros.\n  apply functional_extensionality; intros. auto. \n  subst g; auto.\nQed.\n\nEnd FIX.\n\n(** Same, with a nonnegative measure instead of a well-founded ordering *)\n\nSection FIXM.\n\nVariables A B: Type.\nVariable measure: A -> nat.\nVariable F: forall (x: A), (forall (y: A), measure y < measure x -> B) -> B.\n\nDefinition Fixm (x: A) : B := Wf.Fix (well_founded_ltof A measure) (fun (x: A) => B) F x.\n\nTheorem unroll_Fixm:\n  forall x, Fixm x = F (fun (y: A) (P: measure y < measure x) => Fixm y).\nProof.\n  unfold Fixm; intros. apply Wf.Fix_eq with (P := fun (x: A) => B). \n  intros. assert (f = g). apply functional_extensionality_dep; intros.\n  apply functional_extensionality; intros. auto. \n  subst g; auto.\nQed.\n\nEnd FIXM.\n\n\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/lib/Wfsimpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.29827247364548753}}
{"text": "From discprob.basic Require Import base sval order monad bigop_ext nify seq_ext.\nRequire Import Reals Psatz Omega.\n\nRequire ClassicalEpsilon.\nFrom mathcomp Require Import ssrfun ssreflect eqtype ssrbool seq fintype choice.\nGlobal Set Bullet Behavior \"Strict Subproofs\".\nFrom mathcomp Require Import ssreflect ssrbool ssrfun eqtype seq div choice fintype finset finfun bigop.\nRequire Import stdpp.tactics.\nLocal Open Scope R_scope.\nFrom discprob.idxval Require Import ival pival ival_dist pival_dist pidist_singleton extrema.\nFrom discprob.prob Require Import prob countable finite stochastic_order.\n\nDefinition pspec {A: Type} (m: pidist A) (P: A → Prop) :=\n  ∀ y, In_psupport y m → P y.\n\n\nSection pspec.\n\n  Context {A: Type}.\n  Implicit Types m : pidist A.\n  Implicit Types P : A → Prop.\n          \nLemma pspec_mret (x: A) P:\n  P x → pspec (mret x) P.\nProof.\n  intros HP y. intros (I&i&Hin&Heq&Hgt).\n  rewrite -Heq. inversion Hin as [Heq']. subst => //=.\nQed.\n\nLemma pspec_union m1 m2 P:\n  pspec m1 P → pspec m2 P → pspec (pidist_union m1 m2) P.\nProof.\n  intros HP1 HP2. intros a (I&i&Hin&?&?).\n  destruct Hin.\n  * eapply HP1; eauto. eexists; eauto. \n  * eapply HP2; eauto. eexists; eauto. \nQed.\n\nLemma pspec_union_inv_l m1 m2 P:\n  pspec (pidist_union m1 m2) P →\n  pspec m1 P.\nProof.\n  intros HP. intros a (I&i&Hin&?&?).\n  eapply HP. eapply In_psupport_alt. exists I; split_and!; eauto.\n  * by left.\n  * eexists; eauto.\nQed.\n\nLemma pspec_union_inv_r m1 m2 P:\n  pspec (pidist_union m1 m2) P →\n  pspec m2 P.\nProof.\n  intros HP. intros a (I&i&Hin&?&?).\n  eapply HP. eapply In_psupport_alt. exists I; split_and!; eauto.\n  * by right.\n  * eexists; eauto.\nQed.\n\nLemma In_isupport_proper (a: A) (I1 I2: ival A):\n  eq_ival I1 I2 →\n  In_isupport a I1 →\n  In_isupport a I2.\nProof.\n  intros Heq Hin.\n  destruct Heq as (w1&w2&?&?&Hind&Hval).\n  destruct Hin as (i1&Heq&Hgt).\n  assert (Hgti: Rgt_dec (val I1 i1) 0).\n  { destruct Rgt_dec => //=. }\n  unshelve (eexists).\n  { exact (sval (w1 (exist _ i1 Hgti))).  }\n  rewrite Hind Hval //=.\nQed.\n\nLemma In_psupport_proper (a: A) (I1 I2: pival A):\n  eq_pival I1 I2 →\n  In_psupport a I1 →\n  In_psupport a I2.\nProof.\n  intros Heqpi (I&i&Hin&Heq&Hval).\n  apply In_psupport_alt.\n  destruct (Heqpi) as (Hle1&Hle2).\n  destruct (Hle1 _ Hin) as (I'&HeqI'&Hin').\n  exists I'; split; auto. eapply In_isupport_proper; try eassumption.\n  subst. eexists; eauto.\nQed.\n\nGlobal Instance pspec_proper:\n  Proper (@eq_pidist A ==> pointwise_relation A iff ==> iff) pspec.\nProof.\n  intros m1 m2 Heq P1 P2 Hiff.\n  split.\n  - intros Hm x Hin. apply Hiff. apply Hm. eapply In_psupport_proper; eauto.\n    by symmetry.\n  - intros Hm x Hin. apply Hiff. apply Hm. eapply In_psupport_proper; eauto.\nQed.\n\nLemma In_isupport_iscale p (I: ival A) x:\n  In_isupport x (iscale p I) → In_isupport x I.\nProof.\n  intros (i&Heq&Hval).\n  subst. rewrite //=. exists i; split; eauto.\n  rewrite //= in Hval.\n  apply Rlt_gt.\n  destruct (Rabs_pos p).\n  * eapply Rmult_gt_reg_l; first eassumption.\n    nra.\n  * nra.\nQed.\n\nLemma In_psupport_pscale p (Is: pival A) x:\n  In_psupport x (pscale p Is) → In_psupport x Is.\nProof.\n  intros (I&i&Hin&Heq&Hval).\n  apply pscale_in_inv in Hin as (I'&?&?).\n  apply In_psupport_alt.\n  exists I'; split; eauto.\n  eapply In_isupport_iscale.\n  eapply In_isupport_proper; eauto. subst.\n  eexists; eauto.\nQed.\n\nLemma pspec_pidist_plus p Hpf m1 m2 P:\n  pspec m1 P → pspec m2 P → pspec (pidist_plus p Hpf m1 m2) P.\nProof.\n  intros HP1 HP2. intros a (I&i&Hin&?&Hval).\n  destruct Hin as (I1&I2&Hin1&Hin2&Heq).\n  subst. rewrite //= in Hval. destruct i as [i|i].\n  * eapply HP1. rewrite //=. eapply In_psupport_pscale; eauto.\n    exists I1; eauto.\n  * eapply HP2. rewrite //=. eapply In_psupport_pscale; eauto.\n    exists I2; eauto.\nQed.\n\nLemma pspec_conseq m (P Q: A → Prop):\n  pspec m P → (∀ a, P a → Q a) → pspec m Q.\nProof.\n  intros HP HPQ a Hin. apply HPQ; eauto.\nQed.\n\nLemma pspec_mbind {B: Type} (f: A → pidist B) m (P: A → Prop) (Q: B → Prop):\n  pspec m P →\n  (∀ a, P a → pspec (f a) Q) →\n  pspec (mbind f m) Q.\nProof.\n  intros Hinput Hbody b Hin.\n  edestruct (@In_psupport_bind_inv) as (x&Hin'&I&i&?&?); eauto.\n  eapply Hbody; eauto. exists I, i. eauto.\nQed.\n\nLemma pspec_bounded m (f: A → R):\n  (∃ c, pspec m (λ x, Rabs (f x) <= c)) →\n  bounded_fun_on f (λ x, In_psupport x m).\nProof.\n  intros (c&Hspec). exists c. intros. eapply Hspec; eauto.\nQed.\n\nLemma bounded_psupp_pidist_plus f p Hpf (Is1 Is2: pidist A):\n    bounded_fun_on f (λ i, In_psupport i Is1) →\n    bounded_fun_on f (λ i, In_psupport i Is2) →\n    bounded_fun_on f (λ i, In_psupport i (pidist_plus p Hpf Is1 Is2)).\nProof.\n  intros (max1&Hm1).\n  intros (max2&Hm2).\n  exists (Rmax max1 max2).\n  eapply pspec_pidist_plus.\n  * eapply pspec_conseq; rewrite /pspec; first apply Hm1.\n    intros. setoid_rewrite <-Rmax_l. auto.\n  * eapply pspec_conseq; rewrite /pspec; first apply Hm2.\n    intros. setoid_rewrite <-Rmax_r. auto.\nQed.\n\nEnd pspec.\n\nTactic Notation \"pbind\" open_constr(P) :=\n  match goal with\n  | [ |- pspec (mbind ?f ?m) ?Q ] =>\n    intros; eapply (@pspec_mbind _ _ f m P); auto\n  end.\n", "meta": {"author": "jtassarotti", "repo": "polaris", "sha": "c7873f05214351d54cacf3d8482625ee33ad3288", "save_path": "github-repos/coq/jtassarotti-polaris", "path": "github-repos/coq/jtassarotti-polaris/polaris-c7873f05214351d54cacf3d8482625ee33ad3288/proba/theories/idxval/pidist_post_cond.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.29827247364548753}}
{"text": "(** The polymorphic lambda calculus, a.k.a. System F *)\n\n(** * Description *)\n\n(** The main elements of this file are:\n\n  - Syntax: types [ty] and terms [tm], with typed DeBruijn indices.\n  - Denotational semantics:\n      - [eval_ty]: types evaluated as Coq types;\n      - [eval_tm]: terms evaluated as Coq values;\n      - [eval2_ty]: types evaluated/interpreted as (Coq) relations between term\n        values/denotations.\n  - Parametricity theorem, [parametricity]: all terms satisfy the relational\n    interpretation of their type.\n\n  Example application:\n  - [parametric_ID]: the polymorphic identity function is the only function of\n    its type.\n  *)\n\n(* begin hide *)\nRequire Import List.\nImport ListNotations.\n(* end hide *)\n\n(** * Generic (dependently typed) data structures *)\n\n(** If you're reading this for the first time, you might want to\n    skip to the next section, Polymorphic lambda calculus. *)\n\n(** ** Bijections *)\n\nRecord iso (A B : Type) : Type :=\n  { iso_from : A -> B\n  ; iso_to   : B -> A\n  }.\n\nArguments iso_from {A B} _.\nArguments iso_to {A B} _.\n\nDefinition iso_id {A} : iso A A :=\n  {| iso_from := fun i => i ; iso_to := fun i => i |}.\n\nDefinition iso_prod {A A' B B'}\n  : iso A A' -> iso B B' -> iso (A * B) (A' * B') :=\n  fun ia ib =>\n    {| iso_from := fun x => (iso_from ia (fst x), iso_from ib (snd x))\n     ; iso_to   := fun x => (iso_to ia (fst x), iso_to ib (snd x))\n    |}.\n\nDefinition iso_sum {A A' B B'}\n  : iso A A' -> iso B B' -> iso (A + B) (A' + B') :=\n  fun ia ib =>\n    {| iso_from := fun x =>\n         match x with\n         | inl y => inl (iso_from ia y)\n         | inr z => inr (iso_from ib z)\n         end\n     ; iso_to := fun x =>\n         match x with\n         | inl y => inl (iso_to ia y)\n         | inr z => inr (iso_to ib z)\n         end\n    |}.\n\nDefinition iso_eq {A A'}\n  : A = A' -> iso A A' :=\n  fun e =>\n  match e with\n  | eq_refl => iso_id\n  end.\n\n(** ** Generic collections *)\n\n(** Bounded nats *)\nFixpoint bnat (n : nat) : Type :=\n  match n with\n  | O => Empty_set\n  | S n => option (bnat n)\n  end.\n\nDefinition N0 {n : nat} : bnat (S n) := None.\nDefinition NS {n : nat} : bnat n -> bnat (S n) := Some.\n\nNotation N1 := (NS N0).\nNotation N2 := (NS N1).\nNotation N3 := (NS N2).\n\n(** Length-indexed lists (aka \"vectors\") *)\nFixpoint lilist (A : Type) (n : nat)\n  : Type :=\n  match n with\n  | O => unit\n  | S n => A * lilist A n\n  end.\n\n(** Heterogeneous lists (type-indexed lists)\n    This could also be defined with [lilist]. *)\nFixpoint hlist {A : Type} (f : A -> Type) (xs : list A)\n  : Type :=\n  match xs with\n  | [] => unit\n  | x :: xs => f x * hlist f xs\n  end.\n\n(** Heterogeneous lists indexed by two lists. *)\nFixpoint ziphlist {A B : Type} {n : nat} (f : A -> B -> Type)\n  : lilist A n -> lilist B n -> Type :=\n  match n with\n  | O => fun _ _ => unit\n  | S n => fun ts1 ts2 =>\n      (f (fst ts1) (fst ts2) * ziphlist f (snd ts1) (snd ts2))%type\n  end.\n\n(** *** Bounded lookup *)\n\nFixpoint lookup_lilist {A : Type} {n : nat}\n  : bnat n -> lilist A n -> A :=\n  match n with\n  | O => fun y => match y with end\n  | S n => fun tv ts =>\n    match tv with\n    | None => fst ts\n    | Some tv => lookup_lilist tv (snd ts)\n    end\n  end.\n\nFixpoint lookup_list {A : Type} (xs : list A) : bnat (length xs) -> A :=\n  match xs with\n  | [] => fun v => match v with end\n  | x :: xs => fun v =>\n    match v with\n    | None => x\n    | Some v => lookup_list xs v\n    end\n  end.\n\nFixpoint lookup_hlist {A} {f : A -> Type} {vs : list A}\n  : forall v : bnat (length vs), hlist f vs -> f (lookup_list vs v) :=\n  match vs with\n  | [] => fun v => match v with end\n  | t :: vs => fun v vls =>\n    match v with\n    | None => fst vls\n    | Some v => lookup_hlist v (snd vls)\n    end\n  end.\n\nFixpoint lookup_ziphlist {A B} {f : A -> B -> Type} {n : nat}\n  : forall {ts1 : lilist A n} {ts2 : lilist B n} (tv : bnat n),\n      ziphlist f ts1 ts2 -> f (lookup_lilist tv ts1) (lookup_lilist tv ts2) :=\n  match n with\n  | O => fun _ _ tv => match tv with end\n  | S n => fun ts1 ts2 tv rs =>\n      match tv with\n      | None => fst rs\n      | Some tv => lookup_ziphlist tv (snd rs)\n      end\n  end.\n\nDefinition rel_list {n : nat} : lilist Type n -> lilist Type n -> Type :=\n  ziphlist (fun a b => a -> b -> Prop).\n\n(** *** Insertion *)\n\n(** \"Insert\" a number in the range [[0 .. n-1]] into the range [[0 .. n]],\n    by sending [[0 .. m-1]] to itself, and [[m .. n-1]] to [[m+1 .. n]]. *)\nFixpoint insert_bnat (m : nat) {n : nat} : bnat n -> bnat (S n) :=\n  match n with\n  | O => fun v => match v with end\n  | S n => fun v =>\n    match m with\n    | O => Some v\n    | S m =>\n      match v with\n      | None => None\n      | Some v => Some (insert_bnat m v)\n      end\n    end\n  end.\n\n(** Insert an element at position [n]. *)\nFixpoint insert_lilist {A} (m : nat) (t0 : A) {n : nat}\n  : lilist A n -> lilist A (S n) :=\n  match m with\n  | O => fun ts => (t0, ts)\n  | S m =>\n    match n with\n    | O => fun _ => (t0, tt)\n    | S n => fun ts => (fst ts, insert_lilist m t0 (snd ts))\n    end\n  end.\n\nFixpoint eq_insert_lookup_lilist (m : nat) (t0 : Type) {n : nat}\n  : forall {ts : lilist Type n} (tv : bnat n),\n        lookup_lilist tv ts\n      = lookup_lilist (insert_bnat m tv) (insert_lilist m t0 ts) :=\n  match n with\n  | O => fun ts tv => match tv with end\n  | S n => fun ts tv =>\n    match m with\n    | O => eq_refl\n    | S m =>\n      match tv with\n      | None => eq_refl\n      | Some tv => eq_insert_lookup_lilist m t0 tv\n      end\n    end\n  end.\n\nDefinition iso_insert_lookup_lilist (m : nat) (t0 : Type) {n : nat}\n  : forall {ts : lilist Type n} (tv : bnat n),\n      iso (lookup_lilist tv ts) (lookup_lilist (insert_bnat m tv) (insert_lilist m t0 ts)) :=\n  fun ts tv => iso_eq (eq_insert_lookup_lilist m t0 tv).\n\nFixpoint insert_lookup_rel_list (m : nat) {n : nat}\n  {t01 t02 : Type} (r0 : t01 -> t02 -> Prop)\n  : forall {ts01 ts02 : lilist Type n},\n      rel_list ts01 ts02 -> rel_list (insert_lilist m t01 ts01) (insert_lilist m t02 ts02) :=\n  match m with\n  | O => fun _ _ rs => (r0, rs)\n  | S m =>\n    match n with\n    | O => fun _ _ rs => (r0, rs)\n    | S n => fun _ _ rs => (fst rs, insert_lookup_rel_list m r0 (snd rs))\n    end\n  end.\n\n(** * Polymorphic lambda calculus *)\n\n(** ** Syntax *)\n\n(** *** Types *)\n\n(**\n<<\nt ::= t -> t     (* Function *)\n    | forall t   (* Type generalization *)\n    | i          (* Type variable (DeBruijn index) *)\n    | unit       (* Unit type *)\n    | t * t      (* Product *)\n    | t + t      (* Sum *)\n>>\n  *)\nInductive ty (n : nat) : Type :=\n| Arrow : ty n -> ty n -> ty n\n| Forall : ty (S n) -> ty n\n| Tyvar : bnat n -> ty n\n\n(* Basic data types *)\n| Unit : ty n\n| Prod : ty n -> ty n -> ty n\n| Sum : ty n -> ty n -> ty n\n.\n\nArguments Arrow  {n}.\nArguments Forall {n}.\nArguments Tyvar  {n}.\n\nArguments Unit {n}.\nArguments Prod {n}.\nArguments Sum  {n}.\n\n(** **** Notations *)\n\nDelimit Scope ty_scope with ty.\nBind Scope ty_scope with ty.\n\nInfix \"->\" := Arrow : ty_scope.\nCoercion Tyvar : bnat >-> ty.\n\nDefinition V0 {n} : bnat (S n) := N0.\nDefinition V1 {n} : bnat (S (S n)) := NS N0.\nDefinition V2 {n} : bnat (S (S (S n))) := NS (NS N0).\n\n(** Shift *)\nFixpoint shift_ty (m : nat) {n : nat} (t : ty n) : ty (S n) :=\n  match t with\n  | Arrow t1 t2 => Arrow (shift_ty m t1) (shift_ty m t2)\n  | Forall t => Forall (shift_ty (S m) t)\n  | Tyvar v => @Tyvar (S n) (insert_bnat m v)\n  | Unit => Unit\n  | Prod t1 t2 => Prod (shift_ty m t1) (shift_ty m t2)\n  | Sum t1 t2 => Sum (shift_ty m t1) (shift_ty m t2)\n  end.\n\n(** *** Terms *)\n\nSection Constants.\n\nContext {n : nat}.\n\n(** Constants *)\nInductive cn : ty n -> Type :=\n| One : cn Unit\n  (* [unit] *)\n\n| Pair : cn (Forall (Forall (V1 -> V0 -> Prod V1 V0)))\n  (* [forall a b, a -> b -> a * b] *)\n\n| Fst : cn (Forall (Forall (Prod V1 V0 -> V1)))\n  (* [forall a b, a * b -> a] *)\n\n| Snd : cn (Forall (Forall (Prod V1 V0 -> V0)))\n  (* [forall a b, a * b -> b] *)\n\n| Inl : cn (Forall (Forall (V1 -> Sum V1 V0)))\n  (* [forall a b, a -> a + b] *)\n\n| Inr : cn (Forall (Forall (V0 -> Sum V1 V0)))\n  (* [forall a b, b -> a + b] *)\n\n| Case : cn (Forall (Forall (Forall (\n    (V2 -> V0) ->\n    (V1 -> V0) ->\n    Sum V2 V1 -> V0))))\n  (* [forall a b c, (a -> c) -> (b -> c) -> (a + b -> c)] *)\n.\n\nEnd Constants.\n\n(**\n<<\nu ::= tyfun u   (* Type abstraction *)\n    | fun u     (* Value abstraction *)\n    | u u       (* Application *)\n    | i         (* Variable *)\n    | c         (* Constant *)\n>>\n  *)\nInductive tm (n : nat) (vs : list (ty n)) : ty n -> Type :=\n| TAbs {t}\n  : tm (S n) (map (shift_ty 0) vs) t ->\n    tm n vs (Forall t)\n| Abs {t1 t2}\n  : tm n (t1 :: vs) t2 ->\n    tm n vs (Arrow t1 t2)\n| App {t1 t2}\n  : tm n vs (Arrow t1 t2) ->\n    tm n vs t1 ->\n    tm n vs t2\n| Var (v : bnat (length vs))\n  : tm n vs (lookup_list vs v)\n| Con {t}\n  : cn t ->\n    tm n vs t\n.\n\nArguments TAbs {n vs t}.\nArguments Abs  {n vs t1 t2}.\nArguments App  {n vs t1 t2}.\nArguments Var  {n vs}.\nArguments Con  {n vs t}.\n\nDelimit Scope tm_scope with tm.\nBind Scope tm_scope with tm.\n\nInfix \"@@\" := App (at level 40) : tm_scope.\n\n(** Closed term *)\nNotation tm0 := (tm 0 []).\n\n(** ** Semantics *)\n\n(** *** Types *)\n\n(** Semantics of types as Coq types *)\nFixpoint eval_ty {n : nat} (ts : lilist Type n) (t : ty n)\n  : Type :=\n  match t with\n  | Arrow t1 t2 => eval_ty ts t1 -> eval_ty ts t2\n  | Forall t => forall (t0 : Type), @eval_ty (S n) (t0, ts) t\n  | Tyvar tv => lookup_lilist tv ts\n  | Unit => unit\n  | Prod t1 t2 => eval_ty ts t1 * eval_ty ts t2\n  | Sum t1 t2 => eval_ty ts t1 + eval_ty ts t2\n  end.\n\n(** Semantics of types in the empty context. *)\nDefinition eval_ty0 : ty 0 -> Type := @eval_ty 0 tt.\n\n(** *** Terms *)\n\n(** To evaluate terms, we need some auxiliary functions to update the context\n  when new type variables are introduced, together with the [Type] that the\n  variable denotes. *)\n\n(** Add a new variable-[Type] binding to the context of a term *)\nFixpoint shift_eval (m : nat) {n : nat} {ts : lilist Type n} (t0 : Type) (t : ty n)\n  : iso (eval_ty ts t) (@eval_ty (S n) (insert_lilist m t0 ts) (shift_ty m t)) :=\n  match t with\n  | Arrow t1 t2 =>\n      let i1 := shift_eval m t0 t1 in\n      let i2 := shift_eval m t0 t2 in\n      {| iso_from := fun f x1 => iso_from i2 (f (iso_to i1 x1))\n       ; iso_to := fun f x0 => iso_to i2 (f (iso_from i1 x0))\n      |}\n  | Forall t =>\n      {| iso_from := fun (f : forall a : Type, @eval_ty (S n) (a, ts) t) a =>\n           let i := @shift_eval (S m) (S n) (a, ts) t0 t in\n           iso_from i (f a)\n       ; iso_to := fun (f : forall a : Type, @eval_ty (S (S n)) (a, _) (shift_ty (S m) t)) a =>\n           let i := @shift_eval (S m) (S n) (a, _) t0 t in\n           iso_to i (f a)\n      |} : iso (forall (a : Type), @eval_ty (S n) (a, ts) t) _\n  | Tyvar tv => iso_insert_lookup_lilist m t0 tv\n  | Unit => iso_id\n  | Prod t1 t2 => iso_prod (shift_eval m t0 t1) (shift_eval m t0 t2)\n  | Sum t1 t2 => iso_sum (shift_eval m t0 t1) (shift_eval m t0 t2)\n  end.\n\n(** Add a new variable-[Type] binding to the context of a context. *)\nFixpoint shift_hlist {n : nat} {ts : lilist Type n} {vs : list (ty n)} (t0 : Type)\n  : hlist (eval_ty ts) vs -> hlist (@eval_ty (S n) (t0, ts)) (map (shift_ty 0) vs) :=\n  match vs with\n  | [] => fun _ => tt\n  | t :: vs => fun ts =>\n    (iso_from (shift_eval 0 t0 _) (fst ts), shift_hlist t0 (snd ts))\n  end.\n\n(** Semantics of constants as Coq values *)\nDefinition eval_cn {n : nat} (ts : lilist Type n) {t : ty n} (c : cn t)\n  : eval_ty ts t :=\n  match c with\n  | One => tt\n  | Pair => @pair\n  | Fst => @fst\n  | Snd => @snd\n  | Inl => @inl\n  | Inr => @inr\n  | Case => fun _ _ _ f g x =>\n    match x with\n    | inl y => f y\n    | inr z => g z\n    end\n  end.\n\n(** Semantics of terms as Coq values *)\nFixpoint eval_tm\n  {n : nat} (ts : lilist Type n)\n  {vs : list (ty n)} (vls : hlist (eval_ty ts) vs)\n  {t : ty n} (u : tm n vs t)\n  : eval_ty ts t :=\n  match u with\n  | TAbs u => fun t0 => @eval_tm (S n) (t0, ts) _ (shift_hlist t0 vls) _ u\n  | Abs u => fun x => @eval_tm _ ts (_ :: vs) (x, vls) _ u\n  | App u1 u2 => (eval_tm ts vls u1) (eval_tm ts vls u2)\n  | Var v => lookup_hlist v vls\n  | Con c => eval_cn _ c\n  end.\n\n(** Semantics of terms in the empty context *)\nDefinition eval_tm0 {t : ty 0} : tm0 t -> eval_ty0 t :=\n  @eval_tm 0 tt [] tt t.\n\n(** *** Types as relations *)\n\n(** Relational semantics of types *)\nFixpoint eval2_ty {n : nat}\n  {ts1 ts2 : lilist Type n}\n  (rs : rel_list ts1 ts2)\n  (t : ty n)\n  : eval_ty ts1 t -> eval_ty ts2 t -> Prop :=\n  match t with\n  | Arrow t1 t2 => fun f1 f2 =>\n      forall x1 x2, eval2_ty rs t1 x1 x2 -> eval2_ty rs t2 (f1 x1) (f2 x2)\n  | Forall t => fun f1 f2 =>\n      forall (t01 t02 : Type) (r0 : t01 -> t02 -> Prop),\n        @eval2_ty (S n) (t01, ts1) (t02, ts2) (r0, rs) t (f1 t01) (f2 t02)\n  | Tyvar tv => lookup_ziphlist tv rs\n\n  | Unit => fun _ _ => True\n  | Prod t1 t2 => fun x1 x2 =>\n      eval2_ty rs t1 (fst x1) (fst x2) /\\\n      eval2_ty rs t2 (snd x1) (snd x2)\n  | Sum t1 t2 => fun x1 x2 =>\n      match x1, x2 with\n      | inl y1, inl y2 => eval2_ty rs t1 y1 y2\n      | inr z1, inr z2 => eval2_ty rs t2 z1 z2\n      | _, _ => False\n      end\n  end.\n\n(** Relational semantics in the empty context *)\nDefinition eval2_ty0 (t : ty 0) : eval_ty0 t -> eval_ty0 t -> Prop :=\n  @eval2_ty 0 tt tt tt t.\n\n(** Relational semantics of contexts *)\nFixpoint eval2_ctx {n : nat} {vs : list (ty n)}\n  : forall\n      {ts1 ts2 : lilist Type n} (rs : rel_list ts1 ts2)\n      (vls1 : hlist (eval_ty ts1) vs) (vls2 : hlist (eval_ty ts2) vs),\n        Prop :=\n  match vs with\n  | [] => fun _ _ _ _ _ => True\n  | v :: vs => fun _ _ rs vls1 vls2 =>\n    eval2_ty rs v (fst vls1) (fst vls2) /\\\n    eval2_ctx rs (snd vls1) (snd vls2)\n  end.\n\n(** ** Parametricity theorem *)\n\n(* TODO: generalize *)\nLemma param_insert_bnat_from (m : nat)\n  : forall {n : nat}\n      (ts1 ts2 : lilist Type n)\n      (rs : rel_list ts1 ts2)\n      (v : bnat n)\n      (t01 t02 : Type) (r0 : t01 -> t02 -> Prop)\n      (vl1 : lookup_lilist v ts1) (vl2 : lookup_lilist v ts2)\n      , lookup_ziphlist v rs vl1 vl2 ->\n        lookup_ziphlist (insert_bnat m v) (insert_lookup_rel_list m r0 rs)\n          (iso_from (iso_insert_lookup_lilist m t01 v) vl1)\n          (iso_from (iso_insert_lookup_lilist m t02 v) vl2).\nProof.\n  induction m; intros; cbn; (destruct n; [ destruct v |]); auto.\n  destruct v; cbn; auto.\n  apply IHm. auto.\nQed.\n\nLemma param_insert_bnat_to (m : nat)\n  : forall {n : nat}\n      (ts1 ts2 : lilist Type n)\n      (rs : rel_list ts1 ts2)\n      (v : bnat n)\n      (t01 t02 : Type) (r0 : t01 -> t02 -> Prop)\n      (vl1' : lookup_lilist (insert_bnat m v) (insert_lilist m t01 ts1))\n      (vl2' : lookup_lilist (insert_bnat m v) (insert_lilist m t02 ts2))\n      , lookup_ziphlist (insert_bnat m v) (insert_lookup_rel_list m r0 rs) vl1' vl2'->\n        lookup_ziphlist v rs\n          (iso_to (iso_insert_lookup_lilist m t01 v) vl1')\n          (iso_to (iso_insert_lookup_lilist m t02 v) vl2').\nProof.\n  induction m; intros; cbn; (destruct n; [ destruct v |]); auto.\n  destruct v; cbn in *; auto.\n  apply IHm in H. auto.\nQed.\n\n(* TODO: get rid of this hack of not unfolding these function. *)\nSection Hack_param_shift.\nArguments lookup_ziphlist : simpl never.\nArguments lookup_lilist : simpl never.\n\nLemma param_shift (m : nat) {n : nat}\n  (ts1 ts2 : lilist Type n)\n  (rs : rel_list ts1 ts2)\n  (t : ty n)\n  (t01 t02 : Type)\n  (r0 : t01 -> t02 -> Prop)\n  : (forall (vl1 : eval_ty ts1 t) (vl2 : eval_ty ts2 t),\n       eval2_ty rs t vl1 vl2 ->\n       @eval2_ty (S n) _ _ (insert_lookup_rel_list m r0 rs) (shift_ty m t)\n         (iso_from (shift_eval m t01 _) vl1)\n         (iso_from (shift_eval m t02 _) vl2))\n  /\\ (forall vl1' vl2',\n       eval2_ty (insert_lookup_rel_list m r0 rs) (shift_ty m t) vl1' vl2' ->\n       eval2_ty rs t\n         (iso_to (shift_eval m t01 _) vl1')\n         (iso_to (shift_eval m t02 _) vl2')).\nProof.\n  revert m.\n  induction t; cbn; intros; auto.\n  - edestruct IHt1, IHt2; auto.\n  - split; intros;\n      eapply (IHt (_, ts1) (_, ts2) (r1, rs) (S m));\n      eauto.\n  - split; intros.\n    + auto using param_insert_bnat_from.\n    + eauto using param_insert_bnat_to.\n  - split; intros; destruct H; split; apply IHt1 + apply IHt2; auto.\n  - split; intros; destruct (_ : _ + _), (_ : _ + _);\n      contradiction + apply IHt1 + apply IHt2; auto.\nQed.\n\nEnd Hack_param_shift.\n\nLemma param_tabs {n : nat}\n  (ts1 ts2 : lilist Type n)\n  (rs : rel_list ts1 ts2)\n  (vs : list (ty n)) (vls1 : hlist (eval_ty ts1) vs) (vls2 : hlist (eval_ty ts2) vs)\n  (t01 t02 : Type)\n  (r0 : t01 -> t02 -> Prop)\n  : eval2_ctx rs vls1 vls2 ->\n    @eval2_ctx (S n) _ (t01, ts1) (t02, ts2) (r0, rs)\n      (shift_hlist t01 vls1)\n      (shift_hlist t02 vls2).\nProof.\n  induction vs; auto.\n  destruct vls1, vls2; cbn.\n  intros []; split; auto.\n  apply (param_shift 0); auto.\nQed.\n\nLemma param_var {n : nat}\n  (ts1 ts2 : lilist Type n)\n  (rs : rel_list ts1 ts2)\n  (vs : list (ty n)) (vls1 : hlist (eval_ty ts1) vs) (vls2 : hlist (eval_ty ts2) vs)\n  (v : bnat (length vs))\n  : eval2_ctx rs vls1 vls2 ->\n    eval2_ty rs (lookup_list vs v) (lookup_hlist v vls1) (lookup_hlist v vls2).\nProof.\n  induction vs; [ contradiction | ].\n  destruct vls1, vls2, v; cbn; intros []; auto.\nQed.\n\nLemma param_cn {n : nat}\n  (ts1 ts2 : lilist Type n)\n  (rs : rel_list ts1 ts2)\n  (t : ty n)\n  (c : cn t)\n  : eval2_ty rs t (eval_cn ts1 c) (eval_cn ts2 c).\nProof.\n  destruct c; simpl; auto; intros.\n  - apply H.\n  - apply H.\n  - do 2 destruct (_ : _ + _); contradiction + auto.\nQed.\n\n(** Main theorem! Every term satisfies the logical relation of its type. *)\nTheorem parametricity (n : nat)\n  (ts1 ts2 : lilist Type n)\n  (rs : rel_list ts1 ts2)\n  (vs : list (ty n)) (vls1 : hlist (eval_ty ts1) vs) (vls2 : hlist (eval_ty ts2) vs)\n  (t : ty n)\n  (u : tm n vs t)\n  : eval2_ctx rs vls1 vls2 -> eval2_ty rs t (eval_tm ts1 vls1 u) (eval_tm ts2 vls2 u).\nProof.\n  induction u; cbn; intros; auto.\n  - (* TAbs u *)\n    auto using param_tabs.\n\n  - (* Abs u *)\n    apply IHu; split; auto.\n\n  - (* App u1 u2 *)\n    pose proof H as H'.\n    apply IHu1 in H.\n    apply IHu2 in H'.\n    auto.\n\n  - (* Var v *)\n    apply param_var; auto.\n\n  - (* Con c *)\n    apply param_cn.\nQed.\n\n(** Parametricity theorem in the empty context. *)\nTheorem parametricity0 (t : ty 0) (u : tm0 t)\n  : eval2_ty0 t (eval_tm0 u) (eval_tm0 u).\nProof.\n  apply parametricity. constructor.\nQed.\n\n(** * Examples *)\n\n(** Type of the polymorphic identity function *)\nDefinition ID_ty {n} : ty n := (Forall (V0 -> V0)).\n\nCompute (eval_ty0 ID_ty).\nCompute (eval2_ty0 ID_ty).\n\n(** Any term [u] of the same type as the polymorphic identity behaves like the\n    identity function. Let [f] be the interpretation of [u] ([f := eval_tm0 u]),\n    then [f _ a = a].\n  *)\nExample parametric_ID (t : tm0 ID_ty) (A : Type) (a : A)\n  : (eval_tm0 t) A a = a.\nProof.\n  pose proof (parametricity0 ID_ty t A A (fun x1 x2 => x1 = a) a a) as H.\n  simpl in H; auto.\nQed.\n", "meta": {"author": "Lysxia", "repo": "system-F", "sha": "d5ada3ed4673fd76638b50884f0e4dc1dcf76c8f", "save_path": "github-repos/coq/Lysxia-system-F", "path": "github-repos/coq/Lysxia-system-F/system-F-d5ada3ed4673fd76638b50884f0e4dc1dcf76c8f/PLC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.29827247364548753}}
{"text": "(**\n * QueueData.v\n *\n * Definitions and properties of queue and node data.\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.\n(** CertiKOS layer library *)\nRequire Import Structures.\nRequire Import AbstractData.\nRequire Import AbstractionRelation.\nRequire Import SimulationRelation.\nRequire Import CPrimitives.\nRequire Import MemWithData.\nRequire Import Decision.\n\nRequire Import TutoLib.\n\n(** This file contains the definitions of the abstract data for the queue\n  layers as well as some auxiliary lemmas. The queue is represented at the low\n  level by a doubly-linked list where indices into a fixed-size array are used\n  instead of pointers. This is then abstracted in the top layer to a\n  Coq [list]. This example differs from the other two by having two layers at\n  the same level ([Node] and [QueueIntro]), and then building on top of their\n  composition. One consequence of this is that the both the abstract data as\n  well as the [match_data] and [relate_data] relations must be the same for\n  both layers. For this reason, these definitions are in this file instead of\n  their usual places. *)\n\nOpen Scope Z_scope.\n\nDefinition MAX_NODES : Z := 1024.\nFact MAX_NODES_range : 0 < 12 * MAX_NODES <= Int.max_unsigned.\nProof. cbv. intuition. Qed.\n\nGlobal Opaque MAX_NODES.\n\n(** ** Node Representations *)\nSection NODE_DATA.\n\n  (** *** Low Level Definition *)\n\n  (** The low level node represents a node in a typical C doubly-linked list *)\n  Inductive node_low : Type :=\n  | NodeUndef\n  | Node (data: Z) (next: Z) (prev: Z).\n\n  Definition node_pool := ZMap.t node_low.\n\n  (** Struct offsets *)\n  Definition data_off := 0.\n  Definition next_off := 4.\n  Definition prev_off := 8.\n  Definition node_sz := 12.\n\n  (** A node is valid if it only points to nodes in the appropriate range. *)\n  Inductive node_valid : node_low -> Prop :=\n  | NodeOk: forall d nxt prv,\n      0 <= nxt <= MAX_NODES ->\n      0 <= prv <= MAX_NODES ->\n      node_valid (Node d nxt prv).\n\n  (** Sanity check. *)\n  Remark node_undef_not_valid : ~node_valid NodeUndef.\n  Proof. red; intros; inv H. Qed.\n\n  (** *** Abstract Definition *)\n\n  (** The high level node just stores data and keeps track of whether it is\n    currently in the queue. *)\n  Inductive abs_node : Type :=\n  | AbsNodeUndef\n  | AbsNode (data: Z) (inQ: bool).\n\n  Definition abs_node_pool := ZMap.t abs_node.\n\n  (** All non-undef nodes are valid here. *)\n  Inductive abs_node_valid : abs_node -> Prop :=\n  | AbsNodeOk: forall d inq,\n      abs_node_valid (AbsNode d inq).\n\n  Remark abs_node_undef_not_valid : ~abs_node_valid AbsNodeUndef.\n  Proof. red; intros; inv H. Qed.\n\nEnd NODE_DATA.\n\nLtac unfold_node_fields :=\n  unfold node_sz, data_off, next_off, prev_off in *.\n\n(** ** Queue Representations *)\nSection QUEUE_DATA.\n\n  (** *** Low Level Definition *)\n\n  (** The low level queue is also essentially a C-style doubly-linked list. *)\n  Inductive queue_low : Type :=\n  | QueueUndef\n  | Queue (head: Z) (tail: Z).\n\n  (** Struct offsets. *)\n  Definition head_off := 0.\n  Definition tail_off := 4.\n  Definition queue_sz := 8.\n\n  (** A queue is valid if its head and tail are in the appropriate range. *)\n  Inductive queue_valid : queue_low -> Prop :=\n  | QVOk: forall hd tl,\n      0 <= hd <= MAX_NODES ->\n      0 <= tl <= MAX_NODES ->\n      queue_valid (Queue hd tl).\n\n  Remark queue_undef_not_valid : ~queue_valid QueueUndef.\n  Proof. red; intros; inv H. Qed.\n\n  (** ** Abstract Definition *)\n\n  (** The high level queue is just a Coq [list]. *)\n  Inductive abs_queue : Type :=\n  | AbsQueueUndef\n  | AbsQueue (q: list Z).\n\n  (** Here a queue is valid if all of its nodes are in the right range. *)\n  Inductive abs_queue_valid : abs_queue -> Prop :=\n  | AQVQOk: forall q,\n      Forall (fun nd => 0 <= nd < MAX_NODES) q ->\n      abs_queue_valid (AbsQueue q).\n\n  Remark abs_queue_undef_not_valid : ~abs_queue_valid AbsQueueUndef.\n  Proof. red; intros; inv H. Qed.\n\n  (** The elements of a queue are unique if each appears exactly once. *)\n  Inductive abs_queue_unique : abs_queue -> Prop :=\n  | AQUOk: forall q,\n      Forall (fun nd => count_occ zeq q nd = 1%nat) q ->\n      abs_queue_unique (AbsQueue q).\n\n  (** The [inQ] flag of [abs_node] should actually mean the node is in the\n    queue. *)\n  Inductive In_Q_inQ : abs_queue -> Z -> abs_node_pool -> Prop :=\n  | IQOk: forall q nd anpool dat inQ,\n      ZMap.get nd anpool = AbsNode dat inQ ->\n      (inQ = true <-> In nd q) ->\n      In_Q_inQ (AbsQueue q) nd anpool.\n\nEnd QUEUE_DATA.\n\nLtac unfold_queue_fields :=\n  unfold queue_sz, head_off, tail_off in *.\n\n(** ** Abstract Data *)\nSection ABS_DATA.\n\n  Context `{Hmem: BaseMemoryModel}.\n\n  (** The abstract data tracks both the low level and high level queue\n    representations, but each layer will only place invariants on one\n    of them. *)\n  Record abs_data : Type := {\n    init_flag: bool;\n    npool: node_pool;\n    queue: queue_low;\n    anpool: abs_node_pool;\n    aqueue: abs_queue\n  }.\n\n  Definition abs_data_init : abs_data :=\n    {|\n      init_flag := false;\n      npool := ZMap.init NodeUndef;\n      queue := QueueUndef;\n      anpool := ZMap.init AbsNodeUndef;\n      aqueue := AbsQueueUndef\n    |}.\n\n  Instance boot_data_ops : AbstractDataOps unit :=\n    {|\n      init_data := tt;\n      data_inv := fun _ => True;\n      data_inject := fun _ _ _ => True\n    |}.\n\n  Instance boot_data_data : AbstractData unit.\n  Proof. repeat constructor. Qed.\n\n  Definition boot_layerdata : layerdata :=\n    {|\n      ldata_type := unit;\n      ldata_ops  := boot_data_ops;\n      ldata_prf  := boot_data_data\n    |}.\n\n  Definition boot_L : clayer boot_layerdata := ∅.\n\n  (** The [Intro] layer represents the composition of the [Node] and\n    [QueueIntro] layers. *)\n  Record intro_inv (d: abs_data) : Prop := {\n    npool_valid: forall node,\n      let n := ZMap.get node (npool d) in\n      0 <= node < MAX_NODES ->\n      (n = NodeUndef \\/ node_valid n);\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 intro_data_ops : AbstractDataOps abs_data :=\n    {|\n      init_data := abs_data_init;\n      data_inv := intro_inv;\n      data_inject := fun _ _ _ => True\n    |}.\n\n  Instance intro_data_data : AbstractData abs_data.\n  Proof.\n    constructor; constructor; cbn; intros; try congruence.\n    rewrite ZMap.gi. auto.\n  Qed.\n\n  Definition intro_layerdata : layerdata :=\n    {|\n      ldata_type := abs_data;\n      ldata_ops  := intro_data_ops;\n      ldata_prf  := intro_data_data\n    |}.\n\n  (** Some functions to allow us to fake a record update syntax. *)\n  Definition update_init_flag new abs :=\n    {|\n      init_flag := new;\n      npool := npool abs;\n      queue := queue abs;\n      anpool := anpool abs;\n      aqueue := aqueue abs\n    |}.\n\n  Definition update_npool new abs :=\n    {|\n      init_flag := init_flag abs;\n      npool := new;\n      queue := queue abs;\n      anpool := anpool abs;\n      aqueue := aqueue abs\n    |}.\n\n  Definition update_queue new abs :=\n    {|\n      init_flag := init_flag abs;\n      npool := npool abs;\n      queue := new;\n      anpool := anpool abs;\n      aqueue := aqueue abs\n    |}.\n\n  Definition update_anpool new abs :=\n    {|\n      init_flag := init_flag abs;\n      npool := npool abs;\n      queue := queue abs;\n      anpool := new;\n      aqueue := aqueue abs\n    |}.\n\n  Definition update_aqueue new abs :=\n    {|\n      init_flag := init_flag abs;\n      npool := npool abs;\n      queue := queue abs;\n      anpool := anpool abs;\n      aqueue := new\n    |}.\n\nEnd ABS_DATA.\n\n(** Shorthand for updating one field of a record. *)\nNotation \"abs {init_flag : new }\" := (update_init_flag new abs) (at level 1).\nNotation \"abs {npool : new }\" := (update_npool new abs) (at level 1).\nNotation \"abs {queue : new }\" := (update_queue new abs) (at level 1).\nNotation \"abs {anpool : new }\" := (update_anpool new abs) (at level 1).\nNotation \"abs {aqueue : new }\" := (update_aqueue new abs) (at level 1).\n\n(** ** Node Properties *)\nSection NODE_DATA_PROPS.\n\n  Context `{Hmem: BaseMemoryModel}.\n\n  (** Just like in the container example, we write some general lemmas to\n    allow us to rewrite the [Ptrofs] expressions into something simpler. *)\n  Lemma node_fields_off_rewrite : forall foff i,\n    0 <= Int.unsigned i < MAX_NODES ->\n    0 <= foff < node_sz ->\n    (Ptrofs.unsigned\n      (Ptrofs.add\n        (Ptrofs.add Ptrofs.zero\n          (Ptrofs.mul (Ptrofs.repr node_sz) (Ptrofs.of_intu i)))\n        (Ptrofs.repr foff))) = node_sz * Int.unsigned i + foff.\n  Proof.\n    intros ? ? Hi_range Hoff_range.\n    pose proof MAX_NODES_range as Hmn_range.\n    pose proof int_ptrofs_max as Hint_ptr.\n    rewrite Ptrofs.add_zero_l.\n    unfold Ptrofs.add, Ptrofs.mul, Ptrofs.zero, Ptrofs.of_intu, Ptrofs.of_int.\n    unfold_node_fields.\n    repeat rewrite Ptrofs.unsigned_repr; omega.\n  Qed.\n\n  Corollary node_fields_store_ok : forall foff m m' b i v,\n    0 <= Int.unsigned i < MAX_NODES ->\n    0 <= foff < node_sz ->\n    Mem.store Mint32 m b (node_sz * Int.unsigned i + foff) v = Some m' ->\n    Mem.store Mint32 m b\n      (Ptrofs.unsigned\n        (Ptrofs.add\n          (Ptrofs.add Ptrofs.zero\n            (Ptrofs.mul (Ptrofs.repr node_sz) (Ptrofs.of_intu i)))\n          (Ptrofs.repr foff))) v = Some m'.\n  Proof. intros; rewrite node_fields_off_rewrite; auto. Qed.\n\n  Corollary node_fields_load_ok : forall foff m b i v,\n    0 <= Int.unsigned i < MAX_NODES ->\n    0 <= foff < node_sz ->\n    Mem.load Mint32 m b (node_sz * Int.unsigned i + foff) = Some v ->\n    Mem.load Mint32 m b\n      (Ptrofs.unsigned\n        (Ptrofs.add\n          (Ptrofs.add Ptrofs.zero\n            (Ptrofs.mul (Ptrofs.repr node_sz) (Ptrofs.of_intu i)))\n          (Ptrofs.repr foff))) = Some v.\n  Proof. intros; rewrite node_fields_off_rewrite; auto. Qed.\n\n  Lemma node_fields_align : forall i off,\n    (off = data_off \\/ off = next_off \\/ off = prev_off) ->\n    (4 | node_sz * i + off).\n  Proof.\n    intros; unfold_node_fields.\n    replace (12 * i) with (4 * (3 * i)) by omega.\n    apply Z.divide_add_r; [apply Z.divide_factor_l |].\n    destruct H as [? | [? | ? ]]; subst.\n    - now exists 0.\n    - now exists 1.\n    - now exists 2.\n  Qed.\n\nEnd NODE_DATA_PROPS.\n\n(** Queue Properties *)\nSection QUEUE_DATA_PROPS.\n\n  Context `{Hmem: BaseMemoryModel}.\n\n  Lemma queue_fields_off_rewrite : forall foff,\n    0 <= foff < queue_sz ->\n    (Ptrofs.unsigned (Ptrofs.add Ptrofs.zero (Ptrofs.repr foff))) = foff.\n  Proof.\n    intros ? Hoff_range.\n    pose proof int_ptrofs_max as Hint_ptr.\n    rewrite Ptrofs.add_zero_l.\n    unfold_queue_fields.\n    rewrite Ptrofs.unsigned_repr; cbn in *; omega.\n  Qed.\n\n  Corollary queue_fields_store_ok : forall foff m m' b v,\n    0 <= foff < queue_sz ->\n    Mem.store Mint32 m b foff v = Some m' ->\n    Mem.store Mint32 m b\n      (Ptrofs.unsigned (Ptrofs.add Ptrofs.zero (Ptrofs.repr foff))) v = Some m'.\n  Proof. intros; rewrite queue_fields_off_rewrite; auto. Qed.\n\n  Corollary queue_fields_load_ok : forall foff m b v,\n    0 <= foff < queue_sz ->\n    Mem.load Mint32 m b foff = Some v ->\n    Mem.load Mint32 m b\n      (Ptrofs.unsigned (Ptrofs.add Ptrofs.zero (Ptrofs.repr foff))) = Some v.\n  Proof. intros; rewrite queue_fields_off_rewrite; auto. Qed.\n\n  Lemma queue_fields_align : forall off,\n    (off = head_off \\/ off = tail_off) ->\n    (4 | off).\n  Proof.\n    intros; unfold_queue_fields; destruct H.\n    - now exists 0.\n    - now exists 1.\n  Qed.\n\n  (** Some additional lemmas about the uniqueness property. *)\n  Lemma unique_unique : forall nd q,\n    abs_queue_unique (AbsQueue (nd :: q)) ->\n    abs_queue_unique (AbsQueue q).\n  Proof.\n    intros ? ? Hunique.\n    inv Hunique; constructor.\n    rewrite Forall_forall in *.\n    intros ? Hin.\n    assert (Hin': In x (nd :: q)) by (cbn; auto).\n    apply H0 in Hin'. cbn in Hin'.\n    destruct (zeq nd x); subst; auto.\n    inv Hin'.\n    rewrite <- count_occ_not_In in H1.\n    contradiction.\n  Qed.\n\n  Lemma unique_not_in : forall nd q,\n    abs_queue_unique (AbsQueue (nd :: q)) ->\n    ~In nd q.\n  Proof.\n    red; intros ? ? Hunique Hin.\n    pose proof Hunique as Hunique'. apply unique_unique in Hunique'.\n    inv Hunique; inv Hunique'. rewrite Forall_forall in *.\n    assert (Hin': In nd (nd :: q)) by (cbn; auto).\n    apply H1 in Hin; apply H0 in Hin'.\n    cbn in Hin'. rewrite zeq_true in Hin'.\n    congruence.\n  Qed.\n\n  Lemma unique_not_in_unique : forall nd q,\n    abs_queue_unique (AbsQueue q) ->\n    ~In nd q ->\n    abs_queue_unique (AbsQueue (nd :: q)).\n  Proof.\n    intros ? ? Hunique Hnin.\n    inv Hunique; constructor.\n    rewrite Forall_forall in *.\n    intros ? Hin; cbn.\n    destruct (zeq nd x); subst.\n    - rewrite count_occ_not_In in Hnin; eauto.\n    - destruct Hin; [contradiction | auto].\n  Qed.\n\n  (** A property about nodes not in the queue. *)\n  Lemma NIn_Q_inQ : forall q nd anpool dat,\n    In_Q_inQ (AbsQueue q) nd anpool ->\n    ZMap.get nd anpool = AbsNode dat false ->\n    ~In nd q.\n  Proof.\n    red; intros ? ? ? ? Hinq Hnode Hin.\n    inv Hinq. rewrite Hnode in H0; inv H0.\n    destruct H1. apply H0 in Hin. discriminate.\n  Qed.\n\nEnd QUEUE_DATA_PROPS.\n\n(** ** Composite Environments *)\n\n(** The [Node] and [QueueIntro] layers also have to have the same\n  [composite_env] so these definitions have to be somewhere that both files can\n  import from. *)\n\nDefinition node_t : ident := 7%positive.\nDefinition node_t_data : ident := 8%positive.\nDefinition node_t_next : ident := 9%positive.\nDefinition node_t_prev : ident := 10%positive.\nNotation node_t_struct := (Tstruct node_t noattr).\n\nDefinition node_t_comp : composite_definition :=\n  Composite node_t Struct\n    ((node_t_data, tuint) ::\n     (node_t_next, tuint) ::\n     (node_t_prev, tuint) ::\n     nil)\n    noattr.\n\nDefinition queue_t : ident := 25%positive.\nDefinition queue_t_head : ident := 26%positive.\nDefinition queue_t_tail : ident := 27%positive.\nNotation queue_t_struct := (Tstruct queue_t noattr).\n\nDefinition queue_t_comp : composite_definition :=\n  Composite queue_t Struct\n    ((queue_t_head, tuint) ::\n     (queue_t_tail, tuint) ::\n     nil)\n    noattr.\n\n(** ** Intro Layer Relations *)\nSection ABS_REL.\n\n  Context `{Hmem: BaseMemoryModel}.\n\n  (** We must combine the [Node] and [QueueIntro] layers together so we can\n    build the [Queue] layer on top. In particular, this means defining a\n    new abstraction relation where the components are combinations of the\n    corresponding components in the [Node] and [QueueIntro] relations. *)\n\n  (** *** Node *)\n\n  Definition NODE_POOL : ident := 6%positive.\n\n  Inductive match_node : node_low -> val -> val -> val -> Prop :=\n  | match_node_undef: forall dv nv pv,\n      match_node NodeUndef dv nv pv\n  | match_node_intro: forall d n p,\n      match_node (Node d n p) (Vint (Int.repr d)) (Vint (Int.repr n)) (Vint (Int.repr p)).\n\n  Inductive node_match_data : intro_layerdata -> mem -> Prop :=\n  | node_match_data_intro:\n      forall m (abs: intro_layerdata) npb\n             (Hnpb: find_symbol NODE_POOL = Some npb),\n        (forall node, 0 <= node < MAX_NODES ->\n          (exists dat nxt prv,\n            Mem.load Mint32 m npb (node_sz * node + data_off) = Some (Vint dat) /\\\n            Mem.load Mint32 m npb (node_sz * node + next_off) = Some (Vint nxt) /\\\n            Mem.load Mint32 m npb (node_sz * node + prev_off) = Some (Vint prv) /\\\n            Mem.valid_access m Mint32 npb (node_sz * node + data_off) Writable /\\\n            Mem.valid_access m Mint32 npb (node_sz * node + next_off) Writable /\\\n            Mem.valid_access m Mint32 npb (node_sz * node + prev_off) Writable /\\\n            match_node (ZMap.get node (npool abs))\n                       (Vint dat) (Vint nxt) (Vint prv))) ->\n        node_match_data abs m.\n\n  Definition node_relate_data (hadt: intro_layerdata) (ladt: boot_layerdata) := True.\n\n  (** *** QueueIntro *)\n\n  Definition QUEUE : ident := 24%positive.\n\n  Inductive match_queue : queue_low -> val -> val -> Prop :=\n  | match_queue_undef: forall hv tv,\n      match_queue QueueUndef hv tv\n  | match_queue_intro: forall h t,\n      match_queue (Queue h t) (Vint (Int.repr h)) (Vint (Int.repr t)).\n\n  Inductive queue_intro_match_data : intro_layerdata -> mem -> Prop :=\n  | queue_intro_match_data_intro:\n      forall m (abs: intro_layerdata) qb\n             (Hqb: find_symbol QUEUE = Some qb),\n        (exists hd tl,\n          Mem.load Mint32 m qb head_off = Some (Vint hd) /\\\n          Mem.load Mint32 m qb tail_off = Some (Vint tl) /\\\n          Mem.valid_access m Mint32 qb head_off Writable /\\\n          Mem.valid_access m Mint32 qb tail_off Writable /\\\n          match_queue (queue abs)\n                      (Vint hd) (Vint tl)) ->\n        queue_intro_match_data abs m.\n\n  Definition queue_intro_relate_data (hadt: intro_layerdata) (ladt: boot_layerdata) := True.\n\n  (** Define [match] and [relate] relations by and-ing together the\n    corresponding [Node] and [QueueIntro] definitions. *)\n  Definition abrel_components_intro_boot :\n    abrel_components intro_layerdata boot_layerdata :=\n    {|\n      abrel_relate :=\n        fun D1 D2 =>\n          node_relate_data D1 D2 /\\ queue_intro_relate_data D1 D2;\n      abrel_match  :=\n        fun D1 D2 =>\n          node_match_data D1 D2 /\\ queue_intro_match_data D1 D2;\n      abrel_new_glbl :=\n        (NODE_POOL, Init_space (MAX_NODES * node_sz) :: nil) ::\n        (QUEUE, Init_space queue_sz :: nil) ::\n        nil\n    |}.\n\n  Global Instance intro_rel_ops :\n    AbstractionRelation _ _ abrel_components_intro_boot.\n  Proof.\n    constructor.\n    - split; constructor.\n    - intros. split.\n      + (** Node match_data *)\n        inv_abrel_init_props.\n        econstructor; eauto; intros.\n        pose MAX_NODES_range as Hmn_range.\n        cbn -[Z.mul] in *; unfold_node_fields.\n        rewrite Zmax_left in aip_perm by omega.\n        destruct aip_load as [aip_load _].\n        pose node_fields_align as Halign.\n        do 3 eexists.\n        repeat match goal with\n        | |- _ /\\ _ => split\n        | |- Mem.load _ _ _ _ = Some _ =>\n          apply aip_load; [omega | try omega | auto]\n        | |- (4 | 12 * ?x + 0) => exists (3*x); omega\n        | |- (4 | ?x * 12) => exists (3*x); omega\n        | |- (4 | 12 * ?x + 4) => exists (3*x + 1); omega\n        | |- (4 | 12 * ?x + 8) => exists (3*x + 2); omega\n        | |- Mem.valid_access _ _ _ (12 * node + ?off) _ =>\n            split; cbn -[Z.mul];\n            [red; intros; apply aip_perm; omega | auto]\n        end.\n        rewrite ZMap.gi.\n        constructor.\n      + (** QueueIntro match_data *)\n        inv_abrel_init_props.\n        econstructor; eauto; intros.\n        (** pose MAX_NODES_range as Hmn_range. *)\n        cbn in *; unfold_queue_fields.\n        destruct aip_load as [aip_load _].\n        pose queue_fields_align as Halign.\n        do 2 eexists.\n        repeat match goal with\n        | |- _ /\\ _ => split\n        | |- Mem.load _ _ _ _ = Some _ =>\n          apply aip_load0; [omega | try omega | auto]\n        | |- (4 | 0) => exists 0; omega\n        | |- (4 | 4) => exists 1; omega\n        | |- (4 | 8) => exists 2; omega\n        | |- Mem.valid_access _ _ _ ?off _ =>\n            split; cbn;\n            [red; intros; apply aip_perm0; omega | auto]\n        end.\n        constructor.\n    - repeat red; cbn. intros d m1 m2 Hunchange [Hnode_match Hqueue_match].\n      split.\n      + (** Node relate_data *)\n        inv Hnode_match; econstructor; eauto.\n        intros ? Hnode; specialize (H _ Hnode).\n        destruct H as (dat & nxt & prv & ?).\n        repeat match goal with\n        | H: _ /\\ _ |- _ => destruct H\n        | H: Mem.valid_access _ _ _ _ _ |- _ => destruct H; red in H\n        end.\n        do 3 eexists.\n        repeat match goal with\n        | |- _ /\\ _ => split\n        | |- Mem.load _ _ _ _ = Some _ =>\n            eapply Mem.load_unchanged_on; eauto; red; cbn; eauto\n        | |- Mem.valid_access _ _ _ _ _ =>\n            split;\n            [red; intros; eapply Mem.perm_unchanged_on; eauto; red; cbn |];\n            eauto\n        end.\n        assumption.\n      + (** QueueIntro relate_data *)\n        inv Hqueue_match; econstructor; eauto.\n        destruct H as (hd & tl & ?).\n        repeat match goal with\n        | H: _ /\\ _ |- _ => destruct H\n        | H: Mem.valid_access _ _ _ _ _ |- _ => destruct H; red in H\n        end.\n        do 2 eexists.\n        repeat match goal with\n        | |- _ /\\ _ => split\n        | |- Mem.load _ _ _ _ = Some _ =>\n            eapply Mem.load_unchanged_on; eauto; red; cbn; eauto\n        | |- Mem.valid_access _ _ _ _ _ =>\n            split;\n            [red; intros; eapply Mem.perm_unchanged_on; eauto; red; cbn |];\n            eauto\n        end; intros; repeat eexists; eauto.\n    - repeat constructor.\n  Qed.\n\n  Definition abrel_intro_boot : abrel intro_layerdata boot_layerdata :=\n    {|\n      abrel_ops := abrel_components_intro_boot;\n      abrel_prf := intro_rel_ops\n    |}.\n\n  Definition intro_R : simrel _ _ :=\n    abrel_simrel _ _ abrel_intro_boot.\n\nEnd ABS_REL.\n\n(** ** Helper Lemmas *)\nSection AUX_LEMMAS.\n\n  (** Some additional properties of Coq [list] functions and how they\n    interact with the queue properties. *)\n\n  Lemma remove_nin : forall x xs,\n    ~In x xs -> remove zeq x xs = xs.\n  Proof.\n    induction xs; auto; cbn; intros.\n    destruct (zeq x a); [subst |]; try tauto.\n    f_equal. auto.\n  Qed.\n\n  Lemma remove_neq : forall x y xs,\n    x <> y -> In x (remove zeq y xs) <-> In x xs.\n  Proof.\n    induction xs; cbn; intros; try tauto.\n    destruct (zeq y a); [subst |]; cbn; try tauto.\n    split; intros; try tauto.\n    destruct H0; [congruence | tauto].\n  Qed.\n\n  Lemma count_occ_remove_neq : forall x y xs,\n    x <> y -> count_occ zeq (remove zeq y xs) x = count_occ zeq xs x.\n  Proof.\n    induction xs; cbn; intros; try tauto.\n    destruct (zeq y a); [subst |]; cbn.\n    - rewrite zeq_false; auto.\n    - destruct (zeq a x); [subst |]; cbn; try tauto.\n      f_equal. tauto.\n  Qed.\n\n  Lemma count_occ_app : forall xs ys z,\n    count_occ zeq (xs ++ ys) z = (count_occ zeq xs z + count_occ zeq ys z)%nat.\n  Proof.\n    induction xs.\n    - simpl; intros; auto.\n    - simpl; intros.\n      destruct (zeq a z); simpl; f_equal; apply IHxs.\n  Qed.\n\n  Lemma last_In : forall x (q: list Z),\n    (q = nil \\/ In (last q x) q).\n  Proof.\n    induction q; auto.\n    simpl.\n    destruct q; auto.\n    destruct IHq; [congruence | auto].\n  Qed.\n\n  Lemma remove_last : forall z q,\n    ~ In z q ->\n    List.remove zeq z (q ++ z :: nil) = q.\n  Proof.\n    induction q.\n    - simpl. rewrite zeq_true. auto.\n    - simpl in *.\n      intros HNin.\n      rewrite zeq_false by (contradict HNin; left; congruence).\n      rewrite IHq by tauto.\n      reflexivity.\n  Qed.\n\n  Lemma last_nonempty_dummy : forall {A} y z xs (x: A),\n    last (x :: xs) y = last (x :: xs) z.\n  Proof.\n    induction xs; simpl in *; try rewrite IHxs; reflexivity.\n  Qed.\n\n  Lemma app_last : forall {A} (xs ys : list A) z,\n    ys <> nil -> last (xs ++ ys) z = last ys z.\n  Proof.\n    induction xs.\n    - simpl; auto.\n    - intros.\n      specialize (IHxs ys z H).\n      simpl.\n      destruct (xs ++ ys) eqn:?; auto; destruct xs; simpl in *; congruence.\n  Qed.\n\n  Lemma tail_last : forall dummy (q: list Z),\n    q = nil \\/  exists q', q = q' ++ (last q dummy :: nil).\n  Proof.\n    induction q.\n    - left; congruence.\n    - destruct q.\n      + right. exists nil. reflexivity.\n      + destruct IHq as [? |[ q' IH]]; [congruence|].\n        right. exists (a :: q').\n        simpl in *.\n        congruence.\n  Qed.\n\n   Lemma last_nin_default : forall {A} xs (x y: A),\n     ~In x xs -> last xs y = x -> xs = nil.\n   Proof.\n     intros.\n     induction xs.\n     - reflexivity.\n     - cbn in H0.\n       destruct xs.\n       + rewrite <- H0 in H.\n         contradict H.\n         constructor.\n         reflexivity.\n       + discriminate IHxs.\n         * rewrite not_in_cons in H.\n           destruct H.\n           exact H1.\n         * exact H0.\n  Qed.\n\n  Lemma Forall_app_inv2 : forall (A: Type) (P: A -> Prop) (xs ys: list A),\n    Forall P (xs ++ ys) -> Forall P ys.\n  Proof.\n    induction xs.\n    - simpl; auto.\n    - inversion 1. eauto.\n  Qed.\n\n  Lemma unique_not_In : forall xs y ys,\n    abs_queue_unique (AbsQueue (xs ++ y :: ys)) ->\n    ~ In y xs /\\ ~In y ys.\n  Proof.\n    inversion 1 as [q Hcount Hq]. subst.\n    repeat rewrite (count_occ_not_In zeq).\n    apply Forall_app_inv2 in Hcount.\n    inversion Hcount as [| ? ? Hcount' _]. subst.\n    rewrite count_occ_app in Hcount'.\n    destruct (count_occ zeq xs y); simpl in *;\n      rewrite zeq_true in Hcount'; auto; omega.\n  Qed.\n\nEnd AUX_LEMMAS.\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/QueueData.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.5, "lm_q1q2_score": 0.29821657313231276}}
{"text": "From Hammer Require Import Hammer.\n\n\n\nFrom WeakUpTo Require Export Theory.\nSet Implicit Arguments.\n\n\nSection RelaxedExpansion.\n\nVariables A X Y: Type.\nVariable TX: reduction_t A X.\nVariable TY: reduction_t A Y.\n\nVariable B: relation X.\nHypothesis HB: wexpansion1 TX TX B.\n\n\nLet wexpansion1_ctrl_t:\nforall R, evolve_t TX TY R (comp (star B) R) -> simulation_t TX TY (comp (star B) R).\nProof. hammer_hook \"Controlled\" \"Controlled.RelaxedExpansion.wexpansion1_ctrl_t\".\nintros R HR x x' y Hxx' xRy; destruct xRy as [ w xRw wRy ].\ncgen Hxx'; cgen x'; induction xRw as [ x | z x w xRz zRw IH ]; intros x' Hxx'.\napply (HR _ _ _ Hxx' wRy).\ndestruct (HB Hxx' xRz) as [ z' Hzz' x'Rz' ].\ncelim Hzz'; intro Hzz'.\ndestruct Hzz'; exists y; auto; exists w; auto; apply star_trans with z; auto.\ndestruct (IH wRy _ Hzz') as [ y' Hyy' z'Ry' ] ; destruct z'Ry' as [ w' ].\nexists y'; auto; exists w'; auto; apply S_star with z'; auto.\nQed.\n\n\nTheorem wexpansion1_ctrl: wexpansion1 TX TX B -> controlled TX TY B.\nProof. hammer_hook \"Controlled\" \"Controlled.wexpansion1_ctrl\".\nsplit; auto.\nintros R S HR HS HRS HRS' a x x' y Hxx' xRy; destruct xRy as [ w xRw wRy ].\ncgen Hxx'; cgen x'; induction xRw as [ x | z x w xRz zRw IH ]; intros x' Hxx'.\ndestruct (HRS _ _ _ _ Hxx' wRy) as [ y' Hyy' w'Ry' ]; exists y'; auto; exists x'; auto.\ndestruct (HB Hxx' xRz) as [ z' Hzz' x'Rz' ].\ndestruct Hzz' as [ z1 Hzz1 Hz1z' ].\ndestruct (IH wRy _ Hzz1) as [ y1 Hyy1 z1Ry1 ].\ncut (simulation_t TX TY (comp (star B) S)).\nintro HS'; destruct (weak_strong_t HS' _ Hz1z' z1Ry1) as [ y' Hy1y' z'Ry' ]; exists y'.\napply weak_taus with y1; auto.\ndestruct z'Ry' as [ w' ]; exists w'; auto; apply S_star with z'; auto.\napply wexpansion1_ctrl_t; auto.\nunfold evolve_t; eapply evolve_incl; try apply HS; intros u v K; exists u; auto.\nQed.\n\nEnd RelaxedExpansion.\n\n\n\nSection PlusWf.\n\nVariable A: Type.\nVariable X: Set.\nVariable Y: Type.\nVariable TX: reduction_t A X.\nVariable TY: reduction_t A Y.\n\nVariable B: relation X.\nHypothesis HB: evolve TX TX B (plus B).\nHypothesis HB': well_founded (trans B).\n\n\nTheorem plus_wf_controlled: controlled TX TY B.\nProof. hammer_hook \"Controlled\" \"Controlled.plus_wf_controlled\".\nsplit.\nintros R HR x x' y Hxx' xRy; destruct xRy as [ w xRw wRy ]; destar xRw z.\napply (HR _ _ _ Hxx' wRy).\nelim (diagram_plus_wf_2 (HB (l:=T _)) HB') with (eq (A:=X)) Y R R (TY (T A)) (eq (A:=Y)) x x' y; auto.\nintros y' Hyy' x'Ry'; exists y'; auto; destruct Hyy' as [ y1 Hyy1 Hy1y' ]; destruct Hy1y'; auto.\nintros u u' v Huu' uRv; destruct Huu'; exists v; auto; exists v; auto.\nintros u u' v Huu' uRv; destruct Huu'; exists v; auto; (exists v || exists u); auto.\nexists x'; auto.\nexists w; auto.\n\nintros R S HR HS HRS HRS' a x x' y Hxx' xRy.\nelim (diagram_plus_wf_2 (HB (l:=T _)) HB') with\n(comp (TX (L a)) (star (TX (T _)))) Y R S (TY (T _))\n(comp (TY (L a)) (star (TY (T _)))) x x' y; auto.\nintros y' Hyy' x'Ry'; exists y'; auto.\nclear Hxx' xRy x x' y; intros x x' y Hxx' xRy; destruct Hxx' as [ x1 Hxx1 Hx1x' ].\ndestruct (HB Hxx1 xRy) as [ y1 Hyy1 x1Ry1 ].\ndestruct (diagram_plus_wf (HB (l:=T _)) HB' Hx1x' x1Ry1) as [ y' Hy1y' x'Ry' ].\nexists y'; auto; fold (Weak TX (L a)); apply weak_taus with y1; auto.\nclear Hxx' xRy x x' y; intros x x' y Hxx' xRy; destruct Hxx' as [ x1 Hxx1 Hx1x' ].\ndestruct (HRS _ _ _ _ Hxx1 xRy) as [ y1 Hyy1 x1Ry1 ].\ndestruct (weak_strong_t HS _ Hx1x' x1Ry1) as [ y' Hy1y' x'Ry' ]; exists y'.\nfold (Weak TY (L a)); apply weak_taus with y1; auto.\nexists x'; auto.\nexists x; auto; exists x'; auto.\nQed.\n\nEnd PlusWf.\n\n\nSection StarWf.\n\nVariable A: Type.\nVariable X: Set.\nVariable Y: Type.\nVariable TX: reduction_t A X.\nVariable TY: reduction_t A Y.\n\nVariable B: relation X.\nHypothesis HB: evolve TX TX B (star B).\nHypothesis HB': well_founded (trans (comp (plus B) (plus (TX (T _))))).\n\n\nTheorem star_wf_controlled: controlled TX TY B.\nProof. hammer_hook \"Controlled\" \"Controlled.star_wf_controlled\".\nsplit.\nintros R HR; unfold simulation_t, evolve_t, evolve_1, Weak.\napply diagram_reverse; apply diagram_incl with (star (TX (T _))) (star (TY (T _))); auto; apply diagram_reverse.\napply diagram_star_wf_1; auto; exact (HB (l:=T _)).\n\nintros R S HR HS HRS HRS' a; unfold evolve_1.\napply diagram_reverse; apply diagram_incl with (Weak TX (L a)) (Weak TY (L a)); auto; apply diagram_reverse.\nunfold Weak; apply diagram_star_wf_2; auto; try exact (HB (l:=T _));\nintros x x' y Hxx' xRy; destruct Hxx' as [ x1 Hxx1 Hx1x' ].\ndestruct (HB Hxx1 xRy) as [ y1 Hyy1 x1Ry1 ].\ndestruct (diagram_star_wf (HB (l:=T _)) HB' Hx1x' x1Ry1) as [ y' Hy1y' x'Ry' ].\nexists y'; auto; fold (Weak TX (L a)); apply weak_taus with y1; auto.\ndestruct (HRS _ _ _ _ Hxx1 xRy) as [ y1 Hyy1 x1Ry1 ].\ndestruct (weak_strong_t HS _ Hx1x' x1Ry1) as [ y' Hy1y' x'Ry' ]; exists y'.\nfold (Weak TY (L a)); apply weak_taus with y1; auto.\nexists x'; auto.\nQed.\n\nEnd StarWf.\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/Controlled.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.5, "lm_q1q2_score": 0.29821656595887436}}
{"text": "(**\n/A module for “displayed categories”, based over UniMath’s [CategoryTheory] library.\n\nRoughly, a “displayed category _D_ over a category _C_” is analogous to “a family of types _Y_ indexed over a type _X_”.  A displayed category has a “total category” ∑ _C_ _D_, with a functor to _D_; and indeed displayed categories should be equivalent to categories over _D_, by taking fibers.\n\nIn a little more detail: if [D] is a displayed category over [C], then [D] has a type of objects indexed over [ob C], and for each [x y : C, f : x --> y, xx : D x, yy : D y], a type of “morphisms over [f] from [xx] to [yy]”.  The identity and composition (and axioms) for [D] all overlie the corresponding structure on [C].\n\nTwo major motivations for displayed categories:\n\n- Pragmatically, they give a convenient tool for building categories of “structured objects”, and functors into such categories, encapsulating a lot of frequently-used constructions, and allowing for very modular proofs of e.g. saturation of such categories.\n- More conceptually, they give a setting for defining Grothendieck fibrations and isofibrations without mentioning equality of objects.\n\nContents:\n\n- Displayed categories: [disp_cat C]\n  - various access functions, etc.\n  - utility lemmas\n  - isomorphisms\n  - saturation\n- Total categories (and their forgetful functors)\n  - [total_category D]\n  - [pr1_category D]\n- Functors between displayed categories, over functors between their bases\n  - [functor_lifting], [lifted_functor]\n  - [disp_functor], [total_functor]\n  - properties of functors: [disp_functor_ff], …\n  - natural transformations: [disp_nat_trans], …\n*)\n\n(* TODO: this file has become large and unwieldy; should probably be split up.  Displayed functors can certainly be happily split off.  Should total cats stay here, or also be split out? *)\n\nRequire Import UniMath.Foundations.Sets.\nRequire Import UniMath.Foundations.PartD.\nRequire Import UniMath.MoreFoundations.PartA.\nRequire Import UniMath.MoreFoundations.AxiomOfChoice.\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Isos.\nRequire Import UniMath.CategoryTheory.Core.NaturalTransformations.\nRequire Import UniMath.CategoryTheory.Core.Univalence.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.whiskering.\nLocal Open Scope cat.\nLocal Open Scope type_scope.\n\n(* Undelimit Scope transport. *)\n\n(** * Displayed categories *)\n\n(*\n  Here is an iterated ∑-type that displays a logical structure equivalent to the\n  type called disp_cat defined below.\n*)\n\nDefinition disp_cat' (C : category) : UU :=\n  ∑ (ob_disp : C -> UU)\n    (mor_disp : ∏ {x y : C}, (x --> y) -> ob_disp x -> ob_disp y -> UU)\n    (id_disp : ∏ {x : C} (xx : ob_disp x), mor_disp (identity x) xx xx)\n    (comp_disp : ∏ {x y z : C} {f : x --> y} {g : y --> z}\n                   {xx : ob_disp x} {yy : ob_disp y} {zz : ob_disp z},\n                 mor_disp f xx yy -> mor_disp g yy zz -> mor_disp (f · g) xx zz)\n    (id_left_disp : ∏ {x y} {f : x --> y} {xx} {yy} (ff : mor_disp f xx yy),\n                    comp_disp (id_disp xx) ff\n                    = transportb (λ g, mor_disp g xx yy) (id_left _) ff)\n    (id_right_disp : ∏ {x y} {f : x --> y} {xx} {yy} (ff : mor_disp f xx yy),\n                     comp_disp ff (id_disp yy)\n                     = transportb (λ g, mor_disp g xx yy) (id_right _) ff)\n    (assoc_disp : ∏ {x y z w} {f : x --> y} {g : y --> z} {h : z --> w}\n                    {xx} {yy} {zz} {ww}\n                    (ff : mor_disp f xx yy) (gg : mor_disp g yy zz) (hh : mor_disp h zz ww),\n                  comp_disp ff (comp_disp gg hh)\n                  = transportb (λ k, mor_disp k _ _) (assoc _ _ _)\n                               (comp_disp (comp_disp ff gg) hh)),\n  (* homsets_disp : *) ∏ x y (f : x --> y) xx yy, isaset (mor_disp f xx yy).\n\n(** ** Definition *)\n\n(** The actual definition is structured analogously to [category], as an iterated ∑-type:\n\n- [disp_cat]\n  - [disp_cat_data]\n    - [disp_cat_ob_mor]\n      - [ob_disp]\n      - [mod_disp]\n    - [disp_cat_id_comp]\n      - [id_disp]\n      - [comp_disp]\n  - [disp_cat_axioms]\n    - [id_left_disp]\n    - [id_right_disp]\n    - [assoc_disp]\n    - [homsets_disp]\n\n*)\n\nSection Disp_Cat.\n\nDefinition disp_cat_ob_mor (C : precategory_ob_mor)\n  := ∑ (obd : C -> UU), (∏ x y:C, obd x -> obd y -> (x --> y) -> UU).\n\nDefinition make_disp_cat_ob_mor\n           (C : precategory_ob_mor)\n           (obd : C -> UU)\n           (mord : ∏ x y:C, obd x -> obd y -> (x --> y) -> UU)\n  : disp_cat_ob_mor C\n  := obd,, mord.\n\nDefinition ob_disp {C: precategory_ob_mor} (D : disp_cat_ob_mor C) : C -> UU := pr1 D.\nCoercion ob_disp : disp_cat_ob_mor >-> Funclass.\n\nDefinition mor_disp {C: precategory_ob_mor} {D : disp_cat_ob_mor C}\n  {x y} xx yy (f : x --> y)\n:= pr2 D x y xx yy f : UU.\n\nLocal Notation \"xx -->[ f ] yy\" := (mor_disp xx yy f) (at level 50, left associativity, yy at next level).\n\nDefinition disp_cat_id_comp (C : precategory_data)\n  (D : disp_cat_ob_mor C)\n  : UU\n:= (forall (x:C) (xx : D x), xx -->[identity x] xx)\n  × (forall (x y z : C) (f : x --> y) (g : y --> z) (xx:D x) (yy:D y) (zz:D z),\n           (xx -->[f] yy) -> (yy -->[g] zz) -> (xx -->[f · g] zz)).\n\nDefinition disp_cat_data C := total2 (disp_cat_id_comp C).\n\nDefinition disp_cat_ob_mor_from_disp_cat_data {C: precategory_data}\n  (D : disp_cat_data C)\n  : disp_cat_ob_mor C\n:= pr1 D.\n\nCoercion disp_cat_ob_mor_from_disp_cat_data :\n disp_cat_data >-> disp_cat_ob_mor.\n\nDefinition id_disp {C: precategory_data} {D : disp_cat_data C} {x:C} (xx : D x)\n  : xx -->[identity x] xx\n:= pr1 (pr2 D) x xx.\n\nDefinition comp_disp {C: precategory_data} {D : disp_cat_data C}\n  {x y z : C} {f : x --> y} {g : y --> z}\n  {xx : D x} {yy} {zz} (ff : xx -->[f] yy) (gg : yy -->[g] zz)\n  : xx -->[f · g] zz\n:= pr2 (pr2 D) _ _ _ _ _ _ _ _ ff gg.\n\nDeclare Scope mor_disp_scope.\nLocal Notation \"ff ;; gg\" := (comp_disp ff gg)\n  (at level 50, left associativity, format \"ff  ;;  gg\")\n  : mor_disp_scope.\nDelimit Scope mor_disp_scope with mor_disp.\nBind Scope mor_disp_scope with mor_disp.\nLocal Open Scope mor_disp_scope.\n\nDefinition disp_cat_axioms (C : category) (D : disp_cat_data C)\n  : UU\n:= (∏ x y (f : x --> y) (xx : D x) yy (ff : xx -->[f] yy),\n     id_disp _ ;; ff\n     = transportb _ (id_left _) ff)\n   × (∏ x y (f : x --> y) (xx : D x) yy (ff : xx -->[f] yy),\n     ff ;; id_disp _\n     = transportb _ (id_right _) ff)\n   × (∏ x y z w f g h (xx : D x) (yy : D y) (zz : D z) (ww : D w)\n        (ff : xx -->[f] yy) (gg : yy -->[g] zz) (hh : zz -->[h] ww),\n     ff ;; (gg ;; hh)\n     = transportb _ (assoc _ _ _) ((ff ;; gg) ;; hh))\n   × (∏ x y f (xx : D x) (yy : D y), isaset (xx -->[f] yy)).\n\n\nDefinition disp_cat (C : category) := total2 (disp_cat_axioms C).\n\nDefinition disp_cat_data_from_disp_cat {C} (D : disp_cat C)\n := pr1 D : disp_cat_data C.\nCoercion disp_cat_data_from_disp_cat : disp_cat >-> disp_cat_data.\n\n\n(** All the axioms are given in two versions, [foo : T1 = transportb e T2] and [foo_var : T2 = transportf e T1], so that either direction can be invoked easily in “compute left-to-right” style. *)\n\n(* TODO: consider naming conventions? *)\n(* TODO: maybe would be better to have a single [pathsinv0_dep] lemma, or something. *)\n\nDefinition id_left_disp {C} {D : disp_cat C}\n  {x y} {f : x --> y} {xx : D x} {yy} (ff : xx -->[f] yy)\n: id_disp _ ;; ff = transportb _ (id_left _) ff\n:= pr1 (pr2 D) _ _ _ _ _ _.\n\nDefinition id_left_disp_var {C} {D : disp_cat C}\n  {x y} {f : x --> y} {xx : D x} {yy} (ff : xx -->[f] yy)\n: ff = transportf _ (id_left _) (id_disp _ ;; ff).\nProof.\n  apply transportf_transpose_right.\n  apply @pathsinv0, id_left_disp.\nQed.\n\nDefinition id_right_disp {C} {D : disp_cat C}\n  {x y} {f : x --> y} {xx : D x} {yy} (ff : xx -->[f] yy)\n  : ff ;; id_disp _ = transportb _ (id_right _) ff\n:= pr1 (pr2 (pr2 D)) _ _ _ _ _ _.\n\nDefinition id_right_disp_var {C} {D : disp_cat C}\n  {x y} {f : x --> y} {xx : D x} {yy} (ff : xx -->[f] yy)\n  : ff = transportf _ (id_right _) (ff ;; id_disp _).\nProof.\n  apply transportf_transpose_right.\n  apply @pathsinv0, id_right_disp.\nQed.\n\nDefinition assoc_disp {C} {D : disp_cat C}\n  {x y z w} {f} {g} {h} {xx : D x} {yy : D y} {zz : D z} {ww : D w}\n  (ff : xx -->[f] yy) (gg : yy -->[g] zz) (hh : zz -->[h] ww)\n: ff ;; (gg ;; hh) = transportb _ (assoc _ _ _) ((ff ;; gg) ;; hh)\n:= pr1 (pr2 (pr2 (pr2 D))) _ _ _ _ _ _ _ _ _ _ _ _ _ _.\n\nDefinition assoc_disp_var {C} {D : disp_cat C}\n  {x y z w} {f} {g} {h} {xx : D x} {yy : D y} {zz : D z} {ww : D w}\n  (ff : xx -->[f] yy) (gg : yy -->[g] zz) (hh : zz -->[h] ww)\n: (ff ;; gg) ;; hh = transportf _ (assoc _ _ _) (ff ;; (gg ;; hh)).\nProof.\n  apply pathsinv0, transportf_pathsinv0.\n  apply pathsinv0, assoc_disp.\nDefined.\n\nDefinition homsets_disp {C} {D : disp_cat C} {x y} (f : x --> y) (xx : D x) (yy : D y)\n  : isaset (xx -->[f] yy) := pr2 (pr2 (pr2 (pr2 D))) _ _ _ _ _.\n\n(** ** Utility lemmas *)\nSection Lemmas.\n\n(** [etrans_disp]: a version of [etrans_dep] for use when the equality transport in the RHS of the goal is already present, and not of the form produced by [etrans_dep], so [etrans_dep] doesn’t apply.  Where possible, [etrans_dep] should still be used, since it *produces* a RHS, whereas this does not (and so leads to lots of unsolved existentials if used where not needed).\n\nNOTE: as with [etrans_dep], proofs using [etrans_disp] seem to typecheck more slowly than proofs using [etrans] plus other lemmas directly. *)\nLemma pathscomp0_disp {C} {D : disp_cat C}\n  {x y} {f f' f'' : x --> y} (e : f' = f) (e' : f'' = f') (e'' : f'' = f)\n  {xx : D x} {yy}\n  (ff : xx -->[f] yy) (ff' : xx -->[f'] yy) (ff'' : xx -->[f''] yy)\n: (ff = transportf _ e ff') -> (ff' = transportf _ e' ff'')\n  -> ff = transportf _ e'' ff''.\nProof.\n  intros ee ee'.\n  etrans. eapply pathscomp0_dep. apply ee. apply ee'.\n  apply maponpaths_2, homset_property.\nQed.\n\nTactic Notation \"etrans_disp\" := eapply @pathscomp0_disp.\n\nLemma isaprop_disp_cat_axioms (C : category) (D : disp_cat_data C)\n  : isaprop (disp_cat_axioms C D).\nProof.\n  apply isofhlevelsn.\n  intro X.\n  set (XR := ( _ ,, X) : disp_cat C).\n  apply isofhleveltotal2.\n  - repeat (apply impred; intro).\n    apply (@homsets_disp _ XR).\n  - intros x.\n    repeat (apply isofhleveldirprod); repeat (apply impred; intro).\n    + apply (@homsets_disp _ XR).\n    + apply (@homsets_disp _ XR).\n    + apply isapropiscontr.\nQed.\n\n(* TODO: consider naming of following few transport lemmas *)\nLemma mor_disp_transportf_postwhisker\n    {C : precategory} {D : disp_cat_data C}\n    {x y z : C} {f f' : x --> y} (ef : f = f') {g : y --> z}\n    {xx : D x} {yy} {zz} (ff : xx -->[f] yy) (gg : yy -->[g] zz)\n  : (transportf _ ef ff) ;; gg\n  = transportf _ (cancel_postcomposition _ _ g ef) (ff ;; gg).\nProof.\n  destruct ef; apply idpath.\nQed.\n\nLemma mor_disp_transportf_prewhisker\n    {C : precategory} {D : disp_cat_data C}\n    {x y z : C} {f : x --> y} {g g' : y --> z} (eg : g = g')\n    {xx : D x} {yy} {zz} (ff : xx -->[f] yy) (gg : yy -->[g] zz)\n  : ff ;; (transportf _ eg gg)\n  = transportf _ (maponpaths (compose f) eg) (ff ;; gg).\nProof.\n  destruct eg; apply idpath.\nQed.\n\n(* TODO: use the following lemmas in more of the displayed category proofs. Most instances of [mor_disp_transportf_Xwhisker] are places that can be simplified with these. *)\n(* TODO: consider naming of [cancel_Xcomposition_disp].  Currently follows the UniMath base lemmas, but those are bad names — cancellation properties traditionally mean things like like [ ax = ay -> x = y ], whereas these lemmas are the converse of that. *)\nLemma cancel_postcomposition_disp {C} {D : disp_cat C}\n  {x y z} {f f' : x --> y} {e : f' = f} {g : y --> z}\n  {xx : D x} {yy} {zz}\n  {ff : xx -->[f] yy} {ff' : xx -->[f'] yy} (gg : yy -->[g] zz)\n  (ee : ff = transportf _ e ff')\n: ff ;; gg = transportf _ (cancel_postcomposition _ _ g e) (ff' ;; gg).\nProof.\n  etrans. apply maponpaths_2, ee.\n  apply mor_disp_transportf_postwhisker.\nQed.\n\nLemma cancel_precomposition_disp {C} {D : disp_cat C}\n  {x y z} {f : x --> y} {g g' : y --> z} {e : g' = g}\n  {xx : D x} {yy} {zz}\n  (ff : xx -->[f] yy) {gg : yy -->[g] zz} {gg' : yy -->[g'] zz}\n  (ee : gg = transportf _ e gg')\n: ff ;; gg = transportf _ (cancel_precomposition _ _ _ _ _ _ f e) (ff ;; gg').\nProof.\n  etrans. apply maponpaths, ee.\n  apply mor_disp_transportf_prewhisker.\nQed.\n\nEnd Lemmas.\n\nEnd Disp_Cat.\n\n(** Redeclare sectional notations globally. *)\nNotation \"xx -->[ f ] yy\" := (mor_disp xx yy f) (at level 50, left associativity, yy at next level).\n\nDeclare Scope mor_disp_scope.\nNotation \"ff ;; gg\" := (comp_disp ff gg)\n  (at level 50, left associativity, format \"ff  ;;  gg\")\n  : mor_disp_scope.\nDelimit Scope mor_disp_scope with mor_disp.\nBind Scope mor_disp_scope with mor_disp.\nLocal Open Scope mor_disp_scope.\n\n(** A useful notation for hiding the huge irrelevant equalities that occur in algebra of displayed categories.  For individual proofs, use [Open Scope hide_transport_scope.] at the start, and then [Close Scope hide_transport_scope.] afterwards.  For whole files/sections, use [Local Open Scope hide_transport_scope.]\n\nLevel is chosen to bind *tighter* than categorical composition, for readability. *)\n(* TODO: consider symbol(s) used. *)\nDeclare Scope hide_transport_scope.\nNotation \"#? x\" := (transportf _ _ x) (at level 45) : hide_transport_scope.\nNotation \"#?' x\" := (transportb _ _ x) (at level 45) : hide_transport_scope.\n\n(** * Functors\n\n- Reindexing of displayed cats along functors: [reindex_disp_cat]\n- Functors into displayed cats, lifting functors into the base: [functor_lifting]\n- Functors between displayed cats, over functors between the bases: [disp_functor]\n- Natural transformations between these: [disp_nat_trans] *)\n\n\n(** some TODOs for the displayed-cats library:\n\n- add lemmas connecting with products of cats (as required for displayed bicats)\n- add more applications of the displayed arrow category: slices; equalisers, inserters; hence groups etc.\n\n *)\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/DisplayedCats/Core.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.5, "lm_q1q2_score": 0.29821656595887436}}
{"text": "Require Import Undecidability.Synthetic.Definitions Undecidability.Synthetic.Undecidability.\nRequire Import Undecidability.PCP.PCP_undec.\nFrom Undecidability.FOL.Undecidability Require Import binZF_undec FOL.\nFrom Undecidability.FOL.Sets Require Import binZF.\nRequire Import Undecidability.FOL.Syntax.Core.\nRequire Import Undecidability.FOL.Syntax.BinSig.\nRequire Import Undecidability.FOL.Semantics.Tarski.FullFacts.\nRequire Import Undecidability.FOL.Deduction.FullNDFacts.\n\nLemma binZF_binFOL_valid :\n  entailment_binZF ⪯ binFOL_valid.\nProof.\n  exists (impl binZF). intros phi. unfold binFOL_valid, valid, entailment_binZF.\n  setoid_rewrite impl_sat. reflexivity.\nQed.\n\nLemma binFOL_valid_undec :\n  undecidable binFOL_valid.\nProof.\n  apply (undecidability_from_reducibility undecidable_entailment_binZF), binZF_binFOL_valid.\nQed.\n\nLemma binZF_binFOL_prv_intu :\n  deduction_binZF ⪯ binFOL_prv_intu.\nProof.\n  exists (impl binZF). intros phi. unfold binFOL_prv_intu, deduction_binZF.\n  setoid_rewrite <- impl_prv. rewrite List.app_nil_r.\n  split; intros H; apply (Weak H); unfold List.incl; apply List.in_rev.\nQed.\n\nLemma binFOL_prv_intu_undec :\n  undecidable binFOL_prv_intu.\nProof.\n  apply (undecidability_from_reducibility undecidable_deduction_binZF), binZF_binFOL_prv_intu.\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/FOL/Undecidability/binFOL_undec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.29810726372546426}}
{"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.\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 OrdStep.\nRequire Import Writes.\n\nSet Implicit Arguments.\n\n\nModule Normal.\n  Section Normal.\n    Variable L: Loc.t -> bool.\n\n    Definition normal_view (view: View.t): Prop :=\n      forall loc (LOC: L loc), (View.rlx view) loc = (View.pln view) loc.\n\n    Variant normal_tview (tview:TView.t): Prop :=\n    | normal_tview_intro\n        (REL: forall loc, normal_view ((TView.rel tview) loc))\n        (CUR: normal_view (TView.cur tview))\n        (ACQ: normal_view (TView.acq tview))\n    .\n\n    Definition normal_memory (mem: Memory.t): Prop :=\n      forall loc from to val released\n        (GET: Memory.get loc to mem = Some (from, Message.concrete val (Some released))),\n        normal_view released.\n\n    Inductive normal_thread {lang: language} (e: Thread.t lang): Prop :=\n    | normal_thread_intro\n        (NORMAL_TVIEW: normal_tview (Local.tview (Thread.local e)))\n        (NORMAL_MEMORY: normal_memory (Thread.memory e))\n    .\n    Hint Constructors normal_thread: core.\n\n    Lemma join_normal_view\n          view1 view2\n          (NORMAL1: normal_view view1)\n          (NORMAL2: normal_view view2):\n      normal_view (View.join view1 view2).\n    Proof.\n      ii. unfold normal_view in *.\n      destruct view1, view2. ss.\n      unfold TimeMap.join.\n      rewrite NORMAL1, NORMAL2; ss.\n    Qed.\n\n    Lemma singleton_ur_normal_view loc ts:\n      normal_view (View.singleton_ur loc ts).\n    Proof. ss. Qed.\n\n    Lemma singleton_rw_normal_view\n          loc ts\n          (LOC: ~ L loc):\n      normal_view (View.singleton_rw loc ts).\n    Proof.\n      ii. ss.\n      unfold TimeMap.singleton, LocFun.add, LocFun.init, LocFun.find.\n      condtac; ss. subst. ss.\n    Qed.\n\n    Lemma singleton_ur_if_normal_view\n          b loc ts\n          (LOC: ~ L loc):\n      normal_view (View.singleton_ur_if b loc ts).\n    Proof.\n      unfold View.singleton_ur_if. condtac.\n      - apply singleton_ur_normal_view.\n      - apply singleton_rw_normal_view. ss.\n    Qed.\n\n    Lemma get_normal_view\n          mem loc from to val released\n          (MEM: normal_memory mem)\n          (GET: Memory.get loc to mem = Some (from, Message.concrete val released)):\n      normal_view (View.unwrap released).\n    Proof.\n      destruct released; ss. eapply MEM; eauto.\n    Qed.\n\n    Lemma promise\n          promises1 mem1 loc from to msg promises2 mem2 kind\n          (NORMAL_MEM1: normal_memory mem1)\n          (MSG: forall val released\n                  (MSG: msg = Message.concrete val (Some released)),\n              normal_view released)\n          (PROMISE: Memory.promise promises1 mem1 loc from to msg promises2 mem2 kind):\n      <<NORMAL_MEM2: normal_memory mem2>>.\n    Proof.\n      ii. revert GET. inv PROMISE; ss.\n      - erewrite Memory.add_o; eauto. condtac; ss; i.\n        + inv GET. eapply MSG; eauto.\n        + eapply NORMAL_MEM1; eauto.\n      - erewrite Memory.split_o; eauto. repeat condtac; ss; i.\n        + inv GET. eapply MSG; eauto.\n        + guardH o. des. inv GET.\n          exploit Memory.split_get0; try exact MEM. i. des.\n          eapply NORMAL_MEM1; eauto.\n        + eapply NORMAL_MEM1; eauto.\n      - erewrite Memory.lower_o; eauto. condtac; ss; i.\n        + inv GET. eapply MSG; eauto.\n        + eapply NORMAL_MEM1; eauto.\n      - erewrite Memory.remove_o; eauto. condtac; ss; i.\n        eapply NORMAL_MEM1; eauto.\n    Qed.\n\n    Lemma write\n          promises1 mem1 loc from to msg promises2 mem2 kind\n          (NORMAL_MEM1: normal_memory mem1)\n          (MSG: forall val released\n                  (MSG: msg = Message.concrete val (Some released)),\n              normal_view released)\n          (WRITE: Memory.write promises1 mem1 loc from to msg promises2 mem2 kind):\n      <<NORMAL_MEM2: normal_memory mem2>>.\n    Proof.\n      inv WRITE. eauto using promise.\n    Qed.\n\n    Lemma write_na\n          ts promises1 mem1 loc from to msg promises2 mem2 msgs kinds kind\n          (NORMAL_MEM1: normal_memory mem1)\n          (WRITE: Memory.write_na ts promises1 mem1 loc from to msg promises2 mem2 msgs kinds kind):\n      <<NORMAL_MEM2: normal_memory mem2>>.\n    Proof.\n      induction WRITE.\n      - eapply write; eauto; ss.\n      - apply IHWRITE. eapply write; eauto.\n        unguard. des; subst; ss.\n    Qed.\n\n    Lemma promise_step\n          lc1 mem1 loc from to msg lc2 mem2 kind\n          (NORMAL_TVIEW1: normal_tview (Local.tview lc1))\n          (NORMAL_MEM1: normal_memory mem1)\n          (MSG: forall val released\n                  (MSG: msg = Message.concrete val (Some released)),\n              normal_view released)\n          (STEP: Local.promise_step lc1 mem1 loc from to msg lc2 mem2 kind):\n      <<NORMAL_TVIEW2: normal_tview (Local.tview lc2)>> /\\\n      <<NORMAL_MEM2: normal_memory mem2>>.\n    Proof.\n      inv STEP. splits; ss. eapply promise; eauto.\n    Qed.\n\n    Lemma read_step\n          lc1 mem1 loc to val released ord lc2\n          (WF1: Local.wf lc1 mem1)\n          (NORMAL_TVIEW1: normal_tview (Local.tview lc1))\n          (NORMAL_MEM1: normal_memory mem1)\n          (STEP: Local.read_step lc1 mem1 loc to val released ord lc2)\n          (TO: L loc -> Ordering.le ord Ordering.plain ->\n               to = (TView.cur (Local.tview lc1)).(View.rlx) loc):\n      <<NORMAL_TVIEW2: normal_tview (Local.tview lc2)>>.\n    Proof.\n      destruct lc1. inv NORMAL_TVIEW1. inv STEP. ss.\n      hexploit get_normal_view; eauto. i.\n      destruct (classic (L loc /\\ Ordering.le ord Ordering.plain)).\n      { des. exploit TO; eauto. i. subst.\n        econs; ss.\n        - apply join_normal_view.\n          + rewrite View.le_join_l; ss.\n            apply View.singleton_ur_if_spec; try apply WF1.\n            condtac; try refl. rewrite CUR; ss. refl.\n          + condtac; ss.\n        - apply join_normal_view.\n          + rewrite View.le_join_l; ss.\n            apply View.singleton_ur_if_spec; try apply WF1.\n            condtac; try apply WF1. rewrite CUR; ss. apply WF1.\n          + condtac; ss.\n      }\n      { econs; ss.\n        - repeat apply join_normal_view; try condtac; ss.\n          unfold View.singleton_ur_if.\n          condtac; eauto using singleton_ur_normal_view.\n          destruct (L loc) eqn:LOC.\n          + exfalso. apply H0. destruct ord; ss.\n          + apply singleton_rw_normal_view; eauto. rewrite LOC. ss.\n        - condtac; repeat eapply join_normal_view; eauto; ss.\n          destruct (L loc) eqn:LOC.\n          + exfalso. apply H0. destruct ord; ss.\n          + apply singleton_rw_normal_view; eauto. rewrite LOC. ss.\n      }\n    Qed.\n\n    Lemma write_step\n          lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind\n          (NORMAL_TVIEW1: normal_tview (Local.tview lc1))\n          (NORMAL_MEM1: normal_memory mem1)\n          (RELEASEDM: normal_view (View.unwrap releasedm))\n          (STEP: Local.write_step lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind):\n      (<<NORMAL_TVIEW2: normal_tview (Local.tview lc2)>>) /\\\n      (<<NORMAL_MEM2: normal_memory mem2>>).\n    Proof.\n      destruct lc1. inv NORMAL_TVIEW1. inv STEP. ss.\n      hexploit write; eauto.\n      { i. revert MSG. unfold TView.write_released.\n        condtac; ss. i. inv MSG.\n        condtac; repeat apply join_normal_view; eauto.\n        - unfold LocFun.add. condtac; ss.\n          apply join_normal_view; ss.\n        - unfold LocFun.add. condtac; ss.\n          apply join_normal_view; ss.\n      }\n      i. des. splits; ss.\n      econs; repeat apply join_normal_view; ss;\n        try apply singleton_ur_normal_view. i.\n      unfold LocFun.add.\n      repeat condtac; ss; eauto;\n        repeat apply join_normal_view; ss.\n    Qed.\n\n    Lemma write_na_step\n          lc1 sc1 mem1 loc from to val ord lc2 sc2 mem2 msgs kinds kind\n          (NORMAL_TVIEW1: normal_tview (Local.tview lc1))\n          (NORMAL_MEM1: normal_memory mem1)\n          (STEP: Local.write_na_step lc1 sc1 mem1 loc from to val ord lc2 sc2 mem2 msgs kinds kind):\n      (<<NORMAL_TVIEW2: normal_tview (Local.tview lc2)>>) /\\\n      (<<NORMAL_MEM2: normal_memory mem2>>).\n    Proof.\n      destruct lc1. inv NORMAL_TVIEW1. inv STEP. ss.\n      hexploit write_na; eauto. i. des. splits; ss.\n      econs; repeat apply join_normal_view; ss;\n        try apply singleton_ur_normal_view. i.\n      unfold LocFun.add.\n      repeat condtac; ss; eauto;\n        repeat apply join_normal_view; ss.\n    Qed.\n\n    Lemma fence_step\n          lc1 sc1 ordr ordw lc2 sc2\n          (NORMAL_TVIEW1: normal_tview (Local.tview lc1))\n          (STEP: Local.fence_step lc1 sc1 ordr ordw lc2 sc2):\n      (<<NORMAL_TVIEW2: normal_tview (Local.tview lc2)>>).\n    Proof.\n      inv NORMAL_TVIEW1. inv STEP. ss.\n      econs; ss; i; repeat condtac; ss;\n        repeat apply join_normal_view; ss.\n    Qed.\n\n    Lemma ord_program_step\n          ordcr ordcw e lc1 sc1 mem1 lc2 sc2 mem2\n          (WF1: Local.wf lc1 mem1)\n          (NORMAL_TVIEW1: normal_tview (Local.tview lc1))\n          (NORMAL_MEM1: normal_memory mem1)\n          (STEP: OrdLocal.program_step L ordcr ordcw e lc1 sc1 mem1 lc2 sc2 mem2)\n          (READ: forall loc to val released ord\n                   (EVENT: ThreadEvent.is_reading e = Some (loc, to, val, released, ord))\n                   (LOC: L loc)\n                   (ORD: Ordering.le ord Ordering.plain),\n              to = (TView.cur (Local.tview lc1)).(View.rlx) loc):\n      (<<NORMAL_TVIEW2: normal_tview (Local.tview lc2)>>) /\\\n      (<<NORMAL_MEM2: normal_memory mem2>>).\n    Proof.\n      inv STEP; ss.\n      - inv LOCAL. hexploit read_step; eauto.\n        i. exploit READ; eauto.\n        revert H0. condtac; ss. destruct ord, ordcr; ss.\n      - inv LOCAL. hexploit write_step; eauto. ss.\n      - inv LOCAL1. inv LOCAL2.\n        hexploit read_step; eauto.\n        { i. exploit READ; eauto.\n          revert H0. condtac; ss. destruct ordr, ordcr; ss.\n        }\n        i. des.\n        hexploit write_step; eauto.\n        inv STEP. ss. eapply get_normal_view; eauto.\n      - hexploit fence_step; eauto.\n      - hexploit fence_step; eauto.\n      - inv LOCAL.\n        + hexploit write_na_step; eauto.\n        + hexploit write_step; eauto. ss.\n    Qed.\n\n    Lemma future_normal_thread\n          lang e sc' mem'\n          (NORMAL: @normal_thread lang e)\n          (NORMAL_MEM: normal_memory mem'):\n      normal_thread (Thread.mk _ (Thread.state e) (Thread.local e) sc' mem').\n    Proof.\n      inv NORMAL. econs; ss.\n    Qed.\n  End Normal.\nEnd Normal.\n\n\nModule Stable.\n  Section Stable.\n    Variable L: Loc.t -> bool.\n\n    Definition stable_view (mem: Memory.t) (view: View.t): Prop :=\n      forall loc from val released\n        (LOC: L loc)\n        (GET: Memory.get loc ((View.rlx view) loc) mem =\n              Some (from, Message.concrete val (Some released))),\n        View.le released view.\n\n    Definition stable_timemap (mem: Memory.t) (tm: TimeMap.t): Prop :=\n      stable_view mem (View.mk tm tm).\n\n    Inductive stable_tview (mem: Memory.t) (tview: TView.t): Prop :=\n    | stable_tview_intro\n        (REL: forall loc (LOC: ~ L loc), stable_view mem ((TView.rel tview) loc))\n        (CUR: stable_view mem (TView.cur tview))\n        (ACQ: stable_view mem (TView.acq tview))\n    .\n\n    Definition stable_memory (rels: Writes.t) (mem: Memory.t): Prop :=\n      forall loc from to val released\n        (LOC: ~ L loc \\/\n              exists ord, List.In (loc, to, ord) rels /\\ Ordering.le Ordering.acqrel ord)\n        (GET: Memory.get loc to mem = Some (from, Message.concrete val (Some released))),\n        stable_view mem released.\n\n    Inductive stable_thread {lang: language} (rels: Writes.t) (e: Thread.t lang): Prop :=\n    | stable_thread_intro\n        (STABLE_TVIEW: Stable.stable_tview (Thread.memory e) (Local.tview (Thread.local e)))\n        (STABLE_SC: Stable.stable_timemap (Thread.memory e) (Thread.sc e))\n        (STABLE_MEMORY: Stable.stable_memory rels (Thread.memory e))\n    .\n    Hint Constructors stable_thread: core.\n\n\n    Lemma future_stable_view\n          mem1 mem2 view\n          (CLOSED: Memory.closed_view view mem1)\n          (STABLE: stable_view mem1 view)\n          (MEM_FUTURE: Memory.future mem1 mem2):\n      stable_view mem2 view.\n    Proof.\n      ii. inv CLOSED. specialize (RLX loc). des.\n      exploit Memory.future_get1; try exact RLX; eauto; ss. i. des.\n      rewrite GET0 in *. inv GET. inv MSG_LE. inv RELEASED.\n      exploit STABLE; eauto.\n    Qed.\n\n    Lemma future_stable_tview\n          mem1 mem2 tview\n          (CLOSED: TView.closed tview mem1)\n          (STABLE: stable_tview mem1 tview)\n          (MEM_FUTURE: Memory.future mem1 mem2):\n      stable_tview mem2 tview.\n    Proof.\n      destruct tview. inv CLOSED. inv STABLE. ss.\n      econs; ss; eauto using future_stable_view.\n    Qed.\n\n    Lemma future_stable_thread\n          lang rels e sc' mem'\n          (WF: Local.wf (Thread.local e) (Thread.memory e))\n          (STABLE: stable_thread rels e)\n          (SC: TimeMap.le (Thread.sc e) sc')\n          (MEM: Memory.future (Thread.memory e) mem')\n          (STABLE_SC: Stable.stable_timemap mem' sc')\n          (STABLE_MEM: Stable.stable_memory rels mem'):\n      stable_thread rels (Thread.mk lang (Thread.state e) (Thread.local e) sc' mem').\n    Proof.\n      destruct e, local. inv STABLE. inv WF. ss.\n      econs; i; ss; eauto using Stable.future_stable_tview.\n    Qed.\n\n    Lemma join_stable_view\n          mem view1 view2\n          (STABLE1: stable_view mem view1)\n          (STABLE2: stable_view mem view2):\n      stable_view mem (View.join view1 view2).\n    Proof.\n      ii. unfold stable_view in *.\n      unfold View.join, TimeMap.join in GET. ss.\n      exploit Time.join_cases. i. des.\n      - erewrite x0 in GET.\n        exploit STABLE1; eauto. i.\n        etrans; eauto. apply View.join_l.\n      - erewrite x0 in GET.\n        exploit STABLE2; eauto. i.\n        etrans; eauto. apply View.join_r.\n    Qed.\n\n    Lemma bot_stable_view\n          mem\n          (MEM: Memory.closed mem):\n      stable_view mem View.bot.\n    Proof.\n      ii. inv MEM. rewrite INHABITED in *. inv GET.\n    Qed.\n\n    Lemma singleton_ur_stable_view\n          mem loc ts\n          (MEM: Memory.closed mem)\n          (LOC: ~ L loc):\n      stable_view mem (View.singleton_ur loc ts).\n    Proof.\n      ii. revert GET. ss.\n      unfold TimeMap.singleton, LocFun.add, LocFun.init, LocFun.find.\n      condtac; subst; ss. i.\n      inv MEM. rewrite INHABITED in *. inv GET.\n    Qed.\n\n    Lemma singleton_rw_stable_view\n          mem loc ts\n          (MEM: Memory.closed mem)\n          (LOC: ~ L loc):\n      stable_view mem (View.singleton_rw loc ts).\n    Proof.\n      ii. revert GET. ss.\n      unfold TimeMap.singleton, LocFun.add, LocFun.init, LocFun.find.\n      condtac; subst; ss. i.\n      inv MEM. rewrite INHABITED in *. inv GET.\n    Qed.\n\n    Lemma singleton_ur_if_stable_view\n          mem b loc ts\n          (MEM: Memory.closed mem)\n          (LOC: ~ L loc):\n      stable_view mem (View.singleton_ur_if b loc ts).\n    Proof.\n      unfold View.singleton_ur_if. condtac.\n      - apply singleton_ur_stable_view; ss.\n      - apply singleton_rw_stable_view; ss.\n    Qed.\n\n    Lemma stable_view_stable_timemap\n          mem view\n          (VIEW: View.wf view)\n          (STABLE: stable_view mem view):\n      stable_timemap mem (View.rlx view).\n    Proof.\n      ii. etrans; [eapply STABLE|]; eauto.\n      econs; ss; try refl. apply VIEW.\n    Qed.\n\n    Lemma join_stable_timemap\n          mem tm1 tm2\n          (STABLE1: stable_timemap mem tm1)\n          (STABLE2: stable_timemap mem tm2):\n      stable_timemap mem (TimeMap.join tm1 tm2).\n    Proof.\n      unfold stable_timemap in *.\n      hexploit join_stable_view; [exact STABLE1|exact STABLE2|]. ss.\n    Qed.\n\n    Lemma stable_tview_read_tview\n          mem tview\n          loc from val released ord\n          (WF: TView.wf tview)\n          (NORMAL: Normal.normal_tview L tview)\n          (STABLE: stable_tview mem tview)\n          (LOC: L loc)\n          (GET: Memory.get loc ((View.rlx (TView.cur tview)) loc) mem =\n                Some (from, Message.concrete val released)):\n      TView.read_tview tview loc ((View.rlx (TView.cur tview)) loc) released ord = tview.\n    Proof.\n      inv STABLE. inv NORMAL.\n      destruct tview. unfold TView.read_tview. ss. f_equal.\n      - rewrite (@View.le_join_l cur); cycle 1.\n        { unfold View.singleton_ur_if. condtac; ss.\n          - unfold View.singleton_ur. econs; ss.\n            + ii. unfold TimeMap.singleton, LocFun.add, LocFun.find, LocFun.init.\n              condtac; try apply Time.bot_spec. subst.\n              rewrite CUR0; ss. refl.\n            + ii. unfold TimeMap.singleton, LocFun.add, LocFun.find, LocFun.init.\n              condtac; try apply Time.bot_spec. subst. refl.\n          - unfold View.singleton_rw. econs; ss; try apply TimeMap.bot_spec.\n            ii. unfold TimeMap.singleton, LocFun.add, LocFun.find, LocFun.init.\n            condtac; try apply Time.bot_spec. subst. refl.\n        }\n        condtac; try apply View.join_bot_r.\n        apply View.le_join_l.\n        destruct released; eauto. apply View.bot_spec.\n      - rewrite (@View.le_join_l acq); cycle 1.\n        { etrans; [|eapply WF]. ss.\n          unfold View.singleton_ur_if. condtac; ss.\n          - unfold View.singleton_ur. econs; ss.\n            + ii. unfold TimeMap.singleton, LocFun.add, LocFun.find, LocFun.init.\n              condtac; try apply Time.bot_spec. subst.\n              rewrite CUR0; ss. refl.\n            + ii. unfold TimeMap.singleton, LocFun.add, LocFun.find, LocFun.init.\n              condtac; try apply Time.bot_spec. subst. refl.\n          - unfold View.singleton_rw. econs; ss; try apply TimeMap.bot_spec.\n            ii. unfold TimeMap.singleton, LocFun.add, LocFun.find, LocFun.init.\n            condtac; try apply Time.bot_spec. subst. refl.\n        }\n        condtac; try apply View.join_bot_r.\n        apply View.le_join_l.\n        etrans; [|eapply WF]. ss.\n        destruct released; eauto. apply View.bot_spec.\n    Qed.\n\n    Lemma stable_memory_tail\n          a rels mem\n          (STABLE: stable_memory (a :: rels) mem):\n      stable_memory rels mem.\n    Proof.\n      ii. des.\n      - eapply STABLE; eauto.\n      - eapply STABLE; eauto. ss.\n        right. esplits; eauto.\n    Qed.\n\n    Lemma promise_stable_view\n          view promises1 mem1 loc from to msg promises2 mem2 kind\n          (CLOSED1: Memory.closed_view view mem1)\n          (STABLE1: stable_view mem1 view)\n          (PROMISE: Memory.promise promises1 mem1 loc from to msg promises2 mem2 kind):\n      stable_view mem2 view.\n    Proof.\n      ii. revert GET. inv PROMISE; ss.\n      { erewrite Memory.add_o; eauto. condtac; ss; eauto.\n        i. des. inv GET.\n        exploit Memory.add_get0; try exact MEM. i. des.\n        inv CLOSED1. specialize (RLX loc). des. congr.\n      }\n      { erewrite Memory.split_o; eauto. repeat condtac; ss; eauto.\n        - i. des. inv GET.\n          exploit Memory.split_get0; try exact MEM. i. des.\n          inv CLOSED1. specialize (RLX loc). des. congr.\n        - guardH o. i. des. inv GET.\n          exploit Memory.split_get0; try exact MEM. i. des. eauto.\n      }\n      { erewrite Memory.lower_o; eauto. condtac; ss; eauto.\n        i. des. inv GET.\n        exploit Memory.lower_get0; try exact MEM. i. des.\n        inv MSG_LE. inv RELEASED. etrans; eauto.\n      }\n      { erewrite Memory.remove_o; eauto. condtac; ss; eauto. }\n    Qed.\n\n    Lemma write_stable_view\n          view promises1 mem1 loc from to msg promises2 mem2 kind\n          (CLOSED1: Memory.closed_view view mem1)\n          (STABLE1: stable_view mem1 view)\n          (WRITE: Memory.write promises1 mem1 loc from to msg promises2 mem2 kind):\n      stable_view mem2 view.\n    Proof.\n      inv WRITE. eauto using promise_stable_view.\n    Qed.\n\n    Lemma write_na_stable_view\n          view ts promises1 mem1 loc from to msg promises2 mem2 msgs kinds kind\n          (CLOSED1: Memory.closed_view view mem1)\n          (STABLE1: stable_view mem1 view)\n          (WRITE: Memory.write_na ts promises1 mem1 loc from to msg promises2 mem2 msgs kinds kind):\n      stable_view mem2 view.\n    Proof.\n      induction WRITE; eauto using write_stable_view.\n      hexploit write_stable_view; try exact WRITE_EX; eauto. i.\n      hexploit Memory.write_closed_view; try exact WRITE_EX; eauto.\n    Qed.\n\n    Lemma promise_stable_tview\n          tview promises1 mem1 loc from to msg promises2 mem2 kind\n          (CLOSED1: TView.closed tview mem1)\n          (STABLE1: stable_tview mem1 tview)\n          (PROMISE: Memory.promise promises1 mem1 loc from to msg promises2 mem2 kind):\n      stable_tview mem2 tview.\n    Proof.\n      inv CLOSED1. inv STABLE1.\n      econs; eauto using promise_stable_view.\n    Qed.\n\n    Lemma write_stable_tview\n          tview promises1 mem1 loc from to msg promises2 mem2 kind\n          (CLOSED1: TView.closed tview mem1)\n          (STABLE1: stable_tview mem1 tview)\n          (WRITE: Memory.write promises1 mem1 loc from to msg promises2 mem2 kind):\n      stable_tview mem2 tview.\n    Proof.\n      inv CLOSED1. inv STABLE1.\n      econs; eauto using write_stable_view.\n    Qed.\n\n    Lemma write_na_stable_tview\n          tview ts promises1 mem1 loc from to msg promises2 mem2 msgs kinds kind\n          (CLOSED1: TView.closed tview mem1)\n          (STABLE1: stable_tview mem1 tview)\n          (WRITE: Memory.write_na ts promises1 mem1 loc from to msg promises2 mem2 msgs kinds kind):\n      stable_tview mem2 tview.\n    Proof.\n      inv CLOSED1. inv STABLE1.\n      econs; eauto using write_na_stable_view.\n    Qed.\n\n    Lemma promise_stable_memory\n          rels promises1 mem1 loc from to msg promises2 mem2 kind\n          (MEM1: Memory.closed mem1)\n          (STABLE_MEM1: stable_memory rels mem1)\n          (MSG: forall val released\n                  (MSG: msg = Message.concrete val (Some released)),\n              stable_view mem2 released)\n          (PROMISE: Memory.promise promises1 mem1 loc from to msg promises2 mem2 kind):\n      stable_memory rels mem2.\n    Proof.\n      unfold stable_memory in *. i. revert GET. guardH LOC.\n      dup PROMISE. inv PROMISE0; ss.\n      { (* add *)\n        erewrite Memory.add_o; eauto. condtac; ss; i.\n        - des. inv GET. eauto.\n        - guardH o.\n          inv MEM1. exploit CLOSED; eauto. i. des. inv MSG_CLOSED. inv CLOSED0.\n          hexploit STABLE_MEM1; eauto. i.\n          eapply promise_stable_view; eauto.\n      }\n      { (* split *)\n        erewrite Memory.split_o; eauto. repeat condtac; ss; i.\n        - des. inv GET. eauto.\n        - guardH o. des. inv GET.\n          exploit Memory.split_get0; try exact MEM. i. des.\n          inv MEM1. exploit CLOSED; try exact GET0. i. des. inv MSG_CLOSED. inv CLOSED0.\n          hexploit STABLE_MEM1; try exact GET0; eauto. i.\n          eapply promise_stable_view; eauto.\n        - guardH o. guardH o0.\n          inv MEM1. exploit CLOSED; eauto. i. des. inv MSG_CLOSED. inv CLOSED0.\n          hexploit STABLE_MEM1; eauto. i.\n          eapply promise_stable_view; eauto.\n      }\n      { (* lower *)\n        erewrite Memory.lower_o; eauto. condtac; ss; i.\n        - des. inv GET. eauto.\n        - guardH o.\n          inv MEM1. exploit CLOSED; eauto. i. des. inv MSG_CLOSED. inv CLOSED0.\n          hexploit STABLE_MEM1; eauto. i.\n          eapply promise_stable_view; eauto.\n      }\n      { (* cancel *)\n        erewrite Memory.remove_o; eauto. condtac; ss; i.\n        guardH o.\n        inv MEM1. exploit CLOSED; eauto. i. des. inv MSG_CLOSED. inv CLOSED0.\n        hexploit STABLE_MEM1; eauto. i.\n        eapply promise_stable_view; eauto.\n      }\n    Qed.\n\n    Lemma write_stable_memory\n          ord\n          rels promises1 mem1 loc from to msg promises2 mem2 kind\n          (MEM1: Memory.closed mem1)\n          (STABLE_MEM1: stable_memory rels mem1)\n          (WRITES1: Writes.wf L rels mem1)\n          (RESERVE_ONLY1: OrdLocal.reserve_only L promises1)\n          (MSG: forall val released\n                  (LOC: ~ L loc \\/ Ordering.le Ordering.acqrel ord)\n                  (MSG: msg = Message.concrete val (Some released)),\n              stable_view mem2 released)\n          (WRITE: Memory.write promises1 mem1 loc from to msg promises2 mem2 kind):\n      stable_memory (if L loc then (loc, to, ord) :: rels else rels) mem2.\n    Proof.\n      destruct (L loc) eqn:LOC; cycle 1.\n      { inv WRITE. eauto using promise_stable_memory. }\n      exploit OrdLocal.reserve_only_write_add; eauto. i. subst.\n      inv WRITE. dup PROMISE. inv PROMISE0.\n      unfold stable_memory in *. i. revert GET.\n      erewrite Memory.add_o; eauto. condtac; ss; i.\n      - des; clarify; eauto.\n        inv WRITES1. exploit SOUND; eauto. i. des.\n        exploit Memory.add_get0; try exact MEM. i. des. congr.\n      - guardH o.\n        hexploit STABLE_MEM1; eauto; i.\n        { des; eauto. clarify. unguard. des; ss. }\n        clear LOC0.\n        inv MEM1. exploit CLOSED; eauto. i. des. inv MSG_CLOSED. inv CLOSED0.\n        eapply promise_stable_view; eauto.\n    Qed.\n\n    Lemma write_na_stable_memory\n          rels ts promises1 mem1 loc from to val promises2 mem2 msgs kinds kind\n          (MEM1: Memory.closed mem1)\n          (STABLE_MEM1: stable_memory rels mem1)\n          (WRITE: Memory.write_na ts promises1 mem1 loc from to val promises2 mem2 msgs kinds kind):\n      stable_memory rels mem2.\n    Proof.\n      induction WRITE.\n      - inv WRITE. eapply promise_stable_memory; eauto; ss.\n      - exploit Memory.write_closed; try exact WRITE_EX; ss.\n        { unguard. des; subst; ss. econs. ss. }\n        { unguard. des; subst; ss. econs. apply Time.bot_spec. }\n        i. inv WRITE_EX.\n        hexploit promise_stable_memory; try exact PROMISE; eauto.\n        i. subst. unguard. des; ss.\n    Qed.\n\n    Lemma stable_memory_strong_relaxed\n          rels mem loc to ord\n          (ORD: Ordering.le ord Ordering.strong_relaxed):\n      stable_memory rels mem <-> stable_memory ((loc, to, ord) :: rels) mem.\n    Proof.\n      split; ii.\n      - eapply H; eauto. des; eauto.\n        inv LOC; eauto. inv H0. destruct ord0; ss.\n      - eapply H; eauto. des; eauto.\n        right. esplits; eauto. right. ss.\n    Qed.\n\n    Lemma stable_memory_le\n          rels mem loc to ord1 ord2\n          (STABLE_MEM1: stable_memory ((loc, to, ord1) :: rels) mem)\n          (ORD: Ordering.le ord2 ord1):\n      stable_memory ((loc, to, ord2) :: rels) mem.\n    Proof.\n      ii. eapply STABLE_MEM1; eauto. des; eauto. inv LOC.\n      - inv H. right. esplits; [left; eauto|]. etrans; eauto.\n      - right. esplits; [right; eauto|]. ss.\n    Qed.\n\n\n    (* step *)\n\n    Lemma promise_step\n          rels lc1 mem1 loc from to msg lc2 mem2 kind\n          (WF1: Local.wf lc1 mem1)\n          (MEM1: Memory.closed mem1)\n          (STABLE_TVIEW1: stable_tview mem1 (Local.tview lc1))\n          (STABLE_MEM1: stable_memory rels mem1)\n          (MSG: forall val released\n                  (MSG: msg = Message.concrete val (Some released)),\n              stable_view mem2 released)\n          (STEP: Local.promise_step lc1 mem1 loc from to msg lc2 mem2 kind):\n      <<STABLE_TVIEW2: stable_tview mem2 (Local.tview lc2)>> /\\\n      <<STABLE_MEM2: stable_memory rels mem2>>.\n    Proof.\n      inv STEP.\n      hexploit promise_stable_tview; eauto; try apply WF1. i.\n      hexploit promise_stable_memory; eauto.\n    Qed.\n\n    Lemma read_step_loc_cur\n          lc1 mem1 loc to val released ord lc2\n          (WF1: Local.wf lc1 mem1)\n          (NORMAL_TVIEW1: Normal.normal_tview L (Local.tview lc1))\n          (STABLE_TVIEW1: stable_tview mem1 (Local.tview lc1))\n          (LOC: L loc)\n          (TO: to = (TView.cur (Local.tview lc1)).(View.rlx) loc)\n          (STEP: Local.read_step lc1 mem1 loc to val released ord lc2):\n      <<LC2: lc2 = lc1>>.\n    Proof.\n      inv STEP. destruct lc1. f_equal; ss.\n      erewrite stable_tview_read_tview; eauto. apply WF1.\n    Qed.\n\n    Lemma read_step_loc_ra\n          rels ordw lc1 mem1 loc to val released ord lc2\n          (WF1: Local.wf lc1 mem1)\n          (MEM1: Memory.closed mem1)\n          (STABLE_TVIEW1: stable_tview mem1 (Local.tview lc1))\n          (STABLE_MEM1: stable_memory rels mem1)\n          (LOC: L loc)\n          (IN: List.In (loc, to, ordw) rels)\n          (ORDW: Ordering.le Ordering.acqrel ordw)\n          (ORD: Ordering.le Ordering.acqrel ord)\n          (STEP: Local.read_step lc1 mem1 loc to val released ord lc2):\n      <<STABLE_TVIEW2: stable_tview mem1 (Local.tview lc2)>>.\n    Proof.\n      inv STEP. ss.\n      inv STABLE_TVIEW1. econs; ss.\n      - unfold View.singleton_ur_if.\n        repeat (condtac; [|destruct ord; ss]). ii.\n        destruct (Loc.eq_dec loc loc0); subst; ss.\n        + unfold TimeMap.join, View.singleton_ur_if,\n            TimeMap.singleton, LocFun.add, LocFun.init, LocFun.find in GET0.\n          revert GET0. condtac; ss. i.\n          rewrite TimeFacts.le_join_l in GET0; cycle 1.\n          { etrans; [|eapply Time.join_r].\n            inv MEM1. exploit CLOSED; try exact GET. i. des.\n            inv MSG_TS. ss.\n          }\n          rewrite TimeFacts.le_join_r in GET0; cycle 1.\n          { inv READABLE. auto. }\n          rewrite GET0 in *. inv GET. ss.\n          etrans; [|apply View.join_r]. refl.\n        + unfold TimeMap.join, View.singleton_ur_if,\n            TimeMap.singleton, LocFun.add, LocFun.init, LocFun.find in GET0.\n          revert GET0. condtac; try congr; ss. i.\n          rewrite (@TimeFacts.le_join_l _ Time.bot) in GET0; try apply Time.bot_spec.\n          exploit Time.join_cases. i. des.\n          { rewrite x0 in GET0.\n            exploit CUR; eauto. i. etrans; eauto.\n            etrans; [|apply View.join_l].\n            etrans; [|apply View.join_l].\n            refl.\n          }\n          { rewrite x0 in GET0. destruct released; ss; cycle 1.\n            { unfold TimeMap.bot in *.\n              inv MEM1. rewrite INHABITED in GET0. ss. }\n            exploit STABLE_MEM1; try exact GET; eauto. i.\n            etrans; eauto.\n            etrans; [|apply View.join_r].\n            refl.\n          }\n      - unfold View.singleton_ur_if.\n        repeat (condtac; [|destruct ord; ss]). ii.\n        destruct (Loc.eq_dec loc loc0); subst; ss.\n        + unfold TimeMap.join, View.singleton_ur_if,\n            TimeMap.singleton, LocFun.add, LocFun.init, LocFun.find in GET0.\n          revert GET0. condtac; ss. i.\n          rewrite Time.join_assoc in GET0.\n          rewrite (@TimeFacts.le_join_l to) in GET0; cycle 1.\n          { inv MEM1. exploit CLOSED; try exact GET. i. des.\n            inv MSG_TS. ss. }\n          exploit Time.join_cases. i. des.\n          { rewrite x0 in GET0.\n            exploit ACQ; eauto. i. etrans; eauto.\n            etrans; [|apply View.join_l].\n            etrans; [|apply View.join_l].\n            refl.\n          }\n          { rewrite x0 in GET0. rewrite GET0 in *. inv GET. ss.\n            etrans; [|apply View.join_r].\n            refl.\n          }\n        + unfold TimeMap.join, View.singleton_ur_if,\n            TimeMap.singleton, LocFun.add, LocFun.init, LocFun.find in GET0.\n          revert GET0. condtac; try congr; ss. i.\n          rewrite (@TimeFacts.le_join_l _ Time.bot) in GET0; try apply Time.bot_spec.\n          exploit Time.join_cases. i. des.\n          { rewrite x0 in GET0.\n            exploit ACQ; eauto. i. etrans; eauto.\n            etrans; [|apply View.join_l].\n            etrans; [|apply View.join_l].\n            refl.\n          }\n          { rewrite x0 in GET0. destruct released; ss; cycle 1.\n            { unfold TimeMap.bot in *.\n              inv MEM1. rewrite INHABITED in GET0. ss. }\n            exploit STABLE_MEM1; try exact GET; eauto. i.\n            etrans; eauto.\n            etrans; [|apply View.join_r]. refl.\n          }\n    Qed.\n\n    Lemma read_step_other\n          rels lc1 mem1 loc to val released ord lc2\n          (WF1: Local.wf lc1 mem1)\n          (MEM1: Memory.closed mem1)\n          (STABLE_TVIEW1: stable_tview mem1 (Local.tview lc1))\n          (STABLE_MEM1: stable_memory rels mem1)\n          (LOC: ~ L loc)\n          (STEP: Local.read_step lc1 mem1 loc to val released ord lc2):\n      <<STABLE_TVIEW2: stable_tview mem1 (Local.tview lc2)>>.\n    Proof.\n      inv STEP. ss. splits; ss.\n      inv STABLE_TVIEW1. econs; ss.\n      + repeat apply join_stable_view; ss.\n        * apply singleton_ur_if_stable_view; ss.\n        * condtac; ss.\n          { destruct released; ss.\n            - eapply STABLE_MEM1; eauto.\n            - apply bot_stable_view; ss. }\n          { apply bot_stable_view; ss. }\n      + repeat apply join_stable_view; ss.\n        * apply singleton_ur_if_stable_view; ss.\n        * condtac; ss.\n          { destruct released; ss.\n            - eapply STABLE_MEM1; eauto.\n            - apply bot_stable_view; ss. }\n          { apply bot_stable_view; ss. }\n    Qed.\n\n    Lemma write_tview_stable\n          mem tview sc loc to ord\n          (WF: TView.wf tview)\n          (MEM: Memory.closed mem)\n          (STABLE: stable_tview mem tview)\n          (WRITABLE: TView.writable (TView.cur tview) sc loc to ord)\n          (TO: forall from val released\n                 (LOC: L loc)\n                 (GET: Memory.get loc to mem = Some (from, Message.concrete val (Some released))),\n              View.le released (TView.cur (TView.write_tview tview sc loc to ord))):\n      stable_tview mem (TView.write_tview tview sc loc to ord).\n    Proof.\n      inv WRITABLE. inv STABLE. econs; ss; i.\n      { condtac; ss.\n        - unfold LocFun.add, LocFun.find.\n          condtac; ss; eauto. subst.\n          apply join_stable_view; eauto.\n          apply singleton_ur_stable_view; eauto.\n        - unfold LocFun.add, LocFun.find.\n          condtac; ss; eauto. subst.\n          apply join_stable_view; eauto.\n          apply singleton_ur_stable_view; eauto.\n      }\n      { ii. ss. revert GET.\n        unfold TimeMap.join, TimeMap.singleton, LocFun.add, LocFun.init, LocFun.find.\n        condtac; ss.\n        - subst. rewrite TimeFacts.le_join_r; [|econs; ss]. eauto.\n        - rewrite TimeFacts.le_join_l; try apply Time.bot_spec. i.\n          exploit CUR; eauto. i.\n          etrans; eauto. apply View.join_l.\n      }\n      { ii. ss. revert GET.\n        unfold TimeMap.join, TimeMap.singleton, LocFun.add, LocFun.init, LocFun.find.\n        condtac; ss.\n        - subst. exploit Time.join_cases. intro JOIN. des; rewrite JOIN; i.\n          + exploit ACQ; eauto. i.\n            etrans; eauto. apply View.join_l.\n          + exploit TO; eauto. i.\n            etrans; eauto.\n            eapply View.join_spec; try apply View.join_r.\n            etrans; [|apply View.join_l]. apply WF.\n        - rewrite TimeFacts.le_join_l; try apply Time.bot_spec. i.\n          exploit ACQ; eauto. i.\n          etrans; eauto. apply View.join_l.\n      }\n    Qed.\n\n    Lemma write_step\n          rels lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind\n          (WF1: Local.wf lc1 mem1)\n          (SC1: Memory.closed_timemap sc1 mem1)\n          (MEM1: Memory.closed mem1)\n          (RELS_WF1: Writes.wf L rels mem1)\n          (RESERVE_ONLY1: OrdLocal.reserve_only L (Local.promises lc1))\n          (STABLE_TVIEW1: stable_tview mem1 (Local.tview lc1))\n          (STABLE_MEM1: stable_memory rels mem1)\n          (WF_RELEASEDM: View.opt_wf releasedm)\n          (CLOSED_RELEASEDM: Memory.closed_opt_view releasedm mem1)\n          (STABLE_RELEASEDM: ~ L loc -> stable_view mem1 (View.unwrap releasedm))\n          (RELEASEDM: L loc -> View.le (View.unwrap releasedm) (TView.cur (Local.tview lc1)))\n          (STEP: Local.write_step lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind):\n      <<STABLE_TVIEW2: stable_tview mem2 (Local.tview lc2)>> /\\\n      <<STABLE_MEM2: stable_memory (if L loc then (loc, to, ord) :: rels else rels) mem2>>.\n    Proof.\n      exploit Local.write_step_future; try exact STEP; eauto. i. des.\n      inv STEP. ss.\n      hexploit write_stable_tview; eauto; try apply WF1. i.\n      assert (REL: forall released\n                     (LOC: L loc)\n                     (REL: Some released = TView.write_released (Local.tview lc1) sc1 loc to releasedm ord),\n                 View.le released (TView.cur (TView.write_tview (Local.tview lc1) sc1 loc to ord))).\n      { unfold TView.write_released. condtac; ss. i. inv REL.\n        unfold LocFun.add. repeat condtac; ss.\n        - apply View.join_spec; try refl.\n          etrans; eauto. apply View.join_l.\n        - apply View.join_spec.\n          + etrans; eauto. apply View.join_l.\n          + apply View.join_spec; try by apply View.join_r.\n            etrans; [|apply View.join_l]. apply WF1.\n      }\n      hexploit write_tview_stable; try exact H; eauto; try apply WF1.\n      { i. exploit Memory.write_get2; eauto. i. des.\n        rewrite GET in *. inv GET_MEM. eauto.\n      }\n      i. splits; auto.\n      eapply write_stable_memory; try exact WRITE; eauto. i.\n      revert MSG. unfold TView.write_released. condtac; ss. i. inv MSG.\n      unfold LocFun.add. condtac; ss.\n      destruct (classic (L loc)).\n      - des; ss. condtac; try by destruct ord; ss.\n        rewrite View.le_join_r; cycle 1.\n        { etrans; [|apply View.join_l]. apply RELEASEDM. ss. }\n        ii. ss. revert GET.\n        unfold TimeMap.join, TimeMap.singleton, LocFun.add, LocFun.init, LocFun.find.\n        condtac; ss.\n        + subst. rewrite TimeFacts.le_join_r; cycle 1.\n          { inv WRITABLE. econs. ss. }\n          exploit Memory.write_get2; eauto. i. des.\n          rewrite GET in *. inv GET_MEM. eauto.\n        + rewrite TimeFacts.le_join_l; try apply Time.bot_spec. i.\n          etrans; [|apply View.join_l].\n          inv H. eapply CUR; eauto.\n      - guardH LOC. inv STABLE_TVIEW1.\n        condtac; ss; repeat apply join_stable_view;\n          (try by apply singleton_ur_stable_view);\n          try eapply write_stable_view; eauto; try apply WF1.\n        + apply Memory.unwrap_closed_opt_view; ss. apply MEM1.\n        + apply Memory.unwrap_closed_opt_view; ss. apply MEM1.\n    Qed.\n\n    Lemma write_na_get_to\n          ts promises1 mem1 loc from to val promsies2 mem2 msgs kinds kind\n          (WRITE: Memory.write_na ts promises1 mem1 loc from to val promsies2 mem2 msgs kinds kind):\n      Memory.get loc to mem2 = Some (from, Message.concrete val None).\n    Proof.\n      induction WRITE; eauto.\n      exploit Memory.write_get2; eauto. i. des. ss.\n    Qed.\n\n    Lemma write_na_step\n          rels lc1 sc1 mem1 loc from to val ord lc2 sc2 mem2 msgs kinds kind\n          (WF1: Local.wf lc1 mem1)\n          (SC1: Memory.closed_timemap sc1 mem1)\n          (MEM1: Memory.closed mem1)\n          (RELS_WF1: Writes.wf L rels mem1)\n          (RESERVE_ONLY1: OrdLocal.reserve_only L (Local.promises lc1))\n          (STABLE_TVIEW1: stable_tview mem1 (Local.tview lc1))\n          (STABLE_MEM1: stable_memory rels mem1)\n          (STEP: Local.write_na_step lc1 sc1 mem1 loc from to val ord lc2 sc2 mem2 msgs kinds kind):\n      <<STABLE_TVIEW2: stable_tview mem2 (Local.tview lc2)>> /\\\n      <<STABLE_MEM2: stable_memory (if L loc then (loc, to, ord) :: rels else rels) mem2>>.\n    Proof.\n      exploit Local.write_na_step_future; try exact STEP; eauto. i. des.\n      inv STEP. ss.\n      hexploit write_na_stable_tview; eauto; try apply WF1. i.\n      exploit Memory.write_na_times; eauto. i. des.\n      hexploit write_tview_stable; try exact H; eauto; try apply WF1.\n      { econs. eauto. }\n      { i. apply write_na_get_to in WRITE. congr. }\n      i. splits; eauto.\n      eapply write_na_stable_memory; try exact WRITE; eauto.\n      condtac; ss. rewrite <- stable_memory_strong_relaxed; eauto.\n    Qed.\n\n    Lemma fence_step\n          rels lc1 sc1 mem1 ordr ordw lc2 sc2\n          (WF1: Local.wf lc1 mem1)\n          (NORMAL_TVIEW1: Normal.normal_tview L (Local.tview lc1))\n          (STABLE_TVIEW1: stable_tview mem1 (Local.tview lc1))\n          (STABLE_SC1: stable_timemap mem1 sc1)\n          (RELS_WF1: Writes.wf L rels mem1)\n          (STEP: Local.fence_step lc1 sc1 ordr ordw lc2 sc2):\n      <<STABLE_TVIEW2: stable_tview mem1 (Local.tview lc2)>> /\\\n      <<STABLE_SC2: stable_timemap mem1 sc2>>.\n    Proof.\n      inv STEP. ss. splits; ss.\n      - inv STABLE_TVIEW1.\n        econs; ss; i; repeat (condtac; ss); eauto.\n        + unfold TView.write_fence_sc. repeat (condtac; ss).\n          * hexploit join_stable_view; [apply STABLE_SC1| apply ACQ|]. i.\n            unfold View.join in H. ss. ii.\n            etrans; [eapply H; eauto|].\n            econs; try refl. ss.\n            apply TimeMap.join_spec.\n            { apply TimeMap.join_l. }\n            { etrans; [|apply TimeMap.join_r]. apply WF1. }\n          * hexploit join_stable_view; [apply STABLE_SC1| apply CUR|]. i.\n            unfold View.join in H. ss. ii.\n            etrans; [eapply H; eauto|].\n            econs; try refl. ss.\n            apply TimeMap.join_spec.\n            { apply TimeMap.join_l. }\n            { etrans; [|apply TimeMap.join_r]. apply WF1. }\n        + unfold TView.write_fence_sc. repeat (condtac; ss).\n          * hexploit join_stable_view; [apply STABLE_SC1| apply ACQ|]. i.\n            unfold View.join in H. ss. ii.\n            etrans; [eapply H; eauto|].\n            econs; try refl. ss.\n            apply TimeMap.join_spec.\n            { apply TimeMap.join_l. }\n            { etrans; [|apply TimeMap.join_r]. apply WF1. }\n          * hexploit join_stable_view; [apply STABLE_SC1| apply CUR|]. i.\n            unfold View.join in H. ss. ii.\n            etrans; [eapply H; eauto|].\n            econs; try refl. ss.\n            apply TimeMap.join_spec.\n            { apply TimeMap.join_l. }\n            { etrans; [|apply TimeMap.join_r]. apply WF1. }\n        + unfold TView.write_fence_sc. repeat (condtac; ss).\n          * apply join_stable_view; ss.\n            hexploit join_stable_view; [apply STABLE_SC1| apply ACQ|]. i.\n            unfold View.join in H. ss. ii.\n            etrans; [eapply H; eauto|].\n            econs; try refl. ss.\n            apply TimeMap.join_spec.\n            { apply TimeMap.join_l. }\n            { etrans; [|apply TimeMap.join_r]. apply WF1. }\n          * apply join_stable_view; ss.\n            hexploit join_stable_view; [apply STABLE_SC1| apply CUR|]. i.\n            unfold View.join in H. ss. ii.\n            etrans; [eapply H; eauto|].\n            econs; try refl. ss.\n            apply TimeMap.join_spec.\n            { apply TimeMap.join_l. }\n            { etrans; [|apply TimeMap.join_r]. apply WF1. }\n        + rewrite View.le_join_l; try by apply View.bot_spec. ss.\n      - unfold TView.write_fence_sc. repeat (condtac; ss).\n        + eapply join_stable_timemap; ss.\n          apply stable_view_stable_timemap.\n          * apply WF1.\n          * apply STABLE_TVIEW1.\n        + eapply join_stable_timemap; ss.\n          apply stable_view_stable_timemap.\n          * apply WF1.\n          * apply STABLE_TVIEW1.\n    Qed.\n\n\n    (* cap *)\n\n    Lemma max_concrete_timemap_stable\n          mem tm\n          (CLOSED: Memory.closed mem)\n          (MAX: Memory.max_concrete_timemap mem tm):\n      stable_timemap mem tm.\n    Proof.\n      ii. dup CLOSED. inv CLOSED.\n      exploit CLOSED1; eauto. i. des. inv MSG_CLOSED. inv CLOSED. inv CLOSED2.\n      hexploit Memory.max_concrete_timemap_spec; try exact PLN; eauto. i.\n      hexploit Memory.max_concrete_timemap_spec; try exact RLX; eauto. i.\n      econs; ss.\n    Qed.\n\n    Lemma cap_normal_memory\n          mem1 mem2\n          (CLOSED: Memory.closed mem1)\n          (CAP: Memory.cap mem1 mem2)\n          (NORMAL: Normal.normal_memory L mem1):\n      Normal.normal_memory L mem2.\n    Proof.\n      ii. exploit Memory.cap_inv; eauto. i. des; ss.\n      eapply NORMAL; eauto.\n    Qed.\n\n    Lemma cap_stable_view\n          mem1 mem2 view\n          (CLOSED: Memory.closed mem1)\n          (CAP: Memory.cap mem1 mem2)\n          (STABLE: stable_view mem1 view):\n      stable_view mem2 view.\n    Proof.\n      ii. exploit Memory.cap_inv; eauto. i. des; ss.\n      eapply STABLE; eauto.\n    Qed.\n\n    Lemma cap_stable_timemap\n          mem1 mem2 tm\n          (CLOSED: Memory.closed mem1)\n          (CAP: Memory.cap mem1 mem2)\n          (STABLE: stable_timemap mem1 tm):\n      stable_timemap mem2 tm.\n    Proof.\n      eapply cap_stable_view; eauto.\n    Qed.\n\n    Lemma cap_stable_tview\n          mem1 mem2 tview\n          (CLOSED: Memory.closed mem1)\n          (CAP: Memory.cap mem1 mem2)\n          (STABLE: stable_tview mem1 tview):\n      stable_tview mem2 tview.\n    Proof.\n      inv STABLE. econs; eauto using cap_stable_view.\n    Qed.\n\n    Lemma cap_stable_memory\n          rels mem1 mem2\n          (CLOSED: Memory.closed mem1)\n          (CAP: Memory.cap mem1 mem2)\n          (STABLE: stable_memory rels mem1):\n      stable_memory rels mem2.\n    Proof.\n      ii. guardH LOC.\n      exploit Memory.cap_inv; try exact GET; eauto. i. des; ss.\n      exploit Memory.cap_inv; try exact GET0; eauto. i. des; ss.\n      eapply STABLE; eauto.\n    Qed.\n  End Stable.\nEnd Stable.\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/ldrfra/Stable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.29810725303782215}}
{"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.\n\nRequire Import EnhancedData.\n\nImport ListNotations.\nLocal Open Scope list_scope.\nLocal Open Scope string_scope.\nLocal Open Scope nstring_scope.\n\nInductive enhanced_numeric_type :=\n| enhanced_numeric_int\n| enhanced_numeric_float.\n\nGlobal Instance enhanced_numeric_type_eqdec : EqDec enhanced_numeric_type eq.\nProof.\n  red. unfold equiv, complement.\n  change (forall x y : enhanced_numeric_type, {x = y} + {x <> y}).\n  decide equality.\nDefined.\n\nInductive enhanced_reduce_op\n  := RedOpCount : enhanced_reduce_op\n   | RedOpSum (typ:enhanced_numeric_type) : enhanced_reduce_op\n   | RedOpMin (typ:enhanced_numeric_type) : enhanced_reduce_op\n   | RedOpMax (typ:enhanced_numeric_type) : enhanced_reduce_op\n   | RedOpArithMean (typ:enhanced_numeric_type) : enhanced_reduce_op\n   | RedOpStats (typ:enhanced_numeric_type) : enhanced_reduce_op.\n\nDefinition enhanced_numeric_type_prefix\n           (typ:enhanced_numeric_type) : string\n  := match typ with\n     | enhanced_numeric_int => \"\"%string\n     | enhanced_numeric_float => \"F\"%string\n     end.\n\nDefinition enhanced_reduce_op_tostring (op:enhanced_reduce_op) : string\n  := match op with\n     | RedOpCount => \"COUNT\"%string\n     | RedOpSum typ => append (enhanced_numeric_type_prefix typ) \"FSUM\"%string\n     | RedOpMin typ  => append (enhanced_numeric_type_prefix typ) \"FMIN\"%string\n     | RedOpMax typ => append (enhanced_numeric_type_prefix typ) \"FMAX\"%string\n     | RedOpArithMean typ => append (enhanced_numeric_type_prefix typ) \"FARITHMEAN\"%string\n     | RedOpStats typ => append (enhanced_numeric_type_prefix typ) \"FSTATS\"%string\n     end.\n\nDefinition enhanced_numeric_sum (typ:enhanced_numeric_type) : unary_op\n  := match typ with\n     | enhanced_numeric_int\n       => OpNatSum\n     | enhanced_numeric_float\n       => OpFloatSum\n     end.\n\nDefinition enhanced_numeric_min (typ:enhanced_numeric_type) : unary_op\n  := match typ with\n     | enhanced_numeric_int\n       => OpNatMin\n     | enhanced_numeric_float\n       => OpFloatBagMin\n     end.\n\nDefinition enhanced_numeric_max (typ:enhanced_numeric_type) : unary_op\n  := match typ with\n     | enhanced_numeric_int\n       => OpNatMax\n     | enhanced_numeric_float\n       => OpFloatBagMax\n     end.\n\nDefinition enhanced_numeric_arith_mean (typ:enhanced_numeric_type) : unary_op\n  := match typ with\n     | enhanced_numeric_int\n       => OpNatMean\n     | enhanced_numeric_float\n       => OpFloatMean\n     end.\n\nDefinition enhanced_reduce_op_interp\n           (br:brand_relation_t)\n           (op:enhanced_reduce_op)\n           (dl:list data) : option data\n  := match op with\n     | RedOpCount | RedOpSum _ | RedOpMin _ | RedOpMax _ | RedOpArithMean _ =>\n                                                           let uop :=\n                                                               match op with\n                                                               | RedOpCount  => OpCount\n                                                               | RedOpSum typ => enhanced_numeric_sum typ\n                                                               | RedOpMin typ => enhanced_numeric_min typ\n                                                               | RedOpMax typ => enhanced_numeric_max typ\n                                                               | RedOpArithMean typ => enhanced_numeric_arith_mean typ\n                                                               | RedOpStats _ => OpCount (* assert false *)\n                                                               end\n                                                           in\n                                                           unary_op_eval br uop (dcoll dl) \n     | RedOpStats typ =>\n       let coll := dcoll dl in\n       let count := unary_op_eval br OpCount coll in\n       let sum := unary_op_eval br (enhanced_numeric_sum typ) coll in\n       let min := unary_op_eval br (enhanced_numeric_min typ) coll in\n       let max := unary_op_eval br (enhanced_numeric_max typ) coll in\n       let v :=\n           match (count, sum, min, max) with\n           | (Some count, Some sum, Some min, Some max) =>\n             Some (drec ((\"count\"%string, count)\n                           ::(\"max\"%string, max)\n                           ::(\"min\"%string, min)\n                           ::(\"sum\"%string, sum)\n                           ::nil))\n           | _ => None\n           end\n       in\n       v\n     end.\n\nProgram Instance enhanced_foreign_reduce_op : foreign_reduce_op\n  := mk_foreign_reduce_op enhanced_foreign_data enhanced_reduce_op _ _ enhanced_reduce_op_interp _.\nNext Obligation.\n  red; unfold equiv, complement.\n  change (forall x y:enhanced_reduce_op, {x = y} + {x <> y}).\n  decide equality; decide equality.\nDefined.\nNext Obligation.\n  constructor.\n  apply enhanced_reduce_op_tostring.\nDefined.\nNext Obligation.\n  destruct op; simpl in *; invcs H.\n  - constructor.\n  - destruct typ; simpl in *.\n    + apply some_lift in H2; destruct H2 as [? eqq ?];\n        subst; constructor.\n    + apply some_lift in H2; destruct H2 as [? eqq ?];\n        subst; constructor.\n  - destruct typ; simpl in *.\n    + unfold lifted_min in *.\n      apply some_lift in H2; destruct H2 as [? eqq ?];\n        subst; constructor.\n    + unfold lifted_fmin in *.\n      apply some_lift in H2; destruct H2 as [? eqq ?];\n        subst; constructor.\n  - destruct typ; simpl in *.\n    + unfold lifted_max in * .\n      apply some_lift in H2; destruct H2 as [? eqq ?];\n        subst; constructor.\n    + unfold lifted_fmax in * .\n      apply some_lift in H2; destruct H2 as [? eqq ?];\n        subst; constructor.\n  - destruct typ; simpl in *.\n    + unfold lifted_max in * .\n      apply some_lift in H2; destruct H2 as [? eqq ?];\n        subst; constructor.\n    + unfold lifted_fmax in * .\n      apply some_lift in H2; destruct H2 as [? eqq ?];\n        subst; constructor.\n  - destruct typ; simpl in *.\n    + destruct (dsum dl); simpl in *; try discriminate.\n      unfold lifted_min, lifted_max in *.\n      destruct ((lift bnummin (lifted_zbag dl))); simpl in *; try discriminate.\n      destruct ((lift bnummax (lifted_zbag dl))); simpl in *; try discriminate.\n      invcs H2.\n      constructor.\n      * repeat constructor.\n      * reflexivity.\n    + case_eq (lifted_fsum dl); intros; simpl in *; rewrite H in *; try discriminate.\n      unfold lifted_fmin, lifted_fmax in *.\n      destruct ((lift float_list_min (lifted_fbag dl))); simpl in *; try discriminate.\n      destruct ((lift float_list_max (lifted_fbag dl))); simpl in *; try discriminate.\n      invcs H2.\n      constructor.\n      * repeat constructor.\n        apply some_lift in H; destruct H as [? eqq ?]; subst.\n        constructor.\n      * reflexivity.\nQed.\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/Compiler/Enhanced/EnhancedReduceOps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.29803816461509924}}
{"text": "Require Import RamifyCoq.CertiGC.gc_spec.\n\nLemma typed_true_tag: forall (to : nat) (g : LGraph) (index : nat),\n    typed_true tint\n               (force_val\n                  (option_map (fun b : bool => Val.of_bool (negb b))\n                              (bool_val_i\n                                 (Val.of_bool\n                                    (negb (Int.lt (Int.repr (raw_tag\n                                                               (vlabel g (to, index))))\n                                                  (Int.repr 251))))))) ->\n    ~ no_scan g (to, index).\nProof.\n  intros. remember (Int.lt (Int.repr (raw_tag (vlabel g (to, index))))\n                           (Int.repr 251)). unfold typed_true in H.\n  destruct b; simpl in H. 2: inversion H. symmetry in Heqb. apply lt_repr in Heqb.\n  - unfold no_scan. rep_omega.\n  - red. pose proof (raw_tag_range (vlabel g (to, index))). rep_omega.\n  - red. rep_omega.\nQed.\n\nLemma typed_false_tag: forall (to : nat) (g : LGraph) (index : nat),\n    typed_false tint\n               (force_val\n                  (option_map (fun b : bool => Val.of_bool (negb b))\n                              (bool_val_i\n                                 (Val.of_bool\n                                    (negb (Int.lt (Int.repr (raw_tag\n                                                               (vlabel g (to, index))))\n                                                  (Int.repr 251))))))) ->\n    no_scan g (to, index).\nProof.\n  intros. remember (Int.lt (Int.repr (raw_tag (vlabel g (to, index))))\n                           (Int.repr 251)). unfold typed_false in H.\n  destruct b; simpl in H. 1: inversion H. symmetry in Heqb.\n  apply lt_repr_false in Heqb.\n  - unfold no_scan. rep_omega.\n  - red. pose proof (raw_tag_range (vlabel g (to, index))). rep_omega.\n  - red. rep_omega.\nQed.\n\nLemma body_do_scan: semax_body Vprog Gprog f_do_scan do_scan_spec.\nProof.\n  start_function.\n  forward.\n  forward_loop (EX n: nat, EX g': LGraph, EX t_info': thread_info,\n                PROP (super_compatible (g', t_info', roots) f_info outlier;\n                      forward_condition g' t_info' from to;\n                      thread_info_relation t_info t_info';\n                      closure_has_index g' to (to_index + n);\n                      scan_vertex_while_loop from to (nat_seq to_index n) g g')\n                LOCAL\n                (temp _s (offset_val (- WORD_SIZE)\n                                     (vertex_address g' (to, (to_index + n)%nat)));\n                 temp _from_start (gen_start g' from);\n                 temp _from_limit (limit_address g' t_info' from);\n                 temp _next (next_address t_info' to))\n                SEP (all_string_constants rsh gv; fun_info_rep rsh f_info fi;\n               outlier_rep outlier; graph_rep g'; thread_info_rep sh t_info' ti))\n  break: (EX g' : LGraph, EX t_info' : thread_info,\n          PROP (super_compatible (g', t_info', roots) f_info outlier;\n                forward_condition g' t_info' from to;\n                do_scan_relation from to to_index g g';\n                thread_info_relation t_info t_info')\n          LOCAL ()\n          SEP (all_string_constants rsh gv; fun_info_rep rsh f_info fi;\n               outlier_rep outlier; graph_rep g'; thread_info_rep sh t_info' ti)).\n  - Exists O g t_info. destruct H as [? [? [? ?]]].\n    replace (to_index + 0)%nat with to_index by omega. entailer!.\n    split; [|split]; [red; auto | apply tir_id | constructor].\n  - Intros n g' t_info'. remember (to_index + n)%nat as index.\n    unfold next_address, thread_info_rep. Intros.\n    unfold heap_struct_rep. destruct H5 as [? [? [? ?]]].\n    destruct H6 as [? [? [? [? ?]]]].\n    assert (0 <= Z.of_nat to < 12). {\n      clear -H5 H14. destruct H5 as [_ [_ ?]]. red in H14.\n      pose proof (spaces_size (ti_heap t_info')).\n      rewrite Zlength_correct in H0. rep_omega. }\n    destruct (gt_gs_compatible _ _ H5 _ H14) as [? [? ?]]. 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 <- H18; 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. now rewrite Znth_map by (rewrite spaces_size; rep_omega). }\n    forward; rewrite H22; unfold space_tri. 1: entailer!.\n    unfold vertex_address, vertex_offset. rewrite offset_offset_val.\n    simpl vgeneration; simpl vindex.\n    replace (WORD_SIZE * (previous_vertices_size g' to index + 1) + - WORD_SIZE) with\n        (WORD_SIZE * (previous_vertices_size g' to index))%Z by rep_omega.\n    unfold gen_start at 1. rewrite if_true by assumption. rewrite H18.\n    remember (WORD_SIZE * used_space sp_to)%Z as used_offset.\n    remember (WORD_SIZE * previous_vertices_size g' to index)%Z as index_offset.\n    freeze [0; 1; 2; 4; 5] FR.\n    gather_SEP (graph_rep g') (heap_rest_rep (ti_heap t_info')).\n    assert (\n        forall b i,\n          Vptr b i = space_start sp_to ->\n          graph_rep g' * heap_rest_rep (ti_heap t_info') |--\n      !! (WORD_SIZE * total_space sp_to + Ptrofs.unsigned i <= Ptrofs.max_unsigned)). {\n      intros. sep_apply (graph_and_heap_rest_data_at_ _ _ _ H14 H5).\n      assert (space_start sp_to = gen_start g' to) by\n          (unfold gen_start; rewrite if_true by assumption;\n           rewrite <- H18; reflexivity). rewrite H24 in H23.\n      sep_apply (generation_data_at__ptrofs g' t_info' to b i H23).\n      unfold gen_size; rewrite nth_space_Znth; entailer!. }\n    assert_PROP (force_val\n                   (sem_cmp_pp Clt (offset_val index_offset (space_start sp_to))\n                               (offset_val used_offset (space_start sp_to))) =\n                 Vint (if if zlt index_offset used_offset then true else false\n                       then Int.one else Int.zero)). { (**)\n      remember (space_start sp_to). destruct v; try contradiction. inv_int i.\n      specialize (H23 b (Ptrofs.repr ofs) eq_refl).\n      rewrite Ptrofs.unsigned_repr in H23 by rep_omega. sep_apply H23. Intros.\n      assert (0 <= ofs + used_offset <= Ptrofs.max_unsigned). {\n        subst.\n        pose proof (space_order (Znth (Z.of_nat to) (spaces (ti_heap t_info')))).\n        rep_omega. }\n      assert (0 <= ofs + index_offset <= Ptrofs.max_unsigned). {\n        subst. red in H8. pose proof (pvs_ge_zero g' to (to_index + n)%nat).\n        pose proof (pvs_mono g' to _ _ H8). rep_omega. } apply prop_right.\n      rewrite force_sem_cmp_pp; [|rewrite isptr_offset_val; assumption..].\n      simpl. rewrite !ptrofs_add_repr, if_true. 2: reflexivity.\n      unfold Ptrofs.ltu. rewrite !Ptrofs.unsigned_repr; auto. f_equal.\n      if_tac; if_tac; try reflexivity; omega. }\n    forward_if (gen_has_index g' to index).\n    + remember (Znth (Z.of_nat to) (spaces (ti_heap t_info'))) as sp_to.\n      sep_apply (graph_and_heap_rest_data_at_ _ _ _ H14 H5).\n      unfold generation_data_at_.\n      assert (gen_start g' to = space_start sp_to) by\n          (subst; unfold gen_start; rewrite if_true; assumption). rewrite H31.\n      rewrite data_at__memory_block. Intros. rewrite sizeof_tarray_int_or_ptr.\n      2: unfold gen_size; apply total_space_range.\n      remember (WORD_SIZE * used_space sp_to)%Z as used_offset.\n      remember (to_index + n)%nat as index.\n      remember (WORD_SIZE * previous_vertices_size g' to index)%Z as index_offset.\n      destruct (space_start sp_to); try contradiction. simpl. unfold test_order_ptrs.\n      simpl. case (peq b b); intros. 2: contradiction. simpl.\n      assert (sepalg.nonidentity (nth_sh g' to)). {\n        apply readable_nonidentity, writable_readable_share. unfold nth_sh.\n        apply generation_share_writable. }\n      assert (forall offset,\n                 0 <= offset <= used_offset ->\n                 memory_block (nth_sh g' to) (WORD_SIZE * gen_size t_info' to)\n                              (Vptr b i) * TT * FRZL FR |--\n        weak_valid_pointer (Vptr b (Ptrofs.add i (Ptrofs.repr offset)))). {\n        intros. change (Vptr b (Ptrofs.add i (Ptrofs.repr offset))) with\n            (offset_val offset (Vptr b i)).\n        sep_apply (memory_block_weak_valid_pointer\n                     (nth_sh g' to) (WORD_SIZE * gen_size t_info' to)\n                     (Vptr b i) offset); auto.\n        3: apply extend_weak_valid_pointer.\n        - subst. unfold gen_size. split. 1: apply (proj1 H34).\n          transitivity (WORD_SIZE * used_space (nth_space t_info' to))%Z.\n          + rewrite nth_space_Znth. apply (proj2 H34).\n          + apply Zmult_le_compat_l. apply (proj2 (space_order _)). rep_omega.\n        - clear -H3 H7. destruct H7 as [? [? ?]].\n          rewrite <- H0.\n          rep_omega. }\n      apply andp_right; apply H34.\n      * subst. split. 1: pose proof (pvs_ge_zero g' to (to_index + n)%nat); rep_omega.\n        apply Zmult_le_compat_l. 2: rep_omega. rewrite <- H20.\n        apply pvs_mono. assumption.\n      * split; [|omega]; subst; apply Z.mul_nonneg_nonneg;\n                                  [rep_omega | apply space_order].\n    + assert (index_offset < used_offset). {\n        now destruct (zlt index_offset used_offset); [|rewrite H24 in H25; unfold typed_true in H25]. }\n      forward. entailer!. red. rewrite <- H20 in H26.\n      rewrite <- Z.mul_lt_mono_pos_l in H26 by rep_omega.\n      apply pvs_lt_rev in H26. assumption.\n    + assert (~ index_offset < used_offset). {\n        destruct (zlt index_offset used_offset); trivial. \n        now rewrite H24 in H25; unfold typed_false in H25. }\n      forward. thaw FR. unfold thread_info_rep, heap_struct_rep.\n      Exists g' t_info'. unfold forward_condition. entailer!.\n      split; [red; auto | exists n; split; trivial].\n      unfold gen_has_index. rewrite <- H20 in H26.\n      rewrite <- Z.mul_lt_mono_pos_l in H26 by rep_omega. intro; apply H26.\n      now apply pvs_mono_strict.\n    + clear H8 H23 H24. Intros. thaw FR. freeze [1;2;3;4;5;6] FR.\n      assert (graph_has_v g' (to, index)) by easy. \n      localize [vertex_rep (nth_sh g' to) g' (to, index)].\n      assert (readable_share (nth_sh g' to)) by\n          (unfold nth_sh; apply writable_readable_share, generation_share_writable).\n      unfold vertex_rep, vertex_at. Intros.\n      assert (offset_val (- WORD_SIZE) (vertex_address g' (to, index)) =\n              offset_val index_offset (space_start sp_to)). {\n        unfold vertex_address. rewrite offset_offset_val. unfold vertex_offset.\n        simpl vgeneration. simpl vindex.\n        replace (WORD_SIZE * (previous_vertices_size g' to index + 1) + - WORD_SIZE)\n          with index_offset by rep_omega.\n        f_equal. unfold gen_start.\n        rewrite if_true by assumption; now rewrite H18. }\n      rewrite H25. forward. rewrite <- H25.\n      gather_SEP (data_at (nth_sh g' to) tuint (Z2val (make_header g' (to, index)))\n            (offset_val (- WORD_SIZE) (vertex_address g' (to, index))))\n     (data_at (nth_sh g' to)\n       (tarray int_or_ptr_type (Zlength (make_fields_vals g' (to, index))))\n       (make_fields_vals g' (to, index)) (vertex_address g' (to, index))). \n      replace_SEP 0 (vertex_rep (nth_sh g' to) g' (to, index)) by\n          (unfold vertex_rep, vertex_at; entailer!).\n      unlocalize [graph_rep g']. 1: apply graph_vertex_ramif_stable; assumption.\n      forward. forward. assert (gen_unmarked g' to). {\n        eapply (svwl_gen_unmarked from to _ g); eauto.\n        destruct H0 as [_ [_ [? _]]]. assumption. }\n      specialize (H26 H14 _ H8).\n      rewrite make_header_Wosize, make_header_tag by assumption. deadvars!.\n      fold (next_address t_info' to). thaw FR.\n      fold (heap_struct_rep sh l (ti_heap_p t_info')). \n      (* gather_SEP 5 6 1. *)\n      gather_SEP\n        (data_at sh thread_info_type _ _)\n        (heap_struct_rep sh l _ ) (heap_rest_rep _).\n      replace_SEP 0 (thread_info_rep sh t_info' ti) by\n          (unfold thread_info_rep; entailer!).\n      forward_if\n        (EX g'': LGraph, EX t_info'': thread_info,\n         PROP (super_compatible (g'', t_info'', roots) f_info outlier;\n               forward_condition g'' t_info'' from to;\n               thread_info_relation t_info t_info'';\n               (no_scan g' (to, index) /\\ g'' = g') \\/\n               (~ no_scan g' (to, index) /\\\n                scan_vertex_for_loop\n                  from to (to, index)\n                  (nat_inc_list (length (vlabel g' (to, index)).(raw_fields))) g' g''))\n         LOCAL (temp _tag (vint (raw_tag (vlabel g' (to, index))));\n                temp _sz (vint (Zlength (raw_fields (vlabel g' (to, index)))));\n                temp _s (offset_val (- WORD_SIZE) (vertex_address g'' (to, index)));\n                temp _from_start (gen_start g'' from);\n                temp _from_limit (limit_address g'' t_info'' from);\n                temp _next (next_address t_info'' to))\n         SEP (thread_info_rep sh t_info'' ti; graph_rep g'';\n              fun_info_rep rsh f_info fi;\n              all_string_constants rsh gv; outlier_rep outlier)).\n      * apply typed_true_tag in H27.\n        remember (Zlength (raw_fields (vlabel g' (to, index)))).\n        assert (1 <= z < Int.max_signed). {\n          subst z. pose proof (raw_fields_range (vlabel g' (to, index))). split; [omega|].\n          transitivity (two_power_nat 22); [omega | vm_compute; reflexivity]. }\n        forward_loop\n          (EX i: Z, EX g3: LGraph, EX t_info3: thread_info,\n           PROP (scan_vertex_for_loop\n                   from to (to, index)\n                   (sublist 0 (i - 1)\n                            (nat_inc_list\n                               (length (vlabel g' (to, index)).(raw_fields)))) g' g3;\n                super_compatible (g3, t_info3, roots) f_info outlier;\n                forward_condition g3 t_info3 from to;\n                thread_info_relation t_info t_info3;\n                1 <= i <= z + 1)\n           LOCAL (temp _tag (vint (raw_tag (vlabel g' (to, index))));\n                  temp _j (vint i);\n                  temp _sz (vint z);\n                  temp _s (offset_val (- WORD_SIZE) (vertex_address g3 (to, index)));\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           SEP (all_string_constants rsh gv;\n                outlier_rep outlier;\n                fun_info_rep rsh f_info fi;\n                graph_rep g3;\n                thread_info_rep sh t_info3 ti))\n          continue: (EX i: Z, EX g3: LGraph, EX t_info3: thread_info,\n           PROP (scan_vertex_for_loop\n                   from to (to, index)\n                   (sublist 0 i\n                            (nat_inc_list\n                               (length (vlabel g' (to, index)).(raw_fields)))) g' g3;\n                super_compatible (g3, t_info3, roots) f_info outlier;\n                forward_condition g3 t_info3 from to;\n                thread_info_relation t_info t_info3;\n                1 <= i + 1 <= z + 1)\n           LOCAL (temp _tag (vint (raw_tag (vlabel g' (to, index))));\n                  temp _j (vint i);\n                  temp _sz (vint z);\n                  temp _s (offset_val (- WORD_SIZE) (vertex_address g3 (to, index)));\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           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)).\n        -- forward. Exists 1 g' t_info'. replace (1 - 1) with 0 by omega.\n           autorewrite with sublist. unfold forward_condition. entailer!.\n           split; [apply svfl_nil | red; auto].\n        -- Intros i g3 t_info3. forward_if (i <= z).\n           ++ forward. entailer!.\n           ++ forward. assert (i = z + 1) by omega. subst i. clear H33 H34.\n              replace (z + 1 - 1) with z in H29 by omega.\n              remember (raw_fields (vlabel g' (to, index))) as r.\n              replace (sublist 0 z (nat_inc_list (Datatypes.length r))) with\n                  (nat_inc_list (Datatypes.length r)) in H29.\n              ** Exists g3 t_info3. entailer!.\n              ** rewrite sublist_all; trivial. rewrite Z.le_lteq. right.\n                 subst z. rewrite !Zlength_correct, nat_inc_list_length. reflexivity.\n           ++ Intros.\n              change (Tpointer tvoid {| attr_volatile := false;\n                                        attr_alignas := Some 2%N |}) with\n                  int_or_ptr_type.\n              assert (isptr (vertex_address g3 (to, index))). {\n                erewrite <- svfl_vertex_address; eauto. rewrite <- H18 in H21.\n                2: apply graph_has_v_in_closure; assumption. clear -H21 H14.\n                unfold vertex_address. unfold gen_start. simpl.\n                rewrite if_true by assumption. rewrite isptr_offset_val. assumption. }\n              assert (graph_has_gen g3 to) by\n                  (eapply svfl_graph_has_gen in H29; [rewrite <- H29|]; assumption).\n              assert (graph_has_v g3 (to, index)) by\n                  (eapply svfl_graph_has_v in H29; [apply H29| assumption..]).\n              forward_call (rsh, sh, gv, fi, ti, g3, t_info3, f_info, roots,\n                            outlier, from, to, 0, (@inr Z _ ((to, index), i - 1))).\n              ** simpl snd. apply prop_right.\n                 split; [split; [split|]|]; [|reflexivity..].\n                 rewrite sem_add_pi_ptr_special;\n                   [| rewrite isptr_offset_val; assumption | rep_omega]. simpl.\n                 rewrite offset_offset_val. do 2 f_equal. rep_omega.\n              ** split; [|split; [|split; [|split; [|split; [|split]]]]];\n                   try assumption. 2: rep_omega. red. split; [|split;[|split]].\n                 --- assumption.\n                 --- eapply svfl_raw_fields in H29;\n                       [rewrite <- H29; omega | assumption..].\n                 --- rewrite <- H26. symmetry.\n                     eapply svfl_raw_mark in H29; [apply H29 | assumption..|].\n                     simpl. omega.\n                 --- simpl; auto.\n              ** Intros vret. destruct vret as [[g4 t_info4] roots']. simpl fst in *.\n                 simpl snd in *. simpl in H37. subst roots'. Exists i g4 t_info4.\n                 destruct H38 as [? [? [? ?]]].\n                 assert (gen_start g3 from = gen_start g4 from) by\n                     (eapply fr_gen_start; eauto).\n                 assert (limit_address g3 t_info3 from =\n                         limit_address g4 t_info4 from). {\n                   unfold limit_address. rewrite H45.\n                   do 2 f_equal. apply (proj2 H42). }\n                 assert (next_address t_info3 to = next_address t_info4 to) by\n                     (unfold next_address; f_equal; apply (proj1 H42)). entailer!.\n                 split; [|split; [|split]]; try easy.\n                 --- remember (nat_inc_list\n                                 (Datatypes.length\n                                    (raw_fields (vlabel g' (to,\n                                                            (to_index + n)%nat))))).\n                     assert (i <= Zlength l). {\n                       subst l. rewrite Zlength_correct, nat_inc_list_length.\n                       rewrite Zlength_correct in H34. omega. }\n                     rewrite (sublist_split 0 (i - 1) i) by omega.\n                     rewrite (sublist_one (i - 1) i) by omega.\n                     apply svfl_add_tail with roots g3; trivial. \n                     assert (Z.of_nat (Znth (i - 1) l) = i - 1). {\n                       rewrite <- nth_Znth by omega. subst l.\n                       rewrite nat_inc_list_nth; [rewrite Z2Nat.id; omega|].\n                       rewrite <- ZtoNat_Zlength. rewrite Zlength_correct in H52.\n                       rewrite nat_inc_list_length in H52. rewrite Nat2Z.inj_lt.\n                       rewrite !Z2Nat.id; omega. } rewrite H53. assumption.\n                 --- apply tir_trans with t_info3; assumption.\n                 --- f_equal. symmetry. eapply fr_vertex_address; eauto.\n                     apply graph_has_v_in_closure; assumption.\n        -- Intros i g3 t_info3. forward. rewrite add_repr. Exists (i + 1) g3 t_info3.\n           replace (i + 1 - 1) with i by omega. entailer!.\n      * apply typed_false_tag in H27. forward. Exists g' t_info'.\n        unfold forward_condition. entailer!. easy.\n      * Intros g'' t_info''. assert (isptr (vertex_address g'' (to, index))). {\n          assert (isptr (vertex_address g' (to, index))). {\n            unfold vertex_address. rewrite isptr_offset_val. unfold gen_start.\n            rewrite <- H18 in H21. rewrite if_true; assumption. }\n          destruct H30 as [[? ?] | [? ?]]. 1: subst g''; assumption.\n          eapply svfl_vertex_address in H32;\n            [rewrite <- H32 | | apply graph_has_v_in_closure]; assumption. }\n        pose proof (raw_fields_range (vlabel g' (to, index))). forward.\n        -- entailer!. split. 1: rep_omega.\n           assert (two_power_nat 22 < Int.max_signed) by (vm_compute; reflexivity).\n           rewrite Int.signed_repr; rep_omega.\n        -- change (Tpointer tvoid {| attr_volatile := false;\n                                     attr_alignas := Some 2%N |}) with int_or_ptr_type.\n           simpl sem_binary_operation'. rewrite add_repr.\n           assert (force_val (sem_add_ptr_int\n                                int_or_ptr_type Unsigned\n                                (offset_val (- WORD_SIZE)\n                                            (vertex_address g'' (to, index)))\n                                (vint (1 + Zlength\n                                             (raw_fields (vlabel g' (to, index))))))\n                   = offset_val (- WORD_SIZE)\n                                (vertex_address g''\n                                                (to, (to_index + (n + 1))%nat))). {\n             rewrite sem_add_pi_ptr_special.\n             - assert (Zlength (raw_fields (vlabel g' (to, index))) =\n                       Zlength (raw_fields (vlabel g'' (to, index)))). {\n                 destruct H30 as [[? ?] | [? ?]]. 1: subst g''; reflexivity.\n                 erewrite svfl_raw_fields; eauto. } rewrite H33.\n               simpl. replace (to_index + (n + 1))%nat with (S index) by omega.\n               unfold vertex_address. rewrite !offset_offset_val.\n               unfold vertex_offset. simpl vgeneration. simpl vindex. f_equal.\n               rewrite pvs_S. unfold vertex_size. rep_omega.\n             - rewrite isptr_offset_val. assumption.\n             - split. 1: rep_omega.\n               assert (two_power_nat 22 < Int.max_unsigned) by\n                   (vm_compute; reflexivity). omega. } rewrite H33. clear H33.\n           assert (closure_has_index g'' to (to_index + (n + 1))). {\n             replace (to_index + (n + 1))%nat with (index + 1)%nat by omega.\n             cut (gen_has_index g'' to index). 1: red; intros; red in H33; omega.\n             destruct H30 as [[? ?] | [? ?]].\n             - subst g''. destruct H23. assumption.\n             - eapply svfl_graph_has_v in H33; eauto. destruct H33. assumption. }\n           Exists (n + 1)%nat g'' t_info''. destruct H27 as [? [? [? ?]]]. entailer!.\n           clear H37 H38 H39 H40. replace (n + 1)%nat with (S n) by omega.\n           rewrite nat_seq_S, Nat.add_comm. destruct H30 as [[? ?] | [? ?]].\n           ++ subst g''. split; [| apply svwl_add_tail_no_scan]; easy.\n           ++ split; [|apply svwl_add_tail_scan with g']; easy.\n  - Intros g' t_info'. forward. Exists g' t_info'. 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_do_scan.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6688802735722129, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2980059172817702}}
{"text": "Require Export DEX_ElemLemmas.\n\n\nImport DEX_BigStepWithTypes.DEX_BigStepWithTypes DEX_BigStep.DEX_Dom DEX_Prog.\n\n(*   Opaque BigStep.Dom.Heap.update.\n *)\nSection p.\n\nVariable kobs: L.t.\nVariable p:DEX_ExtendedProgram.\nVariable se : DEX_PC -> L.t.\nVariable reg : DEX_PC -> (* option DEX_ClassName -> *) DEX_PC -> Prop.\nVariable m : DEX_Method.\n(* Variable 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 r1' rt1' r2 r2' rt2 rt2' ,\n   instructionAt m pc = Some i ->\n   NormalStep se reg m sgn i (pc,r1) rt1 (pc2,r2) rt2 ->\n   NormalStep se reg m sgn i (pc,r1') rt1' (pc2',r2') rt2' ->\n   pc2 <> pc2' ->\n   st_in kobs rt1 rt1' (pc,r1) (pc,r1') ->\n\n    forall j, reg pc j -> ~ L.leql (se j) kobs.\nProof.\n  intros sgn pc pc2 pc2' i r1 rt1 r1' rt1' r2 r2' rt2 rt2' 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  (* 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.\n\n\n\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_ElemLemmaNormalIntra3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2980059114002438}}
{"text": "(** * A box to mirror a server over untrusted channels using encryption while preventing timing side channels (part of TCB) *)\nRequire Import Coq.Program.Basics Coq.NArith.NArith Coq.Lists.List.\nRequire Import FunctionApp EncryptionInterface TrustedTickBox TrustedEncryptBox TrustedDecryptBox.\nRequire Import Common.\n\nLocal Open Scope list_scope.\nLocal Open Scope program_scope.\n\nSet Implicit Arguments.\n\n(** ** Summary\n\n    We implement a box that presents the interface of a server storing\n    unencrypted data.  It handles \"set\" and \"get eventually\" requests,\n    and raises \"value changed\" and \"remote corrupted\".\n\n    We assume the remote server has a \"compare and set\" event; we use\n    this to be robust to update messages lost over the network.  It is\n    the client's responsibility to set up the tick-box intervals so\n    that we get an updated server value sufficiently close to our\n    sending that CAS succeeds.\n\n    We maintain the following internal state:\n    - [remoteStateE] - state we think the remote server has right now (encrypted)\n    - [localStateD] - state we want the remote server to have (decrypted)\n\n    We implement the following events:\n\n    Client Events:\n\n    - [ssbClientGetUpdate] - When the client requests an\n      update from the server, we request an update from our remote\n      server, hidden behind a tick box.\n\n    - [ssbClientSet (newD : rawDataT)] - When the client requests a\n      SET, we set [localStateD] to [newD], and schedule a remote\n      update.\n\n    Server Events:\n\n    - [ssbServerGotUpdate (newE : encryptedDataT)] - When the server\n      provides us with an update, we decrypt it to [newD].  If we\n      fail, we inform the client that the remote server got messed up.\n      If we succeed, and it is different from [localStateD], we set\n      [localStateD] to [newD], and push an update to the client.  In\n      all cases, we set [remoteStateE] to [newE].\n\n    Timed events:\n\n    - When it's time to do a server CAS, we compute an encryption\n      [localStateE] of [localStateD].  We then tell the server that if\n      it's state is [remoteStateE], it should replace it with\n      [localStateE].  The server is expected to respond with\n      [ssbServerGotUpdate] with it's updated state on both failure and\n      success.\n\n  *)\n\nModule TrustedServerSyncBox (DataTypes : EncryptionDataTypes) (Algorithm : EncryptionAlgorithm DataTypes).\n  Import DataTypes.\n\n  Module Import TEB := TrustedEncryptBox DataTypes Algorithm.\n  Module Import TDB := TrustedDecryptBox DataTypes Algorithm.\n\n  Section trustedServerSyncBox.\n    Variable d_eqb : rawDataT -> rawDataT -> bool.\n\n    Record ServerSyncBoxPreState\n      := { localStateD : rawDataT;\n           remoteStateE : option encryptedDataT }.\n\n    Record ServerSyncBoxState :=\n      {\n        ssbState :> ServerSyncBoxPreState;\n        ssbGetUpdateState : TickBoxState unit;\n        ssbCASState : TickBoxState encryptedDataT;\n        ssbEncryptState : EncryptBoxState;\n        ssbDecryptState : DecryptBoxState\n      }.\n\n(* python:\n<<\nfields=[(x.strip(), y.strip()) for x, y in [z.split(':') for z in \"\"\"\n        ssbState : ServerSyncBoxPreState;\n        ssbGetUpdateState : TickBoxState unit;\n        ssbCASState : TickBoxState cas_state;\n        ssbEncryptState : EncryptBoxState;\n        ssbDecryptState : DecryptBoxState\"\"\".split(';')]]\nfor field0, ty0 in fields:\n    body = ';\\n          '.join((('%s := st.(%s)' % (field, field)) if field != field0 else ('%s := v' % field))\n                                for field, ty in fields)\n    print('  Definition set_%s (st : ServerSyncBoxState) (v : %s)' % (field0, ty0))\n    print('    := {| ' + body + ' |}.\\n')\n>> *)\n\n    Definition set_ssbState (st : ServerSyncBoxState) (v : ServerSyncBoxPreState)\n      := {| ssbState := v;\n            ssbGetUpdateState := st.(ssbGetUpdateState);\n            ssbCASState := st.(ssbCASState);\n            ssbEncryptState := st.(ssbEncryptState);\n            ssbDecryptState := st.(ssbDecryptState) |}.\n\n    Definition set_ssbGetUpdateState (st : ServerSyncBoxState) (v : TickBoxState unit)\n      := {| ssbState := st.(ssbState);\n            ssbGetUpdateState := v;\n            ssbCASState := st.(ssbCASState);\n            ssbEncryptState := st.(ssbEncryptState);\n            ssbDecryptState := st.(ssbDecryptState) |}.\n\n    Definition set_ssbCASState (st : ServerSyncBoxState) (v : TickBoxState encryptedDataT)\n      := {| ssbState := st.(ssbState);\n            ssbGetUpdateState := st.(ssbGetUpdateState);\n            ssbCASState := v;\n            ssbEncryptState := st.(ssbEncryptState);\n            ssbDecryptState := st.(ssbDecryptState) |}.\n\n    Definition set_ssbEncryptState (st : ServerSyncBoxState) (v : EncryptBoxState)\n      := {| ssbState := st.(ssbState);\n            ssbGetUpdateState := st.(ssbGetUpdateState);\n            ssbCASState := st.(ssbCASState);\n            ssbEncryptState := v;\n            ssbDecryptState := st.(ssbDecryptState) |}.\n\n    Definition set_ssbDecryptState (st : ServerSyncBoxState) (v : DecryptBoxState)\n      := {| ssbState := st.(ssbState);\n            ssbGetUpdateState := st.(ssbGetUpdateState);\n            ssbCASState := st.(ssbCASState);\n            ssbEncryptState := st.(ssbEncryptState);\n            ssbDecryptState := v |}.\n\n    Inductive ssbConfigInput :=\n    | ssbGetUpdateConfig (_ : tbConfigInput)\n    | ssbCASConfig (_ : tbConfigInput)\n    | ssbSetMasterKey (key : masterKeyT).\n\n    Inductive ssbEventInput :=\n    | ssbClientGetUpdate\n    | ssbClientSet (newD : rawDataT)\n    | ssbServerGotUpdate (newE : encryptedDataT)\n    | ssbSystemRandomness (randomness : systemRandomnessT) (tag : rawDataT)\n    | ssbTick (_ : N).\n\n    Definition ssbInput := (ssbConfigInput + ssbEventInput)%type.\n\n    Inductive ssbWarningOutput :=\n    | ssbGetUpdateWarning (_ : tbWarningOutput unit)\n    | ssbCASWarning (_ : tbWarningOutput encryptedDataT)\n    | ssbEncryptError (_ : ebErrorOutput)\n    | ssbDecryptError (_ : dbErrorOutput unit)\n    | ssbWarningInvalidTransition (ev : ssbInput) (st : ServerSyncBoxState)\n    | ssbWarningPushBeforePull.\n\n    Inductive ssbEventOutput :=\n    | ssbClientGotUpdate (data : rawDataT)\n    | ssbServerGetUpdate\n    | ssbServerCAS (curE newE : encryptedDataT)\n    | ssbRequestSystemRandomness (howMuch : systemRandomnessHintT) (tag : rawDataT).\n\n    Definition ssbOutput := (ssbWarningOutput + ssbEventOutput)%type.\n\n    Variable initRawData : rawDataT.\n    Context (world : Type)\n            (handle : ssbOutput -> action world).\n\n    Definition initState : ServerSyncBoxState :=\n      {|\n        ssbState := {| localStateD := initRawData;\n                       remoteStateE := None |};\n        ssbGetUpdateState := TrustedTickBox.initState _;\n        ssbCASState := TrustedTickBox.initState _;\n        ssbEncryptState := TEB.initState;\n        ssbDecryptState := TDB.initState\n      |}.\n\n    Local Ltac handle_eq_false' :=\n      idtac;\n      match goal with\n        | _ => progress subst_body\n        | _ => intro\n        | _ => progress simpl in *\n        | _ => progress subst\n        | [ H : appcontext[match ?E with _ => _ end] |- _ ] => (atomic E; destruct E)\n        | [ H : Some _ = None |- _ ] => solve [ inversion H ]\n        | [ H : None = Some _ |- _ ] => solve [ inversion H ]\n        | [ H : inl _ = inr _ |- _ ] => solve [ inversion H ]\n        | [ H : inr _ = inl _ |- _ ] => solve [ inversion H ]\n        | [ H : _::_ = nil |- _ ] => solve [ inversion H ]\n        | [ H : appcontext[match ?E with _ => _ end] |- _ ] => (revert H; case_eq E; intros)\n        | [ H : (_, _) = (_, _) |- _ ] => inversion H; clear H\n        | [ H : inl _ = inl _ |- _ ] => inversion H; clear H\n        | [ H : inr _ = inr _ |- _ ] => inversion H; clear H\n        | [ H : Some _ = Some _ |- _ ] => inversion H; clear H\n        | [ H : _::_ = _::_ |- _ ] => inversion H; clear H\n        | [ H : ?a = ?b |- _ ]\n          => let a' := (eval hnf in a) in\n             let b' := (eval hnf in b) in\n             progress change (a' = b') in H\n      end.\n\n    Local Ltac handle_eq_false :=\n      match goal with\n        | [ |- _ -> False ] => idtac\n      end;\n      subst_body; clear; intro;\n      abstract (repeat handle_eq_false').\n\n    Definition handle_ssbGetUpdate'\n               (st : ServerSyncBoxState)\n    : tbOutput unit * TickBoxState unit -> list ssbOutput * ServerSyncBoxState.\n    Proof.\n      refine (fun i =>\n                (match fst i with\n                   | inl warning\n                     => inl (ssbGetUpdateWarning warning)::nil\n                   | inr tbRequestDataUpdate\n                     => let upd := tickBoxLoopPreBody\n                                     (st.(ssbGetUpdateState))\n                                     (inr (tbValueReady tt)) in\n                        match fst upd as u return u = fst upd -> _ with\n                          | nil => fun _ => nil\n                          | inl warning::nil => fun _ => inl (ssbGetUpdateWarning warning)::nil\n                          | inl warning::inl warning'::nil => fun _ => inl (ssbGetUpdateWarning warning)::inl (ssbGetUpdateWarning warning')::nil\n                          | _ => fun H => match (_ H) : False with end\n                        end eq_refl\n                   | inr (tbPublishUpdate val)\n                     => inr ssbServerGetUpdate::nil\n                 end,\n                 set_ssbGetUpdateState st (snd i)));\n      handle_eq_false.\n    Defined.\n\n    Definition fold_handler {outT stT}\n               (get : ServerSyncBoxState -> stT)\n               (set : ServerSyncBoxState -> stT -> ServerSyncBoxState)\n               (handle : ServerSyncBoxState -> outT * stT -> list ssbOutput * ServerSyncBoxState)\n               (st : ServerSyncBoxState)\n    : list outT * stT -> list ssbOutput * ServerSyncBoxState\n      := fun outs_st =>\n           fold_left (fun ls_st out =>\n                        let ls'_st' := handle (snd ls_st) (out, get (snd ls_st)) in\n                        (fst ls_st ++ fst ls'_st', snd ls'_st'))\n                     (fst outs_st)\n                     (nil, set st (snd outs_st)).\n\n    Definition handle_ssbGetUpdate\n      := fold_handler ssbGetUpdateState set_ssbGetUpdateState handle_ssbGetUpdate'.\n\n    Definition handle_ssbEncrypt\n               (st : ServerSyncBoxState)\n    : option (ebOutput unit) * EncryptBoxState -> list ssbOutput * ServerSyncBoxState.\n    Proof.\n      refine (fun i =>\n                let st' := set_ssbEncryptState st (snd i) in\n                match fst i with\n\n                   | Some (inl warning)\n                     => ((inl (ssbEncryptError warning))::nil, st')\n\n                   | Some (inr (ebRequestSystemRandomness howMuch tag))\n                     => ((inr (ssbRequestSystemRandomness howMuch (fst tag)))::nil, st')\n\n                   | Some (inr (ebEncrypted newE _))\n                     => let upd := tickBoxLoopPreBody\n                                     (st'.(ssbCASState))\n                                     (inr (tbValueReady newE)) in\n                        (match fst upd as u return u = fst upd -> _ with\n                           | nil => fun _ => nil\n                           | inl warning::nil => fun _ => (inl (ssbCASWarning warning))::nil\n                           | inl warning::inl warning'::nil => fun _ => inl (ssbCASWarning warning)::inl (ssbCASWarning warning')::nil\n                           | _ => fun H => match (_ H) : False with end\n                         end eq_refl,\n                         set_ssbCASState st' (snd upd))\n\n                   | None => (nil, st')\n                 end);\n      handle_eq_false.\n    Defined.\n\n    Definition handle_ssbCAS'\n               (st : ServerSyncBoxState)\n    : tbOutput encryptedDataT * TickBoxState encryptedDataT -> list ssbOutput * ServerSyncBoxState.\n    Proof.\n      refine (fun i =>\n                let st' := set_ssbCASState st (snd i) in\n                match fst i with\n                  | inl warning\n                    => (inl (ssbCASWarning warning)::nil, st')\n\n                  | inr (tbPublishUpdate val)\n                    => (match st'.(remoteStateE) with\n                          | Some curE\n                            => inr (ssbServerCAS curE val)\n                          | None => inl ssbWarningPushBeforePull\n                        end::nil,\n                        st')\n\n                  | inr tbRequestDataUpdate\n                    => let encResult := encryptBoxLoopPreBody\n                                          (st'.(ssbEncryptState))\n                                          (ebEncrypt (st.(localStateD)) tt) in\n                       handle_ssbEncrypt st' encResult\n                end).\n    Defined.\n\n    Definition handle_ssbCAS\n      := fold_handler ssbCASState set_ssbCASState handle_ssbCAS'.\n\n    Definition handle_ssbDecrypt\n               (st : ServerSyncBoxState)\n    : option (dbOutput unit) * DecryptBoxState -> list ssbOutput * ServerSyncBoxState.\n    Proof.\n      refine (fun i =>\n                let st' := set_ssbDecryptState st (snd i) in\n                match fst i with\n\n                  | Some (inl warning)\n                    => (inl (ssbDecryptError warning)::nil, st)\n\n                  | Some (inr (dbDecrypted dataD _))\n                    => ((if d_eqb dataD st.(localStateD)\n                         then nil\n                         else (inr (ssbClientGotUpdate dataD))::nil),\n                        set_ssbState st' {| localStateD := dataD;\n                                            remoteStateE := st'.(remoteStateE) |})\n\n                  | None => (nil, st')\n\n                end).\n    Defined.\n\n    Definition serverSyncBoxLoopPreBody\n               (st : ServerSyncBoxState)\n    : ssbInput -> list ssbOutput * ServerSyncBoxState.\n    Proof.\n      refine (fun i =>\n                match i with\n\n                  | inl (ssbGetUpdateConfig i')\n                    => handle_ssbGetUpdate\n                         st\n                         (tickBoxLoopPreBody\n                            (st.(ssbGetUpdateState))\n                            (inl i'))\n\n                  | inl (ssbCASConfig i')\n                    => handle_ssbCAS\n                         st\n                         (tickBoxLoopPreBody\n                            (st.(ssbCASState))\n                            (inl i'))\n\n                  | inl (ssbSetMasterKey newKey)\n                    => let (ls0, st0) := handle_ssbEncrypt\n                                           st\n                                           (encryptBoxLoopPreBody\n                                              (st.(ssbEncryptState))\n                                              (ebSetMasterKey _ newKey)) in\n                       let (ls1, st1) := handle_ssbDecrypt\n                                           st0\n                                           (decryptBoxLoopPreBody\n                                              (st.(ssbDecryptState))\n                                              (dbSetMasterKey _ newKey)) in\n                       (ls0 ++ ls1, st1)\n\n                  | inr (ssbTick n)\n                    => let (ls0, st0) := handle_ssbGetUpdate\n                                           st\n                                           (tickBoxLoopPreBody\n                                              (st.(ssbGetUpdateState))\n                                              (inr (tbTick _ n))) in\n                       let (ls1, st1) := handle_ssbCAS\n                                           st0\n                                           (tickBoxLoopPreBody\n                                              (st0.(ssbCASState))\n                                              (inr (tbTick _ n))) in\n                       (ls0 ++ ls1, st1)\n\n                  | inr ssbClientGetUpdate\n                    => handle_ssbGetUpdate\n                         st\n                         (tickBoxLoopPreBody\n                            (st.(ssbGetUpdateState))\n                            (inr (tbNotifyChange _)))\n\n                  | inr (ssbClientSet newD)\n                    => let st' := set_ssbState\n                                    st\n                                    {| localStateD := newD;\n                                       remoteStateE := st.(remoteStateE) |} in\n                       handle_ssbCAS\n                         st'\n                         (tickBoxLoopPreBody\n                            (st'.(ssbCASState))\n                            (inr (tbNotifyChange _)))\n\n                  | inr (ssbServerGotUpdate dataE)\n                    => let st' := set_ssbState\n                                    st\n                                    {| localStateD := st.(localStateD);\n                                       remoteStateE := Some dataE |} in\n                       handle_ssbDecrypt\n                         st'\n                         (decryptBoxLoopPreBody\n                            (st'.(ssbDecryptState))\n                            (dbDecrypt dataE tt))\n\n                  | inr (ssbSystemRandomness randomness tag)\n                    => handle_ssbEncrypt\n                         st\n                         (encryptBoxLoopPreBody\n                            (st.(ssbEncryptState))\n                            (ebSystemRandomness randomness (tag, tt)))\n\n                end).\n    Defined.\n\n    Definition serverSyncBoxLoopBody {T}\n               (serverSyncBoxLoop : ServerSyncBoxState -> T)\n               (st : ServerSyncBoxState)\n    : ssbInput -> action world * T\n      := fun i => let outs := fst (serverSyncBoxLoopPreBody st i) in\n                  (fold_left compose (map handle outs) id,\n                   serverSyncBoxLoop (snd (serverSyncBoxLoopPreBody st i))).\n\n    CoFixpoint serverSyncBoxLoop (st : ServerSyncBoxState) :=\n      Step (serverSyncBoxLoopBody serverSyncBoxLoop st).\n\n    Definition serverSyncBox : process _ _ := serverSyncBoxLoop initState.\n  End trustedServerSyncBox.\nEnd TrustedServerSyncBox.\n", "meta": {"author": "JasonGross", "repo": "apps", "sha": "906b9ca6f3f53e3a37a9a487a9289959f5167ba2", "save_path": "github-repos/coq/JasonGross-apps", "path": "github-repos/coq/JasonGross-apps/apps-906b9ca6f3f53e3a37a9a487a9289959f5167ba2/TrustedServerSyncBox.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2980059114002438}}
{"text": "(**************************************************\n * Author: Ana Nora Evans (ananevans@virginia.edu)\n **************************************************)\nRequire Import Coq.PArith.BinPos.\n\nRequire Import Common.Definitions.\n\nRequire Import Intermediate.Machine.\nRequire Import TargetSFI.Machine.\n\nDefinition label :Set := N*N.\n\n(*Definition register := RiscMachine.Register.t.*)\n\nInductive ainstr :=\n| INop : ainstr\n| ILabel : label -> ainstr\n(* register operations *)\n| IConst : RiscMachine.value -> RiscMachine.Register.t -> ainstr\n| IMov : RiscMachine.Register.t -> RiscMachine.Register.t -> ainstr\n| IBinOp : RiscMachine.ISA.binop -> RiscMachine.Register.t ->\n           RiscMachine.Register.t -> RiscMachine.Register.t -> ainstr\n(* memory operations *)\n| ILoad : RiscMachine.Register.t -> RiscMachine.Register.t -> ainstr\n| IStore : RiscMachine.Register.t -> RiscMachine.Register.t -> ainstr\n(* conditional and unconditional jumps *)\n| IBnz : RiscMachine.Register.t -> label -> ainstr\n| IJump : RiscMachine.Register.t -> ainstr\n| IJal : label -> ainstr\n(* termination *)\n| IHalt : ainstr.\n\nDefinition code := list ainstr.\n\nDefinition lcode : Set := list ((option (list label)) * ainstr).\n\nDefinition map_register (reg : Intermediate.Machine.register) : RiscMachine.Register.t :=\n  match reg with\n  | Intermediate.Machine.R_ONE => RiscMachine.Register.R_ONE\n  | Intermediate.Machine.R_COM => RiscMachine.Register.R_COM\n  | Intermediate.Machine.R_AUX1 => RiscMachine.Register.R_AUX1\n  | Intermediate.Machine.R_AUX2 => RiscMachine.Register.R_AUX2\n  | Intermediate.Machine.R_RA => RiscMachine.Register.R_RA\n  | Intermediate.Machine.R_SP => RiscMachine.Register.R_SP\n  | Intermediate.Machine.R_ARG => RiscMachine.Register.R_ARG\n  end.\n\nDefinition map_binop (op : Common.Values.binop) : RiscMachine.ISA.binop :=\n  match op with\n  | Add => RiscMachine.ISA.Addition\n  | Minus => RiscMachine.ISA.Subtraction\n  | Mul => RiscMachine.ISA.Multiplication\n  | Eq => RiscMachine.ISA.Equality\n  | Leq => RiscMachine.ISA.Leq\n  end.\n\nDefinition label_eqb (l1 l2 : label) :=\n  let '(c1,i1) := l1 in\n  let '(c2,i2) := l2 in\n  (N.eqb c1 c2) && (N.eqb i1 i2).\n\nDefinition label_eq_dec:\n  forall l1 l2 : label,  {l1 = l2} + {l1 <> l2}.\n  Proof.\n    repeat decide equality. Defined.\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/I2SFI/AbstractMachine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710085, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.29800591140024374}}
{"text": "(** a generalization of heterogeneous substitution systems to monoidal categories in place of endofunctor categories\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.Monoidal.WhiskeredBifunctors.\nRequire Import UniMath.CategoryTheory.Monoidal.Categories.\nRequire Import UniMath.CategoryTheory.Monoidal.CategoriesOfMonoids.\nRequire Import UniMath.CategoryTheory.Actegories.Actegories.\nRequire Import UniMath.CategoryTheory.Actegories.ConstructionOfActegories.\nRequire Import UniMath.CategoryTheory.Actegories.MorphismsOfActegories.\nRequire Import UniMath.CategoryTheory.Actegories.CoproductsInActegories.\nRequire Import UniMath.CategoryTheory.coslicecat.\nRequire Import UniMath.CategoryTheory.limits.bincoproducts.\nRequire Import UniMath.CategoryTheory.Monoidal.Examples.MonoidalPointedObjects.\n\n\nLocal Open Scope cat.\n\nImport BifunctorNotations.\nImport MonoidalNotations.\n(* Import ActegoryNotations. *)\n\nSection hss.\n\n  Context {V : category} (Mon_V : monoidal V).\n\n  Local Definition PtdV : category := coslice_cat_total V I_{Mon_V}.\n  Local Definition Mon_PtdV : monoidal PtdV := monoidal_pointed_objects Mon_V.\n  Local Definition Act : actegory Mon_PtdV V := actegory_with_canonical_pointed_action Mon_V.\n\n  Context (H : V ⟶ V).\n  Context (θ : pointedtensorialstrength Mon_V H).\n\n  Section TheProperty.\n\n    Context (t : V) (η : I_{Mon_V} --> t) (τ : H t --> t).\n\n  Definition gbracket_property_parts {z : V} (e : I_{Mon_V} --> z) (f : z --> t) (h : z ⊗_{Mon_V} t --> t) : UU :=\n    (ru^{Mon_V}_{z} · f = z ⊗^{Mon_V}_{l} η · h) ×\n      (θ (z,,e) t · #H h · τ =  z ⊗^{Mon_V}_{l} τ · h).\n\n  Definition gbracket_parts_at {z : V} (e : I_{Mon_V} --> z) (f : z --> t) : UU :=\n    ∃! h : z ⊗_{Mon_V} t --> t, gbracket_property_parts e f h.\n\n  Definition gbracket : UU :=\n    ∏ (Z : PtdV) (f : pr1 Z --> t), gbracket_parts_at (pr2 Z) f.\n\n  Lemma isaprop_gbracket_property_parts {z : V} (e : I_{Mon_V} --> z) (f : z --> t) (h : z ⊗_{Mon_V} t --> t) :\n    isaprop (gbracket_property_parts e f h).\n  Proof.\n    apply isapropdirprod; apply V.\n  Qed.\n\n  Lemma isaprop_gbracket : isaprop gbracket.\n  Proof.\n    apply impred_isaprop; intro Z.\n    apply impred_isaprop; intro f.\n    apply isapropiscontr.\n  Qed.\n\n  Section PropertyAsOneEquation.\n\n    Context (CP : BinCoproducts V).\n\n  Definition Const_plus_H (v : V) : functor V V := BinCoproduct_of_functors _ _ CP (constant_functor _ _ v) H.\n\n  Definition gbracket_property_single {z : V} (e : I_{Mon_V} --> z) (f : z --> t) (h : z ⊗_{Mon_V} t --> t) : UU :=\n    actegory_bincoprod_antidistributor Mon_PtdV CP Act (z,,e) I_{Mon_V} (H t) ·\n      (z,,e) ⊗^{Act}_{l} (BinCoproductArrow (CP _ _) η τ) · h =\n    BinCoproductOfArrows _ (CP _ _) (CP _ _) (ru_{Mon_V} z) (θ (z,,e) t) ·\n      #(Const_plus_H z) h · BinCoproductArrow (CP _ _) f τ.\n\n  Lemma isaprop_gbracket_property_single {z : V} (e : I_{Mon_V} --> z) (f : z --> t) (h : z ⊗_{Mon_V} t --> t) :\n    isaprop (gbracket_property_single e f h).\n  Proof.\n    apply V.\n  Qed.\n\n  Lemma gbracket_property_single_equivalent {z : V} (e : I_{Mon_V} --> z) (f : z --> t) (h : z ⊗_{Mon_V} t --> t) :\n    gbracket_property_parts e f h <-> gbracket_property_single e f h.\n  Proof.\n    split.\n    - intros [Hη Hτ].\n      use BinCoproductArrowsEq.\n      + etrans.\n        { repeat rewrite assoc.\n          do 2 apply cancel_postcomposition.\n          apply BinCoproductIn1Commutes. }\n        etrans.\n        { apply cancel_postcomposition.\n          apply pathsinv0, (functor_comp (leftwhiskering_functor Act (z,,e))). }\n        rewrite BinCoproductIn1Commutes.\n        etrans.\n        2: { repeat rewrite assoc.\n             do 2 apply cancel_postcomposition.\n             apply pathsinv0, BinCoproductOfArrowsIn1. }\n        etrans.\n        { apply pathsinv0, Hη. }\n        repeat rewrite assoc'.\n        apply maponpaths.\n        rewrite assoc.\n        etrans.\n        2: { apply cancel_postcomposition.\n             apply pathsinv0, BinCoproductOfArrowsIn1. }\n        rewrite assoc'.\n        rewrite id_left.\n        apply pathsinv0, BinCoproductIn1Commutes.\n      + etrans.\n        { repeat rewrite assoc.\n          do 2 apply cancel_postcomposition.\n          apply BinCoproductIn2Commutes. }\n        etrans.\n        { apply cancel_postcomposition.\n          apply pathsinv0, (functor_comp (leftwhiskering_functor Act (z,,e))). }\n        rewrite BinCoproductIn2Commutes.\n        etrans.\n        2: { repeat rewrite assoc.\n             do 2 apply cancel_postcomposition.\n             apply pathsinv0, BinCoproductOfArrowsIn2. }\n        etrans.\n        { apply pathsinv0, Hτ. }\n        repeat rewrite assoc'.\n        apply maponpaths.\n        rewrite assoc.\n        etrans.\n        2: { apply cancel_postcomposition.\n             apply pathsinv0, BinCoproductOfArrowsIn2. }\n        rewrite assoc'.\n        apply maponpaths.\n        apply pathsinv0, BinCoproductIn2Commutes.\n    - intro H1.\n      split.\n      + apply (maponpaths (fun m => BinCoproductIn1 (CP _ _) · m)) in H1.\n        unfold actegory_bincoprod_antidistributor, bifunctor_bincoprod_antidistributor, bincoprod_antidistributor in H1.\n        repeat rewrite assoc in H1.\n        rewrite BinCoproductIn1Commutes in H1.\n        assert (aux := functor_comp (leftwhiskering_functor Act (z,,e))\n                         (BinCoproductIn1 (CP I_{ Mon_V} (H t)))\n                         (BinCoproductArrow (CP I_{ Mon_V} (H t)) η τ)).\n        cbn in aux.\n        apply (maponpaths (fun m => m · h)) in aux.\n        assert (H1' := aux @ H1).\n        clear H1 aux.\n        rewrite BinCoproductIn1Commutes in H1'.\n        etrans.\n        2: { apply pathsinv0, H1'. }\n        clear H1'.\n        etrans.\n        2: { repeat rewrite assoc.\n             do 2 apply cancel_postcomposition.\n             apply pathsinv0, BinCoproductOfArrowsIn1. }\n        repeat rewrite assoc'.\n        apply maponpaths.\n        rewrite assoc.\n        etrans.\n        2: { apply cancel_postcomposition.\n             apply pathsinv0, BinCoproductOfArrowsIn1. }\n        rewrite assoc'.\n        rewrite id_left.\n        apply pathsinv0, BinCoproductIn1Commutes.\n      + apply (maponpaths (fun m => BinCoproductIn2 (CP _ _) · m)) in H1.\n        unfold actegory_bincoprod_antidistributor, bifunctor_bincoprod_antidistributor, bincoprod_antidistributor in H1.\n        repeat rewrite assoc in H1.\n        rewrite BinCoproductIn2Commutes in H1.\n        assert (aux := functor_comp (leftwhiskering_functor Act (z,,e))\n                         (BinCoproductIn2 (CP I_{ Mon_V} (H t)))\n                         (BinCoproductArrow (CP I_{ Mon_V} (H t)) η τ)).\n        cbn in aux.\n        apply (maponpaths (fun m => m · h)) in aux.\n        assert (H1' := aux @ H1).\n        clear H1 aux.\n        rewrite BinCoproductIn2Commutes in H1'.\n        etrans.\n        2: { apply pathsinv0, H1'. }\n        clear H1'.\n        etrans.\n        2: { repeat rewrite assoc.\n             do 2 apply cancel_postcomposition.\n             apply pathsinv0, BinCoproductOfArrowsIn2. }\n        repeat rewrite assoc'.\n        apply maponpaths.\n        rewrite assoc.\n        etrans.\n        2: { apply cancel_postcomposition.\n             apply pathsinv0, BinCoproductOfArrowsIn2. }\n        rewrite assoc'.\n        apply maponpaths.\n        apply pathsinv0, BinCoproductIn2Commutes.\n  Qed.\n\n  End PropertyAsOneEquation.\n\n  End TheProperty.\n\n  Definition ghss : UU := ∑ (t : V) (η : I_{Mon_V} --> t) (τ : H t --> t), gbracket t η τ.\n  Coercion carrierghss (t : ghss) : V := pr1 t.\n\n  Section FixAGhss.\n\n  Context (gh : ghss).\n\n  Definition eta_from_alg : I_{Mon_V} --> gh := pr12 gh.\n  Definition tau_from_alg : H gh --> gh := pr122 gh.\n\n  Definition ptd_from_gh : PtdV := (pr1 gh,,eta_from_alg).\n\n  Local Notation η := eta_from_alg.\n  Local Notation τ := tau_from_alg.\n\n  Definition gfbracket (Z : PtdV) (f : pr1 Z --> gh) : pr1 Z ⊗_{Mon_V} gh --> gh :=\n    pr1 (pr1 (pr222 gh Z f)).\n\n  Notation \"⦃ f ⦄_{ Z }\" := (gfbracket Z f)(at level 0).\n\n  Lemma gfbracket_unique {Z : PtdV} (f : pr1 Z --> gh)\n    : ∏ α : pr1 Z ⊗_{Mon_V} gh --> gh, gbracket_property_parts gh η τ (pr2 Z) f α\n   → α = ⦃f⦄_{Z}.\n  Proof.\n    intros α Hyp.\n    apply path_to_ctr.\n    assumption.\n  Qed.\n\n  Lemma gfbracket_η {Z : PtdV} (f : pr1 Z --> gh) :\n    ru^{Mon_V}_{pr1 Z} · f = pr1 Z ⊗^{Mon_V}_{l} η · ⦃f⦄_{Z}.\n  Proof.\n    exact (pr1 ((pr2 (pr1 (pr222 gh Z f))))).\n  Qed.\n\n  Lemma gfbracket_τ {Z : PtdV} (f : pr1 Z --> gh) :\n    θ Z gh · #H ⦃f⦄_{Z} · τ =  pr1 Z ⊗^{Mon_V}_{l} τ · ⦃f⦄_{Z}.\n  Proof.\n    exact (pr2 ((pr2 (pr1 (pr222 gh Z f))))).\n  Qed.\n\n  (** there is a restricted form of naturality in the [f] argument, only for pointed [f] *)\n  Lemma gfbracket_natural {Z Z' : PtdV} (f : Z --> Z') (g : pr1 Z' --> gh) :\n    pr1 f ⊗^{ Mon_V}_{r} gh · ⦃g⦄_{Z'} = ⦃pr1 f · g⦄_{Z}.\n  Proof.\n    apply gfbracket_unique.\n    split.\n    - etrans.\n      2: { rewrite assoc.\n           apply cancel_postcomposition.\n           apply (bifunctor_equalwhiskers Mon_V). }\n      unfold functoronmorphisms1.\n      etrans.\n      2: { rewrite assoc'.\n           apply maponpaths.\n           apply gfbracket_η. }\n      repeat rewrite assoc.\n      apply cancel_postcomposition.\n      apply pathsinv0, monoidal_rightunitornat.\n    - etrans.\n      2: { rewrite assoc.\n           apply cancel_postcomposition.\n           apply (bifunctor_equalwhiskers Mon_V). }\n      unfold functoronmorphisms1.\n      etrans.\n      2: { rewrite assoc'.\n           apply maponpaths.\n           apply gfbracket_τ. }\n      rewrite functor_comp.\n      repeat rewrite assoc.\n      do 2 apply cancel_postcomposition.\n      apply pathsinv0, (lineator_linnatright Mon_PtdV Act Act).\n  Qed.\n\n  (** As a consequence of naturality, we can compute [gfbracket f] from [gfbracket identity] for\n      pointed morphisms [f] *)\n  Lemma compute_gfbracket {Z : PtdV} (f : Z --> ptd_from_gh) :\n    ⦃pr1 f⦄_{Z} = pr1 f ⊗^{ Mon_V}_{r} gh · ⦃identity gh⦄_{ptd_from_gh}.\n  Proof.\n    etrans.\n    { rewrite <- (id_right (pr1 f)).\n      apply pathsinv0, gfbracket_natural. }\n    apply idpath.\n  Qed.\n\n  (** we are constructing a monoid in the monoidal base category *)\n\n  Definition Ptd_from_ghss : PtdV := (pr1 gh,,η).\n\n  Definition mu_from_ghss : gh ⊗_{Mon_V} gh --> gh := ⦃identity gh⦄_{Ptd_from_ghss}.\n\n  Local Notation μ := mu_from_ghss.\n\n  Definition μ_0 : I_{Mon_V} --> gh := η.\n\n  Definition μ_0_Ptd : I_{Mon_PtdV} --> Ptd_from_ghss.\n  Proof.\n    exists μ_0.\n    cbn. apply id_left.\n  Defined.\n\n  Definition μ_1 : I_{Mon_V} ⊗_{Mon_V} gh --> gh := ⦃μ_0⦄_{I_{Mon_PtdV}}.\n\n  Lemma μ_1_is_instance_of_left_unitor : μ_1 = lu^{Mon_V}_{gh}.\n  Proof.\n    apply pathsinv0, (gfbracket_unique(Z:=I_{Mon_PtdV})).\n    split.\n    - cbn. unfold μ_0.\n      rewrite monoidal_leftunitornat.\n      apply cancel_postcomposition.\n      apply pathsinv0, unitors_coincide_on_unit.\n    - etrans.\n      { apply cancel_postcomposition.\n        apply pointedtensorialstrength_preserves_unitor.\n        apply lineator_preservesunitor. }\n      cbn.\n      apply pathsinv0, monoidal_leftunitornat.\n  Qed.\n\n  Definition ghss_monoid_data : monoid_data Mon_V gh := μ,,μ_0.\n\n  Lemma ghss_first_monoidlaw : monoid_laws_unit_right Mon_V ghss_monoid_data.\n  Proof.\n    red. cbn.\n    etrans.\n    { apply pathsinv0, (gfbracket_η(Z:=Ptd_from_ghss)). }\n    apply id_right.\n  Qed.\n\n\n  Lemma ghss_second_monoidlaw_aux :\n    ru^{Mon_V}_{I_{Mon_V}} · η = I_{Mon_V} ⊗^{Mon_V}_{l} η · (η ⊗^{Mon_V}_{r} gh · μ).\n  Proof.\n    rewrite assoc.\n    etrans.\n    2: { apply cancel_postcomposition.\n         apply (bifunctor_equalwhiskers Mon_V). }\n    unfold functoronmorphisms1.\n    rewrite assoc'.\n    etrans.\n    2: { apply maponpaths.\n         apply pathsinv0, ghss_first_monoidlaw. }\n    apply pathsinv0, monoidal_rightunitornat.\n  Qed.\n\n  Lemma ghss_second_monoidlaw : monoid_laws_unit_left Mon_V ghss_monoid_data.\n  Proof.\n    red. cbn.\n    etrans.\n    2: { apply μ_1_is_instance_of_left_unitor. }\n    apply (gfbracket_unique(Z:=I_{Mon_PtdV})).\n    split.\n    - exact ghss_second_monoidlaw_aux.\n    - rewrite functor_comp.\n      transitivity (μ_0 ⊗^{ Mon_V}_{r} H (pr1 gh) · θ Ptd_from_ghss (pr1 gh) · # H μ · τ). (* give this term due to efficiency problems *)\n      { apply cancel_postcomposition.\n        rewrite assoc.\n        apply cancel_postcomposition.\n        apply pathsinv0.\n        set (aux := lineator_linnatright Mon_PtdV\n                      (actegory_with_canonical_pointed_action Mon_V)\n                      (actegory_with_canonical_pointed_action Mon_V)\n                      H θ I_{ Mon_PtdV} Ptd_from_ghss (pr1 gh) μ_0_Ptd).\n        cbn in aux.\n        etrans.\n        { exact aux. }\n        apply idpath.\n      }\n      etrans.\n      { do 2 rewrite assoc'.\n        apply maponpaths.\n        rewrite assoc.\n        apply (gfbracket_τ(Z:=Ptd_from_ghss)).\n      }\n      repeat rewrite assoc.\n      apply cancel_postcomposition.\n      cbn.\n      apply (bifunctor_equalwhiskers Mon_V).\n  Qed.\n\n  Definition gh_squared : PtdV := Ptd_from_ghss ⊗_{Mon_PtdV} Ptd_from_ghss.\n\n  Definition μ_2 : gh ⊗_{Mon_V} gh --> gh := μ.\n\n  Lemma μ_2_is_Ptd_mor : luinv^{Mon_V}_{I_{Mon_V}} · η ⊗^{Mon_V} η · μ_2 = η.\n  Proof.\n    rewrite assoc'.\n    apply (z_iso_inv_on_right _ _ _ (nat_z_iso_pointwise_z_iso (leftunitor_nat_z_iso Mon_V) I_{ Mon_V})).\n    cbn.\n    rewrite unitors_coincide_on_unit.\n    etrans.\n    2: { apply pathsinv0, ghss_second_monoidlaw_aux. }\n    rewrite assoc.\n    apply cancel_postcomposition.\n    apply (bifunctor_equalwhiskers Mon_V).\n  Qed.\n\n  Definition μ_2_Ptd : gh_squared --> Ptd_from_ghss := μ_2,,μ_2_is_Ptd_mor.\n\n  Definition μ_3 : (gh ⊗_{Mon_V} gh) ⊗_{Mon_V} gh --> gh := ⦃μ_2⦄_{gh_squared}.\n\n  Lemma ghss_third_monoidlaw_aux : θ (pr1 gh_squared,, pr2 gh_squared) gh · # H (μ ⊗^{Mon_V}_{r} gh) =\n                                     μ_2 ⊗^{Mon_V}_{r} H gh · θ Ptd_from_ghss gh.\n  Proof.\n    apply pathsinv0.\n    assert (aux := lineator_linnatright Mon_PtdV\n                     (actegory_with_canonical_pointed_action Mon_V)\n                     (actegory_with_canonical_pointed_action Mon_V)\n                     H θ gh_squared Ptd_from_ghss gh μ_2_Ptd).\n    simpl in aux. (* simpl not cbn for efficiency of Qed *)\n    etrans.\n    { exact aux. }\n    apply idpath.\n  Qed.\n\n  Lemma ghss_third_monoidlaw : monoid_laws_assoc Mon_V ghss_monoid_data.\n  Proof.\n    red. cbn. apply pathsinv0.\n    transitivity μ_3.\n    - (** this case is the monoidal generalization of the second item on p.168 of Matthes & Uustalu, TCS 2004 *)\n      apply (gfbracket_unique(Z:=gh_squared)).\n      split.\n      + cbn.\n        etrans.\n        2: { rewrite assoc.\n             apply cancel_postcomposition.\n             apply (bifunctor_equalwhiskers Mon_V). }\n        unfold functoronmorphisms1.\n        etrans.\n        2: { rewrite assoc'.\n             apply maponpaths.\n             apply pathsinv0, ghss_first_monoidlaw.\n        }\n        apply pathsinv0, monoidal_rightunitornat.\n      + etrans.\n        { apply cancel_postcomposition.\n          rewrite functor_comp.\n          rewrite assoc.\n          apply cancel_postcomposition.\n          exact ghss_third_monoidlaw_aux.\n        }\n        etrans.\n        { do 2 rewrite assoc'.\n          apply maponpaths.\n          rewrite assoc.\n          apply (gfbracket_τ(Z:=Ptd_from_ghss)).\n        }\n        do 2 rewrite assoc.\n        apply cancel_postcomposition.\n        cbn.\n        apply (bifunctor_equalwhiskers Mon_V).\n    - (** this case is the monoidal generalization of the first item on p.168 of Matthes & Uustalu, TCS 2004 *)\n      apply pathsinv0, (gfbracket_unique(Z:=gh_squared)).\n      split.\n      + cbn.\n        etrans.\n        2: { rewrite assoc.\n             apply cancel_postcomposition.\n             rewrite assoc.\n             rewrite <- monoidal_associatornatleft.\n             rewrite assoc'.\n             apply maponpaths.\n             apply (bifunctor_leftcomp Mon_V). }\n        etrans.\n        2: { apply cancel_postcomposition.\n             do 2 apply maponpaths.\n             apply pathsinv0, ghss_first_monoidlaw. }\n        apply cancel_postcomposition.\n        apply pathsinv0, left_whisker_with_runitor.\n      + etrans.\n        { apply cancel_postcomposition.\n          rewrite assoc'.\n          rewrite functor_comp.\n          rewrite assoc.\n          apply cancel_postcomposition.\n          apply pointedtensorialstrength_preserves_actor.\n          apply lineator_preservesactor. }\n        cbn.\n        etrans.\n        { repeat rewrite assoc'.\n          do 2 apply maponpaths.\n          etrans.\n          { rewrite assoc.\n            apply cancel_postcomposition.\n            rewrite functor_comp.\n            rewrite assoc.\n            apply cancel_postcomposition.\n            apply pathsinv0, (lineator_linnatleft Mon_PtdV _ _ H θ Ptd_from_ghss _ _ μ).\n          }\n          repeat rewrite assoc'.\n          apply maponpaths.\n          rewrite assoc.\n          apply (gfbracket_τ(Z:=Ptd_from_ghss)).\n        }\n        cbn.\n        repeat rewrite assoc.\n        apply cancel_postcomposition.\n        etrans.\n        { repeat rewrite assoc'.\n          apply maponpaths.\n          do 2 rewrite <- (bifunctor_leftcomp Mon_V).\n          apply maponpaths.\n          rewrite assoc.\n          apply (gfbracket_τ(Z:=Ptd_from_ghss)).\n        }\n        cbn.\n        rewrite (bifunctor_leftcomp Mon_V).\n        repeat rewrite assoc.\n        apply cancel_postcomposition.\n        apply monoidal_associatornatleft.\n  Qed.\n\n  Definition ghss_monoid : monoid Mon_V gh.\n  Proof.\n    exists ghss_monoid_data.\n    exact (ghss_second_monoidlaw,,ghss_first_monoidlaw,,ghss_third_monoidlaw).\n  Defined.\n\n  End FixAGhss.\n\nEnd hss.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/SubstitutionSystems/GeneralizedSubstitutionSystems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2979381125646468}}
{"text": "From iris.algebra Require Import proofmode_classes.\nFrom iris.proofmode Require Import classes.\nFrom iris.base_logic Require Export derived.\nFrom iris.prelude Require Import options.\n\nImport base_logic.bi.uPred.\n\n(* Setup of the proof mode *)\nSection class_instances.\nContext {M : ucmra}.\nImplicit Types P Q R : uPred M.\n\nGlobal Instance into_pure_cmra_valid `{!CmraDiscrete A} (a : A) :\n  @IntoPure (uPredI M) (✓ a) (✓ a).\nProof. by rewrite /IntoPure discrete_valid. Qed.\n\nGlobal Instance from_pure_cmra_valid {A : cmra} (a : A) :\n  @FromPure (uPredI M) false (✓ a) (✓ a).\nProof.\n  rewrite /FromPure /=. eapply bi.pure_elim=> // ?.\n  rewrite -uPred.cmra_valid_intro //.\nQed.\n\nGlobal Instance from_sep_ownM (a b1 b2 : M) :\n  IsOp a b1 b2 →\n  FromSep (uPred_ownM a) (uPred_ownM b1) (uPred_ownM b2).\nProof. intros. by rewrite /FromSep -ownM_op -is_op. Qed.\nGlobal Instance from_sep_ownM_core_id (a b1 b2 : M) :\n  IsOp a b1 b2 → TCOr (CoreId b1) (CoreId b2) →\n  FromAnd (uPred_ownM a) (uPred_ownM b1) (uPred_ownM b2).\nProof.\n  intros ? H. rewrite /FromAnd (is_op a) ownM_op.\n  destruct H; by rewrite bi.persistent_and_sep.\nQed.\n\nGlobal Instance into_and_ownM p (a b1 b2 : M) :\n  IsOp a b1 b2 → IntoAnd p (uPred_ownM a) (uPred_ownM b1) (uPred_ownM b2).\nProof.\n  intros. apply bi.intuitionistically_if_mono. by rewrite (is_op a) ownM_op bi.sep_and.\nQed.\n\nGlobal Instance into_sep_ownM (a b1 b2 : M) :\n  IsOp a b1 b2 → IntoSep (uPred_ownM a) (uPred_ownM b1) (uPred_ownM b2).\nProof. intros. by rewrite /IntoSep (is_op a) ownM_op. Qed.\nEnd class_instances.\n", "meta": {"author": "jtassarotti", "repo": "iris-inv-hierarchy", "sha": "b25fe890d72ecb5bafa9db422ece3939d99882ab", "save_path": "github-repos/coq/jtassarotti-iris-inv-hierarchy", "path": "github-repos/coq/jtassarotti-iris-inv-hierarchy/iris-inv-hierarchy-b25fe890d72ecb5bafa9db422ece3939d99882ab/iris/base_logic/proofmode.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878414043816, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2979363004572027}}
{"text": "(* -*- company-coq-local-symbols: ((\"|=\" . ?⊨) (\"=|\" . ?⫤) (\"->>\" . ?↠) (\"=~\" . ?≈) (\"<|\" . ?⟨) (\"|>\" . ?⟩) ); -*- *)\nSet Warnings \"-notation-overridden\".\n\nRequire Import Prelude.Prelude.\nRequire Import Defs.Defs.\nRequire Import Wf.Wf.\n\nLemma subst_exvar_Sch_close_Sch_wrt_Ty : forall sch ty__in exA skA,\n    skA \\notin free_skvars_Ty ty__in\n  -> lc_Ty ty__in\n  -> subst_exvar_Sch ty__in exA (close_Sch_wrt_Ty skA sch) = close_Sch_wrt_Ty skA (subst_exvar_Sch ty__in exA sch).\nProof.\n  introv NIT LC. unfold close_Sch_wrt_Ty. generalize 0. Sch_Ty_ind sch; intros.\n  - simpl. ifdec; reflexivity.\n  - unfold close_Sch_wrt_Ty. crush. ifdec; crush.\n  - crush. if_taut. unfold close_Sch_wrt_Ty. simpl. rewrite close_Ty_wrt_Ty_rec_involuntive; crush. crush.\n  - crush.\n  - forwards: IHTy1 n. forwards: IHTy2 n.\n    unfold close_Sch_wrt_Ty in *. rewr*. crush.\n  - unfold close_Sch_wrt_Ty. simpl. rewrite IHsch. reflexivity.\nQed.\n\n(*** Overrides*)\nTheorem DSub_app_close_Sch_wrt_Ty : forall (dsub : DSub) (skA : skvar) (sch : Sch),\n    skA \\notin DSub_codom_dskvars dsub\n  -> DSub_lc dsub\n  -> DSub_app (close_Sch_wrt_Ty skA sch) dsub = close_Sch_wrt_Ty skA (DSub_app sch dsub).\nProof.\n  introv NID LC. DSub_ind dsub. crush. subdist.\n  rewrite IHdsub0. rewrite subst_exvar_Sch_close_Sch_wrt_Ty. crush.\n  rewrite free_skvars_Ty_DSub_codom_dskvars. eauto. rewr. fsetdec. rewrite emb_Ty_lc. apply LC. rewr. fsetdec.\n  rewr in NID. fsetdec. eauto.\nQed.\n\nLemma Gen_complete__helper : forall dty__exA exA skA sch dsub,\n    skA \\notin free_skvars_Sch sch\n  -> skA \\notin DSub_codom_dskvars dsub\n  -> DSub_unique ([(exA, dty__exA)] ++ dsub)\n  -> subst_skvar_Sch (emb_Ty dty__exA) skA (DSub_app (subst_exvar_Sch (T_SkVar_f skA) exA sch) dsub) = DSub_app sch ([(exA, dty__exA)] ++ dsub).\nProof.\n  introv NIT NIS UNI. Sch_Ty_ind sch; rewr.\n  - crush.\n  - crush. if_taut.\n  - destruct (exA0 == exA).\n    + subst. simpl. if_taut. rewr. simpl. if_taut.\n      do_DSub_exA_decide dsub exA.\n      * rewrite INV. rewr. reflexivity.\n      * assert (dty = dty__exA). unfold DSub_unique in UNI. applys UNI exA. crush. crush.\n        subst. rewrite EMB. rewr. reflexivity.\n    + simpl. if_taut. rewr.\n      do_DSub_exA_decide dsub exA0.\n      * rewrite INV. simpl. if_taut.\n      * rewrite EMB. rewr.\n        rewrite subst_skvar_Ty_not_in_Ty_idempotent. reflexivity. eauto.\n        rewrite free_skvars_Ty_DSub_codom_dskvars. eauto. eauto.\n  - crush.\n  - crush.\n  - simpl. rewrite IHsch. reflexivity. crush.\nQed.\n\nTheorem Gen_complete : forall ty dty dsub dsub__a denv dsch,\n    DSub_app_t ty (dsub__a ++ dsub) = emb_Ty dty\n  -> DSub_app (generalize_Sch (S_Mono ty) (DSub_to_A dsub__a) empty) dsub = emb_Sch dsch\n  -> DSub_WfDTy denv (dsub__a ++ dsub)\n  -> DSub_unique (dsub__a ++ dsub)\n  -> SubSump denv dsch (DS_Mono dty).\nProof.\n  introv EMB1 EMB2 WF UNI. gen dsub dsch denv. induction dsub__a as [|[exA dty__exA] dsub__a]; intros.\n  - simpl in EMB2. rewr*. emb_auto''. rewrite EMB in EMB1. apply emb_Ty_inj in EMB1. crush.\n  - rewrite (generalize_Sch_l_irrelevance (DSub_codom_dskvars dsub)) in EMB2.\n    simpl in EMB2.\n    remember (proj1_sig (atom_fresh (union (free_skvars_Sch (generalize_Sch (S_Mono ty) (DSub_to_A dsub__a) (DSub_codom_dskvars dsub))) (DSub_codom_dskvars dsub)))) as skA.\n    emb_auto''.\n    remember (proj1_sig (atom_fresh (union (free_skvars_Sch (generalize_Sch (S_Mono ty) (DSub_to_A dsub__a) (DSub_codom_dskvars dsub))) (DSub_codom_dskvars dsub)))) as skA.\n    eapply (SubSumpInst (free_dskvars_DSch dsch0) _ _ _ dty__exA). apply WF. rewr. fsetdec. intros.\n    rewrite <- subst_dskvar_DSch_intro. applys IHdsub__a ([(exA, dty__exA)] ++ dsub).\n    rewrite app_assoc. rewrite DSub_app_t_app_distr. rewrite DSub_app_t_app_symm.\n    subdist. subdist in EMB1. assumption. norm in UNI. eauto using DSub_unique_app_symm.\n    eapply DSub_unique_rewr. eassumption. rewr_dsrel. fsetdec'.\n    rewrite (generalize_Sch_l_irrelevance (DSub_codom_dskvars dsub)).\n    remember (generalize_Sch (S_Mono ty) (DSub_to_A dsub__a) (DSub_codom_dskvars dsub)) as dsch__gen.\n    rewrite embed_Sch_open_comm. rewrite <- EMB. rewrite DSub_app_close_Sch_wrt_Ty. rewrite <- subst_skvar_Sch_spec.\n    rewrite Gen_complete__helper. reflexivity.\n    1,2,4: subst; fresh_assert; fsetdec. eapply DSub_unique_rewr. eassumption. rewr_dsrel. fsetdec'. eauto.\n    eapply DSub_WfDTy_rewr. eassumption. auto. rewr_dsrel. fsetdec'. assumption.\nQed.\n\nTheorem subst_dskvar_DSch_generalize_DSch : forall dskA da dty sch,\n     dskA \\notin varl da\n  -> varl da [><] free_dskvars_DTy dty\n  -> lc_DTy dty\n  -> subst_dskvar_DSch dty dskA (generalize_DSch sch da)\n  = generalize_DSch (subst_dskvar_DSch dty dskA sch) da.\nProof.\n  introv NID DISJ LC. da_ind da.\n  - crush.\n  - simpl. forwards: IHda.\n    rewr in NID. fsetdec. rewr in DISJ. eapply disj_subset_proper; rewr. 3:eassumption. fsetdec. crush.\n    rewrite <- H.\n    rewrite subst_dskvar_DSch_close_DSch_wrt_DTy. reflexivity. assumption.\n    destruct (dskA == dskA0). 2:assumption. subst. false. apply NID. rewr. fsetdec.\n    eapply in_disjoint_impl_notin2.  eassumption. rewr. fsetdec.\nQed.\n\nDefinition subst_dskvar_DSub (dskA dskB : dskvar) : DSub -> DSub := map (fun pair => (fst pair, subst_dskvar_DTy (DT_SkVar_f dskA) dskB (snd pair))).\n\nTheorem subst_dskvar_DSub_to_A : forall dsub dskA dskB,\n    DSub_to_A (subst_dskvar_DSub dskB dskA dsub) = DSub_to_A dsub.\nProof. intros. induction dsub; crush. Qed.\n\nTheorem subst_dskvar_DSub_app : forall dskA dskB dsub1 dsub2,\n    subst_dskvar_DSub dskA dskB (dsub1 ++ dsub2)\n  = subst_dskvar_DSub dskA dskB dsub1 ++ subst_dskvar_DSub dskA dskB dsub2.\nProof. induction dsub1; crush. Qed.\n#[local] Hint Rewrite subst_dskvar_DSub_app : core.\n\nLemma DSub_app_t_exA_subst_dskvar_DSub : forall exA dskA dskB dsub dty,\n    DSub_app_t (T_ExVar exA) dsub = emb_Ty dty\n  -> DSub_app_t (T_ExVar exA) (subst_dskvar_DSub dskA dskB dsub) = emb_Ty (subst_dskvar_DTy (DT_SkVar_f dskA) dskB dty).\nProof.\n  introv EMB. rev_DSub_ind dsub.\n  - rewr in EMB. emb_auto''. contradiction.\n  - rewr. simpl. rewr. subdist. simpl.\n    ifdec.\n    + subst. rewr. subdist in EMB. apply emb_Ty_inj in EMB. crush.\n    + apply IHdsub0. rewr in EMB. subdist in EMB. simpl in EMB.\n      if_taut.\nQed.\n\nLemma DGen_complete__helper : forall dsub__a ty dsub dty dskB dskA,\n    DSub_app_t ty (dsub__a ++ dsub) = emb_Ty dty\n  -> dskB \\notin DSub_codom_dskvars dsub\n  -> dskB \\notin free_skvars_Ty ty\n  -> DSub_app_t ty ((subst_dskvar_DSub dskA dskB dsub__a) ++ dsub)\n  = emb_Ty (subst_dskvar_DTy (DT_SkVar_f dskA) dskB dty).\nProof.\n  introv EMB NID NIT. gen dty. induction ty; intros; emb_auto''.\n  - subdist. simpl. reflexivity.\n  - subdist. simpl. ifdec. false. apply NIT. rewr. fsetdec. crush.\n  - do_DSub_exA_decide dsub exA.\n    + subdist*. rewrite INV in *.\n      do_DSub_exA_decide dsub__a exA.\n      * rewrite INV0 in EMB. emb_auto''. contradiction.\n      * eauto using DSub_app_t_exA_subst_dskvar_DSub.\n    + subdist. rewrite EMB0. rewr. subdist in EMB. rewrite EMB0 in EMB. rewr in EMB. apply emb_Ty_inj in EMB. subst.\n      rewrite subst_dskvar_DTy_not_in_DTy_idempotent. reflexivity.\n      rewrite <- free_skvars_Ty_embed_Ty.\n      rewrite free_skvars_Ty_DSub_codom_dskvars. 2:eauto. eassumption.\n  - crush.\n  - subdist.\n    forwards IH1: IHty1. rewr in NIT. fsetdec. eassumption. subdist in IH1. rewrite IH1.\n    forwards IH2: IHty2. rewr in NIT. fsetdec. eassumption. subdist in IH2. rewrite IH2.\n    simpl. reflexivity.\nQed.\n\nTheorem subst_dskvar_DSub_lookup : forall exA dty dsub dskA dskB,\n    DTyPSI.In (exA, dty) (DSub_bindings (subst_dskvar_DSub dskB dskA dsub))\n  -> exists dty', subst_dskvar_DTy (DT_SkVar_f dskB) dskA dty' = dty /\\ DTyPSI.In (exA, dty') (DSub_bindings dsub).\nProof.\n  intros. DSub_ind dsub.\n  - crush.\n  - simpl in H. rewr in H. indestr.\n    + rewr in H. destr. exists. crush.\n    + forwards: IHdsub0. eassumption. destr. exists. crush.\nQed.\n\nTheorem DSub_unique_subst_dskvar_DSub : forall dsub dskA dskB,\n    DSub_unique dsub\n  -> DSub_unique (subst_dskvar_DSub dskB dskA dsub).\nProof.\n  introv UNI. unfold DSub_unique. intros.\n  apply subst_dskvar_DSub_lookup in H. apply subst_dskvar_DSub_lookup in H0. destr.\n  forwards: UNI. apply H1. apply H2. crush.\nQed.\n\nTheorem DSub_WfDTy_subst : forall denv1 denv2 dsub dskA dskB,\n    DSub_WfDTy denv1 dsub\n  -> Metatheory.remove dskA (DEnv_dskvars denv1) \\u singleton dskB [<=] DEnv_dskvars denv2\n  -> DSub_WfDTy denv2 (subst_dskvar_DSub dskB dskA dsub).\nProof.\n  introv WF SUB. induction dsub.\n  - crush.\n  - unfold DSub_WfDTy. intros. rewr in H. indestr.\n    + destruct a as [exA dty']. rewr in H. subst.\n      assert (denv1 |=dty DS_Mono dty'). apply WF. rewr. fsetdec.\n      apply WfDTy_props in H. apply WfDTy_props. split. 2:crush.\n      simpl. rewrite free_dskvars_DTy_subst_dskvar_DTy_upper. rewrite <- SUB.\n      destr. simpl in H. rewrite H. simpl. fsetdec.\n    + apply IHdsub. eauto. assumption.\nQed.\n\nTheorem subst_dskvar_DSub_notincodom_involuntive : forall dskA dskB dsub,\n    dskA \\notin DSub_codom_dskvars dsub\n  -> subst_dskvar_DSub dskB dskA dsub = dsub.\nProof.\n  intros. DSub_ind dsub. crush.\n  simpl.\n  asserts_rewrite (subst_dskvar_DTy (DT_SkVar_f dskB) dskA dty = dty).\n    assert (dskA \\notin free_dskvars_DTy dty).\n    rewrite <- free_skvars_Ty_embed_Ty. rewrite free_skvars_Ty_DSub_codom_dskvars. eassumption.\n    rewr. fsetdec'. crush.\n  rewrite IHdsub0. reflexivity. rewr in H. fsetdec.\nQed.\n\n\nTheorem DGen_complete : forall da ty dty dsub dsub__a denv dsch,\n    DSub_app_t ty (dsub__a ++ dsub) = emb_Ty dty\n  -> DSub_app (generalize_Sch (S_Mono ty) (DSub_to_A dsub__a) empty) dsub = emb_Sch dsch\n  -> DSub_WfDTy  denv          dsub\n  -> DSub_WfDTy (denv :::a da) dsub__a\n  -> DSub_unique (dsub__a ++ dsub)\n  -> varl da [><] DSub_codom_dskvars dsub\n  -> varl da [><] free_skvars_Ty ty\n  -> NoDup' da\n  -> SubSump denv dsch (generalize_DSch (DS_Mono dty) da).\nProof.\n  introv EMB1 EMB2 WF1 WF2 UNI DISJ1 DISJ2 ND. gen dsub__a dty dsch denv. da_ind da; intros.\n  - simpl in WF2.\n    assert (DSub_WfDTy denv (dsub__a ++ dsub)). apply DSub_WfDTy_app; assumption.\n    eapply Gen_complete; eassumption.\n  - intros. simpl. eapply (SubSumpSkol (varl da)). intros dskB NI__dskB. rewrite <- subst_dskvar_DSch_spec.\n    rewrite subst_dskvar_DSch_generalize_DSch. simpl. applys IHda (subst_dskvar_DSub dskB dskA dsub__a).\n    + eapply disj_subset_proper. 3:apply DISJ1. rewr. crush. crush.\n    + eapply disj_subset_proper. 3:apply DISJ2. rewr. crush. crush.\n    + inverts ND. eassumption.\n    + forwards: subst_dskvar_DSub_notincodom_involuntive dskA dskB dsub.\n      eapply in_disjoint_impl_notin2. eassumption. rewr. fsetdec.\n      rewrite <- H. rewrite <- subst_dskvar_DSub_app. auto using DSub_unique_subst_dskvar_DSub.\n    + apply DGen_complete__helper. eassumption.\n      eapply in_disjoint_impl_notin2. eassumption. rewr. crush.\n      eapply in_disjoint_impl_notin2. eassumption. rewr. crush.\n    + rewrite subst_dskvar_DSub_to_A in *. eassumption.\n    + eauto.\n    + eapply DSub_WfDTy_subst. eassumption. rewr_derel. fsetdec.\n    + inverts ND. eassumption.\n    + unfold AtomSetImpl.disjoint. simpl. fsetdec.\n    + auto.\nQed.\n\nTheorem free_dskvars_DSch_generalize_DSch : forall dsch da,\n    free_dskvars_DSch (generalize_DSch dsch da) [<=] free_dskvars_DSch dsch.\nProof.\n  intros. induction da. crush.\n  simpl. simpl. rewrite free_dskvars_DSch_close_DSch_wrt_DTy. rewrite IHda. crush.\nQed.\n\nTheorem SubSump_DEnv_sub : forall denv1 denv2 sch1 sch2,\n    SubSump denv1 sch1 sch2\n  -> denv1 [<=]de denv2\n  -> SubSump denv2 sch1 sch2.\nProof.\n  introv SS SUB. gen denv2. induction SS; intros.\n  - auto.\n  - econstructor. intros. apply H. eassumption. crush.\n  - econstructor. intros. eapply WfDTy_DEnv_sub. 1,2:eassumption.\n    eauto.\nQed.\n#[export] Hint Resolve SubSump_DEnv_sub : core.\n\nTheorem DGen_complete' : forall da ty dty dsub dsub__a denv dsch da__disj,\n    DSub_app_t ty (dsub__a ++ dsub) = emb_Ty dty\n  -> DSub_app (generalize_Sch (S_Mono ty) (DSub_to_A dsub__a) empty) dsub = emb_Sch dsch\n  -> DSub_WfDTy denv dsub\n  -> DSub_WfDTy (denv :::a da) dsub__a\n  -> DSub_unique (dsub__a ++ dsub)\n  -> varl da     [><] DSub_codom_dskvars dsub\n  -> varl da     [><] free_skvars_Ty ty\n  -> varl da__disj [><] free_dskvars_DTy dty\n  -> NoDup' da\n  -> SubSump denv dsch (generalize_DSch (generalize_DSch (DS_Mono dty) da) da__disj).\nProof.\n  intros. induction da__disj.\n  - simpl. eapply DGen_complete; eassumption.\n  - simpl. apply (SubSumpSkol empty). intros.\n    rewrite <- subst_dskvar_DSch_spec. rewrite subst_dskvar_DSch_not_in_DSch_idempotent.\n    eapply SubSump_DEnv_sub. apply IHda__disj. eapply disj_subset_proper. 3:eassumption. rewr. crush. crush. crush.\n    do 2 rewrite free_dskvars_DSch_generalize_DSch. eapply in_disjoint_impl_notin2. eassumption. rewr. crush.\nQed.\n\nTheorem generalize_DSch_app : forall da1 da2 sch,\n    generalize_DSch sch (da2 ++ da1) = generalize_DSch (generalize_DSch sch da1) da2.\nProof. induction da2; crush. Qed.\n", "meta": {"author": "rogerbosman", "repo": "hdm-fully-grounding", "sha": "master", "save_path": "github-repos/coq/rogerbosman-hdm-fully-grounding", "path": "github-repos/coq/rogerbosman-hdm-fully-grounding/hdm-fully-grounding-main/coq/Complete/Generalisation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878414043816, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2979363004572027}}
{"text": "Require Export Coq.Lists.List.\n\nPolymorphic Fixpoint LIn (A : Type) (a:A) (l:list A) : Type :=\n  match l with\n    | nil => False\n    | b :: m => (b = a) + LIn A a m\n  end.\n\nPolymorphic Inductive NTerm : Type :=\n| cterm : NTerm\n| oterm : list NTerm -> NTerm.\n\nPolymorphic Fixpoint dummy {A B} (x : list (A * B)) : list (A * B) :=\n  match x with\n    | nil => nil\n    | (_, _) :: _ => nil\n  end.\n\nLemma foo :\n  forall v t sub vars,\n    LIn (nat * NTerm) (v, t) (dummy sub)\n    ->\n    (\n      LIn (nat * NTerm) (v, t) sub\n      *\n      notT (LIn nat v vars)\n    ).\nProof.\n  induction sub; simpl; intros.\n  destruct H.\n  Set Printing Universes.\n  try (apply IHsub in X). (* Toplevel input, characters 5-21:\nError: Universe inconsistency (cannot enforce Top.47 = Set). *)\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_057.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2978482411040654}}
{"text": "Require Import Coq.Strings.String.\nRequire Import BinNat.\nRequire Import BinInt.\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 Poulet4.P4light.Architecture.Tofino.\nRequire Import Poulet4.P4light.Syntax.P4Notations.\nRequire Import Poulet4.Utils.P4Arith.\nRequire Import ProD3.core.Core.\nRequire Import Hammer.Plugin.Hammer.\nOpen Scope string_scope.\nOpen Scope list_scope.\nOpen Scope Z_scope.\n\nSection TofinoSpec.\n\nContext {tags_t: Type} {tags_t_inhabitant : Inhabitant tags_t}.\nNotation Val := (@ValueBase bool).\nNotation Sval := (@ValueBase (option bool)).\n(* Notation ValSet := (@ValueSet tags_t). *)\nNotation ValSetT := (@ValSetT tags_t).\nNotation Lval := ValueLvalue.\n\nNotation ident := (String.string).\nNotation path := (list ident).\nNotation P4Int := (P4Int.t tags_t).\nNotation P4String := (P4String.t tags_t).\nNotation Expression := (@Expression tags_t).\nNotation table_entry_valset := (@table_entry_valset tags_t Expression).\n\nInstance target : @Target tags_t Expression := Tofino.\n\nVariable ge : genv.\nVariable am_ge : genv.\n\nLemma hoare_extern_match_list_intro : forall keys_match_kinds entryvs,\n  hoare_extern_match_list keys_match_kinds entryvs (extern_matches keys_match_kinds entryvs).\nProof.\n  intros. unfold hoare_extern_match_list.\n  simpl. unfold extern_match.\n  remember (extern_matches keys_match_kinds entryvs) as cases.\n  clear Heqcases.\n  induction cases.\n  - auto.\n  - destruct a.\n    destruct b; auto.\nQed.\n\nFixpoint assert_int_nondet (sv : Sval) : option (N * option Z * list (option bool)) :=\n  match sv with\n  | ValBaseBit sbits =>\n      match lift_option sbits with\n      | Some bits =>\n          Some (map_snd Some (BitArith.from_lbool bits), sbits)\n      | None =>\n          Some (Z.to_N (Zlength sbits), None, sbits)\n      end\n  | ValBaseInt sbits =>\n      match lift_option sbits with\n      | Some bits =>\n          Some (map_snd Some (BitArith.from_lbool bits), sbits)\n      | None =>\n          Some (Z.to_N (Zlength sbits), None, sbits)\n      end\n  | ValBaseSenumField _ val => assert_int_nondet val\n  | _ => None\n  end.\n\nDefinition values_match_singleton_nondet (key: Sval) (val: Val): option bool :=\n  match eval_sval_to_val key with\n  | Some v =>\n      Some (values_match_singleton v val)\n  | None => None\n  end.\n\n(* Fixpoint vmm_help (bits0 bits1 bits2: list bool): bool :=\n  match bits2, bits1, bits0 with\n  | [], [], [] => true\n  | false::tl2, _::tl1, _::tl0 => vmm_help tl0 tl1 tl2\n  | true::tl2, hd1::tl1, hd0::tl0 =>\n      if (Bool.eqb hd0 hd1)\n      then (vmm_help tl0 tl1 tl2)\n      else false\n  (* should never hit *)\n  | _, _, _ => dummy_bool\n  end.\n\nDefinition values_match_mask (key: Val) (val mask: Val): bool :=\n  match assert_int key, assert_int val, assert_int mask with\n  | Some (w0, _, bits0), Some (w1, _, bits1), Some (w2, _, bits2) =>\n    if negb ((w0 =? w1)%N && (w1 =? w2)%N) then dummy_bool\n    else vmm_help bits0 bits1 bits2\n  | _, _, _ => dummy_bool\n  end.\n\nFixpoint vmm_help_z (v : Z) (bits1 bits2: list bool) :=\n  match bits2, bits1 with\n  | [], [] => true\n  | false::tl2, _::tl1 => vmm_help_z (v / 2) tl1 tl2\n  | true::tl2, hd1::tl1 =>\n      if Bool.eqb (Z.odd v) hd1\n      then (vmm_help_z (v / 2) tl1 tl2)\n      else false\n  | _, _ => dummy_bool\n  end.\n\n(* Fixpoint vmm_help_z' (v : Z) (bits1 bits2: list bool) :=\n  match bits2, bits1 with\n  | [], [] => true\n  | false::tl2, _::tl1 => vmm_help_z' (v / 2) tl1 tl2\n  | true::tl2, hd1::tl1 =>\n      andb (Bool.eqb (Z.odd v) hd1) (vmm_help_z' (v / 2) tl1 tl2)\n  | _, _ => Tofino.dummy_bool\n  end. *)\n\n\nDefinition lpm_nbits_to_mask (w1 w2 : N) : list bool :=\n(Zrepeat false (Z.of_N (w1 - w2))) ++ (Zrepeat true (Z.of_N w2)).\n\nDefinition values_match_lpm (key: Val) (val: Val) (lpm_num_bits: N): bool :=\n  match assert_int key, assert_int val with\n  | Some (w0, _, bits0), Some (w1, _, bits1) =>\n    if negb ((w0 =? w1)%N && (lpm_num_bits <=? w1)%N) then dummy_bool\n    else let bits2 := lpm_nbits_to_mask w1 lpm_num_bits in\n     vmm_help bits0 bits1 bits2\n  | _, _ => dummy_bool\n  end. *)\n\nDefinition values_match_range_nondet (key: Sval) (lo hi: Val): option bool :=\n  match assert_int_nondet key, assert_int lo, assert_int hi with\n  | Some (w0, Some z0, _), Some (w1, z1, _), Some (w2, z2, _) =>\n      if negb ((w0 =? w1)%N && (w1 =? w2)%N) then Some dummy_bool\n      else Some ((z1 <=? z0) && (z0 <=? z2))\n  | _, _, _ => None\n  end.\n\nDefinition values_match_set_nondet (keys : list Sval) (valset : ValSetT) : option bool :=\n  let values_match_set'' (key_valset: Sval * ValSetT) :=\n    let (key, valset) := key_valset in\n    match valset with\n    | VSTSingleton v => values_match_singleton_nondet key v\n    | VSTUniversal => Some true\n    | VSTMask v1 v2 => None (* values_match_mask key v1 v2 *)\n    | VSTRange lo hi => values_match_range_nondet key lo hi\n    | VSTLpm w2 v1 => None (* values_match_lpm key v1 w2 *)\n    | _ => Some dummy_bool\n    end in\n  let values_match_set' (keys: list Sval) (valset: ValSetT) :=\n    match valset with\n    | VSTProd l =>\n        if negb (Nat.eqb (List.length l) (List.length keys)) then Some dummy_bool\n        else option_map fold_andb (lift_option (List.map values_match_set'' (List.combine keys l)))\n    | _ => values_match_set'' (List.hd ValBaseNull keys, valset)\n    end in\n  match valset with\n  | VSTValueSet _ _ sets =>\n      option_map fold_orb (lift_option (List.map (values_match_set' keys) sets))\n  | _ => values_match_set' keys valset\n  end.\n\nDefinition extern_matches_nondet (key: list (Sval * ident)) (entries: list table_entry_valset)\n    : list (option bool * action_ref) :=\n  let ks := List.map fst key in\n  let mks := List.map snd key in\n  match check_lpm_count mks with\n  | None => []\n  | Some lpm_idx =>\n    let entries' := List.map (fun p => (valset_to_valsett (fst p), snd p)) entries in\n    let entries'' :=\n      if (Nat.ltb lpm_idx (List.length mks))\n      then sort_lpm entries' lpm_idx\n      else entries' in\n    List.map (fun s => (values_match_set_nondet ks (fst s), snd s)) entries''\n  end.\n\nLemma hoare_extern_match_list_nondet_intro : forall keys match_kinds entryvs,\n  hoare_extern_match_list_nondet keys match_kinds entryvs\n      (extern_matches_nondet (combine keys match_kinds) entryvs).\nProof.\n  (* intros. induction entryvs.\n  - red; intros.\n    unfold extern_matches_nondet.\n    simpl.\n  unfold hoare_extern_match_list_nondet.\n    simpl.\n  unfold hoare_extern_match_list_nondet; intros.\n\n  simpl. unfold extern_match.\n  inductionn\n  remember (extern_matches keys_match_kinds c) as cases.\n  clear Heqcases.\n  induction cases.\n  - auto.\n  - destruct a.\n    destruct b; auto. *)\n(* Qed. *)\nAdmitted.\n\nOpen Scope func_spec.\n\n(* This is the general form of RegisterAction's apply method's spec that we support.\n  We expecct this is general enough for all practical application. We don't support\n  other kind of apply methods. *)\n(* I don't define f as (Val -> Val) because this function should be partial. *)\nDefinition RegisterAction_apply_spec {A} (p : path) (repr : A -> Val) (f : A -> A) (retv : A -> Sval) : func_spec :=\n  WITH,\n    PATH p\n    MOD None []\n    WITH (old_value : A),\n      PRE\n        (ARG [eval_val_to_sval (repr old_value)]\n        (MEM []\n        (EXT [])))\n      POST\n        (ARG_RET [eval_val_to_sval (repr (f old_value));\n                  retv old_value]\n           ValBaseNull\n        (MEM []\n        (EXT []))).\n\nDefinition RegisterAction_apply_spec' {A} (p : path) (valid : A -> Prop) (repr : A -> Val) (f : A -> A) (retv : A -> Sval) : func_spec :=\n  WITH,\n    PATH p\n    MOD None []\n    WITH (old_value : A) (H_old_value : valid old_value),\n      PRE\n        (ARG [eval_val_to_sval (repr old_value)]\n        (MEM []\n        (EXT [])))\n      POST\n        (ARG_RET [eval_val_to_sval (repr (f old_value));\n                  retv old_value]\n           ValBaseNull\n        (MEM []\n        (EXT []))).\n\n(* Remove the content type constaint of register, right? *)\n\nDefinition RegisterAction_execute_spec : func_spec :=\n  WITH A p (* path *) index_w typ s (* size *) r (* reg *)\n      (H_r : PathMap.get p (ge_ext ge) = Some (Tofino.EnvRegAction r))\n      (H_ws : PathMap.get r (ge_ext ge) = Some (Tofino.EnvRegister (index_w, typ, s)))\n      (H_s : 0 <= s <= Z.pow 2 (Z.of_N index_w))\n      apply_fd repr apply_f apply_retv\n      (H_apply_fd : PathMap.get (p ++ [\"apply\"]) (ge_ext ge) =\n          Some (Tofino.EnvAbsMet (exec_abstract_method am_ge p apply_fd)))\n      (H_apply_body : func_sound am_ge apply_fd nil\n          (RegisterAction_apply_spec (A := A) p repr apply_f apply_retv)),\n    PATH p\n    MOD None [r]\n    WITH (c : list Val) (i : Z)\n      (H_c : Zlength c = s)\n      (H_i : 0 <= i < s)\n      old_v\n      (H_old_v : Znth i c = repr old_v),\n      PRE\n        (ARG [P4Bit index_w i]\n        (MEM []\n        (EXT [ExtPred.singleton r (Tofino.ObjRegister c)])))\n      POST\n        (ARG_RET [] (apply_retv old_v)\n        (MEM []\n        (EXT [ExtPred.singleton r\n            (Tofino.ObjRegister (upd_Znth i c (repr (apply_f old_v))))]))).\n\nDefinition RegisterAction_execute_spec' : func_spec :=\n  WITH A p (* path *) index_w typ s (* size *) r (* reg *)\n      (H_r : PathMap.get p (ge_ext ge) = Some (Tofino.EnvRegAction r))\n      (H_ws : PathMap.get r (ge_ext ge) = Some (Tofino.EnvRegister (index_w, typ, s)))\n      (H_s : 0 <= s <= Z.pow 2 (Z.of_N index_w))\n      apply_fd apply_valid repr apply_f apply_retv\n      (H_apply_fd : PathMap.get (p ++ [\"apply\"]) (ge_ext ge) =\n          Some (Tofino.EnvAbsMet (exec_abstract_method am_ge p apply_fd)))\n      (H_apply_body : func_sound am_ge apply_fd nil\n          (RegisterAction_apply_spec' (A := A) p apply_valid repr apply_f apply_retv)),\n    PATH p\n    MOD None [r]\n    WITH (c : list Val) (i : Z)\n      (H_c : Zlength c = s)\n      (H_i : 0 <= i < s)\n      old_v\n      (H_old_v : Znth i c = repr old_v)\n      (H_valid : apply_valid old_v),\n      PRE\n        (ARG [P4Bit index_w i]\n        (MEM []\n        (EXT [ExtPred.singleton r (Tofino.ObjRegister c)])))\n      POST\n        (ARG_RET [] (apply_retv old_v)\n        (MEM []\n        (EXT [ExtPred.singleton r\n            (Tofino.ObjRegister (upd_Znth i c (repr (apply_f old_v))))]))).\n\nDefinition execute_fundef : (@fundef tags_t) := FExternal \"RegisterAction\" \"execute\".\n\nLemma to_lbool_lbool_to_val' : forall bs w,\n  w = Z.to_N (Zlength bs) ->\n  P4Arith.to_lbool w\n      (P4Arith.BitArith.lbool_to_val bs 1 0)\n  = bs.\nProof.\n  intros; subst.\n  apply to_lbool_lbool_to_val.\nQed.\n\nLemma RegisterAction_execute_body' :\n  func_sound ge execute_fundef nil RegisterAction_execute_spec'.\nProof.\n  intros_fs_bind.\n  split.\n  2 : {\n    unfold func_modifies. intros.\n    inv H.\n    inv H5. inv H.\n    eapply eq_trans in H0; only 2 : (symmetry; apply H_r).\n    symmetry in H0; inv H0.\n    eapply eq_trans in H3; only 2 : (symmetry; apply H_ws).\n    symmetry in H3; inv H3.\n    eapply eq_trans in H1; only 2 : (symmetry; apply H_apply_fd).\n    symmetry in H1; inv H1.\n    destruct (-1 <? index) eqn:?.\n    2 : {\n      simpl in H8. destruct H8; subst.\n      apply modifies_refl.\n    }\n    destruct (index <? s) eqn:?.\n    2 : {\n      simpl in H8. destruct H8; subst.\n      apply modifies_refl.\n    }\n    simpl in H8. destruct H8; subst.\n    eapply modifies_trans.\n    { eapply modifies_incl.\n      { assert (modifies None [] (m, es) (m, s')). {\n          inv H7.\n          eapply (proj2 H_apply_body) in H1.\n          solve_modifies.\n        }\n        eassumption.\n      }\n      all : solve_modifies.\n    }\n    eapply modifies_set_ext with (st := (m, s')).\n    simpl.\n    replace (in_scope r r) with true. 2 : {\n      clear; induction r.\n      - auto.\n      - simpl. rewrite eqb_refl; auto.\n    }\n    auto.\n  }\n  intros_fsh_bind.\n  unfold fundef_satisfies_hoare.\n  unfold hoare_func; intros.\n  inv H0. inv H6.\n  inv H0.\n  eapply eq_trans in H1; only 2 : (symmetry; apply H_r).\n  symmetry in H1; inv H1.\n  eapply eq_trans in H4; only 2 : (symmetry; apply H_ws).\n  symmetry in H4; inv H4.\n  eapply eq_trans in H2; only 2 : (symmetry; apply H_apply_fd).\n  symmetry in H2; inv H2.\n  destruct H as [? []].\n  destruct H1 as [? _].\n  simpl in H1.\n  rewrite H5 in H1. inv H1.\n  assert (index = i). {\n    clear -H_i H_s H H3 H6.\n    unfold arg_denote, arg_satisfies in H.\n    inv H. inv H5.\n    inv H3. clear H7.\n    assert (ValBaseBit indexb = (ValBaseBit (P4Arith.to_lbool index_w i))). {\n      eapply exec_val_eq.\n      eapply exec_val_sym with eq.\n      { clear; auto. }\n      assert (val_to_sval\n          (ValBaseBit (P4Arith.to_lbool index_w i))\n          (eval_val_to_sval (ValBaseBit (P4Arith.to_lbool index_w i)))). {\n        eapply exec_val_sym with strict_read_ndetbit.\n        2 : eapply sval_to_val_eval_val_to_sval.\n        { clear; sauto. }\n        { clear; sauto. }\n      }\n      eapply exec_val_trans with (f := read_detbit);\n        [ | eapply exec_val_trans; [ | eassumption | eassumption] | eassumption ].\n      { unfold rel_trans; clear; sauto. }\n      { unfold rel_trans; clear; sauto. }\n    }\n    inv H.\n    rewrite P4Arith.bit_from_to_bool in H6.\n    inv H6.\n    apply Z.mod_small.\n    unfold P4Arith.BitArith.upper_bound.\n    lia.\n  }\n  clear H H3 H6.\n  subst.\n  destruct (-1 <? i) eqn:Heqb; only 2 : lia. clear Heqb.\n  destruct (i <? Zlength c) eqn:Heqb; only 2 : lia. clear Heqb.\n  simpl in H7. destruct H9. subst.\n  clear H0.\n  assert (content' = c). {\n    clear -H_apply_body H H5 H8.\n    inv H8.\n    apply (H_apply_body) in H1.\n    destruct H1.\n    assert (PathMap.get r s' = PathMap.get r es). {\n      symmetry.\n      apply H3.\n      auto.\n    }\n    rewrite H4 in H.\n    change (@extern_object tags_t Expression (@extern_sem tags_t Expression target))\n      with (@Tofino.object tags_t Expression) in H.\n    congruence.\n  }\n  clear H H5.\n  subst.\n  rewrite H_old_v in H8.\n  assert (new_value = repr (apply_f old_v)\n      /\\ sval_to_val read_ndetbit (apply_retv old_v) retv). {\n    clear -H_apply_body H_valid H8.\n    inv H8.\n    eapply (proj1 H_apply_body old_v) in H0.\n    2 : { auto. }\n    2 : {\n      split.\n      2 : { split; constructor. }\n      inv H. inv H6.\n      apply val_to_sval_iff in H4.\n      subst.\n      constructor; only 2 : constructor.\n      apply sval_refine_refl.\n    }\n    clear H.\n    destruct H0.\n    inv H. inv H6. inv H7.\n    inv H1. inv H8. inv H9.\n    eapply sval_refine_sval_to_val_n_trans in H6. 2 : eapply H4. clear H4.\n    eapply sval_refine_sval_to_val_n_trans in H5. 2 : eapply H3. clear H3.\n    split.\n    { eapply sval_to_val_n_eval_val_to_sval_eq; eauto. }\n    { auto. }\n  }\n  clear H8.\n  destruct H; subst.\n  split.\n  { inv H12. constructor. }\n  clear H12.\n  split.\n  { unfold ret_denote, ret_satisfies.\n    intros.\n    eapply exec_val_trans; only 2, 3 : eassumption.\n    clear; red; sauto.\n  }\n  split.\n  { constructor. }\n  { constructor.\n    2 : constructor.\n    simpl.\n    rewrite PathMap.get_set_same.\n    auto.\n  }\nQed.\n\nLemma RegisterAction_execute_body :\n  func_sound ge execute_fundef nil RegisterAction_execute_spec.\nProof.\n  intros_fs_bind.\n  assert (H_apply_body' : func_sound am_ge apply_fd []\n      (RegisterAction_apply_spec' p (fun _ => True) repr apply_f apply_retv)). {\n    refine_function H_apply_body.\n    entailer.\n    entailer.\n  }\n  split.\n  2 : {\n    unshelve eapply (proj2 (RegisterAction_execute_body' _ _ _ _ _ _ _ _ _ _ (fun _ => True) _ _ _ _ _));\n      eauto.\n  }\n  intros_fsh_bind.\n  eapply hoare_func_post.\n  { eapply hoare_func_pre.\n    2 : {\n      unshelve eapply (proj1 (RegisterAction_execute_body' _ _ _ _ s _ _ _ _ _ (fun _ => True) _ _ _ _ _));\n        eauto.\n    }\n    entailer.\n  }\n  entailer.\nQed.\n\nDefinition extend_hash_output_Z (hash_w : N) (output : list bool) : Z :=\n  let output_w := N.of_nat (List.length output) in\n  let num_copies := N.div hash_w output_w in\n  let num_remainder := Z.of_N (N.modulo hash_w output_w) in\n  let lsbs := repeat_concat_list (N.to_nat num_copies) output in\n  let msbs := sublist (Z.of_N output_w - num_remainder) (Z.of_N output_w) output in\n  BitArith.lbool_to_val (app msbs lsbs) 1 0.\n\nDefinition dummy_Z : Z.\nProof. exact 0. Qed.\n\nDefinition hash_Z (hash_w : N) (poly : CRC_polynomial) (v : Val) : Z :=\n  match convert_to_bits v with\n  | Some input =>\n      extend_hash_output_Z hash_w (Hash.compute_crc (N.to_nat (CRCP_width poly)) (lbool_to_N (CRCP_coeff poly))\n          (lbool_to_N (CRCP_init poly)) (lbool_to_N (CRCP_xor poly))\n          (CRCP_reversed poly) (CRCP_reversed poly) input)\n  | None =>\n      dummy_Z\n  end.\n\nDefinition Hash_get_fundef : (@fundef tags_t) := FExternal \"Hash\" \"get\".\n\nDefinition Hash_get_spec : func_spec :=\n  WITH p (* path *) hash_w poly\n      (H_p : PathMap.get p (ge_ext ge) = Some (EnvHash (hash_w, poly)))\n      (H_width : (CRCP_width poly > 0)%N),\n    PATH p\n    MOD None []\n    WITH (v : Val),\n      PRE\n        (ARG [eval_val_to_sval v]\n        (MEM []\n        (EXT [])))\n      POST\n        (ARG_RET [] (P4Bit hash_w (hash_Z hash_w poly v))\n        (MEM []\n        (EXT []))).\n\nLemma Zlength_repeat_concat_list : forall {A} num (l : list A),\n  Zlength (repeat_concat_list num l) = Z.of_nat num * Zlength l.\nProof.\n  intros. unfold repeat_concat_list.\n  assert (forall l',\n    Zlength\n      ((fix repeat_concat_list' (num0 : nat) (l0 res : list A) {struct num0} : list A :=\n          match num0 with\n          | 0%nat => res\n          | S num' => repeat_concat_list' num' l0 (l0 ++ res)\n          end) num l l') = Z.of_nat num * Zlength l + Zlength l'). {\n    induction num; intros.\n    - list_solve.\n    - rewrite IHnum.\n      list_solve.\n  }\n  specialize (H []).\n  list_solve.\nQed.\n\nLemma Hash_get_body targs :\n  func_sound ge Hash_get_fundef targs Hash_get_spec.\nProof.\n  intros_fs_bind.\n  split.\n  2 : {\n    red. intros.\n    inv H.\n    inv H5. inv H.\n    apply modifies_refl.\n  }\n  intros_fsh_bind.\n  hnf; intros.\n  inv H0. inv H6.\n  inv H0.\n  eapply eq_trans in H1; only 2 : (symmetry; apply H_p).\n  symmetry in H1; inv H1.\n  unfold hash_Z.\n  destruct H as [? []].\n  hnf in H. inv H. inv H8.\n  inv H3. clear H9.\n  assert (sval_to_val read_ndetbit (eval_val_to_sval v) v0). {\n    eapply exec_val_trans. 2, 3 : eassumption.\n    red; clear; sauto lq: on.\n  }\n  clear H7. rename H into H7.\n  apply sval_to_val_eval_val_to_sval_iff in H7. 2 : {\n    clear; sauto lq: on.\n  }\n  subst.\n  rewrite H2. clear H2.\n  split.\n  { inv H12. constructor. }\n  split.\n  { apply eval_val_to_sval_ret_denote.\n    unfold extend_hash_output_Z.\n    unfold P4Bit.\n    unfold to_loptbool.\n    rewrite to_lbool_lbool_to_val'. 2 : {\n      clear -H_width.\n      assert (Datatypes.length\n                 (Hash.compute_crc (N.to_nat (CRCP_width poly)) (lbool_to_N (CRCP_coeff poly))\n                    (lbool_to_N (CRCP_init poly)) (lbool_to_N (CRCP_xor poly))\n                    (CRCP_reversed poly) (CRCP_reversed poly) input) = N.to_nat (CRCP_width poly)). {\n        apply Hash.length_compute_crc.\n      }\n      revert H.\n      generalize (Hash.compute_crc (N.to_nat (CRCP_width poly)) (lbool_to_N (CRCP_coeff poly))\n                    (lbool_to_N (CRCP_init poly)) (lbool_to_N (CRCP_xor poly))\n                    (CRCP_reversed poly) (CRCP_reversed poly) input).\n      intros.\n      replace (N.of_nat (Datatypes.length b)) with (Z.to_N (Zlength b)). 2 : {\n        rewrite Zlength_correct. lia.\n      }\n      assert (Zlength b > 0). {\n        rewrite Zlength_correct. lia.\n      }\n      clear -H0.\n      assert (0 <= Z.of_N (hash_w mod Z.to_N (Zlength b)) < (Zlength b)). {\n        assert (0 <= hash_w mod Z.to_N (Zlength b) < Z.to_N (Zlength b))%N. {\n          apply N.mod_bound_pos; lia.\n        }\n        lia.\n      }\n      list_simplify.\n      rewrite Zlength_repeat_concat_list.\n      replace (Z.of_N (Z.to_N (Zlength b))) with (Zlength b) by list_solve.\n      replace (Z.of_nat (N.to_nat (hash_w / Z.to_N (Zlength b))) * Zlength b) with\n        (Z.of_N (hash_w / Z.to_N (Zlength b) * Z.to_N (Zlength b))) by lia.\n      pose proof (N.div_mod hash_w (Z.to_N (Zlength b))).\n      lia.\n    }\n    reflexivity.\n  }\n  repeat constructor.\nQed.\n\n(* Lemmas for table matching simplifcation. *)\n\nLemma reduce_match_range: forall w x lo hi x' lo' hi' xb lob hib,\n  Tofino.assert_int x = Some (w, x', xb) ->\n  Tofino.assert_int lo = Some (w, lo', lob) ->\n  Tofino.assert_int hi = Some (w, hi', hib) ->\n  Tofino.values_match_range x lo hi = (lo' <=? x') && (x' <=? hi').\nProof.\n  intros.\n  unfold Tofino.values_match_range.\n  rewrite H, H0, H1. rewrite N.eqb_refl. simpl.\n  reflexivity.\nQed.\n\nLemma reduce_match_singleton: forall w x y x' y' xb yb,\n  val_sim x y ->\n  Tofino.assert_int x = Some (w, x', xb) ->\n  Tofino.assert_int y = Some (w, y', yb) ->\n  Tofino.values_match_singleton x y = (x' =? y').\nProof.\n  intros. revert y H H1.\n  induction x;\n  induction y; intros;\n  simpl in H0; simpl in H1; unfold val_sim in H; try discriminate; try inv H.\n  { unfold Tofino.values_match_singleton, Ops.eval_binary_op_eq.\n    remember (P4Arith.BitArith.from_lbool value0) as n0_name. inv H1.\n    remember (P4Arith.BitArith.from_lbool value) as n_name. inv H0.\n    rewrite N.eqb_refl. trivial. }\n  { unfold Tofino.values_match_singleton, Ops.eval_binary_op_eq.\n    remember (P4Arith.IntArith.from_lbool value0) as z0_name. inv H1.\n    remember (P4Arith.IntArith.from_lbool value) as z_name. inv H0.\n    rewrite N.eqb_refl. trivial. }\n  unfold Tofino.values_match_singleton in IHx |- *. simpl in IHx |- *. rewrite String.eqb_refl.\n  eapply IHx; assumption.\nQed.\n\nLemma assert_int_len : forall x w x' xb,\n  Tofino.assert_int x = Some (w, x', xb) -> Z.to_N (Zlength xb) = w.\nProof.\n  induction x; intros; simpl in H; try discriminate.\n  - unfold P4Arith.BitArith.from_lbool in H; inv H; trivial.\n  - unfold P4Arith.IntArith.from_lbool in H; inv H; trivial.\n  - eapply IHx; eauto.\nQed.\n\n(* This lemma is unused. *)\nLemma to_lbool''_to_lbool : forall (width : N) (value : Z),\n  rev (to_lbool'' (N.to_nat width) value) = P4Arith.to_lbool width value.\nProof.\n  intros.\n  apply to_lbool''_to_lbool'.\nQed.\n\n(* This lemma is unused. *)\nLemma bit_to_from_bool : forall bl,\n  P4Arith.to_lbool (fst (P4Arith.BitArith.from_lbool bl)) (snd (P4Arith.BitArith.from_lbool bl)) = bl.\nProof.\n  intros.\n  rewrite <- to_lbool''_to_lbool.\n  unfold BitArith.from_lbool, BitArith.lbool_to_val. simpl.\n  rewrite <- Zlength_rev. rewrite <- (rev_involutive bl) at 3. f_equal.\n  generalize (rev bl). clear bl. intro bl.\n  induction bl; auto.\n  simpl.\n  replace (N.to_nat (Z.to_N (Zlength (a :: bl)))) with (S (N.to_nat (Z.to_N (Zlength bl)))) by list_solve.\n  simpl to_lbool''.\n  destruct a; rewrite P4Arith.BitArith.le_lbool_to_val_1_0.\n  - f_equal.\n    { replace (P4Arith.BitArith.le_lbool_to_val bl 1 0 * 2 + 1) with\n        (1 + 2 * P4Arith.BitArith.le_lbool_to_val bl 1 0) by lia.\n      rewrite Z.odd_add_mul_2; auto.\n    }\n    rewrite Z.div_add_l by lia.\n    replace (1 / 2) with 0 by auto.\n    rewrite Z.add_0_r.\n    apply IHbl.\n  - f_equal.\n    { replace (P4Arith.BitArith.le_lbool_to_val bl 1 0 * 2 + 0) with\n        (0 + 2 * P4Arith.BitArith.le_lbool_to_val bl 1 0) by lia.\n      rewrite Z.odd_add_mul_2; auto.\n    }\n    rewrite Z.div_add_l by lia.\n    replace (0 / 2) with 0 by auto.\n    rewrite Z.add_0_r.\n    apply IHbl.\nQed.\n\n(* This lemma is unused. *)\nLemma int_to_from_bool : forall bl,\n  P4Arith.to_lbool (fst (P4Arith.IntArith.from_lbool bl)) (snd (P4Arith.IntArith.from_lbool bl)) = bl.\nProof.\n  intros.\n  rewrite <- to_lbool''_to_lbool.\n  unfold IntArith.from_lbool, IntArith.lbool_to_val. simpl.\n  rewrite <- Zlength_rev. rewrite <- (rev_involutive bl) at 3. f_equal.\n  generalize (rev bl). clear bl. intro bl.\n  induction bl; auto.\n  simpl.\n  replace (N.to_nat (Z.to_N (Zlength (a :: bl)))) with (S (N.to_nat (Z.to_N (Zlength bl)))) by list_solve.\n  simpl to_lbool''.\n  destruct a; rewrite P4Arith.IntArith.le_lbool_to_val_1_0.\n  - f_equal.\n    { destruct bl as [ | b bl']; auto.\n      set (bl := b :: bl') in *.\n      replace (P4Arith.IntArith.le_lbool_to_val bl 1 0 * 2 + 1) with\n        (1 + 2 * P4Arith.IntArith.le_lbool_to_val bl 1 0) by lia.\n      rewrite Z.odd_add_mul_2; auto.\n    }\n    destruct bl as [ | b bl']; auto.\n    set (bl := b :: bl') in *.\n    rewrite Z.div_add_l by lia.\n    replace (1 / 2) with 0 by auto.\n    rewrite Z.add_0_r.\n    apply IHbl.\n  - f_equal.\n    { destruct bl as [ | b bl']; auto.\n      set (bl := b :: bl') in *.\n      replace (P4Arith.IntArith.le_lbool_to_val bl 1 0 * 2 + 0) with\n        (0 + 2 * P4Arith.IntArith.le_lbool_to_val bl 1 0) by lia.\n      rewrite Z.odd_add_mul_2; auto.\n    }\n    destruct bl as [ | b bl']; auto.\n    set (bl := b :: bl') in *.\n    rewrite Z.div_add_l by lia.\n    replace (0 / 2) with 0 by auto.\n    rewrite Z.add_0_r.\n    apply IHbl.\nQed.\n\n(* This lemma is unused. *)\nLemma assert_int_conv : forall w x x' xb,\n  Tofino.assert_int x = Some (w, x', xb) ->\n  P4Arith.to_lbool w x' = xb.\nProof.\n  induction x; intros; simpl in H; try discriminate; inv H.\n  - apply bit_to_from_bool.\n  - apply int_to_from_bool.\n  - auto.\nQed.\n\nLemma reduce_match_mask: forall w x v m x' v' m' xb vb mb,\n  Tofino.assert_int x = Some (w, x', xb) ->\n  Tofino.assert_int v = Some (w, v', vb) ->\n  Tofino.assert_int m = Some (w, m', mb) ->\n  Tofino.values_match_mask x v m = Tofino.vmm_help xb vb mb.\nProof.\n  intros.\n  unfold Tofino.values_match_mask; rewrite H, H0, H1; rewrite N.eqb_refl; simpl.\n  auto.\nQed.\n\nEnd TofinoSpec.\n\n#[export] Hint Extern 5 (func_modifies _ _ _ _ _) =>\n  (refine (proj2 (Hash_get_body _ _ _ _ _ _ _)); try exact (@nil _); compute; reflexivity) : func_specs.\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/TofinoSpec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.29779552760158867}}
{"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(* begin hide *)\n\nRequire Export CoRN.ftc.COrdLemmas.\nRequire Export CoRN.ftc.Partitions.\n\nSection Separating__Separated.\n\nVariables a b : IR.\nHypothesis Hab : a[<=]b.\nLet I := compact a b Hab.\n\nVariable F : PartIR.\nHypothesis contF : Continuous_I Hab F.\nHypothesis incF : included (Compact Hab) (Dom F).\n\nHypothesis Hab' : a[<]b.\nVariables m n : nat.\nVariable P : Partition Hab n.\nVariable R : Partition Hab m.\n\nHypothesis HP : _Separated P.\nHypothesis HR : _Separated R.\n\nLemma RS_pos_n : 0 < n.\nProof.\n apply partition_less_imp_gt_zero with a b Hab; assumption.\nQed.\n\nLemma RS_pos_m : 0 < m.\nProof.\n apply partition_less_imp_gt_zero with a b Hab; assumption.\nQed.\n\nVariable alpha : IR.\nHypothesis Halpha : [0][<]alpha.\n\nLet e := alpha [/]TwoNZ[/] _[//]max_one_ap_zero (b[-]a).\n\nLemma RS_He : [0][<]e.\nProof.\n unfold e in |- *; apply div_resp_pos.\n  apply pos_max_one.\n apply pos_div_two; assumption.\nQed.\n\nLet contF' := contin_prop _ _ _ _ contF.\n\nLet d : IR.\nProof.\n elim (contF' e RS_He).\n intros; apply x.\nDefined.\n\nLemma RS_Hd : [0][<]d.\nProof.\n unfold d in |- *; elim (contF' e RS_He); auto.\nQed.\n\nLemma RS_Hd' :\n  forall x y : IR,\n  I x ->\n  I y -> forall Hx Hy, AbsIR (x[-]y)[<=]d -> AbsIR (F x Hx[-]F y Hy)[<=]e.\nProof.\n unfold d in |- *; elim (contF' e RS_He); auto.\nQed.\n\nVariable csi : IR.\nHypothesis Hcsi : [0][<]csi.\n\nLet M := Norm_Funct contF.\n\nLet deltaP := AntiMesh P.\nLet deltaR := AntiMesh R.\nLet delta :=\n  Min (Min deltaP deltaR)\n    (Min (alpha [/]TwoNZ[/] _[//]max_one_ap_zero (nring n[*]M)) (Min csi d)).\n\nLemma RS_delta_deltaP : delta[<=]deltaP.\nProof.\n unfold delta in |- *; eapply leEq_transitive.\n  apply Min_leEq_lft.\n apply Min_leEq_lft.\nQed.\n\nLemma RS_delta_deltaR : delta[<=]deltaR.\nProof.\n unfold delta in |- *; eapply leEq_transitive.\n  apply Min_leEq_lft.\n apply Min_leEq_rht.\nQed.\n\nLemma RS_delta_csi : delta[<=]csi.\nProof.\n unfold delta in |- *; eapply leEq_transitive.\n  apply Min_leEq_rht.\n eapply leEq_transitive.\n  apply Min_leEq_rht.\n apply Min_leEq_lft.\nQed.\n\nLemma RS_delta_d : delta[<=]d.\nProof.\n unfold delta in |- *; eapply leEq_transitive.\n  apply Min_leEq_rht.\n eapply leEq_transitive; apply Min_leEq_rht.\nQed.\n\nLemma RS_delta_pos : [0][<]delta.\nProof.\n unfold delta in |- *; apply less_Min; apply less_Min.\n    unfold deltaP in |- *; apply pos_AntiMesh; [ apply RS_pos_n | assumption ].\n   unfold deltaR in |- *; apply pos_AntiMesh; [ apply RS_pos_m | assumption ].\n  apply div_resp_pos.\n   apply pos_max_one.\n  apply pos_div_two; assumption.\n apply less_Min.\n  assumption.\n apply RS_Hd.\nQed.\n\nSection Defining_ai'.\n\nVariable i : nat.\nHypothesis Hi : i <= n.\n\nLemma separation_conseq :\n  forall (j : nat) (Hj : j <= m),\n  AbsIR (P i Hi[-]R j Hj)[<]delta [/]TwoNZ ->\n  forall j' : nat,\n  j <> j' -> forall Hj' : j' <= m, delta [/]TwoNZ[<]AbsIR (P i Hi[-]R j' Hj').\nProof.\n intros j Hj H; intros.\n elim (Cnat_total_order _ _ H0); clear H0; intro H0.\n  elim (le_lt_dec j' m); intro.\n   cut (S j <= m); [ intro | clear H; apply le_trans with j'; auto ].\n   eapply less_wdr.\n    2: apply AbsIR_minus.\n   cut (R (S j) H1[<=]R j' Hj'); intros.\n    eapply less_wdr.\n     2: apply eq_symmetric_unfolded; apply AbsIR_eq_x.\n     rstepr (R _ Hj'[-]R _ H1[+](R _ H1[-]R _ Hj)[+](R _ Hj[-]P i Hi)).\n     rstepl ([0][+]delta[+][--](delta [/]TwoNZ)).\n     apply plus_resp_leEq_less.\n      apply plus_resp_leEq_both.\n       apply shift_leEq_minus; astepl (R _ H1).\n       assumption.\n      apply leEq_transitive with deltaR.\n       apply RS_delta_deltaR.\n      unfold deltaR in |- *; apply AntiMesh_lemma.\n     rstepl ([--](delta [/]TwoNZ)).\n     rstepr ([--](P i Hi[-]R j Hj)).\n     apply inv_resp_less.\n     eapply leEq_less_trans.\n      apply leEq_AbsIR.\n     assumption.\n    apply shift_leEq_minus; astepl (P i Hi).\n    eapply leEq_transitive.\n     2: apply H2.\n    apply less_leEq; apply less_transitive_unfolded with (R j Hj[+]delta [/]TwoNZ).\n     apply shift_less_plus'.\n     eapply leEq_less_trans; [ apply leEq_AbsIR | apply H ].\n    apply shift_plus_less'.\n    apply less_leEq_trans with delta.\n     apply pos_div_two'; exact RS_delta_pos.\n    apply leEq_transitive with deltaR.\n     apply RS_delta_deltaR.\n    unfold deltaR in |- *; apply AntiMesh_lemma.\n   apply local_mon_imp_mon'_le with (f := fun (i : nat) (Hi : i <= m) => R i Hi).\n     intros; apply HR.\n    red in |- *; intros; apply prf1; auto.\n   assumption.\n  exfalso; apply (le_not_lt j' m); auto.\n elim (le_lt_dec j 0); intro.\n  exfalso; apply lt_n_O with j'; red in |- *; apply le_trans with j; auto.\n generalize Hj H H0; clear H0 H Hj.\n set (jj := pred j) in *.\n cut (j = S jj); [ intro | unfold jj in |- *; apply S_pred with 0; auto ].\n rewrite H; intros.\n cut (jj <= m); [ intro | auto with arith ].\n cut (R j' Hj'[<=]R jj H2); intros.\n  eapply less_wdr.\n   2: apply eq_symmetric_unfolded; apply AbsIR_eq_x.\n   rstepr (P i Hi[-]R _ Hj[+](R _ Hj[-]R jj H2)[+](R jj H2[-]R j' Hj')).\n   rstepl ([--](delta [/]TwoNZ)[+]delta[+][0]).\n   apply plus_resp_less_leEq.\n    apply plus_resp_less_leEq.\n     eapply less_wdr.\n      2: apply cg_inv_inv.\n     apply inv_resp_less; eapply leEq_less_trans.\n      2: apply H0.\n     apply inv_leEq_AbsIR.\n    eapply leEq_transitive.\n     apply RS_delta_deltaR.\n    unfold deltaR in |- *; apply AntiMesh_lemma.\n   apply shift_leEq_minus; eapply leEq_wdl.\n    apply H3.\n   algebra.\n  apply shift_leEq_minus; astepl (R j' Hj').\n  eapply leEq_transitive.\n   apply H3.\n  apply less_leEq; apply less_transitive_unfolded with (R _ Hj[-]delta [/]TwoNZ).\n   apply shift_less_minus; apply shift_plus_less'.\n   apply less_leEq_trans with delta.\n    apply pos_div_two'; exact RS_delta_pos.\n   eapply leEq_transitive.\n    apply RS_delta_deltaR.\n   unfold deltaR in |- *; apply AntiMesh_lemma.\n  apply shift_minus_less; apply shift_less_plus'.\n  eapply leEq_less_trans.\n   2: apply H0.\n  eapply leEq_wdr.\n   2: apply AbsIR_minus.\n  apply leEq_AbsIR.\n apply local_mon_imp_mon'_le with (f := fun (i : nat) (Hi : i <= m) => R i Hi).\n   intros; apply HR.\n  red in |- *; intros; apply prf1; auto.\n auto with arith.\nQed.\n\nLet pred1 (j : nat) (Hj : j <= m) :=\n  forall Hi' : i <= n, AbsIR (P i Hi'[-]R j Hj)[<]delta [/]TwoNZ.\nLet pred2 (j : nat) (Hj : j <= m) :=\n  forall Hi' : i <= n, delta [/]FourNZ[<]AbsIR (P i Hi'[-]R j Hj).\n\nLemma sep__sep_aux_lemma :\n {j : nat | {Hj : j <= m | pred1 j Hj}}\n or (forall (j : nat) (Hj : j <= m), pred2 j Hj).\nProof.\n apply finite_or_elim.\n   red in |- *; unfold pred1 in |- *; do 3 intro.\n   rewrite H; intros H0 H' H1 Hi'.\n   eapply less_wdl.\n    apply H1 with (Hi' := Hi').\n   apply AbsIR_wd; apply cg_minus_wd; apply prf1; auto.\n  red in |- *; unfold pred2 in |- *; intros. rename X into H1.\n  eapply less_wdr.\n   apply H1 with (Hi' := Hi').\n  apply AbsIR_wd; apply cg_minus_wd; apply prf1; auto.\n intros j Hj.\n cut (pred2 j Hj or pred1 j Hj).\n  intro H; inversion_clear H; [ right | left ]; assumption.\n unfold pred1, pred2 in |- *.\n cut (forall Hi' : i <= n, delta [/]FourNZ[<]AbsIR (P i Hi'[-]R j Hj)\n   or AbsIR (P i Hi'[-]R j Hj)[<]delta [/]TwoNZ). intro H.\n  elim (le_lt_dec i n); intro.\n   elim (H a0); intro.\n    left; intro.\n    eapply less_wdr.\n     apply a1.\n    apply AbsIR_wd; apply cg_minus_wd; apply prf1; auto.\n   right; intro.\n   eapply less_wdl.\n    apply b0.\n   apply AbsIR_wd; apply cg_minus_wd; apply prf1; auto.\n  left; intro.\n  exfalso; apply le_not_lt with i n; auto.\n intros.\n apply less_cotransitive_unfolded.\n rstepl ((delta [/]TwoNZ) [/]TwoNZ).\n apply pos_div_two'; apply pos_div_two; apply RS_delta_pos.\nQed.\n\nHypothesis Hi0 : 0 < i.\nHypothesis Hin : i < n.\n\nDefinition sep__sep_fun_i : IR.\nProof.\n elim sep__sep_aux_lemma; intros.\n  2: apply (P i Hi).\n apply (P i Hi[+]delta [/]TwoNZ).\nDefined.\n\nLemma sep__sep_leEq : forall Hi' : i <= n, P i Hi'[<=]sep__sep_fun_i.\nProof.\n unfold sep__sep_fun_i in |- *.\n elim sep__sep_aux_lemma; intros; simpl in |- *.\n  2: apply eq_imp_leEq; apply prf1; auto.\n apply leEq_wdl with (P i Hi).\n  2: apply prf1; auto.\n apply shift_leEq_plus'; astepl ZeroR.\n astepr (delta [/]TwoNZ).\n apply less_leEq; apply pos_div_two; exact RS_delta_pos.\nQed.\n\nLemma sep__sep_less : forall Hi' : S i <= n, sep__sep_fun_i[<]P (S i) Hi'.\nProof.\n unfold sep__sep_fun_i in |- *.\n elim sep__sep_aux_lemma; intros; simpl in |- *.\n  2: apply HP.\n apply shift_plus_less'.\n apply less_leEq_trans with delta.\n  astepl (delta [/]TwoNZ).\n  apply pos_div_two'; exact RS_delta_pos.\n apply leEq_transitive with deltaP.\n  apply RS_delta_deltaP.\n unfold deltaP in |- *; apply AntiMesh_lemma.\nQed.\n\nLemma sep__sep_ap : forall (j : nat) (Hj : j <= m), sep__sep_fun_i[#]R j Hj.\nProof.\n intros.\n unfold sep__sep_fun_i in |- *; elim sep__sep_aux_lemma; intro; simpl in |- *.\n  2: apply zero_minus_apart; apply AbsIR_cancel_ap_zero; apply Greater_imp_ap.\n  elim a0; intros j' H.\n  elim H; clear a0 H; intros Hj' H.\n  unfold pred1 in H.\n  rstepr (P i Hi[+](R j Hj[-]P i Hi)).\n  apply op_lft_resp_ap.\n  apply un_op_strext_unfolded with AbsIR.\n  apply ap_wdl_unfolded with (delta [/]TwoNZ).\n   2: apply eq_symmetric_unfolded; apply AbsIR_eq_x.\n   2: apply less_leEq; apply pos_div_two; exact RS_delta_pos.\n  eapply ap_wdr_unfolded.\n   2: apply AbsIR_minus.\n  elim (le_lt_dec j j'); intro.\n   elim (le_lt_eq_dec _ _ a0); clear a0; intro.\n    apply less_imp_ap; apply separation_conseq with j' Hj'.\n     apply H.\n    intro; rewrite H0 in a0; apply (lt_irrefl _ a0).\n   apply Greater_imp_ap.\n   eapply less_wdl.\n    apply H with (Hi' := Hi).\n   apply AbsIR_wd.\n   apply cg_minus_wd.\n    algebra.\n   apply prf1; auto.\n  apply less_imp_ap; apply separation_conseq with j' Hj'.\n   apply H.\n  intro; rewrite H0 in b0; apply (lt_irrefl _ b0).\n unfold pred2 in b0.\n eapply less_transitive_unfolded.\n  2: apply b0.\n apply pos_div_four; exact RS_delta_pos.\nQed.\n\nEnd Defining_ai'.\n\nDefinition sep__sep_fun : forall i : nat, i <= n -> IR.\nProof.\n intros.\n elim (le_lt_dec i 0); intro.\n  apply a.\n elim (le_lt_eq_dec _ _ H); intro.\n  apply (sep__sep_fun_i i H).\n apply b.\nDefined.\n\nLemma sep__sep_fun_i_delta :\n forall (i : nat) (Hi Hi' : i <= n) (Hi0 : i < n),\n AbsIR (sep__sep_fun_i i Hi[-]P i Hi')[<=]delta [/]TwoNZ.\nProof.\n intros.\n unfold sep__sep_fun_i in |- *.\n elim (sep__sep_aux_lemma i); intro; simpl in |- *.\n  apply eq_imp_leEq.\n  eapply eq_transitive_unfolded.\n   2: apply AbsIR_eq_x.\n   apply AbsIR_wd.\n   rstepr (P i Hi'[+]delta [/]TwoNZ[-]P i Hi').\n   apply cg_minus_wd.\n    apply bin_op_wd_unfolded.\n     apply prf1; auto.\n    algebra.\n   algebra.\n  astepr (delta [/]TwoNZ); apply less_leEq; apply pos_div_two; exact RS_delta_pos.\n apply leEq_wdl with ZeroR.\n  astepr (delta [/]TwoNZ); apply less_leEq; apply pos_div_two; exact RS_delta_pos.\n eapply eq_transitive_unfolded.\n  apply eq_symmetric_unfolded; apply AbsIRz_isz.\n apply AbsIR_wd.\n astepl (P i Hi[-]P i Hi).\n apply cg_minus_wd; apply prf1; auto.\nQed.\n\nLemma sep__sep_fun_delta :\n forall (i : nat) (Hi Hi' : i <= n),\n AbsIR (sep__sep_fun i Hi[-]P i Hi')[<=]delta [/]TwoNZ.\nProof.\n intros.\n unfold sep__sep_fun in |- *.\n elim (le_lt_dec i 0); intro; simpl in |- *.\n  cut (i = 0); [ intro | auto with arith ].\n  generalize Hi'; rewrite H; intros.\n  apply leEq_wdl with ZeroR.\n   astepr (delta [/]TwoNZ); apply less_leEq; apply pos_div_two; exact RS_delta_pos.\n  eapply eq_transitive_unfolded.\n   apply eq_symmetric_unfolded; apply AbsIRz_isz.\n  apply AbsIR_wd.\n  astepl (a[-]a).\n  apply cg_minus_wd; [ algebra | apply eq_symmetric_unfolded; apply start ].\n elim (le_lt_eq_dec _ _ Hi); intro; simpl in |- *.\n  apply sep__sep_fun_i_delta; assumption.\n generalize Hi'; rewrite b1; intros.\n apply leEq_wdl with ZeroR.\n  astepr (delta [/]TwoNZ); apply less_leEq; apply pos_div_two; exact RS_delta_pos.\n eapply eq_transitive_unfolded.\n  apply eq_symmetric_unfolded; apply AbsIRz_isz.\n apply AbsIR_wd.\n astepl (b[-]b).\n apply cg_minus_wd; [ algebra | apply eq_symmetric_unfolded; apply finish ].\nQed.\n\nLemma sep__sep_mon_i :\n forall (i : nat) (Hi : i <= n) (Hi' : S i <= n) (Hi0 : i < n),\n sep__sep_fun_i i Hi[<]sep__sep_fun_i (S i) Hi'.\nProof.\n intros.\n apply less_leEq_trans with (P (S i) Hi0).\n  apply sep__sep_less.\n apply sep__sep_leEq.\nQed.\n\nLemma sep__sep_mon :\n forall (i : nat) (Hi : i <= n) (Hi' : S i <= n),\n sep__sep_fun i Hi[<]sep__sep_fun (S i) Hi'.\nProof.\n intros.\n unfold sep__sep_fun in |- *.\n elim (le_lt_dec (S i) 0); intro; simpl in |- *.\n  exfalso; apply (le_Sn_O _ a0).\n elim (le_lt_dec i 0); intro; simpl in |- *.\n  elim (le_lt_eq_dec _ _ Hi'); intro; simpl in |- *.\n   apply less_leEq_trans with (P (S i) Hi').\n    apply leEq_less_trans with (P i Hi).\n     elim (Partition_in_compact _ _ _ _ P i Hi); intros; auto.\n    apply HP.\n   apply sep__sep_leEq.\n  assumption.\n elim (le_lt_eq_dec _ _ Hi); intro; simpl in |- *.\n  elim (le_lt_eq_dec _ _ Hi'); intro; simpl in |- *.\n   apply sep__sep_mon_i; assumption.\n  eapply less_wdr.\n   2: apply finish with (p := P) (H := le_n n).\n  eapply less_wdr.\n   apply sep__sep_less with (Hi' := Hi').\n  generalize Hi'; rewrite b2.\n  intro; apply prf1; auto.\n exfalso; rewrite b2 in Hi'; apply (le_Sn_n _ Hi').\nQed.\n\nLemma sep__sep_fun_i_wd :\n forall i j : nat,\n i = j ->\n forall (Hi : i <= n) (Hj : j <= n),\n sep__sep_fun_i i Hi[=]sep__sep_fun_i j Hj.\nProof.\n do 3 intro.\n rewrite <- H.\n intros.\n unfold sep__sep_fun_i in |- *.\n elim (sep__sep_aux_lemma i); intros; simpl in |- *.\n  apply bin_op_wd_unfolded; [ apply prf1; auto | algebra ].\n apply prf1; auto.\nQed.\n\nLemma sep__sep_fun_wd :\n forall i j : nat,\n i = j ->\n forall (Hi : i <= n) (Hj : j <= n), sep__sep_fun i Hi[=]sep__sep_fun j Hj.\nProof.\n intros.\n unfold sep__sep_fun in |- *.\n elim (le_lt_dec i 0); elim (le_lt_dec j 0); intros; simpl in |- *.\n    algebra.\n   exfalso; apply (lt_irrefl 0); apply lt_le_trans with j; auto; rewrite <- H; auto.\n  exfalso; apply (lt_irrefl 0); apply lt_le_trans with j; auto; rewrite <- H; auto.\n elim (le_lt_eq_dec _ _ Hi); elim (le_lt_eq_dec _ _ Hj); intros; simpl in |- *.\n    apply sep__sep_fun_i_wd; auto.\n   exfalso; rewrite H in a0; rewrite b2 in a0; apply (lt_irrefl _ a0).\n  exfalso; rewrite <- H in a0; rewrite b2 in a0; apply (lt_irrefl _ a0).\n algebra.\nQed.\n\nDefinition sep__sep_part : Partition Hab n.\nProof.\n apply Build_Partition with sep__sep_fun.\n    exact sep__sep_fun_wd.\n   intros; apply less_leEq; apply sep__sep_mon.\n  intros; unfold sep__sep_fun in |- *.\n  elim (le_lt_dec 0 0); intro; simpl in |- *.\n   algebra.\n  exfalso; inversion b0.\n intros; unfold sep__sep_fun in |- *.\n elim (le_lt_dec n 0); intro; simpl in |- *.\n  apply partition_length_zero with Hab.\n  cut (n = 0); [ intro | auto with arith ].\n  rewrite <- H0; apply P.\n elim (le_lt_eq_dec _ _ H); intro; simpl in |- *.\n  exfalso; apply (lt_irrefl _ a0).\n algebra.\nDefined.\n\nLemma sep__sep_lemma : Separated sep__sep_part R.\nProof.\n repeat split; unfold _Separated in |- *; intros.\n   apply sep__sep_mon.\n  apply HR.\n unfold sep__sep_part in |- *; simpl in |- *.\n unfold sep__sep_fun in |- *; simpl in |- *.\n elim (le_lt_dec i 0); intro; simpl in |- *.\n  exfalso; apply lt_irrefl with 0; apply lt_le_trans with i; auto.\n elim (le_lt_eq_dec _ _ Hi); intro; simpl in |- *.\n  apply sep__sep_ap.\n exfalso; rewrite b1 in H1; apply (lt_irrefl _ H1).\nQed.\n\nVariable g : forall i : nat, i < n -> IR.\nHypothesis gP : Points_in_Partition P g.\n\nDefinition sep__sep_points (i : nat) (Hi : i < n) : IR.\nProof.\n intros.\n apply (Max (sep__sep_fun_i i (lt_le_weak _ _ Hi)) (g i Hi)).\nDefined.\n\nLemma sep__sep_points_lemma :\n Points_in_Partition sep__sep_part sep__sep_points.\nProof.\n red in |- *; intros.\n split.\n  unfold sep__sep_part in |- *; simpl in |- *.\n  unfold sep__sep_fun, sep__sep_points in |- *.\n  elim (le_lt_dec i 0); intro; simpl in |- *.\n   apply leEq_transitive with (g i Hi).\n    elim (Pts_part_lemma _ _ _ _ _ _ gP i Hi); intros; assumption.\n   apply rht_leEq_Max.\n  elim (le_lt_eq_dec _ _ (lt_le_weak _ _ Hi)); intro; simpl in |- *.\n   eapply leEq_wdl.\n    apply lft_leEq_Max.\n   apply sep__sep_fun_i_wd; auto.\n  exfalso; rewrite b1 in Hi; apply (lt_irrefl _ Hi).\n unfold sep__sep_part in |- *; simpl in |- *.\n unfold sep__sep_fun, sep__sep_points in |- *.\n elim (le_lt_dec (S i) 0); intro; simpl in |- *.\n  exfalso; inversion a0.\n elim (le_lt_eq_dec _ _ Hi); intro; simpl in |- *.\n  apply Max_leEq.\n   apply less_leEq; apply sep__sep_mon_i; assumption.\n  apply leEq_transitive with (P (S i) Hi).\n   elim (gP i Hi); intros; auto.\n  apply sep__sep_leEq.\n apply Max_leEq.\n  unfold sep__sep_fun_i in |- *.\n  elim (sep__sep_aux_lemma i); intro; simpl in |- *.\n   apply leEq_transitive with (P (S i) Hi).\n    apply shift_plus_leEq'.\n    apply leEq_transitive with delta.\n     astepl (delta [/]TwoNZ); apply less_leEq; apply pos_div_two'; exact RS_delta_pos.\n    apply leEq_transitive with deltaP.\n     apply RS_delta_deltaP.\n    unfold deltaP in |- *; apply AntiMesh_lemma.\n   elim (Partition_in_compact _ _ _ _ P (S i) Hi); intros; assumption.\n  elim (Partition_in_compact _ _ _ _ P i (lt_le_weak _ _ Hi)); intros; assumption.\n elim (Pts_part_lemma _ _ _ _ _ _ gP i Hi); intros; assumption.\nQed.\n\nLemma sep__sep_aux :\n  forall (i : nat) (H : i < n) Hg Hs,\n  AbsIR (F (g i H) Hg[-]F (sep__sep_points i H) Hs)[<=]e.\nProof.\n intros.\n apply RS_Hd'.\n   unfold I in |- *; apply Pts_part_lemma with n P; assumption.\n  unfold I in |- *; apply Pts_part_lemma with n sep__sep_part; apply sep__sep_points_lemma.\n unfold sep__sep_points in |- *; simpl in |- *.\n eapply leEq_wdl.\n  2: apply AbsIR_minus.\n eapply leEq_wdl.\n  2: apply eq_symmetric_unfolded; apply AbsIR_eq_x.\n  apply shift_minus_leEq; apply Max_leEq.\n   unfold sep__sep_fun_i in |- *.\n   elim sep__sep_aux_lemma; intro; simpl in |- *.\n    apply leEq_transitive with (P i (lt_le_weak _ _ H)[+]delta).\n     apply plus_resp_leEq_lft.\n     apply less_leEq; astepl (delta [/]TwoNZ); apply pos_div_two'; exact RS_delta_pos.\n    eapply leEq_wdr.\n     2: apply cag_commutes_unfolded.\n    apply plus_resp_leEq_both.\n     elim (gP i H); intros; assumption.\n    apply RS_delta_d.\n   astepl ([0][+]P i (lt_le_weak _ _ H)).\n   apply plus_resp_leEq_both.\n    apply less_leEq; exact RS_Hd.\n   elim (gP i H); intros; auto.\n  apply shift_leEq_plus; astepl ZeroR; apply less_leEq; exact RS_Hd.\n apply shift_leEq_minus.\n eapply leEq_wdl.\n  apply rht_leEq_Max.\n algebra.\nQed.\n\nNotation just1 := (incF _ (Pts_part_lemma _ _ _ _ _ _ gP _ _)).\nNotation just2 :=\n  (incF _ (Pts_part_lemma _ _ _ _ _ _ sep__sep_points_lemma _ _)).\n\nLemma sep__sep_Sum :\n AbsIR (Partition_Sum gP incF[-]Partition_Sum sep__sep_points_lemma incF)[<=]\n alpha.\nProof.\n unfold Partition_Sum in |- *; simpl in |- *.\n rstepr (alpha [/]TwoNZ[+]alpha [/]TwoNZ).\n apply leEq_transitive with (e[*](b[-]a)[+]nring n[*]M[*]delta).\n  apply leEq_wdr with (e[*] Sumx (fun (i : nat) (Hi : i < n) => P _ Hi[-]P _ (lt_le_weak _ _ Hi))[+]\n    Sumx (fun (i : nat) (Hi : i < n) => M[*]delta)).\n   apply leEq_transitive with (Sumx (fun (i : nat) (Hi : i < n) =>\n     AbsIR (F (g i Hi) just1[-]F (sep__sep_points i Hi) just2)[*] (P _ Hi[-]P _ (lt_le_weak _ _ Hi)))[+]\n       Sumx (fun (i : nat) (Hi : i < n) => AbsIR (F (sep__sep_points i Hi) just2)[*]\n         (AbsIR (sep__sep_fun _ Hi[-]P _ Hi)[+]\n           AbsIR (P _ (lt_le_weak _ _ Hi)[-]sep__sep_fun _ (lt_le_weak _ _ Hi))))).\n    apply leEq_transitive with (AbsIR (Sumx (fun (i : nat) (Hi : i < n) =>\n      F (g i Hi) just1[*](P _ Hi[-]P _ (lt_le_weak _ _ Hi))[-] F (sep__sep_points i Hi) just2[*]\n        (P _ Hi[-]P _ (lt_le_weak _ _ Hi))))[+] AbsIR (Sumx (fun (i : nat) (Hi : i < n) =>\n          F (sep__sep_points i Hi) just2[*] (sep__sep_fun _ Hi[-]P _ Hi[+]\n            (P _ (lt_le_weak _ _ Hi)[-]sep__sep_fun _ (lt_le_weak _ _ Hi)))))).\n     eapply leEq_wdl.\n      apply triangle_IR_minus.\n     apply eq_symmetric_unfolded.\n     apply AbsIR_wd.\n     eapply eq_transitive_unfolded.\n      apply Sumx_minus_Sumx.\n     eapply eq_transitive_unfolded.\n      2: apply eq_symmetric_unfolded; apply Sumx_minus_Sumx.\n     apply Sumx_wd; intros.\n     astepl (F (g i H) just1[*](P _ H[-]P _ (lt_le_weak _ _ H))[-] F (sep__sep_points i H) just2[*]\n       (sep__sep_fun _ H[-]sep__sep_fun _ (lt_le_weak _ _ H))).\n     rational.\n    apply plus_resp_leEq_both.\n     eapply leEq_wdr.\n      apply triangle_SumxIR.\n     apply Sumx_wd; intros.\n     apply eq_transitive_unfolded with (AbsIR (F (g i H) just1[-]F (sep__sep_points i H) just2)[*]\n       AbsIR (P _ H[-]P _ (lt_le_weak _ _ H))).\n      eapply eq_transitive_unfolded.\n       2: apply AbsIR_resp_mult.\n      apply AbsIR_wd; algebra.\n     apply mult_wdr.\n     apply AbsIR_eq_x.\n     apply shift_leEq_minus; astepl (P i (lt_le_weak _ _ H)); apply prf2.\n    eapply leEq_transitive.\n     apply triangle_SumxIR.\n    apply Sumx_resp_leEq; intros.\n    eapply leEq_wdl.\n     2: apply eq_symmetric_unfolded; apply AbsIR_resp_mult.\n    apply mult_resp_leEq_lft.\n     apply triangle_IR.\n    apply AbsIR_nonneg.\n   apply plus_resp_leEq_both.\n    eapply leEq_wdr.\n     2: apply Sumx_comm_scal'.\n    apply Sumx_resp_leEq; intros.\n    apply mult_resp_leEq_rht.\n     apply sep__sep_aux.\n    apply shift_leEq_minus; astepl (P i (lt_le_weak _ _ H)); apply prf2.\n   apply Sumx_resp_leEq; intros.\n   apply mult_resp_leEq_both.\n      apply AbsIR_nonneg.\n     astepl (ZeroR[+][0]); apply plus_resp_leEq_both; apply AbsIR_nonneg.\n    unfold I, M in |- *; apply norm_bnd_AbsIR.\n    apply Pts_part_lemma with n sep__sep_part; apply sep__sep_points_lemma.\n   rstepr (delta [/]TwoNZ[+]delta [/]TwoNZ).\n   apply plus_resp_leEq_both.\n    apply sep__sep_fun_delta.\n   eapply leEq_wdl.\n    2: apply AbsIR_minus.\n   apply sep__sep_fun_delta.\n  apply bin_op_wd_unfolded.\n   apply mult_wdr.\n   eapply eq_transitive_unfolded.\n    apply Mengolli_Sum with (f := fun (i : nat) (Hi : i <= n) => P i Hi).\n     red in |- *; intros; apply prf1; auto.\n    intros; algebra.\n   apply cg_minus_wd.\n    apply finish.\n   apply start.\n  astepr (nring n[*](M[*]delta)); apply sumx_const.\n apply plus_resp_leEq_both.\n  unfold e in |- *.\n  apply leEq_wdl with (alpha [/]TwoNZ[*](b[-]a[/] _[//]max_one_ap_zero (b[-]a))).\n   rstepr (alpha [/]TwoNZ[*][1]).\n   apply mult_resp_leEq_lft.\n    apply shift_div_leEq.\n     apply pos_max_one.\n    astepr (Max (b[-]a) [1]); apply lft_leEq_Max.\n   apply less_leEq; apply pos_div_two; assumption.\n  simpl in |- *; rational.\n apply leEq_transitive with (Max (nring n[*]M) [1][*]delta).\n  apply mult_resp_leEq_rht.\n   apply lft_leEq_Max.\n  apply less_leEq; apply RS_delta_pos.\n apply shift_mult_leEq' with (max_one_ap_zero (nring n[*]M)).\n  apply pos_max_one.\n unfold delta in |- *.\n eapply leEq_transitive.\n  apply Min_leEq_rht.\n apply Min_leEq_lft.\nQed.\n\nLemma sep__sep_Mesh : Mesh sep__sep_part[<=]Mesh P[+]csi.\nProof.\n unfold Mesh in |- *.\n apply maxlist_leEq.\n  apply length_Part_Mesh_List.\n  exact RS_pos_n.\n intros x H.\n elim (Part_Mesh_List_lemma _ _ _ _ _ _ H); intros i Hi.\n elim Hi; clear Hi; intros Hi Hi'.\n elim Hi'; clear Hi'; intros Hi' Hx.\n eapply leEq_wdl.\n  2: apply eq_symmetric_unfolded; apply Hx.\n unfold sep__sep_part in |- *; simpl in |- *.\n unfold sep__sep_fun in |- *; simpl in |- *.\n elim (le_lt_dec (S i) 0); intro; simpl in |- *.\n  exfalso; inversion a0.\n elim (le_lt_eq_dec _ _ Hi'); intro; simpl in |- *.\n  elim (le_lt_dec i 0); intro; simpl in |- *.\n   cut (i = 0); [ intro | auto with arith ].\n   unfold sep__sep_fun_i in |- *; simpl in |- *.\n   elim (sep__sep_aux_lemma (S i)); intro; simpl in |- *.\n    generalize Hi'; rewrite H0; clear Hx Hi'; intro.\n    apply leEq_wdl with (P 1 Hi'[+]delta [/]TwoNZ[-]P 0 (le_O_n _)).\n     rstepl (P 1 Hi'[-]P 0 (le_O_n _)[+]delta [/]TwoNZ).\n     apply plus_resp_leEq_both.\n      fold (Mesh P) in |- *; apply Mesh_lemma.\n     apply leEq_transitive with delta.\n      apply less_leEq; apply pos_div_two'; exact RS_delta_pos.\n     apply RS_delta_csi.\n    apply cg_minus_wd; [ algebra | apply start ].\n   generalize Hi'; rewrite H0; clear Hx Hi'; intro.\n   apply leEq_wdl with (P 1 Hi'[-]P 0 (le_O_n _)).\n    fold (Mesh P) in |- *; apply leEq_transitive with (Mesh P[+][0]).\n     astepr (Mesh P); apply Mesh_lemma.\n    apply plus_resp_leEq_lft.\n    apply less_leEq; assumption.\n   apply cg_minus_wd; [ algebra | apply start ].\n  elim (le_lt_eq_dec _ _ Hi); intro; simpl in |- *.\n   unfold sep__sep_fun_i in |- *.\n   elim (sep__sep_aux_lemma (S i)); elim (sep__sep_aux_lemma i); intros; simpl in |- *.\n      rstepl (P (S i) Hi'[-]P i Hi).\n      fold (Mesh P) in |- *; apply leEq_transitive with (Mesh P[+][0]).\n       astepr (Mesh P); apply Mesh_lemma.\n      apply plus_resp_leEq_lft.\n      apply less_leEq; assumption.\n     rstepl (P _ Hi'[-]P _ Hi[+]delta [/]TwoNZ).\n     apply plus_resp_leEq_both.\n      fold (Mesh P) in |- *; apply Mesh_lemma.\n     apply leEq_transitive with delta.\n      apply less_leEq; apply pos_div_two'; exact RS_delta_pos.\n     apply RS_delta_csi.\n    rstepl (P _ Hi'[-]P _ Hi[-]delta [/]TwoNZ).\n    unfold cg_minus at 1 in |- *; apply plus_resp_leEq_both.\n     fold (Mesh P) in |- *; apply Mesh_lemma.\n    apply leEq_transitive with ZeroR.\n     astepr ([--]ZeroR); apply inv_resp_leEq.\n     apply less_leEq; apply pos_div_two; exact RS_delta_pos.\n    apply leEq_transitive with delta.\n     apply less_leEq; exact RS_delta_pos.\n    apply RS_delta_csi.\n   fold (Mesh P) in |- *; apply leEq_transitive with (Mesh P[+][0]).\n    astepr (Mesh P); apply Mesh_lemma.\n   apply plus_resp_leEq_lft.\n   apply less_leEq; assumption.\n  exfalso; rewrite b2 in a0; apply lt_irrefl with (S n);\n    apply lt_trans with (S n); auto with arith.\n elim (le_lt_dec i 0); intro; simpl in |- *.\n  cut (i = 0); [ intro | auto with arith ].\n  rewrite H0 in b1.\n  clear Hx; rewrite H0 in Hi'.\n  apply leEq_wdl with (P 1 Hi'[-]P 0 (le_O_n n)).\n   fold (Mesh P) in |- *; apply leEq_transitive with (Mesh P[+][0]).\n    astepr (Mesh P); apply Mesh_lemma.\n   apply plus_resp_leEq_lft.\n   apply less_leEq; assumption.\n  apply cg_minus_wd.\n   generalize Hi'; rewrite b1; intro; apply finish.\n  apply start.\n elim (le_lt_eq_dec _ _ Hi); intro; simpl in |- *.\n  unfold sep__sep_fun_i in |- *.\n  elim (sep__sep_aux_lemma i); intro; simpl in |- *.\n   apply leEq_wdl with (P (S i) Hi'[-](P i Hi[+]delta [/]TwoNZ)).\n    rstepl (P (S i) Hi'[-]P i Hi[-]delta [/]TwoNZ).\n    unfold cg_minus at 1 in |- *; apply plus_resp_leEq_both.\n     fold (Mesh P) in |- *; apply Mesh_lemma.\n    apply leEq_transitive with ZeroR.\n     astepr ([--]ZeroR); apply inv_resp_leEq.\n     apply less_leEq; apply pos_div_two; exact RS_delta_pos.\n    apply leEq_transitive with delta.\n     apply less_leEq; exact RS_delta_pos.\n    apply RS_delta_csi.\n   apply cg_minus_wd.\n    generalize Hi'; rewrite b1; intro; apply finish.\n   algebra.\n  apply leEq_wdl with (P (S i) Hi'[-]P i Hi).\n   fold (Mesh P) in |- *; apply leEq_transitive with (Mesh P[+][0]).\n    astepr (Mesh P); apply Mesh_lemma.\n   apply plus_resp_leEq_lft.\n   apply less_leEq; assumption.\n  apply cg_minus_wd.\n   generalize Hi'; rewrite b1; intro; apply finish.\n  algebra.\n exfalso; rewrite b3 in b1; apply n_Sn with n; auto.\nQed.\n\nEnd Separating__Separated.\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/ftc/RefSeparated.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.29776811902630584}}
{"text": "Set Bullet Behavior \"Strict Subproofs\".\nSet Implicit Arguments.\n\nRequire Import FcEtt.imports.\n\nRequire Export FcEtt.ett_inf.\nRequire Export FcEtt.ett_ind.\nRequire Import FcEtt.tactics.\n\nRequire Import FcEtt.utils.\nRequire Import FcEtt.toplevel.\n\n(* This file contains these results:\n\n   -- the context is well-formed in any judgement\n   -- all components are locally closed in any judgement\n  *)\n\n\n(* -------------------------------- *)\n\nLemma ctx_wff_mutual :\n  (forall G0 a A, Typing G0 a A -> Ctx G0) /\\\n  (forall G0 phi,   PropWff G0 phi -> Ctx G0) /\\\n  (forall G0 D p1 p2, Iso G0 D p1 p2 -> Ctx G0) /\\\n  (forall G0 D A B T R,   DefEq G0 D A B T R -> Ctx G0) /\\\n  (forall G0, Ctx G0 -> True).\nProof.\n  eapply typing_wff_iso_defeq_mutual; auto.\nQed.\n\nDefinition Typing_Ctx := first ctx_wff_mutual.\nDefinition PropWff_Ctx := second ctx_wff_mutual. \nDefinition Iso_Ctx := third ctx_wff_mutual.\nDefinition DefEq_Ctx := fourth ctx_wff_mutual.\n\n\nHint Resolve Typing_Ctx PropWff_Ctx Iso_Ctx DefEq_Ctx.\n\nFixpoint ctx_nom (G : context) := match G with\n  | nil => nil\n  | (x, Tm _) :: G' => (x, Nom) :: ctx_nom G'\n  | (x, Co _) :: G' => ctx_nom G'\n  end.\n\nLemma Ctx_uniq : forall G, Ctx G -> uniq G.\n  induction G; try auto.\n  inversion 1; subst; solve_uniq.\nQed.\n\nLemma dom_rctx_le_ctx : forall G, dom (ctx_nom G) [<=] dom G.\nProof. intros; induction G; simpl. fsetdec.\n       destruct a, s. simpl. fsetdec. fsetdec.\nQed.\n\nLemma notin_ctx_rctx : forall x G, x `notin` (dom G) -> x `notin` dom (ctx_nom G).\nProof. intros. induction G. auto. destruct a, s; simpl in *.\n       all : pose (P := H); apply notin_add_2 in P; fsetdec.\nQed.\n\nLemma ctx_to_rctx_uniq : forall G, Ctx G -> uniq (ctx_nom G).\nProof. intros G. induction G; intros.\n        - simpl; auto.\n        - inversion H; subst; simpl. apply Ctx_uniq in H.\n          apply IHG in H2. econstructor; eauto. \n          assert (P : dom (ctx_nom G) [<=] dom G). \n          { apply dom_rctx_le_ctx. } fsetdec.\n          inversion H. apply IHG; auto.\nQed.\n\nLemma ctx_to_rctx_binds_tm : forall G x A, binds x (Tm A) G ->\n                                             binds x Nom (ctx_nom G).\nProof. intros G. induction G; intros; simpl; eauto.\n       destruct a, s. apply binds_cons_1 in H. inversion H; eauto.\n       inversion H0. inversion H2. subst. auto.\n       apply binds_cons_1 in H. inversion H. inversion H0. inversion H2.\n       eauto.\nQed.\n\nHint Resolve Ctx_uniq.\n\n(* ------------------------------------------------------------------------ *)\n\n\nLemma RolePath_lc : forall a R, RolePath a R -> lc_tm a.\nProof. intros. induction H; eauto.\nQed.\n\nLemma ValuePath_lc : forall F a, ValuePath a F -> lc_tm a.\nProof. intros. induction H; eauto.\nQed.\n\nLemma CasePath_lc : forall F a R, CasePath R a F -> lc_tm a.\nProof. intros. induction H; eauto using ValuePath_lc. \nQed.\n\nLemma PatternContexts_lc2 : forall W G D F p A B, PatternContexts W G D F A p B -> lc_tm p.\nProof. intros. induction H; eauto.\nQed.\n\nLemma Rename_lc2 : forall p b p' b' D D', Rename p b p' b' D D' -> lc_tm b.\nProof. induction 1; eauto. Qed.\n\nLemma Rename_lc4 : forall p b p' b' D D', Rename p b p' b' D D' -> lc_tm b'.\nProof. induction 1; eauto using tm_subst_tm_tm_lc_tm. Qed.\n\nLemma roleing_lc : (forall W a R, roleing W a R -> lc_tm a).\nProof. induction 1; eauto. Qed.\n\n\nLemma Value_lc : forall R a, Value R a -> lc_tm a.\nProof. intros. induction H; eauto using CasePath_lc. \nQed.\n\nHint Resolve PatternContexts_lc2 roleing_lc Value_lc : lc.\n\n\nLemma MatchSubst_lc1 : forall a p b b', MatchSubst a p b b' →  lc_tm a.\nProof.\n  induction 1; auto.\nQed.\n\nLemma MatchSubst_lc2 : forall a p b b', MatchSubst a p b b' →  lc_tm p.\nProof.\n  induction 1; auto.\nQed.\n\nLemma MatchSubst_lc3 : forall a p b b', MatchSubst a p b b' →  lc_tm b.\nProof.\n  induction 1; auto.\nQed.\n\nLemma MatchSubst_lc4 : forall a p b b', MatchSubst a p b b' →  lc_tm b'.\nProof.\n  induction 1;\n    eauto using tm_subst_tm_tm_lc_tm, co_subst_co_tm_lc_tm.\nQed.\n\n\n\n\nLemma ApplyArgs_lc1 : forall a b1 b1',  ApplyArgs a b1 b1' -> lc_tm a.\nProof.\n  intros. induction H; auto.\nQed.\nLemma ApplyArgs_lc2 : forall a b1 b1',  ApplyArgs a b1 b1' -> lc_tm b1.\nProof.\n  intros. induction H; auto.\nQed.\nLemma ApplyArgs_lc3 : forall a b1 b1',  ApplyArgs a b1 b1' -> lc_tm b1'.\nProof.\n  intros. induction H; auto.\nQed.\n\n\nLemma Par_lc1 : forall W a a' R, Par W a a' R → lc_tm a.\nProof. induction 1; eauto using roleing_lc, MatchSubst_lc1.\nQed.\n\n\nLemma Par_lc2 : forall W a a' R, Par W a a' R → lc_tm a'.\nProof.\n  intros. induction H; eauto. \n  all: try with binds do ltac:(fun h =>\n     apply toplevel_inversion in h; inversion h; autofwd).\n\n  all: try solve [eauto 2 using roleing_lc, MatchSubst_lc4].\n  all: try solve [lc_solve]. \n  econstructor; eauto using ApplyArgs_lc3.\nQed.\n\nHint Resolve MatchSubst_lc1 MatchSubst_lc4 ApplyArgs_lc2 ApplyArgs_lc3 Par_lc1 Par_lc2 : lc.\n\n\n\n\nLemma lc_mutual :\n  (forall G0 a A, Typing G0 a A -> lc_tm a /\\ lc_tm A) /\\\n  (forall G0 phi , PropWff G0 phi -> lc_constraint phi) /\\\n  (forall G0 D p1 p2,  Iso G0 D p1 p2 -> lc_constraint p1 /\\ lc_constraint p2) /\\\n  (forall G0 D A B T R, DefEq G0 D A B T R -> lc_tm A /\\ lc_tm B /\\ lc_tm T) /\\\n  (forall G0, Ctx G0 -> forall x s , binds x s G0 -> lc_sort s).\nProof.\n  eapply typing_wff_iso_defeq_mutual.\n  all: TacticsInternals.pre; basic_solve_n 2.\n  all: split_hyp.\n  all: lc_solve.\nQed.\n\nDefinition Typing_lc  := first lc_mutual.\nDefinition PropWff_lc := second lc_mutual.\nDefinition Iso_lc     := third lc_mutual.\nDefinition DefEq_lc   := fourth lc_mutual.\nDefinition Ctx_lc     := fifth lc_mutual.\n\nLemma Typing_lc1 : forall G0 a A, Typing G0 a A -> lc_tm a.\nProof.\n  intros. apply (first lc_mutual) in H. destruct H. auto.\nQed.\nLemma Typing_lc2 : forall G0 a A, Typing G0 a A -> lc_tm A.\nProof.\n  intros. apply (first lc_mutual) in H. destruct H. auto.\nQed.\n\nLemma Iso_lc1 : forall G0 D p1 p2 , Iso G0 D p1 p2  -> lc_constraint p1.\nProof.\n  intros. apply (third lc_mutual) in H. destruct H. auto.\nQed.\nLemma Iso_lc2 : forall G0 D p1 p2 , Iso G0 D p1 p2 -> lc_constraint p2.\nProof.\n  intros. apply (third lc_mutual) in H. destruct H. auto.\nQed.\nLemma DefEq_lc1 : forall G0 D A B T R,   DefEq G0 D A B T R -> lc_tm A.\nProof.\n  intros. apply (fourth lc_mutual) in H. destruct H. auto.\nQed.\n\nLemma DefEq_lc2 : forall G0 D A B T R,   DefEq G0 D A B T R -> lc_tm B.\nProof.\n  intros. apply (fourth lc_mutual) in H. split_hyp. auto.\nQed.\nLemma DefEq_lc3 : forall G0 D A B T R,   DefEq G0 D A B T R -> lc_tm T.\nProof.\n  intros. apply (fourth lc_mutual) in H. split_hyp. auto.\nQed.\n\nHint Resolve Typing_lc1 Typing_lc2 Iso_lc1 Iso_lc2 DefEq_lc1 DefEq_lc2 DefEq_lc3 Ctx_lc : lc.\n\nLemma Toplevel_lc : forall c s, binds c s toplevel -> lc_sig_sort s.\nProof. induction Sig_toplevel.\n       - intros. inversion H.\n       - intros. destruct H1. inversion H1. subst.\n         simpl in H0. eauto. eauto with lc.\n         eauto.\n       - intros.\n         with binds do fun h => destruct (binds_cons_1  _ _ _ _ _ _ h); basic_solve.\n         autofwd.\n         subst. econstructor. all: eauto 3 with lc.\n         all: eauto using PatternContexts_lc2, roleing_lc, Typing_lc1.\nQed.\n\nLemma AppsPath_lc : forall R a F Apps,  AppsPath R a F Apps -> lc_tm a.\nProof.\n  intros; induction H; auto.\nQed.\n\n\nHint Resolve AppsPath_lc.\n\n  \nLemma Beta_lc1 : forall a a' R, Beta a a' R -> lc_tm a.\nProof.\n  intros.  induction H; auto.\n  all: try with AxiomUnfold do ltac:(fun h => inversion h; subst).\n  - eapply Value_lc in H0. eauto. \n  - eauto 2 with lc.\n  - constructor; eauto 3 with lc.\n  - lc_solve.\n  Unshelve.\n  all: auto.\nQed.\n\nLemma Beta_lc2 : forall a a' R, Beta a a' R -> lc_tm a'.\nProof.\n  intros.  induction H; auto.\n  all: try with AxiomUnfold do ltac:(fun h => inversion h; subst; eauto).\n  - apply Value_lc in H0. inversion H0.\n    apply lc_body_tm_wrt_tm; auto.\n  - inversion H. apply lc_body_tm_wrt_co; auto.\n  - with binds do ltac:(fun h => apply Toplevel_lc in h; inversion h).\n    subst.\n    eauto 2 with lc.\n  - lc_solve.\nQed.\n\nLemma reduction_in_one_lc : forall a a' R, reduction_in_one a a' R -> lc_tm a -> lc_tm a'.\nProof.\n   induction 1; intros; try (eapply Beta_lc2; eauto 1; fail).\n   lc_solve.\n   lc_solve.\n   lc_solve.\n   inversion H2. econstructor; eauto 2.\nQed.\n\nLemma axiom_body_lc : forall F p b A R Rs, binds F (Ax p b A R Rs) toplevel ->\n      lc_tm b.\nProof. intros. apply toplevel_inversion in H.\n       autofwd.\n       lc_solve.\nQed.\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_wf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.29776811152754046}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import fastpile.\nRequire Import spec_stdlib.\n\nRecord FastpileConcreteAPD:= {\n  countrep: Z -> val -> mpred;\n  countrep_local_facts: forall s p, countrep s p |-- !! isptr p;\n  countrep_valid_pointer: forall s p, countrep s p |-- valid_pointer p;\n  count_freeable: val -> mpred\n}.\n#[export] Hint Resolve countrep_local_facts : saturate_local.\n#[export] Hint Resolve countrep_valid_pointer : valid_pointer.\n\nDefinition tpile := Tstruct _pile noattr.\n\nLocal Open Scope assert.\n\nSection FastpileConcASI.\nVariable M: MallocFreeAPD.\nVariable FCP: FastpileConcreteAPD.\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(countrep FCP 0 p; count_freeable FCP p; mem_mgr M 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 FCP s p; mem_mgr M gv)\n POST[ tvoid ]\n    PROP() LOCAL()\n    SEP(countrep FCP (n+s) p; mem_mgr M 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 FCP 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 FCP 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 FCP s p; count_freeable FCP p; mem_mgr M gv)\n POST[ tvoid ]\n    PROP() LOCAL() SEP(mem_mgr M gv).\n\nDefinition FastpileConcreteASI:funspecs := [ Pile_new_spec; Pile_add_spec; Pile_count_spec; Pile_free_spec].\n\nEnd FastpileConcASI.\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/VSUpile/fast/spec_fastpile_concrete.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.2977681115275404}}
{"text": "(** * Equidistribution theorems for cotrees, itrees, CF trees, and cpGCL. *)\n\nSet Implicit Arguments.\nSet Contextual Implicit.\n\nFrom Coq Require Import\n  Basics\n  List\n  Morphisms\n  Equality\n  Lia\n.\n\nImport ListNotations.\nLocal Open Scope program_scope.\n\nFrom ITree Require Import\n  ITree ITreeFacts.\nImport ITreeNotations.\nLocal Open Scope itree_scope.\n\nFrom Paco Require Import paco.\n\nFrom algco Require Import\n  aCPO\n  axioms\n  cocwp\n  cocwp_facts\n  colist\n  cotree\n  cpo\n  misc\n  mu\n  order\n  prod\n  eR\n  (* set *)\n  tactics\n.\n\nLocal Open Scope eR_scope.\nLocal Open Scope order_scope.\n(* Local Open Scope set_scope. *)\n\nInductive is_stream_prefix {A} : list A -> colist A -> Prop :=\n| is_stream_prefix_nil : forall s, is_stream_prefix [] s\n| is_stream_prefix_cons : forall x l s,\n    is_stream_prefix l s ->\n    is_stream_prefix (x :: l) (cocons x s).\n\nLemma is_stream_prefix_consistent_pair {A} (a b : list A) (l : colist A) :\n  is_stream_prefix a l ->\n  is_stream_prefix b l ->\n  list_le a b \\/ list_le b a.\nProof.\n  revert b l; induction a; simpl; intros b l Ha Hb.\n  { left; constructor. }\n  inv Ha; inv Hb.\n  { right; constructor. }\n  eapply IHa in H1; eauto.\n  destruct H1 as [H|H].\n  - left; constructor; auto.\n  - right; constructor; auto.\nQed.\n\n(* Definition bitstring_set (l : list bool) : set (colist bool) := *)\n(*   is_stream_prefix l. *)\n\n(* #[global] *)\n(*   Instance ToSet_bitstring : ToSet (list bool) (colist bool) := *)\n(*   { to_set := bitstring_set }. *)\n\nDefinition bitstring_measure (l : list bool) : eR :=\n  1 / 2 ^ length l.\n\nLemma list_le_stream_prefix_trans {A} (a b : list A) (c : colist A) :\n  list_le a b ->\n  is_stream_prefix b c ->\n  is_stream_prefix a c.\nProof.\n  revert b c; induction a; intros b c Hab Hbc.\n  { constructor. }\n  inv Hab; inv Hbc.\n  constructor; eapply IHa; eauto.\nQed.\n\nLemma is_stream_prefix_inj {A} (l : list A) :\n  is_stream_prefix l (inj l).\nProof. induction l; constructor; auto. Qed.\n                       \n(* Lemma bitstring_incomparable_disjoint (a b : list bool) : *)\n(*   incomparable a b <-> partition [[ a ]] [[ b ]]. *)\n(* Proof. *)\n(*   unfold incomparable, disjoint, to_set; simpl. *)\n(*   unfold bitstring_set. *)\n(*   split. *)\n(*   - intros Hinc l. *)\n(*     contra HC; apply Hinc. *)\n(*     apply Classical_Prop.not_or_and in HC. *)\n(*     destruct HC as [H0 H1]. *)\n(*     apply Classical_Prop.NNPP in H0. *)\n(*     apply Classical_Prop.NNPP in H1. *)\n(*     eapply is_stream_prefix_consistent_pair; eauto. *)\n(*   - intros H [HC|HC]. *)\n(*     + specialize (H (inj b)). *)\n(*       destruct H as [H|H]. *)\n(*       * apply H. *)\n(*         eapply list_le_stream_prefix_trans; eauto. *)\n(*         apply is_stream_prefix_inj. *)\n(*       * apply H, is_stream_prefix_inj. *)\n(*     + specialize (H (inj a)). *)\n(*       destruct H as [H|H]. *)\n(*       * apply H, is_stream_prefix_inj. *)\n(*       * apply H. *)\n(*         eapply list_le_stream_prefix_trans; eauto. *)\n(*         apply is_stream_prefix_inj. *)\n(* Qed. *)\n\n(* Lemma bitstream_ext a b : *)\n(*   [[ a ]] = [[ b ]] -> *)\n(*   a = b. *)\n(* Proof. *)\n(*   simpl; unfold bitstring_set. *)\n(*   intro Hab. *)\n(*   apply eq_set_eq in Hab. *)\n(*   unfold set_eq in Hab. *)\n(*   revert Hab; revert b; induction a; intros b Hab. *)\n(*   - specialize (Hab conil). *)\n(*     destruct Hab as [H0 H1]. *)\n(*     specialize (H0 is_stream_prefix_nil). *)\n(*     inv H0; auto. *)\n(*   - destruct b. *)\n(*     { specialize (Hab conil). *)\n(*       destruct Hab as [H0 H1]. *)\n(*       specialize (H1 is_stream_prefix_nil). *)\n(*       inv H1. } *)\n(*     pose proof Hab as Hab'. *)\n(*     specialize (Hab (cocons a (inj a0))). *)\n(*     destruct Hab as [H0 H1]. *)\n(*     assert (H: is_stream_prefix (a :: a0) (cocons a (inj a0))). *)\n(*     { constructor; apply is_stream_prefix_inj. } *)\n(*     apply H0 in H; clear H0. *)\n(*     inv H; f_equal. *)\n(*     apply IHa. *)\n(*     intro l; specialize (Hab' (cocons a l)); destruct Hab' as [H0 H1']. *)\n(*     split; intro H. *)\n(*     + specialize (H0 (is_stream_prefix_cons H)); inv H0; auto. *)\n(*     + specialize (H1' (is_stream_prefix_cons H)); inv H1'; auto. *)\n(* Qed. *)\n\n(* Lemma bitstream_measure_proper a b : *)\n(*   [[ a ]] = [[ b ]] -> *)\n(*   bitstring_measure a = bitstring_measure b. *)\n(* Proof. intro Hab; apply bitstream_ext in Hab; subst; reflexivity. Qed. *)\n\n(* #[global] *)\n(*   Program *)\n(*   Instance Measurable_bitstring : Measurable (list bool) (colist bool) := *)\n(*   { mu := bitstring_measure }. *)\n(* Next Obligation. apply bitstream_measure_proper; auto. Qed. *)\n\nDefinition Sigma01 : Type := cotree bool (list bool).\n\n(* Definition measure {A T} `{Measurable A T} (U : cotree bool A) : eR := *)\n(*   tcosum mu U. *)\n\n(* Lemma coset_le_cotree_all_some (a b : Sigma01) : *)\n(*   [[ a ]] ⊑ [[ b ]] -> *)\n(*   cotree_all (fun x => cotree_some (fun y => y ⊑ x) b) a. *)\n(* Proof. *)\n(* Admitted. *)\n\n(* Lemma kdfg {A} (t : cotree bool A) : *)\n(*   cotree_all (fun x => cotree_some (eq x) cobot) t -> *)\n(*   t = cobot. *)\n(* Proof with eauto with cotree order. *)\n(*   intro Hall. *)\n(*   destruct t; auto; apply coop_elim with (i := S (S O)) in Hall... *)\n(*   - unfold atree_all in Hall. simpl in Hall. *)\n(*     apply cotree_some_bot in Hall; contradiction. *)\n(*   - unfold atree_all in Hall. simpl in Hall. *)\n(*     unfold compose in Hall. *)\n(*     simpl in Hall. *)\n\n(** IDEA: define stream of all bitstreams, then general construction\n    of Sigma01 stream of cotree by filtering out elements of the\n    stream not in the cotree. Prove their elements coincide and both\n    are partitionings, and that those together imply their measures\n    are equal. *)\n\n(* #[global] *)\n(*   Program *)\n(*   Instance Measurable_Sigma01 : Measurable Sigma01 (colist bool) := *)\n(*   { mu := measure }. *)\n(* Next Obligation. *)\n(*   apply eq_set_eq in H. *)\n(*   unfold set_eq in H. *)\n(*   unfold bitstring_set in H. *)\n\n(*   apply Proper_co_general_ext; eauto with mu order. *)\n(*   intro i. *)\n(*   simpl; unfold flip. *)\n(*   revert Hab Hba; induction i; intros Hab Hba; simpl. *)\n(*   { reflexivity. } *)\n(*   destruct a. *)\n(*   - destruct b; auto. *)\n(*     + apply cotree_all_elim_leaf in Hba. *)\n(*       apply cotree_some_bot in Hba; contradiction. *)\n(*     + unfold asum. simpl. *)\n(*       unfold compose in *. *)\n      \n(*       eapply IHi in Hba; auto. *)\n(*       destruct i. *)\n(*       { eRauto. } *)\n(*       simpl in *. *)\n\n(*       pose proof Hba as Hba'. *)\n(*       apply cotree_all_elim_node with (b:=true) in Hba. *)\n(*       apply cotree_all_elim_node with (b:=false) in Hba'. *)\n  \n\n\n(* Qed. *)\n\n\n(** TODO: generalize to class of measurable types (ToSet with\n    measure). *)\n(* Definition measure (U : Sigma01) : eR := *)\n(*   mu (fun bs => 1 / 2 ^ length bs) U. *)\n(* #[global] Hint Unfold measure : mu. *)\n\n(* Lemma dfgdfg (U V : Sigma01) : *)\n(*   [[ U ]] = [[ V ]] -> *)\n(*   measure U = measure V. *)\n\nDefinition cotree_union {A} (U V : cotree bool A) : cotree bool A :=\n  conode (fun b : bool => if b then U else V).\n\nLemma Sigma01_union_pairwise_disjoint (U V : Sigma01) :\n  cotree_pairwise_disjoint U ->\n  cotree_pairwise_disjoint V ->\n  cotree_disjoint U V ->\n  cotree_pairwise_disjoint (cotree_union U V).\nProof with eauto with cotree order.\n  intros HU HV [HVU HUV].\n  apply coop_intro...\n  intro i; simpl; unfold flip.\n  unfold cotree_union.\n  destruct i.\n  { constructor. }\n  apply coop_elim with (i:=i) in HU...\n  apply coop_elim with (i:=i) in HV...\n  apply coop_elim with (i:=i) in HVU...\n  apply coop_elim with (i:=i) in HUV...\n  simpl in *; unfold flip in *.\n  constructor.\n  - intros []; auto.\n  - split; eapply atree_all_impl; eauto; simpl;\n      intros bs Hbs; apply coop_elim with (i:=i) in Hbs...\nQed.\n\nDefinition alist_union {A} : list (cotree bool A) -> cotree bool A :=\n  fold ⊥ cotree_union.\n\n#[global]\n  Instance monotone_alist_union {A}\n  : Proper (leq ==> leq) (@alist_union A).\nProof.\n  unfold alist_union.\n  intro a; induction a; intros b Hab; unfold flip; simpl.\n  { constructor. }\n  unfold cotree_union.\n  inv Hab; simpl.\n  constructor; intros [].\n  - reflexivity.\n  - apply IHa; auto.\nQed.\n#[global] Hint Resolve monotone_alist_union : colist.\n\nDefinition colist_union {A} : colist (cotree bool A) -> cotree bool A :=\n  co alist_union.\n  \nInductive alist_pairwise_disjoint {A} `{OType A} : list (cotree bool A) -> Prop :=\n| alist_pairwise_disjoint_nil : alist_pairwise_disjoint []\n| alist_pairwise_disjoint_cons : forall t l,\n    (* cotree_pairwise_disjoint t -> *)\n    alist_pairwise_disjoint l ->\n    list_forall (cotree_disjoint t) l ->\n    alist_pairwise_disjoint (t :: l).\n\n#[global]\n  Instance antimonotone_alist_pairwise_disjoint {A} `{OType A}\n  : Proper (leq ==> flip leq) (@alist_pairwise_disjoint A _).\nProof.\n  intro a; induction a; intros b Hab Hb.\n  { constructor. }\n  inv Hab; inv Hb.\n  constructor; auto.\n  - eapply IHa; eauto.\n  - eapply antimonotone_list_forall; eauto.\nQed.\n#[global] Hint Resolve antimonotone_alist_pairwise_disjoint : colist.\n\nDefinition colist_pairwise_disjoint {A} `{OType A} : colist (cotree bool A) -> Prop :=\n  coop alist_pairwise_disjoint.\n\nLemma continuous_pair_plus :\n  wcontinuous (fun f : bool -> eR => f false + f true).\nProof.\n  intros ch Hch f Hsup; unfold compose.\n  apply supremum_sum.\n  { intro i; apply Hch. }\n  { intro i; apply Hch. }\n  { apply apply_supremum; auto. }\n  { apply apply_supremum; auto. }\nQed.\n\n(* Lemma countable_additivity (l : colist Sigma01) : *)\n(*   measure (colist_union l) = cosum (comap measure l). *)\n(* Proof with eauto with order colist cotree aCPO mu eR. *)\n(*   unfold colist_union. *)\n(*   rewrite co_co_ext... *)\n(*   2: { apply continuous_wcontinuous, continuous_co, monotone_asum. } *)\n(*   unfold comap, cofold. *)\n(*   rewrite co_co_ext with (g := cosum)... *)\n(*   2: { apply continuous_wcontinuous, continuous_co... } *)\n(*   eapply Proper_co_ext; eauto. *)\n(*   { apply monotone_compose. *)\n(*     - apply monotone_alist_union. *)\n(*     - apply continuous_monotone, continuous_co, monotone_asum. } *)\n(*   { apply monotone_compose. *)\n(*     - apply monotone_amap. *)\n(*     - apply continuous_monotone, continuous_co... } *)\n(*   clear l; unfold compose. *)\n(*   unfold alist_union. *)\n(*   unfold measure, tcosum, asum, cosum, cofold. *)\n(*   ext b; induction b; simpl. *)\n(*   { rewrite co_tfold_bot', co_fold_nil'; reflexivity. } *)\n(*   unfold cotree_union. *)\n(*   rewrite co_tfold_node'... *)\n(*   2: { apply continuous_pair_plus. } *)\n(*   unfold compose. *)\n(*   unfold map_f in *. *)\n(*   rewrite co_fold_cons'... *)\n(*   2: { intro; apply continuous_eRplus. } *)\n(*   rewrite eRplus_comm. *)\n(*   f_equal; apply IHb. *)\n(* Qed. *)\n\n(* Lemma countable_additivity (l : colist Sigma01) : *)\n(*   colist_pairwise_disjoint l -> *)\n(*   measure (colist_union l) = cosum (comap measure l). *)\n(* Proof with eauto with order colist cotree aCPO mu eR. *)\n(*   intro Hpart. *)\n(*   unfold colist_union. *)\n(*   rewrite co_co_ext... *)\n(*   2: { apply continuous_wcontinuous, continuous_co... } *)\n(*   unfold comap, cofold. *)\n(*   rewrite co_co_ext with (g := cosum)... *)\n(*   2: { apply continuous_wcontinuous, continuous_co... } *)\n(*   eapply Proper_co_P_ext; eauto. *)\n(*   { apply antimonotone_alist_pairwise_disjoint. } *)\n(*   { apply monotone_compose. *)\n(*     - apply monotone_alist_union. *)\n(*     - apply continuous_monotone, continuous_co, monotone_amu. } *)\n(*   { apply monotone_compose. *)\n(*     - apply monotone_amap. *)\n(*     - apply continuous_monotone, continuous_co, monotone_asum. } *)\n(*   clear l Hpart; unfold compose. *)\n(*   unfold alist_union. *)\n(*   unfold measure, mu, amu, cosum, cofold. *)\n(*   intro b; induction b; simpl; intro Hpart. *)\n(*   { rewrite co_tfold_bot', co_fold_nil'; reflexivity. } *)\n(*   unfold cotree_union. *)\n(*   rewrite co_tfold_node'... *)\n(*   2: { apply continuous_pair_plus. } *)\n(*   unfold compose. *)\n(*   inv Hpart. *)\n(*   unfold map_f in *. *)\n(*   rewrite co_fold_cons'... *)\n(*   2: { intro; apply continuous_eRplus. } *)\n(*   apply IHb in H1. *)\n(*   rewrite eRplus_comm. *)\n(*   f_equal; apply H1. *)\n(* Qed. *)\n\nFixpoint count {A} (P : A -> Prop) (l : list A) : nat :=\n  match l with\n  | [] => O\n  | x :: xs => if classicT (P x) then S (count P xs) else count P xs\n  end.\n\nDefinition freq {A} (P : A -> Prop) (l : list A) :=\n  INeR (count P l) / INeR (length l).\n\nDefinition in_Sigma01 (U : Sigma01) (s : colist bool) : Prop :=\n  cotree_some (fun l => is_stream_prefix l s) U.\n\nDefinition mu (U : Sigma01) : eR :=\n  tcosum bitstring_measure U.\n\nDefinition uniform (bitstreams : nat -> colist bool) : Prop :=\n  forall U : Sigma01,\n    cotree_pairwise_disjoint U ->\n    converges (freq (in_Sigma01 U) ∘ seq_prefix bitstreams) (mu U).\n\nInductive produces {A} (P : A -> Prop) : colist bool -> cotree bool A -> Prop :=\n| produces_leaf : forall bs x, P x -> produces P bs (coleaf x)\n| produces_node : forall b bs k,\n    produces P bs (k b) ->\n    produces P (cocons b bs) (conode k).\n\nLemma list_rel_count {A B} (P : A -> Prop) (Q : B -> Prop) (l1 : list A) (l2 : list B) :\n  list_rel (fun x y => P x <-> Q y) l1 l2 ->\n  count P l1 = count Q l2.\nProof.\n  induction 1; simpl; auto.\n  repeat destruct_classic; auto.\n  - apply H in p; congruence.\n  - apply H in q; congruence.\nQed.\n\nLemma produces_in_sigma01 {A} (x : A) (bs : colist bool) (P : A -> bool) (t : cotree bool A) :\n  produces (eq x) bs t ->\n  in_Sigma01 (cotree_preimage P t) bs <-> is_true (P x).\nProof.\n  unfold in_Sigma01.\n  induction 1; subst.\n  - rewrite cotree_preimage_leaf.\n    split.\n    + intro Hsome.\n      destruct (P x0); auto.\n      apply co_elim in Hsome; eauto with cotree order.\n      destruct Hsome as [i Hsome].\n      destruct i; inv Hsome.\n    + unfold is_true; intro HP.\n      destruct (P x0); try congruence.\n      apply co_intro with (S O); eauto with cotree order.\n      constructor; constructor.\n  - rewrite cotree_preimage_node; split.\n    + intro Hsome.\n      apply co_elim in Hsome; eauto with cotree order.\n      destruct Hsome as [i Hsome].\n      apply IHproduces.\n      apply atree_some_exists in Hsome.\n      destruct Hsome as [l [H1 H2] ].\n      apply atree_some_exists in H1.\n      destruct H1 as [l' [Hsome Hl] ]; subst.\n      inv H2.\n      { destruct i; simpl in Hsome.\n        - inv Hsome.\n        - destruct Hsome as [c H0].\n          unfold compose in H0. simpl in H0.\n          rewrite tprefix_map in H0.\n          apply atree_some_map in H0.\n          unfold compose in H0.\n          apply atree_some_exists in H0.\n          destruct H0 as [l [H0 Heq] ].\n          inv Heq. }\n      destruct i.\n      { inv Hsome. }\n      { simpl in Hsome; unfold flip in Hsome; simpl in Hsome.\n        unfold compose in Hsome.\n        destruct Hsome as [c H1].\n        unfold compose in H1.\n        rewrite tprefix_map in H1.\n        apply atree_some_map in H1.\n        apply atree_some_exists in H1.\n        destruct H1 as [l' [Hsome Hl'] ].\n        inv Hl'.\n        eapply co_intro; eauto with cotree order.\n        apply atree_some_exists; exists l'; split; eauto.\n        apply Hsome. }\n    + unfold is_true; intro HPx.\n      unfold cotree_some.\n      apply IHproduces in HPx.\n      apply co_elim in HPx; eauto with cotree order.\n      destruct HPx as [i Hi].\n      apply co_intro with (S i); eauto with cotree order.\n      simpl; unfold flip; simpl.\n      econstructor.\n      unfold compose.\n      rewrite tprefix_map.\n      apply atree_map_some.\n      unfold compose.\n      eapply atree_some_impl; try apply Hi.\n      intros l Hl; constructor; auto.\nQed.\n\nRecord SamplingEnvironment : Type :=\n  mkSampleEnvironment\n    { bitstreams : nat -> colist bool\n    ; bitstreams_uniform : uniform bitstreams }.\n\n(** Cotree sampling theorem. *)\nSection cotree_equidistribution.\n  Context (env : SamplingEnvironment) (A : Type) (t : cotree bool A) (P : A -> bool).\n\n  Variable samples : nat -> A.\n  Hypothesis bitstreams_samples : forall i, produces (eq (samples i)) (env.(bitstreams) i) t.\n\n  Lemma cotree_freq_bitstreams_samples (n : nat) :\n    freq (in_Sigma01 (cotree_preimage P t)) (seq_prefix env.(bitstreams) n) =\n      freq (fun x : A => is_true (P x)) (seq_prefix samples n).\n  Proof.\n    unfold freq; f_equal.\n    2: { f_equal; rewrite 2!length_seq_prefix; reflexivity. }\n    f_equal; apply list_rel_count, list_rel_prefix.\n    intro i; specialize (@bitstreams_samples i).\n    apply produces_in_sigma01; auto.\n  Qed.\n\n  Theorem cotree_samples_equidistributed :\n    converges (freq (is_true ∘ P) ∘ seq_prefix samples)\n      (cotwp (fun s => if P s then 1 else 0) t).\n  Proof.\n    intros eps Heps.\n    pose proof env.(bitstreams_uniform) as Huniform.\n    specialize (Huniform _ (pairwise_disjoint_cotree_preimage P t) _ Heps).\n    destruct Huniform as [n0 Huniform].\n    exists n0; intros n Hn; specialize (Huniform n Hn).\n    unfold compose in *.\n    rewrite cotwp_tcosum_preimage'.\n    unfold mu in Huniform.\n    rewrite <- cotree_freq_bitstreams_samples; apply Huniform.\n  Qed.\nEnd cotree_equidistribution.\n\nPrint Assumptions cotree_samples_equidistributed.\n", "meta": {"author": "bagnalla", "repo": "algco", "sha": "433836e4a0743c0443d530913769a00549b6993a", "save_path": "github-repos/coq/bagnalla-algco", "path": "github-repos/coq/bagnalla-algco/algco-433836e4a0743c0443d530913769a00549b6993a/equidistribution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.2977681115275404}}
{"text": "(* THIS FILE IS JUST THE BEGINNING OF AN EXPERIMENTAL SKETCH!\n  We explore whether multivariate first-order Taylor expansions,\n  in the style of FPTaylor, might be useful.\n *)\n\nRequire Import Reals ZArith Lra Lia IntervalFlocq3.Tactic.\nImport Raux.\nFrom Flocq3 Require Import IEEE754.Binary Zaux.\nRequire Import Setoid.\n\nImport Coq.Lists.List ListNotations.\nImport Tree. (* must import this _after_ List *)\nImport Interval Private Interval_helper I2 IT2.IH I2.T Xreal Eval.Reify.\n\nImport Basic.\nImport Bool.\nFrom vcfloat Require Import Prune.\n\nLemma doppler1_test:\n  forall\n  (v_v : R)\n  (BOUND : 20 <= v_v <= 2e4)\n  (v_u : R)\n  (BOUND0 : -100 <= v_u <= 100)\n  (v_t : R)\n  (BOUND1 : -30 <= v_t <= 50)\n  (e0 : R)\n  (E : Rabs e0 <= powerRZ 2 (-1075))\n  (e1 : R)\n  (E0 : Rabs e1 <= powerRZ 2 (-1075))\n  (e3 : R)\n  (E2 : Rabs e3 <= powerRZ 2 (-1075))\n  (e4 : R)\n  (E3 : Rabs e4 <= powerRZ 2 (-1075))\n  (e8 : R)\n  (E7 : Rabs e8 <= powerRZ 2 (-1075))\n  (e9 : R)\n  (E8 : Rabs e9 <= powerRZ 2 (-1075))\n  (d : R)\n  (E10 : Rabs d <= powerRZ 2 (-53))\n  (d0 : R)\n  (E11 : Rabs d0 <= powerRZ 2 (-53))\n  (d1 : R)\n  (E12 : Rabs d1 <= powerRZ 2 (-53))\n  (d2 : R)\n  (E13 : Rabs d2 <= powerRZ 2 (-53))\n  (d3 : R)\n  (E14 : Rabs d3 <= powerRZ 2 (-53))\n  (d6 : R)\n  (E17 : Rabs d6 <= powerRZ 2 (-53))\n  (a := 2915025227559731 / 8796093022208 : R)\n  (b := 5404319552844595 / 9007199254740992 : R),\n {bound: R | \nRabs\n  ((- ((a + (b * v_t * (1 + d) + e1)) * (1 + d1) + e0) * v_v *\n    (1 + d2) + e8) /\n   ((((a + (b * v_t * (1 + d) + e1)) * (1 + d1) + e0 + v_u) *\n     (1 + d0) + e4) *\n    (((a + (b * v_t * (1 + d) + e1)) * (1 + d1) + e0 + v_u) *\n     (1 + d0) + e4) * (1 + d6) + e3) * (1 + d3) + e9 -\n   - (a + b * v_t) * v_v *\n   / ((a + b * v_t + v_u) * (a + b * v_t + v_u))) \n   <= bound}.\nProof. intros.\nevar (bound: R).\nexists bound. (*eexists.*)\nunfold a, b.\n\nsimple_reify.\n\nDefinition bind2 (f: expr -> expr -> expr) (x1: option expr) (x2: option expr) : option expr :=\n match x1, x2 with\n | Some y1, Some y2 => Some (f y1 y2)\n | _, _ => None\n end.\n\nDefinition Mul' (e1 e2: expr) :=\n match e1, e2 with\n | Econst (Int 0) , _ => zeroexpr\n | _, Econst (Int 0) => zeroexpr\n | Econst (Int 1) , _ => e2\n | _, Econst (Int 1) => e1\n | _, _ => Ebinary Mul e1 e2\n end.\n\n\nDefinition Div' (e1 e2: expr) :=\n match e1, e2 with\n | Econst (Int 0) , _ => zeroexpr\n | _, Econst (Int 1) => e1\n | _, _ => Ebinary Div e1 e2\n end.\n\nDefinition Neg' (e1: expr) :=\n match e1 with Econst (Int 0) => zeroexpr | _ => e1 end.\n\nDefinition Sqr' (e1: expr) :=\n match e1 with\n | Econst (Int 0) => zeroexpr \n | Econst (Int 1) => oneexpr\n | _ => e1 \n end.\n\n\nPrint Add0.\n\nDefinition partial_deriv (x: nat) : expr -> option expr :=\n fix aux (e: expr) : option expr := \n match e with\n | Evar y => Some (if Nat.eqb x y then oneexpr else zeroexpr)\n | Econst _ => Some zeroexpr\n | Eunary Neg e1 => option_map Neg' (aux e1)\n | Eunary Inv e1 => option_map (fun d => Neg' (Div' d (Sqr' e1))) (aux e1) \n | Eunary Sqr e => option_map (Mul' (Econst (Int 2))) (aux e)\n | Ebinary Add e1 e2 => bind2 Add0 (aux e1) (aux e2)\n | Ebinary Sub e1 e2 => bind2 Sub0 (aux e1) (aux e2)\n | Ebinary Mul e1 e2 => bind2 (fun d1 d2 => Add0 (Mul' e1 d2) (Mul' e2 d1)) (aux e1) (aux e2)\n | Ebinary Div e1 e2 => bind2 (fun d1 d2 => Div' (Sub0 (Mul' e2 d1) (Mul' e1 d2)) (Sqr' e2))\n            (aux e1) (aux e2)\n | e => None\n end.\n\nFixpoint option_list {A} (al: list (option A)) : option (list A) :=\n match al with\n | nil => Some nil\n | Some x :: r => option_map (cons x) (option_list r)\n | None :: _ => None\n end.\n\nDefinition gradient (vars: list R) e  :=\n option_list (map (fun x => partial_deriv x e) (seq.iota 0 (length vars))).\n\nassert (\n match partial_deriv 3%nat __expr with\n  | Some d => eval d __vars = 0%R\n | _ => False\n end).\ncbv -[IZR].\nrepeat change (?A * / ?B) with (A/B).\nfold a. fold b.\nclear __expr.\n\n\n\n\n\n\npose (vars := seq.iota 0 (length __vars)).\n\nSearch (list (option _) -> option (list _)).\nassert (partial_deriv 3%nat __expr = None).\ncbv.\n\ncbv [partial_deriv __expr Nat.eqb ].\n\n\n  \n\nCheck option_map.\n\n\n\n\n\n", "meta": {"author": "VeriNum", "repo": "vcfloat", "sha": "9cad8c4b48fe4353d01f02f6dc5bd03e1ea4eb5c", "save_path": "github-repos/coq/VeriNum-vcfloat", "path": "github-repos/coq/VeriNum-vcfloat/vcfloat-9cad8c4b48fe4353d01f02f6dc5bd03e1ea4eb5c/vcfloat/Taylor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.29774974864482723}}
{"text": "Require Import Coq.ZArith.BinInt.\nRequire Import Coq.Init.Byte.\nRequire Import coqutil.Word.Bitwidth.\nRequire Import coqutil.Tactics.rewr.\nRequire Import coqutil.Map.Interface.\nRequire Import bedrock2.SepAuto.\nRequire Import bedrock2.Array.\nRequire Import bedrock2.groundcbv.\nRequire Import bedrock2.TransferSepsOrder.\nRequire Import bedrock2.SepCalls.\n\nSection SepLog.\n  Context {width: Z} {BW: Bitwidth width} {word: word.word width} {mem: map.map word byte}.\n  Context {word_ok: word.ok word} {mem_ok: map.ok mem}.\n\n  Lemma array_app{E : Type}{elem: sep_predicate mem E}{sz: Z}:\n    forall (xs ys: list E) (start : word),\n      (start :-> xs ++ ys : array elem (word.of_Z sz)) =\n      (sep (start :-> xs : array elem (word.of_Z sz))\n           (word.add start (word.of_Z (sz * Z.of_nat (Datatypes.length xs))) :-> ys\n             : array elem (word.of_Z sz))).\n  Proof.\n    intros.\n    eapply iff1ToEq.\n    etransitivity.\n    1: eapply array_append.\n    cancel.\n    cancel_seps_at_indices 0%nat 0%nat. {\n      f_equal. f_equal.\n      destruct width_cases; ZnWords.\n    }\n    reflexivity.\n  Qed.\n\n  Lemma access_elem_in_array: forall a a' E (elem: sep_predicate mem E) sz fullLength,\n      0 < sz < 2 ^ width ->\n      let i := Z.to_nat (word.unsigned (word.sub a' a) / sz) in\n      (word.unsigned (word.sub a' a) mod sz = 0 /\\\n       (* only here to make sure automation picks the right array *)\n       (i < fullLength)%nat) ->\n      forall vs vs1 v vs2,\n        (* connected with /\\ because it needs to be solved by considering both at once *)\n        vs = vs1 ++ [v] ++ vs2 /\\ List.length vs1 = i ->\n        iff1 (a :-> vs : array elem (word.of_Z sz))\n             (sep (a' :-> v : elem)\n                  (seps [a :-> vs1 : array elem (word.of_Z sz);\n                         word.add a (word.of_Z (sz * Z.of_nat (S i))) :-> vs2\n                           : array elem (word.of_Z sz)])).\n  Proof.\n    unfold seps.\n    intros. fwd.\n    cbn [List.app].\n    etransitivity.\n    1: eapply array_append.\n    cbn [Array.array].\n    cancel.\n    cancel_seps_at_indices 0%nat 0%nat. {\n      f_equal. rewrite H1p1.\n      destruct width_cases; ZnWords.\n    }\n    cancel_seps_at_indices 0%nat 0%nat. {\n      f_equal. destruct width_cases; ZnWords.\n    }\n    reflexivity.\n  Qed.\n\n  Lemma access_subarray: forall a a' E (elem: sep_predicate mem E) sz n fullLength,\n      0 < sz < 2 ^ width ->\n      let i := Z.to_nat (word.unsigned (word.sub a' a) / sz) in\n      (word.unsigned (word.sub a' a) mod sz = 0 /\\\n       (* only here to make sure automation picks the right array *)\n       (i + n <= fullLength)%nat) ->\n      forall vs vs1 vs2 vs3,\n        vs = vs1 ++ vs2 ++ vs3 /\\ List.length vs1 = i /\\ List.length vs2 = n ->\n        iff1 (a :-> vs : array elem (word.of_Z sz))\n             (sep (a' :-> vs2 : array elem (word.of_Z sz))\n                  (seps [a :-> vs1 : array elem (word.of_Z sz);\n                         word.add a (word.of_Z (sz * Z.of_nat (i + n))) :-> vs3\n                           : array elem (word.of_Z sz)])).\n  Proof.\n    intros.\n    unfold seps.\n    intros. fwd.\n    rewrite 2array_append.\n    cancel.\n    cancel_seps_at_indices 0%nat 0%nat. {\n      f_equal. rewrite H1p1.\n      destruct width_cases; ZnWords.\n    }\n    cancel_seps_at_indices 0%nat 0%nat. {\n      f_equal. destruct width_cases; ZnWords.\n    }\n    reflexivity.\n  Qed.\n\n  Lemma access_suffix: forall a a' E (elem: sep_predicate mem E) sz lenPrefix,\n      0 < sz < 2 ^ width ->\n      word.sub a' a = word.mul (word.of_Z sz) (word.of_Z (Z.of_nat lenPrefix)) ->\n      forall vs vs1 vs2,\n        vs = vs1 ++ vs2 /\\ List.length vs1 = lenPrefix ->\n        iff1 (a :-> vs : array elem (word.of_Z sz))\n             (sep (a' :-> vs2 : array elem (word.of_Z sz))\n                  (seps [a :-> vs1 : array elem (word.of_Z sz)])).\n  Proof.\n    intros. intros. fwd.\n    rewrite array_app. cbn [seps].\n    cancel. cbn [seps].\n    match goal with\n    | |- iff1 (?x :-> _ : _) _ => replace x with a'\n    end.\n    1: reflexivity.\n    destruct width_cases; ZnWords.\n  Qed.\n\n  Lemma access_tail: forall a a' E (elem: sep_predicate mem E) sz,\n      0 < sz < 2 ^ width ->\n      word.sub a' a = word.of_Z sz ->\n      forall v vs,\n        iff1 (a :-> List.cons v vs : array elem (word.of_Z sz))\n             (sep (a' :-> vs : array elem (word.of_Z sz))\n                  (seps [a :-> v : elem])).\n  Proof.\n    intros. intros. cbn.\n    cancel. cbn [seps].\n    match goal with\n    | |- iff1 (Array.array _ _ ?x _) _ => replace x with a'\n    end.\n    1: reflexivity.\n    destruct width_cases; ZnWords.\n  Qed.\nEnd SepLog.\n\n\nLtac destruct_bool_vars :=\n  repeat match goal with\n         | H: context[if ?b then _ else _] |- _ =>\n             is_var b; let t := type of b in constr_eq t bool; destruct b\n         end.\n\nLtac concrete_list_length l :=\n  lazymatch l with\n  | cons ?h ?t => let r := concrete_list_length t in constr:(S r)\n  | nil => constr:(O)\n  | List.app ?l1 ?l2 =>\n      let r1 := concrete_list_length l1 in\n      let r2 := concrete_list_length l2 in\n      let r := eval cbv in (r1 + r2)%nat in constr:(r)\n  | List.map _ ?l' => concrete_list_length l'\n  | List.unfoldn _ ?n _ =>\n      let n' := groundcbv n in\n      lazymatch isnatcst n' with\n      | true => constr:(n')\n      end\n  | _ => let l' := eval unfold l in l in concrete_list_length l'\n  end.\n\nLtac rewr_with_eq e :=\n  lazymatch type of e with\n  | ?LHS = _ => progress (pattern LHS; eapply rew_zoom_bw; [exact e|])\n  end.\n\nLtac list_length_simpl_step_in_goal :=\n  match goal with\n  | |- context[@List.length ?T ?l] =>\n      let n := concrete_list_length l in change (@List.length T l) with n\n  | |- context[List.length (List.skipn ?n ?l)] => rewr_with_eq (List.length_skipn n l)\n  | |- context[List.length (List.firstn ?n ?l)] => rewr_with_eq (List.firstn_length n l)\n  | |- context[List.length (?l1 ++ ?l2)] => rewr_with_eq (List.app_length l1 l2)\n  | |- context[List.length (?h :: ?t)] => rewr_with_eq (List.length_cons h t)\n  | |- context[List.length (List.map ?f ?l)] => rewr_with_eq (List.map_length f l)\n  | |- context[List.length (List.unfoldn ?step ?n ?start)] =>\n      rewr_with_eq (List.length_unfoldn step n start)\n  | |- context[List.length (List.repeat ?v ?n)] => rewr_with_eq (List.repeat_length v n)\n  end.\n\nGoal forall (l1 l2: list Z) (a: Z),\n    a + Z.of_nat (List.length (l1 ++ l2)) =\n    Z.of_nat (List.length l1) + Z.of_nat (List.length l2) + a.\nProof.\n  intros. list_length_simpl_step_in_goal.\nAbort.\n\n(* Only rewrites below the line, because rewriting above the line should already\n   have been done (or will be done later), but the goal below the line might be the\n   sidecondition of another rewrite lemma that's being tried and thus did not yet\n   appear anywhere in the context before.\n   For example, trying to rewrite with List.firstn_all2 creates a sidecondition\n   containing a (List.length l) that did not yet have any chance to get\n   simplified.\n   For efficiency, we only use rewrite lemmas here that don't have sideconditions\n   themselves, and use the simplest possible homemade rewr_with_eq to avoid any\n   unexpected performance pitfalls of Coq's existing rewrite tactics. *)\nLtac list_length_rewrites_without_sideconds_in_goal :=\n  repeat list_length_simpl_step_in_goal.\n\nLtac listZnWords :=\n  destruct_bool_vars;\n  unfold List.upd, List.upds;\n  list_length_rewrites_without_sideconds_in_goal;\n  ZnWords.\n\nSection WithA.\n  Context {A: Type}.\n\n  Lemma list_expose_nth{inhA: inhabited A}: forall (vs: list A) i,\n      (i < List.length vs)%nat ->\n      vs = List.firstn i vs ++ [List.nth i vs default] ++ List.skipn (S i) vs /\\\n        List.length (List.firstn i vs) = i.\n  Proof.\n    intros. rewrite List.firstn_nth_skipn by assumption.\n    rewrite List.firstn_length_le by Lia.lia. auto.\n  Qed.\n\n  Lemma list_expose_subarray: forall (vs: list A) i n,\n      (i + n <= List.length vs)%nat ->\n      vs = List.firstn i vs ++ List.firstn n (List.skipn i vs) ++ List.skipn (i + n) vs /\\\n        List.length (List.firstn i vs) = i /\\\n        List.length (List.firstn n (List.skipn i vs)) = n.\n  Proof.\n    intros. list_length_rewrites_without_sideconds_in_goal. ssplit; [ | Lia.lia..].\n    rewrite <- (List.firstn_skipn i vs) at 1. f_equal.\n    rewrite <- (List.firstn_skipn n (List.skipn i vs)) at 1. f_equal.\n    rewrite List.skipn_skipn. f_equal. apply Nat.add_comm.\n  Qed.\nEnd WithA.\n\nNotation word_array := (array Scalars.scalar (word.of_Z 4)).\n\nLtac concrete_sz_bounds :=\n  lazymatch goal with\n  | |- 0 < ?sz < 2 ^ ?width =>\n      lazymatch isZcst sz with\n      | true => lazymatch isZcst width with\n                | true => split; reflexivity\n                end\n      end\n  end.\n\n(* Hints in three different DBs indicating how to find the rewrite lemma,\n   how to solve its sideconditions for the split direction, and how to solve its\n   sideconditions for the merge direction: *)\n\n(* split_sepclause_goal: *)\n\n#[export] Hint Extern 1\n  (split_sepclause (?a :-> ?vsAll : array ?elem (word.of_Z ?sz)) (?a' :-> _ : ?elem) _ _) =>\n  unshelve (epose proof (access_elem_in_array a a' _ elem sz (List.length vsAll) _ _));\n  [ concrete_sz_bounds | listZnWords | shelve ]\n: split_sepclause_goal.\n\n#[export] Hint Extern 1\n  (split_sepclause (?a :-> ?vsAll : array ?elem (word.of_Z ?sz))\n                   (?a' :-> ?vsPart : array ?elem (word.of_Z ?sz)) _ ?G) =>\n  (* most likely, vsPart is still an evar (because it's universally quantified by the\n     callee's correctness lemma), so we have to search for its desired length in G,\n     but maybe it has a concrete structure (eg [?a; ?b; ?c]), in which case\n     concrete_list_length can find that length *)\n  let n := match G with\n           | _ /\\ ?C => match C with context[List.length vsPart = ?n] => n end\n           | _ => concrete_list_length vsPart\n           end in\n  unshelve (epose proof (access_subarray a a' _ elem sz n (List.length vsAll) _ _));\n  [ concrete_sz_bounds | listZnWords | shelve ]\n: split_sepclause_goal.\n\n#[export] Hint Extern 1 (split_sepclause (?a  :-> ?vs1 ++ ?vs2 : array ?elem (word.of_Z ?sz))\n                                         (?a' :-> ?vs2 : array ?elem (word.of_Z ?sz)) _ _) =>\n  unshelve (epose proof (access_suffix a a' _ elem sz (List.length vs1) _ _));\n  [ concrete_sz_bounds | listZnWords | shelve ]\n: split_sepclause_goal.\n\n#[export] Hint Extern 1\n  (split_sepclause (?a  :-> (_ :: ?vsTail) : array ?elem (word.of_Z ?sz))\n                   (?a' :-> ?vsTail : array ?elem (word.of_Z ?sz)) _ _) =>\n  unshelve (epose proof (access_tail a a' _ elem sz _ _));\n  [ concrete_sz_bounds | listZnWords | shelve ]\n: split_sepclause_goal.\n\n\n(* split_sepclause_sidecond: *)\n\n#[export] Hint Extern 1 (_ = ?l ++ [_] ++ _ /\\ List.length ?l = _) =>\n  eapply list_expose_nth; listZnWords\n: split_sepclause_sidecond.\n\n#[export] Hint Extern 1\n (_ = ?l1 ++ ?l2 ++ ?l3 /\\ List.length ?l1 = _ /\\ List.length ?l2 = _) =>\n  eapply list_expose_subarray; listZnWords\n: split_sepclause_sidecond.\n\n\n(* merge_sepclause_sidecond: *)\n\n#[export] Hint Extern 1 (@eq (list _) ?listL ?listR /\\ @eq nat ?lenL ?lenR) =>\n  assert_fails (has_evar lenL);\n  assert_fails (has_evar lenR);\n  is_evar listL; split; [ reflexivity | listZnWords ]\n: merge_sepclause_sidecond.\n\n(* TODO make more generic *)\n#[export] Hint Extern 1 (?listL = ?listR1 ++ ?listR2 /\\ ?lenR1 = _ /\\ ?lenR2 = _) =>\n  apply_in_hyps @map.getmany_of_list_length; rewrite List.length_unfoldn in *;\n  is_evar listL; split; [ reflexivity | split; listZnWords ]\n: merge_sepclause_sidecond.\n\n(* TODO make more generic *)\n#[export] Hint Extern 1\n  (?listL = ?listR1 ++ ?listR2 ++ ?listR3 /\\ ?lenR1 = ?i /\\ ?lenR2 = ?n) =>\n  apply_in_hyps @map.getmany_of_list_length; rewrite ?List.length_unfoldn in *;\n  is_evar listL; split; [ reflexivity | split; listZnWords ]\n: merge_sepclause_sidecond.\n\n\n(* Hints to simplify/cleanup the expressions that were created by repeated\n   splitting and merging of sep clauses: *)\n#[export] Hint Rewrite\n  List.firstn_all2\n  List.skipn_all2\n  List.firstn_eq_O\n  List.skipn_eq_O\n  Nat.min_l\n  Nat.min_r\nusing (unfold List.upd, List.upds;\n       list_length_rewrites_without_sideconds_in_goal;\n       ZnWords)\n: fwd_rewrites.\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/SepAutoArray.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.2977497486448272}}
{"text": "From iris.algebra Require Import excl auth agree frac list cmra csum.\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.\nFrom iris_examples.logatom.rdcss Require Import spec.\nImport uPred bi List Decidable.\nSet Default Proof Using \"Type\".\n\n(** We consider here an implementation of the RDCSS (Restricted Double-Compare\n    Single-Swap) data structure of Harris et al., as described in \"A Practical\n    Multi-Word Compare-and-Swap Operation\" (DISC 2002).\n\n    Our goal is to prove logical atomicity for the operations of RDCSS, and to\n    do so we will need to use prophecy variables! This Coq file is part of the\n    artifact accompanying the paper \"The Future is Ours: Prophecy Variables in\n    Separation Logic\" (POPL 2020). Proving logical atomicity for RDCSS appears\n    as a major case study in the paper, so it makes sense to read the relevant\n    sections first (§4 to §6) to better understand the Coq proof. The paper is\n    available online at: <https://plv.mpi-sws.org/prophecies/>. *)\n\n(** * Implementation of the RDCSS operations *)\n\n(** The RDCSS data structure manipulates two kinds of locations:\n    - N-locations (a.k.a. RDCSS locations) denoted [l_n] identify a particular\n      instance of RDCSS. (Harris et al. refer to them as locations in the data\n      section.) They are the locations that may be updated by a call to RDCSS.\n    - M-locations denoted [l_m] are not tied to a particular RDCSS instance.\n      (Harris et al. refer to them as locations in the control section.)  They\n      are never directly modified by the RDCSS operation, but they are subject\n      to arbitrary interference by other heap operations.\n\n    An N-location can contain values of two forms.\n    - A value of the form [injL n] indicates that there is currently no active\n      RDCSS operation on the N-location, and that the location has the logical\n      value [n]. In that case, the N-location is in a \"quiescent\" state.\n    - A value of the form [injR descr] indicates that the RDCSS operation that\n      is identified by descriptor [descr] is ongoing. In that case, descriptor\n      [descr] must point to a tuple [(l_m, m1, n1, n2, p)] for some M-location\n      [l_m], integers [m1], [n1], [n2] and prophecy [p]. An N-location holding\n      a value of the form [injR descr] is in an \"updating\" state. *)\n\n(** As mentioned in the paper, there are minor differences between our version\n    of RDCSS and the original one (by Harris et al.):\n    - In the original version, the RDCSS operation takes as input a descriptor\n      for the operation,  whereas in our version the RDCSS operation allocates\n      the descriptor itself.\n    - In the original version, values (inactive state) and descriptors (active\n      state) are distinguished by looking at their least significant bits. Our\n      version rather relies on injections to avoid bit-level manipulations. *)\n\n(** The [new_rdcss] operation creates a new RDCSS location.  It corresponds to\n    the following pseudo-code:\n<<\n  new_rdcss(n) := ref (injL n)\n>>\n*)\nDefinition new_rdcss : val := λ: \"n\", ref (InjL \"n\").\n\n(** The [complete] function is used internally by the RDCSS operations. It can\n    be expressed using the following pseudo-code:\n<<\n  complete(l_descr, l_n) :=\n    let (l_m, m1, n1, n2, p) := !l_descr;\n    (* data = (l_m, m1, n1, n2, p) *)\n    let tid_ghost = NewProph;\n    let n_new = (if !l_m = m1 then n1 else n2);\n    Resolve (CmpXchg l_n (InjR l_descr) (ref (InjL n_new))) p tid_ghost;\n    #().\n>>\n\n    In this function, we rely on a prophecy variable to emulate a ghost thread\n    identifier. In particular, the corresponding prophecy variable [tid_ghost]\n    is never resolved.  Here, the main reason for using a prophecy variable is\n    that we can use erasure to argue that it has no effect on the code. *)\nDefinition complete : val :=\n  λ: \"l_descr\" \"l_n\",\n    let: \"data\" := !\"l_descr\" in (* data = (l_m, m1, n1, n2, p) *)\n    let: \"l_m\" := Fst (Fst (Fst (Fst (\"data\")))) in\n    let: \"m1\"  := Snd (Fst (Fst (Fst (\"data\")))) in\n    let: \"n1\"  := Snd (Fst (Fst (\"data\"))) in\n    let: \"n2\"  := Snd (Fst (\"data\")) in\n    let: \"p\"   := Snd (\"data\") in\n    (* Create a thread identifier using NewProph. *)\n    let: \"tid_ghost\" := NewProph in\n    let: \"n_new\" := (if: !\"l_m\" = \"m1\" then \"n2\" else \"n1\") in\n    Resolve (CmpXchg \"l_n\" (InjR \"l_descr\") (InjL \"n_new\")) \"p\" \"tid_ghost\";;\n    #().\n\n(** The [get] operation reads the value stored in an RDCSS location previously\n    created using [new_rdcss]. In pseudo-code, it corresponds to:\n<<\n  rec get(l_n) :=\n    match !l_n with\n    | injL n       => n\n    | injR l_descr => complete(l_descr, l_n);\n                      get(l_n)\n    end\n>>\n*)\nDefinition get : val :=\n  rec: \"get\" \"l_n\" :=\n    match: !\"l_n\" with\n      InjL \"n\"    => \"n\"\n    | InjR \"l_descr\" =>\n        complete \"l_descr\" \"l_n\" ;;\n        \"get\" \"l_n\"\n    end.\n\n(** Finally, the [rdcss] operation corresponds to the following pseudo-code:\n<<\n  rdcss(l_m, l_n, m1, n1, n2) :=\n    let p := NewProph;\n    let l_descr := ref (l_m, m1, n1, n2, p);\n    rec rdcss_inner() =\n      let (r, b) := CmpXchg(l_n, InjL n1, InjR l_descr) in\n      match r with\n      | InjL n             =>\n          if b then\n            complete(l_descr, l_n); n1\n          else\n            n\n      | InjR l_descr_other =>\n           complete(l_descr_other, l_n);\n           rdcss_inner()\n      end;\n    rdcss_inner()\n>>\n*)\nDefinition rdcss: val :=\n  λ: \"l_m\" \"l_n\" \"m1\" \"n1\" \"n2\",\n    (* Allocate the descriptor for the operation. *)\n    let: \"p\" := NewProph in\n    let: \"l_descr\" := ref (\"l_m\", \"m1\", \"n1\", \"n2\", \"p\") in\n    (* Attempt to establish the descriptor to make the operation \"active\". *)\n    ( rec: \"rdcss_inner\" \"_\" :=\n        let: \"r\" := CmpXchg \"l_n\" (InjL \"n1\") (InjR \"l_descr\") in\n        match: Fst \"r\" with\n          InjL \"n\" =>\n            (* non-descriptor value read, check if CmpXchg was successful *)\n            if: Snd \"r\" then\n              (* CmpXchg was successful, finish operation *)\n              complete \"l_descr\" \"l_n\" ;; \"n1\"\n            else\n              (* CmpXchg failed, hence we could linearize at the CmpXchg *)\n              \"n\"\n        | InjR \"l_descr_other\" =>\n            (* A descriptor from a concurrent operation was read, try to help\n               and then restart. *)\n            complete \"l_descr_other\" \"l_n\";;\n            \"rdcss_inner\" #()\n        end\n    ) #().\n\n(** ** Proof setup *)\n\nDefinition valUR      := authR $ optionUR $ exclR valO.\nDefinition tokenUR    := exclR unitO.\nDefinition one_shotUR := csumR (exclR unitO) (agreeR unitO).\n\nClass rdcssG Σ := RDCSSG {\n                     rdcss_valG      :> inG Σ valUR;\n                     rdcss_tokenG    :> inG Σ tokenUR;\n                     rdcss_one_shotG :> inG Σ one_shotUR;\n                   }.\n\nDefinition rdcssΣ : gFunctors :=\n  #[GFunctor valUR; GFunctor tokenUR; GFunctor one_shotUR].\n\nInstance subG_rdcssΣ {Σ} : subG rdcssΣ Σ → rdcssG Σ.\nProof. solve_inG. Qed.\n\nSection rdcss.\n  Context {Σ} `{!heapG Σ, !rdcssG Σ, !gcG Σ }.\n  Context (N : namespace).\n\n  Implicit Types γ_n γ_a γ_t γ_s : gname.\n  Implicit Types l_n l_m l_descr : loc.\n  Implicit Types p : proph_id.\n\n  Local Definition descrN := N .@ \"descr\".\n  Local Definition rdcssN := N .@ \"rdcss\".\n\n  (** Logical value for the N-location. *)\n\n  Definition rdcss_state_auth (l_n : loc) (n : val) :=\n    (∃ (γ_n : gname), meta l_n rdcssN γ_n ∗ own γ_n (● Excl' n))%I.\n\n  Definition rdcss_state (l_n : loc) (n : val) :=\n    (∃ (γ_n : gname), meta l_n rdcssN γ_n ∗ own γ_n (◯ Excl' n))%I.\n\n  (** Updating and synchronizing the value RAs *)\n\n  Lemma sync_values l_n (n m : val) :\n    rdcss_state_auth l_n n -∗ rdcss_state l_n m -∗ ⌜n = m⌝.\n  Proof.\n    iIntros \"H● H◯\".\n    iDestruct \"H●\" as (γ) \"[#HMeta H●]\".\n    iDestruct \"H◯\" as (γ') \"[HMeta' H◯]\".\n    iDestruct (meta_agree with \"HMeta' HMeta\") as %->. iClear \"HMeta'\".\n    iCombine \"H●\" \"H◯\" as \"H\". iDestruct (own_valid with \"H\") as \"H\".\n    by iDestruct \"H\" as %[H%Excl_included%leibniz_equiv _]%auth_both_valid.\n  Qed.\n\n  Lemma update_value l_n (n1 n2 m : val) :\n    rdcss_state_auth l_n n1 -∗ rdcss_state l_n n2 ==∗\n      rdcss_state_auth l_n m ∗ rdcss_state l_n m.\n  Proof.\n    iIntros \"H● H◯\".\n    iDestruct \"H●\" as (γ) \"[#HMeta H●]\".\n    iDestruct \"H◯\" as (γ') \"[HMeta' H◯]\".\n    iDestruct (meta_agree with \"HMeta' HMeta\") as %->. iClear \"HMeta'\".\n    iCombine \"H●\" \"H◯\" as \"H\".\n    iApply (bupd_mono (meta l_n rdcssN γ ∗ own γ (● Excl' m)\n                                         ∗ own γ (◯ Excl' m)))%I.\n    { iIntros \"(#HMeta & H● & H◯)\". iSplitL \"H●\"; iExists γ; by iFrame. }\n    iApply bupd_frame_l. iSplit; first done.\n    rewrite -own_op. iApply (own_update with \"H\").\n    by apply auth_update, option_local_update, exclusive_local_update.\n  Qed.\n\n  (** Definition of the invariant *)\n\n  (** Extract the [tid] of the winner (i.e., the first thread that preforms a\n      CAS) from the prophecy. *)\n  Fixpoint proph_extract_winner (pvs : list (val * val)) : option proph_id :=\n    match pvs with\n    | (_, LitV (LitProphecy tid)) :: _  => Some tid\n    | _                                 => None\n    end.\n\n  Inductive abstract_state : Set :=\n    | Quiescent : val → abstract_state\n    | Updating  : loc → loc → val → val → val → proph_id → abstract_state.\n\n  Definition state_to_val (s : abstract_state) : val :=\n    match s with\n    | Quiescent n                => InjLV n\n    | Updating l_descr _ _ _ _ _ => InjRV #l_descr\n    end.\n\n  Definition own_token γ := (own γ (Excl ()))%I.\n\n  Definition pending_state P (n1 : val) (proph_winner : option proph_id) tid_ghost_winner l_n γ_a :=\n    (P ∗ ⌜from_option (λ p, p = tid_ghost_winner) True proph_winner⌝ ∗\n     rdcss_state_auth l_n n1 ∗ own_token γ_a)%I.\n\n  (* After the prophecy said we are going to win the race, we commit and run the AU,\n     switching from [pending] to [accepted]. *)\n  Definition accepted_state Q (proph_winner : option proph_id) (tid_ghost_winner : proph_id) :=\n    ((∃ vs, proph tid_ghost_winner vs) ∗\n     Q ∗ ⌜from_option (λ p, p = tid_ghost_winner) True proph_winner⌝)%I.\n\n  (* The same thread then wins the CmpXchg and moves from [accepted] to [done].\n     Then, the [γ_t] token guards the transition to take out [Q].\n     Remember that the thread winning the CmpXchg might be just helping.  The token\n     is owned by the thread whose request this is.\n     In this state, [tid_ghost_winner] serves as a token to make sure that\n     only the CmpXchg winner can transition to here, and owning half of [l_descr] serves as a\n     \"location\" token to ensure there is no ABA going on. Notice how [rdcss_inv]\n     owns *more than* half of its [l_descr] in the Updating state,\n     which means we know that the [l_descr] there and here cannot be the same. *)\n  Definition done_state Qn l_descr (tid_ghost_winner : proph_id) γ_t γ_a :=\n    ((Qn ∨ own_token γ_t) ∗ (∃ vs, proph tid_ghost_winner vs) ∗\n     l_descr ↦{1/2} - ∗ own_token γ_a)%I.\n\n  (* Invariant expressing the descriptor protocol.\n     - We always need the [proph] in here so that failing threads coming late can\n       always resolve their stuff.\n     - We need a way for anyone who has observed the [done] state to\n       prove that we will always remain [done]; that's what the one-shot token [γ_s] is for.\n     - [γ_a] is a token which is owned by the invariant in [pending] and [done] but not in [accepted].\n       This permits the CmpXchg winner to gain ownership of the token when moving to [accepted] and\n       hence ensures that no other thread can move from [accepted] to [done].\n       Side remark: One could get rid of this token if one supported fractional ownership of\n                    prophecy resources by only keeping half permission to the prophecy resource\n                    in the invariant in [accepted] while the other half would be kept by the CmpXchg winner.\n   *)\n  Definition descr_inv P Q p n l_n l_descr (tid_ghost_winner : proph_id) γ_t γ_s γ_a: iProp Σ :=\n    (∃ vs, proph p vs ∗\n      (own γ_s (Cinl $ Excl ()) ∗\n       (l_n ↦{1/2} InjRV #l_descr ∗ ( pending_state P n (proph_extract_winner vs) tid_ghost_winner l_n γ_a\n        ∨ accepted_state (Q n) (proph_extract_winner vs) tid_ghost_winner ))\n       ∨ own γ_s (Cinr $ to_agree ()) ∗ done_state (Q n) l_descr tid_ghost_winner γ_t γ_a))%I.\n\n  Local Hint Extern 0 (environments.envs_entails _ (descr_inv _ _ _ _ _ _ _ _ _ _)) => unfold descr_inv.\n\n  Definition pau P Q l_n l_m m1 n1 n2 :=\n    (▷ P -∗ ◇ AU << ∀ (m n : val), (gc_mapsto l_m m) ∗ rdcss_state l_n n >> @ (⊤∖↑N)∖↑gcN, ∅\n                 << (gc_mapsto l_m m) ∗ (rdcss_state l_n (if (decide ((m = m1) ∧ (n = n1))) then n2 else n)),\n                    COMM Q n >>)%I.\n\n  Definition rdcss_inv l_n :=\n    (∃ (s : abstract_state),\n       l_n ↦{1/2} (state_to_val s) ∗\n       match s with\n       | Quiescent n =>\n           (* (InjLV #n) = state_to_val (Quiescent n) *)\n           (* In this state the CmpXchg which expects to read (InjRV _) in\n              [complete] fails always.*)\n           l_n ↦{1/2} (InjLV n) ∗ rdcss_state_auth l_n n\n        | Updating l_descr l_m m1 n1 n2 p =>\n           ∃ q P Q tid_ghost_winner γ_t γ_s γ_a,\n             (* (InjRV #l_descr) = state_to_val (Updating l_descr l_m m1 n1 n2 p) *)\n             (* There are three pieces of per-[descr]-protocol ghost state:\n             - [γ_t] is a token owned by whoever created this protocol and used\n               to get out the [Q] in the end.\n             - [γ_s] reflects whether the protocol is [done] yet or not.\n             - [γ_a] is a token which is used to ensure that only the CmpXchg winner\n               can move from the [accepted] to the [done] state. *)\n           (* We own *more than* half of [l_descr], which shows that this cannot\n              be the [l_descr] of any [descr] protocol in the [done] state. *)\n             ⌜val_is_unboxed m1⌝ ∗\n             l_descr ↦{1/2 + q} (#l_m, m1, n1, n2, #p)%V ∗\n             inv descrN (descr_inv P Q p n1 l_n l_descr tid_ghost_winner γ_t γ_s γ_a) ∗\n             □ pau P Q l_n l_m m1 n1 n2 ∗ is_gc_loc l_m\n       end)%I.\n\n  Local Hint Extern 0 (environments.envs_entails _ (rdcss_inv _)) => unfold rdcss_inv.\n\n  Definition is_rdcss (l_n : loc) :=\n    (inv rdcssN (rdcss_inv l_n) ∧ gc_inv ∧ ⌜N ## gcN⌝)%I.\n\n  Global Instance is_rdcss_persistent l_n : Persistent (is_rdcss l_n) := _.\n\n  Global Instance rdcss_state_timeless l_n n : Timeless (rdcss_state l_n n) := _.\n\n  Global Instance abstract_state_inhabited: Inhabited abstract_state := populate (Quiescent #0).\n\n  Lemma rdcss_state_exclusive l_n n_1 n_2 :\n    rdcss_state l_n n_1 -∗ rdcss_state l_n n_2 -∗ False.\n  Proof.\n    iIntros \"Hn1 Hn2\".\n    iDestruct \"Hn1\" as (γ_1) \"[#Meta1 Hn1]\".\n    iDestruct \"Hn2\" as (γ_2) \"[#Meta2 Hn2]\".\n    iDestruct (meta_agree with \"Meta1 Meta2\") as %->.\n    by iDestruct (own_valid_2 with \"Hn1 Hn2\") as %?.\n  Qed.\n\n  (** A few more helper lemmas that will come up later *)\n\n  Lemma mapsto_valid_3 l v1 v2 q :\n    l ↦ v1 -∗ l ↦{q} v2 -∗ ⌜False⌝.\n  Proof.\n    iIntros \"Hl1 Hl2\". iDestruct (mapsto_valid_2 with \"Hl1 Hl2\") as %Hv.\n    apply (iffLR (frac_valid' _)) in Hv. by apply Qp_not_plus_q_ge_1 in Hv.\n  Qed.\n\n  (** Once a [descr] protocol is [done] (as reflected by the [γ_s] token here),\n      we can at any later point in time extract the [Q]. *)\n  Lemma state_done_extract_Q P Q p n l_n l_descr tid_ghost γ_t γ_s γ_a :\n    inv descrN (descr_inv P Q p n l_n l_descr tid_ghost γ_t γ_s γ_a) -∗\n    own γ_s (Cinr (to_agree ())) -∗\n    □(own_token γ_t ={⊤}=∗ ▷ (Q n)).\n  Proof.\n    iIntros \"#Hinv #Hs !# Ht\".\n    iInv descrN as (vs) \"(Hp & [NotDone | Done])\".\n    * (* Moved back to NotDone: contradiction. *)\n      iDestruct \"NotDone\" as \"(>Hs' & _ & _)\".\n      iDestruct (own_valid_2 with \"Hs Hs'\") as %?. contradiction.\n    * iDestruct \"Done\" as \"(_ & QT & Hrest)\".\n      iDestruct \"QT\" as \"[Qn | >T]\"; last first.\n      { iDestruct (own_valid_2 with \"Ht T\") as %Contra.\n          by inversion Contra. }\n      iSplitR \"Qn\"; last done. iIntros \"!> !>\". unfold descr_inv.\n      iExists _. iFrame \"Hp\". iRight.\n      unfold done_state. iFrame \"#∗\".\n  Qed.\n\n  (** ** Proof of [complete] *)\n\n  (** The part of [complete] for the succeeding thread that moves from [accepted] to [done] state *)\n  Lemma complete_succeeding_thread_pending γ_t γ_s γ_a l_n P Q p\n        (n1 n : val) (l_descr : loc) (tid_ghost : proph_id) Φ :\n    inv rdcssN (rdcss_inv l_n) -∗\n    inv descrN (descr_inv P Q p n1 l_n l_descr tid_ghost γ_t γ_s γ_a) -∗\n    own_token γ_a -∗\n    (□(own_token γ_t ={⊤}=∗ ▷ (Q n1)) -∗ Φ #()) -∗\n    rdcss_state_auth l_n n -∗\n    WP Resolve (CmpXchg #l_n (InjRV #l_descr) (InjLV n)) #p #tid_ghost ;; #() {{ v, Φ v }}.\n  Proof.\n    iIntros \"#InvC #InvS Token_a HQ Hn●\". wp_bind (Resolve _ _ _)%E.\n    iInv rdcssN as (s) \"(>Hln & Hrest)\".\n    iInv descrN as (vs) \"(>Hp & [NotDone | Done])\"; last first.\n    { (* We cannot be [done] yet, as we own the [γ_a] token that serves\n         as token for that transition. *)\n      iDestruct \"Done\" as \"(_ & _ & _ & _ & >Token_a')\".\n      by iDestruct (own_valid_2 with \"Token_a Token_a'\") as %?.\n    }\n    iDestruct \"NotDone\" as \"(>Hs & >Hln' & [Pending | Accepted])\".\n    { (* We also cannot be [Pending] any more because we own the [γ_a] token. *)\n      iDestruct \"Pending\" as \"[_ >(_ & _ & Token_a')]\".\n      by iDestruct (own_valid_2 with \"Token_a Token_a'\") as %?.\n    }\n    (* So, we are [Accepted]. Now we can show that (InjRV l_descr) = (state_to_val s), because\n       while a [descr] protocol is not [done], it owns enough of\n       the [rdcss] protocol to ensure that does not move anywhere else. *)\n    destruct s as [n' | l_descr' l_m' m1' n1' n2' p'].\n    { simpl. iDestruct (mapsto_agree with \"Hln Hln'\") as %Heq. inversion Heq. }\n    iDestruct (mapsto_agree with \"Hln Hln'\") as %[= ->].\n    simpl.\n    iDestruct \"Hrest\" as (q P' Q' tid_ghost' γ_t' γ_s' γ_a') \"(_ & [>Hld >Hld'] & Hrest)\".\n    (* We perform the CmpXchg. *)\n    iCombine \"Hln Hln'\" as \"Hln\".\n    wp_apply (wp_resolve with \"Hp\"); first done. wp_cmpxchg_suc.\n    iIntros (vs'' ->) \"Hp'\". simpl.\n    (* Update to Done. *)\n    iDestruct \"Accepted\" as \"[Hp_phost_inv [Q Heq]]\".\n    iMod (own_update with \"Hs\") as \"Hs\".\n    { apply (cmra_update_exclusive (Cinr (to_agree ()))). done. }\n    iDestruct \"Hs\" as \"#Hs'\". iModIntro.\n    iSplitL \"Hp_phost_inv Token_a Q Hp' Hld\".\n    (* Update state to Done. *)\n    { eauto 12 with iFrame. }\n    iModIntro. iSplitR \"HQ\".\n    { iNext. iDestruct \"Hln\" as \"[Hln1 Hln2]\". iExists (Quiescent n). by iFrame. }\n    iApply wp_fupd. wp_seq. iApply \"HQ\".\n    iApply state_done_extract_Q; done.\n  Qed.\n\n  (** The part of [complete] for the failing thread *)\n  Lemma complete_failing_thread γ_t γ_s γ_a l_n l_descr P Q p n1 n tid_ghost_inv tid_ghost Φ :\n    tid_ghost_inv ≠ tid_ghost →\n    inv rdcssN (rdcss_inv l_n) -∗\n    inv descrN (descr_inv P Q p n1 l_n l_descr tid_ghost_inv γ_t γ_s γ_a) -∗\n    (□(own_token γ_t ={⊤}=∗ ▷ (Q n1)) -∗ Φ #()) -∗\n    WP Resolve (CmpXchg #l_n (InjRV #l_descr) (InjLV n)) #p #tid_ghost ;; #() {{ v, Φ v }}.\n  Proof.\n    iIntros (Hnl) \"#InvC #InvS HQ\". wp_bind (Resolve _ _ _)%E.\n    iInv rdcssN as (s) \"(>Hln & Hrest)\".\n    iInv descrN as (vs) \"(>Hp & [NotDone | [#Hs Done]])\".\n    { (* [descr] protocol is not done yet: we can show that it\n         is the active protocol still (l = l').  But then the CmpXchg would\n         succeed, and our prophecy would have told us that.\n         So here we can prove that the prophecy was wrong. *)\n        iDestruct \"NotDone\" as \"(_ & >Hln' & State)\".\n        iDestruct (mapsto_agree with \"Hln Hln'\") as %[=->].\n        iCombine \"Hln Hln'\" as \"Hln\".\n        wp_apply (wp_resolve with \"Hp\"); first done; wp_cmpxchg_suc.\n        iIntros (vs'' ->). simpl.\n        iDestruct \"State\" as \"[Pending | Accepted]\".\n        + iDestruct \"Pending\" as \"[_ [Hvs _]]\". iDestruct \"Hvs\" as %Hvs. by inversion Hvs.\n        + iDestruct \"Accepted\" as \"[_ [_ Hvs]]\". iDestruct \"Hvs\" as %Hvs. by inversion Hvs.\n    }\n    (* So, we know our protocol is [Done]. *)\n    (* It must be that (state_to_val s) ≠ (InjRV l_descr) because we are in the failing thread. *)\n    destruct s as [n' | l_descr' l_m' m1' n1' n2' p'].\n    - (* (injL n) is the current value, hence the CmpXchg fails *)\n      (* FIXME: proof duplication *)\n      wp_apply (wp_resolve with \"Hp\"); first done. wp_cmpxchg_fail.\n      iIntros (vs'' ->) \"Hp\". iModIntro.\n      iSplitL \"Done Hp\". { by eauto 12 with iFrame. }\n      iModIntro.\n      iSplitL \"Hln Hrest\". { by eauto 12 with iFrame. }\n      wp_seq. iApply \"HQ\".\n      iApply state_done_extract_Q; done.\n    - (* (injR l_descr') is the current value *)\n      destruct (decide (l_descr' = l_descr)) as [->|Hn].\n      + (* The [descr] protocol is [done] while still being the active protocol\n         of the [rdcss] instance?  Impossible, now we will own more than the whole descriptor location! *)\n        iDestruct \"Done\" as \"(_ & _ & >Hld & _)\".\n        iDestruct \"Hld\" as (v') \"Hld\".\n        iDestruct \"Hrest\" as (q P' Q' tid_ghost' γ_t' γ_s' γ_a') \"(_ & >[Hld' Hld''] & Hrest)\".\n        iDestruct (mapsto_combine with \"Hld Hld'\") as \"[Hld _]\".\n        rewrite Qp_half_half. iDestruct (mapsto_valid_3 with \"Hld Hld''\") as \"[]\".\n      + (* l_descr' ≠ l_descr: The CmpXchg fails. *)\n        wp_apply (wp_resolve with \"Hp\"); first done. wp_cmpxchg_fail.\n        iIntros (vs'' ->) \"Hp\". iModIntro.\n        iSplitL \"Done Hp\". { by eauto 12 with iFrame. }\n        iModIntro.\n        iSplitL \"Hln Hrest\". { by eauto 12 with iFrame. }\n        wp_seq. iApply \"HQ\".\n        iApply state_done_extract_Q; done.\n  Qed.\n\n  (** ** Proof of [complete] *)\n  (* The postcondition basically says that *if* you were the thread to own\n     this request, then you get [Q].  But we also try to complete other\n     thread's requests, which is why we cannot ask for the token\n     as a precondition. *)\n  Lemma complete_spec l_n l_m l_descr (m1 n1 n2 : val) p γ_t γ_s γ_a tid_ghost_inv P Q q :\n    val_is_unboxed m1 →\n    N ## gcN →\n    inv rdcssN (rdcss_inv l_n) -∗\n    inv descrN (descr_inv P Q p n1 l_n l_descr tid_ghost_inv γ_t γ_s γ_a) -∗\n    □ pau P Q l_n l_m m1 n1 n2 -∗\n    is_gc_loc l_m -∗\n    gc_inv -∗\n    {{{ l_descr ↦{q} (#l_m, m1, n1, n2, #p) }}}\n       complete #l_descr #l_n\n    {{{ RET #(); □ (own_token γ_t ={⊤}=∗ ▷(Q n1)) }}}.\n  Proof.\n    iIntros (Hm_unbox Hdisj) \"#InvC #InvS #PAU #isGC #InvGC !>\".\n    iIntros (Φ) \"Hld HQ\".  wp_lam. wp_let. wp_bind (! _)%E.\n    wp_load. iClear \"Hld\". wp_pures. wp_apply wp_new_proph; first done.\n    iIntros (vs_ghost tid_ghost) \"Htid_ghost\". wp_pures. wp_bind (! _)%E.\n    (* open outer invariant *)\n    iInv rdcssN as (s) \"(>Hln & Hrest)\"=>//.\n    (* two different proofs depending on whether we are succeeding thread *)\n    destruct (decide (tid_ghost_inv = tid_ghost)) as [-> | Hnl].\n    - (* we are the succeeding thread *)\n      (* we need to move from [pending] to [accepted]. *)\n      iInv descrN as (vs) \"(>Hp & [(>Hs & >Hln' & [Pending | Accepted]) | [#Hs Done]])\".\n      + (* Pending: update to accepted *)\n        iDestruct \"Pending\" as \"[P >(Hvs & Hn● & Token_a)]\".\n        iDestruct (\"PAU\" with \"P\") as \">AU\".\n        iMod (gc_access with \"InvGC\") as \"Hgc\"; first solve_ndisj.\n        (* open and *COMMIT* AU, sync B location l_n and A location l_m *)\n        iMod \"AU\" as (m' n') \"[CC [_ Hclose]]\".\n        iDestruct \"CC\" as \"[Hgc_lm Hn◯]\".\n        (* sync B location and update it if required *)\n        iDestruct (sync_values with \"Hn● Hn◯\") as %->.\n        iMod (update_value _ _ _ (if decide (m' = m1 ∧ n' = n') then n2 else n') with \"Hn● Hn◯\")\n          as \"[Hn● Hn◯]\".\n        (* get access to A location *)\n        iDestruct (\"Hgc\" with \"Hgc_lm\") as \"[Hl Hgc_close]\".\n        (* read A location *)\n        wp_load.\n        (* sync A location *)\n        iMod (\"Hgc_close\" with \"Hl\") as \"[Hgc_lm Hgc_close]\".\n        (* give back access to A location *)\n        iMod (\"Hclose\" with \"[Hn◯ $Hgc_lm]\") as \"Q\"; first done.\n        iModIntro. iMod \"Hgc_close\" as \"_\".\n        (* close descr inv *)\n        iModIntro. iSplitL \"Q Htid_ghost Hp Hvs Hs Hln'\".\n        { iModIntro. iNext. iExists _. iFrame \"Hp\". eauto 12 with iFrame. }\n        (* close outer inv *)\n        iModIntro. iSplitR \"Token_a HQ Hn●\".\n        { by eauto 12 with iFrame. }\n        iModIntro.\n        destruct (decide (m' = m1)) as [-> | ?];\n        wp_op;\n        case_bool_decide; simplify_eq; wp_if; wp_pures;\n           [rewrite decide_True; last done | rewrite decide_False; last tauto];\n          iApply (complete_succeeding_thread_pending with \"InvC InvS Token_a HQ Hn●\").\n      + (* Accepted: contradiction *)\n        iDestruct \"Accepted\" as \"[>Htid_ghost_inv _]\".\n        iDestruct \"Htid_ghost_inv\" as (p') \"Htid_ghost_inv\".\n        by iDestruct (proph_exclusive with \"Htid_ghost Htid_ghost_inv\") as %?.\n      + (* Done: contradiction *)\n        iDestruct \"Done\" as \"[QT >[Htid_ghost_inv _]]\".\n        iDestruct \"Htid_ghost_inv\" as (p') \"Htid_ghost_inv\".\n        by iDestruct (proph_exclusive with \"Htid_ghost Htid_ghost_inv\") as %?.\n    - (* we are the failing thread *)\n      (* close invariant *)\n      iMod (is_gc_access with \"InvGC isGC\") as (v) \"[Hlm Hclose]\"; first solve_ndisj.\n      wp_load.\n      iMod (\"Hclose\" with \"Hlm\") as \"_\". iModIntro.\n      iModIntro.\n      iSplitL \"Hln Hrest\".\n      { eauto with iFrame. }\n      (* two equal proofs depending on value of m1 *)\n      wp_op.\n      destruct (decide (v = m1)) as [-> | ];\n      case_bool_decide; simplify_eq; wp_if;  wp_pures;\n      by iApply (complete_failing_thread with \"InvC InvS HQ\").\n  Qed.\n\n  (** ** Proof of [rdcss] *)\n  Lemma rdcss_spec (l_n l_m : loc) (m1 n1 n2 : val) :\n    val_is_unboxed m1 →\n    val_is_unboxed (InjLV n1) →\n    is_rdcss l_n -∗\n    <<< ∀ (m n: val), gc_mapsto l_m m ∗ rdcss_state l_n n >>>\n        rdcss #l_m #l_n m1 n1 n2 @((⊤∖↑N)∖↑gcN)\n    <<< gc_mapsto l_m m ∗ rdcss_state l_n (if decide (m = m1 ∧ n = n1) then n2 else n), RET n >>>.\n  Proof.\n    iIntros (Hm1_unbox Hn1_unbox) \"(#InvR & #InvGC & %)\". iIntros (Φ) \"AU\".\n    (* allocate fresh descriptor *)\n    wp_lam. wp_pures. wp_apply wp_new_proph; first done.\n    iIntros (proph_values p) \"Hp\".\n    wp_let. wp_alloc l_descr as \"Hld\". wp_pures.\n    (* invoke inner recursive function [rdcss_inner] *)\n    iLöb as \"IH\".\n    wp_bind (CmpXchg _ _ _)%E.\n    (* open outer invariant for the CmpXchg *)\n    iInv rdcssN as (s) \"(>Hln & Hrest)\".\n    destruct s as [n | l_descr' l_m' m1' n1' n2' p'].\n    - (* l_n ↦ injL n *)\n      (* a non-value descriptor n is currently stored at l_n *)\n      iDestruct \"Hrest\" as \">[Hln' Hn●]\".\n      destruct (decide (n1 = n)) as [-> | Hneq].\n      + (* values match -> CmpXchg is successful *)\n        iCombine \"Hln Hln'\" as \"Hln\".\n        wp_cmpxchg_suc.\n        (* Take a \"peek\" at [AU] and abort immediately to get [gc_is_gc f]. *)\n        iMod \"AU\" as (b' n') \"[[Hf CC] [Hclose _]]\".\n        iDestruct (gc_is_gc with \"Hf\") as \"#Hgc\".\n        iMod (\"Hclose\" with \"[Hf CC]\") as \"AU\"; first by iFrame.\n        (* Initialize new [descr] protocol .*)\n        iDestruct (laterable with \"AU\") as (AU_later) \"[AU #AU_back]\".\n        iMod (own_alloc (Excl ())) as (γ_t) \"Token_t\"; first done.\n        iMod (own_alloc (Excl ())) as (γ_a) \"Token_a\"; first done.\n        iMod (own_alloc (Cinl $ Excl ())) as (γ_s) \"Hs\"; first done.\n        iDestruct \"Hln\" as \"[Hln Hln']\".\n        set (winner := default p (proph_extract_winner proph_values)).\n        iMod (inv_alloc descrN _ (descr_inv AU_later _ _ _ _ _ winner _ _ _)\n              with \"[AU Hs Hp Hln' Hn● Token_a]\") as \"#Hinv\".\n        { iNext. iExists _. iFrame \"Hp\". iLeft. iFrame. iLeft.\n          iFrame. destruct (proph_extract_winner proph_values); simpl; done. }\n        iModIntro. iDestruct \"Hld\" as \"[Hld1 [Hld2 Hld3]]\". iSplitR \"Hld2 Token_t\".\n        { (* close outer invariant *)\n          iNext. iCombine \"Hld1 Hld3\" as \"Hld1\".\n          iExists (Updating l_descr l_m m1 n n2 p).\n          eauto 15 with iFrame. }\n        wp_pures.\n        wp_apply (complete_spec with \"[] [] [] [] [] [$Hld2]\");[ done..|].\n        iIntros \"Ht\". iMod (\"Ht\" with \"Token_t\") as \"Φ\". by wp_seq.\n      + (* values do not match -> CmpXchg fails\n           we can commit here *)\n        wp_cmpxchg_fail.\n        iMod \"AU\" as (m'' n'') \"[[Hm◯ Hn◯] [_ Hclose]]\"; simpl.\n        (* synchronize B location *)\n        iDestruct (sync_values with \"Hn● Hn◯\") as %->.\n        iMod (\"Hclose\" with \"[Hm◯ Hn◯]\") as \"HΦ\".\n        {  destruct (decide _) as [[_ ?] | _]; [done | iFrame ]. }\n        iModIntro. iSplitR \"HΦ\".\n        { iModIntro. iExists (Quiescent n''). iFrame. }\n        wp_pures. iFrame.\n    - (* l_n ↦ injR l_ndescr' *)\n      (* a descriptor l_descr' is currently stored at l_n -> CmpXchg fails\n         try to help the on-going operation *)\n      wp_cmpxchg_fail.\n      iModIntro.\n      (* extract descr invariant *)\n      iDestruct \"Hrest\" as (q P Q tid_ghost γ_t γ_s γ_a)\n                              \"(#Hm1'_unbox & [Hld1 [Hld2 Hld3]] & #InvS & #P_AU & #P_GC)\".\n      iDestruct \"Hm1'_unbox\" as %Hm1'_unbox.\n      iSplitR \"AU Hld2 Hld Hp\".\n      (* close invariant, retain some permission to l_descr', so it can be read later *)\n      { iModIntro. iExists (Updating l_descr' l_m' m1' n1' n2' p'). eauto 15 with iFrame. }\n      wp_pures.\n      wp_apply (complete_spec with \"[] [] [] [] [] [$Hld2]\"); [done..|].\n      iIntros \"_\". wp_seq. wp_pures.\n      iApply (\"IH\" with \"AU Hp Hld\").\n  Qed.\n\n  (** ** Proof of [new_rdcss] *)\n  Lemma new_rdcss_spec (n : val) :\n    N ## gcN → gc_inv -∗\n    {{{ True }}}\n        new_rdcss n\n    {{{ l_n, RET #l_n ; is_rdcss l_n ∗ rdcss_state l_n n }}}.\n  Proof.\n    iIntros (Hdisj) \"#InvGC\". iIntros \"!>\" (Φ) \"_ HΦ\".\n    wp_lam. wp_apply wp_fupd. wp_apply wp_alloc; first done.\n    iIntros (l_n) \"[Hln HMeta]\".\n    iMod (own_alloc (● Excl' n  ⋅ ◯ Excl' n)) as (γ_n) \"[Hn● Hn◯]\";\n      first by apply auth_both_valid.\n    iMod (meta_set _ l_n γ_n rdcssN with \"HMeta\") as \"#HMeta\"; first done.\n    iMod (inv_alloc rdcssN _ (rdcss_inv l_n)\n      with \"[Hln Hn●]\") as \"#InvR\".\n    { iDestruct \"Hln\" as \"[Hln1 Hln2]\". iExists (Quiescent n).\n      iFrame \"Hln1 Hln2\". iExists γ_n. by iFrame. }\n    iModIntro. iApply (\"HΦ\" $! l_n).\n    iSplit; first by iFrame \"InvR InvGC\".\n    iExists γ_n. by iFrame.\n  Qed.\n\n  (** ** Proof of [get] *)\n  Lemma get_spec l_n :\n    is_rdcss l_n -∗\n    <<< ∀ (n : val), rdcss_state l_n n >>>\n        get #l_n @(⊤∖↑N)\n    <<< rdcss_state l_n n, RET n >>>.\n  Proof.\n    iIntros \"(#InvR & #InvGC & %)\" (Φ) \"AU\". iLöb as \"IH\".\n    wp_lam. wp_bind (! _)%E. iInv rdcssN as (s) \"(>Hln & Hrest)\". wp_load.\n    destruct s as [n | l_descr l_m m1 n1 n2 p].\n    - iMod \"AU\" as (au_n) \"[Hn◯ [_ Hclose]]\".\n      iDestruct \"Hrest\" as \"[Hln' Hn●]\".\n      iDestruct (sync_values with \"Hn● Hn◯\") as %->.\n      iMod (\"Hclose\" with \"Hn◯\") as \"HΦ\".\n      iModIntro. iSplitR \"HΦ\". { iExists (Quiescent au_n). iFrame. }\n      wp_match. iApply \"HΦ\".\n    - iDestruct \"Hrest\" as (q P Q tid_ghost γ_t γ_s γ_a)\n        \"(% & [Hld [Hld' Hld'']] & #InvS & #PAU & #GC)\".\n      iModIntro. iSplitR \"AU Hld'\".\n      { iExists (Updating l_descr l_m m1 n1 n2 p). eauto 15 with iFrame. }\n      wp_match.\n      wp_apply (complete_spec with \"[] [] [] [] [] [$Hld']\"); [done..|].\n      iIntros \"Ht\". wp_seq. iApply \"IH\". iApply \"AU\".\n  Qed.\n\nEnd rdcss.\n\nDefinition atomic_rdcss `{!heapG Σ, !rdcssG Σ, !gcG Σ} :\n  spec.atomic_rdcss Σ :=\n  {| spec.new_rdcss_spec := new_rdcss_spec;\n     spec.rdcss_spec := rdcss_spec;\n     spec.get_spec := get_spec;\n     spec.rdcss_state_exclusive := rdcss_state_exclusive |}.\n\nTypeclasses Opaque rdcss_state is_rdcss.\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/rdcss/rdcss.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.29774973445369884}}
{"text": "Require Import GhostSimulations.\n\nRequire Import Raft.\n\nRequire Import UpdateLemmas.\nLocal Arguments update {_} {_} {_} _ _ _ _ : simpl never.\n\nRequire Import CommonTheorems.\nRequire Import StateMachineSafetyInterface.\nRequire Import SortedInterface.\nRequire Import UniqueIndicesInterface.\nRequire Import LogMatchingInterface.\nRequire Import MaxIndexSanityInterface.\nRequire Import CommitRecordedCommittedInterface.\nRequire Import LeaderCompletenessInterface.\nRequire Import LastAppliedCommitIndexMatchingInterface.\n\nRequire Import SpecLemmas.\n\nRequire Import AppliedEntriesMonotonicInterface.\n\nSection AppliedEntriesMonotonicProof.\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 {si : sorted_interface}.\n  Context {lmi : log_matching_interface}.\n  Context {uii : unique_indices_interface}.\n  Context {smsi : state_machine_safety_interface}.\n  Context {misi : max_index_sanity_interface}.\n  Context {crci : commit_recorded_committed_interface}.\n  Context {lci : leader_completeness_interface}.\n  Context {lacimi : lastApplied_commitIndex_match_interface}.\n  \n  Lemma findAtIndex_max_thing :\n    forall net h e i,\n      raft_intermediate_reachable net ->\n      In e (log (nwState net h)) ->\n      eIndex e > i ->\n      1 <= i ->\n      exists e',\n        findAtIndex (log (nwState net h)) i = Some e'.\n  Proof using lmi si. \n    intros.\n    find_copy_apply_lem_hyp logs_sorted_invariant.\n    pose proof log_matching_invariant.\n    eapply_prop_hyp raft_intermediate_reachable raft_intermediate_reachable.\n    unfold log_matching, log_matching_hosts, logs_sorted in *.\n    intuition.\n    match goal with\n      | H : forall _ _, _ <= _ <= _ -> _ |- _ =>\n        specialize (H h i);\n          conclude H ltac:(intuition; find_apply_lem_hyp maxIndex_is_max; eauto; omega)\n    end.\n    break_exists_exists. intuition. apply findAtIndex_intro; eauto using sorted_uniqueIndices.\n  Qed.\n  \n  Lemma entries_max_thing :\n    forall net p es,\n      raft_intermediate_reachable net ->\n      In p (nwPackets net) ->\n      mEntries (pBody p) = Some es ->\n      es <> nil ->\n      1 <= maxIndex es.\n  Proof using lmi. \n    intros.\n    find_apply_lem_hyp maxIndex_non_empty.\n    break_exists; intuition; find_rewrite.\n    find_apply_lem_hyp log_matching_invariant.\n    unfold log_matching, log_matching_nw in *.\n    intuition. destruct (pBody p) eqn:?; simpl in *; try congruence.\n    find_apply_hyp_hyp. intuition. find_inversion.\n    find_apply_hyp_hyp. omega.\n  Qed.\n\n  Lemma deghost_snd :\n    forall net h,\n      snd (nwState net h) = nwState (deghost net) h.\n  Proof using. \n    intros. unfold deghost in *. simpl.\n    repeat break_match; subst; simpl.\n    repeat find_rewrite. reflexivity.\n  Qed.\n\n  Lemma lt_committed_committed :\n    forall net e e' t h,\n      log_matching (deghost net) ->\n      committed net e t ->\n      eIndex e' <= eIndex e ->\n      In e (log (snd (nwState net h))) ->\n      In e' (log (snd (nwState net h))) ->\n      committed net e' t.\n  Proof using. \n    intros.\n    unfold committed in *.\n    break_exists_exists. intuition.\n    unfold log_matching, log_matching_hosts in *.\n    intuition. unfold entries_match in *.\n    rewrite deghost_snd in *.\n    match goal with\n      | H : forall _ _ _ _ _, _  |- In _ (_ (_ _ ?x)) =>\n        specialize (H h x e e e')\n    end; intuition eauto.\n  Qed.\n\n  Lemma logs_contiguous :\n    forall net h,\n      raft_intermediate_reachable net ->\n      contiguous_range_exact_lo (log (nwState net h)) 0.\n  Proof using lmi. \n    intros.\n    find_apply_lem_hyp log_matching_invariant.\n    unfold log_matching, log_matching_hosts in *.\n    intuition.\n    unfold contiguous_range_exact_lo.\n    intuition eauto.\n    find_apply_hyp_hyp. intuition.\n  Qed.\n\n  Lemma entries_gt_0 :\n    forall net p es e,\n      raft_intermediate_reachable net ->\n      In p (nwPackets net) ->\n      mEntries (pBody p) = Some es ->\n      In e es ->\n      0 < eIndex e.\n  Proof using lmi. \n    intros.\n    find_apply_lem_hyp log_matching_invariant.\n    unfold log_matching, log_matching_nw in *.\n    intuition. destruct (pBody p) eqn:?; simpl in *; try congruence.\n    find_inversion.\n    find_apply_hyp_hyp. intuition.\n    find_apply_hyp_hyp. omega.\n  Qed.\n\n  Lemma entries_gt_pli :\n    forall net p e t n pli plt es ci,\n      raft_intermediate_reachable net ->\n      In p (nwPackets net) ->\n      pBody p = AppendEntries t n pli plt es ci ->\n      In e es ->\n      pli < eIndex e.\n  Proof using lmi. \n    intros.\n    find_apply_lem_hyp log_matching_invariant.\n    unfold log_matching, log_matching_nw in *.\n    intuition. destruct (pBody p) eqn:?; simpl in *; try congruence.\n    find_inversion.\n    find_apply_hyp_hyp. intuition.\n  Qed.\n  \n  Lemma sorted_app :\n    forall l l',\n      sorted (l ++ l') ->\n      sorted l.\n  Proof using. \n    induction l; simpl in *; intros; intuition eauto.\n    - apply H0. intuition.\n    - apply H0. intuition.\n  Qed.\n  \n  Lemma handleMessage_applied_entries :\n    forall net h h' m st' ms,\n      raft_intermediate_reachable net ->\n      In {| pBody := m; pDst := h; pSrc := h' |} (nwPackets net) ->\n      handleMessage h' h m (nwState net h) = (st', ms) ->\n      applied_entries (nwState net) = applied_entries (update (nwState net) h st').\n  Proof using misi smsi uii lmi si. \n    intros. symmetry.\n    unfold handleMessage in *. break_match; repeat break_let; repeat find_inversion.\n    - apply applied_entries_log_lastApplied_update_same;\n      eauto using handleRequestVote_same_log, handleRequestVote_same_lastApplied.\n    - apply applied_entries_log_lastApplied_update_same;\n      eauto using handleRequestVoteReply_same_log, handleRequestVoteReply_same_lastApplied.\n    - find_copy_eapply_lem_hyp handleAppendEntries_logs_sorted;\n      eauto using logs_sorted_invariant.\n      apply applied_entries_safe_update; eauto using handleAppendEntries_same_lastApplied.\n      find_apply_lem_hyp handleAppendEntries_log_detailed. intuition.\n      + repeat find_rewrite. auto.\n      + subst.\n        find_copy_apply_lem_hyp state_machine_safety_invariant.\n        unfold state_machine_safety in *. intuition.\n        find_copy_apply_lem_hyp max_index_sanity_invariant. intuition.\n        find_copy_apply_lem_hyp logs_sorted_invariant.\n        unfold logs_sorted, maxIndex_sanity in *. intuition.\n        apply removeAfterIndex_same_sufficient; eauto.\n        * intros.\n          copy_eapply_prop_hyp state_machine_safety_nw In;\n            unfold commit_recorded in *.\n            simpl in *; repeat (forwards; eauto; concludes).\n            intuition; try omega;\n            exfalso;\n            find_eapply_lem_hyp findAtIndex_max_thing; eauto; try break_exists; try congruence;\n            eauto using entries_max_thing;\n            find_apply_lem_hyp logs_contiguous; auto; omega.\n        * intros.\n          find_copy_apply_lem_hyp log_matching_invariant.\n          unfold log_matching, log_matching_hosts in *. intuition.\n          match goal with\n            | H : forall _ _, _ <= _ <= _ -> _ |- _ => specialize (H h (eIndex e));\n                forward H\n          end;\n            copy_eapply_prop_hyp log_matching_nw AppendEntries; eauto;\n            repeat (forwards; [intuition eauto; omega|]; concludes);\n            intuition; [eapply le_trans; eauto|].\n          match goal with\n            | H : exists _, _ |- _ => destruct H as [e']\n          end.\n          intuition.\n          copy_eapply_prop_hyp state_machine_safety_nw In;\n            unfold commit_recorded in *;\n            simpl in *; repeat (forwards; [intuition eauto; omega|]; concludes).\n          match goal with H : _ /\\ (_ \\/ _) |- _ => clear H end.\n          intuition; try omega;\n          [|find_copy_apply_lem_hyp UniqueIndices_invariant;\n             unfold UniqueIndices in *; intuition;\n             eapply rachet; [symmetry|idtac|idtac|idtac|idtac]; eauto].\n          exfalso.\n          find_eapply_lem_hyp findAtIndex_max_thing; eauto; try break_exists; try congruence;\n          eauto using entries_max_thing.\n      + repeat find_rewrite.\n        find_copy_apply_lem_hyp state_machine_safety_invariant.\n        find_copy_apply_lem_hyp max_index_sanity_invariant.\n        unfold state_machine_safety, maxIndex_sanity in *. intuition.\n        find_copy_apply_lem_hyp logs_sorted_invariant.\n        unfold logs_sorted in *. intuition.\n        eapply removeAfterIndex_same_sufficient'; eauto using logs_contiguous.\n        * intros. eapply entries_gt_0; intuition eauto.\n        * intros.\n          copy_eapply_prop_hyp state_machine_safety_nw In;\n            unfold commit_recorded in *;\n            simpl in *; repeat (forwards; [intuition eauto; omega|]; concludes).\n          match goal with H : _ /\\ (_ \\/ _) |- _ => clear H end.\n          intuition; try omega; try solve [find_apply_lem_hyp logs_contiguous; auto; omega].\n          exfalso.\n          subst.\n          break_exists. intuition.\n          find_false.\n          find_apply_lem_hyp maxIndex_non_empty.\n          break_exists. intuition. repeat find_rewrite.\n          f_equal.\n          find_apply_lem_hyp findAtIndex_elim. intuition.\n          eapply uniqueIndices_elim_eq with (xs := log st'); eauto using sorted_uniqueIndices.\n          unfold state_machine_safety_nw in *.\n          eapply_prop_hyp commit_recorded In; intuition; eauto; try omega;\n          try solve [find_apply_lem_hyp logs_contiguous; auto; omega].\n          unfold commit_recorded. intuition.\n      + repeat find_rewrite.\n        find_copy_apply_lem_hyp logs_sorted_invariant.\n        unfold logs_sorted in *. intuition.\n        eapply removeAfterIndex_same_sufficient'; eauto using logs_contiguous.\n        * { intros. do_in_app. intuition.\n            - eapply entries_gt_0; eauto. reflexivity.\n            - find_apply_lem_hyp removeAfterIndex_in.\n              find_apply_lem_hyp logs_contiguous; eauto.\n          }\n        * find_apply_lem_hyp max_index_sanity_invariant.\n          unfold maxIndex_sanity in *. intuition.\n        * intros.\n          find_copy_apply_lem_hyp state_machine_safety_invariant.\n          unfold state_machine_safety in *. break_and.\n          copy_eapply_prop_hyp state_machine_safety_nw In; eauto.\n          simpl in *. intuition eauto. forwards; eauto. concludes.\n          forwards; [unfold commit_recorded in *; intuition eauto|].\n          concludes.\n          intuition; apply in_app_iff;\n          try solve [right; eapply removeAfterIndex_le_In; eauto; omega];\n          exfalso.\n          find_eapply_lem_hyp findAtIndex_max_thing; eauto using entries_max_thing.\n          break_exists; congruence.\n      + break_exists. intuition. subst.\n        repeat find_rewrite.\n        find_copy_apply_lem_hyp logs_sorted_invariant.\n        unfold logs_sorted in *. intuition.\n        eapply removeAfterIndex_same_sufficient'; eauto using logs_contiguous.\n        * { intros. do_in_app. intuition.\n            - eapply entries_gt_0; eauto. reflexivity.\n            - find_apply_lem_hyp removeAfterIndex_in.\n              find_apply_lem_hyp logs_contiguous; eauto.\n          }\n        * find_apply_lem_hyp max_index_sanity_invariant.\n          unfold maxIndex_sanity in *. intuition.\n        * {\n            intros.\n            find_copy_apply_lem_hyp state_machine_safety_invariant.\n            unfold state_machine_safety in *. break_and.\n            copy_eapply_prop_hyp state_machine_safety_nw In; eauto.\n            simpl in *. intuition eauto. forwards; eauto. concludes.\n            forwards; [unfold commit_recorded in *; intuition eauto|].\n            concludes.\n            intuition; apply in_app_iff;\n            try solve [right; eapply removeAfterIndex_le_In; eauto; omega].\n            subst.\n            find_apply_lem_hyp maxIndex_non_empty.\n            break_exists. intuition. repeat find_rewrite.\n            find_apply_lem_hyp findAtIndex_elim. intuition.\n            find_false. f_equal.\n            eapply uniqueIndices_elim_eq with (xs := log (nwState net h));\n              eauto using sorted_uniqueIndices.\n            unfold state_machine_safety_nw in *.\n            eapply rachet; eauto using sorted_app, sorted_uniqueIndices.\n            copy_eapply_prop_hyp commit_recorded In; intuition; eauto; try omega;\n            unfold commit_recorded; intuition.\n            - exfalso.\n              pose proof entries_gt_pli.\n              eapply_prop_hyp AppendEntries AppendEntries;\n                [|idtac|simpl; eauto|]; eauto. omega.\n            -  exfalso.\n              pose proof entries_gt_pli.\n              eapply_prop_hyp AppendEntries AppendEntries;\n                [|idtac|simpl; eauto|]; eauto. omega.\n          }\n    - apply applied_entries_log_lastApplied_update_same;\n      eauto using handleAppendEntriesReply_same_log, handleAppendEntriesReply_same_lastApplied.\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  Lemma handleInput_applied_entries :\n    forall net h inp os st' ms,\n      raft_intermediate_reachable net ->\n      handleInput h inp (nwState net h) = (os, st', ms) ->\n      applied_entries (nwState net) = applied_entries (update (nwState net) h st').\n  Proof using misi. \n    intros. symmetry.\n    unfold handleInput in *. break_match; repeat break_let; repeat find_inversion.\n    - apply applied_entries_log_lastApplied_update_same;\n      eauto using handleTimeout_log, handleTimeout_lastApplied.\n    - apply applied_entries_safe_update; eauto using handleClientRequest_lastApplied.\n\n      destruct (log st') using (handleClientRequest_log_ind ltac:(eauto)); auto.\n\n      simpl in *. break_if; auto.\n      exfalso.\n      do_bool.\n      find_apply_lem_hyp max_index_sanity_invariant.\n      unfold maxIndex_sanity, maxIndex_lastApplied in *.\n      intuition.\n      match goal with\n        | H : forall _, _ |- _ => specialize (H h)\n      end. omega.\n  Qed.\n\n  Ltac update_destruct_hyp :=\n    match goal with\n    | [ _ : context [ update _ ?y _ ?x ] |- _ ] => destruct (name_eq_dec y x)\n    end.\n\n  Lemma doGenericServer_applied_entries :\n    forall ps h sigma os st' ms,\n      raft_intermediate_reachable (mkNetwork ps sigma) ->\n      doGenericServer h (sigma h) = (os, st', ms) ->\n      exists es, applied_entries (update sigma h st') = (applied_entries sigma) ++ es.\n  Proof using lacimi si. \n    intros.\n    unfold doGenericServer in *. break_let. find_inversion.\n    use_applyEntries_spec. subst. simpl in *. unfold raft_data in *.\n    simpl in *.\n    break_if; [|rewrite applied_entries_safe_update; simpl in *; eauto using app_nil_r].\n    do_bool.\n    match goal with\n      | |- context [update ?sigma ?h ?st] => pose proof applied_entries_update sigma h st\n    end.\n    simpl in *. concludes. intuition.\n    - find_rewrite. eauto using app_nil_r.\n    - pose proof applied_entries_cases sigma.\n      intuition; repeat find_rewrite; eauto.\n      match goal with | H : exists _, _ |- _ => destruct H as [h'] end.\n      repeat find_rewrite.\n      find_apply_lem_hyp argmax_elim. intuition.\n      match goal with\n        | H : forall _: name, _ |- _ =>\n          specialize (H h'); conclude H ltac:(eauto using all_fin_all)\n      end.\n      rewrite_update. simpl in *.\n      update_destruct_hyp; subst; rewrite_update; simpl in *.\n      + apply rev_exists.\n        erewrite removeAfterIndex_le with (i := lastApplied (sigma h')) (j := commitIndex (sigma h')); [|omega].\n        eauto using removeAfterIndex_partition.\n      + apply rev_exists.\n        match goal with\n          | _ : ?h <> ?h' |- exists _, removeAfterIndex ?l (commitIndex (?sigma ?h)) = _ =>\n            pose proof removeAfterIndex_partition (removeAfterIndex l (commitIndex (sigma h)))\n                 (lastApplied (sigma h'))\n        end. break_exists_exists.\n        repeat match goal with | H : applied_entries _ = _ |- _ => clear H end.\n        find_rewrite. f_equal.\n        erewrite <- removeAfterIndex_le; eauto.\n        find_copy_apply_lem_hyp logs_sorted_invariant. unfold logs_sorted in *.\n        intuition. find_copy_apply_lem_hyp lastApplied_commitIndex_match_invariant.\n        eapply removeAfterIndex_same_sufficient; eauto;\n        intros;\n        eapply_prop_hyp lastApplied_commitIndex_match le; intuition eauto.\n  Qed.\n\n  Theorem applied_entries_monotonic' :\n    forall failed net failed' net' os,\n      raft_intermediate_reachable net ->\n      (@step_f _ _ failure_params (failed, net) (failed', net') os) ->\n      exists es,\n        applied_entries (nwState net') = applied_entries (nwState net) ++ es.\n  Proof using lacimi misi smsi uii lmi si. \n    intros. match goal with H : step_f _ _ _ |- _ => invcs H end.\n    - unfold RaftNetHandler in *. repeat break_let. subst.\n      find_inversion.\n      match goal with\n        | Hdl : doLeader ?st ?h = _,\n          Hdgs : doGenericServer ?h ?st' = _ |- context [update (nwState ?net) ?h ?st''] =>\n          replace st with (update (nwState net) h st h) in Hdl by eauto using update_eq;\n            replace st' with (update (update (nwState net) h st) h st' h) in Hdgs by eauto using update_eq;\n            let H := fresh \"H\" in\n            assert (update (nwState net) h st'' =\n                    update (update (update (nwState net) h st) h st') h st'') by (repeat rewrite update_overwrite; auto); unfold data in *; simpl in *; rewrite H; clear H\n      end.\n      find_copy_apply_lem_hyp doLeader_appliedEntries.\n      find_copy_eapply_lem_hyp RIR_handleMessage; eauto.\n      find_eapply_lem_hyp RIR_doLeader; simpl in *; eauto.\n      find_apply_lem_hyp handleMessage_applied_entries; auto; [|destruct p; find_rewrite; in_crush].\n      unfold raft_data in *. simpl in *. unfold raft_data in *. simpl in *.\n      match goal with\n        | H : applied_entries (update (update _ _ _) _ _) =\n              applied_entries (update _ _ _) |- _ =>\n          symmetry in H\n      end.\n      repeat find_rewrite.\n      repeat match goal with H : applied_entries _ = applied_entries _ |- _ => clear H end.\n      eauto using doGenericServer_applied_entries.\n    - unfold RaftInputHandler in *. repeat break_let. subst.\n      find_inversion.\n      match goal with\n        | Hdgs : doGenericServer ?h ?st' = _,\n          Hdl : doLeader ?st ?h = _ |- context [update (nwState ?net) ?h ?st''] =>\n          replace st with (update (nwState net) h st h) in Hdl by eauto using update_eq;\n            replace st' with (update (update (nwState net) h st) h st' h) in Hdgs by eauto using update_eq;\n            let H := fresh \"H\" in\n            assert (update (nwState net) h st'' =\n                    update (update (update (nwState net) h st) h st') h st'') by (repeat rewrite update_overwrite; auto); unfold data in *; simpl in *; rewrite H; clear H\n      end.\n      find_copy_apply_lem_hyp doLeader_appliedEntries.\n      find_copy_eapply_lem_hyp RIR_handleInput; eauto.\n      find_eapply_lem_hyp RIR_doLeader; simpl in *; eauto.      \n      find_apply_lem_hyp handleInput_applied_entries; auto.\n      unfold raft_data in *. simpl in *. unfold raft_data in *. simpl in *.\n      match goal with\n        | H : applied_entries (update (update _ _ _) _ _) =\n              applied_entries (update _ _ _) |- _ =>\n          symmetry in H\n      end.\n      repeat find_rewrite.\n      repeat match goal with H : applied_entries _ = applied_entries _ |- _ => clear H end.\n      eauto using doGenericServer_applied_entries.\n    - exists nil; intuition.\n    - exists nil; intuition.\n    - exists nil; intuition.\n    - exists nil.\n      rewrite app_nil_r.\n      apply applied_entries_log_lastApplied_same;\n        intros; unfold reboot in *; break_if; simpl; auto.\n  Qed.\n\n  Theorem applied_entries_monotonic :\n    forall e failed net failed' net' os,\n      raft_intermediate_reachable net ->\n      (@step_f _ _ failure_params (failed, net) (failed', net') os) ->\n      In e (applied_entries (nwState net)) ->\n      In e (applied_entries (nwState net')).\n  Proof using lacimi misi smsi uii lmi si. \n    intros. find_eapply_lem_hyp applied_entries_monotonic'; eauto.\n    break_exists. find_rewrite. in_crush.\n  Qed.\n\n  Instance aemi : applied_entries_monotonic_interface.\n  Proof.\n    split;\n    eauto using applied_entries_monotonic,\n                applied_entries_monotonic'.\n  Qed.\n\nEnd AppliedEntriesMonotonicProof.", "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/AppliedEntriesMonotonicProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.685949467848392, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.29768935483829984}}
{"text": "\n(* Distributed under the terms of the MIT license. *)\nFrom Coq Require Import Utf8 CRelationClasses ProofIrrelevance.\nFrom MetaCoq.Template Require Import config Universes utils BasicAst.\nFrom MetaCoq.PCUIC Require Import PCUICAst PCUICAstUtils PCUICTactics PCUICInduction\n     PCUICReflect PCUICLiftSubst PCUICSigmaCalculus\n     PCUICUnivSubst PCUICTyping PCUICUnivSubstitutionConv PCUICUnivSubstitutionTyp\n     PCUICCumulativity PCUICPosition PCUICEquality\n     PCUICInversion PCUICCumulativity PCUICReduction\n     PCUICCasesContexts\n     PCUICConfluence PCUICParallelReductionConfluence PCUICConversion PCUICContextConversion\n     PCUICContextConversionTyp\n     PCUICWeakeningEnvConv PCUICWeakeningEnvTyp\n     PCUICClosed PCUICClosedTyp PCUICSubstitution PCUICContextSubst\n     PCUICWellScopedCumulativity\n     PCUICWeakeningConv PCUICWeakeningTyp PCUICGeneration PCUICUtils PCUICContexts\n     PCUICArities PCUICSpine.\n\nRequire Import Equations.Prop.DepElim.\nRequire Import Equations.Type.Relation_Properties.\nFrom Equations Require Import Equations.\nRequire Import ssreflect ssrbool.\n\nImplicit Types (cf : checker_flags) (Σ : global_env_ext).\n\nInductive tele_inst {cf:checker_flags} Σ (Γ : context) : list term -> telescope -> Type :=\n| tele_inst_empty : tele_inst Σ Γ [] []\n| tele_inst_ass Δ s na t T :\n  Σ ;;; Γ |- t : T ->\n  tele_inst Σ Γ s (subst_telescope [t] 0 Δ) ->\n  tele_inst Σ Γ (t :: s) (Δ ,, vass na T)\n| tele_inst_def Δ s na t T :\n  tele_inst Σ Γ s (subst_telescope [t] 0 Δ) ->\n  tele_inst Σ Γ s (Δ ,, vdef na t T).\n\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/PCUICTelescopes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2976840574842258}}
{"text": "From isla Require Import opsem.\n\nDefinition a740c : isla_trace :=\n  Smt (DeclareConst 38%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"R0\" [] (RegVal_Base (Val_Symbolic 38%Z)) Mk_annot :t:\n  Smt (DefineConst 39%Z (Val (Val_Symbolic 38%Z) Mk_annot)) Mk_annot :t:\n  Smt (DefineConst 44%Z (Manyop (Bvmanyarith Bvadd) [Manyop (Bvmanyarith Bvadd) [Unop (ZeroExtend 64%N) (Val (Val_Symbolic 39%Z) Mk_annot) Mk_annot; Val (Val_Bits (BV 128%N 0xffffffffffffffe9%Z)) Mk_annot] Mk_annot; Val (Val_Bits (BV 128%N 0x1%Z)) Mk_annot] Mk_annot)) Mk_annot :t:\n  Smt (DefineConst 48%Z (Unop (Extract 63%N 0%N) (Val (Val_Symbolic 44%Z) Mk_annot) Mk_annot)) Mk_annot :t:\n  Smt (DefineConst 61%Z (Manyop Concat [Manyop Concat [Manyop Concat [Manyop (Bvmanyarith Bvor) [Manyop (Bvmanyarith Bvand) [Val (Val_Bits (BV 1%N 0x0%Z)) Mk_annot; Unop (Bvnot) (Val (Val_Bits (BV 1%N 0x1%Z)) Mk_annot) Mk_annot] Mk_annot; Unop (Extract 0%N 0%N) (Binop ((Bvarith Bvlshr)) (Val (Val_Symbolic 48%Z) Mk_annot) (Unop (Extract 63%N 0%N) (Val (Val_Bits (BV 128%N 0x3f%Z)) Mk_annot) Mk_annot) Mk_annot) Mk_annot] Mk_annot; Ite (Binop (Eq) (Val (Val_Symbolic 48%Z) Mk_annot) (Val (Val_Bits (BV 64%N 0x0%Z)) Mk_annot) Mk_annot) (Val (Val_Bits (BV 1%N 0x1%Z)) Mk_annot) (Val (Val_Bits (BV 1%N 0x0%Z)) Mk_annot) Mk_annot] Mk_annot; Ite (Binop (Eq) (Unop (ZeroExtend 64%N) (Val (Val_Symbolic 48%Z) Mk_annot) Mk_annot) (Val (Val_Symbolic 44%Z) Mk_annot) Mk_annot) (Val (Val_Bits (BV 1%N 0x0%Z)) Mk_annot) (Val (Val_Bits (BV 1%N 0x1%Z)) Mk_annot) Mk_annot] Mk_annot; Ite (Binop (Eq) (Unop (SignExtend 64%N) (Val (Val_Symbolic 48%Z) Mk_annot) Mk_annot) (Manyop (Bvmanyarith Bvadd) [Manyop (Bvmanyarith Bvadd) [Unop (SignExtend 64%N) (Val (Val_Symbolic 39%Z) Mk_annot) Mk_annot; Val (Val_Bits (BV 128%N 0xffffffffffffffffffffffffffffffe9%Z)) Mk_annot] Mk_annot; Val (Val_Bits (BV 128%N 0x1%Z)) Mk_annot] Mk_annot) Mk_annot) (Val (Val_Bits (BV 1%N 0x0%Z)) Mk_annot) (Val (Val_Bits (BV 1%N 0x1%Z)) Mk_annot) Mk_annot] Mk_annot)) Mk_annot :t:\n  Smt (DefineConst 63%Z (Unop (Extract 3%N 3%N) (Val (Val_Symbolic 61%Z) Mk_annot) Mk_annot)) Mk_annot :t:\n  WriteReg \"PSTATE\" [Field \"N\"] (RegVal_Struct [(\"N\", RegVal_Base (Val_Symbolic 63%Z))]) Mk_annot :t:\n  Smt (DefineConst 64%Z (Unop (Extract 2%N 2%N) (Val (Val_Symbolic 61%Z) Mk_annot) Mk_annot)) Mk_annot :t:\n  WriteReg \"PSTATE\" [Field \"Z\"] (RegVal_Struct [(\"Z\", RegVal_Base (Val_Symbolic 64%Z))]) Mk_annot :t:\n  Smt (DefineConst 65%Z (Unop (Extract 1%N 1%N) (Val (Val_Symbolic 61%Z) Mk_annot) Mk_annot)) Mk_annot :t:\n  WriteReg \"PSTATE\" [Field \"C\"] (RegVal_Struct [(\"C\", RegVal_Base (Val_Symbolic 65%Z))]) Mk_annot :t:\n  Smt (DefineConst 66%Z (Unop (Extract 0%N 0%N) (Val (Val_Symbolic 61%Z) Mk_annot) Mk_annot)) Mk_annot :t:\n  WriteReg \"PSTATE\" [Field \"V\"] (RegVal_Struct [(\"V\", RegVal_Base (Val_Symbolic 66%Z))]) Mk_annot :t:\n  Smt (DeclareConst 67%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"_PC\" [] (RegVal_Base (Val_Symbolic 67%Z)) Mk_annot :t:\n  Smt (DefineConst 68%Z (Manyop (Bvmanyarith Bvadd) [Val (Val_Symbolic 67%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 68%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/a740c.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2976840574842257}}
{"text": "From Coq.Lists Require Import List.\nFrom Equations Require Import Equations.\n\n(* This type is from VST: https://github.com/PrincetonUniversity/VST/blob/v2.1/floyd/compact_prod_sum.v#L6 *)\nFixpoint compact_prod (T: list Type): Type :=\n  match T with\n  | nil => unit\n  | t :: nil => t\n  | t :: T0 => (t * compact_prod T0)%type\n  end.\n\n(* The rest is a nonsensical, just to give a minimalistic reproducible example *)\nInductive foo :=\n| Nat : foo -> nat -> foo\n| List : list foo -> foo.\n\nEquations foo_type (ft:foo) : Type :=\n  foo_type (Nat f _) := foo_type f;\n  foo_type (List fs) := compact_prod (List.map foo_type fs).\nTransparent foo_type.\n\n(* val was moved into the result type, rather than being an argument, to work around issues #73 and #85 *)\nEquations sum (fx:foo) : forall (val:foo_type fx), nat := {\n  sum (Nat f _) := fun val => sum f val;\n  sum (List ff) := fun val => sum_list ff val }\n\nwhere sum_list (fs : list foo) (vval: compact_prod (map foo_type fs)) : nat := {\n  sum_list nil vval := 0;\n  (* The \"with clause\" below is there to work around issue #78 *)\n  sum_list (cons hd tl) val1 with fun val => sum_list tl val => {\n    sum_list (cons hd nil) val1 _ := sum hd val1;\n    sum_list (cons hd _) val1 sumtl := sum hd (fst val1) + sumtl (snd val1)}}.\n", "meta": {"author": "mattam82", "repo": "Coq-Equations", "sha": "5603bfff39f3866eed8f010591b5503d5776fa4e", "save_path": "github-repos/coq/mattam82-Coq-Equations", "path": "github-repos/coq/mattam82-Coq-Equations/Coq-Equations-5603bfff39f3866eed8f010591b5503d5776fa4e/test-suite/issues/issue93.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2976840509151863}}
{"text": "Require Import lemmasfortoptheo. \nRequire Import ucos_include.\nRequire Import oscorrectness. \n\nImport DeprecatedTactic.\n\nLemma join_get_set_eq:\n  forall (A B T:Type) (X:PermMap A B T) O1 O2 O O' a b b',\n    usePerm = false ->\n    join O1 O2 O ->\n    get O1 a = Some b ->\n    join (set O1 a b') O2 O' ->\n    O' = set O a b'.\n  intros.\n  assert (join (set O1 a b') O2 (set O a b')).\n  {\n    clear H2.\n    geat.\n  }\n  eapply map_join_deter; eauto.\nQed.\n\nLemma join_get_set_eq_2:\n  forall (A B T:Type) (X:PermMap A B T) O1 O2 O O' a b b' a' c c',\n    usePerm = false ->\n    join O1 O2 O ->\n    get O1 a = Some b ->\n    get O1 a' = Some c -> \n    join (set (set O1 a b') a' c') O2 O' ->\n    O' = set (set O a b') a' c'.\n  intros.\n  Ltac infer ::= infer_v.\n  hy.\n  Ltac infer ::= infer_q.\nQed.\n\nLemma join_get_set_eq_3\n: forall (A B T : Type) (X : PermMap A B T) (O1 O2 O O' : T) \n         (a : A) (b b' : B) (a' : A) (c c' : B) a'' d d',\n    usePerm = false ->\n    join O1 O2 O ->\n    get O1 a = Some b ->\n    get O1 a' = Some c ->\n    get O1 a'' = Some d ->\n    join (set ((set (set O1 a b') a' c')) a'' d') O2 O' -> O' = set (set (set O a b') a' c') a'' d'.\n  intros.\n  Ltac infer ::= infer_v.\n  hy.\n  Ltac infer ::= infer_q.\nQed. \n\nDefinition WAIT_OWNER t t_owner tls els:=\n  exists qid p v m p_owner wl p_q,\n    TcbMod.get tls t = Some (p,wait (os_stat_mutexsem qid) v,m) /\\\n    EcbMod.get els qid = Some (absmutexsem p_q (Some (t_owner,p_owner)),wl).\n\nInductive WAIT_CHAIN: tid -> tid -> TcbMod.map ->  EcbMod.map -> Prop :=\n| wait_O: forall t t_owner tls els, WAIT_OWNER t t_owner tls els /\\ t <> t_owner  ->\n                     WAIT_CHAIN t t_owner tls els\n| wait_S: forall t t_owner tls els t', WAIT_OWNER t t' tls els -> WAIT_CHAIN t' t_owner tls els ->\n                     WAIT_CHAIN t t_owner tls els.\n\nDefinition IS_OWNER t_owner qid els :=\n  exists p_q p_owner wl, EcbMod.get els qid =  Some (absmutexsem p_q (Some (t_owner,p_owner)),wl).\n\nDefinition IS_OWNER_P t_owner qid els p_owner:=\n  exists p_q wl, EcbMod.get els qid =  Some (absmutexsem p_q (Some (t_owner,p_owner)),wl).\n\nDefinition IS_WAITING t els:=\n  exists qid p_q owner wl, EcbMod.get els qid =  Some (absmutexsem p_q owner,wl) /\\ In t wl.\n\nDefinition IS_WAITING_E t eid els:=\n  exists p_q owner wl, EcbMod.get els eid =  Some (absmutexsem p_q owner,wl) /\\ In t wl.\n\nDefinition NO_NEST_PENDING tls els:=\n  forall t qid,\n    TcbMod.get tls t <> None ->\n    IS_OWNER t qid els ->\n    (~ IS_WAITING t els /\\ ~ exists qid', qid <> qid' /\\ IS_OWNER t qid' els).\n\n\nDefinition NO_NEST_PENDING_O O:=\n  forall els tls,\n    OSAbstMod.get O absecblsid = Some (absecblist els) ->\n    OSAbstMod.get O abtcblsid = Some (abstcblist tls) ->\n    NO_NEST_PENDING tls els.\n\nDefinition GET_OP t tls els p :=\n  TcbMod.get tls t <> None ->\n  (exists qid, IS_OWNER_P t qid els p) \\/\n  ((~ exists qid, IS_OWNER t qid els) /\\ exists st msg, TcbMod.get tls t = Some (p,st,msg)).\n\n\nDefinition HighestRdy tls t :=\n  exists prio msg0,\n    TcbMod.get tls t = Some (prio, rdy, msg0) /\\\n    (forall (i : tid) (prio' : priority) (msg' : msg),\n       i <> t ->\n       TcbMod.get tls i = Some (prio', rdy, msg') ->\n       Int.ltu prio prio' = true).\n\n\nDefinition WEAK_PIF (O:osabst) :=\n  forall els tls ct p_ct,\n    OSAbstMod.get O absecblsid = Some (absecblist els) ->\n    OSAbstMod.get O abtcblsid = Some (abstcblist tls) ->\n    OSAbstMod.get O curtid = Some (oscurt ct) ->\n    GET_OP ct tls els p_ct ->\n    NO_NEST_PENDING tls els ->\n    HighestRdy tls ct ->\n    ~ (exists eid, IS_OWNER ct eid els) ->\n    forall t p_t,\n      t <> ct ->\n      TcbMod.get tls t <> None ->\n      GET_OP t tls els p_t ->\n      IS_WAITING t els ->\n      Int.ltu p_ct p_t = true.\n\nDefinition O_PI tls els :=\n  exists t t_owner p p_owner st st_owner msg msg_owner,\n    WAIT_OWNER t t_owner tls els /\\\n    TcbMod.get tls t = Some (p,st,msg) /\\\n    TcbMod.get tls t_owner = Some (p_owner,st_owner,msg_owner) /\\\n    Int.ltu p p_owner = true.\n\nDefinition O_PIF tls els := ~ O_PI tls els.\n\nDefinition OLD_PIF O:=\n  forall els tls,\n    OSAbstMod.get O absecblsid = Some (absecblist els) ->\n    OSAbstMod.get O abtcblsid = Some (abstcblist tls) ->\n    O_PIF tls els.\n\n\nDefinition PIF (O:osabst) :=\n  forall els tls ct p_ct,\n    OSAbstMod.get O absecblsid = Some (absecblist els) ->\n    OSAbstMod.get O abtcblsid = Some (abstcblist tls) ->\n    OSAbstMod.get O curtid = Some (oscurt ct) ->\n    GET_OP ct tls els p_ct ->\n    HighestRdy tls ct ->\n    ~ (exists eid, IS_OWNER ct eid els) -> \n    forall t p_t,\n      t <> ct ->\n      TcbMod.get tls t <> None ->\n      GET_OP t tls els p_t ->\n      IS_WAITING t els ->\n      Int.ltu p_ct p_t = true.\n\n\n\nDefinition PREEMP O :=\n  forall ct tls ,\n    OSAbstMod.get O abtcblsid = Some (abstcblist tls) ->\n    OSAbstMod.get O curtid = Some (oscurt ct) ->\n    HighestRdy tls ct.\n\n\nDefinition api_spec_list' := \n  (OSMutexAccept, mutexaccapi)\n    :: (OSMutexCreate, mutexcreapi)\n    :: (OSMutexDel, mutexdelapi)\n    :: (OSMutexPend, mutexpendapi)\n    :: (OSMutexPost, mutexpostapi)\n    :: nil.\n\nDefinition api_spec':= convert_api_spec api_spec_list'.\n\nDefinition os_spec' := (api_spec',int_spec,GetHPrio).\n\n\nDefinition GOOD_API_CODE O T :=\n  exists C t,\n    OSAbstMod.get O curtid = Some (oscurt t) /\\\n    TasksMod.get T t = Some C /\\\n    (\n      (exists ke ks vl, C = (curs (hapi_code (spec_prim vl mutexacc_succ)), (ke,ks))) \\/\n      (exists ke ks vl, C = (curs (hapi_code (spec_prim vl mutexcre_succ)), (ke,ks))) \\/\n      (exists ke ks vl, C = (curs (hapi_code (spec_prim vl mutexdel_succ)), (ke,ks))) \\/\n      (exists ke ks vl, C = (curs (hapi_code (spec_prim vl mutexpend_get_succ)), (ke,ks))) \\/\n      (exists ke ks vl s, C = (curs (hapi_code (mutexpend_block_no_lift (|vl|);;s)), (ke,ks))) \\/\n      (exists ke ks vl s, C = (curs (hapi_code (mutexpend_block_lift (|vl|);;s)), (ke,ks))) \\/\n      (exists ke ks vl, C = (curs (hapi_code (mutexpost_nowt_return_prio_succ (|vl|))), (ke,ks))) \\/\n      (exists ke ks vl, C = (curs (hapi_code (mutexpost_nowt_no_return_prio_succ (|vl|))), (ke,ks))) \\/\n      (exists ke ks vl s, C = (curs (hapi_code (mutexpost_exwt_return_prio_succ (|vl|);;s)), (ke,ks))) \\/\n      (exists ke ks vl s, C = (curs (hapi_code (mutexpost_exwt_no_return_prio_succ (|vl|);;s)), (ke,ks)))\\/\n      (exists ke ks s, C = (curs (hapi_code (timetick_spec (|nil|);;s)), (ke,ks)))\\/\n      (exists ke ks s, C = (curs (hapi_code (sched;;s)), (ke,ks)))\n    ).\n\nDefinition rdy_notin_wl tls els :=\n  (forall t p m, TcbMod.get tls t = Some (p,rdy,m) -> ~ IS_WAITING t els) /\\\n  (forall t p m eid tm,TcbMod.get tls t = Some (p,wait (os_stat_mutexsem eid) tm,m) -> IS_WAITING_E t eid els)/\\\n  (forall t eid,  IS_WAITING_E t eid els -> exists p tm m, TcbMod.get tls t = Some (p,wait (os_stat_mutexsem eid) tm,m)) .\n\nDefinition not_in_two_wl els:= forall t,\n                                 ~ exists eid eid', eid <> eid' /\\ IS_WAITING_E t eid els /\\ IS_WAITING_E t eid' els.\n\nDefinition owner_prio_prop tls els:=\n  forall t p st m eid pe po l,\n    TcbMod.get tls t = Some (p,st,m) ->\n    EcbMod.get els eid = Some (absmutexsem pe (Some (t,po)), l) ->\n    (p = pe \\/ p = po) /\\ Int.ltu pe po =true.\n\nDefinition task_stat_prop tls:=\n  forall t p st m,\n    TcbMod.get tls t = Some (p,st,m) ->\n    st = rdy \\/ (exists eid tm, st = wait (os_stat_mutexsem eid) tm).\n\nDefinition op_p_prop tls els :=\n  forall t st p m op,\n    TcbMod.get tls t = Some (p,st,m) ->\n    GET_OP t tls els op ->\n    Int.ltu p op = true \\/ Int.eq p op = true.\n\nDefinition wait_prop tls els:=\n  forall t p m eid tm,\n    TcbMod.get tls t = Some (p,wait (os_stat_mutexsem eid) tm,m) ->\n    exists t' po m, IS_OWNER t' eid els /\\ TcbMod.get tls t' = Some (po,rdy,m) /\\ Int.ltu po p = true /\\\n                    (forall op, GET_OP t tls els op -> op = p).\n\nDefinition no_owner_prio_prop tls els:=\n  forall t p st m  op,\n    TcbMod.get tls t = Some (p,st,m) ->\n    (~exists eid, IS_OWNER t eid els) ->\n    GET_OP t tls els op ->\n    op = p.\n\n    \nDefinition GOOD_ST O :=\n  forall tls els,\n    OSAbstMod.get O absecblsid = Some (absecblist els) ->\n    OSAbstMod.get O abtcblsid = Some (abstcblist tls) ->\n    rdy_notin_wl tls els /\\\n    owner_prio_prop tls els /\\\n    task_stat_prop tls/\\\n    op_p_prop tls els/\\\n    wait_prop tls els/\\\n    no_owner_prio_prop tls els.\n\nLemma joinsig_joinsig_eq:\n  forall tls tls' a b x y,\n    TcbMod.join tls (TcbMod.sig a b ) tls' ->\n    TcbMod.join tls (TcbMod.sig x y) tls' ->\n    a = x /\\ b = y.\nProof.\n  intros.\n  pose proof H a.\n  pose proof H0 a.\n  rewrite TcbMod.get_sig_some in H1.\n  destruct (TcbMod.get tls a);\n    destruct (TcbMod.get (TcbMod.sig x y) a) eqn : eq1;\n    destruct (TcbMod.get tls' a); tryfalse; substs.\n  rewrite TcbMod.sig_sem in eq1.\n  destruct (tidspec.beq x a) eqn : eq2; tryfalse.\n  inverts eq1.\n  apply tidspec.beq_true_eq in eq2; substs.\n  auto.\nQed.\n\nLemma osabst_get_get_disj_eq : \n  forall O x y Of z,\n    OSAbstMod.get O x = Some y ->\n    OSAbstMod.get (OSAbstMod.merge O Of) x =\n    Some z ->\n    OSAbstMod.disj O Of -> y = z.\nProof.\n  intros.\n  rewrite OSAbstMod.merge_sem in H0.\n  rewrite H in H0.\n  destruct (OSAbstMod.get Of x); inverts H0; auto.\nQed.\n\nLemma osabst_get_get_disj_get : \n  forall O x y Of ,\n    OSAbstMod.get O x = Some y ->\n    \n    OSAbstMod.disj O Of ->\n    OSAbstMod.get (OSAbstMod.merge O Of) x =\n    Some y.\nProof.\n  intros.\n  rewrite OSAbstMod.merge_sem.\n  rewrite H.\n  destruct(OSAbstMod.get Of x); auto.\nQed.\n\n\n(*\nLemma abst_disj_merge_eq_eq:\n  forall O Of O',OSAbstMod.disj O Of -> OSAbstMod.merge O Of = OSAbstMod.merge O' Of -> eqdomO O O' -> O = O'.\nProof.\n  intros.\n  apply OSAbstMod.extensionality; intros.\n  assert(OSAbstMod.get (OSAbstMod.merge O Of) a = OSAbstMod.get (OSAbstMod.merge O' Of) a).\n  rewrite H0; auto.\n  do 2 rewrite OSAbstMod.merge_sem in H2.\n  destruct H1 as (H1&Hx).\n  pose proof H1 a; unfold OSAbstMod.indom in H3; destruct H3.\n  pose proof H a.\n  destruct (OSAbstMod.get O a);\n  destruct (OSAbstMod.get O' a);\n  destruct (OSAbstMod.get Of a);\n  tryfalse; auto.\n  assert (exists b1, Some b = Some b1) by eauto.\n  apply H1 in H6.\n  mytac; tryfalse.\nQed.\n*)\nLemma spec_ext : forall f1 f2 : vallist -> osabst -> option val * osabst -> Prop,\n                   f1 = f2 -> (forall vl O1 rst, f1 vl O1 rst = f2 vl O1 rst).\nProof.\n  intros.\n  substs.\n  auto.\nQed.\n\nLemma prop_eq_impl : forall P Q : Prop, P = Q -> (P -> Q).\nProof.\n  intros.\n  substs.\n  auto.\nQed.\n\nDefinition addrval_a := (xI xH, Int.one).\nDefinition tid_a := (xH, Int.zero).\n\nLemma no_nest_pending_set_none:\n  forall tls p_ct st msg els eid ct p_e wl x6 x7,\n    TcbMod.get tls ct = Some (p_ct, st, msg) ->\n    EcbMod.get els eid = Some (absmutexsem x6 None, x7) ->\n    NO_NEST_PENDING tls (EcbMod.set els eid (absmutexsem p_e (Some (ct, p_ct)), wl)) ->\n    ~ (exists qid, IS_OWNER ct qid els).\nProof.\n  intros.\n  unfolds in H1.\n  assert (TcbMod.get tls ct <> None).\n  intro; rewrite H in H2; tryfalse.\n  assert (IS_OWNER ct eid\n         (EcbMod.set els eid (absmutexsem p_e (Some (ct, p_ct)), wl))).\n  unfolds.\n  rewrite EcbMod.set_a_get_a; eauto.\n  apply tidspec.eq_beq_true; auto.\n  lets Hx: H1 H2 H3; clear H1 H2 H3; mytac.\n  intro; apply H2; mytac.\n  destruct (tidspec.beq eid x) eqn : eq1.\n  apply tidspec.beq_true_eq in eq1; substs.\n  unfolds in H3; mytac.\n  rewrite H0 in H3; tryfalse.\n  exists x; mytac.\n  apply tidspec.beq_false_neq; auto.\n  unfolds.\n  rewrite EcbMod.set_a_get_a'; auto.\nQed.\n\nLemma no_nest_pending_set_prio_eq:\n  forall tls x4 x3 x6 ct x8 x7 x9 x10 p_ct,\n    NO_NEST_PENDING tls (EcbMod.set x4 x3 (absmutexsem x6 (Some (ct, x8)), x7)) ->\n    GET_OP ct tls (EcbMod.set x4 x3 (absmutexsem x6 (Some (ct, x8)), x7)) p_ct ->\n    TcbMod.get tls ct = Some (x8, x9, x10) ->\n    p_ct = x8.\nProof.\n  intros.\n  unfolds in H.\n  unfolds in H0.\n  assert(TcbMod.get tls ct <> None).\n  intro; rewrite H1 in H2; tryfalse.\n  assert(IS_OWNER ct x3 (EcbMod.set x4 x3 (absmutexsem x6 (Some (ct, x8)), x7))).\n  unfolds; do 3 eexists.\n  rewrite EcbMod.set_a_get_a; eauto.\n  apply tidspec.eq_beq_true; auto.\n  lets Hx1: H H2 H3.\n  lets Hx2: H0 H2.\n  clear H H0 H2 H3.\n  destruct Hx2; mytac.\n  unfolds in H; mytac.\n  destruct (tidspec.beq x3 x) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a in H; inverts H; auto.\n  false; apply H2.\n  exists x; unfold IS_OWNER.\n  rewrite EcbMod.set_a_get_a'; auto.\n  rewrite EcbMod.set_a_get_a' in H; auto.\n  apply tidspec.beq_false_neq in eq1.\n  eauto.\n\n  false; apply H.\n  unfold IS_OWNER.\n  do 4 eexists.\n  rewrite EcbMod.set_a_get_a; eauto.\n  apply tidspec.eq_beq_true; auto.\nQed.\n\n\nLemma no_nest_pending_set_hold:\n  forall tls x4 x3 x6 ct x8 x7,\n    NO_NEST_PENDING tls\n                    (EcbMod.set x4 x3 (absmutexsem x6 (Some (ct, x8)), x7)) ->\n    EcbMod.get x4 x3 = Some (absmutexsem x6 None, x7) ->\n    NO_NEST_PENDING tls x4.\nProof.\n  intros.\n  unfolds; intros.\n  destruct(tidspec.beq x3 qid) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  unfolds in H2; do 3 destruct H2.\n  rewrite H0 in H2; tryfalse.\n\n  assert(IS_OWNER t qid (EcbMod.set x4 x3 (absmutexsem x6 (Some (ct, x8)), x7))).\n  unfolds; rewrite EcbMod.set_a_get_a'; auto.\n  lets Hx: H H1 H3; mytac.\n  intro; apply H4.\n  unfolds in H6; mytac.\n  destruct (tidspec.beq x3 x) eqn : eq2.\n  pose proof tidspec.beq_true_eq _ _ eq2; substs.\n  unfolds; do 4 eexists.\n  rewrite EcbMod.set_a_get_a; eauto.\n  rewrite H0 in H6; inverts H6; eauto.\n  unfolds; do 4 eexists.\n  rewrite EcbMod.set_a_get_a'; eauto.\n\n  intro; apply H5; mytac.\n  exists x; mytac; auto.\n  unfolds in H7; mytac.\n  destruct (tidspec.beq x3 x) eqn : eq2.\n  pose proof tidspec.beq_true_eq _ _ eq2; substs.\n  unfolds; do 3 eexists.\n  rewrite EcbMod.set_a_get_a; eauto.\n  rewrite H7 in H0; inverts H0.\n  unfolds; do 3 eexists.\n  rewrite EcbMod.set_a_get_a'; eauto.\n  Grab Existential Variables.\n  auto.\n  apply Int.zero.\n  apply Int.zero.\nQed.\n\nLemma set_neq_getop_eq:\n  forall t ct tls x4 x3 x6 x7 x8 p_t,\n    t <> ct ->\n    TcbMod.get tls t <> None ->\n    EcbMod.get x4 x3 = Some (absmutexsem x6 None, x7) ->\n    GET_OP t tls (EcbMod.set x4 x3 (absmutexsem x6 (Some (ct, x8)), x7)) p_t ->\n    GET_OP t tls x4 p_t.\nProof.\n  intros.\n  lets Hx: H2 H0.\n  unfolds; intros.\n  destruct Hx; mytac.\n  left.\n  unfolds in H4; mytac.\n  destruct (tidspec.beq x3 x) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a in H4; inverts H4; tryfalse.\n  auto.\n  rewrite EcbMod.set_a_get_a' in H4; auto.\n  exists x; unfolds; eauto.\n\n  right.\n  split.\n  intro; apply H4; mytac.\n  destruct (tidspec.beq x3 x1) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  unfolds in H6; mytac.\n  rewrite H1 in H6; tryfalse.\n  exists x1.\n  unfolds; rewrite EcbMod.set_a_get_a'; auto.\n  eauto.\nQed.\n\n\nLemma iswaiting_set_ct_neq_hold:\n  forall t ct tls x4 x3 x6 x7 xx yy,\n    t <> ct ->\n    TcbMod.get tls t <> None ->\n    EcbMod.get x4 x3 = Some (absmutexsem x6 xx, x7) ->\n    IS_WAITING t (EcbMod.set x4 x3 (absmutexsem x6 yy, x7)) ->\n    IS_WAITING t x4.\nProof.\n  intros.\n  unfolds in H2; mytac.\n  unfolds.\n  destruct (tidspec.beq x3 x) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a in H2; auto.\n  inverts H2.\n  do 4 eexists; eauto.\n\n  rewrite EcbMod.set_a_get_a' in H2; auto.\n  do 4 eexists; eauto.\nQed.\n\nLemma ecb_joinsig_get_eq:\n  forall x6 x3 x4 els x8 a0 x9 x,\n    EcbMod.joinsig x6 (absmutexsem x3 None, nil) x4 els ->\n    EcbMod.get x4 x = Some (absmutexsem x9 a0, x8) ->\n    EcbMod.get els x = Some (absmutexsem x9 a0, x8).\nProof.\n  intros.\n  unfolds in H; pose proof H x.\n  rewrite H0 in H1.\n  destruct(EcbMod.get (EcbMod.sig x6 (absmutexsem x3 None, nil)) x); tryfalse.\n  destruct(EcbMod.get els x); tryfalse.\n  rewrite H1; auto.\nQed.\n\nLemma getop_cre_hold:\n  forall x6 x3 x4 els tls ct p_ct,\n    GET_OP ct tls els p_ct ->\n    EcbMod.joinsig x6 (absmutexsem x3 None, nil) x4 els ->\n    GET_OP ct tls x4 p_ct.\nProof.\n  intros.\n  unfolds; intros.\n  lets Hx: H H1.\n  destruct Hx; mytac.\n  left.\n  destruct (tidspec.beq x6 x) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  unfolds in H2; mytac.\n  pose proof H0 x.\n  rewrite H2 in H3.\n  rewrite EcbMod.get_sig_some in H3.\n  destruct (EcbMod.get x4 x); tryfalse.\n  pose proof H0 x.\n  rewrite EcbMod.get_sig_none in H3.\n  destruct (EcbMod.get x4 x) eqn : eq2;\n    destruct (EcbMod.get els x) eqn : eq3;\n    tryfalse; substs.\n  unfolds in H2; mytac.\n  rewrite H2 in eq3; inverts eq3.\n  exists x; unfolds; eauto.\n  unfolds in H2; mytac.\n  rewrite H2 in eq3; tryfalse.\n  apply tidspec.beq_false_neq; auto.\n\n  right. \n  split.\n  intro; apply H2; mytac.\n  unfolds in H4; mytac.\n  pose proof H0 x1.\n  rewrite H4 in H5.\n  destruct (tidspec.beq x6 x1) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.get_sig_some in H5; tryfalse.\n  rewrite EcbMod.get_sig_none in H5.\n  destruct (EcbMod.get els x1) eqn : eq2; tryfalse.\n  exists x1; unfolds; do 3 eexists.\n  inverts H5.\n  eauto.\n  apply tidspec.beq_false_neq; auto.\n\n  eauto.\nQed.\n\n\nLemma no_nest_pending_cre_hold:\n  forall tls els x6 x3 x4,\n    NO_NEST_PENDING tls els ->\n    EcbMod.joinsig x6 (absmutexsem x3 None, nil) x4 els ->\n    NO_NEST_PENDING tls x4.\nProof.\n  intros.\n  unfolds; intros.\n  assert(IS_OWNER t qid els).\n  unfolds in H2; mytac.\n  pose proof H0 qid.\n  destruct (tidspec.beq x6 qid) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.get_sig_some in H3.\n  rewrite H2 in H3; tryfalse.\n  rewrite EcbMod.get_sig_none in H3.\n  rewrite H2 in H3.\n  destruct (EcbMod.get els qid) eqn : eq2; tryfalse; inverts H3.\n  unfolds; do 3 eexists; eauto.\n  apply tidspec.beq_false_neq; auto.\n\n  lets Hx: H H1 H3; mytac.\n  intro; apply H4.\n  unfolds in H6; mytac.\n  pose proof H0 x.\n  rewrite H6 in H8.\n  destruct (tidspec.beq x6 x) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.get_sig_some in H8; tryfalse.\n  rewrite EcbMod.get_sig_none in H8.\n  destruct (EcbMod.get els x) eqn : eq2; tryfalse.\n  inverts H8.\n  unfolds; do 3 eexists; eauto.\n  apply tidspec.beq_false_neq; auto.\n\n  intro; apply H5; mytac.\n  exists x; split; auto.\n  unfolds in H7; mytac.\n  pose proof H0 x.\n  rewrite H7 in H8.\n  destruct (tidspec.beq x6 x) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.get_sig_some in H8; tryfalse.\n  rewrite EcbMod.get_sig_none in H8.\n  destruct (EcbMod.get els x) eqn : eq2; tryfalse.\n  inverts H8.\n  unfolds; do 3 eexists; eauto.\n  apply tidspec.beq_false_neq; auto.\nQed.\n\nLemma iswaiting_cre_hold:\n  forall t x4 x3 x6 els,\n    EcbMod.joinsig x6 (absmutexsem x3 None, nil) x4 els ->\n    IS_WAITING t els ->\n    IS_WAITING t x4.\nProof.\n  intros.\n  unfolds in H0; mytac.\n  pose proof H x.\n  rewrite H0 in H2.\n  destruct (tidspec.beq x6 x) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.get_sig_some in H2; tryfalse.\n  destruct (EcbMod.get x4 x) eqn: eq2; tryfalse.\n  inverts H2.\n  unfolds in H1; tryfalse.\n  rewrite EcbMod.get_sig_none in H2.\n  destruct (EcbMod.get x4 x) eqn: eq2; tryfalse.\n  inverts H2.\n  unfolds; do 3 eexists; eauto.\n  apply tidspec.beq_false_neq; auto.\nQed.  \n\n\nLemma ecb_join_get_eq':\n  forall x6 x3 x4 els x7 x8 a0 x9 x,\n    EcbMod.join els (EcbMod.sig x3 (absmutexsem x6 None, nil)) x4 ->\n    EcbMod.get x4 x = Some (absmutexsem x9 (Some (a0, x7)), x8) ->\n    EcbMod.get els x = Some (absmutexsem x9 (Some (a0, x7)), x8).\nProof.\n  intros.\n  pose proof H x.\n  rewrite H0 in H1.\n  destruct (EcbMod.get (EcbMod.sig x3 (absmutexsem x6 None, nil)) x) eqn : eq1;\n    destruct (EcbMod.get els x) eqn : eq2; tryfalse; substs; auto.\n  rewrite EcbMod.sig_sem in eq1.\n  destruct (tidspec.beq x3 x); tryfalse.\nQed.\n\nLemma getop_del_hold:\n  forall ct tls els p_ct x3 x6 x4,\n    GET_OP ct tls els p_ct ->\n    EcbMod.join els (EcbMod.sig x3 (absmutexsem x6 None, nil)) x4 ->\n    GET_OP ct tls x4 p_ct.\nProof.\n  intros.\n  unfolds; intros.\n  lets Hx: H H1.\n  destruct Hx; mytac.\n  left.\n  destruct (tidspec.beq x3 x) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  unfolds in H2; mytac.\n  pose proof H0 x.\n  rewrite H2 in H3.\n  rewrite EcbMod.get_sig_some in H3; tryfalse.\n  pose proof H0 x.\n  rewrite EcbMod.get_sig_none in H3.\n  destruct (EcbMod.get x4 x) eqn : eq2;\n    destruct (EcbMod.get els x) eqn : eq3;\n    tryfalse; substs.\n  unfolds in H2; mytac.\n  rewrite H2 in eq3; inverts eq3.\n  exists x; unfolds; eauto.\n  unfolds in H2; mytac.\n  rewrite H2 in eq3; tryfalse.\n  apply tidspec.beq_false_neq; auto.\n\n  right. \n  split.\n  intro; apply H2; mytac.\n  unfolds in H4; mytac.\n  pose proof H0 x1.\n  rewrite H4 in H5.\n  destruct (tidspec.beq x3 x1) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.get_sig_some in H5.\n  destruct (EcbMod.get els x1) eqn : eq2; tryfalse.\n  rewrite EcbMod.get_sig_none in H5.\n  destruct (EcbMod.get els x1) eqn : eq2; tryfalse.\n  substs.\n  exists x1; unfolds; do 3 eexists.\n  eauto.\n  apply tidspec.beq_false_neq; auto.\n\n  eauto.\nQed.\n\n\nLemma no_nest_pending_del:\n  forall tls els x3 x6 x4,\n    NO_NEST_PENDING tls els ->\n    EcbMod.join els (EcbMod.sig x3 (absmutexsem x6 None, nil)) x4 ->\n    NO_NEST_PENDING tls x4.\nProof.\n  intros.\n  unfolds; intros.\n  assert(IS_OWNER t qid els).\n  unfolds in H2; mytac.\n  pose proof H0 qid.\n  destruct (tidspec.beq x3 qid) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.get_sig_some in H3.\n  rewrite H2 in H3.\n  destruct (EcbMod.get els qid) eqn : eq2; tryfalse.\n  rewrite EcbMod.get_sig_none in H3.\n  rewrite H2 in H3.\n  destruct (EcbMod.get els qid) eqn : eq2; tryfalse; inverts H3.\n  unfolds; do 3 eexists; eauto.\n  apply tidspec.beq_false_neq; auto.\n\n  lets Hx: H H1 H3; mytac.\n  intro; apply H4.\n  unfolds in H6; mytac.\n  pose proof H0 x.\n  rewrite H6 in H8.\n  destruct (tidspec.beq x3 x) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.get_sig_some in H8.\n  destruct (EcbMod.get els x) eqn : eq2; tryfalse.\n  inverts H8.\n  simpl in H7; tryfalse.\n  rewrite EcbMod.get_sig_none in H8.\n  destruct (EcbMod.get els x) eqn : eq2; tryfalse.\n  inverts H8.\n  unfolds; do 3 eexists; eauto.\n  apply tidspec.beq_false_neq; auto.\n\n  intro; apply H5; mytac.\n  exists x; split; auto.\n  unfolds in H7; mytac.\n  pose proof H0 x.\n  rewrite H7 in H8.\n  destruct (tidspec.beq x3 x) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.get_sig_some in H8.\n  destruct (EcbMod.get els x) eqn : eq2; tryfalse.\n  rewrite EcbMod.get_sig_none in H8.\n  destruct (EcbMod.get els x) eqn : eq2; tryfalse.\n  inverts H8.\n  unfolds; do 3 eexists; eauto.\n  apply tidspec.beq_false_neq; auto.\nQed.\n\nLemma iswaiting_del_hold:\n  forall t x4 x3 x6 els,\n    EcbMod.join els (EcbMod.sig x3 (absmutexsem x6 None, nil)) x4 ->\n    IS_WAITING t els ->\n    IS_WAITING t x4.\nProof.\n  intros.\n  unfolds in H0; mytac.\n  pose proof H x.\n  rewrite H0 in H2.\n  destruct (tidspec.beq x3 x) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.get_sig_some in H2; tryfalse.\n  rewrite EcbMod.get_sig_none in H2.\n  destruct (EcbMod.get x4 x) eqn: eq2; tryfalse.\n  inverts H2.\n  unfolds; do 4 eexists; eauto.\n  apply tidspec.beq_false_neq; auto.\nQed.\n\n\nLemma pend_no_lift_getop:\n  forall tls ct x12 x2 els x x8 x9 x10 x7 x0 t p_t,\n    TcbMod.get tls ct = Some (x12, rdy, x2) ->\n    EcbMod.get els x = Some (absmutexsem x8 (Some (x9, x10)), x7) -> \n    GET_OP t (TcbMod.set tls ct (x12, wait (os_stat_mutexsem x) x0, Vnull))\n           (EcbMod.set els x (absmutexsem x8 (Some (x9, x10)), ct :: x7)) p_t ->\n    GET_OP t tls els p_t.\nProof.\n  intros.\n  unfolds; intros.\n  assert(TcbMod.get (TcbMod.set tls ct (x12, wait (os_stat_mutexsem x) x0, Vnull)) t <> None).\n  destruct (tidspec.beq ct t) eqn : eq1.\n  rewrite TcbMod.set_a_get_a; auto.\n  rewrite TcbMod.set_a_get_a'; auto.\n  apply H1 in H3.\n  destruct H3; mytac.\n  left.\n  unfolds in H3; mytac.\n  destruct (tidspec.beq x x1) eqn : eq1.\n  rewrite EcbMod.set_a_get_a in H3; auto; inverts H3.\n  exists x; unfolds; do 2 eexists; eauto.\n\n  rewrite EcbMod.set_a_get_a' in H3; auto.\n  exists x1; unfolds; do 2 eexists; eauto.\n\n  right.\n  split.\n  intro; apply H3; mytac.\n  unfolds in H5; mytac.\n  destruct (tidspec.beq x x4) eqn : eq2.\n  pose proof tidspec.beq_true_eq _ _ eq2; substs.\n  rewrite H0 in H5; inverts H5.\n  eexists; unfolds; do 3 eexists.\n  rewrite EcbMod.set_a_get_a; eauto.\n  eexists; unfolds.\n  do 3 eexists; rewrite EcbMod.set_a_get_a'; eauto.\n\n  destruct (tidspec.beq ct t) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite TcbMod.set_a_get_a in H4; auto.\n  inverts H4; eauto.\n\n  rewrite TcbMod.set_a_get_a' in H4; eauto.\nQed.\n\n\nLemma pend_no_lift_nnp:\n  forall tls ct x12 x2 els x x8 x9 x10 x7 x0,\n    TcbMod.get tls ct = Some (x12, rdy, x2) ->\n    EcbMod.get els x = Some (absmutexsem x8 (Some (x9, x10)), x7) -> \n    NO_NEST_PENDING (TcbMod.set tls ct (x12, wait (os_stat_mutexsem x) x0, Vnull))\n                    (EcbMod.set els x (absmutexsem x8 (Some (x9, x10)), ct :: x7)) ->\n    NO_NEST_PENDING tls els.\nProof.\n  intros.\n  unfolds; intros.\n  assert(TcbMod.get (TcbMod.set tls ct (x12, wait (os_stat_mutexsem x) x0, Vnull)) t <> None).\n  destruct (tidspec.beq ct t) eqn : eq1.\n  rewrite TcbMod.set_a_get_a; auto.\n  rewrite TcbMod.set_a_get_a'; auto.\n  assert(IS_OWNER t qid (EcbMod.set els x (absmutexsem x8 (Some (x9, x10)), ct :: x7))).\n  unfolds in H3; mytac.\n  destruct (tidspec.beq x qid) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite H0 in H3; inverts H3.\n  unfolds.\n  rewrite EcbMod.set_a_get_a; auto.\n  eauto.\n  unfolds.\n  rewrite EcbMod.set_a_get_a'; eauto.\n\n  lets Hx: H1 H4 H5; mytac.\n  intro; apply H6; mytac.\n  unfolds in H8; mytac.\n  unfolds.\n  destruct (tidspec.beq x x1) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  do 4 eexists; rewrite EcbMod.set_a_get_a.\n  rewrite H0 in H8; inverts H8.\n  split; eauto.\n  destruct (tidspec.beq t ct) eqn : eq2.\n  pose proof tidspec.beq_true_eq _ _ eq2; substs.\n  simpl; auto.\n  simpl; right; auto.\n  eauto.\n  do 4 eexists; rewrite EcbMod.set_a_get_a'; eauto.\n\n  intro; apply H7; mytac.\n  exists x1.\n  split; auto.\n  unfolds in H9; mytac.\n  destruct (tidspec.beq x x1) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  unfolds; do 3 eexists; rewrite EcbMod.set_a_get_a; auto.\n  rewrite H9 in H0; inverts H0; eauto.\n\n  unfolds; do 3 eexists; rewrite EcbMod.set_a_get_a'; eauto.\nQed.\n\n\nLemma pend_no_lift_iswating:\n  forall t ct els x x8 x9 x10 x7,\n    t <> ct ->\n    EcbMod.get els x = Some (absmutexsem x8 (Some (x9, x10)), x7) ->\n    IS_WAITING t (EcbMod.set els x (absmutexsem x8 (Some (x9, x10)), ct :: x7)) ->\n    IS_WAITING t els.\nProof.\n  intros.\n  unfolds in H1; mytac.\n  destruct (tidspec.beq x x0) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a in H1; auto.\n  inverts H1.\n  unfolds; do 4 eexists.\n  split; eauto.\n  simpl in H2; destruct H2; tryfalse; auto.\n\n  rewrite EcbMod.set_a_get_a' in H1; auto.\n  unfolds; do 4 eexists.\n  split; eauto.\nQed.\n\nLemma tcb_get_set_neq_none:\n  forall t ct x tls,\n    t <> ct ->\n    TcbMod.get (TcbMod.set tls ct x) t <> None ->\n    TcbMod.get tls t <> None.\nProof.\n  intros.\n  rewrite TcbMod.set_a_get_a' in H0; auto.\n  apply tidspec.neq_beq_false; auto.\nQed.\n\nLemma pend_lift_nnp:\n  forall tls ct x11 x12 x2 els x x8 x9 x10 x0 x13 x14 x15,\n    TcbMod.get tls ct = Some (x13, rdy, x2) ->\n    TcbMod.get tls x10 = Some (x12, x14, x15) ->\n    EcbMod.get els x = Some (absmutexsem x9 (Some (x10, x11)), x8) -> \n    NO_NEST_PENDING (TcbMod.set\n                       (TcbMod.set tls ct (x13, wait (os_stat_mutexsem x) x0, x2)) x10\n                       (x9, x14, x15))\n                    (EcbMod.set els x (absmutexsem x9 (Some (x10, x11)), ct :: x8)) ->\n    NO_NEST_PENDING tls els.\nProof.\n  intros.\n  unfolds; intros.\n  assert(TcbMod.get\n           (TcbMod.set\n              (TcbMod.set tls ct (x13, wait (os_stat_mutexsem x) x0, x2))\n            x10 (x9, x14, x15))\n         t <> None).\n  destruct (tidspec.beq x10 t) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite TcbMod.set_a_get_a; auto.\n  rewrite TcbMod.set_a_get_a'; auto.\n  destruct (tidspec.beq ct t) eqn : eq2.\n  pose proof tidspec.beq_true_eq _ _ eq2; substs.\n  rewrite TcbMod.set_a_get_a; auto.\n  rewrite TcbMod.set_a_get_a'; auto.\n\n  assert (IS_OWNER t qid (EcbMod.set els x (absmutexsem x9 (Some (x10, x11)), ct :: x8))).\n  unfolds in H4; mytac.\n  destruct (tidspec.beq x qid) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  unfolds; do 3 eexists; rewrite EcbMod.set_a_get_a; auto.\n  rewrite H4 in H1; inverts H1; eauto.\n\n  unfolds; do 3 eexists; rewrite EcbMod.set_a_get_a'; auto.\n  eauto.\n\n  lets Hx: H2 H5 H6; mytac.\n  intro; apply H7.\n  unfolds in H9; mytac; unfolds.\n  exists x1.\n  destruct (tidspec.beq x x1) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a; auto.\n  rewrite H9 in H1; inverts H1.\n  do 3 eexists; mytac; eauto.\n  simpl; auto.\n\n  rewrite EcbMod.set_a_get_a'; auto.\n  do 3 eexists; eauto.\n\n  intro; apply H8; mytac.\n  exists x1; mytac; auto.\n  unfolds in H10; mytac; unfolds.\n  destruct (tidspec.beq x x1) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a; auto.\n  rewrite H10 in H1; inverts H1.\n  do 3 eexists; mytac; eauto.\n\n  rewrite EcbMod.set_a_get_a'; auto.\n  do 3 eexists; eauto.\nQed.\n\n\nLemma pend_lift_getop_t:\n  forall tls ct x10 x13 x2 x12 x14 x15 x11 x x8 x9 t p_t els x0 st,\n    t<> ct ->\n    t<> x10 ->\n    TcbMod.get tls ct = Some (x13, st, x2) ->\n    TcbMod.get tls x10 = Some (x12, x14, x15) ->\n    EcbMod.get els x = Some (absmutexsem x9 (Some (x10, x11)), x8) ->\n    GET_OP t\n           (TcbMod.set\n              (TcbMod.set tls ct (x13, wait (os_stat_mutexsem x) x0, x2)) x10\n              (x9, x14, x15))\n           (EcbMod.set els x (absmutexsem x9 (Some (x10, x11)), ct :: x8)) p_t ->\n    GET_OP t tls els p_t.\nProof.\n  intros.\n  unfolds; intros.\n  assert(TcbMod.get\n           (TcbMod.set\n              (TcbMod.set tls ct (x13, wait (os_stat_mutexsem x) x0, x2))\n            x10 (x9, x14, x15))\n         t <> None).\n  rewrite TcbMod.set_a_get_a'; auto.\n  rewrite TcbMod.set_a_get_a'; auto.\n  apply tidspec.neq_beq_false; auto.\n  apply tidspec.neq_beq_false; auto.\n  \n  lets Hx: H4 H6; destruct Hx; mytac.\n  left.\n  unfolds in H7; mytac.\n  destruct (tidspec.beq x x1) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a in H7; auto.\n  inverts H7; exists x1; unfolds; do 2 eexists; eauto.\n  rewrite EcbMod.set_a_get_a' in H7; auto.\n  exists x1; unfolds; do 2 eexists; eauto.\n\n  right.\n  split.\n  intro; apply H7; mytac.\n  exists x4.\n  unfolds in H9; mytac.\n  destruct (tidspec.beq x x4) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite H9 in H3; inverts H3.\n  unfolds; do 3 eexists; rewrite EcbMod.set_a_get_a; auto.\n  unfolds; do 3 eexists; rewrite EcbMod.set_a_get_a'; eauto.\n\n  rewrite TcbMod.set_a_get_a' in H8.\n  rewrite TcbMod.set_a_get_a' in H8.\n  eauto.\n  apply tidspec.neq_beq_false; auto.\n  apply tidspec.neq_beq_false; auto.\nQed.\n\n\n\nLemma pend_lift_iswait:\n  forall t ct els x x9 x10 x11 x8 ,\n    t <> ct ->\n    EcbMod.get els x = Some (absmutexsem x9 (Some (x10, x11)), x8) ->\n    IS_WAITING t\n               (EcbMod.set els x (absmutexsem x9 (Some (x10, x11)), ct :: x8)) ->\n    IS_WAITING t els.\nProof.\n  intros.\n  unfolds; unfolds in H1; mytac.\n  destruct (tidspec.beq x x0) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a in H1; auto.\n  inverts H1; do 4 eexists; mytac; eauto.\n  simpl in H2; destruct H2; tryfalse; auto.\n\n  rewrite EcbMod.set_a_get_a' in H1; auto.\n  do 4 eexists; eauto.\nQed.\n\n\nLemma post_nowt_return_getop_ct:\n  forall tls els x x5 ct x6 x7 x8 p_ct,\n    NO_NEST_PENDING tls els ->\n    EcbMod.get els x = Some (absmutexsem x5 (Some (ct, x6)), nil) ->\n    TcbMod.get tls ct = Some (x5, x7, x8) ->\n    GET_OP ct (TcbMod.set tls ct (x6, x7, x8))\n           (EcbMod.set els x (absmutexsem x5 None, nil)) p_ct ->\n    GET_OP ct tls els x6 /\\ p_ct = x6.\nProof.\n    intros.\n  \n  assert(p_ct = x6).\n  unfolds in H2.\n  assert(TcbMod.get (TcbMod.set tls ct (x6, x7, x8)) ct <> None).\n  rewrite TcbMod.set_a_get_a; auto.\n  apply tidspec.eq_beq_true; auto.\n  apply H2 in H3; clear H2.\n  destruct H3; mytac.\n  assert(TcbMod.get tls ct <> None).\n  rewrite H1; auto.\n  lets Hx: H H3.\n  assert(IS_OWNER ct x els).\n  unfolds; eauto.\n  apply Hx in H4; clear Hx; mytac.\n  unfolds in H2; mytac.\n  destruct (tidspec.beq x x0) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a in H2; auto; inversion H2.\n  rewrite EcbMod.set_a_get_a' in H2; auto.\n  false; apply H5.\n  exists x0.\n  split.\n  apply tidspec.beq_false_neq; auto.\n  unfolds; eauto.\n\n  rewrite TcbMod.set_a_get_a in H3; inversion H3; auto.\n  apply tidspec.eq_beq_true; auto.\n  substs.\n\n  split; auto.\n  unfolds; intros.\n  assert(TcbMod.get (TcbMod.set tls ct (x6, x7, x8)) ct <> None).\n  rewrite TcbMod.set_a_get_a; auto.\n  apply tidspec.eq_beq_true; auto.\n\n  lets Hx: H2 H4.\n  destruct Hx; mytac.\n  left.\n  \n  unfolds in H5; mytac.\n  destruct (tidspec.beq x x0) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1;substs.\n  rewrite EcbMod.set_a_get_a in H5; auto.\n  inverts H5.\n  rewrite EcbMod.set_a_get_a' in H5; auto. \n  exists x; unfolds; do 2 eexists; eauto.\n\n  left.\n  exists x; unfolds; do 2 eexists; eauto.\nQed.\n\nLemma post_nowt_return_getop_t:\n  forall tls els x x5 t ct x6 x7 x8 p_t,\n    t <> ct -> \n    EcbMod.get els x = Some (absmutexsem x5 (Some (ct, x6)), nil) ->\n    TcbMod.get tls ct = Some (x5, x7, x8) ->\n    GET_OP t (TcbMod.set tls ct (x6, x7, x8))\n           (EcbMod.set els x (absmutexsem x5 None, nil)) p_t ->\n    GET_OP t tls els p_t.\nProof.\n  intros.\n  unfolds; intros.  \n  assert (TcbMod.get (TcbMod.set tls ct (x6, x7, x8)) t <> None).\n  rewrite TcbMod.set_a_get_a'; auto.\n  apply tidspec.neq_beq_false; auto.\n  apply H2 in H4.\n  destruct H4; mytac.\n  left.\n  exists x0.\n  unfolds in H4; mytac.\n  destruct (tidspec.beq x x0) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a in H4; auto; inverts H4.\n  rewrite EcbMod.set_a_get_a' in H4; auto.\n  unfolds; eauto.\n\n  right.\n  split.\n  intro; apply H4; mytac.\n  exists x2.\n  unfolds in H6; mytac.\n  unfolds.\n  destruct (tidspec.beq x x2) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite H6 in H0; inverts H0; tryfalse.\n  rewrite EcbMod.set_a_get_a'; auto.\n  eauto.\n\n  rewrite TcbMod.set_a_get_a' in H5.\n  eauto.\n  apply tidspec.neq_beq_false; auto.\nQed.\n\n\nLemma no_owner_cre:\n  forall ct els x6 x3 x4,\n    ~ (exists eid, IS_OWNER ct eid els) ->\n    EcbMod.joinsig x6 (absmutexsem x3 None, nil) x4 els ->\n    ~ (exists eid, IS_OWNER ct eid x4).\nProof.\n  intros.\n  intro; apply H; mytac.\n  exists x.\n  unfolds in H1; mytac.\n  unfolds.\n  pose proof H0 x.\n  rewrite H1 in H2.\n  destruct (tidspec.beq x6 x) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.get_sig_some in H2; tryfalse.\n  rewrite EcbMod.get_sig_none in H2.\n  destruct (EcbMod.get els x); tryfalse.\n  substs; eauto.\n  apply tidspec.beq_false_neq; auto.\nQed.\n\nLemma no_owner_del:\n  forall ct els x6 x3 x4,\n    ~ (exists eid, IS_OWNER ct eid els) ->\n    EcbMod.join els (EcbMod.sig x3 (absmutexsem x6 None, nil)) x4 ->\n    ~ (exists eid, IS_OWNER ct eid x4).\nProof.\n  intros.\n  intro; apply H; mytac.\n  unfolds in H1; mytac.\n  exists x; unfolds.\n  pose proof H0 x; rewrite H1 in H2.\n  destruct (tidspec.beq x3 x) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.get_sig_some in H2.\n  destruct (EcbMod.get els x); tryfalse.\n  rewrite EcbMod.get_sig_none in H2.\n  destruct (EcbMod.get els x); tryfalse.\n  substs; eauto.\n  apply tidspec.beq_false_neq; auto.\nQed.\n\nLemma post_lift_get_op_ct:\n  forall Ox els tls x x5 ct x0 x1 p_ct,\n    NO_NEST_PENDING_O Ox ->\n    OSAbstMod.get Ox absecblsid = Some (absecblist els) ->\n    OSAbstMod.get Ox abtcblsid = Some (abstcblist tls) ->\n    EcbMod.get els x = Some (absmutexsem x5 (Some (ct, x0)), nil) ->\n    TcbMod.get tls ct = Some (x5, rdy, x1) ->\n    GET_OP ct (TcbMod.set tls ct (x0, rdy, x1))\n           (EcbMod.set els x (absmutexsem x5 None, nil)) p_ct ->\n    p_ct = x0.\nProof.\n  intros.\n  unfolds in H4.\n  assert(TcbMod.get (TcbMod.set tls ct (x0, rdy, x1)) ct <> None).\n  rewrite TcbMod.set_a_get_a; auto; apply tidspec.eq_beq_true; auto.\n  apply H4 in H5; clear H4.\n  destruct H5; mytac.\n  unfolds in H.\n  lets Hx: H H0 H1.\n  unfolds in Hx.\n  assert(TcbMod.get tls ct <> None).\n  rewrite H3; auto.\n  assert(IS_OWNER ct x els).\n  unfolds; eauto.\n  lets Hx1: Hx H5 H6; mytac.\n  unfolds in H4; mytac.\n  destruct (tidspec.beq x x2) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a in H4; auto.\n  inversion H4.\n  rewrite EcbMod.set_a_get_a' in H4; auto.\n  false; apply H8.\n  exists x2; mytac.\n  apply tidspec.beq_false_neq; auto.\n  unfolds.\n  eauto.\n\n  rewrite TcbMod.set_a_get_a in H5; inverts H5; auto.\n  apply tidspec.eq_beq_true; auto.\nQed.\n\n\nLemma post_lift_ct_nowner:\n  forall Ox els tls x x5 ct x0 x1 p_ct x3,\n    NO_NEST_PENDING_O Ox ->\n    OSAbstMod.get Ox absecblsid = Some (absecblist els) ->\n    OSAbstMod.get Ox abtcblsid = Some (abstcblist tls) ->\n    EcbMod.get els x = Some (absmutexsem x5 (Some (ct, p_ct)), nil) ->\n    TcbMod.get tls ct = Some (x5, rdy, x1) ->\n    IS_OWNER x3 x0 (EcbMod.set els x (absmutexsem x5 None, nil)) ->\n    x3 <> ct.\nProof.\n  intros.\n  lets Hx: H H0 H1.\n  unfolds in Hx.\n  assert(TcbMod.get tls ct <> None).\n  rewrite H3; auto.\n  assert(IS_OWNER ct x els).\n  unfolds; eauto.\n  lets Hx1: Hx H5 H6; mytac.\n  unfolds in H4; mytac.\n  destruct (tidspec.beq x x0) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a in H4; auto.\n\n  rewrite EcbMod.set_a_get_a' in H4; auto.\n  intro; substs; apply H8.\n  exists x0; mytac.\n  apply tidspec.beq_false_neq; auto.\n  unfolds; eauto.\nQed.\n\n\nLemma post_nolift_get_op_ct:\n  forall Ox els tls x x5 x0 ct x1 p_ct,\n    NO_NEST_PENDING_O Ox ->\n    OSAbstMod.get Ox absecblsid = Some (absecblist els) ->\n    OSAbstMod.get Ox abtcblsid = Some (abstcblist tls) ->\n    EcbMod.get els x = Some (absmutexsem x5 (Some (ct, x0)), nil) ->\n    TcbMod.get tls ct = Some (x0, rdy, x1) ->\n    GET_OP ct tls\n           (EcbMod.set els x (absmutexsem x5 None, nil)) p_ct ->\n    p_ct = x0.\nProof.\n  intros.\n  lets Hx: H H0 H1.\n  unfolds in H4.\n  assert(TcbMod.get tls ct <> None).\n  rewrite H3; auto.\n  unfolds in Hx.\n  assert (IS_OWNER ct x els).\n  unfolds; eauto.\n  lets Hx1: Hx H5 H6.\n  apply H4 in H5; clear H4.\n  unfolds in H6; mytac.\n  destruct H5; mytac.\n  unfolds in H5; mytac.\n  destruct (tidspec.beq x x6) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a in H5; auto; inversion H5.\n  false; apply H7.\n  exists x6; mytac.\n  apply tidspec.beq_false_neq; auto.\n  unfolds.\n  rewrite EcbMod.set_a_get_a' in H5; eauto.\n\n  rewrite H3 in H8; inverts H8.\n  auto.\nQed.\n\n\nLemma post_no_lift_ct_nowner:\n  forall Ox els tls x x5 ct x0 x1 p_ct x3,\n    NO_NEST_PENDING_O Ox ->\n    OSAbstMod.get Ox absecblsid = Some (absecblist els) ->\n    OSAbstMod.get Ox abtcblsid = Some (abstcblist tls) ->\n    EcbMod.get els x = Some (absmutexsem x5 (Some (ct, p_ct)), nil) ->\n    TcbMod.get tls ct = Some (p_ct, rdy, x1) ->\n    IS_OWNER x3 x0 (EcbMod.set els x (absmutexsem x5 None, nil)) ->\n    x3 <> ct.\nProof.\n  intros.\n  lets Hx: H H0 H1.\n  unfolds in H4.\n  unfolds in Hx.\n  assert (TcbMod.get tls ct <> None).\n  rewrite H3; auto.\n  assert (IS_OWNER ct x els).\n  unfolds; eauto.\n  lets Hx1: Hx H5 H6; mytac.\n  destruct (tidspec.beq x x0) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a in H4; auto; inversion H4.\n  intro; substs.\n  apply H8.\n  exists x0; mytac.\n  apply tidspec.beq_false_neq; auto.\n  rewrite EcbMod.set_a_get_a' in H4; auto.\n  unfolds; eauto.\nQed.\n\n\nLemma post_ex_wait_ct_neq:\n  forall Ox els tls x x6 ct x8 x11 x12,\n    NO_NEST_PENDING_O Ox ->\n    OSAbstMod.get Ox absecblsid = Some (absecblist els) ->\n    OSAbstMod.get Ox abtcblsid = Some (abstcblist tls) ->\n    EcbMod.get els x = Some (absmutexsem x6 (Some (ct, x8)), x11) ->\n    GetHWait tls x11 x12 ->\n    x12 <> ct.\nProof.\n  intros.\n  lets Hx: H H0 H1.\n  unfolds in H3.\n  unfolds in Hx.\n  mytac; intro; substs.\n  assert(get tls ct <> None).\n  unfolddef.\n  unfold get.\n  simpl.\n  unfold get in H4.\n  simpl in H4.\n  rewrite H4;auto.\n  assert(IS_OWNER ct x els).\n  unfolds; eauto.\n  lets Hx1: Hx H6 H7.\n  mytac.\n  apply H8.\n  unfolds.\n  do 4 eexists.\n  mytac; eauto.\nQed.\n\nLemma post_lift_exwt_get_op_ct:\n  forall (Ox : OSAbstMod.map) (els : EcbMod.map) \n         (tls : TcbMod.map) (x : tidspec.A) (x6 : int32) \n         (ct : tid) (x0 : int32) (x1 : msg) (p_ct : int32) x12 x7 x11 x5,\n    x12 <> ct ->\n    NO_NEST_PENDING_O Ox ->\n    OSAbstMod.get Ox absecblsid = Some (absecblist els) ->\n    OSAbstMod.get Ox abtcblsid = Some (abstcblist tls) ->\n    EcbMod.get els x = Some (absmutexsem x6 (Some (ct, x0)), x11) ->\n    TcbMod.get tls ct = Some (x5, rdy, x1) ->\n    GET_OP ct\n           (TcbMod.set (TcbMod.set tls ct (x0, rdy, x1)) x12 (x7, rdy, Vptr x))\n           (EcbMod.set els x\n                       (absmutexsem x6 (Some (x12, x7)), remove_tid x12 x11)) p_ct -> \n    p_ct = x0.\nProof.\n  intros.\n  lets Hx:H0 H1 H2.\n  unfolds in H5.\n  unfolds in Hx.\n  assert (TcbMod.get\n         (TcbMod.set (TcbMod.set tls ct (x0, rdy, x1)) x12 (x7, rdy, Vptr x))\n         ct <> None ).\n  rewrite TcbMod.set_a_get_a'.\n  rewrite TcbMod.set_a_get_a; auto.\n  apply tidspec.eq_beq_true; auto.\n  apply tidspec.neq_beq_false; auto.\n  apply H5 in H6; clear H5.\n  assert(TcbMod.get tls ct <> None).\n  rewrite H4; auto.\n  assert(IS_OWNER ct x els).\n  unfolds; eauto.\n  lets Hx1: Hx H5 H7.\n  destruct H6; mytac.\n  unfolds in H6; mytac.\n  destruct (tidspec.beq x x2) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a in H6; auto.\n  inverts H6; tryfalse.\n\n  rewrite EcbMod.set_a_get_a' in H6; auto.\n  false; apply H9; exists x2; mytac.\n  apply tidspec.beq_false_neq; auto.\n  unfolds; eauto.\n\n  rewrite TcbMod.set_a_get_a' in H10.\n  rewrite TcbMod.set_a_get_a in H10.\n  inverts H10; auto.\n  apply tidspec.eq_beq_true; auto.\n  apply tidspec.neq_beq_false; auto.\nQed.\n\nLemma post_lift_exwt_ct_nowner:\n  forall Ox els tls x x5 ct x0 x1 p_ct x3 x12 x7 x11,\n    NO_NEST_PENDING_O Ox ->\n    OSAbstMod.get Ox absecblsid = Some (absecblist els) ->\n    OSAbstMod.get Ox abtcblsid = Some (abstcblist tls) ->\n    EcbMod.get els x = Some (absmutexsem x5 (Some (ct, p_ct)), x11) ->\n    TcbMod.get tls ct = Some (x5, rdy, x1) ->\n    IS_OWNER x3 x0 (EcbMod.set els x (absmutexsem x5 (Some (x12, x7)), remove_tid x12 x11)) -> x12 <> ct ->\n    x3 <> ct.\nProof.\n  intros.\n  unfolds in H4; mytac.\n  destruct (tidspec.beq x x0) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a in H4; auto.\n  inverts H4; auto.\n\n  rewrite EcbMod.set_a_get_a' in H4; auto.\n  lets Hx: H H0 H1.\n  unfolds in Hx.\n  assert(TcbMod.get tls ct <> None).\n  rewrite H3; auto.\n  assert(IS_OWNER ct x els).\n  unfolds; eauto.\n  lets Hx1: Hx H6 H7; mytac.\n  intro; substs.\n  apply H9.\n  exists x0; mytac.\n  apply tidspec.beq_false_neq; auto.\n  unfolds; eauto.\nQed.\n\nLemma post_nolift_exwt_get_op_ct:\n  forall Ox els tls x ct p_ct x11 x12 x13 x6 x7 x8 x9,\n    x13 <> ct ->\n    NO_NEST_PENDING_O Ox ->\n    OSAbstMod.get Ox absecblsid = Some (absecblist els) ->\n    OSAbstMod.get Ox abtcblsid = Some (abstcblist tls) ->\n    EcbMod.get els x = Some (absmutexsem x6 (Some (ct, x9)), x12) ->\n    TcbMod.get tls ct =  Some (x8, rdy, x11) ->\n    GET_OP ct (TcbMod.set tls x13 (x7, rdy, Vptr x))\n           (EcbMod.set els x\n                       (absmutexsem x6 (Some (x13, x7)), remove_tid x13 x12)) p_ct ->\n    p_ct = x8.\nProof.\n  intros.\n  lets Hx: H0 H1 H2.\n  unfolds in H5.\n  assert(TcbMod.get (TcbMod.set tls x13 (x7, rdy, Vptr x)) ct <> None).\n  rewrite TcbMod.set_a_get_a'.\n  rewrite H4; auto.\n  apply tidspec.neq_beq_false; auto.\n  apply H5 in H6; clear H5.\n  unfolds in Hx.\n  assert(TcbMod.get tls ct <> None).\n  rewrite H4; auto.\n  assert(IS_OWNER ct x els).\n  unfolds; eauto.\n  lets Hx1: Hx H5 H7.\n  destruct H6; mytac.\n  unfolds in H6; mytac.\n  destruct(tidspec.beq x x0) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a in H6; auto.\n  inverts H6; tryfalse.\n\n  rewrite EcbMod.set_a_get_a' in H6; auto.\n  false; apply H9; exists x0; mytac.\n  apply tidspec.beq_false_neq; auto.\n  unfolds; eauto.\n\n  rewrite TcbMod.set_a_get_a' in H10.\n  rewrite H4 in H10; inverts H10; auto.\n  apply tidspec.neq_beq_false; auto.\nQed.\n\nLemma post_nolift_exwt_ct_nowner:\n  forall Ox els tls x x3 ct x0 p_ct x13 x6 x7 x12 x11,\n    NO_NEST_PENDING_O Ox ->\n    OSAbstMod.get Ox absecblsid = Some (absecblist els) ->\n    OSAbstMod.get Ox abtcblsid = Some (abstcblist tls) ->\n    EcbMod.get els x = Some (absmutexsem x6 (Some (ct, p_ct)), x12) ->\n    TcbMod.get tls ct = Some (p_ct, rdy, x11) ->\n    IS_OWNER x3 x0  (EcbMod.set els x\n                                (absmutexsem x6 (Some (x13, x7)), remove_tid x13 x12))->  x13 <> ct ->\n    x3 <> ct.\nProof.\n  intros.\n  unfolds in H4; mytac.\n  destruct (tidspec.beq x x0) eqn :eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a in H4; auto.\n  inverts H4; auto.\n\n  rewrite EcbMod.set_a_get_a' in H4; auto.\n  lets Hx: H H0 H1.\n  unfolds in Hx.\n  assert(TcbMod.get tls ct <> None).\n  rewrite H3; auto.\n  assert(IS_OWNER ct x els).\n  unfolds; eauto.\n  lets Hx1: Hx H6 H7; mytac.\n  intro; substs.\n  apply H9.\n  exists x0; mytac.\n  apply tidspec.beq_false_neq; auto.\n  unfolds; eauto.\nQed.\n\n\n\nLemma tickchange_els :\n  forall t st st' els els',\n    tickchange t st els st' els' ->\n    (els = els' \\/\n     (exists eid m wl, EcbMod.get els eid = Some (m, wl) /\\\n        els' = EcbMod.set els eid (m, remove_tid t wl))\n    ).\nProof.\n  intros.\n  inverts H;\n    try solve [left; auto].\n  right.\n  do 3 eexists; split; eauto.\nQed.\n\nLemma GET_OP_st_irrel :\n  forall tls els t ct p st st' msg p_ct,\n    TcbMod.get tls t = Some (p, st, msg) ->\n    GET_OP ct (TcbMod.set tls t (p, st', msg)) els p_ct ->\n    GET_OP ct tls els p_ct.\nProof.\n  intros.\n  unfolds in H0; unfolds; intros.\n  assert(TcbMod.get (TcbMod.set tls t (p, st', msg)) ct <> None).\n  destruct(tidspec.beq t ct) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite TcbMod.set_a_get_a; auto.\n  rewrite TcbMod.set_a_get_a'; auto.\n  apply H0 in H2.\n  destruct H2; mytac.\n  left; eauto.\n  right; split; eauto.\n  destruct(tidspec.beq t ct) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite TcbMod.set_a_get_a in H3; auto; inverts H3; eauto.\n  rewrite TcbMod.set_a_get_a' in H3; auto; eauto.\nQed.\n\nLemma IS_OWNER_remove_tid_irrel :\n    forall els m wl x x0 t ct,\n      EcbMod.get els x = Some (m, wl) ->\n      IS_OWNER ct x0 (EcbMod.set els x (m, remove_tid t wl)) ->\n      IS_OWNER ct x0 els.\nProof.\n  intros.\n  unfolds in H0; mytac.\n  unfolds.\n  destruct (tidspec.beq x x0) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a in H0; inverts H0; eauto.\n  rewrite EcbMod.set_a_get_a' in H0; eauto.\nQed.\n\nLemma IS_OWNER_remove_tid_irrel' :\n    forall els m wl x x0 t ct,\n      EcbMod.get els x = Some (m, wl) ->\n      IS_OWNER ct x0 els ->\n      IS_OWNER ct x0 (EcbMod.set els x (m, remove_tid t wl)).\nProof.\n  intros.\n  unfolds in H0; mytac.\n  unfolds.\n  destruct (tidspec.beq x x0) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite H0 in H; inverts H.\n  rewrite EcbMod.set_a_get_a; eauto.\n  rewrite EcbMod.set_a_get_a'; eauto.\nQed.\n\nLemma IS_OWNER_P_remove_tid_irrel :\n  forall els m wl x x0 t ct p_ct,\n    EcbMod.get els x = Some (m, wl) ->\n    IS_OWNER_P ct x0 (EcbMod.set els x (m, remove_tid t wl)) p_ct ->\n    IS_OWNER_P ct x0 els p_ct.\nProof.\n  intros.\n  unfolds in H0; mytac.\n  unfolds.\n  destruct (tidspec.beq x x0) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a in H0; auto; inverts H0; eauto.\n  rewrite EcbMod.set_a_get_a' in H0; eauto.\nQed.\n\nLemma GET_OP_remove_tid_irrel :\n  forall tls els ct t x m wl p_ct,\n    EcbMod.get els x = Some (m, wl) ->\n    GET_OP ct tls (EcbMod.set els x (m, remove_tid t wl)) p_ct ->\n    GET_OP ct tls els p_ct.\nProof.\n  intros.\n  unfolds in H0; unfolds; intros.\n  apply H0 in H1; clear H0.\n  destruct H1; mytac.\n  left.\n  apply IS_OWNER_P_remove_tid_irrel in H0; eauto.  \n  right; split.\n  intro; apply H0; mytac; eexists.\n  apply IS_OWNER_remove_tid_irrel'; eauto.\n  eauto.\nQed.\n\n  \nLemma tickchange_getop_eq:\n  forall ct tls tls' t0 p st msg0 st' els els' p_ct',\n    TcbMod.get tls t0 = Some (p, st, msg0) ->\n    TcbMod.set tls t0 (p, st', msg0) = tls' ->\n    tickchange t0 st els st' els' ->\n    GET_OP ct tls' els' p_ct' ->\n    GET_OP ct tls els p_ct'.\nProof.\n  intros.\n  apply tickchange_els in H1.\n  destruct H1.\n  substs.\n  eapply GET_OP_st_irrel; eauto.\n  mytac.\n  assert(GET_OP ct tls (EcbMod.set els x (x0, remove_tid t0 x1)) p_ct').\n  eapply GET_OP_st_irrel; eauto.\n  eapply GET_OP_remove_tid_irrel; eauto.\nQed.\n  \nLemma tickchange_highestrdy_rdy:\n  forall ct tls tls' t0 p st msg0 st' els els',\n    TcbMod.get tls t0 = Some (p, st, msg0) ->\n    TcbMod.set tls t0 (p, st', msg0) = tls' ->\n    tickchange t0 st els st' els' ->\n    HighestRdy tls' ct ->\n    (exists p msg, TcbMod.get tls ct = Some (p,rdy,msg)) -> \n    HighestRdy tls ct.\nProof.\n\n  intros.\n  assert ( t0 = ct \\/ t0 <> ct ) by tauto.\n  destruct H4.\n  subst.\n  mytac.\n  rewrite H0 in H;inverts H.\n  inverts H1;tryfalse;auto.\n  destruct H;tryfalse.\n  rewrite TcbMod.get_set_same in H2;auto.\n  destruct H;tryfalse.\n  destruct H;tryfalse.\n  destruct H;tryfalse.\n  clear H3.\n  rename H4 into H3.\n  \n  unfolds in H2; unfolds; mytac.\n  rewrite TcbMod.set_a_get_a' in H2.\n  do 2 eexists; mytac; eauto.\n  intros.\n  eapply H4; eauto.\n  destruct (tidspec.beq t0 i) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite H5 in H; inverts H.\n  rewrite TcbMod.set_a_get_a; eauto.\n  inverts H1; substs; eauto; tryfalse.\n  rewrite TcbMod.set_a_get_a'; eauto.\n  apply tidspec.neq_beq_false; auto.\nQed.\n\n\n\nLemma tickchange_no_owner:\n  forall ct tls tls' t0 p st msg0 st' els els',\n    TcbMod.get tls t0 = Some (p, st, msg0) ->\n    TcbMod.set tls t0 (p, st', msg0) = tls' ->\n    tickchange t0 st els st' els' ->\n    ~ (exists eid, IS_OWNER ct eid els') ->\n    ~ (exists eid, IS_OWNER ct eid els).\nProof.\n  intros.\n  apply tickchange_els in H1; destruct H1.\n  substs; eauto.\n  mytac; intro; apply H2; mytac.\n  eexists; eapply IS_OWNER_remove_tid_irrel'; eauto.\nQed.\n\nLemma tickchange_nonone:\n  forall ct tls tls' t0 p st msg0 st' els els',\n    TcbMod.get tls t0 = Some (p, st, msg0) ->\n    TcbMod.set tls t0 (p, st', msg0) = tls' ->\n    tickchange t0 st els st' els' ->\n    TcbMod.get tls' ct <> None ->\n    TcbMod.get tls ct <> None.\nProof.\n  intros.\n  intro; apply H2.\n  destruct (tidspec.beq t0 ct) eqn:eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite H3 in H; tryfalse.\n  substs; rewrite TcbMod.set_a_get_a'; auto.\nQed.\n\nLemma tickchange_iswait:\n  forall ct tls tls' t0 p st msg0 st' els els',\n    TcbMod.get tls t0 = Some (p, st, msg0) ->\n    TcbMod.set tls t0 (p, st', msg0) = tls' ->\n    tickchange t0 st els st' els' ->\n    IS_WAITING ct els' ->\n    IS_WAITING ct els.\nProof.\n  intros.\n  apply tickchange_els in H1; destruct H1.\n  substs; auto.\n  mytac.\n  unfolds; unfolds in H2; mytac.\n  destruct(tidspec.beq x x2) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a in H0; auto; inverts H0.\n  do 4 eexists; split; eauto.\n  Lemma In_remove_tid : forall wl t ct, In ct (remove_tid t wl) -> In ct wl.\n  Proof.\n    inductions wl; intros.\n    simpl in H; tryfalse.\n    simpl in H.\n    destruct (beq_tid t a) eqn : eq1.\n    simpl.\n    right; eapply IHwl; eauto.\n    simpl in H; destruct H; substs.\n    simpl; left; auto.\n    simpl; right; eapply IHwl; eauto.\n  Qed.\n  eapply In_remove_tid; eauto.\n\n  rewrite EcbMod.set_a_get_a' in H0; eauto.\n  do 4 eexists; split; eauto.\nQed.\n\nLemma tickchange_nonestpend:\n  forall tls tls' t0 p st msg0 st' els els',\n    TcbMod.get tls t0 = Some (p, st, msg0) ->\n    TcbMod.set tls t0 (p, st', msg0) = tls' ->\n    tickchange t0 st els st' els' ->\n    NO_NEST_PENDING tls els ->\n    NO_NEST_PENDING tls' els'.\nProof.\n  intros.\n  apply tickchange_els in H1; destruct H1.\n  substs. \n  unfolds; intros; unfolds in H2.\n  assert(TcbMod.get tls t <> None).\n  intro; apply H0.\n  destruct(tidspec.beq t0 t) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite H3 in H; tryfalse.\n  rewrite TcbMod.set_a_get_a'; auto.\n  eapply H2; eauto.\n\n  mytac.\n  unfolds; intros; unfolds in H2.\n  assert(TcbMod.get tls t <> None).\n  destruct(tidspec.beq t0 t) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite H; auto.\n  rewrite TcbMod.set_a_get_a' in H0; auto.\n  assert(IS_OWNER t qid els).\n  eapply IS_OWNER_remove_tid_irrel; eauto.\n  lets Hx: H2 H4 H5; clear H2 H4 H5.\n  mytac.\n  intro; apply H2.\n  unfolds in H5; unfolds; mytac.\n  destruct(tidspec.beq x x2) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a in H5; auto; inverts H5.\n  do 4 eexists; mytac; eauto.\n  eapply In_remove_tid; eauto.\n  rewrite EcbMod.set_a_get_a' in H5; eauto.\n  do 4 eexists; mytac; eauto.\n  intro; apply H4; mytac.\n  exists x2; split; eauto.\n  eapply IS_OWNER_remove_tid_irrel; eauto.\nQed.\n\nLemma tickchange_exct:\n  forall tls els els' tls' t0 ct p st st' msg0,\n    tickchange t0 st els st' els' ->\n    TcbMod.set tls t0 (p, st', msg0) = tls' ->\n    TcbMod.get tls t0 = Some (p, st, msg0) ->\n    HighestRdy tls' ct ->\n    exists  pct stct mct,TcbMod.get tls ct = Some (pct,stct,mct).\nProof.\n  intros.\n  destruct(tidspec.beq t0 ct) eqn :eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  inverts H; eauto.\n  substs.\n  unfolds in H2; mytac.\n  rewrite TcbMod.set_a_get_a' in H0; eauto.\nQed.\n\nLemma tickchange_eq_prio:\n  forall tls els els' tls' t0 ct p msg0 pct pct' st st' stx stx' m m',\n    tickchange t0 st els st' els' ->\n    TcbMod.set tls t0 (p, st', msg0) = tls' ->\n    TcbMod.get tls t0 = Some (p, st, msg0) ->\n    TcbMod.get tls ct = Some (pct,stx,m) ->\n    TcbMod.get tls' ct = Some (pct',stx',m') ->\n    pct = pct'.\nProof.\n  intros.\n  substs.\n  destruct(tidspec.beq t0 ct) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite TcbMod.set_a_get_a in H3; auto.\n  inverts H3; rewrite H2 in H1; inverts H1; auto.\n\n  rewrite TcbMod.set_a_get_a' in H3; auto.\n  rewrite H2 in H3; inverts H3; auto.\nQed.\n\nLemma tickchange_nonest_ct:\n  forall tls els els' tls' t0 ct p msg0 pct' st st' tm m eid x2,\n    rdy_notin_wl tls els ->\n    tickchange t0 st els st' els' ->\n    TcbMod.set tls t0 (p, st', msg0) = tls' ->\n    TcbMod.get tls t0 = Some (p, st, msg0) ->\n    IS_OWNER ct x2 els' -> \n    TcbMod.get tls ct = Some (pct', wait (os_stat_mutexsem eid) tm, m) ->\n    NO_NEST_PENDING tls els ->\n    False.\nProof.\n  intros.\n  inverts H0.\n\n  unfolds in H; mytac.\n  lets Hx: H0 H4; unfolds in Hx; mytac.\n  unfolds in H5.\n  assert(TcbMod.get tls ct <> None).\n  rewrite H4; auto.\n  lets Hx: H5 H9 H3.\n  mytac.\n  apply H10.\n  unfolds.\n  exists eid x x0 x1.\n  split; auto.\n\n  unfolds in H; mytac.\n  lets Hx: H0 H4; unfolds in Hx; mytac.\n  unfolds in H5.\n  assert(TcbMod.get tls ct <> None).\n  rewrite H4; auto.\n  lets Hx: H5 H9 H3.\n  mytac.\n  apply H10.\n  unfolds.\n  exists eid x x0 x1.\n  split; auto.\n\n  unfolds in H; mytac.\n  lets Hx: H0 H4; unfolds in Hx; mytac.\n  unfolds in H5.\n  assert(TcbMod.get tls ct <> None).\n  rewrite H4; auto.\n  lets Hx: H5 H8 H3.\n  mytac.\n  apply H9.\n  unfolds.\n  exists eid x x0 x1.\n  split; auto.\n\n  unfolds in H; mytac.\n  lets Hx: H0 H4; unfolds in Hx; mytac.\n  unfolds in H5.\n  assert(TcbMod.get tls ct <> None).\n  rewrite H4; auto.\n  lets Hx: H5 H11 H3.\n  mytac.\n  apply H12.\n  unfolds.\n  exists eid x0 x1 x3.\n  split; auto.\n\n  clear H6.\n  assert(IS_OWNER ct x2 els).\n  eapply IS_OWNER_remove_tid_irrel; eauto.\n  unfolds in H; mytac.\n  lets Hx: H6 H4; unfolds in Hx; mytac.\n  unfolds in H5.\n  assert(TcbMod.get tls ct <> None).\n  rewrite H4; auto.\n  lets Hx: H5 H10 H0.\n  mytac.\n  apply H11.\n  unfolds.\n  exists eid x0 x1 x3.\n  split; auto.\nQed.\n\n\n\nLemma joinsig_neq_get:\n  forall x y els els0 s eid,\n    eid <> x ->\n    EcbMod.get els0 eid = s ->\n    EcbMod.joinsig x y els els0 ->\n    EcbMod.get els eid = s.\nProof.\n  intros.\n  pose proof H1 eid.\n  rewrite EcbMod.get_sig_none in H2; auto.\n  destruct (EcbMod.get els eid);\n  destruct (EcbMod.get els0 eid); tryfalse; substs; auto.\nQed.\n\nLemma ecb_joinsig_get_eq'\n: forall (x6 : tidspec.A) (x3 : int32) (x4 els : EcbMod.map)\n         (x8 : waitset) a0 (x9 : int32) (x : tidspec.A),\n    EcbMod.joinsig x6 (absmutexsem x3 None, nil) els x4->\n    EcbMod.get x4 x = Some (absmutexsem x9 (Some a0), x8) ->\n    EcbMod.get els x = Some (absmutexsem x9 (Some a0), x8).\nProof.\n  intros.\n  pose proof H x.\n  rewrite H0 in H1.\n  destruct (tidspec.beq x6 x) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.get_sig_some in H1.\n  destruct (EcbMod.get els x); tryfalse.\n  rewrite EcbMod.get_sig_none in H1.\n  destruct(EcbMod.get els x); tryfalse.\n  substs; auto.\n  apply tidspec.beq_false_neq; auto.\nQed.\n\nLemma is_owner_set_other:\n  forall t eid els x x3 x4 x5 ct,\n    t <> ct ->\n    IS_OWNER t eid els ->\n    EcbMod.get els x = Some (absmutexsem x3 None, x4) ->\n    IS_OWNER t eid\n             (EcbMod.set els x (absmutexsem x3 (Some (ct, x5)), x4)).\nProof.\n  intros.\n  unfolds; unfolds in H0; mytac.\n  destruct(tidspec.beq x eid) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a; auto.\n  rewrite H0 in H1; inverts H1.\n  rewrite EcbMod.set_a_get_a'; auto.\n  eauto.\nQed.\n\n\nLemma pend_lift_getop_ct:\n  forall (tls : TcbMod.map) (ct x10 : tidspec.A) \n         (x13 : priority) (x2 : msg) (x12 : priority) \n         (x14 : taskstatus) (x15 : msg) (x11 : int32) \n         (x : tidspec.A) (x8 : waitset) (x9 : int32) \n         (p_t : int32) (els : EcbMod.map) \n         (x0 : int32) (st : taskstatus),\n    x10 <> ct ->\n    TcbMod.get tls ct = Some (x13, st, x2) ->\n    TcbMod.get tls x10 = Some (x12, x14, x15) ->\n    EcbMod.get els x = Some (absmutexsem x9 (Some (x10, x11)), x8) ->\n    GET_OP ct\n           (TcbMod.set\n              (TcbMod.set tls ct (x13, wait (os_stat_mutexsem x) x0, x2)) x10\n              (x9, x14, x15))\n           (EcbMod.set els x (absmutexsem x9 (Some (x10, x11)), ct :: x8)) p_t ->\n    GET_OP ct tls els p_t.\nProof.\n  intros.\n  unfolds; intros.\n  assert(TcbMod.get (TcbMod.set\n            (TcbMod.set tls ct (x13, wait (os_stat_mutexsem x) x0, x2)) x10\n            (x9, x14, x15)) ct <> None).\n  rewrite TcbMod.set_a_get_a'.\n  rewrite TcbMod.set_a_get_a; auto.\n  apply tidspec.eq_beq_true; auto.\n  apply tidspec.neq_beq_false; auto.\n  apply H3 in H5; clear H3; destruct H5; mytac.\n  left.\n  unfolds in H3; mytac.\n  destruct (tidspec.beq x x1) eqn: eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a in H3; auto; inverts H3; tryfalse.\n  rewrite EcbMod.set_a_get_a' in H3; auto.\n  exists x1; unfolds; eauto.\n\n  right.\n  split.\n  intro; apply H3.\n  destruct H6; unfolds in H6; mytac.\n  destruct(tidspec.beq x x4) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite H6 in H2; inverts H2; tryfalse.\n  exists x4; unfolds; rewrite EcbMod.set_a_get_a'; eauto.\n  rewrite TcbMod.set_a_get_a' in H5.\n  rewrite TcbMod.set_a_get_a in H5.\n  inverts H5; eauto.\n  apply tidspec.eq_beq_true; auto.\n  apply tidspec.neq_beq_false; auto.\nQed.\n\nLemma post_iswait:\n  forall t x11 x12 x x6 els owner owner',\n    t <> x12 ->\n    EcbMod.get els x = Some (absmutexsem x6 owner, x11) ->\n    (IS_WAITING t\n               (EcbMod.set els x\n                           (absmutexsem x6 owner', remove_tid x12 x11)) <->\n    IS_WAITING t els).\nProof.\n  intros.\n  split; intros.\n  unfolds in H1; mytac.\n  unfolds.\n  destruct(tidspec.beq x x0) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a in H1; auto.\n  inverts H1.\n  do 4 eexists.\n  split; eauto.\n  eapply In_remove_tid; eauto.\n  rewrite EcbMod.set_a_get_a' in H1; auto.\n  do 4 eexists; split; eauto.\n\n  unfolds in H1; mytac.\n  unfolds.\n  destruct(tidspec.beq x x0) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite H1 in H0; inverts H0.\n  exists x0.\n  rewrite EcbMod.set_a_get_a; auto.\n  do 3 eexists; split; eauto.\n  Lemma In_remove_tid' : forall wl t t', t <> t' -> In t wl -> In t (remove_tid t' wl).\n  Proof.\n    intro; inductions wl; intros.\n    simpl in ; tryfalse.\n    simpl in H0; destruct H0; substs.\n    simpl.\n    destruct(beq_tid t' t) eqn : eq1.\n    false; apply H.\n    Lemma beq_tid_true_eq: forall t1 t2, beq_tid t1 t2 = true -> t1 = t2.\n    Proof.\n      intros.\n      unfolds in H; destruct t1; destruct t2.\n      apply andb_true_iff in H; destruct H.\n      rewrite beq_pos_Pos_eqb_eq in H.\n      apply Pos.eqb_eq in H.\n      pose proof Int.eq_spec i i0.\n      rewrite H0 in H1.\n      substs; auto.\n    Qed.\n    apply beq_tid_true_eq in eq1; auto.\n    simpl; auto.\n    simpl.\n    destruct(beq_tid t' a) eqn : eq1.\n    eapply IHwl; eauto.\n    simpl.\n    right.\n    eapply IHwl; eauto.\n  Qed.\n  eapply In_remove_tid'; eauto.\n\n  exists x0.\n  rewrite EcbMod.set_a_get_a'; auto.\n  eauto.\nQed.\n\nLemma post_iswait':\n  forall t x11 x12 x x6 eid els owner owner',\n    t <> x12 ->\n    EcbMod.get els x = Some (absmutexsem x6 owner, x11) ->\n    (IS_WAITING_E t eid\n                 (EcbMod.set els x\n                             (absmutexsem x6 owner', remove_tid x12 x11)) <->\n    IS_WAITING_E t eid els).\nProof.\n  intros.\n  split; intros.\n  unfolds in H1; mytac.\n  unfolds.\n  destruct(tidspec.beq x eid) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a in H1; auto; inverts H1.\n  do 3 eexists; split; eauto.\n  eapply In_remove_tid; eauto.\n  rewrite EcbMod.set_a_get_a' in H1; auto.\n  do 3 eexists; split; eauto.\n\n  unfolds in H1; mytac.\n  unfolds.\n  destruct(tidspec.beq x eid) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite H1 in H0; inverts H0.\n  rewrite EcbMod.set_a_get_a; auto.\n  do 3 eexists; split; eauto.\n  eapply In_remove_tid'; eauto.\n  rewrite EcbMod.set_a_get_a'; auto.\n  do 3 eexists; split; eauto.\nQed.\n\nLemma In_remove_tid_false : forall wl t, In t (remove_tid t wl) -> False.\nProof.\n  intro; inductions wl; intros.\n  simpl in H; auto.\n  simpl in H.\n  destruct (beq_tid t a) eqn : eq1.\n  eapply IHwl; eauto.\n  simpl in H.\n  destruct H.\n  substs.\n  Lemma beq_tid_true : forall t, beq_tid t t = true.\n  Proof.\n    intros.\n    unfolds; destruct t.\n    rewrite beq_pos_Pos_eqb_eq.\n    rewrite Pos.eqb_refl.\n    rewrite Int.eq_true.\n    simpl; auto.\n  Qed.\n  rewrite beq_tid_true in eq1; tryfalse.\n  eapply IHwl; eauto.\nQed.\n  \nLemma nnp_remove_nwait:\n  forall tls els x11 t x x6 ct x8 p x13 x14,\n    NO_NEST_PENDING tls els ->\n    rdy_notin_wl tls els ->\n    GetHWait tls x11 t ->\n    EcbMod.get els x = Some (absmutexsem x6 (Some (ct, x8)), x11) ->\n    TcbMod.get tls t = Some (p, x13, x14) ->\n    ~\n      IS_WAITING t\n      (EcbMod.set els x (absmutexsem x6 (Some (t, p)), remove_tid t x11)).\nProof.\n  intros.\n  intro.\n  unfolds in H4; mytac.\n  destruct(tidspec.beq x x0) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a in H4; auto.\n  inverts H4.\n  eapply In_remove_tid_false; eauto.\n\n  rewrite EcbMod.set_a_get_a' in H4; auto.\n  unfolds in H1; mytac.\n  unfolds in H0; mytac.\n  assert(IS_WAITING_E t x els).\n  unfolds; do 3 eexists; split; eauto.\n  assert(IS_WAITING_E t x0 els).\n  unfolds; do 3 eexists; split; eauto.\n  lets Hx1 : H9 H10.\n  lets Hx2 : H9 H11.\n  mytac.\n  rewrite H13 in H12; inverts H12.\n  assert(tidspec.beq x0 x0 = true).\n  apply tidspec.eq_beq_true; auto.\n  rewrite eq1 in H12; tryfalse.\nQed.\n\nLemma remove_is_wait_neq:\n  forall x12 t x x6 x7 x11 els ct x8,\n    t <> x12 ->\n    EcbMod.get els x = Some (absmutexsem x6 (Some (ct, x8)), x11) ->\n    IS_WAITING t\n               (EcbMod.set els x\n                           (absmutexsem x6 (Some (x12, x7)), remove_tid x12 x11)) ->\n    IS_WAITING t els.\nProof.\n  intros.\n  unfolds in H1; mytac.\n  destruct (tidspec.beq x x0) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a in H1; auto; inverts H1.\n  unfolds; exists x0 x1 (Some (ct, x8)) x11.\n  split; auto.\n  eapply In_remove_tid; eauto.\n\n  rewrite EcbMod.set_a_get_a' in H1; auto.\n  unfolds.\n  exists x0 x1 x2 x3; split; eauto.\nQed.\n\nLemma tickchange_not_waiting:\n  forall tls t p0 eid m0 m wl els,\n    EcbMod.get els eid = Some (m, wl) ->\n    TcbMod.get tls t = Some (p0, wait (os_stat_mutexsem eid) Int.one, m0)->\n    rdy_notin_wl tls els ->\n    NO_NEST_PENDING tls els ->\n    ~ IS_WAITING t (EcbMod.set els eid (m, remove_tid t wl)).\nProof.\n  intros.\n  unfolds in H1; mytac.\n  lets Hx: H3 H0.\n  unfolds in Hx; mytac.\n  intro; unfolds in H7; mytac.\n  destruct (tidspec.beq eid x2) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.set_a_get_a in H7; auto; inverts H7.\n  \n  eapply In_remove_tid_false; eauto.\n\n  rewrite EcbMod.set_a_get_a' in H7; auto.\n  assert(IS_WAITING_E t eid els).\n  unfolds; do 3 eexists; split; eauto.\n  assert(IS_WAITING_E t x2 els).\n  unfolds; do 3 eexists; split; eauto.\n  lets Hx1: H4 H9.\n  lets Hx2: H4 H10.\n  mytac.\n  rewrite H12 in H11.\n  inverts H11.\n  assert(tidspec.beq x2 x2 = true).\n  apply tidspec.eq_beq_true; auto.\n  rewrite eq1 in H11; tryfalse.\nQed.\n\n\nLemma remove_tid_in_false:\n  forall t wl,\n    In t (remove_tid t wl) -> False.\nProof.\n  intros; gen t.\n  inductions wl; intros.\n  simpl in H; auto.\n  simpl in H.\n  destruct(beq_tid t a) eqn : eq1.\n  eapply IHwl; eauto.\n  \n  simpl in H; destruct H.\n  substs; unfolds in eq1; destruct t.\n  apply andb_false_iff in eq1; destruct eq1.\n  rewrite beq_pos_Pos_eqb_eq in H.\n  assert(b = b) by auto.\n  apply Pos.eqb_eq in H0.\n  rewrite H in H0; tryfalse.\n  rewrite Int.eq_true in H; tryfalse.\n  eapply IHwl; eauto.\nQed.\n(*-----------------------*)\n\nFixpoint GoodStmt_h (s : stmts) {struct s} : Prop :=\n  match s with\n    | sskip _ => True\n    | sassign _ _ => True\n    | sif _ s1 s2 => GoodStmt_h s1 /\\ GoodStmt_h s2\n    | sifthen _ _ => False\n    | swhile _ s' => GoodStmt_h s'\n    | sret => True\n    | srete  _ => True\n    | scall f _ => True\n    | scalle _ f _ => True\n    | sseq s1 s2 => GoodStmt_h s1 /\\ GoodStmt_h s2\n    | sprint _ => True\n    | sfexec _ _ _ => False\n    | sfree _ _ => False\n    | salloc _ _ => False\n    | sprim _ => False\n    | hapi_code _ => False\n  end.\n\nDefinition GoodAcc (s:spec_code) vl:=\n  (s = mutexacc_null (|vl|)\n                     ?? mutexacc_no_mutex_err (|vl|)\n                     ?? mutexacc_no_available (|vl|)\n                     ?? mutexacc_prio_err (|vl|) ?? mutexacc_succ (|vl|)) \\/\n  s = mutexacc_null (|vl|) \\/\n  (s = mutexacc_no_mutex_err (|vl|)\n                             ?? mutexacc_no_available (|vl|)\n                             ?? mutexacc_prio_err (|vl|) ?? mutexacc_succ (|vl|)) \\/\n  s = mutexacc_no_mutex_err (|vl|) \\/\n  (s = mutexacc_no_available (|vl|)\n                             ?? mutexacc_prio_err (|vl|) ?? mutexacc_succ (|vl|))\\/\n  s = mutexacc_no_available (|vl|)\\/\n  (s = mutexacc_prio_err (|vl|) ?? mutexacc_succ (|vl|) ) \\/\n  s = mutexacc_prio_err (|vl|) \\/\n  s = mutexacc_succ (|vl|) \\/\n  exists v, s = spec_done v.\n\nDefinition GoodCre (s:spec_code) vl:=\n  (s = mutexcre_error (|vl|) ?? mutexcre_succ (|vl|)) \\/\n  s = mutexcre_error (|vl|) \\/\n  s = mutexcre_succ (|vl|) \\/\n  exists v, s = spec_done v.\n\nDefinition GoodDel (s:spec_code) vl:=\n  (s = mutexdel_null (|vl|)\n                     ?? mutexdel_no_mutex_err (|vl|)\n                     ?? mutexdel_type_err (|vl|)\n                     ?? mutexdel_ex_wt_err (|vl|) ?? mutexdel_succ (|vl|) ?? mutexdel_pr_not_holder_err (|vl|)) \\/\n  (s = mutexdel_null (|vl|)) \\/\n  (s = mutexdel_no_mutex_err (|vl|)\n                     ?? mutexdel_type_err (|vl|)\n                     ?? mutexdel_ex_wt_err (|vl|) ?? mutexdel_succ (|vl|) ?? mutexdel_pr_not_holder_err (|vl|) ) \\/\n  (s = mutexdel_no_mutex_err (|vl|)) \\/\n  (s = mutexdel_type_err (|vl|)\n                         ?? mutexdel_ex_wt_err (|vl|) ?? mutexdel_succ (|vl|)?? mutexdel_pr_not_holder_err (|vl|)) \\/\n  (s = mutexdel_type_err (|vl|)) \\/\n  (s = mutexdel_ex_wt_err (|vl|) ?? mutexdel_succ (|vl|)?? mutexdel_pr_not_holder_err (|vl|)) \\/\n  (s = mutexdel_ex_wt_err (|vl|)) \\/\n  (s = mutexdel_succ (|vl|)?? mutexdel_pr_not_holder_err (|vl|)) \\/\n  s = mutexdel_succ (|vl|) \\/\n  s = mutexdel_pr_not_holder_err (|vl|) \\/\n  exists v, s = spec_done v.\n\n\nDefinition GoodPend (s:spec_code) vl :=\n  s = mutexpend_null (|vl|)\n                     ?? mutexpend_no_mutex_err (|vl|)\n                     ?? mutexpend_type_err (|vl|)\n                     ?? mutexpend_idle_err (|vl|)\n                     ?? mutexpend_stat_err (|vl|)\n                     ?? mutexpend_prio_err (|vl|)\n                     ?? mutexpend_get_succ (|vl|)\n                     ?? (mutexpend_block_lift (|vl|)\n                                              ?? mutexpend_block_no_lift (|vl|));;\n                     isched;;\n                     (mutexpend_to (|vl|) ?? mutexpend_block_get (|vl|))  ?? mutexpend_pr_not_holder_err (|vl|) ??\n                     mutexpend_nest_err (|vl|) ?? mutexpend_deadlock_err (|vl|)\n                     ?? mutexpend_msg_not_null_err (|vl|) ?? mutexpend_cur_prio_eql_mprio_err\n                                       (|vl|)\n                                       ?? mutexpend_ptcb_prio_eql_idle_err\n                                          (|vl|)\n  \\/\n  s = mutexpend_null (|vl|) \\/\n  s = mutexpend_no_mutex_err (|vl|)\n                             ?? mutexpend_type_err (|vl|)\n                             ?? mutexpend_idle_err (|vl|)\n                             ?? mutexpend_stat_err (|vl|)\n                             ?? mutexpend_prio_err (|vl|)\n                             ?? mutexpend_get_succ (|vl|)\n                             ?? (mutexpend_block_lift (|vl|)\n                                                      ?? mutexpend_block_no_lift (|vl|));;\n                                                      isched;;\n                                                      (mutexpend_to (|vl|) ?? mutexpend_block_get (|vl|))  ?? mutexpend_pr_not_holder_err (|vl|) ??\n  mutexpend_nest_err (|vl|) ?? mutexpend_deadlock_err (|vl|)\n                              ?? mutexpend_msg_not_null_err (|vl|) ?? mutexpend_cur_prio_eql_mprio_err\n                                       (|vl|)\n                                       ?? mutexpend_ptcb_prio_eql_idle_err\n                                          (|vl|) \\/\n  s = mutexpend_no_mutex_err (|vl|) \\/\n  s = mutexpend_type_err (|vl|)\n                         ?? mutexpend_idle_err (|vl|)\n                         ?? mutexpend_stat_err (|vl|)\n                         ?? mutexpend_prio_err (|vl|)\n                         ?? mutexpend_get_succ (|vl|)\n                         ?? (mutexpend_block_lift (|vl|)\n                                                  ?? mutexpend_block_no_lift (|vl|));;\n                                                  isched;;\n                                                  (mutexpend_to (|vl|) ?? mutexpend_block_get (|vl|))  ?? mutexpend_pr_not_holder_err (|vl|)??\n  mutexpend_nest_err (|vl|) ?? mutexpend_deadlock_err (|vl|)\n                              ?? mutexpend_msg_not_null_err (|vl|) ?? mutexpend_cur_prio_eql_mprio_err\n                                       (|vl|)\n                                       ?? mutexpend_ptcb_prio_eql_idle_err\n                                          (|vl|) \\/\n  s = mutexpend_type_err (|vl|) \\/\n  s = mutexpend_idle_err (|vl|)\n                         ?? mutexpend_stat_err (|vl|)\n                         ?? mutexpend_prio_err (|vl|)\n                         ?? mutexpend_get_succ (|vl|)\n                         ?? (mutexpend_block_lift (|vl|)\n                                                  ?? mutexpend_block_no_lift (|vl|));;\n                                                  isched;;\n                                                  (mutexpend_to (|vl|) ?? mutexpend_block_get (|vl|))  ?? mutexpend_pr_not_holder_err (|vl|)??\n  mutexpend_nest_err (|vl|) ?? mutexpend_deadlock_err (|vl|)\n                              ?? mutexpend_msg_not_null_err (|vl|) ?? mutexpend_cur_prio_eql_mprio_err\n                                       (|vl|)\n                                       ?? mutexpend_ptcb_prio_eql_idle_err\n                                          (|vl|) \\/\n  s = mutexpend_idle_err (|vl|) \\/\n  s = mutexpend_stat_err (|vl|)\n                         ?? mutexpend_prio_err (|vl|)\n                         ?? mutexpend_get_succ (|vl|)\n                         ?? (mutexpend_block_lift (|vl|)\n                                                  ?? mutexpend_block_no_lift (|vl|));;\n                                                  isched;;\n                                                  (mutexpend_to (|vl|) ?? mutexpend_block_get (|vl|))  ?? mutexpend_pr_not_holder_err (|vl|)??\n  mutexpend_nest_err (|vl|) ?? mutexpend_deadlock_err (|vl|)\n                              ?? mutexpend_msg_not_null_err (|vl|) ?? mutexpend_cur_prio_eql_mprio_err\n                                       (|vl|)\n                                       ?? mutexpend_ptcb_prio_eql_idle_err\n                                          (|vl|)\\/\n  s = mutexpend_stat_err (|vl|) \\/\n  s = mutexpend_prio_err (|vl|)\n                         ?? mutexpend_get_succ (|vl|)\n                         ?? (mutexpend_block_lift (|vl|)\n                                                  ?? mutexpend_block_no_lift (|vl|));;\n                                                  isched;;\n                                                  (mutexpend_to (|vl|) ?? mutexpend_block_get (|vl|))  ?? mutexpend_pr_not_holder_err (|vl|)??\n  mutexpend_nest_err (|vl|) ?? mutexpend_deadlock_err (|vl|)\n                              ?? mutexpend_msg_not_null_err (|vl|) ?? mutexpend_cur_prio_eql_mprio_err\n                                       (|vl|)\n                                       ?? mutexpend_ptcb_prio_eql_idle_err\n                                          (|vl|) \\/\n  s = mutexpend_prio_err (|vl|)\\/\n  s = mutexpend_get_succ (|vl|)\n                         ?? (mutexpend_block_lift (|vl|)\n                                                  ?? mutexpend_block_no_lift (|vl|));;\n                                                  isched;;\n                                                  (mutexpend_to (|vl|) ?? mutexpend_block_get (|vl|)) ?? mutexpend_pr_not_holder_err (|vl|)??\n  mutexpend_nest_err (|vl|) ?? mutexpend_deadlock_err (|vl|)\n                              ?? mutexpend_msg_not_null_err (|vl|) ?? mutexpend_cur_prio_eql_mprio_err\n                                       (|vl|)\n                                       ?? mutexpend_ptcb_prio_eql_idle_err\n                                          (|vl|) \\/\n  s = mutexpend_get_succ (|vl|) \\/\n  s = (mutexpend_block_lift (|vl|)\n                            ?? mutexpend_block_no_lift (|vl|));;\n                            isched;;\n                            (mutexpend_to (|vl|) ?? mutexpend_block_get (|vl|))  ?? mutexpend_pr_not_holder_err (|vl|) ??\n  mutexpend_nest_err (|vl|) ?? mutexpend_deadlock_err (|vl|)\n                              ?? mutexpend_msg_not_null_err (|vl|) ?? mutexpend_cur_prio_eql_mprio_err\n                                       (|vl|)\n                                       ?? mutexpend_ptcb_prio_eql_idle_err\n                                          (|vl|)\\/\n\n  s = (mutexpend_block_lift (|vl|)\n                            ?? mutexpend_block_no_lift (|vl|));;\n                                                              isched;;\n                                                              (mutexpend_to (|vl|) ?? mutexpend_block_get (|vl|)) \\/\n  s = mutexpend_pr_not_holder_err (|vl|) ??\n                                  mutexpend_nest_err (|vl|) ?? mutexpend_deadlock_err (|vl|)\n                              ?? mutexpend_msg_not_null_err (|vl|) ?? mutexpend_cur_prio_eql_mprio_err\n                                       (|vl|)\n                                       ?? mutexpend_ptcb_prio_eql_idle_err\n                                          (|vl|) \\/\n  s = mutexpend_pr_not_holder_err (|vl|) \\/\n  s = mutexpend_nest_err (|vl|) ?? mutexpend_deadlock_err (|vl|)\n                         ?? mutexpend_msg_not_null_err (|vl|) ?? mutexpend_cur_prio_eql_mprio_err\n                                       (|vl|)\n                                       ?? mutexpend_ptcb_prio_eql_idle_err\n                                          (|vl|) \\/\n  s = mutexpend_nest_err (|vl|) \\/\n  s = mutexpend_deadlock_err (|vl|)\n                             ?? mutexpend_msg_not_null_err (|vl|) ?? mutexpend_cur_prio_eql_mprio_err\n                                       (|vl|)\n                                       ?? mutexpend_ptcb_prio_eql_idle_err\n                                          (|vl|) \\/\n  s = mutexpend_deadlock_err (|vl|) \\/\n  s = mutexpend_msg_not_null_err (|vl|) ?? mutexpend_cur_prio_eql_mprio_err\n                                       (|vl|)\n                                       ?? mutexpend_ptcb_prio_eql_idle_err\n                                       (|vl|) \\/\n  s = mutexpend_msg_not_null_err (|vl|) \\/\n  s = mutexpend_cur_prio_eql_mprio_err\n                                       (|vl|)\n                                       ?? mutexpend_ptcb_prio_eql_idle_err\n                                       (|vl|) \\/\n  s = mutexpend_cur_prio_eql_mprio_err\n        (|vl|) \\/\n  s = mutexpend_ptcb_prio_eql_idle_err\n        (|vl|) \\/\n  s = mutexpend_block_lift (|vl|)\n                            ;;\n                            isched;;\n                            (mutexpend_to (|vl|) ?? mutexpend_block_get (|vl|)) \\/\n\n  s = mutexpend_block_no_lift (|vl|)\n                            ;;\n                            isched;;\n                            (mutexpend_to (|vl|) ?? mutexpend_block_get (|vl|)) \\/\n  s = spec_done None ;; isched ;;\n                            (mutexpend_to (|vl|) ?? mutexpend_block_get (|vl|)) \\/\n  s = isched ;; (mutexpend_to (|vl|) ?? mutexpend_block_get (|vl|)) \\/\n  s = (ASSUME sc;; sched) ;;(mutexpend_to (|vl|) ?? mutexpend_block_get (|vl|)) \\/\n  s = (spec_done None;;sched) ;; (mutexpend_to (|vl|) ?? mutexpend_block_get (|vl|)) \\/\n  s = sched;;(mutexpend_to (|vl|) ?? mutexpend_block_get (|vl|)) \\/\n  s = ASSUME nsc;;(mutexpend_to (|vl|) ?? mutexpend_block_get (|vl|)) \\/\n  s = spec_done None;;(mutexpend_to (|vl|) ?? mutexpend_block_get (|vl|)) \\/\n  s = mutexpend_to (|vl|) ?? mutexpend_block_get (|vl|) \\/\n  s = mutexpend_to (|vl|)  \\/\n  s = mutexpend_block_get (|vl|) \\/\n  exists v, s = spec_done v.\n\nOpen Scope int_scope.\nDefinition GoodPost (s:spec_code) vl:=\n  s = mutexpost_null (|vl|)\n                     ?? mutexpost_no_mutex_err (|vl|)\n                     ?? mutexpost_type_err (|vl|)\n                     ?? mutexpost_no_owner_err (|vl|)\n                     ?? mutexpost_nowt_return_prio_succ (|vl|)\n                                                         ?? mutexpost_nowt_no_return_prio_succ (|vl|)\n\n                                                           ?? (mutexpost_exwt_return_prio_succ (|vl|)\n                                                              ?? mutexpost_exwt_no_return_prio_succ (|vl|))\n                                                         ;;isched;; END Some (V$NO_ERR)??\n                     mutexpost_original_not_holder_err (|vl|) ??\n                     mutexpost_prio_err (|vl|)  ?? mutexpost_wl_highest_prio_err (|vl|) \\/\n  s = mutexpost_null (|vl|) \\/\n  s = mutexpost_no_mutex_err (|vl|)\n                             ?? mutexpost_type_err (|vl|)\n                             ?? mutexpost_no_owner_err (|vl|)\n                             ?? mutexpost_nowt_return_prio_succ (|vl|)\n                                                                  ?? mutexpost_nowt_no_return_prio_succ (|vl|)\n                                                                  ?? (mutexpost_exwt_return_prio_succ (|vl|)\n                                                                  ?? mutexpost_exwt_no_return_prio_succ (|vl|))\n                                   ;;isched;; END Some (V$NO_ERR)??\n                     mutexpost_original_not_holder_err (|vl|) ??\n                     mutexpost_prio_err (|vl|)  ?? mutexpost_wl_highest_prio_err (|vl|) \\/\n  s = mutexpost_no_mutex_err (|vl|) \\/\n  s = mutexpost_type_err (|vl|)\n                         ?? mutexpost_no_owner_err (|vl|)\n                         ?? mutexpost_nowt_return_prio_succ (|vl|)\n                                                              ?? mutexpost_nowt_no_return_prio_succ (|vl|)\n                                                              ?? (mutexpost_exwt_return_prio_succ (|vl|)\n                                                              ?? mutexpost_exwt_no_return_prio_succ (|vl|))\n                               ;;isched;; END Some (V$NO_ERR)??\n                     mutexpost_original_not_holder_err (|vl|) ??\n                     mutexpost_prio_err (|vl|)  ?? mutexpost_wl_highest_prio_err (|vl|)\\/\n  s = mutexpost_type_err (|vl|) \\/\n  s = mutexpost_no_owner_err (|vl|)\n                             ?? mutexpost_nowt_return_prio_succ (|vl|)\n                                                                  ?? mutexpost_nowt_no_return_prio_succ (|vl|)\n                                                                  ?? (mutexpost_exwt_return_prio_succ (|vl|)\n                                                                  ?? mutexpost_exwt_no_return_prio_succ (|vl|))\n                                   ;;isched;; END Some (V$NO_ERR)??\n                     mutexpost_original_not_holder_err (|vl|) ??\n                     mutexpost_prio_err (|vl|)  ?? mutexpost_wl_highest_prio_err (|vl|) \\/\n  s = mutexpost_no_owner_err (|vl|) \\/\n  s = mutexpost_nowt_return_prio_succ (|vl|)\n                                        ?? mutexpost_nowt_no_return_prio_succ (|vl|)\n                                        ?? (mutexpost_exwt_return_prio_succ (|vl|)\n                                        ?? mutexpost_exwt_no_return_prio_succ (|vl|))\n         ;;isched;; END Some (V$NO_ERR)??\n                     mutexpost_original_not_holder_err (|vl|) ??\n                     mutexpost_prio_err (|vl|) ?? mutexpost_wl_highest_prio_err (|vl|) \\/\n  s = mutexpost_nowt_return_prio_succ (|vl|) \\/\n  s = mutexpost_nowt_no_return_prio_succ (|vl|)\n                                        ?? (mutexpost_exwt_return_prio_succ (|vl|)\n                                        ?? mutexpost_exwt_no_return_prio_succ (|vl|))\n         ;;isched;; END Some (V$NO_ERR) ?? mutexpost_original_not_holder_err (|vl|) ??\n                     mutexpost_prio_err (|vl|) ?? mutexpost_wl_highest_prio_err (|vl|) \\/\n  s = mutexpost_nowt_no_return_prio_succ (|vl|) \\/\n  s = (mutexpost_exwt_return_prio_succ (|vl|)\n                                        ?? mutexpost_exwt_no_return_prio_succ (|vl|))\n         ;;isched;; END Some (V$NO_ERR) ?? mutexpost_original_not_holder_err (|vl|) ??\n                     mutexpost_prio_err (|vl|)  ?? mutexpost_wl_highest_prio_err (|vl|)\\/\n  s = (mutexpost_exwt_return_prio_succ (|vl|)\n                                        ?? mutexpost_exwt_no_return_prio_succ (|vl|))\n       ;;isched;; END Some (V$NO_ERR) \\/                             \n  s = mutexpost_original_not_holder_err (|vl|) ??\n                                        mutexpost_prio_err (|vl|) ?? mutexpost_wl_highest_prio_err (|vl|) \\/\n  s = mutexpost_exwt_return_prio_succ (|vl|);;isched;; END Some (V$NO_ERR) \\/\n  s = mutexpost_exwt_no_return_prio_succ (|vl|);;isched;; END Some (V$NO_ERR) \\/\n  s = spec_done None ;;isched;; END Some (V$NO_ERR) \\/\n  s = isched;; END Some (V$NO_ERR) \\/\n  s = (ASSUME sc;; sched) ;; END Some (V$NO_ERR) \\/\n  s = (spec_done None;;sched) ;;END Some (V$NO_ERR) \\/\n  s = sched;; END Some (V$NO_ERR) \\/\n  s = ASSUME nsc;;END Some (V$NO_ERR) \\/\n  s = END None;;END Some (V$NO_ERR) \\/\n  s = mutexpost_original_not_holder_err (|vl|) \\/\n  s = mutexpost_prio_err (|vl|)  ?? mutexpost_wl_highest_prio_err (|vl|) \\/\n  s = mutexpost_prio_err (|vl|) \\/\n  s = mutexpost_wl_highest_prio_err (|vl|) \\/\n  exists v, s = spec_done v.\n\nDefinition GoodTick s:=\n  s = timetick_spec (|nil|);;\n                    ((isched;; END None)\n                            ?? END None) \\/\n  s = spec_done None;;\n                    ( (isched;; END None)\n                            ?? END None) \\/\n  s =  ( (isched;; END None)\n                            ?? END None)  \\/\n  s = (isched;; END None) \\/\n  s = (ASSUME sc;; sched) ;; END None \\/\n  s = (spec_done None;;sched) ;;END None \\/\n  s = sched;; END None \\/\n  s = ASSUME nsc;;END None \\/\n  s = spec_done None;;END None \\/\n  exists v, s = spec_done v.\n\nDefinition GoodToy s:=\n  s = toyint_spec (|nil|);;\n                    ((isched;; END None)\n                            ?? END None) \\/\n  s = spec_done None;;\n                    ( (isched;; END None)\n                            ?? END None) \\/\n  s =  ( (isched;; END None)\n                            ?? END None)  \\/\n  s = (isched;; END None) \\/\n  s = (ASSUME sc;; sched) ;; END None \\/\n  s = (spec_done None;;sched) ;;END None \\/\n  s = sched;; END None \\/\n  s = ASSUME nsc;;END None \\/\n  s = spec_done None;;END None \\/\n  exists v, s = spec_done v.\n\nDefinition good_api_stmt s:=\n  (exists vl, GoodAcc s vl) \\/\n  (exists vl, GoodCre s vl) \\/\n  (exists vl, GoodDel s vl) \\/\n  (exists vl, GoodPend s vl) \\/\n  (exists vl, GoodPost s vl) \\/\n  ( GoodTick s ) \\/\n  ( GoodToy s ).\n\nFixpoint goodstmt_h (s : stmts) {struct s} : Prop :=\n  match s with\n    | sskip _ => True\n    | sassign _ _ => True\n    | sif _ s1 s2 => goodstmt_h s1 /\\ goodstmt_h s2\n    | sifthen _ s => goodstmt_h s\n    | swhile _ s' => goodstmt_h s'\n    | sret => True\n    | srete _ => True\n    | scall f _ => True\n    | scalle _ f _ => True\n    | sseq s1 s2 => goodstmt_h s1 /\\ goodstmt_h s2\n    | sprint _ => True\n    | sfexec _ _ _ => True\n    | sfree _ _ => True\n    | salloc _ _ => True\n    | sprim _ => False\n    | hapi_code s => good_api_stmt s\n  end.\n\nDefinition goodeval_h (c:cureval):=\n  match c with\n    | cure _ => True\n    | curs s => goodstmt_h s\n  end.\n\nFixpoint goodks_h ks:=\n  match ks with\n    | kint _ _ _ _ => False\n    | kevent c ke ks' => goodeval_h c /\\ goodks_h ks'\n    | kstop => True\n    | kcall _ s _ ks' => goodks_h ks' /\\ goodstmt_h s\n    | kseq s ks' => goodks_h ks' /\\ goodstmt_h s\n    | kassignr _ _ ks' => goodks_h ks'\n    | kassignl _ _ ks' => goodks_h ks'\n    | kfuneval _ _ _ _ ks' => goodks_h ks'\n    | kif s1 s2 ks' => goodks_h ks' /\\ goodstmt_h s1 /\\ goodstmt_h s2\n    | kwhile _ s ks' => goodks_h ks' /\\ goodstmt_h s\n    | kret ks' => goodks_h ks'\n  end.\n\nDefinition goodcode_h (c:code):=\n  match c with\n    | (c,(ke,ks)) => goodeval_h c /\\ goodks_h ks\n  end.\n\nDefinition goodtasks_h T:=\n  forall t c, TasksMod.get T t = Some c -> goodcode_h c.\n\n\nDefinition no_nest_client (client_code:progunit) O T cst:=\n  forall  T' cst' O',\n    hpstepstar (client_code, os_spec') T cst O T' cst' O' ->\n    NO_NEST_PENDING_O O'.\n\n\nDefinition good_client_code client_code :=\n      (forall (f : fid) (a : type) (b c : decllist) (s : stmts),\n       client_code f = Some (a, b, c, s) -> GoodStmt_h s).\n\nDefinition INV_PROP (client_code:progunit) O T cst :=\n  good_client_code client_code /\\ no_nest_client  client_code O T cst /\\ GOOD_ST O.\n\nDefinition apibound (api: fid -> option osapi)   T  (O:osabst) : Prop :=\n  exists t  C ks cd f tl,\n         exists (s:spec_code) tp  vl,\n     OSAbstMod.get O curtid = Some (oscurt t) /\\\n     TasksMod.get T t = Some C /\\\n     C = (curs (hapi_code (cd vl)), (kenil,ks))\n     /\\ api f = Some (cd, (tp,tl))  /\\ s = cd vl.\n\n\nDefinition intbound (ints : hid -> option int_code) \n           (T : TasksMod.map)  (O:osabst) : Prop := \n  exists cd h  t ke ks  c s C,\n      OSAbstMod.get O curtid = Some (oscurt t) /\\\n      TasksMod.get T t = Some C /\\\n      C = (curs (hapi_code s), (kenil, kevent c ke ks))\n       /\\ ints h = Some cd /\\ s = cd.\n\nRequire Import auxdef.\nLemma good_clt_imp :\n  forall C pc, good_clt C pc -> \n      ~(exists s' ke' ks', C = (curs (hapi_code s'), (ke',ks'))).\nProof.\n  intros.\n  introv Hf.\n  mytac.\n  simpl in H.\n  mytac.\n  auto.\nQed.\n\nLemma cstep_good_clt_hold:\n  forall pc C m C' m' ,\n    good_clt C pc ->\n    cstep pc C m C' m' ->\n    good_clt C' pc.\n Proof.\n   introv Hgood Hcs.\n   inverts Hcs.\n   inverts H0; simpl; auto.\n   inverts H0; simpl; auto; simpl in Hgood;\n   mytac; auto.\n   rewrite H in H2.\n   tryfalse.\n   eapply step_prop.good_clt_scont_callcont; eauto.\nQed.   \n \n\n Definition nhapi T pc :=\n   forall  t C,  TasksMod.get T t = Some C ->  good_clt C pc .\n\n\n Lemma nhapi_set_hold:\n   forall T C t pc,          \n     nhapi T pc-> \n     good_clt C pc ->\n     nhapi (TasksMod.set T t C) pc.\n Proof.   \n   introv Hnp Hne.\n   unfolds in Hnp.\n   unfolds.\n   intros.\n   rewrite TasksMod.set_sem in H.\n   assert (t=t0 \\/ t <> t0) by tauto.\n   destruct H0.\n   subst .\n   rewrite tidspec.eq_beq_true in H; auto.\n   inverts H.\n   auto.\n   rewrite tidspec.neq_beq_false in H; eauto.\n Qed.\n\nLemma cstep_nhapi_hold:\n  forall pc C m C' m' t T,\n    nhapi T pc->\n    cstep pc C m C' m' ->\n    TasksMod.get T t = Some C ->\n    nhapi (TasksMod.set T t C') pc.\nProof.\n  introv Hcs Hget Hn.\n  apply Hcs in  Hn.\n  lets Hres : cstep_good_clt_hold Hget; eauto.\n  eapply nhapi_set_hold; eauto.\nQed.\n\n\nLtac destruct_inverts1 H:=\n  let Hx:= fresh in\n  match type of H with\n    | ?H1 \\/ ?H2 => destruct H as [Hx | H]; [inverts Hx | destruct_inverts1 H]\n    | exists _, _ = _ => let x:= fresh in (destruct H as (x&H);inverts H)\n    | _ => idtac\n  end.\n\nLemma callcont_goodks:\n  forall ks f s le ks',\n    callcont ks = Some (kcall f s le ks') ->\n    goodks_h ks ->\n    goodks_h ks'.\nProof.\n  induction ks;intros;simpl in *;auto;tryfalse;mytac.\n  apply IHks in H;auto.\n  inverts H;auto.\n  apply IHks in H;auto.\n  apply IHks in H;auto.\n  apply IHks in H;auto.\n  apply IHks in H;auto.\n  apply IHks in H;auto.\n  apply IHks in H;auto.\n  apply IHks in H;auto.\nQed.\n\nOpen Scope nat_scope.\nLemma hapistep_goodcode:\n  forall C O c O',\n    goodcode_h C->\n    goodcode_h C -> \n    goodcode_h C ->\n    goodcode_h C ->\n    goodcode_h C ->\n    goodcode_h C ->\n    goodcode_h C -> \n    hapistep os_spec' C O c O' ->\n    goodcode_h c.\nProof.\n  intros.\n  clear H2 H0.\n  \n  inverts H6.\n  unfolds in H0.\n  inverts H0.\n  unfolds in H9.\n  simpl in H9.\n  remember (Zeq_bool OSMutexAccept f) as X.\n  destruct X.\n  inverts H9.\n  simpl in H1.\n  simpl.\n  mytac;auto.\n  unfolds.\n  left.\n  exists vl.\n  unfolds.\n  left;auto.\n  remember (Zeq_bool OSMutexCreate f) as X0.\n  destruct X0.\n  inverts H9.\n  simpl in H1.\n  simpl.\n  mytac;auto.\n  unfolds.\n  right;left.\n  exists vl.\n  unfolds.\n  left;auto.\n  remember (Zeq_bool OSMutexDel f) as X1.\n  destruct X1.\n  inverts H9.\n  simpl in H1.\n  simpl.\n  mytac;auto.\n  unfolds.\n  right;right;left.\n  exists vl.\n  unfolds.\n  left;auto.\n  remember (Zeq_bool OSMutexPend f) as X1.\n  destruct X1.\n  inverts H9.\n  simpl in H1.\n  simpl.\n  mytac;auto.\n  unfolds.\n  right;right;right;left.\n  exists vl.\n  unfolds.\n  unfold mutexpend.\n  left;auto.\n\n  remember (Zeq_bool OSMutexPost f) as X1.\n  destruct X1.\n  inverts H9.\n  simpl in H1.\n  simpl.\n  mytac;auto.\n  unfolds.\n  right;right;right;right;left.\n  exists vl.\n  unfolds.\n  unfold mutexpost.\n  left;auto.\n  \n  tryfalse.\n\n  (*----------------*)\n  simpl in H1.\n  simpl;mytac;auto.\n  unfolds in H1.\n\n  (* acc *)\n  destruct H1.\n  unfold GoodAcc in H1.\n  mytac.\n  destruct_inverts1 H1.\n  inverts H0;tryfalse.\n  unfolds.\n  left.\n  eexists;unfolds.\n  right;left;auto.\n  unfolds.\n  left.\n  eexists;unfolds.\n  right;right;left;auto.\n  inverts H0.\n  unfolds.\n  left.\n  eexists;unfolds.\n  right;right;right.\n  branch 7%nat.\n  eexists;eauto.\n  inverts H0.\n  unfolds.\n  left.\n  eexists;unfolds.\n  branch 4;eauto.\n  unfolds.\n  left.\n  eexists;unfolds.\n  branch 5;eauto.\n  inverts H0.\n  unfolds.\n  left.\n  eexists;unfolds.\n  right;right;right;branch 7.\n  eexists;eauto.\n  inverts H0.\n  unfolds.\n  left.\n  eexists;unfolds.\n  branch 6;eauto.\n  unfolds.\n  left.\n  eexists;unfolds.\n  branch 7;eauto.\n  inverts H0.\n  left.\n  eexists;unfolds.\n  right;right;right;branch 7.\n  eexists;eauto.\n  inverts H0.\n  unfolds.\n  left.\n  eexists;unfolds.\n  branch 8;eauto.\n  unfolds.\n  left.\n  eexists;unfolds.\n  right;branch 8;eauto.\n  inverts H0.\n  unfolds.\n  left.\n  eexists;unfolds.\n  right;right;right;branch 7.\n  eexists;eauto.\n  inverts H0.\n  unfolds.\n  left.\n  eexists;unfolds.\n  right;right;right;branch 7.\n  eexists;eauto.\n  inverts H0.\n  (* cre *)\n  destruct H1.\n  unfold GoodCre in H1.\n  mytac.\n  destruct_inverts1 H1.\n  inverts H0;tryfalse.\n  unfolds.\n  right;left.\n  eexists;unfolds.\n  right;left;eauto.\n  unfolds.\n  right;left.\n  eexists;unfolds.\n  right;right;left;eauto.\n\n  inverts H0;tryfalse.\n  unfolds.\n  right;left.\n  eexists;unfolds.\n  branch 4;eauto.\n\n  inverts H0;tryfalse.\n  unfolds.\n  right;left.\n  eexists;unfolds.\n  branch 4;eauto.\n\n  inverts H0.\n\n  (*del*)\n  destruct H1.\n  unfold GoodDel in H1.\n  mytac.\n\n  destruct_inverts1 H1.\n  inverts H0;tryfalse.\n  unfolds.\n  branch 3.\n  eexists;unfolds.\n  branch 2;auto.\n  unfolds;branch 3.\n  eexists;unfolds.\n  branch 3;eauto.\n\n  inverts H0.\n  unfolds.\n  branch 3.\n  eexists;unfolds.\n  right;right;right;right;branch 8.\n  eexists;eauto.\n  inverts H0.\n  unfolds.\n  branch 3.\n  eexists;unfolds.\n  branch 4;auto.\n  unfolds.\n  branch 3.\n  eexists;unfolds.\n  branch 5;auto.\n\n  inverts H0.\n  unfolds;branch 3.\n  eexists;unfolds.\n  right;right;right;right;branch 8.\n  eauto.\n\n  inverts H0.\n  unfolds;branch 3.\n  eexists;unfolds.\n  branch 6;auto.\n  unfolds;branch 3.\n  eexists;unfolds.\n  branch 7;auto.\n\n  inverts H0.\n  unfolds;branch 3.\n  eexists;unfolds.\n  right;right;right;right;branch 8.\n  eexists;eauto.\n\n  inverts H0.\n  unfolds;branch 3.\n  eexists;unfolds.\n  branch 8;auto.\n  unfolds;branch 3.\n  eexists;unfolds.\n  right;branch 8;auto.\n\n  inverts H0.\n  unfolds;branch 3.\n  eexists;unfolds.\n  right;right;right;right;branch 8.\n  eexists;eauto.\n\n  inverts H0.\n  unfolds;branch 3.\n  eexists;unfolds.\n  right;right;branch 8.\n  eauto.\n\n  unfolds;branch 3.\n  eexists;unfolds.\n  branch 8.\n  branch 4;eauto.\n\n  inverts H0.\n  unfolds;branch 3.\n  eexists;unfolds.\n  right;right;right;right;branch 8.\n  eexists;eauto.\n\n  inverts H0.\n  unfolds;branch 3.\n  eexists;unfolds.\n  right;right;right;right;branch 8.\n  eexists;eauto.\n  inverts H0.\n  \n  (*pend*)\n  destruct H1.\n  unfold GoodPend in H1.\n  mytac.\n\n  destruct_inverts1 H1.\n  \n  inverts H0;tryfalse.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 2;auto.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 3;simpl;eauto.\n\n  inverts H0;tryfalse.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8;branch 8;branch 8;branch 8;branch 5.\n  eauto.\n\n  inverts H0;tryfalse.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 4;auto.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 5;auto.\n  \n  inverts H0;tryfalse.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8;branch 8;branch 8;branch 8;branch 5.\n  eauto.\n\n  inverts H0;tryfalse.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 6;auto.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 7;eauto.\n\n  inverts H0.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8;branch 8;branch 8;branch 8;branch 5;eauto.\n\n  inverts H0.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;auto.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8.\n  branch 2;auto.\n\n  inverts H0.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8;branch 8;branch 8;branch 8;branch 5.\n  eauto.\n\n  inverts H0.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8.\n  branch 3;auto.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8.\n  branch 4;auto.\n  inverts H0.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8;branch 8;branch 8;branch 8;branch 5;eauto.\n\n  inverts H0.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8.\n  branch 5;auto.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8.\n  branch 6;auto.\n\n  inverts H0.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8;branch 8;branch 8;branch 8;branch 5;eauto.\n\n  inverts H0.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8.\n  branch 7;auto.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8.\n  branch 8;auto.\n\n  inverts H0.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8;branch 8;branch 8;branch 8;branch 5;eauto.\n\n  inverts H0.\n  unfolds.\n  branch 4.\n  eexists;unfolds.\n  branch 8.\n  branch 8.\n  right.\n  left.\n  eauto.\n\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8.\n  branch 8.\n  branch 3;eauto.\n  \n  inverts H0.\n  inverts H12.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 8.\n  branch 7;auto.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 8;branch 8;auto.\n\n  inverts H0.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 4;eauto.\n\n  \n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 5;eauto.\n\n  inverts H0.\n  unfolds;branch 4.\n  eexists;unfolds;branch 8;branch 8;branch 8;branch 8;branch 8;branch 5.\n  eauto.\n  \n  inverts H0.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 6;auto.\n\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 7;auto.\n\n  inverts H0.\n  unfolds;branch 4.\n  eexists;unfolds;branch 8;branch 8;branch 8;branch 8;branch 8;branch 5.\n  eauto.\n\n  inverts H0.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 8;auto.\n\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 8;eauto.\n\n  inverts H0.\n  unfolds;branch 4.\n  eexists;unfolds;branch 8;branch 8;branch 8;branch 8;branch 8;branch 5.\n  eauto.\n\n  inverts H0.\n  unfolds;branch 4.\n  eexists;unfolds;branch 8;branch 8;branch 8;branch 3.\n  eauto.\n  \n  unfolds;branch 4.\n  eexists;unfolds;branch 8;branch 8;branch 8.\n  branch 4.\n  eauto.\n\n  inverts H0.\n  unfolds;branch 4.\n  eexists;unfolds;branch 8;branch 8;branch 8;branch 8;branch 8;branch 5.\n  eauto.\n  \n  inverts H0.\n  unfolds;branch 4.\n  eexists;unfolds;branch 8;branch 8;branch 8.\n  branch 5.\n  eauto.\n\n  unfolds;branch 4.\n  eexists;unfolds;branch 8;branch 8;branch 8.\n  branch 6.\n  eauto.\n\n  inverts H0.\n  unfolds;branch 4.\n  eexists;unfolds;branch 8;branch 8;branch 8;branch 8;branch 8;branch 5.\n  eauto.\n\n  inverts H0.\n  unfolds;branch 4.\n  eexists;unfolds;branch 8;branch 8;branch 8;branch 8;branch 8;branch 5.\n  eauto.\n\n  inverts H0.\n  inverts H12.\n  unfolds in H7.\n  mytac.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 8.\n  branch 8.\n  branch 2.\n  auto.\n\n  inverts H0.\n  inverts H12.\n  unfolds in H7.\n  mytac.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 8; branch 8.\n  branch 2.\n  auto.\n\n  inverts H0.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 8; branch 8.\n  branch 3.\n  auto.\n\n  inverts H12.\n\n  inverts H0.\n  inverts H12.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 8;branch 8.\n  branch 4;auto.\n\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 8;branch 8.\n  branch 7;auto.\n\n  inverts H0.\n  inverts H12.\n  inverts H11.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 8.\n  branch 8.\n  branch 5;auto.\n\n  inverts H0.\n  inverts H12.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 8.\n  branch 8.\n  branch 6;auto.\n\n  inverts H11.\n\n  inverts H0.\n  inverts H12.\n\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8;branch 8.\n  branch 8;branch 8;eauto.\n\n  inverts H0.\n  inverts H12.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8;branch 8.\n  branch 8;branch 8;eauto.\n\n  inverts H0.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8;branch 8.\n  branch 8;branch 8;eauto.\n\n  inverts H12.\n\n  inverts H0.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8;branch 8.\n  branch 8;branch 8;eauto.\n\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8;branch 8.\n  branch 8;branch 8;eauto.\n  \n  inverts H0.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8;branch 8.\n  branch 8;branch 8;branch 5;eauto.\n\n  inverts H0.\n  unfolds;branch 4.\n  eexists;unfolds.\n  branch 8;branch 8;branch 8.\n  branch 8;branch 8;branch 5;eauto.\n\n  inverts H0.\n  \n  (* post *)\n  destruct H1.\n  unfold GoodPost in H1.\n  mytac.\n  destruct_inverts1 H1.\n  \n  inverts H0;tryfalse.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 2;auto.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 3;simpl;eauto.\n\n  inverts H0.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8.\n  branch 8.\n  branch 8.\n  branch 8.\n  eauto.\n\n  inverts H0.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 4;auto.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 5;simpl;eauto.\n\n  inverts H0.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;branch 8;branch 8;branch 8;eauto.\n\n  inverts H0.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 6;auto.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 7;simpl;eauto.\n\n  inverts H0.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;branch 8;branch 8;branch 8;eauto.\n\n  inverts H0.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;auto.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8.\n  branch 2;simpl;eauto.\n\n  inverts H0.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;branch 8;branch 8;branch 8;eauto.\n\n  inverts H0.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;auto.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8.\n  branch 4;simpl;eauto.\n\n  inverts H0.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;branch 8;branch 8;branch 8;eauto.\n\n  inverts H0.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;branch 5.\n  eauto.\n  \n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;branch 6.\n  eauto.\n\n  inverts H0.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;branch 8;branch 8;branch 8;eauto.\n\n  inverts H0.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;branch 7.\n  auto.\n\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;branch 8.\n  left.\n  auto.\n\n  inverts H0.\n  inverts H12.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 2;auto.\n\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 3;auto.\n\n  inverts H0.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 8.\n  branch 4.\n  auto.\n\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 8.\n  branch 5.\n  auto.\n\n  inverts H0.\n  inverts H12.\n  unfolds;branch 5.\n  inverts H7.\n  mytac.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 4;auto.\n\n  inverts H0.\n  inverts H12.\n  inverts H7.\n  mytac.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 4;auto.\n\n  inverts H0.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 5;auto.\n\n  inverts H12.\n  \n  inverts H0.\n  inverts H12.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 6;auto.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 8.\n  branch 2;auto.\n  \n  inverts H0.\n  inverts H12.\n  inverts H11.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 7;auto.\n\n  inverts H0.\n  inverts H12.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 8;auto.\n  \n  inverts H11.\n  inverts H0.\n  inverts H12.\n  unfolds;branch 5.\n  eexists;unfolds.\n  \n  branch 8;branch 8;branch 8.\n  branch 3;auto.\n  inverts H0.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;branch 8.\n  branch 8.\n  branch 3.\n  inverts H12.\n  auto.\n\n  inverts H0.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;branch 8;branch 8.\n  branch 8;eauto.\n\n  inverts H12.\n  \n  inverts H0.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;branch 8;branch 8.\n  branch 8.\n  eauto.\n  \n  inverts H0.\n  unfolds.\n  branch 5.\n  eexists.\n  unfolds.\n  branch 8;branch 8;branch 8.\n  branch 6;eauto.\n\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;branch 8;branch 8.\n  branch 7.\n  eauto.\n\n  inverts H0.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;branch 8;branch 8.\n  branch 8.\n  eauto.\n  inverts H0.\n  unfolds;branch 5.\n  eexists;unfolds.\n  branch 8;branch 8;branch 8.\n  branch 8.\n  eauto.\n\n  inverts H0.\n  (*timetick*)\n  destruct H1.\n  unfold GoodTick in H1.\n  mytac.\n  destruct_inverts1 H1;clear H H3 H4 H5.\n\n  inverts H0.\n  inverts H8.\n  inverts H3;mytac.\n  unfolds;branch 6.\n  unfolds.\n  branch 2;auto.\n\n  inverts H0.\n  unfolds;branch 6.\n  unfolds.\n  branch 3;auto.\n  inverts H8.\n\n  inverts H0.\n  unfolds;branch 6.\n  unfolds.\n  branch 4;auto.\n  unfolds;branch 6.\n  unfolds.\n  branch 8.\n  branch 3;eauto.\n  \n  inverts H0.\n  inverts H8.\n  unfolds.\n  branch 6.\n  unfolds.\n  branch 5;auto.\n\n  unfolds.\n  branch 6.\n  unfolds.\n  branch 8;auto.\n  \n  inverts H0.\n  inverts H8.\n  inverts H7.\n  unfolds;branch 6.\n  unfolds.\n  branch 6;auto.\n\n  inverts H0.\n  inverts H8.\n  unfolds;branch 6.\n  unfolds.\n  branch 7;auto.\n\n  inverts H7.\n  inverts H0.\n  inverts H8.\n  unfolds;branch 6.\n  unfolds.\n  branch 8.\n  branch 2;auto.\n  inverts H0.\n  unfolds;branch 6.\n  unfolds.\n  branch 8.\n  inverts H8.\n  branch 2;eauto.\n\n  inverts H0.\n  unfolds;branch 6.\n  unfolds.\n  branch 8.\n  branch 3;eauto.\n  inverts H8.\n  inverts H0.\n\n  (*toy*)\n  unfold GoodToy in H1.\n  mytac.\n  destruct_inverts1 H1;clear H H3 H4 H5.\n\n  inverts H0.\n  inverts H8.\n  inverts H3;mytac.\n  unfolds;branch 7.\n  unfolds.\n  branch 2;auto.\n\n  inverts H0.\n  unfolds;branch 7.\n  unfolds.\n  branch 3;auto.\n  inverts H8.\n\n  inverts H0.\n  unfolds;branch 7.\n  unfolds.\n  branch 4;auto.\n  unfolds;branch 7.\n  unfolds.\n  branch 8.\n  branch 3;eauto.\n  \n  inverts H0.\n  inverts H8.\n  unfolds.\n  branch 7.\n  unfolds.\n  branch 5;auto.\n\n  unfolds.\n  branch 7.\n  unfolds.\n  branch 8;auto.\n  \n  inverts H0.\n  inverts H8.\n  inverts H7.\n  unfolds;branch 7.\n  unfolds.\n  branch 6;auto.\n\n  inverts H0.\n  inverts H8.\n  unfolds;branch 7.\n  unfolds.\n  branch 7;auto.\n\n  inverts H7.\n  inverts H0.\n  inverts H8.\n  unfolds;branch 7.\n  unfolds.\n  branch 8.\n  branch 2;auto.\n  inverts H0.\n  inverts H8.\n  unfolds;branch 7.\n  unfolds.\n  branch 8.\n  branch 2;eauto.\n\n  inverts H0.\n  unfolds;branch 7.\n  unfolds.\n  branch 8.\n  branch 3;eauto.\n  inverts H8.\n  inverts H0.\n \n\n  simpl in H.\n  simpl;mytac;auto.\n  simpl.\n  simpl in H5.\n  mytac;auto.\n  Grab Existential Variables.\n  trivial. trivial. trivial. trivial. trivial.\n  trivial. trivial. trivial. \n  trivial.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\n  exact nil.\nQed.\n\nLemma htstep_goodcode_h:\n  forall pc t C cst O c cst' O',\n    good_client_code pc ->\n    htstep (pc, os_spec') t C cst O c cst' O' ->\n    goodcode_h C ->\n    goodcode_h c.\nProof.\n  intros.\n  inverts H0.\n\n  inverts H2.\n\n  inverts H3.\n  inverts H2;simpl in H1;simpl;mytac;auto;tryfalse.\n  \n  inverts H2;simpl in H1;simpl;mytac;auto;tryfalse.\n  apply H in H4.\n  clear -H4.\n  induction s;simpl in H4;simpl;auto;tryfalse.\n  mytac.\n  eapply IHs1;eauto.\n  eapply IHs2;eauto.\n  mytac.\n  eapply IHs1;eauto.\n  eapply IHs2;eauto.\n\n  eapply callcont_goodks;eauto.\n\n  inverts H2.\n\n  eapply hapistep_goodcode;eauto.\nQed.\n\n\nLemma hpstep_goodcode_h:\n  forall pc T cst O T' cst' O',\n    goodtasks_h T ->\n    good_client_code pc ->\n    hpstep (pc,os_spec') T cst O T' cst' O' ->\n    goodtasks_h T'.\nProof.\n  intros.\n  inverts H1.\n  unfolds;intros.\n  assert ( t <> t0 \\/ t = t0) by tauto.\n  destruct H5.\n  rewrite TasksMod.set_a_get_a' in H1;[ | apply tidspec.neq_beq_false;auto].\n  apply H in H1;auto.\n\n  rewrite TasksMod.set_a_get_a in H1;[ | apply tidspec.eq_beq_true;auto]. \n  inverts H1.\n  subst t0.\n  apply H in H4.\n  eapply htstep_goodcode_h;eauto.\n\n  inverts H6.\n  unfolds;intros.\n  assert ( t <> t0 \\/ t = t0) by tauto.\n  destruct H6.\n  rewrite TasksMod.set_a_get_a' in H5;[ | apply tidspec.neq_beq_false;auto].\n  apply H in H5;auto.\n\n  rewrite TasksMod.set_a_get_a in H5;[ | apply tidspec.eq_beq_true;auto]. \n  inverts H5.\n  subst t0.\n  apply H in H4.\n  simpl in H4.\n  simpl.\n  mytac;auto.\n  unfolds in H1.\n  simpl in H1.\n  destruct i.\n  inverts H1.\n  unfolds.\n  branch 6.\n  unfold timetick.\n  unfold GoodTick.\n  left;auto.\n  destruct i.\n  inverts H1.\n  unfolds.\n  branch 7.\n  unfold toyint.\n  unfold GoodToy.\n  left;auto.\n  inverts H1.\n\n  unfolds.\n  intros.\n  assert (t <> t0 \\/ t = t0) by tauto.\n  destruct H6.\n  rewrite TasksMod.set_a_get_a' in H1;[ | apply tidspec.neq_beq_false;auto].\n  apply H in H1;auto.\n  rewrite TasksMod.set_a_get_a in H1;[ | apply tidspec.eq_beq_true;auto]. \n  inverts H1.\n  subst t0.\n  apply H in H5.\n  unfold goodcode_h in *.\n  mytac;auto.\n  unfold goodeval_h in *.\n  unfold goodstmt_h in *.\n  unfold good_api_stmt in *.\n  destruct H1.\n  mytac.\n  unfolds in H1.\n  destruct H1;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n\n  destruct H1.\n  unfold GoodCre in H1;mytac.\n  destruct H1;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n\n  destruct H1.\n  unfold GoodDel in H1;mytac.\n  destruct H1;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  \n  destruct H1.\n  unfold GoodPend in H1;mytac.\n  destruct H1;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  branch 4.\n  exists x.\n  unfolds.\n  branch 8.\n  branch 8.\n  branch 8.\n  branch 8.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  \n  destruct H2;inverts H1.\n  inverts H2.\n  \n  destruct H2;inverts H1.\n  inverts H2.\n\n  branch 8.\n  eauto.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2.\n  inverts H1.\n  mytac.\n  inverts H1.\n\n  destruct H1.\n  Focus 1.\n  unfold GoodPost in H1;mytac.\n  destruct H1;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  branch 5.\n  exists x.\n  unfolds.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  eexists;eauto.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2.\n  inverts H1.\n  destruct H1.\n  inverts H1.\n  destruct H1;inverts H1.\n  \n  destruct H1.\n  unfold GoodTick in H1.\n  mytac.\n  destruct H1;inverts H1.\n  inverts H2.\n  \n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  branch 6.\n  unfolds.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  eexists;auto.\n  inverts H2.\n  inverts H2.\n  inverts H1.\n  destruct H1;inverts H1.\n\n  unfold GoodToy in H1.\n  mytac.\n  destruct H1;inverts H1.\n  inverts H2.\n  \n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  inverts H2.\n  destruct H2;inverts H1.\n  branch 6.\n  unfolds.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  eexists;auto.\n  inverts H2.\n  inverts H2.\n  inverts H1.\n  destruct H1;inverts H1.\n  (*\n  unfolds.\n  intros.\n  assert (t0 = t' \\/ t0 <> t') by tauto.\n  destruct H2.\n  subst.\n  rewrite TasksMod.map_get_set in H1.\n  inverts H1.\n  simpl.\n  split;auto.\n  unfolds in H0.\n  apply H0 in H9.\n  clear -H9.\n  inductions s;simpl in *;mytac;auto;tryfalse.\n  \n  SearchAbout (_<>_ -> TasksMod.get _ _ = _ ).\n  rewrite tasks_set_get_neq in H1.\n  assert (t0 = t \\/ t0 <> t) by tauto.\n  destruct H3.\n  subst.\n  rewrite TasksMod.map_get_set in H1.\n  inverts H1.\n  simpl.*)\n  unfolds in H.\n  apply H in H4.\n  simpl in H4.\n  destruct H4.\n  unfolds in H1.\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  unfolds in H.\n  apply H in H4.\n  simpl in H4.\n  destruct H4.\n  unfolds in H1.\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  unfolds in H.\n  apply H in H2.\n  simpl in H2.\n  destruct H2.\n  unfolds in H1.\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\nQed.\n\nLemma hpstepstar_goodcode_h:\n  forall pc T cst O T' cst' O',\n    hpstepstar (pc,os_spec') T cst O T' cst' O' ->\n    goodtasks_h T ->\n    good_client_code pc ->\n    goodtasks_h T'.\nProof.\n  intros.\n  inductions H;auto.\n  eapply IHhpstepstar;eauto.\n  eapply hpstep_goodcode_h;eauto.\nQed.\n\nLemma hpstep_goodcode_goodapi:\n  forall pc T cst O T' cst' O',\n    goodtasks_h T ->\n    good_client_code pc ->\n    hpstep (pc,os_spec') T cst O T' cst' O' ->\n    O = O' \\/ GOOD_API_CODE O T.\nProof.\n  intros.\n  inverts H1.\n  inverts H3;try solve [left;auto].\n\n  (*api step*)\n\n  inverts H1.\n  lets Hx: H H4.\n  inverts H5;try solve [left;auto].\n  simpl in Hx.\n  mytac.\n  unfolds in H3.\n  destruct H3.\n\n  (*acc*)\n  unfold GoodAcc in H3;mytac.\n  destruct_inverts1 H3;inverts H1;try solve [left;auto].\n  inverts H8;mytac;subst.\n  left;eapply map_join_deter;eauto.\n  inverts H8;mytac;subst.\n  left;eapply map_join_deter;eauto.\n  inverts H8;mytac;subst.\n  left;eapply map_join_deter;eauto.\n  inverts H8;mytac;subst.\n  left;eapply map_join_deter;eauto.\n\n  right.\n  unfolds.\n  exists (curs (hapi_code (mutexacc_succ (|x|))), (ke, ks)) t.\n  mytac;auto.\n  left;do 3 eexists;eauto.\n\n  (*cre*)\n  destruct H3.\n  unfold GoodCre in H3;mytac.\n  destruct_inverts1 H3;inverts H1;try solve [left;auto].\n  inverts H8;mytac;subst.\n  left;eapply map_join_deter;eauto.\n\n  right.\n  unfolds.\n  exists (curs (hapi_code (mutexcre_succ (|x|))), (ke, ks)) t.\n  mytac;auto.\n  right;left;do 3 eexists;eauto.\n\n  (*del*)\n  destruct H3.\n  unfold GoodDel in H3;mytac.\n  destruct_inverts1 H3;inverts H1;try solve [left;auto].\n  inverts H8;mytac;subst.\n  left;eapply map_join_deter;eauto.\n  inverts H8;mytac;subst.\n  left;eapply map_join_deter;eauto.\n  inverts H8;mytac;subst.\n  left;eapply map_join_deter;eauto.\n  inverts H8;mytac;subst.\n  left;eapply map_join_deter;eauto.\n\n  right.\n  unfolds.\n  exists (curs (hapi_code (mutexdel_succ (|x|))), (ke, ks)) t.\n  mytac;auto.\n  right;right;left;do 3 eexists;eauto.\n  inverts H8;mytac;subst.\n  left;eapply map_join_deter;eauto.\n  (*pend*)\n  destruct H3.\n  unfold GoodPend in H3;mytac.\n  destruct_inverts1 H3;inverts H1;try solve [left;auto].\n  inverts H8;mytac;subst.\n  left;eapply map_join_deter;eauto.\n  inverts H8;mytac;subst.\n  left;eapply map_join_deter;eauto.\n  inverts H8;mytac;subst.\n  left;eapply map_join_deter;eauto.\n  inverts H8;mytac;subst.\n  left;eapply map_join_deter;eauto.\n  inverts H8;mytac;subst.\n  left;eapply map_join_deter;eauto.\n  inverts H8;mytac;subst.\n  left;eapply map_join_deter;eauto.\n  \n  right.\n  unfolds.\n  exists (curs (hapi_code (mutexpend_get_succ (|x|))), (ke, ks)) t.\n  mytac;auto.\n  right;right;right;left;do 3 eexists;eauto.\n\n  inverts H12.\n  left;auto.\n  left;auto.\n  inverts H8.\n  left;eapply map_join_deter;eauto.\n  \n  unfolds in H8.\n  mytac.\n  left;eapply map_join_deter;eauto.\n\n  inverts H8.\n  mytac.\n  left;eapply map_join_deter;eauto.\n\n  \n  inverts H8.\n  mytac.\n  left;eapply map_join_deter;eauto.\n  \n  inverts H8.\n  mytac.\n  left;eapply map_join_deter;eauto.\n  \n  inverts H8.\n  mytac.\n  left;eapply map_join_deter;eauto.\n  \n  right.\n  unfolds.\n  exists (curs\n            (hapi_code\n               (mutexpend_block_lift (|x|);;\n                isched;; (mutexpend_to (|x|) ?? mutexpend_block_get (|x|)))),\n         (ke, ks)) t.\n  mytac;auto.\n  right;right;right;right;right;left.\n  do 4 eexists;eauto.\n\n  right.\n  unfolds.\n  exists (curs\n            (hapi_code\n               (mutexpend_block_no_lift (|x|);;\n                isched;; (mutexpend_to (|x|) ?? mutexpend_block_get (|x|)))),\n         (ke, ks)) t.\n  mytac;auto.\n  right;right;right;right;left.\n  do 4 eexists;eauto.\n\n  inverts H12.\n\n  inverts H12.\n  left;auto.\n  left;auto.\n  inverts H12.\n  inverts H11.\n  left;auto.\n  inverts H12.\n  left;auto.\n  inverts H11.\n\n  right.\n  unfolds.\n  exists (curs\n            (hapi_code\n               (sched;; (mutexpend_to (|x|) ?? mutexpend_block_get (|x|)))),\n         (ke, ks)) t.\n  mytac;auto.\n  branch 8.\n  branch 5.\n  do 3 eexists;eauto.\n\n  inverts H12;left;auto.\n\n  inverts H12.\n  inverts H8.\n  mytac.\n  left;eapply map_join_deter;eauto.\n  inverts H8;mytac;left;eapply map_join_deter;eauto.\n\n  (*post*)\n  destruct H3.\n  unfold GoodPost in H3;mytac.\n  destruct_inverts1 H3;inverts H1;try solve [left;auto].\n  inverts H8;mytac;subst.\n  left;eapply map_join_deter;eauto.\n  inverts H8;mytac;subst.\n  left;eapply map_join_deter;eauto.\n  inverts H8;mytac;subst.\n  left;eapply map_join_deter;eauto.\n  inverts H8;mytac;subst.\n  left;eapply map_join_deter;eauto.\n\n  right.\n  unfolds.\n  exists  (curs\n            (hapi_code\n               (mutexpost_nowt_return_prio_succ (|x|))), (ke, ks)) t.\n  mytac;auto.\n  branch 7.\n  do 3 eexists;eauto.\n\n  right.\n  unfolds.\n  exists  (curs\n            (hapi_code\n               (mutexpost_nowt_no_return_prio_succ (|x|))), (ke, ks)) t.\n  mytac;auto.\n  branch 8.\n  left;do 3 eexists;eauto.\n\n  inverts H12;left;auto.\n  \n  right.\n  unfolds.\n  exists  (curs\n            (hapi_code\n               (mutexpost_exwt_return_prio_succ (|x|);;\n                isched;; END Some (V$NO_ERR))), (ke, ks)) t.\n  mytac;auto.\n  branch 8.\n  branch 2.\n  do 3 eexists;eauto.\n\n  right.\n  unfolds.\n  exists  (curs\n            (hapi_code\n               (mutexpost_exwt_no_return_prio_succ (|x|);;\n                isched;; END Some (V$NO_ERR))), (ke, ks)) t.\n  mytac;auto.\n  branch 8.\n  branch 3.\n  do 3 eexists;eauto.\n\n  inverts H12.\n  inverts H12;left;auto.\n  inverts H12.\n  inverts H11;left;auto.\n\n  inverts H12;left;auto.\n  inverts H11.\n\n  right.\n  unfolds.\n  exists  (curs (hapi_code (sched;; END Some (V$NO_ERR))), (ke, ks)) t.\n  mytac;auto.\n  branch 8.\n  branch 5.\n  do 3 eexists;eauto.\n\n  inverts H12;left;auto.\n  inverts H12.\n  inverts H8;mytac;left;eapply map_join_deter;eauto.\n  inverts H8;mytac;left;eapply map_join_deter;eauto.\n  inverts H8;mytac;left;eapply map_join_deter;eauto.\n  (*timetick*)\n  destruct H3.\n  unfold GoodTick in H3.\n  mytac.\n  destruct_inverts1 H3;inverts H1;try solve [left;auto].\n\n  right.\n  unfolds.\n  exists (curs\n            (hapi_code\n               (timetick_spec (|nil|);;\n                ( isched;; END None ?? END None\n                 ))), (ke, ks)) t.\n  mytac;auto.\n  branch 8.\n  branch 4.\n  do 3 eexists;eauto.\n  inverts H12.\n  inverts H12;left;auto.\n  inverts H12.\n  inverts H11;left;auto.\n  inverts H12;left;auto.\n  inverts H11.\n  inverts H12;left;auto.\n  inverts H12;left;auto.\n  inverts H12.\n \n  (*toy int*)\n  unfold GoodToy in H3.\n  mytac.\n  destruct_inverts1 H3;inverts H1;try solve [left;auto].\n\n  left.\n  inverts H12.\n  unfolds in H7.\n  mytac;eapply map_join_deter;eauto.\n \n  inverts H12.\n  inverts H12;left;auto.\n  inverts H12.\n  inverts H11;left;auto.\n  inverts H12;left;auto.\n  inverts H11.\n  inverts H12;left;auto.\n  inverts H12;left;auto.\n  inverts H12.\n\n\n  (*int step*)\n  inverts H6.\n  left;auto.\n  (*sched*)\n  right.\n  unfolds.\n  exists (curs (hapi_code (sched;; s)), (ke, ks)) t.\n  mytac;auto.\n  branch 8.\n  branch 5.\n  do 3 eexists;eauto.\n\n    unfolds in H.\n  apply H in H4.\n  simpl in H4.\n  destruct H4.\n  unfolds in H1.\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  unfolds in H.\n  apply H in H4.\n  simpl in H4.\n  destruct H4.\n  unfolds in H1.\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  unfolds in H.\n  apply H in H2.\n  simpl in H2.\n  destruct H2.\n  unfolds in H1.\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  destruct H1.\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\n  unfolds in H1.\n  repeat progress (destruct H1;tryfalse).\nQed.\n\nLemma init_goodks_h:\n  forall T client_code cst O,\n    InitTasks T client_code cst O ->\n    INV_PROP client_code O T cst ->\n    goodtasks_h T .\nProof.\n  intros.\n  unfolds in H.\n  unfolds.\n  intros.\n  mytac.\n  apply H2 in H1.\n  mytac.\n  unfolds in H0.\n  mytac.\n  unfolds in H0.\n  apply H0 in H3.\n  clear -H3.\n  unfolds.\n  unfolds in H3.\n  induction x;simpl in *;auto;tryfalse.\n  mytac.\n  apply IHx1;auto.\n  apply IHx2;auto.\n  mytac.\n  apply IHx1;auto.\n  apply IHx2;auto.\nQed.\n\nLemma code_exe_prop1:\n  forall client_code T cst O T' cst' O' T'' O'' cst'',\n    good_client_code client_code  ->\n    goodtasks_h T -> \n    hpstepstar (client_code, os_spec') T cst O T' cst' O' ->\n    hpstep (client_code, os_spec') T' cst' O' T'' cst'' O''->\n    O' = O'' \\/ GOOD_API_CODE O' T'.\nProof.\n  intros.\n  eapply hpstep_goodcode_goodapi;eauto.\n  eapply hpstepstar_goodcode_h;eauto.\nQed.\n\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 sub_joinsig_get:\n  forall tls_used tls t x tls_used',\n    TcbMod.sub tls_used tls -> TcbMod.joinsig t x tls_used' tls_used -> TcbMod.get tls t = Some x.\nProof.\n  intros.\n  pose proof H0 t.\n  rewrite TcbMod.get_sig_some in H1.\n  destruct (TcbMod.get tls_used' t); tryfalse.\n  destruct (TcbMod.get tls_used t) eqn : eq1; tryfalse.\n  substs.\n  unfolds in H.\n  unfold TcbMod.lookup in H.\n  apply H in eq1; auto.\nQed.\n\nLemma tickchange_goodst:\n  forall tls els tls' els' st' t0 p st msg0,\n    NO_NEST_PENDING tls els -> \n    TcbMod.get tls t0 = Some (p, st, msg0)->\n    (rdy_notin_wl tls els /\\\n\n     owner_prio_prop tls els /\\\n     task_stat_prop tls /\\\n     op_p_prop tls els /\\\n     wait_prop tls els /\\ no_owner_prio_prop tls els) ->\n    tickchange t0 st els st' els' ->\n    TcbMod.set tls t0 (p, st', msg0) = tls' ->\n    (rdy_notin_wl tls' els' /\\\n\n     owner_prio_prop tls' els' /\\\n     task_stat_prop tls' /\\\n     op_p_prop tls' els' /\\ wait_prop tls' els' /\\ no_owner_prio_prop tls' els'\n    ).\nProof.\n  intros.\n  inverts H2;auto;tryfalse.\n  (*================*)\n  rewrite TcbMod.get_set_same in H3;auto.\n  subst;auto.\n\n  (*=============*)\n  destructs H1.\n  unfold task_stat_prop in *.\n  apply H4 in H0.\n  destruct H0.\n  inverts H0.\n  do 2 destruct H0.\n  tryfalse.\n\n  (*==============*)\n  destructs H1.\n  unfold task_stat_prop in *.\n  apply H4 in H0.\n  destruct H0.\n  inverts H0.\n  do 2 destruct H0.\n  tryfalse.\n\n\n  (*=============*)\n  mytac.\n  unfold rdy_notin_wl in *.\n  mytac.\n  intros.\n  assert (t0 <> t).\n  intro.\n  subst t0.\n  rewrite TcbMod.set_a_get_a in H12;[ | apply tidspec.eq_beq_true;auto].\n  inverts H12.\n  rewrite TcbMod.set_a_get_a' in H12;[ | apply tidspec.neq_beq_false;auto].\n  apply H1 in H12;auto.\n\n  intros.\n  assert (t0 <> t \\/ t0 = t) by tauto.\n  destruct H13.\n  rewrite TcbMod.set_a_get_a' in H12;[ | apply tidspec.neq_beq_false;auto].\n  apply H3 in H12;auto.\n  subst t0.\n  rewrite TcbMod.set_a_get_a in H12;[ | apply tidspec.eq_beq_true;auto].\n  inverts H12.\n  apply H3 in H0.\n  auto.\n  \n  intros.\n  apply H11 in H12.\n  mytac.\n  assert (t0 <> t \\/ t0 = t) by tauto.\n  destruct H13.\n  rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n  do 3 eexists;eauto.\n\n  subst t0.\n  rewrite H12 in H0;inverts H0.\n  rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n  do 3 eexists;eauto.\n\n  (*---------------------*)\n  unfold owner_prio_prop in *.\n  intros.\n\n  assert (t0 <> t \\/ t0 = t) by tauto.\n  destruct H12.\n  eapply H2;eauto.\n  rewrite TcbMod.set_a_get_a' in H3;[ | apply tidspec.neq_beq_false;auto].\n  eauto.\n  subst t0.\n  eapply H2;eauto.\n  rewrite TcbMod.set_a_get_a in H3;[ | apply tidspec.eq_beq_true;auto].\n  inverts H3.\n  eauto.\n\n  (*-----------------------*)\n  unfold task_stat_prop in *.\n  intros.\n  assert (t0 <> t \\/ t0 = t) by tauto.\n  destruct H11.\n  eapply H4;eauto.\n  rewrite TcbMod.set_a_get_a' in H3;[ | apply tidspec.neq_beq_false;auto].\n  eauto.\n\n  subst t0.\n  rewrite TcbMod.set_a_get_a in H3;[ | apply tidspec.eq_beq_true;auto].\n  inverts H3.\n  right.\n  apply H4 in H0.\n  destruct H0;tryfalse.\n  mytac.\n  inverts H0.\n  do 2 eexists;eauto.\n\n  (*----------------------*)\n  unfold op_p_prop in *.\n  intros.\n  assert (t = t0 \\/ t <> t0) by tauto.\n  destruct H12.\n  subst t0.\n  rewrite TcbMod.set_a_get_a in H3;[ | apply tidspec.eq_beq_true;auto].\n  inverts H3.\n  eapply H7;eauto.\n  eapply GET_OP_st_irrel;eauto.\n  rewrite TcbMod.set_a_get_a' in H3;[ | apply tidspec.neq_beq_false;auto].\n  eapply H7;eauto.\n  eapply GET_OP_st_irrel with (t:=t0);eauto.\n  \n  (*--------------------*)\n  unfold wait_prop in *.\n  intros.\n  assert (t = t0 \\/ t <> t0) by tauto.\n  destruct H11.\n  subst t0.\n  rewrite TcbMod.set_a_get_a in H3;[ | apply tidspec.eq_beq_true;auto].\n  inverts H3.\n  lets Hx:H8 H0.\n  mytac.\n  assert (x<>t).\n  intro.\n  subst x.\n  rewrite H0 in H11.\n  inverts H11.\n  do 3 eexists;splits;eauto.\n  rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n  eauto.\n  intros.\n  eapply H13;eauto.\n  eapply GET_OP_st_irrel with (t:=t);eauto.\n\n  rewrite TcbMod.set_a_get_a' in H3;[ | apply tidspec.neq_beq_false;auto].\n  apply H8 in H3.\n  mytac.\n  assert (x0<>t0).\n  intro.\n  subst x0.\n  rewrite H0 in H12.\n  inverts H12.\n  do 3 eexists;splits;eauto.\n  rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n  eauto.\n  intros.\n  apply H14.\n  eapply GET_OP_st_irrel with (t:=t0);eauto.\n\n  (*--------------------*)\n  unfold no_owner_prio_prop in *.\n  intros.\n  assert (t0 = t \\/ t0 <> t) by tauto.\n  destruct H13.\n  subst t0.\n  rewrite TcbMod.set_a_get_a in H3;[ | apply tidspec.eq_beq_true;auto].\n  inverts H3.\n  eapply H9;eauto.\n  eapply GET_OP_st_irrel with (t:=t);eauto.\n\n  rewrite TcbMod.set_a_get_a' in H3;[ | apply tidspec.neq_beq_false;auto].\n  eapply H9;eauto.\n  eapply GET_OP_st_irrel with (t:=t0);eauto.\n\n  (*=======================*)\n  destructs H1.\n  unfolds in H5.\n  lets Hx:H5 H0.\n  destruct H4;subst.\n  destruct Hx;tryfalse.\n  do 2 destruct H3;tryfalse.\n  \n  destruct H4;subst.\n  destruct Hx;tryfalse.\n  do 2 destruct H3;tryfalse.\n\n  destruct H3;subst.\n  destruct Hx;tryfalse.\n  do 2 destruct H3;tryfalse.\n\n  clear Hx.\n\n  mytac.\n\n  (*---------------*)\n  unfold rdy_notin_wl in *.\n  mytac.\n  intros.\n  assert (t = t0 \\/ t <> t0) by tauto.\n  destruct H11.\n  subst t0.\n  rewrite TcbMod.set_a_get_a in H10;[ | apply tidspec.eq_beq_true;auto].\n  inverts H10.\n\n  eapply tickchange_not_waiting;eauto.\n  unfolds;splits;eauto.\n  rewrite TcbMod.set_a_get_a' in H10;[ | apply tidspec.neq_beq_false;auto].\n  apply H1 in H10.\n  intro.\n  destruct H10.\n  lets Hx:H3 H0.\n  unfolds in Hx.\n  mytac.\n  unfolddef.\n  unfold get in *.\n  simpl in *.\n  rewrite H7 in H10;inverts H10.\n  eapply post_iswait;eauto.\n\n  intros.\n  assert (t0 = t \\/ t0 <> t) by tauto.\n  destruct H11.\n  subst t0.\n  rewrite TcbMod.set_a_get_a in H10;[ | apply tidspec.eq_beq_true;auto].\n  inverts H10.\n  rewrite TcbMod.set_a_get_a' in H10;[ | apply tidspec.neq_beq_false;auto].\n  lets Hx:H3 H10.\n  assert (eid0 = eid \\/ eid0 <> eid) by tauto.\n  destruct H12.\n  subst eid0.\n  lets Hy:Hx.\n  unfolds in Hy.\n  mytac.\n  unfolddef.\n  unfold get in *.\n  simpl in *.\n  rewrite H12 in H7;inverts H7.\n  eapply post_iswait' in Hx;eauto.\n  unfolds in Hx.\n  unfolds.\n  mytac.\n  do 3 eexists;split;eauto.\n  rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n  eauto.\n\n  intros.\n  assert (t = t0 \\/ t <> t0) by tauto.\n  destruct H11.\n  subst t0.\n  apply H3 in H0.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H11.\n  subst eid0.\n  unfolds in H10.\n  mytac.\n  rewrite EcbMod.set_a_get_a in H10;[ | apply tidspec.eq_beq_true;auto].\n  inverts H10.\n\n  false;eapply remove_tid_in_false;eauto.\n  assert (IS_WAITING_E t eid0 els).\n  unfolds in H10.\n  unfolds.\n  mytac.\n  rewrite EcbMod.set_a_get_a' in H10;[ | apply tidspec.neq_beq_false;auto].\n  do 3 eexists;split;eauto.\n  apply H4 in H12.\n  apply H4 in H0.\n  mytac.\n  rewrite H0 in H12;inverts H12;tryfalse.\n  apply H3 in H0.\n  unfolds in H0.\n  mytac.\n  unfolddef.\n  unfold get in *.\n  simpl in *.\n  rewrite H7 in H0;inverts H0.\n  assert (IS_WAITING_E t eid0 els).\n  eapply post_iswait';eauto.\n  apply H4 in H0.\n  rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n  mytac;do 3 eexists;eauto.\n\n  (*----------------*)\n  unfold owner_prio_prop in *.\n  intros.\n  assert (t0 =t \\/ t0 <> t) by tauto.\n  destruct H10.\n  subst t0.\n  rewrite TcbMod.set_a_get_a in H3;[ | apply tidspec.eq_beq_true;auto].\n  inverts H3.\n  unfolds in H1;destructs H1.\n  lets Hx:H3 H0.\n  unfolds in Hx.\n  destruct Hx.\n  do 2 destruct H11.\n  destruct H11.\n  unfolddef.\n  unfold get in *.\n  simpl in *.\n  rewrite H7 in H11;inverts H11.\n  assert (eid0=eid \\/ eid0 <> eid) by tauto.\n  destruct H11.\n  subst eid0.\n  rewrite EcbMod.set_a_get_a in H4;[ | apply tidspec.eq_beq_true;auto].\n  inverts H4.\n  unfolds in H.\n  assert (TcbMod.get tls t <> None ).\n  intro.\n  rewrite H4 in H0;inverts H0.\n  apply H with (qid:=eid) in H4.\n  destruct H4.\n  destruct H4.\n  unfolds.\n  do 4 eexists;split;eauto.\n  unfolds.\n  do 3 eexists;eauto.\n  rewrite EcbMod.set_a_get_a' in H4;[ | apply tidspec.neq_beq_false;auto].\n  eapply H2;eauto.\n\n  rewrite TcbMod.set_a_get_a' in H3;[ | apply tidspec.neq_beq_false;auto].\n  unfolds in H1.\n  destructs H1.\n  lets Hx:H11 H0.\n  unfolds in Hx.\n  destruct Hx.\n  do 3 destruct H13.\n  unfolddef.\n  unfold get in *.\n  simpl in *.\n  rewrite H7 in H13;inverts H13.\n  assert (eid0 = eid \\/ eid0<>eid) by tauto.\n  destruct H13.\n  subst eid0.\n  rewrite EcbMod.set_a_get_a in H4;[ | apply tidspec.eq_beq_true;auto].\n  inverts H4.\n  eapply H2;eauto.\n  rewrite EcbMod.set_a_get_a' in H4;[ | apply tidspec.neq_beq_false;auto].\n  eapply H2;eauto.\n\n\n  (*------------------------*)\n  unfold task_stat_prop in *.\n  intros.\n  assert (t=t0\\/t<>t0) by tauto.\n  destruct H4.\n  subst t0.\n  rewrite TcbMod.set_a_get_a in H3;[ | apply tidspec.eq_beq_true;auto].\n  inverts H3;auto.\n  rewrite TcbMod.set_a_get_a' in H3;[ | apply tidspec.neq_beq_false;auto].\n  apply H5 in H3;auto.\n\n  (*-----------------------*)\n  unfold op_p_prop in *.\n  intros.\n  assert (t =t0 \\/ t <> t0) by tauto.\n  destruct H10.\n  subst t0.\n  rewrite TcbMod.set_a_get_a in H3;[ | apply tidspec.eq_beq_true;auto].\n  inverts H3.\n  eapply H6;eauto.\n  eapply GET_OP_remove_tid_irrel;eauto.\n  eapply GET_OP_st_irrel;eauto.\n\n  rewrite TcbMod.set_a_get_a' in H3;[ | apply tidspec.neq_beq_false;auto].  \n  eapply H6;eauto.\n  eapply GET_OP_remove_tid_irrel with (t:=t0);eauto.\n  eapply GET_OP_st_irrel with (t:=t0);eauto.\n\n  (*------------------------*)\n  unfold wait_prop in *.\n  intros.\n  assert (t = t0 \\/ t <> t0) by tauto.\n  destruct H4.\n  subst t0.\n  rewrite TcbMod.set_a_get_a in H3;[ | apply tidspec.eq_beq_true;auto].\n  inverts H3.\n  \n  rewrite TcbMod.set_a_get_a' in H3;[ | apply tidspec.neq_beq_false;auto].\n  lets Hx:H8 H3.\n  mytac.\n  assert (x<>t0).\n  intro.\n  subst.\n  rewrite H11 in H0;inverts H0.\n  exists x.\n  rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n  do 2 eexists;splits;eauto.\n  assert (eid0=eid \\/ eid0<>eid) by tauto.\n  destruct H15.\n  subst eid0.\n  unfolds;unfolds in H10.\n  mytac.\n  rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n  unfolddef.\n  unfold get in *.\n  simpl in *.\n  rewrite H10 in H7;inverts H7.\n  do 3 eexists;eauto.\n  unfolds in H10;unfolds;mytac.\n  rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n  do 3 eexists;eauto.\n  intros.\n  apply H13.\n  eapply GET_OP_remove_tid_irrel with (t:=t0);eauto.\n  eapply GET_OP_st_irrel with (t:=t0);eauto.\n\n  (*------------------------*)\n  unfold no_owner_prio_prop in *.\n  intros.\n  assert (t = t0 \\/ t <> t0) by tauto.\n  destruct H11.\n  subst t0.\n  rewrite TcbMod.set_a_get_a in H3;[ | apply tidspec.eq_beq_true;auto].\n  inverts H3.\n  eapply H9;eauto.\n  intro.\n  destruct H4.\n  mytac.\n  exists x.\n  eapply IS_OWNER_remove_tid_irrel';eauto.\n  eapply GET_OP_remove_tid_irrel;eauto.\n  eapply GET_OP_st_irrel;eauto.\n\n  rewrite TcbMod.set_a_get_a' in H3;[ | apply tidspec.neq_beq_false;auto].\n  eapply H9;eauto.\n  intro.\n  destruct H4.\n  mytac.\n  exists x.\n  eapply IS_OWNER_remove_tid_irrel';eauto.\n  eapply GET_OP_remove_tid_irrel with (t:=t0);eauto.\n  eapply GET_OP_st_irrel with (t:=t0);eauto.\n  Grab Existential Variables.\nQed.\n\n\nLemma tickstep_goodst:\n  forall tls els tls' els' tls_sub,\n    TcbMod.sub tls_sub tls ->\n    tickstep' tls els tls' els' tls_sub ->\n    NO_NEST_PENDING tls els ->\n    NO_NEST_PENDING tls' els' ->\n    (rdy_notin_wl tls els /\\\n     owner_prio_prop tls els /\\\n     task_stat_prop tls /\\\n     op_p_prop tls els /\\\n     wait_prop tls els /\\ no_owner_prio_prop tls els) ->\n    rdy_notin_wl tls' els' /\\\n    owner_prio_prop tls' els' /\\\n    task_stat_prop tls' /\\\n    op_p_prop tls' els' /\\\n    wait_prop tls' els' /\\\n    no_owner_prio_prop tls' els'.\nProof.\n  intros.\n  induction H0.\n  auto.\n  eapply IHtickstep';eauto.\n  eapply tcbjoinsig_set_sub_sub;eauto.\n  eapply tickchange_nonestpend;eauto.\n  eapply sub_joinsig_get;eauto.\n  eapply tickchange_goodst with (tls':=tls') (els':=els') in H3;eauto.\n  eapply sub_joinsig_get;eauto.\nQed.\n\nLemma code_exe_prop2:\n  forall client_code T' cst' O' T'' O'' cst'',\n    O' = O'' \\/ GOOD_API_CODE O' T' ->\n    NO_NEST_PENDING_O O' ->\n    GOOD_ST O' ->\n    hpstep (client_code, os_spec') T' cst' O' T'' cst'' O''->\n    NO_NEST_PENDING_O O'' ->\n    GOOD_ST O''.\nProof.\n  intros.\n  rename H3 into Hnnp'.\n  destruct H;subst;auto.\n  inverts H2.\n  inverts H4;auto;tryfalse.\n  inverts H6;subst;auto;tryfalse.\n\n  inverts H2.\n  inverts H4;auto.\n\n  unfolds in H.\n  mytac.\n  unfolddef.\n  unfold get in *.\n  simpl in *.\n  rewrite H in H3;inverts H3.\n  rewrite H5 in H4;inverts H4.\n  destruct H10.\n  mytac.\n\n  (*mutex acc*)\n  clear -H0 H1 H2 H8 H9 Hnnp'.\n  rename H2 into H5.\n  rename H9 into H12.\n  inverts H5.\n  mytac.\n  assert (get O' curtid = Some (oscurt x8)) as Hct.\n  eapply join_get_get_l;eauto.\n  assert (get O' absecblsid = Some (absecblist x0)) as Hels.\n  eapply join_get_get_l;eauto.\n  assert (get O' abstcblsid = Some (abstcblist x2)) as Htls.\n  eapply join_get_get_l;eauto.\n\n  assert (O''= set O'  absecblsid\n                   (absecblist (set x0 x (absmutexsem x3 (Some (x8, x5)), x4)))).\n  eapply join_get_set_eq;eauto.\n  clear H2 H5 H4.\n  remember O' as Ox.\n  clear HeqOx.\n  rename x8 into ct.\n  rename x0 into els.\n  rename x2 into tls.\n  subst O''.\n  \n  unfolds.\n  intros.\n  unfolds in Hnnp'.\n  lets Hnnp'':Hnnp' H H2.\n  clear Hnnp'.\n  rewrite OSAbstMod.map_get_set in H.\n  inverts H.\n  rewrite abst_set_get_neq in H2;auto.\n  unfold get in *;simpl in *.\n  rewrite H2 in Htls;inverts Htls.\n  unfolds in H1.\n  lets Hgoodst: H1 Hels H2.\n  assert (rdy_notin_wl tls (EcbMod.set els x (absmutexsem x3 (Some (ct, x5)), x4))) as Hrdynotintwl.\n  mytac.\n  unfolds.\n  unfolds in H.\n  mytac.\n  intros.\n  apply H in H15.\n  intro.\n  destruct H15.\n  unfold IS_WAITING in *.\n  mytac.\n  assert (x = x0 \\/ x <> x0) by tauto.\n  destruct H17.\n  subst x0.\n  rewrite EcbMod.set_a_get_a in H15.\n  2: apply tidspec.eq_beq_true;auto.\n  inverts H15.\n  do 4 eexists;splits;eauto.\n  rewrite EcbMod.set_a_get_a' in H15;[ | apply tidspec.neq_beq_false;auto].\n  do 4 eexists;splits;eauto.\n  \n  (*---------------*)\n  intros.\n  apply H13 in H15.\n  unfold IS_WAITING_E in *.\n  mytac.\n  assert (x = eid \\/ x <> eid) by tauto.\n  destruct H17.\n  subst x.\n  rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n  rewrite H15 in H9;inverts H9.\n  do 3 eexists;splits;eauto.\n  rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n  do 3 eexists;splits;eauto.\n  (*----------------*)\n  intros.\n  assert (IS_WAITING_E t eid els).\n  unfold IS_WAITING_E in *.\n  mytac.\n  assert (x = eid \\/ x <> eid) by tauto.\n  destruct H17.\n  subst x.\n  rewrite EcbMod.set_a_get_a in H15;[ | apply tidspec.eq_beq_true;auto].\n  inverts H15.\n  do 3 eexists;splits;eauto.\n  rewrite EcbMod.set_a_get_a' in H15;[ | apply tidspec.neq_beq_false;auto].\n  do 3 eexists;splits;eauto.\n  eapply H14 in H16;eauto.\n\n  mytac.\n\n    (* rdy_notin_wl *)\n    auto.\n    \n\n    (*owner_prio_prop*)\n    unfold owner_prio_prop in *.\n    intros.\n    assert (x = eid \\/ x <> eid) by tauto.\n    destruct H15.\n    subst x.\n    rewrite EcbMod.set_a_get_a in H14;[ | apply tidspec.eq_beq_true;auto].\n    inverts H14.\n    rewrite H13 in H6;inverts H6.\n    split;auto.\n    rewrite EcbMod.set_a_get_a' in H14;[ | apply tidspec.neq_beq_false;auto].\n    eapply H3;eauto.\n\n    (*task_stat_prop*)\n    auto.\n\n    (*op_p_prop*)\n    unfold op_p_prop in *.\n    intros.\n    eapply H5;eauto.\n    assert (t = ct \\/ t <> ct) by tauto.\n    destruct H15.\n    Focus 2.\n    eapply set_neq_getop_eq;eauto.\n    intro.\n    rewrite H13 in H16;tryfalse.\n    subst t.\n\n    rewrite H6 in H13;inverts H13.\n    lets Hnoowner: no_nest_pending_set_none H6 H9 Hnnp''.\n    lets Heq: no_nest_pending_set_prio_eq Hnnp'' H14 H6.\n    subst p.\n    unfolds.\n    intro.\n    right.\n    split;auto.\n    do 2 eexists;eauto.\n\n    unfold wait_prop in *.\n    intros.\n    assert (TcbMod.get tls t = Some (p, wait (os_stat_mutexsem eid) tm, m)) as Ht;auto.\n    apply H10 in H13.\n    mytac.\n    do 3 eexists;splits;eauto.\n    unfold IS_OWNER in *.\n    assert (x = eid \\/ x <> eid) by tauto.\n    destruct H17.\n    subst.\n    mytac.\n    rewrite H13 in H9;inverts H9.\n    mytac.\n    rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    do 3 eexists;eauto.\n    assert (t = ct \\/ t <> ct ) by tauto.\n    destruct H17.\n    subst t.\n    intros.\n    rewrite Ht in H6;inverts H6.\n    unfolds in Hnnp''.\n    eapply no_nest_pending_set_prio_eq;eauto.\n    \n    intros.\n    eapply H16.\n    eapply set_neq_getop_eq;eauto.\n    intro.\n    rewrite Ht in H19;tryfalse.\n\n    \n    unfold no_owner_prio_prop in *.\n    intros.\n    assert (t = ct \\/ t <> ct ) by tauto.\n    destruct H16.\n    subst t.\n    rewrite H6 in H13;inverts H13.\n    eapply no_nest_pending_set_prio_eq;eauto.\n    eapply H11;eauto.\n\n    \n    intro.\n    destruct H14.\n    mytac;eexists;eapply is_owner_set_other;eauto.\n    eapply set_neq_getop_eq;eauto.\n    intro.\n    rewrite H13 in H17;tryfalse.\n\n    (*mutex cre*)\n    destruct H3;mytac.\n    clear -H0 H1 H2 H8 H9 Hnnp'.\n    rename H2 into H5.\n    inverts H5.\n    mytac.\n    \n    assert (get O' absecblsid = Some (absecblist x0)) as Hels.\n    eapply join_get_get_l;eauto.\n    assert (get O' abstcblsid = Some (abstcblist x4)) as Htls.\n    eapply join_get_get_l;eauto.\n    assert (O''= set O' absecblsid (absecblist x2)).\n    eapply join_get_set_eq;eauto.\n    subst O''.\n    clear H3 H4.\n    remember O' as Ox.\n    clear HeqOx.\n    rename x4 into tls.\n    rename x0 into els.\n    unfold GOOD_ST in *.\n    intros.\n    unfolds in Hnnp'.\n    lets Hnnp'': Hnnp' H H2.\n    clear Hnnp'.\n    unfolds in H0.\n    lets Hnnp: H0 Hels Htls.\n    clear H0.\n    rewrite OSAbstMod.map_get_set in H.\n    inverts H.\n    rewrite abst_set_get_neq in H2;auto.\n    unfold get in *;simpl in *.\n    rewrite Htls in H2;inversion H2;subst tls0.\n    clear H2.\n    lets Hgoodst: H1 Hels Htls.\n    clear H1.\n\n    mytac.\n    (*ryd_notin_wl*)\n    unfold rdy_notin_wl in *.\n    mytac;intros.\n    apply H in H12.\n    intro.\n    destruct H12.\n    eapply iswaiting_cre_hold;eauto.\n    (*----------*)\n    apply H10 in H12.\n    unfolds.\n    unfolds in H12.\n    mytac.\n    do 3 eexists;split;eauto.\n    eapply ecb_joinsig_get_eq;eauto.\n    (*----------*)\n    apply H11.\n    unfold IS_WAITING_E in *.\n    mytac.\n    exists x0 x1 x2.\n    split;auto.\n    assert (eid = x3 \\/ eid <> x3) by tauto.\n    destruct H14.\n    subst x3.\n    unfolds in H7.\n    eapply EcbMod.join_sig_get in H7;eauto.\n    rewrite H12 in H7;inverts H7;simpl in H13;tryfalse.\n\n    eapply joinsig_neq_get;eauto.\n\n    (*owner_prio_prop*)\n    unfold owner_prio_prop in *.\n    intros.\n    eapply H0;eauto.\n\n\n    eapply ecb_joinsig_get_eq';eauto.\n    (*task_stat_prop*)\n    auto.\n\n    (*op_p_prop*)\n    unfold op_p_prop in *.\n    intros.\n    eapply H2 in H10;eauto.\n    eapply getop_cre_hold;eauto.\n    (*wait_prop*)\n    unfold wait_prop in *.\n    intros.\n    apply H3 in H10.\n    mytac.\n    do 3 eexists;splits;eauto.\n    unfold IS_OWNER in *.\n    mytac.\n    eapply ecb_joinsig_get_eq in H10;eauto.\n    intros.\n    apply H13.\n    eapply getop_cre_hold;eauto.\n\n    (*no_owner_prio_prop*)\n    unfold no_owner_prio_prop in *.\n    intros.\n    eapply H4;eauto.\n    intro.\n    destruct H11.\n    mytac.\n    exists x0.\n    unfold IS_OWNER in *.\n    mytac.\n    eapply ecb_joinsig_get_eq in H11;eauto.\n    eapply getop_cre_hold;eauto.\n    \n    (*mutex del*)\n    destruct H3;mytac.\n    clear -H0 H1 H2 H8 H9 Hnnp'.\n    rename H2 into H5.\n    inverts H5.\n    mytac.\n     \n    assert (get O' absecblsid = Some (absecblist x0)) as Hels.\n    eapply join_get_get_l;eauto.\n    assert (O''= set O' absecblsid (absecblist x2)).\n    eapply join_get_set_eq;eauto.\n    subst O''.\n    clear H2.\n    remember O' as Ox.\n    clear HeqOx.\n    rename x0 into els.\n    unfold GOOD_ST in *.\n    intros.\n    unfolds in Hnnp'.\n    lets Hnnp'': Hnnp' H H2.\n    clear Hnnp'.\n    unfolds in H0.\n    assert (OSAbstMod.get Ox abtcblsid = Some (abstcblist tls)) as Htls.\n    rewrite abst_set_get_neq in H2;auto.\n    lets Hnnp: H0 Hels Htls.\n    clear H0.\n    rewrite OSAbstMod.map_get_set in H.\n    inverts H.\n    rewrite abst_set_get_neq in H2;auto.\n    clear H2.\n    lets Hgoodst: H1 Hels Htls.\n    clear H1.\n\n    unfold get in *;simpl in *.\n    mytac.\n    (*ryd_notin_wl*)\n    unfold rdy_notin_wl in *.\n    mytac;intros.\n    apply H in H11.\n    intro.\n    destruct H11.\n    eapply iswaiting_del_hold;eauto.\n    (*----------*)\n    apply H7 in H11.\n    unfolds.\n    unfolds in H11.\n    mytac.\n    do 3 eexists;split;eauto.\n    assert (eid <> x).\n    intro.\n    subst x.\n    \n    rewrite H11 in H3;inverts H3.\n    simpl in H12;tryfalse.\n    eapply EcbMod.join_comm in H5.\n    lets Hx: EcbMod.join_sig_get H5;eauto.\n    eapply joinsig_neq_get;eauto.\n\n    (*----------*)\n    apply H10.\n    unfold IS_WAITING_E in *.\n    mytac.\n    exists x0 x1 x2.\n    split;auto.\n    eapply ecb_joinsig_get_eq;eauto.\n    unfolds.\n    eapply EcbMod.join_comm in H5;eauto.\n\n    (*owner_prio_prop*)\n    unfold owner_prio_prop in *.\n    intros.\n    eapply H0;eauto.\n    eapply ecb_joinsig_get_eq;eauto.\n    unfolds.\n    eapply EcbMod.join_comm in H5;eauto.\n    (*task_stat_prop*)\n    auto.\n\n    (*op_p_prop*)\n    unfold op_p_prop in *.\n    intros.\n    eapply H2 in H7;eauto.\n    eapply getop_del_hold;eauto.\n    (*wait_prop*)\n    unfold wait_prop in *.\n    intros.\n    apply H4 in H7.\n    mytac.\n    do 3 eexists;splits;eauto.\n    unfold IS_OWNER in *.\n    mytac.\n    eapply ecb_joinsig_get_eq' in H7;eauto.\n    unfolds.\n    eapply EcbMod.join_comm in H5;eauto.\n    intros.\n    apply H12.\n    eapply getop_del_hold;eauto.\n\n    (*no_owner_prio_prop*)\n    unfold no_owner_prio_prop in *.\n    intros.\n    eapply H6;eauto.\n    intro.\n    destruct H10.\n    mytac.\n    exists x0.\n    unfold IS_OWNER in *.\n    mytac.\n    eapply ecb_joinsig_get_eq' in H10;eauto.\n    unfolds.\n    eapply EcbMod.join_comm in H5;eauto.\n    eapply getop_del_hold;eauto.\n    (*mutex pend get succ*)  \n    destruct H3;mytac.\n    clear -H0 H1 H2 H8 H9 Hnnp'.\n    rename H2 into H5.\n    rename H8 into H12.\n    inverts H5.\n    mytac.\n\n    assert (get O' curtid = Some (oscurt x8)) as Hct.\n    eapply join_get_get_l;eauto.\n    assert (get O' absecblsid = Some (absecblist x2)) as Hels.\n    eapply join_get_get_l;eauto.\n    assert (get O' abtcblsid = Some (abstcblist x4)) as Htls.\n    eapply join_get_get_l;eauto.\n    \n    assert (O''= set O' absecblsid\n            (absecblist (set x2 x (absmutexsem x7 (Some (x8, x5)), nil)))).\n    eapply join_get_set_eq;eauto.\n    subst O''.\n    clear H2 H3 H4.\n    remember O' as Ox.\n    clear HeqOx.\n    rename x8 into ct.\n    rename x2 into els.\n    rename x4 into tls.\n\n    unfolds.\n    intros.\n    unfolds in Hnnp'.\n    lets Hnnp'':Hnnp' H H2.\n    clear Hnnp'.\n    rewrite OSAbstMod.map_get_set in H.\n    inverts H.\n    rewrite abst_set_get_neq in H2;auto.\n    unfold get in *;simpl in *.\n    rewrite H2 in Htls;inverts Htls.\n    unfolds in H1.\n    lets Hgoodst: H1 Hels H2.\n    assert (rdy_notin_wl tls (EcbMod.set els x (absmutexsem x7 (Some (ct, x5)), nil))) as Hrdynotintwl.\n    mytac.\n    unfolds.\n    unfolds in H.\n    mytac.\n    intros.\n    apply H in H15.\n    intro.\n    destruct H15.\n    unfold IS_WAITING in *.\n    mytac.\n    assert (x = x1 \\/ x <> x1) by tauto.\n    destruct H17.\n    subst x1.\n    rewrite EcbMod.set_a_get_a in H15.\n    2: apply tidspec.eq_beq_true;auto.\n    inverts H15.\n    do 4 eexists;splits;eauto.\n    rewrite EcbMod.set_a_get_a' in H15;[ | apply tidspec.neq_beq_false;auto].\n    do 4 eexists;splits;eauto.\n    \n    (*---------------*)\n    intros.\n    apply H13 in H15.\n    unfold IS_WAITING_E in *.\n    mytac.\n    assert (x = eid \\/ x <> eid) by tauto.\n    destruct H17.\n    subst x.\n    rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n    rewrite H15 in H5;inverts H5.\n    do 3 eexists;splits;eauto.\n    rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    do 3 eexists;splits;eauto.\n    (*----------------*)\n    intros.\n    assert (IS_WAITING_E t eid els).\n    unfold IS_WAITING_E in *.\n    mytac.\n    assert (x = eid \\/ x <> eid) by tauto.\n    destruct H17.\n    subst x.\n    rewrite EcbMod.set_a_get_a in H15;[ | apply tidspec.eq_beq_true;auto].\n    inverts H15.\n    do 3 eexists;splits;eauto.\n    rewrite EcbMod.set_a_get_a' in H15;[ | apply tidspec.neq_beq_false;auto].\n    do 3 eexists;splits;eauto.\n    eapply H14 in H16;eauto.\n    Focus 1.\n    -\n      mytac.\n      +\n        (* rdy_notin_wl *)\n        auto.\n      +\n        (*owner_prio_prop*)\n        unfold owner_prio_prop in *.\n        intros.\n        assert (x = eid \\/ x <> eid) by tauto.\n        destruct H15.\n        subst x.\n        rewrite EcbMod.set_a_get_a in H14;[ | apply tidspec.eq_beq_true;auto].\n        inverts H14.\n        rewrite H13 in H6;inverts H6.\n        split;auto.\n        rewrite EcbMod.set_a_get_a' in H14;[ | apply tidspec.neq_beq_false;auto].\n        eapply H3;eauto.\n      +\n        (*task_stat_prop*)\n        auto.\n      +\n        (*op_p_prop*)\n        unfold op_p_prop in *.\n        intros.\n        eapply H8;eauto.\n        assert (t = ct \\/ t <> ct) by tauto.\n        destruct H15.\n        Focus 2.\n        eapply set_neq_getop_eq;eauto.\n        intro.\n        rewrite H13 in H16;tryfalse.\n        subst t.\n\n        rewrite H6 in H13;inverts H13.\n        lets Hnoowner: no_nest_pending_set_none H6 H5 Hnnp''.\n        lets Heq: no_nest_pending_set_prio_eq Hnnp'' H14 H6.\n        subst p.\n        unfolds.\n        intro.\n        right.\n        split;auto.\n        do 2 eexists;eauto.\n      +\n        (*wait_prop*)\n        unfold wait_prop in *.\n        intros.\n        assert (TcbMod.get tls t = Some (p, wait (os_stat_mutexsem eid) tm, m)) as Ht;auto.\n        apply H10 in H13.\n        mytac.\n        do 3 eexists;splits;eauto.\n        unfold IS_OWNER in *.\n        assert (x = eid \\/ x <> eid) by tauto.\n        destruct H17.\n        subst.\n        mytac.\n        rewrite H13 in H5;inverts H5.\n        mytac.\n        rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        do 3 eexists;eauto.\n        assert (t = ct \\/ t <> ct ) by tauto.\n        destruct H17.\n        subst t.\n        intros.\n        rewrite Ht in H6;inverts H6.\n        intros.\n        eapply H16.\n        eapply set_neq_getop_eq;eauto.\n        intro.\n        rewrite Ht in H19;tryfalse.\n      +\n        (*no_owner_prio_prop*)      \n        unfold no_owner_prio_prop in *.\n        intros.\n        assert (t = ct \\/ t <> ct ) by tauto.\n        destruct H16.\n        subst t.\n        rewrite H6 in H13;inverts H13.\n        eapply no_nest_pending_set_prio_eq;eauto.\n        eapply H11;eauto.\n        intro.\n        destruct H14.\n        mytac;eexists;eapply is_owner_set_other;eauto.\n        eapply set_neq_getop_eq;eauto.\n        intro.\n        rewrite H13 in H17;tryfalse.\n        +\n   destruct H3;mytac.\n   destruct H3;mytac.\n   destruct H3;mytac.\n\n    clear -H0 H1 H2 H8 H9 Hnnp'.\n    rename H2 into H6.\n    rename H9 into H12.\n    inverts H6.\n    mytac.\n    assert (get O' curtid = Some (oscurt x9)) as Hct.\n    eapply join_get_get_l;eauto.\n    assert (get O' absecblsid = Some (absecblist x0)) as Hels.\n    eapply join_get_get_l;eauto.\n    assert (get O' abtcblsid = Some (abstcblist x2)) as Htls.\n    eapply join_get_get_l;eauto.\n    \n    assert (O''=(set (set O' abtcblsid (abstcblist (set x2 x9 (x6, x7, x8))))\n                     absecblsid (absecblist (set x0 x (absmutexsem x5 None, nil))))).\n\n    eapply join_get_set_eq_2;eauto.\n    clear H2 H3 H4.\n    subst O''.\n    remember O' as Ox.\n    clear HeqOx.\n    rename x9 into ct.\n    rename x0 into els.\n    rename x2 into tls.\n    unfold GOOD_ST in *.\n    intros.\n    unfolds in Hnnp'.\n    lets Hnnp'': Hnnp' H H2.\n    clear Hnnp'.\n    unfolds in H0.\n    lets Hnnp: H0 Hels Htls.\n    clear H0.\n    rewrite OSAbstMod.map_get_set in H.\n    inverts H.\n    rewrite abst_set_get_neq in H2;auto.\n    rewrite OSAbstMod.map_get_set in H2.\n    inverts H2.\n    lets Hgoodst: H1 Hels Htls.\n    clear H1.\n    unfold get in *;simpl in *.\n    mytac.\n      \n        unfold rdy_notin_wl in *;mytac.\n        (*--------------*)\n        intros.\n        assert (t=ct\\/t<>ct) by tauto.\n        destruct H11.\n        subst t.\n        rewrite TcbMod.set_a_get_a in H10;[ | apply tidspec.eq_beq_true;auto].\n        inverts H10.\n        unfolds in Hnnp.\n        assert ( TcbMod.get tls ct <> None ).\n        intro.\n        rewrite H10 in H6;tryfalse.\n        apply Hnnp with (qid:=x) in H10.\n        destruct H10.\n        intro.\n        destruct H10.\n        unfolds in H13.\n        unfolds.\n        mytac.\n        assert (x <> x0).\n        intro.\n        subst x0.\n        rewrite EcbMod.set_a_get_a in H10;[ | apply tidspec.eq_beq_true;auto].\n        inverts H10.\n        simpl in H13;tryfalse.\n        rewrite EcbMod.set_a_get_a' in H10;[ | apply tidspec.neq_beq_false;auto].\n        do 4 eexists;split;eauto.\n        unfolds.\n        do 3 eexists;eauto.\n\n        rewrite  TcbMod.set_a_get_a' in H10;[ | apply tidspec.neq_beq_false;auto].\n        apply H in H10.\n        intro.\n        destruct H10.\n        unfolds in H13.\n        unfolds.\n        mytac.\n        assert (x <> x0).\n        intro.\n        subst x0.\n        rewrite EcbMod.set_a_get_a in H10;[ | apply tidspec.eq_beq_true;auto].\n        inverts H10.\n        simpl in H13;tryfalse.\n        rewrite EcbMod.set_a_get_a' in H10;[ | apply tidspec.neq_beq_false;auto].\n        do 4 eexists;split;eauto.\n\n        (*------------------*)\n        intros.\n        assert (t=ct\\/t<>ct) by tauto.\n        destruct H11.\n        subst t.\n        rewrite TcbMod.set_a_get_a in H10;[ | apply tidspec.eq_beq_true;auto].\n        inverts H10.\n        unfolds in Hnnp.\n        assert ( TcbMod.get tls ct <> None ).\n        intro.\n        rewrite H10 in H6;tryfalse.\n        apply Hnnp with (qid:=x) in H10.\n        destruct H10.\n        destruct H10.\n        eapply H7 in H6.\n        unfolds.\n        unfolds in H6.\n        mytac.\n        do 4 eexists;split;eauto.\n        unfolds.\n        do 3 eexists;eauto.\n\n        rewrite TcbMod.set_a_get_a' in H10;[ | apply tidspec.neq_beq_false;auto].\n        apply H7 in H10.\n        unfolds in H10.\n        unfolds.\n        mytac.\n        assert (x = eid \\/ x <> eid) by tauto.\n        destruct H14.\n        subst x.\n\n        rewrite H10 in H5;inverts H5.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        do 3 eexists;split;eauto.\n        rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        do 3 eexists;split;eauto.\n\n        (*-----------------------*)\n        intros.\n        assert (t=ct\\/t<>ct) by tauto.\n        destruct H11.\n        subst t.\n        unfolds in Hnnp.\n        assert ( TcbMod.get tls ct <> None ).\n        intro.\n        rewrite H11 in H6;tryfalse.\n        apply Hnnp with (qid:=x) in H11.\n        destruct H11.\n        destruct H11.\n\n        unfolds in H10.\n        mytac.\n        assert (eid <> x).\n        intro.\n        subst x.\n        rewrite EcbMod.set_a_get_a in H10;[ | apply tidspec.eq_beq_true;auto].\n        inverts H10;simpl in H11;tryfalse.\n        rewrite EcbMod.set_a_get_a' in H10;[ | apply tidspec.neq_beq_false;auto].\n        unfolds.\n        do 4 eexists;split;eauto.\n        unfolds.\n        do 3 eexists;eauto.\n\n        rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        apply H9.\n        unfolds in H10.\n        mytac.\n        assert (eid <> x).\n        intro.\n        subst x.\n        rewrite EcbMod.set_a_get_a in H10;[ | apply tidspec.eq_beq_true;auto].\n        inverts H10;simpl in H11;tryfalse.\n        rewrite EcbMod.set_a_get_a' in H10;[ | apply tidspec.neq_beq_false;auto].\n        unfolds.\n        do 3 eexists;split;eauto.\n\n        unfolds.\n        intros.\n        assert (t = ct \\/ t <> ct ) by tauto.\n        destruct H10.\n        subst t.\n        \n        assert (eid <> x).\n        intro.\n        subst x.\n        rewrite EcbMod.set_a_get_a in H9;[ | apply tidspec.eq_beq_true;auto].\n        inverts H9.\n\n        unfolds in Hnnp.\n        rewrite EcbMod.set_a_get_a' in H9;[ | apply tidspec.neq_beq_false;auto].\n        assert (TcbMod.get tls ct <> None).\n        intro.\n        rewrite H11 in H6;tryfalse.\n        apply Hnnp with (qid:=eid) in H11.\n        destruct H11.\n        destruct H13.\n        exists x.\n        split;auto.\n        unfolds;do 3 eexists;eauto.\n        unfolds;do 3 eexists;eauto.\n\n        (*--------------*)\n        unfolds in H0.\n        rewrite TcbMod.set_a_get_a' in H7;[ | apply tidspec.neq_beq_false;auto].\n        eapply H0;eauto.\n        assert (eid <> x).\n        intro.\n        subst x.\n        rewrite EcbMod.set_a_get_a in H9;[ | apply tidspec.eq_beq_true;auto].\n        inverts H9.\n        rewrite EcbMod.set_a_get_a' in H9;[ | apply tidspec.neq_beq_false;auto].\n        eauto.\n\n        unfolds.\n        intros.\n        assert (t = ct \\/ t <> ct ) by tauto.\n        destruct H9.\n        subst.\n        rewrite TcbMod.set_a_get_a in H7;[ | apply tidspec.eq_beq_true;auto].\n        inverts H7.\n        unfolds in H1.\n        apply H1 in H6.\n        auto.\n\n        unfolds in H1.\n        rewrite TcbMod.set_a_get_a' in H7;[ | apply tidspec.neq_beq_false;auto].\n        eapply H1;eauto.\n\n\n        unfold op_p_prop in *.\n        intros.\n        assert (t= ct \\/ t <> ct) by tauto.\n        destruct H10.\n        subst.\n        rewrite TcbMod.set_a_get_a in H7;[ | apply tidspec.eq_beq_true;auto].\n        inverts H7.\n        unfolds in H9.\n\n        assert ( TcbMod.get (TcbMod.set tls ct (p, st, m)) ct <> None ).\n        rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        auto.\n        apply H9 in H7.\n        destruct H7.\n        mytac.\n        assert (x0 <> x).\n        intro.\n        subst x0.\n        unfolds in H7.\n        mytac.\n        rewrite EcbMod.set_a_get_a in H7;[ | apply tidspec.eq_beq_true;auto].\n        inverts H7.\n        unfolds in H7.\n        rewrite EcbMod.set_a_get_a' in H7;[ | apply tidspec.neq_beq_false;auto].\n        mytac.\n\n        unfolds in Hnnp.\n        assert (TcbMod.get tls ct <> None).\n        intro.\n        rewrite H11 in H6;tryfalse.\n        apply Hnnp with (qid:=x) in H11.\n        destruct H11.\n        destruct H13.\n        exists x0.\n        split;auto.\n        unfolds;do 3 eexists;eauto.\n        unfolds;do 3 eexists;eauto.\n        destruct H7.\n        rewrite TcbMod.set_a_get_a in H10;[ | apply tidspec.eq_beq_true;auto]. \n        mytac.\n        inverts H10.\n        right.\n        clear.\n        int auto.\n\n        (*-------------------*)\n        rewrite TcbMod.set_a_get_a' in H7;[ | apply tidspec.neq_beq_false;auto].\n        eapply H2;eauto.\n        eapply post_nowt_return_getop_t;eauto.\n        \n\n        unfold wait_prop in *.\n        intros.\n        assert (t = ct \\/ t <> ct ) by tauto.\n        destruct H9.\n        subst.\n        rewrite TcbMod.set_a_get_a in H7;[ | apply tidspec.eq_beq_true;auto].\n        inverts H7.\n        unfolds in Hnnp.\n        assert ( TcbMod.get tls ct <> None ).\n        intro.\n        rewrite H7 in H6;tryfalse.\n        apply Hnnp with (qid:=x) in H7.\n        mytac.\n        destruct H7.\n        unfolds in H.\n        mytac.\n        apply H7 in H6.\n        unfolds.\n        unfolds in H6.\n        mytac.\n        do 4 eexists;split;eauto.\n        unfolds;do 3 eexists;eauto.\n\n        (*---------------*)\n        rewrite TcbMod.set_a_get_a' in H7;[ | apply tidspec.neq_beq_false;auto].\n        lets Hx:H3 H7.\n        mytac.\n        \n        assert (x0 = ct \\/ x0 <> ct) by tauto.\n        destruct H15.\n        subst x0.\n        unfolds in H.\n        destructs H.\n        lets Hy:H15 H7.\n        unfolds in Hy.\n        mytac.\n        unfolds in H10.\n        mytac.\n        assert (eid = x \\/ eid <> x) by tauto.\n        destruct H19.\n        subst x.\n        rewrite H17 in H5.\n        inverts H5.\n        simpl in H18;tryfalse.\n\n        rewrite H10 in H17;inverts H17.\n        unfolds in Hnnp.\n        assert (TcbMod.get tls ct <> None).\n        intro.\n        rewrite H17 in H6;tryfalse.\n        apply Hnnp with (qid:=eid) in H17.\n        destruct H17.\n        destruct H20.\n        exists x;split;auto.\n        unfolds;do 3 eexists;eauto.\n        unfolds;do 3 eexists;eauto.\n\n        (*-----------------*)\n        exists x0.\n        rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        do 2 eexists;splits;eauto.\n        unfolds in H10;unfolds.\n        mytac.\n        assert (x<> eid).\n        intro.\n        subst x.\n        rewrite H10 in H5;inverts H5;tryfalse.\n        rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        do 3 eexists;eauto.\n        intros.\n        apply H14.\n        eapply post_nowt_return_getop_t;eauto.\n\n        unfold no_owner_prio_prop in *.\n        intros.\n        assert (t = ct \\/ t <> ct ) by tauto.\n        destruct H11.\n        subst.\n        rewrite TcbMod.set_a_get_a in H7;[ | apply tidspec.eq_beq_true;auto].\n        inverts H7.\n        unfolds in H10.\n        assert (TcbMod.get (TcbMod.set tls ct (p, st, m)) ct <> None).\n        rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        auto.\n        apply H10 in H7.\n\n        destruct H7.\n        mytac.\n        assert (x0 <> x).\n        intro.\n        subst x0.\n        unfolds in H7.\n        mytac.\n        rewrite EcbMod.set_a_get_a in H7;[ | apply tidspec.eq_beq_true;auto].\n        inverts H7.\n        unfolds in H7.\n        rewrite EcbMod.set_a_get_a' in H7;[ | apply tidspec.neq_beq_false;auto].\n        mytac.\n\n        unfolds in Hnnp.\n        assert (TcbMod.get tls ct <> None).\n        intro.\n        rewrite H13 in H6;tryfalse.\n        apply Hnnp with (qid:=x) in H13.\n        destruct H13.\n        destruct H14.\n        exists x0.\n        split;auto.\n        unfolds;do 3 eexists;eauto.\n        unfolds;do 3 eexists;eauto.\n        \n        destruct H7.\n        rewrite TcbMod.set_a_get_a in H11;[ | apply tidspec.eq_beq_true;auto]. \n        mytac.\n        inverts H11.\n        auto.\n\n        (*---------------*)\n        rewrite TcbMod.set_a_get_a' in H7;[ | apply tidspec.neq_beq_false;auto].\n        eapply H4;eauto.\n        intro.\n        destruct H9.\n        mytac.\n        exists x0.\n        assert (x0 <> x).\n        intro.\n        subst x0.\n        unfolds in H9.\n        mytac.\n        rewrite H9 in H5;inverts H5.\n        tryfalse.\n        unfolds in H9.\n        unfolds.\n        rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto]. \n        mytac.\n        do 3 eexists;eauto.\n        eapply post_nowt_return_getop_t;eauto.\n\n   destruct H3;mytac.\n\n   clear -H0 H1 H2 H8 H9 Hnnp'.\n   rename H2 into H6.\n   rename H9 into H12.\n   inverts H6.\n   mytac.\n\n   assert (get O' curtid = Some (oscurt x9)) as Hct.\n   eapply join_get_get_l;eauto.\n   assert (get O' absecblsid = Some (absecblist x0)) as Hels.\n   eapply join_get_get_l;eauto.\n   assert (get O' abtcblsid = Some (abstcblist x2)) as Htls.\n   eapply join_get_get_l;eauto.\n\n   assert (O'' = (set O' absecblsid\n                      (absecblist (set x0 x (absmutexsem x4 None, nil))))).\n   eapply join_get_set_eq;eauto.\n   subst O''.\n   clear H2 H3 H4.\n   remember O' as Ox.\n   clear HeqOx.\n   rename x9 into ct.\n   rename x0 into els.\n   rename x2 into tls.\n   unfold GOOD_ST in *.\n   intros.\n   unfolds in Hnnp'.\n   lets Hnnp'': Hnnp' H H2.\n   clear Hnnp'.\n   unfolds in H0.\n   lets Hnnp: H0 Hels Htls.\n   clear H0.\n   rewrite OSAbstMod.map_get_set in H.\n   inverts H.\n   rewrite abst_set_get_neq in H2;auto.\n   unfold get in *;simpl in *.\n   rewrite Htls in H2;inversion H2;subst tls0.\n   lets Hgoodst: H1 Hels Htls.\n   clear H1.\n   clear H2.\n   mytac.\n  \n    (* rdy_notin_wl*)\n    unfold rdy_notin_wl in *.\n    mytac.\n    intros.\n    apply H in H11.\n    intro.\n    destruct H11.\n    unfold IS_WAITING in *.\n    mytac.\n    assert (x <> x0).\n    intro.\n    subst x0.\n    rewrite EcbMod.set_a_get_a in H11;[ | apply tidspec.eq_beq_true;auto]. \n    inverts H11.\n    simpl in H13.\n    tryfalse.\n    \n    rewrite EcbMod.set_a_get_a' in H11;[ | apply tidspec.neq_beq_false;auto]. \n    do 4 eexists;split;eauto.\n\n    (*-----------------*)\n    intros.\n    apply H9 in H11.\n\n    unfolds in H11.\n    unfolds.\n    mytac.\n    assert (x <> eid).\n    intro.\n    subst x.\n    rewrite H11 in H5.\n    inverts H5.\n    simpl in H13;tryfalse.\n    rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto]. \n    do 3 eexists;split;eauto.\n\n    (*-----------------*)\n    intros.\n    assert (x <> eid).\n    intro.\n    subst x.\n    unfolds in H11.\n    mytac.\n    rewrite EcbMod.set_a_get_a in H11;[ | apply tidspec.eq_beq_true;auto]. \n    inverts H11.\n    simpl in H13.\n    tryfalse.\n\n    apply H10.\n    unfolds in H11.\n    unfolds.\n    mytac.\n    rewrite EcbMod.set_a_get_a' in H11;[ | apply tidspec.neq_beq_false;auto]. \n    do 3 eexists;split;eauto.\n\n    (* owner_prio_prop *)\n\n    unfold owner_prio_prop in *.\n    intros.\n    assert (x <> eid).\n    intro.\n    subst x.\n    rewrite EcbMod.set_a_get_a in H10;[ | apply tidspec.eq_beq_true;auto]. \n    inverts H10.\n    rewrite EcbMod.set_a_get_a' in H10;[ | apply tidspec.neq_beq_false;auto].\n    eapply H0;eauto.\n\n    (* task_stat_prop *)\n    unfold task_stat_prop in *.\n    intros.\n    eapply H1;eauto.\n\n    (* op_p_prop *)\n    unfold op_p_prop in *.\n    intros.\n    eapply H2;eauto.\n    assert (t = ct \\/ t <> ct) by tauto.\n    destruct H11.\n    subst t.\n    unfolds.\n    intros.\n    left.\n    exists x.\n    unfolds.\n    unfolds in H10.\n    lets Hx: H10 H11.\n    destruct Hx.\n    mytac.\n    unfolds in H13.\n    mytac.\n    assert (x=x0\\/x<>x0) by tauto.\n    destruct H14.\n    subst x0.\n    rewrite EcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n    inverts H13.\n    rewrite EcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n    unfolds in Hnnp.\n    apply Hnnp with (qid:=x) in H11.\n    destruct H11.\n    destruct H15.\n    exists x0.\n    split;auto.\n    unfolds.\n    do 3 eexists;eauto.\n    unfolds;do 3 eexists;eauto.\n    destruct H13.\n    mytac.\n    rewrite H14 in H9;inverts H9.\n    unfolds in H0.\n    lets Hx:H0 H14 H5.\n    rewrite H6 in H14;inverts H14.\n    mytac.\n    destruct H9.\n    subst.\n    clear -H7;int auto.\n    subst x5.\n    do 2 eexists;eauto.\n    (*------------------*)\n    unfolds.\n    intros.\n    unfolds in H10.\n    lets Hx:H10 H13.\n    destruct Hx.\n    left.\n    mytac.\n    assert (x0 <> x).\n    intro.\n    subst x0.\n    unfolds in H14.\n    rewrite EcbMod.set_a_get_a in H14;[ | apply tidspec.eq_beq_true;auto].\n    mytac.\n    inverts H14.\n    unfolds in H14.\n    rewrite EcbMod.set_a_get_a' in H14;[ | apply tidspec.neq_beq_false;auto].\n    mytac.\n    exists x0.\n    unfolds.\n    do 2 eexists.\n    eauto.\n    right.\n    mytac.\n    intro.\n    destruct H14.\n    mytac.\n    exists x2.\n    unfolds in H14.\n    unfolds.\n    mytac.\n    assert (x<>x2).\n    intro.\n    subst x2.\n    rewrite H5 in H14;inverts H14;tryfalse.\n    rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    do 3 eexists;eauto.\n    do 2 eexists;eauto.\n\n    (* wait_prop *)\n    unfolds.\n    intros.\n    assert (t <> ct).\n    intro.\n    subst t.\n    unfolds in H.\n    mytac.\n    lets Hx: H10 H9.\n    unfolds in Hnnp.\n    assert (TcbMod.get tls ct <> None).\n    intro.\n    rewrite H13 in H6;inverts H6.\n    apply Hnnp with (qid:=x) in H13.\n    destruct H13.\n    destruct H13.\n    unfolds.\n    unfolds in Hx.\n    mytac.\n    do 4 eexists;split;eauto.\n    do 3 eexists;eauto.\n    (*----------------*)\n    unfolds in H3.\n    lets Hx:H3 H9.\n    mytac.\n    exists x0.\n    assert (x0<>ct).\n    intro.\n    subst x0.\n    assert (eid = x \\/ eid <> x) by tauto.\n    destruct H16.\n    subst x.\n    unfolds in H.\n    mytac.\n    lets Hy:H16 H9.\n    unfolds in Hy.\n    mytac.\n    rewrite H18 in H5.\n    inverts H5.\n    simpl in H19;tryfalse.\n    unfolds in Hnnp.\n    assert (TcbMod.get tls ct <> None).\n    intro.\n    rewrite H17 in H6;inverts H6.\n    eapply Hnnp in H17.\n    destruct H17.\n    destruct H18.\n    exists x.\n    split;eauto.\n    unfolds.\n    do 3 eexists;eauto.\n    unfolds in H11.\n    mytac.\n    unfolds;do 3 eexists;eauto.\n\n    assert (eid = x \\/ eid <> x) by tauto.\n    destruct H17.\n    subst x.\n    unfolds in H.\n    mytac.\n    lets Hy:H17 H9.\n    unfolds in Hy.\n    mytac.\n    rewrite H19 in H5.\n    inverts H5.\n    simpl in H20;tryfalse.\n    do 2 eexists.\n    splits;eauto.\n    unfolds.\n    unfolds in H11.\n    mytac.\n    rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    do 3 eexists;eauto.\n    (*------------------*)\n    intros.\n    apply H15.\n    unfolds.\n    intro.\n    unfolds in H18.\n    lets Hx: H18 H19.\n    destruct Hx.\n    mytac.\n    assert (x3 <> x).\n    intro.\n    subst x3.\n    unfolds in H20.\n    mytac.\n    rewrite EcbMod.set_a_get_a in H20;[ | apply tidspec.eq_beq_true;auto].\n    inverts H20.\n    \n    left.\n    exists x3.\n    unfolds.\n    unfolds in H20.\n    mytac.\n    rewrite EcbMod.set_a_get_a' in H20;[ | apply tidspec.neq_beq_false;auto].\n    do 2 eexists.\n    eauto.\n    right.\n    mytac.\n    intro.\n    destruct H20.\n    mytac.\n    exists x10.\n    assert (x10 <> x).\n    intro.\n    subst x10.\n    unfolds in H20.\n    mytac.\n    rewrite H20 in H5;inverts H5;tryfalse.\n    unfolds in H20.\n    unfolds.\n    mytac.\n    rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    do 3 eexists;eauto.\n    do 2 eexists;eauto.\n\n    (*no_owner_prio_prop*)\n    unfold no_owner_prio_prop in *.\n    intros.\n    assert (t = ct \\/ t <> ct) by tauto.\n    destruct H13.\n    subst t.\n    unfolds in H11.\n    assert (TcbMod.get tls ct <> None).\n    intro.\n    rewrite H9 in H13;tryfalse.\n    lets Hx:H11 H13;clear H11.\n    destruct Hx.\n    mytac.\n    assert (x0 = x \\/ x0 <> x) by tauto.\n    destruct H14.\n    subst x0.\n    unfolds in H11.\n    mytac.\n    rewrite EcbMod.set_a_get_a in H11;[ | apply tidspec.eq_beq_true;auto].\n    inverts H11.\n    unfolds in Hnnp.\n    eapply Hnnp in H13.\n    destruct H13.\n    destruct H15.\n    exists x;split;eauto.\n    unfolds.\n    do 3 eexists;eauto.\n    unfolds in H11.\n    unfolds.\n    mytac.\n    rewrite EcbMod.set_a_get_a' in H11;[ | apply tidspec.neq_beq_false;auto].\n    do 3 eexists;eauto.\n\n    destruct H11.\n    mytac.\n    rewrite H14 in H9;inverts H9;auto.\n\n    (*---------------------*)\n    eapply H4;eauto.\n    intro.\n    destruct H10.\n    mytac.\n    exists x0.\n    unfolds in H10.\n    mytac.\n    unfolds.\n    assert (x0 <> x).\n    intro.\n    subst x0.\n    rewrite H10 in H5.\n    inverts H5;tryfalse.\n    rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    do 3 eexists;eauto.\n\n    unfolds.\n    intro.\n    unfolds in H11.\n    lets Hx: H11 H14.\n    destruct Hx.\n    mytac.\n    assert (x0 <> x).\n    intro.\n    subst x0.\n    unfolds in H15.\n    mytac.\n    rewrite EcbMod.set_a_get_a in H15;[ | apply tidspec.eq_beq_true;auto].\n    inverts H15.\n    \n    left.\n    exists x0.\n    unfolds.\n    unfolds in H15.\n    mytac.\n    rewrite EcbMod.set_a_get_a' in H15;[ | apply tidspec.neq_beq_false;auto].\n    do 2 eexists.\n    eauto.\n    right.\n    mytac.\n    intro.\n    destruct H15.\n    mytac.\n    exists x2.\n    assert (x2 <> x).\n    intro.\n    subst x2.\n    unfolds in H15.\n    mytac.\n    rewrite H15 in H5;inverts H5;tryfalse.\n    unfolds in H15.\n    unfolds.\n    mytac.\n    rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    do 3 eexists;eauto.\n    do 2 eexists;eauto.\n   \n   destruct H3;mytac.\n   destruct H3;mytac.\n   destruct H3;mytac.\n   +\n    unfolds in H.\n    mytac.\n    unfold get in *;simpl in *.\n    rewrite H in H3;inverts H3.\n    rewrite H4 in H5.\n    inverts H5.\n    destruct H6;mytac.\n    destruct H3;mytac.\n    destruct H3;mytac.\n    destruct H3;mytac.\n    inverts H2;auto.\n    Focus 2.\n    destruct H3;mytac.\n    destruct H2;mytac.\n    destruct H2;mytac.\n    destruct H2;mytac.\n    destruct H2;mytac.\n    destruct H2;mytac.\n    destruct H2;mytac.\n\n    (*mutex pend block no lift*)\n    Focus 1.\n    destruct H3;mytac.\n    clear -H0 H1 H5 H8 H9 Hnnp'.\n    rename H5 into H6.\n    rename H9 into H12.\n    inverts H6.\n    mytac.\n    \n   assert (get O' curtid = Some (oscurt x14)) as Hct.\n   eapply join_get_get_l;eauto.\n   assert (get O' absecblsid = Some (absecblist x5)) as Hels.\n   eapply join_get_get_l;eauto.\n   assert (get O' abtcblsid = Some (abstcblist x3)) as Htls.\n   eapply join_get_get_l;eauto.\n\n   assert (O'' = (set\n             (set O' abtcblsid\n                (abstcblist\n                   (set x3 x14 (x12, wait (os_stat_mutexsem x) x0, Vnull))))\n             absecblsid\n             (absecblist\n                (set x5 x (absmutexsem x8 (Some (x9, x10)), x14 :: x7))))).\n   eapply join_get_set_eq_2;eauto.\n   subst O''.\n   clear H2 H3 H4.\n   remember O' as Ox.\n    clear HeqOx.\n    rename x14 into ct.\n    rename x5 into els.\n    rename x3 into tls.\n    unfold GOOD_ST in *.\n    intros.\n    unfolds in Hnnp'.\n    lets Hnnp'': Hnnp' H H2.\n    clear Hnnp'.\n    rewrite OSAbstMod.map_get_set in H.\n    inverts H.\n    rewrite abst_set_get_neq in H2;auto.\n    rewrite OSAbstMod.map_get_set in H2.\n    inverts H2.\n    lets Hgoodst: H1 Hels Htls.\n    clear H1.\n    unfold get in *;simpl in *.\n    -\n      mytac.\n      +\n        unfold rdy_notin_wl in *.\n        mytac;intros;auto.\n        assert (t = ct \\/ t <> ct) by tauto.\n        destruct H16.\n        subst t.\n        rewrite TcbMod.set_a_get_a in H15;[ | apply tidspec.eq_beq_true;auto].\n        inverts H15.\n        rewrite TcbMod.set_a_get_a' in H15;[ | apply tidspec.neq_beq_false;auto].\n        apply H in H15.\n        intro.\n        destruct H15.\n        eapply pend_no_lift_iswating;eauto.\n        (*----------------------*)\n        assert (t = ct \\/ t <> ct) by tauto.\n        destruct H16.\n        subst t.\n        unfolds.\n        rewrite TcbMod.set_a_get_a in H15;[ | apply tidspec.eq_beq_true;auto].\n        inverts H15.\n        do 3 eexists;split;auto.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        auto.\n        simpl;auto.\n        rewrite TcbMod.set_a_get_a' in H15;[ | apply tidspec.neq_beq_false;auto].\n        apply H13 in H15.\n        unfolds in H15.\n        unfolds.\n        mytac.\n        assert (x = eid \\/ x <> eid) by tauto.\n        destruct H18.\n        subst x.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        rewrite H15 in H5.\n        inverts H5.\n        do 3 eexists;split;auto.\n        simpl.\n        right;auto.\n        rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        do 3 eexists;split;eauto.\n        \n        assert (t = ct \\/ t <> ct) by tauto.\n        destruct H16.\n        subst t.\n        rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        unfolds in H15.\n        assert (x = eid \\/ x <> eid) by tauto.\n        destruct H16.\n        subst x.\n        rewrite EcbMod.set_a_get_a in H15;[ | apply tidspec.eq_beq_true;auto].\n        mytac.\n        do 3 eexists;eauto.\n        apply H in H6.\n        rewrite EcbMod.set_a_get_a' in H15;[ | apply tidspec.neq_beq_false;auto].\n        destruct H6.\n        unfolds.\n        mytac.\n        do 4 eexists;split;eauto.\n        rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        apply H14.\n        unfold IS_WAITING_E in *.\n        assert (x = eid \\/ x <> eid) by tauto.\n        destruct H17.\n        subst x.\n        rewrite EcbMod.set_a_get_a in H15;[ | apply tidspec.eq_beq_true;auto].\n        mytac.\n        inverts H15.\n        do 3 eexists;split;eauto.\n        simpl in H17.\n        destruct H17;auto;tryfalse.\n        rewrite EcbMod.set_a_get_a' in H15;[ | apply tidspec.neq_beq_false;auto].\n        auto.\n\n        unfold owner_prio_prop in *.\n        intros.\n        assert (t = ct \\/ t <> ct) by tauto.\n        destruct H15.\n        subst t.\n        rewrite TcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n        inverts H13.\n        assert (x=eid \\/ x<>eid) by tauto.\n        destruct H13.\n        subst x.\n        rewrite EcbMod.set_a_get_a in H14;[ | apply tidspec.eq_beq_true;auto].\n        inverts H14.\n        rewrite H6 in H7;inverts H7.\n        eapply H1;eauto.\n        rewrite EcbMod.set_a_get_a' in H14;[ | apply tidspec.neq_beq_false;auto].\n        eapply H1;eauto.\n\n        rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n        assert (x=eid \\/ x<>eid) by tauto.\n        destruct H16.\n        subst x.\n        rewrite EcbMod.set_a_get_a in H14;[ | apply tidspec.eq_beq_true;auto].\n        inverts H14.\n        eapply H1;eauto.\n        rewrite EcbMod.set_a_get_a' in H14;[ | apply tidspec.neq_beq_false;auto].\n        eapply H1;eauto.\n\n        unfold task_stat_prop in *.\n        intros.\n        assert (t = ct \\/ t <> ct) by tauto.\n        destruct H14.\n        subst t.\n        rewrite TcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n        inverts H13.\n        right.\n        do 2 eexists;auto.\n        rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n        eapply H2;eauto.\n\n        unfold op_p_prop in *.\n        intros.\n        assert (t = ct \\/ t <> ct) by tauto.\n        destruct H15.\n        Focus 2.\n        rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n        eapply H3;eauto.\n        eapply pend_no_lift_getop with (ct:=ct);eauto.\n\n        subst t.\n        rewrite TcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n        inverts H13.\n        eapply H3;eauto.        \n        unfolds.\n\n        unfolds in H14.\n        rewrite TcbMod.set_a_get_a in H14;[ | apply tidspec.eq_beq_true;auto].\n        assert (Some (p, wait (os_stat_mutexsem x) x0, Vnull) <> None) by auto.\n        apply H14 in H13.\n        destruct H13.\n        intros.\n        unfolds in Hnnp''.\n        assert (TcbMod.get\n             (TcbMod.set tls ct (p, wait (os_stat_mutexsem x) x0, Vnull)) ct <>\n                None).\n        rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        auto.\n        destruct H13.\n        eapply Hnnp'' with (qid:=x1) in H16;eauto.\n        destruct H16.\n        destruct H16.\n        unfolds.\n        exists x.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto]. \n        do 3 eexists;split;simpl;auto.\n        simpl;left;auto.\n        unfolds.\n        unfolds in H13.\n        mytac.\n        do 3 eexists;eauto.\n        destruct H13.\n        mytac.\n        inverts H15.\n        intros.\n        right.\n        unfolds in Hnnp''.\n        assert (TcbMod.get\n             (TcbMod.set tls ct (op, wait (os_stat_mutexsem x) x0, Vnull)) ct <>\n                None).\n        rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        auto.\n        split.\n        intro.\n        destruct H13.\n        mytac.\n        exists x1.\n        unfold IS_OWNER in *.\n        mytac.\n        assert (x= x1 \\/ x <> x1) by tauto.\n        destruct H17.\n        subst x.\n        rewrite H13 in H5;inverts H5.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto]. \n        do 3 eexists;simpl;auto.\n        rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto]. \n        do 3 eexists;simpl;eauto.\n        do 2 eexists;eauto.\n\n        (*wait_prop*)\n        unfold wait_prop in *.\n        intros.\n        assert (t=ct \\/ t<>ct) by tauto.\n        destruct H14.\n        subst t.\n        rewrite TcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n        inverts H13.\n        exists x9 x11 x13.\n        splits.\n        unfolds.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        do 3 eexists;auto.\n        assert (x9 <> ct).\n        intro.\n        subst x9.\n        unfolds in Hnnp''.\n        assert (TcbMod.get\n             (TcbMod.set tls ct (p, wait (os_stat_mutexsem eid) tm, Vnull)) ct <>\n                None).\n        rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        auto.\n        eapply Hnnp'' with (qid:=eid) in H13.\n        destruct H13.\n        destruct H13.\n        unfolds.\n        exists eid.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        do 3 eexists;split;auto.\n        simpl;left;auto.\n        unfolds.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        do 3 eexists;auto.\n        rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        assert (IS_OWNER x9 eid els).\n        unfolds.\n        do 3 eexists;eauto.\n        unfolds in H0.\n        lets Hxx:H0 Hels Htls.\n        unfolds in Hxx.\n        assert (TcbMod.get tls x9 <> None).\n        intro.\n        rewrite H15 in H7;tryfalse.\n        lets Hx:Hxx H15 H14.\n        unfolds in H2.\n        lets Hy: H2 H7.\n        destruct Hy;subst;auto.\n\n        destruct H9.\n        assert (Int.eq x11 x8 = true).\n        clear -H9.\n        int auto.\n        lets Hx: Int.eq_spec x11 x8.\n        rewrite H13 in Hx.\n        subst;auto.\n        lets Hx: H1 H7 H5.\n        destruct Hx.\n        destruct H13;subst;auto.\n\n        intros.\n        unfolds in H13.\n        assert (TcbMod.get\n          (TcbMod.set tls ct (p, wait (os_stat_mutexsem eid) tm, Vnull)) ct <>\n                None ).\n        rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        auto.\n        apply H13 in H14.\n        clear H13.\n        destruct H14.\n        destruct H13.\n        unfolds in Hnnp''.\n        assert (TcbMod.get\n          (TcbMod.set tls ct (p, wait (os_stat_mutexsem eid) tm, Vnull)) ct <>\n                None ).\n        rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        auto.\n\n        apply Hnnp'' with (qid:=x)in H14.\n        destruct H14.\n        destruct H14.\n        unfolds.\n        exists eid.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        do 3 eexists;split;auto.\n        simpl;left;auto.\n        unfolds in H13.\n        unfolds.\n        mytac.\n        do 3 eexists;eauto.\n        destruct H13.\n        rewrite TcbMod.set_a_get_a in H14;[ | apply tidspec.eq_beq_true;auto].\n        mytac.\n        inverts H14.\n        auto.\n        (*----------*)\n        rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n        apply H4 in H13.\n        mytac.\n        exists x1.\n        do 2 eexists;splits;eauto.\n        clear -H13 H5.\n        assert (x = eid \\/ x <> eid) by tauto.\n        destruct H.\n        subst x.\n        unfold IS_OWNER in *.\n        mytac.\n        rewrite H in H5;inverts H5.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        do 3 eexists;auto.\n        unfold IS_OWNER in *.\n        mytac.\n        rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        do 3 eexists;eauto.\n\n        assert (x1 <> ct).\n        intro;subst x1.\n        unfolds in Hnnp''.\n        assert ( TcbMod.get\n             (TcbMod.set tls ct (x12, wait (os_stat_mutexsem x) x0, Vnull)) ct <>\n                 None).\n        rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        auto.\n        eapply Hnnp'' with (qid:=eid) in H18.\n        destruct H18.\n        destruct H18.\n        unfolds.\n        exists x.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        do 3 eexists;split;auto.\n        simpl;left;auto.\n        \n        clear -H13 H5.\n        assert (x = eid \\/ x <> eid) by tauto.\n        destruct H.\n        subst x.\n        unfold IS_OWNER in *.\n        mytac.\n        rewrite H in H5;inverts H5.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        do 3 eexists;auto.\n        unfold IS_OWNER in *.\n        mytac.\n        rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        do 3 eexists;eauto.\n        rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        eauto.\n\n        intros.\n        apply H17.\n        eapply pend_no_lift_getop with (ct:=ct);eauto.\n\n        (*no_owner_prio_prop*)\n        unfold no_owner_prio_prop in *.\n        intros.\n        assert (t = ct \\/ t <> ct ) by tauto.\n        destruct H16.\n        (*------------*)\n        subst t.\n        rewrite TcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n        inverts H13.\n        lets Hx:pend_no_lift_getop H6 H5 H15.\n        eapply H11;eauto.\n        intro.\n        mytac.\n        unfolds in Hnnp''.\n        assert (TcbMod.get\n             (TcbMod.set tls ct (p, wait (os_stat_mutexsem x) x0, Vnull)) ct <>\n                None).\n        rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        auto.\n        apply Hnnp'' with (qid:=x1) in H16.\n        destruct H16.\n        destruct H16.\n        unfolds.\n        exists x.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        do 3 eexists;auto.\n        split;auto.\n        simpl;left;auto.\n\n        clear -H13 H5.\n        assert (x = x1 \\/ x <> x1) by tauto.\n        destruct H.\n        subst x1.\n        unfold IS_OWNER in *.\n        mytac.\n        rewrite H in H5;inverts H5.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        do 3 eexists;auto.\n        unfold IS_OWNER in *.\n        mytac.\n        rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        do 3 eexists;eauto.\n\n        (*-----------------*)\n        rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n        eapply H11;eauto.\n        intro.\n        destruct H14.\n        mytac.\n        exists x1.\n\n        clear -H14 H5.\n        assert (x = x1 \\/ x <> x1) by tauto.\n        destruct H.\n        subst x.\n        unfold IS_OWNER in *.\n        mytac.\n        rewrite H in H5;inverts H5.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        do 3 eexists;auto.\n        unfold IS_OWNER in *.\n        mytac.\n        rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        do 3 eexists;eauto.\n        eapply pend_no_lift_getop with (ct:=ct);eauto.\n\n    (*mutex pend lift*)\n    destruct H2;mytac.\n    Focus 1.\n    clear -H0 H1 H5 H8 H9 Hnnp'.\n    rename H5 into H6.\n    rename H9 into H12.\n    rename H8 into Hff.\n    inverts H6.\n    mytac.\n    \n    assert (get O' curtid = Some (oscurt x15)) as Hct.\n    eapply join_get_get_l;eauto.\n    assert (get O' absecblsid = Some (absecblist x6)) as Hels.\n    eapply join_get_get_l;eauto.\n    assert (get O' abtcblsid = Some (abstcblist x3)) as Htls.\n    eapply join_get_get_l;eauto.\n\n    assert (O'' = (set\n             (set O' abtcblsid\n                (abstcblist\n                   (set (set x3 x15 (x13, wait (os_stat_mutexsem x) x0, x2))\n                      x10 (x9, rdy, x14)))) absecblsid\n             (absecblist\n                (set x6 x (absmutexsem x9 (Some (x10, x11)), x15 :: x8))))).\n    eapply join_get_set_eq_2;eauto.\n    subst O''.\n    clear H2 H3 H4.\n    remember O' as Ox.\n    clear HeqOx.\n    rename x15 into ct.\n    rename x6 into els.\n    rename x3 into tls.\n    unfold GOOD_ST in *.\n    intros.\n    unfolds in Hnnp'.\n    lets Hnnp'': Hnnp' H H2.\n    clear Hnnp'.\n    rewrite OSAbstMod.map_get_set in H.\n    inverts H.\n    rewrite abst_set_get_neq in H2;auto.\n    rewrite OSAbstMod.map_get_set in H2.\n    inverts H2.\n    lets Hgoodst: H1 Hels Htls.\n    clear H1.\n    -\n      assert (x10 <> ct) as Hneq.\n      intro Hneq.\n      subst x10.\n      unfolds in Hnnp''.\n      assert (TcbMod.get\n             (TcbMod.set\n                (TcbMod.set tls ct (x13, wait (os_stat_mutexsem x) x0, x2))\n                ct (x9, rdy, x14)) ct <> None).\n      rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n      auto.\n      apply Hnnp'' with (qid:=x) in H.\n      destruct H.\n      destruct H.\n      unfolds.\n      exists x.\n      rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n      do 3 eexists;split;auto.\n      simpl;left;auto.\n      unfolds.\n      rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n      do 3 eexists;split;auto.\n      unfold get in *;simpl in *.\n      mytac.\n      +\n        unfold rdy_notin_wl in *.\n        mytac;intros;auto.\n        (*------------*)\n        assert (t = ct \\/ t <> ct) by tauto.\n        destruct H16.\n        subst t.\n        rewrite TcbMod.set_a_get_a' in H15;[ | apply tidspec.neq_beq_false;auto].\n        rewrite TcbMod.set_a_get_a in H15;[ | apply tidspec.eq_beq_true;auto].\n        inverts H15.\n\n        assert (t = x10 \\/ t <> x10) by tauto.\n        destruct H17.\n        subst t.\n\n        rewrite TcbMod.set_a_get_a in H15;[ | apply tidspec.eq_beq_true;auto].\n        inverts H15.\n        apply H in H7.\n        intro.\n        destruct H7.\n        eapply pend_no_lift_iswating;eauto.\n\n        rewrite TcbMod.set_a_get_a' in H15;[ | apply tidspec.neq_beq_false;auto].\n        rewrite TcbMod.set_a_get_a' in H15;[ | apply tidspec.neq_beq_false;auto].\n        apply H in H15.\n        intro.\n        destruct H15.\n        eapply pend_no_lift_iswating with (ct:=ct);eauto.\n        (*----------------------*)\n        assert (t = ct \\/ t <> ct) by tauto.\n        destruct H16.\n        subst t.\n        unfolds.\n        rewrite TcbMod.set_a_get_a' in H15;[ | apply tidspec.neq_beq_false;auto].\n        rewrite TcbMod.set_a_get_a in H15;[ | apply tidspec.eq_beq_true;auto].\n        inverts H15.\n        do 3 eexists;split;auto.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        auto.\n        simpl;auto.\n\n        assert (t = x10 \\/ t <> x10) by tauto.\n        destruct H17.\n        subst.\n        rewrite TcbMod.set_a_get_a in H15;[ | apply tidspec.eq_beq_true;auto].\n        inverts H15.\n\n        rewrite TcbMod.set_a_get_a' in H15;[ | apply tidspec.neq_beq_false;auto].\n        rewrite TcbMod.set_a_get_a' in H15;[ | apply tidspec.neq_beq_false;auto].\n        apply H13 in H15.\n        unfolds in H15.\n        unfolds.\n        mytac.\n        assert (x = eid \\/ x <> eid) by tauto.\n        destruct H19.\n        subst x.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        rewrite H15 in H5.\n        inverts H5.\n        do 3 eexists;split;auto.\n        simpl.\n        right;auto.\n        rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        do 3 eexists;split;eauto.\n        (*-------------------*)\n        assert (t = ct \\/ t <> ct) by tauto.\n        destruct H16.\n        subst t.\n        rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        unfolds in H15.\n        assert (x = eid \\/ x <> eid) by tauto.\n        destruct H16.\n        subst x.\n        rewrite EcbMod.set_a_get_a in H15;[ | apply tidspec.eq_beq_true;auto].\n        mytac.\n        do 3 eexists;eauto.\n        apply H in H6.\n        rewrite EcbMod.set_a_get_a' in H15;[ | apply tidspec.neq_beq_false;auto].\n        destruct H6.\n        unfolds.\n        mytac.\n        do 4 eexists;split;eauto.\n\n        assert (t=x10 \\/ t<>x10) by tauto.\n        destruct H17.\n        subst.\n        rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        assert (IS_WAITING_E x10 eid els).\n        unfold IS_WAITING_E in *.\n        assert (x = eid \\/ x <> eid) by tauto.\n        destruct H17.\n        subst x.\n        rewrite EcbMod.set_a_get_a in H15;[ | apply tidspec.eq_beq_true;auto].\n        mytac.\n        inverts H15.\n        do 3 eexists;split;eauto.\n        simpl in H17.\n        destruct H17;auto;tryfalse.\n        rewrite EcbMod.set_a_get_a' in H15;[ | apply tidspec.neq_beq_false;auto].\n        auto.\n        apply H14 in H17.\n        mytac.\n        rewrite H17 in H7;inverts H7.\n\n        rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        apply H14.\n        unfold IS_WAITING_E in *.\n        assert (x = eid \\/ x <> eid) by tauto.\n        destruct H18.\n        subst x.\n        rewrite EcbMod.set_a_get_a in H15;[ | apply tidspec.eq_beq_true;auto].\n        mytac.\n        inverts H15.\n        do 3 eexists;split;eauto.\n        simpl in H18.\n        destruct H18;auto;tryfalse.\n        rewrite EcbMod.set_a_get_a' in H15;[ | apply tidspec.neq_beq_false;auto].\n        auto.\n\n        unfold owner_prio_prop in *.\n        intros.\n        assert (t = ct \\/ t <> ct) by tauto.\n        destruct H15.\n        subst t.\n        rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n        rewrite TcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n        inverts H13.\n        assert (x=eid \\/ x<>eid) by tauto.\n        destruct H13.\n        subst x.\n        rewrite EcbMod.set_a_get_a in H14;[ | apply tidspec.eq_beq_true;auto].\n        inverts H14.\n        rewrite H6 in H7;inverts H7.\n        eapply H1;eauto.\n        rewrite EcbMod.set_a_get_a' in H14;[ | apply tidspec.neq_beq_false;auto].\n        eapply H1;eauto.\n\n        assert (t = x10 \\/ t <> x10) by tauto.\n        destruct H16.\n        subst t.\n        rewrite TcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n        inverts H13.\n        assert (x=eid \\/ x<>eid) by tauto.\n        destruct H13.\n        subst x.\n        rewrite EcbMod.set_a_get_a in H14;[ | apply tidspec.eq_beq_true;auto].\n        inverts H14.\n        lets Hx: H1 H7 H5.\n        destruct Hx.\n        split;auto.\n        rewrite EcbMod.set_a_get_a' in H14;[ | apply tidspec.neq_beq_false;auto].\n        unfolds in H0.\n        lets Hx:H0 Hels Htls.\n        unfolds in Hx.\n        assert (IS_OWNER x10 eid els).\n        unfolds.\n        do 3 eexists;eauto.\n        lets Hy:Hx H16.\n        intro.\n        rewrite H17 in H7;tryfalse.\n        destruct Hy.\n        destruct H18.\n        exists x;split;auto.\n        unfolds;do 3 eexists;eauto.\n        \n        rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n        rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n        assert (x=eid \\/ x<>eid) by tauto.\n        destruct H17.\n        subst x.\n        rewrite EcbMod.set_a_get_a in H14;[ | apply tidspec.eq_beq_true;auto].\n        inverts H14.\n        eapply H1;eauto.\n        rewrite EcbMod.set_a_get_a' in H14;[ | apply tidspec.neq_beq_false;auto].\n        eapply H1;eauto.\n\n        unfold task_stat_prop in *.\n        intros.\n        assert (t = ct \\/ t <> ct) by tauto.\n        destruct H14.\n        subst t.\n        rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n        rewrite TcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n        inverts H13.\n        right.\n        do 2 eexists;auto.\n\n        assert (t=x10\\/t<>x10) by tauto.\n        destruct H15.\n        subst t.\n        rewrite TcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n        inverts H13.\n        eapply H2;eauto.\n        \n        rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n        rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n        eapply H2;eauto.\n\n        unfold op_p_prop in *.\n        intros.\n        assert (t = ct \\/ t <> ct) by tauto.\n        destruct H15.\n        Focus 2.\n        assert (t <> x10 \\/ t = x10) by tauto.\n        destruct H16.\n        rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n        rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n        eapply H3;eauto.\n        eapply pend_lift_getop_t with (ct:=ct) (x10:=x10);eauto.\n\n        subst t.\n        unfolds in H14.\n        assert (TcbMod.get\n          (TcbMod.set\n             (TcbMod.set tls ct (x13, wait (os_stat_mutexsem x) x0, x2)) x10\n             (x9, rdy, x14)) x10 <> None).\n        rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        auto.\n        lets Hx: H14 H16.\n        clear H14.\n        destruct Hx.\n        destruct H14.\n        assert (x1 = x \\/ x1 <> x) by tauto.\n        destruct H17.\n        subst x1.\n        unfolds in H14.\n        rewrite EcbMod.set_a_get_a in H14;[ | apply tidspec.eq_beq_true;auto].\n        mytac.\n        inverts H14.\n        rewrite TcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n        inverts H13.\n        left.\n        clear -H9 H10;int auto.\n\n        unfolds in Hnnp''.\n        assert (IS_OWNER x10 x1\n                         (EcbMod.set els x (absmutexsem x9 (Some (x10, x11)), ct :: x8))).\n        unfolds.\n        unfolds in H14.\n        mytac.\n        do 3 eexists;eauto.\n        lets Hx:Hnnp'' H16 H18.\n        destruct Hx.\n        destruct H20.\n        exists x.\n        split;auto.\n        unfolds.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        do 3 eexists;auto.\n\n        destruct H14.\n        destruct H14.\n        exists x.\n        unfolds.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        do 3 eexists;auto.\n        (*---------------*)\n\n        subst t.\n        rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n        rewrite TcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n        inverts H13.\n        eapply H3;eauto.        \n        unfolds.\n\n        unfolds in H14.\n        rewrite TcbMod.set_a_get_a' in H14;[ | apply tidspec.neq_beq_false;auto].\n        rewrite TcbMod.set_a_get_a in H14;[ | apply tidspec.eq_beq_true;auto].\n        assert (Some (p, wait (os_stat_mutexsem x) x0, m) <> None) by auto.\n        apply H14 in H13.\n        destruct H13.\n        intros.\n        unfolds in Hnnp''.\n        assert (TcbMod.get\n             (TcbMod.set\n                (TcbMod.set tls ct (p, wait (os_stat_mutexsem x) x0, m)) x10\n                (x9, rdy, x14)) ct <>\n                None).\n        rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        auto.\n        destruct H13.\n        eapply Hnnp'' with (qid:=x1) in H16;eauto.\n        destruct H16.\n        destruct H16.\n        unfolds.\n        exists x.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto]. \n        do 3 eexists;split;simpl;auto.\n        simpl;left;auto.\n        unfolds.\n        unfolds in H13.\n        mytac.\n        do 3 eexists;eauto.\n        destruct H13.\n        mytac.\n        inverts H15.\n        intros.\n        right.\n        unfolds in Hnnp''.\n        assert ( TcbMod.get\n             (TcbMod.set\n                (TcbMod.set tls ct (op, wait (os_stat_mutexsem x) x0, x2))\n                x10 (x9, rdy, x14)) ct <>\n                None).\n        rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        auto.\n        split.\n        intro.\n        destruct H13.\n        mytac.\n        exists x1.\n        unfold IS_OWNER in *.\n        mytac.\n        assert (x= x1 \\/ x <> x1) by tauto.\n        destruct H17.\n        subst x.\n        rewrite H13 in H5;inverts H5.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto]. \n        do 3 eexists;simpl;auto.\n        rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto]. \n        do 3 eexists;simpl;eauto.\n        do 2 eexists;eauto.\n\n        (*wait_prop*)\n        unfold wait_prop in *.\n        intros.\n        assert (t=ct \\/ t<>ct) by tauto.\n        destruct H14.\n        subst t.\n        rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n        rewrite TcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n        inverts H13.\n        exists x10 x9 x14.\n        splits.\n        unfolds.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        do 3 eexists;auto.\n        \n        rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        auto.\n        auto.\n\n        intros.\n        unfolds in H13.\n        assert (TcbMod.get\n                  (TcbMod.set\n                     (TcbMod.set tls ct (p, wait (os_stat_mutexsem eid) tm, m)) x10\n                     (x9, rdy, x14)) ct <> None).\n        rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        auto.\n        apply H13 in H14.\n        clear H13.\n        destruct H14.\n        destruct H13.\n        unfolds in Hnnp''.\n        assert (TcbMod.get\n                  (TcbMod.set\n                     (TcbMod.set tls ct (p, wait (os_stat_mutexsem eid) tm, m)) x10\n                     (x9, rdy, x14)) ct <> None).\n        rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        auto.\n\n        apply Hnnp'' with (qid:=x)in H14.\n        destruct H14.\n        destruct H14.\n        unfolds.\n        exists eid.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        do 3 eexists;split;auto.\n        simpl;left;auto.\n        unfolds in H13.\n        unfolds.\n        mytac.\n        do 3 eexists;eauto.\n        destruct H13.\n        rewrite TcbMod.set_a_get_a' in H14;[ | apply tidspec.neq_beq_false;auto].\n        rewrite TcbMod.set_a_get_a in H14;[ | apply tidspec.eq_beq_true;auto].\n        mytac.\n        inverts H14.\n        auto.\n        (*----------*)\n        assert (t <> x10 \\/ t = x10) by tauto.\n        destruct H15.\n        rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n        rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n        assert (TcbMod.get tls t = Some (p, wait (os_stat_mutexsem eid) tm, m)) as Hgett.\n        auto.\n        apply H4 in H13.\n        mytac.\n        \n        assert (x1<>x10 \\/ x1 = x10) by tauto.\n        destruct H19.\n        rename H19 into Hf.\n        exists x1.\n        do 2 eexists;splits;eauto.\n        clear -H13 H5.\n        assert (x = eid \\/ x <> eid) by tauto.\n        destruct H.\n        subst x.\n        unfold IS_OWNER in *.\n        mytac.\n        rewrite H in H5;inverts H5.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        do 3 eexists;auto.\n        unfold IS_OWNER in *.\n        mytac.\n        rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        do 3 eexists;eauto.\n\n        assert (x1 <> ct).\n        intro;subst x1.\n        unfolds in Hnnp''.\n        assert ( TcbMod.get\n             (TcbMod.set\n                (TcbMod.set tls ct (x13, wait (os_stat_mutexsem x) x0, x2))\n                x10 (x9, rdy, x14)) ct <>\n                 None).\n        rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        auto.\n        eapply Hnnp'' with (qid:=eid) in H19.\n        destruct H19.\n        destruct H19.\n        unfolds.\n        exists x.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        do 3 eexists;split;auto.\n        simpl;left;auto.\n        \n        clear -H13 H5.\n        assert (x = eid \\/ x <> eid) by tauto.\n        destruct H.\n        subst x.\n        unfold IS_OWNER in *.\n        mytac.\n        rewrite H in H5;inverts H5.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        do 3 eexists;auto.\n        unfold IS_OWNER in *.\n        mytac.\n        rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        do 3 eexists;eauto.\n        \n        rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        eauto.\n\n        intros.\n        apply H18.\n        eapply pend_lift_getop_t with (ct:=ct);eauto.\n        (*--------------*)\n        subst x1.\n        assert (x <> eid \\/ x = eid) by tauto.\n        destruct H19.\n        unfolds in Hnnp''.\n        assert ( TcbMod.get\n             (TcbMod.set\n                (TcbMod.set tls ct (x13, wait (os_stat_mutexsem x) x0, x2))\n                x10 (x9, rdy, x14)) x10 <> None ).\n\n        rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        auto.\n        apply Hnnp'' with (qid:=eid) in H20.\n        destruct H20.\n        destruct H21.\n        exists x.\n        split;auto.\n        unfold IS_OWNER in *.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        mytac;do 3 eexists;auto.\n        unfold IS_OWNER in *.\n        mytac.\n        rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        do 3 eexists;eauto.\n        subst x.\n        \n        exists x10 x9 x14.\n        splits.\n        unfolds.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        do 3 eexists;auto.\n        \n        rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        auto.\n\n        assert (IS_OWNER x10 eid els).\n        unfolds.\n        do 3 eexists;eauto.\n        auto.\n        auto.\n        unfolds in H0.\n        lets Hxx:H0 Hels Htls.\n        unfolds in Hxx.\n        assert (TcbMod.get tls x10 <> None).\n        intro.\n        rewrite H16 in H7;tryfalse.\n        lets Hx:Hxx H20 H13.\n        unfolds in H2.\n        lets Hy: H2 H7.\n        destruct Hy;mytac;subst;auto;tryfalse.\n        mytac.\n        unfolds in H.\n        mytac.\n\n        rewrite H7 in H16;inverts H16.\n        unfolds in H1.\n        lets Hx:H1 H7 H5.\n        destruct Hx.\n        destruct H16;subst;auto.\n        clear -H25 H17.\n        int auto.\n\n        intros.\n        apply H18.\n        eapply pend_lift_getop_t with (ct:=ct) (x10:=x10) in H19;eauto.\n\n        (*--------------*)\n        subst t.\n        rewrite TcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n        inverts H13.\n        \n        (*no_owner_prio_prop*)\n        unfold no_owner_prio_prop in *.\n        intros.\n        assert (t = ct \\/ t <> ct ) by tauto.\n        destruct H16.\n        (*------------*)\n        subst t.\n        rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n        rewrite TcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n        inverts H13.\n\n        lets Hx:pend_lift_getop_ct H6 H5 H15;eauto.\n        eapply H11;eauto.\n        intro.\n        mytac.\n        unfolds in Hnnp''.\n        assert (TcbMod.get\n             (TcbMod.set\n                (TcbMod.set tls ct (p, wait (os_stat_mutexsem x) x0, m)) x10\n                (x9, rdy, x14)) ct <>\n                None).\n        rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        auto.\n        apply Hnnp'' with (qid:=x1) in H16.\n        destruct H16.\n        destruct H16.\n        unfolds.\n        exists x.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        do 3 eexists;auto.\n        split;auto.\n        simpl;left;auto.\n\n        clear -H13 H5.\n        assert (x = x1 \\/ x <> x1) by tauto.\n        destruct H.\n        subst x1.\n        unfold IS_OWNER in *.\n        mytac.\n        rewrite H in H5;inverts H5.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        do 3 eexists;auto.\n        unfold IS_OWNER in *.\n        mytac.\n        rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        do 3 eexists;eauto.\n\n        (*-----------------*)\n        assert (t <> x10 \\/ t = x10) by tauto.\n        destruct H17.\n        rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n        rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n        eapply H11;eauto.\n        intro.\n        destruct H14.\n        mytac.\n        exists x1.\n\n        clear -H14 H5.\n        assert (x = x1 \\/ x <> x1) by tauto.\n        destruct H.\n        subst x.\n        unfold IS_OWNER in *.\n        mytac.\n        rewrite H in H5;inverts H5.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        do 3 eexists;auto.\n        unfold IS_OWNER in *.\n        mytac.\n        rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n        do 3 eexists;eauto.\n        eapply pend_lift_getop_t with (ct:=ct);eauto.\n        \n        (*------------------*)\n        subst t.\n        destruct H14.\n        exists x.\n        unfolds.\n        rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n        do 3 eexists;auto.\n\n    destruct H2;mytac.\n    destruct H2;mytac.\n    destruct H2;mytac.\n\n  (* post exwt return *)\n    clear -H0 H1 H5 H8 H9 Hnnp'.\n    rename H5 into H6.\n    rename H9 into H12.\n    rename H8 into Hfff.\n    inverts H6.\n    mytac.\n    assert (get O' curtid = Some (oscurt x15)) as Hct.\n    eapply join_get_get_l;eauto.\n    assert (get O' absecblsid = Some (absecblist x0)) as Hels.\n    eapply join_get_get_l;eauto.\n    assert (get O' abtcblsid = Some (abstcblist x2)) as Htls.\n    eapply join_get_get_l;eauto.\n\n    assert (O'' =  (set\n             (set O' abtcblsid\n                (abstcblist\n                   (set (set x2 x15 (x8, x9, x10)) x12 (x7, rdy, Vptr x))))\n             absecblsid\n             (absecblist\n                (set x0 x\n                   (absmutexsem x6 (Some (x12, x7)), remove_tid x12 x11))))).\n    eapply join_get_set_eq_2;eauto.\n    subst O''.\n    clear H2 H3 H4.\n    remember O' as Ox.\n    clear HeqOx.\n    rename x15 into ct.\n    rename x0 into els.\n    rename x2 into tls.\n    unfold GOOD_ST in *.\n    intros.\n    unfolds in Hnnp'.\n    lets Hnnp'': Hnnp' H H2.\n    clear Hnnp'.\n    unfolds in H0.\n    lets Hnnp: H0 Hels Htls.\n    clear H0.\n    rewrite OSAbstMod.map_get_set in H.\n    inverts H.\n    rewrite abst_set_get_neq in H2;auto.\n    rewrite OSAbstMod.map_get_set in H2.\n    inverts H2.\n    unfold get in *;simpl in *.\n    lets Hgoodst: H1 Hels Htls.\n    clear H1.\n    destructs Hgoodst.\n    assert (ct <> x12) as Hneq.\n    intro.\n    subst x12.\n    unfolds in Hnnp.\n    assert (TcbMod.get tls ct <> None).\n    intro.\n    rewrite H10 in H8;tryfalse.\n    apply Hnnp with (qid:=x) in H10.\n    mytac.\n    destruct H10.\n    unfolds.\n    do 4 eexists;split;eauto.\n    unfolds in H7.\n    mytac;auto.\n    unfolds.\n    do 3 eexists;eauto.\n\n    assert (~ IS_WAITING ct els) as Hctnwait.\n    intro.\n    unfolds in Hnnp.\n    assert (TcbMod.get tls ct <> None).\n    intro.\n    rewrite H11 in H8;tryfalse.\n    apply Hnnp with (qid:=x) in H11.\n    mytac.\n    destruct H11.\n    auto.\n    unfolds.\n    do 3 eexists;eauto.\n\n    \n    (*rdy_notin_wl*)\n    unfold rdy_notin_wl in *.\n    mytac.\n    intros.\n    assert (t = ct \\/ t <> ct) by tauto.\n    destruct H14.\n    subst t.\n    rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n    rewrite TcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n    inverts H13.\n    apply H in H8.\n    intro.\n\n    destruct H8.\n    eapply post_iswait;eauto.\n    assert (t = x12 \\/ t <> x12) by tauto.\n    destruct H15.\n    subst x12.\n    rewrite TcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n    inverts H13.\n\n    eapply nnp_remove_nwait;eauto.\n    unfolds;splits;eauto.\n    rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n    rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n    apply H in H13.\n    intro.\n    destruct H13.\n\n\n    eapply remove_is_wait_neq;eauto.\n    (*--------------------*)\n    intros.\n    assert (t = ct \\/ t <> ct) by tauto.\n    destruct H14.\n    subst t.\n    rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n    rewrite TcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n    inverts H13.\n    lets Hx:H10 H8.\n    unfolds in Hnnp.\n    assert (TcbMod.get tls ct <> None).\n    intro.\n    rewrite H13 in H8;tryfalse.\n    apply Hnnp with(qid:=x)in H13.\n    destruct H13.\n    destruct H13.\n    unfolds in Hx;mytac;unfolds;do 4 eexists;eauto.\n    unfolds;do 3 eexists;eauto.\n\n    assert (t <> x12).\n    intro.\n    subst x12.\n    rewrite TcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n    inverts H13.\n    \n    rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n    rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n    apply H10 in H13.\n    eapply post_iswait' in H15;eauto.\n    destruct H15;eauto.\n\n    (*----------------*)\n    intros.\n    assert (t = ct \\/ t <> ct) by tauto.\n    destruct H14.\n    subst t.\n    assert (IS_WAITING_E ct eid els).\n    eapply post_iswait';eauto.\n    unfolds in Hnnp.\n    assert (TcbMod.get tls ct <> None).\n    intro.\n    rewrite H15 in H8;tryfalse.\n    apply Hnnp with(qid:=x)in H15.\n    destruct H15.\n    destruct H15.\n    unfolds in H14;mytac;unfolds;do 4 eexists;eauto.\n    unfolds;do 3 eexists;eauto.\n\n    assert (t = x12 \\/ t <> x12) by tauto.\n    destruct H15.\n    subst t.\n    lets Hx: nnp_remove_nwait Hnnp H7 H5 H9.\n    unfolds;split;auto.\n    destruct Hx.\n    unfolds in H13;mytac.\n    unfolds;do 4 eexists;split;eauto.\n    rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    eapply H11;eauto.\n    eapply post_iswait';eauto.\n\n    (*owner_prio_prop*)\n    unfold owner_prio_prop in *.\n    intros.\n\n    assert (t = ct \\/ t <> ct ) by tauto.\n    destruct H15.\n    subst t.\n    \n    assert (eid <> x).\n    intro.\n    subst x.\n    rewrite EcbMod.set_a_get_a in H14;[ | apply tidspec.eq_beq_true;auto].\n    inverts H14;tryfalse.\n\n    unfolds in Hnnp.\n    rewrite EcbMod.set_a_get_a' in H14;[ | apply tidspec.neq_beq_false;auto].\n    assert (TcbMod.get tls ct <> None).\n    intro.\n    rewrite H16 in H8;tryfalse.\n    apply Hnnp with (qid:=eid) in H16.\n    destruct H16.\n    destruct H17.\n    exists x.\n    split;auto.\n    unfolds;do 3 eexists;eauto.\n    unfolds;do 3 eexists;eauto.\n\n    (*--------------*)\n    assert (t <> x12 \\/ t = x12) by tauto.\n    destruct H16.\n    rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n    rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n    eapply H0;eauto.\n    assert (eid <> x).\n    intro.\n    subst x.\n    rewrite EcbMod.set_a_get_a in H14;[ | apply tidspec.eq_beq_true;auto].\n    inverts H14;tryfalse.\n    rewrite EcbMod.set_a_get_a' in H14;[ | apply tidspec.neq_beq_false;auto].\n    eauto.\n\n    subst x12.\n    rewrite TcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n    inverts H13.\n\n    assert (eid = x \\/ eid <> x ) by tauto.\n    destruct H13.\n    subst x.\n    rewrite  EcbMod.set_a_get_a in H14;[ | apply tidspec.eq_beq_true;auto].\n    inverts H14.\n    split;auto.\n    unfolds in H3.\n    assert (IS_WAITING_E t eid els).\n    unfolds.\n    do 3 eexists;split;eauto.\n    unfolds in H7;mytac;auto.\n    apply H11 in H13.\n    mytac.\n    rewrite H13 in H9;inverts H9.\n    apply H3 in H13.\n    mytac.\n    unfolds in H9.\n    mytac.\n    rewrite H9 in H5;inverts H5.\n    rewrite H13 in H8;inverts H8.\n    auto.\n\n    rewrite EcbMod.set_a_get_a' in H14;[ | apply tidspec.neq_beq_false;auto].\n    eauto.\n\n    (*task_stat_prop*)\n    unfolds.\n    intros.\n    assert (t = ct \\/ t <> ct ) by tauto.\n    destruct H14.\n    subst t.\n    rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n    rewrite TcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n    inverts H13;auto.\n    apply H1 in H8;auto.\n\n    assert (t = x12 \\/ t <> x12 ) by tauto.\n    destruct H15.\n    subst t.\n    rewrite TcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n    inverts H13;auto.\n\n    rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n    rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n    apply H1 in H13.\n    auto.\n\n    (*op_p_prop*)\n    unfold op_p_prop in *.\n    intros.\n    assert (t= ct \\/ t <> ct) by tauto.\n    destruct H15.\n    subst.\n    rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n    rewrite TcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n    inverts H13.\n    unfolds in H14.\n\n    assert ( TcbMod.get\n          (TcbMod.set (TcbMod.set tls ct (p, st, m)) x12 (x7, rdy, Vptr x))\n          ct <> None ).\n    rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n    auto.\n    apply H14 in H13.\n    destruct H13.\n    mytac.\n    assert (x0 <> x).\n    intro.\n    subst x0.\n    unfolds in H13.\n    mytac.\n    rewrite EcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n    inverts H13;tryfalse.\n    unfolds in H13.\n    rewrite EcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n    mytac.\n\n    unfolds in Hnnp.\n    assert (TcbMod.get tls ct <> None).\n    intro.\n    rewrite H16 in H8;tryfalse.\n    apply Hnnp with (qid:=x) in H16.\n    destruct H16.\n    destruct H17.\n    exists x0.\n    split;auto.\n    unfolds;do 3 eexists;eauto.\n    unfolds;do 3 eexists;eauto.\n    destruct H13.\n    rewrite TcbMod.set_a_get_a' in H15;[ | apply tidspec.neq_beq_false;auto].\n    rewrite TcbMod.set_a_get_a in H15;[ | apply tidspec.eq_beq_true;auto]. \n    mytac.\n    inverts H15.\n    right.\n    clear.\n    int auto.\n\n    (*-------------------*)\n    assert (t <> x12 \\/ t = x12) by tauto.\n    destruct H16.\n    rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n    rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n    eapply H2;eauto.\n\n    unfolds.\n    intro.\n    unfolds in H14.\n    assert (TcbMod.get\n          (TcbMod.set (TcbMod.set tls ct (x8, x9, x10)) x12 (x7, rdy, Vptr x))\n          t <> None).\n    rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    auto.\n    apply H14 in H18.\n    destruct H18.\n    mytac.\n    left.\n    exists x0.\n    assert (x0 <> x).\n    intro.\n    subst x0.\n    unfolds in H18.\n    rewrite EcbMod.set_a_get_a in H18;[ | apply tidspec.eq_beq_true;auto].\n    mytac.\n    inverts H18;tryfalse.\n    unfolds in H18.\n    mytac.\n    rewrite EcbMod.set_a_get_a' in H18;[ | apply tidspec.neq_beq_false;auto].\n    unfolds.\n    do 2 eexists;eauto.\n    right.\n    rewrite TcbMod.set_a_get_a' in H18;[ | apply tidspec.neq_beq_false;auto].\n    rewrite TcbMod.set_a_get_a' in H18;[ | apply tidspec.neq_beq_false;auto].\n    mytac.\n    intro.\n    destruct H18.\n    mytac.\n    exists x2.\n    unfolds in H18.\n    mytac.\n    unfolds.\n    assert (x <> x2).\n    intro.\n    subst x2.\n    rewrite H18 in H5;inverts H5.\n    tryfalse.\n    rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    do 3 eexists;eauto.\n    do 2 eexists;eauto.\n\n    (*--------------------------*)\n    subst t.\n    rewrite TcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n    inverts H13.\n    unfolds in H14.\n    assert (TcbMod.get\n          (TcbMod.set (TcbMod.set tls ct (x8, x9, x10)) x12 (p, rdy, Vptr x))\n          x12 <> None ).\n    rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n    auto.\n    apply H14 in H13.\n    destruct H13.\n    mytac.\n    assert (x <> x0 \\/ x = x0) by tauto.\n    destruct H16.\n    unfolds in Hnnp''.\n    assert (TcbMod.get\n             (TcbMod.set (TcbMod.set tls ct (x8, x9, x10)) x12\n                (p, rdy, Vptr x)) x12 <> None).\n    intro.\n    rewrite TcbMod.set_a_get_a in H17;[ | apply tidspec.eq_beq_true;auto].\n    tryfalse.\n    apply Hnnp'' with (qid:=x) in H17.\n    mytac.\n    destruct H18.\n    exists x0.\n    split;auto.\n    unfolds in H13.\n    mytac.\n    unfolds.\n    do 3 eexists;eauto.\n    unfolds.\n    rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n    do 3 eexists;eauto.\n    subst x0.\n    unfolds in H13.\n    mytac.\n    rewrite EcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n    inverts H13.\n    right;clear;int auto.\n\n    destruct H13.\n    destruct H13.\n    exists x.\n    unfolds.\n    rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n    do 3 eexists;eauto.\n\n    (*wait_prop*)\n    unfold wait_prop in *.\n    intros.\n    assert (t = ct \\/ t <> ct ) by tauto.\n    destruct H14.\n    subst.\n    rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n    rewrite TcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n    inverts H13.\n    unfolds in Hnnp.\n    assert ( TcbMod.get tls ct <> None ).\n    intro.\n    rewrite H13 in H8;tryfalse.\n    apply Hnnp with (qid:=x) in H13.\n    mytac.\n    destruct H13.\n    mytac.\n    apply H10 in H8.\n    unfolds.\n    unfolds in H8.\n    mytac.\n    do 4 eexists;split;eauto.\n    unfolds;do 3 eexists;eauto.\n\n    (*---------------*)\n   \n    assert (t <> x12 \\/ t = x12) by tauto.\n    destruct H15.\n    rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n    rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n    lets Hx:H3 H13.\n    mytac.\n    \n    assert (x0 = ct \\/ x0 <> ct) by tauto.\n    destruct H20.\n    subst x0.\n    lets Hy:H10 H13.\n    unfolds in Hy.\n    mytac.\n    unfolds in H16.\n    mytac.\n    assert (eid = x \\/ eid <> x) by tauto.\n    destruct H22.\n    subst x.\n    rewrite H20 in H5.\n    inverts H5.\n    rewrite H20 in H16;inverts H16.\n    rewrite H17 in H8.\n    inverts H8.\n    exists x12 x7 (Vptr eid).\n    mytac.\n    unfolds.\n    rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n    do 3 eexists;eauto.\n    rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n    auto.\n    unfolds in H7.\n    lets Hx: H10 H13.\n    unfolds in Hx.\n    mytac.\n    rewrite H5 in H20;inverts H20.\n    eapply H22 with (t':=t) in H8;eauto.\n    unfold get in *;simpl in *.\n    rewrite H16 in H9;inverts H9.\n    mytac.\n    rewrite H8 in H13;inverts H13;auto.\n    \n    intros.\n\n    unfolds in H5.\n    apply H19.\n    unfolds.\n    intro.\n    rewrite TcbMod.set_a_get_a' in H5;[ | apply tidspec.neq_beq_false;auto].\n    rewrite TcbMod.set_a_get_a' in H5;[ | apply tidspec.neq_beq_false;auto].\n    apply H5 in H8.\n    destruct H8.\n    left.\n    mytac.\n    unfolds in H8.\n    mytac.\n    assert (eid <> x).\n    intro.\n    subst eid.\n    rewrite EcbMod.set_a_get_a in H8;[ | apply tidspec.eq_beq_true;auto].\n    inverts H8.\n    tryfalse.\n    rewrite EcbMod.set_a_get_a' in H8;[ | apply tidspec.neq_beq_false;auto].\n    exists x;unfolds.\n    do 2 eexists;eauto.\n\n    right.\n    mytac.\n    intro.\n    destruct H8.\n    mytac.\n    exists x1.\n    unfolds.\n    assert (x1 <> eid).\n    intro.\n    subst x1.\n    unfolds in H8.\n    mytac.\n    rewrite H8 in H20;inverts H20.\n    tryfalse.\n    rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    unfolds in H8;mytac.\n    do 3 eexists;eauto.\n    do 2 eexists;eauto.\n\n    rewrite H16 in H20;inverts H20.\n    unfolds in Hnnp.\n    assert (TcbMod.get tls ct <> None).\n    intro.\n    rewrite H20 in H8;tryfalse.\n    apply Hnnp with (qid:=eid) in H20.\n    destruct H20.\n    destruct H23.\n    exists x;split;auto.\n    unfolds;do 3 eexists;eauto.\n    unfolds;do 3 eexists;eauto.\n\n    (*-----------------*)\n\n    exists x0.\n    assert (x0 <> x12).\n    intro.\n    subst x0.\n    unfolds in Hnnp.\n    assert (TcbMod.get tls x12  <> None).\n    intro.\n    rewrite H21 in H17;tryfalse.\n    apply Hnnp with (qid:=eid) in H21.\n    destruct H21.\n    destruct H21.\n    unfolds.\n    exists x.\n    do 3 eexists;split;eauto.\n    unfolds in H7;mytac;auto.\n    auto.\n    \n    rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    do 2 eexists;splits;eauto.\n    unfolds in H16;unfolds.\n    mytac.\n    assert (x <> eid).\n    intro.\n    subst x.\n    rewrite H16 in H5;inverts H5;tryfalse.\n    rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    do 3 eexists;eauto.\n\n    intros.\n    unfolds in H22.\n    assert (x0 <> x12).\n    intro.\n    subst x0.\n    unfolds in Hnnp.\n    assert (TcbMod.get tls x12 <> None).\n    intro.\n    rewrite H17 in H23;tryfalse.\n    apply Hnnp with (qid:=eid) in H23.\n    destruct H23.\n    destruct H23.\n    unfolds.\n    do 4 eexists;split;eauto.\n    unfolds in H7;mytac;auto.\n    auto.\n    apply H19.\n    unfolds.\n    intro.\n    rewrite TcbMod.set_a_get_a' in H22;[ | apply tidspec.neq_beq_false;auto].\n    rewrite TcbMod.set_a_get_a' in H22;[ | apply tidspec.neq_beq_false;auto].\n    apply H22 in H24.\n    destruct H24.\n    left.\n    mytac.\n    unfolds in H24.\n    mytac.\n    assert (x3 <> x).\n    intro.\n    subst x3.\n    rewrite EcbMod.set_a_get_a in H24;[ | apply tidspec.eq_beq_true;auto].\n    inverts H24.\n    tryfalse.\n    rewrite EcbMod.set_a_get_a' in H24;[ | apply tidspec.neq_beq_false;auto].\n    exists x3;unfolds.\n    do 2 eexists;eauto.\n\n    right.\n    mytac.\n    intro.\n    destruct H24.\n    mytac.\n    exists x5.\n    unfolds.\n    assert (x5 <> x).\n    intro.\n    subst x.\n    unfolds in H24.\n    mytac.\n    rewrite H24 in H5;inverts H5.\n    tryfalse.\n    rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    unfolds in H24;mytac.\n    do 3 eexists;eauto.\n    do 2 eexists;eauto.\n    \n    (*------------------------*)\n    subst t.\n    rewrite TcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n    inverts H13.\n\n\n    (*no_owner_prio_prop*)\n    unfold no_owner_prio_prop in *.\n    intros.\n    assert (t = ct \\/ t <> ct ) by tauto.\n    destruct H16.\n    subst.\n    rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n    rewrite TcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n    inverts H13.\n    unfolds in H15.\n    assert ( TcbMod.get\n          (TcbMod.set (TcbMod.set tls ct (p, st, m)) x12 (x7, rdy, Vptr x))\n          ct <> None).\n    rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n    auto.\n    apply H15 in H13.\n\n    destruct H13.\n    mytac.\n    assert (x0 <> x).\n    intro.\n    subst x0.\n    unfolds in H13.\n    mytac.\n    rewrite EcbMod.set_a_get_a in H13;[ | apply tidspec.eq_beq_true;auto].\n    inverts H13.\n    tryfalse.\n    unfolds in H13.\n    rewrite EcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n    mytac.\n\n    unfolds in Hnnp.\n    assert (TcbMod.get tls ct <> None).\n    intro.\n    rewrite H17 in H8;tryfalse.\n    apply Hnnp with (qid:=x) in H17.\n    destruct H17.\n    destruct H18.\n    exists x0.\n    split;auto.\n    unfolds;do 3 eexists;eauto.\n    unfolds;do 3 eexists;eauto.\n    \n    destruct H13.\n    rewrite TcbMod.set_a_get_a' in H16;[ | apply tidspec.neq_beq_false;auto].\n    rewrite TcbMod.set_a_get_a in H16;[ | apply tidspec.eq_beq_true;auto]. \n    mytac.\n    inverts H16.\n    auto.\n\n    (*---------------*)\n    assert (t = x12 \\/ t <> x12) by tauto.\n    destruct H17.\n    subst t.\n    destruct H14.\n    exists x.\n    unfolds.\n    rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n    do 3 eexists;eauto.\n\n    \n    rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n    rewrite TcbMod.set_a_get_a' in H13;[ | apply tidspec.neq_beq_false;auto].\n    eapply H4;eauto.\n    intro.\n    destruct H14.\n    mytac.\n    exists x0.\n    assert (x0 <> x).\n    intro.\n    subst x0.\n    unfolds in H14.\n    mytac.\n    rewrite H14 in H5;inverts H5.\n    tryfalse.\n    unfolds in H14.\n    unfolds.\n    rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto]. \n    mytac.\n    do 3 eexists;eauto.\n\n    unfolds.\n    unfolds in H15.\n    intros.\n\n    rewrite TcbMod.set_a_get_a' in H15;[ | apply tidspec.neq_beq_false;auto].\n    rewrite TcbMod.set_a_get_a' in H15;[ | apply tidspec.neq_beq_false;auto].\n    apply H15 in H18.\n    destruct H18.\n    left.\n    mytac.\n    unfolds in H18.\n    mytac.\n    assert (x0 <> x).\n    intro.\n    subst x0.\n    rewrite EcbMod.set_a_get_a in H18;[ | apply tidspec.eq_beq_true;auto].\n    inverts H18.\n    tryfalse.\n    rewrite EcbMod.set_a_get_a' in H18;[ | apply tidspec.neq_beq_false;auto].\n    exists x0;unfolds.\n    do 2 eexists;eauto.\n\n    right.\n    mytac.\n    intro.\n    destruct H18.\n    mytac.\n    exists x2.\n    unfolds.\n    assert (x2 <> x).\n    intro.\n    subst x.\n    unfolds in H18.\n    mytac.\n    rewrite H18 in H5;inverts H5.\n    tryfalse.\n    rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    unfolds in H18;mytac.\n    do 3 eexists;eauto.\n    do 2 eexists;eauto.\n\n  destruct H2.\n  mytac.\n  (* post exwt no return *)\n    clear -H0 H1 H5 H8 H9 Hnnp'.\n    rename H5 into H6.\n    rename H9 into H12.\n    rename H8 into Hfff.\n    inverts H6.\n    mytac.\n    assert (get O' curtid = Some (oscurt x5)) as Hct.\n    eapply join_get_get_l;eauto.\n    assert (get O' absecblsid = Some (absecblist x0)) as Hels.\n    eapply join_get_get_l;eauto.\n    assert (get O' abtcblsid = Some (abstcblist x2)) as Htls.\n    eapply join_get_get_l;eauto.\n\n    assert (O'' =  (set (set O' abtcblsid (abstcblist (set x2 x13 (x7, rdy, Vptr x))))\n             absecblsid\n             (absecblist\n                (set x0 x\n                   (absmutexsem x6 (Some (x13, x7)), remove_tid x13 x12))))).\n    eapply join_get_set_eq_2;eauto.\n    subst O''.\n    clear H2 H3 H4.\n    \n    remember O' as Ox.\n    clear HeqOx.\n    rename x5 into ct.\n    rename x0 into els.\n    rename x2 into tls.\n    unfold GOOD_ST in *.\n    intros.\n    unfolds in Hnnp'.\n    unfold get in *;simpl in *.\n    lets Hnnp'': Hnnp' H H2.\n    clear Hnnp'.\n    unfolds in H0.\n    lets Hnnp: H0 Hels Htls.\n    clear H0.\n    rewrite OSAbstMod.map_get_set in H.\n    inverts H.\n    rewrite abst_set_get_neq in H2;auto.\n    rewrite OSAbstMod.map_get_set in H2.\n    inverts H2.\n    lets Hgoodst: H1 Hels Htls.\n    clear H1.\n    destructs Hgoodst.\n    assert (ct <> x13) as Hneq.\n    intro.\n    subst x13.\n    unfolds in Hnnp.\n    assert (TcbMod.get tls ct <> None).\n    intro.\n    rewrite H11 in H9;tryfalse.\n    apply Hnnp with (qid:=x) in H11.\n    mytac.\n    destruct H11.\n    unfolds.\n    do 4 eexists;split;eauto.\n    unfolds in H7.\n    mytac;auto.\n    unfolds.\n    do 3 eexists;eauto.\n    \n    (*rdy_notin_wl*)\n    unfold rdy_notin_wl in *.\n    mytac.\n    intros.\n    assert (t = ct \\/ t <> ct) by tauto.\n    destruct H15.\n    subst t.\n    rewrite TcbMod.set_a_get_a' in H14;[ | apply tidspec.neq_beq_false;auto].\n    apply H in H14.\n    intro.\n    destruct H14.\n    eapply post_iswait;eauto.\n    assert (t = x13 \\/ t <> x13) by tauto.\n    destruct H16.\n    subst x13.\n    rewrite TcbMod.set_a_get_a in H14;[ | apply tidspec.eq_beq_true;auto].\n    inverts H14.\n\n    eapply nnp_remove_nwait;eauto.\n    unfolds;splits;eauto.\n    rewrite TcbMod.set_a_get_a' in H14;[ | apply tidspec.neq_beq_false;auto].\n    apply H in H14.\n    intro.\n    destruct H14.\n    eapply remove_is_wait_neq;eauto.\n    (*--------------------*)\n    intros.\n    assert (t = ct \\/ t <> ct) by tauto.\n    destruct H15.\n    subst t.\n    rewrite TcbMod.set_a_get_a' in H14;[ | apply tidspec.neq_beq_false;auto].\n    lets Hx:H11 H14.\n    unfolds in Hnnp.\n    assert (TcbMod.get tls ct <> None).\n    intro.\n    rewrite H15 in H14;tryfalse.\n    apply Hnnp with(qid:=x)in H15.\n    destruct H15.\n    destruct H15.\n    unfolds in Hx;mytac;unfolds;do 4 eexists;eauto.\n    unfolds;do 3 eexists;eauto.\n\n    assert (t <> x13).\n    intro.\n    subst x13.\n    rewrite TcbMod.set_a_get_a in H14;[ | apply tidspec.eq_beq_true;auto].\n    inverts H14.\n    rewrite TcbMod.set_a_get_a' in H14;[ | apply tidspec.neq_beq_false;auto].\n    apply H11 in H14.\n    eapply post_iswait' in H16;eauto.\n    destruct H16;eauto.\n    (*----------------*)\n    intros.\n    assert (t = ct \\/ t <> ct) by tauto.\n    destruct H15.\n    subst t.\n    assert (IS_WAITING_E ct eid els).\n    eapply post_iswait';eauto.\n    unfolds in Hnnp.\n    assert (TcbMod.get tls ct <> None).\n    intro.\n    rewrite H16 in H9;tryfalse.\n    apply Hnnp with(qid:=x)in H16.\n    destruct H16.\n    destruct H16.\n    unfolds in H15;mytac;unfolds;do 4 eexists;eauto.\n    unfolds;do 3 eexists;eauto.\n\n    assert (t = x13 \\/ t <> x13) by tauto.\n    destruct H16.\n    subst t.\n    lets Hx: nnp_remove_nwait Hnnp H7 H5 H10.\n    unfolds;split;auto.\n    destruct Hx.\n    unfolds in H14;mytac.\n    unfolds;do 4 eexists;split;eauto.\n    rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    eapply H13;eauto.\n    eapply post_iswait';eauto.\n\n    (*owner_prio_prop*)\n    unfold owner_prio_prop in *.\n    intros.\n\n    assert (t = ct \\/ t <> ct ) by tauto.\n    destruct H16.\n    subst t.\n    \n    assert (eid <> x).\n    intro.\n    subst x.\n    rewrite EcbMod.set_a_get_a in H15;[ | apply tidspec.eq_beq_true;auto].\n    inverts H15;tryfalse.\n\n    unfolds in Hnnp.\n    rewrite EcbMod.set_a_get_a' in H15;[ | apply tidspec.neq_beq_false;auto].\n    assert (TcbMod.get tls ct <> None).\n    intro.\n    rewrite H17 in H9;tryfalse.\n    apply Hnnp with (qid:=eid) in H17.\n    destruct H17.\n    destruct H18.\n    exists x.\n    split;auto.\n    unfolds;do 3 eexists;eauto.\n    unfolds;do 3 eexists;eauto.\n\n    (*--------------*)\n    assert (t <> x13 \\/ t = x13) by tauto.\n    destruct H17.\n    rewrite TcbMod.set_a_get_a' in H14;[ | apply tidspec.neq_beq_false;auto].\n    eapply H0;eauto.\n    assert (eid <> x).\n    intro.\n    subst x.\n    rewrite EcbMod.set_a_get_a in H15;[ | apply tidspec.eq_beq_true;auto].\n    inverts H15;tryfalse.\n    rewrite EcbMod.set_a_get_a' in H15;[ | apply tidspec.neq_beq_false;auto].\n    eauto.\n\n    subst x13.\n    rewrite TcbMod.set_a_get_a in H14;[ | apply tidspec.eq_beq_true;auto].\n    inverts H14.\n\n    assert (eid = x \\/ eid <> x ) by tauto.\n    destruct H14.\n    subst x.\n    rewrite  EcbMod.set_a_get_a in H15;[ | apply tidspec.eq_beq_true;auto].\n    inverts H15.\n    split;auto.\n    unfolds in H3.\n    assert (IS_WAITING_E t eid els).\n    unfolds.\n    do 3 eexists;split;eauto.\n    unfolds in H7;mytac;auto.\n    apply H13 in H14.\n    mytac.\n    rewrite H14 in H10;inverts H10.\n    apply H3 in H14.\n    mytac.\n    unfolds in H10.\n    mytac.\n    rewrite H10 in H5;inverts H5.\n    rewrite H14 in H9;inverts H9.\n    auto.\n\n    lets Hx:H0 H14 H10.\n    destruct Hx.\n    destruct H5;subst.\n    auto.\n    clear -H9 H15.\n    int auto.\n    \n    rewrite EcbMod.set_a_get_a' in H15;[ | apply tidspec.neq_beq_false;auto].\n    eauto.\n\n    (*task_stat_prop*)\n    unfolds.\n    intros.\n    assert (t = ct \\/ t <> ct ) by tauto.\n    destruct H15.\n    subst t.\n    rewrite TcbMod.set_a_get_a' in H14;[ | apply tidspec.neq_beq_false;auto].\n    apply H1 in H14;auto.\n\n    assert (t = x13 \\/ t <> x13 ) by tauto.\n    destruct H16.\n    subst t.\n    rewrite TcbMod.set_a_get_a in H14;[ | apply tidspec.eq_beq_true;auto].\n    inverts H14;auto.\n\n    rewrite TcbMod.set_a_get_a' in H14;[ | apply tidspec.neq_beq_false;auto].\n    apply H1 in H14.\n    auto.\n\n    (*op_p_prop*)\n    unfold op_p_prop in *.\n    intros.\n    assert (t= ct \\/ t <> ct) by tauto.\n    destruct H16.\n    subst.\n    rewrite TcbMod.set_a_get_a' in H14;[ | apply tidspec.neq_beq_false;auto].\n    unfolds in H15.\n\n    assert (TcbMod.get (TcbMod.set tls x13 (x7, rdy, Vptr x)) ct <> None ).\n    rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    intro.\n    rewrite H16 in H14;tryfalse.\n    apply H15 in H16.\n    destruct H16.\n    mytac.\n    assert (x0 <> x).\n    intro.\n    subst x0.\n    unfolds in H16.\n    mytac.\n    rewrite EcbMod.set_a_get_a in H16;[ | apply tidspec.eq_beq_true;auto].\n    inverts H16;tryfalse.\n    unfolds in H16.\n    rewrite EcbMod.set_a_get_a' in H16;[ | apply tidspec.neq_beq_false;auto].\n    mytac.\n\n    unfolds in Hnnp.\n    assert (TcbMod.get tls ct <> None).\n    intro.\n    rewrite H18 in H14;tryfalse.\n    apply Hnnp with (qid:=x) in H18.\n    destruct H18.\n    destruct H19.\n    exists x0.\n    split;auto.\n    unfolds;do 3 eexists;eauto.\n    unfolds;do 3 eexists;eauto.\n    destruct H16.\n    rewrite TcbMod.set_a_get_a' in H17;[ | apply tidspec.neq_beq_false;auto].\n\n    mytac.\n    rewrite H14 in H17;inverts H17.\n    right.\n    clear.\n    int auto.\n\n    (*-------------------*)\n    assert (t <> x13 \\/ t = x13) by tauto.\n    destruct H17.\n    rewrite TcbMod.set_a_get_a' in H14;[ | apply tidspec.neq_beq_false;auto].\n    eapply H2;eauto.\n\n    unfolds.\n    intro.\n    unfolds in H15.\n    assert ( TcbMod.get (TcbMod.set tls x13 (x7, rdy, Vptr x)) t <> None ).\n    rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    auto.\n    apply H15 in H19.\n    destruct H19.\n    mytac.\n    left.\n    exists x0.\n    assert (x0 <> x).\n    intro.\n    subst x0.\n    unfolds in H19.\n    rewrite EcbMod.set_a_get_a in H19;[ | apply tidspec.eq_beq_true;auto].\n    mytac.\n    inverts H19;tryfalse.\n    unfolds in H19.\n    mytac.\n    rewrite EcbMod.set_a_get_a' in H19;[ | apply tidspec.neq_beq_false;auto].\n    unfolds.\n    do 2 eexists;eauto.\n    right.\n    rewrite TcbMod.set_a_get_a' in H19;[ | apply tidspec.neq_beq_false;auto].\n    mytac.\n    intro.\n    destruct H19.\n    mytac.\n    exists x2.\n    unfolds in H19.\n    mytac.\n    unfolds.\n    assert (x <> x2).\n    intro.\n    subst x2.\n    rewrite H19 in H5;inverts H5.\n    tryfalse.\n    rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    do 3 eexists;eauto.\n    do 2 eexists;eauto.\n\n    (*--------------------------*)\n    subst t.\n    rewrite TcbMod.set_a_get_a in H14;[ | apply tidspec.eq_beq_true;auto].\n    inverts H14.\n    unfolds in H15.\n    assert (TcbMod.get (TcbMod.set tls x13 (p, rdy, Vptr x)) x13 <> None ).\n    rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n    auto.\n    apply H15 in H14.\n    destruct H14.\n    mytac.\n    assert (x <> x0 \\/ x = x0) by tauto.\n    destruct H17.\n    unfolds in Hnnp''.\n    assert (TcbMod.get (TcbMod.set tls x13 (p, rdy, Vptr x)) x13 <> None).\n    intro.\n    rewrite TcbMod.set_a_get_a in H18;[ | apply tidspec.eq_beq_true;auto].\n    tryfalse.\n    apply Hnnp'' with (qid:=x) in H18.\n    mytac.\n    destruct H19.\n    exists x0.\n    split;auto.\n    unfolds in H14.\n    mytac.\n    unfolds.\n    do 3 eexists;eauto.\n    unfolds.\n    rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n    do 3 eexists;eauto.\n    subst x0.\n    unfolds in H14.\n    mytac.\n    rewrite EcbMod.set_a_get_a in H14;[ | apply tidspec.eq_beq_true;auto].\n    inverts H14.\n    right;clear;int auto.\n\n    destruct H14.\n    destruct H14.\n    exists x.\n    unfolds.\n    rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n    do 3 eexists;eauto.\n\n    (*wait_prop*)\n    unfold wait_prop in *.\n    intros.\n    assert (t = ct \\/ t <> ct ) by tauto.\n    destruct H15.\n    subst.\n    rewrite TcbMod.set_a_get_a' in H14;[ | apply tidspec.neq_beq_false;auto].\n    unfolds in Hnnp.\n    assert ( TcbMod.get tls ct <> None ).\n    intro.\n    rewrite H15 in H9;tryfalse.\n    apply Hnnp with (qid:=x) in H15.\n    mytac.\n    destruct H15.\n    mytac.\n    apply H11 in H14.\n    unfolds.\n    unfolds in H14.\n    mytac.\n    do 4 eexists;split;eauto.\n    unfolds;do 3 eexists;eauto.\n\n    (*---------------*)\n    assert (t <> x13 \\/ t = x13) by tauto.\n    destruct H16.\n    rewrite TcbMod.set_a_get_a' in H14;[ | apply tidspec.neq_beq_false;auto].\n    lets Hx:H3 H14.\n    mytac.\n    \n    assert (x0 = ct \\/ x0 <> ct) by tauto.\n    destruct H21.\n    subst x0.\n    lets Hy:H11 H14.\n    unfolds in Hy.\n    mytac.\n    unfolds in H17.\n    mytac.\n    assert (eid = x \\/ eid <> x) by tauto.\n    destruct H23.\n    subst x.\n    rewrite H21 in H5.\n    inverts H5.\n    rewrite H21 in H17;inverts H17.\n    rewrite H18 in H9.\n    inverts H9.\n    exists x13 x7 (Vptr eid).\n    mytac.\n    unfolds.\n    rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n    do 3 eexists;eauto.\n    rewrite TcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n    auto.\n    unfolds in H7.\n    lets Hx: H11 H14.\n    unfolds in Hx.\n    mytac.\n    rewrite H5 in H21;inverts H21.\n    eapply H23 with (t':=t) in H9;eauto.\n    unfold get in *;simpl in *.\n    rewrite H17 in H10;inverts H10.\n    mytac.\n    rewrite H9 in H14;inverts H14;auto.\n    \n    intros.\n    unfolds in H5.\n    apply H20.\n    unfolds.\n    intro.\n    rewrite TcbMod.set_a_get_a' in H5;[ | apply tidspec.neq_beq_false;auto].\n    apply H5 in H9.\n    destruct H9.\n    left.\n    mytac.\n    unfolds in H9.\n    mytac.\n    assert (eid <> x).\n    intro.\n    subst eid.\n    rewrite EcbMod.set_a_get_a in H9;[ | apply tidspec.eq_beq_true;auto].\n    inverts H9.\n    tryfalse.\n    rewrite EcbMod.set_a_get_a' in H9;[ | apply tidspec.neq_beq_false;auto].\n    exists x;unfolds.\n    do 2 eexists;eauto.\n\n    right.\n    mytac.\n    intro.\n    destruct H9.\n    mytac.\n    exists x1.\n    unfolds.\n    assert (x1 <> eid).\n    intro.\n    subst x1.\n    unfolds in H9.\n    mytac.\n    rewrite H9 in H21;inverts H21.\n    tryfalse.\n    rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    unfolds in H9;mytac.\n    do 3 eexists;eauto.\n    do 2 eexists;eauto.\n\n    rewrite H17 in H21;inverts H21.\n    unfolds in Hnnp.\n    assert (TcbMod.get tls ct <> None).\n    intro.\n    rewrite H21 in H9;tryfalse.\n    apply Hnnp with (qid:=eid) in H21.\n    destruct H21.\n    destruct H24.\n    exists x;split;auto.\n    unfolds;do 3 eexists;eauto.\n    unfolds;do 3 eexists;eauto.\n\n    (*-----------------*)\n\n    exists x0.\n    assert (x0 <> x13).\n    intro.\n    subst x0.\n    unfolds in Hnnp.\n    assert (TcbMod.get tls x13  <> None).\n    intro.\n    rewrite H22 in H18;tryfalse.\n    apply Hnnp with (qid:=eid) in H22.\n    destruct H22.\n    destruct H22.\n    unfolds.\n    exists x.\n    do 3 eexists;split;eauto.\n    unfolds in H7;mytac;auto.\n    auto.\n    \n    rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    do 2 eexists;splits;eauto.\n    unfolds in H17;unfolds.\n    mytac.\n    assert (x <> eid).\n    intro.\n    subst x.\n    rewrite H17 in H5;inverts H5;tryfalse.\n    rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    do 3 eexists;eauto.\n\n    intros.\n    unfolds in H23.\n    assert (x0 <> x13).\n    intro.\n    subst x0.\n    unfolds in Hnnp.\n    assert (TcbMod.get tls x13 <> None).\n    intro.\n    rewrite H18 in H24;tryfalse.\n    apply Hnnp with (qid:=eid) in H24.\n    destruct H24.\n    destruct H24.\n    unfolds.\n    do 4 eexists;split;eauto.\n    unfolds in H7;mytac;auto.\n    auto.\n    apply H20.\n    unfolds.\n    intro.\n    rewrite TcbMod.set_a_get_a' in H23;[ | apply tidspec.neq_beq_false;auto].\n    apply H23 in H25.\n    destruct H25.\n    left.\n    mytac.\n    unfolds in H25.\n    mytac.\n    assert (x3 <> x).\n    intro.\n    subst x3.\n    rewrite EcbMod.set_a_get_a in H25;[ | apply tidspec.eq_beq_true;auto].\n    inverts H25.\n    tryfalse.\n    rewrite EcbMod.set_a_get_a' in H25;[ | apply tidspec.neq_beq_false;auto].\n    exists x3;unfolds.\n    do 2 eexists;eauto.\n\n    right.\n    mytac.\n    intro.\n    destruct H25.\n    mytac.\n    exists x5.\n    unfolds.\n    assert (x5 <> x).\n    intro.\n    subst x.\n    unfolds in H25.\n    mytac.\n    rewrite H25 in H5;inverts H5.\n    tryfalse.\n    rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    unfolds in H25;mytac.\n    do 3 eexists;eauto.\n    do 2 eexists;eauto.\n    \n    (*------------------------*)\n    subst t.\n    rewrite TcbMod.set_a_get_a in H14;[ | apply tidspec.eq_beq_true;auto].\n    inverts H14.\n\n\n    (*no_owner_prio_prop*)\n    unfold no_owner_prio_prop in *.\n    intros.\n    assert (t = ct \\/ t <> ct ) by tauto.\n    destruct H17.\n    subst.\n    rewrite TcbMod.set_a_get_a' in H14;[ | apply tidspec.neq_beq_false;auto].\n    unfolds in H16.\n    assert ( TcbMod.get (TcbMod.set tls x13 (x7, rdy, Vptr x)) ct <> None).\n    rewrite TcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    intro.\n    rewrite H17 in H14;tryfalse.\n\n    apply H16 in H17.\n    destruct H17.\n    mytac.\n    assert (x0 <> x).\n    intro.\n    subst x0.\n    unfolds in H17.\n    mytac.\n    rewrite EcbMod.set_a_get_a in H17;[ | apply tidspec.eq_beq_true;auto].\n    inverts H17.\n    tryfalse.\n    unfolds in H17.\n    rewrite EcbMod.set_a_get_a' in H17;[ | apply tidspec.neq_beq_false;auto].\n    mytac.\n\n    unfolds in Hnnp.\n    assert (TcbMod.get tls ct <> None).\n    intro.\n    rewrite H19 in H9;tryfalse.\n    apply Hnnp with (qid:=x) in H19.\n    destruct H19.\n    destruct H20.\n    exists x0.\n    split;auto.\n    unfolds;do 3 eexists;eauto.\n    unfolds;do 3 eexists;eauto.\n    \n    destruct H17.\n    rewrite TcbMod.set_a_get_a' in H18;[ | apply tidspec.neq_beq_false;auto].\n    mytac.\n    rewrite H18 in H14.\n    inverts H14.\n    auto.\n\n    (*---------------*)\n    assert (t = x13 \\/ t <> x13) by tauto.\n    destruct H18.\n    subst t.\n    destruct H15.\n    exists x.\n    unfolds.\n    rewrite EcbMod.set_a_get_a;[ | apply tidspec.eq_beq_true;auto].\n    do 3 eexists;eauto.\n\n    \n    rewrite TcbMod.set_a_get_a' in H14;[ | apply tidspec.neq_beq_false;auto].\n    eapply H4;eauto.\n    intro.\n    destruct H15.\n    mytac.\n    exists x0.\n    assert (x0 <> x).\n    intro.\n    subst x0.\n    unfolds in H15.\n    mytac.\n    rewrite H15 in H5;inverts H5.\n    tryfalse.\n    unfolds in H15.\n    unfolds.\n    rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto]. \n    mytac.\n    do 3 eexists;eauto.\n\n    unfolds.\n    unfolds in H16.\n    intros.\n\n    rewrite TcbMod.set_a_get_a' in H16;[ | apply tidspec.neq_beq_false;auto].\n    apply H16 in H19.\n    destruct H19.\n    left.\n    mytac.\n    unfolds in H19.\n    mytac.\n    assert (x0 <> x).\n    intro.\n    subst x0.\n    rewrite EcbMod.set_a_get_a in H19;[ | apply tidspec.eq_beq_true;auto].\n    inverts H19.\n    tryfalse.\n    rewrite EcbMod.set_a_get_a' in H19;[ | apply tidspec.neq_beq_false;auto].\n    exists x0;unfolds.\n    do 2 eexists;eauto.\n\n    right.\n    mytac.\n    intro.\n    destruct H19.\n    mytac.\n    exists x2.\n    unfolds.\n    assert (x2 <> x).\n    intro.\n    subst x.\n    unfolds in H19.\n    mytac.\n    rewrite H19 in H5;inverts H5.\n    tryfalse.\n    rewrite EcbMod.set_a_get_a';[ | apply tidspec.neq_beq_false;auto].\n    unfolds in H19;mytac.\n    do 3 eexists;eauto.\n    do 2 eexists;eauto.\n\n\n  destruct H2.\n  mytac.\n  (*------timetick---------*)\n    clear -H0 H1 H5 H8 H9 Hnnp'.\n    rename H5 into H6.\n    rename H9 into H12.\n    rename H8 into Hfff.\n    inverts H6.\n    mytac.\n    assert (get O' absecblsid = Some (absecblist x0)) as Hels.\n    eapply join_get_get_l;eauto.\n    assert (get O' abtcblsid = Some (abstcblist x)) as Htls.\n    eapply join_get_get_l;eauto.\n    assert (get O' ostmid = Some (ostm x1)) as Htm.\n    eapply join_get_get_l;eauto.\n\n    assert (O'' =  (set\n                      (set (set O' absecblsid (absecblist x3)) abtcblsid\n                           (abstcblist x2)) ostmid (ostm (x1 +ᵢ  Int.one)))).\n    eapply join_get_set_eq_3;eauto.\n    subst O''.\n    clear H2 H3 H.\n    remember O' as Ox.\n    clear HeqOx.\n    rename x0 into els.\n    rename x into tls.\n    unfold GOOD_ST in *.\n    intros.\n    unfolds in Hnnp'.\n    lets Hnnp'': Hnnp' H H2.\n    clear Hnnp'.\n    unfolds in H0.\n    lets Hnnp: H0 Hels Htls.\n    clear H0.\n    unfold get in *;simpl in *.\n    rewrite abst_set_get_neq in H;auto.\n    rewrite abst_set_get_neq in H;auto.\n    rewrite OSAbstMod.map_get_set in H.\n    inverts H.\n    rewrite abst_set_get_neq in H2;auto.\n    rewrite OSAbstMod.map_get_set in H2.\n    inverts H2.\n\n    lets Hgoodst: H1 Hels Htls.\n    clear H1.\n    unfolds in H6.\n\n    eapply tickstep_goodst;eauto.\n    apply TcbMod.sub_refl.\n  \n  mytac.\n  +\n  inverts H7.\n  auto.\n  +\n  (* Sched *)\n  unfolds.\n  intros.\n  rewrite abst_set_get_neq in H2;auto.\n  rewrite abst_set_get_neq in H7;auto.\n  +\n    unfolds in H.\n    mytac.\n    unfold get in *;simpl in *.\n    rewrite H in H8;inverts H8.\n    repeat progress (destruct H3;[ mytac;rewrite H2 in H5;tryfalse | ]).\n    mytac.\n    rewrite H2 in H5;tryfalse.\n  +\n    unfolds in H.\n    mytac.\n    unfold get in *;simpl in *.\n    rewrite H in H8;inverts H8.\n    repeat progress (destruct H3;[ mytac;rewrite H2 in H5;tryfalse | ]).\n    mytac.\n    rewrite H2 in H5;tryfalse.\n  +\n    unfolds in H.\n    mytac.\n    unfold get in *;simpl in *.\n    rewrite H in H13;inverts H13.\n    repeat progress (destruct H4;[ mytac;rewrite H2 in H3;tryfalse | ]).\n    mytac.\n    rewrite H2 in H3;tryfalse.\nQed.\n\n  \nLemma timetick_weakpif:\n  forall tls tls0 els els0 tlsx ct t p_ct p_t,\n    (rdy_notin_wl tls els /\\\n\n         owner_prio_prop tls els /\\\n         task_stat_prop tls /\\\n         op_p_prop tls els /\\ wait_prop tls els /\\ no_owner_prio_prop tls els) ->\n    TcbMod.sub tlsx tls ->\n    (forall p_ct',\n       GET_OP ct tls els p_ct' ->\n       NO_NEST_PENDING tls els ->\n       HighestRdy tls ct ->\n        ~ (exists eid, IS_OWNER ct eid els) ->\n       forall (t0 : addrval) (p_t0 : int32),\n         t0 <> ct ->\n         TcbMod.get tls t0 <> None ->\n         GET_OP t0 tls els p_t0 ->\n         IS_WAITING t0 els -> Int.ltu p_ct' p_t0 = true) ->\n    t <> ct ->\n    TcbMod.get tls0 t <> None ->\n    GET_OP ct tls0 els0 p_ct ->\n    GET_OP t tls0 els0 p_t ->\n    NO_NEST_PENDING tls els ->\n    NO_NEST_PENDING tls0 els0 ->\n    HighestRdy tls0 ct ->\n    ~ (exists eid, IS_OWNER ct eid els0) ->\n    IS_WAITING t els0 ->\n    tickstep' tls els tls0 els0 tlsx ->\n    Int.ltu p_ct p_t = true.\nProof.\n   introv Hgoodst.\n  intros.\n  induction H10.\n  eapply H0;eauto.\n  assert (TcbMod.get tls t0 = Some (p, st, msg0) ).\n  eapply sub_joinsig_get;eauto.\n  lets Hgoodst': tickchange_goodst H5 H14 Hgoodst H11 H12.\n  eapply IHtickstep';eauto.\n  eapply tcbjoinsig_set_sub_sub;eauto. \n  intros.\n\n  assert (exists pct stct mct,TcbMod.get tls ct = Some (pct,stct,mct)).\n\n  eapply tickchange_exct;eauto.\n  destruct H23 as (pct&stct&mct&H23).\n  destruct Hgoodst as (Hrdyninwl&Hownerpp&Htaskstp&Hoppprop&Hwaitexowner&Hnoownerp).\n  unfolds in Htaskstp.\n  lets Hx:Htaskstp H23.\n  destruct Hx.\n  subst stct.\n  \n  eapply H0;eauto.\n  eapply tickchange_getop_eq with (t0:=t0);eauto.\n  eapply tickchange_highestrdy_rdy with (t0:=t0);eauto.\n  eapply tickchange_no_owner with (t0:=t0);eauto.\n  eapply tickchange_nonone with (t0:=t0);eauto.\n  eapply tickchange_getop_eq with (t0:=t0);eauto.\n  eapply tickchange_iswait with (t0:=t0);eauto.\n\n  destruct H24 as (eid&tm&H24).\n  subst stct.\n  assert ( p_ct' = pct).\n  unfolds in Hnoownerp.\n  eapply Hnoownerp;eauto.\n\n  clear -H5 H23 Hrdyninwl.\n  unfolds in H5.\n  intro.\n  destruct H.\n  lets Hx: H5 H.\n  intro.\n  rewrite H0 in H23;tryfalse.\n  destruct Hx.\n  destruct H0.\n  unfolds in Hrdyninwl.\n  destructs Hrdyninwl.\n  lets Hx: H2 H23.\n  unfolds in Hx.\n  mytac.\n  unfolds.\n  do 4 eexists;eauto.\n  eapply tickchange_getop_eq with (t0:=t0);eauto.\n  subst pct.\n\n  assert (exists p st m, TcbMod.get tls' t1 = Some (p,st,m)).\n  remember (TcbMod.get tls' t1) as X;destruct X;tryfalse.\n  destruct b.\n  destruct p0.\n  do 3 eexists;eauto.\n  destruct Hgoodst' as (Hrdyninwl'&Hownerpp'&Htaskstp'&Hoppprop'&Hwaitexowner'&Hnoownerp').\n  clear IHtickstep'.\n  unfolds in Htaskstp'.\n  mytac.\n  lets Htaskstpx:Htaskstp' H24.\n\n  destruct Htaskstpx.\n  subst x0.\n  unfolds in H17.\n  mytac.\n\n  lets Hx:tickchange_eq_prio ct H11 H14 H23 H12.\n  auto.\n  subst x0.\n  lets Hx:H17 H19 H24.\n  unfolds in Hoppprop'.\n  lets Hy:Hoppprop' H24 H21.\n  clear -Hx Hy.\n  destruct Hy;int auto.\n  \n  mytac;subst.\n  unfolds in Hwaitexowner'.\n  lets Hx:Hwaitexowner' H24.\n  mytac.\n\n  assert (x0 <> ct ).\n  intro.\n  subst x0.\n\n  lets Hx:tickchange_nonest_ct H11 H14 H12 H23 H5.\n  eauto.\n  auto.\n  auto.\n  unfolds in H17.\n  mytac.\n  lets Hx:tickchange_eq_prio ct H11 H14 H23 H17.\n  auto.\n  subst x6.\n  lets Hz: H29 H28 H25.\n  lets Hy:H27 H21.\n  clear -H26 Hz Hy.\n  subst x.\n  int auto.\n\n  eapply tickchange_nonestpend with (t0:=t0);eauto.\nQed.\n\nTheorem no_nest_pif:\n  forall client_code T cst O T' cst' O',\n    NO_NEST_PENDING_O O ->\n    NO_NEST_PENDING_O O' ->\n    (O = O' \\/ (GOOD_API_CODE O T)) ->\n    GOOD_ST O ->\n    WEAK_PIF O ->\n    hpstep (client_code, os_spec') T cst O T' cst' O' ->\n    WEAK_PIF O'.\nProof.\n  introv Hnonesto Hnonesto' Hgoodapicode Hgoodst.\n  intros.\n  unfold os_spec in *.\n  assert (GOOD_ST O') as Hgoodst'.\n  eapply code_exe_prop2;eauto.\n  inversion H0;subst.\n  unfold get in *;simpl in *.\n  -\n    clear H0.\n    rename H3 into Htget.\n    inverts H2.\n    \n    \n      (*task step*)\n        (*client step*)\n        auto.\n\n        (*no cre del api step*)\n        inverts H0;auto.\n        inverts H3;auto.\n        inverts H0;auto.\n        destruct Hgoodapicode.\n        subst O'.\n        assert (O0 =O'0) as Hx.\n        apply join_comm in H6.\n        apply join_comm in H5.\n        eapply join_unique_r;eauto.\n        subst.\n        auto.\n        unfolds in H0.\n        mytac.\n        rewrite H1 in H0;inverts H0.\n        rewrite Htget in H7;inverts H7.\n        destruct H8.\n        mytac.\n\n        (*mutex acc*)\n        clear -H H2 H5 H6 Hgoodst Hnonesto' Hnonesto.\n        rename H2 into H1.\n        rename H5 into Hfff.\n        rename H6 into Hffff.\n        inverts H1.\n        \n        mytac.\n        clear H6;rename H7 into H6.\n        assert (get O curtid = Some (oscurt x8)) as Hct.\n        eapply join_get_get_l;eauto.\n        assert (get O absecblsid = Some (absecblist x0)) as Hels.\n        eapply join_get_get_l;eauto.\n        assert (get O abtcblsid = Some (abstcblist x1)) as Htls.\n        eapply join_get_get_l;eauto.\n\n        assert (O' = (set O absecblsid\n            (absecblist (set x0 x (absmutexsem x3 (Some (x8, x5)), x4))))).\n        eapply join_get_set_eq;eauto.\n        subst O'.\n        remember O as Ox.\n        clear HeqOx.\n        rename x8 into ct.\n        rename x0 into els.\n        rename x1 into tls.\n\n        unfold get in *;simpl in *.\n        unfolds.\n        intros.\n        rewrite OSAbstMod.map_get_set in H0.\n        inverts H0.\n        rewrite abst_set_get_neq in H7;auto.\n        rewrite H7 in Hct;inverts Hct.\n        destruct H11.\n        exists x.\n        unfolds.\n        exists x3 x5 x4.\n        rewrite EcbMod.set_a_get_a.\n        auto.\n        apply tidspec.eq_beq_true;auto.\n        \n       \n        Lemma set_getop_eq:\n          forall ct tls x4 x3 x6 x7 p_ct x0 x1,\n            TcbMod.get tls ct = Some (p_ct, x0, x1) ->\n            EcbMod.get x4 x3 = Some (absmutexsem x6 None, x7) ->\n            GET_OP ct tls (EcbMod.set x4 x3 (absmutexsem x6 (Some (ct, p_ct)), x7)) p_ct ->\n            NO_NEST_PENDING tls\n                            (EcbMod.set x4 x3 (absmutexsem x6 (Some (ct, p_ct)), x7)) ->\n            GET_OP ct tls x4 p_ct.\n        Proof.\n          intros.\n          rename H2 into Hnonest.\n          unfolds in H1.\n          unfolds;intros.\n          apply H1 in H2.\n          clear H1.\n          destruct H2.\n          right.\n          split;eauto.\n          eapply no_nest_pending_set_none;eauto.\n          right;split;eauto.\n          eapply no_nest_pending_set_none;eauto.\n        Qed.\n\n        (*mutex cre*)\n        destruct H0.\n        mytac.\n        unfold mutexcre_succ in H2.\n        mytac.\n        assert (O' = (set O absecblsid (absecblist x5))).\n        eapply join_get_set_eq;eauto.\n        subst O'.\n        remember O as Ox.\n        clear Htget H3 H4 H6.\n        unfold WEAK_PIF in *.\n        intros.\n        rewrite OSAbstMod.map_get_set in H0.\n        inverts H0.\n        rewrite abst_set_get_neq in H2;auto.\n        rewrite abst_set_get_neq in H3;auto.\n        rewrite H1 in H3;inverts H3.\n        lets Hgetop: getop_cre_hold H4 H11.\n        lets Hnonest: no_nest_pending_cre_hold H6 H11.\n        assert (OSAbstMod.get Ox absecblsid = Some (absecblist x4)).\n        subst.\n        eapply join_get_l in H7;eauto.\n        unfolds in H7;simpl in *;auto.\n        rewrite H2 in H7;inverts H7.\n        eapply join_get_l in H8;eauto.\n        unfold get in *;simpl in *.\n        lets Hx:H H0 H2 H1 Hgetop Hnonest.\n        lets Hgetop': getop_cre_hold H16 H11.\n        lets Hiswait: iswaiting_cre_hold H11 H17;auto.\n        lets Hnoowner: no_owner_cre H13 H11.\n        lets Hx': Hx H12 Hnoowner H15 Hiswait;eauto.\n\n        (*mutex del*)\n        destruct H0.\n        mytac.\n        unfold mutexdel_succ in H2.\n        mytac.\n        assert (O'= (set O absecblsid (absecblist x5))).\n        eapply join_get_set_eq;eauto.\n        subst O'.\n        clear H6.\n        remember O as Ox.\n        subst O.\n        eapply join_get_l in H2;eauto.\n        \n        unfold get in *;simpl in *.\n        clear Htget H3 H4.\n        unfold WEAK_PIF in *.\n        intros.\n        rewrite OSAbstMod.map_get_set in H0.\n        inverts H0.\n        rewrite abst_set_get_neq in H3;auto.\n        rewrite abst_set_get_neq in H4;auto.\n        rewrite H1 in H4;inverts H4.\n        assert (OSAbstMod.get Ox absecblsid = Some (absecblist x4)).\n        auto.\n        lets Hgetop: getop_del_hold H14 H9.\n        lets Hgetop':getop_del_hold H6 H9.\n        lets Hnonest: no_nest_pending_del H8 H9.\n        lets Hx': H H0 H3 H1 Hgetop' Hnonest.\n\n        lets Hiswait:iswaiting_del_hold H9 H15.\n        lets Hnoowner: no_owner_del H11 H9.\n        lets Hx'': Hx' H10 Hnoowner Hgetop Hiswait;auto.\n\n        (*mutex pend get succ *)\n        destruct H0.\n        mytac.\n        clear -H H2 H5 H6 Hgoodst Hnonesto' Hnonesto.\n        rename H2 into H1.\n        rename H5 into Hfff.\n        rename H6 into Hffff.\n        inverts H1.\n        mytac.\n        clear H6.\n        assert (get O curtid = Some (oscurt x8)) as Hct by (eapply join_get_l;eauto).\n        assert (get O absecblsid = Some (absecblist x1)) as Hels by (eapply join_get_l;eauto).\n        assert (get O abtcblsid = Some (abstcblist x4)) as Htls by (eapply join_get_l;eauto).\n        assert (O' = (set O absecblsid\n                          (absecblist (set x1 x (absmutexsem x7 (Some (x8, x5)), nil))))).\n        eapply join_get_set_eq;eauto.\n        subst O'.\n        clear H1 H2 H3 Hffff Hfff.\n        remember O as Ox.\n        clear HeqOx.\n        rename x8 into ct.\n        rename x1 into els.\n        rename x4 into tls.\n        unfold get in *;simpl in *.\n        unfolds.\n        intros.\n        rewrite OSAbstMod.map_get_set in H0.\n        inverts H0.\n        rewrite abst_set_get_neq in H2;auto.\n        rewrite H2 in Hct;inverts Hct.\n        destruct H8.\n        exists x.\n        unfolds.\n        do 3 eexists.\n        rewrite EcbMod.set_a_get_a.\n        auto.\n        apply tidspec.eq_beq_true;auto.\n        \n        (*---------------*)\n        destruct H0;mytac.\n        destruct H0;mytac.\n        destruct H0;mytac.\n\n        clear -H H2 H5 H6 Hnonesto Hgoodst Hgoodst'.\n        rename H2 into H3.\n        rename H5 into Hfff.\n        rename H6 into Hffff.\n        unfolds in H3.\n        assert (NO_NEST_PENDING_O O) as H4 by auto.\n        assert (GOOD_ST O) as H5 by auto.\n        \n        mytac.\n        clear H4 H5.\n        assert (get O curtid = Some (oscurt x9)) as Hct by (eapply join_get_l;eauto).\n        assert (get O absecblsid = Some (absecblist x0)) as Hels by (eapply join_get_l;eauto).\n        assert (get O abtcblsid = Some (abstcblist x1)) as Htls by (eapply join_get_l;eauto).\n        assert (O' = (set (set O abtcblsid (abstcblist (set x1 x9 (x6, x7, x8))))\n               absecblsid (absecblist (set x0 x (absmutexsem x5 None, nil))))).\n        eapply join_get_set_eq_2;eauto.\n        subst O'.\n        clear H1 H2 H3 Hffff Hfff.\n        remember O as Ox.\n        rename x9 into ct.\n        rename x0 into els.\n        rename x1 into tls.\n        clear HeqOx.\n\n        unfold get in *;simpl in *.\n        unfold WEAK_PIF in *.\n        intros.\n\n        rewrite OSAbstMod.map_get_set in H0;inverts H0.\n        rewrite abst_set_get_neq in H1;auto.\n        rewrite OSAbstMod.map_get_set in H1;inverts H1.\n        rewrite abst_set_get_neq in H2;auto.\n        rewrite abst_set_get_neq in H2;auto.\n        rewrite H2 in Hct;inverts Hct.\n        assert (HighestRdy (TcbMod.set tls ct (x6, x7, x8)) ct) as Hhighest by auto.\n        unfolds in H5.\n        mytac.\n        rewrite TcbMod.set_a_get_a in H0.\n        inverts H0.\n        unfolds in Hgoodst'.\n        rewrite OSAbstMod.map_get_set in Hgoodst'.\n        rewrite abst_set_get_neq in Hgoodst';auto.\n        rewrite OSAbstMod.map_get_set in Hgoodst'.\n\n        assert (Some (absecblist (EcbMod.set els x (absmutexsem x5 None, nil))) =\n                Some (absecblist (EcbMod.set els x (absmutexsem x5 None, nil)))).\n        auto.\n        assert (Some (abstcblist (TcbMod.set tls ct (x0, rdy, x1))) =\n                Some (abstcblist  (TcbMod.set tls ct (x0, rdy, x1)))).\n        auto.\n        lets Hgoodstx:Hgoodst' H0 H5.\n        clear H0 Hgoodst' H5.\n        destruct Hgoodstx as (Hrdyninwl&Hownerpp&Htaskstp&Hoppprop&Hwaitexowner&Hnoownerp).\n        unfolds in Htaskstp.\n        assert (exists p st m, TcbMod.get (TcbMod.set tls ct (x0, rdy, x1)) t = Some (p,st,m)).\n        remember (TcbMod.get (TcbMod.set tls ct (x0, rdy, x1)) t) as X;destruct X;tryfalse.\n        destruct b.\n        destruct p.\n        do 3 eexists;eauto.\n        destruct H10;auto.\n        mytac.\n        assert (TcbMod.get tls t = Some (x2, x3, x4)).\n        rewrite TcbMod.set_a_get_a' in H0;[ | apply tidspec.neq_beq_false;auto];auto.\n        lets Htaskstp':Htaskstp H0.\n\n        lets Hpct:post_lift_get_op_ct Hnonesto Hels Htls H6 H3;auto.\n        subst x0.\n        \n        destruct Htaskstp'.\n        subst x3.\n        lets Hx:H1 H9 H0.\n        unfolds in Hoppprop.\n        lets Hy:Hoppprop H0 H11.\n        clear -Hx Hy.\n        destruct Hy;int auto.\n        mytac;subst.\n        unfolds in Hwaitexowner.\n        lets Hx:Hwaitexowner H0.\n        mytac.\n\n        lets Hx:post_lift_ct_nowner Hnonesto Hels Htls H6 H13;auto.\n        eauto.\n        lets Hz: H1 Hx H14.\n        lets Hy:H16 H11.\n        clear -H15 Hz Hy.\n        subst x2.\n        int auto.\n        apply tidspec.eq_beq_true;auto.\n        \n        destruct H0;mytac.\n\n        (*mutex post nowt no return*)\n        clear -H H2  H5 H6 Hnonesto Hgoodst Hgoodst'.\n        rename H2 into H3.\n        rename H5 into Hfff.\n        rename H6 into Hffff.\n        unfolds in H3.\n        assert ( NO_NEST_PENDING_O O) as H4 by auto.\n        assert ( NO_NEST_PENDING_O O) as H5 by auto.\n        mytac.\n        clear H4 H5.\n        assert (get O curtid = Some (oscurt x9)) as Hct by (eapply join_get_l;eauto).\n        assert (get O absecblsid = Some (absecblist x0)) as Hels by (eapply join_get_l;eauto).\n        assert (get O abtcblsid = Some (abstcblist x1)) as Htls by (eapply join_get_l;eauto).\n        assert (O' =(set O absecblsid\n               (absecblist (set x0 x (absmutexsem x4 None, nil))))).\n        eapply join_get_set_eq;eauto.\n        subst O'.\n        clear H1 H2 H3 Hffff Hfff.\n        remember O as Ox.\n        rename x9 into ct.\n        rename x0 into els.\n        rename x1 into tls.\n        clear HeqOx.\n        unfold get in *;simpl in *.\n        unfold WEAK_PIF in *.\n        intros.\n        rename H10 into Hn.\n        rewrite OSAbstMod.map_get_set in H0;inverts H0.\n        rewrite abst_set_get_neq in H1;auto.\n        rewrite Htls in H1;inversion H1;subst tls0.\n        rewrite abst_set_get_neq in H2;auto.\n        rewrite H2 in Hct;inverts Hct.\n        unfolds in H5.\n        mytac.\n        unfolds in Hgoodst'.\n        rewrite OSAbstMod.map_get_set in Hgoodst'.\n        rewrite abst_set_get_neq in Hgoodst';auto.\n\n        assert (Some (absecblist (EcbMod.set els x (absmutexsem x4 None, nil))) =\n                Some (absecblist (EcbMod.set els x (absmutexsem x4 None, nil)))).\n        auto.\n        \n        lets Hgoodstx:Hgoodst' H1 Htls.\n        clear Hgoodst' H1.\n        destruct Hgoodstx as (Hrdyninwl&Hownerpp&Htaskstp&Hoppprop&Hwaitexowner&Hnoownerp).\n        unfolds in Htaskstp.\n        assert (exists p st m, TcbMod.get tls t = Some (p,st,m)).\n        remember (TcbMod.get tls t) as X;destruct X;tryfalse.\n        destruct b.\n        destruct p.\n        do 3 eexists;eauto.\n        mytac.\n        lets Htaskstp':Htaskstp H1.\n\n        rewrite H7 in H0;inverts H0.\n        assert (x0 = x5).\n        clear -Hgoodst H8 H7 H6 Htls Hels.\n        unfolds in Hgoodst.\n        lets Hx:Hgoodst Hels Htls.\n        mytac.\n        unfolds in H0.\n        lets Hx: H0 H7 H6.\n        destruct Hx.\n        destruct H5;auto.\n        subst x0.\n        false.\n        clear -H8.\n        int auto.\n\n        subst x5.\n        lets Hpct:post_nolift_get_op_ct Hnonesto Hels Htls H6 H3;auto.\n        eauto.\n        subst x0.\n        \n        destruct Htaskstp'.\n        subst x3.\n        lets Hx:H5 Hn H1.\n        unfolds in Hoppprop.\n        lets Hy:Hoppprop H1 H12.\n        clear -Hx Hy.\n        destruct Hy;int auto.\n        mytac;subst.\n        unfolds in Hwaitexowner.\n        lets Hx:Hwaitexowner H1.\n        mytac.\n\n        lets Hx:post_no_lift_ct_nowner Hnonesto Hels Htls H6 H0;auto.\n        eauto.\n        lets Hz: H5 Hx H10.\n        lets Hy:H15 H12.\n        clear -H14 Hz Hy.\n        subst x2.\n        int auto.\n        \n        destruct H0;mytac.\n        destruct H0;mytac.\n        destruct H0;mytac.\n        \n        destruct Hgoodapicode;subst;auto.\n        unfolds in H0.\n        mytac.\n        rewrite H0 in H1;inverts H1.\n        rewrite Htget in H3.\n        inverts H3.\n        destruct H4;mytac.\n        destruct H1;mytac.\n        destruct H1;mytac.\n        destruct H1;mytac.\n\n        (*mutex pend block no lift*)\n        destruct H1;mytac.\n        clear -H H2.\n        rename H2 into H1.\n        inverts H1.\n        rename H7 into Hfff.\n        rename H11 into Hffff.\n        unfolds in H3.\n        mytac.\n        clear H10.\n        clear H4 H5.\n        assert (get O curtid = Some (oscurt x14)) as Hct by (eapply join_get_l;eauto).\n        assert (get O absecblsid = Some (absecblist x5)) as Hels by (eapply join_get_l;eauto).\n        assert (get O abtcblsid = Some (abstcblist x3)) as Htls by (eapply join_get_l;eauto).\n        assert (O' =(set\n               (set O abtcblsid\n                  (abstcblist\n                     (set x3 x14 (x12, wait (os_stat_mutexsem x) x0, Vnull))))\n               absecblsid\n               (absecblist\n                  (set x5 x (absmutexsem x8 (Some (x9, x10)), x14 :: x7))))).\n        eapply join_get_set_eq_2;eauto.\n        subst O'.\n        clear H1 H2 H3 Hffff Hfff.\n        remember O as Ox.\n        rename x14 into ct.\n        rename x5 into els.\n        rename x3 into tls.\n        clear HeqOx.\n        unfold get in *;simpl in *.\n        unfold WEAK_PIF.\n        intros.\n        rewrite OSAbstMod.map_get_set in H0;inverts H0.\n        rewrite abst_set_get_neq in H1;auto.\n        rewrite OSAbstMod.map_get_set in H1;inverts H1.\n        rewrite abst_set_get_neq in H2;auto.\n        rewrite abst_set_get_neq in H2;auto.\n\n        rewrite H2 in Hct;inverts Hct.\n        unfolds in H5.\n        mytac.\n        \n        rewrite TcbMod.set_a_get_a in H0.\n        inverts H0.\n        apply tidspec.eq_beq_true;auto.\n\n        (*mutex pend lift*)\n        destruct H1;mytac.\n        clear -H H2 Hgoodst.\n        rename H2 into H1.\n        inverts H1.\n        rename H7 into Hfff.\n        rename H11 into Hffff.\n        unfolds in H3.\n        mytac.\n        clear H11.\n        clear H4 H5.\n        assert (get O curtid = Some (oscurt x15)) as Hct by (eapply join_get_l;eauto).\n        assert (get O absecblsid = Some (absecblist x6)) as Hels by (eapply join_get_l;eauto).\n        assert (get O abtcblsid = Some (abstcblist x3)) as Htls by (eapply join_get_l;eauto).\n        assert (O' = (set\n               (set O abtcblsid\n                  (abstcblist\n                     (set\n                        (set x3 x15 (x13, wait (os_stat_mutexsem x) x0, x2))\n                        x10 (x9, rdy, x14)))) absecblsid\n               (absecblist\n                  (set x6 x (absmutexsem x9 (Some (x10, x11)), x15 :: x8))))).\n        eapply join_get_set_eq_2;eauto.\n        subst O'.\n        clear H1 H2 H3 Hffff Hfff.\n        remember O as Ox.\n        rename x15 into ct.\n        rename x6 into els.\n        rename x3 into tls.\n        clear HeqOx.\n        unfold get in *;simpl in *.\n        unfold WEAK_PIF in *.\n        intros.\n        rewrite OSAbstMod.map_get_set in H0;inverts H0.\n        rewrite abst_set_get_neq in H1;auto.\n        rewrite OSAbstMod.map_get_set in H1;inverts H1.\n        rewrite abst_set_get_neq in H2;auto.\n        rewrite abst_set_get_neq in H2;auto.\n        rewrite H2 in Hct;inverts Hct.\n        unfolds in H5.\n        mytac.\n        assert (x10 = ct \\/ x10 <> ct) by tauto.\n        destruct H5;try subst x10.\n\n\n        unfolds in H4.\n        assert (TcbMod.get\n         (TcbMod.set\n            (TcbMod.set tls ct (x13, wait (os_stat_mutexsem x) x0, x2)) ct\n            (x9, rdy, x14)) ct <> None).\n        intro.\n        unfold set in *;simpl in *.\n        rewrite H5 in H0;tryfalse.\n\n        eapply H4 with (qid:=x) in H5.\n        destruct H5.\n        destruct H5.\n        unfolds.\n        do 4 eexists.\n        split.\n        rewrite EcbMod.set_a_get_a;eauto.\n        apply tidspec.eq_beq_true;auto.\n        simpl;auto.\n        unfolds.\n        do 3 eexists.\n        rewrite EcbMod.set_a_get_a;eauto.\n        apply tidspec.eq_beq_true;auto.\n        \n        rewrite TcbMod.set_a_get_a' in H0;[ | apply tidspec.neq_beq_false;auto].\n        rewrite TcbMod.set_a_get_a in H0.\n        inverts H0.\n        apply tidspec.eq_beq_true;auto.\n\n   \n        destruct H1;mytac.\n        destruct H1;mytac.\n\n        (*mutex post exwt return*)\n        destruct H1.\n        mytac.\n        rename H2 into H1.\n        clear -H H1 Hnonesto Hgoodst Hgoodst'.\n        inverts H1.\n        rename H7 into Hfff.\n        rename H11 into Hffff.\n        unfolds in H3.\n        mytac.\n        clear H4 H5.\n        assert (get O curtid = Some (oscurt x15)) as Hct by (eapply join_get_l;eauto).\n        assert (get O absecblsid = Some (absecblist x0)) as Hels by (eapply join_get_l;eauto).\n        assert (get O abtcblsid = Some (abstcblist x2)) as Htls by (eapply join_get_l;eauto).\n        assert (O' =  (set\n               (set O abtcblsid\n                  (abstcblist\n                     (set (set x2 x15 (x8, x9, x10)) x12 (x7, rdy, Vptr x))))\n               absecblsid\n               (absecblist\n                  (set x0 x\n                     (absmutexsem x6 (Some (x12, x7)), remove_tid x12 x11))))).\n        eapply join_get_set_eq_2;eauto.\n        subst O'.\n        clear H1 H2 H3 Hffff Hfff.\n        remember O as Ox.\n        rename x15 into ct.\n        rename x0 into els.\n        rename x2 into tls.\n        clear HeqOx.\n        unfold get in *;simpl in *.\n        lets Hneq: post_ex_wait_ct_neq Hnonesto Hels Htls H6 H8.\n        \n        unfold WEAK_PIF in *.\n        intros.\n        unfold set in *;simpl in *.\n        rewrite OSAbstMod.map_get_set in H0;inverts H0.\n        rewrite abst_set_get_neq in H1;auto.\n        rewrite OSAbstMod.map_get_set in H1;inverts H1.\n        rewrite abst_set_get_neq in H2;auto.\n        rewrite abst_set_get_neq in H2;auto.\n        rewrite H2 in Hct;inverts Hct.\n        unfolds in H5.\n        mytac.\n        rewrite TcbMod.set_a_get_a' in H0.\n        rewrite TcbMod.set_a_get_a in H0.\n        inverts H0.\n        unfolds in Hgoodst'.\n        rewrite OSAbstMod.map_get_set in Hgoodst'.\n        rewrite abst_set_get_neq in Hgoodst';auto.\n        rewrite OSAbstMod.map_get_set in Hgoodst'.\n\n        assert ( Some\n               (absecblist\n                  (EcbMod.set els x\n                     (absmutexsem x6 (Some (x12, x7)), remove_tid x12 x11))) =\n                Some\n               (absecblist\n                  (EcbMod.set els x\n                     (absmutexsem x6 (Some (x12, x7)), remove_tid x12 x11)))).\n        auto.\n        assert ( Some\n               (abstcblist\n                  (TcbMod.set (TcbMod.set tls ct (x0, rdy, x1)) x12\n                     (x7, rdy, Vptr x)))   =\n                Some\n               (abstcblist\n                  (TcbMod.set (TcbMod.set tls ct (x0, rdy, x1)) x12\n                     (x7, rdy, Vptr x)))  ).\n        auto.\n        lets Hgoodstx:Hgoodst' H0 H5.\n        clear H0 Hgoodst' H5.\n        destruct Hgoodstx as (Hrdyninwl&Hownerpp&Htaskstp&Hoppprop&Hwaitexowner&Hnoownerp).\n        unfolds in Htaskstp.\n        assert (exists p st m, TcbMod.get  (TcbMod.set (TcbMod.set tls ct (x0, rdy, x1)) x12 (x7, rdy, Vptr x)) t = Some (p,st,m)).\n        remember (TcbMod.get (TcbMod.set (TcbMod.set tls ct (x0, rdy, x1)) x12 (x7, rdy, Vptr x)) t) as X;destruct X;tryfalse.\n        destruct b.\n        destruct p.\n        do 3 eexists;eauto.\n        destruct H13;auto.\n        mytac.\n        assert (t = x12 \\/ t <> x12) by tauto.\n        destruct H5.\n        subst x12.\n        Focus 2.\n        assert (TcbMod.get tls t = Some (x2, x3, x4)).\n        \n        rewrite TcbMod.set_a_get_a' in H0;[ | apply tidspec.neq_beq_false;auto];auto.\n        rewrite TcbMod.set_a_get_a' in H0;[ | apply tidspec.neq_beq_false;auto];auto.\n        \n        lets Htaskstp':Htaskstp H0.\n\n        lets Hpct:post_lift_exwt_get_op_ct Hneq Hnonesto Hels Htls H3;auto.\n        eauto.\n        subst x0.\n        \n        destruct Htaskstp'.\n        subst x3.\n        lets Hx:H1 H12 H0.\n        unfolds in Hoppprop.\n        lets Hy:Hoppprop H0 H14.\n        clear -Hx Hy.\n        destruct Hy;int auto.\n        mytac;subst.\n        unfolds in Hwaitexowner.\n        lets Hx:Hwaitexowner H0.\n        mytac.\n\n        lets Hx:post_lift_exwt_ct_nowner Hnonesto Hels Htls H17 Hneq;auto.\n        eauto.\n        eauto.\n        lets Hz: H1 Hx H18.\n        lets Hy:H20 H14.\n        clear -H19 Hz Hy.\n        subst x2.\n        int auto.\n\n        lets Hpct:post_lift_exwt_get_op_ct Hneq Hnonesto Hels Htls H3;auto.\n        eauto.\n        subst x0.\n        assert (x3 = rdy).\n        rewrite TcbMod.set_a_get_a in H0;[ | apply tidspec.eq_beq_true;auto];auto.\n        inverts H0.\n        auto.\n        subst x3.\n        lets Hx:H1 H12 H0.\n        unfolds in Hoppprop.\n        lets Hy:Hoppprop H0 H14.\n        clear -Hx Hy.\n        destruct Hy;int auto.\n        mytac;subst.\n        apply tidspec.eq_beq_true;auto.\n        apply tidspec.neq_beq_false;auto.\n\n        (*mutex post exwt no return*)\n        destruct H1.\n        mytac.\n        rename H2 into H1.\n        clear -H H1 Hnonesto Hgoodst Hgoodst'.\n        inverts H1.\n        rename H7 into Hfff.\n        rename H11 into Hffff.\n        unfolds in H3.\n        mytac.\n        clear H4 H5.\n        assert (get O curtid = Some (oscurt x5)) as Hct by (eapply join_get_l;eauto).\n        assert (get O absecblsid = Some (absecblist x0)) as Hels by (eapply join_get_l;eauto).\n        assert (get O abtcblsid = Some (abstcblist x2)) as Htls by (eapply join_get_l;eauto).\n        assert (O' = (set\n               (set O abtcblsid (abstcblist (set x2 x13 (x7, rdy, Vptr x))))\n               absecblsid\n               (absecblist\n                  (set x0 x\n                     (absmutexsem x6 (Some (x13, x7)), remove_tid x13 x12))))).\n        eapply join_get_set_eq_2;eauto.\n        subst O'.\n        clear H1 H2 H3 Hffff Hfff.\n        remember O as Ox.\n        rename x5 into ct.\n        rename x0 into els.\n        rename x2 into tls.\n        clear HeqOx.\n        lets Hneq: post_ex_wait_ct_neq Hnonesto Hels Htls H6 H8.\n        unfold get in *;unfold set in *;simpl in *.\n        unfold WEAK_PIF in *.\n        intros.\n        rewrite OSAbstMod.map_get_set in H0;inverts H0.\n        rewrite abst_set_get_neq in H1;auto.\n        rewrite OSAbstMod.map_get_set in H1;inverts H1.\n        rewrite abst_set_get_neq in H2;auto.\n        rewrite abst_set_get_neq in H2;auto.\n       \n        rewrite H2 in Hct;inverts Hct.\n        unfolds in H5.\n        mytac.\n        unfolds in Hgoodst'.\n        rewrite OSAbstMod.map_get_set in Hgoodst'.\n        rewrite abst_set_get_neq in Hgoodst';auto.\n        rewrite OSAbstMod.map_get_set in Hgoodst'.\n        assert ( Some\n               (absecblist\n                  (EcbMod.set els x\n                     (absmutexsem x6 (Some (x13, x7)), remove_tid x13 x12)))=\n                 Some\n               (absecblist\n                  (EcbMod.set els x\n                     (absmutexsem x6 (Some (x13, x7)), remove_tid x13 x12)))).\n        auto.\n        assert (Some (abstcblist (TcbMod.set tls x13 (x7, rdy, Vptr x))) =Some (abstcblist (TcbMod.set tls x13 (x7, rdy, Vptr x)))).\n        auto.\n        \n        lets Hgoodstx:Hgoodst' H5 H17.\n        clear Hgoodst' H5 H17.\n        destruct Hgoodstx as (Hrdyninwll&Hownerpp&Htaskstp&Hoppprop&Hwaitexowner&Hnoownerp).\n        unfolds in Htaskstp.\n        assert (exists p st m, TcbMod.get (TcbMod.set tls x13 (x7, rdy, Vptr x)) t = Some (p,st,m)).\n        remember (TcbMod.get (TcbMod.set tls x13 (x7, rdy, Vptr x)) t) as X;destruct X;tryfalse.\n        destruct b.\n        destruct p.\n        do 3 eexists;eauto.\n        mytac.\n        assert (t = x13 \\/ t <> x13) by tauto.\n        destruct H17.\n        Focus 2.\n        lets Htaskstp':Htaskstp H5.\n        rewrite TcbMod.set_a_get_a' in H0;[ | apply tidspec.neq_beq_false;auto];auto.\n        unfold get in *;unfold set in *;simpl in *.\n        rewrite H0 in H10;inverts H10.\n\n        assert (x8 = x9).\n        clear -Hgoodst H9 H0 H6 Htls Hels.\n        unfolds in Hgoodst.\n        lets Hx:Hgoodst Hels Htls.\n        mytac.\n        unfolds in H1.\n        lets Hx: H1 H0 H6.\n        destruct Hx.\n        destruct H7;auto.\n        subst x8.\n        false.\n        clear -H9.\n        int auto.\n        subst x8.\n\n        lets Hpct:post_nolift_exwt_get_op_ct Hnonesto Hels Htls H6 H3;auto.\n        eauto.\n        subst x9.\n        \n        destruct Htaskstp'.\n        subst x3.\n        lets Hx:H1 H13 H5.\n        unfolds in Hoppprop.\n        lets Hy:Hoppprop H5 H15.\n        clear -Hx Hy.\n        destruct Hy;int auto.\n        mytac;subst.\n        unfolds in Hwaitexowner.\n        lets Hx:Hwaitexowner H5.\n        mytac.\n        \n        lets Hx:post_nolift_exwt_ct_nowner Hnonesto Hels Htls H10 Hneq;auto.\n        eauto.\n        eauto.\n        lets Hz: H1 Hx H18.\n        lets Hy:H20 H15.\n        clear -H19 Hz Hy.\n        subst x2.\n        int auto.\n\n        rewrite TcbMod.set_a_get_a' in H0;[ | apply tidspec.neq_beq_false;auto];auto.\n        inverts H0.\n        lets Hpct:post_nolift_exwt_get_op_ct Hnonesto Hels Htls H6 H3;auto.\n        eauto.\n        subst x0.\n        assert (x3 = rdy).\n        rewrite TcbMod.set_a_get_a in H5;[ | apply tidspec.eq_beq_true;auto];auto.\n        inverts H5.\n        auto.\n        subst x3.\n        lets Hx:H1 H13 H5.\n        unfolds in Hoppprop.\n        lets Hy:Hoppprop H5 H15.\n        clear -Hx Hy.\n        destruct Hy;int auto.\n\n        (* -------time tick---------- *)\n        destruct H1;mytac.\n        rename H2 into H1.\n        clear -H H1 Hnonesto Hgoodst Hgoodst'.\n        inverts H1.\n        rename H7 into Hfff.\n        rename H11 into Hffff.\n        unfolds in H3.\n        mytac.\n        clear H4 H5.\n        assert (get O ostmid = Some (ostm x1)) as Htm by (eapply join_get_l;eauto).\n        assert (get O absecblsid = Some (absecblist x0)) as Hels by (eapply join_get_l;eauto).\n        assert (get O abtcblsid = Some (abstcblist x)) as Htls by (eapply join_get_l;eauto).\n        assert (O' =(set\n               (set (set O absecblsid (absecblist x3)) abtcblsid\n                  (abstcblist x2)) ostmid (ostm (x1 +ᵢ  Int.one)))).\n        eapply join_get_set_eq_3;eauto.\n        subst O'.\n        clear H1 H2 H0 Hffff Hfff.\n        remember O as Ox.\n        rename x1 into tm.\n        rename x0 into els.\n        rename x into tls.\n        clear HeqOx.\n        unfold tickstep in H7.\n        unfold WEAK_PIF in *.\n        intros.\n\n        rewrite abst_set_get_neq in H0;auto.\n        rewrite abst_set_get_neq in H0;auto.\n        rewrite OSAbstMod.map_get_set in H0;inverts H0.\n        rewrite abst_set_get_neq in H1;auto.\n        rewrite OSAbstMod.map_get_set in H1;inverts H1.\n\n        rewrite abst_set_get_neq in H2;auto.\n        rewrite abst_set_get_neq in H2;auto.\n        rewrite abst_set_get_neq in H2;auto.\n        lets Hx:H Hels Htls H2.\n        \n        unfolds in Hgoodst'.\n        rewrite abst_set_get_neq in Hgoodst';auto.\n        rewrite abst_set_get_neq in Hgoodst';auto.\n\n        unfolds in Hgoodst.\n        lets Hxx': Hgoodst Hels Htls.\n\n        eapply timetick_weakpif;eauto.\n        eapply TcbMod.sub_refl;eauto.\n\n        inverts H2.\n\n    +\n      inverts H3;auto.\n  -\n    inverts H1.\n    inverts H5;auto.\n  -\n    (*swi step*)\n    inverts H1.\n    rename H2 into H1.\n    rename H3 into H2.\n    rename H4 into H3.\n    assert (t' = t \\/ t' <> t) by tauto.\n    destruct H4.\n    subst t'.\n    assert ((OSAbstMod.set O curtid (oscurt t)) = O).\n    rewrite OSAbstMod.get_set_same;auto.\n    unfold set in *;simpl in *.\n    rewrite H4 in *.\n    auto.\n\n    destruct Hgoodapicode.\n    rewrite <- H5;auto.\n\n    destruct H5.\n    mytac.\n    unfold get in *;simpl in *.\n    rewrite H2 in H5;inverts H5.\n    rewrite H3 in H6;inverts H6.\n    destruct H7;mytac;tryfalse.\n    repeat progress (destruct H5;mytac;tryfalse).\n    unfolds.\n    intros.\n    rewrite OSAbstMod.map_get_set in H7;inverts H7.\n    unfolds in H1.\n    mytac.\n\n    unfold get in *;unfold set in *;simpl in *.\n    unfolds in Hgoodst'.\n    lets Hgoodstx: Hgoodst' H5 H6.\n    \n    rewrite abst_set_get_neq in H5;auto.\n    rewrite abst_set_get_neq in H6;auto.\n    rewrite H1 in H6;inverts H6.\n    destruct Hgoodstx as (Hrdyninwl&Hownerpp&Htaskstp&Hoppprop&Hwaitexowner&Hnoownerp).\n    unfolds in Htaskstp.\n    assert (exists p st m, TcbMod.get tls t = Some (p,st,m)).\n    remember (TcbMod.get tls t) as X;destruct X;tryfalse.\n    destruct b.\n    destruct p.\n    do 3 eexists;eauto.\n    mytac.\n    lets Htaskstp':Htaskstp H6.\n\n    unfolds in Hnoownerp.\n    lets Hx:Hnoownerp H7 H11 H8.\n    subst x4.\n    \n    destruct Htaskstp'.\n    subst x7.\n    assert (isrdy rdy).\n    unfolds.\n    auto.\n    lets Hx:H17 H12 H6 H18.\n    unfolds in Hoppprop.\n    lets Hy:Hoppprop H6 H14.\n    clear -Hx Hy.\n    destruct Hy;int auto.\n    mytac;subst.\n    unfolds in Hwaitexowner.\n    lets Hx:Hwaitexowner H6.\n    mytac.\n    assert (x7 <> ct).\n    intro.\n    subst x7.\n    destruct H11.\n    eexists;eauto.\n    assert (isrdy rdy).\n    unfolds.\n    auto.\n    lets Hx:H17 H22 H19 H23.\n    lets Hy:H21 H14.\n    clear -H20 Hy Hx.\n    subst x3.\n    int auto.\n  -\n    destruct Hgoodapicode.\n    rewrite <- H1.\n    auto.\n    unfolds in H1.\n    mytac.\n    unfold get in *;simpl in *.\n    rewrite H1 in H6;inverts H6.\n    rewrite H3 in H2;inverts H2.\n    destruct H4.\n    mytac.\n    repeat progress (destruct H2;mytac).\n  -\n    destruct Hgoodapicode.\n    rewrite <- H1.\n    auto.\n    unfolds in H1.\n    mytac.\n    unfold get in *;simpl in *.\n    rewrite H1 in H6;inverts H6.\n    rewrite H3 in H2;inverts H2.\n    destruct H4.\n    mytac.\n    repeat progress (destruct H2;mytac).\n  -\n    destruct Hgoodapicode.\n    rewrite <- H2.\n    auto.\n    unfolds in H2.\n    mytac.\n    unfold get in *;simpl in *.\n    rewrite H2 in H11;inverts H11.\n    rewrite H3 in H1;inverts H1.\n    destruct H4.\n    mytac.\n    repeat progress (destruct H1;mytac).\n    Grab Existential Variables.\n    trivial.\nQed.\n\nLemma no_nest_prop_step_hold:\n  forall client_code T cst O T' cst' O' ,\n    no_nest_client client_code O T cst ->\n    hpstep (client_code, os_spec') T cst O T' cst' O' ->\n    no_nest_client client_code O' T' cst'.\nProof.\n  introv Hn Hp.\n  unfolds in Hn.\n  unfolds.\n  intros.\n  eapply Hn.\n  constructors; eauto.\nQed.\n\n\n\nLemma hpstep_inv_prop_hold:\n  forall client_code T cst O T' cst' O' ,\n    goodtasks_h T ->\n    hpstep (client_code, os_spec') T cst O T' cst' O' ->\n    INV_PROP client_code O T cst ->\n    INV_PROP client_code O' T' cst'.\nProof.\n  introv Hgoodtasks.\n  introv Hp Hinv.\n  unfolds in Hinv.\n  destruct Hinv as (Hinv1 & Hinv2 & Hinv3).\n  splits; auto.\n  eapply no_nest_prop_step_hold; eauto.\n  lets Hps :  code_exe_prop2 Hinv3 Hp.\n  eauto.\n  eapply code_exe_prop1; eauto.\n  constructors.\n  unfolds in Hinv2.\n  eapply Hinv2.\n  constructors.\n  eapply Hps.\n  unfolds in Hinv2.\n  eapply Hinv2.\n  constructors;eauto.\n  constructors.\nQed.\n   \nLemma hpstep_wpif_hold:\n  forall client_code T cst O T' cst' O',\n    goodtasks_h T ->\n    INV_PROP client_code O T cst ->\n    WEAK_PIF O ->\n    hpstep (client_code, os_spec') T cst O T' cst' O' ->\n    WEAK_PIF O'.\nProof.    \n  introv Hgoodtasks Hinv Hw Hsptep.\n  unfolds in Hinv.\n  destruct Hinv as (Hic & Hn & Hgood).\n  unfolds in Hic.\n  unfolds in Hn.\n  assert (hpstepstar (client_code, os_spec') T cst O T cst O).\n  constructors.\n  lets Hnest: Hn H.\n  lets Hres : no_nest_pif Hnest Hw Hsptep; eauto.\n  eapply Hn.\n  constructors;eauto.\n  constructors.\n  eapply code_exe_prop1; eauto.\nQed.  \n\nLemma hpstep_pif_hold\n: forall (client_code : progunit) (T : TasksMod.map) \n         (cst : clientst) (O : osabst) (T' : tasks) \n         (cst' : clientst) (O' : osabst),\n    goodtasks_h T ->\n    INV_PROP client_code O T cst ->\n    PIF O ->\n    hpstep (client_code, os_spec') T cst O T' cst' O' -> PIF O'.\nProof.\n  intros.\n  unfolds.\n  intros.\n  lets Hx:hpstep_wpif_hold H H0 H2.\n  unfolds in H1.\n  unfolds.\n  intros.\n  eapply H1;eauto.\n  unfolds in Hx.\n  eapply Hx;eauto.\n  unfolds in H0.\n  mytac.\n  unfolds in H13.\n  assert (NO_NEST_PENDING_O O').\n  unfolds in H14.\n  eapply H13;eauto.\n  constructors.\n  eauto.\n  constructors.\n  unfolds in H15.\n  lets Hy:H15 H3 H4.\n  auto.\nQed.\n\nTheorem Priority_Inversion_Free_Prop:\n  forall client_code T cst O T' cst' O',\n    InitTasks T client_code cst O ->\n    INV_PROP client_code O T cst ->\n    hpstepstar (client_code, os_spec') T cst O T' cst' O' ->\n    PIF O ->\n    PIF O'.\nProof.\n  introv Hinittasks.\n  intros.\n  lets hgoodtasks:init_goodks_h Hinittasks H.\n  clear Hinittasks.\n  inductions H0.\n  auto.\n  eapply IHhpstepstar;eauto.\n  eapply hpstep_inv_prop_hold; eauto.\n  eapply hpstep_pif_hold; eauto.\n  eapply hpstep_goodcode_h;eauto.\n  unfolds in H;mytac;auto.\nQed.\n\nDefinition init_st O:=\n  exists tls,\n    OSAbstMod.get O absecblsid = Some (absecblist EcbMod.emp) /\\\n    OSAbstMod.get O abstcblsid = Some (abstcblist tls) /\\\n    forall t, exists p msg, TcbMod.get tls t = Some (p,rdy,msg).\n\nTheorem GOOD_ST_Prop':\n  forall client_code T cst O T' cst' O',\n    goodtasks_h T ->\n    good_client_code client_code ->\n    GOOD_ST O->\n    good_client_code client_code ->\n    no_nest_client client_code O T cst ->\n    hpstepstar (client_code, os_spec') T cst O T' cst' O' ->\n    GOOD_ST O'.\nProof.\n  intros.\n  inductions H4;auto.\n  eapply IHhpstepstar with (O:=O') (T:=T');eauto.\n  2:eapply hpstep_goodcode_h;eauto.\n  2:eapply no_nest_prop_step_hold;eauto.\n  eapply code_exe_prop2 with (O':=O) (O'':=O');eauto.\n  eapply hpstep_goodcode_goodapi;eauto.\n  unfolds in H3.\n  eapply H3.\n  constructors.\n  unfolds in H3.\n  eapply H3.\n  eapply hp_stepS.\n  2:constructors.\n  eauto.\nQed.\n\nLemma init_goodks_h':\n  forall T client_code cst O,\n    InitTasks T client_code cst O ->\n    good_client_code client_code ->\n    goodtasks_h T .\nProof.\n  intros.\n  unfolds in H.\n  unfolds.\n  intros.\n  mytac.\n  apply H2 in H1.\n  mytac.\n  unfolds in H0.\n  mytac.\n  apply H0 in H3.\n  clear -H3.\n  unfolds.\n  unfolds in H3.\n  induction x;simpl in *;auto;tryfalse.\n  mytac.\n  apply IHx1;auto.\n  apply IHx2;auto.\n  mytac.\n  apply IHx1;auto.\n  apply IHx2;auto.\nQed.\n\n  \nTheorem GOOD_ST_Prop:\n  forall client_code T cst O T' cst' O',\n    InitTasks T client_code cst O ->\n    init_st O ->\n    good_client_code client_code ->\n    no_nest_client client_code O T cst ->\n    hpstepstar (client_code, os_spec') T cst O T' cst' O' ->\n    GOOD_ST O'.\nProof.\n  intros.\n  eapply GOOD_ST_Prop';eauto.\n  eapply init_goodks_h';eauto.\n\n  unfolds.\n  unfolds in H0.\n  mytac.\n  intros.\n  rewrite H0 in H6.\n  inverts H6.\n  rewrite H4 in H7;inverts H7.\n  splits.\n  unfolds.\n  splits.\n  intros.\n  intro.\n  unfolds in H7.\n  mytac.\n  rewrite EcbMod.emp_sem in H7;tryfalse.\n  intros.\n  lets Hx:H5 t.\n  mytac.\n  rewrite H6 in H7;inverts H7.\n  intros.\n  unfolds in H6.\n  mytac.\n  rewrite EcbMod.emp_sem in H6;tryfalse.\n  unfolds.\n  intros.\n  rewrite EcbMod.emp_sem in H7;tryfalse.\n  unfolds.\n  intros.\n  left.\n  lets Hx:H5 t.\n  mytac.\n  rewrite H6 in H7;inverts H7;auto.\n  unfolds.\n  intros.\n  unfolds in H7.\n  right.\n  assert (TcbMod.get tls t <> None).\n  intro.\n  rewrite H6 in H8;inverts H8.\n  apply H7 in H8.\n  destruct H8.\n  mytac.\n  unfolds in H8.\n  mytac.\n  rewrite EcbMod.emp_sem in H8;tryfalse.\n  destruct H8.\n  mytac.\n  rewrite H9 in H6;inverts H6.\n  clear.\n  int auto.\n  unfolds.\n  intros.\n  lets Hx:H5 t.\n  mytac.\n  rewrite H7 in H6;inverts H6.\n  unfolds.\n  intros.\n  unfolds in H8.\n  assert (TcbMod.get tls t <> None).\n  intro.\n  rewrite H6 in H9;inverts H9.\n  apply H8 in H9.\n  destruct H9.\n  mytac.\n  unfolds in H9.\n  mytac.\n  rewrite EcbMod.emp_sem in H9;tryfalse.\n  destruct H9.\n  mytac.\n  rewrite H6 in H10;inverts H10;auto.\nQed.\n\n\n  \nTheorem Priority_Inversion_Free_Proof:\n  forall client_code T cst O T' cst' O',\n    InitTasks T client_code cst O ->\n    init_st O ->\n    good_client_code client_code ->\n    no_nest_client client_code O T cst ->\n    hpstepstar (client_code, os_spec') T cst O T' cst' O' ->\n    PIF O'.\nProof.\n  intros.\n  eapply Priority_Inversion_Free_Prop;eauto.\n  unfolds;splits;auto.\n  unfolds.\n  unfolds in H0.\n  mytac.\n  intros.\n  rewrite H0 in H6.\n  inverts H6.\n  rewrite H4 in H7;inverts H7.\n  splits.\n  unfolds.\n  splits.\n  intros.\n  intro.\n  unfolds in H7.\n  mytac.\n  rewrite EcbMod.emp_sem in H7;tryfalse.\n  intros.\n  lets Hx:H5 t.\n  mytac.\n  rewrite H6 in H7;inverts H7.\n  intros.\n  unfolds in H6.\n  mytac.\n  rewrite EcbMod.emp_sem in H6;tryfalse.\n  unfolds.\n  intros.\n  rewrite EcbMod.emp_sem in H7;tryfalse.\n  unfolds.\n  intros.\n  left.\n  lets Hx:H5 t.\n  mytac.\n  rewrite H6 in H7;inverts H7;auto.\n  unfolds.\n  intros.\n  unfolds in H7.\n  right.\n  assert (TcbMod.get tls t <> None).\n  intro.\n  rewrite H6 in H8;inverts H8.\n  apply H7 in H8.\n  destruct H8.\n  mytac.\n  unfolds in H8.\n  mytac.\n  rewrite EcbMod.emp_sem in H8;tryfalse.\n  destruct H8.\n  mytac.\n  rewrite H9 in H6;inverts H6.\n  clear.\n  int auto.\n  unfolds.\n  intros.\n  lets Hx:H5 t.\n  mytac.\n  rewrite H7 in H6;inverts H6.\n  unfolds.\n  intros.\n  unfolds in H8.\n  assert (TcbMod.get tls t <> None).\n  intro.\n  rewrite H6 in H9;inverts H9.\n  apply H8 in H9.\n  destruct H9.\n  mytac.\n  unfolds in H9.\n  mytac.\n  rewrite EcbMod.emp_sem in H9;tryfalse.\n  destruct H9.\n  mytac.\n  rewrite H6 in H10;inverts H10;auto.\n\n  unfolds.\n  intros.\n  unfolds in H13.\n  mytac.\n  unfolds in H0.\n  mytac.\n  rewrite H0 in H4;inverts H4.\n  rewrite EcbMod.emp_sem in H13;tryfalse.\nQed.\n\nTheorem Old_Priority_Inversion_Free_Proof':\n  forall client_code T cst O T' cst' O',\n    InitTasks T client_code cst O ->\n    init_st O ->\n    good_client_code client_code ->\n    no_nest_client client_code O T cst ->\n    hpstepstar (client_code, os_spec') T cst O T' cst' O' ->\n    OLD_PIF O'.\nProof.\n  intros.\n  lets Hx: GOOD_ST_Prop H H0 H1 H2 H3.\n  unfolds in Hx.\n  unfolds.\n  intros.\n  unfolds.\n  intro.\n  lets Hy :Hx H4 H5.\n  mytac.\n  unfolds in H6.\n  unfolds in H11.\n  mytac.\n  unfolds in H6.\n  mytac.\n  rewrite H6 in H13;inverts H13.\n  lets Hz:H11 H6.\n  mytac.\n  unfolds in H13.\n  mytac.\n  rewrite H13 in H16;inverts H16.\n  rewrite H14 in H17;inverts H17.\n  clear -H15 H18.\n  int auto.\nQed.\n\n\nDefinition O_PI_CHAIN tls els :=\n  exists t t_owner p p_owner st st_owner msg msg_owner,\n    WAIT_CHAIN t t_owner tls els /\\\n    TcbMod.get tls t = Some (p,st,msg) /\\\n    TcbMod.get tls t_owner = Some (p_owner,st_owner,msg_owner) /\\\n    Int.ltu p p_owner = true.\n\nDefinition O_PIF_CHAIN tls els := ~ O_PI_CHAIN tls els.\n\nDefinition OLD_PIF_CHAIN O:=\n  forall els tls,\n    OSAbstMod.get O absecblsid = Some (absecblist els) ->\n    OSAbstMod.get O abtcblsid = Some (abstcblist tls) ->\n    O_PIF_CHAIN tls els.\n\n  \nDefinition UPIF (O:osabst) :=\n  forall els tls ct p_ct,\n    OSAbstMod.get O absecblsid = Some (absecblist els) ->\n    OSAbstMod.get O abtcblsid = Some (abstcblist tls) ->\n    OSAbstMod.get O curtid = Some (oscurt ct) ->\n    GET_OP ct tls els p_ct ->\n    ~ (exists eid, IS_OWNER ct eid els)  ->\n    forall t p_t,\n      t <> ct ->\n      TcbMod.get tls t <> None ->\n      GET_OP t tls els p_t ->\n      (exists t', WAIT_CHAIN t t' tls els) ->\n      Int.ltu p_ct p_t = true \\/ Int.eq p_ct p_t = true.\n\nTheorem Unbounded_Priority_Inversion_Free_Proof:\n  forall client_code T cst O T' cst' O',\n    InitTasks T client_code cst O ->\n    init_st O ->\n    good_client_code client_code ->\n    no_nest_client client_code O T cst ->\n    hpstepstar (client_code, os_spec') T cst O T' cst' O' ->\n    PREEMP O' ->\n    UPIF O'.\nProof.\n  intros.\n  rename H4 into Hpreemp.\n  unfolds;intros.\n  left.\n  eapply Priority_Inversion_Free_Proof;eauto.\n  assert (GOOD_ST O').\n  eapply GOOD_ST_Prop;eauto.\n  unfolds in H13.\n  lets Hx:H13 H4 H5.\n  mytac.\n  clear H13.  \n\n  inverts H12.\n  destruct H13.\n  unfolds in H12.\n  mytac.\n  unfolds in H14.\n  mytac.\n  apply H21 in H12.\n  unfolds in H12;unfolds.\n  mytac;do 4 eexists;eauto.\n  unfolds in H13.\n  mytac.\n  unfolds in H14.\n  mytac.\n  apply H21 in H12.\n  unfolds in H12;unfolds;mytac.\n  do 4 eexists;eauto.\nQed.\n\nTheorem Old_Priority_Inversion_Free_Proof:\n  forall client_code T cst O T' cst' O',\n    InitTasks T client_code cst O ->\n    init_st O ->\n    good_client_code client_code ->\n    no_nest_client client_code O T cst ->\n    hpstepstar (client_code, os_spec') T cst O T' cst' O' ->\n    OLD_PIF_CHAIN O'.\nProof.\n  intros.\n  lets Hx: GOOD_ST_Prop H H0 H1 H2 H3.\n  lets Hy: Old_Priority_Inversion_Free_Proof' H H0 H1 H2 H3.\n  unfolds.\n  intros.\n  unfolds.\n  intro.\n  unfolds in Hy.\n  lets Hz:Hy H4 H5.\n  unfolds in Hz.\n  destruct Hz.\n  unfolds in H6.\n  unfolds.\n  mytac.\n  exists x x0;do 6 eexists;splits;eauto.\n  inverts H6.\n  destruct H10;auto.\n  unfolds in H10.\n  mytac.\n  unfolds in H2.\n  lets Hw:H2 H3.\n  unfolds in Hw.\n  lets Hv:Hw H4 H5.\n  unfolds in Hv.\n  \n  inverts H11.\n  destruct H12.\n  unfolds in H11.\n  mytac.\n  assert (TcbMod.get tls t' <> None).\n  intro.\n  rewrite H14 in H11;inverts H11.\n  eapply Hv with (qid:=x7) in H14;eauto.\n  destruct H14.\n  destruct H14.\n  unfolds in Hx.\n\n  lets Hu: Hx H4 H5.\n  mytac.\n  unfolds in H14.\n  destructs H14.\n  apply H21 in H11.\n  unfolds in H11.\n  unfolds.\n  mytac;do 4 eexists;eauto.\n  unfolds.\n  do 3 eexists;eauto.\n  \n  unfolds in H12.\n  mytac.\n  assert (TcbMod.get tls t' <> None).\n  intro.\n  rewrite H14 in H11;inverts H11.\n  eapply Hv with (qid:=x7) in H14;eauto.\n  destruct H14.\n  destruct H14.\n  unfolds in Hx.\n\n  lets Hu: Hx H4 H5.\n  mytac.\n  unfolds in H14.\n  destructs H14.\n  apply H21 in H11.\n  unfolds in H11.\n  unfolds.\n  mytac;do 4 eexists;eauto.\n  unfolds.\n  do 3 eexists;eauto.\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/spec/pif_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2976840509151863}}
{"text": "From algebra Require Export auth upred_tactics.\nFrom program_logic Require Export invariants ghost_ownership.\nImport uPred.\n\n(* The CMRA we need. *)\nClass authG Λ Σ (A : cmraT) `{Empty A} := AuthG {\n  auth_inG :> inG Λ Σ (authR A);\n  auth_identity :> CMRAUnit A;\n  auth_timeless :> CMRADiscrete A;\n}.\n(* The Functor we need. *)\nDefinition authGF (A : cmraT) : gFunctor := GFunctor (constRF (authR A)).\n(* Show and register that they match. *)\nInstance authGF_inGF (A : cmraT) `{inGF Λ Σ (authGF A)}\n  `{CMRAUnit A, CMRADiscrete A} : authG Λ Σ A.\nProof. split; try apply _. apply: inGF_inG. Qed.\n\nSection definitions.\n  Context `{authG Λ Σ A} (γ : gname).\n  Definition auth_own  (a : A) : iPropG Λ Σ :=\n    own γ (◯ a).\n  Definition auth_inv (φ : A → iPropG Λ Σ) : iPropG Λ Σ :=\n    (∃ a, own γ (● a) ★ φ a)%I.\n  Definition auth_ctx (N : namespace) (φ : A → iPropG Λ Σ) : iPropG Λ Σ :=\n    inv N (auth_inv φ).\n\n  Global Instance auth_own_ne n : Proper (dist n ==> dist n) auth_own.\n  Proof. solve_proper. Qed.\n  Global Instance auth_own_proper : Proper ((≡) ==> (≡)) auth_own.\n  Proof. solve_proper. Qed.\n  Global Instance auth_own_timeless a : TimelessP (auth_own a).\n  Proof. apply _. Qed.\n  Global Instance auth_ctx_always_stable N φ : AlwaysStable (auth_ctx N φ).\n  Proof. apply _. Qed.\nEnd definitions.\n\nTypeclasses Opaque auth_own auth_ctx.\nInstance: Params (@auth_inv) 6.\nInstance: Params (@auth_own) 6.\nInstance: Params (@auth_ctx) 7.\n\nSection auth.\n  Context `{AuthI : authG Λ Σ A}.\n  Context (φ : A → iPropG Λ Σ) {φ_proper : Proper ((≡) ==> (≡)) φ}.\n  Implicit Types N : namespace.\n  Implicit Types P Q R : iPropG Λ Σ.\n  Implicit Types a b : A.\n  Implicit Types γ : gname.\n\n  Lemma auth_own_op γ a b :\n    auth_own γ (a ⋅ b) ≡ (auth_own γ a ★ auth_own γ b)%I.\n  Proof. by rewrite /auth_own -own_op auth_frag_op. Qed.\n  Lemma auth_own_valid γ a : auth_own γ a ⊑ ✓ a.\n  Proof. by rewrite /auth_own own_valid auth_validI. Qed.\n\n  Lemma auth_alloc N E a :\n    ✓ a → nclose N ⊆ E →\n    ▷ φ a ⊑ (|={E}=> ∃ γ, auth_ctx γ N φ ∧ auth_own γ a).\n  Proof.\n    intros Ha HN. eapply sep_elim_True_r.\n    { by eapply (own_alloc (Auth (Excl a) a) E). }\n    rewrite pvs_frame_l. apply pvs_strip_pvs.\n    rewrite sep_exist_l. apply exist_elim=>γ. rewrite -(exist_intro γ).\n    trans (▷ auth_inv γ φ ★ auth_own γ a)%I.\n    { rewrite /auth_inv -(exist_intro a) later_sep.\n      ecancel [▷ φ _]%I.\n      by rewrite -later_intro -own_op auth_both_op. }\n    rewrite (inv_alloc N E) // /auth_ctx pvs_frame_r. apply pvs_mono.\n    by rewrite always_and_sep_l.\n  Qed.\n\n  Lemma auth_empty γ E : True ⊑ |={E}=> auth_own γ ∅.\n  Proof. by rewrite -own_empty. Qed.\n\n  Lemma auth_opened E γ a :\n    (▷ auth_inv γ φ ★ auth_own γ a)\n    ⊑ (|={E}=> ∃ a', ✓ (a ⋅ a') ★ ▷ φ (a ⋅ a') ★ own γ (● (a ⋅ a') ⋅ ◯ a)).\n  Proof.\n    rewrite /auth_inv. rewrite later_exist sep_exist_r. apply exist_elim=>b.\n    rewrite later_sep [(▷ own _ _)%I]pvs_timeless !pvs_frame_r. apply pvs_mono.\n    rewrite own_valid_l discrete_valid -!assoc. apply const_elim_sep_l=>Hv.\n    rewrite [(▷φ _ ★ _)%I]comm assoc -own_op.\n    rewrite own_valid_r auth_validI /= and_elim_l sep_exist_l sep_exist_r /=.\n    apply exist_elim=>a'.\n    rewrite left_id -(exist_intro a').\n    apply (eq_rewrite b (a ⋅ a') (λ x, ✓ x ★ ▷ φ x ★ own γ (● x ⋅ ◯ a))%I).\n    { by move=>n x y /timeless_iff ->. }\n    { by eauto with I. }\n    rewrite -valid_intro; last by apply Hv.\n    rewrite left_id comm. auto with I.\n  Qed.\n\n  Lemma auth_closing `{!LocalUpdate Lv L} E γ a a' :\n    Lv a → ✓ (L a ⋅ a') →\n    (▷ φ (L a ⋅ a') ★ own γ (● (a ⋅ a') ⋅ ◯ a))\n    ⊑ (|={E}=> ▷ auth_inv γ φ ★ auth_own γ (L a)).\n  Proof.\n    intros HL Hv. rewrite /auth_inv -(exist_intro (L a ⋅ a')).\n    (* TODO it would be really nice to use cancel here *)\n    rewrite later_sep [(_ ★ ▷φ _)%I]comm -assoc.\n    rewrite -pvs_frame_l. apply sep_mono_r.\n    rewrite -later_intro -own_op.\n    by apply own_update, (auth_local_update_l L).\n  Qed.\n\n  Context {V} (fsa : FSA Λ (globalF Σ) V) `{!FrameShiftAssertion fsaV fsa}.\n\n  Lemma auth_fsa E N P (Ψ : V → iPropG Λ Σ) γ a :\n    fsaV →\n    nclose N ⊆ E →\n    P ⊑ auth_ctx γ N φ →\n    P ⊑ (▷ auth_own γ a ★ ∀ a',\n          ■ ✓ (a ⋅ a') ★ ▷ φ (a ⋅ a') -★\n          fsa (E ∖ nclose N) (λ x, ∃ L Lv (Hup : LocalUpdate Lv L),\n            ■ (Lv a ∧ ✓ (L a ⋅ a')) ★ ▷ φ (L a ⋅ a') ★\n            (auth_own γ (L a) -★ Ψ x))) →\n    P ⊑ fsa E Ψ.\n  Proof.\n    rewrite /auth_ctx=>? HN Hinv Hinner.\n    eapply (inv_fsa fsa); eauto. rewrite Hinner=>{Hinner Hinv P HN}.\n    apply wand_intro_l. rewrite assoc.\n    rewrite (pvs_timeless (E ∖ N)) pvs_frame_l pvs_frame_r.\n    apply (fsa_strip_pvs fsa).\n    rewrite (auth_opened (E ∖ N)) !pvs_frame_r !sep_exist_r.\n    apply (fsa_strip_pvs fsa). apply exist_elim=>a'.\n    rewrite (forall_elim a'). rewrite [(▷_ ★ _)%I]comm.\n    eapply wand_apply_r; first (by eapply (wand_frame_l (own γ _))); last first.\n    { rewrite assoc [(_ ★ own _ _)%I]comm -assoc discrete_valid.  done. }\n    rewrite fsa_frame_l.\n    apply (fsa_mono_pvs fsa)=> x.\n    rewrite sep_exist_l; apply exist_elim=> L.\n    rewrite sep_exist_l; apply exist_elim=> Lv.\n    rewrite sep_exist_l; apply exist_elim=> ?.\n    rewrite comm -!assoc. apply const_elim_sep_l=>-[HL Hv].\n    rewrite assoc [(_ ★ (_ -★ _))%I]comm -assoc.\n    rewrite (auth_closing (E ∖ N)) //; [].\n    rewrite pvs_frame_l. apply pvs_mono.\n    by rewrite assoc [(_ ★ ▷_)%I]comm -assoc wand_elim_l.\n  Qed.\n  Lemma auth_fsa' L `{!LocalUpdate Lv L} E N P (Ψ : V → iPropG Λ Σ) γ a :\n    fsaV →\n    nclose N ⊆ E →\n    P ⊑ auth_ctx γ N φ →\n    P ⊑ (▷ auth_own γ a ★ (∀ a',\n          ■ ✓ (a ⋅ a') ★ ▷ φ (a ⋅ a') -★\n          fsa (E ∖ nclose N) (λ x,\n            ■ (Lv a ∧ ✓ (L a ⋅ a')) ★ ▷ φ (L a ⋅ a') ★\n            (auth_own γ (L a) -★ Ψ x)))) →\n    P ⊑ fsa E Ψ.\n  Proof.\n    intros ??? HP. eapply auth_fsa with N γ a; eauto.\n    rewrite HP; apply sep_mono_r, forall_mono=> a'.\n    apply wand_mono; first done. apply (fsa_mono fsa)=> b.\n    rewrite -(exist_intro L). by repeat erewrite <-exist_intro by apply _.\n  Qed.\nEnd auth.\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/program_logic/auth.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2976840509151863}}
{"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 RVIC.Spec.\nRequire Import RVIC2.Specs.rvic_is_pending.\nRequire Import RVIC2.LowSpecs.rvic_is_pending.\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       get_rvic_pending_bits_spec\n       rvic_test_flag_spec\n    .\n\n  Lemma rvic_is_pending_spec_exists:\n    forall habd  labd rvic intid res\n           (Hspec: rvic_is_pending_spec rvic intid habd = Some res)\n            (Hrel: relate_RData habd labd),\n    rvic_is_pending_spec0 rvic intid labd = Some res.\n  Proof.\n    intros. inv Hrel. destruct rvic.\n    unfold rvic_is_pending_spec, rvic_is_pending_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); 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_is_pending.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.29768404434614676}}
{"text": "(** * Facts about the elaboration of the Transition design's generic constants *)\n\nRequire Import common.CoqLib.\nRequire Import common.NatMap.\nRequire Import common.proofs.NatMapTactics.\n\nRequire Import hvhdl.HVhdlCoreLib.\nRequire Import hvhdl.HVhdlHilecopLib.\nRequire Import hvhdl.HVhdlElaborationLib.\nRequire Import hvhdl.proofs.HVhdlElaborationFactsLib.\n\n(** ** Facts about the [input_arcs_number] generic constant *)\n\nLemma EGen_in_arcs_nb_1 :\n  forall {Δ M__g Δ'},\n    EGen Δ M__g (gdecl_ Transition.input_arcs_number (tind_natural 0 NATMAX) 1) Δ' ->\n    exists t n, MapsTo Transition.input_arcs_number (Generic t (Vnat n)) Δ'.\nProof.\n  inversion_clear 1.\n  inversion_clear H2 in H3.\n  inversion_clear H3 in H4.\n  inversion_clear H4 in H6.\n  exists (Tnat l u), n; eauto with mapsto.\n  inversion_clear H2.\n  exists t0, 1; eauto with mapsto.\nQed.\n\nLemma EGens_T_Δ_in_arcs_nb_1 :\n  forall {Δ M__g Δ'},\n    EGens Δ M__g transition_gens Δ' ->\n    exists t n, MapsTo Transition.input_arcs_number (Generic t (Vnat n)) Δ'.\nProof.\n  inversion_clear 1.\n  inversion_clear H1.\n  edestruct @EGen_in_arcs_nb_1 with (Δ := Δ'0) as (t, (n, MapsTo_ian)); eauto.\n  exists t, n; eapply EGens_inv_Δ; eauto.\nQed.\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/TGenericElaborationFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.661922862511608, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.29746325899654646}}
{"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 sovar.\nRequire Export alphaeq_sub.\n\n\nLemma range_combine {o} :\n  forall (ts : list (@NTerm o)) vs,\n    length vs = length ts\n    -> range (combine vs ts) = ts.\nProof.\n  induction ts; destruct vs; introv len; allsimpl; cpx.\n  rw IHts; sp.\nQed.\n\nLemma swap_apply_list {o} :\n  forall ts (t : @NTerm o) s,\n    swap s (apply_list t ts) = apply_list (swap s t) (map (swap s) ts).\nProof.\n  induction ts; simpl; introv; auto.\n  rw IHts; simpl; auto.\nQed.\n\nFixpoint so_swap {p} (l : swapping) (t : @SOTerm p) :=\n  match t with\n    | sovar v ts =>\n      if bnull ts\n      then sovar (swapvar l v) []\n      else sovar v (map (so_swap l) ts)\n    | soterm o bts => soterm o (map (so_swapbt l) bts)\n  end\nwith so_swapbt {p} (l : swapping) (bt : SOBTerm) :=\n  match bt with\n    | sobterm vs t => sobterm (swapbvars l vs) (so_swap l t)\n  end.\n\n(*\nLemma soterm2nterm_so_swap {o} :\n  forall (t : @SOTerm o) s,\n    soterm2nterm (so_swap s t) = swap s (soterm2nterm t).\nProof.\n  soterm_ind t as [ v ts ind | op lbt ind ] Case; simpl; introv.\n\n  - Case \"sovar\".\n    rw @swap_apply_list; simpl.\n    allrw map_map; unfold compose.\n    f_equal.\n    apply eq_maps; introv i.\n    eapply ind in i; eauto.\n\n  - Case \"soterm\".\n    apply f_equal.\n    allrw map_map; unfold compose.\n    apply eq_maps; introv i.\n    destruct x; allsimpl.\n    f_equal.\n    eapply ind in i; eauto.\nQed.\n*)\n\nLemma wf_soterm_so_swap {o} :\n  forall (t : @SOTerm o) s,\n    wf_soterm t <=> wf_soterm (so_swap s t).\nProof.\n  soterm_ind t as [ v ts ind | op lbt ind ] Case; simpl; introv.\n\n  - Case \"sovar\".\n    boolvar; subst; allsimpl; allrw @wf_sovar; tcsp.\n    split; introv k i; allsimpl.\n    + rw in_map_iff in i; exrepnd; subst.\n        apply ind; auto.\n    + pose proof (k (so_swap s t)) as h; autodimp h hyp.\n      rw in_map_iff; eexists; dands; eauto.\n      apply ind in h; tcsp.\n\n  - Case \"soterm\".\n    allrw @wf_soterm_iff; split; intro k; repnd; dands.\n    + rw <- k0.\n      rw map_map; unfold compose; apply eq_maps; introv i.\n      destruct x; simpl.\n      rw length_swapbvars; auto.\n    + introv i.\n      rw in_map_iff in i; exrepnd; subst.\n      destruct a; allsimpl; ginv.\n      dup i1 as i.\n      eapply ind in i; rw <- i.\n      apply k in i1; auto.\n    + rw <- k0.\n      rw map_map; unfold compose; apply eq_maps; introv i.\n      destruct x; simpl.\n      rw length_swapbvars; auto.\n    + introv i.\n      pose proof (k (swapbvars s vs) (so_swap s t)) as h; autodimp h hyp.\n      rw in_map_iff; eexists; dands; eauto.\n      dup i as j.\n      eapply ind in i; rw <- i in h; auto.\nQed.\n\nInductive so_alphaeq_vs {p} (l : list NVar) : @SOTerm p -> @SOTerm p -> Type :=\n  | soaeqv :\n      forall v ts1 ts2,\n        length ts1 = length ts2\n        -> (forall t1 t2, LIn (t1,t2) (combine ts1 ts2) -> so_alphaeq_vs l t1 t2)\n        -> so_alphaeq_vs l (sovar v ts1) (sovar v ts2)\n  | soaeqo :\n      forall o bts1 bts2,\n        length bts1 = length bts2\n        -> (forall b1 b2,\n              LIn (b1,b2) (combine bts1 bts2)\n              -> so_alphaeqbt_vs l b1 b2)\n        -> so_alphaeq_vs l (soterm o bts1) (soterm o bts2)\nwith so_alphaeqbt_vs {p} (l : list NVar) : @SOBTerm p -> @SOBTerm p -> Type :=\n | soaeqbt :\n     forall vs vs1 vs2 t1 t2,\n       length vs = length vs1\n       -> length vs = length vs2\n       -> disjoint vs (l ++ vs1 ++ vs2 ++ all_fo_vars t1 ++ all_fo_vars t2)\n       -> no_repeats vs\n       -> so_alphaeq_vs l (so_swap (mk_swapping vs1 vs) t1) (so_swap (mk_swapping vs2 vs) t2)\n       -> so_alphaeqbt_vs l (sobterm vs1 t1) (sobterm vs2 t2).\nHint Constructors so_alphaeq_vs.\nHint Constructors so_alphaeqbt_vs.\n\nDefinition so_alphaeq {p} := @so_alphaeq_vs p [].\nDefinition so_alphaeqbt {p} := @so_alphaeqbt_vs p [].\n\nDefinition alphaeq_sk {o} (sk1 sk2 : @sosub_kind o) :=\n  alphaeqbt (sk2bterm sk1) (sk2bterm sk2).\n\nLemma alphaeq_sk_iff_alphaeq_bterm {o} :\n  forall vs1 vs2 (t1 t2 : @NTerm o),\n    alphaeqbt (bterm vs1 t1) (bterm vs2 t2)\n    <=> alphaeq_sk (sosk vs1 t1) (sosk vs2 t2).\nProof. sp. Qed.\n\nLemma symm_rel_alphaeq_sk {o} :\n  symm_rel (@alphaeq_sk o).\nProof.\n  unfold alphaeq_sk, symm_rel; introv h.\n  apply alphaeqbt_eq.\n  apply alpha_eq_bterm_sym.\n  apply alphaeqbt_eq; auto.\nQed.\nHint Immediate symm_rel_alphaeq_sk.\n\nLemma alphaeq_sk_eq_length {o} :\n  forall (a b : @sosub_kind o),\n    alphaeq_sk a b -> length (sosk_vs a) = length (sosk_vs b).\nProof.\n  introv aeq.\n  invertsn aeq; auto.\n  destruct a, b; allsimpl; ginv; omega.\nQed.\n\nDefinition default_soterm {o} : @SOTerm o := soterm (Can NAxiom) [].\nDefinition default_sobterm {o} : @SOBTerm o := sobterm [] default_soterm.\nDefinition default_sk {o} : @sosub_kind o := sosk [] mk_axiom.\n\nDefinition bin_rel_sk {p} := binrel_list (@default_sk p).\n\nLemma binrel_list_sym  :\n  forall T (def : T) R,\n    symm_rel R\n    -> symm_rel (binrel_list def R).\nProof.\n  unfold binrel_list; introv sr h; allsimpl; repnd; dands; auto.\n  introv k; rw <- h0 in k; apply h in k.\n  apply sr; auto.\nQed.\n\nLemma bin_rel_sk_sym {o} :\n  forall R, symm_rel R -> symm_rel (@bin_rel_sk o R).\nProof.\n  unfold bin_rel_sk; introv sr h.\n  apply binrel_list_sym; auto.\nQed.\n\nLemma bin_rel_sk_cons {o} :\n  forall (sk1 sk2 : @sosub_kind o) sks1 sks2,\n    bin_rel_sk alphaeq_sk (sk1 :: sks1) (sk2 :: sks2)\n    <=> (bin_rel_sk alphaeq_sk sks1 sks2 # alphaeq_sk sk1 sk2).\nProof.\n  introv; unfold bin_rel_sk, binrel_list; simpl.\n  split; intro k; repnd; cpx; dands; auto.\n  - introv i.\n    pose proof (k (S n)) as h; autodimp h hyp; omega.\n  - pose proof (k 0) as h; autodimp h hyp; omega.\n  - introv i.\n    destruct n; cpx.\nQed.\n\nLemma alphaeq_sosub_kind_if_alphaeq_sosub_find {o} :\n  forall (vs : list NVar) (sks1 sks2 : list (@sosub_kind o)) (sk1 sk2 : sosub_kind) (sv : sovar_sig),\n    length vs = length sks1\n    -> length vs = length sks2\n    -> bin_rel_sk alphaeq_sk sks1 sks2\n    -> sosub_find (combine vs sks1) sv = Some sk1\n    -> sosub_find (combine vs sks2) sv = Some sk2\n    -> alphaeq_sk sk1 sk2.\nProof.\n  induction vs; introv len1 len2 aeq f1 f2; allsimpl; cpx.\n  destruct sks1; destruct sks2; allsimpl; cpx.\n  apply binrel_list_cons in aeq; repnd.\n  fold (@bin_rel_sk o) in aeq0.\n  applydup @alphaeq_sk_eq_length in aeq; allsimpl.\n\n  destruct s; destruct s0; boolvar; allsimpl; cpx;\n  try (complete (provefalse; apply n1; sp)).\n\n  apply IHvs with (sks1 := sks1) (sks2 := sks2) (sv := sv); auto.\nQed.\n\nLemma false_if_alphaeq_sosub_find {o} :\n  forall (vs : list NVar) (sks1 sks2 : list (@sosub_kind o)) (sk : sosub_kind) (sv : sovar_sig),\n    length vs = length sks1\n    -> length vs = length sks2\n    -> bin_rel_sk alphaeq_sk sks1 sks2\n    -> sosub_find (combine vs sks1) sv = Some sk\n    -> sosub_find (combine vs sks2) sv = None\n    -> False.\nProof.\n  induction vs; introv len1 len2 aeq f1 f2; allsimpl; cpx.\n  destruct sks1; destruct sks2; allsimpl; cpx.\n  apply binrel_list_cons in aeq; repnd.\n  fold (@bin_rel_sk o) in aeq0.\n  applydup @alphaeq_sk_eq_length in aeq; allsimpl.\n\n  destruct s; destruct s0; boolvar; allsimpl; cpx;\n  try (complete (provefalse; apply n1; sp)).\n\n  eapply IHvs in f1; eauto.\nQed.\n\nLemma alphaeq_apply_list {o} :\n  forall ts1 ts2 (t1 t2 : @NTerm o),\n    alphaeq t1 t2\n    -> bin_rel_nterm alpha_eq ts1 ts2\n    -> alphaeq (apply_list t1 ts1) (apply_list t2 ts2).\nProof.\n  induction ts1; introv aeq brel; destruct ts2; allsimpl; tcsp.\n  - unfold bin_rel_nterm, binrel_list in brel; repnd; allsimpl; cpx.\n  - unfold bin_rel_nterm, binrel_list in brel; repnd; allsimpl; cpx.\n  - apply binrel_list_cons in brel; repnd.\n    apply IHts1; auto.\n    apply alphaeq_eq.\n    apply alphaeq_eq in aeq.\n    prove_alpha_eq4.\n    introv h; destruct n0.\n    + apply alphaeqbt_nilv2; auto.\n    + destruct n0; sp.\n      apply alphaeqbt_nilv2; auto.\nQed.\n\nLemma sosize_so_swap {p} :\n  forall (t : @SOTerm p) l,\n    sosize (so_swap l t) = sosize t.\nProof.\n  soterm_ind1 t as [v ts Hind | o bts Hind] Case; introv; simpl; auto.\n  - boolvar; subst; simpl; auto.\n    f_equal; f_equal.\n    rw map_map; unfold compose.\n    apply eq_maps; introv i.\n    apply Hind; sp.\n  - f_equal; f_equal.\n    rw map_map; unfold compose.\n    apply eq_maps; introv i.\n    destruct x; simpl.\n    eapply Hind; eauto.\nQed.\n\nLemma sosize_so_swap_le {o} :\n  forall (t : @SOTerm o) sw,\n    sosize (so_swap sw t) <= sosize t.\nProof.\n  introv; rw @sosize_so_swap; sp.\nQed.\n\nLemma disjoint_all_fo_vars_so_swap {p} :\n  forall (t : @SOTerm p) vs vs1 vs2,\n    length vs1 = length vs2\n    -> disjoint vs vs1\n    -> disjoint vs vs2\n    -> disjoint vs (all_fo_vars t)\n    -> disjoint vs (all_fo_vars (so_swap (mk_swapping vs1 vs2) t)).\nProof.\n  soterm_ind1s t as [v ts Hind | o lbt Hind] Case; introv len disj1 disj2 disj3; allsimpl.\n\n  - Case \"sovar\".\n    boolvar; subst; simpl.\n    + allrw disjoint_cons_r; repnd; dands; auto.\n      intro k; apply in_swapvar_disj_iff2 in k; auto.\n    + allsimpl; allrw disjoint_cons_r; repnd.\n      dands; auto.\n      rw flat_map_map; unfold compose.\n      allrw disjoint_flat_map_r; introv i.\n      eapply Hind; eauto.\n\n  - Case \"soterm\".\n    rw flat_map_map.\n    rw disjoint_flat_map_r in disj3.\n    apply disjoint_flat_map_r; introv i.\n    applydup disj3 in i as d.\n    destruct x; unfold compose; allsimpl.\n    allrw disjoint_app_r; repnd.\n    dands; try (complete (eapply Hind; eauto)).\n    apply disjoint_swapbvars; auto.\nQed.\n\nLemma so_swap_so_swap {p} :\n  forall s1 s2 (t : @SOTerm p),\n    so_swap s1 (so_swap s2 t) = so_swap (s2 ++ s1) t.\nProof.\n  soterm_ind1 t as [v ts Hind | o lbt Hind] Case; simpl.\n\n  - Case \"sovar\".\n    boolvar; subst; allsimpl; boolvar; allsimpl; auto; tcsp;\n    try (complete (rw swapvar_swapvar; auto));\n    try (complete (destruct ts; allsimpl; tcsp)).\n    f_equal.\n    rw map_map; unfold compose.\n    apply eq_maps; introv i.\n    apply Hind; auto.\n\n  - Case \"soterm\".\n    f_equal.\n    rw map_map; unfold compose.\n    apply eq_maps; introv i.\n    destruct x; simpl.\n    apply Hind in i.\n    rw i.\n    rw swapbvars_swapbvars; auto.\nQed.\n\nLemma so_swap_app_so_swap {p} :\n  forall (t : @SOTerm p) vs1 vs2 vs3 vs4,\n    length vs1 = length vs3\n    -> length vs2 = length vs4\n    -> no_repeats vs3\n    -> no_repeats vs4\n    -> disjoint vs3 vs1\n    -> disjoint vs3 vs2\n    -> disjoint vs3 vs4\n    -> disjoint vs3 (all_fo_vars t)\n    -> disjoint vs4 (all_fo_vars t)\n    -> disjoint vs2 vs4\n    -> disjoint vs1 vs4\n    -> so_swap (mk_swapping (vs1 ++ vs2) (vs3 ++ vs4)) t\n       = so_swap\n           (mk_swapping (vs2 ++ swapbvars (mk_swapping vs2 vs4) vs1)\n                        (vs4 ++ vs3))\n           t.\nProof.\n  soterm_ind1s t as [v ts Hind | o lbt Hind] Case;\n  introv len1 len2 norep2 norep3;\n  introv disj1 disj2 disj3 disj4 disj5 disj6 disj7.\n\n  - Case \"sovar\".\n    allsimpl; boolvar; subst; allsimpl.\n    + allrw disjoint_singleton_r; repnd.\n      rw swapvar_app_swap; auto.\n    + allrw disjoint_cons_r; repnd.\n      allrw disjoint_flat_map_r.\n      apply f_equal.\n      apply eq_maps; introv i.\n      apply Hind; auto.\n\n  - Case \"soterm\".\n    simpl.\n    f_equal.\n    apply eq_maps; introv i.\n    destruct x; simpl.\n    allsimpl.\n    allrw disjoint_flat_map_r.\n    applydup disj4 in i as d1.\n    applydup disj5 in i as d2.\n    allsimpl; allrw disjoint_app_r; repnd.\n\n    rw <- swapbvars_app_swap; auto.\n\n    f_equal.\n    eapply Hind; eauto.\nQed.\n\nLemma so_alphaeq_add_so_swap {p} :\n  forall vs vs1 vs2 (t1 t2 : @SOTerm p),\n    length vs1 = length vs2\n    -> no_repeats vs2\n    -> disjoint vs2 (vs1 ++ all_fo_vars t1 ++ all_fo_vars t2)\n    -> so_alphaeq_vs (vs1 ++ vs2 ++ vs) t1 t2\n    -> so_alphaeq_vs\n         (vs1 ++ vs2 ++ vs)\n         (so_swap (mk_swapping vs1 vs2) t1)\n         (so_swap (mk_swapping vs1 vs2) t2).\nProof.\n  soterm_ind1s t1 as [v1 ts1 Hind | o1 lbt1 Hind] Case; introv len norep2 disj aeq.\n\n  - Case \"sovar\".\n    inversion aeq as [? ? ? e imp|]; clear aeq; subst; allsimpl; auto.\n    boolvar; subst; allsimpl; tcsp;\n    try (complete (destruct ts2; allsimpl; cpx));\n    try (complete (destruct ts1; allsimpl; cpx)).\n    constructor; [allrw map_length; complete auto|].\n    introv i.\n    rw <- @map_combine in i.\n    rw in_map_iff in i; exrepnd; cpx; allsimpl.\n    applydup in_combine in i1; repnd.\n    apply Hind; auto.\n    repeat (first [ progress (allrw disjoint_app_r)\n                  | progress (allrw disjoint_cons_r)\n                  | progress (allrw disjoint_flat_map_r)\n           ]); repnd.\n    dands; auto.\n\n  - Case \"soterm\".\n    allsimpl.\n    inversion aeq as [|? ? ? eqlens aeqbts e1 oeq]; subst; clear aeq.\n    allsimpl.\n    apply soaeqo; allrw map_length; auto.\n    introv lt.\n    rw <- @map_combine in lt; rw in_map_iff in lt; exrepnd; cpx; allsimpl.\n    applydup aeqbts in lt1 as aeq; repnd.\n    destruct a0 as [bvs1 t1].\n    destruct a  as [bvs2 t2].\n    allsimpl.\n    applydup in_combine in lt1; repnd.\n    inversion aeq as [? ? ? ? ? leneq1 leneq2 d n a]; subst; clear aeq.\n    allrw disjoint_app_r; repnd.\n    allrw disjoint_flat_map_r.\n    applydup disj1 in lt2.\n    applydup disj in lt0.\n    allsimpl; allrw disjoint_app_r; repnd.\n\n    apply Hind with (vs0 := bvs1) (t := t1) in a; auto; allrw @sosize_so_swap; auto;\n    try (complete (allrw disjoint_app_r; dands; auto;\n                   apply disjoint_all_fo_vars_so_swap; auto;\n                   try (apply disjoint_sym; auto))).\n\n    repeat (rw @so_swap_so_swap in a).\n    repeat (rw mk_swapping_app in a; auto).\n\n    apply @soaeqbt with (vs := vs0); auto;\n    try (complete (rw length_swapbvars; omega)).\n\n    allrw disjoint_app_r; repnd.\n    pose proof (disjoint_swapbvars bvs1 vs0 vs1 vs2) as h1;\n      repeat (autodimp h1 hyp); try omega.\n    pose proof (disjoint_swapbvars bvs2 vs0 vs1 vs2) as h2;\n      repeat (autodimp h2 hyp); try omega.\n    pose proof (disjoint_all_fo_vars_so_swap t1 vs0 vs1 vs2) as h3;\n      repeat (autodimp h3 hyp); try omega.\n    pose proof (disjoint_all_fo_vars_so_swap t2 vs0 vs1 vs2) as h4;\n      repeat (autodimp h4 hyp); try omega.\n\n    allrw @so_swap_so_swap.\n    repeat (rw mk_swapping_app;[|complete omega]).\n\n    rw <- @so_swap_app_so_swap; auto; try (complete (apply disjoint_sym; auto)).\n    rw <- @so_swap_app_so_swap; auto; try (complete (apply disjoint_sym; auto)).\nQed.\n\nLemma so_swap_disj_chain {p} :\n  forall (t : @SOTerm p) vs1 vs vs2,\n    length vs = length vs1\n    -> length vs = length vs2\n    -> no_repeats vs\n    -> no_repeats vs2\n    -> disjoint vs (vs1 ++ vs2 ++ all_fo_vars t)\n    -> disjoint vs2 (vs1 ++ all_fo_vars t)\n    -> so_swap (mk_swapping (vs1 ++ vs) (vs ++ vs2)) t\n       = so_swap (mk_swapping vs1 vs2) t.\nProof.\n  soterm_ind1s t as [v ts Hind | o lbt Hind] Case;\n  introv len1 len2 norep1 norep2 disj1 disj2; allsimpl.\n\n  - Case \"sovar\".\n    allrw disjoint_app_r; allrw disjoint_cons_r; allrw disjoint_flat_map_r; repnd.\n    rw swapvar_disj_chain; auto;\n    try (complete (allrw disjoint_app_r; allrw disjoint_singleton_r; sp)).\n    boolvar; subst; allsimpl; tcsp.\n    f_equal.\n    apply eq_maps; introv i.\n    apply Hind; auto; allrw disjoint_app_r; sp.\n\n  - Case \"soterm\".\n    f_equal.\n    apply eq_maps; introv i.\n    destruct x; allsimpl.\n    allrw disjoint_app_r; repnd.\n    allrw disjoint_flat_map_r.\n    applydup disj1 in i; applydup disj2 in i; allsimpl.\n    allrw disjoint_app_r; repnd.\n    erewrite Hind; eauto; allrw disjoint_app_r; auto.\n    rw swapbvars_disj_chain; auto; allrw disjoint_app_r; auto.\nQed.\n\nLemma so_alphaeq_vs_implies_less {p} :\n  forall (t1 t2 : @SOTerm p) l1 l2,\n    so_alphaeq_vs l1 t1 t2\n    -> subvars l2 l1\n    -> so_alphaeq_vs l2 t1 t2.\nProof.\n  soterm_ind1s t1 as [v1 ts1 Hind | o1 lbt1 Hind] Case; introv aeq sv.\n\n  - Case \"sovar\".\n    inversion aeq as [? ? ? e imp|]; clear aeq; subst; auto.\n    constructor; auto.\n    introv i.\n    applydup imp in i.\n    apply in_combine in i; repnd.\n    eapply Hind; eauto.\n\n  - Case \"soterm\".\n    inversion aeq as [| ? ? ? len aeqbts]; subst; clear aeq.\n    constructor; auto.\n    introv i.\n    applydup aeqbts in i as h.\n    destruct b1 as [vs1 t1].\n    destruct b2 as [vs2 t2].\n    inversion h as [? ? ? ? ? len1 len2 disj norep a]; subst.\n    applydup in_combine in i; repnd.\n\n    pose proof (Hind\n                  t1\n                  (so_swap (mk_swapping vs1 vs) t1)\n                  vs1\n                  i1) as a1.\n\n    autodimp a1 hyp; try (complete (rw @sosize_so_swap; auto)).\n\n    pose proof (a1 (so_swap (mk_swapping vs2 vs) t2)\n                   l1\n                   l2\n                   a\n                   sv) as a2;\n      clear a1.\n\n    apply @soaeqbt with (vs := vs); auto; try omega.\n    allrw disjoint_app_r; repnd; dands; auto.\n\n    unfold disjoint; introv x y.\n    rw subvars_prop in sv.\n    apply disj0 in x.\n    apply sv in y; auto.\nQed.\n\nLemma so_alphaeq_implies_alphaeq_vs {p} :\n  forall t1 t2 : @SOTerm p, so_alphaeq t1 t2 -> forall l, so_alphaeq_vs l t1 t2.\nProof.\n  soterm_ind1s t1 as [v1 ts1 ind1 | o1 lbt1 ind1] Case; introv aeq; introv.\n\n  - Case \"sovar\".\n    inversion aeq as [? ? ? len imp|]; clear aeq; subst; auto.\n    constructor; auto.\n    introv i.\n    applydup imp in i.\n    apply ind1; auto.\n    apply in_combine in i; sp.\n\n  - inversion aeq as [| ? ? ? len aeqbts]; subst; clear aeq.\n    constructor; auto.\n    introv i.\n    applydup aeqbts in i as h.\n    destruct b1 as [l1 t1].\n    destruct b2 as [l2 t2].\n    inversion h as [? ? ? ? ? len1 len2 disj norep a]; subst.\n\n    pose proof (fresh_vars (length vs)\n                           (l ++ vs\n                              ++ l1\n                              ++ l2\n                              ++ all_fo_vars t1\n                              ++ all_fo_vars t2))\n      as Hfresh.\n    destruct Hfresh as [l' d]; repnd.\n\n    apply @soaeqbt with (vs := l'); auto; try omega.\n    allrw disjoint_app_r; sp.\n\n    applydup in_combine in i; repnd.\n    pose proof (ind1\n                  t1\n                  (so_swap (mk_swapping l1 vs) t1)\n                  l1\n                  i1) as a1.\n\n    autodimp a1 hyp.\n    rw @sosize_so_swap; auto.\n\n    pose proof (a1 (so_swap (mk_swapping l2 vs) t2)\n                   a\n                   (vs ++ l' ++ l)) as a2;\n      clear a1.\n\n    allsimpl.\n\n    assert (disjoint l' vs) as disj1 by (allrw disjoint_app_r; sp).\n    assert (disjoint l' (all_fo_vars (so_swap (mk_swapping l1 vs) t1)))\n      as disj2 by (allrw disjoint_app_r; repnd;\n                   apply disjoint_all_fo_vars_so_swap; auto).\n    assert (disjoint l' (all_fo_vars (so_swap (mk_swapping l2 vs) t2)))\n      as disj3 by (allrw disjoint_app_r; repnd;\n                   apply disjoint_all_fo_vars_so_swap; auto).\n\n    applydup @so_alphaeq_add_so_swap in a2; auto;\n    try (complete (allrw disjoint_app_r; auto)).\n\n    allrw @so_swap_so_swap.\n    repeat (rw mk_swapping_app in a0; try omega).\n\n    rw @so_swap_disj_chain in a0; auto;\n    try (complete (allrw disjoint_app_r; sp; try (complete (apply disjoint_sym; auto)))).\n\n    rw @so_swap_disj_chain in a0; auto;\n    try (complete (allrw disjoint_app_r; sp; try (complete (apply disjoint_sym; auto)))).\n\n    apply @so_alphaeq_vs_implies_less with (l1 := vs ++ l' ++ l); auto.\n    rw app_assoc; apply subvars_app_trivial_r.\nQed.\n\nLemma so_alphaeq_vs_implies_more {p} :\n  forall (t1 t2 : @SOTerm p) l1 l2,\n    so_alphaeq_vs l1 t1 t2\n    -> subvars l1 l2\n    -> so_alphaeq_vs l2 t1 t2.\nProof.\n  introv aeq sv.\n  apply @so_alphaeq_vs_implies_less with (l2 := []) in aeq; auto.\n  apply so_alphaeq_implies_alphaeq_vs; auto.\nQed.\n\nLemma so_alphaeq_all {p} :\n  forall t1 t2 : @SOTerm p, so_alphaeq t1 t2 <=> (forall l, so_alphaeq_vs l t1 t2).\nProof.\n  introv; split; intro k.\n  - introv; apply so_alphaeq_implies_alphaeq_vs; auto.\n  - pose proof (k []); auto.\nQed.\n\nLemma so_alphaeq_exists {p} :\n  forall t1 t2 : @SOTerm p, so_alphaeq t1 t2 <=> {l : list NVar & so_alphaeq_vs l t1 t2}.\nProof.\n  introv; split; intro k.\n  - exists ([] : list NVar); auto.\n  - exrepnd; apply so_alphaeq_vs_implies_less with (l1 := l); auto.\nQed.\n\nLemma so_alphaeqbt_vs_implies_more {p} :\n  forall (t1 t2 : @SOBTerm p) l1 l2,\n    so_alphaeqbt_vs l1 t1 t2\n    -> subvars l1 l2\n    -> so_alphaeqbt_vs l2 t1 t2.\nProof.\n  introv aeq sv.\n  pose proof (so_alphaeq_vs_implies_more (soterm Exc [t1]) (soterm Exc [t2]) l1 l2) as h.\n  autodimp h hyp.\n  - constructor; simpl; auto.\n    introv k; sp; cpx.\n  - autodimp h hyp.\n    inversion h as [|? ? ? ? imp]; subst; allsimpl; GC.\n    apply imp; sp.\nQed.\n\nDefinition swap_sub {o} (sw : swapping) (sub : @Sub o) : Sub :=\n  map (fun x =>\n         match x with\n           | (v,t) => (swapvar sw v,swap sw t)\n         end)\n      sub.\n\nDefinition cswap_sub {o} (sw : swapping) (sub : @Sub o) : Sub :=\n  map (fun x =>\n         match x with\n           | (v,t) => (swapvar sw v,cswap sw t)\n         end)\n      sub.\n\nLemma sub_find_some_implies_swap {o} :\n  forall (sub : @Sub o) v t vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> sub_find sub v = Some t\n    -> sub_find\n         (swap_sub (mk_swapping vs1 vs2) sub)\n         (swapvar (mk_swapping vs1 vs2) v)\n       = Some (swap (mk_swapping vs1 vs2) t).\nProof.\n  induction sub; introv norep disj f; allsimpl; cpx.\n  destruct a; simpl; boolvar; cpx; ginv; tcsp;\n  allrw length_swapbvars; tcsp.\n  provefalse.\n  destruct Heqb0.\n  eapply swapvars_eq; [|idtac|complete eauto]; auto.\nQed.\n\nLemma sub_find_some_implies_cswap {o} :\n  forall (sub : @Sub o) v t vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> sub_find sub v = Some t\n    -> sub_find\n         (cswap_sub (mk_swapping vs1 vs2) sub)\n         (swapvar (mk_swapping vs1 vs2) v)\n       = Some (cswap (mk_swapping vs1 vs2) t).\nProof.\n  induction sub; introv norep disj f; allsimpl; cpx.\n  destruct a; simpl; boolvar; cpx; ginv; tcsp;\n  allrw length_swapbvars; tcsp.\n  provefalse.\n  destruct Heqb0.\n  eapply swapvars_eq; [|idtac|complete eauto]; auto.\nQed.\n\nLemma sub_find_none_implies_swap {o} :\n  forall (sub : @Sub o) v vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> sub_find sub v = None\n    -> sub_find\n         (swap_sub (mk_swapping vs1 vs2) sub)\n         (swapvar (mk_swapping vs1 vs2) v)\n       = None.\nProof.\n  induction sub; introv norep disj f; allsimpl; cpx.\n  destruct a; simpl; boolvar; cpx; ginv; tcsp;\n  allrw length_swapbvars; tcsp.\n  provefalse.\n  destruct Heqb0.\n  eapply swapvars_eq; [|idtac|complete eauto]; auto.\nQed.\n\nLemma sub_find_none_implies_cswap {o} :\n  forall (sub : @Sub o) v vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> sub_find sub v = None\n    -> sub_find\n         (cswap_sub (mk_swapping vs1 vs2) sub)\n         (swapvar (mk_swapping vs1 vs2) v)\n       = None.\nProof.\n  induction sub; introv norep disj f; allsimpl; cpx.\n  destruct a; simpl; boolvar; cpx; ginv; tcsp;\n  allrw length_swapbvars; tcsp.\n  provefalse.\n  destruct Heqb0.\n  eapply swapvars_eq; [|idtac|complete eauto]; auto.\nQed.\n\nLemma sub_filter_swap_sub {o} :\n  forall (sub : @Sub o) vs vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> sub_filter\n         (swap_sub (mk_swapping vs1 vs2) sub)\n         (swapbvars (mk_swapping vs1 vs2) vs)\n       = swap_sub (mk_swapping vs1 vs2) (sub_filter sub vs).\nProof.\n  induction sub; introv norep disj; simpl; auto.\n  destruct a; boolvar; simpl; tcsp.\n  - provefalse.\n    apply in_swapbvars in Heqb; exrepnd.\n    apply swapvars_eq in Heqb1; auto; subst; tcsp.\n  - provefalse.\n    rw in_swapbvars in Heqb.\n    destruct Heqb.\n    eexists; dands; eauto.\n  - apply eq_cons; auto.\nQed.\n\nLemma sub_filter_cswap_sub {o} :\n  forall (sub : @Sub o) vs vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> sub_filter\n         (cswap_sub (mk_swapping vs1 vs2) sub)\n         (swapbvars (mk_swapping vs1 vs2) vs)\n       = cswap_sub (mk_swapping vs1 vs2) (sub_filter sub vs).\nProof.\n  induction sub; introv norep disj; simpl; auto.\n  destruct a; boolvar; simpl; tcsp.\n  - provefalse.\n    apply in_swapbvars in Heqb; exrepnd.\n    apply swapvars_eq in Heqb1; auto; subst; tcsp.\n  - provefalse.\n    rw in_swapbvars in Heqb.\n    destruct Heqb.\n    eexists; dands; eauto.\n  - apply eq_cons; auto.\nQed.\n\nLemma swap_sub_combine {o} :\n  forall (ts : list (@NTerm o)) vs vs1 vs2,\n    swap_sub (mk_swapping vs1 vs2) (combine vs ts)\n    = combine (swapbvars (mk_swapping vs1 vs2) vs)\n              (map (swap (mk_swapping vs1 vs2)) ts).\nProof.\n  induction ts; destruct vs; introv; simpl; auto.\n  apply eq_cons; auto.\nQed.\n\nLemma cswap_sub_combine {o} :\n  forall (ts : list (@NTerm o)) vs vs1 vs2,\n    cswap_sub (mk_swapping vs1 vs2) (combine vs ts)\n    = combine (swapbvars (mk_swapping vs1 vs2) vs)\n              (map (cswap (mk_swapping vs1 vs2)) ts).\nProof.\n  induction ts; destruct vs; introv; simpl; auto.\n  apply eq_cons; auto.\nQed.\n\nLemma lsubst_aux_swap_swap {o} :\n  forall (t : @NTerm o) vs1 vs2 sub,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> swap (mk_swapping vs1 vs2) (lsubst_aux t sub)\n       = lsubst_aux\n           (swap (mk_swapping vs1 vs2) t)\n           (swap_sub (mk_swapping vs1 vs2) sub).\nProof.\n  nterm_ind1 t as [v|f ind|op bts Hind] Case; introv norep disj; simpl; auto.\n\n  - Case \"vterm\".\n    remember (sub_find sub v) as p; destruct p; symmetry in Heqp.\n\n    + apply (sub_find_some_implies_swap sub v n vs1 vs2) in Heqp; auto.\n      rw Heqp; auto.\n\n    + apply (sub_find_none_implies_swap sub v vs1 vs2) in Heqp; auto.\n      rw Heqp; auto.\n\n  - Case \"oterm\".\n    f_equal.\n    repeat (rw map_map); unfold compose.\n    apply eq_maps; introv i.\n    destruct x; simpl.\n    f_equal.\n    rw @sub_filter_swap_sub; auto.\n    eapply Hind; eauto.\nQed.\n\nLemma lsubst_aux_cswap_cswap {o} :\n  forall (t : @NTerm o) vs1 vs2 sub,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> cswap (mk_swapping vs1 vs2) (lsubst_aux t sub)\n       = lsubst_aux\n           (cswap (mk_swapping vs1 vs2) t)\n           (cswap_sub (mk_swapping vs1 vs2) sub).\nProof.\n  nterm_ind1 t as [v|f ind|op bts Hind] Case; introv norep disj; simpl; auto.\n\n  - Case \"vterm\".\n    remember (sub_find sub v) as p; destruct p; symmetry in Heqp.\n\n    + apply (sub_find_some_implies_cswap sub v n vs1 vs2) in Heqp; auto.\n      rw Heqp; auto.\n\n    + apply (sub_find_none_implies_cswap sub v vs1 vs2) in Heqp; auto.\n      rw Heqp; auto.\n\n  - Case \"oterm\".\n    f_equal.\n    repeat (rw map_map); unfold compose.\n    apply eq_maps; introv i.\n    destruct x; simpl.\n    f_equal.\n    rw @sub_filter_cswap_sub; auto.\n    eapply Hind; eauto.\nQed.\n\nDefinition swapsk {o} (sw : swapping) (sk : @sosub_kind o) : sosub_kind :=\n  match sk with\n    | sosk vs t => sosk (swapbvars sw vs) (swap sw t)\n  end.\n\nDefinition cswapsk {o} (sw : swapping) (sk : @sosub_kind o) : sosub_kind :=\n  match sk with\n    | sosk vs t => sosk (swapbvars sw vs) (cswap sw t)\n  end.\n\nDefinition swap_sosub {o} (sw : swapping) (sub : @SOSub o) : SOSub :=\n  map (fun x =>\n         match x with\n           | (v,sk) =>\n             (if bnull (sosk_vs sk) then swapvar sw v else v,swapsk sw sk)\n         end)\n      sub.\n\nDefinition cswap_sosub {o} (sw : swapping) (sub : @SOSub o) : SOSub :=\n  map (fun x =>\n         match x with\n           | (v,sk) =>\n             (if bnull (sosk_vs sk) then swapvar sw v else v,cswapsk sw sk)\n         end)\n      sub.\n\nDefinition swap_all_sosub {o} (sw : swapping) (sub : @SOSub o) : SOSub :=\n  map (fun x =>\n         match x with\n           | (v,sk) => (swapvar sw v,swapsk sw sk)\n         end)\n      sub.\n\nDefinition cswap_all_sosub {o} (sw : swapping) (sub : @SOSub o) : SOSub :=\n  map (fun x =>\n         match x with\n           | (v,sk) => (swapvar sw v,cswapsk sw sk)\n         end)\n      sub.\n\nDefinition swap_range_sosub {o} (sw : swapping) (sub : @SOSub o) : SOSub :=\n  map (fun x =>\n         match x with\n           | (v,sk) => (v,swapsk sw sk)\n         end)\n      sub.\n\nDefinition cswap_range_sosub {o} (sw : swapping) (sub : @SOSub o) : SOSub :=\n  map (fun x =>\n         match x with\n           | (v,sk) => (v,cswapsk sw sk)\n         end)\n      sub.\n\nLemma sosub_find_some_implies_swap_0 {o} :\n  forall (sub : @SOSub o) v t vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> sosub_find sub (v,0) = Some (sosk [] t)\n    -> sosub_find\n         (swap_sosub (mk_swapping vs1 vs2) sub)\n         (swapvar (mk_swapping vs1 vs2) v, 0)\n       = Some (sosk [] (swap (mk_swapping vs1 vs2) t)).\nProof.\n  induction sub; introv norep disj f; allsimpl; cpx.\n  destruct a; destruct s; simpl; boolvar; cpx; ginv; tcsp;\n  allrw length_swapbvars; allsimpl; tcsp; GC;\n  try (complete (destruct l; allsimpl; cpx)).\n  provefalse; destruct n1.\n  f_equal.\n  eapply swapvars_eq; [|idtac|complete eauto]; auto.\nQed.\n\nLemma sosub_find_some_implies_cswap_0 {o} :\n  forall (sub : @SOSub o) v t vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> sosub_find sub (v,0) = Some (sosk [] t)\n    -> sosub_find\n         (cswap_sosub (mk_swapping vs1 vs2) sub)\n         (swapvar (mk_swapping vs1 vs2) v, 0)\n       = Some (sosk [] (cswap (mk_swapping vs1 vs2) t)).\nProof.\n  induction sub; introv norep disj f; allsimpl; cpx.\n  destruct a; destruct s; simpl; boolvar; cpx; ginv; tcsp;\n  allrw length_swapbvars; allsimpl; tcsp; GC;\n  try (complete (destruct l; allsimpl; cpx)).\n  provefalse; destruct n1.\n  f_equal.\n  eapply swapvars_eq; [|idtac|complete eauto]; auto.\nQed.\n\nLemma sosub_find_some_implies_swap_S {o} :\n  forall (sub : @SOSub o) v n vs t vs1 vs2,\n    n > 0\n    -> no_repeats vs2\n    -> disjoint vs1 vs2\n    -> sosub_find sub (v,n) = Some (sosk vs t)\n    -> sosub_find (swap_sosub (mk_swapping vs1 vs2) sub) (v, n)\n       = Some (sosk (swapbvars (mk_swapping vs1 vs2) vs)\n                    (swap (mk_swapping vs1 vs2) t)).\nProof.\n  induction sub; introv gt norep disj f; allsimpl; cpx.\n  destruct a; destruct s; simpl; boolvar; cpx; ginv; tcsp;\n  allrw length_swapbvars; allsimpl; tcsp; inversion gt.\nQed.\n\nLemma sosub_find_some_implies_cswap_S {o} :\n  forall (sub : @SOSub o) v n vs t vs1 vs2,\n    n > 0\n    -> no_repeats vs2\n    -> disjoint vs1 vs2\n    -> sosub_find sub (v,n) = Some (sosk vs t)\n    -> sosub_find (cswap_sosub (mk_swapping vs1 vs2) sub) (v, n)\n       = Some (sosk (swapbvars (mk_swapping vs1 vs2) vs)\n                    (cswap (mk_swapping vs1 vs2) t)).\nProof.\n  induction sub; introv gt norep disj f; allsimpl; cpx.\n  destruct a; destruct s; simpl; boolvar; cpx; ginv; tcsp;\n  allrw length_swapbvars; allsimpl; tcsp; inversion gt.\nQed.\n\nLemma sosub_find_some_implies_swap_all {o} :\n  forall (sub : @SOSub o) v n vs t vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> sosub_find sub (v,n) = Some (sosk vs t)\n    -> sosub_find (swap_all_sosub (mk_swapping vs1 vs2) sub)\n                  (swapvar (mk_swapping vs1 vs2) v, n)\n       = Some (sosk (swapbvars (mk_swapping vs1 vs2) vs)\n                    (swap (mk_swapping vs1 vs2) t)).\nProof.\n  induction sub; introv norep disj f; allsimpl; cpx.\n  destruct a; destruct s; simpl; boolvar; cpx; ginv; tcsp;\n  allrw length_swapbvars; allsimpl; tcsp.\n  provefalse; destruct n2.\n  f_equal.\n  eapply swapvars_eq; [|idtac|complete eauto]; auto.\nQed.\n\nLemma sosub_find_none_implies_swap_0 {o} :\n  forall (sub : @SOSub o) v vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> sosub_find sub (v,0) = None\n    -> sosub_find\n         (swap_sosub (mk_swapping vs1 vs2) sub)\n         (swapvar (mk_swapping vs1 vs2) v, 0)\n       = None.\nProof.\n  induction sub; introv norep disj f; allsimpl; cpx.\n  destruct a; destruct s; simpl; boolvar; cpx; ginv; tcsp;\n  allrw length_swapbvars; tcsp; allsimpl; GC;\n  try (complete (destruct l; allsimpl; cpx)).\n  provefalse; destruct n1.\n  f_equal.\n  eapply swapvars_eq; [|idtac|complete eauto]; auto.\nQed.\n\nLemma sosub_find_none_implies_cswap_0 {o} :\n  forall (sub : @SOSub o) v vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> sosub_find sub (v,0) = None\n    -> sosub_find\n         (cswap_sosub (mk_swapping vs1 vs2) sub)\n         (swapvar (mk_swapping vs1 vs2) v, 0)\n       = None.\nProof.\n  induction sub; introv norep disj f; allsimpl; cpx.\n  destruct a; destruct s; simpl; boolvar; cpx; ginv; tcsp;\n  allrw length_swapbvars; tcsp; allsimpl; GC;\n  try (complete (destruct l; allsimpl; cpx)).\n  provefalse; destruct n1.\n  f_equal.\n  eapply swapvars_eq; [|idtac|complete eauto]; auto.\nQed.\n\nLemma sosub_find_none_implies_swap_S {o} :\n  forall (sub : @SOSub o) v n vs1 vs2,\n    n > 0\n    -> no_repeats vs2\n    -> disjoint vs1 vs2\n    -> sosub_find sub (v,n) = None\n    -> sosub_find (swap_sosub (mk_swapping vs1 vs2) sub) (v, n) = None.\nProof.\n  induction sub; introv gt norep disj f; allsimpl; cpx.\n  destruct a; destruct s; simpl; boolvar; cpx; ginv; tcsp;\n  allrw length_swapbvars; tcsp; allsimpl; inversion gt.\nQed.\n\nLemma sosub_find_none_implies_swap_all {o} :\n  forall (sub : @SOSub o) v n vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> sosub_find sub (v,n) = None\n    -> sosub_find (swap_all_sosub (mk_swapping vs1 vs2) sub)\n                  (swapvar (mk_swapping vs1 vs2) v, n)\n       = None.\nProof.\n  induction sub; introv norep disj f; allsimpl; cpx.\n  destruct a; destruct s; simpl; boolvar; cpx; ginv; tcsp;\n  allrw length_swapbvars; tcsp; allsimpl.\n  provefalse; destruct n2.\n  f_equal.\n  eapply swapvars_eq; [|idtac|complete eauto]; auto.\nQed.\n\nLemma sosub_filter_swap_sosub {o} :\n  forall (sub : @SOSub o) vs vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> sosub_filter\n         (swap_sosub (mk_swapping vs1 vs2) sub)\n         (vars2sovars (swapbvars (mk_swapping vs1 vs2) vs))\n       = swap_sosub (mk_swapping vs1 vs2) (sosub_filter sub (vars2sovars vs)).\nProof.\n  induction sub; introv norep disj; simpl; auto.\n  destruct a; destruct s; simpl;\n  repeat (progress (boolvar; try (subst); allsimpl)); tcsp; GC.\n  - provefalse.\n    allrw in_map_iff; exrepnd; allunfold var2sovar; cpx.\n    rw in_swapbvars in l0; exrepnd.\n    apply swapvars_eq in l1; auto; subst; tcsp.\n    destruct n1; eexists; dands; eauto.\n  - provefalse.\n    allrw in_map_iff; exrepnd; allunfold var2sovar; cpx.\n    allrw length_swapbvars; destruct l; allsimpl; cpx.\n  - provefalse.\n    allrw in_map_iff; exrepnd.\n    allunfold var2sovar; cpx.\n    destruct n1; eexists; dands; eauto.\n    rw in_swapbvars; eexists; eauto.\n  - provefalse.\n    allrw in_map_iff; exrepnd.\n    allunfold var2sovar; cpx.\n    destruct l; cpx.\n  - apply eq_cons; auto.\n  - apply eq_cons; auto.\nQed.\n\nLemma sosub_filter_cswap_sosub {o} :\n  forall (sub : @SOSub o) vs vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> sosub_filter\n         (cswap_sosub (mk_swapping vs1 vs2) sub)\n         (vars2sovars (swapbvars (mk_swapping vs1 vs2) vs))\n       = cswap_sosub (mk_swapping vs1 vs2) (sosub_filter sub (vars2sovars vs)).\nProof.\n  induction sub; introv norep disj; simpl; auto.\n  destruct a; destruct s; simpl;\n  repeat (progress (boolvar; try (subst); allsimpl)); tcsp; GC.\n  - provefalse.\n    allrw in_map_iff; exrepnd; allunfold var2sovar; cpx.\n    rw in_swapbvars in l0; exrepnd.\n    apply swapvars_eq in l1; auto; subst; tcsp.\n    destruct n1; eexists; dands; eauto.\n  - provefalse.\n    allrw in_map_iff; exrepnd; allunfold var2sovar; cpx.\n    allrw length_swapbvars; destruct l; allsimpl; cpx.\n  - provefalse.\n    allrw in_map_iff; exrepnd.\n    allunfold var2sovar; cpx.\n    destruct n1; eexists; dands; eauto.\n    rw in_swapbvars; eexists; eauto.\n  - provefalse.\n    allrw in_map_iff; exrepnd.\n    allunfold var2sovar; cpx.\n    destruct l; cpx.\n  - apply eq_cons; auto.\n  - apply eq_cons; auto.\nQed.\n\nFixpoint filter_out_fo_vars (l : list sovar_sig) : list sovar_sig :=\n  match l with\n    | [] => []\n    | (v,0) :: vs => filter_out_fo_vars vs\n    | (v,S n) :: vs => (v,S n) :: filter_out_fo_vars vs\n  end.\n\nLemma subsovars_filter_out_fo_vars :\n  forall l, subsovars (filter_out_fo_vars l) l.\nProof.\n  induction l; simpl; auto.\n  destruct a; destruct n0; auto.\n  - apply subsovars_cons_weak_r; auto.\n  - apply subsovars_cons_lr; auto.\nQed.\n\nLemma in_filter_out_fo_vars :\n  forall v n l,\n    n > 0\n    -> (LIn (v, n) (filter_out_fo_vars l) <=> LIn (v, n) l).\nProof.\n  induction l; introv k; split; intro i; allsimpl; tcsp;\n  destruct a; destruct n1; tcsp.\n  - apply IHl in i; auto.\n  - simpl in i; dorn i; cpx.\n    apply IHl in i; auto.\n  - dorn i; cpx; try omega.\n    apply IHl; auto.\n  - dorn i; cpx; simpl.\n    right; apply IHl; auto.\nQed.\n\nLemma in_filter_out_fo_vars2 :\n  forall v n l,\n    LIn (v, S n) (filter_out_fo_vars l) <=> LIn (v, S n) l.\nProof.\n  introv; apply in_filter_out_fo_vars; omega.\nQed.\n\nLemma filter_out_fo_vars_app :\n  forall l1 l2,\n    filter_out_fo_vars (l1 ++ l2)\n    = filter_out_fo_vars l1 ++ filter_out_fo_vars l2.\nProof.\n  induction l1; introv; simpl; auto.\n  destruct a; destruct n0; auto.\n  apply eq_cons; auto.\nQed.\n\nLemma filter_out_fo_vars_flat_map :\n  forall {A} (x : A) f l,\n    LIn x l\n    -> subsovars (filter_out_fo_vars (f x)) (filter_out_fo_vars (flat_map f l)).\nProof.\n  induction l; introv i; allsimpl; tcsp.\n  dorn i; subst; auto; rw filter_out_fo_vars_app.\n  - apply subsovars_app_weak_r1; auto.\n  - apply subsovars_app_weak_r2; auto.\nQed.\n\nLemma subvars_filter_out_fo_vars_flat_map :\n  forall {A} f (l : list A) vs,\n    subsovars (filter_out_fo_vars (flat_map f l)) vs\n    <=> (forall x, LIn x l -> subsovars (filter_out_fo_vars (f x)) vs).\nProof.\n  induction l; introv; split; introv k; allsimpl; tcsp.\n  - rw filter_out_fo_vars_app in k; rw subsovars_app_l in k; repnd.\n    introv i; dorn i; subst; tcsp.\n    rw IHl in k; apply k; auto.\n  - rw filter_out_fo_vars_app; rw subsovars_app_l; dands; auto.\n    rw IHl; introv i.\n    apply k; sp.\nQed.\n\nDefinition cover_so_vars {o} (t : @SOTerm o) (sub : @SOSub o) :=\n  subsovars\n    (filter_out_fo_vars (so_free_vars t))\n    (filter_out_fo_vars (sodom sub)).\n\nLemma cover_so_vars_sovar {o} :\n  forall v (ts : list (@SOTerm o)) sub,\n    cover_so_vars (sovar v ts) sub\n    <=>\n    ((!null ts -> LIn (v,length ts) (sodom sub))\n     # (forall t, LIn t ts -> cover_so_vars t sub)).\nProof.\n  introv; unfold cover_so_vars; simpl; boolvar;\n  destruct ts; allsimpl; cpx; allsimpl; GC.\n  - rw null_nil_iff.\n    split; intro k; repnd; dands; tcsp.\n  - rw subsovars_cons_l; split; intro k; repnd; dands; auto.\n    + intro h.\n      pose proof (subsovars_filter_out_fo_vars (sodom sub)) as sv.\n      rw subsovars_prop in sv; apply sv in k0; auto.\n    + rw filter_out_fo_vars_app in k.\n      rw subsovars_app_l in k; repnd.\n      introv i; dorn i; subst; auto.\n      pose proof (filter_out_fo_vars_flat_map t so_free_vars ts i) as sv.\n      eapply subsovars_trans; [exact sv|]; auto.\n    + autodimp k0 hyp.\n      apply in_filter_out_fo_vars; auto; omega.\n    + rw filter_out_fo_vars_app.\n      rw subsovars_app_l; dands; tcsp.\n      rw @subvars_filter_out_fo_vars_flat_map; introv i.\n      apply k; sp.\nQed.\n\nLemma filter_out_fo_vars_remove_fo_vars :\n  forall fovs sovs,\n    filter_out_fo_vars (remove_so_vars (vars2sovars fovs) sovs)\n    = filter_out_fo_vars sovs.\nProof.\n  induction sovs; simpl.\n  - rw remove_so_vars_nil_r; simpl; auto.\n  - destruct a; destruct n0; simpl;\n    rw remove_so_vars_cons_r; boolvar; simpl; auto.\n    + allrw in_map_iff; exrepnd.\n      allunfold var2sovar; cpx.\n    + apply eq_cons; auto.\nQed.\n\nLemma cover_so_vars_soterm {o} :\n  forall op (bs : list (@SOBTerm o)) sub,\n    cover_so_vars (soterm op bs) sub\n    <=>\n    (forall vs t, LIn (sobterm vs t) bs -> cover_so_vars t sub).\nProof.\n  introv; unfold cover_so_vars; simpl; split; intro k.\n  - introv i.\n    rw @subvars_filter_out_fo_vars_flat_map in k.\n    apply k in i; simpl in i.\n    rw filter_out_fo_vars_remove_fo_vars in i; auto.\n  - rw @subvars_filter_out_fo_vars_flat_map; introv i.\n    destruct x; simpl.\n    rw filter_out_fo_vars_remove_fo_vars.\n    eapply k; eauto.\nQed.\n\nLemma cover_so_vars_sosub_filter {o} :\n  forall (sub : @SOSub o) t vs,\n    cover_so_vars t (sosub_filter sub (vars2sovars vs))\n    <=> cover_so_vars t sub.\nProof.\n  introv; unfold cover_so_vars.\n  rw @sodom_sosub_filter.\n  rw filter_out_fo_vars_remove_fo_vars; sp.\nQed.\n\n(* vs2 can be disjoint from whatever we want *)\nLemma sosub_aux_swap_swap {p} :\n  forall (t : @SOTerm p) vs1 vs2 sub,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> cover_so_vars t sub\n    -> swap (mk_swapping vs1 vs2) (sosub_aux sub t)\n       = sosub_aux (swap_sosub (mk_swapping vs1 vs2) sub)\n                   (so_swap (mk_swapping vs1 vs2) t).\nProof.\n  soterm_ind1s t as [v ts ind | o lbt Hind] Case;\n  introv norep disj cov.\n\n  - Case \"sovar\".\n    simpl.\n    remember (sosub_find sub (v,length ts)) as f;\n      symmetry in Heqf; destruct f;\n      boolvar; subst; allsimpl;\n      try (destruct s);\n      try (rw map_length).\n\n    + applydup @sosub_find_some in Heqf; repnd.\n      destruct l; allsimpl; cpx; GC.\n      dup Heqf as e.\n      eapply sosub_find_some_implies_swap_0 in e; eauto.\n      rw e; clear e; simpl.\n      rw @lsubst_aux_swap_swap; auto.\n\n    + dup Heqf as e.\n      eapply sosub_find_some_implies_swap_S in e; eauto;\n      try (complete (destruct ts; allsimpl; sp; apply gt_Sn_O)).\n      rw e; clear e.\n      rw @lsubst_aux_swap_swap; auto.\n      rw @swap_sub_combine.\n      f_equal; f_equal.\n      repeat (rw map_map); unfold compose.\n      apply eq_maps; introv i.\n      apply ind; auto.\n      rw @cover_so_vars_sovar in cov; repnd; apply cov; auto.\n\n    + eapply sosub_find_none_implies_swap_0 in Heqf; eauto.\n      rw Heqf; clear Heqf; auto.\n\n    + apply sosub_find_none in Heqf.\n      rw @cover_so_vars_sovar in cov; repnd.\n      autodimp cov0 hyp; tcsp.\n      rw null_iff_nil; auto.\n\n  - Case \"soterm\".\n    simpl.\n    f_equal.\n    repeat (rw map_map); unfold compose; apply eq_maps; introv i.\n    destruct x; simpl.\n    f_equal.\n    rw @sosub_filter_swap_sosub; auto.\n    eapply Hind; eauto.\n    rw @cover_so_vars_soterm in cov.\n    apply cov in i.\n    rw @cover_so_vars_sosub_filter; auto.\nQed.\n\nLemma sosub_aux_cswap_cswap {p} :\n  forall (t : @SOTerm p) vs1 vs2 sub,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> cover_so_vars t sub\n    -> cswap (mk_swapping vs1 vs2) (sosub_aux sub t)\n       = sosub_aux (cswap_sosub (mk_swapping vs1 vs2) sub)\n                   (so_swap (mk_swapping vs1 vs2) t).\nProof.\n  soterm_ind1s t as [v ts ind | o lbt Hind] Case;\n  introv norep disj cov.\n\n  - Case \"sovar\".\n    simpl.\n    remember (sosub_find sub (v,length ts)) as f;\n      symmetry in Heqf; destruct f;\n      boolvar; subst; allsimpl;\n      try (destruct s);\n      try (rw map_length).\n\n    + applydup @sosub_find_some in Heqf; repnd.\n      destruct l; allsimpl; cpx; GC.\n      dup Heqf as e.\n      eapply sosub_find_some_implies_cswap_0 in e; eauto.\n      rw e; clear e; simpl.\n      rw @lsubst_aux_cswap_cswap; auto.\n\n    + dup Heqf as e.\n      eapply sosub_find_some_implies_cswap_S in e; eauto;\n      try (complete (destruct ts; allsimpl; sp; apply gt_Sn_O)).\n      rw e; clear e.\n      rw @lsubst_aux_cswap_cswap; auto.\n      rw @cswap_sub_combine.\n      f_equal; f_equal.\n      repeat (rw map_map); unfold compose.\n      apply eq_maps; introv i.\n      apply ind; auto.\n      rw @cover_so_vars_sovar in cov; repnd; apply cov; auto.\n\n    + eapply sosub_find_none_implies_cswap_0 in Heqf; eauto.\n      rw Heqf; clear Heqf; auto.\n\n    + apply sosub_find_none in Heqf.\n      rw @cover_so_vars_sovar in cov; repnd.\n      autodimp cov0 hyp; tcsp.\n      rw null_iff_nil; auto.\n\n  - Case \"soterm\".\n    simpl.\n    f_equal.\n    repeat (rw map_map); unfold compose; apply eq_maps; introv i.\n    destruct x; simpl.\n    f_equal.\n    rw @sosub_filter_cswap_sosub; auto.\n    eapply Hind; eauto.\n    rw @cover_so_vars_soterm in cov.\n    apply cov in i.\n    rw @cover_so_vars_sosub_filter; auto.\nQed.\n\nLemma in_swap_range_sosub_implies {o} :\n  forall (sub : @SOSub o) sw v vs t,\n    LIn (v,sosk vs t) (swap_range_sosub sw sub)\n    -> LIn (v,length vs) (sodom sub).\nProof.\n  introv i.\n  rw in_map_iff in i; exrepnd; cpx.\n  destruct a; allsimpl; ginv.\n  rw length_swapbvars.\n  eapply in_sodom_if in i1; eauto.\nQed.\n\nLemma sosub_find_some_implies_swap2 {o} :\n  forall (sub : @SOSub o) v n vs t vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> sosub_find sub (v,n) = Some (sosk vs t)\n    -> sosub_find (swap_range_sosub (mk_swapping vs1 vs2) sub) (v,n)\n       = Some (sosk (swapbvars (mk_swapping vs1 vs2) vs)\n                    (swap (mk_swapping vs1 vs2) t)).\nProof.\n  induction sub; introv norep disj f; allsimpl; cpx.\n  destruct a; destruct s; simpl; boolvar; cpx; ginv; tcsp;\n  allrw length_swapbvars; tcsp.\nQed.\n\nLemma sosub_find_none_implies_swap2 {o} :\n  forall (sub : @SOSub o) v n vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> sosub_find sub (v,n) = None\n    -> sosub_find (swap_range_sosub (mk_swapping vs1 vs2) sub) (v,n) = None.\nProof.\n  induction sub; introv norep disj f; allsimpl; cpx.\n  destruct a; destruct s; simpl; boolvar; cpx; ginv; tcsp;\n  allrw length_swapbvars; tcsp.\nQed.\n\nLemma sosub_filter_swap_range_sosub {o} :\n  forall (sub : @SOSub o) vs vs1 vs2,\n    sosub_filter (swap_range_sosub (mk_swapping vs1 vs2) sub) vs\n    = swap_range_sosub (mk_swapping vs1 vs2) (sosub_filter sub vs).\nProof.\n  induction sub; introv; simpl; auto.\n  destruct a; destruct s; simpl; boolvar; simpl; tcsp;\n  allrw length_swapbvars; tcsp.\n  apply eq_cons; auto.\nQed.\n\nLemma sosub_filter_cswap_range_sosub {o} :\n  forall (sub : @SOSub o) vs vs1 vs2,\n    sosub_filter (cswap_range_sosub (mk_swapping vs1 vs2) sub) vs\n    = cswap_range_sosub (mk_swapping vs1 vs2) (sosub_filter sub vs).\nProof.\n  induction sub; introv; simpl; auto.\n  destruct a; destruct s; simpl; boolvar; simpl; tcsp;\n  allrw length_swapbvars; tcsp.\n  apply eq_cons; auto.\nQed.\n\nLemma swap_range_sosub_eq {o} :\n  forall (sub : @SOSub o) vs1 vs2,\n    disjoint vs1 (sovars2vars (sodom sub))\n    -> disjoint vs2 (sovars2vars (sodom sub))\n    -> swap_range_sosub (mk_swapping vs1 vs2) sub\n       = swap_sosub (mk_swapping vs1 vs2) sub.\nProof.\n  introv disj1 disj2.\n  unfold swap_range_sosub, swap_sosub.\n  apply eq_maps; introv i.\n  destruct x; destruct s.\n  boolvar; auto.\n  destruct l; allsimpl; cpx; GC.\n  allrw disjoint_map_r.\n  eapply in_sodom_if in i; eauto.\n  applydup disj1 in i.\n  applydup disj2 in i.\n  allsimpl.\n  rw swapvar_not_in; auto.\nQed.\n\nLemma sosub_aux_swap_swap2 {o} :\n  forall (t : @SOTerm o) sub vs1 vs2,\n    disjoint vs2 (vs1 ++ sovars2vars (sodom sub))\n    -> disjoint vs1 (sovars2vars (sodom sub))\n    -> no_repeats vs2\n    -> cover_so_vars t sub\n    -> swap (mk_swapping vs1 vs2) (sosub_aux sub t)\n       = sosub_aux\n           (swap_range_sosub (mk_swapping vs1 vs2) sub)\n           (so_swap (mk_swapping vs1 vs2) t).\nProof.\n  introv disj1 disj2 norep cov.\n  allrw disjoint_app_r; repnd.\n  rw (sosub_aux_swap_swap t vs1 vs2 sub); eauto with slow.\n  f_equal.\n  rw @swap_range_sosub_eq; auto.\nQed.\n\nFixpoint get_fo_vars (l : list sovar_sig) : list NVar :=\n  match l with\n    | [] => []\n    | (v,0) :: vs => v :: get_fo_vars vs\n    | _ :: vs => get_fo_vars vs\n  end.\n\nLemma get_fo_vars_app :\n  forall vs1 vs2, get_fo_vars (vs1 ++ vs2) = get_fo_vars vs1 ++ get_fo_vars vs2.\nProof.\n  induction vs1; introv; simpl; auto.\n  destruct a; destruct n0; simpl; auto.\n  rw IHvs1; auto.\nQed.\n\nLemma in_get_fo_vars :\n  forall v vs, LIn v (get_fo_vars vs) <=> LIn (v,0) vs.\nProof.\n  induction vs; split; introv i; allsimpl; tcsp;\n  destruct a; destruct n0; allsimpl; tcsp;\n  try (dorn i; subst; cpx);\n  try (complete (try right; apply IHvs; auto)).\nQed.\n\nLemma swap_range_sosub_eq2 {o} :\n  forall (sub : @SOSub o) vs1 vs2,\n    disjoint vs1 (get_fo_vars (sodom sub))\n    -> disjoint vs2 (get_fo_vars (sodom sub))\n    -> swap_range_sosub (mk_swapping vs1 vs2) sub\n       = swap_sosub (mk_swapping vs1 vs2) sub.\nProof.\n  introv disj1 disj2.\n  apply eq_maps; introv i.\n  destruct x; destruct s.\n  boolvar; auto.\n  destruct l; allsimpl; cpx; GC.\n  eapply in_sodom_if in i; eauto; allsimpl.\n  apply in_get_fo_vars in i.\n  apply disjoint_sym in disj1.\n  apply disjoint_sym in disj2.\n  applydup disj1 in i.\n  applydup disj2 in i.\n  rw swapvar_not_in; auto.\nQed.\n\nLemma cswap_range_sosub_eq2 {o} :\n  forall (sub : @SOSub o) vs1 vs2,\n    disjoint vs1 (get_fo_vars (sodom sub))\n    -> disjoint vs2 (get_fo_vars (sodom sub))\n    -> cswap_range_sosub (mk_swapping vs1 vs2) sub\n       = cswap_sosub (mk_swapping vs1 vs2) sub.\nProof.\n  introv disj1 disj2.\n  apply eq_maps; introv i.\n  destruct x; destruct s.\n  boolvar; auto.\n  destruct l; allsimpl; cpx; GC.\n  eapply in_sodom_if in i; eauto; allsimpl.\n  apply in_get_fo_vars in i.\n  apply disjoint_sym in disj1.\n  apply disjoint_sym in disj2.\n  applydup disj1 in i.\n  applydup disj2 in i.\n  rw swapvar_not_in; auto.\nQed.\n\nLemma sosub_aux_swap_swap3 {o} :\n  forall (t : @SOTerm o) sub vs1 vs2,\n    disjoint vs2 (vs1 ++ get_fo_vars (sodom sub))\n    -> disjoint vs1 (get_fo_vars (sodom sub))\n    -> no_repeats vs2\n    -> cover_so_vars t sub\n    -> swap (mk_swapping vs1 vs2) (sosub_aux sub t)\n       = sosub_aux\n           (swap_range_sosub (mk_swapping vs1 vs2) sub)\n           (so_swap (mk_swapping vs1 vs2) t).\nProof.\n  introv disj1 disj2 norep cov.\n  allrw disjoint_app_r; repnd.\n  rw (sosub_aux_swap_swap t vs1 vs2 sub); eauto with slow.\n  f_equal.\n  rw @swap_range_sosub_eq2; auto.\nQed.\n\nLemma sosub_aux_cswap_cswap3 {o} :\n  forall (t : @SOTerm o) sub vs1 vs2,\n    disjoint vs2 (vs1 ++ get_fo_vars (sodom sub))\n    -> disjoint vs1 (get_fo_vars (sodom sub))\n    -> no_repeats vs2\n    -> cover_so_vars t sub\n    -> cswap (mk_swapping vs1 vs2) (sosub_aux sub t)\n       = sosub_aux\n           (cswap_range_sosub (mk_swapping vs1 vs2) sub)\n           (so_swap (mk_swapping vs1 vs2) t).\nProof.\n  introv disj1 disj2 norep cov.\n  allrw disjoint_app_r; repnd.\n  rw (sosub_aux_cswap_cswap t vs1 vs2 sub); eauto with slow.\n  f_equal.\n  rw @cswap_range_sosub_eq2; auto.\nQed.\n\n(*\nLemma lsubst_aux_alpha_congr2 {p} :\n  forall (t1 t2 : @NTerm p) vs1 vs2 ts1 ts2,\n    alpha_eq_bterm (bterm vs1 t1) (bterm vs2 t2)\n    -> bin_rel_nterm alpha_eq ts1 ts2 (*enforces that the lengths are equal*)\n    -> alpha_eq (lsubst_aux t1 (combine vs1 ts1)) (lsubst_aux t2 (combine vs2 ts2)).\nProof.\n  introv aeq aeqs.\n  inversion aeq as [? ? ? ? ? disj len1 len2 norep a]; subst.\n\n  introv Hal Hbr Hl. unfold apply_bterm.\n  destruct bt1 as [lv1 nt1]. destruct bt2 as [lv2 nt2];allsimpl.\n  invertsna Hal Hal.\n  remember (change_bvars_alpha (lv++(flat_map free_vars lnt1)) nt1) as X99.\n  revert HeqX99. add_changebvar_spec nt1' Hnt1'. intro H99. clear dependent X99.\n  repnd. clear Heqnt1'.\n  remember (change_bvars_alpha (lv++(flat_map free_vars lnt2)) nt2) as X99.\n  revert HeqX99. add_changebvar_spec nt2' Hnt2'. intro H99. clear dependent X99.\n  repnd. clear Heqnt2'.\n  unfold num_bvars in Hl. allsimpl. duplicate Hbr.\n  destruct Hbr as [Hll X99]. clear X99.\n  alpharws Hnt1'.\n  alpharws Hnt2'.\n  alpharwh Hnt1' Hal3.\n  alpharwhs Hnt2' Hal3.\n  eapply lsubst_alpha_congr with (lvi:=lv) in Hal3; eauto.\n  Focus 2. spc;fail. Focus 2. spc;fail.\n\n  rewrite lsubst_nest_same in Hal3; spc; spcls;disjoint_reasoningv.\n  - rewrite lsubst_nest_same in Hal3; spc; spcls;disjoint_reasoningv.\n    alpharw_rev  Hnt2'. trivial.\n  - alpharw_rev  Hnt1'. trivial.\nQed.\n*)\n\nLemma disjoint_bound_vars_prop1 {o} :\n  forall (sub : @SOSub o) v vs t ts,\n    disjoint (bound_vars_in_sosub sub) (free_vars_sosub sub)\n    -> disjoint (bound_vars_in_sosub sub) (flat_map all_fo_vars ts)\n    -> LIn (v, sosk vs t) sub\n    -> disjoint (bound_vars t) (flat_map (fun x => free_vars (sosub_aux sub x)) ts).\nProof.\n  introv disj1 disj2 insub.\n  apply disjoint_flat_map_r; introv i.\n  allrw disjoint_flat_map_l.\n  applydup disj1 in insub; allsimpl.\n  applydup disj2 in insub; allsimpl.\n  pose proof (isprogram_sosub_aux_free_vars x sub) as h.\n  eapply subvars_disjoint_r;[eauto|]; clear h.\n  rw disjoint_app_r; dands; auto.\n  apply disjoint_map_r; introv k.\n  rw in_remove_so_vars in k; repnd.\n  destruct x0; simpl.\n  apply so_free_vars_in_all_fo_vars in k0.\n  rw disjoint_flat_map_r in insub1.\n  apply insub1 in i.\n  apply disjoint_sym in i.\n  apply i in k0; auto.\nQed.\n\n(*\nLemma swap_sosub_combine {o} :\n  forall sw (sks : list (@sosub_kind o)) vs,\n    swap_sosub sw (combine vs sks)\n    = combine (swapbvars sw vs) (map (swapsk sw) sks).\nProof.\n  induction sks; destruct vs; allsimpl; auto.\n  apply eq_cons; auto.\nQed.\n*)\n\nLemma swap_range_sosub_combine {o} :\n  forall sw (sks : list (@sosub_kind o)) vs,\n    swap_range_sosub sw (combine vs sks)\n    = combine vs (map (swapsk sw) sks).\nProof.\n  induction sks; destruct vs; allsimpl; auto.\n  apply eq_cons; auto.\nQed.\n\nLemma cswap_range_sosub_combine {o} :\n  forall sw (sks : list (@sosub_kind o)) vs,\n    cswap_range_sosub sw (combine vs sks)\n    = combine vs (map (cswapsk sw) sks).\nProof.\n  induction sks; destruct vs; allsimpl; auto.\n  apply eq_cons; auto.\nQed.\n\nLemma get_fo_vars_remove_so_vars :\n  forall fovs sovs,\n    get_fo_vars (remove_so_vars (vars2sovars fovs) sovs)\n    = remove_nvars fovs (get_fo_vars sovs).\nProof.\n  induction sovs; simpl.\n  - rw remove_so_vars_nil_r.\n    rw remove_nvars_nil_r; auto.\n  - rw remove_so_vars_cons_r.\n    destruct a; destruct n0; boolvar; tcsp;\n    rw remove_nvars_cons_r; boolvar; simpl; tcsp.\n    + allrw in_map_iff; exrepnd.\n      allunfold var2sovar; cpx.\n    + allrw in_map_iff; exrepnd.\n      allunfold var2sovar; cpx.\n      provefalse; destruct n0.\n      eexists; eauto.\n    + apply eq_cons; auto.\nQed.\n\nLemma disjoint_get_fo_vars_remove :\n  forall fovs sovs,\n    disjoint fovs (get_fo_vars (remove_so_vars (vars2sovars fovs) sovs)).\nProof.\n  introv.\n  rw get_fo_vars_remove_so_vars.\n  introv i j.\n  rw in_remove_nvars in j; sp.\nQed.\n\nLemma subvars_sovars2vars_prop2 :\n  forall vs1 vs2,\n    subsovars vs1 vs2\n    -> subvars (get_fo_vars vs1) (sovars2vars vs2).\nProof.\n  introv k.\n  rw subvars_prop; introv i.\n  allrw in_sovars2vars; exrepnd.\n  allrw in_get_fo_vars.\n  rw subsovars_prop in k.\n  apply k in i.\n  eexists; eauto.\nQed.\n\nLemma alphaeq_sks_implies_eq_sodom_combine {o} :\n  forall (sks1 sks2 : list (@sosub_kind o)) vs,\n    bin_rel_sk alphaeq_sk sks1 sks2\n    -> sodom (combine vs sks1) = sodom (combine vs sks2).\nProof.\n  induction sks1; destruct sks2; introv aeqs; allsimpl; auto.\n  - inversion aeqs; allsimpl; sp.\n  - inversion aeqs; allsimpl; sp.\n  - destruct vs; allsimpl; auto.\n    destruct a; destruct s.\n    rw @bin_rel_sk_cons in aeqs; repnd.\n    erewrite IHsks1; eauto.\n    inversion aeqs; subst.\n    apply eq_cons; auto.\n    f_equal; omega.\nQed.\n\nLemma swapvar_implies3 :\n  forall (vs1 vs2 : list NVar) (v : NVar),\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> length vs1 = length vs2\n    -> LIn v vs1\n    -> LIn (swapvar (mk_swapping vs1 vs2) v) vs2.\nProof.\n  induction vs1; destruct vs2; introv norep disj len i; allsimpl; cpx; GC; tcsp.\n  allrw no_repeats_cons; repnd.\n  allrw disjoint_cons_l; allrw disjoint_cons_r; allsimpl.\n  allrw not_over_or; repnd.\n  unfold oneswapvar; boolvar; dorn i; subst; tcsp; GC;\n  rw swapvar_not_in; auto.\nQed.\n\nLemma disjoint_get_fo_vars_flat_map_r :\n  forall {T} (l : list T) f vs,\n    disjoint vs (get_fo_vars (flat_map f l))\n    <=>\n    (forall x, LIn x l -> disjoint vs (get_fo_vars (f x))).\nProof.\n  induction l; simpl; introv; split; intro k; tcsp.\n  - introv i; dorn i; subst; tcsp.\n    + allrw get_fo_vars_app.\n      allrw disjoint_app_r; sp.\n    + allrw get_fo_vars_app.\n      allrw disjoint_app_r; repnd.\n      rw IHl in k; apply k; auto.\n  - rw get_fo_vars_app.\n    rw disjoint_app_r; dands; auto.\n    apply IHl; introv i.\n    apply k; sp.\nQed.\n\nLemma disjoint_swapbvars2 :\n  forall bvs vs1 vs2 : list NVar,\n    disjoint vs1 vs2\n    -> no_repeats vs2\n    -> disjoint vs2 bvs\n    -> length vs1 = length vs2\n    -> disjoint vs1 (swapbvars (mk_swapping vs1 vs2) bvs).\nProof.\n  induction bvs; introv disj1 norep disj2 len; allsimpl; auto.\n  rw disjoint_cons_r in disj2; repnd.\n  rw disjoint_cons_r; dands; auto.\n  pose proof (in_deq NVar deq_nvar a vs1) as h; dorn h.\n  * pose proof (swapvar_implies3 vs1 vs2 a norep disj1 len h) as k.\n    rw disjoint_sym in disj1; apply disj1 in k; tcsp.\n  * rw swapvar_not_in; sp.\nQed.\n\nLemma free_fo_vars_so_swap {o} :\n  forall (t : @SOTerm o) vs1 vs2,\n    disjoint vs1 vs2\n    -> disjoint vs2 (all_fo_vars t)\n    -> no_repeats vs2\n    -> length vs1 = length vs2\n    -> disjoint vs1 (get_fo_vars (so_free_vars (so_swap (mk_swapping vs1 vs2) t))).\nProof.\n  soterm_ind t as [ v ts ind | op lbt ind ] Case; simpl;\n  introv disj1 disj2 norep len.\n\n  - Case \"sovar\".\n    boolvar; subst; allsimpl.\n    + allrw disjoint_singleton_r.\n      pose proof (in_deq NVar deq_nvar v vs1) as h; dorn h.\n      * pose proof (swapvar_implies3 vs1 vs2 v norep disj1 len h) as k.\n        rw disjoint_sym in disj1; apply disj1 in k; tcsp.\n      * rw swapvar_not_in; sp.\n    + rw map_length.\n      allrw disjoint_cons_r; repnd.\n      rw <- length0 in n.\n      destruct (length ts); cpx.\n      apply disjoint_get_fo_vars_flat_map_r; introv k.\n      rw in_map_iff in k; exrepnd; subst.\n      apply ind; auto.\n      allrw disjoint_flat_map_r.\n      apply disj0; auto.\n\n  - Case \"soterm\".\n    apply disjoint_get_fo_vars_flat_map_r; introv k.\n    rw in_map_iff in k; exrepnd; subst.\n    destruct a; simpl.\n    rw get_fo_vars_remove_so_vars.\n    pose proof (ind s l k1 vs1 vs2) as h; repeat (autodimp h hyp).\n    + allrw disjoint_flat_map_r.\n      apply disj2 in k1; simpl in k1.\n      allrw disjoint_app_r; sp.\n    + introv i j.\n      apply h in i.\n      rw in_remove_nvars in j; sp.\nQed.\n\nLemma fo_bound_vars_so_swap {o} :\n  forall (t : @SOTerm o) vs1 vs2,\n    disjoint vs1 vs2\n    -> disjoint vs2 (all_fo_vars t)\n    -> no_repeats vs2\n    -> length vs1 = length vs2\n    -> disjoint vs1 (fo_bound_vars (so_swap (mk_swapping vs1 vs2) t)).\nProof.\n  soterm_ind t as [ v ts ind | op lbt ind ] Case; simpl;\n  introv disj1 disj2 norep len.\n\n  - Case \"sovar\".\n    boolvar; subst; allsimpl; auto.\n    rw disjoint_flat_map_r; introv i.\n    rw in_map_iff in i; exrepnd; subst.\n    apply ind; auto.\n    allrw disjoint_cons_r; allrw disjoint_flat_map_r; repnd.\n    apply disj0; auto.\n\n  - Case \"soterm\".\n    rw flat_map_map; unfold compose.\n    rw disjoint_flat_map_r; introv i.\n    destruct x; simpl.\n    rw disjoint_app_r; dands; auto.\n    + apply disjoint_swapbvars2; auto.\n      rw disjoint_flat_map_r in disj2.\n      apply disj2 in i; simpl in i.\n      rw disjoint_app_r in i; sp.\n    + eapply ind; eauto.\n      rw disjoint_flat_map_r in disj2.\n      apply disj2 in i; simpl in i.\n      rw disjoint_app_r in i; sp.\nQed.\n\nLemma sosub_find_sosub_filter {o} :\n  forall (sub : @SOSub o) vs v,\n    !LIn v vs\n    -> sosub_find (sosub_filter sub vs) v\n       = sosub_find sub v.\nProof.\n  induction sub; introv i; simpl; auto.\n  destruct v; destruct a; destruct s;\n  boolvar; simpl; cpx;\n  boolvar; simpl; cpx.\nQed.\n\nLemma sosub_filter_swap {o} :\n  forall (sub : @SOSub o) vs1 vs2,\n    sosub_filter (sosub_filter sub vs1) vs2\n    = sosub_filter (sosub_filter sub vs2) vs1.\nProof.\n  induction sub; introv; simpl; auto.\n  destruct a; destruct s;\n  boolvar; simpl; tcsp;\n  boolvar; simpl; tcsp.\n  rw IHsub; auto.\nQed.\n\nFixpoint fovars {p} (t : @SOTerm p) : list NVar :=\n  match t with\n    | sovar v ts =>\n      if bnull ts\n      then v :: flat_map fovars ts\n      else flat_map fovars ts\n    | soterm op bs => flat_map fovars_bterm bs\n  end\nwith fovars_bterm {p} (bt : @SOBTerm p) : list NVar :=\n       match bt with\n         | sobterm lv nt => lv ++ fovars nt\n       end.\n\nLemma fovars_subvars_all_fo_vars {o} :\n  forall t : @SOTerm o,\n    subvars (fovars t) (all_fo_vars t).\nProof.\n  soterm_ind t as [ v ts ind | op lbt ind ] Case; simpl; introv.\n\n  - Case \"sovar\".\n    boolvar; subst; allsimpl; auto.\n    apply subvars_cons_r.\n    apply subvars_flat_map2; auto.\n\n  - Case \"soterm\".\n    apply subvars_flat_map2; introv i.\n    destruct x; simpl.\n    apply subvars_app_l; dands.\n    + apply subvars_app_weak_l; auto.\n    + apply subvars_app_weak_r; auto.\n      eapply ind; eauto.\nQed.\n\nLemma get_fo_vars_flat_map :\n  forall {T} f (l : list T),\n    get_fo_vars (flat_map f l)\n    = flat_map (fun x => get_fo_vars (f x)) l.\nProof.\n  induction l; simpl; auto.\n  rw get_fo_vars_app.\n  rw IHl; auto.\nQed.\n\nLemma flat_map_app_f :\n  forall {A B} (f g : A -> list B) (l : list A),\n    eqset\n      (flat_map f l ++ flat_map g l)\n      (flat_map (fun x => f x ++ g x) l).\nProof.\n  induction l; simpl; auto.\n  allunfold @eqset; introv; split; intro i; allrw in_app_iff.\n  - rw <- IHl; allrw in_app_iff; sp.\n  - rw <- IHl in i; allrw in_app_iff; sp.\nQed.\n\nLemma eqvars_is_eqset :\n  forall l1 l2,\n    eqvars l1 l2 <=> eqset l1 l2.\nProof.\n  introv; rw eqvars_prop; unfold eqset; sp.\nQed.\n\nLemma implies_eqvars_flat_map :\n  forall {A} f g (l : list A),\n    (forall x, LIn x l -> eqvars (f x) (g x))\n    -> eqvars (flat_map f l) (flat_map g l).\nProof.\n  induction l; introv h; allsimpl; auto.\n  apply eqvars_app; auto.\nQed.\n\nLemma eqvars_remove_nvars_app :\n  forall vs1 vs2 vs3,\n    eqvars (remove_nvars vs1 vs2 ++ vs1 ++ vs3)\n           (vs1 ++ vs2 ++ vs3).\nProof.\n  introv; rw eqvars_prop; introv; split; intro i;\n  allrw in_app_iff; allrw in_remove_nvars; sp.\n  destruct (in_deq NVar deq_nvar x vs1); sp.\nQed.\n\nLemma fovars_eqvars {o} :\n  forall (t : @SOTerm o),\n    eqvars\n      (fovars t)\n      (get_fo_vars (so_free_vars t) ++ fo_bound_vars t).\nProof.\n  soterm_ind t as [ v ts ind | op lbt ind ] Case; simpl; introv.\n\n  - Case \"sovar\".\n    boolvar; subst; simpl; auto.\n    rw <- length0 in n.\n    destruct (length ts); tcsp.\n    rw @get_fo_vars_flat_map.\n    pose proof (flat_map_app_f\n                  (fun t : SOTerm => get_fo_vars (so_free_vars t))\n                  fo_bound_vars\n                  ts) as e.\n    rw <- eqvars_is_eqset in e.\n    eapply eqvars_trans;[|apply eqvars_sym; exact e].\n    apply implies_eqvars_flat_map; auto.\n\n  - Case \"soterm\".\n    rw @get_fo_vars_flat_map.\n    pose proof (flat_map_app_f\n                  (fun t => get_fo_vars (so_free_vars_bterm t))\n                  fo_bound_vars_bterm\n                  lbt) as e.\n    rw <- eqvars_is_eqset in e.\n    eapply eqvars_trans;[|apply eqvars_sym; exact e].\n    apply implies_eqvars_flat_map; auto.\n    introv i; destruct x; simpl.\n    rw get_fo_vars_remove_so_vars.\n    pose proof (eqvars_remove_nvars_app\n                  l (get_fo_vars (so_free_vars s))\n                  (fo_bound_vars s)) as h.\n    eapply eqvars_trans; [|apply eqvars_sym; exact h].\n    apply eqvars_app; auto.\n    eapply ind; eauto.\nQed.\n\nLemma fo_free_vars_in_fovars {o} :\n  forall (t : @SOTerm o) v,\n    LIn (v, 0) (so_free_vars t)\n    -> LIn v (fovars t).\nProof.\n  introv i.\n  pose proof (fovars_eqvars t) as h.\n  rw eqvars_prop in h.\n  apply h.\n  rw in_app_iff.\n  left.\n  rw in_get_fo_vars; auto.\nQed.\n\nLemma disjoint_bound_vars_prop2 {o} :\n  forall (sub : @SOSub o) v vs t ts,\n    disjoint (bound_vars_in_sosub sub) (free_vars_sosub sub)\n    -> disjoint (bound_vars_in_sosub sub) (flat_map fovars ts)\n    -> LIn (v, sosk vs t) sub\n    -> (forall u, LIn u ts -> cover_so_vars u sub)\n    -> disjoint (bound_vars t) (flat_map (fun x => free_vars (sosub_aux sub x)) ts).\nProof.\n  introv disj1 disj2 insub cov.\n  apply disjoint_flat_map_r; introv i.\n  allrw disjoint_flat_map_l.\n  applydup disj1 in insub; allsimpl.\n  applydup disj2 in insub; allsimpl.\n  pose proof (isprogram_sosub_aux_free_vars x sub) as h.\n  eapply subvars_disjoint_r;[eauto|]; clear h.\n  rw disjoint_app_r; dands; auto.\n  applydup cov in i.\n  apply disjoint_map_r; introv k.\n  rw in_remove_so_vars in k; repnd.\n  destruct x0; simpl.\n  unfold cover_so_vars in i0.\n  destruct n0.\n  - rw disjoint_flat_map_r in insub1.\n    apply insub1 in i.\n    apply disjoint_sym in i.\n    apply fo_free_vars_in_fovars in k0.\n    apply i in k0; auto.\n  - rw subsovars_prop in i0.\n    pose proof (i0 (n,S n0)) as h; autodimp h hyp.\n    + apply in_filter_out_fo_vars; auto; omega.\n    + rw in_filter_out_fo_vars2 in h; tcsp.\nQed.\n\nLemma disjoint_bound_vars_prop3 {o} :\n  forall (sub : @SOSub o) v vs t ts,\n    disjoint (bound_vars_sosub sub) (free_vars_sosub sub)\n    -> disjoint (bound_vars_sosub sub) (flat_map fovars ts)\n    -> LIn (v, sosk vs t) sub\n    -> (forall u, LIn u ts -> cover_so_vars u sub)\n    -> disjoint (bound_vars t) (flat_map (fun x => free_vars (sosub_aux sub x)) ts).\nProof.\n  introv disj1 disj2 insub cov.\n  eapply disjoint_bound_vars_prop2; eauto;\n  eapply subvars_disjoint_l;[|eauto|idtac|eauto];\n  apply subvars_bound_vars_in_sosub_bound_vars_sosub.\nQed.\n\nLemma disjoint_fovars_so_swap {o} :\n  forall (t : @SOTerm o) vs1 vs2,\n    disjoint vs1 vs2\n    -> disjoint vs2 (all_fo_vars t)\n    -> no_repeats vs2\n    -> length vs1 = length vs2\n    -> disjoint vs1 (fovars (so_swap (mk_swapping vs1 vs2) t)).\nProof.\n  introv disj1 disj2 norep len.\n  eapply eqvars_disjoint_r;\n    [apply eqvars_sym;apply fovars_eqvars|].\n  rw disjoint_app_r; dands.\n  - apply free_fo_vars_so_swap; auto.\n  - apply fo_bound_vars_so_swap; auto.\nQed.\n\nLemma sosub_aux_sosub_filter {o} :\n  forall (t : @SOTerm o) (sub : @SOSub o) l,\n    disjoint l (fovars t)\n    -> sosub_aux (sosub_filter sub (vars2sovars l)) t\n       = sosub_aux sub t.\nProof.\n  soterm_ind t as [ v ts ind | op lbt ind ] Case; simpl; introv disj.\n\n  - Case \"sovar\".\n    boolvar; subst; allsimpl.\n    + rw disjoint_singleton_r in disj; repnd.\n      rw @sosub_find_sosub_filter;\n        [|rw in_map_iff; unfold var2sovar; intro k; exrepnd; complete cpx].\n      remember (sosub_find sub (v, 0)) as f;\n        symmetry in Heqf; destruct f; auto.\n    + rw @sosub_find_sosub_filter;\n        [|rw in_map_iff; unfold var2sovar; intro k; exrepnd;\n          cpx; destruct ts; allsimpl; complete cpx].\n      remember (sosub_find sub (v, length ts)) as f;\n        symmetry in Heqf; destruct f.\n      * destruct s.\n        f_equal; f_equal.\n        apply eq_maps; introv i.\n        apply ind; auto.\n        rw disjoint_flat_map_r in disj; apply disj; auto.\n      * f_equal.\n        apply eq_maps; introv i.\n        apply ind; auto.\n        rw disjoint_flat_map_r in disj; apply disj; auto.\n\n  - Case \"soterm\".\n    f_equal.\n    apply eq_maps; introv i.\n    destruct x; simpl.\n    f_equal.\n    rw @sosub_filter_swap.\n    eapply ind; eauto.\n    rw disjoint_flat_map_r in disj.\n    apply disj in i; simpl in i.\n    rw disjoint_app_r in i; sp.\nQed.\n\nLemma disjoint_swap :\n  forall vs1 vs2 l1 l2,\n    disjoint vs1 vs2\n    -> no_repeats vs2\n    -> disjoint l1 l2\n    -> disjoint\n         (swapbvars (mk_swapping vs1 vs2) l1)\n         (swapbvars (mk_swapping vs1 vs2) l2).\nProof.\n  introv disj1 norep disj2 i j.\n  allrw in_swapbvars; exrepnd; subst.\n  apply swapvars_eq in i0; subst; auto.\n  apply disj2 in j1; auto.\nQed.\n\nLemma fo_bound_var_so_swap {o} :\n  forall (t : @SOTerm o) vs1 vs2,\n    fo_bound_vars (so_swap (mk_swapping vs1 vs2) t)\n    = swapbvars (mk_swapping vs1 vs2) (fo_bound_vars t).\nProof.\n  soterm_ind t as [ v ts ind | op lbt ind ] Case; simpl; introv.\n\n  - Case \"sovar\".\n    boolvar; subst; simpl; auto.\n    unfold swapbvars; rw map_flat_map.\n    rw flat_map_map; unfold compose.\n    apply eq_flat_maps; introv i.\n    apply ind; auto.\n\n  - Case \"soterm\".\n    unfold swapbvars; rw map_flat_map.\n    rw flat_map_map; unfold compose.\n    apply eq_flat_maps; introv i.\n    destruct x; simpl.\n    rw map_app.\n    erewrite ind; eauto.\nQed.\n\nLemma swapbvars_app :\n  forall sw vs1 vs2,\n    swapbvars sw (vs1 ++ vs2) = swapbvars sw vs1 ++ swapbvars sw vs2.\nProof.\n  introv; unfold swapbvars; rw map_app; auto.\nQed.\n\nLemma swapbvars_flat_map :\n  forall {A} sw f (l : list A),\n    swapbvars sw (flat_map f l)\n    = flat_map (fun a => swapbvars sw (f a)) l.\nProof.\n  introv; unfold swapbvars.\n  rw map_flat_map; unfold compose; auto.\nQed.\n\nLemma fovars_so_swap {o} :\n  forall (t : @SOTerm o) vs1 vs2,\n    fovars (so_swap (mk_swapping vs1 vs2) t)\n    = swapbvars (mk_swapping vs1 vs2) (fovars t).\nProof.\n  soterm_ind t as [ v ts ind | op lbt ind ] Case; simpl; introv.\n\n  - Case \"sovar\".\n    boolvar; subst; simpl; boolvar; simpl; auto; cpx.\n    + destruct ts; allsimpl; cpx.\n    + rw flat_map_map; unfold compose.\n      rw @swapbvars_flat_map.\n      apply eq_flat_maps; introv i.\n      apply ind; auto.\n\n  - Case \"soterm\".\n    rw @swapbvars_flat_map.\n    rw flat_map_map; unfold compose.\n    apply eq_flat_maps; introv i.\n    destruct x; simpl.\n    rw swapbvars_app.\n    apply app_if; auto.\n    eapply ind; eauto.\nQed.\n\nLemma free_vars_sosub_kind_swapsk {o} :\n  forall (sk : @sosub_kind o) vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> free_vars_sosub_kind (swapsk (mk_swapping vs1 vs2) sk)\n       = swapbvars (mk_swapping vs1 vs2) (free_vars_sosub_kind sk).\nProof.\n  introv norep disj.\n  destruct sk; simpl.\n  unfold free_vars_sosub_kind; simpl.\n\n  revert l.\n  nterm_ind n as [v|f ind|op bs ind] Case; simpl; introv; auto.\n\n  - Case \"vterm\".\n    repeat (rw remove_nvars_cons_r); boolvar; simpl;\n    allrw remove_nvars_nil_r; auto; provefalse.\n    + rw in_map_iff in Heqb; exrepnd.\n      apply swapvars_eq in Heqb1; subst; sp.\n    + destruct Heqb.\n      rw in_map_iff.\n      eexists; eauto.\n\n  - Case \"sterm\".\n    allrw remove_nvars_nil_r.\n    unfold swapbvars; simpl; auto.\n\n  - Case \"oterm\".\n    repeat (rw remove_nvars_flat_map); unfold compose.\n    unfold swapbvars; rw map_flat_map; unfold compose.\n    rw flat_map_map; unfold compose.\n    apply eq_flat_maps; introv i; destruct x; simpl.\n    repeat (rw remove_nvars_app_l).\n    unfold swapbvars; rw <- map_app.\n    eapply ind; eauto.\nQed.\n\nLemma free_vars_sosub_kind_cswapsk {o} :\n  forall (sk : @sosub_kind o) vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> free_vars_sosub_kind (cswapsk (mk_swapping vs1 vs2) sk)\n       = swapbvars (mk_swapping vs1 vs2) (free_vars_sosub_kind sk).\nProof.\n  introv norep disj.\n  destruct sk; simpl.\n  unfold free_vars_sosub_kind; simpl.\n\n  revert l.\n  nterm_ind n as [v|f ind|op bs ind] Case; simpl; introv; auto.\n\n  - Case \"vterm\".\n    repeat (rw remove_nvars_cons_r); boolvar; simpl;\n    allrw remove_nvars_nil_r; auto; provefalse.\n    + rw in_map_iff in Heqb; exrepnd.\n      apply swapvars_eq in Heqb1; subst; sp.\n    + destruct Heqb.\n      rw in_map_iff.\n      eexists; eauto.\n\n  - Case \"sterm\".\n    allrw remove_nvars_nil_r.\n    unfold swapbvars; simpl; auto.\n\n  - Case \"oterm\".\n    repeat (rw remove_nvars_flat_map); unfold compose.\n    unfold swapbvars; rw map_flat_map; unfold compose.\n    rw flat_map_map; unfold compose.\n    apply eq_flat_maps; introv i; destruct x; simpl.\n    repeat (rw remove_nvars_app_l).\n    unfold swapbvars; rw <- map_app.\n    eapply ind; eauto.\nQed.\n\nLemma free_vars_sosub_kind_swapsks {o} :\n  forall (sks : list (@sosub_kind o)) vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> flat_map free_vars_sosub_kind (map (swapsk (mk_swapping vs1 vs2)) sks)\n       = swapbvars (mk_swapping vs1 vs2) (flat_map free_vars_sosub_kind sks).\nProof.\n  induction sks; introv norep disj; simpl; auto.\n  rw IHsks; auto; clear IHsks.\n  rw swapbvars_app.\n  rw @free_vars_sosub_kind_swapsk; auto.\nQed.\n\nLemma free_vars_sk_swapsks {o} :\n  forall (sks : list (@sosub_kind o)) vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> flat_map free_vars_sk (map (swapsk (mk_swapping vs1 vs2)) sks)\n       = swapbvars (mk_swapping vs1 vs2) (flat_map free_vars_sk sks).\nProof.\n  induction sks; introv norep disj; simpl; auto.\n  rw IHsks; auto; clear IHsks.\n  rw swapbvars_app.\n  allrw @free_vars_sk_is_free_vars_sosub_kind.\n  rw @free_vars_sosub_kind_swapsk; auto.\nQed.\n\nLemma free_vars_sk_cswapsks {o} :\n  forall (sks : list (@sosub_kind o)) vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> flat_map free_vars_sk (map (cswapsk (mk_swapping vs1 vs2)) sks)\n       = swapbvars (mk_swapping vs1 vs2) (flat_map free_vars_sk sks).\nProof.\n  induction sks; introv norep disj; simpl; auto.\n  rw IHsks; auto; clear IHsks.\n  rw swapbvars_app.\n  allrw @free_vars_sk_is_free_vars_sosub_kind.\n  rw @free_vars_sosub_kind_cswapsk; auto.\nQed.\n\nLemma bound_vars_swap {o} :\n  forall (t : @NTerm o) vs1 vs2,\n    bound_vars (swap (mk_swapping vs1 vs2) t)\n    = swapbvars (mk_swapping vs1 vs2) (bound_vars t).\nProof.\n  nterm_ind t as [v|f ind|op bs ind] Case; introv; simpl; auto.\n  rw @swapbvars_flat_map.\n  rw flat_map_map; unfold compose.\n  apply eq_flat_maps; introv i; destruct x; simpl.\n  rw swapbvars_app.\n  apply app_if; auto.\n  eapply ind; eauto.\nQed.\n\nLemma bound_vars_cswap {o} :\n  forall (t : @NTerm o) vs1 vs2,\n    bound_vars (cswap (mk_swapping vs1 vs2) t)\n    = swapbvars (mk_swapping vs1 vs2) (bound_vars t).\nProof.\n  nterm_ind t as [v|f ind|op bs ind] Case; introv; simpl; auto.\n  rw @swapbvars_flat_map.\n  rw flat_map_map; unfold compose.\n  apply eq_flat_maps; introv i; destruct x; simpl.\n  rw swapbvars_app.\n  apply app_if; auto.\n  eapply ind; eauto.\nQed.\n\nLemma bound_vars_in_sk_swapsk {o} :\n  forall (sk : @sosub_kind o) vs1 vs2,\n    bound_vars_in_sk (swapsk (mk_swapping vs1 vs2) sk)\n    = swapbvars (mk_swapping vs1 vs2) (bound_vars_in_sk sk).\nProof.\n  destruct sk; introv; simpl.\n  apply bound_vars_swap; auto.\nQed.\n\nLemma bound_vars_sk_swapsk {o} :\n  forall (sk : @sosub_kind o) vs1 vs2,\n    bound_vars_sk (swapsk (mk_swapping vs1 vs2) sk)\n    = swapbvars (mk_swapping vs1 vs2) (bound_vars_sk sk).\nProof.\n  destruct sk; introv; simpl.\n  rw swapbvars_app.\n  apply app_if; auto.\n  apply bound_vars_swap; auto.\nQed.\n\nLemma bound_vars_sk_cswapsk {o} :\n  forall (sk : @sosub_kind o) vs1 vs2,\n    bound_vars_sk (cswapsk (mk_swapping vs1 vs2) sk)\n    = swapbvars (mk_swapping vs1 vs2) (bound_vars_sk sk).\nProof.\n  destruct sk; introv; simpl.\n  rw swapbvars_app.\n  apply app_if; auto.\n  apply bound_vars_cswap; auto.\nQed.\n\nLemma bound_vars_in_sosub_combine_map_swapsk {o} :\n  forall (sks : list (@sosub_kind o)) vs1 vs2 vs,\n    bound_vars_in_sosub (combine vs (map (swapsk (mk_swapping vs1 vs2)) sks))\n    = swapbvars (mk_swapping vs1 vs2) (bound_vars_in_sosub (combine vs sks)).\nProof.\n  induction sks; destruct vs; introv; allsimpl; auto.\n  rw IHsks; clear IHsks.\n  rw swapbvars_app.\n  apply app_if; auto.\n  apply bound_vars_in_sk_swapsk; auto.\nQed.\n\nLemma bound_vars_sosub_combine_map_swapsk {o} :\n  forall (sks : list (@sosub_kind o)) vs1 vs2 vs,\n    bound_vars_sosub (combine vs (map (swapsk (mk_swapping vs1 vs2)) sks))\n    = swapbvars (mk_swapping vs1 vs2) (bound_vars_sosub (combine vs sks)).\nProof.\n  induction sks; destruct vs; introv; allsimpl; auto.\n  rw IHsks; clear IHsks.\n  rw swapbvars_app.\n  apply app_if; auto.\n  apply bound_vars_sk_swapsk; auto.\nQed.\n\nLemma bound_vars_sosub_combine_map_cswapsk {o} :\n  forall (sks : list (@sosub_kind o)) vs1 vs2 vs,\n    bound_vars_sosub (combine vs (map (cswapsk (mk_swapping vs1 vs2)) sks))\n    = swapbvars (mk_swapping vs1 vs2) (bound_vars_sosub (combine vs sks)).\nProof.\n  induction sks; destruct vs; introv; allsimpl; auto.\n  rw IHsks; clear IHsks.\n  rw swapbvars_app.\n  apply app_if; auto.\n  apply bound_vars_sk_cswapsk; auto.\nQed.\n\nLemma free_vars_sosub_combine_map_swapsk {o} :\n  forall (sks : list (@sosub_kind o)) vs vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> free_vars_sosub (combine vs (map (swapsk (mk_swapping vs1 vs2)) sks))\n       = swapbvars (mk_swapping vs1 vs2) (free_vars_sosub (combine vs sks)).\nProof.\n  induction sks; destruct vs; introv norep disj; allsimpl; auto.\n  rw IHsks; auto; clear IHsks.\n  rw swapbvars_app.\n  apply app_if; auto.\n  allrw @free_vars_sk_is_free_vars_sosub_kind.\n  apply free_vars_sosub_kind_swapsk; auto.\nQed.\n\nLemma free_vars_sosub_combine_map_cswapsk {o} :\n  forall (sks : list (@sosub_kind o)) vs vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> free_vars_sosub (combine vs (map (cswapsk (mk_swapping vs1 vs2)) sks))\n       = swapbvars (mk_swapping vs1 vs2) (free_vars_sosub (combine vs sks)).\nProof.\n  induction sks; destruct vs; introv norep disj; allsimpl; auto.\n  rw IHsks; auto; clear IHsks.\n  rw swapbvars_app.\n  apply app_if; auto.\n  allrw @free_vars_sk_is_free_vars_sosub_kind.\n  apply free_vars_sosub_kind_cswapsk; auto.\nQed.\n\nLemma implies_subvars_flat_map_r :\n  forall {A} f (l : list A) k a,\n    LIn a l\n    -> subvars k (f a)\n    -> subvars k (flat_map f l).\nProof.\n  introv i s.\n  allrw subvars_prop; introv h.\n  rw lin_flat_map.\n  eexists; eauto.\nQed.\n\nLemma in_sodom_iff {o}:\n  forall (sub : @SOSub o) v k,\n    LIn (v, k) (sodom sub)\n   <=> {vs : list NVar\n        & {t : NTerm\n        & LIn (v, sosk vs t) sub\n        # k = length vs}}.\nProof.\n  induction sub; introv; simpl; split; intro h; exrepnd; tcsp;\n  destruct a; subst.\n  - dorn h; cpx.\n    + exists l n; sp.\n    + apply IHsub in h; exrepnd; subst.\n      exists vs t; sp.\n  - dorn h0; cpx; ginv; tcsp.\n    right; apply IHsub.\n    exists vs t; sp.\nQed.\n\nLemma select_map :\n  forall {A B} (l : list A) (f : A -> B) n,\n    select n (map f l) = option_map f (select n l).\nProof.\n  induction l; introv; simpl; auto.\n  - destruct n; simpl; auto.\n  - destruct n; simpl; auto.\nQed.\n\nLemma cover_so_vars_so_swap {o} :\n  forall (t : @SOTerm o) vs1 vs2 vs sks,\n    cover_so_vars t (combine vs sks)\n    -> cover_so_vars\n         (so_swap (mk_swapping vs1 vs2) t)\n         (combine vs (map (swapsk (mk_swapping vs1 vs2)) sks)).\nProof.\n  soterm_ind1s t as [ v ts ind | op lbt ind ] Case; simpl; introv cov.\n\n  - Case \"sovar\".\n    boolvar; subst; allsimpl; auto;\n    allrw @cover_so_vars_sovar; repnd; dands; allsimpl; tcsp; introv k.\n\n    + rw null_nil_iff in k; provefalse; sp.\n\n    + rw null_map in k.\n      apply cov0 in k; clear cov0.\n      rw map_length.\n      allrw @in_sodom_iff; exrepnd.\n      exists (swapbvars (mk_swapping vs1 vs2) vs0)\n             (swap (mk_swapping vs1 vs2) t).\n      rw length_swapbvars; dands; auto.\n\n      allrw in_combine_sel_iff; exrepnd.\n      exists n0; rw map_length; dands; auto.\n      rw @select_map; rw <- k2; simpl; auto.\n\n    + rw in_map_iff in k; exrepnd; subst.\n      applydup cov in k1.\n      apply ind; auto.\n\n  - Case \"soterm\".\n    allrw @cover_so_vars_soterm; introv i.\n    rw in_map_iff in i; exrepnd.\n    destruct a; allsimpl; ginv.\n    applydup cov in i1.\n    eapply ind; eauto.\nQed.\n\nLemma cover_so_vars_so_swapc {o} :\n  forall (t : @SOTerm o) vs1 vs2 vs sks,\n    cover_so_vars t (combine vs sks)\n    -> cover_so_vars\n         (so_swap (mk_swapping vs1 vs2) t)\n         (combine vs (map (cswapsk (mk_swapping vs1 vs2)) sks)).\nProof.\n  soterm_ind1s t as [ v ts ind | op lbt ind ] Case; simpl; introv cov.\n\n  - Case \"sovar\".\n    boolvar; subst; allsimpl; auto;\n    allrw @cover_so_vars_sovar; repnd; dands; allsimpl; tcsp; introv k.\n\n    + rw null_nil_iff in k; provefalse; sp.\n\n    + rw null_map in k.\n      apply cov0 in k; clear cov0.\n      rw map_length.\n      allrw @in_sodom_iff; exrepnd.\n      exists (swapbvars (mk_swapping vs1 vs2) vs0)\n             (cswap (mk_swapping vs1 vs2) t).\n      rw length_swapbvars; dands; auto.\n\n      allrw in_combine_sel_iff; exrepnd.\n      exists n0; rw map_length; dands; auto.\n      rw @select_map; rw <- k2; simpl; auto.\n\n    + rw in_map_iff in k; exrepnd; subst.\n      applydup cov in k1.\n      apply ind; auto.\n\n  - Case \"soterm\".\n    allrw @cover_so_vars_soterm; introv i.\n    rw in_map_iff in i; exrepnd.\n    destruct a; allsimpl; ginv.\n    applydup cov in i1.\n    eapply ind; eauto.\nQed.\n\nLemma bound_vars_in_sosub_combine {o} :\n  forall (sks : list (@sosub_kind o)) vs,\n    length vs = length sks\n    -> bound_vars_in_sosub (combine vs sks)\n       = flat_map bound_vars_in_sk sks.\nProof.\n  induction sks; destruct vs; introv len; allsimpl; cpx.\n  rw IHsks; sp.\nQed.\n\nLemma bound_vars_sosub_combine {o} :\n  forall (sks : list (@sosub_kind o)) vs,\n    length vs = length sks\n    -> bound_vars_sosub (combine vs sks)\n       = flat_map bound_vars_sk sks.\nProof.\n  induction sks; destruct vs; introv len; allsimpl; cpx.\n  rw IHsks; sp.\nQed.\n\nLemma free_vars_sosub_combine {o} :\n  forall (sks : list (@sosub_kind o)) vs,\n    length vs = length sks\n    -> free_vars_sosub (combine vs sks)\n       = flat_map free_vars_sk sks.\nProof.\n  induction sks; destruct vs; introv len; allsimpl; cpx.\n  rw IHsks; auto.\nQed.\n\nLemma swapbvars_trivial :\n  forall vs1 vs2 l,\n    disjoint l vs1\n    -> disjoint l vs2\n    -> swapbvars (mk_swapping vs1 vs2) l = l.\nProof.\n  induction l; introv d1 d2; allsimpl; auto.\n  allrw disjoint_cons_l; repnd.\n  rw IHl; auto.\n  rw swapvar_not_in; auto.\nQed.\n\nLemma eq_map_l :\n  forall A (f : A -> A) (l : list A),\n    (forall x,  LIn x l -> f x = x)\n    -> map f l = l.\nProof.\n  induction l; intro h; allsimpl; tcsp.\n  rw IHl; auto.\n  rw h; auto.\nQed.\n\nLemma cswap_trivial {o} :\n  forall (t : @NTerm o) vs1 vs2,\n    disjoint (allvars t) vs1\n    -> disjoint (allvars t) vs2\n    -> cswap (mk_swapping vs1 vs2) t = t.\nProof.\n  nterm_ind t as [v|f ind|op bs ind] Case; introv d1 d2; allsimpl; auto.\n\n  - Case \"vterm\".\n    allrw disjoint_singleton_l.\n    rw swapvar_not_in; auto.\n\n  - Case \"oterm\".\n    f_equal.\n    allrw disjoint_flat_map_l.\n    apply eq_map_l; introv i.\n    destruct x; allsimpl.\n    applydup d1 in i.\n    applydup d2 in i.\n    allsimpl; allrw disjoint_app_l; repnd.\n    rw swapbvars_trivial; auto.\n    f_equal.\n    eapply ind; eauto.\nQed.\n\nLemma cswapsk_trivial {o} :\n  forall (sk : @sosub_kind o) vs1 vs2,\n    disjoint (bound_vars_sk sk) vs1\n    -> disjoint (bound_vars_sk sk) vs2\n    -> disjoint (free_vars_sk sk) vs1\n    -> disjoint (free_vars_sk sk) vs2\n    -> cswapsk (mk_swapping vs1 vs2) sk = sk.\nProof.\n  destruct sk; introv d1 d2 d3 d4; allsimpl.\n  allrw disjoint_app_l; repnd.\n  rw swapbvars_trivial; auto.\n  f_equal.\n  pose proof (allvars_eq_all_vars n) as e.\n  apply eqvars_sym in e.\n  apply disjoint_sym in d3; apply disjoint_sym in d4.\n  apply disjoint_sym in d0; apply disjoint_sym in d5.\n  apply cswap_trivial.\n  - eapply eqvars_disjoint;[eauto|].\n    rw disjoint_app_l; dands; auto.\n    introv a b.\n    applydup d3 in b.\n    applydup d0 in b.\n    rw in_remove_nvars in b0; sp.\n  - eapply eqvars_disjoint;[eauto|].\n    rw disjoint_app_l; dands; auto.\n    introv a b.\n    applydup d4 in b.\n    applydup d5 in b.\n    rw in_remove_nvars in b0; sp.\nQed.\n\nLemma sosub_aux_alpha_congr {p} :\n  forall (t1 t2 : @SOTerm p) (vs : list NVar) (ts1 ts2 : list sosub_kind),\n    let sub1 := combine vs ts1 in\n    let sub2 := combine vs ts2 in\n    so_alphaeq t1 t2\n    -> length vs = length ts1\n    -> length vs = length ts2\n    -> disjoint (free_vars_sosub sub1) (fo_bound_vars t1)\n    -> disjoint (free_vars_sosub sub2) (fo_bound_vars t2)\n    (* These 2 disjoints we can always assume because they are ensured by sosub *)\n    -> disjoint (bound_vars_sosub sub1) (free_vars_sosub sub1 ++ fovars t1)\n    -> disjoint (bound_vars_sosub sub2) (free_vars_sosub sub2 ++ fovars t2)\n    -> cover_so_vars t1 sub1\n    -> cover_so_vars t2 sub2\n    -> bin_rel_sk alphaeq_sk ts1 ts2\n    -> alphaeq (sosub_aux sub1 t1) (sosub_aux sub2 t2).\nProof.\n  soterm_ind1s t1 as [ v1 ts1 ind1 | op1 lbt1 ind1 ] Case; simpl;\n  introv aeq len1 len2 d1 d2 d3 d4 cov1 cov2 ask.\n\n  - Case \"sovar\".\n    inversion aeq as [? ? ? len imp|]; subst; clear aeq; simpl.\n    remember (sosub_find (combine vs ts0) (v1, length ts1)) as o;\n      destruct o; symmetry in Heqo;\n      remember (sosub_find (combine vs ts2) (v1, length ts4)) as q;\n      destruct q; symmetry in Heqq;\n      try (destruct s); try (destruct s0).\n\n    + rw len in Heqo.\n\n      pose proof (apply_bterm_alpha_congr\n                    (bterm l n)\n                    (bterm l0 n0)\n                    (map (sosub_aux (combine vs ts0)) ts1)\n                    (map (sosub_aux (combine vs ts2)) ts4)) as h.\n      unfold apply_bterm in h; simpl in h.\n\n      revert h.\n      change_to_lsubst_aux4.\n\n      * introv h; apply alphaeq_eq; apply h; clear h; auto.\n\n        {\n          apply alphaeqbt_eq.\n          apply alphaeq_sk_iff_alphaeq_bterm.\n          eapply alphaeq_sosub_kind_if_alphaeq_sosub_find;\n            [|idtac|idtac|exact Heqo|exact Heqq]; auto.\n        }\n\n        {\n          apply bin_rel_nterm_if_combine; allrw map_length; auto.\n          introv i.\n          rw <- @map_combine in i.\n          rw in_map_iff in i; exrepnd; cpx; allsimpl.\n        }\n\n        {\n          rw map_length; unfold num_bvars; simpl; auto.\n          apply sosub_find_some in Heqo; sp; omega.\n        }\n\n      * apply alphaeq_eq; apply h; clear h; auto.\n\n        {\n          apply alphaeqbt_eq.\n          apply alphaeq_sk_iff_alphaeq_bterm.\n          eapply alphaeq_sosub_kind_if_alphaeq_sosub_find;\n            [|idtac|idtac|exact Heqo|exact Heqq]; auto.\n        }\n\n        {\n          apply bin_rel_nterm_if_combine; allrw map_length; auto.\n          introv i.\n          rw <- @map_combine in i.\n          rw in_map_iff in i; exrepnd; cpx; allsimpl.\n          applydup imp in i1.\n          applydup in_combine in i1; repnd.\n          apply alphaeq_eq.\n          apply ind1; auto.\n\n          {\n            rw disjoint_flat_map_r in d1.\n            apply d1 in i3; auto.\n          }\n\n          {\n            rw disjoint_flat_map_r in d2.\n            apply d2 in i2; auto.\n          }\n\n          {\n            rw disjoint_app_r; dands; auto.\n            rw disjoint_flat_map_r in d3.\n            apply d3 in i3; auto.\n          }\n\n          {\n            rw disjoint_app_r; dands; auto.\n            boolvar.\n            {\n              rw disjoint_cons_r in d4; repnd.\n              rw disjoint_flat_map_r in d7.\n              apply d7 in i2; auto.\n            }\n            {\n              rw disjoint_flat_map_r in d4.\n              apply d4 in i2; auto.\n            }\n          }\n\n          {\n            rw @cover_so_vars_sovar in cov1; repnd.\n            apply cov1; auto.\n          }\n\n          {\n            rw @cover_so_vars_sovar in cov2; repnd.\n            apply cov2; auto.\n          }\n        }\n\n        {\n          unfold num_bvars; simpl.\n          apply sosub_find_some in Heqo; repnd; omega.\n        }\n\n      * clear h; allsimpl; clear d.\n        apply sosub_find_some in Heqq; repnd.\n        rw @range_combine;[|rw map_length; omega].\n        allrw disjoint_cons_r; repnd.\n        rw flat_map_map; unfold compose.\n        eapply disjoint_bound_vars_prop3; eauto.\n        {\n          boolvar; auto.\n          allrw disjoint_cons_r; sp.\n        }\n        {\n          allrw @cover_so_vars_sovar; sp.\n        }\n\n      * clear h; allsimpl; clear d.\n        apply sosub_find_some in Heqq; repnd.\n        rw @range_combine;[|rw map_length; omega].\n        allrw disjoint_cons_r; repnd.\n        rw flat_map_map; unfold compose.\n        eapply disjoint_bound_vars_prop3; eauto.\n        {\n          boolvar; auto.\n          allrw disjoint_cons_r; sp.\n        }\n        {\n          allrw @cover_so_vars_sovar; sp.\n        }\n\n      * clear h; allsimpl; clear d.\n        apply sosub_find_some in Heqo; repnd.\n        rw @range_combine;[|rw map_length; omega].\n        allrw disjoint_cons_r; repnd.\n        rw flat_map_map; unfold compose.\n        eapply disjoint_bound_vars_prop3; eauto.\n        allrw @cover_so_vars_sovar; sp.\n\n      * clear h; allsimpl; clear d.\n        apply sosub_find_some in Heqo; repnd.\n        rw @range_combine;[|rw map_length; omega].\n        allrw disjoint_cons_r; repnd.\n        rw flat_map_map; unfold compose.\n        eapply disjoint_bound_vars_prop3; eauto.\n        allrw @cover_so_vars_sovar; sp.\n\n      * clear h; allsimpl.\n        apply sosub_find_some in Heqq; repnd.\n        rw @range_combine;[|rw map_length; omega].\n        allrw disjoint_cons_r; repnd.\n        rw flat_map_map; unfold compose.\n        eapply disjoint_bound_vars_prop3; eauto.\n        allrw @cover_so_vars_sovar; sp.\n        {\n          boolvar; auto.\n          allrw disjoint_cons_r; sp.\n        }\n        {\n          allrw @cover_so_vars_sovar; sp.\n        }\n\n      * clear h; allsimpl.\n        apply sosub_find_some in Heqq; repnd.\n        rw @range_combine;[|rw map_length; omega].\n        allrw disjoint_cons_r; repnd.\n        rw flat_map_map; unfold compose.\n        eapply disjoint_bound_vars_prop3; eauto.\n        allrw @cover_so_vars_sovar; sp.\n        {\n          boolvar; auto.\n          allrw disjoint_cons_r; sp.\n        }\n        {\n          allrw @cover_so_vars_sovar; sp.\n        }\n\n    + rw len in Heqo.\n      eapply false_if_alphaeq_sosub_find in Heqo; eauto; sp.\n\n    + rw len in Heqo.\n      eapply false_if_alphaeq_sosub_find in Heqo; eauto; sp.\n      apply bin_rel_sk_sym; auto.\n\n    + apply alphaeq_apply_list; auto.\n      * apply alphaeq_eq; auto.\n      * apply bin_rel_nterm_if_combine; allrw map_length; auto.\n        introv i.\n        rw <- @map_combine in i.\n        rw in_map_iff in i; exrepnd; cpx; allsimpl.\n        applydup imp in i1.\n        applydup in_combine in i1; repnd.\n        apply alphaeq_eq.\n        apply ind1; auto.\n\n        {\n          introv i j; apply d1 in i.\n          destruct i; rw lin_flat_map; eexists; eauto.\n        }\n\n        {\n          introv i j; apply d2 in i.\n          destruct i; rw lin_flat_map; eexists; eauto.\n        }\n\n        {\n          allrw disjoint_app_r; repnd; dands; auto.\n          boolvar; subst; allsimpl; cpx.\n          rw disjoint_flat_map_r in d3; apply d3 in i3; auto.\n        }\n\n        {\n          allrw disjoint_app_r; repnd; dands; auto.\n          boolvar; subst; allsimpl; cpx.\n          rw disjoint_flat_map_r in d4; apply d4 in i2; auto.\n        }\n\n        {\n          rw @cover_so_vars_sovar in cov1; repnd.\n          apply cov1; auto.\n        }\n\n        {\n          rw @cover_so_vars_sovar in cov2; repnd.\n          apply cov2; auto.\n        }\n\n  - Case \"soterm\".\n    inversion aeq as [|? ? ? len imp]; subst; clear aeq; simpl.\n    constructor; try (complete (repeat (rw map_length); auto)).\n    introv i.\n    rw map_length in i.\n    repeat (rw @selectbt_map_sosub_b_aux).\n    assert (LIn (selectsobt lbt1 n, selectsobt bts2 n) (combine lbt1 bts2))\n      as j by (apply in_combine_sel_iff; exists n; dands; auto; try omega;\n               apply selectsobt_as_select; auto; try omega).\n    remember (selectsobt lbt1 n) as bt1.\n    remember (selectsobt bts2 n) as bt2.\n    clear Heqbt1 Heqbt2.\n    applydup imp in j.\n    destruct bt1, bt2; simpl.\n\n    apply so_alphaeqbt_vs_implies_more\n    with (l2 := vs\n                ++\n                allvars (sosub_aux (sosub_filter (combine vs ts1) (vars2sovars l)) s)\n                ++\n                allvars (sosub_aux (sosub_filter (combine vs ts2) (vars2sovars l0)) s0)\n                ++\n                bound_vars_sosub (combine vs ts1)\n                ++\n                bound_vars_sosub (combine vs ts2)\n                ++\n                free_vars_sosub (combine vs ts1)\n                ++\n                free_vars_sosub (combine vs ts2)) in j0; auto.\n\n    inversion j0 as [? ? ? ? ? le1 le2 disj norep aeq]; subst; clear j0.\n    apply (aeqbt [] vs0); auto; simpl.\n\n    + eapply subvars_disjoint_r;[|complete eauto].\n      repeat (rw subvars_app_l); dands.\n\n      * apply subvars_app_weak_r.\n        apply subvars_app_weak_l; auto.\n\n      * apply subvars_app_weak_r.\n        apply subvars_app_weak_r.\n        apply subvars_app_weak_l; auto.\n\n      * apply subvars_app_weak_l.\n        apply subvars_app_weak_r.\n        apply subvars_app_weak_l; auto.\n\n      * apply subvars_app_weak_l.\n        apply subvars_app_weak_r.\n        apply subvars_app_weak_r.\n        apply subvars_app_weak_l; auto.\n\n    + assert (disjoint l vs0 # disjoint l0 vs0 # disjoint vs vs0)\n        as disjl by (allrw disjoint_app_r; sp; apply disjoint_sym; auto); repnd.\n\n      applydup in_combine in j; repnd.\n      simpl in d2.\n      rw disjoint_flat_map_r in d1; applydup d1 in j1 as disjb1.\n      rw disjoint_flat_map_r in d2; applydup d2 in j0 as disjb2.\n      simpl in disjb1, disjb2.\n      rw disjoint_app_r in disjb1; rw disjoint_app_r in disjb2; repnd.\n\n      apply so_alphaeq_vs_implies_less with (l2 := []) in aeq; auto.\n\n      repeat (rw @sosub_aux_cswap_cswap3; auto);\n        [\n        | allrw disjoint_app_r; sp;\n          rw @sodom_sosub_filter;\n          apply subvars_disjoint_r with (l2 := sovars2vars (sodom (combine vs ts2)));\n          [ apply subvars_sovars2vars_prop2;\n            apply subsovars_remove_so_vars\n          | rewrite @sovars2vars_sodom_combine; auto\n          ]\n        | rw @sodom_sosub_filter; complete (apply disjoint_get_fo_vars_remove)\n        | rw @cover_so_vars_soterm in cov2;\n          apply cover_so_vars_sosub_filter;\n          eapply cov2; eauto\n        | allrw disjoint_app_r; sp;\n          rw @sodom_sosub_filter;\n          apply subvars_disjoint_r with (l2 := sovars2vars (sodom (combine vs ts2)));\n          [ apply subvars_sovars2vars_prop2;\n            erewrite alphaeq_sks_implies_eq_sodom_combine; eauto;\n            apply subsovars_remove_so_vars\n          | rewrite @sovars2vars_sodom_combine; auto\n          ]\n        | rw @sodom_sosub_filter; complete (apply disjoint_get_fo_vars_remove)\n        | rw @cover_so_vars_soterm in cov1;\n          apply cover_so_vars_sosub_filter;\n          eapply cov1; eauto\n        ].\n\n      repeat (rw <- @sosub_filter_cswap_range_sosub; auto).\n      repeat (rw @cswap_range_sosub_combine).\n\n      repeat (rw @sosub_aux_sosub_filter; auto);\n      [\n      | apply disjoint_fovars_so_swap; auto; allrw disjoint_app_r; repnd; complete auto\n      | apply disjoint_fovars_so_swap; auto; allrw disjoint_app_r; repnd; complete auto\n      ].\n\n      pose proof (ind1\n                    s\n                    (so_swap (mk_swapping l vs0) s)\n                    l\n                    j1\n                    (sosize_so_swap_le s (mk_swapping l vs0))\n                    (so_swap (mk_swapping l0 vs0) s0)\n                    vs\n                    (map (cswapsk (mk_swapping l vs0)) ts1)\n                    (map (cswapsk (mk_swapping l0 vs0)) ts2)\n                 ) as h; simpl in h.\n      repeat (autodimp h hyp); try (rw map_length; complete auto).\n\n      * rw @fo_bound_var_so_swap.\n        rw @free_vars_sosub_combine; [|rw map_length; complete auto].\n        rewrite free_vars_sk_cswapsks; auto.\n        apply disjoint_swap; auto.\n        rw @free_vars_sosub_combine in disjb1; auto.\n\n      * rw @fo_bound_var_so_swap.\n        rw @free_vars_sosub_combine; [|rw map_length; complete auto].\n        rewrite free_vars_sk_cswapsks; auto.\n        apply disjoint_swap; auto.\n        rw @free_vars_sosub_combine in disjb2; auto.\n\n      * rw @bound_vars_sosub_combine_map_cswapsk.\n        rw @free_vars_sosub_combine_map_cswapsk; auto.\n        rw @fovars_so_swap.\n        rw <- swapbvars_app.\n        apply disjoint_swap; auto.\n        eapply subvars_disjoint_r;[|exact d3].\n        apply subvars_app_l; dands; auto.\n        {\n          apply subvars_app_weak_l; auto.\n        }\n        {\n          apply subvars_app_weak_r.\n          eapply implies_subvars_flat_map_r; eauto; simpl.\n          apply subvars_app_weak_r; auto.\n        }\n\n      * rw @bound_vars_sosub_combine_map_cswapsk.\n        rw @free_vars_sosub_combine_map_cswapsk; auto.\n        rw @fovars_so_swap.\n        rw <- swapbvars_app.\n        apply disjoint_swap; auto.\n        eapply subvars_disjoint_r;[|exact d4].\n        apply subvars_app_l; dands; auto.\n        {\n          apply subvars_app_weak_l; auto.\n        }\n        {\n          apply subvars_app_weak_r.\n          eapply implies_subvars_flat_map_r; eauto; simpl.\n          apply subvars_app_weak_r; auto.\n        }\n\n      * rw @cover_so_vars_soterm in cov1.\n        apply cov1 in j1.\n        apply cover_so_vars_so_swapc; auto.\n\n      * rw @cover_so_vars_soterm in cov2.\n        apply cov2 in j0.\n        apply cover_so_vars_so_swapc; auto.\n\n      * allsimpl.\n        rw disjoint_app_r in d3; rw disjoint_app_r in d4; repnd.\n        rw disjoint_flat_map_r in d3; rw disjoint_flat_map_r in d4.\n        applydup d3 in j1.\n        applydup d4 in j0.\n        simpl in j2, j3.\n        rw disjoint_app_r in j2; rw disjoint_app_r in j3; repnd.\n        rw @bound_vars_sosub_combine in j4; auto.\n        rw @bound_vars_sosub_combine in j5; auto.\n\n        unfold bin_rel_sk, binrel_list.\n        allrw map_length.\n        unfold bin_rel_sk, binrel_list in ask; repnd.\n        dands; auto; introv x.\n        applydup ask in x.\n\n        assert (default_sk = cswapsk (mk_swapping l vs0) (@default_sk p))\n          as e1 by sp.\n        rw e1; clear e1; rw map_nth; simpl; fold (@mk_axiom p); fold (@default_sk p).\n        assert (default_sk = cswapsk (mk_swapping l0 vs0) (@default_sk p))\n          as e2 by sp.\n        rw e2; clear e2; rw map_nth; simpl; fold (@mk_axiom p); fold (@default_sk p).\n\n        pose proof (nth_in _ n0 ts1 default_sk) as i1.\n        pose proof (nth_in _ n0 ts2 default_sk) as i2.\n        autodimp i1 hyp; autodimp i2 hyp; try omega.\n        remember (nth n0 ts1 default_sk) as sk1.\n        remember (nth n0 ts2 default_sk) as sk2.\n        clear Heqsk1 Heqsk2.\n\n        rw @free_vars_sosub_combine in disjb3; auto.\n        rw @free_vars_sosub_combine in disjb0; auto.\n        rw disjoint_flat_map_l in j5.\n        rw disjoint_flat_map_l in j4.\n        rw disjoint_flat_map_l in disjb3.\n        rw disjoint_flat_map_l in disjb0.\n        applydup j5 in i1.\n        applydup j4 in i2.\n        applydup disjb3 in i1.\n        applydup disjb0 in i2.\n        repeat (rw @cswapsk_trivial; auto).\n\n        {\n          allrw disjoint_app_r; repnd.\n          rw @bound_vars_sosub_combine in disj8; auto.\n          rw disjoint_flat_map_r in disj8.\n          applydup disj8 in i2.\n          apply disjoint_sym; auto.\n        }\n\n        {\n          allrw disjoint_app_r; repnd.\n          rw @free_vars_sosub_combine in disj0; auto.\n          rw disjoint_flat_map_r in disj0.\n          applydup disj0 in i2.\n          apply disjoint_sym; auto.\n        }\n\n        {\n          allrw disjoint_app_r; repnd.\n          rw @bound_vars_sosub_combine in disj7; auto.\n          rw disjoint_flat_map_r in disj7.\n          applydup disj7 in i1.\n          apply disjoint_sym; auto.\n        }\n\n        {\n          allrw disjoint_app_r; repnd.\n          rw @free_vars_sosub_combine in disj9; auto.\n          rw disjoint_flat_map_r in disj9.\n          applydup disj9 in i1.\n          apply disjoint_sym; auto.\n        }\nQed.\n\nLemma sosub_change_bvars_alpha_combine {o} :\n  forall (sks : list (@sosub_kind o)) vs l,\n    sosub_change_bvars_alpha l (combine vs sks)\n    = combine vs (map (sk_change_bvars_alpha l) sks).\nProof.\n  induction sks; destruct vs; introv; allsimpl; auto.\n  rw IHsks; auto.\nQed.\n\nLemma free_vars_sk_change_bvars_alpha {o} :\n  forall (sk : @sosub_kind o) vs,\n    free_vars_sk (sk_change_bvars_alpha vs sk)\n    = free_vars_sk sk.\nProof.\n  destruct sk; introv; simpl.\n  match goal with\n    | [ |- context[fresh_distinct_vars ?a ?b] ] =>\n      remember (fresh_distinct_vars a b) as f\n  end.\n  apply fresh_distinct_vars_spec1 in Heqf; repnd.\n  allrw disjoint_app_r; repnd.\n  pose proof (free_vars_lsubst_aux_var_ren (change_bvars_alpha vs n) l f []) as h.\n  repeat (autodimp h hyp); allrw app_nil_r.\n  rw h; rw @free_vars_change_bvars_alpha; auto.\nQed.\n\nLemma allvars_range_sosub_combine {o} :\n  forall (sks : list (@sosub_kind o)) vs,\n    length vs = length sks\n    -> allvars_range_sosub (combine vs sks)\n       = flat_map allvars_sk sks.\nProof.\n  induction sks; destruct vs; introv len; allsimpl; tcsp.\n  rw IHsks; auto.\nQed.\n\nLemma free_vars_subvars_allvars_sk {o} :\n  forall sk : @sosub_kind o,\n    subvars (free_vars_sk sk) (allvars_sk sk).\nProof.\n  destruct sk; simpl.\n  rw subvars_prop; introv i.\n  rw in_remove_nvars in i; rw in_app_iff; repnd; right.\n  pose proof (allvars_eq_all_vars n) as e.\n  rw eqvars_prop in e; apply e; rw in_app_iff; sp.\nQed.\n\nLemma sodom_combine_sk_change_bvars_alpha {o} :\n  forall (sks : list (@sosub_kind o)) vs l,\n    sodom (combine vs (map (sk_change_bvars_alpha l) sks))\n    = sodom (combine vs sks).\nProof.\n  induction sks; destruct vs; introv; allsimpl; auto.\n  destruct a; rw IHsks.\n  simpl.\n  match goal with\n    | [ |- context[fresh_distinct_vars ?a ?b] ] =>\n      remember (fresh_distinct_vars a b) as f\n  end.\n  apply fresh_distinct_vars_spec1 in Heqf; repnd; allrw; sp.\nQed.\n\nLemma cover_so_vars_sk_change_bvars_alpha {o} :\n  forall (t : @SOTerm o) vs sks l,\n    cover_so_vars t (combine vs sks)\n    <=> cover_so_vars t (combine vs (map (sk_change_bvars_alpha l) sks)).\nProof.\n  introv.\n  unfold cover_so_vars.\n  rw @sodom_combine_sk_change_bvars_alpha; sp.\nQed.\n\nLemma alphaeq_sk_trans {o} :\n  forall sk1 sk2 sk3 : @sosub_kind o,\n    alphaeq_sk sk1 sk2\n    -> alphaeq_sk sk2 sk3\n    -> alphaeq_sk sk1 sk3.\nProof.\n  destruct sk1, sk2, sk3; introv aeq1 aeq2.\n  allunfold @alphaeq_sk; allsimpl.\n  allrw @alphaeqbt_eq.\n  eapply alpha_eq_bterm_trans; eauto.\nQed.\n\nLemma alphaeq_sk_sym {o} :\n  forall (sk1 sk2 : @sosub_kind o),\n    alphaeq_sk sk1 sk2 -> alphaeq_sk sk2 sk1.\nProof.\n  introv aeq.\n  destruct sk1, sk2.\n  allunfold @alphaeq_sk; allsimpl.\n  apply alphaeqbt_eq.\n  apply alphaeqbt_eq in aeq.\n  apply alpha_eq_bterm_sym; auto.\nQed.\n\nLemma alphaeq_sk_change_bvars_alpha {o} :\n  forall (sk : @sosub_kind o) l,\n    alphaeq_sk sk (sk_change_bvars_alpha l sk).\nProof.\n  destruct sk; introv.\n  unfold alphaeq_sk; simpl.\n  match goal with\n    | [ |- context[fresh_distinct_vars ?a ?b] ] =>\n      remember (fresh_distinct_vars a b) as f\n  end.\n  apply fresh_distinct_vars_spec1 in Heqf; repnd.\n  rw disjoint_app_r in Heqf1; repnd.\n\n  pose proof (btchange_alpha_aux l (change_bvars_alpha l0 n) f) as h;\n    repeat (autodimp h hyp); eauto with slow.\n  revert h.\n  change_to_lsubst_aux4; introv h.\n  apply alphaeqbt_eq.\n  eapply alpha_eq_bterm_trans;[|exact h].\n  apply alpha_eq_bterm_congr.\n\n  pose proof (change_bvars_alpha_spec n l0) as k; simpl in k; repnd; auto.\nQed.\n\nLemma so_alphaeq_vs_iff {p} :\n  forall l (t1 t2 : @SOTerm p),\n    so_alphaeq_vs l t1 t2\n    <=> so_alphaeq t1 t2.\nProof.\n  introv; split; intro k.\n  - apply so_alphaeq_exists; eexists; eauto.\n  - rw @so_alphaeq_all in k; sp.\nQed.\n\nLemma so_alphaeq_add_so_swap2 {p} :\n  forall vs1 vs2 (t1 t2 : @SOTerm p),\n    length vs1 = length vs2\n    -> no_repeats vs2\n    -> disjoint vs2 (vs1 ++ all_fo_vars t1 ++ all_fo_vars t2)\n    -> so_alphaeq t1 t2\n    -> so_alphaeq\n         (so_swap (mk_swapping vs1 vs2) t1)\n         (so_swap (mk_swapping vs1 vs2) t2).\nProof.\n  introv len norep2 disj aeq.\n  rw <- (@so_alphaeq_vs_iff p (vs1 ++ vs2 ++ [])).\n  apply so_alphaeq_add_so_swap; auto.\n  apply so_alphaeq_vs_iff; auto.\nQed.\n\nLemma so_alphaeq_vs_trans {o} :\n  forall (t1 t2 t3 : @SOTerm o) vs,\n    so_alphaeq_vs vs t1 t2\n    -> so_alphaeq_vs vs t2 t3\n    -> so_alphaeq_vs vs t1 t3.\nProof.\n  soterm_ind1s t1 as [v1 ts1 ind1|op1 bs1 ind1] Case; introv aeq1 aeq2; allsimpl.\n\n  - Case \"sovar\".\n    inversion aeq1 as [? ? ? len1 imp1|]; subst; clear aeq1.\n    inversion aeq2 as [? ? ? len2 imp2|]; subst; clear aeq2.\n    constructor; try omega.\n    introv i.\n    rw in_combine_sel_iff in i; exrepnd.\n\n    pose proof (nth_select1 n ts1 default_soterm i1) as h1.\n    pose proof (nth_select1 n ts3 default_soterm i2) as h2.\n    rw h1 in i3; rw h2 in i0; cpx; clear h1 h2.\n\n    pose proof (imp1 (nth n ts1 default_soterm) (nth n ts2 default_soterm)) as h1.\n    pose proof (imp2 (nth n ts2 default_soterm) (nth n ts3 default_soterm)) as h2.\n    autodimp h1 hyp.\n    {\n      apply in_combine_sel_iff; exists n; dands; auto; try omega;\n      symmetry; apply nth_select1; auto; omega.\n    }\n    autodimp h2 hyp.\n    {\n      apply in_combine_sel_iff; exists n; dands; auto; try omega;\n      symmetry; apply nth_select1; auto; omega.\n    }\n\n    eapply ind1; eauto.\n    apply nth_in; auto.\n\n  - Case \"soterm\".\n    inversion aeq1 as [|? ? ? len1 imp1]; subst; clear aeq1.\n    inversion aeq2 as [|? ? ? len2 imp2]; subst; clear aeq2.\n    constructor; try omega.\n    introv i.\n    destruct b1, b2.\n    rw in_combine_sel_iff in i; exrepnd.\n\n    pose proof (nth_select1 n bs1  default_sobterm i1) as h1.\n    pose proof (nth_select1 n bts0 default_sobterm i2) as h2.\n    rw h1 in i3; rw h2 in i0; cpx; clear h1 h2.\n\n    pose proof (imp1 (nth n bs1  default_sobterm) (nth n bts2 default_sobterm)) as h1; clear imp1.\n    pose proof (imp2 (nth n bts2 default_sobterm) (nth n bts0 default_sobterm)) as h2; clear imp2.\n    autodimp h1 hyp.\n    {\n      apply in_combine_sel_iff; exists n; dands; auto; try omega;\n      symmetry; apply nth_select1; auto; omega.\n    }\n    autodimp h2 hyp.\n    {\n      apply in_combine_sel_iff; exists n; dands; auto; try omega;\n      symmetry; apply nth_select1; auto; omega.\n    }\n\n    pose proof (nth_in _ n bs1 default_sobterm i1) as j1.\n    pose proof (nth_in _ n bts0 default_sobterm i2) as j2.\n    rw <- i3 in h1; rw <- i3 in j1; clear i3.\n    rw <- i0 in h2; rw <- i0 in j2; clear i0.\n    remember (nth n bts2 default_sobterm) as b; clear Heqb.\n\n    inversion h1 as [? ? ? ? ? l1 l2 disj1 norep1 aeq1]; subst; clear h1.\n\n    assert (subvars vs (vs\n                          ++ (vs0\n                                ++ l\n                                ++ all_fo_vars s\n                                ++ all_fo_vars t2\n                                ++ all_fo_vars (so_swap (mk_swapping l vs0) s)\n                                ++ all_fo_vars (so_swap (mk_swapping vs2 vs0) t2)\n                             )\n                       )\n           ) as sv by (apply subvars_app_weak_l; auto).\n    eapply so_alphaeqbt_vs_implies_more in h2;[|exact sv].\n\n    inversion h2 as [? ? ? ? ? l3 l4 disj2 norep2 aeq2]; subst; clear h2.\n    apply (soaeqbt vs vs1); auto;\n    try omega;\n    try (complete (allrw disjoint_app_r; sp)).\n\n    apply so_alphaeq_vs_iff in aeq1.\n    apply so_alphaeq_vs_iff in aeq2.\n\n    apply (so_alphaeq_add_so_swap2 vs0 vs1) in aeq1; auto;\n    try omega;\n    try (complete (allrw disjoint_app_r; sp)).\n\n    repeat (rw @so_swap_so_swap in aeq1).\n    repeat (rw mk_swapping_app in aeq1; auto).\n\n    rw @so_swap_disj_chain in aeq1; auto;\n    try omega;\n    try (complete (allrw disjoint_app_r; sp; eauto with slow)).\n\n    rw @so_swap_disj_chain in aeq1; auto;\n    try omega;\n    try (complete (allrw disjoint_app_r; sp; eauto with slow)).\n\n    apply so_alphaeq_vs_iff.\n    eapply ind1;[exact j1|idtac|exact aeq1|exact aeq2].\n    rw @sosize_so_swap; auto.\nQed.\n\nLemma so_alphaeq_trans {o} :\n  forall (t1 t2 t3 : @SOTerm o),\n    so_alphaeq t1 t2\n    -> so_alphaeq t2 t3\n    -> so_alphaeq t1 t3.\nProof.\n  introv aeq1 aeq2.\n  pose proof (so_alphaeq_vs_trans t1 t2 t3 []); sp.\nQed.\n\nFixpoint soren_filter (ren : soren) (vars : list sovar_sig) : soren :=\n  match ren with\n    | nil => nil\n    | (sov,v) :: xs =>\n      if memsovar sov vars\n      then soren_filter xs vars\n      else (sov,v) :: soren_filter xs vars\n  end.\n\nFixpoint so_rename {p} (ren : soren) (t : @SOTerm p) :=\n  match t with\n    | sovar v ts =>\n      sovar\n        (sovar2var (rename_sovar ren (v,length ts)))\n        (map (so_rename ren) ts)\n    | soterm o bs => soterm o (map (so_rename_bt ren) bs)\n  end\nwith so_rename_bt {p} ren bt :=\n       match bt with\n         | sobterm vs t =>\n           sobterm vs (so_rename (soren_filter ren (vars2sovars vs)) t)\n       end.\n\nLemma swapvar_is_rename_var :\n  forall v vs1 vs2,\n    !LIn v vs2\n    -> no_repeats vs2\n    -> disjoint vs1 vs2\n    -> swapvar (mk_swapping vs1 vs2) v\n       = rename_var (mk_swapping vs1 vs2) v.\nProof.\n  induction vs1; destruct vs2; introv ni norep disj;\n  unfold rename_var; allsimpl; auto.\n  allrw not_over_or; repnd.\n  allrw disjoint_cons_l.\n  allrw disjoint_cons_r; allsimpl; repnd.\n  allrw not_over_or; repnd.\n  allrw no_repeats_cons; repnd.\n  unfold oneswapvar.\n  boolvar; tcsp.\n  - apply swapvar_not_in; auto.\n  - apply IHvs1; auto.\nQed.\n\nLemma in_combine_swap :\n  forall {A} (l1 l2 : list A) a1 a2,\n    length l1 = length l2\n    -> LIn (a1, a2) (combine l1 l2)\n    -> LIn (a2, a1) (combine l2 l1).\nProof.\n  induction l1; destruct l2; introv len i; allsimpl; cpx.\n  dorn i; cpx.\nQed.\n\nLemma so_alphaeq_vs_sym {o} :\n  forall (t1 t2 : @SOTerm o) vs,\n    so_alphaeq_vs vs t1 t2 -> so_alphaeq_vs vs t2 t1.\nProof.\n  soterm_ind1s t1 as [v ts ind|op bs ind] Case; introv aeq.\n\n  - Case \"sovar\".\n    inversion aeq as [? ? ? len imp|]; subst; clear aeq.\n    constructor; auto.\n    introv i.\n    apply in_combine_swap in i; auto.\n    applydup imp in i.\n    apply ind; auto.\n    apply in_combine in i; sp.\n\n  - Case \"soterm\".\n    inversion aeq as [|? ? ? len imp]; subst; clear aeq.\n    constructor; auto.\n    introv i.\n    apply in_combine_swap in i; auto.\n    applydup imp in i.\n    destruct b1, b2.\n    inversion i0 as [? ? ? ? ? len1 len2 disj norep ae]; subst; clear i0.\n    apply (soaeqbt vs vs0); auto;\n    try omega;\n    try (complete (allrw disjoint_app_r; sp)).\n    apply in_combine in i; repnd.\n    eapply ind; eauto.\n    rw @sosize_so_swap; auto.\nQed.\n\nLemma so_alphaeq_refl {o} :\n  forall t : @SOTerm o, so_alphaeq t t.\nProof.\n  soterm_ind1s t as [v ts ind|op bs ind] Case; auto.\n\n  - Case \"sovar\".\n    constructor; auto.\n    introv i.\n    apply in_combine_sel_iff in i; exrepnd.\n    rw <- i3 in i0; ginv; apply ind; auto.\n    symmetry in i3; apply select_in in i3; auto.\n\n  - Case \"soterm\".\n    constructor; auto.\n    introv i.\n    apply in_combine_sel_iff in i; exrepnd.\n    rw <- i3 in i0; ginv.\n    symmetry in i3; apply select_in in i3; auto.\n    destruct b1.\n    pose proof (fresh_vars (length l) (l ++ all_fo_vars s)) as h; exrepnd.\n    apply (soaeqbt [] lvn); allsimpl; auto;\n    [allrw disjoint_app_r; complete sp|].\n    eapply ind; eauto.\n    rw @sosize_so_swap; auto.\nQed.\nHint Immediate so_alphaeq_refl.\n\nLemma app_combine :\n  forall {A} (vs1 vs2 vs3 vs4 : list A),\n    length vs1 = length vs2\n    -> combine vs1 vs2 ++ combine vs3 vs4\n       = combine (vs1 ++ vs3) (vs2 ++ vs4).\nProof.\n  induction vs1; destruct vs2; introv len; allsimpl; cpx.\n  rw IHvs1; auto.\nQed.\n\nLemma foren_find_app :\n  forall v ren1 ren2,\n    foren_find (ren1 ++ ren2) v\n    = match foren_find ren1 v with\n        | Some w => Some w\n        | None => foren_find ren2 v\n      end.\nProof.\n  induction ren1; simpl; sp.\n  destruct a0; destruct v; boolvar; cpx.\nQed.\n\nLemma foren_find_none :\n  forall (ren : foren) v,\n    foren_find ren v = None\n    -> !LIn v (foren_dom ren).\nProof.\n  induction ren; introv k; allsimpl; tcsp.\n  destruct a; boolvar; cpx.\n  apply IHren in k.\n  apply not_over_or; sp.\nQed.\n\nLemma foren_find_filter_eq :\n  forall ren1 ren2 v,\n    !LIn v (foren_dom ren1)\n    -> foren_find (foren_filter ren2 (foren_dom ren1)) v\n       = foren_find ren2 v.\nProof.\n  induction ren2; introv ni; allsimpl; auto.\n  destruct a; boolvar; simpl; boolvar; tcsp.\nQed.\n\nLemma rename_var_filter :\n  forall ren1 ren2 v,\n    rename_var (ren1 ++ ren2) v\n    = rename_var (ren1 ++ foren_filter ren2 (foren_dom ren1)) v.\nProof.\n  unfold rename_var; introv.\n  allrw foren_find_app.\n  remember (foren_find ren1 v) as f1; destruct f1; symmetry in Heqf1; auto.\n  apply foren_find_none in Heqf1.\n  rw foren_find_filter_eq; auto.\nQed.\n\nLemma foren_vars_app :\n  forall ren1 ren2 : foren,\n    foren_vars (ren1 ++ ren2) = foren_vars ren1 ++ foren_vars ren2.\nProof.\n  induction ren1; introv; allsimpl; auto.\n  destruct a; simpl.\n  rw IHren1; auto.\nQed.\n\n(*\nLemma fo_change_bvars_alpha_filter {o} :\n  forall (t : @SOTerm o) vs ren1 ren2,\n    so_alphaeq\n      (fo_change_bvars_alpha vs (ren1 ++ ren2) t)\n      (fo_change_bvars_alpha vs (ren1 ++ foren_filter ren2 (foren_dom ren1)) t).\nProof.\n  soterm_ind t as [v ts ind|op bs ind] Case; introv; simpl.\n\n  - Case \"sovar\".\n    boolvar; subst; allsimpl.\n    + rw rename_var_filter; auto.\n    + constructor; allrw map_length; auto.\n      introv i.\n      rw <- @map_combine in i.\n      rw in_map_iff in i; exrepnd; cpx.\n      apply in_combine_sel_iff in i1; exrepnd.\n      rw <- i3 in i0; ginv.\n      symmetry in i3; apply select_in in i3.\n      apply ind; simpl; auto.\n\n  - Case \"soterm\".\n    constructor; allrw map_length; auto.\n    introv i.\n    rw <- @map_combine in i.\n    rw in_map_iff in i; exrepnd; cpx; allsimpl.\n    apply in_combine_sel_iff in i1; exrepnd.\n    rw <- i3 in i0; ginv.\n    symmetry in i3; apply select_in in i3.\n    destruct a0; simpl.\n\n    repeat gen_fresh.\n    allrw foren_vars_app.\n    pose proof (fresh_vars\n                  (length f)\n                  (f\n                     ++ f0\n                     ++ vs\n                     ++ all_fo_vars s\n                     ++ foren_vars ren1\n                     ++ foren_vars ren2\n                     ++ all_fo_vars (fo_change_bvars_alpha vs (mk_foren l f ++ ren1 ++ ren2) s)\n                     ++ all_fo_vars (fo_change_bvars_alpha vs (mk_foren l f0 ++ ren1 ++ foren_filter ren2 (foren_dom ren1)) s)\n                  )\n               ) as fv; exrepnd.\n    apply (soaeqbt [] lvn); simpl; auto; try omega.\n\n    + allrw disjoint_app_r; sp.\n\n    +\n\nQed.\n*)\n\nLemma eqvars_move_around :\n  forall vs1 v vs2,\n    eqvars (v :: vs1 ++ vs2) (vs1 ++ v :: vs2).\nProof.\n  introv; rw eqvars_prop; introv; simpl.\n  allrw in_app_iff; allsimpl; split; sp.\nQed.\n\nLemma foren_vars_mk_swapping :\n  forall vs1 vs2,\n    length vs1 = length vs2\n    -> eqvars (foren_vars (mk_swapping vs1 vs2)) (vs1 ++ vs2).\nProof.\n  induction vs1; destruct vs2; introv len; allsimpl; cpx.\n  apply eqvars_cons_lr; auto.\n  pose proof (eqvars_move_around vs1 n vs2) as eqv.\n  eapply eqvars_trans;[|exact eqv].\n  apply eqvars_cons_lr; auto.\nQed.\n\nLemma subvars_eqvars_r :\n  forall s1 s2 s3 : list NVar,\n    subvars s1 s2 -> eqvars s2 s3 -> subvars s1 s3.\nProof.\n  introv sv eqv.\n  allrw subvars_prop.\n  allrw eqvars_prop.\n  introv i.\n  apply sv in i.\n  apply eqv in i; auto.\nQed.\n\nLemma swapvar_app :\n  forall sw2 sw1 v,\n    swapvar (sw1 ++ sw2) v = swapvar sw2 (swapvar sw1 v).\nProof.\n  induction sw1; introv; simpl; auto.\n  destruct a; simpl.\n  rw IHsw1; auto.\nQed.\n\nLemma mk_swapping_cons :\n  forall a b vs1 vs2,\n    mk_swapping (a :: vs1) (b :: vs2) = (a,b) :: mk_swapping vs1 vs2.\nProof. sp. Qed.\n\nLemma swapvar_cons :\n  forall a b sw v,\n    swapvar ((a,b) :: sw) v = swapvar sw (oneswapvar a b v).\nProof. sp. Qed.\n\nLemma swapvar_disj_chain2 :\n  forall vs1 vs2 vs3 vs4 vs v,\n    length vs1 = length vs\n    -> length vs2 = length vs3\n    -> length vs = length vs4\n    -> !LIn v vs\n    -> !LIn v vs4\n    -> disjoint vs vs1\n    -> disjoint vs vs2\n    -> disjoint vs vs3\n    -> disjoint vs vs4\n    -> disjoint vs4 vs1\n    -> disjoint vs4 vs2\n    -> disjoint vs4 vs3\n    -> no_repeats vs\n    -> no_repeats vs3\n    -> no_repeats vs4\n    -> swapvar (mk_swapping (vs1 ++ vs2 ++ vs) (vs ++ vs3 ++ vs4)) v\n       = swapvar (mk_swapping (vs1 ++ vs2) (vs4 ++ vs3)) v.\nProof.\n  induction vs1; destruct vs; allsimpl;\n  introv len1 len2 len3;\n  introv ni1 ni2;\n  introv disj1 disj2 disj3 disj4 disj5 disj6 disj7;\n  introv norep1 norep2 norep3;\n  allrw app_nil_r; cpx; allsimpl; allrw app_nil_r; auto.\n\n  destruct vs4; allsimpl; cpx.\n\n  unfold oneswapvar; boolvar; tcsp; allrw not_over_or; repnd;\n  allrw disjoint_cons_l; allrw disjoint_cons_r; repnd;\n  allsimpl; allrw not_over_or; repnd;\n  allrw no_repeats_cons; repnd; tcsp.\n\n  - rw app_assoc.\n    rw app_assoc.\n    rw <- mk_swapping_app; try (complete (allrw length_app; sp)).\n    rw swapvar_app.\n    rw (swapvar_not_in n (vs1 ++ vs2) (vs ++ vs3)); try (complete (rw in_app_iff; sp)).\n    rw mk_swapping_cons; simpl.\n    unfold oneswapvar; boolvar.\n    repeat (rw swapvar_not_in); auto; allrw in_app_iff; tcsp.\n\n  - rw app_assoc.\n    rw app_assoc.\n    rw <- mk_swapping_app; try (complete (allrw length_app; sp)).\n    rw swapvar_app.\n    rw mk_swapping_cons; simpl.\n    unfold oneswapvar; boolvar; auto.\n\n    + provefalse.\n      pose proof (swapvar_implies (vs1 ++ vs2) (vs ++ vs3) v) as h.\n      rw e in h; simpl in h.\n      allrw in_app_iff; sp.\n\n    + provefalse.\n      pose proof (swapvar_implies (vs1 ++ vs2) (vs ++ vs3) v) as h.\n      rw e in h; simpl in h.\n      allrw in_app_iff; sp.\n\n    + rw <- swapvar_app.\n      rw mk_swapping_app; try (complete (allrw length_app; sp)).\n      allrw <- app_assoc.\n      apply IHvs1; auto.\nQed.\n\nLemma swapbvars_disj_chain2 :\n  forall vs1 vs2 vs3 vs4 vs l,\n    length vs1 = length vs\n    -> length vs2 = length vs3\n    -> length vs = length vs4\n    -> disjoint vs l\n    -> disjoint vs4 l\n    -> disjoint vs vs1\n    -> disjoint vs vs2\n    -> disjoint vs vs3\n    -> disjoint vs vs4\n    -> disjoint vs4 vs1\n    -> disjoint vs4 vs2\n    -> disjoint vs4 vs3\n    -> no_repeats vs\n    -> no_repeats vs3\n    -> no_repeats vs4\n    -> swapbvars (mk_swapping (vs1 ++ vs2 ++ vs) (vs ++ vs3 ++ vs4)) l\n       = swapbvars (mk_swapping (vs1 ++ vs2) (vs4 ++ vs3)) l.\nProof.\n  induction l;\n  introv len1 len2 len3;\n  introv ni1 ni2;\n  introv disj1 disj2 disj3 disj4 disj5 disj6 disj7;\n  introv norep1 norep2 norep3;\n  allsimpl; auto.\n  allrw disjoint_cons_r; repnd.\n  rw swapvar_disj_chain2; auto.\n  apply eq_cons; auto.\nQed.\n\nLemma so_swap_disj_chain2 {o} :\n  forall (t : @SOTerm o) (vs1 vs2 vs3 vs4 vs : list NVar),\n    length vs1 = length vs\n    -> length vs2 = length vs3\n    -> length vs = length vs4\n    -> disjoint vs (all_fo_vars t)\n    -> disjoint vs4 (all_fo_vars t)\n    -> disjoint vs vs1\n    -> disjoint vs vs2\n    -> disjoint vs vs3\n    -> disjoint vs vs4\n    -> disjoint vs4 vs1\n    -> disjoint vs4 vs2\n    -> disjoint vs4 vs3\n    -> no_repeats vs\n    -> no_repeats vs3\n    -> no_repeats vs4\n    -> so_swap (mk_swapping (vs1 ++ vs2 ++ vs) (vs ++ vs3 ++ vs4)) t\n       = so_swap (mk_swapping (vs1 ++ vs2) (vs4 ++ vs3)) t.\nProof.\n  soterm_ind1s t as [v ts ind|op bs ind] Case;\n  introv len1 len2 len3;\n  introv disj1 disj2 disj3 disj4 disj5 disj6 disj7 disj8 disj9;\n  introv norep1 norep2 norep3;\n  allsimpl.\n\n  - Case \"sovar\".\n    boolvar; subst; allsimpl; auto.\n\n    + allrw disjoint_singleton_r.\n      rw swapvar_disj_chain2; auto.\n\n    + f_equal.\n      allrw disjoint_cons_r; repnd.\n      allrw disjoint_flat_map_r.\n      apply eq_maps; introv i.\n      applydup disj0 in i.\n      applydup disj10 in i.\n      apply ind; auto.\n\n  - Case \"soterm\".\n    f_equal.\n    apply eq_maps; introv i.\n    destruct x; simpl.\n    allrw disjoint_flat_map_r.\n    applydup disj1 in i.\n    applydup disj2 in i.\n    allsimpl.\n    allrw disjoint_app_r; repnd.\n    rw swapbvars_disj_chain2; auto.\n    f_equal.\n    eapply ind; eauto.\nQed.\n\nLemma so_alphaeq_fo_change_bvars_alpha {o} :\n  forall (t : @SOTerm o) vs vs1 vs2,\n    length vs1 = length vs2\n    -> disjoint vs2 vs1\n    -> disjoint vs2 vs\n    -> disjoint vs2 (all_fo_vars t)\n    -> no_repeats vs2\n    -> so_alphaeq\n         (so_swap (mk_swapping vs1 vs2) t)\n         (fo_change_bvars_alpha vs (mk_swapping vs1 vs2) t).\nProof.\n  soterm_ind t as [v ts ind|op bs ind] Case; introv len disj1 disj2 disj3 norep; simpl.\n\n  - Case \"sovar\".\n    boolvar; subst; allsimpl; auto.\n    + rw disjoint_singleton_r in disj3.\n      rw swapvar_is_rename_var; eauto with slow; auto.\n\n    + constructor;[allrw map_length; complete auto|].\n      introv i.\n      rw <- @map_combine in i.\n      rw in_map_iff in i; exrepnd; cpx; allsimpl.\n      rw in_combine_sel_iff in i1; exrepnd.\n      rw <- i3 in i0; ginv.\n      symmetry in i3; apply select_in in i3.\n      eapply ind; auto.\n      allrw disjoint_cons_r; repnd.\n      allrw disjoint_flat_map_r.\n      apply disj0; auto.\n\n  - Case \"soterm\".\n    constructor;[allrw map_length; complete auto|].\n    introv i.\n    rw <- @map_combine in i.\n    rw in_map_iff in i; exrepnd; cpx; allsimpl.\n    rw in_combine_sel_iff in i1; exrepnd.\n    rw <- i3 in i0; ginv.\n    symmetry in i3; apply select_in in i3.\n\n    destruct a0; simpl.\n    gen_fresh.\n\n    rw @app_combine; auto.\n\n    pose proof (fresh_vars\n                  (length l)\n                  (l\n                     ++ vs1\n                     ++ vs2\n                     ++ swapbvars (mk_swapping vs1 vs2) l\n                     ++ f\n                     ++ all_fo_vars (so_swap (mk_swapping vs1 vs2) s)\n                     ++ all_fo_vars (fo_change_bvars_alpha vs (mk_swapping (l ++ vs1) (f ++ vs2)) s)\n                     ++ all_fo_vars (so_swap (mk_swapping (l ++ vs1) (f ++ vs2)) s)\n                     ++ all_fo_vars s)) as h; exrepnd.\n    apply (soaeqbt [] lvn); simpl; auto; try omega.\n\n    + rw length_swapbvars; auto.\n\n    + allrw disjoint_app_r; sp; eauto with slow.\n\n    + pose proof (ind s l i3 vs (l ++ vs1) (f ++ vs2)) as h.\n      repeat (autodimp h hyp); auto.\n\n      * allrw length_app; omega.\n\n      * allrw disjoint_app_r; allrw disjoint_app_l; sp; eauto with slow.\n        {\n          rw disjoint_flat_map_r in disj3.\n          apply disj3 in i3; simpl in i3; rw disjoint_app_r in i3; sp.\n        }\n        {\n          pose proof (foren_vars_mk_swapping vs1 vs2) as eqv;\n          autodimp eqv hyp.\n          eapply subvars_disjoint_r;[|exact Heqf1].\n          apply eqvars_sym in eqv.\n          eapply subvars_eqvars_r;[|exact eqv].\n          apply subvars_app_weak_l; auto.\n        }\n\n      * allrw disjoint_app_r; allrw disjoint_app_l; sp; eauto with slow.\n\n      * allrw disjoint_app_r; allrw disjoint_app_l; sp; eauto with slow.\n        rw disjoint_flat_map_r in disj3.\n        apply disj3 in i3; simpl in i3; rw disjoint_app_r in i3; sp.\n\n      * rw no_repeats_app; sp.\n        allrw disjoint_app_r; sp.\n        pose proof (foren_vars_mk_swapping vs1 vs2) as eqv;\n          autodimp eqv hyp.\n        eapply subvars_disjoint_r;[|exact Heqf1].\n        apply eqvars_sym in eqv.\n        eapply subvars_eqvars_r;[|exact eqv].\n        apply subvars_app_weak_r; auto.\n\n      * pose proof (so_alphaeq_add_so_swap2\n                      f lvn\n                      (so_swap (mk_swapping (l ++ vs1) (f ++ vs2)) s)\n                      (fo_change_bvars_alpha vs (mk_swapping (l ++ vs1) (f ++ vs2)) s)\n                   ) as k.\n        repeat (autodimp k hyp); try omega.\n\n        {\n          allrw disjoint_app_r; sp.\n        }\n\n        eapply so_alphaeq_trans;[|exact k]; clear h k.\n\n        allrw @so_swap_so_swap.\n        repeat (rw mk_swapping_app;[|auto; allrw length_app; complete sp]).\n        rw <- @so_swap_app_so_swap;\n          try (complete (allrw disjoint_app_r; sp; eauto with slow));\n          try (complete (allrw disjoint_flat_map_r;\n                         apply disj3 in i3; simpl in i3;\n                         rw disjoint_app_r in i3; sp; eauto with slow)).\n\n        allrw <- app_assoc.\n        rw @so_swap_disj_chain2; auto; try omega; eauto with slow;\n          try (complete (allrw disjoint_app_r; sp; eauto with slow));\n          try (complete (allrw disjoint_flat_map_r;\n                         apply disj3 in i3; simpl in i3;\n                         rw disjoint_app_r in i3; sp; eauto with slow)).\n\n        {\n          allrw disjoint_app_r; repnd.\n          pose proof (foren_vars_mk_swapping vs1 vs2) as eqv;\n            autodimp eqv hyp.\n          eapply subvars_disjoint_r;[|exact Heqf1].\n          apply eqvars_sym in eqv.\n          eapply subvars_eqvars_r;[|exact eqv].\n          apply subvars_app_weak_l; auto.\n        }\n\n        {\n          allrw disjoint_app_r; repnd.\n          pose proof (foren_vars_mk_swapping vs1 vs2) as eqv;\n            autodimp eqv hyp.\n          eapply subvars_disjoint_r;[|exact Heqf1].\n          apply eqvars_sym in eqv.\n          eapply subvars_eqvars_r;[|exact eqv].\n          apply subvars_app_weak_r; auto.\n        }\nQed.\n\nLemma swapbvars_nil_l :\n  forall l, swapbvars [] l = l.\nProof.\n  induction l; allsimpl; auto.\n  rw IHl; auto.\nQed.\n\nLemma so_swap_nil {o} :\n  forall t : @SOTerm o, so_swap [] t = t.\nProof.\n  soterm_ind t as [v ts ind|op bs ind] Case; introv; simpl.\n\n  - Case \"sovar\".\n    boolvar; subst; auto.\n    f_equal.\n    apply eq_map_l; auto.\n\n  - Case \"soterm\".\n    f_equal.\n    apply eq_map_l; introv i.\n    destruct x; simpl.\n    rw swapbvars_nil_l; f_equal.\n    eapply ind; eauto.\nQed.\n\nLemma so_alphaeq_fo_change_bvars_alpha2 {o} :\n  forall (t : @SOTerm o) vs,\n    so_alphaeq t (fo_change_bvars_alpha vs [] t).\nProof.\n  introv.\n  pose proof (so_alphaeq_fo_change_bvars_alpha t vs [] []) as h.\n  repeat (autodimp h hyp).\n  allsimpl; rw @so_swap_nil in h; auto.\nQed.\n\nLemma fo_bound_vars_fo_change_bvars_alpha {o} :\n  forall (t : @SOTerm o) vs ren,\n    disjoint vs (fo_bound_vars (fo_change_bvars_alpha vs ren t)).\nProof.\n  soterm_ind t as [v ts ind|op bs ind] Case; introv; simpl.\n\n  - Case \"sovar\".\n    boolvar; subst; allsimpl; auto.\n    rw disjoint_flat_map_r; introv i.\n    allrw in_map_iff; exrepnd; subst; auto.\n\n  - Case \"soterm\".\n    rw disjoint_flat_map_r; introv i.\n    allrw in_map_iff; exrepnd; subst.\n    destruct a; simpl.\n    gen_fresh; allrw disjoint_app_r; repnd; dands; eauto with slow.\nQed.\n\nLemma fo_bound_vars_fo_change_bvars_alpha2 {o} :\n  forall (t : @SOTerm o) vs1 vs2 ren,\n    subvars vs1 vs2\n    -> disjoint vs1 (fo_bound_vars (fo_change_bvars_alpha vs2 ren t)).\nProof.\n  introv sv.\n  eapply subvars_disjoint_l; eauto.\n  apply fo_bound_vars_fo_change_bvars_alpha.\nQed.\n\nLemma map_rename_sovar_nil :\n  forall vs, map (rename_sovar []) vs = vs.\nProof.\n  introv; apply eq_map_l; introv i.\n  unfold rename_sovar; simpl; auto.\nQed.\n\nLemma cover_so_vars_fo_change_bvars_alpha {o} :\n  forall (t : @SOTerm o) vs sub,\n    cover_so_vars (fo_change_bvars_alpha vs [] t) sub\n    <=> cover_so_vars t sub.\nProof.\n  introv.\n  unfold cover_so_vars.\n  rw @so_free_vars_fo_change_bvars_alpha; simpl.\n  rw map_rename_sovar_nil; sp.\nQed.\n\nLemma nth_map_sk_change_bvars_alpha {o} :\n  forall (sks : list (@sosub_kind o)) vs n,\n    nth n (map (sk_change_bvars_alpha vs) sks) default_sk\n    = sk_change_bvars_alpha vs (nth n sks default_sk).\nProof.\n  introv.\n  assert (default_sk = sk_change_bvars_alpha vs (@default_sk o)) as e by auto.\n  rw e; rw map_nth; clear e; auto.\nQed.\n\nInductive alphaeq_sosub {o} : @SOSub o -> @SOSub o -> Type :=\n  | aeqsosub_nil : alphaeq_sosub [] []\n  | aeqsosub_cons :\n      forall v sk1 sk2 sub1 sub2,\n        alphaeq_sk sk1 sk2\n        -> alphaeq_sosub sub1 sub2\n        -> alphaeq_sosub ((v,sk1) :: sub1) ((v,sk2) :: sub2).\nHint Constructors alphaeq_sosub.\n\nLemma sosub_as_combine {o} :\n  forall sub : @SOSub o,\n    sub = combine (so_dom sub) (so_range sub).\nProof.\n  induction sub; simpl; auto.\n  destruct a; simpl; rw <- IHsub; auto.\nQed.\n\nLemma sosub_change_bvars_alpha_spec {o} :\n  forall vars (sub : @SOSub o),\n    let sub' := sosub_change_bvars_alpha vars sub in\n    disjoint vars (bound_vars_sosub sub')\n    # alphaeq_sosub sub sub'.\nProof.\n  induction sub; introv; allsimpl; repnd; dands; allsimpl; auto.\n  - rw disjoint_app_r; dands; auto.\n    apply disjoint_bound_vars_sk; auto.\n  - constructor; auto.\n    apply alphaeq_sk_change_bvars_alpha.\nQed.\n\nLtac sosub_change s :=\n  match goal with\n    | [ |- context[sosub_change_bvars_alpha ?vs ?sub] ] =>\n      let h := fresh \"h\" in\n      pose proof (sosub_change_bvars_alpha_spec vs sub) as h;\n        simpl in h;\n        remember (sosub_change_bvars_alpha vs sub) as s;\n        clear_eq s (sosub_change_bvars_alpha vs sub);\n        repnd\n  end.\n\nLemma alphaeq_sosub_implies_eq_sodoms {o} :\n  forall (sub1 sub2 : @SOSub o),\n    alphaeq_sosub sub1 sub2 -> sodom sub1 = sodom sub2.\nProof.\n  induction sub1; destruct sub2; introv aeq; allsimpl; tcsp.\n  - inversion aeq.\n  - inversion aeq.\n  - inversion aeq; subst; clear aeq.\n    destruct sk1, sk2; f_equal; auto.\n    allapply @alphaeq_sk_eq_length; allsimpl; sp.\nQed.\n\nLemma alphaeq_sosub_implies_eq_lengths {o} :\n  forall (sub1 sub2 : @SOSub o),\n    alphaeq_sosub sub1 sub2 -> length sub1 = length sub2.\nProof.\n  induction sub1; destruct sub2; introv aeq; inversion aeq; tcsp; cpx.\nQed.\n\nLemma alphaeq_sosub_implies_alphaeq_sk {o} :\n  forall (sub1 sub2 : @SOSub o),\n    alphaeq_sosub sub1 sub2\n    -> bin_rel_sk alphaeq_sk (so_range sub1) (so_range sub2).\nProof.\n  induction sub1; destruct sub2; introv aeq; allsimpl; tcsp.\n  - unfold bin_rel_sk, binrel_list; simpl; sp.\n  - inversion aeq.\n  - inversion aeq.\n  - inversion aeq; subst; clear aeq.\n    simpl; apply bin_rel_sk_cons; dands; sp.\nQed.\n\nLemma alpha_eq_bterm_preserves_free_vars {o} :\n  forall (bt1 bt2 : @BTerm o),\n    alpha_eq_bterm bt1 bt2 -> free_vars_bterm bt1 = free_vars_bterm bt2.\nProof.\n  introv aeq.\n  pose proof (alphaeq_preserves_free_vars (oterm Exc [bt1]) (oterm Exc [bt2])) as h.\n  simpl in h; allrw app_nil_r; apply h.\n  constructor; simpl; auto.\n  introv i; destruct n; cpx.\nQed.\n\nLemma alphaeq_sk_preserves_free_vars {o} :\n  forall (sk1 sk2 : @sosub_kind o),\n    alphaeq_sk sk1 sk2\n    -> free_vars_sk sk1 = free_vars_sk sk2.\nProof.\n  destruct sk1, sk2; introv aeq.\n  apply alphaeq_sk_iff_alphaeq_bterm in aeq.\n  apply alphaeqbt_eq in aeq.\n  apply alpha_eq_bterm_preserves_free_vars in aeq; allsimpl; auto.\nQed.\n\nLemma alphaeq_sosub_preserves_free_vars {o} :\n  forall (sub1 sub2 : @SOSub o),\n    alphaeq_sosub sub1 sub2\n    -> free_vars_sosub sub1 = free_vars_sosub sub2.\nProof.\n  induction sub1; destruct sub2; introv aeq; inversion aeq; allsimpl; auto;\n  subst; clear aeq.\n  f_equal;[|apply IHsub1;auto].\n  apply alphaeq_sk_preserves_free_vars; auto.\nQed.\n\nLemma alphaeq_sosub_trans {o} :\n  forall (sub1 sub2 sub3 : @SOSub o),\n    alphaeq_sosub sub1 sub2\n    -> alphaeq_sosub sub2 sub3\n    -> alphaeq_sosub sub1 sub3.\nProof.\n  induction sub1; destruct sub2, sub3; introv aeq1 aeq2; tcsp;\n  inversion aeq1; inversion aeq2; subst; cpx; clear aeq1 aeq2.\n  constructor; eauto.\n  eapply alphaeq_sk_trans; eauto.\nQed.\nHint Resolve alphaeq_sosub_trans : slow.\n\nLemma alphaeq_sosub_sym {o} :\n  forall (sub1 sub2 : @SOSub o),\n    alphaeq_sosub sub1 sub2\n    -> alphaeq_sosub sub2 sub1.\nProof.\n  induction sub1; destruct sub2; introv aeq; tcsp;\n  inversion aeq; subst; cpx; clear aeq.\n  constructor; eauto.\n  eapply alphaeq_sk_sym; eauto.\nQed.\nHint Resolve alphaeq_sosub_sym : slow.\n\nLemma alphaeq_sosub_app {o} :\n  forall (sub1 sub2 sub3 sub4 :@SOSub o),\n    alphaeq_sosub sub1 sub2\n    -> alphaeq_sosub sub3 sub4\n    -> alphaeq_sosub (sub1 ++ sub3) (sub2 ++ sub4).\nProof.\n  induction sub1; destruct sub2; introv aeq1 aeq2; tcsp;\n  inversion aeq1; subst; clear aeq1; allsimpl.\n  constructor; auto.\nQed.\n\nLemma alphaeq_sk_iff_alphaeq_bterm2 {o} :\n  forall (sk1 sk2 : @sosub_kind o),\n    alphaeq_sk sk1 sk2 <=> alpha_eq_bterm (sk2bterm sk1) (sk2bterm sk2).\nProof.\n  destruct sk1, sk2.\n  pose proof (alphaeq_sk_iff_alphaeq_bterm l l0 n n0) as h; rw <- h.\n  rw @alphaeqbt_eq; simpl; sp.\nQed.\n\nLemma alphaeq_sk_refl {o} :\n  forall (sk : @sosub_kind o),\n    alphaeq_sk sk sk.\nProof.\n  introv.\n  apply alphaeq_sk_iff_alphaeq_bterm2.\n  apply alphaeqbt_refl.\nQed.\n\nLemma alphaeq_sosub_refl {o} :\n  forall (sub :@SOSub o),\n    alphaeq_sosub sub sub.\nProof.\n  induction sub; auto.\n  destruct a.\n  constructor; auto.\n  apply alphaeq_sk_refl.\nQed.\nHint Resolve alphaeq_sosub_refl : slow.\n\nLemma sosub_find_some_if_alphaeq_sosub {o} :\n  forall (sub1 sub2 : @SOSub o) v sk,\n    alphaeq_sosub sub1 sub2\n    -> sosub_find sub1 v = Some sk\n    -> {sk' : sosub_kind & alphaeq_sk sk sk' # sosub_find sub2 v = Some sk'}.\nProof.\n  induction sub1; destruct sub2; introv aeq sf; allsimpl; tcsp.\n  - inversion aeq.\n  - destruct a, p; destruct s, s0.\n    inversion aeq; subst; clear aeq.\n    boolvar; subst; cpx.\n    + eexists; dands; eauto.\n    + allapply @alphaeq_sk_eq_length; allsimpl.\n      destruct n; allrw; sp.\n    + allapply @alphaeq_sk_eq_length; allsimpl.\n      destruct n; allrw; sp.\nQed.\n\nLemma eqvars_allvars_sk {o} :\n  forall (sk : @sosub_kind o),\n    eqvars (allvars_sk sk)\n           (free_vars_sk sk ++ bound_vars_sk sk).\nProof.\n  destruct sk; simpl.\n  rw eqvars_prop; introv; split; intro i;\n  allrw in_app_iff; allrw in_remove_nvars.\n  - destruct (in_deq _ deq_nvar x l); tcsp.\n    dorn i; tcsp.\n    pose proof (allvars_eq_all_vars n) as h; rw eqvars_prop in h; apply h in i.\n    rw in_app_iff in i; tcsp.\n  - dorn i; repnd.\n    + right.\n      pose proof (allvars_eq_all_vars n) as h; rw eqvars_prop in h; apply h.\n      rw in_app_iff; sp.\n    + dorn i; tcsp.\n      right.\n      pose proof (allvars_eq_all_vars n) as h; rw eqvars_prop in h; apply h.\n      rw in_app_iff; sp.\nQed.\n\nLemma eqvars_allvars_range_sosub {o} :\n  forall (sub : @SOSub o),\n    eqvars\n      (allvars_range_sosub sub)\n      (free_vars_sosub sub ++ bound_vars_sosub sub).\nProof.\n  induction sub; allsimpl; auto.\n  pose proof (eqvars_allvars_sk (snd a)) as h; rw eqvars_prop in h.\n  rw eqvars_prop in IHsub.\n  rw eqvars_prop; introv; split; intro i; allrw in_app_iff.\n  - dorn i.\n    + apply h in i; allrw in_app_iff; sp.\n    + apply IHsub in i; allrw in_app_iff; sp.\n  - dorn i; dorn i.\n    + left; apply h; allrw in_app_iff; sp.\n    + right; apply IHsub; allrw in_app_iff; sp.\n    + left; apply h; allrw in_app_iff; sp.\n    + right; apply IHsub; allrw in_app_iff; sp.\nQed.\n\nLemma fo_change_bvars_alpha_spec {o} :\n  forall vars (t : @SOTerm o),\n    let t' := fo_change_bvars_alpha vars [] t in\n    disjoint vars (fo_bound_vars t')\n    # so_alphaeq t t'.\nProof.\n  introv; simpl.\n  pose proof (so_alphaeq_fo_change_bvars_alpha2 t vars) as h1.\n  pose proof (fo_bound_vars_fo_change_bvars_alpha t vars []) as h2; sp.\nQed.\n\nLtac fo_change s :=\n  match goal with\n    | [ |- context[fo_change_bvars_alpha ?vs [] ?t] ] =>\n      let h := fresh \"h\" in\n      pose proof (fo_change_bvars_alpha_spec vs t) as h;\n        simpl in h;\n        remember (fo_change_bvars_alpha vs [] t) as s;\n        clear_eq s (fo_change_bvars_alpha vs [] t);\n        repnd\n  end.\n\nLemma unfold_sosub {o} :\n  forall (sub : @SOSub o) t,\n    {sub' : SOSub\n     & {t' : SOTerm\n     & alphaeq_sosub sub sub'\n     # so_alphaeq t t'\n     # disjoint (fo_bound_vars t') (free_vars_sosub sub')\n     # disjoint (free_vars_sosub sub') (bound_vars_sosub sub')\n     # disjoint (all_fo_vars t') (bound_vars_sosub sub')\n     # sosub sub t = sosub_aux sub' t'}}.\nProof.\n  introv.\n  unfold sosub; boolvar.\n\n  - allrw disjoint_app_l; repnd.\n    exists sub t; dands; auto.\n    apply alphaeq_sosub_refl.\n\n  - sosub_change sub'.\n\n    applydup @alphaeq_sosub_preserves_free_vars in h as eqfv.\n    pose proof (eqvars_allvars_range_sosub sub) as eqv.\n    allrw disjoint_app_l; repnd.\n\n    exists sub' t; dands; auto.\n\n    * rw <- eqfv; auto.\n\n    * rw <- eqfv.\n      eapply subvars_disjoint_l;[|exact h1].\n      eapply subvars_eqvars_r;[|apply eqvars_sym;exact eqv].\n      apply subvars_app_weak_l; auto.\n\n  - fo_change t'.\n    allrw disjoint_app_l; repnd.\n\n    exists sub t'; dands; eauto with slow.\n\n  - sosub_change sub'.\n    fo_change t'.\n    allrw disjoint_app_l; repnd.\n\n    applydup @alphaeq_sosub_preserves_free_vars in h as eqfv.\n    pose proof (eqvars_allvars_range_sosub sub) as eqv.\n\n    exists sub' t'; dands; eauto with slow.\n\n    * rw <- eqfv; eauto with slow.\n\n    * rw <- eqfv.\n      eapply subvars_disjoint_l;[|exact h3].\n      eapply subvars_eqvars_r;[|apply eqvars_sym;exact eqv].\n      apply subvars_app_weak_l; auto.\nQed.\n\nLemma eq_sodoms_implies_eq_so_doms {o} :\n  forall (sub1 sub2 : @SOSub o),\n    sodom sub1 = sodom sub2 -> so_dom sub1 = so_dom sub2.\nProof.\n  induction sub1; destruct sub2; introv e; allsimpl; tcsp.\n  destruct a; destruct p; destruct s; destruct s0; cpx; allsimpl.\n  f_equal.\n  apply IHsub1; auto.\nQed.\n\nLemma sosub_aux_alpha_congr2 {p} :\n  forall (t1 t2 : @SOTerm p) (sub1 sub2 : @SOSub p),\n    so_alphaeq t1 t2\n    -> disjoint (free_vars_sosub sub1) (fo_bound_vars t1)\n    -> disjoint (free_vars_sosub sub2) (fo_bound_vars t2)\n    -> disjoint (bound_vars_sosub sub1) (free_vars_sosub sub1 ++ fovars t1)\n    -> disjoint (bound_vars_sosub sub2) (free_vars_sosub sub2 ++ fovars t2)\n    -> cover_so_vars t1 sub1\n    -> cover_so_vars t2 sub2\n    -> alphaeq_sosub sub1 sub2\n    -> alphaeq (sosub_aux sub1 t1) (sosub_aux sub2 t2).\nProof.\n  introv aeqt disj1 disj2 disj3 disj4 cov1 cov2 aeqs.\n  pose proof (sosub_aux_alpha_congr\n                t1 t2\n                (so_dom sub1)\n                (so_range sub1) (so_range sub2)) as h; simpl in h.\n\n  allrw @length_so_dom.\n  allrw @length_so_range.\n  allrw <- @sosub_as_combine.\n  applydup @alphaeq_sosub_implies_eq_sodoms in aeqs as ed1.\n  applydup @eq_sodoms_implies_eq_so_doms in ed1 as ed2.\n  rw ed2 in h.\n  allrw <- @sosub_as_combine.\n\n  repeat (autodimp h hyp).\n\n  - apply alphaeq_sosub_implies_eq_lengths; auto.\n\n  - apply alphaeq_sosub_implies_alphaeq_sk; auto.\nQed.\n\nLemma so_alphaeq_sym {o} :\n  forall (t1 t2 : @SOTerm o),\n    so_alphaeq t1 t2 -> so_alphaeq t2 t1.\nProof.\n  introv aeq.\n  apply so_alphaeq_vs_sym; auto.\nQed.\nHint Resolve so_alphaeq_sym : slow.\nHint Resolve so_alphaeq_trans : slow.\nHint Resolve so_alphaeq_refl : slow.\n\nLemma cover_so_vars_if_alphaeq_sosub {o} :\n  forall (t : @SOTerm o) sub1 sub2,\n    cover_so_vars t sub1\n    -> alphaeq_sosub sub1 sub2\n    -> cover_so_vars t sub2.\nProof.\n  introv cov aeq.\n  allunfold @cover_so_vars.\n  apply alphaeq_sosub_implies_eq_sodoms in aeq; rw <- aeq; auto.\nQed.\nHint Resolve cover_so_vars_if_alphaeq_sosub : slow.\n\nFixpoint swap_fo_vars (s : swapping) (vs : list sovar_sig) :=\n  match vs with\n    | [] => []\n    | (v,0) :: vs => (swapvar s v,0) :: swap_fo_vars s vs\n    | (v,n) :: vs => (v,n) :: swap_fo_vars s vs\n  end.\n\nLemma swap_fo_vars_app :\n  forall (l1 l2 : list sovar_sig) s,\n    swap_fo_vars s (l1 ++ l2)\n    = swap_fo_vars s l1 ++ swap_fo_vars s l2.\nProof.\n  induction l1; introv; allsimpl; auto.\n  destruct a; destruct n0; simpl; rw IHl1; auto.\nQed.\n\nLemma swap_fo_vars_flat_map :\n  forall {A} (l : list A) (f : A -> list sovar_sig) s,\n    swap_fo_vars s (flat_map f l) = flat_map (fun a => swap_fo_vars s (f a)) l.\nProof.\n  induction l; introv; allsimpl; auto.\n  rw swap_fo_vars_app; rw IHl; auto.\nQed.\n\nLemma swap_fo_vars_implies_remove_fo_vars :\n  forall vs1 vs2 vs l1 l2,\n    no_repeats vs\n    -> disjoint vs vs1\n    -> disjoint vs vs2\n    -> disjoint vs (sovars2vars l1)\n    -> disjoint vs (sovars2vars l2)\n    -> length vs1 = length vs\n    -> length vs2 = length vs\n    -> swap_fo_vars (mk_swapping vs1 vs) l1 = swap_fo_vars (mk_swapping vs2 vs) l2\n    -> remove_so_vars (vars2sovars vs1) l1 = remove_so_vars (vars2sovars vs2) l2.\nProof.\n  induction l1; destruct l2;\n  introv norep disj1 disj2 disj3 disj4 len1 len2 e;\n  allsimpl; auto;\n  allrw remove_so_vars_nil_r; allrw remove_so_vars_cons_r; auto.\n\n  - destruct s; destruct n0; cpx.\n\n  - destruct a; destruct n0; cpx.\n\n  - allrw disjoint_cons_r; repnd.\n    destruct a, s.\n    destruct n0, n2.\n    inversion e as [e1].\n    allsimpl; boolvar; auto.\n\n    + provefalse.\n      allrw in_map_iff; exrepnd.\n      allunfold var2sovar; cpx.\n      pose proof (swapvar_in vs1 vs a) as h;\n        repeat (autodimp h hyp);\n        try (complete (apply disjoint_sym; auto)).\n      assert (LIn (swapvar (mk_swapping vs2 vs) n1) vs) as k by (allrw <-; auto).\n      pose proof (swapvar_implies2 vs2 vs n1) as x; simpl in x; dorn x;[|dorn x]; tcsp.\n      * rw x in k; sp.\n      * destruct n0; eexists; eauto.\n\n    + provefalse.\n      allrw in_map_iff; exrepnd.\n      allunfold var2sovar; cpx.\n      pose proof (swapvar_in vs2 vs a) as h;\n        repeat (autodimp h hyp);\n        try (complete (apply disjoint_sym; auto)).\n      assert (LIn (swapvar (mk_swapping vs1 vs) n) vs) as k by (allrw; auto).\n      pose proof (swapvar_implies2 vs1 vs n) as x; simpl in x; dorn x;[|dorn x]; tcsp.\n      * rw x in k; sp.\n      * destruct n0; eexists; eauto.\n\n    + rw (IHl1 l2); auto; f_equal; f_equal.\n      allrw in_map_iff; allunfold var2sovar.\n      rw swapvar_not_in in e1; auto;[|introv k; destruct n0; eexists; complete eauto].\n      rw swapvar_not_in in e1; auto.\n      introv k; destruct n2; eexists; complete eauto.\n\n    + boolvar; allsimpl; cpx.\n\n    + boolvar; allsimpl; cpx.\n\n    + boolvar; allsimpl; cpx.\n      * provefalse.\n        allrw in_map_iff; exrepnd.\n        allunfold var2sovar; cpx.\n      * provefalse.\n        allrw in_map_iff; exrepnd.\n        allunfold var2sovar; cpx.\n      * f_equal; auto.\nQed.\n\nLemma so_free_vars_so_swap {o} :\n  forall vs1 vs2 (t : @SOTerm o),\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> so_free_vars (so_swap (mk_swapping vs1 vs2) t)\n       = swap_fo_vars (mk_swapping vs1 vs2) (so_free_vars t).\nProof.\n  soterm_ind t as [v ts ind|op bs ind] Case; introv norep disj; allsimpl.\n\n  - Case \"sovar\".\n    boolvar; subst; allsimpl; auto.\n    rw <- length0 in n.\n    remember (length ts) as l; destruct l; cpx.\n    rw map_length; f_equal; auto.\n    rw flat_map_map; unfold compose.\n    rw @swap_fo_vars_flat_map.\n    apply eq_flat_maps; introv i.\n    apply ind; auto.\n\n  - Case \"soterm\".\n    rw flat_map_map; unfold compose.\n    rw @swap_fo_vars_flat_map.\n    apply eq_flat_maps; introv i; destruct x; simpl.\n    rw (ind s l); auto.\n    remember (so_free_vars s) as vars; clear Heqvars.\n\n    induction vars; simpl; auto.\n    + allrw remove_so_vars_nil_r; simpl; auto.\n    + destruct a; destruct n0; simpl.\n      * allrw remove_so_vars_cons_r; simpl.\n        boolvar; allrw in_map_iff; exrepnd; cpx; allsimpl; auto.\n        { unfold var2sovar in l1; cpx.\n          allrw in_swapbvars; exrepnd.\n          apply swapvars_eq in l1; auto; subst.\n          provefalse.\n          destruct n0; eexists; eauto. }\n        { allunfold var2sovar; cpx.\n          provefalse.\n          destruct n0.\n          eexists; dands; eauto.\n          rw in_swapbvars; eexists; eauto. }\n        { rw IHvars; auto. }\n      * allrw remove_so_vars_cons_r; simpl; boolvar; simpl; auto.\n        { allrw in_map_iff; exrepnd.\n          allunfold var2sovar; cpx. }\n        { allrw in_map_iff; exrepnd.\n          allunfold var2sovar; cpx. }\n        { rw IHvars; auto. }\nQed.\n\nLemma so_alphaeq_preserves_free_vars {o} :\n  forall (t1 t2 : @SOTerm o),\n    so_alphaeq t1 t2\n    -> so_free_vars t1 = so_free_vars t2.\nProof.\n  soterm_ind1s t1 as [v1 ts1 ind1|op1 bs1 ind1] Case; introv aeq.\n\n  - Case \"sovar\".\n    inversion aeq as [? ? ? len imp|]; subst; clear aeq.\n    simpl; rw len; f_equal.\n    apply eq_flat_maps_diff; auto.\n    introv i.\n    applydup imp in i.\n    apply ind1 in i0; auto.\n    apply in_combine in i; sp.\n\n  - Case \"soterm\".\n    inversion aeq as [|? ? ? len imp]; subst; clear aeq; simpl.\n    apply eq_flat_maps_diff; auto.\n    intros b1 b2 i.\n    applydup imp in i.\n    destruct b1 as [l1 t1].\n    destruct b2 as [l2 t2].\n    simpl.\n    inversion i0 as [? ? ? ? ? len1 len2 disj norep a]; subst.\n    applydup in_combine in i; repnd.\n    apply (ind1 t1 _ l1) in a; auto; allrw @sosize_so_swap; auto.\n\n    allsimpl; allrw disjoint_app_r; repnd.\n\n    rw @so_free_vars_so_swap in a; eauto with slow.\n    rw @so_free_vars_so_swap in a; eauto with slow.\n\n    apply swap_fo_vars_implies_remove_fo_vars in a; auto.\n\n    + eapply subvars_disjoint_r;[|exact disj2].\n      apply sovars2vars_so_free_vars_subvars_all_fo_vars.\n\n    + eapply subvars_disjoint_r;[|exact disj].\n      apply sovars2vars_so_free_vars_subvars_all_fo_vars.\nQed.\n\nLemma cover_so_vars_if_so_alphaeq {o} :\n  forall (t1 t2 : @SOTerm o) sub,\n    cover_so_vars t1 sub\n    -> so_alphaeq t1 t2\n    -> cover_so_vars t2 sub.\nProof.\n  introv cov aeq.\n  allunfold @cover_so_vars.\n  apply so_alphaeq_preserves_free_vars in aeq.\n  rw <- aeq; auto.\nQed.\nHint Resolve cover_so_vars_if_so_alphaeq : slow.\n\nLemma alphaeq_sosub_combine {o} :\n  forall vs (sks1 sks2 : list (@sosub_kind o)),\n    length vs = length sks1\n    -> length vs = length sks2\n    -> (alphaeq_sosub (combine vs sks1) (combine vs sks2)\n        <=> bin_rel_sk alphaeq_sk sks1 sks2).\nProof.\n  induction vs; destruct sks1, sks2; introv len1 len2; split; intro k;\n  repnd; dands; allsimpl; tcsp; cpx.\n  - constructor; simpl; sp.\n  - inversion k; subst.\n    apply bin_rel_sk_cons; sp.\n    apply IHvs; sp.\n  - allrw @bin_rel_sk_cons; repnd.\n    constructor; sp.\n    apply IHvs; sp.\nQed.\n\nLemma sosub_alpha_congr {p} :\n  forall (t1 t2 : @SOTerm p) (vs : list NVar) (ts1 ts2 : list sosub_kind),\n    so_alphaeq t1 t2\n    -> length vs = length ts1\n    -> length vs = length ts2\n    -> cover_so_vars t1 (combine vs ts1)\n    -> cover_so_vars t2 (combine vs ts2)\n    -> bin_rel_sk alphaeq_sk ts1 ts2\n    -> alphaeq (sosub (combine vs ts1) t1) (sosub (combine vs ts2) t2).\nProof.\n  introv Hal H1l H2l cov1 cov2 Hbr.\n  pose proof (fovars_subvars_all_fo_vars t1) as sv1.\n  pose proof (fovars_subvars_all_fo_vars t2) as sv2.\n\n  pose proof (unfold_sosub (combine vs ts1) t1) as h1.\n  pose proof (unfold_sosub (combine vs ts2) t2) as k1.\n  exrepnd.\n  rw h1; rw k1.\n\n  apply sosub_aux_alpha_congr2; eauto with slow.\n\n  - rw disjoint_app_r; dands; eauto with slow.\n    pose proof (fovars_subvars_all_fo_vars t'0) as h.\n    eapply subvars_disjoint_r;[exact h|]; eauto with slow.\n\n  - rw disjoint_app_r; dands; eauto with slow.\n    pose proof (fovars_subvars_all_fo_vars t') as h.\n    eapply subvars_disjoint_r;[exact h|]; eauto with slow.\n\n  - eapply alphaeq_sosub_trans;[|exact k0].\n    eapply alphaeq_sosub_trans;[apply alphaeq_sosub_sym;exact h0|].\n    apply alphaeq_sosub_combine; auto.\nQed.\n\nLemma sosub_alpha_congr2 {o} :\n  forall (t1 t2 : @SOTerm o) (sub1 sub2 : @SOSub o),\n    so_alphaeq t1 t2\n    -> alphaeq_sosub sub1 sub2\n    -> cover_so_vars t1 sub1\n    -> cover_so_vars t2 sub2\n    -> alphaeq (sosub sub1 t1) (sosub sub2 t2).\nProof.\n  introv aeqt aeqs cov1 cov2.\n  rw (sosub_as_combine sub1).\n  rw (sosub_as_combine sub2).\n  applydup @alphaeq_sosub_implies_eq_sodoms in aeqs as ed1.\n  applydup @eq_sodoms_implies_eq_so_doms in ed1 as ed2.\n  rw ed2.\n  apply sosub_alpha_congr; auto.\n\n  - rw <- ed2.\n    rw @length_so_dom; rw @length_so_range; auto.\n\n  - rw @length_so_dom; rw @length_so_range; auto.\n\n  - rw <- ed2.\n    rw <- @sosub_as_combine; auto.\n\n  - rw <- @sosub_as_combine; auto.\n\n  - apply alphaeq_sosub_implies_alphaeq_sk; auto.\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/sovar_alpha.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2974624512721018}}
{"text": "(** This files extends the implementation of finite over [positive] to finite\nmaps whose keys range over Coq's data type of binary naturals [N]. *)\nFrom stdpp Require Import pmap mapset.\nFrom stdpp Require Export prelude fin_maps.\nFrom stdpp Require Import options.\n\nLocal Open Scope N_scope.\n\nRecord Nmap (A : Type) : Type := NMap { Nmap_0 : option A; Nmap_pos : Pmap A }.\nGlobal Arguments Nmap_0 {_} _ : assert.\nGlobal Arguments Nmap_pos {_} _ : assert.\nGlobal Arguments NMap {_} _ _ : assert.\n\nGlobal Instance Nmap_eq_dec `{EqDecision A} : EqDecision (Nmap A).\nProof.\n refine (λ t1 t2,\n  match t1, t2 with\n  | NMap x t1, NMap y t2 => cast_if_and (decide (x = y)) (decide (t1 = t2))\n  end); abstract congruence.\nDefined.\nGlobal Instance Nempty {A} : Empty (Nmap A) := NMap None ∅.\nGlobal Opaque Nempty.\nGlobal Instance Nlookup {A} : Lookup N A (Nmap A) := λ i t,\n  match i with\n  | N0 => Nmap_0 t\n  | Npos p => Nmap_pos t !! p\n  end.\nGlobal Instance Npartial_alter {A} : PartialAlter N A (Nmap A) := λ f i t,\n  match i, t with\n  | N0, NMap o t => NMap (f o) t\n  | Npos p, NMap o t => NMap o (partial_alter f p t)\n  end.\nGlobal Instance Nto_list {A} : FinMapToList N A (Nmap A) := λ t,\n  match t with\n  | NMap o t =>\n     from_option (λ x, [(0,x)]) [] o ++ (prod_map Npos id <$> map_to_list t)\n  end.\nGlobal Instance Nomap: OMap Nmap := λ A B f t,\n  match t with NMap o t => NMap (o ≫= f) (omap f t) end.\nGlobal Instance Nmerge: Merge Nmap := λ A B C f t1 t2,\n  match t1, t2 with\n  | NMap o1 t1, NMap o2 t2 => NMap (diag_None f o1 o2) (merge f t1 t2)\n  end.\nGlobal Instance Nfmap: FMap Nmap := λ A B f t,\n  match t with NMap o t => NMap (f <$> o) (f <$> t) end.\n\nGlobal Instance: FinMap N Nmap.\nProof.\n  split.\n  - intros ? [??] [??] H. f_equal; [apply (H 0)|].\n    apply map_eq. intros i. apply (H (Npos i)).\n  - by intros ? [|?].\n  - intros ? f [? t] [|i]; simpl; [done |]. apply lookup_partial_alter.\n  - intros ? f [? t] [|i] [|j]; simpl; try intuition congruence.\n    intros. apply lookup_partial_alter_ne. congruence.\n  - intros ??? [??] []; simpl; [done|]. apply lookup_fmap.\n  - intros ? [[x|] t]; unfold map_to_list; simpl.\n    + constructor.\n      * rewrite elem_of_list_fmap. by intros [[??] [??]].\n      * by apply (NoDup_fmap _), NoDup_map_to_list.\n    + apply (NoDup_fmap _), NoDup_map_to_list.\n  - intros ? t i x. unfold map_to_list. split.\n    + destruct t as [[y|] t]; simpl.\n      * rewrite elem_of_cons, elem_of_list_fmap.\n        intros [? | [[??] [??]]]; simplify_eq/=; [done |].\n        by apply elem_of_map_to_list.\n      * rewrite elem_of_list_fmap; intros [[??] [??]]; simplify_eq/=.\n        by apply elem_of_map_to_list.\n    + destruct t as [[y|] t]; simpl.\n      * rewrite elem_of_cons, elem_of_list_fmap.\n        destruct i as [|i]; simpl; [intuition congruence |].\n        intros. right. exists (i, x). by rewrite elem_of_map_to_list.\n      * rewrite elem_of_list_fmap.\n        destruct i as [|i]; simpl; [done |].\n        intros. exists (i, x). by rewrite elem_of_map_to_list.\n  - intros ?? f [??] [|?]; simpl; [done|]; apply (lookup_omap f).\n  - intros ??? f [??] [??] [|?]; simpl; [done|]; apply (lookup_merge f).\nQed.\n\n(** * Finite sets *)\n(** We construct sets of [N]s satisfying extensional equality. *)\nNotation Nset := (mapset Nmap).\nGlobal Instance Nmap_dom {A} : Dom (Nmap A) Nset := mapset_dom.\nGlobal Instance: FinMapDom N Nmap Nset := mapset_dom_spec.\n", "meta": {"author": "rems-project", "repo": "stdpp_MC", "sha": "26b4b992e501c924db1de99994ac9cec9796a974", "save_path": "github-repos/coq/rems-project-stdpp_MC", "path": "github-repos/coq/rems-project-stdpp_MC/stdpp_MC-26b4b992e501c924db1de99994ac9cec9796a974/stdpp/nmap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.29746244384854564}}
{"text": "Require Import List.\nRequire Export Util Get Drop Var Val Isa.Ops IL.Exp\n        Envs Map CSet AutoIndTac MoreList OptionMap.\nRequire Export IL.Events SizeInduction SmallStepRelations StateType.\nRequire Import SetOperations.\n\nSet Implicit Arguments.\n\n(** * Intermediate Language IL *)\n\n(** ** Syntax *)\n\n(** [args] is the type of the list of variables passed at a goto ... *)\nNotation \"'args'\" := (list op) (at level 0).\n(** ... while [params] is the type of the list of formal parameters *)\nNotation \"'params'\" := (list var) (at level 0).\n\nInductive stmt : Type :=\n| stmtLet    (x : var) (e: exp) (s : stmt) : stmt\n| stmtIf     (e : op) (s : stmt) (t : stmt) : stmt\n| stmtApp    (l : lab) (Y:args) : stmt\n| stmtReturn (e : op) : stmt\n(* block f Z : rt = s in b *)\n| stmtFun    (F:list (params * stmt)) (t : stmt) : stmt.\n\nInstance Stmt_size : Size stmt. gen_Size. Defined.\n\nLemma stmt_ind'\n  : forall P : stmt -> Prop,\n       (forall (x : var) (e : exp) (s : stmt), P s -> P (stmtLet x e s)) ->\n       (forall (e : op) (s : stmt), P s -> forall t : stmt, P t -> P (stmtIf e s t)) ->\n       (forall (l : lab) (Y : args), P (stmtApp l Y)) ->\n       (forall e : op, P (stmtReturn e)) ->\n       (forall (F : 〔params * stmt〕) (t : stmt),\n           P t -> (forall n Zs, get F n Zs -> P (snd Zs)) -> P (stmtFun F t)) -> forall s : stmt, P s.\nProof.\n  intros. sind s; destruct s; eauto.\nQed.\n\n(** *** Free, Defined and Occuring Variables *)\n\nFixpoint freeVars (s:stmt) : set var :=\n  match s with\n    | stmtLet x e s0 => (freeVars s0 \\ singleton x) ∪ Exp.freeVars e\n    | stmtIf e s1 s2 => freeVars s1 ∪ freeVars s2 ∪ Ops.freeVars e\n    | stmtApp l Y => list_union (List.map Ops.freeVars Y)\n    | stmtReturn e => Ops.freeVars e\n    | stmtFun s t =>\n      list_union (List.map (fun f => (freeVars (snd f) \\ of_list (fst f))) s) ∪ freeVars t\n  end.\n\nDefinition defVarsZs (definedVars:stmt -> set var) (Zs:params*stmt) :=\n  of_list (fst Zs) ∪ definedVars (snd Zs).\n\nDefinition definedVarsF (definedVars:stmt -> set var)\n           (F:list (params*stmt)) :=\n  list_union (List.map (defVarsZs definedVars) F).\n\nFixpoint definedVars (s:stmt) : set var :=\n  match s with\n    | stmtLet x e s0 => {x; definedVars s0}\n    | stmtIf e s1 s2 => definedVars s1 ∪ definedVars s2\n    | stmtApp l Y => ∅\n    | stmtReturn e => ∅\n    | stmtFun F t => (definedVarsF definedVars F) ∪ definedVars t\n  end.\n\nFixpoint occurVars (s:stmt) : set var :=\n  match s with\n    | stmtLet x e s0 => {x; occurVars s0} ∪ Exp.freeVars e\n    | stmtIf e s1 s2 => occurVars s1 ∪ occurVars s2 ∪ Ops.freeVars e\n    | stmtApp l Y => list_union (List.map Ops.freeVars Y)\n    | stmtReturn e => Ops.freeVars e\n    | stmtFun s t =>\n      list_union (List.map (fun f => (occurVars (snd f) ∪ of_list (fst f))) s) ∪ occurVars t\n  end.\n\nLemma freeVars_occurVars s\n: freeVars s ⊆ occurVars s.\nProof.\n  sind s; destruct s; simpl in * |- *; repeat rewrite IH; eauto.\n  - cset_tac.\n  - rewrite list_union_f_incl. reflexivity.\n    intros. destruct y; simpl.\n    rewrite IH; cset_tac; intuition; eauto.\nQed.\n\nLemma occurVars_freeVars_definedVars s\n: occurVars s [=] freeVars s ∪ definedVars s.\nProof.\n  sind s; destruct s; simpl in * |- *; eauto with cset.\n  - rewrite IH; eauto.\n    clear_all; cset_tac.\n  - repeat rewrite IH; eauto.\n    clear_all; cset_tac.\n  - cset_tac.\n  - cset_tac.\n  - rewrite IH; eauto. unfold definedVarsF, defVarsZs.\n    repeat setoid_rewrite union_assoc at 1.\n    setoid_rewrite union_comm at 5.\n    repeat setoid_rewrite <- union_assoc.\n    erewrite list_union_f_union.\n    rewrite list_union_f_eq. cset_tac.\n    simpl. intros. rewrite IH; eauto.\n    clear; cset_tac.\nQed.\n\nLemma definedVars_occurVars s\n: definedVars s ⊆ occurVars s.\nProof.\n  sind s; destruct s; simpl in * |- *; eauto with cset.\n  - unfold definedVarsF, defVarsZs.\n    rewrite IH, list_union_f_incl; eauto.\n    + reflexivity.\n    + intros. destruct y; simpl. rewrite IH; cset_tac.\nQed.\n\nFixpoint externals (s:stmt) : set var :=\n  match s with\n  | stmtLet x e s0 => Exp.externals e ∪ externals s0\n  | stmtIf e s1 s2 => externals s1 ∪ externals s2\n  | stmtApp l Y => {}\n  | stmtReturn e => {}\n  | stmtFun F t => list_union ((fun Zs => externals (snd Zs)) ⊝ F) ∪ externals t\n  end.\n\nDefinition defVars' ( Zs:params*stmt) := of_list (fst Zs) ∪ definedVars (snd Zs).\n\nLemma list_union_definedVars F\n  : definedVarsF definedVars F\n                 [=] list_union (of_list ⊝ fst ⊝ F) ∪ list_union (definedVars ⊝ snd ⊝ F).\nProof.\n  unfold definedVarsF, defVarsZs.\n  general induction F; simpl; eauto with cset.\n  norm_lunion. rewrite IHF; clear IHF. cset_tac.\nQed.\n\nLemma list_union_definedVars' F\n  : list_union (defVars' ⊝ F)\n               [=] list_union (of_list ⊝ fst ⊝ F) ∪ list_union (definedVars ⊝ snd ⊝ F).\nProof.\n  general induction F; simpl; eauto with cset.\n  norm_lunion. rewrite IHF; clear IHF. unfold defVars' at 1.\n  cset_tac.\nQed.\n\nLemma list_union_definedVarsF_decomp F\n  : list_union (defVarsZs definedVars ⊝ F)\n               [=] list_union (of_list ⊝ fst ⊝ F) ∪ list_union (definedVars ⊝ snd ⊝ F).\nProof.\n  general induction F; simpl.\n  - cset_tac.\n  - norm_lunion. rewrite IHF.\n    unfold defVarsZs at 1. clear.\n    cset_tac.\nQed.\n\n\n(** ** Semantics *)\n\n(** *** Functional Semantics *)\nModule F.\n\n  Inductive block : Type :=\n    blockI {\n      block_E : onv val;\n      block_Z : params;\n      block_s : stmt;\n      block_n : nat\n    }.\n\n  Definition labenv := list block.\n  Definition state : Type := (labenv * onv val * stmt)%type.\n\n  Definition mkBlock E n f :=\n    blockI E (fst f) (snd f) n.\n\n  Inductive step : state -> event -> state -> Prop :=\n  | StepLet L E x e b v\n    (def:op_eval E e = Some v)\n    : step (L, E, stmtLet x (Operation e) b) EvtTau (L, E[x<-Some v], b)\n\n  | StepExtern L E x f Y s vl v\n    (def:omap (op_eval E) Y = Some vl)\n    : step  (L, E, stmtLet x (Call f Y) s)\n            (EvtExtern (ExternI f vl v))\n            (L, E[x <- Some v], s)\n\n  | StepIfT L E\n    e (b1 b2 : stmt) v\n    (def:op_eval E e = Some v)\n    (condTrue: val2bool v = true)\n    : step (L, E, stmtIf e b1 b2) EvtTau (L, E, b1)\n\n  | StepIfF L E\n    e (b1 b2:stmt) v\n    (def:op_eval E e = Some v)\n    (condFalse: val2bool v = false)\n    : step (L, E, stmtIf e b1 b2) EvtTau (L, E, b2)\n\n  | StepGoto L E (l:lab) Y blk vl\n    (Ldef:get L l blk)\n    (len:length (block_Z blk) = length Y)\n    (def:omap (op_eval E) Y = Some vl) E'\n    (updOk:(block_E blk) [block_Z blk <-- List.map Some vl] = E')\n    : step  (L, E, stmtApp l Y)\n            EvtTau\n            (drop (l - block_n blk) L, E', block_s blk)\n\n  | StepFun L E\n    F (t:stmt)\n    : step (L, E, stmtFun F t) EvtTau ((mapi (mkBlock E) F ++ L)%list, E, t).\n\n  Lemma step_internally_deterministic\n  : internally_deterministic step.\n  Proof.\n    hnf; intros.\n    inv H; inv H0; split; eauto; try get_functional; try congruence.\n  Qed.\n\n  Lemma step_externally_determined\n  : externally_determined step.\n  Proof.\n    hnf; intros.\n    inv H; inv H0; eauto; try get_functional; try congruence.\n  Qed.\n\n  Lemma step_dec\n  : reddec2 step.\n  Proof.\n    hnf; intros. destruct x as [[L V] []].\n    - destruct e.\n      + case_eq (op_eval V e); intros. left. do 2 eexists. eauto 20 using step.\n        right. stuck.\n      + case_eq (omap (op_eval V) Y); intros; try now (right; stuck).\n        left; eexists (EvtExtern (ExternI f l (default_val))). eexists; eauto using step.\n    - case_eq (op_eval V e); intros.\n      left. case_eq (val2bool v); intros; do 2 eexists; eauto using step.\n      right. stuck.\n    - destruct (get_dec L l) as [[blk A]|?]; [ | right; stuck2 ].\n      decide (length (block_Z blk) = length Y); [ | right; stuck2 ].\n      case_eq (omap (op_eval V) Y); intros; [ | right; stuck2 ].\n      left. do 2 eexists. econstructor; eauto.\n    - right; stuck.\n    - left. eexists. eauto using step.\n  Qed.\n\n  Lemma StepGoto_mapi L blk Y E E'' vl (f:lab) F k\n        (Ldef:get L (f - ❬F❭) blk)\n        (len:length (F.block_Z blk) = length Y)\n        (def:omap (op_eval E) Y = Some vl) E'\n        (updOk:F.block_E blk [F.block_Z blk <-- List.map Some vl] = E')\n        (ST:f - block_n blk >= ❬mapi (F.mkBlock E'') F❭) (GE: f >= ❬F❭) (EQ:k = f - ❬F❭ - block_n blk)\n    : F.step (mapi (F.mkBlock E'') F ++ L, E, stmtApp f Y) EvtTau\n             (drop k L,\n              E', F.block_s blk).\n  Proof.\n    subst.\n    rewrite <- (mapi_length (F.mkBlock E'')).\n    orewrite (f - ❬mapi (F.mkBlock E'') F❭ - block_n blk\n              =  (f - block_n blk) - ❬mapi (F.mkBlock E'') F❭).\n    rewrite <- (drop_app_gen _ (mapi (F.mkBlock E'') F)); eauto.\n    eapply F.StepGoto; eauto.\n    rewrite get_app_ge. rewrite mapi_length. eauto. omega.\n  Qed.\n\nEnd F.\n\n(** *** Imperative Semantics *)\n\nModule I.\n  Inductive block : Type :=\n    blockI {\n      block_Z : params;\n      block_s : stmt;\n      block_n : nat\n    }.\n\n  Definition labenv := list block.\n  Definition state : Type := (labenv * onv val * stmt)%type.\n  Definition mkBlock n f := blockI (fst f) (snd f) n.\n\n  Inductive step : state -> event -> state -> Prop :=\n  | StepLet L E x e b v\n    (def:op_eval E e = Some v)\n    : step (L, E, stmtLet x (Operation e) b) EvtTau (L, E[x<-Some v], b)\n\n  | StepExtern L E x f Y s vl v\n               (def:omap (op_eval E) Y = Some vl)\n    : step  (L, E, stmtLet x (Call f Y) s)\n            (EvtExtern (ExternI f vl v))\n            (L, E[x <- Some v], s)\n\n  | StepIfT L E\n    e (b1 b2 : stmt) v\n    (def:op_eval E e = Some v)\n    (condTrue: val2bool v = true)\n    : step (L, E, stmtIf e b1 b2) EvtTau (L, E, b1)\n\n  | StepIfF L E\n    e (b1 b2:stmt) v\n    (def:op_eval E e = Some v)\n    (condFalse: val2bool v = false)\n    : step (L, E, stmtIf e b1 b2) EvtTau (L, E, b2)\n\n  | StepGoto L E (l:lab) Y blk vl\n    (Ldef:get L l blk)\n    (len:length (block_Z blk) = length Y)\n    (def:omap (op_eval E) Y = Some vl) E'\n    (updOk:E[block_Z blk  <-- List.map Some vl] = E')\n    : step  (L, E, stmtApp l Y)\n            EvtTau\n            (drop (l - block_n blk) L, E', block_s blk)\n\n\n  | StepFun L E\n    s (t:stmt)\n    : step (L, E, stmtFun s t) EvtTau ((mapi mkBlock s ++ L)%list, E, t).\n\n  Lemma step_internally_deterministic\n  : internally_deterministic step.\n  Proof.\n    hnf; intros.\n    inv H; inv H0; split; eauto; try get_functional; try congruence.\n  Qed.\n\n  Lemma step_externally_determined\n  : externally_determined step.\n  Proof.\n    hnf; intros.\n    inv H; inv H0; eauto; try get_functional; try congruence.\n  Qed.\n\n  Lemma step_dec\n  : reddec2 step.\n  Proof.\n    hnf; intros. destruct x as [[L V] []].\n    - destruct e.\n      + case_eq (op_eval V e); intros. left. do 2 eexists. eauto 20 using step.\n        right. stuck.\n      + case_eq (omap (op_eval V) Y); intros; try now (right; stuck).\n        left; eexists (EvtExtern (ExternI f l default_val)). eexists; eauto using step.\n    - case_eq (op_eval V e); intros.\n      left. case_eq (val2bool v); intros; do 2 eexists; eauto using step.\n      right. stuck.\n    - destruct (get_dec L l) as [[blk A]|?]; [| right; stuck2].\n      decide (length (block_Z blk) = length Y); [| right; stuck2].\n      case_eq (omap (op_eval V) Y); intros; [| right; stuck2].\n      left. do 2 eexists. econstructor; eauto.\n    - right. stuck2.\n    - left. eexists. eauto using step.\n  Qed.\n\n  Lemma StepGoto_mapi L blk Y E vl (f:lab) F k\n        (Ldef:get L (f - ❬F❭) blk)\n        (len:length (I.block_Z blk) = length Y)\n        (def:omap (op_eval E) Y = Some vl) E'\n        (updOk:E [I.block_Z blk <-- List.map Some vl] = E')\n        (ST:f - block_n blk >= ❬mapi I.mkBlock F❭)\n        (GE:f >= ❬F❭) (EQ:k = f - ❬F❭ - block_n blk)\n    : I.step (mapi I.mkBlock F ++ L, E, stmtApp f Y) EvtTau\n             (drop k L,\n              E', I.block_s blk).\n  Proof.\n    subst.\n    rewrite <- (mapi_length I.mkBlock).\n    orewrite (f - ❬mapi I.mkBlock F❭ - block_n blk\n              =  (f - block_n blk) - ❬mapi I.mkBlock F❭).\n    rewrite <- (drop_app_gen _ (mapi I.mkBlock F)); eauto.\n    eapply I.StepGoto; eauto.\n    rewrite get_app_ge. rewrite mapi_length. eauto. omega.\n  Qed.\n\nEnd I.\n\n\nDefinition state_result X (s:X*onv val*stmt) : option val :=\n  match s with\n    | (_, E, stmtReturn e) => op_eval E e\n    | _ => None\n  end.\n\nInstance statetype_F : StateType F.state := {\n  step := F.step;\n  result := (@state_result F.labenv);\n  step_dec := F.step_dec;\n  step_internally_deterministic := F.step_internally_deterministic;\n  step_externally_determined := F.step_externally_determined\n}.\n\nInstance statetype_I : StateType I.state := {\n  step := I.step;\n  result := (@state_result I.labenv);\n  step_dec := I.step_dec;\n  step_internally_deterministic := I.step_internally_deterministic;\n  step_externally_determined := I.step_externally_determined\n}.\n\nLtac single_step_IL :=\n  match goal with\n  | [ H : agree_on _ ?E ?E', I : val2bool (?E ?x) = true |- step (_, ?E', stmtIf ?x _ _) _ ] =>\n    econstructor; eauto; rewrite <- H; eauto; cset_tac; intuition\n  | [ H : agree_on _ ?E ?E', I : val2bool (?E ?x) = false |- step (_, ?E', stmtIf ?x _ _) _ ] =>\n    econstructor 3; eauto; rewrite <- H; eauto; cset_tac; intuition\n  | [ H : val2bool _ = false |- @StateType.step _ statetype_I _ _ _ ] =>\n    econstructor 4; try eassumption; try reflexivity\n  | [ H : val2bool _ = false |- @StateType.step _ statetype_F _ _ _ ] =>\n    econstructor 4; try eassumption; try reflexivity\n  | [ H : val2bool _ = true |- @StateType.step _ statetype_I _ _ _ ] =>\n    econstructor 3; try eassumption; try reflexivity\n  | [ H : val2bool _ = true |- @StateType.step _ statetype_F _ _ _ ] =>\n    econstructor 3; try eassumption; try reflexivity\n  | [ H : step (?L, _ , stmtApp ?l _) _, H': get ?L (labN ?l) _ |- _] =>\n    econstructor; try eapply H'; eauto\n(*  | [ H': get ?L ?n _ |- @StateType.step _ _ (?L, _ , stmtApp (LabI ?n) _) _ _] =>\n    econstructor; [ eapply H'\n                  | simpl; eauto with len\n                  | try eassumption\n                  | reflexivity]*)\n  | [ H': get ?F (labN ?l) _ |- @StateType.step _ _ (mapi _ ?F ++ _, _, stmtApp ?l _) _ _] =>\n    econstructor; [ try solve [simpl; eauto using get_app, get_mapi]\n                  | simpl; eauto with len\n                  | try eassumption; eauto; try reflexivity\n                  | reflexivity]\n  | [ |- @StateType.step _ _ (?L, _ , stmtApp _ _) _ _] =>\n    econstructor; [ try eassumption; try solve [simpl; eauto using get]\n                  | simpl; eauto with len\n                  | try eassumption; eauto; try reflexivity\n                  | reflexivity]\n  | [ |- @StateType.step _ _ (_, ?E, stmtLet _ (Operation ?e) _) _ _] =>\n    econstructor; eauto\n  | [ |- @StateType.step _ _ (_, ?E, stmtFun _ _) _ _] =>\n    econstructor; eauto\n  end.\n\nSmpl Add single_step_IL : single_step.\n\nLemma ZL_mapi F L\n  : I.block_Z ⊝ (mapi I.mkBlock F ++ L) = fst ⊝ F ++ I.block_Z ⊝ L.\nProof.\n  rewrite List.map_app. rewrite map_mapi. unfold mapi.\n  erewrite <- mapi_map_ext; [ reflexivity | simpl; reflexivity].\nQed.\n\nHint Extern 1 =>\nmatch goal with\n| [ |- context [ I.block_Z ⊝ (mapi I.mkBlock ?F ++ ?L) ] ] =>\n  rewrite (ZL_mapi F L)\n| [ |- context [ pair ⊜ (?A ++ ?B) (?C ++ ?D) ] ] =>\n  rewrite (zip_app pair A C B D);\n    [| eauto with len]\nend.\n\nInductive noFun : stmt->Prop :=\n| NoFunLet x e s :\n   noFun s\n   -> noFun (stmtLet x e s)\n| NoFunIf e s t :\n   noFun s\n   -> noFun t\n   -> noFun (stmtIf e s t)\n| NoFunCall l Y :\n   noFun (stmtApp l Y)\n| NoFunExp e :\n   noFun (stmtReturn e).\n\nInductive noCall : stmt->Prop :=\n| NoCallLet x e s :\n   noCall s\n   -> noCall (stmtLet x (Operation e) s)\n| NoCallIf e s t :\n   noCall s\n   -> noCall t\n   -> noCall (stmtIf e s t)\n| NoCallApp l Y :\n   noCall (stmtApp l Y)\n| NoCallExp e :\n    noCall (stmtReturn e)\n| NoAppCall F t\n  : (forall n Zs, get F n Zs -> noCall (snd Zs))\n    -> noCall t\n    -> noCall (stmtFun F t).\n\nInductive notApp : stmt -> Prop :=\n| NotAppLet x e s : notApp (stmtLet x e s)\n| NotAppIf e s t : notApp (stmtIf e s t)\n| NotAppReturn e : notApp (stmtReturn e)\n| NotAppFun F t : notApp (stmtFun F t).\n", "meta": {"author": "sigurdschneider", "repo": "lvc", "sha": "be41194f16495d283fe7bbc982c3393ac554dd5b", "save_path": "github-repos/coq/sigurdschneider-lvc", "path": "github-repos/coq/sigurdschneider-lvc/lvc-be41194f16495d283fe7bbc982c3393ac554dd5b/theories/IL/IL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.29736039459680247}}
{"text": "Require Import Coq.Logic.Classical.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Sets.Ensembles.\nRequire Import CertiGraph.lib.Coqlib.\nRequire Import CertiGraph.lib.Ensembles_ext.\nRequire Import CertiGraph.lib.EquivDec_ext.\nRequire Import CertiGraph.lib.Relation_ext.\nRequire Import CertiGraph.lib.List_ext.\nRequire Import CertiGraph.graph.graph_model.\nRequire Import CertiGraph.graph.weak_mark_lemmas.\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_computable.\nRequire Export CertiGraph.graph.FiniteGraph.\nRequire Export CertiGraph.graph.MathGraph.\nRequire Export CertiGraph.graph.LstGraph.\nRequire Export CertiGraph.graph.UnionFind.\nRequire Import CertiGraph.msl_application.Graph.\nRequire Import CertiGraph.msl_application.UnionFindGraph.\n\nLocal Open Scope logic.\n\nClass pPointwiseGraph_GList: Type :=\n  {\n    addr: Type;\n    null: addr;\n    SGBA: PointwiseGraphBasicAssum addr (addr * unit)\n  }.\n\n#[export] Existing Instance SGBA.\n\nDefinition is_null_SGBA {pSGG: pPointwiseGraph_GList} : DecidablePred addr := (existT (fun P => forall a, {P a} + {~ P a}) (fun x => x = null) (fun x => SGBA_VE x null)).\n\nClass sPointwiseGraph_GList {pSGG_Bi: pPointwiseGraph_GList} (DV DE: Type): Type :=\n  {\n    pred: Type;\n    SGP: PointwiseGraphPred addr (addr * unit) (DV * addr) unit pred;\n    SGA: PointwiseGraphAssum SGP;\n    SGAvs: PointwiseGraphAssum_vs SGP;\n    SGAvn: PointwiseGraphAssum_vn SGP null\n  }.\n\n#[export] Existing Instances SGP SGA SGAvs.\n\nSection GRAPH_GList.\n\n  Context {pSGG: pPointwiseGraph_GList}.\n  Context {DV DE DG: Type}.\n\n  #[global] Instance SGC_GList: PointwiseGraphConstructor addr (addr * unit) DV DE DG (DV * addr) unit.\n  Proof.\n    refine (Build_PointwiseGraphConstructor _ _ _ _ _ _ _ SGBA _ _).\n    + exact (@vgamma addr (addr * unit) SGBA_VE SGBA_EE is_null_SGBA (fun x => (x, tt)) DV DE DG).\n    + exact (fun _ _ => tt).\n  Defined.\n\n  #[global] Instance L_SGC_GList: Local_PointwiseGraphConstructor addr (addr * unit) DV DE DG (DV * addr) unit.\n  Proof.\n    refine (Build_Local_PointwiseGraphConstructor\n              _ _ _ _ _ _ _ SGBA SGC_GList\n              (fun G v => evalid (pg_lg G) (v, tt) /\\ src (pg_lg G) (v, tt) = v) _\n              (fun _ _ => True) _).\n    - intros. simpl. unfold vgamma.  simpl. destruct H as [? ?], H0 as [? ?]. f_equal; auto. pose proof (H3 _ H H5 H0 H6). rewrite <- !H7. clear H7.\n      destruct (SGBA_VE (dst (pg_lg G1) (x, tt)) null); auto.\n    - intros; simpl. auto.\n  Defined.\n\n  Local Coercion UFGraph_LGraph: UFGraph >-> LGraph.\n  Local Identity Coercion LGraph_LabeledGraph: LGraph >-> LabeledGraph.\n  Local Coercion pg_lg: LabeledGraph >-> PreGraph.\n\n  Notation UFGraph := (@UFGraph addr (addr * unit) _ _ is_null_SGBA (fun x => (x, tt)) DV DE DG).\n  Notation LGraph := (@LGraph addr (addr * unit) _ _ DV DE DG).\n\n  #[global] Instance RGF (G: UFGraph): ReachableFiniteGraph G.\n  Proof.\n    apply Build_ReachableFiniteGraph.\n    intros.\n    apply finite_reachable_computable with (is_null := is_null_SGBA) in H.\n    - destruct H as [l [? ?]]. exists l; auto.\n    - apply maGraph.\n    - apply (LocalFiniteGraph_FiniteGraph G), finGraph.\n    - apply (FiniteGraph_EnumCovered G), finGraph.\n  Defined.\n\n  Definition make_set_pregraph (v: addr) (g: PreGraph addr (addr * unit)) := pregraph_add_edge (pregraph_add_vertex g v) (v, tt) v null.\n\n  Lemma is_partial_make_set_pregraph: forall x (g: UFGraph), ~ vvalid g x -> is_partial_graph g (make_set_pregraph x g).\n  Proof.\n    intros. hnf. simpl. unfold addValidFunc, updateEdgeFunc. split; [|split; [|split]]; intros; [left; auto..| |].\n    - destruct (equiv_dec (x, tt) e); auto. hnf in e0. subst e. pose proof (@only_one_edge _ _ _ _ g _ (liGraph g) (src g (x, tt)) (x, tt) H1). simpl in H2.\n      assert (src g (x, tt) = src g (x, tt) /\\ evalid g (x, tt)) by (split; auto). rewrite H2 in H3. inversion H3. exfalso. rewrite H5 in H. intuition.\n    - destruct (equiv_dec (x, tt) e); auto. hnf in e0. subst e. destruct (@valid_graph _ _ _ _ g _ (maGraph g) _ H0) as [? _].\n      pose proof (@only_one_edge _ _ _ _ g _ (liGraph g) (src g (x, tt)) (x, tt) H2). assert (src g (x, tt) = src g (x, tt) /\\ evalid g (x, tt)) by (split; auto).\n      rewrite H3 in H4. inversion H4. exfalso. rewrite H6 in H. intuition.\n  Qed.\n\n  Definition make_set_LabeledGraph (v: addr) (g: LabeledGraph addr (addr * unit) DV DE DG) (default_dv: DV) (default_de: DE) (default_dg: DG) : LGraph :=\n    Build_LabeledGraph _ _ _ (make_set_pregraph v g) (fun x => if SGBA_VE x v then default_dv else vlabel g x) (fun e => default_de) default_dg.\n\n  Definition make_set_MathGraph (v: addr) (g: PreGraph addr (addr * unit)) (H: v <> null) (Hm: MathGraph g is_null_SGBA): MathGraph (make_set_pregraph v g) is_null_SGBA.\n  Proof.\n    apply (Build_MathGraph _ is_null_SGBA).\n    - intros. simpl. unfold updateEdgeFunc, addValidFunc. destruct (equiv_dec (v, tt) e). 1: intuition. simpl in H0. unfold addValidFunc in H0. destruct H0.\n      + destruct Hm. apply valid_graph in H0. destruct H0. split. 1: left; auto. hnf in H1. simpl in H1. destruct H1; [left | right; left]; auto.\n      + compute in c. exfalso; intuition.\n    - intros. hnf in H0. simpl in H1. destruct H0.\n      + subst x. destruct Hm. apply valid_not_null in H0; auto. simpl. auto.\n      + subst v. auto.\n  Defined.\n\n  Definition make_set_FiniteGraph (v: addr) (g: PreGraph addr (addr * unit)) (Hf: FiniteGraph g): FiniteGraph (make_set_pregraph v g).\n  Proof.\n    destruct Hf. unfold EnumEnsembles.Enumerable in *. destruct finiteV as [vl [? ?]]. destruct finiteE as [el [? ?]]. constructor; hnf; simpl; unfold addValidFunc.\n    - destruct (in_dec SGBA_VE v vl).\n      + exists vl. split; auto. intros. unfold In in H0 |-* . rewrite H0. intuition. subst v. rewrite H0 in i. auto.\n      + exists (v :: vl). split; [constructor; auto|]. intros. simpl. unfold In in H0 |-* . rewrite H0. intuition.\n    - unfold In in H2 |-* . destruct (in_dec SGBA_EE (v, tt) el).\n      + exists el. split; auto. intros. rewrite H2. intuition. inversion H4. rewrite H2 in i. auto.\n      + exists ((v, tt) :: el). split; [constructor; auto|]. intros. simpl. rewrite H2. intuition.\n  Defined.\n\n  Lemma make_set_valid_path_pfoot: forall (v: addr) (g: PreGraph addr (addr * unit)) x p (Hn: v <> null) (Hi: ~ vvalid g v) (Hm: MathGraph g is_null_SGBA),\n      x <> v -> pfoot (make_set_pregraph v g) p = x -> valid_path (make_set_pregraph v g) p -> pfoot g p = x /\\ valid_path g p.\n  Proof.\n    intros. destruct p as [p l]. assert (forall e, List.In e l -> e <> (v, tt)). {\n      intros. apply (valid_path_strong_evalid _ _ _ e) in H1; auto. hnf in H1. simpl in H1. unfold addValidFunc, updateEdgeFunc in H1.\n      destruct H1 as [? [? ?]]. intro. destruct (equiv_dec (v, tt) e). 2: compute in c; auto. destruct H4; auto. destruct Hm. apply valid_not_null in H4; simpl; auto.\n    } split.\n    - clear H1. revert p H0. induction l; intros. 1: simpl in H0 |-* ; auto.\n      assert (forall e : addr * unit, List.In e l -> e <> (v, tt)) by (intros; apply H2; right; auto). specialize (IHl H1). clear H1.\n      rewrite pfoot_cons in H0 |-* . simpl dst in H0. unfold updateEdgeFunc in H0. destruct (equiv_dec (v, tt) a).\n      + hnf in e. assert (a <> (v, tt)) by (apply H2; left; auto). exfalso; auto.\n      + apply IHl; auto.\n    - assert (p <> v). {\n        intro. subst p. destruct l. 1: simpl in H0; auto. simpl in H1. destruct H1. assert (strong_evalid (make_set_pregraph v g) p) by (destruct l; [|destruct H3]; auto).\n        clear H3. hnf in H4. simpl in H4. unfold addValidFunc, updateEdgeFunc in H1, H4. destruct H4 as [? _]. assert (p <> (v, tt)) by (apply H2; left; auto).\n        destruct (equiv_dec (v, tt) p). 1: hnf in e; auto. destruct H3; auto. destruct Hm. apply valid_graph in H3. destruct H3 as [? _]. rewrite <- H1 in H3. auto.\n      } clear H0. revert p H1 H3. induction l; intros.\n      + simpl in H1. unfold addValidFunc in H1. simpl. destruct H1; [|exfalso]; auto.\n      + assert (forall e : addr * unit, List.In e l -> e <> (v, tt)) by (intros; apply H2; right; auto). specialize (IHl H0). clear H0.\n        assert (a <> (v, tt)) by (apply H2; left; auto). rewrite valid_path_cons_iff in H1 |-* . destruct H1 as [? [? ?]]. split; [|split].\n        * simpl in H1. unfold updateEdgeFunc in H1. destruct (equiv_dec (v, tt) a); [exfalso|]; auto.\n        * hnf in H4. simpl in H4. unfold addValidFunc, updateEdgeFunc in H4. destruct H4 as [? [? ?]].\n          destruct (equiv_dec (v, tt) a); [hnf in e; exfalso|]; auto. destruct H4; [|exfalso]; auto. clear c.\n          destruct H6. 2: destruct Hm; apply valid_graph in H4; destruct H4; rewrite H6 in H4; exfalso; auto.\n          destruct H7. 2: destruct Hm; apply valid_graph in H4; destruct H4; hnf in H8; simpl in H8; rewrite H7 in H8; exfalso; destruct H8; auto. hnf. split; auto.\n        * simpl dst in H5. unfold updateEdgeFunc in H5. destruct (equiv_dec (v, tt) a); [hnf in e; exfalso|]; auto. apply IHl; auto.\n          destruct H4 as [? _]. simpl in H4. unfold addValidFunc in H4. destruct H4; [|exfalso]; auto. destruct Hm. apply valid_graph in H4. destruct H4 as [_ ?].\n          hnf in H4. simpl in H4. intro. rewrite H6 in H4. destruct H4; auto.\n  Qed.\n\n  Definition make_set_LstGraph (v: addr) (g: PreGraph addr (addr * unit)) (Hn: v <> null) (Hi: ~ vvalid g v) (Hm: MathGraph g is_null_SGBA)\n             (Hl: LstGraph g (fun x => (x, tt))): LstGraph (make_set_pregraph v g) (fun x => (x, tt)).\n  Proof.\n    constructor; simpl.\n    - unfold addValidFunc, updateEdgeFunc. intros. destruct H.\n      + destruct Hl. specialize (only_one_edge x e H). destruct (equiv_dec (v, tt) e).\n        * hnf in e0. subst e. rewrite <- only_one_edge. split; intros.\n          -- destruct H0. subst v. rewrite only_one_edge. auto.\n          -- rewrite only_one_edge in H0. inversion H0. subst v. split; auto.\n        * compute in c. rewrite <- only_one_edge. split; intros.\n          -- destruct H0. split; auto. destruct H1; auto. exfalso; auto.\n          -- destruct H0. split; auto.\n      + subst v. split; intros.\n        * destruct H. destruct H0; auto. destruct (equiv_dec (x, tt) e).\n          -- hnf in e0; auto.\n          -- destruct Hm. specialize (valid_graph _ H0). destruct valid_graph. rewrite H in H1. exfalso; auto.\n        * destruct (equiv_dec (x, tt) e).\n          -- hnf in e0. split; auto.\n          -- compute in c. exfalso; auto.\n    - intros. destruct_eq_dec x v.\n      + subst x. destruct p as [p l]. destruct H as [[? ?] [? _]]. simpl in H. subst p. simpl in H1. destruct l; auto. unfold updateEdgeFunc in H1. destruct H1.\n        assert (strong_evalid (make_set_pregraph v g) p) by (simpl in H1; destruct l; [|destruct H1]; auto). hnf in H2. simpl in H2. unfold addValidFunc, updateEdgeFunc in H2.\n        destruct H2 as [? [? ?]]. destruct (equiv_dec (v, tt) p).\n        * exfalso. destruct H4; auto. destruct Hm. apply valid_not_null in H4; simpl; auto.\n        * compute in c. exfalso. destruct H2; auto. destruct Hm. apply valid_graph in H2. destruct H2. subst v. auto.\n      + destruct Hl. apply no_loop_path. destruct H as [[? ?] [? ?]]. assert (pfoot g p = x /\\ valid_path g p) by (apply (make_set_valid_path_pfoot v); auto).\n        destruct H4. split; split; auto.\n  Defined.\n\n  Definition make_set_sound (v: addr)  (g: PreGraph addr (addr * unit)) (Hn: v <> null) (Hi: ~ vvalid g v) (Hlmf: LiMaFin g) : LiMaFin (make_set_pregraph v g) :=\n    Build_LiMaFin _ (make_set_LstGraph v g Hn Hi ma li) (make_set_MathGraph v g Hn ma) (make_set_FiniteGraph v g fin).\n\n  Definition make_set_Graph (default_dv: DV) (default_de: DE) (default_dg: DG) (v: addr) (g: UFGraph) (Hn: v <> null) (Hi: ~ vvalid g v) : UFGraph :=\n    Build_GeneralGraph _ _ _ _ (make_set_LabeledGraph v g default_dv default_de default_dg) (make_set_sound v g Hn Hi (sound_gg g)).\n\n  Lemma uf_under_bound_make_set_graph: forall (default_dv: DV) (default_de: DE) (default_dg: DG) (v: addr) (g: UFGraph) (Hn: v <> null) (Hi: ~ vvalid g v) (extract: DV -> nat),\n      extract default_dv = O -> uf_under_bound extract g -> uf_under_bound extract (make_set_Graph default_dv default_de default_dg v g Hn Hi).\n  Proof.\n    intros. hnf in H0 |-* . simpl. intro x; intros. unfold addValidFunc in H1. destruct (SGBA_VE x v).\n    - hnf in e. subst v. destruct H1; [exfalso; auto |]. clear H1. hnf. intros. rewrite H. destruct p as [p l]. destruct l; simpl; auto. exfalso.\n      apply pfoot_in_cons in H2. destruct H2 as [e [? ?]]. simpl in H3. unfold updateEdgeFunc in H3. pose proof (valid_path_strong_evalid _ _ _ _ H1 H2). hnf in H4.\n      simpl in H4. unfold addValidFunc, updateEdgeFunc in H4. destruct H4 as [? [? ?]]. destruct (equiv_dec (x, tt) e). 1: exfalso; auto. compute in c.\n      destruct H4; auto. destruct (@valid_graph _ _ _ _ g _ (maGraph g) _ H4) as [_ ?]. rewrite H3 in H7. destruct H7; auto.\n    - compute in c. destruct H1; [|exfalso; auto]. hnf. intros. assert (pfoot g p = x /\\ valid_path g p) by (apply (make_set_valid_path_pfoot v); auto; exact (maGraph g)).\n      destruct H4. unfold uf_bound in H0. apply H0; auto.\n  Qed.\n\n  Definition single_uf_pregraph (v: addr) : PreGraph addr (addr * unit) :=\n    pregraph_add_edge (single_vertex_pregraph v) (v, tt) v null.\n\n  Lemma reachabel_single_uf: forall x y, x <> null -> reachable (single_uf_pregraph x) x y <-> x = y.\n  Proof.\n    intros. split; intros.\n    - destruct H0 as [[? ?] [[? ?] [? _]]]. simpl in H0. subst a. destruct l.\n      + simpl in H1. auto.\n      + destruct H2. simpl in H2. assert (strong_evalid (single_uf_pregraph x) p) by (destruct l; intuition). clear H2. exfalso.\n        hnf in H3. simpl in H3. unfold updateEdgeFunc in H3. destruct H3 as [? [_ ?]]. unfold addValidFunc in H2. destruct H2; auto. subst p.\n        destruct (equiv_dec (x, tt) (x, tt)); [|compute in c]; auto.\n    - subst y. apply reachable_refl. simpl. auto.\n  Qed.\n\n  Definition single_uf_LabeledGraph (v: addr) (default_dv: DV) (default_de: DE) (default_dg: DG) : LGraph :=\n    Build_LabeledGraph _ _ _ (single_uf_pregraph v) (fun v => default_dv) (fun e => default_de) default_dg.\n\n  Definition single_uf_MathGraph (v: addr) (H: v <> null): MathGraph (single_uf_pregraph v) is_null_SGBA.\n  Proof.\n    apply (Build_MathGraph _ is_null_SGBA).\n    - intros. simpl. unfold updateEdgeFunc.\n      destruct (equiv_dec (v, tt) e); intuition.\n    - intros. hnf in *. subst v. intuition.\n  Defined.\n\n  Definition single_uf_FiniteGraph (v: addr): FiniteGraph (single_uf_pregraph v).\n  Proof.\n    constructor; hnf.\n    - exists (v :: nil). split.\n      + constructor. intro. inversion H. constructor.\n      + intros. simpl. unfold In. intuition.\n    - exists ((v, tt) :: nil). split.\n      + constructor. intro. inversion H. constructor.\n      + intros. simpl. unfold In, addValidFunc. intuition.\n  Defined.\n\n  Definition single_uf_LstGraph (v: addr) (H: v <> null): LstGraph (single_uf_pregraph v) (fun x => (x, tt)).\n  Proof.\n    constructor; simpl; intros; unfold updateEdgeFunc.\n    - unfold addValidFunc. subst. destruct (equiv_dec (x, tt) e); intuition.\n    - destruct H0 as [[? _] [? _]]. destruct p as [p l]. simpl in *. subst p.\n      destruct l; auto. destruct H1. clear H0. simpl in H1. assert (strong_evalid (single_uf_pregraph v) p) by (destruct l; [|destruct H1]; auto). clear H1.\n      hnf in H0. simpl in H0. unfold addValidFunc, updateEdgeFunc in H0. destruct H0 as [? [_ ?]]. exfalso. destruct H0; auto. subst p.\n      destruct (equiv_dec (v, tt) (v, tt)); auto. compute in c. apply c; auto.\n  Defined.\n\n  Definition single_sound (v: addr) (H: v <> null) : LiMaFin (single_uf_pregraph v) :=\n    Build_LiMaFin _ (single_uf_LstGraph v H) (single_uf_MathGraph v H) (single_uf_FiniteGraph v).\n\n  Definition single_Graph (v: addr) (H: v <> null) (default_dv: DV) (default_de: DE) (default_dg: DG): UFGraph :=\n    Build_GeneralGraph _ _ _ _ (single_uf_LabeledGraph v default_dv default_de default_dg) (single_sound v H).\n\nEnd GRAPH_GList.\n", "meta": {"author": "CertiGraph", "repo": "CertiGraph", "sha": "1be51414c139f8bc16b3e22f72989e454c37ce3c", "save_path": "github-repos/coq/CertiGraph-CertiGraph", "path": "github-repos/coq/CertiGraph-CertiGraph/CertiGraph-1be51414c139f8bc16b3e22f72989e454c37ce3c/msl_application/GList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.29736038891054617}}
{"text": "Require Import List.\nRequire Import Cps.\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 CPS.\n\n  Section maps.\n    Variable env_v : Type -> Type.\n    Context {Mv : DMap var env_v}.\n    \n    Section monadic. \n      Variable m : Type -> Type.\n      Context {Monad_m : Monad m}.\n      Context {Reader_m : MonadReader (env_v var) 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      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 args1 , App_e f2 args2 =>\n            alpha_op f1 f2 ;;\n            all2 alpha_op args1 args2\n          | Let_e ds1 e1 , Let_e ds2 e2 =>\n            (** ignore permutations for now... **)\n            alpha_dec ds1 ds2 (alpha_exp' e1 e2)\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                | _ , _ => 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          | _ , _ => 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 a1 e1 , Fn_d v2 a2 e2 =>\n            (fix map_multi (x y : list var) (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) 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 (unOptionT (alpha_exp' (m := optionT (reader (alist var var))) e1 e2)) empty in\n    match res with\n      | None => false\n      | Some _ => true\n    end.\n\n  Definition alpha_lam (e1 e2 : exp) : list var -> list var -> bool :=\n    (fix build acc l1 l2 {struct l1} : bool :=\n      match l1 , l2 with\n        | nil , nil => \n          let res := runReader (unOptionT (alpha_exp' (m := optionT (reader (alist var var))) e1 e2)) acc 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.\n  \n  Module TEST.\n    Require Import String.\n\n\n    (** Test cases needed **)\n    Definition f (v : var) : exp := Halt_e (Var_o v) (Var_o (wrapVar \"world\"%string)).\n\n    Goal (alpha_exp (f (wrapVar \"0\")) (f (wrapVar \"2\")) = false)%string.\n    Proof. vm_compute; reflexivity. Abort.\n\n    Goal (alpha_exp (f (wrapVar \"0\")) (f (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/AlphaEquivCps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2973108115627875}}
{"text": "Require Import Lang.Syntax Lang.Bindings.\nSet Implicit Arguments.\n\nSection section_ktx.\n\nContext (EV LV V L : Set).\n\n(** Use [t] to fill in the hole of [ktx] *)\nFixpoint ktx_plug\n(K : ktx EV LV V L) (t : tm EV LV V L) {struct K} :\ntm EV LV V L :=\nmatch K with\n| ktx_hole => t\n| ktx_op K => tm_op (ktx_plug K t)\n| ktx_up K => tm_up (ktx_plug K t)\n| ktx_down K X => tm_down X (ktx_plug K t)\n| ktx_let K s => tm_let (ktx_plug K t) s\n| ktx_throw K s => tm_throw (ktx_plug K t) s\n| ktx_app_eff K E => tm_app_eff (ktx_plug K t) E\n| ktx_app_lbl K ℓ => tm_app_lbl (ktx_plug K t) ℓ\n| ktx_app_tm1 K s => tm_app_tm (ktx_plug K t) s\n| ktx_app_tm2 K v => tm_app_tm v (ktx_plug K t)\nend.\n\n(** Compose outer evaluation context [K] and inner evaluation context\n[J] to form a new evaluation context. *)\nFixpoint ktx_comp\n(K : ktx EV LV V L) (J : ktx EV LV V L) {struct K} :\nktx EV LV V L :=\nmatch K with\n| ktx_hole => J\n| ktx_op K => ktx_op (ktx_comp K J)\n| ktx_up K => ktx_up (ktx_comp K J)\n| ktx_down K X => ktx_down (ktx_comp K J) X\n| ktx_let K t => ktx_let (ktx_comp K J) t\n| ktx_throw K t => ktx_throw (ktx_comp K J) t\n| ktx_app_eff K E => ktx_app_eff (ktx_comp K J) E\n| ktx_app_lbl K ℓ => ktx_app_lbl (ktx_comp K J) ℓ\n| ktx_app_tm1 K t => ktx_app_tm1 (ktx_comp K J) t\n| ktx_app_tm2 K v => ktx_app_tm2 (ktx_comp K J) v\nend.\n\n(** Return [True] iff [X] is not a delimiter in [K]. *)\nFixpoint tunnels (X : var) (K : ktx EV LV V L) : Prop :=\nmatch K with\n| ktx_hole => True\n| ktx_op K => tunnels X K\n| ktx_up K => tunnels X K\n| ktx_down K Y => tunnels X K ∧ X ≠ Y\n| ktx_let K _ => tunnels X K\n| ktx_throw K _ => tunnels X K\n| ktx_app_eff K _ => tunnels X K\n| ktx_app_lbl K _ => tunnels X K\n| ktx_app_tm1 K _ => tunnels X K\n| ktx_app_tm2 K _ => tunnels X K\nend.\n\nEnd section_ktx.\n\n\nInductive config :=\n| config_mk : list var → tm0 → config\n.\n\nNotation \"⟨ ξ , t ⟩\" := (config_mk ξ t) : core_scope.\n\nInductive step : config → config → Prop :=\n(** reduction rules *)\n| step_let :\n  ∀ ξ (v : val0) t,\n  step ⟨ξ, tm_let v t⟩ ⟨ξ, V_subst_tm v t⟩\n| step_throw :\n  ∀ ξ K t,\n  step\n  ⟨ξ, tm_throw (val_cont K) t⟩\n  ⟨ξ, ktx_plug K t⟩\n| step_op :\n  ∀ ξ m ι,\n  step\n  ⟨ξ, tm_op (val_fix m ι)⟩\n  ⟨ξ, val_md (V_subst_md (val_fix m ι) m) ι⟩\n| step_app_eff :\n  ∀ ξ m ι E,\n  step\n  ⟨ξ, tm_app_eff (val_md (md_ev m) ι) E⟩\n  ⟨ξ, val_md (EV_subst_md E m) ι⟩\n| step_app_lbl :\n  ∀ ξ m ι ℓ,\n  step\n  ⟨ξ, tm_app_lbl (val_md (md_lv m) ι) ℓ⟩\n  ⟨ξ, val_md (LV_subst_md ℓ m) ι⟩\n| step_app_tm :\n  ∀ ξ m ι (v : val0),\n  step\n  ⟨ξ, tm_app_tm (val_md (md_tm m) ι) v⟩\n  ⟨ξ, val_md (V_subst_md v m) ι⟩\n| step_Down :\n  ∀ ξ t X,\n  X ∉ from_list ξ → (* This arbitrariness of [X] induces non-determinism *)\n  step\n  ⟨ξ, ⬇ t⟩\n  ⟨X :: ξ, ⇩ X (L_subst_tm (lid_f X) t)⟩\n| step_down_val :\n  ∀ ξ X (v : val0),\n  step ⟨ξ, ⇩ X v⟩ ⟨ξ, v⟩\n| step_down_up :\n  ∀ ξ X K t,\n  tunnels X K →\n  step\n  ⟨ξ, ⇩ X (ktx_plug K (⇧ (val_md (md_res t) (lid_f X))))⟩\n  ⟨ξ, V_subst_tm (val_cont (ktx_down K X)) t⟩\n\n(** structural rules *)\n| step_ktx_let :\n  ∀ ξ₁ ξ₂ t₁ t₂ s,\n  step ⟨ξ₁, t₁⟩ ⟨ξ₂, t₂⟩ →\n  step ⟨ξ₁, tm_let t₁ s⟩ ⟨ξ₂, tm_let t₂ s⟩\n| step_ktx_throw :\n  ∀ ξ₁ ξ₂ t₁ t₂ s,\n  step ⟨ξ₁, t₁⟩ ⟨ξ₂, t₂⟩ →\n  step ⟨ξ₁, tm_throw t₁ s⟩ ⟨ξ₂, tm_throw t₂ s⟩\n| step_ktx_app_tm1 :\n  ∀ ξ₁ ξ₂ t₁ t₂ s,\n  step ⟨ξ₁, t₁⟩ ⟨ξ₂, t₂⟩ →\n  step ⟨ξ₁, tm_app_tm t₁ s⟩ ⟨ξ₂, tm_app_tm t₂ s⟩\n| step_ktx_app_tm2 :\n  ∀ ξ₁ ξ₂ (v : val0) t₁ t₂ ,\n  step ⟨ξ₁, t₁⟩ ⟨ξ₂, t₂⟩ →\n  step ⟨ξ₁, tm_app_tm v t₁⟩ ⟨ξ₂, tm_app_tm v t₂⟩\n| step_ktx_app_eff :\n  ∀ ξ₁ ξ₂ t₁ t₂ E,\n  step ⟨ξ₁, t₁⟩ ⟨ξ₂, t₂⟩ →\n  step ⟨ξ₁, tm_app_eff t₁ E⟩ ⟨ξ₂, tm_app_eff t₂ E⟩\n| step_ktx_app_lbl :\n  ∀ ξ₁ ξ₂ t₁ t₂ ℓ,\n  step ⟨ξ₁, t₁⟩ ⟨ξ₂, t₂⟩ →\n  step ⟨ξ₁, tm_app_lbl t₁ ℓ⟩ ⟨ξ₂, tm_app_lbl t₂ ℓ⟩\n| step_ktx_op :\n  ∀ ξ₁ ξ₂ t₁ t₂ ,\n  step ⟨ξ₁, t₁⟩ ⟨ξ₂, t₂⟩ →\n  step ⟨ξ₁, tm_op t₁⟩ ⟨ξ₂, tm_op t₂⟩\n| step_ktx_up :\n  ∀ ξ₁ ξ₂ t₁ t₂ ,\n  step ⟨ξ₁, t₁⟩ ⟨ξ₂, t₂⟩ →\n  step ⟨ξ₁, tm_up t₁⟩ ⟨ξ₂, tm_up t₂⟩\n| step_ktx_down :\n  ∀ ξ₁ ξ₂ t₁ t₂ X,\n  step ⟨ξ₁, t₁⟩ ⟨ξ₂, t₂⟩ →\n  step ⟨ξ₁, ⇩ X t₁⟩ ⟨ξ₂, ⇩ X t₂⟩\n.\n\n(** The transitive closure of the reduction relation. *)\nDefinition step_tran := @Relation_Operators.clos_trans_1n _ step.\n\n(** The reflexive and transitive closure of the reduction relation. *)\nDefinition step_refl_tran := @Relation_Operators.clos_refl_trans_1n _ step.\n\n(** Reduction in a given number of steps. *)\nInductive step_n : nat → config → config → Prop :=\n| step_n_O : ∀ c, step_n O c c\n| step_n_S : ∀ n c₁ c₂ c₃,\n    step c₁ c₂ →\n    step_n n c₂ c₃ →\n    step_n (S n) c₁ c₃\n.\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/Operational.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2973108115627875}}
{"text": "Require Import Events.\nRequire Import TraceModel.\nRequire Import Properties.\nRequire Import CommonST.\nRequire Import Robustdef.\nRequire Import Setoid.\nRequire Import ClassicalExtras.\nRequire Import List.\n\nRequire Import XPrefix.\nRequire Import Criteria.\nRequire Import TechnicalLemmas. \n\n(** *our assumptions *)\n(**********************************************************)\nHypothesis input_totality_tgt : input_totality tgt.\nHypothesis determinacy_src    : determinacy src.\nHypothesis tgt_sem           : semantics_safety_like tgt.\n(**********************************************************)\n\n  \nLemma three_continuations_tbd :\n  forall l t, xprefix (xtbd l) t ->\n         ( (exists e, t = tstop l e) \\/\n                 (t = tsilent l) \\/\n            (exists e, xprefix (xtbd (snoc l e)) t)).\nProof.\n  intros l [] Hpref.\n  + simpl in Hpref. apply list_proper_or_equal in Hpref. destruct Hpref.\n    ++ subst. left. now exists e.\n    ++ right. right. firstorder.  \n  + simpl in Hpref. apply list_proper_or_equal in Hpref. destruct Hpref.\n    ++ subst. right. now left.\n    ++ right. right. firstorder. \n  + generalize dependent s. induction l.\n    ++ right. right. destruct s. now exists e. \n    ++ intros [] Hpref. inversion Hpref. simpl.\n       destruct (IHl s) as [ [ef FALSE] | [ FALSE | [e0 HH] ]]; try now inversion FALSE; auto.\n       now simpl. right. right. exists e0; firstorder.  \nQed.\n\n\n(*********************************************************************************)\n\nDefinition myXr (x1 x2: xpref) : Prop :=\n  (xpr x1 x2) \\/ (xpr x2 x1) \\/\n  (exists l i1 i2, is_input i1 /\\\n               is_input i2 /\\\n               i1 <> i2 /\\\n               xpr (xtbd (snoc l i1)) x1 /\\\n               xpr (xtbd (snoc l i2)) x2).\n\n\nLemma myXr_symmetric : forall x1 x2, myXr x1 x2 -> myXr x2 x1.\n Proof. firstorder. Qed. \n\nLemma auXiliary_tstop :\n  forall x2 l1 e1 t2, xprefix x2 t2 ->\n                  traces_match (tstop l1 e1) t2 -> myXr (xstop l1 e1) x2.\nProof.\n  intros x2 l1 e1 t2 xprefix2 [Heq | [ll [i1 [i2 [I1 [I2 [Idiff [l_prefix1 l_prefix2]]]]]]]].\n  + rewrite <- Heq in *. destruct (xsame_ext (xstop l1 e1) x2 (tstop l1 e1)); simpl; auto;\n                          [now left |  right; now left].\n  + destruct x2, t2; simpl in xprefix2; simpl in l_prefix1, l_prefix2; try now auto.   \n    ++ inversion xprefix2; subst.  \n       right. right. now exists ll, i1, i2.\n    ++ destruct (list_list_same_ext l (snoc ll i2) l0); auto.\n       * destruct (list_proper_or_equal _ _ H) as [HH | [a HH]].        \n         ** subst. right. right. now exists ll, i1, i2.\n         ** apply list_pref_snoc_pref in HH.\n            right. left. simpl. apply (list_list_prefix_trans l (snoc ll i1) l1);auto.\n            apply (list_list_prefix_trans l ll _); auto. now apply snoc_longer. \n       * right. right. now exists ll, i1, i2.  \n    ++ destruct (list_list_same_ext l (snoc ll i2) l0); auto.\n       * destruct (list_proper_or_equal _ _ H) as [HH | [a HH]].        \n         ** subst. right. right. now exists ll, i1, i2.\n         ** apply list_pref_snoc_pref in HH.\n            right. left. simpl. apply (list_list_prefix_trans l (snoc ll i1) l1);auto.\n            apply (list_list_prefix_trans l ll _); auto. now apply snoc_longer. \n       * right. right. now exists ll, i1, i2.\n    ++ destruct (list_stream_same_ext l (snoc ll i2) s); auto.\n       * destruct (list_proper_or_equal _ _ H) as [HH | [a HH]].        \n         ** subst. right. right. now exists ll, i1, i2.\n         ** apply list_pref_snoc_pref in HH.\n            right. left. simpl. apply (list_list_prefix_trans l (snoc ll i1) l1);auto.\n            apply (list_list_prefix_trans l ll _); auto. now apply snoc_longer. \n       * right. right. now exists ll, i1, i2.  \n    ++ subst. right. right. now exists ll, i1, i2. \nQed. \n\nLemma auXiliary_tsilent :\n  forall x2 l1 t2, xprefix x2 t2 ->\n                traces_match (tsilent l1) t2 -> myXr (xsilent l1) x2.\nProof.\n  intros x2 l1 t2 xprefix2 [Heq | [ll [i1 [i2 [I1 [I2 [Idiff [l_prefix1 l_prefix2]]]]]]]].\n  + rewrite <- Heq in *. destruct (xsame_ext (xsilent l1) x2 (tsilent l1)); simpl; auto;\n                          [now left |  right; now left].\n   + destruct x2, t2; simpl in xprefix2; simpl in l_prefix1, l_prefix2; try now auto.   \n    ++ inversion xprefix2; subst.  \n       right. right. now exists ll, i1, i2.\n    ++ destruct (list_list_same_ext l (snoc ll i2) l0); auto.\n       * destruct (list_proper_or_equal _ _ H) as [HH | [a HH]].        \n         ** subst. right. right. now exists ll, i1, i2.\n         ** apply list_pref_snoc_pref in HH.\n            right. left. simpl. apply (list_list_prefix_trans l (snoc ll i1) l1);auto.\n            apply (list_list_prefix_trans l ll _); auto. now apply snoc_longer. \n       * right. right. now exists ll, i1, i2.  \n    ++ destruct (list_list_same_ext l (snoc ll i2) l0); auto.\n       * destruct (list_proper_or_equal _ _ H) as [HH | [a HH]].        \n         ** subst. right. right. now exists ll, i1, i2.\n         ** apply list_pref_snoc_pref in HH.\n            right. left. simpl. apply (list_list_prefix_trans l (snoc ll i1) l1);auto.\n            apply (list_list_prefix_trans l ll _); auto. now apply snoc_longer. \n       * right. right. now exists ll, i1, i2.\n    ++ destruct (list_stream_same_ext l (snoc ll i2) s); auto.\n       * destruct (list_proper_or_equal _ _ H) as [HH | [a HH]].        \n         ** subst. right. right. now exists ll, i1, i2.\n         ** apply list_pref_snoc_pref in HH.\n            right. left. simpl. apply (list_list_prefix_trans l (snoc ll i1) l1);auto.\n            apply (list_list_prefix_trans l ll _); auto. now apply snoc_longer. \n       * right. right. now exists ll, i1, i2.  \n    ++ subst. right. right. now exists ll, i1, i2.\nQed. \n\n\nLemma auXiliary_xtbd:\n  forall l1 l2 t1 t2, xprefix (xtbd l1) t1 -> xprefix (xtbd l2) t2 ->\n                  traces_match t1 t2 -> myXr (xtbd l1) (xtbd l2).\nProof.\n  intros l1 l2 t1 t2 xpref1 xpref2 [Heq | [ll [i1 [i2 [I1 [I2 [Idiff [l_prefix1 l_prefix2]]]]]]]].\n  + subst. destruct (xsame_ext (xtbd l1) (xtbd l2) t2); auto; [now left | right; now left]. \n  + assert (H1: xprefix (xtbd (snoc ll i1)) t1).\n    { destruct t1; simpl in *; now auto. }\n    assert (H2 : xprefix (xtbd (snoc ll i2)) t2).\n    { destruct t2; simpl in *; now auto. }\n    destruct (xsame_ext (xtbd l1) (xtbd (snoc ll i1)) t1) as [l1_shorter | l1_longer]; auto. \n    ++ destruct (xsame_ext (xtbd l2) (xtbd (snoc ll i2)) t2) as [l2_shorter | l2_longer]; auto.\n       destruct (list_proper_or_equal _ _ l1_shorter) as [l1_ll | [a1 l1_ll]]; subst.\n       * destruct (list_proper_or_equal _ _ l2_shorter) as [l2_ll | [a2 l2_ll]]; subst. \n          ** right. right. now exists ll, i1, i2. \n          ** apply list_pref_snoc_pref in l2_ll. right. left. simpl.\n             apply (list_list_prefix_trans l2 ll _); auto. now apply snoc_longer.  \n       * apply list_pref_snoc_pref in l1_ll.\n         destruct (list_proper_or_equal _ _ l2_shorter) as [l2_ll | [a2 l2_ll]]; subst. \n         **  left. simpl. apply (list_list_prefix_trans l1 ll _ ); auto. now apply snoc_longer.  \n         ** apply list_pref_snoc_pref in l2_ll. destruct (list_list_same_ext l1 l2 ll); auto;\n                                                  [now left | right; now left].  \n       * destruct (list_proper_or_equal  _ _ l1_shorter); auto; subst. \n         ** right. right. now exists ll, i1, i2.  \n         ** destruct H as [a H]. apply list_pref_snoc_pref in H. left.\n            simpl. apply (list_list_prefix_trans l1 ll l2); auto.\n            simpl in l2_longer. apply (list_list_prefix_trans ll (snoc ll i2) l2); auto.\n            now apply snoc_longer.  \n    ++ destruct (xsame_ext (xtbd l2) (xtbd (snoc ll i2)) t2) as [l2_shorter | l2_longer]; auto.\n       * destruct (list_proper_or_equal _ _ l2_shorter) as [l2_ll | [a2 l2_ll]]; subst. \n          ** right. right. now exists ll, i1, i2. \n          ** apply list_pref_snoc_pref in l2_ll. right. left. simpl.\n             apply (list_list_prefix_trans l2 ll _); auto.\n             apply (list_list_prefix_trans ll (snoc ll i1) _); auto. now apply snoc_longer.\n        * right. right. now exists ll, i1, i2.\nQed.   \n    \n\nLemma auXiliary_lemma (t1 t2 : trace) :\n  traces_match t1 t2 ->\n  forall x1 x2,  xprefix x1 t1 -> xprefix x2 t2 -> myXr x1 x2.\nProof.\n  intros [Heq | [ll [i1 [i2 [I1 [I2 [Idiff [l_prefix1 l_prefix2]]]]]]]] x1 x2 xprefix1 xprefix2. \n  - subst. unfold myXr. destruct (xsame_ext x1 x2 t2) as [go_left | go_right_left]; auto. \n  - destruct x1, x2.\n    ++ destruct t1, t2; inversion xprefix1; inversion xprefix2; subst.\n       right. right. now exists ll, i1, i2.\n    ++ destruct t1; inversion xprefix1; subst.  \n       apply (auXiliary_tstop (xtbd l0) l1 e0 t2); auto.\n       right. now exists ll, i1, i2. \n    ++ destruct t1, t2; inversion xprefix1; inversion xprefix2; subst.\n       simpl in *. right. right. now exists ll, i1, i2.\n    ++ destruct t2; inversion xprefix2; subst. apply myXr_symmetric. \n       apply (auXiliary_tstop (xtbd l) l1 e0 t1); auto.\n       right. exists ll, i2, i1. repeat (split; try now auto). \n    ++ apply (auXiliary_xtbd l l0 t1 t2); auto. right. now exists ll, i1, i2.  \n    ++ destruct t2; inversion xprefix2; subst. apply myXr_symmetric.  \n       apply (auXiliary_tsilent (xtbd l) l1 t1); auto.\n       right. exists ll, i2, i1. repeat (split; try now auto).  \n    ++ destruct t1, t2; inversion xprefix1; inversion xprefix2; subst.\n       simpl in *. right. right. now exists ll, i1, i2.\n    ++ destruct t1; inversion xprefix1; subst.   \n       apply (auXiliary_tsilent (xtbd l0) l1 t2); auto.\n       right. now exists ll, i1, i2.\n    ++ destruct t1, t2; inversion xprefix1; inversion xprefix2; subst.\n       simpl in *. right. right. now exists ll, i1, i2.   \nQed. \n  \nLemma teq_premises_myXr_holds : forall P1 P2,\n    (forall Cs t, sem src (Cs [P1]) t <-> sem src (Cs [P2]) t) ->\n    (forall Cs x1 x2, xsem (Cs [P1]) x1 -> xsem (Cs [P2]) x2 ->\n                 myXr x1 x2).\nProof.\n  intros P1 P2 H Cs x1 x2 [t1 [xpref1 sem1]] [t2 [xpref2 sem2]].\n    rewrite (H Cs t1) in sem1.\n   specialize (determinacy_src (Cs[P2]) t1 t2 sem1 sem2). \n   intros Hmatch. now apply (auXiliary_lemma t1 t2).\nQed.\n    \n\nLemma  longest_in_xsem :\n  forall W t, ~ sem tgt W t ->\n    exists x, xprefix x t /\\ xsem W x /\\\n     (forall x', xprefix x' t -> xsem W x' -> xpr x' x).\nProof.\n  intros W [] HsemWt.  \n  + destruct (list_longest_in_psem W l) as [ll [Hpref [Hpsem Hmax]]].\n    exists (xtbd ll). repeat (split; try now auto). \n    intros [] Hx Hsemx.\n    ++ inversion Hx; subst. destruct Hsemx as [tx [Hprefxtx Hsemx]].\n       destruct tx; inversion Hprefxtx; subst. contradiction.  \n    ++ simpl in *. apply Hmax; auto. \n    ++ inversion Hx. \n  + destruct (list_longest_in_psem W l) as [ll [Hpref [Hpsem Hmax]]].\n    exists (xtbd ll). repeat (split; try now auto). \n    intros [] Hx Hsemx.\n    ++ inversion Hx; subst.   \n    ++ simpl in *. apply Hmax; auto. \n    ++ inversion Hx; subst. simpl in *.\n       destruct Hsemx as [tx [Hprefxtx Hsemx]].\n       destruct tx; inversion Hprefxtx; subst. contradiction.\n  + destruct (tgt_sem (tstream s) W) as [l [ebad [Hseml [Hprefl Hnsem_longer]]]]; auto. \n    exists (xtbd l). simpl in *. repeat (split; try now auto).\n    ++ apply (list_stream_prefix_trans l (snoc l ebad) s); auto.\n       now apply snoc_longer.\n    ++ intros [] Hpref_x HxsemW; try now inversion Hpref_x.   \n       simpl in *. destruct (list_stream_same_ext l0 (snoc l ebad) s); auto.\n       * apply list_proper_or_equal in H. destruct H as [H | [a H]].\n         ** subst. exfalso. apply Hnsem_longer. destruct HxsemW as [tx [H1 H2]]. \n                 now exists tx. \n         ** now apply list_pref_snoc_pref in H.\n       * exfalso. apply Hnsem_longer. destruct HxsemW as [tx [H1 H2]].\n             exists tx. split; try now auto.\n             destruct tx; simpl in *; try now apply (list_list_prefix_trans (snoc l ebad) l0 l1). \n             now apply (list_stream_prefix_trans (snoc l ebad) l0 s0).\nQed.\n\n\nLemma input_tot_consequence (W : prg tgt): forall l i1 i2,\n    is_input i1 -> is_input i2 -> \n    xsem W (xtbd (snoc l i1)) -> xsem W (xtbd (snoc l i2)).\nProof.\n  intros l i1 i2 Hi1 Hi2 [t [xpref_x_t Hsemt]].\n  assert (psem W (ftbd  (snoc l i1))).\n  { simpl in *. now exists t. }\n  now apply (input_totality_tgt W l i1 i2) in H.\nQed.  \n\nLemma t_being_tstop_leads_to_contra (W1 W2 : prg tgt) t l2 e2 \n                                    (sem1 : sem tgt W1 t) (sem2 : sem tgt W2 (tstop l2 e2))\n                                    (nsem12: ~ sem tgt W2 t)\n                                    (xpref_x_t : xprefix (xtbd l2) t)\n  : \n    (forall x1 x2, xsem W1 x1 -> xsem W2 x2 -> myXr x1 x2) -> False.\nProof.\n intros twoX. destruct t.\n - simpl in *. destruct (twoX (xstop l e) (xstop l2 e2))\n     as [xpr1 | [xpr2 | [xx [i1 [i2 [Hi1 [Hi2 [Hdiff [Hxpr1 Hxpr2]]]]]]]]].\n   now exists (tstop l e). now exists (tstop l2 e2).\n   + inversion xpr1; subst. contradiction.\n   + inversion xpr2; subst. contradiction.                                \n   + simpl in Hxpr1, Hxpr2.\n     apply (list_list_prefix_trans (snoc xx i2) l2 l Hxpr2) in xpref_x_t.   \n     destruct (list_list_same_ext (snoc xx i1) (snoc xx i2) l) as [F | F]; auto;\n       apply Hdiff; apply (list_snoc_diff xx _ _ ) in F; congruence.\n - simpl in xpref_x_t.  destruct (twoX (xsilent l) (xstop l2 e2))\n     as [xpr1 | [xpr2 | [xx [i1 [i2 [Hi1 [Hi2 [Hdiff [Hxpr1 Hxpr2]]]]]]]]].\n    now exists (tsilent l). try now exists (tstop l2 e2).  \n    + now inversion xpr1.                              \n    + now inversion xpr2.\n    + simpl in Hxpr1, Hxpr2.\n     apply (list_list_prefix_trans (snoc xx i2) l2 l Hxpr2) in xpref_x_t.   \n     destruct (list_list_same_ext (snoc xx i1) (snoc xx i2) l) as [F | F]; auto;\n       apply Hdiff; apply (list_snoc_diff xx _ _ ) in F; congruence.\n - simpl in xpref_x_t.\n   destruct (tgt_sem (tstream s) W2 nsem12) as [l [ebad [Hpsem [Hpref Hnpsem]]]]; auto. \n   simpl in Hpref.\n   destruct (twoX (xtbd (snoc l ebad)) (xstop l2 e2))\n     as [xpr1 | [xpr2 | [xx [i1 [i2 [Hi1 [Hi2 [Hdiff [Hxpr1 Hxpr2]]]]]]]]]; auto.  \n   now exists (tstream s). now exists (tstop l2 e2).\n   + simpl in xpr1. apply Hnpsem. now exists (tstop l2 e2).\n   + simpl in *.\n     apply (list_stream_prefix_trans _ _ s) in Hxpr1; auto.  \n     apply (list_stream_prefix_trans _ _ s) in Hxpr2; auto.  \n     destruct (list_stream_same_ext (snoc xx i1) (snoc xx i2) s) as [F | F]; auto;                              apply Hdiff; apply (list_snoc_diff xx _ _) in F; congruence.         \nQed. \n\nLemma t_being_tsilent_leads_to_contra (W1 W2 : prg tgt) t l2  \n                                      (sem1 : sem tgt W1 t) (sem2 : sem tgt W2 (tsilent l2))\n                                      (nsem12: ~ sem tgt W2 t)\n                                      (xpref_x_t : xprefix (xtbd l2) t)\n  : \n    (forall x1 x2, xsem W1 x1 -> xsem W2 x2 -> myXr x1 x2) -> False.\nProof.\n intros twoX. destruct t.\n - simpl in *. destruct (twoX (xstop l e) (xsilent l2))\n     as [xpr1 | [xpr2 | [xx [i1 [i2 [Hi1 [Hi2 [Hdiff [Hxpr1 Hxpr2]]]]]]]]].\n   now exists (tstop l e). now exists (tsilent l2).\n   + now inversion xpr1. \n   + now inversion xpr2.                                \n   + simpl in Hxpr1, Hxpr2.\n     apply (list_list_prefix_trans (snoc xx i2) l2 l Hxpr2) in xpref_x_t.   \n     destruct (list_list_same_ext (snoc xx i1) (snoc xx i2) l) as [F | F]; auto;\n       apply Hdiff; apply (list_snoc_diff xx _ _ ) in F; congruence.\n - simpl in xpref_x_t.  destruct (twoX (xsilent l) (xsilent l2))\n     as [xpr1 | [xpr2 | [xx [i1 [i2 [Hi1 [Hi2 [Hdiff [Hxpr1 Hxpr2]]]]]]]]].\n    now exists (tsilent l). try now exists (tsilent l2).  \n    + simpl in xpr1. now subst.                              \n    + simpl in xpr2. now subst. \n    + simpl in Hxpr1, Hxpr2.\n     apply (list_list_prefix_trans (snoc xx i2) l2 l Hxpr2) in xpref_x_t.   \n     destruct (list_list_same_ext (snoc xx i1) (snoc xx i2) l) as [F | F]; auto;\n       apply Hdiff; apply (list_snoc_diff xx _ _ ) in F; congruence.\n - simpl in xpref_x_t.\n   destruct (tgt_sem (tstream s) W2 nsem12) as [l [ebad [Hpsem [Hpref Hnpsem]]]]; auto. \n   simpl in Hpref.\n   destruct (twoX (xtbd (snoc l ebad)) (xsilent l2))\n     as [xpr1 | [xpr2 | [xx [i1 [i2 [Hi1 [Hi2 [Hdiff [Hxpr1 Hxpr2]]]]]]]]]; auto.  \n   now exists (tstream s). now exists (tsilent l2).\n   + simpl in xpr1. apply Hnpsem. now exists (tsilent l2).\n   + simpl in *.\n     apply (list_stream_prefix_trans _ _ s) in Hxpr1; auto.  \n     apply (list_stream_prefix_trans _ _ s) in Hxpr2; auto.  \n     destruct (list_stream_same_ext (snoc xx i1) (snoc xx i2) s) as [F | F]; auto;                              apply Hdiff; apply (list_snoc_diff xx _ _) in F; congruence.         \nQed. \n \n\nLemma violates_xmax  (W1 W2 : prg tgt) t t2 l a aa\n                     (sem1 : sem tgt W1 t) (sem2 : sem tgt W2 t2)\n                     (nsem12: ~ sem tgt W2 t)\n                     (xpref_x_t : xprefix (xtbd (snoc l aa)) t)\n                     (x_t2 : xprefix (xtbd (snoc l a)) t2)\n                       \n  :\n    (forall x' : xpref, xprefix x' t -> xsem W2 x' -> xpr x' (xtbd l)) -> \n    (forall x1 x2, xsem W1 x1 -> xsem W2 x2 ->  myXr x1 x2) -> False.\nProof.\n  intros xmax twoX.\n  assert (xsem1 : xsem W1 (xtbd (snoc l aa))) by now exists t.\n  assert (xsem2 : xsem W2 (xtbd (snoc l a))) by now exists t2.\n  specialize (twoX (xtbd (snoc l aa)) (xtbd (snoc l a)) xsem1 xsem2).\n  destruct twoX as [xpr1 | [xpr2 | matching]].\n  + simpl in xpr1. apply list_snoc_diff in xpr1. subst.\n    specialize (xmax (xtbd (snoc l a)) xpref_x_t xsem2).\n    simpl in xmax. now apply snoc_strictly_longer in xmax. \n  + simpl in xpr2. apply list_snoc_diff in xpr2. subst.\n    specialize (xmax (xtbd (snoc l aa)) xpref_x_t xsem2).\n    simpl in xmax. now apply snoc_strictly_longer in xmax. \n  + destruct matching as [xx [i1 [i2 [Hi1 [Hi2 [Hdiff_is [Hxpr1 Hxpr2 ]]]]]]].\n    simpl in Hxpr1, Hxpr2.  \n    apply (list_snoc_pointwise xx l i1 i2 aa a) in Hxpr2; auto.  \n    destruct Hxpr2 as [H1 H2]. subst.\n    apply (input_tot_consequence W2 l a aa) in xsem2; auto. \n    specialize (xmax (xtbd (snoc l aa)) xpref_x_t xsem2).\n    simpl in xmax. now apply snoc_strictly_longer in xmax. \nQed. \n    \n\nLemma tinp_premises_myXr_holds : forall P1 P2,\n    (forall Cs t, sem src (Cs [P1]) t -> sem src (Cs [P2]) t) ->\n    (forall Cs x1 x2, xsem (Cs [P1]) x1 -> xsem (Cs [P2]) x2 ->\n                 myXr x1 x2).\nProof.\n  intros P1 P2 H Cs x1 x2 [t1 [xpref1 sem1]] [t2 [xpref2 sem2]].\n  apply (H Cs t1) in sem1.\n   specialize (determinacy_src (Cs[P2]) t1 t2 sem1 sem2). \n   intros Hmatch. now apply (auXiliary_lemma t1 t2).\nQed.\n     \nTheorem R2rXP_RTIP : R2rXP -> RTIP.\nProof.\n  rewrite <- R2rXC_R2rXP, R2rXC_R2rXC'. unfold R2rXC', RTIP, beh.\n  intros twoX P1 P2 Hsrc Ct t.\n  specialize (twoX myXr P1 P2 (tinp_premises_myXr_holds P1 P2 Hsrc) Ct).\n  intros case1.\n    apply NNPP. intros t_not_sem2.\n    destruct (longest_in_xsem (Ct [P2↓]) t t_not_sem2) as [x [xpref_x_t [xsem2_x x_max]]].\n    destruct xsem2_x as [t2 [x_t2 t2_sem2]].\n    destruct x.\n    ++ (* it can only be t2 '=' xstop p e = t *)\n       destruct t, t2; auto.\n       inversion xpref_x_t; inversion x_t2; subst; congruence.  \n    ++ destruct (three_continuations_tbd l t2 x_t2) as [t2stop | [t2silent | t2longer]].\n       +++ destruct t2stop as [e2 Ht2]. rewrite Ht2 in *. \n           now apply (t_being_tstop_leads_to_contra (Ct [P1↓]) (Ct [P2↓]) t l e2).\n       +++ rewrite t2silent in *. \n           now apply (t_being_tsilent_leads_to_contra  (Ct [P1↓]) (Ct [P2↓]) t l).         \n       +++ destruct t2longer as [a t2longer].\n           destruct (three_continuations_tbd l t xpref_x_t) as [ttstop | [ttsilent | ttlonger]].\n           - destruct ttstop as [e ttstop]. subst. \n             destruct (twoX (xstop l e) (xtbd (snoc l a))) as [xpr1 | [xpr2 | matching]]; auto.\n             now exists (tstop l e). now exists t2. \n             -- simpl in xpr2. now apply snoc_strictly_longer in xpr2. \n             -- destruct matching as [xx [i1 [i2 [Hi1 [Hi2 [Hdiff [Hxpr1 Hxpr2 ]]]]]]].\n                simpl in Hxpr1, Hxpr2. \n                apply (snocs_aux_lemma xx l i2 i1 a); congruence.       \n           - subst. \n             destruct (twoX (xsilent l) (xtbd (snoc l a))) as [xpr1 | [xpr2 | matching]]; auto.\n             now exists (tsilent l). now exists t2. \n             -- simpl in xpr2. now apply snoc_strictly_longer in xpr2.\n             -- destruct matching as [xx [i1 [i2 [Hi1 [Hi2 [Hdiff [Hxpr1 Hxpr2 ]]]]]]].\n                simpl in Hxpr1, Hxpr2.\n                apply (snocs_aux_lemma xx l i2 i1 a); congruence. \n           - destruct ttlonger as [aa ttlonger].\n             now apply (violates_xmax (Ct [P1↓]) (Ct [P2↓]) t t2 l a aa).              \n   ++ (*  it can only be t2 '=' xsilent p e = t *)\n      destruct t, t2; auto. \n      inversion xpref_x_t; inversion x_t2; subst; congruence. \nQed.\n\n\nTheorem  R2rXP_RTEP : R2rXP -> RTEP.\nProof. intros H. apply RTIP_RTEP. exact (R2rXP_RTIP H). Qed.", "meta": {"author": "JourneyBeyondFullAbstraction", "repo": "Anonymous", "sha": "db63e973a889738ec3b20453c82307a2857b216b", "save_path": "github-repos/coq/JourneyBeyondFullAbstraction-Anonymous", "path": "github-repos/coq/JourneyBeyondFullAbstraction-Anonymous/Anonymous-db63e973a889738ec3b20453c82307a2857b216b/R2rXP_RTEP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.29731081156278744}}
{"text": "Require Import GhostSimulations.\n\nRequire Import Raft.\nRequire Import RaftRefinementInterface.\nRequire Import CommonDefinitions.\n\nRequire Import LogMatchingInterface.\nRequire Import SortedInterface.\nRequire Import AllEntriesIndicesGt0Interface.\n\nRequire Import RefinedLogMatchingLemmasInterface.\n\nSection RefinedLogMatchingLemmas.\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 {lmi : log_matching_interface}.\n  Context {si : sorted_interface}.\n  Context {aeigt0 : allEntries_indices_gt_0_interface}.\n\n  Lemma 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  Ltac forward_invariant :=\n    match goal with\n    | [ H : refined_raft_intermediate_reachable _, H' : _ |- _ ] =>\n      apply H' in H; clear H'\n    end.\n\n  Ltac forward_nw_invariant :=\n    match goal with\n    | [ H : forall _ _ _ _ _ _ _, In _ _ -> pBody _ = _ -> _,\n        H' : In _ _,\n        H'' : pBody _ = _ |- _ ] =>\n      specialize (H _ _ _ _ _ _ _ H' H'')\n    end.\n\n\n  Lemma entries_contiguous_nw_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      entries_contiguous_nw net.\n  Proof using lmi rri. \n    intros.\n    pose proof (lift_prop _ log_matching_invariant).\n    forward_invariant.\n    unfold log_matching, log_matching_nw, entries_contiguous_nw in *. intuition.\n    find_apply_lem_hyp ghost_packet.\n    forward_nw_invariant. red. intuition.\n  Qed.\n\n  Lemma entries_gt_0_nw_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      entries_gt_0_nw net.\n  Proof using lmi rri. \n    intros.\n    pose proof (lift_prop _ log_matching_invariant).\n    forward_invariant.\n    unfold log_matching, log_matching_nw, entries_gt_0_nw in *. intuition.\n    find_apply_lem_hyp ghost_packet.\n    forward_nw_invariant. break_and.\n    find_apply_hyp_hyp. omega.\n  Qed.\n\n  Lemma entries_sorted_nw_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      entries_sorted_nw net.\n  Proof using si rri. \n    intros.\n    pose proof (lift_prop _ logs_sorted_invariant).\n    forward_invariant.\n    unfold log_matching, log_matching_nw, entries_sorted_nw in *. intuition.\n    find_apply_lem_hyp ghost_packet.\n    unfold logs_sorted in *. break_and.\n    unfold logs_sorted_nw in *.\n    eauto.\n  Qed.\n\n  Lemma entries_gt_0_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      entries_gt_0 net.\n  Proof using lmi rri. \n    intros.\n    pose proof (lift_prop _ log_matching_invariant).\n    forward_invariant.\n    unfold log_matching, log_matching_hosts, entries_gt_0 in *. intuition.\n    match goal with\n    | [ H : _ |- _ ] => setoid_rewrite deghost_spec in H\n    end.\n    eauto.\n  Qed.\n\n  Lemma entries_contiguous_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      entries_contiguous net.\n  Proof using lmi rri. \n    intros.\n    pose proof (lift_prop _ log_matching_invariant).\n    forward_invariant.\n    unfold log_matching, log_matching_hosts, entries_contiguous in *. break_and.\n    intros.\n    repeat match goal with\n    | [ H : _ |- _ ] => setoid_rewrite deghost_spec in H\n    end.\n    red. intuition eauto.\n    find_apply_hyp_hyp. auto.\n  Qed.\n\n  Lemma entries_sorted_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      entries_sorted net.\n  Proof using si rri. \n    intros.\n    pose proof (lift_prop _ logs_sorted_invariant).\n    forward_invariant.\n    unfold entries_sorted, logs_sorted, logs_sorted_host in *. break_and.\n    match goal with\n    | [ H : _ |- _ ] => setoid_rewrite deghost_spec in H\n    end.\n    eauto.\n  Qed.\n\n  Lemma entries_match_invariant :\n    forall net h h',\n      refined_raft_intermediate_reachable net ->\n      entries_match (log (snd (nwState net h))) (log (snd (nwState net h'))).\n  Proof using lmi rri. \n    intros.\n    pose proof (lift_prop _ log_matching_invariant).\n    forward_invariant.\n    unfold log_matching, log_matching_hosts in *. break_and.\n    repeat match goal with\n    | [ H : _ |- _ ] => setoid_rewrite deghost_spec in H\n    end.\n    eauto.\n  Qed.\n\n  Lemma entries_match_nw_1_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      entries_match_nw_1 net.\n  Proof using lmi rri. \n    intros.\n    pose proof (lift_prop _ log_matching_invariant).\n    forward_invariant.\n    unfold log_matching, log_matching_nw, entries_match_nw_1 in *. break_and.\n    intros.\n    repeat find_apply_lem_hyp ghost_packet.\n    match goal with\n    | [ H : forall _ _ _ _ _ _ , _,\n        Hp : In (deghost_packet ?p) _,\n        Hp' : In (deghost_packet ?p') _,\n        Hes : pBody ?p = AppendEntries _ _ _ _ ?es _,\n        Hes' : pBody ?p' = AppendEntries _ _ _ _ ?es' _,\n        He'' : In ?e'' ?es\n        |- In ?e'' ?es' ] =>\n      specialize (H _ _ _ _ _ _ _ Hp Hes); break_and;\n      match goal with\n      | [ H' : forall _ _ _ _ _ _ , _ |- _ ] =>\n        specialize (H' _ _ _ _ _ _ _ Hp' Hes')\n      end\n    end.\n\n    match goal with\n    | [ H : forall _ _, In _ _ -> _ |- _ ] => eapply H with (e1 := e) (e2 := e'); auto\n    end.\n  Qed.\n\n  Lemma entries_match_nw_host_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      entries_match_nw_host net.\n  Proof using lmi rri. \n    intros.\n    pose proof (lift_prop _ log_matching_invariant).\n    forward_invariant.\n    unfold log_matching, log_matching_nw, entries_match_nw_host in *. break_and.\n    intros.\n    repeat find_apply_lem_hyp ghost_packet.\n    forward_nw_invariant. break_and.\n    match goal with\n    | [  |- context [ snd (nwState ?net ?h) ] ] =>\n      replace (snd (nwState net h)) with (nwState (deghost net) h) in * by auto using deghost_spec\n    end.\n    match goal with\n    | [ H : forall _ _ _, In _ ?es -> _,\n        He : In ?e ?es,\n        He' : In ?e' ?log,\n        Hle : eIndex ?e'' <= eIndex ?e\n        |- In ?e'' ?log ] =>\n      specialize (H _ _ _ He He')\n    end.\n    repeat concludes; break_and. eauto.\n  Qed.\n\n  Lemma allEntries_gt_0_invariant :\n    forall net h e,\n      refined_raft_intermediate_reachable net ->\n      In e (map snd (allEntries (fst (nwState net h)))) ->\n      eIndex e > 0.\n  Proof using aeigt0. \n    intros.\n    eapply allEntries_indices_gt_0_invariant; eauto.\n  Qed.\n\n  Instance rlmli : refined_log_matching_lemmas_interface.\n  Proof.\n    constructor.\n    - apply entries_contiguous_nw_invariant.\n    - apply entries_gt_0_nw_invariant.\n    - apply entries_sorted_nw_invariant.\n    - apply entries_gt_0_invariant.\n    - apply entries_contiguous_invariant.\n    - apply entries_sorted_invariant.\n    - apply entries_match_invariant.\n    - apply entries_match_nw_1_invariant.\n    - apply entries_match_nw_host_invariant.\n    - apply allEntries_gt_0_invariant.\n  Qed.\nEnd RefinedLogMatchingLemmas.", "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/RefinedLogMatchingLemmasProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438502, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.29731080480715566}}
{"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\n(** This module reasons about the precise types of variables in inert contexts. *)\n\nSet Implicit Arguments.\n\nRequire Import Coq.Program.Equality.\nRequire Import Definitions RecordAndInertTypes ConstrLangAlt ConstrTyping.\nRequire Import PreciseTyping.\n\nRequire Export PreciseTyping.\n\n(** * Precise Typing for Constraints\n\n    This is a replicate of original precise typing for the constraint-based type system.\n\n    The precise flow relation defined for the original system\n    simply retrieves type assignments from the environment.\n    So we simply reuse the existing definition for the constraint-based system.\n *)\n\n(** ** Precise typing for values *)\nReserved Notation \"e '⊢c!v' v ':' T\" (at level 40, v at level 59).\n\nInductive cty_val_p : (constr * ctx) -> val -> typ -> Prop :=\n\n(** [G, x: T ⊢ t^x: U^x]       #<br>#\n    [x fresh]                  #<br>#\n    [――――――――――――――――――――――――] #<br>#\n    [G ⊢! lambda(T)t: forall(T) U]     *)\n| cty_all_intro_p : 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!v val_lambda T t : typ_all T U\n\n(** [G, x: T^x ⊢ ds^x :: T^x]   #<br>#\n    [x fresh]                   #<br>#\n    [―――――――――――――――――――――――]   #<br>#\n    [G ⊢! nu(T)ds :: mu(T)]        *)\n| cty_new_intro_p : 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!v val_new T ds : typ_bnd T\n\nwhere \"e '⊢c!v' v ':' T\" := (cty_val_p e v T).\n\nHint Constructors cty_val_p.\n\n(** The precise type of a value is inert. *)\nLemma constr_precise_inert_typ : forall C G v T,\n    (C, G) ⊢c!v v : T ->\n    inert_typ T.\nProof.\n  introv Ht. inversions Ht; constructor; rename T0 into T.\n  constr_pick_fresh z. assert (Hz: z \\notin L) by auto.\n  match goal with\n  | [H: forall x, _ \\notin _ -> _,\n     Hz: ?z \\notin _ |- _] =>\n    specialize (H z Hz);\n      pose proof (cty_defs_record_type H);\n      assert (Hz': z \\notin fv_typ T) by auto;\n      apply* record_type_open\n  end.\nQed.\n\nLemma constr_precise_to_general_v: forall C G v T,\n    (C, G) ⊢c!v v : T ->\n    (C, G) ⊢c trm_val v: T.\nProof.\n  intros. induction H; intros; subst; eauto.\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/PreciseConstrTyping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.2973108048071556}}
{"text": "(********************************************************\n\n Internal Street fibrations\n\n In this file, we define the notion of Street fibration\n internal to a bicategory.\n\n 1. Definition of an internal Street fibration\n 2. Lemmas on cartesians\n 3. Street fibrations in locally groupoidal bicategories\n 4. Morphisms of internal Street fibrations\n 5. Cells of internal Street fibrations\n\n ********************************************************)\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Isos.\nRequire Import UniMath.CategoryTheory.DisplayedCats.StreetFibration.\nRequire Import UniMath.Bicategories.Core.Bicat.\nImport Bicat.Notations.\nRequire Import UniMath.Bicategories.Core.Invertible_2cells.\nRequire Import UniMath.Bicategories.Core.Univalence.\n\nLocal Open Scope cat.\n\n(**\n1. Definition of an internal Street fibration\n\nWe define internal Street fibrations using an unfolded definition.\nWe also show that it is equivalent to the usual definition of internal Street\nfibrations, which is formulated using hom-categories.\n *)\nSection InternalStreetFibration.\n  Context {B : bicat}\n          {e b : B}\n          (p : e --> b).\n\n  Definition is_cartesian_2cell_sfib\n             {x : B}\n             {f g : x --> e}\n             (γ : f ==> g)\n    : UU\n    := ∏ (h : x --> e)\n         (α : h ==> g)\n         (δp : h · p ==> f · p)\n         (q : α ▹ p = δp • (γ ▹ p)),\n       ∃! (δ : h ==> f),\n       δ ▹ p = δp\n       ×\n       δ • γ = α.\n\n  Definition is_cartesian_2cell_sfib_factor\n             {x : B}\n             {f g : x --> e}\n             {γ : f ==> g}\n             (Hγ : is_cartesian_2cell_sfib γ)\n             {h : x --> e}\n             (α : h ==> g)\n             (δp : h · p ==> f · p)\n             (q : α ▹ p = δp • (γ ▹ p))\n    : h ==> f\n    := pr11 (Hγ h α δp q).\n\n  Definition is_cartesian_2cell_sfib_factor_over\n             {x : B}\n             {f g : x --> e}\n             {γ : f ==> g}\n             (Hγ : is_cartesian_2cell_sfib γ)\n             {h : x --> e}\n             {α : h ==> g}\n             {δp : h · p ==> f · p}\n             (q : α ▹ p = δp • (γ ▹ p))\n    : (is_cartesian_2cell_sfib_factor Hγ _ _ q) ▹ p = δp\n    := pr121 (Hγ h α δp q).\n\n  Definition is_cartesian_2cell_sfib_factor_comm\n             {x : B}\n             {f g : x --> e}\n             {γ : f ==> g}\n             (Hγ : is_cartesian_2cell_sfib γ)\n             {h : x --> e}\n             {α : h ==> g}\n             {δp : h · p ==> f · p}\n             (q : α ▹ p = δp • (γ ▹ p))\n    : is_cartesian_2cell_sfib_factor Hγ _ _ q • γ = α\n    := pr221 (Hγ h α δp q).\n\n  Definition is_cartesian_2cell_sfib_factor_unique\n             {x : B}\n             {f g : x --> e}\n             {γ : f ==> g}\n             (Hγ : is_cartesian_2cell_sfib γ)\n             (h : x --> e)\n             (α : h ==> g)\n             (δp : h · p ==> f · p)\n             (q : α ▹ p = δp • (γ ▹ p))\n             (δ₁ δ₂ : h ==> f)\n             (pδ₁ : δ₁ ▹ p = δp)\n             (pδ₂ : δ₂ ▹ p = δp)\n             (δγ₁ : δ₁ • γ = α)\n             (δγ₂ : δ₂ • γ = α)\n    : δ₁ = δ₂.\n  Proof.\n    pose (proofirrelevance\n            _\n            (isapropifcontr (Hγ h α δp q))\n            (δ₁ ,, pδ₁ ,, δγ₁)\n            (δ₂ ,, pδ₂ ,, δγ₂))\n      as H.\n    exact (maponpaths pr1 H).\n  Qed.\n\n  Definition isaprop_is_cartesian_2cell_sfib\n             {x : B}\n             {f : x --> e}\n             {g : x --> e}\n             (γ : f ==> g)\n    : isaprop (is_cartesian_2cell_sfib γ).\n  Proof.\n    do 4 (use impred ; intro).\n    apply isapropiscontr.\n  Qed.\n\n  Definition internal_sfib_cleaving\n    : UU\n    := ∏ (x : B)\n         (f : x --> b)\n         (g : x --> e)\n         (α : f ==> g · p),\n       ∑ (h : x --> e)\n         (γ : h ==> g)\n         (β : invertible_2cell (h · p) f),\n       is_cartesian_2cell_sfib γ\n       ×\n       γ ▹ p = β • α.\n\n  Definition internal_sfib_cleaving_lift_mor\n             (H : internal_sfib_cleaving)\n             {x : B}\n             {f : x --> b}\n             {g : x --> e}\n             (α : f ==> g · p)\n    : x --> e\n    := pr1 (H _ _ _ α).\n\n  Definition internal_sfib_cleaving_lift_cell\n             (H : internal_sfib_cleaving)\n             {x : B}\n             {f : x --> b}\n             {g : x --> e}\n             (α : f ==> g · p)\n    : internal_sfib_cleaving_lift_mor H α ==> g\n    := pr12 (H _ _ _ α).\n\n  Definition internal_sfib_cleaving_com\n             (H : internal_sfib_cleaving)\n             {x : B}\n             {f : x --> b}\n             {g : x --> e}\n             (α : f ==> g · p)\n    : invertible_2cell (internal_sfib_cleaving_lift_mor H α · p) f\n    := pr122 (H _ _ _ α).\n\n  Definition internal_sfib_cleaving_is_cartesian\n             (H : internal_sfib_cleaving)\n             {x : B}\n             {f : x --> b}\n             {g : x --> e}\n             (α : f ==> g · p)\n    : is_cartesian_2cell_sfib (internal_sfib_cleaving_lift_cell H α)\n    := pr1 (pr222 (H _ _ _ α)).\n\n  Definition internal_sfib_cleaving_over\n             (H : internal_sfib_cleaving)\n             {x : B}\n             {f : x --> b}\n             {g : x --> e}\n             (α : f ==> g · p)\n    : internal_sfib_cleaving_lift_cell H α ▹ p\n      =\n      internal_sfib_cleaving_com H α • α\n    := pr2 (pr222 (H _ _ _ α)).\n\n  Definition lwhisker_is_cartesian\n    : UU\n    := ∏ (x y : B)\n         (h : y --> x)\n         (f g : x --> e)\n         (γ : f ==> g)\n         (Hγ : is_cartesian_2cell_sfib γ),\n       is_cartesian_2cell_sfib (h ◃ γ).\n\n  Definition internal_sfib\n    : UU\n    := internal_sfib_cleaving × lwhisker_is_cartesian.\n\n  Coercion internal_sfib_to_cleaving\n           (H : internal_sfib)\n    : internal_sfib_cleaving\n    := pr1 H.\n\n  Definition rep_internal_sfib\n    : UU\n    := (∏ (x : B),\n        street_fib (post_comp x p))\n       ×\n       (∏ (x y : B)\n          (h : y --> x),\n        preserves_cartesian\n          (post_comp x p)\n          (post_comp y p)\n          (pre_comp e h)).\n\n  Definition rep_internal_sfib_to_internal_sfib\n             (H : rep_internal_sfib)\n    : internal_sfib.\n  Proof.\n    split.\n    - intros x f g α.\n      pose (lift := pr1 H x g f α).\n      exact (pr1 lift\n             ,, pr112 lift\n             ,, z_iso_to_inv2cell (pr212 lift)\n             ,, pr222 lift\n             ,, pr122 lift).\n    - exact (pr2 H).\n  Defined.\n\n  Definition internal_sfib_to_rep_internal_sfib\n             (H : internal_sfib)\n    : rep_internal_sfib.\n  Proof.\n    split.\n    - intros x f g α.\n      pose (lift := pr1 H x g f α).\n      exact (pr1 lift\n             ,, (pr12 lift ,, inv2cell_to_z_iso (pr122 lift))\n             ,, pr2 (pr222 lift)\n             ,, pr1 (pr222 lift)).\n    - exact (pr2 H).\n  Defined.\n\n  Definition internal_sfib_to_rep_to_sfib\n             (H : rep_internal_sfib)\n    : internal_sfib_to_rep_internal_sfib\n        (rep_internal_sfib_to_internal_sfib H)\n      =\n      H.\n  Proof.\n    use pathsdirprod ; [ | apply idpath ].\n    use funextsec ; intro x.\n    use funextsec ; intro f.\n    use funextsec ; intro g.\n    use funextsec ; intro α.\n    simpl.\n    refine (maponpaths (λ z, _ ,, z) _).\n    use subtypePath.\n    {\n      intro.\n      use isapropdirprod.\n      - apply cellset_property.\n      - apply isaprop_is_cartesian_2cell_sfib.\n    }\n    simpl.\n    refine (maponpaths (λ z, _ ,, z) _).\n    use subtypePath.\n    {\n      intro. apply (isaprop_is_z_isomorphism(C:=hom x b)).\n    }\n    cbn.\n    apply idpath.\n  Qed.\n\n  Definition rep_sfib_to_internal_to_rep\n             (H : internal_sfib)\n    : rep_internal_sfib_to_internal_sfib\n        (internal_sfib_to_rep_internal_sfib H)\n      =\n      H.\n  Proof.\n    use pathsdirprod ; [ | apply idpath ].\n    use funextsec ; intro x.\n    use funextsec ; intro f.\n    use funextsec ; intro g.\n    use funextsec ; intro α.\n    simpl.\n    refine (maponpaths (λ z, _ ,, _ ,, z) _).\n    use subtypePath.\n    {\n      intro.\n      apply isapropdirprod.\n      - apply isaprop_is_cartesian_2cell_sfib.\n      - apply cellset_property.\n    }\n    use subtypePath.\n    {\n      intro ; apply isaprop_is_invertible_2cell.\n    }\n    cbn.\n    apply idpath.\n  Qed.\n\n  Definition rep_internal_sfib_weq_internal_sfib\n    : rep_internal_sfib ≃ internal_sfib.\n  Proof.\n    use make_weq.\n    - exact rep_internal_sfib_to_internal_sfib.\n    - use isweq_iso.\n      + exact internal_sfib_to_rep_internal_sfib.\n      + exact internal_sfib_to_rep_to_sfib.\n      + exact rep_sfib_to_internal_to_rep.\n  Defined.\n\n  Definition isaprop_rep_internal_sfib\n             (HB_2_1 : is_univalent_2_1 B)\n    : isaprop rep_internal_sfib.\n  Proof.\n    use isapropdirprod.\n    - use impred ; intro.\n      apply isaprop_street_fib.\n      apply is_univ_hom.\n      exact HB_2_1.\n    - do 7 (use impred ; intro).\n      apply isaprop_is_cartesian_sfib.\n  Qed.\n\n  Definition isaprop_internal_sfib\n             (HB_2_1 : is_univalent_2_1 B)\n    : isaprop internal_sfib.\n  Proof.\n    use (isofhlevelweqf _ rep_internal_sfib_weq_internal_sfib).\n    exact (isaprop_rep_internal_sfib HB_2_1).\n  Qed.\nEnd InternalStreetFibration.\n\n(**\n2. Lemmas on cartesians\n *)\nDefinition id_is_cartesian_2cell_sfib\n           {B : bicat}\n           {e b : B}\n           (p : e --> b)\n           {x : B}\n           (f : x --> e)\n  : is_cartesian_2cell_sfib p (id2 f).\nProof.\n  intros g α δp q.\n  use iscontraprop1.\n  - abstract\n      (use invproofirrelevance ;\n       intros φ₁ φ₂ ;\n       use subtypePath ;\n       [ intro ; apply isapropdirprod ; apply cellset_property | ] ;\n       exact (!(id2_right _) @ pr22 φ₁ @ !(pr22 φ₂) @ id2_right _)).\n  - refine (α ,, _ ,, _).\n    + abstract\n        (rewrite q ;\n         rewrite id2_rwhisker ;\n         apply id2_right).\n    + abstract\n        (apply id2_right).\nDefined.\n\nSection VcompIsCartesian.\n  Context {B : bicat}\n          {e b : B}\n          (p : e --> b)\n          {x : B}\n          {f g h : x --> e}\n          {α : f ==> g}\n          {β : g ==> h}\n          (Hα : is_cartesian_2cell_sfib p α)\n          (Hβ : is_cartesian_2cell_sfib p β).\n\n  Definition vcomp_is_cartesian_2cell_sfib_unique\n             {k : x --> e}\n             {ζ : k ==> h}\n             {δp : k · p ==> f · p}\n             (q : ζ ▹ p = δp • ((α • β) ▹ p))\n    : isaprop (∑ δ : k ==> f, δ ▹ p = δp × δ • (α • β) = ζ).\n  Proof.\n    use invproofirrelevance.\n    intros φ₁ φ₂.\n    use subtypePath ; [ intro ; apply isapropdirprod ; apply cellset_property | ].\n    rewrite <- rwhisker_vcomp in q.\n    rewrite !vassocr in q.\n    use (is_cartesian_2cell_sfib_factor_unique\n           _\n           Hα\n           _\n           (is_cartesian_2cell_sfib_factor _ Hβ ζ (δp • (α ▹ _)) q)\n           δp\n           (is_cartesian_2cell_sfib_factor_over _ _ _)\n           _ _\n           (pr12 φ₁)\n           (pr12 φ₂)) ;\n    use (is_cartesian_2cell_sfib_factor_unique\n           _\n           Hβ\n           _\n           ζ\n           (δp • (α ▹ _))\n           q\n           _\n           _\n           _\n           (is_cartesian_2cell_sfib_factor_over _ _ _)\n           _\n           (is_cartesian_2cell_sfib_factor_comm _ _ _)).\n    - rewrite <- rwhisker_vcomp.\n      rewrite (pr12 φ₁).\n      apply idpath.\n    - rewrite !vassocl.\n      apply (pr22 φ₁).\n    - rewrite <- rwhisker_vcomp.\n      rewrite (pr12 φ₂).\n      apply idpath.\n    - rewrite !vassocl.\n      apply (pr22 φ₂).\n  Qed.\n\n  Definition vcomp_is_cartesian_2cell_sfib\n    : is_cartesian_2cell_sfib p (α • β).\n  Proof.\n    intros k ζ δp q.\n    use iscontraprop1.\n    - apply vcomp_is_cartesian_2cell_sfib_unique.\n      exact q.\n    - simple refine (_ ,, _ ,, _).\n      + simple refine (is_cartesian_2cell_sfib_factor _ Hα _ δp _).\n        * simple refine (is_cartesian_2cell_sfib_factor _ Hβ ζ (δp • (α ▹ p)) _).\n          abstract\n            (rewrite !vassocl ;\n             rewrite q ;\n             rewrite <- rwhisker_vcomp ;\n             apply idpath).\n        * apply is_cartesian_2cell_sfib_factor_over.\n      + apply is_cartesian_2cell_sfib_factor_over.\n      + abstract\n          (simpl ;\n           rewrite !vassocr ;\n           rewrite !is_cartesian_2cell_sfib_factor_comm ;\n           apply idpath).\n  Defined.\nEnd VcompIsCartesian.\n\nDefinition invertible_is_cartesian_2cell_sfib\n           {B : bicat}\n           {e b : B}\n           (p : e --> b)\n           {x : B}\n           {f g : x --> e}\n           (α : f ==> g)\n           (Hα : is_invertible_2cell α)\n  : is_cartesian_2cell_sfib p α.\nProof.\n  intros h ζ δp q.\n  use iscontraprop1.\n  - abstract\n      (use invproofirrelevance ;\n       intros φ₁ φ₂ ;\n       use subtypePath ;\n         [ intro ; apply isapropdirprod ; apply cellset_property | ] ;\n       refine (!(id2_right _) @ _ @ id2_right _) ;\n       rewrite <- (vcomp_rinv Hα) ;\n       rewrite !vassocr ;\n       rewrite (pr22 φ₁), (pr22 φ₂) ;\n       apply idpath).\n  - refine (ζ • Hα^-1 ,, _ ,, _).\n    + abstract\n        (rewrite <- rwhisker_vcomp ;\n         use vcomp_move_R_Mp ; [ is_iso | ] ;\n         cbn ;\n         exact q).\n    + abstract\n        (rewrite !vassocl ;\n         rewrite vcomp_linv ;\n         apply id2_right).\nDefined.\n\nSection PostComposition.\n  Context {B : bicat}\n          {e b : B}\n          (p : e --> b)\n          {x : B}\n          {f g h : x --> e}\n          (α : f ==> g) {β : g ==> h}\n          {γ : f ==> h}\n          (Hβ : is_cartesian_2cell_sfib p β)\n          (Hγ : is_cartesian_2cell_sfib p γ)\n          (q : α • β = γ).\n\n  Section PostCompositionFactor.\n    Context {k : x --> e}\n            {δ : k ==> g}\n            (δp : k · p ==> f · p)\n            (r : δ ▹ p = δp • (α ▹ p)).\n\n    Definition is_cartesian_2cell_sfib_postcomp_factor\n      : k ==> f.\n    Proof.\n      use (is_cartesian_2cell_sfib_factor _ Hγ (δ • β) δp).\n      abstract\n        (rewrite <- rwhisker_vcomp ;\n         rewrite r ;\n         rewrite !vassocl ;\n         rewrite rwhisker_vcomp ;\n         rewrite q ;\n         apply idpath).\n    Defined.\n\n    Definition is_cartesian_2cell_sfib_postcomp_comm\n      : is_cartesian_2cell_sfib_postcomp_factor • α = δ.\n    Proof.\n      use (is_cartesian_2cell_sfib_factor_unique\n             _\n             Hβ\n             k\n             (δ • β)\n             (δ ▹ p)).\n      - rewrite rwhisker_vcomp.\n        apply idpath.\n      - rewrite <- rwhisker_vcomp.\n        etrans.\n        {\n          apply maponpaths_2.\n          apply is_cartesian_2cell_sfib_factor_over.\n        }\n        rewrite r.\n        apply idpath.\n      - apply idpath.\n      - rewrite !vassocl.\n        etrans.\n        {\n          apply maponpaths.\n          exact q.\n        }\n        apply is_cartesian_2cell_sfib_factor_comm.\n      - apply idpath.\n    Qed.\n\n    Definition is_cartesian_2cell_sfib_postcomp_unique\n      : isaprop (∑ φ, φ ▹ p = δp × φ • α = δ).\n    Proof.\n      use invproofirrelevance.\n      intros φ₁ φ₂.\n      use subtypePath.\n      {\n        intro.\n        apply isapropdirprod ; apply cellset_property.\n      }\n      use (is_cartesian_2cell_sfib_factor_unique\n             _\n             Hγ\n             _\n             (δ • β)\n             δp).\n      - rewrite <- rwhisker_vcomp.\n        rewrite r.\n        rewrite !vassocl.\n        rewrite rwhisker_vcomp.\n        rewrite q.\n        apply idpath.\n      - exact (pr12 φ₁).\n      - exact (pr12 φ₂).\n      - rewrite <- q.\n        rewrite !vassocr.\n        apply maponpaths_2.\n        exact (pr22 φ₁).\n      - rewrite <- q.\n        rewrite !vassocr.\n        apply maponpaths_2.\n        exact (pr22 φ₂).\n    Qed.\n  End PostCompositionFactor.\n\n  Definition is_cartesian_2cell_sfib_postcomp\n    : is_cartesian_2cell_sfib p α.\n  Proof.\n    intros k δ δp r.\n    use iscontraprop1.\n    - exact (is_cartesian_2cell_sfib_postcomp_unique δp r).\n    - simple refine (_ ,, _ ,, _).\n      + exact (is_cartesian_2cell_sfib_postcomp_factor δp r).\n      + apply is_cartesian_2cell_sfib_factor_over.\n      + exact (is_cartesian_2cell_sfib_postcomp_comm δp r).\n  Defined.\nEnd PostComposition.\n\nDefinition is_cartesian_eq\n           {B : bicat}\n           {e b : B}\n           {p : e --> b}\n           {x : B}\n           {f g : x --> e}\n           (α : f ==> g)\n           {β : f ==> g}\n           (q : α = β)\n           (Hα : is_cartesian_2cell_sfib p α)\n  : is_cartesian_2cell_sfib p β.\nProof.\n  intros h ζ δp r.\n  use iscontraprop1.\n  - abstract\n      (use invproofirrelevance ;\n       intros φ₁ φ₂ ;\n       use subtypePath ; [ intro ; apply isapropdirprod ; apply cellset_property | ] ;\n       induction q ;\n       exact (is_cartesian_2cell_sfib_factor_unique\n                _\n                Hα h ζ δp\n                r _ _\n                (pr12 φ₁)\n                (pr12 φ₂)\n                (pr22 φ₁)\n                (pr22 φ₂))).\n  - simple refine (_ ,, _).\n    + refine (is_cartesian_2cell_sfib_factor _ Hα ζ δp _).\n      abstract\n        (rewrite q, r ;\n         apply idpath).\n    + split.\n      * apply is_cartesian_2cell_sfib_factor_over.\n      * abstract\n          (refine (maponpaths (λ z, _ • z) (!q) @ _) ;\n           apply is_cartesian_2cell_sfib_factor_comm).\nDefined.\n\nDefinition is_cartesian_from_factor\n           {B : bicat}\n           {e b : B}\n           {p : e --> b}\n           {x : B}\n           {f₁ f₂ g : x --> e}\n           (α : f₁ ==> f₂)\n           (Hα : is_invertible_2cell α)\n           (β : f₁ ==> g)\n           (γ : f₂ ==> g)\n           (Hγ : is_cartesian_2cell_sfib p γ)\n           (q : β = α • γ)\n  : is_cartesian_2cell_sfib p β.\nProof.\n  use (is_cartesian_eq _ (!q)).\n  use vcomp_is_cartesian_2cell_sfib.\n  - apply invertible_is_cartesian_2cell_sfib.\n    exact Hα.\n  - exact Hγ.\nDefined.\n\nDefinition map_between_cartesians\n           {B : bicat}\n           {x e b : B}\n           {p : e --> b}\n           {g₀ g₁ g₂ : x --> e}\n           {α : g₀ ==> g₂}\n           (Hα : is_cartesian_2cell_sfib p α)\n           {β : g₁ ==> g₂}\n           (Hβ : is_cartesian_2cell_sfib p β)\n           (δ : invertible_2cell (g₀ · p) (g₁ · p))\n           (r : α ▹ p = δ • (β ▹ p))\n  : g₀ ==> g₁\n  := is_cartesian_2cell_sfib_factor _ Hβ α δ r.\n\nSection InvertibleBetweenCartesians.\n  Context {B : bicat}\n          {x e b : B}\n          {p : e --> b}\n          {g₀ g₁ g₂ : x --> e}\n          {α : g₀ ==> g₂}\n          (Hα : is_cartesian_2cell_sfib p α)\n          {β : g₁ ==> g₂}\n          (Hβ : is_cartesian_2cell_sfib p β)\n          (δ : invertible_2cell (g₀ · p) (g₁ · p))\n          (r : α ▹ p = δ • (β ▹ p)).\n\n  Let φ : g₀ ==> g₁ := map_between_cartesians Hα Hβ δ r.\n\n  Local Lemma invertible_between_cartesians_help\n    : β ▹ p = δ^-1 • (α ▹ p).\n  Proof.\n    cbn.\n    use vcomp_move_L_pM ; is_iso ; cbn.\n    exact (!r).\n  Qed.\n\n  Let ψ : g₁ ==> g₀\n    := map_between_cartesians\n         Hβ Hα\n         (inv_of_invertible_2cell δ)\n         invertible_between_cartesians_help.\n\n  Local Lemma invertible_between_cartesians_inv₁\n    : φ • ψ = id₂ _.\n  Proof.\n    use (is_cartesian_2cell_sfib_factor_unique _ Hα _ α (id2 _)).\n    - rewrite id2_left.\n      apply idpath.\n    - unfold φ, ψ, map_between_cartesians.\n      rewrite <- rwhisker_vcomp.\n      rewrite !is_cartesian_2cell_sfib_factor_over.\n      apply (vcomp_rinv δ).\n    - apply id2_rwhisker.\n    - unfold φ, ψ, map_between_cartesians.\n      rewrite !vassocl.\n      rewrite !is_cartesian_2cell_sfib_factor_comm.\n      apply idpath.\n    - apply id2_left.\n  Qed.\n\n  Local Lemma invertible_between_cartesians_inv₂\n    : ψ • φ = id₂ _.\n  Proof.\n    use (is_cartesian_2cell_sfib_factor_unique _ Hβ _ β (id2 _)).\n    - rewrite id2_left.\n      apply idpath.\n    - unfold φ, ψ, map_between_cartesians.\n      rewrite <- rwhisker_vcomp.\n      rewrite !is_cartesian_2cell_sfib_factor_over.\n      apply (vcomp_linv δ).\n    - apply id2_rwhisker.\n    - unfold φ, ψ, map_between_cartesians.\n      rewrite !vassocl.\n      rewrite !is_cartesian_2cell_sfib_factor_comm.\n      apply idpath.\n    - apply id2_left.\n  Qed.\n\n  Definition invertible_between_cartesians\n    : invertible_2cell g₀ g₁.\n  Proof.\n    use make_invertible_2cell.\n    - exact φ.\n    - use make_is_invertible_2cell.\n      + exact ψ.\n      + exact invertible_between_cartesians_inv₁.\n      + exact invertible_between_cartesians_inv₂.\n  Defined.\nEnd InvertibleBetweenCartesians.\n\n(**\n 3. Street fibrations in locally groupoidal bicategories\n *)\nDefinition locally_grpd_cartesian\n           {B : bicat}\n           (HB : locally_groupoid B)\n           {e b : B}\n           (p : e --> b)\n           {x : B}\n           {f g : x --> e}\n           (γ : f ==> g)\n  : is_cartesian_2cell_sfib p γ.\nProof.\n  intros h α δp q.\n  pose (α_iso := make_invertible_2cell (HB _ _ _ _ α)).\n  pose (γ_iso := make_invertible_2cell (HB _ _ _ _ γ)).\n  use iscontraprop1.\n  - abstract\n      (use invproofirrelevance ;\n       intros φ₁ φ₂ ;\n       use subtypePath ;\n       [ intro ; apply isapropdirprod ; apply cellset_property | ] ;\n       use (vcomp_rcancel _ γ_iso) ;\n       cbn ;\n       exact (pr22 φ₁ @ !(pr22 φ₂))).\n  - refine (α • γ_iso^-1 ,, _ ,, _).\n    + abstract\n        (rewrite <- rwhisker_vcomp ;\n         use vcomp_move_R_Mp ; [ is_iso | ] ;\n         cbn ;\n         rewrite q ;\n         apply idpath).\n    + abstract\n        (rewrite !vassocl ;\n         rewrite vcomp_linv ;\n         apply id2_right).\nDefined.\n\nDefinition locally_grpd_internal_sfib\n           {B : bicat}\n           (HB : locally_groupoid B)\n           {e b : B}\n           (p : e --> b)\n  : internal_sfib p.\nProof.\n  split.\n  - intros x f g α.\n    refine (g\n            ,,\n            id2 _\n            ,,\n            inv_of_invertible_2cell (make_invertible_2cell (HB _ _ _ _ α))\n            ,,\n            locally_grpd_cartesian HB _ _\n            ,,\n            _).\n    abstract\n      (cbn ;\n       rewrite id2_rwhisker ;\n       rewrite vcomp_linv ;\n       apply idpath).\n  - intro ; intros.\n    apply (locally_grpd_cartesian HB).\nDefined.\n\n(**\n 4. Morphisms of internal Street fibrations\n *)\nDefinition mor_preserves_cartesian\n           {B : bicat}\n           {e₁ b₁ : B}\n           (p₁ : e₁ --> b₁)\n           {e₂ b₂ : B}\n           (p₂ : e₂ --> b₂)\n           (fe : e₁ --> e₂)\n  : UU\n  := ∏ (x : B)\n       (f g : x --> e₁)\n       (γ : f ==> g)\n       (Hγ : is_cartesian_2cell_sfib p₁ γ),\n     is_cartesian_2cell_sfib p₂ (γ ▹ fe).\n\nDefinition id_mor_preserves_cartesian\n           {B : bicat}\n           {e b : B}\n           (p : e --> b)\n  : mor_preserves_cartesian p p (id₁ e).\nProof.\n  intros ? ? ? ? H.\n  assert (γ ▹ id₁ e = runitor _ • γ • rinvunitor _) as q.\n  {\n    use vcomp_move_L_Mp ; [ is_iso | ].\n    cbn.\n    rewrite !vcomp_runitor.\n    apply idpath.\n  }\n  rewrite q.\n  use vcomp_is_cartesian_2cell_sfib.\n  - use vcomp_is_cartesian_2cell_sfib.\n    + use invertible_is_cartesian_2cell_sfib.\n      is_iso.\n    + exact H.\n  - use invertible_is_cartesian_2cell_sfib.\n    is_iso.\nQed.\n\nDefinition comp_preserves_cartesian\n           {B : bicat}\n           {e₁ b₁ e₂ b₂ e₃ b₃ : B}\n           {p₁ : e₁ --> b₁}\n           {p₂ : e₂ --> b₂}\n           {p₃ : e₃ --> b₃}\n           {fe₁ : e₁ --> e₂}\n           {fe₂ : e₂ --> e₃}\n           (H₁ : mor_preserves_cartesian p₁ p₂ fe₁)\n           (H₂ : mor_preserves_cartesian p₂ p₃ fe₂)\n  : mor_preserves_cartesian p₁ p₃ (fe₁ · fe₂).\nProof.\n  intros x f g γ Hγ.\n  specialize (H₁ x _ _ γ Hγ).\n  specialize (H₂ x _ _ _ H₁).\n  assert (γ ▹ fe₁ · fe₂\n          =\n          lassociator _ _ _\n          • ((γ ▹ fe₁) ▹ fe₂)\n          • rassociator _ _ _)\n    as q.\n  {\n    use vcomp_move_L_Mp ; [ is_iso | ] ; cbn.\n    rewrite rwhisker_rwhisker.\n    apply idpath.\n  }\n  rewrite q.\n  use vcomp_is_cartesian_2cell_sfib.\n  - use vcomp_is_cartesian_2cell_sfib.\n    + use invertible_is_cartesian_2cell_sfib.\n      is_iso.\n    + exact H₂.\n  - use invertible_is_cartesian_2cell_sfib.\n    is_iso.\nQed.\n\nSection Invertible2CellCartesian.\n  Context {B : bicat}\n          {x e b : B}\n          {p p' : e --> b}\n          (α : invertible_2cell p p')\n          {f g : x --> e}\n          {β : f ==> g}\n          (Hβ : is_cartesian_2cell_sfib p β)\n          {k : x --> e}\n          {ζ : k ==> g}\n          (δp : k · p' ==> f · p')\n          (q : ζ ▹ p' = δp • (β ▹ p')).\n\n  Let δp' : k · p ==> f · p\n    := ((k ◃ α) • δp • (f ◃ α^-1)).\n\n  Lemma help_eq\n    : ζ ▹ p\n      =\n      (((k ◃ α) • δp) • (f ◃ α ^-1)) • (β ▹ p).\n  Proof.\n    rewrite !vassocl.\n    use vcomp_move_L_pM.\n    {\n      is_iso.\n      apply property_from_invertible_2cell.\n    }\n    cbn.\n    rewrite <- vcomp_whisker.\n    rewrite q.\n    rewrite !vassocl.\n    rewrite <- vcomp_whisker.\n    apply idpath.\n  Qed.\n\n  Definition is_cartesian_2cell_sfib_factor_inv2cell_unique\n    : isaprop (∑ (δ : k ==> f), δ ▹ p' = δp × δ • β = ζ).\n  Proof.\n    use invproofirrelevance.\n    intros φ₁ φ₂.\n    use subtypePath ; [ intro ; apply isapropdirprod ; apply cellset_property | ].\n    use (is_cartesian_2cell_sfib_factor_unique\n           _\n           Hβ\n           k ζ\n           ((k ◃ α) • δp • (f ◃ α^-1))\n           help_eq).\n    - use vcomp_move_L_Mp ; [ is_iso | ].\n      cbn.\n      rewrite vcomp_whisker.\n      apply maponpaths.\n      exact (pr12 φ₁).\n    - use vcomp_move_L_Mp ; [ is_iso | ].\n      cbn.\n      rewrite vcomp_whisker.\n      apply maponpaths.\n      exact (pr12 φ₂).\n    - exact (pr22 φ₁).\n    - exact (pr22 φ₂).\n  Qed.\n\n  Definition is_cartesian_2cell_sfib_factor_inv2cell\n    : k ==> f\n    := is_cartesian_2cell_sfib_factor\n         _ Hβ\n         ζ\n         ((k ◃ α) • δp • (f ◃ α^-1))\n         help_eq.\n\n  Definition is_cartesian_2cell_sfib_factor_inv2cell_over\n    : is_cartesian_2cell_sfib_factor_inv2cell ▹ p' = δp.\n  Proof.\n    use (vcomp_lcancel (_ ◃ α)).\n    {\n      is_iso.\n      apply property_from_invertible_2cell.\n    }\n    rewrite <- vcomp_whisker.\n    unfold is_cartesian_2cell_sfib_factor_inv2cell.\n    rewrite is_cartesian_2cell_sfib_factor_over.\n    rewrite !vassocl.\n    rewrite lwhisker_vcomp.\n    rewrite vcomp_linv.\n    rewrite lwhisker_id2.\n    rewrite id2_right.\n    apply idpath.\n  Qed.\nEnd Invertible2CellCartesian.\n\nDefinition is_cartesian_2cell_sfib_inv2cell\n           {B : bicat}\n           {x e b : B}\n           {p p' : e --> b}\n           (α : invertible_2cell p p')\n           {f g : x --> e}\n           {β : f ==> g}\n           (Hβ : is_cartesian_2cell_sfib p β)\n  : is_cartesian_2cell_sfib p' β.\nProof.\n  intros k ζ δp q.\n  use iscontraprop1.\n  - exact (is_cartesian_2cell_sfib_factor_inv2cell_unique α Hβ δp q).\n  - simple refine (_ ,, _ ,, _).\n    + exact (is_cartesian_2cell_sfib_factor_inv2cell α Hβ δp q).\n    + exact (is_cartesian_2cell_sfib_factor_inv2cell_over α Hβ δp q).\n    + apply is_cartesian_2cell_sfib_factor_comm.\nDefined.\n\nDefinition invertible_2cell_mor_between_preserves_cartesian\n           {B : bicat}\n           {e₁ e₂ b₁ b₂ : B}\n           {p₁ : e₁ --> b₁}\n           {p₂ : e₂ --> b₂}\n           {fe fe' : e₁ --> e₂}\n           (α : invertible_2cell fe fe')\n           (H : mor_preserves_cartesian p₁ p₂ fe)\n  : mor_preserves_cartesian p₁ p₂ fe'.\nProof.\n  intros x f g γ Hγ.\n  assert (γ ▹ fe' • (_ ◃ α^-1) = (f ◃ α^-1) • (γ ▹ fe)) as p.\n  {\n    rewrite vcomp_whisker.\n    apply idpath.\n  }\n  use (is_cartesian_2cell_sfib_postcomp _ _ _ _ p).\n  - use invertible_is_cartesian_2cell_sfib.\n    is_iso.\n  - use vcomp_is_cartesian_2cell_sfib.\n    + use invertible_is_cartesian_2cell_sfib.\n      is_iso.\n    + exact (H x f g γ Hγ).\nDefined.\n\nDefinition invertible_2cell_between_preserves_cartesian\n           {B : bicat}\n           {e₁ e₂ b₁ b₂ : B}\n           {p₁ p₁' : e₁ --> b₁}\n           {p₂ p₂' : e₂ --> b₂}\n           {fe fe' : e₁ --> e₂}\n           (α : invertible_2cell p₁ p₁')\n           (β : invertible_2cell p₂ p₂')\n           (γ : invertible_2cell fe fe')\n           (H : mor_preserves_cartesian p₁ p₂ fe)\n  : mor_preserves_cartesian p₁' p₂' fe'.\nProof.\n  intros w h₁ h₂ ζ Hζ.\n  use (is_cartesian_2cell_sfib_inv2cell β).\n  use (invertible_2cell_mor_between_preserves_cartesian γ H).\n  use (is_cartesian_2cell_sfib_inv2cell (inv_of_invertible_2cell α)).\n  exact Hζ.\nDefined.\n\nDefinition locally_grpd_preserves_cartesian\n           {B : bicat}\n           (HB : locally_groupoid B)\n           {e₁ b₁ e₂ b₂ : B}\n           (p₁ : e₁ --> b₁)\n           (p₂ : e₂ --> b₂)\n           (fe : e₁ --> e₂)\n  : mor_preserves_cartesian p₁ p₂ fe.\nProof.\n  intro ; intros.\n  apply (locally_grpd_cartesian HB).\nDefined.\n\nDefinition isaprop_mor_preserves_cartesian\n           {B : bicat}\n           {e₁ b₁ : B}\n           (p₁ : e₁ --> b₁)\n           {e₂ b₂ : B}\n           (p₂ : e₂ --> b₂)\n           (fe : e₁ --> e₂)\n  : isaprop (mor_preserves_cartesian p₁ p₂ fe).\nProof.\n  do 5 (use impred ; intro).\n  exact (isaprop_is_cartesian_2cell_sfib _ _).\nQed.\n\nDefinition mor_of_internal_sfib_over\n           {B : bicat}\n           {e₁ b₁ : B}\n           (p₁ : e₁ --> b₁)\n           {e₂ b₂ : B}\n           (p₂ : e₂ --> b₂)\n           (fb : b₁ --> b₂)\n  : UU\n  := ∑ (fe : e₁ --> e₂),\n     mor_preserves_cartesian p₁ p₂ fe\n     ×\n     invertible_2cell (p₁ · fb) (fe · p₂).\n\nDefinition make_mor_of_internal_sfib_over\n           {B : bicat}\n           {e₁ b₁ : B}\n           {p₁ : e₁ --> b₁}\n           {e₂ b₂ : B}\n           {p₂ : e₂ --> b₂}\n           {fb : b₁ --> b₂}\n           (fe : e₁ --> e₂)\n           (fc : mor_preserves_cartesian p₁ p₂ fe)\n           (f_com : invertible_2cell (p₁ · fb) (fe · p₂))\n  : mor_of_internal_sfib_over p₁ p₂ fb\n  := (fe ,, fc ,, f_com).\n\nCoercion mor_of_internal_sfib_over_to_mor\n         {B : bicat}\n         {e₁ b₁ : B}\n         {p₁ : e₁ --> b₁}\n         {e₂ b₂ : B}\n         {p₂ : e₂ --> b₂}\n         {fb : b₁ --> b₂}\n         (fe : mor_of_internal_sfib_over p₁ p₂ fb)\n  : e₁ --> e₂\n  := pr1 fe.\n\nDefinition mor_of_internal_sfib_over_preserves\n           {B : bicat}\n           {e₁ b₁ : B}\n           {p₁ : e₁ --> b₁}\n           {e₂ b₂ : B}\n           {p₂ : e₂ --> b₂}\n           {fb : b₁ --> b₂}\n           (fe : mor_of_internal_sfib_over p₁ p₂ fb)\n  : mor_preserves_cartesian p₁ p₂ fe\n  := pr12 fe.\n\nDefinition mor_of_internal_sfib_over_com\n           {B : bicat}\n           {e₁ b₁ : B}\n           {p₁ : e₁ --> b₁}\n           {e₂ b₂ : B}\n           {p₂ : e₂ --> b₂}\n           {fb : b₁ --> b₂}\n           (fe : mor_of_internal_sfib_over p₁ p₂ fb)\n  : invertible_2cell (p₁ · fb) (fe · p₂)\n  := pr22 fe.\n\nDefinition id_mor_of_internal_sfib_over\n           {B : bicat}\n           {e b : B}\n           (p : e --> b)\n  : mor_of_internal_sfib_over p p (id₁ _).\nProof.\n  use make_mor_of_internal_sfib_over.\n  - exact (id₁ e).\n  - apply id_mor_preserves_cartesian.\n  - use make_invertible_2cell.\n    + refine (runitor _ • linvunitor _).\n    + is_iso.\nDefined.\n\nDefinition comp_mor_of_internal_sfib_over\n           {B : bicat}\n           {e₁ e₂ e₃ b₁ b₂ b₃ : B}\n           {fb₁ : b₁ --> b₂}\n           {fb₂ : b₂ --> b₃}\n           {p₁ : e₁ --> b₁}\n           {p₂ : e₂ --> b₂}\n           {p₃ : e₃ --> b₃}\n           (fe₁ : mor_of_internal_sfib_over p₁ p₂ fb₁)\n           (fe₂ : mor_of_internal_sfib_over p₂ p₃ fb₂)\n  : mor_of_internal_sfib_over p₁ p₃ (fb₁ · fb₂).\nProof.\n  use make_mor_of_internal_sfib_over.\n  - exact (fe₁ · fe₂).\n  - exact (comp_preserves_cartesian\n             (mor_of_internal_sfib_over_preserves fe₁)\n             (mor_of_internal_sfib_over_preserves fe₂)).\n  - use make_invertible_2cell.\n    + exact (lassociator _ _ _\n             • (mor_of_internal_sfib_over_com fe₁ ▹ _)\n             • rassociator _ _ _\n             • (_ ◃ mor_of_internal_sfib_over_com fe₂)\n             • lassociator _ _ _).\n    + is_iso.\n      * apply property_from_invertible_2cell.\n      * apply property_from_invertible_2cell.\nDefined.\n\n(**\n 5. Cells of internal Street fibrations\n *)\nDefinition cell_of_internal_sfib_over_homot\n           {B : bicat}\n           {b₁ b₂ e₁ e₂ : B}\n           {fb gb : b₁ --> b₂}\n           (γ : fb ==> gb)\n           {p₁ : e₁ --> b₁}\n           {p₂ : e₂ --> b₂}\n           {fe : mor_of_internal_sfib_over p₁ p₂ fb}\n           {ge : mor_of_internal_sfib_over p₁ p₂ gb}\n           (γe : fe ==> ge)\n  : UU\n  := mor_of_internal_sfib_over_com fe • (γe ▹ _)\n     =\n     (_ ◃ γ) • mor_of_internal_sfib_over_com ge.\n\n\nDefinition cell_of_internal_sfib_over\n           {B : bicat}\n           {b₁ b₂ e₁ e₂ : B}\n           {fb gb : b₁ --> b₂}\n           (γ : fb ==> gb)\n           {p₁ : e₁ --> b₁}\n           {p₂ : e₂ --> b₂}\n           (fe : mor_of_internal_sfib_over p₁ p₂ fb)\n           (ge : mor_of_internal_sfib_over p₁ p₂ gb)\n  : UU\n  := ∑ (γe : fe ==> ge), cell_of_internal_sfib_over_homot γ γe.\n\nDefinition make_cell_of_internal_sfib_over\n           {B : bicat}\n           {b₁ b₂ e₁ e₂ : B}\n           {fb gb : b₁ --> b₂}\n           {γ : fb ==> gb}\n           {p₁ : e₁ --> b₁}\n           {p₂ : e₂ --> b₂}\n           {fe : mor_of_internal_sfib_over p₁ p₂ fb}\n           {ge : mor_of_internal_sfib_over p₁ p₂ gb}\n           (γe : fe ==> ge)\n           (p : cell_of_internal_sfib_over_homot γ γe)\n  : cell_of_internal_sfib_over γ fe ge\n  := (γe ,, p).\n\nCoercion cell_of_cell_of_internal_sfib_over\n         {B : bicat}\n         {b₁ b₂ e₁ e₂ : B}\n         {fb gb : b₁ --> b₂}\n         {γ : fb ==> gb}\n         {p₁ : e₁ --> b₁}\n         {p₂ : e₂ --> b₂}\n         {fe : mor_of_internal_sfib_over p₁ p₂ fb}\n         {ge : mor_of_internal_sfib_over p₁ p₂ gb}\n         (γe : cell_of_internal_sfib_over γ fe ge)\n  : fe ==> ge\n  := pr1 γe.\n\nDefinition cell_of_internal_sfib_over_eq\n           {B : bicat}\n           {b₁ b₂ e₁ e₂ : B}\n           {fb gb : b₁ --> b₂}\n           {γ : fb ==> gb}\n           {p₁ : e₁ --> b₁}\n           {p₂ : e₂ --> b₂}\n           {fe : mor_of_internal_sfib_over p₁ p₂ fb}\n           {ge : mor_of_internal_sfib_over p₁ p₂ gb}\n           (γe : cell_of_internal_sfib_over γ fe ge)\n  : mor_of_internal_sfib_over_com fe • (γe ▹ _)\n     =\n     (_ ◃ γ) • mor_of_internal_sfib_over_com ge\n  := pr2 γe.\n\nDefinition eq_cell_of_internal_sfib_over\n           {B : bicat}\n           {b₁ b₂ e₁ e₂ : B}\n           {fb gb : b₁ --> b₂}\n           {γ : fb ==> gb}\n           {p₁ : e₁ --> b₁}\n           {p₂ : e₂ --> b₂}\n           {fe : mor_of_internal_sfib_over p₁ p₂ fb}\n           {ge : mor_of_internal_sfib_over p₁ p₂ gb}\n           (γe₁ γe₂ : cell_of_internal_sfib_over γ fe ge)\n           (p : pr1 γe₁ = γe₂)\n  : γe₁ = γe₂.\nProof.\n  use subtypePath.\n  {\n    intro.\n    apply cellset_property.\n  }\n  exact p.\nQed.\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/Morphisms/InternalStreetFibration.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.29731079805152366}}
{"text": "From stdpp Require Export binders strings.\nFrom stdpp Require Import fin_maps gmap.\nFrom iris.algebra Require Export ofe.\nFrom iris.program_logic Require Export language ectx_language ectxi_language.\nFrom iris.heap_lang Require Export locations.\nFrom iris.prelude Require Import options.\n\n\n(** cs_lambda.  \n\nA fairly simple language used for common Iris examples.\n\nNoteworthy design choices:\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- Even after deallocating a location, the heap remembers that these locations\n  were previously allocated and makes sure they do not get reused. This is\n  necessary to ensure soundness of the [meta] feature provided by [gen_heap].\n  Also, unlike in languages like C, allocated and deallocated \"blocks\" do not\n  have to match up: you can allocate a large array of locations and then\n  deallocate a hole out of it in the middle.\n*)\n\nDelimit Scope expr_scope with E.\nDelimit Scope val_scope with V.\n\nModule cs_lambda.\n\n(** Expressions and vals. *)\nDefinition proph_id := positive.\n\n(** We have a notion of \"poison\" as a variant of unit that may not be compared\nwith anything. This is useful for erasure proofs: if we erased things to unit,\n[<erased> == unit] would evaluate to true after erasure, changing program\nbehavior. So we erase to the poison value instead, making sure that no legal\ncomparisons could be affected. *)\n\nInductive base_lit : Set :=\n  | LitInt (n : Z) \n  | LitBool (b : bool) \n  | LitUnit.\nInductive un_op : Set :=\n  | NegOp | MinusUnOp.\nInductive bin_op : Set :=\n  | PlusOp\n  | AndOp\n  | EqOp.\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  (* a ref pair is our equivalent of a ref struct, as a struct is just a product type with named fields, otherwise it's just a struct? *)\n  | Pair (ref: bool) (e1 e2 : expr)\n  | Fst (e : expr)\n  | Snd (e : expr)\n  | Ref (e: expr)\n  | Class (e1 e2 : expr)\nwith val :=\n  | LitV (l : base_lit)\n  | RecV (f x : binder) (e : expr)\n  | PairV (ref : bool) (v1 v2 : val).\n\nBind Scope expr_scope with expr.\nBind Scope val_scope with val.\n\nInductive type : Type :=\n  | TInt   : type\n  | TBool  : type\n  | TPair  : bool -> type -> type -> type\n  | TClass : type -> type -> type\n  | TRef   : type -> type\n  | TArrow : type -> type -> type\n  | TUnit  : type.\n\n(* \nfield_valid property holds if type can be used as a field in \n  - struct/class (when bool is false) \n  - ref struct (when bool is true) \n*)\nInductive field_valid : type -> bool -> Prop :=\n  | FVInt   : forall (b : bool), field_valid TInt b\n  | FVUnit  : forall (b : bool), field_valid TUnit b\n  (* functions aren't really special *)\n  | FVArrow τ1 τ2: forall (b : bool), field_valid (TArrow τ1 τ2) b\n  (* non-ref pairs are fine for any type of pair, just check for nested stuff *)\n  | FVPair τ1 τ2 : forall (b : bool),\n      field_valid τ1 false -> field_valid τ2 false -> field_valid (TPair false τ1 τ2) b\n  (* provided our args are fine for a ref pair, we can have a ref pair as a field *)\n  | FVPairR τ1 τ2:\n      field_valid τ1 true -> field_valid τ2 true -> field_valid (TPair true τ1 τ2) true.\n\nReserved Notation \"Γ ⊢ e : τ\" (at level 74, e, τ at next level).\n\nInductive has_type (Γ: gmap binder type) : expr -> type -> Prop :=\n  | IntT n : \n      Γ ⊢ (Val (LitV (LitInt n))) : TInt\n  | BoolT b :\n      Γ ⊢ (Val (LitV (LitBool b))) : TBool\n  | UnitT :\n      Γ ⊢ (Val (LitV (LitUnit))) : TUnit\n  | RecVT f x e τ1 τ2 : \n      (* if giving x the type τ1 in the context resolves the expression, then the function is valid *)\n      (<[ x := τ1 ]> Γ) ⊢ e : τ2 ->\n      Γ ⊢ (Val (RecV f x e)) : TArrow τ1 τ2\n  | PairVT ref v1 v2 τ1 τ2 : \n      Γ ⊢ Val v1 : τ1 -> \n      Γ ⊢ Val v2 : τ2 ->\n      field_valid τ1 ref -> \n      field_valid τ2 ref ->\n      Γ ⊢ (Val (PairV ref v1 v2)) : TPair ref τ1 τ2\n  | VarT x τ1 :\n      (* x is type string but context wants binder *)\n      (lookup (BNamed x) Γ) = Some τ1 ->\n      Γ ⊢ (Var x) : τ1\n  | RecT f x e τ1 τ2 : \n      (* if giving x the type τ1 in the context resolves the expression, then the function is valid *)\n      (<[ x := τ1 ]> Γ) ⊢ e : τ2 ->\n      Γ ⊢ Rec f x e : TArrow τ1 τ2\n  | AppT e1 e2 τ1 τ2 :\n      Γ ⊢ e1 : (TArrow τ1 τ2) ->\n      Γ ⊢ e2 : τ1 -> \n      Γ ⊢ (App e1 e2) : τ2\n  | NegT e1 :\n      Γ ⊢ e1 : TBool ->\n      Γ ⊢ (UnOp NegOp e1) : TBool\n  | MinusT e1 :\n      Γ ⊢ e1 : TInt ->\n      Γ ⊢ (UnOp MinusUnOp e1) : TInt\n  | PlusT e1 e2 :\n      Γ ⊢ e1 : TInt ->\n      Γ ⊢ e2 : TInt -> \n      Γ ⊢ (BinOp PlusOp e1 e2) : TInt\n  | AndT e1 e2 :\n      Γ ⊢ e1 : TBool ->\n      Γ ⊢ e2 : TBool -> \n      Γ ⊢ (BinOp AndOp e1 e2) : TBool\n  | EqT e1 e2 :\n      Γ ⊢ e1 : TBool ->\n      Γ ⊢ e2 : TBool -> \n      Γ ⊢ (BinOp EqOp e1 e2) : TBool\n  | IfT e1 e2 e3 τ1 : \n      Γ ⊢ e1 : TBool ->\n      Γ ⊢ e2 : τ1 -> \n      Γ ⊢ e3 : τ1 -> \n      Γ ⊢ (If e1 e2 e3) : τ1    \n  | PairT ref e1 e2 τ1 τ2 : \n      Γ ⊢ e1 : τ1 -> \n      Γ ⊢ e2 : τ2 ->\n      field_valid τ1 ref -> \n      field_valid τ2 ref ->\n      Γ ⊢ (Pair ref e1 e2) : TPair ref τ1 τ2\n  | FstT e1 ref τ1 τ2 :\n      Γ ⊢ e1 : TPair ref τ1 τ2 ->\n      Γ ⊢ (Fst e1) : τ1  \n  | SndT e1 ref τ1 τ2 :\n      Γ ⊢ e1 : TPair ref τ1 τ2 ->\n      Γ ⊢ (Snd e1) : τ2\n  | RefT x τ1 :\n      Γ ⊢ (Var x) : τ1 -> \n      Γ ⊢ (Ref (Var x)) : TRef τ1\n  | ClassT e1 e2 τ1 τ2 : \n      Γ ⊢ e1 : τ1 -> \n      Γ ⊢ e2 : τ2 -> \n      field_valid τ1 false -> \n      field_valid τ2 false -> \n      Γ ⊢ (Class e1 e2) : TClass τ1 τ2\n(* e has type tau *)\nwhere \"Γ ⊢ e : τ\" := (has_type Γ e τ).\n\n(*\n\n\n(** An observation associates a prophecy variable (identifier) to a pair of\nvalues. The first value is the one that was returned by the (atomic) operation\nduring which the prophecy resolution happened (typically, a boolean when the\nwrapped operation is a CmpXchg). The second value is the one that the prophecy\nvariable was actually resolved to. *)\nDefinition observation : Set := proph_id * (val * 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 LitPoison, InjLV (LitV LitPoison), InjRV (LitV LitPoison),\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 lit_is_unboxed (l: base_lit) : Prop :=\n  match l with\n  (** Disallow comparing (erased) prophecies with (erased) prophecies, by\n  considering them boxed. *)\n  | LitInt _ | LitBool _  | LitLoc _ | LitUnit => True\n  end.\n\nDefinition val_is_unboxed (v : val) : Prop :=\n  match v with\n  | LitV l         => lit_is_unboxed l\n  | _              => False\n  end.\n\nDefinition expr_ref (e : expr) : Prop :=\n  match e with \n  | Ref _  => True\n  | _      => False\n  end.\n\nGlobal Instance lit_is_unboxed_dec l : Decision (lit_is_unboxed l).\nProof. \n  destruct l;\n  simpl;\n  exact (decide _).\nDefined.\n\nGlobal Instance val_is_unboxed_dec v : Decision (val_is_unboxed v).\nProof. \n  destruct v; \n  simpl; \n  exact (decide _). \nDefined.\n\nGlobal Instance expr_ref_dec v : Decision (expr_is_ref v).\nProof.\n  destruct v;\n  simpl;\n  exact (decide _).\nDefined.\n\n(** We just compare the word-sized representation of two values, without looking\ninto 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_compare_safe (vl v1 : val) : Prop :=\n  val_is_unboxed vl ∨ val_is_unboxed v1.\nGlobal Arguments vals_compare_safe !_ !_ /.\n\n(** The state: heaps of [option val]s, with [None] representing deallocated locations. *)\nRecord state : Type := {\n  heap: gmap loc (option val);\n  used_proph_id: gset proph_id;\n}.\n\n(** Equality and other typeclass stuff *)\nLemma to_of_val v : to_val (of_val v) = Some v.\nProof. \n  by destruct v. \nQed.\n\nLemma of_to_val e v : to_val e = Some v → of_val v = e.\nProof. \n  destruct e=>//=. \n  by intros [= <-]. \nQed.\n\nGlobal Instance of_val_inj : Inj (=) (=) of_val.\nProof. \n  intros ??. \n  congruence. \nQed.\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'         => 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' => cast_if_and3 (decide (o = o')) (decide (e1 = e1')) (decide (e2 = e2'))\n     | If e0 e1 e2, If e0' e1' e2'     => cast_if_and3 (decide (e0 = e0')) (decide (e1 = e1')) (decide (e2 = e2'))\n     | Pair r e1 e2, Pair r' e1' e2'   => cast_if_and3 (decide (r = r')) (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     | AllocN e1 e2, AllocN e1' e2'    => cast_if_and (decide (e1 = e1')) (decide (e2 = e2'))\n     | Free e, Free e'                 => cast_if (decide (e = e'))\n     | Load e, Load e'                 => cast_if (decide (e = e'))\n     | Store e1 e2, Store e1' e2'      => cast_if_and (decide (e1 = e1')) (decide (e2 = e2'))\n     | Ref e, Ref e'                   => cast_if (decide (e = e'))\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'  => cast_if_and3 (decide (f = f')) (decide (x = x')) (decide (e = e'))\n     | PairV r e1 e2, PairV r' e1' e2' => cast_if_and3 (decide (r = r')) (decide (e1 = e1')) (decide (e2 = e2'))\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 state_inhabited : Inhabited state :=\n  populate {| heap := inhabitant; used_proph_id := inhabitant |}.\nGlobal Instance val_inhabited : Inhabited val := populate (LitV LitUnit).\nGlobal Instance expr_inhabited : Inhabited expr := populate (Val inhabitant).\n\n(** Evaluation contexts *)\n(** Note that [ResolveLCtx] is not by itself an evaluation context item: we do\nnot reduce directly under Resolve's first argument. We only reduce things nested\nfurther down. Once no nested contexts exist any more, the expression must take\nexactly one more step to a value, and Resolve then (atomically) also uses that\nvalue for prophecy resolution.  *)\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 (ref : bool) (v2 : val)\n  | PairRCtx (ref : bool) (e1 : expr)\n  | FstCtx\n  | SndCtx\n  | AllocNLCtx (v2 : val)\n  | AllocNRCtx (e1 : expr)\n  | FreeCtx\n  | LoadCtx\n  | StoreLCtx (v2 : val)\n  | StoreRCtx (e1 : expr).\n\n(** Contextual closure will only reduce [e] in [Resolve e (Val _) (Val _)] if\nthe local context of [e] is non-empty. As a consequence, the first argument of\n[Resolve] is not completely evaluated (down to a value) by contextual closure:\nno head steps (i.e., surface reductions) are taken. This means that contextual\nclosure will reduce [Resolve (CmpXchg #l #n (#n + #1)) #p #v] into [Resolve\n(CmpXchg #l #n #(n+1)) #p #v], but it cannot context-step any further. *)\n\nDefinition fill_item (Ki : ectx_item) (e : expr) : expr :=\n  match Ki with\n  | AppLCtx v2      => App e (of_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 r v2   => Pair r e (Val v2)\n  | PairRCtx r e1   => Pair r e1 e\n  | FstCtx          => Fst e\n  | SndCtx          => Snd e\n  | AllocNLCtx v2   => AllocN e (Val v2)\n  | AllocNRCtx e1   => AllocN e1 e\n  | FreeCtx         => Free e\n  | LoadCtx         => Load e\n  | StoreLCtx v2    => Store e (Val v2)\n  | StoreRCtx e1    => Store 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      => 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 r e1 e2   => Pair r (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  | AllocN e1 e2   => AllocN (subst x v e1) (subst x v e2)\n  | Free e         => Free (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  | Ref e          => Ref (subst x v e)\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  | _, _ => None\n  end.\n\nDefinition bin_op_eval_int (op : bin_op) (n1 n2 : Z) : option base_lit :=\n  match op with\n  | PlusOp   => Some $ LitInt  (n1 + n2)\n  | AndOp    => Some $ LitInt  (Z.land n1 n2)\n  | EqOp     => Some $ LitBool (bool_decide (n1 = n2))\n  | OffsetOp => None (* Pointer arithmetic *)\n  end%Z.\n\nDefinition bin_op_eval_bool (op : bin_op) (b1 b2 : bool) : option base_lit :=\n  match op with\n  | PlusOp              => None (* Arithmetic *)\n  | AndOp               => Some (LitBool (b1 && b2))\n  | EqOp                => Some (LitBool (bool_decide (b1 = b2)))\n  | OffsetOp            => None (* Pointer arithmetic *)\n  end.\n\nDefinition bin_op_eval_loc (op : bin_op) (l1 : loc) (v2 : base_lit) : option base_lit :=\n  match op, v2 with\n  | OffsetOp, LitInt off => Some $ LitLoc (l1 +ₗ off)\n  | _, _ => None\n  end.\n\nDefinition bin_op_eval (op : bin_op) (v1 v2 : val) : option val :=\n  if decide (op = EqOp) then\n    (* Crucially, this compares the same way as [CmpXchg]! *)\n    if decide (vals_compare_safe v1 v2) then\n      Some $ LitV $ LitBool $ bool_decide (v1 = v2)\n    else\n      None\n  else\n    match v1, v2 with\n    | LitV (LitInt n1), LitV (LitInt n2)   => LitV <$> bin_op_eval_int op n1 n2\n    | LitV (LitBool b1), LitV (LitBool b2) => LitV <$> bin_op_eval_bool op b1 b2\n    | LitV (LitLoc l1), LitV v2            => LitV <$> bin_op_eval_loc op l1 v2\n    | _, _ => None\n    end.\n\nDefinition state_upd_heap (f: gmap loc (option val) → gmap loc (option val)) (σ: state) : state :=\n  {| heap := f σ.(heap); used_proph_id := σ.(used_proph_id) |}.\nGlobal Arguments state_upd_heap _ !_ /.\n\nDefinition state_upd_used_proph_id (f: gset proph_id → gset proph_id) (σ: state) : state :=\n  {| heap := σ.(heap); used_proph_id := f σ.(used_proph_id) |}.\nGlobal Arguments state_upd_used_proph_id _ !_ /.\n\nFixpoint heap_array (l : loc) (vs : list val) : gmap loc (option val) :=\n  match vs with\n  | [] => ∅\n  | v :: vs' => {[l := Some v]} ∪ heap_array (l +ₗ 1) vs'\n  end.\n\nLemma heap_array_singleton l v : heap_array l [v] = {[l := Some 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 w, (0 ≤ j)%Z ∧ k = l +ₗ j ∧ ow = Some w ∧ vs !! (Z.to_nat j) = Some w.\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 & w & ? & -> & -> & ?)].\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 (option val)) (l : loc) (vs : list val) :\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\n(* [h] is added on the right here to make [state_init_heap_singleton] true. *)\nDefinition state_init_heap (l : loc) (n : Z) (v : val) (σ : state) : state :=\n  state_upd_heap (λ h, heap_array l (replicate (Z.to_nat n) v) ∪ h) σ.\n\nLemma state_init_heap_singleton l v σ :\n  state_init_heap l 1 v σ = state_upd_heap <[l:=Some v]> σ.\nProof.\n  destruct σ as [h p]. rewrite /state_init_heap /=. f_equiv.\n  rewrite right_id insert_union_singleton_l. done.\nQed.\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 r v1 v2 σ :\n     head_step (Pair r (Val v1) (Val v2)) σ [] (Val $ PairV r v1 v2) σ []\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 r v1 v2 σ :\n     head_step (Fst (Val $ PairV r v1 v2)) σ [] (Val v1) σ []\n  | SndS r v1 v2 σ :\n     head_step (Snd (Val $ PairV r v1 v2)) σ [] (Val v2) σ []\n  | AllocNS n v σ l :\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 v w σ :\n     σ.(heap) !! l = Some $ Some v →\n     head_step (Store (Val $ LitV $ LitLoc l) (Val w)) σ\n               []\n               (Val $ LitV LitUnit) (state_upd_heap <[l:=Some w]> σ)\n               [].\n\n(** Basic properties about the language *)\nGlobal Instance fill_item_inj Ki : Inj (=) (=) (fill_item Ki).\nProof. \n  induction Ki; \n  intros ???; \n  simplify_eq/=; \n  auto with f_equal. \nQed.\n\nLemma fill_item_val Ki e :\n  is_Some (to_val (fill_item Ki e)) → is_Some (to_val e).\nProof. \n  intros [v ?].\n  induction Ki;\n  simplify_option_eq;\n  eauto.\nQed.\n\nLemma val_head_stuck e1 σ1 κ e2 σ2 efs : head_step e1 σ1 κ e2 σ2 efs → to_val e1 = None.\nProof. \n  destruct 1;\n  naive_solver.\nQed.\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. \n  revert κ e2.\n  induction Ki;\n  inversion_clear 1;\n  simplify_option_eq;\n  eauto.\nQed.\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  revert Ki1.\n  induction Ki2;\n  intros Ki1;\n  induction Ki1;\n  naive_solver eauto with f_equal.\nQed.\n\nLemma alloc_fresh v n σ :\n  let l := fresh_locs (dom σ.(heap)) in\n  (0 < n)%Z →\n  head_step (AllocN ((Val $ LitV $ LitInt $ n)) (Val v)) σ []\n            (Val $ LitV $ LitLoc l) (state_init_heap l n v σ) [].\nProof.\n  intros.\n  apply AllocNS; first done.\n  intros. apply not_elem_of_dom.\n  by apply fresh_locs_fresh.\nQed.\n\nLemma cs_lambda_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 cs_lambda.\n\n(** Language *)\nCanonical Structure heap_ectxi_lang := EctxiLanguage cs_lambda.cs_lambda_mixin.\nCanonical Structure heap_ectx_lang  := EctxLanguageOfEctxi heap_ectxi_lang.\n\n(* Prefer cs_lambda names over ectx_language names. *)\nExport cs_lambda.\n\n(** The following lemma is not provable using the axioms of [ectxi_language].\nThe proof requires a case analysis over context items ([destruct i] on the\nlast line), which in all cases yields a non-value. To prove this lemma for\n[ectxi_language] in general, we would require that a term of the form\n[fill_item i e] is never a value. *)\nLemma to_val_fill_some K e v : \n  to_val (fill K e) = Some v → K = [] ∧ e = Val v.\nProof.\n  intro H. destruct K as [|Ki K]; first by apply of_to_val in H. exfalso.\n  assert (to_val e ≠ None) as He.\n  { intro A. by rewrite fill_not_val in H. }\n  assert (∃ w, e = Val w) as [w ->].\n  { destruct e; try done; eauto. }\n  assert (to_val (fill (Ki :: K) (Val w)) = None).\n  { destruct Ki; simpl; apply fill_not_val; done. }\n  by simplify_eq.\nQed.\n\nLemma prim_step_to_val_is_head_step e σ1 κs w σ2 efs :\n  prim_step e σ1 κs (Val w) σ2 efs → head_step e σ1 κs (Val w) σ2 efs.\nProof.\n  intro H. destruct H as [K e1 e2 H1 H2].\n  assert (to_val (fill K e2) = Some w) as H3; first by rewrite -H2.\n  apply to_val_fill_some in H3 as [-> ->]. subst e. done.\nQed.\n\n(** If [e1] makes a head step to a value under some state [σ1] then any head\n step from [e1] under any other state [σ1'] must necessarily be to a value. *)\nLemma head_step_to_val e1 σ1 κ e2 σ2 efs σ1' κ' e2' σ2' efs' :\n  head_step e1 σ1 κ e2 σ2 efs →\n  head_step e1 σ1' κ' e2' σ2' efs' → is_Some (to_val e2) → is_Some (to_val e2').\nProof. \n  destruct 1;\n  inversion 1;\n  naive_solver.\nQed.\n\n*)\n", "meta": {"author": "fifty-six", "repo": "cs-lambda", "sha": "9ff96ba69936a5282fb75b00527c703336089a0f", "save_path": "github-repos/coq/fifty-six-cs-lambda", "path": "github-repos/coq/fifty-six-cs-lambda/cs-lambda-9ff96ba69936a5282fb75b00527c703336089a0f/src/lang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.297248083344021}}
{"text": "Require Import List.\nImport ListNotations.\nRequire Import String.\nRequire Import ZArith.\nRequire Import Ascii.\n\nRequire Import CakeSem.Namespace.\nRequire Import CakeSem.ffi.FFI.\nRequire Import CakeSem.CakeAST.\n\nDefinition dec_def_0 := Dtype [(0%nat)] (((pair (pair (nil) (\"nat\"%string) ) ((pair (\"O\"%string) (nil))::(pair (\"S\"%string) ((Atapp (nil) (Short (\"nat\"%string)))::nil))::nil))::nil)).\n\nDefinition dec_def_1 := Dletrec [(0%nat)] ((pair (pair (\"plus\"%string) (\"x\"%string) ) (EFun (\"y\"%string) (ELannot (EMat (ELannot (EVar (Short (\"x\"%string))) [(0%nat)]) ((pair (Pcon (Some (Short (\"O\"%string))) (nil)) (ELannot (EVar (Short (\"y\"%string))) [(0%nat)]))::(pair (Pcon (Some (Short (\"S\"%string))) ((Pvar (\"xp\"%string))::nil)) (ELannot (ECon (Some (Short (\"S\"%string))) ((EApp (Opapp) ((ELannot (EApp (Opapp) ((ELannot (EVar (Short (\"plus\"%string))) [(0%nat)])::(ELannot (EVar (Short (\"xp\"%string))) [(0%nat)])::nil)) [(0%nat)])::(ELannot (EVar (Short (\"y\"%string))) [(0%nat)])::nil))::nil)) [(0%nat)]))::nil)) [(0%nat)])))::nil).\n\nDefinition dec_def_2 := Dlet [(0%nat)] (Pvar (\"two\"%string)) (ELannot (ECon (Some (Short (\"S\"%string))) ((ECon (Some (Short (\"S\"%string))) ((ECon (Some (Short (\"O\"%string))) (nil))::nil))::nil)) [(0%nat)]).\n\nDefinition dec_def_3 := Dlet [(0%nat)] (Pvar (\"three\"%string)) (ELannot (ECon (Some (Short (\"S\"%string))) ((EVar (Short (\"two\"%string)))::nil)) [(0%nat)]).\n\nDefinition dec_def_4 := Dlet [(0%nat)] (Pvar (\"answer\"%string)) (ELannot (EApp (Opapp) ((ELannot (EApp (Opapp) ((ELannot (EVar (Short (\"plus\"%string))) [(0%nat)])::(ELannot (EVar (Short (\"two\"%string))) [(0%nat)])::nil)) [(0%nat)])::(ELannot (EVar (Short (\"three\"%string))) [(0%nat)])::nil)) [(0%nat)]).\n\nDefinition prog := [dec_def_0; dec_def_1; dec_def_2; dec_def_3; dec_def_4].\n\n\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/noBasisRed/NoBasis.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.29724808334402086}}
{"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 sepcomp.mem_lemmas.\nRequire Import sepcomp.core_semantics.\nRequire Import sepcomp.effect_semantics.\nRequire Import StructuredInjections.\nRequire Import effect_simulations.\nRequire Import sepcomp.effect_properties.\nRequire Import effect_simulations_lemmas.\n\nRequire Export Axioms.\nRequire Import CminorSel_coop.\nRequire Import CminorSel_eff.\nRequire Import RTL_coop.\nRequire Import RTL_eff.\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. exfalso.\n  apply valid_fresh_absurd with r0 s1.\n  apply H1. left; exists id2; auto.\n  eauto with rtlg.\n  intros. inv H2. exfalso.\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(** 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  (Genv.find_var_info_transf_partial transl_fundef _ TRANSL).\n\n(*LENB: GFP as in selectionproofEFF*)\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.\nQed.\n\n(*From Cminorgenproof*)\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 Int.add_zero. trivial.\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 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  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 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 we should\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.\n  Let's see whether this works...*)\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 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 j tm cs f map pr ns nd rd rs dst\n (*NEW:*)(PG: meminj_preserves_globals ge j)\n         sp' (SP: sp_preserved j sp sp')\n\n    (MWF: map_wf map)\n    (TE: tr_expr f.(fn_code) map pr a ns nd rd dst)\n    (ME: match_env j map e le rs)\n    (EXT: Mem.inject j m tm),\n  exists rs', exists tm',\n     corestep_star rtl_eff_sem tge\n        (RTL_State cs f sp' ns rs) tm (RTL_State cs f sp' nd rs') tm'\n  /\\ match_env j map (set_optvar dst v e) le rs'\n  /\\ val_inject j v rs'#rd\n  /\\ (forall r, In r pr -> rs'#r = rs#r)\n  /\\ Mem.inject j m tm' /\\ tm=tm'.\n\nDefinition transl_exprlist_prop\n     (le: letenv) (al: exprlist) (vl: list val) : Prop :=\n  forall j tm cs f map pr ns nd rl rs\n (*NEW:*)(PG: meminj_preserves_globals ge j)\n         sp' (SP: sp_preserved j sp sp')\n\n    (MWF: map_wf map)\n    (TE: tr_exprlist f.(fn_code) map pr al ns nd rl)\n    (ME: match_env j map e le rs)\n    (EXT: Mem.inject j m tm),\n  exists rs', exists tm',\n     corestep_star rtl_eff_sem tge\n       (RTL_State cs f sp' ns rs) tm (RTL_State cs f sp' nd rs') tm'\n  /\\ match_env j map e le rs'\n  /\\ val_list_inject j vl rs'##rl\n  /\\ (forall r, In r pr -> rs'#r = rs#r)\n  /\\ Mem.inject j m tm' /\\ tm=tm'.\n\nDefinition transl_condexpr_prop\n     (le: letenv) (a: condexpr) (v: bool) : Prop :=\n  forall j tm cs f map pr ns ntrue nfalse rs\n (*NEW:*)(PG: meminj_preserves_globals ge j)\n         sp' (SP: sp_preserved j sp sp')\n\n    (MWF: map_wf map)\n    (TE: tr_condition f.(fn_code) map pr a ns ntrue nfalse)\n    (ME: match_env j map e le rs)\n    (EXT: Mem.inject j m tm),\n  exists rs', exists tm',\n     corestep_plus rtl_eff_sem 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 j map e le rs'\n  /\\ (forall r, In r pr -> rs'#r = rs#r)\n  /\\ Mem.inject j m tm' /\\ tm=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; 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. inv TE.\n(* normal case *)\n  exploit H0; eauto. intros [rs1 [tm1 [EX1 [ME1 [RR1 [RO1 [EXT1 X]]]]]]]; subst tm.\n  (*Was: edestruct eval_operation_lessdef...*)\n\n  destruct SP as [spb [spb' [SP [SP' Jsp]]]]. subst sp sp'.\n  edestruct eval_operation_inject as [v' []]; eauto.\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(* 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. inv TE.\n  exploit H0; eauto. intros [rs1 [tm1 [EX1 [ME1 [RES1 [OTHER1 [EXT1 X]]]]]]]; subst tm.\n  (*Was: edestruct eval_addressing_lessdef as [vaddr' []]; eauto.*)\n\n  destruct SP as [spb [spb' [SP [SP' Jsp]]]]. subst sp sp'.\n  edestruct eval_addressing_inject as [vaddr' [? ?]]; eauto.\n  rewrite shift_stack_addressing_zero in H3; simpl in H3.\n  edestruct Mem.loadv_inject as [v' []]; eauto.\n  exists (rs1#rd <- v'); exists tm1.\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. intros [rs1 [tm1 [EX1 [ME1 [OTHER1 [EXT1 X]]]]]]; subst tm.\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  exploit H2; eauto. intros [rs2 [tm2 [EX2 [ME2 [RES2 [OTHER2 EXT2]]]]]].\n  exists rs2; exists tm2.\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. intros [rs1 [tm1 [EX1 [ME1 [RES1 [OTHER1 [EXT1 X]]]]]]]; subst tm.\n  assert (map_wf (add_letvar map r)).\n    eapply add_letvar_wf; eauto.\n  exploit H2; eauto. eapply match_env_bind_letvar; eauto.\n  intros [rs2 [tm2 [EX2 [ME3 [RES2 [OTHER2 EXT2]]]]]].\n  exists rs2; exists tm2.\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.\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\n(*LENB: TODO: builtin: Lemma doesn;'t quite hold -nned to extend j -> j'.\n  But maye we won't need this case, if\n  builtin-expressions can be eliminated from CminorSel.expressions*)\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  admit. (*We do not yet support use of builtins for 64-bit operations.*)\nQed.\n(*Proof.\n  intros; red; intros. inv TE.\n  exploit H0; eauto. intros [rs1 [tm1 [EX1 [ME1 [RR1 [RO1 EXT1]]]]]].\n  (*WAS: exploit external_call_mem_extends; eauto.\n        intros [v' [tm2 [A [B [C [D E]]]]]].*)\n  exploit external_call_mem_inject; eauto.\n        intros [j' [v' [tm2 [A [B [C [D [E [F G]]]]]]]]].\n  exists (rs1#rd <- v'); exists tm2.\n(* Exec *)\n  split. eapply corestep_star_trans. eexact EX1.\n         apply corestep_star_one. eapply rtl_corestep_exec_Ibuiltin; eauto.\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         eapply val_inject_incr. eassumption. split; intros.  eexists. eauto with rtlg.\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  auto.\nQed.\n*)\n\n(*LENB: Lemma should not be needed any more since external calls are\n handled by coresemantics interface now. We can probably eliminate\n  external expressions from CminorSel.v, but that's a modification of a\n  language definition*)\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  admit. (*We do not yet support use of builtins for 64-bit operations.*)\nQed.\n(*\nProof.\n  intros; red; intros. inv TE.\n  exploit H3; eauto. intros [rs1 [tm1 [EX1 [ME1 [RR1 [RO1 EXT1]]]]]].\n  exploit external_call_mem_extends; eauto.\n  intros [v' [tm2 [A [B [C [D E]]]]]].\n  exploit function_ptr_translated; eauto. simpl. intros [tf [P Q]]. inv Q.\n  exists (rs1#rd <- v'); exists tm2.\n(* Exec *)\n  split. eapply star_trans. eexact EX1.\n  eapply star_left. eapply exec_Icall; eauto.\n  simpl. rewrite symbols_preserved. rewrite H. eauto. auto.\n  eapply star_left. eapply exec_function_external.\n  eapply external_call_symbols_preserved; eauto. exact symbols_preserved. exact varinfo_preserved.\n  apply star_one. apply exec_return.\n  reflexivity. reflexivity. reflexivity.\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*)\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.\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. intros [rs1 [tm1 [EX1 [ME1 [RES1 [OTHER1 [EXT1 X1]]]]]]]; subst.\n  exploit H2; eauto. intros [rs2 [tm2 [EX2 [ME2 [RES2 [OTHER2 [EXT2 X2]]]]]]]; subst.\n  exists rs2; exists tm2.\n(* Exec *)\n  split. eapply corestep_star_trans. eexact EX1. eexact EX2. auto.\n(* Match-env *)\n  split. assumption.\n(* Results *)\n  split. simpl. constructor. rewrite OTHER2. auto.\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. intros [rs1 [tm1 [EX1 [ME1 [RES1 [OTHER1 [EXT1 X]]]]]]]; subst.\n  exists rs1; exists tm1.\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. 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. intros [rs1 [tm1 [EX1 [ME1 [OTHER1 [EXT1 X]]]]]]; subst.\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  exploit H2; eauto. intros [rs2 [tm2 [EX2 [ME2 [OTHER2 [EXT2 X]]]]]]; subst.\n  exists rs2; exists tm2.\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. intros [rs1 [tm1 [EX1 [ME1 [RES1 [OTHER1 [EXT1 X]]]]]]]; subst.\n  assert (map_wf (add_letvar map r)).\n    eapply add_letvar_wf; eauto.\n  exploit H2; eauto. eapply match_env_bind_letvar; eauto.\n  intros [rs2 [tm2 [EX2 [ME3 [OTHER2 [EXT2 X]]]]]]; subst.\n  exists rs2; exists tm2.\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 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  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(* 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  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(* 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 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  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.\nQed.\n\nVariable sp: val.\nVariable e: env.\nVariable m: mem.\n\n\nDefinition Efftransl_expr_prop\n     (le: letenv) (a: expr) (v: val) : Prop :=\n  forall j tm cs f map pr ns nd rd rs dst\n (*NEW:*)(PG: meminj_preserves_globals ge j)\n         sp' (SP: sp_preserved j sp sp')\n\n    (MWF: map_wf map)\n    (TE: tr_expr f.(fn_code) map pr a ns nd rd dst)\n    (ME: match_env j map e le rs)\n    (EXT: Mem.inject j m tm),\n  exists rs', exists tm',\n     effstep_star rtl_eff_sem tge EmptyEffect\n        (RTL_State cs f sp' ns rs) tm (RTL_State cs f sp' nd rs') tm'\n  /\\ match_env j map (set_optvar dst v e) le rs'\n  /\\ val_inject j v rs'#rd\n  /\\ (forall r, In r pr -> rs'#r = rs#r)\n  /\\ Mem.inject j m tm' /\\ tm=tm'.\n\nDefinition Efftransl_exprlist_prop\n     (le: letenv) (al: exprlist) (vl: list val) : Prop :=\n  forall j tm cs f map pr ns nd rl rs\n (*NEW:*)(PG: meminj_preserves_globals ge j)\n         sp' (SP: sp_preserved j sp sp')\n\n    (MWF: map_wf map)\n    (TE: tr_exprlist f.(fn_code) map pr al ns nd rl)\n    (ME: match_env j map e le rs)\n    (EXT: Mem.inject j m tm),\n  exists rs', exists tm',\n     effstep_star rtl_eff_sem tge EmptyEffect\n       (RTL_State cs f sp' ns rs) tm (RTL_State cs f sp' nd rs') tm'\n  /\\ match_env j map e le rs'\n  /\\ val_list_inject j vl rs'##rl\n  /\\ (forall r, In r pr -> rs'#r = rs#r)\n  /\\ Mem.inject j m tm' /\\ tm=tm'.\n\nDefinition Efftransl_condexpr_prop\n     (le: letenv) (a: condexpr) (v: bool) : Prop :=\n  forall j tm cs f map pr ns ntrue nfalse rs\n (*NEW:*)(PG: meminj_preserves_globals ge j)\n         sp' (SP: sp_preserved j sp sp')\n\n    (MWF: map_wf map)\n    (TE: tr_condition f.(fn_code) map pr a ns ntrue nfalse)\n    (ME: match_env j map e le rs)\n    (EXT: Mem.inject j m tm),\n  exists rs', exists tm',\n     effstep_plus rtl_eff_sem 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 j map e le rs'\n  /\\ (forall r, In r pr -> rs'#r = rs#r)\n  /\\ Mem.inject j m tm' /\\ tm=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; 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. intros [rs1 [tm1 [EX1 [ME1 [RR1 [RO1 [EXT1 X]]]]]]]; subst tm.\n  (*Was: edestruct eval_operation_lessdef...*)\n\n  destruct SP as [spb [spb' [SP [SP' Jsp]]]]. subst sp sp'.\n  edestruct eval_operation_inject as [v' []]; eauto.\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(* 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(* 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. intros [rs1 [tm1 [EX1 [ME1 [RES1 [OTHER1 [EXT1 X]]]]]]]; subst tm.\n  (*Was: edestruct eval_addressing_lessdef as [vaddr' []]; eauto.*)\n\n  destruct SP as [spb [spb' [SP [SP' Jsp]]]]. subst sp sp'.\n  edestruct eval_addressing_inject as [vaddr' [? ?]]; eauto.\n  rewrite shift_stack_addressing_zero in H3; simpl in H3.\n  edestruct Mem.loadv_inject as [v' []]; eauto.\n  exists (rs1#rd <- v'); exists tm1.\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(* 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. intros [rs1 [tm1 [EX1 [ME1 [OTHER1 [EXT1 X]]]]]]; subst tm.\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  exploit H2; eauto. intros [rs2 [tm2 [EX2 [ME2 [RES2 [OTHER2 EXT2]]]]]].\n  exists rs2; exists tm2.\n(* Exec *)\n  split. eapply effstep_star_trans.\n           apply effstep_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 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. intros [rs1 [tm1 [EX1 [ME1 [RES1 [OTHER1 [EXT1 X]]]]]]]; subst tm.\n  assert (map_wf (add_letvar map r)).\n    eapply add_letvar_wf; eauto.\n  exploit H2; eauto. eapply match_env_bind_letvar; eauto.\n  intros [rs2 [tm2 [EX2 [ME3 [RES2 [OTHER2 EXT2]]]]]].\n  exists rs2; exists tm2.\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.\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\n(*LENB: TODO: builtin: Lemma doesn;'t quite hold -nned to extend j -> j'.\n  But maye we won't need this case, if\n  builtin-expressions can be eliminated from CminorSel.expressions*)\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  admit. (*We do not yet support use of builtins for 64-bit operations.*)\nQed.\n(*Proof.\n  intros; red; intros. inv TE.\n  exploit H0; eauto. intros [rs1 [tm1 [EX1 [ME1 [RR1 [RO1 EXT1]]]]]].\n  (*WAS: exploit external_call_mem_extends; eauto.\n        intros [v' [tm2 [A [B [C [D E]]]]]].*)\n  exploit external_call_mem_inject; eauto.\n        intros [j' [v' [tm2 [A [B [C [D [E [F G]]]]]]]]].\n  exists (rs1#rd <- v'); exists tm2.\n(* Exec *)\n  split. eapply effstep_star_trans. eexact EX1.\n         apply effstep_star_one. eapply rtl_effstep_exec_Ibuiltin; eauto.\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         eapply val_inject_incr. eassumption. split; intros.  eexists. eauto with rtlg.\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  auto.\nQed.\n*)\n\n(*LENB: Lemma should not be needed any more since external calls are\n handled by effsemantics interface now. We can probably eliminate\n  external expressions from CminorSel.v, but that's a language definieiotn modification*)\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  admit. (*We do not yet support use of builtins for 64-bit operations.*)\nQed.\n(*Proof.\n  intros; red; intros. inv TE.\n  exploit H3; eauto. intros [rs1 [tm1 [EX1 [ME1 [RR1 [RO1 EXT1]]]]]].\n  exploit external_call_mem_extends; eauto.\n  intros [v' [tm2 [A [B [C [D E]]]]]].\n  exploit function_ptr_translated; eauto. simpl. intros [tf [P Q]]. inv Q.\n  exists (rs1#rd <- v'); exists tm2.\n(* Exec *)\n  split. eapply star_trans. eexact EX1.\n  eapply star_left. eapply exec_Icall; eauto.\n  simpl. rewrite symbols_preserved. rewrite H. eauto. auto.\n  eapply star_left. eapply exec_function_external.\n  eapply external_call_symbols_preserved; eauto. exact symbols_preserved. exact varinfo_preserved.\n  apply star_one. apply exec_return.\n  reflexivity. reflexivity. reflexivity.\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*)\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.\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  exploit H0; eauto. intros [rs1 [tm1 [EX1 [ME1 [RES1 [OTHER1 [EXT1 X1]]]]]]]; subst.\n  exploit H2; eauto. intros [rs2 [tm2 [EX2 [ME2 [RES2 [OTHER2 [EXT2 X2]]]]]]]; subst.\n  exists rs2; exists tm2.\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. auto.\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. intros [rs1 [tm1 [EX1 [ME1 [RES1 [OTHER1 [EXT1 X]]]]]]]; subst.\n  exists rs1; exists tm1.\n(* Exec *)\n  split. eapply effstep_star_plus_trans. eexact EX1.\n      eapply effstep_plus_one. eapply rtl_effstep_exec_Icond. eauto.\n      (*eapply eval_condition_lessdef; eauto.*)\n    eapply eval_condition_inject; eauto. auto.\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. intros [rs1 [tm1 [EX1 [ME1 [OTHER1 [EXT1 X]]]]]]; subst.\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  exploit H2; eauto. intros [rs2 [tm2 [EX2 [ME2 [OTHER2 [EXT2 X]]]]]]; subst.\n  exists rs2; exists tm2.\n(* Exec *)\n  split. eapply effstep_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 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. intros [rs1 [tm1 [EX1 [ME1 [RES1 [OTHER1 [EXT1 X]]]]]]]; subst.\n  assert (map_wf (add_letvar map r)).\n    eapply add_letvar_wf; eauto.\n  exploit H2; eauto. eapply match_env_bind_letvar; eauto.\n  intros [rs2 [tm2 [EX2 [ME3 [OTHER2 [EXT2 X]]]]]]; subst.\n  exists rs2; exists tm2.\n(* Exec *)\n  split. eapply effstep_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 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 j*)\nInductive tr_cont (j:meminj): 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 j c map k n nexits ngoto nret rret cs ->\n      tr_cont j 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 j c map k nd nexits ngoto nret rret cs ->\n      tr_cont j 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 j Kstop cs ->\n      tr_cont j 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 j (Kcall optid f sp e k) cs ->\n      tr_cont j c map (Kcall optid f sp e k) nret nil ngoto nret rret cs\n\nwith match_stacks (j:meminj) : CminorSel.cont -> list RTL.stackframe -> Prop :=\n  | match_stacks_stop:\n      match_stacks j 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 j map e nil rs ->\n      reg_map_ok map r optid ->\n      tr_cont j tf.(fn_code) map k n nexits ngoto nret rret cs ->\n      (*NEW:*) sp_preserved j sp sp' ->\n      match_stacks j (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_inject_incr:\n      forall j j' (INC: inject_incr j j'),\n      (forall c map k ncont nexits ngoto nret rret cs,\n         tr_cont j c map k ncont nexits ngoto nret rret cs ->\n         tr_cont j' c map k ncont nexits ngoto nret rret cs) /\\\n       (forall k cs, match_stacks j k cs -> match_stacks j' 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; eassumption.\n     destruct s as [b [b' [B [B' SP]]]].\n       apply INC in SP. exists b, b'; eauto.\nQed.\nLemma tr_cont_inject_incr:\n      forall j c map k ncont nexits ngoto nret rret cs\n        (TR: tr_cont j c map k ncont nexits ngoto nret rret cs)\n        j' (INC: inject_incr j j'),\n      tr_cont j' c map k ncont nexits ngoto nret rret cs.\nProof. intros.\n       eapply tr_cont_match_stacks_inject_incr; try eassumption.\nQed.\nLemma match_stacks_inject_incr:\n      forall j  k cs (MS:match_stacks j k cs)\n             j' (INC: inject_incr j j'),\n      match_stacks j' k cs.\nProof. intros.\n       eapply tr_cont_match_stacks_inject_incr; try eassumption.\nQed.\n\nInductive match_states (j:meminj): 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 j tf.(fn_code) map k ncont nexits ngoto nret rret cs)\n        (ME: match_env j map e nil rs)\n        (*(MEXT: Mem.extends m tm)*)\n        (MINJ: Mem.inject j m tm)\n        (*NEW:*) (SP: sp_preserved j sp sp'),\n      match_states j (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 j k cs)\n        (*(LD: Val.lessdef_list args targs)*)\n        (AINJ: val_list_inject j args targs)\n        (*(MEXT: Mem.extends m tm)*)\n        (MINJ: Mem.inject j m tm),\n      match_states j (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 j k cs)\n        (*(LD: Val.lessdef v tv)*)\n         (VINJ: val_inject j v tv)\n        (*(MEXT: Mem.extends m tm)*)\n        (MINJ: Mem.inject j m tm),\n      match_states j (CMinSel_Returnstate v k) m\n                     (RTL_Returnstate cs tv) tm.\n\n\nLemma match_stacks_call_cont:\n  forall j c map k ncont nexits ngoto nret rret cs,\n  tr_cont j c map k ncont nexits ngoto nret rret cs ->\n  match_stacks j (call_cont k) cs /\\ c!nret = Some(Ireturn rret).\nProof.\n  induction 1; simpl; auto.\nQed.\n\nLemma tr_cont_call_cont:\n  forall j c map k ncont nexits ngoto nret rret cs,\n  tr_cont j c map k ncont nexits ngoto nret rret cs ->\n  tr_cont j 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 j 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 j 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 j 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 (as_inj 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 (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_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  rewrite restrict_sm_all.\n  eapply inject_restrict; eassumption.\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 v1 v2 sig entrypoints\n      (EP: In (v1, v2, sig) entrypoints)\n      (entry_points_ok : 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      vals1 c1 m1 j vals2 m2 (DomS DomT : block -> bool)\n      (Ini: initial_core cminsel_eff_sem ge v1 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      (R : list_norepet (map fst (prog_defs prog)))\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      (InitMem : exists m0 : mem, Genv.init_mem prog = Some m0\n               /\\ Ple (Mem.nextblock m0) (Mem.nextblock m1)\n               /\\ Ple (Mem.nextblock m0) (Mem.nextblock m2))\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 tge v2 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 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 [FP TF]].\n  exists (RTL_Callstate nil tf vals2).\n  split.\n    destruct (entry_points_ok _ _ _ EP) as [b0 [f1 [f2 [A [B [C D]]]]]].\n    subst. inv A. rewrite C in Heqzz. inv Heqzz.\n    unfold tge in FP. rewrite D in FP. inv FP.\n    unfold cminsel_eff_sem, cminsel_coop_sem. simpl.\n    case_eq (Int.eq_dec Int.zero Int.zero). intros ? e.\n    solve[rewrite D; auto].\n\n    intros CONTRA.\n    solve[exfalso; auto].\n(*  assert (exists targs tres, type_of_fundef f = Tfunction targs tres).\n         destruct f; simpl. eexists; eexists. reflexivity.\n         eexists; eexists. reflexivity.\n  destruct H as [targs [tres Tfun]].*)\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    eapply match_callstate; try eassumption.\n      constructor.\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 initial_SM_as_inj.\n      unfold vis, initial_SM; simpl.\n      eapply inject_restrict; eassumption.\n  intuition.\n    rewrite match_genv_meminj_preserves_extern_iff_all.\n      assumption.\n      apply BB.\n      apply EE.\n    (*as in selectionprffEFF*)\n    rewrite initial_SM_as_inj.\n      red; intros. specialize (Genv.find_funct_ptr_not_fresh prog). intros.\n         destruct InitMem as [m0 [INIT_MEM [? ?]]].\n         specialize (H0 _ _ _ INIT_MEM H).\n         destruct (valid_init_is_global _ R _ INIT_MEM _ H0) as [id Hid].\n           destruct PG as [PGa [PGb PGc]]. split. eapply PGa; eassumption.\n         unfold isGlobalBlock.\n          apply orb_true_iff. left. apply genv2blocksBool_char1.\n            simpl. exists id; eassumption.\n    rewrite initial_SM_as_inj; assumption.\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 st1 = Some (e, ef_sig, vals1))\n      (AtExtTgt : at_external rtl_eff_sem 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: 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 (Some ret1) st1 =Some st1' /\\\n  after_external rtl_eff_sem (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 eexists. eexists.\n    split. reflexivity.\n    split. reflexivity.\n simpl in *.\n inv TF.\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.\nassert (PHnu': meminj_preserves_globals (Genv.globalenv prog) (as_inj nu')).\n    subst. clear - INC SEP PG Glob 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      assert (GG: isGlobalBlock ge b = true).\n          unfold isGlobalBlock, ge. apply genv2blocksBool_char1 in H.\n          rewrite H. trivial.\n      destruct (frgnSrc _ WDmu _ (Glob _ GG)) as [bb2 [dd [FF FT2]]].\n      rewrite (foreign_in_all _ _ _ _ FF) in PGa. inv PGa.\n      apply foreign_in_extern; eassumption.\n    split; intros. specialize (PGb _ H).\n      apply joinI; left. apply INC.\n      rewrite replace_locals_extern.\n      assert (GG: isGlobalBlock ge b = true).\n          unfold isGlobalBlock, ge. apply genv2blocksBool_char2 in H.\n          rewrite H. intuition.\n      destruct (frgnSrc _ WDmu _ (Glob _ GG)) as [bb2 [dd [FF FT2]]].\n      rewrite (foreign_in_all _ _ _ _ FF) in PGb. inv PGb.\n      apply foreign_in_extern; eassumption.\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.\n        destruct p.\n        apply extern_incr_as_inj in INC; trivial.\n        rewrite replace_locals_as_inj in INC.\n        rewrite (INC _ _ _ Heqd) in H0. trivial.\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.\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(*assert (RRR: REACH_closed m1' (exportedSrc nu' (ret1 :: nil))).\n    intros b Hb. apply 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       unfold exportedSrc.\n       eapply REACH_cons; 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.\nsplit.\n  econstructor; try eassumption.\n    eapply match_stacks_inject_incr; try eassumption.\n    unfold vis in *.\n      rewrite replace_externs_frgnBlocksSrc, replace_externs_locBlocksSrc in *.\n      rewrite (*restrict_sm_all, *)replace_externs_as_inj.\n      clear RRC RR1 RC' PHnu' INCvisNu' UnchLOOR UnchPrivSrc.\n      destruct INC. rewrite replace_locals_extern in H.\n        rewrite replace_locals_frgnBlocksTgt, replace_locals_frgnBlocksSrc,\n                replace_locals_pubBlocksTgt, replace_locals_pubBlocksSrc,\n                replace_locals_locBlocksTgt, replace_locals_locBlocksSrc,\n                replace_locals_extBlocksTgt, replace_locals_extBlocksSrc,\n                replace_locals_local in H0.\n        destruct H0 as [? [? [? [? [? [? [? [? ?]]]]]]]].\n        red; intros. destruct (restrictD_Some _ _ _ _ _ H9); clear H9.\n          apply restrictI_Some.\n            apply joinI.\n            destruct (joinD_Some _ _ _ _ _ H10).\n              apply H in H9. left; trivial.\n            destruct H9. right. rewrite H0 in H12.\n              split; trivial.\n              destruct (disjoint_extern_local _ WDnu' b); trivial. congruence.\n          (*rewrite replace_externs_frgnBlocksSrc, replace_externs_locBlocksSrc. *)\n          rewrite H3, H7 in H11.\n            remember (locBlocksSrc nu' b) as d.\n            destruct d; trivial; simpl in *.\n            apply andb_true_iff.\n            split. unfold DomSrc. rewrite (frgnBlocksSrc_extBlocksSrc _ WDnu' _ H11). intuition.\n               apply REACH_nil. unfold exportedSrc.\n                 apply frgnSrc_shared in H11; trivial. rewrite H11; intuition.\n      unfold vis. rewrite replace_externs_as_inj.\n       rewrite replace_externs_frgnBlocksSrc, replace_externs_locBlocksSrc.\n       eapply restrict_val_inject; try eassumption.\n       intros.\n        destruct (getBlocks_inject (as_inj nu') (ret1::nil) (ret2::nil))\n           with (b:=b) as [bb [dd [JJ' GBbb]]]; try eassumption.\n          constructor. assumption. constructor.\n        remember (locBlocksSrc nu' b) as d.\n        destruct d; simpl; trivial. apply andb_true_iff.\n        split. eapply as_inj_DomRng; eassumption.\n        apply REACH_nil. unfold exportedSrc.\n           rewrite H. trivial.\nunfold vis in *.\nrewrite replace_externs_locBlocksSrc, replace_externs_frgnBlocksSrc,\n        replace_externs_as_inj in *.\n  eapply inject_mapped; try eassumption.\n  eapply restrict_mapped_closed; try eassumption.\n\ndestruct (eff_after_check2 _ _ _ _ _ MemInjNu' RValInjNu'\n      _ (eq_refl _) _ (eq_refl _) _ (eq_refl _) WDnu' SMvalNu').\nunfold vis in *.\n  rewrite replace_externs_locBlocksSrc, replace_externs_frgnBlocksSrc,\n  replace_externs_as_inj 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_corestep: forall\n       st1 m1 st1' m1'\n       (CS: corestep cminsel_eff_sem ge st1 m1 st1' m1')\n       st2 mu m2 (MTCH: MATCH st1 mu st1 m1 st2 m2),\nexists st2' m2' mu',\n  (corestep_plus rtl_eff_sem tge st2 m2 st2' m2' \\/\n   (corestep_star rtl_eff_sem tge st2 m2 st2' m2' /\\ lt_state st1' st1))\n  /\\ intern_incr mu mu'\n  /\\ sm_inject_separated mu mu' m1 m2\n  /\\ sm_locally_allocated mu mu' m1 m2 m1' m2'\n  /\\ MATCH st1' mu' st1' m1' st2' m2'\n  /\\ SM_wd mu' /\\ sm_valid mu' m1' m2'.\nProof. intros.\n   destruct CS; intros; destruct MTCH as [MSTATE PRE]; inv MSTATE.\n\n  (* skip seq *)\n  inv TS. inv TK.\n  eexists; exists m2, mu; split.\n     right; split. apply corestep_star_zero. Lt_state.\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\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; split.\n    right; split. apply corestep_star_zero. Lt_state.\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\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 (as_inj mu) (vis mu)) k cs).\n    inv TK; simpl in H; try contradiction; auto.\n  destruct H1.\n  assert (fn_stacksize tf = fn_stackspace f).\n    inv TF. auto.\n  destruct SP as [spb [spb' [X [Y Rsp]]]]; subst sp'; inv X.\n  destruct PRE as [RC [PG [GFP [Glob [SMV [WD MInj]]]]]].\n  edestruct free_parallel_inject as [tm' []]; eauto.\n  destruct (restrictD_Some _ _ _ _ _ Rsp).\n  eexists; exists tm', mu; split.\n    simpl in *; rewrite Zplus_0_r in H4. rewrite <- H3 in H4.\n    left; apply corestep_plus_one.\n      eapply rtl_corestep_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 sm_inject_separated_same_sminj.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b;\n          try rewrite (freshloc_free _ _ _ _ _ H4);\n          try rewrite (freshloc_free _ _ _ _ _ H0); intuition.\n  econstructor. econstructor; eauto.\n      intuition.\n      eapply REACH_closed_free; try eassumption.\n      eapply (free_free_inject _ m m' m2); try eassumption.\n\n  (* assign *)\n  inv TS.\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  exploit transl_expr_correct; eauto.\n  intros [rs' [tm' [A [B [C [D [E F]]]]]]]; subst.\n  eexists; eexists; exists mu; split.\n    right; split. eauto. Lt_state.\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\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  (* store *)\n  inv TS.\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  exploit transl_exprlist_correct; eauto.\n  intros [rs' [tm' [A [B [C [D [E F]]]]]]]; subst.\n  exploit transl_expr_correct; eauto.\n  intros [rs'' [tm'' [F [G [J [K [L M]]]]]]]; subst.\n  destruct SP as [spb [spb' [X [Y Rsp]]]]; subst sp'; inv X.\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  edestruct eval_addressing_inject as [vaddr' []]; eauto.\n  edestruct Mem.storev_mapped_inject as [tm''' []]; eauto.\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  eexists; exists tm''', mu; split.\n    left; eapply corestep_star_plus_trans.\n      eapply corestep_star_trans. eexact A. eexact F.\n      eapply corestep_plus_one.\n        eapply rtl_corestep_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  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality bb;\n        try rewrite (store_freshloc _ _ _ _ _ H2);\n        try rewrite (store_freshloc _ _ _ _ _ H6); intuition.\n      econstructor. econstructor; eauto. constructor.\n        exists spb, spb'. split; trivial. split; trivial.\n      intuition.\n      (*rest of this case is almost identical to SelectionproofEFF.v, instruction store*)\n      destruct vaddr; inv H2.\n        eapply REACH_Store; try eassumption.\n          inv H5. destruct (restrictD_Some _ _ _ _ _ H10); trivial.\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      assert (VaddrMu: val_inject (as_inj mu) vaddr vaddr').\n        eapply val_inject_incr; try eassumption.\n        apply restrict_incr.\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          MInj H2 VaddrMu VMu) as [mm [Hmm1 Hmm2]].\n      rewrite Hmm1 in H6. inv H6. assumption.\n\n  (* call *)\n  inv TS; inv H.\n  (* indirect *)\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  exploit transl_expr_correct; eauto.\n  intros [rs' [tm' [A [B [C [D [X ?]]]]]]]; subst m2.\n  exploit transl_exprlist_correct; eauto.\n  intros [rs'' [tm'' [E [F [G [J [Y ?]]]]]]]; subst tm'.\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). rewrite H in muBB. inv muBB.\n  rewrite Int.add_zero in H3.\n  eexists; eexists; exists mu; split.\n    left; eapply corestep_star_plus_trans.\n            eapply corestep_star_trans. eexact A. eexact E.\n          eapply corestep_plus_one.\n            eapply rtl_corestep_exec_Icall; eauto.\n               simpl. rewrite J. rewrite <- H3. eassumption. simpl; eauto.\n               apply sig_transl_function; auto.\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b';\n          try rewrite (freshloc_irrefl); intuition.\n      econstructor. econstructor; eauto. econstructor; try eassumption.\n      intuition.\n  (* direct *)\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  exploit transl_exprlist_correct; eauto.\n  intros [rs'' [tm'' [E [F [G [J [Y ?]]]]]]]; subst m2.\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; split.\n    left. eapply corestep_star_plus_trans. eexact E.\n          eapply corestep_plus_one. eapply rtl_corestep_exec_Icall; eauto. simpl. rewrite symbols_preserved. rewrite H4.\n             rewrite Genv.find_funct_find_funct_ptr in P. eauto.\n             apply sig_transl_function; auto.\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b';\n          try rewrite (freshloc_irrefl); intuition.\n      econstructor. econstructor; eauto. econstructor; try eassumption.\n      intuition.\n\n  (* tailcall *)\n  inv TS; inv H.\n  (* indirect *)\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  exploit transl_expr_correct; eauto.\n  intros [rs' [tm' [A [B [C [D [X ?]]]]]]]; subst m2.\n  exploit transl_exprlist_correct; eauto.\n  intros [rs'' [tm'' [E [F [G [J [Y ?]]]]]]]; subst tm'.\n  exploit functions_translated; eauto. intros [tf' [P Q]].\n  exploit match_stacks_call_cont; eauto. intros [U V].\n  assert (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  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 _ _ _ _ _ H10). rewrite H7 in muBB. inv muBB.\n  rewrite Int.add_zero in H9.\n  eexists; exists tm'''; exists mu; split.\n    left; eapply corestep_star_plus_trans.\n           eapply corestep_star_trans. eexact A. eexact E.\n           eapply corestep_plus_one.\n             eapply rtl_corestep_exec_Itailcall; eauto.\n             simpl. rewrite J. rewrite <- H9. eassumption.\n             simpl; eauto.\n             apply sig_transl_function; auto.\n  simpl in H2; rewrite Zplus_0_r in H2. rewrite H; 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 sm_inject_separated_same_sminj.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b';\n          try rewrite (freshloc_free _ _ _ _ _ H2);\n          try rewrite (freshloc_free _ _ _ _ _ H3); intuition.\n      econstructor. econstructor; eauto.\n      intuition.\n         eapply REACH_closed_free; eassumption.\n         destruct (restrictD_Some _ _ _ _ _ Rsp).\n           eapply free_free_inject; try eassumption.\n  (* direct *)\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  exploit transl_exprlist_correct; eauto.\n  intros [rs'' [tm'' [E [F [G [J [Y ?]]]]]]]; subst m2.\n  exploit functions_translated; eauto. intros [tf' [P Q]].\n  exploit match_stacks_call_cont; eauto. intros [U V].\n  assert (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  eexists; exists tm''', mu; split.\n    left; eapply corestep_star_plus_trans. eexact E.\n          eapply corestep_plus_one.\n            eapply rtl_corestep_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  simpl in H2; rewrite Zplus_0_r in H2; rewrite H; 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 sm_inject_separated_same_sminj.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b';\n          try rewrite (freshloc_free _ _ _ _ _ H2);\n          try rewrite (freshloc_free _ _ _ _ _ H3); intuition.\n      econstructor. econstructor; eauto.\n      intuition.\n         eapply REACH_closed_free; eassumption.\n         destruct (restrictD_Some _ _ _ _ _ Rsp).\n           eapply free_free_inject; try eassumption.\n\n  (* builtin TODO\n  inv TS.\n  exploit transl_exprlist_correct; eauto.\n  intros [rs' [tm' [E [F [G [J K]]]]]].\n  edestruct external_call_mem_extends as [tv [tm'' [A [B [C D]]]]]; eauto.\n  econstructor; split.\n  left. eapply plus_right. eexact E.\n  eapply exec_Ibuiltin. eauto.\n  eapply external_call_symbols_preserved. eauto.\n  exact symbols_preserved. exact varinfo_preserved.\n  traceEq.\n  econstructor; eauto. constructor.\n  eapply match_env_update_dest; eauto.\n\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\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  (* seq *)\n  inv TS.\n  eexists; exists m2, mu; split.\n    right; split. apply corestep_star_zero. Lt_state.\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\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  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  exploit transl_condexpr_correct; eauto.\n  intros [rs' [tm' [A [B [C [D ?]]]]]]; subst m2.\n  eexists; exists tm', mu; split.\n    left. eexact A.\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality bb;\n          try rewrite (freshloc_irrefl); intuition.\n      econstructor.\n       destruct b; econstructor; eauto.\n      intuition.\n\n  (* loop *)\n  inversion TS; subst.\n  eexists; exists m2, mu; split.\n    left. apply corestep_plus_one. eapply rtl_corestep_exec_Inop; eauto.\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\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  (* block *)\n  inv TS.\n  eexists; exists m2, mu; split.\n    right; split. apply corestep_star_zero. Lt_state.\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\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; split.\n    right; split. apply corestep_star_zero. Lt_state.\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\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; split.\n    right; split. apply corestep_star_zero. Lt_state.\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\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; split.\n    right; split. apply corestep_star_zero. Lt_state.\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\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  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  exploit validate_switch_correct; eauto. intro CTM.\n  exploit transl_expr_correct; eauto.\n  intros [rs' [tm' [A [B [C [D [X ?]]]]]]]; subst m2.\n  exploit transl_switch_correct; eauto. inv C. auto.\n  intros [nd [rs'' [E [F G]]]].\n  eexists; eexists; exists mu; split.\n    right; split. eapply corestep_star_trans. eexact A. eexact E. Lt_state.\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b;\n          try rewrite (freshloc_irrefl); intuition.\n      econstructor. econstructor; eauto. constructor; eassumption.\n      intuition.\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  destruct SP as [spb [spb' [SPB [SPB' Rsp]]]]; subst sp'; inv SPB.\n  edestruct free_parallel_inject as [tm''' []]; eauto.\n  eexists; exists tm''', mu; split.\n    simpl in H0; rewrite Zplus_0_r in H0. rewrite <- H2 in H0.\n    left; eapply corestep_plus_one.\n            eapply rtl_corestep_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 sm_inject_separated_same_sminj.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b';\n          try rewrite (freshloc_free _ _ _ _ _ H0);\n          try rewrite (freshloc_free _ _ _ _ _ H); intuition.\n      econstructor. econstructor; eauto.\n      intuition.\n         eapply REACH_closed_free; eassumption.\n         destruct (restrictD_Some _ _ _ _ _ Rsp).\n           eapply free_free_inject; try eassumption.\n\n  (* return some *)\n  inv TS.\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  exploit transl_expr_correct; eauto.\n  intros [rs' [tm' [A [B [C [D [E ?]]]]]]]; subst m2.\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  eexists; exists tm'', mu; split.\n    simpl in H5; rewrite Zplus_0_r in H5. rewrite <- H4 in H5.\n    left; eapply corestep_star_plus_trans. eexact A.\n          eapply corestep_plus_one.\n            eapply rtl_corestep_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 sm_inject_separated_same_sminj.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b';\n          try rewrite (freshloc_free _ _ _ _ _ H0);\n          try rewrite (freshloc_free _ _ _ _ _ H5); intuition.\n      econstructor. econstructor; eauto.\n      intuition.\n         eapply REACH_closed_free; eassumption.\n         destruct (restrictD_Some _ _ _ _ _ Rsp).\n           eapply free_free_inject; try eassumption.\n  (* label *)\n  inv TS.\n  eexists; exists m2, mu; split.\n    right; split. apply corestep_star_zero. Lt_state.\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b;\n          try rewrite (freshloc_irrefl); intuition.\n      econstructor. econstructor; eauto.\n      intuition.\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; split.\n    left; apply corestep_plus_one. eapply rtl_corestep_exec_Inop; eauto.\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b;\n          try rewrite (freshloc_irrefl); intuition.\n      econstructor. econstructor; eauto.\n      intuition.\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  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  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. intros [A B].\n    eapply add_vars_wf; eauto. eapply add_vars_wf; eauto. apply init_mapping_wf.\n  edestruct alloc_parallel_intern as [mu' [tm' [b' [Alloc' [MInj' [IntInc [mu'SP mu'MuR]]]]]]]; eauto; try apply Zle_refl.\n  destruct mu'MuR as [A [B [C [D [E F]]]]].\n  eexists. exists tm', mu'; split.\n    left; apply corestep_plus_one. eapply rtl_corestep_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 (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  split. econstructor; try eassumption.\n           econstructor; eauto.\n           simpl. inversion MS; subst; econstructor; eauto.\n           econstructor.\n           inv MS. econstructor; try eassumption.\n                     eapply match_env_inject_incr; try eassumption.\n                     eapply tr_cont_inject_incr; eassumption.\n                       destruct H27 as [spb [spb' [SP [SP' XX]]]].\n                       exists spb, spb'; split; trivial. split; trivial.\n                       eapply IncVis; eassumption.\n                     eapply match_env_inject_incr; try eassumption.\n           eapply inject_restrict; eassumption.\n           exists sp, b'. split; trivial. split; trivial.\n             eapply restrictI_Some; try eassumption.\n           destruct (as_inj_DomRng _ _ _ _ mu'SP); trivial.\n              unfold DomSrc in H7; unfold vis.\n              remember (locBlocksSrc mu' sp) as d.\n              destruct d; trivial; simpl in *; apply eq_sym in Heqd.\n              assert (extBlocksSrc mu = extBlocksSrc mu') by eapply IntInc.\n              rewrite <- H9 in H7. unfold DomSrc in DomSP. rewrite H7 in DomSP. apply orb_false_iff in DomSP. destruct DomSP; discriminate.\n  (*as in selectionproofEff*)\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 IntInc.\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  eexists; exists m2, mu; split.\n    left; apply corestep_plus_one; constructor.\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b;\n          try rewrite (freshloc_irrefl); intuition.\n      split. econstructor; eauto. constructor.\n             eapply match_env_update_dest; eauto.\n      intuition.\nQed.\n\nLemma MATCH_effcore_diagram: forall\n         st1 m1 st1' m1' (U1 : block -> Z -> bool)\n         (CS: effstep cminsel_eff_sem ge U1 st1 m1 st1' m1')\n         st2 mu m2\n         (UHyp: forall b z, U1 b z = true ->\n                Mem.valid_block m1 b -> vis mu b = true)\n         (MTCH: MATCH st1 mu st1 m1 st2 m2),\nexists st2' m2' mu', exists U2 : block -> Z -> bool,\n  (effstep_plus rtl_eff_sem tge U2 st2 m2 st2' m2' \\/\n      effstep_star rtl_eff_sem tge U2 st2 m2 st2' m2' /\\ lt_state st1' st1)\n /\\ intern_incr mu mu' /\\\n  sm_inject_separated mu mu' m1 m2 /\\\n  sm_locally_allocated mu mu' m1 m2 m1' m2' /\\\n  MATCH st1' mu' st1' m1' st2' m2' /\\\n     (forall (b : block) (ofs : Z),\n      U2 b ofs = true ->\n      Mem.valid_block m2 b /\\\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   induction CS; intros.\n\n  (* skip seq *)\n  destruct MTCH as [MSTATE PRE]. inv MSTATE.\n  inv TS. inv TK.\n  eexists; exists m2, mu; exists EmptyEffect; split.\n     right; split. apply effstep_star_zero. Lt_state.\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\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  destruct MTCH as [MSTATE PRE]. inv MSTATE.\n  inv TS. inv TK.\n  eexists; exists m2, mu; exists EmptyEffect; split.\n    right; split. apply effstep_star_zero. Lt_state.\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\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  destruct MTCH as [MSTATE PRE]. inv MSTATE.\n  inv TS.\n  assert ((fn_code tf)!ncont = Some(Ireturn rret)\n          /\\ match_stacks (restrict (as_inj mu) (vis mu)) k cs).\n    inv TK; simpl in H; try contradiction; auto.\n  destruct H1.\n  assert (fn_stacksize tf = fn_stackspace f).\n    inv TF. auto.\n  destruct SP as [spb [spb' [X [Y Rsp]]]]; subst sp'; inv X.\n  destruct PRE as [RC [PG [GFP [Glob [SMV [WD MInj]]]]]].\n  edestruct free_parallel_inject as [tm' []]; eauto.\n  destruct (restrictD_Some _ _ _ _ _ Rsp).\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; eapply 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 sm_inject_separated_same_sminj.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b;\n          try rewrite (freshloc_free _ _ _ _ _ H4);\n          try rewrite (freshloc_free _ _ _ _ _ H0); intuition.\n  econstructor. econstructor; eauto.\n      intuition.\n      eapply REACH_closed_free; try eassumption.\n      eapply (free_free_inject _ m m' m2); try eassumption.\n  eapply FreeEffect_validblock; eassumption.\n  rewrite H3 in H8. eapply FreeEffect_PropagateLeft; eassumption.\n\n  (* assign *)\n  destruct MTCH as [MSTATE PRE]. inv MSTATE.\n  inv TS.\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  exploit Efftransl_expr_correct; eauto.\n  intros [rs' [tm' [A [B [C [D [E F]]]]]]]; subst.\n  eexists; eexists; exists mu, EmptyEffect; split.\n    right; split. eassumption. Lt_state.\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b;\n          try rewrite (freshloc_irrefl); intuition.\n      econstructor. econstructor; eauto. econstructor.\n      intuition.\n\n  (* store *)\n  destruct MTCH as [MSTATE PRE]. inv MSTATE.\n  inv TS.\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  exploit Efftransl_exprlist_correct; eauto.\n  intros [rs' [tm' [A [B [C [D [E F]]]]]]]; subst.\n  exploit Efftransl_expr_correct; eauto.\n  intros [rs'' [tm'' [F [G [J [K [L M]]]]]]]; subst.\n  destruct SP as [spb [spb' [X [Y Rsp]]]]; subst sp'; inv X.\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  edestruct eval_addressing_inject as [vaddr' []]; eauto.\n  edestruct Mem.storev_mapped_inject as [tm''' []]; eauto.\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  eexists; exists tm''', mu.\n    exists (StoreEffect vaddr' (encode_val chunk (rs'' # rd))).\n    split. left; eapply effstep_star_plus_trans.\n      eapply effstep_star_trans.\n         eapply effstep_star_sub. eexact A. intuition.\n         eapply effstep_star_sub. eexact F. intuition.\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  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality bb;\n        try rewrite (store_freshloc _ _ _ _ _ H2);\n        try rewrite (store_freshloc _ _ _ _ _ H6); intuition.\n      econstructor. econstructor; eauto. constructor.\n        exists spb, spb'. split; trivial. split; trivial.\n      intuition.\n      (*rest of this case is almost identical to SelectionproofEFF.v, instruction store*)\n      destruct vaddr; inv H2.\n        eapply REACH_Store; try eassumption.\n          inv H5. destruct (restrictD_Some _ _ _ _ _ H10); trivial.\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      assert (VaddrMu: val_inject (as_inj mu) vaddr vaddr').\n        eapply val_inject_incr; try eassumption.\n        apply restrict_incr.\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          MInj H2 VaddrMu VMu) as [mm [Hmm1 Hmm2]].\n      rewrite Hmm1 in H6. inv H6. assumption.\n      destruct (StoreEffectD _ _ _ _ H8) as [i [HI OFF]]. subst.\n        simpl in H6. inv H5; inv H2.\n          destruct (restrictD_Some _ _ _ _ _ H12).\n          destruct (as_inj_DomRng _ _ _ _ H2); trivial.\n          eapply SMV. apply H11.\n      eapply StoreEffect_PropagateLeft; eassumption.\n\n  (* call *)\n  destruct MTCH as [MSTATE PRE]. inv MSTATE.\n  inv TS; inv H.\n  (* indirect *)\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  exploit Efftransl_expr_correct; eauto.\n  intros [rs' [tm' [A [B [C [D [X ?]]]]]]]; subst m2.\n  exploit Efftransl_exprlist_correct; eauto.\n  intros [rs'' [tm'' [E [F [G [J [Y ?]]]]]]]; subst tm'.\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). rewrite H in muBB. inv muBB.\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 E.\n          eapply effstep_plus_one.\n            eapply rtl_effstep_exec_Icall; eauto.\n               simpl. rewrite J. rewrite <- H3. eassumption. simpl; eauto.\n               apply sig_transl_function; auto.\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b';\n          try rewrite (freshloc_irrefl); intuition.\n      econstructor. econstructor; eauto. econstructor; try eassumption.\n      intuition.\n  (* direct *)\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  exploit Efftransl_exprlist_correct; eauto.\n  intros [rs'' [tm'' [E [F [G [J [Y ?]]]]]]]; subst m2.\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 E.\n          eapply effstep_plus_one. eapply rtl_effstep_exec_Icall; eauto. simpl. rewrite symbols_preserved. rewrite H4.\n             rewrite Genv.find_funct_find_funct_ptr in P. eauto.\n             apply sig_transl_function; auto.\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b';\n          try rewrite (freshloc_irrefl); intuition.\n      econstructor. econstructor; eauto. econstructor; try eassumption.\n      intuition.\n\n  (* tailcall *)\n  destruct MTCH as [MSTATE PRE]. inv MSTATE.\n  inv TS; inv H.\n  (* indirect *)\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  exploit Efftransl_expr_correct; eauto.\n  intros [rs' [tm' [A [B [C [D [X ?]]]]]]]; subst m2.\n  exploit Efftransl_exprlist_correct; eauto.\n  intros [rs'' [tm'' [E [F [G [J [Y ?]]]]]]]; subst tm'.\n  exploit functions_translated; eauto. intros [tf' [P Q]].\n  exploit match_stacks_call_cont; eauto. intros [U V].\n  assert (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  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 _ _ _ _ _ H10). rewrite H7 in muBB. inv muBB.\n  rewrite Int.add_zero in H9.\n  eexists; exists tm'''; exists mu.\n    exists (FreeEffect tm'' 0 (fn_stacksize tf) spb').\n    split.\n    left; eapply effstep_star_plus_trans.\n           eapply effstep_star_trans.\n              eapply effstep_star_sub. eexact A. intuition.\n              eapply effstep_star_sub. eexact E. intuition.\n           eapply effstep_plus_one.\n             eapply rtl_effstep_exec_Itailcall; eauto.\n             simpl. rewrite J. rewrite <- H9. eassumption.\n             simpl; eauto.\n             apply sig_transl_function; auto.\n  simpl in H2; rewrite Zplus_0_r in H2. rewrite H; eauto.\n  rewrite H in *.\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  destruct (restrictD_Some _ _ _ _ _ Rsp).\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b';\n          try rewrite (freshloc_free _ _ _ _ _ H2);\n          try rewrite (freshloc_free _ _ _ _ _ H3); intuition.\n      econstructor. econstructor; eauto.\n      intuition.\n         eapply REACH_closed_free; eassumption.\n           eapply free_free_inject; try eassumption.\n         eapply FreeEffect_validblock; eassumption.\n         eapply FreeEffect_PropagateLeft; try eassumption.\n  (* direct *)\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  exploit Efftransl_exprlist_correct; eauto.\n  intros [rs'' [tm'' [E [F [G [J [Y ?]]]]]]]; subst m2.\n  exploit functions_translated; eauto. intros [tf' [P Q]].\n  exploit match_stacks_call_cont; eauto. intros [U V].\n  assert (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  eexists; exists tm''', mu.\n    exists (FreeEffect tm'' 0 (fn_stacksize tf) spb').\n    split.\n    left; eapply effstep_star_plus_trans.\n            eapply effstep_star_sub. eexact E. intuition.\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  simpl in H2; rewrite Zplus_0_r in H2; rewrite H; eauto.\n  rewrite H in *.\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  destruct (restrictD_Some _ _ _ _ _ Rsp).\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b';\n          try rewrite (freshloc_free _ _ _ _ _ H2);\n          try rewrite (freshloc_free _ _ _ _ _ H3); intuition.\n      econstructor. econstructor; eauto.\n      intuition.\n         eapply REACH_closed_free; eassumption.\n         destruct (restrictD_Some _ _ _ _ _ Rsp).\n           eapply free_free_inject; try eassumption.\n         eapply FreeEffect_validblock; eassumption.\n         eapply FreeEffect_PropagateLeft; try eassumption.\n\n  (* builtin TODO\n  inv TS.\n  exploit transl_exprlist_correct; eauto.\n  intros [rs' [tm' [E [F [G [J K]]]]]].\n  edestruct external_call_mem_extends as [tv [tm'' [A [B [C D]]]]]; eauto.\n  econstructor; split.\n  left. eapply plus_right. eexact E.\n  eapply exec_Ibuiltin. eauto.\n  eapply external_call_symbols_preserved. eauto.\n  exact symbols_preserved. exact varinfo_preserved.\n  traceEq.\n  econstructor; eauto. constructor.\n  eapply match_env_update_dest; eauto.\n\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\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  (* seq *)\n  destruct MTCH as [MSTATE PRE]. inv MSTATE.\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 sm_inject_separated_same_sminj.\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  destruct MTCH as [MSTATE PRE]. inv MSTATE.\n  inv TS.\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  exploit Efftransl_condexpr_correct; eauto.\n  intros [rs' [tm' [A [B [C [D ?]]]]]]; subst m2.\n  eexists; exists tm', mu, EmptyEffect; split.\n    left. eexact A.\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality bb;\n          try rewrite (freshloc_irrefl); intuition.\n      econstructor.\n       destruct b; econstructor; eauto.\n      intuition.\n\n  (* loop *)\n  destruct MTCH as [MSTATE PRE]. inv MSTATE.\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 sm_inject_separated_same_sminj.\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  destruct MTCH as [MSTATE PRE]. inv MSTATE.\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 sm_inject_separated_same_sminj.\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  destruct MTCH as [MSTATE PRE]. inv MSTATE.\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 sm_inject_separated_same_sminj.\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  destruct MTCH as [MSTATE PRE]. inv MSTATE.\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 sm_inject_separated_same_sminj.\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  destruct MTCH as [MSTATE PRE]. inv MSTATE.\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 sm_inject_separated_same_sminj.\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  destruct MTCH as [MSTATE PRE]. inv MSTATE.\n  inv TS.\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  exploit validate_switch_correct; eauto. intro CTM.\n  exploit Efftransl_expr_correct; eauto.\n  intros [rs' [tm' [A [B [C [D [X ?]]]]]]]; subst m2.\n  exploit Efftransl_switch_correct; eauto. inv C. auto.\n  intros [nd [rs'' [E [F G]]]].\n  eexists; eexists; exists mu, EmptyEffect; split.\n    right; split. eapply effstep_star_trans. eexact A. eexact E. Lt_state.\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b;\n          try rewrite (freshloc_irrefl); intuition.\n      econstructor. econstructor; eauto. constructor; eassumption.\n      intuition.\n\n  (* return none *)\n  destruct MTCH as [MSTATE PRE]. inv MSTATE.\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  destruct SP as [spb [spb' [SPB [SPB' Rsp]]]]; subst sp'; inv SPB.\n  edestruct free_parallel_inject as [tm''' []]; eauto.\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  rewrite H2 in *.\n  destruct (restrictD_Some _ _ _ _ _ Rsp).\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b';\n          try rewrite (freshloc_free _ _ _ _ _ H0);\n          try rewrite (freshloc_free _ _ _ _ _ H); intuition.\n      econstructor. econstructor; eauto.\n      intuition.\n         eapply REACH_closed_free; eassumption.\n         destruct (restrictD_Some _ _ _ _ _ Rsp).\n           eapply free_free_inject; try eassumption.\n         eapply FreeEffect_validblock; eassumption.\n         eapply FreeEffect_PropagateLeft; try eassumption.\n\n  (* return some *)\n  destruct MTCH as [MSTATE PRE]. inv MSTATE.\n  inv TS.\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  exploit Efftransl_expr_correct; eauto.\n  intros [rs' [tm' [A [B [C [D [E ?]]]]]]]; subst m2.\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  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.\n             eapply effstep_star_sub. eexact A. intuition.\n          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  rewrite H4 in *.\n  destruct (restrictD_Some _ _ _ _ _ Rsp).\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b';\n          try rewrite (freshloc_free _ _ _ _ _ H0);\n          try rewrite (freshloc_free _ _ _ _ _ H5); intuition.\n      econstructor. econstructor; eauto.\n      intuition.\n         eapply REACH_closed_free; eassumption.\n         destruct (restrictD_Some _ _ _ _ _ Rsp).\n           eapply free_free_inject; try eassumption.\n         eapply FreeEffect_validblock; eassumption.\n         eapply FreeEffect_PropagateLeft; try eassumption.\n\n  (* label *)\n  destruct MTCH as [MSTATE PRE]. inv MSTATE.\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 sm_inject_separated_same_sminj.\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  destruct MTCH as [MSTATE PRE]. inv MSTATE.\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 sm_inject_separated_same_sminj.\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  destruct MTCH as [MSTATE PRE]. inv MSTATE.\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  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  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. intros [A B].\n    eapply add_vars_wf; eauto. eapply add_vars_wf; eauto. apply init_mapping_wf.\n  edestruct alloc_parallel_intern as [mu' [tm' [b' [Alloc' [MInj' [IntInc [mu'SP mu'MuR]]]]]]]; eauto; try apply Zle_refl.\n  destruct mu'MuR as [A [B [C [D [E F]]]]].\n  eexists. exists tm', mu', EmptyEffect; split.\n    left; apply effstep_plus_one. 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 (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  split. econstructor; try eassumption.\n           econstructor; eauto.\n           simpl. inversion MS; subst; econstructor; eauto.\n           econstructor.\n           inv MS. econstructor; try eassumption.\n                     eapply match_env_inject_incr; try eassumption.\n                     eapply tr_cont_inject_incr; eassumption.\n                       destruct H27 as [spb [spb' [SP [SP' XX]]]].\n                       exists spb, spb'; split; trivial. split; trivial.\n                       eapply IncVis; eassumption.\n                     eapply match_env_inject_incr; try eassumption.\n           eapply inject_restrict; eassumption.\n           exists sp, b'. split; trivial. split; trivial.\n             eapply restrictI_Some; try eassumption.\n           destruct (as_inj_DomRng _ _ _ _ mu'SP); trivial.\n              unfold DomSrc in H7; unfold vis.\n              remember (locBlocksSrc mu' sp) as d.\n              destruct d; trivial; simpl in *; apply eq_sym in Heqd.\n              assert (extBlocksSrc mu = extBlocksSrc mu') by eapply IntInc.\n              rewrite <- H9 in H7. unfold DomSrc in DomSP. rewrite H7 in DomSP. apply orb_false_iff in DomSP. destruct DomSP; discriminate.\n  (*as in selectionproofEff*)\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 IntInc.\n      apply Glob in H7. rewrite <-FF; trivial.\n\n  (* no external call *)\n\n  (* return *)\n  destruct MTCH as [MSTATE PRE]. inv MSTATE.\n  inv MS.\n  destruct PRE as [RC [PG [GFP [Glob [SMV [WD MInj]]]]]].\n  eexists; exists m2, mu, EmptyEffect; split.\n    left; apply effstep_plus_one; constructor.\n  intuition.\n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b;\n          try rewrite (freshloc_irrefl); intuition.\n      split. econstructor; eauto. constructor.\n             eapply match_env_update_dest; eauto.\n      intuition.\n\n(*inductive case*)\n  assert (EHyp: forall b z, E b z = true ->\n           Mem.valid_block m b -> vis mu b = true).\n     intros. eapply UHyp; eauto.\n  destruct (IHCS _ _ _ EHyp MTCH) as [c2' [m2' [mu' [U2 [HH1 HH2]]]]].\n  exists c2', m2', mu', U2. split; trivial.\n  destruct HH2 as [? [? [? [? ?]]]].\n  repeat (split; trivial).\n    eapply (H4 _ _ H5).\n  intros. destruct (H4 _ _ H5).\n    destruct (H8 H6) as [b1 [delta [Frg [HE HP]]]]; clear H8.\n    exists b1, delta. split; trivial. split; trivial.\n    apply Mem.perm_valid_block in HP.\n    apply H; assumption.\nQed.\n\n(** The simulation proof *)\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),\nSM_simulation.SM_simulation_inject cminsel_eff_sem\n   rtl_eff_sem ge tge entrypoints.\nProof.\nintros.\nassert (GDE: genvs_domain_eq ge tge).\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    rewrite varinfo_preserved. intuition.\n apply sepcomp.effect_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 _ _ _ 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 - 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 H3.\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(*halted*)\n  { intros. destruct H as [MC [RC [PG [GFP [Glob [VAL [WD INJ]]]]]]].\n    destruct c1; inv H0. destruct k; inv H1.\n    inv MC. exists tv.\n    split. assumption.\n    split. eassumption.\n    simpl. inv MS. trivial. }\n(* at_external*)\n  { intros. destruct H as [MC [RC [PG [GFP [Glob [VAL [WD INJ]]]]]]].\n    split; trivial.\n    destruct c1; inv H0. destruct f; inv H1.\n    inv MC. simpl. exists targs; intuition.\n      apply val_list_inject_forall_inject; eassumption.\n    inv TF. trivial. }\n(* after_external*)\n  { apply MATCH_afterExternal. assumption. }\n(* order_wf *)\n  { apply lt_state_wf. }\n(* core_diagram*)\n  { intros. exploit MATCH_corestep; try eassumption.\n     intros [st2' [m2' [mu' [CS' X]]]].\n     exists st2', m2', mu'. intuition. }\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": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/sepcomp/submit_shmem/compcert_adapt/RTLgenproofEFF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.29724808334402086}}
{"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 A B X Y T PX PY Bprime Cprime : Universe, ((wd_ A B /\\ (wd_ A T /\\ (wd_ PX A /\\ (wd_ PY A /\\ (wd_ T B /\\ (wd_ B Y /\\ (wd_ A Y /\\ (wd_ B X /\\ (wd_ A X /\\ (wd_ PY Cprime /\\ (wd_ B Bprime /\\ (wd_ A Cprime /\\ (wd_ A Bprime /\\ (col_ PX A T /\\ (col_ PY A T /\\ (col_ A PX PY /\\ (col_ PX A B /\\ (col_ PY A Cprime /\\ col_ B A Bprime)))))))))))))))))) -> col_ T A B)).\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_0619.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2971272163201458}}
{"text": "Require Export DEX_ElemLemmas.\n\nImport DEX_BigStepWithTypes.DEX_BigStepWithTypes DEX_BigStep.DEX_Dom DEX_Prog.\n\nSection p.\n  Variable kobs : L.t.\n  Variable p : DEX_ExtendedProgram.\n\nLemma some_eq: forall (A:Type) (x y:A), Some x = Some y -> x = y.\nProof. intros; inversion H; auto. Qed.\n\nLemma leql_join_eq: forall (k k1 k2: L.t) , k2 = L.join k k1 -> L.leql k k2.\nProof. intros. subst; apply leql_join2; apply L.leql_refl; auto. Qed.\n\nLtac indist2_intra_normal_aux Hindistreg rn:=\n  specialize Hindistreg with rn;\n  inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist];\n  try (constructor 1 with (k:=lvl) (k':=lvl'); \n  try (rewrite MapList.get_update2; auto); auto);\n  try (constructor 2; rewrite ?DEX_Registers.get_update_old; auto).\n\nLemma indist2_intra_normal : \n forall se reg m sgn pc pc2 pc2' i r1 rt1 h1 b1 \n      r1' rt1' h1' b1' r2 rt2 h2 b2 r2' rt2' h2' b2',\n   instructionAt m pc = Some i ->\n\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   st_in kobs (DEX_ft p) b1 b1' rt1 rt1' (pc,h1,r1) (pc,h1',r1') ->\n\n   st_in kobs (DEX_ft p) b2 b2' rt2 rt2' (pc2,h2,r2) (pc2',h2',r2').\nProof.\n  intros se reg m sgn pc pc2 pc2' i r1 rt1 h1 b1 \n      r1' rt1' h1' b1' r2 rt2 h2 b2 r2' rt2' h2' b2'\n    Hins Hstep Hstep' Hindist.\n  inversion_clear Hindist.\n  destruct i; simpl in Hstep, Hstep';\n  inversion_clear Hstep in Hins Hstep' H H0;\n  inversion_clear Hstep' in H H0;\n  constructor; auto. \n  (* DEX_Move *)\n  subst.\n  inversion H as [Heqset Hindistreg].\n  constructor; auto. \n  (* proving eq_set *)\n  rewrite MapList.domain_inv; auto. rewrite MapList.domain_inv; auto.\n  intros rn.\n  destruct Reg_eq_dec with (x:=rn) (y:=rt) as [Hreg | Hreg].\n    (* rn = rt *)\n    rewrite Hreg.\n    specialize Hindistreg with (rn:=rs).  \n    inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist]. \n    constructor 1 with (k:=L.join k0 (se pc)) (k':=L.join k1 (se pc)); \n      try (rewrite MapList.get_update1; auto); auto.\n    rewrite Hget in H9; inversion H9; subst; apply not_leql_join1; auto.\n    rewrite Hget' in H19; inversion H19; subst; apply not_leql_join1; auto.\n    constructor 2. rewrite <- H7 in Hvalueindist; rewrite <- H17 in Hvalueindist.\n    rewrite ?DEX_Registers.get_update_new; auto.\n    (* rn <> rt *) \n    indist2_intra_normal_aux Hindistreg rn.\n  (* DEX_Const *)\n  subst.\n  inversion H as [Heqset Hindistreg].\n  constructor; auto.\n  (* proving eq_set *)\n  rewrite MapList.domain_inv; auto. rewrite MapList.domain_inv; auto.\n  intros rn. \n  destruct Reg_eq_dec with (x:=rn) (y:=rt) as [Hreg | Hreg].\n    (* rn = rt *)\n    rewrite Hreg.\n    constructor 2.\n    rewrite ?DEX_Registers.get_update_new.\n    constructor 1. constructor.\n    (* rn <> rt *) \n    indist2_intra_normal_aux Hindistreg rn.\n  (* DEX_Ineg *)\n  subst.\n  inversion H as [Heqset Hindistreg].\n  constructor; auto.\n  (* proving eq_set *)\n  rewrite MapList.domain_inv; auto. rewrite MapList.domain_inv; auto.\n  intros rn. \n  destruct Reg_eq_dec with (x:=rn) (y:=rt) as [Hreg | Hreg].\n    (* rn = rt *)\n    rewrite Hreg.\n    specialize Hindistreg with (rn:=rs).  \n    inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist]. \n    constructor 1 with (k:=L.join k (se pc)) (k':=L.join k0 (se pc)); \n      try (rewrite MapList.get_update1; auto); auto.\n    rewrite Hget in H7; inversion H7; subst; apply not_leql_join1; auto.\n    rewrite Hget' in H16; inversion H16; subst; apply not_leql_join1; auto.\n    constructor 2. rewrite <- H6 in Hvalueindist; rewrite <- H15 in Hvalueindist.\n    rewrite ?DEX_Registers.get_update_new; auto.\n    inversion Hvalueindist. inversion H17. constructor 1; constructor.\n    (* rn <> rt *) \n    indist2_intra_normal_aux Hindistreg rn.\n  (* DEX_Inot *)\n  subst.\n  inversion H as [Heqset Hindistreg].\n  constructor; auto.\n  (* proving eq_set *)\n  rewrite MapList.domain_inv; auto. rewrite MapList.domain_inv; auto.\n  intros rn. \n  destruct Reg_eq_dec with (x:=rn) (y:=rt) as [Hreg | Hreg].\n    (* rn = rt *)\n    rewrite Hreg.\n    specialize Hindistreg with (rn:=rs).  \n    inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist]. \n    constructor 1 with (k:=L.join k (se pc)) (k':=L.join k0 (se pc)); \n      try (rewrite MapList.get_update1; auto); auto.\n    rewrite Hget in H7; inversion H7; subst; apply not_leql_join1; auto.\n    rewrite Hget' in H16; inversion H16; subst; apply not_leql_join1; auto.\n    constructor 2. rewrite <- H6 in Hvalueindist; rewrite <- H15 in Hvalueindist.\n    rewrite ?DEX_Registers.get_update_new; auto.\n    inversion Hvalueindist. inversion H17. constructor 1; constructor.\n    (* rn <> rt *) \n    indist2_intra_normal_aux Hindistreg rn.\n  (* DEX I2b *)\n  subst.\n  inversion H as [Heqset Hindistreg].\n  constructor; auto.\n  (* proving eq_set *)\n  rewrite MapList.domain_inv; auto. rewrite MapList.domain_inv; auto.\n  intros rn. \n  destruct Reg_eq_dec with (x:=rn) (y:=rt) as [Hreg | Hreg].\n    (* rn = rt *)\n    rewrite Hreg.\n    specialize Hindistreg with (rn:=rs).  \n    inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist]. \n    constructor 1 with (k:=L.join k (se pc)) (k':=L.join k0 (se pc)); \n      try (rewrite MapList.get_update1; auto); auto.\n    rewrite Hget in H7; inversion H7; subst; apply not_leql_join1; auto.\n    rewrite Hget' in H16; inversion H16; subst; apply not_leql_join1; auto.\n    constructor 2. rewrite <- H6 in Hvalueindist; rewrite <- H15 in Hvalueindist.\n    rewrite ?DEX_Registers.get_update_new; auto.\n    inversion Hvalueindist. inversion H17. constructor 1; constructor.\n    (* rn <> rt *) \n    indist2_intra_normal_aux Hindistreg rn.\n  (* DEX_I2s *)\n  subst.\n  inversion H as [Heqset Hindistreg].\n  constructor; auto.\n  (* proving eq_set *)\n  rewrite MapList.domain_inv; auto. rewrite MapList.domain_inv; auto.\n  intros rn. \n  destruct Reg_eq_dec with (x:=rn) (y:=rt) as [Hreg | Hreg].\n    (* rn = rt *)\n    rewrite Hreg.\n    specialize Hindistreg with (rn:=rs).  \n    inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist]. \n    constructor 1 with (k:=L.join k (se pc)) (k':=L.join k0 (se pc)); \n      try (rewrite MapList.get_update1; auto); auto.\n    rewrite Hget in H7; inversion H7; subst; apply not_leql_join1; auto.\n    rewrite Hget' in H16; inversion H16; subst; apply not_leql_join1; auto.\n    constructor 2. rewrite <- H6 in Hvalueindist; rewrite <- H15 in Hvalueindist.\n    rewrite ?DEX_Registers.get_update_new; auto.\n    inversion Hvalueindist. inversion H17. constructor 1; constructor.\n    (* rn <> rt *) \n    indist2_intra_normal_aux Hindistreg rn.\n  (* DEX_IBinop *)\n  subst.\n  inversion H as [Heqset Hindistreg].\n  constructor; auto.\n  (* proving eq_set *)\n  rewrite MapList.domain_inv; auto. rewrite MapList.domain_inv; auto.\n  intros rn. \n  destruct Reg_eq_dec with (x:=rn) (y:=rt) as [Hreg | Hreg].\n    (* rn = rt *)\n    rewrite Hreg.\n    assert (Hindistreg' := Hindistreg).\n    specialize Hindistreg with (rn:=ra).\n    specialize Hindistreg' with (rn:=rb).  \n    inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist]. \n    constructor 1 with (k:=L.join k1 (L.join k2 (se pc))) (k':=L.join k0 (L.join k3 (se pc))); \n      try (rewrite MapList.get_update1; auto); auto.\n    rewrite Hget in H10; inversion H10; subst; apply not_leql_join1; auto.\n    rewrite Hget' in H23; inversion H23; subst; apply not_leql_join1; auto.\n    (* case of register b *)\n    inversion Hindistreg' as [lvl2 lvl2' Hget2 Hget2' Hleq2 Hleq2' | Hvalueindist'].\n    constructor 1 with (k:=L.join k1 (L.join k2 (se pc))) (k':=L.join k0 (L.join k3 (se pc))); \n      try (rewrite MapList.get_update1; auto); auto.\n    rewrite Hget2 in H11; inversion H11; subst.\n    apply not_leql_join2; apply not_leql_join1; auto.\n    rewrite Hget2' in H24; inversion H24; subst.\n    apply not_leql_join2; apply not_leql_join1; auto.\n    constructor 2. \n    rewrite ?DEX_Registers.get_update_new.\n    rewrite <- H8 in Hvalueindist; rewrite <- H21 in Hvalueindist.\n    rewrite <- H9 in Hvalueindist'; rewrite <- H22 in Hvalueindist'.\n    inversion Hvalueindist as [v v' Hin | Hnone]; inversion Hvalueindist' as [v2 v2' Hin' | Hnone']; \n    inversion Hin; inversion Hin'. repeat (constructor); auto.\n    (* rn <> rt *) \n    indist2_intra_normal_aux Hindistreg rn.\n  (* DEX_IBinopConst *)\n  subst.\n  inversion H as [Heqset Hindistreg].\n  constructor; auto.\n  (* proving eq_set *)\n  rewrite MapList.domain_inv; auto. rewrite MapList.domain_inv; auto.\n  intros rn. \n  destruct Reg_eq_dec with (x:=rn) (y:=rt) as [Hreg | Hreg].\n    (* rn = rt *)\n    rewrite Hreg.\n    specialize Hindistreg with (rn:=r).\n    inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist]. \n    constructor 1 with (k:=L.join k (se pc)) (k':=L.join k0 (se pc)); \n      try (rewrite MapList.get_update1; auto); auto.\n    rewrite Hget in H7; inversion H7; subst; apply not_leql_join1; auto.\n    rewrite Hget' in H16; inversion H16; subst; apply not_leql_join1; auto.\n    constructor 2. \n    rewrite ?DEX_Registers.get_update_new.\n    rewrite <- H6 in Hvalueindist; rewrite <- H15 in Hvalueindist. \n    inversion Hvalueindist as [val val' Hin | Hnone]; inversion Hin;\n    repeat (constructor); auto.\n    (* rn <> rt *) \n    indist2_intra_normal_aux Hindistreg rn.\n  (* DEX_Iget *)\n  subst.\n  inversion H as [Heqset Hindistreg].\n  constructor; auto.\n  (* proving eq_set *)\n  rewrite MapList.domain_inv; auto. rewrite MapList.domain_inv; auto.\n  intros rn. \n  destruct Reg_eq_dec with (x:=rn) (y:=rt) as [Hreg | Hreg].\n    (* rn = rt *)\n    rewrite Hreg.\n    specialize Hindistreg with (rn:=ro).\n    inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist]. \n    constructor 1 with (k:=L.join ko (L.join (se pc) (DEX_ft p f))) \n        (k':=L.join ko0 (L.join (se pc) (DEX_ft p f))); \n      try (rewrite MapList.get_update1; auto); auto.\n    rewrite Hget in H12; inversion H12; subst; apply not_leql_join1; auto.\n    rewrite Hget' in H25; inversion H25; subst; apply not_leql_join1; auto.\n    generalize (L.leql_dec (DEX_ft p f) (kobs)). \n    intro Hft; inversion Hft.\n    constructor 2. \n    rewrite ?DEX_Registers.get_update_new.\n    constructor.\n    rewrite <- H7 in Hvalueindist; rewrite <- H20 in Hvalueindist; inversion Hvalueindist.\n    apply hp_in_getfield with (kobs:=kobs) (p:=p) (h2:=h2) (h2':=h2') (loc:=loc)\n      (loc0:=loc0) (cn:=cn) (cn0:=cn0) (f:=f); auto.\n    constructor 1 with (k:=L.join ko (L.join (se pc) (DEX_ft p f))) \n        (k':=L.join ko0 (L.join (se pc) (DEX_ft p f))); \n      try (rewrite MapList.get_update1; auto); auto;\n    apply not_leql_join2; apply not_leql_join2; auto.\n    (* rn <> rt *) \n    indist2_intra_normal_aux Hindistreg rn.\n  (* DEX_Iput *)\n    (* heap indist *)\n  rewrite H29; rewrite H12.\n  generalize (L.leql_dec (DEX_ft p f) (kobs)). \n    intro Hft; inversion_clear Hft.\n  inversion H as [Heqset Hindistreg].\n  apply hp_in_putfield_ffun with (cn:=cn) (cn':=cn0); auto.\n  specialize Hindistreg with (rn:=rs).\n  inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist].\n  rewrite Hget in H14; inversion H14; subst.\n  apply not_leql_trans with (k2:=(DEX_ft p f)) in Hleq; auto.\n  contradiction.\n  rewrite <- H25 in Hvalueindist; rewrite <- H8 in Hvalueindist; inversion Hvalueindist; auto.\n  specialize Hindistreg with ro.\n  inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist].\n  rewrite Hget in H13; inversion H13; subst.\n  apply not_leql_trans with (k2:=(DEX_ft p f)) in Hleq; auto.\n  contradiction.\n  rewrite <- H24 in Hvalueindist; rewrite <- H7 in Hvalueindist; inversion Hvalueindist; auto.\n  apply hp_in_putfield_high with (cn:=cn) (cn':=cn0); auto.\n  (* DEX_New *)\n  subst.\n  inversion H as [Heqset Hindistreg].\n  constructor; auto.\n  (* proving eq_set *)\n  rewrite MapList.domain_inv; auto. rewrite MapList.domain_inv; auto.\n  intros rn. \n  destruct Reg_eq_dec with (x:=rn) (y:=rt) as [Hreg | Hreg].\n    (* rn = rt *)\n    rewrite Hreg.\n    unfold newb. destruct L.leql_dec.\n    (* update Low *)\n    constructor 2.\n    rewrite ?DEX_Registers.get_update_new.\n    constructor 1. \n    apply Value_in_extends with (kobs:=kobs) (p:=p) (h1:=h1) (h2:=h1'); auto.\n    apply DEX_Heap.new_fresh_location with (p:=DEX_prog p) (h':=h2) (lt:=(DEX_Heap.DEX_LocationObject c)); auto.\n    apply DEX_Heap.new_fresh_location with (p:=DEX_prog p) (h':=h2') (lt:=(DEX_Heap.DEX_LocationObject c)); auto.\n    (* update High *)\n    apply Reg_in_upd_high; auto.\n    (* rn <> rt *) \n    unfold newb. destruct L.leql_dec.\n    indist2_intra_normal_aux Hindistreg rn.\n      apply ffun_extends_val_in_opt; auto.\n    indist2_intra_normal_aux Hindistreg rn.\n    (* heap indist *)\n  unfold newb. destruct (L.leql_dec (se pc) kobs); auto.\n  apply ffun_extends_hp_in with (c:=c) (h:=h1) (h':=h1'); auto. \n  apply ffun_extends_hp_in_simpl with (c:=c) (c':=c) (h:=h1) (h':=h1') (loc:=loc) (loc':=loc0); auto.\nQed.\n\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_ElemLemmaNormalIntra2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032313, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2971213079078571}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\nFrom compcert Require Import Raux.\nFrom compcert Require Import Defs.\nFrom compcert Require Import Round_pred.\nFrom compcert Require Import Generic_fmt.\nFrom compcert Require Import Float_prop.\nFrom compcert Require Import Ulp.\n\nNotation ZnearestE := (Znearest (fun x => negb (Z.even x))).\n\nSection Fcore_rnd_NE.\n\nVariable beta : radix.\n\nNotation bpow e := (bpow beta e).\n\nVariable fexp : Z -> Z.\n\nContext { valid_exp : Valid_exp fexp }.\n\nNotation format := (generic_format beta fexp).\nNotation canonical := (canonical beta fexp).\n\nDefinition NE_prop (_ : R) f :=\nexists g : float beta, f = F2R g /\\ canonical g /\\ Z.even (Fnum g) = true.\n\nDefinition Rnd_NE_pt :=\nRnd_NG_pt format NE_prop.\n\nDefinition DN_UP_parity_pos_prop :=\nforall x xd xu,\n(0 < x)%R ->\n~ format x ->\ncanonical xd ->\ncanonical xu ->\nF2R xd = round beta fexp Zfloor x ->\nF2R xu = round beta fexp Zceil x ->\nZ.even (Fnum xu) = negb (Z.even (Fnum xd)).\n\nDefinition DN_UP_parity_prop :=\nforall x xd xu,\n~ format x ->\ncanonical xd ->\ncanonical xu ->\nF2R xd = round beta fexp Zfloor x ->\nF2R xu = round beta fexp Zceil x ->\nZ.even (Fnum xu) = negb (Z.even (Fnum xd)).\n\nLemma DN_UP_parity_aux :\nDN_UP_parity_pos_prop ->\nDN_UP_parity_prop.\nProof. hammer_hook \"Round_NE\" \"Round_NE.DN_UP_parity_aux\".\nintros Hpos x xd xu Hfx Hd Hu Hxd Hxu.\ndestruct (total_order_T 0 x) as [[Hx|Hx]|Hx].\n\nexact (Hpos x xd xu Hx Hfx Hd Hu Hxd Hxu).\nelim Hfx.\nrewrite <- Hx.\napply generic_format_0.\n\nassert (Hx': (0 < -x)%R).\napply Ropp_lt_cancel.\nnow rewrite Ropp_involutive, Ropp_0.\ndestruct xd as (md, ed).\ndestruct xu as (mu, eu).\nsimpl.\nrewrite <- (Bool.negb_involutive (Z.even mu)).\napply f_equal.\napply sym_eq.\nrewrite <- (Z.even_opp mu), <- (Z.even_opp md).\nchange (Z.even (Fnum (Float beta (-md) ed)) = negb (Z.even (Fnum (Float beta (-mu) eu)))).\napply (Hpos (-x)%R _ _ Hx').\nintros H.\napply Hfx.\nrewrite <- Ropp_involutive.\nnow apply generic_format_opp.\nnow apply canonical_opp.\nnow apply canonical_opp.\nrewrite round_DN_opp, F2R_Zopp.\nnow apply f_equal.\nrewrite round_UP_opp, F2R_Zopp.\nnow apply f_equal.\nQed.\n\nClass Exists_NE :=\nexists_NE : Z.even beta = false \\/ forall e,\n((fexp e < e)%Z -> (fexp (e + 1) < e)%Z) /\\ ((e <= fexp e)%Z -> fexp (fexp e + 1) = fexp e).\n\nContext { exists_NE_ : Exists_NE }.\n\nTheorem DN_UP_parity_generic_pos :\nDN_UP_parity_pos_prop.\nProof with auto with typeclass_instances. hammer_hook \"Round_NE\" \"Round_NE.DN_UP_parity_generic_pos\".\nintros x xd xu H0x Hfx Hd Hu Hxd Hxu.\ndestruct (mag beta x) as (ex, Hexa).\nspecialize (Hexa (Rgt_not_eq _ _ H0x)).\ngeneralize Hexa. intros Hex.\nrewrite (Rabs_pos_eq _ (Rlt_le _ _ H0x)) in Hex.\ndestruct (Zle_or_lt ex (fexp ex)) as [Hxe|Hxe].\n\nassert (Hd3 : Fnum xd = Z0).\napply eq_0_F2R with beta (Fexp xd).\nchange (F2R xd = R0).\nrewrite Hxd.\napply round_DN_small_pos with (1 := Hex) (2 := Hxe).\nassert (Hu3 : xu = Float beta (1 * Zpower beta (fexp ex - fexp (fexp ex + 1))) (fexp (fexp ex + 1))).\napply canonical_unique with (1 := Hu).\napply (f_equal fexp).\nrewrite <- F2R_change_exp.\nnow rewrite F2R_bpow, mag_bpow.\nnow apply valid_exp.\nrewrite <- F2R_change_exp.\nrewrite F2R_bpow.\napply sym_eq.\nrewrite Hxu.\napply sym_eq.\napply round_UP_small_pos with (1 := Hex) (2 := Hxe).\nnow apply valid_exp.\nrewrite Hd3, Hu3.\nrewrite Zmult_1_l.\nsimpl.\ndestruct exists_NE_ as [H|H].\napply Zeven_Zpower_odd with (2 := H).\napply Zle_minus_le_0.\nnow apply valid_exp.\nrewrite (proj2 (H ex)).\nnow rewrite Zminus_diag.\nexact Hxe.\n\nassert (Hd4: (bpow (ex - 1) <= Rabs (F2R xd) < bpow ex)%R).\nrewrite Rabs_pos_eq.\nrewrite Hxd.\nsplit.\napply (round_DN_pt beta fexp x).\napply generic_format_bpow.\nring_simplify (ex - 1 + 1)%Z.\nomega.\napply Hex.\napply Rle_lt_trans with (2 := proj2 Hex).\napply (round_DN_pt beta fexp x).\nrewrite Hxd.\napply (round_DN_pt beta fexp x).\napply generic_format_0.\nnow apply Rlt_le.\nassert (Hxe2 : (fexp (ex + 1) <= ex)%Z) by now apply valid_exp.\nassert (Hud: (F2R xu = F2R xd + ulp beta fexp x)%R).\nrewrite Hxu, Hxd.\nnow apply round_UP_DN_ulp.\ndestruct (total_order_T (bpow ex) (F2R xu)) as [[Hu2|Hu2]|Hu2].\n\nelim (Rlt_not_le _ _ Hu2).\nrewrite Hxu.\napply round_bounded_large_pos...\n\nassert (Hu3: xu = Float beta (1 * Zpower beta (ex - fexp (ex + 1))) (fexp (ex + 1))).\napply canonical_unique with (1 := Hu).\napply (f_equal fexp).\nrewrite <- F2R_change_exp.\nnow rewrite F2R_bpow, mag_bpow.\nnow apply valid_exp.\nrewrite <- Hu2.\napply sym_eq.\nrewrite <- F2R_change_exp.\napply F2R_bpow.\nexact Hxe2.\nassert (Hd3: xd = Float beta (Zpower beta (ex - fexp ex) - 1) (fexp ex)).\nassert (H: F2R xd = F2R (Float beta (Zpower beta (ex - fexp ex) - 1) (fexp ex))).\nunfold F2R. simpl.\nrewrite minus_IZR.\nunfold Rminus.\nrewrite Rmult_plus_distr_r.\nrewrite IZR_Zpower, <- bpow_plus.\nring_simplify (ex - fexp ex + fexp ex)%Z.\nrewrite Hu2, Hud.\nrewrite ulp_neq_0;[idtac|now apply Rgt_not_eq].\nunfold cexp.\nrewrite mag_unique with beta x ex.\nunfold F2R.\nsimpl. ring.\nrewrite Rabs_pos_eq.\nexact Hex.\nnow apply Rlt_le.\napply Zle_minus_le_0.\nnow apply Zlt_le_weak.\napply canonical_unique with (1 := Hd) (3 := H).\napply (f_equal fexp).\nrewrite <- H.\napply sym_eq.\nnow apply mag_unique.\nrewrite Hd3, Hu3.\nunfold Fnum.\nrewrite Z.even_mul. simpl.\nunfold Zminus at 2.\nrewrite Z.even_add.\nrewrite eqb_sym. simpl.\nfold (negb (Z.even (beta ^ (ex - fexp ex)))).\nrewrite Bool.negb_involutive.\nrewrite (Z.even_pow beta (ex - fexp ex)). 2: omega.\ndestruct exists_NE_.\nrewrite H.\napply Zeven_Zpower_odd with (2 := H).\nnow apply Zle_minus_le_0.\napply Z.even_pow.\nspecialize (H ex).\nomega.\n\nrevert Hud.\nrewrite ulp_neq_0;[idtac|now apply Rgt_not_eq].\nunfold F2R.\nrewrite Hd, Hu.\nunfold cexp.\nrewrite mag_unique with beta (F2R xu) ex.\nrewrite mag_unique with (1 := Hd4).\nrewrite mag_unique with (1 := Hexa).\nintros H.\nreplace (Fnum xu) with (Fnum xd + 1)%Z.\nrewrite Z.even_add.\nnow apply eqb_sym.\napply sym_eq.\napply eq_IZR.\nrewrite plus_IZR.\napply Rmult_eq_reg_r with (bpow (fexp ex)).\nrewrite H.\nsimpl. ring.\napply Rgt_not_eq.\napply bpow_gt_0.\nrewrite Rabs_pos_eq.\nsplit.\napply Rle_trans with (1 := proj1 Hex).\nrewrite Hxu.\napply (round_UP_pt beta fexp x).\nexact Hu2.\napply Rlt_le.\napply Rlt_le_trans with (1 := H0x).\nrewrite Hxu.\napply (round_UP_pt beta fexp x).\nQed.\n\nTheorem DN_UP_parity_generic :\nDN_UP_parity_prop.\nProof. hammer_hook \"Round_NE\" \"Round_NE.DN_UP_parity_generic\".\napply DN_UP_parity_aux.\napply DN_UP_parity_generic_pos.\nQed.\n\nTheorem Rnd_NE_pt_total :\nround_pred_total Rnd_NE_pt.\nProof. hammer_hook \"Round_NE\" \"Round_NE.Rnd_NE_pt_total\".\napply satisfies_any_imp_NG.\nnow apply generic_format_satisfies_any.\nintros x d u Hf Hd Hu.\ngeneralize (proj1 Hd).\nunfold generic_format.\nset (ed := cexp beta fexp d).\nset (md := Ztrunc (scaled_mantissa beta fexp d)).\nintros Hd1.\ncase_eq (Z.even md) ; [ intros He | intros Ho ].\nright.\nexists (Float beta md ed).\nunfold Generic_fmt.canonical.\nrewrite <- Hd1.\nnow repeat split.\nleft.\ngeneralize (proj1 Hu).\nunfold generic_format.\nset (eu := cexp beta fexp u).\nset (mu := Ztrunc (scaled_mantissa beta fexp u)).\nintros Hu1.\nrewrite Hu1.\neexists ; repeat split.\nunfold Generic_fmt.canonical.\nnow rewrite <- Hu1.\nrewrite (DN_UP_parity_generic x (Float beta md ed) (Float beta mu eu)).\nsimpl.\nnow rewrite Ho.\nexact Hf.\nunfold Generic_fmt.canonical.\nnow rewrite <- Hd1.\nunfold Generic_fmt.canonical.\nnow rewrite <- Hu1.\nrewrite <- Hd1.\napply Rnd_DN_pt_unique with (1 := Hd).\nnow apply round_DN_pt.\nrewrite <- Hu1.\napply Rnd_UP_pt_unique with (1 := Hu).\nnow apply round_UP_pt.\nQed.\n\nTheorem Rnd_NE_pt_monotone :\nround_pred_monotone Rnd_NE_pt.\nProof. hammer_hook \"Round_NE\" \"Round_NE.Rnd_NE_pt_monotone\".\napply Rnd_NG_pt_monotone.\nintros x d u Hd Hdn Hu Hun (cd, (Hd1, Hd2)) (cu, (Hu1, Hu2)).\ndestruct (Req_dec x d) as [Hx|Hx].\nrewrite <- Hx.\napply sym_eq.\napply Rnd_UP_pt_idempotent with (1 := Hu).\nrewrite Hx.\napply Hd.\nrewrite (DN_UP_parity_aux DN_UP_parity_generic_pos x cd cu) in Hu2 ; try easy.\nnow rewrite (proj2 Hd2) in Hu2.\nintros Hf.\napply Hx.\napply sym_eq.\nnow apply Rnd_DN_pt_idempotent with (1 := Hd).\nrewrite <- Hd1.\napply Rnd_DN_pt_unique with (1 := Hd).\nnow apply round_DN_pt.\nrewrite <- Hu1.\napply Rnd_UP_pt_unique with (1 := Hu).\nnow apply round_UP_pt.\nQed.\n\nTheorem Rnd_NE_pt_round :\nround_pred Rnd_NE_pt.\nProof. hammer_hook \"Round_NE\" \"Round_NE.Rnd_NE_pt_round\".\nsplit.\napply Rnd_NE_pt_total.\napply Rnd_NE_pt_monotone.\nQed.\n\nLemma round_NE_pt_pos :\nforall x,\n(0 < x)%R ->\nRnd_NE_pt x (round beta fexp ZnearestE x).\nProof with auto with typeclass_instances. hammer_hook \"Round_NE\" \"Round_NE.round_NE_pt_pos\".\nintros x Hx.\nsplit.\nnow apply round_N_pt.\nunfold NE_prop.\nset (mx := scaled_mantissa beta fexp x).\nset (xr := round beta fexp ZnearestE x).\ndestruct (Req_dec (mx - IZR (Zfloor mx)) (/2)) as [Hm|Hm].\n\nleft.\nexists (Float beta (Ztrunc (scaled_mantissa beta fexp xr)) (cexp beta fexp xr)).\nsplit.\napply round_N_pt...\nsplit.\nunfold Generic_fmt.canonical. simpl.\napply f_equal.\napply round_N_pt...\nsimpl.\nunfold xr, round, Znearest.\nfold mx.\nrewrite Hm.\nrewrite Rcompare_Eq. 2: apply refl_equal.\ncase_eq (Z.even (Zfloor mx)) ; intros Hmx.\n\nchange (Z.even (Ztrunc (scaled_mantissa beta fexp (round beta fexp Zfloor x))) = true).\ndestruct (Rle_or_lt (round beta fexp Zfloor x) 0) as [Hr|Hr].\nrewrite (Rle_antisym _ _ Hr).\nunfold scaled_mantissa.\nrewrite Rmult_0_l.\nnow rewrite Ztrunc_IZR.\nrewrite <- (round_0 beta fexp Zfloor).\napply round_le...\nnow apply Rlt_le.\nrewrite scaled_mantissa_DN...\nnow rewrite Ztrunc_IZR.\n\nchange (Z.even (Ztrunc (scaled_mantissa beta fexp (round beta fexp Zceil x))) = true).\ndestruct (mag beta x) as (ex, Hex).\nspecialize (Hex (Rgt_not_eq _ _ Hx)).\nrewrite (Rabs_pos_eq _ (Rlt_le _ _ Hx)) in Hex.\ndestruct (Z_lt_le_dec (fexp ex) ex) as [He|He].\n\nassert (Hu := round_bounded_large_pos _ _ Zceil _ _ He Hex).\nassert (Hfc: Zceil mx = (Zfloor mx + 1)%Z).\napply Zceil_floor_neq.\nintros H.\nrewrite H in Hm.\nunfold Rminus in Hm.\nrewrite Rplus_opp_r in Hm.\nelim (Rlt_irrefl 0).\nrewrite Hm at 2.\napply Rinv_0_lt_compat.\nnow apply IZR_lt.\ndestruct (proj2 Hu) as [Hu'|Hu'].\n\nunfold scaled_mantissa.\nrewrite cexp_fexp_pos with (1 := conj (proj1 Hu) Hu').\nunfold round, F2R. simpl.\nrewrite cexp_fexp_pos with (1 := Hex).\nrewrite Rmult_assoc, <- bpow_plus, Zplus_opp_r, Rmult_1_r.\nrewrite Ztrunc_IZR.\nfold mx.\nrewrite Hfc.\nnow rewrite Z.even_add, Hmx.\n\nrewrite Hu'.\nunfold scaled_mantissa, cexp.\nrewrite mag_bpow.\nrewrite <- bpow_plus, <- IZR_Zpower.\nrewrite Ztrunc_IZR.\ncase_eq (Z.even beta) ; intros Hr.\ndestruct exists_NE_ as [Hs|Hs].\nnow rewrite Hs in Hr.\ndestruct (Hs ex) as (H,_).\nrewrite Z.even_pow.\nexact Hr.\nomega.\nassert (Z.even (Zfloor mx) = true). 2: now rewrite H in Hmx.\nreplace (Zfloor mx) with (Zceil mx + -1)%Z by omega.\nrewrite Z.even_add.\napply eqb_true.\nunfold mx.\nreplace (Zceil (scaled_mantissa beta fexp x)) with (Zpower beta (ex - fexp ex)).\nrewrite Zeven_Zpower_odd with (2 := Hr).\neasy.\nomega.\napply eq_IZR.\nrewrite IZR_Zpower. 2: omega.\napply Rmult_eq_reg_r with (bpow (fexp ex)).\nunfold Zminus.\nrewrite bpow_plus.\nrewrite Rmult_assoc, <- bpow_plus, Zplus_opp_l, Rmult_1_r.\npattern (fexp ex) ; rewrite <- cexp_fexp_pos with (1 := Hex).\nnow apply sym_eq.\napply Rgt_not_eq.\napply bpow_gt_0.\ngeneralize (proj1 (valid_exp ex) He).\nomega.\n\nassert (Z.even (Zfloor mx) = true). 2: now rewrite H in Hmx.\nunfold mx, scaled_mantissa.\nrewrite cexp_fexp_pos with (1 := Hex).\nnow rewrite mantissa_DN_small_pos.\n\nright.\nintros g Hg.\ndestruct (Req_dec x g) as [Hxg|Hxg].\nrewrite <- Hxg.\napply sym_eq.\napply round_generic...\nrewrite Hxg.\napply Hg.\nset (d := round beta fexp Zfloor x).\nset (u := round beta fexp Zceil x).\napply Rnd_N_pt_unique with (d := d) (u := u) (4 := Hg).\nnow apply round_DN_pt.\nnow apply round_UP_pt.\n2: now apply round_N_pt.\nrewrite <- (scaled_mantissa_mult_bpow beta fexp x).\nunfold d, u, round, F2R. simpl. fold mx.\nrewrite <- 2!Rmult_minus_distr_r.\nintros H.\napply Rmult_eq_reg_r in H.\napply Hm.\napply Rcompare_Eq_inv.\nrewrite Rcompare_floor_ceil_middle.\nnow apply Rcompare_Eq.\ncontradict Hxg.\napply sym_eq.\napply Rnd_N_pt_idempotent with (1 := Hg).\nrewrite <- (scaled_mantissa_mult_bpow beta fexp x).\nfold mx.\nrewrite <- Hxg.\nchange (IZR (Zfloor mx) * bpow (cexp beta fexp x))%R with d.\nnow eapply round_DN_pt.\napply Rgt_not_eq.\napply bpow_gt_0.\nQed.\n\nTheorem round_NE_opp :\nforall x,\nround beta fexp ZnearestE (-x) = (- round beta fexp ZnearestE x)%R.\nProof. hammer_hook \"Round_NE\" \"Round_NE.round_NE_opp\".\nintros x.\nunfold round. simpl.\nrewrite scaled_mantissa_opp, cexp_opp.\nrewrite Znearest_opp.\nrewrite <- F2R_Zopp.\napply (f_equal (fun v => F2R (Float beta (-v) _))).\nset (m := scaled_mantissa beta fexp x).\nunfold Znearest.\ncase Rcompare ; trivial.\napply (f_equal (fun (b : bool) => if b then Zceil m else Zfloor m)).\nrewrite Bool.negb_involutive.\nrewrite Z.even_opp.\nrewrite Z.even_add.\nnow rewrite eqb_sym.\nQed.\n\nLemma round_NE_abs:\nforall x : R,\nround beta fexp ZnearestE (Rabs x) = Rabs (round beta fexp ZnearestE x).\nProof with auto with typeclass_instances. hammer_hook \"Round_NE\" \"Round_NE.round_NE_abs\".\nintros x.\napply sym_eq.\nunfold Rabs at 2.\ndestruct (Rcase_abs x) as [Hx|Hx].\nrewrite round_NE_opp.\napply Rabs_left1.\nrewrite <- (round_0 beta fexp ZnearestE).\napply round_le...\nnow apply Rlt_le.\napply Rabs_pos_eq.\nrewrite <- (round_0 beta fexp ZnearestE).\napply round_le...\nnow apply Rge_le.\nQed.\n\nTheorem round_NE_pt :\nforall x,\nRnd_NE_pt x (round beta fexp ZnearestE x).\nProof with auto with typeclass_instances. hammer_hook \"Round_NE\" \"Round_NE.round_NE_pt\".\nintros x.\ndestruct (total_order_T x 0) as [[Hx|Hx]|Hx].\napply Rnd_NG_pt_opp_inv.\napply generic_format_opp.\nunfold NE_prop.\nintros _ f ((mg,eg),(H1,(H2,H3))).\nexists (Float beta (- mg) eg).\nrepeat split.\nrewrite H1.\nnow rewrite F2R_Zopp.\nnow apply canonical_opp.\nsimpl.\nnow rewrite Z.even_opp.\nrewrite <- round_NE_opp.\napply round_NE_pt_pos.\nnow apply Ropp_0_gt_lt_contravar.\nrewrite Hx, round_0...\napply Rnd_NG_pt_refl.\napply generic_format_0.\nnow apply round_NE_pt_pos.\nQed.\n\nEnd Fcore_rnd_NE.\n\n\nNotation rndNE := ZnearestE (only parsing).\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/Round_NE.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.29712130790785707}}
{"text": "(* En este archivo se demuestra la corrección de la acción revoke *)\nRequire Export Exec.\nRequire Export Implementacion.\nRequire Export AuxFunsCorrect.\nRequire Export ListAuxFuns.\nRequire Import Classical.\nRequire Import Estado.\nRequire Import DefBasicas.\nRequire Import EqTheorems.\nRequire Import Semantica.\nRequire Import Operaciones.\nRequire Import ErrorManagement.\nRequire Import Maps.\nRequire Import Tacticas.\nRequire Import ValidStateLemmas.\n\nSection Revoke.\n\nLemma postRevokeCorrect : forall (s:System) (a:idApp) (p:Perm), (pre (revoke p a) s) -> validstate s -> post_revoke p a s (revoke_post p a s).\nProof.\n    intros.\n    unfold post_revoke.\n    split. simpl; auto.\n    simpl in H.\n    unfold pre_revoke in H;simpl in H.\n    destruct H.\n    destruct H as [lPerm H2].\n    destruct H2.\n\n    split.\n    unfold revokePerm.\n    unfold revoke_post;unfold revokePermission;simpl.\n    rewrite H.\n    split;intros.\n    elim (classic (a=a'));intros.\n    exists lPerm.\n    \n    split.\n    rewrite <- H4.\n    auto.\n    intros.\n    rewrite <- H4 in H3.\n    rewrite <-(addAndApply idApp_eq a (remove Perm_eq p lPerm) (perms (state s))) in H3.\n    inversion H3.\n    rewrite <- H7 in H5.\n    apply removeSthElse in H5.\n    destruct H5;auto.\n\n    exists lPerm'.\n    split.\n    rewrite overrideNotEq in H3; auto.\n    intros;auto.\n\n    split;intros.\n    elim (classic (a=a'));intros.\n    exists (remove Perm_eq p lPerm).\n    split.\n    rewrite H4.\n    symmetry.\n    apply addAndApply.\n    intros.\n    split;auto.\n    symmetry.\n    apply (notInRemove Perm lPerm p' p Perm_eq ).\n    rewrite H4 in H.\n    rewrite H in H3.\n    inversion H3.\n    auto.\n    auto.\n\n    exists lPerm0.\n    split.\n    rewrite overrideNotEq.\n    auto.\n    auto.\n    intros.\n    contradiction.\n    split.\n    exists (remove Perm_eq p lPerm).\n    split.\n    symmetry.\n    apply addAndApply.\n    rewrite <-removeSthElse.\n    unfold not;intros.\n    destruct H3.\n    apply H3;auto.\n    apply addPreservesCorrectness.\n    apply permsCorrect;auto.\n    repeat (split;auto).\nQed.\n\nLemma notPreRevokeThenError : forall (s:System) (a:idApp) (p:Perm), ~(pre (revoke p a) s) -> validstate s -> exists ec : ErrorCode, response (step s (revoke p a)) = error ec /\\ ErrorMsg s (revoke p a) ec /\\ s = system (step s (revoke p a)).\nProof.\n    intros.\n    simpl.\n    simpl in H.\n    unfold revoke_safe, revoke_pre.\n    case_eq (negb (InBool Perm Perm_eq p (grantedPermsForApp a s))); intros.\n    simpl. exists perm_wasnt_granted. auto.\n    case_eq (isSomethingBool idGrp (maybeGrp p)); intros.\n    simpl. exists perm_is_grouped. split; auto. split; auto.\n    unfold isSomethingBool in H2.\n    destruct (maybeGrp p).\n    exists i; auto. inversion H2.\n\n    destruct H.\n    unfold pre_revoke.\n    split.\n    rewrite negb_false_iff in H1.\n    unfold InBool in H1.\n    rewrite existsb_exists in H1.\n    destruct H1 as [p' [H1 H3]].\n    unfold grantedPermsForApp in H1.\n    case_eq (map_apply idApp_eq (perms (state s)) a); intros.\n    rewrite H in H1. exists l.\n    destruct (Perm_eq p p'). rewrite e. auto.\n    inversion H3.\n    rewrite H in H1. inversion H1.\n    unfold isSomethingBool in H2.\n    destruct (maybeGrp p).\n    inversion H2. auto.\nQed.\n\nLemma revokeIsSound : forall (s:System) (a:idApp) (p:Perm),\n        validstate s -> exec s (revoke p a) (system (step s (revoke p a))) (response (step s (revoke p a))).\nProof.\n    intros.\n    unfold exec.\n    split.\n    auto.\n    elim (classic (pre (revoke p a) s));intro.\n    left.\n    assert(revoke_pre p a s = None).\n    unfold revoke_pre.\n    destruct H0.\n    destruct H0.\n    \n    assert (InBool Perm Perm_eq p (grantedPermsForApp a s) = true).\n    unfold InBool.\n    rewrite existsb_exists.\n    exists p.\n    split.\n    destruct H0.\n    unfold grantedPermsForApp.\n    rewrite H0.\n    auto.\n    destruct Perm_eq; auto.\n    rewrite H1.\n    rewrite H2. simpl.\n    auto.\n\n    unfold step;simpl.\n    unfold revoke_safe;simpl.\n    rewrite H1;simpl.\n    split;auto.\n    split;auto.\n    apply postRevokeCorrect;auto.\n    right.\n    apply notPreRevokeThenError;auto.\n    \nQed.\nEnd Revoke.\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/RevokeIsSound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.29699859004258317}}
{"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.AST.\nRequire Import compcert.common.Values.\nRequire Import compcert.common.Memory.\nRequire Import compcert.common.Events.\nRequire Import compcert.common.Globalenvs.\n\nRequire Import VST.sepcomp.mem_lemmas.\n\nNotation val_inject:=Val.inject.\n\n(*A value that is (if its a pointer) not dangling wrt m - a condition\n like this will probably be need to imposed on after-external return\n values (and thus also on the values returned by halted)*)\nDefinition val_valid (v:val) (m:mem):Prop :=\n     match v with Vptr b ofs => Mem.valid_block m b | _ => True\n     end.\n\n(*In fact val_valid is a slight relaxtion of valid_pointer*)\nLemma valid_ptr_val_valid: forall b ofs m,\n    Mem.valid_pointer m b ofs = true -> val_valid (Vptr b (Ptrofs.repr ofs)) m.\nProof. intros.\n  apply Mem.valid_pointer_nonempty_perm in H. eapply Mem.perm_valid_block. apply H.\nQed.\n\nLemma extends_valvalid: forall m1 m2 (Ext: Mem.extends m1 m2) v,\n        val_valid v m1 <-> val_valid v m2.\nProof. intros.\n  split; intros. destruct v; simpl in *; try econstructor.\n     eapply (Mem.valid_block_extends _ _ _ Ext). apply H.\n  destruct v; simpl in *; try econstructor.\n     eapply (Mem.valid_block_extends _ _ _ Ext). apply H.\nQed.\n\nLemma inject_valvalid: forall j m1 m2 (Inj: Mem.inject j m1 m2) v2 (V:val_valid v2 m2) v1,\n             val_inject j v1 v2 -> val_valid v1 m1.\nProof. intros.\n  inv H; repeat constructor.\n     simpl in *. eapply Mem.valid_block_inject_1; eassumption.\nQed.\n\n(*Preservation of val_valid along an injection only holds\n  if the LHS value is defined*)\nLemma inject_valvalid_1:\n  forall (j : meminj) (m1 m2 : mem),\n  Mem.inject j m1 m2 ->\n  forall v1 : val,\n  val_valid v1 m1 -> forall v2 : val, val_inject j v1 v2 ->\n  match v1 with Vundef => True\n      | _ => val_valid v2 m2\n  end.\nProof. intros.\n  destruct v1; auto; inv H1; auto.\n  simpl in *.\n  eapply Mem.valid_block_inject_2; eassumption.\nQed.\n\n(*memories that do not contain \"dangling pointers\"*)\nDefinition mem_wd m := Mem.inject_neutral (Mem.nextblock m) m.\n\nLemma align_chunk_0: forall chunk, (align_chunk chunk | 0).\nProof.\n  intros chunk. destruct chunk; simpl; apply Z.divide_0_r.\nQed.\n\nLemma mem_wdI: forall m,\n  (forall (b:block) ofs  (R:Mem.perm m b ofs Cur Readable),\n    memval_inject  (Mem.flat_inj (Mem.nextblock m))\n    (ZMap.get ofs (PMap.get b (Mem.mem_contents m)))\n    (ZMap.get ofs (PMap.get b (Mem.mem_contents m)))) -> mem_wd m.\nProof. intros.\n  split; intros.\n     apply flatinj_E in  H0. destruct H0 as [? [? ?]]; subst. rewrite Zplus_0_r. trivial.\n     apply flatinj_E in  H0. destruct H0 as [? [? ?]]; subst. apply align_chunk_0.\n     apply flatinj_E in  H0. destruct H0 as [? [? ?]]; subst. rewrite Zplus_0_r.\n        apply H. apply H1.\nQed.\n\nLemma mem_wd_E: forall m, mem_wd m ->  Mem.inject (Mem.flat_inj (Mem.nextblock m)) m m.\nProof. intros. apply Mem.neutral_inject. apply H. Qed.\n\nLemma meminj_split_flatinjR: forall j m m' (J:Mem.inject j m' m), mem_wd m ->\n     j = compose_meminj j (Mem.flat_inj (Mem.nextblock m)).\nProof. intros. apply mem_wd_E in H.\n   unfold  compose_meminj.\n   apply extensionality. intro b.\n   remember (j b).\n   destruct o; trivial. destruct p. unfold Mem.flat_inj in *.\n   destruct (plt b0 (Mem.nextblock m)).\n     rewrite Zplus_0_r. trivial.\n   inv J. apply eq_sym in Heqo. specialize (mi_mappedblocks _ _ _ Heqo).\n               exfalso. unfold Mem.valid_block in mi_mappedblocks. contradiction.\nQed.\n\nLemma meminj_split_flatinjL: forall j m m' (J:Mem.inject j m m'), mem_wd m ->\n     j = compose_meminj (Mem.flat_inj (Mem.nextblock m)) j.\nProof. intros. apply mem_wd_E in H.\n   unfold  compose_meminj.\n   apply extensionality. intro b.\n   unfold Mem.flat_inj in *.\n   destruct (plt b (Mem.nextblock m)).\n     remember (j b). destruct o. destruct p0.  rewrite Zplus_0_l. trivial. trivial.\n  inv J. apply mi_freeblocks. assumption.\nQed.\n\nLemma mem_wd_inject_splitL: forall j m1 m2\n              (J:Mem.inject j m1 m2)  (WD: mem_wd m1),\n     Mem.inject (Mem.flat_inj (Mem.nextblock m1)) m1 m1\n     /\\ j = compose_meminj (Mem.flat_inj (Mem.nextblock m1)) j.\nProof. intros.\n    split. apply mem_wd_E. apply WD.\n    eapply (meminj_split_flatinjL _ _ _ J WD).\nQed.\n\nLemma mem_wd_inject_splitR: forall j m1 m2\n              (J:Mem.inject j m1 m2)  (WD: mem_wd m2),\n     Mem.inject (Mem.flat_inj (Mem.nextblock m2)) m2 m2\n     /\\ j = compose_meminj j (Mem.flat_inj (Mem.nextblock m2)).\nProof. intros.\n    split. apply mem_wd_E. apply WD.\n    eapply (meminj_split_flatinjR _ _ _ J WD).\nQed.\n\n(*Preservation of mem_wd by memory operations*)\nLemma mem_wd_empty: mem_wd Mem.empty.\nProof.  apply Mem.empty_inject_neutral. Qed.\n\nLemma  mem_wd_alloc: forall m b lo hi m' (ALL: Mem.alloc m lo hi = (m',b))\n     (WDm: mem_wd m), mem_wd m'.\nProof. intros. unfold mem_wd in *.\n  rewrite (Mem.nextblock_alloc _ _ _ _ _ ALL).\n  eapply (Mem.alloc_inject_neutral _ _ _ _ _ _ ALL); try lia.\n  inv WDm.\n         split; intros.\n             apply flatinj_E in H. destruct H as [? [? ?]]; subst. rewrite Zplus_0_r. assumption.\n             apply flatinj_E in H. destruct H as [? [? ?]]; subst. apply align_chunk_0.\n             apply flatinj_E in H. destruct H as [? [? ?]]; subst. rewrite Zplus_0_r.\n                 assert (X: Mem.flat_inj (Mem.nextblock m) b1 = Some (b1, 0)).\n                     apply flatinj_I. apply (Mem.perm_valid_block _ _ _ _ _ H0).\n                  specialize (mi_memval _ _ _ _ X H0). rewrite Zplus_0_r in mi_memval.\n                  eapply memval_inject_incr; try eassumption.\n                       intros bb; intros.\n                        eapply flatinj_mono; try eassumption. apply Plt_succ.\n     apply Plt_succ.\nQed.\n\nLemma  mem_wd_drop: forall m b lo hi p m' (DROP: Mem.drop_perm m b lo hi p = Some m')\n     (WDm: mem_wd m), Mem.valid_block m b -> mem_wd m'.\nProof. intros. unfold mem_wd in *.\n  rewrite (Mem.nextblock_drop _ _ _ _ _ _ DROP).\n  eapply (Mem.drop_inject_neutral _ _ _ _ _ _ _ DROP); trivial.\nQed.\n\nLemma free_neutral: forall (thr : block) (m : mem) (lo hi : Z) (b : block) (m' : Mem.mem')\n  (FREE: Mem.free m b lo hi = Some m'),\n  Mem.inject_neutral thr m -> Mem.inject_neutral thr m'.\nProof. intros. inv H.\n  split; intros.\n     apply flatinj_E in H. destruct H as [? [? ?]]; subst. rewrite Zplus_0_r. assumption.\n     apply flatinj_E in H. destruct H as [? [? ?]]; subst. apply align_chunk_0.\n     apply flatinj_E in H. destruct H as [? [? ?]]; subst. rewrite Zplus_0_r.\n        assert (X: Mem.flat_inj thr b1 = Some (b1,0)). apply flatinj_I. assumption.\n        assert (Y:= Mem.perm_free_3 _ _ _ _ _ FREE _ _ _ _ H0).\n         specialize (mi_memval _ _ _ _ X Y). rewrite Zplus_0_r in *.\n         rewrite (Mem.free_result _ _ _ _ _ FREE) in *. simpl in *. apply mi_memval.\nQed.\n\nLemma mem_wd_free: forall m b lo hi m' (WDm: mem_wd m)\n  (FREE: Mem.free m b lo hi = Some m'), mem_wd m'.\nProof. intros. unfold mem_wd in *.\n  eapply free_neutral. apply FREE.\n   rewrite (Mem.nextblock_free _ _ _ _ _ FREE). assumption.\nQed.\n\nLemma mem_wd_store: forall m b ofs v m' chunk (WDm: mem_wd m)\n  (ST: Mem.store chunk m b ofs v = Some m')\n  (V: val_valid v m), mem_wd m'.\nProof. intros. unfold mem_wd in *.\n  eapply Mem.store_inject_neutral. apply ST.\n      rewrite (Mem.nextblock_store _ _ _ _ _ _ ST). assumption.\n      assert (X:= Mem.store_valid_access_3 _ _ _ _ _ _ ST).\n          rewrite (Mem.nextblock_store _ _ _ _ _ _ ST).\n           apply (Mem.valid_access_implies _ _ _ _ _  Nonempty) in X.\n                apply Mem.valid_access_valid_block in X. apply X.\n            constructor.\n      rewrite (Mem.nextblock_store _ _ _ _ _ _ ST).\n          destruct v; try solve [constructor].\n            econstructor. eapply flatinj_I. apply V.\n                          rewrite Ptrofs.add_zero. trivial.\nQed.\n\nLemma extends_memwd:\nforall m1 m2 (Ext: Mem.extends m1 m2), mem_wd m2 -> mem_wd m1.\nProof.\n  intros. eapply mem_wdI. intros.\n  assert (Mem.perm m2 b ofs Cur Readable).\n    eapply (Mem.perm_extends _ _ _ _ _ _ Ext R).\n  assert (Mem.valid_block m2 b).\n     apply (Mem.perm_valid_block _ _ _ _ _ H0).\n  destruct Ext. rewrite mext_next.\n  assert (Mem.flat_inj (Mem.nextblock m2) b = Some (b,0)).\n    apply flatinj_I. apply H1.\n  destruct mext_inj. specialize (mi_memval b ofs b 0 (eq_refl _) R).\n  rewrite Zplus_0_r in mi_memval.\n  destruct H. specialize (mi_memval0 b ofs b 0 H2 H0).\n  rewrite Zplus_0_r in mi_memval0.\n  remember (ZMap.get ofs (PMap.get b (Mem.mem_contents m1))) as v.\n  destruct v. repeat econstructor.\n  econstructor.\n  econstructor.\n  destruct v; try constructor.\n  econstructor.\n    eapply flatinj_I. inv mi_memval.\n    inv H3. inv H5. rewrite Ptrofs.add_zero in H6.\n      rewrite <- H6 in mi_memval0. simpl in mi_memval0.\n     inv mi_memval0. inversion H3.\n      apply flatinj_E in H7. apply H7.\n   rewrite Ptrofs.add_zero. reflexivity.\nQed.\n\nInductive valid_genv {F V:Type} (ge:Genv.t F V) (m:mem) : Type :=\n  mk_valid_genv :\n    (forall b, isGlobalBlock ge b=true -> val_valid (Vptr b Ptrofs.zero) m) ->\n    (forall b f, Genv.find_funct_ptr ge b = Some f -> val_valid (Vptr b Ptrofs.zero) m) ->\n    valid_genv ge m.\n\nLemma valid_genv_alloc: forall {F V:Type} (ge:Genv.t F V) (m m1:mem) lo hi b\n    (ALLOC: Mem.alloc m lo hi = (m1,b)) (G: valid_genv ge m), valid_genv ge m1.\nProof. intros. case G; intros. constructor; intros.\n  apply (Mem.valid_block_alloc _ _ _ _ _ ALLOC).\n  apply (v _ H).\n  apply (Mem.valid_block_alloc _ _ _ _ _ ALLOC).\n  apply (v0 _ _ H).\nQed.\n\nLemma valid_genv_store: forall {F V:Type} (ge:Genv.t F V) m m1 b ofs v chunk\n    (STORE: Mem.store chunk m b ofs v = Some m1)\n     (G: valid_genv ge m), valid_genv ge m1.\nProof. intros. case G; intros. constructor; intros.\n  apply (Mem.store_valid_block_1 _ _ _ _ _ _ STORE).\n  apply (v0 _ H).\n  apply (Mem.store_valid_block_1 _ _ _ _ _ _ STORE).\n  apply (v1 _ _ H).\nQed.\n\nLemma valid_genv_store_zeros: forall {F V:Type} (ge:Genv.t F V) m m1 b y z\n    (STORE_ZERO: store_zeros m b y z = Some m1)\n    (G: valid_genv ge m), valid_genv ge m1.\nProof. intros. case G; intros. constructor; intros.\n  apply Genv.store_zeros_nextblock in STORE_ZERO.\n  specialize (v _ H); simpl in *.\n  unfold Mem.valid_block in *.\n  rewrite STORE_ZERO. apply G; auto.\n  specialize (v0 _ _ H); simpl in *.\n  apply Genv.store_zeros_nextblock in STORE_ZERO.\n  unfold Mem.valid_block in *.\n  rewrite STORE_ZERO. auto.\nQed.\n\nRequire Import FunInd.\n\nLemma mem_wd_store_zeros: forall m b p n m1\n    (STORE_ZERO: store_zeros m b p n = Some m1) (WD: mem_wd m), mem_wd m1.\nProof. intros until n. functional induction (store_zeros m b p n); intros.\n  inv STORE_ZERO; tauto.\n  apply (IHo _ STORE_ZERO); clear IHo.\n      eapply (mem_wd_store m). apply WD. apply e0. simpl; trivial.\n  inv STORE_ZERO.\nQed.\n\nLemma valid_genv_drop: forall {F V:Type} (ge:Genv.t F V) (m m1:mem) b lo hi p\n    (DROP: Mem.drop_perm m b lo hi p = Some m1) (G: valid_genv ge m),\n    valid_genv ge m1.\nProof. intros. case G; intros. constructor; intros.\n  apply (Mem.drop_perm_valid_block_1 _ _ _ _ _ _ DROP).\n  apply (v _ H); auto.\n  apply (Mem.drop_perm_valid_block_1 _ _ _ _ _ _ DROP).\n  apply (v0 _ _ H); auto.\nQed.\n\nLemma mem_wd_store_init_data: forall {F V} (ge: Genv.t F V) a (b:block) (z:Z)\n  m1 m2 (SID:Genv.store_init_data ge m1 b z a = Some m2),\n  valid_genv ge m1 -> mem_wd m1 -> mem_wd m2.\nProof. intros F V ge a.\n  destruct a; simpl; intros;\n      try apply (mem_wd_store _ _ _ _ _ _ H0 SID); simpl; trivial.\n   inv SID; trivial.\n   remember (Genv.find_symbol ge i) as d.\n     destruct d; inv SID.\n     eapply (mem_wd_store _ _ _ _ _ _ H0 H2).\n    apply eq_sym in Heqd.\n    destruct H.\n    apply v.\n    unfold isGlobalBlock.\n    rewrite orb_true_iff.\n    unfold genv2blocksBool; simpl.\n    apply Genv.find_invert_symbol in Heqd.\n    rewrite Heqd; left; auto.\nQed.\n\nLemma valid_genv_store_init_data:\n  forall {F V}  (ge: Genv.t F V) a (b:block) (z:Z) m1 m2\n  (SID: Genv.store_init_data ge m1 b z a = Some m2),\n  valid_genv ge m1 -> valid_genv ge m2.\nProof. intros F V ge a.\n  destruct a; simpl; intros; inv H; constructor;\n    try (intros b0 X; eapply Mem.store_valid_block_1 with (b':=b0); eauto;\n          apply H0; auto);\n    try (intros b0 ? X; eapply Mem.store_valid_block_1 with (b':=b0); eauto;\n          eapply H1; eauto);\n    try (inv SID; auto).\n  intros.\n  remember (Genv.find_symbol ge i) as d.\n  destruct d; inv H2.\n  eapply Mem.store_valid_block_1; eauto.\n  apply eq_sym in Heqd.\n  eapply H0; eauto.\n  revert H2. destruct (Genv.find_symbol ge i); intros; try congruence.\n  eapply Mem.store_valid_block_1; eauto.\n  eapply H1; eauto.\nQed.\n\nLemma mem_wd_store_init_datalist: forall {F V} (ge: Genv.t F V) l (b:block)\n  (z:Z) m1 m2 (SID: Genv.store_init_data_list ge m1 b z l = Some m2),\n  valid_genv ge m1 -> mem_wd m1 -> mem_wd m2.\nProof. intros F V ge l.\n  induction l; simpl; intros.\n    inv SID. trivial.\n  remember (Genv.store_init_data ge m1 b z a) as d.\n  destruct d; inv SID; apply eq_sym in Heqd.\n  apply (IHl _ _ _ _ H2); clear IHl H2.\n     eapply valid_genv_store_init_data. apply Heqd. apply H.\n  eapply mem_wd_store_init_data. apply Heqd. apply H. apply H0.\nQed.\n\nLemma valid_genv_store_init_datalist: forall {F V} (ge: Genv.t F V) l (b:block)\n  (z:Z) m1 m2 (SID: Genv.store_init_data_list ge m1 b z l = Some m2),\n   valid_genv ge m1 -> valid_genv ge m2.\nProof. intros F V ge l.\n  induction l; simpl; intros.\n    inv SID. trivial.\n  remember (Genv.store_init_data ge m1 b z a) as d.\n  destruct d; inv SID; apply eq_sym in Heqd.\n  apply (IHl _ _ _ _ H1); clear IHl H1.\n     eapply valid_genv_store_init_data. apply Heqd. apply H.\nQed.\n\nLemma mem_wd_alloc_global: forall  {F V} (ge: Genv.t F V) a m0 m1\n   (GA: Genv.alloc_global ge m0 a = Some m1),\n   mem_wd m0 -> valid_genv ge m0 -> mem_wd m1.\nProof. intros F V ge a.\ndestruct a; simpl. intros.\ndestruct g.\n  remember (Mem.alloc m0 0 1) as mm. destruct mm.\n    apply eq_sym in Heqmm.\n    specialize (mem_wd_alloc _ _ _ _ _ Heqmm). intros.\n     eapply (mem_wd_drop _ _ _ _ _  _ GA).\n    apply (H1 H).\n    apply (Mem.valid_new_block _ _ _ _ _ Heqmm).\nremember (Mem.alloc m0 0 (init_data_list_size (AST.gvar_init v)) ) as mm.\n  destruct mm. apply eq_sym in Heqmm.\n  remember (store_zeros m b 0 (init_data_list_size (AST.gvar_init v)))\n           as d.\n  destruct d; inv GA; apply eq_sym in Heqd.\n  remember (Genv.store_init_data_list ge m2 b 0 (AST.gvar_init v)) as dd.\n  destruct dd; inv H2; apply eq_sym in Heqdd.\n  eapply (mem_wd_drop _ _ _ _ _ _ H3); clear H3.\n    eapply (mem_wd_store_init_datalist _ _ _ _ _ _ Heqdd).\n    apply (valid_genv_store_zeros _ _ _ _ _ _ Heqd).\n    apply (valid_genv_alloc ge _ _ _ _ _ Heqmm H0).\n  apply (mem_wd_store_zeros _ _ _ _ _ Heqd).\n    apply (mem_wd_alloc _ _ _ _ _ Heqmm H).\n  unfold Mem.valid_block.\n     apply Genv.store_init_data_list_nextblock in Heqdd.\n           rewrite Heqdd. clear Heqdd.\n      apply Genv.store_zeros_nextblock in Heqd. rewrite Heqd; clear Heqd.\n      apply (Mem.valid_new_block _ _ _ _ _  Heqmm).\nQed.\n\nLemma valid_genv_alloc_global: forall  {F V} (ge: Genv.t F V) a m0 m1\n   (GA: Genv.alloc_global ge m0 a = Some m1),\n   valid_genv ge m0 -> valid_genv ge m1.\nProof. intros F V ge a.\ndestruct a; simpl. intros.\ndestruct g.\n  remember (Mem.alloc m0 0 1) as d. destruct d.\n    apply eq_sym in Heqd.\n    apply (valid_genv_drop _ _ _ _ _ _ _ GA).\n    apply (valid_genv_alloc _ _ _ _ _ _ Heqd H).\nremember (Mem.alloc m0 0 (init_data_list_size (AST.gvar_init v)) )\n         as Alloc.\n  destruct Alloc. apply eq_sym in HeqAlloc.\n  remember (store_zeros m b 0\n           (init_data_list_size (AST.gvar_init v))) as SZ.\n  destruct SZ; inv GA; apply eq_sym in HeqSZ.\n  remember (Genv.store_init_data_list ge m2 b 0 (AST.gvar_init v)) as Drop.\n  destruct Drop; inv H1; apply eq_sym in HeqDrop.\n  eapply (valid_genv_drop _ _ _ _ _ _ _ H2); clear H2.\n  eapply (valid_genv_store_init_datalist _ _ _ _ _ _ HeqDrop). clear HeqDrop.\n  apply (valid_genv_store_zeros _ _ _ _ _ _ HeqSZ).\n    apply (valid_genv_alloc _ _ _ _ _ _ HeqAlloc H).\nQed.\n\nLemma valid_genv_alloc_globals:\n   forall F V (ge: Genv.t F V) init_list m0 m\n   (GA: Genv.alloc_globals ge m0 init_list = Some m),\n   valid_genv ge m0 -> valid_genv ge m.\nProof. intros F V ge l.\ninduction l; intros; simpl in *.\n  inv GA. assumption.\nremember (Genv.alloc_global ge m0 a) as d.\n  destruct d; inv GA. apply eq_sym in Heqd.\n  eapply (IHl  _ _  H1). clear H1.\n    apply (valid_genv_alloc_global _ _ _ _ Heqd H).\nQed.\n\nLemma mem_wd_alloc_globals:\n   forall F V (ge: Genv.t F V) init_list m0 m\n   (GA: Genv.alloc_globals ge m0 init_list = Some m),\n   mem_wd m0 -> valid_genv ge m0 -> mem_wd m.\nProof. intros F V ge l.\ninduction l; intros; simpl in *.\n  inv GA. assumption.\nremember (Genv.alloc_global ge m0 a) as d.\n  destruct d; inv GA. apply eq_sym in Heqd.\neapply (IHl  _ _  H2).\n    apply (mem_wd_alloc_global ge _ _ _ Heqd H H0).\n    apply (valid_genv_alloc_global _ _ _ _ Heqd H0).\nQed.\n\n(*POPL-compcomp used the following lemma to prove mem_wd_load:\nLemma decode_val_pointer_inv:\n  forall chunk mvl b ofs,\n  decode_val chunk mvl = Vptr b ofs ->\n  chunk = Mint32 /\\ mvl = inj_value Q32 (Vptr b ofs).\n A version of this lemma is in\n  CompCert 2.3, Memdata.v,\n but missing from CompCert 2.4.  I'm not even sure\n it's true in CompCert 2.4.  -A.W.A.\n\nIn CompCert2.5, the proof of mem_wd_load uses the new load_ptr_is_fragment, recently added to mem_lemmas*)\nLemma mem_wd_load: forall m ch b ofs v\n  (LD: Mem.load ch m b ofs = Some v)\n  (WD : mem_wd m), val_valid v m.\nProof. intros.\n  destruct v; simpl; trivial.\n  destruct (load_ptr_is_fragment _ _ _ _ _ _ LD) as [q [n FRAG]].\n  destruct (Mem.load_valid_access _ _ _ _ _ LD) as [Perms Align].\n  apply Mem.load_result in LD.\n  destruct WD.\n  assert (Arith: ofs <= ofs < ofs + (size_chunk ch)). specialize (size_chunk_pos ch); lia.\n  specialize (Perms _ Arith).\n  assert (VB:= Mem.perm_valid_block _ _ _ _ _ Perms).\n  assert (Z:= flatinj_I (Mem.nextblock m) b VB).\n  specialize (mi_memval _ _ _ _ Z Perms).\n  rewrite Zplus_0_r in mi_memval. rewrite FRAG in mi_memval.\n  inversion mi_memval. subst.\n  inversion H0.\n  apply flatinj_E in H3. apply H3.\nQed.\n\nLemma mem_wd_storebytes: forall m b ofs bytes m' (WDm: mem_wd m)\n  (ST: Mem.storebytes m b ofs bytes = Some m')\n  (BytesValid: forall v, In v bytes ->\n               memval_inject (Mem.flat_inj (Mem.nextblock m)) v v),\n   mem_wd m'.\nProof. intros. apply mem_wdI. intros.\n  assert (F: Mem.flat_inj (Mem.nextblock m) b0 = Some (b0, 0)).\n        apply flatinj_I.\n        apply (Mem.storebytes_valid_block_2 _ _ _ _ _ ST).\n        eapply Mem.perm_valid_block; eassumption.\n  apply mem_wd_E in WDm.\n  assert (P:= Mem.perm_storebytes_2 _ _ _ _ _ ST _ _ _ _ R).\n  specialize (Mem.mi_memval _ _ _ (Mem.mi_inj _ _ _ WDm) _ _ _ _ F P).\n  rewrite Zplus_0_r.\n  intros MVI.\n  rewrite (Mem.nextblock_storebytes _ _ _ _ _ ST).\n  rewrite (Mem.storebytes_mem_contents _ _ _ _ _ ST).\n  remember (eq_block b0 b).\n  destruct s; subst; clear Heqs.\n  (*case b0=b*)\n    rewrite PMap.gss.\n    remember (zlt ofs0 ofs) as d.\n    destruct d; clear Heqd.\n    (*case ofs0 < ofs*)\n      rewrite Mem.setN_outside; try (left; assumption).\n      assumption.\n    (*case ofs0 >= ofs*)\n      remember (zlt ofs0 (ofs + (Z.of_nat (length bytes)))) as d.\n      destruct d; clear Heqd.\n      (*case <*)\n        apply BytesValid; clear BytesValid.\n        apply Mem.setN_in. lia.\n      (*case >= *)\n         rewrite Mem.setN_outside; try (right; assumption).\n      assumption.\n  (*case b0 <> b*)\n    rewrite PMap.gso; trivial.\nQed.\n\nLemma getN_aux: forall n p c B1 v B2, Mem.getN n p c = B1 ++ v::B2 ->\n    v = ZMap.get (p + Z.of_nat (length B1)) c.\nProof. intros n.\n  induction n; simpl; intros.\n    destruct B1; simpl in *. inv H. inv H.\n    destruct B1; simpl in *.\n      inv H. rewrite Zplus_0_r. trivial.\n      inv H. specialize (IHn _ _ _ _ _ H2). subst.\n        rewrite Zpos_P_of_succ_nat.\n        remember (Z.of_nat (length B1)) as m. clear Heqm H2. rewrite <- Z.add_1_l.\n         rewrite Zplus_assoc. trivial.\nQed.\n\nLemma getN_range: forall n ofs M bytes1 v bytes2,\n  Mem.getN n ofs M = bytes1 ++ v::bytes2 ->\n  (length bytes1 < n)%nat.\nProof. intros n.\n  induction n; simpl; intros.\n    destruct bytes1; inv H.\n    destruct bytes1; simpl in *; inv H.\n      lia.\n    specialize (IHn _ _ _ _ _ H2). lia.\nQed.\n\nLemma loadbytes_D: forall m b ofs n bytes\n      (LD: Mem.loadbytes m b ofs n = Some bytes),\n      Mem.range_perm m b ofs (ofs + n) Cur Readable /\\\n      bytes = Mem.getN (Z.to_nat n) ofs (PMap.get b (Mem.mem_contents m)).\nProof. intros.\n  Transparent Mem.loadbytes.\n  unfold Mem.loadbytes in LD.\n  Opaque Mem.loadbytes.\n  remember (Mem.range_perm_dec m b ofs (ofs + n) Cur Readable) as d.\n  destruct d; inv LD. auto.\nQed.\n\nLemma loadbytes_valid: forall m (WD: mem_wd m) b ofs' n bytes\n      (LD: Mem.loadbytes m b (Int.unsigned ofs') n = Some bytes)\n      v (B: In v bytes),\n      memval_inject (Mem.flat_inj (Mem.nextblock m)) v v.\nProof. intros.\n  destruct (loadbytes_D _ _ _ _ _ LD) as [Range BB]; subst.\n  assert (L:= Mem.loadbytes_length _ _ _ _ _ LD).\n  apply In_split in B. destruct B as [bytes1 [bytes2 B]]. subst.\n  assert (I: Int.unsigned ofs' <= (Int.unsigned ofs') + Z.of_nat (length bytes1) <\n                  Int.unsigned ofs' + n).\n    assert (II:= getN_range _ _ _ _ _ _ B).\n    clear Range LD B L.\n    split. lia.\n    assert (Z.of_nat (length bytes1) < Z.of_nat (Z.to_nat n)).\n        lia.\n    rewrite Z2Nat.id in H. lia. clear H.\n        destruct n. lia. specialize (Pos2Z.is_pos p); lia.\n        rewrite Z2Nat.inj_neg in II. destruct bytes1; simpl in II; inv II.\n  specialize (Range _ I).\n  assert (F: Mem.flat_inj (Mem.nextblock m) b = Some (b, 0)).\n    apply flatinj_I. apply Mem.perm_valid_block in Range. apply Range.\n    specialize (Mem.mi_memval _ _ _ WD _ _ _ _ F Range).\n    intros. rewrite Zplus_0_r in H.\n   apply getN_aux in B. subst. apply H.\nQed.\n\nLemma freelist_mem_wd: forall l m m'\n      (M: Mem.free_list m l = Some m')\n      (WD: mem_wd m), mem_wd m'.\nProof. intros l.\n  induction l; simpl; intros.\n    inv M; trivial.\n  destruct a. destruct p.\n  remember (Mem.free m b z0 z) as d.\n  destruct d; inv M; apply eq_sym in Heqd.\n  apply (IHl _ _ H0).\n  eapply mem_wd_free; eassumption.\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/mem_wd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.29699859004258317}}
{"text": "(** Definition of Wasm datatypes\n    See https://webassembly.github.io/spec/core/syntax/index.html\n    and https://webassembly.github.io/spec/core/exec/index.html **)\n(* (C) J. Pichon, M. Bodin - see LICENSE.txt *)\n\n(* TODO: use better representations than \"nat\", which is expensive;\n   maybe N? maybe a 32-bit word type? *)\n\nRequire Import BinNat.\nFrom Wasm Require array.\nFrom Wasm Require Import common memory memory_list.\nFrom Wasm Require Export numerics bytes.\nFrom mathcomp Require Import ssreflect ssrfun ssrnat ssrbool eqtype seq.\nFrom compcert Require common.Memdata.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\n(** * Basic Datatypes **)\n\n(* TODO: Documentation. *)\n\n(* TODO: make these have structure; this will require monad-ifying the whole thing *)\nDefinition host := unit.\nDefinition host_state := unit.\n\nDefinition depth := nat.\n\nDefinition immediate (* i *) :=\n  (* TODO: this is not a great representation *)\n  nat.\n\nDefinition static_offset := (* off *) N. (* TODO: should be u32 *)\n\nDefinition alignment_exponent := (* a *) N. (* TODO: should be u32 *)\n\nDefinition serialise_i32 (i : i32) : bytes :=\n  common.Memdata.encode_int 4%nat (numerics.Wasm_int.Int32.unsigned i).\n\nDefinition serialise_i64 (i : i64) : bytes :=\n  common.Memdata.encode_int 8%nat (numerics.Wasm_int.Int64.unsigned i).\n\nDefinition serialise_f32 (f : f32) : bytes :=\n  common.Memdata.encode_int 4%nat (Integers.Int.unsigned (numerics.Wasm_float.FloatSize32.to_bits f)).\n\nDefinition serialise_f64 (f : f64) : bytes :=\n  common.Memdata.encode_int 8%nat (Integers.Int64.unsigned (numerics.Wasm_float.FloatSize64.to_bits f)).\n\n(** std-doc:\nLimits classify the size range of resizeable storage associated with memory types and table types.\nIf no maximum is given, the respective storage can grow to any size.\n[https://webassembly.github.io/spec/core/syntax/types.html#limits]\n *)\nRecord limits : Type := {\n  lim_min : N; (* TODO: should be u32 *)\n  lim_max : option N; (* TODO: should be u32 *)\n}.\n\n(* TODO: factor this out, following the `memory` branch *)\nModule Byte_Index <: array.Index_Sig.\nDefinition Index := N.\nDefinition Value := byte.\nDefinition index_eqb := N.eqb.\nEnd Byte_Index.\n\nModule Byte_array := array.Make Byte_Index.\n\nRecord data_vec : Type := {\n  dv_length : N;\n  dv_array : Byte_array.array;\n}.\n\nRecord memory : Type := {\n  mem_data : memory_list;\n  mem_max_opt: option N; (* TODO: should be u32 *)\n}.\n\n(** std-doc:\nMemory types classify linear memories and their size range.\nThe limits constrain the minimum and optionally the maximum size of a memory. The limits are given in units of page size.\n[https://webassembly.github.io/spec/core/syntax/types.html#memory-types]\n*)\nDefinition memory_type := limits.\n\n(** std-doc:\nValue types classify the individual values that WebAssembly code can compute with and the values that a variable accepts.\nThe types i32 and i64 classify 32 and 64 bit integers, respectively. Integers are not inherently signed or unsigned, their interpretation is determined by individual operations.\n\nThe types f32 and f64 classify 32 and 64 bit floating-point data, respectively. They correspond to the respective binary floating-point representations, also known as single and double precision, as defined by the IEEE 754-2019 standard (Section 3.3).\n[https://webassembly.github.io/spec/core/syntax/types.html#value-types]\n*)\nInductive value_type : Type := (* t *)\n  | T_i32\n  | T_i64\n  | T_f32\n  | T_f64\n  .\n\n\nInductive packed_type : Type := (* tp *)\n  | Tp_i8\n  | Tp_i16\n  | Tp_i32\n  .\n\n(* TODO: the standard calls those const and var *)\n(** std-doc:\n[https://webassembly.github.io/spec/core/syntax/types.html#global-types]\n*)\nInductive mutability : Type := (* mut *)\n  | MUT_immut\n  | MUT_mut\n  .\n\n(** std-doc:\nGlobal types classify global variables, which hold a value and can either be mutable or immutable.\n[https://webassembly.github.io/spec/core/syntax/types.html#global-types]\n*)\nRecord global_type : Type := (* tg *) {\n  tg_mut : mutability;\n  tg_t : value_type\n}.\n\n(** std-doc:\nResult types classify the result of executing instructions or functions, which is a sequence of values written with brackets.\n[https://webassembly.github.io/spec/core/syntax/types.html#result-types]\n*)\nDefinition result_type : Type :=\n  list value_type.\n(** Note from the specification:\n  In the current version of WebAssembly, at most one value is allowed as a result.\n  However, this may be generalized to sequences of values in future versions. **)\n(* FIXME: Do we want to enforce it? *)\n\n\n(** std-doc:\nFunction types classify the signature of functions, mapping a vector of\nparameters to a vector of results. They are also used to classify the inputs\nand outputs of instructions.\n[https://webassembly.github.io/spec/core/syntax/types.html#function-types]\n*)\nInductive function_type := (* tf *)\n  | Tf : result_type -> result_type -> function_type\n  (** Note from the specification:\n    In the current version of Wasm, the result list has an arity of at most [1]. **)\n  (* FIXME: Shouldn’t we enforce it? *)\n  .\n\n(** std-doc:\nThe element type funcref is the infinite union of all function types. A table\nof that type thus contains references to functions of heterogeneous type.\n*)\nInductive elem_type : Type :=\n| ELT_funcref : elem_type.\n\n(** std-doc:\nTable types classify tables over elements of element types within a size range.\n\nLike memories, tables are constrained by limits for their minimum and\noptionally maximum size. The limits are given in numbers of entries.\n[https://webassembly.github.io/spec/core/syntax/types.html#table-types]\n*)\nRecord table_type : Type := {\n  tt_limits : limits;\n  tt_elem_type : elem_type;\n}.\n\n(** Typing context. **)\n(** std-doc:\nValidity of an individual definition is specified relative to a context, which\ncollects relevant information about the surrounding module and the definitions\nin scope:\n- Types: the list of types defined in the current module.\n- Functions: the list of functions declared in the current module, represented\n  by their function type.\n- Tables: the list of tables declared in the current module, represented by\n  their table type.\n- Memories: the list of memories declared in the current module, represented by\n  their memory type.\n- Globals: the list of globals declared in the current module, represented by\n  their global type.\n- Locals: the list of locals declared in the current function (including\n  parameters), represented by their value type.\n- Labels: the stack of labels accessible from the current position, represented\n  by their result type.\n- Return: the return type of the current function, represented as an optional\n  result type that is absent when no return is allowed, as in free-standing\n  expressions.\nIn other words, a context contains a sequence of suitable types for each index\nspace, describing each defined entry in that space. Locals, labels and return\ntype are only used for validating instructions in function bodies, and are left\nempty elsewhere. The label stack is the only part of the context that changes\nas validation of an instruction sequence proceeds.\n*)\nRecord t_context : Type := {\n  tc_types_t : list function_type;\n  tc_func_t : list function_type;\n  tc_global : list global_type;\n  tc_table : list table_type;\n  tc_memory : list memory_type;\n  tc_local : list value_type;\n  tc_label : list (list value_type);\n  tc_return : option (list value_type);\n}.\n\n(** std-doc:\nWebAssembly computations manipulate values of the four basic value types:\nintegers and floating-point data of 32 or 64 bit width each, respectively.\n*)\nInductive value : Type := (* v *)\n  | VAL_int32 : i32 -> value\n  | VAL_int64 : i64 -> value\n  | VAL_float32 : f32 -> value\n  | VAL_float64 : f64 -> value\n  .\n\nInductive result : Type :=\n  | result_values : list value -> result\n  (** Note from the specification:\n    In the current version of WebAssembly, a result can consist of at most one value. **)\n  | result_trap : result\n  .\n\n(** * Basic Instructions **)\n\nInductive sx : Type :=\n  | SX_S\n  | SX_U\n  .\n\nInductive unop_i : Type :=\n  | UOI_clz\n  | UOI_ctz\n  | UOI_popcnt\n  .\n\nInductive unop_f : Type :=\n  | UOF_neg\n  | UOF_abs\n  | UOF_ceil\n  | UOF_floor\n  | UOF_trunc\n  | UOF_nearest\n  | UOF_sqrt\n  .\n\nInductive unop : Type :=\n  | Unop_i : unop_i -> unop\n  | Unop_f : unop_f -> unop\n  .\n\nInductive binop_i : Type :=\n  | BOI_add\n  | BOI_sub\n  | BOI_mul\n  | BOI_div : sx -> binop_i\n  | BOI_rem : sx -> binop_i\n  | BOI_and\n  | BOI_or\n  | BOI_xor\n  | BOI_shl\n  | BOI_shr : sx -> binop_i\n  | BOI_rotl\n  | BOI_rotr\n  .\n\nInductive binop_f : Type :=\n  | BOF_add\n  | BOF_sub\n  | BOF_mul\n  | BOF_div\n  | BOF_min\n  | BOF_max\n  | BOF_copysign\n  .\n\nInductive binop : Type :=\n  | Binop_i : binop_i -> binop\n  | Binop_f : binop_f -> binop\n  .\n  \nInductive testop : Type :=\n  | TO_eqz\n  .\n\nInductive relop_i : Type :=\n  | ROI_eq\n  | ROI_ne\n  | ROI_lt : sx -> relop_i\n  | ROI_gt : sx -> relop_i\n  | ROI_le : sx -> relop_i\n  | ROI_ge : sx -> relop_i\n  .\n\nInductive relop_f : Type :=\n  | ROF_eq\n  | ROF_ne\n  | ROF_lt\n  | ROF_gt\n  | ROF_le\n  | ROF_ge\n  .\n  \nInductive relop : Type :=\n  | Relop_i : relop_i -> relop\n  | Relop_f : relop_f -> relop\n  .\n\nInductive cvtop : Type :=\n  | CVO_convert\n  | CVO_reinterpret\n  .\n\nInductive basic_instruction : Type := (* be *)\n  | BI_unreachable\n  | BI_nop\n  | BI_drop\n  | BI_select\n  | BI_block : function_type -> list basic_instruction -> basic_instruction\n  | BI_loop : function_type -> list basic_instruction -> basic_instruction\n  | BI_if : function_type -> list basic_instruction -> list basic_instruction -> basic_instruction\n  | BI_br : immediate -> basic_instruction\n  | BI_br_if : immediate -> basic_instruction\n  | BI_br_table : list immediate -> immediate -> basic_instruction\n  | BI_return\n  | BI_call : immediate -> basic_instruction\n  | BI_call_indirect : immediate -> basic_instruction\n  | BI_get_local : immediate -> basic_instruction\n  | BI_set_local : immediate -> basic_instruction\n  | BI_tee_local : immediate -> basic_instruction\n  | BI_get_global : immediate -> basic_instruction\n  | BI_set_global : immediate -> basic_instruction\n  | BI_load : value_type -> option (packed_type * sx) -> alignment_exponent -> static_offset -> basic_instruction\n  | BI_store : value_type -> option packed_type -> alignment_exponent -> static_offset -> basic_instruction\n  | BI_current_memory\n  | BI_grow_memory\n  | BI_const : value -> basic_instruction\n  | BI_unop : value_type -> unop -> basic_instruction\n  | BI_binop : value_type -> binop -> basic_instruction\n  | BI_testop : value_type -> testop -> basic_instruction\n  | BI_relop : value_type -> relop -> basic_instruction\n  | BI_cvtop : value_type -> cvtop -> value_type -> option sx -> basic_instruction\n  .\n\n(** * Functions and Store **)\n\nSection Host.\n\n(** We assume a family of host functions. **)\nVariable host_function : Type.\n\nDefinition funcaddr := immediate (* TODO: should be funcidx *).\nDefinition tableaddr := immediate (* TODO: should be tableidx *).\nDefinition memaddr := immediate. (* TODO: should be memidx *)\nDefinition globaladdr := immediate. (* TODO: should be globalidx *)\n\n\n(** std-doc:\nA module instance is the runtime representation of a module. It is created by\ninstantiating a module, and collects runtime representations of all entities\nthat are imported, defined, or exported by the module.\n\nEach component references runtime instances corresponding to respective\ndeclarations from the original module – whether imported or defined – in the\norder of their static indices. Function instances, table instances, memory\ninstances, and global instances are referenced with an indirection through\ntheir respective addresses in the store.\n\nIt is an invariant of the semantics that all export instances in a given module\ninstance have different names.\n*)\nRecord instance : Type := (* inst *) {\n  inst_types : list function_type;\n  inst_funcs : list funcaddr;\n  inst_tab : list tableaddr;\n  inst_memory : list memaddr;\n  inst_globs : list globaladdr;\n  (* TODO: exports field? *)\n}.\n(** std-doc:\nA function instance is the runtime representation of a function. It effectively\nis a closure of the original function over the runtime module instance of its\noriginating module. The module instance is used to resolve references to other\ndefinitions during execution of the function.\n*)\nInductive function_closure : Type := (* cl *)\n  | FC_func_native : instance -> function_type -> list value_type -> list basic_instruction -> function_closure\n  | FC_func_host : function_type -> host_function -> function_closure\n.\n\n(** std-doc:\nEach function element is either empty, representing an uninitialized table\nentry, or a function address. Function elements can be mutated through the\nexecution of an element segment or by external means provided by the embedder.\n*)\nDefinition funcelem := option nat.\n\n(** std-doc:\nA table instance is the runtime representation of a table. It holds a vector of\nfunction elements and an optional maximum size, if one was specified in the\ntable type at the table’s definition site.\n\nIt is an invariant of the semantics that the length of the element vector never\nexceeds the maximum size, if present.\n*)\nRecord tableinst : Type := {\n  table_data: list funcelem;\n  table_max_opt: option N; (* TODO: should be u32 *)\n}.\n\n(** std-doc:\nhttps://webassembly.github.io/spec/core/syntax/types.html#global-types\n*)\nRecord global : Type := {\n  g_mut : mutability;\n  g_val : value;\n}.\n\n(** std-doc:\nThe store represents all global state that can be manipulated by WebAssembly\nprograms. It consists of the runtime representation of all instances of\nfunctions, tables, memories, and globals that have been allocated during the\nlife time of the abstract machine\n*)\nRecord store_record : Type := (* s *) {\n  s_funcs : list function_closure;\n  s_tables : list tableinst;\n  s_mems : list memory;\n  s_globals : list global;\n}.\n\n(** std-doc:\n\n[https://webassembly.github.io/spec/core/exec/runtime.html#syntax-frame]\n*)\nRecord frame : Type := (* f *) {\n  f_locs: list value;\n  f_inst: instance\n}.\n\n(** * Administrative Instructions **)\n\n(** std-doc:\nWebAssembly code consists of sequences of instructions. Its computational model is based on a stack machine in that instructions manipulate values on an implicit operand stack, consuming (popping) argument values and producing or returning (pushing) result values.\n\nIn addition to dynamic operands from the stack, some instructions also have static immediate arguments, typically indices or type annotations, which are part of the instruction itself.\n\nSome instructions are structured in that they bracket nested sequences of instructions.\n[https://webassembly.github.io/spec/core/syntax/instructions.html]\n\nIn order to express the reduction of traps, calls, and control instructions,\nthe syntax of instructions is extended to include the following administrative\ninstructions:\n*)\nInductive administrative_instruction : Type := (* e *)\n| AI_basic : basic_instruction -> administrative_instruction\n| AI_trap\n| AI_invoke : funcaddr -> administrative_instruction\n| AI_label : nat -> seq administrative_instruction -> seq administrative_instruction -> administrative_instruction\n| AI_local : nat -> frame -> seq administrative_instruction -> administrative_instruction\n.\n\nInductive lholed : Type :=\n| LH_base : list administrative_instruction -> list administrative_instruction -> lholed\n| LH_rec : list administrative_instruction -> nat -> list administrative_instruction -> lholed -> list administrative_instruction -> lholed\n.\n\n(** std-doc:\nFunction bodies, initialization values for globals, and offsets of element or data segments are given as expressions, which are sequences of instructions terminated by an 𝖾𝗇𝖽 marker.\nIn some places, validation restricts expressions to be constant, which limits the set of allowable instructions.\n[https://webassembly.github.io/spec/core/syntax/instructions.html#expressions]\n*)\nDefinition expr := list basic_instruction.\n\nInductive labelidx : Type :=\n| Mk_labelidx : nat -> labelidx.\n\nInductive funcidx : Type :=\n| Mk_funcidx : nat -> funcidx.\n\nInductive tableidx : Type :=\n| Mk_tableidx : nat -> tableidx.\n\nInductive memidx : Type :=\n| Mk_memidx : nat -> memidx.\n\nInductive typeidx : Type :=\n| Mk_typeidx : nat -> typeidx.\n\nInductive localidx : Type :=\n| Mk_localidx : nat -> localidx.\n\nInductive globalidx : Type :=\n| Mk_globalidx : nat -> globalidx.\n\nInductive import_desc : Type :=\n| ID_func : nat -> import_desc\n| ID_table : table_type -> import_desc\n| ID_mem : memory_type -> import_desc\n| ID_global : global_type -> import_desc.\n\nDefinition name := list Byte.byte.\n\nRecord module_import : Type := {\n  imp_module : name;\n  imp_name : name;\n  imp_desc : import_desc;\n}.\n\nRecord module_table : Type := {\n  modtab_type : table_type;\n}.\n\nRecord module_glob : Type := {\n  modglob_type : global_type;\n  modglob_init : expr;\n}.\n\nRecord module_start : Type := {\n  modstart_func : funcidx;\n}.\n\nRecord module_element : Type := {\n  modelem_table : tableidx;\n  modelem_offset : expr;\n  modelem_init : list funcidx;\n}.\n\nRecord code_func : Type := {\n  fc_locals : list value_type;\n  fc_expr : expr;\n}.\n\nRecord module_data : Type := {\n  moddata_data : memidx;\n  moddata_offset : expr;\n  moddata_init : list Byte.byte;\n}.\n\nInductive module_export_desc : Type :=\n| MED_func : funcidx -> module_export_desc\n| MED_table : tableidx -> module_export_desc\n| MED_mem : memidx -> module_export_desc\n| MED_global : globalidx -> module_export_desc.\n\nRecord module_export : Type := {\n  modexp_name : name;\n  modexp_desc : module_export_desc;\n}.\n\nRecord module_func : Type := {\n  modfunc_type : typeidx;\n  modfunc_locals : list value_type;\n  modfunc_body : expr;\n}.\n\n(** std-doc:\nWebAssembly programs are organized into modules, which are the unit of deployment, loading, and compilation. A module collects definitions for types, functions, tables, memories, and globals. In addition, it can declare imports and exports and provide initialization logic in the form of data and element segments or a start function.\n[https://webassembly.github.io/spec/core/syntax/modules.html]\n*)\nRecord module : Type := {\n  mod_types : list function_type;\n  mod_funcs : list module_func;\n  mod_tables : list module_table;\n  mod_mems : list memory_type;\n  mod_globals : list module_glob;\n  mod_elem : list module_element;\n  mod_data : list module_data;\n  mod_start : option module_start;\n  mod_imports : list module_import;\n  mod_exports : list module_export;\n}.\n\nInductive extern_t : Type :=\n| ET_func : function_type -> extern_t\n| ET_tab : table_type -> extern_t\n| ET_mem : memory_type -> extern_t\n| ET_glob : global_type -> extern_t\n.\n\n\n(** Some types used in the interpreter. **)\n\nDefinition config_tuple : Type := store_record * frame * seq administrative_instruction.\n\nDefinition config_one_tuple_without_e : Type := store_record * frame * seq value.\n\nInductive res_crash : Type :=\n  | C_error : res_crash\n  .\n\nInductive res_step : Type :=\n  | RS_crash : res_crash -> res_step\n  | RS_break : nat -> seq value -> res_step\n  | RS_return : seq value -> res_step\n  | RS_normal : seq administrative_instruction -> res_step\n  .\n\nDefinition res_tuple : Type := store_record * frame * res_step.\n\nEnd Host.\nArguments FC_func_native [host_function].\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/datatypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.29695076817973254}}
{"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 ModSem.\nRequire Export SimMem.\n(* Include SimMem. *)\n\nSet Implicit Arguments.\n\n\n(* A special instance of private transition, for backward compatibility *)\n\nModule SimMemLift.\n\n  (* Context `{SM: SimMem.class}. *)\n\n  Class class (SM: SimMem.class) :=\n  { lepriv_Trans :> Transitive SimMem.lepriv;\n\n    lift: SimMem.t -> SimMem.t;\n    unlift: SimMem.t -> SimMem.t -> SimMem.t;\n\n    lift_wf: forall mrel, SimMem.wf mrel -> SimMem.wf (lift mrel);\n    lift_src: forall mrel, (lift mrel).(SimMem.src) = mrel.(SimMem.src);\n    lift_tgt: forall mrel, (lift mrel).(SimMem.tgt) = mrel.(SimMem.tgt);\n    unlift_src: forall mrel0 mrel1, (unlift mrel0 mrel1).(SimMem.src) = mrel1.(SimMem.src);\n    unlift_tgt: forall mrel0 mrel1, (unlift mrel0 mrel1).(SimMem.tgt) = mrel1.(SimMem.tgt);\n    lift_spec: forall mrel0 mrel1, SimMem.le (lift mrel0) mrel1 -> SimMem.wf mrel0 -> SimMem.le mrel0 (unlift mrel0 mrel1);\n    unlift_wf: forall mrel0 mrel1,\n        SimMem.wf mrel0 -> SimMem.wf mrel1 -> SimMem.le (lift mrel0) mrel1 -> SimMem.wf (unlift mrel0 mrel1);\n\n    lift_sim_val: forall mrel, SimMem.sim_val mrel <2= SimMem.sim_val (lift mrel);\n\n    (* Required for \"forward\" compatibility *)\n\n    lift_priv: forall sm0 (MWF: SimMem.wf sm0), SimMem.lepriv sm0 (lift sm0);\n    (* unlift_priv: forall sm0 sm1 (MWF: SimMem.wf sm0), SimMem.lepriv sm1 (unlift sm0 sm1); *)\n    unlift_priv: forall\n        sm_at sm_arg sm_ret\n        (MWF: SimMem.wf sm_at)\n        (MLIFT: SimMem.lepriv sm_at sm_arg)\n        (MLE: SimMem.le sm_arg sm_ret)\n        (MWF: SimMem.wf sm_ret),\n        SimMem.lepriv sm_ret (unlift sm_at sm_ret);\n  }.\n\n  Section PROPS.\n\n  Context {SM: SimMem.class}.\n  Context {SML: SimMemLift.class SM}.\n\n  Lemma lift_sim_regset: forall sm0, SimMem.sim_regset sm0 <2= SimMem.sim_regset (SimMemLift.lift sm0).\n  Proof. ii. eapply SimMemLift.lift_sim_val; et. Qed.\n\n  Lemma le_lift_lepriv\n        sm0 sm1 sm_lift\n        (MWF0: SimMem.wf sm0)\n        (MWF1: SimMem.wf sm1)\n        (MLE: SimMem.le sm0 sm1)\n        (MLIFT: SimMemLift.lift sm1 = sm_lift):\n      <<MLE: SimMem.lepriv sm0 sm_lift>>.\n  Proof.\n    subst. hexploit (SimMemLift.lift_priv sm1); eauto. intro T. r. etrans; et.\n  Qed.\n\n  Lemma lift_args\n        args_src args_tgt sm_arg0\n        (ARGS: SimMem.sim_args args_src args_tgt sm_arg0):\n      <<ARGS: SimMem.sim_args args_src args_tgt (SimMemLift.lift sm_arg0)>>.\n  Proof.\n    inv ARGS.\n    - econs; eauto.\n      + eapply SimMemLift.lift_sim_val; et.\n      + erewrite <- SimMem.sim_val_list_spec in *.\n        eapply Forall2_impl.\n        { eapply SimMemLift.lift_sim_val; et. }\n        ss.\n      + rewrite SimMemLift.lift_src. ss.\n      + rewrite SimMemLift.lift_tgt. ss.\n    - econs 2; eauto.\n      + eapply lift_sim_regset; et.\n      + rewrite SimMemLift.lift_src. ss.\n      + rewrite SimMemLift.lift_tgt. ss.\n  Qed.\n\n  (* Lemma unlift_le_lepriv *)\n  (*       sm_arg sm_ret sm1 *)\n  (*       (MWF0: SimMem.wf sm_arg) *)\n  (*       (MWF1: SimMem.wf (SimMemLift.unlift sm_arg sm_ret)) *)\n  (*       (MLE: SimMem.le (SimMemLift.unlift sm_arg sm_ret) sm1) *)\n  (*   : *)\n  (*     <<MLE: SimMem.lepriv sm_ret sm1>> *)\n  (* . *)\n  (* Proof. *)\n  (*   hexploit (SimMemLift.unlift_priv sm_arg sm_ret); eauto. intro T. *)\n  (*   r. etrans; et. *)\n  (* Qed. *)\n\n  End PROPS.\n\nEnd SimMemLift.\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/SimMemLift.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6723316991792861, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.29695076238012014}}
{"text": "(** * Properties about Context Free Grammars *)\nRequire Import Fiat.Parsers.StringLike.Core Fiat.Parsers.ContextFreeGrammar.Core.\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": "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/TransferProperties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2969507623801201}}
{"text": "Require Import list_examples.\nRequire Import step_ok.\n\nDefinition oddDef :=\n  FunDef \"odd\" [\"x\"]\n         (SIf (BEq \"x\" 0) (SReturn (ECon 0))\n              (SReturn (ECall \"even\" [EMinus (EVar \"x\") (ECon 1)]))).\nDefinition evenDef :=\n  FunDef \"even\" [\"x\"]\n         (SIf (BEq \"x\" 0) (SReturn (ECon 1))\n              (SReturn (ECall \"odd\" [EMinus (EVar \"x\") (ECon 1)]))).\n\n(* spec claims that calling def computes the same result as f\n   as long as deps and def are included in the funs *)\nDefinition z_spec (f:Z -> bool) spec deps def :=\n  forall y, heap_fun spec deps def [Int y] emptyP (fun r => constraint (r = if f y then 1 else 0)).\n\nLemma heap_fun_mono (spec1 : Spec kcfg) (spec2 : Spec kcfg):\n  forall deps d args init_heap ret,\n    heap_fun spec1 deps d args init_heap ret ->\n    (forall x P, spec1 x P -> spec2 x P) ->\n    heap_fun spec2 deps d args init_heap ret.\nProof.\n  intros. unfold heap_fun. destruct d. intros. apply H0. eapply H; eauto.\nQed.\n\nLemma z_spec_mono (spec1 : Spec kcfg) (spec2 : Spec kcfg):\n  forall f deps def,\n     z_spec f spec1 deps def ->\n     (forall x P, spec1 x P -> spec2 x P) ->\n     z_spec f spec2 deps def.\nProof.\n  unfold z_spec, heap_fun. firstorder. eapply heap_fun_mono with spec1.\n  unfold heap_fun. firstorder. assumption.\nQed.\n\nInductive ho_spec (A : Spec kcfg): Spec kcfg :=\n| even_claim :\n    forall OddDef,\n      name OddDef = \"odd\" ->\n      (z_spec Z.odd A [evenDef] OddDef) ->\n      z_spec Z.even (ho_spec A) [OddDef] evenDef\n| odd_claim :\n    forall EvenDef,\n      name EvenDef = \"even\" ->\n      (z_spec Z.even A [oddDef] EvenDef) ->\n      z_spec Z.odd (ho_spec A) [EvenDef] oddDef.\n\nInductive nonho_spec : Spec kcfg :=\n| even_final :\n    z_spec Z.even nonho_spec [oddDef] evenDef\n| odd_final :\n    z_spec Z.odd nonho_spec [evenDef] oddDef.\n\nInductive make_mono (F : Spec kcfg -> Spec kcfg) X: Spec kcfg :=\n  mono_claim :\n    forall A : Spec kcfg,\n      (forall x P, A x P -> X x P) ->\n      forall x P, F A x P -> make_mono F X x P.\n\nDefinition make_increasing : forall (F : Spec kcfg -> Spec kcfg) A x P,\n    F A x P -> make_mono F A x P :=\n  fun F A x P => mono_claim _ _ _ (fun _ _ H => H) x P.\n\nLemma made_mono : forall (F : Spec kcfg -> Spec kcfg),\n   forall A B, (forall x P, A x P -> B x P) ->\n               (forall x P, make_mono F A x P -> make_mono F B x P).\nProof. intros. destruct H. econstructor;eauto. Qed.\n\nLemma my_ho_spec_mono : forall (A : Spec kcfg) x P, make_mono ho_spec A x P -> ho_spec A x P.\nProof.\n  destruct 1. destruct H0;econstructor(solve[eauto using z_spec_mono]).\nQed.\n\n(*Lemma ho_spec_mono :*)\n\nLemma ho_gfp : subspec (nonho_spec) (ho_spec nonho_spec).\nProof.\n  destruct 1.\n  eapply even_claim with (OddDef := oddDef); try eauto. apply odd_final.\n  eapply odd_claim with (EvenDef := evenDef); try eauto. apply even_final. \nQed.\n  \nLemma ho_spec_mono : mono ho_spec.\nProof.\n  destruct 2; econstructor; try(eapply z_spec_mono; eassumption; apply H); eassumption.\nQed. \n\nLemma ho_ok : sound kstep nonho_spec.\nProof.\n  unfold sound. apply ok with ho_spec. apply ho_spec_mono.\n  intros. \n  destruct 1. destruct OddDef. simpl in H, H1. \n  eapply sstep. step_solver.\n  do 6 (eapply tstep; try apply ho_spec_mono; try step_solver). \n  simpl.\n  split_bool (y =? 0);use_assumptions.\n  do 2 (eapply tstep; try apply ho_spec_mono; try step_solver). \n  eapply tdone; try apply ho_spec_mono; done_solver.\n  do 8 (eapply tstep; try apply ho_spec_mono; try step_solver). \n  simpl.\n  eapply ttrans; try apply ho_spec_mono.\n\n  eapply z_spec_mono with (spec2 := T (step kstep) ho_spec A) in H0. eapply H0.\n  simpl;equate_maps. assumption. pat_solver.\n  intros. eapply Tf_id. trivial.\n  trans_use_result.\n  do 2 (eapply tstep; try apply ho_spec_mono; try step_solver).\n  eapply tdone. apply ho_spec_mono. done_solver.\n  rewrite Z.sub_1_r, Z.odd_pred. trivial.\n\n  (* Now odd *)\n\n  destruct EvenDef. simpl in H, H1. \n  eapply sstep. step_solver.\n  do 6 (eapply tstep; try apply ho_spec_mono; try step_solver).\n  simpl.\n  split_bool (y =? 0);use_assumptions.\n  do 2 (eapply tstep; try apply ho_spec_mono; try step_solver).\n  eapply tdone; try apply ho_spec_mono; done_solver.\n  do 8 (eapply tstep; try apply ho_spec_mono; try step_solver).\n  simpl.\n  eapply ttrans; try apply ho_spec_mono.\n\n  eapply z_spec_mono in H0.\n  eapply H0.\n  simpl;equate_maps. assumption. pat_solver.\n  intros. eapply Tf_id. trivial.\n  trans_use_result.\n  do 2 (eapply tstep; try apply ho_spec_mono; try step_solver).\n  eapply tdone. apply ho_spec_mono. done_solver.\n  rewrite Z.sub_1_r, Z.even_pred. trivial.\n\n  apply ho_gfp.\nQed.\n\n(* Print Assumptions ho_ok. *)\n\n", "meta": {"author": "Formal-Systems-Laboratory", "repo": "coinduction", "sha": "1031da11c4a4523ea9b7347036b6bdabc7620e1d", "save_path": "github-repos/coq/Formal-Systems-Laboratory-coinduction", "path": "github-repos/coq/Formal-Systems-Laboratory-coinduction/coinduction-1031da11c4a4523ea9b7347036b6bdabc7620e1d/coinduction-proofs/himp/examples/ex03_list/ho.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.29695075658050757}}
{"text": "Require Import Bool List.\nRequire Import ExtLib.Tactics.Consider.\nRequire Import MirrorShard.Expr.\nRequire Import MirrorShard.SepExpr.\nRequire Import MirrorShard.Env MirrorShard.Prover.\nRequire Import SymEval.\nRequire Import Word Memory IL SepIL SymIL ILEnv.\nRequire Import PropX PropXTac Nomega NArith.\n\nSet Implicit Arguments.\n\nDefinition array (ws : list W) (p : W) : HProp := ptsto32m _ p O ws.\n\nFixpoint div4 (n : nat) : option nat :=\n  match n with\n    | O => Some O\n    | S (S (S (S n'))) => match div4 n' with\n                            | None => None\n                            | Some n'' => Some (S n'')\n                          end\n    | _ => None\n  end.\n\nFixpoint selN (ws : list W) (n : nat) : W :=\n  match ws with\n    | nil => wzero _\n    | w :: ws' => match n with\n                    | O => w\n                    | S n' => selN ws' n'\n                  end\n  end.\n\nDefinition sel (ws : list W) (a : W) : W :=\n  selN ws (wordToNat a).\n\nFixpoint updN (ws : list W) (n : nat) (v : W) : list W :=\n  match ws with\n    | nil => nil\n    | w :: ws' => match n with\n                    | O => v :: ws'\n                    | S n' => w :: updN ws' n' v\n                  end\n  end.\n\nDefinition upd (ws : list W) (a v : W) : list W :=\n  updN ws (wordToNat a) v.\n\nDefinition bedrock_type_listW : type :=\n  {| Expr.Impl := list W\n   ; Expr.Eqb := (fun _ _ => false)\n   ; Expr.Eqb_correct := @ILEnv.all_false_compare _ |}.\n\nDefinition types_r : Env.Repr Expr.type :=\n  Eval cbv beta iota zeta delta [ Env.listOptToRepr ] in \n    let lst := \n      Some ILEnv.bedrock_type_W ::\n      Some ILEnv.bedrock_type_setting_X_state ::\n      None ::\n(*      None :: *)\n      None ::\n      Some ILEnv.bedrock_type_nat ::\n      Some bedrock_type_listW :: nil\n    in Env.listOptToRepr lst EmptySet_type.\n\nLocal Notation \"'pcT'\" := (tvType 0).\nLocal Notation \"'stT'\" := (tvType 1).\nLocal Notation \"'wordT'\" := (tvType 0).\nLocal Notation \"'natT'\" := (tvType 4).\nLocal Notation \"'listWT'\" := (tvType 5).\n\nLocal Notation \"'wplusF'\" := 0.\nLocal Notation \"'wmultF'\" := 2.\nLocal Notation \"'wltF'\" := 4.\nLocal Notation \"'natToWF'\" := 5.\nLocal Notation \"'lengthF'\" := 6.\nLocal Notation \"'selF'\" := 7.\nLocal Notation \"'updF'\" := 8.\n\nSection parametric.\n  Variable types' : list type.\n  Definition types := repr types_r types'.\n  Variable Prover : ProverT types.\n\n  Definition natToW_r : signature types.\n    refine {| Domain := natT :: nil; Range := wordT |}.\n    exact natToW.\n  Defined.\n\n  Definition wlength_r : signature types.\n    refine {| Domain := listWT :: nil; Range := natT |}.\n    exact (@length _).\n  Defined.\n\n  Definition sel_r : signature types.\n    refine {| Domain := listWT :: wordT :: nil; Range := wordT |}.\n    exact sel.\n  Defined.\n\n  Definition upd_r : signature types.\n    refine {| Domain := listWT :: wordT :: wordT :: nil; Range := listWT |}.\n    exact upd.\n  Defined.\n\n  Definition funcs_r : Env.Repr (signature types) :=\n    Eval cbv beta iota zeta delta [ Env.listOptToRepr ] in \n      let lst := \n        Some (ILEnv.wplus_r types) ::\n        None ::\n        Some (ILEnv.wmult_r types) ::\n(*        None :: *)\n        None ::\n        Some (ILEnv.wlt_r types) ::\n        Some (ILEnv.natToW_r types) ::\n        Some wlength_r ::\n        Some sel_r ::\n        Some upd_r ::\n        nil\n      in Env.listOptToRepr lst (Default_signature _).\n\n  Definition deref (e : expr types) : option (expr types * expr types) :=\n    match e with\n      | Func wplusF (base :: offset :: nil) =>\n        match offset with\n          | Func wmultF (Func natToWF (Const t k :: nil) :: offset :: nil) =>\n            match t return tvarD types t -> _ with\n              | natT => fun k => match k with\n                                   | 4 => Some (base, offset)\n                                   | _ => None\n                                 end\n              | _ => fun _ => None\n            end k\n          | Func natToWF (Const t k :: nil) =>\n            match t return tvarD types t -> _ with\n              | natT => fun k => match div4 k with\n                                   | None => None\n                                   | Some k' => Some (base, Func natToWF (Const (types := types) (t := natT) k'\n                                     :: nil))\n                                 end\n              | _ => fun _ => None\n            end k\n          | _ => None\n        end\n      | _ => None\n    end.\n\n  Definition sym_read (summ : Prover.(Facts)) (args : list (expr types)) (p : expr types)\n    : option (expr types) :=\n    match args with\n      | ws :: p' :: nil =>\n        match deref p with\n          | None => None\n          | Some (base, offset) =>\n            if Prover.(Prove) summ (Equal wordT p' base)\n              && Prover.(Prove) summ (Func wltF (offset :: Func natToWF (Func lengthF (ws :: nil)\n                :: nil) :: nil))\n              then Some (Func selF (ws :: offset :: nil))\n              else None\n        end\n      | _ => None\n    end.\n\n  Definition sym_write (summ : Prover.(Facts)) (args : list (expr types)) (p v : expr types)\n    : option (list (expr types)) :=\n    match args with\n      | ws :: p' :: nil =>\n        match deref p with\n          | None => None\n          | Some (base, offset) =>\n            if Prover.(Prove) summ (Equal wordT p' base)\n              && Prover.(Prove) summ (Func wltF (offset :: Func natToWF (Func lengthF (ws :: nil)\n                :: nil) :: nil))\n              then Some (Func updF (ws :: offset :: v :: nil) :: p' :: nil)\n              else None\n        end\n      | _ => None\n    end.\nEnd parametric.\n\nDefinition MemEval types' : @MEVAL.PredEval.MemEvalPred (types types').\n  apply MEVAL.PredEval.Build_MemEvalPred.\n  apply sym_read.\n  apply sym_write.\n  exact (fun _ _ _ _ => None).\n  exact (fun _ _ _ _ _ => None).\nDefined.\n\nLtac destr' E := destruct E. (*case_eq E; intros;\n  try match goal with\n        | [ H : _ = _ |- _ ] => rewrite H in *\n      end.*)\n\nLtac destr simp E :=\n  match E with\n    | context[match _ with None => _ | _ => _ end] => fail 1\n    | div4 _ => fail 1\n    | _ => destr' E; discriminate || tauto\n    | _ => destr' E; try (discriminate || tauto); [simp]\n  end.\n\nLtac destr2 simp E :=\n  match E with\n    | context[match _ with None => _ | _ => _ end] => fail 1\n    | div4 _ => fail 1\n    | _ => destr' E; try (discriminate || tauto); [simp]\n    | _ => destr' E; try (discriminate || tauto); [ | ]; simp\n  end.\n\nLtac stripSuffix E :=\n  match E with\n    | ?E = _ => stripSuffix E\n    | ?E _ => stripSuffix E\n    | ?E _ _ => stripSuffix E\n    | _ => E\n  end.\n\nLtac doMatch simp P :=\n  match P with\n    | match ?E with 0 => _ | _ => _ end => destr2 simp E\n    | match ?E with nil => _ | _ => _ end => destr simp E\n    | match ?E with Const _ _ => _ | _ => _ end => destr2 simp E\n    | match ?E with tvProp => _ | _ => _ end => destr simp E\n    | match ?E with None => _ | _ => _ end => destr simp E\n    | match ?E with left _ => _ | _ => _ end => destr2 simp E\n  end.\n\nLtac deconstruct' simp := match goal with\n                            | [ H : Some _ = Some _ |- _ ] => injection H; clear H; intros; subst; simp\n                            | [ H : ?P |- _ ] =>\n                              let P := stripSuffix P in\n                                doMatch simp P\n                                || match P with\n                                     | match ?P with None => _ | _ => _ end =>\n                                       let P := stripSuffix P in\n                                         doMatch simp P\n                                   end\n                          end.\n\nLtac deconstruct := repeat deconstruct' ltac:(simpl in *).\n\nSection correctness.\n  Variable types' : list type.\n  Definition types0 := types types'.\n\n  Definition ssig : SEP.predicate types0.\n    refine (SEP.PSig _ (listWT :: wordT :: nil) _).\n    exact array.\n  Defined.\n\n  Definition ssig_r : Env.Repr (SEP.predicate types0) :=\n    Eval cbv beta iota zeta delta [ Env.listOptToRepr ] in \n      let lst := \n        None :: Some ssig :: nil\n      in Env.listOptToRepr lst (SEP.Default_predicate _).\n\n  Variable funcs' : functions types0.\n  Definition funcs := Env.repr (funcs_r _) funcs'.\n\n  Variable Prover : ProverT types0.\n  Variable Prover_correct : ProverT_correct Prover funcs.\n\n  Lemma div4_correct' : forall n0 n m, (n < n0)%nat\n    -> div4 n = Some m\n    -> n = 4 * m.\n    induction n0; simpl; intuition.\n    destruct n; simpl in *.\n    injection H0; omega.\n    repeat destr ltac:(simpl in *) n.\n    specialize (IHn0 n).\n    destruct (div4 n).\n    injection H0.\n    rewrite (IHn0 n1); auto; omega.\n    discriminate.\n  Qed.\n\n  Lemma div4_correct : forall n m, div4 n = Some m\n    -> n = 4 * m.\n    intros; eapply div4_correct'; eauto.\n  Qed.    \n\n  Lemma deref_correct : forall uvars vars e w base offset,\n    exprD funcs uvars vars e wordT = Some w\n    -> deref e = Some (base, offset)\n    -> exists wb, exists wo,\n      exprD funcs uvars vars base wordT = Some wb\n      /\\ exprD funcs uvars vars offset wordT = Some wo\n      /\\ w = wb ^+ $4 ^* wo.\n    destruct e; simpl; intuition; try discriminate.\n    repeat (deconstruct' ltac:(simpl in *); []).\n    case_eq (exprD funcs uvars vars e wordT); intros;\n      match goal with\n        | [ H : _ = _ |- _ ] => rewrite H in *\n      end; try discriminate.\n    deconstruct; eauto.\n    match goal with\n      | [ _ : context[div4 ?N] |- _ ] => specialize (div4_correct N); destruct (div4 N)\n    end; try discriminate.\n    deconstruct.\n    specialize (H2 _ (refl_equal _)); subst.\n    repeat (esplit || eassumption).\n    replace (n + (n + (n + (n + 0)))) with (n * 4) by omega.\n    rewrite natToW_times4.\n    W_eq.\n  Qed.\n\n  Fixpoint ptsto32m' sos (a : W) (offset : nat) (vs : list W) : hpropB sos :=\n    match vs with\n      | nil => Emp\n      | v :: vs' => (a ^+ $(offset)) =*> v * ptsto32m' sos a (4 + offset) vs'\n    end%Sep.\n\n  Theorem ptsto32m'_in : forall a cs stn vs offset m,\n    interp cs (ptsto32m _ a offset vs stn m)\n    -> interp cs (ptsto32m' _ a offset vs stn m).\n    induction vs.\n\n    auto.\n\n    unfold ptsto32m, ptsto32m'.\n    fold ptsto32m; fold ptsto32m'.\n    destruct vs; destruct offset; intros.\n\n    replace (a ^+ $0) with a by W_eq.\n    simpl.\n    propxFo.\n    exists m.\n    exists smem_emp; intuition.\n    apply split_comm; apply split_emp. \n    reflexivity.\n    \n    unfold ptsto32m'.\n    apply simplify_bwd.\n    exists m.\n    exists smem_emp; intuition.\n    split.\n    apply split_comm; apply split_emp. reflexivity.\n    split. \n    apply simplify_fwd; assumption.\n    split.\n    constructor.\n    reflexivity.\n\n    replace (a ^+ $0) with a by W_eq.\n    apply simplify_fwd in H.\n    destruct H.\n    destruct H.\n    destruct H.\n    destruct H0.\n    apply simplify_bwd in H0.\n    apply simplify_bwd in H1.\n    apply simplify_bwd.\n    exists x.\n    exists x0.\n    split; auto.\n    split.\n    apply simplify_fwd; assumption.\n    apply simplify_fwd; auto.\n\n    apply simplify_fwd in H.\n    destruct H.\n    destruct H.\n    destruct H.\n    destruct H0.\n    apply simplify_bwd in H0.\n    apply simplify_bwd in H1.\n    apply simplify_bwd.\n    exists x.\n    exists x0.\n    split; auto.\n    split.\n    apply simplify_fwd; assumption.\n    apply simplify_fwd; auto.\n  Qed.\n\n  Lemma smem_read_correct'' : forall cs base stn ws offset i m,\n    interp cs (ptsto32m' _ base (offset * 4) ws stn m)\n    -> (i < length ws)%nat\n    -> smem_read_word stn (base ^+ $((offset + i) * 4)) m = Some (selN ws i).\n    induction ws.\n\n    simpl length.\n    intros.\n    elimtype False.\n    nomega.\n\n    simpl length.\n    unfold ptsto32m'.\n    fold ptsto32m'.\n    intros.\n    destruct i; simpl selN.\n    replace (offset + 0) with offset by omega.\n    apply simplify_fwd in H.\n    destruct H.\n    destruct H.\n    destruct H.\n    destruct H1.\n    destruct H1.\n    simpl in H.\n    eapply MSMF.split_multi_read; eauto.\n\n    apply simplify_fwd in H.\n    destruct H.\n    destruct H.\n    destruct H.\n    destruct H1.\n    apply simplify_bwd in H2.\n    replace (4 + offset * 4) with (S offset * 4) in H2 by omega.\n    eapply (IHws _ i) in H2.\n    eapply split_comm in H.\n    eapply MSMF.split_multi_read in H; eauto. unfold smem_read_word in H2.\n    replace (offset + S i) with (S offset + i) by omega. auto. omega.\n  Qed.\n\n  Lemma smem_get_disjoint : forall a w1 w2 dom m1 m2,\n    disjoint' dom m1 m2\n    -> smem_get' dom a m1 = Some w1\n    -> smem_get' dom a m2 = Some w2\n    -> False.\n  Proof.\n    induction dom; simpl; intuition.\n    discriminate.\n    destruct (M.addr_dec a0 a); subst; try congruence.\n    eauto.\n    destruct (M.addr_dec a0 a); subst; try congruence.\n    eauto.\n  Qed.\n\n  Lemma smem_read_word_disjoint : forall a m m1 m2 w1 w2 addrs,\n    split m m1 m2\n    -> smem_read_word addrs a m1 = Some w1\n    -> smem_read_word addrs a m2 = Some w2\n    -> False.\n  Proof.\n    unfold smem_read_word; intros. \n    unfold MultiMem.multi_read in *.\n    generalize (split_disjoint _ _ _ H). clear H. intros. simpl in *.\n\n    consider (smem_get a m1); intros; try congruence.\n    assert (in_domain a m1). red. congruence.\n    eapply H in H3. apply H3. red. \n    consider (smem_get a m2); try congruence.\n  Qed.\n\n  Lemma array_bound' : forall cs base stn ws m i,\n    (0 < i < length ws)%nat\n    -> base ^+ $(i * 4) = base\n    -> interp cs (ptsto32m' _ base 0 ws stn m)\n    -> False.\n    destruct ws; simpl length; intros.\n\n    elimtype False; omega.\n\n    simpl in H1.\n    propxFo.\n    destruct i; try omega.\n    generalize (@smem_read_correct'' cs base stn ws 1 i x0).\n    simpl plus.\n    rewrite H0.\n    rewrite wplus_comm in H4.\n    rewrite wplus_unit in H4.\n    intuition.\n    assert (i < length ws)%nat by omega; intuition.\n    eapply smem_read_word_disjoint; eauto.\n  Qed.\n\n  Lemma pow2_pos : forall n, (pow2 n > 0)%nat.\n    induction n; simpl; omega.\n  Qed.\n\n  Lemma pow2_monotone : forall n m,\n    (n < m)%nat\n    -> (pow2 n < pow2 m)%nat.\n    induction 1; simpl; intuition.\n    specialize (pow2_pos n).\n    omega.\n  Qed.\n\n  Lemma pow2_mult : forall m n,\n    pow2 n * pow2 m = pow2 (n + m).\n    induction n; simpl; intuition.\n    repeat rewrite <- IHn.\n    repeat rewrite <- plus_n_O.\n    apply Mult.mult_plus_distr_r.\n  Qed.      \n\n  Lemma array_bound : forall cs ws base stn m,\n    interp cs (array ws base stn m)\n    -> (length ws < pow2 32)%nat.\n  Proof. \n    intros.\n    Require Import Arith.\n    destruct (lt_dec (length ws) (pow2 32)); auto.\n    elimtype False.\n    apply ptsto32m'_in in H.\n    apply (@array_bound' _ _ _ _ _ (pow2 30)) in H; auto.\n    split.\n    unfold pow2; omega.\n    specialize (@pow2_monotone 30 32).\n    omega.\n    change (pow2 30 * 4) with (pow2 30 * pow2 2).\n    rewrite pow2_mult.\n    simpl plus.\n    clear.\n    rewrite wplus_alt.\n    unfold wplusN, wordBinN.\n    rewrite natToWord_pow2.\n    rewrite roundTrip_0.\n    rewrite plus_0_r.\n    apply natToWord_wordToNat.\n  Qed.\n\n  Lemma smem_read_correct' : forall cs base stn ws i m,\n    interp cs (array ws base stn m)\n    -> i < $(length ws)\n    -> smem_read_word stn (base ^+ $4 ^* i) m = Some (sel ws i).\n  Proof.\n    unfold sel; intros; rewrite <- (@smem_read_correct'' cs base stn ws 0 (wordToNat i) m).\n    f_equal.\n    simpl plus.\n    rewrite natToW_times4.\n    unfold natToW.\n    rewrite natToWord_wordToNat.\n    W_eq.\n\n    apply ptsto32m'_in; auto. \n\n    red in H0.\n    apply Nlt_out in H0.\n    repeat rewrite wordToN_nat in *.\n    repeat rewrite Nat2N.id in *.\n    rewrite wordToNat_natToWord_idempotent in H0; auto.\n    apply array_bound in H.\n    apply Nlt_in.\n    rewrite Nat2N.id.\n    rewrite Npow2_nat.\n    assumption.\n  Qed.\n\n  Lemma sym_read_correct : forall args uvars vars cs summ pe p ve m stn,\n    sym_read Prover summ args pe = Some ve ->\n    Valid Prover_correct uvars vars summ ->\n    exprD funcs uvars vars pe wordT = Some p ->\n    match \n      applyD (exprD funcs uvars vars) (SEP.SDomain ssig) args _ (SEP.SDenotation ssig)\n      with\n      | None => False\n      | Some p => PropX.interp cs (p stn m)\n    end ->\n    match exprD funcs uvars vars ve wordT with\n      | Some v =>\n        smem_read_word stn p m = Some v\n      | _ => False\n    end.\n  Proof.\n    simpl; intuition.\n    do 3 (destruct args; simpl in *; intuition; try discriminate).\n    generalize (deref_correct uvars vars pe); destr ltac:(simpl in *) (deref pe); intro Hderef.\n    destruct p0.\n\n    repeat  match goal with\n             | [ H : Valid _ _ _ _, _ : context[Prove Prover ?summ ?goal] |- _ ] =>\n               match goal with\n                 | [ _ : context[exprD _ _ _ goal _] |- _ ] => fail 1\n                 | _ => specialize (@Prove_correct _ _ _ Prover_correct _ _ summ H goal); intro\n               end\n           end; unfold ValidProp in *; simpl in *.\n\n    match goal with\n      | [ _ : (if ?E then _ else _) = Some _ |- _ ] => case_eq E; intro Heq; rewrite Heq in *\n    end; try discriminate.\n    unfold types0 in *; simpl in *.\n    unfold Provable in *; simpl in *.\n    deconstruct.\n    repeat match goal with\n             | [ H : _ |- _ ] => apply andb_prop in H; intuition\n           end.\n    rewrite H1 in *.\n    specialize (Hderef _ _ _ (refl_equal _) (refl_equal _)); destruct Hderef as [ ? [ ] ]; intuition.\n    subst.\n    simpl in *.\n    rewrite H4 in *.\n    rewrite H7 in *.\n    subst.\n    eapply smem_read_correct'; eauto.\n  Qed.\n\n  Theorem ptsto32m'_out : forall a cs stn vs offset m,\n    interp cs (ptsto32m' _ a offset vs stn m)\n    -> interp cs (ptsto32m _ a offset vs stn m).\n  Proof.\n    induction vs.\n\n    auto.\n\n    unfold ptsto32m, ptsto32m'.\n    fold ptsto32m; fold ptsto32m'.\n    destruct vs; destruct offset; intros.\n\n    replace (a ^+ $0) with a in * by W_eq.\n    simpl.\n    propxFo.\n    { rewrite <- H1.\n      f_equal.\n      eapply split_emp. subst.\n      apply split_comm; eauto. }\n    { apply split_comm in H3.\n      subst. eapply split_emp in H3. red in H3. subst.\n      specialize (H7 a'). intuition. }\n\n    { apply simplify_fwd in H.\n      destruct H.\n      destruct H.\n      destruct H.\n      destruct H0.\n      apply simplify_bwd in H0.\n      replace m with x; auto.\n      symmetry; eapply split_emp.\n      apply split_comm; eauto.    \n      simpl in H. simpl in H1. intuition; subst; auto. }\n\n    { replace (a ^+ $0) with a in * by W_eq.\n      apply simplify_fwd in H.\n      apply simplify_bwd.\n      destruct H.\n      destruct H.\n      destruct H.\n      destruct H0.\n      exists x; exists x0; split.\n      auto.\n      split; auto.\n      apply simplify_fwd.\n      apply simplify_bwd in H1.\n      auto. }\n\n    { apply simplify_fwd in H.\n      apply simplify_bwd.\n      destruct H.\n      destruct H.\n      destruct H.\n      destruct H0.\n      exists x; exists x0; split.\n      auto.\n      split; auto.\n      apply simplify_fwd.\n      apply simplify_bwd in H1.\n      auto. }\n    Qed.\n\n  Lemma smem_write_correct'' : forall cs base stn v ws i m offset,\n    (i < length ws)%nat\n    -> interp cs (ptsto32m' _ base (offset * 4) ws stn m)\n    -> exists m', smem_write_word stn (base ^+ $4 ^* $(offset + i)) v m = Some m'\n      /\\ PropX.interp cs ((ptsto32m' _ base (offset * 4) (updN ws i v)) stn m').\n  Proof.\n    induction ws; simpl length; intros.\n\n    inversion H.\n\n    unfold ptsto32m' in *.\n    fold ptsto32m' in *.\n    destruct i; simpl updN.\n    { rewrite wmult_comm.\n      rewrite <- natToW_times4.\n      replace (offset + 0) with offset by omega.\n      unfold ptsto32m'.\n      fold ptsto32m'.\n      apply simplify_fwd in H0.\n      destruct H0.\n      destruct H0.\n      destruct H0.\n      destruct H1.\n      hnf in H1.\n      unfold natToW.\n      destruct H1.\n      \n      unfold smem_read_word in *.\n\n      match goal with \n        | _ : ?X = Some _ |- _ =>\n          assert (X <> None) by congruence\n      end.\n      specialize (@MSMF.smem_set_get_valid_multi W 4 (fun a : W =>\n                                                        let '(a0, b, c, d) := footprint_w a in (a0, (b, (c, (d, tt)))))\n                                                 (fun v : MultiMem.vector B 4 =>\n                                                    let '(a, (b, (c, (d, _)))) := v in implode stn (a, b, c, d))\n                                                 (fun v0 : W =>\n                                                    let '(a0, b, c, d) := explode stn v0 in (a0, (b, (c, (d, tt)))))\n                                                 (base ^+ $ (offset * 4)) v x H4); clear H4; intro.\n      match goal with \n        | _ : not (?X = None) |- _ =>\n          consider X; try congruence; intros\n      end.\n      clear H5.\n      simpl in H0.\n      generalize H4.\n      eapply MSMF.split_multi_write in H4; try solve [ intuition eauto ].\n      destruct H4. destruct H4. intro.\n      exists (join s x0); split. \n      { destruct H4; subst; auto. }\n      { unfold starB, star, STK.istar.\n        eapply Exists_I with (B := s). eapply Exists_I with (B := x0).\n        eapply And_I.\n        apply Inj_I. destruct H4; split; auto.\n        eapply And_I. 2: propxFo.\n        apply Inj_I.\n        split.\n        { unfold smem_read_word, MultiMem.multi_read.\n          eapply MSMF.smem_read_write_eq_multi' with (k := (fun v0 : MultiMem.vector B 4 =>\n      let '(a0, (b, (c, (d, _)))) := v0 in implode stn (a0, b, c, d))) in H6.\n          clear - H6. etransitivity. eapply H6. f_equal.\n          clear. consider (explode stn v); simpl. destruct p as [ [ ] ]. intros. \n          rewrite <- H. eapply implode_explode.\n          Theorem footprint_w_NoDup : forall p,\n                                        MultiMem.NoDup_v M.addr 4\n                                                         (let '(a0, b, c, d) := footprint_w p in\n                                                          (a0, (b, (c, (d, tt))))).\n          Proof.\n            clear. Opaque natToWord. simpl; intros.\n            cut (MultiMem.NoDup_v M.addr 4\n                                     (p ^+ $(0), (p ^+ $ (1), (p ^+ $ (2), (p ^+ $ (3), tt))))).\n            rewrite Word.wplus_comm. rewrite Word.wplus_unit. auto.\n            repeat constructor; simpl; intuition; auto;\n            match goal with\n              | H0 : _ = _ |- _ =>\n                do 2 (rewrite (Word.wplus_comm p) in H0); apply Word.wplus_cancel in H0; inversion H0\n            end.\n          Qed.\n          eapply footprint_w_NoDup. }\n        { intro. specialize (H3 a'). intuition.\n          erewrite <- MSMF.smem_multi_write_footprint.\n          eassumption. eapply H6.\n          clear - H8 H7 H9 H11. simpl. intuition. } } }\n    { simpl.\n      eapply STK.interp_star in H0. do 3 destruct H0. destruct H1.\n      replace (base ^+ $ (4) ^* $ (offset + S i)) with\n              (base ^+ $ (4) ^* $ ((S offset) + i)) in H2 by (f_equal; f_equal; f_equal; omega).\n      assert (i < length ws)%nat by omega.\n      destruct (@IHws i x0 (S offset) H3 H2).\n      destruct H4. replace (offset + S i)%nat with (S offset + i)%nat by omega.\n      generalize H4; intro.\n      eapply MSMF.split_multi_write in H4. 2: eapply split_comm; eassumption.\n      destruct H4. intuition. eexists. split. eapply H8.\n      eapply Exists_I with (B := x).\n      eapply Exists_I with (B := x1).\n      eapply And_I.\n      2: eapply And_I; eauto.\n      eapply Inj_I. eapply split_comm; auto. }\n  Qed.\n\n  Lemma smem_write_correct' : forall i ws cs base stn m v,\n    i < natToW (length ws)\n    -> interp cs (array ws base stn m)\n    -> exists m', smem_write_word stn (base ^+ $4 ^* i) v m = Some m'\n      /\\ PropX.interp cs ((array (upd ws i v) base) stn m').\n  Proof.\n    intros.\n    destruct (@smem_write_correct'' cs base stn v ws (wordToNat i) m 0).\n    \n    red in H.\n    apply Nlt_out in H.\n    repeat rewrite wordToN_nat in *.\n    repeat rewrite Nat2N.id in *.\n    rewrite wordToNat_natToWord_idempotent in H; auto.\n    apply array_bound in H0.\n    apply Nlt_in.\n    rewrite Nat2N.id.\n    rewrite Npow2_nat.\n    assumption. \n\n    apply ptsto32m'_in; auto.\n\n    intuition.\n    simpl plus in *.\n    simpl mult in *.\n    rewrite natToWord_wordToNat in H2.\n    exists x; split; auto.\n    apply ptsto32m'_out; auto.\n  Qed.\n\n  Lemma sym_write_correct : forall args uvars vars cs summ pe p ve v m stn args',\n    sym_write Prover summ args pe ve = Some args' ->\n    Valid Prover_correct uvars vars summ ->\n    exprD funcs uvars vars pe wordT = Some p ->\n    exprD funcs uvars vars ve wordT = Some v ->\n    match\n      applyD (@exprD _ funcs uvars vars) (SEP.SDomain ssig) args _ (SEP.SDenotation ssig)\n      with\n      | None => False\n      | Some p => PropX.interp cs (p stn m)\n    end ->\n    match \n      applyD (@exprD _ funcs uvars vars) (SEP.SDomain ssig) args' _ (SEP.SDenotation ssig)\n      with\n      | None => False\n      | Some pr => \n        match smem_write_word stn p v m with\n          | None => False\n          | Some sm' => PropX.interp cs (pr stn sm')\n        end\n    end.\n  Proof.\n    simpl; intuition.\n    do 3 (destruct args; simpl in *; intuition; try discriminate).\n    generalize (deref_correct uvars vars pe); destr ltac:(simpl in *) (deref pe); intro Hderef.\n    destruct p0.\n\n    repeat  match goal with\n             | [ H : Valid _ _ _ _, _ : context[Prove Prover ?summ ?goal] |- _ ] =>\n               match goal with\n                 | [ _ : context[exprD _ _ _ goal _] |- _ ] => fail 1\n                 | _ => specialize (@Prove_correct _ _ _ Prover_correct _ _ summ H goal); intro\n               end\n           end; unfold ValidProp in *; simpl in *.\n\n    match goal with\n      | [ _ : (if ?E then _ else _) = Some _ |- _ ] => case_eq E; intro Heq; rewrite Heq in *\n    end; try discriminate.\n    unfold types0 in *; simpl in *.\n    unfold Provable in *; simpl in *.\n    deconstruct.\n    repeat match goal with\n             | [ H : _ |- _ ] => apply andb_prop in H; intuition\n           end.\n    rewrite H1 in *.\n    rewrite H2 in *.\n    specialize (Hderef _ _ _ (refl_equal _) (refl_equal _)); destruct Hderef as [ ? [ ] ]; intuition.\n    subst.\n    simpl in *.\n    rewrite H8 in *.\n    rewrite H5 in *.\n    subst.\n    eapply smem_write_correct' in H3; eauto.\n    destruct H3; intuition.\n    rewrite H7. assumption.\n  Qed.\nEnd correctness.\n\nDefinition MemEvaluator types' : MEVAL.MemEvaluator (types types') :=\n  Eval cbv beta iota zeta delta [ MEVAL.PredEval.MemEvalPred_to_MemEvaluator ] in \n    @MEVAL.PredEval.MemEvalPred_to_MemEvaluator _ (MemEval types') 1.\n\nTheorem MemEvaluator_correct types' funcs' preds'\n  : @MEVAL.MemEvaluator_correct (Env.repr types_r types') (tvType 0) (tvType 1) \n  (MemEvaluator (Env.repr types_r types')) (funcs funcs') (Env.repr (ssig_r _) preds')\n  (IL.settings * IL.state) (tvType 0) (tvType 0)\n  (@IL_mem_satisfies (types types')) (@IL_ReadWord (types types')) (@IL_WriteWord (types types'))\n  (@IL_ReadByte (types types')) (@IL_WriteByte (types types')).\nProof.\n  intros. eapply (@MemPredEval_To_MemEvaluator_correct (types types')); try reflexivity;\n  intros; unfold MemEval in *; simpl in *; try discriminate.\n  { generalize (@sym_read_correct types' funcs' P PE). simpl in *. intro.\n    eapply H3 in H; eauto. }\n  { generalize (@sym_write_correct types' funcs' P PE). simpl in *. intro.\n    eapply H4 in H; eauto. }\nQed.\n\nDefinition pack : MEVAL.MemEvaluatorPackage types_r (tvType 0) (tvType 1) (tvType 0) (tvType 0)\n  IL_mem_satisfies IL_ReadWord IL_WriteWord IL_ReadByte IL_WriteByte :=\n\n  @MEVAL.Build_MemEvaluatorPackage types_r (tvType 0) (tvType 1) (tvType 0) (tvType 0) \n  IL_mem_satisfies IL_ReadWord IL_WriteWord IL_ReadByte IL_WriteByte\n  types_r\n  funcs_r\n  (fun ts => Env.listOptToRepr (None :: Some (ssig ts) :: nil)\n    (SEP.Default_predicate (Env.repr types_r ts)))\n  (fun ts => MemEvaluator _)\n  (fun ts fs ps => MemEvaluator_correct _ _).\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/sep/Array.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.296936794421029}}
{"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 O E Eprime P A B C D A1 B1 C1 D1 C1prime M D1prime N : Universe, ((wd_ O E /\\ (wd_ P B /\\ (wd_ A B /\\ (wd_ O M /\\ (wd_ M C1 /\\ (wd_ P D /\\ (wd_ O C1 /\\ (wd_ C1 C1prime /\\ (wd_ O C1prime /\\ (wd_ E Eprime /\\ (wd_ O Eprime /\\ (wd_ P A /\\ (wd_ A C /\\ (wd_ P C /\\ (wd_ C D /\\ (wd_ C1prime A1 /\\ (wd_ O A1 /\\ (wd_ O D1 /\\ (wd_ O D1prime /\\ (wd_ O B1 /\\ (wd_ M C1prime /\\ (wd_ N O /\\ (wd_ D1 N /\\ (wd_ D1 D1prime /\\ (wd_ N D1prime /\\ (wd_ A1 Eprime /\\ (col_ P A B /\\ (col_ P C D /\\ (col_ O E A1 /\\ (col_ O E B1 /\\ (col_ O E C1 /\\ (col_ O E D1 /\\ (col_ O M N /\\ (col_ D A B /\\ (col_ N D1 D1prime /\\ (col_ M C1 C1prime /\\ (col_ O C1prime D1prime /\\ (col_ O A1 C1 /\\ col_ O C1 D1)))))))))))))))))))))))))))))))))))))) -> col_ P A 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_1418.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.29686411998986467}}
{"text": "From mathcomp Require Import ssreflect ssrbool ssrnat eqtype ssrfun seq path.\nFrom Coq Require Import Eqdep Relation_Operators.\nFrom pcm Require Import axioms pred prelude ordtype finmap pcm unionmap heap.\nFrom DiSeL Require Import Freshness State EqTypeX DepMaps Protocols.\nFrom DiSeL Require Import Worlds NetworkSem Rely Actions Injection Process.\nFrom DiSeL Require Import Always HoareTriples InferenceRules InductiveInv While.\nFrom DiSeL Require Import TwoPhaseProtocol.\n\nModule TwoPhaseCoordinator.\nSection TwoPhaseCoordinator.\n\nVariable l : Label.\nVariables (cn : nid) (pts : seq nid) (others : seq nid).\nHypothesis Hnin : cn \\notin pts.\nHypothesis Puniq : uniq pts.\nHypothesis PtsNonEmpty : pts != [::].\n\nDefinition tpc := TwoPhaseCommitProtocol others Hnin l.\nNotation W := (mkWorld tpc).\n\nSection CoordinatorImplementation.\n\n(************** Atomic actions **************)\n\n(* Three send-actions, e -- id of the current era *)\n\n(* TODO: automate the proofs of obligations *)\nProgram Definition send_prep e data to :=\n  act (@send_action_wrapper W tpc cn l (prEq tpc) (cn_send_prep_trans cn pts others) _ (e :: data) to).\nNext Obligation. by rewrite InE; do![left|right]. Qed.\n\nProgram Definition send_commit e to :=\n  act (@send_action_wrapper W tpc cn l (prEq tpc) (cn_send_commit_trans cn pts others) _ [:: e] to).\nNext Obligation. by rewrite !InE; right; left. Qed.\n\nProgram Definition send_abort e to :=\n  act (@send_action_wrapper W tpc cn l (prEq tpc) (cn_send_abort_trans cn pts others) _ [:: e] to).\nNext Obligation. by rewrite !InE; right; right; left. Qed.\n\n(* Three receive-actions *)\n\n(* This action actually encompasses two receive-transitions *)\nProgram Definition tryrecv_prep_resp := act (@tryrecv_action_wrapper W cn\n      (* filter *)\n      (fun k _ t b => (k == l) && ((t == prep_yes) || (t == prep_no))) _).\n(* TODO: automate these kinds of proofs *)\nNext Obligation. by case/andP: H=>/eqP->_; rewrite /ddom domPt inE/=. Qed.\n\nProgram Definition tryrecv_commit_ack :=\n  act (@tryrecv_action_wrapper W cn (fun k _ t b => (k == l) && (t == commit_ack)) _).\nNext Obligation. by case/andP: H=>/eqP->_; rewrite /ddom domPt inE/=. Qed.\n\nProgram Definition tryrecv_abort_ack :=\n  act (@tryrecv_action_wrapper W cn (fun k _ t b => (k == l) && (t == abort_ack)) _).\nNext Obligation. by case/andP: H=>/eqP->_; rewrite /ddom domPt inE/=. Qed.\n\n\n(************** Coordinator code **************)\n\n(*** Reading internal state ***)\nArguments TPCProtocol.TPCCoh {cn pts others}.\nNotation coh := (@TPCProtocol.TPCCoh cn pts others).\nNotation getS s := (getStatelet s l).\nNotation loc i := (getLocal cn (getStatelet i l)).\n\nExport TPCProtocol.\n\n(*************************************)\n(* Reading current state - with spec *)\n(*************************************)\n\nProgram Definition read_round :\n  {(ecl : (nat * CState) * Log)}, DHT [cn, W]\n  (fun i => loc i = st :-> ecl.1 \\+ log :-> ecl.2,\n   fun r m => loc m = st :-> ecl.1 \\+ log :-> ecl.2 /\\\n              exists (pf : coh (getS m)), r = (getStC pf).1) :=\n  Do (act (@skip_action_wrapper W cn l tpc (prEq tpc) _\n                                (fun s pf => (getStC pf).1))).\nNext Obligation.\napply: ghC=>i [[e c]lg]/= E _.\napply: act_rule=>j R; split=>[|r k m]; first by case: (rely_coh R).\ncase=>/=H1[Cj]Z; subst j=>->R'.\nsplit; first by rewrite (rely_loc' l R') (rely_loc' _ R).\ncase: (rely_coh R')=>_; case=>_ _ _ _/(_ l)=>/= pf; rewrite prEq in pf.\nexists pf; move: (rely_loc' l R').\nmove => E'.\napply sym_eq in E'.\nsuff X: getStC (Actions.safe_local (prEq tpc) H1) = getStC pf by rewrite X.\nby apply: (getStCE pf _ E').\nQed.\n\n(*******************************************)\n(***   Sending out proposals in a loop   ***)\n(*******************************************)\n\nDefinition send_prep_loop_spec (e : nat) d := forall to_send,\n  {l : Log}, DHT [cn, W]\n  (fun i =>\n     loc i = st :-> (e, CInit) \\+ log :-> l /\\ perm_eq pts to_send \\/\n     if to_send == [::]\n     then loc i = st :-> (e, CWaitPrepResponse d [::]) \\+ log :-> l\n     else exists (ps : seq nid),\n         loc i = st :-> (e, CSentPrep d ps) \\+ log :-> l /\\\n         perm_eq pts (ps ++ to_send),\n   fun r m => r = tt /\\ loc m = st :-> (e, CWaitPrepResponse d [::]) \\+ log :-> l).\n\nProgram Definition send_prep_loop e d :\n  {l : Log}, DHT [cn, W]\n  (fun i => loc i = st :-> (e, CInit) \\+ log :-> l,\n   fun r m => r = tt /\\\n              loc m = st :-> (e, CWaitPrepResponse d [::]) \\+ log :-> l) :=\n  Do (ffix (fun (rec : send_prep_loop_spec e d) to_send =>\n              Do (match to_send with\n                  | to :: tos => send_prep e d to ;; rec tos\n                  | [::] => ret _ _ tt\n                  end)) pts).\n\n(* Verifying the loop invariant *)\nNext Obligation.\napply: ghC=>i1 lg.\n(*********************************)\n(* two cases of the precondition *)\n(*********************************)\ncase=>[[E1 P1 C1]|].\n\n(*--------------------------------------*)\n(* Case 1: We are in the initial state  *)\n(*--------------------------------------*)\n\n- case: to_send P1=>[|to tos Hp].\n  + by move/perm_size=>/=/size0nil=>Z; rewrite Z in (PtsNonEmpty).\n- apply: step; apply:act_rule=>j1 R1/=; split=>[|r k m[Sf]St R2].\n  split=>//=; first by case: (rely_coh R1).\n  + split; first by split=>//; move/perm_mem: Hp->; rewrite inE eqxx.\n    case: (proj2 (rely_coh R1))=>_ _ _ _/(_ l); rewrite (prEq tpc)=>C; exists C.\n    left; exists e; split; last by exists d.\n    by rewrite -(rely_loc' _ R1) in E1; rewrite (getStC_K _ E1).\n  + rewrite /Actions.can_send /nodes inE eqxx andbC/=.\n    by rewrite -(cohD (proj2 (rely_coh R1)))/ddom domPt inE/=.\n  + rewrite /Actions.filter_hooks umfilt0=>???.\n    move => F.\n    apply sym_eq in F.\n    move: F.\n    by move/find_some; rewrite dom0.\ncase: {-1}(Sf)=>_/=[]Hc[C][]; last first.\n- move=>[n][d'][ps][E1'][]Z1 Z2 _; subst n d'.\n  rewrite -(rely_loc' _ R1) in E1.\n  by rewrite (getStC_K C E1) in E1'; discriminate E1'.\ncase=>b[E1'][d'][Z1 Z2]_ _; subst b d'.\nmove: St=>[Z][h][[]Z' G]; subst r h.\napply: (gh_ex (g := lg)).\n\n(* Verifying precondition of the recursive call *)\nhave Pre:\n  (if tos == [::]\n   then loc m = st :-> (e, CWaitPrepResponse d [::]) \\+ log :-> lg\n   else exists ps : seq nid, loc m = st :-> (e, CSentPrep d ps) \\+ log :-> lg /\\ perm_eq pts (ps ++ tos)).\n- case X: ([::] == tos);[move/eqP: X=>X; subst tos; rewrite eqxx|\n                         rewrite eq_sym X].\n  have Y: pts == [:: to] by rewrite (perm_small_eq _ Hp).\n  rewrite /cstep_send/= Y in G.\n  move: (proj2 Hc)=>Y'; rewrite Y' in G=>{Y'}.\n  rewrite [cn_safe_coh _ ](pf_irr _ C) E1' in G. (* TADA! *)\n  rewrite (rely_loc' l R2); subst k; rewrite -(rely_loc' _ R1) in E1.\n  rewrite locE; last apply: (cohVl C).\n  + by rewrite -(pf_irr (cn_in cn pts others) (cn_this_in _ _))\n                  (getStL_Kc _ (cn_in cn pts others) E1).\n  + by rewrite -(cohD (proj2 (rely_coh R1)))/ddom domPt inE/=.\n  by apply: (cohS (proj2 (rely_coh R1))).\n- exists [:: to]; split; last by rewrite cat_cons/=.\n  have Y: pts == [:: to] = false.\n  + apply/negP=>/eqP Z; rewrite Z in Hp.\n    move/perm_size: (Hp).\n    move => F.\n    apply sym_eq in F.\n    move: F.\n    by case=>/size0nil=>Z'; rewrite Z' eqxx in X.\n    (* This part is similar to the previous step *)\n  rewrite /cstep_send/= Y in G.\n  move: (proj2 Hc)=>Y'; rewrite Y' in G=>{Y'}.\n  rewrite [cn_safe_coh _ ](pf_irr _ C) E1' in G. (* TADA! *)\n  rewrite (rely_loc' l R2); subst k; rewrite -(rely_loc' _ R1) in E1.\n  rewrite locE; last apply: (cohVl C).\n  + by rewrite -(pf_irr (cn_in cn pts others) (cn_this_in _ _))\n                  (getStL_Kc _ (cn_in cn pts others) E1).\n  + by rewrite -(cohD (proj2 (rely_coh R1)))/ddom domPt inE/=.\n  by apply: (cohS (proj2 (rely_coh R1))).\n\napply: call_rule'=>/=[Cm|r2 m2]; first by right.\nby case=>//; right.\n\n(*------------------------------------------*)\n(* Case 2: We are in the intermediate state *)\n(*------------------------------------------*)\n\n(*** Subcase 2.1 : The last step of the loop ***)\ncase X: (to_send == [::]).\n- move=>E1 C1; move/eqP: X=>Z; subst to_send.\n  by apply: ret_rule=>m R; split=>//; rewrite (rely_loc' _ R).\n\n(*** Subcase 2.2 : The proper intermediate step ***)\ncase=>ps[E1]Hp C1.\nhave Y: exists to tos, to_send = to :: tos.\n- case: to_send X Hp; first by rewrite eqxx.\n  by move=>to tos _ _; exists to, tos.\ncase: Y=>to[tos] Z; subst to_send=>{X}.\n- apply: step; apply:act_rule=>j1 R1/=; split=>[|r k m[Sf]St R2].\n  split=>//=; first by case: (rely_coh R1).\n  + split; first by split=>//; move/perm_mem: Hp->;\n                    rewrite mem_cat orbC inE eqxx.\n    case: (proj2 (rely_coh R1))=>_ _ _ _/(_ l); rewrite prEq=>C; exists C.\n    right; exists e, d, ps; split=>//.\n      by rewrite -(rely_loc' _ R1) in E1; rewrite (getStC_K _ E1).\n  + move/perm_uniq: Hp; rewrite Puniq.\n    move => F.\n    apply sym_eq in F.\n    move: F.\n    rewrite -cat_rcons cat_uniq -cats1 cat_uniq=>/andP[]/andP[_]/andP[].\n    by rewrite /= orbC/=.\n  + rewrite /Actions.can_send /nodes inE eqxx andbC.\n    by rewrite -(cohD (proj2 (rely_coh R1)))/ddom domPt inE/=.\n  rewrite /Actions.filter_hooks umfilt0=>???.\n  move => F.\n  apply sym_eq in F.\n  move: F.\n  by move/find_some; rewrite dom0.\n(* dismiss the bogus branch *)\ncase: {-1}(Sf)=>_/=[]Hc[C][].\n- case=>b[E1'][d'][Z1 Z2]_; subst b d'.\n  rewrite -(rely_loc' _ R1) in E1.\n  by rewrite (getStC_K C E1) in E1'; discriminate E1'.\nmove=>[n][d'][ps'][E1'][]Z1 Z2 N _ _; subst n d'.\nrewrite -(rely_loc' _ R1) in E1.\nmove: (E1'); rewrite (getStC_K C E1); case=>Z; subst ps'.\nmove: St=>[Z][h][[]Z' G]; subst r h.\napply: (gh_ex (g := lg)).\n\n(* the same precondition, but different state *)\nsuff Pre:\n  (if tos == [::]\n   then loc m = st :-> (e, CWaitPrepResponse d [::]) \\+ log :-> lg\n   else exists ps : seq nid,\n   loc m = st :-> (e, CSentPrep d ps) \\+ log :-> lg /\\ perm_eq pts (ps ++ tos)).\n- apply: call_rule'=>/=[Cm|r2 m2]; first by right.\n  by case=>//; right.\n- case X: ([::] == tos);\n    [move/eqP: X=>X; subst tos; rewrite eqxx| rewrite eq_sym X].\n    rewrite /cstep_send/= (proj2 Hc)/= in G.\n    rewrite [cn_safe_coh _ ](pf_irr _ C) E1' in G.\n  have Y: perm_eq (to :: ps) pts\n    by move: Hp; rewrite (perm_sym pts) perm_catC cat1s.\n  rewrite Y/= in G.\n  rewrite (rely_loc' l R2); subst k; rewrite locE; last apply: (cohVl C).\n  + by rewrite -(pf_irr (cn_in cn pts others) (cn_this_in _ _))\n               (getStL_Kc _ (cn_in cn pts others) E1).\n  + by rewrite -(cohD (proj2 (rely_coh R1)))/ddom domPt inE/=.\n  by apply: (cohS (proj2 (rely_coh R1))).\n\nrewrite /cstep_send/= (proj2 Hc)/= in G.\nrewrite [cn_safe_coh _ ](pf_irr _ C) E1' in G.\nhave Y : perm_eq (to :: ps) pts = false.\n- apply/negP=>Hp'; move: (perm_trans Hp' Hp).\n  rewrite -[to::ps]cat1s -[to::tos]cat1s.\n  move/permEl: (perm_catC ps [::to])=>Hs.\n  move/(perm_trans Hs); rewrite -[_++[::_]]cats0 catA perm_cat2l.\n  move/perm_size.\n  move => F.\n  apply sym_eq in F.\n  move: F.\n  by move/size0nil=>Z; subst tos.\nrewrite Y/= in G.\nrewrite (rely_loc' l R2); subst k; rewrite locE; last apply: (cohVl C).\n  + rewrite -(pf_irr (cn_in cn pts others) (cn_this_in _ _))\n               (getStL_Kc _ (cn_in cn pts others) E1); exists (to::ps).\n    split=>//; move: Hp.\n    by rewrite -cat_rcons -cat1s -!catA !(perm_sym pts) -perm_catCA catA cats1.\n  + by rewrite -(cohD (proj2 (rely_coh R1)))/ddom domPt inE/=.\n  by apply: (cohS (proj2 (rely_coh R1))).\nQed.\n\n(* Verifying the top-level call of ffix *)\nNext Obligation.\napply:ghC=>i lg E1 _; apply: (gh_ex (g:=lg)).\nby apply: call_rule=>C1; first by left.\nQed.\n\n\n(*******************************************)\n(*** Receiving responses to the proposal ***)\n(*******************************************)\n\n(* Ending condition *)\nDefinition rc_prep_cond (acc : seq (nid * bool)) := ~~ perm_eq (map fst acc) pts.\n\n(* Invariant relates the argument and the shape of the state *)\nDefinition rc_prep_inv (e : nat) (dl : data * Log) : cont (seq (nid * bool)) :=\n  fun acc i => loc i = st :-> (e, CWaitPrepResponse dl.1 acc) \\+ log :-> dl.2.\n\nProgram Definition receive_prep_loop (e : nat):\n  {(dl : data * Log)}, DHT [cn, W]\n  (fun i => loc i = st :-> (e, CWaitPrepResponse dl.1 [::]) \\+ log :-> dl.2,\n   fun res m =>\n       loc m = st :-> (e, CWaitPrepResponse dl.1 res) \\+ log :-> dl.2 /\\\n       (perm_eq (map fst res) pts))\n  :=\n  Do _ (@while cn W _ _ rc_prep_cond (rc_prep_inv e) _\n        (fun acc => Do _ (\n           r <-- tryrecv_prep_resp;\n           match r with\n           | Some (from, tg, body) =>\n               if [&& from \\in pts, head 0 body == e & from \\notin (map fst acc)]\n               then ret _ _ ((from, tg == prep_yes) :: acc)\n               else ret _ _ acc\n           | None => ret _ _ acc\n           end\n        )) [::]).\n\n(* TODO: Get rid of this bogus obligation! *)\nNext Obligation. by apply: with_spec x. Defined.\nNext Obligation. by move:H; rewrite /rc_prep_inv (rely_loc' _ H0). Qed.\n\nNext Obligation.\nmove=>i[[d lg]]/=[H1 I1]; apply: step.\napply: act_rule=>j R1/=; split; first by case: (rely_coh R1).\ncase=>[[[from tg] body] k m|k m]; last first.\n- case=>Sf []Cj[]H; last by case: H=>[?][?][?][?][?][?][].\n  have E: k = j by case: H.\n  move: H; subst k=>_ R2; apply: ret_rule=>m' R3 {d lg I1}[d lg][H2].\n  by rewrite /rc_prep_inv; rewrite -(rely_loc' _ R1)-(rely_loc' _ R2)-(rely_loc' _ R3).\ncase=>Sf []Cj[]=>[|[l'][mid][tms][from'][rt][pf][][E]Hin E1 Hw/=]; first by case.\ncase/andP=>/eqP Z G->{k}[]Z1 Z2 Z3 R2; subst l' from' tg body.\nmove: rt pf (coh_s (w:=W) l (s:=j) Cj) Hin R2 E1 Hw G E; rewrite prEq/=.\nmove=>rt pf Cj' Hin R E1 Hw G E.\nhave D: rt = cn_receive_prep_yes_trans _ _ _ \\/ rt = cn_receive_prep_no_trans _ _ _.\n- case: Hin G=>/=; first by intuition.\n  case; first by intuition.\n  by do! [case; first by move=>->].\n(* Some forward facts: *)\nhave P1: valid (dstate (getS j))\n  by apply: (@cohVl _ TPCCoh); case: (Cj')=>P1 P2 P3 P4; split=>//=; done.\nhave P2: valid j by apply: (cohS (proj2 (rely_coh R1))).\nhave P3: l \\in dom j by rewrite -(cohD (proj2 (rely_coh R1)))/ddom domPt inE/=.\n(* Two cases: received yes or no from a participant *)\ncase: D=>{Hin G Hw}Z; subst rt; rewrite/= in E1 R; case:ifP=>G1;\napply: ret_rule=>m' R'=>{d lg I1}[[d lg][I1]]; rewrite /rc_prep_inv ?E1 ?eqxx/=;\nrewrite -(rely_loc' _ R1)(rely_loc' _ R')(rely_loc' _ R)=>Ej; rewrite locE//;\nrewrite /rc_step eqxx/cstep_recv/= (getStC_K Cj' Ej) (getStL_Kc _ _ Ej) ?eqxx/=;\ndo? [by move: G1; case: (from \\in pts)=>//=;\n        case: (head 0 tms == e)=>//=/negbFE->/=];\ndo ? by case/andP:G1=>->/andP[]/eqP->G1; rewrite negbF ?eqxx//=;\n     by move/negbTE: G1=>->.\nQed.\n\nNext Obligation.\napply: ghC=>i[d lg]E1 C1.\nhave Pre: rc_prep_inv e (d, lg) [::] i by rewrite /rc_prep_inv/= E1.\napply: call_rule'=>[|acc m]; first by exists (d, lg).\ncase/(_ (d, lg) Pre)=>/=H1 H2 Cm; split=>//;  by move/negbNE: H1.\nQed.\n\nDefinition read_res (st : CStateT) :=\n  let: (_, s) := st in\n  match s with\n  | CWaitPrepResponse _ res => res\n  | _ => [::]\n  end.\n\n(* Reading the accumulated responses from the state *)\nProgram Definition read_resp_result :\n  {(e : nat) (d : data) (lg : Log) res}, DHT [cn, W]\n  (fun i => loc i = st :-> (e, CWaitPrepResponse d res) \\+ log :-> lg,\n   fun r m => loc m = st :-> (e, CWaitPrepResponse d res) \\+ log :-> lg /\\\n              r = all (fun i => i) (map snd res)) :=\n  Do (act (@skip_action_wrapper W cn l tpc (prEq tpc) _\n          (fun s pf => all (fun i => i) (map snd (read_res (getStC pf)))))).\nNext Obligation.\nmove=>/=i[e][d][lg][res] E/=.\napply: act_rule=>j R; split=>/=[|r k m]; first by case: (rely_coh R).\ncase=>/=H1[Cj]Z; subst j=>->R'.\nsplit; first by rewrite (rely_loc' l R') (rely_loc' _ R).\nby rewrite -(rely_loc' _ R) in H; rewrite (getStC_K _ H)/=.\nQed.\n\n(*************************)\n(* Coordinator's prelude *)\n(*************************)\n\nProgram Definition coordinator_prelude (d : data) :\n  {(lg : Log)}, DHT [cn, W]\n  (fun i => exists (e : nat), loc i = st :-> (e, CInit) \\+ log :-> lg,\n   fun r m => let: (res, b) := r in\n       exists (e : nat),\n       [/\\ loc m = st :-> (e, CWaitPrepResponse d res) \\+ log :-> lg,\n           perm_eq (map fst res) pts &\n           b = all id (map snd res)]) :=\n  Do (e <-- read_round;\n      send_prep_loop e d;;\n      res <-- receive_prep_loop e;\n      b <-- read_resp_result;\n      ret _ _ (res, b)).\nNext Obligation.\nmove=>s0/=[lg][e]E0; apply: step.\napply: (gh_ex (g := (e, CInit, lg))).\napply: call_rule=>//=e' s1 [E1][pf]->C1.\nrewrite !(getStC_K _ E1)=>{e'}.\napply: step; apply: (gh_ex (g:=lg)).\napply: call_rule=>//_ s2[_]/=E2 C2.\napply: step; apply: (gh_ex (g:=(d, lg))).\napply: call_rule=>//res s3/= [E3 H3] C3.\napply: step; apply: (gh_ex (g:=e)); apply: (gh_ex (g:=d));\n  apply: (gh_ex (g:=lg)); apply: (gh_ex (g:=res)).\napply: call_rule=>// b s4 [E4]->{b}C4/=.\napply: ret_rule=>i5 R5 lg'[e'] E0'; exists e.\nrewrite E0 in E0'; case: (hcancelV _ E0'); first by rewrite validPtUn.\ncase=>Z1 _; subst e'; move/(hcancelPtV _).\nby rewrite validPt (rely_loc' _ R5)=>/(_ is_true_true)=><-.\nQed.\n\n(*******************************************)\n(***    Sending commits/aborts           ***)\n(*******************************************)\n\n(* Commit *)\n\nDefinition send_commit_loop_spec (e : nat) d := forall to_send,\n  {lg : Log}, DHT [cn, W]\n  (fun i =>\n     (exists res,\n         [/\\ loc i = st :-> (e, CWaitPrepResponse d res) \\+ log :-> lg,\n          to_send = pts, perm_eq (map fst res) pts &\n          all id (map snd res)]) \\/\n     if to_send == [::]\n     then loc i = st :-> (e, CWaitAckCommit d [::]) \\+ log :-> lg\n     else exists (ps : seq nid),\n         loc i = st :-> (e, CSentCommit d ps) \\+ log :-> lg /\\\n         perm_eq pts (ps ++ to_send),\n   fun (r : unit) m => loc m = st :-> (e, CWaitAckCommit d [::]) \\+ log :-> lg).\n\nProgram Definition send_commit_loop e d : send_commit_loop_spec e d :=\n  fun to_send  =>\n    Do (fix rec to_send :=\n          (match to_send with\n           | to :: tos => send_commit e to ;; rec tos\n           | [::] => ret _ _ tt\n           end)) to_send.\n\nNext Obligation.\napply: ghC=>s1 lg E1 C1; elim: to_send s1 E1 C1=>//=.\n- move=>s1; case; first by case=>?[]_ Z; rewrite -Z in (PtsNonEmpty).\n  by move=>E1 _; apply: ret_rule=>i2 R; rewrite (rely_loc' _ R).\nmove=>to tos Hi s1 H C1.\napply: step; apply: act_rule=>s2 R2/=.\nhave Pre: Actions.send_act_safe W (p:=tpc) cn l\n          (cn_send_commit_trans cn pts others) [:: e] to s2.\n- split; [by case: (rely_coh R2) | | |]; last first.\n  + rewrite /Actions.filter_hooks umfilt0=>???.\n    move => F.\n    apply sym_eq in F.\n    move: F.\n    by move/find_some; rewrite dom0.\n  + rewrite /Actions.can_send /nodes inE eqxx andbC/=.\n    by rewrite -(cohD (proj2 (rely_coh R2)))/ddom domPt inE/=.\n  case: (proj2 (rely_coh R2))=>_ _ _ _/(_ l); rewrite prEq=>C; split.\n  + split=>//; case: H; first by case=>?[_]<-; rewrite inE eqxx.\n    by case=>ps[_]/perm_mem->; rewrite mem_cat orbC inE eqxx.\n  exists C; case:H=>[[res][P1]P2 P3|[ps][P1 P2]];[left|right];\n  rewrite -(rely_loc' _ R2) in P1; rewrite (getStC_K _ P1);\n  first by exists e, d, res=>//.\n  exists e, d, ps; split=>//.\n  move/perm_uniq: P2; rewrite Puniq.\n  move => F.\n  apply sym_eq in F.\n  move: F.\n  rewrite -cat_rcons cat_uniq -cats1 cat_uniq=>/andP[]/andP[_]/andP[].\n  by rewrite /= orbC.\n\n(* Using the postcondition *)\nsplit=>// body i3 i4[Sf]/=St R3.\napply: Hi; last by case: (rely_coh R3).\nright; rewrite (rely_loc' _ R3).\ncase: (Sf)=>C2/=[][]_ Tp [C2']/=; case; move=>[e'][d'].\n- move=>[res][E'][]Z P1 P2/andP[P3] _; subst e'.\n  case: H=>[[res'][E1]Te _ _|[ps]]; last first.\n  + by rewrite -(rely_loc' _ R2)=>[][E1]; rewrite (getStC_K _ E1) in E'.\n  rewrite -(rely_loc' _ R2) in E1; rewrite (getStC_K _ E1) in E'.\n  case: E'=>Z Z'; subst res' d'.\n  case: St=>Z1[h][];case=>->{h}; subst body=>G.\n  rewrite (getStC_K _ E1) (getStL_Kc _ _ E1)\n          /cstep_send -{1}Te inE eqxx/= P1 P2 in G.\n  have X: (pts == [:: to]) = (tos == [::]).\n  + rewrite -Te; apply/Bool.eq_iff_eq_true.\n    by split; [move=>/eqP[]->|move/eqP->;rewrite eqxx].\n    rewrite X in G; subst i3.\n    rewrite locE//; [|by apply: (cohS C2)|by apply: (cohVl C2')].\n  by case: ifP=>X'; rewrite X'//; exists [::to]; split=>//; rewrite -Te.\ncase=>ps[E'][]Z N/andP[P1]_; subst e'.\ncase: H=>[[res'][E1]Te _ _|[ps']].\n- by rewrite -(rely_loc' _ R2) in E1; rewrite (getStC_K _ E1) in E'.\nrewrite -(rely_loc' _ R2)=>[][E1] P2; rewrite (getStC_K _ E1) in E'.\ncase: E'=>Z1 Z2; subst d' ps'; case: St=>Z1[h][];case=>->{h}; subst body=>G.\nrewrite (getStC_K _ E1) (getStL_Kc _ _ E1)\n        /cstep_send Tp in G.\nhave X: perm_eq (to :: ps) pts = (tos == [::]).\n- apply/Bool.eq_iff_eq_true; split.\n  + move=>Hp'; move: (perm_trans Hp' P2).\n    rewrite -[to::ps]cat1s -[to::tos]cat1s.\n    move/permEl: (perm_catC ps [::to])=>Hs.\n    move/(perm_trans Hs); rewrite -[_++[::_]]cats0 catA perm_cat2l.\n    move/perm_size.\n    move => F.\n    apply sym_eq in F.\n    move: F.\n    by move/size0nil=>Z; subst tos.\n  move/eqP=>Z; subst tos; rewrite perm_sym; apply: (perm_trans P2).\n  by apply/permEl; move: (perm_catC ps [:: to]).\nrewrite X in G=>{X}; subst i3.\nrewrite locE//; [|by apply: (cohS C2)|by apply: (cohVl C2')].\ncase:ifP=>->//; exists (to :: ps);split=>//.\napply: (perm_trans P2).\nby rewrite -[to::ps]cat1s -[to::tos]cat1s -!catA perm_catCA.\nQed.\n\nProgram Definition send_commits e d :\n  {lg : Log}, DHT [cn, W]\n  (fun i => exists res,\n         [/\\ loc i = st :-> (e, CWaitPrepResponse d res) \\+ log :-> lg,\n          perm_eq (map fst res) pts &\n          all id (map snd res)],\n   fun (r : unit) m => loc m = st :-> (e, CWaitAckCommit d [::]) \\+ log :-> lg)\n  := Do (send_commit_loop e d pts).\nNext Obligation.\napply: ghC=>i lg[res][H1]H2 H3 C; apply: (gh_ex (g:=lg)).\napply: call_rule=>//; first by move=>_; left; exists res.\nQed.\n\n(* Abort *)\n\nDefinition send_abort_loop_spec (e : nat) d := forall to_send,\n  {lg : Log}, DHT [cn, W]\n  (fun i =>\n     (exists res,\n         [/\\ loc i = st :-> (e, CWaitPrepResponse d res) \\+ log :-> lg,\n          to_send = pts, perm_eq (map fst res) pts &\n          has (fun r => negb r) (map snd res)]) \\/\n     if to_send == [::]\n     then loc i = st :-> (e, CWaitAckAbort d [::]) \\+ log :-> lg\n     else exists (ps : seq nid),\n         loc i = st :-> (e, CSentAbort d ps) \\+ log :-> lg /\\\n         perm_eq pts (ps ++ to_send),\n   fun (r : unit) m => loc m = st :-> (e, CWaitAckAbort d [::]) \\+ log :-> lg).\n\nProgram Definition send_abort_loop e d : send_abort_loop_spec e d :=\n  fun to_send  =>\n    Do (fix rec to_send :=\n          (match to_send with\n           | to :: tos => send_abort e to ;; rec tos\n           | [::] => ret _ _ tt\n           end)) to_send.\n\nNext Obligation.\napply: ghC=>s1 lg E1 C1; elim: to_send s1 E1 C1=>//=.\n- move=>s1; case; first by case=>?[]_ Z; rewrite -Z in (PtsNonEmpty).\n  by move=>E1 _; apply: ret_rule=>i2 R; rewrite (rely_loc' _ R).\nmove=>to tos Hi s1 H C1.\napply: step; apply: act_rule=>s2 R2/=.\nhave Pre: Actions.send_act_safe W (p:=tpc) cn l\n          (cn_send_abort_trans cn pts others) [:: e] to s2.\n- split; [by case: (rely_coh R2) | | |]; last first.\n  + rewrite /Actions.filter_hooks umfilt0=>???.\n    move => F.\n    apply sym_eq in F.\n    move: F.\n    by move/find_some; rewrite dom0.\n  + rewrite /Actions.can_send /nodes inE eqxx andbC/=.\n    by rewrite -(cohD (proj2 (rely_coh R2)))/ddom domPt inE/=.\n  case: (proj2 (rely_coh R2))=>_ _ _ _/(_ l); rewrite prEq=>C; split.\n  + split=>//; case: H; first by case=>?[_]<-; rewrite inE eqxx.\n    by case=>ps[_]/perm_mem->; rewrite mem_cat orbC inE eqxx.\n  exists C; case:H=>[[res][P1]P2 P3|[ps][P1 P2]];[left|right];\n  rewrite -(rely_loc' _ R2) in P1; rewrite (getStC_K _ P1);\n  first by exists e, d, res=>//.\n  exists e, d, ps; split=>//.\n  move/perm_uniq: P2; rewrite Puniq.\n  move => F.\n  apply sym_eq in F.\n  move: F.\n  rewrite -cat_rcons cat_uniq -cats1 cat_uniq=>/andP[]/andP[_]/andP[].\n  by rewrite /= orbC.\n\n(* Using the postcondition *)\nsplit=>// body i3 i4[Sf]/=St R3.\napply: Hi; last by case: (rely_coh R3).\nright; rewrite (rely_loc' _ R3).\ncase: (Sf)=>C2/=[][]_ Tp [C2']/=; case; move=>[e'][d'].\n- move=>[res][E'][]Z P1 P2/andP[P3] _; subst e'.\n  case: H=>[[res'][E1]Te _ _|[ps]]; last first.\n  + by rewrite -(rely_loc' _ R2)=>[][E1]; rewrite (getStC_K _ E1) in E'.\n  rewrite -(rely_loc' _ R2) in E1; rewrite (getStC_K _ E1) in E'.\n  case: E'=>Z Z'; subst res' d'.\n  case: St=>Z1[h][];case=>->{h}; subst body=>G.\n  have P2' : all id [seq i.2 | i <- res] = false\n    by rewrite has_predC in P2; apply/negbTE.\n  rewrite (getStC_K _ E1) (getStL_Kc _ _ E1)\n          /cstep_send -{1}Te inE eqxx/= P1 P2' in G.\n  have X: (pts == [:: to]) = (tos == [::]).\n  + rewrite -Te; apply/Bool.eq_iff_eq_true.\n    by split; [move=>/eqP[]->|move/eqP->;rewrite eqxx].\n    rewrite X in G; subst i3.\n    rewrite locE//; [|by apply: (cohS C2)|by apply: (cohVl C2')].\n  by case: ifP=>X'; rewrite X'//; exists [::to]; split=>//; rewrite -Te.\ncase=>ps[E'][]Z N/andP[P1]_; subst e'.\ncase: H=>[[res'][E1]Te _ _|[ps']].\n- by rewrite -(rely_loc' _ R2) in E1; rewrite (getStC_K _ E1) in E'.\nrewrite -(rely_loc' _ R2)=>[][E1] P2; rewrite (getStC_K _ E1) in E'.\ncase: E'=>Z1 Z2; subst d' ps'; case: St=>Z1[h][];case=>->{h}; subst body=>G.\nrewrite (getStC_K _ E1) (getStL_Kc _ _ E1)\n        /cstep_send Tp in G.\nhave X: perm_eq (to :: ps) pts = (tos == [::]).\n- apply/Bool.eq_iff_eq_true; split.\n  + move=>Hp'; move: (perm_trans Hp' P2).\n    rewrite -[to::ps]cat1s -[to::tos]cat1s.\n    move/permEl: (perm_catC ps [::to])=>Hs.\n    move/(perm_trans Hs); rewrite -[_++[::_]]cats0 catA perm_cat2l.\n    move/perm_size.\n    move => F.\n    apply sym_eq in F.\n    move: F.\n    by move/size0nil=>Z; subst tos.\n  move/eqP=>Z; subst tos; rewrite perm_sym; apply: (perm_trans P2).\n  by apply/permEl; move: (perm_catC ps [:: to]).\nrewrite X in G=>{X}; subst i3.\nrewrite locE//; [|by apply: (cohS C2)|by apply: (cohVl C2')].\ncase:ifP=>->//; exists (to :: ps);split=>//.\napply: (perm_trans P2).\nby rewrite -[to::ps]cat1s -[to::tos]cat1s -!catA perm_catCA.\nQed.\n\nProgram Definition send_aborts e d :\n  {lg : Log}, DHT [cn, W]\n  (fun i => exists res,\n         [/\\ loc i = st :-> (e, CWaitPrepResponse d res) \\+ log :-> lg,\n          perm_eq (map fst res) pts &\n          has (fun r => negb r) (map snd res)],\n   fun (r : unit) m => loc m = st :-> (e, CWaitAckAbort d [::]) \\+ log :-> lg)\n  := Do (send_abort_loop e d pts).\nNext Obligation.\napply: ghC=>i lg[res][H1]H2 H3 C; apply: (gh_ex (g:=lg)).\napply: call_rule=>//; first by move=>_; left; exists res.\nQed.\n\n\n(*******************************************)\n(*** Receiving acks on commit/abort    ***)\n(*******************************************)\n\n(* Acks on Commit *)\n\n(* Ending condition *)\nDefinition rc_commit_cond (acc : seq nid) := ~~ perm_eq acc pts.\n\n(* Invariant relates the argument and the shape of the state *)\nDefinition rc_commit_inv (e : nat) (dl : data * Log) : cont (seq nid) :=\n  fun acc i =>\n    if perm_eq acc pts\n    then loc i = st :-> (e.+1, CInit) \\+ log :-> rcons dl.2 (true, dl.1)\n    else loc i = st :-> (e, CWaitAckCommit dl.1 acc) \\+ log :-> dl.2.\n\nProgram Definition receive_commit_loop (e : nat):\n  {(dl : data * Log)}, DHT [cn, W]\n  (fun i => loc i = st :-> (e, CWaitAckCommit dl.1 [::]) \\+ log :-> dl.2,\n   fun (res : seq nat) m =>\n       loc m = st :-> (e.+1, CInit) \\+ log :-> rcons dl.2 (true, dl.1))\n  :=\n  Do _ (@while cn W _ _ rc_commit_cond (rc_commit_inv e) _\n        (fun acc => Do _ (\n           r <-- tryrecv_commit_ack;\n           match r with\n           | Some (from, tg, body) =>\n               if [&& from \\in pts, head 0 body == e & from \\notin acc]\n               then ret _ _ (from :: acc)\n               else ret _ _ acc\n           | None => ret _ _ acc\n           end\n        )) [::]).\n\nNext Obligation. by apply: with_spec x. Defined.\nNext Obligation. by move:H; rewrite /rc_commit_inv (rely_loc' _ H0). Qed.\n\nNext Obligation.\nmove=>i[[d lg]]/=[H1 I1]; apply: step.\napply: act_rule=>j R1/=; split; first by case: (rely_coh R1).\ncase=>[[[from tg] body] k m|k m]; last first.\n- case=>Sf []Cj[]H; last by case: H=>[?][?][?][?][?][?][].\n  have E: k = j by case: H.\n  move: H; subst k=>_ R2; apply: ret_rule=>m' R3 {d lg I1}[d lg][H2].\n  by rewrite /rc_commit_inv;\n     rewrite -(rely_loc' _ R1)-(rely_loc' _ R2)-(rely_loc' _ R3).\ncase=>Sf []Cj[]=>[|[l'][mid][tms][from'][rt][pf][][E]Hin E1 Hw/=]; first by case.\ncase/andP=>/eqP Z G->{k}[]Z1 Z2 Z3 R2; subst l' from' tg body.\nmove: rt pf (coh_s (w:=W) l (s:=j) Cj) Hin R2 E1 Hw G E; rewrite prEq/=.\nmove=>rt pf Cj' Hin R E1 Hw G E.\nhave D: rt = cn_receive_commit_ack_trans _ _ _.\n- by move: Hin G; do! [case ;first by move=>->].\n(* Some forward facts: *)\nhave P1: valid (dstate (getS j))\n  by apply: (@cohVl _ TPCCoh); case: (Cj')=>P1 P2 P3 P4; split=>//=; done.\nhave P2: valid j by apply: (cohS (proj2 (rely_coh R1))).\nhave P3: l \\in dom j by rewrite -(cohD (proj2 (rely_coh R1)))/ddom domPt inE/=.\n(* The final blow *)\nby subst rt; rewrite/= in E1 R; case:ifP=>G1;\napply: ret_rule=>m' R'; rewrite /rc_commit_cond=>{d lg I1}[[d lg][I1]];\nrewrite /rc_commit_inv ?E1 ?eqxx/=;\nrewrite -(rely_loc' _ R1)(rely_loc' _ R')(rely_loc' _ R)=>Ej; rewrite locE//;\nrewrite /rc_step eqxx/cstep_recv/=;\nmove/negbTE: I1=>I1; rewrite I1 in Ej *;\nrewrite (getStC_K Cj' Ej) (getStL_Kc _ _ Ej) ?eqxx/=;\nmove: G1; case: (from \\in pts)=>//=;case: (head 0 tms == e)=>//=;\ncase: (from \\in acc)=>//=_; case:ifP=>X; rewrite X//=.\nQed.\n\nNext Obligation.\napply: ghC=>i[d lg]E1 C1.\nhave Pre: rc_commit_inv e (d, lg) [::] i.\n- rewrite /rc_commit_inv/= E1/=.\n  have X: perm_eq [::] pts = false.\n  - apply/negP.\n    move/perm_size.\n    move => F.\n    apply sym_eq in F.\n    move: F.\n    move/size0nil=>Z.\n    by move: (PtsNonEmpty); rewrite Z.\n  by rewrite X.\napply: call_rule'=>[|acc m]; first by exists (d, lg).\ncase/(_ (d, lg) Pre)=>/=H1 H2 Cm.\nby move/negbNE: H1=>H1; rewrite /rc_commit_inv H1 in H2.\nQed.\n\n(* Acks on Abort *)\n\n(* Ending condition *)\nDefinition rc_abort_cond (acc : seq nid) := ~~ perm_eq acc pts.\n\n(* Invariant relates the argument and the shape of the state *)\nDefinition rc_abort_inv (e : nat) (dl : data * Log) : cont (seq nid) :=\n  fun acc i =>\n    if perm_eq acc pts\n    then loc i = st :-> (e.+1, CInit) \\+ log :-> rcons dl.2 (false, dl.1)\n    else loc i = st :-> (e, CWaitAckAbort dl.1 acc) \\+ log :-> dl.2.\n\nProgram Definition receive_abort_loop (e : nat):\n  {(dl : data * Log)}, DHT [cn, W]\n  (fun i => loc i = st :-> (e, CWaitAckAbort dl.1 [::]) \\+ log :-> dl.2,\n   fun (res : seq nat) m =>\n       loc m = st :-> (e.+1, CInit) \\+ log :-> rcons dl.2 (false, dl.1))\n  :=\n  Do _ (@while cn W _ _ rc_abort_cond (rc_abort_inv e) _\n        (fun acc => Do _ (\n           r <-- tryrecv_abort_ack;\n           match r with\n           | Some (from, tg, body) =>\n               if [&& from \\in pts, head 0 body == e & from \\notin acc]\n               then ret _ _ (from :: acc)\n               else ret _ _ acc\n           | None => ret _ _ acc\n           end\n        )) [::]).\n\nNext Obligation. by apply: with_spec x. Defined.\nNext Obligation. by move:H; rewrite /rc_abort_inv (rely_loc' _ H0). Qed.\n\nNext Obligation.\nmove=>i[[d lg]]/=[H1 I1]; apply: step.\napply: act_rule=>j R1/=; split; first by case: (rely_coh R1).\ncase=>[[[from tg] body] k m|k m]; last first.\n- case=>Sf []Cj[]H; last by case: H=>[?][?][?][?][?][?][].\n  have E: k = j by case: H.\n  move: H; subst k=>_ R2; apply: ret_rule=>m' R3 {d lg I1}[d lg][H2].\n  by rewrite /rc_abort_inv;\n     rewrite -(rely_loc' _ R1)-(rely_loc' _ R2)-(rely_loc' _ R3).\ncase=>Sf []Cj[]=>[|[l'][mid][tms][from'][rt][pf][][E]Hin E1 Hw/=]; first by case.\ncase/andP=>/eqP Z G->{k}[]Z1 Z2 Z3 R2; subst l' from' tg body.\nmove: rt pf (coh_s (w:=W) l (s:=j) Cj) Hin R2 E1 Hw G E; rewrite prEq/=.\nmove=>rt pf Cj' Hin R E1 Hw G E.\nhave D: rt = cn_receive_abort_ack_trans _ _ _.\n- by move: Hin G; do! [case ;first by move=>->].\n(* Some forward facts: *)\nhave P1: valid (dstate (getS j))\n  by apply: (@cohVl _ TPCCoh); case: (Cj')=>P1 P2 P3 P4; split=>//=; done.\nhave P2: valid j by apply: (cohS (proj2 (rely_coh R1))).\nhave P3: l \\in dom j by rewrite -(cohD (proj2 (rely_coh R1)))/ddom domPt inE/=.\n(* The final blow *)\nby subst rt; rewrite/= in E1 R; case:ifP=>G1;\napply: ret_rule=>m' R'; rewrite /rc_abort_cond=>{d lg I1}[[d lg][I1]];\nrewrite /rc_abort_inv ?E1 ?eqxx/=;\nrewrite -(rely_loc' _ R1)(rely_loc' _ R')(rely_loc' _ R)=>Ej; rewrite locE//;\nrewrite /rc_step eqxx/cstep_recv/=;\nmove/negbTE: I1=>I1; rewrite I1 in Ej *;\nrewrite (getStC_K Cj' Ej) (getStL_Kc _ _ Ej) ?eqxx/=;\nmove: G1; case: (from \\in pts)=>//=;case: (head 0 tms == e)=>//=;\ncase: (from \\in acc)=>//=_; case:ifP=>X; rewrite X//=.\nQed.\n\nNext Obligation.\napply: ghC=>i[d lg]E1 C1.\nhave Pre: rc_abort_inv e (d, lg) [::] i.\n- rewrite /rc_abort_inv/= E1/=.\n  have X: perm_eq [::] pts = false.\n  - apply/negP.\n    move/perm_size.\n    move => F.\n    apply sym_eq in F.\n    move: F.\n    move/size0nil=>Z.\n    by move: (PtsNonEmpty); rewrite Z.\n  by rewrite X.\napply: call_rule'=>[|acc m]; first by exists (d, lg).\ncase/(_ (d, lg) Pre)=>/=H1 H2 Cm.\nby move/negbNE: H1=>H1; rewrite /rc_abort_inv H1 in H2.\nQed.\n\n(*****************************************************)\n(*      Full coordinator Implementation              *)\n(*****************************************************)\n\nProgram Definition coordinator_round (d : data) :\n  {(e : nat)(lg : Log)}, DHT [cn, W]\n  (fun i => loc i = st :-> (e, CInit) \\+ log :-> lg,\n   fun res m => loc m = st :-> (e.+1, CInit) \\+ log :-> rcons lg (res, d))\n  :=\n  Do (e <-- read_round;\n      send_prep_loop e d;;\n      res <-- receive_prep_loop e;\n      b <-- read_resp_result;\n      (if b\n       then send_commits e d;;\n            receive_commit_loop e\n       else send_aborts e d;;\n            receive_abort_loop e);;\n      ret _ _ b).\nNext Obligation.\nmove=>s0/=[e][lg]E0; apply: step.\napply: (gh_ex (g := (e, CInit, lg))).\napply: call_rule=>//e' s1 [E1][pf]->C1.\nrewrite !(getStC_K _ E1)=>{e'}.\napply: step; apply: (gh_ex (g:=lg)).\napply: call_rule=>//_ s2[_]/=E2 C2.\napply: step; apply: (gh_ex (g:=(d, lg))).\napply: call_rule=>//res s3/= [E3 H3] C3.\napply: step; apply: (gh_ex (g:=e)); apply: (gh_ex (g:=d));\n  apply: (gh_ex (g:=lg)); apply: (gh_ex (g:=res)).\napply: call_rule=>// b s4 [E4]->{b}C4/=.\ncase:ifP=>A.\n- do![apply: step]; apply: (gh_ex (g:=lg)).\n  apply: call_rule=>_; first by exists res.\n  move=>s5 E5 C5; apply: (gh_ex (g:=(d, lg))).\n  apply: call_rule=>//_ s6 E6 C6.\n  apply: ret_rule=>i6 R6 e' lg' E0'.\n  rewrite E0 in E0'; case: (hcancelV _ E0'); first by rewrite validPtUn.\n  + case=>Z1 _; subst e'; move/(hcancelPtV _).\n  by rewrite validPt (rely_loc' _ R6)=>/(_ is_true_true)=><-.\ndo![apply: step]; apply: (gh_ex (g:=lg)).\napply: call_rule=>_; first by exists res; rewrite has_predC A.\nmove=>s5 E5 C5; apply: (gh_ex (g:=(d, lg))).\napply: call_rule=>//_ s6 E6 C6.\napply: ret_rule=>i6 R6 e' lg' E0'.\nrewrite E0 in E0'; case: (hcancelV _ E0'); first by rewrite validPtUn.\n- case=>Z1 _; subst e'; move/(hcancelPtV _).\nby rewrite validPt (rely_loc' _ R6)=>/(_ is_true_true)=><-.\nQed.\n\n(**************************************************)\n(*\nOverall Implementation effort:\n\n2 full person-days\n\nTODO: Do something about severe proof duplication!\n\n*)\n(**************************************************)\n\n\n(*****************************************************)\n(*    Announcing a list of data transactions         *)\n(*****************************************************)\n\nDefinition coord_loop_spec := forall dts,\n  {(el : nat * Log)}, DHT [cn, W]\n  (fun i =>  loc i = st :-> (el.1, CInit) \\+ log :-> el.2,\n   fun (_ : unit) m => exists (chs : seq bool),\n     loc m = st :-> (el.1 + (size dts), CInit) \\+ log :-> (el.2 ++ (seq.zip chs dts))).\n\n\nProgram Definition coord_loop : coord_loop_spec :=\n  fun dts  =>\n    Do (fix rec dts :=\n          (match dts with\n           | d :: dts => coordinator_round d ;; rec dts\n           | [::] => ret _ _ tt\n           end)) dts.\nNext Obligation.\napply:ghC=>i; elim: dts i=>//=[|d ds/= Hi]i1 [e lg] E1 C1.\n- by apply: ret_rule=>i2 R1; exists [::]; rewrite cats0 addn0 (rely_loc' _ R1).\napply: step; apply: (gh_ex (g:=e)); apply: (gh_ex (g:=lg)).\napply: call_rule=>//b i2/=E2 C2/=.\nmove:(Hi i2 (e.+1, rcons lg (b, d)) E2 C2)=>/=; apply: vrf_mono=>_ i3 [chs]->.\nrewrite -[e.+1]addn1 -[(size ds).+1]addn1 addnAC addnA; exists (b :: chs)=>/=.\nby rewrite -cats1 -!catA/=.\nQed.\n\nProgram Definition coordinator_loop_zero (ds : seq data) :\n  DHT [cn, W]\n  (fun i =>  loc i = st :-> (0, CInit) \\+ log :-> ([::] : seq (bool * data)),\n   fun (_ : unit) m => exists (chs : seq bool),\n       loc m = st :-> (size ds, CInit) \\+ log :-> (seq.zip chs ds))\n  := Do (coord_loop ds).\nNext Obligation.\nby move=>i/=E; apply: (gh_ex (g:=(0, [::]))); apply: call_rule.\nQed.\n\n(*****************************************************)\n(*          Checking the invariant rule              *)\n(*****************************************************)\n\n(* Section CheckingDummyInv. *)\n\n(* Require Import TwoPhaseInductiveInv. *)\n(* Definition tpc' := tpc_with_inv l cn pts others Hnin PtsNonEmpty. *)\n\n(* Definition W' := mkWorld tpc'. *)\n(* Notation ii := (tpc_ii l cn pts others Hnin PtsNonEmpty). *)\n\n(* (* Check with_inv ii. *) *)\n\n(* Program Definition coordinator_inv (d : data) : *)\n(*   {(e : nat)(lg : Log)}, DHT [cn, W']  *)\n(*   (fun i => loc i = st :-> (e, CInit) \\+ log :-> lg, *)\n(*    fun r m => 1 == 1 /\\ *)\n(*        loc m = st :-> (e.+1, CInit) \\+ log :-> rcons lg (r, d)) *)\n(*   := Do (with_inv ii (coordinator_round d)). *)\n(* Next Obligation. *)\n(* move=>i1/=[e][lg]E1; apply with_inv_rule'. *)\n(* apply: (gh_ex (g:=e)); apply: (gh_ex (g:=lg)). *)\n(* apply: call_rule=>//r m H/=C' I e' lg' E'. *)\n(* have X: e' = e /\\ lg' = lg. *)\n(* rewrite E1 in E'; case: (hcancelV _ E'); first by rewrite hvalidPtUn. *)\n(* - case=>Z1 _; subst e'; move/(hcancelPtV _)=>/=. *)\n(*   by rewrite hvalidPt/=/(_ is_true_true)=><-. *)\n(* case: X=>Z1 Z2; subst e' lg'; split; last by []. *)\n(* move: I; rewrite/TwoPhaseInductiveInv.Inv. *)\n(* done. *)\n(* Qed. *)\n\n(* End CheckingDummyInv. *)\n\nEnd CoordinatorImplementation.\nEnd TwoPhaseCoordinator.\n\nModule Exports.\nSection Exports.\n\nDefinition coordinator_loop_zero := coordinator_loop_zero.\nDefinition coordinator_loop := coord_loop.\nDefinition coordinator_round := coordinator_round.\n\nEnd Exports.\nEnd Exports.\n\nEnd TwoPhaseCoordinator.\n\nExport TwoPhaseCoordinator.Exports.\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/TwoPhaseCommit/TwoPhaseCoordinator.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7154240079185318, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.29682859514069726}}
{"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(*           Bihong Zhang <sa614257@mail.ustc.edu.cn>                         *)\n(*                                     School of Software Engineering, USTC   *)\n(*                                                                            *)\n(* ************************************************************************** *)\n\n(* \n\n*)\n\n(* ************* ************************************* *****)\n(* ftl interface *)\n\nRequire Import ListEx.\nRequire Import Monad.\nRequire Import Data.\nRequire Import Params.\nRequire Import Nand.\nRequire Import NPeano.\nRequire Import bnat.\n\nDefinition bvalid_logical_page_no (lpn: page_no) := blt_nat lpn (MAX_LOGICAL_BLOCKS * PAGES_PER_BLOCK).\n\n\nDefinition valid_page_no (ppn: page_no):Prop := bvalid_page_no ppn = true.\n\n\n(*\nCache mapping table\n\nThe cmt_record is (lpn,ppn,flag,time).The init cmt is all the cmt_empty.\n*)\n\nInductive flag :Set := \n | dirty:flag \n | clean:flag.\n\nInductive cmt_record: Set := \n| cmt_empty\n| cmt_trans(lpn:page_no)(pbn:block_no)(offset:nat)(is_dirty:flag).\n\n\nDefinition cache_mapping_table := list cmt_record.\n\nFixpoint  find_empty_cmt(cmt:cache_mapping_table) (i:nat): option nat := \n  match cmt with\n  | nil => None\n  | cons a cmt' => match a with\n                     | cmt_empty => Some i\n                     | _ => find_empty_cmt cmt' (S i)\n                   end\nend.\n\nDefinition cmt_get(cmt : cache_mapping_table) (loc: nat) : option cmt_record :=\n  list_get cmt loc.\n\nDefinition cmt_set(cmt: cache_mapping_table) (loc: nat) (newrecord:cmt_record): option cache_mapping_table :=\n  list_set cmt loc newrecord.\n\nDefinition cmt_get_trans(record:cmt_record) : option (prod (prod block_no page_no) flag)  :=\n  match record with\n      | cmt_empty => None\n      | cmt_trans lpn pbn off f => ret((pbn,off),f)\nend.\n \nFixpoint cmt_in (cmt:cache_mapping_table) (lpn:page_no) :bool :=\n  match cmt with\n      | nil => false\n      | cons a cmt' => match a with\n                           | (cmt_trans lpn' _ _ _) => if beq_nat lpn lpn' then true else cmt_in cmt' lpn\n                           | _ => cmt_in cmt' lpn\n                       end\n  end.\n\nFixpoint find_cmtrecord(cmt:cache_mapping_table)(lpn:page_no)(i:nat) : option nat :=\n  match cmt with\n    | nil => None\n    | cons a cmt' => match a with \n                         |(cmt_trans lpn' _ _ _) =>if beq_nat lpn' lpn then Some i else find_cmtrecord cmt' lpn (S i)  \n                         | _ => find_cmtrecord cmt' lpn (S i)\n                     end\nend.\n\nFixpoint remove_cmt(cmt:cache_mapping_table) (lpn:page_no):  cache_mapping_table :=\n  match cmt with\n    | nil => nil\n    | cons a cmt' => match a with \n                         |(cmt_trans lpn' _  _ _) =>if beq_nat lpn' lpn then cmt' else cons a (remove_cmt cmt' lpn)\n                         | _ => cons a (remove_cmt cmt' lpn)\n                     end\nend.\n\nFixpoint insert_cmt (cmt:cache_mapping_table) (record:cmt_record) (num:nat) :cache_mapping_table :=\n  match num with\n      | O => cons record cmt\n      | S i => match cmt with\n                 | nil => nil\n                 | cons a cmt' => (cons a (insert_cmt cmt' record i ) )\n                end\n   end.\n\nDefinition remove_head(cmt:cache_mapping_table) : option cache_mapping_table :=\n  match cmt with\n      | nil => None\n      | cons a cmt' => Some cmt'\nend.\n\nFixpoint append_tail(cmt:cache_mapping_table)(newrecord:cmt_record) : cache_mapping_table :=\n  match cmt with \n      | nil => cons newrecord nil\n      | cons a nil => cons a (cons newrecord nil)\n      | cons a cmt' => cons a (append_tail cmt' newrecord)\nend.\n\n(*Init the cache mapping table *)\nFixpoint init_cmt(cmt:cache_mapping_table)(i:nat): option cache_mapping_table :=\n  match i with\n|  O => None\n|  S O => Some cmt\n|  S i' => init_cmt (list_append cmt cmt_empty) i'\nend.\n\nDefinition blank_cmt : cache_mapping_table :=\n  list_repeat_list CMT_LENGTH cmt_empty.\n\n(*\nGlobal translation table\n\nThe length of the gtd is fixed.The record is(index,ppn).\n*)\n\n(* Inductive gtd_record: Set := *)\n(* | gtd_empty *)\n(* | gtd_trans (pbn:block_no) (offset:nat ). *)\n\nInductive gtd_record: Set :=\n| gtd_empty\n| gtd_trans:block_no ->nat->gtd_record.\n\n(* Inductive gtd_record': Set := *)\n(* | gtd_empty *)\n(* | gtd_trans:forall (pbn:block_no) (offset:nat), gtd_record'. *)\n\n\nDefinition global_mapping_directory := list gtd_record.\n\n(* Definition gtd_len(gtd:global_mapping_directory) : nat :=  *)\n(*   length gtd. *)\n\nDefinition gtd_get(gtd:global_mapping_directory)(loc: nat) : option gtd_record :=\n  list_get gtd loc.\n\nDefinition gtd_set(gtd:global_mapping_directory) (loc: nat) (newrecord:gtd_record): option global_mapping_directory :=\n  list_set gtd loc newrecord.\n\n(* SearchAbout andb. *)\nFixpoint gtd_look_by_record(gtd:global_mapping_directory)(lbn:block_no) (off:nat) (num:nat) : option nat :=\n  match gtd with\n      | nil  => None\n      | cons record' gtd' => match record' with\n                                 | gtd_empty => gtd_look_by_record gtd' lbn off (S num)\n                                 | gtd_trans lbn' off' => if andb (beq_nat lbn lbn') (beq_nat off off')  then Some num else gtd_look_by_record gtd' lbn off (S num) \n\n                             end\nend.\n\nFixpoint gtd_look_by_lpn_aux (gtd:global_mapping_directory) (lpn:page_no) (num:nat):option nat :=\n  test bvalid_logical_page_no lpn;\n  match gtd with\n      | nil => None\n      | cons record' l => if blt_nat lpn (((S num) * RECORD_PER_TRANS)) then Some num else gtd_look_by_lpn_aux l lpn (S num)\nend.\n\nFixpoint gtd_look_by_lpn (gtd:global_mapping_directory) (lpn:page_no):option nat :=\n  gtd_look_by_lpn_aux gtd lpn 0.\n\n(* Definition gtd_look_by_lpn (gtd:global_mapping_directory) (lpn:page_no) :option nat :=  *)\n(*   test bvalid_logical_page_no lpn; *)\n(*   Some (lpn / RECORD_PER_TRANS). *)\n\n   \nDefinition  gtd_get_trans_by_lpn(gtd:global_mapping_directory)(lpn:page_no):option (prod nat nat) :=\n  do gtd_loc <-- gtd_look_by_lpn gtd lpn;\n  do record <-- gtd_get gtd gtd_loc;\n  match record with\n      | gtd_empty => None\n      | gtd_trans pbn off => ret (pbn,off)\nend.\n\nFixpoint init_gtd(gtd:global_mapping_directory)(i:nat): option global_mapping_directory :=\n  match i with\n|  O => None\n|  S O => Some gtd\n|  S i' => init_gtd (list_append gtd gtd_empty) i'\nend.\n\nDefinition blank_gtd : global_mapping_directory :=\n  list_repeat_list GTD_LENGTH gtd_empty.\n\n(* Compute ( *)\n(*  do gtd <-- Some blank_gtd; *)\n(*  do i <-- gtd_look_by_lpn gtd 7 0; *)\n(*  ret i *)\n(* ). *)\n(*\nTrans_page data\n\nThe data of trans_page is (lpn,ppn)\n*)\n\n(* Inductive trans_record: Set := *)\n(*   | trans_empty *)\n(*   | trans_data(lpn:page_no)(ppn:page_no). *)\n\n(* Definition trans_page := list trans_record. *)\n\n(* Definition trans_len(trans:trans_page) : nat :=  *)\n(*   length trans. *)\n\n(* Definition trans_get(trans:trans_page)(loc: nat) : option trans_record := *)\n(*   list_get trans loc. *)\n\n(* Definition trans_set(trans:trans_page) (loc: nat) (newrecord:trans_record): option trans_page := *)\n(*   list_set trans loc newrecord. *)\n\n\n(*\nFTL block state\n*)\n\nInductive ftl_block_state : Set :=\n  | bs_invalid\n  | bs_erased\n  | bs_data\n  | bs_trans.\n\nInductive ftl_page_state : Set :=\n  | ps_invalid\n  | ps_erased\n  | ps_data  (lpn:page_no)\n  | ps_trans (gtd_loc:nat).\n\nDefinition page_state_table := list ftl_page_state.\n\nDefinition pst_get(pst:page_state_table)(loc: nat) : option ftl_page_state :=\n  list_get pst loc.\n\nDefinition pst_set(pst:page_state_table) (loc: nat) (newstate:ftl_page_state): option page_state_table :=\n  list_set pst loc newstate.\n\nDefinition pst_set_all (state:ftl_page_state):page_state_table  :=\n  list_repeat_list  PAGES_PER_BLOCK state.\n\n(*\nBlock_info_table\n*)\n\nRecord block_info : Set := \n  mk_bi {\n      bi_state: ftl_block_state;\n      bi_used_pages: nat;\n      bi_erase_count: nat;\n      bi_page_state: page_state_table\n    }.\n\nDefinition block_info_table :=  list block_info.\n\nDefinition bi_set_state (bi : block_info) (bi_state : ftl_block_state) : block_info :=\n  mk_bi bi_state (bi_used_pages bi) (bi_erase_count bi) (bi_page_state bi).\n\n(* set both the block and page state *)\nDefinition pi_set_state (bi : block_info) (bi_state : ftl_block_state) (bi_page_state:page_state_table) : block_info :=\n  mk_bi bi_state (bi_used_pages bi) (bi_erase_count bi) bi_page_state.\n\nDefinition bit_get (bit: block_info_table) (b: block_no) \n     : option block_info := \n  list_get bit b.\n\nDefinition bit_update (bit: block_info_table) (b: block_no) (bi: block_info)\n      : option block_info_table := \n  list_set bit b bi.\n\n(* In FTL, a block is initialized to be 'bs_invalid' *)\nDefinition blank_bi : block_info := \n  mk_bi bs_erased 0 0 (pst_set_all ps_erased).\n\n(*\nFree block queue\n\nFree blocks are those not used, and each of them can be invalid or\nerased (filled with \\og{0xFF}). All the free blocks are put into a \nqueue, where a new allocated block is get from the head.\n*)\n\nDefinition block_queue := list block_no.\n\nDefinition fbq_enq (fbq : block_queue) (b : block_no) : option (block_queue) :=\n  Some (list_append fbq b).\n\nDefinition fbq_deq (fbq : block_queue) : option (prod block_no (block_queue)) := \n  match fbq with\n    | nil => None\n    | cons b fbq' => Some (b, fbq')\n  end.\n\nDefinition fbq_in (fbq: list block_no) (pbn: block_no) : bool := list_inb beq_nat fbq pbn.\n\nDefinition fbq_get (fbq: list block_no) (i: nat) : option block_no := list_get fbq i.\n\nDefinition check_block_is_full (bi: block_info) : bool :=\n  match blt_nat (bi_used_pages bi) PAGES_PER_BLOCK with \n    | true => false\n    | false => true\n  end.\n\n(*\n\nCurrnt data/translation block\n\n*)\n\n(* Definition current_data_block := block_no. *)\n\n(* Definition current_trans_block := block_no. *)\n\n(*\nFTL structure\n*)\n\nRecord FTL : Set := \n  mk_FTL {\n      ftl_bi_table: block_info_table;\n      ftl_free_blocks: block_queue;\n      ftl_cmt_table:cache_mapping_table;\n      ftl_gtd_table:global_mapping_directory;\n      current_data_block:block_no;\n      current_trans_block:block_no\n    }.\n\nDefinition ftl_update_bit (f: FTL) (bit: block_info_table) : option FTL :=\n  ret mk_FTL bit (ftl_free_blocks f) (ftl_cmt_table f) (ftl_gtd_table f) (current_data_block f) (current_trans_block f).\n\nDefinition ftl_update_fbq (f: FTL) (fbq: block_queue) : option FTL :=\n  ret mk_FTL (ftl_bi_table f) fbq  (ftl_cmt_table f) (ftl_gtd_table f) (current_data_block f) (current_trans_block f).\n\nDefinition ftl_update_cmt (f: FTL) (cmt: cache_mapping_table) : option FTL :=\n  ret mk_FTL (ftl_bi_table f)  (ftl_free_blocks f) cmt (ftl_gtd_table f) (current_data_block f) (current_trans_block f).\n\nDefinition ftl_update_cur_trans (f: FTL) (pbn:block_no) : option FTL :=\n  ret mk_FTL (ftl_bi_table f) (ftl_free_blocks f) (ftl_cmt_table f) (ftl_gtd_table f) (current_data_block f) pbn.\n\nDefinition ftl_update_cur_data (f: FTL) (pbn:block_no) : option FTL :=\n  ret mk_FTL (ftl_bi_table f) (ftl_free_blocks f) (ftl_cmt_table f) (ftl_gtd_table f)  pbn (current_trans_block f).\n\nInductive freebq_state : Set :=\n  | fbqs_abundant\n  (* | fbqs_needgc *)\n  | fbqs_scarce.\n\n(* IMPORTANT !!! *)\nDefinition check_freebq_count (freebq: block_queue): freebq_state :=\n  match (ble_nat MIN_FREE_BLOCKS (length freebq)) with\n    | false => fbqs_scarce\n    | true => fbqs_abundant\n  end.\n\n\n(* **************************************************** \n\n   * ReadBlock/WriteBlock Operations\n*)\n\nDefinition read_block (c: chip) (pbn: block_no) (off: page_off) : option data :=\n  (* read the page from \"off\" in pbn_data *)\n  do [d, o] <-- (nand_read_page c pbn off);\n\n  (* return the data in the page *)\n  ret d.\n\nDefinition read_block_oob (c: chip) (pbn: block_no) (off: page_off) : option (prod data page_oob_nat) :=\n  (* read the page from \"off\" in pbn_data *)\n  do [d, o] <-- (nand_read_page c pbn off);\n  ret (d,o).\n\n\nDefinition write_data_block (c: chip) (pbn_bi: block_info) (pbn: block_no) \n           (loc: page_off) (d: data) (oob:page_oob_nat)(page_state:ftl_page_state): option (prod chip block_info) := \n  (* write the data to \"pbn#loc\", return c' *)\n  let pst := bi_page_state pbn_bi in\n  do c' <-- (nand_write_page c pbn loc d oob);\n  do pst' <-- pst_set pst loc page_state;\n  (* return bi := <bi_state, used+1, ec> *)\n  let bi' := mk_bi (bi_state pbn_bi) ((bi_used_pages pbn_bi)+1) (bi_erase_count pbn_bi) pst' in\n\n  ret  (c', bi').\n\n(* Definition read_trans_block (c: chip) (bi: block_info) (pbn_log: block_no) (off: page_off) : option data := *)\n(*   (* find the lastest log page for \"poff\" in 'bk' , return the log-location *) *)\n(*   do loc <-- (find_page_in_log_block bi off); *)\n\n(*   (* read the page from \"loc\" in pbn_log *) *)\n(*   do [d, o] <-- (nand_read_page c pbn_log loc);  *)\n\n(*   (* return the data in the page *) *)\n(*   ret d. *)\n\n(* Definition write_trans_block *)\n\n(*\nFTL read algorithm\n\n*)\n\n\nDefinition zero_page := (zero_data PAGE_DATA_SIZE).\n\n(*\n* Check the current_data_block and current_trans_block\n*)\n\nDefinition check_current_block(bit:block_info_table) (pbn: block_no):option bool :=\n  do bi <-- bit_get bit pbn; \n  match check_block_is_full bi with\n     | false => Some false\n     | true => Some true\n  end.\n\nFixpoint find_trans_in_metatrans(l:meta_trans_record_list) (lpn:page_off) : option (prod nat nat) :=\n  match l with\n      | nil => None\n      | cons record l' =>match record with\n                             | trans_empty => find_trans_in_metatrans l' lpn\n                             | trans_data lpn' pbn' off' => if beq_nat lpn lpn' then Some (pbn',off') else find_trans_in_metatrans l' lpn \n                          end\nend.\n\n(* Definition div (n1:nat)(n2:nat):nat := 1. *)\n\n(* Definition mod (n1:nat)(n2:nat):nat := 1. *)\n \nDefinition check_block_full(bi:block_info): bool :=\n  do num <<-- (bi_used_pages bi); \n  match blt_nat num PAGES_PER_BLOCK with\n      | true =>  false\n      | false => true\n end.\n\n(**********************************************************************)\n\n(*\nInit the ftl and nand\n*)\nDefinition bit_init : block_info_table :=\n  list_repeat_list BLOCKS blank_bi.\n\nDefinition cmt_init :cache_mapping_table := blank_cmt.\n\nDefinition gtd_init_empty : global_mapping_directory := blank_gtd.\n\nDefinition fbq_init : block_queue :=\n  list_make_nat_list BLOCKS.\n\nDefinition bit_init_current:option block_info_table :=\n  do bit <-- Some bit_init;\n  do bit' <-- bit_update bit 0 (mk_bi bs_data 0 0 (pst_set_all ps_erased) );\n  do bit'' <-- bit_update bit' 1 (mk_bi bs_trans 0 0  (pst_set_all ps_erased) );\n  ret bit''.\n\nDefinition fbq_init_current:option block_queue :=\n  do [_,fbq'] <-- fbq_deq fbq_init;\n  do [_,fbq''] <-- fbq_deq fbq';\n  ret fbq''.\n\nDefinition ftl_init : option FTL :=\n   do bit <-- bit_init_current;\n   do fbq <-- fbq_init_current;\n   ret (mk_FTL bit fbq cmt_init gtd_init_empty 0 1).\n\n(* Fixpoint gtd_init_trans(c:chip) (f:FTL) (gtd:global_mapping_table) (num:nat):option FTL := *)\n(*   match num with *)\n(*       | O => ret f *)\n(*       | S i => do cur_trans <-- Some (current_trans_block f); *)\n(*                do bit <-- ftl_bi_table f; *)\n(*                do cur_trans_bi <-- bit_get bit cur_trans; *)\n(*                match  check_block_full cur_trans_bi with *)\n(*                    | false => do off <-- Some (bi_used_pages cur_trans_bi); *)\n(*                               do gtd' <-- gtd_set gtd (minus 32 num) (gtd_trans cur_trans off); *)\n(*                               do bit' <-- bit_update bit'; *)\n(*                               do f' <-- (mk_FTL ( *)\n\n(*\nThe meta_trans_data Definition && Operations\n\n*)\nDefinition data_metatrans_get(dmt : meta_trans_record_list) (loc: nat) : option trans_record :=\n  list_get dmt loc.\n\nDefinition data_metatrans_set(dmt: meta_trans_record_list) (loc: nat) (newrecord:trans_record): option meta_trans_record_list :=\n  list_set dmt loc newrecord.\n\nDefinition blank_dmt :meta_trans_record_list  :=\n  list_repeat_list RECORD_PER_TRANS trans_empty.\n\nFixpoint find_meta_trans_record(l:meta_trans_record_list)(lpn:page_no)(i:nat) :option nat :=\n  match l with\n      | nil =>None\n      | cons record l' =>  match record with\n                           | trans_empty => find_meta_trans_record l' lpn (S i)\n                           | trans_data lpn' _ _ => if beq_nat lpn lpn' then Some i else find_meta_trans_record l' lpn (S i)\n                          end\nend.\n\nFixpoint find_meta_trans_empty(l:meta_trans_record_list)(lpn:page_no)(i:nat) :option nat :=\n  match l with\n      | nil =>None\n      | cons record l' =>  match record with\n                           | trans_empty => Some i\n                           | trans_data lpn' _ _ => find_meta_trans_empty l' lpn (S i)\n                          end\nend.\n\nFixpoint get_meta_trans_record (l:meta_trans_record_list)(lpn:page_no)(i:nat) : option (prod block_no page_no) :=\n  (* do i <-- find_meta_trans_record l lpn 0; *)\n  do record <-- data_metatrans_get l i;\n  match record with\n      | trans_data lpn pbn off => ret (pbn,off)\n      | _ => None\n  end.\n\nFixpoint copy_data_trans(l:meta_trans_record_list) (lpn:page_no) (newrecord:trans_record) : option meta_trans_record_list :=\n  match find_meta_trans_record l lpn 0 with\n      | Some loc => do l' <-- data_metatrans_set l loc newrecord;\n                    ret l'                   \n      | None => do empty_loc <-- find_meta_trans_empty l lpn 0;\n                do l' <-- data_metatrans_set l empty_loc newrecord;\n                ret l' \n   end.\n\n(*\nInvalid the block page\n*)\nDefinition invalid_old_page(bit:block_info_table)(pbn:block_no)(off:nat) :option block_info_table :=\n  do bi <-- bit_get bit pbn;\n  do pst <-- Some (bi_page_state bi);\n  do pst' <--  pst_set pst off ps_invalid;\n  do bi' <-- Some (pi_set_state bi (bi_state bi) pst');\n  do bit' <-- bit_update bit pbn bi';\n  ret bit'.\n\n(* **************************************************** \n* Alloc_Block \n\nAllocation block routine, no GC yet. But I believe that it will be \nnot difficult to add a simple GC. \n\n*)\n\nInductive alloc_block_type:Set :=\n  | alloc_trans_block:alloc_block_type\n  | alloc_data_block:alloc_block_type.\n\nInductive gc_block_type:Set :=\n  | gc_trans_block:gc_block_type\n  | gc_data_block:gc_block_type.\n\nDefinition set_alloc_block_status (flag:alloc_block_type):ftl_block_state :=\n  match flag with\n      | alloc_trans_block => bs_trans\n      | alloc_data_block => bs_data\n  end.\n\n  \nDefinition bit_set_state (bit: block_info_table) (pbn: block_no) (st: ftl_block_state) (pst:page_state_table) \n  : option block_info_table :=\n  do bi <-- bit_get bit pbn;\n  do bi' <-- Some (mk_bi st (bi_used_pages bi) (bi_erase_count bi) pst);\n  do bit' <-- bit_update bit pbn bi';\n  ret bit'.\n\nDefinition bit_get_bstate (f: FTL) (pbn: block_no) : option ftl_block_state := \n  do bi <-- bit_get (ftl_bi_table f) pbn;\n  ret (bi_state bi).\n\n(* **************************************************** \n* Auxiliary Routines for update Meta-Data \n*)\n\nDefinition free_block (bit: block_info_table) (fbq: block_queue) (pbn: block_no)\n  : option (prod block_info_table block_queue) :=\n  do bi <-- bit_get bit pbn;\n  do pst <-- Some (pst_set_all ps_invalid);\n  do bi' <-- Some (mk_bi bs_invalid (bi_used_pages bi) (bi_erase_count bi) pst);\n  do bit' <-- bit_update bit pbn bi';\n  do fbq' <-- fbq_enq fbq pbn;\n  ret (bit', fbq').\n\n(* **********************************************************\n*\n*)\n(* \nThe Garbge Collection \n*)\n \n(*\nThe gc trans block\n*)\n\n(* Definition gc(c:chip) (f:FTL)(flag:alloc_block_type):option (prod chip FTL) :=  *)\nDefinition alloc_gc_block (c: chip) (f: FTL) : option (prod block_no (prod chip FTL)) :=\n  let bit := ftl_bi_table f in\n  let fbq := ftl_free_blocks f in\n  do [b, fbq'] <-- fbq_deq fbq; \n  do bi_free <-- bit_get bit b;\n  match bi_state bi_free with\n     | bs_erased => \n       (* TODO:  we don't need to update bit. No,we need,we set the used_pages and pages_state *)\n       do bit' <-- bit_update bit b (mk_bi bs_erased 0 (bi_erase_count bi_free) (pst_set_all ps_erased));\n       ret (b, (c, (mk_FTL bit'  fbq' (ftl_cmt_table f) (ftl_gtd_table f) (current_data_block f) (current_trans_block f) )))\n          \n     | bs_invalid => \n       do c' <-- nand_erase_block c b;\n       do bit' <-- bit_update bit b (mk_bi bs_erased 0 (1 + bi_erase_count bi_free) (pst_set_all ps_erased));\n       ret (b, (c',(mk_FTL bit' fbq' (ftl_cmt_table f) (ftl_gtd_table f) (current_data_block f) (current_trans_block f) )))\n\n     | _ => None\n  end. \n\nDefinition gc_copy_trans_page (c:chip) (f:FTL) (pbn:block_no) (off:nat)(gtd_loc:nat) : option (prod chip FTL) :=\n  let bit := ftl_bi_table f in\n  let gtd := ftl_gtd_table f in\n  let fbq := ftl_free_blocks f in\n  let cur_trans := current_trans_block f in\n  let cur_data := current_data_block f in\n  let cmt := ftl_cmt_table f in\n  let gtd := ftl_gtd_table f in\n  do cur_trans_info <-- bit_get bit cur_trans;\n  do cur_trans_off <-- Some (bi_used_pages cur_trans_info);\n  do [trans_d,oob] <-- read_block_oob c pbn off;\n  (* Also it can look from the page_status *)\n  (* do gtd_loc <-- gtd_look_by_record gtd pbn off 0; *)\n  do [c',cur_bi'] <-- write_data_block c cur_trans_info cur_trans cur_trans_off trans_d oob (ps_trans gtd_loc) ;\n  do bit' <-- bit_update bit cur_trans cur_bi';\n  do gtd' <-- gtd_set gtd gtd_loc (gtd_trans cur_trans cur_trans_off);\n  do new_f <-- Some (mk_FTL bit'  fbq cmt gtd' cur_data cur_trans);\n  ret(c',new_f).\n\nDefinition invalid_old_block(bit:block_info_table)(pbn:block_no) :option block_info_table :=\n  do bi <-- bit_get bit pbn;\n  do pst <-- Some (pst_set_all ps_invalid);\n  do bi' <-- Some (pi_set_state bi (bs_invalid) pst);\n  do bit' <-- bit_update bit pbn bi';\n  ret bit'.\n\n(*\nAssume:we have already look for the invaild trans_block:pbn\n*)\n\n\n\nFixpoint  gc_trans_page (c:chip) (f:FTL) (pbn:block_no) (i:nat) :option (prod chip FTL) :=\n  let bit := ftl_bi_table f in\n  let fbq := ftl_free_blocks f in\n  let cmt := ftl_cmt_table f in\n  let gtd := ftl_gtd_table f in\n  let cur_data := current_data_block f in\n  let cur_trans := current_trans_block f in\n  do bi <-- bit_get bit pbn;\n  do pst <-- Some ( bi_page_state bi );\n  match i with\n      | O => (* free_block also will do this *)\n             do bit' <-- invalid_old_block bit pbn;\n             ret(c,(mk_FTL bit' fbq cmt gtd cur_data cur_trans) )\n              \n      | S i' => do ps <-- pst_get pst i'; \n                match ps with\n                    | ps_trans gtd_loc =>  do [c',f'] <-- gc_copy_trans_page c f pbn i' gtd_loc;\n                                           gc_trans_page c' f' pbn i'\n                                                 \n                    | _ =>  gc_trans_page c f pbn i'\n                            \n                 end\n   end.\n\n(*\nReturn a (c,f),means have a empty page in the translation page\n*)\nDefinition gc_trans(c:chip) (f:FTL)(pbn:block_no):option (prod chip FTL) :=\n  let fbq := ftl_free_blocks f in\n  (*alloc a trans page*)\n  do [cur_trans,cf] <-- alloc_gc_block c f;\n  do [c',f'] <-- Some cf;\n  do bi <-- bit_get (ftl_bi_table f') cur_trans;\n  do bi' <-- Some (bi_set_state bi bs_trans);\n  do bit' <-- bit_update (ftl_bi_table f') cur_trans bi';                                  \n  (* still have a probelm --> Done *)\n  do f'' <-- ftl_update_cur_trans f' cur_trans;\n  do f''' <-- ftl_update_bit f'' bit';\n  (*GC*)\n  do [c'',f4] <-- gc_trans_page c' f''' pbn PAGES_PER_BLOCK;\n  (* enter_free_blocks *)\n  do bit'' <-- Some (ftl_bi_table f4);\n  do fbq' <-- Some (ftl_free_blocks f4);\n  do [bit''',fbq''] <-- free_block bit'' fbq' pbn;\n  do f5 <-- ftl_update_bit f4 bit''';\n  do f6 <-- ftl_update_fbq f5 fbq''; \n  ret (c'',f6).\n\n(* ------------------------------------------------------------------------------- *)\n(*\nTO DO Invalid the old_data,but copy_trans_page do this\n*)\n\n\nDefinition gc_copy_data_page (c:chip) (f:FTL) (pbn:block_no) (off:nat) (lpn:page_no): option (prod (prod nat  nat) (prod chip FTL) ) :=\n  let bit := ftl_bi_table f in\n  let gtd := ftl_gtd_table f in\n  let fbq := ftl_free_blocks f in\n  let cur_trans := current_trans_block f in\n  let cur_data := current_data_block f in\n  let cmt := ftl_cmt_table f in\n  let gtd := ftl_gtd_table f in\n  do cur_data_info <-- bit_get bit cur_data; \n  do cur_data_off <-- Some (bi_used_pages cur_data_info); \n  do [data_d,oob] <-- read_block_oob c pbn off;\n  do [c',cur_bi'] <-- write_data_block c cur_data_info cur_data cur_data_off data_d oob (ps_data lpn) ;\n  do bit' <-- bit_update bit cur_data cur_bi';\n  do new_f <-- Some (mk_FTL bit' fbq cmt gtd cur_data cur_trans);\n  ret((cur_data,cur_data_off),(c',new_f)).\n\n\nFixpoint check_invalid_page (f:FTL)(num:nat)(i:nat):option bool :=\n  do bit <-- Some (ftl_bi_table f);\n  do bi <-- bit_get bit num;\n  do pst <-- Some (bi_page_state bi);\n  match i with\n      | O => Some false\n      | S i' => do ps_state <-- pst_get pst i';\n                match ps_state with\n                    | ps_invalid => Some true\n                    | ps_erased => Some true\n                    | _ => check_invalid_page f num i'\n                 end\n  end.\n\nDefinition check_valid_gc_block (f:FTL) (t:gc_block_type) (num:nat): option bool :=\n  do bit <-- Some (ftl_bi_table f);\n  do bi <-- bit_get bit num;\n  do bs_status <-- Some (bi_state bi);\n  match t with\n      | gc_trans_block => match bs_status with\n                             | bs_trans => match check_invalid_page f num PAGES_PER_BLOCK with\n                                               | Some true => Some true\n                                               | _ => Some false \n                                           end\n                             | _ => Some false\n                         end\n      | gc_data_block => match bs_status with\n                             | bs_data => match check_invalid_page f num PAGES_PER_BLOCK with\n                                               | Some true => Some true\n                                               | _ => Some false \n                                           end\n                             | _ => Some false\n                         end\n  end.\n\n\n(*\n\nThe GC_BLOCK has 3 limits:\n\n1)it can't be cur_trans : wrong\n\n2)it can't be cur_data : wrong\n\n3)it can't be in the fbq\n \n*)\n\nFixpoint lookfor_gc_block (f:FTL) (count:nat) (num:nat) (t:gc_block_type):option nat :=\n  do fbq <-- Some (ftl_free_blocks f);\n  match count with\n          | O  => None\n          | S count' =>\n            match fbq_in fbq num  with\n              | true => match num with\n                      | 15 => lookfor_gc_block f  count' 0 t\n                      | _ =>  lookfor_gc_block f  count' (S num) t\n                        end\n              | false =>\n                match check_valid_gc_block f t num with\n                  | Some true => ret num\n                  | _ => match num with\n                               | 15 => lookfor_gc_block f  count' 0 t\n                               | _ =>  lookfor_gc_block f  count' (S num) t\n                             end\n                end\n            end\n end.\n\nDefinition gc_data_copy_trans_page(c:chip)(f:FTL)(lpn:page_no)(trans_pbn:block_no)(trans_off:nat)(pbn:block_no)(off:nat): option (prod chip FTL) :=\n  let bit := ftl_bi_table f in\n  let fbq := ftl_free_blocks f in\n  let cmt := ftl_cmt_table f in\n  let gtd := ftl_gtd_table f in\n  let cur_trans := current_trans_block f in\n  let cur_data := current_data_block f in\n  do d <-- read_block c trans_pbn trans_off;\n  match d with\n    | metabyte _ => None\n    | metarecord meta_list => do new_list <-- copy_data_trans meta_list lpn (trans_data lpn pbn off);\n                              do cur_bi <-- bit_get bit cur_trans;\n                              do gtd_loc <-- gtd_look_by_lpn gtd lpn;\n                              do cur_off <-- Some (bi_used_pages cur_bi);\n                              do [c',bi'] <-- write_data_block c cur_bi cur_trans cur_off (metarecord new_list) (Some(gtd_loc, 0)) (ps_trans gtd_loc);\n                              do bit' <-- bit_update bit cur_trans bi';\n                              (*Invalide the old trans page*)\n                              do bit'' <-- invalid_old_page bit' trans_pbn trans_off;\n                              (*Invalidate the old data one*)\n                              match find_meta_trans_record meta_list lpn 0 with\n                                | None =>  (* update the gtd,find the gtd_loc *)\n                                           do gtd' <-- gtd_set gtd gtd_loc (gtd_trans cur_trans cur_off);\n                                           ret (c',(mk_FTL bit'' fbq cmt  gtd' cur_data cur_trans ) )\n\n                                | Some i => do [old_data,old_off] <--  get_meta_trans_record meta_list lpn i;\n                                            do bit''' <-- invalid_old_page bit'' old_data old_off;\n                                            (* update the gtd,find the gtd_loc *)\n                                            do gtd' <-- gtd_set gtd gtd_loc (gtd_trans cur_trans cur_off);\n                                            ret (c',(mk_FTL bit''' fbq cmt  gtd' cur_data cur_trans ) )\n                             end\n                               \nend.\n\nDefinition gc_trans_in_gc_data (c:chip) (f:FTL) :option (prod chip FTL) :=\n   let cur_trans := current_trans_block f in\n   do cur_trans_bi <-- bit_get (ftl_bi_table f) cur_trans ;\n   match check_block_is_full cur_trans_bi with\n                     | false => ret (c,f)\n                     | true =>do pbn <-- lookfor_gc_block f PAGES_PER_BLOCK 0 gc_trans_block ;\n                              do [newc,newf] <-- gc_trans c f pbn;\n                               ret (newc,newf)\n  end.\n                                   \nDefinition gc_data_copy_and_update (c:chip) (f:FTL) (pbn:block_no) (off:nat) (lpn:page_no): option (prod chip FTL) :=\n  let gtd := ftl_gtd_table f in\n  let cur_trans := current_trans_block f in\n  do [pbn_off,cf] <-- gc_copy_data_page c f pbn off lpn;\n  do [c',f'] <-- Some cf;\n  do [new_data,new_off] <-- Some pbn_off;\n  do cmt <-- Some ( ftl_cmt_table f');\n  (* Have a bug <-- Done *)\n  match gtd_get_trans_by_lpn gtd lpn with\n      | Some _ =>(* maybe it is not in the trans page *)\n                 do [old_trans,old_off] <-- gtd_get_trans_by_lpn gtd lpn;\n                  (*update the corrsponding trans_page and gtd *)\n                 (* TODO *)\n                 do [newc,newf] <-- gc_trans_in_gc_data c' f';\n                 do [c'',f''] <-- gc_data_copy_trans_page newc newf lpn old_trans old_off new_data new_off;\n                 (* update the cmt *)\n                 do cmt' <-- Some (ftl_cmt_table f'');\n                 match cmt_in cmt lpn with\n                      | false =>   ret (c'',f'')\n                      | true => do loc <-- find_cmtrecord cmt' lpn 0;\n                                do cmt'' <-- cmt_set cmt' loc (cmt_trans lpn new_data new_off clean);\n                                do f''' <-- (ftl_update_cmt f'' cmt'');\n                                ret (c'',f''')\n                 end\n      | _ =>    match cmt_in cmt lpn with\n                      | false =>   ret (c',f')\n                      | true => do loc <-- find_cmtrecord cmt lpn 0;\n                                do cmt' <-- cmt_set cmt loc (cmt_trans lpn new_data new_off clean);\n                                do f'' <-- (ftl_update_cmt f' cmt');\n                                ret (c',f'')\n                end\n  end.\n\nFixpoint  gc_data_page(c:chip) (f:FTL) (pbn:block_no) (i:nat) :option (prod chip FTL) :=\n  let bit := ftl_bi_table f in\n  let fbq := ftl_free_blocks f in\n  let cmt := ftl_cmt_table f in\n  let gtd := ftl_gtd_table f in\n  let cur_trans := current_trans_block f in\n  let cur_data := current_data_block f in\n  do bi <-- bit_get bit pbn;\n  do pst <-- Some ( bi_page_state bi );\n  match i with\n      | O => do bit' <-- invalid_old_block bit pbn;\n             ret(c,(mk_FTL bit fbq cmt gtd cur_data cur_trans) )\n              \n      | S i' =>  do ps <-- pst_get pst i';\n                 match ps with\n                    | ps_data lpn =>  do [c',f'] <-- gc_data_copy_and_update c f pbn i' lpn;\n                                      gc_data_page c' f' pbn i'\n                                                 \n                    | _ =>  gc_data_page c f pbn i'\n                            \n                 end\n   end.                                                                                                                              \n\nDefinition gc_data(c:chip) (f:FTL) (pbn:block_no) :option (prod chip FTL) :=\n  do [cur_data,cf] <-- alloc_gc_block c f;\n  do [c',f'] <-- Some cf;\n  do bit <-- Some (ftl_bi_table f');\n  do bi <-- bit_get bit cur_data;\n  do bi' <-- Some (bi_set_state bi bs_data);\n  do bit' <-- bit_update bit cur_data bi';                                  \n  (* it still have a probelm --> Done *)\n  do f'' <-- ftl_update_cur_data f' cur_data;\n  do f''' <-- ftl_update_bit f'' bit';\n  (*GC*)\n  do [c'',f4] <-- gc_data_page c' f''' pbn PAGES_PER_BLOCK;\n  (* enter_free_blocks *)\n  do bit'' <-- Some (ftl_bi_table f4);\n  do fbq <-- Some (ftl_free_blocks f4);\n  do [bit''',fbq'] <-- free_block bit'' fbq pbn;\n  do f5 <-- ftl_update_bit f4 bit''';\n  do f6 <-- ftl_update_fbq f5 fbq'; \n  ret (c'',f6).\n                                                                                     \n(*\n\nThe GC Opertions\n\nThe pbn has 3 limits:\n\n1)it can't be cur_trans\n\n2)it can't be cur_data\n\n3)it can't be in the fbq\n \n*)\n\nDefinition gc(c:chip) (f:FTL) (flag:alloc_block_type): option (prod chip FTL) :=\n  match flag with\n      | alloc_trans_block => do pbn <-- lookfor_gc_block f PAGES_PER_BLOCK 0 gc_trans_block; \n                             do [c',f'] <--gc_trans c f pbn;\n                             ret (c',f')\n      \n      | alloc_data_block =>  do pbn <-- lookfor_gc_block f PAGES_PER_BLOCK 0 gc_data_block; \n                             do [c',f'] <--gc_data c f pbn;\n                             ret (c',f')\n  end.\n\nDefinition alloc_block (c: chip) (f: FTL) (flag:alloc_block_type) : option (prod chip FTL) :=\n  let bit := ftl_bi_table f in\n  let fbq := ftl_free_blocks f in\n  match (check_freebq_count fbq) with\n    | fbqs_abundant =>\n        do bs_status <-- Some (set_alloc_block_status flag);\n        do [b, fbq'] <-- fbq_deq fbq; \n        do bi_free <-- bit_get bit b;\n        match bi_state bi_free with\n          | bs_erased => \n              (* TODO:  we don't need to update bit. No,we need,we set the used_pages and pages_state *)\n              do bit' <-- bit_update bit b (mk_bi bs_status 0 (bi_erase_count bi_free) (pst_set_all ps_erased));\n              match flag with\n                  | alloc_trans_block => ret (c, (mk_FTL bit'  fbq' (ftl_cmt_table f) (ftl_gtd_table f) (current_data_block f) b ))\n                  | alloc_data_block => ret (c, (mk_FTL bit'  fbq' (ftl_cmt_table f) (ftl_gtd_table f) b (current_trans_block f )))\n              end\n          | bs_invalid => \n              do c' <-- nand_erase_block c b;\n              do bit' <-- bit_update bit b (mk_bi bs_status 0 (1 + bi_erase_count bi_free) (pst_set_all ps_erased));\n              match flag with\n                  | alloc_trans_block => ret (c',(mk_FTL bit' fbq' (ftl_cmt_table f) (ftl_gtd_table f) (current_data_block f) b ))\n                  | alloc_data_block =>  ret (c',(mk_FTL bit' fbq' (ftl_cmt_table f) (ftl_gtd_table f) b (current_trans_block f)))\n              end\n          | bs_data => None\n\n          | bs_trans => None\n        end \n  \n    | _ =>  do [c',f'] <-- gc c f flag;\n            ret (c',f')\n  end.\n                                                                                                          \n(* ******************************************************************************\n* copy the trans_page_data(trans_pbn,trans_off) to current block  page or new allock page \n  for updating the pbn off\n*)\n\nDefinition copy_trans_page(c:chip)(f:FTL)(lpn:page_no)(trans_pbn:block_no)(trans_off:nat)(pbn:block_no)(off:nat): option (prod chip FTL) :=\n  let bit := ftl_bi_table f in\n  let fbq := ftl_free_blocks f in\n  let cmt := ftl_cmt_table f in\n  let gtd := ftl_gtd_table f in\n  let cur_trans := current_trans_block f in\n  let cur_data := current_data_block f in\n  do d <-- read_block c trans_pbn trans_off;\n  match d with\n    | metabyte _ => None\n    | metarecord meta_list => do new_list <-- copy_data_trans meta_list lpn (trans_data lpn pbn off);\n                              do cur_bi <-- bit_get bit cur_trans;\n                              do gtd_loc <-- gtd_look_by_lpn gtd lpn;\n                              match check_block_full cur_bi with\n                                | true =>(* If it is full *)\n                                         do cfx <-- alloc_block c f alloc_trans_block;\n                                         do [c',f'] <-- Some cfx;\n                                         do new_trans <-- Some (current_trans_block f');\n                                         do bi <-- bit_get (ftl_bi_table f') new_trans;\n                                         do new_trans_off <-- Some (bi_used_pages bi);\n                                         (* Repeat *)\n                                         do [c'',bi'] <-- write_data_block c' bi new_trans new_trans_off (metarecord new_list) (Some (gtd_loc, 0)) (ps_trans gtd_loc);\n                                         do bit' <-- bit_update (ftl_bi_table f') new_trans bi';\n                                         (*Invalidate the old trans one*)\n                                         do bit'' <-- invalid_old_page bit' trans_pbn trans_off;\n                                         (*Invalidate the old data one*)\n                                         match find_meta_trans_record meta_list lpn 0 with\n                                             | None =>  (* update the gtd *)\n                                                        do gtd' <-- gtd_set gtd gtd_loc (gtd_trans new_trans new_trans_off) ;\n                                                        ret(c'',(mk_FTL bit'' (ftl_free_blocks f') (ftl_cmt_table f') gtd' cur_data new_trans) )\n                                                           \n                                             | Some i => do [old_data,old_off] <--  get_meta_trans_record meta_list lpn i;\n                                                         do bit''' <-- invalid_old_page bit'' old_data old_off;\n                                                         do gtd' <-- gtd_set gtd gtd_loc (gtd_trans new_trans new_trans_off) ;\n                                                         ret(c'',(mk_FTL bit''' (ftl_free_blocks f') (ftl_cmt_table f') gtd' cur_data new_trans) )\n                                        end\n                                                        \n                                | false =>\n                                           do cur_off <-- Some (bi_used_pages cur_bi);\n                                           do [c',bi'] <-- write_data_block c cur_bi cur_trans cur_off (metarecord new_list) (Some(gtd_loc, 0)) (ps_trans gtd_loc);\n                                           do bit' <-- bit_update bit cur_trans bi';\n                                           (*Invalide the old trans page*)\n                                           do bit'' <-- invalid_old_page bit' trans_pbn trans_off;\n                                           (*Invalidate the old data one*)\n                                           match find_meta_trans_record meta_list lpn 0 with\n                                             | None =>  (* update the gtd,find the gtd_loc *)\n                                                        do gtd' <-- gtd_set gtd gtd_loc (gtd_trans cur_trans cur_off);\n                                                        ret (c',(mk_FTL bit'' fbq cmt  gtd' cur_data cur_trans ) )\n\n                                             | Some i => do [old_data,old_off] <--  get_meta_trans_record meta_list lpn i;\n                                                         do bit''' <-- invalid_old_page bit'' old_data old_off;\n                                                         (* update the gtd,find the gtd_loc *)\n                                                         do gtd' <-- gtd_set gtd gtd_loc (gtd_trans cur_trans cur_off);\n                                                         ret (c',(mk_FTL bit''' fbq cmt  gtd' cur_data cur_trans ) )\n                                            end\n                               end\nend.\n   \nDefinition write_trans_page(c:chip)(f:FTL)(lpn:page_no) (pbn:block_no)(off:nat): option (prod chip FTL) :=\n  let bit := ftl_bi_table f in\n  let fbq := ftl_free_blocks f in\n  let cmt := ftl_cmt_table f in\n  let gtd := ftl_gtd_table f in\n  let cur_trans := current_trans_block f in\n  let cur_data := current_data_block f in\n  do meta_list <-- Some (blank_dmt);\n  do new_list <-- copy_data_trans meta_list lpn (trans_data lpn pbn off);\n  do cur_bi <-- bit_get bit cur_trans;\n  do gtd_loc <-- gtd_look_by_lpn gtd lpn;\n  match check_block_full cur_bi with\n       | true =>(* If it is full *)\n             do cfx <-- alloc_block c f alloc_trans_block;\n             do [c',f'] <-- Some cfx;\n             do new_trans <-- Some (current_trans_block f');\n             do bi <-- bit_get (ftl_bi_table f') new_trans;\n             do new_trans_off <-- Some (bi_used_pages bi);\n             (* Repeat *)\n             do [c'',bi'] <-- write_data_block c' bi new_trans new_trans_off (metarecord new_list) (Some (gtd_loc, 0)) (ps_trans gtd_loc);\n             do bit' <-- bit_update (ftl_bi_table f') new_trans bi';\n             do gtd' <-- gtd_set gtd gtd_loc (gtd_trans new_trans new_trans_off) ;\n             ret(c'',(mk_FTL bit' (ftl_free_blocks f') (ftl_cmt_table f') gtd' cur_data new_trans) )\n                                        \n                                                        \n       | false =>\n            do cur_off <-- Some (bi_used_pages cur_bi);\n            do [c',bi'] <-- write_data_block c cur_bi cur_trans cur_off (metarecord new_list) (Some (gtd_loc, 0)) (ps_trans gtd_loc);\n            do bit' <-- bit_update bit cur_trans bi';\n            do gtd' <-- gtd_set gtd gtd_loc (gtd_trans cur_trans cur_off);\n            ret (c',(mk_FTL bit' fbq cmt  gtd' cur_data cur_trans ) )\nend.\n\n                                                                          \nDefinition FTL_read(c:chip)(f:FTL)(lpn:page_no) : option (prod data (prod chip FTL) ) :=\n  let bit := ftl_bi_table f in\n  let fbq := ftl_free_blocks f in\n  let cmt := ftl_cmt_table f in\n  let gtd := ftl_gtd_table f in\n  (* test valid_page_off off; *)\n  (* If the lpn in the cmt *)\n  test bvalid_logical_page_no lpn;\n  match find_cmtrecord cmt lpn 0 with\n      | Some num =>\n                  (* Do the read change the priitoty *)\n                  do record <-- cmt_get cmt num;\n                  match record with\n                   | cmt_empty => None\n                   | cmt_trans lpn' pbn' off' flag' =>\n                                              match find_empty_cmt cmt 0 with\n                                                  | None =>  do cmt' <-- Some (remove_cmt cmt lpn);\n                                                             do cmt'' <-- Some (append_tail cmt' record);\n                                                             do d <-- read_block c pbn' off';\n                                                             ret (d,(c,mk_FTL (ftl_bi_table f) (ftl_free_blocks f) cmt'' (ftl_gtd_table f) (current_data_block f) (current_trans_block f) ) )\n                                                  | Some i => do cmt' <-- Some (remove_cmt cmt lpn);\n                                                              do cmt'' <-- Some (insert_cmt cmt' record (pred i) );\n                                                              do d <-- read_block c pbn' off';\n                                                              ret (d,(c,mk_FTL (ftl_bi_table f) (ftl_free_blocks f) cmt'' (ftl_gtd_table f) (current_data_block f) (current_trans_block f) ) )\n                                               end\n                  end\n      | None => do gtd_loc <-- gtd_look_by_lpn gtd lpn;\n                do gtd_record <-- gtd_get gtd gtd_loc;\n                match gtd_record with\n                   | gtd_empty => ret (zero_page,(c,f))\n                   | gtd_trans trans_lbn trans_offset =>\n                             do [data,oob] <-- nand_read_page c trans_lbn trans_offset;\n                             match data with\n                                   | metabyte _ => None\n                                   | metarecord meta_trans_list =>do [data_pbn,data_off] <-- find_trans_in_metatrans meta_trans_list lpn;\n                                                                  match find_empty_cmt cmt 0 with\n                                                                    | Some i =>(* Thec cmt is not full ,still have empty location *)\n                                                                               (* If find the empty the empty must in the end,cmt_set and append_tail is both ok *)\n                                                                               do newcmt <-- cmt_set cmt i (cmt_trans lpn data_pbn data_off clean);\n                                                                               do d <-- read_block c data_pbn data_off;\n                                                                               ret (d,(c,mk_FTL (ftl_bi_table f) (ftl_free_blocks f) newcmt (ftl_gtd_table f) (current_data_block f) (current_trans_block f)))\n                                                                    \n                                                                    | None =>  (*If it doesn't find the empty,the cmt is full *)\n                                                                               do head <-- cmt_get cmt 0;\n                                                                               match head with\n                                                                                | cmt_trans h_lpn h_pbn h_off flag'' =>\n                                                                                     match flag'' with\n                                                                                       | clean =>\n                                                                                                 do newcmt' <-- remove_head cmt;\n                                                                                                 do newcmt'' <-- Some (append_tail newcmt' (cmt_trans lpn data_pbn data_off clean) );\n                                                                                                 do d <-- read_block c data_pbn data_off;\n                                                                                                 ret (d,(c,mk_FTL (ftl_bi_table f) (ftl_free_blocks f) newcmt'' (ftl_gtd_table f) (current_data_block f) (current_trans_block f)))\n                                                                                       | drity =>\n                                                                                                 (* it is dirty *)\n                                                                                                 (*find the the trans_page for h_lpn *)\n                                                                                                 do newcmt' <-- remove_head cmt;\n                                                                                                 do newcmt'' <-- Some (append_tail newcmt' (cmt_trans lpn data_pbn data_off clean) );\n                                                                                                 do newf <-- ftl_update_cmt f newcmt'';\n                                                                                                 do d <-- read_block c data_pbn data_off;\n                                                                                                 match gtd_get_trans_by_lpn gtd h_lpn with\n                                                                                                     | Some _ =>\n                                                                                                          do [h_trans_pbn,h_trans_off] <-- gtd_get_trans_by_lpn gtd h_lpn;\n                                                                                                          do [c',f'] <-- copy_trans_page c newf h_lpn h_trans_pbn h_trans_off h_pbn h_off;\n                                                                                                          ret (d,(c', f'))\n                                                                                                     | None =>\n                                                                                                          do [c',f'] <-- write_trans_page c newf h_lpn h_pbn h_off;\n                                                                                                          ret (d,(c',f'))\n                                                                                                  end\n                                                                                         end\n                                                                                | cmt_empty => None\n                                                                               end\n      \n                                                                    end\n                                                                                          \n                                end\n                  end\nend.\n                \nDefinition cmt_update_when_ftl_write(c:chip) (f:FTL) (lbn:block_no) (loff:nat):option (prod chip FTL) :=\n  let bit := ftl_bi_table f in\n  let fbq := ftl_free_blocks f in\n  let cmt := ftl_cmt_table f in\n  let gtd := ftl_gtd_table f in\n  let cur_trans := current_trans_block f in\n  let cur_data := current_data_block f in\n  let lpn := lbn * PAGES_PER_BLOCK + loff in\n  do bi <-- bit_get bit cur_data;\n  do poff <-- Some (pred (bi_used_pages bi) );\n  match find_cmtrecord cmt lpn 0 with\n                     (* The cmt don't have the record *)\n                     | None =>\n                           match find_empty_cmt cmt 0 with\n                                (* find the cmt is not full *)\n                               | Some i => do cmt' <-- cmt_set cmt i (cmt_trans lpn cur_data poff dirty);\n                                           ret (c,mk_FTL bit fbq cmt' gtd cur_data cur_trans)\n                               | None  =>  do record <-- cmt_get cmt 0;\n                                           match record with\n                                               | cmt_empty => None\n                                               | cmt_trans h_lpn h_pbn h_off h_flag =>\n                                                       do cmt' <-- remove_head cmt;\n                                                       do cmt'' <-- Some (append_tail cmt' (cmt_trans lpn cur_data poff dirty) );\n                                                       match h_flag with\n                                                           | clean =>  ret (c,mk_FTL bit fbq cmt'' gtd cur_data cur_trans)\n                                                           | dirty =>  (*TO DO-->Done,This is not the invalid data*)\n                                                                      match gtd_get_trans_by_lpn gtd h_lpn with\n                                                                          | Some _ =>\n                                                                                 do [h_trans_pbn,h_trans_off] <-- gtd_get_trans_by_lpn gtd h_lpn;\n                                                                                 do new_f <-- Some (mk_FTL bit fbq cmt'' gtd cur_data cur_trans);\n                                                                                 do [c'',new_f'] <-- copy_trans_page c new_f  h_lpn h_trans_pbn h_trans_off h_pbn h_off;\n                                                                                 ret (c'',new_f')\n                                                                          | None => (* The gtd loc is empty *)\n                                                                                 do f' <-- ftl_update_cmt f cmt'';\n                                                                                 do [c',f''] <-- write_trans_page c f' h_lpn h_pbn h_off;\n                                                                                 ret (c',f'')\n                                                                       end\n                                                       end\n                                           end\n                                     \n                           end\n                     (* It is in the cmt *)\n                     | Some i => do record <-- cmt_get cmt i;\n                                 do [old_pbn_off,cmt_flag] <-- cmt_get_trans record;\n                                 (* The old data_one *)\n                                 do [old_pbn,old_off] <-- Some old_pbn_off;\n                                 (* do cmt' <-- cmt_set cmt i (cmt_trans lpn cur_data poff dirty); *)\n                                 match find_empty_cmt cmt 0 with\n                                     | None => do cmt' <-- Some (remove_cmt cmt lpn);\n                                               do cmt'' <-- Some (append_tail cmt' (cmt_trans lpn cur_data poff dirty) );\n                                               match cmt_flag with\n                                                 | dirty => do bit' <-- invalid_old_page bit old_pbn old_off;\n                                                           do new_f <-- Some (mk_FTL bit' fbq cmt'' gtd cur_data cur_trans);\n                                                           ret (c,new_f)\n                                                 | clean => (*TO DO-->Done,invalid is lazy*)\n                                                            do new_f <-- Some (mk_FTL bit fbq cmt'' gtd cur_data cur_trans);\n                                                            ret(c,new_f)\n                                               end\n                                    | Some empty_loc =>  do cmt' <-- Some (remove_cmt cmt  lpn);\n                                                         do cmt'' <-- Some (insert_cmt cmt' (cmt_trans lpn cur_data poff dirty) (pred empty_loc) );\n                                                          match cmt_flag with\n                                                            | dirty => do bit' <-- invalid_old_page bit old_pbn old_off;\n                                                                      do new_f <-- Some (mk_FTL bit' fbq cmt'' gtd cur_data cur_trans);\n                                                                      ret (c,new_f)\n                                                            | clean => (*TO DO-->Done,invalid is lazy*)\n                                                                      do new_f <-- Some (mk_FTL bit fbq cmt'' gtd cur_data cur_trans);\n                                                                      ret(c,new_f)\n                                                           end\n                                 end\n                                                 \n    end.\n\nFixpoint get_lbnandoff_by_lpn (lpn:page_no) (num:nat) : option (prod nat nat) :=\n match num with\n      | O  => None\n      | S i'  => if ble_nat (i' * PAGES_PER_BLOCK) lpn then Some (i',(minus lpn (i' * PAGES_PER_BLOCK) ) ) else get_lbnandoff_by_lpn lpn i'\n end.\n\nDefinition FTL_write (c:chip) (f:FTL) (lpn:page_no) (d:data):option (prod chip FTL) :=\n  let bit := ftl_bi_table f in\n  let fbq := ftl_free_blocks f in\n  let cmt := ftl_cmt_table f in\n  let gtd := ftl_gtd_table f in\n  let cur_trans := current_trans_block f in\n  let cur_data := current_data_block f in\n  (* let lpn := lbn * PAGES_PER_BLOCK + loff in *)\n  do [lbn,loff] <-- get_lbnandoff_by_lpn lpn BLOCKS;\n  do bi <-- bit_get bit cur_data;\n  do poff <-- Some (bi_used_pages bi);\n  match check_block_is_full bi with\n      (*It is not full*)\n      | false => do [c',bi'] <-- write_data_block c bi cur_data poff d (Some (lbn,loff)) (ps_data lpn);\n                 (* update the page_state in the bit *)\n                 do bit' <-- bit_update bit cur_data bi';\n                 do new_f <-- ftl_update_bit f bit';\n                 do [new_c',new_f'] <-- cmt_update_when_ftl_write c' new_f lbn loff;\n                 ret (new_c',new_f')\n      | true  =>  do cfx <-- alloc_block c f alloc_data_block;\n                  do [c',f'] <-- Some cfx;\n                  do new_data <-- Some (current_data_block f');\n                  do bi' <-- bit_get (ftl_bi_table f') new_data;\n                  do new_data_off <-- Some (bi_used_pages bi');\n                  do [c'',bi''] <-- write_data_block c' bi' new_data (new_data_off) d (Some (lbn, loff)) (ps_data lpn);\n                  do bit' <-- bit_update (ftl_bi_table f') new_data bi'';\n                  do new_f <-- Some (mk_FTL bit' (ftl_free_blocks f') (ftl_cmt_table f') (ftl_gtd_table f') new_data (current_trans_block f') );\n                  (* update the cmt *)\n                  do [new_c',new_f'] <-- cmt_update_when_ftl_write c'' new_f lbn loff;\n                  ret (new_c',new_f')\n end.\n                \n\n\n", "meta": {"author": "zbh24", "repo": "formal_dftl", "sha": "b8e1141a7094c73def3a064c11d6ec241c031e75", "save_path": "github-repos/coq/zbh24-formal_dftl", "path": "github-repos/coq/zbh24-formal_dftl/formal_dftl-b8e1141a7094c73def3a064c11d6ec241c031e75/Dftl2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.29682220008291893}}
{"text": "From iris.program_logic Require Export weakestpre.\nFrom iris.base_logic.lib Require Export invariants.\nFrom iris.heap_lang Require Export lang.\nFrom iris.proofmode Require Import tactics.\nFrom iris.heap_lang Require Import proofmode notation.\nFrom iris.algebra Require Import excl.\nSet Default Proof Using \"Type\".\n\nDefinition spawn : val :=\n  λ: \"f\",\n    let: \"c\" := ref NONE in\n    Fork (\"c\" <- SOME (\"f\" #())) ;; \"c\".\nDefinition join : val :=\n  rec: \"join\" \"c\" :=\n    match: !\"c\" with\n      SOME \"x\" => \"x\"\n    | NONE => \"join\" \"c\"\n    end.\n\n(** The CMRA & functor we need. *)\n(* Not bundling heapG, as it may be shared with other users. *)\nClass spawnG Σ := SpawnG { spawn_tokG :> inG Σ (exclR unitC) }.\nDefinition spawnΣ : gFunctors := #[GFunctor (exclR unitC)].\n\nInstance subG_spawnΣ {Σ} : subG spawnΣ Σ → spawnG Σ.\nProof. solve_inG. Qed.\n\n(** Now we come to the Iris part of the proof. *)\nSection proof.\nContext `{!heapG Σ, !spawnG Σ} (N : namespace).\n\nDefinition spawn_inv (γ : gname) (l : loc) (Ψ : val → iProp Σ) : iProp Σ :=\n  (∃ lv, l ↦ lv ∗ (⌜lv = NONEV⌝ ∨\n                   ∃ v, ⌜lv = SOMEV v⌝ ∗ (Ψ v ∨ own γ (Excl ()))))%I.\n\nDefinition join_handle (l : loc) (Ψ : val → iProp Σ) : iProp Σ :=\n  (∃ γ, own γ (Excl ()) ∗ 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) :\n  to_val e = Some f →\n  {{{ WP f #() {{ Ψ }} }}} spawn e {{{ l, RET #l; join_handle l Ψ }}}.\nProof.\n  iIntros (<-%of_to_val Φ) \"Hf HΦ\". rewrite /spawn /=.\n  wp_let. wp_alloc l as \"Hl\". wp_let.\n  iMod (own_alloc (Excl ())) as (γ) \"Hγ\"; first done.\n  iMod (inv_alloc N _ (spawn_inv γ l Ψ) with \"[Hl]\") as \"#?\".\n  { iNext. iExists NONEV. iFrame; eauto. }\n  wp_apply wp_fork; simpl. iSplitR \"Hf\".\n  - wp_seq. iApply \"HΦ\". rewrite /join_handle. eauto.\n  - wp_bind (f _). iApply (wp_wand with \"Hf\"); iIntros (v) \"Hv\".\n    iInv N as (v') \"[Hl _]\" \"Hclose\".\n    wp_store. iApply \"Hclose\". iNext. iExists (SOMEV v). iFrame. eauto.\nQed.\n\nLemma join_spec (Ψ : val → iProp Σ) l :\n  {{{ join_handle l Ψ }}} join #l {{{ v, RET v; Ψ v }}}.\nProof.\n  iIntros (Φ) \"H HΦ\". iDestruct \"H\" as (γ) \"[Hγ #?]\".\n  iLöb as \"IH\". wp_rec. wp_bind (! _)%E. iInv N as (v) \"[Hl Hinv]\" \"Hclose\".\n  wp_load. iDestruct \"Hinv\" as \"[%|Hinv]\"; subst.\n  - iMod (\"Hclose\" with \"[Hl]\"); [iNext; iExists _; iFrame; eauto|].\n    iModIntro. wp_match. iApply (\"IH\" with \"Hγ [HΦ]\"). auto.\n  - iDestruct \"Hinv\" as (v') \"[% [HΨ|Hγ']]\"; simplify_eq/=.\n    + iMod (\"Hclose\" with \"[Hl Hγ]\"); [iNext; iExists _; iFrame; eauto|].\n      iModIntro. wp_match. by iApply \"HΦ\".\n    + iDestruct (own_valid_2 with \"Hγ Hγ'\") as %[].\nQed.\nEnd proof.\n\nTypeclasses Opaque join_handle.\n", "meta": {"author": "jeehoonkang", "repo": "iRRAM-coq", "sha": "54205696dbc71535b78cb1403b19d325161172d6", "save_path": "github-repos/coq/jeehoonkang-iRRAM-coq", "path": "github-repos/coq/jeehoonkang-iRRAM-coq/iRRAM-coq-54205696dbc71535b78cb1403b19d325161172d6/src/lang/lib/spawn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.29682220008291893}}
{"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(*                   SF-Calculus                                      *)\n(*                                                                    *)\n(* is implemented in Coq by adapting the implementation of            *)\n(* Lambda Calculus from Project Coq                                   *)\n(* 2015                                                               *)\n(**********************************************************************)\n\n(**********************************************************************)\n(*                   SF_tactics.v                                     *)\n(*                                                                    *)\n(*                     Barry Jay                                      *)\n(*                                                                    *)\n(**********************************************************************)\n\nRequire Import Arith.\nRequire Import Test. \nRequire Import General.\nRequire Import SF_Terms. \n\nDefinition termred := SF -> SF -> Prop.\n\nDefinition preserve (R : termred) (P : SF -> Prop) :=\n  forall x : SF, P x -> forall y : SF, R x y -> P y.\n\n\nInductive multi_step : termred -> termred :=\n  | zero_red : forall red M, multi_step red M M\n  | succ_red : forall (red: SF-> SF -> Prop) M N P, \n                   red M N -> multi_step red N P -> multi_step red M P\n.\n\nInductive sequential : termred -> termred -> termred :=\n  | seq_red : forall (red1 red2 : termred) M N P, \n                red1 M N -> red2 N P -> sequential red1 red2 M P.\n\nHint Resolve zero_red succ_red seq_red\n.\n\nDefinition reflective red := forall (M: SF), red M M.\n\nLemma refl_multi_step : forall (red: termred), reflective (multi_step red).\nProof. red; split_all. Qed.\n\nLemma refl_seq : forall (red1 red2: termred),\n                   reflective red1 -> reflective red2 -> reflective(sequential red1 red2).\nProof. red; split_all; eapply2 seq_red. Qed.\n\n\nLtac reflect := match goal with \n| |- reflective (multi_step _) => eapply2 refl_multi_step\n| |- multi_step _ _ _ => try (eapply2 refl_multi_step)\n| |- reflective (sequential _) => eapply2 refl_seq; reflect \n| |- sequential _ _ _ _ => try (eapply2 refl_seq)\n| _ => split_all\nend.\n\n\nLtac one_step := \nmatch goal with \n| |- multi_step _ _ ?N => apply succ_red with N; auto; try red; try reflect\nend.\n\nLtac seq_l := \nmatch goal with \n| |- sequential _ _ ?M ?N => apply seq_red with N; auto; red; reflect\nend.\n\nLtac seq_r := \nmatch goal with \n| |- sequential _ _ ?M ?N => apply seq_red with M; auto; red; reflect\nend.\n\n\nDefinition transitive red := forall (M N P: SF), red M N -> red N P -> red M P. \n\nLemma transitive_red : forall red, transitive (multi_step red). \nProof. red; induction 1; split_all. \napply succ_red with N; auto. \nQed. \n\n\nDefinition preserves_app (red : termred) := \nforall M M' N N', red M M' -> red N N' -> red (App M N) (App M' N').\n\n\nLemma preserves_app_multi_step : forall (red: termred), reflective red -> preserves_app red -> preserves_app (multi_step red). \nProof.\nred. induction 3; split_all. generalize H0; induction 1. \nreflect. \napply succ_red with (App M N); auto.\nassert( transitive (multi_step red)) by eapply2 transitive_red.  \napply X0 with (App N0 N); auto. \none_step. \nQed.\n\nLemma preserves_app_seq : forall (red1 red2: termred), preserves_app red1 -> preserves_app red2 -> preserves_app (sequential red1 red2). \nProof.\nred; split_all. \ninversion H1; inversion H2.\napply seq_red with (App N0 N1); auto.\nQed.\n\nHint Resolve preserves_app_multi_step preserves_app_seq .\n\n\nLtac eelim_for_equal := \nmatch goal with \n| H: forall _, _ = _ -> _  |- _ => eelim H; clear H; subst; eelim_for_equal\n| _ => split_all \nend. \n\nLtac inv1 prop := \nmatch goal with \n| H: prop (Ref _) |- _ => inversion H; clear H; inv1 prop\n| H: prop (App  _ _) |- _ => inversion H; clear H; inv1 prop\n| H: prop Op _ |- _ => inversion H; clear H; inv1 prop\n| _ => split_all\n end.\n\n\nDefinition implies_red (red1 red2: termred) := forall M N, red1 M N -> red2 M N. \n\nLemma implies_red_multi_step: forall red1 red2, implies_red red1  (multi_step red2) -> \n                                                implies_red (multi_step red1) (multi_step red2).\nProof. red. \nintros red1 red2 IR M N R; induction R; split_all. \napply transitive_red with N; auto. \nQed. \nLemma implies_red_seq: \n forall red1 red2 red3, \n  implies_red red1  (multi_step red3)  ->  \n  implies_red red2 (multi_step red3) -> \n  implies_red (sequential red1 red2) (multi_step red3) .\nProof. \nred; split_all. inversion H1. apply transitive_red with N0; auto. \nQed. \n\n\nDefinition subst_preserves_l (red: termred) := \nforall (M M' N : SF), red M M' -> red  (subst M N) (subst M' N).\n\nDefinition subst_preserves_r (red: termred) := \nforall (M N N' : SF), red N N' -> red  (subst M N) (subst M N').\n\nDefinition subst_preserves (red: termred) := \nforall (M M' : SF), red M M' -> forall N N', red N N' -> \nred  (subst M N) (subst M' N').\n\nLemma subst_preserves_l_multi_step : \nforall (red: termred), subst_preserves_l red -> subst_preserves_l (multi_step red). \nProof. unfold subst_preserves_l. \n induction 2; split_all.  \napply succ_red with (subst N0 N); auto.\nQed.\n\nLemma subst_preserves_r_multi_step : \nforall (red: termred), subst_preserves_r red -> subst_preserves_r (multi_step red). \nProof. unfold subst_preserves_r. \n induction 2; split_all.  \napply succ_red with (subst M N); auto.\nQed. \n\nLemma subst_preserves_multi_step : \nforall (red: termred), subst_preserves_l red -> subst_preserves_r red -> subst_preserves (multi_step red). \nProof. \nunfold subst_preserves. split_all.\nassert(transitive (multi_step red)) by eapply2 transitive_red. \nunfold transitive in *.\napply X with  (subst M' N); auto. \neapply2 subst_preserves_l_multi_step.\neapply2 subst_preserves_r_multi_step.\nQed.\n\n\n\nLtac inv red := \nmatch goal with \n| H: multi_step red (App _ _) _ |- _ => inversion H; clear H; inv red\n| H: multi_step red (Ref _) _ |- _ => inversion H; clear H; inv red\n| H: multi_step red (Op _) _ |- _ => inversion H; clear H; inv red\n| H: red (Ref _) _ |- _ => inversion H; clear H; inv red\n| H: red (App _ _) _ |- _ => inversion H; clear H; inv red\n| H: red (Op _) _ |- _ => inversion H; clear H; inv red\n| H: multi_step red _ (Ref _) |- _ => inversion H; clear H; inv red\n| H: multi_step red _ (App _ _) |- _ => inversion H; clear H; inv red\n| H: multi_step red _ (Op _) |- _ => inversion H; clear H; inv red\n| H: red _ (Ref _) |- _ => inversion H; clear H; inv red\n| H: red _ (App _ _) |- _ => inversion H; clear H; inv red\n| H: red _ (Op _) |- _ => inversion H; clear H; inv red\n| _ => subst; split_all \n end.\n\n\n\nDefinition diamond (red1 red2 : termred) := \nforall M N, red1 M N -> forall P, red2 M P -> exists Q, red2 N Q /\\ red1 P Q. \n\nLemma diamond_flip: forall red1 red2, diamond red1 red2 -> diamond red2 red1. \nProof. unfold diamond; split_all. elim (H M P H1 N H0); split_all. exist x. Qed.\n\nLemma diamond_strip : \nforall red1 red2, diamond red1 red2 -> diamond red1 (multi_step red2). \nProof. intros. \neapply2 diamond_flip. \nred; induction 1; split_all.\nexist P.\nelim (H M P0 H2 N); split_all. \nelim(IHmulti_step H x); split_all. \nexist x0.\napply succ_red with x; auto. \nQed. \n\n\nDefinition diamond_star (red1 red2: termred) := forall  M N, red1 M N -> forall P, red2 M P -> \n  exists Q, red1 P Q /\\ multi_step red2 N Q. \n\nLemma diamond_star_strip: forall red1 red2, diamond_star red1 red2 -> diamond (multi_step red2) red1 .\nProof. \nred. induction 2; split_all. \nexist P.\nelim(H M P0 H2 N H0); split_all. \nelim(IHmulti_step H x); split_all. \nexist x0.\napply transitive_red with x; auto. \nQed. \n\nLemma diamond_tiling : \nforall red1 red2, diamond red1 red2 -> diamond (multi_step red1) (multi_step red2).\nProof. \nred.  induction 2; split_all.\nexist P.\nelim(diamond_strip red red2 H M N H0 P0); split_all.\nelim(IHmulti_step H x H4); split_all.\nexist x0.\napply succ_red with x; auto.\nQed. \n\nHint Resolve diamond_tiling. \n\nLemma diamond_seq: forall red red1 red2, diamond red red1 -> diamond red red2 -> diamond red (sequential red1 red2). \nProof. unfold diamond; split_all. \ninversion H2. \nelim(H M N H1 N0); split_all.\nelim(H0 N0 x H11 P); split_all.\nexist x0. \napply seq_red with x; auto. \nQed.\n\nLemma relocate_null :\nforall (n n0 : nat), relocate n n0 0 = n.\nProof. split_all. unfold relocate. case (test n0 n); intro; auto with arith. Qed.\n\nLemma relocate_lessthan : forall m n k, m<=k -> relocate k m n = (n+k). \nProof. split_all. unfold relocate. elim(test m k); split_all; try noway. Qed. \nLemma relocate_greaterthan : forall m n k, m>k -> relocate k m n = k. \nProof. split_all. unfold relocate. elim(test m k); split_all; try noway. Qed. \n\nLtac relocate_lt := \ntry (rewrite relocate_lessthan; [| omega]; relocate_lt); \ntry (rewrite relocate_greaterthan; [| omega]; relocate_lt);\ntry(rewrite relocate_null). \n\n\nLemma relocate_zero_succ :\nforall n k, relocate 0 (S n) k = 0.\nProof.  split_all. Qed.\n\nLemma relocate_succ :\nforall n n0 k, relocate (S n) (S n0) k = S(relocate n n0 k).\nProof. \nintros; unfold relocate. elim(test(S n0) (S n)); elim(test n0 n); split_all. \nnoway. \nnoway. \nQed. \n\nLemma relocate_mono : forall M N n k, relocate M n k = relocate N n k -> M=N. \nProof. \nintros M N n k. \nunfold relocate.\nelim(test n M); elim(test n N); split_all; omega. \nQed. \n\n\n\nFixpoint rank (M: SF) := \nmatch M with \n| Ref _ => 1\n| Op _ => 1\n| App M1 M2 => S((rank M1) + (rank M2))\nend.\n\nLemma rank_positive: forall M, rank M > 0. \nProof. \ninduction M; split_all; try omega. \nQed. \n\n\n\nLtac rank_tac := match goal with \n| |- forall M, ?P  => \ncut (forall p M, p >= rank M -> P ); [ intros H M;  eapply2 H | \nintro p; induction p; intro M;  [ assert(rank M >0) by eapply2 rank_positive; noway |]\n]\nend .\n\n", "meta": {"author": "Barry-Jay", "repo": "SF", "sha": "748d1960e883b0433537ac0345632e550162d78c", "save_path": "github-repos/coq/Barry-Jay-SF", "path": "github-repos/coq/Barry-Jay-SF/SF-748d1960e883b0433537ac0345632e550162d78c/SF_Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.29680407630919603}}
{"text": "Require Import LibTactics.\nRequire Import Metalib.Metatheory.\nRequire Import syntax_ott\n               rules_inf.\n\nRequire Import List. Import ListNotations.\nRequire Import Strings.String.\n\n\nDefinition irred e : Prop := forall b, ~(step e b).\n\n\nNotation \"Γ ⊢ E ⇒ A\" := (Typing Γ E Inf A) (at level 45).\nNotation \"Γ ⊢ E ⇐ A\" := (Typing Γ E Chk A) (at level 45).\n\n\nNotation \"[ z ~> u ] e\" := (subst_exp u z e) (at level 0).\nNotation \"t ^^ u\"       := (open_exp_wrt_exp t u) (at level 67).\nNotation \"e ^ x\"        := (open_exp_wrt_exp e (e_var_f x)).\n\nNotation \"v ~-> A v'\" := (TypedReduce v A v') (at level 68).\n\nNotation \"t ->* r\" := (steps t r) (at level 68). \nNotation \"t ->** r\" := (gsteps t r) (at level 68).\n\nLemma star_one:\nforall a b, step a (Expr b) -> steps a (Expr b).\nProof.\neauto using steps.\nQed.\n\nLemma star_trans:\nforall a b, steps a (Expr b) -> forall c, steps b (Expr c) -> steps a (Expr c).\nProof.\n  introv H.\n  inductions H; eauto using steps.\nQed.\n\n\nLemma gstar_one:\nforall a b, gstep a (Expr b) -> gsteps a (Expr b).\nProof.\neauto using steps.\nQed.\n\nLemma gstar_trans:\nforall a b, gsteps a (Expr b) -> forall c, gsteps b (Expr c) -> gsteps a (Expr c).\nProof.\n  introv H.\n  inductions H; eauto using steps.\nQed.\n\n\nLemma gstar_transb:\nforall a b, gsteps a (Expr b) -> gsteps b Blame -> gsteps a Blame.\nProof.\n  introv red1 red2.\n  inductions red1; eauto using gsteps.\nQed.\n\nHint Resolve star_one star_trans gstar_one gstar_trans gstar_transb : core.\n\n\n\n\n(** [x # E] to be read x fresh from E captures the fact that\n    x is unbound in E . *)\n\nNotation \"x '#' E\" := (x \\notin (dom E)) (at level 67) : env_scope.\n\nDefinition env := list (atom * exp).\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 : list (var * typ) => dom x) in\n  let D := gather_atoms_with (fun x : exp => fv_exp x) in\n  let E := gather_atoms_with (fun x : ctx => dom x) in\n  let F := gather_atoms_with (fun x : env => dom x) in\n  constr:(A `union` B `union` C `union` D `union` F).\n\n\n\nLemma ssvalue_lc : forall v,\n    ssval v -> lc_exp v.\nProof.\n  intros v H.\n  induction* H. \nQed.\n\n\n\nLemma value_lc : forall v,\n    value v -> lc_exp v.\nProof.\n  intros v H.\n  induction* H.\n  forwards*: ssvalue_lc H. \nQed.\n\n\n\nLemma walue_lc : forall v,\n    walue v -> lc_exp v.\nProof.\n  intros v H.\n  induction* H.\n  forwards*: value_lc H. \nQed.\n\n\n\nLemma val_wal : forall v,\n    value v ->  walue v.\nProof.\n  introv H.\n  induction* H.\nQed.\n\n\n\nHint Resolve value_lc ssvalue_lc val_wal : core.\n\n\nLemma ssvalue_blame: forall (v:exp),\n    ssval v -> not(step v Blame).\nProof.\n  introv sval.\n  unfold not;intros nt. \n  inductions sval;inverts nt;\n  try solve[destruct E; unfold simpl_fill in H0; inverts* H0].\n  -\n  inverts H1; try solve[destruct E; unfold simpl_fill in H0; inverts* H0].\n  -\n  inverts H4; try solve[destruct E; unfold simpl_fill in H0; inverts* H0].\n  -\n  destruct E; unfold simpl_fill in H; inverts* H.\n  -\n  destruct E; unfold simpl_fill in H; inverts* H.\nQed.\n\nLemma step_not_value: forall (v:exp),\n    value v -> irred v.\nProof.\n  introv.\n  unfold irred.\n  inductions v; introv H;\n  inverts* H;\n  unfold not;intros.\n  - inverts* H; try solve[inverts H1].\n    destruct E; unfold simpl_fill in H0; inverts* H0.\n    destruct E; unfold simpl_fill in H0; inverts* H0.\n    forwards*:ssvalue_blame H4.\n    inverts* H5.\n    inverts H1;inverts* H3.\n    inverts H1;inverts* H3.\nQed.\n\n\nLemma step_not_walue: forall (v:exp),\n    walue v -> irred v.\nProof.\n  introv wal.\n  unfold irred.\n  inductions wal; intros.\n  forwards*: step_not_value H.\n  unfold not; intros nt; inverts* nt; \n  destruct E; unfold simpl_fill in H0; inverts* H0.\nQed.\n\n\nLemma sfill_appl : forall e1 e2,\n  (e_app e1 e2) = (simpl_fill (sappCtxL e2) e1).\nProof.\n  intros. eauto.\nQed.\n\nLemma sfill_appr : forall e1 e2,\n  (e_app e1 e2) = (simpl_fill (sappCtxR e1) e2).\nProof.\n  intros. eauto.\nQed.\n\nLemma sfill_addl : forall e1 e2,\n  (e_add e1 e2) = (simpl_fill (saddCtxL e2) e1).\nProof.\n  intros. eauto.\nQed.\n\nLemma sfill_addr : forall e1 e2,\n  (e_add e1 e2) = (simpl_fill (saddCtxR e1) e2).\nProof.\n  intros. eauto.\nQed.\n\n\n\nLemma sfill_prol : forall e1 e2,\n  (e_pro e1 e2) = (simpl_fill (sproCtxL e2) e1).\nProof.\n  intros. eauto.\nQed.\n\nLemma sfill_pror : forall e1 e2,\n  (e_pro e1 e2) = (simpl_fill (sproCtxR e1) e2).\nProof.\n  intros. eauto.\nQed.\n\n\nLemma sfill_l : forall e1,\n  (e_l e1) = (simpl_fill (slCtx) e1).\nProof.\n  intros. eauto.\nQed.\n\nLemma sfill_r : forall e1,\n(e_r e1) = (simpl_fill (srCtx) e1).\nProof.\n  intros. eauto.\nQed.\n\n\nLemma multi_red_app : forall v t t',\n    walue v -> t ->* (Expr t') -> (e_app v t) ->* (Expr (e_app v t')).\nProof.\n  introv Val Red.\n  inductions Red; eauto.\n  -\n  assert(simpl_wf (sappCtxR v)). eauto.\n  forwards*: do_step H0 H.\n  -\n  forwards*: IHRed.\n  assert(simpl_wf (sappCtxR v)). eauto.\n  forwards*: do_step H1 H.\nQed.\n\nLemma multi_red_app2 : forall t1 t2 t1',\n    lc_exp t2 -> t1 ->* (Expr t1') -> (e_app t1 t2) ->* (Expr (e_app t1' t2)).\nProof.\n  introv Val Red.\n  inductions Red; eauto.\n  -\n  assert(simpl_wf (sappCtxL t2)). eauto.\n  forwards*: do_step H0 H.\n  -\n  assert(simpl_wf (sappCtxL t2)). eauto.\n  forwards*: do_step H0 H.\nQed.\n\nLemma wmulti_red_pro : forall v t t',\n    walue v -> t ->* (Expr t') -> (e_pro v t) ->* (Expr (e_pro v t')).\nProof.\n  introv Val Red.\n  inductions Red; eauto.\n  -\n  assert(simpl_wf (sproCtxR v)). eauto.\n  forwards*: do_step H0 H.\n  -\n  forwards*: IHRed.\n  assert(simpl_wf (sproCtxR v)). eauto.\n  forwards*: do_step H1 H.\nQed.\n\nLemma multi_red_pro : forall v t t',\n    value v -> t ->* (Expr t') -> (e_pro v t) ->* (Expr (e_pro v t')).\nProof.\n  introv Val Red.\n  inductions Red; eauto.\n  -\n  assert(simpl_wf (sproCtxR v)). eauto.\n  forwards*: do_step H0 H.\n  -\n  forwards*: IHRed.\n  assert(simpl_wf (sproCtxR v)). eauto.\n  forwards*: do_step H1 H.\nQed.\n\nLemma multi_red_pro2 : forall t1 t2 t1',\n    lc_exp t2 -> t1 ->* (Expr t1') -> (e_pro t1 t2) ->* (Expr (e_pro t1' t2)).\nProof.\n  introv Val Red.\n  inductions Red; eauto.\n  -\n  assert(simpl_wf (sproCtxL t2)). eauto.\n  forwards*: do_step H0 H.\n  -\n  assert(simpl_wf (sproCtxL t2)). eauto.\n  forwards*: do_step H0 H.\nQed.\n\nLemma multi_red_l : forall t1 t1',\n     t1 ->* (Expr t1') -> (e_l t1) ->* (Expr (e_l t1')).\nProof.\n  introv Red.\n  inductions Red; eauto.\n  -\n  assert(simpl_wf (slCtx)). eauto.\n  forwards*: do_step H0 H.\n  -\n  assert(simpl_wf (slCtx)). eauto.\n  forwards*: do_step H0 H.\nQed.\n\n\nLemma multi_red_r : forall t1 t1',\n     t1 ->* (Expr t1') -> (e_r t1) ->* (Expr (e_r t1')).\nProof.\n  introv Red.\n  inductions Red; eauto.\n  -\n  assert(simpl_wf (srCtx)). eauto.\n  forwards*: do_step H0 H.\n  -\n  assert(simpl_wf (srCtx)). eauto.\n  forwards*: do_step H0 H.\nQed.\n\nLemma step_not_ssval: forall e e', \n step e (Expr e') ->\n not(ssval e').\nProof.\n  introv red.\n  inductions red; try solve[unfold not;intros nt;inverts* nt].\n  -\n  destruct E; unfold simpl_fill;unfold not;intros nt;inverts* nt.\n  -\n  unfold not;intros nt;inverts* nt.\n  inverts red; try solve[\n    destruct E; unfold simpl_fill in *;inverts* H0\n  ].\n  inverts* H2.\n  -\n  inverts* H0.\n  unfold not;intros nt;inverts* nt; try solve[inverts H3].\n  -\n  inverts H.\n  unfold not;intros nt;inverts* nt; try solve[inverts H2].\n  inverts H2. inverts H4.\n  -\n  inverts H.\n  unfold not;intros nt;inverts* nt; try solve[inverts H2].\n  inverts H2. inverts H5.\n  (* -\n  unfold not;intros nt;inverts* nt; try solve[inverts H2].\n  -\n  unfold not;intros nt;inverts* nt; try solve[inverts H2].\n  inverts H0; inverts H3.\n  inverts H1. *)\nQed.\n\n\n\nLemma multi_red_add : forall v t t',\n    value v -> t ->* (Expr t') -> (e_add v t) ->* (Expr (e_add v t')).\nProof.\n  introv Val Red.\n  inductions Red; eauto.\n  -\n  assert(simpl_wf (saddCtxR v)). eauto.\n  forwards*: do_step H0 H.\n  -\n  assert(simpl_wf (saddCtxR v)). eauto.\n  forwards*: do_step H0 H.\nQed.\n\nLemma multi_red_add2 : forall t1 t2 t1',\n    lc_exp t2 -> t1 ->* (Expr t1') -> (e_add t1 t2) ->* (Expr (e_add t1' t2)).\nProof.\n  introv Val Red.\n  inductions Red; eauto.\n  -\n  assert(simpl_wf (saddCtxL t2)). eauto.\n  forwards*: do_step H0 H.\n  -\n  assert(simpl_wf (saddCtxL t2)). eauto.\n  forwards*: do_step H0 H.\nQed.\n\n\nLemma multi_red_anno : forall A t t',\n    not (value (e_anno t A)) ->\n    t ->* (Expr t') -> (e_anno t A) ->* (Expr (e_anno t' A)).\nProof.\n  introv nt Red.\n  inductions Red; eauto.\n  assert(step (e_anno e A) (Expr (e_anno e' A))). eauto.\n  forwards*: IHRed.\n  unfold not; intros.\n  apply nt.\n  inverts H1.\n  forwards*: step_not_ssval H.\nQed.\n\n\nLemma gmulti_red_app : forall v t t',\n    gvalue v -> t ->** (Expr t') -> (e_app v t) ->** (Expr (e_app v t')).\nProof.\n  introv Val Red.\n  inductions Red; eauto.\n  forwards*: IHRed.\n  assert(wellformed (appCtxR v)). eauto.\n  forwards*: gdo_step H1 H.\nQed.\n\nLemma multi_blame_app : forall v t,\n    gvalue v -> t ->** (Blame) -> (e_app v t) ->** (Blame).\nProof.\n  introv Val Red.\n  inductions Red; eauto.\n  eapply gstep_nb.\n  assert(wellformed (appCtxR v)). eauto.\n  forwards*: gdo_step H0 H.\n  simpl. forwards*: IHRed.\n  apply gstep_b. \n  assert(wellformed (appCtxR v)). eauto.\n  forwards*: gblame_step H0 H.\nQed.\n\n\nLemma gmulti_red_app2 : forall t1 t2 t1',\n    lc_exp t2 -> t1 ->** (Expr t1') -> (e_app t1 t2) ->** (Expr (e_app t1' t2)).\nProof.\n  introv Val Red.\n  inductions Red; eauto.\n  assert(wellformed (appCtxL t2)). eauto.\n  forwards*: gdo_step H0 H.\nQed.\n\n\n\n\nLemma multi_blame_app2 : forall t1 t2 ,\n    lc_exp t2 -> t1 ->** Blame -> (e_app t1 t2) ->** Blame.\nProof.\n  introv Val Red.\n  inductions Red; eauto.\n  eapply gstep_nb.\n  assert(wellformed (appCtxL t2)). eauto.\n  forwards*: gdo_step H0 H.\n  simpl. forwards*: IHRed.\n  apply gstep_b. \n  assert(wellformed (appCtxL t2)). eauto.\n  forwards*: gblame_step H0 H.\nQed.\n\nLemma gmulti_red_anno : forall A t t',\n    t ->** (Expr t') -> (e_anno t A) ->** (Expr (e_anno t' A)).\nProof.\n  introv Red.\n  inductions Red; eauto.\n  forwards*: IHRed.\n  assert(wellformed (annoCtx A)). eauto.\n  forwards*: gdo_step H1 H.\nQed.\n\n\nLemma multi_blame_anno : forall t A ,\n    t ->** Blame -> (e_anno t A) ->** Blame.\nProof.\n  introv Red.\n  inductions Red; eauto.\n  eapply gstep_nb.\n  assert(wellformed (annoCtx A)). eauto.\n  forwards*: gdo_step H0 H.\n  simpl. forwards*: IHRed.\n  apply gstep_b. \n  assert(wellformed (annoCtx A)). eauto.\n  forwards*: gblame_step H0 H.\nQed.", "meta": {"author": "YeWenjia", "repo": "TypedDirectedGradualTypingWithBlame", "sha": "99210b5208555d4ea729738ea4a959c59b0646d0", "save_path": "github-repos/coq/YeWenjia-TypedDirectedGradualTypingWithBlame", "path": "github-repos/coq/YeWenjia-TypedDirectedGradualTypingWithBlame/TypedDirectedGradualTypingWithBlame-99210b5208555d4ea729738ea4a959c59b0646d0/JFP-Artifact/\\E/coq/Infrastructure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.2967681393653595}}
{"text": "Require Import List.\nImport ListNotations.\n\nRequire Export Map.\nRequire Export Shared.\n\nDefinition var := nat.\nDefinition id := nat.\nDefinition qid := nat.\nDefinition loc := nat.\n\n(*\n======\nTypes\n======\n*)\n\nInductive ty : Type :=\n  | TAct : ty\n  | TBes : ty\n  | TPas : ty\n  | TArr : ty -> ty -> ty\n  | TUnit: ty\n.\n\nFunction is_active (t : ty) : bool :=\n  match t with\n    | TAct => true\n    | TBes => true\n    | _ => false\n  end.\n\n(*\n============\nExpressions\n============\n*)\n\nInductive expr : Type :=\n  | EVar : var -> expr\n  | EApp : expr -> expr -> expr\n  | ESend : expr -> var -> ty -> expr -> expr\n  | EMut : expr -> expr\n  | ENew : ty -> expr\n  | EBes : expr -> expr\n  | EAtStart : expr -> expr\n  | EAtEnd : expr -> expr\n  | ELam : var -> ty -> expr -> expr\n  | EUnit : expr\n  | EId : id -> expr\n  | ELoc : loc -> expr\n  | EBId : loc -> id -> expr\n.\n\nTactic Notation \"expr_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"EVar\"\n  | Case_aux c \"EApp\"\n  | Case_aux c \"ESend\"\n  | Case_aux c \"EMut\"\n  | Case_aux c \"ENew\"\n  | Case_aux c \"EBes\"\n  | Case_aux c \"EAtStart\"\n  | Case_aux c \"EAtEnd\"\n  | Case_aux c \"ELam\"\n  | Case_aux c \"EUnit\"\n  | Case_aux c \"EId\"\n  | Case_aux c \"ELoc\"\n  | Case_aux c \"EBId\"\n].\n\nInductive is_val : expr -> Prop :=\n  | LamIsVal : forall x t e, is_val (ELam x t e)\n  | UnitIsVal : is_val EUnit\n  | IdIsVal : forall id, is_val (EId id)\n  | LocIsVal : forall l, is_val (ELoc l)\n  | BIdIsVal : forall l id, is_val (EBId l id)\n.\n\nDefinition econtext := expr -> expr.\n\nDefinition ctx_appl (e' : _) : econtext := (fun e => EApp e e').\nHint Unfold ctx_appl.\nDefinition ctx_appr (v : _) : econtext := (fun e => EApp v e).\nHint Unfold ctx_appr.\nDefinition ctx_send (x : _) (ty : _) (e' : _): econtext := (fun e => ESend e x ty e').\nHint Unfold ctx_send.\nDefinition ctx_mut : econtext := (fun e => EMut e).\nHint Unfold ctx_mut.\nDefinition ctx_bes : econtext := (fun e => EBes e).\nHint Unfold ctx_bes.\nDefinition ctx_atstart : econtext := (fun e => EAtStart e).\nHint Unfold ctx_atstart.\nDefinition ctx_atend : econtext := (fun e => EAtEnd e).\nHint Unfold ctx_atend.\n\nInductive is_econtext : econtext -> Prop :=\n  | EC_AppL :\n      forall e',\n        is_econtext (ctx_appl e')\n  | EC_AppR :\n      forall v,\n        is_val v ->\n        is_econtext (ctx_appr v)\n  | EC_Send :\n      forall x t e,\n        is_econtext (ctx_send x t e)\n  | EC_Mut :\n        is_econtext ctx_mut\n  | EC_Bes :\n        is_econtext ctx_bes\n  | EC_AtStart :\n        is_econtext ctx_atstart\n  | EC_AtEnd :\n        is_econtext ctx_atend\n.\n\nFixpoint freeVars (e : expr) : list var :=\n  match e with\n    | EVar x => [x]\n    | EApp e1 e2 => freeVars e1 ++ freeVars e2\n    | ESend e1 x _ e2 => freeVars e1 ++ List.remove id_eq_dec x (freeVars e2)\n    | EMut e' => freeVars e'\n    | EBes e' => freeVars e'\n    | EAtStart e' => freeVars e'\n    | EAtEnd e' => freeVars e'\n    | ELam x _ e' => List.remove id_eq_dec x (freeVars e')\n    | _ => []\n  end.\n\nFixpoint freeLocs (e : expr) : list loc :=\n  match e with\n    | ELoc l => [l]\n    | EApp e1 e2 => freeLocs e1 ++ freeLocs e2\n    | ESend e1 x _ e2 => freeLocs e1 ++ freeLocs e2\n    | EMut e' => freeLocs e'\n    | EBes e' => freeLocs e'\n    | EAtStart e' => freeLocs e'\n    | EAtEnd e' => freeLocs e'\n    | ELam x _ e' => freeLocs e'\n    | _ => []\n  end.\n\nFixpoint freeIds (e : expr) : list id :=\n  match e with\n    | EId id => [id]\n    | EApp e1 e2 => freeIds e1 ++ freeIds e2\n    | ESend e1 x _ e2 => freeIds e1 ++ freeIds e2\n    | EMut e' => freeIds e'\n    | EBes e' => freeIds e'\n    | EAtStart e' => freeIds e'\n    | EAtEnd e' => freeIds e'\n    | ELam x _ e' => freeIds e'\n    | _ => []\n  end.\n\nFixpoint freeBIds (e : expr) : list (loc * id) :=\n  match e with\n    | EBId l id => [(l, id)]\n    | EApp e1 e2 => freeBIds e1 ++ freeBIds e2\n    | ESend e1 x _ e2 => freeBIds e1 ++ freeBIds e2\n    | EMut e' => freeBIds e'\n    | EBes e' => freeBIds e'\n    | EAtStart e' => freeBIds e'\n    | EAtEnd e' => freeBIds e'\n    | ELam x _ e' => freeBIds e'\n    | _ => []\n  end.\n\nFixpoint subst (x : var) (v : expr) (e : expr) : expr :=\n  match e with\n    | EVar y => if id_eq_dec x y then v else e\n    | EApp e1 e2 => EApp (subst x v e1) (subst x v e2)\n    | ESend e1 y t e2 =>\n      ESend (subst x v e1) y t\n            (if id_eq_dec x y\n             then e2\n             else subst x v e2)\n    | EMut e' => EMut (subst x v e')\n    | EBes e' => EBes (subst x v e')\n    | EAtStart e' => EAtStart (subst x v e')\n    | EAtEnd e'   => EAtEnd (subst x v e')\n    | ELam y t e' =>\n      ELam y t\n           (if id_eq_dec x y then\n              e'\n            else\n              (subst x v e'))\n    | _ => e\n  end.\n\n(*\n==============\nConfiguration\n==============\n*)\n\nInductive msg : Type :=\n  | Msg : expr -> msg\n  | Atomic : qid -> msg\n  | EndAtomic : msg.\n\nDefinition localHeap := list loc.\n\nDefinition conversations := partial_map id qid.\n\nDefinition queue := list msg.\n\nDefinition actor := (loc * localHeap * conversations * queue * expr)%type.\n\nDefinition heap := list actor.\n\nDefinition heapExtend (H : heap) (a : actor) := snoc H a.\n\nHint Unfold heapExtend.\n\nDefinition heapLookup (H : heap) (id : id) :=\n  nth_error H id.\n\nFixpoint heapUpdate (H : heap) (id : id) (a : actor) :=\n  match H with\n  | nil => nil\n  | a' :: H' =>\n    match id with\n    | O    => a :: H'\n    | S id' => a' :: (heapUpdate H' id' a)\n    end\n  end.\n\nDefinition LH (H : heap) (id : id) :=\n  match heapLookup H id with\n    | Some (_, L, _, _, _) => Some L\n    | None => None\n  end.\n\nHint Unfold LH.\n\nDefinition conv (H : heap) (id : id) :=\n  match heapLookup H id with\n    | Some (_, _, C, _, _) => Some C\n    | None => None\n  end.\n\nHint Unfold conv.\n\n(*\n--------------\nConfiguration\n--------------\n*)\n\nDefinition queueMap := partial_map qid (queue*id).\n\nInductive actor_idle (M : queueMap) : actor -> Prop :=\n  | ActorIdle : forall l L C v, is_val v -> actor_idle M (l, L, C, [], v)\n  | ActorBlocked :\n      forall l L C q Q v id,\n        is_val v ->\n        M q = Some ([], id) ->\n        actor_idle M (l, L, C, Atomic q::Q, v)\n.\n\nDefinition heap_done (M : queueMap) := Forall (actor_idle M).\n\nDefinition configuration := (queueMap * heap * nat)%type.\n\nDefinition actor_done (cfg : configuration) (id : id) : Prop :=\n  match cfg with\n    | (M, H, _) => match heapLookup H id with\n                     | Some a => actor_idle M a\n                     | None => False\n                   end\n  end\n.\n\nDefinition cfg_done (cfg : configuration) : Prop :=\n  match cfg with\n    | (M, H, _) => heap_done M H\n  end\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/Syntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.2967681312105448}}
{"text": "From Undecidability Require Import TM.Util.Prelim.\nFrom Undecidability Require Import TM.Util.TM_facts TM.Compound.MoveToSymbol.\n\nRequire Import ssrbool Lia.\nLemma last_not_default X (d d':X) A :\n  A <> [] -> last A d = last A d'.\nProof. induction A. easy. destruct A;cbn. easy. intros ?. now apply IHA. Qed.\n\n\nLemma removelast_as_tail X (x:list X): removelast x = rev (tail (rev x)).\nProof.\n  rewrite tl_rev. symmetry. apply rev_involutive.\nQed.\n\nLocal Arguments removelast : simpl nomatch.\nLocal Arguments last : simpl nomatch.\n\n(** TIPP: Look in ./Copy.v **)\n(** I have no Idea anymore why i called this nicer ... *)\n\nDefinition MoveToSymbol_Rel_nice (sig':finType) (f:sig' -> bool) (g:sig' -> sig') t t' := \n  ((current t = None /\\ t = t')\n   \\/ (exists t__L c t__R1 t__R2,\n         t = midtape t__L c (t__R1++t__R2)\n         /\\ (forall x, x el (removelast (c::t__R1)) -> f x = false)\n         /\\ f (last (c::t__R1) c) = ssrbool.isSome (current t')\n         /\\ (t' = midtape (rev (map g (removelast (c::t__R1)))++t__L) (g (last (c::t__R1) c)) t__R2\n            \\/ (t' = rightof (g (last (c::t__R1) c)) (rev (map g (removelast (c::t__R1)))++t__L) /\\ t__R2 = [])))).\n\nLemma MoveToSymbol_Fun_nice (sig':finType) (f:sig' -> bool) (g:sig' -> sig') t t' :\n  MoveToSymbol_Fun f g t = t' <-> MoveToSymbol_Rel_nice f g t t'. \nProof.\n  remember (tape_local t) as A eqn:eqA.\n  revert t t' eqA. unfold MoveToSymbol_Rel_nice.\n  induction A using (size_induction (f:=@length sig'));intros t t' eqA.\n  rewrite MoveToSymbol_Fun_equation. destruct current eqn:eq.\n  2:{ split. now left. intros [ | H']. easy. destruct H' as (?&?&?&?&->&?). easy. }\n  destruct f eqn:Hf.\n  { destruct t;inv eq. all:cbn. split.\n    -intros <-. right. eexists _,_,[],_.\n     repeat split;eauto.\n     intros x Hx. destruct Hx.\n    -intros [ | (t__L&c&t__R1&t__R2&[= -> -> -> ]&Hfalse&Hc&H'')];[ easy | ].\n     destruct t__R1 as [ | c__R t__R1].\n     2:{exfalso. cbn in *. rewrite Hfalse in Hf;auto. }\n     cbn in *. \n     destruct H'' as [-> | [-> -> ]]. all:cbn in *;now eauto + congruence.\n  }\n  destruct t. all:inv eq. destruct l0. all:cbn - [removelast].\n  all:rewrite H;[ | | reflexivity];[cbn | cbn;nia].\n  - cbn. split.\n    +intros [(_&<-)| (?&?&?&?&[=]&?)];[]. right.\n     eexists _,_,[],[]. split;[reflexivity| ]. split;[easy| ]. unfold last, removelast;cbn. eauto. \n    +intros [([=]&?)|(t__L&c&t__R1&t__R2&[= <- <- H__nil]&Hfalse&Hc&H'')];[].\n     destruct t__R1;[ |now inv H__nil]. destruct t__R2;[ |now inv H__nil]. clear H__nil.\n     cbn in H''|-*. destruct H'' as [-> | [-> _ ]]. 2:now left. now unfold last in Hc;cbn in Hc;congruence.\n  -eapply Morphisms_Prop.or_iff_morphism. easy.\n   split. all:intros (t__L&c&t__R1&t__R2&Heq&Hfalse&Hc&H');revert Heq.\n   +intros [= <- -> ->]. eexists _,_,(_::_),_. split. reflexivity.\n    cbn. split. now intros ? [-> | ];eauto.\n    autorewrite with list in |-*;cbn. erewrite last_not_default. split;now eauto. easy.\n   +intros [= -> -> Heq]. destruct t__R1.\n    {cbn in *. destruct H' as [ -> | [-> ->]]. all: now cbn in *;congruence. }\n    revert Heq;intros [= -> ->].\n    eexists (_::_),_,_,_. split. reflexivity. cbn in *.\n    split. now eauto. autorewrite with list in H';cbn. erewrite last_not_default. 2:easy. split;now eauto.\nQed.\n\nLemma MoveToSymbol_Fun_is_rel (sig':finType) (f:sig' -> bool) (g:sig' -> sig') t :\n  MoveToSymbol_Rel_nice f g t (MoveToSymbol_Fun f g t).\nProof.\n  now rewrite <- MoveToSymbol_Fun_nice.\nQed.\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/TM/Compound/MoveToSymbol_niceSpec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.5039061705290806, "lm_q1q2_score": 0.2967448740228882}}
{"text": "Require Import List.\nRequire Import Arith.\n\n(** * VM for \"Virtual Machine\" *)\n\nRequire Import CU.\nRequire Import FB.\nRequire Import Common.\n\nInductive code_pointer : Set :=\n| CP_user : nat -> code_pointer\n| CP_pap : nat -> code_pointer\n| CP_cons : constructor -> nat -> code_pointer.\n\nDefinition eq_cp_dec : forall c d : code_pointer, {c = d} + {c <> d}.\nProof.\nrepeat decide equality.\nDefined.\n\nInductive expr : Set :=\n| App : var -> vars -> CU.cleanup -> expr\n| Constr : constructor -> vars -> CU.cleanup -> expr\n| Letrec : list (vars * code_pointer) -> expr -> expr\n| Case : expr -> code_pointer -> expr.\n\nDefinition lambda_form := gen_lambda_form (Expr := expr).\n\nDefinition alt := gen_alt (Expr := code_pointer).\n\nDefinition alts := list alt.\n\nInductive cs_node : Set :=\n| CS_expr : expr -> cs_node\n| CS_alts : alts -> cs_node\n| CS_lf : lambda_form -> cs_node\n| CS_None.\n\nDefinition code_store := list (code_pointer * cs_node).\n\nFixpoint find_cs (cs : code_store) (cp : code_pointer) : cs_node :=\nmatch cs with\n| nil => CS_None\n| (cp0, node) :: cs0 => if eq_cp_dec cp cp0\n  then node\n  else find_cs cs0 cp\nend.\n\nDefinition closure := (code_pointer * addresses)%type.\n\nDefinition closures := list closure.\n\nDefinition heap := address -> option closure.\n\nInductive config : Set :=\n| Config : heap -> expr -> env -> (argstack * FB.fake_bottom)\n  -> address -> config\n| Enter : heap -> address -> argstack * FB.fake_bottom -> env -> config.\n\nInductive ret_value : Set :=\n| Val_con : heap -> constructor -> addresses -> ret_value\n| Val_pap : heap -> address -> addresses -> ret_value.\n\nDefinition value := (ret_value * env * (argstack * FB.fake_bottom))%type.\n\nNotation \" << a , b , c , d , e >> \" := (Config a b c d e) (at level 70).\nNotation \" << a , b , c , d >> \" := (Enter a b c d) (at level 70).\n\nInductive action : Set :=\n| E : config -> action\n| A : value -> action.\n\nInductive stack_elem : Set :=\n| K_alt : code_pointer -> FB.fake_bottom -> stack_elem\n| K_upd : address -> FB.fake_bottom -> stack_elem.\n\nDefinition stack := list stack_elem.\n\nDefinition look_up (e : env) (g : heap) (p : address) (v : var)\n  : option address :=\nmatch v with\n| B_ind n => nth n e \n| C_ind n => match g p with Some (_, clo) => nth n clo | None => None end\nend.\n\nFixpoint map_env (e : env) (g : heap) (a : address) (vs : vars) {struct vs}\n  : option addresses :=\nmatch vs with\n| nil => Some nil\n| x::xs =>\n  match map_env e g a xs with\n  | Some ps =>\n    match look_up e g a x with\n    | Some p => Some (p::ps)\n    | None => None\n    end\n  | None => None\n  end\nend.\n\nDefinition set (g : heap) (a : address) (clo : closure) : gen_heap :=\nfun (x : address) => if eq_nat_dec x a\n  then Some clo\n  else g x.\n\nDefinition alloc (g : heap) (addrs : addresses) (clos : list closure)\n  : heap :=\nfold_right (fun (ad : address * closure) (h : gen_heap) =>\n  set h (fst ad) (snd ad))\n  g (combine addrs clos).\n\nLemma set_eq :\nforall H s v,\n  set H s v s = Some v.\nProof with isa.\nintros.\nunfold set.\ndestruct (eq_nat_dec)...\ntauto.\nQed.\n\nLemma set_neq :\nforall H s v p\n  (NEQ : p <> s),\n  set H p v s = H s.\nProof with isa.\nintros.\nunfold set.\ndestruct eq_nat_dec...\nsymmetry in e.\nintuition.\nQed.\n\nLemma alloc_in :\nforall H vs v lfs lf\n  (LEN   : length vs = length lfs)\n  (IN    : In v vs)\n  (ALLOC : alloc H vs lfs v = Some lf),\n  In lf lfs.\nProof with isa.\ninduction vs...\ncontradiction.\ndestruct lfs; try discriminate...\ninversion LEN as [ LEN0 ].\ndestruct (eq_nat_dec a v).\n(* eq *)\nsubst...\nunfold alloc in *...\nrewrite set_eq in ALLOC.\ninversion ALLOC as [ ALLOC0 ]; subst; auto.\n(* neq *)\nunfold alloc in *...\nrewrite set_neq in ALLOC...\nright; eapply IHvs; eauto.\nfold (alloc H vs lfs) in ALLOC.\ninversion IN...\ncontradiction.\nQed.\n\nLemma alloc_nin :\nforall H vs p\n  (NIN : ~ In p vs)\n  lfs,\n  alloc H vs lfs p = H p.\nProof with isa.\ninduction vs.\ntrivial.\nassert (NOTIN : forall A p (x : A) xs,\n  ~ In p (x :: xs) -> p <> x /\\ ~ In p xs).\n  isa.\nintros.\napply NOTIN in NIN.\ndestruct NIN as [ NEQ NIN ].\ndestruct lfs...\nunfold alloc...\nrewrite set_neq...\nfold (alloc H vs lfs)...\nQed.\n\nLemma alloc_some :\nforall H a ats lfs\n  (LEN : length ats = length lfs)\n  (IN  : In a ats),\n  exists r, alloc H ats lfs a = Some r.\nProof with isa.\ninduction ats...\ncontradiction.\nunfold alloc in *.\ndestruct lfs; simpl in *; try discriminate.\nunfold set in *.\ndestruct (eq_nat_dec a a0); subst.\n(* eq *)\nexists c...\n(* neq *)\napply IHats.\ninversion LEN...\ndestruct IN...\ndestruct n...\nQed.\n\nDefinition make_closure (e : env) (g : heap) (p : address)\n  (cpvs : vars * code_pointer) : option closure :=\nmatch cpvs with\n| (vs, cp) =>\n  match map_env e g p vs with\n  | Some addrs => Some (cp, addrs)\n  | None => None\n  end\nend.\n\nFixpoint make_closures (e : env) (g : heap) (p : address)\n  (cps : list (vars * code_pointer)) {struct cps} : option closures:=\nmatch cps with\n| nil => Some nil\n| cp::cps0 =>\n  match make_closures e g p cps0 with\n  | Some clos =>\n    match make_closure e g p cp with\n    | Some clo => Some (clo::clos)\n    | None => None\n    end\n  | None => None\n  end\nend.\n\nReserved Notation \" cs @@ a ^\\ b \" (at level 70, no associativity).\n\nInductive Sem (cs : code_store) : (action * stack) -> value -> Prop :=\n\n| Halt : forall Value,\n  cs @@ (A Value, nil) ^\\ Value\n\n| Cons : forall Gamma C xs sigma addrs cleanup args fake_bot pclo Value K\n  (MAPENV  : map_env sigma Gamma pclo xs = Some addrs)\n  (ARGSNIL : fake_bot = length args)\n  (PREMISE : cs @@ (A (Val_con Gamma C addrs, (skipn cleanup sigma), (args, fake_bot)), K) ^\\ Value),\n  cs @@ (E (<< Gamma, Constr C xs (cleanup), sigma, (args, fake_bot), pclo >>), K) ^\\ Value\n\n| Accum : forall Gamma x xs sigma args p new_args Value cleanup fake_bot pclo K\n  (MAPENV  : map_env sigma Gamma pclo xs = Some new_args)\n  (LOOKUP  : look_up sigma Gamma pclo x = Some p)\n  (PREMISE : cs @@ (E (<< Gamma, p, (new_args++args, fake_bot), skipn cleanup sigma >>), K) ^\\ Value),\n  cs @@ (E (<< Gamma, App x xs (cleanup), sigma, (args, fake_bot), pclo >>), K) ^\\ Value\n\n| App1 : forall cp Gamma p args clovars bind e some_clo sigma fake_bot real_args fake_args Value K\n  (CS      : find_cs cs cp = CS_lf (Lf Dont_update clovars bind e))\n  (ONHEAP  : Gamma p = Some (cp, some_clo))\n  (REAL    : real_args = firstn (length args - fake_bot) args)\n  (FAKE    : fake_args = skipn (length args - fake_bot) args)\n  (LENGTH  : bind > length args - fake_bot)\n  (PREMISE : cs @@ (A (Val_pap Gamma p real_args, sigma, (fake_args, fake_bot)), K) ^\\ Value),\n  cs @@ (E (<< Gamma, p, (args, fake_bot), sigma >>), K) ^\\ Value \n\n| App2 : forall cp Gamma p args Value e bind clo clovars sigma fake_bot K\n  (CS      : find_cs cs cp = CS_lf (Lf Dont_update clovars bind e))\n  (ONHEAP  : Gamma p = Some (cp, clo))\n  (LENGTH  : bind <= length args - fake_bot)\n  (PREMISE : cs @@ (E (<< Gamma, e, firstn bind args ++ sigma, (skipn bind args, fake_bot), p >>), K) ^\\ Value),\n  cs @@ (E (<< Gamma, p, (args, fake_bot), sigma >>), K) ^\\ Value\n\n| App_Eval : forall cp Gamma p args Value e clovars clo_e sigma fake_bot K\n  (CS      : find_cs cs cp = CS_lf (Lf Update clovars 0 e))\n  (ONHEAP1 : Gamma p = Some (cp, clo_e))\n  (* NO CLOG !!! *)\n  (PREMISE : cs @@ (E (<< Gamma, e, sigma, (args, length args), p >>), K_upd p fake_bot :: K) ^\\ Value),\n  cs @@ (E (<< Gamma, p, (args, fake_bot), sigma >>), K) ^\\ Value\n\n| App3 : forall p C addrs Delta theta args fake_bot fake_bot_dummy K Value\n  (ARGSNIL : fake_bot = length args)\n  (PREMISE : cs @@ (A (Val_con (set Delta p (CP_cons C (length addrs), addrs)) C addrs, theta, (args, fake_bot)), K) ^\\ Value),\n  cs @@ (A (Val_con Delta C addrs, theta, (args, fake_bot)), K_upd p fake_bot_dummy :: K) ^\\ Value\n\n| App4 : forall p Value q addrs Delta theta args0 fake_bot fake_bot0 K\n  (PREMISE : cs @@ (E (<< set Delta p (CP_pap (length addrs), q :: addrs), q, (addrs++args0, fake_bot), theta >>), K) ^\\ Value),\n  cs @@ (A (Val_pap Delta q addrs, theta, (args0, fake_bot0)), K_upd p fake_bot :: K) ^\\ Value\n\n| Let : forall Gamma e lfs sigma closures Value addrs args pclo K\n  (LENGTH  : length addrs = length lfs)\n  (FRESH   : forall p : address, In p addrs -> Gamma p = None)\n  (CLOS    : make_closures (addrs++sigma) Gamma pclo lfs = Some closures)\n  (PREMISE : cs @@ (E (<< alloc Gamma addrs closures, e, addrs++sigma, args, pclo >>), K) ^\\ Value),\n  cs @@ (E (<< Gamma, Letrec lfs e, sigma, args, pclo >>), K) ^\\ Value\n\n| Case_of_Eval : forall Gamma e als sigma pclo Value args fake_bot K\n  (PREMISE : cs @@ (E (<< Gamma, e, sigma, (args, length args), pclo >>), K_alt als fake_bot :: K) ^\\ Value),\n  cs @@ (E (<< Gamma, Case e als, sigma, (args, fake_bot), pclo >>), K) ^\\ Value\n\n| Case_of_Apply : forall p_als als pclo Value bind Delta p_e0 e0 C addrs theta args0 fake_bot fake_bot0 K\n  (CS1     : find_cs cs p_als = CS_alts als)\n  (SELECT  : nth C als = Some (Alt bind p_e0))\n  (CS2     : find_cs cs p_e0 = CS_expr e0)\n  (PREMISE : cs @@ (E (<< Delta, e0, addrs++theta, (args0, fake_bot), pclo >>), K) ^\\ Value),\n  cs @@ (A (Val_con Delta C addrs, theta, (args0, fake_bot0)), K_alt p_als fake_bot :: K) ^\\ Value\n\nwhere \"cs @@ a ^\\ b \" := (Sem cs a b).\n\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/vm/src/VM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2967448740228881}}
{"text": "(**********************************************************************)\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 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(**********************************************************************)\n(*                Typed LambdaFactor Calculus                         *)\n(*                                                                    *)\n(* is implemented in Coq by adapting the implementation of            *) \n(* Lambda Calculus from Project Coq                                   *)\n(* 2015                                                               *)\n(**********************************************************************)\n\n(**********************************************************************)\n(*                        LamSF_Confluence.v                          *)\n(*                                                                    *)\n(* adapted from Confluence.v for Lambda Calculus                      *)\n(*                                                                    *)\n(*                          Barry Jay                                 *)\n(*                                                                    *)\n(**********************************************************************)\n\nRequire Import Arith.\nRequire Import Test.\nRequire Import General.\nRequire Import LamSF_Terms.\nRequire Import LamSF_Tactics.\nRequire Import Beta_Reduction.\nRequire Import LamSF_Redexes.\nRequire Import LamSF_Marks.\nRequire Import LamSF_Substitution.\nRequire Import LamSF_Residuals.\nRequire Import LamSF_Simulation.\nRequire Import LamSF_Cube. \n\n(* Confluence *)\n\nDefinition confluence (A : Set) (R : A -> A -> Prop) :=\n  forall x y : A,\n  R x y -> forall z : A, R x z -> exists u : A, R y u /\\ R z u.\n\n\n(***************************************)\n(* Parallel moves lemma and confluence *)\n(***************************************)\n\nLemma parallel_moves : confluence lamSF par_red1.\nProof.\n\nred in |- *; intros M N R1 P R2.\nelim (simulation M N); trivial with arith.\nelim (simulation M P); trivial with arith.\nintros V RV U RU.  \nelim (paving U V (mark M) (mark N) (mark P)); trivial with arith.\nintros UV C1; elim C1.\nintros VU C2; elim C2.\nintros UVW C3; elim C3; intros P1 P2.\nexists (unmark UVW); split.\nrewrite (inverse N).\napply completeness with VU; trivial with arith.\nrewrite (inverse P).\napply completeness with UV; trivial with arith.\n\n\nQed.\n\nLemma confluence_parallel_reduction : confluence lamSF par_red.\nProof.\nred.\neapply2 diamond_tiling.\neapply2 parallel_moves.\nQed.\n\n", "meta": {"author": "Barry-Jay", "repo": "typed-lambdaFactor", "sha": "80f5ccf75903e9cad68f9c405bca492df1d107ed", "save_path": "github-repos/coq/Barry-Jay-typed-lambdaFactor", "path": "github-repos/coq/Barry-Jay-typed-lambdaFactor/typed-lambdaFactor-80f5ccf75903e9cad68f9c405bca492df1d107ed/LamSF_Confluence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2967448740228881}}
{"text": "Require Export Qual.metalib.\nRequire Export Qual.tactics.\nRequire Export Qual.labels. \n\nSet Implicit Arguments.\nOpen Scope grade_scope.\n\n(* Helps with specializing the IH for weakening proofs. *)\nLocal Ltac weakening_ih := \n    match goal with \n    | [ H3 : forall P5 P4, [(?x, ?psi0)] ++ ?P2 ++ ?P1 = P4 ++ P5 -> _ |- _ ]\n     => specialize (H3 P1 (x ~ psi0 ++ P2) ltac:(eauto) ltac:(simpl_env;auto)); simpl_env in H3\n     end.\n\nLemma CGrade_Grade_weakening_middle : (forall P psi psi0 b,\n    CGrade P psi psi0 b -> forall P1 P2, P = P2 ++ P1 -> forall P3,\n     uniq (P2 ++ P3 ++ P1) \n    -> CGrade (P2 ++ P3 ++ P1) psi psi0 b) /\\ (forall P psi b,\n    Grade P psi b -> forall P1 P2, P = P2 ++ P1 -> forall P3,\n     uniq (P2 ++ P3 ++ P1) \n    -> Grade (P2 ++ P3 ++ P1) psi b).     \nProof.\n  eapply CGrade_Grade_mutual.\n  all: intros; eauto.\n  all: try solve [subst; eapply G_Var; eauto].\n\n  all: try solve \n        [subst; fresh_apply_Grade x; eauto;\n         repeat spec x;\n         weakening_ih;\n         eauto].\nQed. \n\nLemma Grade_weakening_middle : forall P1 P2 P3 psi b,\n    Grade (P2 ++ P1) psi b -> uniq (P2 ++ P3 ++ P1) \n    -> Grade (P2 ++ P3 ++ P1) psi b.     \nProof. \n  intros.   eapply CGrade_Grade_weakening_middle; eauto. Qed.\n\nLemma Grade_weakening : forall P2 P1 psi b,\n    Grade P1 psi b\n    -> uniq (P2 ++ P1) \n    -> Grade (P2 ++ P1) psi b.     \nProof. \n  intros.\n  eapply CGrade_Grade_weakening_middle with (P2 := nil); simpl_env; eauto.\nQed.\n\nLtac geq_weakening_ih := \n    match goal with \n    | [ H3 : forall P3 P4, [(?x, ?psi0)] ++ ?P2 ++ ?P1 = P4 ++ P3 -> _ |- _ ]\n     => specialize (H3 P1 ([(x,psi0)] ++ P2) ltac:(eauto) _ ltac:(simpl_env;eauto)); simpl_env in H3\n     end.\n\nLemma CEq_GEq_weakening : \n  (forall P phi phi0 a b,\n  CEq P phi phi0 a b -> forall P1 P2, P = P2 ++ P1 -> forall P3, uniq (P2 ++ P3 ++ P1) -> CEq (P2 ++ P3 ++ P1) phi phi0 a b) /\\\n  (forall P phi a b,\n  GEq P phi a b -> forall P1 P2, P = P2 ++ P1 -> forall P3, uniq (P2 ++ P3 ++ P1) -> GEq (P2 ++ P3 ++ P1) phi a b).\nProof.\n  eapply CEq_GEq_mutual.\n  all: intros; eauto.\n  all: try solve [subst; eapply GEq_Var; eauto].\n  all: try solve [subst;\n    fresh_apply_GEq x; eauto;\n    repeat spec x;\n    geq_weakening_ih;\n    eauto].\nQed.\n\nLemma GEq_weakening_middle :  (forall P phi a b,\n  GEq P phi a b -> forall P1 P2, P = P2 ++ P1 -> forall P3, uniq (P2 ++ P3 ++ P1) -> GEq (P2 ++ P3 ++ P1) phi a b).\nProof.\n  destruct CEq_GEq_weakening.\n  auto.\nQed.\n\n\nLemma GEq_weakening : forall P phi b1 b2,\n  GEq P phi b1 b2 -> forall P2, uniq (P2 ++ P) -> GEq (P2 ++ P) phi b1 b2. \nProof.\n  destruct CEq_GEq_weakening.\n  intros.\n  eapply H0 with (P2 := nil); eauto.\nQed.\n\nLemma CDefEq_DefEq_weakening_middle : \n  (forall P phi psi a b,\n  CDefEq P phi psi a b -> forall P1 P2, P = P2 ++ P1 -> forall P3, uniq (P2 ++ P3 ++ P1) -> CDefEq (P2 ++ P3 ++ P1) phi psi a b) /\\\n  (forall P phi a b,\n  DefEq P phi a b -> forall P1 P2, P = P2 ++ P1 -> forall P3, uniq (P2 ++ P3 ++ P1) -> DefEq (P2 ++ P3 ++ P1) phi a b).\nProof.\n  apply CDefEq_DefEq_mutual.\n  all: intros; subst; eauto 3 using Grade_weakening_middle.\n  all: try solve [subst;\n    fresh_apply_DefEq x; auto;\n    repeat spec x;\n    geq_weakening_ih;\n    eauto].\n  all: try solve [\n             pick fresh x and apply Eq_SubstIrrel; eauto 2;\n             repeat spec x;\n             geq_weakening_ih;\n             eauto].\n\n  all: eauto 4 using Grade_weakening_middle.\n  all: try (eapply Eq_Case; eauto 3 using Grade_weakening_middle).\nQed.\n\nLemma DefEq_weakening_middle : \n  (forall P phi a b,\n  DefEq P phi a b -> forall P1 P2, P = P2 ++ P1 -> forall P3, uniq (P2 ++ P3 ++ P1) -> DefEq (P2 ++ P3 ++ P1) phi a b).\nProof. \n  intros.\n  eapply CDefEq_DefEq_weakening_middle; eauto.\nQed.\n\nLemma DefEq_weakening : forall P phi b1 b2,\n  DefEq P phi b1 b2 -> forall P2, uniq (P2 ++ P) -> DefEq (P2 ++ P) phi b1 b2. \nProof.\n  intros.\n  eapply CDefEq_DefEq_weakening_middle with (P2 := nil); eauto.\nQed.\n\nLemma CPar_Par_weakening_middle :\n  (forall G0 psi psi0 a b, CPar G0 psi psi0 a b ->\n  forall E F G, (G0 = F ++ G) -> uniq (F ++ E ++ G) ->  CPar (F ++ E ++ G) psi psi0 a b) /\\\n  (forall G0 psi a b, Par G0 psi a b ->\n  forall E F G, (G0 = F ++ G) -> uniq (F ++ E ++ G) ->  Par (F ++ E ++ G) psi a b).\nProof.\n  apply CPar_Par_mutual.\n  all: intros; subst; eauto 3 using Grade_weakening_middle.\n  all: try solve [\n  subst; fresh_apply_Par x; auto; repeat spec x;\n  match goal with \n  | [ H3 : forall E F0 G0, [(?x, ?psi0)] ++ ?F ++ ?G = F0 ++ G0 -> _ |- _ ]\n    =>  specialize (H3 E ([(x,psi0)] ++ F) G ltac:(simpl_env;eauto) ltac:(simpl_env;eauto)) ;\n  simpl_env in H3 end; eauto].\n\n  all: eauto 5 using Grade_weakening_middle.\nQed.\n\nLemma Par_weakening_middle :\n  forall G0 a psi b, Par G0 psi a b ->\n  forall E F G, (G0 = F ++ G) -> uniq (F ++ E ++ G) ->  Par (F ++ E ++ G) psi a b.\nProof. \n  intros. eapply CPar_Par_weakening_middle; eauto.\nQed.\n\n\nLemma Par_weakening :\n  forall G a psi b, Par G psi a b ->\n  forall E, uniq (E ++ G) ->  Par (E ++ G) psi a b.\nProof.\n  intros. eapply Par_weakening_middle with (F := nil); eauto.\nQed.\n\n\nLemma Typing_weakening_middle : forall W2 W1 q b B, \n    Typing (W2 ++ W1) q b B ->\n    forall W, uniq (W2 ++ W ++ W1) ->\n    Typing (W2 ++ W ++ W1) q b B.\nProof.\n  intros W2 W1 q b B h. dependent induction h.\n  all: intros; subst; eauto 3 using DefEq_weakening_middle.\n  all: have UL1: uniq (meet_ctx_l q_C W2 ++ meet_ctx_l q_C W ++ meet_ctx_l q_C W1) by\n    unfold meet_ctx_l; solve_uniq.\n  all: have UL2: uniq (labels (meet_ctx_l q_C W2) ++ labels (meet_ctx_l q_C W) ++ labels (meet_ctx_l q_C W1)) by\n   unfold labels; solve_uniq.\n  (* easy cases *)\n  all: try solve [eapply T_App; eauto].\n  all: try solve [\n             eapply T_AppIrrel; simpl_env; eauto;\n             eapply IHh2; simpl_env; eauto].\n  all: try solve [\n             eapply T_WPair; simpl_env; eauto;\n             eapply IHh1; simpl_env; eauto].\n  all: try solve [\n             eapply T_WPairIrrel; simpl_env; eauto;\n             try eapply IHh1; simpl_env; eauto;\n             try eapply IHh2; simpl_env; eauto].\n  all: try solve [\n             eapply T_SPair; simpl_env; eauto;\n             try eapply IHh1; simpl_env; eauto;\n             try eapply IHh2; simpl_env; eauto].\n  all: try solve [\n             apply T_Sum; simpl_env; eauto;\n             try eapply IHh1; simpl_env; eauto;\n             try eapply IHh2; simpl_env; eauto].\n  all: try solve [\n             eapply T_Inj1; simpl_env; eauto;\n             eapply IHh2; simpl_env; eauto].\n  all: try solve [\n             eapply T_Inj2; simpl_env; eauto;\n             eapply IHh2; simpl_env; eauto].\n  all: try solve [eapply T_Eq; simpl_env; eauto].\n  \n  (* conversion *)\n  all: try match goal with [ H : DefEq _ _ _ _ |- _ ] => \n                  eapply T_Conv; eauto 3;\n                    simpl_env in *;\n                    try eapply DefEq_weakening_middle; eauto end.\n\n  (* pi *)\n  subst; fresh_apply_Typing x; eauto 1; auto; repeat spec x;\n  match goal with \n  | [ H2 : forall F0 G0, [(?x, ?psi0)] ++ ?F ++ ?G ~= F0 ++ G0 -> _ |- _ ]\n    => specialize (H2 ([(x,psi0)] ++ F) G ltac:(simpl_env;eauto 3));\n  simpl_env in H2; eauto 3; try eapply H2; try solve_uniq end.\n\n  (* abs *)\n  subst; fresh_apply_Typing x; simpl_env; try eapply IHh; simpl_env; eauto; repeat spec x;\n  try match goal with \n  | [ H3 : forall F0 G0, [(?x, ?psi0)] ++ ?F ++ ?G ~= F0 ++ G0 -> _ |- _ ]\n    => specialize (H3 ([(x,psi0)] ++ F) G ltac:(simpl_env;eauto 3) W) ;\n  simpl_env in H3 ; eauto 3; try eapply H3 end. \n\n  (* wsigma *)\n  subst; fresh_apply_Typing x; eauto 1; auto; repeat spec x;\n  match goal with \n  | [ H3 : forall F0 G0, [(?x, ?psi0)] ++ ?F ++ ?G ~= F0 ++ G0 -> _ |- _ ]\n    => specialize (H3 ([(x,psi0)] ++ F) G ltac:(simpl_env;eauto 3)) ;\n  simpl_env in H3; eauto 3; try eapply H3; try solve_uniq end.\n\n  (* letpair *)\n  - subst; fresh_apply_Typing x.\n    + clear H H1 H2 IHh.\n    repeat spec x. simpl_env.\n    match goal with \n    | [ H3 : forall F0 G0, [(?x, ?psi0)] ++ meet_ctx_l q_C (?F ++ ?G) ~= F0 ++ G0 -> _ |- _ ] \n      => specialize (H3 ([(x,psi0)] ++ meet_ctx_l q_C F) (meet_ctx_l q_C G) ltac:(simpl_env;eauto 3) (meet_ctx_l q_C W));\n          simpl_env in H3; eapply H3 end.\n    eapply uniq_cons_3; auto. repeat rewrite dom_app. repeat rewrite dom_meet_ctx_l. auto.\n    + eapply IHh; auto.\n    + move => y Fry.\n      clear H H0 H1 IHh.\n      spec x. spec y.\n      specialize (H0 ([(x, (psi0 * psi,A))] ++ W2) W1 ltac:(simpl_env; auto) W).\n      simpl_env in H0. eapply H0. solve_uniq.\n\n  (* ssigma *)\n  - subst; fresh_apply_Typing x; eauto 1; auto; repeat spec x;\n      match goal with \n      | [ H3 : forall F0 G0, [(?x, ?psi0)] ++ ?F ++ ?G ~= F0 ++ G0 -> _ |- _ ]\n        => specialize (H3 ([(x,psi0)] ++ F) G ltac:(simpl_env;eauto 3)) ;\n            simpl_env in H3; eauto 3; try eapply H3; try solve_uniq end.\n  - (* case *) \n    fresh_apply_Typing x; auto.\n    repeat spec x.\n    simpl_env.\n    match goal with \n    | [ H3 : forall F0 G0, [(?x, ?psi0)] ++ meet_ctx_l q_C (?F ++ ?G) ~= F0 ++ G0 -> _ |- _ ]\n      => specialize (H3 ([(x,psi0)] ++ meet_ctx_l q_C F) (meet_ctx_l q_C G) ltac:(simpl_env;eauto 3)\n                   (meet_ctx_l q_C W));\n          simpl_env in H3 ; eapply H3 end.\n    eapply uniq_cons_3; auto. repeat rewrite dom_app. repeat rewrite dom_meet_ctx_l. auto.\nQed.    \n\nLemma Typing_weakening : forall W1 q b B, \n    Typing W1 q b B ->\n    forall W2, uniq (W2 ++ W1) -> \n    Typing (W2 ++ W1) q b B.\nProof. \n  intros.\n  eapply Typing_weakening_middle with (W2 := nil); simpl_env; eauto.\nQed.\n\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/DDC/src/weakening.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.29674486675141715}}
{"text": "Require Import Common.Definitions.\nRequire Import Common.Values.\nRequire Import Source.CS.\nRequire Import Source.GlobalEnv.\n\nRequire Export Source.Language.\nRequire Export Extraction.Definitions.\n\nImport Source.\n\nDefinition run (p: program) (fuel: nat) :=\n  let G := prepare_global_env p in\n  let st := CS.initial_machine_state p in\n  match CS.execN fuel G st with\n  | Some [CState _, _, _, _, E_exit, _] => print_explicit_exit tt\n  | Some [CState _, _, _, _, E_val (Int n), _] => print_ocaml_int (z2int n)\n  | _ => print_error ocaml_int_0\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/Source/Examples/Helper.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5888891163376236, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2967448594799461}}
{"text": "\n(* First a simplification of the bug *)\n\nSet Printing Universes.\n\nInductive enc (A:Type (*1*)) (* : Type.1 *) := C : A -> enc A.\n\nDefinition id (X:Type(*5*)) (x:X) := x.\n\nLemma test : let S := Type(*6 : 7*) in enc S -> S.\nsimpl; intros.\napply enc.\napply id.\napply Prop.\nDefined.\n\n(* Then the original bug *)\n\nRequire Import List.\n\nInductive a : Set := (* some dummy inductive *)\nb : (list a) -> a.   (* i don't know if this *)\n                     (* happens for smaller  *)\n                     (* ones                 *)\n\nInductive sg : Type := Sg. (* single *)\n\nDefinition ipl2 (P : a -> Type) :=   (* in Prop, that means P is true forall *)\nfold_right (fun x => prod (P x)) sg. (* the elements of a given list         *)\n\nDefinition ind\n     : forall S : a -> Type,\n       (forall ls : list a, ipl2 S ls -> S (b ls)) -> forall s : a, S s :=\nfun (S : a -> Type)\n  (X : forall ls : list a, ipl2 S ls -> S (b ls)) =>\nfix ind2 (s : a) :=\nmatch s as a return (S a) with\n| b l =>\n    X l\n      (list_rect (fun l0 : list a => ipl2 S l0) Sg\n         (fun (a0 : a) (l0 : list a) (IHl : ipl2 S l0) =>\n          pair (ind2 a0) IHl) l)\nend. (* some induction principle *)\n\nImplicit Arguments ind [S].\n\nLemma k : a -> Type. (* some ininteresting lemma *)\nintro;pattern H;apply ind;intros.\n  assert (K : Type).\n    induction ls.\n      exact sg.\n      exact sg.\n  exact (prod K sg).\nDefined.\n\nLemma k' : a -> Type. (* same lemma but with our bug *)\nintro;pattern H;apply ind;intros.\n  apply prod.\n    induction ls.\n      exact sg.\n      exact sg.\n    exact sg. (* Proof complete *)\nDefined. (* bug *)\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/test-suite/bugs/closed/shouldsucceed/1951.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.29671184270086887}}
{"text": "Require Import RGref.DSL.Core.\n\n(** * Helpful Constants, Lemmas, and Proof Tactics *)\n(** ** General stufff *)\nDefinition any {A:Set} : hpred A := fun _ => fun _ => True.\n\nLemma stable_any : forall (A:Set) (R:hrel A), stable any R.\nProof.\n  intros; compute; eauto.\nQed.\nHint Resolve stable_any.\nLemma precise_any : forall (A:Set){RA:ImmediateReachability A}, @precise_pred A RA any.\nProof.\n  intros; compute; eauto.\nQed.\nHint Resolve precise_any.\nLemma any_true : forall (A:Set) (a:A) h, any a h.\nProof. compute; auto. Qed.\nHint Resolve any_true.\n\nDefinition havoc {A:Set} : hrel A := fun _ => fun _ => fun _ => fun _ => True.\nLemma precise_havoc : forall (A:Set)`{ImmediateReachability A}, precise_rel (@havoc A).\nProof. intros; compute; eauto. Qed.\nHint Resolve precise_havoc.\nLemma havoc_true : forall (A:Set) (a a':A) h h', havoc a a' h h'.\nProof. intros; compute; auto. Qed.\nHint Resolve havoc_true.\nLemma havoc_refl : forall (A:Set), hreflexive (@havoc A).\nProof. compute; eauto. Qed.\nHint Resolve havoc_refl.\n\nDefinition empty {A:Set} : hrel A := fun _ => fun _ => fun _ => fun _ => False.\nDefinition locally_const {A:Set} (R:hrel A) := forall a a' h h', R a a' h h' -> a=a'.\n\nLemma stable_empty : forall (A:Set) (P:hpred A), stable P empty.\nProof.\n  compute; intuition.\nQed.\nHint Resolve stable_empty.\nLemma precise_empty : forall (A:Set)`{ImmediateReachability A}, precise_rel empty.\nProof. intros; compute; eauto. Qed.\nHint Resolve precise_empty.\n\nDefinition local_imm {A:Set} : hrel A := fun a => fun a' => fun _ => fun _ => a=a'.\nLemma local_imm_const : forall A, locally_const (@local_imm A).\nProof. intros; firstorder. Qed.\nHint Resolve local_imm_const.\nLemma local_imm_precise : forall (T:Set)`{ImmediateReachability T}, precise_rel (@local_imm T).\nProof.\n  red; intros. induction H2. red. reflexivity.\nQed.\nHint Resolve local_imm_precise.\nLemma local_imm_refl : forall (T:Set), @hreflexive T local_imm.\nProof.\n  compute; eauto.\nQed.\nHint Resolve local_imm_refl.\nAxiom immutable_vals :\n  forall T P h h' (r:ref{T|P}[local_imm,local_imm]), h[r]=h'[r].\n\n\n(** We can always read when we have only one writable ref *)\nGlobal Instance strong_read (T:Set) : readable_at T local_imm havoc :=\n  { res := T ;\n    dofold := fun x => x\n  }.\n(** And we can always read when the guarantee is strictly local *)\nGlobal Instance weak_read (T:Set) : readable_at T local_imm local_imm :=\n  { res := T ;\n    dofold := fun x => x\n  }.\n(** I'm torn about providing this, but it's a common enough pattern (it is\n    the common case that types are only read at one R/G) that\n    we should(?) make it easy as a matter of library design...*)\nDefinition id_fold {T:Set}{R G:hrel T} : readable_at T R G :=\n  Build_readable_at T R G T (fun x => x).\n\nDefinition heap_agnostic_pred {A:Set} (P:hpred A) := forall a h h', P a h -> P a h'.\nDefinition heap_agnostic_rel {A:Set} (R:hrel A) := forall a a' h h' h'' h''', R a a' h h' -> R a a' h'' h'''.\n\nLemma agnostic_pred_stable : forall (A:Set) (P:hpred A), heap_agnostic_pred P -> stable P local_imm.\nProof.\n  compute. intros. subst; intuition; eauto.\nQed.\n\nHint Resolve agnostic_pred_stable.\n\n(** *** Option types *)\nInductive optset (A:Set) : hrel (option A) :=\n  | optset_nop : forall (o:option A) h h', optset A o o h h'\n  | optset_set : forall (a:A) h h', optset A None (Some a) h h'.\nInductive option_reach : forall (A:Set)`(ImmediateReachability A) {T:Set}{P R G} (p:ref{T|P}[R,G]) (ao:option A), Prop :=\n  | opt_reach_some : forall (A:Set)(a:A)`(ImmediateReachability A) {T:Set}{P R G} (p:ref{T|P}[R,G]),\n                         imm_reachable_from_in p a ->\n                         option_reach A _ p (Some a).\nGlobal Instance reach_option {A:Set}`{ImmediateReachability A} : ImmediateReachability (option A) :=\n  { imm_reachable_from_in := fun T P R G p oa => option_reach A _ p oa }.\nLemma optset_precise : forall A `(ImmediateReachability A), precise_rel (optset A).\nProof. compute. intros. inversion H2; subst; constructor. Qed.\nHint Resolve optset_precise.\n(* TODO: Contains instance for options *)\nGlobal Instance option_fold {A:Set}`{rel_fold A} : rel_fold (option A) :=\n  { rgfold := fun R G => option (rgfold havoc (fun a a' h h' => G (Some a) (Some a') h h')) ;\n    fold := fun R G o => match o with None => None | Some o' => Some (fold o') end\n  }.\nLemma optset_refl : forall (A:Set), hreflexive (optset A).\nProof. compute; intuition; constructor. Qed.\nHint Resolve optset_refl.\nInductive opt_contains {A:Set}`{Containment A} : hrel (option A) -> Prop :=\n  | some_contains : forall RR (h h':heap),\n                      contains (fun a a' h h' => RR (Some a) (Some a') h h') ->\n                      opt_contains RR.\nGlobal Instance option_contains {A:Set}`{Containment A} : Containment (option A) :=\n  { contains := opt_contains }.\n\n(** ** Combinator Lemmas *)\n\nLemma pred_and_stable : forall (A:Set) (P:hpred A) Q R, stable P R -> stable Q R -> stable (P ⊓ Q) R.\nProof. intros; firstorder. Qed.\nLemma pred_or_stable : forall (A:Set) (P Q:hpred A) R, stable P R -> stable Q R -> stable (P ⊔ Q) R.\nProof. intros; firstorder. Qed.\nLemma rel_and_stable : forall (A:Set) (P:hpred A) R S, stable P R -> stable P S -> stable P (R ⋂ S).\nProof. intros; firstorder. Qed.\nLemma rel_or_stable : forall (A:Set) (P:hpred A) R S, stable P R -> stable P S -> stable P (R ⋃ S).\nProof. intros; firstorder. Qed.\nLemma pred_and_precise : forall (A:Set){RA:ImmediateReachability A}(P Q:hpred A), precise_pred P -> precise_pred Q -> precise_pred (P ⊓ Q).\nProof. intros; firstorder. Qed.\nLemma pred_or_precise : forall (A:Set){RA:ImmediateReachability A}(P Q:hpred A), precise_pred P -> precise_pred Q -> precise_pred (P ⊔ Q).\nProof. intros; firstorder. Qed.\nLemma rel_and_precise : forall (A:Set){RA:ImmediateReachability A}(R S:hrel A), precise_rel R -> precise_rel S -> precise_rel (R ⋂ S).\nProof. intros. compute[precise_rel rel_and] in *. intuition. eauto. eauto. Qed.\nLemma rel_or_precise : forall (A:Set){RA:ImmediateReachability A}(R S:hrel A), precise_rel R -> precise_rel S -> precise_rel (R ⋃ S).\nProof. intros. compute[precise_rel rel_or] in *. intuition. eauto. eauto. Qed.\nRequire Import Coq.Classes.RelationClasses.\nGlobal Instance rel_sub_eq_preorder `{A:Set} : PreOrder (@rel_sub_eq A).\nProof. constructor. firstorder. firstorder. Qed.\nGlobal Instance pred_sub_eq_preorder `{A:Set} : PreOrder (@pred_sub_eq A).\nProof. constructor; firstorder. Qed.\n\nLemma pred_sub_refl : forall T (P:hpred T), P⊑P.\nProof.\n  reflexivity.\nQed.\nHint Resolve pred_sub_refl.\n\nLemma rel_sub_refl : forall T (R:hrel T), R⊆R.\nProof.\n  reflexivity.\nQed.\nHint Resolve rel_sub_refl.\n\n(** Also need to be able to pull results out of conjunctions *)\nLemma pred_and_proj1 : forall (A:Set) P Q (a:A) (h:heap), (P ⊓ Q) a h -> P a h.\nProof. firstorder. Qed.\nLemma pred_and_proj2 : forall (A:Set) P Q (a:A) (h:heap), (P ⊓ Q) a h -> Q a h.\nProof. firstorder. Qed.\n\nHint Resolve pred_and_stable rel_and_stable pred_and_precise rel_and_precise.\nHint Resolve pred_or_stable rel_or_stable pred_or_precise rel_or_precise.\n", "meta": {"author": "csgordon", "repo": "rgref-concurrent", "sha": "06091e1eb67c90682be7686020fb3a30233f21ec", "save_path": "github-repos/coq/csgordon-rgref-concurrent", "path": "github-repos/coq/csgordon-rgref-concurrent/rgref-concurrent-06091e1eb67c90682be7686020fb3a30233f21ec/RGref/DSL/Theories.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.2967118357622338}}
{"text": "From iris.algebra Require Import gmap agree auth.\nFrom iris.proofmode Require Import tactics.\nFrom cap_machine Require Export stdpp_extra iris_extra multiple_updates region.\nFrom cap_machine.binary_model Require Export region_invariants_binary region_invariants_transitions_binary logrel_binary.\nImport uPred.\n\nSection heap.\n  Context {Σ:gFunctors} {memg:memG Σ} {regg:regG Σ}\n          {stsg : STSG Addr region_type Σ} {heapg : heapG Σ}\n          {nainv: logrel_na_invs Σ} {cfgg : cfgSG Σ}\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  (* --------------------------------------------------------------------------------------------------------- *)\n  (* ------------------------------------------ UNINITIALIZATION --------------------------------------------- *)\n  (* --------------------------------------------------------------------------------------------------------- *)\n\n  (*\n     Full uninitialization turns every temporary/monotemporary\n     location state to uninitialized.\n     Unlike revocation, it is only required to uninitialize\n     all addresses above some chosen address a\n   *)\n\n  (* Uninitializing only changes the states of the standard STS collection *)\n  (* A weaker revocation which only revokes elements from a list *)\n  Definition u_merge_op (wo : option (Word * Word)) (ro : option region_type) : option region_type :=\n    match wo,ro with\n    | Some w, Some r => match r with\n                       | Monotemporary => Some (Uninitialized w)\n                       | _ => Some r\n                       end\n    | _, Some r => Some r\n    |_, None => None\n    end.\n\n  Definition uninitialize_std_sta (m : gmap Addr (Word * Word)) : STS_STD → STS_STD :=\n    merge u_merge_op m.\n\n  Definition uninitialize W m : WORLD := (uninitialize_std_sta m (std W),loc W).\n\n  Global Instance diag_none_u_merge_op : DiagNone u_merge_op.\n  Proof. by rewrite /u_merge_op /DiagNone /=. Qed.\n\n  Lemma uninitialize_std_sta_empty fs :\n    uninitialize_std_sta ∅ fs = fs.\n  Proof.\n    rewrite map_eq_iff. intros a.\n    rewrite /uninitialize_std_sta.\n    rewrite lookup_merge lookup_empty /=.\n    destruct (fs !! a) eqn:Hsome;rewrite Hsome;auto.\n  Qed.\n\n  Lemma uninitialize_empty W :\n    uninitialize W ∅ = W.\n  Proof.\n    rewrite /uninitialize uninitialize_std_sta_empty.\n    destruct W;auto.\n  Qed.\n\n  Definition uninitialize_i j w :=\n    match j with\n    | Monotemporary => Uninitialized w\n    | _ => j\n    end.\n\n  Lemma uninitialize_std_sta_spec (m : gmap Addr (Word * Word)) :\n    forall (Wstd_sta : STS_STD) (i : Addr),\n      (uninitialize_std_sta m Wstd_sta) !! i = match Wstd_sta !! i with\n                                              | None => None\n                                              | Some j => Some (match m !! i with\n                                                               | Some w => uninitialize_i j w\n                                                               | None => j\n                                                               end)\n                                              end.\n  Proof.\n    induction m using map_ind; intros.\n    - rewrite uninitialize_std_sta_empty.\n      destruct (Wstd_sta !! i) eqn:Hsome;auto.\n    - destruct (decide (i = i0));subst.\n      + simplify_map_eq.\n        rewrite lookup_merge.\n        destruct (Wstd_sta !! i0) eqn:Hsome.\n        * simplify_map_eq. destruct r; auto.\n        * simplify_map_eq. auto.\n      + simplify_map_eq.\n        rewrite lookup_merge. rewrite lookup_insert_ne//.\n        specialize (IHm Wstd_sta i0). by rewrite lookup_merge in IHm.\n  Qed.\n\n  Lemma uninitialize_std_sta_None_lookup i l m :\n    l !! i = None →\n    (uninitialize_std_sta l m) !! i = m !! i.\n  Proof.\n    intros Hnin.\n    rewrite lookup_merge Hnin.\n    simpl; destruct (m !! i) eqn:Hsome;rewrite Hsome;auto.\n  Qed.\n\n  Lemma uninitialize_std_sta_not_elem_of_lookup i l m :\n    i ∉ dom (gset Addr) l →\n    (uninitialize_std_sta l m) !! i = m !! i.\n  Proof.\n    intros Hnin. apply not_elem_of_dom in Hnin.\n    apply uninitialize_std_sta_None_lookup;auto.\n  Qed.\n\n  Lemma uninitialize_std_sta_is_Some i l m :\n    is_Some (m !! i) <->\n    is_Some ((uninitialize_std_sta l m) !! i).\n  Proof.\n    split; intros Hsome; destruct Hsome as [x Hx].\n    rewrite lookup_merge Hx.\n    destruct (l !! i);simpl;destruct x;eauto.\n    rewrite lookup_merge in Hx.\n    destruct (m !! i) eqn:Hsome;eauto.\n    rewrite Hsome /= in Hx.\n    destruct (l !! i);simpl in Hx; inversion Hx.\n  Qed.\n\n  Lemma uninitialize_dom W m :\n    dom (gset Addr) (uninitialize W m).1 = dom (gset Addr) W.1.\n  Proof.\n    apply set_equiv_spec_L. split.\n    - apply elem_of_subseteq. intros x Hx.\n      apply elem_of_gmap_dom in Hx as [y Hx].\n      apply elem_of_gmap_dom. eapply (uninitialize_std_sta_is_Some _ m). eauto.\n    - apply elem_of_subseteq. intros x Hx.\n      apply elem_of_gmap_dom. rewrite -(uninitialize_std_sta_is_Some _ m).\n      apply elem_of_gmap_dom. auto.\n  Qed.\n\n  Lemma uninitialize_std_sta_insert fs m w a :\n    fs !! a = Some Monotemporary →\n    <[a:=Uninitialized w]> (uninitialize_std_sta m fs) = uninitialize_std_sta (<[a:=w]> m) fs.\n  Proof.\n    intros Htemps.\n    apply map_eq'. intros k v;split.\n    - intros Ha. destruct (decide (k = a));subst;simplify_map_eq_alt.\n      + rewrite lookup_merge lookup_insert /=.\n        rewrite Htemps;auto.\n      + rewrite lookup_merge /=. rewrite /u_merge_op. simplify_map_eq.\n        destruct (m !! k) eqn:Hsome.\n        * destruct (fs !! k) eqn:Hsome';rewrite Hsome';[destruct r;auto|].\n          all: rewrite lookup_merge Hsome Hsome' /= in Ha;auto.\n        * rewrite lookup_merge Hsome /= in Ha;auto.\n    - intros Ha. destruct (decide (k = a));subst;simplify_map_eq_alt;simplify_eq.\n      + rewrite lookup_merge lookup_insert in Ha.\n        rewrite Htemps /= in Ha;auto. rewrite lookup_insert. auto.\n      + rewrite lookup_merge lookup_insert_ne// in Ha.\n        rewrite lookup_insert_ne//. rewrite lookup_merge. auto.\n  Qed.\n\n  Lemma uninitialize_std_sta_lookup_in i m (fs : STS_STD) (v : Word * Word) :\n    m !! i = Some v →\n    fs !! i = Some Monotemporary →\n    (uninitialize_std_sta m fs) !! i = Some (Uninitialized v).\n  Proof.\n    intros Hi Hsome.\n    rewrite lookup_merge Hi.\n    rewrite Hsome; auto.\n  Qed.\n\n  Lemma uninitialize_std_sta_singleton fs a v :\n    fs !! a = Some Monotemporary ->\n    uninitialize_std_sta {[a := v]} fs = <[a:=Uninitialized v]> fs.\n  Proof.\n    intros Hin.\n    apply map_eq'. intros k w. rewrite lookup_merge.\n    destruct (decide (a = k));subst;simplify_map_eq;simplify_map_eq_alt;auto.\n    rewrite lookup_insert;auto.\n    destruct (fs !! k) eqn:Hsome;auto;rewrite lookup_insert_ne//;rewrite Hsome//.\n  Qed.\n\n  Lemma uninitialize_related_pub_a W m a :\n    (∀ a' : Addr, is_Some (m !! a') ↔ (W.1 !! a' = Some Monotemporary) ∧ (a <= a')%a) →\n    related_sts_a_world W (uninitialize W m) a.\n  Proof.\n    intros Hcond.\n    split;[|apply related_sts_pub_plus_refl].\n    split.\n    - rewrite uninitialize_dom. done.\n    - intros i x y Hx Hy.\n      destruct (decide (le_a a i)).\n      + destruct (decide (x = Monotemporary)).\n        * assert (is_Some (m !! i)) as [v Hv].\n          { apply Hcond. split;auto. subst;auto. }\n          rewrite lookup_merge Hv Hx /= in Hy.\n          simplify_eq. eright;[|left]. right. constructor.\n        * assert ((m !! i) = None) as Hnone.\n          { apply eq_None_not_Some. intros Hcontr%Hcond. destruct Hcontr as [Hcontr _].\n            rewrite Hx in Hcontr; inversion Hcontr; congruence. }\n          rewrite lookup_merge Hnone Hx /= in Hy. simplify_eq. left.\n      + destruct (m !! i) eqn:Hsome.\n        2: { rewrite lookup_merge Hsome Hx /= in Hy. simplify_eq. left. }\n        destruct (decide (W.1 !! i = Some Monotemporary)).\n        2: { rewrite lookup_merge Hsome Hx /= in Hy. destruct x;simplify_eq;try contradiction;left. }\n        assert (is_Some (m !! i)) as Hcontr%Hcond;eauto. destruct Hcontr as [_ Hcontr].\n        solve_addr.\n  Qed.\n\n  (* ------------------------------------------------------------------------------------------------- *)\n  (* ------------------------ Binary versions of lemmas in the revocation file ----------------------- *)\n  (* ------------------------------------------------------------------------------------------------- *)\n\n  Lemma reg_get (γ : gname) (R : relT) (n : Addr) (r : leibnizO (gname)) :\n    own γ (● (to_agree <$> R : relUR)) ∧ ⌜R !! n = Some r⌝ ==∗\n    (own γ (● (to_agree <$> R : relUR)) ∗ own γ (◯ {[n := to_agree r]})).\n  Proof.\n    iIntros \"[HR #Hlookup]\".\n    iDestruct \"Hlookup\" as %Hlookup.\n    iApply own_op.\n    iApply (own_update with \"HR\").\n    apply auth_update_core_id; auto. apply gmap_core_id,agree_core_id.\n    apply singleton_included_l. exists (to_agree r). split; auto.\n    (* apply leibniz_equiv_iff in Hlookup.  *)\n    rewrite lookup_fmap. apply fmap_Some_equiv.\n    exists r. split; auto.\n  Qed.\n\n  Lemma region_rel_get (W : WORLD) (a : Addr) :\n    (std W) !! a = Some Monotemporary ->\n    region W ∗ sts_full_world W ==∗\n     region W ∗ sts_full_world W ∗ ∃ φ, ⌜forall Wv, Persistent (φ Wv)⌝ ∗ rel a φ.\n  Proof.\n    iIntros (Hlookup) \"[Hr Hsts]\".\n    rewrite region_eq /region_def.\n    iDestruct \"Hr\" as (M Mρ) \"(HM & #Hdom & #Hdom' & Hr)\".\n    iDestruct \"Hdom\" as %Hdom. iDestruct \"Hdom'\" as %Hdom'.\n    assert (is_Some (M !! a)) as [γp Hγp].\n    { apply elem_of_gmap_dom. rewrite -Hdom. apply elem_of_gmap_dom. eauto. }\n    rewrite RELS_eq /RELS_def.\n    iMod (reg_get with \"[$HM]\") as \"[HM Hrel]\";[eauto|].\n    (* rewrite /region_map_def. iDestruct (reg_in with \"[$HM $Hrel]\") as %HMeq. *)\n    iDestruct (big_sepM_delete _ _ a with \"Hr\") as \"[Hstate Hr]\";[eauto|].\n    iDestruct \"Hstate\" as (ρ Ha) \"[Hρ Hstate]\".\n    iDestruct (sts_full_state_std with \"Hsts Hρ\") as %Hx''.\n    all: rewrite Hlookup in Hx'';inversion Hx'';subst.\n    all: iDestruct \"Hstate\" as (φ Hpers) \"(#Hsaved & Ha)\".\n    all: iDestruct \"Ha\" as (v v') \"(Ha & Ha' & Hmono & #Hφ)\".\n    all: iDestruct (big_sepM_delete _ _ a with \"[Hρ Ha Ha' Hmono Hφ $Hr]\") as \"Hr\";[eauto| |].\n    { iExists Monotemporary. iFrame. iSplit;auto. iExists φ. iFrame \"∗ # %\". iExists _,_;iFrame. auto. }\n    all: iModIntro.\n    all: iSplitL \"HM Hr\".\n    { iExists M. iFrame. auto. }\n    all: iFrame; iExists φ; iSplit;auto; rewrite rel_eq /rel_def REL_eq /REL_def;iExists γp.\n    all: iFrame \"Hsaved Hrel\".\n  Qed.\n\n  (* ------------------------------------------------------------------------------------------------- *)\n  (* ------------------ A version of uninitialization where we remember the invariants --------------- *)\n  (* ------------------------------------------------------------------------------------------------- *)\n\n  Definition monotemp_pers_resources W φ a v1 v2 : iProp Σ :=\n    (future_pub_a_mono a φ v1 v2 ∗ φ (W,(v1,v2)))%I.\n\n  Lemma uninitialize_region_last_keep W E :\n    region W ∗ sts_full_world W ={E}=∗ ∃ m, ⌜((∃ (v v' : Word), {[addr_reg.top:=(v,v')]} = m) ↔ W.1 !! addr_reg.top = Some Monotemporary)\n                                             ∧ (∅ = m <-> W.1 !! addr_reg.top ≠ Some Monotemporary)⌝\n                                             ∗ region W ∗ sts_full_world (uninitialize W m)\n                                             ∗ □ ▷ ([∗ map] a↦w ∈ m, □ ∃ φ, ⌜forall Wv, Persistent (φ Wv)⌝ ∗ monotemp_pers_resources W φ a w.1 w.2 ∗ rel a φ).\n  Proof.\n    iIntros \"[Hr Hsts]\".\n    destruct (decide (W.1 !! addr_reg.top = Some Monotemporary)).\n    + iMod (region_rel_get with \"[$Hr $Hsts]\") as \"(Hr & Hsts & #Hrel)\";eauto.\n      iDestruct \"Hrel\" as (φ' Hpers') \"Hrel\".\n      rewrite region_eq /region_def.\n      iDestruct \"Hr\" as (M Mρ) \"(HM & #HM_dom & #HMρ_dom & Hmap)\".\n      iDestruct \"HM_dom\" as %HM_dom. iDestruct \"HMρ_dom\" as %HMρ_dom.\n      assert (is_Some (M !! addr_reg.top)) as [γp Hγp].\n      { apply elem_of_gmap_dom. rewrite -HM_dom. apply elem_of_gmap_dom. eauto. }\n      iDestruct (big_sepM_delete with \"Hmap\") as \"[Ha Hmap]\";[apply Hγp|].\n      iDestruct \"Ha\" as (ρ Hlookup) \"[Hstate Hresources]\".\n      iDestruct (sts_full_state_std with \"Hsts Hstate\") as %Hρ.\n      iDestruct \"Hresources\" as (φ Hpers) \"[#Hsaved Ha]\".\n      rewrite e in Hρ;inversion Hρ;subst ρ.\n      iDestruct \"Ha\" as (v1 v2) \"(Ha & Ha' & Hres)\".\n      iMod (sts_update_std _ _ _ (Uninitialized (v1,v2)) with \"Hsts Hstate\") as \"[Hsts Hstate]\".\n      iDestruct (region_map_delete_nonstatic with \"Hmap\") as \"Hmap\".\n      { intros m'. rewrite Hlookup. auto. }\n      iDestruct (region_map_insert_nonmonostatic (Uninitialized (v1,v2)) with \"Hmap\") as \"Hmap\";auto.\n      iDestruct (big_sepM_insert _ _ addr_reg.top with \"[$Hmap Ha Ha' Hstate]\") as \"Hmap\";[apply lookup_delete|..].\n      { iExists (Uninitialized _). rewrite lookup_insert. iSplit;auto. iFrame. iExists _. iSplit;eauto. }\n      rewrite insert_delete. rewrite (insert_id M);[|auto]. iModIntro.\n      iExists {[addr_reg.top:= _]}. rewrite /uninitialize uninitialize_std_sta_singleton// /=. iFrame.\n      iSplit;[iPureIntro|iSplit].\n      * split;split.\n        { intros;auto. }\n        { intros _. eexists;eauto. }\n        { intros Hcontr;inversion Hcontr. }\n        { intros Hcontr; contradiction. }\n      * iExists _,_. iFrame. iPureIntro. rewrite HM_dom -HMρ_dom. clear -Hlookup. split;auto.\n          assert (addr_reg.top ∈ dom (gset Addr) Mρ);[apply elem_of_gmap_dom;eauto|]. rewrite dom_insert_L. set_solver.\n      * rewrite rel_eq /rel_def REL_eq /REL_def RELS_eq /RELS_def. iDestruct \"Hrel\" as (γpred') \"[HREL Hsaved']\".\n        iDestruct (reg_in with \"[$HM $HREL]\") as %Hmeq. rewrite Hmeq lookup_insert in Hγp;inversion Hγp. simplify_eq.\n        iDestruct (saved_pred_agree _ _ _ (W,(v1,v2)) with \"Hsaved Hsaved'\") as \"Heq\".\n        iDestruct \"Hres\" as \"#Hres\". iModIntro.\n        rewrite big_sepM_singleton. iModIntro. iExists φ. iModIntro. iSplit;auto. \n    + iModIntro. iExists ∅. rewrite uninitialize_empty. iFrame. rewrite big_sepM_empty. iSplit;[|auto].\n      iPureIntro. split. split;intros;try contradiction. destruct H0. inversion H0. done.\n      split;intros;auto.\n  Qed.\n\n\n  Lemma uninitialize_region_states_keep W (a : Addr) (l : list Addr) E :\n    ⌜l = region_addrs a addr_reg.top ++ [addr_reg.top]⌝ -∗\n    region W ∗ sts_full_world W ={E}=∗\n    ∃ m, ⌜∀ (a' : Addr), is_Some(m !! a') ↔ ((W.1 !! a' = Some Monotemporary) ∧ (a' ∈ l)%a)⌝\n         ∗ region W ∗ sts_full_world (uninitialize W m)\n         ∗ □ ▷ ([∗ map] a↦w ∈ m, □ ∃ φ, ⌜forall Wv, Persistent (φ Wv)⌝ ∗ monotemp_pers_resources W φ a w.1 w.2 ∗ rel a φ).\n  Proof.\n    iIntros (Heq) \"(Hr & Hsts)\".\n    iInduction (l) as [|a' l] \"IH\" forall (a Heq).\n    { destruct (region_addrs a addr_reg.top); inversion Heq. }\n    destruct l.\n    - iMod (uninitialize_region_last_keep with \"[$Hr $Hsts]\") as (m [Hcond Hcond']) \"[Hr [Hsts #Hresources] ]\".\n      iExists m. iModIntro. iFrame \"∗ #\". iPureIntro. intros a0. split;intros Hc.\n      + destruct (region_addrs a addr_reg.top);[inversion Heq;subst|destruct l; inversion Heq].\n        destruct (decide (W.1 !! addr_reg.top = Some Monotemporary));[|exfalso]. assert (e':=e).\n        apply Hcond in e as [v [v' <-] ]. destruct Hc as [c Hc]. apply lookup_singleton_Some in Hc as [Heq1 Heq2];subst.\n        split;auto. constructor.\n        apply Hcond' in n. subst. rewrite lookup_empty in Hc. inversion Hc. done.\n      + destruct Hc as [Hc1 Hc2]. destruct (region_addrs a addr_reg.top);[inversion Heq;subst|destruct l; inversion Heq].\n        apply elem_of_list_singleton in Hc2. subst. apply Hcond in Hc1 as [v [v' <-] ]. eauto.\n    - assert ((a' + 1)%a = Some a0 ∧ (a' = a) ∧ (region_addrs a addr_reg.top = a :: region_addrs a0 addr_reg.top))\n        as [Hnext [Heqa Haddrs_cons ] ].\n      { assert (a < addr_reg.top)%a as Hlt.\n        { destruct (decide (a < addr_reg.top)%a);auto.\n          apply Znot_lt_ge in n. rewrite region_addrs_empty in Heq;[|solve_addr]. inversion Heq. }\n        assert (Heq':=Heq).\n        rewrite region_addrs_cons in Heq;auto. inversion Heq;subst.\n        assert ((a + 1)%a = Some a0) as  Ha''.\n        { destruct (a + 1)%a eqn:Hsome;[|solve_addr].\n          simpl in *. destruct (decide (a1 = addr_reg.top));subst;auto.\n          - rewrite region_addrs_empty in H2;[|solve_addr]. destruct l;inversion H2. auto.\n          - rewrite region_addrs_cons in Heq;[|solve_addr]. inversion Heq;auto. }\n        repeat split;auto. rewrite region_addrs_cons;auto. rewrite Ha''. auto. }\n      subst a'.\n      destruct (decide (W.1 !! a = Some Monotemporary)).\n      + iMod (region_rel_get with \"[$Hr $Hsts]\") as \"(Hr & Hsts & #Hrel)\";eauto.\n        iDestruct \"Hrel\" as (φ' Hpers') \"Hrel\".\n        iMod (\"IH\" $! a0 with \"[] Hr Hsts\") as (m Hmcond) \"[Hr [Hsts #Hres] ]\".\n        { rewrite region_addrs_cons in Heq;[|solve_addr]. rewrite Hnext in Heq. inversion Heq;auto. }\n        assert (m !! a = None) as Hnone.\n        { destruct (m!!a)eqn:Hsome';auto. assert (is_Some (m!!a)) as HisSome;eauto. apply Hmcond in HisSome as [Htemps Hin]. exfalso.\n          rewrite Haddrs_cons in Heq. inversion Heq. rewrite H1 in Hin. apply elem_of_app in Hin as [Hin | Heq'].\n          apply elem_of_region_addrs in Hin. solve_addr. apply elem_of_list_singleton in Heq';subst;solve_addr. }\n        rewrite region_eq /region_def.\n        iDestruct \"Hr\" as (M Mρ) \"(HM & #HM_dom & #HMρ_dom & Hmap)\".\n        iDestruct \"HM_dom\" as %HM_dom. iDestruct \"HMρ_dom\" as %HMρ_dom.\n        assert (is_Some (M !! a)) as [γp Hγp].\n        { apply elem_of_gmap_dom. rewrite -HM_dom. apply elem_of_gmap_dom. eauto. }\n        iDestruct (big_sepM_delete with \"Hmap\") as \"[Ha Hmap]\";[apply Hγp|].\n        iDestruct \"Ha\" as (ρ Hlookup) \"[Hstate Hresources]\".\n        iDestruct (sts_full_state_std with \"Hsts Hstate\") as %Hρ.\n        rewrite uninitialize_std_sta_None_lookup in Hρ;[|auto].\n        iDestruct \"Hresources\" as (φ Hpers) \"[#Hsaved Ha]\".\n        rewrite e in Hρ;inversion Hρ;subst ρ.\n        iDestruct \"Ha\" as (v v') \"(Ha & Ha' & Hres')\".\n        iMod (sts_update_std _ _ _ (Uninitialized _) with \"Hsts Hstate\") as \"[Hsts Hstate]\".\n        iDestruct (region_map_delete_nonstatic with \"Hmap\") as \"Hmap\".\n        { intros m'. rewrite Hlookup. auto. }\n        iDestruct(region_map_insert_nonmonostatic (Uninitialized (v,v')) with \"Hmap\") as \"Hmap\";auto.\n        iDestruct (big_sepM_insert _ _ a with \"[$Hmap Ha Ha' Hstate]\") as \"Hmap\";[apply lookup_delete|..].\n        { iExists (Uninitialized (v,v')). rewrite lookup_insert. iSplit;auto. iFrame. iExists _. iSplit;eauto. }\n        rewrite insert_delete. rewrite (insert_id M);[|auto]. iModIntro.\n        iExists (<[a:=(v,v')]> m). rewrite /uninitialize /= uninitialize_std_sta_insert;[|auto]. iFrame.\n        iSplit;[iPureIntro|iSplit].\n        * intros a'. destruct (decide (a = a'));[subst;rewrite lookup_insert|rewrite lookup_insert_ne//].\n          { split;intros;[split;auto;constructor|eauto]. }\n          { split;intros Hcond;[apply Hmcond in Hcond as [? ?]|]. split;auto. constructor;auto.\n            apply Hmcond. destruct Hcond as [? Hcond]. split;auto. apply elem_of_cons in Hcond as [-> | Hcond];[|auto].\n            contradiction. }\n        * iExists _,_. iFrame. iPureIntro. rewrite HM_dom -HMρ_dom. clear -Hlookup. split;auto.\n          assert (a ∈ dom (gset Addr) Mρ);[apply elem_of_gmap_dom;eauto|]. rewrite dom_insert_L. set_solver.\n        * rewrite rel_eq /rel_def REL_eq /REL_def RELS_eq /RELS_def. iDestruct \"Hrel\" as (γpred') \"[HREL Hsaved']\".\n          iDestruct (reg_in with \"[$HM $HREL]\") as %Hmeq. rewrite Hmeq lookup_insert in Hγp;inversion Hγp. simplify_eq.\n          iDestruct (saved_pred_agree _ _ _ (W,(v,v')) with \"Hsaved Hsaved'\") as \"Heq\".\n          iDestruct \"Hres'\" as \"#Hres'\". iModIntro. iNext. iApply big_sepM_insert;[auto|].\n          iFrame \"Hres\". iExists φ. iModIntro. iSplit;auto.\n      + iMod (\"IH\" $! a0 with \"[] Hr Hsts\") as (m Hmcond) \"[Hr [Hsts #Hres] ]\".\n        { rewrite region_addrs_cons in Heq;[|solve_addr]. rewrite Hnext in Heq. inversion Heq;auto. }\n        assert (m !! a = None) as Hnone.\n        { destruct (m!!a)eqn:Hsome';auto. assert (is_Some (m!!a)) as HisSome;eauto. apply Hmcond in HisSome as [Htemps Hin]. exfalso.\n          rewrite Haddrs_cons in Heq. inversion Heq. rewrite H1 in Hin. apply elem_of_app in Hin as [Hin | Heq'].\n          apply elem_of_region_addrs in Hin. solve_addr. apply elem_of_list_singleton in Heq';subst;solve_addr. }\n        iModIntro. iExists m.\n        iFrame \"∗ #\". iPureIntro. intros a'. split.\n        * intros Hsome. apply Hmcond in Hsome as [? ?]. split;auto. constructor;auto.\n        * intros [Htemps Hin]. apply Hmcond. split;auto.\n          apply elem_of_cons in Hin as [-> | Hcons];auto. contradiction.\n  Qed.\n\n  Lemma uninitialize_region_world W a m :\n    ⌜∀ (a' : Addr), is_Some(m !! a') ↔ ((W.1 !! a' = Some Monotemporary) ∧ (a <= a')%a)⌝ -∗\n    region W -∗ sts_full_world (uninitialize W m) -∗ region (uninitialize W m) ∗ sts_full_world (uninitialize W m).\n  Proof.\n    iIntros (Hcond) \"Hr Hsts\".\n    rewrite region_eq /region_def.\n    iDestruct \"Hr\" as (M Mρ) \"(HM & #Hdom_m & #Hdom_mρ & Hpreds)\".\n    iDestruct \"Hdom_m\" as %Hdom_m. iDestruct \"Hdom_mρ\" as %Hdom_mρ.\n    iApply sep_exist_r. iExists M. iApply sep_exist_r. iExists Mρ.\n    iAssert (⌜∀ a ρ, Mρ !! a = Some ρ → (uninitialize W m).1 !! a = Some ρ⌝)%I as %Hρcond.\n    { iIntros (a' ρ Ha'). assert (is_Some (M !! a')) as [γp HMa'];[apply elem_of_gmap_dom;rewrite -Hdom_mρ;apply elem_of_gmap_dom;eauto|].\n      iDestruct (big_sepM_delete with \"Hpreds\") as \"[Ha _]\";[apply HMa'|].\n      iDestruct \"Ha\" as (ρ' Hlookup) \"[Hρ' _]\".\n      iDestruct (sts_full_state_std with \"Hsts Hρ'\") as %Hρ'. simplify_eq. auto. }\n    iFrame. rewrite uninitialize_dom. repeat iSplit;auto.\n    iApply (big_sepM_mono with \"Hpreds\").\n    iIntros (a' x Hmx) \"Ha\".\n    iDestruct \"Ha\" as (ρ Hlookup) \"[Hstate Ha]\".\n    iDestruct \"Ha\" as (φ Hpers) \"[#Hsaved Hres]\".\n    apply Hρcond in Hlookup as Hρ.\n    iExists ρ. iSplit;auto. iFrame. iExists φ. repeat iSplit;auto.\n    destruct (decide (W.1 !! a' = Some Monotemporary)).\n    - destruct (decide (a <= a')%a).\n      + assert (is_Some (m !! a')) as [v Hv];[apply Hcond;auto|].\n        pose proof (uninitialize_std_sta_lookup_in a' m W.1 v Hv e) as Hmin.\n        rewrite Hρ in Hmin. inversion Hmin;subst ρ. iFrame.\n      + assert (m !! a' = None) as Hnone.\n        { apply eq_None_not_Some. intros Hcontr%Hcond. destruct Hcontr as [? ?]; contradiction. }\n        rewrite uninitialize_std_sta_None_lookup in Hρ;auto.\n        rewrite e in Hρ. inversion Hρ;subst ρ.\n        iDestruct \"Hres\" as (v v') \"Hres\".\n        iDestruct \"Hres\" as \"(Ha & Ha' & #Hmono & #Hφ)\".\n        iExists _,_; iFrame \"∗ #\".\n        iApply (\"Hmono\" with \"[] Hφ\"). iPureIntro.\n        apply related_sts_a_weak_world with a. clear -n;solve_addr. apply uninitialize_related_pub_a. auto.\n    - assert (m !! a' = None) as Hnone.\n      { apply eq_None_not_Some. intros Hcontr%Hcond. destruct Hcontr as [ ? ?]; contradiction. }\n      rewrite uninitialize_std_sta_None_lookup in Hρ;auto.\n      rewrite Hρ in n.\n      destruct ρ;auto;try contradiction.\n      * iDestruct \"Hres\" as (v v') \"Ha\".\n        iDestruct \"Ha\" as \"(Ha & Ha' & #Hmono & #Hφ)\".\n        iExists v,v'. iFrame \"∗ #\". iNext.\n        iApply (\"Hmono\" with \"[] Hφ\"). iPureIntro.\n        apply related_sts_pub_plus_priv_world.\n        apply related_sts_a_pub_plus_world with a.\n        apply uninitialize_related_pub_a; auto.\n  Qed.\n\n  Lemma uninitialize_region_keep W (a : Addr) E :\n    region W ∗ sts_full_world W ={E}=∗\n    ∃ m, ⌜∀ (a' : Addr), is_Some(m !! a') ↔ (((std W) !! a' = Some Monotemporary) ∧ (a <= a')%a)⌝\n      ∗ region (uninitialize W m) ∗ sts_full_world (uninitialize W m)\n      ∗ □ ▷ ([∗ map] a↦w ∈ m, □ ∃ φ, ⌜forall Wv, Persistent (φ Wv)⌝ ∗ monotemp_pers_resources W φ a w.1 w.2 ∗ rel a φ).\n  Proof.\n    iIntros \"(Hr & Hsts)\".\n    iMod (uninitialize_region_states_keep _ _ (region_addrs a addr_reg.top ++ [addr_reg.top])\n            with \"[] [$Hr $Hsts]\") as (m Hconds) \"[Hr [Hsts #Hres] ]\";[eauto|].\n    iModIntro. iExists m.\n    assert (∀ (a' : Addr), is_Some(m !! a') ↔ ((W.1 !! a' = Some Monotemporary) ∧ (a <= a')%a)) as Hconds'.\n    { intros a'. split.\n      - intros Hsome. apply Hconds in Hsome. destruct Hsome as [Hmono Hin].\n        apply elem_of_app in Hin as [Hin | Hin];[|apply elem_of_list_singleton in Hin;subst].\n        apply elem_of_region_addrs in Hin as [Hin ?]. split;auto.\n        split;auto. solve_addr.\n      - intros [Hmono Hle]. apply Hconds. split;auto. apply elem_of_app. destruct (decide (a' < addr_reg.top)%a).\n        left. apply elem_of_region_addrs;auto. right. assert (a' = addr_reg.top);[solve_addr|subst]. constructor. }\n    iDestruct (uninitialize_region_world with \"[] Hr Hsts\") as \"[Hr Hsts]\";[eauto|iFrame;auto].\n  Qed.\n\n  (* ------------------------------------------------------------------------------------------------- *)\n  (* ------------------- A version of uninitialization where we forget the invariants ---------------- *)\n  (* ------------------------------------------------------------------------------------------------- *)\n\n  Lemma uninitialize_region_last W E :\n    region W ∗ sts_full_world W ={E}=∗ ∃ m, ⌜((∃ (v v': Word), {[addr_reg.top:=(v,v')]} = m) ↔ W.1 !! addr_reg.top = Some Monotemporary)\n                                             ∧ (∅ = m <-> W.1 !! addr_reg.top ≠ Some Monotemporary)⌝\n                                       ∗ region W ∗ sts_full_world (uninitialize W m).\n  Proof.\n    iIntros \"[Hr Hsts]\".\n    iMod (uninitialize_region_last_keep with \"[$Hr $Hsts]\") as (m Hforall) \"(Hr & Hsts & Hm)\".\n    iModIntro. iExists m. iFrame. auto.\n  Qed.\n\n  Lemma uninitialize_region_states W (a : Addr) (l : list Addr) E :\n    ⌜l = region_addrs a addr_reg.top ++ [addr_reg.top]⌝ -∗\n    region W ∗ sts_full_world W ={E}=∗\n    ∃ m, ⌜∀ (a' : Addr), is_Some(m !! a') ↔ ((W.1 !! a' = Some Monotemporary) ∧ (a' ∈ l)%a)⌝\n         ∗ region W ∗ sts_full_world (uninitialize W m).\n  Proof.\n    iIntros (Heq) \"(Hr & Hsts)\".\n    iMod (uninitialize_region_states_keep with \"[] [$Hr $Hsts]\") as (m Hforall) \"(Hr & Hsts & Hm)\". eauto.\n    iModIntro. iExists m. iFrame. auto.\n  Qed.\n\n  Lemma uninitialize_region W (a : Addr) E :\n    region W ∗ sts_full_world W ={E}=∗\n    ∃ m, ⌜∀ (a' : Addr), is_Some(m !! a') ↔ (((std W) !! a' = Some Monotemporary) ∧ (a <= a')%a)⌝\n         ∗ region (uninitialize W m) ∗ sts_full_world (uninitialize W m).\n  Proof.\n    iIntros \"(Hr & Hsts)\".\n    iMod (uninitialize_region_keep with \"[$Hr $Hsts]\") as (m Hforall) \"(Hr & Hsts & Hres)\".\n    iModIntro. iExists m. iFrame. auto.\n  Qed.\n\n  (* ------------------------------------------------------------------------------------------------- *)\n  (* -------------- We will want to change the values of an already uninitialized region ------------- *)\n  (* ------------------------------------------------------------------------------------------------- *)\n\n  Lemma uninitialized_condition W m a :\n    (∀ a' : Addr, is_Some (m !! a') ↔ (W.1 !! a' = Some Monotemporary) ∧ (a <= a')%a) →\n    ∀ a'' : Addr, (a <= a'')%a → (uninitialize W m).1 !! a'' ≠ Some Monotemporary.\n  Proof.\n    intros Hcond.\n    intros a'' Hle.\n    destruct (m !! a'') eqn:Hsome.\n    - assert (is_Some (m !! a'')) as Ha'';[eauto|]. apply Hcond in Ha'' as [Hmono Ha''].\n      rewrite (uninitialize_std_sta_lookup_in _ _ _ p);auto.\n    - intros Hcontr. rewrite uninitialize_std_sta_None_lookup in Hcontr;auto.\n      assert (is_Some (m !! a'')) as [v Hv]. apply Hcond. split;auto.\n      rewrite Hsome in Hv. done.\n  Qed.\n\n  Lemma valid_uninitialized_condition_weak W m a p g b e b' (w : Word) :\n    pwlU p = true → isU p = true → (b' <= b)%a →\n    (∀ a' : Addr, is_Some (m !! a') ↔ (W.1 !! a' = Some Monotemporary) ∧ (b' <= a')%a) →\n    interp W (inr (p,g,b,e,a),w) -∗ ⌜∀ a', (b <= a' < e)%a → (∃ w, (uninitialize W m).1 !! a' = Some (Uninitialized w))⌝.\n  Proof.\n    iIntros (HpwlU HU Hle' Hcond) \"#Hv\".\n    iDestruct (interp_eq with \"Hv\") as %<-.\n    iIntros (a' [Hle Hlt]).\n    iDestruct (writeLocalAllowedU_implies_local with \"Hv\") as %Hmono;auto.\n    destruct g;inversion Hmono.\n    destruct p;inversion HU;inversion HpwlU.\n    - rewrite fixpoint_interp1_eq /=. iDestruct \"Hv\" as \"[_ [Hv' Hv]]\".\n      destruct (decide (a <= a'))%a.\n      + iDestruct (big_sepL_elem_of _ _ a' with \"Hv\") as \"[Hcond #Hreg]\".\n        { apply elem_of_region_addrs. solve_addr. }\n        iDestruct \"Hreg\" as %[Hreg | [? Hreg] ].\n        { assert (is_Some (m !! a')) as [v Hv];[apply Hcond;split;auto;solve_addr|].\n          rewrite (uninitialize_std_sta_lookup_in _ _ _ v);eauto. }\n        { assert (m !! a' = None) as Hv;[|rewrite uninitialize_std_sta_None_lookup//;rewrite Hreg;eauto].\n          destruct (m !! a') eqn:Hsome;auto. assert (is_Some (m!!a')) as Hissome;eauto.\n          apply Hcond in Hissome as [Heq ?]. rewrite Heq in Hreg;inversion Hreg. }\n      + iDestruct (big_sepL_elem_of _ _ a' with \"Hv'\") as \"[Hcond #Hreg]\".\n        { apply elem_of_region_addrs. solve_addr. }\n        iDestruct \"Hreg\" as %Hreg.\n        assert (is_Some (m !! a')) as [v Hv];[apply Hcond;split;auto;solve_addr|].\n        rewrite (uninitialize_std_sta_lookup_in _ _ _ v);eauto.\n    - rewrite fixpoint_interp1_eq /=. iDestruct \"Hv\" as \"[_ [Hv' Hv]]\".\n      destruct (decide (a <= a'))%a.\n      + iDestruct (big_sepL_elem_of _ _ a' with \"Hv\") as \"[Hcond #Hreg]\".\n        { apply elem_of_region_addrs. solve_addr. }\n        iDestruct \"Hreg\" as %[Hreg | [? Hreg] ].\n        { assert (is_Some (m !! a')) as [v Hv];[apply Hcond;split;auto;solve_addr|].\n          rewrite (uninitialize_std_sta_lookup_in _ _ _ v);eauto. }\n        { assert (m !! a' = None) as Hv;[|rewrite uninitialize_std_sta_None_lookup//;rewrite Hreg;eauto].\n          destruct (m !! a') eqn:Hsome;auto. assert (is_Some (m!!a')) as Hissome;eauto.\n          apply Hcond in Hissome as [Heq ?]. rewrite Heq in Hreg;inversion Hreg. }\n      + iDestruct (big_sepL_elem_of _ _ a' with \"Hv'\") as \"[Hcond #Hreg]\".\n        { apply elem_of_region_addrs. solve_addr. }\n        iDestruct \"Hreg\" as %Hreg.\n        assert (is_Some (m !! a')) as [v Hv];[apply Hcond;split;auto;solve_addr|].\n        rewrite (uninitialize_std_sta_lookup_in _ _ _ v);eauto.\n  Qed.\n\n  Lemma valid_readAllowed_condition_weak W m a p g b e b' (w : Word) :\n    readAllowed p = true → (b' <= b)%a →\n    (∀ a' : Addr, is_Some (m !! a') ↔ (W.1 !! a' = Some Monotemporary) ∧ (b' <= a')%a) →\n    interp W (inr (p,g,b,e,a),w) -∗ ⌜∀ a', (b <= a' < e)%a → ((uninitialize W m).1 !! a' = Some Permanent ∨ (∃ w, (uninitialize W m).1 !! a' = Some (Uninitialized w)))⌝.\n  Proof.\n    iIntros (Hra Hle' Hcond) \"#Hv\".\n    iDestruct (interp_eq with \"Hv\") as %<-.\n    iIntros (a' [Hle Hlt]).\n    iDestruct (readAllowed_implies_region_conditions with \"Hv\") as \"Hcond\";auto.\n    rewrite /region_conditions.\n    destruct (pwl p).\n    - iDestruct (big_sepL_elem_of _ _ a' with \"Hcond\") as \"[Ha' #Hreg]\".\n      { apply elem_of_region_addrs. solve_addr. }\n      rewrite /region_state_pwl_mono. iDestruct \"Hreg\" as %Hmono.\n      iRight.\n      assert (is_Some (m !! a')) as [v Hv];[apply Hcond;split;auto;solve_addr|].\n      rewrite (uninitialize_std_sta_lookup_in _ _ _ v);eauto.\n    - iDestruct (big_sepL_elem_of _ _ a' with \"Hcond\") as \"[Ha' #Hreg]\".\n      { apply elem_of_region_addrs. solve_addr. }\n      rewrite /region_state_nwl. iDestruct \"Hreg\" as %Hmono.\n      destruct g.\n      { iLeft;auto.\n        assert (m !! a' = None) as Hv;[|rewrite uninitialize_std_sta_None_lookup//;rewrite Hreg;eauto].\n        destruct (m !! a') eqn:Hsome;auto. assert (is_Some (m!!a')) as Hissome;eauto.\n        apply Hcond in Hissome as [Heq ?]. rewrite Hmono in Heq. congruence. }\n      { iLeft;auto.\n        assert (m !! a' = None) as Hv;[|rewrite uninitialize_std_sta_None_lookup//;rewrite Hreg;eauto].\n        destruct (m !! a') eqn:Hsome;auto. assert (is_Some (m!!a')) as Hissome;eauto.\n        apply Hcond in Hissome as [Heq ?]. rewrite Hmono in Heq. congruence. }\n      { destruct Hmono as [Hmono | Hmono].\n        + assert (is_Some (m !! a')) as [v Hv];[apply Hcond;split;auto;solve_addr|].\n          rewrite (uninitialize_std_sta_lookup_in _ _ _ v);eauto.\n        + assert (m !! a' = None) as Hv;[|rewrite uninitialize_std_sta_None_lookup//;rewrite Hmono;eauto].\n          destruct (m !! a') eqn:Hsome;auto. assert (is_Some (m!!a')) as Hissome;eauto.\n          apply Hcond in Hissome as [Heq ?]. rewrite Hmono in Heq. congruence.\n      }\n  Qed.\n\n  Lemma valid_uninitialized_condition W m a p g b e w :\n    pwlU p = true → isU p = true →\n    (∀ a' : Addr, is_Some (m !! a') ↔ (W.1 !! a' = Some Monotemporary) ∧ (b <= a')%a) →\n    interp W (inr (p,g,b,e,a),w) -∗ ⌜∀ a', (b <= a' < e)%a → (∃ w, (uninitialize W m).1 !! a' = Some (Uninitialized w))⌝.\n  Proof.\n    iIntros (HpwlU HU Hcond) \"#Hv\".\n    iApply valid_uninitialized_condition_weak;eauto.\n    solve_addr.\n  Qed.\n\n  Lemma region_map_uninitialized_monotone W W' M Mρ a :\n    related_sts_a_world W W' a →\n    (∀ a'', (a <= a'')%a → Mρ !! a'' ≠ Some Monotemporary) →\n    region_map_def M Mρ W -∗ region_map_def M Mρ W'.\n  Proof.\n    iIntros (Hrelated Hcond) \"Hr\".\n    iApply big_sepM_mono; iFrame.\n    iIntros (a' γ Hsome) \"Hm\".\n    iDestruct \"Hm\" as (ρ Hρ) \"[Hstate Hm]\".\n    iExists ρ. iFrame. iSplitR;[auto|].\n    destruct ρ.\n    - destruct (decide (a' <= a))%a.\n      2: { exfalso. assert (a <= a')%a as Hle;[solve_addr|].\n           apply Hcond in Hle as ?. congruence. }\n      iDestruct \"Hm\" as (φ Hpers) \"(#Hsavedφ & Hl)\".\n      iDestruct \"Hl\" as (v1 v2) \"(Hl & Hl' & Hmono & Hφ)\".\n      iExists _. do 2 (iSplitR;[eauto|]).\n      iFrame \"#\". iExists _,_.\n      iDestruct \"Hmono\" as \"#Hmono\"; iFrame \"∗ #\";\n        iApply \"Hmono\"; iFrame; auto.\n      iPureIntro. eapply related_sts_a_weak_world;eauto.\n    - iDestruct \"Hm\" as (φ Hpers) \"(#Hsavedφ & Hl)\".\n      iDestruct \"Hl\" as (v v') \"(Hl & Hl' & #Hmono & Hφ)\".\n      iExists _. do 2 (iSplitR;[eauto|]).\n      iFrame \"∗ #\". iExists _,_. iFrame \"∗ #\".\n      iApply \"Hmono\"; iFrame \"∗ #\"; auto.\n      iPureIntro.\n      apply related_sts_pub_plus_priv_world.\n      eapply related_sts_a_pub_plus_world;eauto.\n    - done.\n    - done.\n    - done.\n  Qed.\n\n  Lemma related_sts_a_uninitialized W a a' w :\n    (a <= a')%a →\n    (∃ v, W.1 !! a' = Some (Uninitialized v)) →\n    related_sts_a_world W (<s[a':=Uninitialized w]s>W) a.\n  Proof.\n    intros Hle Hcond.\n    split;[|apply related_sts_pub_plus_refl].\n    split.\n    - rewrite dom_insert_L. set_solver.\n    - intros i x y Hx Hy.\n      destruct (decide (i = a')).\n      + subst. rewrite lookup_insert in Hy.\n        destruct Hcond as [v Hv]. rewrite Hv in Hx.\n        simplify_eq. right with Monotemporary.\n        rewrite decide_True;auto. left. constructor.\n        eright;[|left]. rewrite decide_True;auto. right. constructor.\n      + rewrite lookup_insert_ne// in Hy. rewrite Hx in Hy;inversion Hy. left.\n  Qed.\n\n  Lemma uninitialize_open_region_change E W a a' φ v w w' `{∀ Wv, Persistent (φ Wv)}:\n    (a <= a')%a →\n    (∀ a'', (a <= a'')%a → W.1 !! a'' ≠ Some Monotemporary) →\n    rel a' φ\n    ∗ open_region a' W\n    ∗ sts_full_world W\n    ∗ a' ↦ₐ w\n    ∗ a' ↣ₐ w'\n    ∗ sts_state_std a' (Uninitialized v)\n    ={E}=∗\n    region (<s[a':=Uninitialized (w,w')]s> W) ∗ sts_full_world (<s[a':=Uninitialized (w,w')]s> W).\n  Proof.\n    iIntros (Hle Hcond) \"(#Hrel & Hreg & Hsts & Ha & Ha' & Hstate)\".\n    rewrite open_region_eq /open_region_def rel_eq /rel_def REL_eq /REL_def RELS_eq /RELS_def.\n    iDestruct \"Hrel\" as (γpred) \"[Hown Hsaved]\".\n    iDestruct \"Hreg\" as (M Mρ) \"(HM & #Hdom_m & #Hdom_mρ & Hpreds)\".\n    iDestruct \"Hdom_m\" as %Hdom_m; iDestruct \"Hdom_mρ\" as %Hdom_mρ.\n    assert (Hle':=Hle).\n    apply Hcond in Hle' as Hv.\n    iDestruct (sts_full_state_std with \"Hsts Hstate\") as %Hρ.\n    iDestruct (reg_in γrel M with \"[$HM $Hown]\") as %HMeq.\n\n    iAssert (⌜∀ a ρ, delete a' Mρ !! a = Some ρ ↔ delete a' W.1 !! a = Some ρ⌝)%I as %Hρcond.\n    { iIntros (a0 ρ). rewrite iff_to_and.\n      iSplit;iIntros (Ha').\n      - destruct (decide (a0 = a'));[subst;rewrite lookup_delete in Ha';done|rewrite lookup_delete_ne// in Ha'].\n        assert (is_Some (M !! a0)) as [γp HMa'];[apply elem_of_gmap_dom;rewrite -Hdom_mρ;apply elem_of_gmap_dom;eauto|].\n        iDestruct (big_sepM_delete with \"Hpreds\") as \"[Ha'' _]\";[rewrite lookup_delete_ne// apply HMa'|].\n        iDestruct \"Ha''\" as (ρ' Hlookup) \"[Hρ' _]\".\n        iDestruct (sts_full_state_std with \"Hsts Hρ'\") as %Hρ';\n          rewrite lookup_delete_ne// in Hlookup; rewrite lookup_delete_ne//; simplify_eq; auto.\n      - destruct (decide (a0 = a'));[subst;rewrite lookup_delete in Ha';done|rewrite lookup_delete_ne// in Ha'].\n        assert (is_Some (M !! a0)) as [γp HMa'];[apply elem_of_gmap_dom;rewrite -Hdom_m;apply elem_of_gmap_dom;eauto|].\n        iDestruct (big_sepM_delete with \"Hpreds\") as \"[Ha'' _]\";[rewrite lookup_delete_ne// apply HMa'|].\n        iDestruct \"Ha''\" as (ρ' Hlookup) \"[Hρ' _]\".\n        iDestruct (sts_full_state_std with \"Hsts Hρ'\") as %Hρ'. rewrite Ha' in Hρ'. inversion Hρ'. auto. }\n\n    iDestruct (region_map_insert_nonmonostatic (Uninitialized (w,w')) with \"Hpreds\") as \"Hpreds\";[intros;auto|].\n    iDestruct (region_map_uninitialized_monotone _ (<s[a':=Uninitialized (w,w')]s>W) _ _ a with \"Hpreds\") as \"Hpreds\".\n    { apply related_sts_a_uninitialized;auto. rewrite Hρ. eauto. }\n    { intros a'' Ha''. destruct (decide (a'' = a')); subst;simplify_map_eq;eauto.\n      intros Hcontr. specialize (Hρcond a'' Monotemporary).\n      apply Hcond in Ha''. rewrite !lookup_delete_ne// in Hρcond. apply Hρcond in Hcontr. contradiction. }\n\n    iMod (sts_update_std _ _ _ (Uninitialized (w,w')) with \"Hsts Hstate\") as \"[Hsts Hstate]\".\n    iModIntro. iFrame.\n\n    iDestruct (big_sepM_insert _ (delete a' M) a' with \"[-HM]\") as \"test\";\n      first by rewrite lookup_delete.\n    { iFrame. iExists _. iFrame.\n      iSplit;[iPureIntro;apply lookup_insert|].\n      iExists _. iFrame \"∗ #\". repeat iSplitR; auto. }\n    rewrite -HMeq. rewrite region_eq /region_def RELS_eq /RELS_def. iExists _,_; iFrame. iPureIntro.\n    repeat rewrite dom_insert_L. rewrite Hdom_m Hdom_mρ.\n    assert (a' ∈ dom (gset Addr) M) as Hin;[rewrite HMeq dom_insert_L;clear;set_solver|].\n    split;clear -Hin;set_solver.\n  Qed.\n\nEnd heap.\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/region_invariants_batch_uninitialized_binary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.29671183576223376}}
{"text": "(* --------------------------------------------------------------------\n * Copyright (c) - 2017--2020 - Xavier Allamigeon <xavier.allamigeon at inria.fr>\n * Copyright (c) - 2017--2020 - Ricardo D. Katz <katz@cifasis-conicet.gov.ar>\n * Copyright (c) - 2019--2020 - Pierre-Yves Strub <pierre-yves@strub.nu>\n *\n * Distributed under the terms of the CeCILL-B-V1 license\n * -------------------------------------------------------------------- *)\n\n(* -------------------------------------------------------------------- *)\nFrom mathcomp Require Import all_ssreflect all_algebra finmap.\nRequire Import extra_misc inner_product lrel.\n\nImport Order.Theory.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLocal Open Scope ring_scope.\nImport Order.TTheory GRing.Theory Num.Theory.\n\n(* -------------------------------------------------------------------- *)\nDeclare Scope polyh_scope.\nDelimit Scope polyh_scope with PH.\n\nLocal Open Scope polyh_scope.\n\n(* -------------------------------------------------------------------- *)\nReserved Notation \"''affine[' R ]_ n\"\n  (at level 8, n at level 2, format \"''affine[' R ]_ n\").\nReserved Notation \"''affine[' R ]\"\n  (at level 8, format \"''affine[' R ]\").\nReserved Notation \"''affine_' n\"\n  (at level 8, format \"''affine_' n\").\nReserved Notation \"[ 'affine' I ]\" (at level 0, format \"[ 'affine'  I ]\").\nReserved Notation \"[ 'affine' U & Ω ]\"\n         (at level 0, format \"[ 'affine'  U  &  Ω ]\").\nReserved Notation \"[ 'hp' e ]\" (at level 0, format \"[ 'hp'  e ]\").\nReserved Notation \"[ 'pt' Ω ]\" (at level 0, format \"[ 'pt'  Ω ]\").\nReserved Notation \"[ 'line' c & Ω ]\"  (at level 0, format \"[ 'line'  c  &  Ω ]\").\n\nReserved Notation \"'[' 'affine0' ']'\" (at level 0).\nReserved Notation \"'[' 'affineT' ']'\" (at level 0).\n\n(* -------------------------------------------------------------------- *)\nReserved Notation \"\\polyI_ i F\"\n  (at level 41, F at level 41, i at level 0,\n           format \"'[' \\polyI_ i '/  '  F ']'\").\nReserved Notation \"\\polyI_ ( i <- r | P ) F\"\n  (at level 41, F at level 41, i, r at level 50,\n           format \"'[' \\polyI_ ( i  <-  r  |  P ) '/  '  F ']'\").\nReserved Notation \"\\polyI_ ( i <- r ) F\"\n  (at level 41, F at level 41, i, r at level 50,\n           format \"'[' \\polyI_ ( i  <-  r ) '/  '  F ']'\").\nReserved Notation \"\\polyI_ ( m <= i < n | P ) F\"\n  (at level 41, F at level 41, i, m, n at level 50,\n           format \"'[' \\polyI_ ( m  <=  i  <  n  |  P ) '/  '  F ']'\").\nReserved Notation \"\\polyI_ ( m <= i < n ) F\"\n  (at level 41, F at level 41, i, m, n at level 50,\n           format \"'[' \\polyI_ ( m  <=  i  <  n ) '/  '  F ']'\").\nReserved Notation \"\\polyI_ ( i | P ) F\"\n  (at level 41, F at level 41, i at level 50,\n           format \"'[' \\polyI_ ( i  |  P ) '/  '  F ']'\").\nReserved Notation \"\\polyI_ ( i : t | P ) F\"\n  (at level 41, F at level 41, i at level 50).\nReserved Notation \"\\polyI_ ( i : t ) F\"\n  (at level 41, F at level 41, i at level 50).\nReserved Notation \"\\polyI_ ( i < n | P ) F\"\n  (at level 41, F at level 41, i, n at level 50,\n           format \"'[' \\polyI_ ( i  <  n  |  P ) '/  '  F ']'\").\nReserved Notation \"\\polyI_ ( i < n ) F\"\n  (at level 41, F at level 41, i, n at level 50,\n           format \"'[' \\polyI_ ( i  <  n )  F ']'\").\nReserved Notation \"\\polyI_ ( i 'in' A | P ) F\"\n  (at level 41, F at level 41, i, A at level 50,\n           format \"'[' \\polyI_ ( i  'in'  A  |  P ) '/  '  F ']'\").\nReserved Notation \"\\polyI_ ( i 'in' A ) F\"\n  (at level 41, F at level 41, i, A at level 50,\n           format \"'[' \\polyI_ ( i  'in'  A ) '/  '  F ']'\").\n\nReserved Notation \"x `<=` y `<=` z\" (at level 70, y, z at next level).\nReserved Notation \"x `<=` y `<` z\" (at level 70, y, z at next level).\nReserved Notation \"x `<` y `<=` z\" (at level 70, y, z at next level).\nReserved Notation \"x `<` y `<` z\" (at level 70, y, z at next level).\n\nReserved Notation \"x `>=` y\" (at level 70, y at next level).\nReserved Notation \"x `>` y\" (at level 70, y at next level).\n\nReserved Notation \"x `<=` y :> T\" (at level 70, y at next level).\nReserved Notation \"x `<` y :> T\" (at level 70, y at next level).\nReserved Notation \"x `>=` y :> T\" (at level 70, y at next level).\nReserved Notation \"x `>` y :> T\" (at level 70, y at next level).\n\nReserved Notation \"x `>=<` y\" (at level 70, y at next level).\nReserved Notation \"x `><` y\" (at level 70, y at next level).\n\nReserved Notation \"`<=` y\" (at level 35).\nReserved Notation \"`>=` y\" (at level 35).\nReserved Notation \"`<` y\" (at level 35).\nReserved Notation \"`>` y\" (at level 35).\nReserved Notation \"`>=<` y\" (at level 35).\nReserved Notation \"`><` y\" (at level 35).\nReserved Notation \"`<=` y :> T\" (at level 35, y at next level).\nReserved Notation \"`>=` y :> T\" (at level 35, y at next level).\nReserved Notation \"`<` y :> T\" (at level 35, y at next level).\nReserved Notation \"`>` y :> T\" (at level 35, y at next level).\nReserved Notation \"`>=<` y :> T\" (at level 35, y at next level).\nReserved Notation \"`><` y :> T\" (at level 35, y at next level).\n\nReserved Notation \"x `<=` y ?= 'iff' c\"\n  (at level 70, y, c at next level,\n       format \"x '[hv'  `<=`  y '/'  ?=  'iff'  c ']'\").\n\nReserved Notation \"x `<=` y ?= 'iff' c :> T\"\n  (at level 70, y, c at next level,\n       format \"x '[hv'  `<=`  y '/'  ?=  'iff'  c  :> T ']'\").\n\n(* -------------------------------------------------------------------- *)\nFact polyh_display : unit. Proof. exact: tt. Qed.\n\nNotation poly_0    := (@Order.bottom polyh_display) (only parsing).\nNotation poly_1    := (@Order.top polyh_display) (only parsing).\nNotation poly_le   := (@Order.le polyh_display _) (only parsing).\nNotation poly_lt   := (@Order.lt polyh_display _) (only parsing).\nNotation poly_ge   := (@Order.ge polyh_display _) (only parsing).\nNotation poly_gt   := (@Order.gt polyh_display _) (only parsing).\nNotation poly_leif := (@Order.leif polyh_display _) (only parsing).\nNotation poly_cmp  := (@Order.comparable polyh_display _) (only parsing).\nNotation poly_meet := (@Order.meet polyh_display _).\n\nNotation \"<=%PH\"  := poly_le   : fun_scope.\nNotation \">=%PH\"  := poly_ge   : fun_scope.\nNotation \"<%PH\"   := poly_lt   : fun_scope.\nNotation \">%PH\"   := poly_gt   : fun_scope.\nNotation \"<?=%PH\" := poly_leif : fun_scope.\nNotation \">=<%PH\" := poly_cmp  : fun_scope.\nNotation \"><%PH\"  := (fun x y => ~~ (poly_cmp x y)) : fun_scope.\n\nNotation \"`<=` y\" := (poly_ge y) : polyh_scope.\nNotation \"`<=` y :> T\" := (`<=` (y : T)) (only parsing) : polyh_scope.\nNotation \"`>=` y\"  := (poly_le y) : polyh_scope.\nNotation \"`>=` y :> T\" := (`>=` (y : T)) (only parsing) : polyh_scope.\n\nNotation \"`<` y\" := (poly_gt y) : polyh_scope.\nNotation \"`<` y :> T\" := (`<` (y : T)) (only parsing) : polyh_scope.\nNotation \"`>` y\" := (poly_lt y) : polyh_scope.\nNotation \"`>` y :> T\" := (`>` (y : T)) (only parsing) : polyh_scope.\n\nNotation \"`>=<` y\" := (poly_cmp y) : polyh_scope.\nNotation \"`>=<` y :> T\" := (`>=<` (y : T)) (only parsing) : polyh_scope.\n\nNotation \"`><` y\" := (fun x => ~~ (poly_cmp y x)) : polyh_scope.\nNotation \"`><` y :> T\" := (`><` (y : T)) (only parsing) : polyh_scope.\n\nNotation \"x `<=` y\" := (poly_le x y) : polyh_scope.\nNotation \"x `<=` y :> T\" := ((x : T) `<=` (y : T)) (only parsing) : polyh_scope.\nNotation \"x `>=` y\" := (y `<=` x) (only parsing) : polyh_scope.\nNotation \"x `>=` y :> T\" := ((x : T) `>=` (y : T)) (only parsing) : polyh_scope.\n\nNotation \"x `<` y\"  := (poly_lt x y) : polyh_scope.\nNotation \"x `<` y :> T\" := ((x : T) `<` (y : T)) (only parsing) : polyh_scope.\nNotation \"x `>` y\"  := (y `<` x) (only parsing) : polyh_scope.\nNotation \"x `>` y :> T\" := ((x : T) `>` (y : T)) (only parsing) : polyh_scope.\n\nNotation \"x `<=` y `<=` z\" := ((x `<=` y) && (y `<=` z)) : polyh_scope.\nNotation \"x `<` y `<=` z\" := ((x `<` y) && (y `<=` z)) : polyh_scope.\nNotation \"x `<=` y `<` z\" := ((x `<=` y) && (y `<` z)) : polyh_scope.\nNotation \"x `<` y `<` z\" := ((x `<` y) && (y `<` z)) : polyh_scope.\n\nNotation \"x `<=` y ?= 'iff' C\" := (poly_leif x y C) : polyh_scope.\nNotation \"x `<=` y ?= 'iff' C :> R\" := ((x : R) `<=` (y : R) ?= iff C)\n  (only parsing) : polyh_scope.\n\nNotation \"x `>=<` y\" := (poly_cmp x y) : polyh_scope.\nNotation \"x >< y\" := (~~ (poly_cmp x y)) : polyh_scope.\n\nNotation \"P `&` Q\" := (poly_meet P Q) (at level 48, left associativity) : polyh_scope.\n\nNotation \"\\meet_ ( i <- r | P ) F\" :=\n  (\\big[poly_meet/poly_1]_(i <- r | P%B) F).\nNotation \"\\meet_ ( i <- r ) F\" :=\n  (\\big[poly_meet/poly_1]_(i <- r) F).\nNotation \"\\meet_ ( i | P ) F\" :=\n  (\\big[poly_meet/poly_1]_(i | P%B) F).\nNotation \"\\meet_ i F\" :=\n  (\\big[poly_meet/poly_1]_i F).\nNotation \"\\meet_ ( i : I | P ) F\" :=\n  (\\big[poly_meet/poly_1]_(i : I | P%B) F) (only parsing).\nNotation \"\\meet_ ( i : I ) F\" :=\n  (\\big[poly_meet/poly_1]_(i : I) F) (only parsing).\nNotation \"\\meet_ ( m <= i < n | P ) F\" :=\n (\\big[poly_meet/poly_1]_(m <= i < n | P%B) F).\nNotation \"\\meet_ ( m <= i < n ) F\" :=\n (\\big[poly_meet/poly_1]_(m <= i < n) F).\nNotation \"\\meet_ ( i < n | P ) F\" :=\n (\\big[poly_meet/poly_1]_(i < n | P%B) F).\nNotation \"\\meet_ ( i < n ) F\" :=\n (\\big[poly_meet/poly_1]_(i < n) F).\nNotation \"\\meet_ ( i 'in' A | P ) F\" :=\n (\\big[poly_meet/poly_1]_(i in A | P%B) F).\nNotation \"\\meet_ ( i 'in' A ) F\" :=\n (\\big[poly_meet/poly_1]_(i in A) F).\n\nSection Solve.\n\nVariable (R : realFieldType) (n : nat) (V : {vspace lrel[R]_n}).\n\nLet base := vbasis V.\n\nDefinition sat x :=\n   all (fun e : lrel => '[e.1, x] == e.2) base.\n\nLemma sum_lrel_fst m (v : 'I_m -> lrel[R]_n) : (* RK : I have added this auxiliary lemma. Should it be somewhere else? *)\n  (\\sum_(i < m) v i).1 = (\\sum_(i < m) (v i).1).\nProof.\nby apply: (@big_morph _ lrel[R]_n (fun y => y.1)).\nQed.\n\n(*TODO : change the name, and maybe put this lemma somewhere else *)\nLemma sum_lrel_fst_gen (F : finType) (P : pred F) (v : F -> lrel[R]_n) :\n  (\\sum_(i : F | P i) v i).1 = (\\sum_(i : F | P i) (v i).1).\nProof. by apply: (@big_morph _ lrel[R]_n (fun y => y.1)). Qed.\n\nLemma sum_lrel_snd m (v : 'I_m -> lrel[R]_n) : (* RK : I have added this auxiliary lemma. Should it be somewhere else? *)\n  (\\sum_(i < m) v i).2 = (\\sum_(i < m) (v i).2).\nProof.\nby apply: (@big_morph _ lrel[R]_n (fun y => y.2)).\nQed.\n\nLemma sum_lrel_snd_gen (F : finType) (P : pred F) (v : F -> lrel[R]_n) :\n  (\\sum_(i : F | P i) v i).2 = (\\sum_(i : F | P i) (v i).2).\nProof. by apply: (@big_morph _ lrel[R]_n (fun y => y.2)). Qed.\n\nLemma size_vbasis_dim : (* RK : I have added this auxiliary lemma, since I could not find it even if it is quite natural. Should it be somewhere else? *)\n  size (vbasis V) = \\dim V.\nProof.\napply/eqP; rewrite eqn_leq.\nmove: (vbasisP V) => basis_of_vbasis.\napply/andP; split.\n- rewrite basisEdim in basis_of_vbasis.\n  exact: (proj2 (andP basis_of_vbasis)).\n- rewrite basisEfree in basis_of_vbasis.\n  exact: (proj2 (andP (proj2 (andP basis_of_vbasis)))).\nQed.\n\nLemma satP x :\n  reflect (forall e, e \\in V -> '[e.1, x] = e.2) (sat x).\nProof. (* RK *)\napply/(iffP idP) => [/allP sat_x e e_in_V | sat_in_V ].\n- rewrite (coord_vbasis e_in_V) sum_lrel_fst sum_lrel_snd vdot_sumDl.\n  apply: eq_bigr => i _; rewrite vdotZl.\n  apply/(congr1 (fun y => coord (vbasis V) i e * y))/eqP/sat_x/mem_nth.\n  by rewrite size_vbasis_dim.\n- apply/allP => e ?.\n  by apply/eqP/(sat_in_V e)/vbasis_mem.\nQed.\n\nLet A := (\\matrix_i (tnth base i).1^T)^T.\nLet b := (\\row_i (tnth base i).2).\n\nLemma satE x : sat x = (b == x^T *m A).\nProof. (* RK *)\napply/idP/idP => [/allP sat_x |/eqP/rowP b_eq].\n- apply/eqP/trmx_inj/colP => j.\n  rewrite trmx_mul -row_vdot trmxK rowK 2!trmxK !mxE.\n  symmetry; apply/eqP/sat_x/mem_nth.\n  by rewrite size_vbasis_dim.\n- apply/satP => e e_in_V.\n  rewrite (coord_vbasis e_in_V) sum_lrel_fst sum_lrel_snd vdot_sumDl.\n  apply: eq_bigr => i _; rewrite vdotZl.\n  apply/(congr1 (fun y => coord (vbasis V) i e * y)).\n  move: (b_eq i) => b_eq_i; rewrite mxE (tnth_nth 0%R) in b_eq_i.\n  by rewrite b_eq_i -trmx_mul mxE -row_vdot rowK (tnth_nth 0%R) trmxK.\nQed.\n\nDefinition is_sat := (b <= A)%MS.\n\nLemma is_satP :\n  reflect (exists x, sat x) is_sat.\nProof.\napply/(iffP idP).\n- move => h_sat.\n  exists (b *m pinvmx A)^T; by rewrite satE trmxK mulmxKpV.\n- case => x; rewrite satE => /eqP sat_x.\n  by apply/submxP; exists x^T.\nQed.\n\nLemma is_satPn :\n  reflect (sat =1 pred0) (~~ is_sat).\nProof.\napply/(iffP idP).\n- move => satN x /=; apply/negbTE.\n  move: satN; apply/contra => sat_x.\n  by apply/is_satP; exists x.\n- move => sat0.\n  by apply/negP; case/is_satP => x; rewrite sat0.\nQed.\n\nEnd Solve.\n\nArguments satP {R n V x}.\nArguments is_satP {R n V}.\nArguments is_satPn {R n V}.\n\nSection Lift.\n\nVariable (R : realFieldType) (n : nat).\n\nDefinition be_lift0 (x: 'cV[R]_n) := fun v => [<v, '[v,x]>].\n\nLemma be_lift0_linear x : lmorphism (be_lift0 x).\nProof.\nby split; move => v w; rewrite /be_lift0 ?beaddE ?bescaleE ?vdotBl ?vdotZl.\nQed.\n\nDefinition be_lift x := linfun (Linear (be_lift0_linear x)).\n\nLemma befstE x : (befst \\o (be_lift x) = \\1)%VF.\nProof.\napply/lfunP => v.\nby rewrite comp_lfunE !lfunE.\nQed.\n\nLemma be_liftE W x :\n  sat W x -> ((be_lift x) @: (befst @: W))%VS = W.\nProof. (* RK *)\nmove/satP => sat_x.\nhave be_liftE_on_W u: u \\in W -> be_lift x (befst u) = u.\n  move => u_in_W.\n  rewrite !lfunE; apply/eqP/be_eqP; split; first by done.\n  exact: (sat_x _ u_in_W).\napply/vspaceP => w.\napply/idP/idP => [/memv_imgP [? /memv_imgP [v v_in_W] ->] ->| w_in_W].\n- by rewrite (be_liftE_on_W _ v_in_W).\n- apply/memv_imgP; exists (fst (be_lift0 x (fst w))).\n  + by apply/memv_imgP; exists w; [done | rewrite lfunE].\n  + by rewrite -(be_liftE_on_W _ w_in_W) !lfunE.\nQed.\n\n(*Lemma dim_be_lift W Ω : (\\dim ((be_lift Ω) @: W) = \\dim W)%N.\nProof.\napply/limg_dim_eq/subv_anti/andP; split; rewrite ?sub0v //.\napply/subvP => v; rewrite memv_cap memv_ker => /andP [h /eqP].\nmove/(congr1 befst); rewrite -comp_lfunE befstE id_lfunE linear0 => ->.\nby rewrite memv0.\nQed.*)\n\nEnd Lift.\n\nModule Core.\nSection Core.\nContext {R : realFieldType} (n : nat).\n\nVariant type :=\n| Affine0\n| Affine (I : {vspace lrel[R]_n}) of is_sat I.\n\nDefinition type_of of phant R := type.\nNotation  \"''affine[' R ]\" := (type_of (Phant R)).\n\nDefinition eq_vect V :=\n  match V with\n  | Affine0 => let e := [<0, 1>] in <[ e ]>%VS\n  | Affine eqV _ => eqV\n  end.\n\nDefinition affine V :=\n  if (@idP (is_sat V)) is ReflectT H then\n    Affine H\n  else Affine0.\n\nDefinition affine_of (phR : phant R) := affine : _ -> type_of phR.\n\nLemma eq_vectK : cancel eq_vect affine.\nProof.\nmove => V; rewrite /eq_vect.\ncase: V.\n- set e := [<0, 1>].\n  suff /negP h: ~~ (is_sat <[e]>).\n  rewrite /affine; case: {-}_/idP => //.\n  apply/is_satPn; move => x /=.\n  apply/negbTE/negP; move/satP/(_ _ (memv_line _)) => /= /eqP.\n  by rewrite vdot0l eq_sym oner_eq0.\n- move => V h; rewrite /affine.\n  case: {-}_/idP => // h'.\n  by apply/congr1/bool_irrelevance.\nQed.\n\nDefinition affine_eqMixin := (CanEqMixin eq_vectK).\nCanonical affine_eqType := EqType type affine_eqMixin.\nDefinition affine_choiceMixin := (CanChoiceMixin eq_vectK).\nCanonical affine_choiceType := ChoiceType type affine_choiceMixin.\n\nIdentity Coercion type_of_type : type_of >-> type.\nCanonical affine_of_eqType := [eqType of 'affine[R]].\nCanonical affine_of_choiceType := [choiceType of 'affine[R]].\n\nDefinition affine_pred_sort (S : type) : {pred 'cV[R]_n} :=\n  match S with\n  | Affine0 => pred0\n  | Affine eqV _ => sat eqV\n  end.\n\nEnd Core.\n\nModule Import Exports.\nCoercion affine_pred_sort : type >-> pred_sort.\nCanonical affine_eqType.\nCanonical affine_choiceType.\nCanonical affine_of_eqType.\nCanonical affine_of_choiceType.\nEnd Exports.\nEnd Core.\n\nExport Core.Exports.\nNotation \"''affine[' R ]_ n\" := (Core.type_of n (Phant R)).\nNotation \"''affine[' R ]\"    := 'affine[R]_(_).\nNotation \"''affine_' n\"      := 'affine[_]_n.\nNotation \"[ 'affine' I ]\"    := (@Core.affine_of _ _ (Phant _) I%VS).\nNotation \"'eq_vect'\"         := Core.eq_vect (at level 8).\n\nSection Specs.\n\nContext {R : realFieldType} {n : nat}.\n\nImplicit Type (x : 'cV[R]_n) (e : lrel[R]_n)\n         (U : {vspace lrel[R]_n}) (V : 'affine[R]_n)\n         (W : {vspace 'cV[R]_n}).\n\nDefinition affine0 : 'affine[R]_n := (Core.Affine0 _).\n\nLemma in_affine0 x : x \\in affine0 = false.\nProof.\nby [].\nQed.\n\nLemma affineN0 V :\n  reflect (exists x, x \\in V) (V != affine0).\nProof.\napply/(iffP idP).\n- by case: V => [/eqP //| U U_sat _]; apply/is_satP.\n- by case => x; apply/contraTneq => ->; rewrite in_affine0.\nQed.\n\nLemma in_affineE U x :\n  (x \\in [affine U]) = sat U x.\nProof.\nrewrite /Core.affine_of /Core.affine.\ncase: {-}_/idP => [// | /negP/is_satPn ->].\nby rewrite in_affine0.\nQed.\n\nLemma in_affineP {U x} :\n  reflect (forall e, e \\in U -> '[e.1, x] = e.2) (x \\in [affine U]).\nProof.\nrewrite in_affineE; exact: satP.\nQed.\n\nVariant affine_spec : 'affine[R]_n -> bool -> Type :=\n| Affine0 : affine_spec affine0 true\n| Affine U of (exists x, x \\in [affine U]) : affine_spec [affine U] false.\n\nLemma affineP V : affine_spec V (V == affine0).\nProof.\ncase: V => [| U U_sat].\n- rewrite eq_refl; constructor.\n- have ->: (Core.Affine U_sat) = [affine U].\n    rewrite /Core.affine_of /Core.affine; case: {-}_/idP => // ?.\n    apply/congr1; exact: bool_irrelevance.\n  suff h: exists x, x \\in [affine U].\n    have /negbTE ->: [affine U] != affine0 by apply/affineN0.\n    by constructor.\n  case/is_satP : U_sat => x x_in; exists x.\n  by rewrite in_affineE.\nQed.\n\nLemma affine_is_sat U :\n  [affine U] != affine0 = is_sat U.\nProof.\nrewrite /Core.affine_of /Core.affine; case: {-}_/idP.\n- move => is_sat; rewrite is_sat.\n  by apply/eqP.\n- move/negP/negbTE ->.\n  by rewrite eq_refl.\nQed.\n\nDefinition mk_affine W Ω : 'affine[R]_n :=\n  [affine ((be_lift Ω) @: W^OC)%VS].\n\nNotation \"[ 'affine' W & Ω ]\" := (mk_affine W Ω) : polyh_scope.\n\nLemma in_mk_affine W Ω x :\n  (x \\in [affine W & Ω]) = (x - Ω \\in W).\nProof.\napply/in_affineP/idP => [h|].\n- rewrite -[W]orthK; apply/orthvP => y.\n  move/(memv_img (be_lift Ω))/h; rewrite lfunE /= => /eqP.\n  by rewrite -subr_eq0 -vdotBr => /eqP.\n- rewrite -{1}[W]orthK => /orthvP h.\n  move => v /memv_imgP [{}v /h eq0 ->].\n  rewrite vdotBr in eq0.\n  by move/subr0_eq: eq0; rewrite lfunE /=.\nQed.\n\nLemma in_mk_affineP {W Ω x} :\n  reflect (exists2 d, d \\in W & x = Ω + d) (x \\in [affine W & Ω]).\nProof.\nrewrite in_mk_affine; apply/(iffP idP) => [?|[?? ->]].\n- by exists (x - Ω); last rewrite addrC subrK.\n- by rewrite addrC addKr.\nQed.\n\nLemma orig_affine W Ω : Ω \\in [affine W & Ω].\nProof.\nby rewrite in_mk_affine addrN mem0v.\nQed.\n\nLemma mk_affineN0 W Ω :\n  [affine W & Ω] != affine0.\nProof.\nby apply/affineN0; exists Ω; apply/orig_affine.\nQed.\n\nDefinition dir V :=\n  match affineP V with\n  | Affine0 => 0%VS\n  | Affine U _ => (befst @: U)^OC%VS\n  end.\n\nLemma dir0 : dir affine0 = 0%VS.\nProof.\nrewrite /dir.\nby case/affineP: affine0 (eq_refl (affine0 : 'affine[R]_n)).\nQed.\n\nLemma in_dirP V x :\n  x \\in V -> forall d, (d \\in dir V) = (x + d \\in V).\nProof.\nrewrite /dir; case/affineP: V; rewrite ?in_affine0 ?in_affine //.\nmove => U _ /in_affineP x_in d.\napply/idP/in_affineP.\n- move/orthvP => h v v_in_U.\n  move/(_ (befst v) (memv_img _ v_in_U)): h.\n  rewrite vdotDr lfunE => ->; rewrite addr0.\n  by apply/x_in.\n- move => h; apply/orthvP => c c_in.\n  pose e := (be_lift x) c.\n  have e_in_U: e \\in U.\n  + move/satP: x_in => /be_liftE <-.\n    by apply/memv_img.\n  move/(_ _ e_in_U): h.\n  rewrite vdotDr; move/(_ _ e_in_U): x_in ->.\n  move/(canRL (addKr _)); rewrite addNr.\n  by rewrite /e lfunE.\nQed.\n\nLemma dir_mk_affine W Ω :\n  dir [affine W & Ω] = W.\nProof.\napply/vspaceP => d.\nrewrite (in_dirP (orig_affine W Ω)) in_mk_affine.\nby rewrite addrAC addrN add0r.\nQed.\n\nLemma mk_affine_dir V x :\n  x \\in V -> V = [affine (dir V) & x].\nProof.\nrewrite /dir; case/affineP: V; rewrite ?in_affine0 //.\nmove => U _ x_in.\napply/congr1; rewrite orthK.\nby rewrite be_liftE //; rewrite in_affineE in x_in.\nQed.\n\nLemma dir_eq V V' x :\n  x \\in V -> x \\in V' -> dir V = dir V' -> V = V'.\nProof.\nby move => /mk_affine_dir {2}-> /mk_affine_dir {2}-> ->.\nQed.\n\nInductive mk_affine_spec : 'affine[R]_n -> {vspace 'cV[R]_n} -> Prop :=\n| MkAffine0 : mk_affine_spec affine0 0%VS\n| MKAffineN0 W Ω : mk_affine_spec [affine W & Ω] W.\n\nLemma mk_affineP V : mk_affine_spec V (dir V).\nProof.\ncase/affineP: V => [| U [x]].\n- rewrite dir0; constructor.\n- by move/mk_affine_dir => {1}->; constructor.\nQed.\n\nLemma affine_eqP V V' :\n  (V =i V') <-> (V = V').\nProof.\nsplit; last by move ->.\ncase/mk_affineP: V.\n- move => ext_eq.\n  apply/contraTeq: isT => /=.\n  rewrite eq_sym; case/affineN0 => x.\n  by rewrite -ext_eq; rewrite in_affine0.\n- move => W Ω ext_eq.\n  have Ω_in_V' : Ω \\in V'.\n  + by rewrite -ext_eq orig_affine.\n  apply/(dir_eq (orig_affine _ _)) => //.\n  apply/vspaceP => d.\n  rewrite (in_dirP Ω_in_V') dir_mk_affine -ext_eq in_mk_affine.\n  by rewrite addrAC addrN add0r.\nQed.\n\nDefinition affineI V V' :=\n  match affineP V, affineP V' with\n  | Affine0, _ => affine0\n  | _, Affine0 => affine0\n  | Affine U _, Affine U' _ => [affine (U + U')]\n  end.\n\nLemma in_affineI x V V' :\n  x \\in affineI V V' = (x \\in V) && (x \\in V').\nProof.\nrewrite /affineI.\ncase: (affineP V) => [| U _]; case: (affineP V') => [| U' _];\n  rewrite ?in_affine0 ?andbF //.\napply/in_affineP/andP => [x_in| [x_in x_in']].\n- by split; apply/in_affineP => e e_in; apply/x_in;\n    move: e_in; apply/subvP; rewrite ?addvSl ?addvSr.\n  (* TODO: add mem_addvl and mem_addvr statements  to vector.v *)\n- move => ? /memv_addP [e1 e1_in] [e2 e2_in] -> /=.\n  by rewrite vdotDl; apply: congr2; [apply/(in_affineP x_in) | apply/(in_affineP x_in')].\nQed.\n\nDefinition affine_le V V' := (V == affineI V V').\n\nLemma affine_leP {V V'} : reflect {subset V <= V'} (affine_le V V').\nProof.\napply/(iffP eqP).\n- move/affine_eqP => eq x.\n  by rewrite eq in_affineI => /andP[].\n- move => sub; apply/affine_eqP => x.\n  rewrite in_affineI.\n  by apply/idP/andP => [?|[] //]; split => //; apply/sub.\nQed.\n\nEnd Specs.\n\nNotation \"[ 'affine' W & Ω ]\" := (mk_affine W Ω) : polyh_scope.\n\nModule Order.\nSection Order.\n\nContext {R : realFieldType} {n : nat}.\n\nImplicit Type (V : 'affine[R]_n).\n\nLemma affine_le_refl : reflexive (@affine_le R n).\nProof.\nby move => ?; apply/affine_leP.\nQed.\n\nLemma affine_le_anti : antisymmetric (@affine_le R n).\nProof.\nmove => V V' /andP [/affine_leP sub /affine_leP sub'].\nby apply/affine_eqP => x; apply/idP/idP; [apply/sub | apply/sub'].\nQed.\n\nLemma affine_le_trans : transitive (@affine_le R n).\nProof. (* RK *)\nmove => ? ? ? /affine_leP subset1 /affine_leP subset2.\nby apply/affine_leP => ? ?; apply/subset2/subset1.\nQed.\n\nDefinition affine_LtPOrderMixin :=\n  LePOrderMixin (fun _ _ => erefl _) affine_le_refl affine_le_anti affine_le_trans.\n\nCanonical affine_POrderType :=\n  Eval hnf in POrderType polyh_display 'affine[R]_n affine_LtPOrderMixin.\n\nProgram Definition affine_bottomMixin :=\n  @BottomMixin polyh_display [porderType of 'affine[R]_n] affine0 _.\n\nNext Obligation.\nby apply/affine_leP => v; rewrite in_affine0.\nQed.\n\nProgram Canonical affine_PBOrderType :=\n  Eval hnf in BPOrderType 'affine[R]_n affine_bottomMixin.\n\nProgram Definition affine_meetMixin :=\n  @MeetMixin _ _ affineI _ _ _.\n\nNext Obligation.\nby move => V V'; apply/affine_eqP => x; rewrite !in_affineI andbC.\nQed.\n\nNext Obligation.\nby move => V1 V2 V3; apply/affine_eqP => x; rewrite !in_affineI andbA.\nQed.\n\nNext Obligation.\napply/affine_leP/eqP => [|<-].\n+ move=> le_xy; apply/affine_eqP=> c; rewrite in_affineI.\n  by apply: andb_idr; apply: le_xy.\n+ by move => c; rewrite in_affineI => /andP[].\nQed.\n\nCanonical affine_MeetSemilatticeType :=\n  Eval hnf in MeetSemilatticeType 'affine[R]_n affine_meetMixin.\n\nCanonical affine_bMeetSemilatticeType := [bMeetSemilatticeType of 'affine[R]_n].\nEnd Order.\n\nModule Import Exports.\nCanonical affine_POrderType.\nCanonical affine_PBOrderType.\nCanonical affine_MeetSemilatticeType.\nCanonical affine_bMeetSemilatticeType.\nEnd Exports.\nEnd Order.\n\nExport Order.Exports.\n\nNotation \"'[' 'affine0' ']'\" := affine0.\n\nSection BasicObjects.\n\nContext {R : realFieldType} {n : nat}.\n\nImplicit Type (Ω d : 'cV[R]_n) (e : lrel[R]_n)\n         (U : {vspace lrel[R]_n}) (V : 'affine[R]_n).\n\nLemma affineS :\n  {homo (@Core.affine _ _: {vspace lrel[R]_n} -> 'affine[R]_n) : U V / (U <= V)%VS >-> (U `>=` V)}.\nProof. (* RK *)\nmove => ? ? /subvP Hsubset; apply/affine_leP => ?.\nmove/in_affineP => Hin_affime.\napply/in_affineP =>  ? ?.\nby apply/Hin_affime/Hsubset.\nQed.\n\nLemma dir_affine U :\n  [affine U] `>` [affine0] -> dir [affine U] = (befst @: U)^OC%VS.\nProof. (* RK *)\nmove/andP => [? _].\nhave aff_U_neq0: exists x : 'cV_n, x \\in [affine U] by apply/affineN0.\nmove: aff_U_neq0 => [? in_aff_U].\napply/vspaceP => d; rewrite (in_dirP in_aff_U).\napply/idP/orthvP => [/in_affineP in_aff ? /memv_imgP [u u_in_U] ->| H].\n- rewrite lfunE /=; move/eqP: (in_aff _ u_in_U).\n  by rewrite vdotDr ((in_affineP in_aff_U) _ u_in_U) -subr_eq0 [X in X-_]addrC -addrA subrr addr0 => /eqP <-.\n- apply/in_affineP => u u_in_U.\n  rewrite vdotDr ((in_affineP in_aff_U) _ u_in_U).\n  suff ->: '[ u.1, d] = 0 by rewrite addr0.\n  by apply/H/memv_imgP; exists u; [exact: u_in_U | rewrite lfunE].\nQed.\n\n\nLemma affine_proper0P V :\n  reflect (exists x, x \\in V) (V `>` [affine0]).\nProof.\nrewrite lt0x; exact: affineN0.\nQed.\n\nLemma mk_affine_proper0 Ω W :\n  [affine W & Ω] `>` [affine0].\nProof.\napply/affine_proper0P; exists Ω; exact: orig_affine.\nQed.\n\nLemma mk_affineS Ω : { mono (mk_affine^~ Ω) : W W' / (W <= W')%VS >-> (W `<=` W') }.\nProof. (* RK *)\nmove => ? ?; apply/affine_leP/subvP => [Hsubset w ? | Hsubset ?].\n- rewrite -[w]addr0 -(subrr Ω) addrA -in_mk_affine addrC.\n  by apply/Hsubset/in_mk_affineP; exists w.\n- by rewrite !in_mk_affine; apply: Hsubset.\nQed.\n\nLemma dirS V V' : (V `<=` V') -> (dir V <= dir V')%VS.\nProof. (* RK *)\ncase/affineP: V => [_  |U [? Hin_affine] /affine_leP Hsubset];\n  rewrite ?dir0 ?sub0v //.\nby apply/subvP => ?; rewrite (in_dirP Hin_affine) (in_dirP (Hsubset _ Hin_affine)); apply/Hsubset.\nQed.\n\nLemma affine_mono U U' :\n  [affine U] `>` [affine0] -> [affine U] `<=` [affine U'] = (U' <= U)%VS.\nProof.\nmove => U_neq0.\napply/idP/idP; last by apply/affineS.\nmove => U_sub_U'.\nhave U'_neq0: [affine U'] `>` [affine0] by apply/lt_le_trans: U_sub_U'.\nmove/dirS: (U_sub_U'); rewrite ?dir_affine // orthS.\ncase/affine_proper0P : U_neq0 => x x_in_U.\nhave x_in_U' : x \\in [affine U'] by apply/(affine_leP U_sub_U').\nby move/(limgS (be_lift x)); rewrite ?be_liftE -?in_affineE.\nQed.\n\nNotation \"'[' 'hp' e  ']'\" := [affine <[e]> ].\n\nLemma in_hp :\n  (forall e x, (x \\in [hp e]) = ('[e.1,x] == e.2))\n  * (forall c α (x : 'cV[R]_n), (x \\in [hp [<c, α>]]) = ('[c,x] == α)).\nProof. (* RK *)\nsplit => [ e x | c α x]; apply/in_affineP/idP => [in_hp | /eqP in_hp ? /vlineP [?] ->];\n  rewrite ?vdotZl ?in_hp ?memv_line //.\nby apply/eqP/(in_hp [<c, α>])/memv_line.\nQed.\n\nLemma hpN (e : lrel[R]_n) : [hp -e] = [hp e].\nProof.\nby apply/affine_eqP => x; rewrite !in_hp /= vdotNl eqr_opp.\nQed.\n\nLemma be_lift_hp (x : 'cV[R]_n) (e : lrel[R]_n) :\n  x \\in [hp e] -> (be_lift x (befst e)) = e.\nProof.\nrewrite lfunE /= /be_lift0 lfunE /=.\nby rewrite in_hp => /eqP ->; rewrite beE.\nQed.\n\nLemma affineS1 (U : {vspace lrel[R]_n}) e :\n  e \\in U -> ([affine U] `<=` [hp e]).\nProof. (* RK *)\nby apply/affineS.\nQed.\n\nDefinition affineT : 'affine[R]_n := [hp 0].\n\nNotation \"'[' 'affineT' ']'\" := affineT : polyh_scope.\n\nLemma in_affineT x : x \\in affineT = true.\nProof.\nby rewrite in_hp vdot0l eq_refl.\nQed.\n\nLemma dir_affineT : dir affineT = fullv.\nProof.\nhave nullv_in_affineT : 0 \\in affineT by rewrite in_affineT.\nby apply/vspaceP => ?; rewrite memvf (in_dirP nullv_in_affineT) in_affineT.\nQed.\n\nProgram Definition affine_topMixin :=\n  @TopMixin polyh_display [porderType of 'affine[R]_n] affineT _.\n\nNext Obligation. by apply/affine_leP=> ? _; rewrite in_affineT. Qed.\n\nCanonical affine_tPOrderType := TPOrderType 'affine[R]_n affine_topMixin.\nCanonical affine_tbPOrderType := [tbPOrderType of 'affine[R]_n].\n\nCanonical affine_tMeetSemilatticeType := [tMeetSemilatticeType of 'affine[R]_n].\nCanonical affine_tbMeetSemilatticeType := [tbMeetSemilatticeType of 'affine[R]_n].\n\nLemma in_big_affineIP (I : finType) (P : pred I) (F : I -> 'affine[R]_n) x :\n  reflect (forall i : I, P i -> x \\in (F i)) (x \\in \\meet_(i | P i) (F i)).\nProof.\napply: (iffP idP) => [? i Pi | x_in_F].\n- by apply: (affine_leP (meets_inf F Pi)).\n- elim/big_rec: _ => [|i V Pi ?]; first by rewrite in_affineT.\n  by rewrite in_affineI; apply/andP; split; [apply: (x_in_F i) | done].\nQed.\n\nLemma in_big_affineI (I : finType) (P : pred I) (F : I -> 'affine[R]_n) x :\n  (x \\in \\meet_(i | P i) (F i)) = [forall i, P i ==> (x \\in F i)].\nProof. (* RK *)\napply/in_big_affineIP/idP.\n- by move => Hforall; apply/forallP => i; apply/implyP/Hforall.\n- by move/forallP => Hforall i; apply/implyP/Hforall.\nQed.\n\nLemma affine_span (I : base_t[R,n]) :\n  [affine <<I>>] = \\meet_(e : I) [hp (val e)].\nProof. (* RK *)\napply/affine_eqP => x.\nrewrite in_affineE.\napply/idP/idP => [/satP sat_I | /in_big_affineIP in_all_hps].\n- apply/in_big_affineIP => i _; rewrite (fst (in_hp)).\n  by apply/eqP/(sat_I (val i))/memv_span/valP.\n- apply/satP => e e_in.\n  rewrite (coord_span e_in) sum_lrel_fst sum_lrel_snd vdot_sumDl /=.\n  apply: eq_bigr => i _.\n  have in_enum_fset_I: (I`_i) \\in (enum_fset I) by apply/memt_nth.\n  rewrite vdotZl; apply/congr1/eqP; rewrite -(fst (in_hp)).\n  by apply: (in_all_hps (FSetSub in_enum_fset_I)).\nQed.\n\nLemma affine_vbasis (U : {vspace lrel[R]_n}) :\n  let base := [fset e in ((vbasis U) : seq _)]%fset : {fset lrel[R]_n} in\n  [affine U] = [affine << base >>].\nProof.\nset base := [fset e in ((vbasis U) : seq _)]%fset : {fset lrel[R]_n}.\nsuff ->: U = << base >>%VS by [].\nmove: (vbasisP U) => /andP [/eqP <- _].\napply/subv_anti/andP; split; apply/sub_span; by move => ?; rewrite inE.\nQed.\n\nNotation \"'[' 'line' d & Ω ']'\" := [affine <[d]> & Ω].\n\nLemma in_lineP {d Ω x : 'cV[R]_n} :\n  reflect (exists μ, x = Ω + μ *: d) (x \\in [line d & Ω]).\nProof.\napply/(iffP in_mk_affineP) => [[y /vlineP [μ ->]]| [μ ->] ].\n+ by exists μ.\n+ by exists (μ *: d); rewrite ?memvZ ?memv_line.\nQed.\n\nLemma line_subset_hp e v v' :\n  (v \\in [hp e]) -> (v' \\in [hp e]) -> ([line (v' - v) & v] `<=` [hp e]).\nProof.\nrewrite !in_hp => /eqP v_in /eqP v'_in.\napply/affine_leP => ? /in_lineP [μ -> ]; rewrite in_hp.\nby rewrite vdotDr vdotZr vdotBr v_in v'_in addrN mulr0 addr0.\nQed.\n\nNotation \"'[' 'pt' Ω ']'\" := [affine 0%VS & Ω].\n\nLemma in_pt Ω x : (x \\in [pt Ω]) = (x == Ω).\nProof.\nby rewrite in_mk_affine memv0 subr_eq0.\nQed.\n\nEnd BasicObjects.\n\nNotation \"'[' 'hp' e  ']'\" := [affine <[e]> ] : polyh_scope.\nNotation \"'[' 'line' d & Ω ']'\" := [affine <[d]> & Ω] : polyh_scope.\nNotation \"'[' 'pt' Ω ']'\" := [affine 0%VS & Ω] : polyh_scope.\nNotation \"'[' 'affineT' ']'\" := (@affineT _ _) : polyh_scope.\n\nSection Dimension.\n\nContext {R : realFieldType} {n : nat}.\n\nImplicit Type (V : 'affine[R]_n) (U : {vspace lrel[R]_n}).\n\nDefinition adim V :=\n  if V == [affine0] then 0%N\n  else (\\dim (dir V)).+1%N.\n\nLemma adim0 : adim [affine0] = 0%N.\nProof.\nby rewrite /adim ifT //.\nQed.\n\nLemma adimN0 V : (adim V > 0)%N = (V `>` affine0).\nProof.\nby rewrite /adim; case: ifP => [/eqP -> // |]; rewrite lt0x => ->.\nQed.\n\nLemma adim_eq0 V : adim V = 0%N -> V = [affine0].\nProof.\nby rewrite /adim; case: ifP => [/eqP ->|].\nQed.\n\nLemma adimN0_eq V : V `>` [affine0] -> adim V = (\\dim (dir V)).+1%N.\nProof.\nby rewrite lt0x /adim => /negbTE ->.\nQed.\n\nLemma adimS : {homo adim : V V' / (V `<=` V') >-> (V <= V')%N}.\nProof.\nmove => V V' sub.\nrewrite /adim; case: ifPn => // V_neq0.\nhave V'_neq0: V' != [affine0].\n- move: V_neq0; apply/contra_neq => V'_eq0.\n  by rewrite V'_eq0 lex0 in sub; move/eqP: sub.\nrewrite ifF ?ltnS; last by apply/negbTE.\nby apply/dimvS/dirS.\nQed.\n\nLemma adim_leqif_eq V V' :\n  (V `<=` V') -> (adim V <= adim V' ?= iff (V == V'))%N.\nProof.\nmove => V_sub_V'; split; rewrite ?adimS //.\napply/eqP/eqP; last by move => ->.\nrewrite {1}/adim; case: ifP.\n- by move/eqP ->; symmetry; apply/adim_eq0.\n- move/negbT => V_neq0.\n  have V'_neq0: V' != [affine0].\n    rewrite -!lt0x in V_neq0 *.\n    by apply/lt_le_trans: V_sub_V'.\n  rewrite /adim ifF; last by apply/negbTE.\n  move/succn_inj => adim_dir_eq.\n  suff: dir V = dir V'.\n  - case/affineN0: V_neq0 => x x_in.\n    by apply/(dir_eq x_in)/(affine_leP V_sub_V').\n  - by apply/eqP; rewrite -(eq_leqif (dimv_leqif_eq (dirS _))) ?adim_dir_eq.\nQed.\n\nLemma sub_geq_adim V V' :\n  (V `<=` V') -> (adim V >= adim V')%N -> V = V'.\nProof. (* RK *)\nmove => V_sub_V' adimV_gte_adimV'; apply/eqP/contraT => V_neq_V'.\nby move/leqifP: (adim_leqif_eq V_sub_V'); rewrite ifF;\n  [rewrite ltnNge adimV_gte_adimV' | apply/negbTE].\nQed.\n\nLemma sub_eq_adim V V' :\n  (V `<=` V') -> adim V = adim V' -> V = V'.\nProof. (* RK *)\nmove => ? adimV_eq_adimV'.\nby apply/sub_geq_adim; [done | rewrite adimV_eq_adimV'].\nQed.\n\nLemma adim_affine_lt V V' :\n  (V `<` V') -> (adim V < adim V')%N.\nProof. (* RK *)\nmove/andP => [V'_neq_V ?].\nrewrite ltn_neqAle; apply/andP; split; last by apply/adimS.\nmove: V'_neq_V; apply/contra_neqN => /eqP ?; symmetry.\nby apply/sub_eq_adim.\nQed.\n\nLemma adim_line Ω d : adim [line d & Ω] = (d != 0).+1.\nProof.\nrewrite /adim ifF; last by apply/negbTE/mk_affineN0.\nby rewrite dir_mk_affine dim_vline.\nQed.\n\nLemma affine_addv U U' :\n  [affine (U + U')] = [affine U] `&` [affine U'].\nProof.\napply/affine_eqP=> x; rewrite in_affineI.\napply/in_affineP/andP.\n- by move=> x_in_UU'; split; apply/in_affineP => e e_in;\n     apply: x_in_UU'; apply/subvP: e_in; rewrite ?addvSl ?addvSr.\n- case=> /in_affineP x_in_U /in_affineP x_in_U' e /memv_addP.\n  case=> [e0 e0_in_U] [e1 e1_in_U'] -> /=.\n  by rewrite vdotDl; apply: congr2; by [exact: x_in_U | exact: x_in_U'].\nQed.\n\nLemma dim_affineI V e :\n  let V' := V `&` [hp e] in\n  ~~ (V `<=` [hp e]) -> V' `>` [affine0] ->\n  adim V = (adim V').+1%N.\nProof.\ncase/affineP: V; rewrite ?le0x // => [U] _ /= U_subN_e V'_prop0.\nhave [U_prop0 e_prop0]:\n  ([affine0] `<` [affine U]) /\\ ([affine0] `<` [hp e]).\n- by split; apply: (lt_le_trans V'_prop0); rewrite ?leIl ?leIr.\nhave e_notin: (befst e \\notin befst @: U)%VS.\n- move: U_subN_e; apply: contraNN.\n  case/affine_proper0P: V'_prop0 => x.\n  rewrite in_affineI => /andP [x_in_U x_in_e].\n  move/(memv_img (be_lift x)).\n  rewrite be_liftE -?in_affineE ?be_lift_hp //.\n  exact: affineS.\nrewrite -affine_addv in V'_prop0 *.\nrewrite ?adimN0_eq ?dir_affine //; apply congr1; rewrite !dim_orthv.\nmove/dir_affine: V'_prop0.\nrewrite limgD limg_line.\nmove/(canLR orthK)/(congr1 (@dimv _ _)).\nrewrite dim_add_line // => dim_eq.\nby rewrite subnSK -?dim_eq ?dim_leqn.\nQed.\n\nLemma adim_pt Ω : adim [pt Ω] = 1%N.\nProof.\nby rewrite adim_line eq_refl.\nQed.\n\nLemma dimv_eq1P (K : fieldType) (vT : vectType K) (V : {vspace vT}) :\n  reflect (exists2 v, v != 0 & V = <[v]>%VS) (\\dim V == 1%N).\n(* TODO: move to extra_vector.v *)\nProof.\napply/(iffP idP) => [/eqP dim_V_eq1 |[? neq0 ->]];\n  last by rewrite dim_vline neq0.\nhave : ~~ (V <= 0)%VS.\n  move: dim_V_eq1; apply/contra_eqN.\n  by rewrite subv0; move/eqP => ->; rewrite dimv0.\nmove/subvPn => [v ? v_not_in_V].\nexists v; first by move: v_not_in_V; apply/contra; rewrite memv0.\napply/eqP; rewrite eqEsubv; apply/andP; split;\n  last by rewrite -memvE.\nsuff ->: (V = <[v]>)%VS by done.\napply/eqP; rewrite eq_sym eqEdim; apply/andP; split;\n  first by rewrite -memvE.\nsuff ->: \\dim <[v]> = 1%N by rewrite dim_V_eq1.\nrewrite memv0 in v_not_in_V.\nby rewrite dim_vline v_not_in_V.\nQed.\n\nLemma adim2P V :\n  adim V = 2%N -> exists Ω, exists2 d, d != 0 & V = [line d & Ω].\nProof. (* RK *)\nmove => adim_V_eq2.\nhave V_neq0 : V != affine0.\n  apply/contraT => V_eq0; rewrite negbK in V_eq0.\n  by rewrite (eqP V_eq0) adim0 in adim_V_eq2.\nhave dim_dir_V_eq1: (\\dim (dir V)) = 1%N\n  by apply/eq_add_S; rewrite /adim ifF // in adim_V_eq2; apply/negbTE.\nmove/eqP/dimv_eq1P: (dim_dir_V_eq1) => [d ? dir_V_eq].\nmove/affineN0: V_neq0 => [Ω Ω_in_V].\nexists Ω; exists d; first by done.\nby rewrite -dir_V_eq; apply/mk_affine_dir.\nQed.\n\nLemma adim1P V :\n  adim V = 1%N -> exists Ω, V = [pt Ω].\nProof. (* RK *)\nmove => adim_V_eq1.\nhave V_neq0 : V != affine0.\n  apply/contraT => V_eq0; rewrite negbK in V_eq0.\n  by rewrite (eqP V_eq0) adim0 in adim_V_eq1.\nmove: (affineN0 _ V_neq0) => [Ω Ω_in_V].\nexists Ω.\nsuff <-: (dir V) = 0%VS by apply/mk_affine_dir.\napply/eqP; rewrite -dimv_eq0.\nby apply/eqP/eq_add_S; rewrite /adim ifF // in adim_V_eq1; apply/negbTE.\nQed.\n\nLemma adim_leSn V :\n  (adim V <= n.+1)%N.\nProof. (* RK *)\nrewrite /adim; case: (boolP (V == affine0)) => [_|_]; first by done.\nrewrite ltnS.\nby apply/(@leq_trans (n * 1)); [apply/rank_leq_col | rewrite muln1].\nQed.\n\nLemma dim_affine_le (U : {vspace lrel[R]_n}) :\n  [affine U] `>` [affine0] -> (\\dim U <= n)%N.\nProof. (* RK *)\napply/contraTT; rewrite -ltnNge lt0x negbK => dimU.\nhave {dimU} -> : U = fullv\n  by apply/eqP; rewrite eqEdim; apply/andP; split;\n    [exact: subvf | rewrite dimvf /Vector.dim /= addn1].\napply/eqP/affine_eqP => x; rewrite in_affine0; apply/negbTE/negP.\npose e := [<0, 1>]: lrel[R]_n.\nhave e_in_U: e \\in fullv by rewrite memvf.\nmove/in_affineP/(_ _ e_in_U); rewrite vdot0l /= => /esym/eqP.\nby rewrite oner_eq0.\nQed.\n\nLemma adimT : (adim affineT = n.+1)%N.\nProof. (* RK *)\nrewrite /adim ifF.\n- by rewrite dir_affineT dimvf /Vector.dim /= muln1.\n- apply/(contraFF _ (erefl false)).\n  move/eqP/affine_eqP => aff_eq.\n  by move: (aff_eq 0); rewrite in_affine0 in_affineT.\nQed.\n\nLemma adimTP V : adim V = n.+1%N -> V = affineT.\nProof. (* RK *)\nrewrite -adimT => ?.\napply/sub_eq_adim; last by done.\nby apply/affine_leP => ?; rewrite in_affineT.\nQed.\n\nLemma adim_hp e :\n  [hp e] `>` [affine0] -> adim [hp e] = ((e.1 == 0%R) + n)%N.\nProof. (* RK *)\nmove => hp_neq0.\nrewrite /adim ifF; last by apply/negbTE; move/andP: hp_neq0 => [? _].\ncase: (boolP (e.1 == 0)) => [/eqP e1_eq0 | e1_neq0].\n- suff ->: [hp e] = affineT\n    by rewrite dir_affineT dimvf /Vector.dim /= muln1 add1n.\n  apply/affine_eqP => ?; rewrite in_affineT in_hp e1_eq0 vdot0l.\n  move/affineN0: (proj1 (andP hp_neq0)) => [?].\n  by rewrite in_hp e1_eq0 vdot0l => ?.\n- case: (boolP (0 < n)%N) => [? | n_eq0].\n  + rewrite /adim (dir_affine hp_neq0) dim_orthv.\n    have ->: ((befst @: <[e]>) = <[e.1]>)%VS\n      by rewrite limg_line lfunE.\n    rewrite dim_vline e1_neq0 add0n subn1.\n    by apply/prednK.\n  + rewrite -eqn0Ngt in n_eq0.\n    rewrite extra_matrix.col_neq_0 in e1_neq0.\n    move/existsP: e1_neq0 => [i _].\n    by rewrite (eqP n_eq0) in i; move: (ord0_false i).\nQed.\n\nLemma subset_hp (V : {fset 'cV[R]_n}) :\n  (0 < #|` V | <= n)%N ->\n  exists2 e : lrel[R]_n, (e.1 != 0) & {subset V <= [hp e]}.\nProof.\nrewrite cardfs_gt0 => /andP [/fset0Pn [v v_in] cardV_le].\npose U := <<[seq w - v | w <- (V `\\ v)%fset]>>%VS.\nhave: ((\\dim U).+1 <= n)%N.\n- apply/leq_trans: cardV_le.\n  have ->: #|` V| = #|` (V `\\  v)|%fset.+1%N by rewrite (@cardfsD1 _ v) v_in.\n  rewrite ltnS; apply/(leq_trans (dim_span _)).\n  by rewrite size_map.\nrewrite -subn_gt0 -dim_orthv lt0n dimv_eq0 => h.\npose c := vpick (U^OC)%VS.\npose e := [< c, '[c,v] >]; exists e; first by rewrite vpick0.\nmove => w; case/altP : (w =P v) => [-> _| w_neq_v w_in_V].\n- by rewrite in_hp.\n- rewrite in_hp /=.\n  have ->: w = v + (w - v) by rewrite addrCA addrN addr0.\n  rewrite vdotDr; suff ->: '[c, w-v] = 0 by rewrite addr0.\n  rewrite vdotC; apply/(orthvP (V := U)); first exact: memv_pick.\n  by rewrite memv_span //; apply/map_f; rewrite !inE w_neq_v.\nQed.\n\nEnd Dimension.\n", "meta": {"author": "Coq-Polyhedra", "repo": "Coq-Polyhedra", "sha": "bcf68b3baf5b4a39d5ef61fa92ca36f14c5b0e51", "save_path": "github-repos/coq/Coq-Polyhedra-Coq-Polyhedra", "path": "github-repos/coq/Coq-Polyhedra-Coq-Polyhedra/Coq-Polyhedra-bcf68b3baf5b4a39d5ef61fa92ca36f14c5b0e51/theories/affine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2967118357622337}}
{"text": "Require Import ExtLib.Structures.Monads.\nRequire Import ExtLib.Structures.Maps.\nRequire Import ExtLib.Structures.Reducible.\nRequire Import ExtLib.Core.RelDec.\nRequire Import ExtLib.Data.Lists.\nRequire Import String.\nRequire Import List.\nRequire Import Strings.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nModule ExtractTypes.\n  Require Import CoqCompile.Lambda.\n  Import MonadNotation.\n  Local Open Scope monad_scope.\n\n  Definition type : Type := nat.\n\n  (** Function returns:\n   ** 1) map from constructor to arity and type\n   ** 2) map of types to constructors \n   **)\n\n  Section using_maps.\n    Variable map_ctor : Type -> Type.\n    Variable map_type : Type -> Type.\n    Context {Map_ctor : DMap Lambda.constructor map_ctor}.\n    Context {FMap_ctor : forall x, Reducible (Lambda.constructor * x) (map_ctor x)}.\n    Context {Map_type : DMap type map_type}.\n\n    Section monadic.\n      Variable m : Type -> Type.\n      Variable Monad_m : Monad m.\n      Context {State_types : MonadState (map_type (list Lambda.constructor))  m}.\n      Context {State_ctors : MonadState (map_ctor (nat * type))  m}.\n      Context {State_fresh : MonadState (type) m}.\n      Context {Exc_error : MonadExc string m}.\n\n      Definition fresh_type : m type :=\n        x <- MonadState.get (MonadState := State_fresh) ;;\n        put (S x) ;;\n        ret x.\n\n      Definition newCtor (ctor : Lambda.constructor) (arity : nat) : m type :=\n        x <- MonadState.get (MonadState := State_ctors) ;;\n        match Maps.lookup ctor x with\n          | None => \n            t <- fresh_type ;;\n            put (Maps.add ctor (arity, t) x) ;;\n            y <- MonadState.get (MonadState := State_types) ;;\n            put (Maps.add t (ctor :: nil) y) ;;\n            ret t\n          | Some (arity', t) =>\n            if eq_dec arity arity' then\n              ret t\n            else\n              raise (\"Found constructor '\" ++ ctor ++ \"' inconsistent arities: \" ++ nat2string10 arity ++ \" and \" ++ nat2string10 arity')%string\n        end.\n\n      Definition mergeTypes' (t1 t2 : type) : m type :=\n        map <- MonadState.get (MonadState := State_types) ;;\n        match Maps.lookup t1 map with\n          | None => ret t2\n          | Some ctors => \n            iterM (fun ctor => \n              map' <- MonadState.get (MonadState := State_ctors) ;;\n              match Maps.lookup ctor map' with\n                | None => raise \"type constructor not found\"%string\n                | Some (arity, t) =>\n                  put (Maps.add ctor (arity, t2) map')\n              end\n              ) ctors ;;\n            let map' := Maps.remove t1 map in\n            match Maps.lookup t2 map' with\n              | None => raise \"type constructor not found\"%string\n              | Some ctors' => \n                put (Maps.add t2 (ctors++ctors') map') ;;\n                ret t2\n            end\n        end.\n\n      Definition mergeTypes (t1 t2 : type) : m type :=\n        if eq_dec t1 t2 then ret t1 else mergeTypes' t1 t2.\n\n      Definition newType (ctors : list (Lambda.constructor * nat)) (closed : bool) : m type :=\n        ts <- mapM (fun x : Lambda.constructor * nat => newCtor (fst x) (snd x)) ctors ;;\n        match ts with\n          | nil => fresh_type\n          | t::ts => foldM (fun a b => mergeTypes a b) (ret t) ts \n        end.\n        \n      (** This function will extract types and arity of construcors \n       ** from a Lambda.exp\n       **)\n      Fixpoint extract' (e : Lambda.exp) : m unit :=\n        match e with\n          | Lambda.Var_e _ => ret tt\n          | Lambda.Lam_e _ e => extract' e\n          | Lambda.App_e l r => extract' l ;; extract' r\n          | Lambda.Let_e _ l r => extract' l ;; extract' r\n          | Lambda.Con_e c ls => \n            mapM extract' ls ;;\n            newCtor c (length ls) ;;\n            ret tt\n          | Lambda.Match_e e arms =>\n            extract' e ;;\n            mapM (fun x => extract' (snd x)) arms ;;\n            let res := \n              List.fold_left (fun acc arm => \n                let '(ctors, closed) := acc in\n                  match fst arm with\n                    | Lambda.Var_p _ => (ctors, false)\n                    | Lambda.Con_p c ls =>\n                      ((c, length ls) :: ctors, closed)\n                  end) arms (nil, true)\n            in\n            if eq_dec 0 (length (fst res)) then\n              ret tt\n            else \n              newType (fst res) (snd res) ;;\n              ret tt\n          | Lambda.Letrec_e ds b =>\n            mapM (fun x => extract' (snd (snd x))) ds ;;\n            extract' b\n        end.\n      End monadic.\n\n      Require Import ExtLib.Data.Monads.EitherMonad.\n      Require Import ExtLib.Data.Monads.StateMonad.\n\n      Definition m : Type -> Type :=\n        eitherT string (stateT (map_type (list Lambda.constructor)) (stateT (map_ctor (nat * type)) (state type))).\n\n      Definition init_types : map_type (list Lambda.constructor) :=\n        Maps.add 0 (\"True\"::\"False\"::nil)%string Maps.empty.\n\n      Definition init_ctors : map_ctor (nat * type) :=\n        Maps.add \"True\"%string (0,0) (Maps.add \"False\"%string (0,0) Maps.empty).\n\n      Definition runM T (cmd : m T) : string + (map_type (list Lambda.constructor) * map_ctor (nat * type)) :=\n        let res := (runState (runStateT (runStateT (unEitherT cmd) init_types) init_ctors) 1) in\n          match res with\n            | (either, mctor, mtyp, _) => \n              match either with\n                | inl str => inl str\n                | inr _ => inr (mctor, mtyp)\n              end\n          end.\n\n      Definition extract (e:Lambda.exp) : string + (map_type (list Lambda.constructor) * map_ctor (nat * type)) :=\n        runM (@extract' m _ _ _ _ _ e).\n\n    End using_maps.\n\nEnd ExtractTypes.", "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/ExtractTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2967118357622337}}
{"text": "Require Import Raft.\nRequire Import RaftRefinementInterface.\nRequire Import RefinementCommonDefinitions.\n\nSection PrevLogCandidateEntriesTermInterface.\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 prevLog_candidateEntriesTerm (net : network) :=\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      0 < prevLogTerm ->\n      candidateEntriesTerm prevLogTerm (nwState net).\n\n  Class prevLog_candidateEntriesTerm_interface : Prop :=\n    {\n      prevLog_candidateEntriesTerm_invariant :\n        forall net,\n          refined_raft_intermediate_reachable net ->\n          prevLog_candidateEntriesTerm net\n    }.\nEnd PrevLogCandidateEntriesTermInterface.", "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/PrevLogCandidateEntriesTermInterface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.29670206685186795}}
{"text": "(***************************************************************)\n(* Basci Coq lib                                               *)\n(***************************************************************)\nRequire Import Omega.\nRequire Export ZArith.\nRequire Export Znumtheory.\nRequire Export List.\nRequire Export Bool.\n\n(* *********************************************************************** *)\n(** * The [skip] tactic from Stephanie Weirich and Brian Andemir of UPenn  *)\n\n(** The [skip] tactic will prove any goal, since we assert below that\n    [False] is provable.  This is a useful technique for skipping over\n    troublesome parts of proofs.  In a complete development, one would\n    comment out the [skip] axiom and tactic.\n\n    In the exercises below, [skip] lets us give partial proofs by\n    using it as a placeholder for locations in the proof script where\n    the reader should fill in the proof.\n*)\n(* Axiom false_false : forall P, P. *)\n(* Ltac skip := apply false_false. *)\n(* *)\n\n(** Section 1: optionT and pairT **)\n(*\nAxiom extensionality:\n  forall (A B: Set) (f g : A -> B),\n  (forall x, f x = g x) -> f = g.\n*)\nInductive OptionT (T : Type) : Type :=\n    NoneT1 : OptionT T\n  | SomeT1 : T -> OptionT T.\n\nInductive optionT (A : Type) : Type :=\n  | SomeT : A -> optionT A\n  | NoneT : optionT A.\n\n Arguments SomeT [A].\n Arguments NoneT [A].\n\nNotation opt_predT :=\n  (fun opt:optionT _ => \n    fun f =>\n      match opt with\n\t| SomeT t => f t\n\t| NoneT => False\n      end).\n\nNotation optpT :=\n  (fun f => fun opt:optionT _ => \n    match opt with\n      | SomeT t => f t\n      | NoneT => False\n    end).\n\nNotation optgT :=\n  (fun f => fun opt:optionT _ =>\n    fun t' =>\n      match opt with\n        | SomeT t => f t t'\n        | NoneT => False\n      end).\n\nNotation opt_predT2 :=\n  (fun opt:optionT _ => \n    fun opt':optionT _ => \n      fun f =>\n\tmatch opt, opt' with\n\t  | SomeT t, SomeT t' => f t t'\n\t  | _, _ => False\n\tend).\n\nInductive prodT (A : Set) (B : Type) : Type :=\n    pairT : A -> B -> prodT A B.\n\nArguments pairT [A B].\n\nNotation \"( x , y , .. , z )\" :=\n  (pairT .. (pairT x y) .. z) : t_type_scope.\n\n(** Section 2: Tactics **)\n(***************************************************************)\n\nLtac hypreplace H y :=\n  let H' := fresh in\n    (assert (H' := y); try (clear H; rename H' into H)).\n\nLtac hypreplace2 H y Hn:=\n  let H' := fresh in\n    (assert (H' := y); try (clear H; rename H' into Hn)).\n\nTactic Notation \"substH\" hyp (H) :=\n  match goal with\n    | |- ?a -> ?b => clear H; intro H\n    | |- _ => fail 1 \"goal must be 'A -> B'.\"\n  end.\n\nTactic Notation \"substH\" hyp (H) \"with\" constr (t) := \n  hypreplace H t.\n\nTactic Notation \"substH\" hyp (H) \"with\" constr (t) \"into\" ident (Hn) := \n  hypreplace2 H t Hn.\n\nTactic Notation \"bool_destruct\" hyp (H) \"as\" simple_intropattern (pat) :=\n  let H0 := fresh \"H\" in\n    (rename H into H0;\n    match type of (H0) with\n      | (andb ?a ?b = true) => \n        destruct (andb_prop a b H0) as pat; clear H0\n      | (orb ?a ?b = true) =>\n        destruct (orb_prop a b H0) as pat; clear H0\n      | _ => fail \"not destructable\" \n    end).\n\n\nTactic Notation \"destructH\" hyp (H) \"with\" constr (t) :=\n  destruct t; clear H.\n\nTactic Notation \"destructH\" hyp (H) \"with\" constr (t)\n  \"as\" simple_intropattern (p) :=\n  destruct t as p; clear H.\n  \nTactic Notation \"discri\" :=\n  match goal with\n    | H : ?a <> ?a |- _ => \n      elimtype False; apply H; reflexivity\n    | |- _ -> _ => intros; discriminate\n    | H : False |- _ => destruct H\n    | _ => discriminate\n  end.\n\nTactic Notation \"gen_clear\" hyp (H) :=\n  generalize H; clear H.\n\nTactic Notation \"gen_clear\" hyp (H1) hyp (H2) :=\n  generalize H1 H2; clear H1 H2.\n\nTactic Notation \"gen_clear\" \n  hyp (H1) hyp (H2) hyp (H3) :=\n  generalize H1 H2 H3; clear H1 H2 H3.\n\nTactic Notation \"gen_clear\" \n  hyp (H1) hyp (H2) hyp (H3) hyp (H4) :=\n  generalize H1 H2 H3 H4; \n    clear H1 H2 H3 H4.\n\nTactic Notation \"gen_clear\" \n  hyp (H1) hyp (H2) hyp (H3) \n  hyp (H4) hyp (H5):=\n  generalize H1 H2 H3 H4 H5; \n    clear H1 H2 H3 H4 H5.\n\nTactic Notation \"gen_clear\" \n  hyp (H1) hyp (H2) hyp (H3) \n  hyp (H4) hyp (H5) hyp (H6):=\n  generalize H1 H2 H3 H4 H5 H6; \n    clear H1 H2 H3 H4 H5 H6.\n\nTactic Notation \"split_l\" :=\n  split; [trivial | idtac].\n\nTactic Notation \"split_r\" :=\n  split; [idtac | trivial ].\n\nTactic Notation \"split_lr\" :=\n  split; [trivial | trivial ].\n\nTactic Notation \"split_l\" \"with\" constr (t) :=\n  split; [apply t | idtac].\n\nTactic Notation \"split_r\" \"with\" constr (t) :=\n  split; [idtac | apply t ].\n\nTactic Notation \"split_l\" \"by\" tactic (tac) :=\n  split; [tac | idtac ].\n\nTactic Notation \"split_r\" \"by\" tactic (tac) :=\n  split; [idtac | tac ].\n\nTactic Notation \"split_l_clear\" \"with\" hyp (H) :=\n  split; [apply H | clear H].\n\nTactic Notation \"split_r_clear\" \"with\" hyp (H) :=\n  split; [clear H | apply H ].\n\nLemma and_sym : forall (A B : Prop), A /\\ B -> B /\\ A.\nProof. intros  A B [HA HB]; split; trivial. Qed.\n\nArguments and_sym [A B].\n\nLtac rsplit := apply and_sym; split.\n\nLemma and_sym_rr : forall A B C : Prop, A /\\ B /\\ C -> B /\\ C /\\ A.\nProof.\n  tauto.\nQed.\n\nLtac rrsplit := apply and_sym_rr; split.\n\nTactic Notation \"inj_hyp\" hyp (H) :=\n  injection H; clear H; intro H.\n\nTactic Notation \"rew_clear\" hyp (H) :=\n  rewrite H; clear H.\n\nTactic Notation \"injection\" hyp (H) :=\n  injection H.\n\nTactic Notation \"injection\" hyp (H) \"as\" \n  simple_intropattern (pat) :=\n  injection H; intros pat.\n\nTactic Notation \"injsubst\" ident (id) \"in\" hyp (H) :=\n  injection H; intro; subst id; clear H.\n\nLtac InvertAll :=\n  repeat\n    match goal with\n      | H: _ /\\ _ |- _ => inversion_clear H\n      | H: ex _   |- _ => inversion_clear H\n    end.\n\nLtac arith_replace t1 t2 := \n  (replace t1 with t2; fail \"error\") ||\n    (replace t1 with t2; [trivial | try omega; fail \"error\" ]).\n\nLtac arith_replaceH H t1 t2 := \n  (replace t1 with t2 in H; fail \"error\") ||\n    (replace t1 with t2 in H; [trivial | try omega; fail \"error\" ]).\n\nTactic Notation \"arith_rep\" constr(t1) \"with\" constr (t2) :=\n  arith_replace t1 t2.\n\nTactic Notation \"arith_rep\" constr(t1) \"with\" constr (t2) \"in\" hyp (H):=\n  arith_replaceH H t1 t2.\n\n\nLtac clearall := \n  match goal with \n    | H : _ |- _ =>\n      (clear H || (generalize H; clear H)); clearall\n    | _ => intros\n  end.\n\nLtac clearall_arith := \n  match goal with \n    | H : ?a > ?b |- _ => (generalize H; clear H); clearall_arith\n    | H : ?a >= ?b |- _ => (generalize H; clear H); clearall_arith\n    | H : ?a < ?b |- _ => (generalize H; clear H); clearall_arith\n    | H : ?a <= ?b |- _ => (generalize H; clear H); clearall_arith\n    | H : ?a = ?b |- _ => \n      match type of a with\n        | nat => (generalize H; clear H); clearall_arith\n        | _ => (clear H || (generalize H; clear H)); clearall_arith\n      end\n    | H : _ |- _ =>\n      (clear H || (generalize H; clear H)); clearall_arith\n    | _ => intros\n  end.\n\n\n\n\n(** * Useful tactics *)\n\nLtac inv H := inversion H; clear H; subst.\n\nLtac predSpec pred predspec x y :=\n  generalize (predspec x y); case (pred x y); intro.\n\nLtac caseEq name :=\n  generalize (refl_equal name); pattern name at -1 in |- *; case name.\n\nLtac destructEq name :=\n  destruct name eqn:?.\n\nLtac decEq :=\n  match goal with\n  | [ |- _ = _ ] => f_equal\n  | [ |- (?X ?A <> ?X ?B) ] =>\n      cut (A <> B); [intro; congruence | try discriminate]\n  end.\n\nLtac byContradiction :=\n  cut False; [contradiction|idtac].\n\nLtac omegaContradiction :=\n  cut False; [contradiction|omega].\n\nLemma modusponens: forall (P Q: Prop), P -> (P -> Q) -> Q.\nProof. auto. Qed.\n\nLtac exploit x :=\n    refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _) _)\n || refine (modusponens _ _ (x _ _) _)\n || refine (modusponens _ _ (x _) _).\n\n(** * Definitions and theorems over the type [positive] *)\n\nDefinition peq: forall (x y: positive), {x = y} + {x <> y} := Pos.eq_dec.\nGlobal Opaque peq.\n\nLemma peq_true:\n  forall (A: Type) (x: positive) (a b: A), (if peq x x then a else b) = a.\nProof.\n  intros. case (peq x x); intros.\n  auto.\n  elim n; auto.\nQed.\n\nLemma peq_false:\n  forall (A: Type) (x y: positive) (a b: A), x <> y -> (if peq x y then a else b) = b.\nProof.\n  intros. case (peq x y); intros.\n  elim H; auto.\n  auto.\nQed.  \n\nDefinition Plt: positive -> positive -> Prop := Pos.lt.\n\nLemma Plt_ne:\n  forall (x y: positive), Plt x y -> x <> y.\nProof.\n  unfold Plt; intros. red; intro. subst y. eelim Pos.lt_irrefl; eauto. \nQed.\nHint Resolve Plt_ne: coqlib.\n\nLemma Plt_trans:\n  forall (x y z: positive), Plt x y -> Plt y z -> Plt x z.\nProof (Pos.lt_trans).\n\nLemma Plt_succ:\n  forall (x: positive), Plt x (Psucc x).\nProof.\n  unfold Plt; intros. apply Pos.lt_succ_r. apply Pos.le_refl. \nQed.\nHint Resolve Plt_succ: coqlib.\n\nLemma Plt_trans_succ:\n  forall (x y: positive), Plt x y -> Plt x (Psucc y).\nProof.\n  intros. apply Plt_trans with y. assumption. apply Plt_succ.\nQed.\nHint Resolve Plt_succ: coqlib.\n\nLemma Plt_succ_inv:\n  forall (x y: positive), Plt x (Psucc y) -> Plt x y \\/ x = y.\nProof.\n  unfold Plt; intros. rewrite Pos.lt_succ_r in H. \n  apply Pos.le_lteq; auto.\nQed.\n\nDefinition plt (x y: positive) : {Plt x y} + {~ Plt x y}.\nProof.\n  unfold Plt, Pos.lt; intros. destruct (Pos.compare x y).\n  - right; congruence.\n  - left; auto.\n  - right; congruence.\nDefined.\nGlobal Opaque plt.\n\nDefinition Ple: positive -> positive -> Prop := Pos.le.\n\nLemma Ple_refl: forall (p: positive), Ple p p.\nProof (Pos.le_refl).\n\nLemma Ple_trans: forall (p q r: positive), Ple p q -> Ple q r -> Ple p r.\nProof (Pos.le_trans).\n\nLemma Plt_Ple: forall (p q: positive), Plt p q -> Ple p q.\nProof (Pos.lt_le_incl).\n\nLemma Ple_succ: forall (p: positive), Ple p (Psucc p).\nProof.\n  intros. apply Plt_Ple. apply Plt_succ.\nQed.\n\nLemma Plt_Ple_trans:\n  forall (p q r: positive), Plt p q -> Ple q r -> Plt p r.\nProof (Pos.lt_le_trans).\n\nLemma Plt_strict: forall p, ~ Plt p p.\nProof (Pos.lt_irrefl).\n\nHint Resolve Ple_refl Plt_Ple Ple_succ Plt_strict: coqlib.\n\nLtac xomega := unfold Plt, Ple in *; zify; omega.\nLtac xomegaContradiction := exfalso; xomega.\n\n(** Peano recursion over positive numbers. *)\n\nSection POSITIVE_ITERATION.\n\nLemma Plt_wf: well_founded Plt.\nProof.\n  apply well_founded_lt_compat with nat_of_P.\n  intros. apply nat_of_P_lt_Lt_compare_morphism. exact H.\nQed.\n\nVariable A: Type.\nVariable v1: A.\nVariable f: positive -> A -> A.\n\nLemma Ppred_Plt:\n  forall x, x <> xH -> Plt (Ppred x) x.\nProof.\n  intros. elim (Psucc_pred x); intro. contradiction.\n  set (y := Ppred x) in *. rewrite <- H0. apply Plt_succ.\nQed.\n\nLet iter (x: positive) (P: forall y, Plt y x -> A) : A :=\n  match peq x xH with\n  | left EQ => v1\n  | right NOTEQ => f (Ppred x) (P (Ppred x) (Ppred_Plt x NOTEQ))\n  end.\n\nDefinition positive_rec : positive -> A :=\n  Fix Plt_wf (fun _ => A) iter.\n\nLemma unroll_positive_rec:\n  forall x,\n  positive_rec x = iter x (fun y _ => positive_rec y).\nProof.\n  unfold positive_rec. apply (Fix_eq Plt_wf (fun _ => A) iter).\n  intros. unfold iter. case (peq x 1); intro. auto. decEq. apply H.\nQed.\n\nLemma positive_rec_base:\n  positive_rec 1%positive = v1.\nProof.\n  rewrite unroll_positive_rec. unfold iter. case (peq 1 1); intro.\n  auto. elim n; auto.\nQed.\n\nLemma positive_rec_succ:\n  forall x, positive_rec (Psucc x) = f x (positive_rec x).\nProof.\n  intro. rewrite unroll_positive_rec. unfold iter.\n  case (peq (Psucc x) 1); intro.\n  destruct x; simpl in e; discriminate.\n  rewrite Ppred_succ. auto.\nQed.\n\nLemma positive_Peano_ind:\n  forall (P: positive -> Prop),\n  P xH ->\n  (forall x, P x -> P (Psucc x)) ->\n  forall x, P x.\nProof.\n  intros.\n  apply (well_founded_ind Plt_wf P).\n  intros. \n  case (peq x0 xH); intro.\n  subst x0; auto.\n  elim (Psucc_pred x0); intro. contradiction. rewrite <- H2.\n  apply H0. apply H1. apply Ppred_Plt. auto. \nQed.\n\nEnd POSITIVE_ITERATION.\n\n(** * Definitions and theorems over the type [Z] *)\n\nDefinition zeq: forall (x y: Z), {x = y} + {x <> y} := Z.eq_dec.\n\nLemma zeq_true:\n  forall (A: Type) (x: Z) (a b: A), (if zeq x x then a else b) = a.\nProof.\n  intros. case (zeq x x); intros.\n  auto.\n  elim n; auto.\nQed.\n\nLemma zeq_false:\n  forall (A: Type) (x y: Z) (a b: A), x <> y -> (if zeq x y then a else b) = b.\nProof.\n  intros. case (zeq x y); intros.\n  elim H; auto.\n  auto.\nQed.  \n\nOpen Scope Z_scope.\n\nDefinition zlt: forall (x y: Z), {x < y} + {x >= y} := Z_lt_dec.\n\nLemma zlt_true:\n  forall (A: Type) (x y: Z) (a b: A), \n  x < y -> (if zlt x y then a else b) = a.\nProof.\n  intros. case (zlt x y); intros.\n  auto.\n  omegaContradiction.\nQed.\n\nLemma zlt_false:\n  forall (A: Type) (x y: Z) (a b: A), \n  x >= y -> (if zlt x y then a else b) = b.\nProof.\n  intros. case (zlt x y); intros.\n  omegaContradiction.\n  auto.\nQed.\n\nDefinition zle: forall (x y: Z), {x <= y} + {x > y} := Z_le_gt_dec.\n\nLemma zle_true:\n  forall (A: Type) (x y: Z) (a b: A), \n  x <= y -> (if zle x y then a else b) = a.\nProof.\n  intros. case (zle x y); intros.\n  auto.\n  omegaContradiction.\nQed.\n\nLemma zle_false:\n  forall (A: Type) (x y: Z) (a b: A), \n  x > y -> (if zle x y then a else b) = b.\nProof.\n  intros. case (zle x y); intros.\n  omegaContradiction.\n  auto.\nQed.\n\n(** Properties of powers of two. *)\n\nLemma two_power_nat_O : two_power_nat O = 1.\nProof. reflexivity. Qed.\n\nLemma two_power_nat_pos : forall n : nat, two_power_nat n > 0.\nProof.\n  induction n. rewrite two_power_nat_O. omega.\n  rewrite two_power_nat_S. omega.\nQed.\n\nLemma two_power_nat_two_p:\n  forall x, two_power_nat x = two_p (Z_of_nat x).\nProof.\n  induction x. auto. \n  rewrite two_power_nat_S. rewrite inj_S. rewrite two_p_S. omega. omega.\nQed.\n\nLemma two_p_monotone:\n  forall x y, 0 <= x <= y -> two_p x <= two_p y.\nProof.\n  intros.\n  replace (two_p x) with (two_p x * 1) by omega. \n  replace y with (x + (y - x)) by omega.\n  rewrite two_p_is_exp; try omega.\n  apply Zmult_le_compat_l.\n  assert (two_p (y - x) > 0). apply two_p_gt_ZERO. omega. omega.\n  assert (two_p x > 0). apply two_p_gt_ZERO. omega. omega.\nQed.\n\nLemma two_p_monotone_strict:\n  forall x y, 0 <= x < y -> two_p x < two_p y.\nProof.\n  intros. assert (two_p x <= two_p (y - 1)). apply two_p_monotone; omega.\n  assert (two_p (y - 1) > 0). apply two_p_gt_ZERO. omega.\n  replace y with (Zsucc (y - 1)) by omega. rewrite two_p_S. omega. omega.\nQed.\n\nLemma two_p_strict:\n  forall x, x >= 0 -> x < two_p x.\nProof.\n  intros x0 GT. pattern x0. apply natlike_ind.\n  simpl. omega.\n  intros. rewrite two_p_S; auto. generalize (two_p_gt_ZERO x H). omega. \n  omega.\nQed.\n\nLemma two_p_strict_2:\n  forall x, x >= 0 -> 2 * x - 1 < two_p x.\nProof.\n  intros. assert (x = 0 \\/ x - 1 >= 0) by omega. destruct H0.\n  subst. vm_compute. auto.\n  replace (two_p x) with (2 * two_p (x - 1)).\n  generalize (two_p_strict _ H0). omega. \n  rewrite <- two_p_S. decEq. omega. omega.\nQed.\n\n(** Properties of [Zmin] and [Zmax] *)\n\nLemma Zmin_spec:\n  forall x y, Zmin x y = if zlt x y then x else y.\nProof.\n  intros. case (zlt x y); unfold Zlt, Zge; intro z.\n  unfold Zmin. rewrite z. auto.\n  unfold Zmin. caseEq (x ?= y); intro. \n  apply Zcompare_Eq_eq. auto.\n  contradiction.\n  reflexivity.\nQed.\n\nLemma Zmax_spec:\n  forall x y, Zmax x y = if zlt y x then x else y.\nProof.\n  intros. case (zlt y x); unfold Zlt, Zge; intro z.\n  unfold Zmax. rewrite <- (Zcompare_antisym y x).\n  rewrite z. simpl. auto.\n  unfold Zmax. rewrite <- (Zcompare_antisym y x).\n  caseEq (y ?= x); intro; simpl.\n  symmetry. apply Zcompare_Eq_eq. auto.\n  contradiction. reflexivity.\nQed.\n\nLemma Zmax_bound_l:\n  forall x y z, x <= y -> x <= Zmax y z.\nProof.\n  intros. generalize (Zmax1 y z). omega.\nQed.\nLemma Zmax_bound_r:\n  forall x y z, x <= z -> x <= Zmax y z.\nProof.\n  intros. generalize (Zmax2 y z). omega.\nQed.\n\n(** Properties of Euclidean division and modulus. *)\n\nLemma Zdiv_small:\n  forall x y, 0 <= x < y -> x / y = 0.\nProof.\n  intros. assert (y > 0). omega. \n  assert (forall a b,\n    0 <= a < y ->\n    0 <= y * b + a < y ->\n    b = 0).\n  intros. \n  assert (b = 0 \\/ b > 0 \\/ (-b) > 0). omega.\n  elim H3; intro.\n  auto.\n  elim H4; intro.\n  assert (y * b >= y * 1). apply Zmult_ge_compat_l. omega. omega. \n  omegaContradiction. \n  assert (y * (-b) >= y * 1). apply Zmult_ge_compat_l. omega. omega.\n  rewrite <- Zopp_mult_distr_r in H6. omegaContradiction.\n  apply H1 with (x mod y). \n  apply Z_mod_lt. auto.\n  rewrite <- Z_div_mod_eq. auto. auto.\nQed.\n\nLemma Zmod_small:\n  forall x y, 0 <= x < y -> x mod y = x.\nProof.\n  intros. assert (y > 0). omega.\n  generalize (Z_div_mod_eq x y H0). \n  rewrite (Zdiv_small x y H). omega.\nQed.\n\nLemma Zmod_unique:\n  forall x y a b,\n  x = a * y + b -> 0 <= b < y -> x mod y = b.\nProof.\n  intros. subst x. rewrite Zplus_comm. \n  rewrite Z_mod_plus. apply Zmod_small. auto. omega.\nQed.\n\nLemma Zdiv_unique:\n  forall x y a b,\n  x = a * y + b -> 0 <= b < y -> x / y = a.\nProof.\n  intros. subst x. rewrite Zplus_comm.\n  rewrite Z_div_plus. rewrite (Zdiv_small b y H0). omega. omega.\nQed.\n\nLemma Zdiv_Zdiv:\n  forall a b c,\n  b > 0 -> c > 0 -> (a / b) / c = a / (b * c).\nProof.\n  intros.\n  generalize (Z_div_mod_eq a b H). generalize (Z_mod_lt a b H). intros.\n  generalize (Z_div_mod_eq (a/b) c H0). generalize (Z_mod_lt (a/b) c H0). intros.\n  set (q1 := a / b) in *. set (r1 := a mod b) in *.\n  set (q2 := q1 / c) in *. set (r2 := q1 mod c) in *.\n  symmetry. apply Zdiv_unique with (r2 * b + r1). \n  rewrite H2. rewrite H4. ring.\n  split. \n  assert (0 <= r2 * b). apply Zmult_le_0_compat. omega. omega. omega.\n  assert ((r2 + 1) * b <= c * b).\n  apply Zmult_le_compat_r. omega. omega. \n  replace ((r2 + 1) * b) with (r2 * b + b) in H5 by ring.\n  replace (c * b) with (b * c) in H5 by ring.\n  omega.\nQed.\n\nLemma Zmult_le_compat_l_neg :\n  forall n m p:Z, n >= m -> p <= 0 -> p * n <= p * m.\nProof.\n  intros.\n  assert ((-p) * n >= (-p) * m). apply Zmult_ge_compat_l. auto. omega.\n  replace (p * n) with (- ((-p) * n)) by ring.\n  replace (p * m) with (- ((-p) * m)) by ring.\n  omega.\nQed.\n\nLemma Zdiv_interval_1:\n  forall lo hi a b,\n  lo <= 0 -> hi > 0 -> b > 0 ->\n  lo * b <= a < hi * b ->\n  lo <= a/b < hi.\nProof.\n  intros. \n  generalize (Z_div_mod_eq a b H1). generalize (Z_mod_lt a b H1). intros.\n  set (q := a/b) in *. set (r := a mod b) in *.\n  split.\n  assert (lo < (q + 1)).\n  apply Zmult_lt_reg_r with b. omega.  \n  apply Zle_lt_trans with a. omega. \n  replace ((q + 1) * b) with (b * q + b) by ring.\n  omega.\n  omega.\n  apply Zmult_lt_reg_r with b. omega. \n  replace (q * b) with (b * q) by ring.\n  omega.\nQed.\n\nLemma Zdiv_interval_2:\n  forall lo hi a b,\n  lo <= a <= hi -> lo <= 0 -> hi >= 0 -> b > 0 ->\n  lo <= a/b <= hi.\nProof.\n  intros.\n  assert (lo <= a / b < hi+1).\n  apply Zdiv_interval_1. omega. omega. auto.\n  assert (lo * b <= lo * 1). apply Zmult_le_compat_l_neg. omega. omega. \n  replace (lo * 1) with lo in H3 by ring.\n  assert ((hi + 1) * 1 <= (hi + 1) * b). apply Zmult_le_compat_l. omega. omega.\n  replace ((hi + 1) * 1) with (hi + 1) in H4 by ring.\n  omega.\n  omega.\nQed.\n\nLemma Zmod_recombine:\n  forall x a b,\n  a > 0 -> b > 0 ->\n  x mod (a * b) = ((x/b) mod a) * b + (x mod b).\nProof.\n  intros. \n  set (xb := x/b). \n  apply Zmod_unique with (xb/a).\n  generalize (Z_div_mod_eq x b H0); fold xb; intro EQ1.\n  generalize (Z_div_mod_eq xb a H); intro EQ2.\n  rewrite EQ2 in EQ1. \n  eapply trans_eq. eexact EQ1. ring.\n  generalize (Z_mod_lt x b H0). intro. \n  generalize (Z_mod_lt xb a H). intro.\n  assert (0 <= xb mod a * b <= a * b - b).\n    split. apply Zmult_le_0_compat; omega.\n    replace (a * b - b) with ((a - 1) * b) by ring.\n    apply Zmult_le_compat; omega. \n  omega.\nQed.\n\n(** Properties of divisibility. *)\n\nLemma Zdivides_trans:\n  forall x y z, (x | y) -> (y | z) -> (x | z).\nProof.\n  intros x y z [a A] [b B]; subst. exists (a*b); ring.\nQed.\n\nDefinition Zdivide_dec:\n  forall (p q: Z), p > 0 -> { (p|q) } + { ~(p|q) }.\nProof.\n  intros. destruct (zeq (Zmod q p) 0).\n  left. exists (q / p). \n  transitivity (p * (q / p) + (q mod p)). apply Z_div_mod_eq; auto.\n  transitivity (p * (q / p)). omega. ring.\n  right; red; intros. elim n. apply Z_div_exact_1; auto. \n  inv H0. rewrite Z_div_mult; auto. ring.\nDefined.\nGlobal Opaque Zdivide_dec.\n\nLemma Zdivide_interval:\n  forall a b c,\n  0 < c -> 0 <= a < b -> (c | a) -> (c | b) -> 0 <= a <= b - c.\nProof.\n  intros. destruct H1 as [x EQ1]. destruct H2 as [y EQ2]. subst. destruct H0.\n  split. omega. exploit Zmult_lt_reg_r; eauto. intros. \n  replace (y * c - c) with ((y - 1) * c) by ring.\n  apply Zmult_le_compat_r; omega.\nQed.\n\n(** Conversion from [Z] to [nat]. *)\n\nDefinition nat_of_Z: Z -> nat := Z.to_nat.\n\nLemma nat_of_Z_of_nat:\n  forall n, nat_of_Z (Z_of_nat n) = n.\nProof.\n  exact Nat2Z.id.\nQed.\n\nLemma nat_of_Z_max:\n  forall z, Z_of_nat (nat_of_Z z) = Zmax z 0.\nProof.\n  intros. unfold Zmax. destruct z; simpl; auto. \n  change (Z.of_nat (Z.to_nat (Zpos p)) = Zpos p).\n  apply Z2Nat.id. compute; intuition congruence. \nQed.\n\nLemma nat_of_Z_eq:\n  forall z, z >= 0 -> Z_of_nat (nat_of_Z z) = z.\nProof.\n  unfold nat_of_Z; intros. apply Z2Nat.id. omega.\nQed.\n\nLemma nat_of_Z_neg:\n  forall n, n <= 0 -> nat_of_Z n = O.\nProof.\n  destruct n; unfold Zle; simpl; auto. congruence.\nQed.\n\nLemma nat_of_Z_plus:\n  forall p q,\n  p >= 0 -> q >= 0 ->\n  nat_of_Z (p + q) = (nat_of_Z p + nat_of_Z q)%nat.\nProof.\n  unfold nat_of_Z; intros. apply Z2Nat.inj_add; omega. \nQed.\n\n\n(** Alignment: [align n amount] returns the smallest multiple of [amount]\n  greater than or equal to [n]. *)\n\nDefinition align (n: Z) (amount: Z) :=\n  ((n + amount - 1) / amount) * amount.\n\nLemma align_le: forall x y, y > 0 -> x <= align x y.\nProof.\n  intros. unfold align. \n  generalize (Z_div_mod_eq (x + y - 1) y H). intro.\n  replace ((x + y - 1) / y * y) \n     with ((x + y - 1) - (x + y - 1) mod y).\n  generalize (Z_mod_lt (x + y - 1) y H). omega.\n  rewrite Zmult_comm. omega.\nQed.\n\nLemma align_divides: forall x y, y > 0 -> (y | align x y).\nProof.\n  intros. unfold align. apply Zdivide_factor_l. \nQed.\n\n(** * Definitions and theorems on the data types [option], [sum] and [list] *)\n\nSet Implicit Arguments.\n\n(** Comparing option types. *)\n\nDefinition option_eq (A: Type) (eqA: forall (x y: A), {x=y} + {x<>y}):\n  forall (x y: option A), {x=y} + {x<>y}.\nProof. decide equality. Defined.\nGlobal Opaque option_eq.\n\n(** Mapping a function over an option type. *)\n\nDefinition option_map (A B: Type) (f: A -> B) (x: option A) : option B :=\n  match x with\n  | None => None\n  | Some y => Some (f y)\n  end.\n\n(** Mapping a function over a sum type. *)\n\nDefinition sum_left_map (A B C: Type) (f: A -> B) (x: A + C) : B + C :=\n  match x with\n  | inl y => inl C (f y)\n  | inr z => inr B z\n  end.\n\n(** Properties of [List.nth] (n-th element of a list). *)\n\nHint Resolve in_eq in_cons: coqlib.\n\nLemma nth_error_in:\n  forall (A: Type) (n: nat) (l: list A) (x: A),\n  List.nth_error l n = Some x -> In x l.\nProof.\n  induction n; simpl.\n   destruct l; intros.\n    discriminate.\n    injection H; intro; subst a. apply in_eq.\n   destruct l; intros.\n    discriminate.\n    apply in_cons. auto.\nQed.\nHint Resolve nth_error_in: coqlib.\n\nLemma nth_error_nil:\n  forall (A: Type) (idx: nat), nth_error (@nil A) idx = None.\nProof.\n  induction idx; simpl; intros; reflexivity.\nQed.\nHint Resolve nth_error_nil: coqlib.\n\n(** Compute the length of a list, with result in [Z]. *)\n\nFixpoint list_length_z_aux (A: Type) (l: list A) (acc: Z) {struct l}: Z :=\n  match l with\n  | nil => acc\n  | hd :: tl => list_length_z_aux tl (Zsucc acc)\n  end.\n\nRemark list_length_z_aux_shift:\n  forall (A: Type) (l: list A) n m,\n  list_length_z_aux l n = list_length_z_aux l m + (n - m).\nProof.\n  induction l; intros; simpl.\n  omega.\n  replace (n - m) with (Zsucc n - Zsucc m) by omega. auto.\nQed.\n\nDefinition list_length_z (A: Type) (l: list A) : Z :=\n  list_length_z_aux l 0.\n\nLemma list_length_z_cons:\n  forall (A: Type) (hd: A) (tl: list A),\n  list_length_z (hd :: tl) = list_length_z tl + 1.\nProof.\n  intros. unfold list_length_z. simpl.\n  rewrite (list_length_z_aux_shift tl 1 0). omega. \nQed.\n\nLemma list_length_z_pos:\n  forall (A: Type) (l: list A),\n  list_length_z l >= 0.\nProof.\n  induction l; simpl. unfold list_length_z; simpl. omega. \n  rewrite list_length_z_cons. omega.\nQed.\n\nLemma list_length_z_map:\n  forall (A B: Type) (f: A -> B) (l: list A),\n  list_length_z (map f l) = list_length_z l.\nProof.\n  induction l. reflexivity. simpl. repeat rewrite list_length_z_cons. congruence.\nQed. \n\n(** Extract the n-th element of a list, as [List.nth_error] does,\n    but the index [n] is of type [Z]. *)\n\nFixpoint list_nth_z (A: Type) (l: list A) (n: Z) {struct l}: option A :=\n  match l with\n  | nil => None\n  | hd :: tl => if zeq n 0 then Some hd else list_nth_z tl (Zpred n)\n  end.\n\nLemma list_nth_z_in:\n  forall (A: Type) (l: list A) n x,\n  list_nth_z l n = Some x -> In x l.\nProof.\n  induction l; simpl; intros. \n  congruence.\n  destruct (zeq n 0). left; congruence. right; eauto.\nQed.\n\nLemma list_nth_z_map:\n  forall (A B: Type) (f: A -> B) (l: list A) n,\n  list_nth_z (List.map f l) n = option_map f (list_nth_z l n).\nProof.\n  induction l; simpl; intros.\n  auto.\n  destruct (zeq n 0). auto. eauto.\nQed.\n\nLemma list_nth_z_range:\n  forall (A: Type) (l: list A) n x,\n  list_nth_z l n = Some x -> 0 <= n < list_length_z l.\nProof.\n  induction l; simpl; intros.\n  discriminate.\n  rewrite list_length_z_cons. destruct (zeq n 0).\n  generalize (list_length_z_pos l); omega.\n  exploit IHl; eauto. unfold Zpred. omega. \nQed.\n\n(** Properties of [List.incl] (list inclusion). *)\n\nLemma incl_cons_inv:\n  forall (A: Type) (a: A) (b c: list A),\n  incl (a :: b) c -> incl b c.\nProof.\n  unfold incl; intros. apply H. apply in_cons. auto.\nQed.\nHint Resolve incl_cons_inv: coqlib.\n\nLemma incl_app_inv_l:\n  forall (A: Type) (l1 l2 m: list A),\n  incl (l1 ++ l2) m -> incl l1 m.\nProof.\n  unfold incl; intros. apply H. apply in_or_app. left; assumption.\nQed.\n\nLemma incl_app_inv_r:\n  forall (A: Type) (l1 l2 m: list A),\n  incl (l1 ++ l2) m -> incl l2 m.\nProof.\n  unfold incl; intros. apply H. apply in_or_app. right; assumption.\nQed.\n\nHint Resolve  incl_tl incl_refl incl_app_inv_l incl_app_inv_r: coqlib.\n\nLemma incl_same_head:\n  forall (A: Type) (x: A) (l1 l2: list A),\n  incl l1 l2 -> incl (x::l1) (x::l2).\nProof.\n  intros; red; simpl; intros. intuition. \nQed.\n\n(** Properties of [List.map] (mapping a function over a list). *)\n\nLemma list_map_exten:\n  forall (A B: Type) (f f': A -> B) (l: list A),\n  (forall x, In x l -> f x = f' x) ->\n  List.map f' l = List.map f l.\nProof.\n  induction l; simpl; intros.\n  reflexivity.\n  rewrite <- H. rewrite IHl. reflexivity.\n  intros. apply H. tauto.\n  tauto.\nQed.\n\nLemma list_map_compose:\n  forall (A B C: Type) (f: A -> B) (g: B -> C) (l: list A),\n  List.map g (List.map f l) = List.map (fun x => g(f x)) l.\nProof.\n  induction l; simpl. reflexivity. rewrite IHl; reflexivity.\nQed.\n\nLemma list_map_identity:\n  forall (A: Type) (l: list A),\n  List.map (fun (x:A) => x) l = l.\nProof.\n  induction l; simpl; congruence.\nQed.\n\nLemma list_map_nth:\n  forall (A B: Type) (f: A -> B) (l: list A) (n: nat),\n  nth_error (List.map f l) n = option_map f (nth_error l n).\nProof.\n  induction l; simpl; intros.\n  repeat rewrite nth_error_nil. reflexivity.\n  destruct n; simpl. reflexivity. auto.\nQed.\n\nLemma list_length_map:\n  forall (A B: Type) (f: A -> B) (l: list A),\n  List.length (List.map f l) = List.length l.\nProof.\n  induction l; simpl; congruence.\nQed.\n\nLemma list_in_map_inv:\n  forall (A B: Type) (f: A -> B) (l: list A) (y: B),\n  In y (List.map f l) -> exists x:A, y = f x /\\ In x l.\nProof.\n  induction l; simpl; intros.\n  contradiction.\n  elim H; intro. \n  exists a; intuition auto.\n  generalize (IHl y H0). intros [x [EQ IN]]. \n  exists x; tauto.\nQed.\n\nLemma list_append_map:\n  forall (A B: Type) (f: A -> B) (l1 l2: list A),\n  List.map f (l1 ++ l2) = List.map f l1 ++ List.map f l2.\nProof.\n  induction l1; simpl; intros.\n  auto. rewrite IHl1. auto.\nQed.\n\nLemma list_append_map_inv:\n  forall (A B: Type) (f: A -> B) (m1 m2: list B) (l: list A),\n  List.map f l = m1 ++ m2 ->\n  exists l1, exists l2, List.map f l1 = m1 /\\ List.map f l2 = m2 /\\ l = l1 ++ l2.\nProof.\n  induction m1; simpl; intros.\n  exists (@nil A); exists l; auto.\n  destruct l; simpl in H; inv H. \n  exploit IHm1; eauto. intros [l1 [l2 [P [Q R]]]]. subst l. \n  exists (a0 :: l1); exists l2; intuition. simpl; congruence.\nQed.\n\n(** Folding a function over a list *)\n\nSection LIST_FOLD.\n\nVariables A B: Type.\nVariable f: A -> B -> B.\n\n(** This is exactly [List.fold_left] from Coq's standard library,\n  with [f] taking arguments in a different order. *)\n\nFixpoint list_fold_left (accu: B) (l: list A) : B :=\n  match l with nil => accu | x :: l' => list_fold_left (f x accu) l' end.\n\n(** This is exactly [List.fold_right] from Coq's standard library,\n  except that it runs in constant stack space. *)\n\nDefinition list_fold_right (l: list A) (base: B) : B :=\n  list_fold_left base (List.rev' l).\n\nRemark list_fold_left_app:\n  forall l1 l2 accu,\n  list_fold_left accu (l1 ++ l2) = list_fold_left (list_fold_left accu l1) l2.\nProof.\n  induction l1; simpl; intros. \n  auto.\n  rewrite IHl1. auto.\nQed.\n\nLemma list_fold_right_eq:\n  forall l base,\n  list_fold_right l base =\n  match l with nil => base | x :: l' => f x (list_fold_right l' base) end.\nProof.\n  unfold list_fold_right; intros. \n  destruct l.\n  auto.\n  unfold rev'. rewrite <- ! rev_alt. simpl.  \n  rewrite list_fold_left_app. simpl. auto. \nQed.\n\nLemma list_fold_right_spec:\n  forall l base, list_fold_right l base = List.fold_right f base l.\nProof.\n  induction l; simpl; intros; rewrite list_fold_right_eq; congruence.\nQed.\n\nEnd LIST_FOLD.\n\n(** Properties of list membership. *)\n\nLemma in_cns:\n  forall (A: Type) (x y: A) (l: list A), In x (y :: l) <-> y = x \\/ In x l.\nProof.\n  intros. simpl. tauto.\nQed.\n\nLemma in_app:\n  forall (A: Type) (x: A) (l1 l2: list A), In x (l1 ++ l2) <-> In x l1 \\/ In x l2.\nProof.\n  intros. split; intro. apply in_app_or. auto. apply in_or_app. auto.\nQed.\n\nLemma list_in_insert:\n  forall (A: Type) (x: A) (l1 l2: list A) (y: A),\n  In x (l1 ++ l2) -> In x (l1 ++ y :: l2).\nProof.\n  intros. apply in_or_app; simpl. elim (in_app_or _ _ _ H); intro; auto.\nQed.\n\n(** [list_disjoint l1 l2] holds iff [l1] and [l2] have no elements \n  in common. *)\n\nDefinition list_disjoint (A: Type) (l1 l2: list A) : Prop :=\n  forall (x y: A), In x l1 -> In y l2 -> x <> y.\n\nLemma list_disjoint_cons_l:\n  forall (A: Type) (a: A) (l1 l2: list A),\n  list_disjoint l1 l2 -> ~In a l2 -> list_disjoint (a :: l1) l2.\nProof.\n  unfold list_disjoint; simpl; intros. destruct H1. congruence. apply H; auto.\nQed.\n\nLemma list_disjoint_cons_r:\n  forall (A: Type) (a: A) (l1 l2: list A),\n  list_disjoint l1 l2 -> ~In a l1 -> list_disjoint l1 (a :: l2).\nProof.\n  unfold list_disjoint; simpl; intros. destruct H2. congruence. apply H; auto.\nQed.\n\nLemma list_disjoint_cons_left:\n  forall (A: Type) (a: A) (l1 l2: list A),\n  list_disjoint (a :: l1) l2 -> list_disjoint l1 l2.\nProof.\n  unfold list_disjoint; simpl; intros. apply H; tauto. \nQed.\n\nLemma list_disjoint_cons_right:\n  forall (A: Type) (a: A) (l1 l2: list A),\n  list_disjoint l1 (a :: l2) -> list_disjoint l1 l2.\nProof.\n  unfold list_disjoint; simpl; intros. apply H; tauto. \nQed.\n\nLemma list_disjoint_notin:\n  forall (A: Type) (l1 l2: list A) (a: A),\n  list_disjoint l1 l2 -> In a l1 -> ~(In a l2).\nProof.\n  unfold list_disjoint; intros; red; intros. \n  apply H with a a; auto.\nQed.\n\nLemma list_disjoint_sym:\n  forall (A: Type) (l1 l2: list A),\n  list_disjoint l1 l2 -> list_disjoint l2 l1.\nProof.\n  unfold list_disjoint; intros. \n  apply sym_not_equal. apply H; auto.\nQed.\n\nLemma list_disjoint_dec:\n  forall (A: Type) (eqA_dec: forall (x y: A), {x=y} + {x<>y}) (l1 l2: list A),\n  {list_disjoint l1 l2} + {~list_disjoint l1 l2}.\nProof.\n  induction l1; intros.\n  left; red; intros. elim H.\n  case (In_dec eqA_dec a l2); intro.\n  right; red; intro. apply (H a a); auto with coqlib. \n  case (IHl1 l2); intro.\n  left; red; intros. elim H; intro. \n    red; intro; subst a y. contradiction.\n    apply l; auto.\n  right; red; intros. elim n0. eapply list_disjoint_cons_left; eauto.\nDefined.\n\n(** [list_equiv l1 l2] holds iff the lists [l1] and [l2] contain the same elements. *)\n\nDefinition list_equiv (A : Type) (l1 l2: list A) : Prop :=\n  forall x, In x l1 <-> In x l2.\n\n(** [list_norepet l] holds iff the list [l] contains no repetitions,\n  i.e. no element occurs twice. *)\n\nInductive list_norepet (A: Type) : list A -> Prop :=\n  | list_norepet_nil:\n      list_norepet nil\n  | list_norepet_cons:\n      forall hd tl,\n      ~(In hd tl) -> list_norepet tl -> list_norepet (hd :: tl).\n\nLemma list_norepet_dec:\n  forall (A: Type) (eqA_dec: forall (x y: A), {x=y} + {x<>y}) (l: list A),\n  {list_norepet l} + {~list_norepet l}.\nProof.\n  induction l.\n  left; constructor.\n  destruct IHl. \n  case (In_dec eqA_dec a l); intro.\n  right. red; intro. inversion H. contradiction. \n  left. constructor; auto.\n  right. red; intro. inversion H. contradiction.\nDefined.\n\nLemma list_map_norepet:\n  forall (A B: Type) (f: A -> B) (l: list A),\n  list_norepet l ->\n  (forall x y, In x l -> In y l -> x <> y -> f x <> f y) ->\n  list_norepet (List.map f l).\nProof.\n  induction 1; simpl; intros.\n  constructor.\n  constructor.\n  red; intro. generalize (list_in_map_inv f _ _ H2).\n  intros [x [EQ IN]]. generalize EQ. change (f hd <> f x).\n  apply H1. tauto. tauto. \n  red; intro; subst x. contradiction.\n  apply IHlist_norepet. intros. apply H1. tauto. tauto. auto.\nQed.\n\nRemark list_norepet_append_commut:\n  forall (A: Type) (a b: list A),\n  list_norepet (a ++ b) -> list_norepet (b ++ a).\nProof.\n  intro A.\n  assert (forall (x: A) (b: list A) (a: list A), \n           list_norepet (a ++ b) -> ~(In x a) -> ~(In x b) -> \n           list_norepet (a ++ x :: b)).\n    induction a; simpl; intros.\n    constructor; auto.\n    inversion H. constructor. red; intro.\n    elim (in_app_or _ _ _ H6); intro.\n    elim H4. apply in_or_app. tauto.\n    elim H7; intro. subst a. elim H0. left. auto. \n    elim H4. apply in_or_app. tauto.\n    auto.\n  induction a; simpl; intros.\n  rewrite <- app_nil_end. auto.\n  inversion H0. apply H. auto. \n  red; intro; elim H3. apply in_or_app. tauto.\n  red; intro; elim H3. apply in_or_app. tauto.\nQed.\n\nLemma list_norepet_app:\n  forall (A: Type) (l1 l2: list A),\n  list_norepet (l1 ++ l2) <->\n  list_norepet l1 /\\ list_norepet l2 /\\ list_disjoint l1 l2.\nProof.\n  induction l1; simpl; intros; split; intros.\n  intuition. constructor. red;simpl;auto.\n  tauto.\n  inversion H; subst. rewrite IHl1 in H3. rewrite in_app in H2.\n  intuition.\n  constructor; auto. red; intros. elim H2; intro. congruence. auto. \n  destruct H as [B [C D]]. inversion B; subst. \n  constructor. rewrite in_app. intuition. elim (D a a); auto. apply in_eq. \n  rewrite IHl1. intuition. red; intros. apply D; auto. apply in_cons; auto. \nQed.\n\nLemma list_norepet_append:\n  forall (A: Type) (l1 l2: list A),\n  list_norepet l1 -> list_norepet l2 -> list_disjoint l1 l2 ->\n  list_norepet (l1 ++ l2).\nProof.\n  generalize list_norepet_app; firstorder.\nQed.\n\nLemma list_norepet_append_right:\n  forall (A: Type) (l1 l2: list A),\n  list_norepet (l1 ++ l2) -> list_norepet l2.\nProof.\n  generalize list_norepet_app; firstorder.\nQed.\n\nLemma list_norepet_append_left:\n  forall (A: Type) (l1 l2: list A),\n  list_norepet (l1 ++ l2) -> list_norepet l1.\nProof.\n  generalize list_norepet_app; firstorder.\nQed.\n\n(** [is_tail l1 l2] holds iff [l2] is of the form [l ++ l1] for some [l]. *)\n\nInductive is_tail (A: Type): list A -> list A -> Prop :=\n  | is_tail_refl:\n      forall c, is_tail c c\n  | is_tail_cons:\n      forall i c1 c2, is_tail c1 c2 -> is_tail c1 (i :: c2).\n\nLemma is_tail_in:\n  forall (A: Type) (i: A) c1 c2, is_tail (i :: c1) c2 -> In i c2.\nProof.\n  induction c2; simpl; intros.\n  inversion H.\n  inversion H. tauto. right; auto.\nQed.\n\nLemma is_tail_cons_left:\n  forall (A: Type) (i: A) c1 c2, is_tail (i :: c1) c2 -> is_tail c1 c2.\nProof.\n  induction c2; intros; inversion H.\n  constructor. constructor. constructor. auto. \nQed.\n\nHint Resolve is_tail_refl is_tail_cons is_tail_in is_tail_cons_left: coqlib.\n\nLemma is_tail_incl:\n  forall (A: Type) (l1 l2: list A), is_tail l1 l2 -> incl l1 l2.\nProof.\n  induction 1; eauto with coqlib.\nQed.\n\nLemma is_tail_trans:\n  forall (A: Type) (l1 l2: list A),\n  is_tail l1 l2 -> forall (l3: list A), is_tail l2 l3 -> is_tail l1 l3.\nProof.\n  induction 1; intros. auto. apply IHis_tail. eapply is_tail_cons_left; eauto.\nQed.\n\n(** [list_forall2 P [x1 ... xN] [y1 ... yM]] holds iff [N = M] and\n  [P xi yi] holds for all [i]. *)\n\nSection FORALL2.\n\nVariable A: Type.\nVariable B: Type.\nVariable P: A -> B -> Prop.\n\nInductive list_forall2: list A -> list B -> Prop :=\n  | list_forall2_nil:\n      list_forall2 nil nil\n  | list_forall2_cons:\n      forall a1 al b1 bl,\n      P a1 b1 ->\n      list_forall2 al bl ->\n      list_forall2 (a1 :: al) (b1 :: bl).\n\nLemma list_forall2_app:\n  forall a2 b2 a1 b1,\n  list_forall2 a1 b1 -> list_forall2 a2 b2 -> \n  list_forall2 (a1 ++ a2) (b1 ++ b2).\nProof.\n  induction 1; intros; simpl. auto. constructor; auto. \nQed.\n\nLemma list_forall2_length:\n  forall l1 l2,\n  list_forall2 l1 l2 -> length l1 = length l2.\nProof.\n  induction 1; simpl; congruence.\nQed.\n\nEnd FORALL2.\n\nLemma list_forall2_imply:\n  forall (A B: Type) (P1: A -> B -> Prop) (l1: list A) (l2: list B),\n  list_forall2 P1 l1 l2 ->\n  forall (P2: A -> B -> Prop),\n  (forall v1 v2, In v1 l1 -> In v2 l2 -> P1 v1 v2 -> P2 v1 v2) ->\n  list_forall2 P2 l1 l2.\nProof.\n  induction 1; intros.\n  constructor.\n  constructor. auto with coqlib. apply IHlist_forall2; auto. \n  intros. auto with coqlib.\nQed.\n\n(** Dropping the first N elements of a list. *)\n\nFixpoint list_drop (A: Type) (n: nat) (x: list A) {struct n} : list A :=\n  match n with\n  | O => x\n  | S n' => match x with nil => nil | hd :: tl => list_drop n' tl end\n  end.\n\nLemma list_drop_incl:\n  forall (A: Type) (x: A) n (l: list A), In x (list_drop n l) -> In x l.\nProof.\n  induction n; simpl; intros. auto. \n  destruct l; auto with coqlib.\nQed.\n\nLemma list_drop_norepet:\n  forall (A: Type) n (l: list A), list_norepet l -> list_norepet (list_drop n l).\nProof.\n  induction n; simpl; intros. auto.\n  inv H. constructor. auto.\nQed.\n\nLemma list_map_drop:\n  forall (A B: Type) (f: A -> B) n (l: list A),\n  list_drop n (map f l) = map f (list_drop n l).\nProof.\n  induction n; simpl; intros. auto. \n  destruct l; simpl; auto.\nQed.\n\n(** A list of [n] elements, all equal to [x]. *)\n\nFixpoint list_repeat {A: Type} (n: nat) (x: A) {struct n} :=\n  match n with\n  | O => nil\n  | S m => x :: list_repeat m x\n  end.\n\nLemma length_list_repeat:\n  forall (A: Type) n (x: A), length (list_repeat n x) = n.\nProof.\n  induction n; simpl; intros. auto. decEq; auto.\nQed.\n\nLemma in_list_repeat:\n  forall (A: Type) n (x: A) y, In y (list_repeat n x) -> y = x.\nProof.\n  induction n; simpl; intros. elim H. destruct H; auto.\nQed.\n\n(** * Definitions and theorems over boolean types *)\n\nDefinition proj_sumbool (P Q: Prop) (a: {P} + {Q}) : bool :=\n  if a then true else false.\n\n Arguments proj_sumbool [P Q].\n\nCoercion proj_sumbool: sumbool >-> bool.\n\nLemma proj_sumbool_true:\n  forall (P Q: Prop) (a: {P}+{Q}), proj_sumbool a = true -> P.\nProof.\n  intros P Q a. destruct a; simpl. auto. congruence.\nQed.\n\nLemma proj_sumbool_is_true:\n  forall (P: Prop) (a: {P}+{~P}), P -> proj_sumbool a = true.\nProof.\n  intros. unfold proj_sumbool. destruct a. auto. contradiction. \nQed.\n\nLtac InvBooleans :=\n  match goal with\n  | [ H: _ && _ = true |- _ ] =>\n      destruct (andb_prop _ _ H); clear H; InvBooleans\n  | [ H: _ || _ = false |- _ ] =>\n      destruct (orb_false_elim _ _ H); clear H; InvBooleans\n  | [ H: proj_sumbool ?x = true |- _ ] =>\n      generalize (proj_sumbool_true _ H); clear H; intro; InvBooleans\n  | _ => idtac\n  end.\n\nSection DECIDABLE_EQUALITY.\n\nVariable A: Type.\nVariable dec_eq: forall (x y: A), {x=y} + {x<>y}.\nVariable B: Type.\n\nLemma dec_eq_true:\n  forall (x: A) (ifso ifnot: B),\n  (if dec_eq x x then ifso else ifnot) = ifso.\nProof.\n  intros. destruct (dec_eq x x). auto. congruence.\nQed.\n\nLemma dec_eq_false:\n  forall (x y: A) (ifso ifnot: B),\n  x <> y -> (if dec_eq x y then ifso else ifnot) = ifnot.\nProof.\n  intros. destruct (dec_eq x y). congruence. auto.\nQed.\n\nLemma dec_eq_sym:\n  forall (x y: A) (ifso ifnot: B),\n  (if dec_eq x y then ifso else ifnot) =\n  (if dec_eq y x then ifso else ifnot).\nProof.\n  intros. destruct (dec_eq x y). \n  subst y. rewrite dec_eq_true. auto.\n  rewrite dec_eq_false; auto.\nQed.\n\nEnd DECIDABLE_EQUALITY.\n\nSection DECIDABLE_PREDICATE.\n\nVariable P: Prop.\nVariable dec: {P} + {~P}.\nVariable A: Type.\n\nLemma pred_dec_true:\n  forall (a b: A), P -> (if dec then a else b) = a.\nProof.\n  intros. destruct dec. auto. contradiction.\nQed.\n\nLemma pred_dec_false:\n  forall (a b: A), ~P -> (if dec then a else b) = b.\nProof.\n  intros. destruct dec. contradiction. auto.\nQed.\n\nEnd DECIDABLE_PREDICATE.\n\n(** * Well-founded orderings *)\n\nRequire Import Relations.\n\n(** A non-dependent version of lexicographic ordering. *)\n\nSection LEX_ORDER.\n\nVariable A: Type.\nVariable B: Type.\nVariable ordA: A -> A -> Prop.\nVariable ordB: B -> B -> Prop.\n\nInductive lex_ord: A*B -> A*B -> Prop :=\n  | lex_ord_left: forall a1 b1 a2 b2,\n      ordA a1 a2 -> lex_ord (a1,b1) (a2,b2)\n  | lex_ord_right: forall a b1 b2,\n      ordB b1 b2 -> lex_ord (a,b1) (a,b2).\n\nLemma wf_lex_ord: \n  well_founded ordA -> well_founded ordB -> well_founded lex_ord.\nProof.\n  intros Awf Bwf.\n  assert (forall a, Acc ordA a -> forall b, Acc ordB b -> Acc lex_ord (a, b)).\n    induction 1. induction 1. constructor; intros. inv H3.\n    apply H0. auto. apply Bwf.\n    apply H2; auto. \n  red; intros. destruct a as [a b]. apply H; auto.\nQed.\n\nLemma transitive_lex_ord:\n  transitive _ ordA -> transitive _ ordB -> transitive _ lex_ord.\nProof.\n  intros trA trB; red; intros. \n  inv H; inv H0. \n  left; eapply trA; eauto.\n  left; auto.\n  left; auto.\n  right; eapply trB; eauto.\nQed.\n\nEnd LEX_ORDER.\n\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/framework/auxiliary/Coqlib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.296696282741732}}
{"text": "(* ll_fragments library for yalla *)\n\n\n(* output in Type *)\n\n\n(** * Definitions of various Linear Logic fragments *)\n\nRequire Import Bool_more.\nRequire Import List_more.\nRequire Import List_Type_more.\nRequire Import Permutation_Type_more.\nRequire Import Permutation_Type_solve.\nRequire Import genperm_Type.\n\nRequire Export ll_prop.\nRequire Import subs.\n\n\n(** ** Standard linear logic: [ll_ll] (no mix, no axiom, commutative) *)\n\n(** cut / axioms / mix0 / mix2 / permutation *)\nDefinition pfrag_ll :=  mk_pfrag false NoAxioms false false true.\n(*                               cut   axioms   mix0  mix2  perm  *)\n\nDefinition ll_ll := ll pfrag_ll.\n\nLemma cut_ll_r : forall A l1 l2,\n  ll_ll (dual A :: l1) -> ll_ll (A :: l2) -> ll_ll (l2 ++ l1).\nProof with myeeasy.\nintros A l1 l2 pi1 pi2.\neapply cut_r_axfree...\nintros a ; destruct a.\nQed.\n\nLemma cut_ll_admissible :\n  forall l, ll (cutupd_pfrag pfrag_ll true) l -> ll_ll l.\nProof with myeeasy.\nintros l pi.\ninduction pi ; try (now econstructor).\n- eapply ex_r...\n- eapply ex_wn_r...\n- eapply cut_ll_r...\nQed.\n\n\n\n(** ** Linear logic with mix0: [ll_mix0] (no mix2, no axiom, commutative) *)\n\n(** cut / axioms / mix0 / mix2 / permutation *)\nDefinition pfrag_mix0 := mk_pfrag false NoAxioms true false true.\n(*                                cut   axioms   mix0 mix2  perm  *)\n\nDefinition ll_mix0 := ll pfrag_mix0.\n\nDefinition mix0add_pfrag P :=\n  mk_pfrag (pcut P) (pgax P) true (pmix2 P) (pperm P).\n\nLemma cut_mix0_r : forall A l1 l2, \n  ll_mix0 (dual A :: l1) -> ll_mix0 (A :: l2) -> ll_mix0 (l2 ++ l1).\nProof with myeeasy.\nintros A l1 l2 pi1 pi2.\neapply cut_r_axfree...\nintros a ; destruct a.\nQed.\n\nLemma cut_mix0_admissible :\n  forall l, ll (cutupd_pfrag pfrag_mix0 true) l -> ll_mix0 l.\nProof with myeeasy.\nintros l pi.\ninduction pi ; try (now econstructor).\n- eapply ex_r...\n- eapply ex_wn_r...\n- eapply cut_mix0_r...\nQed.\n\n(** Provability in [ll_mix0] is equivalent to adding [wn one] in [ll] *)\n\nLemma mix0_to_ll {P} : pperm P = true -> forall b0 bp l,\n  ll (mk_pfrag P.(pcut) P.(pgax) b0 P.(pmix2) bp) l -> ll P (wn one :: l).\nProof with myeeasy ; try PCperm_Type_solve.\nintros fp b0 bp l pi.\neapply (ext_wn_param _ P fp _ (one :: nil)) in pi.\n- eapply ex_r...\n- intros Hcut...\n- simpl ; intros a.\n  eapply ex_r ; [ | apply PCperm_Type_last ].\n  apply wk_r.\n  apply gax_r.\n- intros.\n  eapply de_r.\n  eapply one_r.\n- intros Hpmix2 Hpmix2'.\n  exfalso.\n  simpl in Hpmix2.\n  rewrite Hpmix2 in Hpmix2'.\n  inversion Hpmix2'.\nQed.\n\nLemma ll_to_mix0_axat {P} : (forall a, Forall atomic (projT2 (pgax P) a)) ->\n  pperm P = true -> forall l,\n  ll P (wn one :: l) -> ll (mix0add_pfrag P) l.\nProof with myeeasy ; try PCperm_Type_solve.\nintros Hgax Hperm.\nenough (forall l, ll P l -> forall l' (l0 l1 : list unit),\n  Permutation_Type l (l' ++ map (fun _ => one) l1\n                         ++ map (fun _ => wn one) l0)  ->\n  ll (mix0add_pfrag P) l').\n{ intros l pi.\n  eapply (X _ pi l (tt :: nil) nil)... }\nintros l pi.\ninduction pi ; intros l' l0' l1' HP.\n- assert (HP' := HP).\n  symmetry in HP'.\n  apply Permutation_Type_vs_cons_inv in HP'.\n  destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.\n  rewrite Heq in HP.\n  apply Permutation_Type_cons_app_inv in HP.\n  apply Permutation_Type_length_1_inv in HP.\n  apply app_eq_unit_Type in HP.\n  destruct HP as [[Heq1 Heq2] | [Heq1 Heq2]] ; subst ; destruct l' ; inversion Heq ; subst.\n  + destruct l1' ; inversion H0.\n    destruct l0' ; inversion H1.\n  + destruct l' ; inversion H1.\n    * destruct l1' ; inversion H0.\n      destruct l0' ; inversion H2.\n    * destruct l' ; inversion H2.\n      rewrite H3.\n      apply ax_r.\n  + destruct l1' ; inversion H0.\n    destruct l0' ; inversion H1.\n  + destruct l' ; inversion H1.\n    * destruct l1' ; inversion H0.\n      destruct l0' ; inversion H2.\n    * destruct l' ; inversion H2.\n      rewrite H3.\n      eapply ex_r ; [ apply ax_r | ]...\n- rewrite Hperm in p ; simpl in p.\n  eapply IHpi.\n  etransitivity...\n- apply (Permutation_Type_map wn) in p.\n  eapply IHpi.\n  etransitivity...\n- apply Permutation_Type_nil in HP.\n  destruct l' ; inversion HP.\n  rewrite H0.\n  apply mix0_r...\n- apply Permutation_Type_app_app_inv in HP.\n  destruct HP as [[[l1a l2a] [l3a l4a]] [[HP1 HP2] [HP3 HP4]]] ;\n    simpl in HP1 ; simpl in HP2 ; simpl in HP3 ; simpl in HP4.\n  apply Permutation_Type_app_app_inv in HP4.\n  destruct HP4 as [[[l1b l2b] [l3b l4b]] [[HP1b HP2b] [HP3b HP4b]]] ;\n    simpl in HP1b ; simpl in HP2b ; simpl in HP3b ; simpl in HP4b.\n  symmetry in HP1b.\n  apply Permutation_Type_map_inv in HP1b.\n  destruct HP1b as [la Heqa _].\n  decomp_map_Type Heqa ; simpl in Heqa1 ; simpl in Heqa2 ; subst.\n  symmetry in HP2b.\n  apply Permutation_Type_map_inv in HP2b.\n  destruct HP2b as [lb Heqb _].\n  decomp_map_Type Heqb ; simpl in Heqb1 ; simpl in Heqb2 ; subst.\n  apply (Permutation_Type_app_head l2a) in HP4b.\n  assert (IHP1 := Permutation_Type_trans HP2 HP4b).\n  apply (Permutation_Type_app_head l1a) in HP3b.\n  assert (IHP2 := Permutation_Type_trans HP1 HP3b).\n  apply IHpi1 in IHP1.\n  apply IHpi2 in IHP2.\n  symmetry in HP3.\n  eapply ex_r ; [ apply mix2_r | simpl ; rewrite Hperm ; apply HP3 ]...\n- apply Permutation_Type_length_1_inv in HP.\n  destruct l' ; inversion HP.\n  + apply mix0_r...\n  + apply app_eq_nil in H1 ; destruct H1 ; subst.\n    apply one_r.\n- assert (HP' := HP).\n  symmetry in HP'.\n  apply Permutation_Type_vs_cons_inv in HP'.\n  destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.\n  rewrite Heq in HP.\n  apply Permutation_Type_cons_app_inv in HP.\n  dichot_Type_elt_app_exec Heq ; subst.\n  + rewrite app_assoc in HP.\n    apply IHpi in HP.\n    eapply ex_r ; [ apply bot_r | simpl ; rewrite Hperm ]...\n  + dichot_Type_elt_app_exec Heq1 ; subst.\n    * decomp_map_Type Heq0.\n      inversion Heq0.\n    * decomp_map_Type Heq2.\n      inversion Heq2.\n- assert (HP' := HP).\n  symmetry in HP'.\n  apply Permutation_Type_vs_cons_inv in HP'.\n  destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.\n  rewrite Heq in HP.\n  apply Permutation_Type_cons_app_inv in HP.\n  dichot_Type_elt_app_exec Heq ; subst.\n  + rewrite app_assoc in HP.\n    remember (l'l ++ l) as l'.\n    apply Permutation_Type_app_app_inv in HP.\n    destruct HP as [[[l1a l2a] [l3a l4a]] [[HP1 HP2] [HP3 HP4]]] ;\n      simpl in HP1 ; simpl in HP2 ; simpl in HP3 ; simpl in HP4.\n    apply Permutation_Type_app_app_inv in HP4.\n    destruct HP4 as [[[l1b l2b] [l3b l4b]] [[HP1b HP2b] [HP3b HP4b]]] ;\n      simpl in HP1b ; simpl in HP2b ; simpl in HP3b ; simpl in HP4b.\n    symmetry in HP1b.\n    apply Permutation_Type_map_inv in HP1b.\n    destruct HP1b as [la Heqa _].\n    decomp_map_Type Heqa ; simpl in Heqa1 ; simpl in Heqa2 ; subst.\n    symmetry in HP2b.\n    apply Permutation_Type_map_inv in HP2b.\n    destruct HP2b as [lb Heqb _].\n    decomp_map_Type Heqb ; simpl in Heqb1 ; simpl in Heqb2 ; subst.\n    apply (Permutation_Type_app_head l2a) in HP4b.\n    assert (IHP1 := Permutation_Type_trans HP2 HP4b).\n    apply (@Permutation_Type_cons _ A _ eq_refl) in IHP1.\n    rewrite app_comm_cons in IHP1.\n    apply (Permutation_Type_app_head l1a) in HP3b.\n    assert (IHP2 := Permutation_Type_trans HP1 HP3b).\n    apply (@Permutation_Type_cons _ B _ eq_refl) in IHP2.\n    rewrite app_comm_cons in IHP2.\n    apply IHpi1 in IHP1.\n    apply IHpi2 in IHP2.\n    symmetry in HP3.\n    apply (Permutation_Type_cons_app _ _ (tens A B)) in HP3.\n    eapply ex_r ; [ apply tens_r | simpl ; rewrite Hperm ; apply HP3 ]...\n  + dichot_Type_elt_app_exec Heq1 ; subst.\n    * exfalso.\n      decomp_map_Type Heq0 ; inversion Heq0.\n    * decomp_map_Type Heq2.\n      inversion Heq2.\n- assert (HP' := HP).\n  symmetry in HP'.\n  apply Permutation_Type_vs_cons_inv in HP'.\n  destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.\n  rewrite Heq in HP.\n  apply Permutation_Type_cons_app_inv in HP.\n  dichot_Type_elt_app_exec Heq ; subst.\n  + rewrite app_assoc in HP.\n    apply (@Permutation_Type_cons _ B _ eq_refl) in HP.\n    apply (@Permutation_Type_cons _ A _ eq_refl) in HP.\n    rewrite 2 app_comm_cons in HP.\n    apply IHpi in HP.\n    eapply ex_r ; [ apply parr_r | simpl ; rewrite Hperm ]...\n  + dichot_Type_elt_app_exec Heq1 ; subst.\n    * decomp_map_Type Heq0.\n      inversion Heq0.\n    * decomp_map_Type Heq2.\n      inversion Heq2.\n- assert (HP' := HP).\n  symmetry in HP'.\n  apply Permutation_Type_vs_cons_inv in HP'.\n  destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.\n  rewrite Heq in HP.\n  apply Permutation_Type_cons_app_inv in HP.\n  dichot_Type_elt_app_exec Heq ; subst.\n  + eapply ex_r ; [ apply top_r\n                  | simpl ; rewrite Hperm ; apply Permutation_Type_middle ]...\n  + dichot_Type_elt_app_exec Heq1 ; subst.\n    * decomp_map_Type Heq0.\n      inversion Heq0.\n    * decomp_map_Type Heq2.\n      inversion Heq2.\n- assert (HP' := HP).\n  symmetry in HP'.\n  apply Permutation_Type_vs_cons_inv in HP'.\n  destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.\n  rewrite Heq in HP.\n  apply Permutation_Type_cons_app_inv in HP.\n  dichot_Type_elt_app_exec Heq ; subst.\n  + rewrite app_assoc in HP.\n    apply (@Permutation_Type_cons _ A _ eq_refl) in HP.\n    rewrite app_comm_cons in HP.\n    apply IHpi in HP.\n    eapply ex_r ; [ apply plus_r1 | simpl ; rewrite Hperm ]...\n  + dichot_Type_elt_app_exec Heq1 ; subst.\n    * decomp_map_Type Heq0.\n      inversion Heq0.\n    * decomp_map_Type Heq2.\n      inversion Heq2.\n- assert (HP' := HP).\n  symmetry in HP'.\n  apply Permutation_Type_vs_cons_inv in HP'.\n  destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.\n  rewrite Heq in HP.\n  apply Permutation_Type_cons_app_inv in HP.\n  dichot_Type_elt_app_exec Heq ; subst.\n  + rewrite app_assoc in HP.\n    apply (@Permutation_Type_cons _ A _ eq_refl) in HP.\n    rewrite app_comm_cons in HP.\n    apply IHpi in HP.\n    eapply ex_r ; [ apply plus_r2 | simpl ; rewrite Hperm ]...\n  + dichot_Type_elt_app_exec Heq1 ; subst.\n    * decomp_map_Type Heq0.\n      inversion Heq0.\n    * decomp_map_Type Heq2.\n      inversion Heq2.\n- assert (HP' := HP).\n  symmetry in HP'.\n  apply Permutation_Type_vs_cons_inv in HP'.\n  destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.\n  rewrite Heq in HP.\n  apply Permutation_Type_cons_app_inv in HP.\n  dichot_Type_elt_app_exec Heq ; subst.\n  + rewrite app_assoc in HP.\n    assert (HP2 := HP).\n    apply (@Permutation_Type_cons _ A _ eq_refl) in HP.\n    rewrite app_comm_cons in HP.\n    apply IHpi1 in HP.\n    apply (@Permutation_Type_cons _ B _ eq_refl) in HP2.\n    rewrite app_comm_cons in HP2.\n    apply IHpi2 in HP2.\n    eapply ex_r ; [ apply with_r\n                  | simpl ; rewrite Hperm ; apply Permutation_Type_middle ]...\n  + dichot_Type_elt_app_exec Heq1 ; subst.\n    * decomp_map_Type Heq0.\n      inversion Heq0.\n    * decomp_map_Type Heq2.\n      inversion Heq2.\n- assert (HP' := HP).\n  symmetry in HP'.\n  apply Permutation_Type_vs_cons_inv in HP'.\n  destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.\n  rewrite Heq in HP.\n  apply Permutation_Type_cons_app_inv in HP.\n  dichot_Type_elt_app_exec Heq ; subst.\n  + symmetry in HP.\n    apply Permutation_Type_map_inv in HP.\n    destruct HP as [l' Heq HP].\n    decomp_map_Type Heq ;\n      simpl in Heq1 ; simpl in Heq2 ; simpl in Heq3 ; simpl in Heq5 ; subst ;\n      simpl in HP.\n    apply (Permutation_Type_map wn) in HP.\n    list_simpl in HP.\n    rewrite app_assoc in HP.\n    rewrite <- map_app in HP.\n    apply (@Permutation_Type_cons _ A _ eq_refl) in HP.\n    rewrite app_comm_cons in HP.\n    rewrite <- Heq2 in HP.\n    rewrite <- Heq5 in HP.\n    apply IHpi in HP.\n    eapply ex_r ; [ apply oc_r | simpl ; rewrite Hperm ]...\n  + dichot_Type_elt_app_exec Heq1 ; subst.\n    * decomp_map_Type Heq0.\n      inversion Heq0.\n    * decomp_map_Type Heq2.\n      inversion Heq2.\n- assert (HP' := HP).\n  symmetry in HP'.\n  apply Permutation_Type_vs_cons_inv in HP'.\n  destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.\n  rewrite Heq in HP.\n  apply Permutation_Type_cons_app_inv in HP.\n  dichot_Type_elt_app_exec Heq ; subst.\n  + rewrite app_assoc in HP.\n    apply (@Permutation_Type_cons _ A _ eq_refl) in HP.\n    rewrite app_comm_cons in HP.\n    apply IHpi in HP.\n    eapply ex_r ; [ apply de_r | simpl ; rewrite Hperm ]...\n  + dichot_Type_elt_app_exec Heq1 ; subst.\n    * decomp_map_Type Heq0.\n      inversion Heq0.\n    * decomp_map_Type Heq2 ; simpl in Heq1 ; simpl in Heq2 ; simpl in Heq3 ; subst ; simpl in HP.\n      inversion Heq2 ; subst.\n      list_simpl in HP ; rewrite <- map_app in HP.\n      apply (@Permutation_Type_cons _ one _ eq_refl) in HP.\n      assert (Permutation_Type (one :: l)\n                               (l' ++ map (fun _ : unit => one) (tt :: l1')\n                                   ++ map (fun _ : unit => wn one) (l1 ++ l4)))\n        as HP' by (etransitivity ; [ apply HP | ] ; perm_Type_solve). \n      apply IHpi in HP'...\n- assert (HP' := HP).\n  symmetry in HP'.\n  apply Permutation_Type_vs_cons_inv in HP'.\n  destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.\n  rewrite Heq in HP.\n  apply Permutation_Type_cons_app_inv in HP.\n  dichot_Type_elt_app_exec Heq ; subst.\n  + rewrite app_assoc in HP.\n    apply IHpi in HP.\n    eapply ex_r ; [ apply wk_r | simpl ; rewrite Hperm ]...\n  + dichot_Type_elt_app_exec Heq1 ; subst.\n    * decomp_map_Type Heq0.\n      inversion Heq0.\n    * decomp_map_Type Heq2 ; simpl in Heq1 ; simpl in Heq2 ; simpl in Heq3 ; subst ; simpl in HP.\n      inversion Heq2 ; subst.\n      list_simpl in HP ; rewrite <- map_app in HP.\n      apply IHpi in HP...\n- assert (HP' := HP).\n  symmetry in HP'.\n  apply Permutation_Type_vs_cons_inv in HP'.\n  destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.\n  rewrite Heq in HP.\n  apply Permutation_Type_cons_app_inv in HP.\n  dichot_Type_elt_app_exec Heq ; subst.\n  + rewrite app_assoc in HP.\n    apply (@Permutation_Type_cons _ (wn A) _ eq_refl) in HP.\n    apply (@Permutation_Type_cons _ (wn A) _ eq_refl) in HP.\n    rewrite 2 app_comm_cons in HP.\n    apply IHpi in HP.\n    eapply ex_r ; [ apply co_r | simpl ; rewrite Hperm ]...\n  + dichot_Type_elt_app_exec Heq1 ; subst.\n    * decomp_map_Type Heq0.\n      inversion Heq0.\n    * decomp_map_Type Heq2 ; simpl in Heq1 ; simpl in Heq2 ; simpl in Heq3 ; subst ; simpl in HP.\n      inversion Heq2 ; subst.\n      list_simpl in HP ; rewrite <- map_app in HP.\n      apply (@Permutation_Type_cons _ (wn one) _ eq_refl) in HP.\n      apply (@Permutation_Type_cons _ (wn one) _ eq_refl) in HP.\n      assert (Permutation_Type (wn one :: wn one :: l)\n                               (l' ++ map (fun _ : unit => one) l1' ++\n                                  map (fun _ : unit => wn one) (tt :: tt :: l1 ++ l4)))\n        as HP' by (etransitivity ; [ apply HP | perm_Type_solve ]).\n      apply IHpi in HP'...\n- apply Permutation_Type_app_app_inv in HP.\n  destruct HP as [[[l1a l2a] [l3a l4a]] [[HP1 HP2] [HP3 HP4]]] ;\n    simpl in HP1 ; simpl in HP2 ; simpl in HP3 ; simpl in HP4.\n  apply Permutation_Type_app_app_inv in HP4.\n  destruct HP4 as [[[l1b l2b] [l3b l4b]] [[HP1b HP2b] [HP3b HP4b]]] ;\n    simpl in HP1b ; simpl in HP2b ; simpl in HP3b ; simpl in HP4b.\n  symmetry in HP1b.\n  apply Permutation_Type_map_inv in HP1b.\n  destruct HP1b as [la Heqa _].\n  decomp_map_Type Heqa ; simpl in Heqa1 ; simpl in Heqa2 ; subst.\n  symmetry in HP2b.\n  apply Permutation_Type_map_inv in HP2b.\n  destruct HP2b as [lb Heqb _].\n  decomp_map_Type Heqb ; simpl in Heqb1 ; simpl in Heqb2 ; subst.\n  apply (Permutation_Type_app_head l2a) in HP4b.\n  assert (IHP1 := Permutation_Type_trans HP2 HP4b).\n  apply (@Permutation_Type_cons _ (dual A) _ eq_refl) in IHP1.\n  rewrite app_comm_cons in IHP1.\n  apply (Permutation_Type_app_head l1a) in HP3b.\n  assert (IHP2 := Permutation_Type_trans HP1 HP3b).\n  apply (@Permutation_Type_cons _ A _ eq_refl) in IHP2.\n  rewrite app_comm_cons in IHP2.\n  apply IHpi1 in IHP1.\n  apply IHpi2 in IHP2.\n  symmetry in HP3.\n  eapply ex_r ; [ eapply cut_r | simpl ; rewrite Hperm ; apply HP3 ]...\n- destruct l1' ; destruct l0' ; simpl in HP.\n  + eapply ex_r ; [ apply gax_r | simpl ; rewrite Hperm ]...\n  + exfalso.\n    apply Permutation_Type_vs_elt_inv in HP.\n    specialize (Hgax a).\n    destruct HP as [[l1 l2] Heq] ; rewrite Heq in Hgax.\n    apply Forall_elt in Hgax.\n    inversion Hgax.\n  + exfalso.\n    apply Permutation_Type_vs_elt_inv in HP.\n    specialize (Hgax a).\n    destruct HP as [[l1 l2] Heq] ; rewrite Heq in Hgax.\n    apply Forall_elt in Hgax.\n    inversion Hgax.\n  + exfalso.\n    apply Permutation_Type_vs_elt_inv in HP.\n    specialize (Hgax a).\n    destruct HP as [[l1 l2] Heq] ; rewrite Heq in Hgax.\n    apply Forall_elt in Hgax.\n    inversion Hgax.\nQed.\n\nLemma ll_to_mix0_cut {P} : forall l,\n  ll P (wn one :: l) -> ll (mk_pfrag true P.(pgax) true P.(pmix2) P.(pperm)) l.\nProof with myeasy.\nintros l pi.\neapply stronger_pfrag in pi.\n- rewrite <- (app_nil_r l).\n  eapply cut_r ; [ | | apply pi]...\n  change nil with (map wn nil).\n  apply oc_r.\n  apply bot_r.\n  eapply mix0_r...\n- nsplit 5...\n  + destruct pcut...\n  + intros a.\n    exists a...\n  + destruct pmix0...\nQed.\n\nLemma mix0_wn_one : forall l, ll_mix0 (wn one :: l) -> ll_mix0 l.\nProof with myeeasy.\nintros l pi.\n(* an alternative proof is by introducing a cut with (oc bot) *)\nassert (pfrag_mix0 = mk_pfrag pfrag_mix0.(pcut) pfrag_mix0.(pgax)\n                              true pfrag_mix0.(pmix2) true)\n  as Heqfrag by reflexivity.\napply cut_mix0_admissible.\napply ll_to_mix0_cut.\napply co_r.\neapply mix0_to_ll...\nQed.\n\n\n(** Provability in [ll_mix0] is equivalent to provability of [ll]\nextended with the provability of [bot :: bot :: nil] *)\n\nLemma mix0_to_ll_bot {P} : pcut P = true -> pperm P = true -> forall bc b0 bp l,\n  ll (mk_pfrag bc P.(pgax) b0 P.(pmix2) bp) l ->\n    ll (axupd_pfrag P (existT (fun x => x -> list formula) _\n                              (fun a => match a with\n                                        | inl x => projT2 (pgax P) x\n                                        | inr tt => bot :: bot :: nil\n                                        end))) l.\nProof with myeeasy ; try (unfold PCperm_Type ; PCperm_Type_solve).\nremember (axupd_pfrag P (existT (fun x => x -> list formula) _\n                                (fun a => match a with\n                                          | inl x => projT2 (pgax P) x\n                                          | inr tt => bot :: bot :: nil\n                                          end))) as P'.\nintros fc fp bc b0 bp l pi.\neapply stronger_pfrag in pi.\n- eapply mix0_to_ll in pi...\n  assert (pcut P' = true) as fc' by (rewrite HeqP' ; simpl ; assumption).\n  apply (stronger_pfrag _ P') in pi.\n  + assert (ll P' (bot :: map wn nil)) as pi'.\n    { change (bot :: map wn nil) with ((bot :: nil) ++ nil).\n      eapply (@cut_r _ fc' bot).\n      - apply one_r.\n      - assert ({ b | bot :: bot :: nil = projT2 (pgax P') b })\n          as [b Hgax] by (rewrite HeqP' ; now (exists (inr tt))).\n        rewrite Hgax.\n        apply gax_r. }\n    apply oc_r in pi'.\n    rewrite <- (app_nil_l l).\n    eapply (@cut_r _ fc' (oc bot)) ; [ simpl ; apply pi | apply pi' ].\n  + nsplit 5 ; rewrite HeqP'...\n    simpl ; intros a ; exists (inl a)...\n- nsplit 5 ; intros ; simpl...\n  + rewrite fc.\n    destruct bc...\n  + exists a...\nQed.\n\nLemma ll_bot_to_mix0 {P} : forall l,\n  ll (axupd_pfrag P (existT (fun x => x -> list formula) _\n                              (fun a => match a with\n                                        | inl x => projT2 (pgax P) x\n                                        | inr tt => bot :: bot :: nil\n                                        end))) l\n  -> ll (mk_pfrag P.(pcut) P.(pgax) true P.(pmix2) P.(pperm)) l.\nProof with myeeasy.\nintros l pi.\nremember (mk_pfrag P.(pcut) P.(pgax) true P.(pmix2) P.(pperm)) as P'.\napply (stronger_pfrag _\n  (axupd_pfrag P' (existT (fun x => x -> list formula) _\n                          (fun a => match a with\n                                    | inl x => projT2 (pgax P) x\n                                    | inr tt => bot :: bot :: nil\n                                    end)))) in pi.\n- eapply ax_gen...\n  clear - HeqP' ; simpl ; intros a.\n  destruct a.\n  + assert ({ b | projT2 (pgax P) p = projT2 (pgax P') b })\n      as [b Hgax] by (rewrite HeqP' ; now exists p).\n    rewrite Hgax.\n    apply gax_r.\n  + destruct u.\n    apply bot_r.\n    apply bot_r.\n    apply mix0_r.\n    rewrite HeqP'...\n- rewrite HeqP' ; nsplit 5 ; simpl ; intros...\n  + exists a...\n  + destruct (pmix0 P)...\nQed.\n\n(** [mix2] is not valid in [ll_mix0] *)\n\nLemma mix0_not_mix2 : ll_mix0 (one :: one :: nil) -> False.\nProof.\nintros pi.\nremember (one :: one :: nil) as l.\nrevert Heql ; induction pi ; intros Heql ; subst ; try inversion Heql.\n- apply IHpi.\n  simpl in p ; apply Permutation_Type_sym in p.\n  apply Permutation_Type_length_2_inv in p.\n  destruct p ; assumption.\n- destruct l1 ; destruct lw' ; inversion Heql ; subst.\n  + now symmetry in p ; apply Permutation_Type_nil in p ; subst.\n  + now symmetry in p ; apply Permutation_Type_nil in p ; subst.\n  + destruct l1 ; inversion H2.\n    destruct l1 ; inversion H3.\n- inversion f.\n- inversion f.\n- destruct a.\nQed.\n\n\n(** ** Linear logic with mix2: [ll_mix2] (no mix0, no axiom, commutative) *)\n\n(** cut / axioms / mix0 / mix2 / permutation *)\nDefinition pfrag_mix2 := mk_pfrag false NoAxioms false true true.\n(*                                cut   axioms   mix0  mix2 perm  *)\n\nDefinition ll_mix2 := ll pfrag_mix2.\n\nDefinition mix2add_pfrag P :=\n  mk_pfrag (pcut P) (pgax P) (pmix0 P) true (pperm P).\n\nLemma cut_mix2_r : forall A l1 l2,\n  ll_mix2 (dual A :: l1) -> ll_mix2 (A :: l2) -> ll_mix2 (l2 ++ l1).\nProof with myeeasy.\nintros A l1 l2 pi1 pi2.\neapply cut_r_axfree...\nintros a ; destruct a.\nQed.\n\nLemma cut_mix2_admissible :\n  forall l, ll (cutupd_pfrag pfrag_mix2 true) l -> ll_mix2 l.\nProof with myeeasy.\nintros l pi.\ninduction pi ; try (now econstructor).\n- eapply ex_r...\n- eapply ex_wn_r...\n- eapply cut_mix2_r...\nQed.\n\n(** Provability in [ll_mix2] is equivalent to adding [wn (tens bot bot)] in [ll] *)\n\nLemma mix2_to_ll {P} : pperm P = true -> forall b2 bp l,\n  ll (mk_pfrag P.(pcut) P.(pgax) P.(pmix0) b2 bp) l -> ll P (wn (tens bot bot) :: l).\nProof with myeeasy ; try PCperm_Type_solve.\nintros fp b2 bp l pi.\neapply (ext_wn_param _ P fp _ (tens bot bot :: nil)) in pi.\n- eapply ex_r...\n- intros Hcut...\n- simpl ; intros a.\n  eapply ex_r ; [ | apply PCperm_Type_last ].\n  apply wk_r.\n  apply gax_r.\n- intros Hpmix0 Hpmix0'.\n  exfalso.\n  simpl in Hpmix0.\n  rewrite Hpmix0 in Hpmix0'.\n  inversion Hpmix0'.\n- intros _ _ l1 l2 pi1 pi2.\n  apply (ex_r _ (wn (tens bot bot) :: l2 ++ l1))...\n  apply co_r.\n  apply co_r.\n  apply de_r.\n  eapply ex_r.\n  + apply tens_r ; apply bot_r ; [ apply pi1 | apply pi2 ].\n  + rewrite fp...\nQed.\n\nLemma ll_to_mix2_axat {P} : (forall a, Forall atomic (projT2 (pgax P) a)) ->\n  pperm P = true -> forall l,\n  ll P (wn (tens bot bot) :: l) -> ll (mix2add_pfrag P) l.\nProof with myeeasy ; try PCperm_Type_solve.\nintros Hgax Hperm.\nassert (forall a, In bot (projT2 (pgax P) a) -> False) as Hgaxbot.\n{ intros a Hbot.\n  apply (Forall_In _ _ _ (Hgax a)) in Hbot.\n  inversion Hbot. }\nenough (forall l, ll P l -> forall l' (l0 l1 : list unit),\n  Permutation_Type l (l' ++ map (fun _ => tens bot bot) l1\n                         ++ map (fun _ => wn (tens bot bot)) l0)  ->\n  ll (mix2add_pfrag P) l').\n{ intros l pi.\n  eapply (X _ pi l (tt :: nil) nil)... }\nintros l pi.\ninduction pi ; intros l' l0' l1' HP.\n- assert (HP' := HP).\n  symmetry in HP'.\n  apply Permutation_Type_vs_cons_inv in HP'.\n  destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.\n  rewrite Heq in HP.\n  apply Permutation_Type_cons_app_inv in HP.\n  apply Permutation_Type_length_1_inv in HP.\n  apply app_eq_unit_Type in HP.\n  destruct HP as [[Heq1 Heq2] | [Heq1 Heq2]] ; subst ; destruct l' ; inversion Heq ; subst.\n  + destruct l1' ; inversion H0.\n    destruct l0' ; inversion H1.\n  + destruct l' ; inversion H1.\n    * destruct l1' ; inversion H0.\n      destruct l0' ; inversion H2.\n    * destruct l' ; inversion H2.\n      rewrite H3.\n      apply ax_r.\n  + destruct l1' ; inversion H0.\n    destruct l0' ; inversion H1.\n  + destruct l' ; inversion H1.\n    * destruct l1' ; inversion H0.\n      destruct l0' ; inversion H2.\n    * destruct l' ; inversion H2.\n      rewrite H3.\n      eapply ex_r ; [ apply ax_r | ]...\n- rewrite Hperm in p ; simpl in p.\n  eapply IHpi.\n  etransitivity...\n- apply (Permutation_Type_map wn) in p.\n  eapply IHpi.\n  etransitivity...\n- apply Permutation_Type_nil in HP.\n  destruct l' ; inversion HP.\n  rewrite H0.\n  apply mix0_r...\n- apply Permutation_Type_app_app_inv in HP.\n  destruct HP as [[[l1a l2a] [l3a l4a]] [[HP1 HP2] [HP3 HP4]]] ;\n    simpl in HP1 ; simpl in HP2 ; simpl in HP3 ; simpl in HP4.\n  apply Permutation_Type_app_app_inv in HP4.\n  destruct HP4 as [[[l1b l2b] [l3b l4b]] [[HP1b HP2b] [HP3b HP4b]]] ;\n    simpl in HP1b ; simpl in HP2b ; simpl in HP3b ; simpl in HP4b.\n  symmetry in HP1b.\n  apply Permutation_Type_map_inv in HP1b.\n  destruct HP1b as [la Heqa _].\n  decomp_map_Type Heqa ; simpl in Heqa1 ; simpl in Heqa2 ; subst.\n  symmetry in HP2b.\n  apply Permutation_Type_map_inv in HP2b.\n  destruct HP2b as [lb Heqb _].\n  decomp_map_Type Heqb ; simpl in Heqb1 ; simpl in Heqb2 ; subst.\n  apply (Permutation_Type_app_head l2a) in HP4b.\n  assert (IHP1 := Permutation_Type_trans HP2 HP4b).\n  apply (Permutation_Type_app_head l1a) in HP3b.\n  assert (IHP2 := Permutation_Type_trans HP1 HP3b).\n  apply IHpi1 in IHP1.\n  apply IHpi2 in IHP2.\n  symmetry in HP3.\n  eapply ex_r ; [ apply mix2_r | simpl ; rewrite Hperm ; apply HP3 ]...\n- apply Permutation_Type_length_1_inv in HP.\n  destruct l' ; inversion HP.\n  + destruct l1' ; inversion H0.\n    destruct l0' ; inversion H1.\n  + apply app_eq_nil in H1 ; destruct H1 ; subst.\n    apply one_r.\n- assert (HP' := HP).\n  symmetry in HP'.\n  apply Permutation_Type_vs_cons_inv in HP'.\n  destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.\n  rewrite Heq in HP.\n  apply Permutation_Type_cons_app_inv in HP.\n  dichot_Type_elt_app_exec Heq ; subst.\n  + rewrite app_assoc in HP.\n    apply IHpi in HP.\n    eapply ex_r ; [ apply bot_r | simpl ; rewrite Hperm ]...\n  + dichot_Type_elt_app_exec Heq1 ; subst.\n    * decomp_map_Type Heq0.\n      inversion Heq0.\n    * decomp_map_Type Heq2.\n      inversion Heq2.\n- assert (HP' := HP).\n  symmetry in HP'.\n  apply Permutation_Type_vs_cons_inv in HP'.\n  destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.\n  rewrite Heq in HP.\n  apply Permutation_Type_cons_app_inv in HP.\n  dichot_Type_elt_app_exec Heq ; subst.\n  + rewrite app_assoc in HP.\n    remember (l'l ++ l) as l'.\n    apply Permutation_Type_app_app_inv in HP.\n    destruct HP as [[[l1a l2a] [l3a l4a]] [[HP1 HP2] [HP3 HP4]]] ;\n      simpl in HP1 ; simpl in HP2 ; simpl in HP3 ; simpl in HP4.\n    apply Permutation_Type_app_app_inv in HP4.\n    destruct HP4 as [[[l1b l2b] [l3b l4b]] [[HP1b HP2b] [HP3b HP4b]]] ;\n      simpl in HP1b ; simpl in HP2b ; simpl in HP3b ; simpl in HP4b.\n    symmetry in HP1b.\n    apply Permutation_Type_map_inv in HP1b.\n    destruct HP1b as [la Heqa _].\n    decomp_map_Type Heqa ; simpl in Heqa1 ; simpl in Heqa2 ; subst.\n    symmetry in HP2b.\n    apply Permutation_Type_map_inv in HP2b.\n    destruct HP2b as [lb Heqb _].\n    decomp_map_Type Heqb ; simpl in Heqb1 ; simpl in Heqb2 ; subst.\n    apply (Permutation_Type_app_head l2a) in HP4b.\n    assert (IHP1 := Permutation_Type_trans HP2 HP4b).\n    apply (@Permutation_Type_cons _ A _ eq_refl) in IHP1.\n    rewrite app_comm_cons in IHP1.\n    apply (Permutation_Type_app_head l1a) in HP3b.\n    assert (IHP2 := Permutation_Type_trans HP1 HP3b).\n    apply (@Permutation_Type_cons _ B _ eq_refl) in IHP2.\n    rewrite app_comm_cons in IHP2.\n    apply IHpi1 in IHP1.\n    apply IHpi2 in IHP2.\n    symmetry in HP3.\n    apply (Permutation_Type_cons_app _ _ (tens A B)) in HP3.\n    eapply ex_r ; [ apply tens_r | simpl ; rewrite Hperm ; apply HP3 ]...\n  + dichot_Type_elt_app_exec Heq1 ; subst.\n    * decomp_map_Type Heq0.\n      inversion Heq0 ; subst ; list_simpl in HP.\n      rewrite (app_assoc (map _ l4)) in HP.\n      rewrite <- map_app in HP.\n      remember (l4 ++ l6) as l0 ; clear Heql0.\n      apply Permutation_Type_app_app_inv in HP.\n      destruct HP as [[[l1a l2a] [l3a l4a]] [[HP1 HP2] [HP3 HP4]]] ;\n        simpl in HP1 ; simpl in HP2 ; simpl in HP3 ; simpl in HP4.\n      apply Permutation_Type_app_app_inv in HP4.\n      destruct HP4 as [[[l1b l2b] [l3b l4b]] [[HP1b HP2b] [HP3b HP4b]]] ;\n        simpl in HP1b ; simpl in HP2b ; simpl in HP3b ; simpl in HP4b.\n      symmetry in HP1b.\n      apply Permutation_Type_map_inv in HP1b.\n      destruct HP1b as [la Heqa _].\n      decomp_map_Type Heqa ; simpl in Heqa1 ; simpl in Heqa2 ; subst.\n      symmetry in HP2b.\n      apply Permutation_Type_map_inv in HP2b.\n      destruct HP2b as [lb Heqb _].\n      decomp_map_Type Heqb ; simpl in Heqb1 ; simpl in Heqb2 ; subst.\n      apply (Permutation_Type_app_head l2a) in HP4b.\n      assert (IHP1 := Permutation_Type_trans HP2 HP4b).\n      apply (@Permutation_Type_cons _ bot _ eq_refl) in IHP1.\n      rewrite app_comm_cons in IHP1.\n      apply IHpi1 in IHP1.\n      rewrite <- app_nil_l in IHP1.\n      eapply bot_rev in IHP1 ; [ | apply Hgaxbot ].\n      list_simpl in IHP1.\n      apply (Permutation_Type_app_head l1a) in HP3b.\n      assert (IHP2 := Permutation_Type_trans HP1 HP3b).\n      apply (@Permutation_Type_cons _ bot _ eq_refl) in IHP2.\n      rewrite app_comm_cons in IHP2.\n      apply IHpi2 in IHP2.\n      rewrite <- app_nil_l in IHP2.\n      eapply bot_rev in IHP2 ; [ | apply Hgaxbot ].\n      list_simpl in IHP2.\n      assert (Permutation_Type (l2a ++ l1a) l') as HP' by perm_Type_solve.\n      eapply ex_r ; [ apply mix2_r | simpl ; rewrite Hperm ; apply HP' ]...\n    * decomp_map_Type Heq2.\n      inversion Heq2.\n- assert (HP' := HP).\n  symmetry in HP'.\n  apply Permutation_Type_vs_cons_inv in HP'.\n  destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.\n  rewrite Heq in HP.\n  apply Permutation_Type_cons_app_inv in HP.\n  dichot_Type_elt_app_exec Heq ; subst.\n  + rewrite app_assoc in HP.\n    apply (@Permutation_Type_cons _ B _ eq_refl) in HP.\n    apply (@Permutation_Type_cons _ A _ eq_refl) in HP.\n    rewrite 2 app_comm_cons in HP.\n    apply IHpi in HP.\n    eapply ex_r ; [ apply parr_r | simpl ; rewrite Hperm ]...\n  + dichot_Type_elt_app_exec Heq1 ; subst.\n    * decomp_map_Type Heq0.\n      inversion Heq0.\n    * decomp_map_Type Heq2.\n      inversion Heq2.\n- assert (HP' := HP).\n  symmetry in HP'.\n  apply Permutation_Type_vs_cons_inv in HP'.\n  destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.\n  rewrite Heq in HP.\n  apply Permutation_Type_cons_app_inv in HP.\n  dichot_Type_elt_app_exec Heq ; subst.\n  + eapply ex_r ; [ apply top_r\n                  | simpl ; rewrite Hperm ; apply Permutation_Type_middle ]...\n  + dichot_Type_elt_app_exec Heq1 ; subst.\n    * decomp_map_Type Heq0.\n      inversion Heq0.\n    * decomp_map_Type Heq2.\n      inversion Heq2.\n- assert (HP' := HP).\n  symmetry in HP'.\n  apply Permutation_Type_vs_cons_inv in HP'.\n  destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.\n  rewrite Heq in HP.\n  apply Permutation_Type_cons_app_inv in HP.\n  dichot_Type_elt_app_exec Heq ; subst.\n  + rewrite app_assoc in HP.\n    apply (@Permutation_Type_cons _ A _ eq_refl) in HP.\n    rewrite app_comm_cons in HP.\n    apply IHpi in HP.\n    eapply ex_r ; [ apply plus_r1 | simpl ; rewrite Hperm ]...\n  + dichot_Type_elt_app_exec Heq1 ; subst.\n    * decomp_map_Type Heq0.\n      inversion Heq0.\n    * decomp_map_Type Heq2.\n      inversion Heq2.\n- assert (HP' := HP).\n  symmetry in HP'.\n  apply Permutation_Type_vs_cons_inv in HP'.\n  destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.\n  rewrite Heq in HP.\n  apply Permutation_Type_cons_app_inv in HP.\n  dichot_Type_elt_app_exec Heq ; subst.\n  + rewrite app_assoc in HP.\n    apply (@Permutation_Type_cons _ A _ eq_refl) in HP.\n    rewrite app_comm_cons in HP.\n    apply IHpi in HP.\n    eapply ex_r ; [ apply plus_r2 | simpl ; rewrite Hperm ]...\n  + dichot_Type_elt_app_exec Heq1 ; subst.\n    * decomp_map_Type Heq0.\n      inversion Heq0.\n    * decomp_map_Type Heq2.\n      inversion Heq2.\n- assert (HP' := HP).\n  symmetry in HP'.\n  apply Permutation_Type_vs_cons_inv in HP'.\n  destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.\n  rewrite Heq in HP.\n  apply Permutation_Type_cons_app_inv in HP.\n  dichot_Type_elt_app_exec Heq ; subst.\n  + rewrite app_assoc in HP.\n    assert (HP2 := HP).\n    apply (@Permutation_Type_cons _ A _ eq_refl) in HP.\n    rewrite app_comm_cons in HP.\n    apply IHpi1 in HP.\n    apply (@Permutation_Type_cons _ B _ eq_refl) in HP2.\n    rewrite app_comm_cons in HP2.\n    apply IHpi2 in HP2.\n    eapply ex_r ; [ apply with_r\n                  | simpl ; rewrite Hperm ; apply Permutation_Type_middle ]...\n  + dichot_Type_elt_app_exec Heq1 ; subst.\n    * decomp_map_Type Heq0.\n      inversion Heq0.\n    * decomp_map_Type Heq2.\n      inversion Heq2.\n- assert (HP' := HP).\n  symmetry in HP'.\n  apply Permutation_Type_vs_cons_inv in HP'.\n  destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.\n  rewrite Heq in HP.\n  apply Permutation_Type_cons_app_inv in HP.\n  dichot_Type_elt_app_exec Heq ; subst.\n  + symmetry in HP.\n    apply Permutation_Type_map_inv in HP.\n    destruct HP as [l' Heq HP].\n    decomp_map_Type Heq ;\n      simpl in Heq1 ; simpl in Heq2 ; simpl in Heq3 ; simpl in Heq5 ; subst ;\n      simpl in HP.\n    apply (Permutation_Type_map wn) in HP.\n    list_simpl in HP.\n    rewrite app_assoc in HP.\n    rewrite <- map_app in HP.\n    apply (@Permutation_Type_cons _ A _ eq_refl) in HP.\n    rewrite app_comm_cons in HP.\n    rewrite <- Heq2 in HP.\n    rewrite <- Heq5 in HP.\n    apply IHpi in HP.\n    eapply ex_r ; [ apply oc_r | simpl ; rewrite Hperm ]...\n  + dichot_Type_elt_app_exec Heq1 ; subst.\n    * decomp_map_Type Heq0.\n      inversion Heq0.\n    * decomp_map_Type Heq2.\n      inversion Heq2.\n- assert (HP' := HP).\n  symmetry in HP'.\n  apply Permutation_Type_vs_cons_inv in HP'.\n  destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.\n  rewrite Heq in HP.\n  apply Permutation_Type_cons_app_inv in HP.\n  dichot_Type_elt_app_exec Heq ; subst.\n  + rewrite app_assoc in HP.\n    apply (@Permutation_Type_cons _ A _ eq_refl) in HP.\n    rewrite app_comm_cons in HP.\n    apply IHpi in HP.\n    eapply ex_r ; [ apply de_r | simpl ; rewrite Hperm ]...\n  + dichot_Type_elt_app_exec Heq1 ; subst.\n    * decomp_map_Type Heq0.\n      inversion Heq0.\n    * decomp_map_Type Heq2 ; simpl in Heq1 ; simpl in Heq2 ; simpl in Heq3 ; subst ; simpl in HP.\n      inversion Heq2 ; subst.\n      list_simpl in HP ; rewrite <- map_app in HP.\n      apply (@Permutation_Type_cons _ (tens bot bot) _ eq_refl) in HP.\n      assert (Permutation_Type (tens bot bot :: l)\n                               (l' ++ map (fun _ : unit => tens bot bot) (tt :: l1')\n                                   ++ map (fun _ : unit => wn (tens bot bot)) (l1 ++ l4)))\n        as HP' by (etransitivity ; [ apply HP | ] ; perm_Type_solve). \n      apply IHpi in HP'...\n- assert (HP' := HP).\n  symmetry in HP'.\n  apply Permutation_Type_vs_cons_inv in HP'.\n  destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.\n  rewrite Heq in HP.\n  apply Permutation_Type_cons_app_inv in HP.\n  dichot_Type_elt_app_exec Heq ; subst.\n  + rewrite app_assoc in HP.\n    apply IHpi in HP.\n    eapply ex_r ; [ apply wk_r | simpl ; rewrite Hperm ]...\n  + dichot_Type_elt_app_exec Heq1 ; subst.\n    * decomp_map_Type Heq0.\n      inversion Heq0.\n    * decomp_map_Type Heq2 ; simpl in Heq1 ; simpl in Heq2 ; simpl in Heq3 ; subst ; simpl in HP.\n      inversion Heq2 ; subst.\n      list_simpl in HP ; rewrite <- map_app in HP.\n      apply IHpi in HP...\n- assert (HP' := HP).\n  symmetry in HP'.\n  apply Permutation_Type_vs_cons_inv in HP'.\n  destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.\n  rewrite Heq in HP.\n  apply Permutation_Type_cons_app_inv in HP.\n  dichot_Type_elt_app_exec Heq ; subst.\n  + rewrite app_assoc in HP.\n    apply (@Permutation_Type_cons _ (wn A) _ eq_refl) in HP.\n    apply (@Permutation_Type_cons _ (wn A) _ eq_refl) in HP.\n    rewrite 3 app_comm_cons in HP.\n    apply IHpi in HP.\n    eapply ex_r ; [ apply co_r | simpl ; rewrite Hperm ]...\n  + dichot_Type_elt_app_exec Heq1 ; subst.\n    * decomp_map_Type Heq0.\n      inversion Heq0.\n    * decomp_map_Type Heq2 ; simpl in Heq1 ; simpl in Heq2 ; simpl in Heq3 ; subst ; simpl in HP.\n      inversion Heq2 ; subst.\n      list_simpl in HP ; rewrite <- map_app in HP.\n      apply (@Permutation_Type_cons _ (wn (tens bot bot)) _ eq_refl) in HP.\n      apply (@Permutation_Type_cons _ (wn (tens bot bot)) _ eq_refl) in HP.\n      assert (Permutation_Type (wn (tens bot bot) :: wn (tens bot bot) :: l)\n                               (l' ++ map (fun _ : unit => tens bot bot) l1' ++\n                                  map (fun _ : unit => wn (tens bot bot)) (tt :: tt :: l1 ++ l4)))\n        as HP' by (etransitivity ; [ apply HP | perm_Type_solve ]).\n      apply IHpi in HP'...\n- apply Permutation_Type_app_app_inv in HP.\n  destruct HP as [[[l1a l2a] [l3a l4a]] [[HP1 HP2] [HP3 HP4]]] ;\n    simpl in HP1 ; simpl in HP2 ; simpl in HP3 ; simpl in HP4.\n  apply Permutation_Type_app_app_inv in HP4.\n  destruct HP4 as [[[l1b l2b] [l3b l4b]] [[HP1b HP2b] [HP3b HP4b]]] ;\n    simpl in HP1b ; simpl in HP2b ; simpl in HP3b ; simpl in HP4b.\n  symmetry in HP1b.\n  apply Permutation_Type_map_inv in HP1b.\n  destruct HP1b as [la Heqa _].\n  decomp_map_Type Heqa ; simpl in Heqa1 ; simpl in Heqa2 ; subst.\n  symmetry in HP2b.\n  apply Permutation_Type_map_inv in HP2b.\n  destruct HP2b as [lb Heqb _].\n  decomp_map_Type Heqb ; simpl in Heqb1 ; simpl in Heqb2 ; subst.\n  apply (Permutation_Type_app_head l2a) in HP4b.\n  assert (IHP1 := Permutation_Type_trans HP2 HP4b).\n  apply (@Permutation_Type_cons _ (dual A) _ eq_refl) in IHP1.\n  rewrite app_comm_cons in IHP1.\n  apply (Permutation_Type_app_head l1a) in HP3b.\n  assert (IHP2 := Permutation_Type_trans HP1 HP3b).\n  apply (@Permutation_Type_cons _ A _ eq_refl) in IHP2.\n  rewrite app_comm_cons in IHP2.\n  apply IHpi1 in IHP1.\n  apply IHpi2 in IHP2.\n  symmetry in HP3.\n  eapply ex_r ; [ eapply cut_r | simpl ; rewrite Hperm ; apply HP3 ]...\n- destruct l1' ; destruct l0' ; simpl in HP.\n  + eapply ex_r ; [ apply gax_r | simpl ; rewrite Hperm ]...\n  + exfalso.\n    apply Permutation_Type_vs_elt_inv in HP.\n    specialize (Hgax a).\n    destruct HP as [[l1 l2] Heq] ; rewrite Heq in Hgax.\n    apply Forall_elt in Hgax.\n    inversion Hgax.\n  + exfalso.\n    apply Permutation_Type_vs_elt_inv in HP.\n    specialize (Hgax a).\n    destruct HP as [[l1 l2] Heq] ; rewrite Heq in Hgax.\n    apply Forall_elt in Hgax.\n    inversion Hgax.\n  + exfalso.\n    apply Permutation_Type_vs_elt_inv in HP.\n    specialize (Hgax a).\n    destruct HP as [[l1 l2] Heq] ; rewrite Heq in Hgax.\n    apply Forall_elt in Hgax.\n    inversion Hgax.\nQed.\n\nLemma ll_to_mix2_cut {P} : forall l,\n  ll P (wn (tens bot bot) :: l) -> ll (mk_pfrag true P.(pgax) P.(pmix0) true P.(pperm)) l.\nProof with myeasy.\nintros l pi.\neapply stronger_pfrag in pi.\n- rewrite <- (app_nil_r l).\n  eapply cut_r ; [ | | apply pi]...\n  change nil with (map wn nil).\n  apply oc_r.\n  apply parr_r.\n  change (one :: one :: map wn nil) with ((one :: nil) ++ one :: nil).\n  eapply mix2_r...\n  + apply one_r.\n  + apply one_r.\n- nsplit 5...\n  + destruct pcut...\n  + intros a.\n    exists a...\n  + destruct pmix2...\nQed.\n\n(** Provability in [ll_mix2] is equivalent to\nprovability of [ll] extended with the provability of [one :: one :: nil]\nand to provability of [ll] extended with the provability of [parr (dual B) (dual A) :: tens A B :: nil]\nfor all [A] and [B] *)\n\nLemma mix2_to_ll_one_one {P} : pcut P = true -> pperm P = true -> forall bc b2 bp l,\n  ll (mk_pfrag bc P.(pgax) P.(pmix0) b2 bp) l ->\n    ll (axupd_pfrag P (existT (fun x => x -> list formula) _\n                              (fun a => match a with\n                                        | inl x => projT2 (pgax P) x\n                                        | inr tt => one :: one :: nil\n                                        end))) l.\nProof with myeeasy ; try (unfold PCperm_Type ; PCperm_Type_solve).\nremember (axupd_pfrag P (existT (fun x => x -> list formula) _\n                                (fun a => match a with\n                                          | inl x => projT2 (pgax P) x\n                                          | inr tt => one :: one :: nil\n                                          end))) as P'.\nintros fc fp bc b2 bp l pi.\neapply stronger_pfrag in pi.\n- eapply mix2_to_ll in pi...\n  assert (pcut P' = true) as fc' by (rewrite HeqP' ; simpl ; assumption).\n  apply (stronger_pfrag _ P') in pi.\n  + assert (ll P' (parr one one :: map wn nil)) as pi'.\n    { change (parr one one :: map wn nil) with ((parr one one :: nil) ++ nil).\n      eapply (@cut_r _ fc' bot).\n      - apply one_r.\n      - apply bot_r.\n        apply parr_r.\n        assert ({ b | one :: one :: nil = projT2 (pgax P') b })\n          as [b Hgax] by (rewrite HeqP' ; now (exists (inr tt))).\n        rewrite Hgax.\n        apply gax_r. }\n    apply oc_r in pi'.\n    rewrite <- (app_nil_l l).\n    eapply (@cut_r _ fc' (oc (parr one one))) ; [ simpl ; apply pi | apply pi' ].\n  + nsplit 5 ; rewrite HeqP'...\n    simpl ; intros a ; exists (inl a)...\n- nsplit 5 ; intros ; simpl...\n  + rewrite fc.\n    destruct bc...\n  + exists a...\nQed.\n\nLemma ll_one_one_to_ll_tens_parr_one_one_cut {P} : (pcut P = true) ->\n  ll P (parr one one :: parr bot bot :: nil) -> ll P (one :: one :: nil).\nProof.\nintros Hcut pi.\nassert (ll P (dual (parr (parr one one) (parr bot bot)) :: one :: one :: nil)) as pi'.\n{ simpl.\n  rewrite <- (app_nil_r _) ; rewrite <- app_comm_cons.\n  apply tens_r.\n  - rewrite <- (app_nil_r _) ; rewrite <- app_comm_cons.\n    apply tens_r ; apply one_r.\n  - rewrite <- (app_nil_l (one :: nil)).\n    rewrite (app_comm_cons _ _ one).\n    apply tens_r ; apply ax_exp. }\nrewrite <- (app_nil_l _).\neapply cut_r ; [ assumption | apply pi' | ].\napply parr_r ; apply pi.\nQed.\n\nLemma ll_tens_parr_one_one_to_ll_tens_parr {P} : forall l,\n  ll (axupd_pfrag P (existT (fun x => x -> list formula) _\n                              (fun a => match a with\n                                        | inl x => projT2 (pgax P) x\n                                        | inr tt => parr one one :: parr bot bot :: nil\n                                        end))) l\n  -> ll (axupd_pfrag P (existT (fun x => x -> list formula) _\n                              (fun a => match a with\n                                        | inl x => projT2 (pgax P) x\n                                        | inr (A,B) => parr (dual B) (dual A) :: parr A B :: nil\n                                        end))) l.\nProof with myeeasy.\nintros l pi.\nremember (axupd_pfrag P (existT (fun x => x -> list formula) _\n                         (fun a => match a with\n                                   | inl x => projT2 (pgax P) x\n                                   | inr tt => parr one one :: parr bot bot :: nil\n                                   end))) as P'.\napply (ax_gen P') ; (try now (rewrite HeqP' ; simpl ; reflexivity))...\nclear - HeqP' ; simpl ; intros a.\nrevert a ; rewrite HeqP' ; intros a ; destruct a ; simpl.\n- assert ({ b | projT2 (pgax P) p =\n                projT2 (pgax (axupd_pfrag P (existT (fun x => x -> list formula) _\n                       (fun a => match a with\n                                 | inl x => projT2 (pgax P) x\n                                 | inr (A,B) => parr (dual B) (dual A) :: parr A B :: nil\n                                 end)))) b })\n    as [b Hgax] by (now exists (inl p)).\n  rewrite Hgax.\n  apply gax_r.\n- destruct u.\n  assert ({ b | parr one one :: parr bot bot :: nil =\n                projT2 (pgax (axupd_pfrag P (existT (fun x => x -> list formula) _\n                       (fun a => match a with\n                                 | inl x => projT2 (pgax P) x\n                                 | inr (A,B) => parr (dual B) (dual A) :: parr A B :: nil\n                                 end)))) b })\n    as [b Hgax] by (exists (inr (bot,bot)) ; reflexivity).\n  rewrite Hgax.\n  apply gax_r.\nQed.\n\nLemma ll_tens_parr_to_mix2 {P} : forall l,\n  ll (axupd_pfrag P (existT (fun x => x -> list formula) _\n                              (fun a => match a with\n                                        | inl x => projT2 (pgax P) x\n                                        | inr (A,B) => parr (dual B) (dual A) :: parr A B :: nil\n                                        end))) l\n  -> ll (mk_pfrag P.(pcut) P.(pgax) P.(pmix0) true P.(pperm)) l.\nProof with myeeasy.\nintros l pi.\nremember (mk_pfrag P.(pcut) P.(pgax) P.(pmix0) true P.(pperm)) as P'.\napply (stronger_pfrag _\n  (axupd_pfrag P' (existT (fun x => x -> list formula) _\n                          (fun a => match a with\n                                    | inl x => projT2 (pgax P) x\n                                    | inr (A,B) => parr (dual B) (dual A) :: parr A B :: nil\n                                    end)))) in pi.\n- eapply ax_gen...\n  clear - HeqP' ; simpl ; intros a.\n  destruct a.\n  + assert ({ b | projT2 (pgax P) p = projT2 (pgax P') b })\n      as [b Hgax] by (rewrite HeqP' ; now exists p).\n    rewrite Hgax.\n    apply gax_r.\n  + destruct p as [A B].\n    apply parr_r.\n    apply (ex_r _ (parr A B :: (dual B :: nil) ++ (dual A) :: nil)) ;\n      [ |etransitivity ; [ apply PCperm_Type_last | reflexivity ] ].\n    apply parr_r.\n    eapply ex_r ;\n      [ | symmetry ; apply PCperm_Type_last ].\n    list_simpl.\n    rewrite <- (app_nil_l (dual A :: _)).\n    rewrite 2 app_comm_cons.\n    apply mix2_r.\n    * rewrite HeqP'...\n    * eapply ex_r ; [ | apply PCperm_Type_swap ].\n      apply ax_exp.\n    * apply ax_exp.\n- rewrite HeqP' ; nsplit 5 ; simpl ; intros...\n  + exists a...\n  + destruct (pmix2 P)...\nQed.\n\nLemma ll_one_one_to_mix2 {P} : forall l,\n  ll (axupd_pfrag P (existT (fun x => x -> list formula) _\n                              (fun a => match a with\n                                        | inl x => projT2 (pgax P) x\n                                        | inr tt => one :: one :: nil\n                                        end))) l\n  -> ll (mk_pfrag P.(pcut) P.(pgax) P.(pmix0) true P.(pperm)) l.\nProof with myeeasy.\nintros l pi.\nremember (mk_pfrag P.(pcut) P.(pgax) P.(pmix0) true P.(pperm)) as P'.\napply (stronger_pfrag _\n  (axupd_pfrag P' (existT (fun x => x -> list formula) _\n                          (fun a => match a with\n                                    | inl x => projT2 (pgax P) x\n                                    | inr tt => one :: one :: nil\n                                    end)))) in pi.\n- eapply ax_gen...\n  clear - HeqP' ; simpl ; intros a.\n  destruct a.\n  + assert ({ b | projT2 (pgax P) p = projT2 (pgax P') b })\n      as [b Hgax] by (rewrite HeqP' ; now exists p).\n    rewrite Hgax.\n    apply gax_r.\n  + destruct u.\n    change (one :: one :: nil) with ((one :: nil) ++ one :: nil).\n    rewrite HeqP'.\n    apply mix2_r...\n    * apply one_r.\n    * apply one_r.\n- rewrite HeqP' ; nsplit 5 ; simpl ; intros...\n  + exists a...\n  + destruct (pmix2 P)...\nQed.\n\n(** [mix0] is not valid in [ll_mix2] *)\n\nLemma mix2_not_mix0 : ll_mix2 nil -> False.\nProof.\nintros pi.\nremember nil as l.\nrevert Heql ; induction pi ; intros Heql ; subst ; try inversion Heql.\n- apply IHpi.\n  simpl in p ; apply Permutation_Type_sym in p.\n  apply Permutation_Type_nil in p.\n  assumption.\n- apply app_eq_nil in Heql ; destruct Heql as [Heql Heql2].\n  apply app_eq_nil in Heql2 ; destruct Heql2 as [Heql2 _] ; subst.\n  destruct lw' ; inversion Heql2.\n  symmetry in p ; apply Permutation_Type_nil in p ; subst.\n  intuition.\n- inversion f.\n- apply IHpi2.\n  apply app_eq_nil in Heql.\n  apply Heql.\n- inversion f.\n- destruct a.\nQed.\n\n\n(** ** Linear logic with both mix0 and mix2: [ll_mix02] (no axiom, commutative) *)\n\n(** cut / axioms / mix0 / mix2 / permutation *)\nDefinition pfrag_mix02 := mk_pfrag false NoAxioms true true true.\n(*                                 cut   axioms   mix0 mix2 perm  *)\n\nDefinition ll_mix02 := ll pfrag_mix02.\n\nLemma cut_mix02_r : forall A l1 l2,\n  ll_mix02 (dual A :: l1) -> ll_mix02 (A :: l2) -> ll_mix02 (l2 ++ l1).\nProof with myeeasy.\nintros A l1 l2 pi1 pi2.\neapply cut_r_axfree...\nintros a ; destruct a.\nQed.\n\nLemma cut_mix02_admissible :\n  forall l, ll (cutupd_pfrag pfrag_mix02 true) l -> ll_mix02 l.\nProof with myeeasy.\nintros l pi.\ninduction pi ; try (now econstructor).\n- eapply ex_r...\n- eapply ex_wn_r...\n- eapply cut_mix02_r...\nQed.\n\n(** Provability in [ll_mix02] is equivalent to adding [wn (tens (wn one) (wn one))] in [ll] *)\n\nLemma mix02_to_ll {P} : pperm P = true -> forall b1 b2 bp l,\n  ll (mk_pfrag P.(pcut) P.(pgax) b1 b2 bp) l -> ll P (wn (tens (wn one) (wn one)) :: l).\nProof with myeeasy ; try PCperm_Type_solve.\nintros fp b1 b2 bp l pi.\neapply (ext_wn_param _ P fp _ (tens (wn one) (wn one) :: nil)) in pi.\n- eapply ex_r...\n- intros Hcut...\n- simpl ; intros a.\n  eapply ex_r ; [ | apply PCperm_Type_last ].\n  apply wk_r.\n  apply gax_r.\n- intros Hpmix0 Hpmix0'.\n  apply de_r...\n  rewrite <- (app_nil_l nil).\n  apply tens_r ; apply de_r ; apply one_r.\n- intros _ _ l1 l2 pi1 pi2.\n  apply (ex_r _ (wn (tens (wn one) (wn one)) :: l2 ++ l1))...\n  apply co_r.\n  apply co_r.\n  apply de_r.\n  eapply ex_r.\n  + apply tens_r ; apply wk_r ; [ apply pi1 | apply pi2 ].\n  + rewrite fp...\nQed.\n\nLemma ll_to_mix02_cut {P} : forall l,\n  ll P (wn (tens (wn one) (wn one)) :: l) -> ll (mk_pfrag true P.(pgax) true true P.(pperm)) l.\nProof with myeasy.\nintros l pi.\neapply stronger_pfrag in pi.\n- rewrite <- (app_nil_r l).\n  eapply cut_r ; [ | | apply pi]...\n  change nil with (map wn nil).\n  apply oc_r.\n  apply parr_r.\n  change (oc bot :: oc bot :: map wn nil) with ((oc bot :: map wn nil) ++ oc bot :: map wn nil).\n  eapply mix2_r...\n  + apply oc_r.\n    apply bot_r.\n    apply mix0_r...\n  + apply oc_r.\n    apply bot_r.\n    apply mix0_r...\n- nsplit 5...\n  + destruct pcut...\n  + intros a.\n    exists a...\n  + destruct pmix0...\n  + destruct pmix2...\nQed.\n\n(** Provability in [ll_mix02] is equivalent to adding other stuff in [ll] *)\n\nLemma mix02_to_ll' {P} : pperm P = true -> forall b0 b2 bp l,\n  ll (mk_pfrag P.(pcut) P.(pgax) b0 b2 bp) l -> ll P (wn one :: wn (tens bot bot) :: l).\nProof with myeasy.\nintros Hperm b0 b2 bp l pi.\neapply mix0_to_ll...\neapply mix2_to_ll...\napply pi.\nQed.\n\nLemma ll_to_mix02'_axat {P} : (forall a, Forall atomic (projT2 (pgax P) a)) ->\n  pperm P = true -> forall l,\n  ll P (wn one :: wn (tens bot bot) :: l) -> ll (mix2add_pfrag (mix0add_pfrag P)) l.\nProof with myeasy.\nintros Hgax Hperm l pi.\napply ll_to_mix2_axat...\napply ll_to_mix0_axat...\nQed.\n\nLemma mix02_to_ll'' {P} : pperm P = true -> forall b0 b2 bp l,\n  ll (mk_pfrag P.(pcut) P.(pgax) b0 b2 bp) l -> ll P (wn one :: wn (tens (wn one) bot) :: l).\nProof with myeeasy ; try PCperm_Type_solve.\nintros Hperm b0 b2 bp l pi.\neapply (ext_wn_param _ _ _ _ (one :: tens (wn one) bot :: nil)) in pi.\n- eapply ex_r...\n- intros Hcut...\n- simpl ; intros a.\n  eapply ex_r ; [ | apply PCperm_Type_app_comm ] ; list_simpl.\n  apply wk_r.\n  apply wk_r.\n  apply gax_r.\n- intros Hpmix0 Hpmix0'.\n  apply de_r...\n  eapply ex_r ; [ | apply PCperm_Type_swap ].\n  apply wk_r.\n  apply one_r.\n- intros _ _ l1 l2 pi1 pi2.\n  apply (ex_r _ (wn (tens (wn one) bot) :: (wn one :: l2) ++ l1)) ; [ | rewrite Hperm ]...\n  apply co_r.\n  apply co_r.\n  apply de_r.\n  apply (ex_r _ (tens (wn one) bot :: (wn (tens (wn one) bot) :: wn one :: l2)\n                                   ++ (wn (tens (wn one) bot) :: l1))) ;\n    [ | rewrite Hperm ]...\n  apply tens_r.\n  + eapply ex_r ; [ apply pi1 | ]...\n  + apply bot_r ; eapply ex_r ; [ apply pi2 | rewrite Hperm ]...\nUnshelve. assumption.\nQed.\n\n(* Hgax_cut is here only to allow the use of cut_admissible\n   the more general result without Hgax_cut should be provable by induction as for [ll_to_mix2] *)\nLemma ll_to_mix02''_axcut {P} : (forall a, Forall atomic (projT2 (pgax P) a)) ->\n  (forall a b x l1 l2 l3 l4,\n     projT2 (pgax P) a = (l1 ++ dual x :: l2) -> projT2 (pgax P) b = (l3 ++ x :: l4) ->\n     { c | projT2 (pgax P) c = l3 ++ l2 ++ l1 ++ l4 }) ->\n  pperm P = true -> forall l,\n  ll P (wn one :: wn (tens (wn one) bot) :: l) -> ll (mix2add_pfrag (mix0add_pfrag P)) l.\nProof with myeasy.\nintros Hgax_at Hgax_cut Hperm l pi.\napply (stronger_pfrag (cutrm_pfrag (cutupd_pfrag (mix2add_pfrag (mix0add_pfrag P)) true))).\n{ nsplit 5...\n  intros a ; exists a... }\neapply cut_admissible...\neapply stronger_pfrag in pi.\n- rewrite <- (app_nil_r l).\n  eapply (cut_r _ (wn (tens (wn one) bot))) ; simpl.\n  + change nil with (map wn nil).\n    apply oc_r.\n    apply parr_r.\n    change (one :: oc bot :: map wn nil) with ((one :: nil) ++ oc bot :: map wn nil).\n    eapply mix2_r...\n    * apply oc_r.\n      apply bot_r.\n      apply mix0_r...\n    * apply one_r.\n  + rewrite <- app_nil_r.\n    eapply cut_r ; [ | | apply pi ] ; simpl...\n    change nil with (map wn nil).\n    apply oc_r.\n    apply bot_r.\n    apply mix0_r...\n- etransitivity ; [ apply cutupd_pfrag_true| ].\n  nsplit 5...\n  + intros a ; exists a...\n  + apply leb_true.\n  + apply leb_true.\nUnshelve. reflexivity.\nQed.\n\n(* Hgax_cut is here only to allow the use of cut_admissible\n   the more general result without Hgax_cut should be provable by induction as for [ll_to_mix2] *)\nLemma ll_to_mix02'''_axcut {P} : (forall a, Forall atomic (projT2 (pgax P) a)) ->\n  (forall a b x l1 l2 l3 l4,\n     projT2 (pgax P) a = (l1 ++ dual x :: l2) -> projT2 (pgax P) b = (l3 ++ x :: l4) ->\n     { c | projT2 (pgax P) c = l3 ++ l2 ++ l1 ++ l4 }) ->\n  pperm P = true -> forall l (l0 : list unit),\n  ll P (wn one :: map (fun _ => wn (tens (wn one) bot)) l0 ++ l)  ->\n  ll (mix2add_pfrag (mix0add_pfrag P)) l.\nProof with try assumption.\nintros Hgax_at Hgax_cut Hperm l l0 pi.\napply ll_to_mix02''_axcut...\nrevert l pi ; induction l0 ; intros l pi.\n- cons2app.\n  eapply ex_r ; [ | rewrite Hperm ; apply Permutation_Type_app_comm ].\n  simpl ; apply wk_r.\n  eapply ex_r ; [ | rewrite Hperm ; apply Permutation_Type_app_comm ]...\n- cons2app.\n  eapply ex_r ; [ | rewrite Hperm ; apply Permutation_Type_app_comm ].\n  simpl ; apply co_r.\n  rewrite 2 app_comm_cons.\n  eapply ex_r ; [ | rewrite Hperm ; apply Permutation_Type_app_comm ].\n  list_simpl ; apply IHl0.\n  list_simpl in pi.\n  eapply ex_r ; [ apply pi | rewrite Hperm ; PCperm_Type_solve ].\nQed.\n\n\n(** Provability in [ll_mix02] is equivalent to provability of [ll]\nextended with the provability of both [bot :: bot :: nil] and [one :: one :: nil] *)\n\nLemma mix02_to_ll_one_eq_bot {P} : pcut P = true -> pperm P = true -> forall bc b0 b2 bp l,\n  ll (mk_pfrag bc P.(pgax) b0 b2 bp) l ->\n    ll (axupd_pfrag P (existT (fun x => x -> list formula) _\n                              (fun a => match a with\n                                        | inl x => projT2 (pgax P) x\n                                        | inr true => one :: one :: nil\n                                        | inr false => bot :: bot :: nil\n                                        end))) l.\nProof with myeeasy ; try (unfold PCperm_Type ; PCperm_Type_solve).\nremember (axupd_pfrag P (existT (fun x => x -> list formula) _\n                                (fun a => match a with\n                                          | inl x => projT2 (pgax P) x\n                                          | inr true => one :: one :: nil\n                                          | inr false => bot :: bot :: nil\n                                          end))) as P'.\nintros fc fp bc b0 b2 bp l pi.\neapply stronger_pfrag in pi.\n- eapply mix02_to_ll in pi...\n  assert (pcut P' = true) as fc' by (rewrite HeqP' ; simpl ; assumption).\n  apply (stronger_pfrag _ P') in pi.\n  + assert (ll P' (parr (oc bot) (oc bot) :: map wn nil)) as pi'.\n    { apply parr_r.\n      change (oc bot :: oc bot :: map wn nil)\n        with ((oc bot :: nil) ++ oc bot :: map wn nil).\n      eapply (@cut_r _ fc' one).\n      - apply bot_r.\n        apply oc_r.\n        change (bot :: map wn nil) with ((bot :: nil) ++ nil).\n        eapply (@cut_r _ fc' bot).\n        + apply one_r.\n        + assert ({ b | bot :: bot :: nil = projT2 (pgax P') b })\n            as [b Hgax] by (rewrite HeqP' ; now (exists (inr false))).\n          rewrite Hgax.\n          apply gax_r.\n      - change (one :: oc bot :: nil)\n          with ((one :: nil) ++ oc bot :: map wn nil).\n        eapply (@cut_r _ fc' one).\n        + apply bot_r.\n          apply oc_r.\n          change (bot :: map wn nil) with ((bot :: nil) ++ nil).\n          eapply (@cut_r _ fc' bot).\n          * apply one_r.\n          * assert ({ b | bot :: bot :: nil = projT2 (pgax P') b })\n              as [b Hgax] by (rewrite HeqP' ; now (exists (inr false))).\n            rewrite Hgax.\n            apply gax_r.\n        + assert ({ b | one :: one :: nil = projT2 (pgax P') b })\n            as [b Hgax] by (rewrite HeqP' ; now (exists (inr true))).\n          rewrite Hgax.\n          apply gax_r. }\n    apply oc_r in pi'.\n    rewrite <- (app_nil_l l).\n    eapply (@cut_r _ fc' (oc (parr (oc bot) (oc bot)))) ; [ simpl ; apply pi | apply pi' ].\n  + nsplit 5 ; rewrite HeqP'...\n    simpl ; intros a ; exists (inl a)...\n- nsplit 5 ; intros ; simpl...\n  + rewrite fc.\n    destruct bc...\n  + exists a...\nQed.\n\nLemma ll_one_eq_bot_to_mix02 {P} : forall l,\n  ll (axupd_pfrag P (existT (fun x => x -> list formula) _\n                            (fun a => match a with\n                                      | inl x => projT2 (pgax P) x\n                                      | inr true => one :: one :: nil\n                                      | inr false => bot :: bot :: nil\n                                      end))) l\n  -> ll (mk_pfrag P.(pcut) P.(pgax) true true P.(pperm)) l.\nProof with myeeasy.\nintros l pi.\nremember (mk_pfrag P.(pcut) P.(pgax) true true P.(pperm)) as P'.\napply (stronger_pfrag _\n  (axupd_pfrag P' (existT (fun x => x -> list formula) _\n                          (fun a => match a with\n                                    | inl x => projT2 (pgax P) x\n                                    | inr true => one :: one :: nil\n                                    | inr false => bot :: bot :: nil\n                                    end)))) in pi.\n- eapply ax_gen...\n  clear - HeqP' ; simpl ; intros a.\n  destruct a.\n  + assert ({ b | projT2 (pgax P) p = projT2 (pgax P') b })\n      as [b Hgax] by (rewrite HeqP' ; now exists p).\n    rewrite Hgax.\n    apply gax_r.\n  + destruct b.\n    * change (one :: one :: nil) with ((one :: nil) ++ one :: nil).\n      rewrite HeqP'.\n      apply mix2_r...\n      -- apply one_r.\n      -- apply one_r.\n    * apply bot_r.\n      apply bot_r.\n      rewrite HeqP'.\n      apply mix0_r...\n- rewrite HeqP' ; nsplit 5 ; simpl ; intros...\n  + exists a...\n  + destruct (pmix0 P)...\n  + destruct (pmix2 P)...\nQed.\n\n\n(* llR *)\n\n(** ** Linear logic extended with [R] = [bot]: [llR] *)\n\n(** cut / axioms / mix0 / mix2 / permutation *)\nDefinition pfrag_llR R :=\n  mk_pfrag true (existT (fun x => x -> list formula) _\n                        (fun a => match a with\n                                  | true => dual R :: nil\n                                  | false => R :: one :: nil\n                                  end))\n             false false true.\n(*         cut  axioms\n             mix0  mix2  perm  *)\n\nDefinition llR R := ll (pfrag_llR R).\n\nLemma llR1_R2 : forall R1 R2,\n  llR R2 (dual R1 :: R2 :: nil) -> llR R2 (dual R2 :: R1 :: nil) ->\n    forall l, llR R1 l-> llR R2 l.\nProof with myeeasy.\nintros R1 R2 HR1 HR2 l Hll.\ninduction Hll ; try (now constructor).\n- eapply ex_r...\n- eapply ex_wn_r...\n- eapply cut_r...\n- destruct a.\n  + rewrite <- (app_nil_l _).\n    apply (@cut_r (pfrag_llR R2) eq_refl (dual R2)).\n    * rewrite bidual.\n      eapply ex_r.\n      apply HR1.\n      apply PCperm_Type_swap.\n    * assert ({ b | dual R2 :: nil = projT2 (pgax (pfrag_llR R2)) b })\n        as [b Hgax] by (now exists true).\n      rewrite Hgax.\n      apply gax_r.\n  + eapply (@cut_r (pfrag_llR R2) eq_refl R2) in HR2.\n    * eapply ex_r ; [ apply HR2 | ].\n      unfold PCperm_Type.\n      simpl.\n      apply Permutation_Type_sym.\n      apply Permutation_Type_cons_app.\n      rewrite app_nil_r.\n      apply Permutation_Type_refl.\n    * assert ({ b | R2 :: one :: nil = projT2 (pgax (pfrag_llR R2)) b })\n        as [b Hgax] by (now exists false).\n      rewrite Hgax.\n      apply gax_r.\nQed.\n\nLemma ll_to_llR : forall R l, ll_ll l -> llR R l.\nProof with myeeasy.\nintros R l pi.\ninduction pi ; try (now econstructor).\n- eapply ex_r...\n- eapply ex_wn_r...\nQed.\n\nLemma subs_llR : forall R C x l, llR R l -> llR (subs C x R) (map (subs C x) l).\nProof with myeeasy.\nintros R C x l pi.\napply (subs_ll C x) in pi.\neapply stronger_pfrag in pi...\nnsplit 5...\nsimpl ; intros a.\ndestruct a ; simpl.\n- exists true.\n  rewrite subs_dual...\n- exists false...\nQed.\n\nLemma llR_to_ll : forall R l, llR R l-> ll_ll (l ++ wn R :: wn (tens (dual R) bot) :: nil).\nProof with myeasy.\nintros R l pi.\napply cut_ll_admissible.\nreplace (wn R :: wn (tens (dual R) bot) :: nil) with (map wn (map dual (dual R :: parr one R :: nil)))\n  by (simpl ; rewrite bidual ; reflexivity).\napply deduction_list...\neapply ax_gen ; [ | | | | | apply pi ]...\nsimpl ; intros a.\ndestruct a ; simpl.\n- assert ({ b | dual R :: nil = projT2 (pgax (axupd_pfrag (cutupd_pfrag pfrag_ll true)\n    (existT (fun x => x -> list formula) (sum _ {k : nat | k < 2})\n            (fun a => match a with\n                      | inl x => Empty_fun x\n                      | inr x => match proj1_sig x with\n                                 | 0 => dual R\n                                 | 1 => parr one R\n                                 | 2 => one\n                                 | S (S (S _)) => one\n                                 end :: nil\n                      end)))) b })\n    as [b Hgax] by (now exists (inr (exist _ 0 (le_n_S _ _ (le_S _ _ (le_n 0)))))).\n  rewrite Hgax.\n  apply gax_r.\n- rewrite <- (app_nil_r nil).\n  rewrite_all app_comm_cons.\n  eapply (cut_r _ (dual (parr one R))).\n  + rewrite bidual.\n    assert ({ b | parr one R :: nil = projT2 (pgax (axupd_pfrag (cutupd_pfrag pfrag_ll true)\n      (existT (fun x => x -> list formula) (sum _ {k : nat | k < 2})\n              (fun a => match a with\n                        | inl x => Empty_fun x\n                        | inr x => match proj1_sig x with\n                                   | 0 => dual R\n                                   | 1 => parr one R\n                                   | 2 => one\n                                   | S (S (S _)) => one\n                                   end :: nil\n                        end)))) b })\n      as [b Hgax] by (now exists (inr (exist _ 1 (le_n 2)))).\n    erewrite Hgax.\n    apply gax_r.\n  + apply (ex_r _ (tens (dual R) bot :: (one :: nil) ++ R :: nil)) ; [ | PCperm_Type_solve ].\n    apply tens_r.\n    * eapply ex_r ; [ | apply PCperm_Type_swap ].\n      eapply stronger_pfrag ; [ | apply ax_exp ].\n      nsplit 5...\n      simpl ; intros a.\n      destruct a as [a | a].\n      -- destruct a.\n      -- destruct a as [n Hlt].\n         destruct n ; simpl.\n         ++ exists (inr (exist _ 0 Hlt))...\n         ++ destruct n ; simpl.\n            ** exists (inr (exist _ 1 Hlt))...\n            ** exfalso.\n               inversion Hlt ; subst.\n               inversion H0 ; subst.\n               inversion H1.\n    * apply bot_r.\n      apply one_r.\nUnshelve. reflexivity.\nQed.\n\nLemma llwnR_to_ll : forall R l, llR (wn R) l -> ll_ll (l ++ wn R :: nil).\nProof with myeeasy.\nintros R l pi.\napply llR_to_ll in pi.\neapply (ex_r _ _ (wn (tens (dual (wn R)) bot) :: l ++ wn (wn R) :: nil)) in pi ;\n  [ | PCperm_Type_solve ].\neapply (cut_ll_r _ nil) in pi.\n- eapply (cut_ll_r (wn (wn R))).\n  + simpl.\n    change (wn R :: nil) with (map wn (R :: nil)).\n    apply oc_r ; simpl.\n    replace (wn R) with (dual (oc (dual R))) by (simpl ; rewrite bidual ; reflexivity).\n    apply ax_exp.\n  + eapply ex_r ; [ apply pi | PCperm_Type_solve ].\n- simpl ; rewrite bidual.\n  change nil with (map wn nil).\n  apply oc_r.\n  apply parr_r.\n  eapply ex_r ; [ apply wk_r ; apply one_r | PCperm_Type_solve ].\nQed.\n\nLemma ll_wn_wn_to_llR : forall R l, ll_ll (l ++ wn R :: wn (tens (dual R) bot) :: nil) -> llR R l.\nProof with myeasy.\nintros R l pi.\napply (ll_to_llR R) in pi.\nrewrite <- (app_nil_l l).\neapply (cut_r _ (oc (dual R))).\n- rewrite <- (app_nil_l (dual _ :: l)).\n  eapply (cut_r _ (oc (parr one R))).\n  + simpl ; rewrite bidual ; eapply ex_r ; [apply pi | PCperm_Type_solve ].\n  + change nil with (map wn nil).\n    apply oc_r.\n    apply parr_r.\n    apply (ex_r _ (R :: one :: nil)).\n    * assert ({ b | R :: one :: nil = projT2 (pgax (pfrag_llR R)) b })\n        as [b Hgax] by (now exists false).\n      rewrite Hgax.\n      apply gax_r.\n    * PCperm_Type_solve.\n- change nil with (map wn nil).\n  apply oc_r.\n  assert ({ b | dual R :: map wn nil = projT2 (pgax (pfrag_llR R)) b })\n    as [b Hgax] by (now exists true).\n  rewrite Hgax.\n  apply gax_r.\nUnshelve. all : reflexivity.\nQed.\n\nLemma ll_wn_to_llwnR : forall R l, ll_ll (l ++ wn R :: nil) -> llR (wn R) l.\nProof with myeasy.\nintros R l pi.\neapply ll_wn_wn_to_llR.\neapply (ex_r _ (wn (tens (dual (wn R)) bot) :: wn (wn R) :: l)) ;\n  [ | PCperm_Type_solve ].\napply wk_r.\napply de_r.\neapply ex_r ; [ apply pi | PCperm_Type_solve ].\nQed.\n\n\n\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/ll_fragments.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.2966962745201913}}
{"text": "Require Import Coq.Bool.Bool.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.Lists.List. Import ListNotations.\nRequire Import bedrock2.MetricLogging.\nRequire Import coqutil.Macros.unique.\nRequire Import bedrock2.Memory.\nRequire Import compiler.util.Common.\nRequire Import coqutil.Decidable.\nRequire Import coqutil.Datatypes.PropSet.\nRequire Import coqutil.Byte.\nRequire Import bedrock2.Syntax.\nRequire Import coqutil.Z.Lia.\nRequire Import compiler.SeparationLogic.\nRequire Import bedrock2.Semantics.\nRequire Import coqutil.Word.Interface.\nRequire Import compiler.FlatImp.\nRequire Import coqutil.Datatypes.ListSet.\n\nLocal Hint Mode Word.Interface.word - : typeclass_instances.\n\nModule exec.\n  Section FlatImpExec.\n    Context {varname: Type} {varname_eqb: varname -> varname -> bool}.\n    Context {width: Z} {BW: Bitwidth width} {word: word.word width}.\n    Context {mem: map.map word byte} {locals: map.map varname word}\n            {env: map.map String.string (list varname * list varname * stmt varname)}.\n    Context {ext_spec: ExtSpec}.\n    Context {varname_eq_spec: EqDecider varname_eqb}\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: ext_spec.ok ext_spec}.\n    Variable (e: env).\n\n    Local Notation metrics := MetricLog.\n\n    Definition one sz addr (value: word) : mem -> Prop :=\n      littleendian (bytes_per (width:=width) sz) addr (word.unsigned value).\n\n    (* COQBUG(unification finds Type instead of Prop and fails to downgrade *)\n    Implicit Types post : trace -> mem -> locals -> metrics -> Prop.\n\n    Inductive exec:\n      stmt varname ->\n      trace -> mem -> locals -> metrics ->\n      (trace -> mem -> locals -> metrics -> Prop)\n    -> Prop :=\n\n    | interact: forall t m Keep Give l mc action argvars argvals resvars outcome post,\n        (Keep * Give)%sep m ->\n        map.getmany_of_list l argvars = Some argvals ->\n        (forall mGive, Give mGive ->\n            ext_spec t mGive action argvals outcome /\\\n            forall mReceive resvals,\n            outcome mReceive resvals ->\n            exists l', map.putmany_of_list_zip resvars resvals l = Some l' /\\\n            forall m', (Keep * eq mReceive)%sep m' ->\n            post (((mGive, action, argvals), (mReceive, resvals)) :: t) m' l'\n                 (addMetricInstructions 1\n                 (addMetricStores 1\n                 (addMetricLoads 2 mc)))) ->\n        exec (SInteract resvars action argvars) t m l mc post\n\n    | call: forall t m l mc binds fname args params rets fbody argvs st0 post outcome,\n        map.get e fname = Some (params, rets, fbody) ->\n        map.getmany_of_list l args = Some argvs ->\n        map.putmany_of_list_zip params argvs map.empty = Some st0 ->\n        exec fbody t m st0 mc outcome ->\n        (forall t' m' mc' st1,\n            outcome t' m' st1 mc' ->\n            exists retvs l',\n              map.getmany_of_list st1 rets = Some retvs /\\\n              map.putmany_of_list_zip binds retvs l = Some l' /\\\n              post t' m' l' mc') ->\n        exec (SCall binds fname args) t m l mc post\n\n    | load: forall t m l mc sz R x a o v addr post,\n        map.get l a = Some addr ->\n        (R * one sz (word.add addr (word.of_Z o)) v)%sep m ->\n        post t m (map.put l x v)\n             (addMetricLoads 2\n             (addMetricInstructions 1 mc)) ->\n        exec (SLoad sz x a o) t m l mc post\n\n    | store: forall t m mc l sz a o addr v old_val val R post,\n        map.get l a = Some addr ->\n        map.get l v = Some val ->\n        (R * one sz (word.add addr (word.of_Z o)) old_val)%sep m ->\n        (* below could/should be seplog entailment: (R * one sz addr val) ==> post *)\n        (forall m',\n            (R * one sz (word.add addr (word.of_Z o)) val)%sep m' ->\n            post t m' l\n                 (addMetricLoads 1\n                 (addMetricInstructions 1\n                 (addMetricStores 1 mc)))) ->\n        exec (SStore sz a v o) t m l mc post\n\n    | stackalloc: forall t (M M': mem -> Prop) mSmall l mc x n body post,\n        n mod (bytes_per_word width) = 0 ->\n        M mSmall ->\n        (forall a mCombined,\n            (anybytes a n * M)%sep mCombined ->\n            exec body t mCombined (map.put l x a) (addMetricLoads 1 (addMetricInstructions 1 mc))\n             (fun t' mCombined' l' mc' =>\n                (M' * anybytes a n)%sep mCombined' /\\\n                forall mSmall', M' mSmall' -> post t' mSmall' l' mc')) ->\n        exec (SStackalloc x n body) t mSmall l mc post\n\n    | lit: forall t m l mc x v post,\n        post t m (map.put l x (word.of_Z v))\n             (addMetricLoads 8\n             (addMetricInstructions 8 mc)) ->\n        exec (SLit x v) t m l mc post\n    | op: forall t m l mc x op y y' z z' post,\n        map.get l y = Some y' ->\n        map.get l z = Some z' ->\n        post t m (map.put l x (interp_binop op y' z'))\n             (addMetricLoads 2\n             (addMetricInstructions 2 mc)) ->\n        exec (SOp x op y z) t m l mc post\n    | set: forall t m l mc x y y' post,\n        map.get l y = Some y' ->\n        post t m (map.put l x y')\n             (addMetricLoads 1\n             (addMetricInstructions 1 mc)) ->\n        exec (SSet x y) t m l mc post\n    | if_true: forall t m l mc cond  bThen bElse post,\n        eval_bcond l cond = Some true ->\n        exec bThen t m l\n             (addMetricLoads 2\n             (addMetricInstructions 2\n             (addMetricJumps 1 mc))) post ->\n        exec (SIf cond bThen bElse) t m l mc post\n    | if_false: forall t m l mc cond bThen bElse post,\n        eval_bcond l cond = Some false ->\n        exec bElse t m l\n             (addMetricLoads 2\n             (addMetricInstructions 2\n             (addMetricJumps 1 mc))) post ->\n        exec (SIf cond bThen bElse) t m l mc post\n    | loop: forall t m l mc cond body1 body2 mid1 mid2 post,\n        (* This case is carefully crafted in such a way that recursive uses of exec\n         only appear under forall and ->, but not under exists, /\\, \\/, to make sure the\n         auto-generated induction principle contains an IH for all recursive uses. *)\n        exec body1 t m l mc mid1 ->\n        (forall t' m' l' mc',\n            mid1 t' m' l' mc' ->\n            eval_bcond l' cond <> None) ->\n        (forall t' m' l' mc',\n            mid1 t' m' l' mc' ->\n            eval_bcond l' cond = Some false ->\n            post t' m' l'\n                 (addMetricLoads 1\n                 (addMetricInstructions 1\n                 (addMetricJumps 1 mc')))) ->\n        (forall t' m' l' mc',\n            mid1 t' m' l' mc' ->\n            eval_bcond l' cond = Some true ->\n            exec body2 t' m' l' mc' mid2) ->\n        (forall t'' m'' l'' mc'',\n            mid2 t'' m'' l'' mc'' ->\n            exec (SLoop body1 cond body2) t'' m'' l''\n                 (addMetricLoads 2\n                 (addMetricInstructions 2\n                 (addMetricJumps 1 mc''))) post) ->\n        exec (SLoop body1 cond body2) t m l mc post\n\n(* Error: Non strictly positive occurrence of \"exec\"\n    | seq_cps: forall t m l mc s1 s2 post,\n        exec s1 t m l mc (fun t' m' l' mc' => exec s2 t' m' l' mc' post) ->\n        exec (SSeq s1 s2) t m l mc post\n*)\n\n    | seq: forall t m l mc s1 s2 mid post,\n        exec s1 t m l mc mid ->\n        (forall t' m' l' mc', mid t' m' l' mc' -> exec s2 t' m' l' mc' post) ->\n        exec (SSeq s1 s2) t m l mc post\n    | skip: forall t m l mc post,\n        post t m l mc ->\n        exec SSkip t m l mc post.\n\n  End FlatImpExec.\nEnd exec.\nNotation 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/compiler/src/compiler/FlatImpSepLog.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2966896033148437}}
{"text": "Require Import List.\nExport ListNotations.\n\nRequire Import PeanoNat.\n\nRequire Import Ensembles.\nRequire Import BiInt_GHC.\n\nLemma subst_Ax : forall A f, (BIAxioms A) -> (BIAxioms (subst f A)).\nProof.\nintros A f Ax. induction Ax.\n- destruct H. destruct H. destruct H. subst. apply RA1_I.\n  exists (subst f x). exists (subst f x0). exists (subst f x1). unfold RA1. reflexivity.\n- destruct H. destruct H. subst. apply RA2_I.\n  exists (subst f x). exists (subst f x0). reflexivity.\n- destruct H. destruct H. subst. apply RA3_I.\n  exists (subst f x). exists (subst f x0). reflexivity.\n- destruct H. destruct H. destruct H. subst. apply RA4_I.\n  exists (subst f x). exists (subst f x0). exists (subst f x1). reflexivity.\n- destruct H. destruct H. subst. apply RA5_I.\n  exists (subst f x). exists (subst f x0). reflexivity.\n- destruct H. destruct H. subst. apply RA6_I.\n  exists (subst f x). exists (subst f x0). reflexivity.\n- destruct H. destruct H. destruct H. subst. apply RA7_I.\n  exists (subst f x). exists (subst f x0). exists (subst f x1). reflexivity.\n- destruct H. destruct H. destruct H. subst. apply RA8_I.\n  exists (subst f x). exists (subst f x0). exists (subst f x1). reflexivity.\n- destruct H. destruct H. destruct H. subst. apply RA9_I.\n  exists (subst f x). exists (subst f x0). exists (subst f x1). reflexivity.\n- destruct H. destruct H. subst. apply RA10_I.\n  exists (subst f x). exists (subst f x0). reflexivity.\n- destruct H. destruct H. subst. apply RA11_I.\n  exists (subst f x). exists (subst f x0). reflexivity.\n- destruct H. destruct H. subst. apply RA12_I.\n  exists (subst f x). exists (subst f x0). reflexivity.\n- destruct H. destruct H. destruct H. subst. apply RA13_I.\n  exists (subst f x). exists (subst f x0). exists (subst f x1). reflexivity.\n- destruct H. destruct H. subst. apply RA14_I.\n  exists (subst f x). exists (subst f x0). reflexivity.\n- destruct H. subst. apply RA15_I.\n  exists (subst f x). reflexivity.\n- destruct H. subst. apply RA16_I.\n  exists (subst f x). reflexivity.\nQed.\n\nTheorem wBIH_monot : forall s,\n          (wBIH_rules s) ->\n          (forall Γ1, (Included _ (fst s) Γ1) ->\n          (wBIH_rules (Γ1, (snd s)))).\nProof.\nintros s D0. induction D0.\n(* Id *)\n- intros Γ1 incl. inversion H. subst. apply Id. apply IdRule_I. simpl. apply incl.\n  assumption.\n(* Ax *)\n- intros Γ1 incl. inversion H. subst. apply Ax. apply AxRule_I. assumption.\n(* MP *)\n- intros Γ1 incl. inversion H1. subst. simpl. apply MP with (ps:=[(Γ1, A → B); (Γ1, A)]).\n  intros. inversion H2. subst. assert (J1: List.In (Γ, A → B) [(Γ, A → B); (Γ, A)]). apply in_eq.\n  pose (H0 (Γ, A → B) J1 Γ1). apply w. simpl. auto. inversion H3. subst.\n  assert (J2: List.In (Γ, A) [(Γ, A → B); (Γ, A)]). apply in_cons. apply in_eq.\n  pose (H0 (Γ, A) J2 Γ1). apply w. auto. inversion H4. apply MPRule_I.\n(* DNw *)\n- intros Γ1 incl. inversion H1. subst. simpl. apply DNw with (ps:=[(Empty_set _, A)]).\n  intros. inversion H2. subst. auto. inversion H3. apply DNwRule_I.\nQed.\n\nTheorem sBIH_monot : forall s,\n          (sBIH_rules s) ->\n          (forall Γ1, (Included _ (fst s) Γ1) ->\n          (sBIH_rules (Γ1, (snd s)))).\nProof.\nintros s D0. induction D0.\n(* Ids *)\n- intros Γ1 incl. inversion H. subst. apply Ids. apply IdRule_I. simpl. apply incl.\n  assumption.\n(* Axs *)\n- intros Γ1 incl. inversion H. subst. apply Axs. apply AxRule_I. assumption.\n(* MPs *)\n- intros Γ1 incl. inversion H1. subst. simpl. apply MPs with (ps:=[(Γ1, A → B); (Γ1, A)]).\n  intros. inversion H2. subst. assert (J1: List.In (Γ, A → B) [(Γ, A → B); (Γ, A)]). apply in_eq.\n  pose (H0 (Γ, A → B) J1 Γ1). apply s. simpl. auto. inversion H3. subst.\n  assert (J2: List.In (Γ, A) [(Γ, A → B); (Γ, A)]). apply in_cons. apply in_eq.\n  pose (H0 (Γ, A) J2 Γ1). apply s. auto. inversion H4. apply MPRule_I.\n(* DNs *)\n- intros Γ1 incl. inversion H1. subst. simpl. apply DNs with (ps:=[(Γ1, A)]).\n  intros. inversion H2. subst. assert (J1: List.In (Γ, A) [(Γ, A)]). apply in_eq.\n  pose (H0 (Γ, A) J1 Γ1). apply s. simpl. auto. inversion H3. apply DNsRule_I.\nQed.\n\nTheorem wBIH_comp : forall s,\n          (wBIH_rules s) ->\n          (forall Γ,  (forall A, ((fst s) A) -> wBIH_rules (Γ, A)) ->\n          wBIH_rules (Γ, (snd s))).\nProof.\nintros s D0. induction D0.\n(* Id *)\n- intros Γ derall. inversion H. subst. pose (derall A). apply w. auto.\n(* Ax *)\n- intros Γ derall. inversion H. subst. apply Ax. apply AxRule_I. assumption.\n(* MP *)\n- intros Γ derall. inversion H1. subst. apply MP with (ps:=[(Γ, A → B); (Γ, A)]).\n  intros. inversion H2. subst. assert (J1: List.In (Γ0, A → B) [(Γ0, A → B); (Γ0, A)]). apply in_eq.\n  pose (H0 (Γ0, A → B) J1 Γ). apply w. simpl. auto. inversion H3. subst.\n  assert (J2: List.In (Γ0, A) [(Γ0, A → B); (Γ0, A)]). apply in_cons. apply in_eq.\n  pose (H0 (Γ0, A) J2 Γ). apply w. auto. inversion H4. apply MPRule_I.\n(* DNw *)\n- intros Γ derall. inversion H1. subst. simpl. apply DNw with (ps:=[(Empty_set _, A)]).\n  intros. inversion H2. subst. auto. inversion H3. apply DNwRule_I.\nQed.\n\nTheorem sBIH_comp : forall s,\n          (sBIH_rules s) ->\n          (forall Γ,  (forall A, ((fst s) A) -> sBIH_rules (Γ, A)) ->\n          sBIH_rules (Γ, (snd s))).\nProof.\nintros s D0. induction D0.\n(* Ids *)\n- intros Γ derall. inversion H. subst. pose (derall A). apply s. auto.\n(* Axs *)\n- intros Γ derall. inversion H. subst. apply Axs. apply AxRule_I. assumption.\n(* MPs *)\n- intros Γ derall. inversion H1. subst. apply MPs with (ps:=[(Γ, A → B); (Γ, A)]).\n  intros. inversion H2. subst. assert (J1: List.In (Γ0, A → B) [(Γ0, A → B); (Γ0, A)]). apply in_eq.\n  pose (H0 (Γ0, A → B) J1 Γ). apply s. simpl. auto. inversion H3. subst.\n  assert (J2: List.In (Γ0, A) [(Γ0, A → B); (Γ0, A)]). apply in_cons. apply in_eq.\n  pose (H0 (Γ0, A) J2 Γ). apply s. auto. inversion H4. apply MPRule_I.\n(* DNs *)\n- intros Γ derall. inversion H1. subst. simpl. apply DNs with (ps:=[(Γ, A)]).\n  intros. inversion H2. subst. assert (J1: List.In (Γ0, A) [(Γ0, A)]). apply in_eq.\n  pose (H0 (Γ0, A) J1 Γ). apply s. simpl. auto. inversion H3. apply DNsRule_I.\nQed.\n\nTheorem wBIH_struct : forall s,\n          (wBIH_rules s) ->\n          (forall (f : V -> (BPropF V)),\n          (wBIH_rules ((fun y => (exists A, prod ((fst s) A) (y = (subst f A)))), (subst f (snd s))))).\nProof.\nintros s D0. induction D0.\n(* Id *)\n- intros f. inversion H. subst. simpl. apply Id. apply IdRule_I.\n  exists A. auto.\n(* Ax *)\n- intros f. inversion H. subst. apply Ax. apply AxRule_I. \n  apply subst_Ax with (f:=f). assumption.\n(* MP *)\n- intros f. inversion H1. subst. apply MP with (ps:=[((fun y : BPropF V =>\n  exists A0 : BPropF V, prod (Γ A0) (y = subst f A0)), (subst f A) → (subst f B)); ((fun y : BPropF V =>\n  exists A0 : BPropF V, prod (Γ A0) (y = subst f A0)), (subst f A))]). simpl.\n  intros. inversion H2. subst. assert (J1: List.In (Γ, A → B) [(Γ, A → B); (Γ, A)]). apply in_eq.\n  pose (H0 (Γ, A → B) J1 f). apply w. simpl. auto. inversion H3. subst.\n  assert (J2: List.In (Γ, A) [(Γ, A → B); (Γ, A)]). apply in_cons. apply in_eq.\n  pose (H0 (Γ, A) J2 f). apply w. auto. inversion H4. apply MPRule_I.\n(* DNw *)\n- intros f. inversion H1. subst. apply DNw with (ps:=[(Empty_set _, (subst f A))]).\n  intros. inversion H2. subst. assert (J1: List.In (Empty_set (BPropF V), A) [(Empty_set (BPropF V), A)]). apply in_eq.\n  pose (H0 (Empty_set (BPropF V), A) J1 f). simpl in w.\n  assert ((fun y : BPropF V => exists A : BPropF V,\n  prod (Empty_set _ A) (y = subst f A)) = Empty_set _).\n  { apply Extensionality_Ensembles. split. intro. intro. inversion H3. destruct H4.\n    inversion e. intro. intro. inversion H3. } rewrite H3 in w. apply w. simpl. auto.\n  inversion H3. apply DNwRule_I.\nQed.\n\nTheorem sBIH_struct : forall s,\n          (sBIH_rules s) ->\n          (forall (f : V -> (BPropF V)),\n          (sBIH_rules ((fun y => (exists A, prod ((fst s) A) (y = (subst f A)))), (subst f (snd s))))).\nProof.\nintros s D0. induction D0.\n(* Ids *)\n- intros f. inversion H. subst. simpl. apply Ids. apply IdRule_I.\n  exists A. auto.\n(* Axs *)\n- intros f. inversion H. subst. apply Axs. apply AxRule_I.\n  apply subst_Ax with (f:=f). assumption.\n(* MPs *)\n- intros f. inversion H1. subst. apply MPs with (ps:=[((fun y : BPropF V =>\n  exists A0 : BPropF V, prod (Γ A0) (y = subst f A0)), (subst f A) → (subst f B)); ((fun y : BPropF V =>\n  exists A0 : BPropF V, prod (Γ A0) (y = subst f A0)), (subst f A))]). simpl.\n  intros. inversion H2. subst. assert (J1: List.In (Γ, A → B) [(Γ, A → B); (Γ, A)]). apply in_eq.\n  pose (H0 (Γ, A → B) J1 f). apply s. simpl. auto. inversion H3. subst.\n  assert (J2: List.In (Γ, A) [(Γ, A → B); (Γ, A)]). apply in_cons. apply in_eq.\n  pose (H0 (Γ, A) J2 f). apply s. auto. inversion H4. apply MPRule_I.\n(* DNs *)\n- intros f. inversion H1. subst. simpl. apply DNs with (ps:=[((fun y : BPropF V => exists A0 : BPropF V,\n  (prod (Γ A0) (y = subst f A0))), (subst f A))]).\n  intros. inversion H2. subst. assert (J1: List.In (Γ, A) [(Γ, A)]). apply in_eq.\n  pose (H0 (Γ, A) J1 f). simpl in s. apply s. inversion H3. apply DNsRule_I.\nQed.\n\nTheorem wBIH_finite : forall s,\n          (wBIH_rules s) ->\n          (exists (Γ : Ensemble _), prod (Included _ Γ (fst s))\n                                     (prod (wBIH_rules (Γ, snd s))\n                                     (exists (l : list (BPropF V)), (forall A, ((Γ A) -> List.In A l) * (List.In A l -> (Γ A)))))).\nProof.\nintros s D0. induction D0.\n(* Id *)\n- inversion H. subst. simpl. exists (fun x => x = A).\n  repeat split. intro. intro. unfold In. inversion H1. assumption.\n  apply Id. apply IdRule_I. auto.\n  exists [A]. intro. split. intro. subst. apply in_eq. intro. inversion H1.\n  subst. auto. inversion H2.\n(* Ax *)\n- inversion H. subst. simpl. exists (Empty_set _).\n  repeat split. intro. intro. unfold In. inversion H1.\n  apply Ax. apply AxRule_I. auto.\n  exists []. intro. split. intro. subst. inversion H1. intro. inversion H1.\n(* MP *)\n- inversion H1. subst. assert (J1: List.In (Γ, A → B) [(Γ, A → B); (Γ, A)]). apply in_eq.\n  pose (H0 (Γ, A → B) J1). destruct e. destruct H2. destruct p. destruct e.\n  assert (J2: List.In (Γ, A) [(Γ, A → B); (Γ, A)]). apply in_cons. apply in_eq.\n  pose (H0 (Γ, A) J2). destruct e. destruct H3. destruct p. destruct e.\n  exists (Union _ x x1). repeat split. intro. intro. simpl. inversion H4.\n  subst. apply i. assumption. apply i0. assumption. simpl.\n  apply MP with (ps:=[(Union _ x x1, A → B); (Union _ x x1, A)]).\n  intros. inversion H4. subst.\n  assert (J3: Included _ (fst (x, A → B)) (Union _ x x1)). intro. simpl. intro.\n  apply Union_introl. assumption. pose (@wBIH_monot (x, A → B) w (Union _ x x1) J3). assumption.\n  inversion H5. subst. assert (J4: Included _ (fst (x1, A)) (Union _ x x1)). intro. simpl. intro.\n  apply Union_intror. assumption. pose (@wBIH_monot (x1, A) w0 (Union _ x x1) J4). assumption.\n  inversion H6. apply MPRule_I.\n  exists (x0 ++ x2). intro. split. intro. inversion H4. subst. pose (H2 A0).\n  destruct p. apply in_or_app. apply i1 in H5. auto. subst. pose (H3 A0).\n  destruct p. apply i1 in H5. apply in_or_app. auto. intro. apply in_app_or in H4.\n  destruct H4. apply Union_introl. apply H2. assumption. apply Union_intror.\n  apply H3. assumption.\n(* DNw *)\n- inversion H1. subst. exists (Empty_set _). repeat split.\n  intro. intro. simpl. inversion H2. apply DNw with (ps:=[(Empty_set _, A)]).\n  assumption. apply DNwRule_I. exists []. intro. split. intro. inversion H2.\n  intro. inversion H2.\nQed.\n\nTheorem sBIH_finite : forall s,\n          (sBIH_rules s) ->\n          (exists (Γ : Ensemble _), prod (Included _ Γ (fst s))\n                                     (prod (sBIH_rules (Γ, snd s))\n                                     (exists (l : list (BPropF V)), (forall A, ((Γ A) -> List.In A l) * (List.In A l -> (Γ A)))))).\nProof.\nintros s D0. induction D0.\n(* Ids *)\n- inversion H. subst. simpl. exists (fun x => x = A).\n  repeat split. intro. intro. unfold In. inversion H1. assumption.\n  apply Ids. apply IdRule_I. auto.\n  exists [A]. intro. split. intro. subst. apply in_eq. intro. inversion H1.\n  subst. auto. inversion H2.\n(* Axs *)\n- inversion H. subst. simpl. exists (Empty_set _).\n  repeat split. intro. intro. unfold In. inversion H1.\n  apply Axs. apply AxRule_I. auto.\n  exists []. intro. split. intro. subst. inversion H1. intro. inversion H1.\n(* MPs *)\n- inversion H1. subst. assert (J1: List.In (Γ, A → B) [(Γ, A → B); (Γ, A)]). apply in_eq.\n  pose (H0 (Γ, A → B) J1). destruct e. destruct H2. destruct p. destruct e.\n  assert (J2: List.In (Γ, A) [(Γ, A → B); (Γ, A)]). apply in_cons. apply in_eq.\n  pose (H0 (Γ, A) J2). destruct e. destruct H3. destruct p. destruct e.\n  exists (Union _ x x1). repeat split. intro. intro. simpl. inversion H4.\n  subst. apply i. assumption. apply i0. assumption. simpl.\n  apply MPs with (ps:=[(Union _ x x1, A → B); (Union _ x x1, A)]).\n  intros. inversion H4. subst.\n  assert (J3: Included _ (fst (x, A → B)) (Union _ x x1)). intro. simpl. intro.\n  apply Union_introl. assumption. pose (@sBIH_monot (x, A → B) s (Union _ x x1) J3). assumption.\n  inversion H5. subst. assert (J4: Included _ (fst (x1, A)) (Union _ x x1)). intro. simpl. intro.\n  apply Union_intror. assumption. pose (@sBIH_monot (x1, A) s0 (Union _ x x1) J4). assumption.\n  inversion H6. apply MPRule_I.\n  exists (x0 ++ x2). intro. split. intro. inversion H4. subst. pose (H2 A0).\n  destruct p. apply in_or_app. apply i1 in H5. auto. subst. pose (H3 A0).\n  destruct p. apply i1 in H5. apply in_or_app. auto. intro. apply in_app_or in H4.\n  destruct H4. apply Union_introl. apply H2. assumption. apply Union_intror.\n  apply H3. assumption.\n(* DNs *)\n- inversion H1. subst. assert (J1: List.In (Γ, A) [(Γ, A)]). apply in_eq.\n  pose (H0 (Γ, A) J1). destruct e. destruct H2. destruct p. destruct e.\n  exists x. repeat split. assumption.\n  apply DNs with (ps:=[(x, A)]). intro. intro. simpl. inversion H3. subst.\n  auto. inversion H4. apply DNsRule_I. exists x0. intro. split. intro. apply H2 ; assumption.\n  intro. apply H2 ; assumption.\nQed.\n", "meta": {"author": "ianshil", "repo": "PhD_thesis", "sha": "af4940397f0d95c1d63a196ab29a3b9f715d9f4e", "save_path": "github-repos/coq/ianshil-PhD_thesis", "path": "github-repos/coq/ianshil-PhD_thesis/PhD_thesis-af4940397f0d95c1d63a196ab29a3b9f715d9f4e/Prop_Bi_Int/BiInt_logics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.29665145754110916}}
{"text": "Require Import ExtLib.Structures.Monad.\n\nSet Implicit Arguments.\n\nClass MonadPlus (m : Type -> Type) : Type :=\n{ mplus : forall {A B:Type}, m A -> m B -> m (A + B)%type }.\n\nDefinition mjoin {m : Type -> Type} {M : Monad m} {MP : MonadPlus m} {T} (a b : m T) : m T :=\n  bind (mplus a b) (fun x =>\n    match x with\n      | inl x | inr x => ret x\n    end).\n\nModule MonadPlusNotation.\n  Notation \"x <+> y\" := (@mplus _ _ _ _ x y) (at level 49, right associativity) : monad_scope.\nEnd MonadPlusNotation.\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/MonadPlus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2966514575411091}}
{"text": "(**********************************************************************\n\n The empty enriched category\n\n In this file, we define the empty enriched categories, which is the\n enriched categories without any objects. In addition, we provide the\n necessary functors and natural transformations in order to prove that\n it is a strict biinitial object in the bicategory of enriched\n categories.\n\n Contents\n 1. The empty enriched category\n 2. Functors from the empty enriched category\n 3. Natural transformations involving the empty enriched category\n\n **********************************************************************)\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Isos.\nRequire Import UniMath.CategoryTheory.Core.Univalence.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.Core.NaturalTransformations.\nRequire Import UniMath.CategoryTheory.categories.StandardCategories.\nRequire Import UniMath.CategoryTheory.EnrichedCats.Enrichment.\nRequire Import UniMath.CategoryTheory.EnrichedCats.EnrichmentFunctor.\nRequire Import UniMath.CategoryTheory.EnrichedCats.EnrichmentTransformation.\nRequire Import UniMath.CategoryTheory.Monoidal.Categories.\n\nLocal Open Scope cat.\nLocal Open Scope moncat.\n\nSection EnrichedEmpty.\n  Context (V : monoidal_cat).\n\n  (**\n   1. The empty enriched category\n   *)\n  Definition empty_category_enrichment_data\n    : enrichment_data empty_category V.\n  Proof.\n    simple refine (_ ,, _ ,, _ ,, _ ,, _).\n    - exact (λ x, fromempty x).\n    - exact (λ x, fromempty x).\n    - exact (λ x, fromempty x).\n    - exact (λ x, fromempty x).\n    - exact (λ x, fromempty x).\n  Defined.\n\n  Definition empty_category_enrichment\n    : enrichment empty_category V.\n  Proof.\n    simple refine (_ ,, _).\n    - exact empty_category_enrichment_data.\n    - abstract\n        (repeat split ; intro x ; induction x).\n  Defined.\n\n  (**\n   2. Functors from the empty enriched category\n   *)\n  Definition functor_from_empty_enrichment\n             {C : category}\n             (E : enrichment C V)\n    : functor_enrichment\n        (functor_from_empty C)\n        empty_category_enrichment\n        E.\n  Proof.\n    simple refine (_ ,, _ ,, _ ,, _).\n    - exact (λ x, fromempty x).\n    - abstract\n        (intro x ; induction x).\n    - abstract\n        (intro x ; induction x).\n    - abstract\n        (intro x ; induction x).\n  Defined.\n\n  (**\n   3. Natural transformations involving the empty enriched category\n   *)\n  Definition nat_trans_from_empty_enrichment\n             {C : category}\n             {E : enrichment C V}\n             {F G : empty_category ⟶ C}\n             (FE : functor_enrichment F empty_category_enrichment E)\n             (GE : functor_enrichment G empty_category_enrichment E)\n    : nat_trans_enrichment\n        (nat_trans_from_empty F G)\n        FE\n        GE.\n  Proof.\n    intro x.\n    induction x.\n  Qed.\n\n  Definition nat_trans_to_empty_enrichment\n             {C₁ C₂ : category}\n             {E₁ : enrichment C₁ V}\n             {E₂ : enrichment C₂ V}\n             {F : C₁ ⟶ empty_category}\n             (EF : functor_enrichment F E₁ empty_category_enrichment)\n             {G : empty_category ⟶ C₂}\n             (EG : functor_enrichment G empty_category_enrichment E₂)\n             {H : C₁ ⟶ C₂}\n             (EH : functor_enrichment H E₁ E₂)\n    : nat_trans_enrichment\n        (nat_trans_to_empty F G H)\n        EH\n        (functor_comp_enrichment EF EG).\n  Proof.\n    intros x.\n    induction (F x).\n  Qed.\n\n  Definition nat_trans_to_empty_inv_enrichment\n             {C₁ C₂ : category}\n             {E₁ : enrichment C₁ V}\n             {E₂ : enrichment C₂ V}\n             {F : C₁ ⟶ empty_category}\n             (EF : functor_enrichment F E₁ empty_category_enrichment)\n             {G : empty_category ⟶ C₂}\n             (EG : functor_enrichment G empty_category_enrichment E₂)\n             {H : C₁ ⟶ C₂}\n             (EH : functor_enrichment H E₁ E₂)\n    : nat_trans_enrichment\n        (nat_z_iso_inv\n           (make_nat_z_iso _ _ _ (nat_trans_to_empty_is_nat_z_iso F G H)))\n        (functor_comp_enrichment EF EG)\n        EH.\n  Proof.\n    intros x.\n    induction (F x).\n  Qed.\nEnd EnrichedEmpty.\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/EnrichedCats/Examples/EmptyEnriched.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2966514575411091}}
{"text": "Require Export Fiat.QueryStructure.Implementation.DataStructures.Bags.BagsInterface\n        Fiat.QueryStructure.Implementation.DataStructures.Bags.BagsProperties.\nRequire Import\n        Coq.FSets.FMapInterface\n        Coq.FSets.FMapFacts\n        Coq.FSets.FMapAVL\n        Coq.omega.Omega\n        Fiat.Common\n        Fiat.Common.List.ListFacts\n        Fiat.Common.List.FlattenList\n        Fiat.Common.SetEqProperties\n        Fiat.Common.FMapExtensions\n        Fiat.Common.List.PermutationFacts\n        Fiat.QueryStructure.Specification.SearchTerms.ListPrefix.\n\nModule TrieBag (X:OrderedType).\n\n  Module XMap := FMapAVL.Make X.\n  Module Import XMapFacts := WFacts_fun X XMap.\n  Module Import MoreXMapFacts := FMapExtensions_fun X XMap.\n\n  Section TrieBagDefinitions.\n\n    Definition SearchTerm := option (list X.t).\n\n    Context {BagType TItem SearchTermType UpdateTermType : Type}\n            (TBag : Bag BagType TItem SearchTermType UpdateTermType)\n            (RepInv : BagType -> Prop)\n            (ValidUpdate : UpdateTermType -> Prop)\n            (TBagCorrect : CorrectBag RepInv ValidUpdate TBag)\n            (projection: TItem -> list X.t).\n\n    Import XMap.Raw.\n    Import XMap.Raw.Proofs.\n\n    Definition Map := t.\n\n    Inductive Trie :=\n    | Node : BagType -> Map Trie -> Trie.\n\n    Definition TrieNode (trie : Trie) :=\n      match trie with\n        | Node bag tries => bag\n      end.\n\n    Definition SubTries (trie : Trie) :=\n      match trie with\n        | Node bag tries => tries\n      end.\n\n    (* Emptiness *)\n\n    Definition TrieBag_bempty := Node bempty (empty Trie).\n\n    Definition IsPrefix l (st : list X.t) : bool :=\n      if Prefix_dec X.eq_dec l st then true else false.\n\n    Arguments IsPrefix _ _  / .\n\n    Definition TrieBag_bfind_matcher\n               (search_term: SearchTerm * SearchTermType) (item: TItem) :=\n      match fst search_term with\n        | Some st =>\n          IsPrefix (projection item) st\n        | None => true\n      end && (bfind_matcher (snd search_term) item).\n\n    Definition XMapfold\n               (A : Type) (f : X.t -> Trie -> A -> A) :=\n      fix XMapfold (m : tree Trie) (a : A) {struct m} : A :=\n      match m with\n        | XMap.Raw.Leaf => a\n        | XMap.Raw.Node l x d r _ => XMapfold r (f x d (XMapfold l a))\n      end.\n\n    Lemma XMapfold_eq A f\n    : forall m acc,\n        @XMapfold A f m acc =\n        @XMap.Raw.fold _ A f m acc.\n    Proof.\n      unfold XMapfold, XMap.Raw.fold; simpl.\n      induction m; eauto.\n      intros; rewrite IHm1, IHm2; reflexivity.\n    Qed.\n\n    Fixpoint Trie_enumerate\n             (t : Trie)\n             {struct t}\n    : list BagType :=\n      match t with\n        | Node bag tries =>\n          XMapfold (fun _ tries bags =>\n                      Trie_enumerate tries ++ bags) tries [bag]\n      end.\n\n    Definition TrieBag_benumerate\n               (container: Trie)\n      := flatten (List.map benumerate (Trie_enumerate container)).\n\n    Fixpoint Trie_find\n             (trie : Trie)\n             (st : list X.t)\n    : list BagType :=\n      (TrieNode trie) :: match st with\n                           | nil => [ ]\n                           | key :: st' =>\n                             match find key (SubTries trie) with\n                               | Some subtrie => Trie_find subtrie st'\n                               | None => [ ]\n                             end\n                         end.\n\n    Fixpoint Trie_find'\n             (trie : Trie)\n             (st : list X.t)\n      : list BagType :=\n      (TrieNode trie) ::\n                      XMapfold (fun k tries found =>\n                                  (Trie_find' tries st) ++ found) (SubTries trie) [ ].\n\n    Definition TrieBag_bcount\n               (trie : Trie)\n               (key_searchterm: SearchTerm * SearchTermType)\n    : nat :=\n      match key_searchterm with\n        | (Some st, search_term) =>\n          fold_left plus (List.map (fun bag : BagType => bcount bag search_term)\n                                   (Trie_find trie st)) 0\n        | (None, search_term) =>\n          fold_left plus (List.map (fun bag : BagType => bcount bag search_term)\n                                   (Trie_enumerate trie)) 0\n      end.\n\n    Definition TrieBag_bfind\n               (trie : Trie)\n               (key_searchterm: SearchTerm * SearchTermType)\n    : list TItem :=\n      match key_searchterm with\n      | (Some st, search_term) =>\n        flatten (List.map (fun bag : BagType => bfind bag search_term)\n                                 (Trie_find trie st))\n      | (None, search_term) =>\n        flatten (List.map (fun bag : BagType => bfind bag search_term)\n                                 (Trie_enumerate trie))\n      end.\n\n    Fixpoint Trie_add\n             (trie : Trie)\n             (st : list X.t)\n             (item : TItem) : Trie :=\n      match st with\n        | [ ] =>\n          Node (binsert (TrieNode trie) item) (SubTries trie)\n        | key :: st' =>\n          match find key (SubTries trie) with\n            | Some subtrie =>\n              Node (TrieNode trie)\n                   (add key (Trie_add subtrie st' item)\n                        (SubTries trie))\n            | None =>\n              Node (TrieNode trie)\n                   (add key (Trie_add TrieBag_bempty st' item)\n                        (SubTries trie))\n          end\n      end.\n\n    Definition TrieBag_binsert\n               (trie : Trie)\n               (item: TItem) : Trie :=\n      Trie_add trie (projection item) item.\n\n    Fixpoint Trie_delete\n             (trie : Trie)\n             (st : list X.t)\n             (search_term : SearchTermType)\n    : (list TItem) * Trie :=\n      match st with\n        | nil =>\n          let (deletedItems, bag') :=\n              bdelete (TrieNode trie) search_term in\n          (deletedItems, Node bag' (SubTries trie))\n        | key :: st' =>\n          let (deletedItems, bag') :=\n              bdelete (TrieNode trie) search_term in\n          match find key (SubTries trie) with\n            | Some subtrie =>\n              let (deletedSubItems, bag'') :=\n                  Trie_delete subtrie st' search_term in\n              (deletedItems ++ deletedSubItems,\n               Node bag' (add key bag'' (SubTries trie)))\n            | None =>\n              (deletedItems, Node bag' (SubTries trie))\n          end\n      end.\n\n    Fixpoint Trie_delete'\n             (trie : Trie)\n             (search_term : SearchTermType)\n             {struct trie}\n    : (list TItem) * Trie :=\n      match trie with\n      | Node bag tries =>\n        let (deletedItems, bag') :=\n            bdelete (TrieNode trie) search_term in\n        let tries' :=\n            XMapfold (fun k tries (deleted : (list TItem) * _)  =>\n                        let (deletedItems', bag') := Trie_delete' tries search_term in\n                        let (deletedItems'', bags') := deleted in\n                        (deletedItems' ++ deletedItems'', XMap.add k bag' bags'))\n                     tries ([ ], XMap.empty _) in\n        (deletedItems ++ fst tries', Node bag' (XMap.this (snd tries')))\n      end.\n\n    Definition TrieBag_bdelete\n               (trie : Trie)\n               (key_searchterm : SearchTerm * SearchTermType)\n      : (list TItem) * Trie :=\n      match key_searchterm with\n      | (Some st, search_term) => Trie_delete trie st search_term\n      | (None, search_term) => Trie_delete' trie search_term\n      end.\n\n    Fixpoint Trie_update\n             (trie : Trie)\n             (st : list _)\n             (search_term : SearchTermType)\n             (updateTerm : UpdateTermType)\n    : (list TItem) * Trie :=\n      match st with\n        | nil =>\n          let (updatedItems, bag') :=\n              bupdate (TrieNode trie) search_term updateTerm in\n          (updatedItems, Node bag' (SubTries trie))\n        | key :: st' =>\n          let (updatedItems, bag') :=\n              bupdate (TrieNode trie) search_term updateTerm in\n          match find key (SubTries trie) with\n            | Some subtrie =>\n              let (updatedSubItems, bag'') :=\n                  Trie_update subtrie st' search_term updateTerm in\n              (updatedItems ++ updatedSubItems,\n               Node bag' (add key bag'' (SubTries trie)))\n            | None =>\n              (updatedItems, Node bag' (SubTries trie))\n          end\n      end.\n\n    Fixpoint Trie_update'\n             (trie : Trie)\n             (search_term : SearchTermType)\n             (updateTerm : UpdateTermType)\n             {struct trie}\n    : (list TItem) * Trie :=\n      match trie with\n      | Node bag tries =>\n        let (updatedItems, bag') :=\n            bupdate (TrieNode trie) search_term updateTerm in\n        let tries' :=\n            XMapfold (fun k tries (updated : (list TItem) * _)  =>\n                        let (updatedItems', bag') := Trie_update' tries search_term updateTerm in\n                        let (updatedItems'', bags') := updated in\n                        (updatedItems' ++ updatedItems'', XMap.add k bag' bags'))\n                     tries ([ ], XMap.empty _) in\n        (updatedItems ++ fst tries', Node bag' (XMap.this (snd tries')))\n      end.\n\n    Definition TrieBag_bupdate\n               (trie : Trie)\n               (key_searchterm : SearchTerm * SearchTermType)\n               (updateTerm : UpdateTermType)\n      : (list TItem) * Trie :=\n      match key_searchterm with\n      | (Some st, search_term) => Trie_update trie st search_term updateTerm\n      | (None, search_term) => Trie_update' trie search_term updateTerm\n      end.\n\n    Definition WFMap := bst.\n\n    Definition Prefix (s s' : list X.t) :=\n      exists s'', eqlistA X.eq (s ++ s'') s'.\n\n    Lemma IsPrefix_iff_Prefix :\n      forall (s s' : list X.t),\n        IsPrefix s s' = true <-> Prefix s s'.\n    Proof.\n      unfold Prefix; split; revert s'; induction s; intros s' H.\n      - eexists s'; reflexivity.\n      - destruct s'; simpl in H.\n        + discriminate.\n        + destruct (F.eq_dec a t); [subst | discriminate].\n          unfold IsPrefix in IHs.\n          destruct (IHs s').\n          destruct (Prefix_dec F.eq_dec s s'); try discriminate; eauto.\n          eexists; subst; eauto.\n          simpl; econstructor; eauto.\n      - simpl; reflexivity.\n      - destruct s'; simpl in *; destruct H.\n        + inversion H.\n        + inversion H; subst; destruct (F.eq_dec a t).\n          destruct (Prefix_dec F.eq_dec s s'); eauto.\n          elimtype False; apply n; eexists; eauto.\n          congruence.\n    Qed.\n\n    Inductive TrieOK : Trie -> list X.t -> Prop :=\n    | NodeSomeOK :\n        forall bag subtries st,\n          RepInv bag\n          -> bst subtries\n          -> (forall (item: TItem),\n                List.In item (benumerate bag) ->\n                eqlistA X.eq (projection item) st)\n          -> (forall k subtrie,\n                MapsTo k subtrie subtries\n                -> TrieOK subtrie (st ++ [k]))\n          -> TrieOK (Node bag subtries) st.\n\n    Lemma SubTrieMapBST\n    : forall bag subtries st,\n        TrieOK (Node bag subtries) st\n        -> bst subtries.\n    Proof.\n      inversion 1; eauto.\n    Qed.\n\n    Lemma SubTrieMapBST'\n    : forall trie st,\n        TrieOK trie st -> bst (SubTries trie).\n    Proof.\n      inversion 1; eauto.\n    Qed.\n\n    Hint Resolve SubTrieMapBST SubTrieMapBST'.\n\n    Lemma TrieNode_RepInv\n    : forall bag subtries st,\n        TrieOK (Node bag subtries) st\n        -> RepInv bag.\n    Proof.\n      inversion 1; eauto.\n    Qed.\n\n    Lemma TrieNode_RepInv'\n    : forall trie st,\n        TrieOK trie st -> RepInv (TrieNode trie).\n    Proof.\n      inversion 1; eauto.\n    Qed.\n\n    Hint Resolve TrieNode_RepInv TrieNode_RepInv'.\n\n    Lemma SubTrieOK\n    : forall trie k subtrie st,\n        TrieOK trie st\n        -> find k (SubTries trie) = Some subtrie\n        -> TrieOK subtrie (st ++ [k]).\n    Proof.\n      destruct trie; simpl.\n      induction m; simpl in *; intros.\n      - discriminate.\n      - inversion H; subst.\n        case_eq (X.compare k0 k); intros; rewrite H1 in H0.\n        + eapply IHm1; eauto.\n          econstructor; simpl in *; eauto.\n          inversion H4; subst; eauto.\n        + injections; simpl in *.\n          eapply (H7 k0 _); eauto.\n        + eapply IHm2; eauto.\n          econstructor; simpl in *; eauto.\n          inversion H4; subst; eauto.\n    Qed.\n\n    Hint Resolve SubTrieOK.\n\n    Definition TrieBagRepInv (trie : Trie) := TrieOK trie [ ].\n\n    Definition TrieBag_ValidUpdate (update_term : UpdateTermType) :=\n      ValidUpdate update_term /\\\n      forall K item,\n        eqlistA X.eq (projection item) K\n        -> eqlistA X.eq (projection (bupdate_transform update_term item)) K.\n\n    Lemma Trie_Empty_RepInv :\n      TrieBagRepInv (TrieBag_bempty).\n    Proof.\n      unfold TrieBagRepInv; intros; econstructor; simpl in *.\n      apply bempty_RepInv.\n      econstructor.\n      intros; elimtype False; eapply benumerate_empty; eauto.\n      intros; elimtype False; eapply empty_1; eauto.\n    Qed.\n\n    Functional Scheme Trie_add_ind := Induction for Trie_add Sort Prop.\n    Functional Scheme Trie_delete_ind := Induction for Trie_delete Sort Prop.\n    Functional Scheme Trie_update_ind := Induction for Trie_update Sort Prop.\n    Functional Scheme Trie_find_ind := Induction for Trie_find Sort Prop.\n\n    Hint Resolve add_bst.\n    Hint Constructors eqlistA.\n\n    Lemma Trie_add_Preserves_TreeOK\n    : forall trie item st1 st2,\n        eqlistA X.eq (projection item) (st2 ++ st1)\n        -> TrieOK trie st2\n        -> TrieOK (Trie_add trie st1 item) st2.\n    Proof.\n      intros trie item st1; eapply Trie_add_ind; intros; subst.\n      - econstructor; inversion H0; subst; eauto.\n        + eapply binsert_RepInv; eauto.\n        + intros; rewrite binsert_enumerate in H5 by eauto.\n          simpl in *; intuition; subst.\n          rewrite H, app_nil_r; reflexivity.\n      - econstructor; inversion H1; subst; simpl; eauto.\n        intros; destruct (X.eq_dec k key0).\n        apply find_1 in H6; eauto.\n        pose proof (add_1 subtries (Trie_add subtrie st' item0) (X.eq_sym e)) as H7; apply find_1 in H7; eauto.\n        rewrite H6 in H7; injections; intros; subst.\n        eapply H; eauto.\n        rewrite <- app_assoc.\n        rewrite H0.\n        apply eqlistA_app;\n          repeat first [econstructor; eauto\n                       | try reflexivity ].\n        apply H5.\n        apply MapsTo_1 with (x := key0).\n        symmetry; eauto.\n        apply find_2; eassumption.\n        apply H5.\n        eapply add_3 in H6; eauto.\n      - econstructor; inversion H1; subst; simpl; eauto.\n        + intros; destruct (X.eq_dec k key0).\n          apply find_1 in H6; eauto.\n          pose proof (add_1 subtries (Trie_add TrieBag_bempty st' item0) (X.eq_sym e)) as H7; apply find_1 in H7; eauto.\n          rewrite H6 in H7; injections; intros; subst.\n          eapply H; eauto.\n          rewrite <- app_assoc.\n          rewrite H0.\n          apply eqlistA_app;\n            repeat first [econstructor; eauto\n                         | try reflexivity ].\n          unfold TrieBagRepInv; intros; econstructor; simpl in *.\n          apply bempty_RepInv.\n          econstructor.\n          intros; elimtype False; eapply benumerate_empty; eauto.\n          intros; elimtype False; eapply empty_1; eauto.\n          apply H5.\n          eapply add_3 in H6; eauto.\n    Qed.\n\n    Corollary TrieBag_binsert_Preserves_RepInv :\n      binsert_Preserves_RepInv TrieBagRepInv TrieBag_binsert.\n    Proof.\n      unfold binsert_Preserves_RepInv; intros.\n      eapply Trie_add_Preserves_TreeOK; simpl.\n      reflexivity.\n      apply containerCorrect.\n    Qed.\n\n    Lemma Trie_ind'\n          (P : Trie -> list key -> Prop)\n          (IH : forall (b : BagType) (m : Map Trie) l,\n              (forall k trie l, MapsTo k trie m -> P trie (l ++ [k]))\n              -> P (Node b m) l)\n          (trie : Trie)\n      : forall l, P trie l.\n          refine ((fix Trie_ind trie :=\n                    match trie return forall l, P trie l with\n                    | Node b tries => fun l => IH _ _ _ ((fun f0 =>\n                                                fix F (t : t Trie) : (forall k trie l, MapsTo k trie t -> P trie (l ++ [k])) :=\n                                                match t as t0 return ((forall k trie l, MapsTo k trie t0 -> P trie (l ++ [k]))) with\n                                                | Leaf =>  _\n                                                | XMap.Raw.Node t0 k e t1 t2 => f0 t0 (F t0) k e t1 (F t1) t2\n                                                end) _ tries)\n                    end) trie).\n          - intros; inversion H.\n          - intros; inversion H; subst.\n            + let Trie_ind0 := match goal with Trie_ind0 : forall (trie : Trie) (l : list key), ?P trie l |- _ => constr:(Trie_ind0) end in\n              apply Trie_ind0.\n            + eapply x0; eauto.\n            + eapply x4; eauto.\n    Qed.\n\n    Definition XMapfold_ind\n               (P : Trie -> list BagType -> list X.t-> Prop)\n               (f : forall trie st, P trie (Trie_enumerate trie) st)\n               (m : tree Trie) (is_bst : bst m) :\n      forall k trie st , MapsTo k trie m ->\n                         P trie (Trie_enumerate trie) (st ++ [k]).\n    Proof.\n      refine ((fix XMapfold (m : tree Trie) {struct m} :\n                 bst m ->\n                 forall k trie st, MapsTo k trie m ->\n                                   P trie (Trie_enumerate trie) (st ++ [k]) :=\n                 match m with\n                   | XMap.Raw.Leaf => _\n                   | XMap.Raw.Node l x d r _ => _\n                 end) m is_bst).\n      - intros; apply find_1 in H0; simpl in H0;\n        [ discriminate | eauto ].\n      - intros; apply find_1 in H0; simpl in H0;\n        [ destruct (X.compare k x)\n        | eassumption ].\n        + apply find_2 in H0.\n          let XMapfold0 := match goal with XMapfold0 : forall m : XMap.Raw.t Trie, _ -> forall (k : key) (trie : Trie) (st : list key), _ -> _ |- _ => constr:(XMapfold0) end in\n          eapply (XMapfold0 l); eauto.\n          inversion H; subst; eauto.\n        + pose proof (f d (st ++ [k])).\n          injections; eassumption.\n        + apply find_2 in H0.\n          let XMapfold0 := match goal with XMapfold0 : forall m : XMap.Raw.t Trie, _ -> forall (k : key) (trie : Trie) (st : list key), _ -> _ |- _ => constr:(XMapfold0) end in\n          eapply (XMapfold0 r); eauto.\n          inversion H; subst; eauto.\n    Defined.\n\n    Lemma TrieBag_bdelete_Preserves_RepInv :\n      bdelete_Preserves_RepInv TrieBagRepInv TrieBag_bdelete.\n    Proof.\n      unfold bdelete_Preserves_RepInv, TrieBagRepInv;\n      intros trie search_term; remember []; clear Heql; revert l.\n      unfold TrieBag_bdelete.\n      destruct search_term as [ [l | ] s].\n      { eapply Trie_delete_ind; intros; subst.\n        - econstructor; inversion containerCorrect; subst; eauto.\n          + pose proof (bdelete_RepInv bag search_term) as e'; simpl in *;\n            rewrite e0 in e'; eapply e'.\n            inversion containerCorrect; eauto.\n          + intros; eapply H1.\n            destruct (bdelete_correct bag search_term); eauto.\n            simpl in *; rewrite e0 in *; simpl in *.\n            rewrite H4 in H3.\n            rewrite In_partition; eauto.\n        - econstructor; inversion containerCorrect; subst; eauto.\n          + pose proof (bdelete_RepInv bag search_term) as e'; simpl in *;\n            rewrite e0 in e'; eapply e'; eauto.\n          + intros; eapply H2.\n            destruct (bdelete_correct bag search_term); eauto.\n            simpl in *; rewrite e0 in *; simpl in *.\n            rewrite H5 in H4.\n            rewrite In_partition; eauto.\n          + intros; destruct (X.eq_dec k key0).\n            * apply find_1 in H4; eauto.\n              simpl in *.\n              pose proof (add_1 subtries bag'' (X.eq_sym e)) as H7; apply find_1 in H7; eauto.\n              rewrite H4 in H7; injections; intros; subst.\n              rewrite e2 in H; eapply H.\n              eapply H3.\n              apply MapsTo_1 with (x := key0).\n              symmetry; eauto.\n              apply find_2; eauto.\n            * apply H3.\n              eapply add_3; eauto.\n        - simpl; econstructor; inversion containerCorrect; subst; eauto.\n          + pose proof (bdelete_RepInv bag search_term) as e'; simpl in *;\n            rewrite e0 in e'; eapply e'.\n            inversion containerCorrect; eauto.\n          + intros; eapply H1.\n            destruct (bdelete_correct bag search_term); eauto.\n            simpl in *; rewrite e0 in *; simpl in *.\n            rewrite H4 in H3.\n            rewrite In_partition; eauto.\n      }\n      { intro; pattern trie, l; apply Trie_ind'; simpl; intros.\n        intros; inversion containerCorrect; subst.\n        case_eq (bdelete b s); simpl; intros.\n        econstructor.\n        + pose proof (bdelete_RepInv b s) as e'; simpl in *.\n          rewrite H0 in e'; eapply e'; eauto.\n        + apply XMap.is_bst.\n        + intros; eapply H4.\n          destruct (bdelete_correct b s); eauto.\n          simpl in *; rewrite H0 in *; simpl in *.\n          rewrite H5 in H1.\n          rewrite In_partition; eauto.\n        + intros; rewrite XMapfold_eq in H1.\n          setoid_rewrite (fold_pair (XMap.Bst H3)) in H1; simpl in H1.\n          assert (XMap.MapsTo k subtrie\n                              (XMap.fold\n                                 (fun (k0 : XMap.key) (m0 : Trie) (b' : XMap.t Trie) =>\n                                    XMap.add k0 (snd (Trie_delete' m0 s)) b')\n                                 {| XMap.this := m; XMap.is_bst := H3 |}\n                                 (XMap.empty Trie))) by apply H1; clear H1.\n          setoid_rewrite FMap_Insert_fold_add_map_eq in H5.\n          rewrite map_mapsto_iff in H5; destruct_ex; intuition; subst.\n          eapply H; eauto.\n      }\n    Qed.\n\n    Lemma ValidUpdate_TrieBag_ValidUpdate :\n      forall updateTerm,\n        TrieBag_ValidUpdate updateTerm\n        -> ValidUpdate updateTerm.\n    Proof.\n      inversion 1; subst; eauto.\n    Qed.\n\n    Hint Resolve ValidUpdate_TrieBag_ValidUpdate.\n\n    Lemma TrieBag_bupdate_Preserves_RepInv :\n      bupdate_Preserves_RepInv\n        TrieBagRepInv\n        TrieBag_ValidUpdate\n        TrieBag_bupdate.\n    Proof.\n      unfold bupdate_Preserves_RepInv, TrieBagRepInv;\n      intros trie search_term update_term; remember [];\n      clear Heql; revert l.\n      unfold TrieBag_bupdate.\n      destruct search_term as [ [l | ] s].\n      {\n        eapply Trie_update_ind; intros; subst.\n      - econstructor; inversion containerCorrect; subst; eauto.\n        + pose proof (bupdate_RepInv bag search_term updateTerm) as e'; simpl in *;  rewrite e0 in e'; eapply e'; eauto.\n        + intros; destruct (bupdate_correct bag search_term updateTerm);\n          eauto.\n          simpl in *; rewrite e0 in *; simpl in *.\n          rewrite H4 in H3.\n          apply in_app_or in H3; intuition.\n          * eapply H1; erewrite In_partition; eauto.\n          * rewrite in_map_iff in H6; destruct_ex; intuition.\n            inversion valid_update; subst.\n            apply H8; apply H1; rewrite In_partition; eauto.\n      - econstructor; inversion containerCorrect; subst; eauto.\n        + pose proof (bupdate_RepInv bag search_term updateTerm) as e'; simpl in *;  rewrite e0 in e'; eapply e'; eauto.\n        + intros; destruct (bupdate_correct bag search_term updateTerm);\n          eauto.\n          simpl in *; rewrite e0 in *; simpl in *.\n          rewrite H5 in H4.\n          apply in_app_or in H4; intuition.\n          * eapply H2; erewrite In_partition; eauto.\n          * rewrite in_map_iff in H7; destruct_ex; intuition.\n            inversion valid_update; subst.\n            apply H9; apply H2; rewrite In_partition; eauto.\n        + intros; destruct (X.eq_dec k key0).\n          * apply find_1 in H4; eauto.\n            simpl in *.\n            pose proof (add_1 subtries bag'' (X.eq_sym e)) as H7; apply find_1 in H7; eauto.\n            rewrite H4 in H7; injections; intros; subst.\n            rewrite e2 in H; eapply H; eauto.\n            eapply H3.\n            apply MapsTo_1 with (x := key0).\n            symmetry; eauto.\n            apply find_2; eauto.\n          * apply H3.\n            eapply add_3; eauto.\n      - simpl; econstructor; inversion containerCorrect; subst; eauto.\n        + pose proof (bupdate_RepInv bag search_term updateTerm) as e'; simpl in *;  rewrite e0 in e'; eapply e'; eauto.\n        + intros; destruct (bupdate_correct bag search_term updateTerm);\n          eauto.\n          simpl in *; rewrite e0 in *; simpl in *.\n          rewrite H4 in H3.\n          apply in_app_or in H3; intuition.\n          * eapply H1; erewrite In_partition; eauto.\n          * rewrite in_map_iff in H6; destruct_ex; intuition.\n            inversion valid_update; subst.\n            apply H8; apply H1; rewrite In_partition; eauto.\n      }\n      { intro; pattern trie, l; apply Trie_ind'; simpl; intros.\n        intros; inversion containerCorrect; subst.\n        case_eq (bupdate b s update_term); simpl; intros.\n        econstructor.\n        + pose proof (bupdate_RepInv b s update_term) as e'; simpl in *.\n          rewrite H0 in e'; eapply e'; eauto.\n        + apply XMap.is_bst.\n        + intros; destruct (bupdate_correct b s update_term); eauto.\n          simpl in *; rewrite H0 in *; simpl in *.\n          intros; rewrite H5 in H1.\n          apply in_app_or in H1; destruct H1.\n          * intros; eapply H4.\n            rewrite In_partition; eauto.\n          * rewrite in_map_iff in H1; destruct H1 as [item' [item'_eq In_item'] ].\n            rewrite <- item'_eq in *.\n            destruct valid_update as [valid_update valid_update'].\n            eapply valid_update'.\n            eapply H4.\n            rewrite In_partition; eauto.\n        + intros; rewrite XMapfold_eq in H1.\n          setoid_rewrite (fold_pair (XMap.Bst H3)) in H1; simpl in H1.\n          assert (XMap.MapsTo k subtrie\n                              (XMap.fold\n                                 (fun (k0 : XMap.key) (m0 : Trie) (b' : XMap.t Trie) =>\n                                    XMap.add k0 (snd (Trie_update' m0 s update_term)) b')\n                                 {| XMap.this := m; XMap.is_bst := H3 |}\n                                 (XMap.empty Trie))) by apply H1; clear H1.\n          setoid_rewrite FMap_Insert_fold_add_map_eq in H5.\n          rewrite map_mapsto_iff in H5; destruct_ex; intuition; subst.\n          eapply H; eauto.\n      }\n    Qed.\n\n    Lemma Permutation_app_fold_left\n    : forall l bags,\n        Permutation ((fold_left\n                        (fun (a : list BagType) (p : key * Trie) =>\n                           Trie_enumerate (snd p) ++ a) l\n                        bags))\n                    (bags ++\n                          (fold_left\n                             (fun (a : list BagType) (p : key * Trie) =>\n                                Trie_enumerate (snd p) ++ a) l\n                             [ ])).\n    Proof.\n      induction l; simpl; intros.\n      - rewrite app_nil_r; reflexivity.\n      - rewrite IHl, <- app_assoc,\n        Permutation_app_comm, <- app_assoc.\n        f_equiv.\n        rewrite Permutation_app_comm, <- IHl, app_nil_r; reflexivity.\n    Qed.\n\n    Lemma Permutation_benumerate_fold_left\n    : forall l bags,\n        Permutation (List.map benumerate\n                              (fold_left\n                                 (fun (a : list BagType) (p : key * Trie) =>\n                                    Trie_enumerate (snd p) ++ a) l\n                                 bags))\n                    ((List.map benumerate bags) ++\n                                                (List.map benumerate (fold_left\n                                                                        (fun (a : list BagType) (p : key * Trie) =>\n                                                                           Trie_enumerate (snd p) ++ a) l\n                                                                        [ ]))).\n    Proof.\n      intros; rewrite Permutation_app_fold_left, map_app; eauto.\n    Qed.\n\n    Lemma XMapfoldBst A :\n      forall f m (acc : A) (WFm : bst m),\n        XMapfold f m acc =\n        XMap.fold f (XMap.Bst WFm) acc.\n    Proof.\n      intros; rewrite XMapfold_eq; reflexivity.\n    Qed.\n\n    Ltac replaceXMapfold :=\n      match goal with\n          |- context [XMapfold ?f ?m ?acc] =>\n          let Bst_m := fresh in\n          assert (bst m) as Bst_m;\n            [ eauto | setoid_rewrite (XMapfoldBst f acc Bst_m)]\n      end.\n\n    Lemma XMapfindBst elt :\n      forall k (m : Map elt) (WFm : bst m),\n        find k m = XMap.find k (XMap.Bst WFm).\n    Proof.\n      reflexivity.\n    Qed.\n\n    Lemma Tries_enumerate_app_Proper\n    : Proper\n        (X.eq ==> eq ==> Permutation (A:=BagType) ==> Permutation (A:=BagType))\n        (fun (_ : X.t) (tries : Trie) (bags : list BagType) =>\n           Trie_enumerate tries ++ bags).\n    Proof.\n      unfold Proper, respectful; intros.\n      subst; rewrite H1; reflexivity.\n    Qed.\n\n    Lemma Tries_enumerate_app_transpose_neqkey\n    : transpose_neqkey (Permutation (A:=BagType))\n                       (fun (_ : X.t) (tries : Trie) (bags : list BagType) =>\n                          Trie_enumerate tries ++ bags).\n    Proof.\n      unfold transpose_neqkey; intros; rewrite Permutation_app_swap, <- app_assoc; f_equiv; apply Permutation_app_swap.\n    Qed.\n\n    Lemma benumerate_bempty_nil :\n      benumerate bempty = nil.\n      pose proof benumerate_empty; unfold BagEnumerateEmpty in *.\n      induction (benumerate bempty); eauto.\n      simpl in *; elimtype False; eapply H; eauto.\n    Qed.\n\n    Lemma Proper_KeyBasedPartitioningFunction\n    : forall key, Proper (X.eq ==> eq ==> eq) (KeyBasedPartitioningFunction Trie key).\n      unfold Proper, respectful; intros; subst.\n      unfold KeyBasedPartitioningFunction.\n      repeat find_if_inside; eauto.\n      rewrite H in e; intuition.\n    Qed.\n\n    Lemma TrieBag_BagEnumerateEmpty :\n      BagEnumerateEmpty TrieBag_benumerate TrieBag_bempty.\n    Proof.\n      intros;\n      unfold BagEnumerateEmpty, TrieBag_benumerate, flatten; simpl.\n      rewrite app_nil_r; apply benumerate_empty.\n    Qed.\n\n    Lemma Trie_find_TreeOK\n    : forall trie st2 st1,\n        TrieOK trie st1\n        -> forall bag,\n             List.In bag (Trie_find trie st2)\n             -> RepInv bag.\n    Proof.\n      intros trie st2; eapply Trie_find_ind; intros; subst.\n      - inversion H; subst; eauto.\n        simpl in H0; intuition eauto; subst; eauto.\n      - simpl in H1; intuition; subst.\n        + inversion H0; subst; eauto.\n        + eapply (H (st1 ++ [key0])); eauto.\n      - simpl in H0; intuition; subst; eauto.\n    Qed.\n\n    Fixpoint Trie_enumerate_ind\n             (P : Trie -> list BagType -> list X.t -> Prop)\n             (H : forall trie st,\n                    (bst (SubTries trie)\n                     -> forall (k : key) (trie' : Trie),\n                          MapsTo k trie' (SubTries trie) -> P trie' (Trie_enumerate trie') (st ++ [k])) -> P trie (Trie_enumerate trie) st)\n             (trie : Trie)\n             (st : list X.t)\n             {struct trie}\n    : P trie (Trie_enumerate trie) st.\n    Proof.\n      refine (match trie with\n                | Node bag tries => _\n              end).\n      pose proof (@XMapfold_ind P (Trie_enumerate_ind P H) tries).\n      clear Trie_enumerate_ind.\n      eauto.\n    Qed.\n\n    Lemma Permute_XMapfold_cons\n      : forall m l,\n        XMapfold\n          (fun (_ : X.t) (tries : Trie) (bags : list BagType) =>\n             Trie_enumerate tries ++ bags) m l =\n        (XMapfold (fun (_ : X.t) (tries : Trie) (bags : list BagType) =>\n                     Trie_enumerate tries ++ bags) m []) ++ l.\n    Proof.\n      induction m; simpl; eauto.\n      intros.\n      rewrite IHm2; symmetry; rewrite IHm2.\n      rewrite <- !app_assoc; f_equiv; f_equiv.\n      symmetry; eauto.\n    Qed.\n\n    Lemma Trie_enumerate_RepInv\n      : forall trie l,\n        TrieOK trie l\n        -> forall item,\n          List.In item (Trie_enumerate trie)\n          -> RepInv item.\n    Proof.\n      intros trie l; pattern trie, l; eapply Trie_ind'; simpl; intros.\n      inversion H0; subst; clear H0.\n      rewrite Permute_XMapfold_cons in H1; apply List.in_app_or in H1; intuition.\n      - rewrite XMapfold_eq in H0.\n        pose fold_spec_right as e; unfold XMap.fold in e; rewrite (e _ (XMap.Bst H5)) in H0;\n        clear e.\n        assert (exists k trie, List.In (k, trie)\n                                       (XMap.elements (elt := Trie)\n                                       {| XMap.this := m;\n                                          XMap.is_bst := H5 |})\n                               /\\ List.In item (Trie_enumerate trie)).\n        { revert H0; clear.\n          induction\n            (XMap.elements (elt := Trie)\n                           {| XMap.this := m;\n                              XMap.is_bst := H5 |}); simpl; intros; intuition.\n          rewrite fold_right_app in H0; simpl in H0.\n          rewrite fold_left_rev_right in H0; simpl in H0.\n          unfold uncurry in *.\n          rewrite Permutation_app_fold_left in H0; apply in_app_or in H0; intuition.\n          apply in_app_or in H; intuition.\n          destruct a; eauto.\n          destruct IHl as [k [trie' [In_k In_trie] ] ].\n          rewrite fold_left_rev_right; eauto.\n          eexists; eauto.\n          }\n        destruct H1 as [k [trie' [In_k In_trie'] ] ].\n        eapply (H k trie' l0); eauto.\n        eapply elements_mapsto_iff with (m := XMap.Bst H5).\n        eapply InA_In; eauto.\n        econstructor; reflexivity.\n        apply H8.\n        eapply elements_mapsto_iff with (m := XMap.Bst H5).\n        eapply InA_In; eauto.\n        econstructor; reflexivity.\n      - simpl in H0; intuition; subst; eauto.\n    Qed.\n\n    Lemma TrieBag_BagCountCorrect :\n      BagCountCorrect TrieBagRepInv TrieBag_bcount TrieBag_bfind .\n    Proof.\n      unfold TrieBagRepInv, TrieBag_bcount, TrieBag_bfind, BagCountCorrect.\n      simpl; intros; destruct search_term as [ [key | ] search_term ].\n      - rewrite length_flatten.\n        rewrite !foldright_compose.\n        rewrite <- !fold_left_rev_right.\n        rewrite map_map.\n        generalize (Trie_find_TreeOK key containerCorrect).\n        remember 0 as n; clear Heqn; revert n.\n        induction (Trie_find container key); simpl; eauto.\n        intros.\n        intros; rewrite IHl by eauto.\n        rewrite fold_right_app; simpl.\n        rewrite bcount_correct by eauto.\n        rewrite !fold_left_rev_right; simpl.\n        clear; revert n; induction l; simpl; eauto with arith.\n        intros; rewrite IHl; f_equal; omega.\n      - rewrite length_flatten.\n        remember [] as l; replace 0 with (length l) by (subst; eauto).\n        clear Heql; generalize (Trie_enumerate_RepInv containerCorrect).\n        induction (Trie_enumerate container); simpl; eauto.\n        rewrite !foldright_compose, <- !fold_left_rev_right, map_map.\n        intros; unfold compose in *; rewrite bcount_correct by eauto.\n        rewrite !fold_left_rev_right.\n        rewrite <- map_map, <- foldright_compose.\n        unfold compose; rewrite IHl0 by eauto.\n        remember (length l) as n; clear Heqn; generalize n.\n        clear; induction l0; simpl; eauto with arith; intros.\n        rewrite IHl0; f_equal; omega.\n    Qed.\n\n    Lemma Permutation_KeyBasedPartition\n    : forall key m bst_m b,\n        Permutation\n          (fold\n             (fun (_ : XMap.Raw.key) (trie : Trie) (a : list BagType) =>\n                Trie_enumerate trie ++ a) m b)\n          (XMap.fold\n             (fun (_ : XMap.key) (trie : Trie) (a : list BagType) =>\n                Trie_enumerate trie ++ a)\n             (fst\n                (partition (KeyBasedPartitioningFunction Trie key)\n                           {|\n                             XMap.this := m;\n                             XMap.is_bst := bst_m |}))\n             (XMap.fold\n                (fun (_ : XMap.key) (trie : Trie) (a : list BagType) =>\n                   Trie_enumerate trie ++ a)\n                (snd\n                   (partition (KeyBasedPartitioningFunction Trie key)\n                              {|\n                                XMap.this := m;\n                                XMap.is_bst :=  bst_m |}))\n                b)) .\n    Proof.\n      intros.\n      pose proof (partition_Partition_simple\n                    _\n                    (KeyBasedPartitioningFunction Trie key0)\n                    (KeyBasedPartitioningFunction_Proper _ _)\n                    (XMap.Bst bst_m)) as part.\n      erewrite Partition_fold with\n      (f := (fun (_ : key) (trie : Trie) (a : list BagType) =>\n               Trie_enumerate trie ++ a))\n        (m := {| XMap.this := m; XMap.is_bst := bst_m |} )\n        (i := b);\n        (eauto using part, Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n    Qed.\n\n      Lemma In_fold_left_split' :\n      forall bag l acc,\n        List.In bag\n                (acc ++ fold_left\n                     (fun (a0 : list BagType) (p : key * Trie) =>\n                        Trie_enumerate (snd p) ++ a0) l\n                     [ ])\n        <-> List.In bag\n                    ((fold_left\n                        (fun (a0 : list BagType) (p : key * Trie) =>\n                           Trie_enumerate (snd p) ++ a0) l\n                        acc)).\n    Proof.\n      induction l; simpl; intros.\n      - rewrite app_nil_r in *; eauto.\n        reflexivity.\n      - rewrite <- IHl.\n        split; intros.\n        rewrite <- app_assoc; apply in_or_app.\n        apply in_app_or in H; intuition eauto.\n        right; apply in_or_app; eauto.\n        rewrite <- IHl in H0.\n        rewrite <- !app_assoc in H0.\n        apply in_app_or in H0; intuition.\n        apply in_app_or in H; intuition.\n        apply in_app_or in H0; intuition.\n        apply in_or_app; intuition.\n        right; rewrite <- IHl; intuition.\n        apply in_or_app; intuition.\n        rewrite <- IHl in H0.\n        apply in_app_or in H0; intuition.\n        right.\n        rewrite <- IHl.\n        apply in_or_app; auto.\n    Qed.\n\n    Corollary In_fold_left_split :\n      forall (k : X.t) t bag l acc,\n        List.In (k, bag)\n                (List.map (fun bag0 : BagType => (t, bag0))\n                          (acc ++ fold_left\n                               (fun (a0 : list BagType) (p : key * Trie) =>\n                                  Trie_enumerate (snd p) ++ a0) l\n                               [ ]))\n        <-> List.In (k, bag)\n                    (List.map (fun bag0 : BagType => (t, bag0))\n                              (fold_left\n                                 (fun (a0 : list BagType) (p : key * Trie) =>\n                                    Trie_enumerate (snd p) ++ a0) l\n                                 acc)).\n    Proof.\n      intros; rewrite !in_map_iff;\n      split; intros; destruct_ex; intuition;\n      eexists; split; eauto.\n      rewrite In_fold_left_split' in H1; eauto.\n      rewrite <- In_fold_left_split' in H1; eauto.\n    Qed.\n\n    Lemma In_fold_left_map_split' :\n      forall bag l acc,\n        List.In bag\n                (acc ++ fold_left\n                     (fun (a0 : list (key * BagType)) (p : key * Trie) =>\n                      List.map (fun bag0 : BagType => (fst p, bag0))\n                               (Trie_enumerate (snd p)) ++ a0)\n                     l\n                     [ ])\n        <-> List.In bag\n                    (fold_left\n                         (fun (a0 : list (key * BagType)) (p : key * Trie) =>\n                               List.map (fun bag0 : BagType => (fst p, bag0))\n                                        (Trie_enumerate (snd p)) ++ a0)\n                         l\n                         acc).\n    Proof.\n      induction l; simpl; intros.\n      - rewrite app_nil_r in *; eauto.\n        reflexivity.\n      - rewrite <- IHl.\n        split; intros.\n        rewrite <- app_assoc; apply in_or_app.\n        apply in_app_or in H; intuition eauto.\n        right; apply in_or_app; eauto.\n        rewrite <- IHl in H0.\n        rewrite <- !app_assoc in H0.\n        apply in_app_or in H0; intuition.\n        apply in_app_or in H; intuition.\n        apply in_app_or in H0; intuition.\n        apply in_or_app; intuition.\n        right; rewrite <- IHl; intuition.\n        apply in_or_app; intuition.\n        rewrite <- IHl in H0.\n        apply in_app_or in H0; intuition.\n        right.\n        rewrite <- IHl.\n        apply in_or_app; auto.\n    Qed.\n\n    Lemma Trie_add_Correct\n    : forall trie item st1 st2,\n        eqlistA X.eq (projection item) (st2 ++ st1)\n        -> TrieOK trie st2\n        -> Permutation\n             (TrieBag_benumerate (Trie_add trie st1 item))\n             (item :: TrieBag_benumerate trie).\n    Proof.\n      intros trie item st1; eapply Trie_add_ind; intros; subst.\n      - destruct trie0; simpl.\n        unfold TrieBag_benumerate; simpl.\n        rewrite !XMapfold_eq, !fold_1 by eauto.\n        rewrite Permutation_benumerate_fold_left.\n        simpl; rewrite binsert_enumerate; eauto.\n        simpl; constructor.\n        symmetry.\n        rewrite Permutation_benumerate_fold_left; simpl.\n        reflexivity.\n      - destruct trie0; simpl.\n        unfold TrieBag_benumerate; simpl.\n        replaceXMapfold.\n        replaceXMapfold.\n        unfold XMap.fold at 2.\n\n        rewrite Permutation_KeyBasedPartition with (key0 := key0)\n                                                     (bst_m := SubTrieMapBST H1).\n\n        pose proof (@partition_after_KeyBasedPartition_and_add\n                      _ key0 (Trie_add subtrie st' item0) (XMap.Bst (SubTrieMapBST H1)))\n          as part_add.\n\n        rewrite Partition_fold at 1;\n          (eauto using part_add, Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n\n        apply find_2 in e0.\n\n        pose proof (KeyBasedPartition_fst_singleton key0 subtrie (XMap.Bst (SubTrieMapBST H1)) e0) as singleton.\n        pose proof (add_Equal_simple singleton key0 (Trie_add subtrie st' item0)) as singleton'.\n        rewrite (fold_Equal_simpl (eqA := @Permutation BagType) singleton')\n          by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n        rewrite (fold_Equal_simpl (eqA := @Permutation BagType) singleton)\n          by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n        rewrite (fold_Equal_simpl (multiple_adds _ _ _ _))\n          by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n        rewrite !fold_add\n          by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey, empty_In).\n\n        rewrite fold_empty.\n        rewrite !map_app.\n        unfold TrieBag_benumerate in H.\n        rewrite !flatten_app, (H (st2 ++ [key0])); eauto.\n        rewrite <- app_assoc; simpl; eauto.\n        inversion H1; subst; eauto.\n      - destruct trie0; simpl.\n        unfold TrieBag_benumerate; simpl.\n        replaceXMapfold.\n        replaceXMapfold.\n\n        pose proof (@partition_after_KeyBasedPartition_and_add\n                      _ key0 (Trie_add TrieBag_bempty st' item0) (XMap.Bst (SubTrieMapBST H1)))\n          as part_add.\n\n        pose proof (partition_Partition_simple\n                      _\n                      (KeyBasedPartitioningFunction Trie key0)\n                      (KeyBasedPartitioningFunction_Proper _ _)\n                      (XMap.Bst (SubTrieMapBST H1))) as part.\n\n        rewrite Partition_fold at 1;\n          (eauto using part_add, Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n        rewrite Partition_fold with (m := {| XMap.this := m; XMap.is_bst := H3 |} );\n          (eauto using part, Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n        rewrite !fold_add;\n          eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey, empty_In.\n        rewrite map_app, flatten_app.\n        rewrite (H (st2 ++ [key0])); simpl.\n        unfold TrieBag_benumerate; simpl.\n        rewrite benumerate_bempty_nil; simpl.\n        reflexivity.\n        rewrite <- app_assoc; eauto.\n        econstructor; eauto using bempty_RepInv.\n        + rewrite benumerate_bempty_nil in *; simpl in *; intuition.\n        + intros; elimtype False; eapply empty_1; eauto.\n        + intro H4.\n          destruct H4.\n          apply (@partition_iff_1 _\n                                  (KeyBasedPartitioningFunction Trie key0)\n                                  (Proper_KeyBasedPartitioningFunction key0)\n                                  {| XMap.this := m; XMap.is_bst := SubTrieMapBST H1 |}\n                                  _\n                                  key0 x\n                                  (refl_equal _)) in H4; intuition.\n          apply find_1 in H5; eauto; simpl in *; congruence.\n    Qed.\n\n    Corollary TrieBag_BagInsertEnumerate :\n      BagInsertEnumerate TrieBagRepInv TrieBag_benumerate TrieBag_binsert.\n    Proof.\n      unfold BagInsertEnumerate; intros; eapply Trie_add_Correct; eauto.\n      simpl; reflexivity.\n    Qed.\n\n    Lemma TrieBag_enumerateOK\n    : forall l st1 (bags : list (key * BagType)) k bag,\n        (forall (k : X.t) (subtrie : Trie),\n           InA (PX.eqke (elt:=Trie)) (k, subtrie) l ->\n           TrieOK subtrie (st1 ++ [k])) ->\n        (forall (k : key) (bag : BagType),\n           List.In (k, bag) bags ->\n           forall (item: TItem),\n              List.In item (benumerate bag) ->\n              Prefix (st1 ++ [k]) (projection item))\n        -> List.In (k, bag) (fold_left\n                          (fun (a : list (key * BagType)) (p : key * Trie) =>\n                             (List.map (fun bag => (fst p, bag)) (Trie_enumerate (snd p)) ++ a)) l bags)\n        -> forall (item: TItem),\n              List.In item (benumerate bag) ->\n              Prefix (st1 ++ [k]) (projection item).\n    Proof.\n      induction l; simpl; eauto.\n      - intros.\n        rewrite <- In_fold_left_map_split' in H1.\n        rewrite <- app_assoc in H1.\n        apply in_app_or in H1; intuition eauto.\n        destruct a as [k' t]; simpl in *.\n        assert (InA (PX.eqke (elt:=Trie)) (k', t) ((k', t) :: l))\n               by (econstructor; eauto).\n        generalize (H k' t H1).\n        assert (k = k')\n          by (revert H3; clear; induction (Trie_enumerate t);\n              simpl; intro; intuition; injections; eauto).\n        subst.\n        apply in_map with (f := snd) in H3; rewrite map_map, map_id in H3.\n        remember (st1 ++ [k']).\n        setoid_rewrite <- Heql0.\n        generalize bag H2 H3; clear.\n        eapply (fun P H => @Trie_enumerate_ind P H t l0).\n        simpl; intros.\n        destruct trie; simpl in *.\n        rewrite !XMapfold_eq, !fold_1 in H3; eauto.\n        rewrite <- In_fold_left_split' in H3.\n        apply in_app_or in H3; intuition.\n        + simpl in H1; intuition; injections; subst.\n          inversion H0; subst.\n          apply H6 in H2; revert H2; clear.\n          * revert st; induction (projection item); simpl.\n            intros; inversion H2; subst.\n            eexists nil; rewrite app_nil_r.\n            constructor; symmetry; eauto.\n            eexists nil; simpl; rewrite app_nil_r; symmetry; eauto.\n        +  assert\n             (forall (k : key) (trie' : Trie),\n                InA (XMap.eq_key_elt (elt:=Trie)) (k,trie') (elements m) ->     List.In item (benumerate bag) ->\n                List.In (t, bag)\n                        (List.map (fun bag0 : BagType => (t, bag0)) (Trie_enumerate trie')) ->\n                TrieOK trie' (st ++ [k]) -> Prefix (st ++ [k]) (projection item)).\n           { intros; eapply H; eauto.\n             eapply (@XMap.elements_2 _ (XMap.Bst (SubTrieMapBST H0))); eauto.\n             apply in_map with (f := snd) in H5;\n               rewrite map_map, map_id in H5; simpl in *;\n               eauto.\n           }\n           assert (forall k' trie,\n                     InA (XMap.eq_key_elt (elt:=Trie)) (k', trie) (elements m)\n                     -> TrieOK trie (st ++ [k'])).\n           {  revert H0; clear.\n              intros; inversion H0; subst.\n              apply (@XMap.elements_2 _ (XMap.Bst H4)) in H.\n              apply H7 in H; simpl in H; eauto.\n           }\n           generalize st bag item b t H2 H3 H1 H4; clear.\n           induction (elements m); simpl; intros.\n           * intuition.\n           * rewrite <- In_fold_left_split' in H1.\n             apply in_app_or in H1; intuition eauto.\n             assert (forall a b c, Prefix (a ++ [b]) c ->\n                                   Prefix a c).\n             {\n               clear; intros; destruct H.\n               exists (b :: x); rewrite <- app_assoc in H; eauto.\n             }\n             destruct a; eapply H0; eapply H3.\n             econstructor; reflexivity.\n             eauto.\n             rewrite app_nil_r in H.\n             eauto.\n             simpl in H.\n             apply in_map_iff; eauto.\n             eapply H4; econstructor; eauto.\n             reflexivity.\n             eapply IHl; eauto.\n        + eapply IHl; eauto.\n          apply In_fold_left_map_split'; eauto.\n    Qed.\n\n    Lemma TrieBag_enumerateOK1\n    : forall l st1 search_term bags,\n        (forall (k : X.t) (subtrie : Trie),\n           InA (PX.eqke (elt:=Trie)) (k, subtrie) l ->\n           TrieOK subtrie (st1 ++ [k])) ->\n        (forall (k : X.t) (bag : BagType) item,\n           List.In (k, bag) bags\n           -> List.In item (benumerate (Bag := TBag) bag)\n           -> Prefix (st1 ++ [k]) (projection item))\n        -> Permutation\n             (List.filter (TrieBag_bfind_matcher (Some st1, search_term))\n                          (flatten\n                             (List.map (fun p => benumerate (snd p))\n                                       (fold_left\n                                          (fun (a : list (key * BagType)) (p : key * Trie) =>\n                                             (List.map (fun bag => (fst p, bag)) (Trie_enumerate (snd p)) ++ a)) l bags))))\n             [].\n    Proof.\n      induction l; simpl; eauto.\n      - induction bags; simpl in *; intros; eauto.\n        rewrite filter_app, IHbags; eauto.\n        destruct a.\n        rewrite app_nil_r.\n        simpl.\n        generalize (fun item => H0 _ _ item (or_introl (refl_equal _))) ; clear; simpl.\n        induction (benumerate b); simpl; eauto.\n        intros.\n        unfold TrieBag_bfind_matcher, IsPrefix; simpl.\n        destruct (Prefix_dec F.eq_dec (projection a) st1); simpl in *.\n        find_if_inside; eauto.\n        intros.\n        pose proof (H _ (or_introl (refl_equal _))).\n        elimtype False.\n        generalize st1 p H0; clear.\n        induction (projection a); simpl.\n        + destruct st1; simpl; intros;  destruct H0; inversion H.\n        + destruct st1; simpl; try congruence.\n          intros; inversion p; inversion H.\n          intros; eapply (IHl st1).\n          destruct p; simpl in *; inversion H; subst; eexists; eauto.\n          intros; destruct H0; inversion H; subst.\n          eexists; eauto.\n        + eauto.\n      - intros; rewrite IHl; eauto.\n        intros.\n        apply in_app_or in H1; intuition eauto.\n        destruct a.\n        assert (InA (PX.eqke (elt:=Trie)) (t, t0) ((t, t0) :: l)) by\n            (econstructor; eauto).\n        apply H in H1; simpl in *.\n        assert (k = t).\n        {\n          revert H3; clear; induction (Trie_enumerate t0); simpl;\n          intros; intuition;  congruence.\n        }\n        subst.\n        revert H2 H3 H1.\n        clear.\n        eapply (fun P H => @Trie_enumerate_ind P H t0 (st1 ++ [t])).\n        simpl; intros.\n        destruct trie; simpl in *.\n        rewrite !XMapfold_eq, !fold_1 in H3; eauto.\n        rewrite <- In_fold_left_split, map_app in H3.\n        apply in_app_or in H3; intuition.\n        + simpl in H0; intuition; injections; subst.\n          inversion H1; subst.\n          apply H6 in H2; revert H2; clear.\n          * revert st; induction (projection item); simpl.\n            intros; inversion H2; subst.\n            eexists nil; rewrite app_nil_r.\n            constructor; symmetry; eauto.\n            eexists nil; simpl; rewrite app_nil_r; symmetry; eauto.\n        +  assert\n             (forall (k : key) (trie' : Trie),\n                InA (XMap.eq_key_elt (elt:=Trie)) (k,trie') (elements m) ->     List.In item (benumerate bag) ->\n                List.In (t, bag)\n                        (List.map (fun bag0 : BagType => (t, bag0)) (Trie_enumerate trie')) ->\n                TrieOK trie' (st ++ [k]) -> Prefix (st ++ [k]) (projection item)).\n           { intros; eapply H; eauto.\n             eapply (@XMap.elements_2 _ (XMap.Bst (SubTrieMapBST H1))); eauto. }\n           assert (forall k' trie,\n                     InA (XMap.eq_key_elt (elt:=Trie)) (k', trie) (elements m)\n                     -> TrieOK trie (st ++ [k'])).\n           {  revert H1; clear.\n              intros; inversion H1; subst.\n              apply (@XMap.elements_2 _ (XMap.Bst H4)) in H.\n              apply H7 in H; simpl in H; eauto.\n           }\n           generalize st bag item b t H2 H3 H0 H4; clear.\n           induction (elements m); simpl; intros.\n           * intuition.\n           * rewrite <- In_fold_left_split, map_app in H0.\n             apply in_app_or in H0; intuition eauto.\n             assert (forall a b c, Prefix (a ++ [b]) c ->\n                                   Prefix a c).\n             {\n               clear; intros; destruct H.\n               exists (b :: x); rewrite <- app_assoc in H; eauto.\n             }\n             destruct a; eapply H0; eapply H3.\n             econstructor; reflexivity.\n             eauto.\n             rewrite app_nil_r in H.\n             eauto.\n             eapply H4; econstructor; eauto.\n             reflexivity.\n             eapply IHl; eauto.\n    Qed.\n\n    Corollary TrieBag_enumerateOK'\n    : forall l st1 search_term,\n        (forall (k : X.t) (subtrie : Trie),\n           InA (PX.eqke (elt:=Trie)) (k, subtrie) l ->\n           TrieOK subtrie (st1 ++ [k]))\n        -> Permutation\n             (List.filter (TrieBag_bfind_matcher (Some st1, search_term))\n                          (flatten\n                             (List.map benumerate\n                                       (fold_left\n                                          (fun (a : list (BagType)) (p : key * Trie) =>\n                                             (Trie_enumerate (snd p)) ++ a) l [ ]))))\n             [].\n    Proof.\n      intros.\n      rewrite <- (@TrieBag_enumerateOK1 l st1 search_term [ ] H) by\n          intuition.\n      remember (@nil BagType); remember (@nil (X.t * BagType)).\n      assert (List.map snd l1 = l0) by (subst; eauto).\n      generalize l1 l0 H0; clear; induction l; simpl; intros.\n      rewrite <- map_map with (f := snd). setoid_rewrite H0.\n      reflexivity.\n      rewrite <- IHl; eauto.\n      rewrite map_app, map_map, map_id; simpl.\n      setoid_rewrite H0; reflexivity.\n    Qed.\n\n    Global Instance Prefix_refl :\n      Reflexive Prefix.\n    Proof.\n      intros; eexists nil; rewrite app_nil_r; reflexivity.\n    Qed.\n\n    Global Instance Prefix_trans :\n      Transitive Prefix.\n    Proof.\n      unfold Transitive;\n      intros; destruct H as [k H]; destruct H0 as [k' H0].\n      eexists (k ++ k'); rewrite <- H0, <- H, <- app_assoc; reflexivity.\n    Qed.\n\n    (*Add Parametric Relation\n    : (list _) (Prefix)\n        reflexivity proved by reflexivity\n        transitivity proved by transitivity\n          as refine_rel.*)\n\n    Lemma Prefix_app :\n      forall l l',\n        Prefix l (l ++ l').\n    Proof.\n      intros; eexists l'; reflexivity.\n    Qed.\n\n    Lemma filter_Prefix\n    : forall (b : BagType) m st l search_term',\n        TrieOK (Node b m) l\n        -> Prefix l st\n        -> Permutation (List.filter (bfind_matcher search_term') (benumerate b))\n                       (List.filter (TrieBag_bfind_matcher (Some st, search_term'))\n                                    (benumerate b)).\n    Proof.\n      intros; inversion H; subst.\n      revert H0 H5; clear.\n      induction (benumerate b); simpl; eauto.\n      unfold TrieBag_bfind_matcher; simpl.\n      intros; case_eq (Prefix_dec F.eq_dec (projection a) st); simpl; intros.\n      find_if_inside; simpl; rewrite IHl0; eauto.\n      assert (Prefix (projection a) l)\n        by (eexists nil; rewrite app_nil_r; eauto).\n      destruct n.\n      rewrite H1; apply H0.\n    Qed.\n\n    Lemma filter_negb_Prefix\n    : forall (b : BagType) m st l search_term',\n        TrieOK (Node b m) l\n        -> Prefix l st\n        -> Permutation (List.filter (fun a => negb (bfind_matcher search_term' a)) (benumerate b))\n                       (List.filter (fun a => negb (TrieBag_bfind_matcher (Some st, search_term') a))\n                                    (benumerate b)).\n    Proof.\n      intros; inversion H; subst.\n      revert H0 H5; clear.\n      induction (benumerate b); simpl; eauto.\n      unfold TrieBag_bfind_matcher; simpl.\n      intros; case_eq (Prefix_dec F.eq_dec (projection a) st); simpl; intros.\n      find_if_inside; simpl; rewrite IHl0; eauto.\n      assert (Prefix (projection a) l)\n        by (eexists nil; rewrite app_nil_r; eauto).\n      destruct n.\n      rewrite H1; apply H0.\n    Qed.\n\n    Lemma Prefix_cons_inv\n    : forall a l l',\n        Prefix (a :: l) (a :: l') -> Prefix l l'.\n    Proof.\n      induction l; simpl; intros.\n      - eexists l'; simpl; reflexivity.\n      - destruct H; inversion H; subst.\n        exists x; eauto.\n    Qed.\n\n    Lemma Prefix_app_inv\n    : forall a l l',\n        Prefix (a ++ l) (a ++ l') -> Prefix l l'.\n    Proof.\n      induction a; simpl; intros; eauto.\n      apply IHa; eapply Prefix_cons_inv; eauto.\n    Qed.\n\n    Lemma filter_remove_key :\n      forall key' m l st' search_term,\n        (forall (k : X.t) (subtrie : Trie),\n           InA (PX.eqke (elt:=Trie)) (k, subtrie)\n               (elements (remove key' (XMap.this m))) ->\n           TrieOK subtrie (l ++ [k]))\n        -> Permutation\n          (flatten\n             (List.map\n                (fun x : BagType =>\n                   List.filter\n                     (TrieBag_bfind_matcher (Some (l ++ key' :: st'), search_term))\n                     (benumerate x))\n                (XMap.fold\n                   (fun (_ : key) (trie : Trie) (a : list BagType) =>\n                      Trie_enumerate trie ++ a)\n                   (XMap.remove (elt:=Trie) key' m\n                   )\n                   []))) [].\n    Proof.\n      intros; unfold XMap.fold; rewrite fold_1; simpl; eauto.\n      remember (@nil BagType) as bags.\n      remember (@nil (key * BagType)) as bags'.\n      assert (forall (k0 : key) (bag0 : BagType),\n     List.In (k0, bag0) bags' ->\n     forall item : TItem,\n       List.In item (benumerate bag0) -> Prefix (l ++ [k0]) (projection item)) by (rewrite Heqbags'; intuition).\n      generalize\n           (fun k bag =>\n              @TrieBag_enumerateOK\n                (elements (remove key' (XMap.this m))) l bags' k bag\n                H H0).\n      clear H0.\n      assert (bags = List.map (@snd _ _) bags')  as H0\n        by (rewrite Heqbags', Heqbags; reflexivity);\n        rewrite H0; clear H0.\n      assert (forall (k : X.t) (subtrie : Trie),\n                InA (PX.eqke (elt:=Trie)) (k, subtrie)\n                    (elements (remove key' (XMap.this m))) ->\n                ~X.eq k key')\n        by (intros;\n            rewrite <- (@elements_mapsto_iff _ (XMap.Bst (remove_bst key' (XMap.is_bst m)))) in H0;\n            apply remove_mapsto_iff in H0; intuition).\n      assert (forall (k : X.t) b,\n                InA (PX.eqke (elt:=BagType)) (k, b) bags' ->\n                ~X.eq k key')\n        by (intros;\n            rewrite Heqbags' in *; inversion H1).\n      generalize bags' H H0 H1; clear; induction (elements (remove key' (XMap.this m))); simpl.\n      - induction bags'; simpl; intros; eauto.\n        rewrite IHbags'; eauto.\n        destruct a; simpl in *.\n        assert (~ X.eq k key') by\n            (intros; eapply H1; econstructor; eauto).\n        generalize (fun item => H2 k b (or_introl (refl_equal _)) item) H3;\n          clear.\n        induction (benumerate b); simpl; eauto; intros.\n        pose proof (H _ (or_introl (refl_equal _))).\n        rewrite <- IsPrefix_iff_Prefix in H0.\n        unfold TrieBag_bfind_matcher, IsPrefix in *; simpl in *.\n        case_eq (Prefix_dec F.eq_dec (projection a) (l ++ key' :: st')); eauto.\n        intros.\n        assert (Prefix (l ++ [k]) (l ++ key' :: st')).\n        etransitivity; eauto.\n        pose proof (Prefix_app_inv _ _ _ H2).\n        destruct H4; inversion H4; subst.\n        elimtype False; eapply H3; eauto.\n      - intros.\n        rewrite <- (IHl0 ((List.map (fun a' => (fst a, a')) (Trie_enumerate (snd a))) ++ bags')); eauto.\n        rewrite map_app, map_map, map_id; reflexivity.\n        intros.\n        apply InA_app in H3; intuition eauto.\n        assert (~X.eq k (fst a))\n          by (destruct a; intro; eapply H0; eauto; econstructor).\n        apply H3; revert H5; clear; induction (Trie_enumerate (snd a));\n        intros; inversion H5; subst; eauto.\n        destruct H0; simpl in *; eauto.\n      - eapply (remove_bst _ (XMap.is_bst m)).\n    Qed.\n\n    Lemma elements_add_eq elt\n    : forall k (v : elt) m,\n        XMap.Equal (XMap.add k v m)\n                   (XMap.add k v (XMap.remove k m)).\n    Proof.\n      unfold XMap.Equal; intros.\n      symmetry; case_eq (XMap.find (elt:=elt) y (XMap.add k v m)); intros.\n      apply find_2 in H.\n      rewrite (@add_mapsto_iff _ m k y v e) in H; intuition; subst.\n      apply find_1; eauto.\n      exact (XMap.is_bst _).\n      apply add_1; eauto.\n      apply find_1; eauto.\n      exact (XMap.is_bst _).\n      apply add_2; eauto.\n      apply remove_2; eauto.\n      exact (XMap.is_bst _).\n      rewrite <- not_find_in_iff in *.\n      intro; apply H.\n      destruct H0.\n      rewrite (@add_mapsto_iff _ (XMap.remove k m) k y v x) in H0; intuition; subst.\n      eexists; eapply add_1; eauto.\n      rewrite (@remove_mapsto_iff _ m k y x) in H2; intuition.\n      eexists; eauto.\n      apply add_2; eauto.\n    Qed.\n\n    Lemma Permutation_benumerate_add\n    : forall k v m,\n        Permutation\n          (flatten\n             (List.map benumerate\n                       (fold_left\n                          (fun (a : list BagType) (p : XMap.key * Trie) =>\n                             Trie_enumerate (snd p) ++ a) (XMap.elements (XMap.add k v m))\n                          [])))\n          (flatten\n             (List.map benumerate\n                       (Trie_enumerate v ++\n                                       (fold_left\n                                          (fun (a : list BagType) (p : key * Trie) =>\n                                             Trie_enumerate (snd p) ++ a) (XMap.elements (XMap.remove k m))\n                                          [])))).\n    Proof.\n      intros; pose (@XMap.fold_1 _ (XMap.add k v m) _ nil\n                                 (fun _ (p : Trie) (a : list BagType) =>\n                                    Trie_enumerate p ++ a)).\n      simpl in e.\n      rewrite <- !e.\n      rewrite (fold_Equal_simpl (eqA := @Permutation BagType) (elements_add_eq k v m))\n        by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n      rewrite !fold_add;\n        eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey, empty_In.\n      rewrite XMap.fold_1; simpl.\n      f_equiv.\n      eapply XMap.remove_1; reflexivity.\n    Qed.\n\n    Corollary TrieBag_enumerateOK'''\n    : forall l st1 key' st' search_term,\n        (forall (k : X.t) (subtrie : Trie),\n           InA (PX.eqke (elt:=Trie)) (k, subtrie) l ->\n           TrieOK subtrie (st1 ++ [k]))\n        -> ( forall (k : X.t) (subtrie : Trie),\n               InA (PX.eqke (elt:=Trie)) (k, subtrie)\n                   l -> ~X.eq k key')\n        -> Permutation\n             (List.filter (fun a => negb (TrieBag_bfind_matcher (Some (st1 ++ key' :: st'), search_term) a))\n                          (flatten\n                             (List.map benumerate\n                                       (fold_left\n                                          (fun (a : list (BagType)) (p : key * Trie) =>\n                                             (Trie_enumerate (snd p)) ++ a) l [ ]))))\n             (flatten\n                (List.map benumerate\n                          (fold_left\n                             (fun (a : list (BagType)) (p : key * Trie) =>\n                                (Trie_enumerate (snd p)) ++ a) l [ ]))).\n    Proof.\n      intros.\n      remember (@nil BagType) as bags.\n      remember (@nil (key * BagType)) as bags'.\n      assert (forall (k0 : key) (bag0 : BagType),\n                List.In (k0, bag0) bags' ->\n                forall item : TItem,\n                  List.In item (benumerate bag0) -> Prefix (st1 ++ [k0]) (projection item)) by (rewrite Heqbags'; intuition).\n      generalize\n        (fun k bag =>\n           @TrieBag_enumerateOK\n             l st1 bags' k bag\n             H H1).\n      clear H1.\n      assert (bags = List.map (@snd _ _) bags') as H1\n          by (rewrite Heqbags', Heqbags; reflexivity);\n        rewrite H1; clear H1.\n      assert (forall (k : X.t) b,\n                InA (PX.eqke (elt:=BagType)) (k, b) bags' ->\n                ~X.eq k key')\n        by (intros;\n            rewrite Heqbags' in *; inversion H1).\n      generalize bags' H H0 H1; clear; induction l; simpl; intros.\n      - induction bags'; simpl; intros; eauto.\n        rewrite filter_app, IHbags'; eauto; f_equiv.\n        destruct a; simpl in *.\n        assert (~ X.eq k key') by\n            (intros; eapply H1; econstructor; eauto).\n        generalize (fun item => H2 k b (or_introl (refl_equal _)) item) H3;\n          clear.\n        induction (benumerate b); simpl; eauto; intros.\n        pose proof (H _ (or_introl (refl_equal _))).\n        rewrite <- IsPrefix_iff_Prefix in H0.\n        unfold TrieBag_bfind_matcher, IsPrefix in *; simpl in *.\n        case_eq (Prefix_dec F.eq_dec (projection a) (st1 ++ key' :: st')); eauto.\n        intros.\n        assert (Prefix (st1 ++ [k]) (st1 ++ key' :: st'))\n          by (etransitivity; eauto).\n        pose proof (Prefix_app_inv _ _ _ H2).\n        destruct H4; inversion H4; subst.\n        elimtype False; eapply H3; eauto.\n        simpl; intros; f_equiv.\n        generalize (fun item In_item => H item (or_intror In_item)).\n        generalize H3; clear; induction l; simpl; intros; eauto.\n        pose proof (H _ (or_introl (refl_equal _))).\n        destruct (Prefix_dec F.eq_dec (projection a) (st1 ++ key' :: st')); simpl in *; eauto.\n        intros.\n        assert (Prefix (st1 ++ [k]) (st1 ++ key' :: st'))\n          by (etransitivity; eauto).\n        apply Prefix_app_inv in H1.\n        destruct H1; simpl in H1; inversion H1; subst.\n        intuition.\n        try rewrite IHl; eauto.\n        intros; try eapply H2; eauto.\n        constructor 2; eauto.\n      - intros.\n        pose proof (IHl ((List.map (fun a' => (fst a, a')) (Trie_enumerate (snd a))) ++ bags')) as H'.\n        rewrite map_app, map_map, map_id in H'.\n        rewrite <- H' at 2; clear H'; intros.\n        rewrite !flatten_filter; eauto.\n        destruct a; eapply H; econstructor 2; eauto.\n        eapply H0; eauto.\n        apply InA_app in H3; intuition eauto.\n        assert (~X.eq k (fst a))\n          by (destruct a; intro; eapply H0; eauto; econstructor).\n        apply H3; revert H5; clear; induction (Trie_enumerate (snd a));\n        intros; inversion H5; subst; eauto.\n        destruct H0; simpl in *; eauto.\n        eapply H2; eauto.\n    Qed.\n\n    Lemma filter_negb_remove\n    : forall key m,\n        XMap.Equal (filter\n                      (fun (k : XMap.key) (e : Trie) =>\n                         negb (KeyBasedPartitioningFunction Trie key k e))\n                      m)\n                   (XMap.remove key m).\n    Proof.\n      unfold XMap.Equal; intros.\n      destruct (X.eq_dec key0 y).\n      - rewrite remove_eq_o; eauto.\n        rewrite <- e; unfold filter; clear y e.\n        destruct m; unfold XMap.fold; rewrite fold_1; simpl; eauto.\n        assert (XMap.find (elt:=Trie) key0 (XMap.empty Trie) = None).\n        { rewrite <- not_find_in_iff.\n          intro H; destruct H; simpl in *; eapply empty_1; eauto.\n        }\n        revert H.\n        remember (XMap.empty Trie); generalize t; clear Heqt.\n        induction (elements this); intros; simpl.\n        + eauto.\n        + eapply IHl.\n          case_eq (negb (KeyBasedPartitioningFunction Trie key0 (fst a) (snd a)));\n            intros; eauto.\n          rewrite add_neq_o; eauto.\n          intro; unfold KeyBasedPartitioningFunction in *.\n          case_eq (F.eq_dec (fst a) key0); intros; rewrite H2 in H0;\n          simpl in *; try congruence.\n      - rewrite remove_neq_o by eauto.\n        destruct m; unfold filter, XMap.fold; rewrite fold_1; simpl; eauto.\n        case_eq (XMap.find (elt:=Trie) y {| XMap.this := this; XMap.is_bst := is_bst |}).\n        + intros; apply find_2 in H.\n          pose (@elements_mapsto_iff _ (XMap.Bst is_bst)) as H2; simpl in H2;\n          unfold XMap.MapsTo in H2; simpl in H2; rewrite H2 in H;\n          unfold XMap.elements in H; simpl in H; clear H2.\n          assert (InA (XMap.eq_key_elt (elt:=Trie)) (y, t) (elements this) \\/\n                  InA (XMap.eq_key_elt (elt:=Trie)) (y, t) (XMap.elements (XMap.empty Trie)))\n            by eauto.\n          assert (forall key' v, XMap.MapsTo key' v (XMap.empty Trie) ->\n                                 ~ X.eq key' key0)\n            by (unfold not; intros; eapply XMap.empty_1; eauto).\n          assert (forall key' v, XMap.MapsTo key' v (XMap.empty Trie) ->\n                                 ~ InA X.eq key' (List.map fst (elements this)))\n            by (unfold not; intros; eapply XMap.empty_1; eauto).\n          assert (forall key' v, InA X.eq key' (List.map fst (elements this))\n                                 -> ~ XMap.MapsTo key' v (XMap.empty Trie))\n            by (unfold not; intros; eapply XMap.empty_1; eauto).\n          assert (NoDupA X.eq (List.map fst (XMap.elements (elt:=_) (XMap.Bst is_bst)))).\n          { pose proof (@XMap.elements_3w _ (XMap.Bst is_bst)).\n            unfold XMap.eq_key, PX.eqk in H4.\n            revert H4; clear; induction (XMap.elements (XMap.Bst is_bst)); intros;\n            constructor; eauto;\n            inversion H4; subst;\n            [ | apply IHl; eauto].\n            intro; apply H1; revert H; clear; induction l; intros; inversion H; subst.\n            constructor; eauto.\n            constructor 2; eauto.\n          }\n          unfold XMap.elements in H4; simpl in H4.\n          revert H1 H0 H2 H3 H4.\n          remember (XMap.empty Trie) as t'; generalize t'; clear Heqt' H.\n          induction (elements this); intros; simpl.\n          destruct t'0; apply find_1; eauto.\n          apply elements_mapsto_iff; simpl in H0; intuition.\n          inversion H.\n          eapply IHl; simpl in *; intuition.\n          * unfold KeyBasedPartitioningFunction in *.\n            destruct (X.eq_dec (fst a) key0); simpl in *; eauto; try congruence.\n            destruct a; simpl in *.\n            eapply XMap.add_3 in H0; eauto.\n          * unfold KeyBasedPartitioningFunction in *.\n            destruct (X.eq_dec (fst a) key0); simpl in *; eauto; try congruence.\n            eapply XMap.add_3 in H0; eauto.\n          * inversion H; subst.\n            destruct H5; destruct a; simpl in *; subst.\n            right; rewrite <- elements_mapsto_iff; simpl.\n            unfold KeyBasedPartitioningFunction in *.\n            destruct (X.eq_dec k key0); simpl in *; eauto; try congruence.\n            rewrite e in H0; symmetry in H0; intuition.\n            apply add_1; eauto.\n            eauto.\n          * right; rewrite <- elements_mapsto_iff; simpl.\n            unfold KeyBasedPartitioningFunction in *.\n            destruct (X.eq_dec (fst a) key0); simpl in *; eauto; try congruence.\n            rewrite <- elements_mapsto_iff in *; simpl; eauto.\n            rewrite <- elements_mapsto_iff in *; simpl; eauto.\n            apply add_2; eauto.\n          * unfold KeyBasedPartitioningFunction in *.\n            destruct (F.eq_dec (fst a) key0); simpl in *; eauto.\n            pose proof (proj1 (add_mapsto_iff _ _ _ _ _) H0); intuition; subst.\n            inversion H4; subst; eauto.\n            rewrite H6 in H9; eauto.\n            eapply H3; eauto.\n          * unfold KeyBasedPartitioningFunction in *.\n            destruct (F.eq_dec (fst a) key0); simpl in *; eauto.\n            pose proof (proj1 (add_mapsto_iff _ _ _ _ _) H0); intuition; subst.\n            inversion H4; subst; eauto.\n            rewrite H6 in H9; eauto.\n            eapply H3; eauto.\n          *  unfold KeyBasedPartitioningFunction in *.\n             destruct (F.eq_dec (fst a) key0); simpl in *; eauto.\n             pose proof (proj1 (add_mapsto_iff _ _ _ _ _) H5); intuition; subst.\n             inversion H4; subst; eauto.\n             rewrite H6 in H9; eauto.\n             eapply H3; eauto.\n          * unfold KeyBasedPartitioningFunction in *.\n            destruct (F.eq_dec (fst a) key0); simpl in *; eauto.\n            pose proof (proj1 (add_mapsto_iff _ _ _ _ _) H5); intuition; subst.\n            inversion H4; subst; eauto.\n            rewrite H6 in H9; eauto.\n            eapply H3; eauto.\n          * inversion H4; eauto.\n          * inversion H4; eauto.\n        + intros; apply not_find_in_iff in H.\n          assert (forall v, ~ InA (XMap.eq_key_elt (elt:=Trie)) (y, v) (XMap.elements (XMap.Bst is_bst)) /\\\n                            ~ InA (XMap.eq_key_elt (elt:=Trie)) (y, v) (XMap.elements (XMap.empty Trie))).\n          { unfold not in*; split; intros.\n            rewrite <- elements_mapsto_iff in H0.\n            apply H; eexists v; simpl in *; apply H0.\n            rewrite <- elements_mapsto_iff in H0.\n            eapply XMap.empty_1; eauto.\n          }\n          assert (forall key' v, XMap.MapsTo key' v (XMap.empty Trie) ->\n                                 ~ X.eq key' key0)\n            by (unfold not; intros; eapply XMap.empty_1; eauto).\n          assert (forall key' v, XMap.MapsTo key' v (XMap.empty Trie) ->\n                                 ~ InA X.eq key' (List.map fst (elements this)))\n            by (unfold not; intros; eapply XMap.empty_1; eauto).\n          assert (forall key' v, InA X.eq key' (List.map fst (elements this))\n                                 -> ~ XMap.MapsTo key' v (XMap.empty Trie))\n            by (unfold not; intros; eapply XMap.empty_1; eauto).\n          assert (NoDupA X.eq (List.map fst (XMap.elements (elt:=_) (XMap.Bst is_bst)))).\n          { pose proof (@XMap.elements_3w _ (XMap.Bst is_bst)).\n            unfold XMap.eq_key, PX.eqk in H4.\n            revert H4; clear; induction (XMap.elements (XMap.Bst is_bst)); intros;\n            constructor; eauto;\n            inversion H4; subst;\n            [ | apply IHl; eauto].\n            intro; apply H1; revert H; clear; induction l; intros; inversion H; subst.\n            constructor; eauto.\n            constructor 2; eauto.\n          }\n          unfold XMap.elements in H4; simpl in H4, H0.\n          unfold XMap.elements at 1 in H0; simpl in H0.\n          rewrite <- not_find_in_iff.\n          revert H1 H0 H2 H3 H4.\n          remember (XMap.empty Trie) as t'; generalize t'; clear Heqt' H.\n          induction (elements this); intros; simpl.\n          unfold not; intros; destruct H as [x H].\n          apply (proj2 (H0 x)).\n          rewrite <- elements_mapsto_iff; eassumption.\n          eapply IHl; simpl in *; intuition.\n          * unfold KeyBasedPartitioningFunction in *.\n            destruct (X.eq_dec (fst a) key0); simpl in *; eauto; try congruence.\n            destruct a; simpl in *.\n            eapply XMap.add_3 in H; eauto.\n          * apply (proj1 (H0 v)); eauto.\n          * unfold KeyBasedPartitioningFunction in *.\n            destruct (X.eq_dec (fst a) key0); simpl in *; eauto; try congruence.\n            apply (proj2 (H0 v)); eauto.\n            rewrite <- elements_mapsto_iff in H.\n            pose proof (proj1 (add_mapsto_iff _ _ _ _ _) H); intuition; subst.\n            apply (proj1 (H0 (snd a))); econstructor.\n            constructor; eauto.\n            apply (proj2 (H0 v)); rewrite <- elements_mapsto_iff; eauto.\n          * unfold KeyBasedPartitioningFunction in *.\n            destruct (X.eq_dec (fst a) key0); simpl in *; eauto; try congruence.\n            pose proof (proj1 (add_mapsto_iff _ _ _ _ _) H); intuition; subst.\n            inversion H4; subst; eauto.\n            rewrite H6 in H9; eauto.\n            eapply H2; eauto.\n          * unfold KeyBasedPartitioningFunction in *.\n            destruct (F.eq_dec (fst a) key0); simpl in *; eauto.\n            pose proof (proj1 (add_mapsto_iff _ _ _ _ _) H5); intuition; subst.\n            inversion H4; subst; eauto.\n            rewrite H6 in H9; eauto.\n            eapply H3; eauto.\n          * inversion H4; eauto.\n    Qed.\n\n    Hint Resolve filter_negb_Prefix filter_Prefix Prefix_app.\n\n    Lemma TrieOK_subtrie_remove\n    : forall b m l key' k subtrie,\n        TrieOK (Node b m) l\n        -> bst m\n        -> InA (PX.eqke (elt:=Trie)) (k, subtrie)\n            (elements\n               (remove key' m)) ->\n        TrieOK subtrie (l ++ [k]).\n    Proof.\n      intros.\n      inversion H; subst; intros; eapply H8.\n      assert (bst (remove key'\n                          (XMap.this\n                             {| XMap.this := m; XMap.is_bst := H0 |}))).\n      apply remove_bst; eauto.\n      rewrite <- (@elements_mapsto_iff _ (XMap.Bst H2)) in H1.\n      simpl in H1; unfold XMap.MapsTo in H1; simpl in H1.\n      eapply remove_3; eauto.\n    Qed.\n\n    Lemma TrieOK_subtrie_filter\n    : forall b m l bst_m f k subtrie,\n        Proper (X.eq ==> eq ==> eq) f\n        -> TrieOK (Node b m) l\n        -> InA (PX.eqke (elt:=Trie)) (k, subtrie)\n            (XMap.elements\n               (filter f\n                       {| XMap.this := m; XMap.is_bst := bst_m |})) ->\n        TrieOK subtrie (l ++ [k]).\n    Proof.\n      intros.\n      inversion H0; subst; intros; eapply H8.\n      rewrite <- elements_mapsto_iff in H1.\n      rewrite filter_iff in H1; intuition.\n    Qed.\n\n    Hint Resolve TrieOK_subtrie_remove TrieOK_subtrie_filter.\n\n    Lemma TrieBag_BagFindCorrect :\n      BagFindCorrect TrieBagRepInv TrieBag_bfind TrieBag_bfind_matcher TrieBag_benumerate.\n    Proof.\n      intros container search_term.\n      destruct search_term as [ [st |] search_term].\n      { unfold TrieBag_bfind.\n        rewrite <- (app_nil_l st) at 1.\n        unfold TrieBagRepInv; remember [] as l; clear Heql; revert l.\n        eapply Trie_find_ind; intros; subst; simpl.\n        - rewrite !app_nil_r, <- bfind_correct by eauto.\n          destruct trie; simpl.\n          unfold TrieBag_benumerate; simpl.\n          rewrite !XMapfold_eq, !fold_1 by eauto.\n          rewrite Permutation_benumerate_fold_left, flatten_app; simpl;\n          rewrite filter_app, app_nil_r; simpl.\n          rewrite <- app_nil_r; f_equiv.\n          + rewrite filter_Prefix; eauto; reflexivity.\n          + inversion H; subst.\n            eapply TrieBag_enumerateOK'; intros.\n            eapply H6.\n            eapply (@XMap.elements_2 _ (XMap.Bst (SubTrieMapBST' H))); eauto.\n        - rewrite <- H; eauto.\n          destruct trie; simpl in *.\n          unfold TrieBag_benumerate; simpl.\n          rewrite !XMapfold_eq, !fold_1 by eauto.\n          rewrite Permutation_benumerate_fold_left, flatten_app; simpl;\n          rewrite filter_app, app_nil_r; simpl; f_equiv.\n          rewrite <- bfind_correct by eauto.\n          + inversion H0; subst.\n            rewrite filter_Prefix; eauto.\n          + rewrite <- (fun H => @fold_1 _ m H (list BagType) [ ] (fun k trie a => Trie_enumerate trie ++ a)) by eauto.\n            rewrite Permutation_KeyBasedPartition with (key0 := key0)\n                                                         (bst_m := SubTrieMapBST H0).\n            simpl.\n            apply find_2 in e0.\n            pose proof (KeyBasedPartition_fst_singleton key0 subtrie (XMap.Bst (SubTrieMapBST H0)) e0) as singleton.\n            rewrite (fold_Equal_simpl (eqA := @Permutation BagType) singleton)\n              by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n            rewrite !fold_add;\n              eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey, empty_In.\n            rewrite map_app, flatten_app, filter_app, <- app_nil_r.\n            f_equiv.\n            rewrite <- app_assoc; simpl; eauto.\n            rewrite fold_empty, flatten_filter,map_map.\n\n            rewrite (fold_Equal_simpl (eqA := @Permutation BagType) (filter_negb_remove key0 _))\n              by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n            eapply filter_remove_key; eauto.\n        - rewrite !app_nil_r, <- bfind_correct by eauto.\n          destruct trie; simpl.\n          unfold TrieBag_benumerate; simpl.\n          rewrite !XMapfold_eq, !fold_1 by eauto.\n          rewrite Permutation_benumerate_fold_left, flatten_app; simpl;\n          rewrite filter_app, app_nil_r; simpl.\n          rewrite <- app_nil_r; f_equiv.\n          + rewrite filter_Prefix; eauto.\n          + rewrite <- (fun H => @fold_1 _ m H (list BagType) [ ] (fun k trie a => Trie_enumerate trie ++ a)) by eauto.\n            rewrite Permutation_KeyBasedPartition with (key0 := key0)\n                                                         (bst_m := SubTrieMapBST' H).\n            simpl in *.\n            rewrite <- (@not_find_in_iff _ (XMap.Bst (SubTrieMapBST' H)) key0) in e0.\n            pose proof (KeyBasedPartition_fst_singleton_None key0 (XMap.Bst (SubTrieMapBST H)) e0) as singleton.\n            rewrite (fold_Equal_simpl (eqA := @Permutation BagType) singleton)\n              by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n            rewrite fold_empty, flatten_filter, map_map.\n            rewrite (fold_Equal_simpl (eqA := @Permutation BagType) (filter_negb_remove key0 _))\n              by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n            eapply filter_remove_key; eauto.\n      }\n      { simpl; unfold TrieBag_bfind_matcher; simpl.\n        intros.\n        generalize (Trie_enumerate_RepInv containerCorrect).\n        unfold TrieBag_benumerate.\n        induction (Trie_enumerate container); simpl.\n        - eauto.\n        - intros; rewrite <- bfind_correct by eauto.\n          rewrite !filter_app; f_equiv; eauto.\n      }\n    Qed.\n\n    Corollary TrieBag_enumerateOK''\n      : forall l st1 search_term,\n        (forall (k : X.t) (subtrie : Trie),\n            InA (PX.eqke (elt:=Trie)) (k, subtrie) l ->\n            TrieOK subtrie (st1 ++ [k]))\n        -> Permutation\n             (List.filter (fun a => negb (TrieBag_bfind_matcher (Some st1, search_term) a))\n                          (flatten\n                             (List.map benumerate\n                                       (fold_left\n                                          (fun (a : list (BagType)) (p : key * Trie) =>\n                                             (Trie_enumerate (snd p)) ++ a) l [ ]))))\n             (flatten\n                (List.map benumerate\n                          (fold_left\n                             (fun (a : list (BagType)) (p : key * Trie) =>\n                                (Trie_enumerate (snd p)) ++ a) l [ ]))).\n    Proof.\n      intros; generalize (@TrieBag_enumerateOK' l st1 search_term H); clear.\n      induction (flatten\n                   (List.map benumerate\n                             (fold_left\n                                (fun (a : list (BagType)) (p : key * Trie) =>\n                                   (Trie_enumerate (snd p)) ++ a) l [ ])));\n        simpl; eauto.\n      find_if_inside; intros; simpl.\n      symmetry in H; apply Permutation_nil in H; discriminate.\n      eauto.\n    Qed.\n\n    Lemma TrieOK_distinct_subtries :\n      forall b m key' l k subtrie bst_m\n             (OK : TrieOK (Node b m) l),\n        InA (PX.eqke (elt:=Trie)) (k, subtrie)\n            (elements\n               (XMap.this\n                  (XMap.remove (elt:=Trie) key'\n                               {|\n                                 XMap.this := m;\n                                 XMap.is_bst := bst_m  |}))) ->\n        ~ X.eq k key'.\n    Proof.\n      simpl; intros.\n      assert (bst (remove key' m)) by eauto using remove_bst.\n      rewrite <- (@elements_mapsto_iff _ (XMap.Bst (H0))) in H;\n        simpl in H0.\n      unfold not; intros.\n      symmetry in H1; revert H1.\n      pose proof (@remove_mapsto_iff  _ (XMap.Bst (bst_m))).\n      eapply H1; simpl; eauto.\n    Qed.\n\n    Lemma TrieOK_distinct_subtries' :\n      forall b m key' l k subtrie bst_m\n             (OK : TrieOK (Node b m) l),\n        InA (PX.eqke (elt:=Trie)) (k, subtrie)\n            (elements\n               (XMap.this\n                  (filter\n                     (fun (k0 : XMap.key) (e : Trie) =>\n                        negb (KeyBasedPartitioningFunction Trie key' k0 e))\n                     {|\n                       XMap.this := m;\n                       XMap.is_bst := bst_m |}))) ->\n        ~ X.eq k key'.\n    Proof.\n      intros * OK H2.\n      assert (bst ((XMap.this\n                              (filter\n                                 (fun (k0 : XMap.key) (e : Trie) =>\n                                    negb (KeyBasedPartitioningFunction Trie key' k0 e))\n                                 {|\n                                   XMap.this := m;\n                                   XMap.is_bst := bst_m |})))) by exact (XMap.is_bst _).\n      intros; rewrite <- (@elements_mapsto_iff _ (XMap.Bst H) k subtrie) in H2.\n      apply (@filter_iff _ (fun (k0 : XMap.key) (e : Trie) =>\n                              negb\n                                (KeyBasedPartitioningFunction Trie key' k0 e))) in H2.\n      intuition.\n      unfold KeyBasedPartitioningFunction in *.\n      find_if_inside; simpl in *; try congruence.\n      unfold Proper, respectful; intros; subst.\n      unfold KeyBasedPartitioningFunction; repeat find_if_inside; eauto.\n      rewrite <- e in n; intuition.\n    Qed.\n\n    Lemma Proper_negb_KeyBasedPartitioningFunction\n    : forall key',\n        Proper (X.eq ==> eq ==> eq)\n               (fun (k0 : XMap.key) (e : Trie) =>\n                  negb (KeyBasedPartitioningFunction Trie key' k0 e)).\n    Proof.\n      unfold Proper, respectful, KeyBasedPartitioningFunction; intros.\n      repeat find_if_inside; subst; simpl; eauto.\n      rewrite H in n; intuition.\n    Qed.\n\n    Instance Proper_Trie_enumerate_app\n      : Proper\n          (X.eq ==> eq ==> Permutation (A:=BagType) ==> Permutation (A:=BagType))\n          (fun (_ : X.t) (tries : Trie) (bags : list BagType) =>\n             Trie_enumerate tries ++ bags).\n    Proof.\n      unfold Proper, respectful, KeyBasedPartitioningFunction; intros.\n      subst; rewrite H1.\n      reflexivity.\n    Qed.\n\n    Lemma transpose_neqkey_Trie_enumerate_app\n      : transpose_neqkey (Permutation (A:=BagType))\n                         (fun (_ : X.t) (tries : Trie) (bags : list BagType) =>\n                            Trie_enumerate tries ++ bags).\n    Proof.\n      unfold transpose_neqkey; intros.\n      rewrite !app_assoc; f_equiv.\n      apply Permutation_app_swap.\n    Qed.\n\n    Lemma TrieBag_BagDeleteCorrect :\n      BagDeleteCorrect TrieBagRepInv TrieBag_bfind TrieBag_bfind_matcher\n                       TrieBag_benumerate TrieBag_bdelete.\n    Proof.\n      intros container search_term.\n      destruct search_term as [ [st | ] search_term].\n      { unfold TrieBag_bdelete.\n        split.\n        {\n          rewrite <- (app_nil_l st) at 2.\n          revert containerCorrect.\n          unfold TrieBagRepInv; remember [] as l; clear Heql; revert l.\n          eapply Trie_delete_ind; intros; subst; simpl.\n          - destruct (bdelete_correct (TrieNode trie) search_term0); eauto.\n            destruct trie; simpl.\n            unfold TrieBag_benumerate; simpl.\n            rewrite !XMapfold_eq, !fold_1 by eauto.\n            rewrite e0 in H.\n            rewrite partition_filter_neq.\n            rewrite Permutation_benumerate_fold_left, flatten_app; simpl.\n            rewrite (Permutation_benumerate_fold_left _ [b]), flatten_app; simpl.\n            rewrite filter_app.\n            rewrite H, partition_filter_neq, !app_nil_r; simpl.\n            f_equiv.\n            + eapply filter_negb_Prefix; eauto; reflexivity.\n            + inversion containerCorrect; subst.\n              rewrite <- TrieBag_enumerateOK'' at 1.\n              unfold TrieBag_bfind_matcher, IsPrefix; reflexivity.\n              intros; eapply H7.\n              eapply (@XMap.elements_2 _ (XMap.Bst H4)); eauto.\n          - rewrite e2 in H; simpl in *.\n            destruct trie; simpl in *.\n            unfold TrieBag_benumerate; simpl.\n            rewrite !XMapfold_eq, !fold_1 by eauto.\n            rewrite partition_filter_neq.\n            rewrite Permutation_benumerate_fold_left, flatten_app; simpl.\n            rewrite (Permutation_benumerate_fold_left _ [b]), flatten_app; simpl.\n            rewrite !filter_app.\n            rewrite app_nil_r, <- app_assoc.\n            f_equiv.\n            + replace (bag') with (snd  (bdelete b search_term0))\n                by (rewrite e0; eauto).\n              destruct (bdelete_correct b search_term0); eauto.\n              rewrite H0.\n              rewrite partition_filter_neq.\n              eapply filter_negb_Prefix; eauto; reflexivity.\n            + simpl.\n              rewrite <- (fun H => @fold_1 _ m H (list BagType) [ ] (fun k trie a => Trie_enumerate trie ++ a)) by eauto.\n              rewrite Permutation_KeyBasedPartition with (key0 := key0)\n                                                           (bst_m := SubTrieMapBST containerCorrect).\n              simpl in *.\n              apply find_2 in e1.\n              pose proof (KeyBasedPartition_fst_singleton key0 subtrie (XMap.Bst (SubTrieMapBST containerCorrect)) e1) as singleton.\n              rewrite (fold_Equal_simpl (eqA := @Permutation BagType) singleton)\n                by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n              rewrite !fold_add;\n                eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey, empty_In.\n              rewrite flatten_filter.\n              rewrite !map_app, fold_empty, !map_map.\n              rewrite flatten_app.\n              rewrite (Permutation_benumerate_add key0 bag'' (XMap.Bst (SubTrieMapBST containerCorrect))).\n              rewrite map_app, flatten_app.\n              f_equiv.\n              * rewrite (H (l ++ [key0])), partition_filter_neq.\n                unfold TrieBag_benumerate; rewrite flatten_filter, map_map.\n                unfold TrieBag_bfind_matcher; rewrite <- app_assoc.\n                repeat f_equiv.\n                inversion containerCorrect; subst; eauto.\n              * pose (@XMap.fold_1 _ (XMap.remove key0 (XMap.Bst (SubTrieMapBST containerCorrect)))\n                                   _ nil\n                                   (fun (_ : key) (trie : Trie) (a : list BagType) =>\n                                      Trie_enumerate trie ++ a)).\n                simpl in e;  unfold XMap.key, key in *; rewrite <- e.\n                rewrite (fold_Equal_simpl (eqA := @Permutation BagType) (filter_negb_remove key0 _))\n                  by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n                unfold XMap.fold.\n                rewrite !fold_1.\n                rewrite <- TrieBag_enumerateOK'''.\n                rewrite flatten_filter.\n                rewrite map_map.\n                unfold TrieBag_bfind_matcher, IsPrefix; simpl.\n                f_equiv.\n                intros; eapply TrieOK_subtrie_remove; simpl in *;\n                eauto using Proper_negb_KeyBasedPartitioningFunction.\n                intros; eapply TrieOK_distinct_subtries; eauto.\n                exact (XMap.is_bst _).\n          - destruct trie; simpl in *.\n            unfold TrieBag_benumerate; simpl.\n            rewrite !XMapfold_eq, !fold_1 by eauto.\n            rewrite partition_filter_neq.\n            rewrite Permutation_benumerate_fold_left, flatten_app; simpl.\n            rewrite (Permutation_benumerate_fold_left _ [b]), flatten_app; simpl.\n            rewrite !filter_app.\n            rewrite app_nil_r, <- app_assoc.\n            f_equiv.\n            + replace (bag') with (snd  (bdelete b search_term0))\n                by (rewrite e0; eauto).\n              destruct (bdelete_correct b search_term0); eauto.\n              rewrite H.\n              rewrite partition_filter_neq.\n              eapply filter_negb_Prefix; eauto; reflexivity.\n            + simpl.\n              rewrite <- (fun H => @fold_1 _ m H (list BagType) [ ] (fun k trie a => Trie_enumerate trie ++ a)) by eauto.\n              rewrite Permutation_KeyBasedPartition with (key0 := key0)\n                                                           (bst_m := SubTrieMapBST containerCorrect).\n              simpl.\n              rewrite <- (@not_find_in_iff _ (XMap.Bst (SubTrieMapBST' containerCorrect)) key0) in e1.\n              pose proof (KeyBasedPartition_fst_singleton_None key0 (XMap.Bst (SubTrieMapBST containerCorrect)) e1) as singleton.\n              rewrite (fold_Equal_simpl (eqA := @Permutation BagType) singleton)\n                by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n              rewrite !fold_empty;\n                eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey, empty_In.\n              unfold XMap.fold; rewrite !fold_1.\n              rewrite <- TrieBag_enumerateOK''' at 1.\n              unfold TrieBag_bfind_matcher, IsPrefix.\n              f_equiv.\n              intros; eapply TrieOK_subtrie_filter; simpl in *;\n              eauto using Proper_negb_KeyBasedPartitioningFunction.\n              intros; eapply TrieOK_distinct_subtries'; eauto.\n              exact (XMap.is_bst _).\n        }\n        { rewrite <- (app_nil_l st) at 2.\n          revert containerCorrect.\n          unfold TrieBagRepInv; remember [] as l; clear Heql; revert l.\n          eapply Trie_delete_ind; intros; subst; simpl.\n          - destruct (bdelete_correct (TrieNode trie) search_term0); eauto.\n            destruct trie; simpl.\n            unfold TrieBag_benumerate; simpl.\n            rewrite !XMapfold_eq, !fold_1 by eauto.\n            rewrite e0 in H.\n            rewrite partition_filter_eq.\n            rewrite Permutation_benumerate_fold_left, flatten_app; simpl.\n            rewrite filter_app.\n            replace deletedItems with (fst (bdelete b search_term0)) by\n                (simpl in *; rewrite e0; eauto).\n            destruct (bdelete_correct b search_term0); eauto.\n            rewrite H2, partition_filter_eq; simpl.\n            rewrite <- app_nil_r at 1.\n            f_equiv.\n            + inversion containerCorrect; subst.\n              revert H7; clear.\n              induction (benumerate b); simpl; eauto.\n              unfold TrieBag_bfind_matcher, IsPrefix.\n              intros; case_eq (Prefix_dec F.eq_dec (projection a) l); simpl; intros.\n              find_if_inside; simpl; rewrite IHl0; eauto.\n              rewrite app_nil_r, H; simpl; eauto.\n              rewrite andb_false_r; eauto.\n              find_if_inside.\n              simpl; rewrite app_nil_r, H; simpl.\n              assert (Prefix (projection a) l)\n                by (eexists nil; rewrite app_nil_r; eauto).\n              rewrite <- IsPrefix_iff_Prefix in H0; simpl in *; rewrite H in H0; congruence.\n              assert (Prefix (projection a) l)\n                by (eexists nil; rewrite app_nil_r; eauto).\n              rewrite <- IsPrefix_iff_Prefix in H0; simpl in *; rewrite H in H0; congruence.\n            + inversion containerCorrect; subst.\n              rewrite TrieBag_enumerateOK' at 1; eauto.\n              rewrite app_nil_r.\n              intros; eapply H9.\n              eapply (@XMap.elements_2 _ (XMap.Bst H6)); eauto.\n          - rewrite e2 in H; simpl in *.\n            destruct trie; simpl in *.\n            unfold TrieBag_benumerate; simpl.\n            rewrite !XMapfold_eq, !fold_1 by eauto.\n            rewrite partition_filter_eq.\n            rewrite Permutation_benumerate_fold_left, flatten_app; simpl.\n            rewrite !filter_app; simpl.\n            f_equiv.\n            + replace deletedItems with (fst (bdelete b search_term0))\n                by (rewrite e0; eauto).\n              destruct (bdelete_correct b search_term0); eauto.\n              rewrite H1, partition_filter_eq, app_nil_r.\n              inversion containerCorrect; subst.\n              intros; eapply filter_Prefix; eauto; reflexivity.\n            + rewrite (H (l ++ [key0])); simpl; eauto.\n              rewrite partition_filter_eq.\n              rewrite <- (fun H => @fold_1 _ m H (list BagType) [ ] (fun k trie a => Trie_enumerate trie ++ a)) by eauto.\n              rewrite Permutation_KeyBasedPartition with (key0 := key0)\n                                                           (bst_m := SubTrieMapBST containerCorrect).\n              simpl.\n              apply find_2 in e1.\n              pose proof (KeyBasedPartition_fst_singleton key0 subtrie (XMap.Bst (SubTrieMapBST containerCorrect)) e1) as singleton.\n              rewrite (fold_Equal_simpl (eqA := @Permutation BagType) singleton)\n                by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n              rewrite !fold_add;\n                eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey, empty_In.\n              rewrite flatten_filter.\n              rewrite !map_app, fold_empty, !map_map.\n              rewrite flatten_app.\n              rewrite <- app_nil_r at 1.\n              f_equiv.\n              * unfold TrieBag_benumerate; rewrite flatten_filter, map_map, <- app_assoc; reflexivity.\n              * rewrite <- filter_remove_key; eauto.\n                rewrite (fold_Equal_simpl (eqA := @Permutation BagType) (filter_negb_remove key0 _))\n                  by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n                eauto.\n                simpl; eauto.\n          - destruct trie; simpl in *.\n            unfold TrieBag_benumerate; simpl.\n            rewrite !XMapfold_eq, !fold_1 by eauto.\n            rewrite partition_filter_eq.\n            rewrite Permutation_benumerate_fold_left, flatten_app; simpl.\n            rewrite !filter_app.\n            rewrite <- app_nil_r at 1.\n            f_equiv.\n            + replace deletedItems with (fst (bdelete b search_term0))\n                by (rewrite e0; eauto).\n              destruct (bdelete_correct b search_term0); eauto.\n              rewrite H0, partition_filter_eq, app_nil_r.\n              eapply filter_Prefix; eauto.\n            + simpl.\n              rewrite <- (fun H => @fold_1 _ m H (list BagType) [ ] (fun k trie a => Trie_enumerate trie ++ a)) by eauto.\n              rewrite Permutation_KeyBasedPartition with (key0 := key0)\n                                                           (bst_m := SubTrieMapBST containerCorrect).\n              rewrite <- (@not_find_in_iff _ (XMap.Bst (SubTrieMapBST' containerCorrect)) key0) in e1.\n              pose proof (KeyBasedPartition_fst_singleton_None key0 (XMap.Bst (SubTrieMapBST containerCorrect)) e1) as singleton.\n              rewrite (fold_Equal_simpl (eqA := @Permutation BagType) singleton)\n                by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n              rewrite !fold_empty;\n                eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey, empty_In.\n              simpl.\n              rewrite (fold_Equal_simpl (eqA := @Permutation BagType) (filter_negb_remove key0 _))\n                by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n              rewrite <- filter_remove_key, flatten_filter, map_map; eauto.\n        }\n      }\n      { unfold TrieBag_bfind_matcher; simpl.\n        unfold TrieBagRepInv.\n        pattern container, (@nil X.t) ; apply Trie_ind'; simpl; intros.\n        unfold TrieBag_benumerate; simpl.\n        intros; inversion containerCorrect; subst.\n        case_eq (bdelete b search_term); simpl; intros.\n        destruct (bdelete_correct b search_term); eauto.\n        rewrite H0 in H1, H5; simpl in H1, H5.\n        rewrite (Permute_XMapfold_cons m [b]), Permute_XMapfold_cons with (l := [b0]).\n        rewrite !map_app, !flatten_app, !partition_app; simpl.\n        rewrite !app_nil_r.\n        split.\n        - rewrite H1; f_equiv.\n          rewrite !XMapfold_eq.\n          setoid_rewrite (fold_pair (XMap.Bst H3)); simpl.\n          rewrite fold_spec_right.\n          pose fold_spec_right as e; unfold XMap.fold in e; rewrite (e _ (XMap.Bst H3));\n          clear e.\n          assert (forall k trie,\n                     InA (@XMap.eq_key_elt _)\n                         (k, trie)\n                         (rev\n                            (XMap.elements (elt:=Trie)\n                                           {| XMap.this := m; XMap.is_bst := H3 |}))\n                     -> Permutation (TrieBag_benumerate (snd (Trie_delete' trie search_term)))\n                                    (snd\n                                       (List.partition\n                                          (fun item : TItem => bfind_matcher search_term item)\n                                          (TrieBag_benumerate trie)))).\n          { intros; eapply H; eauto using elements_mapsto_iff.\n            pose elements_mapsto_iff as e; unfold XMap.MapsTo in e; rewrite (e _ (XMap.Bst H3));\n            clear e.\n            rewrite <- InA_rev; eauto with typeclass_instances.\n            eapply H6.\n            eapply (@elements_mapsto_iff _ (XMap.Bst H3)).\n            eapply InA_rev; eauto with typeclass_instances.\n          }\n          generalize H7; clear.\n          assert (NoDupA (@XMap.eq_key _)\n                         (rev\n                            (XMap.elements (elt:=Trie) {| XMap.this := m; XMap.is_bst := H3 |})))\n          by (apply NoDupA_rev; eauto with typeclass_instances;\n              eapply XMap.elements_3w).\n          revert H.\n          induction (rev\n                       (XMap.elements (elt:=Trie) {| XMap.this := m; XMap.is_bst := H3 |}));\n            simpl; intros; eauto.\n          unfold uncurry.\n          pose fold_add as e; unfold XMap.fold, XMap.add in e; simpl in e.\n          rewrite e; clear e.\n          rewrite !map_app, !flatten_app, !partition_app; simpl.\n          unfold TrieBag_benumerate in H7.\n          rewrite H7 with (k := fst a); f_equiv; eauto.\n          rewrite <- IHl; eauto.\n          inversion H; eauto.\n          intros; eapply H7; simpl; econstructor 2; eauto.\n          econstructor; destruct a; simpl; reflexivity.\n          eauto with typeclass_instances.\n          eauto with typeclass_instances.\n          eauto using transpose_neqkey_Trie_enumerate_app.\n          inversion H; subst; intro; apply H2.\n          unfold XMap.In, In0 in H0.\n          revert H0; clear; induction l; simpl.\n          + intros; destruct H0; inversion H.\n          + intros; destruct H0.\n            pose add_mapsto_iff as e; unfold XMap.add, XMap.MapsTo in e; simpl in e;\n            rewrite e in H; clear e.\n            intuition.\n            * econstructor 1; symmetry; apply H.\n            * eauto.\n        - rewrite H5, Permutation_app_swap; f_equiv.\n          rewrite !XMapfold_eq.\n          setoid_rewrite (fold_pair (XMap.Bst H3)); simpl.\n          rewrite fold_spec_right.\n          pose fold_spec_right as e; unfold XMap.fold in e; rewrite (e _ (XMap.Bst H3));\n          clear e.\n          assert (forall k trie,\n                     InA (@XMap.eq_key_elt _)\n                         (k, trie)\n                         (rev\n                            (XMap.elements (elt:=Trie)\n                                           {| XMap.this := m; XMap.is_bst := H3 |}))\n                     -> Permutation ((fst (Trie_delete' trie search_term)))\n                                    (fst\n                                       (List.partition\n                                          (fun item : TItem => bfind_matcher search_term item)\n                                          (TrieBag_benumerate trie)))).\n          { intros; eapply H; eauto using elements_mapsto_iff.\n            pose elements_mapsto_iff as e; unfold XMap.MapsTo in e; rewrite (e _ (XMap.Bst H3));\n            clear e.\n            rewrite <- InA_rev; eauto with typeclass_instances.\n            eapply H6.\n            eapply (@elements_mapsto_iff _ (XMap.Bst H3)).\n            eapply InA_rev; eauto with typeclass_instances.\n          }\n          generalize H7; clear.\n          assert (NoDupA (@XMap.eq_key _)\n                         (rev\n                            (XMap.elements (elt:=Trie) {| XMap.this := m; XMap.is_bst := H3 |})))\n          by (apply NoDupA_rev; eauto with typeclass_instances;\n              eapply XMap.elements_3w).\n          revert H.\n          induction (rev\n                       (XMap.elements (elt:=Trie) {| XMap.this := m; XMap.is_bst := H3 |}));\n            simpl; intros; eauto.\n          unfold uncurry.\n          rewrite !map_app, !flatten_app, !partition_app; simpl.\n          unfold TrieBag_benumerate in H7.\n          rewrite H7 with (k := fst a); f_equiv; eauto.\n          rewrite <- IHl; eauto.\n          inversion H; eauto.\n          econstructor; destruct a; simpl; reflexivity.\n      }\n    Qed.\n\n    Lemma TrieBag_BagUpdateCorrect :\n      BagUpdateCorrect TrieBagRepInv TrieBag_ValidUpdate\n                       TrieBag_bfind TrieBag_bfind_matcher\n                       TrieBag_benumerate bupdate_transform TrieBag_bupdate.\n    Proof.\n      intros container search_term.\n      destruct search_term as [ [st | ] search_term].\n      {\n        unfold TrieBag_bupdate.\n        split.\n        {\n          rewrite <- (app_nil_l st); rewrite app_nil_l at 1.\n          revert containerCorrect.\n          unfold TrieBagRepInv; remember [] as l; clear Heql; revert l valid_update.\n          eapply Trie_update_ind; intros; subst; simpl.\n          - destruct (bupdate_correct (TrieNode trie) search_term0 updateTerm); eauto.\n            destruct trie; simpl.\n            rewrite partition_filter_neq, partition_filter_eq.\n            unfold TrieBag_benumerate; simpl.\n            rewrite !XMapfold_eq, !fold_1 by eauto.\n            rewrite e0 in H, H0; simpl in *.\n            rewrite Permutation_benumerate_fold_left, flatten_app; simpl.\n            rewrite (Permutation_benumerate_fold_left _ [b]), flatten_app; simpl.\n            rewrite H, partition_filter_neq,\n            partition_filter_eq, !app_nil_r, !filter_app, <- !app_assoc ; simpl.\n            f_equiv.\n            + eapply filter_negb_Prefix; eauto; reflexivity.\n            + symmetry.\n              rewrite map_app, Permutation_app_swap, <- app_assoc; f_equiv.\n              f_equiv.\n              * symmetry; eapply filter_Prefix; eauto; reflexivity.\n              * inversion containerCorrect; subst.\n                rewrite TrieBag_enumerateOK'; simpl.\n                rewrite <- TrieBag_enumerateOK'' at 2.\n                unfold TrieBag_bfind_matcher, IsPrefix; reflexivity.\n                intros; eapply H7; eapply (@elements_mapsto_iff _ (XMap.Bst H4)); eauto.\n                intros; eapply H7; eapply (@elements_mapsto_iff _ (XMap.Bst H4)); eauto.\n          - rewrite e2 in H; simpl in *.\n            destruct trie; simpl in *.\n            unfold TrieBag_benumerate; simpl.\n            rewrite !XMapfold_eq, !fold_1 by eauto.\n            rewrite partition_filter_neq, partition_filter_eq.\n            rewrite Permutation_benumerate_fold_left, flatten_app; simpl.\n            rewrite (Permutation_benumerate_fold_left _ [b]), flatten_app; simpl.\n            rewrite !filter_app.\n            rewrite app_nil_r, <- !app_assoc; simpl.\n            rewrite map_app.\n            replace (bag') with (snd  (bupdate b search_term0 updateTerm))\n              by (rewrite e0; eauto).\n            destruct (bupdate_correct b search_term0 updateTerm); eauto.\n            rewrite H0, partition_filter_neq, partition_filter_eq, <- !app_assoc.\n            f_equiv.\n            + eapply filter_negb_Prefix; eauto; reflexivity.\n            + symmetry; rewrite Permutation_app_swap, <- app_assoc.\n              f_equiv.\n              * symmetry; f_equiv; eapply filter_Prefix; eauto.\n              * rewrite <- (fun H => @fold_1 _ m H (list BagType) [ ] (fun k trie a => Trie_enumerate trie ++ a)) by eauto.\n                rewrite Permutation_KeyBasedPartition with (key0 := key0)\n                                                             (bst_m := SubTrieMapBST containerCorrect).\n                rewrite (Permutation_benumerate_add key0 bag'' (XMap.Bst (SubTrieMapBST containerCorrect))).\n                rewrite map_app, flatten_app.\n                rewrite (H (l ++ [key0])), partition_filter_neq, partition_filter_eq.\n                rewrite <- app_assoc.\n                symmetry; rewrite Permutation_app_swap; symmetry.\n                rewrite <- app_assoc.\n                f_equiv.\n                { simpl.\n                  apply find_2 in e1.\n                  pose proof (KeyBasedPartition_fst_singleton key0 subtrie (XMap.Bst (SubTrieMapBST containerCorrect)) e1) as singleton.\n                  rewrite (fold_Equal_simpl (eqA := @Permutation BagType) singleton)\n                    by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n                  rewrite !fold_add;\n                    eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey, empty_In.\n                  rewrite flatten_filter.\n                  rewrite !map_app, fold_empty, !map_map.\n                  rewrite flatten_app.\n                  rewrite Permutation_app_swap, map_app.\n                  rewrite (fold_Equal_simpl (eqA := @Permutation BagType) (filter_negb_remove key0 _))\n                    by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n                  rewrite filter_remove_key; eauto.\n                  simpl.\n                  unfold TrieBag_benumerate.\n                  rewrite <- map_map.\n                  rewrite flatten_filter, map_flatten.\n                  setoid_rewrite map_id; setoid_rewrite map_id.\n                  rewrite map_map, <- app_assoc; reflexivity.\n                }\n                simpl.\n                rewrite flatten_filter, map_map.\n                apply find_2 in e1.\n                pose proof (KeyBasedPartition_fst_singleton key0 subtrie (XMap.Bst (SubTrieMapBST containerCorrect)) e1) as singleton.\n                rewrite (fold_Equal_simpl (eqA := @Permutation BagType) singleton)\n                  by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n                rewrite !fold_add;\n                  eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey, empty_In.\n                rewrite map_app, flatten_app.\n                symmetry; rewrite Permutation_app_swap; symmetry.\n                f_equiv.\n                { unfold TrieBag_benumerate;\n                  rewrite <- map_map.\n                  rewrite flatten_filter, <- app_assoc; simpl; reflexivity.\n                }\n                rewrite fold_empty.\n                rewrite (fold_Equal_simpl (eqA := @Permutation BagType) (filter_negb_remove key0 _))\n                  by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n                unfold XMap.fold, XMap.remove, XMap.elements; simpl.\n                rewrite fold_1; simpl.\n                rewrite <- TrieBag_enumerateOK'''; eauto.\n                rewrite flatten_filter, map_map; unfold TrieBag_bfind_matcher, IsPrefix; reflexivity; eauto.\n                intros; eapply TrieOK_distinct_subtries; eauto.\n                apply remove_bst.\n                eauto.\n                eauto.\n                eauto.\n          - destruct trie; simpl in *.\n            unfold TrieBag_benumerate; simpl.\n            rewrite !XMapfold_eq, !fold_1 by eauto.\n            rewrite partition_filter_neq, partition_filter_eq.\n            rewrite Permutation_benumerate_fold_left, flatten_app; simpl.\n            rewrite (Permutation_benumerate_fold_left _ [b]), flatten_app; simpl.\n            rewrite !filter_app.\n            rewrite app_nil_r, <- !app_assoc; simpl.\n            rewrite map_app.\n            replace (bag') with (snd  (bupdate b search_term0 updateTerm))\n              by (rewrite e0; eauto).\n            destruct (bupdate_correct b search_term0 updateTerm); eauto.\n            rewrite H, partition_filter_neq, partition_filter_eq, <- !app_assoc.\n            f_equiv.\n            + eapply filter_negb_Prefix; eauto; reflexivity.\n            + symmetry; rewrite Permutation_app_swap, <- app_assoc.\n              f_equiv.\n              * rewrite filter_Prefix; eauto; reflexivity.\n              * simpl.\n                rewrite <- (fun H => @fold_1 _ m H (list BagType) [ ] (fun k trie a => Trie_enumerate trie ++ a)) by eauto.\n                rewrite Permutation_KeyBasedPartition with (key0 := key0)\n                                                             (bst_m := SubTrieMapBST containerCorrect).\n                simpl.\n                rewrite <- (@not_find_in_iff _ (XMap.Bst (SubTrieMapBST' containerCorrect)) key0) in e1.\n                pose proof (KeyBasedPartition_fst_singleton_None key0 (XMap.Bst (SubTrieMapBST containerCorrect)) e1) as singleton.\n                rewrite (fold_Equal_simpl (eqA := @Permutation BagType) singleton)\n                  by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n                rewrite !fold_empty;\n                  eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey, empty_In.\n                rewrite <- app_nil_l; f_equiv.\n                {\n                  replace (@nil TItem) with (List.map (bupdate_transform updateTerm) (@nil _)) by\n                      reflexivity.\n                  f_equiv.\n                  rewrite (fold_Equal_simpl (eqA := @Permutation BagType) (filter_negb_remove key0 _))\n                    by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n                  rewrite <- filter_remove_key; eauto.\n                  rewrite flatten_filter, map_map; eauto.\n                  eauto.\n                }\n                unfold XMap.fold; symmetry.\n                rewrite fold_1, <- TrieBag_enumerateOK''' at 1.\n                rewrite fold_1; unfold TrieBag_bfind_matcher, IsPrefix; eauto.\n                exact (XMap.is_bst _).\n                eauto using Proper_negb_KeyBasedPartitioningFunction.\n                intros; eapply TrieOK_distinct_subtries'; eauto.\n                exact (XMap.is_bst _).\n        }\n        {\n          rewrite <- (app_nil_l st); rewrite app_nil_l at 1.\n          revert containerCorrect.\n          unfold TrieBagRepInv; remember [] as l; clear Heql; revert l valid_update.\n          eapply Trie_update_ind; intros; subst; simpl.\n          - destruct (bupdate_correct (TrieNode trie) search_term0 updateTerm); eauto.\n            destruct trie; simpl.\n            rewrite partition_filter_eq.\n            unfold TrieBag_benumerate; simpl.\n            rewrite !XMapfold_eq, !fold_1 by eauto.\n            rewrite e0 in H, H0; simpl in *.\n            rewrite Permutation_benumerate_fold_left, flatten_app; simpl.\n            rewrite H0, partition_filter_eq, !app_nil_r, !filter_app ; simpl.\n            rewrite <- app_nil_r at 1.\n            f_equiv.\n            + rewrite filter_Prefix; eauto; reflexivity.\n            + inversion containerCorrect; subst.\n              rewrite TrieBag_enumerateOK' at 1; eauto.\n              intros; eapply H7.\n              eapply (@XMap.elements_2 _ (XMap.Bst H4)); eauto.\n          - rewrite e2 in H; simpl in *.\n            destruct trie; simpl in *.\n            unfold TrieBag_benumerate; simpl.\n            rewrite !XMapfold_eq, !fold_1 by eauto.\n            rewrite partition_filter_eq.\n            rewrite Permutation_benumerate_fold_left, flatten_app; simpl.\n            rewrite !filter_app, app_nil_r; simpl.\n            replace (updatedItems) with (fst (bupdate b search_term0 updateTerm))\n              by (rewrite e0; eauto).\n            destruct (bupdate_correct b search_term0 updateTerm); eauto.\n            rewrite H1, partition_filter_eq.\n            f_equiv.\n            + rewrite filter_Prefix; eauto; reflexivity.\n            + rewrite (H (l ++ [key0])); simpl; eauto.\n              rewrite partition_filter_eq.\n              rewrite <- (fun H => @fold_1 _ m H (list BagType) [ ] (fun k trie a => Trie_enumerate trie ++ a)) by eauto.\n              rewrite Permutation_KeyBasedPartition with (key0 := key0)\n                                                           (bst_m := SubTrieMapBST containerCorrect).\n              simpl.\n              apply find_2 in e1.\n              pose proof (KeyBasedPartition_fst_singleton key0 subtrie (XMap.Bst (SubTrieMapBST containerCorrect)) e1) as singleton.\n              rewrite (fold_Equal_simpl (eqA := @Permutation BagType) singleton)\n                by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n              rewrite !fold_add;\n                eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey, empty_In.\n              rewrite flatten_filter.\n              rewrite !map_app, fold_empty, !map_map.\n              rewrite flatten_app.\n              rewrite <- app_nil_r at 1.\n              f_equiv.\n              * unfold TrieBag_benumerate; rewrite flatten_filter, map_map, <- app_assoc; reflexivity.\n              * rewrite <- filter_remove_key; eauto.\n                rewrite (fold_Equal_simpl (eqA := @Permutation BagType) (filter_negb_remove key0 _))\n                  by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n                eauto.\n                eauto.\n          - destruct trie; simpl in *.\n            unfold TrieBag_benumerate; simpl.\n            rewrite !XMapfold_eq, !fold_1 by eauto.\n            rewrite partition_filter_eq.\n            rewrite Permutation_benumerate_fold_left, flatten_app; simpl.\n            rewrite !filter_app, app_nil_r; simpl.\n            replace (updatedItems) with (fst (bupdate b search_term0 updateTerm))\n              by (rewrite e0; eauto).\n            destruct (bupdate_correct b search_term0 updateTerm); eauto.\n            rewrite H0, partition_filter_eq.\n            rewrite <- app_nil_r at 1.\n            f_equiv.\n            + rewrite filter_Prefix; eauto.\n            + simpl.\n              rewrite <- (fun H => @fold_1 _ m H (list BagType) [ ] (fun k trie a => Trie_enumerate trie ++ a)) by eauto.\n              rewrite Permutation_KeyBasedPartition with (key0 := key0)\n                                                           (bst_m := SubTrieMapBST containerCorrect).\n              rewrite <- (@not_find_in_iff _ (XMap.Bst (SubTrieMapBST' containerCorrect)) key0) in e1.\n              pose proof (KeyBasedPartition_fst_singleton_None key0 (XMap.Bst (SubTrieMapBST containerCorrect)) e1) as singleton.\n              rewrite (fold_Equal_simpl (eqA := @Permutation BagType) singleton)\n                by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n              rewrite !fold_empty;\n                eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey, empty_In.\n              simpl.\n              rewrite (fold_Equal_simpl (eqA := @Permutation BagType) (filter_negb_remove key0 _))\n                by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n              rewrite <- filter_remove_key; eauto.\n              rewrite flatten_filter, map_map; eauto.\n              eauto.\n        }\n      }\n      { unfold TrieBag_bfind_matcher; simpl.\n        unfold TrieBagRepInv.\n        pattern container, (@nil X.t) ; apply Trie_ind'; simpl; intros.\n        unfold TrieBag_benumerate; simpl.\n        intros; inversion containerCorrect; subst.\n        case_eq (bupdate b search_term update_term); simpl; intros.\n        destruct (bupdate_correct b search_term update_term); eauto.\n        rewrite H0 in H1, H5; simpl in H1, H5.\n        rewrite (Permute_XMapfold_cons m [b]), Permute_XMapfold_cons with (l := [b0]).\n        rewrite !map_app, !flatten_app, !partition_app; simpl.\n        rewrite !app_nil_r.\n        split.\n        - rewrite H1.\n          rewrite app_assoc.\n          symmetry.\n          rewrite (Permutation_app_swap).\n          symmetry.\n          rewrite <- !app_assoc.\n          rewrite (Permutation_app_swap (snd _)).\n          rewrite !app_assoc, map_app.\n          f_equiv.\n          symmetry; rewrite Permutation_app_swap, app_assoc.\n          f_equiv.\n          rewrite !XMapfold_eq.\n          symmetry.\n          setoid_rewrite (fold_pair (XMap.Bst H3)); simpl.\n          rewrite fold_spec_right.\n          pose fold_spec_right as e; unfold XMap.fold in e; rewrite (e _ (XMap.Bst H3));\n          clear e.\n          assert (forall k trie,\n                     InA (@XMap.eq_key_elt _)\n                         (k, trie)\n                         (rev\n                            (XMap.elements (elt:=Trie)\n                                           {| XMap.this := m; XMap.is_bst := H3 |}))\n                     -> Permutation (TrieBag_benumerate (snd (Trie_update' trie search_term update_term)))\n                                    (snd\n                                       (List.partition\n                                          (fun item : TItem => bfind_matcher search_term item)\n                                          (TrieBag_benumerate trie))\n                                          ++ List.map (bupdate_transform update_term)\n                                          (fst\n                                             (List.partition\n                                                (fun item : TItem => bfind_matcher search_term item)\n                                                (TrieBag_benumerate trie)))\n                 )).\n          { intros; eapply H; eauto using elements_mapsto_iff.\n            pose elements_mapsto_iff as e; unfold XMap.MapsTo in e; rewrite (e _ (XMap.Bst H3));\n            clear e.\n            rewrite <- InA_rev; eauto with typeclass_instances.\n            eapply H6.\n            eapply (@elements_mapsto_iff _ (XMap.Bst H3)).\n            eapply InA_rev; eauto with typeclass_instances.\n          }\n          generalize H7; clear.\n          assert (NoDupA (@XMap.eq_key _)\n                         (rev\n                            (XMap.elements (elt:=Trie) {| XMap.this := m; XMap.is_bst := H3 |})))\n          by (apply NoDupA_rev; eauto with typeclass_instances;\n              eapply XMap.elements_3w).\n          revert H.\n          induction (rev\n                       (XMap.elements (elt:=Trie) {| XMap.this := m; XMap.is_bst := H3 |}));\n            simpl; intros; eauto.\n          unfold uncurry.\n          pose fold_add as e; unfold XMap.fold, XMap.add in e; simpl in e.\n          rewrite e; clear e.\n          rewrite !map_app, !flatten_app, !partition_app; simpl.\n          unfold TrieBag_benumerate in H7.\n          rewrite H7 with (k := fst a); eauto with typeclass_instances.\n          rewrite <- !app_assoc; f_equiv; eauto.\n          rewrite IHl.\n          rewrite Permutation_app_swap, <- app_assoc, map_app.\n          f_equiv.\n          rewrite Permutation_app_swap; f_equiv.\n          inversion H; eauto.\n          intros; eapply H7; econstructor 2; eauto.\n          destruct a; econstructor 1; reflexivity.\n          eauto with typeclass_instances.\n          eauto with typeclass_instances.\n          eauto using transpose_neqkey_Trie_enumerate_app.\n          inversion H; subst; intro; apply H2.\n          unfold XMap.In, In0 in H0.\n          revert H0; clear; induction l; simpl.\n          + intros; destruct H0; inversion H.\n          + intros; destruct H0.\n            pose add_mapsto_iff as e; unfold XMap.add, XMap.MapsTo in e; simpl in e;\n            rewrite e in H; clear e.\n            intuition.\n            * econstructor 1; symmetry; apply H.\n            * eauto.\n        - rewrite H5, Permutation_app_swap; f_equiv.\n          rewrite !XMapfold_eq.\n          setoid_rewrite (fold_pair (XMap.Bst H3)); simpl.\n          rewrite fold_spec_right.\n          pose fold_spec_right as e; unfold XMap.fold in e; rewrite (e _ (XMap.Bst H3));\n          clear e.\n          assert (forall k trie,\n                     InA (@XMap.eq_key_elt _)\n                         (k, trie)\n                         (rev\n                            (XMap.elements (elt:=Trie)\n                                           {| XMap.this := m; XMap.is_bst := H3 |}))\n                     -> Permutation ((fst (Trie_update' trie search_term update_term)))\n                                    (fst\n                                       (List.partition\n                                          (fun item : TItem => bfind_matcher search_term item)\n                                          (TrieBag_benumerate trie)))).\n          { intros; eapply H; eauto using elements_mapsto_iff.\n            pose elements_mapsto_iff as e; unfold XMap.MapsTo in e; rewrite (e _ (XMap.Bst H3));\n            clear e.\n            rewrite <- InA_rev; eauto with typeclass_instances.\n            eapply H6.\n            eapply (@elements_mapsto_iff _ (XMap.Bst H3)).\n            eapply InA_rev; eauto with typeclass_instances.\n          }\n          generalize H7; clear.\n          assert (NoDupA (@XMap.eq_key _)\n                         (rev\n                            (XMap.elements (elt:=Trie) {| XMap.this := m; XMap.is_bst := H3 |})))\n          by (apply NoDupA_rev; eauto with typeclass_instances;\n              eapply XMap.elements_3w).\n          revert H.\n          induction (rev\n                       (XMap.elements (elt:=Trie) {| XMap.this := m; XMap.is_bst := H3 |}));\n            simpl; intros; eauto.\n          unfold uncurry.\n          rewrite !map_app, !flatten_app, !partition_app; simpl.\n          unfold TrieBag_benumerate in H7.\n          rewrite H7 with (k := fst a); f_equiv; eauto.\n          rewrite <- IHl; eauto.\n          inversion H; eauto.\n          econstructor; destruct a; simpl; reflexivity.\n      }\n      Grab Existential Variables.\n      eauto.\n    Qed.\n\n  End TrieBagDefinitions.\n\n  Global Instance TrieAsBag\n         {BagType TItem SearchTermType UpdateTermType : Type}\n         (TBag : Bag BagType TItem SearchTermType UpdateTermType)\n         projection\n  : Bag Trie TItem ((option (list TKey)) * (SearchTermType)) UpdateTermType :=\n    {\n\n      bempty            := TrieBag_bempty TBag;\n\n      bfind_matcher     := TrieBag_bfind_matcher TBag projection;\n      bupdate_transform := bupdate_transform;\n\n      benumerate := TrieBag_benumerate TBag;\n      bfind      := TrieBag_bfind TBag;\n      binsert    := TrieBag_binsert TBag projection;\n      bcount     := TrieBag_bcount TBag;\n      bdelete    := TrieBag_bdelete TBag;\n      bupdate    := TrieBag_bupdate TBag }.\n\n  Global Instance TrieBagAsCorrectBag\n         {BagType TItem SearchTermType UpdateTermType : Type}\n         (TBag : Bag BagType TItem SearchTermType UpdateTermType)\n         (RepInv : BagType -> Prop)\n         (ValidUpdate : UpdateTermType -> Prop)\n         (CorrectTBag : CorrectBag RepInv ValidUpdate TBag)\n         projection\n  : CorrectBag (TrieBagRepInv TBag RepInv projection)\n               (TrieBag_ValidUpdate _ ValidUpdate projection)\n               (TrieAsBag TBag projection ) :=\n    {\n      bempty_RepInv     := Trie_Empty_RepInv CorrectTBag projection;\n      binsert_RepInv    := @TrieBag_binsert_Preserves_RepInv _ _ _ _ TBag _ _ _ projection;\n      bdelete_RepInv    := @TrieBag_bdelete_Preserves_RepInv _ _ _ _ TBag _ _ _ projection;\n      bupdate_RepInv    := @TrieBag_bupdate_Preserves_RepInv _ _ _ _ TBag _ _ CorrectTBag projection;\n\n      binsert_enumerate := @TrieBag_BagInsertEnumerate _ _ _ _ _ _ _ CorrectTBag projection;\n      benumerate_empty  := @TrieBag_BagEnumerateEmpty _ _ _ _ _ _ _ CorrectTBag;\n      bfind_correct     := @TrieBag_BagFindCorrect _ _ _ _ _ _ _ CorrectTBag projection;\n      bcount_correct    := @TrieBag_BagCountCorrect _ _ _ _ _ _ _ CorrectTBag projection;\n      bdelete_correct   := @TrieBag_BagDeleteCorrect _ _ _ _ _ _ _ CorrectTBag projection ;\n      bupdate_correct   := @TrieBag_BagUpdateCorrect _ _ _ _ _ _ _ CorrectTBag projection\n    }.\n\nEnd TrieBag.\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/TrieBags.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.296651450865509}}
{"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 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(** Formalizations of machine integers modulo $2^N$ #2<sup>N</sup>#. *)\n\nRequire Import Eqdep_dec Zquot Zwf.\nRequire Import Coqlib Zbits.\nRequire Archi.\n\n(** * Comparisons *)\n\nInductive comparison : Type :=\n  | Ceq : comparison               (**r same *)\n  | Cne : comparison               (**r different *)\n  | Clt : comparison               (**r less than *)\n  | Cle : comparison               (**r less than or equal *)\n  | Cgt : comparison               (**r greater than *)\n  | Cge : comparison.              (**r greater than or equal *)\n\nDefinition negate_comparison (c: comparison): comparison :=\n  match c with\n  | Ceq => Cne\n  | Cne => Ceq\n  | Clt => Cge\n  | Cle => Cgt\n  | Cgt => Cle\n  | Cge => Clt\n  end.\n\nDefinition swap_comparison (c: comparison): comparison :=\n  match c with\n  | Ceq => Ceq\n  | Cne => Cne\n  | Clt => Cgt\n  | Cle => Cge\n  | Cgt => Clt\n  | Cge => Cle\n  end.\n\n(** * Parameterization by the word size, in bits. *)\n\nModule Type WORDSIZE.\n  Parameter wordsize: nat.\n  Axiom wordsize_not_zero: wordsize <> 0%nat.\nEnd WORDSIZE.\n\n(* To avoid useless definitions of inductors in extracted code. *)\nLocal Unset Elimination Schemes.\nLocal Unset Case Analysis Schemes.\n\nModule Make(WS: WORDSIZE).\n\nDefinition wordsize: nat := WS.wordsize.\nDefinition zwordsize: Z := Z.of_nat wordsize.\nDefinition modulus : Z := two_power_nat wordsize.\nDefinition half_modulus : Z := modulus / 2.\nDefinition max_unsigned : Z := modulus - 1.\nDefinition max_signed : Z := half_modulus - 1.\nDefinition min_signed : Z := - half_modulus.\n\nRemark wordsize_pos: zwordsize > 0.\nProof.\n  unfold zwordsize, wordsize. generalize WS.wordsize_not_zero. lia.\nQed.\n\nRemark modulus_power: modulus = two_p zwordsize.\nProof.\n  unfold modulus. apply two_power_nat_two_p.\nQed.\n\nRemark modulus_gt_one: modulus > 1.\nProof.\n  rewrite modulus_power. apply Z.lt_gt. apply (two_p_monotone_strict 0).\n  generalize wordsize_pos; lia.\nQed.\n\nRemark modulus_pos: modulus > 0.\nProof.\n  generalize modulus_gt_one; lia.\nQed.\n\nGlobal Hint Resolve modulus_pos: ints.\n\n(** * Representation of machine integers *)\n\n(** A machine integer (type [int]) is represented as a Coq arbitrary-precision\n  integer (type [Z]) plus a proof that it is in the range 0 (included) to\n  [modulus] (excluded). *)\n\nRecord int: Type := mkint { intval: Z; intrange: -1 < intval < modulus }.\n\n(** Fast normalization modulo [2^wordsize] *)\n\nDefinition Z_mod_modulus (x: Z) : Z :=\n  match x with\n  | Z0 => 0\n  | Zpos p => P_mod_two_p p wordsize\n  | Zneg p => let r := P_mod_two_p p wordsize in if zeq r 0 then 0 else modulus - r\n  end.\n\nLemma Z_mod_modulus_range:\n  forall x, 0 <= Z_mod_modulus x < modulus.\nProof (Z_mod_two_p_range wordsize).\n\nLemma Z_mod_modulus_range':\n  forall x, -1 < Z_mod_modulus x < modulus.\nProof.\n  intros. generalize (Z_mod_modulus_range x); intuition.\nQed.\n\nLemma Z_mod_modulus_eq:\n  forall x, Z_mod_modulus x = x mod modulus.\nProof (Z_mod_two_p_eq wordsize).\n\n(** The [unsigned] and [signed] functions return the Coq integer corresponding\n  to the given machine integer, interpreted as unsigned or signed\n  respectively. *)\n\nDefinition unsigned (n: int) : Z := intval n.\n\nDefinition signed (n: int) : Z :=\n  let x := unsigned n in\n  if zlt x half_modulus then x else x - modulus.\n\n(** Conversely, [repr] takes a Coq integer and returns the corresponding\n  machine integer.  The argument is treated modulo [modulus]. *)\n\nDefinition repr (x: Z) : int :=\n  mkint (Z_mod_modulus x) (Z_mod_modulus_range' x).\n\nDefinition zero := repr 0.\nDefinition one  := repr 1.\nDefinition mone := repr (-1).\nDefinition iwordsize := repr zwordsize.\n\nLemma mkint_eq:\n  forall x y Px Py, x = y -> mkint x Px = mkint y Py.\nProof.\n  intros. subst y.\n  assert (forall (n m: Z) (P1 P2: n < m), P1 = P2).\n  {\n    unfold Z.lt; intros.\n    apply eq_proofs_unicity.\n    intros c1 c2. destruct c1; destruct c2; (left; reflexivity) || (right; congruence).\n  }\n  destruct Px as [Px1 Px2]. destruct Py as [Py1 Py2].\n  rewrite (H _ _ Px1 Py1).\n  rewrite (H _ _ Px2 Py2).\n  reflexivity.\nQed.\n\nLemma eq_dec: forall (x y: int), {x = y} + {x <> y}.\nProof.\n  intros. destruct x; destruct y. destruct (zeq intval0 intval1).\n  left. apply mkint_eq. auto.\n  right. red; intro. injection H. exact n.\nDefined.\n\n(** * Arithmetic and logical operations over machine integers *)\n\nDefinition eq (x y: int) : bool :=\n  if zeq (unsigned x) (unsigned y) then true else false.\nDefinition lt (x y: int) : bool :=\n  if zlt (signed x) (signed y) then true else false.\nDefinition ltu (x y: int) : bool :=\n  if zlt (unsigned x) (unsigned y) then true else false.\n\nDefinition neg (x: int) : int := repr (- unsigned x).\n\nDefinition add (x y: int) : int :=\n  repr (unsigned x + unsigned y).\nDefinition sub (x y: int) : int :=\n  repr (unsigned x - unsigned y).\nDefinition mul (x y: int) : int :=\n  repr (unsigned x * unsigned y).\n\nDefinition divs (x y: int) : int :=\n  repr (Z.quot (signed x) (signed y)).\nDefinition mods (x y: int) : int :=\n  repr (Z.rem (signed x) (signed y)).\n\nDefinition divu (x y: int) : int :=\n  repr (unsigned x / unsigned y).\nDefinition modu (x y: int) : int :=\n  repr ((unsigned x) mod (unsigned y)).\n\n(** Bitwise boolean operations. *)\n\nDefinition and (x y: int): int := repr (Z.land (unsigned x) (unsigned y)).\nDefinition or (x y: int): int := repr (Z.lor (unsigned x) (unsigned y)).\nDefinition xor (x y: int) : int := repr (Z.lxor (unsigned x) (unsigned y)).\n\nDefinition not (x: int) : int := xor x mone.\n\n(** Shifts and rotates. *)\n\nDefinition shl (x y: int): int := repr (Z.shiftl (unsigned x) (unsigned y)).\nDefinition shru (x y: int): int := repr (Z.shiftr (unsigned x) (unsigned y)).\nDefinition shr (x y: int): int := repr (Z.shiftr (signed x) (unsigned y)).\n\nDefinition rol (x y: int) : int :=\n  let n := (unsigned y) mod zwordsize in\n  repr (Z.lor (Z.shiftl (unsigned x) n) (Z.shiftr (unsigned x) (zwordsize - n))).\nDefinition ror (x y: int) : int :=\n  let n := (unsigned y) mod zwordsize in\n  repr (Z.lor (Z.shiftr (unsigned x) n) (Z.shiftl (unsigned x) (zwordsize - n))).\n\nDefinition rolm (x a m: int): int := and (rol x a) m.\n\n(** Viewed as signed divisions by powers of two, [shrx] rounds towards\n  zero, while [shr] rounds towards minus infinity. *)\n\nDefinition shrx (x y: int): int :=\n  divs x (shl one y).\n\n(** High half of full multiply. *)\n\nDefinition mulhu (x y: int): int := repr ((unsigned x * unsigned y) / modulus).\nDefinition mulhs (x y: int): int := repr ((signed x * signed y) / modulus).\n\n(** Condition flags *)\n\nDefinition negative (x: int): int :=\n  if lt x zero then one else zero.\n\nDefinition add_carry (x y cin: int): int :=\n  if zlt (unsigned x + unsigned y + unsigned cin) modulus then zero else one.\n\nDefinition add_overflow (x y cin: int): int :=\n  let s := signed x + signed y + signed cin in\n  if zle min_signed s && zle s max_signed then zero else one.\n\nDefinition sub_borrow (x y bin: int): int :=\n  if zlt (unsigned x - unsigned y - unsigned bin) 0 then one else zero.\n\nDefinition sub_overflow (x y bin: int): int :=\n  let s := signed x - signed y - signed bin in\n  if zle min_signed s && zle s max_signed then zero else one.\n\n(** [shr_carry x y] is 1 if [x] is negative and at least one 1 bit is shifted away. *)\n\nDefinition shr_carry (x y: int) : int :=\n  if lt x zero && negb (eq (and x (sub (shl one y) one)) zero)\n  then one else zero.\n\n(** Zero and sign extensions *)\n\nDefinition zero_ext (n: Z) (x: int) : int := repr (Zzero_ext n (unsigned x)).\nDefinition sign_ext (n: Z) (x: int) : int := repr (Zsign_ext n (unsigned x)).\n\n(** Decomposition of a number as a sum of powers of two. *)\n\nDefinition one_bits (x: int) : list int :=\n  List.map repr (Z_one_bits wordsize (unsigned x) 0).\n\n(** Recognition of powers of two. *)\n\nDefinition is_power2 (x: int) : option int :=\n  match Z_is_power2 (unsigned x) with\n  | Some i => Some (repr i)\n  | None => None\n  end.\n\n(** Comparisons. *)\n\nDefinition cmp (c: comparison) (x y: int) : bool :=\n  match c with\n  | Ceq => eq x y\n  | Cne => negb (eq x y)\n  | Clt => lt x y\n  | Cle => negb (lt y x)\n  | Cgt => lt y x\n  | Cge => negb (lt x y)\n  end.\n\nDefinition cmpu (c: comparison) (x y: int) : bool :=\n  match c with\n  | Ceq => eq x y\n  | Cne => negb (eq x y)\n  | Clt => ltu x y\n  | Cle => negb (ltu y x)\n  | Cgt => ltu y x\n  | Cge => negb (ltu x y)\n  end.\n\nDefinition is_false (x: int) : Prop := x = zero.\nDefinition is_true  (x: int) : Prop := x <> zero.\nDefinition notbool  (x: int) : int  := if eq x zero then one else zero.\n\n(** x86-style extended division and modulus *)\n\nDefinition divmodu2 (nhi nlo: int) (d: int) : option (int * int) :=\n  if eq_dec d zero then None else\n   (let (q, r) := Z.div_eucl (unsigned nhi * modulus + unsigned nlo) (unsigned d) in\n    if zle q max_unsigned then Some(repr q, repr r) else None).\n\nDefinition divmods2 (nhi nlo: int) (d: int) : option (int * int) :=\n  if eq_dec d zero then None else\n   (let (q, r) := Z.quotrem (signed nhi * modulus + unsigned nlo) (signed d) in\n    if zle min_signed q && zle q max_signed then Some(repr q, repr r) else None).\n\n(** * Properties of integers and integer arithmetic *)\n\n(** ** Properties of [modulus], [max_unsigned], etc. *)\n\nRemark half_modulus_power:\n  half_modulus = two_p (zwordsize - 1).\nProof.\n  unfold half_modulus. rewrite modulus_power.\n  set (ws1 := zwordsize - 1).\n  replace (zwordsize) with (Z.succ ws1).\n  rewrite two_p_S. rewrite Z.mul_comm. apply Z_div_mult. lia.\n  unfold ws1. generalize wordsize_pos; lia.\n  unfold ws1. lia.\nQed.\n\nRemark half_modulus_modulus: modulus = 2 * half_modulus.\nProof.\n  rewrite half_modulus_power. rewrite modulus_power.\n  rewrite <- two_p_S. apply f_equal. lia.\n  generalize wordsize_pos; lia.\nQed.\n\n(** Relative positions, from greatest to smallest:\n<<\n      max_unsigned\n      max_signed\n      2*wordsize-1\n      wordsize\n      0\n      min_signed\n>>\n*)\n\nRemark half_modulus_pos: half_modulus > 0.\nProof.\n  rewrite half_modulus_power. apply two_p_gt_ZERO. generalize wordsize_pos; lia.\nQed.\n\nRemark min_signed_neg: min_signed < 0.\nProof.\n  unfold min_signed. generalize half_modulus_pos. lia.\nQed.\n\nRemark max_signed_pos: max_signed >= 0.\nProof.\n  unfold max_signed. generalize half_modulus_pos. lia.\nQed.\n\nRemark wordsize_max_unsigned: zwordsize <= max_unsigned.\nProof.\n  assert (zwordsize < modulus).\n    rewrite modulus_power. apply two_p_strict.\n    generalize wordsize_pos. lia.\n  unfold max_unsigned. lia.\nQed.\n\nRemark two_wordsize_max_unsigned: 2 * zwordsize - 1 <= max_unsigned.\nProof.\n  assert (2 * zwordsize - 1 < modulus).\n    rewrite modulus_power. apply two_p_strict_2. generalize wordsize_pos; lia.\n  unfold max_unsigned; lia.\nQed.\n\nRemark max_signed_unsigned: max_signed < max_unsigned.\nProof.\n  unfold max_signed, max_unsigned. rewrite half_modulus_modulus.\n  generalize half_modulus_pos. lia.\nQed.\n\nLemma unsigned_repr_eq:\n  forall x, unsigned (repr x) = Z.modulo x modulus.\nProof.\n  intros. simpl. apply Z_mod_modulus_eq.\nQed.\n\nLemma signed_repr_eq:\n  forall x, signed (repr x) = if zlt (Z.modulo x modulus) half_modulus then Z.modulo x modulus else Z.modulo x modulus - modulus.\nProof.\n  intros. unfold signed. rewrite unsigned_repr_eq. auto.\nQed.\n\n(** ** Modulo arithmetic *)\n\n(** [eqm] is equality modulo $2^{wordsize}$ #2<sup>wordsize</sup>#. *)\n\nDefinition eqm := eqmod modulus.\n\nLemma eqm_refl: forall x, eqm x x.\nProof (eqmod_refl modulus).\nGlobal Hint Resolve eqm_refl: ints.\n\nLemma eqm_refl2:\n  forall x y, x = y -> eqm x y.\nProof (eqmod_refl2 modulus).\nGlobal Hint Resolve eqm_refl2: ints.\n\nLemma eqm_sym: forall x y, eqm x y -> eqm y x.\nProof (eqmod_sym modulus).\nGlobal Hint Resolve eqm_sym: ints.\n\nLemma eqm_trans: forall x y z, eqm x y -> eqm y z -> eqm x z.\nProof (eqmod_trans modulus).\nGlobal Hint Resolve eqm_trans: ints.\n\nLemma eqm_small_eq:\n  forall x y, eqm x y -> 0 <= x < modulus -> 0 <= y < modulus -> x = y.\nProof (eqmod_small_eq modulus).\nGlobal Hint Resolve eqm_small_eq: ints.\n\nLemma eqm_add:\n  forall a b c d, eqm a b -> eqm c d -> eqm (a + c) (b + d).\nProof (eqmod_add modulus).\nGlobal Hint Resolve eqm_add: ints.\n\nLemma eqm_neg:\n  forall x y, eqm x y -> eqm (-x) (-y).\nProof (eqmod_neg modulus).\nGlobal Hint Resolve eqm_neg: ints.\n\nLemma eqm_sub:\n  forall a b c d, eqm a b -> eqm c d -> eqm (a - c) (b - d).\nProof (eqmod_sub modulus).\nGlobal Hint Resolve eqm_sub: ints.\n\nLemma eqm_mult:\n  forall a b c d, eqm a c -> eqm b d -> eqm (a * b) (c * d).\nProof (eqmod_mult modulus).\nGlobal Hint Resolve eqm_mult: ints.\n\nLemma eqm_same_bits:\n  forall x y,\n  (forall i, 0 <= i < zwordsize -> Z.testbit x i = Z.testbit y i) ->\n  eqm x y.\nProof (eqmod_same_bits wordsize).\n\nLemma same_bits_eqm:\n  forall x y i,\n  eqm x y ->\n  0 <= i < zwordsize ->\n  Z.testbit x i = Z.testbit y i.\nProof (same_bits_eqmod wordsize).\n\n(** ** Properties of the coercions between [Z] and [int] *)\n\nLemma eqm_samerepr: forall x y, eqm x y -> repr x = repr y.\nProof.\n  intros. unfold repr. apply mkint_eq.\n  rewrite !Z_mod_modulus_eq. apply eqmod_mod_eq. auto with ints. exact H.\nQed.\n\nLemma eqm_unsigned_repr:\n  forall z, eqm z (unsigned (repr z)).\nProof.\n  unfold eqm; intros. rewrite unsigned_repr_eq. apply eqmod_mod. auto with ints.\nQed.\nGlobal Hint Resolve eqm_unsigned_repr: ints.\n\nLemma eqm_unsigned_repr_l:\n  forall a b, eqm a b -> eqm (unsigned (repr a)) b.\nProof.\n  intros. apply eqm_trans with a.\n  apply eqm_sym. apply eqm_unsigned_repr. auto.\nQed.\nGlobal Hint Resolve eqm_unsigned_repr_l: ints.\n\nLemma eqm_unsigned_repr_r:\n  forall a b, eqm a b -> eqm a (unsigned (repr b)).\nProof.\n  intros. apply eqm_trans with b. auto.\n  apply eqm_unsigned_repr.\nQed.\nGlobal Hint Resolve eqm_unsigned_repr_r: ints.\n\nLemma eqm_signed_unsigned:\n  forall x, eqm (signed x) (unsigned x).\nProof.\n  intros; red. unfold signed. set (y := unsigned x).\n  case (zlt y half_modulus); intro.\n  apply eqmod_refl. red; exists (-1); ring.\nQed.\n\nTheorem unsigned_range:\n  forall i, 0 <= unsigned i < modulus.\nProof.\n  destruct i. simpl. lia.\nQed.\nGlobal Hint Resolve unsigned_range: ints.\n\nTheorem unsigned_range_2:\n  forall i, 0 <= unsigned i <= max_unsigned.\nProof.\n  intro; unfold max_unsigned.\n  generalize (unsigned_range i). lia.\nQed.\nGlobal Hint Resolve unsigned_range_2: ints.\n\nTheorem signed_range:\n  forall i, min_signed <= signed i <= max_signed.\nProof.\n  intros. unfold signed.\n  generalize (unsigned_range i). set (n := unsigned i). intros.\n  case (zlt n half_modulus); intro.\n  unfold max_signed. generalize min_signed_neg. lia.\n  unfold min_signed, max_signed.\n  rewrite half_modulus_modulus in *. lia.\nQed.\n\nTheorem repr_unsigned:\n  forall i, repr (unsigned i) = i.\nProof.\n  destruct i; simpl. unfold repr. apply mkint_eq.\n  rewrite Z_mod_modulus_eq. apply Z.mod_small; lia.\nQed.\nGlobal Hint Resolve repr_unsigned: ints.\n\nLemma repr_signed:\n  forall i, repr (signed i) = i.\nProof.\n  intros. transitivity (repr (unsigned i)).\n  apply eqm_samerepr. apply eqm_signed_unsigned. auto with ints.\nQed.\nGlobal Hint Resolve repr_signed: ints.\n\nOpaque repr.\n\nLemma eqm_repr_eq: forall x y, eqm x (unsigned y) -> repr x = y.\nProof.\n  intros. rewrite <- (repr_unsigned y). apply eqm_samerepr; auto.\nQed.\n\nTheorem unsigned_repr:\n  forall z, 0 <= z <= max_unsigned -> unsigned (repr z) = z.\nProof.\n  intros. rewrite unsigned_repr_eq.\n  apply Z.mod_small. unfold max_unsigned in H. lia.\nQed.\nGlobal Hint Resolve unsigned_repr: ints.\n\nTheorem signed_repr:\n  forall z, min_signed <= z <= max_signed -> signed (repr z) = z.\nProof.\n  intros. unfold signed. destruct (zle 0 z).\n  replace (unsigned (repr z)) with z.\n  rewrite zlt_true. auto. unfold max_signed in H. lia.\n  symmetry. apply unsigned_repr. generalize max_signed_unsigned. lia.\n  pose (z' := z + modulus).\n  replace (repr z) with (repr z').\n  replace (unsigned (repr z')) with z'.\n  rewrite zlt_false. unfold z'. lia.\n  unfold z'. unfold min_signed in H.\n  rewrite half_modulus_modulus. lia.\n  symmetry. apply unsigned_repr.\n  unfold z', max_unsigned. unfold min_signed, max_signed in H.\n  rewrite half_modulus_modulus. lia.\n  apply eqm_samerepr. unfold z'; red. exists 1. lia.\nQed.\n\nTheorem signed_eq_unsigned:\n  forall x, unsigned x <= max_signed -> signed x = unsigned x.\nProof.\n  intros. unfold signed. destruct (zlt (unsigned x) half_modulus).\n  auto. unfold max_signed in H. extlia.\nQed.\n\nTheorem signed_positive:\n  forall x, signed x >= 0 <-> unsigned x <= max_signed.\nProof.\n  intros. unfold signed, max_signed.\n  generalize (unsigned_range x) half_modulus_modulus half_modulus_pos; intros.\n  destruct (zlt (unsigned x) half_modulus); lia.\nQed.\n\n(** ** Properties of zero, one, minus one *)\n\nTheorem unsigned_zero: unsigned zero = 0.\nProof.\n  unfold zero; rewrite unsigned_repr_eq. apply Zmod_0_l.\nQed.\n\nTheorem unsigned_one: unsigned one = 1.\nProof.\n  unfold one; rewrite unsigned_repr_eq. apply Z.mod_small. split. lia.\n  unfold modulus. replace wordsize with (S(Init.Nat.pred wordsize)).\n  rewrite two_power_nat_S. generalize (two_power_nat_pos (Init.Nat.pred wordsize)).\n  lia.\n  generalize wordsize_pos. unfold zwordsize. lia.\nQed.\n\nTheorem unsigned_mone: unsigned mone = modulus - 1.\nProof.\n  unfold mone; rewrite unsigned_repr_eq.\n  replace (-1) with ((modulus - 1) + (-1) * modulus).\n  rewrite Z_mod_plus_full. apply Z.mod_small.\n  generalize modulus_pos. lia. lia.\nQed.\n\nTheorem signed_zero: signed zero = 0.\nProof.\n  unfold signed. rewrite unsigned_zero. apply zlt_true. generalize half_modulus_pos; lia.\nQed.\n\nTheorem signed_one: zwordsize > 1 -> signed one = 1.\nProof.\n  intros. unfold signed. rewrite unsigned_one. apply zlt_true. \n  change 1 with (two_p 0). rewrite half_modulus_power. apply two_p_monotone_strict. lia. \nQed.\n\nTheorem signed_mone: signed mone = -1.\nProof.\n  unfold signed. rewrite unsigned_mone.\n  rewrite zlt_false. lia.\n  rewrite half_modulus_modulus. generalize half_modulus_pos. lia.\nQed.\n\nTheorem one_not_zero: one <> zero.\nProof.\n  assert (unsigned one <> unsigned zero).\n  rewrite unsigned_one; rewrite unsigned_zero; congruence.\n  congruence.\nQed.\n\nTheorem unsigned_repr_wordsize:\n  unsigned iwordsize = zwordsize.\nProof.\n  unfold iwordsize; rewrite unsigned_repr_eq. apply Z.mod_small.\n  generalize wordsize_pos wordsize_max_unsigned; unfold max_unsigned; lia.\nQed.\n\n(** ** Properties of equality *)\n\nTheorem eq_sym:\n  forall x y, eq x y = eq y x.\nProof.\n  intros; unfold eq. case (zeq (unsigned x) (unsigned y)); intro.\n  rewrite e. rewrite zeq_true. auto.\n  rewrite zeq_false. auto. auto.\nQed.\n\nTheorem eq_spec: forall (x y: int), if eq x y then x = y else x <> y.\nProof.\n  intros; unfold eq. case (eq_dec x y); intro.\n  subst y. rewrite zeq_true. auto.\n  rewrite zeq_false. auto.\n  destruct x; destruct y.\n  simpl. red; intro. elim n. apply mkint_eq. auto.\nQed.\n\nTheorem eq_true: forall x, eq x x = true.\nProof.\n  intros. generalize (eq_spec x x); case (eq x x); intros; congruence.\nQed.\n\nTheorem eq_false: forall x y, x <> y -> eq x y = false.\nProof.\n  intros. generalize (eq_spec x y); case (eq x y); intros; congruence.\nQed.\n\nTheorem same_if_eq: forall x y, eq x y = true -> x = y.\nProof.\n  intros. generalize (eq_spec x y); rewrite H; auto.\nQed.\n\nTheorem eq_signed:\n  forall x y, eq x y = if zeq (signed x) (signed y) then true else false.\nProof.\n  intros. predSpec eq eq_spec x y.\n  subst x. rewrite zeq_true; auto.\n  destruct (zeq (signed x) (signed y)); auto.\n  elim H. rewrite <- (repr_signed x). rewrite <- (repr_signed y). congruence.\nQed.\n\n(** ** Properties of addition *)\n\nTheorem add_unsigned: forall x y, add x y = repr (unsigned x + unsigned y).\nProof. intros; reflexivity.\nQed.\n\nTheorem add_signed: forall x y, add x y = repr (signed x + signed y).\nProof.\n  intros. rewrite add_unsigned. apply eqm_samerepr.\n  apply eqm_add; apply eqm_sym; apply eqm_signed_unsigned.\nQed.\n\nTheorem add_commut: forall x y, add x y = add y x.\nProof. intros; unfold add. decEq. lia. Qed.\n\nTheorem add_zero: forall x, add x zero = x.\nProof.\n  intros. unfold add. rewrite unsigned_zero.\n  rewrite Z.add_0_r. apply repr_unsigned.\nQed.\n\nTheorem add_zero_l: forall x, add zero x = x.\nProof.\n  intros. rewrite add_commut. apply add_zero.\nQed.\n\nTheorem add_assoc: forall x y z, add (add x y) z = add x (add y z).\nProof.\n  intros; unfold add.\n  set (x' := unsigned x).\n  set (y' := unsigned y).\n  set (z' := unsigned z).\n  apply eqm_samerepr.\n  apply eqm_trans with ((x' + y') + z').\n  auto with ints.\n  rewrite <- Z.add_assoc. auto with ints.\nQed.\n\nTheorem add_permut: forall x y z, add x (add y z) = add y (add x z).\nProof.\n  intros. rewrite (add_commut y z). rewrite <- add_assoc. apply add_commut.\nQed.\n\nTheorem add_neg_zero: forall x, add x (neg x) = zero.\nProof.\n  intros; unfold add, neg, zero. apply eqm_samerepr.\n  replace 0 with (unsigned x + (- (unsigned x))).\n  auto with ints. lia.\nQed.\n\nTheorem unsigned_add_carry:\n  forall x y,\n  unsigned (add x y) = unsigned x + unsigned y - unsigned (add_carry x y zero) * modulus.\nProof.\n  intros.\n  unfold add, add_carry. rewrite unsigned_zero. rewrite Z.add_0_r.\n  rewrite unsigned_repr_eq.\n  generalize (unsigned_range x) (unsigned_range y). intros.\n  destruct (zlt (unsigned x + unsigned y) modulus).\n  rewrite unsigned_zero. apply Zmod_unique with 0. lia. lia.\n  rewrite unsigned_one. apply Zmod_unique with 1. lia. lia.\nQed.\n\nCorollary unsigned_add_either:\n  forall x y,\n  unsigned (add x y) = unsigned x + unsigned y\n  \\/ unsigned (add x y) = unsigned x + unsigned y - modulus.\nProof.\n  intros. rewrite unsigned_add_carry. unfold add_carry.\n  rewrite unsigned_zero. rewrite Z.add_0_r.\n  destruct (zlt (unsigned x + unsigned y) modulus).\n  rewrite unsigned_zero. left; lia.\n  rewrite unsigned_one. right; lia.\nQed.\n\n(** ** Properties of negation *)\n\nTheorem neg_repr: forall z, neg (repr z) = repr (-z).\nProof.\n  intros; unfold neg. apply eqm_samerepr. auto with ints.\nQed.\n\nTheorem neg_zero: neg zero = zero.\nProof.\n  unfold neg. rewrite unsigned_zero. auto.\nQed.\n\nTheorem neg_involutive: forall x, neg (neg x) = x.\nProof.\n  intros; unfold neg.\n  apply eqm_repr_eq. eapply eqm_trans. apply eqm_neg.\n  apply eqm_unsigned_repr_l. apply eqm_refl. apply eqm_refl2. lia.\nQed.\n\nTheorem neg_add_distr: forall x y, neg(add x y) = add (neg x) (neg y).\nProof.\n  intros; unfold neg, add. apply eqm_samerepr.\n  apply eqm_trans with (- (unsigned x + unsigned y)).\n  auto with ints.\n  replace (- (unsigned x + unsigned y))\n     with ((- unsigned x) + (- unsigned y)).\n  auto with ints. lia.\nQed.\n\n(** ** Properties of subtraction *)\n\nTheorem sub_zero_l: forall x, sub x zero = x.\nProof.\n  intros; unfold sub. rewrite unsigned_zero.\n  replace (unsigned x - 0) with (unsigned x) by lia. apply repr_unsigned.\nQed.\n\nTheorem sub_zero_r: forall x, sub zero x = neg x.\nProof.\n  intros; unfold sub, neg. rewrite unsigned_zero. auto.\nQed.\n\nTheorem sub_add_opp: forall x y, sub x y = add x (neg y).\nProof.\n  intros; unfold sub, add, neg. apply eqm_samerepr.\n  apply eqm_add; auto with ints.\nQed.\n\nTheorem sub_idem: forall x, sub x x = zero.\nProof.\n  intros; unfold sub. unfold zero. decEq. lia.\nQed.\n\nTheorem sub_add_l: forall x y z, sub (add x y) z = add (sub x z) y.\nProof.\n  intros. repeat rewrite sub_add_opp.\n  repeat rewrite add_assoc. decEq. apply add_commut.\nQed.\n\nTheorem sub_add_r: forall x y z, sub x (add y z) = add (sub x z) (neg y).\nProof.\n  intros. repeat rewrite sub_add_opp.\n  rewrite neg_add_distr. rewrite add_permut. apply add_commut.\nQed.\n\nTheorem sub_shifted:\n  forall x y z,\n  sub (add x z) (add y z) = sub x y.\nProof.\n  intros. rewrite sub_add_opp. rewrite neg_add_distr.\n  rewrite add_assoc.\n  rewrite (add_commut (neg y) (neg z)).\n  rewrite <- (add_assoc z). rewrite add_neg_zero.\n  rewrite (add_commut zero). rewrite add_zero.\n  symmetry. apply sub_add_opp.\nQed.\n\nTheorem sub_signed:\n  forall x y, sub x y = repr (signed x - signed y).\nProof.\n  intros. unfold sub. apply eqm_samerepr.\n  apply eqm_sub; apply eqm_sym; apply eqm_signed_unsigned.\nQed.\n\nTheorem unsigned_sub_borrow:\n  forall x y,\n  unsigned (sub x y) = unsigned x - unsigned y + unsigned (sub_borrow x y zero) * modulus.\nProof.\n  intros.\n  unfold sub, sub_borrow. rewrite unsigned_zero. rewrite Z.sub_0_r.\n  rewrite unsigned_repr_eq.\n  generalize (unsigned_range x) (unsigned_range y). intros.\n  destruct (zlt (unsigned x - unsigned y) 0).\n  rewrite unsigned_one. apply Zmod_unique with (-1). lia. lia.\n  rewrite unsigned_zero. apply Zmod_unique with 0. lia. lia.\nQed.\n\n(** ** Properties of multiplication *)\n\nTheorem mul_commut: forall x y, mul x y = mul y x.\nProof.\n  intros; unfold mul. decEq. ring.\nQed.\n\nTheorem mul_zero: forall x, mul x zero = zero.\nProof.\n  intros; unfold mul. rewrite unsigned_zero.\n  unfold zero. decEq. ring.\nQed.\n\nTheorem mul_one: forall x, mul x one = x.\nProof.\n  intros; unfold mul. rewrite unsigned_one.\n  transitivity (repr (unsigned x)). decEq. ring.\n  apply repr_unsigned.\nQed.\n\nTheorem mul_mone: forall x, mul x mone = neg x.\nProof.\n  intros; unfold mul, neg. rewrite unsigned_mone.\n  apply eqm_samerepr.\n  replace (-unsigned x) with (0 - unsigned x) by lia.\n  replace (unsigned x * (modulus - 1)) with (unsigned x * modulus - unsigned x) by ring.\n  apply eqm_sub. exists (unsigned x). lia. apply eqm_refl.\nQed.\n\nTheorem mul_assoc: forall x y z, mul (mul x y) z = mul x (mul y z).\nProof.\n  intros; unfold mul.\n  set (x' := unsigned x).\n  set (y' := unsigned y).\n  set (z' := unsigned z).\n  apply eqm_samerepr. apply eqm_trans with ((x' * y') * z').\n  auto with ints.\n  rewrite <- Z.mul_assoc. auto with ints.\nQed.\n\nTheorem mul_add_distr_l:\n  forall x y z, mul (add x y) z = add (mul x z) (mul y z).\nProof.\n  intros; unfold mul, add.\n  apply eqm_samerepr.\n  set (x' := unsigned x).\n  set (y' := unsigned y).\n  set (z' := unsigned z).\n  apply eqm_trans with ((x' + y') * z').\n  auto with ints.\n  replace ((x' + y') * z') with (x' * z' + y' * z').\n  auto with ints.\n  ring.\nQed.\n\nTheorem mul_add_distr_r:\n  forall x y z, mul x (add y z) = add (mul x y) (mul x z).\nProof.\n  intros. rewrite mul_commut. rewrite mul_add_distr_l.\n  decEq; apply mul_commut.\nQed.\n\nTheorem neg_mul_distr_l:\n  forall x y, neg(mul x y) = mul (neg x) y.\nProof.\n  intros. unfold mul, neg.\n  set (x' := unsigned x).  set (y' := unsigned y).\n  apply eqm_samerepr. apply eqm_trans with (- (x' * y')).\n  auto with ints.\n  replace (- (x' * y')) with ((-x') * y') by ring.\n  auto with ints.\nQed.\n\nTheorem neg_mul_distr_r:\n   forall x y, neg(mul x y) = mul x (neg y).\nProof.\n  intros. rewrite (mul_commut x y). rewrite (mul_commut x (neg y)).\n  apply neg_mul_distr_l.\nQed.\n\nTheorem mul_signed:\n  forall x y, mul x y = repr (signed x * signed y).\nProof.\n  intros; unfold mul. apply eqm_samerepr.\n  apply eqm_mult; apply eqm_sym; apply eqm_signed_unsigned.\nQed.\n\n(** ** Properties of division and modulus *)\n\nLemma modu_divu_Euclid:\n  forall x y, y <> zero -> x = add (mul (divu x y) y) (modu x y).\nProof.\n  intros. unfold add, mul, divu, modu.\n  transitivity (repr (unsigned x)). auto with ints.\n  apply eqm_samerepr.\n  set (x' := unsigned x). set (y' := unsigned y).\n  apply eqm_trans with ((x' / y') * y' + x' mod y').\n  apply eqm_refl2. rewrite Z.mul_comm. apply Z_div_mod_eq.\n  generalize (unsigned_range y); intro.\n  assert (unsigned y <> 0). red; intro.\n  elim H. rewrite <- (repr_unsigned y). unfold zero. congruence.\n  unfold y'. lia.\n  auto with ints.\nQed.\n\nTheorem modu_divu:\n  forall x y, y <> zero -> modu x y = sub x (mul (divu x y) y).\nProof.\n  intros.\n  assert (forall a b c, a = add b c -> c = sub a b).\n  intros. subst a. rewrite sub_add_l. rewrite sub_idem.\n  rewrite add_commut. rewrite add_zero. auto.\n  apply H0. apply modu_divu_Euclid. auto.\nQed.\n\nLemma mods_divs_Euclid:\n  forall x y, x = add (mul (divs x y) y) (mods x y).\nProof.\n  intros. unfold add, mul, divs, mods.\n  transitivity (repr (signed x)). auto with ints.\n  apply eqm_samerepr.\n  set (x' := signed x). set (y' := signed y).\n  apply eqm_trans with ((Z.quot x' y') * y' + Z.rem x' y').\n  apply eqm_refl2. rewrite Z.mul_comm. apply Z.quot_rem'.\n  apply eqm_add; auto with ints.\n  apply eqm_unsigned_repr_r. apply eqm_mult; auto with ints.\n  unfold y'. apply eqm_signed_unsigned.\nQed.\n\nTheorem mods_divs:\n  forall x y, mods x y = sub x (mul (divs x y) y).\nProof.\n  intros.\n  assert (forall a b c, a = add b c -> c = sub a b).\n  intros. subst a. rewrite sub_add_l. rewrite sub_idem.\n  rewrite add_commut. rewrite add_zero. auto.\n  apply H. apply mods_divs_Euclid.\nQed.\n\nTheorem divu_one:\n  forall x, divu x one = x.\nProof.\n  unfold divu; intros. rewrite unsigned_one. rewrite Zdiv_1_r. apply repr_unsigned.\nQed.\n\nTheorem divs_one:\n  forall x, zwordsize > 1 -> divs x one = x.\nProof.\n  unfold divs; intros. rewrite signed_one. rewrite Z.quot_1_r. apply repr_signed. auto.\nQed.\n\nTheorem modu_one:\n  forall x, modu x one = zero.\nProof.\n  intros. rewrite modu_divu. rewrite divu_one. rewrite mul_one. apply sub_idem.\n  apply one_not_zero.\nQed.\n\nTheorem divs_mone:\n  forall x, divs x mone = neg x.\nProof.\n  unfold divs, neg; intros.\n  rewrite signed_mone.\n  replace (Z.quot (signed x) (-1)) with (- (signed x)).\n  apply eqm_samerepr. apply eqm_neg. apply eqm_signed_unsigned.\n  set (x' := signed x).\n  set (one := 1).\n  change (-1) with (- one). rewrite Zquot_opp_r.\n  assert (Z.quot x' one = x').\n  symmetry. apply Zquot_unique_full with 0. red.\n  change (Z.abs one) with 1.\n  destruct (zle 0 x'). left. lia. right. lia.\n  unfold one; ring.\n  congruence.\nQed.\n\nTheorem mods_mone:\n  forall x, mods x mone = zero.\nProof.\n  intros. rewrite mods_divs. rewrite divs_mone.\n  rewrite <- neg_mul_distr_l. rewrite mul_mone. rewrite neg_involutive. apply sub_idem.\nQed.\n\nTheorem divmodu2_divu_modu:\n  forall n d,\n  d <> zero -> divmodu2 zero n d = Some (divu n d, modu n d).\nProof.\n  unfold divmodu2, divu, modu; intros.\n  rewrite dec_eq_false by auto.\n  set (N := unsigned zero * modulus + unsigned n).\n  assert (E1: unsigned n = N) by (unfold N; rewrite unsigned_zero; ring). rewrite ! E1.\n  set (D := unsigned d).\n  set (Q := N / D); set (R := N mod D).\n  assert (E2: Z.div_eucl N D = (Q, R)).\n  { unfold Q, R, Z.div, Z.modulo. destruct (Z.div_eucl N D); auto. }\n  rewrite E2. rewrite zle_true. auto.\n  assert (unsigned d <> 0).\n  { red; intros. elim H. rewrite <- (repr_unsigned d). rewrite H0; auto. }\n  assert (0 < D).\n  { unfold D. generalize (unsigned_range d); intros. lia. }\n  assert (0 <= Q <= max_unsigned).\n  { unfold Q. apply Zdiv_interval_2.\n    rewrite <- E1; apply unsigned_range_2.\n    lia. unfold max_unsigned; generalize modulus_pos; lia. lia. }\n  lia.\nQed.\n\nLemma unsigned_signed:\n  forall n, unsigned n = if lt n zero then signed n + modulus else signed n.\nProof.\n  intros. unfold lt. rewrite signed_zero. unfold signed.\n  generalize (unsigned_range n). rewrite half_modulus_modulus. intros.\n  destruct (zlt (unsigned n) half_modulus).\n- rewrite zlt_false by lia. auto.\n- rewrite zlt_true by lia. ring.\nQed.\n\nTheorem divmods2_divs_mods:\n  forall n d,\n  d <> zero -> n <> repr min_signed \\/ d <> mone ->\n  divmods2 (if lt n zero then mone else zero) n d = Some (divs n d, mods n d).\nProof.\n  unfold divmods2, divs, mods; intros.\n  rewrite dec_eq_false by auto.\n  set (N := signed (if lt n zero then mone else zero) * modulus + unsigned n).\n  set (D := signed d).\n  assert (D <> 0).\n  { unfold D; red; intros. elim H. rewrite <- (repr_signed d). rewrite H1; auto. }\n  assert (N = signed n).\n  { unfold N. rewrite unsigned_signed. destruct (lt n zero).\n    rewrite signed_mone. ring.\n    rewrite signed_zero. ring. }\n  set (Q := Z.quot N D); set (R := Z.rem N D).\n  assert (E2: Z.quotrem N D = (Q, R)).\n  { unfold Q, R, Z.quot, Z.rem. destruct (Z.quotrem N D); auto. }\n  rewrite E2.\n  assert (min_signed <= N <= max_signed) by (rewrite H2; apply signed_range).\n  assert (min_signed <= Q <= max_signed).\n  { unfold Q. destruct (zeq D 1); [ | destruct (zeq D (-1))].\n  - (* D = 1 *)\n    rewrite e. rewrite Z.quot_1_r; auto.\n  - (* D = -1 *)\n    rewrite e. change (-1) with (Z.opp 1). rewrite Z.quot_opp_r by lia.\n    rewrite Z.quot_1_r.\n    assert (N <> min_signed).\n    { red; intros; destruct H0.\n    + elim H0. rewrite <- (repr_signed n). rewrite <- H2. rewrite H4. auto.\n    + elim H0. rewrite <- (repr_signed d). unfold D in e; rewrite e; auto. }\n    unfold min_signed, max_signed in *. lia.\n  - (* |D| > 1 *)\n    assert (Z.abs (Z.quot N D) < half_modulus).\n    { rewrite <- Z.quot_abs by lia. apply Zquot_lt_upper_bound.\n      extlia. extlia.\n      apply Z.le_lt_trans with (half_modulus * 1).\n      rewrite Z.mul_1_r. unfold min_signed, max_signed in H3; extlia.\n      apply Zmult_lt_compat_l. generalize half_modulus_pos; lia. extlia. }\n    rewrite Z.abs_lt in H4.\n    unfold min_signed, max_signed; lia.\n  }\n  unfold proj_sumbool; rewrite ! zle_true by lia; simpl.\n  unfold Q, R; rewrite H2; auto.\nQed.\n\n(** ** Bit-level properties *)\n\nDefinition testbit (x: int) (i: Z) : bool := Z.testbit (unsigned x) i.\n\nLemma testbit_repr:\n  forall x i,\n  0 <= i < zwordsize ->\n  testbit (repr x) i = Z.testbit x i.\nProof.\n  intros. unfold testbit. apply same_bits_eqm; auto with ints.\nQed.\n\nLemma same_bits_eq:\n  forall x y,\n  (forall i, 0 <= i < zwordsize -> testbit x i = testbit y i) ->\n  x = y.\nProof.\n  intros. rewrite <- (repr_unsigned x). rewrite <- (repr_unsigned y).\n  apply eqm_samerepr. apply eqm_same_bits. auto.\nQed.\n\nLemma bits_above:\n  forall x i, i >= zwordsize -> testbit x i = false.\nProof.\n  intros. apply Ztestbit_above with wordsize; auto. apply unsigned_range.\nQed.\n\nLemma bits_below:\n  forall x i, i < 0 -> testbit x i = false.\nProof.\n  intros. apply Z.testbit_neg_r; auto.\nQed.\n\nLemma bits_zero:\n  forall i, testbit zero i = false.\nProof.\n  intros. unfold testbit. rewrite unsigned_zero. apply Ztestbit_0.\nQed.\n\nRemark bits_one: forall n, testbit one n = zeq n 0.\nProof.\n  unfold testbit; intros. rewrite unsigned_one. apply Ztestbit_1.\nQed.\n\nLemma bits_mone:\n  forall i, 0 <= i < zwordsize -> testbit mone i = true.\nProof.\n  intros. unfold mone. rewrite testbit_repr; auto. apply Ztestbit_m1. lia.\nQed.\n\nHint Rewrite bits_zero bits_mone : ints.\n\nLtac bit_solve :=\n  intros; apply same_bits_eq; intros; autorewrite with ints; auto with bool.\n\nLemma sign_bit_of_unsigned:\n  forall x, testbit x (zwordsize - 1) = if zlt (unsigned x) half_modulus then false else true.\nProof.\n  intros. unfold testbit.\n  set (ws1 := Init.Nat.pred wordsize).\n  assert (zwordsize - 1 = Z.of_nat ws1).\n    unfold zwordsize, ws1, wordsize.\n    destruct WS.wordsize as [] eqn:E.\n    elim WS.wordsize_not_zero; auto.\n    rewrite Nat2Z.inj_succ. simpl. lia.\n  assert (half_modulus = two_power_nat ws1).\n    rewrite two_power_nat_two_p. rewrite <- H. apply half_modulus_power.\n  rewrite H; rewrite H0.\n  apply Zsign_bit. rewrite two_power_nat_S. rewrite <- H0.\n  rewrite <- half_modulus_modulus. apply unsigned_range.\nQed.\n\nLemma bits_signed:\n  forall x i, 0 <= i ->\n  Z.testbit (signed x) i = testbit x (if zlt i zwordsize then i else zwordsize - 1).\nProof.\n  intros.\n  destruct (zlt i zwordsize).\n  - apply same_bits_eqm. apply eqm_signed_unsigned. lia.\n  - unfold signed. rewrite sign_bit_of_unsigned. destruct (zlt (unsigned x) half_modulus).\n    + apply Ztestbit_above with wordsize. apply unsigned_range. auto.\n    + apply Ztestbit_above_neg with wordsize.\n      fold modulus. generalize (unsigned_range x). lia. auto.\nQed.\n\nLemma bits_le:\n  forall x y,\n  (forall i, 0 <= i < zwordsize -> testbit x i = true -> testbit y i = true) ->\n  unsigned x <= unsigned y.\nProof.\n  intros. apply Ztestbit_le. generalize (unsigned_range y); lia.\n  intros. fold (testbit y i). destruct (zlt i zwordsize).\n  apply H. lia. auto.\n  fold (testbit x i) in H1. rewrite bits_above in H1; auto. congruence.\nQed.\n\n(** ** Properties of bitwise and, or, xor *)\n\nLemma bits_and:\n  forall x y i, 0 <= i < zwordsize ->\n  testbit (and x y) i = testbit x i && testbit y i.\nProof.\n  intros. unfold and. rewrite testbit_repr; auto. rewrite Z.land_spec; intuition.\nQed.\n\nLemma bits_or:\n  forall x y i, 0 <= i < zwordsize ->\n  testbit (or x y) i = testbit x i || testbit y i.\nProof.\n  intros. unfold or. rewrite testbit_repr; auto. rewrite Z.lor_spec; intuition.\nQed.\n\nLemma bits_xor:\n  forall x y i, 0 <= i < zwordsize ->\n  testbit (xor x y) i = xorb (testbit x i) (testbit y i).\nProof.\n  intros. unfold xor. rewrite testbit_repr; auto. rewrite Z.lxor_spec; intuition.\nQed.\n\nLemma bits_not:\n  forall x i, 0 <= i < zwordsize ->\n  testbit (not x) i = negb (testbit x i).\nProof.\n  intros. unfold not. rewrite bits_xor; auto. rewrite bits_mone; auto.\nQed.\n\nHint Rewrite bits_and bits_or bits_xor bits_not: ints.\n\nTheorem and_commut: forall x y, and x y = and y x.\nProof.\n  bit_solve.\nQed.\n\nTheorem and_assoc: forall x y z, and (and x y) z = and x (and y z).\nProof.\n  bit_solve.\nQed.\n\nTheorem and_zero: forall x, and x zero = zero.\nProof.\n  bit_solve. apply andb_b_false.\nQed.\n\nCorollary and_zero_l: forall x, and zero x = zero.\nProof.\n  intros. rewrite and_commut. apply and_zero.\nQed.\n\nTheorem and_mone: forall x, and x mone = x.\nProof.\n  bit_solve. apply andb_b_true.\nQed.\n\nCorollary and_mone_l: forall x, and mone x = x.\nProof.\n  intros. rewrite and_commut. apply and_mone.\nQed.\n\nTheorem and_idem: forall x, and x x = x.\nProof.\n  bit_solve. destruct (testbit x i); auto.\nQed.\n\nTheorem or_commut: forall x y, or x y = or y x.\nProof.\n  bit_solve.\nQed.\n\nTheorem or_assoc: forall x y z, or (or x y) z = or x (or y z).\nProof.\n  bit_solve.\nQed.\n\nTheorem or_zero: forall x, or x zero = x.\nProof.\n  bit_solve.\nQed.\n\nCorollary or_zero_l: forall x, or zero x = x.\nProof.\n  intros. rewrite or_commut. apply or_zero.\nQed.\n\nTheorem or_mone: forall x, or x mone = mone.\nProof.\n  bit_solve.\nQed.\n\nTheorem or_idem: forall x, or x x = x.\nProof.\n  bit_solve. destruct (testbit x i); auto.\nQed.\n\nTheorem and_or_distrib:\n  forall x y z,\n  and x (or y z) = or (and x y) (and x z).\nProof.\n  bit_solve. apply demorgan1.\nQed.\n\nCorollary and_or_distrib_l:\n  forall x y z,\n  and (or x y) z = or (and x z) (and y z).\nProof.\n  intros. rewrite (and_commut (or x y)). rewrite and_or_distrib. f_equal; apply and_commut.\nQed.\n\nTheorem or_and_distrib:\n  forall x y z,\n  or x (and y z) = and (or x y) (or x z).\nProof.\n  bit_solve. apply orb_andb_distrib_r.\nQed.\n\nCorollary or_and_distrib_l:\n  forall x y z,\n  or (and x y) z = and (or x z) (or y z).\nProof.\n  intros. rewrite (or_commut (and x y)). rewrite or_and_distrib. f_equal; apply or_commut.\nQed.\n\nTheorem and_or_absorb: forall x y, and x (or x y) = x.\nProof.\n  bit_solve.\n  assert (forall a b, a && (a || b) = a) by destr_bool.\n  auto.\nQed.\n\nTheorem or_and_absorb: forall x y, or x (and x y) = x.\nProof.\n  bit_solve.\n  assert (forall a b, a || (a && b) = a) by destr_bool.\n  auto.\nQed.\n\nTheorem xor_commut: forall x y, xor x y = xor y x.\nProof.\n  bit_solve. apply xorb_comm.\nQed.\n\nTheorem xor_assoc: forall x y z, xor (xor x y) z = xor x (xor y z).\nProof.\n  bit_solve. apply xorb_assoc.\nQed.\n\nTheorem xor_zero: forall x, xor x zero = x.\nProof.\n  bit_solve. apply xorb_false.\nQed.\n\nCorollary xor_zero_l: forall x, xor zero x = x.\nProof.\n  intros. rewrite xor_commut. apply xor_zero.\nQed.\n\nTheorem xor_idem: forall x, xor x x = zero.\nProof.\n  bit_solve. apply xorb_nilpotent.\nQed.\n\nTheorem xor_zero_one: xor zero one = one.\nProof. rewrite xor_commut. apply xor_zero. Qed.\n\nTheorem xor_one_one: xor one one = zero.\nProof. apply xor_idem. Qed.\n\nTheorem xor_zero_equal: forall x y, xor x y = zero -> x = y.\nProof.\n  intros. apply same_bits_eq; intros.\n  assert (xorb (testbit x i) (testbit y i) = false).\n    rewrite <- bits_xor; auto. rewrite H. apply bits_zero.\n  destruct (testbit x i); destruct (testbit y i); reflexivity || discriminate.\nQed.\n\nTheorem xor_is_zero: forall x y, eq (xor x y) zero = eq x y.\nProof.\n  intros. predSpec eq eq_spec (xor x y) zero.\n- apply xor_zero_equal in H. subst y. rewrite eq_true; auto. \n- predSpec eq eq_spec x y.\n+ elim H; subst y; apply xor_idem. \n+ auto.\nQed. \n\nTheorem and_xor_distrib:\n  forall x y z,\n  and x (xor y z) = xor (and x y) (and x z).\nProof.\n  bit_solve.\n  assert (forall a b c, a && (xorb b c) = xorb (a && b) (a && c)) by destr_bool.\n  auto.\nQed.\n\nTheorem and_le:\n  forall x y, unsigned (and x y) <= unsigned x.\nProof.\n  intros. apply bits_le; intros.\n  rewrite bits_and in H0; auto. rewrite andb_true_iff in H0. tauto.\nQed.\n\nTheorem or_le:\n  forall x y, unsigned x <= unsigned (or x y).\nProof.\n  intros. apply bits_le; intros.\n  rewrite bits_or; auto. rewrite H0; auto.\nQed.\n\n(** ** Properties of bitwise complement.*)\n\nTheorem not_involutive:\n  forall (x: int), not (not x) = x.\nProof.\n  intros. unfold not. rewrite xor_assoc. rewrite xor_idem. apply xor_zero.\nQed.\n\nTheorem not_zero:\n  not zero = mone.\nProof.\n  unfold not. rewrite xor_commut. apply xor_zero.\nQed.\n\nTheorem not_mone:\n  not mone = zero.\nProof.\n  rewrite <- (not_involutive zero). symmetry. decEq. apply not_zero.\nQed.\n\nTheorem not_or_and_not:\n  forall x y, not (or x y) = and (not x) (not y).\nProof.\n  bit_solve. apply negb_orb.\nQed.\n\nTheorem not_and_or_not:\n  forall x y, not (and x y) = or (not x) (not y).\nProof.\n  bit_solve. apply negb_andb.\nQed.\n\nTheorem and_not_self:\n  forall x, and x (not x) = zero.\nProof.\n  bit_solve.\nQed.\n\nTheorem or_not_self:\n  forall x, or x (not x) = mone.\nProof.\n  bit_solve.\nQed.\n\nTheorem xor_not_self:\n  forall x, xor x (not x) = mone.\nProof.\n  bit_solve. destruct (testbit x i); auto.\nQed.\n\nLemma unsigned_not:\n  forall x, unsigned (not x) = max_unsigned - unsigned x.\nProof.\n  intros. transitivity (unsigned (repr(-unsigned x - 1))).\n  f_equal. bit_solve. rewrite testbit_repr; auto. symmetry. apply Z_one_complement. lia.\n  rewrite unsigned_repr_eq. apply Zmod_unique with (-1).\n  unfold max_unsigned. lia.\n  generalize (unsigned_range x). unfold max_unsigned. lia.\nQed.\n\nTheorem not_neg:\n  forall x, not x = add (neg x) mone.\nProof.\n  bit_solve.\n  rewrite <- (repr_unsigned x) at 1. unfold add.\n  rewrite !testbit_repr; auto.\n  transitivity (Z.testbit (-unsigned x - 1) i).\n  symmetry. apply Z_one_complement. lia.\n  apply same_bits_eqm; auto.\n  replace (-unsigned x - 1) with (-unsigned x + (-1)) by lia.\n  apply eqm_add.\n  unfold neg. apply eqm_unsigned_repr.\n  rewrite unsigned_mone. exists (-1). ring.\nQed.\n\nTheorem neg_not:\n  forall x, neg x = add (not x) one.\nProof.\n  intros. rewrite not_neg. rewrite add_assoc.\n  replace (add mone one) with zero. rewrite add_zero. auto.\n  apply eqm_samerepr. rewrite unsigned_mone. rewrite unsigned_one.\n  exists (-1). ring.\nQed.\n\nTheorem sub_add_not:\n  forall x y, sub x y = add (add x (not y)) one.\nProof.\n  intros. rewrite sub_add_opp. rewrite neg_not.\n  rewrite ! add_assoc. auto.\nQed.\n\nTheorem sub_add_not_3:\n  forall x y b,\n  b = zero \\/ b = one ->\n  sub (sub x y) b = add (add x (not y)) (xor b one).\nProof.\n  intros. rewrite ! sub_add_not. rewrite ! add_assoc. f_equal. f_equal.\n  rewrite <- neg_not. rewrite <- sub_add_opp. destruct H; subst b.\n  rewrite xor_zero_l. rewrite sub_zero_l. auto.\n  rewrite xor_idem. rewrite sub_idem. auto.\nQed.\n\nTheorem sub_borrow_add_carry:\n  forall x y b,\n  b = zero \\/ b = one ->\n  sub_borrow x y b = xor (add_carry x (not y) (xor b one)) one.\nProof.\n  intros. unfold sub_borrow, add_carry. rewrite unsigned_not.\n  replace (unsigned (xor b one)) with (1 - unsigned b).\n  destruct (zlt (unsigned x - unsigned y - unsigned b)).\n  rewrite zlt_true. rewrite xor_zero_l; auto.\n  unfold max_unsigned; lia.\n  rewrite zlt_false. rewrite xor_idem; auto.\n  unfold max_unsigned; lia.\n  destruct H; subst b.\n  rewrite xor_zero_l. rewrite unsigned_one, unsigned_zero; auto.\n  rewrite xor_idem. rewrite unsigned_one, unsigned_zero; auto.\nQed.\n\n(** ** Connections between [add] and bitwise logical operations. *)\n\nLemma Z_add_is_or:\n  forall i, 0 <= i ->\n  forall x y,\n  (forall j, 0 <= j <= i -> Z.testbit x j && Z.testbit y j = false) ->\n  Z.testbit (x + y) i = Z.testbit x i || Z.testbit y i.\nProof.\n  intros i0 POS0. pattern i0. apply Zlt_0_ind; auto.\n  intros i IND POS x y EXCL.\n  rewrite (Zdecomp x) in *. rewrite (Zdecomp y) in *.\n  transitivity (Z.testbit (Zshiftin (Z.odd x || Z.odd y) (Z.div2 x + Z.div2 y)) i).\n  - f_equal. rewrite !Zshiftin_spec.\n    exploit (EXCL 0). lia. rewrite !Ztestbit_shiftin_base. intros.\nOpaque Z.mul.\n    destruct (Z.odd x); destruct (Z.odd y); simpl in *; discriminate || ring.\n  - rewrite !Ztestbit_shiftin; auto.\n    destruct (zeq i 0).\n    + auto.\n    + apply IND. lia. intros.\n      exploit (EXCL (Z.succ j)). lia.\n      rewrite !Ztestbit_shiftin_succ. auto.\n      lia. lia.\nQed.\n\nTheorem add_is_or:\n  forall x y,\n  and x y = zero ->\n  add x y = or x y.\nProof.\n  bit_solve. unfold add. rewrite testbit_repr; auto.\n  apply Z_add_is_or. lia.\n  intros.\n  assert (testbit (and x y) j = testbit zero j) by congruence.\n  autorewrite with ints in H2. assumption. lia.\nQed.\n\nTheorem xor_is_or:\n  forall x y, and x y = zero -> xor x y = or x y.\nProof.\n  bit_solve.\n  assert (testbit (and x y) i = testbit zero i) by congruence.\n  autorewrite with ints in H1; auto.\n  destruct (testbit x i); destruct (testbit y i); simpl in *; congruence.\nQed.\n\nTheorem add_is_xor:\n  forall x y,\n  and x y = zero ->\n  add x y = xor x y.\nProof.\n  intros. rewrite xor_is_or; auto. apply add_is_or; auto.\nQed.\n\nTheorem add_and:\n  forall x y z,\n  and y z = zero ->\n  add (and x y) (and x z) = and x (or y z).\nProof.\n  intros. rewrite add_is_or.\n  rewrite and_or_distrib; auto.\n  rewrite (and_commut x y).\n  rewrite and_assoc.\n  repeat rewrite <- (and_assoc x).\n  rewrite (and_commut (and x x)).\n  rewrite <- and_assoc.\n  rewrite H. rewrite and_commut. apply and_zero.\nQed.\n\n(** ** Properties of shifts *)\n\nLemma bits_shl:\n  forall x y i,\n  0 <= i < zwordsize ->\n  testbit (shl x y) i =\n  if zlt i (unsigned y) then false else testbit x (i - unsigned y).\nProof.\n  intros. unfold shl. rewrite testbit_repr; auto.\n  destruct (zlt i (unsigned y)).\n  apply Z.shiftl_spec_low. auto.\n  apply Z.shiftl_spec_high. lia. lia.\nQed.\n\nLemma bits_shru:\n  forall x y i,\n  0 <= i < zwordsize ->\n  testbit (shru x y) i =\n  if zlt (i + unsigned y) zwordsize then testbit x (i + unsigned y) else false.\nProof.\n  intros. unfold shru. rewrite testbit_repr; auto.\n  rewrite Z.shiftr_spec. fold (testbit x (i + unsigned y)).\n  destruct (zlt (i + unsigned y) zwordsize).\n  auto.\n  apply bits_above; auto.\n  lia.\nQed.\n\nLemma bits_shr:\n  forall x y i,\n  0 <= i < zwordsize ->\n  testbit (shr x y) i =\n  testbit x (if zlt (i + unsigned y) zwordsize then i + unsigned y else zwordsize - 1).\nProof.\n  intros. unfold shr. rewrite testbit_repr; auto.\n  rewrite Z.shiftr_spec. apply bits_signed.\n  generalize (unsigned_range y); lia.\n  lia.\nQed.\n\nHint Rewrite bits_shl bits_shru bits_shr: ints.\n\nTheorem shl_zero: forall x, shl x zero = x.\nProof.\n  bit_solve. rewrite unsigned_zero. rewrite zlt_false. f_equal; lia. lia.\nQed.\n\nLemma bitwise_binop_shl:\n  forall f f' x y n,\n  (forall x y i, 0 <= i < zwordsize -> testbit (f x y) i = f' (testbit x i) (testbit y i)) ->\n  f' false false = false ->\n  f (shl x n) (shl y n) = shl (f x y) n.\nProof.\n  intros. apply same_bits_eq; intros.\n  rewrite H; auto. rewrite !bits_shl; auto.\n  destruct (zlt i (unsigned n)); auto.\n  rewrite H; auto. generalize (unsigned_range n); lia.\nQed.\n\nTheorem and_shl:\n  forall x y n,\n  and (shl x n) (shl y n) = shl (and x y) n.\nProof.\n  intros. apply bitwise_binop_shl with andb. exact bits_and. auto.\nQed.\n\nTheorem or_shl:\n  forall x y n,\n  or (shl x n) (shl y n) = shl (or x y) n.\nProof.\n  intros. apply bitwise_binop_shl with orb. exact bits_or. auto.\nQed.\n\nTheorem xor_shl:\n  forall x y n,\n  xor (shl x n) (shl y n) = shl (xor x y) n.\nProof.\n  intros. apply bitwise_binop_shl with xorb. exact bits_xor. auto.\nQed.\n\nLemma ltu_inv:\n  forall x y, ltu x y = true -> 0 <= unsigned x < unsigned y.\nProof.\n  unfold ltu; intros. destruct (zlt (unsigned x) (unsigned y)).\n  split; auto. generalize (unsigned_range x); lia.\n  discriminate.\nQed.\n\nLemma ltu_iwordsize_inv:\n  forall x, ltu x iwordsize = true -> 0 <= unsigned x < zwordsize.\nProof.\n  intros. generalize (ltu_inv _ _ H). rewrite unsigned_repr_wordsize. auto.\nQed.\n\nTheorem shl_shl:\n  forall x y z,\n  ltu y iwordsize = true ->\n  ltu z iwordsize = true ->\n  ltu (add y z) iwordsize = true ->\n  shl (shl x y) z = shl x (add y z).\nProof.\n  intros.\n  generalize (ltu_iwordsize_inv _ H) (ltu_iwordsize_inv _ H0); intros.\n  assert (unsigned (add y z) = unsigned y + unsigned z).\n    unfold add. apply unsigned_repr.\n    generalize two_wordsize_max_unsigned; lia.\n  apply same_bits_eq; intros.\n  rewrite bits_shl; auto.\n  destruct (zlt i (unsigned z)).\n  - rewrite bits_shl; auto. rewrite zlt_true. auto. lia.\n  - rewrite bits_shl. destruct (zlt (i - unsigned z) (unsigned y)).\n    + rewrite bits_shl; auto. rewrite zlt_true. auto. lia.\n    + rewrite bits_shl; auto. rewrite zlt_false. f_equal. lia. lia.\n    + lia.\nQed.\n\nTheorem sub_ltu:\n  forall x y,\n    ltu x y = true ->\n    0 <= unsigned y - unsigned x <= unsigned y.\nProof.\n  intros.\n  generalize (ltu_inv x y H). intros .\n  split. lia. lia.\nQed.\n\nTheorem shru_zero: forall x, shru x zero = x.\nProof.\n  bit_solve. rewrite unsigned_zero. rewrite zlt_true. f_equal; lia. lia.\nQed.\n\nLemma bitwise_binop_shru:\n  forall f f' x y n,\n  (forall x y i, 0 <= i < zwordsize -> testbit (f x y) i = f' (testbit x i) (testbit y i)) ->\n  f' false false = false ->\n  f (shru x n) (shru y n) = shru (f x y) n.\nProof.\n  intros. apply same_bits_eq; intros.\n  rewrite H; auto. rewrite !bits_shru; auto.\n  destruct (zlt (i + unsigned n) zwordsize); auto.\n  rewrite H; auto. generalize (unsigned_range n); lia.\nQed.\n\nTheorem and_shru:\n  forall x y n,\n  and (shru x n) (shru y n) = shru (and x y) n.\nProof.\n  intros. apply bitwise_binop_shru with andb; auto. exact bits_and.\nQed.\n\nTheorem or_shru:\n  forall x y n,\n  or (shru x n) (shru y n) = shru (or x y) n.\nProof.\n  intros. apply bitwise_binop_shru with orb; auto. exact bits_or.\nQed.\n\nTheorem xor_shru:\n  forall x y n,\n  xor (shru x n) (shru y n) = shru (xor x y) n.\nProof.\n  intros. apply bitwise_binop_shru with xorb; auto. exact bits_xor.\nQed.\n\nTheorem shru_shru:\n  forall x y z,\n  ltu y iwordsize = true ->\n  ltu z iwordsize = true ->\n  ltu (add y z) iwordsize = true ->\n  shru (shru x y) z = shru x (add y z).\nProof.\n  intros.\n  generalize (ltu_iwordsize_inv _ H) (ltu_iwordsize_inv _ H0); intros.\n  assert (unsigned (add y z) = unsigned y + unsigned z).\n    unfold add. apply unsigned_repr.\n    generalize two_wordsize_max_unsigned; lia.\n  apply same_bits_eq; intros.\n  rewrite bits_shru; auto.\n  destruct (zlt (i + unsigned z) zwordsize).\n  - rewrite bits_shru. destruct (zlt (i + unsigned z + unsigned y) zwordsize).\n    + rewrite bits_shru; auto. rewrite zlt_true. f_equal. lia. lia.\n    + rewrite bits_shru; auto. rewrite zlt_false. auto. lia.\n    + lia.\n  - rewrite bits_shru; auto. rewrite zlt_false. auto. lia.\nQed.\n\nTheorem shr_zero: forall x, shr x zero = x.\nProof.\n  bit_solve. rewrite unsigned_zero. rewrite zlt_true. f_equal; lia. lia.\nQed.\n\nLemma bitwise_binop_shr:\n  forall f f' x y n,\n  (forall x y i, 0 <= i < zwordsize -> testbit (f x y) i = f' (testbit x i) (testbit y i)) ->\n  f (shr x n) (shr y n) = shr (f x y) n.\nProof.\n  intros. apply same_bits_eq; intros.\n  rewrite H; auto. rewrite !bits_shr; auto.\n  rewrite H; auto.\n  destruct (zlt (i + unsigned n) zwordsize).\n  generalize (unsigned_range n); lia.\n  lia.\nQed.\n\nTheorem and_shr:\n  forall x y n,\n  and (shr x n) (shr y n) = shr (and x y) n.\nProof.\n  intros. apply bitwise_binop_shr with andb. exact bits_and.\nQed.\n\nTheorem or_shr:\n  forall x y n,\n  or (shr x n) (shr y n) = shr (or x y) n.\nProof.\n  intros. apply bitwise_binop_shr with orb. exact bits_or.\nQed.\n\nTheorem xor_shr:\n  forall x y n,\n  xor (shr x n) (shr y n) = shr (xor x y) n.\nProof.\n  intros. apply bitwise_binop_shr with xorb. exact bits_xor.\nQed.\n\nTheorem shr_shr:\n  forall x y z,\n  ltu y iwordsize = true ->\n  ltu z iwordsize = true ->\n  ltu (add y z) iwordsize = true ->\n  shr (shr x y) z = shr x (add y z).\nProof.\n  intros.\n  generalize (ltu_iwordsize_inv _ H) (ltu_iwordsize_inv _ H0); intros.\n  assert (unsigned (add y z) = unsigned y + unsigned z).\n    unfold add. apply unsigned_repr.\n    generalize two_wordsize_max_unsigned; lia.\n  apply same_bits_eq; intros.\n  rewrite !bits_shr; auto. f_equal.\n  destruct (zlt (i + unsigned z) zwordsize).\n  rewrite H4. replace (i + (unsigned y + unsigned z)) with (i + unsigned z + unsigned y) by lia. auto.\n  rewrite (zlt_false _ (i + unsigned (add y z))).\n  destruct (zlt (zwordsize - 1 + unsigned y) zwordsize); lia.\n  lia.\n  destruct (zlt (i + unsigned z) zwordsize); lia.\nQed.\n\nTheorem and_shr_shru:\n  forall x y z,\n  and (shr x z) (shru y z) = shru (and x y) z.\nProof.\n  intros. apply same_bits_eq; intros.\n  rewrite bits_and; auto. rewrite bits_shr; auto. rewrite !bits_shru; auto.\n  destruct (zlt (i + unsigned z) zwordsize).\n  - rewrite bits_and; auto. generalize (unsigned_range z); lia.\n  - apply andb_false_r.\nQed.\n\nTheorem shr_and_shru_and:\n  forall x y z,\n  shru (shl z y) y = z ->\n  and (shr x y) z = and (shru x y) z.\nProof.\n  intros.\n  rewrite <- H.\n  rewrite and_shru. rewrite and_shr_shru. auto.\nQed.\n\nTheorem shru_lt_zero:\n  forall x,\n  shru x (repr (zwordsize - 1)) = if lt x zero then one else zero.\nProof.\n  intros. apply same_bits_eq; intros.\n  rewrite bits_shru; auto.\n  rewrite unsigned_repr.\n  destruct (zeq i 0).\n  subst i. rewrite Z.add_0_l. rewrite zlt_true.\n  rewrite sign_bit_of_unsigned.\n  unfold lt. rewrite signed_zero. unfold signed.\n  destruct (zlt (unsigned x) half_modulus).\n  rewrite zlt_false. auto. generalize (unsigned_range x); lia.\n  rewrite zlt_true. unfold one; rewrite testbit_repr; auto.\n  generalize (unsigned_range x); lia.\n  lia.\n  rewrite zlt_false.\n  unfold testbit. rewrite Ztestbit_eq. rewrite zeq_false.\n  destruct (lt x zero).\n  rewrite unsigned_one. simpl Z.div2. rewrite Z.testbit_0_l; auto.\n  rewrite unsigned_zero. simpl Z.div2. rewrite Z.testbit_0_l; auto.\n  auto. lia. lia.\n  generalize wordsize_max_unsigned; lia.\nQed.\n\nTheorem shr_lt_zero:\n  forall x,\n  shr x (repr (zwordsize - 1)) = if lt x zero then mone else zero.\nProof.\n  intros. apply same_bits_eq; intros.\n  rewrite bits_shr; auto.\n  rewrite unsigned_repr.\n  transitivity (testbit x (zwordsize - 1)).\n  f_equal. destruct (zlt (i + (zwordsize - 1)) zwordsize); lia.\n  rewrite sign_bit_of_unsigned.\n  unfold lt. rewrite signed_zero. unfold signed.\n  destruct (zlt (unsigned x) half_modulus).\n  rewrite zlt_false. rewrite bits_zero; auto. generalize (unsigned_range x); lia.\n  rewrite zlt_true. rewrite bits_mone; auto. generalize (unsigned_range x); lia.\n  generalize wordsize_max_unsigned; lia.\nQed.\n\n(** ** Properties of rotations *)\n\nLemma bits_rol:\n  forall x y i,\n  0 <= i < zwordsize ->\n  testbit (rol x y) i = testbit x ((i - unsigned y) mod zwordsize).\nProof.\n  intros. unfold rol.\n  exploit (Z_div_mod_eq (unsigned y) zwordsize). apply wordsize_pos.\n  set (j := unsigned y mod zwordsize). set (k := unsigned y / zwordsize).\n  intros EQ.\n  exploit (Z_mod_lt (unsigned y) zwordsize). apply wordsize_pos.\n  fold j. intros RANGE.\n  rewrite testbit_repr; auto.\n  rewrite Z.lor_spec. rewrite Z.shiftr_spec. 2: lia.\n  destruct (zlt i j).\n  - rewrite Z.shiftl_spec_low; auto. simpl.\n    unfold testbit. f_equal.\n    symmetry. apply Zmod_unique with (-k - 1).\n    rewrite EQ. ring.\n    lia.\n  - rewrite Z.shiftl_spec_high.\n    fold (testbit x (i + (zwordsize - j))).\n    rewrite bits_above. rewrite orb_false_r.\n    fold (testbit x (i - j)).\n    f_equal. symmetry. apply Zmod_unique with (-k).\n    rewrite EQ. ring.\n    lia. lia. lia. lia.\nQed.\n\nLemma bits_ror:\n  forall x y i,\n  0 <= i < zwordsize ->\n  testbit (ror x y) i = testbit x ((i + unsigned y) mod zwordsize).\nProof.\n  intros. unfold ror.\n  exploit (Z_div_mod_eq (unsigned y) zwordsize). apply wordsize_pos.\n  set (j := unsigned y mod zwordsize). set (k := unsigned y / zwordsize).\n  intros EQ.\n  exploit (Z_mod_lt (unsigned y) zwordsize). apply wordsize_pos.\n  fold j. intros RANGE.\n  rewrite testbit_repr; auto.\n  rewrite Z.lor_spec. rewrite Z.shiftr_spec. 2: lia.\n  destruct (zlt (i + j) zwordsize).\n  - rewrite Z.shiftl_spec_low; auto. rewrite orb_false_r.\n    unfold testbit. f_equal.\n    symmetry. apply Zmod_unique with k.\n    rewrite EQ. ring.\n    lia. lia.\n  - rewrite Z.shiftl_spec_high.\n    fold (testbit x (i + j)).\n    rewrite bits_above. simpl.\n    unfold testbit. f_equal.\n    symmetry. apply Zmod_unique with (k + 1).\n    rewrite EQ. ring.\n    lia. lia. lia. lia.\nQed.\n\nHint Rewrite bits_rol bits_ror: ints.\n\nTheorem shl_rolm:\n  forall x n,\n  ltu n iwordsize = true ->\n  shl x n = rolm x n (shl mone n).\nProof.\n  intros. generalize (ltu_inv _ _ H). rewrite unsigned_repr_wordsize; intros.\n  unfold rolm. apply same_bits_eq; intros.\n  rewrite bits_and; auto. rewrite !bits_shl; auto. rewrite bits_rol; auto.\n  destruct (zlt i (unsigned n)).\n  - rewrite andb_false_r; auto.\n  - generalize (unsigned_range n); intros.\n    rewrite bits_mone. rewrite andb_true_r. f_equal.\n    symmetry. apply Z.mod_small. lia.\n    lia.\nQed.\n\nTheorem shru_rolm:\n  forall x n,\n  ltu n iwordsize = true ->\n  shru x n = rolm x (sub iwordsize n) (shru mone n).\nProof.\n  intros. generalize (ltu_inv _ _ H). rewrite unsigned_repr_wordsize; intros.\n  unfold rolm. apply same_bits_eq; intros.\n  rewrite bits_and; auto. rewrite !bits_shru; auto. rewrite bits_rol; auto.\n  destruct (zlt (i + unsigned n) zwordsize).\n  - generalize (unsigned_range n); intros.\n    rewrite bits_mone. rewrite andb_true_r. f_equal.\n    unfold sub. rewrite unsigned_repr. rewrite unsigned_repr_wordsize.\n    symmetry. apply Zmod_unique with (-1). ring. lia.\n    rewrite unsigned_repr_wordsize. generalize wordsize_max_unsigned. lia.\n    lia.\n  - rewrite andb_false_r; auto.\nQed.\n\nTheorem rol_zero:\n  forall x,\n  rol x zero = x.\nProof.\n  bit_solve. f_equal. rewrite unsigned_zero. rewrite Z.sub_0_r.\n  apply Z.mod_small; auto.\nQed.\n\nLemma bitwise_binop_rol:\n  forall f f' x y n,\n  (forall x y i, 0 <= i < zwordsize -> testbit (f x y) i = f' (testbit x i) (testbit y i)) ->\n  rol (f x y) n = f (rol x n) (rol y n).\nProof.\n  intros. apply same_bits_eq; intros.\n  rewrite H; auto. rewrite !bits_rol; auto. rewrite H; auto.\n  apply Z_mod_lt. apply wordsize_pos.\nQed.\n\nTheorem rol_and:\n  forall x y n,\n  rol (and x y) n = and (rol x n) (rol y n).\nProof.\n  intros. apply bitwise_binop_rol with andb. exact bits_and.\nQed.\n\nTheorem rol_or:\n  forall x y n,\n  rol (or x y) n = or (rol x n) (rol y n).\nProof.\n  intros. apply bitwise_binop_rol with orb. exact bits_or.\nQed.\n\nTheorem rol_xor:\n  forall x y n,\n  rol (xor x y) n = xor (rol x n) (rol y n).\nProof.\n  intros. apply bitwise_binop_rol with xorb. exact bits_xor.\nQed.\n\nTheorem rol_rol:\n  forall x n m,\n  Z.divide zwordsize modulus ->\n  rol (rol x n) m = rol x (modu (add n m) iwordsize).\nProof.\n  bit_solve. f_equal. apply eqmod_mod_eq. apply wordsize_pos.\n  set (M := unsigned m); set (N := unsigned n).\n  apply eqmod_trans with (i - M - N).\n  apply eqmod_sub.\n  apply eqmod_sym. apply eqmod_mod. apply wordsize_pos.\n  apply eqmod_refl.\n  replace (i - M - N) with (i - (M + N)) by lia.\n  apply eqmod_sub.\n  apply eqmod_refl.\n  apply eqmod_trans with (Z.modulo (unsigned n + unsigned m) zwordsize).\n  replace (M + N) with (N + M) by lia. apply eqmod_mod. apply wordsize_pos.\n  unfold modu, add. fold M; fold N. rewrite unsigned_repr_wordsize.\n  assert (forall a, eqmod zwordsize a (unsigned (repr a))).\n    intros. eapply eqmod_divides. apply eqm_unsigned_repr. assumption.\n  eapply eqmod_trans. 2: apply H1.\n  apply eqmod_refl2. apply eqmod_mod_eq. apply wordsize_pos. auto.\n  apply Z_mod_lt. apply wordsize_pos.\nQed.\n\nTheorem rolm_zero:\n  forall x m,\n  rolm x zero m = and x m.\nProof.\n  intros. unfold rolm. rewrite rol_zero. auto.\nQed.\n\nTheorem rolm_rolm:\n  forall x n1 m1 n2 m2,\n  Z.divide zwordsize modulus ->\n  rolm (rolm x n1 m1) n2 m2 =\n    rolm x (modu (add n1 n2) iwordsize)\n           (and (rol m1 n2) m2).\nProof.\n  intros.\n  unfold rolm. rewrite rol_and. rewrite and_assoc.\n  rewrite rol_rol. reflexivity. auto.\nQed.\n\nTheorem or_rolm:\n  forall x n m1 m2,\n  or (rolm x n m1) (rolm x n m2) = rolm x n (or m1 m2).\nProof.\n  intros; unfold rolm. symmetry. apply and_or_distrib.\nQed.\n\nTheorem ror_rol:\n  forall x y,\n  ltu y iwordsize = true ->\n  ror x y = rol x (sub iwordsize y).\nProof.\n  intros.\n  generalize (ltu_iwordsize_inv _ H); intros.\n  apply same_bits_eq; intros.\n  rewrite bits_ror; auto. rewrite bits_rol; auto. f_equal.\n  unfold sub. rewrite unsigned_repr. rewrite unsigned_repr_wordsize.\n  apply eqmod_mod_eq. apply wordsize_pos. exists 1. ring.\n  rewrite unsigned_repr_wordsize.\n  generalize wordsize_pos; generalize wordsize_max_unsigned; lia.\nQed.\n\nTheorem ror_rol_neg:\n  forall x y, (zwordsize | modulus) -> ror x y = rol x (neg y).\nProof.\n  intros. apply same_bits_eq; intros.\n  rewrite bits_ror by auto. rewrite bits_rol by auto.\n  f_equal. apply eqmod_mod_eq. lia.\n  apply eqmod_trans with (i - (- unsigned y)).\n  apply eqmod_refl2; lia.\n  apply eqmod_sub. apply eqmod_refl.\n  apply eqmod_divides with modulus.\n  apply eqm_unsigned_repr. auto.\nQed.\n\nTheorem or_ror:\n  forall x y z,\n  ltu y iwordsize = true ->\n  ltu z iwordsize = true ->\n  add y z = iwordsize ->\n  ror x z = or (shl x y) (shru x z).\nProof.\n  intros.\n  generalize (ltu_iwordsize_inv _ H) (ltu_iwordsize_inv _ H0); intros.\n  unfold ror, or, shl, shru. apply same_bits_eq; intros.\n  rewrite !testbit_repr; auto.\n  rewrite !Z.lor_spec. rewrite orb_comm. f_equal; apply same_bits_eqm; auto.\n  - apply eqm_unsigned_repr_r. apply eqm_refl2. f_equal.\n    rewrite Z.mod_small; auto.\n    assert (unsigned (add y z) = zwordsize).\n      rewrite H1. apply unsigned_repr_wordsize.\n    unfold add in H5. rewrite unsigned_repr in H5.\n    lia.\n    generalize two_wordsize_max_unsigned; lia.\n  - apply eqm_unsigned_repr_r. apply eqm_refl2. f_equal.\n    apply Z.mod_small; auto.\nQed.\n\n(** ** Properties of [is_power2]. *)\n\nRemark is_power2_inv:\n  forall n logn,\n  is_power2 n = Some logn ->\n  Z_is_power2 (unsigned n) = Some (unsigned logn) /\\ 0 <= unsigned logn < zwordsize.\nProof.\n  unfold is_power2; intros.\n  destruct (Z_is_power2 (unsigned n)) as [i|] eqn:E; inv H.\n  assert (0 <= i < zwordsize).\n  { apply Z_is_power2_range with (unsigned n). \n    generalize wordsize_pos; lia.\n    rewrite <- modulus_power. apply unsigned_range.\n    auto. }\n  rewrite unsigned_repr; auto. generalize wordsize_max_unsigned; lia.\nQed.\n\nLemma is_power2_rng:\n  forall n logn,\n  is_power2 n = Some logn ->\n  0 <= unsigned logn < zwordsize.\nProof.\n  intros. apply (is_power2_inv n logn); auto.\nQed.\n\nTheorem is_power2_range:\n  forall n logn,\n  is_power2 n = Some logn -> ltu logn iwordsize = true.\nProof.\n  intros. unfold ltu. rewrite unsigned_repr_wordsize.\n  apply zlt_true. generalize (is_power2_rng _ _ H). tauto.\nQed.\n\nLemma is_power2_correct:\n  forall n logn,\n  is_power2 n = Some logn ->\n  unsigned n = two_p (unsigned logn).\nProof.\n  intros. apply is_power2_inv in H. destruct H as [P Q].\n  apply Z_is_power2_sound in P. tauto.\nQed.\n\nRemark two_p_range:\n  forall n,\n  0 <= n < zwordsize ->\n  0 <= two_p n <= max_unsigned.\nProof.\n  intros. split.\n  assert (two_p n > 0). apply two_p_gt_ZERO. lia. lia.\n  generalize (two_p_monotone_strict _ _ H).\n  unfold zwordsize; rewrite <- two_power_nat_two_p.\n  unfold max_unsigned, modulus. lia.\nQed.\n\nLemma is_power2_two_p:\n  forall n, 0 <= n < zwordsize ->\n  is_power2 (repr (two_p n)) = Some (repr n).\nProof.\n  intros. unfold is_power2. rewrite unsigned_repr.\n  rewrite Z_is_power2_complete by lia; auto.\n  apply two_p_range. auto.\nQed.\n\n(** ** Relation between bitwise operations and multiplications / divisions by powers of 2 *)\n\n(** Left shifts and multiplications by powers of 2. *)\n\nLemma shl_mul_two_p:\n  forall x y,\n  shl x y = mul x (repr (two_p (unsigned y))).\nProof.\n  intros. unfold shl, mul. apply eqm_samerepr.\n  rewrite Zshiftl_mul_two_p. auto with ints.\n  generalize (unsigned_range y); lia.\nQed.\n\nTheorem shl_mul:\n  forall x y,\n  shl x y = mul x (shl one y).\nProof.\n  intros.\n  assert (shl one y = repr (two_p (unsigned y))).\n  {\n    rewrite shl_mul_two_p. rewrite mul_commut. rewrite mul_one. auto.\n  }\n  rewrite H. apply shl_mul_two_p.\nQed.\n\nTheorem mul_pow2:\n  forall x n logn,\n  is_power2 n = Some logn ->\n  mul x n = shl x logn.\nProof.\n  intros. generalize (is_power2_correct n logn H); intro.\n  rewrite shl_mul_two_p. rewrite <- H0. rewrite repr_unsigned.\n  auto.\nQed.\n\nTheorem shifted_or_is_add:\n  forall x y n,\n  0 <= n < zwordsize ->\n  unsigned y < two_p n ->\n  or (shl x (repr n)) y = repr(unsigned x * two_p n + unsigned y).\nProof.\n  intros. rewrite <- add_is_or.\n  - unfold add. apply eqm_samerepr. apply eqm_add; auto with ints.\n    rewrite shl_mul_two_p. unfold mul. apply eqm_unsigned_repr_l.\n    apply eqm_mult; auto with ints. apply eqm_unsigned_repr_l.\n    apply eqm_refl2. rewrite unsigned_repr. auto.\n    generalize wordsize_max_unsigned; lia.\n  - bit_solve.\n    rewrite unsigned_repr.\n    destruct (zlt i n).\n    + auto.\n    + replace (testbit y i) with false. apply andb_false_r.\n      symmetry. unfold testbit.\n      assert (EQ: Z.of_nat (Z.to_nat n) = n) by (apply Z2Nat.id; lia).\n      apply Ztestbit_above with (Z.to_nat n).\n      rewrite <- EQ in H0. rewrite <- two_power_nat_two_p in H0.\n      generalize (unsigned_range y); lia.\n      rewrite EQ; auto.\n    + generalize wordsize_max_unsigned; lia.\nQed.\n\n(** Unsigned right shifts and unsigned divisions by powers of 2. *)\n\nLemma shru_div_two_p:\n  forall x y,\n  shru x y = repr (unsigned x / two_p (unsigned y)).\nProof.\n  intros. unfold shru.\n  rewrite Zshiftr_div_two_p. auto.\n  generalize (unsigned_range y); lia.\nQed.\n\nTheorem divu_pow2:\n  forall x n logn,\n  is_power2 n = Some logn ->\n  divu x n = shru x logn.\nProof.\n  intros. generalize (is_power2_correct n logn H). intro.\n  symmetry. unfold divu. rewrite H0. apply shru_div_two_p.\nQed.\n\n(** Signed right shifts and signed divisions by powers of 2. *)\n\nLemma shr_div_two_p:\n  forall x y,\n  shr x y = repr (signed x / two_p (unsigned y)).\nProof.\n  intros. unfold shr.\n  rewrite Zshiftr_div_two_p. auto.\n  generalize (unsigned_range y); lia.\nQed.\n\nTheorem divs_pow2:\n  forall x n logn,\n  is_power2 n = Some logn ->\n  divs x n = shrx x logn.\nProof.\n  intros. generalize (is_power2_correct _ _ H); intro.\n  unfold shrx. rewrite shl_mul_two_p.\n  rewrite mul_commut. rewrite mul_one.\n  rewrite <- H0. rewrite repr_unsigned. auto.\nQed.\n\n(** Unsigned modulus over [2^n] is masking with [2^n-1]. *)\n\nTheorem modu_and:\n  forall x n logn,\n  is_power2 n = Some logn ->\n  modu x n = and x (sub n one).\nProof.\n  intros. generalize (is_power2_correct _ _ H); intro.\n  generalize (is_power2_rng _ _ H); intro.\n  apply same_bits_eq; intros.\n  rewrite bits_and; auto.\n  unfold sub. rewrite testbit_repr; auto.\n  rewrite H0. rewrite unsigned_one.\n  unfold modu. rewrite testbit_repr; auto. rewrite H0.\n  rewrite Ztestbit_mod_two_p. rewrite Ztestbit_two_p_m1.\n  destruct (zlt i (unsigned logn)).\n  rewrite andb_true_r; auto.\n  rewrite andb_false_r; auto.\n  tauto. tauto. tauto. tauto.\nQed.\n\n(** ** Properties of [shrx] (signed division by a power of 2) *)\n\nTheorem shrx_zero:\n  forall x, zwordsize > 1 -> shrx x zero = x.\nProof.\n  intros. unfold shrx. rewrite shl_zero. unfold divs. rewrite signed_one by auto.\n  rewrite Z.quot_1_r. apply repr_signed.\nQed. \n\nTheorem shrx_shr:\n  forall x y,\n  ltu y (repr (zwordsize - 1)) = true ->\n  shrx x y = shr (if lt x zero then add x (sub (shl one y) one) else x) y.\nProof.\n  intros.\n  set (uy := unsigned y).\n  assert (0 <= uy < zwordsize - 1).\n    generalize (ltu_inv _ _ H). rewrite unsigned_repr. auto.\n    generalize wordsize_pos wordsize_max_unsigned; lia.\n  rewrite shr_div_two_p. unfold shrx. unfold divs.\n  assert (shl one y = repr (two_p uy)).\n    transitivity (mul one (repr (two_p uy))).\n    symmetry. apply mul_pow2. replace y with (repr uy).\n    apply is_power2_two_p. lia. apply repr_unsigned.\n    rewrite mul_commut. apply mul_one.\n  assert (two_p uy > 0). apply two_p_gt_ZERO. lia.\n  assert (two_p uy < half_modulus).\n    rewrite half_modulus_power.\n    apply two_p_monotone_strict. auto.\n  assert (two_p uy < modulus).\n    rewrite modulus_power. apply two_p_monotone_strict. lia.\n  assert (unsigned (shl one y) = two_p uy).\n    rewrite H1. apply unsigned_repr. unfold max_unsigned. lia.\n  assert (signed (shl one y) = two_p uy).\n    rewrite H1. apply signed_repr.\n    unfold max_signed. generalize min_signed_neg. lia.\n  rewrite H6.\n  rewrite Zquot_Zdiv; auto.\n  unfold lt. rewrite signed_zero.\n  destruct (zlt (signed x) 0); auto.\n  rewrite add_signed.\n  assert (signed (sub (shl one y) one) = two_p uy - 1).\n    unfold sub. rewrite H5. rewrite unsigned_one.\n    apply signed_repr.\n    generalize min_signed_neg. unfold max_signed. lia.\n  rewrite H7. rewrite signed_repr. f_equal. f_equal. lia.\n  generalize (signed_range x). intros.\n  assert (two_p uy - 1 <= max_signed). unfold max_signed. lia. lia.\nQed.\n\nTheorem shrx_shr_2:\n  forall x y,\n  ltu y (repr (zwordsize - 1)) = true ->\n  shrx x y = shr (add x (shru (shr x (repr (zwordsize - 1))) (sub iwordsize y))) y.\nProof.\n  intros.\n  rewrite shrx_shr by auto. f_equal.\n  rewrite shr_lt_zero. destruct (lt x zero).\n- set (uy := unsigned y).\n  generalize (unsigned_range y); fold uy; intros.\n  assert (0 <= uy < zwordsize - 1).\n    generalize (ltu_inv _ _ H). rewrite unsigned_repr. auto.\n    generalize wordsize_pos wordsize_max_unsigned; lia.\n  assert (two_p uy < modulus).\n    rewrite modulus_power. apply two_p_monotone_strict. lia.\n  f_equal. rewrite shl_mul_two_p. fold uy. rewrite mul_commut. rewrite mul_one.\n  unfold sub. rewrite unsigned_one. rewrite unsigned_repr.\n  rewrite unsigned_repr_wordsize. fold uy.\n  apply same_bits_eq; intros. rewrite bits_shru by auto.\n  rewrite testbit_repr by auto. rewrite Ztestbit_two_p_m1 by lia.\n  rewrite unsigned_repr by (generalize wordsize_max_unsigned; lia).\n  destruct (zlt i uy).\n  rewrite zlt_true by lia. rewrite bits_mone by lia. auto.\n  rewrite zlt_false by lia. auto.\n  assert (two_p uy > 0) by (apply two_p_gt_ZERO; lia). unfold max_unsigned; lia.\n- replace (shru zero (sub iwordsize y)) with zero.\n  rewrite add_zero; auto.\n  bit_solve. destruct (zlt (i + unsigned (sub iwordsize y)) zwordsize); auto.\nQed.\n\nTheorem shrx_carry:\n  forall x y,\n  ltu y (repr (zwordsize - 1)) = true ->\n  shrx x y = add (shr x y) (shr_carry x y).\nProof.\n  intros. rewrite shrx_shr; auto. unfold shr_carry.\n  unfold lt. set (sx := signed x). rewrite signed_zero.\n  destruct (zlt sx 0); simpl.\n  2: rewrite add_zero; auto.\n  set (uy := unsigned y).\n  assert (0 <= uy < zwordsize - 1).\n    generalize (ltu_inv _ _ H). rewrite unsigned_repr. auto.\n    generalize wordsize_pos wordsize_max_unsigned; lia.\n  assert (shl one y = repr (two_p uy)).\n    rewrite shl_mul_two_p. rewrite mul_commut. apply mul_one.\n  assert (and x (sub (shl one y) one) = modu x (repr (two_p uy))).\n    symmetry. rewrite H1. apply modu_and with (logn := y).\n    rewrite is_power2_two_p. unfold uy. rewrite repr_unsigned. auto.\n    lia.\n  rewrite H2. rewrite H1.\n  repeat rewrite shr_div_two_p. fold sx. fold uy.\n  assert (two_p uy > 0). apply two_p_gt_ZERO. lia.\n  assert (two_p uy < modulus).\n    rewrite modulus_power. apply two_p_monotone_strict. lia.\n  assert (two_p uy < half_modulus).\n    rewrite half_modulus_power.\n    apply two_p_monotone_strict. auto.\n  assert (two_p uy < modulus).\n    rewrite modulus_power. apply two_p_monotone_strict. lia.\n  assert (sub (repr (two_p uy)) one = repr (two_p uy - 1)).\n    unfold sub. apply eqm_samerepr. apply eqm_sub. apply eqm_sym; apply eqm_unsigned_repr.\n    rewrite unsigned_one. apply eqm_refl.\n  rewrite H7. rewrite add_signed. fold sx.\n  rewrite (signed_repr (two_p uy - 1)). rewrite signed_repr.\n  unfold modu. rewrite unsigned_repr.\n  unfold eq. rewrite unsigned_zero. rewrite unsigned_repr.\n  assert (unsigned x mod two_p uy = sx mod two_p uy).\n    apply eqmod_mod_eq; auto. apply eqmod_divides with modulus.\n    fold eqm. unfold sx. apply eqm_sym. apply eqm_signed_unsigned.\n    unfold modulus. rewrite two_power_nat_two_p.\n    exists (two_p (zwordsize - uy)). rewrite <- two_p_is_exp.\n    f_equal. fold zwordsize; lia. lia. lia.\n  rewrite H8. rewrite Zdiv_shift; auto.\n  unfold add. apply eqm_samerepr. apply eqm_add.\n  apply eqm_unsigned_repr.\n  destruct (zeq (sx mod two_p uy) 0); simpl.\n  rewrite unsigned_zero. apply eqm_refl.\n  rewrite unsigned_one. apply eqm_refl.\n  generalize (Z_mod_lt (unsigned x) (two_p uy) H3). unfold max_unsigned. lia.\n  unfold max_unsigned; lia.\n  generalize (signed_range x). fold sx. intros. split. lia. unfold max_signed. lia.\n  generalize min_signed_neg. unfold max_signed. lia.\nQed.\n\n(** Connections between [shr] and [shru]. *)\n\nLemma shr_shru_positive:\n  forall x y,\n  signed x >= 0 ->\n  shr x y = shru x y.\nProof.\n  intros.\n  rewrite shr_div_two_p. rewrite shru_div_two_p.\n  rewrite signed_eq_unsigned. auto. apply signed_positive. auto.\nQed.\n\nLemma and_positive:\n  forall x y, signed y >= 0 -> signed (and x y) >= 0.\nProof.\n  intros.\n  assert (unsigned y < half_modulus). rewrite signed_positive in H. unfold max_signed in H; lia.\n  generalize (sign_bit_of_unsigned y). rewrite zlt_true; auto. intros A.\n  generalize (sign_bit_of_unsigned (and x y)). rewrite bits_and. rewrite A.\n  rewrite andb_false_r. unfold signed.\n  destruct (zlt (unsigned (and x y)) half_modulus).\n  intros. generalize (unsigned_range (and x y)); lia.\n  congruence.\n  generalize wordsize_pos; lia.\nQed.\n\nTheorem shr_and_is_shru_and:\n  forall x y z,\n  lt y zero = false -> shr (and x y) z = shru (and x y) z.\nProof.\n  intros. apply shr_shru_positive. apply and_positive.\n  unfold lt in H. rewrite signed_zero in H. destruct (zlt (signed y) 0). congruence. auto.\nQed.\n\n(** ** Properties of integer zero extension and sign extension. *)\n\nLemma bits_zero_ext:\n  forall n x i, 0 <= i ->\n  testbit (zero_ext n x) i = if zlt i n then testbit x i else false.\nProof.\n  intros. unfold zero_ext. destruct (zlt i zwordsize).\n  rewrite testbit_repr; auto. rewrite Zzero_ext_spec. auto. auto.\n  rewrite !bits_above; auto. destruct (zlt i n); auto.\nQed.\n\nLemma bits_sign_ext:\n  forall n x i, 0 <= i < zwordsize ->\n  testbit (sign_ext n x) i = testbit x (if zlt i n then i else n - 1).\nProof.\n  intros. unfold sign_ext.\n  rewrite testbit_repr; auto. apply Zsign_ext_spec. lia. \nQed.\n\nHint Rewrite bits_zero_ext bits_sign_ext: ints.\n\nTheorem zero_ext_above:\n  forall n x, n >= zwordsize -> zero_ext n x = x.\nProof.\n  intros. apply same_bits_eq; intros.\n  rewrite bits_zero_ext. apply zlt_true. lia. lia.\nQed.\n\nTheorem zero_ext_below:\n  forall n x, n <= 0 -> zero_ext n x = zero.\nProof.\n  intros. bit_solve. destruct (zlt i n); auto. apply bits_below; lia. lia.\nQed.\n\nTheorem sign_ext_above:\n  forall n x, n >= zwordsize -> sign_ext n x = x.\nProof.\n  intros. apply same_bits_eq; intros.\n  unfold sign_ext; rewrite testbit_repr; auto.\n  rewrite Zsign_ext_spec. rewrite zlt_true. auto. lia. lia.\nQed.\n\nTheorem sign_ext_below:\n  forall n x, n <= 0 -> sign_ext n x = zero.\nProof.\n  intros. bit_solve. apply bits_below. destruct (zlt i n); lia.\nQed.\n\nTheorem zero_ext_and:\n  forall n x, 0 <= n -> zero_ext n x = and x (repr (two_p n - 1)).\nProof.\n  bit_solve. rewrite testbit_repr; auto. rewrite Ztestbit_two_p_m1; intuition.\n  destruct (zlt i n).\n  rewrite andb_true_r; auto.\n  rewrite andb_false_r; auto.\n  tauto.\nQed.\n\nTheorem zero_ext_mod:\n  forall n x, 0 <= n < zwordsize ->\n  unsigned (zero_ext n x) = Z.modulo (unsigned x) (two_p n).\nProof.\n  intros. apply equal_same_bits. intros.\n  rewrite Ztestbit_mod_two_p; auto.\n  fold (testbit (zero_ext n x) i).\n  destruct (zlt i zwordsize).\n  rewrite bits_zero_ext; auto.\n  rewrite bits_above. rewrite zlt_false; auto. lia. lia.\n  lia.\nQed.\n\nTheorem zero_ext_widen:\n  forall x n n', 0 <= n <= n' ->\n  zero_ext n' (zero_ext n x) = zero_ext n x.\nProof.\n  bit_solve. destruct (zlt i n).\n  apply zlt_true. lia.\n  destruct (zlt i n'); auto.\n  tauto. tauto.\nQed.\n\nTheorem sign_ext_widen:\n  forall x n n', 0 < n <= n' ->\n  sign_ext n' (sign_ext n x) = sign_ext n x.\nProof.\n  intros. destruct (zlt n' zwordsize).\n  bit_solve. destruct (zlt i n').\n  auto.\n  rewrite (zlt_false _ i n).\n  destruct (zlt (n' - 1) n); f_equal; lia.\n  lia.\n  destruct (zlt i n'); lia.\n  apply sign_ext_above; auto.\nQed.\n\nTheorem sign_zero_ext_widen:\n  forall x n n', 0 <= n < n' ->\n  sign_ext n' (zero_ext n x) = zero_ext n x.\nProof.\n  intros. destruct (zlt n' zwordsize).\n  bit_solve.\n  destruct (zlt i n').\n  auto.\n  rewrite !zlt_false. auto. lia. lia. lia.\n  destruct (zlt i n'); lia.\n  apply sign_ext_above; auto.\nQed.\n\nTheorem zero_ext_narrow:\n  forall x n n', 0 <= n <= n' ->\n  zero_ext n (zero_ext n' x) = zero_ext n x.\nProof.\n  bit_solve. destruct (zlt i n).\n  apply zlt_true. lia.\n  auto.\n  lia. lia. lia.\nQed.\n\nTheorem sign_ext_narrow:\n  forall x n n', 0 < n <= n' ->\n  sign_ext n (sign_ext n' x) = sign_ext n x.\nProof.\n  intros. destruct (zlt n zwordsize).\n  bit_solve. destruct (zlt i n); f_equal; apply zlt_true; lia.\n  destruct (zlt i n); lia.\n  rewrite (sign_ext_above n'). auto. lia.\nQed.\n\nTheorem zero_sign_ext_narrow:\n  forall x n n', 0 < n <= n' ->\n  zero_ext n (sign_ext n' x) = zero_ext n x.\nProof.\n  intros. destruct (zlt n' zwordsize).\n  bit_solve.\n  destruct (zlt i n); auto.\n  rewrite zlt_true; auto. lia.\n  lia. lia.\n  rewrite sign_ext_above; auto.\nQed.\n\nTheorem zero_ext_idem:\n  forall n x, 0 <= n -> zero_ext n (zero_ext n x) = zero_ext n x.\nProof.\n  intros. apply zero_ext_widen. lia.\nQed.\n\nTheorem sign_ext_idem:\n  forall n x, 0 < n -> sign_ext n (sign_ext n x) = sign_ext n x.\nProof.\n  intros. apply sign_ext_widen. lia.\nQed.\n \nTheorem sign_ext_zero_ext:\n  forall n x, 0 < n -> sign_ext n (zero_ext n x) = sign_ext n x.\nProof.\n  intros. destruct (zlt n zwordsize).\n  bit_solve.\n  destruct (zlt i n).\n  rewrite zlt_true; auto.\n  rewrite zlt_true; auto. lia.\n  destruct (zlt i n); lia.\n  rewrite zero_ext_above; auto.\nQed.\n\nTheorem zero_ext_sign_ext:\n  forall n x, 0 < n -> zero_ext n (sign_ext n x) = zero_ext n x.\nProof.\n  intros. apply zero_sign_ext_narrow. lia.\nQed.\n\nTheorem sign_ext_equal_if_zero_equal:\n  forall n x y, 0 < n ->\n  zero_ext n x = zero_ext n y ->\n  sign_ext n x = sign_ext n y.\nProof.\n  intros. rewrite <- (sign_ext_zero_ext n x H).\n  rewrite <- (sign_ext_zero_ext n y H). congruence.\nQed.\n\nTheorem shru_shl:\n  forall x y z, ltu y iwordsize = true -> ltu z iwordsize = true ->\n  shru (shl x y) z =\n  if ltu z y then shl (zero_ext (zwordsize - unsigned y) x) (sub y z)\n             else zero_ext (zwordsize - unsigned z) (shru x (sub z y)).\nProof.\n  intros. apply ltu_iwordsize_inv in H; apply ltu_iwordsize_inv in H0.\n  unfold ltu. set (Y := unsigned y) in *; set (Z := unsigned z) in *.\n  apply same_bits_eq; intros. rewrite bits_shru by auto. fold Z.\n  destruct (zlt Z Y).\n- assert (A: unsigned (sub y z) = Y - Z).\n  { apply unsigned_repr. generalize wordsize_max_unsigned; lia. }\n  symmetry; rewrite bits_shl, A by lia.\n  destruct (zlt (i + Z) zwordsize).\n+ rewrite bits_shl by lia. fold Y.\n  destruct (zlt i (Y - Z)); [rewrite zlt_true by lia|rewrite zlt_false by lia]; auto.\n  rewrite bits_zero_ext by lia. rewrite zlt_true by lia. f_equal; lia.\n+ rewrite bits_zero_ext by lia. rewrite ! zlt_false by lia. auto.\n- assert (A: unsigned (sub z y) = Z - Y).\n  { apply unsigned_repr. generalize wordsize_max_unsigned; lia. }\n  rewrite bits_zero_ext, bits_shru, A by lia.\n  destruct (zlt (i + Z) zwordsize); [rewrite zlt_true by lia|rewrite zlt_false by lia]; auto.\n  rewrite bits_shl by lia. fold Y.\n  destruct (zlt (i + Z) Y).\n+ rewrite zlt_false by lia. auto.\n+ rewrite zlt_true by lia. f_equal; lia.\nQed.\n\nCorollary zero_ext_shru_shl:\n  forall n x,\n  0 < n < zwordsize ->\n  let y := repr (zwordsize - n) in\n  zero_ext n x = shru (shl x y) y.\nProof.\n  intros.\n  assert (A: unsigned y = zwordsize - n).\n  { unfold y. apply unsigned_repr. generalize wordsize_max_unsigned. lia. }\n  assert (B: ltu y iwordsize = true).\n  { unfold ltu; rewrite A, unsigned_repr_wordsize. apply zlt_true; lia. }\n  rewrite shru_shl by auto. unfold ltu; rewrite zlt_false by lia.\n  rewrite sub_idem, shru_zero. f_equal. rewrite A; lia.\nQed.\n\nTheorem shr_shl:\n  forall x y z, ltu y iwordsize = true -> ltu z iwordsize = true ->\n  shr (shl x y) z =\n  if ltu z y then shl (sign_ext (zwordsize - unsigned y) x) (sub y z)\n             else sign_ext (zwordsize - unsigned z) (shr x (sub z y)).\nProof.\n  intros. apply ltu_iwordsize_inv in H; apply ltu_iwordsize_inv in H0.\n  unfold ltu. set (Y := unsigned y) in *; set (Z := unsigned z) in *.\n  apply same_bits_eq; intros. rewrite bits_shr by auto. fold Z.\n  rewrite bits_shl by (destruct (zlt (i + Z) zwordsize); lia). fold Y.\n  destruct (zlt Z Y).\n- assert (A: unsigned (sub y z) = Y - Z).\n  { apply unsigned_repr. generalize wordsize_max_unsigned; lia. }\n  rewrite bits_shl, A by lia.\n  destruct (zlt i (Y - Z)).\n+ apply zlt_true. destruct (zlt (i + Z) zwordsize); lia.\n+ rewrite zlt_false by (destruct (zlt (i + Z) zwordsize); lia).\n  rewrite bits_sign_ext by lia. f_equal. \n  destruct (zlt (i + Z) zwordsize).\n  rewrite zlt_true by lia. lia.\n  rewrite zlt_false by lia. lia.\n- assert (A: unsigned (sub z y) = Z - Y).\n  { apply unsigned_repr. generalize wordsize_max_unsigned; lia. }\n  rewrite bits_sign_ext by lia.\n  rewrite bits_shr by (destruct (zlt i (zwordsize - Z)); lia).\n  rewrite A. rewrite zlt_false by (destruct (zlt (i + Z) zwordsize); lia).\n  f_equal. destruct (zlt i (zwordsize - Z)).\n+ rewrite ! zlt_true by lia. lia.\n+ rewrite ! zlt_false by lia. rewrite zlt_true by lia. lia.\nQed.\n\nCorollary sign_ext_shr_shl:\n  forall n x,\n  0 < n <= zwordsize ->\n  let y := repr (zwordsize - n) in\n  sign_ext n x = shr (shl x y) y.\nProof.\n  intros.\n  assert (A: unsigned y = zwordsize - n).\n  { unfold y. apply unsigned_repr. generalize wordsize_max_unsigned. lia. }\n  assert (B: ltu y iwordsize = true).\n  { unfold ltu; rewrite A, unsigned_repr_wordsize. apply zlt_true; lia. }\n  rewrite shr_shl by auto. unfold ltu; rewrite zlt_false by lia.\n  rewrite sub_idem, shr_zero. f_equal. rewrite A; lia.\nQed.\n\n(** [zero_ext n x] is the unique integer congruent to [x] modulo [2^n]\n    in the range [0...2^n-1]. *)\n\nLemma zero_ext_range:\n  forall n x, 0 <= n < zwordsize -> 0 <= unsigned (zero_ext n x) < two_p n.\nProof.\n  intros. rewrite zero_ext_mod; auto. apply Z_mod_lt. apply two_p_gt_ZERO. lia.\nQed.\n\nLemma eqmod_zero_ext:\n  forall n x, 0 <= n < zwordsize -> eqmod (two_p n) (unsigned (zero_ext n x)) (unsigned x).\nProof.\n  intros. rewrite zero_ext_mod; auto. apply eqmod_sym. apply eqmod_mod.\n  apply two_p_gt_ZERO. lia.\nQed.\n\n(** [sign_ext n x] is the unique integer congruent to [x] modulo [2^n]\n    in the range [-2^(n-1)...2^(n-1) - 1]. *)\n\nLemma sign_ext_range:\n  forall n x, 0 < n < zwordsize -> -two_p (n-1) <= signed (sign_ext n x) < two_p (n-1).\nProof.\n  intros. rewrite sign_ext_shr_shl by lia.\n  set (X := shl x (repr (zwordsize - n))).\n  assert (two_p (n - 1) > 0) by (apply two_p_gt_ZERO; lia).\n  assert (unsigned (repr (zwordsize - n)) = zwordsize - n).\n    apply unsigned_repr.\n    split. lia. generalize wordsize_max_unsigned; lia.\n  rewrite shr_div_two_p.\n  rewrite signed_repr.\n  rewrite H1.\n  apply Zdiv_interval_1.\n  lia. lia. apply two_p_gt_ZERO; lia.\n  replace (- two_p (n - 1) * two_p (zwordsize - n))\n     with (- (two_p (n - 1) * two_p (zwordsize - n))) by ring.\n  rewrite <- two_p_is_exp.\n  replace (n - 1 + (zwordsize - n)) with (zwordsize - 1) by lia.\n  rewrite <- half_modulus_power.\n  generalize (signed_range X). unfold min_signed, max_signed. lia.\n  lia. lia.\n  apply Zdiv_interval_2. apply signed_range.\n  generalize min_signed_neg; lia.\n  generalize max_signed_pos; lia.\n  rewrite H1. apply two_p_gt_ZERO. lia.\nQed.\n\nLemma eqmod_sign_ext':\n  forall n x, 0 < n < zwordsize ->\n  eqmod (two_p n) (unsigned (sign_ext n x)) (unsigned x).\nProof.\n  intros.\n  set (N := Z.to_nat n).\n  assert (Z.of_nat N = n) by (apply Z2Nat.id; lia).\n  rewrite <- H0. rewrite <- two_power_nat_two_p.\n  apply eqmod_same_bits; intros.\n  rewrite H0 in H1. rewrite H0.\n  fold (testbit (sign_ext n x) i). rewrite bits_sign_ext.\n  rewrite zlt_true. auto. lia. lia.\nQed.\n\nLemma eqmod_sign_ext:\n  forall n x, 0 < n < zwordsize ->\n  eqmod (two_p n) (signed (sign_ext n x)) (unsigned x).\nProof.\n  intros. apply eqmod_trans with (unsigned (sign_ext n x)).\n  apply eqmod_divides with modulus. apply eqm_signed_unsigned.\n  exists (two_p (zwordsize - n)).\n  unfold modulus. rewrite two_power_nat_two_p. fold zwordsize.\n  rewrite <- two_p_is_exp. f_equal. lia. lia. lia.\n  apply eqmod_sign_ext'; auto.\nQed.\n\n(** Combinations of shifts and zero/sign extensions *)\n\nLemma shl_zero_ext:\n  forall n m x, 0 <= n ->\n  shl (zero_ext n x) m = zero_ext (n + unsigned m) (shl x m).\nProof.\n  intros. apply same_bits_eq; intros.\n  rewrite bits_zero_ext, ! bits_shl by lia.\n  destruct (zlt i (unsigned m)).\n- rewrite zlt_true by lia; auto.\n- rewrite bits_zero_ext by lia.\n  destruct (zlt (i - unsigned m) n); [rewrite zlt_true by lia|rewrite zlt_false by lia]; auto.\nQed.\n\nLemma shl_sign_ext:\n  forall n m x, 0 < n ->\n  shl (sign_ext n x) m = sign_ext (n + unsigned m) (shl x m).\nProof.\n  intros. generalize (unsigned_range m); intros.\n  apply same_bits_eq; intros.\n  rewrite bits_sign_ext, ! bits_shl by lia.\n  destruct (zlt i (n + unsigned m)).\n- rewrite bits_shl by auto. destruct (zlt i (unsigned m)); auto.\n  rewrite bits_sign_ext by lia. f_equal. apply zlt_true. lia.\n- rewrite zlt_false by lia. rewrite bits_shl by lia. rewrite zlt_false by lia.\n  rewrite bits_sign_ext by lia. f_equal. rewrite zlt_false by lia. lia.\nQed.\n\nLemma shru_zero_ext:\n  forall n m x, 0 <= n ->\n  shru (zero_ext (n + unsigned m) x) m = zero_ext n (shru x m).\nProof.\n  intros. bit_solve.\n- destruct (zlt (i + unsigned m) zwordsize).\n* destruct (zlt i n); [rewrite zlt_true by lia|rewrite zlt_false by lia]; auto.\n* destruct (zlt i n); auto.\n- generalize (unsigned_range m); lia.\n- lia.\nQed.\n\nLemma shru_zero_ext_0:\n  forall n m x, n <= unsigned m ->\n  shru (zero_ext n x) m = zero.\nProof.\n  intros. bit_solve.\n- destruct (zlt (i + unsigned m) zwordsize); auto.\n  apply zlt_false. lia.\n- generalize (unsigned_range m); lia.\nQed.\n\nLemma shr_sign_ext:\n  forall n m x, 0 < n -> n + unsigned m < zwordsize ->\n  shr (sign_ext (n + unsigned m) x) m = sign_ext n (shr x m).\nProof.\n  intros. generalize (unsigned_range m); intros.\n  apply same_bits_eq; intros.\n  rewrite bits_sign_ext, bits_shr by auto.\n  rewrite bits_sign_ext, bits_shr.\n- f_equal.\n  destruct (zlt i n), (zlt (i + unsigned m) zwordsize).\n+ apply zlt_true; lia.\n+ apply zlt_true; lia.\n+ rewrite zlt_false by lia. rewrite zlt_true by lia. lia.\n+ rewrite zlt_false by lia. rewrite zlt_true by lia. lia.\n- destruct (zlt i n); lia.\n- destruct (zlt (i + unsigned m) zwordsize); lia.\nQed.\n\nLemma zero_ext_shru_min:\n  forall s x n, ltu n iwordsize = true ->\n  zero_ext s (shru x n) = zero_ext (Z.min s (zwordsize - unsigned n)) (shru x n).\nProof.\n  intros. apply ltu_iwordsize_inv in H.\n  apply Z.min_case_strong; intros; auto.\n  bit_solve; try lia.\n  destruct (zlt i (zwordsize - unsigned n)).\n  rewrite zlt_true by lia. auto.\n  destruct (zlt i s); auto. rewrite zlt_false by lia; auto.\nQed.\n\nLemma sign_ext_shr_min:\n  forall s x n, ltu n iwordsize = true ->\n  sign_ext s (shr x n) = sign_ext (Z.min s (zwordsize - unsigned n)) (shr x n).\nProof.\n  intros. apply ltu_iwordsize_inv in H.\n  rewrite Z.min_comm. \n  destruct (Z.min_spec (zwordsize - unsigned n) s) as [[A B] | [A B]]; rewrite B; auto.\n  apply same_bits_eq; intros. rewrite ! bits_sign_ext by auto.\n  destruct (zlt i (zwordsize - unsigned n)). \n  rewrite zlt_true by lia. auto.\n  assert (C: testbit (shr x n) (zwordsize - unsigned n - 1) = testbit x (zwordsize - 1)).\n  { rewrite bits_shr by lia. rewrite zlt_true by lia. f_equal; lia. }\n  rewrite C. destruct (zlt i s); rewrite bits_shr by lia.\n  rewrite zlt_false by lia. auto.\n  rewrite zlt_false by lia. auto.\nQed.\n\nLemma shl_zero_ext_min:\n  forall s x n, ltu n iwordsize = true ->\n  shl (zero_ext s x) n = shl (zero_ext (Z.min s (zwordsize - unsigned n)) x) n.\nProof.\n  intros. apply ltu_iwordsize_inv in H.\n  apply Z.min_case_strong; intros; auto.\n  apply same_bits_eq; intros. rewrite ! bits_shl by auto.\n  destruct (zlt i (unsigned n)); auto.\n  rewrite ! bits_zero_ext by lia.\n  destruct (zlt (i - unsigned n) s).\n  rewrite zlt_true by lia; auto.\n  rewrite zlt_false by lia; auto.\nQed.\n\nLemma shl_sign_ext_min:\n  forall s x n, ltu n iwordsize = true ->\n  shl (sign_ext s x) n = shl (sign_ext (Z.min s (zwordsize - unsigned n)) x) n.\nProof.\n  intros. apply ltu_iwordsize_inv in H.\n  rewrite Z.min_comm. \n  destruct (Z.min_spec (zwordsize - unsigned n) s) as [[A B] | [A B]]; rewrite B; auto.\n  apply same_bits_eq; intros. rewrite ! bits_shl by auto.\n  destruct (zlt i (unsigned n)); auto.\n  rewrite ! bits_sign_ext by lia. f_equal.\n  destruct (zlt (i - unsigned n) s).\n  rewrite zlt_true by lia; auto.\n  extlia.\nQed.\n\n(** ** Properties of [one_bits] (decomposition in sum of powers of two) *)\n\nTheorem one_bits_range:\n  forall x i, In i (one_bits x) -> ltu i iwordsize = true.\nProof.\n  assert (A: forall p, 0 <= p < zwordsize -> ltu (repr p) iwordsize = true).\n    intros. unfold ltu, iwordsize. apply zlt_true.\n    repeat rewrite unsigned_repr. tauto.\n    generalize wordsize_max_unsigned; lia.\n    generalize wordsize_max_unsigned; lia.\n  unfold one_bits. intros.\n  destruct (list_in_map_inv _ _ _ H) as [i0 [EQ IN]].\n  subst i. apply A. apply Z_one_bits_range with (unsigned x); auto.\nQed.\n\nFixpoint int_of_one_bits (l: list int) : int :=\n  match l with\n  | nil => zero\n  | a :: b => add (shl one a) (int_of_one_bits b)\n  end.\n\nTheorem one_bits_decomp:\n  forall x, x = int_of_one_bits (one_bits x).\nProof.\n  intros.\n  transitivity (repr (powerserie (Z_one_bits wordsize (unsigned x) 0))).\n  transitivity (repr (unsigned x)).\n  auto with ints. decEq. apply Z_one_bits_powerserie.\n  auto with ints.\n  unfold one_bits.\n  generalize (Z_one_bits_range wordsize (unsigned x)).\n  generalize (Z_one_bits wordsize (unsigned x) 0).\n  induction l.\n  intros; reflexivity.\n  intros; simpl. rewrite <- IHl. unfold add. apply eqm_samerepr.\n  apply eqm_add. rewrite shl_mul_two_p. rewrite mul_commut.\n  rewrite mul_one. apply eqm_unsigned_repr_r.\n  rewrite unsigned_repr. auto with ints.\n  generalize (H a (in_eq _ _)). change (Z.of_nat wordsize) with zwordsize.\n  generalize wordsize_max_unsigned. lia.\n  auto with ints.\n  intros; apply H; auto with coqlib.\nQed.\n\n(** ** Properties of comparisons *)\n\nTheorem negate_cmp:\n  forall c x y, cmp (negate_comparison c) x y = negb (cmp c x y).\nProof.\n  intros. destruct c; simpl; try rewrite negb_elim; auto.\nQed.\n\nTheorem negate_cmpu:\n  forall c x y, cmpu (negate_comparison c) x y = negb (cmpu c x y).\nProof.\n  intros. destruct c; simpl; try rewrite negb_elim; auto.\nQed.\n\nTheorem swap_cmp:\n  forall c x y, cmp (swap_comparison c) x y = cmp c y x.\nProof.\n  intros. destruct c; simpl; auto. apply eq_sym. decEq. apply eq_sym.\nQed.\n\nTheorem swap_cmpu:\n  forall c x y, cmpu (swap_comparison c) x y = cmpu c y x.\nProof.\n  intros. destruct c; simpl; auto. apply eq_sym. decEq. apply eq_sym.\nQed.\n\nLemma translate_eq:\n  forall x y d,\n  eq (add x d) (add y d) = eq x y.\nProof.\n  intros. unfold eq. case (zeq (unsigned x) (unsigned y)); intro.\n  unfold add. rewrite e. apply zeq_true.\n  apply zeq_false. unfold add. red; intro. apply n.\n  apply eqm_small_eq; auto with ints.\n  replace (unsigned x) with ((unsigned x + unsigned d) - unsigned d).\n  replace (unsigned y) with ((unsigned y + unsigned d) - unsigned d).\n  apply eqm_sub. apply eqm_trans with (unsigned (repr (unsigned x + unsigned d))).\n  eauto with ints. apply eqm_trans with (unsigned (repr (unsigned y + unsigned d))).\n  eauto with ints. eauto with ints. eauto with ints.\n  lia. lia.\nQed.\n\nLemma translate_ltu:\n  forall x y d,\n  0 <= unsigned x + unsigned d <= max_unsigned ->\n  0 <= unsigned y + unsigned d <= max_unsigned ->\n  ltu (add x d) (add y d) = ltu x y.\nProof.\n  intros. unfold add. unfold ltu.\n  repeat rewrite unsigned_repr; auto. case (zlt (unsigned x) (unsigned y)); intro.\n  apply zlt_true. lia.\n  apply zlt_false. lia.\nQed.\n\nTheorem translate_cmpu:\n  forall c x y d,\n  0 <= unsigned x + unsigned d <= max_unsigned ->\n  0 <= unsigned y + unsigned d <= max_unsigned ->\n  cmpu c (add x d) (add y d) = cmpu c x y.\nProof.\n  intros. unfold cmpu.\n  rewrite translate_eq. repeat rewrite translate_ltu; auto.\nQed.\n\nLemma translate_lt:\n  forall x y d,\n  min_signed <= signed x + signed d <= max_signed ->\n  min_signed <= signed y + signed d <= max_signed ->\n  lt (add x d) (add y d) = lt x y.\nProof.\n  intros. repeat rewrite add_signed. unfold lt.\n  repeat rewrite signed_repr; auto. case (zlt (signed x) (signed y)); intro.\n  apply zlt_true. lia.\n  apply zlt_false. lia.\nQed.\n\nTheorem translate_cmp:\n  forall c x y d,\n  min_signed <= signed x + signed d <= max_signed ->\n  min_signed <= signed y + signed d <= max_signed ->\n  cmp c (add x d) (add y d) = cmp c x y.\nProof.\n  intros. unfold cmp.\n  rewrite translate_eq. repeat rewrite translate_lt; auto.\nQed.\n\nTheorem notbool_isfalse_istrue:\n  forall x, is_false x -> is_true (notbool x).\nProof.\n  unfold is_false, is_true, notbool; intros; subst x.\n  rewrite eq_true. apply one_not_zero.\nQed.\n\nTheorem notbool_istrue_isfalse:\n  forall x, is_true x -> is_false (notbool x).\nProof.\n  unfold is_false, is_true, notbool; intros.\n  generalize (eq_spec x zero). case (eq x zero); intro.\n  contradiction. auto.\nQed.\n\nTheorem ltu_range_test:\n  forall x y,\n  ltu x y = true -> unsigned y <= max_signed ->\n  0 <= signed x < unsigned y.\nProof.\n  intros.\n  unfold ltu in H. destruct (zlt (unsigned x) (unsigned y)); try discriminate.\n  rewrite signed_eq_unsigned.\n  generalize (unsigned_range x). lia. lia.\nQed.\n\nTheorem lt_sub_overflow:\n  forall x y,\n  xor (sub_overflow x y zero) (negative (sub x y)) = if lt x y then one else zero.\nProof.\n  intros. unfold negative, sub_overflow, lt. rewrite sub_signed.\n  rewrite signed_zero. rewrite Z.sub_0_r.\n  generalize (signed_range x) (signed_range y).\n  set (X := signed x); set (Y := signed y). intros RX RY.\n  unfold min_signed, max_signed in *.\n  generalize half_modulus_pos half_modulus_modulus; intros HM MM.\n  destruct (zle 0 (X - Y)).\n- unfold proj_sumbool at 1; rewrite zle_true at 1 by lia. simpl.\n  rewrite (zlt_false _ X) by lia.\n  destruct (zlt (X - Y) half_modulus).\n  + unfold proj_sumbool; rewrite zle_true by lia.\n    rewrite signed_repr. rewrite zlt_false by lia. apply xor_idem.\n    unfold min_signed, max_signed; lia.\n  + unfold proj_sumbool; rewrite zle_false by lia.\n    replace (signed (repr (X - Y))) with (X - Y - modulus).\n    rewrite zlt_true by lia. apply xor_idem.\n    rewrite signed_repr_eq. replace ((X - Y) mod modulus) with (X - Y).\n    rewrite zlt_false; auto.\n    symmetry. apply Zmod_unique with 0; lia.\n- unfold proj_sumbool at 2. rewrite zle_true at 1 by lia. rewrite andb_true_r.\n  rewrite (zlt_true _ X) by lia.\n  destruct (zlt (X - Y) (-half_modulus)).\n  + unfold proj_sumbool; rewrite zle_false by lia.\n    replace (signed (repr (X - Y))) with (X - Y + modulus).\n    rewrite zlt_false by lia. apply xor_zero.\n    rewrite signed_repr_eq. replace ((X - Y) mod modulus) with (X - Y + modulus).\n    rewrite zlt_true by lia; auto.\n    symmetry. apply Zmod_unique with (-1); lia.\n  + unfold proj_sumbool; rewrite zle_true by lia.\n    rewrite signed_repr. rewrite zlt_true by lia. apply xor_zero_l.\n    unfold min_signed, max_signed; lia.\nQed.\n\nLemma signed_eq:\n  forall x y, eq x y = zeq (signed x) (signed y).\nProof.\n  intros. unfold eq. unfold proj_sumbool.\n  destruct (zeq (unsigned x) (unsigned y));\n  destruct (zeq (signed x) (signed y)); auto.\n  elim n. unfold signed. rewrite e; auto.\n  elim n. apply eqm_small_eq; auto with ints.\n  eapply eqm_trans. apply eqm_sym. apply eqm_signed_unsigned.\n  rewrite e. apply eqm_signed_unsigned.\nQed.\n\nLemma not_lt:\n  forall x y, negb (lt y x) = (lt x y || eq x y).\nProof.\n  intros. unfold lt. rewrite signed_eq. unfold proj_sumbool.\n  destruct (zlt (signed y) (signed x)).\n  rewrite zlt_false. rewrite zeq_false. auto. lia. lia.\n  destruct (zeq (signed x) (signed y)).\n  rewrite zlt_false. auto. lia.\n  rewrite zlt_true. auto. lia.\nQed.\n\nLemma lt_not:\n  forall x y, lt y x = negb (lt x y) && negb (eq x y).\nProof.\n  intros. rewrite <- negb_orb. rewrite <- not_lt. rewrite negb_involutive. auto.\nQed.\n\nLemma not_ltu:\n  forall x y, negb (ltu y x) = (ltu x y || eq x y).\nProof.\n  intros. unfold ltu, eq.\n  destruct (zlt (unsigned y) (unsigned x)).\n  rewrite zlt_false. rewrite zeq_false. auto. lia. lia.\n  destruct (zeq (unsigned x) (unsigned y)).\n  rewrite zlt_false. auto. lia.\n  rewrite zlt_true. auto. lia.\nQed.\n\nLemma ltu_not:\n  forall x y, ltu y x = negb (ltu x y) && negb (eq x y).\nProof.\n  intros. rewrite <- negb_orb. rewrite <- not_ltu. rewrite negb_involutive. auto.\nQed.\n\n(** ** Non-overlapping test *)\n\nDefinition no_overlap (ofs1: int) (sz1: Z) (ofs2: int) (sz2: Z) : bool :=\n  let x1 := unsigned ofs1 in let x2 := unsigned ofs2 in\n     zlt (x1 + sz1) modulus && zlt (x2 + sz2) modulus\n  && (zle (x1 + sz1) x2 || zle (x2 + sz2) x1).\n\nLemma no_overlap_sound:\n  forall ofs1 sz1 ofs2 sz2 base,\n  sz1 > 0 -> sz2 > 0 -> no_overlap ofs1 sz1 ofs2 sz2 = true ->\n  unsigned (add base ofs1) + sz1 <= unsigned (add base ofs2)\n  \\/ unsigned (add base ofs2) + sz2 <= unsigned (add base ofs1).\nProof.\n  intros.\n  destruct (andb_prop _ _ H1). clear H1.\n  destruct (andb_prop _ _ H2). clear H2.\n  apply proj_sumbool_true in H1.\n  apply proj_sumbool_true in H4.\n  assert (unsigned ofs1 + sz1 <= unsigned ofs2 \\/ unsigned ofs2 + sz2 <= unsigned ofs1).\n  destruct (orb_prop _ _ H3). left. eapply proj_sumbool_true; eauto. right. eapply proj_sumbool_true; eauto.\n  clear H3.\n  generalize (unsigned_range ofs1) (unsigned_range ofs2). intros P Q.\n  generalize (unsigned_add_either base ofs1) (unsigned_add_either base ofs2).\n  intros [C|C] [D|D]; lia.\nQed.\n\n(** ** Size of integers, in bits. *)\n\nDefinition size (x: int) : Z := Zsize (unsigned x).\n\nTheorem size_zero: size zero = 0.\nProof.\n  unfold size; rewrite unsigned_zero; auto.\nQed.\n\nTheorem bits_size_1:\n  forall x, x = zero \\/ testbit x (Z.pred (size x)) = true.\nProof.\n  intros. destruct (zeq (unsigned x) 0).\n  left. rewrite <- (repr_unsigned x). rewrite e; auto.\n  right. apply Ztestbit_size_1. generalize (unsigned_range x); lia.\nQed.\n\nTheorem bits_size_2:\n  forall x i, size x <= i -> testbit x i = false.\nProof.\n  intros. apply Ztestbit_size_2. generalize (unsigned_range x); lia.\n  fold (size x); lia.\nQed.\n\nTheorem size_range:\n  forall x, 0 <= size x <= zwordsize.\nProof.\n  intros; split. apply Zsize_pos.\n  destruct (bits_size_1 x).\n  subst x; unfold size; rewrite unsigned_zero; simpl. generalize wordsize_pos; lia.\n  destruct (zle (size x) zwordsize); auto.\n  rewrite bits_above in H. congruence. lia.\nQed.\n\nTheorem bits_size_3:\n  forall x n,\n  0 <= n ->\n  (forall i, n <= i < zwordsize -> testbit x i = false) ->\n  size x <= n.\nProof.\n  intros. destruct (zle (size x) n). auto.\n  destruct (bits_size_1 x).\n  subst x. unfold size; rewrite unsigned_zero; assumption.\n  rewrite (H0 (Z.pred (size x))) in H1. congruence.\n  generalize (size_range x); lia.\nQed.\n\nTheorem bits_size_4:\n  forall x n,\n  0 <= n ->\n  testbit x (Z.pred n) = true ->\n  (forall i, n <= i < zwordsize -> testbit x i = false) ->\n  size x = n.\nProof.\n  intros.\n  assert (size x <= n).\n    apply bits_size_3; auto.\n  destruct (zlt (size x) n).\n  rewrite bits_size_2 in H0. congruence. lia.\n  lia.\nQed.\n\nTheorem size_interval_1:\n  forall x, 0 <= unsigned x < two_p (size x).\nProof.\n  intros; apply Zsize_interval_1. generalize (unsigned_range x); lia.\nQed.\n\nTheorem size_interval_2:\n  forall x n, 0 <= n -> 0 <= unsigned x < two_p n -> n >= size x.\nProof.\n  intros. apply Zsize_interval_2; auto.\nQed.\n\nTheorem size_and:\n  forall a b, size (and a b) <= Z.min (size a) (size b).\nProof.\n  intros.\n  assert (0 <= Z.min (size a) (size b)).\n    generalize (size_range a) (size_range b). zify; lia.\n  apply bits_size_3. auto. intros.\n  rewrite bits_and by lia.\n  rewrite andb_false_iff.\n  generalize (bits_size_2 a i).\n  generalize (bits_size_2 b i).\n  zify; intuition.\nQed.\n\nCorollary and_interval:\n  forall a b, 0 <= unsigned (and a b) < two_p (Z.min (size a) (size b)).\nProof.\n  intros.\n  generalize (size_interval_1 (and a b)); intros.\n  assert (two_p (size (and a b)) <= two_p (Z.min (size a) (size b))).\n  apply two_p_monotone. split. generalize (size_range (and a b)); lia.\n  apply size_and.\n  lia.\nQed.\n\nTheorem size_or:\n  forall a b, size (or a b) = Z.max (size a) (size b).\nProof.\n  intros. generalize (size_range a) (size_range b); intros.\n  destruct (bits_size_1 a).\n  subst a. rewrite size_zero. rewrite or_zero_l. zify; lia.\n  destruct (bits_size_1 b).\n  subst b. rewrite size_zero. rewrite or_zero. zify; lia.\n  zify. destruct H3 as [[P Q] | [P Q]]; subst.\n  apply bits_size_4. tauto. rewrite bits_or. rewrite H2. apply orb_true_r.\n  lia.\n  intros. rewrite bits_or. rewrite !bits_size_2. auto. lia. lia. lia.\n  apply bits_size_4. tauto. rewrite bits_or. rewrite H1. apply orb_true_l.\n  destruct (zeq (size a) 0). unfold testbit in H1. rewrite Z.testbit_neg_r in H1.\n  congruence. lia. lia.\n  intros. rewrite bits_or. rewrite !bits_size_2. auto. lia. lia. lia.\nQed.\n\nCorollary or_interval:\n  forall a b, 0 <= unsigned (or a b) < two_p (Z.max (size a) (size b)).\nProof.\n  intros. rewrite <- size_or. apply size_interval_1.\nQed.\n\nTheorem size_xor:\n  forall a b, size (xor a b) <= Z.max (size a) (size b).\nProof.\n  intros.\n  assert (0 <= Z.max (size a) (size b)).\n    generalize (size_range a) (size_range b). zify; lia.\n  apply bits_size_3. auto. intros.\n  rewrite bits_xor. rewrite !bits_size_2. auto.\n  zify; lia.\n  zify; lia.\n  lia.\nQed.\n\nCorollary xor_interval:\n  forall a b, 0 <= unsigned (xor a b) < two_p (Z.max (size a) (size b)).\nProof.\n  intros.\n  generalize (size_interval_1 (xor a b)); intros.\n  assert (two_p (size (xor a b)) <= two_p (Z.max (size a) (size b))).\n  apply two_p_monotone. split. generalize (size_range (xor a b)); lia.\n  apply size_xor.\n  lia.\nQed.\n\n(** ** Accessing bit fields *)\n\nDefinition unsigned_bitfield_extract (pos width: Z) (n: int) : int :=\n  zero_ext width (shru n (repr pos)).\n\nDefinition signed_bitfield_extract (pos width: Z) (n: int) : int :=\n  sign_ext width (shru n (repr pos)).\n\nDefinition bitfield_insert (pos width: Z) (n p: int) : int :=\n  let mask := shl (repr (two_p width - 1)) (repr pos) in\n  or (shl (zero_ext width p) (repr pos))\n     (and n (not mask)).\n\nLemma bits_unsigned_bitfield_extract:\n  forall pos width n i,\n  0 <= pos -> 0 < width -> pos + width <= zwordsize ->\n  0 <= i < zwordsize ->\n  testbit (unsigned_bitfield_extract pos width n) i =\n  if zlt i width then testbit n (i + pos) else false.\nProof.\n  intros. unfold unsigned_bitfield_extract. rewrite bits_zero_ext by lia.\n  destruct (zlt i width); auto.\n  rewrite bits_shru by auto. rewrite unsigned_repr, zlt_true. auto.\n  lia.\n  generalize wordsize_max_unsigned; lia.\nQed.\n\nLemma bits_signed_bitfield_extract:\n  forall pos width n i,\n  0 <= pos -> 0 < width -> pos + width <= zwordsize ->\n  0 <= i < zwordsize ->\n  testbit (signed_bitfield_extract pos width n) i =\n  testbit n (if zlt i width then i + pos else width - 1 + pos).\nProof.\n  intros. unfold signed_bitfield_extract. rewrite bits_sign_ext by lia.\n  rewrite bits_shru, unsigned_repr, zlt_true.\n  destruct (zlt i width); auto.\n  destruct (zlt i width); lia.\n  generalize wordsize_max_unsigned; lia.\n  destruct (zlt i width); lia.\nQed.\n\nLemma bits_bitfield_insert:\n  forall pos width n p i,\n  0 <= pos -> 0 < width -> pos + width <= zwordsize ->\n  0 <= i < zwordsize ->\n  testbit (bitfield_insert pos width n p) i =\n  if zle pos i && zlt i (pos + width) then testbit p (i - pos) else testbit n i.\nProof.\n  intros. unfold bitfield_insert.\n  assert (P: unsigned (repr pos) = pos).\n  { apply unsigned_repr. generalize wordsize_max_unsigned; lia. }\n  rewrite bits_or, bits_and, bits_not, ! bits_shl, ! P by auto.\n  destruct (zlt i pos).\n- unfold proj_sumbool; rewrite zle_false by lia. cbn. apply andb_true_r.\n- unfold proj_sumbool; rewrite zle_true by lia; cbn.\n  rewrite bits_zero_ext, testbit_repr, Ztestbit_two_p_m1 by lia.\n  destruct (zlt (i - pos) width); cbn.\n+ rewrite zlt_true by lia. rewrite andb_false_r, orb_false_r. auto.\n+ rewrite zlt_false by lia. apply andb_true_r.\nQed.\n\nLemma unsigned_bitfield_extract_by_shifts:\n  forall pos width n,\n  0 <= pos -> 0 < width -> pos + width <= zwordsize ->\n  unsigned_bitfield_extract pos width n =\n  shru (shl n (repr (zwordsize - pos - width))) (repr (zwordsize - width)).\nProof.\n  intros. apply same_bits_eq; intros.\n  rewrite bits_unsigned_bitfield_extract by lia.\n  rewrite bits_shru by auto.\n  rewrite unsigned_repr by (generalize wordsize_max_unsigned; lia).\n  destruct (zlt i width).\n- rewrite bits_shl by lia.\n  rewrite unsigned_repr by (generalize wordsize_max_unsigned; lia).\n  rewrite zlt_true by lia. rewrite zlt_false by lia. f_equal; lia.\n- rewrite zlt_false by lia. auto.\nQed.\n\nLemma signed_bitfield_extract_by_shifts:\n  forall pos width n,\n  0 <= pos -> 0 < width -> pos + width <= zwordsize ->\n  signed_bitfield_extract pos width n =\n  shr (shl n (repr (zwordsize - pos - width))) (repr (zwordsize - width)).\nProof.\n  intros. apply same_bits_eq; intros.\n  rewrite bits_signed_bitfield_extract by lia.\n  rewrite bits_shr by auto.\n  rewrite unsigned_repr by (generalize wordsize_max_unsigned; lia).\n  rewrite bits_shl.\n  rewrite unsigned_repr by (generalize wordsize_max_unsigned; lia).\n  symmetry. rewrite zlt_false. f_equal.\n  destruct (zlt i width); [rewrite zlt_true | rewrite zlt_false]; lia.\n  destruct zlt; lia.\n  destruct zlt; lia.\nQed.\n\nLemma bitfield_insert_alternative:\n  forall pos width n p,\n  0 <= width ->\n  bitfield_insert pos width n p =\n  let mask := shl (repr (two_p width - 1)) (repr pos) in\n  or (and (shl p (repr pos)) mask)\n     (and n (not mask)).\nProof.\n  intros. unfold bitfield_insert. \n  set (m1 := repr (two_p width - 1)).\n  set (m2 := shl m1 (repr pos)).\n  f_equal.\n  rewrite zero_ext_and by lia. fold m1. unfold m2. rewrite <- and_shl. auto.\nQed.\n\nEnd Make.\n\n(** * Specialization to integers of size 8, 32, and 64 bits *)\n\nModule Wordsize_32.\n  Definition wordsize := 32%nat.\n  Remark wordsize_not_zero: wordsize <> 0%nat.\n  Proof. unfold wordsize; congruence. Qed.\nEnd Wordsize_32.\n\nStrategy opaque [Wordsize_32.wordsize].\n\nModule Int := Make(Wordsize_32).\n\nStrategy 0 [Wordsize_32.wordsize].\n\nNotation int := Int.int.\n\nRemark int_wordsize_divides_modulus:\n  Z.divide (Z.of_nat Int.wordsize) Int.modulus.\nProof.\n  exists (two_p (32-5)); reflexivity.\nQed.\n\nModule Wordsize_8.\n  Definition wordsize := 8%nat.\n  Remark wordsize_not_zero: wordsize <> 0%nat.\n  Proof. unfold wordsize; congruence. Qed.\nEnd Wordsize_8.\n\nStrategy opaque [Wordsize_8.wordsize].\n\nModule Byte := Make(Wordsize_8).\n\nStrategy 0 [Wordsize_8.wordsize].\n\nNotation byte := Byte.int.\n\nModule Wordsize_64.\n  Definition wordsize := 64%nat.\n  Remark wordsize_not_zero: wordsize <> 0%nat.\n  Proof. unfold wordsize; congruence. Qed.\nEnd Wordsize_64.\n\nStrategy opaque [Wordsize_64.wordsize].\n\nModule Int64.\n\nInclude Make(Wordsize_64).\n\n(** Shifts with amount given as a 32-bit integer *)\n\nDefinition iwordsize': Int.int := Int.repr zwordsize.\n\nDefinition shl' (x: int) (y: Int.int): int :=\n  repr (Z.shiftl (unsigned x) (Int.unsigned y)).\nDefinition shru' (x: int) (y: Int.int): int :=\n  repr (Z.shiftr (unsigned x) (Int.unsigned y)).\nDefinition shr' (x: int) (y: Int.int): int :=\n  repr (Z.shiftr (signed x) (Int.unsigned y)).\nDefinition rol' (x: int) (y: Int.int): int :=\n  rol x (repr (Int.unsigned y)).\nDefinition shrx' (x: int) (y: Int.int): int :=\n  divs x (shl' one y).\nDefinition shr_carry' (x: int) (y: Int.int): int :=\n  if lt x zero && negb (eq (and x (sub (shl' one y) one)) zero)\n  then one else zero.\n\nLemma bits_shl':\n  forall x y i,\n  0 <= i < zwordsize ->\n  testbit (shl' x y) i =\n  if zlt i (Int.unsigned y) then false else testbit x (i - Int.unsigned y).\nProof.\n  intros. unfold shl'. rewrite testbit_repr; auto.\n  destruct (zlt i (Int.unsigned y)).\n  apply Z.shiftl_spec_low. auto.\n  apply Z.shiftl_spec_high. lia. lia.\nQed.\n\nLemma bits_shru':\n  forall x y i,\n  0 <= i < zwordsize ->\n  testbit (shru' x y) i =\n  if zlt (i + Int.unsigned y) zwordsize then testbit x (i + Int.unsigned y) else false.\nProof.\n  intros. unfold shru'. rewrite testbit_repr; auto.\n  rewrite Z.shiftr_spec. fold (testbit x (i + Int.unsigned y)).\n  destruct (zlt (i + Int.unsigned y) zwordsize).\n  auto.\n  apply bits_above; auto.\n  lia.\nQed.\n\nLemma bits_shr':\n  forall x y i,\n  0 <= i < zwordsize ->\n  testbit (shr' x y) i =\n  testbit x (if zlt (i + Int.unsigned y) zwordsize then i + Int.unsigned y else zwordsize - 1).\nProof.\n  intros. unfold shr'. rewrite testbit_repr; auto.\n  rewrite Z.shiftr_spec. apply bits_signed.\n  generalize (Int.unsigned_range y); lia.\n  lia.\nQed.\n\nLemma shl'_mul_two_p:\n  forall x y,\n  shl' x y = mul x (repr (two_p (Int.unsigned y))).\nProof.\n  intros. unfold shl', mul. apply eqm_samerepr.\n  rewrite Zshiftl_mul_two_p. apply eqm_mult. apply eqm_refl. apply eqm_unsigned_repr.\n  generalize (Int.unsigned_range y); lia.\nQed.\n\nLemma shl'_one_two_p:\n  forall y, shl' one y = repr (two_p (Int.unsigned y)).\nProof.\n  intros. rewrite shl'_mul_two_p. rewrite mul_commut. rewrite mul_one. auto.\nQed.\n\nTheorem shl'_mul:\n  forall x y,\n  shl' x y = mul x (shl' one y).\nProof.\n  intros. rewrite shl'_one_two_p. apply shl'_mul_two_p.\nQed.\n\nTheorem shl'_zero:\n  forall x, shl' x Int.zero = x.\nProof.\n  intros. unfold shl'. rewrite Int.unsigned_zero. unfold Z.shiftl.\n  apply repr_unsigned.\nQed.\n\nTheorem shru'_zero :\n  forall x, shru' x Int.zero = x.\nProof.\n  intros. unfold shru'. rewrite Int.unsigned_zero. unfold Z.shiftr.\n  apply repr_unsigned.\nQed.\n\nTheorem shr'_zero :\n  forall x, shr' x Int.zero = x.\nProof.\n  intros. unfold shr'. rewrite Int.unsigned_zero. unfold Z.shiftr.\n  apply repr_signed.\nQed.\n\nTheorem shrx'_zero:\n  forall x, shrx' x Int.zero = x.\nProof.\n  intros. change (shrx' x Int.zero) with (shrx x zero). apply shrx_zero. compute; auto.\nQed.\n\nTheorem shrx'_carry:\n  forall x y,\n  Int.ltu y (Int.repr 63) = true ->\n  shrx' x y = add (shr' x y) (shr_carry' x y).\nProof.\n  intros. apply Int.ltu_inv in H. change (Int.unsigned (Int.repr 63)) with 63 in H.\n  set (y1 := Int64.repr (Int.unsigned y)).\n  assert (U: unsigned y1 = Int.unsigned y).\n  { apply unsigned_repr. assert (63 < max_unsigned) by reflexivity. lia. }\n  transitivity (shrx x y1).\n- unfold shrx', shrx, shl', shl. rewrite U; auto.\n- rewrite shrx_carry. \n+ f_equal. \n  unfold shr, shr'. rewrite U; auto.\n  unfold shr_carry, shr_carry', shl, shl'. rewrite U; auto.\n+ unfold ltu. apply zlt_true. rewrite U; tauto. \nQed.\n\nTheorem shrx'_shr_2:\n  forall x y,\n  Int.ltu y (Int.repr 63) = true ->\n  shrx' x y = shr' (add x (shru' (shr' x (Int.repr 63)) (Int.sub (Int.repr 64) y))) y.\nProof.\n  intros.\n  set (z := repr (Int.unsigned y)).\n  apply Int.ltu_inv in H. change (Int.unsigned (Int.repr 63)) with 63 in H.\n  assert (N1: 63 < max_unsigned) by reflexivity.\n  assert (N2: 63 < Int.max_unsigned) by reflexivity.\n  assert (A: unsigned z = Int.unsigned y).\n  { unfold z; apply unsigned_repr; lia. }\n  assert (B: unsigned (sub (repr 64) z) = Int.unsigned (Int.sub (Int.repr 64) y)).\n  { unfold z. unfold sub, Int.sub.\n    change (unsigned (repr 64)) with 64.\n    change (Int.unsigned (Int.repr 64)) with 64.\n    rewrite (unsigned_repr (Int.unsigned y)) by lia.\n    rewrite unsigned_repr, Int.unsigned_repr by lia.\n    auto. }\n  unfold shrx', shr', shru', shl'.\n  rewrite <- A.\n  change (Int.unsigned (Int.repr 63)) with (unsigned (repr 63)).\n  rewrite <- B.\n  apply shrx_shr_2.\n  unfold ltu. apply zlt_true. change (unsigned z < 63). rewrite A; lia.\nQed.\n\nRemark int_ltu_2_inv:\n  forall y z,\n  Int.ltu y iwordsize' = true ->\n  Int.ltu z iwordsize' = true ->\n  Int.unsigned (Int.add y z) <= Int.unsigned iwordsize' ->\n  let y' := repr (Int.unsigned y) in\n  let z' := repr (Int.unsigned z) in\n     Int.unsigned y = unsigned y'\n  /\\ Int.unsigned z = unsigned z'\n  /\\ ltu y' iwordsize = true\n  /\\ ltu z' iwordsize = true\n  /\\ Int.unsigned (Int.add y z) = unsigned (add y' z')\n  /\\ add y' z' = repr (Int.unsigned (Int.add y z)).\nProof.\n  intros. apply Int.ltu_inv in H. apply Int.ltu_inv in H0.\n  change (Int.unsigned iwordsize') with 64 in *.\n  assert (128 < max_unsigned) by reflexivity.\n  assert (128 < Int.max_unsigned) by reflexivity.\n  assert (Y: unsigned y' = Int.unsigned y) by (apply unsigned_repr; lia).\n  assert (Z: unsigned z' = Int.unsigned z) by (apply unsigned_repr; lia).\n  assert (P: Int.unsigned (Int.add y z) = unsigned (add y' z')).\n  { unfold Int.add. rewrite Int.unsigned_repr by lia.\n    unfold add. rewrite unsigned_repr by lia. congruence. }\n  intuition auto.\n  apply zlt_true. rewrite Y; auto.\n  apply zlt_true. rewrite Z; auto.\n  rewrite P. rewrite repr_unsigned. auto.\nQed.\n\nTheorem or_ror':\n  forall x y z,\n  Int.ltu y iwordsize' = true ->\n  Int.ltu z iwordsize' = true ->\n  Int.add y z = iwordsize' ->\n  ror x (repr (Int.unsigned z)) = or (shl' x y) (shru' x z).\nProof.\n  intros. destruct (int_ltu_2_inv y z) as (A & B & C & D & E & F); auto. rewrite H1; lia.\n  replace (shl' x y) with (shl x (repr (Int.unsigned y))).\n  replace (shru' x z) with (shru x (repr (Int.unsigned z))).\n  apply or_ror; auto. rewrite F, H1. reflexivity.\n  unfold shru, shru'; rewrite <- B; auto.\n  unfold shl, shl'; rewrite <- A; auto.\nQed.\n\nTheorem shl'_shl':\n  forall x y z,\n  Int.ltu y iwordsize' = true ->\n  Int.ltu z iwordsize' = true ->\n  Int.ltu (Int.add y z) iwordsize' = true ->\n  shl' (shl' x y) z = shl' x (Int.add y z).\nProof.\n  intros. apply Int.ltu_inv in H1.\n  destruct (int_ltu_2_inv y z) as (A & B & C & D & E & F); auto. lia.\n  set (y' := repr (Int.unsigned y)) in *.\n  set (z' := repr (Int.unsigned z)) in *.\n  replace (shl' x y) with (shl x y').\n  replace (shl' (shl x y') z) with (shl (shl x y') z').\n  replace (shl' x (Int.add y z)) with (shl x (add y' z')).\n  apply shl_shl; auto. apply zlt_true. rewrite <- E.\n  change (unsigned iwordsize) with zwordsize. tauto.\n  unfold shl, shl'. rewrite E; auto.\n  unfold shl at 1, shl'. rewrite <- B; auto.\n  unfold shl, shl'; rewrite <- A; auto.\nQed.\n\nTheorem shru'_shru':\n  forall x y z,\n  Int.ltu y iwordsize' = true ->\n  Int.ltu z iwordsize' = true ->\n  Int.ltu (Int.add y z) iwordsize' = true ->\n  shru' (shru' x y) z = shru' x (Int.add y z).\nProof.\n  intros. apply Int.ltu_inv in H1.\n  destruct (int_ltu_2_inv y z) as (A & B & C & D & E & F); auto. lia.\n  set (y' := repr (Int.unsigned y)) in *.\n  set (z' := repr (Int.unsigned z)) in *.\n  replace (shru' x y) with (shru x y').\n  replace (shru' (shru x y') z) with (shru (shru x y') z').\n  replace (shru' x (Int.add y z)) with (shru x (add y' z')).\n  apply shru_shru; auto. apply zlt_true. rewrite <- E.\n  change (unsigned iwordsize) with zwordsize. tauto.\n  unfold shru, shru'. rewrite E; auto.\n  unfold shru at 1, shru'. rewrite <- B; auto.\n  unfold shru, shru'; rewrite <- A; auto.\nQed.\n\nTheorem shr'_shr':\n  forall x y z,\n  Int.ltu y iwordsize' = true ->\n  Int.ltu z iwordsize' = true ->\n  Int.ltu (Int.add y z) iwordsize' = true ->\n  shr' (shr' x y) z = shr' x (Int.add y z).\nProof.\n  intros. apply Int.ltu_inv in H1.\n  destruct (int_ltu_2_inv y z) as (A & B & C & D & E & F); auto. lia.\n  set (y' := repr (Int.unsigned y)) in *.\n  set (z' := repr (Int.unsigned z)) in *.\n  replace (shr' x y) with (shr x y').\n  replace (shr' (shr x y') z) with (shr (shr x y') z').\n  replace (shr' x (Int.add y z)) with (shr x (add y' z')).\n  apply shr_shr; auto. apply zlt_true. rewrite <- E.\n  change (unsigned iwordsize) with zwordsize. tauto.\n  unfold shr, shr'. rewrite E; auto.\n  unfold shr at 1, shr'. rewrite <- B; auto.\n  unfold shr, shr'; rewrite <- A; auto.\nQed.\n\nTheorem shru'_shl':\n  forall x y z, Int.ltu y iwordsize' = true -> Int.ltu z iwordsize' = true ->\n  shru' (shl' x y) z =\n  if Int.ltu z y then shl' (zero_ext (zwordsize - Int.unsigned y) x) (Int.sub y z)\n                 else zero_ext (zwordsize - Int.unsigned z) (shru' x (Int.sub z y)).\nProof.\n  intros. apply Int.ltu_inv in H; apply Int.ltu_inv in H0.\n  change (Int.unsigned iwordsize') with zwordsize in *.\n  unfold Int.ltu. set (Y := Int.unsigned y) in *; set (Z := Int.unsigned z) in *.\n  apply same_bits_eq; intros. rewrite bits_shru' by auto. fold Z.\n  destruct (zlt Z Y).\n- assert (A: Int.unsigned (Int.sub y z) = Y - Z).\n  { apply Int.unsigned_repr. assert (zwordsize < Int.max_unsigned) by reflexivity. lia. }\n  symmetry; rewrite bits_shl', A by lia.\n  destruct (zlt (i + Z) zwordsize).\n+ rewrite bits_shl' by lia. fold Y.\n  destruct (zlt i (Y - Z)); [rewrite zlt_true by lia|rewrite zlt_false by lia]; auto.\n  rewrite bits_zero_ext by lia. rewrite zlt_true by lia. f_equal; lia.\n+ rewrite bits_zero_ext by lia. rewrite ! zlt_false by lia. auto.\n- assert (A: Int.unsigned (Int.sub z y) = Z - Y).\n  { apply Int.unsigned_repr. assert (zwordsize < Int.max_unsigned) by reflexivity. lia. }\n  rewrite bits_zero_ext, bits_shru', A by lia.\n  destruct (zlt (i + Z) zwordsize); [rewrite zlt_true by lia|rewrite zlt_false by lia]; auto.\n  rewrite bits_shl' by lia. fold Y.\n  destruct (zlt (i + Z) Y).\n+ rewrite zlt_false by lia. auto.\n+ rewrite zlt_true by lia. f_equal; lia.\nQed.\n\nTheorem shr'_shl':\n  forall x y z, Int.ltu y iwordsize' = true -> Int.ltu z iwordsize' = true ->\n  shr' (shl' x y) z =\n  if Int.ltu z y then shl' (sign_ext (zwordsize - Int.unsigned y) x) (Int.sub y z)\n                 else sign_ext (zwordsize - Int.unsigned z) (shr' x (Int.sub z y)).\nProof.\n  intros. apply Int.ltu_inv in H; apply Int.ltu_inv in H0.\n  change (Int.unsigned iwordsize') with zwordsize in *.\n  unfold Int.ltu. set (Y := Int.unsigned y) in *; set (Z := Int.unsigned z) in *.\n  apply same_bits_eq; intros. rewrite bits_shr' by auto. fold Z.\n  rewrite bits_shl' by (destruct (zlt (i + Z) zwordsize); lia). fold Y.\n  destruct (zlt Z Y).\n- assert (A: Int.unsigned (Int.sub y z) = Y - Z).\n  { apply Int.unsigned_repr. assert (zwordsize < Int.max_unsigned) by reflexivity. lia. }\n  rewrite bits_shl', A by lia.\n  destruct (zlt i (Y - Z)).\n+ apply zlt_true. destruct (zlt (i + Z) zwordsize); lia.\n+ rewrite zlt_false by (destruct (zlt (i + Z) zwordsize); lia).\n  rewrite bits_sign_ext by lia. f_equal. \n  destruct (zlt (i + Z) zwordsize).\n  rewrite zlt_true by lia. lia.\n  rewrite zlt_false by lia. lia.\n- assert (A: Int.unsigned (Int.sub z y) = Z - Y).\n  { apply Int.unsigned_repr. assert (zwordsize < Int.max_unsigned) by reflexivity. lia. }\n  rewrite bits_sign_ext by lia.\n  rewrite bits_shr' by (destruct (zlt i (zwordsize - Z)); lia).\n  rewrite A. rewrite zlt_false by (destruct (zlt (i + Z) zwordsize); lia).\n  f_equal. destruct (zlt i (zwordsize - Z)).\n+ rewrite ! zlt_true by lia. lia.\n+ rewrite ! zlt_false by lia. rewrite zlt_true by lia. lia.\nQed.\n\nLemma shl'_zero_ext:\n  forall n m x, 0 <= n ->\n  shl' (zero_ext n x) m = zero_ext (n + Int.unsigned m) (shl' x m).\nProof.\n  intros. apply same_bits_eq; intros.\n  rewrite bits_zero_ext, ! bits_shl' by lia.\n  destruct (zlt i (Int.unsigned m)).\n- rewrite zlt_true by lia; auto.\n- rewrite bits_zero_ext by lia.\n  destruct (zlt (i - Int.unsigned m) n); [rewrite zlt_true by lia|rewrite zlt_false by lia]; auto.\nQed.\n\nLemma shl'_sign_ext:\n  forall n m x, 0 < n ->\n  shl' (sign_ext n x) m = sign_ext (n + Int.unsigned m) (shl' x m).\nProof.\n  intros. generalize (Int.unsigned_range m); intros.\n  apply same_bits_eq; intros.\n  rewrite bits_sign_ext, ! bits_shl' by lia.\n  destruct (zlt i (n + Int.unsigned m)).\n- rewrite bits_shl' by auto. destruct (zlt i (Int.unsigned m)); auto.\n  rewrite bits_sign_ext by lia. f_equal. apply zlt_true. lia.\n- rewrite zlt_false by lia. rewrite bits_shl' by lia. rewrite zlt_false by lia.\n  rewrite bits_sign_ext by lia. f_equal. rewrite zlt_false by lia. lia.\nQed.\n\nLemma shru'_zero_ext:\n  forall n m x, 0 <= n ->\n  shru' (zero_ext (n + Int.unsigned m) x) m = zero_ext n (shru' x m).\nProof.\n  intros. generalize (Int.unsigned_range m); intros.\n  bit_solve; [|lia]. rewrite bits_shru', bits_zero_ext, bits_shru' by lia.\n  destruct (zlt (i + Int.unsigned m) zwordsize).\n* destruct (zlt i n); [rewrite zlt_true by lia|rewrite zlt_false by lia]; auto.\n* destruct (zlt i n); auto.\nQed.\n\nLemma shru'_zero_ext_0:\n  forall n m x, n <= Int.unsigned m ->\n  shru' (zero_ext n x) m = zero.\nProof.\n  intros. generalize (Int.unsigned_range m); intros.\n  bit_solve. rewrite bits_shru', bits_zero_ext by lia.\n  destruct (zlt (i + Int.unsigned m) zwordsize); auto.\n  apply zlt_false. lia.\nQed.\n\nLemma shr'_sign_ext:\n  forall n m x, 0 < n -> n + Int.unsigned m < zwordsize ->\n  shr' (sign_ext (n + Int.unsigned m) x) m = sign_ext n (shr' x m).\nProof.\n  intros. generalize (Int.unsigned_range m); intros.\n  apply same_bits_eq; intros.\n  rewrite bits_sign_ext, bits_shr' by auto.\n  rewrite bits_sign_ext, bits_shr'.\n- f_equal.\n  destruct (zlt i n), (zlt (i + Int.unsigned m) zwordsize).\n+ apply zlt_true; lia.\n+ apply zlt_true; lia.\n+ rewrite zlt_false by lia. rewrite zlt_true by lia. lia.\n+ rewrite zlt_false by lia. rewrite zlt_true by lia. lia.\n- destruct (zlt i n); lia.\n- destruct (zlt (i + Int.unsigned m) zwordsize); lia.\nQed.\n\nLemma zero_ext_shru'_min:\n  forall s x n, Int.ltu n iwordsize' = true ->\n  zero_ext s (shru' x n) = zero_ext (Z.min s (zwordsize - Int.unsigned n)) (shru' x n).\nProof.\n  intros. apply Int.ltu_inv in H. change (Int.unsigned iwordsize') with zwordsize in H.\n  apply Z.min_case_strong; intros; auto.\n  bit_solve; try lia. rewrite ! bits_shru' by lia. \n  destruct (zlt i (zwordsize - Int.unsigned n)).\n  rewrite zlt_true by lia. auto.\n  destruct (zlt i s); auto. rewrite zlt_false by lia; auto.\nQed.\n\nLemma sign_ext_shr'_min:\n  forall s x n, Int.ltu n iwordsize' = true ->\n  sign_ext s (shr' x n) = sign_ext (Z.min s (zwordsize - Int.unsigned n)) (shr' x n).\nProof.\n  intros. apply Int.ltu_inv in H. change (Int.unsigned iwordsize') with zwordsize in H.\n  rewrite Z.min_comm. \n  destruct (Z.min_spec (zwordsize - Int.unsigned n) s) as [[A B] | [A B]]; rewrite B; auto.\n  apply same_bits_eq; intros. rewrite ! bits_sign_ext by auto.\n  destruct (zlt i (zwordsize - Int.unsigned n)). \n  rewrite zlt_true by lia. auto.\n  assert (C: testbit (shr' x n) (zwordsize - Int.unsigned n - 1) = testbit x (zwordsize - 1)).\n  { rewrite bits_shr' by lia. rewrite zlt_true by lia. f_equal; lia. }\n  rewrite C. destruct (zlt i s); rewrite bits_shr' by lia.\n  rewrite zlt_false by lia. auto.\n  rewrite zlt_false by lia. auto.\nQed.\n\nLemma shl'_zero_ext_min:\n  forall s x n, Int.ltu n iwordsize' = true ->\n  shl' (zero_ext s x) n = shl' (zero_ext (Z.min s (zwordsize - Int.unsigned n)) x) n.\nProof.\n  intros. apply Int.ltu_inv in H. change (Int.unsigned iwordsize') with zwordsize in H.\n  apply Z.min_case_strong; intros; auto.\n  apply same_bits_eq; intros. rewrite ! bits_shl' by auto.\n  destruct (zlt i (Int.unsigned n)); auto.\n  rewrite ! bits_zero_ext by lia.\n  destruct (zlt (i - Int.unsigned n) s).\n  rewrite zlt_true by lia; auto.\n  rewrite zlt_false by lia; auto.\nQed.\n\nLemma shl'_sign_ext_min:\n  forall s x n, Int.ltu n iwordsize' = true ->\n  shl' (sign_ext s x) n = shl' (sign_ext (Z.min s (zwordsize - Int.unsigned n)) x) n.\nProof.\n  intros. apply Int.ltu_inv in H. change (Int.unsigned iwordsize') with zwordsize in H.\n  rewrite Z.min_comm. \n  destruct (Z.min_spec (zwordsize - Int.unsigned n) s) as [[A B] | [A B]]; rewrite B; auto.\n  apply same_bits_eq; intros. rewrite ! bits_shl' by auto.\n  destruct (zlt i (Int.unsigned n)); auto.\n  rewrite ! bits_sign_ext by lia. f_equal.\n  destruct (zlt (i - Int.unsigned n) s).\n  rewrite zlt_true by lia; auto.\n  extlia.\nQed.\n\n(** Powers of two with exponents given as 32-bit ints *)\n\nDefinition one_bits' (x: int) : list Int.int :=\n  List.map Int.repr (Z_one_bits wordsize (unsigned x) 0).\n\nDefinition is_power2' (x: int) : option Int.int :=\n  match Z_one_bits wordsize (unsigned x) 0 with\n  | i :: nil => Some (Int.repr i)\n  | _ => None\n  end.\n\nTheorem one_bits'_range:\n  forall x i, In i (one_bits' x) -> Int.ltu i iwordsize' = true.\nProof.\n  intros.\n  destruct (list_in_map_inv _ _ _ H) as [i0 [EQ IN]].\n  exploit Z_one_bits_range; eauto. fold zwordsize. intros R.\n  unfold Int.ltu. rewrite EQ. rewrite Int.unsigned_repr.\n  change (Int.unsigned iwordsize') with zwordsize. apply zlt_true. lia.\n  assert (zwordsize < Int.max_unsigned) by reflexivity. lia.\nQed.\n\nFixpoint int_of_one_bits' (l: list Int.int) : int :=\n  match l with\n  | nil => zero\n  | a :: b => add (shl' one a) (int_of_one_bits' b)\n  end.\n\nTheorem one_bits'_decomp:\n  forall x, x = int_of_one_bits' (one_bits' x).\nProof.\n  assert (REC: forall l,\n           (forall i, In i l -> 0 <= i < zwordsize) ->\n           int_of_one_bits' (List.map Int.repr l) = repr (powerserie l)).\n  { induction l; simpl; intros.\n  - auto.\n  - rewrite IHl by eauto. apply eqm_samerepr; apply eqm_add.\n  + rewrite shl'_one_two_p. rewrite Int.unsigned_repr. apply eqm_sym; apply eqm_unsigned_repr.\n    exploit (H a). auto. assert (zwordsize < Int.max_unsigned) by reflexivity. lia.\n  + apply eqm_sym; apply eqm_unsigned_repr.\n  }\n  intros. rewrite <- (repr_unsigned x) at 1. unfold one_bits'. rewrite REC.\n  rewrite <- Z_one_bits_powerserie. auto. apply unsigned_range.\n  apply Z_one_bits_range.\nQed.\n\nLemma is_power2'_rng:\n  forall n logn,\n  is_power2' n = Some logn ->\n  0 <= Int.unsigned logn < zwordsize.\nProof.\n  unfold is_power2'; intros n logn P2.\n  destruct (Z_one_bits wordsize (unsigned n) 0) as [ | i [ | ? ?]] eqn:B; inv P2.\n  assert (0 <= i < zwordsize).\n  { apply Z_one_bits_range with (unsigned n). rewrite B; auto with coqlib. }\n  rewrite Int.unsigned_repr. auto.\n  assert (zwordsize < Int.max_unsigned) by reflexivity.\n  lia.\nQed.\n\nTheorem is_power2'_range:\n  forall n logn,\n  is_power2' n = Some logn -> Int.ltu logn iwordsize' = true.\nProof.\n  intros. unfold Int.ltu. change (Int.unsigned iwordsize') with zwordsize.\n  apply zlt_true. generalize (is_power2'_rng _ _ H). tauto.\nQed.\n\nLemma is_power2'_correct:\n  forall n logn,\n  is_power2' n = Some logn ->\n  unsigned n = two_p (Int.unsigned logn).\nProof.\n  unfold is_power2'; intros.\n  destruct (Z_one_bits wordsize (unsigned n) 0) as [ | i [ | ? ?]] eqn:B; inv H.\n  rewrite (Z_one_bits_powerserie wordsize (unsigned n)) by (apply unsigned_range).\n  rewrite Int.unsigned_repr. rewrite B; simpl. lia.\n  assert (0 <= i < zwordsize).\n  { apply Z_one_bits_range with (unsigned n). rewrite B; auto with coqlib. }\n  assert (zwordsize < Int.max_unsigned) by reflexivity.\n  lia.\nQed.\n\nTheorem mul_pow2':\n  forall x n logn,\n  is_power2' n = Some logn ->\n  mul x n = shl' x logn.\nProof.\n  intros. rewrite shl'_mul. f_equal. rewrite shl'_one_two_p.\n  rewrite <- (repr_unsigned n). f_equal. apply is_power2'_correct; auto.\nQed.\n\nTheorem divu_pow2':\n  forall x n logn,\n  is_power2' n = Some logn ->\n  divu x n = shru' x logn.\nProof.\n  intros. generalize (is_power2'_correct n logn H). intro.\n  symmetry. unfold divu. rewrite H0. unfold shru'. rewrite Zshiftr_div_two_p. auto.\n  eapply is_power2'_rng; eauto.\nQed.\n\n(** Decomposing 64-bit ints as pairs of 32-bit ints *)\n\nDefinition loword (n: int) : Int.int := Int.repr (unsigned n).\n\nDefinition hiword (n: int) : Int.int := Int.repr (unsigned (shru n (repr Int.zwordsize))).\n\nDefinition ofwords (hi lo: Int.int) : int :=\n  or (shl (repr (Int.unsigned hi)) (repr Int.zwordsize)) (repr (Int.unsigned lo)).\n\nLemma bits_loword:\n  forall n i, 0 <= i < Int.zwordsize -> Int.testbit (loword n) i = testbit n i.\nProof.\n  intros. unfold loword. rewrite Int.testbit_repr; auto.\nQed.\n\nLemma bits_hiword:\n  forall n i, 0 <= i < Int.zwordsize -> Int.testbit (hiword n) i = testbit n (i + Int.zwordsize).\nProof.\n  intros. unfold hiword. rewrite Int.testbit_repr; auto.\n  assert (zwordsize = 2 * Int.zwordsize) by reflexivity.\n  fold (testbit (shru n (repr Int.zwordsize)) i). rewrite bits_shru.\n  change (unsigned (repr Int.zwordsize)) with Int.zwordsize.\n  apply zlt_true. lia. lia.\nQed.\n\nLemma bits_ofwords:\n  forall hi lo i, 0 <= i < zwordsize ->\n  testbit (ofwords hi lo) i =\n  if zlt i Int.zwordsize then Int.testbit lo i else Int.testbit hi (i - Int.zwordsize).\nProof.\n  intros. unfold ofwords. rewrite bits_or; auto. rewrite bits_shl; auto.\n  change (unsigned (repr Int.zwordsize)) with Int.zwordsize.\n  assert (zwordsize = 2 * Int.zwordsize) by reflexivity.\n  destruct (zlt i Int.zwordsize).\n  rewrite testbit_repr; auto.\n  rewrite !testbit_repr; auto.\n  fold (Int.testbit lo i). rewrite Int.bits_above. apply orb_false_r. auto.\n  lia.\nQed.\n\nLemma lo_ofwords:\n  forall hi lo, loword (ofwords hi lo) = lo.\nProof.\n  intros. apply Int.same_bits_eq; intros.\n  rewrite bits_loword; auto. rewrite bits_ofwords. apply zlt_true. lia.\n  assert (zwordsize = 2 * Int.zwordsize) by reflexivity. lia.\nQed.\n\nLemma hi_ofwords:\n  forall hi lo, hiword (ofwords hi lo) = hi.\nProof.\n  intros. apply Int.same_bits_eq; intros.\n  rewrite bits_hiword; auto. rewrite bits_ofwords.\n  rewrite zlt_false. f_equal. lia. lia.\n  assert (zwordsize = 2 * Int.zwordsize) by reflexivity. lia.\nQed.\n\nLemma ofwords_recompose:\n  forall n, ofwords (hiword n) (loword n) = n.\nProof.\n  intros. apply same_bits_eq; intros. rewrite bits_ofwords; auto.\n  destruct (zlt i Int.zwordsize).\n  apply bits_loword. lia.\n  rewrite bits_hiword. f_equal. lia.\n  assert (zwordsize = 2 * Int.zwordsize) by reflexivity. lia.\nQed.\n\nLemma ofwords_add:\n  forall lo hi, ofwords hi lo = repr (Int.unsigned hi * two_p 32 + Int.unsigned lo).\nProof.\n  intros. unfold ofwords. rewrite shifted_or_is_add.\n  apply eqm_samerepr. apply eqm_add. apply eqm_mult.\n  apply eqm_sym; apply eqm_unsigned_repr.\n  apply eqm_refl.\n  apply eqm_sym; apply eqm_unsigned_repr.\n  change Int.zwordsize with 32; change zwordsize with 64; lia.\n  rewrite unsigned_repr. generalize (Int.unsigned_range lo). intros [A B]. exact B.\n  assert (Int.max_unsigned < max_unsigned) by (compute; auto).\n  generalize (Int.unsigned_range_2 lo); lia.\nQed.\n\nLemma ofwords_add':\n  forall lo hi, unsigned (ofwords hi lo) = Int.unsigned hi * two_p 32 + Int.unsigned lo.\nProof.\n  intros. rewrite ofwords_add. apply unsigned_repr.\n  generalize (Int.unsigned_range hi) (Int.unsigned_range lo).\n  change (two_p 32) with Int.modulus.\n  change Int.modulus with 4294967296.\n  change max_unsigned with 18446744073709551615.\n  lia.\nQed.\n\nRemark eqm_mul_2p32:\n  forall x y, Int.eqm x y -> eqm (x * two_p 32) (y * two_p 32).\nProof.\n  intros. destruct H as [k EQ]. exists k. rewrite EQ.\n  change Int.modulus with (two_p 32).\n  change modulus with (two_p 32 * two_p 32).\n  ring.\nQed.\n\nLemma ofwords_add'':\n  forall lo hi, signed (ofwords hi lo) = Int.signed hi * two_p 32 + Int.unsigned lo.\nProof.\n  intros. rewrite ofwords_add.\n  replace (repr (Int.unsigned hi * two_p 32 + Int.unsigned lo))\n     with (repr (Int.signed hi * two_p 32 + Int.unsigned lo)).\n  apply signed_repr.\n  generalize (Int.signed_range hi) (Int.unsigned_range lo).\n  change (two_p 32) with Int.modulus.\n  change min_signed with (Int.min_signed * Int.modulus).\n  change max_signed with (Int.max_signed * Int.modulus + Int.modulus - 1).\n  change Int.modulus with 4294967296.\n  lia.\n  apply eqm_samerepr. apply eqm_add. apply eqm_mul_2p32. apply Int.eqm_signed_unsigned. apply eqm_refl.\nQed.\n\n(** Expressing 64-bit operations in terms of 32-bit operations *)\n\nLemma decompose_bitwise_binop:\n  forall f f64 f32 xh xl yh yl,\n  (forall x y i, 0 <= i < zwordsize -> testbit (f64 x y) i = f (testbit x i) (testbit y i)) ->\n  (forall x y i, 0 <= i < Int.zwordsize -> Int.testbit (f32 x y) i = f (Int.testbit x i) (Int.testbit y i)) ->\n  f64 (ofwords xh xl) (ofwords yh yl) = ofwords (f32 xh yh) (f32 xl yl).\nProof.\n  intros. apply Int64.same_bits_eq; intros.\n  rewrite H by auto. rewrite ! bits_ofwords by auto.\n  assert (zwordsize = 2 * Int.zwordsize) by reflexivity.\n  destruct (zlt i Int.zwordsize); rewrite H0 by lia; auto.\nQed.\n\nLemma decompose_and:\n  forall xh xl yh yl,\n  and (ofwords xh xl) (ofwords yh yl) = ofwords (Int.and xh yh) (Int.and xl yl).\nProof.\n  intros. apply decompose_bitwise_binop with andb.\n  apply bits_and. apply Int.bits_and.\nQed.\n\nLemma decompose_or:\n  forall xh xl yh yl,\n  or (ofwords xh xl) (ofwords yh yl) = ofwords (Int.or xh yh) (Int.or xl yl).\nProof.\n  intros. apply decompose_bitwise_binop with orb.\n  apply bits_or. apply Int.bits_or.\nQed.\n\nLemma decompose_xor:\n  forall xh xl yh yl,\n  xor (ofwords xh xl) (ofwords yh yl) = ofwords (Int.xor xh yh) (Int.xor xl yl).\nProof.\n  intros. apply decompose_bitwise_binop with xorb.\n  apply bits_xor. apply Int.bits_xor.\nQed.\n\nLemma decompose_not:\n  forall xh xl,\n  not (ofwords xh xl) = ofwords (Int.not xh) (Int.not xl).\nProof.\n  intros. unfold not, Int.not. rewrite <- decompose_xor. f_equal.\n  apply (Int64.eq_spec mone (ofwords Int.mone Int.mone)).\nQed.\n\nLemma decompose_shl_1:\n  forall xh xl y,\n  0 <= Int.unsigned y < Int.zwordsize ->\n  shl' (ofwords xh xl) y =\n  ofwords (Int.or (Int.shl xh y) (Int.shru xl (Int.sub Int.iwordsize y)))\n          (Int.shl xl y).\nProof.\n  intros.\n  assert (Int.unsigned (Int.sub Int.iwordsize y) = Int.zwordsize - Int.unsigned y).\n  { unfold Int.sub. rewrite Int.unsigned_repr. auto.\n    rewrite Int.unsigned_repr_wordsize. generalize Int.wordsize_max_unsigned; lia. }\n  assert (zwordsize = 2 * Int.zwordsize) by reflexivity.\n  apply Int64.same_bits_eq; intros.\n  rewrite bits_shl' by auto. symmetry. rewrite bits_ofwords by auto.\n  destruct (zlt i Int.zwordsize). rewrite Int.bits_shl by lia.\n  destruct (zlt i (Int.unsigned y)). auto.\n  rewrite bits_ofwords by lia. rewrite zlt_true by lia. auto.\n  rewrite zlt_false by lia. rewrite bits_ofwords by lia.\n  rewrite Int.bits_or by lia. rewrite Int.bits_shl by lia.\n  rewrite Int.bits_shru by lia. rewrite H0.\n  destruct (zlt (i - Int.unsigned y) (Int.zwordsize)).\n  rewrite zlt_true by lia. rewrite zlt_true by lia.\n  rewrite orb_false_l. f_equal. lia.\n  rewrite zlt_false by lia. rewrite zlt_false by lia.\n  rewrite orb_false_r. f_equal. lia.\nQed.\n\nLemma decompose_shl_2:\n  forall xh xl y,\n  Int.zwordsize <= Int.unsigned y < zwordsize ->\n  shl' (ofwords xh xl) y =\n  ofwords (Int.shl xl (Int.sub y Int.iwordsize)) Int.zero.\nProof.\n  intros.\n  assert (zwordsize = 2 * Int.zwordsize) by reflexivity.\n  assert (Int.unsigned (Int.sub y Int.iwordsize) = Int.unsigned y - Int.zwordsize).\n  { unfold Int.sub. rewrite Int.unsigned_repr. auto.\n    rewrite Int.unsigned_repr_wordsize. generalize (Int.unsigned_range_2 y). lia. }\n  apply Int64.same_bits_eq; intros.\n  rewrite bits_shl' by auto. symmetry. rewrite bits_ofwords by auto.\n  destruct (zlt i Int.zwordsize). rewrite zlt_true by lia. apply Int.bits_zero.\n  rewrite Int.bits_shl by lia.\n  destruct (zlt i (Int.unsigned y)).\n  rewrite zlt_true by lia. auto.\n  rewrite zlt_false by lia.\n  rewrite bits_ofwords by lia. rewrite zlt_true by lia. f_equal. lia.\nQed.\n\nLemma decompose_shru_1:\n  forall xh xl y,\n  0 <= Int.unsigned y < Int.zwordsize ->\n  shru' (ofwords xh xl) y =\n  ofwords (Int.shru xh y)\n          (Int.or (Int.shru xl y) (Int.shl xh (Int.sub Int.iwordsize y))).\nProof.\n  intros.\n  assert (Int.unsigned (Int.sub Int.iwordsize y) = Int.zwordsize - Int.unsigned y).\n  { unfold Int.sub. rewrite Int.unsigned_repr. auto.\n    rewrite Int.unsigned_repr_wordsize. generalize Int.wordsize_max_unsigned; lia. }\n  assert (zwordsize = 2 * Int.zwordsize) by reflexivity.\n  apply Int64.same_bits_eq; intros.\n  rewrite bits_shru' by auto. symmetry. rewrite bits_ofwords by auto.\n  destruct (zlt i Int.zwordsize).\n  rewrite zlt_true by lia.\n  rewrite bits_ofwords by lia.\n  rewrite Int.bits_or by lia. rewrite Int.bits_shl by lia.\n  rewrite Int.bits_shru by lia. rewrite H0.\n  destruct (zlt (i + Int.unsigned y) (Int.zwordsize)).\n  rewrite zlt_true by lia.\n  rewrite orb_false_r. auto.\n  rewrite zlt_false by lia.\n  rewrite orb_false_l. f_equal. lia.\n  rewrite Int.bits_shru by lia.\n  destruct (zlt (i + Int.unsigned y) zwordsize).\n  rewrite bits_ofwords by lia.\n  rewrite zlt_true by lia. rewrite zlt_false by lia. f_equal. lia.\n  rewrite zlt_false by lia. auto.\nQed.\n\nLemma decompose_shru_2:\n  forall xh xl y,\n  Int.zwordsize <= Int.unsigned y < zwordsize ->\n  shru' (ofwords xh xl) y =\n  ofwords Int.zero (Int.shru xh (Int.sub y Int.iwordsize)).\nProof.\n  intros.\n  assert (zwordsize = 2 * Int.zwordsize) by reflexivity.\n  assert (Int.unsigned (Int.sub y Int.iwordsize) = Int.unsigned y - Int.zwordsize).\n  { unfold Int.sub. rewrite Int.unsigned_repr. auto.\n    rewrite Int.unsigned_repr_wordsize. generalize (Int.unsigned_range_2 y). lia. }\n  apply Int64.same_bits_eq; intros.\n  rewrite bits_shru' by auto. symmetry. rewrite bits_ofwords by auto.\n  destruct (zlt i Int.zwordsize).\n  rewrite Int.bits_shru by lia. rewrite H1.\n  destruct (zlt (i + Int.unsigned y) zwordsize).\n  rewrite zlt_true by lia. rewrite bits_ofwords by lia.\n  rewrite zlt_false by lia. f_equal; lia.\n  rewrite zlt_false by lia. auto.\n  rewrite zlt_false by lia. apply Int.bits_zero.\nQed.\n\nLemma decompose_shr_1:\n  forall xh xl y,\n  0 <= Int.unsigned y < Int.zwordsize ->\n  shr' (ofwords xh xl) y =\n  ofwords (Int.shr xh y)\n          (Int.or (Int.shru xl y) (Int.shl xh (Int.sub Int.iwordsize y))).\nProof.\n  intros.\n  assert (Int.unsigned (Int.sub Int.iwordsize y) = Int.zwordsize - Int.unsigned y).\n  { unfold Int.sub. rewrite Int.unsigned_repr. auto.\n    rewrite Int.unsigned_repr_wordsize. generalize Int.wordsize_max_unsigned; lia. }\n  assert (zwordsize = 2 * Int.zwordsize) by reflexivity.\n  apply Int64.same_bits_eq; intros.\n  rewrite bits_shr' by auto. symmetry. rewrite bits_ofwords by auto.\n  destruct (zlt i Int.zwordsize).\n  rewrite zlt_true by lia.\n  rewrite bits_ofwords by lia.\n  rewrite Int.bits_or by lia. rewrite Int.bits_shl by lia.\n  rewrite Int.bits_shru by lia. rewrite H0.\n  destruct (zlt (i + Int.unsigned y) (Int.zwordsize)).\n  rewrite zlt_true by lia.\n  rewrite orb_false_r. auto.\n  rewrite zlt_false by lia.\n  rewrite orb_false_l. f_equal. lia.\n  rewrite Int.bits_shr by lia.\n  destruct (zlt (i + Int.unsigned y) zwordsize).\n  rewrite bits_ofwords by lia.\n  rewrite zlt_true by lia. rewrite zlt_false by lia. f_equal. lia.\n  rewrite zlt_false by lia. rewrite bits_ofwords by lia.\n  rewrite zlt_false by lia. f_equal.\nQed.\n\nLemma decompose_shr_2:\n  forall xh xl y,\n  Int.zwordsize <= Int.unsigned y < zwordsize ->\n  shr' (ofwords xh xl) y =\n  ofwords (Int.shr xh (Int.sub Int.iwordsize Int.one))\n          (Int.shr xh (Int.sub y Int.iwordsize)).\nProof.\n  intros.\n  assert (zwordsize = 2 * Int.zwordsize) by reflexivity.\n  assert (Int.unsigned (Int.sub y Int.iwordsize) = Int.unsigned y - Int.zwordsize).\n  { unfold Int.sub. rewrite Int.unsigned_repr. auto.\n    rewrite Int.unsigned_repr_wordsize. generalize (Int.unsigned_range_2 y). lia. }\n  apply Int64.same_bits_eq; intros.\n  rewrite bits_shr' by auto. symmetry. rewrite bits_ofwords by auto.\n  destruct (zlt i Int.zwordsize).\n  rewrite Int.bits_shr by lia. rewrite H1.\n  destruct (zlt (i + Int.unsigned y) zwordsize).\n  rewrite zlt_true by lia. rewrite bits_ofwords by lia.\n  rewrite zlt_false by lia. f_equal; lia.\n  rewrite zlt_false by lia. rewrite bits_ofwords by lia.\n  rewrite zlt_false by lia. auto.\n  rewrite Int.bits_shr by lia.\n  change (Int.unsigned (Int.sub Int.iwordsize Int.one)) with (Int.zwordsize - 1).\n  destruct (zlt (i + Int.unsigned y) zwordsize);\n  rewrite bits_ofwords by lia.\n  symmetry. rewrite zlt_false by lia. f_equal.\n  destruct (zlt (i - Int.zwordsize + (Int.zwordsize - 1)) Int.zwordsize); lia.\n  symmetry. rewrite zlt_false by lia. f_equal.\n  destruct (zlt (i - Int.zwordsize + (Int.zwordsize - 1)) Int.zwordsize); lia.\nQed.\n\nLemma decompose_add:\n  forall xh xl yh yl,\n  add (ofwords xh xl) (ofwords yh yl) =\n  ofwords (Int.add (Int.add xh yh) (Int.add_carry xl yl Int.zero))\n          (Int.add xl yl).\nProof.\n  intros. symmetry. rewrite ofwords_add. rewrite add_unsigned.\n  apply eqm_samerepr.\n  rewrite ! ofwords_add'. rewrite (Int.unsigned_add_carry xl yl).\n  set (cc := Int.add_carry xl yl Int.zero).\n  set (Xl := Int.unsigned xl); set (Xh := Int.unsigned xh);\n  set (Yl := Int.unsigned yl); set (Yh := Int.unsigned yh).\n  change Int.modulus with (two_p 32).\n  replace (Xh * two_p 32 + Xl + (Yh * two_p 32 + Yl))\n     with ((Xh + Yh) * two_p 32 + (Xl + Yl)) by ring.\n  replace (Int.unsigned (Int.add (Int.add xh yh) cc) * two_p 32 +\n              (Xl + Yl - Int.unsigned cc * two_p 32))\n     with ((Int.unsigned (Int.add (Int.add xh yh) cc) - Int.unsigned cc) * two_p 32\n           + (Xl + Yl)) by ring.\n  apply eqm_add. 2: apply eqm_refl. apply eqm_mul_2p32.\n  replace (Xh + Yh) with ((Xh + Yh + Int.unsigned cc) - Int.unsigned cc) by ring.\n  apply Int.eqm_sub. 2: apply Int.eqm_refl.\n  apply Int.eqm_unsigned_repr_l. apply Int.eqm_add. 2: apply Int.eqm_refl.\n  apply Int.eqm_unsigned_repr_l. apply Int.eqm_refl.\nQed.\n\nLemma decompose_sub:\n  forall xh xl yh yl,\n  sub (ofwords xh xl) (ofwords yh yl) =\n  ofwords (Int.sub (Int.sub xh yh) (Int.sub_borrow xl yl Int.zero))\n          (Int.sub xl yl).\nProof.\n  intros. symmetry. rewrite ofwords_add.\n  apply eqm_samerepr.\n  rewrite ! ofwords_add'. rewrite (Int.unsigned_sub_borrow xl yl).\n  set (bb := Int.sub_borrow xl yl Int.zero).\n  set (Xl := Int.unsigned xl); set (Xh := Int.unsigned xh);\n  set (Yl := Int.unsigned yl); set (Yh := Int.unsigned yh).\n  change Int.modulus with (two_p 32).\n  replace (Xh * two_p 32 + Xl - (Yh * two_p 32 + Yl))\n     with ((Xh - Yh) * two_p 32 + (Xl - Yl)) by ring.\n  replace (Int.unsigned (Int.sub (Int.sub xh yh) bb) * two_p 32 +\n              (Xl - Yl + Int.unsigned bb * two_p 32))\n     with ((Int.unsigned (Int.sub (Int.sub xh yh) bb) + Int.unsigned bb) * two_p 32\n           + (Xl - Yl)) by ring.\n  apply eqm_add. 2: apply eqm_refl. apply eqm_mul_2p32.\n  replace (Xh - Yh) with ((Xh - Yh - Int.unsigned bb) + Int.unsigned bb) by ring.\n  apply Int.eqm_add. 2: apply Int.eqm_refl.\n  apply Int.eqm_unsigned_repr_l. apply Int.eqm_add. 2: apply Int.eqm_refl.\n  apply Int.eqm_unsigned_repr_l. apply Int.eqm_refl.\nQed.\n\nLemma decompose_sub':\n  forall xh xl yh yl,\n  sub (ofwords xh xl) (ofwords yh yl) =\n  ofwords (Int.add (Int.add xh (Int.not yh)) (Int.add_carry xl (Int.not yl) Int.one))\n          (Int.sub xl yl).\nProof.\n  intros. rewrite decompose_sub. f_equal.\n  rewrite Int.sub_borrow_add_carry by auto.\n  rewrite Int.sub_add_not_3. rewrite Int.xor_assoc. rewrite Int.xor_idem.\n  rewrite Int.xor_zero. auto.\n  rewrite Int.xor_zero_l. unfold Int.add_carry.\n  destruct (zlt (Int.unsigned xl + Int.unsigned (Int.not yl) + Int.unsigned Int.one) Int.modulus);\n  compute; [right|left]; apply Int.mkint_eq; auto.\nQed.\n\nDefinition mul' (x y: Int.int) : int := repr (Int.unsigned x * Int.unsigned y).\n\nLemma mul'_mulhu:\n  forall x y, mul' x y = ofwords (Int.mulhu x y) (Int.mul x y).\nProof.\n  intros.\n  rewrite ofwords_add. unfold mul', Int.mulhu, Int.mul.\n  set (p := Int.unsigned x * Int.unsigned y).\n  set (ph := p / Int.modulus). set (pl := p mod Int.modulus).\n  transitivity (repr (ph * Int.modulus + pl)).\n- f_equal. rewrite Z.mul_comm. apply Z_div_mod_eq. apply Int.modulus_pos.\n- apply eqm_samerepr. apply eqm_add. apply eqm_mul_2p32. auto with ints.\n  rewrite Int.unsigned_repr_eq. apply eqm_refl.\nQed.\n\nLemma decompose_mul:\n  forall xh xl yh yl,\n  mul (ofwords xh xl) (ofwords yh yl) =\n  ofwords (Int.add (Int.add (hiword (mul' xl yl)) (Int.mul xl yh)) (Int.mul xh yl))\n          (loword (mul' xl yl)).\nProof.\n  intros.\n  set (pl := loword (mul' xl yl)); set (ph := hiword (mul' xl yl)).\n  assert (EQ0: unsigned (mul' xl yl) = Int.unsigned ph * two_p 32 + Int.unsigned pl).\n  { rewrite <- (ofwords_recompose (mul' xl yl)). apply ofwords_add'. }\n  symmetry. rewrite ofwords_add. unfold mul. rewrite !ofwords_add'.\n  set (XL := Int.unsigned xl); set (XH := Int.unsigned xh);\n  set (YL := Int.unsigned yl); set (YH := Int.unsigned yh).\n  set (PH := Int.unsigned ph) in *. set (PL := Int.unsigned pl) in *.\n  transitivity (repr (((PH + XL * YH) + XH * YL) * two_p 32 + PL)).\n  apply eqm_samerepr. apply eqm_add. 2: apply eqm_refl.\n  apply eqm_mul_2p32.\n  rewrite Int.add_unsigned. apply Int.eqm_unsigned_repr_l. apply Int.eqm_add.\n  rewrite Int.add_unsigned. apply Int.eqm_unsigned_repr_l. apply Int.eqm_add.\n  apply Int.eqm_refl.\n  unfold Int.mul. apply Int.eqm_unsigned_repr_l. apply Int.eqm_refl.\n  unfold Int.mul. apply Int.eqm_unsigned_repr_l. apply Int.eqm_refl.\n  transitivity (repr (unsigned (mul' xl yl) + (XL * YH + XH * YL) * two_p 32)).\n  rewrite EQ0. f_equal. ring.\n  transitivity (repr ((XL * YL + (XL * YH + XH * YL) * two_p 32))).\n  apply eqm_samerepr. apply eqm_add. 2: apply eqm_refl.\n  unfold mul'. apply eqm_unsigned_repr_l. apply eqm_refl.\n  transitivity (repr (0 + (XL * YL + (XL * YH + XH * YL) * two_p 32))).\n  rewrite Z.add_0_l; auto.\n  transitivity (repr (XH * YH * (two_p 32 * two_p 32) + (XL * YL + (XL * YH + XH * YL) * two_p 32))).\n  apply eqm_samerepr. apply eqm_add. 2: apply eqm_refl.\n  change (two_p 32 * two_p 32) with modulus. exists (- XH * YH). ring.\n  f_equal. ring.\nQed.\n\nLemma decompose_mul_2:\n  forall xh xl yh yl,\n  mul (ofwords xh xl) (ofwords yh yl) =\n  ofwords (Int.add (Int.add (Int.mulhu xl yl) (Int.mul xl yh)) (Int.mul xh yl))\n          (Int.mul xl yl).\nProof.\n  intros. rewrite decompose_mul. rewrite mul'_mulhu.\n  rewrite hi_ofwords, lo_ofwords. auto.\nQed.\n\nLemma decompose_ltu:\n  forall xh xl yh yl,\n  ltu (ofwords xh xl) (ofwords yh yl) = if Int.eq xh yh then Int.ltu xl yl else Int.ltu xh yh.\nProof.\n  intros. unfold ltu. rewrite ! ofwords_add'. unfold Int.ltu, Int.eq.\n  destruct (zeq (Int.unsigned xh) (Int.unsigned yh)).\n  rewrite e. destruct (zlt (Int.unsigned xl) (Int.unsigned yl)).\n  apply zlt_true; lia.\n  apply zlt_false; lia.\n  change (two_p 32) with Int.modulus.\n  generalize (Int.unsigned_range xl) (Int.unsigned_range yl).\n  change Int.modulus with 4294967296. intros.\n  destruct (zlt (Int.unsigned xh) (Int.unsigned yh)).\n  apply zlt_true; lia.\n  apply zlt_false; lia.\nQed.\n\nLemma decompose_leu:\n  forall xh xl yh yl,\n  negb (ltu (ofwords yh yl) (ofwords xh xl)) =\n  if Int.eq xh yh then negb (Int.ltu yl xl) else Int.ltu xh yh.\nProof.\n  intros. rewrite decompose_ltu. rewrite Int.eq_sym.\n  unfold Int.eq. destruct (zeq (Int.unsigned xh) (Int.unsigned yh)).\n  auto.\n  unfold Int.ltu. destruct (zlt (Int.unsigned xh) (Int.unsigned yh)).\n  rewrite zlt_false by lia; auto.\n  rewrite zlt_true by lia; auto.\nQed.\n\nLemma decompose_lt:\n  forall xh xl yh yl,\n  lt (ofwords xh xl) (ofwords yh yl) = if Int.eq xh yh then Int.ltu xl yl else Int.lt xh yh.\nProof.\n  intros. unfold lt. rewrite ! ofwords_add''. rewrite Int.eq_signed.\n  destruct (zeq (Int.signed xh) (Int.signed yh)).\n  rewrite e. unfold Int.ltu. destruct (zlt (Int.unsigned xl) (Int.unsigned yl)).\n  apply zlt_true; lia.\n  apply zlt_false; lia.\n  change (two_p 32) with Int.modulus.\n  generalize (Int.unsigned_range xl) (Int.unsigned_range yl).\n  change Int.modulus with 4294967296. intros.\n  unfold Int.lt. destruct (zlt (Int.signed xh) (Int.signed yh)).\n  apply zlt_true; lia.\n  apply zlt_false; lia.\nQed.\n\nLemma decompose_le:\n  forall xh xl yh yl,\n  negb (lt (ofwords yh yl) (ofwords xh xl)) =\n  if Int.eq xh yh then negb (Int.ltu yl xl) else Int.lt xh yh.\nProof.\n  intros. rewrite decompose_lt. rewrite Int.eq_sym.\n  rewrite Int.eq_signed. destruct (zeq (Int.signed xh) (Int.signed yh)).\n  auto.\n  unfold Int.lt. destruct (zlt (Int.signed xh) (Int.signed yh)).\n  rewrite zlt_false by lia; auto.\n  rewrite zlt_true by lia; auto.\nQed.\n\n(** Utility proofs for mixed 32bit and 64bit arithmetic *)\n\nRemark int_unsigned_range:\n  forall x, 0 <= Int.unsigned x <= max_unsigned.\nProof.\n  intros.\n  unfold max_unsigned. unfold modulus.\n  generalize (Int.unsigned_range x).\n  unfold Int.modulus in *.\n  change (wordsize) with  64%nat in *.\n  change (Int.wordsize) with 32%nat in *.\n  unfold two_power_nat. simpl.\n  lia.\nQed.\n\nRemark int_unsigned_repr:\n  forall x, unsigned (repr (Int.unsigned x)) = Int.unsigned x.\nProof.\n  intros. rewrite unsigned_repr. auto.\n  apply int_unsigned_range.\nQed.\n\nLemma int_sub_ltu:\n  forall x y,\n    Int.ltu x y= true ->\n    Int.unsigned (Int.sub y x) = unsigned (sub (repr (Int.unsigned y)) (repr (Int.unsigned x))).\nProof.\n  intros. generalize (Int.sub_ltu x y H). intros. unfold Int.sub. unfold sub.\n  rewrite Int.unsigned_repr. rewrite unsigned_repr.\n  rewrite unsigned_repr by apply int_unsigned_range. rewrite int_unsigned_repr. reflexivity.\n  rewrite unsigned_repr by apply int_unsigned_range.\n  rewrite int_unsigned_repr. generalize (int_unsigned_range y).\n  lia.\n  generalize (Int.sub_ltu x y H). intros.\n  generalize (Int.unsigned_range_2 y). intros. lia.\nQed.\n\nEnd Int64.\n\nStrategy 0 [Wordsize_64.wordsize].\n\nNotation int64 := Int64.int.\n\nGlobal Opaque Int.repr Int64.repr Byte.repr.\n\n(** * Specialization to offsets in pointer values *)\n\nModule Wordsize_Ptrofs.\n  Definition wordsize := if Archi.ptr64 then 64%nat else 32%nat.\n  Remark wordsize_not_zero: wordsize <> 0%nat.\n  Proof. unfold wordsize; destruct Archi.ptr64; congruence. Qed.\nEnd Wordsize_Ptrofs.\n\nStrategy opaque [Wordsize_Ptrofs.wordsize].\n\nModule Ptrofs.\n\nInclude Make(Wordsize_Ptrofs).\n\nDefinition to_int (x: int): Int.int := Int.repr (unsigned x).\n\nDefinition to_int64 (x: int): Int64.int := Int64.repr (unsigned x).\n\nDefinition of_int (x: Int.int) : int := repr (Int.unsigned x).\n\nDefinition of_intu := of_int.\n\nDefinition of_ints (x: Int.int) : int := repr (Int.signed x).\n\nDefinition of_int64 (x: Int64.int) : int := repr (Int64.unsigned x).\n\nDefinition of_int64u := of_int64.\n\nDefinition of_int64s (x: Int64.int) : int := repr (Int64.signed x).\n\nSection AGREE32.\n\nHypothesis _32: Archi.ptr64 = false.\n\nLemma modulus_eq32: modulus = Int.modulus.\nProof.\n  unfold modulus, wordsize.\n  change Wordsize_Ptrofs.wordsize with (if Archi.ptr64 then 64%nat else 32%nat).\n  rewrite _32. reflexivity.\nQed.\n\nLemma eqm32:\n  forall x y, Int.eqm x y <-> eqm x y.\nProof.\n  intros. unfold Int.eqm, eqm. rewrite modulus_eq32; tauto.\nQed.\n\nDefinition agree32 (a: Ptrofs.int) (b: Int.int) : Prop :=\n  Ptrofs.unsigned a = Int.unsigned b.\n\nLemma agree32_repr:\n  forall i, agree32 (Ptrofs.repr i) (Int.repr i).\nProof.\n  intros; red. rewrite Ptrofs.unsigned_repr_eq, Int.unsigned_repr_eq.\n  apply f_equal2. auto. apply modulus_eq32.\nQed.\n\nLemma agree32_signed:\n  forall a b, agree32 a b -> Ptrofs.signed a = Int.signed b.\nProof.\n  unfold agree32; intros. unfold signed, Int.signed, half_modulus, Int.half_modulus.\n  rewrite modulus_eq32. rewrite H. auto.\nQed.\n\nLemma agree32_of_int:\n  forall b, agree32 (of_int b) b.\nProof.\n  unfold of_int; intros. rewrite <- (Int.repr_unsigned b) at 2. apply agree32_repr.\nQed.\n\nLemma agree32_of_ints:\n  forall b, agree32 (of_ints b) b.\nProof.\n  unfold of_int; intros. rewrite <- (Int.repr_signed b) at 2. apply agree32_repr.\nQed.\n\nLemma agree32_of_int_eq:\n  forall a b, agree32 a b -> of_int b = a.\nProof.\n  unfold agree32, of_int; intros. rewrite <- H. apply repr_unsigned.\nQed.\n\nLemma agree32_of_ints_eq:\n  forall a b, agree32 a b -> of_ints b = a.\nProof.\n  unfold of_ints; intros. erewrite <- agree32_signed by eauto. apply repr_signed.\nQed.\n\nLemma agree32_to_int:\n  forall a, agree32 a (to_int a).\nProof.\n  unfold agree32, to_int; intros. rewrite <- (agree32_repr (unsigned a)).\n  rewrite repr_unsigned; auto.\nQed.\n\nLemma agree32_to_int_eq:\n  forall a b, agree32 a b -> to_int a = b.\nProof.\n  unfold agree32, to_int; intros. rewrite H. apply Int.repr_unsigned.\nQed.\n\nLemma agree32_neg:\n  forall a1 b1, agree32 a1 b1 -> agree32 (Ptrofs.neg a1) (Int.neg b1).\nProof.\n  unfold agree32, Ptrofs.neg, Int.neg; intros. rewrite H. apply agree32_repr.\nQed.\n\nLemma agree32_add:\n  forall a1 b1 a2 b2,\n  agree32 a1 b1 -> agree32 a2 b2 -> agree32 (Ptrofs.add a1 a2) (Int.add b1 b2).\nProof.\n  unfold agree32, Ptrofs.add, Int.add; intros. rewrite H, H0. apply agree32_repr.\nQed.\n\nLemma agree32_sub:\n  forall a1 b1 a2 b2,\n  agree32 a1 b1 -> agree32 a2 b2 -> agree32 (Ptrofs.sub a1 a2) (Int.sub b1 b2).\nProof.\n  unfold agree32, Ptrofs.sub, Int.sub; intros. rewrite H, H0. apply agree32_repr.\nQed.\n\nLemma agree32_mul:\n  forall a1 b1 a2 b2,\n  agree32 a1 b1 -> agree32 a2 b2 -> agree32 (Ptrofs.mul a1 a2) (Int.mul b1 b2).\nProof.\n  unfold agree32, Ptrofs.mul, Int.mul; intros. rewrite H, H0. apply agree32_repr.\nQed.\n\nLemma agree32_divs:\n  forall a1 b1 a2 b2,\n  agree32 a1 b1 -> agree32 a2 b2 -> agree32 (Ptrofs.divs a1 a2) (Int.divs b1 b2).\nProof.\n  intros; unfold agree32, Ptrofs.divs, Int.divs.\n  erewrite ! agree32_signed by eauto. apply agree32_repr.\nQed.\n\nLemma of_int_to_int:\n  forall n, of_int (to_int n) = n.\nProof.\n  intros; unfold of_int, to_int. apply eqm_repr_eq. rewrite <- eqm32.\n  apply Int.eqm_sym; apply Int.eqm_unsigned_repr.\nQed.\n\nLemma to_int_of_int:\n  forall n, to_int (of_int n) = n.\nProof.\n  intros; unfold of_int, to_int. rewrite unsigned_repr. apply Int.repr_unsigned.\n  unfold max_unsigned. rewrite modulus_eq32. destruct (Int.unsigned_range n); lia.\nQed.\n\nEnd AGREE32.\n\nSection AGREE64.\n\nHypothesis _64: Archi.ptr64 = true.\n\nLemma modulus_eq64: modulus = Int64.modulus.\nProof.\n  unfold modulus, wordsize.\n  change Wordsize_Ptrofs.wordsize with (if Archi.ptr64 then 64%nat else 32%nat).\n  rewrite _64. reflexivity.\nQed.\n\nLemma eqm64:\n  forall x y, Int64.eqm x y <-> eqm x y.\nProof.\n  intros. unfold Int64.eqm, eqm. rewrite modulus_eq64; tauto.\nQed.\n\nDefinition agree64 (a: Ptrofs.int) (b: Int64.int) : Prop :=\n  Ptrofs.unsigned a = Int64.unsigned b.\n\nLemma agree64_repr:\n  forall i, agree64 (Ptrofs.repr i) (Int64.repr i).\nProof.\n  intros; red. rewrite Ptrofs.unsigned_repr_eq, Int64.unsigned_repr_eq.\n  apply f_equal2. auto. apply modulus_eq64.\nQed.\n\nLemma agree64_signed:\n  forall a b, agree64 a b -> Ptrofs.signed a = Int64.signed b.\nProof.\n  unfold agree64; intros. unfold signed, Int64.signed, half_modulus, Int64.half_modulus.\n  rewrite modulus_eq64. rewrite H. auto.\nQed.\n\nLemma agree64_of_int:\n  forall b, agree64 (of_int64 b) b.\nProof.\n  unfold of_int64; intros. rewrite <- (Int64.repr_unsigned b) at 2. apply agree64_repr.\nQed.\n\nLemma agree64_of_int_eq:\n  forall a b, agree64 a b -> of_int64 b = a.\nProof.\n  unfold agree64, of_int64; intros. rewrite <- H. apply repr_unsigned.\nQed.\n\nLemma agree64_to_int:\n  forall a, agree64 a (to_int64 a).\nProof.\n  unfold agree64, to_int64; intros. rewrite <- (agree64_repr (unsigned a)).\n  rewrite repr_unsigned; auto.\nQed.\n\nLemma agree64_to_int_eq:\n  forall a b, agree64 a b -> to_int64 a = b.\nProof.\n  unfold agree64, to_int64; intros. rewrite H. apply Int64.repr_unsigned.\nQed.\n\nLemma agree64_neg:\n  forall a1 b1, agree64 a1 b1 -> agree64 (Ptrofs.neg a1) (Int64.neg b1).\nProof.\n  unfold agree64, Ptrofs.neg, Int64.neg; intros. rewrite H. apply agree64_repr.\nQed.\n\nLemma agree64_add:\n  forall a1 b1 a2 b2,\n  agree64 a1 b1 -> agree64 a2 b2 -> agree64 (Ptrofs.add a1 a2) (Int64.add b1 b2).\nProof.\n  unfold agree64, Ptrofs.add, Int.add; intros. rewrite H, H0. apply agree64_repr.\nQed.\n\nLemma agree64_sub:\n  forall a1 b1 a2 b2,\n  agree64 a1 b1 -> agree64 a2 b2 -> agree64 (Ptrofs.sub a1 a2) (Int64.sub b1 b2).\nProof.\n  unfold agree64, Ptrofs.sub, Int.sub; intros. rewrite H, H0. apply agree64_repr.\nQed.\n\nLemma agree64_mul:\n  forall a1 b1 a2 b2,\n  agree64 a1 b1 -> agree64 a2 b2 -> agree64 (Ptrofs.mul a1 a2) (Int64.mul b1 b2).\nProof.\n  unfold agree64, Ptrofs.mul, Int.mul; intros. rewrite H, H0. apply agree64_repr.\nQed.\n\nLemma agree64_divs:\n  forall a1 b1 a2 b2,\n  agree64 a1 b1 -> agree64 a2 b2 -> agree64 (Ptrofs.divs a1 a2) (Int64.divs b1 b2).\nProof.\n  intros; unfold agree64, Ptrofs.divs, Int64.divs.\n  erewrite ! agree64_signed by eauto. apply agree64_repr.\nQed.\n\nLemma of_int64_to_int64:\n  forall n, of_int64 (to_int64 n) = n.\nProof.\n  intros; unfold of_int64, to_int64. apply eqm_repr_eq. rewrite <- eqm64.\n  apply Int64.eqm_sym; apply Int64.eqm_unsigned_repr.\nQed.\n\nLemma to_int64_of_int64:\n  forall n, to_int64 (of_int64 n) = n.\nProof.\n  intros; unfold of_int64, to_int64. rewrite unsigned_repr. apply Int64.repr_unsigned.\n  unfold max_unsigned. rewrite  modulus_eq64. destruct (Int64.unsigned_range n); lia.\nQed.\n\nEnd AGREE64.\n\nGlobal Hint Resolve\n  agree32_repr agree32_of_int agree32_of_ints agree32_of_int_eq agree32_of_ints_eq\n  agree32_to_int agree32_to_int_eq agree32_neg agree32_add agree32_sub agree32_mul agree32_divs\n  agree64_repr agree64_of_int agree64_of_int_eq\n  agree64_to_int agree64_to_int_eq agree64_neg agree64_add agree64_sub agree64_mul agree64_divs : ptrofs.\n\nEnd Ptrofs.\n\nStrategy 0 [Wordsize_Ptrofs.wordsize].\n\nNotation ptrofs := Ptrofs.int.\n\nGlobal Opaque Ptrofs.repr.\n\nGlobal Hint Resolve\n  Int.modulus_pos Int.eqm_refl Int.eqm_refl2 Int.eqm_sym Int.eqm_trans\n  Int.eqm_small_eq Int.eqm_add Int.eqm_neg Int.eqm_sub Int.eqm_mult\n  Int.eqm_unsigned_repr Int.eqm_unsigned_repr_l Int.eqm_unsigned_repr_r\n  Int.unsigned_range Int.unsigned_range_2\n  Int.repr_unsigned Int.repr_signed Int.unsigned_repr : ints.\n\nGlobal Hint Resolve\n  Int64.modulus_pos Int64.eqm_refl Int64.eqm_refl2 Int64.eqm_sym Int64.eqm_trans\n  Int64.eqm_small_eq Int64.eqm_add Int64.eqm_neg Int64.eqm_sub Int64.eqm_mult\n  Int64.eqm_unsigned_repr Int64.eqm_unsigned_repr_l Int64.eqm_unsigned_repr_r\n  Int64.unsigned_range Int64.unsigned_range_2\n  Int64.repr_unsigned Int64.repr_signed Int64.unsigned_repr : ints.\n\nGlobal Hint Resolve\n  Ptrofs.modulus_pos Ptrofs.eqm_refl Ptrofs.eqm_refl2 Ptrofs.eqm_sym Ptrofs.eqm_trans\n  Ptrofs.eqm_small_eq Ptrofs.eqm_add Ptrofs.eqm_neg Ptrofs.eqm_sub Ptrofs.eqm_mult\n  Ptrofs.eqm_unsigned_repr Ptrofs.eqm_unsigned_repr_l Ptrofs.eqm_unsigned_repr_r\n  Ptrofs.unsigned_range Ptrofs.unsigned_range_2\n  Ptrofs.repr_unsigned Ptrofs.repr_signed Ptrofs.unsigned_repr : ints.\n\n", "meta": {"author": "MisakaCenter", "repo": "AClightGen", "sha": "616d093b3ab6a2d4dd61807acb9398fa0089468c", "save_path": "github-repos/coq/MisakaCenter-AClightGen", "path": "github-repos/coq/MisakaCenter-AClightGen/AClightGen-616d093b3ab6a2d4dd61807acb9398fa0089468c/lib/Integers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.296651450865509}}
{"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 IndexedStreams.\nFrom Velus Require Import Stc.StcIsLast.\nFrom Velus Require Import Stc.StcIsVariable.\nFrom Velus Require Import Stc.StcIsDefined.\nFrom Velus Require Import Stc.StcIsSystem.\nFrom Velus Require Import Stc.StcOrdered.\nFrom Velus Require Import CoreExpr.CESyntax.\nFrom Velus Require Import Stc.StcSyntax.\nFrom Velus Require Import CoreExpr.CEClocking.\nFrom Velus Require Import Stc.StcClocking.\nFrom Velus Require Import CoreExpr.CESemantics.\nFrom Velus Require Import Stc.StcSemantics.\nFrom Velus Require Import CoreExpr.CEClockingSemantics.\nFrom Coq Require Import List.\n\n(** * Link (static) clocking predicates to (dynamic) semantic model *)\n\n(**\n\nThese results confirm the correctness of the clocking predicates wrt the\nsemantics. In particular, they are useful for relating static invariants to\ndynamic properties. They hold essentially due to the \"additional\" clocking\nconstraints in the NLustre semantic model.\n\n *)\n\nModule Type STCCLOCKINGSEMANTICS\n       (Import Ids      : IDS)\n       (Import Op       : OPERATORS)\n       (Import OpAux    : OPERATORS_AUX           Op)\n       (Import CESyn    : CESYNTAX                Op)\n       (Import Syn      : STCSYNTAX           Ids Op       CESyn)\n       (Import Str      : INDEXEDSTREAMS          Op OpAux)\n       (Import Last     : STCISLAST           Ids Op       CESyn Syn)\n       (Import Var      : STCISVARIABLE       Ids Op       CESyn Syn)\n       (Import Def      : STCISDEFINED        Ids Op       CESyn Syn Var Last)\n       (Import Syst     : STCISSYSTEM         Ids Op       CESyn Syn)\n       (Import Ord      : STCORDERED          Ids Op       CESyn Syn Syst)\n       (Import CESem    : CESEMANTICS         Ids Op OpAux CESyn               Str)\n       (Import Sem      : STCSEMANTICS        Ids Op OpAux CESyn Syn Syst Ord Str CESem)\n       (Import CEClo    : CECLOCKING          Ids Op       CESyn)\n       (Import Clkg     : STCCLOCKING         Ids Op       CESyn Syn Last Var Def Syst Ord CEClo)\n       (Import CECloSem : CECLOCKINGSEMANTICS Ids Op OpAux CESyn Str CESem                  CEClo).\n\n  Lemma sem_clocked_var_instant_tc:\n    forall P base R S I S' vars x ck tc,\n      Ordered_systems P ->\n      wc_program P ->\n      NoDupMembers vars ->\n      sem_trconstr P base R S I S' tc ->\n      wc_trconstr P vars tc ->\n      Is_defined_in_tc x tc ->\n      In (x, ck) vars ->\n      sem_clocked_var_instant base R x ck.\n  Proof.\n    intros ?????????? Ord WCP Nodup Sem WC Def Hin.\n    revert dependent ck; revert dependent x; revert dependent vars.\n    induction Sem as [????????? Hexp Hvar|\n                      ?????????? Find Hvar Hexp Find'|\n                      ?????????? Clock Find Init|\n                      ??????????????? Hexps Clock Rst Find System Vars Sub IH|\n                      ????????? Find Hins Houts Hvars Htcs ??? IH]\n                       using sem_trconstr_mult with\n        (P_system := fun f S xs ys S' =>\n                       forall base R s P',\n                         find_system f P = Some (s, P') ->\n                         base = clock_of_instant xs ->\n                         sem_vars_instant R (map fst s.(s_in)) xs ->\n                         sem_vars_instant R (map fst s.(s_out)) ys ->\n                         sem_clocked_vars_instant base R (idck s.(s_in)) ->\n                         sem_clocked_vars_instant base R (idck s.(s_out)));\n      intros; try inversion Def as [| |??????? Hyys];\n      try inversion WC\n        as [| | |?????? bl' ? sub Hfind' Hfai Hfao]; subst.\n\n    - match goal with H1:In (x, _) vars, H2:In (x, _) vars |- _ =>\n                      eapply NoDupMembers_det with (2:=H1) in H2; eauto; subst end.\n      unfold sem_clocked_var_instant.\n      inv Hexp; eauto; intuition; eauto; by_sem_det.\n\n    - match goal with H1:In (x, _) vars, H2:In (x, _) vars |- _ =>\n        eapply NoDupMembers_det with (2:=H1) in H2; eauto; subst end.\n      unfold sem_clocked_var_instant.\n      inv Hexp; eauto; intuition; eauto; by_sem_det.\n\n    - inversion_clear System as [?????? R' ?? Hfind Hvi Hvo Hsck].\n      specialize (IH _ _ _ _ Hfind eq_refl Hvi Hvo).\n      assert (Hvi' := Hvi).\n      rewrite <-map_fst_idck in Hvi'.\n      specialize (IH Hsck).\n      rewrite Hfind in Hfind'; inv Hfind'.\n\n      assert (forall x y ys,\n                 InMembers x (idck (bl'.(s_in) ++ bl'.(s_out))) ->\n                 sub x = Some y ->\n                 sem_var_instant R' x ys ->\n                 sem_var_instant R y ys) as Htranso.\n      { setoid_rewrite InMembers_idck.\n        intros; eapply sem_var_instant_transfer_out_instant\n                  with (xin := s_in bl') (xout := s_out bl'); eauto.\n        - pose proof bl'.(s_nodup) as Hnd.\n          rewrite 2 app_assoc in Hnd; apply NoDup_app_weaken in Hnd.\n          rewrite <-app_assoc, NoDup_swap, NoDup_app'_iff in Hnd.\n          rewrite fst_NoDupMembers, map_app; intuition.\n        - apply Forall2_impl_In with (2:=Hfai); intuition.\n        - apply Forall2_impl_In with (2:=Hfao); intuition.\n      }\n\n      rewrite <-map_fst_idck in Hvo. unfold idck in Hvo. rewrite map_map in Hvo.\n      unfold sem_vars_instant in Hvo.\n      rewrite Forall2_map_1 in Hvo.\n      apply Forall2_swap_args in Hfao.\n      apply Forall2_trans_ex with (1:=Hfao) in Hvo.\n      apply Forall2_swap_args in Vars.\n      apply Forall2_trans_ex with (1:=Hvo) in Vars.\n      apply Forall2_same in Vars.\n      eapply Forall_forall in Vars\n        as (s & Hins & ((x', (xty, xck)) & Hxin &\n                       (Hotc & yck' & Hin' & Hinst) & Hsvx) & Hsvy); eauto.\n      simpl in *.\n      eapply NoDupMembers_det with (2:=Hin) in Hin'; eauto; subst yck'.\n      unfold idck in *. setoid_rewrite Forall_map in IH.\n      eapply Forall_forall in IH; eauto; simpl in IH.\n      apply wc_find_system with (1:=WCP) in Hfind as (WCi & WCo & WCv & WCtcs).\n      assert (In (x', xck) (idck (bl'.(s_in) ++ bl'.(s_out)))) as Hxin'\n        by (rewrite idck_app, in_app; right;\n            apply In_idck_exists; eauto).\n      apply wc_env_var with (1:=WCo) in Hxin'.\n      destruct s.\n      + split; intuition; eauto; try by_sem_det;\n          eapply IH, sem_clock_instant_transfer_out_instant in Hsvx; eauto; by_sem_det.\n      + split; intuition; eauto; try by_sem_det.\n        * eapply sem_clock_instant_transfer_out_instant; eauto; eapply IH; eauto.\n        * assert (exists c, sem_var_instant R' x' (present c)) as Hsvx' by eauto.\n          eapply IH, sem_clock_instant_transfer_out_instant in Hsvx'; eauto; by_sem_det.\n\n    - (* systems *)\n      rename H2 into Find'; rename H4 into Hins'; rename H5 into Houts'.\n      rewrite Find' in Find; inv Find.\n      apply Forall_forall; unfold idck.\n      intros (x, xck) Hxin.\n      apply In_idck_exists in Hxin as (xty & Hxin). assert (Hxin' := Hxin).\n      apply in_map with (f:=fst), system_output_defined_in_tcs in Hxin.\n      apply Is_defined_in_In in Hxin as (tc & Htcin & Hxtc).\n      eapply Forall_forall in IH; eauto.\n      pose proof Find' as Find; apply find_system_app in Find as (?&?&?); subst.\n      apply wc_find_system with (1:=WCP) in Find' as (WCi & WCo & WCv & WCtcs).\n      eapply Forall_forall in WCtcs; eauto.\n      assert (NoDupMembers (idck (s_in s ++ s_vars s ++ s_out s) ++ idck (s_lasts s)))\n        as Hnd.\n      { apply fst_NoDupMembers.\n        rewrite map_app, 2 map_fst_idck, 2 map_app, <-2 app_assoc.\n        apply s_nodup.\n      }\n      apply IH with (x:=x) (ck:=xck) in Hnd; eauto.\n      + simpl in *.\n        unfold sem_vars_instant in Hins, Houts, Hins', Houts'.\n        rewrite Forall2_map_1 in Hins', Houts'.\n        apply Forall2_app with (2:=Houts') in Hins'.\n        rewrite Forall2_map_1 in Hins, Houts.\n        assert (Houts2:=Houts).\n        apply Forall2_app with (1:=Hins) in Houts2.\n        apply Forall2_Forall2 with (1:=Houts) in Houts'.\n        apply Forall2_in_left with (2:=Hxin') in Houts' as (? & Hsin & Hvs & Hvs').\n        destruct x1.\n      (* * split; intuition; eauto; try by_sem_det. *)\n        * split; intuition; eauto; try by_sem_det.\n          -- eapply Hnd in Hvs.\n             eapply clock_vars_to_sem_clock_instant with (Hn' := R) in H2; eauto; try by_sem_det.\n             eapply in_app; eauto.\n          -- eapply clock_vars_to_sem_clock_instant; eauto.\n             ++ eapply in_app; eauto.\n             ++ apply Hnd; auto.\n        * split; intuition; eauto; try by_sem_det;\n          assert (exists c, sem_var_instant R x (present c)) as Hvs'' by eauto.\n          -- eapply clock_vars_to_sem_clock_instant; eauto.\n             ++ eapply in_app; eauto.\n             ++ apply Hnd; auto.\n          -- eapply Hnd in Hvs''.\n             eapply clock_vars_to_sem_clock_instant with (Hn' := R0) in Hvs''; eauto; try by_sem_det.\n             eapply in_app; eauto.\n      + apply wc_trconstr_program_app; auto.\n        apply wc_trconstr_program_cons; auto.\n        apply Ordered_systems_append in Ord; auto.\n      + rewrite in_app; left; apply In_idck_exists.\n        exists xty; rewrite 2 in_app; auto.\n  Qed.\n\n  Corollary sem_clocked_var_instant_tcs:\n    forall P base R S I S' inputs vars tcs,\n      Ordered_systems P ->\n      wc_program P ->\n      NoDupMembers (inputs ++ vars) ->\n      Forall (sem_trconstr P base R S I S') tcs ->\n      Forall (wc_trconstr P (inputs ++ vars)) tcs ->\n      Permutation.Permutation (defined tcs) (map fst vars) ->\n      forall x xck,\n        In (x, xck) vars ->\n        sem_clocked_var_instant base R x xck.\n  Proof.\n    intros * OP WCP Hndup Hsem Hwc Hdef x xck Hin.\n    assert (In x (defined tcs)) as Hxin\n        by (now rewrite Hdef; apply in_map with (f:=fst) in Hin).\n    apply Is_defined_in_defined, Is_defined_in_In in Hxin\n      as (tc & Hitc & Hdtc).\n    eapply Forall_forall in Hsem; eauto.\n    eapply Forall_forall in Hwc; eauto.\n    eapply sem_clocked_var_instant_tc; eauto.\n    rewrite in_app; auto.\n  Qed.\n\nEnd STCCLOCKINGSEMANTICS.\n\nModule StcClockingSemanticsFun\n       (Import Ids      : IDS)\n       (Import Op       : OPERATORS)\n       (Import OpAux    : OPERATORS_AUX           Op)\n       (Import CESyn    : CESYNTAX                Op)\n       (Import Syn      : STCSYNTAX           Ids Op       CESyn)\n       (Import Str      : INDEXEDSTREAMS          Op OpAux)\n       (Import Last     : STCISLAST           Ids Op       CESyn Syn)\n       (Import Var      : STCISVARIABLE       Ids Op       CESyn Syn)\n       (Import Def      : STCISDEFINED        Ids Op       CESyn Syn Var Last)\n       (Import Syst     : STCISSYSTEM         Ids Op       CESyn Syn)\n       (Import Ord      : STCORDERED          Ids Op       CESyn Syn Syst)\n       (Import CESem    : CESEMANTICS         Ids Op OpAux CESyn               Str)\n       (Import Sem      : STCSEMANTICS        Ids Op OpAux CESyn Syn Syst Ord Str CESem)\n       (Import CEClo    : CECLOCKING          Ids Op       CESyn)\n       (Import Clkg     : STCCLOCKING         Ids Op       CESyn Syn Last Var Def Syst Ord CEClo)\n       (Import CECloSem : CECLOCKINGSEMANTICS Ids Op OpAux CESyn Str CESem                  CEClo)\n<: STCCLOCKINGSEMANTICS Ids Op OpAux CESyn Syn Str Last Var Def Syst Ord CESem Sem CEClo Clkg CECloSem.\n  Include STCCLOCKINGSEMANTICS Ids Op OpAux CESyn Syn Str Last Var Def Syst Ord CESem Sem CEClo Clkg CECloSem.\nEnd StcClockingSemanticsFun.\n", "meta": {"author": "INRIA", "repo": "velus", "sha": "116a88bc71f3608ff43ed967895743e8b9a340e0", "save_path": "github-repos/coq/INRIA-velus", "path": "github-repos/coq/INRIA-velus/velus-116a88bc71f3608ff43ed967895743e8b9a340e0/src/Stc/StcClockingSemantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.296651450865509}}
{"text": "Require Import CT.Category.\nRequire Import CT.Morphism.\nRequire Import ProofIrrelevance.\n\nSection ArrowCategory.\n  Variable (C : Category).\n\n  (** * Morphisms in the arrow category.\n\n  These correspond to a commutative square as per\n  https://ncatlab.org/nlab/show/arrow+category#definition\n  *)\n  Definition morphism a b :=\n    { m : (mor (M_dom a) (M_dom b) * mor (M_cod a) (M_cod b)) |\n      comp (M_mor a) (snd m) = comp (fst m) (@M_mor C b) }.\n\n  (* This is annoying. *)\n  Lemma exist_injective :\n    forall A (f : A -> Prop) a b a' b',\n      a = b -> exist f a a' = exist f b b'.\n  Proof.\n    intros.\n    subst.\n    f_equal.\n    apply proof_irrelevance.\n  Qed.\n\n  (** * Arrow categories *)\n  Program Definition ArrowCategory : Category :=\n    {| ob := @Morphism C;\n       mor := morphism\n    |}.\n  Next Obligation.\n  Proof.\n    destruct a, b, c, X, X0.\n    unfold morphism.\n    simpl in *.\n    destruct x, x0.\n    simpl in *.\n    exists (comp m m1, comp m0 m2).\n    simpl.\n    rewrite <- assoc.\n    rewrite <- e0.\n    repeat rewrite assoc.\n    rewrite <- e.\n    reflexivity.\n  Defined.\n  Next Obligation.\n  Proof.\n    destruct a.\n    unfold morphism.\n    exists (id (M_dom), id (M_cod)).\n    rewrite id_right.\n    rewrite id_left.\n    reflexivity.\n  Defined.\n  Next Obligation.\n  Proof.\n    destruct a, b, c, d.\n    destruct f, g, h.\n    destruct x, x0, x1.\n    simpl in *.\n    apply exist_injective.\n    repeat rewrite assoc.\n    reflexivity.\n  Defined.\n  Next Obligation.\n  Proof.\n    rewrite ArrowCategory_obligation_3.\n    reflexivity.\n  Defined.\n  Next Obligation.\n  Proof.\n    destruct a, b, f.\n    simpl in *.\n    destruct x.\n    apply exist_injective.\n    assert (comp id m = m).\n    rewrite id_left.\n    reflexivity.\n    rewrite H.\n    assert (comp id m0 = m0).\n    rewrite id_left.\n    reflexivity.\n    rewrite H0.\n    reflexivity.\n  Qed.\n  Next Obligation.\n  Proof.\n    destruct a, b, f.\n    simpl in *.\n    destruct x.\n    apply exist_injective.\n    assert (comp m id = m).\n    rewrite id_right.\n    reflexivity.\n    rewrite H.\n    assert (comp m0 id = m0).\n    rewrite id_right.\n    reflexivity.\n    rewrite H0.\n    reflexivity.\n  Qed.\n\n  (* Isn't LTac pretty? :P *)\nEnd ArrowCategory.", "meta": {"author": "relrod", "repo": "ct", "sha": "abd8b0067e219ee4867f7136bdf1b35885224cb4", "save_path": "github-repos/coq/relrod-ct", "path": "github-repos/coq/relrod-ct/ct-abd8b0067e219ee4867f7136bdf1b35885224cb4/CT/Instance/Category/ArrowCategory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2966514508655089}}
{"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(*                        Behaviour_Struct_lemmas.v                         *)\n(****************************************************************************)\n \n\nRequire Export Arbitration.\nRequire Export Arbiter4_Proof.\nRequire Export Timing_Proof.\nRequire Export PriorityDecode_Proof.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\n\n(* Some tools for proofs *)\n\nLemma S_tail_Behaviour_TIMING :\n forall (s : Stream (bool * d_list bool 4)) (st : label_t),\n S_tail (Behaviour_TIMING s st) =\n Behaviour_TIMING (S_tail s) (Trans_Timing (S_head s) st).\nunfold Behaviour_TIMING in |- *.\nunfold Moore in |- *; simpl in |- *; auto.\nQed.\n\nLemma S_head_Behaviour_TIMING :\n forall (s : Stream (bool * d_list bool 4)) (st : label_t),\n S_head (Behaviour_TIMING s st) = Out_Timing st.\nauto.\nQed.\n\n\nLemma S_head_Behaviour_PDECODE :\n forall\n   (s : Stream (d_list bool 4 * (d_list bool 4 * d_list (d_list bool 2) 4)))\n   (sp : STATE_p),\n S_head (Behaviour_PRIORITY_DECODE s sp) = Out_PriorityDecode sp.\nauto.\nQed.\n\nLemma S_tail_Behaviour_PDECODE :\n forall\n   (s : Stream (d_list bool 4 * (d_list bool 4 * d_list (d_list bool 2) 4)))\n   (sp : STATE_p),\n S_tail (Behaviour_PRIORITY_DECODE s sp) =\n Behaviour_PRIORITY_DECODE (S_tail s) (Trans_PriorityDecode (S_head s) sp).\nauto.\nQed.\n\n\nLemma S_tail_States_TIMING :\n forall (s : Stream (bool * d_list bool 4)) (st : label_t),\n S_tail (States_TIMING s st) =\n States_TIMING (S_tail s) (Trans_Timing (S_head s) st).\nauto.\nQed.\n\n\nLemma S_head_States_TIMING :\n forall (s : Stream (bool * d_list bool 4)) (st : label_t),\n S_head (States_TIMING s st) = st.\nauto.\nQed.\n\n\nLemma S_tail_States_Structure_TIMING :\n forall (i : Stream (bool * d_list bool 4)) (x : d_list bool 2),\n S_tail (States_Structure_TIMING i x) =\n States_Structure_TIMING (S_tail i) (Timing_Aux (S_head i) x).\nauto.\nQed.\n\n\nLemma S_head_States_Structure_TIMING :\n forall (i : Stream (bool * d_list bool 4)) (x : d_list bool 2),\n S_head (States_Structure_TIMING i x) = x.\nauto.\nQed.\n\n\nLemma S_tail_States_FOUR_ARBITERS :\n forall (i : Stream (bool * (bool * d_list (d_list bool 4) 4)))\n   (s : STATE_a4),\n S_tail (States_FOUR_ARBITERS i s) =\n States_FOUR_ARBITERS (S_tail i) (Trans_Four_Arbiters (S_head i) s).\nauto.\nQed.\n\n\nLemma S_tail_Structure_States_FOUR_ARBITERS :\n forall (i : Stream (bool * (bool * d_list (d_list bool 4) 4)))\n   (olds : d_list bool 2 * bool * (d_list bool 2 * bool) *\n           (d_list bool 2 * bool * (d_list bool 2 * bool))),\n S_tail (Structure_States_FOUR_ARBITERS i olds) =\n Structure_States_FOUR_ARBITERS (S_tail i)\n   (Trans_Struct_four_arbiters (S_head i) olds).\nauto.\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/Behaviour_Struct_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.29658854060646633}}
{"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\n(** This module proves the Canonical Forms Lemmas, which allow us\n    to retrieve the shape of a value given its type. *)\n\nSet Implicit Arguments.\n\nRequire Import Coq.Program.Equality.\nRequire Import TLC.LibLN.\nRequire Import Definitions RecordAndInertTypes PreciseTyping TightTyping InvertibleTyping\n        GeneralToTight Subenvironments Weakening Narrowing Substitution.\n\n(** * Simple Implications of Typing *)\n\n(** If a variable can be typed in an environment,\n    then it is bound in that environment. *)\nLemma typing_implies_bound: forall G x T,\n  G ⊢ trm_var (avar_f x) : T ->\n  exists S, binds x S G.\nProof.\n  introv Ht. dependent induction Ht; eauto.\nQed.\n\n(** [d1 isin ds]             #<br>#\n    [label(d2) \\notin ds]     #<br>#\n    [―――――――――――――――――――――]  #<br>#\n    [label(d1) <> label(d2)]  *)\nLemma defs_has_hasnt_neq: forall ds d1 d2,\n  defs_has ds d1 ->\n  defs_hasnt ds (label_of_def d2) ->\n  label_of_def d1 <> label_of_def d2.\nProof.\n  introv Hhas Hhasnt.\n  unfold defs_has in Hhas.\n  unfold defs_hasnt in Hhasnt.\n  induction ds.\n  - simpl in Hhas. inversion Hhas.\n  - simpl in Hhasnt. simpl in Hhas. case_if; case_if.\n    + inversions Hhas. assumption.\n    + apply IHds; eauto.\nQed.\n\n(** [G ⊢ ds :: ... /\\ D /\\ ...]       #<br>#\n    [―――――――――――――――――――――――]       #<br>#\n    [exists d, ds = ... /\\ d /\\ ...]       #<br>#\n    [G ⊢ d: D]                      *)\nLemma record_has_ty_defs: forall G T ds D,\n  G /- ds :: T ->\n  record_has T D ->\n  exists d, defs_has ds d /\\ G /- d : D.\nProof.\n  introv Hdefs Hhas. induction Hdefs.\n  - inversion Hhas; subst. exists d. split.\n    + unfold defs_has. simpl. rewrite If_l; reflexivity.\n    + assumption.\n  - inversion Hhas; subst.\n    + destruct (IHHdefs H4) as [d' [H1 H2]].\n      exists d'. split.\n      * unfold defs_has. simpl. rewrite If_r. apply H1.\n        apply not_eq_sym. eapply defs_has_hasnt_neq; eauto.\n      * assumption.\n    + exists d. split.\n      * unfold defs_has. simpl. rewrite If_l; reflexivity.\n      * inversions* H4.\nQed.\n\n(** * Functions under Inert Contexts *)\n(** This lemma corresponds to Lemma 3.7 ([forall] to [G(x)]) in the paper.\n\n    [inert G]            #<br>#\n    [G ⊢ x: forall(T)U]       #<br>#\n    [――――――――――――――-]    #<br>#\n    [exists T', U',]          #<br>#\n    [G(x) = forall(T')U']     #<br>#\n    [G ⊢ T <: T']        #<br>#\n    [forall fresh y, G, y: T ⊢ U'^y <: U^y] *)\nLemma var_typ_all_to_binds: forall G x T U,\n    inert G ->\n    G ⊢ trm_var (avar_f x) : typ_all T U ->\n    (exists L T' U',\n        binds x (typ_all T' U') G /\\\n        G ⊢ T <: T' /\\\n        (forall y, y \\notin L -> G & y ~ T ⊢ (open_typ y U') <: (open_typ y U))).\nProof.\n  introv Hin Ht.\n  lets Htt: (general_to_tight_typing Hin Ht).\n  lets Hinv: (tight_to_invertible Hin Htt).\n  destruct (invertible_to_precise_typ_all (inert_ok Hin) Hinv) as [T' [U' [V' [L [Htp [Hs1 Hs2]]]]]].\n  exists L T' U'. repeat split.\n  - apply* inert_precise_all_inv.\n  - apply~ tight_to_general.\n  - assumption.\nQed.\n\n(** This lemma corresponds to Lemma 3.8 ([forall] to [lambda]) in the paper.\n\n    [inert G]                       #<br>#\n    [G ⊢ v: forall(T)U]                  #<br>#\n    [――――――――――――]                  #<br>#\n    [exists T', t,]                       #<br>#\n    [v = lambda(T')t]              #<br>#\n    [G ⊢ T <: T']                   #<br>#\n    [forall fresh y, G, y: T ⊢ t^y: U^y] *)\nLemma val_typ_all_to_lambda: forall G v T U,\n    inert G ->\n    G ⊢ trm_val v : typ_all T U ->\n    (exists L T' t,\n        v = val_lambda T' t /\\\n        G ⊢ T <: T' /\\\n        (forall y, y \\notin L -> G & y ~ T ⊢ (open_trm y t) : open_typ y U)).\nProof.\n  introv Hin Ht.\n  lets Htt: (general_to_tight_typing Hin Ht).\n  lets Hinv: (tight_to_invertible_v Hin Htt).\n  destruct (invertible_val_to_precise_lambda Hin Hinv) as [L [T' [U' [Htp [Hs1 Hs2]]]]].\n  inversions Htp.\n  exists (L0 \\u L \\u (dom G)) T' t. repeat split~.\n  intros. assert (HL: y \\notin L) by auto. assert (HL0: y \\notin L0) by auto.\n  specialize (Hs2 y HL).\n  specialize (H2 y HL0).\n  eapply ty_sub; eauto. eapply narrow_typing in H2; eauto.\nQed.\n\n(** * Objects under Inert Contexts *)\n(** This lemma corresponds to Lemma 3.9 ([mu] to [G(x)]) in the paper.\n\n    [inert G]                    #<br>#\n    [G ⊢ x: {a: T}]              #<br>#\n    [―――――――――――――――――――――――]    #<br>#\n    [exists S, T', G(x) = mu(S)]       #<br>#\n    [S^x = ... /\\ {a: T'} /\\ ...]  #<br>#\n    [G ⊢ T' <: T]                *)\nLemma var_typ_rcd_to_binds: forall G x a T,\n    inert G ->\n    G ⊢ trm_var (avar_f x) : typ_rcd (dec_trm a T) ->\n    (exists S T',\n        binds x (typ_bnd S) G /\\\n        record_has (open_typ x S) (dec_trm a T') /\\\n        G ⊢ T' <: T).\nProof.\n  introv Hin Ht.\n  destruct (typing_implies_bound Ht) as [S BiG].\n  lets Htt: (general_to_tight_typing Hin Ht).\n  lets Hinv: (tight_to_invertible Hin Htt).\n  destruct (invertible_to_precise_trm_dec Hinv) as [T' [U [Htp Hs]]].\n  destruct (pf_inert_rcd_U Hin Htp) as [U' Hr]. subst.\n  lets Hr': (precise_flow_record_has Hin Htp). apply pf_binds in Htp.\n  exists U' T'. split. assumption. split. assumption. apply* tight_to_general.\nQed.\n\nLemma var_typ_rcd_typ_to_binds: forall G x a T U,\n    inert G ->\n    G ⊢ trm_var (avar_f x) : typ_rcd (dec_typ a T U) ->\n    (exists S T' U',\n        binds x (typ_bnd S) G /\\\n        record_has (open_typ x S) (dec_typ a T' U') /\\\n        G ⊢ T <: T' /\\\n        G ⊢ U' <: U).\nProof.\n  introv Hin Ht.\n  destruct (typing_implies_bound Ht) as [S BiG].\n  lets Htt: (general_to_tight_typing Hin Ht).\n  lets Hinv: (tight_to_invertible Hin Htt).\n  destruct (invertible_to_precise_typ_dec Hinv) as [T' [U' [U0 [Htp Hs]]]].\n  destruct (pf_inert_rcd_U Hin Htp) as [U'1 Hr]. subst.\n  lets Hr': (precise_flow_record_has Hin Htp). apply pf_binds in Htp.\n  exists U'1 T' U'. split. assumption. split. assumption.\n  destruct Hs. split.\n  apply~ tight_to_general. assumption.\nQed.\n\n(** This lemma corresponds to Lemma 3.10 ([mu] to [nu]) in the paper.\n\n    [inert G]                  #<br>#\n    [G ⊢ v: mu(T)]             #<br>#\n    [G ⊢ x: T^x]               #<br>#\n    [T = ... /\\ {a: U} /\\ ...  ] #<br>#\n    [――――――――――――――――――――――――] #<br>#\n    [exists t, ds, v = nu(T)ds     ] #<br>#\n    [ds^x = ... /\\ {a = t} /\\ ...] #<br>#\n    [G ⊢ t: U] *)\nLemma val_mu_to_new: forall G v T U a x,\n    inert G ->\n    G ⊢ trm_val v: typ_bnd T ->\n    G ⊢ trm_var (avar_f x) : open_typ x T ->\n    record_has (open_typ x T) (dec_trm a U) ->\n    exists t ds,\n      v = val_new T ds /\\\n      defs_has (open_defs x ds) (def_trm a t) /\\\n      G ⊢ t: U.\nProof.\n  introv Hi Ht Hx Hr.\n  lets Htt: (general_to_tight_typing Hi Ht).\n  lets Hinv: (tight_to_invertible_v Hi Htt).\n  inversions Hinv. inversions H.\n  pick_fresh z. assert (z \\notin L) as Hz by auto.\n  specialize (H3 z Hz).\n  assert (G /- open_defs x ds :: open_typ x T) as Hds. {\n    apply* renaming_def; eauto.\n  }\n  destruct (record_has_ty_defs Hds Hr) as [d [Hh Hd]]. inversions Hd.\n  exists t ds. split*.\nQed.\n\n(** * Well-typedness *)\n\n(** If [s: G], the variables in the domain of [s] are distinct. *)\nLemma well_typed_to_ok_G: forall s G,\n    well_typed G s -> ok G.\nProof.\n  intros. destruct H as [? [? ?]]. auto.\nQed.\nHint Resolve well_typed_to_ok_G.\n\nLemma well_typed_to_ok_s: forall s G,\n    well_typed G s -> ok s.\nProof.\n  intros. destruct H as [? [? ?]]. auto.\nQed.\nHint Resolve well_typed_to_ok_s.\n\n(** [s: G]       #<br>#\n    [x ∉ dom(G)] #<br>#\n    [――――――――――] #<br>#\n    [x ∉ dom(s)] *)\nLemma well_typed_notin_dom: forall G s x,\n    well_typed G s ->\n    x # s ->\n    x # G.\nProof.\n  introv Hwt. destruct Hwt as [? [? [?Hdom ?]]].\n  unfold notin. rewrite Hdom.\n  auto.\nQed.\n\nLemma well_typed_empty:\n    well_typed empty empty.\nProof.\n  repeat split; auto.\n  - simpl_dom; auto.\n  - introv B. exfalso; apply* binds_empty_inv.\nQed.\nHint Resolve well_typed_empty.\n\nLemma well_typed_push: forall G s x T v,\n    well_typed G s ->\n    x # G ->\n    x # s ->\n    G ⊢ trm_val v : T ->\n    well_typed (G & x ~ T) (s & x ~ v).\nProof.\n  intros. unfold well_typed in *.\n  destruct_all.\n  repeat split; auto.\n  - simpl_dom. fequal. auto.\n  - intros x0 T0 v0 BxG. gen v0.\n    destruct (binds_push_inv BxG) as [[?Heqx ?HeqT] | [?Hneq ?HB]].\n    + subst x0 T0. introv Bxv. apply binds_push_eq_inv in Bxv.\n      subst v0. apply weaken_ty_trm; auto.\n    + intros.\n      assert (binds x0 T0 G) by eauto using binds_push_neq_inv.\n      assert (binds x0 v0 s) by eauto using binds_push_neq_inv.\n      apply weaken_ty_trm; eauto.\nQed.\nHint Resolve well_typed_push.\n\n(** [s: G]              #<br>#\n    [G(x) = T]          #<br>#\n    [―――――――――――――]     #<br>#\n    [exists v, s(x) = v]     #<br>#\n    [G ⊢ v: T]          *)\nLemma corresponding_types: forall G s x T,\n    well_typed G s ->\n    binds x T G ->\n    (exists v, binds x v s /\\\n          G ⊢ trm_val v : T).\nProof.\n  introv Hwt BiG. destruct Hwt as [?HokG [?HokS [?HdomEq ?]]].\n  pose proof (get_some_inv BiG) as HinDom.\n  symmetry in HdomEq.\n  pose proof (get_some (Logic.eq_ind_r _ HinDom HdomEq)) as [?v Bis].\n  exists v. split.\n  - apply Bis.\n  - eauto.\nQed.\n\n(** * Canonical Forms for Functions\n\n    [inert G]            #<br>#\n    [s: G]               #<br>#\n    [G ⊢ x: forall(T)U]       #<br>#\n    [――――――――――――――――――] #<br>#\n    [s(x) = lambda(T')t] #<br>#\n    [G ⊢ T <: T']        #<br>#\n    [G, x: T ⊢ t: U]          *)\nLemma canonical_forms_fun: forall G s x T U,\n  inert G ->\n  well_typed G s ->\n  G ⊢ trm_var (avar_f x) : typ_all T U ->\n  (exists L T' t, binds x (val_lambda T' t) s /\\ G ⊢ T <: T' /\\\n  (forall y, y \\notin L -> G & y ~ T ⊢ open_trm y t : open_typ y U)).\nProof.\n  introv Hin Hwt Hty.\n  destruct (var_typ_all_to_binds Hin Hty) as [L [S [T' [BiG [Hs1 Hs2]]]]].\n  destruct (corresponding_types Hwt BiG) as [v [Bis Ht]].\n  destruct (val_typ_all_to_lambda Hin Ht) as [L' [S' [t [Heq [Hs1' Hs2']]]]].\n  subst.\n  exists (L \\u L' \\u (dom G)) S' t. repeat split~.\n  - eapply subtyp_trans; eauto.\n  - intros.\n    assert (HL: y \\notin L) by auto.\n    assert (HL': y \\notin L') by auto.\n    specialize (Hs2 y HL).\n    specialize (Hs2' y HL').\n    apply narrow_typing with (G':=G & y ~ T) in Hs2'; auto.\n    + eapply ty_sub; eauto.\nQed.\n\n(** * Canonical Forms for Objects\n\n    [inert G]            #<br>#\n    [s: G]               #<br>#\n    [G ⊢ x: {a:T}]       #<br>#\n    [――――――――――――――――――] #<br>#\n    [exists S, ds, t,] #<br>#\n    [s(x) = nu(S)ds] #<br>#\n    [ds^x = ... /\\ {a = t} /\\ ...] #<br>#\n    [G ⊢ t: T] *)\nLemma canonical_forms_obj: forall G s x a T,\n  inert G ->\n  well_typed G s ->\n  G ⊢ trm_var (avar_f x) : typ_rcd (dec_trm a T) ->\n  (exists S ds t, binds x (val_new S ds) s /\\ defs_has (open_defs x ds) (def_trm a t) /\\ G ⊢ t : T).\nProof.\n  introv Hi Hwt Hty.\n  destruct (var_typ_rcd_to_binds Hi Hty) as [S [T' [Bi [Hr Hs]]]].\n  destruct (corresponding_types Hwt Bi) as [v [Bis Ht]].\n  apply ty_var in Bi. apply ty_rec_elim in Bi.\n  destruct (val_mu_to_new Hi Ht Bi Hr) as [t [ds [Heq [Hdefs Ht']]]].\n  subst. exists S ds t. repeat split~. eapply ty_sub; eauto.\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/CanonicalForms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.296588532798547}}
{"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(*                                                                          *)\n(*  Proof of the three gap theorem.                                         *)\n(*                                                                          *)\n(*  Micaela Mayero (INRIA-Rocquencourt)                                     *)\n(*  September 1998                                                          *)\n(*                                                                          *)\n(****************************************************************************)\n(****************************************************************************)\n(*                               preuve1.v                                  *)\n(****************************************************************************)\n\n(*********************************************************)\n(*           Intermediate proof 1                        *)\n(*                                                       *)\n(*********************************************************)\n\nRequire Export prop_fl.\n\nUnset Standard Proposition Elimination Names.\n\nSection particular.\nHypothesis alpha_irr : forall n p : Z, (alpha * IZR p)%R <> IZR n.\nHypothesis prop_alpha : (0 < alpha)%R /\\ (alpha < 1)%R.\nHypothesis prop_N : forall N : nat, N >= 2.\n\n(**********)\nDefinition M (N : nat) := first N + last N.\n\n(**********)\nLemma inter31a :\n forall N n : nat, 0 < n -> n < last (M N) -> after (M N) n = n + first (M N).\nintros; apply (sym_equal (x:=n + first (M N)) (y:=after (M N) n));\n apply (tech_after alpha_irr (M N) n (n + first (M N)) H);\n auto with arith real.\napply (lt_le_trans n (last (M N)) (M N) H0 (last_N01 (M N))).\nunfold M at 2 in |- *;\n rewrite (last_eq_M_N alpha_irr prop_alpha prop_N N (M N));\n auto with arith real;\n rewrite (first_eq_M_N alpha_irr prop_alpha prop_N N (M N));\n auto with arith real.\nrewrite (plus_comm (first (M N)) (last (M N)));\n apply (plus_lt_compat_r n (last (M N)) (first (M N)) H0).\nfold (frac_part_n_alpha (n + first (M N)) > frac_part_n_alpha n)%R in |- *;\n apply\n  (Rnot_le_lt (frac_part_n_alpha (n + first (M N))) (frac_part_n_alpha n));\n red in |- *; intro;\n generalize\n  (Rplus_le_compat_l (- frac_part_n_alpha (first (M N)))\n     (frac_part_n_alpha (n + first (M N))) (frac_part_n_alpha n) H1);\n rewrite\n  (Rplus_comm (- frac_part_n_alpha (first (M N)))\n     (frac_part_n_alpha (n + first (M N))));\n rewrite\n  (Rplus_comm (- frac_part_n_alpha (first (M N))) (frac_part_n_alpha n))\n  ;\n fold\n  (frac_part_n_alpha (n + first (M N)) - frac_part_n_alpha (first (M N)))%R\n  in |- *;\n fold (frac_part_n_alpha n - frac_part_n_alpha (first (M N)))%R in |- *;\n cut\n  (frac_part_n_alpha (n + first (M N)) >= frac_part_n_alpha (first (M N)))%R.\nintro; unfold frac_part_n_alpha at 1 2 in |- *;\n unfold frac_part_n_alpha in H2;\n rewrite <-\n  (Rminus_fp1 (INR (n + first (M N)) * alpha) (INR (first (M N)) * alpha) H2)\n  ; rewrite (plus_INR n (first (M N)));\n rewrite (Rmult_comm (INR n + INR (first (M N))) alpha);\n rewrite (Rmult_plus_distr_l alpha (INR n) (INR (first (M N))));\n rewrite (Rmult_comm alpha (INR (first (M N)))); unfold Rminus at 1 in |- *;\n rewrite\n  (Rplus_assoc (alpha * INR n) (INR (first (M N)) * alpha)\n     (- (INR (first (M N)) * alpha)));\n rewrite (Rplus_opp_r (INR (first (M N)) * alpha)).\n elim (Rplus_ne (alpha * INR n)); intros a b; rewrite a; clear a b;\n  rewrite (Rmult_comm alpha (INR n)); fold (frac_part_n_alpha n) in |- *;\n  intro; cut (0 < frac_part_n_alpha (first (M N)))%R.\nintro;\n generalize\n  (tech_Rgt_minus (frac_part_n_alpha n) (frac_part_n_alpha (first (M N))) H4);\n clear H4 H1 H2; intro; unfold Rgt in H1;\n generalize\n  (Rgt_not_le (frac_part_n_alpha n)\n     (frac_part_n_alpha n - frac_part_n_alpha (first (M N))) H1);\n auto with arith real.\nfold (frac_part_n_alpha (first (M N)) > 0)%R in |- *;\n apply (fp_first_R0 alpha_irr prop_N (M N)).\nunfold Rge in |- *; unfold Rgt in |- *;\n cut\n  ((frac_part_n_alpha (first (M N)) < frac_part_n_alpha (n + first (M N)))%R \\/\n   frac_part_n_alpha (first (M N)) = frac_part_n_alpha (n + first (M N))).\nintro; elim H2; intro.\nleft; auto with arith real.\nright; auto with arith real.\nfold\n (frac_part_n_alpha (first (M N)) <= frac_part_n_alpha (n + first (M N)))%R\n in |- *; apply (first_n (M N) (n + first (M N))); \n auto with arith real;\n generalize (plus_lt_compat_r n (last (M N)) (first (M N)) H0); \n intro; unfold M at 2 in |- *;\n rewrite (first_eq_M_N alpha_irr prop_alpha prop_N N (M N));\n auto with arith real;\n rewrite (last_eq_M_N alpha_irr prop_alpha prop_N N (M N));\n auto with arith real; rewrite (plus_comm (first (M N)) (last (M N)));\n assumption.\n(**)\nintro; elim H1; intros; elim H2; intros; elim H4; intros; elim H6; intros;\n clear H6 H4 H2 H1.\nelim (le_or_lt x n); intro.\ngeneralize\n (Ropp_lt_gt_contravar (frac_part_n_alpha n) (frac_part_n_alpha x) H7); \n intro;\n generalize\n  (Rplus_gt_compat_l (frac_part_n_alpha (n + first (M N)))\n     (- frac_part_n_alpha n) (- frac_part_n_alpha x) H2);\n fold (frac_part_n_alpha (n + first (M N)) - frac_part_n_alpha n)%R in |- *;\n fold (frac_part_n_alpha (n + first (M N)) - frac_part_n_alpha x)%R in |- *;\n fold (frac_part_n_alpha (n + first (M N)) > frac_part_n_alpha x)%R in H8;\n generalize\n  (Rgt_ge (frac_part_n_alpha (n + first (M N))) (frac_part_n_alpha x) H8);\n intro; unfold frac_part_n_alpha in H4; unfold frac_part_n_alpha in |- *;\n rewrite <- (Rminus_fp1 (INR (n + first (M N)) * alpha) (INR x * alpha) H4);\n fold (frac_part_n_alpha x > frac_part_n_alpha n)%R in H7;\n generalize\n  (Rgt_trans (frac_part_n_alpha (n + first (M N))) \n     (frac_part_n_alpha x) (frac_part_n_alpha n) H8 H7); \n intro;\n generalize\n  (Rgt_ge (frac_part_n_alpha (n + first (M N))) (frac_part_n_alpha n) H6);\n intro; unfold frac_part_n_alpha in H9;\n rewrite <- (Rminus_fp1 (INR (n + first (M N)) * alpha) (INR n * alpha) H9);\n rewrite (plus_INR n (first (M N)));\n rewrite (Rmult_comm (INR n + INR (first (M N))) alpha);\n rewrite (Rmult_plus_distr_l alpha (INR n) (INR (first (M N))));\n rewrite (Rmult_comm alpha (INR n)); unfold Rminus at 1 in |- *;\n rewrite (Rplus_comm (INR n * alpha) (alpha * INR (first (M N))));\n rewrite\n  (Rplus_assoc (alpha * INR (first (M N))) (INR n * alpha)\n     (- (INR n * alpha))); rewrite (Rplus_opp_r (INR n * alpha));\n elim (Rplus_ne (alpha * INR (first (M N)))); intros a b; \n rewrite a; clear a b; rewrite (Rmult_comm alpha (INR (first (M N))));\n fold (frac_part_n_alpha (first (M N))) in |- *; unfold Rminus in |- *;\n rewrite\n  (Rplus_assoc (INR (first (M N)) * alpha) (INR n * alpha)\n     (- (INR x * alpha))); rewrite (Rmult_comm (INR (first (M N))) alpha);\n rewrite (Rmult_comm (INR n) alpha);\n rewrite <- (Ropp_mult_distr_l_reverse (INR x) alpha);\n rewrite (Rmult_comm (- INR x) alpha);\n rewrite <- (Rmult_plus_distr_l alpha (INR n) (- INR x));\n rewrite <- (Rmult_plus_distr_l alpha (INR (first (M N))) (INR n + - INR x));\n fold (INR n - INR x)%R in |- *; rewrite <- (minus_INR n x H1);\n rewrite <- (plus_INR (first (M N)) (n - x));\n rewrite (Rmult_comm alpha (INR (first (M N) + (n - x))));\n fold (frac_part_n_alpha (first (M N) + (n - x))) in |- *; \n intro; clear H2 H4 H6 H9; cut (0 < first (M N) + (n - x)).\ncut (first (M N) + (n - x) < M N).\nintros;\n generalize\n  (first_n (M N) (first (M N) + (n - x)) (prop_N (M N)) H4 H2 prop_alpha);\n intro; clear H2 H4; unfold Rgt in H10;\n generalize\n  (Rgt_not_le (frac_part_n_alpha (first (M N)))\n     (frac_part_n_alpha (first (M N) + (n - x))) H10); \n auto with arith real.\nunfold M at 2 in |- *;\n rewrite (first_eq_M_N alpha_irr prop_alpha prop_N N (M N));\n auto with arith real.\napply (plus_lt_compat_l (n - x) (last N) (first (M N)));\n rewrite (last_eq_M_N alpha_irr prop_alpha prop_N N (M N));\n auto with arith real.\napply (lt_minus_p n (last (M N)) x H0).\napply (lt_O_plus (first (M N)) (n - x) (first_0 (M N) (prop_N (M N)))). \n(**)\ngeneralize\n (Rplus_lt_compat_l (- frac_part_n_alpha n) (frac_part_n_alpha x)\n    (frac_part_n_alpha (n + first (M N))) H8);\n rewrite (Rplus_comm (- frac_part_n_alpha n) (frac_part_n_alpha x));\n rewrite\n  (Rplus_comm (- frac_part_n_alpha n) (frac_part_n_alpha (n + first (M N))))\n  ; fold (frac_part_n_alpha x - frac_part_n_alpha n)%R in |- *;\n fold (frac_part_n_alpha (n + first (M N)) - frac_part_n_alpha n)%R in |- *;\n fold (frac_part_n_alpha x > frac_part_n_alpha n)%R in H7;\n generalize (Rgt_ge (frac_part_n_alpha x) (frac_part_n_alpha n) H7); \n intro;\n fold (frac_part_n_alpha (n + first (M N)) > frac_part_n_alpha x)%R in H8;\n generalize\n  (Rgt_trans (frac_part_n_alpha (n + first (M N))) \n     (frac_part_n_alpha x) (frac_part_n_alpha n) H8 H7); \n intro;\n generalize\n  (Rgt_ge (frac_part_n_alpha (n + first (M N))) (frac_part_n_alpha n) H4);\n intro; unfold frac_part_n_alpha in H2, H6; unfold frac_part_n_alpha in |- *;\n rewrite <- (Rminus_fp1 (INR x * alpha) (INR n * alpha) H2);\n rewrite <- (Rminus_fp1 (INR (n + first (M N)) * alpha) (INR n * alpha) H6);\n rewrite (plus_INR n (first (M N)));\n rewrite (Rmult_comm (INR n + INR (first (M N))) alpha);\n rewrite (Rmult_plus_distr_l alpha (INR n) (INR (first (M N))));\n rewrite (Rmult_comm alpha (INR n));\n rewrite (Rmult_comm alpha (INR (first (M N)))); unfold Rminus at 2 in |- *;\n rewrite (Rplus_comm (INR n * alpha) (INR (first (M N)) * alpha));\n rewrite\n  (Rplus_assoc (INR (first (M N)) * alpha) (INR n * alpha)\n     (- (INR n * alpha))); rewrite (Rplus_opp_r (INR n * alpha));\n elim (Rplus_ne (INR (first (M N)) * alpha)); intros a b; \n rewrite a; clear a b; fold (frac_part_n_alpha (first (M N))) in |- *;\n clear H2 H4 H6; unfold Rminus in |- *; rewrite (Rmult_comm (INR x) alpha);\n rewrite <- (Ropp_mult_distr_l_reverse (INR n) alpha);\n rewrite (Rmult_comm (- INR n) alpha);\n rewrite <- (Rmult_plus_distr_l alpha (INR x) (- INR n));\n fold (INR x - INR n)%R in |- *; rewrite (Rmult_comm alpha (INR x - INR n));\n generalize (lt_le_weak n x H1); intro; rewrite <- (minus_INR x n H2);\n fold (frac_part_n_alpha (x - n)) in |- *; intro; cut (0 < x - n).\nintro; cut (x - n < M N).\nintro; generalize (first_n (M N) (x - n) (prop_N (M N)) H6 H9 prop_alpha);\n intro; clear H9 H6;\n generalize\n  (Rgt_not_le (frac_part_n_alpha (first (M N))) (frac_part_n_alpha (x - n))\n     H4); auto with arith real.\napply (lt_minus_p x (M N) n H5).\napply (lt_minus2 n x H1).\nQed.\n\n(**********)\nLemma inter31b :\n forall N n : nat,\n last (M N) <= n -> n < M N -> after (M N) n = n - last (M N).\nintros; elim (le_lt_or_eq (last (M N)) n H); intro; clear H.\napply (sym_equal (x:=n - last (M N)) (y:=after (M N) n));\n apply (tech_after alpha_irr (M N) n (n - last (M N))); \n auto with arith real.\napply (lt_trans 0 (last (M N)) n (last_0 (M N) (prop_N (M N))) H1).\napply (lt_minus_p n (M N) (last (M N)) H0).\ncut\n (frac_part_n_alpha n <\n  frac_part_n_alpha n - frac_part_n_alpha (last (M N)) + 1)%R. \nintro; unfold frac_part_n_alpha in H; generalize H; clear H;\n rewrite <- (Rminus_fp2 (INR n * alpha) (INR (last (M N)) * alpha)).\nfold (frac_part_n_alpha n) in |- *; rewrite (Rmult_comm (INR n) alpha);\n unfold Rminus in |- *;\n rewrite <- (Ropp_mult_distr_l_reverse (INR (last (M N))) alpha);\n rewrite (Rmult_comm (- INR (last (M N))) alpha);\n rewrite <- (Rmult_plus_distr_l alpha (INR n) (- INR (last (M N))));\n fold (INR n - INR (last (M N)))%R in |- *;\n rewrite <- (minus_INR n (last (M N)) (lt_le_weak (last (M N)) n H1));\n rewrite (Rmult_comm alpha (INR (n - last (M N))));\n fold (frac_part_n_alpha (n - last (M N))) in |- *; \n trivial.\nfold (frac_part_n_alpha n) in |- *;\n fold (frac_part_n_alpha (last (M N))) in |- *;\n generalize\n  (last_n (M N) n (prop_N (M N))\n     (lt_trans 0 (last (M N)) n (last_0 (M N) (prop_N (M N))) H1) H0\n     prop_alpha); intro; unfold Rle in H; elim H; intro; \n auto with arith real.\ngeneralize\n (contra_tech_fp_alp_irr alpha_irr prop_alpha (last (M N)) n\n    (lt_not_eq (last (M N)) n H1)); intro; elimtype False;\n auto with arith real.\nunfold Rminus in |- *;\n rewrite\n  (Rplus_assoc (frac_part_n_alpha n) (- frac_part_n_alpha (last (M N))) 1)\n  ; rewrite (Rplus_comm (- frac_part_n_alpha (last (M N))) 1);\n fold (1 - frac_part_n_alpha (last (M N)))%R in |- *;\n elim (Rplus_ne (frac_part_n_alpha n)); intros a b;\n pattern (frac_part_n_alpha n) at 1 in |- *; rewrite <- a; \n clear a b;\n apply\n  (Rplus_lt_compat_l (frac_part_n_alpha n) 0\n     (1 - frac_part_n_alpha (last (M N))));\n fold (1 - frac_part_n_alpha (last (M N)) > 0)%R in |- *;\n apply (Rgt_minus 1 (frac_part_n_alpha (last (M N)))); \n unfold Rgt in |- *; unfold frac_part_n_alpha in |- *;\n elim (base_fp (INR (last (M N)) * alpha)); intros; \n assumption.\n(**)\nintro; elim H; intros; elim H2; intros; elim H4; intros; elim H6; intros;\n clear H H2 H4 H6.\nelim (le_or_lt n x); intro.\ngeneralize\n (Rplus_lt_compat_l (- frac_part_n_alpha (n - last (M N)))\n    (frac_part_n_alpha n) (frac_part_n_alpha x) H7); \n intro;\n generalize\n  (Rplus_lt_compat_l 1\n     (- frac_part_n_alpha (n - last (M N)) + frac_part_n_alpha n)\n     (- frac_part_n_alpha (n - last (M N)) + frac_part_n_alpha x) H2);\n clear H2;\n rewrite\n  (Rplus_comm 1 (- frac_part_n_alpha (n - last (M N)) + frac_part_n_alpha n))\n  ;\n rewrite\n  (Rplus_comm 1 (- frac_part_n_alpha (n - last (M N)) + frac_part_n_alpha x))\n  ;\n rewrite\n  (Rplus_comm (- frac_part_n_alpha (n - last (M N))) (frac_part_n_alpha n))\n  ;\n rewrite\n  (Rplus_comm (- frac_part_n_alpha (n - last (M N))) (frac_part_n_alpha x))\n  ; fold (frac_part_n_alpha n - frac_part_n_alpha (n - last (M N)))%R in |- *;\n fold (frac_part_n_alpha x - frac_part_n_alpha (n - last (M N)))%R in |- *;\n unfold frac_part_n_alpha in |- *;\n rewrite <- (Rminus_fp2 (INR n * alpha) (INR (n - last (M N)) * alpha)). \nrewrite <- (Rminus_fp2 (INR x * alpha) (INR (n - last (M N)) * alpha)). \nrewrite (minus_INR n (last (M N)) (lt_le_weak (last (M N)) n H1));\n unfold Rminus in |- *;\n rewrite (Rmult_comm (INR n + - INR (last (M N))) alpha);\n rewrite (Rmult_plus_distr_l alpha (INR n) (- INR (last (M N))));\n rewrite (Ropp_plus_distr (alpha * INR n) (alpha * - INR (last (M N))));\n rewrite <-\n  (Rplus_assoc (INR n * alpha) (- (alpha * INR n))\n     (- (alpha * - INR (last (M N))))); rewrite (Rmult_comm (INR n) alpha);\n rewrite (Rplus_opp_r (alpha * INR n));\n elim (Rplus_ne (- (alpha * - INR (last (M N))))); \n intros a b; rewrite b; clear a b;\n rewrite (Rmult_comm alpha (- INR (last (M N))));\n rewrite <- (Ropp_mult_distr_l_reverse (- INR (last (M N))) alpha);\n rewrite (Ropp_involutive (INR (last (M N))));\n fold (frac_part_n_alpha (last (M N))) in |- *;\n rewrite <-\n  (Rplus_assoc (INR x * alpha) (- (alpha * INR n)) (INR (last (M N)) * alpha))\n  ; rewrite (Rmult_comm alpha (INR n));\n rewrite <- (Ropp_mult_distr_l_reverse (INR n) alpha);\n rewrite (Rmult_comm (- INR n) alpha); rewrite (Rmult_comm (INR x) alpha);\n rewrite <- (Rmult_plus_distr_l alpha (INR x) (- INR n));\n fold (INR x - INR n)%R in |- *; rewrite <- (minus_INR x n H);\n rewrite (Rmult_comm (INR (last (M N))) alpha);\n rewrite <- (Rmult_plus_distr_l alpha (INR (x - n)) (INR (last (M N))));\n rewrite <- (plus_INR (x - n) (last (M N)));\n rewrite (Rmult_comm alpha (INR (x - n + last (M N))));\n fold (frac_part_n_alpha (x - n + last (M N))) in |- *; \n intro; cut (0 < x - n + last (M N)). \nintro; cut (x - n + last (M N) < M N).\nintro;\n generalize\n  (last_n (M N) (x - n + last (M N)) (prop_N (M N)) H4 H6 prop_alpha); \n intro; clear H4 H6;\n generalize\n  (Rgt_not_le (frac_part_n_alpha (x - n + last (M N)))\n     (frac_part_n_alpha (last (M N))) H2); intro; elimtype False;\n auto with arith real.\napply (tech_inter31b (last (M N)) n x (M N) H1 H H5).\nrewrite plus_comm;\n apply (lt_O_plus (last (M N)) (x - n) (last_0 (M N) (prop_N (M N)))). \nfold (frac_part_n_alpha x) in |- *;\n fold (frac_part_n_alpha (n - last (M N))) in |- *; \n assumption.\nfold (frac_part_n_alpha n) in |- *;\n fold (frac_part_n_alpha (n - last (M N))) in |- *;\n apply\n  (Rlt_trans (frac_part_n_alpha n) (frac_part_n_alpha x)\n     (frac_part_n_alpha (n - last (M N))) H7 H8).\n(**)\ngeneralize\n (Ropp_lt_gt_contravar (frac_part_n_alpha x)\n    (frac_part_n_alpha (n - last (M N))) H8); unfold Rgt in |- *; \n intro;\n generalize\n  (Rplus_lt_compat_l (frac_part_n_alpha n)\n     (- frac_part_n_alpha (n - last (M N))) (- frac_part_n_alpha x) H2);\n clear H2;\n fold (frac_part_n_alpha n - frac_part_n_alpha (n - last (M N)))%R in |- *;\n fold (frac_part_n_alpha n - frac_part_n_alpha x)%R in |- *; \n intro;\n generalize\n  (Rplus_lt_compat_l 1\n     (frac_part_n_alpha n - frac_part_n_alpha (n - last (M N)))\n     (frac_part_n_alpha n - frac_part_n_alpha x) H2); \n clear H2;\n rewrite\n  (Rplus_comm 1 (frac_part_n_alpha n - frac_part_n_alpha (n - last (M N))))\n  ; rewrite (Rplus_comm 1 (frac_part_n_alpha n - frac_part_n_alpha x));\n unfold frac_part_n_alpha in |- *;\n rewrite <- (Rminus_fp2 (INR n * alpha) (INR (n - last (M N)) * alpha)).\nrewrite <- (Rminus_fp2 (INR n * alpha) (INR x * alpha)). \nrewrite (Rmult_comm (INR n) alpha); unfold Rminus at 2 in |- *;\n rewrite <- (Ropp_mult_distr_l_reverse (INR x) alpha);\n rewrite (Rmult_comm (- INR x) alpha);\n rewrite <- (Rmult_plus_distr_l alpha (INR n) (- INR x));\n fold (INR n - INR x)%R in |- *;\n rewrite <- (minus_INR n x (lt_le_weak x n H));\n rewrite (Rmult_comm alpha (INR (n - x)));\n fold (frac_part_n_alpha (n - x)) in |- *;\n rewrite (minus_INR n (last (M N)) (lt_le_weak (last (M N)) n H1));\n unfold Rminus in |- *;\n rewrite (Rmult_comm (INR n + - INR (last (M N))) alpha);\n rewrite (Rmult_plus_distr_l alpha (INR n) (- INR (last (M N))));\n rewrite (Ropp_plus_distr (alpha * INR n) (alpha * - INR (last (M N))));\n rewrite <-\n  (Rplus_assoc (alpha * INR n) (- (alpha * INR n))\n     (- (alpha * - INR (last (M N))))); rewrite (Rplus_opp_r (alpha * INR n));\n elim (Rplus_ne (- (alpha * - INR (last (M N))))); \n intros a b; rewrite b; clear a b;\n rewrite (Rmult_comm alpha (- INR (last (M N))));\n rewrite <- (Ropp_mult_distr_l_reverse (- INR (last (M N))) alpha);\n rewrite (Ropp_involutive (INR (last (M N))));\n fold (frac_part_n_alpha (last (M N))) in |- *; intro; \n cut (0 < n - x).\nintro; cut (n - x < M N).\nintro; generalize (last_n (M N) (n - x) (prop_N (M N)) H4 H6 prop_alpha);\n intro;\n generalize\n  (Rgt_not_le (frac_part_n_alpha (n - x)) (frac_part_n_alpha (last (M N))) H2);\n intro; elimtype False; auto with arith real.\napply (lt_minus_p n (M N) x H0).\napply (lt_minus2 x n H).\nfold (frac_part_n_alpha n) in |- *; fold (frac_part_n_alpha x) in |- *;\n assumption.\nfold (frac_part_n_alpha n) in |- *;\n fold (frac_part_n_alpha (n - last (M N))) in |- *;\n apply\n  (Rlt_trans (frac_part_n_alpha n) (frac_part_n_alpha x)\n     (frac_part_n_alpha (n - last (M N))) H7 H8).\nrewrite <- H1; rewrite <- (minus_n_n (last (M N)));\n apply (after_last prop_alpha prop_N (M N)).\nQed.\n\n(**********)\nLemma tech1 :\n forall N n : nat,\n N - first N <= n ->\n n < last N ->\n (frac_part_n_alpha n < frac_part_n_alpha (n + first N - last N))%R.\nintros; cut (frac_part_n_alpha n < frac_part_n_alpha (n + first N))%R.\nintro;\n cut\n  (frac_part_n_alpha (n + first N) < frac_part_n_alpha (n + first N - last N))%R.\nintro;\n apply\n  (Rlt_trans (frac_part_n_alpha n) (frac_part_n_alpha (n + first N))\n     (frac_part_n_alpha (n + first N - last N)) H1 H2).\ncut (0 < n + first N).\ncut (n + first N < M N).\nintros;\n apply (tech_after_lt (M N) (n + first N) (n + first N - last N) H3 H2).\napply (lt_minus_not (last N) (n + first N)).\ngeneralize (le_minus_plus N (first N) n H); intro;\n apply (lt_le_trans (last N) N (n + first N) (last_N N (prop_N N)) H4).\nrewrite (last_eq_M_N alpha_irr prop_alpha prop_N N (M N));\n auto with arith real.\ngeneralize H2; clear H2;\n rewrite (first_eq_M_N alpha_irr prop_alpha prop_N N (M N));\n auto with arith real.\nintro; cut (last (M N) <= n + first (M N)).\nintro; apply (inter31b N (n + first (M N)) H4 H2).\nrewrite <- (last_eq_M_N alpha_irr prop_alpha prop_N N (M N));\n auto with arith real.\nrewrite <- (first_eq_M_N alpha_irr prop_alpha prop_N N (M N));\n auto with arith real.\ngeneralize (le_minus_plus N (first N) n H); intro;\n apply (le_trans (last N) N (n + first N) (last_N01 N) H4).\nunfold M in |- *; rewrite (plus_comm (first N) (last N));\n apply (plus_lt_compat_r n (last N) (first N) H0).\ngeneralize (le_minus_plus N (first N) n H); intro; cut (0 < N).\nintro; apply (lt_le_trans 0 N (n + first N) H3 H2).\napply (arith_2_0 N (prop_N N)).\n(**)\ncut (0 < n).\ncut (n < M N).\nintros; apply (tech_after_lt (M N) n (n + first N) H2 H1).\ngeneralize (lt_O_plus n (first N) H2); intro; apply Compare.not_eq_sym;\n red in |- *; intro; apply (lt_not_eq 0 (n + first N) H3 H4).\nrewrite (first_eq_M_N alpha_irr prop_alpha prop_N N (M N));\n auto with arith real.\ngeneralize H0; rewrite (last_eq_M_N alpha_irr prop_alpha prop_N N (M N));\n auto with arith real; clear H0; intro; apply (inter31a N n H2 H0).\ngeneralize (lt_trans n (last N) N H0 (last_N N (prop_N N))); intro;\n unfold M in |- *; cut (N <= first N + last N).\nintro; apply (lt_le_trans n N (first N + last N) H1 H2).\napply (le_N_M alpha_irr prop_alpha prop_N N (M N)); auto with arith real.\napply\n (lt_le_trans 0 (N - first N) n\n    (lt_minus2 (first N) N (first_N N (prop_N N))) H).\nQed.\n\n(**********)\nLemma tech_suc_N :\n forall N n : nat,\n 0 < n ->\n n < N ->\n forall k : nat,\n 0 < k ->\n k < N ->\n (frac_part_n_alpha n < frac_part_n_alpha k)%R ->\n frac_part_n_alpha k <> frac_part_n_alpha (after N n) ->\n (frac_part_n_alpha (after N n) < frac_part_n_alpha k)%R.\nunfold after in |- *; intros; generalize H4; clear H4;\n case (exist_after_M (frac_part_n_alpha n) (P1 n) (P2 n) N); \n intro.\nelim s; intros x y H4; clear s; elim y; intros; clear y; unfold Rgt in H6;\n cut (0 <= k).\nelim H6; intros; elim H8; intros; generalize (H11 k H9 H2 H3);\n unfold Rge in |- *; unfold Rgt in |- *; intro; elim H12;\n auto with arith real.\nintro; elimtype False; auto with arith real.\napply (lt_le_weak 0 k H1).\nunfold frac_part_n_alpha in |- *; simpl in |- *; rewrite Rmult_0_l;\n rewrite fp_R0; elim (base_fp (INR k * alpha)); intros; \n unfold Rge in H4; elim H4; auto with arith real.\nintro; elimtype False; auto with arith real.\nQed.\n\n(**********)\nLemma tech_suc_M :\n forall N n : nat,\n N - first N <= n ->\n n < last N ->\n (exists k : nat,\n    0 < k /\\\n    k < N /\\\n    (frac_part_n_alpha n < frac_part_n_alpha k)%R /\\\n    (frac_part_n_alpha k < frac_part_n_alpha (n + first N - last N))%R) ->\n False.\nintros; elim H1; intros; clear H1.\nelim H2; intros; elim H3; intros; clear H3; clear H2; elim H5; intros;\n clear H5.\ncut (0 < n).\nintro; cut (n < M N).\nintros; cut (x < M N).\nintro;\n elim (Rtotal_order (frac_part_n_alpha x) (frac_part_n_alpha (n + first N)));\n intro.\ncut (n + first N = after (M N) n).\nintro; rewrite H9 in H8;\n cut (frac_part_n_alpha x <> frac_part_n_alpha (after (M N) n)).\nintro; generalize (tech_suc_N (M N) n H5 H6 x H1 H7 H2 H10).\nintro;\n generalize\n  (Rlt_asym (frac_part_n_alpha x) (frac_part_n_alpha (after (M N) n)) H8).\nintro; auto with arith real.\napply\n (Rlt_dichotomy_converse (frac_part_n_alpha x)\n    (frac_part_n_alpha (after (M N) n))).\nleft; auto with arith real.\napply sym_equal.\nrewrite (first_eq_M_N alpha_irr prop_alpha prop_N N (M N)).\napply (inter31a N n H5).\nrewrite <- (last_eq_M_N alpha_irr prop_alpha prop_N N (M N)).\nassumption.\nauto with arith real.\nauto with arith real.\n(**)\nelim H8; intro; clear H8.\ncut (x <> n + first N).\nintro;\n generalize (contra_tech_fp_alp_irr alpha_irr prop_alpha x (n + first N) H8);\n auto with arith real.\ncut (x < n + first N).\nintro; red in |- *; intro; apply (lt_not_eq x (n + first N) H8); assumption.\ngeneralize (le_minus_plus N (first N) n H); intro;\n apply (lt_le_trans x N (n + first N) H4 H8).\n(**)\ncut (0 < n + first (M N)).\nintro; cut (n + first (M N) < M N).\nintro;\n cut\n  (frac_part_n_alpha x <> frac_part_n_alpha (after (M N) (n + first (M N)))).\nintro; unfold Rgt in H9;\n rewrite\n  (first_eq_M_N alpha_irr prop_alpha prop_N N (M N)\n     (refl_equal (first N + last N))) in H9;\n generalize (tech_suc_N (M N) (n + first (M N)) H8 H10 x H1 H7 H9 H11); \n intro; cut (last (M N) <= n + first (M N)).\nintro; rewrite (inter31b N (n + first (M N)) H13 H10) in H12.\nrewrite\n (first_eq_M_N alpha_irr prop_alpha prop_N N (M N)\n    (refl_equal (first N + last N))) in H3;\n rewrite\n  (last_eq_M_N alpha_irr prop_alpha prop_N N (M N)\n     (refl_equal (first N + last N))) in H3;\n generalize\n  (Rlt_asym (frac_part_n_alpha (n + first (M N) - last (M N)))\n     (frac_part_n_alpha x) H12); intro; auto with arith real.\ngeneralize (le_minus_plus N (first N) n H); intro.\ngeneralize (last_N01 N); intro.\nrewrite <-\n (first_eq_M_N alpha_irr prop_alpha prop_N N (M N)\n    (refl_equal (first N + last N)));\n rewrite <-\n  (last_eq_M_N alpha_irr prop_alpha prop_N N (M N)\n     (refl_equal (first N + last N)));\n apply (le_trans (last N) N (n + first N) H14 H13).\ncut (last (M N) <= n + first (M N)).\nintro; rewrite (inter31b N (n + first (M N)) H11 H10);\n rewrite <-\n  (first_eq_M_N alpha_irr prop_alpha prop_N N (M N)\n     (refl_equal (first N + last N)));\n rewrite <-\n  (last_eq_M_N alpha_irr prop_alpha prop_N N (M N)\n     (refl_equal (first N + last N)));\n apply\n  (Rlt_dichotomy_converse (frac_part_n_alpha x)\n     (frac_part_n_alpha (n + first N - last N))).\nleft; assumption.\ngeneralize (le_minus_plus N (first N) n H); intro.\ngeneralize (last_N01 N); intro;\n rewrite <-\n  (first_eq_M_N alpha_irr prop_alpha prop_N N (M N)\n     (refl_equal (first N + last N)));\n rewrite <-\n  (last_eq_M_N alpha_irr prop_alpha prop_N N (M N)\n     (refl_equal (first N + last N)));\n apply (le_trans (last N) N (n + first N) H12 H11).\nrewrite <-\n (first_eq_M_N alpha_irr prop_alpha prop_N N (M N)\n    (refl_equal (first N + last N))); unfold M in |- *;\n rewrite (plus_comm (first N) (last N));\n apply (plus_lt_compat_r n (last N) (first N) H0).\napply (lt_O_plus n (first (M N)) H5).\ncut (N <= M N).\nintro; apply (lt_le_trans x N (M N) H4 H7).\napply\n (le_N_M alpha_irr prop_alpha prop_N N (M N) (refl_equal (first N + last N))).\ncut (last N < N).\nintro; cut (N <= M N).\nintro; generalize (lt_trans n (last N) N H0 H6).\nintro; apply (lt_le_trans n N (M N) H8 H7).\napply\n (le_N_M alpha_irr prop_alpha prop_N N (M N) (refl_equal (first N + last N))).\napply (last_N N (prop_N N)).\ncut (0 < N - first N).\nintro; apply (lt_le_trans 0 (N - first N) n H5 H).\napply (lt_minus2 (first N) N (first_N N (prop_N N))).\nQed.\n\n(**********)\nLemma tech_suc_M1 :\n forall N n : nat,\n N - first N <= n ->\n n < last N ->\n forall k : nat,\n ~\n (0 < k /\\\n  k < N /\\\n  (frac_part_n_alpha n < frac_part_n_alpha k)%R /\\\n  (frac_part_n_alpha k < frac_part_n_alpha (n + first N - last N))%R).\nintros; generalize (tech_suc_M N n H H0); intro; red in |- *; intro; apply H1;\n split with k; auto with arith real.\nQed.\n\n(**********)\nLemma eq_after_M_N1 :\n forall N n : nat, 0 < n -> n < N - first N -> after (M N) n = after N n.\nintros; cut (n < last (M N)).\nintro; generalize (inter31a N n H H1);\n rewrite <-\n  (first_eq_M_N alpha_irr prop_alpha prop_N N (M N) (refl_equal (M N)))\n  ; intro; apply (tech_fp_alp_irr alpha_irr (after (M N) n) (after N n));\n apply\n  (Rge_antisym (frac_part_n_alpha (after (M N) n))\n     (frac_part_n_alpha (after N n))).\napply\n (Rnot_lt_ge (frac_part_n_alpha (after (M N) n))\n    (frac_part_n_alpha (after N n))); red in |- *; \n intro; cut (0 < after (M N) n).\nintro; cut (after (M N) n < N).\nintro; cut (frac_part_n_alpha n < frac_part_n_alpha (after (M N) n))%R.\nintro;\n generalize\n  (tech_suc_N N n H (contra_lt_minus_p n N (first N) H0) \n     (after (M N) n) H4 H5 H6\n     (Rlt_dichotomy_converse (frac_part_n_alpha (after (M N) n))\n        (frac_part_n_alpha (after N n))\n        (or_introl\n           (frac_part_n_alpha (after (M N) n) > frac_part_n_alpha (after N n))%R\n           H3))); intro;\n generalize\n  (Rlt_asym (frac_part_n_alpha (after (M N) n))\n     (frac_part_n_alpha (after N n)) H3); intro; elimtype False;\n auto with arith real.\napply\n (tech_after_lt (M N) n (after (M N) n) H\n    (lt_le_trans n N (M N) (contra_lt_minus_p n N (first N) H0)\n       (le_N_M alpha_irr prop_alpha prop_N N (M N) (refl_equal (M N)))));\n auto with arith real.\nrewrite H2; red in |- *; intro; apply (lt_O_plus_eq n (first N) H);\n auto with arith real.\nrewrite H2; apply (lt_n_minus_plus n N (first N) H0). \nrewrite H2; apply (lt_O_plus n (first N) H).\n(**)\napply\n (Rnot_lt_ge (frac_part_n_alpha (after N n))\n    (frac_part_n_alpha (after (M N) n))); red in |- *; \n intro; apply (prop_after (M N) n (after (M N) n)); \n auto with arith real.\nsplit with (after N n); split.\nunfold after in |- *;\n case (exist_after_M (frac_part_n_alpha n) (P1 n) (P2 n) N).\nintro; elim s; intros x y; elim y; intros; assumption.\nintro; generalize (a (last N) (le_O_n (last N)) (last_N N (prop_N N))); intro;\n elim H4; intros; clear a H4;\n generalize\n  (last_n N n (prop_N N) H (contra_lt_minus_p n N (first N) H0) prop_alpha);\n intro; cut (frac_part_n_alpha n = frac_part_n_alpha (last N)).\nintro; generalize (tech_fp_alp_irr alpha_irr n (last N) H7);\n rewrite (last_eq_M_N alpha_irr prop_alpha prop_N N (M N));\n auto with arith real.\nintro; generalize (lt_not_eq n (last (M N)) H1); intro; elimtype False;\n auto with arith real.\nelim (Rle_le_eq (frac_part_n_alpha n) (frac_part_n_alpha (last N))); intros;\n clear H8; apply H7; auto with arith real.\nsplit.\ncut (after N n < N).\nintro;\n apply\n  (lt_le_trans (after N n) N (M N) H4\n     (le_N_M alpha_irr prop_alpha prop_N N (M N) (refl_equal (M N)))).\nunfold after in |- *;\n case (exist_after_M (frac_part_n_alpha n) (P1 n) (P2 n) N).\nintro; elim s; intros x y; elim y; intros; elim H5; intros; assumption.\nintro; apply (arith_2_0 N (prop_N N)).\nsplit; auto with arith real.\napply (tech_after_lt N n (after N n) H (contra_lt_minus_p n N (first N) H0));\n auto with arith real.\nred in |- *; unfold after in |- *;\n case (exist_after_M (frac_part_n_alpha n) (P1 n) (P2 n) N).\nintro; elim s; intros x y H4; elim y; intros; generalize (lt_not_eq 0 x H5);\n intro; auto with arith real.\nintros; generalize (a (last N) (le_O_n (last N)) (last_N N (prop_N N)));\n intro; elim H5; intros; clear a H5;\n generalize\n  (last_n N n (prop_N N) H (contra_lt_minus_p n N (first N) H0) prop_alpha);\n intro; cut (frac_part_n_alpha n = frac_part_n_alpha (last N)).\nintro; generalize (tech_fp_alp_irr alpha_irr n (last N) H8);\n rewrite (last_eq_M_N alpha_irr prop_alpha prop_N N (M N));\n auto with arith real.\nintro; generalize (lt_not_eq n (last (M N)) H1); intro; elimtype False;\n auto with arith real.\nelim (Rle_le_eq (frac_part_n_alpha n) (frac_part_n_alpha (last N))); intros;\n clear H9; apply H8; auto with arith real.\ncut (N - first N <= last (M N)).\nintro; apply (lt_le_trans n (N - first N) (last (M N)) H0 H1).\ngeneralize (le_N_M alpha_irr prop_alpha prop_N N (M N) (refl_equal (M N)));\n unfold M at 1 in |- *;\n rewrite <-\n  (last_eq_M_N alpha_irr prop_alpha prop_N N (M N) (refl_equal (M N)))\n  ; intro; apply (le_plus_min N (first N) (last N) H1).\nQed.\n\n(**********)\nLemma eq_after_M_N2 :\n forall N n : nat, last N <= n -> n < N -> after (M N) n = after N n.\nintros; generalize (le_lt_or_eq (last N) n H); intro; elim H1; intro;\n clear H1.\nrewrite (last_eq_M_N alpha_irr prop_alpha prop_N N (M N) (refl_equal (M N)))\n  in H;\n generalize\n  (inter31b N n H\n     (lt_le_trans n N (M N) H0\n        (le_N_M alpha_irr prop_alpha prop_N N (M N) (refl_equal (M N)))));\n rewrite <-\n  (last_eq_M_N alpha_irr prop_alpha prop_N N (M N) (refl_equal (M N)))\n  ; intro; apply (tech_fp_alp_irr alpha_irr (after (M N) n) (after N n));\n apply\n  (Rge_antisym (frac_part_n_alpha (after (M N) n))\n     (frac_part_n_alpha (after N n))).\napply\n (Rnot_lt_ge (frac_part_n_alpha (after (M N) n))\n    (frac_part_n_alpha (after N n))); red in |- *; \n intro; cut (0 < after (M N) n).\nintro; cut (after (M N) n < N).\nintro; cut (frac_part_n_alpha n < frac_part_n_alpha (after (M N) n))%R.\nintro;\n generalize\n  (tech_suc_N N n (lt_trans 0 (last N) n (last_0 N (prop_N N)) H2) H0\n     (after (M N) n) H4 H5 H6\n     (Rlt_dichotomy_converse (frac_part_n_alpha (after (M N) n))\n        (frac_part_n_alpha (after N n))\n        (or_introl\n           (frac_part_n_alpha (after (M N) n) > frac_part_n_alpha (after N n))%R\n           H3))); intro;\n generalize\n  (Rlt_asym (frac_part_n_alpha (after (M N) n))\n     (frac_part_n_alpha (after N n)) H3); intro; elimtype False;\n auto with arith real.\napply\n (tech_after_lt (M N) n (after (M N) n)\n    (lt_trans 0 (last N) n (last_0 N (prop_N N)) H2)\n    (lt_le_trans n N (M N) H0\n       (le_N_M alpha_irr prop_alpha prop_N N (M N) (refl_equal (M N)))));\n auto with arith real.\nrewrite H1; red in |- *; intro; apply (lt_minus_not (last N) n H2);\n auto with arith real.\nrewrite H1; apply (lt_minus_p n N (last N) H0). \nrewrite H1; apply (lt_minus2 (last N) n H2).\n(**)\napply\n (Rnot_lt_ge (frac_part_n_alpha (after N n))\n    (frac_part_n_alpha (after (M N) n))); red in |- *; \n intro; apply (prop_after (M N) n (after (M N) n)); \n auto with arith real.\nsplit with (after N n); split.\nunfold after in |- *;\n case (exist_after_M (frac_part_n_alpha n) (P1 n) (P2 n) N).\nintro; elim s; intros x y; elim y; intros; assumption.\nintro; generalize (a (last N) (le_O_n (last N)) (last_N N (prop_N N))); intro;\n elim H4; intros; clear a H4;\n generalize\n  (last_n N n (prop_N N) (lt_trans 0 (last N) n (last_0 N (prop_N N)) H2) H0\n     prop_alpha); intro;\n cut (frac_part_n_alpha n = frac_part_n_alpha (last N)).\nintro; generalize (tech_fp_alp_irr alpha_irr n (last N) H7).\nintro; generalize (lt_not_eq (last N) n H2); intro; elimtype False;\n auto with arith real.\nelim (Rle_le_eq (frac_part_n_alpha n) (frac_part_n_alpha (last N))); intros;\n clear H8; apply H7; auto with arith real.\nsplit.\ncut (after N n < N).\nintro;\n apply\n  (lt_le_trans (after N n) N (M N) H4\n     (le_N_M alpha_irr prop_alpha prop_N N (M N) (refl_equal (M N)))).\nunfold after in |- *;\n case (exist_after_M (frac_part_n_alpha n) (P1 n) (P2 n) N).\nintro; elim s; intros x y; elim y; intros; elim H5; intros; assumption.\nintro; apply (arith_2_0 N (prop_N N)).\nsplit; auto with arith real.\napply\n (tech_after_lt N n (after N n)\n    (lt_trans 0 (last N) n (last_0 N (prop_N N)) H2) H0);\n auto with arith real.\nred in |- *; unfold after in |- *;\n case (exist_after_M (frac_part_n_alpha n) (P1 n) (P2 n) N).\nintro; elim s; intros x y H4; elim y; intros; generalize (lt_not_eq 0 x H5);\n intro; auto with arith real.\nintros; generalize (a (last N) (le_O_n (last N)) (last_N N (prop_N N)));\n intro; elim H5; intros; clear a H5;\n generalize\n  (last_n N n (prop_N N) (lt_trans 0 (last N) n (last_0 N (prop_N N)) H2) H0\n     prop_alpha); intro;\n cut (frac_part_n_alpha n = frac_part_n_alpha (last N)).\nintro; generalize (tech_fp_alp_irr alpha_irr n (last N) H8); intro;\n generalize (lt_not_eq (last N) n H2); intro; auto with arith real.\nelim (Rle_le_eq (frac_part_n_alpha n) (frac_part_n_alpha (last N))); intros;\n clear H9; apply H8; auto with arith real.\nrewrite <- H2; rewrite (after_last prop_alpha prop_N N);\n rewrite\n  (last_eq_M_N alpha_irr prop_alpha prop_N N (M N)\n     (refl_equal (first N + last N))); auto with arith real;\n rewrite (after_last prop_alpha prop_N (M N)); trivial.\nQed.\n\nEnd particular.\n", "meta": {"author": "coq-contribs", "repo": "three-gap", "sha": "b176a7b3165aecd171926271a8d90888f16dc297", "save_path": "github-repos/coq/coq-contribs-three-gap", "path": "github-repos/coq/coq-contribs-three-gap/three-gap-b176a7b3165aecd171926271a8d90888f16dc297/preuve1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.29658853279854697}}
{"text": "From Undecidability.L.Tactics Require Import LTactics.\nFrom Undecidability.L Require Import UpToC.\nFrom Undecidability.L Require Import Functions.EqBool.\n\nFrom Undecidability.L.Datatypes Require Export List.List_enc LBool LOptions LNat.\n\nSet Default Proof Using \"Type\".\n\nSection Fix_X.\n  Variable (X:Type).\n  Context {intX : encodable X}.\n\n  Fixpoint inb eqb (x:X) (A: list X) :=\n    match A with\n      nil => false\n    | a::A' => orb (eqb a x) (inb eqb x A')\n    end.\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  Lemma inb_spec: forall x A, Bool.reflect (In x A) (inb X_eqb x A).\n  Proof using X_eqb_spec.\n    intros x A. induction A.\n    -constructor. tauto.\n    -simpl. destruct (X_eqb_spec a x).\n    +constructor. tauto.\n    +inv IHA. destruct (X_eqb_spec a x).\n      *constructor. tauto.\n      *constructor. tauto.\n      *constructor. tauto.\n  Qed.\n\n  Global Instance term_inb: computableTime' inb (fun eq eqT => (5,fun x _ => (1,fun l _ =>\n                                        (fold_right (fun x' res => callTime2 eqT x' x\n                                                                + res + 17) 4 l ,tt)))).\n  Proof.\n    extract.\n    solverec. \n  Defined. (*because other extract*)\n\n  Global Instance term_inb_notime: computable inb.\n  Proof.\n    extract.\n  Defined. (*because other extract*)\n\n\n\nEnd Fix_X.\n\nSection list_eqb.\n\n  Variable X : Type.\n  Variable eqb : X -> X -> bool.\n  Variable spec : forall x y, reflect (x = y) (eqb x y).\n\n  Fixpoint list_eqb A B :=\n    match A,B with\n    | nil,nil => true\n    | a::A',b::B' => eqb a b && list_eqb A' B'\n    | _,_ => false\n    end.\n\n  Lemma list_eqb_spec A B : reflect (A = B) (list_eqb A B).\n  Proof using spec.\n    revert B; induction A; intros; destruct B; cbn in *; try now econstructor.\n    destruct (spec a x), (IHA B); cbn; econstructor; congruence.\n  Qed.\n\nEnd list_eqb.\n\nSection int.\n\n  Context {X : Type}.\n  Context {HX : encodable X}.\n\n  Fixpoint list_eqbTime (eqbT: timeComplexity (X -> X -> bool)) (A B:list X) :=\n    match A,B with\n      a::A,b::B => callTime2 eqbT a b + 22 + list_eqbTime eqbT A B\n    | _,_ => 9\n    end.\n\n  Global Instance term_list_eqb : computableTime' (list_eqb (X:=X))\n                                                  (fun _ eqbT => (1,(fun A _ => (5,fun B _ => (list_eqbTime eqbT A B,tt))))).\n  Proof.\n    extract.\n    solverec.                                                                                             \n  Qed.\n\n  Definition list_eqbTime_leq (eqbT: timeComplexity (X -> X -> bool)) (A B:list X) k:\n    (forall a b, callTime2 eqbT a b <= k)\n    -> list_eqbTime eqbT A B <= length A * (k+22) + 9.\n  Proof.\n    intros H'. induction A in B|-*.\n    -cbn. lia.\n    -destruct B.\n    {cbn. intuition. }\n    cbn - [callTime2]. setoid_rewrite IHA.\n    rewrite H'. ring_simplify. intuition.\n  Qed.\n\n\n  Lemma list_eqbTime_bound_r (eqbT : timeComplexity (X -> X -> bool)) (A B : list X) f:\n    (forall (x y:X), callTime2 eqbT x y <= f y) ->\n    list_eqbTime eqbT A B <= sumn (map f B) + 9 + length B * 22.\n  Proof.\n    intros H.\n    induction A in B|-*;unfold list_eqbTime;fold list_eqbTime. now Lia.lia.\n    destruct B.\n    -cbn. Lia.lia.\n    -rewrite H,IHA. cbn [length map sumn]. Lia.lia.\n  Qed.\n\n  Global Instance eqbList f `{eqbClass (X:=X) f}:\n    eqbClass (list_eqb f).\n  Proof.\n    intros ? ?. eapply list_eqb_spec. all:eauto using eqb_spec.\n  Qed.\n  Import EqBool.\n  Global Instance eqbComp_List `{eqbCompT X (R:=HX)}:\n    eqbCompT (list X).\n  Proof.\n    evar (c:nat). exists c. unfold list_eqb.\n    extract. unfold eqb,eqbTime. cbn - [\"+\"].\n    [c]:exact (c__eqbComp X + 6).\n    all:unfold c. set (c__eqbComp X). \n    solverec. all: set (f:=enc (X:=list X)); unfold enc in f;subst f;cbn [size encodable_list_enc].\n    all:try nia. \n  Qed.\nEnd int.\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/Datatypes/List/List_eqb.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.2965885249906277}}
{"text": "Require Import NonSpec. \nRequire Import Spec.\nRequire Import Coq.Sets.Ensembles. \nRequire Import erasure. \nRequire Import AST. \nRequire Import SfLib. \n\nTheorem listAlign : forall (T:Type) l (x y :T) l' (e:T),\n                      x::y::l = l' ++ [e] ->\n                      exists l'', (y::l) = l'' ++ [e]. \nProof.\n  induction l; intros. \n  {destruct l'. inversion H. exists nil. inversion H.\n   destruct l'. inversion H2. auto. inversion H2. destruct l'; inversion H4. }\n  {destruct l'. \n   {inversion H. }\n   {inversion H. exists l'. assumption. }\n  }\nQed. \n\nTheorem appNil : forall (T:Type) (x:T), [x] = nil ++ [x]. \nProof.\n  intros. auto. Qed. \n\nTheorem unspecBasicAction1 : forall a M M' s2 tid tid' T,\n                               basicAction a M' tid' ->\n                               unspecPoolAux(tAdd T (tid, [a], s2, M)) = \n                               unspecPoolAux(tAdd T (tid', nil, s2, M')). \nProof.\n  intros. apply Extensionality_Ensembles. unfold Same_set. unfold Included. split; intros. \n  {inversion H0; subst. inversion H1; subst. inversion H4; subst; clear H4. inversion H3; subst. \n   {econstructor. econstructor. econstructor. eassumption. reflexivity. assumption. }\n   {destruct tid'. destruct p. econstructor. econstructor. eapply Union_intror. econstructor. \n    reflexivity. inversion H4; subst; clear H4. eapply unspecLastAct. eassumption. eassumption. } \n  }\n  {inversion H0; subst. inversion H1; subst. inversion H4; subst; clear H4. inversion H3; subst. \n   {econstructor. econstructor. econstructor. eassumption. reflexivity. assumption. }\n   {destruct tid. destruct p. econstructor. econstructor. apply Union_intror. econstructor. \n    reflexivity. inversion H4; subst; clear H4. eapply unspecLastAct; eauto. }\n  }\nQed. \n\n\nTheorem unspecBasicAction2 : forall a b s1' s2 M M' tid tid' T,\n                              basicAction a M' tid' ->\n                              unspecPoolAux(tAdd T (tid, a::b::s1', s2, M)) = \n                              unspecPoolAux(tAdd T (tid', b::s1', s2, M')). \nProof.\n  intros. apply Extensionality_Ensembles. unfold Same_set. unfold Included. split; intros. \n  {inversion H0; subst. inversion H1; subst. inversion H4; subst; clear H4. inversion H3; subst. \n   {econstructor. econstructor. econstructor. eassumption. reflexivity. assumption. }\n   {destruct tid'. destruct p. econstructor. econstructor. apply Union_intror. econstructor. \n    reflexivity. inversion H4; subst; clear H4. eapply unspecTwoActs. eassumption. }\n  }\n  {inversion H0; subst. inversion H1; subst. inversion H4; subst; clear H4. inversion H3; subst. \n   {econstructor. econstructor. econstructor. eassumption. reflexivity. assumption. }\n   {destruct tid. destruct p. econstructor. econstructor. apply Union_intror. econstructor. \n    reflexivity. inversion H4; subst; clear H4. eapply unspecTwoActs. eassumption. }\n  }\nQed. \n\nTheorem rollbackWellFormed : forall tid As H T H' T', \n                               wellFormed H T -> rollback tid As H T H' T' ->\n                               wellFormed H' T'. \nProof.\n  intros. induction H1; subst. \n  {assumption. }\n  {apply IHrollback. inversion H0; subst. inversion H2; subst. destruct s1'. \n   {eapply wf with (T' := (unspecPoolAux (tAdd T (tid', [rAct x tid'' M'], s2, M)))). \n    erewrite unspecBasicAction1. econstructor. constructor. eapply unspecHeapRBRead; eauto. \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/erasureWellFormed.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.29658852499062766}}
{"text": "Require Import Coq.PArith.BinPos.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Crypto.Reflection.Syntax.\nRequire Import Crypto.Specific.FancyMachine256.Core.\n\n\nDefinition compiled_syntax\n:= fun (ops : fancy_machine.instructions (2 * 128)) (var : base_type -> Type) =>\n(λ (x x0 : var TZ) (x1 x2 : var TW),\n slet x3 := @Op base_type (interp_base_type ops) op var (@Tbase base_type TZ) (@Tbase base_type TW) OPldi\n              (@Var base_type (interp_base_type ops) op var TZ x) in\n slet x4 := @Op base_type (interp_base_type ops) op var (@Tbase base_type TZ) (@Tbase base_type TW) OPldi\n              (@Var base_type (interp_base_type ops) op var TZ x0) in\n slet x5 := @Op base_type (interp_base_type ops) op var (@Tbase base_type TZ) (@Tbase base_type TW) OPldi\n              (@Const base_type (interp_base_type ops) op var (@Tbase base_type TZ) 0) in\n slet x6 := @Op base_type (interp_base_type ops) op var (@Tbase base_type TW * @Tbase base_type TW * @Tbase base_type TZ)%ctype\n              (@Tbase base_type TW) OPshrd\n              (@Var base_type (interp_base_type ops) op var TW x2, @Var base_type (interp_base_type ops) op var TW x1,\n              @Const base_type (interp_base_type ops) op var (@Tbase base_type TZ) 250) in\n slet x7 := @Op base_type (interp_base_type ops) op var (@Tbase base_type TW * @Tbase base_type TW)%ctype\n              (@Tbase base_type TW) OPmulhwhh\n              (@Var base_type (interp_base_type ops) op var TW x6, @Var base_type (interp_base_type ops) op var TW x4) in\n slet x8 := @Op base_type (interp_base_type ops) op var (@Tbase base_type TW * @Tbase base_type TW)%ctype\n              (@Tbase base_type TW) OPmulhwhl\n              (@Var base_type (interp_base_type ops) op var TW x6, @Var base_type (interp_base_type ops) op var TW x4) in\n slet x9 := @Op base_type (interp_base_type ops) op var (@Tbase base_type TW * @Tbase base_type TW)%ctype\n              (@Tbase base_type TW) OPmulhwll\n              (@Var base_type (interp_base_type ops) op var TW x6, @Var base_type (interp_base_type ops) op var TW x4) in\n slet x10 := @Op base_type (interp_base_type ops) op var (@Tbase base_type TW * @Tbase base_type TW * @Tbase base_type Tbool)%ctype\n               (@Tbase base_type Tbool * @Tbase base_type TW)%ctype OPadc\n               (@Var base_type (interp_base_type ops) op var TW x9,\n               @Op base_type (interp_base_type ops) op var (@Tbase base_type TW * @Tbase base_type TZ)%ctype\n                 (@Tbase base_type TW) OPshl\n                 (@Var base_type (interp_base_type ops) op var TW x8,\n                 @Const base_type (interp_base_type ops) op var (@Tbase base_type TZ) 128),\n               @Const base_type (interp_base_type ops) op var (@Tbase base_type Tbool) false) in\n slet x11 := @Op base_type (interp_base_type ops) op var (@Tbase base_type TW * @Tbase base_type TW * @Tbase base_type Tbool)%ctype\n               (@Tbase base_type Tbool * @Tbase base_type TW)%ctype OPadc\n               (@Var base_type (interp_base_type ops) op var TW x7,\n               @Op base_type (interp_base_type ops) op var (@Tbase base_type TW * @Tbase base_type TZ)%ctype\n                 (@Tbase base_type TW) OPshr\n                 (@Var base_type (interp_base_type ops) op var TW x8,\n                 @Const base_type (interp_base_type ops) op var (@Tbase base_type TZ) 128),\n               @Var base_type (interp_base_type ops) op var Tbool (let (H, _) := x10 in H)) in\n slet x12 := @Op base_type (interp_base_type ops) op var (@Tbase base_type TW * @Tbase base_type TW)%ctype\n               (@Tbase base_type TW) OPmulhwhl\n               (@Var base_type (interp_base_type ops) op var TW x4, @Var base_type (interp_base_type ops) op var TW x6) in\n slet x13 := @Op base_type (interp_base_type ops) op var (@Tbase base_type TW * @Tbase base_type TW * @Tbase base_type Tbool)%ctype\n               (@Tbase base_type Tbool * @Tbase base_type TW)%ctype OPadc\n               (@Var base_type (interp_base_type ops) op var TW (let (_, H) := x10 in H),\n               @Op base_type (interp_base_type ops) op var (@Tbase base_type TW * @Tbase base_type TZ)%ctype\n                 (@Tbase base_type TW) OPshl\n                 (@Var base_type (interp_base_type ops) op var TW x12,\n                 @Const base_type (interp_base_type ops) op var (@Tbase base_type TZ) 128),\n               @Const base_type (interp_base_type ops) op var (@Tbase base_type Tbool) false) in\n slet x14 := @Op base_type (interp_base_type ops) op var (@Tbase base_type TW * @Tbase base_type TW * @Tbase base_type Tbool)%ctype\n               (@Tbase base_type Tbool * @Tbase base_type TW)%ctype OPadc\n               (@Var base_type (interp_base_type ops) op var TW (let (_, H) := x11 in H),\n               @Op base_type (interp_base_type ops) op var (@Tbase base_type TW * @Tbase base_type TZ)%ctype\n                 (@Tbase base_type TW) OPshr\n                 (@Var base_type (interp_base_type ops) op var TW x12,\n                 @Const base_type (interp_base_type ops) op var (@Tbase base_type TZ) 128),\n               @Var base_type (interp_base_type ops) op var Tbool (let (H, _) := x13 in H)) in\n slet x15 := @Op base_type (interp_base_type ops) op var (@Tbase base_type TW * @Tbase base_type TW)%ctype\n               (@Tbase base_type TW) OPmulhwll\n               (@Var base_type (interp_base_type ops) op var TW (let (_, H) := x14 in H),\n               @Var base_type (interp_base_type ops) op var TW x3) in\n slet x16 := @Op base_type (interp_base_type ops) op var (@Tbase base_type TW * @Tbase base_type TW)%ctype\n               (@Tbase base_type TW) OPmulhwhl\n               (@Var base_type (interp_base_type ops) op var TW (let (_, H) := x14 in H),\n               @Var base_type (interp_base_type ops) op var TW x3) in\n slet x17 := @Op base_type (interp_base_type ops) op var (@Tbase base_type TW * @Tbase base_type TW * @Tbase base_type Tbool)%ctype\n               (@Tbase base_type Tbool * @Tbase base_type TW)%ctype OPadc\n               (@Var base_type (interp_base_type ops) op var TW x15,\n               @Op base_type (interp_base_type ops) op var (@Tbase base_type TW * @Tbase base_type TZ)%ctype\n                 (@Tbase base_type TW) OPshl\n                 (@Var base_type (interp_base_type ops) op var TW x16,\n                 @Const base_type (interp_base_type ops) op var (@Tbase base_type TZ) 128),\n               @Const base_type (interp_base_type ops) op var (@Tbase base_type Tbool) false) in\n slet x18 := @Op base_type (interp_base_type ops) op var (@Tbase base_type TW * @Tbase base_type TW)%ctype\n               (@Tbase base_type TW) OPmulhwhl\n               (@Var base_type (interp_base_type ops) op var TW x3,\n               @Var base_type (interp_base_type ops) op var TW (let (_, H) := x14 in H)) in\n slet x19 := @Op base_type (interp_base_type ops) op var (@Tbase base_type TW * @Tbase base_type TW * @Tbase base_type Tbool)%ctype\n               (@Tbase base_type Tbool * @Tbase base_type TW)%ctype OPadc\n               (@Var base_type (interp_base_type ops) op var TW (let (_, H) := x17 in H),\n               @Op base_type (interp_base_type ops) op var (@Tbase base_type TW * @Tbase base_type TZ)%ctype\n                 (@Tbase base_type TW) OPshl\n                 (@Var base_type (interp_base_type ops) op var TW x18,\n                 @Const base_type (interp_base_type ops) op var (@Tbase base_type TZ) 128),\n               @Const base_type (interp_base_type ops) op var (@Tbase base_type Tbool) false) in\n slet x20 := @Op base_type (interp_base_type ops) op var (@Tbase base_type TW * @Tbase base_type TW * @Tbase base_type Tbool)%ctype\n               (@Tbase base_type Tbool * @Tbase base_type TW)%ctype OPsubc\n               (@Var base_type (interp_base_type ops) op var TW x1,\n               @Var base_type (interp_base_type ops) op var TW (let (_, H) := x19 in H),\n               @Const base_type (interp_base_type ops) op var (@Tbase base_type Tbool) false) in\n slet x21 := @Op base_type (interp_base_type ops) op var (@Tbase base_type TW * @Tbase base_type TW * @Tbase base_type TW)%ctype\n               (@Tbase base_type TW) OPaddm\n               (@Var base_type (interp_base_type ops) op var TW (let (_, H) := x20 in H),\n               @Var base_type (interp_base_type ops) op var TW x5, @Var base_type (interp_base_type ops) op var TW x3) in\n slet x22 := @Op base_type (interp_base_type ops) op var (@Tbase base_type TW * @Tbase base_type TW * @Tbase base_type TW)%ctype\n               (@Tbase base_type TW) OPaddm\n               (@Var base_type (interp_base_type ops) op var TW x21, @Var base_type (interp_base_type ops) op var TW x5,\n               @Var base_type (interp_base_type ops) op var TW x3) in\n @Var base_type (interp_base_type ops) op var TW x22)%expr.\n\nDefinition v ops :=\n  Eval cbv [compiled_syntax] in (DefaultAssembleSyntax (compiled_syntax ops)).\n\nLocal Open Scope positive_scope.\n\nRequire Import Crypto.Reflection.Named.Syntax.\n\nTime Eval lazy in v. (* Finished transaction in 0.033 secs (0.032u,0.004s) (successful) *)\nTime Eval compute in v. (* Finished transaction in 0.03 secs (0.032u,0.s) (successful) *)\nTime Eval native_compute in v. (* Finished transaction in 0.081 secs (0.012u,0.016s) (successful) *)\nFail Timeout 5 Eval vm_compute in v. (* The command has indeed failed with message:\n         Timeout! *)\nGoal fancy_machine.instructions (2 * 128) -> True.\n  intros ops.\n  pose (v ops) as v'.\n  unfold v in *; rename v' into v.\n  let T := type of v in set (T' := T) in *; vm_compute in T'; subst T'.\n  unfold DefaultAssembleSyntax, AssembleSyntax, AssembleSyntax', DeadCodeElimination.CompileAndEliminateDeadCode in (value of v).\n  set (k := List.map _ _) in (value of v); vm_compute in k; subst k.\n  set (v' := Compile.compile _ _) in (value of v); vm_compute in v'; subst v'.\n  cbv beta iota in v.\n  set (k := EstablishLiveness.insert_dead_names _ _ _) in (value of v).\n  unfold EstablishLiveness.insert_dead_names in (value of k).\n  revert v; set (n := DefaultRegisters _) in (value of k); intro v.\n  vm_compute in n; subst n.\n  revert v; set (l := EstablishLiveness.compute_liveness _ _ _) in (value of k); intro v.\n  unfold EstablishLiveness.compute_liveness in (value of l).\n  Notation hidden := (FMapPositive.PositiveMap.Node _ _ _).\n  pose I as c.\n  (* HERE: change 15 to other values to see exponential behavior of vm_compute *)\n  do 15 (let m := fresh \"c\" in\n         unfold EstablishLiveness.compute_livenessf in (value of l); fold (@EstablishLiveness.compute_livenessf base_type (interp_base_type _) op positive _) in (value of l); unfold EstablishLiveness.compute_livenessf_step at 1 in (value of l);\n         revert k v; set (m := extend _ _ _) in (value of l); intros k v;\n         vm_compute in m;\n         subst c; rename m into c;\n         simpl @List.app in (value of l));\n    time vm_compute in v.\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_vm_compute/src/Specific/FancyMachine256/Barrett.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.29652870994493924}}
{"text": "From mathcomp Require Import all_ssreflect.\nFrom Usuba Require Import usuba_AST usuba_sem equiv_rel.\n\nGoal\n    forall arch prog type_ctxt ctxt opt_ctxt' var typ dir,\n        find_val type_ctxt var = Some typ ->\n        well_typed_ctxt type_ctxt ctxt ->\n        convert_type typ nil = Some (dir, 1::nil) ->\n        eval_deq arch prog type_ctxt ctxt\n            (Eqn (Index (Var var) (Const_e 0) :: (Index (Var var) (Const_e 0)) :: nil) (Tuple (ECons (Const 1 None)\n                            (ECons (Const 2 None) Enil)))\n                true) = opt_ctxt'\n        -> (ctxt' <- opt_ctxt'; find_val ctxt' var) = Some (CoIR dir (2::nil) (Some (1::nil))).\nProof.\n    simpl.\n    unfold bind; unfold bind_aux_list.\n    unfold bind_aux.\n    simpl.\n    move=> _ _ type_ctxt ctxt opt_ctxt var typ dir HEqType well_typed.\n    rewrite HEqType; move=> Convert; rewrite Convert; simpl.\n    case_eq (find_val ctxt var).\n    {\n        move=> c HEq.\n        pose (p := well_typed_ctxt_imp_find_val _ _ _ _ well_typed HEq).\n        destruct p as [typ' [find_typ valoType]].\n        rewrite find_typ in HEqType; inversion HEqType as [HEq'].\n        destruct HEq'; clear HEqType.\n        destruct c as [|d [|hd tl] form]; simpl.\n        {\n            rewrite String.eqb_refl; simpl.\n            move=> <-; simpl.\n            rewrite String.eqb_refl; reflexivity.\n        }\n        {\n            exfalso.\n            apply (val_of_type_len _ _ _ dir _ [:: 1]) in valoType; trivial.\n            simpl in valoType.\n            unfold muln, muln_rec in valoType.\n            rewrite PeanoNat.Nat.mul_1_l in valoType; discriminate.\n        }\n        destruct tl; simpl.\n        {\n            rewrite String.eqb_refl; simpl.\n            move=> <-; simpl.\n            rewrite String.eqb_refl; reflexivity.\n        }\n        {\n            exfalso.\n            apply (val_of_type_len _ _ _ dir _ [:: 1]) in valoType; trivial.\n            simpl in valoType.\n            unfold muln, muln_rec in valoType.\n            rewrite PeanoNat.Nat.mul_1_l in valoType; discriminate.\n        }\n    }\n    {\n        move=> _; simpl; rewrite String.eqb_refl; simpl.\n        move=> <-; simpl.\n        rewrite String.eqb_refl; reflexivity.\n    }\nQed.\n\nGoal\n    update (2::nil) (1::2::nil) (ASlice [:: 0] AAll) [:: CoIL 1] (DirH 8) = Some (1::2::nil, nil).\nProof.\n    simpl; reflexivity.\nQed.\n\nGoal\n    forall arch prog type_ctxt ctxt opt_ctxt' var typ dir,\n        find_val type_ctxt var = Some typ ->\n        well_typed_ctxt type_ctxt ctxt ->\n        convert_type typ nil = Some (dir, 2::nil) ->\n        eval_deq arch prog type_ctxt ctxt\n             (Eqn (Range (Var var) (Const_e 1) (Const_e 0)::nil) (Tuple (ECons (Const 1 None)\n                            (ECons (Const 2 None) Enil)))\n                true) = opt_ctxt'\n        -> (ctxt' <- opt_ctxt'; find_val ctxt' var) = Some (CoIR dir (2::1::nil) (Some (2::nil))).\nProof.\n    simpl.\n    unfold bind; unfold bind_aux_list.\n    unfold bind_aux.\n    simpl.\n    move=> _ _ type_ctxt ctxt opt_ctxt var typ dir HEqType well_typed.\n    rewrite HEqType; move=> Convert; rewrite Convert; simpl.\n    case_eq (find_val ctxt var).\n    {\n        move=> c HEq.\n        pose (p := well_typed_ctxt_imp_find_val _ _ _ _ well_typed HEq).\n        destruct p as [typ' [find_typ valoType]].\n        rewrite find_typ in HEqType; inversion HEqType as [HEq'].\n        destruct HEq'; clear HEqType.\n        destruct typ' as [|d m n|typ len]; simpl in Convert.\n        by discriminate.\n        all: swap 1 2.\n        {\n            destruct (eval_arith_expr nil len) as [ilen|].\n            2: by discriminate.\n            exfalso; move: Convert.\n            clear.\n            pose (p := [:: ilen]); fold p.\n            assert (p <> nil) as NotEmpty by (unfold p; move=> Eq; discriminate).\n            move: p NotEmpty; clear.\n            induction typ as [|d m n|typ HRec len']; simpl.\n            by discriminate.\n            {\n                destruct m.\n                + move=> []; destruct d; auto.\n                    3-6: by discriminate.\n                    1-2: move=> a []; simpl; discriminate.\n                + discriminate.\n                + discriminate.\n            }\n            {\n                destruct (eval_arith_expr nil len').\n                2: by discriminate.\n                move=> [|hd tl] NotEmpty.\n                by exfalso; apply NotEmpty; reflexivity.\n                apply HRec.\n                discriminate.\n            }\n        }\n        simpl in *.\n        destruct m as [| |].\n        2,3: by destruct valoType.\n        destruct c as [|d' l form]; simpl.\n        {\n            destruct d.\n            3-6: discriminate.\n            all: inversion Convert.\n            all: destruct valoType as [_ [_ HEq2]].\n            all: symmetry in HEq2; destruct HEq2; discriminate.\n        }\n        destruct form.\n        2: by destruct valoType.\n        rewrite muln1 in valoType.\n        destruct d.\n        3-5: by discriminate.\n        all: inversion Convert as [[HEq2 HEq3]]; clear Convert; simpl.\n        all: destruct HEq2.\n        all: symmetry in HEq3; destruct HEq3.\n        all: destruct valoType as [simpl_eq [length_eq dir_eq]].\n        all: rewrite length_eq; simpl.\n        all: destruct l as [|h1 l].\n        1,3: by discriminate.\n        all: destruct l as [|h2 l].\n        1,3: by discriminate.\n        all: destruct l as [|].\n        2,4: by discriminate.\n        all: simpl.\n        all: move=> <-; simpl.\n        all: rewrite String.eqb_refl.\n        all: reflexivity.\n    }\n    {\n        simpl.\n        move=> _ <-; simpl.\n        rewrite String.eqb_refl.\n        reflexivity.\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/test_sem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2965029889164765}}
{"text": "From iris.proofmode Require Import tactics.\nFrom iris.algebra Require Import excl agree csum.\nFrom iris.program_logic Require Export weakestpre hoare.\nFrom iris.heap_lang Require Export lang.\nFrom iris.heap_lang Require Import assert proofmode notation adequacy.\nFrom iris.heap_lang.lib Require Import par.\nSet Default Proof Using \"Type\".\n\n(** This is the introductory example from the \"Iris from the Ground Up\" journal\npaper. *)\n\nDefinition one_shot_example : val := λ: <>,\n  let: \"x\" := ref NONE in (\n  (* tryset *) (λ: \"n\",\n    CAS \"x\" NONE (SOME \"n\")),\n  (* check  *) (λ: <>,\n    let: \"y\" := !\"x\" in λ: <>,\n    match: \"y\" with\n      NONE => #()\n    | SOME \"n\" =>\n       match: !\"x\" with\n         NONE => assert: #false\n       | SOME \"m\" => assert: \"n\" = \"m\"\n       end\n    end)).\n\nDefinition one_shotR := csumR (exclR unitO) (agreeR ZO).\nDefinition Pending : one_shotR := Cinl (Excl ()).\nDefinition Shot (n : Z) : one_shotR := Cinr (to_agree n).\n\nClass one_shotG Σ := { one_shot_inG :> inG Σ one_shotR }.\nDefinition one_shotΣ : gFunctors := #[GFunctor one_shotR].\nInstance subG_one_shotΣ {Σ} : subG one_shotΣ Σ → one_shotG Σ.\nProof. solve_inG. Qed.\n\nSection proof.\nLocal Set Default Proof Using \"Type*\".\nContext `{!heapG Σ, !one_shotG Σ}.\n\nDefinition one_shot_inv (γ : gname) (l : loc) : iProp Σ :=\n  (l ↦ NONEV ∗ own γ Pending ∨ ∃ n : Z, l ↦ SOMEV #n ∗ own γ (Shot n))%I.\n\nLemma wp_one_shot (Φ : val → iProp Σ) :\n  (∀ f1 f2 : val,\n    (∀ n : Z, □ WP f1 #n {{ w, ⌜w = #true⌝ ∨ ⌜w = #false⌝ }}) ∗\n    □ WP f2 #() {{ g, □ WP g #() {{ _, True }} }} -∗ Φ (f1,f2)%V)\n  ⊢ WP one_shot_example #() {{ Φ }}.\nProof.\n  iIntros \"Hf /=\". pose proof (nroot .@ \"N\") as N.\n  rewrite -wp_fupd. wp_lam. wp_alloc l as \"Hl\".\n  iMod (own_alloc Pending) as (γ) \"Hγ\"; first done.\n  iMod (inv_alloc N _ (one_shot_inv γ l) with \"[Hl Hγ]\") as \"#HN\".\n  { iNext. iLeft. by iSplitL \"Hl\". }\n  wp_pures. iModIntro. iApply \"Hf\"; iSplit.\n  - iIntros (n) \"!>\". wp_lam. wp_pures. wp_bind (CmpXchg _ _ _).\n    iInv N as \">[[Hl Hγ]|H]\"; last iDestruct \"H\" as (m) \"[Hl Hγ]\".\n    + iMod (own_update with \"Hγ\") as \"Hγ\".\n      { by apply cmra_update_exclusive with (y:=Shot n). }\n      wp_cmpxchg_suc. iModIntro. iSplitL; last (wp_pures; by eauto).\n      iNext; iRight; iExists n; by iFrame.\n    + wp_cmpxchg_fail. iModIntro. iSplitL; last (wp_pures; by eauto).\n      rewrite /one_shot_inv; eauto 10.\n  - iIntros \"!> /=\". wp_lam. wp_bind (! _)%E.\n    iInv N as \">Hγ\".\n    iAssert (∃ v, l ↦ v ∗ ((⌜v = NONEV⌝ ∗ own γ Pending) ∨\n       ∃ n : Z, ⌜v = SOMEV #n⌝ ∗ own γ (Shot n)))%I with \"[Hγ]\" as \"Hv\".\n    { iDestruct \"Hγ\" as \"[[Hl Hγ]|Hl]\"; last iDestruct \"Hl\" as (m) \"[Hl Hγ]\".\n      + iExists NONEV. iFrame. eauto.\n      + iExists (SOMEV #m). iFrame. eauto. }\n    iDestruct \"Hv\" as (v) \"[Hl Hv]\". wp_load.\n    iAssert (one_shot_inv γ l ∗ (⌜v = NONEV⌝ ∨ ∃ n : Z,\n      ⌜v = SOMEV #n⌝ ∗ own γ (Shot n)))%I with \"[Hl Hv]\" as \"[Hinv #Hv]\".\n    { iDestruct \"Hv\" as \"[[% ?]|Hv]\"; last iDestruct \"Hv\" as (m) \"[% ?]\"; subst.\n      + Show. iSplit. iLeft; by iSplitL \"Hl\". eauto.\n      + iSplit. iRight; iExists m; by iSplitL \"Hl\". eauto. }\n    iSplitL \"Hinv\"; first by eauto.\n    iModIntro. wp_pures. iIntros \"!>\". wp_lam.\n    iDestruct \"Hv\" as \"[%|Hv]\"; last iDestruct \"Hv\" as (m) \"[% Hγ']\";\n      subst; wp_match; [done|].\n    wp_bind (! _)%E.\n    iInv N as \"[[Hl >Hγ]|H]\"; last iDestruct \"H\" as (m') \"[Hl Hγ]\".\n    { by iDestruct (own_valid_2 with \"Hγ Hγ'\") as %?. }\n    wp_load. Show.\n    iDestruct (own_valid_2 with \"Hγ Hγ'\") as %?%to_agree_op_inv_L; subst.\n    iModIntro. iSplitL \"Hl\".\n    { iNext; iRight; by eauto. }\n    wp_apply wp_assert. wp_pures. by case_bool_decide.\nQed.\n\nLemma ht_one_shot (Φ : val → iProp Σ) :\n  ⊢ {{ True }} one_shot_example #()\n    {{ ff,\n      (∀ n : Z, {{ True }} Fst ff #n {{ w, ⌜w = #true⌝ ∨ ⌜w = #false⌝ }}) ∗\n      {{ True }} Snd ff #() {{ g, {{ True }} g #() {{ _, True }} }}\n    }}.\nProof.\n  iIntros \"!> _\". iApply wp_one_shot. iIntros (f1 f2) \"[#Hf1 #Hf2]\"; iSplit.\n  - iIntros (n) \"!> _\". wp_apply \"Hf1\".\n  - iIntros \"!> _\". wp_apply (wp_wand with \"Hf2\"). by iIntros (v) \"#? !> _\".\nQed.\nEnd proof.\n\n(* Have a client with a closed proof. *)\nDefinition client : expr :=\n  let: \"ff\" := one_shot_example #() in\n  (Fst \"ff\" #5 ||| let: \"check\" := Snd \"ff\" #() in \"check\" #()).\n\nSection client.\n  Context `{!heapG Σ, !one_shotG Σ, !spawnG Σ}.\n\n  Lemma client_safe : ⊢ WP client {{ _, True }}.\n  Proof using Type*.\n    rewrite /client. wp_apply wp_one_shot. iIntros (f1 f2) \"[#Hf1 #Hf2]\".\n    wp_let. wp_apply wp_par.\n    - wp_apply \"Hf1\".\n    - wp_proj. wp_bind (f2 _)%E. iApply wp_wand; first by iExact \"Hf2\".\n      iIntros (check) \"Hcheck\". wp_pures. iApply \"Hcheck\".\n    - auto.\n  Qed.\nEnd client.\n\n(** Put together all library functors. *)\nDefinition clientΣ : gFunctors := #[ heapΣ; one_shotΣ; spawnΣ ].\n(** This lemma implicitly shows that these functors are enough to meet\nall library assumptions. *)\nLemma client_adequate σ : adequate NotStuck client σ (λ _ _, True).\nProof. apply (heap_adequacy clientΣ)=> ?. iIntros \"_\". iApply client_safe. Qed.\n\n(* Since we check the output of the test files, this means\nour test suite will fail if we ever accidentally add an axiom\nto anything used by this proof. *)\nPrint Assumptions client_adequate.\n", "meta": {"author": "SkySkimmer", "repo": "iris", "sha": "186d9ece07e210e92be28eb0e1a42f5d5fe6f1b5", "save_path": "github-repos/coq/SkySkimmer-iris", "path": "github-repos/coq/SkySkimmer-iris/iris-186d9ece07e210e92be28eb0e1a42f5d5fe6f1b5/tests/one_shot.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2965029834255887}}
{"text": "From Undecidability.L.Tactics Require Import LTactics.\nFrom Undecidability.L Require Import UpToC.\nFrom Undecidability.L.Datatypes Require Export List_enc List_in List_basics LBool LNat.\n\nSet Default Proof Using \"Type\".\n\nDefinition lengthEq A :=\n  fix f (t:list A) n :=\n    match n,t with\n      0,nil => true\n    | (S n), _::t => f t n\n    | _,_ => false\n    end.\nLemma lengthEq_spec A (t:list A) n:\n| t | =? n = lengthEq t n.\nProof.\n  induction n in t|-*;destruct t;now cbn.\nQed.\nDefinition lengthEq_time k := k * 15 + 9.\nInstance term_lengthEq A `{registered A} : computableTime' (lengthEq (A:=A)) (fun l _ => (5, fun n _ => (lengthEq_time (min (length l) n),tt))).\nProof.\n  extract. unfold lengthEq_time. solverec.\nQed.\n\n\n(* seq *)\nDefinition c__seq := 20.\nDefinition seq_time (len : nat) := (len + 1) * c__seq.\nInstance term_seq : computableTime' seq (fun start _ => (5, fun len _ => (seq_time len, tt))). \nProof. \n  extract. solverec. \n  all: unfold seq_time, c__seq; solverec. \nDefined. \n\n(* prodLists *)\nSection fixprodLists. \n  Variable (X Y : Type).\n  Context `{Xint : registered X} `{Yint : registered Y}.\n\n  Definition c__prodLists1 := 22 + c__map + c__app. \n  Definition c__prodLists2 := 2 * c__map + 39 + c__app.\n  Definition prodLists_time (l1 : list X) (l2 : list Y) := (|l1|) * (|l2| + 1) * c__prodLists2 + c__prodLists1. \n  Global Instance term_prodLists : computableTime' (@list_prod X Y) (fun l1 _ => (5, fun l2 _ => (prodLists_time l1 l2, tt))). \n  Proof. \n    apply computableTimeExt with (x := fix rec (A : list X) (B : list Y) : list (X * Y) := \n      match A with \n      | [] => []\n      | x :: A' => map (@pair X Y x) B ++ rec A' B \n      end). \n    1: { unfold list_prod. change (fun x => ?h x) with h. intros l1 l2. induction l1; easy. }\n    extract. solverec. \n    all: unfold prodLists_time, c__prodLists1, c__prodLists2; solverec. \n    rewrite map_length, map_time_const. leq_crossout. \n  Defined. \nEnd fixprodLists. \n\n", "meta": {"author": "uds-psl", "repo": "constructive-and-synthetic-reducibility-in-coq", "sha": "3bd7c2e7c311d17bb93a9edcd55e39fc1ad9aa9d", "save_path": "github-repos/coq/uds-psl-constructive-and-synthetic-reducibility-in-coq", "path": "github-repos/coq/uds-psl-constructive-and-synthetic-reducibility-in-coq/constructive-and-synthetic-reducibility-in-coq-3bd7c2e7c311d17bb93a9edcd55e39fc1ad9aa9d/L/Datatypes/List/List_extra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.2964449663248682}}
{"text": "Require Import Coq.Sets.Ensembles Platform.AutoSep.\n\nRequire Import Platform.Malloc Platform.Facade.examples.FiatADTs Platform.Facade.examples.FiniteSetF.\n\n\nModule Type ADT.\n  Parameter lset : Ensemble W -> W -> HProp.\n  Parameter lset' : Ensemble W -> nat -> W -> HProp.\n\n  Axiom lset_fwd : forall s c, lset s c ===> [| c <> 0 |] * [| freeable c 2 |]\n    * Ex p, Ex junk, (c ==*> p, junk) * Ex n, lset' s n p.\n  Axiom lset_bwd : forall s (c : W), ([| c <> 0 |] * [| freeable c 2 |]\n    * Ex p, Ex junk, (c ==*> p, junk) * Ex n, lset' s n p) ===> lset s c.\n\n  Axiom lset'_empty_fwd : forall s n (c : W), c = 0\n    -> lset' s n c\n    ===> [| n = O |] * [| s === %0 |].\n\n  Axiom lset'_empty_bwd : forall s n (c : W), c = 0\n    -> [| n = O |] * [| s === %0 |] ===> lset' s n c.\n\n  Axiom lset'_nonempty_fwd : forall s n (c : W), c <> 0\n    -> lset' s n c\n    ===> Ex n', [| n = S n' |] * [| freeable c 2 |] * Ex x, [| s %has x |] * Ex p', (c ==*> x, p')\n        * lset' (s %- x) n' p'.\n\n  Axiom lset'_nonempty_bwd : forall s n (c : W), c <> 0\n    -> (Ex n', [| n = S n' |] * [| freeable c 2 |] * Ex x, [| s %has x |] * Ex p', (c ==*> x, p')\n        * lset' (s %- x) n' p') ===> lset' s n c.\n\n  Axiom lset'_monotone : forall n s s' p, s === s'\n    -> lset' s n p ===> lset' s' n p.\nEnd ADT.\n\nModule Adt : ADT.\n  Open Scope Sep_scope.\n\n  Fixpoint lset' (s : Ensemble W) (n : nat) (p : W) : HProp :=\n    match n with\n      | O => [| p = 0 |] * [| s === %0 |]\n      | S n' => [| p <> 0 |] * [| freeable p 2 |]\n        * Ex x, [| s %has x |] * Ex p', (p ==*> x, p')\n        * lset' (s %- x) n' p'\n    end.\n\n  Definition lset (s : Ensemble W) (c : W) : HProp :=\n    [| c <> 0 |] * [| freeable c 2 |]\n    * Ex p, Ex junk, (c ==*> p, junk) * Ex n, lset' s n p.\n\n  Theorem lset_fwd : forall s c, lset s c ===> [| c <> 0 |] * [| freeable c 2 |]\n    * Ex p, Ex junk, (c ==*> p, junk) * Ex n, lset' s n p.\n    unfold lset; sepLemma.\n  Qed.\n\n  Theorem lset_bwd : forall s (c : W), ([| c <> 0 |] * [| freeable c 2 |]\n    * Ex p, Ex junk, (c ==*> p, junk) * Ex n, lset' s n p) ===> lset s c.\n    unfold lset; sepLemma.\n  Qed.\n\n  Theorem lset'_empty_fwd : forall s n (c : W), c = 0\n    -> lset' s n c\n    ===> [| n = O |] * [| s === %0 |].\n    destruct n; sepLemma.\n  Qed.\n\n  Theorem lset'_empty_bwd : forall s n (c : W), c = 0\n    -> [| n = O |] * [| s === %0 |] ===> lset' s n c.\n    destruct n; sepLemma.\n  Qed.\n\n  Theorem lset'_nonempty_fwd : forall s n (c : W), c <> 0\n    -> lset' s n c\n    ===> Ex n', [| n = S n' |] * [| freeable c 2 |] * Ex x, [| s %has x |] * Ex p', (c ==*> x, p')\n        * lset' (s %- x) n' p'.\n    destruct n; sepLemma.\n  Qed.\n\n  Theorem lset'_nonempty_bwd : forall s n (c : W), c <> 0\n    -> (Ex n', [| n = S n' |] * [| freeable c 2 |] * Ex x, [| s %has x |] * Ex p', (c ==*> x, p')\n        * lset' (s %- x) n' p') ===> lset' s n c.\n    destruct n; sepLemma.\n    injection H0; sepLemma.\n  Qed.\n\n  Theorem lset'_monotone : forall n s s' p, s === s'\n    -> lset' s n p ===> lset' s' n p.\n    induction n; sepLemma.\n    split; do 2 intro.\n    apply (proj2 H) in H0.\n    apply (proj1 H1) in H0.\n    auto.\n    destruct H0.\n    rewrite has_eq in *.\n    apply H; auto.\n    apply IHn.\n    split; do 2 intro.\n    destruct H3.\n    split; auto.\n    apply H; auto.\n    destruct H3.\n    split; auto.\n    apply H; auto.\n  Qed.\nEnd Adt.\n\nImport Adt.\nExport Adt.\n\n(* Hm... to avoid stack overflow, need to rebind these! *)\nDefinition lset'_empty_fwd : forall s n (c : W), c = 0\n  -> lset' s n c\n  ===> [| n = O |] * [| s === %0 |] := lset'_empty_fwd.\n\nDefinition lset'_empty_bwd : forall s n (c : W), c = 0\n  -> [| n = O |] * [| s === %0 |] ===> lset' s n c := lset'_empty_bwd.\n\nDefinition hints : TacPackage.\n  prepare (lset_fwd, lset'_empty_fwd, lset'_nonempty_fwd)\n  (lset_bwd, lset'_empty_bwd, lset'_nonempty_bwd).\nDefined.\n\nDefinition newS := newS lset 8.\nDefinition deleteS := deleteS lset 7.\nDefinition memS := memS lset 1.\nDefinition addS := addS lset 9.\nDefinition removeS := removeS lset 7.\nDefinition sizeS := sizeS lset 1.\n\nDefinition cardinal_plus (s : Ensemble W) (R acc : W) :=\n  exists n, cardinal _ s n /\\ R = natToWord _ n ^+ acc.\n\nDefinition m := bimport [[ \"malloc\"!\"malloc\" @ [mallocS], \"malloc\"!\"free\" @ [freeS] ]]\n  bmodule \"ListSet\" {{\n    bfunction \"new\"(\"extra_stack\", \"x\") [newS]\n      \"x\" <-- Call \"malloc\"!\"malloc\"(0, 2)\n      [PRE[_, R] R =?> 2 * [| R <> 0 |] * [| freeable R 2 |] * mallocHeap 0\n       POST[R'] lset %0 R' * mallocHeap 0];;\n\n      \"x\" *<- 0;;\n      Return \"x\"\n    end\n\n    with bfunction \"delete\"(\"extra_stack\", \"self\", \"ls\") [deleteS]\n      \"ls\" <-* \"self\";;\n\n      Call \"malloc\"!\"free\"(0, \"self\", 2)\n      [Al s, Al n,\n        PRE[V] lset' s n (V \"ls\") * mallocHeap 0\n        POST[R] [| R = $0 |] * mallocHeap 0];;\n\n      [Al s, Al n,\n        PRE[V] lset' s n (V \"ls\") * mallocHeap 0\n        POST[R] [| R = $0 |] * mallocHeap 0]\n      While (\"ls\" <> 0) {\n        \"self\" <-* \"ls\"+4;;\n        Call \"malloc\"!\"free\"(0, \"ls\", 2)\n        [Al s, Al n,\n          PRE[V] lset' s n (V \"self\") * mallocHeap 0\n          POST[R] [| R = $0 |] * mallocHeap 0];;\n\n        \"ls\" <- \"self\"\n      };;\n\n      Return 0\n    end\n\n    with bfunction \"mem\"(\"extra_stack\", \"self\", \"n\", \"tmp\") [memS]\n      \"self\" <-* \"self\";;\n\n      [Al s, Al n,\n        PRE[V] lset' s n (V \"self\")\n        POST[R] lset' s n (V \"self\") * [| s %has V \"n\" \\is R |] ]\n      While (\"self\" <> 0) {\n        \"tmp\" <-* \"self\";;\n\n        If (\"tmp\" = \"n\") {\n          Return 1\n        } else {\n          \"self\" <-* \"self\"+4\n        }\n      };;\n\n      Return 0\n    end\n\n    with bfunction \"add\"(\"extra_stack\", \"self\", \"n\", \"tmp\") [addS]\n      \"tmp\" <-- Call \"ListSet\"!\"mem\"(\"extra_stack\", \"self\", \"n\")\n      [Al s,\n        PRE[V, R] [| s %has V \"n\" \\is R |] * lset s (V \"self\") * mallocHeap 0\n        POST[R'] [| R' = $0 |] * lset (s %+ V \"n\") (V \"self\") * mallocHeap 0];;\n\n      If (\"tmp\" = 1) {\n        Return 0\n      } else {\n        \"tmp\" <-- Call \"malloc\"!\"malloc\"(0, 2)\n        [Al s,\n          PRE[V, R] R =?> 2 * [| R <> 0 |] * [| freeable R 2 |]\n            * [| ~s %has V \"n\" |] * lset s (V \"self\")\n          POST[R'] [| R' = $0 |] * lset (s %+ V \"n\") (V \"self\")];;\n\n        \"tmp\" *<- \"n\";;\n        \"n\" <-* \"self\";;\n        \"tmp\"+4 *<- \"n\";;\n        \"self\" *<- \"tmp\";;\n        Return 0\n      }\n    end\n\n    with bfunction \"remove\"(\"extra_stack\", \"self\", \"n\", \"tmp\") [removeS]\n      \"tmp\" <-* \"self\";;\n\n      [Al s, Al n,\n        PRE[V] V \"self\" =*> V \"tmp\" * lset' s n (V \"tmp\") * mallocHeap 0\n        POST[R] [| R = $0 |] * Ex p, Ex n', V \"self\" =*> p * lset' (s %- V \"n\") n' p * mallocHeap 0 ]\n      While (\"tmp\" <> 0) {\n        \"tmp\" <-* \"tmp\";;\n\n        If (\"tmp\" = \"n\") {\n          \"tmp\" <-* \"self\";;\n          \"n\" <-* \"tmp\"+4;;\n          \"self\" *<- \"n\";;\n\n          Call \"malloc\"!\"free\"(0, \"tmp\", 2)\n          [PRE[_] Emp\n           POST[R] [| R = $0 |] ];;\n\n          Return 0\n        } else {\n          \"tmp\" <-* \"self\";;\n          \"self\" <- \"tmp\"+4;;\n          \"tmp\" <-* \"self\"\n        }\n      };;\n\n      Return 0\n    end\n\n    with bfunction \"size\"(\"extra_stack\", \"self\", \"acc\") [sizeS]\n      \"self\" <-* \"self\";;\n      \"acc\" <- 0;;\n\n      [Al s, Al n,\n        PRE[V] lset' s n (V \"self\")\n        POST[R] lset' s n (V \"self\") * [| cardinal_plus s R (V \"acc\") |] ]\n      While (\"self\" <> 0) {\n        \"acc\" <- \"acc\" + 1;;\n        \"self\" <-* \"self\"+4\n      };;\n\n      Return \"acc\"\n    end\n  }}.\n\nLocal Hint Extern 1 (@eq W _ _) => words.\n\nTheorem Singleton_bwd : forall A x y,\n  Singleton A x y -> x = y.\n  destruct 1; auto.\nQed.\n\nLocal Hint Immediate Singleton_bwd.\n\nLtac sets' := try rewrite has_eq in *;\n  unfold propToWord, IF_then_else, add, sub, Add, Subtract, Setminus,\n  Same_set, Included, Ensembles.In in *;\n  intuition eauto.\n\nTheorem Union_fwd : forall A x y z,\n  x z \\/ y z\n  -> Union A x y z.\nProof.\n  intuition; solve [ constructor; auto | constructor 2; auto ].\nQed.\n\nLtac sets :=\n  repeat match goal with\n           | [ H : _ === _ |- _ ] => generalize dependent H\n           | [ H : _ %has _ |- _ ] => generalize dependent H\n           | [ H : ~(_ %has _) |- _ ] => generalize dependent H\n           | [ H : _ %has _ \\is _ |- _ ] => generalize dependent H\n           | [ H : @eq W _ _ |- _ ] => generalize dependent H\n           | [ H : not (@eq W _ _) |- _ ] => generalize dependent H\n         end; clear; intros;\n  sets'; repeat (match goal with\n                   | [ H0 : ?X = natToW 0, H1 : ?X = natToW 1 |- _ ] => rewrite H0 in H1; discriminate\n                   | [ H : Empty_set _ _ |- _ ] => destruct H\n                   | [ H : Singleton _ _ _ |- _ ] => destruct H\n                   | [ |- Singleton _ _ _] => constructor\n                   | [ H : Union _ _ _ _ |- _ ] => destruct H\n                   | [ |- Union _ _ _ _] => apply Union_fwd\n                 end; sets').\n\nTheorem empty_bwd : forall x, %0 x -> False.\n  destruct 1.\nQed.\n\nLocal Hint Resolve empty_bwd.\n\nLemma cardinal_plus_O : forall s w, cardinal_plus s w 0\n  -> cardinal_is s w.\n  destruct 1; intuition; eexists; eauto.\nQed.\n\nLocal Hint Immediate cardinal_plus_O.\n\nFixpoint nuke (ls : list W) (w : W) : list W :=\n  match ls with\n    | nil => nil\n    | w' :: ls' =>\n      if weq w' w then ls' else w' :: nuke ls' w\n  end.\n\nLemma nuke_ok : forall w ls s,\n  EnsembleListEquivalence (s %- w) ls\n  -> s %has w\n  -> EnsembleListEquivalence s (w :: ls).\n  intros.\n  destruct H.\n  split.\n  constructor; auto.\n  intro.\n  apply H1 in H2.\n  destruct H2.\n  apply H3.\n  constructor.\n\n  simpl; intuition.\n  destruct (weq w x); auto.\n  right; apply H1.\n  constructor; auto.\n  subst; sets.\n  apply H1 in H3.\n  destruct H3; auto.\nQed.\n\nLemma cardinal_plus_minus : forall s w r acc,\n  cardinal_plus (s %- w) r (acc ^+ natToW 1)\n  -> s %has w\n  -> cardinal_plus s r acc.\n  destruct 1; intuition subst.\n  destruct H1; intuition subst.\n  eexists; split.\n  hnf; eauto using nuke_ok.\n  simpl.\n  rewrite natToWord_S.\n  rewrite <- plus_n_O.\n  words.\nQed.\n\nLocal Hint Immediate cardinal_plus_minus.\n\nLemma cardinal_is_bottom : forall r acc s,\n  r = acc\n  -> s === %0\n  -> cardinal_plus s r acc.\nProof.\n  intros; subst.\n  exists 0; intuition.\n  exists nil; intuition.\n  split; intuition.\n  constructor.\n  apply H0 in H.\n  destruct H.\nQed.\n\nLocal Hint Immediate cardinal_is_bottom.\n\nTheorem ok : moduleOk m.\n  vcgen; abstract (sep hints; eauto; try apply lset'_monotone; sets).\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/Facade/examples/ListSetF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.2964449579727892}}
{"text": "(** * Stlc_J: 単純型付きラムダ計算 *)\n(* * Stlc: The Simply Typed Lambda-Calculus *)\n\n(* $Date: 2011-06-09 16:11:42 -0400 (Thu, 09 Jun 2011) $ *)\n\n\nRequire Export Types.\n\n(* ###################################################################### *)\n(* * The Simply Typed Lambda-Calculus *)\n(** * 単純型付きラムダ計算 *)\n\n(* The simply typed lambda-calculus (STLC) is a tiny core calculus\n    embodying the key concept of _functional abstraction_, which shows\n    up in pretty much every real-world programming language in some\n    form (functions, procedures, methods, etc.).\n\n    We will follow exactly the same pattern as above when formalizing\n    of this calculus (syntax, small-step semantics, typing rules) and\n    its main properties (progress and preservation).  The new\n    technical challenges (which will take some work to deal with) all\n    arise from the mechanisms of _variable binding_ and\n    _substitution_. *)\n(** 単純型付きラムダ計算(Simply Typed Lambda-Calculus, STLC)は、\n    関数抽象(_functional abstraction_)を具現する、小さな、核となる計算体系です。\n    関数抽象は、ほとんどすべての実世界のプログラミング言語に何らかの形\n    (関数、手続き、メソッド等)で現れます。\n\n    ここでは、この計算体系(構文、スモールステップ意味論、\n    型付け規則)とその性質(進行と保存)の形式化を、\n    これまでやったのとまったく同じパターンで行います。\n    (扱うためにいくらかの作業が必要になる)新しい技術的挑戦は、\n    すべて変数束縛(_variable binding_)と置換(_substitution_)の機構から生じます。*)\n\n(* ###################################################################### *)\n(* ** Overview *)\n(** ** 概観 *)\n\n(* The STLC is built on some collection of _base types_ -- booleans,\n    numbers, strings, etc.  The exact choice of base types doesn't\n    matter -- the construction of the language and its theoretical\n    properties work out pretty much the same -- so for the sake of\n    brevity let's take just [Bool] for the moment.  At the end of the\n    chapter we'll see how to add more base types, and in later\n    chapters we'll enrich the pure STLC with other useful constructs\n    like pairs, records, subtyping, and mutable state.\n\n    Starting from the booleans, we add three things:\n        - variables\n        - function abstractions\n        - application\n\n    This gives us the following collection of abstract syntax\n    constructors (written out here in informal BNF notation -- we'll\n    formalize it below):\n<<<\n       t ::= x                       variable\n           | \\x:T.t1                 abstraction\n           | t1 t2                   application\n           | true                    constant true\n           | false                   constant false\n           | if t1 then t2 else t3   conditional\n>>\n    The [\\] symbol in a function abstraction [\\x:T.t1] is often\n    written as a greek \"lambda\" (hence the name of the calculus).  The\n    variable [x] is called the _parameter_ to the function; the term\n    [t1] is its _body_.  The annotation [:T] specifies the type of\n    arguments that the function can be applied to.\n\n    Some examples:\n\n      - [\\x:Bool. x]\n\n        The identity function for booleans.\n\n      - [(\\x:Bool. x) true]\n\n        The identity function for booleans, applied to the boolean [true].\n\n      - [\\x:Bool. if x then false else true]\n\n        The boolean \"not\" function.\n\n      - [\\x:Bool. true]\n\n        The constant function that takes every (boolean) argument to\n        [true].\n\n      - [\\x:Bool. \\y:Bool. x]\n\n        A two-argument function that takes two booleans and returns\n        the first one.  (Note that, as in Coq, a two-argument function\n        is really a one-argument function whose body is also a\n        one-argument function.)\n\n      - [(\\x:Bool. \\y:Bool. x) false true]\n\n        A two-argument function that takes two booleans and returns\n        the first one, applied to the booleans [false] and [true].\n        Note that, as in Coq, application associates to the left --\n        i.e., this expression is parsed as [((\\x:Bool. \\y:Bool. x)\n        false) true].\n\n      - [\\f:Bool->Bool. f (f true)]\n\n        A higher-order function that takes a _function_ [f] (from\n        booleans to booleans) as an argument, applies [f] to [true],\n        and applies [f] again to the result.\n\n      - [(\\f:Bool->Bool. f (f true)) (\\x:Bool. false)]\n\n        The same higher-order function, applied to the constantly\n        [false] function.\n\n    As the last several examples show, the STLC is a language of\n    _higher-order_ functions: we can write down functions that take\n    other functions as arguments and/or return other functions as\n    results.\n\n    Another point to note is that the STLC doesn't provide any\n    primitive syntax for defining _named_ functions -- all functions\n    are \"anonymous.\"  We'll see in chapter [MoreStlc] that it is easy\n    to add named functions to what we've got -- indeed, the\n    fundamental naming and binding mechanisms are exactly the same.\n\n    The _types_ of the STLC include [Bool], which classifies the\n    boolean constants [true] and [false] as well as more complex\n    computations that yield booleans, plus _arrow types_ that classify\n    functions.\n<<\n      T ::= Bool\n          | T1 -> T2\n>>\n    For example:\n\n      - [\\x:Bool. false] has type [Bool->Bool]\n\n      - [\\x:Bool. x] has type [Bool->Bool]\n\n      - [(\\x:Bool. x) true] has type [Bool]\n\n      - [\\x:Bool. \\y:Bool. x] has type [Bool->Bool->Bool] (i.e. [Bool -> (Bool->Bool)])\n\n      - [(\\x:Bool. \\y:Bool. x) false] has type [Bool->Bool]\n\n      - [(\\x:Bool. \\y:Bool. x) false true] has type [Bool]\n\n      - [\\f:Bool->Bool. f (f true)] has type [(Bool->Bool) -> Bool]\n\n      - [(\\f:Bool->Bool. f (f true)) (\\x:Bool. false)] has type [Bool]\n*)\n(** STLC は基本型(_base types_)の何らかの集まりの上に構成されます。\n    基本型はブール型、数値、文字列などです。\n    実際にどの基本型を選択するかは問題ではありません。\n    どう選択しても、言語の構成とその理論的性質はまったく同じように導かれます。\n    これから、簡潔にするため、しばらくは[Bool]だけとしましょう。\n    この章の終わりには、さらに基本型を追加する方法がわかるでしょう。\n    また後の章では、純粋なSTLCに、対、レコード、サブタイプ、\n    変更可能状態などの他の便利な構成要素をとり入れてよりリッチなものにします。\n\n    ブール値から始めて3つのものを追加します:\n        - 変数\n        - 関数抽象\n        - (関数)適用\n\n    これから、以下の抽象構文コンストラクタが出てきます\n    (ここではこれを非形式的BNF記法で書き出します。後に形式化します。):\n<<\n       t ::= x                       変数\n           | \\x:T.t1                 関数抽象\n           | t1 t2                   関数適用\n           | true                    定数 true\n           | false                   定数 false\n           | if t1 then t2 else t3   条件式\n>>\n    関数抽象 [\\x:T.t1] の [\\]記号はよくギリシャ文字のラムダ(λ)で記述されます\n    (これがラムダ計算の名前の由来です)。\n    変数[x]は関数のパラメータ(_parameter_)、\n    項[t1]は関数の本体(_body_)と呼ばれます。\n    付記された [:T] は関数が適用される引数の型を定めます。\n\n    例をいくつか:\n\n      - [\\x:Bool. x]\n\n        ブール値の恒等関数。\n\n      - [(\\x:Bool. x) true]\n\n        ブール値[true]に適用された、ブール値の恒等関数。\n\n      - [\\x:Bool. if x then false else true]\n\n        ブール値の否定関数。\n\n      - [\\x:Bool. true]\n\n        すべての(ブール値の)引数に対して[true]を返す定数関数。\n\n      - [\\x:Bool. \\y:Bool. x]\n\n        2つのブール値をとり、最初のものを返す2引数関数。\n        (なお、Coqと同様、2引数関数は、実際には本体が1引数関数である1引数関数です。)\n\n      - [(\\x:Bool. \\y:Bool. x) false true]\n\n        2つのブール値をとり、最初のものを返す2引数関数を、ブール値[false]と[true]\n        に適用したもの。\n        なお、Coqと同様、関数適用は左結合です。つまり、この式は\n        [((\\x:Bool. \\y:Bool. x) false) true] と構文解析されます。\n\n      - [\\f:Bool->Bool. f (f true)]\n\n        (ブール値からブール値への)「関数」[f]を引数にとる高階関数。\n        この高階関数は、[f]を[true]に適用し、その値にさらに[f]を適用します。\n\n      - [(\\f:Bool->Bool. f (f true)) (\\x:Bool. false)]\n\n        上記高階関数を、常に[false]を返す定数関数に適用したもの。\n\n    最後のいくつかの例で示されたように、STLCは高階(_higher-order_)関数の言語です。\n    他の関数を引数として取る関数や、結果として他の関数を返す関数を書き下すことができます。\n\n    別の注目点は、名前を持つ(_named_)関数を定義する基本構文を、STLCは何も持っていないことです。\n    すべての関数は「名無し」(\"anonymous\")です。\n    後の[MoreStlc_J]章で、この体系に名前を持つ関数を追加することが簡単であることがわかるでしょう。\n    実のところ、基本的な命名と束縛の機構はまったく同じです。\n\n    STLCの型には[Bool]が含まれます。\n    この型はブール値定数[true]と[false]、および結果がブール値になるより複雑な計算の型です。\n    それに加えて「関数型」(_arrow types_)があります。\n    これは関数の型です。\n<<\n      T ::= Bool\n          | T1 -> T2\n>>\n    例えば:\n\n      - [\\x:Bool. false] は型 [Bool->Bool] を持ちます。\n\n      - [\\x:Bool. x] は型 [Bool->Bool] を持ちます。\n\n      - [(\\x:Bool. x) true] は型 [Bool] を持ちます。\n\n      - [\\x:Bool. \\y:Bool. x] は型 [Bool->Bool->Bool]\n        (つまり [Bool -> (Bool->Bool)])を持ちます。\n\n      - [(\\x:Bool. \\y:Bool. x) false] は型 [Bool->Bool] を持ちます。\n\n      - [(\\x:Bool. \\y:Bool. x) false true] は型 [Bool] を持ちます。\n\n      - [\\f:Bool->Bool. f (f true)] は型 [(Bool->Bool) -> Bool] を持ちます。\n\n      - [(\\f:Bool->Bool. f (f true)) (\\x:Bool. false)] は型 [Bool] を持ちます。\n*)\n\n(* ###################################################################### *)\n(* ** Syntax *)\n(** ** 構文 *)\n\nModule STLC.\n\n(* ################################### *)\n(* *** Types *)\n(** *** 型 *)\n\nInductive ty : Type :=\n  | ty_Bool  : ty\n  | ty_arrow : ty -> ty -> ty.\n\n(* ################################### *)\n(* *** Terms *)\n(** *** 項 *)\n\nInductive tm : Type :=\n  | tm_var : id -> tm\n  | tm_app : tm -> tm -> tm\n  | tm_abs : id -> ty -> tm -> tm\n  | tm_true : tm\n  | tm_false : tm\n  | tm_if : tm -> tm -> tm -> tm.\n\n(* Something to note here is that an abstraction [\\x:T.t] (formally,\n    [tm_abs x T t]) is always annotated with the type ([T]) of its\n    parameter.  This is in contrast to Coq (and other functional\n    languages like ML, Haskell, etc.), which use _type inference_ to\n    fill in missing annotations. *)\n(** ここで注目すべきは、関数抽象 [\\x:T.t] (形式的には [tm_abs x T t])\n    には常にパラメータの型([T])が付記されることです。\n    これは Coq(あるいは他のML、Haskellといった関数型言語)と対照的です。\n    それらは、付記がないものを型推論で補完します。*)\n\nTactic Notation \"tm_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"tm_var\" | Case_aux c \"tm_app\"\n  | Case_aux c \"tm_abs\" | Case_aux c \"tm_true\"\n  | Case_aux c \"tm_false\" | Case_aux c \"tm_if\" ].\n\n(* Some examples... *)\n(** いくつかの例... *)\n\nNotation a := (Id 0).\nNotation b := (Id 1).\nNotation c := (Id 2).\n\n(** [idB = \\a:Bool. a] *)\n\nNotation idB :=\n  (tm_abs a ty_Bool (tm_var a)).\n\n(** [idBB = \\a:Bool->Bool. a] *)\n\nNotation idBB :=\n  (tm_abs a (ty_arrow ty_Bool ty_Bool) (tm_var a)).\n\n(** [idBBBB = \\a:(Bool->Bool)->(Bool->Bool). a] *)\n\nNotation idBBBB :=\n  (tm_abs a (ty_arrow (ty_arrow ty_Bool ty_Bool)\n                      (ty_arrow ty_Bool ty_Bool))\n    (tm_var a)).\n\n(** [k = \\a:Bool. \\b:Bool. a] *)\n\nNotation k := (tm_abs a ty_Bool (tm_abs b ty_Bool (tm_var a))).\n\n(* (We write these as [Notation]s rather than [Definition]s to make\n    things easier for [auto].) *)\n(** (これらを[Definition]ではなく[Notation]とすることで、\n    [auto]に扱いやすくしています。) *)\n\n(* ###################################################################### *)\n(* ** Operational Semantics *)\n(** ** 操作的意味論 *)\n\n(* To define the small-step semantics of STLC terms, we begin -- as\n    always -- by defining the set of values.  Next, we define the\n    critical notions of _free variables_ and _substitution_, which are\n    used in the reduction rule for application expressions.  And\n    finally we give the small-step relation itself. *)\n(** STLC項のスモールステップ意味論を定義するために、いつものように、\n    値の集合を定義することから始めます。\n    次に、自由変数(_free variables_)と置換(_substitution_)という、\n    重大な概念を定義します。これらは関数適用式の簡約規則に使われます。\n    そして最後に、スモールステップ関係自体を与えます。*)\n\n(* ################################### *)\n(* *** Values *)\n(** *** 値 *)\n\n(* To define the values of the STLC, we have a few cases to consider.\n\n    First, for the boolean part of the language, the situation is\n    clear: [true] and [false] are the only values.  (An [if]\n    expression is never a value.)\n\n    Second, an application is clearly not a value: It represents a\n    function being invoked on some argument, which clearly still has\n    work left to do.\n\n    Third, for abstractions, we have a choice:\n\n      - We can say that [\\a:A.t1] is a value only when [t1] is a\n        value -- i.e., only if the function's body has been\n        reduced (as much as it can be without knowing what argument it\n        is going to be applied to).\n\n      - Or we can say that [\\a:A.t1] is always a value, no matter\n        whether [t1] is one or not -- in other words, we can say that\n        reduction stops at abstractions.\n\n    Coq makes the first choice -- for example,\n[[\n         Eval simpl in (fun a:bool => 3 + 4)\n]]\n    yields [fun a:bool => 7].  But most real functional\n    programming languages make the second choice -- reduction of\n    a function's body only begins when the function is actually\n    applied to an argument.  We also make the second choice here.\n\n    Finally, having made the choice not to reduce under abstractions,\n    we don't need to worry about whether variables are values, since\n    we'll always be reducing programs \"from the outside in,\" and that\n    means the [step] relation will always be working with closed\n    terms (ones with no free variables).  *)\n(** STLCの値を定義するために、いくつかの場合を考えなければなりません。\n\n    最初に、言語のブール値については、状況は明確です:\n    [true]と[false]だけが値です。([if]式は決して値ではありません。)\n\n    二番目に、関数適用は明らかに値ではありません。\n    関数適用は関数が何らかの引数に対して呼ばれたことを表しているのですから、\n    明らかにこれからやることが残っています。\n\n    三番目に、関数抽象については選択肢があります:\n\n      - [\\a:A.t1] が値であるのは、[t1]が値であるときのみである、\n        とすることができます。\n        つまり、関数の本体が\n        (どのような引数に適用されるかわからない状態で可能な限り)\n        簡約済みであるときのみ、ということです。\n\n      - あるいは、[\\a:A.t1] は常に値である、とすることもできます。\n        [t1]が値であるかどうかに関係なく、です。\n        言いかえると、簡約は関数抽象で止まる、とすることです。\n\n    Coq は最初の選択肢を取っています。例えば、\n[[\n         Eval simpl in (fun a:bool => 3 + 4)\n]]\n    は [fun a:bool => 7] となります。\n    しかし実際の関数型プログラミング言語のほとんどは、\n    第二の選択肢を取っています。\n    つまり、関数の本体の簡約は、関数が実際に引数に適用されたときにのみ開始されます。\n    ここでは、同様に第二の選択肢を選びます。\n\n    最後に、関数抽象の中を簡約することを選択しなかったため、\n    変数が値であるかをどうかを心配する必要はなくなります。なぜなら、\n    プログラムの簡約は常に「外側から内側に」行われ、\n    [step]関係は常に閉じた(自由変数を持たない)項だけを対象とするからです。*)\n\nInductive value : tm -> Prop :=\n  | v_abs : forall x T t,\n      value (tm_abs x T t)\n  | t_true :\n      value tm_true\n  | t_false :\n      value tm_false.\n\nHint Constructors value.\n\n(* ###################################################################### *)\n(* *** Free Variables and Substitution *)\n(** *** 自由変数と置換 *)\n\n(* Now we come to the heart of the matter: the operation of\n    substituting one term for a variable in another term.\n\n    This operation will be used below to define the operational\n    semantics of function application, where we will need to\n    substitute the argument term for the function parameter in the\n    function's body.  For example, we reduce\n[[\n       (\\x:Bool. if x then true else x) false\n]]\n    to [false] by substituting [false] for the parameter [x] in the\n    body of the function.  In general, we need to be able to\n    substitute some given term [s] for occurrences of some variable\n    [x] in another term [t].  In informal discussions, this is usually\n    written [ [s/x]t ] and pronounced \"substitute [s] for [x] in [t].\"\n\n    Here are some examples:\n\n      - [[true / a] (if a then a else false)] yields [if true then true else false]\n\n      - [[true / a] a] yields [true]\n\n      - [[true / a] (if a then a else b)] yields [if true then true else b]\n\n      - [[true / a] b] yields [b]\n\n      - [[true / a] false] yields [false] (vacuous substitution)\n\n      - [[true / a] (\\y:Bool. if y then a else false)] yields [\\y:Bool. if y then true else false]\n      - [[true / a] (\\y:Bool. a)] yields [\\y:Bool. true]\n\n      - [[true / a] (\\y:Bool. y)] yields [\\y:Bool. y]\n\n      - [[true / a] (\\a:Bool. a)] yields [\\a:Bool. a]\n\n    The last example is very important: substituting [true] for [a] in\n    [\\a:Bool. a] does _not_ yield [\\a:Bool. true]!  The reason for\n    this is that the [a] in the body of [\\a:Bool. a] is _bound_ by the\n    abstraction: it is a new, local name that just happens to be\n    spelled the same as some global name [a].\n\n    Here is the definition, informally...\n[[\n      [s/x]x = s\n      [s/x]y = y                                     if x <> y\n      [s/x](\\x:T11.t12)   = \\x:T11. t12\n      [s/x](\\y:T11.t12)   = \\y:T11. [s/x]t12         if x <> y\n      [s/x](t1 t2)        = ([s/x]t1) ([s/x]t2)\n      [s/x]true           = true\n      [s/x]false          = false\n      [s/x](if t1 then t2 else t3) =\n                          if [s/x]t1 then [s/x]t2 else [s/x]t3\n]]\n    ... and formally: *)\n(** これから問題の核心に入ります: 項の変数を別の項で置換する操作です。\n\n    この操作は後で関数適用の操作的意味論を定義するために使います。\n    関数適用では、関数本体の中の関数パラメータを引数項で置換することが必要になります。\n    例えば、\n[[\n       (\\x:Bool. if x then true else x) false\n]]\n    は、関数の本体のパラメータ[x]を[false]で置換することで、[false]に簡約されます。\n    一般に、ある項[t]の変数[x]の出現を、与えらえた項[s]で置換できることが必要です。\n    非形式的な議論では、これは通常 [ [s/x]t ] と書き、「[t]の[x]を[s]で置換する」と読みます。\n\n    いくつかの例を示します:\n\n      - [[true / a] (if a then a else false)] は [if true then true else false]\n        となります。\n\n      - [[true / a] a] は [true] となります。\n\n      - [[true / a] (if a then a else b)] は [if true then true else b]\n        となります。\n\n      - [[true / a] b] は [b] となります。\n\n      - [[true / a] false] は [false] となります(何もしない置換です)。\n\n      - [[true / a] (\\y:Bool. if y then a else false)] は\n        [\\y:Bool. if y then true else false] となります。\n\n      - [[true / a] (\\y:Bool. a)] は [\\y:Bool. true] となります。\n\n      - [[true / a] (\\y:Bool. y)] は [\\y:Bool. y] となります。\n\n      - [[true / a] (\\a:Bool. a)] は [\\a:Bool. a] となります。\n\n    最後の例はとても重要です。[\\a:Bool. a] の [a] を [true] で置換したものは、\n    [\\a:Bool. true] に「なりません」! 理由は、[\\a:Bool. a] の本体の [a]\n    は関数抽象で束縛されている(_bound_)からです。\n    この[a]は新しいローカルな名前で、たまたまグローバルな名前[a]と同じ綴りであったものです。\n\n    以下が、非形式的な定義です...\n[[\n      [s/x]x = s\n      [s/x]y = y                                     if x <> y\n      [s/x](\\x:T11.t12)   = \\x:T11. t12\n      [s/x](\\y:T11.t12)   = \\y:T11. [s/x]t12         if x <> y\n      [s/x](t1 t2)        = ([s/x]t1) ([s/x]t2)\n      [s/x]true           = true\n      [s/x]false          = false\n      [s/x](if t1 then t2 else t3) =\n                          if [s/x]t1 then [s/x]t2 else [s/x]t3\n]]\n    ... そして形式的には: *)\n\nFixpoint subst (s:tm) (x:id) (t:tm) : tm :=\n  match t with\n  | tm_var x' => if beq_id x x' then s else t\n  | tm_abs x' T t1 => tm_abs x' T (if beq_id x x' then t1 else (subst s x t1))\n  | tm_app t1 t2 => tm_app (subst s x t1) (subst s x t2)\n  | tm_true => tm_true\n  | tm_false => tm_false\n  | tm_if t1 t2 t3 => tm_if (subst s x t1) (subst s x t2) (subst s x t3)\n  end.\n\n(* Technical note: Substitution becomes trickier to define if we\n    consider the case where [s], the term being substituted for a\n    variable in some other term, may itself contain free variables.\n    Since we are only interested in defining the [step] relation on\n    closed terms here, we can avoid this extra complexity. *)\n(** 技術的注釈: 置換は、もし[s]、つまり他の項の変数を置換する項が、\n    それ自身に自由変数を含むときを考えると、\n    定義がよりトリッキーなものになります。\n    ここで興味があるのは閉じた項についての[step]関係の定義のみなので、\n    そのさらなる複雑さは避けることができます。*)\n\n(* ################################### *)\n(* *** Reduction *)\n(** *** 簡約 *)\n\n(* The small-step reduction relation for STLC follows the same\n    pattern as the ones we have seen before.  Intuitively, to\n    reduce a function application, we first reduce its left-hand\n    side until it becomes a literal function; then we reduce its\n    right-hand side (the argument) until it is also a value; and\n    finally we substitute the argument for the bound variable in\n    the body of the function.  This last rule, written informally\n    as\n[[\n      (\\a:T.t12) v2 ==> [v2/a]t12\n]]\n    is traditionally called \"beta-reduction\".\n\n    Informally:\n[[[\n                     ---------------------------                    (ST_AppAbs)\n                     (\\a:T.t12) v2 ==> [v2/a]t12\n\n                              t1 ==> t1'\n                           ----------------                           (ST_App1)\n                           t1 t2 ==> t1' t2\n\n                              t2 ==> t2'\n                           ----------------                        (ST_App2)\n                           v1 t2 ==> v1 t2'\n]]]\n   (plus the usual rules for booleans).\n\n   Formally:\n*)\n(** STLCのスモールステップ簡約関係は、これまで見てきたものと同じパターンに従います。\n    直観的には、関数適用を簡約するため、最初に左側をリテラル関数になるまで簡約します。\n    次に左側(引数)を値になるまで簡約します。そして最後に関数の本体の束縛変数を引数で置換します。\n    この最後の規則は、非形式的には次のように書きます:\n[[\n      (\\a:T.t12) v2 ==> [v2/a]t12\n]]\n    これは伝統的にベータ簡約(\"beta-reduction\")と呼ばれます。\n\n    非形式的に:\n[[\n                     ---------------------------                    (ST_AppAbs)\n                     (\\a:T.t12) v2 ==> [v2/a]t12\n\n                              t1 ==> t1'\n                           ----------------                           (ST_App1)\n                           t1 t2 ==> t1' t2\n\n                              t2 ==> t2'\n                           ----------------                        (ST_App2)\n                           v1 t2 ==> v1 t2'\n]]\n   (これに通常のブール値の規則をプラスします)。\n\n   形式的には:\n*)\n\nReserved Notation \"t1 '==>' t2\" (at level 40).\n\nInductive step : tm -> tm -> Prop :=\n  | ST_AppAbs : forall x T t12 v2,\n         value v2 ->\n         (tm_app (tm_abs x T t12) v2) ==> (subst v2 x t12)\n  | ST_App1 : forall t1 t1' t2,\n         t1 ==> t1' ->\n         tm_app t1 t2 ==> tm_app t1' t2\n  | ST_App2 : forall v1 t2 t2',\n         value v1 ->\n         t2 ==> t2' ->\n         tm_app v1 t2 ==> tm_app v1  t2'\n  | ST_IfTrue : forall t1 t2,\n      (tm_if tm_true t1 t2) ==> t1\n  | ST_IfFalse : forall t1 t2,\n      (tm_if tm_false t1 t2) ==> t2\n  | ST_If : forall t1 t1' t2 t3,\n      t1 ==> t1' ->\n      (tm_if t1 t2 t3) ==> (tm_if t1' t2 t3)\n\nwhere \"t1 '==>' t2\" := (step t1 t2).\n\nTactic Notation \"step_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"ST_AppAbs\" | Case_aux c \"ST_App1\"\n  | Case_aux c \"ST_App2\" | Case_aux c \"ST_IfTrue\"\n  | Case_aux c \"ST_IfFalse\" | Case_aux c \"ST_If\" ].\n\nNotation stepmany := (refl_step_closure step).\nNotation \"t1 '==>*' t2\" := (stepmany t1 t2) (at level 40).\n\nHint Constructors step.\n\n(* ##################################### *)\n(* *** Examples *)\n(** *** 例 *)\n\nLemma step_example1 :\n  (tm_app idBB idB) ==>* idB.\nProof.\n  eapply rsc_step.\n    apply ST_AppAbs.\n    apply v_abs.\n  simpl.\n  apply rsc_refl.  Qed.\n\n(* A more automatic proof *)\nLemma step_example1' :\n  (tm_app idBB idB) ==>* idB.\nProof. normalize.  Qed.\n\nLemma step_example2 :\n  (tm_app idBB (tm_app idBB idB)) ==>* idB.\nProof.\n  eapply rsc_step.\n    apply ST_App2. auto.\n    apply ST_AppAbs. auto.\n  eapply rsc_step.\n    apply ST_AppAbs. simpl. auto.\n  simpl. apply rsc_refl.  Qed.\n\n(* Again, we can use the [normalize] tactic from above to simplify\n    the proof. *)\n(** 再び、上述の[normalize]タクティックを使って、証明を簡単にすることができます。*)\n\nLemma step_example2' :\n  (tm_app idBB (tm_app idBB idB)) ==>* idB.\nProof.\n  normalize.\nQed.\n\n(* **** Exercise: 2 stars (step_example3) *)\n(** **** 練習問題: ★★ (step_example3) *)\n(* Try to do this one both with and without [normalize]. *)\n(** 次の証明を[normalize]を使う方法と使わない方法の両方で行ないなさい。*)\n\nLemma step_example3 :\n       (tm_app (tm_app idBBBB idBB) idB)\n  ==>* idB.\nProof.\n  eapply rsc_step.\n    apply ST_App1. apply ST_AppAbs. auto.\n    simpl.\n  eapply rsc_step.\n    apply ST_AppAbs. auto.\n    simpl.\n  apply rsc_refl.\nQed.\n\nLemma step_example3' :\n       (tm_app (tm_app idBBBB idBB) idB)\n  ==>* idB.\nProof.\n  normalize.\nQed.\n\n(** [] *)\n\n(* ###################################################################### *)\n(* ** Typing *)\n(** ** 型付け *)\n\n(* ################################### *)\n(* *** Contexts *)\n(** *** コンテキスト *)\n\n(* Question: What is the type of the term \"[x y]\"?\n\n    Answer: It depends on the types of [x] and [y]!\n\n    I.e., in order to assign a type to a term, we need to know\n    what assumptions we should make about the types of its free\n    variables.\n\n    This leads us to a three-place \"typing judgment\", informally\n    written [Gamma |- t : T], where [Gamma] is a \"typing context\"\n    -- a mapping from variables to their types.\n\n    We hide the definition of partial maps in a module since it is\n    actually defined in SfLib. *)\n(** 問い: 項 \"[x y]\" の型は何でしょう？\n\n    答え: それは [x] と [y] の型に依存します!\n\n    つまり、項に型を付けるためには、\n    その自由変数の型についてどういう仮定をしなければならないかを知る必要があります。\n\n    このために、3つのものの間の型付けジャッジメント(\"typing judgment\")を用意します。\n    これを非形式的には [Gamma |- t : T] と記述します。ここで\n    [Gamma] は「型付けコンテキスト」(\"typing context\")、つまり、\n    変数から型への写像です。\n\n    モジュールにおける部分写像の定義は隠蔽します。\n    なぜなら、実際には SfLib で定義されているからです。*)\n\nDefinition context := partial_map ty.\n\nModule Context.\n\nDefinition partial_map (A:Type) := id -> option A.\n\nDefinition empty {A:Type} : partial_map A := (fun _ => None).\n\nDefinition extend {A:Type} (Gamma : partial_map A) (x:id) (T : A) :=\n  fun x' => if beq_id x x' then Some T else Gamma x'.\n\nLemma extend_eq : forall A (ctxt: partial_map A) x T,\n  (extend ctxt x T) x = Some T.\nProof.\n  intros. unfold extend. rewrite <- beq_id_refl. auto.\nQed.\n\nLemma extend_neq : forall A (ctxt: partial_map A) x1 T x2,\n  beq_id x2 x1 = false ->\n  (extend ctxt x2 T) x1 = ctxt x1.\nProof.\n  intros. unfold extend. rewrite H. auto.\nQed.\n\nEnd Context.\n\n(* ################################### *)\n(* *** Typing Relation *)\n(** *** 型付け関係 *)\n\n(* Informally:\n[[[\n                             Gamma x = T\n                            --------------                              (T_Var)\n                            Gamma |- x : T\n\n                      Gamma , x:T11 |- t12 : T12\n                     ----------------------------                       (T_Abs)\n                     Gamma |- \\x:T11.t12 : T11->T12\n\n                        Gamma |- t1 : T11->T12\n                          Gamma |- t2 : T11\n                        ----------------------                          (T_App)\n                         Gamma |- t1 t2 : T12\n\n                         --------------------                          (T_True)\n                         Gamma |- true : Bool\n\n                        ---------------------                         (T_False)\n                        Gamma |- false : Bool\n\n       Gamma |- t1 : Bool    Gamma |- t2 : T    Gamma |- t3 : T\n       --------------------------------------------------------          (T_If)\n                  Gamma |- if t1 then t2 else t3 : T\n]]]\nThe notation [ Gamma , x:T ] means \"extend the partial function [Gamma]\nto also map [x] to [T].\"\n*)\n(** 非形式的に:\n[[\n                             Gamma x = T\n                            --------------                              (T_Var)\n                            Gamma |- x : T\n\n                      Gamma , x:T11 |- t12 : T12\n                     ----------------------------                       (T_Abs)\n                     Gamma |- \\x:T11.t12 : T11->T12\n\n                        Gamma |- t1 : T11->T12\n                          Gamma |- t2 : T11\n                        ----------------------                          (T_App)\n                         Gamma |- t1 t2 : T12\n\n                         --------------------                          (T_True)\n                         Gamma |- true : Bool\n\n                        ---------------------                         (T_False)\n                        Gamma |- false : Bool\n\n       Gamma |- t1 : Bool    Gamma |- t2 : T    Gamma |- t3 : T\n       --------------------------------------------------------          (T_If)\n                  Gamma |- if t1 then t2 else t3 : T\n]]\n記法 [ Gamma , x:T ] は「部分写像[Gamma]を拡張して[x]を[T]に写像するようにしたもの」を表します。\n*)\n\nInductive has_type : context -> tm -> ty -> Prop :=\n  | T_Var : forall Gamma x T,\n      Gamma x = Some T ->\n      has_type Gamma (tm_var x) T\n  | T_Abs : forall Gamma x T11 T12 t12,\n      has_type (extend Gamma x T11) t12 T12 ->\n      has_type Gamma (tm_abs x T11 t12) (ty_arrow T11 T12)\n  | T_App : forall T11 T12 Gamma t1 t2,\n      has_type Gamma t1 (ty_arrow T11 T12) ->\n      has_type Gamma t2 T11 ->\n      has_type Gamma (tm_app t1 t2) T12\n  | T_True : forall Gamma,\n       has_type Gamma tm_true ty_Bool\n  | T_False : forall Gamma,\n       has_type Gamma tm_false ty_Bool\n  | T_If : forall t1 t2 t3 T Gamma,\n       has_type Gamma t1 ty_Bool ->\n       has_type Gamma t2 T ->\n       has_type Gamma t3 T ->\n       has_type Gamma (tm_if t1 t2 t3) T.\n\nTactic Notation \"has_type_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"T_Var\" | Case_aux c \"T_Abs\"\n  | Case_aux c \"T_App\" | Case_aux c \"T_True\"\n  | Case_aux c \"T_False\" | Case_aux c \"T_If\" ].\n\nHint Constructors has_type.\n\n(* ################################### *)\n(* *** Examples *)\n(** *** 例 *)\n\nExample typing_example_1 :\n  has_type empty (tm_abs a ty_Bool (tm_var a)) (ty_arrow ty_Bool ty_Bool).\nProof.\n  apply T_Abs. apply T_Var. reflexivity.  Qed.\n\n(* Note that since we added the has_type constructors to the\n    hints database, auto can actually solve this one immediately.\n    *)\n(** has_typeコンストラクタをヒントデータベースに追加したことから、\n    これを auto は直接解くことができることに注意します。*)\n\nExample typing_example_1' :\n  has_type empty (tm_abs a ty_Bool (tm_var a)) (ty_arrow ty_Bool ty_Bool).\nProof. auto.  Qed.\n\nHint Unfold beq_id beq_nat extend.\n\n(* Written informally, the next one is:\n[[\n     empty |- \\a:A. \\b:A->A. b (b a))\n           : A -> (A->A) -> A.\n]]\n*)\n(** 非形式的に書くと\n[[\n     empty |- \\a:A. \\b:A->A. b (b a))\n           : A -> (A->A) -> A.\n]]\nとなるものが次の例です:\n*)\n\nExample typing_example_2 :\n  has_type empty\n    (tm_abs a ty_Bool\n       (tm_abs b (ty_arrow ty_Bool ty_Bool)\n          (tm_app (tm_var b) (tm_app (tm_var b) (tm_var a)))))\n    (ty_arrow ty_Bool (ty_arrow (ty_arrow ty_Bool ty_Bool) ty_Bool)).\nProof with auto using extend_eq.\n  apply T_Abs.\n  apply T_Abs.\n  eapply T_App. apply T_Var...\n  eapply T_App. apply T_Var...\n  apply T_Var...\nQed.\n\n(* **** Exercise: 2 stars, optional *)\n(** **** 練習問題: ★★, optional *)\n(* Prove the same result without using [auto], [eauto], or\n    [eapply]. *)\n(** [auto]、[eauto]、[eapply] を使わずに同じ結果を証明しなさい。*)\n\nExample typing_example_2_full :\n  has_type empty\n    (tm_abs a ty_Bool\n       (tm_abs b (ty_arrow ty_Bool ty_Bool)\n          (tm_app (tm_var b) (tm_app (tm_var b) (tm_var a)))))\n    (ty_arrow ty_Bool (ty_arrow (ty_arrow ty_Bool ty_Bool) ty_Bool)).\nProof.\n  apply T_Abs.\n  apply T_Abs.\n  apply T_App with (T11 := ty_Bool).\n  - apply T_Var. apply extend_eq.\n  - apply T_App with (T11 := ty_Bool).\n    + apply T_Var. apply extend_eq.\n    + apply T_Var. rewrite extend_neq.\n      * apply extend_eq.\n      * auto.\nQed.\n\n(** [] *)\n\n(* **** Exercise: 2 stars (typing_example_3) *)\n(** **** 練習問題: ★★ (typing_example_3) *)\n(* Formally prove the following typing derivation holds:\n[[\n   empty |- (\\a:Bool->B. \\b:Bool->Bool. \\c:Bool.\n               b (a c))\n         : T.\n]]\n*)\n(** 次の型付けが成立することを形式的に証明しなさい:\n[[\n   empty |- (\\a:Bool->B. \\b:Bool->Bool. \\c:Bool.\n               b (a c))\n         : T.\n]]\n*)\n\nExample typing_example_3 :\n  exists T,\n    has_type empty\n      (tm_abs a (ty_arrow ty_Bool ty_Bool)\n         (tm_abs b (ty_arrow ty_Bool ty_Bool)\n            (tm_abs c ty_Bool\n               (tm_app (tm_var b) (tm_app (tm_var a) (tm_var c))))))\n      T.\n\nProof with auto.\n  exists\n    (ty_arrow\n       (ty_arrow ty_Bool ty_Bool)\n       (ty_arrow\n          (ty_arrow ty_Bool ty_Bool)\n          (ty_arrow ty_Bool ty_Bool))).\n\n  apply T_Abs. apply T_Abs. apply T_Abs.\n  eapply T_App.\n  - apply T_Var. rewrite extend_neq...\n    + apply extend_eq.\n    (* + auto. *)\n  - eapply T_App.\n    + apply T_Var. rewrite extend_neq...\n      * rewrite extend_neq...\n        { apply extend_eq. }\n        (* { auto. } *)\n      (* * auto. *)\n    + eapply T_Var...\nQed.\n\n(** [] *)\n\n(* We can also show that terms are _not_ typable.  For example, let's\n    formally check that there is no typing derivation assigning a type\n    to the term [\\a:Bool. \\b:Bool, a b] -- i.e.,\n[[\n    ~ exists T,\n        empty |- (\\a:Bool. \\b:Bool, a b) : T.\n]]\n*)\n(** 項が「型付けできない」ことを証明することもできます。\n    例えば [\\a:Bool. \\b:Bool, a b] に型をつける型付けが存在しないこと、\n    つまり、\n[[\n    ~ exists T,\n        empty |- (\\a:Bool. \\b:Bool, a b) : T.\n]]\n    を形式的にチェックしましょう。\n*)\nExample typing_nonexample_1 :\n  ~ exists T,\n      has_type empty\n        (tm_abs a ty_Bool\n            (tm_abs b ty_Bool\n               (tm_app (tm_var a) (tm_var b))))\n        T.\nProof.\n  intros C. destruct C.\n  (* The [clear] tactic is useful here for tidying away bits of\n     the context that we're not going to need again. *)\n  inversion H. subst. clear H.\n  inversion H5. subst. clear H5.\n  inversion H4. subst. clear H4.\n  inversion H2. subst. clear H2.\n  inversion H5. subst. clear H5.\n  (* rewrite extend_neq in H1. rewrite extend_eq in H1. *)\n  inversion H1.  Qed.\n\n(* **** Exercise: 3 stars (typing_nonexample_3) *)\n(** **** 練習問題: ★★★ (typing_nonexample_3) *)\n(* Another nonexample:\n[[\n    ~ (exists S, exists T,\n          empty |- (\\a:S. a a) : T).\n]]\n*)\n(** 別の型を持たない例:\n[[\n    ~ (exists S, exists T,\n          empty |- (\\a:S. a a) : T).\n]]\n*)\n\nExample typing_nonexample_3 :\n  ~ (exists S, exists T,\n        has_type empty\n          (tm_abs a S\n             (tm_app (tm_var a) (tm_var a)))\n          T).\nProof.\n  intro P. destruct P as [ wS Q ]. destruct Q as [ wT R ].\n  inversion R; subst; clear R.\n  inversion H4; subst; clear H4.\n  inversion H5; subst; clear H5.\n  inversion H2; subst; clear H2.\n  inversion H1; subst; clear H1.\n  inversion H3. clear H3.\n  induction T11 as [ | T111 IHT11 T112 IHT12 ].\n  - solve by inversion.\n  - inversion H0. rewrite H2 in H1. apply IHT11. assumption.\nQed.\n\n(** [] *)\n\n(* **** Exercise: 1 star (typing_statements) *)\n(** **** 練習問題: ★ (typing_statements) *)\n\n(* Which of the following propositions are provable?\n       - [b:Bool |- \\a:Bool.a : Bool->Bool]\n\n       - [exists T,  empty |- (\\b:Bool->Bool. \\a:Bool. b a) : T]\n\n       - [exists T,  empty |- (\\b:Bool->Bool. \\a:Bool. a b) : T]\n\n       - [exists S, a:S |- (\\b:Bool->Bool. b) a : S]\n\n       - [exists S, exists T,  a:S |- (a a a) : T]\n\n[]\n*)\n(** 以下のうち証明できるのものを挙げなさい。\n       - [b:Bool |- \\a:Bool.a : Bool->Bool]\n\n       - [exists T,  empty |- (\\b:Bool->Bool. \\a:Bool. b a) : T]\n\n       - [exists T,  empty |- (\\b:Bool->Bool. \\a:Bool. a b) : T]\n\n       - [exists S, a:S |- (\\b:Bool->Bool. b) a : S]\n\n       - [exists S, exists T,  a:S |- (a a a) : T]\n\n[]\n*)\n\n(*\n       - [b:Bool |- \\a:Bool.a : Bool->Bool]\n       できる\n\n       - [exists T,  empty |- (\\b:Bool->Bool. \\a:Bool. b a) : T]\n       できる\n\n       - [exists T,  empty |- (\\b:Bool->Bool. \\a:Bool. a b) : T]\n       できない\n\n       - [exists S, a:S |- (\\b:Bool->Bool. b) a : S]\n       できる\n\n       - [exists S, exists T,  a:S |- (a a a) : T]\n       できない\n\n       a : S -> S -> T === S\n *)\n\nExample typing_statements_4 :\n  exists S, has_type (extend empty a S)\n                 (tm_app\n                    (tm_abs b (ty_arrow ty_Bool ty_Bool) (tm_var b))\n                    (tm_var a))\n                 S.\nProof.\n  exists (ty_arrow ty_Bool ty_Bool).\n  apply T_App with (T11 := ty_arrow ty_Bool ty_Bool).\n  apply T_Abs.\n  apply T_Var.\n  apply extend_eq.\n  apply T_Var.\n  apply extend_eq.\nQed.\n\n(* **** Exercise: 1 star, optional (more_typing_statements) *)\n(** **** 練習問題: ★, optional (more_typing_statements) *)\n\n(* Which of the following propositions are provable?  For the\n    ones that are, give witnesses for the existentially bound\n    variables.\n       - [exists T,  empty |- (\\b:B->B->B. \\a:B, b a) : T]\n\n       - [exists T,  empty |- (\\a:A->B, \\b:B-->C, \\c:A, b (a c)):T]\n\n       - [exists S, exists U, exists T,  a:S, b:U |- \\c:A. a (b c) : T]\n\n       - [exists S, exists T,  a:S |- \\b:A. a (a b) : T]\n\n       - [exists S, exists U, exists T,  a:S |- a (\\c:U. c a) : T]\n\n[]\n*)\n(** 以下の命題のうち証明できるものを挙げなさい。証明できるものについては、\n    存在限量された変数に入る具体的な値を示しなさい。\n       - [exists T,  empty |- (\\b:B->B->B. \\a:B, b a) : T]\n\n       - [exists T,  empty |- (\\a:A->B, \\b:B-->C, \\c:A, b (a c)):T]\n\n       - [exists S, exists U, exists T,  a:S, b:U |- \\c:A. a (b c) : T]\n\n       - [exists S, exists T,  a:S |- \\b:A. a (a b) : T]\n\n       - [exists S, exists U, exists T,  a:S |- a (\\c:U. c a) : T]\n\n[]\n*)\n\n(*\n       - [exists T,  empty |- (\\b:B->B->B. \\a:B, b a) : T]\n         できる\n         T = (B -> B -> B) -> B -> B -> B\n\n       - [exists T,  empty |- (\\a:A->B, \\b:B-->C, \\c:A, b (a c)):T]\n         できる\n         T = (A -> B) -> (B -> C) -> A -> C\n\n       - [exists S, exists U, exists T,  a:S, b:U |- \\c:A. a (b c) : T]\n         できる\n         forall (A B C : ty),\n         U = A -> B\n         S = B -> C\n         T = A -> C\n\n         c: A\n         b: A -> B\n         a: B -> C\n\n       - [exists S, exists T,  a:S |- \\b:A. a (a b) : T]\n         できる\n         forall (A : ty),\n         S = A -> A\n         T = A -> A\n\n         a: A -> A\n         b: A\n\n       - [exists S, exists U, exists T,  a:S |- a (\\c:U. c a) : T]\n         できない\n         forall (A : ty),\n         c : S -> A\n         (\\c:U. c a) : (S -> A) -> A\n         a : ((S -> A) -> A) -> T === S\n\n *)\n\n(* ###################################################################### *)\n(* ** Properties *)\n(** ** 性質 *)\n\n(* ###################################################################### *)\n(* *** Free Occurrences *)\n(** *** 自由な出現 *)\n\n(* A variable [x] _appears free in_ a term _t_ if [t] contains some\n    occurrence of [x] that is not under an abstraction labeled [x].  For example:\n      - [y] appears free, but [x] does not, in [\\x:T->U. x y]\n      - both [x] and [y] appear free in [(\\x:T->U. x y) x]\n      - no variables appear free in [\\x:T->U. \\y:T. x y]  *)\n(** 変数[x]が項 t に自由に出現する(_appears free in_ a term _t_)とは、\n    [t]が[x]の出現を含み、その出現が[x]のラベルが付けられた関数抽象のスコープ内にないことです。\n    例えば:\n      - [\\x:T->U. x y] において[y]は自由に現れますが[x]はそうではありません。\n      - [(\\x:T->U. x y) x] においては[x]と[y]はともに自由に現れます。\n      - [\\x:T->U. \\y:T. x y] においては自由に現れる変数はありません。*)\n\nInductive appears_free_in : id -> tm -> Prop :=\n  | afi_var : forall x,\n      appears_free_in x (tm_var x)\n  | afi_app1 : forall x t1 t2,\n      appears_free_in x t1 -> appears_free_in x (tm_app t1 t2)\n  | afi_app2 : forall x t1 t2,\n      appears_free_in x t2 -> appears_free_in x (tm_app t1 t2)\n  | afi_abs : forall x y T11 t12,\n      y <> x  ->\n      appears_free_in x t12 ->\n      appears_free_in x (tm_abs y T11 t12)\n  | afi_if1 : forall x t1 t2 t3,\n      appears_free_in x t1 ->\n      appears_free_in x (tm_if t1 t2 t3)\n  | afi_if2 : forall x t1 t2 t3,\n      appears_free_in x t2 ->\n      appears_free_in x (tm_if t1 t2 t3)\n  | afi_if3 : forall x t1 t2 t3,\n      appears_free_in x t3 ->\n      appears_free_in x (tm_if t1 t2 t3).\n\nTactic Notation \"afi_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"afi_var\"\n  | Case_aux c \"afi_app1\" | Case_aux c \"afi_app2\"\n  | Case_aux c \"afi_abs\"\n  | Case_aux c \"afi_if1\" | Case_aux c \"afi_if2\"\n  | Case_aux c \"afi_if3\" ].\n\nHint Constructors appears_free_in.\n\n(* A term in which no variables appear free is said to be _closed_. *)\n(** 自由に現れる変数を持たない項を「閉じている」(_closed_)と言います。 *)\n\nDefinition closed (t:tm) :=\n  forall x, ~ appears_free_in x t.\n\n(* ###################################################################### *)\n(* *** Substitution *)\n(** *** 置換 *)\n\n(* We first need a technical lemma connecting free variables and\n    typing contexts.  If a variable [x] appears free in a term [t],\n    and if we know [t] is well typed in context [Gamma], then it must\n    be the case that [Gamma] assigns a type to [x]. *)\n(** 最初に、自由変数と型付けコンテキストを結び付ける技術的な補題が必要になります。\n    変数[x]が項[t]に自由に現れ、[t]がコンテキスト[Gamma]で型付けされるならば、\n    [Gamma]は[x]に型を付けなければなりません。*)\n\nLemma free_in_context : forall x t T Gamma,\n   appears_free_in x t ->\n   has_type Gamma t T ->\n   exists T', Gamma x = Some T'.\n\n(* _Proof_: We show, by induction on the proof that [x] appears free\n      in [t], that, for all contexts [Gamma], if [t] is well typed\n      under [Gamma], then [Gamma] assigns some type to [x].\n\n      - If the last rule used was [afi_var], then [t = x], and from\n        the assumption that [t] is well typed under [Gamma] we have\n        immediately that [Gamma] assigns a type to [x].\n\n      - If the last rule used was [afi_app1], then [t = t1 t2] and [x]\n        appears free in [t1].  Since [t] is well typed under [Gamma],\n        we can see from the typing rules that [t1] must also be, and\n        the IH then tells us that [Gamma] assigns [x] a type.\n\n      - Almost all the other cases are similar: [x] appears free in a\n        subterm of [t], and since [t] is well typed under [Gamma], we\n        know the subterm of [t] in which [x] appears is well typed\n        under [Gamma] as well, and the IH gives us exactly the\n        conclusion we want.\n\n      - The only remaining case is [afi_abs].  In this case [t =\n        \\y:T11.t12], and [x] appears free in [t12]; we also know that\n        [x] is different from [y].  The difference from the previous\n        cases is that whereas [t] is well typed under [Gamma], its\n        body [t12] is well typed under [(Gamma, y:T11)], so the IH\n        allows us to conclude that [x] is assigned some type by the\n        extended context [(Gamma, y:T11)].  To conclude that [Gamma]\n        assigns a type to [x], we appeal to lemma [extend_neq], noting\n        that [x] and [y] are different variables. *)\n(** 「証明」: [x]が[t]に自由に現れることの証明についての帰納法によって、\n      すべてのコンテキスト[Gamma]について、\n      [t]が[Gamma]のもとで型付けされるならば[Gamma]は[x]に型をつけることを示す。\n\n      - 最後の規則が [afi_var] の場合、[t = x] である。そして、[t]が[Gamma]\n        で型付けされるという仮定から、そのまま、[Gamma]で[x]に型付けされることが言える。\n\n      - 最後の規則が [afi_app1] の場合、[t = t1 t2] で[x]は[t1]に自由に出現する。\n        [t]が[Gamma]のもとで型付けされることから、型付け規則から[t1]も型付けされることになる。\n        従って帰納仮定より[Gamma]は[x]に型を付ける。\n\n      - 他のほとんどの場合も同様である。[x]が[t]の部分項に自由に現れ、\n        [t]が[Gamma]で片付けされることから、[x]が出現している[t]の部分項は同様に[Gamma]\n        で型付けされる。従って帰納仮定より求めるべき結果が得られる。\n\n      - 残るのは、最後の規則が [afi_abs] の場合だけである。この場合、\n        [t = \\y:T11.t12] で[x]は[t12]に自由に現れる。\n        また[x]は[y]と異なっている。前の場合との違いは、\n        [t]は[Gamma]のもとで型付けされているが、\n        その本体[t12]は [(Gamma, y:T11)] のもとで型付けされているという点である。\n        このため、帰納仮定は、拡張されたコンテキスト [(Gamma, y:T11)] で[x]\n        に型付けされる、という主張になる。\n        [Gamma]のもとで[x]に型が付けられるという結論を得るため、\n        [x]と[y]が異なっているという点に注意して、補題[extend_neq]を使う。*)\n\nProof.\n  intros. generalize dependent Gamma. generalize dependent T.\n  afi_cases (induction H) Case;\n         intros; try solve [inversion H0; eauto].\n  Case \"afi_abs\".\n    inversion H1; subst.\n    apply IHappears_free_in in H7.\n    apply not_eq_beq_id_false in H.\n    rewrite extend_neq in H7; assumption.\nQed.\n\n(* Next, we'll need the fact that any term [t] which is well typed in\n    the empty context is closed -- that is, it has no free variables. *)\n(** 次に、空コンテキストで型付けされる任意の項は閉じている(自由変数を持たない)、\n    という事実を必要とします。*)\n\n(* **** Exercise: 2 stars (typable_empty__closed) *)\n(** **** 練習問題: ★★ (typable_empty__closed) *)\nCorollary typable_empty__closed : forall t T,\n    has_type empty t T  ->\n    closed t.\nProof.\n  intros.\n  intros x AP.\n\n  destruct (free_in_context x t T empty AP H)\n           as [ T' Contra ].\n  (* unfold empty in Contra. *)\n  solve by inversion.\nQed.\n\n(** [] *)\n\n(* Sometimes, when we have a proof [Gamma |- t : T], we will need to\n    replace [Gamma] by a different context [Gamma'].  When is it safe\n    to do this?  Intuitively, it must at least be the case that\n    [Gamma'] assigns the same types as [Gamma] to all the variables\n    that appear free in [t]. In fact, this is the only condition that\n    is needed. *)\n(** しばしば、証明 [Gamma |- t : T] があるとき、コンテキスト[Gamma]\n    を別のコンテキスト[Gamma']に置換する必要が出てきます。\n    これはどのような場合に安全でしょうか？\n    直観的には、[t]に自由に現れるすべての変数について、[Gamma']が\n    [Gamma]と同じ型を割当てることが少なくとも必要です。\n    実際、この条件だけが必要になります。*)\n\nLemma context_invariance : forall Gamma Gamma' t S,\n     has_type Gamma t S  ->\n     (forall x, appears_free_in x t -> Gamma x = Gamma' x) ->\n     has_type Gamma' t S.\n\n(* _Proof_: By induction on a derivation of [Gamma |- t : T].\n\n      - If the last rule in the derivation was [T_Var], then [t = x]\n        and [Gamma x = T].  By assumption, [Gamma' x = T] as well, and\n        hence [Gamma' |- t : T] by [T_Var].\n\n      - If the last rule was [T_Abs], then [t = \\y:T11. t12], with [T\n        = T11 -> T12] and [Gamma, y:T11 |- t12 : T12].  The induction\n        hypothesis is that for any context [Gamma''], if [Gamma,\n        y:T11] and [Gamma''] assign the same types to all the free\n        variables in [t12], then [t12] has type [T12] under [Gamma''].\n        Let [Gamma'] be a context which agrees with [Gamma] on the\n        free variables in [t]; we must show [Gamma' |- \\y:T11. t12 :\n        T11 -> T12].\n\n        By [T_Abs], it suffices to show that [Gamma', y:T11 |- t12 :\n        T12].  By the IH (setting [Gamma'' = Gamma', y:T11]), it\n        suffices to show that [Gamma, y:T11] and [Gamma', y:T11] agree\n        on all the variables that appear free in [t12].\n\n        Any variable occurring free in [t12] must either be [y], or\n        some other variable.  [Gamma, y:T11] and [Gamma', y:T11]\n        clearly agree on [y].  Otherwise, we note that any variable\n        other than [y] which occurs free in [t12] also occurs free in\n        [t = \\y:T11. t12], and by assumption [Gamma] and [Gamma']\n        agree on all such variables, and hence so do [Gamma, y:T11]\n        and [Gamma', y:T11].\n\n      - If the last rule was [T_App], then [t = t1 t2], with [Gamma |-\n        t1 : T2 -> T] and [Gamma |- t2 : T2].  One induction\n        hypothesis states that for all contexts [Gamma'], if [Gamma']\n        agrees with [Gamma] on the free variables in [t1], then [t1]\n        has type [T2 -> T] under [Gamma']; there is a similar IH for\n        [t2].  We must show that [t1 t2] also has type [T] under\n        [Gamma'], given the assumption that [Gamma'] agrees with\n        [Gamma] on all the free variables in [t1 t2].  By [T_App], it\n        suffices to show that [t1] and [t2] each have the same type\n        under [Gamma'] as under [Gamma].  However, we note that all\n        free variables in [t1] are also free in [t1 t2], and similarly\n        for free variables in [t2]; hence the desired result follows\n        by the two IHs.\n*)\n(** 「証明」: [Gamma |- t : T] の導出についての帰納法を使う。\n\n      - 導出の最後の規則が[T_Var]のとき、[t = x] かつ [Gamma x = T] である。\n        仮定から [Gamma' x = T] であるから、[T_Var] より [Gamma' |- t : T] となる。\n\n      - 最後の規則が [T_Abs] のとき、[t = \\y:T11. t12] かつ [T = T11 -> T12]\n        かつ [Gamma, y:T11 |- t12 : T12] である。\n        帰納法の仮定は、任意のコンテキスト[Gamma'']について、\n        もし [Gamma, y:T11] と [Gamma''] が [t12]\n        内のすべての自由変数に同じ型を割り当てるならば、\n        [t12] は [Gamma''] のもとで型[T12]を持つ、である。\n        [Gamma']を、[t]内の自由変数について[Gamma]\n        と同じ割当てをするコンテキストとする。\n        示すべきことは [Gamma' |- \\y:T11. t12 : T11 -> T12] である。\n\n        [T_Abs] より、[Gamma', y:T11 |- t12 : T12] を示せば十分である。\n        帰納仮定(ただし [Gamma'' = Gamma', y:T11] とする)より、\n        [Gamma, y:T11] と [Gamma', y:T11] が\n        [t12]内に自由に現れるすべての変数について割当てが一致することを示せば十分である。\n\n        [t12]に自由に出現する任意の変数は[y]であるか、それ以外の変数かである。\n        [Gamma, y:T11] と [Gamma', y:T11] は明らかに[y]については一致する。\n        それ以外の場合、[t12]に自由に出現する[y]以外の任意の変数は\n        [t = \\y:T11. t12] にも自由に現れることに注意すると、[Gamma] と [Gamma']\n        がそのような変数について割当てが一致するという仮定より、\n        [Gamma, y:T11] と [Gamma', y:T11] も一致する。\n\n      - 最後の規則が [T_App] の場合、[t = t1 t2] かつ [Gamma |- t1 : T2 -> T]\n        かつ [Gamma |- t2 : T2] である。\n        帰納法の仮定の1つは、すべてのコンテキスト[Gamma']について、\n        [Gamma']と[Gamma]が[t1]のすべての自由変数について同じ割当てをするならば、\n        [Gamma']のもとで[t1]は型 [T2 -> T] を持つ、となる。\n        [t2]についても同様の帰納仮定がある。\n        証明すべきことは、[Gamma']が[Gamma]と [t1 t2]\n        のすべての自由変数について同一の割当てをするという仮定の上で、\n        [Gamma']のもとでも [t1 t2] が型[T]を持つ、ということである。\n        [T_App]より、[t1] と [t2] がそれぞれ\n        [Gamma']と[Gamma]のもとで同じ型を持つことを示せば十分である。\n        しかし、[t1]のすべての自由変数は [t1 t2] でも自由変数であり、\n        [t2]の自由変数についても同様である。ゆえに、2つの帰納仮定から求める結果が得られる。\n*)\n\nProof with eauto.\n  intros.\n  generalize dependent Gamma'.\n  has_type_cases (induction H) Case; intros; auto.\n  Case \"T_Var\".\n    apply T_Var. rewrite <- H0...\n  Case \"T_Abs\".\n    apply T_Abs.\n    apply IHhas_type. intros x0 Hafi.\n    (* the only tricky step... the [Gamma'] we use to\n       instantiate is [extend Gamma x T11] *)\n    unfold extend. remember (beq_id x x0) as e. destruct e...\n  Case \"T_App\".\n    apply T_App with T11...\nQed.\n\n(* Now we come to the conceptual heart of the proof that reduction\n    preserves types -- namely, the observation that _substitution_\n    preserves types.\n\n    Formally, the so-called _Substitution Lemma_ says this: suppose we\n    have a term [t] with a free variable [x], and suppose we've been\n    able to assign a type [T] to [t] under the assumption that [x] has\n    some type [U].  Also, suppose that we have some other term [v] and\n    that we've shown that [v] has type [U].  Then, since [v] satisfies\n    the assumption we made about [x] when typing [t], we should be\n    able to substitute [v] for each of the occurrences of [x] in [t]\n    and obtain a new term that still has type [T]. *)\n(** ついに、簡約が型を保存することの証明の概念的な核心です。\n    つまり、「置換」が型を保存することを調べます。\n\n    非形式的には、置換補題(_Substitution Lemma_)と呼ばれる補題は次のことを主張します:\n    項[t]が自由変数[x]を持ち、[x]が型[U]を持つという仮定のもとで[t]に型[T]が付けられるとする。\n    また、別の項[v]について、[v]が型[U]を持つことが示されるとする。このとき、\n    [v]は[t]の型付けに関する[x]についての上述の仮定を満たすことから、[t]におけるそれぞれの\n    [x]の出現を[v]で置換することはできるはずであり、\n    その置換によって型が[T]のままである新しい項を得る。*)\n(* (訳注：冒頭の \"Formally\" は \"Informally\" の間違いと文脈から判断。) *)\n\n\n(* _Lemma_: If [Gamma,x:U |- t : T] and [|- v : U], then [Gamma |-\n    [v/x]t : T]. *)\n(** 「補題」: もし [Gamma,x:U |- t : T] かつ [|- v : U] ならば [Gamma |-\n    [v/x]t : T]. *)\n\nLemma substitution_preserves_typing : forall Gamma x U v t T,\n     has_type (extend Gamma x U) t T ->\n     has_type empty v U   ->\n     has_type Gamma (subst v x t) T.\n\n(* One technical subtlety in the statement of the lemma is that we\n    assign [v] the type [U] in the _empty_ context -- in other words,\n    we assume [v] is closed.  This assumption considerably simplifies\n    the [T_Abs] case of the proof (compared to assuming [Gamma |- v :\n    U], which would be the other reasonable assumption at this point)\n    because the context invariance lemma then tells us that [v] has\n    type [U] in any context at all -- we don't have to worry about\n    free variables in [v] clashing with the variable being introduced\n    into the context by [T-Abs].\n\n    _Proof_: We prove, by induction on [t], that, for all [T] and\n    [Gamma], if [Gamma,x:U |- t : T] and [|- v : U], then [Gamma |-\n    [v/x]t : T].\n\n      - If [t] is a variable, there are two cases to consider, depending\n        on whether [t] is [x] or some other variable.\n\n          - If [t = x], then from the fact that [Gamma, x:U |- x : T] we\n            conclude that [U = T].  We must show that [[v/x]x = v] has\n            type [T] under [Gamma], given the assumption that [v] has\n            type [U = T] under the empty context.  This follows from\n            context invariance: if a closed term has type [T] in the\n            empty context, it has that type in any context.\n\n          - If [t] is some variable [y] that is not equal to [x], then\n            we need only note that [y] has the same type under [Gamma,\n            x:U] as under [Gamma].\n\n      - If [t] is an abstraction [\\y:T11. t12], then the IH tells us,\n        for all [Gamma'] and [T'], that if [Gamma',x:U |- t12 : T']\n        and [|- v : U], then [Gamma' |- [v/x]t12 : T'].  In\n        particular, if [Gamma,y:T11,x:U |- t12 : T12] and [|- v : U],\n        then [Gamma,y:T11 |- [v/x]t12 : T12].  There are again two\n        cases to consider, depending on whether [x] and [y] are the\n        same variable name.\n\n        First, suppose [x = y].  Then, by the definition of\n        substitution, [[v/x]t = t], so we just need to show [Gamma |-\n        t : T].  But we know [Gamma,x:U |- t : T], and since the\n        variable [y] does not appear free in [\\y:T11. t12], the\n        context invariance lemma yields [Gamma |- t : T].\n\n        Second, suppose [x <> y].  We know [Gamma,x:U,y:T11 |- t12 :\n        T12] by inversion of the typing relation, and [Gamma,y:T11,x:U\n        |- t12 : T12] follows from this by the context invariance\n        lemma, so the IH applies, giving us [Gamma,y:T11 |- [v/x]t12 :\n        T12].  By [T_Abs], [Gamma |- \\y:T11. [v/x]t12 : T11->T12], and\n        by the definition of substitution (noting that [x <> y]),\n        [Gamma |- \\y:T11. [v/x]t12 : T11->T12], as required.\n\n      - If [t] is an application [t1 t2], the result follows\n        straightforwardly from the definition of substitution and the\n        induction hypotheses.\n\n      - The remaining cases are similar to the application case.\n\n    Another technical note: This proof is a rare case where an\n    induction on terms, rather than typing derivations, yields a\n    simpler argument.  The reason for this is that the assumption\n    [has_type (extend Gamma x U) t T] is not completely generic, in\n    the sense that one of the \"slots\" in the typing relation -- namely\n    the context -- is not just a variable, and this means that Coq's\n    native induction tactic does not give us the induction hypothesis\n    that we want.  It is possible to work around this, but the needed\n    generalization is a little tricky.  The term [t], on the other\n    hand, _is_ completely generic. *)\n(** 補題の主張について技術的に巧妙な点の1つは、[v]に型[U]を割当てるのが\n    「空」コンテキストであることです。言い換えると、[v]が閉じていると仮定しています。\n    この仮定は[T_Abs]の場合の証明を\n    (この場面でとりうる別の仮定である [Gamma |- v : U] を仮定するのに比べて)\n    大幅に簡単にします。\n    なぜなら、コンテキスト不変補題(the context invariance lemma)が、\n    どんなコンテキストでも[v]が型[U]を持つことを示すからです。\n    [v]内の自由変数が\n    [T-Abs]によってコンテキストに導入された変数と衝突することを心配する必要はありません。\n\n    「証明」: [t]についての帰納法によって、すべての [T] と [Gamma] について\n    [Gamma,x:U |- t : T] かつ [|- v : U] ならば、[Gamma |- [v/x]t : T]\n    であることを証明する。\n\n      - [t]が変数のとき、[t]が[x]であるか否かによって2つの場合がある。\n\n          - [t = x] の場合、[Gamma, x:U |- x : T] という事実から、\n            [U = T] になる。\n            ここで示すべきことは、空コンテキストのもとで[v]が型 [U = T] という仮定の上で、\n            [Gamma]のもとで [[v/x]x = v] が型[T]を持つことである。\n            これは、コンテキスト不変補題、\n            つまり、閉じた項が空コンテキストのもとで型[T]を持つならば、\n            その項は任意のコンテキストのもとで型[T]を持つ、ということから得られる。\n\n          - [t]が[x]以外の変数[y]である場合、[y]の型は[Gamma,x:U]のもとでも\n            [Gamma]のもとでも変わらないということに注意するだけでよい。\n\n      - [t]が関数抽象 [\\y:T11. t12] のとき、帰納仮定から、すべての[Gamma']と[T']について、\n        [Gamma',x:U |- t12 : T'] かつ [|- v : U] ならば [Gamma' |- [v/x]t12 : T']\n        となる。\n        特に [Gamma,y:T11,x:U |- t12 : T12] かつ [|- v : U] ならば\n        [Gamma,y:T11 |- [v/x]t12 : T12] となる。\n        [x]と[y]が同じ変数か否かでまた2つの場合がある。\n\n        最初に [x = y] とすると、置換の定義から [[v/x]t = t] である。\n        これから [Gamma |- t : T] を示すだけで良い。しかし、[Gamma,x:U |- t : T]\n        であって、[\\y:T11. t12]に[y]は自由に出現することはないから、\n        コンテキスト不変補題から [Gamma |- t : T] となる。\n\n        次に [x <> y] とする。型付け関係の反転から [Gamma,x:U,y:T11 |- t12 :\n        T12] であり、これとコンテキスト不変補題から [Gamma,y:T11,x:U |- t12 : T12]\n        となる。これから帰納仮定を使って、[Gamma,y:T11 |- [v/x]t12 : T12] が得られる。\n        [T_Abs]から [Gamma |- \\y:T11. [v/x]t12 : T11->T12] となり、\n        置換の定義から([x <> y] に注意すると)求める\n        [Gamma |- \\y:T11. [v/x]t12 : T11->T12] が得られる。\n\n      - [t] が関数適用 [t1 t2] のときは、結果は置換の定義と帰納法の仮定から直ぐに\n        得られる。\n\n      - 他の場合は、関数適用の場合と同様である。\n\n    別の技術的な注: この証明は、\n    型の導出についての帰納法ではなく項についての帰納法を使うことが議論をより簡単にするという、\n    珍しいものです。この理由は、仮定 [has_type (extend Gamma x U) t T]\n    がある意味で完全に一般化されていないからです。\n    ある意味というのは、型関係の1つの「スロット」、つまりコンテキストが、\n    単に1つの変数ではないということです。\n    このことにより、Coq がもともと持っている帰納法のタクティックでは必要な帰納法の仮定が導かれません。\n    これを回避することは可能ですが、そのために必要な一般化はちょっとトリッキーです。\n    これに対して項[t]は完全に一般化されています。*)\n\nProof with eauto.\n  intros Gamma x U v t T Ht Hv.\n  generalize dependent Gamma. generalize dependent T.\n  tm_cases (induction t) Case; intros T Gamma H;\n    (* in each case, we'll want to get at the derivation of H *)\n    inversion H; subst; simpl...\n  Case \"tm_var\".\n    rename i into y. remember (beq_id x y) as e. destruct e.\n    SCase \"x=y\".\n      apply beq_id_eq in Heqe. subst.\n      rewrite extend_eq in H2.\n      inversion H2; subst. clear H2.\n                  eapply context_invariance... intros x Hcontra.\n      destruct (free_in_context _ _ T empty Hcontra) as [T' HT']...\n      inversion HT'.\n    SCase \"x<>y\".\n      apply T_Var. rewrite extend_neq in H2...\n  Case \"tm_abs\".\n    rename i into y. apply T_Abs.\n    remember (beq_id x y) as e. destruct e.\n    SCase \"x=y\".\n      eapply context_invariance...\n      apply beq_id_eq in Heqe. subst.\n      intros x Hafi. unfold extend.\n      destruct (beq_id y x)...\n    SCase \"x<>y\".\n      apply IHt. eapply context_invariance...\n      intros z Hafi. unfold extend.\n      remember (beq_id y z) as e0. destruct e0...\n      apply beq_id_eq in Heqe0. subst.\n      rewrite <- Heqe...\nQed.\n\n(* The substitution lemma can be viewed as a kind of \"commutation\"\n    property.  Intuitively, it says that substitution and typing can\n    be done in either order: we can either assign types to the terms\n    [t] and [v] separately (under suitable contexts) and then combine\n    them using substitution, or we can substitute first and then\n    assign a type to [ [v/x] t ] -- the result is the same either\n    way. *)\n(** 置換補題は一種の「交換性」(\"commutation\" property)と見なせます。\n    直観的には、置換と型付けはどの順でやってもよいということを主張しています。\n    (適切なコンテキストのもとで)\n    項[t]と[v]に個別に型付けをしてから置換によって両者を組合せても良いし、\n    置換を先にやって後から [ [v/x] t ] に型をつけることもできます。\n    どちらでも結果は同じです。*)\n\n(* ###################################################################### *)\n(* *** Preservation *)\n(** *** 保存 *)\n\n(* We now have the tools we need to prove _preservation_: if a closed\n    term [t] has type [T], and takes an evaluation step to [t'], then [t']\n    is also a closed term with type [T].  In other words, the small-step\n    evaluation relation preserves types.\n*)\n(** さて、(型の)保存(_preservation_)を証明する道具立ては揃いました。\n    保存とは、閉じた項[t]が型[T]を持ち、[t']への評価ステップを持つならば、\n    [t']はまた型[T]を持つ閉じた項である、という性質です。\n    言い換えると、スモールステップ評価関係は型を保存するということです。\n*)\n\nTheorem preservation : forall t t' T,\n     has_type empty t T  ->\n     t ==> t'  ->\n     has_type empty t' T.\n\n(* _Proof_: by induction on the derivation of [|- t : T].\n\n    - We can immediately rule out [T_Var], [T_Abs], [T_True], and\n      [T_False] as the final rules in the derivation, since in each of\n      these cases [t] cannot take a step.\n\n    - If the last rule in the derivation was [T_App], then [t = t1\n      t2].  There are three cases to consider, one for each rule that\n      could have been used to show that [t1 t2] takes a step to [t'].\n\n        - If [t1 t2] takes a step by [ST_App1], with [t1] stepping to\n          [t1'], then by the IH [t1'] has the same type as [t1], and\n          hence [t1' t2] has the same type as [t1 t2].\n\n        - The [ST_App2] case is similar.\n\n        - If [t1 t2] takes a step by [ST_AppAbs], then [t1 =\n          \\x:T11.t12] and [t1 t2] steps to [subst t2 x t12]; the\n          desired result now follows from the fact that substitution\n          preserves types.\n\n    - If the last rule in the derivation was [T_If], then [t = if t1\n      then t2 else t3], and there are again three cases depending on\n      how [t] steps.\n\n        - If [t] steps to [t2] or [t3], the result is immediate, since\n          [t2] and [t3] have the same type as [t].\n\n        - Otherwise, [t] steps by [ST_If], and the desired conclusion\n          follows directly from the induction hypothesis.\n*)\n(** 「証明」: [|- t : T] の導出についての帰納法を使う。\n\n    - まず最後の規則が [T_Var]、[T_Abs]、[T_True]、[T_False]\n      である場合は外して良い。なぜなら、これらの場合、\n      [t]はステップを進むことができないからである。\n\n    - 導出の最後の規則が [T_App] のとき、[t = t1 t2] である。\n      このとき、[t1 t2] が [t'] にステップを進めたことを示すのに使われた規則について、\n      3つの場合が考えられる。\n\n        - [t1 t2] が[ST_App1]によってステップを進めた場合、\n          [t1]がステップを進めたものを[t1']とする。すると帰納仮定より\n          [t1']は[t1]と同じ型を持ち、したがって、[t1' t2] は [t1 t2] と同じ型を持つ。\n\n        - [ST_App2]の場合は同様である。\n\n        - [t1 t2] が[ST_AppAbs]によってステップを進めた場合、\n          [t1 = \\x:T11.t12] であり、\n          [t1 t2] は [subst t2 x t12] にステップする。\n          すると置換が型を保存するという事実から求める結果となる。\n\n    - 導出の最後の規則が [T_If] のとき、[t = if t1 then t2 else t3] であり、\n      やはり[t]のステップについて3つの場合がある。\n\n        - [t]が[t2]または[t3]にステップした場合、結果は直ぐである。なぜなら\n          [t2]と[t3]は[t]と同じ型だからである。\n\n        - そうでない場合、[t]は[ST_If]でステップする。このとき、\n          帰納法の仮定から直接求める結果が得られる。\n*)\n\nProof with eauto.\n  remember (@empty ty) as Gamma.\n  intros t t' T HT. generalize dependent t'.\n  has_type_cases (induction HT) Case;\n     intros t' HE; subst Gamma; subst;\n     try solve [inversion HE; subst; auto].\n  Case \"T_App\".\n    inversion HE; subst...\n    (* Most of the cases are immediate by induction,\n       and [auto] takes care of them *)\n    SCase \"ST_AppAbs\".\n      apply substitution_preserves_typing with T11...\n      inversion HT1...\nQed.\n\n(* **** Exercise: 2 stars, recommended (subject_expansion_stlc) *)\n(** **** 練習問題: ★★, recommended (subject_expansion_stlc) *)\n(* An exercise earlier in this file asked about the subject\n    expansion property for the simple language of arithmetic and\n    boolean expressions.  Does this property hold for STLC?  That\n    is, is it always the case that, if [t ==> t'] and [has_type\n    t' T], then [has_type t T]?  If so, prove it.  If not, give a\n    counter-example.\n\n(* FILL IN HERE *)\n[]\n*)\n(** このファイルの前の練習問題で、\n    算術式とブール式の簡単な言語についての主部展開性についてききました\n    (訳注:実際には Types_J.v内の練習問題)。\n    STLCでこの性質は成立するでしょうか？つまり、\n    [t ==> t'] かつ [has_type t' T] ならば [has_type t T]\n    ということが常に言えるでしょうか？\n    もしそうならば証明しなさい。そうでなければ、反例を挙げなさい。\n*)\n\n(* 言えない。\n   反例は、\n   t  === tm_if tm_ture tm_ture idB\n   t' === tm_true\n   T  === ty_Bool\n *)\n\nTheorem not_subject_expansion_stlc :\n  ~ (forall t t' T,\n       t ==> t' ->\n       has_type empty t' T ->\n       has_type empty t T).\nProof.\n  intro Contra.\n  remember\n    (Contra _ _ _ (ST_IfTrue tm_true idB) (T_True empty)) as N.\n  inversion N; subst.\n  inversion H6.\nQed.\n\n(* [] *)\n\n(* ###################################################################### *)\n(* *** Progress *)\n(** *** 進行 *)\n\n(* Finally, the _progress_ theorem tells us that closed, well-typed\n    terms are never stuck: either a well-typed term is a value, or\n    else it can take an evaluation step.\n*)\n(** 最後に、\n    「進行」定理(the _progress_ theorem)は閉じた、\n    型が付けられる項は行き詰まらないことを示します。\n    つまり、型が付けられる項は、値であるか、または評価ステップを進むことができるか、どちらかです。\n*)\n\nTheorem progress : forall t T,\n     has_type empty t T ->\n     value t \\/ exists t', t ==> t'.\n\n(* _Proof_: by induction on the derivation of [|- t : T].\n\n    - The last rule of the derivation cannot be [T_Var], since a\n      variable is never well typed in an empty context.\n\n    - The [T_True], [T_False], and [T_Abs] cases are trivial, since in\n      each of these cases we know immediately that [t] is a value.\n\n    - If the last rule of the derivation was [T_App], then [t = t1\n      t2], and we know that [t1] and [t2] are also well typed in the\n      empty context; in particular, there exists a type [T2] such that\n      [|- t1 : T2 -> T] and [|- t2 : T2].  By the induction\n      hypothesis, either [t1] is a value or it can take an evaluation\n      step.\n\n        - If [t1] is a value, we now consider [t2], which by the other\n          induction hypothesis must also either be a value or take an\n          evaluation step.\n\n            - Suppose [t2] is a value.  Since [t1] is a value with an\n              arrow type, it must be a lambda abstraction; hence [t1\n              t2] can take a step by [ST_AppAbs].\n\n            - Otherwise, [t2] can take a step, and hence so can [t1\n              t2] by [ST_App2].\n\n        - If [t1] can take a step, then so can [t1 t2] by [ST_App1].\n\n    - If the last rule of the derivation was [T_If], then [t = if t1\n      then t2 else t3], where [t1] has type [Bool].  By the IH, [t1]\n      is either a value or takes a step.\n\n        - If [t1] is a value, then since it has type [Bool] it must be\n          either [true] or [false].  If it is [true], then [t] steps\n          to [t2]; otherwise it steps to [t3].\n\n        - Otherwise, [t1] takes a step, and therefore so does [t] (by\n          [ST_If]).\n\n*)\n(** 「証明」: [|- t : T] の導出についての帰納法による。\n\n    - 導出の最後の規則は[T_Var]ではありえない。なぜなら、\n      空コンテキストにおいて変数には型付けできないからである。\n\n    - [T_True]、[T_False]、[T_Abs]の場合は自明である。\n      なぜなら、これらの場合 [t]は値だからである。\n\n    - 導出の最後の規則が[T_App]の場合、[t = t1 t2] であり、\n      [t1]および[t2]はどちらも空コンテキストで型付けされる。\n      特に型[T2]があって、[|- t1 : T2 -> T] かつ [|- t2 : T2] となる。\n      帰納法の仮定から、[t1]は値であるか、評価ステップを進むことができる。\n\n        - [t1]が値のとき、[t2]を考えると、\n          帰納仮定からさらに値である場合と評価ステップを進む場合がある。\n\n            - [t2]が値のとき、[t1]は値で関数型であるから、ラムダ抽象である。\n              ゆえに、[t1 t2] は [ST_AppAbs] でステップを進むことができる。\n\n            - そうでなければ、[t2]はステップを進むことができる。したがって\n              [ST_App2]で [t1 t2] もステップを進むことができる。\n\n        - [t1]がステップを進むことができるとき、[ST_App1] で [t1 t2]\n          もステップを進むことができる。\n\n    - 導出の最後の規則が[T_If]のとき、[t = if t1 then t2 else t3] で\n      [t1] は型[Bool]を持つ。帰納仮定より[t1]は値かステップを進むことができるかどちらかである。\n\n        - [t1]が値のとき、その型が[Bool]であることから[t1]は[true]または[false]である。\n          [true]ならば[t]は[t2]に進み、そうでなければ[t3]に進む。\n\n        - そうでないとき、[t1]はステップを進むことができる。したがって([ST_If]より)\n          [t]もステップを進むことができる。\n\n*)\n\nProof with eauto.\n  intros t T Ht.\n  remember (@empty ty) as Gamma.\n  has_type_cases (induction Ht) Case; subst Gamma...\n  Case \"T_Var\".\n    (* contradictory: variables cannot be typed in an\n       empty context *)\n    inversion H.\n\n  Case \"T_App\".\n    (* [t] = [t1 t2].  Proceed by cases on whether [t1] is a\n       value or steps... *)\n    right. destruct IHHt1...\n\n    SCase \"t1 is a value\".\n      destruct IHHt2...\n      SSCase \"t2 is also a value\".\n        (* Since [t1] is a value and has an arrow type, it\n           must be an abs. Sometimes this is proved separately\n           and called a \"canonical forms\" lemma. *)\n        inversion H; subst. exists (subst t2 x t)...\n        solve by inversion. solve by inversion.\n      SSCase \"t2 steps\".\n        destruct H0 as [t2' Hstp]. exists (tm_app t1 t2')...\n\n    SCase \"t1 steps\".\n      destruct H as [t1' Hstp]. exists (tm_app t1' t2)...\n\n  Case \"T_If\".\n    right. destruct IHHt1...\n\n    SCase \"t1 is a value\".\n      (* Since [t1] is a value of boolean type, it must\n         be true or false *)\n      inversion H; subst. solve by inversion.\n      SSCase \"t1 = true\". eauto.\n      SSCase \"t1 = false\". eauto.\n\n    SCase \"t1 also steps\".\n      destruct H as [t1' Hstp]. exists (tm_if t1' t2 t3)...\nQed.\n\n(* **** Exercise: 3 stars, optional (progress_from_term_ind) *)\n(** **** 練習問題: ★★★, optional (progress_from_term_ind) *)\n(* Show that progress can also be proved by induction on terms\n    instead of types. *)\n(** 型についての帰納法ではなく項についての帰納法でも進行の証明ができることを示しなさい。*)\n\nTheorem progress' : forall t T,\n     has_type empty t T ->\n     value t \\/ exists t', t ==> t'.\nProof.\n  intros t.\n  tm_cases (induction t) Case; intros T Ht; auto.\n  + (* tm_var *) solve by inversion 2.\n  + (* tm_app *)\n    right.\n    inversion Ht; subst.\n    destruct (IHt1 (ty_arrow T11 T)) as [ V1 | [t1'] ].\n    - (* IHt1 prereq *) assumption.\n    - (* V1 *) destruct (IHt2 T11) as [ V2 | [t2'] ].\n      * (* IHt2 prereq *) assumption.\n      * (* V2 *)\n        inversion V1; subst.\n        { (* Print ST_AppAbs *)\n          exists (subst t2 x t).\n          apply ST_AppAbs.\n          assumption. }\n        { (* t1 tm_true *)  solve by inversion 2. }\n        { (* t1 tm_false *) solve by inversion 2. }\n      * (* t2' *)\n        exists (tm_app t1 t2').\n        apply ST_App2; assumption.\n    - (* t1' *)\n      exists (tm_app t1' t2).\n      apply ST_App1.\n      assumption.\n  + (* tm_if *)\n    inversion Ht; subst.\n    right.\n    destruct (IHt1 ty_Bool) as [ V1 | [t1'] ].\n    - (*IHt1 prereq *) assumption.\n    - (* t1 is V1 *)\n      inversion V1; subst.\n      * (* V1 is tm_abs *) solve by inversion.\n      * (* V1 is tm_true *)  exists t2. apply ST_IfTrue.\n      * (* V1 is tm_false *) exists t3. apply ST_IfFalse.\n    - (* t1 is P1 *)\n      exists (tm_if t1' t2 t3).\n      apply ST_If.\n      assumption.\nQed.\n\n(** [] *)\n\n(* ###################################################################### *)\n(* *** Uniqueness of Types *)\n(** *** 型の一意性 *)\n\n(* **** Exercise: 3 stars (types_unique) *)\n(** **** 練習問題: ★★★ (types_unique) *)\n(* Another pleasant property of the STLC is that types are\n    unique: a given term (in a given context) has at most one\n    type. *)\n(** STLCの別の好ましい性質は、型が唯一であることです。\n    つまり、与えらえた項については(与えられたコンテキストで)\n    高々1つの型しか型付けされません。*)\n(* Formalize this statement and prove it. *)\n(** この主張を形式化し、証明しなさい。*)\nTheorem types_unique :\n  forall Gamma t,\n  forall T0, has_type Gamma t T0 ->\n         forall T1, has_type Gamma t T1 ->\n                T0 = T1.\nProof.\n  intros Gamma t T0 HT0 T1 HT1.\n  generalize dependent T1.\n  generalize dependent T0.\n  generalize dependent Gamma.\n\n  tm_cases (induction t) Case\n  ; intros; inversion HT0; inversion HT1; subst.\n  - (* tm_var *)\n    rewrite H5 in H1.\n    inversion H1.\n    reflexivity.\n  - (* tm_app *)\n    (* apply (IHt1 Gamma (ty_arrow T2 T1)) in H2.\n       inversion H2; subst. *)\n    remember\n      (IHt1 Gamma\n            (ty_arrow T11 T0) H2\n            (ty_arrow T2 T1)  H8) as Feq.\n    inversion Feq; subst.\n    reflexivity.\n  - (* tm_abs *)\n    rewrite (IHt (extend Gamma i t)\n                 T12 H4\n                 T3  H10).\n    reflexivity.\n  - reflexivity.\n  - reflexivity.\n  - rewrite <- (IHt2 Gamma\n                     T0 H5\n                     T1 H13).\n    reflexivity.\nQed.\n\n(** [] *)\n\n\n(* 2016-12-03 kokomade *)\n\n(* ###################################################################### *)\n(* ** Additional Exercises *)\n(** ** さらなる練習問題 *)\n\n(* **** Exercise: 1 star (progress_preservation_statement) *)\n(** **** 練習問題: ★ (progress_preservation_statement) *)\n(* Without peeking, write down the progress and preservation\n    theorems for the simply typed lambda-calculus. *)\n(** なにも見ることなく、単純型付きラムダ計算の進行定理と保存定理を書き下しなさい。*)\n\nTheorem preservation_statement :\n  forall t t' T,\n    has_type empty t T ->\n    t ==> t' ->\n    has_type empty t' T.\nProof.\n  exact preservation.\nQed.\n\n\nTheorem progress_statement :\n  forall t T,\n    has_type empty t T ->\n    value t \\/ exists t', t ==> t'.\nProof.\n  exact progress.\nQed.\n\n(** [] *)\n\n(* **** Exercise: 2 stars, optional (stlc_variation1) *)\n(** **** 練習問題: ★★, optional (stlc_variation1) *)\n(* Suppose we add the following new rule to the evaluation\n    relation of the STLC:\n[[\n      | T_Strange : forall x t,\n           has_type empty (tm_abs x Bool t) Bool\n]]\n    Which of the following properties of the STLC remain true in\n    the presence of this rule?  For each one, write either\n    \"remains true\" or else \"becomes false.\" If a property becomes\n    false, give a counterexample.\n\n      - Determinacy of [step]\n\n      - Progress\n\n      - Preservation\n\n[]\n*)\n(** STLCの評価関係に次の新しい規則を加えたとします:\n[[\n      | T_Strange : forall x t,\n           has_type empty (tm_abs x Bool t) Bool\n]]\n    この規則を加えても真であるSTLCの性質は以下のうちどれでしょうか？\n    それぞれについて、「真のまま」または「偽に変わる」と書きなさい。\n    偽に変わるものについては、反例を挙げなさい。\n\n      - [step]の決定性\n        真のまま\n\n        [step]の決定性は評価規則だけで決まり、\n        型付け規則には影響を受けない。\n\n      - 進行\n        真のまま\n\n        value となる項の型付け規則が増えただけなので、\n        影響を受けない。\n\n      - 保存\n        偽\n\n        t === tm_app (tm_abs x ty_Bool (tm_abs y ty_Bool tm_true)) v\n        T === ty_arrwo ty_Bool ty_Bool\n\n        value v\n        t ==> t'\n        t' === tm_abs y ty_Bool tm_true : ty_Bool\n\n        T =/= ty_Bool\n[]\n*)\n\n(* **** Exercise: 2 stars (stlc_variation2) *)\n(** **** 練習問題: ★★ (stlc_variation2) *)\n(* Suppose we remove the rule [ST_App1] from the [step]\n    relation. Which of the three properties in the previous\n    exercise become false in the absence of this rule? For each\n    that becomes false, give a counterexample.\n\n[]\n*)\n(** [step]関係から[ST_App1]規則を除いたとします。\n    このとき前の練習問題の3つの性質のうち、偽になるものはどれでしょう？\n    偽になるものについては、反例を挙げなさい。\n\n      - [step]の決定性\n        真のまま\n\n        評価規則が減るだけでなので成立する。\n\n      - 進行\n        偽に変わる\n\n        t === tm_app (if tm_true then idB else idB) tm_true\n        T === ty_Bool\n\n        t は value ではないのに step できない。\n\n      - 保存\n        真のまま\n\n        保存しなければならない場合が減るだけなので、\n        成立する。\n\n[]\n*)\n\nEnd STLC.\n\n(* ###################################################################### *)\n(* ###################################################################### *)\n(* * Exercise: STLC with Arithmetic *)\n(** * 練習問題: 算術を持つSTLC *)\n\n(* To see how the STLC might function as the core of a real\n    programming language, let's extend it with a concrete base\n    type of numbers and some constants and primitive\n    operators. *)\n(** STLCが実際のプログラミング言語の核として機能することを見るため、\n    数値についての具体的な基本型と定数、いくつかの基本操作を追加しましょう。*)\n\nModule STLCArith.\n\n(* ###################################################################### *)\n(* ** Syntax and Operational Semantics *)\n(** ** 構文と操作的意味 *)\n\n(* To types, we add a base type of natural numbers (and remove\n    booleans, for brevity) *)\n(** 型について、自然数を基本型として加えます(そして簡潔さのためブール型を除きます)。 *)\n\nInductive ty : Type :=\n  | ty_arrow : ty -> ty -> ty\n  | ty_Nat   : ty.\n\n(* To terms, we add natural number constants, along with\n    successor, predecessor, multiplication, and zero-testing... *)\n(** 項について、自然数の定数、1つ前をとる関数、1つ後をとる関数、積算、ゼロか否かのテスト...\n    を加えます。 *)\n\nInductive tm : Type :=\n  | tm_var : id -> tm\n  | tm_app : tm -> tm -> tm\n  | tm_abs : id -> ty -> tm -> tm\n  | tm_nat  : nat -> tm\n  | tm_succ : tm -> tm\n  | tm_pred : tm -> tm\n  | tm_mult : tm -> tm -> tm\n  | tm_if0  : tm -> tm -> tm -> tm.\n\nTactic Notation \"tm_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"tm_var\" | Case_aux c \"tm_app\"\n  | Case_aux c \"tm_abs\" | Case_aux c \"tm_nat\"\n  | Case_aux c \"tm_succ\" | Case_aux c \"tm_pred\"\n  | Case_aux c \"tm_mult\" | Case_aux c \"tm_if0\" ].\n\n(* **** Exercise: 4 stars, recommended (STLCArith) *)\n(** **** 練習問題: ★★★★, recommended (STLCArith) *)\n(* Finish formalizing the definition and properties of the STLC extended\n    with arithmetic.  Specifically:\n\n    - Copy the whole development of STLC that we went through above (from\n      the definition of values through the Progress theorem), and\n      paste it into the file at this point.\n\n    - Extend the definitions of the [subst] operation and the [step]\n      relation to include appropriate clauses for the arithmetic operators.\n\n    - Extend the proofs of all the properties of the original STLC to deal\n      with the new syntactic forms.  Make sure Coq accepts the whole file. *)\n(** 算術を拡張したSTLCの定義と性質の形式化を完成させなさい。特に:\n\n    - STLCについてここまでやってきたこと(定義から進行定理まで)の全体をコピーして、\n      ファイルのこの部分にペーストしなさい。\n\n    - [subst]操作と[step]関係の定義を拡張して、算術の操作の適切な節を含むようにしなさい。\n\n    - オリジナルのSTLCの性質の証明を拡張して、新しい構文を扱うようにしなさい。\n      Coq がその証明を受理することを確認しなさい。*)\n\n(* FILL IN HERE *)\n(** [] *)\n\nEnd STLCArith.\n", "meta": {"author": "khibino", "repo": "sfja-code", "sha": "2b9f6c561b56652aa67bbc0971db90a211c66373", "save_path": "github-repos/coq/khibino-sfja-code", "path": "github-repos/coq/khibino-sfja-code/sfja-code-2b9f6c561b56652aa67bbc0971db90a211c66373/Stlc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.2964449579727892}}
{"text": "Require Export RecTypes.SpecTypes.\nRequire Export RecTypes.InstTy.\nRequire Export RecTypes.Contraction.\nRequire Export RecTypes.ValidTy.\nRequire Export RecTypes.LemmasTypes.\n\nRequire Import StlcIso.SpecSyntax.\nRequire Import StlcIso.SpecEvaluation.\nRequire Import StlcIso.LemmasEvaluation.\nRequire Import StlcIso.SpecTyping.\nRequire Import StlcIso.SpecAnnot.\nRequire Import StlcIso.LemmasTyping.\nRequire Import StlcIso.Inst.\nRequire Import StlcIso.InstAnnot.\nRequire Import Db.Lemmas.\nRequire Import Db.WellScoping.\n\nRequire Import Coq.Bool.Bool.\n\nLocal Ltac crush :=\n  intros; cbn in * |-;\n  repeat\n    (cbn;\n     repeat crushRecTypesMatchH;\n     repeat crushStlcSyntaxMatchH;\n     repeat crushDbSyntaxMatchH;\n     repeat crushDbLemmasRewriteH;\n     rewrite <- ?ap_liftSub, <- ?up_liftSub\n     (* repeat crushStlcIsoScopingMatchH; *)\n     (* repeat crushScopingMatchH *)\n    );\n  auto.\n\n(* Definition ufix₂_annot (f : TmA) (τ1 τ2 : Ty) : TmA := *)\n(*   let t : TmA := ia_abs (trec (tarr (tvar 0) (tarr τ1 τ2)[wkm])) *)\n(*                        (tarr τ1 τ2) *)\n(*                        (ia_app (tarr τ1 τ2) (tarr τ1 τ2) f[wkm] *)\n(*                                (ia_abs τ1 τ2 (ia_app τ1 τ2 (ia_app (trec (tarr (tvar 0) (tarr τ1 τ2)[wkm])) (tarr τ1 τ2) (ia_unfold_ (tarr (tvar 0) (tarr τ1 τ2)[wkm]) (ia_var 1)) (ia_var 1)) (ia_var 0)))) *)\n(*   in ia_app (trec (tarr (tvar 0) (tarr τ1 τ2)[wkm])) (tarr τ1 τ2) (ia_unfold_ (tarr (tvar 0) (tarr τ1 τ2)[wkm]) (ia_fold_ (tarr (tvar 0) (tarr τ1 τ2)[wkm]) t)) (ia_fold_ (tarr (tvar 0) (tarr τ1 τ2)[wkm]) t). *)\n\nDefinition ufix₁_annot (f : TmA) (τ1 τ2 : Ty) : TmA :=\n  let t : TmA := ia_abs (trec (tarr (tvar 0) (tarr τ1 τ2)[wkm]))\n                       (tarr τ1 τ2)\n                       (ia_app (tarr τ1 τ2) (tarr τ1 τ2) f[wkm]\n                               (ia_abs τ1 τ2 (ia_app τ1 τ2 (ia_app (trec (tarr (tvar 0) (tarr τ1 τ2)[wkm])) (tarr τ1 τ2) (ia_unfold_ (tarr (tvar 0) (tarr τ1 τ2)[wkm]) (ia_var 1)) (ia_var 1)) (ia_var 0))))\n  in ia_app (trec (tarr (tvar 0) (tarr τ1 τ2)[wkm])) (tarr τ1 τ2)\n            (ia_unfold_ (tarr (tvar 0) (tarr τ1 τ2)[wkm]) (ia_fold_ (tarr (tvar 0) (tarr τ1 τ2)[wkm]) t))\n            (ia_fold_ (tarr (tvar 0) (tarr τ1 τ2)[wkm]) t).\n\nDefinition ufix_annot (τ1 τ2 : Ty) : TmA :=\n  ia_abs (tarr (tarr τ1 τ2) (tarr τ1 τ2)) (tarr τ1 τ2) (ufix₁_annot (ia_var 0) τ1 τ2).\n\n\n(* Definition ufix₂ (f : Tm) (τ1 τ2 : Ty) : Tm := *)\n(*   let t : Tm := abs (trec (tarr (tvar 0) (tarr τ1 τ2)[wkm])) (app f[wkm] (abs τ1 (app (app (unfold_ (var 1)) (var 1)) (var 0)))) *)\n(*   in app (unfold_ (fold_ t)) (fold_ t). *)\n\n(* note that ufix₁ has a unfold-fold redex.\n  this is of course unnecessary, but it will appear after evaluation, so it's easier to put it there from the start as well (to reduce the amount of different terms to keep track of).\n*)\nDefinition ufix₁ (f : Tm) (τ1 τ2 : Ty) : Tm :=\n  let t : Tm := abs (trec (tarr (tvar 0) (tarr τ1 τ2)[wkm])) (app f[wkm] (abs τ1 (app (app (unfold_ (var 1)) (var 1)) (var 0))))\n  in app (unfold_ (fold_ t)) (fold_ t).\n\nDefinition ufix (τ1 τ2 : Ty) : Tm :=\n  abs (tarr (tarr τ1 τ2) (tarr τ1 τ2)) (ufix₁ (var 0) τ1 τ2).\n\nDefinition Om (τ : Ty) : Tm :=\n  app (ufix₁ (abs (tunit r⇒ τ) (var 0)) tunit τ) unit.\n\nDefinition OmA (τ : Ty) : TmA :=\n  ia_app tunit τ (ufix₁_annot (ia_abs (tunit r⇒ τ) (tunit r⇒ τ) (ia_var 0)) tunit τ) ia_unit.\n\nLemma eraseAnnot_ufix {τ₁ τ₂} : eraseAnnot (ufix_annot τ₁ τ₂) = ufix τ₁ τ₂.\nProof. reflexivity. Qed.\n\nLemma ufix_eval₁' f (valf: Value f) {τ1 τ2} : (app (ufix τ1 τ2) f) --> (ufix₁ f τ1 τ2).\nProof.\n  unfold ufix, ufix₁.\n  apply (eval_ctx₀ phole); crush; eapply eval_beta''; crush.\nQed.\n\nLemma ufix_eval₁ f (valf: Value f) {τ1 τ2} : app (ufix τ1 τ2) f  --> ufix₁ f τ1 τ2.\nProof.\n  eauto using ufix_eval₁'.\nQed.\n\nLemma ufix₁_evaln' {t τ1 τ2} : evaln (ufix₁ (abs (tarr τ1 τ2) t) τ1 τ2) (t[beta1 (abs τ1 (app (ufix₁ (abs (tarr τ1 τ2) t[wkm↑]) τ1 τ2) (var 0)))]) 3.\nProof.\n  unfold ufix₁.\n  econstructor.\n  {eapply (eval_ctx₀ (papp₁ phole _)); [|now cbn].\n   eapply eval_fold_unfold; now cbn.\n  }\n  cbn.\n  repeat change (apTm ?ξ ?t) with t[ξ].\n  econstructor.\n  { eapply eval_eval₀, eval_beta; now cbn. }\n  cbn.\n  repeat change (apTm ?ξ ?t) with t[ξ].\n  rewrite <-?ap_liftSub, <-?up_liftSub, ?liftSub_wkm.\n  rewrite apply_wkm_beta1_up_cancel.\n  crushDbLemmasRewriteH.\n  econstructor.\n  { eapply eval_eval₀, eval_beta; now cbn. }\n  econstructor.\nQed.\n\n(* Lemma unfold_fold_id { Γ t τ } : *)\n(*   ValidTy τ → *)\n(*   ⟪ Γ i⊢ t : τ ⟫ → *)\n(*   ⟪ Γ i⊢ unfold_ (fold_ t) : τ ⟫. *)\n(* Proof. *)\n(*   intros. *)\n(*   Check WtUnfold. *)\n(*   Check WtFold. *)\n(*   apply WtUnfold. *)\n\nLemma fizz {τ₁ τ₂ }:\n  (trec (tvar 0 r⇒ (τ₁ r⇒ τ₂)[wkm]) r⇒ τ₁ r⇒ τ₂) = (tvar 0 r⇒ (τ₁ r⇒ τ₂) [wkm])[beta1 (trec (tarr (tvar 0) (tarr τ₁ τ₂)[wkm]))].\nProof.\n  crush.\nQed.\n\nLemma ufix₁_typing {t τ₁ τ₂ Γ} :\n  ValidTy τ₁ → ValidTy τ₂ →\n  ⟪ Γ i⊢ t : tarr (tarr τ₁ τ₂) (tarr τ₁ τ₂) ⟫ →\n  ⟪ Γ i⊢ ufix₁ t τ₁ τ₂ : tarr τ₁ τ₂ ⟫.\nProof.\n  intros (cl1 & cr1) (cl2 & cr2) tyt.\n  unfold ufix₁.\n  apply (@WtApp Γ _ _ (trec (tarr (tvar 0) (tarr τ₁ τ₂)[wkm])) (tarr τ₁ τ₂)).\n  - (* rewrite <-(apply_wkm_beta1_cancel (τ₁ r⇒ τ₂) (trec (tarr (tvar 0) (tarr τ₁ τ₂)[wkm]))) at 1. *)\n    rewrite fizz.\n    econstructor.\n    econstructor.\n    rewrite <-fizz.\n    econstructor.\n    econstructor.\n    crush.\n    eapply typing_sub.\n    exact tyt.\n    apply wtSub_wkm.\n    econstructor.\n    econstructor.\n    econstructor.\n    rewrite fizz.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n\n    crushValidTy.\n    crush.\n    apply WsFn.\n    change (wsTy _ _) with ⟨ 1 ⊢ τ₁[wkm] ⟩.\n    crushValidTy.\n    change (wsTy _ _) with ⟨ 1 ⊢ τ₂[wkm] ⟩.\n    crushValidTy.\n    crush.\n    econstructor.\n    econstructor.\n    econstructor.\n    pose proof (SimpleContrRec_ren) as (H & _).\n    specialize (H τ₁ cr1 wkm).\n    erewrite <-ap_liftSub in H.\n    exact H.\n    econstructor.\n    pose proof (SimpleContrRec_ren) as (H & _).\n    specialize (H τ₂ cr2 wkm).\n    erewrite <-ap_liftSub in H.\n    exact H.\n    crushTyping.\n    crushTyping.\n    crushValidTy.\n    crushValidTy.\n    crush.\n    crushValidTy.\n    crushValidTy.\n    crush.\n    econstructor.\n    econstructor;\n    econstructor;\n    pose proof (SimpleContrRec_ren) as (H & _).\n    specialize (H τ₁ cr1 wkm).\n    erewrite <-ap_liftSub in H.\n    exact H.\n    specialize (H τ₂ cr2 wkm).\n    erewrite <-ap_liftSub in H.\n    exact H.\n    crushValidTyMatch.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    crush.\n    crushValidTy.\n    crushValidTy.\n    crush.\n    crushValidTy.\n    crushValidTy.\n    crush.\n    crushValidTy.\n    crush.\n    crushValidTy.\n  - crushTypingMatchH.\n    rewrite <-fizz.\n    crushTypingMatchH.\n    crushTypingMatchH.\n    crush.\n    eapply typing_sub.\n    exact tyt.\n    apply wtSub_wkm.\n    econstructor.\n    econstructor.\n    econstructor.\n    rewrite fizz.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    repeat (crushValidTy; crush).\n    repeat econstructor.\n    repeat econstructor.\n    crushValidTy.\n    repeat (crushValidTy; crush).\n    repeat (crushValidTy; crush).\nQed.\n\nLemma ufix_typing {τ₁ τ₂ Γ} :\n  ValidTy τ₁ -> ValidTy τ₂ ->\n  ⟪ Γ i⊢ ufix τ₁ τ₂ : tarr (tarr (tarr τ₁ τ₂) (tarr τ₁ τ₂)) (tarr τ₁ τ₂) ⟫.\nProof.\n  constructor.\n  apply ufix₁_typing.\n  all: repeat (crushTyping; crushValidTy).\nQed.\n\nLemma ufix₁_annot_typing {t τ₁ τ₂ Γ} :\n  ValidTy τ₁ -> ValidTy τ₂ ->\n  ⟪ (Γ r▻ trec (tvar 0 r⇒ τ₁[wkm] r⇒ τ₂[wkm])) ia⊢ t [wkm] : tarr (tarr τ₁ τ₂) (tarr τ₁ τ₂) ⟫ →\n  ⟪ Γ ia⊢ ufix₁_annot t τ₁ τ₂ : tarr τ₁ τ₂ ⟫.\nProof.\n  intros (cl1 & cr1) (cl2 & cr2) tyt.\n  unfold ufix₁_annot.\n  crushTypingIA.\n  - repeat change (apTy ?ξ ?τ) with τ[ξ].\n    repeat change (τ₁[wkm] r⇒ τ₂[wkm]) with (τ₁ r⇒ τ₂)[wkm].\n    rewrite fizz.\n    econstructor.\n    econstructor.\n    rewrite <-fizz.\n    econstructor.\n    econstructor.\n    crush.\n    crushValidTy.\n    crushValidTy.\n    crush.\n    crushValidTy.\n    econstructor.\n    exact tyt.\n    econstructor.\n    crushValidTy.\n    econstructor.\n    econstructor.\n    rewrite fizz.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    repeat (crush; crushValidTy).\n    repeat (crush; crushValidTy).\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    repeat (crush; crushValidTy).\n    repeat (crush; crushValidTy).\n    repeat (crush; crushValidTy).\n  - repeat change (apTy ?ξ ?τ) with τ[ξ].\n    repeat change (τ₁[wkm] r⇒ τ₂[wkm]) with (τ₁ r⇒ τ₂)[wkm].\n    crush.\n    econstructor.\n    repeat (crush; crushValidTy).\n    econstructor.\n    exact tyt.\n    econstructor.\n    repeat (crush; crushValidTy).\n    econstructor.\n    econstructor.\n    repeat change (τ₁[wkm] r⇒ τ₂[wkm]) with (τ₁ r⇒ τ₂)[wkm].\n    rewrite fizz.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    repeat (crush; crushValidTy).\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n  - repeat (crush; crushValidTy).\nQed.\n\nLemma ufix_annot_typing {τ₁ τ₂ Γ} :\n  ValidTy τ₁ -> ValidTy τ₂ ->\n  ⟪ Γ ia⊢ ufix_annot τ₁ τ₂ : tarr (tarr (tarr τ₁ τ₂) (tarr τ₁ τ₂)) (tarr τ₁ τ₂) ⟫.\nProof.\n  intros (cl1 & cr1) (cl2 & cr2).\n  constructor; crushValidTy.\n  eapply ufix₁_annot_typing; crushValidTy.\n  constructor.\n  crushTyping.\nQed.\n\n(* Lemma ufix₁_evaln {t} : evaln (ufix₁ (abs t)) (t[beta1 (abs (app (ufix₁ (abs t[wkm↑])) (var 0)))]) 2. *)\n(* Proof. *)\n(*   eauto using ufix₁_evaln', ctxevaln_evaln. *)\n(* Qed. *)\n\n(* Lemma ufix₁_eval {t} : ufix₁ (abs t) -->+ t[beta1 (abs (app (ufix₁ (abs t[wkm↑])) (var 0)))]. *)\n(* Proof. *)\n(*   refine (evaln_to_evalPlus _). *)\n(*   apply ufix₁_evaln. *)\n(* Qed. *)\n\n(* Lemma ufix_ws (γ : Dom) : *)\n(*   ⟨ γ ⊢ ufix ⟩. *)\n(* Proof. *)\n(*   unfold ufix, ufix₁. *)\n(*   crush. *)\n(* Qed. *)\n\n(* (* TODO: simplify using result about scoping under subst... *) *)\n(* Lemma ufix₁_ws {γ t} : *)\n(*   ⟨ γ ⊢ t ⟩ → ⟨ γ ⊢ ufix₁ t ⟩. *)\n(* Proof. *)\n(*   unfold ufix₁. *)\n(*   crush. *)\n(* Qed. *)\n\nLemma wtOm_tau {Γ} τ : ValidTy τ → ⟪ Γ i⊢ Om τ : τ ⟫.\nProof.\n  unfold Om.\n  crushTyping;\n  eapply ufix₁_typing;\n    crushTyping.\nQed.\n\nLemma wtOmA_tau {Γ} τ : ValidTy τ → ⟪ Γ ia⊢ OmA τ : τ ⟫.\n  unfold OmA.\n  crushTypingIA;\n  eapply ufix₁_annot_typing;\n    (crushTypingIA; crushValidTy).\nQed.\n\n#[export]\nHint Resolve wtOm_tau : typing.\n#[export]\nHint Resolve wtOmA_tau : typing.\n(* #[export]\nHint Resolve stlcOmegaAT : typing. *)\n\nDefinition OmHelp (τ : Ty) : Tm :=\n  app (abs tunit (app (ufix₁ (abs (tunit r⇒ τ) (var 0)) tunit τ) (var 0))) unit.\n\nLemma evaln_to_evalPlus {t t' n} : evaln t t' (S n) → t -->+ t'.\nProof.\n  intros.\n  eapply evaln_split1 in H as (? & ? & ?).\n  apply evaln_to_evalStar in H0.\n  eapply evalStepStarToPlus.\n  exact H.\n  exact H0.\nQed.\n\nLemma stlcOmega_cycles {τ} : Om τ -->+ Om τ.\n  cut (Om τ -->+ OmHelp τ ∧ OmHelp τ -->+ Om τ).\n  - destruct 1. apply evalPlusToStar in H0. eapply evalPlusStarToPlus. exact H. exact H0.\n  - unfold Om, OmHelp; split.\n    + eapply (evalplus_ctx (papp₁ phole _)).\n      constructor.\n      eapply evaln_to_evalPlus.\n      pose proof (@ufix₁_evaln' (var 0) tunit τ).\n      remember (var 0)[beta1 (abs tunit (app (ufix₁ (abs (tunit r⇒ τ) (var 0)[wkm↑]) tunit τ) (var 0)))] as x.\n      remember (abs tunit (app (ufix₁ (abs (tunit r⇒ τ) (var 0)) tunit τ) (var 0))) as y.\n      enough (x = y).\n      rewrite <-H0.\n      exact H.\n      subst.\n      cbn.\n      reflexivity.\n    + unfold ufix₁.\n      eapply evalStepStarToPlus.\n      apply eval₀_to_eval.\n      apply eval_beta; now cbn.\n      cbn.\n      change (wk 0) with 1.\n      apply rt1n_refl.\nQed.\n\nLemma Om_div {τ} : (Om τ)⇑.\nProof.\n  apply cycles_dont_terminate.\n  apply stlcOmega_cycles.\nQed.\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/StlcIso/Fix.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.2964449502366684}}
{"text": "Require Export P05.\n(*\nLemma replace_cequiv: forall (c1 c2:com),\n  cequiv c1 (constfold_0plus c1) -> cequiv c2 (constfold_0plus c2) -> \n  cequiv ((constfold_0plus c1);; (constfold_0plus c2)) \n    (constfold_0plus (c1;; c2)).\nProof.\n  intros.  \n  unfold constfold_0plus. simpl.\n  destruct c1.\n  Case \"c1=SKIP\".\n    simpl.\n    assert (H1: cequiv (SKIP;; (constfold_0plus c2)) (SKIP;; c2)).\n    apply CSeq_congruence. apply refl_cequiv. apply sym_cequiv. assumption.\n    assert (H2: cequiv (SKIP;; c2) (optimize_0plus_com c2)).\n    assert (H3: cequiv (SKIP;;c2) c2). \n    unfold cequiv. split. apply skip_left. apply skip_left.\n    apply trans_cequiv with (c2:=c2). assumption. apply optimize_0plus_com_sound.\n    unfold constfold_0plus in H1. apply trans_cequiv with (c2:=(SKIP;; c2)). assumption. assumption.\n  Case \"c1 = ::=\".\n    destruct c2. \n    SCase \"c2 = SKIP\". \n      assert (H1: cequiv ((i ::= a);;SKIP) ((constfold_0plus (i ::= a));; (constfold_0plus SKIP))).\n        apply CSeq_congruence. assumption. assumption.\n      assert (H2: cequiv ((i ::= a);;SKIP) (i ::= a)).\n        apply skip_right.\n      apply sym_cequiv in H1.\n      apply trans_cequiv with (c2:=((i ::= a);; SKIP)).\n      unfold constfold_0plus in H1. assumption.\n      assert (H3: cequiv (i ::= a) (optimize_0plus_com (i ::= a))).\n        apply optimize_0plus_com_sound.\n      apply trans_cequiv with (c2:=(i ::= a)).\n      assumption. assumption.\n    SCase \"c2 = ::=\".\n      simpl. apply refl_cequiv.\n    SCase \"c2 = ;;\".\n      simpl. destruct c2_1; \n        apply refl_cequiv;\n        destruct c2_2; apply refl_cequiv.\n          apply refl_cequiv.\n          apply refl_cequiv.\n  Case \"c1 = ;;\".\n    destruct c2.\n    SCase \"c2 = SKIP\". \n      simpl. destruct c1_1.\n      SSCase \"c1_1 = SKIP\".\n        assert (H1: cequiv (optimize_0plus_com c1_2;; SKIP) (optimize_0plus_com c1_2)).\n          apply skip_right.\n        assert (H2: cequiv (optimize_0plus_com c1_2) (optimize_0plus_com SKIP;; optimize_0plus_com c1_2)).\n          assert (H3: cequiv (optimize_0plus_com SKIP;; optimize_0plus_com c1_2)\n            (SKIP;; optimize_0plus_com c1_2)).\n            apply CSeq_congruence. apply sym_cequiv in H0. assumption. apply refl_cequiv.\n        assert (H4: cequiv (SKIP;; optimize_0plus_com c1_2) (optimize_0plus_com c1_2)).\n          apply skip_left.\n        apply sym_cequiv. apply trans_cequiv with (c2:= (SKIP;; optimize_0plus_com c1_2)).\n        assumption. assumption.\n        apply trans_cequiv with (c2:=(optimize_0plus_com c1_2)).\n        assumption. assumption.\n      SSCase \"c1_1 = :=\".\n        destruct c1_2.\n          simpl. apply refl_cequiv.\n          simpl. apply CSeq_congruence.\n*)\n\nLemma constfold_0plus_sound:\n  ctrans_sound constfold_0plus.\nProof.\n  unfold ctrans_sound. intros c.\n  induction c.\n  Case \"SKIP\".\n    unfold constfold_0plus. simpl. apply refl_cequiv.\n  Case \"::=\".\n    apply CAss_congruence. unfold aequiv. intro st.\n    induction a; try auto; \n      simpl; destruct (fold_constants_aexp a1); destruct (fold_constants_aexp a2);\n        try (rewrite IHa1; rewrite IHa2; auto); try destruct n; auto.\n  Case \";;\".\n    destruct c1.\n    SCase \"c1 = SKIP\".\n      unfold constfold_0plus in IHc2.\n      assert (H:cequiv c2 (fold_constants_com c2)).\n      apply fold_constants_com_sound. \n      assert (H1: cequiv (SKIP;;c2) c2). \n      unfold cequiv. split. apply skip_left. apply skip_left. \n      apply trans_cequiv with (c2:=c2). assumption. apply optimize_0plus_com_sound. \n    SCase \"c1 = ::=\".\n    destruct c2. \n      SSCase \"c2 = SKIP\". \n      assert (H1: cequiv ((i ::= a);;SKIP) ((constfold_0plus (i ::= a));; (constfold_0plus SKIP))).\n        apply CSeq_congruence. assumption. assumption.\n      assert (H2: cequiv ((i ::= a);;SKIP) (i ::= a)).\n        apply skip_right.\n      apply sym_cequiv in H1.\n      apply trans_cequiv with (c2:=((i ::= a);; SKIP)).\n      unfold constfold_0plus in H1. apply refl_cequiv.\n      assert (H3: cequiv (i ::= a) (optimize_0plus_com (i ::= a))).\n        apply optimize_0plus_com_sound.\n      apply trans_cequiv with (c2:=(i ::= a)).\n      assumption. assumption.\n      SSCase \"c2 = ::=\".\n        unfold constfold_0plus. simpl. unfold constfold_0plus in *.\n        apply CSeq_congruence. assumption. assumption.\n      SSCase \"c2 = ;;\".\n        unfold constfold_0plus. simpl.\n        destruct c2_1.\n        SSSCase \"c2_1 = SKIP\".\n          simpl. \n          assert (H: cequiv (SKIP;; c2_2) (optimize_0plus_com c2_2)).\n           assert (H1:  cequiv (SKIP;; c2_2) c2_2). apply skip_left.\n           assert (H2: cequiv c2_2 (optimize_0plus_com c2_2)). apply optimize_0plus_com_sound.\n           apply trans_cequiv with (c2:=c2_2). assumption. assumption.\n          apply CSeq_congruence. unfold constfold_0plus in IHc1. assumption. assumption.\n        SSSCase \"c2_1 = ::=\".\n          destruct c2_2.\n          SSSSCase \"c2_2 = SKIP\".\n            assert (H: cequiv (i0 ::= a0;; SKIP) (i0 ::= a0)).\n              apply skip_right.\n            assert (H1: cequiv (i0 ::= a0) (optimize_0plus_com (i0 ::= a0))).\n              apply optimize_0plus_com_sound.\n            apply CSeq_congruence. unfold constfold_0plus in IHc1. assumption.\n            apply trans_cequiv with (c2:=(i0 ::= a0)). assumption. assumption.\n          SSSSCase \"c2_2 = ::=\". simpl. apply CSeq_congruence.\n            unfold constfold_0plus in *. assumption. assumption.\n          SSSSCase \"c2_2 = ;;\". \n\n\n\n    \n    assert (H: cequiv (c1;; c2) ((constfold_0plus c1);; (constfold_0plus c2))).\n      apply CSeq_congruence. assumption. assumption.\n    assert (H1: cequiv ((constfold_0plus c1);; (constfold_0plus c2)) (constfold_0plus (c1;; c2))). \n     destruct c1. unfold constfold_0plus. simpl.\n        SCase \"SKIP\".\n          assert (H1: cequiv (SKIP;; (constfold_0plus c2)) (SKIP;; c2)).\n            apply CSeq_congruence. apply refl_cequiv. apply sym_cequiv. assumption.\n          assert (H2: cequiv (SKIP;; c2) (optimize_0plus_com c2)).\n            assert (H3: cequiv (SKIP;;c2) c2). \n              unfold cequiv. split. apply skip_left. apply skip_left.\n            apply trans_cequiv with (c2:=c2). assumption. apply optimize_0plus_com_sound.\n            unfold constfold_0plus in H1. apply trans_cequiv with (c2:=(SKIP;; c2)). assumption.\n            assumption.\n        SCase \"::=\". \n          \n        assert (H1: cequiv (SKIP;; optimize_0plus_com (fold_constants_com c2)) c2).\n          \n    destruct c1.\n      assert (H1: cequiv (SKIP;;c2) c2). \n      unfold cequiv. split. apply skip_left. apply skip_left.\n      apply trans_cequiv with (c2:=c2). assumption. apply optimize_0plus_com_sound. \n      SCase \"::=\".\n        destruct c2.\n          SSCase \"c2=SKIP\".\n          assert (H:cequiv (i::=a) (optimize_0plus_com (i::=a))).\n          apply optimize_0plus_com_sound. \n          assert (H1: cequiv (i::=a;;SKIP) (i::=a)). \n          unfold cequiv. split. apply skip_right. apply skip_right. \n          apply trans_cequiv with (c2:=(i::=a)). assumption. assumption.\n        SSCase \"c2 = ::=\".\n          unfold constfold_0plus in IHc1. simpl in IHc1. \n          unfold constfold_0plus in IHc2. simpl in IHc2. simpl.\n          apply CSeq_congruence. assumption. assumption.\n        simpl.\n      apply optimize_0plus_com_sound.\n      assert (H:cequiv c2 (fold_constants_com c2)).\n      apply fold_constants_com_sound. \n      assert (H1: cequiv (SKIP;;c2) c2). \n      unfold cequiv. split. apply skip_left. apply skip_left. \n      apply trans_cequiv with (c2:=c2). assumption. apply optimize_0plus_com_sound. \n    assert (H: cequiv ((constfold_0plus c1);;(constfold_0plus c2)) (constfold_0plus (c1;; c2))).\n    unfold constfold_0plus. simpl.\n    induction c1.  \n    SCase \"c1=SKIP\". simpl.\n      unfold constfold_0plus in IHc2.\n      assert (H:cequiv c2 (fold_constants_com c2)).\n      apply fold_constants_com_sound. \n      assert (H1: cequiv (SKIP;;c2) c2). \n      unfold cequiv. split. apply skip_left. apply skip_left. \n      apply trans_cequiv with (c2:=c2). assumption. apply optimize_0plus_com_sound. \n    assumption.\n    \n\n\n\nassert (H: cequiv ((constfold_0plus c1);;(constfold_0plus c2)) (constfold_0plus (c1;; c2))).\n    \n    split.\n      SCase \"->\".\n        intros. inversion H. subst. unfold constfold_0plus.\n        destruct c1. simpl. unfold constfold_0plus in H5. simpl in H5. simpl.\n    unfold constfold_0plus. \n    destruct c1.\n    SCase \"c1=SKIP\". simpl.\n      unfold constfold_0plus in IHc2.\n      assert (H:cequiv c2 (fold_constants_com c2)).\n      apply fold_constants_com_sound. \n      assert (H1: cequiv (SKIP;;c2) c2). \n      unfold cequiv. split. apply skip_left. apply skip_left. \n      apply trans_cequiv with (c2:=c2). assumption. assumption.\n    SCase \"c1 = ::=\".\n      simpl. destruct c2.\n        SSCase \"c2=SKIP\".\n          assert (H:cequiv (i::=a) (optimize_0plus_com (i::=a))).\n          apply optimize_0plus_com_sound. \n          assert (H1: cequiv (i::=a;;SKIP) (i::=a)). \n          unfold cequiv. split. apply skip_right. apply skip_right. \n          apply trans_cequiv with (c2:=(i::=a)). assumption. assumption.\n        SSCase \"c2 = ::=\".\n          unfold constfold_0plus in IHc1. simpl in IHc1. \n          unfold constfold_0plus in IHc2. simpl in IHc2. simpl.\n          apply CSeq_congruence. assumption. assumption.\n        SSCase \"c2 = ;;\".\n          destruct c2_1. \n          SSSCase \"c2_1 = SKIP\". \n            unfold constfold_0plus. simpl. \n            unfold constfold_0plus in IHc1. simpl in IHc1.\n            unfold constfold_0plus in IHc2. simpl in IHc2. \n            apply CSeq_congruence. assumption. assumption.\n          SSSCase \"c2_1 = ::=\".\n          unfold constfold_0plus in IHc1. simpl in IHc1. \n          unfold constfold_0plus in IHc2. \n          unfold constfold_0plus. simpl.\n          destruct c2_2.\n            SSSSCase \"c2_2 = SKIP\". simpl.\n              apply CSeq_congruence. assumption. assumption.\n            SSSSCase \"c2_2 = ::=\".\n              simpl. apply CSeq_congruence. assumption. assumption.\n            SSSSCase \"c2_2 = ;;\". simpl.\n            \n    simpl.\ndestruct c2. simpl.\n      unfold cequiv. split. intros. inversion H. subst. inversion H2. subst. assumption.  \n      intros. apply E_Seq with (st':=st). apply E_Skip. assumption.\n      assert (H:cequiv (i::=a) (optimize_0plus_com (i ::= a))).\n      apply optimize_0plus_com_sound. \n      assert (H1: cequiv (SKIP;; i::= a) (i::=a)). \n      unfold cequiv. split. apply skip_left. apply skip_left. \n      apply trans_cequiv with (c2:= (i ::= a)). assumption. assumption.\n      assert (H1: cequiv (SKIP;; c2_1;; c2_2) (c2_1;; c2_2)).\n        unfold cequiv. split. apply skip_left. apply skip_left.\n      apply trans_cequiv with (c2:= (c2_1;; c2_2)). assumption. \n      assert (H:cequiv (c2_1;; c2_2) (optimize_0plus_com (c2_1;; c2_2))). apply optimize_0plus_com_sound. assumption.\n      simpl. unfold cequiv. split. intros.\n      inversion H. subst. inversion H2. subst.\n      assert (\n      replace (optimize_0plus_aexp a) with a. assumption.\n        apply \n\n\nunfold constfold_0plus in IHc1. simpl in IHc1. SKIP apply E_Seq in H.\n      replace (SKIP;; SKIP) with SKIP. apply refl_cequiv.\n        apply skip_left.\nQed.\n\n", "meta": {"author": "Sooram", "repo": "Software-Foundations", "sha": "9c668f5c8395919645406855cdc78a214afdafd1", "save_path": "github-repos/coq/Sooram-Software-Foundations", "path": "github-repos/coq/Sooram-Software-Foundations/Software-Foundations-9c668f5c8395919645406855cdc78a214afdafd1/P06.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2963333071717}}
{"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.SystemLemmas.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\n\nLemma do_delayed_queries_ptr :\n  forall h st st' ms ts cts,\n    do_delayed_queries h st = (st', ms, ts, cts) ->\n    ptr st' = ptr st.\nProof.\n  intros.\n  unfold do_delayed_queries, clear_delayed_queries in *.\n  break_match; find_inversion; auto.\nQed.\n\nLtac simpler := repeat (repeat find_inversion; subst; simpl in *); auto.\nLemma handle_msg_ptr :\n  forall h h' st m st' ms ts cts,\n    handle_msg h h' st m = (st', ms, ts, cts) ->\n    ptr st' = ptr st.\nProof.\n  intros.\n  unfold handle_msg in *.\n  repeat (break_match; simpler);\n    unfold handle_query_res in *; repeat (break_match; simpler);\n    unfold handle_query_req_busy in *; repeat (break_match; simpler);\n    unfold handle_stabilize in *; repeat (break_match; simpler);\n    unfold schedule_rectify_with in *; repeat (break_match; simpler);\n    unfold end_query in *; repeat (break_match; simpler);\n    unfold handle_rectify in *; repeat (break_match; simpler);\n    unfold start_query in *; repeat (break_match; simpler).\nQed.\n\n(*\nThis is a very good and easy invariant.  At a node h, ptr st is a copy\nof a pointer to h. It's set when the node starts up and never changed\nanywhere.\n\nUSED: In phase two.\n*)\nLemma ptr_correct :\n  forall gst h st,\n    reachable_st gst ->\n    sigma gst h = Some st ->\n    ptr st = make_pointer h.\nProof.\n  intros. induct_reachable_st.\n  - intros.\n    unfold initial_st in *.\n    find_apply_lem_hyp sigma_initial_st_start_handler; simpl in *; auto. subst.\n    unfold start_handler in *. repeat break_match; simpl; auto.\n  - intros. invcs H0; auto.\n    + update_destruct; subst; rewrite_update; auto.\n      now find_inversion.\n    + update_destruct; subst; rewrite_update; auto.\n      find_inversion.\n      unfold timeout_handler, timeout_handler_eff in *.\n      break_match.\n      * unfold tick_handler in *. break_match; simpl in *; try solve_by_inversion.\n        break_if; simpl in *; try solve_by_inversion.\n        unfold add_tick, start_query in *.\n        repeat break_let.\n        subst. find_inversion.\n        repeat break_match; simpl in *;\n          find_inversion; simpl; auto.\n      * unfold do_rectify in *. simpl in *.\n        break_match; simpl in *; try solve_by_inversion;\n        break_match; simpl in *; try solve_by_inversion;\n        break_match; simpl in *; try solve_by_inversion.\n        unfold start_query, update_pred in *;\n          repeat break_match; simpl in *; find_inversion; simpl; auto.\n      * simpl in *. find_inversion. auto.\n      * unfold request_timeout_handler in *.\n        repeat break_match; simpl in *; try solve_by_inversion.\n        subst. unfold update_pred, handle_query_timeout, do_delayed_queries in *.\n        repeat break_match; simpl in *; try find_inversion; simpl in *; auto;\n          repeat find_rewrite || find_injection;\n          simpl; eauto;\n            unfold start_query in *;\n          repeat break_match; try find_inversion; simpl in *; auto.\n    + update_destruct; subst; rewrite_update; auto.\n      find_inversion.\n      unfold recv_handler in *. repeat break_let. find_inversion.\n      find_apply_lem_hyp do_delayed_queries_ptr.\n      repeat find_rewrite.\n      find_apply_lem_hyp handle_msg_ptr.\n      repeat find_rewrite. auto.\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/PtrCorrectInvariant.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2963332999770349}}
{"text": "From Autosubst Require Import Autosubst.\nFrom iris.algebra Require Export list.\nFrom iris.proofmode Require Import proofmode.\nFrom self.prob_lang Require Import metatheory primitive_laws.\nFrom self.prelude Require Import asubst properness.\nFrom self.logrel Require Import model.\nFrom self.typing Require Import types.\n\n(** * Interpretation of types *)\nSection semtypes.\n  Context `{!prelogrelGS Σ}.\n\n  Program Definition ctx_lookup (x : var) : listO (lrelC Σ) -n> (lrelC Σ)\n    := λne Δ, (from_option id lrel_true (Δ !! x))%I.\n  Next Obligation.\n    intros x n Δ Δ' HΔ.\n    destruct (Δ !! x) as [P|] eqn:HP; cbn in *.\n    - eapply (Forall2_lookup_l _ _ _ x P) in HΔ; last done.\n      destruct HΔ as (Q & HQ & HΔ).\n      rewrite HQ /= //.\n    - destruct (Δ' !! x) as [Q|] eqn:HQ; last reflexivity.\n      eapply (Forall2_lookup_r _ _ _ x Q) in HΔ; last done.\n      destruct HΔ as (P & HP' & HΔ). exfalso.\n      rewrite HP in HP'. inversion HP'.\n  Qed.\n\n  Program Fixpoint interp (τ : type) : listO (lrelC Σ) -n> lrelC Σ :=\n    match τ as _ return listO (lrelC Σ) -n> lrelC Σ with\n    | TUnit => λne _, lrel_unit\n    | TInt => λne _, lrel_int\n    | TBool => λne _, lrel_bool\n    | TProd τ1 τ2 => λne Δ, lrel_prod (interp τ1 Δ) (interp τ2 Δ)\n    | TSum τ1 τ2 => λne Δ, lrel_sum (interp τ1 Δ) (interp τ2 Δ)\n    | TArrow τ1 τ2 => λne Δ, lrel_arr (interp τ1 Δ) (interp τ2 Δ)\n    | TRec τ' => λne Δ, lrel_rec (λne τ, interp τ' (τ::Δ))\n    | TVar x => ctx_lookup x\n    | TForall τ' => λne Δ, lrel_forall (λ τ, interp τ' (τ::Δ))\n    | TExists τ' => λne Δ, lrel_exists (λ τ, interp τ' (τ::Δ))\n    | TRef τ => λne Δ, lrel_ref (interp τ Δ)\n    | TTape => λne Δ, lrel_tape\n    end.\n  Solve Obligations with (intros I τ τ' n Δ Δ' HΔ' ??; try solve_proper).\n  Next Obligation.\n    intros I τ τ' n Δ Δ' HΔ' ??.\n    apply lrel_rec_ne=> X /=.\n    apply I. by f_equiv.\n  Defined.\n\n  Lemma unboxed_type_sound τ Δ v v' :\n    UnboxedType τ →\n    interp τ Δ v v' -∗ ⌜val_is_unboxed v ∧ val_is_unboxed v'⌝.\n  Proof.\n    induction 1; simpl;\n    first [iDestruct 1 as (? ?) \"[% [% ?]]\"\n          |iDestruct 1 as (?) \"[% %]\"\n          |iIntros \"[% %]\"];\n    simplify_eq/=; eauto with iFrame.\n  Qed.\n\n  Lemma eq_type_sound τ Δ v v' :\n    EqType τ →\n    interp τ Δ v v' -∗ ⌜v = v'⌝.\n  Proof.\n    intros Hτ; revert v v'; induction Hτ; iIntros (v v') \"#H1 /=\".\n    - by iDestruct \"H1\" as %[-> ->].\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.\n\n  Lemma unboxed_type_eq τ Δ v1 v2 w1 w2 :\n    UnboxedType τ →\n    interp τ Δ v1 v2 -∗\n    interp τ Δ w1 w2 -∗\n    |={⊤}=> ⌜v1 = w1 ↔ v2 = w2⌝.\n  Proof.\n    intros Hunboxed.\n    cut (EqType τ ∨ (∃ τ', τ = TRef τ') ∨ τ = TTape).\n    { intros [Hτ | [[τ' ->] | ->]].\n      - rewrite !eq_type_sound //.\n        iIntros \"% %\". iModIntro.\n        iPureIntro. naive_solver.\n      - rewrite /lrel_car /=.\n        iDestruct 1 as (l1 l2 -> ->) \"Hl\".\n        iDestruct 1 as (r1 r2 -> ->) \"Hr\".\n        destruct (decide (l1 = r1)); subst.\n        + destruct (decide (l2 = r2)); subst; first by eauto.\n          iInv (logN.@(r1, l2)) as (v1 v2) \"(>Hr1 & >Hr2 & Hinv1)\".\n          iInv (logN.@(r1, r2)) as (w1 w2) \"(>Hr1' & >Hr2' & Hinv2)\".\n          iExFalso. by iDestruct (ghost_map_elem_valid_2 with \"Hr1 Hr1'\") as %[].\n        + destruct (decide (l2 = r2)); subst; last first.\n          { iModIntro. iPureIntro. naive_solver. }\n          iInv (logN.@(r1, r2)) as (v1 v2) \"(>Hr1 & >Hr2 & Hinv1)\".\n          iInv (logN.@(l1, r2)) as (w1 w2) \"(>Hr1' & >Hr2' & Hinv2)\".\n          iExFalso. by iDestruct (ghost_map_elem_valid_2 with \"Hr2 Hr2'\") as %[].       - rewrite /lrel_car /=.\n        iDestruct 1 as (l1 l2 -> ->) \"Hl\".\n        iDestruct 1 as (r1 r2 -> ->) \"Hr\".\n        destruct (decide (l1 = r1)); subst.\n        + destruct (decide (l2 = r2)); subst; first by eauto.\n          iInv (logN.@(r1, l2)) as \"> (Hr1 & Hl2)\".\n          iInv (logN.@(r1, r2)) as \"> (Hr1' & Hr2')\".\n          iExFalso. by iDestruct (ghost_map_elem_valid_2 with \"Hr1 Hr1'\") as %[].\n        + destruct (decide (l2 = r2)); subst; last first.\n          { iModIntro. iPureIntro. naive_solver. }\n          iInv (logN.@(r1, r2)) as \"> (Hr1 & Hr2)\".\n          iInv (logN.@(l1, r2)) as \"> (Hl1 & Hr2')\".\n          iExFalso. by iDestruct (ghost_map_elem_valid_2 with \"Hr2 Hr2'\") as %[]. }\n    by apply unboxed_type_ref_or_eqtype.\n  Qed.\n\nEnd semtypes.\n\n(** ** Properties of the type inrpretation w.r.t. the substitutions *)\nSection interp_ren.\n  Context `{!prelogrelGS Σ}.\n  Implicit Types Δ : list (lrel Σ).\n\n  (* TODO: why do I need to unfold lrel_car here? *)\n  Lemma interp_ren_up (Δ1 Δ2 : list (lrel Σ)) τ τi :\n    interp τ (Δ1 ++ Δ2) ≡ interp (τ.[upn (length Δ1) (ren (+1))]) (Δ1 ++ τi :: Δ2).\n  Proof.\n    revert Δ1 Δ2. induction τ => Δ1 Δ2; simpl; eauto;\n    try by\n      (intros ? ?; unfold lrel_car; simpl; properness; repeat f_equiv=>//).\n    - apply fixpoint_proper=> τ' w1 w2 /=.\n      unfold lrel_car. simpl.\n      properness; auto. apply (IHτ (_ :: _)).\n    - intros v1 v2; unfold lrel_car; simpl;\n        simpl; properness; auto.\n      rewrite /lrel_car /=. properness; auto.\n      apply refines_proper=> //. apply (IHτ (_ :: _)).\n    - intros ??; unfold lrel_car; simpl; properness; auto. apply (IHτ (_ :: _)).\n    - intros v1 v2; simpl.\n      rewrite iter_up. case_decide; simpl; properness.\n      { by rewrite !lookup_app_l. }\n      change (bi_ofeO (uPredI (iResUR Σ))) with (uPredO (iResUR Σ)).\n      rewrite !lookup_app_r; [|lia..].\n      assert (∀ x, (length Δ1 + S (x - length Δ1) - length Δ1) = S (x - length Δ1)) as Hwat.\n      { lia. }\n      rewrite Hwat. simpl. done.\n  Qed.\n\n  Lemma interp_ren A Δ (Γ : gmap string type) :\n    ((λ τ, interp τ (A::Δ)) <$> ⤉Γ) ≡ ((λ τ, interp τ Δ) <$> Γ).\n  Proof.\n    rewrite -map_fmap_compose => x /=.\n    rewrite !lookup_fmap.\n    destruct (Γ !! x); auto; simpl. f_equiv.\n    symmetry. apply (interp_ren_up []).\n  Qed.\n\n  Lemma interp_weaken (Δ1 Π Δ2 : list (lrel Σ)) τ :\n    interp (τ.[upn (length Δ1) (ren (+ length Π))]) (Δ1 ++ Π ++ Δ2)\n    ≡ interp τ (Δ1 ++ Δ2).\n  Proof.\n    revert Δ1 Π Δ2. induction τ=> Δ1 Π Δ2; simpl; eauto;\n    try by\n      (intros ? ?; simpl; unfold lrel_car; simpl; repeat f_equiv =>//).\n    - apply fixpoint_proper=> τi ?? /=.\n      unfold lrel_car; simpl.\n      properness; auto. apply (IHτ (_ :: _)).\n    - intros ??; simpl; unfold lrel_car; simpl;\n      properness; auto.\n      rewrite /lrel_car /=. properness; auto.\n      apply refines_proper=> //. apply (IHτ (_ :: _)).\n    - intros ??; unfold lrel_car; simpl; properness; auto.\n        by apply (IHτ (_ :: _)).\n    - intros ??; simpl; properness; auto.\n      rewrite iter_up; case_decide; properness; simpl.\n      { by rewrite !lookup_app_l. }\n      rewrite !lookup_app_r ;[| lia ..]. do 3 f_equiv. lia.\n  Qed.\n\n  Lemma interp_subst_up (Δ1 Δ2 : list (lrel Σ)) τ τ' :\n    interp τ (Δ1 ++ interp τ' Δ2 :: Δ2)\n    ≡ interp (τ.[upn (length Δ1) (τ' .: ids)]) (Δ1 ++ Δ2).\n  Proof.\n    revert Δ1 Δ2; induction τ=> Δ1 Δ2; simpl; eauto;\n    try by\n      (intros ? ?; unfold lrel_car; simpl; properness; repeat f_equiv=>//).\n    - apply fixpoint_proper=> τi ?? /=.\n      unfold lrel_car. simpl.\n      properness; auto. apply (IHτ (_ :: _)).\n    - intros ??. unfold lrel_car; simpl;\n      properness; auto.\n      rewrite /lrel_car /=. properness; auto.\n      apply refines_proper=>//. apply (IHτ (_ :: _)).\n    - intros ??; unfold lrel_car; simpl; properness; auto. apply (IHτ (_ :: _)).\n    - intros w1 w2; simpl.\n      rewrite iter_up; case_decide; simpl; properness.\n      { by rewrite !lookup_app_l. }\n      rewrite !lookup_app_r; [|lia..].\n      case EQ: (_ - length Δ1)=> [|n]; simpl.\n      { symmetry.\n        pose (HW := interp_weaken [] Δ1 Δ2 τ' w1 w2).\n        etrans; last by apply HW.\n        asimpl. reflexivity. }\n      rewrite !lookup_app_r; [|lia ..]. repeat f_equiv. lia.\n  Qed.\n\n  Lemma interp_subst Δ2 τ τ' :\n    interp τ (interp τ' Δ2 :: Δ2) ≡ interp (τ.[τ'/]) Δ2.\n  Proof. apply (interp_subst_up []). Qed.\nEnd interp_ren.\n\n(** * Interpretation of the environments *)\nSection env_typed.\n  Context `{!prelogrelGS Σ}.\n  Implicit Types A B : lrel Σ.\n  Implicit Types Γ : gmap string (lrel Σ).\n\n  (** Substitution [vs] is well-typed w.r.t. [Γ] *)\n  Definition env_ltyped2 (Γ : gmap string (lrel Σ))\n    (vs : gmap string (val*val)) : iProp Σ :=\n    ([∗ map] i ↦ A;vv ∈ Γ;vs, lrel_car A vv.1 vv.2)%I.\n\n  Notation \"⟦ Γ ⟧*\" := (env_ltyped2 Γ).\n\n  (* TODO: make a separate instance for big_sepM2 *)\n  Global Instance env_ltyped2_ne n :\n    Proper (dist n ==> (=) ==> dist n) env_ltyped2.\n  Proof.\n    intros Γ Γ' HΓ ? vvs ->. apply big_sepM2_ne_2; [done..|solve_proper].\n  Qed.\n\n  Global Instance env_ltyped2_proper :\n    Proper ((≡) ==> (=) ==> (≡)) env_ltyped2.\n  Proof. solve_proper_from_ne. Qed.\n\n  Lemma env_ltyped2_lookup Γ vs x A :\n    Γ !! x = Some A →\n    ⟦ Γ ⟧* vs -∗ ∃ v1 v2, ⌜ vs !! x = Some (v1,v2) ⌝ ∧ A v1 v2.\n  Proof.\n    intros ?. rewrite /env_ltyped2 big_sepM2_lookup_l //.\n    iDestruct 1 as ([v1 v2] ?) \"H\". eauto with iFrame.\n  Qed.\n\n  Lemma env_ltyped2_insert Γ vs x A v1 v2 :\n    A v1 v2 -∗ ⟦ Γ ⟧* vs -∗\n    ⟦ (binder_insert x A Γ) ⟧* (binder_insert x (v1,v2) vs).\n  Proof.\n    destruct x as [|x]=> /=; first by auto.\n    rewrite /env_ltyped2. iIntros \"HA HΓ\".\n    now iApply (big_sepM2_insert_2 with \"[HA] [HΓ]\").\n  Qed.\n\n  Lemma env_ltyped2_empty :\n    ⊢ ⟦ ∅ ⟧* ∅.\n  Proof. apply (big_sepM2_empty' _). Qed.\n\n  Lemma env_ltyped2_empty_inv vs :\n    ⟦ ∅ ⟧* vs -∗ ⌜vs = ∅⌝.\n  Proof. apply big_sepM2_empty_r. Qed.\n\n  Global Instance env_ltyped2_persistent Γ vs : Persistent (⟦ Γ ⟧* vs).\n  Proof. apply _. Qed.\nEnd env_typed.\n\nNotation \"⟦ Γ ⟧*\" := (env_ltyped2 Γ).\n\n(** * The semantic typing judgement *)\nSection bin_log_related.\n  Context `{!prelogrelGS Σ}.\n\n  Definition bin_log_related (E : coPset)\n             (Δ : list (lrel Σ)) (Γ : stringmap type)\n             (e e' : expr) (τ : type) : iProp Σ :=\n    (∀ vs, ⟦ (λ τ, interp τ Δ) <$> Γ ⟧* vs -∗\n           REL (subst_map (fst <$> vs) e)\n            << (subst_map (snd <$> vs) e') @ E : (interp τ Δ))%I.\n\nEnd bin_log_related.\n\nNotation \"'{' E ';' Δ ';' Γ '}' ⊨ e '≤log≤' e' : τ\" :=\n  (bin_log_related E Δ Γ e%E e'%E (τ)%ty)\n  (at level 100, E at next level, Δ at next level, Γ at next level, e, e' at next level,\n   τ at level 200,\n   format \"'[hv' '{' E ';'  Δ ';'  Γ '}'  ⊨  '/  ' e  '/' '≤log≤'  '/  ' e'  :  τ ']'\").\nNotation \"'{' Δ ';' Γ '}' ⊨ e '≤log≤' e' : τ\" :=\n  (bin_log_related ⊤ Δ Γ e%E e'%E (τ)%ty)\n  (at level 100, Δ at next level, Γ at next level, e, e' at next level,\n   τ at level 200,\n   format \"'[hv' '{' Δ ';'  Γ '}'  ⊨  '/  ' e  '/' '≤log≤'  '/  ' e'  :  τ ']'\").\n", "meta": {"author": "logsem", "repo": "clutch", "sha": "35144f9b1fe9c913b4bd24106a12ac7f02b20ec5", "save_path": "github-repos/coq/logsem-clutch", "path": "github-repos/coq/logsem-clutch/clutch-35144f9b1fe9c913b4bd24106a12ac7f02b20ec5/theories/typing/interp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.2962663124319514}}
{"text": "(* ** AES-NI *)\n(* From eclib/AES.ec *)\n\n(* ** Imports and settings *)\n\nFrom mathcomp Require Import all_ssreflect all_algebra.\nFrom mathcomp Require Import word_ssrZ word.\nRequire Import word.\nRequire Import Psatz ZArith utils.\nImport Utf8.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport ssrnat.\n\nLocal Open Scope Z_scope.\n\n(* -------------------------------------------------------------- *)\n\nDefinition Sbox (v1 : u8) : u8 :=\n  wrepr U8 match toword v1 with\n  | 0 => 99    | 1 => 124   | 2 => 119   | 3 => 123   | 4 => 242\n  | 5 => 107   | 6 => 111   | 7 => 197   | 8 => 48    | 9 => 1\n  | 10 => 103  | 11 => 43   | 12 => 254  | 13 => 215  | 14 => 171\n  | 15 => 118  | 16 => 202  | 17 => 130  | 18 => 201  | 19 => 125\n  | 20 => 250  | 21 => 89   | 22 => 71   | 23 => 240  | 24 => 173\n  | 25 => 212  | 26 => 162  | 27 => 175  | 28 => 156  | 29 => 164\n  | 30 => 114  | 31 => 192  | 32 => 183  | 33 => 253  | 34 => 147\n  | 35 => 38   | 36 => 54   | 37 => 63   | 38 => 247  | 39 => 204\n  | 40 => 52   | 41 => 165  | 42 => 229  | 43 => 241  | 44 => 113\n  | 45 => 216  | 46 => 49   | 47 => 21   | 48 => 4    | 49 => 199\n  | 50 => 35   | 51 => 195  | 52 => 24   | 53 => 150  | 54 => 5\n  | 55 => 154  | 56 => 7    | 57 => 18   | 58 => 128  | 59 => 226\n  | 60 => 235  | 61 => 39   | 62 => 178  | 63 => 117  | 64 => 9\n  | 65 => 131  | 66 => 44   | 67 => 26   | 68 => 27   | 69 => 110\n  | 70 => 90   | 71 => 160  | 72 => 82   | 73 => 59   | 74 => 214\n  | 75 => 179  | 76 => 41   | 77 => 227  | 78 => 47   | 79 => 132\n  | 80 => 83   | 81 => 209  | 82 => 0    | 83 => 237  | 84 => 32\n  | 85 => 252  | 86 => 177  | 87 => 91   | 88 => 106  | 89 => 203\n  | 90 => 190  | 91 => 57   | 92 => 74   | 93 => 76   | 94 => 88\n  | 95 => 207  | 96 => 208  | 97 => 239  | 98 => 170  | 99 => 251\n  | 100 => 67  | 101 => 77  | 102 => 51  | 103 => 133 | 104 => 69\n  | 105 => 249 | 106 => 2   | 107 => 127 | 108 => 80  | 109 => 60\n  | 110 => 159 | 111 => 168 | 112 => 81  | 113 => 163 | 114 => 64\n  | 115 => 143 | 116 => 146 | 117 => 157 | 118 => 56  | 119 => 245\n  | 120 => 188 | 121 => 182 | 122 => 218 | 123 => 33  | 124 => 16\n  | 125 => 255 | 126 => 243 | 127 => 210 | 128 => 205 | 129 => 12\n  | 130 => 19  | 131 => 236 | 132 => 95  | 133 => 151 | 134 => 68\n  | 135 => 23  | 136 => 196 | 137 => 167 | 138 => 126 | 139 => 61\n  | 140 => 100 | 141 => 93  | 142 => 25  | 143 => 115 | 144 => 96\n  | 145 => 129 | 146 => 79  | 147 => 220 | 148 => 34  | 149 => 42\n  | 150 => 144 | 151 => 136 | 152 => 70  | 153 => 238 | 154 => 184\n  | 155 => 20  | 156 => 222 | 157 => 94  | 158 => 11  | 159 => 219\n  | 160 => 224 | 161 => 50  | 162 => 58  | 163 => 10  | 164 => 73\n  | 165 => 6   | 166 => 36  | 167 => 92  | 168 => 194 | 169 => 211\n  | 170 => 172 | 171 => 98  | 172 => 145 | 173 => 149 | 174 => 228\n  | 175 => 121 | 176 => 231 | 177 => 200 | 178 => 55  | 179 => 109\n  | 180 => 141 | 181 => 213 | 182 => 78  | 183 => 169 | 184 => 108\n  | 185 => 86  | 186 => 244 | 187 => 234 | 188 => 101 | 189 => 122\n  | 190 => 174 | 191 => 8   | 192 => 186 | 193 => 120 | 194 => 37\n  | 195 => 46  | 196 => 28  | 197 => 166 | 198 => 180 | 199 => 198\n  | 200 => 232 | 201 => 221 | 202 => 116 | 203 => 31  | 204 => 75\n  | 205 => 189 | 206 => 139 | 207 => 138 | 208 => 112 | 209 => 62\n  | 210 => 181 | 211 => 102 | 212 => 72  | 213 => 3   | 214 => 246\n  | 215 => 14  | 216 => 97  | 217 => 53  | 218 => 87  | 219 => 185\n  | 220 => 134 | 221 => 193 | 222 => 29  | 223 => 158 | 224 => 225\n  | 225 => 248 | 226 => 152 | 227 => 17  | 228 => 105 | 229 => 217\n  | 230 => 142 | 231 => 148 | 232 => 155 | 233 => 30  | 234 => 135\n  | 235 => 233 | 236 => 206 | 237 => 85  | 238 => 40  | 239 => 223\n  | 240 => 140 | 241 => 161 | 242 => 137 | 243 => 13  | 244 => 191\n  | 245 => 230 | 246 => 66  | 247 => 104 | 248 => 65  | 249 => 153\n  | 250 => 45  | 251 => 15  | 252 => 176 | 253 => 84  | 254 => 187\n  | 255 => 22  | _ => 0\n  end.\n\nDefinition InvSbox (v1 : u8) :=\n  wrepr U8 match toword v1 with\n  | 0 => 82    | 1 => 9     | 2 => 106   | 3 => 213   | 4 => 48\n  | 5 => 54    | 6 => 165   | 7 => 56    | 8 => 191   | 9 => 64\n  | 10 => 163  | 11 => 158  | 12 => 129  | 13 => 243  | 14 => 215\n  | 15 => 251  | 16 => 124  | 17 => 227  | 18 => 57   | 19 => 130\n  | 20 => 155  | 21 => 47   | 22 => 255  | 23 => 135  | 24 => 52\n  | 25 => 142  | 26 => 67   | 27 => 68   | 28 => 196  | 29 => 222\n  | 30 => 233  | 31 => 203  | 32 => 84   | 33 => 123  | 34 => 148\n  | 35 => 50   | 36 => 166  | 37 => 194  | 38 => 35   | 39 => 61\n  | 40 => 238  | 41 => 76   | 42 => 149  | 43 => 11   | 44 => 66\n  | 45 => 250  | 46 => 195  | 47 => 78   | 48 => 8    | 49 => 46\n  | 50 => 161  | 51 => 102  | 52 => 40   | 53 => 217  | 54 => 36\n  | 55 => 178  | 56 => 118  | 57 => 91   | 58 => 162  | 59 => 73\n  | 60 => 109  | 61 => 139  | 62 => 209  | 63 => 37   | 64 => 114\n  | 65 => 248  | 66 => 246  | 67 => 100  | 68 => 134  | 69 => 104\n  | 70 => 152  | 71 => 22   | 72 => 212  | 73 => 164  | 74 => 92\n  | 75 => 204  | 76 => 93   | 77 => 101  | 78 => 182  | 79 => 146\n  | 80 => 108  | 81 => 112  | 82 => 72   | 83 => 80   | 84 => 253\n  | 85 => 237  | 86 => 185  | 87 => 218  | 88 => 94   | 89 => 21\n  | 90 => 70   | 91 => 87   | 92 => 167  | 93 => 141  | 94 => 157\n  | 95 => 132  | 96 => 144  | 97 => 216  | 98 => 171  | 99 => 0\n  | 100 => 140 | 101 => 188 | 102 => 211 | 103 => 10  | 104 => 247\n  | 105 => 228 | 106 => 88  | 107 => 5   | 108 => 184 | 109 => 179\n  | 110 => 69  | 111 => 6   | 112 => 208 | 113 => 44  | 114 => 30\n  | 115 => 143 | 116 => 202 | 117 => 63  | 118 => 15  | 119 => 2\n  | 120 => 193 | 121 => 175 | 122 => 189 | 123 => 3   | 124 => 1\n  | 125 => 19  | 126 => 138 | 127 => 107 | 128 => 58  | 129 => 145\n  | 130 => 17  | 131 => 65  | 132 => 79  | 133 => 103 | 134 => 220\n  | 135 => 234 | 136 => 151 | 137 => 242 | 138 => 207 | 139 => 206\n  | 140 => 240 | 141 => 180 | 142 => 230 | 143 => 115 | 144 => 150\n  | 145 => 172 | 146 => 116 | 147 => 34  | 148 => 231 | 149 => 173\n  | 150 => 53  | 151 => 133 | 152 => 226 | 153 => 249 | 154 => 55\n  | 155 => 232 | 156 => 28  | 157 => 117 | 158 => 223 | 159 => 110\n  | 160 => 71  | 161 => 241 | 162 => 26  | 163 => 113 | 164 => 29\n  | 165 => 41  | 166 => 197 | 167 => 137 | 168 => 111 | 169 => 183\n  | 170 => 98  | 171 => 14  | 172 => 170 | 173 => 24  | 174 => 190\n  | 175 => 27  | 176 => 252 | 177 => 86  | 178 => 62  | 179 => 75\n  | 180 => 198 | 181 => 210 | 182 => 121 | 183 => 32  | 184 => 154\n  | 185 => 219 | 186 => 192 | 187 => 254 | 188 => 120 | 189 => 205\n  | 190 => 90  | 191 => 244 | 192 => 31  | 193 => 221 | 194 => 168\n  | 195 => 51  | 196 => 136 | 197 => 7   | 198 => 199 | 199 => 49\n  | 200 => 177 | 201 => 18  | 202 => 16  | 203 => 89  | 204 => 39\n  | 205 => 128 | 206 => 236 | 207 => 95  | 208 => 96  | 209 => 81\n  | 210 => 127 | 211 => 169 | 212 => 25  | 213 => 181 | 214 => 74\n  | 215 => 13  | 216 => 45  | 217 => 229 | 218 => 122 | 219 => 159\n  | 220 => 147 | 221 => 201 | 222 => 156 | 223 => 239 | 224 => 160\n  | 225 => 224 | 226 => 59  | 227 => 77  | 228 => 174 | 229 => 42\n  | 230 => 245 | 231 => 176 | 232 => 200 | 233 => 235 | 234 => 187\n  | 235 => 60  | 236 => 131 | 237 => 83  | 238 => 153 | 239 => 97\n  | 240 => 23  | 241 => 43  | 242 => 4   | 243 => 126 | 244 => 186\n  | 245 => 119 | 246 => 214 | 247 => 38  | 248 => 225 | 249 => 105\n  | 250 => 20  | 251 => 99  | 252 => 85  | 253 => 33  | 254 => 12\n  | 255 => 125 | _ => 0\n  end.\n\n(* NOTE: SubWord clashes with subword *)\nDefinition SubWord (v1 : u32) :=\n  make_vec U32 (map Sbox (split_vec U8 v1)).\nDefinition InvSubWord (v1 : u32) :=\n  make_vec U32 (map InvSbox (split_vec U8 v1)).\nDefinition RotWord (v1 : u32) :=\n  make_vec U32 [:: (subword (1 * U8) U8 v1); subword (2 * U8) U8 v1; subword (3 * U8) U8 v1; subword (0 * U8) U8 v1].\n\nDefinition to_matrix (s : u128) :=\n  let s_ := fun i j => (subword (i * U8) U8 (subword (j * U32) U32 s)) in\n  (s_ 0 0, s_ 0 1, s_ 0 2, s_ 0 3,\n    s_ 1 0, s_ 1 1, s_ 1 2, s_ 1 3,\n    s_ 2 0, s_ 2 1, s_ 2 2, s_ 2 2,\n    s_ 3 0, s_ 3 1, s_ 3 2, s_ 3 3)%nat.\n\nDefinition to_state (m : u8 * u8 * u8 * u8 * u8 * u8 * u8 * u8 * u8 * u8 * u8 * u8 * u8 * u8 * u8 * u8) :=\n  let '(s00, s01, s02, s03,\n        s10, s11, s12, s13,\n        s20, s21, s22, s23,\n        s30, s31, s32, s33) := m in\n  let c0 := make_vec U32 [:: s00; s10; s20; s30] in\n  let c1 := make_vec U32 [:: s01; s11; s21; s31] in\n  let c2 := make_vec U32 [:: s02; s12; s22; s32] in\n  let c3 := make_vec U32 [:: s03; s13; s23; s33] in\n  make_vec U128 [:: c0; c1; c2; c3].\n\nDefinition SubBytes (s : u128) :=\n  make_vec U128 (map SubWord (split_vec U32 s)).\nDefinition InvSubBytes (s : u128) :=\n  make_vec U128 (map InvSubWord (split_vec U32 s)).\n\nDefinition ShiftRows (s : u128) :=\n let '(s00, s01, s02, s03,\n       s10, s11, s12, s13,\n       s20, s21, s22, s23,\n       s30, s31, s32, s33) := to_matrix s in\n to_state (s00, s01, s02, s03,\n           s11, s12, s13, s10,\n           s22, s23, s20, s21,\n           s33, s30, s31, s32).\n\nDefinition InvShiftRows (s : u128) :=\n let '(s00, s01, s02, s03,\n       s11, s12, s13, s10,\n       s22, s23, s20, s21,\n       s33, s30, s31, s32) := to_matrix s in\n to_state\n    (s00, s01, s02, s03,\n     s10, s11, s12, s13,\n     s20, s21, s22, s23,\n     s30, s31, s32, s33).\n\n(* TODO: Implement these *)\nParameter MixColumns : u128 -> u128.\nParameter InvMixColumns : u128 -> u128.\n\nDefinition wAESDEC (state rkey : u128) :=\n  let state := InvShiftRows state in\n  let state := InvSubBytes state in\n  let state := InvMixColumns state in\n  wxor state rkey.\n\nDefinition wAESDECLAST (state rkey : u128) :=\n  let state := InvShiftRows state in\n  let state := InvSubBytes state in\n  wxor state rkey.\n\nDefinition wAESENC (state rkey : u128) :=\n  let state := ShiftRows state in\n  let state := SubBytes state in\n  let state := MixColumns state in\n  wxor state rkey.\n\nDefinition wAESENCLAST (state rkey : u128) :=\n  let state := ShiftRows state in\n  let state := SubBytes state in\n  wxor state rkey.\n\nNotation wAESIMC := InvMixColumns.\n\nDefinition wAESKEYGENASSIST (v1 : u128) (v2 : u8) :=\n  let rcon := zero_extend U32 v2 in\n  let x1 := subword (1 * U32) U32 v1 in\n  let x3 := subword (3 * U32) U32 v1 in\n  let y0 := SubWord x1 in\n  let y1 := wxor (RotWord (SubWord x1)) rcon in\n  let y2 := SubWord x3 in\n  let y3 := wxor (RotWord (SubWord x3)) rcon in\n  make_vec U128 [:: y0; y1; y2; y3].\n\nDefinition wAESENC_ (state rkey: u128) :=\n  let state := SubBytes state in\n  let state := ShiftRows state in\n  let state := MixColumns state in\n  wxor state rkey.\n\nDefinition wAESENCLAST_ (state rkey: u128) :=\n  let state := SubBytes state in\n  let state := ShiftRows state in\n  wxor state rkey.\n\nDefinition wAESDEC_ (state rkey: u128) :=\n  let state := InvShiftRows state in\n  let state := InvSubBytes state in\n  let state := wxor state rkey in\n  InvMixColumns state.\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/waes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7341195152660688, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2962663030416656}}
{"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  | G symb ofs => v = symbol_address ge symb ofs\n  | S ofs => v = Val.add sp (Vint ofs)\n  | _ => 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 (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  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 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 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 H. apply make_andimm_correct; auto.\n(* or *)\n  InvApproxRegs. SimplVMA. inv H0; rewrite H. apply make_orimm_correct; auto.\n(* xor *)\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(* default *)\n  exists v; auto.\nQed.\n\nEnd STRENGTH_REDUCTION.\n\nEnd ANALYSIS.\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/ia32/ConstpropOpproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.29626561919677047}}
{"text": "Require Import Coq.Logic.Eqdep_dec.\nRequire Import Coq.Bool.Bool.\nFrom mathcomp Require Import all_ssreflect.\nRequire Import PreOrders.\nRequire Import Types.\nRequire Import Cover.\nRequire Import FCL.\nRequire Import DependentFixpoint.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nDelimit Scope it_scope with IT.\nOpen Scope it_scope.\n\nDelimit Scope alg_scope with ALG.\nOpen Scope alg_scope.\n\nImport EqNotations.\n\nNotation \"[ 'sort' c <= d ]\" := (lessOrEqual c d) (at level 0, c at next level): alg_scope.\n\nModule SignatureFamily.\n  Record mixin_of (I: Type) (S: preOrdered) (O: finType): Type :=\n    Mixin {\n        arity: I -> O -> nat;\n        dom: forall i o, (arity i o).-tuple S;\n        range: I -> O -> S;\n      }.\n  Section ClassDef.\n    Structure class_of (I: Type) (S: Type) (O: Type) :=\n      Class {\n          sort_base: PreOrdered.class_of S;\n          operation_base: Finite.class_of O;  \n          mixin: mixin_of I\n                   (PreOrdered.Pack S sort_base)\n                   (@Finite.Pack O operation_base)\n        }.\n    Local Coercion operation_base : class_of >-> Finite.class_of.\n    Local Coercion sort_base : class_of >-> PreOrdered.class_of.\n    Structure type I := Pack { sort_sort : Type; operation_sort: Type; _ : class_of I sort_sort operation_sort }.\n    Variables (I: Type) (S: Type) (O: Type) (sigFam: type I).\n    Definition class := let: Pack _ _ c as sigFam' := sigFam return class_of I\n                                                                             (sort_sort I sigFam')\n                                                                             (operation_sort I sigFam')\n                        in c.\n    Definition clone c of phant_id class c := @Pack S O c.\n    Let xSort := (let: Pack S _ _ := sigFam in S).\n    Let xOperation := (let: Pack _ O _ := sigFam in O).\n    Notation xclass := (class : class_of I xSort xOperation).\n    Definition pack b0 b1 (m0: mixin_of I (PreOrdered.Pack S b1) (@Finite.Pack O b0)) :=\n      fun bSort bsort & phant_id (PreOrdered.class bSort) bsort =>\n        fun bOperation boperation & phant_id (Finite.class bOperation) boperation =>\n          fun m & phant_id m0 m => Pack I S O (@Class I S O bsort boperation m).\n\n    Definition operationEqType := Eval hnf in @Equality.Pack xOperation xclass.\n    Definition operationChoiceType := Eval hnf in  @Choice.Pack xOperation xclass.\n    Definition operationCountType := Eval hnf in  @Countable.Pack xOperation xclass.\n    Definition finType := Eval hnf in  @Finite.Pack xOperation xclass.\n\n    Definition sortEqType := Eval hnf in @Equality.Pack xSort (PreOrdered.base _ xclass).\n    Definition ctorCountType := Eval hnf in @Countable.Pack xSort (PreOrdered.base _ xclass).\n    Definition preOrdered := Eval hnf in  @PreOrdered.Pack xSort xclass.\n  End ClassDef.\n\n  Module Import Exports.\n    Coercion mixin: class_of >-> mixin_of.\n    Coercion preOrdered : type >-> PreOrdered.type.\n    Canonical preOrdered.\n    Coercion finType: type >-> Finite.type.\n    Canonical finType.\n\n    Notation sigFam := type.\n    Notation SignatureFamilyMixin := Mixin.\n    Notation SignatureFamilyType I S O m := (@pack I S O _ _ m _ _ id _ _ id m id).\n    Notation \"[ 'sigFam' I 'of' S ',' O 'for' sigFam ]\" :=\n      (@clone I S O sigFam _ idfun)\n        (at level 0, format \"[ 'sigFam' I 'of' S ',' O 'for' sigFam ]\") : form_scope.\n    Notation \"[ 'sigFam' I 'of' S ',' O ]\" :=\n      (@clone I S O _ _ id) (at level 0, format \"[ 'sigFam' I 'of' S ',' O ]\") : form_scope.\n  End Exports.\nEnd SignatureFamily.\n\nExport SignatureFamily.Exports.\n\nDefinition sort {I: Type} (Sigma: sigFam I): preOrdered :=\n  SignatureFamily.preOrdered I Sigma.\nDefinition operation {I: Type} (Sigma: sigFam I): finType :=\n  SignatureFamily.finType I (Sigma).\nDefinition arity {I: Type} (Sigma: sigFam I): I -> operation Sigma -> nat :=\n  SignatureFamily.arity _ _ _ (SignatureFamily.class I Sigma).\nDefinition dom {I: Type} (Sigma: sigFam I): forall (i: I) (o: operation Sigma), (arity Sigma i o).-tuple (sort Sigma) :=\n  SignatureFamily.dom _ _ _ (SignatureFamily.class I Sigma).\nDefinition range {I: Type} (Sigma: sigFam I): I -> operation Sigma -> (sort Sigma) :=\n  SignatureFamily.range _ _ _ (SignatureFamily.class I Sigma).\n\n\nDefinition sigFamSpec_Mixin {I: Type} {S: preOrdered} {O: finType} (spec: I -> O -> (seq S * S)):\n  SignatureFamily.mixin_of\n    I (PreOrdered.Pack S (PreOrdered.class S))\n    (Finite.Pack (Finite.class O)).\nProof.\n  move: spec.\n  case: O => T1 o.\n  case: S => S c.\n  move => spec.\n  by exact: (@SignatureFamily.Mixin\n               I (PreOrdered.Pack S c) (Finite.Pack o)\n               (fun i o => seq.size (spec i o).1)\n               (fun i o =>\n                  let res := (spec i o).1 in\n                  @Tuple (seq.size res) S res (eq_refl _))\n               (fun i o => (spec i o).2)).\nDefined.\n\nDefinition SigSpec I S O : Type := I -> O -> (seq S * S).\nDefinition sigFamSpec_Type {I: Type} {S: preOrdered} {O: finType} (spec: SigSpec I S O) :=\n  Eval hnf in SignatureFamilyType I S O (sigFamSpec_Mixin spec).\n\nRecord F {I: Type} (Sigma: sigFam I) (C: (sort Sigma) -> Type) (s: sort Sigma): Type :=\n    mkF {\n        index: I;\n        op: operation Sigma;\n        args: {ffun forall n, C (tnth (dom Sigma index op) n) };\n        range_cond: [sort (range Sigma index op) <= s]\n      }.\n\nArguments mkF [I] [Sigma] [C] [s].\nArguments index [I] [Sigma] [C] [s].\nArguments op [I] [Sigma] [C] [s].\nArguments args [I] [Sigma] [C] [s].\nArguments range_cond [I] [Sigma] [C] [s].\n\n\nSection SignatureFunctor.\n  Variable I : Type.\n  Variable Sigma: sigFam I.\n  Variable C D: (sort Sigma) -> Type.\n  Definition fmap (f: forall s, C s -> D s): forall s, F Sigma C s -> F Sigma D s :=\n    fun s x => mkF (index x) (op x) [ffun n => f (tnth (dom Sigma (index x) (op x)) n) (args x n)] (range_cond x).\nEnd SignatureFunctor.\n\nArguments fmap [I] [Sigma] [C D].\n\nSection SignatureFunctorProps.\n  Variable I : Type.\n  Variable Sigma: sigFam I.\n  Variable C D E: (sort Sigma) -> Type.\n\n  Lemma fmap_id: forall s, fmap (fun s => (@id (C s))) s =1 id.\n  Proof.\n    move => s.\n    rewrite /fmap.\n    case => /= *.\n    apply f_equal2 => //.\n    apply ffunP.\n    move => x.\n      by rewrite ffunE.\n  Qed.\n\n  Lemma fmap_comp: forall (f: forall s, D s -> E s) (g: forall s, C s -> D s) s, fmap (fun s => f s \\o g s) s =1 fmap f s \\o fmap g s.\n  Proof.\n    move => f g s.\n    rewrite /fmap /=.\n    case => /= *.\n    apply f_equal2 => //.\n    apply ffunP.\n    move => x.\n      by do 3 rewrite ffunE.\n  Qed.\nEnd SignatureFunctorProps.\n\nModule SigmaAlgebra.\n  Record mixin_of (I: Type) (Sigma: sigFam I) (C: (sort Sigma) -> Type): Type :=\n    Mixin { action: forall s, F Sigma C s -> C s }.\n  Section ClassDef.\n    Notation class_of := mixin_of.\n    Structure type I Sigma := Pack { carrier_sort : (sort Sigma) -> Type; _ : class_of I Sigma carrier_sort }.\n    Variables (I: Type) (Sigma: sigFam I) (C: (sort Sigma) -> Type) (alg: type I Sigma).\n    Definition class := let: Pack _ c as alg' := alg return class_of I Sigma (carrier_sort I Sigma alg') in c.\n    Definition clone c of phant_id class c := @Pack I Sigma C c.\n    Let xCarrier := (let: Pack C _ := alg in C).\n    Notation xclass := (class : class_of I xCarrier).\n    Definition pack (m0: mixin_of I Sigma C) :=\n          fun m & phant_id m0 m => Pack I Sigma C m.\n\n    Definition carrier := Eval hnf in xCarrier.\n  End ClassDef.\n\n  Module Import Exports.\n    Coercion carrier : type >-> Funclass.\n    Coercion action : mixin_of >-> Funclass.\n    \n    Notation sigAlg := (type _).\n    Notation Mixin := Mixin.\n    Notation AlgebraType I Sigma C m := (@pack I Sigma C m m id).\n    Notation \"[ 'sigAlg' Sigma 'on' C 'for' sigAlg ]\" :=\n      (@clone _ Sigma C sigAlg _ idfun)\n        (at level 0, format \"[ 'sigAlg' Sigma 'on' C 'for' sigAlg ]\") : form_scope.\n    Notation \"[ 'sigAlg' Sigma 'on' C ]\" :=\n      (@clone _ Sigma C _ _ id) (at level 0, format \"[ 'sigAlg' Sigma 'on' C ]\") : form_scope.\n  End Exports.\nEnd SigmaAlgebra.\n\nExport SigmaAlgebra.Exports.\n\nDefinition carrier {I: Type} {Sigma: sigFam I} (alg: sigAlg Sigma): sort Sigma -> Type  :=\n  SigmaAlgebra.carrier I Sigma alg.\nDefinition action {I: Type} {Sigma: sigFam I} (alg: sigAlg Sigma): forall s, F Sigma (carrier alg) s -> (carrier alg) s :=\n  SigmaAlgebra.action I (Sigma) (carrier alg) (SigmaAlgebra.class I Sigma alg).\n\nCoercion action: sigAlg >-> Funclass.\n\nDefinition sigAlg_Type {I: Type} {Sigma: sigFam I} {C: (sort Sigma) -> Type} (m: forall s, F Sigma C s -> C s): sigAlg Sigma :=\n  AlgebraType I Sigma C (SigmaAlgebra.Mixin I Sigma C m).\n\nModule SigmaCoAlgebra.\n  Record mixin_of (I: Type) (Sigma: sigFam I) (C: (sort Sigma) -> Type): Type :=\n    Mixin { coaction: forall s, C s -> F Sigma C s }.\n  Section ClassDef.\n    Notation class_of := mixin_of.\n    Structure type I Sigma := Pack { carrier_sort : (sort Sigma) -> Type; _ : class_of I Sigma carrier_sort }.\n    Variables (I: Type) (Sigma: sigFam I) (C: (sort Sigma) -> Type) (coAlg: type I Sigma).\n    Definition class := let: Pack _ c as coAlg' := coAlg return class_of I Sigma (carrier_sort I Sigma coAlg') in c.\n    Definition clone c of phant_id class c := @Pack I Sigma C c.\n    Let xCarrier := (let: Pack C _ := coAlg in C).\n    Notation xclass := (class : class_of I xCarrier).\n    Definition pack (m0: mixin_of I Sigma C) :=\n          fun m & phant_id m0 m => Pack I Sigma C m.\n\n    Definition carrier := Eval hnf in xCarrier.\n  End ClassDef.\n\n  Module Import Exports.\n    Coercion carrier : type >-> Funclass.\n    Coercion coaction : mixin_of >-> Funclass.\n    \n    Notation sigCoAlg := (type _).\n    Notation Mixin := Mixin.\n    Notation CoAlgebraType I Sigma C m := (@pack I Sigma C m m id).\n    Notation \"[ 'sigCoAlg' Sigma 'on' C 'for' sigCoAlg ]\" :=\n      (@clone I Sigma C sigCoAlg _ idfun)\n        (at level 0, format \"[ 'sigCoAlg' Sigma 'on' C 'for' sigCoAlg ]\") : form_scope.\n    Notation \"[ 'sigCoAlg' Sigma 'on' C ]\" :=\n      (@clone I Sigma C _ _ id) (at level 0, format \"[ 'sigCoAlg' Sigma 'on' C ]\") : form_scope.\n  End Exports.\nEnd SigmaCoAlgebra.\n\nExport SigmaCoAlgebra.Exports.\n\nDefinition cocarrier {I: Type} {Sigma: sigFam I} (coAlg: sigCoAlg Sigma): sort Sigma -> Type  :=\n  SigmaCoAlgebra.carrier I Sigma coAlg.\nDefinition coaction {I: Type} {Sigma: sigFam I} (coAlg: sigCoAlg Sigma):\n  forall s, cocarrier coAlg s -> F Sigma (cocarrier coAlg) s :=\n  SigmaCoAlgebra.coaction I (Sigma) (cocarrier coAlg) (SigmaCoAlgebra.class I Sigma coAlg).\n\nCoercion coaction: sigCoAlg >-> Funclass.\n\nDefinition sigCoAlg_Type {I: Type} {Sigma: sigFam I} {C: (sort Sigma) -> Type} (m: forall s, C s -> F Sigma C s): sigCoAlg Sigma :=\n  CoAlgebraType I Sigma C (SigmaCoAlgebra.Mixin I Sigma C m).\n\nInductive AlgGen {I: Type} (Sigma: sigFam I) (h: sigAlg Sigma) (s: sort Sigma): carrier h s -> Prop :=\n| Gen : forall (x: F Sigma (carrier h) s),\n    (forall n, AlgGen Sigma h (tnth (dom Sigma (index x) (op x)) n) (args x n)) ->\n    AlgGen Sigma h s (action h s x).\n\nSection CanonicalAlgebraMorphism.\n  Variable I: Type.\n  Variable Sigma: sigFam I.\n  Variables h g: sigAlg Sigma.\n  Variable h_inv: forall s, carrier h s -> F Sigma (carrier h) s.\n\n  Variable A: Type.\n  Variable measure: forall (s: sort Sigma), carrier h s -> A.\n  Variable R: A -> A -> Prop.\n  Hypothesis R_wf: well_founded R.\n\n  Hypothesis h_inv_dec: forall s x n, R (measure _ (args (h_inv s x) n)) (measure s x).\n\n  Definition fmap_dec (m1: A) (f: forall s2 (y: carrier h s2), R (measure s2 y) m1 -> carrier g s2):\n    forall s (x: F Sigma (carrier h) s), (forall n, R (measure _ (args x n)) m1) -> F Sigma (carrier g) s :=\n    fun s x prfs => mkF (index x) (op x) [ffun n => f (tnth (dom Sigma (index x) (op x)) n)\n                                                  (args x n) (prfs n)] (range_cond x).\n\n  Definition canonical_morphism: forall s, carrier h s -> carrier g s :=\n    DepFix A R R_wf (sort Sigma) (carrier h) (fun s _ => carrier g s) measure\n           (fun s x canonical_morphism_rec =>\n              action g s (fmap_dec (measure s x) canonical_morphism_rec s (h_inv s x) (h_inv_dec s x))).\n          \n  \n  Lemma canonical_morphism_commutes:\n    forall s (x: carrier h s), canonical_morphism s x = action g s (fmap (canonical_morphism) s (h_inv s x)).\n  Proof.\n    move => s x.\n    rewrite /canonical_morphism /DepFix /=.\n    case: (R_wf (measure s x)) => prf /=.\n    apply: f_equal.\n    rewrite /fmap /fmap_dec -/canonical_morphism.\n    apply: (f_equal2 (mkF (index (h_inv s x)) (op (h_inv s x)))) => //.\n    apply: eq_dffun.\n    move => y /=.\n    apply: (fun f eqprf => Fix_F_inv A R (sort Sigma) (carrier h) (fun s _ => carrier g s) measure f eqprf\n                      (tnth (dom Sigma (index (h_inv s x)) (op (h_inv s x))) y)\n                      ((args (h_inv s x)) y)\n                      (prf (measure (tnth (dom Sigma (index (h_inv s x)) (op (h_inv s x))) y)\n                                      ((args (h_inv s x)) y)) (h_inv_dec s x y))\n                      (R_wf (measure (tnth (dom Sigma (index (h_inv s x)) (op (h_inv s x))) y)\n                                     ((args (h_inv s x)) y)))).\n    move => *.\n    apply: f_equal => //.\n    apply: f_equal2 => //.\n    apply ffunP.\n    move => z.\n      by do 2 rewrite ffunE.\n  Qed.\n\n  Variable hC: forall s, cancel (action h s) (h_inv s).\n  Variable h_invC: forall s, cancel (h_inv s) (action h s).\n\n  Lemma canonical_morphism_alg_morphism:\n    forall s, canonical_morphism s \\o (action h s) =1 (action g s) \\o fmap (canonical_morphism) s.\n  Proof.\n    move => s x.\n    rewrite /=.\n    rewrite canonical_morphism_commutes.\n      by rewrite hC.\n  Qed.\n\n  Lemma canonical_morphism_unique:\n    forall (m: forall s, carrier h s -> carrier g s) \n      (is_alg_mor_m: forall s, m s \\o (action h s) =1 (action g s) \\o fmap m s),\n    forall s, canonical_morphism s =1 m s.\n  Proof.\n    move => m is_alg_mor_m s x.\n    rewrite canonical_morphism_commutes.\n    apply: (fun f_rec => Fix_F A R (sort Sigma) (carrier h)\n                            (fun s x => action g s (fmap canonical_morphism s (h_inv s x))  = m s x)\n                            measure f_rec s x (R_wf (measure s x))).\n    move: s x => _ _.\n    move => s x IH.\n    suff: (fmap canonical_morphism s (h_inv s x) = fmap m s (h_inv s x)).\n    { move => ->.\n      move: (is_alg_mor_m s (h_inv s x)).\n      rewrite /= => <-.\n        by rewrite h_invC. }\n    rewrite /fmap.\n    apply: f_equal2 => //.\n    apply ffunP.\n    move => n.\n    do 2 rewrite ffunE.\n    rewrite canonical_morphism_commutes.\n    apply: IH.\n      by apply: h_inv_dec.\n  Qed.\n\n  Lemma canonical_morphism_sound:\n    forall s x, AlgGen Sigma g s (canonical_morphism s x).\n  Proof.\n    move => s x.\n    rewrite canonical_morphism_commutes.\n    apply: (fun f_rec => Fix_F A R (sort Sigma) (carrier h)\n                            (fun s x => AlgGen Sigma g s (action g s (fmap canonical_morphism s (h_inv s x))))\n                            measure f_rec s x (R_wf (measure s x))).\n    move: s x => _ _.\n    move => s x.\n    move: (h_inv_dec s x).\n    case: (h_inv s x) => /= i o args range_prf dec_prf IH.\n    rewrite /fmap /=.\n    constructor.\n    move => /= n.\n    rewrite ffunE.\n    rewrite canonical_morphism_commutes.\n    apply: IH.\n      by apply: dec_prf.\n  Qed.\n\n   Lemma canonical_morphism_complete:\n    forall s x, AlgGen Sigma g s x -> exists y, canonical_morphism s y = x.\n  Proof.\n    move => s x prf.\n    elim: s x / prf.\n    move => s x prfs IH.\n    have: (exists f: {ffun forall n, carrier h (tnth (dom Sigma (index x) (op x)) n) },\n              forall n, canonical_morphism (tnth (dom Sigma (index x) (op x)) n) (f n) = (args x) n).\n    { move: IH.\n      clear ...\n      move: x => [] /= idx op args _ prf.\n      move: (fin_all_exists prf) => [] f f_prf.\n      exists (finfun f).\n      move => n.\n      rewrite ffunE.\n      apply: f_prf. }\n    move => [] args' args'_prf.\n    exists (action h s (mkF (index x) (op x) args' (range_cond x))).\n    move: (canonical_morphism_alg_morphism s (mkF (index x) (op x) args' (range_cond x))).\n    rewrite /= => ->.\n    apply f_equal.\n    rewrite /fmap /=.\n    move: args' args'_prf.\n    clear...\n    case: x => /= i o args range_cond args' args'_prf.\n    apply: f_equal2 => //.\n    apply ffunP.\n    move => n.\n    rewrite ffunE.\n      by apply: args'_prf.\n  Qed.\nEnd CanonicalAlgebraMorphism.\n\nSection FCLAlgebra.\n  Variable I: finType.\n  Variable Sigma: sigFam I.\n\n  Definition Combinator: finType := sum_finType I (operation Sigma).\n  Definition Constructor: ctor := sum_preOrderedType (diag_preOrderedType I) (sort Sigma).\n\n  Definition Gamma__I : {ffun I -> @IT Constructor} :=\n    [ffun i => Ctor (inl i) (Omega)].\n\n  Definition embed (s: sort Sigma): @IT Constructor := @Ctor Constructor (inr s) Omega.\n  Definition unembed (A: @IT Constructor): option (sort Sigma) :=\n    if A is Ctor (inr s) Omega then Some s else None.\n\n  Lemma embed_unembed: pcancel embed unembed.\n  Proof. done. Qed.\n\n  Lemma embed_le: forall s1 s2, [sort s1 <= s2] -> [bcd (embed s1) <= embed s2].\n  Proof.\n    move => s1 s2 prf.\n      by apply: BCD__CAx.\n  Qed.\n\n  Definition typeAtIndex (o: operation Sigma) (i: I) : @IT Constructor :=\n    (Gamma__I i) -> (mkArrow (rev (map embed (dom Sigma i o)), embed (range Sigma i o))).\n\n  Definition Gamma__Sigma : {ffun (operation Sigma) -> @IT Constructor} :=\n    [ffun o => \\bigcap_(A_i <- map (typeAtIndex o) (enum I)) A_i].\n\n  Definition Gamma: {ffun Combinator -> @IT Constructor} :=\n    [ffun c => match c with\n              | inl idx => Gamma__I idx\n              | inr o => Gamma__Sigma o\n              end].\n\n  Definition C__FCL (s: sort Sigma) := { M : @Term Combinator | (typeCheck Gamma M (embed s)) }.\n\n  Definition termAction__FCL (s: sort Sigma) (x: F Sigma C__FCL s): @Term Combinator :=\n    let: mkF i o args rangeprf := x in\n    revApply (Var (inr o) @ (Var (inl i)))\n             (rev (map (fun n => sval (args n)) (enum ('I_(arity Sigma i o))))).\n\n  Lemma proofAction__FCL: forall s x, typeCheck Gamma (termAction__FCL s x) (embed s).\n  Proof.\n    move => s [] i o args range_prf.\n    have size_eq: (seq.size (rev (map (fun n => sval (args n)) (enum 'I_(arity Sigma i o)))) =\n                   seq.size (rev (map embed (dom Sigma i o)))).\n    { do 2 rewrite size_rev size_map.\n        by rewrite -cardE card_ord size_tuple. }\n    apply /fclP.\n    apply: (FCL__Sub (embed (range Sigma i o))); last by apply: embed_le.    \n    apply: (FCL__App Gamma (@Var Combinator (inr o) @ Var (inl i))\n                   (rev (map (fun n => sval (args n)) (enum ('I_(arity Sigma i o)))))\n                   (rev (map embed (dom Sigma i o)), embed (range Sigma i o))) => //.\n    rewrite /=.\n    move => n.\n    case arity0: (n < (arity Sigma i o)).\n    - rewrite nth_rev; last first.\n      { by rewrite size_map -cardE card_ord. }\n      rewrite nth_rev; last first.\n      { by rewrite size_map size_tuple. }\n      rewrite (nth_map s); last first.\n      { by rewrite size_map size_tuple -subn_gt0 subnBA // addnC -addnBA // subnn. }\n      rewrite (nth_map (Ordinal arity0)); last first.\n      { rewrite size_map size_tuple card_ord -subn_gt0 subnBA // addnC -addnBA // subnn. }\n      rewrite size_map.\n      move: (args\n               (nth (Ordinal arity0)\n                    (enum 'I_(arity Sigma i o))\n                    (seq.size (enum 'I_(arity Sigma i o)) - n.+1))).\n      move => [] M /=.\n      rewrite (tnth_nth s).\n      rewrite (@nth_enum_ord _ (Ordinal arity0) ((seq.size (enum 'I_(arity Sigma i o)) - n.+1))); last first.\n      { by rewrite -cardE card_ord -subn_gt0 subnBA // addnC -addnBA // subnn. }\n      move: size_eq.\n        by rewrite size_rev size_rev size_map => -> /fclP.\n    - rewrite nth_default; last first.\n      { by rewrite size_rev size_map -cardE card_ord leqNgt arity0. }\n      rewrite nth_default; last first.\n      { by rewrite size_rev size_map size_tuple leqNgt arity0. }\n      apply: FCL__MP; last by apply: FCL__Var.\n      apply: FCL__Sub; first by apply: FCL__Var.\n      rewrite /Gamma ffunE /Gamma__Sigma ffunE ffunE.\n      apply: BCD__Trans.\n      + apply: (bcd_subset_f _ id _ [:: typeAtIndex o i]).\n        move => x.\n        rewrite mem_seq1.\n        move => /eqP ->.\n        apply /mapP.\n        exists i => //.\n          by rewrite mem_enum.\n      + rewrite /= /typeAtIndex.\n          by apply: BCD__Sub.\n  Qed.\n\n  Definition action__FCL (s: sort Sigma) (x: F Sigma C__FCL s): C__FCL s :=\n    exist _ (termAction__FCL s x) (proofAction__FCL s x).\n\n  Definition termCoAction__FCL (s: sort Sigma) (x: C__FCL s): seq (@Term Combinator) :=\n    behead (rev ((unapply (sval x)).2)).\n\n  Lemma unapplyNotIndex: forall s (x: C__FCL s), if (unapply (sval x)).1 is (inl _) then False else True.\n  Proof.\n    move => s [] M.\n    rewrite -(unapply_revapply M) /= revapply_unapply.\n    move => /fclP /FCL__invApp [] srcs [] size__eq /(fun prf => prf (seq.size srcs)).\n    rewrite nth_default; last by rewrite size__eq.\n    rewrite nth_default //.\n    case: (unapply M).1 => //.\n    move => i /minimalType_minimal.\n    move: size__eq => _.\n    elim /last_ind: srcs.\n    - move => /subty_complete.\n      rewrite /mkArrow /= /embed /= ffunE /Gamma__I ffunE.\n      move => /SubtypeMachine_inv /= /(fun prf => prf (fun i r => if r is Return true then false else true)) res.\n        by move: (res (fun _ _ => isT)).\n    - move => srcs src _.\n      rewrite mkArrow_rcons.\n      move => /subty_complete.\n      rewrite /= /Gamma ffunE /Gamma__I ffunE.\n      move => /SubtypeMachine_inv /(fun prf => prf (fun i r => if r is Return true then false else true)) res.\n      suff: false by done.\n      apply: res.\n      move => Delta r'.\n      rewrite /cast /= omega_mkArrow_tgt /=.\n      move => /emptyDoneTgt -> /=.\n      case: r' => //.\n      move => /Omega__subty.\n      rewrite omega_mkArrow_tgt /=.\n      move => res.\n        by apply: res.\n  Qed.\n\n  Definition opCoAction__FCL (s: sort Sigma) (x: C__FCL s): operation Sigma :=\n    match (unapply (sval x)).1 as o return (if o is (inl _) then False else True) -> operation Sigma with\n    | inl _ => False_rect _\n    | inr o => fun _ => o\n    end (unapplyNotIndex s x).\n\n  Lemma arrow_le {C: ctor}: forall srcs1 srcs2 c1 c2 A1 A2,\n      [bcd (mkArrow (srcs2, @Ctor C c2 A2)) <= (mkArrow (srcs1, Ctor c1 A1))] ->\n      (seq.size srcs2 = seq.size srcs1) /\\\n      all (fun AB => checkSubtypes AB.1 AB.2) (zip srcs1 srcs2) /\\\n      [bcd (Ctor c2 A2) <= (Ctor c1 A1)].\n  Proof.\n    elim /last_ind.\n    - elim /last_ind => // srcs2 src _ c1 c2 A1 A2.\n      move => /subty_complete /SubtypeMachine_inv /=.\n      rewrite mkArrow_rcons.\n      move => /(fun prf => prf (fun i r => if (i, r) is ([subty A -> B of Ctor c C], Return true) then false else true)) res.\n      suff: false by done.\n        by apply: res.\n    - move => // srcs1 src1 IH.\n      elim /last_ind.\n      + move => c1 c2 A1 A2 /subty_complete /SubtypeMachine_inv.\n        rewrite mkArrow_rcons /(mkArrow ([::], _)) /=.\n        move => /(fun prf => prf (fun i r => if (i, r) is ([subty Ctor c A of B -> C], Return true) then false else true)) res.\n        suff: false by done.\n        apply: res.\n        move => Delta.\n        rewrite /cast /= omega_mkArrow_tgt /=.\n        case => //.\n        move => /emptyDoneTgt ->.\n        move => /Omega__subty /= /(fun prf => prf isT).\n          by rewrite omega_mkArrow_tgt.\n      + move => srcs2 src2 _ c1 c2 A1 A2.\n        do 2 rewrite mkArrow_rcons.\n        do 2 rewrite size_rcons.\n        move => /subty_complete /SubtypeMachine_inv prf.\n        have: (checkSubtypes src1 src2 /\\ [bcd (mkArrow (srcs2, Ctor c2 A2)) <= mkArrow (srcs1, Ctor c1 A1)]).\n        { apply: (prf (fun i r => if (i, r) is ([subty A -> B of C -> D], Return true)\n                               then (checkSubtypes C A /\\ [bcd B <= D])\n                               else true)).\n          rewrite /cast /= omega_mkArrow_tgt /=.\n          move => Delta.\n          case => //.\n          move => args_prf.\n          move: (check_tgt_subseq _ _ _ _ args_prf).\n          move: args_prf.\n          case: Delta.\n          - move => _ _ /= /Omega__subty /(fun prf => prf isT).\n              by rewrite omega_mkArrow_tgt.\n          - move => A Delta /=.\n            case A__eq: (A == mkArrow (srcs2, Ctor c2 A2)) => //.\n            move => args_prf /eqP Delta__eq.\n            move: args_prf.\n            rewrite Delta__eq (eqP A__eq) /=.\n            move => /SubtypeMachine_inv /(fun prf => prf (fun i r =>\n                                                        if (i, r) is ([tgt_for_srcs_gte A in [:: (B1, B2)]], [check_tgt [:: C]])\n                                                        then checkSubtypes A B1\n                                                        else true)) res.\n            move => /subty__sound restprf.\n            split => //.\n            apply: res.\n            move => Delta2.\n            case.\n            * move => /subty__sound /subtypeMachineP ->.\n                by case: Delta2.\n            * by move => _ /emptyDoneTgt ->. }\n        move => [] prf1 /IH [] size_prf.\n        rewrite zip_rcons; last by rewrite size_prf.\n          by rewrite all_rcons /= prf1 andTb size_prf.\n  Qed.\n\n  Lemma indexType_sound: forall M i, [FCL Gamma |- M : @Ctor Constructor (inl i) Omega] -> M = (@Var Combinator (inl i)).\n  Proof.\n    move => M i.\n    move A__eq: (@Ctor Constructor (inl i) Omega) => A prf.\n    move: i A__eq.\n    elim /FCL_normalized_ind: M A /prf.\n    - case.\n      + move => i1 i2.\n        rewrite /Gamma ffunE /Gamma__I ffunE.\n          by move => [] ->.\n      + move => o i.\n        rewrite /Gamma ffunE /Gamma__Sigma ffunE.\n          by case: (enum I) => // ? [] //.\n    - move => c A IH prf i A__eq.\n      apply: IH.\n      move: prf.\n      rewrite -A__eq /Gamma ffunE.\n      case: c.\n      + move => i2.\n        rewrite /Gamma__I ffunE.\n        move => /subty_complete /SubtypeMachine_inv /=.\n        move => /(fun prf => prf (fun i r => if (i, r) is ([subty (Ctor (inl i1) Omega) of (Ctor (inl i2) Omega)], Return true)\n                                      then i2 = i1 else True)) => res.\n        apply: f_equal2 => //.\n        apply: f_equal.\n        apply: res.\n        rewrite /cast /=.\n        case res: (i2 == i).\n        * rewrite (eqP res) preorder_reflexive.\n            by case.\n        * by rewrite /[sort _ <= _] /= /[sort _ <= _] /= res.\n      + move => o /subty_complete /SubtypeMachine_inv /(fun prf => prf (fun i r => if r is Return true then false else true)) res.\n        suff: false by done.\n        apply: res.\n        rewrite /Gamma__Sigma ffunE.\n        suff: nilp (cast (@Ctor Constructor (inl i) Omega) (\\bigcap_(A_i <- map (typeAtIndex o) (enum I)) A_i)) by move => ->.\n        rewrite slow_cast_cast.\n        elim: (enum I) => // idx idxs.\n          by case: idxs => [].\n    - move => M N A B devil _ _ _ i B__eq.\n      move: devil.\n      rewrite -B__eq.\n      rewrite -(unapply_revapply M).\n      move => /FCL__invApp prf.\n      suff: false by done.\n      move: prf.\n      case: (unapply M).\n      move: M => _ c Ns.\n      rewrite [(_, _).2]/=.\n      move => [] srcs [] size_eq.\n      move => /(fun prf => prf (seq.size srcs)).\n      rewrite nth_default; last by rewrite size_eq.\n      rewrite nth_default => //.\n      move /minimalType_minimal.\n      rewrite /= /Gamma ffunE.\n      have: (mkArrow (srcs, (A -> @Ctor Constructor (inl i) Omega)) =\n             mkArrow ([:: A & srcs], @Ctor Constructor (inl i) Omega)) by reflexivity.\n      move => ->.\n      clear size_eq.\n      case: c.\n      + move => index.\n        rewrite /Gamma__I ffunE.\n          by move => /(arrow_le _ [::]) [].\n      + move => o.\n        rewrite /Gamma__Sigma ffunE.\n        move => /primeComponentPrime_seq /=.\n        rewrite omega_mkArrow_tgt /=.\n        move => /(fun prf x => prf isT (isPrimeComponentP x)) /=.\n        rewrite mkArrow_prime //=.\n        move => /(fun prf => prf isT).\n        move => /hasP [] x /mapP [] idx inprf__idx ->.\n        move => /subtypeMachineP.\n        rewrite /typeAtIndex -mkArrow_rcons.\n        move => /arrow_le [] _ [] _ /subty_complete /SubtypeMachine_inv.\n        move => /(fun prf => prf (fun i r => if r is Return true then false else true)) res.\n          by apply: res.\n  Qed.\n   \n  Lemma unapplyIsIndex: forall s (x: C__FCL s), if rev (unapply (sval x)).2 is [:: (Var (inl _)) & _] then True else False.\n  Proof.\n    move => s x.\n    move: (unapplyNotIndex s x).\n    case x => M.\n    rewrite -(unapply_revapply M) /= revapply_unapply.\n    move => /fclP /FCL__invApp [] srcs [] size__eq.\n    case: (unapply M).1 => // o.\n    move: size__eq.\n    elim /last_ind: (unapply M).2.\n    - case: srcs => // _.\n      move => /(fun prf => prf 0) /=.\n      move => /minimalType_minimal /=.\n      rewrite /mkArrow /= /Gamma ffunE /Gamma__Sigma ffunE /embed.\n      move => /subty_complete /SubtypeMachine_inv /= /(fun prf => prf (fun i r => if r is Return true then false else true)) res.\n      suff: false by done.\n      apply: res.\n      suff: (nilp (cast (@Ctor Constructor (inr s) Omega) (\\bigcap_(A_i <- map (typeAtIndex o) (enum I)) A_i))) by move ->.\n      rewrite slow_cast_cast.\n      elim (enum I) => // idx idxs.\n        by case: idxs.\n    - elim /last_ind: srcs => // srcs src _; first by rewrite size_rcons.\n      move => Ns N _ /= size__eq prf.\n      have: [FCL Gamma |- N : src].\n      { move: (prf (seq.size srcs)).\n        move: size__eq => /eqP.\n        rewrite size_rcons size_rcons eqSS => /eqP size__eq.\n        rewrite nth_rcons.\n        case lt_prf: (seq.size srcs < seq.size Ns); first by move: lt_prf; rewrite size__eq ltnn.\n        rewrite size__eq eq_refl.\n          by rewrite nth_rcons ltnn eq_refl. }\n      suff: exists i, [bcd src <= @Ctor Constructor (inl i) Omega].\n      { move => [] i le_prf.\n        move => /(fun prf => FCL__Sub _ prf le_prf) /indexType_sound ->.\n          by rewrite rev_rcons. }\n      move: (prf (seq.size (rcons srcs src))).\n      rewrite nth_default; last by rewrite /= size__eq.\n      rewrite nth_default //.\n      move => /minimalType_minimal.\n      rewrite /minimalType /Gamma ffunE /Gamma__Sigma ffunE.\n      move => /primeComponentPrime_seq.\n      rewrite omega_mkArrow_tgt /=.\n      move => /(fun prf x => prf isT (isPrimeComponentP x)).\n      rewrite mkArrow_prime //.\n      move => /(fun prf => prf isT) /hasP [] A /mapP [] i inprf__i -> /subtypeMachineP le_prf.\n      exists i.\n      move: le_prf => /subty_complete.\n      rewrite mkArrow_rcons /typeAtIndex.\n      move => /SubtypeMachine_inv /(fun prf => prf (fun i r => if (i, r) is ([subty A -> B of C -> D], Return true)\n                                                        then  [bcd C <= A]\n                                                        else True)).\n      rewrite /Gamma__I ffunE.\n      move => res.\n      apply: res.\n      rewrite /cast /= omega_mkArrow_tgt /=.\n      move => Delta [] // check_prf.\n      move: (check_prf) => /check_tgt_subseq.\n      move: check_prf.\n      case: Delta.\n      + move => _ _ /= /Omega__subty /(fun prf => prf isT).\n          by rewrite omega_mkArrow_tgt.\n      + move => B ? /=.\n        case B__eq: (B == mkArrow (rev (map embed (dom Sigma i o)), embed (range Sigma i o))) => // check_prf /eqP eq_prf.\n        move: check_prf.\n        rewrite eq_prf /= (eqP B__eq).\n        move => /SubtypeMachine_inv /(fun prf => prf (fun i r => if (i, r) is ([tgt_for_srcs_gte A in [:: (B, _)]], [check_tgt [:: _ ]])\n                                                          then  [bcd A <= B]\n                                                          else True)) res.\n        move => _.\n        apply: res.\n        move => Delta2 r res_prf /emptyDoneTgt ->.\n        move: res_prf.\n        case: r => //.\n          by move => /subty__sound.\n  Qed.\n\n  Definition indexCoAction__FCL (s: sort Sigma) (x: C__FCL s): I :=\n    match rev (unapply (sval x)).2 as args return (if args is [:: (Var (inl _)) & _] then True else False) -> I with\n    | [:: Var (inl i) & _] => fun _ => i\n    | _ => False_rect _\n    end (unapplyIsIndex s x).\n\n\n  Lemma termCoAction_size:\n    forall s x, seq.size (termCoAction__FCL s x) == arity Sigma (indexCoAction__FCL s x) (opCoAction__FCL s x).\n  Proof.\n    move => s [] M.\n    rewrite /opCoAction__FCL /= /termCoAction__FCL /indexCoAction__FCL.\n    move: (unapply_revapply M) => <-.\n    move: (unapply M).1 => c.\n    move: (unapply M).2 => Ns.\n    move: M => _ prf.\n    move: (unapplyNotIndex s\n                           (exist (fun M : Term => typeCheck Gamma M (embed s))\n                                  (revApply (Var c) Ns) prf)).\n    move: (unapplyIsIndex s\n                          (exist (fun M : Term => typeCheck Gamma M (embed s))\n                                  (revApply (Var c) Ns) prf)).\n    rewrite (revapply_unapply (c, Ns)) /=.\n    move: prf => /fclP /FCL__invApp.\n    case: c => //= o [] srcs [].\n    elim /last_ind: Ns => // Ns N _.\n    rewrite rev_rcons.\n    case: N => // [].\n    case => // i.\n    rewrite size_rcons.\n    elim /last_ind: srcs => // srcs src _.\n    rewrite size_rcons.\n    move => /eqP.\n    rewrite eqSS.\n    move => /eqP size__eq prf _ _.\n    rewrite /= size_rev size__eq /=.\n    move: (prf (seq.size srcs).+1).\n    rewrite nth_default; last by rewrite size_rcons size__eq.\n    rewrite nth_default; last by rewrite size_rcons.\n    move => /minimalType_minimal /=.\n    rewrite /Gamma ffunE /Gamma__Sigma ffunE.\n    move => /primeComponentPrime_seq.\n    rewrite omega_mkArrow_tgt /=.\n    move => /(fun prf x => prf isT (isPrimeComponentP x)).\n    rewrite mkArrow_prime //.\n    move => /(fun prf => prf isT) /hasP [] ? /mapP [] idx _ -> /subtypeMachineP.\n    rewrite /typeAtIndex -mkArrow_rcons.\n    move => /arrow_le.\n    do 2 rewrite size_rcons.\n    move => [] /eqP.\n    rewrite eqSS => /eqP size_eq.\n    rewrite -size_eq size_rev size_map size_tuple.\n    move => [].\n    rewrite zip_rcons // all_rcons /=.\n    move => /andP [] /subtypeMachineP src_le.\n    suff: (idx = i) by move => ->.\n    move: (prf (seq.size Ns)).\n    rewrite nth_rcons nth_rcons size__eq ltnn eq_refl.\n    move => /minimalType_minimal.\n    move => /(fun prf => BCD__Trans _ prf src_le).\n    rewrite /= /Gamma ffunE /Gamma__I ffunE ffunE.\n    move => /subty_complete /SubtypeMachine_inv.\n    move => /(fun prf => prf (fun i r => if (i, r) is ([subty Ctor (inl i1) _ of Ctor (inl i2) _], Return true) return Prop\n                                  then  i2 = i1\n                                  else true)) res.\n    apply: res.\n    case; last by rewrite andbF.\n    rewrite /cast /= /[sort _ <= _] /= /[sort _ <= _] /=.\n    case idx__eq: (i == idx) => //=.\n      by rewrite (eqP idx__eq).\n  Qed.\n\n  Lemma proofCoAction__FCL:\n    forall (s: sort Sigma) (x: C__FCL s) n,\n      typeCheck Gamma\n                (tnth (Tuple (termCoAction_size s x)) n)\n                (embed (tnth (dom Sigma (indexCoAction__FCL s x) (opCoAction__FCL s x)) n)).\n  Proof.\n    move => s x [] n n_lt.\n    rewrite (@tnth_nth _ _ (projT1 x)) (@tnth_nth _ _ s).\n    apply /fclP.\n    move: n_lt.\n    move: x => [] M.\n    rewrite /opCoAction__FCL /= /termCoAction__FCL /indexCoAction__FCL.\n    move: (unapply_revapply M) => <-.\n    move: (unapply M).1 => c.\n    move: (unapply M).2 => Ns.\n    move: M => _ prf.\n    move: (unapplyNotIndex s\n                           (exist (fun M : Term => typeCheck Gamma M (embed s))\n                                  (revApply (Var c) Ns) prf)).\n    move: (unapplyIsIndex s\n                          (exist (fun M : Term => typeCheck Gamma M (embed s))\n                                  (revApply (Var c) Ns) prf)).\n    rewrite (revapply_unapply (c, Ns)).\n    move: prf => /fclP /FCL__invApp.\n    case: c => //= o [] srcs [].\n    elim /last_ind: Ns => // Ns N _.\n    rewrite rev_rcons.\n    case: N => // [].\n    case => // i.\n    rewrite size_rcons.\n    elim /last_ind: srcs => // srcs src _.\n    rewrite size_rcons.\n    move => /eqP.\n    rewrite eqSS.\n    move => /eqP size__eq prf _ _.\n    move: (prf (seq.size srcs).+1).\n    rewrite nth_default; last by rewrite size_rcons size__eq.\n    rewrite nth_default; last by rewrite size_rcons.\n    move => /minimalType_minimal /=.\n    rewrite /Gamma ffunE /Gamma__Sigma ffunE.\n    move => /primeComponentPrime_seq.\n    rewrite omega_mkArrow_tgt /=.\n    move => /(fun prf x => prf isT (isPrimeComponentP x)).\n    rewrite mkArrow_prime //.\n    move => /(fun prf => prf isT) /hasP [] ? /mapP [] idx _ -> /subtypeMachineP.\n    rewrite /typeAtIndex -mkArrow_rcons.\n    move => /arrow_le.\n    do 2 rewrite size_rcons.\n    move => [] /eqP.\n    rewrite eqSS => /eqP size_eq.\n    rewrite zip_rcons // all_rcons.\n    move => [] /andP [] /subtypeMachineP src_le.\n    move: size_eq.\n    have: (idx = i).\n    { move: (prf (seq.size Ns)).\n      rewrite nth_rcons nth_rcons size__eq ltnn eq_refl.\n      move => /minimalType_minimal.\n      move => /(fun prf => BCD__Trans _ prf src_le).\n      rewrite /= /Gamma ffunE /Gamma__I ffunE ffunE.\n      move => /subty_complete /SubtypeMachine_inv.\n      move => /(fun prf => prf (fun i r => if (i, r) is ([subty Ctor (inl i1) _ of Ctor (inl i2) _], Return true) return Prop\n                                    then  i2 = i1\n                                    else true)) res.\n      apply: res.\n      case; last by rewrite andbF.\n      rewrite /cast /= /[sort _ <= _] /= /[sort _ <= _] /=.\n      case idx__eq: (i == idx) => //=.\n        by rewrite (eqP idx__eq). }\n    move => -> size_eq prfs _ n_lt.\n    apply: (FCL__Sub (nth (mkArrow (rcons srcs src, embed s)) (rev srcs) n)); last first.\n    { apply /subtypeMachineP.\n      move: prfs.\n      rewrite -all_rev rev_zip; last by rewrite size_eq.\n      move => /allP prfs.\n      apply: (prfs (nth (mkArrow (rcons srcs src, embed s)) (rev srcs) n, embed (nth s (dom Sigma i o) n))).\n      rewrite -(nth_map s (embed s)); last by rewrite size_tuple.\n      rewrite -[X in X \\in _]nth_zip; last by rewrite size_rev -size_eq size_rev.\n      rewrite revK.\n      apply: mem_nth.\n        by rewrite size_zip size_rev -size_eq size_rev minnn size_tuple. }\n    rewrite nth_rev; last by rewrite size__eq -size_eq size_tuple.\n    rewrite nth_rev; last by rewrite -size_eq size_tuple.\n    move: (prf (seq.size srcs - n.+1)).\n    do 2 rewrite nth_rcons.\n    rewrite size__eq.\n    rewrite subnSK; last by rewrite -size_eq size_tuple.\n    rewrite leq_subr.\n    move => res.\n    erewrite set_nth_default; first by exact res.\n    rewrite size__eq subnSK; last by rewrite -size_eq size_tuple.\n      by rewrite leq_subr.\n  Qed.\n\n  Lemma range_coAction:\n    forall (s: sort Sigma) (x: C__FCL s),\n      [sort (range Sigma (indexCoAction__FCL s x) (opCoAction__FCL s x)) <= s].\n  Proof.\n    move => s [] M.\n    rewrite /opCoAction__FCL /= /indexCoAction__FCL.\n    move: (unapply_revapply M) => <-.\n    move: (unapply M).1 => c.\n    move: (unapply M).2 => Ns.\n    move: M => _ prf.\n    move: (unapplyNotIndex s\n                           (exist (fun M : Term => typeCheck Gamma M (embed s))\n                                  (revApply (Var c) Ns) prf)).\n    move: (unapplyIsIndex s\n                          (exist (fun M : Term => typeCheck Gamma M (embed s))\n                                  (revApply (Var c) Ns) prf)).\n    rewrite (revapply_unapply (c, Ns)).\n    move: prf => /fclP /FCL__invApp.\n    case: c => //= o [] srcs [].\n    elim /last_ind: Ns => // Ns N _.\n    rewrite rev_rcons.\n    case: N => // [].\n    case => // i.\n    rewrite size_rcons.\n    elim /last_ind: srcs => // srcs src _.\n    rewrite size_rcons.\n    move => /eqP.\n    rewrite eqSS.\n    move => /eqP size__eq prf _ _.\n    move: (prf (seq.size srcs).+1).\n    rewrite nth_default; last by rewrite size_rcons size__eq.\n    rewrite nth_default; last by rewrite size_rcons.\n    move => /minimalType_minimal /=.\n    rewrite /Gamma ffunE /Gamma__Sigma ffunE.\n    move => /primeComponentPrime_seq.\n    rewrite omega_mkArrow_tgt /=.\n    move => /(fun prf x => prf isT (isPrimeComponentP x)).\n    rewrite mkArrow_prime //.\n    move => /(fun prf => prf isT) /hasP [] ? /mapP [] idx _ -> /subtypeMachineP.\n    rewrite /typeAtIndex -mkArrow_rcons.\n    move => /arrow_le.\n    do 2 rewrite size_rcons.\n    move => [] /eqP.\n    rewrite eqSS => /eqP size_eq.\n    rewrite zip_rcons // all_rcons.\n    move => [] /andP [] /subtypeMachineP src_le.\n    move: size_eq.\n    have: (idx = i).\n    { move: (prf (seq.size Ns)).\n      rewrite nth_rcons nth_rcons size__eq ltnn eq_refl.\n      move => /minimalType_minimal.\n      move => /(fun prf => BCD__Trans _ prf src_le).\n      rewrite /= /Gamma ffunE /Gamma__I ffunE ffunE.\n      move => /subty_complete /SubtypeMachine_inv.\n      move => /(fun prf => prf (fun i r => if (i, r) is ([subty Ctor (inl i1) _ of Ctor (inl i2) _], Return true) return Prop\n                                    then  i2 = i1\n                                    else true)) res.\n      apply: res.\n      case; last by rewrite andbF.\n      rewrite /cast /= /[sort _ <= _] /= /[sort _ <= _] /=.\n      case idx__eq: (i == idx) => //=.\n        by rewrite (eqP idx__eq). }\n    move => -> _ _ /subty_complete /SubtypeMachine_inv.\n    move => /(fun prf => prf (fun i r => if (i, r) is ([subty (Ctor c A) of (Ctor d B)], Return true)\n                                  then [sort c <= d]\n                                  else true)) res.\n    apply: res.\n    case; last by rewrite andbF.\n    rewrite /cast /=.\n      by case: [ sort (inr (range Sigma i o) : Constructor) <= (inr s : Constructor)].\n  Qed.\n\n  Definition coAction__FCL: forall s, C__FCL s -> F Sigma C__FCL s :=\n    fun s c =>\n      @mkF I Sigma C__FCL s\n        (indexCoAction__FCL s c) (opCoAction__FCL s c)\n        [ffun n => exist _ (tnth (Tuple (termCoAction_size s c)) n) (proofCoAction__FCL s c n)]\n        (range_coAction s c).\n\n  Section Measure.\n    Definition measure__FCL: forall s, C__FCL s -> Term := fun s => sval.\n    Definition IsChild: @Term Combinator -> @Term Combinator -> Prop := fun M N => M \\in (unapply N).2.\n    Lemma revApply_rcons: forall (M N: @Term Combinator) Ns, revApply M (rcons Ns N) = revApply (M @ N) Ns.\n    Proof.\n      move => M N Ns.\n        by rewrite /revApply -cats1 (foldr_cat _ _ Ns [:: N]).\n    Qed.\n\n    Lemma revApply_nil: forall (M: @Term Combinator), revApply M [::] = M.\n    Proof. by move => M. Qed.\n\n    Lemma Term_unapply_ind: forall (P : @Term Combinator -> Prop) (f: forall c Ns, (forall N, N \\in Ns -> P N) -> P (revApply (Var c) Ns)) M, P M.\n    Proof.\n      move => P f M.\n      have: (forall N, N \\in [::] -> P N) by done.\n      rewrite -(revApply_nil M).\n      move: [::].\n      elim: M.\n      - move => c Ns IH.\n          by apply: f.\n      - move => M IH__M N IH__N Ns prf.\n        rewrite -revApply_rcons.\n        apply: IH__M.\n        move => N'.\n        rewrite mem_rcons in_cons.\n        case /orP.\n        + move => /eqP ->.\n            by apply: (IH__N [::]).\n        + by apply: prf.\n    Qed.\n    \n    Lemma IsChild_wf: well_founded IsChild.\n    Proof.\n      elim /Term_unapply_ind.\n      move => c Ns IH.\n      apply: Acc_intro.\n      move => N.\n      rewrite /IsChild.\n      rewrite (revapply_unapply (c, Ns)).\n        by move => /IH.\n    Qed.\n\n    Lemma dec_coAction__FCL:\n      forall (s : sort Sigma) (x : C__FCL s)\n        (n : 'I_(arity Sigma (index (coAction__FCL s x)) (op (coAction__FCL s x)))),\n        IsChild (measure__FCL (tnth (dom Sigma (index (coAction__FCL s x)) (op (coAction__FCL s x))) n)\n                            ((args (coAction__FCL s x)) n)) (measure__FCL s x).\n    Proof.\n      move => s x n.\n      rewrite /= ffunE /= /measure__FCL (tnth_nth (sval x)) /IsChild /= /termCoAction__FCL.\n      have n_lt: (n.+1 < seq.size (unapply (sval x)).2).\n      { move: n => [] /= n.\n        move: (termCoAction_size s x) => /eqP <-.\n          by rewrite /termCoAction__FCL size_behead size_rev -subn1 ltn_subRL add1n. }\n      rewrite nth_behead nth_rev //.\n      apply mem_nth.\n        by rewrite subnSK // leq_subr.\n    Qed.\n  End Measure.\n\n  Lemma cancel_action_coAction__FCL: forall s, cancel (action__FCL s) (coAction__FCL s).\n  Proof.\n    move => s [] /= i op args range_cond.\n    rewrite /action__FCL /coAction__FCL.\n    move: (proofCoAction__FCL s _) => prf_action.\n    have i__eq: (indexCoAction__FCL s\n                                (exist (fun M : Term => typeCheck Gamma M (embed s))\n                                       (termAction__FCL s\n                                                      {|\n                                                        index := i;\n                                                        op := op;\n                                                        args := args;\n                                                        range_cond := range_cond |})\n                                       (proofAction__FCL s\n                                                       {|\n                                                         index := i;\n                                                         op := op;\n                                                         args := args;\n                                                         range_cond := range_cond |})) = i).\n    { rewrite /indexCoAction__FCL /=.\n      move: (unapplyIsIndex s _).\n        by rewrite /= -revApply_rcons (revapply_unapply (inr op: Combinator, _)) /= rev_rcons. }\n    have op__eq: (opCoAction__FCL s\n          (exist (fun M : Term => typeCheck Gamma M (embed s))\n             (termAction__FCL s\n                {|\n                index := i;\n                op := op;\n                args := args;\n                range_cond := range_cond |})\n             (proofAction__FCL s\n                {|\n                index := i;\n                op := op;\n                args := args;\n                range_cond := range_cond |})) = op).\n    { rewrite /opCoAction__FCL /=.\n      move: (unapplyNotIndex s _).\n        by rewrite /= -revApply_rcons (revapply_unapply (inr op: Combinator, _)) /=. }    \n    move: (range_coAction s _).\n    move: prf_action.\n    move: (termCoAction_size s _).\n    rewrite i__eq op__eq.\n    move => termCoAction_size prf_action  range_coAction.\n    apply: f_equal2.\n    - apply ffunP.\n      move => x.\n      rewrite ffunE.\n      move: termCoAction_size prf_action.\n      rewrite  /termCoAction__FCL /= -revApply_rcons.\n      rewrite (revapply_unapply (inr op : Combinator, _)) /= rev_rcons revK /=.\n      clear...\n      move rhs__eq: (args x) => rhs.\n      move: rhs__eq.\n      case: rhs => [] m args_prf termCoAction_size.\n      move: args args_prf termCoAction_size.\n      move: (arity Sigma i op) x (dom Sigma i op).\n      move => arity x dom args args_prf rhs__eq prf.\n      move: (prf) (args_prf) (rhs__eq).\n      move: (x) (dom) (args).\n      rewrite -(eqP prf) size_map size_enum_ord.\n      clear x dom args rhs__eq args_prf prf.\n      move => x dom args prf args_prf rhs__eq.\n      have lhs__eq: (tnth (Tuple (n:=arity) (tval:=[seq sval (args n) | n <- enum 'I_arity]) prf) x = m).\n      { rewrite (tnth_nth m) /=.\n        rewrite (nth_map x); last by rewrite size_enum_ord ltn_ord.\n          by rewrite -(tnth_nth x (ord_tuple arity) x) tnth_ord_tuple rhs__eq. }\n      clear rhs__eq.\n      move: args_prf.\n      rewrite -lhs__eq.\n      move => args_prf prf_action.\n      apply: f_equal.\n      move: (prf_action x).\n      clear prf_action.\n      move: args_prf.\n      move: (@UIP_dec bool bool_dec) => res prf1 prf2.\n        by apply: res.\n    - apply: (@UIP_dec bool bool_dec).\n  Qed.\n\n  Lemma cancel_coAction__FCL_action: forall s, cancel (coAction__FCL s) (action__FCL s).\n  Proof.\n    move => s x.\n    rewrite /coAction__FCL /action__FCL /= /indexCoAction__FCL.\n    case: x => M prf.\n    rewrite /=.\n    move: (proofAction__FCL s _).\n    rewrite /= -revApply_rcons /=.\n    move: (proofCoAction__FCL s _).\n    move: (termCoAction_size s _).\n    rewrite  /opCoAction__FCL /=.\n    move: (unapplyNotIndex s\n                           (exist\n                              (fun M0 : Term =>\n                                 typeCheck Gamma M0 (embed s)) M\n                              prf)).\n    rewrite /=.\n    rewrite /indexCoAction__FCL /=.\n    move: (unapplyIsIndex s (exist (fun M0 : Term => typeCheck Gamma M0 (embed s)) M prf)).\n    rewrite /termCoAction__FCL /=.\n    move M__eq: (unapply M) => cNs.\n    move: M__eq.\n    case: cNs => c Ns.\n    elim /last_ind: Ns => //= Ns idx _.\n    rewrite rev_rcons.\n    case: idx; case => //.\n    case: c => // o i.\n    move: (unapply_revapply M) => M__eq unapply__eq.\n    move: M__eq.\n    rewrite unapply__eq /=.\n    move => M__eq _ _ termCoAction_size proofCoAction__FCL.\n    have: (rev\n             [seq sval\n                    ([ ffun n0 : 'I_(arity Sigma i o) =>\n                     exist (fun M0 : Term => typeCheck Gamma M0 (embed (tnth (dom Sigma i o) n0)))\n                       (tnth (Tuple (n:=arity Sigma i o) (tval:=rev Ns) termCoAction_size) n0)\n                       (proofCoAction__FCL n0)] n)\n             | n <- enum 'I_(arity Sigma i o)] = Ns).\n    { rewrite -map_rev.\n      apply: (@eq_from_nth _ M).\n      - by rewrite size_map size_rev size_enum_ord -(eqP termCoAction_size) size_rev.\n      - move => n.\n        rewrite size_map size_rev size_enum_ord.\n        move => lt_n.\n        rewrite (nth_map (Ordinal lt_n)); last by rewrite size_rev size_enum_ord.\n        rewrite ffunE /=.\n        rewrite (tnth_nth M) /=.\n        rewrite nth_rev; last first.\n        { rewrite nth_rev; last by rewrite size_enum_ord.\n          have size_prf: (seq.size (enum 'I_(arity Sigma i o)) - n.+1 < arity Sigma i o).\n          { by rewrite size_enum_ord subnSK // leq_subr. }\n          rewrite nth_enum_ord //.\n          clear proofCoAction__FCL.\n          move: termCoAction_size.\n            by rewrite size_rev => /eqP ->. }\n        apply: f_equal.\n        rewrite nth_rev; last by rewrite size_enum_ord.\n        rewrite nth_enum_ord; last first.\n        { by rewrite size_enum_ord subnSK // leq_subr. }\n        rewrite -subSn; last by rewrite size_enum_ord.\n        rewrite subSS.\n        rewrite size_enum_ord -(eqP termCoAction_size) size_rev subKn //.\n        clear proofCoAction__FCL.\n        move: termCoAction_size.\n        rewrite size_rev => /eqP ->.\n          by apply: ltnW. }\n    move => ->.\n    rewrite M__eq.\n    move => proofAction__FCL.\n    apply: f_equal.\n      by apply: (@UIP_dec bool bool_dec).\n  Qed.\n    \n  Definition algebra_morphism__FCL (g: sigAlg Sigma): forall s, C__FCL s -> carrier g s :=\n    canonical_morphism I Sigma (sigAlg_Type action__FCL) g coAction__FCL\n                       Term measure__FCL IsChild IsChild_wf\n                       dec_coAction__FCL.\n\n  Lemma commutes_algebra_morphism__FCL:\n    forall (g: sigAlg Sigma) (s: sort Sigma) (x: C__FCL s),\n       algebra_morphism__FCL g s x =\n       action g s (fmap (algebra_morphism__FCL g) s (coAction__FCL s x)).\n  Proof.\n    move => g s x.\n      by apply: canonical_morphism_commutes.\n  Qed.\n\n  Theorem unique_algebra_morphism__FCL:\n    forall (g: sigAlg Sigma) (m : forall s : sort Sigma, C__FCL s -> carrier g s),\n      (forall s : sort Sigma, m s \\o action__FCL s =1 action g s \\o fmap m s) ->\n      forall s : sort Sigma, algebra_morphism__FCL g s =1 m s.\n  Proof.\n    move => g m mC s x.\n    rewrite /algebra_morphism__FCL.    \n    apply: canonical_morphism_unique => //.\n      by exact cancel_coAction__FCL_action.\n  Qed.\n\n  Theorem sound_algebra_morphism__FCL:\n    forall (g: sigAlg Sigma) s x, AlgGen Sigma g s (algebra_morphism__FCL g s x).\n  Proof.\n    move => g s x.\n      by apply: canonical_morphism_sound.\n  Qed.\n\n  Theorem complete_algebra_morphism__FCL:\n    forall (g: sigAlg Sigma) s x, AlgGen Sigma g s x -> exists y, (algebra_morphism__FCL g s y) = x.\n  Proof.\n    move => g s x /canonical_morphism_complete prf.\n    apply: (prf (sigAlg_Type action__FCL)).\n      by apply: cancel_action_coAction__FCL.\n  Qed.\n      \nEnd FCLAlgebra. \n\n\n\n\n                           \n\n\n  \n\n\n", "meta": {"author": "combinators", "repo": "cls-coq", "sha": "a4ff8639fc2640c5925ff211dc68ecc63b8b784e", "save_path": "github-repos/coq/combinators-cls-coq", "path": "github-repos/coq/combinators-cls-coq/cls-coq-a4ff8639fc2640c5925ff211dc68ecc63b8b784e/Algebra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.2962656115331755}}
{"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 Not %\\ensuremath\\neg% #~# *)\n(** printing CNot %\\ensuremath\\neg% #~# *)\n(** printing Iff %\\ensuremath\\Leftrightarrow% #&hArr;# *)\n(** printing CFalse %\\ensuremath\\bot% #&perp;# *)\n(** printing False %\\ensuremath\\bot% #&perp;# *)\n(** printing CTrue %\\ensuremath\\top% *)\n(** printing True %\\ensuremath\\top% *)\n(** printing or %\\ensuremath{\\mathrel\\vee}% *)\n(** printing and %\\ensuremath{\\mathrel\\wedge}% *)\n\nRequire Export Coq.Arith.Compare_dec.\nRequire Export CoRN.logic.CornBasics.\nRequire Export Coq.ZArith.ZArith.\nRequire Export Coq.setoid_ring.ZArithRing.\nRequire Export Coq.Arith.Div2.\nRequire Export Coq.Arith.Wf_nat.\nFrom Coq Require Import Lia.\n\nSet Automatic Introduction.\n\n(**\n* Extending the Coq Logic\nBecause notions of apartness and order have computational meaning, we\nwill have to define logical connectives in [Type].  In order to\nkeep a syntactic distinction between types of terms, we define [CProp]\nas an alias for [Type], to be used as type of (computationally meaningful)\npropositions.\n\nFalsehood and negation will typically not be needed in [CProp], as\nthey are used to refer to negative statements, which carry no\ncomputational meaning.  Therefore, we will simply define a negation\noperator from [Type] to [Prop] .\n\nConjunction, disjunction and existential quantification will have to come in\nmultiple varieties.  For conjunction, we will need four operators of type\n[s1->s2->s3], where [s3] is [Prop] if both [s1] and [s2]\nare [Prop] and [CProp] otherwise.\nWe here take advantage of the inclusion of [Prop] in [Type].\n\nDisjunction is slightly different, as it will always return a value in [CProp] even\nif both arguments are propositions.  This is because in general\nit may be computationally important to know which of the two branches of the\ndisjunction actually holds.\n\nExistential quantification will similarly always return a value in [CProp].\n\n- [CProp]-valued conjuction will be denoted as [and];\n- [Crop]-valued conjuction will be denoted as [or];\n- Existential quantification will be written as [{x:A & B}] or [{x:A | B}],\naccording to whether [B] is respectively of type [CProp] or [Prop].\n\nIn a few specific situations we do need truth, false and negation in [CProp],\nso we will also introduce them; this should be a temporary option.\n\nFinally, for other formulae that might occur in our [CProp]-valued\npropositions, such as [(le m n)], we have to introduce a [CProp]-valued\nversion.\n*)\n\nNotation \"'CProp'\":= Type.\n\nSection Basics.\n(**\n** Basics\nHere we treat conversion from [Prop] to [CProp] and vice versa,\nand some basic connectives in [CProp].\n*)\n\nDefinition True_constr := I.\n  (* The name I is occasionally used for other things, hiding True's constructor. *)\n\nDefinition Not (P : CProp) := P -> False.\n\nDefinition Iff (A B : CProp) : CProp := prod (A -> B) (B -> A).\n\nDefinition proj1_sigT (A : Type) (P : A -> CProp) (e : sigT P) :=\n  match e with\n  | existT _ a b => a\n  end.\n\nDefinition proj2_sigT (A : Type) (P : A -> CProp) (e : sigT P) :=\n  match e return (P (proj1_sigT A P e)) with\n  | existT _ a b => b\n  end.\n\nInductive sig2T (A : Type) (P Q : A -> CProp) : CProp :=\n    exist2T : forall x : A, P x -> Q x -> sig2T A P Q.\n\nDefinition proj1_sig2T (A : Type) (P Q : A -> CProp) (e : sig2T A P Q) :=\n  match e with\n  | exist2T _ _ _ a b c => a\n  end.\n\nDefinition proj2a_sig2T (A : Type) (P Q : A -> CProp) (e : sig2T A P Q) :=\n  match e return (P (proj1_sig2T A P Q e)) with\n  | exist2T _ _ _ a b c => b\n  end.\n\nDefinition proj2b_sig2T (A : Type) (P Q : A -> CProp) (e : sig2T A P Q) :=\n  match e return (Q (proj1_sig2T A P Q e)) with\n  | exist2T _ _ _ a b c => c\n  end.\n\nEnd Basics.\n\n\n(* begin hide *)\nInfix \"or\" := sum (at level 85, right associativity).\n\nInfix \"and\" := prod (at level 80, right associativity).\n\nNotation \"A 'IFF' B\" := (Iff A B) (at level 95, no associativity).\n\nNotation ProjT1 := (proj1_sigT _ _).\n\nNotation ProjT2 := (proj2_sigT _ _).\n(* end hide *)\n\n(**\nSome lemmas to make it possible to use [Step]\nwhen reasoning with bi-implications. *)\n\nLemma Iff_left :\n  forall (A B C : CProp),\n  (A IFF B) -> (A IFF C) -> (C IFF B).\nProof.\n unfold Iff.\n intuition.\nQed.\n\nLemma Iff_right:\n  forall (A B C : CProp),\n  (A IFF B) -> (A IFF C) -> (B IFF C).\nProof.\n unfold Iff.\n intuition.\nQed.\n\nLemma Iff_refl : forall (A : CProp), (A IFF A).\nProof.\n unfold Iff.\n intuition.\nQed.\n\nLemma Iff_sym :\n  forall (A B : CProp),(A IFF B) -> (B IFF A).\nProof.\n unfold Iff.\n intuition.\nQed.\n\nLemma Iff_trans :\n  forall (A B C : CProp),\n  (prod (A IFF B) (B IFF C)) -> (A IFF C).\nProof.\n unfold Iff.\n intuition.\nQed.\n\nLemma Iff_imp_imp :\n  forall (A B : CProp),\n  (A IFF B) -> (prod (A->B) (B->A)).\nProof.\n unfold Iff.\n intuition.\nQed.\n\nDeclare Right Step Iff_right.\nDeclare Left Step Iff_left.\n#[global]\nHint Resolve Iff_trans Iff_sym Iff_refl Iff_right Iff_left Iff_imp_imp : algebra.\n\n\n\nLemma not_r_cor_rect :\n  forall (A B : CProp) (S : Type) (l r : S),\n  Not B ->\n  forall H : A or B,\n  @sum_rect A B (fun _ : A or B => S) (fun x : A => l) (fun x : B => r) H = l.\nProof.\n intros. elim H0.\n intros. reflexivity.\n  intro. elim H. assumption.\nQed.\n\nLemma not_l_cor_rect :\n  forall (A B : CProp) (S : Type) (l r : S),\n  Not A ->\n  forall H : A or B,\n  @sum_rect A B (fun _ : A or B => S) (fun x : A => l) (fun x : B => r) H = r.\nProof.\n intros. elim H0.\n intro. elim H. assumption.\n  intros. reflexivity.\nQed.\n\n(* begin hide *)\n(** This notation is incompatible with [Program]. It should be avoided *)\nNotation \"{ x : A  |  P }\" := (sigT (fun x : A => P):CProp)\n  (at level 0, x at level 99) : type_scope.\nNotation \"{ x : A  |  P  |  Q }\" :=\n  (sig2T A (fun x : A => P) (fun x : A => Q)) (at level 0, x at level 99) :\n  type_scope.\n\n(* end hide *)\n\n#[global]\nHint Resolve pair inl inr existT exist2T : core.\n\nSection Choice.\n(* **Choice\nLet [P] be a predicate on $\\NN^2$#N times N#.\n*)\n\nVariable P : nat -> nat -> Prop.\n\nLemma choice :\n  (forall n : nat, {m : nat | P n m}) ->\n  {d : nat -> nat | forall n : nat, P n (d n)}.\nProof.\n intro H.\n exists (fun i : nat => proj1_sigT _ _ (H i)).\n apply (fun i : nat => proj2_sigT _ _ (H i)).\nQed.\n\nEnd Choice.\n\nSection Logical_Remarks.\n\n(** We prove a few logical results which are helpful to have as lemmas\nwhen [A], [B] and [C] are non trivial.\n*)\n\nLemma CNot_Not_or : forall A B C : CProp,\n (A -> Not C) -> (B -> Not C) -> ~ Not (A or B) -> Not C.\nProof.\n intros A B C H H0 H1.\n intro H2.\n apply H1.\n intro H3.\n elim H3.\n  intro; apply H; auto.\n intro; apply H0; auto.\nQed.\n\nLemma CdeMorgan_ex_all : forall (A : Type) (P : A -> CProp) (X : Type),\n (sigT P -> X) -> forall a : A, P a -> X.\nProof.\n intros A P X H a H0.\n eauto.\nQed.\n\nEnd Logical_Remarks.\n\nSection CRelation_Definition.\n\n(**\n** [CProp]-valued Relations\nSimilar to Relations.v in Coq's standard library.\n\n%\\begin{convention}% Let [A:Type] and [R:Crelation].\n%\\end{convention}%\n*)\n\nVariable A : Type.\n\nDefinition Crelation := A -> A -> CProp.\n\nVariable R : Crelation.\n\nDefinition Creflexive : CProp :=\n  forall x : A, R x x.\n\nDefinition Ctransitive : CProp :=\n  forall x y z : A, R x y -> R y z -> R x z.\n\nDefinition Csymmetric : CProp :=\n  forall x y : A, R x y -> R y x.\n\nRecord Cequivalence : CProp :=\n  {Cequiv_refl  : Creflexive;\n   Cequiv_symm  : Csymmetric;\n   Cequiv_trans : Ctransitive}.\n\nDefinition Cdecidable (P:CProp):= P or Not P.\n\nEnd CRelation_Definition.\n\nFixpoint member (A : Type) (n : A) (l : list A) {struct l} : CProp :=\n  match l with\n  | nil => False\n  | cons y m => member A n m or y = n\n  end.\n\nArguments member [A].\n\nSection TRelation_Definition.\n(**\n** [Prop]-valued Relations\nAnalogous.\n\n%\\begin{convention}% Let [A:Type] and [R:Trelation].\n%\\end{convention}%\n*)\n\nVariable A : Type.\n\nDefinition Trelation := A -> A -> Prop.\n\nVariable R : Trelation.\n\nDefinition Treflexive : CProp := forall x : A, R x x.\n\nDefinition Ttransitive : CProp := forall x y z : A, R x y -> R y z -> R x z.\n\nDefinition Tsymmetric : CProp := forall x y : A, R x y -> R y x.\n\nDefinition Tequiv : CProp := Treflexive and Ttransitive and Tsymmetric.\n\nEnd TRelation_Definition.\n\nSection le_odd.\n\n(**\n** The relation [le], [lt], [odd] and [even] in [CProp]\n*)\n\nInductive Cle (n : nat) : nat -> CProp :=\n  | Cle_n : Cle n n\n  | Cle_S : forall m : nat, Cle n m -> Cle n (S m).\n\nTheorem Cnat_double_ind : forall R : nat -> nat -> CProp,\n (forall n : nat, R 0 n) -> (forall n : nat, R (S n) 0) ->\n (forall n m : nat, R n m -> R (S n) (S m)) -> forall n m : nat, R n m.\nProof.\n simple induction n; auto.\n simple induction m; auto.\nQed.\n\nTheorem my_Cle_ind : forall (n : nat) (P : nat -> CProp),\n P n -> (forall m : nat, Cle n m -> P m -> P (S m)) ->\n forall n0 : nat, Cle n n0 -> P n0.\nProof.\n intros n P.\n generalize (Cle_rect n (fun (n0 : nat) (H : Cle n n0) => P n0)); intro.\n assumption.\nQed.\n\nTheorem Cle_n_S : forall n m : nat, Cle n m -> Cle (S n) (S m).\nProof.\n intros n m H.\n pattern m in |- *.\n apply (my_Cle_ind n).\n   apply Cle_n.\n  intros.\n  apply Cle_S.\n  assumption.\n assumption.\nQed.\n\nLemma toCle : forall m n : nat, m <= n -> Cle m n.\nProof.\n intros m.\n induction  m as [| m Hrecm].\n  simple induction n.\n   intro H.\n   apply Cle_n.\n  intros n0 H H0.\n  apply Cle_S.\n  apply H.\n  apply le_O_n.\n simple induction n.\n  intro.\n  exfalso.\n  inversion H.\n intros n0 H H0.\n generalize (le_S_n _ _ H0); intro H1.\n generalize (Hrecm _ H1); intro H2.\n apply Cle_n_S.\n assumption.\nQed.\n\nHint Resolve toCle.\n\nLemma Cle_to : forall m n : nat, Cle m n -> m <= n.\nProof.\n intros m n H.\n elim H.\n  apply le_n.\n intros m0 s H0.\n apply le_S.\n assumption.\nQed.\n\nDefinition Clt (m n : nat) : CProp := Cle (S m) n.\n\nLemma toCProp_lt : forall m n : nat, m < n -> Clt m n.\nProof.\n unfold lt in |- *.\n unfold Clt in |- *.\n intros m n H.\n apply toCle.\n assumption.\nQed.\n\nLemma Clt_to : forall m n : nat, Clt m n -> m < n.\nProof.\n unfold lt in |- *.\n unfold Clt in |- *.\n intros m n H.\n apply Cle_to.\n assumption.\nQed.\n\nLemma Cle_le_S_eq : forall p q : nat, p <= q -> {S p <= q} + {p = q}.\nProof.\n intros p q H.\n elim (gt_eq_gt_dec p q); intro H0.\n  elim H0; auto.\n exfalso.\n apply lt_not_le with q p; auto.\nQed.\n\nLemma Cnat_total_order : forall m n : nat, m <> n -> {m < n} + {n < m}.\nProof.\n intros m n H.\n elim (gt_eq_gt_dec m n).\n  intro H0.\n  elim H0; intros.\n   left; auto.\n  exfalso.\n  auto.\n auto.\nQed.\n\nInductive Codd : nat -> CProp :=\n    Codd_S : forall n : nat, Ceven n -> Codd (S n)\nwith Ceven : nat -> CProp :=\n  | Ceven_O : Ceven 0\n  | Ceven_S : forall n : nat, Codd n -> Ceven (S n).\n\nLemma Codd_even_to : forall n : nat, (Codd n -> odd n) /\\ (Ceven n -> even n).\nProof.\n simple induction n.\n  split.\n   intro H.\n   inversion H.\n  intro.\n  apply even_O.\n intros n0 H.\n elim H; intros H0 H1.\n split.\n  intro H2.\n  inversion H2.\n  apply odd_S.\n  apply H1.\n  assumption.\n intro H2.\n inversion H2.\n apply even_S.\n apply H0.\n assumption.\nQed.\n\nLemma Codd_to : forall n : nat, Codd n -> odd n.\nProof.\n intros n H.\n elim (Codd_even_to n); auto.\nQed.\n\nLemma Ceven_to : forall n : nat, Ceven n -> even n.\nProof.\n intros n H.\n elim (Codd_even_to n); auto.\nQed.\n\nLemma to_Codd_even : forall n : nat, (odd n -> Codd n) and (even n -> Ceven n).\nProof.\n simple induction n.\n  split.\n   intro H.\n   exfalso.\n   inversion H.\n  intro H.\n  apply Ceven_O.\n intros n0 H.\n elim H; intros H0 H1.\n split.\n  intro H2.\n  apply Codd_S.\n  apply H1.\n  inversion H2.\n  assumption.\n intro H2.\n apply Ceven_S.\n apply H0.\n inversion H2.\n assumption.\nQed.\n\nLemma to_Codd : forall n : nat, odd n -> Codd n.\nProof.\n intros.\n elim (to_Codd_even n); auto.\nQed.\n\nLemma to_Ceven : forall n : nat, even n -> Ceven n.\nProof.\n intros.\n elim (to_Codd_even n); auto.\nQed.\n\nEnd le_odd.\n\nSection Misc.\n\n(**\n** Miscellaneous\n*)\n\nLemma CZ_exh : forall z : Z, {n : nat | z = n} or {n : nat | z = (- n)%Z}.\nProof.\n intro z.\n elim z.\n   left.\n   exists 0.\n   auto.\n  intro p.\n  left.\n  exists (nat_of_P p).\n  rewrite convert_is_POS.\n  reflexivity.\n intro p.\n right.\n exists (nat_of_P p).\n rewrite min_convert_is_NEG.\n reflexivity.\nQed.\n\nLemma Cnats_Z_ind : forall P : Z -> CProp,\n (forall n : nat, P n) -> (forall n : nat, P (- n)%Z) -> forall z : Z, P z.\nProof.\n intros P H H0 z.\n elim (CZ_exh z); intros H1.\n  elim H1; intros n H2.\n  rewrite H2.\n  apply H.\n elim H1; intros n H2.\n rewrite H2.\n apply H0.\nQed.\n\nLemma Cdiff_Z_ind : forall P : Z -> CProp,\n (forall m n : nat, P (m - n)%Z) -> forall z : Z, P z.\nProof.\n intros P H z.\n apply Cnats_Z_ind.\n  intro n.\n  replace (Z_of_nat n) with (n - 0%nat)%Z.\n   apply H.\n  simpl in |- *.\n  auto with zarith.\n intro n.\n replace (- n)%Z with (0%nat - n)%Z.\n  apply H.\n simpl in |- *.\n reflexivity.\nQed.\n\nLemma Cpred_succ_Z_ind : forall P : Z -> CProp,\n P 0%Z -> (forall n : Z, P n -> P (n + 1)%Z) ->\n (forall n : Z, P n -> P (n - 1)%Z) -> forall z : Z, P z.\nProof.\n intros P H H0 H1 z.\n apply Cnats_Z_ind.\n  intro n.\n  elim n.\n   exact H.\n  intros n0 H2.\n  replace (S n0:Z) with (n0 + 1)%Z.\n   apply H0.\n   assumption.\n  rewrite Znat.inj_S.\n  reflexivity.\n intro n.\n elim n.\n  exact H.\n intros n0 H2.\n replace (- S n0)%Z with (- n0 - 1)%Z.\n  apply H1.\n  assumption.\n rewrite Znat.inj_S.\n unfold Z.succ in |- *.\n rewrite Zopp_plus_distr.\n reflexivity.\nQed.\n\nLemma not_r_sum_rec : forall (A B S : Set) (l r : S), Not B -> forall H : A + B,\n sum_rec (fun _ : A + B => S) (fun x : A => l) (fun x : B => r) H = l.\nProof.\n intros A B S l r H H0. elim H0.\n intro a. reflexivity.\n  intro b. elim H. assumption.\nQed.\n\nLemma not_l_sum_rec : forall (A B S : Set) (l r : S), Not A -> forall H : A + B,\n sum_rec (fun _ : A + B => S) (fun x : A => l) (fun x : B => r) H = r.\nProof.\n intros A B S l r H H0. elim H0.\n intro a. elim H. assumption.\n  intros. reflexivity.\nQed.\n\n(**\n%\\begin{convention}%\nLet [M:Type].\n%\\end{convention}%\n*)\n\nVariable M : Type.\n\nLemma member_app :\n  forall (x : M) (l k : (list M)),\n  (Iff (member x (app k l))\n       ((member x k) or (member x l))).\nProof.\n induction k; firstorder.\nQed.\n\nEnd Misc.\n\n(**\n** Results about the natural numbers\n\nWe now define a class of predicates on a finite subset of natural\nnumbers that will be important throughout all our work.  Essentially,\nthese are simply setoid predicates, but for clarity we will never\nwrite them in that form but we will single out the preservation of the\nsetoid equality.\n*)\n\nDefinition nat_less_n_pred (n : nat) (P : forall i : nat, i < n -> CProp) :=\n  forall i j : nat, i = j -> forall (H : i < n) (H' : j < n), P i H -> P j H'.\n\nDefinition nat_less_n_pred' (n : nat) (P : forall i : nat, i <= n -> CProp) :=\n  forall i j : nat, i = j -> forall (H : i <= n) (H' : j <= n), P i H -> P j H'.\n\nArguments nat_less_n_pred [n].\nArguments nat_less_n_pred' [n].\n\nSection Odd_and_Even.\n\n(**\nFor our work we will many times need to distinguish cases between even or odd numbers.\nWe begin by proving that this case distinction is decidable.\nNext, we prove the usual results about sums of even and odd numbers:\n*)\n\nLemma even_plus_n_n : forall n : nat, even (n + n).\nProof.\n intro n; induction  n as [| n Hrecn].\n  auto with arith.\n replace (S n + S n) with (S (S (n + n))).\n  apply even_S; apply odd_S; apply Hrecn.\n rewrite plus_n_Sm; simpl in |- *; auto.\nQed.\n\nLemma even_or_odd_plus : forall k : nat, {j : nat &  {k = j + j} + {k = S (j + j)}}.\nProof.\n intro k.\n elim (even_odd_dec k); intro H.\n  elim (even_2n k H); intros j Hj; exists j; auto.\n elim (odd_S2n k H); intros j Hj; exists j; auto.\nQed.\n\n(** Finally, we prove that an arbitrary natural number can be written in some canonical way.\n*)\n\nLemma even_or_odd_plus_gt : forall i j : nat,\n i <= j -> {k : nat &  {j = i + (k + k)} + {j = i + S (k + k)}}.\nProof.\n intros i j H.\n elim (even_or_odd_plus (j - i)).\n intros k Hk.\n elim Hk; intro H0.\n  exists k; left; rewrite <- H0; auto with arith.\n exists k; right; rewrite <- H0; auto with arith.\nQed.\n\nEnd Odd_and_Even.\n\n#[global]\nHint Resolve even_plus_n_n: arith.\n#[global]\nHint Resolve toCle: core.\n\nSection Natural_Numbers.\n\n(**\n** Algebraic Properties\n\nWe now present a series of trivial things proved with [Lia] that are\nstated as lemmas to make proofs shorter and to aid in auxiliary\ndefinitions.  Giving a name to these results allows us to use them in\ndefinitions keeping conciseness.\n*)\n\nLemma Clt_le_weak : forall i j : nat, Clt i j -> Cle i j.\nProof.\n intros.\n apply toCle; apply lt_le_weak; apply Clt_to; assumption.\nQed.\n\nLemma lt_5 : forall i n : nat, i < n -> pred i < n.\nProof.\n intros; apply le_lt_trans with (pred n).\n  apply le_pred; auto with arith.\n apply lt_pred_n_n; apply le_lt_trans with i; auto with arith.\nQed.\n\nLemma lt_8 : forall m n : nat, m < pred n -> m < n.\nProof.\n intros; apply lt_le_trans with (pred n); auto with arith.\nQed.\n\nLemma pred_lt : forall m n : nat, m < pred n -> S m < n.\nProof.\n intros; apply le_lt_trans with (pred n); auto with arith.\n apply lt_pred_n_n; apply le_lt_trans with m.\n  auto with arith.\n apply lt_le_trans with (pred n); auto with arith.\nQed.\n\nLemma lt_10 : forall i m n : nat,\n 0 < i -> i < pred (m + n) -> pred i < pred m + pred n.\nProof.\n intros; lia.\nQed.\n\nLemma lt_pred' : forall m n : nat, 0 < m -> m < n -> pred m < pred n.\nProof.\n intros m n H H0; red in |- *.\n destruct n.\n  inversion H0.\n rewrite <- (S_pred m 0); auto.\n simpl in |- *.\n auto with arith.\nQed.\n\nLemma le_1 : forall m n : nat, Cle m n -> pred m <= n.\nProof.\n intros.\n cut (m <= n); [ intro | apply Cle_to; assumption ].\n apply le_trans with (pred n); auto with arith.\n apply le_pred; auto.\nQed.\n\nLemma le_2 : forall i j : nat, i < j -> i <= pred j.\nProof.\n intros; lia.\nQed.\n\nLemma plus_eq_one_imp_eq_zero : forall m n : nat,\n m + n <= 1 -> {m = 0} + {n = 0}.\nProof.\n intros m n H.\n elim (le_lt_dec m 0); intro.\n  left; auto with arith.\n right; lia.\nQed.\n\nLemma not_not_lt : forall i j : nat, ~ ~ i < j -> i < j.\nProof.\n intros; lia.\nQed.\n\nLemma plus_pred_pred_plus :\n  forall i j k,\n  k <= pred i + pred j ->\n  k <= pred (i + j).\nProof.\n intros; lia.\nQed.\n\n(** We now prove some properties of functions on the natural numbers.\n\n%\\begin{convention}% Let [H:nat->nat].\n%\\end{convention}%\n*)\n\nVariable h : nat -> nat.\n\n(**\nFirst we characterize monotonicity by a local condition: if [h(n) < h(n+1)]\nfor every natural number [n] then [h] is monotonous.  An analogous result\nholds for weak monotonicity.\n*)\n\nLemma nat_local_mon_imp_mon :\n  (forall i : nat, h i < h (S i)) ->\n  forall i j : nat, i < j -> h i < h j.\nProof.\n intros H i j H0.\n induction  j as [| j Hrecj].\n  exfalso; lia.\n cut (i <= j); [ intro H1 | auto with arith ].\n elim (le_lt_eq_dec _ _ H1); intro H2.\n  cut (h i < h j); [ intro | apply Hrecj; assumption ].\n  cut (h j < h (S j)); [ intro | apply H ].\n  apply lt_trans with (h j); auto.\n rewrite H2; apply H.\nQed.\n\nLemma nat_local_mon_imp_mon_le :\n  (forall i : nat, h i <= h (S i)) ->\n  forall i j : nat, i <= j -> h i <= h j.\nProof.\n intros H i j H0.\n induction  j as [| j Hrecj].\n  cut (i = 0); [ intro H1 | auto with arith ].\n  rewrite H1; apply le_n.\n elim (le_lt_eq_dec _ _ H0); intro H1.\n  cut (h i <= h j); [ intro | apply Hrecj; auto with arith ].\n  cut (h j <= h (S j)); [ intro | apply H ].\n  apply le_trans with (h j); auto.\n rewrite H1; apply le_n.\nQed.\n\n(** A strictly increasing function is injective: *)\n\nLemma nat_mon_imp_inj : (forall i j : nat, i < j -> h i < h j) ->\n forall i j : nat, h i = h j -> i = j.\nProof.\n intros H i j H0.\n cut (~ i <> j); [ lia | intro H1 ].\n cut (i < j \\/ j < i); [ intro H2 | lia ].\n inversion_clear H2.\n  cut (h i < h j); [ rewrite H0; apply lt_irrefl | apply H; assumption ].\n cut (h j < h i); [ rewrite H0; apply lt_irrefl | apply H; assumption ].\nQed.\n\n(** And (not completely trivial) a function that preserves [lt] also preserves [le]. *)\n\nLemma nat_mon_imp_mon' : (forall i j : nat, i < j -> h i < h j) ->\n forall i j : nat, i <= j -> h i <= h j.\nProof.\n intros H i j H0.\n elim (le_lt_eq_dec _ _ H0); intro H1.\n  apply lt_le_weak; apply H; assumption.\n rewrite H1; apply le_n.\nQed.\n\n(**\nThe last lemmas in this section state that a monotonous function in the\n natural numbers completely covers the natural numbers, that is, for every\nnatural number [n] there is an [i] such that [h(i) <= n<(n+1) <= h(i+1)].\nThese are useful for integration.\n*)\n\nLemma mon_fun_covers : (forall i j, i < j -> h i < h j) -> h 0 = 0 ->\n forall n, {k : nat | S n <= h k} -> {i : nat | h i <= n | S n <= h (S i)}.\nProof.\n intros H H0 n H1.\n elim H1; intros k Hk.\n induction  k as [| k Hreck].\n  exists 0.\n   rewrite H0; auto with arith.\n  cut (h 0 < h 1); [ intro; apply le_trans with (h 0); auto with arith | apply H; apply lt_n_Sn ].\n cut (h k < h (S k)); [ intro H2 | apply H; apply lt_n_Sn ].\n elim (le_lt_dec (S n) (h k)); intro H3.\n  elim (Hreck H3); intros i Hi.\n  exists i; assumption.\n exists k; auto with arith.\nQed.\n\nLemma weird_mon_covers : forall n (f : nat -> nat), (forall i, f i < n -> f i < f (S i)) ->\n {m : nat | n <= f m | forall i, i < m -> f i < n}.\nProof.\n intros; induction  n as [| n Hrecn].\n  exists 0.\n   auto with arith.\n  intros; inversion H0.\n elim Hrecn.\n  2: auto.\n intros m Hm Hm'.\n elim (le_lt_eq_dec _ _ Hm); intro.\n  exists m.\n   assumption.\n  auto with arith.\n exists (S m).\n  apply le_lt_trans with (f m).\n   rewrite b; auto with arith.\n  apply H.\n  rewrite b; apply lt_n_Sn.\n intros.\n elim (le_lt_eq_dec _ _ H0); intro.\n  auto with arith.\n cut (i = m); [ intro | auto ].\n rewrite b; rewrite <- H1.\n apply lt_n_Sn.\nQed.\n\nEnd Natural_Numbers.\n\n(**\nUseful for the Fundamental Theorem of Algebra.\n*)\n\nLemma kseq_prop :\n  forall (k : nat -> nat) (n : nat),\n  (forall i : nat, 1 <= k i /\\ k i <= n) ->\n  (forall i : nat, k (S i) <= k i) ->\n  {j : nat | S j < 2 * n /\\ k j = k (S j) /\\ k (S j) = k (S (S j))}.\nProof.\n intros k n.\n generalize k; clear k.\n induction  n as [| n Hrecn]; intros k H H0.\n  elim (H 0); intros H1 H2.\n  generalize (le_trans _ _ _ H1 H2); intro H3.\n  exfalso.\n  inversion H3.\n elim (eq_nat_dec (k 0) (k 2)).\n  intro H1.\n  exists 0.\n  cut (k 0 = k 1).\n   intro H2.\n   repeat split.\n     lia.\n    assumption.\n   rewrite <- H1.\n   auto.\n  apply le_antisym.\n   rewrite H1.\n   apply H0.\n  apply H0.\n intro H1.\n elim (Hrecn (fun m : nat => k (S (S m)))).\n   3: intro; apply H0.\n  intros m Hm.\n  exists (S (S m)); lia.\n intro i.\n split.\n  elim (H (S (S i))); auto.\n elim (lt_eq_lt_dec (k 0) (k 2)); intro H2.\n  elim H2; intro H3.\n   generalize (H0 0); intro H4.\n   generalize (H0 1); intro H5.\n   lia.\n  tauto.\n generalize (H 0); intro H3.\n elim H3; intros H4 H5.\n generalize (lt_le_trans _ _ _ H2 H5); intro H6.\n cut (k 2 <= n).\n  2: lia.\n intro H7.\n induction  i as [| i Hreci].\n  assumption.\n apply le_trans with (k (S (S i))); auto.\nQed.\n\nSection Predicates_to_CProp.\n\n(**\n** Logical Properties\n\nThis section contains lemmas that aid in logical reasoning with\nnatural numbers.  First, we present some principles of induction, both\nfor [CProp]- and [Prop]-valued predicates.  We begin by presenting the\nresults for [CProp]-valued predicates:\n*)\n\nLemma even_induction :\n  forall P : nat -> CProp,\n  P 0 ->\n  (forall n, even n -> P n -> P (S (S n))) ->\n  forall n, even n -> P n.\nProof.\n intros P H H0 n.\n pattern n in |- *; apply lt_wf_rect.\n clear n.\n intros n H1 H2.\n induction  n as [| n Hrecn].\n  auto.\n induction  n as [| n Hrecn0].\n  exfalso; inversion H2; inversion H4.\n apply H0.\n  inversion H2; inversion H4; auto.\n apply H1.\n  auto with arith.\n inversion H2; inversion H4; auto.\nQed.\n\nLemma odd_induction :\n  forall P : nat -> CProp,\n  P 1 ->\n  (forall n, odd n -> P n -> P (S (S n))) ->\n  forall n, odd n -> P n.\nProof.\n intros P H H0 n; case n.\n  intro H1; exfalso; inversion H1.\n clear n; intros n H1.\n pattern n in |- *; apply even_induction; auto.\n  intros n0 H2 H3; auto with arith.\n inversion H1; auto.\nQed.\n\nLemma four_induction :\n  forall P : nat -> CProp,\n  P 0 -> P 1 -> P 2 -> P 3 ->\n  (forall n, P n -> P (S (S (S (S n))))) ->\n  forall n, P n.\nProof.\n intros.\n apply lt_wf_rect.\n intro m.\n case m; auto.\n clear m; intro m.\n case m; auto.\n clear m; intro m.\n case m; auto.\n clear m; intro m.\n case m; auto with arith.\nQed.\n\nLemma nat_complete_double_induction : forall P : nat -> nat -> CProp,\n (forall m n, (forall m' n', m' < m -> n' < n -> P m' n') -> P m n) -> forall m n, P m n.\nProof.\n intros P H m.\n pattern m in |- *; apply lt_wf_rect; auto with arith.\nQed.\n\nLemma odd_double_ind : forall P : nat -> CProp, (forall n, odd n -> P n) ->\n (forall n, 0 < n -> P n -> P (double n)) -> forall n, 0 < n -> P n.\nProof.\n cut (forall n : nat, 0 < double n -> 0 < n). intro.\n  intro. intro H0. intro H1. intro n.\n  pattern n in |- *.\n  apply lt_wf_rect. intros n0 H2 H3.\n  generalize (even_odd_dec n0). intro H4. elim H4.\n  intro.\n   rewrite (even_double n0).\n    apply H1.\n     apply H.\n     rewrite <- (even_double n0). assumption.\n      assumption.\n    apply H2.\n     apply lt_div2. assumption.\n     rewrite (even_double n0) in H3.\n     apply H. assumption.\n     assumption.\n   assumption.\n  exact (H0 n0).\n unfold double in |- *. intros.\n case (zerop n). intro.\n  absurd (0 < n + n).\n   rewrite e. auto with arith.\n   assumption.\n intro. assumption.\nQed.\n\n(** For subsetoid predicates in the natural numbers we can eliminate\ndisjunction (and existential quantification) as follows.\n*)\n\nLemma finite_or_elim :\n  forall (n : nat) (P Q : forall i, i <= n -> CProp),\n  nat_less_n_pred' P ->\n  nat_less_n_pred' Q ->\n  (forall i H, P i H or Q i H) ->\n  {m : nat | {Hm : m <= n | P m Hm}} or (forall i H, Q i H).\nProof.\n intro n; induction  n as [| n Hrecn].\n  intros P Q HP HQ H.\n  elim (H _ (le_n 0)); intro H0.\n   left; exists 0; exists (le_n 0); assumption.\n  right; intros i H1.\n  apply HQ with (H := le_n 0); auto with arith.\n intros P Q H H0 H1.\n elim (H1 _ (le_n (S n))); intro H2.\n  left; exists (S n); exists (le_n (S n)); assumption.\n set (P' := fun (i : nat) (H : i <= n) => P i (le_S _ _ H)) in *.\n set (Q' := fun (i : nat) (H : i <= n) => Q i (le_S _ _ H)) in *.\n cut ({m : nat | {Hm : m <= n | P' m Hm}} or (forall (i : nat) (H : i <= n), Q' i H)).\n  intro H3; elim H3; intro H4.\n   left.\n   elim H4; intros m Hm; elim Hm; clear H4 Hm; intros Hm Hm'.\n   exists m.\n   unfold P' in Hm'.\n   exists (le_S _ _ Hm).\n   eapply H with (i := m); [ lia | apply Hm' ].\n  right.\n  intros i H5.\n  unfold Q' in H4.\n  elim (le_lt_eq_dec _ _ H5); intro H6.\n   cut (i <= n); [ intro | auto with arith ].\n   eapply H0 with (i := i); [ auto with arith | apply (H4 i H7) ].\n  eapply H0 with (i := S n); [ auto with arith | apply H2 ].\n apply Hrecn.\n   intro i; intros j H3 H4 H5 H6.\n   unfold P' in |- *.\n   exact (H _ _ H3 _ _ H6).\n  intro i; intros j H3 H4 H5 H6.\n  unfold Q' in |- *.\n  exact (H0 _ _ H3 _ _ H6).\n intros i H3.\n unfold P', Q' in |- *; apply H1.\nQed.\n\nLemma str_finite_or_elim :\n  forall (n : nat) (P Q : forall i, i <= n -> CProp),\n  nat_less_n_pred' P ->\n  nat_less_n_pred' Q ->\n  (forall i H, P i H or Q i H) ->\n  {j : nat | {Hj : j <= n | P j Hj and (forall j' Hj', j' < j -> Q j' Hj')}}\n  or (forall i H, Q i H).\nProof.\n intro n; induction  n as [| n Hrecn].\n  intros P Q H H0 H1.\n  elim (H1 0 (le_n 0)); intro HPQ.\n   left.\n   exists 0; exists (le_n 0).\n   split.\n    apply H with (H := le_n 0); auto.\n   intros; exfalso; inversion H2.\n  right; intros.\n  apply H0 with (H := le_n 0); auto with arith.\n intros P Q H H0 H1.\n set (P' := fun (i : nat) (H : i <= n) => P i (le_S _ _ H)) in *.\n set (Q' := fun (i : nat) (H : i <= n) => Q i (le_S _ _ H)) in *.\n elim (Hrecn P' Q').\n     intro H2.\n     left.\n     elim H2; intros m Hm; elim Hm; clear H2 Hm; intros Hm Hm'.\n     exists m.\n     unfold P' in Hm'.\n     exists (le_S _ _ Hm).\n     elim Hm'; clear Hm'; intros Hm' Hj.\n     split.\n      eapply H with (i := m); [ auto with arith | apply Hm' ].\n     unfold Q' in Hj; intros j' Hj' H2.\n     cut (j' <= n); [ intro H4 | apply le_trans with m; auto with arith ].\n     apply H0 with (H := le_S _ _ H4); [ auto | apply Hj; assumption ].\n    elim (H1 (S n) (le_n (S n))); intro H1'.\n     intro H2.\n     left; exists (S n); exists (le_n (S n)); split.\n      assumption.\n     intros j' Hj' H3; unfold Q' in H1'.\n     cut (j' <= n); [ intro H4 | auto with arith ].\n     unfold Q' in H2.\n     apply H0 with (H := le_S _ _ H4); auto.\n    intro H2.\n    right; intros i H3.\n    unfold Q' in H1'.\n    elim (le_lt_eq_dec _ _ H3); intro H4.\n     cut (i <= n); [ intro H5 | auto with arith ].\n     unfold Q' in H2.\n     apply H0 with (H := le_S _ _ H5); auto.\n    apply H0 with (H := le_n (S n)); auto.\n   intro i; intros j H2 H3 H4 H5.\n   unfold P' in |- *.\n   exact (H _ _ H2 _ _ H5).\n  intro i; intros j H2 H3 H4 H5.\n  unfold Q' in |- *.\n  exact (H0 _ _ H2 _ _ H5).\n intros i H2.\n unfold P', Q' in |- *.\n apply H1.\nQed.\n\nEnd Predicates_to_CProp.\n\nSection Predicates_to_Prop.\n\n(** Finally, analogous results for [Prop]-valued predicates are presented for\ncompleteness's sake.\n*)\n\nLemma even_ind : forall P : nat -> Prop,\n P 0 -> (forall n, even n -> P n -> P (S (S n))) -> forall n, even n -> P n.\nProof.\n intros P H H0 n.\n pattern n in |- *; apply lt_wf_ind.\n clear n.\n intros n H1 H2.\n induction  n as [| n Hrecn].\n  auto.\n induction  n as [| n Hrecn0].\n  exfalso; inversion H2; inversion H4.\n apply H0.\n  inversion H2; inversion H4; auto.\n apply H1.\n  auto with arith.\n inversion H2; inversion H4; auto.\nQed.\n\nLemma odd_ind : forall P : nat -> Prop,\n P 1 -> (forall n, P n -> P (S (S n))) -> forall n, odd n -> P n.\nProof.\n intros P H H0 n; case n.\n  intro H1; exfalso; inversion H1.\n clear n; intros n H1.\n pattern n in |- *; apply even_ind; auto.\n inversion H1; auto.\nQed.\n\nLemma nat_complete_double_ind :\n  forall P : nat -> nat -> Prop,\n  (forall m n, (forall m' n', m' < m -> n' < n -> P m' n') -> P m n) ->\n  forall m n, P m n.\nProof.\n intros P H m.\n pattern m in |- *; apply lt_wf_ind; auto.\nQed.\n\nLemma four_ind :\n  forall P : nat -> Prop,\n  P 0 -> P 1 -> P 2 -> P 3 ->\n  (forall n, P n -> P (S (S (S (S n))))) -> forall n, P n.\nProof.\n intros.\n apply lt_wf_ind.\n intro m.\n case m; auto.\n clear m; intro m.\n case m; auto.\n clear m; intro m.\n case m; auto.\n clear m; intro m.\n case m; auto with arith.\nQed.\n\nEnd Predicates_to_Prop.\n\n(**\n** Integers\n\nSimilar results for integers.\n*)\n\n(* begin hide *)\nTactic Notation \"ElimCompare\" constr(c) constr(d) :=  elim_compare c d.\n(* end hide *)\n\nDefinition Zlts (x y : Z) := eq (A:=Datatypes.comparison) (x ?= y)%Z Datatypes.Lt.\n\nLemma toCProp_Zlt : forall x y : Z, (x < y)%Z -> Zlts x y.\nProof.\n intros x y H.\n unfold Zlts in |- *.\n unfold Z.lt in H.\n auto.\nQed.\n\nLemma CZlt_to : forall x y : Z, Zlts x y -> (x < y)%Z.\nProof.\n intros x y H.\n unfold Z.lt in |- *.\n inversion H.\n auto.\nQed.\n\nLemma Zsgn_1 : forall x : Z, {Z.sgn x = 0%Z} + {Z.sgn x = 1%Z} + {Z.sgn x = (-1)%Z}.\nProof.\n intro x.\n case x.\n   left.\n   left.\n   unfold Z.sgn in |- *.\n   reflexivity.\n  intro p.\n  simpl in |- *.\n  left.\n  right.\n  reflexivity.\n intro p.\n right.\n simpl in |- *.\n reflexivity.\nQed.\n\nLemma Zsgn_2 : forall x : Z, Z.sgn x = 0%Z -> x = 0%Z.\nProof.\n intro x.\n case x.\n   intro H.\n   reflexivity.\n  intros p H.\n  inversion H.\n intros p H.\n inversion H.\nQed.\n\nLemma Zsgn_3 : forall x : Z, x <> 0%Z -> Z.sgn x <> 0%Z.\nProof.\n intro x.\n case x.\n   intro H.\n   elim H.\n   reflexivity.\n  intros p H.\n  simpl in |- *.\n  discriminate.\n intros p H.\n simpl in |- *.\n discriminate.\nQed.\n\n(** The following have unusual names, in line with the series of lemmata in\nfast_integers.v.\n*)\n\nLemma ZL4' : forall y : positive, {h : nat | nat_of_P y = S h}.\nProof.\n simple induction y; [ intros p H; elim H; intros x H1; exists (S x + S x);\n   unfold nat_of_P in |- *; simpl in |- *; rewrite ZL0;\n     rewrite Pmult_nat_r_plus_morphism; unfold nat_of_P in H1; rewrite H1; auto with arith\n       | intros p H1; elim H1; intros x H2; exists (x + S x);\n         unfold nat_of_P in |- *; simpl in |- *; rewrite ZL0;\n           rewrite Pmult_nat_r_plus_morphism; unfold nat_of_P in H2; rewrite H2; auto with arith\n             | exists 0; auto with arith ].\nQed.\n\nLemma ZL9 : forall p : positive, Z_of_nat (nat_of_P p) = Zpos p.\nProof.\n intro p.\n elim (ZL4 p).\n intros x H0.\n rewrite H0.\n unfold Z_of_nat in |- *.\n apply f_equal with (A := positive) (B := Z) (f := Zpos).\n cut (P_of_succ_nat (nat_of_P p) = P_of_succ_nat (S x)).\n  intro H1.\n  rewrite P_of_succ_nat_o_nat_of_P_eq_succ in H1.\n  cut (Pos.pred (Pos.succ p) = Pos.pred (P_of_succ_nat (S x))).\n   intro H2.\n   rewrite Pos.pred_succ in H2.\n   simpl in H2.\n   rewrite Pos.pred_succ in H2.\n   auto.\n  apply f_equal with (A := positive) (B := positive) (f := Pos.pred).\n  assumption.\n apply f_equal with (f := P_of_succ_nat).\n assumption.\nQed.\n\nTheorem Zsgn_4 : forall a : Z, a = (Z.sgn a * Z.abs_nat a)%Z.\nProof.\n intro a.\n case a.\n   simpl in |- *.\n   reflexivity.\n  intro p.\n  unfold Z.sgn in |- *.\n  unfold Z.abs_nat in |- *.\n  rewrite Zmult_1_l.\n  symmetry  in |- *.\n  apply ZL9.\n intro p.\n unfold Z.sgn in |- *.\n unfold Z.abs_nat in |- *.\n rewrite ZL9.\n constructor.\nQed.\n\nTheorem Zsgn_5 : forall a b x y : Z, x <> 0%Z -> y <> 0%Z ->\n (Z.sgn a * x)%Z = (Z.sgn b * y)%Z -> (Z.sgn a * y)%Z = (Z.sgn b * x)%Z.\nProof.\n intros a b x y H H0.\n case a.\n   case b.\n     simpl in |- *.\n     trivial.\n    intro p.\n    unfold Z.sgn in |- *.\n    intro H1.\n    rewrite Zmult_1_l in H1.\n    simpl in H1.\n    elim H0.\n    auto.\n   intro p.\n   unfold Z.sgn in |- *.\n   intro H1.\n   elim H0.\n   apply Z.opp_inj.\n   simpl in |- *.\n   transitivity (-1 * y)%Z; auto.\n  intro p.\n  unfold Z.sgn at 1 in |- *.\n  unfold Z.sgn at 2 in |- *.\n  intro H1.\n  transitivity y.\n   rewrite Zmult_1_l.\n   reflexivity.\n  transitivity (Z.sgn b * (Z.sgn b * y))%Z.\n   case (Zsgn_1 b).\n    intro H2.\n    case H2.\n     intro H3.\n     elim H.\n     rewrite H3 in H1.\n     change ((1 * x)%Z = 0%Z) in H1.\n     rewrite Zmult_1_l in H1.\n     assumption.\n    intro H3.\n    rewrite H3.\n    rewrite Zmult_1_l.\n    rewrite Zmult_1_l.\n    reflexivity.\n   intro H2.\n   rewrite H2.\n   ring.\n  rewrite Zmult_1_l in H1.\n  rewrite H1.\n  reflexivity.\n intro p.\n unfold Z.sgn at 1 in |- *.\n unfold Z.sgn at 2 in |- *.\n intro H1.\n transitivity (Z.sgn b * (-1 * (Z.sgn b * y)))%Z.\n  case (Zsgn_1 b).\n   intro H2.\n   case H2.\n    intro H3.\n    elim H.\n    apply Z.opp_inj.\n    transitivity (-1 * x)%Z.\n     ring.\n    unfold Z.opp in |- *.\n    rewrite H3 in H1.\n    transitivity (0 * y)%Z; auto.\n   intro H3.\n   rewrite H3.\n   ring.\n  intro H2.\n  rewrite H2.\n  ring.\n rewrite <- H1.\n ring.\nQed.\n\n\nLemma nat_nat_pos : forall m n : nat, ((m + 1) * (n + 1) > 0)%Z.\nProof.\n intros m n.\n apply Z.lt_gt.\n cut (Z_of_nat m + 1 > 0)%Z.\n  intro H.\n  cut (0 < Z_of_nat n + 1)%Z.\n   intro H0.\n   cut ((Z_of_nat m + 1) * 0 < (Z_of_nat m + 1) * (Z_of_nat n + 1))%Z.\n    rewrite Zmult_0_r.\n    auto.\n   apply Zlt_reg_mult_l; auto.\n  change (0 < Z.succ (Z_of_nat n))%Z in |- *.\n  apply Zle_lt_succ.\n  change (Z_of_nat 0 <= Z_of_nat n)%Z in |- *.\n  apply Znat.inj_le.\n  apply le_O_n.\n apply Z.lt_gt.\n change (0 < Z.succ (Z_of_nat m))%Z in |- *.\n apply Zle_lt_succ.\n change (Z_of_nat 0 <= Z_of_nat m)%Z in |- *.\n apply Znat.inj_le.\n apply le_O_n.\nQed.\n\nTheorem S_predn : forall m : nat, m <> 0 -> S (pred m) = m.\nProof.\n intros m H.\n symmetry  in |- *.\n apply S_pred with 0.\n lia.\nQed.\n\nLemma absolu_1 : forall x : Z, Z.abs_nat x = 0 -> x = 0%Z.\nProof.\n intros x H.\n case (dec_eq x 0).\n  auto.\n intro H0.\n apply False_ind.\n ElimCompare x 0%Z.\n   intro H2.\n   apply H0.\n   elim (Zcompare_Eq_iff_eq x 0%nat).\n   intros H3 H4.\n   auto.\n  intro H2.\n  cut (exists h : nat, Z.abs_nat x = S h).\n   intro H3.\n   case H3.\n   rewrite H.\n   exact O_S.\n  change (x < 0)%Z in H2.\n  set (H3 := Z.lt_gt _ _ H2) in *.\n  elim (Zcompare_Gt_spec _ _ H3).\n  intros x0 H5.\n  cut (exists q : positive, x = Zneg q).\n   intro H6.\n   case H6.\n   intros x1 H7.\n   rewrite H7.\n   unfold Z.abs_nat in |- *.\n   generalize x1.\n   exact ZL4.\n  cut (x = (- Zpos x0)%Z).\n   simpl in |- *.\n   intro H6.\n   exists x0.\n   assumption.\n  rewrite <- (Z.opp_involutive x).\n  exact (f_equal Z.opp H5).\n intro H2.\n cut (exists h : nat, Z.abs_nat x = S h).\n  intro H3.\n  case H3.\n  rewrite H.\n  exact O_S.\n elim (Zcompare_Gt_spec _ _ H2).\n simpl in |- *.\n rewrite Zplus_0_r.\n intros x0 H4.\n rewrite H4.\n unfold Z.abs_nat in |- *.\n generalize x0.\n exact ZL4.\nQed.\n\nLemma absolu_2 : forall x : Z, x <> 0%Z -> Z.abs_nat x <> 0.\nProof.\n intros x H.\n intro H0.\n apply H.\n apply absolu_1.\n assumption.\nQed.\n\nLemma Zgt_mult_conv_absorb_l : forall a x y : Z,\n (a < 0)%Z -> (a * x > a * y)%Z -> (x < y)%Z.\nProof.\n intros a x y H H0.\n case (dec_eq x y).\n  intro H1.\n  apply False_ind.\n  rewrite H1 in H0.\n  cut ((a * y)%Z = (a * y)%Z).\n   change ((a * y)%Z <> (a * y)%Z) in |- *.\n   apply Zgt_not_eq.\n   assumption.\n  trivial.\n intro H1.\n case (not_Zeq x y H1).\n  trivial.\n intro H2.\n apply False_ind.\n cut (a * y > a * x)%Z.\n  apply Zgt_asym with (m := (a * y)%Z) (n := (a * x)%Z).\n  assumption.\n apply Zlt_conv_mult_l.\n  assumption.\n assumption.\nQed.\n\nLemma Zgt_mult_reg_absorb_l : forall a x y : Z,\n (a > 0)%Z -> (a * x > a * y)%Z -> (x > y)%Z.\nProof.\n intros a x y H H0.\n cut (- a < - (0))%Z.\n  rewrite <- (Z.opp_involutive a) in H.\n  rewrite <- (Z.opp_involutive 0) in H.\n  simpl in |- *.\n  intro H1.\n  rewrite <- (Z.opp_involutive x).\n  rewrite <- (Z.opp_involutive y).\n  apply Zlt_opp.\n  apply Zgt_mult_conv_absorb_l with (a := (- a)%Z) (x := (- x)%Z).\n   assumption.\n  rewrite Zopp_mult_distr_l_reverse.\n  rewrite Zopp_mult_distr_l_reverse.\n  apply Zlt_opp.\n  rewrite <- Zopp_mult_distr_r.\n  rewrite <- Zopp_mult_distr_r.\n  apply Z.gt_lt.\n  apply Zlt_opp.\n  apply Z.gt_lt.\n  assumption.\n lia.\nQed.\n\nLemma Zmult_Sm_Sn : forall m n : Z,\n ((m + 1) * (n + 1))%Z = (m * n + (m + n) + 1)%Z.\nProof.\n intros.\n ring.\nQed.\n\n\nDefinition CForall {A: Type} (P: A -> Type): list A -> Type :=\n  fold_right (fun x => prod (P x)) True.\n\nDefinition CForall_prop {A: Type} (P: A -> Prop) (l: list A):\n (forall x, In x l -> P x)  IFF  CForall P l.\nProof with firstorder. induction l... subst... Qed.\n\nLemma CForall_indexed {A} (P: A -> Type) (l: list A): CForall P l ->\n  forall i (d: A), (i < length l)%nat -> P (nth i l d).\nProof.\n intros X i.\n revert l X.\n induction i; destruct l; simpl in *; intuition; exfalso; inversion H.\nQed.\n\nLemma CForall_map {A B} (P: B -> Type) (f: A -> B) (l: list A):\n  CForall P (map f l)  IFF  CForall (fun x => P (f x)) l.\nProof. induction l; firstorder. Qed.\n\nLemma CForall_weak {A} (P Q: A -> Type):\n  (forall x, P x -> Q x) ->\n  (forall l, CForall P l -> CForall Q l).\nProof. induction l; firstorder. Qed.\n\nFixpoint CNoDup {T: Type} (R: T -> T -> Type) (l: list T): Type :=\n  match l with\n  | nil => True\n  | h :: t => prod (CNoDup R t) (CForall (R h) t)\n  end.\n\nLemma CNoDup_weak {A: Type} (Ra Rb: A -> A -> Type) (l: list A):\n  (forall x y, Ra x y -> Rb x y) ->\n  CNoDup Ra l -> CNoDup Rb l.\nProof with auto.\n induction l... firstorder.\n apply CForall_weak with (Ra a)...\nQed.\n\n\nLemma CNoDup_indexed {T} (R: T -> T -> Type) (Rsym: Csymmetric _ R) (l: list T) (d: T): CNoDup R l ->\n  forall i j, (i < length l)%nat -> (j < length l)%nat -> i <> j -> R (nth i l d) (nth j l d).\nProof with intuition.\n induction l; simpl...\n  exfalso...\n destruct i.\n  destruct j...\n  apply (CForall_indexed (R a) l)...\n destruct j...\n apply Rsym.\n apply (CForall_indexed (R a) l)...\nQed.\n\nLemma CNoDup_map {A B: Type} (R: B -> B -> Type) (f: A -> B):\n  forall l, CNoDup (fun x y => R (f x) (f y)) l  IFF  CNoDup R (map f l).\nProof with auto; intuition.\n induction l; simpl...\n split; intro; split.\n    apply IHl, X.\n   apply CForall_map...\n  apply IHl, X.\n apply CForall_map...\nQed.\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/logic/CLogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.5234203489363239, "lm_q1q2_score": 0.29626561153317543}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom Coq Require Import Bool.Bool Init.Nat Arith.Arith Arith.EqNat\n     Init.Datatypes Strings.String Program Logic.FunctionalExtensionality.\nRequire Export Coq.Strings.String.\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype seq fintype ssrnat ssrfun.\nFrom TLC Require Import LibTactics LibLogic.\nFrom Coq_intermittent Require Export programs semantics algorithms lemmas_1\n     lemmas_0 proofs_0 proofs_n proofs_d. \n\n\n(*weaker version of all_diff_in_fw where the requireement that\n the program can make it up till a checkpoint or termination is omitted*)\nInductive all_diff_in_fww: nvmem -> vmem -> command -> nvmem -> Prop :=\n  Diff_in_FWw: forall{N1 V1 c1 N2 V2 c2 N1c O W} (T: trace_cs (N1, V1, c1) (N2, V2, c2) O W),\n    checkpoint \\notin O -> \n( forall(l: loc ), ((getmap N1) l <> (getmap N1c) l) -> (l \\in getfstwt W))\n-> all_diff_in_fww N1 V1 c1 N1c.\n\n Lemma add_skip_ins_w {N1 V l N2}: all_diff_in_fww N1 V (Ins l) N2 ->\n                                 all_diff_in_fww N1 V (l;; skip) N2.\n   intros Hdiff. inversion Hdiff; subst.\n   inversion T; subst.\n   - \n     econstructor; try eapply CsTrace_Empty; try by [].\n     econstructor. eapply CsTrace_Single.\n     move: (cceval_skip H1) => eq. subst.\n     eapply Seq; try apply H1; try by []; try assumption. intros w contra. subst. inversion H1.\n     intros contra. subst. inversion H1. assumption.\n     assumption.\n     destruct Cmid as [ [nm vm] cm].\n     move: (cceval_skip H3) => eq. subst.\n     econstructor. eapply CsTrace_Single.\n     eapply Seq; try apply H3; try by []; try assumption. intros w contra. subst. inversion H3.\n     intros contra. subst. inversion H3.\n     rewrite mem_cat in H. move/ norP: H => [Ho1 Ho2].\n     assumption.\n     suffices: W2 = emptysets. move => eq. subst.\n     rewrite append_write_empty in H0.\n     assumption.\n     move: (trace_skip H1) => Heq. subst.\n       by move/empty_trace_cs1: H1 => [one two].\n     Qed.\n\n Lemma agreeonread_ins_w_r: forall{N Nend N2: nvmem} {V Vend: vmem}\n                        {l: instruction} {crem c1: command}\n                   {O : obseq} {W: the_write_stuff},\n  all_diff_in_fww N V (l;;crem) N2 ->\n             cceval_w (N2, V, Ins l) O (Nend, Vend, c1) W ->\n             ( forall(z: loc), z \\in (getrd W) ->\n                                (getmap N2) z = (getmap N) z).\n      intros. inversion H; subst. apply/ eqP /negPn /negP.\n        rename H1 into Hread.\n      intros contra.\n      move/ eqP: contra => contra. apply not_eq_sym in contra.\n      apply (H3 z) in contra.\n      destruct (O0 == [::]) eqn: Hbool.\n      - move/eqP : Hbool => Heq. subst.\n        move: (empty_trace_cs1 T) => [ [one two] three four].\n        subst. discriminate contra.\n      - move/ negbT /eqP : Hbool => Hneq.\n        move: (single_step_alls_rev T Hneq) =>\n        [Cmid [W1 [Wrest [O1 [Hcceval [Hsubseq Hw] ] ] ] ] ].\n        subst.\n        simpl in contra.\n        inversion Hcceval; subst.\n        destruct Hsubseq as [Orest Hsub].\n        rewrite Hsub mem_cat in H2.\n        move/norP : H2 => [contra1 H111].\n        move/ negP: contra1. by apply.\n        inversion H0; subst.\n        move: (cceval_agr H0 H12) => Heqrd.\n        rewrite Heqrd in Hread.\n        move: (fw_nin_r_c z H12 Hread) => Hfw.\n        rewrite mem_cat in contra.\n        move/orP : contra => [contra1 | contra2].\n        rewrite mem_filter in contra1.\n        move/ andP : contra1  => [one two].\n        move/negP : one. by apply.\n        move/negP : Hfw. by apply.\n    Qed.\n\n    Lemma agreeonread_ins_w_l: forall{N Nend N2: nvmem} {V Vend: vmem}\n                        {l: instruction} {crem c1: command}\n                   {O : obseq} {W: the_write_stuff},\n  all_diff_in_fww N V (l;;crem) N2 ->\n             cceval_w (N, V, Ins l) O (Nend, Vend, c1) W ->\n             ( forall(z: loc), z \\in (getrd W) ->\n                                (getmap N) z = (getmap N2) z).\n      intros. inversion H; subst. apply/ eqP /negPn /negP.\n        rename H1 into Hread.\n      intros contra.\n      move/ eqP: contra => contra. \n      apply (H3 z) in contra.\n      destruct (O0 == [::]) eqn: Hbool.\n      - move/eqP : Hbool => Heq. subst.\n        move: (empty_trace_cs1 T) => [ [one two] three four].\n        subst. discriminate contra.\n      - move/ negbT /eqP : Hbool => Hneq.\n        assert (cceval_w (N, V, l;; crem) O (Nend, Vend, crem) W) as Hcceval.\n        move: (single_step_alls_rev T Hneq). =>\n        [Cmid [W1 [Wrest [O1 [Hcceval [Hsubseq Hw] ] ] ] ] ].\n        inversion Hcceval; subst.\n        destruct Hsubseq as [Orest Hsub].\n        rewrite Hsub mem_cat in H2.\n        move/norP : H2 => [contra1 H111]. exfalso.\n        move/ negP: contra1. by apply.\n        inversion H0; subst.\n        move: (determinism_c H0 H12) => [one [two three] ].\n        inversion one. subst.\n        assumption.\n        move: (single_step_alls T Hneq Hcceval). =>\n        [W1 [O1 [Trem [Hsub Heq] ] ] ].\n        rewrite Heq in contra. unfold append_write in contra.\n        simpl in contra.\n        move: (fw_nin_r_c z Hcceval Hread) => Hfw.\n        rewrite mem_cat in contra.\n        move/orP : contra => [contra1 | contra2].\n        rewrite mem_filter in contra1.\n        move/ andP : contra1  => [one two].\n        move/negP : one. by apply.\n        move/negP : Hfw. by apply.\n        Qed.\n\n Lemma agreeonread_w_r: forall{N Nend N2: nvmem} {V Vend: vmem}\n                        {c c1: command}\n                   {O : obseq} {W: the_write_stuff},\n  all_diff_in_fww N V c N2 ->\n             cceval_w (N2, V, c) O (Nend, Vend, c1) W ->\n            ( forall(z: loc), z \\in (getrd W) ->\n                   (getmap N2) z = (getmap N) z).\n   intros. move: H H0 H1 => Hdiff Hcc Hr. dependent induction c.\n   apply add_skip_ins_w in Hdiff.\n   eapply agreeonread_ins_w_r; try apply Hdiff; try apply Hcc; try assumption.\n   inversion Hcc; subst; try( rewrite in_nil in Hr; discriminate Hr).\n   eapply agreeonread_ins_w_r; try apply Hdiff; try apply H10; try assumption.\n   inversion Hdiff; subst.\n   apply/eqP /negPn/ negP. intros contra. move/eqP: contra => contra.\n   apply not_eq_sym in contra. apply (H0 z) in contra.\n      destruct (O0 == [::]) eqn: Hbool; move/eqP : Hbool => Heq; subst.\n      - \n        move: (empty_trace_cs1 T) => [ [one two] three four].\n        subst. discriminate contra.\n      - \n        move: (single_step_alls_rev T Heq) =>\n        [Cmid [W1 [Wrest [O1 [Hcceval [Hsubseq Hw] ] ] ] ] ].\n        move: (cceval_agr Hcceval Hcc) => Hww.\n        rewrite Hw in contra.\n        unfold append_write in contra. simpl in contra. rewrite Hww in contra. rewrite - Hww in Hr.\n        move: (fw_nin_r_c z Hcceval Hr) => Hfw.\n        rewrite mem_cat in contra.\n        move/ orP : contra. => [con1 | con2].\n        rewrite mem_filter in con1. move/andP: con1 => [con11 con12]. move/ negP: con11. apply. by rewrite - Hww.\n        move/ negP: Hfw. by apply.\n    Qed.\n\n Lemma agreeonread_w_l: forall{N Nend N2: nvmem} {V Vend: vmem}\n                        {c c1: command}\n                   {O : obseq} {W: the_write_stuff},\n  all_diff_in_fww N V c N2 ->\n             cceval_w (N, V, c) O (Nend, Vend, c1) W ->\n            ( forall(z: loc), z \\in (getrd W) ->\n                   (getmap N) z = (getmap N2) z).\n   intros. move: H H0 H1 => Hdiff Hcc Hr. dependent induction c.\n   apply add_skip_ins_w in Hdiff.\n   eapply agreeonread_ins_w_l; try apply Hdiff; try apply Hcc; try assumption.\n   inversion Hcc; subst; try( rewrite in_nil in Hr; discriminate Hr).\n   eapply agreeonread_ins_w_l; try apply Hdiff; try apply H10; try assumption.\n   inversion Hdiff; subst.\n   apply/eqP /negPn/ negP. intros contra. move/eqP: contra => contra.\n   apply (H0 z) in contra.\n      destruct (O0 == [::]) eqn: Hbool; move/eqP : Hbool => Heq; subst.\n      - \n        move: (empty_trace_cs1 T) => [ [one two] three four].\n        subst. discriminate contra.\n      - \n        move: (single_step_alls T Heq Hcc). =>\n        [Wrest [Orest [Trest [Hsubseq Hw] ] ] ].\n        rewrite Hw in contra.\n        unfold append_write in contra. simpl in contra.\n        move: (fw_nin_r_c z Hcc Hr) => Hfw.\n        rewrite mem_cat in contra.\n        move/ orP : contra. => [con1 | con2].\n        rewrite mem_filter in con1. move/andP: con1 => [con11 con12]. move/ negP: con11. by apply. \n        move/ negP: Hfw. by apply.\n    Qed.\n\n Lemma same_com_hcbc {N N1 Nend1 V V1 l crem O W c1} : all_diff_in_fww N V (l;;crem) N1 ->\n                              cceval_w (N1, V, Ins l) O (Nend1, V1, c1) W ->\n                              exists(Nend: nvmem), (cceval_w (N, V, Ins l) O (Nend, V1, c1) W) /\\\n forall(l: loc), l \\in (getwt W) -> ((getmap Nend) l = (getmap Nend1) l).\n   intros Hdiff Hcceval1.\nmove: (agreeonread_ins_w_r Hdiff Hcceval1) => agr.\n      dependent induction Hcceval1; simpl in agr.\n      - exists (updateNV_sv N x v). split. apply NV_Assign; try assumption.\n        eapply agr_imp_age; try apply H; try assumption.\n        simpl. intros l Hin. rewrite mem_seq1 in Hin.\n        move/ eqP : Hin => Hin. subst.\n        destruct N as [Nmap ND].\n        destruct N1 as [N1map N1D].\n        unfold updateNV_sv. unfold updatemap. simpl.\n        destruct (v == error) eqn: Hbool. simpl in agr.\n        move/ eqP: Hbool => Heq. subst. inversion H1.\n        remember (inl x) as xloc.\n        suffices: (if xloc == xloc then v else Nmap xloc) = v /\\\n                  (if xloc == xloc then v else N1map xloc) = v.\n        move => [one two].\n          by rewrite one two.\n        split; by apply ifT.\n     - exists N. split. apply V_Assign; try assumption.\n       eapply agr_imp_age; try apply H; try assumption.\n       simpl. move => l contra.\n        rewrite in_nil in contra. by exfalso.\n     - exists (updateNV_arr N element a v). split. eapply Assign_Arr.\n       eapply agr_imp_age; try apply H; try assumption.\n       intros z Hin.\n       suffices: (z \\in readobs_wvs (r ++ ri)).\n       move => Hin1.\n         by apply (agr z).\n         rewrite readobs_app_wvs.\n         by eapply in_app_r.\n       eapply agr_imp_age; try apply H0; try assumption.\n       intros z Hin.\n       suffices: (z \\in readobs_wvs (r ++ ri)).\n       move => Hin1.\n         by apply (agr z).\n         rewrite readobs_app_wvs.\n           by eapply in_app_l. assumption. assumption.\n           simpl.\n           intros l Hin.\n        destruct N as [Nmap ND].\n        destruct N1 as [N1map N1D].\n        unfold updateNV_arr. simpl.\n        rewrite mem_seq1 in Hin. move/ eqP : Hin => Hin. subst.\n        unfold updatemap.\n        suffices: \n          ((if inr element == inr element then v else Nmap (inr element)) = v\n                                                                              /\\\n  (if inr element == inr element then v else N1map (inr element)) = v).\n        move => annoying.\n        move: (annoying loc_eqtype loc_eqtype) => [one two].\n        destruct (v == error) eqn: Hbool.\n        move/ eqP: Hbool => three. subst. inversion H1.\n          by rewrite one two.\n          intros. split; by apply ifT.\n          Qed.\n\nLemma trace_converge_minus1w {N V N' Nmid Vmid Nmid'\n                            O W} {l: instruction}:\n  all_diff_in_fww N V l N' ->\n  cceval_w (N, V, Ins l) O (Nmid, Vmid, Ins skip) W ->\n  cceval_w (N', V, Ins l) O (Nmid', Vmid, Ins skip) W ->\n  Nmid = Nmid'.\n  move => Hdiff Hcceval1 Hcceval2.\n  inversion Hdiff. subst.\ndependent induction T.\n-\n  suffices: N2 = N'. move => Heq. subst.\n  move: (determinism_c Hcceval1 Hcceval2). =>\n  [ one two]. inversion one. by subst.\n  simpl in H0. apply nvmem_eq. intros z.\n  apply/eqP/ negPn /negP. intros contra.\n  move/ eqP : contra => contra. apply H0 in contra.\n  discriminate contra.\n-\n  apply nvmem_eq. intros z.\n  move: (same_com_hcbc (add_skip_ins_w Hdiff) Hcceval2).\n  => [Nend [Hcceval3 Hloc] ].\n  move: (determinism_c Hcceval3 Hcceval1) => [one [two three] ]. inversion one. subst.\n  destruct (z \\in (getwt W)) eqn:Hbool.\n  by apply (Hloc z) in Hbool.\n  suffices: (getmap N) z = (getmap N') z.\n  move => Heq.\n  apply (connect_mems Hcceval1 Hcceval2 (negbT Hbool) Heq).\n  move: (determinism_c H Hcceval1). => [eq0 [eq1 eq2] ]. inversion eq0. subst.\n  apply/eqP /negPn /negP. intros contra.\n  move/ eqP / (H1 z) : contra => contra.\n  apply (in_subseq (fw_subst_wt_c Hcceval1)) in contra.\n  rewrite Hbool in contra. discriminate contra.\n  destruct Cmid as [ [nm vm] cm]. move: (cceval_skip H0) => Heq. subst. apply trace_skip in T. exfalso. by apply H.\nQed.\n\n Lemma same_com_hc {N N1 V c Nend2 V1 c1 O W}:\n  all_diff_in_fww N V c N1 ->\n  cceval_w (N1, V, c) O (Nend2, V1, c1) W -> (*use that W2 must be a subset of W*)\n  checkpoint \\notin O ->\n  exists (Nend1: nvmem), cceval_w (N, V, c) O (Nend1, V1, c1) W\n                             /\\ all_diff_in_fww Nend1 V1 c1 Nend2.\n    intros Hdiff Hcceval1 Ho.\n   induction c.\n  - move: (same_com_hcbc (add_skip_ins_w Hdiff) Hcceval1). => [Nend [Hcceval Hloc] ].\n    exists Nend. split; try assumption.\n    move: (cceval_skip Hcceval1) => Heq. subst.\n    pose proof (trace_converge_minus1w Hdiff Hcceval Hcceval1). subst.\n    econstructor; try reflexivity.\n    apply (CsTrace_Empty (Nend2, V1, Ins skip)). \n      by rewrite in_nil.\n      move => l0 contra. exfalso. by apply contra.\n  - inversion Hcceval1; subst.\n    + exfalso. move/negP : Ho. by apply.\n    + exists N. split. apply Skip.\n      inversion Hdiff; subst.\n      destruct (O == [::]) eqn: Hbool.\n       - move/ eqP : Hbool => Hbool. subst.\n      apply empty_trace_cs1 in T. move: T =>\n                                  [ [one two ] three four].\n      subst.\n      econstructor; try apply CsTrace_Empty; try assumption.\n      auto.\n       - move/ negbT / eqP : Hbool => Hneq.\n         move: (single_step_alls_rev T Hneq). => [\n                                                Cmid [W1\n                                                [Wrest1 [O1\n                                                     [Hcceval\n                                                        [Hsubseq1 Hwrite1] ] ] ] ] ].\n         inversion Hcceval; subst.\n         move: (single_step_alls T Hneq Hcceval). =>\n                                                  [Wrest [Orest [Trest [Hsubseq Hwrite] ] ] ].\n         rewrite append_write_empty_l in H0.\n         repeat rewrite append_write_empty_l in Hwrite. subst.\n         econstructor; try apply Trest; try assumption.\n       exfalso. by apply H9.\n         + move: (same_com_hcbc Hdiff H10). => [Nend [ Hcceval Hloc] ].\n           exists Nend. split.\n       apply Seq; try assumption.\n       inversion Hdiff; subst.\n      destruct (O0 == [::]) eqn: Hbool.\n       - move/ eqP : Hbool => Hbool. subst.\n      apply empty_trace_cs1 in T. move: T =>\n                                  [ [one two ] three four].\n      subst.\n      suffices: (getmap N2) =1 (getmap N1). move/nvmem_eq => H500. subst.\n      move: (determinism_c H10 Hcceval) => [ [one two] ]. subst.\n      econstructor; try apply CsTrace_Empty; try assumption.\n      by [].\n      intros l0. apply/ eqP /negPn /negP. intros contra.\n      move/ eqPn / (H0 l0) : contra.\n      by rewrite in_nil. auto.\n       - move/ negbT / eqP : Hbool => Hneq.\n         suffices: cceval_w (N, V, l;;c1) O (Nend, V1, c1) W.\n         move => Hccevalbig.\nmove: (single_step_alls T Hneq Hccevalbig). => [Wrest [Orest\n                                                     [Trest\n                                [Hsubseq Hwrite] ] ] ].\n       econstructor; try apply Trest; try assumption.\n       apply/negP. intros contra.\n       apply/negP / negPn: H.\n       rewrite Hsubseq. rewrite/ orP mem_cat. apply/orP. by right.\n           intros l0 Hl0. remember Hl0 as Hneql.\n           clear HeqHneql.\n           suffices: getmap Nend l0 <> getmap Nend2 l0 -> l0 \\notin getwt W.\n           intros Hlocc. apply Hlocc in Hl0.\n           suffices: (l0 \\in getfstwt W0).\n           intros Hfw.\n           subst. move/ fw_split : Hfw => [one | two].\n           apply (in_subseq (fw_subst_wt_c Hcceval\n                 )) in one.\n           exfalso. move/ negP : Hl0. by apply.\n             by move: two => [whatever done].\n             apply H0.\n             move: (update_one_contra l0 Hcceval Hl0) => Heq1.\n             move: (update_one_contra l0 Hcceval1 Hl0) => Heq2.\n             by rewrite Heq1 Heq2.\n             clear Hneq. intros Hneq. apply/negP. intros contra.\n             apply Hneq. by apply Hloc.\n             apply Seq; try assumption.\n         + inversion Hcceval1; subst; exists N; inversion Hdiff; subst;\n           destruct (O == [::]) eqn: Hbool.\n          -  move/ eqP : Hbool => Hbool. subst.\n      apply empty_trace_cs1 in T. move: T =>\n                                  [ [one two ] three four].\n      subst.\n      suffices: (getmap N2) =1 (getmap Nend2). move/nvmem_eq => H500. subst. split; try assumption.\n      econstructor; try apply CsTrace_Empty; try assumption.\n      intros l0. apply/ eqP /negPn /negP. intros contra.\n      move/ eqPn / (H0 l0) : contra.\n      by rewrite in_nil. auto.\n          - move/ negbT / eqP : Hbool => Hneq.\n            move: (agreeonread_w_r Hdiff Hcceval1) => agr.\n            move: (agr_imp_age H9 agr) => Heval.\n            split.\n           apply If_T; try assumption.\n         move: (single_step_alls_rev T Hneq). => [\n                                                Cmid [W1\n                                                [Wrest1 [O1\n                                                     [Hcceval\n                                                        [Hsubseq1 Hwrite1] ] ] ] ] ].\n       move: (single_step_alls T Hneq Hcceval). => [Wrest [Orest\n                                                     [Trest\n                                                        [Hsubseq Hwrite] ] ] ].\n       destruct Cmid as [ [Nmid Vmid] cmid].\n       inversion Hcceval; subst.\n       econstructor; try apply Trest; try assumption.\n         destruct Wrest1 as [ [w1 w2 ] w3].\n         destruct Wrest as [ [wr1 wr2] wr3]. inversion Hwrite.\n        \n         repeat rewrite cats0 in H2.\n         repeat rewrite cats0 in H4.\n         intros l Hneql.\n         simpl.\n         apply H0 in Hneql. subst. simpl in Hneq.\n         unfold append_write in Hneql.\n         simpl in Hneql. rewrite cats0 in Hneql.\n         rewrite H4 in Hneql.\n         rewrite mem_filter in Hneql.\n           by move/ andP : Hneql => [one two].\n           move: (determinism_e H12 Heval) => [one two].\n           inversion two.\n          -  move/ eqP : Hbool => Hbool. subst.\n      apply empty_trace_cs1 in T. move: T =>\n                                  [ [one two ] three four].\n      subst.\n      suffices: (getmap N2) =1 (getmap Nend2). move/nvmem_eq => H500. subst. split; try assumption.\n      econstructor; try apply CsTrace_Empty; try assumption.\n      intros l0. apply/ eqP /negPn /negP. intros contra.\n      move/ eqPn / (H0 l0) : contra.\n      by rewrite in_nil. auto.\n          - move/ negbT / eqP : Hbool => Hneq.\n            move: (agreeonread_w_r Hdiff Hcceval1) => agr.\n            move: (agr_imp_age H9 agr) => Heval.\n            split.\n           apply If_F; try assumption.\n         move: (single_step_alls_rev T Hneq). => [\n                                                Cmid [W1\n                                                [Wrest1 [O1\n                                                     [Hcceval\n                                                        [Hsubseq1 Hwrite1] ] ] ] ] ].\n       move: (single_step_alls T Hneq Hcceval). => [Wrest [Orest\n                                                     [Trest\n                                                        [Hsubseq Hwrite] ] ] ].\n       destruct Cmid as [ [Nmid Vmid] cmid].\n       inversion Hcceval; subst.\n           move: (determinism_e H12 Heval) => [one two].\n           inversion two.\n       econstructor; try apply Trest; try assumption.\n         destruct Wrest1 as [ [w1 w2 ] w3].\n         destruct Wrest as [ [wr1 wr2] wr3]. inversion Hwrite.\n        \n         repeat rewrite cats0 in H2.\n         repeat rewrite cats0 in H4.\n         intros l Hneql.\n         simpl.\n         apply H0 in Hneql. subst. simpl in Hneq.\n         unfold append_write in Hneql.\n         simpl in Hneql. rewrite cats0 in Hneql.\n         rewrite H4 in Hneql.\n         rewrite mem_filter in Hneql.\n           by move/ andP : Hneql => [one two].\nQed.\n\n  Lemma same_com_help {N N1 V c Nend2 Vend cend O W}:\n  all_diff_in_fww N V c N1 ->\n  trace_cs (N1, V, c) (Nend2, Vend, cend) O W ->\n  checkpoint \\notin O ->\n  exists (Nend1: nvmem), trace_cs (N, V, c) (Nend1, Vend, cend) O W\n  .\n    intros. move: N H.\n    dependent induction H0; intros N Hdiff.\n    + exists N. apply CsTrace_Empty.\n    + move: (same_com_hc Hdiff H H1) => [Nend1 [done blah] ].\n      exists Nend1. by apply CsTrace_Single.\n    + destruct Cmid as [ [Nmid Vmid] cmid].\n      rewrite mem_cat in H2. move/norP : H2 => [Ho1 Ho2].\n      move: (same_com_hc Hdiff H1 Ho1) => [Nendm [Tm Hdiffm] ].\n      suffices: exists Nend1,\n               trace_cs (Nendm, Vmid, cmid)\n                        (Nend1, Vend, cend) O2 W2.\n      move => [Nend1 Tend].\n      exists Nend1. eapply CsTrace_Cons; try apply Tend; try assumption.\n      eapply IHtrace_cs; try reflexivity; try assumption.\nQed.\n\n\nLemma war_cceval: forall{N0 N Nmid: nvmem} {V Vmid: vmem} {c cmid: command}\n                   {l: instruction}\n                   {O: obseq} {W: the_write_stuff} {Wstart Rstart W' R': warvars},\n\n        cceval_w (N, V, l;;c) O (Nmid, Vmid, cmid) W ->\n        WAR_ins (getdomain N0) Wstart Rstart l W' R' ->\n        (subseq ((getwt W) ++ Wstart)  W')\n          /\\ get_smallvars ((getwt W) ++ Wstart) = (get_smallvars W')\n          /\\ (R' =  (getrd W) ++ Rstart).\n    intros. move: H H0 => Hcceval Hwar.\n    dependent induction Hwar.\n    -  inversion Hcceval; subst. split; try split; try by []. exfalso. by apply H9.\n    - inversion Hcceval; subst. move: (extract_write_svv H13 H0) => Heq.\n      rewrite Heq. split; try split; try by [].\n      inversion H13; subst; pose proof (read_deterministic H (RD H10));\n        subst; split; reflexivity.\n    -inversion Hcceval; subst. move: (extract_write_svnv H13 H) => Heq.\n    rewrite Heq. split; try split; try by []. inversion H13; subst;\n    pose proof (read_deterministic H0 (RD H10));\n    subst; split; reflexivity. \n - inversion Hcceval; subst. move: (extract_write_svnv H15 H0) => Heq.\n    rewrite Heq. inversion H15; subst;\n    move: (read_deterministic H (RD H12)) => Heq1; subst;\n    split; try split; try by [].\n - inversion Hcceval; subst. move: (extract_write_svnv H14 H2) => Heq.\n    rewrite Heq. inversion H14; subst;\n    move: (read_deterministic H (RD H11)) => Heq1; subst;\n                                              split; try split; try by [].\n \n - inversion Hcceval; subst; inversion H13; subst.\n   split; try split. simpl.\n   rewrite - cat1s. apply cat_subseq.\n   rewrite sub1seq.\n   destruct element as [a0 index0]. eapply gen_locs_works.\n   apply H17. auto. Opaque get_smallvars. simpl.\n   rewrite (sv_add_el W0 W0); try auto.\n   symmetry. rewrite (sv_add_arr W0 W0 a); try auto.\n   simpl.\n   rewrite readobs_app_wvs. rewrite catA.\n   move: (read_deterministic H (RD H15)) => Heq1.\n   move: (read_deterministic H0 (RD H14)) => Heq2.\n   by subst. \n - inversion Hcceval; subst; inversion H14; subst.\n   split; try split. simpl.\n   rewrite - cat1s. apply cat_subseq.\n   rewrite sub1seq.\n   destruct element as [a0 index0]. eapply gen_locs_works.\n   apply H18. auto.\n   Opaque get_smallvars. simpl.\n   rewrite (sv_add_el W0 W0); try auto.\n   symmetry. rewrite (sv_add_arr W0 W0 a); try auto.\n   simpl. rewrite readobs_app_wvs. rewrite catA.\n   pose proof (read_deterministic H (RD H16)).\n   pose proof (read_deterministic H0 (RD H15)).\n   by subst. \nQed.\n\n\nLemma agsv_war_bc {w W1 W2 R l W' R'}:\n             WAR_ins w W1 R l W' R' ->\n       (get_smallvars W2) = (get_smallvars W1) ->\n       exists(W2': warvars), WAR_ins w W2 R l W2' R' /\\\n       (get_smallvars W2') = (get_smallvars W').\n      \n      intros. \n      inversion H; subst.\n      - exists W2; split. eapply WAR_Skip. assumption.\n      - exists W2. split; try assumption. eapply WAR_Vol; try assumption.\n        by apply (agsv_war_h W' W2).\n      - exists(inl x :: W2). split.\n        eapply WAR_NoRd; try apply H1; try assumption. by apply sv_add_sv.\n      - exists(inl x :: W2). split. eapply WAR_Checkpointed; try apply H0; try assumption.\n        apply/ negP.\n        apply (agsv_war_h W1 W2). assumption. by\n            move/negP: H4. by apply sv_add_sv.\n      - exists(inl x :: W2). split. eapply WAR_WT; try apply H0; try assumption.\n        symmetry in H0.\n        apply/ negPn.\n        apply (contra (agsv_war_h W2 W1 x H0)). \n          by apply/negPn. by apply sv_add_sv.\n      - exists(generate_locs a ++ W2). split.\n        eapply WAR_NoRd_Arr. apply H1. apply H2. assumption.\n        apply sv_add_arr.\n        rewrite (sv_add_arr W1 W2 a); try by [].\n      -exists(generate_locs a ++ W2). split.\n       eapply WAR_Checkpointed_Arr; try apply H0; try apply H1; try assumption. \n        apply sv_add_arr.\n        rewrite (sv_add_arr W1 W2 a); try by [].\nQed.\n\n Lemma agsv_war {w W1 W2 R c}:\n       WARok w W1 R c ->\n       (get_smallvars W2) = (get_smallvars W1) ->\n       WARok w W2 R c. intros.\n      move: W2 H0.  dependent induction H; intros; simpl.\n      - move: (agsv_war_bc H H0) => [W2' Done]. eapply WAR_I. apply Done.\n      - eapply WAR_CP; assumption.\n      - move: (agsv_war_bc H H1) => [W2' [H21 H22] ].\n        eapply WAR_Seq; try assumption.\n        apply H21. by apply IHWARok.\n     - eapply WAR_If. apply H. by apply IHWARok1. by apply IHWARok2.\nQed.\n\n\nLemma warok_partial:  forall{N0 N Nmid: nvmem} {V Vmid: vmem} {c cmid: command} {O: obseq} {W: the_write_stuff} {Wstart Rstart: warvars},\n    cceval_w (N, V, c) O (Nmid, Vmid, cmid) W ->\n    checkpoint \\notin O ->\n    WARok (getdomain N0) Wstart Rstart c ->\n    WARok (getdomain N0) ((getwt W) ++ Wstart) ((getrd W) ++ Rstart) cmid.\n    intros. move: H H0 H1 => Hcceval Ho Hwarok.\n    dependent induction Hwarok; simpl.\n    - apply cceval_skip in Hcceval. subst. eapply WAR_I. constructor.\n    - inversion Hcceval; subst. discriminate Ho.\n      exfalso. by apply (H8 w).\n   - move: (war_cceval Hcceval H) => [Hsubseq [Hsmallvars Hr] ]. subst. apply cceval_steps in Hcceval. subst.  eapply agsv_war. apply Hwarok. assumption.\n - inversion Hcceval; subst; \n    pose proof (read_deterministic H (RD H10));\n    subst; assumption.\nQed.\n\nLemma two_bcw {Ni Ni1 V V1 l c1 crem Nc O W} : all_diff_in_fww Ni V (l;;crem) Nc ->\n                              cceval_w (Ni, V, Ins l) O (Ni1, V1, c1) W ->\n                              exists(Nc1: nvmem), (cceval_w (Nc, V, Ins l) O (Nc1, V1, c1) W /\\\n                              forall(l: loc), l \\in (getwt W) -> ((getmap Ni1) l = (getmap Nc1) l)).\n      intros.\n      move: (agreeonread_ins_w_l H H0) => agr.\n      dependent induction H0; simpl in agr.\n      - exists (updateNV_sv Nc x v). split. apply NV_Assign; try assumption.\n        eapply agr_imp_age; try apply H2; try assumption.\n        simpl. intros l Hin. rewrite mem_seq1 in Hin.\n        move/ eqP : Hin => Hin. subst.\n        destruct Ni as [Nimap NiD].\n        destruct Nc as [Ncmap NcD].\n        unfold updateNV_sv. unfold updatemap. simpl.\n        remember (inl x) as xloc.\n        suffices: (if xloc == xloc then v else Nimap xloc) = v /\\\n                  (if xloc == xloc then v else Ncmap xloc) = v.\n        move => [one two].\n        destruct (v == error) eqn: Hbool.\n        move/ eqP : Hbool => Heq. subst. inversion H1.\n          by rewrite one two.\n        split; by apply ifT.\n     - exists Nc. split. apply V_Assign; try assumption.\n       eapply agr_imp_age; try apply H2; try assumption.\n       simpl. move => l contra.\n        rewrite in_nil in contra. by exfalso.\n     - exists (updateNV_arr Nc element a v). split. eapply Assign_Arr.\n       eapply agr_imp_age; try apply H3; try assumption.\n       intros z Hin.\n       suffices: (z \\in readobs_wvs (r ++ ri)).\n       move => Hin1.\n         by apply (agr z).\n         rewrite readobs_app_wvs.\n         by eapply in_app_r.\n       eapply agr_imp_age; try apply H0; try assumption.\n       intros z Hin.\n       suffices: (z \\in readobs_wvs (r ++ ri)).\n       move => Hin1.\n         by apply (agr z).\n         rewrite readobs_app_wvs.\n           by eapply in_app_l. assumption. assumption.\n           simpl.\n           intros l Hin.\n        destruct Ni as [Nimap NiD].\n        destruct Nc as [Ncmap NcD].\n        unfold updateNV_arr. simpl.\n        rewrite mem_seq1 in Hin.\n        move/ eqP : Hin => Hin. subst.\n        unfold updatemap.\n        suffices: \n          ((if inr element == inr element then v else Nimap (inr element)) = v\n                                                                              /\\\n  (if inr element == inr element then v else Ncmap (inr element)) = v).\n        move => annoying.\n        move: (annoying loc_eqtype loc_eqtype) => [one two].\n        destruct (v == error) eqn: Hbool.\n        move/ eqP : Hbool => Heq. subst. inversion H1.\n          by rewrite one two. \n       intros. split; by apply ifT.\nQed.\n\nLemma war_works_loc_c {N0 N Nend: nvmem} {V Vend: vmem} {c cend: command} {O: obseq} {W: the_write_stuff}\n      {Wstart Rstart: warvars}:\n    cceval_w (N, V, c) O (Nend, Vend, cend) W ->\n    WARok (getdomain N0) Wstart Rstart c ->\n    checkpoint \\notin O ->\n  forall (l: loc),\n(l \\notin (remove Rstart (getfstwt W)) -> \n l \\in (getwt W) ->\n       l \\in (getdomain N0) \\/ l \\in Wstart).\n  intros Hcceval Hwarok Ho.\n  move: Rstart Wstart Hwarok Ho. remember Hcceval as Hcceval1.\n  clear HeqHcceval1.\n  dependent induction Hcceval1; intros; simpl in H;\n    try discriminate H0; try discriminate H1.\n  -  remember H3 as Hwt.\n    clear HeqHwt.\n    simpl in H3. rewrite mem_seq1 in H3.\n    move/eqP : H3 => Heq. subst.\n   inversion Hwarok; subst; inversion H7;\n     subst.\n     +  exfalso. apply (negNVandV x H0 H10).\n     +\n       rewrite mem_cat in H13.\n         move / negP / norP : H13 => [Hre Hrs].\n         rewrite mem_filter in H2.\n         move/nandP: H2. => [contra | H2].\n         rewrite Hrs in contra. discriminate contra.\n         pose proof (negfwandw_means_r Hcceval H2 Hwt) as Hrd.\n         \n         simpl in Hrd.\n         move: (read_deterministic H10 (RD H)) => Heq. subst.\n         exfalso. move/negP : Hre. by apply.\n     + \n        by left.\n     + \n       by right.\n     - \n       rewrite in_nil in H3.\n       discriminate H3.\n     - \n       remember H4 as Hwt. clear HeqHwt.\n       simpl in H4.\n       rewrite mem_seq1 in H4. move/ eqP : H4 => Heq. subst.\n       inversion Hwarok; subst; inversion H8;\n       subst. \n       + \n           remember (inr element) as l.\n           destruct element as [a0 index].\n     -\n           rewrite mem_filter in H3.\n           move/nandP : H3 => [contra | H3].\n           unfold intersect in H15. exfalso. apply H15.\n            exists l.\n           split. subst.\n           eapply gen_locs_works. apply H2.\n           repeat rewrite mem_cat.\n           repeat (apply/ orP; right).\n           apply /negPn : contra.\n           pose proof (negfwandw_means_r Hcceval H3 Hwt) as Hrd. simpl in Hrd.\n       pose proof\n            (read_deterministic (RD H0) H11).\n       pose proof\n            (read_deterministic (RD H) H14).\n       subst.\n       exfalso.\n       apply H15.\n       remember (inr (El a0 index)) as l. exists l.\n           split. subst.\n           eapply gen_locs_works. apply H2.\n       rewrite catA.\n       rewrite <- readobs_app_wvs.\n       rewrite mem_cat.\n       apply/ orP. by left.\n           + \n         destruct element.\n             left. \n         apply (in_subseq H16 (gen_locs_works H2)).\n- \n           inversion Hwarok; subst. exfalso. by apply (H w).\n           eapply IHHcceval1; try apply Hcceval1;\n             try reflexivity;\n             try assumption.\n           eapply WAR_I; try apply H8; try reflexivity; try assumption. assumption.\n           Qed.\n\nLemma war_works_loc {N0 N Nend: nvmem} {V Vend: vmem} {c cend: command} {O: obseq} {W: the_write_stuff}\n      {Wstart Rstart: warvars}:\n    trace_cs (N, V, c) (Nend, Vend, cend) O W ->\n    WARok (getdomain N0) Wstart Rstart c ->\n    checkpoint \\notin O ->\n  forall (l: loc),\n(l \\notin (remove Rstart (getfstwt W)) -> \n l \\in (getwt W) ->\n       l \\in (getdomain N0) \\/ l \\in Wstart).\nintros T Hwarok Ho.\nmove: Wstart Rstart Hwarok.\ndependent induction T; intros.\n+ rewrite in_nil in H0. discriminate H0.\n+ eapply war_works_loc_c; try apply H; try apply Hwarok; try assumption.\n+ destruct W1 as [ [wW1 rW1] fwW1].\n  destruct W2 as [ [wW2 rW2] fwW2].\n  destruct Cmid as [ [Nmid Vmid] cmid].\n  simpl in H1. simpl in H2. simpl in IHT.\n  remember Ho as Hoo. clear HeqHoo.\n  rewrite mem_cat in Hoo. move/ norP : Hoo => [Ho1 Ho2].\n  move: (war_works_loc_c H0 Hwarok Ho1) => Hl1.\n  move: (warok_partial H0 Ho1 Hwarok) => Hwarok2.\n  simpl in Hwarok2.\n  suffices: \n        (forall l : loc,\n        l \\notin remove (rW1 ++ Rstart) fwW2 ->\n        l \\in wW2 -> l \\in getdomain N0 \\/ l \\in (wW1 ++ Wstart)).\n  move => Hl2. simpl in Hl1.\n  rewrite mem_cat in H2. move/orP: H2 => Happ.\ndestruct (l \\in wW1) eqn: Hbool;\n  rewrite mem_filter in H1; move/nandP : H1 => [Hr1 | Hweird].\n+ suffices: (l \\notin remove Rstart fwW1).\nintros H500. apply Hl1; try assumption.\nrewrite mem_filter. apply/nandP. by left.\n+ rewrite mem_cat in Hweird. move/ norP: Hweird => [Hdone H600].\n  apply Hl1. rewrite mem_filter. apply/ nandP. by right.\n    by [].\n +suffices: (l \\notin remove (rW1 ++ Rstart) fwW2).\n  intros H500. destruct Happ as [Hw2 | contra].\n  suffices: (l \\in getdomain N0 \\/ l \\in wW1 ++ Wstart).\n  move => [one | two]. by left. right. rewrite mem_cat in two.\n  move/ orP : two => [contra | done]. rewrite Hbool in contra.\n  discriminate contra. assumption.\n  eapply Hl2; try assumption.\n  rewrite Hbool in contra. discriminate contra.\n  rewrite mem_filter. apply/nandP. left. rewrite mem_cat.\n  apply/negPn / orP. right. apply/negPn: Hr1.\n +\n   suffices: (l \\notin remove (rW1 ++ Rstart) fwW2).\n  intros H500. destruct Happ as [Hw2 | contra].\n  suffices: (l \\in getdomain N0 \\/ l \\in wW1 ++ Wstart).\n  move => [one | two]. by left. right. rewrite mem_cat in two.\n  move/ orP : two => [contra | done]. rewrite Hbool in contra.\n  discriminate contra. assumption.\n  eapply Hl2; try assumption.\n  rewrite Hbool in contra. discriminate contra.\n  rewrite mem_filter. apply/nandP.\n  rewrite mem_cat in Hweird. move/ norP: Hweird. => [Hdone H600].\n  rewrite mem_filter in Hdone. move/ nandP : Hdone => [Hd1 | Hd2].\n  left. rewrite mem_cat. apply/negPn/ orP. left.\n  by apply/negPn. by right.\n  eapply IHT; try reflexivity; try assumption.\n  Qed.\n\n\nLemma wts_cped_sv: forall{N0 N Nend: nvmem} {V Vend: vmem} {c cend: command} {O: obseq} {W: the_write_stuff}\n                  {Wstart Rstart: warvars} {l: loc},\n    trace_cs (N, V, c) (Nend, Vend, cend) O W ->\n    WARok (getdomain N0) Wstart Rstart c ->\n    checkpoint \\notin O ->\n    l \\notin (getdomain N0) ->\n    l \\in (getwt W) -> \n    l \\in (remove Rstart (getfstwt W)) \n          \\/ l \\in Wstart.\n  intros.\n  move: (war_works_loc H H0 H1) => Hl.\n  destruct (l \\in remove Rstart (getfstwt W)) eqn: Hin.\n    by left.\n    move/ negbT / (Hl l): Hin => Himp.\n    move: (Himp H3) => [one | two].\n    exfalso. by move/ negP : H2. by right.\nQed.\n\nLemma war_works {N0 N Nend: nvmem} {V Vend: vmem} {c cend: command} {O: obseq} {W: the_write_stuff}:\n    trace_cs (N, V, c) (Nend, Vend, cend) O W ->\n  subset_nvm N0 N ->\n    WARok (getdomain N0) [::] [::] c ->\n    checkpoint \\notin O ->\n    all_diff_in_fww N V c (N0 U! Nend).\n  intros T Hsub Hwarok Ho.\n  econstructor; try apply T; try assumption.\n  intros l Hneq.\n  destruct N as [Nmap Nd].\n  destruct N0 as [N0map N0d].\n  destruct Nend as [Nendmap Nendd].\n  unfold updatemaps in Hneq. simpl in Hneq.\n  assert (l \\notin N0d) as Hnin0.\n  apply/negP. intros contra.\n  rewrite ifT in Hneq. apply Hneq.\n  unfold subset_nvm in Hsub. symmetry. by eapply Hsub.\n  assumption.\n  rewrite ifF in Hneq.\n  apply (update T) in Hneq.\n  move: (war_works_loc T Hwarok Ho) => Hl.\n  rewrite remove_empty in Hl.\n  apply/ negPn/ negP. intros contra.\n  move/ Hl : contra. => [contra1 | contra2].\n  assumption.\n  move/negP: Hnin0. by apply.\n    by [].\n    by apply negbTE. \nQed.\n\nLemma same_com {N0 N V c Nmid Vmid cmid O1 W1 Nend1 Vend cend O2 W2}:\n  WARok (getdomain N0) [::] [::] c ->\n  subset_nvm N0 N ->\n  trace_cs (N, V, c) (Nmid, Vmid, cmid) O1 W1 ->\n  checkpoint \\notin O1 ->\n  trace_cs (N0 U! Nmid, V, c) (Nend1, Vend, cend) O2 W2 ->\n  checkpoint \\notin O2 ->\n  exists (Nend2: nvmem), trace_cs (N, V, c) (Nend2, Vend, cend) O2 W2.\n  intros Hwar Hsub Tmid Ho1 T2 Ho2.\n  move: (war_works Tmid Hsub Hwar Ho1) => Hdiff.\n  eapply same_com_help; try apply Hdiff; try assumption. apply T2.\nQed.\n\nLemma same_comi {N0 N V c O1 W1 Nend Vend cend }:\n  WARok (getdomain N0) [::] [::] c ->\n  subset_nvm N0 N ->\n  trace_i1 ((N0, V, c), N, V, c) ((N0, V, c), Nend, Vend, cend) O1 W1 ->\n  checkpoint \\notin O1 ->\n  exists (Nend2: nvmem) (Oc: obseq) (Wc: the_write_stuff), (trace_cs (N, V, c) (Nend2, Vend, cend) Oc Wc /\\\ncheckpoint \\notin Oc).\n  intros. dependent induction  H1.\n  exists Nend O W. split; assumption.\n  suffices:(exists Nend2 Oc Wc,\n               trace_cs (N0 U! Nmid, V, c)\n                 (Nend2, Vend, cend) Oc Wc /\\\n               checkpoint \\notin Oc\n           ). move => [Nend2 [Ocend [Wcend [Tend Hocend] ] ] ].\n  move: (same_com H H0 H3 H4 Tend Hocend) => [Nend0 Tdone].\n  exists Nend0 Ocend Wcend. split; assumption.\n  eapply IHtrace_i1; try reflexivity; try assumption.\n  apply sub_update.\n  repeat rewrite mem_cat in H2. move/norP: H2 => [Hblah H2].\n  move/norP: H2 => [contra Hb]. rewrite mem_seq1 in contra.\n    by case/eqP : contra.\n    Qed.\n\n   Lemma warok_cp {N1 N2 V1 V2 c crem O W Wstart Rstart}\n      {w0 w1: warvars}:\n  WARok w0 Wstart Rstart c ->\n  trace_cs (N1, V1, c) (N2, V2, incheckpoint w1;; crem) O W ->\n  WARok w1 [::] [::] crem. intros Hwar T.\n   move: N1 V1 N2 V2 O W T.\n   dependent induction Hwar; subst; intros.\n   2: {\n     destruct (O == [::]) eqn: Hbool; move/ eqP: Hbool => Hbool. subst.\n     move/empty_trace_cs1: T => [one two]. inversion one.\n     subst. assumption.\n     move: (single_step_alls_rev T Hbool). =>\n [ [ [nm vm] cm]\n     [W1\n        [Wrest\n           [ O1\n               [Hcceval\n                  [Hsub Hw]\n               ]\n           ]\n        ]\n ] ].\n     move: (cceval_steps Hcceval) => one. subst.\n     move: (single_step_alls T Hbool Hcceval). =>\n                                               [Wrest0 [Orest [Trest [Hsubr Hwr] ] ] ].\n     eapply IHHwar; try by []. apply Trest.\n   }\n   2: {\n     destruct (O == [::]) eqn: Hbool; move/ eqP: Hbool => Hbool. subst.\n     move/empty_trace_cs1: T => [one two]. inversion one.\n     subst. inversion H. \n     move: (single_step_alls_rev T Hbool). =>\n [ [ [nm vm] cm]\n     [W1\n        [Wrest\n           [ O1\n               [Hcceval\n                  [Hsub Hw]\n               ]\n           ]\n        ]\n ] ].\n     move: (cceval_steps Hcceval) => one. subst.\n     move: (single_step_alls T Hbool Hcceval). =>\n                                               [Wrest0 [Orest [Trest [Hsubr Hwr] ] ] ].\n     eapply IHHwar; try by []. apply Trest.\n   }\n   2: {\nsuffices: O <> [::]. move => Hneq.\n     move: (single_step_alls_rev T Hneq). =>\n [ [ [nm vm] cm]\n     [W1\n        [Wrest\n           [ O1\n               [Hcceval\n                  [Hsub Hw]\n               ]\n           ]\n        ]\n ] ].\n     move: (single_step_alls T Hneq Hcceval). =>\n                                              [Wrest0 [Orest [Trest [Hsubr Hwr] ] ] ].\n     inversion Hcceval; subst;\n       [eapply IHHwar1 | eapply IHHwar2]; try by []; apply Trest.\n     intros contra. subst.\n     move/ empty_trace_cs1: T => [one two]. inversion one.\n   }\n   move/ trace_skip1: T => [one | one]; inversion one.\n   Qed.\n", "meta": {"author": "naomiiiiiiiii", "repo": "intermittent_formalism", "sha": "ce918628977062aad77b0218495d559a502ed6c0", "save_path": "github-repos/coq/naomiiiiiiiii-intermittent_formalism", "path": "github-repos/coq/naomiiiiiiiii-intermittent_formalism/intermittent_formalism-ce918628977062aad77b0218495d559a502ed6c0/proofs_w.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6825737473266736, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.296224354701516}}
{"text": "\n\nTheorem all_equal : forall x y : Empty_set, x = y.\nProof.\n destruct x.\nQed.\n\n\nTheorem all_diff : forall x y : Empty_set, x <> y.\nProof.\n destruct x.\nQed.\n\n", "meta": {"author": "raduom", "repo": "coq-art", "sha": "092a8df8e74d7d7a90a2405e4eacf902e528d83a", "save_path": "github-repos/coq/raduom-coq-art", "path": "github-repos/coq/raduom-coq-art/coq-art-092a8df8e74d7d7a90a2405e4eacf902e528d83a/ch6_inductive_data/SRC/emptyset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6825737344123243, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.2962243490969277}}
{"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 R S Pprime Qprime Rprime Sprime A B X Y Qprimeprime Sprimeprime : Universe, ((wd_ A B /\\ (wd_ X Y /\\ (wd_ P Q /\\ (wd_ R S /\\ (wd_ Pprime Qprime /\\ (wd_ Rprime Sprime /\\ (wd_ Qprime Qprimeprime /\\ (wd_ Sprime Sprimeprime /\\ (wd_ Qprime Sprime /\\ (wd_ Pprime Rprime /\\ (wd_ Pprime Qprimeprime /\\ (wd_ B Qprimeprime /\\ (wd_ A Qprimeprime /\\ (wd_ Qprimeprime Sprimeprime /\\ (wd_ Rprime Sprimeprime /\\ (col_ A B Pprime /\\ (col_ A B Qprime /\\ (col_ A B Rprime /\\ (col_ A B Sprime /\\ (col_ Rprime Pprime Qprimeprime /\\ (col_ Rprime Pprime Sprimeprime /\\ col_ Pprime Rprime A))))))))))))))))))))) -> col_ Pprime Rprime B)).\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_0880.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2961809529932895}}
{"text": "From stdpp Require Import namespaces strings.\n\nLemma test1 (N1 N2 : namespace) :\n  N1 ## N2 → ↑N1 ⊆@{coPset} ⊤ ∖ ↑N2.\nProof. solve_ndisj. Qed.\n\nLemma test2 (N1 N2 : namespace) :\n  N1 ## N2 → ↑N1.@\"x\" ⊆@{coPset} ⊤ ∖ ↑N1.@\"y\" ∖ ↑N2.\nProof. solve_ndisj. Qed.\n\nLemma test3 (N : namespace) :\n  ⊤ ∖ ↑N ⊆@{coPset} ⊤ ∖ ↑N.@\"x\".\nProof. solve_ndisj. Qed.\n\nLemma test4 (N : namespace) :\n  ⊤ ∖ ↑N ⊆@{coPset} ⊤ ∖ ↑N.@\"x\" ∖ ↑N.@\"y\".\nProof. solve_ndisj. Qed.\n\nLemma test5 (N1 N2 : namespace) :\n  ⊤ ∖ ↑N1 ∖ ↑N2 ⊆@{coPset} ⊤ ∖ ↑N1.@\"x\" ∖ ↑N2 ∖ ↑N1.@\"y\".\nProof. solve_ndisj. Qed.\n", "meta": {"author": "SkySkimmer", "repo": "stdpp", "sha": "a40580e6d7e6cd16e60aba6deed496a301804c9f", "save_path": "github-repos/coq/SkySkimmer-stdpp", "path": "github-repos/coq/SkySkimmer-stdpp/stdpp-a40580e6d7e6cd16e60aba6deed496a301804c9f/tests/solve_ndisj.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.29615662377441315}}
{"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 Implicit Arguments.\nUnset Strict Implicit.\nRequire Export Fpart2.\nSection tiroirs_def.\nVariable E F : Setoid.\nVariable f : MAP E F.\n\nLemma diff_add_part2 :\n forall (E : Setoid) (A : part_set E) (x : E),\n in_part x A -> Equal A (add_part (diff A (single x)) x).\nintros E0 A x H'; try assumption.\napply in_eq_part.\nintros x0 H'0; try assumption.\nelim (classic (Equal x x0)); intros.\napply in_part_trans_eq with x; auto with *.\ncut (in_part x0 (diff A (single x))).\nunfold add_part in |- *; auto with *.\napply in_diff; auto with *.\nintros x0 H'0; try assumption.\nelim (classic (Equal x x0)); intros.\napply in_part_trans_eq with x; auto with *.\ncut (in_part x0 (diff A (single x))).\nintros H'1; try assumption.\napply diff_in_l with (single x).\nauto with *.\nunfold add_part in H'0.\nelim (in_part_union H'0); intros.\nauto with *.\nabsurd (Equal x x0); auto with *.\nQed.\nHint Resolve diff_add_part2: algebra.\n\nLemma cardinal_minus_part :\n forall (B : part_set F) (x : F) (n : nat),\n cardinal B (S n) -> in_part x B -> cardinal (diff B (single x)) n.\nintros B x n H' H'0; try assumption.\napply cardinal_S with B x; auto with *.\nunfold not in |- *; intros.\ncut (~ in_part x (single x)).\nunfold not in |- *; auto with *.\napply diff_in_r with B; auto with *.\nQed.\nHint Resolve cardinal_minus_part: algebra.\n\nLemma tiroirs :\n forall (n : nat) (Chaussettes : part_set E),\n cardinal Chaussettes n ->\n forall (m : nat) (Tiroirs : part_set F),\n cardinal Tiroirs m ->\n m < n ->\n (forall x : E, in_part x Chaussettes -> in_part (f x) Tiroirs) ->\n exists x : E, (exists y : E, ~ Equal x y /\\ Equal (f x) (f y)).\nsimple induction n.\nintros Chaussettes H' m Tiroirs H'0 H'1; try assumption.\ninversion H'1.\nintros n0 H' Chaussettes H'0 m Tiroirs H'1 H'2 H'3; try assumption.\ninversion H'0.\nelim (classic (ex (fun y : E => ~ Equal x y /\\ Equal (Ap f x) (Ap f y))));\n intros.\nexists x; try assumption.\ncut (exists m0 : nat, m = S m0).\nintros H'4; try assumption.\ncase H'4; clear H'4; intros.\napply H' with (diff Chaussettes (single x)) x0 (diff Tiroirs (single (f x))).\napply cardinal_S with Chaussettes x.\nunfold not in |- *; intros.\nabsurd (~ in_part x (single x)); auto with *.\napply diff_in_r with Chaussettes; auto with *.\nauto with *.\napply diff_add_part2.\napply in_part_comp_r with (add_part B x); auto with *.\nauto with *.\napply cardinal_minus_part.\nrewrite <- H5; auto with *.\napply H'3; auto with *.\napply in_part_comp_r with (add_part B x).\nauto with *.\nauto with *.\nrewrite H5 in H'2; auto with *.\nintros x1 H'4; try assumption.\napply in_diff.\napply H'3; auto with *.\napply diff_in_l with (single x); auto with *.\nunfold not in |- *; intros.\nunfold not in H4.\napply H4.\nexists x1; try assumption.\nsplit.\nintros H'5; try assumption.\ncut (~ in_part x1 (single x)).\nintro.\napply H7.\napply in_part_trans_eq with x; auto with *.\napply diff_in_r with Chaussettes; auto with *.\nauto with *.\ninversion H'1.\ncut (in_part (f x) Tiroirs).\nintros H'4; try assumption.\nabsurd (in_part (f x) (empty F)); auto with *.\napply in_part_comp_r with Tiroirs; auto with *.\napply H'3.\napply in_part_comp_r with (add_part B x); auto with *.\nexists n2; try assumption.\nauto with *.\nQed.\nEnd tiroirs_def.\n", "meta": {"author": "coq-contribs", "repo": "algebra", "sha": "4006abe46420df0394e20f0fb19279f64bb8501e", "save_path": "github-repos/coq/coq-contribs-algebra", "path": "github-repos/coq/coq-contribs-algebra/algebra-4006abe46420df0394e20f0fb19279f64bb8501e/Tiroirs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.29615662377441315}}
{"text": "Require Import SpecCert.x86.Architecture.\n\nDefinition lock_smramc_pre\n           {Label: Type} :=\n  fun (a:Architecture Label) =>\n    smramc_is_unlocked (memory_controller a).\n\nDefinition lock_smramc_post\n           {Label: Type} :=\n  fun (a a':Architecture Label) =>\n    exists h, let m' := lock_smramc (memory_controller a) h\n    in a' = update_memory_controller a m'.\n", "meta": {"author": "lthms", "repo": "speccert", "sha": "8c1edfb173548af0e9ca3c4e24d43726401fdb71", "save_path": "github-repos/coq/lthms-speccert", "path": "github-repos/coq/lthms-speccert/speccert-8c1edfb173548af0e9ca3c4e24d43726401fdb71/src/x86/Transition/Event/LockSmramc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.29615661095992324}}
{"text": "Require Import HoTT.\nRequire Import UnivalenceAxiom.\n\nRequire Import HoTTEx.\nRequire Import Denotation.\nRequire Import UnivalentSemantics.\nRequire Import AutoTactics.\n\nOpen Scope type.\n\nModule SubqueryOptimization (T : Types) (S : Schemas T) (R : Relations T S)  (A : Aggregators T S).\n  Import T S R A.\n  Module SQL_TSRA := SQL T S R A.\n  Import SQL_TSRA.\n  Module AutoTac := AutoTactics T S R A.\n  Import AutoTac.\n\n  Definition InlineCorrelatedSubquery : Type.\n    refine (forall (Γ s: Schema) (a : relation s) ty (c : Column ty s), _).\n    pose (@variable ty ((Γ ++ s) ++ s) (left⋅right⋅c)) as v0.\n    pose (@variable ty ((Γ ++ s) ++ s) (right⋅c)) as v1.\n    refine (⟦ Γ ⊢ (SELECT * FROM1 table a WHERE (EXISTS (SELECT * FROM1 table a WHERE (equal v0 v1)))) : s ⟧ = \n            ⟦ Γ ⊢ (SELECT * FROM1 table a) : s ⟧); revgoals.\n  Defined.\n  Arguments InlineCorrelatedSubquery /. \n\n  Lemma inlineCorrelatedSubquery : InlineCorrelatedSubquery.\n    solve_summation.\n    \n  Defined.\n  \n  (* \n  Pull up subqueries in FROM clause. Query before:\n     SELECT *\n     FROM A, (SELECT * FROM B WHERE <p>) as C\n     WHERE slct\n  Query after:\n     SELECT *\n     FROM A, B\n     WHERE slct AND <p'>\n  One thing that needs noticing is that <p> and <p'> are on different context\n   *)\n  Definition PullUpSubqueryInFrom : Type.\n    refine (forall Γ (s1 s2: Schema) (a : SQL Γ s1) (b: SQL Γ s2)\n                (slct1: Pred (Γ ++ s1 ++ s2)) \n                (slct0: Pred (Γ ++ s2)), \n        ⟦Γ ⊢ (SELECT * FROM2 a, (SELECT * FROM1 b WHERE slct0 ) WHERE slct1 ): _ ⟧ =\n        ⟦Γ ⊢ (SELECT * FROM2 a, b WHERE slct1 AND _ slct0) : _ ⟧).\n    refine (castPred (combine left (right⋅right))).\n  Defined.\n  \n  Arguments PullUpSubqueryInFrom /.\n   \n  Lemma pullUpSubqueryInFrom : PullUpSubqueryInFrom.\n    hott_ring. \n  Qed.\nEnd SubqueryOptimization.\n", "meta": {"author": "pldi2017paper50", "repo": "DopCert", "sha": "9f540ab3fd609c78b98009605723d1e9ed35bca5", "save_path": "github-repos/coq/pldi2017paper50-DopCert", "path": "github-repos/coq/pldi2017paper50-DopCert/DopCert-9f540ab3fd609c78b98009605723d1e9ed35bca5/hott/optimizations/Subquery.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.29615661095992324}}
{"text": "Require Import Util EqDec DecSolve Val CSet Map Envs Option Get SetOperations IL.Events.\nRequire Export MoreList Isa.Ops.\n\nSet Implicit Arguments.\n\n(** * Extended Expressions *)\n\nInductive exp :=\n| Operation (e:op)\n| Call (f:external) (Y:list op).\n\nDefinition isCall e :=\n  match e with\n  | Operation _ => false\n  | Call _ _ => true\n  end.\n\nDefinition externals (e:exp) :=\n  match e with\n  | Operation _ => {}\n  | Call f _ => singleton f\n  end.\n\nInstance inst_eq_dec_exp : EqDec exp eq.\nProof.\n  hnf; intros. change ({x = y} + {x <> y}).\n  decide equality.\n  - eapply inst_eq_dec_op.\n  - eapply list_eq_dec.\n    intros. eapply inst_eq_dec_op.\n  - eapply Pos.eq_dec.\nDefined.\n\nDefinition freeVars (e:exp) :=\n  match e with\n  | Operation e => Ops.freeVars e\n  | Call f Y => list_union (List.map Ops.freeVars Y)\n  end.\n\n(** ** Renaming *)\n\nDefinition rename_exp (ϱ:env var) (e:exp) :=\n  match e with\n  | Operation e => Operation (rename_op ϱ e)\n  | Call f Y => Call f (List.map (rename_op ϱ) Y)\n  end.\n\nLemma rename_exp_comp e ϱ ϱ'\n  : rename_exp ϱ (rename_exp ϱ' e) = rename_exp (ϱ' ∘ ϱ) e.\nProof.\n  unfold comp. general induction e; simpl; eauto.\n  - f_equal; eauto using rename_op_comp.\n  - f_equal; eauto.\n    rewrite map_map. setoid_rewrite rename_op_comp; eauto.\nQed.\n\nLemma rename_exp_ext\n  : forall e (ϱ ϱ':env var), feq (R:=eq) ϱ ϱ' -> rename_exp ϱ e = rename_exp ϱ' e.\nProof.\n  intros. general induction e; simpl; eauto.\n  - f_equal; eauto using rename_op_ext.\n  - f_equal; eauto.\n    abstract (eapply map_ext; eauto using rename_op_ext) using rename_op_list_ext.\nDefined.\n\nLemma rename_exp_agree ϱ ϱ' e\n  : agree_on eq (freeVars e) ϱ ϱ'\n    -> rename_exp ϱ e = rename_exp ϱ' e.\nProof.\n  intros; general induction e; simpl in *; f_equal;\n    eauto 30 using agree_on_incl, incl_left, incl_right, rename_op_agree.\n  - clear f.\n    abstract (eapply MoreList.map_ext_get_eq; intros; inv_get; eauto with len;\n    eapply rename_op_agree;\n    eapply agree_on_incl; eauto; eapply incl_list_union; eauto using map_get_1) using\n        rename_op_list_agree.\nDefined.\n\nLemma rename_exp_freeVars\n  : forall e ϱ `{Proper _ (_eq ==> _eq) ϱ},\n    freeVars (rename_exp ϱ e) ⊆ lookup_set ϱ (freeVars e).\nProof.\n  intros. general induction e; simpl.\n  - eapply rename_op_freeVars; eauto.\n  - clear f.\n    abstract (eapply list_union_incl; eauto with cset;\n      intros; inv_get; rewrite lookup_set_list_union; eauto using lookup_set_empty;\n      eapply incl_list_union; eauto using map_get_1, rename_op_freeVars)\n             using rename_op_list_freeVars.\nDefined.\n\n(** ** Liveness *)\n\nInductive live_exp_sound : exp -> set var -> Prop :=\n| OperationLiveSound e lv\n  : live_op_sound e lv -> live_exp_sound (Operation e) lv\n| CallLiveSound f Y lv\n  : (forall n e, get Y n e -> live_op_sound e lv)\n    -> live_exp_sound (Call f Y) lv.\n\nInstance live_exp_sound_Subset e\n  : Proper (Subset ==> impl) (live_exp_sound e).\nProof.\n  unfold Proper, respectful, impl; intros.\n  general induction e.\n  - invt live_exp_sound. econstructor. eapply live_op_sound_Subset; eauto.\n  - inv H0; econstructor; intros. eapply live_op_sound_Subset; eauto.\nQed.\n\nInstance live_op_sound_Equal e\n  : Proper (Equal ==> iff) (live_exp_sound e).\nProof.\n  unfold Proper, respectful, impl; split; intros.\n  - eapply subset_equal in H. rewrite H in H0; eauto.\n  - symmetry in H. eapply subset_equal in H.\n    rewrite <- H; eauto.\nQed.\n\n\nInstance live_op_sound_dec e lv\n  : Computable (live_exp_sound e lv).\nProof.\n  induction e; try dec_solve.\n  - decide (live_op_sound e lv); dec_solve.\n  - decide ( forall (n : nat) (e : op), get Y n e -> live_op_sound e lv); try dec_solve.\nQed.\n\nLemma live_exp_sound_incl\n  : forall e lv lv', live_exp_sound e lv' -> lv' ⊆ lv -> live_exp_sound e lv.\nProof.\n  intros. rewrite <- H0; eauto.\nQed.\n\nLemma freeVars_live e lv\n  : live_exp_sound e lv -> freeVars e ⊆ lv.\nProof.\n  intros. general induction H; simpl; eauto using Ops.freeVars_live, Ops.freeVars_live_list.\nQed.\n\nLemma freeVars_live_list Y lv\n  : (forall (n : nat) (y : exp), get Y n y -> live_exp_sound y lv)\n    -> list_union (freeVars ⊝ Y) ⊆ lv.\nProof.\n  intros H. eapply list_union_incl; intros; inv_get; eauto using freeVars_live with cset.\nQed.\n\nLemma live_exp_rename_sound e lv (ϱ:env var)\n  : live_exp_sound e lv\n    -> live_exp_sound (rename_exp ϱ e) (lookup_set ϱ lv).\nProof.\n  intros.\n  general induction H; simpl; econstructor; intros; inv_get; eauto using live_op_rename_sound.\nQed.\n\nLemma live_freeVars\n  : forall e, live_exp_sound e (freeVars e).\nProof.\n  intros. general induction e; simpl; econstructor;\n            eauto using Ops.live_freeVars with cset.\n  intros. eapply live_op_sound_incl.\n  eapply Ops.live_freeVars.\n  eapply incl_list_union; eauto using map_get_1.\nQed.\n\n(** ** Alpha Equivalence *)\n\nInductive alpha_exp : env var -> env var -> exp -> exp -> Prop :=\n| AlphaOperation ϱ ϱ' e e' :\n    alpha_op ϱ ϱ' e e'\n    -> alpha_exp ϱ ϱ' (Operation e) (Operation e')\n| AlphaCall ϱ ϱ' f Y Y' :\n    length Y = length Y'\n  -> (forall n x y, get Y n x -> get Y' n y -> alpha_op ϱ ϱ' x y)\n  -> alpha_exp ϱ ϱ' (Call f Y) (Call f Y').\n\nLemma alpha_exp_rename_injective\n  : forall e ϱ ϱ',\n    inverse_on (freeVars e) ϱ ϱ'\n    -> alpha_exp ϱ ϱ' e (rename_exp ϱ e).\nProof.\n  intros. induction e; simpl; eauto using alpha_exp, alpha_op_rename_injective.\n  econstructor; eauto with len.\n  intros; inv_get. eapply alpha_op_rename_injective.\n  eapply inverse_on_incl; eauto; simpl. eapply incl_list_union; eauto using map_get_1.\nQed.\n\nLemma alpha_exp_refl : forall e, alpha_exp id id e e.\nProof.\n  intros; induction e; eauto 20 using alpha_exp, alpha_op_refl.\n  econstructor; eauto. intros. get_functional. eapply alpha_op_refl.\nQed.\n\nLemma alpha_exp_sym : forall ϱ ϱ' e e', alpha_exp ϱ ϱ' e e' -> alpha_exp ϱ' ϱ e' e.\nProof.\n  intros. general induction H; eauto using alpha_exp, alpha_op_sym.\nQed.\n\nSet Regular Subst Tactic.\n\nLemma alpha_exp_trans\n  : forall ϱ1 ϱ1' ϱ2 ϱ2' s s' s'',\n    alpha_exp ϱ1 ϱ1' s s'\n    -> alpha_exp ϱ2 ϱ2' s' s''\n    -> alpha_exp (ϱ1 ∘ ϱ2) (ϱ2' ∘ ϱ1') s s''.\nProof.\n  intros. general induction H; invt alpha_exp; eauto using alpha_exp, alpha_op_trans.\n  - econstructor; eauto with len.\n    intros. inv_get. eapply alpha_op_trans; eauto.\nQed.\n\nUnset Regular Subst Tactic.\n\nLemma alpha_exp_inverse_on\n  : forall ϱ ϱ' s t, alpha_exp ϱ ϱ' s t -> inverse_on (freeVars s) ϱ ϱ'.\nProof.\n  intros. general induction H; simpl; eauto using alpha_op_inverse_on.\n  + eapply inverse_on_list_union; eauto.\n    intros; inv_get. eauto using alpha_op_inverse_on.\nQed.\n\nLemma alpha_exp_agree_on_morph\n  : forall f g ϱ ϱ' s t,\n    alpha_exp ϱ ϱ' s t\n    -> agree_on _eq (lookup_set ϱ (freeVars s)) g ϱ'\n    -> agree_on _eq (freeVars s) f ϱ\n    -> alpha_exp f g s t.\nProof.\n  intros.\n  general induction H; simpl in *;\n    eauto using alpha_exp, alpha_op_agree_on_morph.\n  - econstructor; eauto. clear H f.\n    abstract (intros; eapply alpha_op_agree_on_morph; eauto;\n      [ eapply agree_on_incl; eauto;\n        rewrite SetOperations.lookup_set_list_union; eauto using lookup_set_empty;\n        eapply incl_list_union; eauto using map_get_1\n      |  eauto with cset ])\n    using alpha_op_list_agree_on_morph.\nDefined.\n\nLemma exp_rename_renamedApart_all_alpha e e' ϱ ϱ'\n  : alpha_exp ϱ ϱ' e e'\n    -> rename_exp ϱ e = e'.\nProof.\n  intros. general induction H; simpl; f_equal; eauto using op_rename_renamedApart_all_alpha.\n  eapply map_ext_get_eq; intros; eauto using op_rename_renamedApart_all_alpha.\nQed.\n\nLemma alpha_exp_morph\n  : forall (ϱ1 ϱ1' ϱ2 ϱ2':env var) e e',\n    @feq _ _ eq ϱ1  ϱ1'\n    -> @feq _ _ eq ϱ2 ϱ2'\n    -> alpha_exp ϱ1 ϱ2 e e'\n    -> alpha_exp ϱ1' ϱ2' e e'.\nProof.\n  intros. general induction H1; eauto using alpha_exp, alpha_op_morph.\nQed.\n\nLemma freeVars_renameExp ϱ e\n  : freeVars (rename_exp ϱ e) [=] lookup_set ϱ (freeVars e).\nProof.\n  general induction e; simpl;\n    eauto using freeVars_rename_op_list, freeVars_renameOp.\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/IL/Exp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.29614125860929985}}
{"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 ZArith.\n\nFrom compcert Require Import Integers.\n\nOpen Scope nat_scope.\n\nInductive opcode_alu64: Type := (**r 0xX7 *)\n  (** ALU64:13 *)\n  | op_BPF_ADD64\n  | op_BPF_SUB64\n  | op_BPF_MUL64\n  | op_BPF_DIV64\n  | op_BPF_OR64\n  | op_BPF_AND64\n  | op_BPF_LSH64\n  | op_BPF_RSH64\n  | op_BPF_NEG64\n  | op_BPF_MOD64\n  | op_BPF_XOR64\n  | op_BPF_MOV64\n  | op_BPF_ARSH64\n  | op_BPF_ALU64_ILLEGAL_INS.\n\n(**\n#define BPF_INSTRUCTION_ALU_OP_MASK     0xf0\n\n#define BPF_INSTRUCTION_ALU_ADD         0x00\n#define BPF_INSTRUCTION_ALU_SUB         0x10\n#define BPF_INSTRUCTION_ALU_MUL         0x20\n#define BPF_INSTRUCTION_ALU_DIV         0x30\n#define BPF_INSTRUCTION_ALU_OR          0x40\n#define BPF_INSTRUCTION_ALU_AND         0x50\n#define BPF_INSTRUCTION_ALU_LSH         0x60\n#define BPF_INSTRUCTION_ALU_RSH         0x70\n#define BPF_INSTRUCTION_ALU_NEG         0x80\n#define BPF_INSTRUCTION_ALU_MOD         0x90\n#define BPF_INSTRUCTION_ALU_XOR         0xA0\n#define BPF_INSTRUCTION_ALU_MOV         0xB0\n#define BPF_INSTRUCTION_ALU_ARSH        0xC0\n\n*)\n\nDefinition byte_to_opcode_alu64 (op: nat): opcode_alu64 :=\n  let opcode_alu := Nat.land op 0xf0 in (**r masking operation *)\n    match opcode_alu with\n    | 0x00 => op_BPF_ADD64\n    | 0x10 => op_BPF_SUB64\n    | 0x20 => op_BPF_MUL64\n    | 0x30 => op_BPF_DIV64\n    | 0x40 => op_BPF_OR64\n    | 0x50 => op_BPF_AND64\n    | 0x60 => op_BPF_LSH64\n    | 0x70 => op_BPF_RSH64\n    | 0x80 => op_BPF_NEG64 (*if Nat.eqb op 0x87 then op_BPF_NEG64 else op_BPF_ALU64_ILLEGAL_INS*)\n    | 0x90 => op_BPF_MOD64\n    | 0xa0 => op_BPF_XOR64\n    | 0xb0 => op_BPF_MOV64\n    | 0xc0 => op_BPF_ARSH64\n    | _    => op_BPF_ALU64_ILLEGAL_INS\n    end.\n\nInductive opcode_alu32: Type := (**r 0xX4 *)\n  (** ALU32:13 *)\n  | op_BPF_ADD32\n  | op_BPF_SUB32\n  | op_BPF_MUL32\n  | op_BPF_DIV32\n  | op_BPF_OR32\n  | op_BPF_AND32\n  | op_BPF_LSH32\n  | op_BPF_RSH32\n  | op_BPF_NEG32\n  | op_BPF_MOD32\n  | op_BPF_XOR32\n  | op_BPF_MOV32\n  | op_BPF_ARSH32\n  | op_BPF_ALU32_ILLEGAL_INS.\n\n\nDefinition byte_to_opcode_alu32 (op: nat): opcode_alu32 :=\n  let opcode_alu := Nat.land op 0xf0 in (**r masking operation *)\n    match opcode_alu with\n    | 0x00 => op_BPF_ADD32\n    | 0x10 => op_BPF_SUB32\n    | 0x20 => op_BPF_MUL32\n    | 0x30 => op_BPF_DIV32\n    | 0x40 => op_BPF_OR32\n    | 0x50 => op_BPF_AND32\n    | 0x60 => op_BPF_LSH32\n    | 0x70 => op_BPF_RSH32\n    | 0x80 => op_BPF_NEG32 (*\n    | 0x80 => if Nat.eqb op 0x84 then op_BPF_NEG32 else op_BPF_ALU32_ILLEGAL_INS *)\n    | 0x90 => op_BPF_MOD32\n    | 0xa0 => op_BPF_XOR32\n    | 0xb0 => op_BPF_MOV32\n    | 0xc0 => op_BPF_ARSH32\n    | _    => op_BPF_ALU32_ILLEGAL_INS\n    end.\n\nInductive opcode_branch: Type := (**r 0xX5 *)\n  (**Branch: 13 *)\n  | op_BPF_JA\n  | op_BPF_JEQ\n  | op_BPF_JGT\n  | op_BPF_JGE\n  | op_BPF_JLT\n  | op_BPF_JLE\n  | op_BPF_JSET\n  | op_BPF_JNE\n  | op_BPF_JSGT\n  | op_BPF_JSGE\n  | op_BPF_JSLT\n  | op_BPF_JSLE\n  | op_BPF_CALL\n  | op_BPF_RET\n  | op_BPF_JMP_ILLEGAL_INS.\n\n(**\n#define BPF_INSTRUCTION_ALU_OP_MASK     0xf0\n\n#define BPF_INSTRUCTION_BRANCH_JA       0x00\n#define BPF_INSTRUCTION_BRANCH_JEQ      0x10\n#define BPF_INSTRUCTION_BRANCH_JGT      0x20\n#define BPF_INSTRUCTION_BRANCH_JGE      0x30\n#define BPF_INSTRUCTION_BRANCH_JLT      0xa0\n#define BPF_INSTRUCTION_BRANCH_JLE      0xb0\n#define BPF_INSTRUCTION_BRANCH_JSET     0x40\n#define BPF_INSTRUCTION_BRANCH_JNE      0x50\n#define BPF_INSTRUCTION_BRANCH_JSGT     0x60\n#define BPF_INSTRUCTION_BRANCH_JSGE     0x70\n#define BPF_INSTRUCTION_BRANCH_JSLT     0xc0\n#define BPF_INSTRUCTION_BRANCH_JSLE     0xd0\n#define BPF_INSTRUCTION_BRANCH_CALL     0x80\n#define BPF_INSTRUCTION_BRANCH_EXIT     0x90\n*)\n\n(**r\nthere is an error:\n\nopcode = 0x0d -> ja\n\n0x0d & 0x07 = 0x05 i.e. op_BPF_Branch\n\n0x0d & 0xf0 = 0x00 i.e. op_BPF_JA\n\n*)\nDefinition byte_to_opcode_branch (op: nat): opcode_branch :=\n  let opcode_jmp := Nat.land op 0xf0 in (**r masking operation *)\n    match opcode_jmp with\n    | 0x00 => op_BPF_JA (*\n    | 0x00 => if Nat.eqb op 0x05 then op_BPF_JA else op_BPF_JMP_ILLEGAL_INS *)\n    | 0x10 => op_BPF_JEQ\n    | 0x20 => op_BPF_JGT\n    | 0x30 => op_BPF_JGE\n    | 0xa0 => op_BPF_JLT\n    | 0xb0 => op_BPF_JLE\n    | 0x40 => op_BPF_JSET\n    | 0x50 => op_BPF_JNE\n    | 0x60 => op_BPF_JSGT\n    | 0x70 => op_BPF_JSGE\n    | 0xc0 => op_BPF_JSLT\n    | 0xd0 => op_BPF_JSLE\n    | 0x80 => op_BPF_CALL\n    | 0x90 => op_BPF_RET (*\n    | 0x80 => if Nat.eqb op 0x85 then op_BPF_CALL else op_BPF_JMP_ILLEGAL_INS\n    | 0x90 => if Nat.eqb op 0x95 then op_BPF_RET else op_BPF_JMP_ILLEGAL_INS *)\n    | _    => op_BPF_JMP_ILLEGAL_INS\n    end.\n\nInductive opcode_mem_ld_imm: Type :=  (**r 0xX8 *)\n  (** Load/Store: 13 *)\n  | op_BPF_LDDW_low\n  | op_BPF_LDDW_high\n  | op_BPF_LDX_IMM_ILLEGAL_INS.\n\nDefinition byte_to_opcode_mem_ld_imm (op: nat): opcode_mem_ld_imm :=\n  let opcode_ld := Nat.land op 0xff in (**r masking operation *)\n    match opcode_ld with\n    | 0x18 => op_BPF_LDDW_low\n    | 0x10 => op_BPF_LDDW_high\n    | _    => op_BPF_LDX_IMM_ILLEGAL_INS\n    end.\n\nInductive opcode_mem_ld_reg: Type :=  (**r 0xX1/0xX9 *)\n  (** Load/Store: 13 *)\n  | op_BPF_LDXW\n  | op_BPF_LDXH\n  | op_BPF_LDXB\n  | op_BPF_LDXDW\n  | op_BPF_LDX_REG_ILLEGAL_INS.\n\nDefinition byte_to_opcode_mem_ld_reg (op: nat): opcode_mem_ld_reg :=\n  let opcode_ld := Nat.land op 0xff in (**r masking operation *)\n    match opcode_ld with\n    | 0x61 => op_BPF_LDXW\n    | 0x69 => op_BPF_LDXH\n    | 0x71 => op_BPF_LDXB\n    | 0x79 => op_BPF_LDXDW\n    | _    => op_BPF_LDX_REG_ILLEGAL_INS\n    end.\n\nInductive opcode_mem_st_imm: Type :=  (**r 0xX2/0xXa *)\n  | op_BPF_STW\n  | op_BPF_STH\n  | op_BPF_STB\n  | op_BPF_STDW\n  | op_BPF_ST_ILLEGAL_INS.\n\nDefinition byte_to_opcode_mem_st_imm (op: nat): opcode_mem_st_imm :=\n  let opcode_st := Nat.land op 0xff in (**r masking operation *)\n    match opcode_st with\n    | 0x62 => op_BPF_STW\n    | 0x6a => op_BPF_STH\n    | 0x72 => op_BPF_STB\n    | 0x7a => op_BPF_STDW\n    | _    => op_BPF_ST_ILLEGAL_INS\n    end.\n\nInductive opcode_mem_st_reg: Type :=  (**r 0xX3/0xXb *)\n  | op_BPF_STXW\n  | op_BPF_STXH\n  | op_BPF_STXB\n  | op_BPF_STXDW\n  | op_BPF_STX_ILLEGAL_INS.\n\nDefinition byte_to_opcode_mem_st_reg (op: nat): opcode_mem_st_reg :=\n  let opcode_st := Nat.land op 0xff in (**r masking operation *)\n    match opcode_st with\n    | 0x63 => op_BPF_STXW\n    | 0x6b => op_BPF_STXH\n    | 0x73 => op_BPF_STXB\n    | 0x7b => op_BPF_STXDW\n    | _    => op_BPF_STX_ILLEGAL_INS\n    end.\n\nInductive opcode: Type :=\n  | op_BPF_ALU64   (**r 0xX7 / 0xXf *)\n  | op_BPF_ALU32   (**r 0xX4 / 0xXc *)\n  | op_BPF_Branch  (**r 0xX5 / 0xXd *)\n  | op_BPF_Mem_ld_imm  (**r 0xX8 *)\n  | op_BPF_Mem_ld_reg  (**r 0xX1/0xX9 *)\n  | op_BPF_Mem_st_imm  (**r 0xX2/0xXa *)\n  | op_BPF_Mem_st_reg  (**r 0xX3/0xXb *)\n\n  | op_BPF_ILLEGAL_INS.\n\n(**\n#define BPF_INSTRUCTION_CLS_MASK        0x07\n\n#define BPF_INSTRUCTION_CLS_LD          0x00\n#define BPF_INSTRUCTION_CLS_LDX         0x01\n#define BPF_INSTRUCTION_CLS_ST          0x02\n#define BPF_INSTRUCTION_CLS_STX         0x03\n#define BPF_INSTRUCTION_CLS_ALU32       0x04\n#define BPF_INSTRUCTION_CLS_BRANCH      0x05\n#define BPF_INSTRUCTION_CLS_ALU64       0x07\n*)\nDefinition byte_to_opcode (op: nat): opcode :=\n  let opc := Nat.land op 0x07 in (**r masking operation *)\n    match opc with\n    | 0x07 => op_BPF_ALU64\n    | 0x04 => op_BPF_ALU32\n    | 0x05 => op_BPF_Branch\n    | 0x00 => op_BPF_Mem_ld_imm\n    | 0x01 => op_BPF_Mem_ld_reg\n    | 0x02 => op_BPF_Mem_st_imm\n    | 0x03 => op_BPF_Mem_st_reg\n    | _    => op_BPF_ILLEGAL_INS\n    end.\n\n(*\nDefinition int64_to_opcode (ins: int64): nat :=\n  Z.to_nat (Z.land (Int.unsigned (Int.repr\n    (Int64.unsigned (Int64.and ins (Int64.repr 0xff)))\n    )) 0xff).\nInt64.unsigned (Int64.and ins (Int64.repr 0xff))). *)\n\n(******************** Dx related *******************)\n\nDefinition opcode_alu64_eqb  (o o' : opcode_alu64): bool :=\n  match o , o' with\n  | op_BPF_ADD64, op_BPF_ADD64\n  | op_BPF_SUB64, op_BPF_SUB64\n  | op_BPF_MUL64, op_BPF_MUL64\n  | op_BPF_DIV64, op_BPF_DIV64\n  | op_BPF_OR64,  op_BPF_OR64\n  | op_BPF_AND64, op_BPF_AND64\n  | op_BPF_LSH64, op_BPF_LSH64\n  | op_BPF_RSH64, op_BPF_RSH64\n  | op_BPF_NEG64,  op_BPF_NEG64\n  | op_BPF_MOD64, op_BPF_MOD64\n  | op_BPF_XOR64, op_BPF_XOR64\n  | op_BPF_MOV64, op_BPF_MOV64\n  | op_BPF_ARSH64,op_BPF_ARSH64\n  | op_BPF_ALU64_ILLEGAL_INS, op_BPF_ALU64_ILLEGAL_INS => true\n  | _, _ => false\n  end.\n\nDefinition opcode_alu32_eqb  (o o' : opcode_alu32) : bool :=\n  match o , o' with\n  | op_BPF_ADD32, op_BPF_ADD32\n  | op_BPF_SUB32, op_BPF_SUB32\n  | op_BPF_MUL32, op_BPF_MUL32\n  | op_BPF_DIV32, op_BPF_DIV32\n  | op_BPF_OR32,  op_BPF_OR32\n  | op_BPF_AND32, op_BPF_AND32\n  | op_BPF_LSH32, op_BPF_LSH32\n  | op_BPF_RSH32, op_BPF_RSH32\n  | op_BPF_NEG32,  op_BPF_NEG32\n  | op_BPF_MOD32, op_BPF_MOD32\n  | op_BPF_XOR32, op_BPF_XOR32\n  | op_BPF_MOV32, op_BPF_MOV32\n  | op_BPF_ARSH32,op_BPF_ARSH32\n  | op_BPF_ALU32_ILLEGAL_INS, op_BPF_ALU32_ILLEGAL_INS => true\n  | _, _ => false\n  end.\n\nDefinition opcode_branch_eqb (o o' : opcode_branch): bool :=\n  match o , o' with\n  | op_BPF_JA,    op_BPF_JA\n  | op_BPF_JEQ,   op_BPF_JEQ\n  | op_BPF_JGT,   op_BPF_JGT\n  | op_BPF_JGE,   op_BPF_JGE\n  | op_BPF_JLT,   op_BPF_JLT\n  | op_BPF_JLE,   op_BPF_JLE\n  | op_BPF_JSET,  op_BPF_JSET\n  | op_BPF_JNE,   op_BPF_JNE\n  | op_BPF_JSGT,  op_BPF_JSGT\n  | op_BPF_JSGE,  op_BPF_JSGE\n  | op_BPF_JSLT,  op_BPF_JSLT\n  | op_BPF_JSLE,  op_BPF_JSLE\n  | op_BPF_CALL,  op_BPF_CALL\n  | op_BPF_RET,   op_BPF_RET\n  | op_BPF_JMP_ILLEGAL_INS, op_BPF_JMP_ILLEGAL_INS => true\n  | _, _ => false\n  end.\n\nDefinition opcode_mem_ld_imm_eqb (o o' : opcode_mem_ld_imm): bool :=\n  match o , o' with\n  | op_BPF_LDDW_low,   op_BPF_LDDW_low\n  | op_BPF_LDDW_high,   op_BPF_LDDW_high\n  | op_BPF_LDX_IMM_ILLEGAL_INS, op_BPF_LDX_IMM_ILLEGAL_INS => true\n  | _, _ => false\n  end.\n\nDefinition opcode_mem_ld_reg_eqb (o o' : opcode_mem_ld_reg): bool :=\n  match o , o' with\n  | op_BPF_LDXW,   op_BPF_LDXW\n  | op_BPF_LDXH,   op_BPF_LDXH\n  | op_BPF_LDXB,   op_BPF_LDXB\n  | op_BPF_LDXDW,  op_BPF_LDXDW\n  | op_BPF_LDX_REG_ILLEGAL_INS, op_BPF_LDX_REG_ILLEGAL_INS => true\n  | _, _ => false\n  end.\n\nDefinition opcode_mem_st_imm_eqb (o o' : opcode_mem_st_imm): bool :=\n  match o , o' with\n  | op_BPF_STW,    op_BPF_STW\n  | op_BPF_STH,    op_BPF_STH\n  | op_BPF_STB,    op_BPF_STB\n  | op_BPF_STDW,   op_BPF_STDW\n  | op_BPF_ST_ILLEGAL_INS, op_BPF_ST_ILLEGAL_INS => true\n  | _, _ => false\n  end.\n\nDefinition opcode_mem_st_reg_eqb (o o' : opcode_mem_st_reg): bool :=\n  match o , o' with\n  | op_BPF_STXW,   op_BPF_STXW\n  | op_BPF_STXH,   op_BPF_STXH\n  | op_BPF_STXB,   op_BPF_STXB\n  | op_BPF_STXDW,  op_BPF_STXDW\n  | op_BPF_STX_ILLEGAL_INS, op_BPF_STX_ILLEGAL_INS => true\n  | _, _ => false\n  end.\n\nDefinition opcode_eqb (o o' : opcode) : bool :=\n  match o , o' with\n  | op_BPF_ALU64,      op_BPF_ALU64\n  | op_BPF_ALU32,      op_BPF_ALU32\n  | op_BPF_Branch,     op_BPF_Branch\n  | op_BPF_Mem_ld_imm, op_BPF_Mem_ld_imm\n  | op_BPF_Mem_ld_reg, op_BPF_Mem_ld_reg\n  | op_BPF_Mem_st_imm, op_BPF_Mem_st_imm\n  | op_BPF_Mem_st_reg, op_BPF_Mem_st_reg\n\n  | op_BPF_ILLEGAL_INS, op_BPF_ILLEGAL_INS => true\n  | _, _ => false\n  end.", "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/monadicmodel/Opcode.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.29613235052132963}}
{"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 omega.\nrewrite <- Zmod_div_mod; try omega.\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_omega.\nrep_omega.\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 omega.\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\nHint 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 [ _x OF int_or_ptr_type ]\n   PROP(valid_int_or_ptr x) LOCAL(temp _x x) SEP()\n POST [ tint ]\n   PROP() \n   LOCAL(temp ret_temp \n          (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 [ _x OF int_or_ptr_type ]\n   PROP(is_int I32 Signed x) LOCAL(temp _x x) SEP()\n POST [ tint ]\n   PROP() LOCAL (temp ret_temp x) SEP().\n\nDefinition int_or_ptr_to_ptr_spec :=\n DECLARE _int_or_ptr_to_ptr\n WITH x : val\n PRE [ _x OF int_or_ptr_type ]\n   PROP(isptr x) LOCAL(temp _x x) SEP()\n POST [ tptr tvoid ]\n   PROP() LOCAL (temp ret_temp x) SEP().\n\nDefinition int_to_int_or_ptr_spec :=\n DECLARE _int_to_int_or_ptr\n WITH x : val\n PRE [ _x OF tint ]\n   PROP(valid_int_or_ptr x)\n   LOCAL(temp _x x) SEP()\n POST [ int_or_ptr_type ]\n   PROP() LOCAL (temp ret_temp x) SEP().\n\nDefinition ptr_to_int_or_ptr_spec :=\n DECLARE _ptr_to_int_or_ptr\n WITH x : val\n PRE [ _x OF tptr tvoid ]\n   PROP(valid_int_or_ptr x) LOCAL(temp _x x) SEP()\n POST [ int_or_ptr_type ]\n   PROP() LOCAL (temp ret_temp x) SEP().\n\nDefinition makenode_spec :=\n DECLARE _makenode \n  WITH p: val, q: val\n  PRE [ _left OF int_or_ptr_type, _right OF int_or_ptr_type ]\n    PROP() LOCAL(temp _left p; temp _right q) SEP()\n  POST [ tptr (Tstruct _tree noattr) ]\n    EX r:val, \n    PROP() LOCAL(temp ret_temp 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  [ _t OF int_or_ptr_type ]\n    PROP() LOCAL(temp _t p) SEP (treerep t p)\n  POST [ int_or_ptr_type ]\n    EX v:val,\n    PROP() LOCAL(temp ret_temp 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   apply 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   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": "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_int_or_ptr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.29613235052132963}}
{"text": "Require Import aes.aesutils.\nRequire Import aes.AES256.\n\nRequire Import Coqlib.\nRequire Import msl.Coqlib2.\nRequire Import floyd.coqlib3.\nRequire Import Integers.\nRequire Import List. Import ListNotations.\nRequire Import zlist.sublist.\nRequire Import sha.SHA256.\nRequire Import sha.general_lemmas.\n\nLocal Open Scope logic.\n\nLemma extra_expansion_sublist : forall k : list word,\n  Zlength k = Nk -> sublist 0 (Nb*(Nr+1)) (blocks_to_ints (extra_key_expansion k)) = blocks_to_ints (KeyExpansion k).\nProof.\n  intros.\n  simpl.\n  unfold extra_key_expansion.\n  unfold KeyExpansion.\n  assert (length k = 8%nat).\n    rewrite Zlength_correct in H.\n    apply Nat2Z.inj.\n    auto.\n  do 9 (destruct k as [ | ?w k]; try (inv H0; rename H2 into H0)).\n  reflexivity.\nQed.\n\n(* FIPS 197 section 5.3.5 mentions that ShiftRows and SubBytes (or InvShiftRows and\n * InvSubBytes) can commute. Normally, we would stipulate that the blocks are in bounds,\n * but it actually turns out to be unnecessary for the proof. *)\n\nLemma subbytes_shiftrows_comm : forall b : block,\n  ShiftRows (SubBytes b) = SubBytes (ShiftRows b).\nProof.\n  intros.\n  destruct b as [[[[[[? ?] ?] ?] [[[? ?] ?] ?]] [[[? ?] ?] ?]] [[[? ?] ?] ?]].\n  reflexivity.\nQed.\n\nLemma invsubbytes_invshiftrows_comm : forall b : block,\n    InvShiftRows (InvSubBytes b) = InvSubBytes (InvShiftRows b).\nProof.\n  intros.\n  destruct b as [[[[[[? ?] ?] ?] [[[? ?] ?] ?]] [[[? ?] ?] ?]] [[[? ?] ?] ?]].\n  reflexivity.\nQed.\n\n(* FIPS 197 section 5.3.5 mentions that MixColumns and InvMixColumns are linear over\n * XOR (i.e., AddRoundKey) *)\n\n(*\nLemma mixcolumns_xor_linear: forall s : state, rk : block,\n    block_in_bounds s -> block_in_bounds rk ->\n    MixColumns (AddRoundKey s rk) = AddRoundKey (MixColumns s) (MixColumns rk)\n*)\n\n(*\nLemma invmixcolumns_xor_linear : forall s : state, rk : block,\n    block_in_bounds s -> block_in_bounds rk ->\n    InvMixColumns (AddRoundKey s rk) = AddRoundKey (InvMixColumns s) (InvMixColumns rk).\n*)\n\n(* To show correctness of the implementation of the AES ciper round,\n * we will need to take into account that the XOR of C ints also XORs the\n * individual bytes *)\n(*\nLemma xor_bytes : forall x y : int,\n  let x_bytes := map Int.repr (intlist_to_Zlist [x]) in\n  let y_bytes := map Int.repr (intlist_to_Zlist [y]) in\n  map Int.repr (intlist_to_Zlist [Int.xor x y]) = map2 Int.xor x_bytes y_bytes.\n*)\n\n(* This would show that the mbed TLS implementation of the encryption round is equivalent to\n * the one in the functional spec *)\n(*\nLemma round_equiv : forall (s : state) (rk : block),\n  block_in_bounds s -> block_in_bounds rk ->\n  block_to_ints (transpose (round s rk)) = mbed_tls_fround (block_to_ints (transpose s)) (block_to_ints (transpose rk)).\n*)\n\n(* This would show that the reverse encryption round is equivalent to the one in the functional spec *)\n(*\nLemma inv_round_equiv : forall (s : state) (rk : block),\n  block_in_bounds s -> block_in_bounds rk ->\n  block_to_ints (transpose (inv_round s rk)) = mbed_tls_rround (blocks_to_ints (transpose s)) (block_to_ints (transpose rk)).\n*)\n\nLemma sbox_invsbox_inverse : forall a : nat, (a < 256)%nat ->\n    let b := Z.to_nat (Int.unsigned (nth a sbox Int.zero)) in\n    nth b inv_sbox Int.zero = Int.repr (Z.of_nat a).\nProof.\n  intros.\n  do 256 (destruct a as [| a]; [reflexivity | ]).\n  omega.\nQed.\n\nLemma invsbox_sbox_inverse : forall a : nat, (a < 256)%nat ->\n    let b := Z.to_nat (Int.unsigned (nth a inv_sbox Int.zero)) in\n    nth b sbox Int.zero = Int.repr (Z.of_nat a).\nProof.\n  intros.\n  do 256 (destruct a as [| a]; [reflexivity | ]).\n  omega.\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/unused/aes_round_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.29613235052132963}}
{"text": "Require Import VST.msl.msl_standard.\nRequire Import VST.msl.cjoins.\nRequire Import VST.msl.rmaps.\nRequire Import VST.msl.Coqlib2.\nRequire Import VST.msl.sepalg_list.\n\nModule Rmaps_Lemmas (R: RMAPS).\nModule R := R.\nImport R.\n\nHint Resolve (@subp_sepcon _ Join_rmap Perm_rmap Sep_rmap): contractive.\n\n Lemma approx_p  : forall (p:pred rmap) n w, approx n p w -> p w.\n Proof. unfold approx; simpl; intuition. Qed.\n\n Lemma approx_lt : forall (p:pred rmap) n w, lt (level w) n -> p w -> approx n p w.\n Proof. unfold approx; simpl; intuition. Qed.\n\n Lemma approx_ge : forall p n w, ge (level w) n -> approx n p w -> False.\n Proof. unfold approx; intros. destruct H0; auto. omega. Qed.\n\n  Definition identity_rmap' : R.rmap' := exist valid (fun _: AV.address => R.NO) AV.valid_empty.\n  Definition identity_rmap (n:nat) : rmap := R.squash (n, identity_rmap').\n\n  Lemma identity_level : forall n, level (identity_rmap n) = n.\n  Proof.\n    intro n; unfold identity_rmap.\n    rewrite rmap_level_eq. rewrite unsquash_squash. auto.\n  Qed.\n\n  Lemma snd_identity_map : forall n, proj1_sig (snd (R.unsquash (identity_rmap n))) = fun _ => R.NO .\n    unfold identity_rmap; intros.\n    rewrite R.unsquash_squash.\n    simpl.\n    apply extensionality; intro l.\n    unfold compose; simpl; auto.\n  Qed.\n\n  Lemma comparable_level : forall phi1 phi2 : rmap ,\n         comparable phi1 phi2 -> level phi1 = level phi2.\n  Proof.\n   intros.\n   apply comparable_fashionR.\n   trivial.\n  Qed.\n\n  Lemma ageN_level : forall n (phi1 phi2 : rmap),\n    ageN n phi1 = Some phi2 -> level phi1 = (n + (level phi2))%nat.\n  Proof.\n    unfold ageN; induction n; simpl; intros.\n    injection H; intros; subst; auto.\n    revert H.\n    repeat rewrite rmap_level_eq in *.\n    intros. invSome.\n    specialize (IHn _ _ H2).\n    apply  age_level in H.  rewrite rmap_level_eq in *. omega.\n  Qed.\n\nLemma NO_identity: identity NO.\nProof.\n  unfold identity; intros.\n  inv H; auto.\nQed.\n\nLemma PURE_identity: forall k pds, identity (PURE k pds).\nProof.\n  unfold identity; intros.\n  inv H; auto.\nQed.\n\nLemma identity_NO:\n  forall r, identity  r -> r = NO \\/ exists k, exists pds, r = PURE k pds.\nProof.\n  destruct r; auto; intros.\n  left. symmetry; apply H.\n  apply res_join_NO2.\n  right. exists k. exists p. trivial.\nQed.\n\nLemma age1_resource_at_identity:\n  forall phi phi' loc, age1 phi = Some phi' ->\n               identity (phi@loc) ->\n               identity (phi'@loc).\nProof.\n  intros.\n  generalize (identity_NO _ H0); clear H0; intro.\n  unfold resource_at in *.\n  rewrite rmap_age1_eq in *.\n  revert H H0; case_eq (unsquash phi); simpl; intros.\n  destruct n; inv H0.\n  rewrite unsquash_squash.\n  simpl.\n  destruct r. simpl in *.\n  unfold compose; simpl. destruct H1 as [H1 | [k [pds H1]]]; rewrite H1; simpl; auto.\n  apply NO_identity.\n  apply PURE_identity.\nQed.\n\nLemma unage1_resource_at_identity:\n  forall phi phi' loc, age1 phi = Some phi' ->\n               identity (phi'@loc) ->\n               identity (phi@loc).\nProof.\n  intros.\n  generalize (identity_NO _ H0); clear H0; intro.\n  unfold resource_at in *. simpl in H.\n  rewrite rmap_age1_eq in H.\n  revert H H0; case_eq (unsquash phi); simpl; intros.\n  destruct n; inv H0.\n  rewrite unsquash_squash in H1. destruct r. simpl in *.\n  unfold compose in H1; simpl in H1.\n  unfold resource_fmap in H1.\n  destruct (x loc).\n  apply NO_identity.\n  destruct H1 as [H1 | [k' [pds' H1]]]; inv H1.\n  apply PURE_identity.\nQed.\n\nLemma necR_resource_at_identity:\n  forall phi phi' loc, necR phi phi' ->\n         identity (phi@loc) ->\n         identity (phi'@loc).\nProof.\n  induction 1; auto.\n  intro; eapply age1_resource_at_identity; eauto.\nQed.\n\nLemma make_rmap': forall f, AV.valid (fun l => res_option (f l)) ->\n          exists phi: rmap', proj1_sig phi = f.\nProof.\n  intros.\n  unfold rmap'.\n  exists (exist valid f H).\n  auto.\nQed.\n\n\nLemma make_rmap (f: AV.address -> resource) (V: AV.valid (res_option oo f))\n    (n: nat) (H: resource_fmap (approx n) oo f = f) :\n  {phi: rmap | level phi = n /\\ resource_at phi = f}.\nProof.\nintros.\napply (exist _ (squash (n, @exist (AV.address -> resource) R.valid f V))).\nsimpl level; rewrite rmap_level_eq in *; unfold resource_at. rewrite unsquash_squash.\nsimpl; auto.\nQed.\n\nLemma make_rmap'':\n    forall n (f: AV.address -> resource) ,\n      AV.valid (fun l => res_option (f l)) ->\n      exists phi:rmap, level phi = n /\\ resource_at phi = resource_fmap (approx n) oo f.\n  Proof.\n    intros.\n    exists (squash (n, exist valid f H)).\n    rewrite rmap_level_eq.\n      unfold resource_at; rewrite unsquash_squash; simpl; split; auto.\nQed.\n\n(*\nLemma make_simple_rmap:\n    forall n (f: AV.address -> resource) ,\n      AV.valid (fun l => res_option (f l)) ->\n      (forall l, match f l with YES _ _ (SomeP _ _) => False | _ => True end) ->\n      exists phi:rmap, level phi = n /\\ resource_at phi = f.\nProof.\n  intros; destruct (make_rmap'' n f H) as [phi [? ?]]; exists phi; split; auto.\n  rewrite H2.\n  extensionality l; unfold compose; simpl;  generalize (H0 l); destruct (f l); auto.\n  destruct p0; intros; try contradiction.\nQed.\n*)\n\nLemma approx_oo_approx':\n  forall n n', (n' >= n)%nat -> approx n oo approx n' = approx n.\nProof.\nunfold compose; intros.\nextensionality P.\n apply pred_ext; intros w ?; unfold approx; simpl in *; intuition.\nQed.\n\nLemma approx_oo_approx: forall n, approx n oo approx n = approx n.\nProof.\nintros; apply approx_oo_approx'; omega.\nQed.\n\nLemma approx_approx' n n' x :\n  (n' >= n)%nat -> approx n (approx n' x) = approx n x.\nProof.\n  intro H.\n  change ((approx n oo approx n') x = approx n x).\n  apply equal_f, approx_oo_approx', H.\nQed.\n\nLemma resources_same_level:\n   forall f phi,\n     (forall l : AV.address, join_sub (f l) (phi @ l)) ->\n        resource_fmap (approx (level phi)) oo f = f.\nProof.\n  intros.\n  rewrite rmap_level_eq.\n  unfold resource_fmap, resource_at in *.\n  unfold compose; extensionality l. spec H l.\n  destruct H as [g ?].\n  revert H; case_eq (unsquash phi); intros n ? ?.\n  generalize H; rewrite <- (squash_unsquash phi).\n  rewrite H. rewrite unsquash_squash.\n  simpl; intros.\n  injection H0. clear H0. intro.\n  clear phi H.\n  rewrite <- H0 in H1.\n  clear H0.\n  unfold rmap_fmap in *.\n  destruct r.\n  simpl in *.\n  revert H1.\n  unfold resource_fmap, compose.\n  destruct (f l); destruct g; destruct (x l); simpl; intro; auto; inv H1.\n  change (preds_fmap (approx n) (preds_fmap (approx n) p2))\n  with ((preds_fmap (approx n) oo preds_fmap (approx n)) p2).\n  rewrite preds_fmap_comp.\n  rewrite approx_oo_approx; auto.\n  change (preds_fmap (approx n) (preds_fmap (approx n) p4))\n  with ((preds_fmap (approx n) oo preds_fmap (approx n)) p4).\n  rewrite preds_fmap_comp.\n  rewrite approx_oo_approx; auto.\n  change (preds_fmap (approx n) (preds_fmap (approx n) p1))\n  with ((preds_fmap (approx n) oo preds_fmap (approx n)) p1).\n  rewrite preds_fmap_comp.\n  rewrite approx_oo_approx; auto.\nQed.\n\nLemma deallocate:\n  forall (phi: rmap) (f g : AV.address -> resource),\n  AV.valid (res_option oo f) -> AV.valid (res_option oo g) ->\n  (forall l, join  (f l) (g l) (phi@l)) ->\n   exists phi1, exists phi2,\n     join phi1 phi2 phi /\\ resource_at phi1 = f.\nProof.\n  intros until g. intros Hf Hg H0.\n  generalize (resources_same_level f phi); intro.\n  spec H. intro; econstructor; apply H0.\n  generalize (resources_same_level g phi); intro.\n  spec H1.\n  intro. econstructor; eapply join_comm; eauto.\n  generalize (make_rmap'' (level phi) f Hf); intros [phif [? Gf]].\n  generalize (make_rmap'' (level phi) g Hg); intros [phig [? Gg]].\n  exists phif; exists phig.\n  split.\n  rewrite rmap_level_eq in *.\n  unfold resource_at in *.\n  revert H0 H Gf H1 Gg H2 H3;\n  case_eq (unsquash phif); intros nf phif' ?.\n  case_eq (unsquash phig); intros ng phig' ?.\n  case_eq (unsquash phi); intros n phi' ?.\n  simpl.\n  intros; subst nf ng.\n  rewrite join_unsquash.\n  rewrite H; rewrite H0; rewrite H1.\n  rewrite <- H1.\n  revert H1; case_eq (unsquash phi); intros n' phi'' ?.\n  intros.\n  inversion H5.\n  simpl.\n  split.\n  simpl; constructor; auto.\n  subst n' phi''.\n  intro l; spec H2 l.\n  simpl.\n  rewrite Gf; rewrite Gg; clear Gf Gg.\n  rewrite H3; rewrite H4.\n  auto.\n  rewrite Gf.\n  auto.\nQed.\n\nLemma allocate:\n     forall (phi : rmap) (f : AV.address -> resource),\n     AV.valid (res_option oo f) ->\n        resource_fmap (approx (level phi)) oo f = f ->\n       (forall l, {r' | join (phi@l) (f l) r'}) ->\n       exists phi1 : rmap,\n         exists phi2 : rmap,\n           join phi phi1 phi2 /\\ resource_at phi1 = f.\nProof.\n intros. rename X into H1.\n generalize (make_rmap'' (level phi) f H); intros [phif [? Gf]].\n pose (g loc := proj1_sig (H1 loc)).\n assert (H3: forall l, join (phi @ l) (f l) (g l))\n   by (unfold g; intro; destruct (H1 l); simpl in *; auto).\n clearbody g.\n generalize (make_rmap'' (level phi) g); intro.\n spec H4.\n   assert (AV.valid (fun l => res_option (phi @ l))).\n     clear.\n     unfold resource_at.\n     case_eq (unsquash phi); intros.\n     simpl.\n     destruct r. simpl.\n     apply v.\n   eapply AV.valid_join. 2: apply H5. 2: apply H.\n   clear - H3.\n   intro l; spec H3 l.\n   destruct (phi @ l); simpl in *.\n   apply join_unit1_e in H3. unfold compose. rewrite H3. constructor. apply NO_identity.\n   unfold compose at 1. unfold res_option.\n   destruct (f l). apply join_unit2_e in H3; [ | apply NO_identity]. rewrite <- H3. constructor.\n   destruct (g l). inv H3. inv H3.\n   constructor; split; auto.\n   inv H3. inv H3. inv H3. unfold compose, res_option. rewrite <- H. constructor.\n destruct H4 as [phig [? ?]].\n exists phif; exists phig.\n split.\n 2: congruence.\n rewrite join_unsquash.\n unfold resource_at in *.\n rewrite rmap_level_eq in *.\n revert H0 H1 H2 H3 H4 H5 Gf.\n case_eq (unsquash phif); intros nf phif' ?.\n case_eq (unsquash phig); intros ng phig' ?.\n case_eq (unsquash phi); intros n phi' ?.\n simpl.\n intros; subst nf ng.\n split. split; trivial.\n simpl.\n intro l.\n spec H6 l.\n assert (proj1_sig phig' l = g l).\n   generalize (f_equal squash H2); intro.\n   rewrite squash_unsquash in H5.\n   subst phi.\n   rewrite unsquash_squash in H2.\n   injection H2; clear H2; intro.\n   rewrite <- H2 in H6.\n   rewrite <- H3 in H6.\n   rewrite H8.\n   clear - H6.\n   revert H6.\n   unfold rmap_fmap, compose, resource_fmap.\n   destruct phi'; simpl.\n   destruct (x l); destruct (f l); destruct (g l); simpl; intros; auto; try inv H6;\n              try change (preds_fmap (approx n) (preds_fmap (approx n) p0)) with\n                ((preds_fmap (approx n) oo preds_fmap (approx n)) p0);\n              try change (preds_fmap (approx n) (preds_fmap (approx n) p)) with\n                ((preds_fmap (approx n) oo preds_fmap (approx n)) p);\n                rewrite preds_fmap_comp; rewrite approx_oo_approx; auto.\n rewrite H5.\n rewrite Gf.\n rewrite H3.\n auto.\nQed.\n\n  Lemma unsquash_inj : forall x y,\n      unsquash x = unsquash y -> x = y.\n  Proof.\n    intros.\n    rewrite <- (squash_unsquash x).\n    rewrite <- (squash_unsquash y).\n    rewrite H; auto.\n  Qed.\n\n  Lemma rmap_ext: forall phi1 phi2,\n    level phi1 = level phi2 ->\n    (forall l, phi1@l = phi2@l) ->\n    phi1=phi2.\n  Proof.\n    intros.\n    apply unsquash_inj.\n    rewrite rmap_level_eq in *.\n    unfold resource_at in *.\n    rewrite <- (squash_unsquash phi1).\n    rewrite <- (squash_unsquash phi2).\n    destruct (unsquash phi1).\n    destruct (unsquash phi2).\n    simpl in H.\n    rewrite H.\n    rewrite unsquash_squash.\n    rewrite unsquash_squash.\n    simpl in H0.\n    replace (rmap_fmap (approx n0) r) with (rmap_fmap (approx n0) r0); auto.\n    destruct r; destruct r0.\n    simpl in *.\n    generalize (valid_res_map (approx n0) x0 v0).\n    generalize (valid_res_map (approx n0) x v).\n    replace (resource_fmap (approx n0) oo x0)\n      with (resource_fmap (approx n0) oo x).\n    intros v1 v2; replace v2 with v1 by apply proof_irr; auto.\n    extensionality l.\n    unfold compose.\n    spec H0 l.\n    subst n0.\n    rewrite H0; auto.\n  Qed.\n\n  Lemma resource_at_join:\n    forall phi1 phi2 phi3 loc,\n      join phi1 phi2 phi3 ->\n      join (phi1@loc) (phi2@loc) (phi3@loc).\n  Proof.\n    intros.\n    revert H; rewrite join_unsquash; unfold resource_at.\n    intros [? ?].\n    apply H0.\n  Qed.\n\n  Lemma resource_at_join2:\n    forall phi1 phi2 phi3,\n      level phi1 = level phi3 -> level phi2 = level phi3 ->\n      (forall loc, join (phi1@loc) (phi2@loc) (phi3@loc)) ->\n      join phi1 phi2 phi3.\n  Proof.\n    intros ? ? ?.\n    rewrite join_unsquash.\n    rewrite rmap_level_eq in *.\n    unfold resource_at.\n    case_eq (unsquash phi1); case_eq (unsquash phi2); case_eq (unsquash phi3); simpl; intros.\n    subst.\n    split; auto.\n  Qed.\n\nLemma all_resource_at_identity:\n  forall w, (forall l, identity (w@l)) ->\n         identity w.\nProof.\n  intros.\n  rewrite identity_unit_equiv.\n  apply join_unsquash.\n  split. split; auto.\n  revert H. unfold resource_at.\n  case_eq (unsquash w); simpl; intros.\n  intro a. spec H0 a.\n  rewrite identity_unit_equiv in H0.\n  trivial.\nQed.\n\n  Lemma ageN_squash : forall d n rm, le d n ->\n    ageN d (squash (n, rm)) = Some (squash ((n - d)%nat, rm)).\n  Proof.\n    induction d; simpl; intros.\n    unfold ageN; simpl.\n    replace (n-0)%nat with n by omega; auto.\n    unfold ageN; simpl.\n    rewrite rmap_age1_eq in *.\n    rewrite unsquash_squash.\n    destruct n.\n    inv H.\n    replace (S n - S d)%nat with (n - d)%nat by omega.\n    unfold ageN in IHd. rewrite rmap_age1_eq in IHd.\n    rewrite IHd.\n    2: omega.\n    replace (squash ((n - d)%nat, rmap_fmap (approx (S n)) rm))\n       with (squash ((n - d)%nat, rm)); auto.\n    apply unsquash_inj.\n    rewrite unsquash_squash.\n    rewrite unsquash_squash.\n    replace (rmap_fmap (approx (n - d)) rm)\n       with (rmap_fmap (approx (n - d) oo approx (S n)) rm); auto.\n    rewrite <- rmap_fmap_comp.\n    unfold compose; auto.\n    replace (approx (n-d) oo approx (S n)) with (approx (n-d)).\n    auto.\n    clear.\n    assert (n-d <= (S n))%nat by omega.\n    revert H; generalize (n-d)%nat (S n).\n    clear.\n    intros.\n    extensionality p.\n    apply pred_ext'.  extensionality w.\n    unfold compose, approx.\n    apply prop_ext; simpl; intuition.\n  Qed.\n\n  Lemma unageN: forall n (phi': rmap),   exists phi, ageN n phi = Some phi'.\n  Proof.\n    intros n phi'.\n    rewrite <- (squash_unsquash phi').\n    destruct (unsquash phi'); clear phi'.\n    exists (squash ((n+n0)%nat,r)).\n    rewrite ageN_squash.\n    replace (n + n0 - n)%nat with n0 by omega; auto.\n    omega.\n  Qed.\n\n\nLemma YES_join_full:\n   forall n P r2 r3,\n       join (R.YES pfullshare n P) r2 r3 ->\n       r2 = NO.\nProof.\n  intros.\n  simpl in H.\n  inv H. trivial.\n  pfullshare_join.\nQed.\n\nLemma YES_not_identity:\n  forall sh k Q, ~ identity (YES sh k Q).\nProof.\nintros. intro.\nrewrite identity_unit_equiv in H.\nsimpl in * |-.\nunfold unit_for in H.\ninv H.\napply no_units in H1; auto.\nQed.\n\nLemma YES_overlap:\nforall (phi0 phi1: rmap) loc (sh : pshare) k k' p p',\n  joins phi0 phi1 -> phi1@loc = R.YES pfullshare k p ->\n               phi0@loc = R.YES sh k' p' -> False.\nProof.\n  intros.\n  destruct H as [phi3 ?].\n  generalize (resource_at_join _ _ _ loc H); intro.\n  rewrite H1 in H2.\n  rewrite H0 in H2.\n  contradiction (YES_not_identity sh k' p').\n  apply join_comm in H2. apply YES_join_full in H2. discriminate.\nQed.\n\nLemma necR_NOx:\n   forall phi phi' l, necR phi phi' -> phi@l = NO -> phi'@l = NO.\nProof.\ninduction 1; eauto.\nunfold age in H; simpl in H.\nrevert H; rewrite rmap_age1_eq; unfold resource_at.\ndestruct (unsquash x).\nintros; destruct n; inv H.\nrewrite unsquash_squash; simpl in *; auto.\ndestruct r; simpl in *.\nunfold compose.\nrewrite H0.\nauto.\nQed.\n\nLtac do_map_arg :=\nmatch goal with |- ?a = ?b =>\n  match a with context [map ?x _] =>\n    match b with context [map ?y _] => replace y with x; auto end end end.\n\nLemma preds_fmap_fmap:\n  forall f g pp, preds_fmap f (preds_fmap g pp) = preds_fmap (f oo g) pp.\nProof.\ndestruct pp; simpl; auto.\nQed.\n\nLemma resource_fmap_fmap:  forall f g r, resource_fmap f (resource_fmap g r) =\n                                                                      resource_fmap (f oo g) r.\nProof.\ndestruct r; simpl; auto.\nrewrite preds_fmap_fmap; auto.\nrewrite preds_fmap_fmap; auto.\nQed.\n\nLemma resource_at_approx:\n  forall phi l,\n      phi @ l = resource_fmap (approx (level phi)) (phi @ l).\nProof.\nintros. rewrite rmap_level_eq. unfold resource_at.\ncase_eq (unsquash phi); intros.\nsimpl.\ndestruct r; simpl in *.\nassert (R.valid (resource_fmap (approx n) oo x)).\napply valid_res_map; auto.\nset (phi' := (squash (n, exist (fun m : AV.address -> resource => R.valid m) _ H0))).\ngeneralize (unsquash_inj phi phi'); intro.\nspec H1.\nreplace (unsquash phi) with (unsquash (squash (unsquash phi))).\n2: rewrite squash_unsquash; auto.\nrewrite H.\nunfold phi'.\nrepeat rewrite unsquash_squash.\nsimpl.\nreplace (exist (fun m : AV.address -> resource => valid m)\n  (resource_fmap (approx n) oo x) (valid_res_map (approx n) x v)) with\n(exist (fun m : AV.address -> resource => valid m)\n  (resource_fmap (approx n) oo resource_fmap (approx n) oo x)\n  (valid_res_map (approx n) (resource_fmap (approx n) oo x) H0)); auto.\nassert (Hex: forall A (F: A -> Prop) (x x': A) y y', x=x' -> exist F x y = exist F x' y') by auto with extensionality.\napply Hex.\nunfold compose.\nextensionality y.\nrewrite resource_fmap_fmap.\nrewrite approx_oo_approx; auto.\nunfold phi' in *; clear phi'.\nsubst.\nrewrite unsquash_squash in H.\ninjection H; clear H; intro.\npattern x at 1; rewrite <- H.\nunfold compose.\nrewrite resource_fmap_fmap.\nrewrite approx_oo_approx; auto.\nQed.\n\nLemma necR_resource_at:\n  forall phi phi' loc r,\n        necR phi phi' ->\n         phi @ loc = resource_fmap (approx (level phi)) r ->\n         phi' @ loc = resource_fmap (approx (level phi')) r.\nProof.\nintros.\nrevert r loc H0; induction H; intros; auto.\nunfold age in H.\nsimpl in H.\nrevert H H0; rewrite rmap_level_eq, rmap_age1_eq; unfold resource_at.\n case_eq (unsquash x); intros.\ndestruct n; inv H0.\nsimpl in *.\nrewrite unsquash_squash; simpl.\ndestruct r0; simpl in *.\nunfold compose in *.\nrewrite H1; clear H1.\nrewrite resource_fmap_fmap.\nrewrite approx_oo_approx'; auto.\nQed.\n\nLemma necR_YES:\n  forall phi phi' loc sh k pp,\n        necR phi phi' ->\n         phi @ loc = YES sh k pp ->\n         phi' @ loc = YES sh k (preds_fmap (approx (level phi')) pp).\nProof.\nintros.\ngeneralize (resource_at_approx phi loc);\npattern (phi @ loc) at 2; rewrite H0; intro.\napply (necR_resource_at _ _ _ _ H H1).\nQed.\n\nLemma necR_PURE:\n  forall phi phi' loc k pp,\n        necR phi phi' ->\n         phi @ loc = PURE k pp ->\n         phi' @ loc = PURE k (preds_fmap (approx (level phi')) pp).\nProof.\n  intros.\n  generalize (resource_at_approx phi loc);\n  pattern (phi @ loc) at 2; rewrite H0; intro.\n  apply (necR_resource_at _ _ _ _ H H1).\nQed.\n\nLemma necR_NO:\n   forall phi phi' l, necR phi phi' ->\n   (phi@l = NO <-> phi'@l = NO).\nProof.\n  intros; split.\n  apply necR_NOx; auto.\n  intros.\n  case_eq (phi @ l); intros; auto.\n  destruct p0.\n  generalize (necR_YES _ _ _ _ _ _ H H1); rewrite H0; congruence.\n  generalize (necR_PURE _ _ _ _ _ H H1); rewrite H0; congruence.\nQed.\n\nLemma resource_at_empty: forall phi, identity phi -> forall l, (phi @ l = NO \\/ exists k, exists pds, phi @ l = PURE k pds).\nProof.\n  intros.\n  rewrite identity_unit_equiv in H.\n  unfold unit_for in H.\n  generalize (resource_at_join _ _ _ l H); intro.\n  remember (phi @ l) as r.\n  destruct r; inv H0; auto.\n  apply no_units in H2; contradiction.\n  right. exists k. exists p. trivial.\nQed.\nImplicit Arguments resource_at_empty.\n\n\nLemma rmap_valid: forall r, AV.valid (res_option oo resource_at r).\nProof.\nunfold compose, resource_at; intros.\ndestruct (unsquash r).\ndestruct r0.\nsimpl.\napply v.\nQed.\n\nLtac inj_pair_tac :=\n match goal with H: (@existT ?U ?P ?p ?x = @existT _ _ _ ?y) |- _ =>\n   generalize (@inj_pair2 U P p x y H); clear H; intro; try (subst x || subst y)\n end.\n\nLemma preds_fmap_NoneP:\n  forall f, preds_fmap f NoneP = NoneP.\nProof.\nintros.\nunfold NoneP.\nsimpl.\nf_equal. extensionality x; destruct  x.\ndestruct v.\nQed.\n\nLemma necR_YES':\n   forall phi phi' loc sh k,\n         necR phi phi' -> (phi@loc = YES sh k NoneP <-> phi'@loc = YES sh k NoneP).\nProof.\nintros.\ninduction H.\nrename x into phi; rename y into phi'.\nunfold age in H; simpl in H.\n(* revert H; case_eq (age1 phi); intros; try discriminate. *)\ninv H.\nsplit; intros.\nrewrite (necR_YES phi phi' loc sh k NoneP); auto; [ | constructor 1; auto].\nf_equal.\napply preds_fmap_NoneP.\nrewrite rmap_age1_eq in *.\nunfold resource_at in *.\nrevert H1; case_eq (unsquash phi); simpl; intros.\ndestruct n; inv H1.\nrewrite unsquash_squash in H. simpl in H. destruct r; simpl in *.\nunfold compose in H.\nrevert H; destruct (x loc); simpl; intros; auto.\ndestruct p0; inv H.\ninj_pair_tac. f_equal.\nunfold NoneP; f_equal.\nextensionality x'; destruct x'.\ndestruct v0.\ninv H.\nintuition.\nintuition.\nQed.\n\nLemma necR_YES'':\n   forall phi phi' loc sh k,\n         necR phi phi' ->\n    ((exists pp, phi@loc = YES sh k pp) <->\n    (exists pp, phi'@loc = YES sh k pp)).\nProof.\nintros.\ninduction H; try solve [intuition].\nrename x into phi; rename y into phi'.\nrevert H; unfold age; case_eq (age1 phi); intros; try discriminate.\ninv H0.\nsimpl in *.\nsplit; intros [pp ?].\neconstructor;\napply (necR_YES phi phi' loc sh k pp).\nconstructor 1; auto. auto.\nrename phi' into r.\nrewrite rmap_age1_eq in *.\nunfold resource_at in *.\nrevert H; case_eq (unsquash phi); simpl; intros.\ndestruct n; inv H1.\nrewrite unsquash_squash in H0. simpl in H0. destruct r0; simpl in *.\nunfold compose in H0.\nrevert H0; destruct (x loc); simpl; intros; auto.\ninv H0.\ninv H0.\neconstructor; eauto.\ninv H0.\nQed.\n\nLemma resource_at_join_sub:\n  forall phi1 phi2 l,\n       join_sub phi1 phi2 -> join_sub (phi1@l) (phi2@l).\nProof.\nintros.\ndestruct H as [phi ?].\ngeneralize (resource_at_join _ _ _ l H); intro.\neconstructor; eauto.\nQed.\n\nLemma age1_res_option: forall phi phi' loc,\n     age1 phi = Some phi' -> res_option (phi @ loc) = res_option (phi' @ loc).\n  Proof.\n    unfold res_option, resource_at; simpl.\n   rewrite rmap_age1_eq; intros phi1 phi2 l.\n case_eq (unsquash phi1); intros. destruct n; inv H0.\n rewrite unsquash_squash.\n   destruct r;\n    simpl.\n   unfold compose. destruct (x l); simpl; auto.\nQed.\n\nLemma necR_res_option:\n  forall (phi phi' : rmap) (loc : AV.address),\n  necR phi phi' -> res_option (phi @ loc) = res_option (phi' @ loc).\nProof.\n  intros.\n  case_eq (phi @ loc); intros.\n  rewrite (necR_NO _ _ _ H) in H0. congruence.\n  destruct p0.\n  rewrite (necR_YES phi phi' loc _ _ _ H H0); auto.\n  rewrite (necR_PURE phi phi' loc _ _ H H0); auto.\nQed.\n\n\nLemma age1_resource_at:\n     forall phi phi',\n          age1 phi = Some phi' ->\n         forall loc r,\n          phi @ loc = resource_fmap (approx (level phi)) r ->\n          phi' @ loc = resource_fmap (approx (level phi')) r.\nProof.\n   unfold resource_at; rewrite rmap_age1_eq, rmap_level_eq.\nintros until phi'; case_eq (unsquash phi); intros.\nsimpl in *.\ndestruct n; inv H0.\nrewrite unsquash_squash.\ndestruct r; simpl in *.\nunfold compose; rewrite H1.\nrewrite resource_fmap_fmap.\nrewrite approx_oo_approx'; auto.\nQed.\n\n\nLemma age1_YES: forall phi phi' l sh k ,\n  age1 phi = Some phi' -> (phi @ l = YES sh k NoneP <-> phi' @ l = YES sh k NoneP).\nProof.\nintros.\napply necR_YES'.\nconstructor 1; auto.\nQed.\n\nLemma empty_NO: forall r, identity r -> r = NO \\/ exists k, exists pds, r = PURE k pds.\nProof.\nintros.\ndestruct r; auto.\nunfold identity in H.\nspec H NO (YES p k p0).\nspec H.\napply res_join_NO2.\nauto.\nright. exists k. exists p. trivial.\nQed.\n\nLemma YES_join_full':\n  forall loc k P m1 m2 m3, join m1 m2 m3 -> m1@loc = YES pfullshare k P ->\n                   m3 @ loc = YES pfullshare k P.\nProof.\n  intros.\n  generalize (resource_at_join _ _ _ loc H); rewrite H0; intro.\n  generalize (YES_join_full _ _ _ _ H1); intro. rewrite H2 in H1.\n  inv H1.\n  trivial.\nQed.\n\n\nLemma level_age_fash:\n  forall m m': rmap, level m = S (level m') -> exists m1, age m m1. (* /\\ comparable m1 m'. *)\nProof.\n  intros.\n  case_eq (age1 m); intros.\n  exists r. auto.\n  elimtype False.\n  eapply age1None_levelS_absurd in H0; eauto.\nQed.\n\nLemma level_later_fash:\n forall m m': rmap, (level m > level m')%nat  -> exists m1, laterR m m1 /\\ level m1 = level m'.\nProof.\n  intros.\n  assert (exists k, level m = S k + level m')%nat.\n    exists (level m - S (level m'))%nat.\n    omega.\n  clear H; destruct H0 as [k ?].\n  revert m H; induction k; intros.\n  simpl in H.\n  destruct (level_age_fash _ _ H) as [m1 ?].\n  exists m1; split; auto.\n  constructor 1; auto.\n  apply age_level in H0. rewrite H in H0. inv H0. trivial.\n  case_eq (age1 m); intros.\n  spec IHk r.\n  rewrite <- ageN1 in H0.\n  generalize (ageN_level _ _ _ H0); intro.\n  spec IHk; try omega.\n  destruct IHk as [m1 [? ?]].\n  exists m1; split; auto.\n  econstructor 2; eauto.\n  rewrite ageN1 in H0.\n  constructor 1.\n  auto.\n  elimtype False.\n  eapply age1None_levelS_absurd in H0; eauto.\nQed.\n\nLemma resource_at_constructive_joins2:\n  forall phi1 phi2,\n       level phi1 = level phi2 ->\n       (forall loc, constructive_joins (phi1 @ loc) (phi2 @ loc)) ->\n         constructive_joins phi1 phi2.\nProof.\nintros ? ? ? H0.\nassert (AV.valid (res_option oo (fun loc => proj1_sig (H0 loc)))).\napply AV.valid_join with (res_option oo (resource_at phi1)) (res_option oo (resource_at phi2));\n try apply rmap_valid.\nintro l.\nunfold compose in *.\ndestruct (H0 l); simpl in *.\ndestruct (phi1 @ l). inv j; constructor.\ninv j; constructor. split; auto.\ninv j; constructor.\n(** End of CompCert_AV.valid proof **)\ndestruct (make_rmap _ H1 (level phi1)) as [phi' [? ?]].\nclear H1.\nunfold compose; extensionality loc.\nspec H0 loc.\ndestruct H0 as [? H1].\nsimpl.\nsymmetry.\nrevert H1; case_eq (phi1 @ loc); intros.\ninv H1. reflexivity.\nrewrite H2.\nrewrite H; apply resource_at_approx.\ninv H1. rewrite <- H0. apply resource_at_approx.\ngeneralize (resource_at_approx phi1 loc); intro.\nrewrite H0 in H1. simpl in H1.\nsimpl. f_equal. injection H1; auto.\ninv H1.\ngeneralize (resource_at_approx phi1 loc); intro.\nrewrite H0 in H1. simpl in H1.\nsimpl. f_equal. injection H1; auto.\n(*  End of make_rmap proof *)\nexists phi'.\napply resource_at_join2; auto.\ncongruence.\nintros.\nrewrite H3.\ndestruct (H0 loc).\nsimpl; auto.\nQed.\n\nLemma resource_at_joins2:\n  forall phi1 phi2,\n       level phi1 = level phi2 ->\n       (forall loc, constructive_joins (phi1 @ loc) (phi2 @ loc)) ->\n         joins phi1 phi2.\nProof.\n  intros.\n  apply cjoins_joins.\n  apply resource_at_constructive_joins2; trivial.\nQed.\n\nDefinition no_preds (r: resource) :=\n   match r with NO => True | YES _ _ pp => pp=NoneP | PURE _ pp => pp=NoneP end.\n\nLemma remake_rmap:\n  forall (f: AV.address -> resource),\n       AV.valid (res_option oo f) ->\n       forall n,\n       (forall l, (exists m, level m = n /\\ f l = m @ l) \\/ no_preds (f l)) ->\n       {phi: rmap | level phi = n /\\ resource_at phi = f}.\nProof.\n  intros.\n  apply make_rmap; auto.\n  extensionality l.\n  unfold compose.\n  destruct (H0 l); clear H0.\n  destruct H1 as [m [?  ?]].\n  rewrite H1.\n  subst.\n  symmetry; apply resource_at_approx.\n  destruct (f l); simpl in *; auto;\n  [destruct p0 | destruct p];\n  rewrite H1;\n  apply f_equal;\n  apply preds_fmap_NoneP.\nQed.\n\nLemma rmap_unage_age:\n  forall r, age (rmap_unage r) r.\nProof.\nintros; unfold age, rmap_unage; simpl.\ncase_eq (unsquash r); intros.\nrewrite rmap_age1_eq.\nrewrite unsquash_squash.\nf_equal.\napply unsquash_inj.\nrewrite H.\nrewrite unsquash_squash.\nf_equal.\ngeneralize (equal_f (rmap_fmap_comp (approx (S n)) (approx n)) r0); intro.\nunfold compose at 1 in H0.\nrewrite H0.\nrewrite approx_oo_approx'; auto.\nclear - H.\ngeneralize (unsquash_squash n r0); intros.\nrewrite <- H in H0.\nrewrite squash_unsquash in H0.\ncongruence.\nQed.\n\nLemma ageN_resource_at_eq:\n  forall phi1 phi2 loc n phi1' phi2',\n          level phi1 = level phi2 ->\n          phi1 @ loc = phi2 @ loc ->\n         ageN n phi1 = Some phi1' ->\n         ageN n phi2 = Some phi2' ->\n         phi1' @ loc = phi2' @ loc.\nProof.\nintros ? ? ? ? ? ? Hcomp ? ? ?; revert phi1 phi2 phi1' phi2' Hcomp H H0 H1; induction n; intros.\ninv H0; inv H1; auto.\nunfold ageN in H0, H1.\nsimpl in *.\nrevert H0 H1; case_eq (age1 phi1); case_eq (age1 phi2); intros; try discriminate.\nassert (level r = level r0) by (apply age_level in H0; apply age_level in H1; omega).\napply (IHn r0 r); auto.\nrewrite (age1_resource_at _ _ H0 loc _ (resource_at_approx _ _)).\nrewrite (age1_resource_at _ _ H1 loc _ (resource_at_approx _ _)).\nrewrite H. rewrite H4; auto.\nQed.\n\nLemma join_YES_pfullshare1:\n    forall pp k p x y, join (YES (mk_lifted Share.top pp) k p) x y -> (NO, YES pfullshare k p) = (x,y).\nProof.\nintros. inv H; try pfullshare_join; f_equal; auto.\n  f_equal. unfold pfullshare. f_equal. apply proof_irr.\nQed.\n\nLemma join_YES_pfullshare2:\n    forall pp k p x y, join x (YES  (mk_lifted Share.top pp) k p) y -> (NO, YES pfullshare k p) = (x,y).\nProof.\nintros. inv H; try pfullshare_join; f_equal; auto.\n  f_equal. unfold pfullshare. f_equal. apply proof_irr.\nQed.\n\nLtac inv H := (apply join_YES_pfullshare1 in H || apply join_YES_pfullshare2 in H || idtac);\n                  (inversion H; clear H; subst).\n\n  Definition empty_rmap' : rmap'.\n    set (f:= fun _: AV.address => NO).\n    assert (R.valid f).\n    red; unfold f; simpl.\n    apply AV.valid_empty.\n    exact (exist _ f H).\n  Defined.\n\n  Definition empty_rmap (n:nat) : rmap := R.squash (n, empty_rmap').\n\nLemma emp_empty_rmap: forall n, emp (empty_rmap n).\nProof.\nintros.\nintro; intros.\napply rmap_ext.\nComp.\nintros.\napply (resource_at_join _ _ _ l) in H.\nunfold empty_rmap, empty_rmap', resource_at in *.\ndestruct (unsquash a); destruct (unsquash b).\nsimpl in *.\ndestruct r; destruct r0; simpl in *.\nrewrite unsquash_squash in H.\nsimpl in *.\nunfold compose in H.\ninv H; auto.\nQed.\n\nLemma empty_rmap_level:\n  forall lev, level (empty_rmap lev) = lev.\nProof.\nintros.\nsimpl.\nrewrite rmap_level_eq.\nunfold  empty_rmap.\nrewrite unsquash_squash; auto.\nQed.\n\nLemma approx_FF: forall n, approx n FF = FF.\nProof.\nintros.\napply pred_ext; auto.\nunfold approx; intros ? ?.\nhnf in H. destruct H; auto.\nQed.\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 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\nInstance Join_trace : Join (AV.address -> option (pshare * AV.kind)) :=\n     (Join_fun AV.address (option (pshare * AV.kind))\n                   (Join_lower (Join_prod pshare Join_pshare AV.kind (Join_equiv AV.kind)))).\n\n\n Lemma res_option_join:\n    forall x y z, join x y z -> @join _ (@Join_lower (pshare * AV.kind)\n     (Join_prod pshare Join_pshare AV.kind (Join_equiv AV.kind))) (res_option x) (res_option y) (res_option  z).\n Proof.\n   intros.\n  inv H; constructor.  split; auto.\n Qed.\n\nDefinition fixup_trace (trace: AV.address -> option (pshare * AV.kind))\n                                    (f: AV.address -> resource) : AV.address -> resource :=\n   fun x => match trace x, f x with\n                   | None, PURE k pp => PURE k pp\n                   | Some(sh,k), PURE _ pp => YES sh k pp\n                   | Some (sh,k), YES _ _ pp => YES sh k pp\n                   | Some (sh, k), NO => YES sh k NoneP\n                   | None, _ => NO\n                   end.\n\nLemma fixup_trace_valid: forall tr f, AV.valid tr -> AV.valid (res_option oo (fixup_trace tr f)).\n Proof. intros.\n  replace (res_option oo fixup_trace tr f) with tr. auto.\n  extensionality l. unfold compose. unfold fixup_trace.\n  destruct (tr l); simpl; auto.\n  destruct p. destruct (f l); simpl; auto.\n  destruct (f l); reflexivity.\nQed.\n\nLemma fixup_trace_rmap:\n    forall (tr: sig AV.valid) (f: rmap),\n        {phi: rmap | level phi = level f /\\ resource_at phi = fixup_trace (proj1_sig tr) (resource_at f)}.\nProof.\n intros.\n apply make_rmap. apply fixup_trace_valid. destruct tr; simpl; auto.\n extensionality l.\n unfold compose, fixup_trace.\n destruct tr. simpl.\n destruct (x l); simpl; auto. destruct p.\n case_eq (f @ l); intros.\n unfold resource_fmap. rewrite preds_fmap_NoneP; auto.\n generalize (resource_at_approx f l); intro.\n rewrite H in H0. symmetry in H0.\n  simpl in H0. simpl.\n   f_equal. injection H0; auto.\n generalize (resource_at_approx f l); intro.\n rewrite H in H0. symmetry in H0.\n  simpl in H0. simpl.\n   f_equal. injection H0; auto.\n case_eq (f @ l); intros; auto.\n generalize (resource_at_approx f l); intro.\n rewrite H in H0. symmetry in H0.\n  simpl in H0. simpl.\n   f_equal. injection H0; auto.\nQed.\n\n\nLtac crtac :=\n repeat  (solve [constructor; auto] ||\n   match goal with\n | H: None = res_option ?A |- _ => destruct A; inv H\n | H: Some _ = res_option ?A |- _ => destruct A; inv H\n | H: join NO _ _ |- _ => inv H\n | H: join _ NO _ |- _ => inv H\n | H: join (YES _ _ _) _ _ |- _ => inv H\n | H: join _ (YES _ _ _) _ |- _ => inv H\n | H: join (PURE _ _) _ _ |- _ => inv H\n | H: join _ (PURE _ _) _ |- _ => inv H\n | H: @join _ _ (Some _) _ _ |- _ => inv H\n | H: @join _ _ _ (Some _) _ |- _ => inv H\n | H: @join _ _ None _ _ |- _ =>\n                apply join_unit1_e in H; [| apply None_identity]\n | H: @join _ _ _ None _ |- _ =>\n                apply join_unit2_e in H; [| apply None_identity]\n | H:  prod pshare AV.kind |- _ => destruct H\n | H: @join _ (Join_equiv _) ?a ?b ?c |- _ => destruct H; try subst a; try subst b; try subst c\n | H: @join _ (Join_prod _ _ _ _) (_,_) (_,_) (_,_) |- _ => destruct H; simpl fst in *; simpl snd in *\n end; auto).\n\nLemma Cross_resource: Cross_alg resource.\nProof.\nintro; intros.\ndestruct a as [|a|a].\nassert (b=z) by (inv H; auto). subst.\nexists (NO,NO,c,d); split; simpl; auto; try constructor; auto.\ninv H. inv H0; split; constructor. inv H0; split; constructor.\ndestruct b as [|b|b].\nassert (z=YES a k p) by (inv H; auto). clear H; subst.\nexists (c,d,NO,NO); split; simpl; auto.\ninv H0; split3; constructor.\nassert (Hz: k0=k /\\ p0=p) by (inv H; auto). destruct Hz; subst.\ndestruct c as [|c|c].\nassert (z=d) by (inv H0; auto). clear H0; subst.\nexists (NO,(YES a k p),NO,(YES b k p)); simpl; split; auto.\nconstructor.\ninv H; split3; constructor; auto.\ndestruct d as [|d|d].\nassert (z=YES c k0 p0) by (inv H0; auto). clear H0; subst.\nassert (Hz: k0=k /\\ p0=p) by (inv H; auto); destruct Hz; subst.\nexists (YES a k p, NO, YES b k p, NO); simpl; split; auto.\nconstructor. inv H; split3; constructor; auto.\ndestruct z as [|z|z].  elimtype False; inv H0.\nassert (Hx: k=k2 /\\ k0=k2 /\\ k1=k2 /\\ p=p2 /\\ p0=p2 /\\ p1=p2) by  (inv H0; inv H; auto 50).\ndestruct Hx as [? [? [? [? [? ?]]]]]; subst.\nassert (join c d z) by (inv H0; auto).\nassert (join a b z) by (inv H; auto).\nclear H H0.\ndestruct (share_cross_split _ _ _ _ _ H2 H1) as [[[[ac ad] bc] bd] [Ha [Hb [Hc Hd]]]].\ndestruct (dec_share_identity ac).\napply i in Ha; apply i in Hc. subst.\ndestruct (dec_share_identity bd).\napply join_comm in Hb; apply join_comm in Hd; apply i0 in Hb; apply i0 in Hd; subst.\napply lifted_eq in Hb. apply lifted_eq in Hd; subst b d.\nrename k2 into k; rename p2 into p.\nexists (NO, YES a k p, YES c k p, NO); simpl; split; auto. constructor.\nsplit3; constructor; auto.\nrename k2 into k; rename p2 into p.\napply nonidentity_nonunit in n.\nexists (NO, YES a k p, YES c k p, YES (mk_lifted _ n) k p); simpl; split; auto.\nconstructor. split3; constructor; auto.\ndestruct (dec_share_identity ad).\napply join_comm in Ha; apply i in Ha; apply i in Hd; subst bd ac.\nclear n.\ndestruct (dec_share_identity bc).\napply join_comm in Hc; apply i0 in Hb; apply i0 in Hc.  apply lifted_eq in Hb; apply lifted_eq in Hc; subst d c.\nrename k2 into k; rename p2 into p.\nexists (YES a k p, NO, NO, YES b k p); simpl; split; auto.\nconstructor. split3; constructor; auto.\nrename k2 into k; rename p2 into p.\nexists (YES a k p, NO, YES (mk_lifted _ (nonidentity_nonunit n)) k p, YES d k p); simpl; split; auto.\nconstructor. split3; constructor; auto.\ndestruct (dec_share_identity bc).\napply join_comm in Hc; apply i in Hb; apply i in Hc.  subst ac bd.\nrename k2 into k; rename p2 into p.\nexists (YES c k p, YES (mk_lifted _ (nonidentity_nonunit n0)) k p, NO, YES b k p); simpl; split; auto.\nconstructor. auto. split3; constructor; auto.\ndestruct (dec_share_identity bd).\napply join_comm in Hb; apply join_comm in Hd;\n apply i in Hb; apply i in Hd. subst bc ad.\nrename k2 into k; rename p2 into p.\nexists (YES (mk_lifted _ (nonidentity_nonunit n)) k p,  YES d k p, YES b k p, NO); split; simpl; auto.\nconstructor; auto. split3; constructor; auto.\nrename k2 into k; rename p2 into p.\nexists (YES (mk_lifted _ (nonidentity_nonunit n)) k p, YES (mk_lifted _ (nonidentity_nonunit n0)) k p,\n       YES (mk_lifted _ (nonidentity_nonunit n1)) k p,  YES (mk_lifted _ (nonidentity_nonunit n2)) k p); split; simpl; auto.\nconstructor; auto.  split3; constructor; auto.\nelimtype False; inv H0.\nelimtype False; inv H0.\nelimtype False; inv H0; inv H.\nelimtype False; inv H.\nexists (PURE a p, PURE a p, PURE a p, PURE a p).\ninv H. inv H0.\nrepeat split; constructor; auto.\nQed.\n\nInstance Cross_rmap:\n      @Cross_alg _ (Join_prop _ Join_trace AV.valid) ->\n      Cross_alg rmap.\nProof.\n  intro CAV.\n  repeat intro.\n  assert (Hz : valid (resource_at z)).\n  unfold resource_at.\n  case_eq (unsquash z); intros.\n  simpl.\n  destruct r; simpl; auto.\n  specialize (CAV\n          (exist AV.valid _ (rmap_valid a))\n          (exist AV.valid _ (rmap_valid b))\n          (exist AV.valid _ (rmap_valid c))\n          (exist AV.valid _ (rmap_valid d))\n          (exist AV.valid _ Hz)).\n  destruct CAV as [[[[Vac Vad] Vbc] Vbd] [Va [Vb [Vc Vd]]]].\n  intro l.  unfold compose. simpl.\n  apply res_option_join. apply resource_at_join. auto.\n  intro l.  simpl. unfold compose.\n  apply res_option_join. apply resource_at_join. auto.\n  destruct (fixup_trace_rmap Vac z) as [Mac [? ?]].\n  destruct (fixup_trace_rmap Vad z) as [Mad [? ?]].\n  destruct (fixup_trace_rmap Vbc z) as [Mbc [? ?]].\n  destruct (fixup_trace_rmap Vbd z) as [Mbd [? ?]].\n  exists (Mac,Mad,Mbc,Mbd).\n  destruct Vac as [ac ?]; destruct Vad as [ad ?]; destruct Vbc as [bc ?];\n  destruct Vbd as [bd ?]; simpl in *.\n  assert (LEVa: level a = level z) by (apply join_level in H; destruct H; auto).\n  assert (LEVb: level b = level z) by (apply join_level in H; destruct H; auto).\n  assert (LEVc: level c = level z) by (apply join_level in H0; destruct H0; auto).\n  assert (LEVd: level d = level z) by (apply join_level in H0; destruct H0; auto).\n  do 2 red in Va,Vb,Vc,Vd; simpl in *.\n  unfold compose in *. clear Hz.\n  split; [|split3];   apply resource_at_join2; try congruence; intro l;\n  spec Va l; spec Vb l; spec Vc l; spec Vd l;\n  apply (resource_at_join _ _ _ l) in H;\n  apply (resource_at_join _ _ _ l) in H0;\n  try rewrite H2; try rewrite H4; try rewrite H6; try rewrite H8;\n  unfold fixup_trace; simpl in *.\n  forget (a @ l) as al; forget (b @ l) as bl; forget (c @ l ) as cl;\n  forget (d @ l) as dl; forget (z @ l) as zl;\n   clear - Va Vb Vc Vd H H0.\n  (* case 1 *)\n  destruct (ac l); crtac. destruct (ad l); crtac.\n  (* case 2 *)\n  destruct (bc l); crtac. destruct (bd l); crtac.\n  (* case 3 *)\n  destruct (ac l); crtac. destruct (bc l); crtac.\n  (* case 4 *)\n  destruct (ad l); crtac. destruct (bd l); crtac.\nQed.\n\nLemma Cross_rmap_simple: (forall f, AV.valid f) -> Cross_alg rmap.\nProof.\n  intro V.\n   apply Cross_rmap.\n   intros [a Ha] [b Hb] [c Hc] [d Hd] [e He] ? ?.\n   do 2 red in H,H0. simpl in *.\n   assert (Cross_alg (AV.address -> option (pshare * AV.kind))).\n     apply (cross_split_fun  (option (pshare * AV.kind))).\n   eapply (Cross_bij' _ _ _ _ (opposite_bij (option_bij (lift_prod_bij _ _)))).\n   apply Cross_smash; auto with typeclass_instances.\n   clear; intro. destruct x. destruct (dec_share_identity t); [left|right].\n    apply identity_unit_equiv in i. apply identity_unit_equiv. split; auto.\n    contradict n.\n    apply identity_unit_equiv in n. apply identity_unit_equiv. destruct n; auto.\n   clear. extensionality a b c. apply prop_ext.\n   destruct a as [[[? ?] ?] | ]; destruct b  as [[[? ?] ?] | ]; destruct c as [[[? ?] ?] | ];\n   split; simpl; intro H; inv H; simpl in *; try constructor; auto; hnf in  *; simpl in *;\n   try proof_irr; try constructor;\n     destruct H3; constructor; simpl; auto. (* this line for compatibility with Coq 8.3 *)\n   destruct (X a b c d e H H0) as [[[[ac ad] bc] bd] [? [? [? ?]]]].\n   exists (exist AV.valid ac (V _), exist AV.valid ad (V _),\n              exist AV.valid bc (V _), exist AV.valid bd (V _)).\n   split; [ |split3]; simpl; auto.\nQed.\n\nLemma identity_resource: forall r: resource, identity r <->\n    match r with YES _ _ _ => False | _ => True end.\nProof.\n intros. destruct r; intuition.\n apply NO_identity.\n specialize (H NO (YES p k p0)).\n spec H. constructor. inv H.\n intros  ? ? ?. inv H0. auto.\nQed.\n\nLemma resource_at_core_identity:  forall m i, identity (core m @ i).\nProof.\n  intros.\n  generalize (core_duplicable m); intro Hdup. apply (resource_at_join _ _ _ i) in Hdup.\n  apply identity_resource.\n  case_eq (core m @ i); intros; auto.\n  rewrite H in Hdup. inv Hdup.\n   apply pshare_nonunit in H1. auto.\nQed.\n\nLemma YES_inj: forall sh k pp sh' k' pp',\n           YES sh k pp = YES sh' k' pp' ->\n          sh=sh' /\\ k=k' /\\ pp=pp'.\nProof. intros. inv H. auto. Qed.\n\nLemma SomeP_inj1: forall t t' a a', SomeP t a = SomeP t' a' -> t=t'.\n  Proof. intros. inv H; auto. Qed.\nLemma SomeP_inj2: forall t a a', SomeP t a = SomeP t a' -> a=a'.\n  Proof. intros. inv H. apply inj_pair2 in H1. auto. Qed.\nLemma SomeP_inj:\n   forall T a b, SomeP T a = SomeP T b -> a=b.\nProof. intros. inv H. apply inj_pair2 in H1. auto.\nQed.\n\nLemma PURE_inj: forall T x x' y y', PURE x (SomeP T y) = PURE x' (SomeP T y') -> x=x' /\\ y=y'.\n Proof. intros. inv H. apply inj_pair2 in H2. subst; auto.\n Qed.\n\nLemma core_resource_at: forall w i, core (w @ i) = core w @ i.\nProof.\n intros.\n generalize (core_unit w); intros.\n apply (resource_at_join _ _ _ i) in H.\n generalize (core_unit (w @ i)); unfold unit_for; intros.\n eapply join_canc; eauto.\nQed.\n\nEnd Rmaps_Lemmas.\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/rmaps_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982043529716, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.29613234430466406}}
{"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.\n\n(******************************************************************************)\n(* Reducibility of configurations number 227 to 230, whose indices in         *)\n(* the_configs range over segment [226, 230).                                 *)\n(******************************************************************************)\n\nLemma red226to230 : reducible_in_range 226 230 the_configs.\nProof. CheckReducible. Qed.\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/job227to230.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.29605060278058815}}
{"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(*               Typed LambdaFactor Calculus                          *)\n(*                                                                    *)\n(* is implemented in Coq by adapting the implementation               *) \n(* of Lambda Calculus  from Project Coq                               *)\n(* 2015                                                               *)\n(**********************************************************************)\n\n(**********************************************************************)\n(*                   type_derivation.v                                *)\n(*                                                                    *)\n(*                      Barry Jay                                     *)\n(*                                                                    *)\n(**********************************************************************)\n\nRequire Import Arith.\nRequire Import Bool.\nRequire Import List.\nRequire Import General.\nRequire Import Max. \nRequire Import Test.\nRequire Import LamSF_Terms.\nRequire Import LamSF_Tactics.\nRequire Import LamSF_Substitution_term.\nRequire Import Components. \nRequire Import Compounds. \nRequire Import LamSF_reduction.\nRequire Import LamSF_Closed.\n\n\n(* Types of System F *) \n\n(* Typing will be implicit, with rules for instantiating and\ngeneralising type variables that do not change the term.  Further, the\npresence of the operators requires that there be rules for pushing type\nvariables to the right of arrows after generalising when the bound\nvariable does not appear in the argument type. \n\nThe main goal is to prove subject reduction. This is challenging since\nthere may be many derivations of the same typing. The strategy will be\nto define derivation in a natural manner, and then reduce the variety\nof derivation strategies allowed, without losing any typings. This is\ndone by first limiting instantiation to variables and operators, and\nthen requiring instantiation to produce a well-formed type,\ni.e. without abstractions to the right of an arrow.\n\n*)  \n\n(* the terms are also used to represent types *) \n\nDefinition varty := Ref .\nDefinition funty ty1 ty2 := App (App s_op ty1) ty2.\n\nFixpoint quant (k:nat) ty := \nmatch k with \n| 0 => ty \n| S k1 => Abs (quant k1 ty)\nend.\n\nLemma quant_quant: forall j n ty, quant j (quant n ty) = quant (j+n) ty. \nProof. induction j; split_all. Qed. \n\n\nLemma lift_rec_preserves_quant : \nforall n ty n0 k, \nlift_rec (quant n ty) n0 k = quant n (lift_rec ty (n+n0) k). \nProof. \ninduction n; split_all. unfold quant; fold quant; simpl. rewrite IHn. \nreplace(n + S n0) with (S (n+n0)) by omega. auto. \nQed. \n\nLemma subst_rec_preserves_quant : \nforall n ty1 ty2 k, \nsubst_rec (quant n ty1) ty2 k = \nquant n (subst_rec ty1 ty2 (n+k)) . \nProof. \ninduction n; unfold lift; split_all. \n(* 2 *) \nrepeat (rewrite lift_rec_null). auto.  \n(* 1 *) \nrewrite IHn; unfold lift. \nreplace (n + S k) with (S (n+k)) by omega; auto. \nQed. \n\nLemma quant_monotonic : \nforall n ty1 ty2, \n quant n ty1 = quant n ty2 -> ty1 = ty2. \nProof. induction n; split_all.  inversion H. auto. Qed. \n\n(* the well-formed type schemes are characterised as follows *) \n\nInductive wfs : lamSF -> Prop := \n| wfs_var : forall i, wfs (varty i)\n| wfs_funty : forall ty1 ty2, wfs ty1 -> wfs ty2 -> wfs (funty ty1 ty2)\n| wfs_abs : forall ty, wfs ty -> wfs (Abs ty)\n.\n\nHint Constructors wfs.\n\n(* the well-formed types are a sub-set of the well-formed schemes *) \n \nInductive wf : lamSF -> Prop := \n| wf_var : forall i, wf (varty i)\n| wf_funty : forall ty1 ty2, wfs ty1 -> wf ty2 -> wf (funty ty1 ty2)\n.\n\nHint Constructors wf.\n \nLemma lift_rec_preserves_wfs: forall ty, wfs ty -> forall n k, wfs(lift_rec ty n k).\nProof. \nrank_tac. induction ty; split_all; inv1 wfs; subst; simpl in *. \neapply2 wfs_abs. \neapply2 IHty. omega. \neapply2 wfs_funty.  eapply2 IHp; omega. eapply2 IHty2; omega. \nQed.\n\nLemma lift_rec_reflects_wfs : forall ty n k, wfs (lift_rec ty n k) -> wfs ty. \nProof. \nrank_tac. \ninduction ty; split_all. \ninversion H0; subst. eapply2 wfs_abs. eapply2 IHp. omega. \ninversion H0; subst. \ngen3_case H H0 H1 ty1. \ninversion H1; subst. \ngen3_case H H0 H5 l; try discriminate. \nrewrite <- H5. \neapply2 wfs_funty. \neapply2 IHp. omega.  \neapply2 IHp. omega.  \nQed. \n\n\n\nLemma subst_rec_preserves_wfs: forall ty1 ty k, wfs ty1 -> wfs ty -> wfs (subst_rec ty1 ty k).\nProof. \nrank_tac. \ninduction ty1; split_all. \nunfold insert_Ref. elim(compare k n); split_all. elim a; split_all. \nunfold lift; eapply2 lift_rec_preserves_wfs. \neapply2 wfs_abs. eapply2 IHty1. simpl in *; omega. inversion H0; auto. \ninversion H0; subst. \nsimpl. eapply2 wfs_funty. \neapply2 IHp. simpl in *; omega. \neapply2 IHp. simpl in *; omega. \nQed. \n\nLemma lift_rec_preserves_wf: forall ty, wf ty -> forall n k, wf(lift_rec ty n k).\nProof. induction ty; split_all; inv1 wf. eapply2 wf_funty.  eapply2 lift_rec_preserves_wfs. Qed.\n\nHint Resolve lift_rec_preserves_wfs lift_rec_preserves_wf. \n\nLemma wf_implies_wfs : forall ty, wf ty -> wfs ty. \nProof. induction ty; split_all; inv1 wf; subst. eapply2 wfs_funty. Qed. \n\nLemma quant_preserves_wfs: forall j ty, wfs ty -> wfs (quant j ty).\nProof. induction j; split_all. Qed.  \n\n(* operator types *) \n\n\nDefinition op_abs o := \nmatch o with \n| Sop => 3\n| Aop => 2 \n| Kop => 2\n| Eop => 3\n| Gop => 2\n| Qop => 2\n| Uop => 1\n| _ => 1\nend.\n\n\nDefinition  opty_core0 (o: operator) := \nmatch o with \n  | Sop => funty (funty (varty 2) (funty (varty 1) (varty 0)))\n                 (funty (funty (varty 2) (varty 1))\n                        (funty (varty 2) (varty 0))\n                 )\n  | Aop => funty (funty (varty 0) (varty 1)) (funty (varty 0) (varty 1)) \n  | Kop => funty (varty 1) (funty (varty 0) (varty 1))\n  | Eop => funty (varty 2) (funty (varty 1) (funty (varty 0) (funty (varty 0) (varty 0)))) \n  | Gop => funty (Abs (funty (funty (varty 0) (varty 2)) (funty (varty 0) (varty 1))))\n                        (funty (varty 1) (varty 0))\n  | Qop => funty (Abs (funty (varty 0) (varty 1)))\n                 (funty (funty (varty 0) (funty (varty 0) (varty 0)))\n                        (funty (varty 1) (varty 0)))\n  | Uop => funty (Abs (Abs (funty (varty 1) \n                                         (funty (funty (varty 0) (varty 1))\n                                                (funty (varty 0) (varty 1))))))\n                        (funty (varty 0) (varty 0))\n  | Yop => funty (funty (varty 0) (varty 0)) (varty 0)\n| _ => Op o (* dummy value *) \nend. \n\nDefinition  case_op_type o := \n  funty (quant (op_abs o) (opty_core0 o)) \n        (funty (funty (varty 0) (varty 0)) \n               (funty (varty 0) (varty 0))) .\n\nDefinition opty_core o := \nmatch o with \n| DSop => case_op_type Sop \n| DAop => case_op_type Aop \n| DKop => case_op_type Kop \n| DEop => case_op_type Eop \n| DGop => case_op_type Gop \n| DQop => case_op_type Qop \n| DUop => case_op_type Uop \n| DYop => case_op_type Yop \n| _ => opty_core0 o\nend. \n\n\nDefinition opty (o: operator) := quant (op_abs o) (opty_core o). \n\nLtac unfold_opty := unfold opty, opty_core, opty_core0, case_op_type, op_abs, quant. \n\n\n(* instance *) \n\n\nInductive instance1 : lamSF -> lamSF -> Prop :=\n| instance_rule : forall ty ty1, wfs ty -> wfs ty1 -> instance1 (Abs ty1) (subst ty ty1)\n| instance_abs : forall ty1 ty2, instance1 ty1 ty2 -> instance1 (Abs ty1) (Abs ty2)\n| instance_funty : forall ty1 ty2 ty3, wfs ty1 -> instance1 ty2 ty3 -> \n                                     instance1 (funty ty1 ty2) (funty ty1 ty3)\n| instance_contra : forall ty0 ty1 ty2, instance1 ty0 ty1 -> wfs ty2 -> \n                                     instance1 (funty ty1 ty2) (funty ty0 ty2)\n. \n\nHint Constructors instance1. \n\nDefinition instance := multi_step instance1.\n\nLemma lift_rec_preserves_instance1 : lift_rec_preserves instance1.  \nProof. \nintros ty1 ty2 p; induction p; split_all. \nunfold subst; replace n with (0+n) by omega; \nrewrite lift_rec_subst_rec; try omega. \neapply2 instance_rule.\neapply2 instance_funty.\neapply2 instance_contra.\nQed. \n\nLemma lift_rec_preserves_instance : \nforall ty1 ty2, instance ty1 ty2 -> \nforall n k, instance (lift_rec ty1 n k) (lift_rec ty2 n k). \nProof. \neapply2 lift_rec_preserves_multi_step. \nred; split_all. eapply2 lift_rec_preserves_instance1.\nQed. \n\nLemma subst_rec_preserves_instance1 : \nforall ty1 ty2, instance1 ty1 ty2 -> \nforall ty k, wfs ty -> instance1(subst_rec ty1 ty k) (subst_rec ty2 ty k). \nProof. \nintros ty1 ty2 p; induction p; split_all. \n(* 3 *) \nunfold subst. replace k with (0+k) by auto. \nrewrite subst_rec_subst_rec. simpl. \nreplace(subst_rec (subst_rec ty1 ty0 (S k)) (subst_rec ty ty0 k) 0)\nwith (subst (subst_rec ty ty0 k) (subst_rec ty1 ty0 (S k))) by auto.\neapply2 instance_rule; eapply2 subst_rec_preserves_wfs. \n(* 2 *) \neapply2 instance_funty.  eapply2 subst_rec_preserves_wfs. \neapply2 instance_contra. eapply2 subst_rec_preserves_wfs.\nQed.\n\nLemma subst_rec_preserves_instance : \nforall ty1 ty2, instance ty1 ty2 -> \nforall ty k, wfs ty -> instance(subst_rec ty1 ty k) (subst_rec ty2 ty k). \nProof. \ncut(forall red ty1 ty2, multi_step red ty1 ty2 -> red = instance1 -> \nforall ty k, wfs ty -> instance(subst_rec ty1 ty k) (subst_rec ty2 ty k)).\nintro c; split_all; eapply2 c. \nintros red ty1 ty2 m; induction m; split_all; subst.\neapply2 zero_red. \napply transitive_red with (subst_rec N ty k); auto.\none_step. eapply2 subst_rec_preserves_instance1.\neapply2 IHm.\nQed.\n\n\nLemma preserves_abs_instance : forall ty1 ty2, instance ty1 ty2 -> instance (Abs ty1) (Abs ty2).\nProof. \ncut(forall red ty1 ty2, multi_step red ty1 ty2 -> red = instance1 -> \ninstance (Abs ty1) (Abs ty2)).\nintro aux; split_all; eapply2 aux. \nintros red ty1 ty2 m; induction m; split_all; subst. eapply2 zero_red. \neapply succ_red. 2: eapply2 IHm. auto. \nQed. \n\nLemma preserves_funty_r_instance : \nforall ty1 ty2 ty3, wfs ty1 -> instance ty2 ty3 -> instance(funty ty1 ty2) (funty ty1 ty3).\nProof. \ncut(forall red ty1 ty2 ty3, wfs ty1 -> multi_step red ty2 ty3 -> red = instance1 -> \ninstance(funty ty1 ty2) (funty ty1 ty3)).\nintro aux; split_all; eapply2 aux. \nintros red ty1 ty2 ty3 w m; induction m; split_all; subst. \neapply2 zero_red. \neapply transitive_red. one_step. eapply instance_funty; auto. \neexact H. eapply2 IHm. \nQed. \n\nLemma preserves_contra_instance : \nforall ty1 ty2 ty3, wfs ty1 -> instance ty2 ty3 -> instance(funty ty3 ty1) (funty ty2 ty1).\nProof. \ncut(forall red ty1 ty2 ty3, wfs ty1 -> multi_step red ty2 ty3 -> red = instance1 -> \ninstance(funty ty3 ty1) (funty ty2 ty1)).\nintro aux; split_all; eapply2 aux. \nintros red ty1 ty2 ty3 w m; induction m; split_all; subst. \neapply2 zero_red. \neapply transitive_red. eapply2 IHm. one_step. \nQed. \n\nLemma instance1_implies_wfs: forall ty1 ty2, instance1 ty1 ty2 -> wfs ty1 /\\ wfs ty2. \nProof. \nintros ty1 ty2 inst; induction inst; split_all. \nunfold subst; eapply2 subst_rec_preserves_wfs.\nQed. \n\nLemma instance_implies_wfs: \nforall ty1 ty2, instance ty1 ty2 -> (wfs ty1 -> wfs ty2) /\\ (wfs ty2 -> wfs ty1). \nProof. \ncut(forall red ty1 ty2, multi_step red ty1 ty2 -> red = instance1 -> \n (wfs ty1 -> wfs ty2) /\\ (wfs ty2 -> wfs ty1)).\nintro aux; intros; \nassert((wfs ty1 -> wfs ty2) /\\ (wfs ty2 -> wfs ty1)) by eapply2 aux; split_all.  \n\nintros red ty1 ty2 m; induction m; split_all; subst. \neapply2 IHm; eapply2 instance1_implies_wfs.  \nassert(wfs M /\\ wfs N) by eapply2 instance1_implies_wfs. split_all. \nQed. \n\n\nLemma preserves_funty_instance : \nforall ty0 ty1 ty2 ty3, wfs ty1 -> wfs ty2 -> instance ty0 ty1 -> instance ty2 ty3 -> \ninstance(funty ty1 ty2) (funty ty0 ty3).\nProof. \nsplit_all. eapply transitive_red. eapply2 preserves_funty_r_instance. \neapply2 preserves_contra_instance. \nassert((wfs ty2 -> wfs ty3) /\\ (wfs ty3 -> wfs ty2)) by eapply2 instance_implies_wfs. \nsplit_all. \nQed. \n\nLemma preserves_varty_instance : \nforall red ty1 ty2, multi_step red ty1 ty2 -> red = instance1 -> forall i, ty1 = varty i -> ty2 = ty1. \nProof. intros red ty1 y2 m; induction m; split_all; subst. inversion H. Qed. \n\n(* push *) \n\nInductive push1 : lamSF -> lamSF -> Prop := \n| push_lift : forall ty1 ty2, wfs ty1 -> wfs ty2 -> \n                push1 (Abs (funty (lift 1 ty1) ty2)) (funty ty1 (Abs ty2))\n| push_abs : forall ty1 ty2, push1 ty1 ty2 -> push1 (Abs ty1) (Abs ty2)\n                                    (* for pushing after generalizing *)\n| push_funty : forall ty1 ty2 ty3, \n                push1 ty2 ty3 -> wfs ty1 -> \n                push1 (funty ty1 ty2) (funty ty1 ty3)  \n. \n\nDefinition push := multi_step push1. \n\nHint Resolve push_lift push_abs push_funty. \n\n\nLemma lift_rec_preserves_push1 : \nforall ty1 ty2, push1 ty1 ty2 -> \nforall n k, push1 (lift_rec ty1 n k) (lift_rec ty2 n k). \nProof. \nintros ty1 ty2 p; induction p; split_all.\nunfold lift, funty; rewrite lift_lift_rec; try omega. eapply2 push_lift.\neapply2 push_funty. \nQed. \n\nLemma subst_rec_preserves_push1 : \nforall ty1 ty2, push1 ty1 ty2 -> \nforall ty k, wfs ty ->  push1 (subst_rec ty1 ty k) (subst_rec ty2 ty k). \nProof. \nintros ty1 ty2 p; induction p; split_all. \nunfold lift; rewrite subst_rec_lift_rec1; try omega.\neapply2 push_lift; eapply2 subst_rec_preserves_wfs. \neapply2 push_funty; eapply2 subst_rec_preserves_wfs. \n\nQed. \n\nLemma subst_rec_preserves_push : \nforall red ty1 ty2, multi_step red ty1 ty2 -> red = push1 -> \nforall ty k, wfs ty -> push (subst_rec ty1 ty k) (subst_rec ty2 ty k). \nProof. \nintros red ty1 ty2 p; induction p; split_all; subst. \neapply2 zero_red. \napply succ_red with (subst_rec N ty k); auto. \neapply2 subst_rec_preserves_push1. \neapply2 IHp. \nQed. \n\n\n\nLemma preserves_funty_r_push : \nforall ty1 ty2 ty3, wfs ty1 -> push ty2 ty3 -> push(funty ty1 ty2) (funty ty1 ty3).\nProof. \ncut(forall red ty1 ty2 ty3, wfs ty1 -> multi_step red ty2 ty3 -> red = push1 -> \npush(funty ty1 ty2) (funty ty1 ty3)).\nintro aux; split_all; eapply2 aux. \nintros red ty1 ty2 ty3 w m; induction m; split_all; subst. \neapply2 zero_red. \neapply transitive_red. one_step. eapply push_funty; auto. \neexact H. eapply2 IHm. \nQed. \n\n\n\nLemma push1_quant : \nforall j ty1 ty2, push1 ty1 ty2 -> push1 (quant j ty1) (quant j ty2).\nProof. induction j; split_all; rewrite IHj; auto. Qed. \n\nLemma push_quant : \nforall j ty1 ty2, wfs ty1 -> wfs ty2 -> push (quant j (funty (lift j ty1) ty2)) \n                       (funty ty1 (quant j ty2)).\nProof.\ninduction j; split_all. \n(* 2 *) \nunfold lift; rewrite lift_rec_null. eapply2 zero_red. \n(* 1 *) \napply transitive_red  with (Abs (funty (lift 1 ty1) (quant j ty2))); auto. \neapply2 preserves_abs_multi_step. red; split_all.\nreplace(lift (S j) ty1) with (lift j (lift 1 ty1)).\neapply2 IHj.\nunfold lift; eapply2 lift_rec_preserves_wfs. \nunfold lift; rewrite lift_rec_lift_rec; try omega.  \nreplace (j+1) with (S j) by omega; auto.\none_step.\neapply2 push_lift. \nclear - H0. \ninduction j; split_all. \nQed. \n\nLemma push_preserves_abs : \nforall ty1 ty2, push ty1 ty2 -> push (Abs ty1) (Abs ty2). \nProof.\ncut(forall red ty1 ty2, multi_step red ty1 ty2 -> red = push1 -> \n                        push (Abs ty1) (Abs ty2)).\nintro aux; split_all; eapply2 aux. \nintros red ty1 ty2 m; induction m; split_all; subst.\neapply2 zero_red. \neapply succ_red.\neapply2 push_abs. \neapply2 IHm.\nQed.\n\n\nLemma push_preserves_funty : \nforall ty0 ty1 ty2, push ty1 ty2 -> wfs ty0 -> push (funty ty0 ty1) (funty ty0 ty2). \nProof.\ncut(forall red ty0 ty1 ty2, multi_step red ty1 ty2 -> red = push1 -> wfs ty0 -> \n                        push (funty ty0 ty1) (funty ty0 ty2)).\nintro aux; split_all; eapply2 aux. \nintros red ty0 ty1 ty2 m; induction m; split_all; subst.\neapply2 zero_red. \neapply succ_red.\neapply2 push_funty. \neapply2 IHm.\nQed.\n\n\nLemma preserves_abs_push : preserves_abs push. \nProof.  eapply2 preserves_abs_multi_step. red; split_all. Qed. \n\nLemma push_implies_wfs: forall ty1 ty2, push1 ty1 ty2 -> wfs ty1 /\\ wfs ty2. \nProof. \nintros ty1 ty2 p; induction p; split_all. \neapply2 wfs_abs. eapply2 wfs_funty. unfold lift; eapply2 lift_rec_preserves_wfs. \nQed. \n\n\nLemma push1_instance1: \nforall ty1 ty2, push1 ty1 ty2 -> forall ty3, instance1 ty2 ty3 -> \nexists ty4, instance1 ty1 ty4 /\\ push ty4 ty3. \nProof. \nintros ty1 ty2 p; induction p; split_all. \n(* 3 *) \ninversion H1; subst. inversion H6; subst.\n(* 5 *) \nexist (subst ty (funty (lift 1 ty1) ty2)).\neapply2 instance_rule.  unfold lift; simpl. eapply2 wfs_funty. \nunfold subst, lift; simpl. \nrewrite subst_rec_lift_rec; try omega. rewrite lift_rec_null. \neapply2 zero_red. \n(* 4 *) \nexist (Abs (funty (lift 1 ty1) ty3)) . \nunfold lift; simpl. eapply2 instance_abs. \nred; one_step. eapply2 push_lift.  eapply2 instance1_implies_wfs. \n(* 3 *) \nunfold lift; simpl. \nexist  (Abs (App (App (Op Sop) (lift_rec ty0 0 1)) ty2)) .\neapply2 instance_abs. eapply2 instance_contra. eapply2 lift_rec_preserves_instance1. \nred; one_step. \nreplace  (App (Op Sop) (lift_rec ty0 0 1)) with (lift 1 (App s_op ty0)) by auto. \neapply2 push_lift.  \nassert(wfs ty0 /\\ wfs ty1) by eapply2 instance1_implies_wfs. split_all. \n(* 2 *) \ninversion H; subst.\n(* 3 *)   \nexist(subst ty ty1). eapply2 instance_rule.\nassert(wfs ty1 /\\ wfs ty2) by eapply2 push_implies_wfs. split_all. \nunfold subst; simpl. red; one_step. eapply2 subst_rec_preserves_push1. \n(* 2 *) \nassert(exists ty5 : lamSF, instance1 ty1 ty5 /\\ push ty5 ty4) by eapply2 IHp.\nsplit_all. \nexist(Abs x). \neapply2 preserves_abs_push. \n(* 1 *) \ninversion H0; subst.  \nassert(exists ty5 : lamSF, instance1 ty2 ty5 /\\ push ty5 ty6) by eapply2 IHp.\nsplit_all. \nexist(funty ty1 x). \neapply2 preserves_funty_r_push.\n(* 1 *) \nexist(funty ty4 ty2). eapply2 instance_contra. \nassert(wfs ty2 /\\ wfs ty3) by eapply2 push_implies_wfs. split_all. \nred; one_step. \neapply2 push_funty. \nassert(wfs ty4 /\\ wfs ty1) by eapply2 instance1_implies_wfs. split_all. \nQed. \n\n\n(* contexts *)\n\n\nDefinition context := list lamSF. \n\nInductive wfc : context -> Prop := \n| wfc_nil : wfc nil\n| wfc_cons : forall ty gamma, wfs ty -> wfc gamma -> wfc (cons ty gamma).\n\nHint Resolve wfc_nil wfc_cons. \n\nLemma lift_rec_preserves_wfc : \nforall gamma, wfc gamma -> forall n k, wfc (map (fun M => lift_rec M n k) gamma). \nProof. induction gamma; split_all. inversion H; subst. eapply2 wfc_cons. Qed. \n\nLemma subst_rec_preserves_wfc : \nforall gamma, wfc gamma -> forall sch k, wfs sch -> wfc (map (fun M => subst_rec M sch k) gamma). \nProof. \ninduction gamma; split_all. \ninversion H; subst. eapply2 wfc_cons. eapply2 subst_rec_preserves_wfs. \nQed. \n\nHint Resolve lift_rec_preserves_wfc subst_rec_preserves_wfc. \n\nLemma lift0_context : forall gamma : context, List.map (lift 0) gamma = gamma. \nProof. induction gamma; split_all. rewrite IHgamma. unfold lift; rewrite lift_rec_null. auto. Qed.\n\nDefinition insertn k (gamma: context) sch := app (firstn k gamma) (cons sch (skipn k gamma)). \nDefinition removen k (gamma: context) := app (firstn k gamma) (tl (skipn k gamma)). \n\n\nLemma append_preserves_wfc : \nforall gamma1 gamma2, wfc gamma1 -> wfc gamma2 -> wfc (gamma1 ++ gamma2).\nProof. induction gamma1; split_all. inversion H. eapply2 wfc_cons. Qed. \n\nLemma tl_preserves_wfc : \nforall gamma, wfc gamma -> wfc (tl gamma).\nProof. induction gamma; split_all. inversion H; auto. Qed. \n\nLemma firstn_preserves_wfc: forall k gamma, wfc gamma -> wfc (firstn k gamma).\nProof. \ninduction k; split_all. induction gamma; split_all. inversion H; subst. eapply2 wfc_cons. \nQed. \n\nLemma skipn_preserves_wfc: forall k gamma, wfc gamma -> wfc (skipn k gamma).\nProof. \ninduction k; split_all. induction gamma; split_all. inversion H; subst. eapply2 IHk. \nQed. \n\nLemma insertn_preserves_wfc: \nforall k gamma sch, wfc gamma -> wfs sch -> wfc (insertn k gamma sch). \nProof. \nsplit_all. unfold insertn. eapply2 append_preserves_wfc.\neapply2 firstn_preserves_wfc. \neapply2 wfc_cons. eapply2 skipn_preserves_wfc. \nQed. \n\nLemma removen_preserves_wfc: forall k gamma, wfc gamma -> wfc (removen k gamma). \nProof. \nsplit_all. unfold removen. eapply2 append_preserves_wfc.\neapply2 firstn_preserves_wfc. \nassert (wfc (skipn k gamma)) by eapply2 skipn_preserves_wfc. \ngen_case H0 (skipn k gamma). \ninversion H0; auto. \nQed. \n\nHint Resolve insertn_preserves_wfc removen_preserves_wfc. \n\n\nLtac wfcs_tac := unfold lift; simpl; relocate_lt; repeat eapply2 wfc_cons;  \nrepeat (repeat eapply2 wfs_abs; repeat eapply2 wfs_funty); simpl; auto.  \n\nLemma insertn_cons : \nforall k sch gamma sch0, insertn (S k) (cons sch gamma) sch0 = cons sch (insertn k gamma sch0). \nProof. auto. Qed. \n\nLemma removen_cons : \nforall k sch gamma , removen (S k) (cons sch gamma) = cons sch (removen k gamma). \nProof. auto. Qed. \n\nLemma map_skipn: \nforall gamma k (f:lamSF -> lamSF), map f (skipn k gamma) = skipn k (map f gamma).\nProof. induction gamma; split_all; induction k; split_all. Qed. \n\nLemma map_insertn : forall k sch gamma f, map f (insertn k gamma sch) = insertn k (map f gamma) (f sch). \nProof. \ninduction k; split_all.\ncase gamma. \nsplit_all. \nintros. \nreplace (map f (l :: l0)) with (f l :: map f l0) by auto. \nreplace (insertn (S k) (l :: l0) sch) with (l :: insertn k l0 sch) by auto. \nreplace (insertn (S k) (f l :: map f l0) (f sch)) \nwith (f l :: insertn k (map f l0) (f sch)) by auto. \nreplace (map f (l :: insertn k l0 sch)) with (f l :: map f (insertn k l0 sch)) \nby auto. \nrewrite IHk. auto. \nQed. \n\nLemma map_removen : forall k gamma f, map f (removen k gamma) = removen k (map f gamma). \nProof. \ninduction k; split_all.\nunfold removen, firstn; simpl.  case gamma; split_all. \ncase gamma; intros. \nsplit_all. \nreplace (map f (l::l0)) with (f l :: map f l0) by auto. \nrewrite removen_cons. \nrewrite removen_cons. \nreplace (map f (l::removen k l0)) with (f l :: map f (removen k l0)) by auto. \nrewrite IHk.  auto. \nQed. \n\n\nLemma lift_rec_reflects_wfc : \nforall gamma n k, wfc (map (fun ty => lift_rec ty n k) gamma) -> wfc gamma.\nProof. \ninduction gamma; split_all. inversion H. eapply2 wfc_cons. \neapply2 lift_rec_reflects_wfs. \nQed. \n\n\n(* type derivation *) \n\nInductive derivation : context -> lamSF -> lamSF -> Prop := \n| derive_op : forall gamma o,  wfc gamma -> derivation gamma (Op o) (opty o) \n| derive_var : forall gamma ty,  wfc gamma -> wfs ty -> derivation (cons ty gamma) (Ref 0) ty\n| derive_weak : forall gamma i ty1 ty,  derivation gamma (Ref i) ty -> wfs ty1 -> \n                                       derivation (cons ty1 gamma) (Ref (S i)) ty\n| derive_abs : forall gamma ty1 ty2 t,   \n                 derivation (cons ty1 gamma) t ty2 ->\n                 derivation gamma (Abs t) (funty ty1 ty2)\n| derive_app: forall gamma t ty1 ty2 u,  \n                derivation gamma t (funty ty1 ty2) -> \n                derivation gamma u ty1 ->\n                derivation gamma (App t u) ty2\n| derive_inst : forall gamma t ty1 ty2, derivation gamma t ty1 -> \n                                         instance1 ty1 ty2 -> \n                                   derivation gamma t ty2\n| derive_gen1: forall gamma t ty, derivation (map (lift 1) gamma) t ty ->\n                                  derivation gamma t (Abs ty)\n| derive_push1 : forall gamma t ty, derivation gamma t ty ->\n                forall ty2, push1 ty ty2 -> derivation gamma t ty2\n .\n\nHint Constructors derivation.\n\nLemma lift_rec_ty_preserves_derive : forall gamma t ty, derivation gamma t ty -> forall n k , \nderivation (map (fun ty0 => lift_rec ty0 n k) gamma) t (lift_rec ty n k). \nProof. \nintros gamma t ty d; induction d; split_all. \n(* 6 *)\nreplace (lift_rec (opty o) n k) with (opty o) by (case o; split_all); auto. \n(* 5 *) \neapply2 derive_abs; eapply2 IHd. \n(* 4 *) \nsimpl in *; eapply2 derive_app.  \n(* 3 *) \neapply2 derive_inst. eapply2 lift_rec_preserves_instance1. \n(* 2 *)\neapply2 derive_gen1.\nreplace(map (lift 1)  (map (fun ty0 : lamSF => lift_rec ty0 n k) gamma)) \nwith (map (fun ty0 : lamSF => lift_rec ty0 (S n) k) (map (lift 1) gamma)).\nauto.\nclear; induction gamma; split_all. \nrewrite IHgamma; unfold lift; rewrite lift_lift_rec; try omega; auto. \n(* 1 *) \neapply2 derive_push1. eapply2 lift_rec_preserves_push1.\nQed. \n\nLemma derive_implies_wfcs: forall gamma t ty, derivation gamma t ty -> wfc gamma /\\  wfs ty. \nProof. \nintros gamma t ty d; induction d; split_all.\n(* 7 *)  \ncase o; split_all; unfold opty, funty; split_all; unfold funty; wfcs_tac.  \n(* 6 *) \ninversion H; auto. \n(* 5 *) \ninversion H; subst. wfcs_tac. \n(* 4 *) \ninversion H2; subst. auto. \n(* 3 *) \neapply2 instance1_implies_wfs. \nassert(wfc(map (subst ty) (map (lift 1) gamma))) \nby eapply2 subst_rec_preserves_wfc. \nreplace gamma with (map (subst ty) (map (lift 1) gamma)); auto. \nclear; induction gamma; split_all. rewrite IHgamma. \nunfold lift, subst; rewrite subst_rec_lift_rec; try omega. \nrewrite lift_rec_null; auto. \neapply2 push_implies_wfs. \nQed. \n\n\n(* general form of derive_weak *)\n\nLemma derive_weak_general_k: \nforall gamma t ty, derivation gamma t ty -> \nforall k sch, wfs sch -> derivation (insertn k gamma sch) (lift_rec t k 1) ty. \nProof. \nintros gamma t ty d; induction d; split_all.\n(* 7 *) \nunfold relocate. elim(test k 0); split_all; try noway. \nassert(k=0) by omega; subst k. unfold insertn; simpl. eapply2 derive_weak. \nreplace k with (S (pred k)) by omega.\nrewrite insertn_cons. eapply2 derive_var. \n(* 6 *)\nunfold relocate. elim(test k (S i)); split_all. \ngen_case a k. unfold insertn; simpl. eapply2 derive_weak. \nrewrite insertn_cons. eapply2 derive_weak. \nreplace (Ref (S i)) with (lift_rec (Ref i) n 1) by (simpl; relocate_lt; auto). \neapply2 IHd. \nreplace k with (S (pred k)) by omega.\nrewrite insertn_cons. eapply2 derive_weak.\nreplace (Ref i) with (lift_rec (Ref i) (pred k) 1) by (simpl; relocate_lt; auto). \neapply2 IHd. \n(* 5 *) \neapply2 derive_abs. rewrite <- insertn_cons. eapply2 IHd. \n(* 4 *) \neapply2 derive_app.\n(* 3 *)\neapply2 derive_inst. \n(* 2 *) \nassert(derivation (insertn k (map (lift 1) gamma) (lift 1 sch)) (lift_rec t k 1) ty).\neapply2 IHd. unfold lift; auto. \nrewrite <- map_insertn in H0. \nauto.\n(* 1 *) \neapply2 derive_push1. \nQed. \n\nProposition derive_weak_general : \nforall gamma t ty, derivation gamma t ty -> \nforall sch, wfs sch -> derivation (sch :: gamma) (lift 1 t) ty. \nProof. \nsplit_all. \nreplace (sch :: gamma) with (insertn 0 gamma sch) by auto. \nreplace (lift 1 t) with (lift_rec t 0 1) by auto. \neapply2 derive_weak_general_k.\nQed. \n\n(* subst_rec_ty_preserves_derive *) \n\n\nLemma weak_aux : forall gamma t sch, derivation gamma t sch -> forall i, t = Ref i -> gamma <> nil. \nProof. intros gamma t sch d; induction d; split_all; \nintro; subst; split_all; unfold map in *; auto; eapply2 IHd.\nQed. \n\nLemma weak_aux1:\nforall gamma t ty, derivation gamma t ty -> forall i, t = Ref (S i) -> \nforall k, k < S i -> derivation (removen k gamma) (Ref i) ty. \nProof. \nintros gamma t ty d; induction d; split_all.\n(* 4 *) \ninversion H0; subst. \ngen_case H1 k. \nrewrite removen_cons. \nreplace i0 with (S (pred i0)) by omega. \neapply2 derive_weak. \neapply2 IHd. \nassert(i0 = S (pred i0)) by omega; congruence. \nomega. \n(* 3 *) \nsubst. eapply2 derive_inst. \n(* 2 *) \nsubst. \nassert(derivation (removen k (map (lift 1) gamma)) (Ref i) ty) by eapply2 IHd. \nrewrite <- map_removen in H. auto. \n(* 1 *) \neapply2 derive_push1.  \nQed. \n\nLemma weak_aux2:\nforall gamma t ty, derivation gamma t ty -> forall i, t = Ref i -> \nforall k, k > i -> derivation (removen k gamma) (Ref i) ty. \nProof. \nintros gamma t ty d; induction d; split_all.\n(* 5 *) \ninversion H1; subst. \ngen_case H2 k; try noway.  \nrewrite removen_cons. \neapply2 derive_var. \n(* 4 *) \ninversion H0; subst. \nreplace k with (S (pred k)) by omega. \nrewrite removen_cons. \neapply2 derive_weak. \neapply2 IHd. omega. \n(* 3 *) \neapply2 derive_inst. \n(* 2 *) \nassert(derivation (removen k (map (lift 1) gamma)) (Ref i) ty) by eapply2 IHd. \nrewrite <- map_removen in H1; auto. \n(* 1 *) \neapply2 derive_push1.  \nQed. \n\n\n\nLemma derive_push0: \nforall red gamma t ty, derivation gamma t ty ->\nforall ty2, multi_step red ty ty2 -> red = push1 -> derivation gamma t ty2.\nProof.\nintros red gamma t ty d ty2 m; induction m; split_all; subst; eapply2 IHm.\nQed.\nLemma derive_push: \nforall gamma t ty, derivation gamma t ty ->\nforall ty2, push ty ty2 -> derivation gamma t ty2.\nProof. split_all; eapply2 derive_push0. Qed. \n\n\nLemma derive_instance: \nforall gamma t ty, derivation gamma t ty ->\nforall ty2,  instance ty ty2 -> derivation gamma t ty2.\nProof.\ncut(forall gamma t ty, derivation gamma t ty ->\nforall red ty2,  multi_step red ty ty2 -> red = instance1 -> \nderivation gamma t ty2); [ intro c; split_all; eapply2 c |]. \nintros gamma t ty d red ty2 m; induction m; split_all; subst. eapply2 IHm.\nQed. \n\n\nLemma derive_gen: \nforall j gamma t ty, derivation (map (lift j) gamma) t ty ->\n                                  derivation gamma t (quant j ty).\nProof. \ninduction j; split_all. \n(* 2 *) \nrewrite lift0_context in *; auto.\n(* 1 *)\nreplace(map (lift (S j)) gamma) \nwith (map (lift j) (map (lift 1) gamma)) in H.\nassert(derivation (map (lift 1) gamma) t (quant j ty)) by eapply2 IHj.\neapply2 derive_gen1. \nclear; induction gamma; split_all; rewrite IHgamma. \nunfold lift; rewrite lift_rec_lift_rec; try omega. \nreplace(j+1) with (S j) by omega; auto.\nQed.\n\n\nLemma subst_rec_ty_preserves_derive : \nforall gamma t ty, wfs ty -> derivation gamma t ty -> \nforall ty1 k, wfs ty1 -> \nderivation (map (fun ty0 => subst_rec ty0 ty1 k) gamma) t \n           (subst_rec ty ty1 k). \nProof. \nintros gamma t ty w d; induction d; split_all. \n(* 8 *) \nreplace(subst_rec (opty o) ty1 k) with (opty o) by (case o; split_all). \neapply2 derive_op.\n(* 7 *) \neapply2 derive_var.  eapply2 subst_rec_preserves_wfs. \n(* 6 *) \neapply2 derive_weak.  eapply2 subst_rec_preserves_wfs.\n(* 5 *) \neapply2 derive_abs. eapply2 IHd. inversion w. auto. \n(* 4 *) \neapply2 derive_app. eapply2 IHd1. eapply2 derive_implies_wfcs. \neapply2 IHd2. assert(wfs (funty ty1 ty2)) by eapply2 derive_implies_wfcs. \ninversion H0. auto. \n(* 3 *) \neapply2 derive_inst. eapply2 IHd.  eapply2 derive_implies_wfcs. \neapply2 subst_rec_preserves_instance1. \n(* 2 *) \nassert(derivation\n          (map (fun ty0 : lamSF => subst_rec ty0 ty1 (S k)) (map (lift 1) gamma))\n          t (subst_rec ty ty1 (S k))).  eapply2 IHd. \ninversion w; auto. \nreplace (map (fun ty0 : lamSF => subst_rec ty0 ty1 (S k)) (map (lift 1) gamma))\nwith (map (lift 1) (map (fun ty0 : lamSF => subst_rec ty0 ty1 k) gamma)) in H0. \nauto.\nclear; induction gamma; split_all; rewrite IHgamma. \nunfold lift; rewrite subst_rec_lift_rec1; auto; omega.\n(* 1 *) \neapply2 derive_push1. eapply2 IHd. eapply2 derive_implies_wfcs. \neapply2 subst_rec_preserves_push1.\nQed. \n\nLtac subst_out := \nunfold subst; simpl; insert_Ref_out;\nrepeat (rewrite subst_rec_lift_rec; [| omega| omega]); \nrepeat (rewrite lift_rec_null); auto.\n\n\n(* subst_rec_preserves_derive *) \n\nProposition subst_rec_preserves_derive : \nforall gamma M ty, derivation gamma M ty -> \nforall k u, k < length gamma -> \nderivation (skipn (S k) gamma) u (nth k gamma s_op) -> \nderivation (removen k gamma) (subst_rec M u k) ty.\nProof. \nintros gamma M ty d; induction d; intros. \n(* 8 *) \nsplit_all.  \n(* 7 *) \ngeneralize H0; clear H0; induction k; split_all; simpl. \n(* 6 *) \nunfold removen; simpl. insert_Ref_out. rewrite lift_rec_null. auto.\n(* 5 *) \nrewrite removen_cons. insert_Ref_out. auto. \n(* 4 *) \n simpl in *. \nunfold insert_Ref. elim(compare k (S i)); split_all. elim a; split_all.\n(* 8 *)\napply weak_aux1 with (Ref (S i)); auto. \n(* 7 *) \nsubst. rewrite removen_cons. \nreplace (lift (S i) u) with (lift 1 (lift i u)). \neapply2 derive_weak_general. \ncut(derivation (removen i gamma) (subst_rec (Ref i) u i) ty).\nsimpl; insert_Ref_out. auto. \n eapply2 IHd. omega. \nunfold lift. rewrite lift_rec_lift_rec; try omega. auto. \n(* 6 *)\napply weak_aux2 with (Ref (S i)); auto. \n(* 5 *) \nsimpl. eapply2 derive_abs. \nassert(derivation (removen (S k) (ty1 :: gamma)) (subst_rec t u (S k)) ty2) by (eapply2 IHd; simpl; omega).\nreplace(removen (S k) (ty1 :: gamma)) with (ty1::removen k gamma) in H1 by auto. \nauto. \n(* 4 *) \nsimpl.  eapply2 derive_app. simpl in *; auto. \n(* 3 *) \neapply2 derive_inst. \n(* 2 *) \nassert( derivation (map (lift 1) (skipn (S k) gamma)) u (lift 1 (nth k gamma s_op))). \nunfold lift; eapply2 lift_rec_ty_preserves_derive. \nrewrite map_skipn in H1.\nassert(derivation (removen k (map (lift 1) gamma))\n          (subst_rec t u k) ty).\n eapply2 IHd. rewrite map_length; omega. \nreplace s_op with (lift 1 s_op) by auto. \nreplace(nth k (map (lift 1) gamma) (lift 1 s_op))\nwith (lift 1 (nth k gamma s_op)).  \nauto.\nrewrite map_nth. auto. \nrewrite <- map_removen in H2. \nauto.\n(* 1 *) \neapply2 derive_push1. \nQed. \n\n\nDefinition preserves_derive (red: termred) := \nforall ty1 ty2, red ty1 ty2 -> \nforall gamma t, derivation gamma t ty1 -> derivation gamma t ty2. \n\nLemma preserves_derive_multi_step: \nforall red, preserves_derive red -> preserves_derive (multi_step red).\nProof. red; intros red p ty1 ty2 m; induction m; split_all; eapply2 IHm. Qed.\n\n\nInductive instance_context : context -> context -> Prop := \n| instance_context_nil : instance_context nil nil \n| instance_context_cons : forall ty1 ty2 gamma1 gamma2, instance ty1 ty2 -> \n  instance_context gamma1 gamma2 -> instance_context (cons ty1 gamma1) (cons ty2 gamma2) \n.\n\nHint Resolve instance_context_nil instance_context_cons. \n\nLemma lift_rec_preserves_instance_context: \nforall gamma1 gamma2, instance_context gamma1 gamma2 -> \nforall n k, instance_context (map (fun M => lift_rec M n k) gamma1) \n                             (map (fun M => lift_rec M n k) gamma2).\nProof. \ninduction gamma1; split_all; inversion H; subst; split_all. \neapply2 instance_context_cons. eapply2 lift_rec_preserves_instance. \nQed. \n\nLemma instance_context_preserves_wfc: \nforall gamma1, wfc gamma1 -> forall gamma2, instance_context gamma1 gamma2 -> wfc gamma2. \nProof. \nintros gamma w; induction w; split_all. \ninversion H; split_all. \ninversion H0; split_all. eapply2 wfc_cons. subst.  \nassert((wfs ty -> wfs ty2) /\\ (wfs ty2 -> wfs ty)). eapply2 instance_implies_wfs. \nsplit_all. \nQed. \n\nLemma instance_context_reflects_wfc: \nforall gamma1, wfc gamma1 -> forall gamma2, instance_context gamma2 gamma1 -> wfc gamma2. \nProof. \nintros gamma1 w; induction w; split_all. \ninversion H; split_all. \ninversion H0; split_all. eapply2 wfc_cons. subst.  eapply2 instance_implies_wfs. \nQed. \n\nLemma derive_instance_context : \nforall gamma1 t ty, derivation gamma1 t ty -> \nforall gamma2, instance_context gamma2 gamma1 -> derivation gamma2 t ty.\nProof. \nintros gamma1 t ty d; induction d; intros gamma2 inst; subst; split_all. \n(* 8 *) \neapply2 derive_op. eapply2 instance_context_reflects_wfc.\n(* 7 *) \ninversion inst; subst. eapply2 derive_instance.  eapply2 derive_var.  \neapply2 instance_context_reflects_wfc. eapply2 instance_implies_wfs. \n(* 6 *) \ninversion inst; subst. eapply2 derive_weak. eapply2 instance_implies_wfs. \n(* 5 *) \neapply2 derive_abs. eapply2 IHd. eapply2 instance_context_cons.  eapply2 zero_red. \n(* 4 *) \neapply2 derive_app. \neapply2 derive_inst. \neapply2 derive_gen1. eapply2 IHd. unfold lift. eapply2 lift_rec_preserves_instance_context. \neapply2 derive_push1. \nQed. \n\n\n\nLemma append_preserves_derive: \nforall gamma t ty, derivation gamma t ty -> \nforall gamma2, wfc gamma2 -> derivation (gamma ++ gamma2) t ty. \nProof. \nintros gamma t ty d; induction d; split_all; \nassert(wfc(gamma++gamma2)) by (eapply2 append_preserves_wfc; eapply2 derive_implies_wfcs). \neapply2 derive_op. \neapply2 derive_var. \neapply2 derive_abs. \neapply2 derive_app. \neapply2 derive_inst. \neapply2 derive_gen1. \nrewrite map_app. eapply2 IHd. \nunfold lift; eapply2 lift_rec_preserves_wfc. \neapply2 derive_push1. \nQed. \n\nLemma derive_nil : \nforall t ty, derivation nil t ty -> forall gamma, wfc gamma -> derivation gamma t ty. \nProof. intros. replace gamma with (app nil gamma) by auto. eapply2 append_preserves_derive. Qed. \n\n\nLemma derive_strong_general_k: \nforall gamma t ty, derivation gamma t ty -> \nforall k, k > maxvar t -> derivation (removen k gamma) t ty. \nProof. \nintros gamma t ty d;  induction d; split_all;\nassert(wfc (removen k gamma)) by (eapply2 removen_preserves_wfc; eapply2 derive_implies_wfcs).\n(* 7 *) \ninduction k; split_all; try noway. unfold removen, firstn. eapply2 derive_var. \neapply2 append_preserves_wfc. \neapply2 firstn_preserves_wfc. \nsimpl. eapply2 tl_preserves_wfc. eapply2 skipn_preserves_wfc. \n(* 6 *) \ninduction k; split_all; try noway. unfold removen, firstn. eapply2 derive_weak. \neapply2 IHd. \nsimpl; omega. \n(* 5 *) \neapply2 derive_abs.\ncut(derivation (removen (S k) (ty1 :: gamma)) t ty2); [auto| eapply2 IHd; omega].\n(* 4 *) \neapply2 derive_app. \neapply2 IHd1. assert(max (maxvar t) (maxvar u) >= maxvar t) by eapply2 max_is_max. omega. \neapply2 IHd2. assert(max (maxvar t) (maxvar u) >= maxvar u) by eapply2 max_is_max. omega. \n(* 3 *) \neapply2 derive_inst. \n(* 2 *) \neapply2 derive_gen1. rewrite map_removen. eapply2 IHd. \n(* 1 *) \neapply2 derive_push1. \nQed. \n\nLemma derivation_var : \nforall gamma t ty, derivation gamma t ty -> forall i, t = Ref i -> length gamma > i.\nProof. \nintros gamma t ty i; induction i; split_all; subst. \ninversion H1; subst. omega. \ninversion H0; subst.  assert(length gamma > i) by auto. omega. \nassert(length (map (lift 1) gamma) > i0) by auto. \nrewrite map_length in *. auto. \nQed.  \n\n\nLemma derive_via_op: \nforall gamma t ty, derivation gamma t ty -> \nforall o, t = Op o -> forall t1, derivation gamma t1 (opty o) -> derivation gamma t1 ty. \nProof. \nintros gamma t ty d; induction d; split_all; subst. \n(* 3 *) \napply derive_inst with ty1; auto. eapply2 IHd. \n(* 2 *)\neapply derive_gen1; auto. eapply2 IHd. \nreplace(opty o) with (lift_rec (opty o) 0 1) by (case o; auto). \nunfold lift; eapply2 lift_rec_ty_preserves_derive. \n(* 1 *) \napply derive_push1 with ty; auto. eapply2 IHd. \nQed.\n\n\nLemma strip_context: forall gamma t ty, derivation gamma t ty -> forall o, t = Op o -> derivation nil (Op o) ty. \nProof. \nintros gamma t ty d; induction d; split_all; invsub; subst. \neapply2 derive_inst. \neapply2 derive_push1. \nQed. \n\n\n", "meta": {"author": "Barry-Jay", "repo": "typed-lambdaFactor", "sha": "80f5ccf75903e9cad68f9c405bca492df1d107ed", "save_path": "github-repos/coq/Barry-Jay-typed-lambdaFactor", "path": "github-repos/coq/Barry-Jay-typed-lambdaFactor/typed-lambdaFactor-80f5ccf75903e9cad68f9c405bca492df1d107ed/type_derivation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.29605060278058815}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.msl.iter_sepcon.\n\nOpen Scope logic.\n\nLemma sepcon_pred_sepcon:\n forall {A B : Type} {ND: NatDed A} {SL: SepLog A}{CA: ClassicalSep A}\n  (f1 f2: B -> A) (P: B -> Prop),\n pred_sepcon f1 P * pred_sepcon f2 P = pred_sepcon (fun i => f1 i * f2 i) P.\nProof.\nintros.\nrewrite !pred_sepcon_eq.\napply pred_ext.\n-\nIntros l1 l2.\nnormalize.\nassert (Permutation l1 l2). {\napply NoDup_Permutation; auto.\nintros. rewrite H,H1. tauto.\n}\nrewrite <- (iter_sepcon_permutation f2 H3).\nExists l1.\nrewrite prop_true_andp by auto.\nclear - CA SL ND.\ninduction l1. simpl. rewrite emp_sepcon; auto.\nsimpl. rewrite !sepcon_assoc. apply sepcon_derives.\nauto. rewrite <- !sepcon_assoc. pull_left (f2 a).\nrewrite !sepcon_assoc.\napply sepcon_derives; auto.\n-\nIntros l.\nExists l l.\nrewrite !prop_true_andp by auto.\nclear H H0.\ninduction l. simpl. rewrite emp_sepcon; auto.\nsimpl. rewrite !sepcon_assoc. apply sepcon_derives.\nauto. rewrite <- !sepcon_assoc. pull_left (f2 a).\nrewrite !sepcon_assoc.\napply sepcon_derives; auto.\nQed.\n\nLemma pred_sepcon_derives:\n forall {A B : Type} {ND: NatDed A} {SL: SepLog A}\n  (f1 f2: B -> A) (P: B -> Prop),\n (forall i, P i -> (f1 i |-- f2 i)) ->\n (pred_sepcon f1 P |-- pred_sepcon f2 P).\nProof.\nintros.\nrewrite !pred_sepcon_eq.\nIntros al.\nExists al.\nrewrite prop_true_andp by auto.\napply iter_sepcon_derives.\nintros.\napply H.\nrewrite <- H0.\nauto.\nQed.\n\nLemma distribute_pred_sepcon:\n forall {A B: Type} {NA: NatDed A} {SA: SepLog A}{CA: ClassicalSep A}\n        (e: A) (f: B -> A) (P: B -> Prop),\n   (e |-- emp) -> (e |-- e * e) -> \n   (e * pred_sepcon f P |-- pred_sepcon (fun i => e * f i) P).\nProof.\nintros.\nrewrite !pred_sepcon_eq.\nIntros l; normalize; Exists l; rewrite prop_true_andp by auto;\nclear H1 H2 P.\ninduction l; simpl. rewrite sepcon_emp; auto.\neapply derives_trans; [apply sepcon_derives; [apply H0 | apply derives_refl ] | ].\nrewrite !sepcon_assoc.\napply sepcon_derives; auto.\nrewrite <- sepcon_assoc.\npull_left (f a).\nrewrite !sepcon_assoc.\napply sepcon_derives; auto.\nQed.\n\nLemma map_inj: forall {A}{B} (f: A -> B), \n   (forall u v, f u = f v -> u=v) ->\n   forall x y, \n   map f x = map f y -> x = y.\nProof.\ninduction x; destruct y; simpl; intros; try discriminate; auto.\ninv H0.\nf_equal; auto.\nQed.\n\nDefinition iota (n: Z) : list Z := map Z.of_nat (seq 0%nat (Z.to_nat n)).\n\nLemma Zlength_iota: forall t, 0 <= t -> Zlength (iota t) = t.\nProof.\nintros. unfold iota. rewrite Zlength_map. \nrewrite Zlength_length; auto. rewrite seq_length; auto.\nQed.\n\n#[export] Hint Rewrite Zlength_iota using lia : Zlength.\n\nLemma iota_S: forall n, 0 <= n -> iota (n+1) = iota n ++ [n].\nProof.\nintros.\nrewrite <- (Z2Nat.id n) by lia. clear.\nforget (Z.to_nat n) as i.\nunfold iota.\nrewrite Nat2Z.id.\nreplace (Z.to_nat (Z.of_nat i + 1)) with (S i) by lia.\nrewrite seq_S.\nrewrite map_app. auto.\nQed.\n\nLemma Znth_iota:\n forall i n, 0 <= i < n -> Znth i (iota n) = i.\nProof.\nintros.\npose proof (Zlength_iota n ltac:(lia)).\nunfold iota in *.\nrewrite Zlength_map in H0.\nrewrite <- (Z2Nat.id n) in H0|-* by lia.\nrewrite <- (Z2Nat.id i) by lia.\nassert (Z.to_nat i < Z.to_nat n)%nat by lia.\nforget (Z.to_nat i) as j.\nforget (Z.to_nat n) as m.\nunfold iota in *.\nrewrite Nat2Z.id  in *.\nrewrite Znth_map by lia.\nrewrite <- nth_Znth by lia.\nrewrite seq_nth by lia.\nlia.\nQed.\n\nLemma in_iota:\n   forall n x, In x (iota n) <-> 0 <= x < n.\n Proof. intros.\n destruct (zlt n 0).\n split; try lia. unfold iota. \n replace (Z.to_nat n) with 0%nat by lia. simpl. tauto.\n  rewrite <- (Z2Nat.id n) by lia.\n  induction (Z.to_nat n).\n  simpl. split; try lia.\n  rewrite inj_S. unfold Z.succ. rewrite iota_S by lia.\n  rewrite in_app.\n  split; intro.\n  destruct H.\n  rewrite IHn0 in H. lia.\n  hnf in H. destruct H; try contradiction.\n  lia.\n  destruct (zeq x (Z.of_nat n0)).\n  subst. right; hnf; auto.\n  left. rewrite IHn0. lia.\nQed.\n\nLemma NoDup_iota:\n forall n, NoDup (iota n).\nProof.\nintros.\n destruct (zlt n 0).\n unfold iota.  \n replace (Z.to_nat n) with 0%nat by lia. simpl. constructor.\n  rewrite <- (Z2Nat.id n) by lia. clear g.\n  induction (Z.to_nat n).\n  simpl. constructor.\n  rewrite inj_S. unfold Z.succ. rewrite iota_S by lia.\n rewrite NoDup_app_iff.\n split; auto.\n split. constructor. intro Hx; inv Hx. constructor.\n intros.\n intro. destruct H0.\n subst x.\n apply in_iota in H. lia. inv H0.\nQed.\n\nLemma Ers_not_bot: Ers <> Share.bot.\nProof.\nunfold Ers.\nintro.\napply lub_bot_e in H. destruct H.\napply juicy_mem.extern_retainer_neq_bot; auto.\nQed.\n\nDefinition comp_Ers : share := Share.comp Ers.\nLemma comp_Ers_not_bot: comp_Ers <> Share.bot.\nProof.\nunfold comp_Ers. unfold Ers.\nunfold extern_retainer.\nrewrite Share.demorgan1.\nintro.\napply sub_glb_bot with (a:= snd (Share.split Share.Rsh)) in H.\nrewrite Share.glb_commute in H.\napply sub_glb_bot with (a:= snd (Share.split Share.Rsh)) in H.\n-\nrewrite Share.glb_idem in H.\ndestruct (Share.split Share.Rsh) eqn:?H.\nsimpl in *. subst.\npose proof Share.split_nontrivial _ _ _ H0.\napply initialize.snd_split_fullshare_not_bot.\napply H. auto.\n-\napply sepalg.join_sub_trans with Share.Rsh.\nexists (fst (Share.split Share.Rsh)).\napply sepalg.join_comm.\napply split_join. destruct (Share.split Share.Rsh); simpl; auto.\napply leq_join_sub.\napply Share.ord_spec1.\nrewrite <- comp_Lsh_Rsh.\nrewrite <- Share.demorgan1.\nf_equal.\nsymmetry.\nrewrite <- (glb_split_x Share.Lsh).\napply Share.lub_absorb.\n-\nclear.\napply leq_join_sub.\nassert (Share.comp (fst (Share.split Share.Rsh)) = \n                 Share.lub Share.Lsh (snd (Share.split Share.Rsh))). {\n apply join_top_comp.\n split.\n rewrite Share.distrib1.\nreplace (Share.glb (fst (Share.split Share.Rsh)) Share.Lsh) with Share.bot.\nrewrite Share.lub_commute, Share.lub_bot.\napply glb_split.\nsymmetry.\nrewrite Share.glb_commute.\napply sub_glb_bot with (c:=Share.Rsh).\nexists (snd (Share.split Share.Rsh)).\napply split_join.\ndestruct (Share.split Share.Rsh); auto.\napply glb_Lsh_Rsh.\nrewrite Share.lub_commute.\nrewrite Share.lub_assoc.\nrewrite (Share.lub_commute (snd _)).\ndestruct (Share.split Share.Rsh) eqn:?H. simpl.\napply Share.split_together in H.\nrewrite H.\napply lub_Lsh_Rsh.\n}\nrewrite H.\napply Share.lub_upper2.\nQed.\n\nLemma join_Ers_comp_Ers: sepalg.join Ers comp_Ers Tsh.\nProof. apply join_comp_Tsh. Qed.\n#[export] Hint Resolve Ers_not_bot comp_Ers_not_bot join_Ers_comp_Ers : shares.\n\nDefinition Ers2 := snd (Share.split Share.Rsh).\nLemma Ers2_not_bot: Ers2 <> Share.bot. \nProof.\nunfold Ers2.\nintro.\ndestruct (Share.split Share.Rsh) eqn:?H.\nsimpl in *; subst.\napply Share.split_nontrivial in H0; auto.\nunfold Share.Rsh in *.\ndestruct (Share.split Share.top) eqn:?H.\nsimpl in *; subst.\napply Share.split_nontrivial in H; auto.\napply Share.nontrivial; auto.\nQed.\n\nLemma join_Ers_Ers2: sepalg.join Ers Ers2 Ews.\nProof.\nunfold Ers, Ers2, Ews.\nunfold extern_retainer.\nsplit.\nrewrite Share.glb_commute.\nrewrite Share.distrib1.\nmatch goal with |- Share.lub ?a ?b = _ => replace a with Share.bot; [replace b with Share.bot |] end.\napply Share.lub_bot.\nsymmetry.\nrewrite Share.glb_commute.\napply glb_split.\nsymmetry.\napply sub_glb_bot with (c:=Share.Lsh).\nexists (snd (Share.split Share.Lsh)).\napply sepalg.join_comm.\ndestruct (Share.split Share.Lsh) eqn:?H.\napply split_join in H. simpl. apply sepalg.join_comm; auto.\nrewrite Share.glb_commute.\napply sub_glb_bot with (c:=Share.Rsh).\nexists (fst (Share.split Share.Rsh)).\napply sepalg.join_comm.\ndestruct (Share.split Share.Rsh) eqn:?H.\napply split_join in H. auto.\napply glb_Lsh_Rsh.\nrewrite Share.lub_assoc.\nf_equal.\napply Share.split_together.\ndestruct (Share.split Share.Rsh); auto.\nQed.\n#[export] Hint Resolve Ers2_not_bot join_Ers_Ers2 : shares.\n\nLemma readable_Ers2: readable_share Ers2. \nProof.\nunfold Ers2.\nred.\nred.\nred.\nintro.\napply identity_share_bot in H.\nassert (Share.split Share.Rsh = (fst (Share.split Share.Rsh), snd (Share.split (Share.Rsh)))).\ndestruct (Share.split Share.Rsh); auto.\napply Share.split_together in H0.\nset (z := snd _) in H.\nrewrite <- H0 in H.\nsubst z.\nclear H0.\nrewrite Share.glb_commute in H.\nrewrite Share.distrib1 in H.\nrewrite Share.glb_commute in H.\nrewrite Share.glb_idem in H.\nrewrite glb_split in H.\nrewrite Share.lub_commute in H.\nrewrite Share.lub_bot in H.\ndestruct (Share.split Share.Rsh) eqn:?H.\napply Share.split_nontrivial in H0; auto.\napply juicy_mem.nonidentity_Rsh.\nrewrite H0; apply bot_identity.\nQed.\n#[export] Hint Resolve readable_Ers2 :core.\n\n\n\n", "meta": {"author": "VeriNum", "repo": "pardotprod", "sha": "5c8febd4e35a878a1824cedacd9cfc7d63610fb6", "save_path": "github-repos/coq/VeriNum-pardotprod", "path": "github-repos/coq/VeriNum-pardotprod/pardotprod-5c8febd4e35a878a1824cedacd9cfc7d63610fb6/basic_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.29605060278058815}}
{"text": "(* -*- mode: coq; mode: visual-line -*-  *)\n\nRequire Import Basics.\nRequire Import Algebra.ooGroup.\n\nLocal Open Scope path_scope.\n\n(** * Actions of oo-Groups *)\n\nDefinition ooAction (G : ooGroup)\n  := classifying_space G -> Type.\n\nDefinition action_space {G} : ooAction G -> Type\n  := fun X => X (point _).\n\nCoercion action_space : ooAction >-> Sortclass.\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/Algebra/ooAction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.29595855948374056}}
{"text": "\nRequire Import VST.floyd.proofauto.\nRequire Import common_predicates.\nRequire Import max.\nFrom SSL_VST Require Import core.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\n\n\n\n\n\n\n\n\n\n\n\n\nDefinition max_spec :=\n  DECLARE _max\n   WITH r: val, x: val, y: val\n   PRE [ (tptr (Tunion _sslval noattr)), tint, tint ]\n   PROP( is_pointer_or_null((r : val)); ssl_is_valid_int((x : val)); ssl_is_valid_int((y : val)) )\n   PARAMS(r; x; y)\n   SEP ((data_at Tsh (tarray (Tunion _sslval noattr) 1) [(inl ((Vint (Int.repr 0)) : val))] (r : val)))\n   POST[ tvoid ]\n   EX m: Z,\n   PROP( ((force_signed_int (x : val)) <= (m : Z)); ((force_signed_int (y : val)) <= (m : Z)) )\n   LOCAL()\n   SEP ((data_at Tsh (tarray (Tunion _sslval noattr) 1) [(inl ((Vint (Int.repr m)) : val))] (r : val))).\n\n\n\n\n\n\nDefinition Gprog : funspecs :=\n  ltac:(with_library prog [max_spec]).\n\n\nLemma body_max : semax_body Vprog Gprog f_max max_spec.\nProof.\n\nstart_function.\nssl_open_context.\nforward_if.\n\n - {\nassert_PROP (isptr r). { entailer!. }\nforward.\nforward; entailer!.\nExists (x : Z).\nssl_entailer.\n\n}\n - {\nassert_PROP (isptr r). { entailer!. }\nforward.\nforward; entailer!.\nExists (y : Z).\nssl_entailer.\n\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/benchmarks/ints/verif_max.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.29595855948374056}}
{"text": "(** Az earleyParser file változásai\n\n*)\n\nRequire Import List.\nImport ListNotations.\nRequire Import Psatz.\n\nRequire Import Earley.datastructures.\nRequire Import Earley.grammarDep.\n\n\nRequire Import Bool.Sumbool.\nRequire Import Arith.\nOpen Scope bool_scope.\n\nSection Earleycontext.\nVariable N T:Type.\nVariable G:grammar N T.\n\n(*TODO it should be visible from grammarDep*)\nInstance grammarruleInOpClass: InOpClass (rule N T) (grammar N T):=\n  fun r g => In r (grammarGetRules g).\n\nVariable i:list T. (*The input string*)\n\n(** A két összehasonlító függvény már nem bool adattipussal tér vissza hanem sumbool-al, ami tartalmassa a bizonyítékot is. A subool valójában vagy egy bizonyítékot ad vissza arra hogy igaz vagy egyet arra hogy hamis.\n\n*)\nVariable nEq: forall (n1 n2: N), {n1 = n2} + {n1 <> n2}.\nInstance nEqEqDecOpClass: EqDecOpClass N:=nEq.\nVariable tEq: forall (t1 t2: T), {t1 = t2} + {t1 <> t2}.\nInstance tEqEqDecOpClass: EqDecOpClass T:=tEq.\n\n(**\nHa nullázható a megadott nemterminális szimbólum, visszaad\negy ennek megfelelő szintaxisfát.\n*)\nVariable isNullable: forall (n:N), Maybe (forall i k, parseTreeDep N T G i k k n).\n\n\n(** Az earley item jelentősen megváltozott. Az általa tartalmazott szabály szét lett bontva 3 részre. Külön áll a bal oldal, a jobb oldal pont előtti és a pont utáni részei. Ezen túl tartalmazza az általa lefedett netminálisok listáját. Továbbra is tartalmazza az általa generált parsetreeket, most már parseForest típusban, és a származási set számát, vagy mászoóval, hogy hányadik szimbólumnál kezdődik az elemzés amit lefed az item. Tartalmaz még kettő bizonylatot, egyet arra hogy az általa lefedett terminálisok listája megegyezik az elemzendő listában levőkkel, az item kezdő pozíciótól indulva. A másik pedig azt bizonyítja, hogy az item által lefedett szabály (a 3 részből összeillesztve) része a nyelvtannak.\n\n*)\nInductive earlyItemD:=\n  eiC (n:N) (*lhs symbol*)\n  (rns: list (N+T)) (*Stuff before the dot*)\n  (pnd: list (N+T)) (*Stuff after the dot*)\n  (poss: list nat)\n  (epos: nat)\n  (pf: parseForestDep N T G i poss epos rns)\n  (pM: (ruleConstr n (rns++pnd)) ∊ G).\n\nNotation \"n → rns • pnd ⟨ poss , epos ⟩ pf , pM\" :=\n  (eiC n rns pnd poss epos pf pM)  (at level 60).\n\n\n\n\n(** Függvények az earley item különböző részeinek kiszedésére.\n\n*)\n\n\nDefinition eitGetRule (it:earlyItemD):= \n  let (n, rns, pnd, poss, epos, pf, pM):=it\n  in ruleConstr  n (rns++pnd).\n\nDefinition eitGetRuleLhs (it:earlyItemD):= \n  let (n, rns, pnd, poss, epos, pf, pM):=it in n.\n\n(**The position of the dot.*)\nDefinition eitGetPOD (it:earlyItemD):= \n  let (n, rns, pnd, poss, epos, pf, pM):=it in length rns.\n\nDefinition eitGetStartposition (it:earlyItemD):= \n  let (n, rns, pnd, poss, epos, pf, pM):=it in hd epos poss.\n\n(*?????*)\n(*Definition eitExtrCH (it:earlyItemD): sigT (fun ris: (list (list T)) => sigT (fun rns=> parseForestWithInput N T G ris rns)):= \n  let (_,ris,rns,pf,_,_,_,_):=it in existT _ ris (existT _ rns pf).\n*)\n\nDefinition eitGetPending (it:earlyItemD):= \n  let (n, rns, pnd, poss, epos, pf, pM):=it in pnd.\n\n(*\nDefinition eitExtrRis (it:earlyItemD):= \n  let (_,ris,_,_,_,_,_,_):=it in ris.*)\n\nDefinition eitGetEndPos (it:earlyItemD):= \n  let (n, rns, pnd, poss, epos, pf, pM):=it in epos.\n\n(** A befejezett earley set-ekhez hozzá került a set száma, és egy bizonyítás, hogy az általa lefedett terminálisok a kadik nál érnek véget.\n\n*)\n\nDefinition completedEarleySets := \n  list {k:nat & list {it:earlyItemD | eitGetEndPos it = k}}.\n\n(*\nInstance ruleEqDecOpClass: EqDecOpClass (rule N T).\nintros [n1 rh1] [n2 rh2].\ndestruct a.\nAdmitted.*)\n\nExisting Instance ruleEqDecOpClass.\n\nDefinition eiEq (ei1 ei2:earlyItemD): bool.\nrefine(\n  Nat.eqb (eitGetStartposition ei1) (eitGetStartposition ei2) &&\n  Nat.eqb (eitGetPOD ei1) (eitGetPOD ei2) &&\n  (if (eitGetRule ei1) =?= (eitGetRule ei2) then true else false)\n).\n(*Coq should be able to find it automatically!*)\neapply ruleEqDecOpClass; auto.\nDefined.\n\n(** Az éppen elemzett itemek listájához is hozzákerült ugyanaz mint a befejezettekhez.\n\n*)\n\nInductive earleySetUnderConstruction: nat->Type:=\n    sucC k (completed:(list {it:earlyItemD | eitGetEndPos it = k}))\n         (pending:(list {it:earlyItemD | eitGetEndPos it = k})):\n  earleySetUnderConstruction k.\n\nDefinition getNextUnprocessed k (s:earleySetUnderConstruction k):=\n  match s with\n    | sucC k c p =>\n    match p with \n      | nil => Nothing\n      | cons h _ => Just h\n    end\n  end.\n\nDefinition markAsCompleted k (s:earleySetUnderConstruction k):\n  earleySetUnderConstruction k:=\n  match s in earleySetUnderConstruction k0 return earleySetUnderConstruction k0 with\n    | sucC k c p =>\n    match p with \n      | nil => sucC k c p\n      | cons h t => sucC k (cons h c) t\n   end \n  end.\n\n\nFixpoint isItemInList k\n (i:earlyItemD) (items:list {it:earlyItemD | eitGetEndPos it = k}):bool :=\n  match items with \n    |cons (exist _ hd _) tl => \n      if eiEq hd i \n      then true\n      else isItemInList k i tl\n    | nil => false\n    end.\n\n(** Az insertIntoESC függvény az earley item mellé a szükséges bizonyítást is beleteszi a listába. Ezt bemenő paraméterként kapja meg.\n\n*)\n\nFixpoint insertIntoESC \n  k (e:earleySetUnderConstruction k) (ni:earlyItemD) (prf: eitGetEndPos ni = k):  \n      earleySetUnderConstruction k.\nrefine(\n    match e in earleySetUnderConstruction k0 return k=k0 -> earleySetUnderConstruction k0 with \n          | sucC k1 comp pend => fun heq =>\n            match (isItemInList k1 ni comp) , \n                  (isItemInList k1 ni pend) with \n              | false, false => sucC k1 comp (pend ++  [exist _ ni _])\n              | _,_ => sucC k1 comp pend\n            end\n    end eq_refl\n).\nrewrite <- heq.\nexact prf.\nDefined.\n\n(** Ez a függvény továbbra is a pont utáni első elemet olvassa ki, ami most a pont utáni szimbólumok listájának az első eleme. Hogyha nincs következő elem, bizonyítékot adunk vissza arra, hogy a szabálynak nincs több megvizsgálandü eleme.\n\n*)\nDefinition getNextSymbolFromEarleyItem (it:earlyItemD): (N+T) + {eitGetPending it = nil}.\nrefine (\n  (let (n, rns, pnd, poss, epos, pf, pM) as it0 return it = it0 -> _ := it in fun ieq =>\n      match pnd as pnd0 return pnd = pnd0 -> _ with \n        | nil => fun heq => inright _\n        | cons hd _ => fun heq => inleft hd\n      end eq_refl) \n  eq_refl\n).\ntry rewrite ieq. (*needed for version 8.6 coq*)\nsimpl.\nexact heq.\nDefined.\n\n(** Ez a függvény a befejezett earley setek közül visszaadja a k-adikat.\n\n*)\n\nFixpoint getKfromCes k (ces:completedEarleySets): list {it:earlyItemD | eitGetEndPos it = k}.\nrefine (\n  match ces with\n    | nil=> nil\n    | cons (existT _ k0 hd) tl => \n    match Nat.eq_dec k k0  with \n      | left _ => _\n      | right _ => getKfromCes k tl\n    end\n  end\n).\nrewrite e.\nexact hd.\nDefined.\n\n(** A lookup a megfelelő itemek mellé tesz két bizonyítékot is, arra hogy a következő szimbólum valóban a megfelelő nemterminális, ittelve a bizonyíték hogy az adott setnél van a feldolgozott terminálisok vége.\n*)\n\n\nFixpoint lookupAux (pos:nat) (eil:list {it:earlyItemD | eitGetEndPos it = pos}) (B:N) {struct eil}:\n(list ({it : earlyItemD | getNextSymbolFromEarleyItem it = inleft (inl B) /\\ eitGetEndPos it = pos})).\nrefine(\n  match eil with\n    | cons (exist _ hd prf) tl => \n    match getNextSymbolFromEarleyItem hd as pr \n    return getNextSymbolFromEarleyItem hd = pr -> _ \n    with\n      | inleft (inl x) => fun heq => if nEq x B then \n    \n        cons (exist _ hd _) (lookupAux pos tl B)\n   else lookupAux pos tl B \n      | _ => fun heq => lookupAux pos tl B\n    end eq_refl\n    | nil => nil\n  end\n).\nsplit.\nrewrite <- e.\nexact heq.\nexact prf.\nDefined.\n\n\nFixpoint lookup (ces:completedEarleySets) (B:N) (pos:nat):\n(list ({it : earlyItemD | getNextSymbolFromEarleyItem it = inleft (inl B) /\\ eitGetEndPos it = pos})).\nrefine (\n  match ces with\n    | nil => nil\n    | cons (existT _ k hd) tl => \n    match Nat.eq_dec k pos with \n      | left _ =>_ \n      | right _ => lookup tl B pos\n    end\n  end\n).\nrewrite <- e.\nexact (lookupAux k hd B).\nDefined.\n\n(** A part of input függvény bool helyett sumbool típust ad vissza.\n\n*)\n\n\nFixpoint AtPosDec (t:T) (ii:list T) (k:nat):\n{AtPos T t ii k}+{~AtPos T t ii k}.\nrefine(\n  match k as k0, ii as ii0\n  return {AtPos T t ii0 k0}+{~AtPos T t ii0 k0}\n  with \n    | S n, cons hd tl =>\n        if AtPosDec t tl n then left _ else right _\n    | O, hd :: tl => if tEq hd t then left _ else right _\n    | _,_ => right _\n    end\n).\nintros H.\ninversion H.\nrewrite e.\napply atposHead.\nintros H.\ninversion H.\ncongruence.\nintros H.\ninversion H.\napply (atposTail _ _ _ _ _ a).\nintros H.\ninversion H.\ncongruence.\nDefined.\n\n\n\n(** A dotacvancer is jelentős változásokon ment keresztül, az earley item változtatása miatt. A pont mozgatásához hozzá kell adnunk a lefedett terminálisokhoz az újonnan lefedetteket, és szolgáltatni kell az earley itemhez tartozó kettő bizonyítékot, illetve a parseforesthez hozzá kell tenni a a megfelelő szintaxisfát. Ezen túl a pont mozgatása is megváltozott, hiszen nem egy szémot kell növelni, hanem áttenni a szabály még nem elemzett részének az első elemét a már elemzettek végére. Bejövő paraméterként kapjuk a lefedett terminálisok listáját, a nemterminálist amin túlmozgatjuk a pontot, a szintaxisfát ami ábrázolja a lefedett terminálisokat, az itemet amiben mozgatjuk a pontot. Illetve bizonyítékot hogy tényleg a megfelelő nemterminális áll a pont után, és hogy a lefedett terminálisok, a megfelelő pozícióban részei az elemzendő szövegnek.\n\n*)\nDefinition dotAdvancerN\n  (b1 e1: nat) (*The input, covered by the new part*)\n  (n1:N)           (*Nonterminal symbol, were the dot is advanced*)\n  (ch:parseTreeDep N T G i b1 e1 n1)\n                  (*The parsetree that parses the input*)\n  (it:earlyItemD) (*Earley item subject to dot advacement*)\n  (nip : getNextSymbolFromEarleyItem it = inleft (inl n1))\n             (*Proof that really there is a b after the dot in it*)\n  (iinp : (eitGetEndPos it) = b1)\n             (*Proof, thet input really is part of the whole\n                 imput at the apropriate position*)\n    : earlyItemD. (*Return it modified with the dot advanced\n                    one position*)\nrefine ( \n  match it as k\n  return it = k ->\n         getNextSymbolFromEarleyItem k = inleft (inl n1)->\n         earlyItemD\n  with n → rns • pnd ⟨ poss , epos ⟩ pf, pM => fun ieq neq => \n    match pnd as pnd0\n    return pnd = pnd0 ->\n           forall pM2,\n           getNextSymbolFromEarleyItem \n             (n → rns • pnd0 ⟨ poss , epos ⟩ pf, pM2) =\n           inleft (inl n1) ->\n           earlyItemD\n    with \n      | nil => fun heq hpm neq2 => it\n      | cons hd tl => fun heq hpm neq2 =>\n        n → rns++[hd] • tl ⟨ poss++[epos] , e1 ⟩ _ , _\n    end eq_refl pM neq\n  end eq_refl nip\n\n\n).\nsimpl in neq2.\nassert (be : hd = inl n1).\ninjection neq2.\nauto.\nrewrite be.\n\nrewrite ieq in iinp.\ncbn in iinp.\nrewrite <- iinp in ch.\nexact (ptSnocN _ _ _ _ _ _ _ _ _ pf ch).\n\nrewrite <- app_assoc.\napply hpm.\nDefined.\n\n\nDefinition parseTreeFromCompletedEarlyItem bpos epos root\n    (it:earlyItemD)\n    (pendIsNull: eitGetPending it = nil)\n    (bEq: bpos = eitGetStartposition it)\n    (eEq: epos = eitGetEndPos it)\n    (rootEq: root = eitGetRuleLhs it):\n    parseTreeDep N T G i bpos epos root.\nrefine(\n  match it as it0\n  return it = it0 -> _\n  with n → rns • pnd ⟨ poss , epos ⟩ pf, pM => fun Heq =>\n     _\n  end eq_refl\n).\nrewrite Heq in *.\ncbn in eEq, bEq, rootEq, pendIsNull.\nclear Heq.\nrewrite pendIsNull in pM.\nrewrite eEq,  rootEq.\nrewrite app_nil_r in pM.\n\neapply (ptNode G i n rns bpos poss epos pf pM ?[pEqb]).\n[pEqb]:{\n  destruct poss; cbn in *; congruence.\n}\nDefined.\n\n\n(** Egy bizonyatott tétel arra, hogy ha a a dotadvancert nullázható nemterminálisra használjuk, ahol a lefedett terminálisok listája az üres lista, akkor az eddig lefedett terminálisok listájának a vége nem változik.\n\n*)\n\nTheorem dotadvancerNul:\n forall bpos n x ei heq prf, eitGetEndPos (dotAdvancerN bpos bpos n x ei heq prf) = eitGetEndPos ei.\nProof.\n  intros bpos n x ei heq prf.\n  destruct ei.\n  simpl.\n  destruct pnd.\n  simpl.\n  reflexivity.\n  simpl.\n  simpl in prf.\n  auto.\nQed.\n\n(** Egy bebizonyított tétel, hogy a dotadvancer haszálata után, az utolsó lefedett terminális pozíciója megegyezik az item által utoljára lefedett szimbóluméval\n\n*)\n(*\neitGetEndPos\n  (dotAdvancerN x k inn (ptNode G i x k inn irns istart irnp ipf ?Goal)\n     hd ?Goal0 ?Goal1) = k\n*)\nTheorem dotadvancerXk: forall hd x k inn pt p0 p1 \n  (prx:eitGetEndPos hd = x)\n  (pnn: eitGetPending hd <> nil), \neitGetEndPos (dotAdvancerN x k inn pt hd p0 p1) = k.\nProof.\n  intros.\n  destruct hd.\n  simpl.\n  destruct pnd.\n  simpl in *.\n  discriminate.\n  simpl.\n  simpl in prx.\n  auto.\nQed.\n\n(** A predictor továbbra is a megfelelő earley itemeket fogja létrehozni, de szolgáltatnia kell bizonyítékokat. A bizonyíték hogy az elemzett terminálisok vége a egfelelő helyen van egyszerű, hiszen a jelen setben kezdődik és a vége is itt ban mert még nem elemeztünk semmit. Az eddig lefedett terminálisok listéja az üreslista, mindenképpen része az eredeti listának. A bizonyítékot hogy a szabály része a nyelvtannak a gExtrRulD függvény szolgáltatja. Az üres szabályokat itt isfigyelembevesszük.\n\n*)\n\nFixpoint predictorAux (k:nat) (n:N) (r:list({s: rule N T | s ∊ G} ))\n    (s_curr:earleySetUnderConstruction k) : earleySetUnderConstruction k.\nrefine (\n  match r with \n    | (exist _ head headProof) :: tail => \n    match (lhs head) =?= n with\n      | left prf => predictorAux k n tail\n            (insertIntoESC k s_curr\n              (*eiC n k nil nil (pfNil N T G i k) (rhs head) _ *)\n              (n → nil • (rhs head) ⟨nil, k⟩ (pfNil N T G i k), _)\n              eq_refl)\n      | right prf => predictorAux k n tail s_curr\n    end\n    | nil => s_curr\n  end\n).\nsimpl.\nrewrite <- prf.\nrewrite ruleReassemble.\nexact headProof.\nDefined.\n\nFixpoint predictor (k:nat) (ei:earlyItemD)\n    (s_curr:earleySetUnderConstruction k) (prf: eitGetEndPos ei = k):\n      earleySetUnderConstruction k.\nrefine(\n       match (getNextSymbolFromEarleyItem ei) as eii \n       return getNextSymbolFromEarleyItem ei = eii -> _  \n       with\n         | inleft (inl n) => fun heq =>\n         let sNext := predictorAux k n\n             (listToMembershipProofList (grammarGetRules G))\n             s_curr in\n         match isNullable n with\n           | Just x => insertIntoESC k sNext\n             (dotAdvancerN k k n\n                 (x i k) ei heq prf) _ \n           | Nothing => sNext\n         end\n         | _ => fun heq => s_curr\n       end eq_refl \n).\nrewrite <- prf.\napply dotadvancerNul.\nDefined.\n\n(** A scannernek is nyújtania kell bizonyos bizonyítékokat. Bizonyatani kell hogy amikor a scanner előremozgatja a pontot egy itemben, az item által lefedett terminálisok listája egyel hosszabb lesz, az új elemmel együtt is része az eredeti terminálisok listájának, és a szabály továbbra is része a nyelvtannak. \n\n*)\n\nDefinition scanner (k:nat) (it:earlyItemD)\n  (s_next:earleySetUnderConstruction (S k)) \n   (kOneAhead: (eitGetEndPos it) = k)\n  : earleySetUnderConstruction (S k).\nrefine (\n    match it as iit return it = iit -> _ \n    with n → rns • pnd ⟨poss, epos⟩ pf , pM => fun ieq => \n      match pnd as pnd0 return pnd = pnd0 -> _ with\n        | cons (inr t) tl => fun heq =>\n        match (AtPosDec t i k) with \n          | left p => \n            (insertIntoESC (S k) s_next\n              (n → (rns ++ [inr t]) • tl ⟨poss++[epos], epos+1⟩\n                (ptSnocT _ _ _ i _  epos _ pf t _) , _)\n            _)\n       | _ => s_next\n     end\n    | _ => fun heq => s_next\n    end eq_refl\n    end eq_refl\n).\nUnshelve.\nsimpl.\nrewrite ieq in kOneAhead.\nsimpl in kOneAhead.\nlia.\nrewrite ieq in kOneAhead.\nsimpl in kOneAhead.\nrewrite kOneAhead.\nexact p.\nrewrite <- app_assoc.\nsimpl.\nrewrite <- heq.\nexact pM.\nDefined.\n\n\n\n(** A transferItems a lookup által visszaadott listának az elemeire meghívja a dotadvancert, és beírja őket a jelenlegi setbe. Ehez előállítjuk a bizonyítékot az insert függvény számára, hogy megfelelő helyen ér véget a lefedett terminálisok listája, ehez felhasználjuk a bemenetként megadott bizonyítékokat a befejezett szabály által lefedett szimbólumok kezdő és vég pontjára, illetve a dotadvancerXk tételt. A dotadvancernek szükséges bizonítékokat előállítjuk az itemben tárolt bizonyatékokból, és parsetreeeben térolt bizonyítékokat is, a befejezett earley itemben levő bizonyítékokkal, valamint inputként megkapjuk hogy a beffejezett szabály bal oldala megegyezik a B paraméterrel, és nincs több vizsgálatlan elem a szabályban.\n\n*)\n\n\nFixpoint transferItems (x:nat) (k:nat) (B:N) (it:earlyItemD)\n           (pendIsNull: eitGetPending it = nil)\n           (beginIsX: eitGetStartposition it = x)\n           (endIsK : eitGetEndPos it = k)\n           (lhsIsB : (eitGetRuleLhs it) = B)\n           (source: list {it : earlyItemD |\n               getNextSymbolFromEarleyItem it = inleft (inl B)\n               /\\  eitGetEndPos it = x} ) \n           (target: earleySetUnderConstruction k):\n           earleySetUnderConstruction k.\nrefine(\nmatch it as iit\nreturn it = iit -> earleySetUnderConstruction k\nwith\n  eiC inn istart irns irnp ipf ipnd ipM =>\n   fun ieq =>\n  match source as ssource return source = ssource -> _ with\n    | nil => fun _ =>target\n    | cons (exist _ hd (conj prf1 prf2)) tl => fun seq =>\n        transferItems  x k B it pendIsNull beginIsX endIsK lhsIsB tl\n        (insertIntoESC k target \n          (\n             dotAdvancerN x k B \n                (parseTreeFromCompletedEarlyItem _ _ _ it _ _ _ _)\n                 hd _ _\n          )\n        _)\n  end eq_refl\nend eq_refl\n).\n\neapply (dotadvancerXk _ x k).\nexact prf2.\ndestruct hd.\ndestruct pnd;\ncbn in prf1 |- *;\ncongruence.\nUnshelve.\nall:firstorder.\nDefined.\n\n\n(** A completernek nem sok feladata maradt, meghívja a lookup függvényt, majd az általa visszaadott értékkel, és további megfleleő paraméterekkel a transferItems függvényt. Ehhez a bizonyítékokat a kezdő pozícióra és a B paraméterre vonatkozókhoz elég egy egyszerű reflexivitási tétel, hiszen pont onnan olvastuk ki őket amivel meg kell egyeznie, a másik kettőt pedig beneő paraméterként fogja megkapni.\n\n*)\n\nDefinition completer (k:nat) (it:earlyItemD)\n   (s_completed: completedEarleySets)\n   (s_curr:earleySetUnderConstruction k) \n   (pendIsNull: eitGetPending it = nil)\n   (endPosIsK: eitGetEndPos it = k):\n      earleySetUnderConstruction k.\nrefine(\n  let source := lookup s_completed ((eitGetRuleLhs it))\n                       (eitGetStartposition it) in \n  transferItems (eitGetStartposition it) k ((eitGetRuleLhs it)) \n  it pendIsNull eq_refl endPosIsK eq_refl source s_curr\n\n).\nDefined.\n\n\n(** A findRules tovébbra is azokat a szabályokat keresi, aminek a kezdőszimbólum áll a bal oldalán. A gExtrRul függvény által visszaadott listának minden eleméhez tartozik egy bbizonyítás, hogy beletartozik a nyelvtanba. Mindig abba a felébe kell belenézni amiben a szabály van, de az eredmény listába a teljes elemeket kell beletenni.\n\n*)\nDefinition findRules (n:N) : list {a : rule N T | In a (grammarGetRules G)}:= \n  let lp := (listToMembershipProofList (grammarGetRules G)) in \n  filter  (fun '(exist _ r _) => if nEq n (lhs r) then true else false ) lp.\n\n(** A oneSet függvény nem sokat változott, az alapvető működése ugyanaz, de a meghívott fügvényekhez bizonyítékokat kell adn. A predictornak és a csannernek csak egy bizonyíték kell, a vizsgált earley item által lefedett terminálisok végéről, ezt ki tudjuk olvasni az itemből. A completernek ugyanez mellé kell mégegy bizonyíték, ami azt igazolja, hogy nincs több elem a vizsgálatra váró részében, ez a match-ből ered, abban az ágában hívjuk meg, amikor nem tudtunk beolvasni több elemet a listából.\n\n*)\n\nFixpoint oneSet (k:nat)\n  (s_completed: completedEarleySets)\n  (s_curr:earleySetUnderConstruction k) \n  (s_next:earleySetUnderConstruction (S k))\n  (num:nat): \n  completedEarleySets * earleySetUnderConstruction (S k).\nrefine(\n  match num , getNextUnprocessed k s_curr with \n    | S x, Just (exist _ it prf) =>\n    match getNextSymbolFromEarleyItem it with\n      | inleft nt => \n      match nt with\n        | inl n => oneSet k\n           s_completed\n          (markAsCompleted k (predictor k it s_curr prf))\n          s_next x\n        | inr t =>\n\n          oneSet k s_completed\n          (markAsCompleted k s_curr)\n          (scanner k it s_next prf) \n          x\n      end\n      | inright heq =>\n          oneSet k s_completed\n          (markAsCompleted k (completer k it s_completed s_curr heq prf))\n          s_next x\n    end\n    | _,_ => (s_completed++[(let (k0,A,_):= s_curr in existT _ k0 A)],s_next)\n  end\n).\nDefined.\n\n\nFixpoint ParserAux \n  (k:nat)\n  (s_completed: completedEarleySets)\n  (s_curr:earleySetUnderConstruction k) \n  (s_next:earleySetUnderConstruction (S k))\n  (lng fuel:nat):\n  completedEarleySets:=\n    match lng with \n      | S x => \n          match (oneSet k s_completed \n          s_curr s_next fuel) with\n            | (a,b) => ParserAux (S k) a b\n                              (sucC (S (S k)) nil nil) x fuel\n          end\n      |_ => s_completed\n  end.\n\n(**Az isNil megállapítja, hogy a megadott lista üres-e. A visszatérési érték sumbool.\n\n*)\n\nDefinition isNil {A:Type} (a:list A): {a = nil}+{a <> nil}.\nrefine(\n  match a as aa return {aa = nil}+{aa <> nil} with \n    | nil => left eq_refl\n    | _ => right _\n  end\n).\ndiscriminate.\nDefined.\n\n(** A proofFilter a filterhez hasonlóan működik, szüksége van bemeneti paraméterként egy listára és egy függvényre amit a lista elemeire meghívva egy sumbool értéket ad vissza. Amire az érték igaz, azt beletesszük a visszatérési listába, a sumboolban levő bizonyítékkal együtt.\n\n*)\n\nFixpoint proofFilter {A:Type} {P Q : A -> Prop} (f: forall a:A , {P a} + {Q a}) (l: list A): list {a:A | P a}:=\n  match l with\n    | nil => nil\n    | cons hd tl => \n      match (f hd) with \n         | left p => exist _ hd p :: (proofFilter f tl) \n         | _ => (proofFilter f tl)\n      end\n    end.\n\n(** A makeces függvény egy új függvény, ez fogha a parserAuxot meghívni, ez állítja elő a teljes befejezett earley seteket. A makeces állítja itt elő a szükséges üres setek listáját, meghívja a findrulest, és a visszaadott szabályokhoz earley itemeket csinál, üres parseforestekkel, és bizonyításokkal. A bizonyítások egyszerüek, minden feldolgozott terminális lista üres, tehét az eleje és a vége is 0, a szabály nyelvtanbatartozását pedig bizonyítja a findRules függvény.\n\n*)\n\nDefinition makeCes (fuel:nat): completedEarleySets.\nrefine (\n\n  ParserAux 0 nil \n    (sucC O nil \n        (map (fun '(exist _ r p) => exist _ \n    ((lhs r) → nil • (rhs r) ⟨nil, 0⟩ (pfNil N T G i 0) , _)\n            _)\n        (findRules (grammarGetStart G)))\n    )\n    (sucC 1 nil nil) (length i+1) fuel\n).\nsimpl.\nreflexivity.\nUnshelve.\nsimpl.\ncbn in p.\nrewrite ruleReassemble.\nexact p.\nDefined.\n\n\n(** A parser függvény meghívja a makeCes függvényt, majd az utolsó setből kiválasztja az early itemet ami megfelel a hátom kritériumnak, a proofFilterrel. A szabály végén van a pont, erre használjuk az isNil függvényt, a kezdőszimbólum a baloldala, és az nulladik setben kezdődött. Ha nem találunk ilyen semmti adunk vissza, ha találunk ilyeneket, akkor az elsőt, kiválasztjuk és visszaadjuk parseTreeDepWithInput-ot.\n\n*)\n\nDefinition Parser \n  (fuel:nat): Maybe (parseTreeDep N T G i 0 (length i) (grammarGetStart G)).\nrefine(\n  let ces := makeCes fuel\n    in let finalItemE := getKfromCes (length i) ces in \n    \n    let ptree := proofFilter (fun it => \n      sumbool_and _ _ _ _ (sumbool_and _ _ _ _ (nEq (lhs (eitGetRule (proj1_sig it))) (grammarGetStart G) ) \n\n      (isNil (eitGetPending (proj1_sig it)))) \n      (Nat.eq_dec (eitGetStartposition (proj1_sig it)) O)) finalItemE \n    in match ptree with\n         | nil => Nothing\n         | cons (exist _ hd hdprf) _ => \n         match hd as hhd return hd = hhd -> _ with\n           | exist _ e prf => fun hdeq =>\n           match e as ee return e = ee -> _ with\n             | (*eiC n bpos rns rnp pf pnd pM =>*)\n               n → rns • pnd ⟨poss, epos⟩ pf , pM =>\n\n\n fun heq => Just _ \n           end eq_refl\n         end eq_refl\n       end\n\n).\nclear ptree.\n\n\nrewrite hdeq in hdprf.\nsimpl in hdprf.\nclear hdeq.\nrewrite heq in prf.\nsimpl in prf.\nrewrite heq in hdprf.\nsimpl in hdprf.\ndestruct hdprf as [[hdprf1 hdprf2] hdprf3].\nclear heq.\nrewrite <- prf.\n(*rewrite hdprf3 in pf |- *.*)\neapply ptNode.\napply pf.\nrewrite hdprf2 in pM.\nrewrite <- app_nil_end in pM.\nrewrite <- hdprf1.\napply pM.\ndestruct poss; cbn in *; congruence.\nDefined.\n\n\nEnd Earleycontext.\n\nPrint Assumptions Parser.\n(*Arguments eitGetRule [N T] _.\nArguments eitGetPOD [N T] _.\nArguments eitExtrSP [N T] _.\nArguments getNextUnprocessed [N T] _.\nArguments insertIntoESC [N T] _ _ _ _.\nArguments getNextSymbolFromEarleyItem [N T] _.\nArguments predictor [N T] _ _ _ _ _ _.\nArguments scanner [N T] _ _ _ _ _ _.\n*)\n", "meta": {"author": "bodri5", "repo": "EarleyParserInCoqPublic", "sha": "bc9ed938f5b2b23cb96bd595f75c8998d1ff5481", "save_path": "github-repos/coq/bodri5-EarleyParserInCoqPublic", "path": "github-repos/coq/bodri5-EarleyParserInCoqPublic/EarleyParserInCoqPublic-bc9ed938f5b2b23cb96bd595f75c8998d1ff5481/src/earleyParserDep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2959585528883825}}
{"text": "\nRequire Import LibTactics.\nRequire Import Metalib.Metatheory.\n\nRequire Import\n        syntax_ott\n        Infrastructure\n        Target_Adequacy\n        Logical_Relation_Def\n        Logical_Relation_Infrastructure\n        Target_Safety\n        Normalize.\n\n\nLemma disjoint_rel_v : forall A1 A2 v1 v2,\n    disjoint A1 A2 ->\n    nil |= v1 ~: (|A1|) ->\n    nil |= v2 ~: (|A2|) ->\n    value v1 ->\n    value v2 ->\n    rel_v (|A1|) (|A2|) v1 v2.\nProof.\n  introv Dis. gen v1 v2.\n  induction Dis; introv Ty1 Ty2 Val1 Val2; try solve [simpls*].\n\n  apply~ rel_v_unit.\n  apply~ rel_v_unit2.\n\n  simpls.\n  splits*.\n  introv Rel.\n  lets [? ?] : rel_v_well_type Rel.\n  assert (HH1 : nil |= (trm_app v1 a1) ~: | A2 |) by autos*.\n  assert (HH2 : nil |= (trm_app v2 a2) ~: | B2 |) by autos*.\n  lets (v3 & ? & Red1): normalization HH1.\n  lets (v3' & ? & Red2): normalization HH2.\n  lets* : preservation_multi_step Red1.\n  lets* : preservation_multi_step Red2.\n  exists* v3 v3'.\n\n  lets* (v1' & v2' & ? & ? & ?) : prod_canonical Ty1.\n  substs.\n  inverts Ty1.\n  apply rel_v_proj1. splits*.\n\n  lets* (v1' & v2' & ? & ? & ?) : prod_canonical Ty2.\n  substs.\n  inverts Ty2.\n  apply rel_v_proj2. splits*.\n\n\n  (* recrds *)\n  simpls.\n  splits*.\n  lets* (v1' & ?): rcd_canonical Val1 Ty1.\n  lets* (v2' & ?): rcd_canonical Val2 Ty2.\n  substs.\n  case_if*.\n  inverts Val1.\n  inverts Val2.\n  inverts Ty1.\n  inverts Ty2.\n  exists~ v1' v2'.\n  splits*.\n  simpls.\n  splits*.\n  case_if*.\nQed.\n\n\nLemma disjoint_rel_e_open : forall G1 G2 t1 t2 T1 T2,\n    G1 |= t1 ~: | T1 | ->\n    G2 |= t2 ~: | T2 | ->\n    disjoint T1 T2 ->\n    rel_e_open G1 G2 t1 t2 (| T1 |)  (| T2 |).\nProof.\n  introv Ty1 Ty2 Dis.\n  splits*.\n  introv GG.\n  lets (HH1 & HH2): bind_close  Ty1 Ty2 GG.\n  lets (v1 & ? & ?): normalization HH1.\n  lets (v2 & ? & ?): normalization HH2.\n  lets* : preservation_multi_step H0.\n  lets* : preservation_multi_step H2.\n  splits*.\n  exists~ v1 v2.\n  splits*.\n  apply~ disjoint_rel_v.\nQed.\n\n\n\n\nLemma compat_var : forall G1 G2 x A1 A2,\n    uniq G1 -> uniq G2 -> binds x A1 G1 -> binds x A2 G2 ->\n    rel_e_open G1 G2 (trm_var_f x) (trm_var_f x) A1 A2.\nProof.\n  intros.\n  unfolds.\n  splits*.\n  introv GG.\n  (* gen A1 A2. *)\n  induction GG.\n  invert H1.\n\n  simpls.\n  lets [[? [? ?]]|[? ?]] : binds_cons_uniq_1 H H1; substs;\n    lets [[? [? ?]]|[? ?]] : binds_cons_uniq_1 H0 H2; substs; tryfalse; case_if*.\n\n  lets* [? ?]: rel_v_well_type H5.\n  repeat rewrite* bind_value; try (sapply* value_no_fv).\n  apply~ rel_v_in_rel_e.\nQed.\n\n\nLemma compat_unit1 : forall G1 G2 t T,\n    G2 |= t ~: T -> uniq G1 -> rel_e_open G1 G2 trm_unit t a_unit T.\nProof.\n  introv H ?.\n  unfolds.\n  splits*.\n  introv GG.\n  assert (HH : G1 |= trm_unit ~: a_unit) by auto.\n  lets (? & HH1): bind_close HH H GG.\n  lets (v & ? & H3): normalization HH1.\n  lets : preservation_multi_step HH1 H3.\n  rewrite* bind_value; try solve [simpl; fsetdec].\n  splits*.\n  exists trm_unit v.\n  splits*.\n  apply~ rel_v_unit.\nQed.\n\n\nLemma compat_unit2 : forall G1 G2 t T,\n    G2 |= t ~: T -> uniq G1 -> rel_e_open G2 G1 t trm_unit T a_unit.\nProof.\n  introv H ?.\n  unfolds.\n  splits*.\n  introv GG.\n  assert (HH : G1 |= trm_unit ~: a_unit) by auto.\n  lets (HH1 & ?): bind_close H HH GG.\n  lets (v & ? & H3): normalization HH1.\n  lets : preservation_multi_step HH1 H3.\n  (* rewrite* bind_value; try solve [simpl; fsetdec]. *)\n  splits*.\n  exists v trm_unit.\n  splits*.\n  rewrite* bind_value; try solve [simpl; fsetdec].\n  apply~ rel_v_unit2.\nQed.\n\n\nLemma compat_int : forall G i,\n    uniq G -> rel_e_open G G (trm_lit i) (trm_lit i) a_nat a_nat.\nProof.\n  intros.\n  unfolds.\n  splits*.\n  introv GG.\n  repeat rewrite* bind_value; try solve [simpl; fsetdec].\n  apply~ rel_v_in_rel_e.\n  splits*.\nQed.\n\nLemma compat_app : forall G1 G2 t1 t2 t3 t4 T1 T2 T1' T2',\n    rel_e_open G1 G2 t1 t2 (a_arrow T1 T1') (a_arrow T2 T2') ->\n    rel_e_open G1 G2 t3 t4 T1 T2 ->\n    rel_e_open G1 G2 (trm_app t1 t3) (trm_app t2 t4) T1' T2'.\nProof.\n  introv Rel1 Rel2.\n  destruct Rel1 as (HH1 & HH2 & Rel1).\n  destruct Rel2 as (HH3 & HH4 & Rel2).\n  splits*.\n  introv GG.\n  lets Rel1' : Rel1 GG.\n  lets Rel2' : Rel2 GG.\n  repeat rewrite bind_app.\n  destruct Rel1' as (Rel1' & ? & ?).\n  destruct Rel1' as (v1 & v1' & ? & ? & Red1 & Red1' & Rel1').\n  destruct Rel2' as (Rel2' & ? & ?).\n  destruct Rel2' as (v2 & v2' & ? & ? & Red2 & Red2' & Rel2').\n  lets [? ?]: bind_close HH1 HH2 GG.\n  lets [? ?]: bind_close HH3 HH4 GG.\n  apply rel_e_convr with (t' := trm_app v1' v2'); auto_star.\n  apply rel_e_convl with (t := trm_app v1 v2); auto_star.\n  destruct Rel1' as (? & ? & ? & ? & Rel1').\n  lets [? ?]: bind_close HH3 HH4 GG.\n  lets* : preservation_multi_step Red2.\n  lets* : preservation_multi_step Red2'.\n  forwards * : Rel1' Rel2'.\n\n  splits*.\n  apply star_trans with (b := trm_app v1 (bind g1 t3)).\n  apply~ multi_red_app2.\n  apply~ multi_red_app.\n  apply star_trans with (b := trm_app v1' (bind g2 t4)).\n  apply~ multi_red_app2.\n  apply~ multi_red_app.\nQed.\n\n\nLemma compat_pair1 : forall G1 G2 T1 T2 T3 t1 t2 t3,\n    rel_e_open G1 G2  (trm_pair t1 t2) t3 (a_prod T1 T2) T3 <->\n    rel_e_open G1 G2 t1 t3 T1 T3 /\\\n    rel_e_open G1 G2 t2 t3 T2 T3.\nProof.\n  intros.\n  splits.\n  introv H.\n\n  - Case \"->\".\n    destruct H as (H & ? & ?).\n    splits.\n\n    inverts H.\n    splits*.\n    introv GG.\n    lets : H1 GG.\n    rewrite bind_pair in H.\n    destruct H as (HH & Ty1 & Ty2).\n    inverts Ty1.\n    lets* (v1 & ? & ?): normalization H5.\n    lets* (vv & ? & ?): normalization Ty2.\n    lets* (v2 & ? & ?): normalization H9.\n    destruct HH as (vv1 & ? & ? & ? & ? & ? & Imp).\n    lets (? & ?) : rel_v_well_type Imp.\n    lets* (v1' & v2' & ? & ? & ?) : prod_canonical H15.\n    substs.\n    assert (trm_pair (bind g1 t1) (bind g1 t2) ->* trm_pair v1 v2).\n    sapply* multi_red_pair.\n    lets* : value_unique H13 H19.\n    inverts H20.\n    apply rel_v_proj1 in Imp.\n    destruct Imp.\n    my_simplfier.\n    splits*.\n    exists v1 vv.\n    splits*.\n\n    inverts H.\n    splits*.\n    introv GG.\n    lets : H1 GG.\n    rewrite bind_pair in H.\n    destruct H as (HH & Ty1 & Ty2).\n    inverts Ty1.\n    lets* (v1 & ? & ?): normalization H5.\n    lets* (vv & ? & ?): normalization Ty2.\n    lets* (v2 & ? & ?): normalization H9.\n    destruct HH as (vv1 & ? & ? & ? & ? & ? & Imp).\n    lets (? & ?) : rel_v_well_type Imp.\n    lets* (v1' & v2' & ? & ? & ?) : prod_canonical H15.\n    substs.\n    assert (trm_pair (bind g1 t1) (bind g1 t2) ->* trm_pair v1 v2).\n    sapply* multi_red_pair.\n    lets* : value_unique H13 H19.\n    inverts H20.\n    apply rel_v_proj1 in Imp.\n    destruct Imp.\n    my_simplfier.\n    splits*.\n    exists v2 vv.\n    splits*.\n\n  - Case \"<-\".\n    introv H.\n    destruct H as (H1 & H2).\n    destruct H1 as (? & ? & Imp1).\n    destruct H2 as (? & ? & Imp2).\n    splits*.\n    introv GG.\n    lets Imp1' : Imp1 GG.\n    lets Imp2' : Imp2 GG.\n    clear Imp1 Imp2.\n    destruct Imp1' as (Imp1' & ? & ?).\n    destruct Imp1' as (v1 & ? & ? & ? & ? & ? & Imp1').\n    destruct Imp2' as (Imp2' & ? & ?).\n    destruct Imp2' as (v2 & ? & ? & ? & ? & ? & Imp2').\n    my_simplfier.\n\n    rewrite bind_pair.\n    splits*.\n    exists (trm_pair v1 v2) x0.\n    splits*.\n    sapply* multi_red_pair.\n    apply rel_v_proj1.\n    splits~.\nQed.\n\n\n\nLemma compat_pair2 : forall G1 G2 T1 T2 T3 t1 t2 t3,\n    rel_e_open G1 G2 t3 (trm_pair t1 t2) T3 (a_prod T1 T2) <->\n    rel_e_open G1 G2 t3 t1 T3 T1 /\\\n    rel_e_open G1 G2 t3 t2 T3 T2.\nProof.\n  intros.\n  splits.\n  introv H.\n\n  - Case \"->\".\n    destruct H as (? & HH & ?).\n    splits.\n\n    inverts HH.\n    splits*.\n    introv GG.\n    lets : H0 GG.\n    rewrite bind_pair in H1.\n    destruct H1 as (HH & Ty1 & Ty2).\n    inverts Ty2.\n    lets* (v1 & ? & ?): normalization H6.\n    lets* (vv & ? & ?): normalization Ty1.\n    lets* (v2 & ? & ?): normalization H9.\n    destruct HH as (? & vv1 & ? & ? & ? & ? & Imp).\n    lets (? & ?) : rel_v_well_type Imp.\n    lets* (v1' & v2' & ? & ? & ?) : prod_canonical H16.\n    substs.\n    assert (trm_pair (bind g2 t1) (bind g2 t2) ->* trm_pair v1 v2).\n    sapply* multi_red_pair.\n    lets* : value_unique H14 H19.\n    inverts H20.\n    apply rel_v_proj2 in Imp.\n    destruct Imp.\n    my_simplfier.\n    splits*.\n    exists vv v1.\n    splits*.\n\n    inverts HH.\n    splits*.\n    introv GG.\n    lets : H0 GG.\n    rewrite bind_pair in H1.\n    destruct H1 as (HH & Ty1 & Ty2).\n    inverts Ty2.\n    lets* (v1 & ? & ?): normalization H6.\n    lets* (vv & ? & ?): normalization Ty1.\n    lets* (v2 & ? & ?): normalization H9.\n    destruct HH as (? & vv1 & ? & ? & ? & ? & Imp).\n    lets (? & ?) : rel_v_well_type Imp.\n    lets* (v1' & v2' & ? & ? & ?) : prod_canonical H16.\n    substs.\n    assert (trm_pair (bind g2 t1) (bind g2 t2) ->* trm_pair v1 v2).\n    sapply* multi_red_pair.\n    lets* : value_unique H14 H19.\n    inverts H20.\n    apply rel_v_proj2 in Imp.\n    destruct Imp.\n    my_simplfier.\n    splits*.\n    exists vv v2.\n    splits*.\n\n  - Case \"<-\".\n    introv H.\n    destruct H as (H1 & H2).\n    destruct H1 as (? & ? & Imp1).\n    destruct H2 as (? & ? & Imp2).\n    splits*.\n    introv GG.\n    lets Imp1' : Imp1 GG.\n    lets Imp2' : Imp2 GG.\n    clear Imp1 Imp2.\n    destruct Imp1' as (Imp1' & ? & ?).\n    destruct Imp1' as (? & v1 & ? & ? & ? & ? & Imp1').\n    destruct Imp2' as (Imp2' & ? & ?).\n    destruct Imp2' as (? & v2 & ? & ? & ? & ? & Imp2').\n    my_simplfier.\n\n    rewrite bind_pair.\n    splits*.\n    exists x0 (trm_pair v1 v2).\n    splits*.\n    sapply* multi_red_pair.\n    apply rel_v_proj2.\n    splits~.\nQed.\n\n\n\nLemma compat_pair : forall G1 G2 t1 t2 t3 t4 A1 A2 A1' A2',\n    rel_e_open G1 G2 t1 t2 (|A1|) (|A2|) ->\n    rel_e_open G1 G2 t3 t4 (|A1'|) (|A2'|) ->\n    disjoint A1 A2' ->\n    disjoint A1' A2 ->\n    rel_e_open G1 G2 (trm_pair t1 t3) (trm_pair t2 t4) (a_prod (|A1|) (|A1'|)) (a_prod (|A2|) (|A2'|)).\nProof.\n  introv Rel1 Rel2 Dis1 Dis2.\n  destruct Rel1 as (HH1 & HH2 & Rel1).\n  destruct Rel2 as (HH3 & HH4 & Rel2).\n  splits*.\n  introv GG.\n  lets Rel1' : Rel1 GG.\n  lets Rel2' : Rel2 GG.\n  repeat rewrite bind_pair.\n  destruct Rel1' as (Rel1' & ? & ?).\n  destruct Rel1' as (v1 & v1' & ? & ? & Red1 & Red1' & Rel1').\n  destruct Rel2' as (Rel2' & ? & ?).\n  destruct Rel2' as (v2 & v2' & ? & ? & Red2 & Red2' & Rel2').\n  lets [TT1 TT2]: bind_close HH1 HH2 GG.\n  lets [TT3 TT4]: bind_close HH3 HH4 GG.\n\n  apply rel_e_convr with (t' := trm_pair v1' v2'); auto_star.\n  apply rel_e_convl with (t := trm_pair v1 v2); auto_star.\n  lets : preservation_multi_step TT1 Red1.\n  lets : preservation_multi_step TT2 Red1'.\n  lets : preservation_multi_step TT3 Red2.\n  lets : preservation_multi_step TT4 Red2'.\n  apply rel_v_in_rel_e.\n  apply rel_v_proj1; splits; apply rel_v_proj2; splits~.\n  apply~ disjoint_rel_v.\n  apply~ disjoint_rel_v.\n  apply~ multi_red_pair.\n  apply~ multi_red_pair.\nQed.\n\n\nLemma compat_co_proj1 : forall G1 G2 t1 t1' t2 T1 T2,\n    rel_e_open G1 G2 (trm_capp co_proj1 (trm_pair t1 t1')) t2 T1 T2 ->\n    rel_e_open G1 G2 t1 t2 T1 T2.\nProof with auto.\n  introv H.\n  destruct H as (Ty1 & Ty2 & Imp).\n  inverts Ty1.\n  inverts H4.\n  inverts H2.\n\n  splits*.\n  introv GG.\n  lets : Imp GG.\n  repeat rewrite bind_capp in *.\n  repeat rewrite bind_pair in *.\n\n  lets (? & ?): bind_close H4 Ty2 GG.\n  lets (? & ?): bind_close H6 Ty2 GG.\n  lets (v1 & ? & ?): normalization H0.\n  lets (v2 & ? & ?): normalization H1.\n  lets (v3 & ? & ?): normalization H2.\n\n  apply rel_e_redl with (t := v1) in H.\n  apply rel_e_redr with (t' := v2) in H...\n  apply rel_e_convl with (t := v1)...\n  apply rel_e_convr with (t' := v2)...\n\n  apply star_trans with (b := (trm_capp co_proj1 (trm_pair v1 v3)))...\n  apply multi_red_capp.\n  apply multi_red_pair...\nQed.\n\nLemma compat_co_proj2 : forall G1 G2 t1 t1' t2 T1 T2,\n    rel_e_open G1 G2 (trm_capp co_proj2 (trm_pair t1' t1)) t2 T1 T2 ->\n    rel_e_open G1 G2 t1 t2 T1 T2.\nProof with auto.\n  introv H.\n  destruct H as (Ty1 & Ty2 & Imp).\n  inverts Ty1.\n  inverts H4.\n  inverts H2.\n\n  splits*.\n  introv GG.\n  lets : Imp GG.\n  repeat rewrite bind_capp in *.\n  repeat rewrite bind_pair in *.\n\n  lets (? & ?): bind_close H4 Ty2 GG.\n  lets (? & ?): bind_close H6 Ty2 GG.\n  lets (v1 & ? & ?): normalization H0.\n  lets (v2 & ? & ?): normalization H1.\n  lets (v3 & ? & ?): normalization H2.\n\n  apply rel_e_redl with (t := v3) in H.\n  apply rel_e_redr with (t' := v2) in H...\n  apply rel_e_convl with (t := v3)...\n  apply rel_e_convr with (t' := v2)...\n\n  apply star_trans with (b := (trm_capp co_proj2 (trm_pair v1 v3)))...\n  apply multi_red_capp.\n  apply multi_red_pair...\nQed.\n\n\n\nLemma compat_abs : forall G1 G2 t1 t2 x T1 T2 T1' T2',\n    x \\notin dom G1 \\u dom G2 \\u fv_exp t1 \\u fv_exp t2 ->\n    rel_e_open ([(x, T1)] ++ G1) ([(x, T2)] ++ G2) (t1 ^ x) (t2 ^ x) T1' T2' ->\n    rel_e_open G1 G2 (trm_abs t1) (trm_abs t2) (a_arrow T1 T1') (a_arrow T2 T2').\nProof.\n  introv ? Rel.\n  destruct Rel as (Ty1 & Ty2 & Rel).\n  splits*.\n  pick fresh y and apply typ_abs.\n  sapply* typing_rename.\n  pick fresh y and apply typ_abs.\n  sapply* typing_rename.\n  introv GG.\n  lets Ty1': typing_to_etyping Ty1.\n  lets Ty2': typing_to_etyping Ty2.\n  apply etyping_abs in Ty1'; autos.\n  apply etyping_abs in Ty2'; autos.\n  apply etyping_to_typing in Ty1'; autos.\n  apply etyping_to_typing in Ty2'; autos.\n  lets* [? ?]: bind_close Ty1' Ty2' GG.\n  repeat rewrite bind_abs in *.\n  apply rel_v_in_rel_e.\n  splits*.\n  intros.\n\n  assert (rel_g ([(x, T1)] ++ G1) ([(x, T2)] ++ G2) ([(x, a1)] ++ g1) ([(x, a2)] ++ g2)) by autos.\n  lets [? ?]: rel_g_well_type_value H3.\n\n  forwards* Imp : Rel.\n  inverts H3 as. intros ? ? ? Typ.\n  lets [? ?]: rel_v_well_type Typ.\n\n  apply rel_e_convr with (t':= (bind g2 t2) ^^ a2); auto_star.\n  apply rel_e_convl with (t := (bind g1 t1) ^^ a1); auto_star.\n  rewrite* <- (@bind_subst g1 x).\n  rewrite* <- (@bind_subst g2 x).\nQed.\n\nLemma compat_rcd : forall G1 G2 t1 t2 T1 T2 l,\n    rel_e_open G1 G2 t1 t2 T1 T2 ->\n    rel_e_open G1 G2 (trm_rcd l t1) (trm_rcd l t2) (a_rcd l T1) (a_rcd l T2).\nProof.\n  introv H.\n  destruct H as (? & ? & Imp).\n  splits*.\n  introv HH.\n  apply Imp in HH.\n  repeat rewrite bind_rcd.\n\n\n  destruct HH as (HH & ? & ?).\n  destruct HH as (v1 & v2 & ? & ? & ? & ? & ?).\n\n  splits*.\n  exists (trm_rcd l v1) (trm_rcd l v2).\n  splits~; try apply~ multi_red_rcd.\n  apply~ rel_v_rcd.\nQed.\n\n\n\nLemma compat_proj : forall G1 G2 t1 t2 T1 T2 l,\n    rel_e_open G1 G2 t1 t2 (a_rcd l T1) (a_rcd l T2) ->\n    rel_e_open G1 G2 (trm_proj t1 l) (trm_proj t2 l) T1 T2.\nProof.\n  introv H.\n  destruct H as (? & ? & Imp).\n  splits*.\n  introv HH.\n  apply Imp in HH.\n  repeat rewrite bind_proj.\n\n\n  destruct HH as (HH & ? & ?).\n  destruct HH as (v1 & v2 & ? & ? & ? & ? & HH).\n  lets (HH1 & HH2) : rel_v_well_type HH.\n  lets* (v1' & ?): rcd_canonical HH1.\n  lets* (v2' & ?): rcd_canonical HH2.\n  substs.\n  inverts H3.\n  inverts H4.\n  inverts HH1.\n  inverts HH2.\n\n  splits*.\n  exists v1' v2'.\n  splits~.\n\n  apply star_trans with (b := trm_proj (trm_rcd l v1') l); auto.\n  apply~ multi_red_proj.\n\n  apply star_trans with (b := trm_proj (trm_rcd l v2') l); auto.\n  apply~ multi_red_proj.\n\n  sapply rel_v_rcd; eauto.\nQed.\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/Compatibility_Lemma.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.29595854629302437}}
{"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 color.\nRequire Import geometry.\nRequire Import patch.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nSection Sew.\n\nVariables (gd gr : hypermap) (bgd : seq gd) (bgr : seq gr).\n\nHypothesis Hbgd : sfcycle edge bgd.\nHypothesis Hbgr : ufcycle node bgr.\nHypothesis Hrs : size bgd = size bgr.\n\nLemma HbgdE : forall xd, bgd xd -> cedge xd =1 bgd.\nProof. by move=> *; apply fconnect_cycle; case (andP Hbgd). Qed.\n\nLemma HbgdE1 : forall xd, bgd (edge xd) -> bgd xd.\nProof. by move=> xd Hxd; rewrite -(HbgdE Hxd) Sedge fconnect1. Qed.\n\nLemma HbgrN : forall xr, bgr xr -> cnode xr =1 bgr.\nProof. by move=> *; apply fconnect_cycle; case (andP Hbgr). Qed.\n\nLemma HbgrN1 : forall xr, bgr (node xr) -> bgr xr.\nProof. by move=> xr Hxr; rewrite -(HbgrN Hxr) Snode fconnect1. Qed.\n\nRemark in_bgd : forall xd, {xr0 : gr | bgd xd} + {setC bgd xd}.\nProof.\nmove=> xd; rewrite /setC; case Hxd: (bgd xd); [ left | by right ].\nby case: bgr Hxd Hrs => [|xr0 pr]; [ case bgd | exists xr0 ].\nQed.\n\nRemark in_bgr : forall xr, {xd0 : gd | bgr xr} + {setC bgr xr}.\nProof.\nmove=> xr; rewrite /setC; case Hxr: (bgr xr); [ left | by right ].\nby case: bgd Hxr Hrs => [|xd0 pd]; [ case bgr | exists xd0 ].\nQed.\n\nLet hdr xr0 xd := sub xr0 (rev bgr) (index xd bgd).\n\nLet hrd xd0 xr := sub xd0 bgd (index xr (rev bgr)).\n\nRemark bgr_hdr : forall xd,  bgd xd -> forall xr0, bgr (hdr xr0 xd).\nProof.\nby move=> *; rewrite /hdr -mem_rev mem_sub // size_rev -Hrs index_mem.\nQed.\n\nRemark bgd_hrd : forall xr, bgr xr -> forall xd0, bgd (hrd xd0 xr).\nProof.\nby move=> *; rewrite /hrd mem_sub // Hrs -size_rev index_mem mem_rev.\nQed.\n\nRemark hrd_hdr : forall xd, bgd xd -> forall xd0 xr0, hrd xd0 (hdr xr0 xd) = xd.\nProof.\nmove=> xd Hxd xd0 xr0; rewrite /hrd /hdr index_uniq ?sub_index //.\n  by rewrite size_rev -Hrs index_mem.\nby rewrite uniq_rev; case: (andP Hbgr).\nQed.\n\nRemark hdr_hrd : forall xr, bgr xr -> forall xd0 xr0, hdr xr0 (hrd xd0 xr) = xr.\nProof.\nmove=> xr Hxr xd0 xr0; rewrite /hrd /hdr index_uniq ?sub_index ?mem_rev //.\n  by rewrite Hrs -size_rev index_mem mem_rev.\nby apply simple_uniq; case: (andP Hbgd).\nQed.\n\nRemark node_hdr : forall xd, bgd xd ->\n  forall xr0, node (hdr xr0 xd) = hdr xr0 (node (face xd)).\nProof.\ncase: (andP Hbgd) (andP Hbgr) => [HdE Ud] [HrN Ur] xd Hxd xr0.\nmove/simple_uniq: Ud => Ud; set xr := hdr xr0 xd.\nhave Hxr: bgr xr by rewrite /xr bgr_hdr.\nrewrite -(eqP (prev_cycle HdE Hxd)) Eedge (eqP (next_cycle HrN Hxr)).\nrewrite -(rev_rev bgr) next_rev ?uniq_rev // !prev_sub Hxd mem_rev Hxr.\ncase Dbgr: {1}(rev bgr) => [|xr1 bgr']; first by rewrite -mem_rev Dbgr in Hxr.\nrewrite /xr {1}/hdr.\ncase Dbgd: {1 2}bgd => [|xd1 bgd'] /=; first by rewrite Dbgd in Hxd.\nset i := index xd bgd'.\nhave Hi: i < size bgd by rewrite Dbgd /= ltnS /i index_size.\nrewrite /hdr index_uniq //; rewrite Hrs -size_rev in Hi.\napply: (etrans (congr1 (sub _ _) _) (set_sub_default Hi _ _)).\nrewrite -uniq_rev Dbgr /= in Ur; case/andP: Ur => [Hxr1' Ur'].\nrewrite Dbgd /= in Ud; case/andP: Ud => [Hxd1' _].\nhave Hrs' := Hrs; rewrite Dbgd -(size_rev bgr) Dbgr /= in Hrs'.\nmove: Hrs' => [Hrs'].\nrewrite Dbgd /= /setU1 eqd_sym in Hxd; case Hxd1: (xd =d xd1) Hxd.\n  rewrite Dbgr /= /i -(cats0 bgr') -(cats0 bgd') !index_cat /= !addn0.\n  by clear; rewrite (eqP Hxd1) (negbE Hxr1') (negbE Hxd1').\nby rewrite Dbgr /= -index_mem; move=> *; rewrite index_uniq // -Hrs'.\nQed.\n\nRemark edge_hrd : forall xr, bgr xr -> forall xd0,\n  edge (hrd xd0 xr) = hrd xd0 (face (edge xr)).\nProof.\nmove=> xr Hxr xd0; set yr := face (edge xr).\nhave Hyr: bgr yr by apply HbgrN1; rewrite /yr Eedge.\nrewrite -{1}[xr]Eedge -/yr -{1}(hdr_hrd Hyr xd0 xr).\nset yd := hrd xd0 yr; have Hyd: bgd yd by rewrite /yd bgd_hrd.\nby rewrite node_hdr // hrd_hdr ?Eface // HbgdE1 ?Eface.\nQed.\n\nInductive sew_tag : Set :=\n  | SewDisk : sew_tag\n  | SewRest : sew_tag.\n\nDefinition sew_tag_eq pt1 pt2 : bool :=\n  match pt1, pt2 with\n  | SewDisk, SewDisk => true\n  | SewRest, SewRest => true\n  | _, _ => false\n  end.\n\nDefinition sew_tag_data : dataSet.\napply (@DataSet _ sew_tag_eq); abstract by do 2 case; constructor.\nDefined.\nCanonical Structure sew_tag_data.\n\nDefinition sew_tag_set : finSet.\napply (@FinSet _ (Seq SewDisk SewRest)); abstract by case.\nDefined.\nCanonical Structure sew_tag_set.\nNotation ptag := sew_tag_set (only parsing).\n\nLet sew_sub_map (i : sew_tag_set) : finSet :=\n  match i with\n  | SewDisk => gd\n  | SewRest => subFin (setC bgr)\n  end.\n\nDefinition sew_dart := sumFin sew_sub_map.\n\nDefinition sewd xd : sew_dart := @sumdI _ sew_sub_map SewDisk xd.\n\nDefinition sewr_r xr Hxr : sew_dart :=\n  @sumdI _ sew_sub_map SewRest (@subdI _ _ xr Hxr).\n\nDefinition sewr xr :=\n  match in_bgr xr with\n  | inleft u => let (xd0, _) := u in sewd (hrd xd0 xr)\n  | inright Hxr => sewr_r Hxr\n  end.\n\nLemma inj_sewd : injective sewd.\nProof.\nmove=> xd yd; move/(introT eqP); rewrite /sewd /= sumd_eqdr; exact (xd =P yd).\nQed.\n\nLemma inj_sewr : injective sewr.\nProof.\nmove=> xr yr; move/(introT eqP); rewrite /sewr.\ncase: (in_bgr xr) (in_bgr yr) => [[xd0 Hxr]|Hxr] [[xd1 Hyr]|Hyr] //=.\n  by move=> Hxy; rewrite -(hdr_hrd Hxr xd0 xr) (inj_sewd (eqP Hxy)) hdr_hrd.\nrewrite /sewr_r sumd_eqdr /eqd /=; exact (xr =P yr).\nQed.\n\nRemark sewr_bgr : forall xd0 xr, bgr xr -> sewr xr = sewd (hrd xd0 xr).\nProof.\nmove=> xd0 xr Hxr; rewrite /sewr; case: (in_bgr xr) => [[xd1 _]|Hxr'].\n  by rewrite -{1}(hdr_hrd Hxr xd0 xr) hrd_hdr ?bgd_hrd.\nby case/idP: Hxr'.\nQed.\n\nRemark sewr_gr : forall xr Hxr, sewr xr = @sewr_r xr Hxr.\nProof.\nmove=> xr Hxr; rewrite /sewr.\ncase: (in_bgr xr) => [[xd0 Hxr']|Hxr']; first by rewrite (negbE Hxr) in Hxr'.\nby rewrite (bool_eqT Hxr Hxr').\nQed.\n\nRemark sewr_hdr : forall xd, bgd xd -> forall xr0, sewr (hdr xr0 xd) = sewd xd.\nProof. by move=> xd Hxd xr0; rewrite (sewr_bgr xd) ?hrd_hdr ?bgr_hdr. Qed.\n\nDefinition sew_edge (w : sew_dart) : sew_dart :=\n  match w with\n  | sumdI SewDisk xd =>\n    if in_bgd xd is inleft (exist xr _) then sewr (edge (hdr xr xd)) else\n    sewd (edge xd)\n  | sumdI SewRest ur =>\n    let (xr, _) := ur in sewr (edge xr)\n  end.\n\nDefinition sew_face_r (xr : gr) : sew_dart :=\n  match sewr (face xr) with\n  | sumdI SewDisk xd => sewd (face xd)\n  | ufr => ufr\n  end.\n\nDefinition sew_face (w : sew_dart) : sew_dart :=\n  match w with\n  | sumdI SewDisk xd =>\n    if in_bgd xd is inleft (exist xr _) then sew_face_r (hdr xr xd) else\n    sewd (face xd)\n  | sumdI SewRest ur =>\n    let (xr, _) := ur in sew_face_r xr\n  end.\n\nDefinition sew_node (w : sew_dart) : sew_dart :=\n  match w with\n  | sumdI SewDisk xd => sewd (node xd)\n  | sumdI SewRest ur => let (xr, _) := ur in sewr (node xr)\n  end.\n\nLemma Esew_map : monic3 sew_edge sew_node sew_face.\nProof.\nmove=> [[|] xd]; [ simpl | case: xd => [xr Hxr] /= ].\n  case: (in_bgd xd) => [[xr0 Hxd]|Hxd] /=.\n    set exr := edge (hdr xr0 xd); transitivity (sew_node (sew_face_r exr)).\n    rewrite /sewr; case: (in_bgr exr) => [[xd0 Hexr]|Hexr] //=.\n    case: (in_bgd (hrd xd0 exr)); last by rewrite /setC bgd_hrd.\n      by move=> [xr1 _]; rewrite /= hdr_hrd.\n    rewrite /= /sew_face_r (sewr_bgr xd) /=.\n      by rewrite /exr -edge_hrd ?bgr_hdr // Eedge (hrd_hdr Hxd).\n    by apply HbgrN1; rewrite /exr Eedge bgr_hdr.\n    case: (in_bgd (edge xd)) => [[xr0 Hexd]|Hexd]; rewrite /= ?Eedge //.\n  by case (negP Hxd); apply HbgdE1.\ntransitivity (sew_node (sew_face_r (edge xr))).\nrewrite /sewr; case: (in_bgr (edge xr)) => [[xd0 Hexr]|Hexr] //=.\n  case: (in_bgd _) => [[xr0 Hexd]|Hexd] /=; first by rewrite hdr_hrd.\n  by rewrite /setC bgd_hrd in Hexd.\nhave Hfexr: setC bgr (face (edge xr)).\n  apply/idP => [Hfexr]; case/idP: Hxr.\n  by rewrite -{1}[xr]Eedge -(HbgrN Hfexr) fconnect1.\nby rewrite /sew_face_r (sewr_gr Hfexr) /= Eedge (sewr_gr Hxr).\nQed.\n\nDefinition sew_map := Hypermap Esew_map.\n\nLemma sewr_rev_sewd : maps sewr bgr = rev (maps sewd bgd).\nProof.\napply: (etrans (esym (rev_rev _)) (congr1 rev _)); rewrite -maps_rev.\nmove: (andP Hbgd) sewr_hdr Hrs => [_ Ud]; rewrite /hdr -(size_rev bgr).\nelim: bgd (rev bgr) {Ud}(simple_uniq Ud) => [|xd pd Hrec] [|xr pr] //=.\nmove/andP=> [Hpxd Upd] Edr; rewrite -(Edr _ (setU11 _ _) xr) set11 /=.\nmove=> [Hsz]; congr Adds; apply: Hrec => // yd Hyd yr0.\nrewrite -(Edr _ (setU1r _ Hyd) yr0).\nby case: (yd =P xd) Hpxd => [<-|_]; rewrite ?Hyd.\nQed.\n\nLemma sew_map_patch : @patch sew_map _ _ sewd sewr bgd bgr.\nProof.\nsplit=> //.\n- exact inj_sewd.\n- exact inj_sewr.\n- exact sewr_rev_sewd.\n- move=> x; case Dx: {0}x => [[|] xd]; move: Dx; last move: xd => [xr Hxr].\n    rewrite -[sumdI _]/(sewd xd) => Dx.\n    rewrite /setU /setC Dx codom_f (mem_maps inj_sewd) /=.\n    case: (in_bgd xd) => [[xr0 Hxd]|Hxd].\n      rewrite Hxd; apply/set0Pn; exists (hdr xr0 xd).\n      by rewrite /preimage (sewr_hdr Hxd) set11.\n    rewrite (negbE Hxd); apply/set0Pn => [] [xr H]; case/idP: Hxd; move: H.\n    rewrite /preimage /sewr; case: (in_bgr xr) => [[xd0 Hxr]|Hxr]; last done.\n    by rewrite (inj_eqd inj_sewd); move/eqP=> Dxd; rewrite Dxd bgd_hrd.\n  rewrite -[sumdI _]/(sewr_r Hxr); move=> Dx.\n  rewrite Dx /setU /setC {2}/codom /set0b eq_card0 //=.\n  by apply/set0Pn; exists xr; rewrite /preimage (sewr_gr Hxr) set11.\n- by move=> xd Hxd /=; case: (in_bgd xd) => // [[xr0 Hxd']]; case/idP: Hxd.\n- move=> xr; rewrite {2}/sewr; case: (in_bgr xr) => [[xd0 Hxr]|Hxr] //=.\n  case: (in_bgd (hrd xd0 xr)) => [[xr0 _]|Hxd']; first by rewrite hdr_hrd.\n  by case (negP Hxd'); rewrite bgd_hrd.\nby move=> xr Hxr; rewrite (sewr_gr Hxr).\nQed.\n\nEnd Sew.\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/sew.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2959585462930243}}
{"text": "From hahn Require Import Hahn.\nFrom PromisingLib Require Import Loc.\nFrom Promising2 Require Import View Time Event.\nFrom imm Require Import AuxRel2.\n\nSet Implicit Arguments.\nRemove Hints plus_n_O.\n\nSection MaxValue.\n  Variable A : Type.\n  \n  Definition max_value f (INR : A -> Prop) val :=\n    ⟪ UB: forall a (INa: INR a), Time.le (f a) val ⟫ /\\\n    ⟪ MAX: ((forall a, ~ INR a) /\\ val = Time.bot) \\/\n       (exists a_max, ⟪ INam: INR a_max ⟫ /\\\n                      ⟪LB': Time.le val (f a_max)⟫) ⟫.\n\n  Lemma max_value_singleton f b t (T: t = f b) : max_value f (eq b) t.\n  Proof using.\n    red; splits; ins; desc; subst.\n      by apply Time.le_lteq; eauto.\n      right; exists b; splits; try apply Time.le_lteq; eauto.\n  Qed.\n\n  Lemma max_value_new_f f f' P t \n        (MAX: max_value f P t) (F: forall x, P x -> f' x = f x): max_value f' P t.\n  Proof using.\n    unfold max_value in *; ins; desf; splits; ins.\n    all: try rewrite F; auto.\n    right; exists a_max; rewrite F; auto.\n  Qed.\n\n  Lemma max_value_same_set f P P' t \n        (MAX: max_value f P t) (SAME: P' ≡₁ P): max_value f P' t.\n  Proof using.\n    unfolder in *; desc.\n    unfold max_value in *; ins; desf; splits; ins.\n    all: try specialize (SAME a); desf; eauto.\n    left; split; eauto; ins; intro;  eapply MAX0; apply SAME; edone.\n  Qed.\n\n  Lemma max_value_join f P P' P'' t t'\n        (MAX: max_value f P t) (MAX':  max_value f P' t')\n        (SAME_: P'' ≡₁ P ∪₁ P'):\n    max_value f P'' (Time.join t t').\n  Proof using.\n    assert (SAME: forall x, P'' x <-> P x \\/ P' x).\n      by unfolder in *; basic_solver 12.\n    unfold max_value in *; ins; desf; splits; ins.\n    all: try apply SAME in INa; desf.\n    all: try apply SAME0 in INa; desf.\n    all: try by etransitivity; eauto; eauto using Time.join_l, Time.join_r. \n    - left; split; eauto. ins; intro. \n      specialize (MAX1 a). specialize (MAX0 a).\n      apply SAME in H; desf.\n    - right; exists a_max; splits.\n      rewrite SAME; eauto.\n      apply Time.join_spec; eauto; etransitivity; eauto; rewrite Time.le_lteq; eauto.\n      apply Time.le_lteq. apply Time.bot_spec.\n    - right; exists a_max; splits.\n      apply SAME; eauto.\n      apply Time.join_spec; eauto; etransitivity; eauto; rewrite Time.le_lteq; eauto.\n      apply Time.le_lteq. apply Time.bot_spec.\n    - right;\n        destruct (Time.le_lt_dec (f a_max) (f a_max0)); [exists a_max0|exists a_max]; splits.\n      all: try rewrite SAME; eauto.\n      all: try (apply Time.join_spec; eauto;\n                etransitivity; eauto; rewrite Time.le_lteq; eauto). \n  Qed.\n\n  Lemma max_value_loc f f' P P' t b\n        (MAX: max_value f P t)\n        (SAME_: P' ≡₁ P ∪₁ eq b)\n        (F: forall x, P x -> f' x = f x):\n    max_value f' P'  (Time.join t (f' b)).\n  Proof using.\n    assert (SAME: forall x, P' x <-> P x \\/ eq b x).\n      by unfolder in *; basic_solver 12.\n    eapply max_value_join with (P':= eq b); eauto.\n    eapply max_value_new_f with (f:=f); eauto.\n    eapply max_value_singleton; done.\n  Qed.\n\n  Lemma max_value_empty f P (SAME: forall x, ~ P x): max_value f P Time.bot.\n  Proof using.\n    red; splits.\n    ins; exfalso; eapply SAME; edone.\n    left; splits; eauto.\n  Qed.\n\n  Lemma max_value_le f b c tm l P\n        (LE: Time.le (tm l) (f b))\n        (MAX: max_value f P (LocFun.find l tm))\n        (LT: Time.lt (f b) (f c))\n        (IN: P c) : False.\n  Proof using.\n    unfold LocFun.find in *.\n    red in MAX; desf.\n    eby eapply MAX0.\n    apply UB in IN.\n    eapply Time.lt_strorder; eauto using TimeFacts.le_lt_lt.\n  Qed.\n\n  Lemma max_value_lt f b tm l P t\n        (LT1: Time.lt t (f b))\n        (MAX: max_value f P (LocFun.find l tm))\n        (LT2: Time.lt (tm l) t)\n        (IN: P b) : False.\n  Proof using.\n    unfold LocFun.find in *.\n    red in MAX; desf.\n    eby eapply MAX0.\n    apply UB in IN.\n    assert (Time.lt (tm l) (f b)).\n    eapply Time.lt_strorder; eauto.\n    eapply Time.lt_strorder; eauto using TimeFacts.le_lt_lt.\n  Qed.\n  \nLemma max_value_le_join f (P P' : A -> Prop) t\n      (LT: forall x, P' x -> Time.lt (f x) t) :\n  max_value f (P ∪₁ P') t -> max_value f P t.\nProof using.\n  intros MAX; red in MAX; desf; red; split; unnw; ins.\n  1,3: by apply UB; left.\n  { destruct (classic (exists a, P a)) as [[a PP]|NN]; [right|left].\n    { exists a; split; auto. apply Time.bot_spec. }\n    split; auto. intros a PP. apply NN. eexists; eauto. }\n  destruct INam as [H|H].\n  { right; eexists; eauto. }\n  exfalso. eapply Time.lt_strorder.\n  eapply TimeFacts.le_lt_lt; eauto.\nQed.\n\nLemma max_value_same_value f S a b\n      (H : max_value f S a) (B : max_value f S b) :\n  a = b.\nProof using.\n  red in H; red in B; desf.\n  { exfalso. eapply MAX; eauto. }\n  { exfalso. eapply MAX0; eauto. }\n  specialize (UB0 a_max INam).\n  specialize (UB a_max0 INam0).\n  apply TimeFacts.antisym.\n  all: etransitivity; eauto. \nQed.\n\nLemma timemap_same_max_value_implies_eq f S (a b : TimeMap.t)\n      (H : forall l, max_value f (S l) (a l)) (B : forall l, max_value f (S l) (b l)):\n  a = b.\nProof using.\n  apply LocFun.ext.\n  intros l. specialize (H l). specialize (B l).\n  eapply max_value_same_value; eauto.\nQed.\n\nLemma view_same_max_value_implies_eq f S a b\n      (A_PLN_RLX : TimeMap.eq (View.pln a) (View.rlx a))\n      (B_PLN_RLX : TimeMap.eq (View.pln b) (View.rlx b))\n      (H : forall l, max_value f (S l) (View.rlx a l))\n      (B : forall l, max_value f (S l) (View.rlx b l)) :\n  a = b.\nProof using.\n  apply View.ext.\n  rewrite A_PLN_RLX. rewrite B_PLN_RLX.\n  all: eapply timemap_same_max_value_implies_eq; eauto.\nQed.\n\nLemma max_value_bot_f S :\n  max_value (fun _ => Time.bot) S Time.bot.\nProof using.\n  red. splits.\n  { ins. apply Time.bot_spec. }\n  destruct (classic (exists e, S e)) as [[e SE]|SE]; [right|left].\n  { exists e. split; auto. apply Time.bot_spec. }\n  split; auto. by apply not_ex_all_not.\nQed.\n\nEnd MaxValue.\n", "meta": {"author": "weakmemory", "repo": "promising2ToImm", "sha": "8f462969e0cfaa0bb71d43b4cdae0f030d06ef9c", "save_path": "github-repos/coq/weakmemory-promising2ToImm", "path": "github-repos/coq/weakmemory-promising2ToImm/promising2ToImm-8f462969e0cfaa0bb71d43b4cdae0f030d06ef9c/src/lib/MaxValue.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.2958879811793677}}
{"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\nSection constants.\n\nRequire Import Reals.\nRequire Import trajectory_const.\nRequire Import rrho.\nRequire Import trajectory_def.\n\nVariable intr : Trajectory.\nVariable evad : EvaderTrajectory.\n\nLemma Rle_201_250 : (MinSpeed <= 250)%R.\nunfold MinSpeed in |- *; left; prove_sup.\nQed.\n\nLemma Rle_250_880 : (250 <= MaxSpeed)%R.\nunfold MaxSpeed in |- *; left; prove_sup.\nQed.\n\n(**********)\nDefinition V : TypeSpeed := mkTypeSpeed 250 Rle_201_250 Rle_250_880.\nDefinition r_V : R := r V.\nDefinition rho_V : R := rho V.\nDefinition AlertTime : R := 19%R.\nDefinition AlertRange : R := 1400%R.\nDefinition tstep : R := (/ 2)%R.\nDefinition MaxStep : R := 1%R.\nDefinition MaxT : R := 10%R.\nDefinition MinT : R := (MaxT - tstep)%R.\nDefinition m (t : R) : R :=\n  let z := IZR 2 in (z * r_V * sin (rho_V * (t / z)))%R.\nDefinition m_rho_ub (t : R) : R :=\n  let z := IZR 2 in (z * r_lb V * sin_lb (rho_lb V * (t / z)))%R.\n\n(**********)\nRecord TimeT : Type := mkTimeT\n  {val :> R; cond_1 : (MinT <= val)%R; cond_2 : (val <= MaxT)%R}.\n\n(**********)\nLemma MinT_is_pos : (0 < MinT)%R.\nProof with trivial.\nunfold MinT in |- *; unfold MaxT, tstep in |- *;\n apply Rmult_lt_reg_l with 2%R...\nprove_sup...\nrewrite Rmult_0_r; rewrite Rmult_minus_distr_l; rewrite <- Rinv_r_sym...\napply Rlt_trans with 1%R; prove_sup...\nQed.\n\n(**********)\nTheorem rho_ub_t_PI2 :\n forall (h : TypeSpeed) (t : TimeT), (rho_ub h * t < PI / 2)%R.\nProof with trivial.\nintros; assert (H := cond_2 t)...\nunfold MaxT in H; apply Rlt_trans with (PI_lb / 2)%R...\nunfold rho_ub in |- *; cut (g < 33)%R...\ncut (tan_ub_MaxBank < 4 / 5)%R...\ncut (/ h < / 200)%R...\nintros; generalize g_pos; intro H3; generalize tan_ub_MaxBank_pos; intro H4;\n generalize (Rinv_0_lt_compat h (TypeSpeed_pos h)); \n intro H5...\ngeneralize\n (Rmult_le_0_lt_compat g 33 tan_ub_MaxBank (4 / 5) \n    (Rlt_le 0 g H3) (Rlt_le 0 tan_ub_MaxBank H4) H2 H1)...\nintro H6; generalize (Rmult_lt_0_compat g tan_ub_MaxBank H3 H4); intro H7...\nassert\n (H8 :=\n  Rmult_le_0_lt_compat (g * tan_ub_MaxBank) (33 * (4 / 5)) \n    (/ h) (/ 200) (Rlt_le 0 (g * tan_ub_MaxBank) H7) \n    (Rlt_le 0 (/ h) H5) H6 H0)...\napply Rlt_trans with (33 * / 200 * (4 / 5) * t)%R...\napply Rmult_lt_compat_r...\napply Rlt_le_trans with MinT...\napply MinT_is_pos...\napply (cond_1 t)...\nrewrite Rmult_assoc; rewrite (Rmult_comm (/ 200)); unfold Rdiv in |- *;\n do 2 rewrite <- Rmult_assoc...\napply Rle_lt_trans with (33 * / 200 * (4 / 5) * 10)%R...\napply Rmult_le_compat_l...\nleft; apply Rmult_lt_0_compat...\napply Rmult_lt_0_compat; [ prove_sup | apply Rinv_0_lt_compat; prove_sup ]...\nunfold Rdiv in |- *; apply Rmult_lt_0_compat;\n [ prove_sup | apply Rinv_0_lt_compat; prove_sup ]...\napply Rmult_lt_reg_l with 2%R...\nprove_sup...\napply Rmult_lt_reg_l with 200%R...\nprove_sup...\napply Rmult_lt_reg_l with 5%R...\nprove_sup...\nset (x := 200%R); set (y := 33%R); set (z := 10%R); set (u := 5%R);\n set (v := 4%R); set (w := 2%R)...\nunfold Rdiv in |- *;\n replace (u * (x * (w * (PI_lb * / w))))%R with (x * PI_lb * u * (w * / w))%R;\n [ idtac | ring ]...\nreplace (u * (x * (w * (y * / x * (v * / u) * z))))%R with\n (w * y * v * z * (u * / u) * (x * / x))%R; [ idtac | ring ]...\nrepeat rewrite <- Rinv_r_sym; unfold x, y, z, u, v, w in |- *; try discrR...\nunfold PI_lb in |- *; prove_sup...\napply Rinv_lt_contravar...\napply Rmult_lt_0_compat...\nprove_sup...\napply Rlt_le_trans with MinSpeed...\nunfold MinSpeed in |- *; prove_sup...\napply (v_cond1 h)...\napply Rlt_le_trans with MinSpeed...\nunfold MinSpeed in |- *; prove_sup...\napply (v_cond1 h)...\nunfold tan_ub_MaxBank in |- *; unfold Rdiv in |- *...\napply Rmult_lt_reg_l with 10%R...\nprove_sup...\nrewrite (Rmult_comm 10); rewrite Rmult_assoc; rewrite <- Rinv_l_sym...\nrewrite Rmult_1_r; apply Rmult_lt_reg_l with 5%R...\nprove_sup...\npattern 5%R at 1 in |- *; rewrite (Rmult_comm 5); do 2 rewrite Rmult_assoc;\n rewrite <- Rinv_l_sym...\nprove_sup...\ndiscrR...\ndiscrR...\nunfold g in |- *; unfold Rdiv in |- *; apply Rmult_lt_reg_l with 10%R...\nprove_sup...\nrewrite <- Rmult_comm; rewrite Rmult_assoc; rewrite <- Rinv_l_sym...\nrewrite Rmult_1_r; prove_sup...\ndiscrR...\nunfold Rdiv in |- *; repeat rewrite <- (Rmult_comm (/ 2));\n apply Rmult_lt_compat_l...\napply Rinv_0_lt_compat; prove_sup...\nassert (H0 := PI_approx); elim H0...\nQed.\n\n(**********)\nTheorem rho_t_PI2 : forall t : TimeT, (rho_V * t < PI / 2)%R.\nProof with trivial.\nintro; generalize (rho_ub_t_PI2 V t); intro; unfold rho_V in |- *...\napply Rlt_trans with (rho_ub V * t)%R...\napply Rmult_lt_compat_r...\napply Rlt_le_trans with MinT; [ apply MinT_is_pos | apply (cond_1 t) ]...\napply rho_ub_0...\nQed.\n\n(**********)\nLemma rho_t_2 : forall t : TimeT, (rho_V * t < 2)%R.\nProof with trivial.\nintro t; apply Rlt_trans with (PI / 2)%R...\napply rho_t_PI2...\napply Rlt_le_trans with (PI_ub / 2)%R...\nunfold Rdiv in |- *; repeat rewrite <- (Rmult_comm (/ 2))...\napply Rmult_lt_compat_l...\napply Rinv_0_lt_compat; prove_sup...\nassert (H := PI_approx); elim H...\nright; unfold PI_ub in |- *; unfold Rdiv in |- *.\nchange 4%R with (IZR (2 * 2)).\nrewrite (mult_IZR 2 2).\n rewrite Rmult_assoc;\n rewrite <- Rinv_r_sym; [ apply Rmult_1_r | discrR ]...\nQed.\n\n(**********)\nLemma r_V_is_pos : (0 < r_V)%R.\nunfold r_V in |- *; unfold r in |- *; unfold Rdiv in |- *;\n apply Rmult_lt_0_compat;\n [ apply (TypeSpeed_pos V) | apply Rinv_0_lt_compat; apply rho_pos ].\nQed.\n\n(**********)\nLemma rho_V_is_pos : (0 < rho_V)%R.\nunfold rho_V in |- *; apply rho_pos.\nQed.\n\n(**********)\nLemma m_le : forall t1 t2 : TimeT, (t1 <= t2)%R -> (m t1 <= m t2)%R.\nProof with trivial.\nintros; unfold m in |- *; repeat rewrite Rmult_assoc...\nrepeat apply Rmult_le_compat_l...\nleft; simpl in |- *; prove_sup...\nleft; apply r_V_is_pos...\ngeneralize (rho_t_PI2 t1); intro H1...\ngeneralize (rho_t_PI2 t2); intro H2...\nassert (Hyp : (0 < 2)%R)...\nprove_sup0...\ngeneralize\n (Rmult_lt_compat_l (/ 2) (rho_V * t1) (PI / 2) (Rinv_0_lt_compat 2 Hyp) H1)...\ngeneralize\n (Rmult_lt_compat_l (/ 2) (rho_V * t2) (PI / 2) (Rinv_0_lt_compat 2 Hyp) H2)...\nreplace (/ 2 * (PI / 2))%R with (PI / 4)%R...\nclear H1 H2; intros H1 H2...\nrewrite Rmult_comm in H1...\nrewrite Rmult_comm in H2...\nunfold Rdiv in |- *...\ngeneralize (cond_1 t1)...\ngeneralize (cond_1 t2)...\ngeneralize MinT_is_pos; intro H7...\nintros H3 H4...\ngeneralize (Rlt_le_trans 0 MinT t1 H7 H4); clear H4; intro H4...\ngeneralize (Rlt_le_trans 0 MinT t2 H7 H3); clear H3; intro H3...\napply sin_incr_1...\nleft; apply Rlt_trans with 0%R...\napply _PI2_RLT_0...\nrepeat simple apply Rmult_lt_0_compat...\napply rho_V_is_pos...\napply Rinv_0_lt_compat; simpl in |- *; prove_sup0...\nleft; apply Rlt_trans with (PI / 4)%R...\nrewrite <- Rmult_assoc...\napply PI4_RLT_PI2...\nleft; apply Rlt_trans with 0%R...\napply _PI2_RLT_0...\nrepeat simple apply Rmult_lt_0_compat...\napply rho_V_is_pos...\napply Rinv_0_lt_compat; simpl in |- *; prove_sup0...\nleft; apply Rlt_trans with (PI / 4)%R...\nrewrite <- Rmult_assoc...\napply PI4_RLT_PI2...\napply Rmult_le_compat_l...\nleft; apply rho_V_is_pos...\napply Rmult_le_compat_r...\nleft; apply Rinv_0_lt_compat; simpl in |- *; prove_sup0...\nunfold Rdiv in |- *; rewrite (Rmult_comm (/ 2)); rewrite Rmult_assoc;\n rewrite <- Rinv_mult_distr...\nQed.\n\n(**********)\nLemma m_rho_ub_0 : forall t : TimeT, (m_rho_ub t <= m t)%R.\nProof with trivial.\nintro; unfold m_rho_ub, m in |- *; repeat rewrite Rmult_assoc;\n apply Rmult_le_compat_l...\nleft; simpl in |- *; prove_sup0...\ncut (0 <= r_lb V <= r_V)%R...\ncut (0 <= sin_lb (rho_lb V * (t / 2)) <= sin (rho_V * (t / 2)))%R...\nintros; elim H; intros H1 H2; elim H0; intros H3 H4...\napply Rmult_le_compat...\ncut (0 < rho_lb V * (t / 2) <= rho_V * (t / 2))%R...\ncut (rho_V * (t / 2) <= PI / 2)%R...\nintros; elim H0; intros H1 H2; split...\nleft; apply sin_lb_gt_0...\napply Rle_trans with (rho_V * (t / 2))%R...\napply Rle_trans with (sin (rho_lb V * (t / 2)))...\ngeneralize\n (SIN (rho_lb V * (t / 2)) (Rlt_le 0 (rho_lb V * (t / 2)) H1)\n    (Rle_trans (rho_lb V * (t / 2)) (PI / 2) PI\n       (Rle_trans (rho_lb V * (t / 2)) (rho_V * (t / 2)) (PI / 2) H2 H)\n       (Rlt_le (PI / 2) PI PI2_Rlt_PI)))...\nintro H3; elim H3; intros H4 H5...\napply sin_incr_1...\nleft; apply (Rlt_trans (- (PI / 2)) 0 (rho_lb V * (t / 2)) _PI2_RLT_0 H1)...\napply Rle_trans with (rho_V * (t / 2))%R...\nleft;\n apply\n  (Rlt_trans (- (PI / 2)) 0 (rho_V * (t / 2)) _PI2_RLT_0\n     (Rlt_le_trans 0 (rho_lb V * (t / 2)) (rho_V * (t / 2)) H1 H2))...\nleft; apply Rlt_trans with (PI / 4)%R...\ngeneralize (rho_t_PI2 t); intro H; unfold Rdiv in |- *;\n replace (/ 4)%R with (/ 2 * / 2)%R...\nrepeat rewrite <- Rmult_assoc; apply Rmult_lt_compat_r...\napply Rinv_0_lt_compat; prove_sup0...\nrewrite <- Rinv_mult_distr...\ndiscrR...\ndiscrR...\napply PI4_RLT_PI2...\nsplit...\nunfold Rdiv in |- *; repeat simple apply Rmult_lt_0_compat...\napply rho_lb_pos...\napply Rlt_le_trans with MinT...\napply MinT_is_pos...\napply (cond_1 t)...\napply Rinv_0_lt_compat; prove_sup0...\napply Rmult_le_compat_r...\nleft; unfold Rdiv in |- *; apply Rmult_lt_0_compat...\napply Rlt_le_trans with MinT...\napply MinT_is_pos...\napply (cond_1 t)...\napply Rinv_0_lt_compat; prove_sup0...\nunfold rho_V in |- *...\nleft; apply rho_lb_0...\nsplit...\nunfold r_lb in |- *...\nunfold Rdiv in |- *; left; apply Rmult_lt_0_compat...\napply (TypeSpeed_pos V)...\napply Rinv_0_lt_compat; apply rho_ub_pos...\nunfold r_V in |- *; left; apply r_lb_0...\nQed.\n\n(**********)\nLemma m_rho_T_pos : forall t : TimeT, (0 < m t)%R.\nProof with trivial.\nintro t; unfold m in |- *; repeat simple apply Rmult_lt_0_compat...\nsimpl in |- *; prove_sup0...\napply r_V_is_pos...\ngeneralize (cond_1 t); generalize MinT_is_pos; intros H H0;\n generalize (Rlt_le_trans 0 MinT t H H0); clear H; \n intro H; apply sin_gt_0...\nrepeat simple apply Rmult_lt_0_compat...\napply rho_V_is_pos...\nunfold Rdiv in |- *; apply Rmult_lt_0_compat;\n try (apply Rinv_0_lt_compat; simpl in |- *; prove_sup0)...\ngeneralize (rho_t_PI2 t); intro H1; assert (Hyp : (0 < 2)%R)...\nprove_sup0...\ngeneralize\n (Rmult_lt_compat_r (/ 2) (rho_V * t) (PI / 2) (Rinv_0_lt_compat 2 Hyp) H1);\n rewrite Rmult_assoc; replace (PI / 2 * / 2)%R with (PI / 4)%R...\nintro H2; apply Rlt_trans with (PI / 4)%R...\napply (Rlt_trans (PI / 4) (PI / 2) PI PI4_RLT_PI2 PI2_Rlt_PI)...\nunfold Rdiv in |- *; rewrite Rmult_assoc; rewrite <- Rinv_mult_distr...\nQed.\n\nVariable T : TimeT.\n\nDefinition MaxDistance : R := (V * T + ConflictRange)%R.\nDefinition MinDistance : R := (m T - ConflictRange)%R.\nDefinition MaxDistance_ub : R := (V * MaxT + ConflictRange)%R.\nDefinition MinDistance_lb : R := (m_rho_ub MinT - ConflictRange)%R.\n\n(**********)\nLemma MaxDistance_ub_0 : (MaxDistance <= MaxDistance_ub)%R.\nunfold MaxDistance, MaxDistance_ub in |- *.\nrewrite (Rplus_comm (V * T)).\nrewrite (Rplus_comm (V * MaxT)).\napply Rplus_le_compat_l.\napply Rmult_le_compat_l.\nleft; apply (TypeSpeed_pos V).\napply (cond_2 T).\nQed.\n\n(**********)\nLemma MinT_MaxT : (MinT <= MaxT)%R.\nunfold MinT in |- *; pattern MaxT at 2 in |- *; rewrite <- (Rplus_0_r MaxT).\nunfold Rminus in |- *; apply Rplus_le_compat_l.\nunfold tstep in |- *; rewrite <- Ropp_0; left; apply Ropp_lt_gt_contravar;\n apply Rinv_0_lt_compat; prove_sup.\nQed.\n\n(**********)\nLemma MinDistance_lb_0 : (MinDistance_lb <= MinDistance)%R.\nProof with trivial.\nunfold MinDistance_lb, MinDistance in |- *; unfold Rminus in |- *;\n rewrite (Rplus_comm (m_rho_ub MinT)); rewrite (Rplus_comm (m T));\n apply Rplus_le_compat_l...\ncut (MinT <= MinT)%R...\nintro H; apply Rle_trans with (m MinT)...\napply (m_rho_ub_0 (mkTimeT MinT H MinT_MaxT))...\napply (m_le (mkTimeT MinT H MinT_MaxT) T)...\nsimpl in |- *; apply (cond_1 T)...\nright...\nQed.\n\n(*** Easy to prove with constructive reals ***)\n(*** Verified with Mapple                  ***)\nAxiom MinDistance_lb_majoration : (V + ConflictRange < MinDistance_lb)%R.\n\n(**********)\nLemma MinDistance_lb_pos : (0 < MinDistance_lb)%R.\nProof with trivial.\napply Rlt_trans with (V + ConflictRange)%R...\nunfold V, ConflictRange in |- *; simpl in |- *; prove_sup...\napply MinDistance_lb_majoration...\nQed.\n\n(**********)\nLemma MinDistance_pos : (0 < MinDistance)%R.\napply Rlt_le_trans with MinDistance_lb.\napply MinDistance_lb_pos.\napply MinDistance_lb_0.\nQed.\n\nDefinition MinBeta : R := (539 / 1000)%R.\n\nEnd constants.\n", "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/constants.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.29588680355380714}}
{"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\nRequire Export sequents.\n\nDefinition wf_bseq {o} (s : @baresequent o) :=\n  vswf_hypotheses [] (hyps s)\n  # wf_term (ctype (concl s))\n  # closed_type_baresequent s.\n\n(* This is a variant of [rule_true2] (which is equivalent to [rule_true])\n   that only needs [wf_bseq] and not [pwf_sequent].\n *)\nDefinition rule_true3 {o} lib (R : @rule o) : Type :=\n  forall wf    : wf_bseq (goal R),\n  forall cargs : args_constraints (sargs R) (hyps (goal R)),\n  forall hyps  : (forall s, LIn s (subgoals R) -> sequent_true2 lib s),\n    sequent_true2 lib (goal R).\n\nLemma pwf_sequent_implies_wf_bseq {o} :\n  forall (seq : @baresequent o),\n    pwf_sequent seq -> wf_bseq seq.\nProof.\n  introv wf.\n  unfold pwf_sequent, wf_sequent, wf_concl in wf; unfold wf_bseq; repnd; dands; auto.\nQed.\nHint Resolve pwf_sequent_implies_wf_bseq : slow.\n\n(* The other direction is not true because [rule_true] and [rule_true2] assume\n   that the extract is well-formed. *)\nLemma rule_true3_implies_rule_true2 {o} :\n  forall lib (R : @rule o), rule_true3 lib R -> rule_true2 lib R.\nProof.\n  introv rt wf args imp.\n  unfold rule_true3 in rt.\n  repeat (autodimp rt hyp); eauto 3 with slow.\nQed.\nHint Resolve rule_true3_implies_rule_true2 : slow.\n\nLemma rule_true3_implies_rule_true {o} :\n  forall lib (R : @rule o), rule_true3 lib R -> rule_true lib R.\nProof.\n  introv rt.\n  rw @rule_true_iff_rule_true2; eauto 3 with slow.\nQed.\nHint Resolve rule_true3_implies_rule_true : slow.\n\nDefinition wf_subgoals2 {o} (R : @rule o) :=\n  forall s, LIn s (subgoals R) -> wf_bseq s.\n\nLemma fold_wf_subgoals2 {o} :\n  forall R : @rule o,\n    (forall s, LIn s (subgoals R) -> wf_bseq s) = wf_subgoals2 R.\nProof. sp. Qed.\n\n(* This is a variant of [wf_rule] that uses [wf_bseq] instead of [pwf_sequent] *)\nDefinition wf_rule2 {o} (R : @rule o) :=\n  wf_bseq (goal R) -> wf_subgoals2 R.\n\n\n(*\n*** Local Variables:\n*** coq-load-path: (\".\" \"../util/\" \"../terms/\" \"../computation/\" \"../cequiv/\" \"../close/\")\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/per/sequents2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.29588680355380714}}
{"text": "(* Contribution to the Coq Library   V6.3 (July 1999)                    *)\nRequire Import securite.\n\nLemma POinv1rel7 :\n forall (l l0 : list C) (k k0 k1 k2 : K) (c c0 c1 c2 : C)\n   (d d0 d1 d2 d3 d4 d5 d6 d7 d8 d9 d10 d11 d12 d13 d14 d15 d16 d17 d18 d19\n    d20 : D),\n inv0\n   (ABSI (MBNaKab d7 d8 d9 k0) (MANbKabCaCb d4 d5 d6 k c c0)\n      (MABNaNbKeyK d d0 d1 d2 d3) l) ->\n inv1\n   (ABSI (MBNaKab d7 d8 d9 k0) (MANbKabCaCb d4 d5 d6 k c c0)\n      (MABNaNbKeyK d d0 d1 d2 d3) l) ->\n rel7\n   (ABSI (MBNaKab d7 d8 d9 k0) (MANbKabCaCb d4 d5 d6 k c c0)\n      (MABNaNbKeyK d d0 d1 d2 d3) l)\n   (ABSI (MBNaKab d18 d19 d20 k2) (MANbKabCaCb d15 d16 d17 k1 c1 c2)\n      (MABNaNbKeyK d10 d11 d12 d13 d14) l0) ->\n inv1\n   (ABSI (MBNaKab d18 d19 d20 k2) (MANbKabCaCb d15 d16 d17 k1 c1 c2)\n      (MABNaNbKeyK d10 d11 d12 d13 d14) l0).\n\nProof.\ndo 32 intro.\nunfold inv0, inv1, rel7 in |- *; intros know_c_c0_l know_Kas_Kbs and1.\nelim know_c_c0_l; intros know_c_l know_c0_l.\nelim know_Kas_Kbs; intros know_Kas know_Kbs.\nelim and1; intros eq_l0 t1.\nclear know_c_c0_l know_Kas_Kbs and1 t1.\nrewrite eq_l0.\nsplit.\n\n(* first part *)\napply D2.\nsimpl in |- *.\nrepeat apply C2 || apply C3 || apply C4.\napply equivncomp with (l ++ rngDDKKeyAB).\napply equivS3.\napply AlreadyInb; apply EP0; assumption.\napply D1; assumption.\ndiscriminate.\ndiscriminate.\n\n(* second part *)\napply D2.\nsimpl in |- *.\nrepeat apply C2 || apply C3 || apply C4.\napply equivncomp with (l ++ rngDDKKeyAB).\napply equivS3.\napply AlreadyInb; apply EP0; assumption.\napply D1; assumption.\ndiscriminate.\ndiscriminate.\nQed.", "meta": {"author": "coq-contribs", "repo": "otway-rees", "sha": "7956542fbb559fcda240c6059919a95ae4c10590", "save_path": "github-repos/coq/coq-contribs-otway-rees", "path": "github-repos/coq/coq-contribs-otway-rees/otway-rees-7956542fbb559fcda240c6059919a95ae4c10590/inv1rel7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.49609382947091957, "lm_q1q2_score": 0.2958868035538071}}
{"text": "(***************************************************************************\n* Principality of type inference for mini-ML with structural polymorphism  *\n* Jacques Garrigue, August 2008                                            *\n***************************************************************************)\n\nSet Implicit Arguments.\n\nRequire Import List Arith Metatheory Cardinal.\nRequire Import ML_SP_Definitions ML_SP_Unify.\n\nModule MkInfer(Cstr:CstrIntf)(Const:CstIntf).\n\nModule Unify := MkUnify(Cstr)(Const).\nImport Unify.\nImport MyEval.\nImport Rename.\nImport Sound.\nImport Infra.\nImport Defs.\nImport Metatheory_Env.Env.\n\nModule Mk2(Delta:DeltaIntf).\n\nModule MyEval2 := MyEval.Mk2(Delta).\nImport MyEval2.Rename2.\nImport Sound2.\nImport Unify.\nImport JudgInfra.\nImport Judge.\n\nDefinition unify K T1 T2 S :=\n  unify (1 + size_pairs S K ((T1,T2)::nil)) ((T1,T2)::nil) K S.\n\nDefinition fvs S K E :=\n  dom S \\u fv_in typ_fv S \\u dom K \\u fv_in kind_fv K \\u env_fv E.\n\n(** Variants looking up a kinding environment *)\n\nFixpoint close_fvars (n:nat)(K:kenv)(VK:vars)(Vs:vars) {struct n} : vars :=\n  match n with\n  | 0 => Vs\n  | S n' =>\n    match S.choose (S.inter VK Vs) with\n    | None => Vs\n    | Some x =>\n      let VK' := S.remove x VK in\n      let Vs' :=\n        match get x K with\n        | None => Vs\n        | Some k => Vs \\u kind_fv k\n        end\n      in close_fvars n' K VK' Vs'\n    end\n  end.\n    \nDefinition close_fvk K := close_fvars (length K) K (dom K).\n\nFixpoint split_env (A:Set) (B:vars) (E:env A) {struct E} : env A * env A :=\n  match E with\n  | nil => (nil, nil)\n  | xk::E' =>\n    let (Eb, EB) := split_env B E' in\n    if S.mem (fst xk) B then (Eb, xk::EB) else (xk::Eb, EB)\n  end.\n\nDefinition vars_subst S L :=\n  typ_fv_list (List.map (fun x => typ_subst S (typ_fvar x)) (S.elements L)).\n\nDefinition typinf_generalize K' E' L T1 :=\n  let ftve := close_fvk K' (env_fv E') in\n  let (K'', KA) := split_env ftve K' in\n  let B := close_fvk K' (typ_fv T1) in\n  let (_, KB) := split_env B K'' in\n  let (Bs, Ks) := split KB in\n  let Bs' := S.elements (S.diff B (ftve \\u dom KB)) in\n  let Ks' := List.map (fun x:var => @None ckind) Bs' in\n  let (_, KC) := split_env L K'' in\n  (KA & KC, sch_generalize (Bs++Bs') T1 (Ks++Ks')).\n\nFixpoint kdom (E : kenv) : vars :=\n  match E with\n  | nil => {}\n  | (x, Some _) :: E' => {{x}} \\u kdom E'\n  | _ :: E' => kdom E'\n  end.\n\nFixpoint trm_depth (t : trm) : nat :=\n  match t with\n  | trm_bvar _ => 0\n  | trm_fvar _ => 0\n  | trm_abs t1 => S (trm_depth t1)\n  | trm_let t1 t2 => S (Max.max (trm_depth t1) (trm_depth t2))\n  | trm_app t1 t2 => S (Max.max (trm_depth t1) (trm_depth t2))\n  | trm_cst _ => 0\n  end.\n\nLemma trm_depth_open : forall x t,\n  trm_depth (t ^ x) = trm_depth t.\nProof.\n  intros; unfold trm_open.\n  generalize 0; induction t; intros; simpl*.\n  destruct (n0 === n); reflexivity.\nQed.\n\nLemma lt_wf : forall n, Acc lt n.\nProof.\n  induction n.\n    apply Acc_intro; intros. elim (le_Sn_O _ H).\n  apply Acc_intro; intros.\n  unfold lt in H.\n  destruct (Lt.le_lt_or_eq _ _ (Le.le_S_n _ _ H)).\n    apply (Acc_inv IHn _ H0).\n  subst*.\nDefined.\n\nLemma dom_inv_abs : forall t t1 x,\n   Acc lt (trm_depth t) ->\n   t = trm_abs t1 -> Acc lt (trm_depth (t1 ^ x)).\nProof.\n  introv P eq.\n  rewrite eq in P.\n  rewrite trm_depth_open.\n  simpl in P.\n  pose (P1 := le_n (S (trm_depth t1))).\n  exact (Acc_inv P _ P1).\nDefined.\n\nLemma lt_max_l : forall n1 n2, n1 < (S (Max.max n1 n2)).\nProof.\n  intros; puts (Max.le_max_l n1 n2); auto with arith.\nQed.\n\nLemma lt_max_r : forall n1 n2, n2 < (S (Max.max n1 n2)).\nProof.\n  intros; puts (Max.le_max_r n1 n2); auto with arith.\nQed.\n\nLtac dom_inv_tac :=\n  intros t t1 t2 P eq;\n  rewrite eq in P;\n  simpl in P;\n  try rewrite trm_depth_open;\n  solve [exact (Acc_inv P _ (lt_max_l (trm_depth t1) (trm_depth t2)))\n        |exact (Acc_inv P _ (lt_max_r (trm_depth t1) (trm_depth t2)))].\n\nLemma dom_inv_app1 : forall t t1 t2,\n   Acc lt (trm_depth t) ->\n   t = trm_app t1 t2 -> Acc lt (trm_depth t1).\nProof. dom_inv_tac. Defined.\n\nLemma dom_inv_app2 : forall t t1 t2,\n   Acc lt (trm_depth t) ->\n   t = trm_app t1 t2 -> Acc lt (trm_depth t2).\nProof. dom_inv_tac. Defined.\n\nLemma dom_inv_let1 : forall t t1 t2,\n   Acc lt (trm_depth t) ->\n   t = trm_let t1 t2 -> Acc lt (trm_depth t1).\nProof. dom_inv_tac. Defined.\n\nLemma dom_inv_let2 : forall x t t1 t2,\n   Acc lt (trm_depth t) ->\n   t = trm_let t1 t2 -> Acc lt (trm_depth (t2 ^ x)).\nProof. intro; dom_inv_tac. Defined.\n\nFixpoint typinf (K:kenv) (E:Defs.env) (t:trm) (T:typ) (L:vars) (S:subs)\n  (h:Acc lt (trm_depth t)) {struct h} : option (kenv * subs) * vars :=\n  match t as t' return t = t' -> option (kenv * subs) * vars with\n  | trm_bvar _ => fun eq => (None, L)\n  | trm_fvar x => fun eq =>\n    match get x E with\n    | None => (None, L)\n    | Some M =>\n      let Vs := proj1_sig (var_freshes L (sch_arity M)) in\n      (unify (K & kinds_open_vars (sch_kinds M) Vs) (M ^ Vs) T S,\n       L \\u mkset Vs)\n    end\n  | trm_abs t1 => fun eq =>\n    let x := proj1_sig (var_fresh (dom E \\u trm_fv t1)) in\n    let v1 := proj1_sig (var_fresh L) in\n    let v2 := proj1_sig (var_fresh (L \\u {{v1}})) in\n    match unify K (typ_arrow (typ_fvar v1) (typ_fvar v2)) T S with\n    | None => (None, L)\n    | Some (K',S') =>\n      typinf K' (E & x ~ Sch (typ_fvar v1) nil) (t1 ^ x) (typ_fvar v2)\n        (L \\u {{v1}} \\u {{v2}}) S' (dom_inv_abs x h eq)\n    end\n  | trm_let t1 t2 => fun eq =>\n    let v := proj1_sig (var_fresh L) in\n    match typinf K E t1 (typ_fvar v) (L \\u {{v}}) S (dom_inv_let1 h eq) with\n    | (Some (K0,S'), L') =>\n      let K' := Env.map (kind_subst S') K0 in\n      let E' := Env.map (sch_subst S') E in\n      let T1 := typ_subst S' (typ_fvar v) in\n      let (KA, M) := typinf_generalize K' E' (vars_subst S' (kdom K)) T1 in\n      let x := proj1_sig (var_fresh (dom E \\u trm_fv t1 \\u trm_fv t2)) in\n      typinf KA (E & x ~ M) (t2 ^ x) T L' S' (dom_inv_let2 x h eq)\n    | none => none\n    end\n  | trm_app t1 t2 => fun eq =>\n    let v := proj1_sig (var_fresh L) in\n    match typinf K E t1 (typ_arrow (typ_fvar v) T) (L \\u {{v}}) S\n      (dom_inv_app1 h eq) with\n    | (Some (K',S'), L') =>\n        typinf K' E t2 (typ_fvar v) L' S' (dom_inv_app2 h eq)\n    | none => none\n    end\n  | trm_cst c => fun eq =>\n    let M := Delta.type c in\n    let Vs := proj1_sig (var_freshes L (sch_arity M)) in\n    (unify (K & kinds_open_vars (sch_kinds M) Vs) (M ^ Vs) T S,\n     L \\u mkset Vs)\n  end (refl_equal t).\n\nDefinition typinf0 K E t T L S := typinf K E t T L S (lt_wf _).\n\nLemma normalize_typinf : forall K E t T L S h,\n  typinf K E t T L S h = typinf0 K E t T L S.\nProof.\n  intros.\n  unfold typinf0; apply f_equal. apply ProofIrrelevance.proof_irrelevance.\nQed.\n\nDefinition typinf' E trm :=\n  let v  :=  Variables.var_default in\n  let min_vars := S.singleton v in\n  let V := typ_fvar v in\n  match\n    typinf empty E trm V min_vars empty (lt_wf _)\n  with (None, _) => None\n  | (Some (k, s), _) =>\n    Some (map (kind_subst s) k, typ_subst s V)\n  end.\n\nLemma env_prop_type_compose : forall S1 S2,\n  env_prop type S1 -> env_prop type S2 -> env_prop type (compose S1 S2).\nProof.\n  unfold compose.\n  intros.\n  intro; intros.\n  destruct* (in_app_or _ _ _ H1).\n  destruct (in_map_inv _ _ _ _ H2) as [T [Eq B']].\n  subst*.\nQed.\n\nHint Resolve env_prop_type_compose : core.\n\nLemma unify_rel_all_kind_types :\n  forall (P:typ->Prop) k k0 kc (v1:Cstr.valid kc),\n  All_kind_types P (Some k) -> All_kind_types P (Some k0) ->\n  let krs := kind_rel k ++ kind_rel k0 in\n  All_kind_types P (Some (Kind v1 (unify_coherent krs))) /\\\n  (forall T1 T2,\n   In (T1, T2) (snd (unify_kind_rel krs nil (Cstr.unique kc) nil)) ->\n   P T1 /\\ P T2).\nProof.\n  unfold All_kind_types; intros.\n  simpl in *.\n  puts (list_forall_app H H0).\n  clear H H0.\n  unfold list_snd in H1; rewrite <- map_app in H1.\n  set (kr':=@nil (Cstr.attr*typ)).\n  set (pairs':=@nil (typ*typ)).\n  assert (list_forall P (List.map (@snd _ _) kr')) by simpl*.\n  assert (forall T1 T2, In (T1, T2) pairs' -> P T1 /\\ P T2) by simpl*.\n  gen kr' pairs'.\n  induction (kind_rel k ++ kind_rel k0); simpl; intros. auto.\n  destruct a.\n  inversion_clear H1.\n  case_eq (Cstr.unique kc a); introv R.\n    case_eq (assoc Cstr.eq_dec a kr'); intros.\n      apply* IHl.\n      simpl; intros.\n      destruct* H4.\n      inversions H4.\n      split2*.\n      clear -H H1.\n      apply* (list_forall_out H).\n      puts (assoc_sound _ _ _ H1).\n      apply (in_map (@snd _ _) _ _ H0).\n    apply* IHl.\n    simpl*.\n  apply* IHl.\n  simpl*.\nQed.\n\nLemma incl_remove_env : forall (A:Set) v (K:env A),\n  incl (remove_env K v) K.\nProof.\n  induction K; simpl; intro; intros. auto.\n  destruct a.\n  destruct* (v == v0).\nQed.\n\nLemma kenv_ok_remove_env : forall K v,\n  kenv_ok K -> kenv_ok (remove_env K v).\nProof.\n  intros; kenv_ok_solve; auto.\n  intro; intros.\n  apply (H0 x).\n  apply* (incl_remove_env v K).\nQed.\n\nHint Resolve kenv_ok_remove_env : core.\n\nLemma unify_type : forall K' S' h pairs K S,\n  Unify.unify h pairs K S = Some (K', S') ->\n  is_subst S ->\n  env_prop type S ->\n  kenv_ok K ->\n  (forall T1 T2, In (T1, T2) pairs -> type T1 /\\ type T2) ->\n  kenv_ok K' /\\ env_prop type S' /\\ is_subst S'.\nProof.\n  induction h; simpl; intros. discriminate.\n  set (h0 := pairs_size S pairs + 1) in *.\n  clearbody h0; gen pairs; induction h0; simpl; intros. discriminate.\n  destruct pairs. inversions* H.\n  destruct p.\n  assert (type t /\\ type t0). apply* H3.\n  destruct H4.\n  puts (typ_subst_type H1 H4).\n  puts (typ_subst_type H1 H5).\n  case_rewrite R1 (typ_subst S t); try solve [inversion H6];\n    case_rewrite R2 (typ_subst S t0); try solve [inversion H7];\n      try (unfold unify_nv in H;\n           case_rewrite R3 (S.mem v (typ_fv (typ_arrow t1 t2)));\n           case_rewrite R4 (get_kind v K); apply* IHh).\n    destruct (v == v0). apply* (IHh0 pairs).\n    simpl in H.\n    unfold unify_vars in H.\n    assert (Hok: forall k, ok (remove_env (remove_env K v) v0 & v0 ~ k)).\n      intro; constructor.\n      repeat apply* ok_remove_env.\n      rewrite* dom_remove_env.\n    assert (Horig: forall x a,\n      In (x, a) (remove_env (remove_env K v) v0) -> All_kind_types type a).\n      intros; apply (proj2 H2 x a).\n      puts (incl_remove_env v0 _ _ H8).\n      apply* (incl_remove_env _ _ _ H9).\n    case_rewrite R3 (get_kind v K); case_rewrite R4 (get_kind v0 K);\n      try poses Aktc (proj2 H2 _ _ (binds_in (get_kind_binds _ _ R3)));\n      try poses Aktc0 (proj2 H2 _ _ (binds_in (get_kind_binds _ _ R4)));\n      simpl unify_kinds in H.\n          destruct c as [kc kv kr kh].\n          destruct c0 as [kc0 kv0 kr0 kh0].\n          destruct (Cstr.valid_dec (Cstr.lub kc kc0)); try discriminate.\n          replace kr with (kind_rel (Kind kv kh)) in H by simpl*.\n          replace kr0 with (kind_rel (Kind kv0 kh0)) in H by simpl*.\n          destruct* (unify_rel_all_kind_types v1 Aktc Aktc0).\n          apply* IHh; clear IHh H. split2*.\n          intro; intros.\n          unfold concat in H; destruct* (in_app_or _ _ _ H).\n        destruct c as [kc kv kr kh].\n        simpl app in H.\n        apply* IHh. split2*.\n      cbv iota beta in H. simpl app in H.\n      apply* IHh. split2*.\n    cbv iota beta in H. simpl app in H.\n    apply* IHh. split2*.\n  apply* IHh0; clear IHh IHh0 H.\n  simpl; intros.\n  inversions H6.\n  inversions H7.\n  destruct H. inversions* H.\n  destruct H. inversions* H.\n  apply* H3.\nQed.\n\nLemma split_env_ok : forall (A:Set) (B:vars) (E Eb EB:env A),\n  split_env B E = (Eb, EB) -> ok E ->\n  ok (EB & Eb) /\\ disjoint B (dom Eb) /\\ dom EB << B /\\\n  incl E (EB & Eb) /\\ incl (EB & Eb) E.\nProof.\n  induction E; simpl; intros.\n    inversions H. simpl. split2*.\n  destruct a.\n  case_rewrite R1 (split_env B E).\n  simpl in *.\n  case_rewrite R2 (S.mem v B).\n    inversions H; clear H.\n    inversions H0; clear H0.\n    destruct* (IHE Eb e0) as [Hok [Dis [Dom [I1 I2]]]]; clear IHE.\n    destruct (ok_concat_inv _ _ Hok).\n    case_eq (get v (e0 & Eb)); intros.\n      elim (binds_fresh (in_ok_binds _ _ (I2 _ (binds_in H1)) H2) H4).\n    split.\n      apply* disjoint_ok.\n        apply* (@ok_push _ e0 v a).\n      simpl*.\n    split2*.\n    split.\n      simpl. use (S.mem_2 R2).\n    split; intro; simpl; intros.\n      destruct H3. apply* in_or_concat.\n      puts (I1 _ H3). destruct* (in_app_or _ _ _ H5).\n    destruct* (in_app_or _ _ _ H3).\n    destruct* H5.\n  inversions H; clear H.\n  inversions H0; clear H0.\n  destruct* (IHE e EB) as [Hok [Dis [Dom [I1 I2]]]]; clear IHE.\n  destruct (ok_concat_inv _ _ Hok).\n  case_eq (get v (EB & e)); intros.\n    elim (binds_fresh (in_ok_binds _ _ (I2 _ (binds_in H1)) H2) H4).\n  split.\n    apply* disjoint_ok.\n    apply* (@ok_push _ e v a).\n  simpl*.\nQed.\n\nLemma proper_instance_well_subst : forall S K K' Ks Us,\n  env_prop type S ->\n  well_subst K K' S ->\n  kenv_ok K' ->\n  proper_instance K Ks Us ->\n  proper_instance K' (List.map (kind_subst S) Ks) (List.map (typ_subst S) Us).\nProof.\n  intros.\n  destruct H2 as [HUs HW].\n  split.\n    destruct HUs.\n    split2*. clear -H H3. induction H3; simpl*.\n  remember Us as Ts.\n  pattern Ts at 2.\n  pattern Ts at 2 in HW.\n  rewrite HeqTs in *.\n  clear HeqTs.\n  destruct HUs.\n  gen Ks; induction H3; destruct Ks; simpl; intros; try discriminate. auto.\n  inversions HW; clear HW.\n  constructor; auto.\n  rewrite* <- kind_subst_open.\nQed.\n\nLemma kenv_ok_map : forall K S,\n  kenv_ok K -> env_prop type S -> kenv_ok (map (kind_subst S) K).\nProof.\n  intros.\n  split2*.\n  destruct H.\n  intro; intros.\n  destruct (in_map_inv _ _ _ _ H2) as [b [Hb B]].\n  subst.\n  apply* All_kind_types_subst.\nQed.\n\nLemma kenv_ok_subst : forall K' K Ks Ys S,\n  env_prop type S ->\n  kenv_ok (K & kinds_open_vars Ks Ys) ->\n  kenv_ok K' ->\n  fresh (dom K') (length Ks) Ys ->\n  kenv_ok (K' & map (kind_subst S) (kinds_open_vars Ks Ys)).\nProof.\n  introv TS HK HK' Fr.\n  apply* kenv_ok_concat.\n  apply* kenv_ok_map.\nQed.\n\nLemma env_ok_map : forall E S,\n  env_ok E -> env_prop type S -> env_ok (map (sch_subst S) E).\nProof.\n  intros; split2*.\n  intro; intros.\n  destruct (in_map_inv _ _ _ _ H1) as [b [Hb B]].\n  subst.\n  apply* sch_subst_type.\n  apply* (proj2 H x).\nQed.\n\nHint Resolve kenv_ok_subst env_ok_map : core.\n\nLemma well_subst_extend : forall K S K' Ks Ys,\n  env_prop type S ->\n  well_subst K K' S ->\n  fresh (dom S \\u dom K') (length Ks) Ys ->\n  well_subst (K & kinds_open_vars Ks Ys)\n     (K' & map (kind_subst S) (kinds_open_vars Ks Ys)) S.\nProof.\n  introv TS WS Fr.\n  intro; intros.\n  binds_cases H.\n    puts (WS _ _ B).\n    inversions H. auto.\n    simpl. rewrite <- H1.\n    apply* wk_kind.\n  rewrite typ_subst_fresh by simpl*.\n  destruct* k as [[kc kv kr kh]|].\n  simpl.\n  apply~ wk_kind.\n  use (binds_map (kind_subst S) B0).\nQed.\n\nLemma typing_typ_well_subst : forall gc S K K' E t T,\n  env_prop type S ->\n  well_subst K K' S ->\n  kenv_ok K' ->\n  K ; E |gc|= t ~: T -> \n  K'; map (sch_subst S) E |gc|= t ~: (typ_subst S T).\nProof.\n  introv TS WS HK' Typ.\n  gen K'; induction Typ; intros.\n  (* Var *)\n  rewrite~ sch_subst_open. apply* typing_var.\n  destruct M as [T Ks]; simpl in *.\n  apply* proper_instance_well_subst.\n  (* Abs *)\n  simpl.\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  assert (y \\notin L) by auto.\n  use (H1 _ H2 _ WS HK').\n  (* Let *)\n  apply_fresh* (@typing_let gc (sch_subst S M)\n    (L1 \\u dom S \\u fv_in typ_fv S \\u sch_fv M \\u dom K \\u dom K')) as y.\n    clear H1 H2. clear L2 T2 t2.\n    simpl. intros Ys Fr.\n    destruct M as [T Ks]; simpl in *.\n    rewrite map_length in Fr.\n    assert (HK: kenv_ok (K & kinds_open_vars Ks Ys)).\n      assert (fresh L1 (length Ks) Ys) by auto*.\n      use (H _ H1).\n    rewrite* <- sch_subst_open_vars.\n    rewrite* <- kinds_subst_open_vars.\n    apply* H0; clear H H0.\n    apply* well_subst_extend.\n  replace (y ~ sch_subst S M) with (map (sch_subst S) (y ~ M)) by simpl*.\n  rewrite <- map_concat.\n  apply* H2.\n  (* App *)\n  simpl in IHTyp1; 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 _ H2).\n  destruct (Delta.type c) as [T Ks]; simpl in *.\n  apply* proper_instance_well_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  apply* (H1 Xs); clear H1.\n    apply* well_subst_extend.\n  forward~ (H0 Xs); intro Typ.\n  apply* (@kenv_ok_subst K' K).\nQed.\n\nLemma map_compose : forall (A:Set) (f f1 f2:A->A) E,\n  (forall a, f1 (f2 a) = f a) ->\n  map f1 (map f2 E) = map f E.\nProof.\n  intros.\n  induction* E.\n  simpl. destruct a. simpl. rewrite H. rewrite* IHE.\nQed.\n\nLemma map_sch_subst_extend : forall S S0 E,\n  extends S S0 ->\n  map (sch_subst S) (map (sch_subst S0) E) = map (sch_subst S) E.\nProof.\n  intros.\n  apply map_compose.\n  intros.\n  destruct a as [T Ks]; unfold sch_subst; simpl.\n  rewrite* (H T).\n  apply (f_equal (Sch (typ_subst S T))).\n  induction Ks; simpl*.\n  rewrite IHKs.\n  rewrite* (@kind_subst_combine S).\nQed.\n\nLemma kenv_ok_sch_kinds : forall K M Xs,\n  kenv_ok K ->\n  scheme M ->\n  fresh (dom K) (sch_arity M) Xs ->\n  kenv_ok (K & kinds_open_vars (sch_kinds M) Xs).\nProof.\n  split.\n    apply* disjoint_ok.\n    apply* ok_combine_fresh.\n  apply env_prop_concat. apply (proj2 H).\n  apply list_forall_env_prop.\n  destruct* (H0 Xs).\n  clear -H3; induction H3. simpl*.\n  simpl; constructor; auto.\n  unfold kind_open. unfold typ_open_vars in H3.\n  apply* All_kind_types_map.\nQed.\n\nLemma kind_subst_extend : forall S' S k,\n  extends S' S -> kind_subst S' (kind_subst S k) = kind_subst S' k.\nProof.\n  intros. apply* kind_subst_combine. \nQed.\n\nLemma well_subst_compose : forall S S' K1 K2 K3,\n  extends S' S ->\n  well_subst K1 K2 S -> well_subst K2 K3 S' -> well_subst K1 K3 S'.\nProof.\n  intros.\n  intro; intros.\n  puts (H0 _ _ H2).\n  inversions H3; clear H3.\n    destruct~ k; discriminate.\n  puts (H1 _ _ H7).\n  inversions* H3.\n  destruct k0; try discriminate.\n  fold (typ_subst S' (typ_fvar x)) in H9.\n  fold (typ_subst S (typ_fvar Z)) in H5.\n  rewrite H5 in H9.\n  rewrite H in H9.\n  rewrite <- H9.\n  rewrite* <- (@kind_subst_extend S' S).\n  rewrite <- H4.\n  simpl. apply* wk_kind.\n  refine (entails_trans H12 _).\n  apply* kind_subst_entails.\nQed.\n\nLemma well_subst_extends : forall K K0 S S0,\n  extends S S0 ->\n  well_subst K0 K S ->\n  well_subst (map (kind_subst S0) K0) K S.\nProof.\n  intros; intro; intros.\n  destruct (binds_map_inv _ _ H1) as [k1 [Hk1 Bk1]].\n  subst k.\n  rewrite* (kind_subst_combine S).\nQed.\n\nHint Resolve well_subst_extends : core.\n\nLemma kind_entails_fv : forall k1 k2,\n  kind_entails k1 k2 -> kind_fv k2 << kind_fv k1.\nProof.\n  unfold kind_entails; intros.\n  destruct k2.\n    destruct* k1.\n    unfold kind_fv; simpl.\n    destruct H.\n    clear H; induction (kind_rel c); simpl; intros y Hy. auto.\n    destruct (S.union_1 Hy).\n      apply* (in_typ_fv (snd a)).\n      apply* in_map.\n    apply* IHl.\n  intros y Hy. elim (in_empty Hy).\nQed.\n\nLemma typ_fv_subst0 : forall S T,\n  typ_fv (typ_subst S T) << S.diff (typ_fv T) (dom S) \\u fv_in typ_fv S.\nProof.\n  induction T; simpl; intros x Hx. elim (in_empty Hx).\n    case_rewrite R1 (get v S).\n      use (fv_in_spec typ_fv _ _ _ (binds_in R1)).\n    puts (get_none_notin _ R1).\n    simpl in Hx. auto.\n  auto.\nQed.\n\nLemma typ_fv_subst : forall S T,\n  typ_fv (typ_subst S T) << typ_fv T \\u fv_in typ_fv S.\nProof.\n  intros; intros y Hy.\n  use (typ_fv_subst0 _ _ Hy).\nQed.\n\nLemma kind_fv_subst : forall S k,\n  kind_fv (kind_subst S k) << S.diff (kind_fv k) (dom S) \\u fv_in typ_fv S.\nProof.\n  intros.\n  destruct k as [[kc kv kr kh]|].\n    unfold kind_fv; simpl.\n    clear kh; induction kr; simpl; intros x Hx; auto.\n    destruct* (S.union_1 Hx).\n    use (typ_fv_subst0 _ _ H).\n  unfold kind_fv; simpl*.\nQed.\n\nDefinition Gc := (false, GcLet).\n\nDefinition soundness_spec h t K0 E T L0 S0 K S L :=\n  trm_depth t < h ->\n  typinf K0 E t T L0 S0 (lt_wf _) = (Some (K, S), L) ->\n  is_subst S0 -> env_prop type S0 ->\n  kenv_ok K0 -> disjoint (dom S0) (dom K0) ->\n  fvs S0 K0 E \\u typ_fv T << L0 ->\n  env_ok E -> type T ->\n  extends S S0 /\\ env_prop type S /\\ is_subst S /\\\n  kenv_ok K /\\ disjoint (dom S) (dom K) /\\\n  well_subst K0 (map (kind_subst S) K) S /\\\n  (fvs S K E \\u L0 << L /\\\n  map (kind_subst S) K; map (sch_subst S) E |Gc|= t ~: typ_subst S T).\n\nLemma soundness_ind : forall h t K0 E T L0 S0 K S L s x,\n  scheme s ->\n  fresh L0 (sch_arity s) x ->\n  unify (K0 & kinds_open_vars (sch_kinds s) x) (sch_open_vars s x) T S0 =\n    Some (K, S) ->\n  (kenv_ok (K0 & kinds_open_vars (sch_kinds s) x) ->\n   extends S S0 -> kenv_ok K ->\n   unifies S ((sch_open_vars s x, T) :: nil) ->\n   (fvs S K E \\u L0 << L /\\\n   map (kind_subst S0) (K0 & kinds_open_vars (sch_kinds s) x);\n   map (sch_subst S0) E |Gc|= t ~: sch_subst S0 s ^^ typ_fvars x)) ->\n  soundness_spec h t K0 E T L0 S0 K S L.\nProof.\n  intros until x; intros Hs f HI Typ Ht _ HS0 HTS0 HK0 Dis HL0 HE HT.\n  unfold unify in HI.\n  poses Fr (fresh_sub _ _ f HL0).\n  assert (kenv_ok (K0 & kinds_open_vars (sch_kinds s) x)).\n    apply* kenv_ok_sch_kinds.\n    unfold fvs in Fr; auto.\n  destruct* (unify_kinds_ok _ _ HI HS0).\n    unfold fvs in Fr. rewrite dom_concat. rewrite* dom_kinds_open_vars.\n  poses Hext (typ_subst_extend _ _ _ HS0 HI).\n  destruct* (unify_type _ _ HI).\n    simpl; intros.\n    destruct* H2.\n    inversions H2; clear H2.\n    split2*.\n    unfold sch_open_vars.\n    destruct* (Hs x).\n  poses HU (unify_types _ _ _ HI HS0).\n  destruct* Typ.\n  intuition.\n    intro; intros.\n    apply H7.\n    apply* binds_concat_ok.\n  rewrite <- (map_sch_subst_extend E Hext).\n  rewrite* <- (HU (sch_open_vars s x) T).\n  rewrite* <- Hext.\n  unfold fvs in Fr.\n  rewrite* sch_subst_open_vars.\n  poses Hkext (fun k => sym_eq (kind_subst_combine _ _ _ k Hext)).\n  rewrite (map_map_env _ _ _ K Hkext).\n  apply* typing_typ_well_subst.\n    rewrite* <- (map_map_env _ _ _ K Hkext).\n  repeat apply* kenv_ok_map.\nQed.\n\nLemma well_kinded_open_vars : forall S K Ks Xs,\n  fresh (dom S \\u dom K) (length Ks) Xs ->\n  env_prop type S ->\n  list_forall2\n     (well_kinded (map (kind_subst S) (K & kinds_open_vars Ks Xs)))\n     (kinds_open (List.map (kind_subst S) Ks) (typ_fvars Xs))\n     (typ_fvars Xs).\nProof.\n  unfold kinds_open_vars, kinds_open; intros.\n  rewrite map_concat.\n  rewrite map_combine.\n  rewrite map_map.\n  rewrite <- (map_ext (fun k => kind_open (kind_subst S k) (typ_fvars Xs))).\n    rewrite <- (map_map (kind_subst S) (fun k => kind_open k (typ_fvars Xs))).\n    refine (well_kinded_combine _ _ Xs nil _).\n    rewrite dom_map.\n    rewrite* map_length.\n  intros. rewrite* kind_subst_open_vars.\nQed.\n\nLemma fv_in_typ_subst : forall S S0,\n  fv_in typ_fv (map (typ_subst S) S0) <<\n  S.diff (fv_in typ_fv S0) (dom S) \\u fv_in typ_fv S.\nProof.\n  induction S0; intros y Hy; simpl in *; sets_simpl.\n  destruct a. simpl in Hy.\n  sets_solve.\n  use (typ_fv_subst0 _ _ H).\nQed.\n\nLemma fv_in_compose : forall S S0,\n  fv_in typ_fv (compose S S0) <<\n  S.diff (fv_in typ_fv S0) (dom S) \\u fv_in typ_fv S.\nProof.\n  intros. unfold compose.\n  rewrite fv_in_concat.\n  sets_solve.\n  apply* fv_in_typ_subst.\nQed.\n\nHint Resolve ok_remove_env : core.\n\nLemma ok_remove_add_env : forall (A:Set) E v (a:A),\n  ok E -> ok (remove_env E v & v ~ a).\nProof.\n  intros. apply* ok_push.\n  rewrite* dom_remove_env.\nQed.\n\nHint Resolve ok_remove_add_env : core.\n\nLemma kind_subst_id : forall k, kind_subst id k = k.\nProof.\n  intros.\n  destruct k as [[kc kv kr kh]|]; simpl*.\n  apply kind_pi; simpl*.\n  clear kh; induction* kr.\n  destruct a; simpl. rewrite IHkr. rewrite* typ_subst_id.\nQed.\n\nLemma fv_in_kind_subst : forall S K,\n  fv_in kind_fv (map (kind_subst S) K) <<\n    S.diff (fv_in kind_fv K) (dom S) \\u fv_in typ_fv S.\nProof.\n  induction K; simpl; intros y Hy. auto.\n  destruct a. simpl in Hy.\n  use (kind_fv_subst S k).\nQed.\n\nLemma unify_keep_fv' : forall K S E h pairs K0 S0,\n  Unify.unify h pairs K0 S0 = Some (K, S) ->\n  is_subst S0 -> ok K0 ->\n  fvs S K E << fvs S0 K0 E \\u all_fv id pairs.\nProof.\n  intros until 2.\n  apply* (unify_ind (K':=K) (S':=S)\n    (fun K0 S0 pairs => ok K0 -> fvs S K E << fvs S0 K0 E \\u all_fv id pairs));\n    clear H H0 K0 S0 pairs h.\n       intros until K1.\n       unfold K1, S1, fvs; clear K1 S1.\n       intros _ R1 R2 _ _ _ R4 IH HK0 y Hy.\n       forward ~IH as G; clear IH.\n       unfold all_fv; simpl. repeat rewrite typ_subst_id.\n       fold (all_fv id pairs).\n       rewrite dom_remove_env in G; auto. simpl in G.\n       puts (G _ Hy); clear G Hy.\n       sets_solve.\n         unfold compose in H0; rewrite dom_concat in H0. rewrite dom_map in H0.\n         simpl in H0.\n         puts (typ_fv_subst S0 t). rewrite R1 in H. simpl in H.\n         use (singleton_subset H).\n        puts (fv_in_compose (v ~ T) S0 H0).\n        simpl in H.\n        puts (typ_fv_subst S0 t0). rewrite R2 in H1. auto.\n       use (fv_in_remove_env _ _ K0 H0).\n      intros until K1.\n      unfold K1, S1, fvs; clear K1 S1.\n      intros Uk _ R1 R2 HS0 HS1 n IH HK0 y Hy.\n      forward ~IH as G; clear IH.\n      puts (G _ Hy); clear G Hy.\n      unfold all_fv; simpl. repeat rewrite typ_subst_id.\n      fold (all_fv id pairs).\n      rewrite dom_concat in H.\n      do 2 rewrite dom_remove_env in H; auto. simpl in H.\n      puts (typ_fv_subst S0 t). rewrite R1 in H0. simpl in H0.\n      puts (singleton_subset H0); clear H0.\n      puts (typ_fv_subst S0 t0). rewrite R2 in H0. simpl in H0.\n      puts (singleton_subset H0); clear H0.\n      puts (unify_kinds_fv _ _ id Uk).\n      rewrite all_fv_app in H.\n      rewrite kind_subst_id in H0.\n      puts (get_kind_fv_in id v K0).\n      puts (get_kind_fv_in id v0 K0).\n      puts (fv_in_kind_subst id K0).\n      replace (fv_in typ_fv id) with {} in H5 by (unfold id; simpl*).\n      sets_solve.\n         unfold compose in H6; rewrite dom_concat in H6. rewrite dom_map in H6.\n         simpl in H6. auto.\n        puts (fv_in_compose _ _ H6). simpl in H. auto.\n       auto.\n      puts (fv_in_remove_env _ _ (remove_env K0 v) H).\n      use (fv_in_remove_env _ _ K0 H6).\n     unfold all_fv; simpl; intros. use (H3 H4).\n    unfold all_fv; simpl; intros. use (H3 H4).\n   unfold all_fv; simpl; intros.\n   repeat rewrite typ_subst_id in *.\n   puts (typ_fv_subst S0 t).\n   puts (typ_fv_subst S0 t0).\n   rewrite H1 in H5; rewrite H2 in H6.\n   simpl in *.\n   puts (H3 H4).\n   clear -H5 H6 H7.\n   unfold fvs in *. auto.\n  unfold all_fv; simpl; intros.\n  use (H H0).\nQed.\n\nLemma soundness_var : forall h L0 v K0 E T S0 K S L,\n  soundness_spec h (trm_fvar v) K0 E T L0 S0 K S L.\nProof.\n  intros; intros Ht HI HS0 HTS0 HK0 Dis HL0 HE HT.\n  poses HI' HI; simpl in HI.\n  case_rewrite R1 (get v E).\n  destruct (var_freshes L0 (sch_arity s));\n    simpl proj1_sig in HI.\n  inversions HI; clear HI. rename H0 into HI.\n  refine (soundness_ind _ _ _ HI _ _ HI' _ _ _ _ _ _ _); auto.\n    apply (proj2 HE _ _ (binds_in R1)).\n  split2*.\n    unfold unify in HI.\n    forward~ (unify_keep_fv' _ _ HI HS0 (E:=E)) as G.\n    unfold fvs in *.\n    rewrite dom_concat in G; rewrite fv_in_concat in G.\n    unfold all_fv in G; simpl in G.\n    rewrite dom_kinds_open_vars in G; auto.\n    repeat rewrite typ_subst_id in G.\n    unfold sch_open_vars, typ_open_vars in G; simpl in G.\n    puts (fv_in_kinds_open_vars (sch_kinds s) x).\n    puts (fv_in_spec sch_fv _ _ _ (binds_in R1)).\n    fold env_fv in H4.\n    unfold sch_fv in H4; simpl in H4.\n    puts (typ_fv_open (typ_fvars x) (sch_type s)).\n    rewrite typ_fv_typ_fvars in H5.\n    auto.\n  apply* typing_var.\n    apply* kenv_ok_map.\n  split.\n    simpl; rewrite map_length.\n    rewrite (fresh_length _ _ _ f). apply types_typ_fvars.\n  destruct s as [Us Ks]; simpl.\n  apply* well_kinded_open_vars.\n  unfold fvs in HL0.\n  use (fresh_sub _ _ f HL0).\nQed.\n\nLemma kinds_subst_cst : forall S c,\n  List.map (kind_subst S) (sch_kinds (Delta.type c)) = sch_kinds (Delta.type c).\nProof.\n  intros.\n  assert (forall x, x \\notin kind_fv_list (sch_kinds (Delta.type c))).\n    intros x Hx.\n    assert (x \\in sch_fv (Delta.type c)).\n      unfold sch_fv.\n      sets_solve.\n    rewrite Delta.closed in H.\n    elim (in_empty H).\n  induction (sch_kinds (Delta.type c)). auto.\n  simpl in *.\n  rewrite IHl.\n    rewrite* kind_subst_fresh.\n    intro. use (H x).\n  intro; use (H x).\nQed.\n\nLemma soundness_cst : forall h L0 c K0 E T S0 K S L,\n  soundness_spec h (trm_cst c) K0 E T L0 S0 K S L.\nProof.\n  intros; intros Ht HI HS0 HTS0 HK0 Dis HL0 HE HT.\n  poses HI' HI; simpl in HI.\n  destruct (var_freshes L0 (sch_arity (Delta.type c)));\n    simpl in HI.\n  inversions HI; clear HI.\n  refine (soundness_ind _ _ _ H0 _ _ HI' _ _ _ _ _ _ _); auto.\n    apply Delta.scheme.\n  intros.\n  rewrite sch_subst_fresh; try (rewrite Delta.closed; intro; auto).\n  split.\n    unfold unify in H0.\n    forward~ (unify_keep_fv' _ _ H0 HS0 (E:=E)) as G.\n    unfold fvs in *.\n    rewrite dom_concat in G; rewrite fv_in_concat in G.\n    unfold all_fv in G; simpl in G.\n    rewrite dom_kinds_open_vars in G; auto.\n    repeat rewrite typ_subst_id in G.\n    unfold sch_open_vars, typ_open_vars in G; simpl in G.\n    puts (fv_in_kinds_open_vars (sch_kinds (Delta.type c)) x).\n    puts (Delta.closed c).\n    unfold sch_fv in H5; simpl in H5.\n    puts (eq_subset H5); clear H5.\n    puts (typ_fv_open (typ_fvars x) (sch_type (Delta.type c))).\n    rewrite typ_fv_typ_fvars in H5.\n    auto.\n  apply* typing_cst.\n    apply* kenv_ok_map.\n  split.\n    rewrite (fresh_length _ _ _ f). apply types_typ_fvars.\n  pattern (sch_kinds (Delta.type c)) at 2.\n  rewrite <- (kinds_subst_cst S0 c).\n  unfold fvs in HL0.\n  apply* well_kinded_open_vars.\n  apply* fresh_sub.\nQed.\n\nLemma soundness_abs : forall h L0 t K0 E T S0 S K L,\n  (forall t K0 E T L0 S0, soundness_spec h t K0 E T L0 S0 K S L) ->\n  soundness_spec (Datatypes.S h) (trm_abs t) K0 E T L0 S0 K S L.\nProof.\n  intros until L; intros IHh Ht HI HS0 HTS0 HK0 Dis HL0 HE HT; simpl in HI.\n  destruct (var_fresh L0); simpl in HI.\n  destruct (var_fresh (L0 \\u {{x}})); simpl in HI.\n  destruct (var_fresh (dom E \\u trm_fv t)); simpl in HI.\n  case_rewrite R1 (unify K0 (typ_arrow (typ_fvar x) (typ_fvar x0)) T S0).\n  destruct p as [K' S'].\n  rewrite normalize_typinf in HI.\n  unfold unify in R1.\n  destruct (unify_keep _ _ _ R1) as [HS' _]; auto.\n  destruct (unify_type _ _ R1); auto.\n    simpl; intros. destruct* H.\n    inversions* H.\n  destruct* (unify_kinds_ok _ _ R1). clear H1; destruct H2.\n  simpl in Ht. rewrite <- (trm_depth_open x1) in Ht.\n  poses Ht' (lt_S_n _ _ Ht).\n  destruct* (IHh _ _ _ _ _ _ Ht' HI); clear IHh HI.\n      forward~ (unify_keep_fv' _ _ R1 HS0 (E:=E)) as G.\n      unfold fvs in *.\n      unfold all_fv in G; simpl in G.\n      repeat rewrite typ_subst_id in G.\n      unfold env_fv; simpl. fold env_fv.\n      unfold sch_fv; simpl.\n      auto.\n    env_fix. split; auto.\n    apply* env_prop_concat.\n    apply env_prop_single.\n    intro; intros. unfold typ_open_vars. simpl*.\n  intuition.\n        apply* extends_trans.\n        apply* typ_subst_extend.\n      apply* well_subst_compose.\n    clear -H10; unfold fvs in *.\n    unfold env_fv in H10; simpl in H10; fold env_fv in H10.\n    auto.\n  puts (unify_types _ _ _ R1 HS0).\n  rewrite <- (H3 T).\n  rewrite* <- (H11 (typ_arrow (typ_fvar x) (typ_fvar x0)) T).\n  rewrite H3.\n  simpl.\n  simpl map in H12.\n  fold (typ_subst S (typ_fvar x0)).\n  fold (typ_subst S (typ_fvar x)).\n  set (E' := map (sch_subst S) E) in *.\n  apply* (@typing_abs Gc (dom E' \\u {{x1}} \\u trm_fv t)).\n  intros.\n  apply typing_gc_raise.\n  apply* (@typing_abs_rename x1).\nQed.\n\nLemma close_fvars_subset : forall K n DK L,\n  L << close_fvars n K DK L.\nProof.\n  induction n; intros; simpl; intros x Hx. auto.\n  case_eq (S.choose (S.inter DK L)); introv R1; auto.\n  case_eq (get e K); introv R2; apply* IHn; sets_solve.\nQed.\n\nLemma close_fvk_subset : forall L K, L << close_fvk K L.\nProof.\n  intros. unfold close_fvk. apply close_fvars_subset.\nQed.\n\nLemma cardinal_env : forall (A:Set) (K:env A),\n  ok K -> S.cardinal (dom K) = length K.\nProof.\n  induction 1; simpl. apply cardinal_empty.\n  rewrite <- (@cardinal_remove x).\n    rewrite remove_union.\n    assert (S.remove x {{x}} = {}).\n      apply eq_ext; intros; split; intro; sets_solve.\n    rewrite H1. rewrite* remove_notin.\n    rewrite* union_empty_l.\n  sets_solve.\nQed.\n\nLemma close_fvk_ok : forall K L x k,\n  ok K -> x \\in close_fvk K L -> binds x k K -> kind_fv k << close_fvk K L.\nProof.\n  intros.\n  unfold close_fvk in *.\n  puts (cardinal_env H).\n  puts (binds_dom H1).\n  revert L H0 H2 H3; generalize (dom K).\n  induction (length K); simpl; intros.\n    rewrite (cardinal_0 H2) in *. elim (in_empty H3).\n  case_rewrite R1 (S.choose (S.inter v L)).\n    puts (S.choose_1 R1).\n    destruct (x == e).\n      subst.\n      rewrite H1 in *.\n      intros x Hx.\n      apply* close_fvars_subset.\n    assert (forall L', x \\in close_fvars n K (S.remove e v) L' ->\n               kind_fv k << close_fvars n K (S.remove e v) L').\n      intros; apply* IHn.\n      rewrite <- (@cardinal_remove e) in H2; auto.\n    case_rewrite R2 (get e K); intros; auto.\n  puts (S.choose_2 R1).\n  elim (H4 x).\n  auto with sets.\nQed.\n\nLemma vars_subst_in : forall v L S,\n  v \\in L -> typ_fv (typ_subst S (typ_fvar v)) << vars_subst S L.\nProof.\n  intros.\n  unfold vars_subst.\n  puts (S.elements_1 H).\n  induction H0; intros x Hx.\n    simpl. do 2 rewrite <- H0. auto with sets.\n  simpl.\n  puts (IHInA _ Hx). auto with sets.\nQed.\n\nLemma sch_arity_subst : forall M S,\n  sch_arity (sch_subst S M) = sch_arity M.\nProof.\n  destruct M as [T Ks]; simpl*.\nQed.\n\nHint Resolve kind_subst_idem : core.\n\nLemma disjoint_subset : forall L1 L2 L3,\n  L1 << L2 -> disjoint L2 L3 -> disjoint L1 L3.\nProof.\n  intros. disjoint_solve.\nQed.\n\nLemma close_fvk_incl : forall EK0 e0 K',\n  ok K' -> dom e0 << close_fvk K' EK0 -> incl e0 K' ->\n  EK0 \\u dom e0 \\u fv_in kind_fv e0 << close_fvk K' EK0.\nProof.\n  introv HK' Se0 Inc2.\n  puts (incl_subset_dom Inc2).\n  sets_solve.\n    apply* close_fvk_subset.\n  destruct (fv_in_binds _ _ H0) as [x [a [B B']]].\n  puts (Inc2 _ B').\n  puts (in_dom _ _ _ B').\n  apply* close_fvk_ok.\nQed.\n\nLemma mkset_elements : forall L,\n  mkset (S.elements L) = L.\nProof.\n  intros. apply eq_ext.\n  intros; split; intro.\n    apply S.elements_2.\n    apply (SetoidList.In_InA _).\n    apply* mkset_in.\n  apply in_mkset.\n  puts (S.elements_1 H).\n  induction H0; auto.\nQed.\n\nLemma elements_fresh : forall L1 L,\n  disjoint L1 L ->\n  fresh L1 (length (S.elements L)) (S.elements L).\nProof.\n  intros.\n  puts (S.elements_3 L).\n  rewrite <- (mkset_elements L) in H.\n  gen L1; induction H0; intros. simpl*.\n  simpl in *. split2*.\n  apply IHSorted.\n  disjoint_solve.\n  elim (sort_lt_notin H0 H).\n  puts (mkset_in _ Hy').\n  clear -H1.\n  induction l; auto with ordered_type.\nQed.\n\nLemma typing_let_fresh : forall T1 l l0 K' e e0 e1 e2 fvT1 fvE,\n  let ftve := close_fvk K' fvE in\n  let Bs := S.elements (S.diff fvT1 (ftve \\u dom e2)) in\n  let l0' := List.map (fun _:var => @None ckind) Bs in\n  let M := sch_generalize (@app var l Bs) T1 (@app kind l0 l0') in\n  split e2 = (l, l0) ->\n  ok (e0 & e) -> ok (e2 & e1) ->\n  ok K' -> incl (e0 & e) K' -> incl (e2 & e1) e ->\n  disjoint ftve (dom e) ->\n  dom e0 << ftve ->\n  fresh (fvE \\u sch_fv M \\u dom e0 \\u fv_in kind_fv e0) (sch_arity M) (l++Bs).\nProof.\n  intros until M. intros R4 Ok Ok' HK' Inc2 Inc4 Dise Se0.\n  poses DM (@sch_generalize_disjoint (l++Bs) T1 (l0 ++ l0')).\n  fold M in DM; rewrite mkset_app in DM.\n  simpl length. rewrite map_length, app_length.\n  rewrite <- (split_length _ R4).\n  puts (split_combine _ R4).\n  assert (incl e0 K') by (intro; auto*).\n  poses SKA (close_fvk_incl HK' Se0 H0); clear H0.\n  fold ftve in SKA.\n  apply fresh_app.\n    apply* (ok_fresh l l0).\n      rewrite* H.\n    rewrite <- (dom_combine l l0) in * by auto.\n    rewrite H in *.\n    use (incl_subset_dom Inc4).\n  unfold l0'.\n  rewrite map_length.\n  unfold Bs.\n  apply elements_fresh.\n  rewrite <- H.\n  rewrite* dom_combine.\n  puts (@diff_disjoint fvT1 (ftve \\u mkset l)).\n  set (l' := S.diff fvT1 (ftve \\u mkset l)) in *.\n  rewrite <- (dom_combine l l0) in * by auto.\n  rewrite H in *.\n  subst Bs. rewrite mkset_elements in DM.\n  puts (incl_subset_dom Inc4).\n  subst l'.\n  disjoint_solve.\nQed.\n\nLemma typing_let_fresh_2 : forall l1 l2 K' T fvE e e0 e1 e2,\n  let Ks := List.map (kind_map (typ_generalize l1)) l2 in\n  let M' := Sch T Ks in\n  kenv_ok K' ->  ok (e0 & e) -> ok (e2 & e1) ->\n  incl (e0 & e) K' -> incl (e2 & e1) e ->\n  split e1 = (l1, l2) ->\n  disjoint (close_fvk K' fvE) (dom e) ->\n  dom e0 << close_fvk K' fvE ->\n  disjoint (close_fvk K' (typ_fv T)) (dom e1) ->\n  dom e2 << close_fvk K' (typ_fv T) ->\n  fresh (fvE \\u sch_fv M' \\u dom (e0 & e2) \\u fv_in kind_fv (e0 & e2))\n    (sch_arity M') l1.\nProof.\n  intros until M'.\n  intros HK' Ok Ok' Inc2 Inc4 R5 Dise Se0 Dise1 Se2.\n  rewrite dom_concat; rewrite fv_in_concat.\n  simpl length.\n  unfold Ks; rewrite map_length.\n  rewrite <- (split_length _ R5).\n  poses He1 (split_combine _ R5).\n  apply* (ok_fresh l1 l2).\n    rewrite* He1.\n  rewrite* <- (dom_combine l1 l2).\n  rewrite He1.\n  puts (incl_subset_dom Inc4).\n  rewrite dom_concat in H.\n  assert (incl e0 K') by (intro; auto*).\n  puts (close_fvk_incl (proj1 HK') Se0 H0).\n  puts (@close_fvk_subset (typ_fv T) K').\n  repeat apply disjoint_union; simpl; auto; apply disjoint_comm.\n  (* Ks *)\n  unfold Ks; simpl.\n  rewrite <- He1. rewrite* dom_combine.\n  apply kinds_generalize_disjoint.\n  (* e2 *)\n  refine (disjoint_subset _ Dise1).\n  intro; intros.\n  apply* close_fvk_incl.\n  clear -Inc2 Inc4.\n  intro; intros.\n  apply Inc2.\n  apply* in_or_app.\nQed.\n\nLemma sch_open_extra : forall Ks Xs T,\n  type T -> sch_open_vars (Sch T Ks) Xs = T.\nProof.\n  unfold sch_open_vars, typ_open_vars; simpl; intros.\n  rewrite* <- typ_open_type.\nQed.\n\nLemma typing_let_incl : forall K' e e0 e1 e2 : kenv,\n  ok (e0 & e) -> ok (e2 & e1) ->\n  incl K' (e0 & e) ->\n  incl (e0 & e) K' ->\n  incl e (e2 & e1) ->\n  incl (e2 & e1) e ->\n  incl K' (e0 & e2 & e1) /\\ incl (e0 & e2 & e1) K'.\nProof.\n  intros until e2; intros Ok Ok' I1 I2 I3 I4.\n  rewrite concat_assoc.\n  set (e' := e2 & e1) in *.\n  split; intro; intros.\n    puts (I1 _ H).\n    destruct* (in_app_or _ _ _ H0).\n  destruct* (in_app_or _ _ _ H).\nQed.\n\nLemma typing_let_kenv_ok : forall K' T1 ftve e2 l l0 e0 e e1,\n  let Bs := S.elements (S.diff (close_fvk K' (typ_fv T1)) (ftve \\u dom e2)) in\n  let l0' := List.map (fun _ : var => None) Bs in\n  split e2 = (l, l0) ->\n  kenv_ok K' -> ok (e0 & e) -> ok (e2 & e1) ->\n  dom e0 << ftve -> incl (e0 & e) K' -> incl (e2 & e1) e ->\n  combine l l0 = e2 ->\n  kenv_ok (e0 & combine Bs l0' & combine l l0).\nProof.\n  intros until l0'; intros R4 HK' Ok Ok' Se0 Inc2 Inc4 He2.\n  rewrite concat_assoc.\n  puts (@diff_disjoint (close_fvk K' (typ_fv T1)) (ftve \\u dom e2)).\n  puts (elements_fresh (disjoint_comm H)).\n  apply kenv_ok_concat.\n      split2*. intro; intros. apply (proj2 HK' x). apply* Inc2.\n    split.\n      apply disjoint_ok.\n          apply* ok_combine_fresh.\n        rewrite* He2.\n      rewrite dom_combine. rewrite* dom_combine.\n        unfold Bs; rewrite mkset_elements.\n        rewrite* <- (dom_combine l l0). rewrite* He2.\n      unfold l0'; rewrite* map_length.\n    apply env_prop_concat.\n      apply list_forall_env_prop.\n      unfold l0'; clear; induction Bs; simpl*.\n    rewrite He2. intro; intros. apply (proj2 HK' x).\n    apply Inc2. apply in_or_concat; left*.\n  rewrite dom_concat. rewrite He2.\n  apply disjoint_union.\n    fold Bs in H0.\n    rewrite* dom_combine.\n    unfold l0'; rewrite* map_length.\n  use (incl_subset_dom Inc4).\nQed.\n\nLemma typ_fv_generalize : forall Xs T,\n  typ_fv (typ_generalize Xs T) << typ_fv T.\nProof.\n  induction T; simpl; intros y Hy; auto.\n  destruct* (index eq_var_dec 0 v Xs).\nQed.\n\nLemma kinds_fv_generalize : forall Bs Ks,\n  kind_fv_list (List.map (kind_map (typ_generalize Bs)) Ks) << kind_fv_list Ks.\nProof.\n  intros. unfold kind_fv_list.\n  induction Ks; simpl*.\n  sets_solve.\n  apply S.union_2.\n  unfold kind_fv in *.\n  clear IHKs Ks; destruct a as [[kc kv kr kh]|]; simpl in *.\n    clear kh; induction kr; simpl in *. auto.\n    sets_solve.\n      use (typ_fv_generalize _ _ H0).\n    apply* S.union_3.\n  auto.\nQed.\n\nLemma sch_fv_generalize : forall Bs T Ks,\n  sch_fv (sch_generalize Bs T Ks) << sch_fv (Sch T Ks).\nProof.\n  intros.\n  unfold sch_generalize, sch_fv; simpl.\n  sets_solve. use (typ_fv_generalize _ _ H).\n  use (kinds_fv_generalize _ _ H).\nQed.\n\nLemma fv_in_kind_fv_list : forall Xs Ks,\n  length Xs = length Ks ->\n  fv_in kind_fv (combine Xs Ks) = kind_fv_list Ks.\nProof.\n  induction Xs; destruct Ks; simpl; intros; try discriminate.\n    auto.\n  inversion H.\n  rewrite* IHXs.\nQed.\n\nLemma soundness_generalize : forall L K' E' t T1 KA M,\n  K'; E' |Gc|= t ~: T1 ->\n  typinf_generalize K' E' L T1 = (KA, M) ->\n  kenv_ok KA /\\ incl KA K' /\\ S.inter (dom K') L << dom KA /\\ scheme M /\\\n  sch_fv M << fv_in kind_fv K' \\u typ_fv T1 /\\\n  exists L1, forall Xs,\n    fresh L1 (sch_arity M) Xs ->\n    KA & kinds_open_vars (sch_kinds M) Xs; E' |(true,GcLet)|= t ~: M ^ Xs.\nProof.\n  unfold typinf_generalize.\n  introv Typ HI.\n  set (ftve := close_fvk K' (env_fv E')) in *.\n  case_rewrite R2 (split_env ftve K').\n  case_rewrite R3 (split_env (close_fvk K' (typ_fv T1)) e).\n  case_rewrite R4 (split e2).\n  set (Bs := S.elements (S.diff (close_fvk K' (typ_fv T1)) (ftve \\u dom e2)))\n    in *.\n  set (l0' := List.map (fun _:var => @None ckind) Bs) in *.\n  case_rewrite R5 (split_env L e).\n  inversion HI; clear HI. subst KA.\n  destruct* (split_env_ok _ R2) as [Ok [Dise [Se0 [Inc1 Inc2]]]].\n  destruct* (split_env_ok _ R3) as [Ok' [Dise' [Se2 [Inc3 Inc4]]]].\n  destruct* (split_env_ok _ R5) as [Ok'' [Dise3 [Se4 [Inc5 Inc6]]]].\n  poses He2 (split_combine _ R4).\n  assert (HK': kenv_ok K') by auto.\n  assert (Hkt: list_forall (All_kind_types type) (l0 ++ l0')).\n    apply list_forall_app.\n      refine (env_prop_list_forall l _ _ _ _); auto*.\n        rewrite He2. intro; intros. apply* (proj2 HK' x).\n        apply Inc2. apply* in_or_concat.\n      rewrite* He2.\n    unfold l0'. clear; induction Bs; simpl*.\n  assert (HM: scheme M).\n    subst M; unfold l0'.\n    apply* scheme_generalize.\n  assert (IncKA: incl (e0 & e4) K').\n    intros a Ha.\n    destruct (in_app_or _ _ _ Ha).\n      assert (In a e); auto.\n    auto.\n  assert (HKA: kenv_ok (e0 & e4)).\n    split. apply* disjoint_ok. \n      use (incl_subset_dom Inc6).\n    intro; intros; apply* HK'.\n  split2*. split2*.\n  split.\n    intro; intros.\n    puts (incl_subset_dom Inc1).\n    use (incl_subset_dom Inc5).\n  split. rewrite* H1.\n  split.\n    intros y Hy. puts (sch_fv_generalize Hy).\n    clear Hy; unfold sch_fv, l0' in H; simpl in H.\n    rewrite kind_fv_list_app in H.\n    clearbody Bs.\n    clear -Inc2 Inc4 R4 H.\n    rewrite <- (fv_in_kind_fv_list l l0 (split_length _ R4)) in H.\n    rewrite (split_combine _ R4) in H.\n    puts (incl_fv_in_subset kind_fv Inc2).\n    puts (incl_fv_in_subset kind_fv Inc4).\n    disjoint_solve.\n    clear -H; induction Bs. elim (in_empty H).\n    apply IHBs. simpl in H; sets_solve. elim (in_empty H0).\n  intros.\n  assert (AryM: sch_arity M = length (l ++ Bs)).\n    rewrite <- H1.\n    unfold l0'. simpl*.\n  esplit; intros.\n  apply typing_weaken_kinds.\n  eapply typing_rename_typ.\n      instantiate (1 := l ++ Bs).\n      unfold l0', Bs, ftve; apply* typing_let_fresh.\n    instantiate (1 := dom (e0 & e4) \\u mkset (l++Bs)) in H.\n    rewrite dom_concat in H.\n    rewrite <- AryM; rewrite* <- H1.\n  unfold sch_open_vars, typ_open_vars. simpl sch_type.\n  rewrite* typ_generalize_reopen.\n  unfold sch_generalize. simpl sch_kinds.\n  rewrite* kinds_generalize_reopen.\n  rewrite* combine_app.\n  fold (@combine var kind Bs l0' & combine l l0).\n  rewrite <- concat_assoc.\n  puts (typing_let_kenv_ok T1 _ _ R4 HK' Ok Ok' Se0 Inc2 Inc4 He2).\n  apply* typing_weaken_kinds; clear H0.\n  rewrite He2.\n  case_eq (split e1); introv R6.\n  poses He1 (split_combine _ R6).\n  pose (Ks := List.map (kind_map (typ_generalize l1)) l2).\n  apply* (@typing_gc (true,GcLet) Ks). simpl*.\n  poses Typ' (typing_gc_raise Typ). clear Typ. simpl in Typ'.\n  intros.\n  pose (M' := Sch T1 Ks).\n  rewrite* <- (@sch_open_extra Ks Xs0). fold M'.\n  replace Ks with (sch_kinds M') by simpl*.\n  eapply typing_rename_typ.\n      instantiate (1 := l1).\n      unfold M', Ks.\n      unfold ftve in *.\n      apply* (@typing_let_fresh_2 l1 l2 K').\n    unfold Ks in H0. rewrite map_length in H0.\n    rewrite* (split_length _ R6).\n  assert (list_forall (All_kind_types type) l2).\n    refine (env_prop_list_forall l1 _ _ _ _); auto*.\n      rewrite He1. intro; intros. apply (proj2 HK' x).\n      apply Inc2. apply* in_or_concat.\n    rewrite* He1.\n  simpl sch_kinds.\n  unfold Ks; rewrite* kinds_generalize_reopen. rewrite He1; clear H2.\n  unfold sch_open_vars, typ_open_vars.\n  simpl sch_type. rewrite* <- typ_open_type.\n  destruct* (typing_let_incl _ _ _ Ok Ok' Inc1 Inc2 Inc3 Inc4).\n  apply* typing_kenv_incl.\n  split.\n    rewrite concat_assoc.\n    apply* disjoint_ok.\n      use (incl_subset_dom Inc4).\n    intro; intros. assert (kenv_ok K') by auto. apply* (proj2 H5).\n  apply* kenv_ok_sch_kinds. rewrite* H1.\nQed.\n\nLemma binds_kdom : forall x k K,\n  binds x (Some k) K -> x \\in kdom K.\nProof.\n  unfold binds; induction K; simpl; intros. discriminate.\n  destruct a.\n  destruct (x == v). inversions* H.\n  puts (IHK H). destruct* o.\nQed.\n\nLemma well_subst_let_inf: forall K0 s k e S K,\n  well_subst K0 (map (kind_subst s) k) s ->\n  well_subst e (map (kind_subst S) K) S ->\n  S.inter (dom (map (kind_subst s) k)) (vars_subst s (kdom K0)) << dom e ->\n  incl e (map (kind_subst s) k) -> ok k ->\n  extends S s ->\n  well_subst K0 (map (kind_subst S) K) S.\nProof.\n  intros until K; intros WS WS' Inc1 Inc2 Hk Hext Z; intros.\n  puts (WS _ _ H).\n  rewrite <- (kind_subst_extend k0 Hext).\n  rewrite <- Hext.\n  inversions* H0.\n  fold (typ_subst s (typ_fvar Z)) in H2.\n  rewrite <- H2.\n  case_eq (get x e); intros.\n    assert (Some k' = k2) by apply* binds_func.\n    subst k2.\n    puts (WS' _ _ H3).\n    eapply kind_entails_well_kinded; try apply H6.\n    simpl*.\n  elim (get_none_notin _ H3).\n  apply Inc1.\n  destruct k0; try discriminate.\n  puts (vars_subst_in s (binds_kdom H)).\n  rewrite <- H2 in H6. simpl in H6.\n  puts (binds_dom H4).\n  puts (S.singleton_2 (refl_equal x)).\n  auto with sets.\nQed.\n\nLemma soundness_let : forall h L0 t1 t2 K0 E T S0 S K L,\n  (forall t K0 E T L0 S0 K S L, soundness_spec h t K0 E T L0 S0 K S L) ->\n  soundness_spec (Datatypes.S h) (trm_let t1 t2) K0 E T L0 S0 K S L.\nProof.\n  intros until L; intros IHh Ht HI HS0 HTS0 HK0 Dis HL0 HE HT; simpl in HI.\n  destruct (var_fresh L0); simpl in HI.\n  rewrite normalize_typinf in HI.\n  case_rewrite R1 (typinf0 K0 E t1 (typ_fvar x) (L0 \\u {{x}}) S0).\n  destruct o; try discriminate. destruct p.\n  fold (typ_subst s (typ_fvar x)) in HI.\n  set (K' := map (kind_subst s) k) in *.\n  set (E' := map (sch_subst s) E) in *.\n  set (T1 := typ_subst s (typ_fvar x)) in *.\n  destruct (var_fresh (dom E \\u trm_fv t1 \\u trm_fv t2)); simpl proj1_sig in HI.\n  case_rewrite R2 (typinf_generalize K' E' (vars_subst s (kdom K0)) T1).\n  simpl in Ht.\n  assert (Ht': trm_depth t1 < h).\n    puts (Max.le_max_l (trm_depth t1) (trm_depth t2)). omega.\n  destruct* (IHh _ _ _ _ _ _ _ _ _ Ht' R1); clear R1.\n    simpl*.\n  destruct H0 as [HTs [Hs [Hk [Disk [WS' [HL0' Typ']]]]]].\n  destruct (soundness_generalize _ Typ' R2)\n    as [HKA [Inc2 [Inc1 [HM [Hfv [L' Typ2]]]]]].\n  rewrite normalize_typinf in HI.\n  clear Ht'; assert (Ht': trm_depth t2 < h).\n    puts (Max.le_max_r (trm_depth t1) (trm_depth t2)). omega.\n  rewrite <- (trm_depth_open x0) in Ht'.\n  destruct* (IHh _ _ _ _ _ _ _ _ _ Ht' HI); clear IHh HI.\n        use (incl_subset_dom Inc2).\n      clear -HL0 HL0' Inc2 Hfv.\n      unfold fvs in *.\n      unfold env_fv; simpl; fold env_fv.\n      puts (incl_subset_dom Inc2).\n      puts (incl_fv_in_subset kind_fv Inc2).\n      puts (fv_in_kind_subst s k).\n      disjoint_solve.\n      puts (typ_fv_subst s (typ_fvar x) H3). simpl in H4. auto.\n    env_fix. split; auto.\n  intuition.\n        apply* extends_trans.\n      apply* well_subst_let_inf.\n    clear -H6 HL0'.\n    unfold fvs in *; simpl in H6. auto.\n  apply* (@typing_let Gc (sch_subst S s0) (dom S \\u dom K \\u L')).\n    intros.\n    simpl.\n    rewrite* <- kinds_subst_open_vars.\n    rewrite* <- sch_subst_open_vars.\n    rewrite sch_arity_subst in H7.\n    rewrite <- (map_sch_subst_extend E H0).\n    apply* typing_typ_well_subst.\n      apply (well_subst_extend (sch_kinds s0) Xs H2 H5).\n      rewrite* dom_map.\n    rewrite <- map_concat.\n    apply* kenv_ok_map.\n    apply* kenv_ok_sch_kinds.\n  instantiate (1 := dom E \\u trm_fv t2 \\u {{x0}}).\n  intros.\n  apply typing_gc_raise.\n  apply* (@typing_abs_rename x0).\nQed.\n\nLemma soundness_app : forall h L0 t1 t2 K0 E T S0 S K L,\n  (forall t K0 E T L0 S0 K S L, soundness_spec h t K0 E T L0 S0 K S L) ->\n  soundness_spec (Datatypes.S h) (trm_app t1 t2) K0 E T L0 S0 K S L.\nProof.\n  intros until L; intros IHh Ht HI HS0 HTS0 HK0 Dis HL0 HE HT; simpl in HI.\n  destruct (var_fresh L0); simpl in HI.\n  rewrite normalize_typinf in HI.\n  case_rewrite R1 (typinf0 K0 E t1 (typ_arrow (typ_fvar x) T) (L0\\u{{x}}) S0).\n  destruct o; try discriminate. destruct p as [K' S'].\n  simpl in Ht.\n  assert (Ht': trm_depth t1 < h).\n    puts (Max.le_max_l (trm_depth t1) (trm_depth t2)). omega.\n  destruct* (IHh _ _ _ _ _ _ _ _ _ Ht' R1); clear R1.\n    simpl*.\n  rewrite normalize_typinf in HI.\n  clear Ht'; assert (Ht': trm_depth t2 < h).\n    puts (Max.le_max_r (trm_depth t1) (trm_depth t2)). omega.\n  destruct* (IHh _ _ _ _ _ _ _ _ _ Ht' HI); clear IHh HI.\n    clear -H0; simpl. remember {{x}} as L. auto*.\n  intuition.\n      apply* extends_trans.\n    apply* well_subst_compose.\n  remember (typ_fvar x) as T1.\n  apply* typing_app.\n  puts (well_subst_extends H1 H10).\n  puts (typing_typ_well_subst H0 H13 (kenv_ok_map H6 H0) H14).\n  rewrite (map_sch_subst_extend E H1) in H16.\n  rewrite H1 in H16.\n  apply H16.\nQed.\n\nTheorem typinf_sound : forall h t K0 E T L0 S0 K S L,\n  soundness_spec h t K0 E T L0 S0 K S L.\nProof.\n induction h; destruct t; intros;\n    intros Ht HI HS0 HTS0 HK0 Dis HL0 HE HT;\n      try elim (lt_n_O _ Ht); try discriminate.\n  apply* soundness_var.\n  apply* soundness_abs.\n  apply* soundness_let. \n  apply* soundness_app.\n  apply* soundness_cst.\nQed.\n\nLemma map_sch_subst_fresh : forall S E,\n  disjoint (dom S) (env_fv E) -> map (sch_subst S) E = E.\nProof.\n  unfold env_fv; induction E; simpl; intros. auto.\n  destruct a. \n  rewrite* sch_subst_fresh.\n  rewrite* IHE.\nQed.\n\nCorollary typinf_sound' : forall t K E T,\n  env_ok E -> env_fv E = {} ->\n  typinf' E t = Some (K, T) -> K; E |Gc|= t ~: T.\nProof.\n  unfold typinf'.\n  introv HE HC HI.\n  rewrite normalize_typinf in HI.\n  case_rewrite R1\n    (typinf0 empty E t (typ_fvar var_default) {{var_default}} empty).\n  destruct o; try discriminate.\n  destruct p. inversions HI; clear HI.\n  destruct* (typinf_sound _ (lt_n_Sn _) R1).\n       intro; intros. elim H.\n      intro; intros. elim H.\n     split2*. intro; intros. elim H.\n   unfold fvs; simpl; sets_solve.\n   rewrite HC in H0. elim (in_empty H0).\n  rewrite* <- (map_sch_subst_fresh s E).\n  rewrite* HC.\nQed.\n\n\n(** Principality *)\n\nLemma typ_subst_concat_fresh : forall S1 S2 T,\n  disjoint (dom S2) (typ_fv T) ->\n  typ_subst (S1 & S2) T = typ_subst S1 T.\nProof.\n  induction T; simpl; intros. auto.\n    case_eq (get v S1); intros.\n      rewrite* (binds_concat_fresh S2 H0).\n    rewrite* get_notin_dom.\n  rewrite* IHT1; rewrite* IHT2.\nQed.\n\nLemma typ_subst_combine_fresh : forall S T Xs Us,\n  fresh (typ_fv T) (length Us) Xs ->\n  typ_subst (S & combine Xs Us) T = typ_subst S T.\nProof.\n  intros.\n  rewrite* typ_subst_concat_fresh.\nQed.\n\nDefinition typ_subst_eq_in L S1 S2 :=\n  forall T, typ_fv T << L -> typ_subst S1 T = typ_subst S2 T.\n\nLemma kind_subst_ext_fv : forall S2 L S1 k,\n  typ_subst_eq_in L S1 S2 ->\n  kind_fv k << L -> kind_subst S1 k = kind_subst S2 k.\nProof.\n  intros.\n  destruct k as [[kc kv kr kh]|].\n    simpl; apply* kind_pi; simpl.\n    unfold kind_fv in H0; simpl in H0.\n    clear kv kh.\n    induction kr. auto.\n    simpl in *.\n    rewrite IHkr; try rewrite* H; intros x Hx; apply* H0.\n  auto.\nQed.\n\nLemma extends_concat : forall S0 S L n Xs Us,\n  dom S0 \\u fv_in typ_fv S0 << L ->\n  extends S S0 ->\n  fresh L n Xs ->\n  typ_subst_eq_in L (S & combine Xs Us) S ->\n  extends (S & combine Xs Us) S0.\nProof.\n  introv HL Hext Fr Hsub; intro; intros.\n  induction T. simpl*.\n    case_eq (get v S0); intros.\n      rewrite Hsub. rewrite Hsub.\n          rewrite Hext. reflexivity.\n        simpl; use (binds_dom H).\n      simpl. rewrite H.\n      use (fv_in_spec typ_fv _ _ _ (binds_in H)).\n    simpl; rewrite* H.\n  simpl. congruence.\nQed.\n\nLemma unifies_open : forall S n Us L Xs M0 T,\n  env_prop type S ->\n  types n Us ->\n  fresh L n Xs ->\n  typ_subst_eq_in L (S & combine Xs Us) S ->\n  sch_fv M0 \\u typ_fv T << L ->\n  sch_open (sch_subst S M0) Us = typ_subst S T ->\n  typ_subst (S & combine Xs Us) (sch_open_vars M0 Xs) =\n  typ_subst (S & combine Xs Us) T.\nProof.\n  intros until T; intros HTS HUs Fr Hsub HM0 HU.\n  rewrite* (Hsub T).\n  rewrite <- HU.\n  unfold sch_open_vars, sch_open.\n  rewrite* <- typ_subst_intro0.\n    unfold sch_fv in HM0.\n    rewrite <- (fresh_length _ _ _ Fr).\n    apply* disjoint_fresh.\n  rewrite* <- (fresh_length _ _ _ Fr).\nQed.\n\nLemma kind_subst_intro0 : forall S Xs Us k, \n  fresh (kind_fv k) (length Xs) Xs -> \n  types (length Xs) Us ->\n  env_prop type S ->\n  kind_open (kind_subst S k) Us =\n  kind_subst (S & combine Xs Us) (kind_open k (typ_fvars Xs)).\nProof.\n  destruct k as [[kc kv kr kh]|]; unfold kind_fv; simpl*; intros.\n  apply kind_pi; simpl*.\n  clear kh; induction kr. auto.\n  destruct a; simpl in *.\n  fold (typ_open_vars t Xs).\n  rewrite* <- typ_subst_intro0.\n  rewrite* IHkr.\nQed.\n\nLemma fv_in_sch : forall Xs M,\n  fv_in kind_fv (combine Xs (sch_kinds M)) << sch_fv M.\nProof.\n  intros.\n  destruct M as [T Ks]. unfold sch_fv; simpl.\n  gen Ks; induction Xs; simpl; intros. auto.\n  destruct Ks; simpl in *; auto.\n  use (IHXs Ks).\nQed.\n\nLemma well_subst_concat : forall E S0 K0 K S L S',\n  well_subst (map (kind_subst S0) K0) K S ->\n  typ_subst_eq_in L (S & S') S ->\n  extends (S & S') S0 ->\n  fvs S0 K0 E << L ->\n  well_subst K0 K (S & S').\nProof.\n  introv WS Hsub Hext' HL.\n  intro; intros.\n  rewrite <- (kind_subst_combine _ _ _ k Hext').\n  puts (WS _ _ (binds_map (kind_subst S0) H)).\n  unfold fvs in HL.\n  rewrite Hsub.\n    rewrite* (@kind_subst_ext_fv S L).\n    intros y Hy.\n    puts (kind_fv_subst _ _ Hy).\n    use (fv_in_spec kind_fv _ _ _ (binds_in H)).\n  simpl.\n  use (binds_dom H).\nQed.\n\nLemma well_subst_concat_abs : forall K M0 Us S S0 K0 E L Xs x,\n  env_prop type S ->\n  dom S \\u fvs S0 K0 E << L ->\n  proper_instance K (sch_kinds (sch_subst S M0)) Us ->\n  well_subst (map (kind_subst S0) K0) K S ->\n  binds x M0 E ->\n  fresh L (sch_arity M0) Xs ->\n  sch_arity M0 = length Us ->\n  typ_subst_eq_in L (S & combine Xs Us) S ->\n  extends (S & combine Xs Us) S0 ->\n  well_subst (K0 & kinds_open_vars (sch_kinds M0) Xs) K (S & combine Xs Us).\nProof.\n  intros until x; intros HTS HL [HUs HWk] WS B Fr AryM Hsub Hext'.\n  intro; intros.\n  binds_cases H.\n    refine (well_subst_concat (E:=E) _ WS Hsub Hext' _ _); auto.\n  simpl.\n  case_eq (get Z (combine Xs Us)); intros.\n    rewrite (binds_prepend S H).\n    unfold kinds_open_vars, kinds_open in B1.\n    rewrite <- map_combine in B1.\n    destruct (binds_map_inv _ _ B1) as [k1 [Hk1 Bk]].\n    subst k.\n    rewrite <- kind_subst_intro0; trivial.\n        destruct M0 as [T1 Ks]. simpl in *.\n        unfold kinds_open in HWk. rewrite map_map in HWk.\n        puts (binds_map (fun k => kind_open (kind_subst S k) Us) Bk).\n        simpl in H0; rewrite map_combine in H0.\n        use (list_forall2_get _ HWk H0 H).\n      puts (fv_in_spec sch_fv _ _ _ (binds_in B)).\n      puts (fv_in_spec kind_fv _ _ _ (binds_in Bk)).\n      puts (fv_in_sch Xs M0).\n      rewrite <- (fresh_length _ _ _ Fr).\n      apply* fresh_sub.\n      unfold fvs, env_fv in HL; intros y Hy; simpl in *; sets_solve.\n    rewrite sch_arity_subst in HUs.\n    rewrite* <- (fresh_length _ _ _ Fr).\n  elim (get_none_notin _ H). auto.\nQed.\n\nDefinition moregen_scheme K M0 M :=\n  forall Ys, fresh (dom K) (sch_arity M) Ys ->\n    exists Ts,\n      proper_instance (K & kinds_open_vars (sch_kinds M) Ys) (sch_kinds M0) Ts\n      /\\ sch_open M0 Ts = sch_open M (typ_fvars Ys).\n\nDefinition moregen_env K E0 E :=\n  dom E0 = dom E /\\\n  forall x M, binds x M E ->\n    exists M0, binds x M0 E0 /\\ moregen_scheme K M0 M.\n\nLemma moregen_scheme_refl : forall K M, moregen_scheme K M M.\nProof.\n  intros; intro; intros.\n  esplit; split2*.\n  split. rewrite (fresh_length _ _ _ H). apply* types_typ_fvars.\n  unfold kinds_open_vars.\n  apply (@well_kinded_combine K (sch_kinds M) Ys nil).\n  apply H.\nQed.\n\nLemma moregen_env_refl : forall K E, moregen_env K E E.\nProof.\n  intros; split2*; intro; intros.\n  esplit; split2*.\n  apply moregen_scheme_refl.\nQed.\n\nLemma sch_fv_subst : forall S M,\n  sch_fv (sch_subst S M) << sch_fv M \\u fv_in typ_fv S.\nProof.\n  destruct M as [T Ks].\n  unfold sch_fv, sch_subst; simpl.\n  sets_solve.\n    use (typ_fv_subst S _ H).\n  induction Ks; simpl in *. auto.\n  sets_solve.\n    use (kind_fv_subst S _ H0).\n  use (IHKs H0).\nQed.\n\nLemma in_kind_fv : forall k Ks,\n  In k Ks -> kind_fv k << kind_fv_list Ks.\nProof.\n  induction Ks; simpl; intros; intros y Hy. elim H.\n  destruct H. subst*.\n  use (IHKs H _ Hy).\nQed.\n\nLemma proper_instance_inf : forall K M Us Ys M' Vs,\n  proper_instance K (sch_kinds M) Us ->\n  proper_instance (K & kinds_open_vars (sch_kinds M) Ys) (sch_kinds M') Vs ->\n  fresh (dom K \\u fv_in kind_fv K \\u sch_fv M \\u sch_fv M') (sch_arity M) Ys ->\n  proper_instance K (sch_kinds M') (List.map (typ_subst (combine Ys Us)) Vs).\nProof.\n  intros until Vs; intros [HUs WUs] [HVs WVs] FrYs.\n  split.\n    apply* typ_subst_type_list.\n    apply list_forall_env_prop.\n    apply (proj2 HUs).\n  assert (HTUs: env_prop type (combine Ys Us)).\n    apply list_forall_env_prop.\n    apply (proj2 HUs).\n  assert (LenYs: length Ys = length Us)\n    by (rewrite <- (proj1 HUs); symmetry; auto).\n  replace (sch_kinds M')\n    with (List.map (kind_subst (combine Ys Us)) (sch_kinds M')).\n    rewrite* <- kinds_subst_open.\n    apply* list_forall2_map.\n    intros.\n    inversions H. simpl*.\n    binds_cases H0.\n      rewrite kind_subst_fresh.\n        rewrite* typ_subst_fresh.\n      assert (kind_entails (Some k') (Some k)) by simpl*.\n      puts (kind_entails_fv _ _ H0).\n      use (fv_in_spec kind_fv _ _ _ (binds_in B)).\n    apply* well_kinded_subst.\n    apply* well_subst_open_vars.\n      unfold sch_fv in FrYs.\n      apply* (fresh_resize (sch_arity M)).\n    rewrite* <- (fresh_length _ _ _ FrYs).\n  rewrite (list_map_ext (sch_kinds M') (kind_subst (combine Ys Us))\n               (fun x:kind => x)).\n    apply list_map_id.\n  intros.\n  apply kind_subst_fresh.\n  unfold sch_fv in FrYs; simpl in FrYs.\n  use (in_kind_fv _ _ H).\nQed.\n\nLemma sch_open_inf : forall M Us M' Vs Ys,\n  types (sch_arity M) Us ->\n  sch_open M' Vs = sch_open M (typ_fvars Ys) ->\n  fresh (sch_fv M \\u sch_fv M') (sch_arity M) Ys ->\n  sch_open M' (List.map (typ_subst (combine Ys Us)) Vs) =\n  sch_open M Us.\nProof.\n  introv HUs EVs FrYs.\n  assert (HTUs: env_prop type (combine Ys Us)).\n    apply list_forall_env_prop.\n    apply (proj2 HUs).\n  replace M' with (sch_subst (combine Ys Us) M').\n    rewrite* <- sch_subst_open.\n    rewrite EVs.\n    rewrite (proj1 HUs) in FrYs.\n    rewrite* sch_subst_open.\n    rewrite* (fresh_subst _ _ Us FrYs).\n    unfold sch_open, sch_subst; simpl.\n    unfold sch_fv in FrYs.\n    rewrite* typ_subst_fresh.\n  rewrite* sch_subst_fresh.\nQed.\n\nLemma type_scheme : forall T,\n  type T -> scheme (Sch T nil).\nProof.\n  intros; intro; intros.\n  destruct Xs; try discriminate.\n  unfold typ_open_vars; simpl.\n  split2*.\n  clear -H; induction H; simpl*.\nQed.\nHint Resolve type_scheme : core.\n\nLemma moregen_scheme_weaken : forall K K' M' M,\n  moregen_scheme K M' M ->\n  ok (K & K') ->\n  moregen_scheme (K & K') M' M.\nProof.\n  intros; intro; intros.\n  rewrite dom_concat in H1.\n  destruct* (H Ys) as [Ts [PI HM]].\n  exists Ts; split2*.\n  rewrite <- dom_concat in H1.\n  apply* proper_instance_weaken.\nQed.\n\nLemma moregen_env_weaken : forall K K' E' E,\n  moregen_env K E' E ->\n  ok (K & K') ->\n  moregen_env (K & K') E' E.\nProof.\n  intros.\n  destruct H.\n  split2*.\n  intros.\n  destruct (H1 _ _ H2) as [M' [B' MG]].\n  exists M'; split2*.\n apply* moregen_scheme_weaken.\nQed.\n\nLemma moregen_env_push : forall K E' E x M' M,\n  moregen_env K E' E -> moregen_scheme K M' M ->\n  moregen_env K (E' & x ~ M') (E & x ~ M).\nProof.\n  intros; split. simpl. rewrite* (proj1 H).\n  intros.\n  binds_cases H1.\n    destruct (proj2 H _ _ B) as [M1 [B' MG]].\n    exists* M1.\n  destruct (binds_single_inv B0). subst.\n  exists M'. split2*.\nQed.\n\nLemma typing_moregen : forall gc K E E' t T,\n  K; E |gc|= t ~: T ->\n  moregen_env K E' E -> env_ok E' ->\n  K; E' |gc|= t ~: T.\nProof.\n  intros; gen E'.\n  induction H; introv MGE HE'; auto*.\n  (* Var *)\n  destruct (proj2 MGE _ _ H1) as [M' [B' MGM]].\n  destruct (var_freshes (dom K \\u fv_in kind_fv K \\u sch_fv M \\u sch_fv M')\n            (sch_arity M)) as [Ys Fr].\n  destruct* (MGM Ys) as [Vs [HVs EVs]].\n  rewrite <- (sch_open_inf _ _ _ _ (proj1 H2) EVs) by auto.\n  apply* typing_var.\n  apply* proper_instance_inf.\n  (* Abs *)\n  apply* (@typing_abs gc (L \\u dom E')).\n  intros.\n  apply* H1.\n    apply* moregen_env_push.\n    apply moregen_scheme_refl.\n  destruct HE'.\n  split2*.\n  (* Let *)\n  apply* (@typing_let gc M L1 (L2 \\u dom E')).\n    intros; apply* H0.\n    apply* moregen_env_weaken.\n    forward~ (H Xs) as Typ.\n  intros.\n  apply* (H2 x).\n    apply* moregen_env_push.\n    apply moregen_scheme_refl.\n  destruct HE'.\n  split2*.\n  forward~ (H1 x) as Typ.\n  (* Gc *)\n  apply* typing_gc.\n  intros.\n  apply* (H1 Xs).\n  apply* moregen_env_weaken.\n  forward~ (H0 Xs) as Typ.\nQed.\n\nDefinition principality S0 K0 E0 S K t T L h :=\n  is_subst S0 -> env_prop type S0 ->\n  kenv_ok K0 -> disjoint (dom S0) (dom K0) ->\n  env_ok E0 ->\n  env_prop type S -> dom S \\u fvs S0 K0 E0 \\u typ_fv T << L ->\n  extends S S0 -> well_subst K0 K S ->\n  K; map (sch_subst S) E0 |(false,GcAny)|= t ~: typ_subst S T ->\n  trm_depth t < h ->\n  exists K', exists S', exists L',\n    typinf K0 E0 t T L S0 (lt_wf _) = (Some (K', S'), L') /\\\n    exists S'',\n      dom S'' << S.diff L' L /\\ env_prop type S'' /\\ extends (S & S'') S' /\\\n      well_subst K' K (S & S'').\n\nLemma principal_var : forall h L S0 K0 E0 S K x T,\n  principality S0 K0 E0 S K (trm_fvar x) T L (Datatypes.S h).\nProof.\n  intros; intros HS0 HTS0 HK0 Dis HE0 HTS HL Hext WS Typ Hh.\n  inversions Typ; clear Typ; try discriminate.\n  simpl.\n  destruct (binds_map_inv _ _ H5) as [M0 [HM0 B]].\n  rewrite B.\n  destruct (var_freshes L (sch_arity M0)) as [Xs Fr]; simpl.\n  assert (AryM0: sch_arity M0 = length Us).\n    rewrite <- (proj1 (proj1 H6)).\n    rewrite <- HM0; rewrite* sch_arity_subst.\n  assert (Hsub: typ_subst_eq_in L (S & combine Xs Us) S).\n    rewrite AryM0 in Fr.\n    intro; intros.\n    apply* typ_subst_combine_fresh.\n    apply* fresh_sub.\n  assert (Ok: ok (K0 & kinds_open_vars (sch_kinds M0) Xs)).\n    unfold fvs in HL.\n    apply* ok_kinds_open_vars. apply* fresh_sub.\n  assert (Hext': extends (S & combine Xs Us) S0).\n    clear -Fr Hext Hsub HL. unfold fvs in HL.\n    apply* extends_concat. auto.\n  assert (HU: unifies (S & combine Xs Us) ((sch_open_vars M0 Xs, T) :: nil)).\n    subst.\n    unfold unifies; simpl; intros.\n    destruct* H. inversions H; clear H.\n    destruct H6. rewrite sch_arity_subst in H.\n    apply* unifies_open.\n    puts (fv_in_spec sch_fv _ _ _ (binds_in B)).\n    unfold fvs, env_fv in HL; simpl in *; auto.\n  case_eq\n    (unify (K0 & kinds_open_vars (sch_kinds M0) Xs) (sch_open_vars M0 Xs) T S0);\n    unfold unify; intros.\n    destruct p as [K' S']. esplit; esplit; esplit. split2*.\n    destruct* (unify_mgu0 (K':=K) (S':=S & combine Xs Us) _ H).\n      intro; intros.\n      subst M.\n      refine (well_subst_concat_abs Xs HTS _ H6 (x:=x) _ _ _ _ _ _ _); auto*.\n      auto.\n    unfold fvs in HL.\n    destruct* (unify_kinds_ok _ _ H).\n    exists (combine Xs Us).\n    intuition.\n    apply* list_forall_env_prop.\n    apply (proj2 (proj1 H6)).\n  elimtype False.\n  refine (unify_complete0 (K:=K) HS0 Ok Hext' HU _ _ H).\n    subst; apply* well_subst_concat_abs. auto.\n  omega.\nQed.\n\nLemma typ_subst_type' : forall S T,\n  type (typ_subst S T) -> type T.\nProof.\n  induction T; simpl; intros; auto.\n  inversions H. auto.\nQed.\n\nLemma sch_subst_ext_fv : forall S1 S2 M,\n  typ_subst_eq_in (sch_fv M) S1 S2 ->\n  sch_subst S1 M = sch_subst S2 M.\nProof.\n  intros.\n  destruct M as [T Ks].\n  unfold sch_subst; simpl.\n  rewrite* H.\n    rewrite* (list_map_ext Ks (kind_subst S1) (kind_subst S2)).\n    intros.\n    apply* kind_subst_ext_fv.\n    unfold env_fv, sch_fv; simpl.\n    intros y Hy.\n    assert (y \\in kind_fv_list Ks).\n      clear -H0 Hy; induction Ks; simpl in *. contradiction.\n      destruct* H0. subst*.\n    auto.\n  unfold env_fv, sch_fv; simpl*.\nQed.\n\nLemma env_subst_ext_fv : forall S1 S2 E,\n  typ_subst_eq_in (env_fv E) S1 S2 ->\n  map (sch_subst S1) E = map (sch_subst S2) E.\nProof.\n  induction E; simpl; intros. auto.\n  destruct a.\n  unfold typ_subst_eq_in in *.\n  rewrite* <- IHE.\n  rewrite* (@sch_subst_ext_fv S1 S2).\n  intro; auto*.\nQed.\n\nLemma principal_abs : forall h L S0 K0 E0 S K t1 T,\n  (forall L S0 K0 E0 S K t T, principality S0 K0 E0 S K t T L h) ->\n  principality S0 K0 E0 S K (trm_abs t1) T L (Datatypes.S h).\nProof.\n  intros until T.\n  intros IHh HS0 HTS0 HK0 Dis HE0 HTS HL Hext WS Typ Hh.\n  simpl.\n  destruct (var_fresh L) as [x1 Fr1]; simpl.\n  destruct (var_fresh (L \\u {{x1}})) as [x2 Fr2]; simpl.\n  destruct (var_fresh (dom E0 \\u trm_fv t1)) as [x Frx]; simpl.\n  inversions Typ; try discriminate.\n  pose (Xs := x1 :: x2 :: nil).\n  pose (Us := U :: T0 :: nil).\n  assert (Fr: fresh L 2 Xs) by simpl*.\n  assert (Hsub: typ_subst_eq_in L (S & combine Xs Us) S).\n    intro; intros.\n    apply* typ_subst_combine_fresh.\n  assert (Hext': extends (S & combine Xs Us) S0).\n    apply* extends_concat. unfold fvs in HL; auto.\n  assert (HU: unifies (S & combine Xs Us)\n                ((typ_arrow (typ_fvar x1) (typ_fvar x2), T) :: nil)).\n    intro; intros.\n    simpl in H; destruct* H. inversions H; clear H.\n    rewrite (typ_subst_combine_fresh S T2).\n      simpl. destruct* (x1 == x1).\n      destruct* (x2 == x1).\n        elim Fr2. rewrite* e0.\n      destruct* (x2 == x2).\n    simpl length. unfold fvs in HL. apply* fresh_sub.\n  case_eq (unify K0 (typ_arrow (typ_fvar x1) (typ_fvar x2)) T S0);\n    unfold unify; intros.\n    destruct p as [K' S'].\n    rewrite normalize_typinf.\n    destruct* (unify_mgu0 _ H (K':=K) (S':=S & combine Xs Us)).\n      apply* well_subst_concat. instantiate (1:=E0); auto.\n    destruct (unify_type _ _ H); auto.\n      simpl; intros.\n      destruct H5; try contradiction.\n      inversions H5.\n      split; auto. apply* (typ_subst_type' S).\n    destruct* (unify_kinds_ok _ _ H).\n    poses Uk (unify_keep_fv' _ _ H (E:=E0) HS0 (proj1 HK0)).\n    poses UT (unify_types _ _ _ H HS0).\n    assert (OkE0': env_ok (E0 & x ~ Sch (typ_fvar x1) nil)) by split2*.\n    assert (TUs: env_prop type (combine Xs Us)).\n      unfold Xs, Us. intro; simpl; intros.\n      rewrite <- H0 in Typ.\n      puts (proj44 (typing_regular Typ)).\n      inversions H10.\n      destruct H9. inversion H9. rewrite* <- H15.\n      destruct* H9. inversion H9. rewrite* <- H15.\n    destruct* (IHh (L\\u{{x1}}\\u{{x2}}) S' K' (E0 & x ~ Sch (typ_fvar x1) nil)\n                   (S & combine Xs Us) K (t1 ^ x) (typ_fvar x2)).\n       clear -UT HL Uk.\n       unfold fvs, all_fv in *; simpl in *.\n       rewrite typ_subst_id in Uk.\n       unfold sch_fv; simpl.\n       sets_solve.\n      simpl typ_subst.\n      destruct (x2 == x1). elim Fr2. rewrite* e.\n      destruct* (x2 == x2). clear n e.\n      destruct (var_fresh (L0 \\u trm_fv t1 \\u {{x}})) as [x0 Fr0].\n      forward~ (H4 x0); intros.\n      rewrite map_concat.\n      rewrite <- (@env_subst_ext_fv S).\n        unfold sch_subst at 2. simpl. destruct* (x1 == x1).\n        env_fix.\n        apply* (@typing_abs_rename x0).\n      clear -Hsub HL.\n      intro; intros.\n      symmetry.\n      unfold fvs in HL.\n      apply* Hsub.\n     simpl in Hh.\n     rewrite trm_depth_open. omega.\n    destruct H9 as [S2 [L' [TI [S3 [HS3 [TS3 [Hext3 WS3]]]]]]].\n    unfold typinf0.\n    esplit; esplit; esplit; split2*.\n    exists (combine Xs Us & S3).\n    rewrite <- concat_assoc.\n    split.\n      rewrite dom_concat.\n      unfold Xs, Us; simpl.\n      destruct* (typinf_sound _ (lt_n_Sn _) TI).\n        unfold fvs in *; simpl. unfold sch_fv; simpl.\n        unfold all_fv in Uk; simpl in Uk.\n        rewrite typ_subst_id in Uk. auto.\n      puts (proj43 (proj44 H10)).\n      clear -HS3 Fr1 Fr2 H11. unfold fvs in H11. simpl in H11.\n      unfold sch_fv in H11. simpl in H11.\n      sets_solve; apply* S.diff_3.\n    split2*.\n  elimtype False.\n  refine (unify_complete0 (K:=K) HS0 (proj1 HK0) Hext' HU _ _ H).\n    apply* well_subst_concat. instantiate (1:=E0); auto.\n  omega.\nQed.\n\nLemma sch_open_vars_type : forall M Xs,\n  scheme M -> sch_arity M = length Xs -> type (sch_open_vars M Xs).\nProof.\n  unfold sch_open_vars, typ_open_vars.\n  intros; fold (sch_open M (typ_fvars Xs)).\n  apply sch_open_types. auto.\n  rewrite H0. apply types_typ_fvars.\nQed.\n\nLemma close_fvk_ok2 : forall K L L',\n  ok K -> L' << close_fvk K L -> close_fvk K L' << close_fvk K L.\nProof.\n  intros.\n  intros y Hy.\n  unfold close_fvk in Hy.\n  puts (cardinal_env H).\n  revert L' H0 Hy H1; generalize (dom K).\n  induction (length K); simpl; intros; auto.\n  case_rewrite R1 (S.choose (S.inter v L')).\n    puts (S.choose_1 R1).\n    assert (e \\in close_fvk K L) by auto.\n    assert (S.cardinal (S.remove e v) = n).\n      assert (e \\in v) by auto.\n      puts (cardinal_remove H4).\n      rewrite H1 in H5.\n      inversion* H5.\n    case_rewrite R2 (get e K).\n      puts (close_fvk_ok L H H3 R2).\n      assert (L' \\u kind_fv k << close_fvk K L) by auto.\n      apply* (IHn _ _ H6 Hy).\n    apply* (IHn _ _ H0 Hy).\n  auto.\nQed.\n\nLemma close_fvk_inv : forall K L,\n  close_fvk K L << fv_in kind_fv K \\u L.\nProof.\n  unfold close_fvk.\n  intro. generalize (dom K).\n  induction (length K); simpl; intros. auto.\n  destruct* (S.choose (S.inter v L)).\n  intro; intros.\n  puts (IHn _ _ _ H).\n  sets_solve.\n  case_rewrite R1 (get e K).\n    use (fv_in_spec kind_fv _ _ _ (binds_in R1)).\n  auto.\nQed.\n\nLemma vars_subst_empty : forall S, vars_subst S {} = {}.\nProof.\n  intros.\n  unfold vars_subst.\n  remember (S.elements {}) as l.\n  destruct* l.\n  assert (SetoidList.InA E.eq e (e::l)) by auto with ordered_type.\n  rewrite Heql in H.\n  puts (S.elements_2 H). elim (in_empty H0).\nQed.\n\nLemma vars_subst_incl : forall S l1 l2,\n  let s := fun x => typ_subst S (typ_fvar x) in\n  incl l1 l2 ->\n  typ_fv_list (List.map s l1) << typ_fv_list (List.map s l2).\nProof.\n  intros; induction l1; simpl. auto.\n  sets_solve.\n    assert (In a l2). apply* H.\n    clear -H0 H1.\n    induction l2; simpl in *. elim H1.\n    destruct H1. subst*.\n    use (IHl2 H).\n  assert (incl l1 l2). intro; intros; apply* H.\n  use (IHl1 H1).\nQed.\n\nLemma vars_subst_union : forall S L1 L2,\n  vars_subst S (L1 \\u L2) = vars_subst S L1 \\u vars_subst S L2.\nProof.\n  intros.\n  unfold vars_subst.\n  set (l:=S.elements (L1 \\u L2)) in *.\n  set (l1:=S.elements L1) in *.\n  set (l2:=S.elements L2) in *.\n  assert (incl (l1 ++ l2) l).\n    intros x Hx.\n    apply InA_In. unfold l; apply S.elements_1.\n    destruct (in_app_or _ _ _ Hx); [apply S.union_2|apply S.union_3];\n      apply S.elements_2; apply (SetoidList.In_InA _).\n      fold l1; auto.\n    fold l2; auto.\n  assert (incl l (l1 ++ l2)).\n    intros x Hx.\n    puts (SetoidList.In_InA _ Hx).\n    apply in_or_app.\n    destruct (S.union_1 (S.elements_2 H0));\n      [left* | right*]; apply InA_In; apply* (S.elements_1 H1).\n  apply eq_ext; split; intros.\n    puts (vars_subst_incl S H0).\n    rewrite map_app in H2.\n    rewrite fv_list_map in H2. auto.\n  puts (vars_subst_incl S H).\n  rewrite map_app in H2.\n  rewrite fv_list_map in H2. auto.\nQed.\n\nLemma typ_fv_after_subst : forall S T,\n  typ_fv (typ_subst S T) = vars_subst S (typ_fv T).\nProof.\n  intros.\n  induction T; simpl. rewrite* vars_subst_empty.\n    unfold vars_subst. rewrite elements_singleton. simpl.\n    rewrite* union_empty_r.\n  rewrite vars_subst_union. congruence.\nQed.\n\nLemma kind_fv_after_subst : forall S k,\n  kind_fv (kind_subst S k) = vars_subst S (kind_fv k).\nProof.\n  unfold kind_fv.\n  intros.\n  destruct k as [[kc kv kr kh]|]; simpl.\n    clear kh; induction kr; simpl. rewrite* vars_subst_empty.\n    rewrite IHkr.\n    rewrite vars_subst_union.\n    rewrite* typ_fv_after_subst.\n  rewrite* vars_subst_empty.\nQed.\n\nLemma sch_fv_after_subst: forall S M,\n  sch_fv (sch_subst S M) = vars_subst S (sch_fv M).\nProof.\n  unfold sch_fv; destruct M as [T Ks]; intros.\n  simpl sch_type. simpl sch_kinds.\n  rewrite vars_subst_union.\n  rewrite typ_fv_after_subst.\n  apply (f_equal (S.union (vars_subst S (typ_fv T)))).\n  induction Ks; simpl. rewrite* vars_subst_empty.\n  rewrite kind_fv_after_subst. rewrite vars_subst_union.\n  congruence.\nQed.\n\nLemma close_fvk_subst : forall K K' S x E,\n  well_subst K K' S -> ok K' ->\n  x \\in close_fvk K (env_fv E) ->\n  typ_fv (typ_subst S (typ_fvar x)) <<\n  close_fvk K' (env_fv (map (sch_subst S) E)).\nProof.\n  unfold env_fv.\n  introv WS Ok Hx.\n  unfold close_fvk in Hx.\n  set (L:=fv_in sch_fv E) in Hx.\n  assert (forall x, x \\in L -> typ_fv (typ_subst S (typ_fvar x)) <<\n    close_fvk K' (fv_in sch_fv (map (sch_subst S) E))).\n    clear x Hx; subst L; intros x Hx.\n    eapply subset_trans; [|apply close_fvk_subset].\n    destruct (fv_in_binds _ _ Hx) as [y [a [Ha B]]].\n    assert (In (y, sch_subst S a) (map (sch_subst S) E)).\n      rewrite <- map_snd_env_map.\n      apply (in_map_snd (sch_subst S) _ _ _ B).\n    eapply subset_trans; [|apply (fv_in_spec sch_fv _ _ _ H)]; clear H.\n    destruct a as [T Ks].\n    unfold sch_fv in Ha; simpl in Ha.\n    destruct (S.union_1 Ha); clear Ha.\n      unfold sch_fv; simpl sch_type.\n      rewrite (typ_fv_after_subst S T).\n      use (vars_subst_in S H).\n    unfold sch_fv; simpl sch_kinds.\n    intros z Hz; apply S.union_3.\n    clear B; induction Ks. elim (in_empty H).\n    simpl in H; simpl. destruct (S.union_1 H); clear H.\n      rewrite (kind_fv_after_subst S).\n      use (vars_subst_in S H0).\n    use (IHKs H0).\n  clearbody L.\n  revert L Hx H. generalize (dom K).\n  induction (length K); simpl close_fvars; intros. auto.\n  case_rewrite R1 (S.choose (S.inter v L)).\n    case_rewrite R2 (get e K).\n      apply (IHn _ _ Hx); clear IHn Hx; intros.\n      destruct* (S.union_1 H0); clear H0.\n      puts (S.inter_2 (S.choose_1 R1)).\n      puts (H _ H0); clear H H0.\n      puts (WS _ _ R2).\n      inversions H.\n        destruct k; try discriminate. elim (in_empty H1).\n      fold (typ_subst S (typ_fvar e)) in H3.\n      rewrite <- H3 in H2. simpl in H2.\n      puts (H2 x1 (S.singleton_2 (refl_equal _))); clear H2.\n      puts (close_fvk_ok _ Ok H4 H5).\n      intros y Hy; apply H2.\n      apply (kind_entails_fv (Some k') (Some k0)). simpl*.\n      rewrite H0. rewrite (kind_fv_after_subst S).\n      apply (vars_subst_in S H1 Hy).\n    apply* IHn.\n  auto*.\nQed.\n\nLemma close_fvk_disjoint : forall K K' L,\n  disjoint (L \\u fv_in kind_fv K) (dom K') -> ok (K & K') ->\n  close_fvk (K & K') L << close_fvk K L.\nProof.\n  introv H Ok x Hx.\n  unfold close_fvk in Hx.\n  set (L' := L) in H, Hx.\n  assert (L' << close_fvk K L) by apply close_fvk_subset.\n  gen L'; generalize (dom (K&K')); induction (length (K & K')); simpl; intros.\n    auto.\n  case_rewrite R1 (S.choose (S.inter v L')).\n    puts (S.inter_2 (S.choose_1 R1)).\n    assert (e # K') by auto.\n    case_eq (get e K); introv R2.\n      rewrite (binds_concat_fresh _ R2 H2) in Hx.\n      refine (IHn _ _ _ Hx _).\n        use (fv_in_spec kind_fv _ _ _ (binds_in R2)).\n      intros y Hy.\n      poses OkK (proj1 (ok_concat_inv _ _ Ok)).\n      apply (close_fvk_ok2 _ OkK H0).\n      clear H0.\n      sets_solve. apply* close_fvk_subset.\n      refine (close_fvk_ok _ OkK _ R2 H0). apply* close_fvk_subset.\n    rewrite get_notin_dom in Hx; auto*.\n  auto.\nQed.\n\nLemma kindl_generalize_reopen : forall Xs Ks,\n  list_forall (All_kind_types type) Ks ->\n  kinds_open (List.map (kind_map (typ_generalize Xs)) Ks) (typ_fvars Xs) = Ks.\nProof.\n  unfold kinds_open; intros.\n  induction H; simpl. auto.\n  rewrite* kind_generalize_reopen.\n  congruence.\nQed.\n\nLemma typ_subst_combine_inv : forall x Xs Ys,\n  let XYs := combine Xs (typ_fvars Ys) in\n  exists y, typ_subst XYs (typ_fvar x) = typ_fvar y\n    /\\ (x = y /\\ x # XYs \\/ binds x (typ_fvar y) XYs).\nProof.\n  induction Xs; destruct Ys; simpl; try solve [exists* x].\n  destruct (x == a). env_fix. subst. exists* v.\n  env_fix.\n  destruct (IHXs Ys) as [y [Ts Hy]].\n  destruct Hy. simpl in Ts; subst. exists* y.\n  exists* y.\nQed.\n\nLemma binds_map_var : forall (A:Set) x y (a:A) Xs Ys As,\n  fresh {} (length Xs) Ys ->\n  binds x (typ_fvar y) (combine Xs (typ_fvars Ys)) ->\n  binds x a (combine Xs As) ->\n  binds y a (combine Ys As).\nProof.\n  unfold binds. generalize {}.\n  induction Xs; destruct Ys; destruct As; simpl; intros; try discriminate.\n  destruct (x == a0).\n    inversions H0.\n    inversions H.\n    destruct* (y == y).\n  destruct (y == v).\n    subst.\n    puts (in_combine_r _ _ _ _ (binds_in H0)).\n    destruct H.\n    clear -H2 H3. elimtype False.\n    gen t. generalize (length Xs).\n    induction Ys; simpl; intros; destruct* n.\n    simpl in H2. destruct H3.\n    destruct H2. inversions* H1.\n    apply* (IHYs H1 n t).\n  apply* (IHXs Ys As).\nQed.\n\nLemma vars_subst_inv : forall S L x,\n  x \\in vars_subst S L ->\n  exists y, y \\in L /\\ x \\in typ_fv (typ_subst S (typ_fvar y)).\nProof.\n  unfold vars_subst.\n  intros.\n  rewrite <- (mkset_elements L).\n  induction (S.elements L). elim (in_empty H).\n  set (sS := typ_subst S) in *.\n  simpl in *.\n  destruct (S.union_1 H); clear H.\n    exists* a.\n  destruct (IHl H0). exists* x0.\nQed.\n\nLemma ftve_subst : forall S' K' E0 S K S1 M Xs y,\n  let K1 := map (kind_subst S') K' in\n  let E1 := map (sch_subst S') E0 in\n  let E := map (sch_subst S) E0 in\n  y \\in close_fvk K1 (env_fv E1) ->\n  env_ok E0 ->\n  extends S1 S' ->\n  well_subst K' (K & kinds_open_vars (sch_kinds M) Xs) S1 ->\n  ok (K & kinds_open_vars (sch_kinds M) Xs) ->\n  fresh (env_fv E \\u fv_in kind_fv K) (sch_arity M) Xs ->\n  typ_subst_eq_in (env_fv E0) S1 S ->\n  typ_fv (typ_subst S1 (typ_fvar y)) << env_fv E \\u fv_in kind_fv K.\nProof.\n  intros until E; intros H OkE0 Hext WS Ok Fr Hsub.\n  poses WS1 (well_subst_extends Hext WS). fold K1 in WS1.\n  intros x Hx.\n  puts (@close_fvk_subst _ _ _ y E1 WS1 Ok H _ Hx).\n  clear H Hx.\n  unfold E1 in H0. rewrite map_sch_subst_extend in H0; auto.\n  rewrite <- (@env_subst_ext_fv S) in H0.\n    fold E in H0.\n    assert (ok (map (sch_subst S) E0)) by auto.\n    cut (x \\in close_fvk K (env_fv E \\u fv_in kind_fv K)); intros.\n      use (close_fvk_inv _ _ H1).\n    refine (close_fvk_ok2 _ _ (L':=env_fv E) _ _).\n        destruct* (ok_concat_inv _ _ Ok).\n      intros z Hz. apply* close_fvk_subset.\n    refine (close_fvk_disjoint _ (kinds_open_vars (sch_kinds M) Xs) _ _ _);\n      auto.\n  intro; intros. symmetry. auto.\nQed.\n\nLemma typinf_generalize_sch_fv : forall K1 E1 T1 e e0 e1 e2 l l0,\n  let ftve := close_fvk K1 (env_fv E1) in\n  let Bs := S.elements (S.diff (close_fvk K1 (typ_fv T1)) (ftve \\u dom e2)) in\n  let l0' := List.map (fun _ : var => None) Bs in\n  let M0 := sch_generalize (l ++ Bs) T1 (l0 ++ l0') in\n  ok K1 ->\n  kenv_ok (e0 & e) ->\n  split_env ftve K1 = (e, e0) -> \n  split_env (close_fvk K1 (typ_fv T1)) e = (e1, e2) ->\n  split e2 = (l, l0) ->\n  sch_fv M0 << ftve.\nProof.\n  intros until M0. intros Ok1 Oke0 R1 R2 R3.\n  unfold M0; intros x Hx.\n  destruct (split_env_ok _ R2).\n    destruct* (ok_concat_inv _ _ (proj1 Oke0)).\n  puts (split_combine _ R3).\n  destruct* (in_vars_dec x ftve).\n  elimtype False.\n  elim (@sch_generalize_disjoint (l++Bs) T1 (l0 ++ l0') x). auto.\n  rewrite mkset_app.\n  unfold Bs; rewrite mkset_elements.\n  rewrite* <- H1.\n  destruct* (in_vars_dec x (mkset l)).\n  cut (x \\in close_fvk K1 (typ_fv T1)). auto*.\n  destruct* (split_env_ok _ R1). clear H H2.\n  puts (sch_fv_generalize Hx).\n  unfold sch_fv in H; simpl in H.\n  sets_solve. apply* close_fvk_subset.\n  rewrite kind_fv_list_app in H2.\n  sets_solve.\n    rewrite <- (fv_in_kind_fv_list _ _ (split_length _ R3)) in H.\n    rewrite H1 in H.\n    destruct (fv_in_binds _ _ H) as [y [b [Hx' Hy]]].\n    assert (In (y,b) K1).\n      apply (proj44 H3).\n      apply in_or_concat; left*.\n    refine (close_fvk_ok _ _ _ _ Hx'); trivial.\n      apply (proj42 H0). apply (in_dom _ _ _ Hy).\n    auto.\n  unfold l0' in H.\n  elimtype False; clear -H; induction Bs. elim (in_empty H).\n  simpl in *. elim IHBs. sets_solve. elim (in_empty H0).\nQed.\n\nLemma sch_subst_compose : forall S1 S2 M,\n  sch_subst (compose S1 S2) M = sch_subst S1 (sch_subst S2 M).\nProof.\n  unfold sch_subst; simpl.\n  intros.\n  rewrite typ_subst_compose.\n  apply f_equal.\n  induction (sch_kinds M). auto.\n  simpl. rewrite IHl. rewrite* kind_subst_compose.\nQed.\n\nLemma typinf_generalize_well_kinded : forall K1 S1 M Xs Ys l l0 K,\n  let XYs := combine Xs (typ_fvars Ys) in\n  fresh (sch_fv M \\u fv_in kind_fv K) (sch_arity M) Xs ->\n  well_subst K1 (K & kinds_open_vars (sch_kinds M) Xs) S1 ->\n  fresh (dom K) (sch_arity M) Ys ->\n  ok K1 ->\n  dom XYs = mkset Xs ->\n  env_prop type XYs ->\n  incl (combine l l0) K1 ->\n  length l = length l0 ->\n  list_forall2 (well_kinded (K & kinds_open_vars (sch_kinds M) Ys))\n    (List.map (kind_subst (compose XYs S1)) l0)\n    (List.map (typ_subst (compose XYs S1)) (List.map typ_fvar l)).\nProof.\n  intros until XYs. intros Fr WS HYs Ok1 DXYs HXYs H6 H0.\n  gen l0. fold kind.\n  induction l; destruct l0; simpl; intros; auto;\n    try discriminate.\n  inversion H0; clear H0.\n  constructor.\n    fold (typ_subst (compose XYs S1) (typ_fvar a)).\n    rename WS into H.\n    assert (well_kinded K1 k (typ_fvar a)) by destruct* k.\n    puts (well_kinded_subst H H0).\n    rewrite kind_subst_compose.\n    rewrite typ_subst_compose.\n    inversions H2. apply wk_any.\n    simpl.\n    rewrite <- H4.\n    clear H3 H4 IHl.\n    destruct (typ_subst_combine_inv x Xs Ys) as [y [Tsy Hy]].\n    fold XYs in Tsy. rewrite Tsy.\n    destruct Hy. destruct H3. subst.\n      binds_cases H7.\n        eapply wk_kind. puts (binds_dom B). apply* binds_concat_fresh.\n        assert (kind_subst XYs (Some k') = (Some k')).\n          apply kind_subst_fresh.\n          rewrite DXYs. \n          use (fv_in_spec kind_fv _ _ _ (binds_in B)).\n        simpl in H3. inversion H3.\n        apply (kind_subst_entails XYs H8).\n      fold XYs in H4; rewrite DXYs in H4.\n      puts (binds_dom B0). rewrite dom_kinds_open_vars in H3; auto*.\n    binds_cases H7.\n      fold XYs in H3.\n      puts (binds_dom H3).\n      rewrite DXYs in H4.\n      rewrite dom_kinds_open_vars in Fr0; auto*.\n    puts (binds_map (kind_subst XYs) B0).\n    apply* (@wk_kind (ckind_map (typ_subst XYs) k')).\n    apply binds_prepend.\n    unfold kinds_open_vars in H4.\n    rewrite map_combine in H4.\n    rewrite kinds_subst_open in H4; auto.\n    poses Fr' Fr.\n    rewrite (fresh_length _ _ _ HYs) in Fr'.\n    replace (length Ys) with (length (typ_fvars Ys)) in Fr' by auto.\n    puts (fresh_subst _ _ _ Fr').\n    fold XYs in H5; rewrite H5 in H4.\n    rewrite kinds_subst_fresh in H4.\n      apply* binds_map_var.\n    rewrite* <- (fresh_length _ _ _ Fr).\n    unfold sch_fv in Fr.\n    rewrite* DXYs.\n  apply* (IHl l0).\nQed.\n\nLemma moregen_let :\n  forall M Xs S' x1 l l0 L L' (K' K0 K:kenv) E0 S S'' e e0 e1 e2 t1,\n  let E := map (sch_subst S) E0 in\n  let MXs := sch_open_vars M Xs in\n  let K1 := map (kind_subst S') K' in\n  let E1 := map (sch_subst S') E0 in\n  let ftve := close_fvk K1 (env_fv E1) in\n  let T1 := typ_subst S' (typ_fvar x1) in\n  let Bs := S.elements (S.diff (close_fvk K1 (typ_fv T1)) (ftve \\u dom e2)) in\n  let l0' := List.map (fun _ : var => None) Bs in\n  let M0 := sch_generalize (l++Bs) T1 (l0++l0') in\n  env_ok E0 ->\n  split_env ftve K1 = (e, e0) ->\n  split_env (close_fvk K1 (typ_fv T1)) e = (e1, e2) ->\n  split e2 = (l, l0) ->\n  dom S \\u env_fv E0 << L ->\n  dom S'' << S.diff L' (L \\u {{x1}}) -> \n  extends (S & x1 ~ MXs & S'') S' ->\n  fresh (L \\u {{x1}} \\u env_fv E \\u sch_fv M \\u fv_in kind_fv K)\n    (sch_arity M) Xs ->\n  x1 \\notin L ->\n  is_subst S' -> env_prop type S' -> env_prop type S -> env_prop type S'' ->\n  kenv_ok (e0 & e) -> kenv_ok (e2 & e1) -> ok K' ->\n  well_subst K' (K & kinds_open_vars (sch_kinds M) Xs) (S & x1 ~ MXs & S'') ->\n  K & kinds_open_vars (sch_kinds M) Xs; E |(false, GcAny)|= t1 ~: MXs ->\n  typ_subst_eq_in L (S & x1 ~ MXs) S ->\n  (forall S, typ_subst_eq_in (L \\u {{x1}}) (S & S'') S) ->\n  moregen_scheme K (sch_subst (S & x1 ~ MXs & S'') M0) M.\nProof.\n  intros until M0.\n  intros OkE0 R1 R2 R3 HL HS'' Hext Fr Fr1 HS' HTS' HTS HTS''\n    Oke0 Oke2 Ok' WS Typ Hsub Hsub'.\n  intro; intros.\n  assert (type T1) by (unfold T1; auto).\n  assert (env_prop type (S & x1 ~ MXs)) by auto.\n  assert (env_prop type (S & x1 ~ MXs & S'')) by auto.\n  set (S1 := S & x1 ~ MXs & S'') in *.\n  pose (XYs := combine Xs (typ_fvars Ys)).\n  assert (Ok1: ok K1) by (unfold K1; auto).\n  assert (sch_fv M0 << ftve)\n    by apply (typinf_generalize_sch_fv _ Ok1 Oke0 R1 R2 R3).\n  assert(sch_fv (sch_subst S1 M0) << env_fv E \\u fv_in kind_fv K).\n    intros x Hx.\n    rewrite sch_fv_after_subst in Hx.\n    destruct (vars_subst_inv _ _ Hx) as [y [Hy Hx']].\n    unfold ftve, K1, E1 in *;\n      refine (ftve_subst _ _ _ (H3 _ Hy) _ Hext WS _ _ _ Hx'); auto.\n    intro; intros; unfold fvs in HL; unfold S1; rewrite* Hsub'.\n  assert (DXYs: dom XYs = mkset Xs).\n    unfold XYs. rewrite dom_combine. auto.\n    rewrite <- (fresh_length _ _ _ Fr).\n    unfold typ_fvars; rewrite map_length.\n    auto.\n  assert (sch_subst (compose XYs S1) M0 = sch_subst S1 M0).\n    rewrite sch_subst_compose.\n    apply sch_subst_fresh.\n    rewrite* DXYs.\n  assert (HXYs: env_prop type XYs).\n     apply list_forall_env_prop. apply (proj2 (types_typ_fvars Ys)).\n  exists (List.map (typ_subst (compose XYs S1)) (typ_fvars (l ++ Bs))).\n  split.\n    split.\n      rewrite sch_arity_subst.\n      unfold M0. simpl.\n      split.\n        unfold l0'. length_hyps. fold kind; rewrite* <- H7.\n      puts (proj2 (types_typ_fvars (l++Bs))).\n      clear -H6 H2 HXYs; induction H6; simpl*.\n    replace (kinds_open (sch_kinds (sch_subst S1 M0))\n        (List.map (typ_subst (compose XYs S1)) (typ_fvars (l ++ Bs))))\n       with (List.map (kind_subst (compose XYs S1))\n              (kinds_open (sch_kinds M0) (typ_fvars (l ++ Bs)))).\n      unfold M0; simpl.\n      rewrite kindl_generalize_reopen.\n      unfold typ_fvars; repeat rewrite map_app.\n      apply list_forall2_app.\n        assert (incl e2 K1). intro; intros.\n          destruct (split_env_ok _ R1); auto.\n          destruct (split_env_ok _ R2); [auto*|].\n          apply (proj44 H8).\n          apply in_or_concat; left*.\n        rewrite <- (split_combine _ R3)in H6.\n        apply* (@typinf_generalize_well_kinded (map (kind_subst S') K')).\n      unfold l0'. clearbody Bs XYs S1. clear.\n      induction Bs; simpl. auto.\n     constructor; auto.\n    apply list_forall_app.\n      puts (split_combine _ R3).\n      refine (env_prop_list_forall l _ _ _ _); auto*; fold kind; rewrite* H6.\n    unfold l0'; clearbody Bs; clear. induction Bs; simpl*.\n   rewrite kinds_subst_open.\n     clearbody M0; clear -H5. unfold sch_subst in H5; simpl in H5.\n     inversion H5. rewrite* H1.\n   apply* env_prop_type_compose.\n  rewrite <- H5.\n  rewrite <- sch_subst_open.\n   rewrite typ_subst_compose.\n   replace M with (sch_subst XYs M).\n    rewrite <- (fresh_subst {} Xs (typ_fvars Ys)). fold XYs.\n     rewrite <- sch_subst_open.\n      unfold M0; simpl.\n      unfold sch_open. simpl.\n      rewrite* typ_generalize_reopen.\n      unfold S1, T1.\n      rewrite Hext.\n      unfold S1; rewrite typ_subst_concat_fresh.\n        simpl. destruct* (x1 == x1).\n      simpl*.\n     auto.\n    unfold typ_fvars; rewrite map_length.\n    rewrite* <- (fresh_length _ _ _ H).\n   rewrite* sch_subst_fresh.\n   rewrite* DXYs.\n  apply* env_prop_type_compose.\nQed.\n\nLemma binds_kdom_inv : forall x K,\n  ok K -> x \\in kdom K -> exists k, binds x (Some k) K.\nProof.\n  induction 1; intros. elim (in_empty H).\n  simpl in H1. destruct a.\n    destruct (x == x0). subst. exists* c.\n    destruct (S.union_1 H1). elim n. rewrite* (S.singleton_1 H2).\n    destruct (IHok H2). exists* x1.\n  destruct (IHok H1). exists* x1.\nQed.\n\nLemma kdom_dom : forall K, kdom K << dom K.\n  induction K; simpl*. destruct a. destruct* k.\nQed.\n\nLemma principal_let : forall h L S0 K0 E0 S K t1 t2 T,\n  (forall L S0 K0 E0 S K t T, principality S0 K0 E0 S K t T L h) ->\n  principality S0 K0 E0 S K (trm_let t1 t2) T L (Datatypes.S h).\nProof.\n  intros until T.\n  intros IHh HS0 HTS0 HK0 Dis HE0 HTS HL Hext WS Typ Hh.\n  simpl.\n  destruct (var_fresh L) as [x1 Fr1]; simpl.\n  destruct (var_fresh (dom E0 \\u trm_fv t1 \\u trm_fv t2)) as [x Frx]; simpl.\n  inversions Typ; try discriminate.\n  destruct (var_freshes (L1 \\u L \\u {{x1}} \\u env_fv (map (sch_subst S) E0)\n    \\u sch_fv M \\u fv_in kind_fv K) (sch_arity M))\n    as [Xs Fr].\n  forward~ (H3 Xs); clear H3; intros Typ1.\n  set (MXs := sch_open_vars M Xs) in *.\n  assert (Hcb: x1 ~ MXs = combine (x1::nil) (MXs :: nil)) by simpl*.\n  assert (Hsub: typ_subst_eq_in L (S & x1 ~ MXs) S).\n    intro; intros.\n    apply typ_subst_concat_fresh.\n    simpl. intro y; destruct* (y == x1).\n  assert (Hext0: extends (S & x1 ~ MXs) S0).\n    rewrite Hcb.\n    apply* (@extends_concat S0 S L 1).\n    unfold fvs in HL; auto.\n  destruct* (IHh (L \\u {{x1}}) S0 K0 E0 (S & x1 ~ MXs)\n                (K & kinds_open_vars (sch_kinds M) Xs) t1 (typ_fvar x1))\n    as [K' [S' [L' [HI [S'' H'']]]]].\n     rewrite Hcb.\n     apply* (@well_subst_concat E0).\n     apply* well_subst_extends.\n     intro; intros.\n     apply* well_kinded_extend.\n    simpl typ_subst. destruct* (x1 == x1).\n    rewrite (@env_subst_ext_fv _ S). auto.\n    unfold fvs in HL; intro; intros; apply* Hsub.\n   simpl in Hh.\n   eapply Lt.le_lt_trans. apply (Max.le_max_l (trm_depth t1) (trm_depth t2)).\n   omega.\n  rewrite normalize_typinf; unfold typinf0.\n  rewrite HI.\n  set (K1 := map (kind_subst S') K') in *.\n  set (E1 := map (sch_subst S') E0) in *.\n  fold (typ_subst S' (typ_fvar x1)).\n  set (T1 := typ_subst S' (typ_fvar x1)) in *.\n  unfold typinf_generalize.\n  set (ftve := close_fvk K1 (env_fv E1)) in *.\n  case_eq (split_env ftve K1); intros.\n  case_eq (split_env (close_fvk K1 (typ_fv T1)) e); intros.\n  case_eq (split e2); intros.\n  case_eq (split_env (vars_subst S' (kdom K0)) e); intros.\n  set (Bs := S.elements (S.diff (close_fvk K1 (typ_fv T1)) (ftve \\u dom e2)))\n    in *.\n  set (l0' := List.map (fun _ : var => @None ckind) Bs) in *.\n  set (M0 := sch_generalize (l++Bs) T1 (l0++l0')).\n  destruct* (typinf_sound _ (lt_n_Sn _) HI). simpl*.\n  rewrite normalize_typinf.\n  assert (OkK1: kenv_ok K1) by apply* kenv_ok_map.\n  destruct* (split_env_ok _ H).\n  assert (Oke: kenv_ok (e0 & e)). kenv_ok_solve; intro; intros; apply* H13.\n  assert (Oke1: kenv_ok (e2 & e1)).\n    destruct* (split_env_ok _ H0).\n    kenv_ok_solve; intro; intros; apply* H22.\n  assert (HM0: scheme M0).\n    unfold M0; apply* scheme_generalize.\n        do 2 rewrite app_length. unfold l0'; rewrite map_length.\n        rewrite* (split_length _ H1).\n      unfold T1; auto*.\n    apply list_forall_app.\n      rewrite <- (split_combine _ H1) in Oke1.\n      apply (env_prop_list_forall l); auto*.\n    unfold l0'; clear. induction Bs; simpl*.\n  assert (Hsub': forall S, typ_subst_eq_in (L \\u {{x1}}) (S & S'') S).\n    intros S1 T' HT'; apply* typ_subst_concat_fresh.\n  assert (Inc04: incl (e0 & e4) K1).\n    intro; intros. apply (proj44 H7).\n    destruct (in_concat_or _ _ _ H8); auto.\n    destruct (split_env_ok _ H2). destruct* Oke.\n    apply in_or_concat. left*; apply* (proj44 H11).\n  assert (Ok04: kenv_ok (e0 & e4)).\n    destruct* (split_env_ok _ H2).\n    kenv_ok_solve.\n      use (incl_subset_dom (proj44 H9)).\n    intro; intros; apply* H25.\n  assert (Dis04: disjoint (dom S') (dom (e0 & e4))).\n    puts (proj41 (proj44 H4)).\n    puts (incl_subset_dom Inc04).\n    clear -H8 H9; subst K1; rewrite dom_map in H9; auto.\n  assert (Fvs04: fvs S' (e0 & e4) (E0 & x ~ M0) \\u typ_fv T << L').\n    puts (incl_subset_dom Inc04).\n    puts (incl_fv_in_subset kind_fv Inc04).\n    subst K1. rewrite dom_map in H8.\n    puts (fv_in_kind_subst S' K').\n    intuition trivial.\n    unfold fvs. unfold fvs in H22.\n    sets_solve. simpl in H25. sets_solve.\n    unfold M0, T1 in H23.\n    puts (sch_fv_generalize H23); clear H23.\n    unfold sch_fv in H25; simpl in H25.\n    fold (typ_subst S' (typ_fvar x1)) in H25.\n    sets_solve. puts (typ_fv_subst _ _ H23). simpl in H25; auto.\n    rewrite kind_fv_list_app in H23.\n    sets_solve.\n      rewrite <- (fv_in_kind_fv_list _ _ (split_length _ H1)) in H25.\n      rewrite (split_combine _ H1) in H25.\n      destruct* (split_env_ok _ H0).\n      puts (incl_fv_in_subset kind_fv (proj44 H26)).\n      use (incl_fv_in_subset kind_fv H21).\n    unfold l0' in H25; clearbody Bs; clear -H25.\n    induction Bs; simpl in *; auto*. sets_solve. elim (in_empty H). auto.\n  assert (OkE0': env_ok (E0 & x ~ M0)) by auto.\n  assert (HT: type T) by apply* (typ_subst_type' S).\n  assert (MG: moregen_scheme K (sch_subst (S & x1 ~ MXs & S'') M0) M).\n    apply* moregen_let.\n    clear -HL; unfold fvs in HL; auto.\n  destruct* (IHh L' S' (e0&e4) (E0&x~M0) (S& x1~MXs &S'') K (t2 ^ x) T)\n    as [K'' [S1' [L'' [HI' [S1'' H1'']]]]].\n       sets_solve.\n       repeat rewrite dom_concat in H9.\n       rewrite dom_single in H9.\n       destruct H4 as [_ [_ [_ [_ [_ [HL' _]]]]]].\n       destruct H'' as [HS'' _].\n       assert (Hy: y \\in {{y}}); auto.\n     intro; intros.\n     assert (binds Z k K1) by auto*.\n     subst K1. destruct (binds_map_inv _ _ H9) as [k1 [Hk1 Bk1]].\n     subst k.\n     puts ((proj44 H'') _ _ Bk1).\n     rewrite (kind_subst_extend k1 (proj43 H'')).\n     inversions H10. destruct k1; try discriminate; auto.\n     simpl; rewrite <- H11; rewrite <- H12.\n     binds_cases H14. auto*.\n     env_fix.\n     fold (typ_subst (S & x1 ~ MXs & S'') (typ_fvar Z)) in H12.\n     puts (binds_dom B0); clear B0 H10 H11.\n     rewrite dom_kinds_open_vars in H13 by auto.\n     binds_cases H8.\n       assert (x0 \\in typ_fv (typ_subst (S & x1 ~ MXs & S'') (typ_fvar Z))).\n         rewrite <- H12. simpl*.\n       assert (x0 \\in env_fv (map (sch_subst S) E0) \\u fv_in kind_fv K).\n         assert (Z \\in ftve). apply (proj42 H7). apply (binds_dom B).\n         refine (ftve_subst _ _ _ H10 _ (proj43 H'') (proj44 H'') _ _ _ H8);\n           auto.\n         intro; intros; unfold fvs in HL; rewrite* Hsub'.\n       elim (fresh_disjoint _ _ Fr H13); auto.\n     destruct* (split_env_ok _ H2).\n     puts ((proj42 H10) _ (binds_dom B0)).\n     destruct (vars_subst_inv _ _ H11) as [y [Hy By]].\n     destruct (binds_kdom_inv (proj1 HK0) Hy).\n     puts ((proj42 (proj44 H4)) _ _ H14).\n     inversion H16. fold (typ_subst S' (typ_fvar y)) in H18.\n     rewrite <- H18 in By.\n     simpl in By. rewrite (S.singleton_1 By) in H18.\n     rewrite H18 in H12.\n     rewrite (proj43 H'') in H12.\n     unfold fvs in HL; puts (kdom_dom K0).\n     rewrite Hsub' in H12 by simpl*. rewrite Hsub in H12 by simpl*.\n     subst. puts (WS _ _ H14).\n     rewrite <- H12 in H17.\n     inversions H17.\n     clear -H13 H25 Typ1 Fr.\n     elim (ok_disjoint _ _ (proj1 (proj41 (typing_regular Typ1)))\n             (binds_dom H25)).\n     auto.\n    poses HTS'' (proj42 H'').\n    assert (HMXs: type MXs) by auto.\n    clear -Hsub Hsub' H5 HL Frx MG HE0 HM0 HTS HTS'' HMXs.\n    rewrite* Hsub'. rewrite Hsub by auto. simpl gc_raise in H5.\n    destruct (var_fresh (L2 \\u trm_fv t2 \\u {{x}})) as [x0 Fr0].\n    forward~ (H5 x0) as Typ2.\n    apply (@typing_moregen _ K (map (sch_subst S) E0 & x ~ M)).\n        apply* (@typing_abs_rename x0).\n      rewrite map_concat.\n      rewrite (@env_subst_ext_fv _ (S & x1 ~ MXs)).\n       rewrite (@env_subst_ext_fv _ S).\n        simpl map.\n        apply moregen_env_push. apply moregen_env_refl.\n        apply MG.\n       clear -HL Hsub; unfold fvs in HL; intro; intros; apply* Hsub.\n      clear -HL Hsub'; unfold fvs in HL; intro; intros; apply* Hsub'.\n     apply* env_ok_map.\n   simpl in Hh.\n   rewrite trm_depth_open.\n   clear -Hh.\n   puts (Max.le_max_r (trm_depth t1) (trm_depth t2)). omega.\n  env_fix. esplit; esplit; esplit; split2*.\n  destruct* (typinf_sound _ (lt_n_Sn _) HI').\n  exists (x1~MXs & S'' & S1'').\n  repeat rewrite <- concat_assoc.\n  intuition trivial.\n    repeat rewrite dom_concat; simpl.\n    sets_solve. apply* S.diff_3.\n      assert (Hy : y \\in {{y}}); auto.\n    use (notin_subset H29 Hn).\n  auto.\nQed.\n\nLemma principal_app : forall h L S0 K0 E0 S K t1 t2 T,\n  (forall L S0 K0 E0 S K t T, principality S0 K0 E0 S K t T L h) ->\n  principality S0 K0 E0 S K (trm_app t1 t2) T L (Datatypes.S h).\nProof.\n  intros until T.\n  intros IHh HS0 HTS0 HK0 Dis HE0 HTS HL Hext WS Typ Hh.\n  simpl.\n  destruct (var_fresh L) as [x1 Fr1]; simpl.\n  inversions Typ; try discriminate. simpl in *.\n  rewrite normalize_typinf.\n  assert (Hsub: typ_subst_eq_in L (S & x1 ~ S1) S).\n    intro; intros.\n    apply typ_subst_concat_fresh.\n    simpl. intro y; destruct* (y == x1).\n  assert (Hcb: x1 ~ S1 = combine (x1::nil) (S1 :: nil)) by simpl*.\n  assert (Hext0: extends (S & x1 ~ S1) S0).\n    rewrite Hcb.\n    apply* (@extends_concat S0 S L 1).\n    unfold fvs in HL; auto.\n  destruct* (IHh (L \\u {{x1}}) S0 K0 E0 (S & x1 ~ S1) K t1\n                 (typ_arrow (typ_fvar x1) T))\n    as [K' [S' [L' [HI [S'' H'']]]]].\n     rewrite Hcb; apply* (@well_subst_concat E0).\n    rewrite (@env_subst_ext_fv _ S).\n     simpl. destruct* (x1 == x1). env_fix. rewrite~ Hsub.\n    intro; intros. unfold fvs in HL; apply* Hsub.\n   clear -Hh.\n   puts (Max.le_max_l (trm_depth t1) (trm_depth t2)). omega.\n  intuition.\n  unfold typinf0; rewrite HI.\n  destruct* (typinf_sound _ (lt_n_Sn _) HI). use (typ_subst_type' S T).\n  intuition.\n  rewrite normalize_typinf.\n  assert (Hsub': forall S, typ_subst_eq_in (L \\u {{x1}}) (S & S'') S).\n    intros S2 T2 HT2; apply* typ_subst_concat_fresh.\n  destruct* (IHh L' S' K' E0 (S & x1 ~ S1 & S'') K t2 (typ_fvar x1))\n    as [K'' [S1' [L'' [HI' [S1'' H''']]]]].\n     repeat rewrite dom_concat; simpl. sets_solve. apply* H11. apply* H11.\n    rewrite (@env_subst_ext_fv _ S).\n     rewrite Hsub' by auto. simpl. destruct* (x1 == x1).\n    intro; intros. unfold fvs in HL.\n    rewrite Hsub' by auto. apply* Hsub.\n   clear -Hh.\n   puts (Max.le_max_r (trm_depth t1) (trm_depth t2)). omega.\n  intuition.\n  unfold typinf0.\n  esplit; esplit; esplit; split2*.\n  destruct* (typinf_sound _ (lt_n_Sn _) HI'). simpl*. intros y Hy; apply* H11.\n  exists (x1 ~ S1 & S'' & S1'').\n  repeat rewrite <- concat_assoc.\n  intuition trivial.\n    repeat rewrite dom_concat; simpl*.\n    sets_solve. apply* S.diff_3. apply* H23. apply* S.union_3.\n    apply* S.diff_3.\n  auto.\nQed.\n\nLemma principal_cst : forall h L S0 K0 E0 S K c T,\n  principality S0 K0 E0 S K (trm_cst c) T L (Datatypes.S h).\nProof.\n  intros; intros HS0 HTS0 HK0 Dis HE0 HTS HL Hext WS Typ Hh.\n  inversions Typ; clear Typ; try discriminate.\n  simpl.\n  set (M := Delta.type c) in *.\n  destruct (var_freshes L (sch_arity M)) as [Xs Fr]; simpl.\n  assert (Hsub: typ_subst_eq_in L (S & combine Xs Us) S).\n    intro; intros.\n    apply* typ_subst_combine_fresh.\n    apply* fresh_sub. rewrite* <- (proj1 (proj1 H5)).\n  assert (Ok: ok (K0 & kinds_open_vars (sch_kinds M) Xs)).\n    unfold fvs in HL.\n    apply* ok_kinds_open_vars. apply* fresh_sub.\n  assert (Hext': extends (S & combine Xs Us) S0).\n    clear -Fr Hext Hsub HL. unfold fvs in HL.\n    apply* extends_concat. auto.\n  assert (HU: unifies (S & combine Xs Us) ((sch_open_vars M Xs, T) :: nil)).\n    unfold unifies; simpl; intros.\n    destruct* H. inversions H; clear H.\n    destruct H5.\n    apply* unifies_open.\n      sets_solve. unfold M in H3. rewrite Delta.closed in H3. auto.\n    rewrite* sch_subst_fresh.\n    unfold M. rewrite Delta.closed. intro; auto.\n  destruct H5 as [TUs Wk].\n  assert (WS': well_subst (K0 & kinds_open_vars (sch_kinds M) Xs) K \n                          (S & combine Xs Us)).\n    intro; intros.\n    binds_cases H.\n      refine (well_subst_concat (E:=E0) _ (well_subst_extends Hext WS)\n                    Hsub Hext' _ _); auto.\n    simpl.\n    case_eq (get Z (combine Xs Us)); intros.\n      rewrite (binds_prepend S H).\n      unfold kinds_open_vars, kinds_open in B0.\n      rewrite <- map_combine in B0.\n      destruct (binds_map_inv _ _ B0) as [k1 [Hk1 Bk]].\n      subst k.\n      assert (kind_fv k1 = {}).\n        puts (fv_in_spec kind_fv _ _ _ (binds_in Bk)). simpl in H2.\n        puts (fv_in_sch Xs M).\n        apply eq_ext; split; intros; auto.\n        sets_solve.\n        unfold M in Hin0; rewrite Delta.closed in Hin0; auto.\n      rewrite <- kind_subst_intro0; trivial.\n        puts (binds_map (fun k => kind_open k Us) Bk).\n        simpl in H3; rewrite map_combine in H3.\n        unfold kinds_open in Wk.\n        puts (list_forall2_get _ Wk H3 H).\n        rewrite kind_subst_fresh. auto.\n        rewrite* H2.\n       rewrite H2; rewrite* <- (fresh_length _ _ _ Fr).\n      rewrite* <- (fresh_length _ _ _ Fr).\n    elim (get_none_notin _ H). auto.\n  case_eq\n    (unify (K0 & kinds_open_vars (sch_kinds M) Xs) (sch_open_vars M Xs) T S0);\n    unfold unify; intros.\n    destruct p as [K' S']. esplit; esplit; esplit. split2*.\n    destruct* (unify_mgu0 (K':=K) (S':=S & combine Xs Us) _ H).\n    unfold fvs in HL.\n    destruct* (unify_kinds_ok _ _ H).\n    exists (combine Xs Us).\n    intuition.\n    apply* list_forall_env_prop. apply (proj2 TUs).\n  elimtype False.\n  refine (unify_complete0 (K:=K) HS0 Ok Hext' HU _ _ H). auto.\n  omega.\nQed.\n\nTheorem typinf_principal : forall h L S0 K0 E0 S K t T,\n  principality S0 K0 E0 S K t T L h.\nProof.\n  induction h; intros until T;\n    intros HS0 HTS0 HK0 Dis HE0 HTS HL Hext WS Typ Hh;\n    try (elimtype False; omega).\n  inversions Typ.\n  apply* principal_var.\n  apply* principal_abs.\n  apply* principal_let.\n  apply* principal_app.\n  apply* principal_cst.\n  discriminate.\nQed.\n\nCorollary typinf_principal' : forall K E t T,\n  env_fv E = {} ->\n  K; E |(false,GcAny)|= t ~: T ->\n  exists K', exists T', typinf' E t = Some (K', T') /\\\n    exists S, well_subst K' K S /\\ T = typ_subst S T'.\nProof.\n  introv HE Typ.\n  destruct*\n    (@typinf_principal (S (trm_depth t)) (S.singleton var_default)\n      empty empty E (var_default ~ T) K t (typ_fvar var_default))\n    as [K' [S' [L' H']]];\n    try solve [try split2*; intro; auto; intros; elim H].\n      unfold fvs; rewrite HE; simpl*.\n     intro; intros. replace (@empty typ) with id by reflexivity.\n     rewrite* typ_subst_id.\n    intro; intros. elim (binds_empty H).\n   simpl. destruct* (var_default == var_default).\n   rewrite* map_sch_subst_fresh. rewrite* HE.\n  intuition.\n  unfold typinf'. rewrite H.\n  esplit; esplit; split2*.\n  destruct H0 as [S''].\n  intuition.\n  exists (var_default ~ T & S'').\n  split.\n    apply* well_subst_extends.\n  rewrite H2.\n  rewrite typ_subst_concat_fresh.\n    simpl. destruct* (var_default == var_default).\n  simpl.\n  intro.\n  destruct* (x == var_default).\nQed.\n\nEnd Mk2.\nEnd MkInfer.\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_Inference.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.2958868035538071}}
{"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.\nRequire Export list. (* why? *)\n\n\n\nLemma cover_vars_upto_if_cover_vars_lsubst {o} :\n  forall (t : @NTerm o) sub s,\n    cover_vars (lsubst t s) sub\n    -> cover_vars_upto t (csub_filter sub (dom_sub s)) (dom_sub s).\nProof.\n  introv c.\n\n  allrw @cover_vars_eq.\n  allunfold @cover_vars_upto.\n  allrw subvars_prop.\n  introv i.\n  rw in_app_iff.\n  rw @dom_csub_csub_filter.\n  rw in_remove_nvars.\n  generalize (in_deq NVar deq_nvar x (dom_sub s)); introv j.\n  destruct j as [j | j]; try (complete sp).\n  right; dands; auto.\n  apply c.\n  generalize (eqvars_free_vars_disjoint t s); introv e.\n  rw eqvars_prop in e; apply e; clear e.\n  rw in_app_iff; rw in_remove_nvars; sp.\nQed.\n\nLemma substc_lsubstc_type_family_codom {o} :\n  forall (a : @NTerm o) x B f t s1 s2 wa wb ws ca cb cs,\n    !LIn f (free_vars B)\n    -> !LIn f (bound_vars B)\n    -> disjoint (remove_nvars [x] (free_vars B)) (dom_csub s2)\n    -> disjoint (dom_csub s1) (bound_vars B)\n    -> disjoint (dom_csub s2) (bound_vars B)\n    -> substc (lsubstc a wa (snoc s1 (f, t) ++ s2) ca) x\n              (lsubstc_vars B wb (csub_filter s1 [x]) [x] cb)\n       = lsubstc (subst B x a) ws (snoc s1 (f, t) ++ s2) cs.\nProof.\n  introv nifb1 nifb2 disj1 disj2 disj3.\n  rw @substc_eq_lsubstc.\n  apply lsubstc_eq_if_csubst; simpl.\n  rw @csubst_app; simpl.\n  rw @csubst_swap_app.\n  unfold csubst, subst.\n  rw @simple_lsubst_lsubst; simpl.\n  unfold csubst.\n  rw @fold_csubst.\n  repeat (rw <- @simple_lsubst_cons).\n  remember (subst B x (csubst a (snoc s1 (f, t) ++ s2))).\n  rw <- @sub_filter_csub2sub.\n  rw @lsubst_sub_filter.\n  rw <- @csub2sub_app.\n  rw @csub2sub_snoc.\n  rw @subset_free_vars_sub_app.\n  rw snoc_as_append.\n  rw @subset_free_vars_sub_app.\n  auto.\n  introv.\n  rw in_app_iff; simpl; sp; cpx.\n  allapply @in_csub2sub; sp.\n  subst; unfold subst.\n  rw @isprogram_lsubst2; simpl.\n  rw disjoint_remove_nvars_l; simpl.\n  rw remove_nvars_cons; simpl.\n  destruct (eq_var_dec x f); subst; sp.\n  rw remove_nvars_nil_l.\n  apply disjoint_nil_r.\n  rw disjoint_singleton_r; auto.\n  sp; cpx.\n  apply isprogram_csubst; sp; rw @nt_wf_eq; sp.\n  introv.\n  rw in_app_iff; simpl; rw in_snoc; sp; cpx.\n  allapply @in_csub2sub; sp.\n  allapply @in_csub2sub; sp.\n  subst; unfold subst.\n  rw @isprogram_lsubst2; simpl.\n  rw @dom_csub_eq.\n  insub.\n  sp; cpx.\n  apply isprogram_csubst; sp; rw @nt_wf_eq; sp.\n  intros.\n  allapply @in_csub2sub; sp.\n  subst; unfold subst.\n  rw @isprogram_lsubst2; simpl.\n  rw disjoint_remove_nvars_l; simpl.\n  rw remove_nvars_eq; sp.\n  sp; cpx.\n  apply isprogram_csubst; sp; rw @nt_wf_eq; sp.\n  apply isprogram_csubst; sp; rw @nt_wf_eq; sp.\n  sp.\n  allapply @in_csub2sub; sp.\n  apply isprogram_csubst; sp; rw @nt_wf_eq; sp.\n  sp.\n  allapply @in_csub2sub; sp.\n  sp; cpx.\n  apply cover_vars_disjoint with (sub := snoc s1 (f, t) ++ s2); sp.\n  rw @dom_csub_app; rw @dom_csub_snoc; simpl.\n  rw disjoint_app_l; rw disjoint_snoc_l; sp.\n  insub.\n  insub.\n  sp.\n  allapply @in_csub2sub; sp.\n  simpl.\n  rw @dom_csub_csub_filter.\n  rw disjoint_remove_nvars_l; simpl.\n  rw remove_nvars_eq; sp.\nQed.\n\nLemma lsubstc2_lsubstc_var {o} :\n  forall bp ba (B : @NTerm o) p a wB s cvB vp va w c,\n    !LIn vp (bound_vars B)\n    -> !LIn va (bound_vars B)\n    -> ((!LIn vp [bp,ba]) -> !LIn vp (free_vars B))\n    -> ((!LIn va [bp,ba]) -> !LIn va (free_vars B))\n    -> !LIn vp (dom_csub s)\n    -> !LIn va (dom_csub s)\n    -> !(ba = bp)\n    -> !(va = vp)\n    -> lsubstc2 bp p ba a\n                (lsubstc_vars B wB (csub_filter s [bp, ba]) [bp, ba] cvB)\n       = lsubstc (lsubst B [(bp, mk_var vp), (ba, mk_var va)]) w\n                 (snoc (snoc s (vp, p)) (va, a)) c.\nProof.\n  introv disj1 disj2 disj3 disj4 disj5 disj6 disj7 disj8.\n\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n\n  repeat (rw @simple_lsubst_lsubst; simpl);\n    try (complete (sp; cpx; simpl; rw disjoint_singleton_l; sp));\n    try (complete (sp; allapply @in_csub2sub; sp; allunfold @isprogram; sp; allrw; sp)).\n\n  rw <- @sub_filter_csub2sub.\n  rw <- @sub_filter_lsubst_sub; simpl.\n\n  rw @lsubst_sub_trivial_closed1;\n    try (complete (simpl; sp; cpx; allapply @in_csub2sub; sp)).\n\n  generalize (lsubst_shift B\n                           (sub_filter (csub2sub s) [bp, ba])\n                           [(bp, get_cterm p), (ba, get_cterm a)]\n                           []).\n  intro eq.\n\n  dest_imp eq hyp.\n  simpl; introv i; allrw in_app_iff; allsimpl; sp; cpx;\n  allrw @in_sub_filter; sp; allapply @in_csub2sub; sp.\n\n  dest_imp eq hyp.\n  simpl; rw <- @dom_sub_sub_filter; unfold disjoint; introv i;\n  allrw in_remove_nvars; sp.\n\n  allrw app_nil_r.\n  rw eq; clear eq; simpl.\n\n  assert (get_cterm p = lsubst (mk_var vp) (csub2sub (snoc (snoc s (vp, p)) (va, a)))) as eq1.\n  (* begin proof of assert *)\n  repeat (rw @csub2sub_snoc).\n  change_to_lsubst_aux4; simpl; sp.\n  repeat (rw @sub_find_snoc).\n  boolvar.\n  assert (!LIn vp (dom_sub (csub2sub s))) as nivp by (rw @dom_csub_eq; sp).\n  rw <- @sub_find_none_iff in nivp; rw nivp; sp.\n  assert (!LIn vp (dom_sub (csub2sub s))) as nivp by (rw @dom_csub_eq; sp).\n  rw <- @sub_find_none_iff in nivp; rw nivp; sp.\n  (* end proof of assert *)\n\n  rw <- eq1; clear eq1.\n\n  assert (get_cterm a = lsubst (mk_var va) (csub2sub (snoc (snoc s (vp, p)) (va, a)))) as eq2.\n  (* begin proof of assert *)\n  rw @csub2sub_snoc.\n  change_to_lsubst_aux4; simpl; sp.\n  rw @sub_find_snoc.\n  boolvar.\n  assert (!LIn va (dom_sub (csub2sub (snoc s (vp, p)))))\n         as niva\n         by (rw @dom_csub_eq; rw @dom_csub_snoc; simpl; rw in_snoc; sp).\n  rw <- @sub_find_none_iff in niva; rw niva; sp.\n  (* end proof of assert *)\n\n  rw <- eq2; clear eq2.\n\n  repeat (rw @csub2sub_snoc).\n\n  assert (forall T (l : list T) x y, x :: y :: l = [x,y] ++ l) as eqc by sp.\n\n  symmetry.\n  rw eqc.\n  rw @lsubst_aux_app_sub_filter; simpl;\n    try (complete (allrw @prog_sub_cons; sp; unfold prog_sub, sub_range_sat; simpl; sp));\n    try (complete (apply @prog_sub_sub_filter; sp));\n    try (complete (repeat (rw @prog_sub_snoc; sp))).\n\n  destruct (eq_var_dec vp bp); sp; subst.\n  destruct (eq_var_dec va ba); sp; subst.\n\n  repeat (rw @sub_filter_snoc); boolvar; sp; try (complete (allrw not_over_or; sp)).\n\n  dest_imp disj4 hyp; try (complete (simpl; sp)).\n  repeat (rw @sub_filter_snoc); boolvar; sp; allrw not_over_or; sp.\n\n  generalize (lsubst_sub_filter\n                B\n                ((bp, get_cterm p)\n                   :: (ba, get_cterm a)\n                   :: snoc (sub_filter (csub2sub s) [bp, ba]) (va, get_cterm a))\n                [va]); simpl; boolvar; try (complete sp); intro k.\n  dest_imp k hyp.\n  introv k; sp; cpx.\n  allrw in_snoc; sp; cpx.\n  allrw @in_sub_filter; sp.\n  allapply @in_csub2sub; sp.\n  dest_imp k hyp.\n  rw disjoint_singleton_r; sp.\n  rw <- k; clear k.\n\n  rw @sub_filter_snoc; boolvar; sp; try (complete (allrw not_over_or; sp)).\n  rw <- @sub_filter_app_r; simpl.\n  symmetry.\n\n  generalize (lsubst_sub_filter\n                B\n                ((bp, get_cterm p)\n                   :: (ba, get_cterm a)\n                   :: sub_filter (csub2sub s) [bp, ba])\n                [va]); simpl; boolvar; try (complete sp); intro k.\n  dest_imp k hyp.\n  introv k; sp; cpx.\n  allrw in_snoc; sp; cpx.\n  allrw @in_sub_filter; sp.\n  allapply @in_csub2sub; sp.\n  dest_imp k hyp.\n  rw disjoint_singleton_r; sp.\n  rw <- k; clear k.\n\n  rw <- @sub_filter_app_r; simpl; sp.\n\n  destruct (eq_var_dec vp ba); sp; subst.\n  destruct (eq_var_dec va bp); sp; subst.\n\n  repeat (rw @sub_filter_snoc); boolvar; sp; try (complete (allrw not_over_or; sp)).\n\n  repeat (rw @sub_filter_snoc); boolvar; sp; allrw not_over_or; sp.\n\n  generalize (lsubst_sub_filter\n                B\n                ((bp, get_cterm p)\n                   :: (ba, get_cterm a)\n                   :: snoc (sub_filter (csub2sub s) [bp, ba]) (va, get_cterm a))\n                [va]); simpl; boolvar; try (complete sp); intro k.\n  dest_imp k hyp.\n  introv k; sp; cpx.\n  allrw in_snoc; sp; cpx.\n  allrw @in_sub_filter; sp.\n  allapply @in_csub2sub; sp.\n  dest_imp k hyp.\n  rw disjoint_singleton_r; sp.\n  rw <- k; clear k.\n\n  rw @sub_filter_snoc; boolvar; sp; try (complete (allrw not_over_or; sp)).\n  rw <- @sub_filter_app_r; simpl.\n  symmetry.\n\n  generalize (lsubst_sub_filter\n                B\n                ((bp, get_cterm p)\n                   :: (ba, get_cterm a)\n                   :: sub_filter (csub2sub s) [bp, ba])\n                [va]); simpl; boolvar; try (complete sp); intro k.\n  dest_imp k hyp.\n  introv k; sp; cpx.\n  allrw in_snoc; sp; cpx.\n  allrw @in_sub_filter; sp.\n  allapply @in_csub2sub; sp.\n  dest_imp k hyp.\n  rw disjoint_singleton_r; sp.\n  rw <- k; clear k.\n\n  rw <- @sub_filter_app_r; simpl; sp.\n\n  dest_imp disj3 hyp; try (complete (simpl; sp)).\n\n  destruct (eq_var_dec va bp); sp; subst.\n\n  repeat (rw @sub_filter_snoc); boolvar; sp; allrw not_over_or; sp.\n\n  generalize (lsubst_sub_filter\n                B\n                ((bp, get_cterm p)\n                   :: (ba, get_cterm a)\n                   :: snoc (sub_filter (csub2sub s) [bp, ba]) (vp, get_cterm p))\n                [vp]); simpl; boolvar; try (complete sp); intro k.\n  dest_imp k hyp.\n  introv k; sp; cpx.\n  allrw in_snoc; sp; cpx.\n  allrw @in_sub_filter; sp.\n  allapply @in_csub2sub; sp.\n  dest_imp k hyp.\n  rw disjoint_singleton_r; sp.\n  rw <- k; clear k.\n\n  rw @sub_filter_snoc; boolvar; sp; try (complete (allrw not_over_or; sp)).\n  rw <- @sub_filter_app_r; simpl.\n  symmetry.\n\n  generalize (lsubst_sub_filter\n                B\n                ((bp, get_cterm p)\n                   :: (ba, get_cterm a)\n                   :: sub_filter (csub2sub s) [bp, ba])\n                [vp]); simpl; boolvar; try (complete sp); intro k.\n  dest_imp k hyp.\n  introv k; sp; cpx.\n  allrw in_snoc; sp; cpx.\n  allrw @in_sub_filter; sp.\n  allapply @in_csub2sub; sp.\n  dest_imp k hyp.\n  rw disjoint_singleton_r; sp.\n  rw <- k; clear k.\n\n  rw <- @sub_filter_app_r; simpl; sp.\n\n  destruct (eq_var_dec va ba); sp; subst.\n\n  repeat (rw @sub_filter_snoc); boolvar; sp; allrw not_over_or; sp.\n\n  generalize (lsubst_sub_filter\n                B\n                ((bp, get_cterm p)\n                   :: (ba, get_cterm a)\n                   :: snoc (sub_filter (csub2sub s) [bp, ba]) (vp, get_cterm p))\n                [vp]); simpl; boolvar; try (complete sp); intro k.\n  dest_imp k hyp.\n  introv k; sp; cpx.\n  allrw in_snoc; sp; cpx.\n  allrw @in_sub_filter; sp.\n  allapply @in_csub2sub; sp.\n  dest_imp k hyp.\n  rw disjoint_singleton_r; sp.\n  rw <- k; clear k.\n\n  rw @sub_filter_snoc; boolvar; sp; try (complete (allrw not_over_or; sp)).\n  rw <- @sub_filter_app_r; simpl.\n  symmetry.\n\n  generalize (lsubst_sub_filter\n                B\n                ((bp, get_cterm p)\n                   :: (ba, get_cterm a)\n                   :: sub_filter (csub2sub s) [bp, ba])\n                [vp]); simpl; boolvar; try (complete sp); intro k.\n  dest_imp k hyp.\n  introv k; sp; cpx.\n  allrw in_snoc; sp; cpx.\n  allrw @in_sub_filter; sp.\n  allapply @in_csub2sub; sp.\n  dest_imp k hyp.\n  rw disjoint_singleton_r; sp.\n  rw <- k; clear k.\n\n  rw <- @sub_filter_app_r; simpl; sp.\n\n  dest_imp disj4 hyp; try (complete (simpl; sp)).\n\n  repeat (rw @sub_filter_snoc); boolvar; sp; allrw not_over_or; sp.\n\n  generalize (lsubst_sub_filter\n                B\n                ((bp, get_cterm p)\n                   :: (ba, get_cterm a)\n                   :: snoc (snoc (sub_filter (csub2sub s) [bp, ba]) (vp, get_cterm p)) (va, get_cterm a))\n                [vp,va]); simpl; boolvar; try (complete sp); intro k.\n  dest_imp k hyp.\n  introv k; sp; cpx.\n  allrw in_snoc; sp; cpx.\n  allrw @in_sub_filter; sp.\n  allapply @in_csub2sub; sp.\n  dest_imp k hyp.\n  rw disjoint_cons_r; rw disjoint_singleton_r; sp.\n  rw <- k; clear k.\n\n  repeat (rw @sub_filter_snoc); boolvar; sp; try (complete (allrw not_over_or; sp)).\n  rw <- @sub_filter_app_r; simpl.\n  symmetry.\n\n  generalize (lsubst_sub_filter\n                B\n                ((bp, get_cterm p)\n                   :: (ba, get_cterm a)\n                   :: sub_filter (csub2sub s) [bp, ba])\n                [vp,va]); simpl; boolvar; try (complete sp); intro k.\n  dest_imp k hyp.\n  introv k; sp; cpx.\n  allrw in_snoc; sp; cpx.\n  allrw @in_sub_filter; sp.\n  allapply @in_csub2sub; sp.\n  dest_imp k hyp.\n  rw disjoint_cons_r; rw disjoint_singleton_r; sp.\n  rw <- k; clear k.\n\n  rw <- @sub_filter_app_r; simpl; sp.\nQed.\n\nLemma simple_lsubst_app2 {o} :\n  forall (t : @NTerm o) sub1 sub2,\n    (forall v u, LIn (v, u) sub1 -> disjoint (free_vars u) (bound_vars t))\n    -> (forall v u, LIn (v, u) sub2 -> isprogram u)\n    -> (forall v,\n          LIn v (dom_sub sub2)\n          -> !LIn v (dom_sub sub1)\n          -> !LIn v (free_vars t))\n    -> lsubst t (sub1 ++ sub2) = lsubst t sub1.\nProof.\n  introv hyp1 hyp2 hyp3.\n  change_to_lsubst_aux4;\n    try (complete (rw @range_app; rw flat_map_app;\n                   rw disjoint_app_r; sp;\n                   rw @prog_sub_flatmap_range; sp)).\n\n  revert_dependents sub2.\n  revert_dependents sub1.\n  nterm_ind t as [| | oo lbt ind] Case; allsimpl;\n  introv disj1 disj2 hyp1 hyp2 disj3; auto.\n\n  - Case \"vterm\".\n    rw @sub_find_app.\n    cases (sub_find sub1 n); sp.\n    rename_last sn1.\n    cases (sub_find sub2 n); sp.\n    rename_last sn2.\n    apply sub_find_none2 in sn1.\n    apply sub_find_some in sn2.\n    apply in_dom_sub in sn2.\n    generalize (hyp2 n); sp.\n    allrw not_over_or; sp.\n\n  - Case \"oterm\".\n    apply oterm_eq; sp.\n    apply eq_maps; introv i.\n    destruct x; simpl.\n    apply bterm_eq; sp.\n    rw @sub_filter_app.\n    apply ind with (lv := l); try (complete sp).\n\n    + rw disjoint_flat_map_l in disj3.\n      generalize (disj3 (bterm l n)); intro k; dest_imp k hyp.\n      simpl in k.\n      rw disjoint_app_l in k; repnd.\n      unfold disjoint in k.\n      unfold disjoint; introv j.\n      apply k in j; intro x.\n      allrw lin_flat_map; exrepnd.\n      apply j; exists x0; sp.\n      allrw @in_range_iff; exrepnd.\n      allrw @in_sub_filter; repnd.\n      exists v.\n      rw in_app_iff; sp.\n\n    + rw disjoint_flat_map_l in disj3.\n      generalize (disj3 (bterm l n)); intro k; dest_imp k hyp.\n      simpl in k.\n      rw disjoint_app_l in k; repnd.\n      unfold disjoint in k.\n      unfold disjoint; introv j.\n      apply k in j; intro x.\n      allrw lin_flat_map; exrepnd.\n      apply j; exists x0; sp.\n      allrw @in_range_iff; exrepnd.\n      allrw @in_sub_filter; repnd.\n      exists v.\n      rw in_app_iff; sp.\n\n    + introv j.\n      apply in_sub_filter in j; repnd.\n      generalize (hyp1 v u); sp.\n\n    + introv j k.\n      rw <- @dom_sub_sub_filter in j.\n      rw in_remove_nvars in j; repnd.\n      rw <- @dom_sub_sub_filter in k.\n      rw in_remove_nvars in k.\n      generalize (hyp2 v); intro imp.\n      intro x.\n      repeat (dest_imp imp hyp).\n      apply imp.\n      rw lin_flat_map.\n      exists (bterm l n); simpl; sp.\n      rw in_remove_nvars; sp.\n\n    + rw disjoint_flat_map_l in disj3.\n      generalize (disj3 (bterm l n)); intro k; dest_imp k hyp.\n      simpl in k.\n      rw disjoint_app_l in k; repnd.\n      unfold disjoint in k.\n      unfold disjoint; introv j.\n      apply k in j; intro x.\n      allrw lin_flat_map; exrepnd.\n      apply j; exists x0; sp.\n      allrw @in_range_iff; exrepnd.\n      allrw in_app_iff.\n      allrw @in_sub_filter.\n      exists v.\n      rw in_app_iff; sp.\nQed.\n\nLemma lsubstc3_lsubstc_var1 {o} :\n  forall cp ca cb (C : @NTerm o) p a b wC s cvC vp va w c,\n    !LIn vp (bound_vars C)\n    -> !LIn va (bound_vars C)\n    -> ((!LIn vp [cp,ca,cb]) -> !LIn vp (free_vars C))\n    -> ((!LIn va [cp,ca,cb]) -> !LIn va (free_vars C))\n    -> !LIn vp (dom_csub s)\n    -> !LIn va (dom_csub s)\n    -> !(va = vp)\n    -> lsubstc3 cp p ca a cb b\n                (lsubstc_vars C wC (csub_filter s [cp, ca, cb]) [cp, ca, cb] cvC)\n       = lsubstc (lsubst C [(cp, mk_var vp), (ca, mk_var va), (cb, get_cterm b)]) w\n                 (snoc (snoc s (vp, p)) (va, a)) c.\nProof.\n  introv h1 h2 h3 h4 h5 h6 h7.\n\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n\n  repeat (rw @simple_lsubst_lsubst; simpl);\n    try (complete (sp; allapply @in_csub2sub; sp; allunfold @isprogram; sp; allrw; sp));\n    try (complete (sp; cpx; simpl; try (rw disjoint_singleton_l; sp); rw @free_vars_cterm; sp)).\n\n  rw <- @sub_filter_csub2sub.\n  rw <- @sub_filter_lsubst_sub; simpl.\n\n  rw @lsubst_sub_trivial_closed1;\n    try (complete (simpl; sp; cpx; allapply @in_csub2sub; sp)).\n\n  generalize (lsubst_shift C\n                           (sub_filter (csub2sub s) [cp, ca, cb])\n                           [(cp, get_cterm p), (ca, get_cterm a), (cb, get_cterm b)]\n                           []).\n  intro eq.\n\n  dest_imp eq hyp.\n  simpl; introv i; allrw in_app_iff; allsimpl; sp; cpx;\n  allrw @in_sub_filter; sp; allapply @in_csub2sub; sp.\n\n  dest_imp eq hyp.\n  simpl; rw <- @dom_sub_sub_filter; unfold disjoint; introv i;\n  allrw in_remove_nvars; sp.\n\n  allrw app_nil_r.\n  rw eq; clear eq; simpl.\n\n  assert (get_cterm p\n          = lsubst (mk_var vp) (csub2sub (snoc (snoc s (vp, p)) (va, a))))\n         as eq1.\n  (* begin proof of assert *)\n  repeat (rw @csub2sub_snoc).\n  change_to_lsubst_aux4; simpl; sp.\n  repeat (rw @sub_find_snoc).\n  boolvar.\n  assert (!LIn vp (dom_sub (csub2sub s))) as nivp by (rw @dom_csub_eq; sp).\n  rw <- @sub_find_none_iff in nivp; rw nivp; sp.\n  assert (!LIn vp (dom_sub (csub2sub s))) as nivp by (rw @dom_csub_eq; sp).\n  rw <- @sub_find_none_iff in nivp; rw nivp; sp.\n  (* end proof of assert *)\n\n  rw <- eq1; clear eq1.\n\n  assert (get_cterm a\n          = lsubst (mk_var va) (csub2sub (snoc (snoc s (vp, p)) (va, a))))\n         as eq2.\n  (* begin proof of assert *)\n  rw @csub2sub_snoc.\n  change_to_lsubst_aux4; simpl; sp.\n  rw @sub_find_snoc.\n  boolvar.\n  assert (!LIn va (dom_sub (csub2sub (snoc s (vp, p)))))\n         as niva\n         by (rw @dom_csub_eq; rw @dom_csub_snoc; simpl; rw in_snoc; sp).\n  rw <- @sub_find_none_iff in niva; rw niva; sp.\n  (* end proof of assert *)\n\n  rw <- eq2; clear eq2.\n\n  rw @lsubst_cterm.\n  repeat (rw @csub2sub_snoc).\n\n  assert (forall T (l : list T) x y z, x :: y :: z :: l = [x,y,z] ++ l) as eqc by sp.\n\n  rw eqc.\n  rw <- @lsubst_aux_app_sub_filter;\n    try (complete (sp; unfold prog_sub, sub_range_sat; simpl; sp; cpx)).\n  rw <- @simple_lsubst_app; try (complete (simpl; sp; allapply @in_csub2sub; cpx)).\n\n  symmetry.\n  rw eqc.\n  rw <- @simple_lsubst_app;\n    try (complete (simpl; sp; allrw in_snoc; sp; allapply @in_csub2sub; cpx)).\n\n  generalize (lsubst_sub_filter\n                (lsubst C [(cp, get_cterm p), (ca, get_cterm a), (cb, get_cterm b)])\n                (snoc (snoc (csub2sub s) (vp, get_cterm p)) (va, get_cterm a))\n                [vp, va]); intro eq.\n  dest_imp eq hyp;\n    try (complete (intros; allrw in_snoc; sp; cpx; allapply @in_csub2sub; sp)).\n  dest_imp eq hyp.\n  generalize (eqvars_free_vars_disjoint C [(cp, get_cterm p), (ca, get_cterm a), (cb, get_cterm b)]);\n    introv eqv.\n  apply eqvars_sym in eqv.\n  apply eqvars_disjoint with (s3 := [vp,va]) in eqv; sp.\n  simpl; boolvar; simpl; repeat (rw @free_vars_cterm); simpl; allrw app_nil_r;\n  apply disjoint_sym; unfold disjoint; intros v i k; simpl in i; repdors; subst;\n  try (destruct (eq_var_dec vp v)); try (destruct (eq_var_dec va v)); try (complete sp);\n  allrw in_remove_nvars; repnd; allrw in_single_iff; try (complete sp).\n\n  rw <- eq.\n  repeat (rw @sub_filter_snoc); boolvar; subst; sp; try (complete (allrw not_over_or; sp)).\n  GC; clear eq.\n\n  apply lsubst_sub_filter;\n    try (complete (intros; allrw in_snoc; sp; cpx; allapply @in_csub2sub; sp)).\n\n  generalize (eqvars_free_vars_disjoint C [(cp, get_cterm p), (ca, get_cterm a), (cb, get_cterm b)]);\n    introv eqv.\n  apply eqvars_sym in eqv.\n  apply eqvars_disjoint with (s3 := [vp,va]) in eqv; sp.\n  simpl; boolvar; simpl; repeat (rw @free_vars_cterm); simpl; allrw app_nil_r;\n  apply disjoint_sym; unfold disjoint; intros v i k; simpl in i; repdors; subst;\n  try (destruct (eq_var_dec vp v)); try (destruct (eq_var_dec va v)); try (complete sp);\n  allrw in_remove_nvars; repnd; allrw in_single_iff; try (complete sp).\nQed.\n\nLemma csubst_subst_pw_Q {o} :\n  forall (Q : @NTerm o) w f b t,\n    !LIn b (bound_vars Q)\n    -> !LIn f (bound_vars Q)\n    -> !b = f\n    -> !b = w\n    -> !LIn b (free_vars Q)\n    -> csubst (subst Q w (mk_apply (mk_var f) (mk_var b))) [(b, t)]\n       = subst Q w (mk_apply (mk_var f) (get_cterm t)).\nProof.\n  introv bc1 bc2 bc3 bc4 bc5.\n  generalize (simple_lsubst_lsubst\n                Q [(w, mk_apply (mk_var f) (mk_var b))] [(b, get_cterm t)]);\n    introv eq.\n  repeat (dest_imp eq hyp);\n    try (complete (simpl; introv k; sp; cpx; simpl; repeat (rw disjoint_cons_l); sp)).\n\n  unfold subst, csubst; simpl.\n  rw eq; clear eq; simpl.\n\n  rw @fold_csubst1.\n  rw @csubst_mk_apply; simpl.\n  rw (@csubst_var_not_in o f); simpl; sp.\n  rw @csubst_mk_var_in.\n  generalize (lsubst_sub_filter2\n                Q [(w, mk_apply (mk_var f) (get_cterm t)), (b, get_cterm t)] [b]);\n    intro e.\n  repeat (dest_imp e hyp);\n    try (complete (rw disjoint_singleton_r; sp));\n    try (complete (unfold disjoint_bv_sub, sub_range_sat; simpl; sp; cpx; simpl;\n                   allrw @free_vars_cterm; simpl;\n                   try (rw disjoint_singleton_l); try (rw disjoint_singleton_r); sp)).\n  simpl in e.\n  rw <- e; clear e.\n\n  boolvar; sp; allrw not_over_or; sp.\nQed.\n\nLemma lsubstc_snoc_snoc {o} :\n  forall (t : @NTerm o) s v1 v2 t1 t2 w c,\n    !LIn v1 (free_vars t)\n    -> {c' : cover_vars t (snoc s (v2, t2))\n        , lsubstc t w (snoc (snoc s (v1, t1)) (v2, t2)) c\n          = lsubstc t w (snoc s (v2, t2)) c'}.\nProof.\n  introv ni.\n  assert (cover_vars t (snoc s (v2, t2)))\n         as c'\n         by (allrw @cover_vars_eq;\n             allrw subvars_prop; introv i;\n             applydup c in i as j; splst in j; splst; sp; subst; sp).\n  exists c'.\n  revert c.\n  rw snoc_as_append; introv.\n  generalize (lsubstc_csubst_ex2 t (snoc s (v1, t1)) [(v2, t2)] w c); intro eq; exrepnd.\n  rw <- eq1; clear eq1.\n  revert w' p'.\n  lsubst_tac; introv.\n  assert (cover_vars t (s ++ [(v2, t2)])) as c'' by (rw <- snoc_as_append; sp).\n  generalize (lsubstc_csubst_ex2 t s [(v2, t2)] w c''); intro eq; exrepnd; proof_irr.\n  rw eq1; clear eq1.\n  revert c''.\n  rw <- snoc_as_append; introv; proof_irr; 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/rules/rules_useful.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2958867964364101}}
{"text": "\nRequire Import Fiat.Parsers.Reflective.Semantics.\nRequire Import Fiat.Parsers.Reflective.ParserSyntax.\nRequire Import Fiat.Parsers.Reflective.ParserSemanticsOptimized.\nRequire Import Fiat.Parsers.Reflective.ParserSoundness.\nRequire Import Fiat.Parsers.Reflective.PartialUnfold.\nRequire Import Fiat.Parsers.Reflective.ParserPartialUnfold.\nSet Implicit Arguments.\n\nModule opt.\n  Section 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} := opt.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      apply polypnormalize_correct; assumption.\n    Qed.\n  End polypnormalize.\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/Reflective/ParserSoundnessOptimized.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.295865622195672}}
{"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.GeneralTactics4.\n\n  Lemma split_triples : forall triples words_cinput coutput, words_cinput = List.map (fun x => (Word x, ADTIn x)) triples -> coutput = List.map (@ADTOut _) triples -> triples = make_triples words_cinput coutput.\n  Proof.\n    induction triples; destruct words_cinput; destruct coutput; simpl in *; intros; try discriminate.\n    eauto.\n    destruct a; inject H; inject H0.\n    f_equal; eauto.\n  Qed.\n\n  Lemma split_triples' : forall triples words cinput coutput, words = List.map (@Word _) triples -> cinput = List.map (@ADTIn _) triples -> coutput = List.map (@ADTOut _) triples -> triples = make_triples (combine words cinput) coutput.\n  Proof.\n    induction triples; destruct words; destruct cinput; destruct coutput; simpl in *; intros; try discriminate.\n    eauto.\n    destruct a; inject H; inject H0; inject H1.\n    f_equal; eauto.\n  Qed.\n\n  Lemma nth_error_make_triples_intro words_cinput : forall coutput i p a a', nth_error words_cinput i = Some (p, a) -> nth_error coutput i = Some a' -> nth_error (make_triples words_cinput coutput) i = Some {| Word := p; ADTIn := a; ADTOut := a'|}.\n  Proof.\n    induction words_cinput; destruct coutput; destruct i; simpl in *; intros; try discriminate.\n    destruct a; inject H; inject H0; eauto.\n    eauto.\n  Qed.\n\n  Lemma nth_error_make_triples_elim wis : forall os i p a a', nth_error (make_triples wis os) i = Some {| Word := p; ADTIn := a; ADTOut := a' |} -> nth_error wis i = Some (p, a) /\\ nth_error os i = Some a'.\n  Proof.\n    induction wis; destruct os; destruct i; simpl in *; intros; try discriminate.\n    destruct a; inject H; eauto.\n    eauto.\n  Qed.\n\n  Arguments store_out {_} _ _.\n  Arguments ADTOut {_} _.\n\n  Lemma make_triples_Word_ADTIn : forall pairs outs, length outs = length pairs -> List.map (fun x => (Word x, ADTIn x)) (make_triples pairs outs) = pairs.\n    induction pairs; destruct outs; simpl; intuition.\n    f_equal; auto.\n  Qed.\n\n  Lemma make_triples_ADTOut : forall pairs outs, length outs = length pairs -> List.map ADTOut (make_triples pairs outs) = outs.\n    induction pairs; destruct outs; simpl; intuition.\n    f_equal; auto.\n  Qed.\n\n  Require Import Platform.Cito.SemanticsFacts6.\n  Require Import Platform.Cito.ListFacts4.\n\n  Lemma make_triples_ADTIn_ADTOut : forall pairs outs, length outs = length pairs -> List.map (fun x => (ADTIn x, ADTOut x)) (@make_triples pairs outs) = List.combine (List.map snd pairs) outs.\n  Proof.\n    intros.\n    erewrite <- combine_map.\n    rewrite make_triples_ADTIn by eauto.\n    rewrite make_triples_ADTOut by eauto.\n    eauto.\n  Qed.\n\nEnd ADTValue.\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/SemanticsFacts7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.2958000196192761}}
{"text": "Require Import Integers.\nRequire Import Coqlib.\nRequire Import Maps.\n\nImport Int.\nRequire Import Hardware.\n\nLtac dec_eq_try :=\n  repeat (rewrite dec_eq_false;\n    [ idtac | solve [ let F := fresh in (intro F; inversion F)] ] +\n  rewrite dec_eq_true + fail).\n\nLtac simpl_code :=\n  repeat autounfold with chipmem; simpl;\n  repeat match goal with\n  | |- context[add (repr ?x) (repr ?y)] =>\n    let GR := fresh in assert (GR: add (repr x) (repr y) = repr (x + y)) by\n      (rewrite add_unsigned; rewrite unsigned_repr_eq; rewrite <- Z_mod_modulus_eq;\n      apply f_equal; auto); rewrite GR; clear GR; simpl\n  | |- context[?x # ?y <- ?z] =>\n    change (x # y <- z) with (RegMap.set y z x); try unfold RegMap.set\n  end; repeat autounfold with chipmem; simpl.\n\nLtac deal_with_eq_dec :=\n  repeat (let F := fresh in\n   (case (eq_dec _ _); intro F; try inversion F));\n  repeat match goal with\n  | |- context[Reg_eq ?x ?x] =>\n    rewrite dec_eq_true\n  | H: context[Reg_eq ?x ?x] |- _ =>\n    rewrite dec_eq_true in H; try rewrite H\n  end; repeat (case (Reg_eq _ _); intros).\n\nLtac inverse_eq :=\n  match goal with\n  | H: ?x = ?y |- _ => try inversion H\n  end.\n\nLtac deal_with_eq :=\n  repeat match goal with\n  | |- context [eq ?x ?x] =>\n    rewrite Z_eq_eq\n  | H: context[eq ?x ?x] |- _ =>\n    rewrite Z_eq_eq in H\n  end; autounfold with Z_unfold;\n  try (case (Z.eq_dec _ _); intros; [intuition | inverse_eq]); simpl in *.\n\nLtac Fine_eq :=\n  match goal with\n  | |- context[Fine ?M' ?IM' ?RF' ?St' = Fine _ _ _ _ /\\ _] =>\n    exists M'; exists IM'; exists RF'; exists St'\n  end.\n\nLemma rsb_is_reverse_sub: forall M IM RF St v v',\n  (IM (RF#PC)) = (Isub v v') ->\n  let EIMsub := ExecuteStep M IM RF St in\n  let EIMrsb := ExecuteStep M (InstructionMap.set (RF#PC) (Irsb v' v) IM) RF St in\n  OutputM EIMsub = OutputM EIMrsb /\\\n  OutputRF EIMsub = OutputRF EIMrsb /\\\n  OutputStack EIMsub = OutputStack EIMrsb.\nProof.\n  intros. subst EIMsub. subst EIMrsb.\n  simpl_code. rewrite H. simpl.\n  dec_eq_try. destruct (lt _ _); auto.\nQed.\n", "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/src/ChipTactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.29553659970168167}}
{"text": "Require Import ExtLib.Core.RelDec.\nRequire Import ExtLib.Data.Fun.\n\nRequire Import MirrorCore.TypesI.\n\nRequire Import MirrorCharge.ModularFunc.BaseType.\nRequire Import MirrorCharge.ModularFunc.ListType.\nRequire Import MirrorCharge.ModularFunc.SubstType.\n\n\nRequire Import MirrorCharge.ModularFunc.ILogicFunc.\nRequire Import MirrorCharge.ModularFunc.BILogicFunc.\nRequire Import MirrorCharge.ModularFunc.EmbedFunc.\nRequire Import MirrorCharge.ModularFunc.LaterFunc.\n\nRequire Import Charge.Open.Subst.\nRequire Import Charge.Logics.ILInsts.\nRequire Import Charge.Logics.BILInsts.\nRequire Import Charge.Logics.ILogic.\nRequire Import Charge.Logics.Later.\n\nRequire Import Java.Logic.AssertionLogic.\nRequire Import Java.Logic.SpecLogic.\nRequire Import Java.Language.Lang.\nRequire Import Java.Language.Program.\n\nRequire Import Coq.Strings.String.\nRequire Import Coq.Bool.Bool.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nInductive typ : Type :=\n| tyArr : typ -> typ -> typ\n| tyList : typ -> typ\n| tyPair : typ -> typ -> typ\n| tyBool : typ\n| tyVal : typ\n| tyString : typ\n| tyNat : typ\n| tyProp : typ\n| tySpec : typ\n| tyAsn : typ\n| tyProg : typ\n| tyCmd : typ\n| tyDExpr : typ\n| tySubst : typ.\n\nNotation \"'tyStack'\" := (tyArr tyString tyVal).\n\nNotation \"'tyPure'\" := (tyArr tyStack tyProp).\nNotation \"'tySasn'\" := (tyArr tyStack tyAsn).\nNotation \"'tyExpr'\" := (tyArr tyStack tyVal).\nNotation \"'tyFields'\" := (tyList tyString).\n\nNotation \"'tyVarList'\" := (tyList tyString).\nNotation \"'tyDExprList'\" := (tyList tyDExpr).\nNotation \"'tySubstList'\" := (tyList (tyPair tyString tyExpr)).\n\nFixpoint type_cast_typ (a b : typ) : option (a = b) :=\n  match a as a , b as b return option (a = b) with\n    | tyProp , tyProp => Some eq_refl\n    | tySpec , tySpec => Some eq_refl\n    | tyVal, tyVal => Some eq_refl\n    | tyBool, tyBool => Some eq_refl\n    | tyProg, tyProg => Some eq_refl\n    | tyNat, tyNat => Some eq_refl\n    | tyArr x y , tyArr a b =>\n      match type_cast_typ x a , type_cast_typ y b with\n        | Some pf , Some pf' =>\n          Some (match pf in _ = t\n                    , pf' in _ = t'\n                      return tyArr x y = tyArr t t'\n                with\n                  | eq_refl , eq_refl => eq_refl\n                end)\n        | _ , _ => None\n      end\n    | tyPair x y , tyPair a b =>\n      match type_cast_typ x a , type_cast_typ y b with\n        | Some pf , Some pf' =>\n          Some (match pf in _ = t\n                    , pf' in _ = t'\n                      return tyPair x y = tyPair t t'\n                with\n                  | eq_refl , eq_refl => eq_refl\n                end)\n        | _ , _ => None\n      end\n    | tyList x, tyList y =>\n    \tmatch type_cast_typ x y with\n          | Some pf =>\n    \t\tSome (match pf in _ = t return tyList x = tyList t with\n    \t\t\t    | eq_refl => eq_refl\n    \t\t\t  end)\n          | None => None\n       end\n    | tyString, tyString => Some eq_refl\n    | tyCmd, tyCmd => Some eq_refl\n    | tyDExpr, tyDExpr => Some eq_refl\n    | tyAsn, tyAsn => Some eq_refl\n    | tySubst, tySubst => Some eq_refl\n\n    | _, _ => None\n  end.\n\nLemma type_cast_typ_sound (a b : typ) :\n\t(exists pf, type_cast_typ a b = Some pf) <->\n\ta = b.\nProof.\n  split; intros H.\n  + destruct a, b; destruct H as [x _]; inversion x; subst; reflexivity.\n  + subst. exists eq_refl. induction b; try reflexivity.\n    simpl. rewrite IHb1, IHb2. reflexivity.\n    simpl. rewrite IHb. reflexivity.\n    simpl. rewrite IHb1, IHb2. reflexivity.\nQed.\n\nInstance RelDec_eq_typ : RelDec (@eq typ) :=\n{ rel_dec := fun a b => match type_cast_typ a b with\n                          | None => false\n                          | Some _ => true\n                        end }.\n\nLemma type_cast_typ_refl (a : typ) : type_cast_typ a a = Some eq_refl.\nProof.\n  induction a; simpl; try reflexivity.\n  rewrite IHa1, IHa2; reflexivity.\n  rewrite IHa. reflexivity.\n  rewrite IHa1, IHa2; reflexivity.\nQed.\n\nInstance RelDec_correct_typ : RelDec_Correct RelDec_eq_typ.\nProof.\n\tsplit; intros x y.\n\tdestruct x, y; simpl; split; intro H; inversion H; subst; try reflexivity.\n\t+ remember (type_cast_typ x1 y1); destruct o; subst; [|inversion H].\n\t  remember (type_cast_typ x2 y2); destruct o; subst; [|inversion H].\n\t  reflexivity.\n\t+ do 2 rewrite type_cast_typ_refl; reflexivity.\n\t+ remember (type_cast_typ x y); destruct o; subst; [|inversion H].\n\t  reflexivity.\n\t+ rewrite type_cast_typ_refl. reflexivity.\n\t+ remember (type_cast_typ x1 y1); destruct o; subst; [|inversion H].\n\t  remember (type_cast_typ x2 y2); destruct o; subst; [|inversion H].\n\t  reflexivity.\n\t+ do 2 rewrite type_cast_typ_refl; reflexivity.\nQed.\n\nFixpoint typD (t : typ) : Type :=\n  match t with\n    | tyArr a b => typD a -> typD b\n    | tyList a => @list (typD a)\n    | tyPair a b => (typD a * typD b)%type\n    | tyProp => Prop\n    | tyNat => nat\n    | tyBool => bool\n    | tySpec => spec\n    | tyAsn => asn\n    | tyVal => val\n    | tyString => string\n    | tyProg => Program\n    | tyCmd => cmd\n    | tyDExpr => dexpr\n    | tySubst => @subst var val\n  end.\n\nInductive tyAcc_typ : typ -> typ -> Prop :=\n| tyAcc_tyArrL : forall a b, tyAcc_typ a (tyArr a b)\n| tyAcc_tyArrR : forall a b, tyAcc_typ a (tyArr b a).\n\nInstance RType_typ : RType typ :=\n{ typD := typD\n; tyAcc := tyAcc_typ\n; type_cast := type_cast_typ\n}.\n\nInstance Typ2_Fun : Typ2 _ (fun x y : Type => x -> y) :=\n{ typ2 := tyArr\n; typ2_cast := fun _ _ => eq_refl\n; typ2_match := fun T t tr =>\n                  match t as t return T (typD t) -> T (typD t) with\n                    | tyArr a b => fun _ => tr a b\n                    | _ => fun fa => fa\n                  end\n}.\n\nInstance Typ2Ok_Fun : Typ2Ok Typ2_Fun.\nProof.\n  split; intros.\n  + reflexivity.\n  + apply tyAcc_tyArrL.\n  + apply tyAcc_tyArrR.\n  + unfold Rty in *. inversion H; subst; intuition congruence.\n  + destruct x; try solve [right; reflexivity].\n    left; exists x1, x2, eq_refl. reflexivity.\n  + destruct pf; reflexivity.\nQed.\n\nInstance Typ0_Prop : Typ0 _ Prop :=\n{ typ0 := tyProp\n; typ0_cast := eq_refl\n; typ0_match := fun T t tr =>\n                  match t as t return T (typD t) -> T (typD t) with\n                    | tyProp => fun _ => tr\n                    | _ => fun fa => fa\n                  end\n}.\n\nInstance Typ0Ok_Prop : Typ0Ok Typ0_Prop.\nProof.\n    constructor.\n    { reflexivity. }\n    { destruct x; try solve [ right ; reflexivity ].\n      { left. exists eq_refl. reflexivity. } }\n    { destruct pf. reflexivity. }\nQed.\n\nInstance RTypeOk_typ : @RTypeOk _ RType_typ.\nProof.\n\tsplit; intros.\n\t+ reflexivity.\n\t+ unfold well_founded.\n\t  intros. induction a; simpl; constructor; intros; inversion H; subst.\n\t  assumption. assumption.\n\t+ destruct pf; reflexivity.\n\t+ destruct pf1, pf2; reflexivity.\n\t+ apply type_cast_typ_refl.\n\t+ intro H1. inversion H1; subst.\n\t  rewrite type_cast_typ_refl in H. inversion H.\n\t+ intros x.\n\t  induction x; intros y; destruct y; try (right; congruence); try (left; congruence).\n\t  * destruct (IHx1 y1) as [Hx1 | Hx1]; clear IHx1;\n\t    destruct (IHx2 y2) as [Hx2 | Hx2]; clear IHx2;\n\t    try (right; congruence); try (left; congruence).\n\t  * destruct (IHx y) as [Hx | Hx]; clear IHx; [\n\t    left; congruence | right; congruence].\n\t  * destruct (IHx1 y1) as [Hx1 | Hx1]; clear IHx1;\n\t    destruct (IHx2 y2) as [Hx2 | Hx2]; clear IHx2;\n\t    try (right; congruence); try (left; congruence).\nQed.\n\nInstance BaseType_typ : BaseType typ := {\n  tyNat := tyNat;\n  tyBool := tyBool;\n  tyString := tyString;\n  tyPair := tyPair\n}.\n\nInstance BaseTypeD_typ : BaseTypeD := {\n\tbtNat := eq_refl;\n\tbtBool := eq_refl;\n\tbtString := eq_refl;\n\tbtPair := fun _ _ => eq_refl\n}.\n\nInstance ListType_typ : ListType typ := {\n\ttyList := tyList\n}.\n\nInstance ListTypeD_typ : ListTypeD := {\n\tbtList := fun _ => eq_refl\n}.\n\nInstance SubstType_typ : SubstType typ := {\n\ttyVal := tyVal;\n\ttySubst := tySubst\n}.\n\nDefinition null' : TypesI.typD tyVal := null.\n\nProgram Instance SubstTypeD_typ : @SubstTypeD typ _ _ _ := {\n\tstSubst := eq_refl\n}.\n\nDefinition should_not_be_necessary : ILogicOps (TypesI.typD tySpec).\nProof.\n  simpl.\n  apply _.\nDefined.\n\nDefinition should_also_not_be_necessary : ILLOperators (TypesI.typD tySpec).\nProof.\n  simpl.\n  apply _.\nDefined.\n\n  Definition ilops : @logic_ops _ RType_typ :=\n  fun t =>\n    match t\n          return option (ILogic.ILogicOps (TypesI.typD t))\n    with\n      | tyProp => Some _\n      | tyAsn => Some _\n      | tySasn => Some (@ILFun_Ops stack asn _)\n      | tySpec => Some should_not_be_necessary\n      | tyPure => Some ( @ILFun_Ops stack Prop _)\n      | _ => None\n    end.\n\n  Definition bilops : @bilogic_ops _ RType_typ :=\n  fun t =>\n    match t\n          return option (BILogic.BILOperators (TypesI.typD t))\n    with\n      | tyAsn => Some _\n      | tySasn => Some (@BILFun_Ops stack asn _)\n      | _ => None\n    end.\n\nDefinition eops : @embed_ops _ RType_typ :=\n  fun t u =>\n    match t as t , u as u\n          return option\n                   (ILEmbed.EmbedOp (TypesI.typD t) (TypesI.typD u))\n    with\n      | tyPure, tySasn => Some _\n      | tyProp, tyAsn => Some _\n      | _ , _ => None\n    end.\n\nDefinition lops : @later_ops _ RType_typ :=\n  fun t =>\n    match t return option (ILLOperators (TypesI.typD t)) with\n\t  | tySpec => Some should_also_not_be_necessary\n\t  | _ => None\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/Java/JavaType.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.29553659970168167}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Relations.Relations.\nRequire Import ExtLib.Data.Set.ListSet.\nRequire Import ExtLib.Tactics.Consider.\nRequire Import ExtLib.Tactics.Injection.\nRequire Import MirrorCore.TypesI.\nRequire Import MirrorCore.ExprI.\nRequire Import MirrorCore.EnvI.\nRequire Import MirrorCore.SubstI.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nSection sealed.\n  Variable expr : Type.\n  Variable lsubst : Type.\n  Context {Subst_lsubst : Subst lsubst expr}.\n  Let uvar : Type := nat.\n\n  Record seal_subst : Type := SealedSubst\n  { allowed : uvar -> bool\n  ; subst : lsubst\n  }.\n\n  Instance Injective_seal_subst a b c d\n  : Injective ({| allowed := a ; subst := b |} =\n               {| allowed := c ; subst := d |}) :=\n  { result := a = c /\\ b = d }.\n  Proof.\n    abstract (inversion 1; intuition).\n  Defined.\n\n  Instance Subst_seal_subst : Subst seal_subst expr :=\n  { set := fun u e s =>\n             match s with\n               | {| allowed := allow ; subst := subst |} =>\n                 if allow u then\n                   match set u e subst with\n                     | None => None\n                     | Some s => Some {| allowed := allow ; subst := s |}\n                   end\n                 else\n                   None\n             end\n  ; lookup := fun u s => lookup u s.(subst)\n  ; empty := {| allowed := fun _ => true ; subst := @SubstI.empty _ _ _ |}\n  }.\n\n  Variable typ : Type.\n  Variable RType_typ : RType typ.\n  Context {Expr_expr : Expr _ expr}.\n  Context {mentionsU : uvar -> expr -> bool}.\n  Context {SubstOk_lsubst : @SubstOk _ _ _ _ Expr_expr Subst_lsubst}.\n\n  Instance SubstOk : SubstOk Expr_expr Subst_seal_subst :=\n  { substD := fun us vs s => substD us vs s.(subst)\n  ; WellTyped_subst := fun tus tvs s => WellTyped_subst tus tvs s.(subst)\n  }.\n  Proof.\n    { simpl; apply substD_empty. }\n    { simpl; apply WellTyped_empty. }\n\n    destruct s; simpl; eauto using substD_lookup, WellTyped_lookup, WellTyped_set, substD_set.\n    destruct s; simpl; eauto using substD_lookup.\n    { destruct s; destruct s'; simpl; eauto using substD_lookup, WellTyped_lookup, WellTyped_set, substD_set.\n      intros. destruct (allowed0 uv); try congruence.\n      consider (set uv e subst0); intros; inv_all; subst; try congruence;\n      eauto using WellTyped_set. }\n    { destruct s; destruct s'; simpl; intros.\n      destruct (allowed0 uv); try congruence; inv_all; subst.\n      consider (set uv e subst0); try congruence; intros; inv_all; subst;\n      eauto using substD_set. }\n  Defined.\n\n  Instance NormalizedSubstOk (N : NormalizedSubstOk Subst_lsubst mentionsU)\n  : NormalizedSubstOk Subst_seal_subst mentionsU.\n  Proof.\n    constructor.\n    { destruct s; simpl. eapply lookup_normalized; eauto. }\n  Qed.\n\n  Definition seal : (uvar -> bool) -> lsubst -> seal_subst := SealedSubst.\n\n  Definition exclude (ls : list uvar) : lsubst -> seal_subst :=\n    seal (fun u => negb (List.anyb (EqNat.beq_nat u) ls)).\n\n  Definition allow (ls : list uvar) : lsubst -> seal_subst :=\n    seal (fun u => List.anyb (EqNat.beq_nat u) ls).\n\nEnd sealed.\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/Subst/SealedSubst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2955139749472744}}
{"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 map.Map.\n\n(* Why3 assumption *)\nDefinition unit := unit.\n\n(* Why3 assumption *)\nInductive ref (a:Type) {a_WT:WhyType a} :=\n  | mk_ref : a -> ref a.\nAxiom ref_WhyType : forall (a:Type) {a_WT:WhyType a}, WhyType (ref a).\nExisting Instance ref_WhyType.\nImplicit Arguments mk_ref [[a] [a_WT]].\n\n(* Why3 assumption *)\nDefinition contents {a:Type} {a_WT:WhyType a} (v:(@ref a a_WT)): a :=\n  match v with\n  | (mk_ref x) => x\n  end.\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 *)\nDefinition appear_twice (a:(@array Z _)) (v:Z) (u:Z): Prop := exists i:Z,\n  ((0%Z <= i)%Z /\\ (i < u)%Z) /\\ (((get a i) = v) /\\ exists j:Z,\n  ((0%Z <= j)%Z /\\ (j < u)%Z) /\\ ((~ (j = i)) /\\ ((get a j) = v))).\n\n(* Why3 goal *)\nTheorem WP_parameter_two_equal_elements : forall (a:Z) (a1:(@map.Map.map Z _\n  Z _)) (n:Z), let a2 := (mk_array a a1) in (((0%Z <= a)%Z /\\\n  (((a = (n + 2%Z)%Z) /\\ (2%Z <= n)%Z) /\\ ((forall (i:Z), ((0%Z <= i)%Z /\\\n  (i < a)%Z) -> ((0%Z <= (map.Map.get a1 i))%Z /\\ ((map.Map.get a1\n  i) < n)%Z)) /\\ exists v1:Z, (appear_twice a2 v1 (n + 2%Z)%Z) /\\\n  exists v2:Z, (appear_twice a2 v2 (n + 2%Z)%Z) /\\ ~ (v2 = v1)))) ->\n  ((0%Z <= n)%Z -> ((0%Z <= n)%Z -> let o := (n + 1%Z)%Z in ((0%Z <= o)%Z ->\n  forall (v2:Z) (v1:Z) (deja_vu:(@map.Map.map Z _ bool _)), forall (i:Z),\n  ((0%Z <= i)%Z /\\ (i <= o)%Z) -> ((((v1 = (-1%Z)%Z) -> (v2 = (-1%Z)%Z)) /\\\n  (((~ (v1 = (-1%Z)%Z)) -> (appear_twice a2 v1 i)) /\\\n  (((~ (v2 = (-1%Z)%Z)) -> ((appear_twice a2 v2 i) /\\ ~ (v2 = v1))) /\\\n  ((forall (v:Z), ((0%Z <= v)%Z /\\ (v < n)%Z) -> ((((map.Map.get deja_vu\n  v) = true) /\\ exists j:Z, ((0%Z <= j)%Z /\\ (j < i)%Z) /\\ ((map.Map.get a1\n  j) = v)) \\/ ((~ ((map.Map.get deja_vu v) = true)) /\\ forall (j:Z),\n  ((0%Z <= j)%Z /\\ (j < i)%Z) -> ~ ((map.Map.get a1 j) = v)))) /\\\n  (((v1 = (-1%Z)%Z) -> forall (v:Z), ((0%Z <= v)%Z /\\ (v < n)%Z) ->\n  ~ (appear_twice a2 v i)) /\\ ((v2 = (-1%Z)%Z) -> forall (v:Z),\n  ((0%Z <= v)%Z /\\ (v < n)%Z) -> ((~ (v = v1)) -> ~ (appear_twice a2 v\n  i)))))))) -> (((0%Z <= i)%Z /\\ (i < a)%Z) -> let v := (map.Map.get a1 i) in\n  (((0%Z <= n)%Z /\\ ((0%Z <= v)%Z /\\ (v < n)%Z)) -> (((map.Map.get deja_vu\n  v) = true) -> ((v1 = (-1%Z)%Z) -> forall (v11:Z), (v11 = v) ->\n  ((v2 = (-1%Z)%Z) -> forall (v3:Z), ((0%Z <= v3)%Z /\\ (v3 < n)%Z) ->\n  ((~ (v3 = v11)) -> ~ (appear_twice a2 v3 (i + 1%Z)%Z)))))))))))).\nintros a a1 n a2 (h1,((h2,h3),(h4,(v1,(h5,(v2,(h6,h7))))))) h8 h9 o\n        h10 v22 v12 deja_vu i (h11,h12) (h13,(h14,(h15,(h16,(h17,h18)))))\n        (h19,h20) v (h21,(h22,h23)) h24 h25 v11 h26 h27 v3 (h28,h29) h30.\nsubst a2 a o v v11 v12 v22.\nintro h0; red in h0.\ndestruct h0 as (i0,(h00,(h01,(j,(h02,(h03,h04)))))).\nintuition.\napply (H3 v3); auto.\nred; exists i0; intuition.\nassert (case: (i0 < i \\/ i0 = i)%Z) by omega. destruct case.\nauto.\nsubst i0.\nunfold get in h01; simpl in h01.\nomega.\nexists j; intuition.\nassert (case: (j < i \\/ j = i)%Z) by omega. destruct case.\nauto.\nsubst j.\nunfold get in h04; simpl in h04.\nomega.\nQed.\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/foveoos11_challenge3/foveoos11_challenge3_WP_TwoEqualElements_WP_parameter_two_equal_elements_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2955139749472744}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nRequire Import Bool.\nRequire Import ZArith.\nFrom IntMap Require Import Allmaps.\nFrom TreeAutomata Require Import bases.\nFrom TreeAutomata Require Import defs.\nFrom TreeAutomata Require Import semantics.\nFrom TreeAutomata Require Import signature.\nFrom TreeAutomata Require Import pl_path.\nFrom TreeAutomata Require Import refcorrect.\nFrom TreeAutomata Require Import states_kill_empty.\nFrom TreeAutomata Require Import lattice_fixpoint.\nFrom TreeAutomata Require Import empty_test.\n\n\n\nLemma prec_list_kill_correct_wrt_sign_invar :\nforall (m : Map bool) (p p' : prec_list) (n : nat),\npl_tl_length p n ->\nprec_list_kill m p = Some p' -> pl_tl_length p' n.\nProof. hammer_hook \"states_kill_correct\" \"states_kill_correct.prec_list_kill_correct_wrt_sign_invar\".\nintros. apply (forall_incl_length p' n). intros. elim (pl_kill_1 p p' m p0 H0 H1). intros. exact (pl_path_incl_length p0 p n H2 H).\nQed.\n\nLemma states_kill_aux_correct_wrt_sign_invar :\nforall (s : state) (m : Map bool) (sigma : signature),\nstate_correct_wrt_sign s sigma ->\nstate_correct_wrt_sign (states_kill_aux m s) sigma.\nProof. hammer_hook \"states_kill_correct\" \"states_kill_correct.states_kill_aux_correct_wrt_sign_invar\".\nunfold state_correct_wrt_sign in |- *. intros. elim (st_kill_2 _ _ _ _ H0).\nintros. elim H1. intros. elim (H _ _ H2). intros. split with x0.\nelim H4. intros. split. exact H5. exact (prec_list_kill_correct_wrt_sign_invar _ _ _ _ H6 H3).\nQed.\n\nLemma states_kill_correct_wrt_sign_invar :\nforall (s s' : state) (m : Map bool) (sigma : signature),\nstate_correct_wrt_sign s sigma ->\nstates_kill m s = Some s' -> state_correct_wrt_sign s' sigma.\nProof. hammer_hook \"states_kill_correct\" \"states_kill_correct.states_kill_correct_wrt_sign_invar\".\nunfold states_kill in |- *. intros. elim (map_sum prec_list (states_kill_aux m s)); intros. rewrite H1 in H0. inversion H0.\nelim H1; intros; elim H2; intros; elim H3; intros; rewrite H4 in H0. inversion H0. rewrite <- H4. exact (states_kill_aux_correct_wrt_sign_invar _ _ _ H). inversion H0.\nrewrite <- H4. exact (states_kill_aux_correct_wrt_sign_invar _ _ _ H).\nQed.\n\nLemma preDTA_kill_correct_wrt_sign_invar :\nforall (d : preDTA) (m : Map bool) (sigma : signature),\npredta_correct_wrt_sign d sigma ->\npredta_correct_wrt_sign (preDTA_kill m d) sigma.\nProof. hammer_hook \"states_kill_correct\" \"states_kill_correct.preDTA_kill_correct_wrt_sign_invar\".\nunfold predta_correct_wrt_sign in |- *. intros. elim (dt_kill_1 _ _ _ _ H0). intros. elim H1. intros. exact (states_kill_correct_wrt_sign_invar _ _ _ _ (H _ _ H2) H3).\nQed.\n\nLemma DTA_kill_correct_wrt_sign_invar :\nforall (d : DTA) (m : Map bool) (sigma : signature),\ndta_correct_wrt_sign d sigma -> dta_correct_wrt_sign (DTA_kill m d) sigma.\nProof. hammer_hook \"states_kill_correct\" \"states_kill_correct.DTA_kill_correct_wrt_sign_invar\".\nsimple induction d. simpl in |- *. intros. elim (option_sum state (MapGet state (preDTA_kill m p) a)). intros y. elim y. intros x y0.\nrewrite y0. exact (preDTA_kill_correct_wrt_sign_invar _ _ _ H). intros y. rewrite y. unfold dta_correct_wrt_sign in |- *.\nunfold predta_correct_wrt_sign in |- *. intros. simpl in H0.\nelim (N.discr a0); intros y0. elim y0. intros x y1. rewrite y1 in H0. inversion H0. rewrite y0 in H0. inversion H0.\nunfold state_correct_wrt_sign in |- *. intros. inversion H1.\nQed.\n\nLemma DTA_kill_empty_states_lazy_correct_wrt_sign_invar :\nforall (d : DTA) (sigma : signature),\ndta_correct_wrt_sign d sigma ->\ndta_correct_wrt_sign (DTA_kill_empty_states_lazy d) sigma.\nProof. hammer_hook \"states_kill_correct\" \"states_kill_correct.DTA_kill_empty_states_lazy_correct_wrt_sign_invar\".\nintro. rewrite (kill_empty_states_lazy_eg_kill_empty_states d). unfold DTA_kill_empty_states in |- *. exact (DTA_kill_correct_wrt_sign_invar d (dta_states_non_empty d)).\nQed.\n\nLemma kill_empty_correct_wrt_sign_invar :\nforall (d : DTA) (sigma : signature),\ndta_correct_wrt_sign d sigma ->\ndta_correct_wrt_sign (DTA_kill_empty_states d) sigma.\nProof. hammer_hook \"states_kill_correct\" \"states_kill_correct.kill_empty_correct_wrt_sign_invar\".\nsimple induction d. simpl in |- *. intros. elim\n(option_sum state (MapGet state (preDTA_kill (dta_non_empty_states p) p) a));\nintros y.\nelim y. intros x y0. rewrite y0. simpl in |- *. exact (kill_empty_correct_wrt_sign_invar p sigma (dta_non_empty_states p) H). rewrite y. simpl in |- *. unfold predta_correct_wrt_sign in |- *.\nintros. simpl in H0. elim (N.discr a0). intros y0. elim y0.\nintros x y1. rewrite y1 in H0. inversion H0. intros y0. rewrite y0 in H0. inversion H0. unfold state_correct_wrt_sign in |- *.\nintros. inversion H1.\nQed.\n\nLemma kill_empty_lazy_correct_wrt_sign_invar :\nforall (d : DTA) (sigma : signature),\ndta_correct_wrt_sign d sigma ->\ndta_correct_wrt_sign (DTA_kill_empty_states_lazy d) sigma.\nProof. hammer_hook \"states_kill_correct\" \"states_kill_correct.kill_empty_lazy_correct_wrt_sign_invar\".\nintro. rewrite (kill_empty_states_lazy_eg_kill_empty_states d).\nexact (kill_empty_correct_wrt_sign_invar d).\nQed.\n\n\n\nLemma prec_list_kill_occur :\nforall (p p' : prec_list) (b : ad) (m : Map bool),\nprec_list_kill m p = Some p' ->\nprec_occur p' b -> MapGet bool m b = Some true.\nProof. hammer_hook \"states_kill_correct\" \"states_kill_correct.prec_list_kill_occur\".\nsimple induction p. intros. simpl in H1. elim (pl_sum p1); intros.\nrewrite H3 in H1. elim (option_sum bool (MapGet bool m a)); intros y. elim y. intros x y0. rewrite y0 in H1. elim (bool_is_true_or_false x); intros; rewrite H4 in H1.\nelim (option_sum prec_list (prec_list_kill m p0)); intros y1.\nelim y1. intros x0 y2. rewrite y2 in H1. inversion H1. rewrite <- H6 in H2. inversion H2. rewrite <- H5. rewrite H4 in y0. exact y0. exact (H _ _ _ y2 H10). inversion H10.\nrewrite y1 in H1. inversion H1. inversion H1. rewrite y in H1. inversion H1. elim H3. intros. elim H4. intros.\nelim H5. intros. rewrite H6 in H1. elim (option_sum bool (MapGet bool m a)); intros y. elim y. intros x2 y0. rewrite y0 in H1. elim (bool_is_true_or_false x2); intros; rewrite H7 in H1. elim (option_sum prec_list (prec_list_kill m p0)); intros y1. elim y1. intros x3 y2. rewrite y2 in H1. elim (option_sum prec_list (prec_list_kill m (prec_cons x x0 x1)));\nintros y3. elim y3. intros x4 y4.\nrewrite y4 in H1. inversion H1. rewrite <- H9 in H2.\ninversion H2. rewrite <- H8. rewrite H7 in y0. exact y0.\nexact (H _ _ _ y2 H13). rewrite <- H6 in y4. exact (H0 _ _ _ y4 H13). rewrite y3 in H1. inversion H1.\nrewrite <- H9 in H2. inversion H2. rewrite <- H8.\nrewrite H7 in y0. exact y0. exact (H _ _ _ y2 H13).\ninversion H13. rewrite y1 in H1. elim (option_sum prec_list (prec_list_kill m (prec_cons x x0 x1)));\nintros y2. elim y2. intros x3 y3. rewrite y3 in H1. inversion H1. rewrite <- H9 in H2. rewrite <- H6 in y3. exact (H0 _ _ _ y3 H2). rewrite y2 in H1. inversion H1.\nrewrite <- H6 in H1. exact (H0 _ _ _ H1 H2). rewrite y in H1. rewrite <- H6 in H1. exact (H0 _ _ _ H1 H2).\nintros. simpl in H. inversion H. rewrite <- H2 in H0.\ninversion H0.\nQed.\n\nLemma prec_list_kill_ref_ok_invar :\nforall (d : preDTA) (p p' : prec_list) (sigma : signature),\nprec_list_ref_ok p d ->\npredta_correct_wrt_sign d sigma ->\nprec_list_kill (dta_non_empty_states d) p = Some p' ->\nprec_list_ref_ok p' (preDTA_kill (dta_non_empty_states d) d).\nProof. hammer_hook \"states_kill_correct\" \"states_kill_correct.prec_list_kill_ref_ok_invar\".\nintros. unfold prec_list_ref_ok in |- *. intros. elim (dt_non_empty_fix d a). intros. elim (H3 (prec_list_kill_occur _ _ _ _ H1 H2)). intros.\nelim (dt_kill_empty_kill_empty d a sigma H0).\nintros. apply H7. split with x. exact H5.\nQed.\n\nLemma states_kill_aux_ref_ok_invar :\nforall (d : preDTA) (s : state) (sigma : signature),\nstate_ref_ok s d ->\npredta_correct_wrt_sign d sigma ->\nstate_ref_ok (states_kill_aux (dta_non_empty_states d) s)\n(preDTA_kill (dta_non_empty_states d) d).\nProof. hammer_hook \"states_kill_correct\" \"states_kill_correct.states_kill_aux_ref_ok_invar\".\nunfold state_ref_ok in |- *. intros. elim (st_kill_2 _ _ _ _ H1).\nintros. elim H2. intros. exact (prec_list_kill_ref_ok_invar d x p sigma (H a x H3) H0 H4).\nQed.\n\nLemma states_kill_ref_ok_invar :\nforall (d : preDTA) (s s' : state) (sigma : signature),\nstate_ref_ok s d ->\npredta_correct_wrt_sign d sigma ->\nstates_kill (dta_non_empty_states d) s = Some s' ->\nstate_ref_ok s' (preDTA_kill (dta_non_empty_states d) d).\nProof. hammer_hook \"states_kill_correct\" \"states_kill_correct.states_kill_ref_ok_invar\".\nintros. unfold states_kill in H1. elim (map_sum prec_list (states_kill_aux (dta_non_empty_states d) s));\nintros.\nrewrite H2 in H1. inversion H1. elim H2; intros; elim H3; intros; elim H4; intros; rewrite H5 in H1. inversion H1.\nrewrite <- H5. exact (states_kill_aux_ref_ok_invar _ _ _ H H0). inversion H1. rewrite <- H5. exact (states_kill_aux_ref_ok_invar _ _ _ H H0).\nQed.\n\nLemma preDTA_kill_ref_ok_distinct_invar :\nforall (d : preDTA) (sigma : signature),\npreDTA_ref_ok_distinct d d ->\npredta_correct_wrt_sign d sigma ->\npreDTA_ref_ok_distinct (preDTA_kill (dta_non_empty_states d) d)\n(preDTA_kill (dta_non_empty_states d) d).\nProof. hammer_hook \"states_kill_correct\" \"states_kill_correct.preDTA_kill_ref_ok_distinct_invar\".\nunfold preDTA_ref_ok_distinct in |- *. intros. elim (dt_kill_1 _ _ _ _ H1). intros. elim H2. intros. exact (states_kill_ref_ok_invar d x s sigma (H a x H3) H0 H4).\nQed.\n\nLemma preDTA_kill_ref_ok_invar :\nforall (d : preDTA) (sigma : signature),\npreDTA_ref_ok d ->\npredta_correct_wrt_sign d sigma ->\npreDTA_ref_ok (preDTA_kill (dta_non_empty_states d) d).\nProof. hammer_hook \"states_kill_correct\" \"states_kill_correct.preDTA_kill_ref_ok_invar\".\nintros. elim (preDTA_ref_ok_def (preDTA_kill (dta_non_empty_states d) d)). intros. apply H2.\nelim (preDTA_ref_ok_def d). intro. intro. exact (preDTA_kill_ref_ok_distinct_invar d sigma (H3 H) H0).\nQed.\n\nLemma DTA_kill_ref_ok_invar :\nforall (d : DTA) (sigma : signature),\nDTA_ref_ok d ->\ndta_correct_wrt_sign d sigma ->\nDTA_ref_ok (DTA_kill (dta_states_non_empty d) d).\nProof. hammer_hook \"states_kill_correct\" \"states_kill_correct.DTA_kill_ref_ok_invar\".\nsimple induction d. simpl in |- *. intros. elim\n(option_sum state (MapGet state (preDTA_kill (dta_non_empty_states p) p) a));\nintros y. elim y. intros x y0. rewrite y0. exact (preDTA_kill_ref_ok_invar _ _ H H0). rewrite y. simpl in |- *.\nunfold preDTA_ref_ok in |- *. intros. simpl in H1. elim (N.discr a0); intros y0. elim y0. intros x y1. rewrite y1 in H1. inversion H1. rewrite y0 in H1. inversion H1. rewrite <- H5 in H2.\ninversion H2.\nQed.\n\nLemma DTA_kill_ref_ok_invar_lazy :\nforall (d : DTA) (sigma : signature),\nDTA_ref_ok d ->\ndta_correct_wrt_sign d sigma -> DTA_ref_ok (DTA_kill_empty_states_lazy d).\nProof. hammer_hook \"states_kill_correct\" \"states_kill_correct.DTA_kill_ref_ok_invar_lazy\".\nintro. rewrite (kill_empty_states_lazy_eg_kill_empty_states d). exact (DTA_kill_ref_ok_invar d).\nQed.\n\n\n\nLemma inter_DTA_main_state_correct_invar :\nforall d : DTA,\nDTA_main_state_correct d ->\nDTA_main_state_correct (DTA_kill (dta_states_non_empty d) d).\nProof. hammer_hook \"states_kill_correct\" \"states_kill_correct.inter_DTA_main_state_correct_invar\".\nsimple induction d. simpl in |- *. intros. elim\n(option_sum state (MapGet state (preDTA_kill (dta_non_empty_states p) p) a));\nintros y. elim y. intros x y0. rewrite y0. simpl in |- *.\nunfold addr_in_preDTA in |- *. unfold addr_in_preDTA in H.\nsplit with x. exact y0. rewrite y. simpl in |- *. unfold addr_in_preDTA in |- *. intros. split with (M0 prec_list).\nreflexivity.\nQed.\n\nLemma inter_DTA_main_state_correct_invar_lazy :\nforall d : DTA,\nDTA_main_state_correct d ->\nDTA_main_state_correct (DTA_kill_empty_states_lazy d).\nProof. hammer_hook \"states_kill_correct\" \"states_kill_correct.inter_DTA_main_state_correct_invar_lazy\".\nintro. rewrite (kill_empty_states_lazy_eg_kill_empty_states d).\nexact (inter_DTA_main_state_correct_invar d).\nQed.\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/tree-automata/states_kill_correct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.29551396750527564}}
{"text": "From VLSM.Lib Require Import Itauto.\nFrom stdpp Require Import prelude.\nFrom VLSM.Lib Require Import Preamble ListExtras StreamExtras StreamFilters StdppExtras.\nFrom VLSM.Core Require Import VLSM VLSMProjections.VLSMPartialProjection.\n\nSection sec_VLSM_projection.\n\n(** * VLSM Total Projections\n\n  A VLSM projection guaranteeing the existence of projection for all states and\n  traces. We say that VLSM <<X>> projects to VLSM <<Y>> (sharing the same messages) if\n  there exists maps <<state_project>> taking <<X>>-states to <<Y>>-states,\n  and <<trace_project>>, taking list of transitions from <<X>> to <<Y>>, such that:\n\n  - state and [trace_project_preserves_valid_trace]s.\n\n  - [trace_project_app]: trace projection commutes with concatenation of traces\n\n  - [final_state_project]: state projection commutes with [finite_trace_last]\n\n  Proper examples of total projections (which are not [VLSM_embedding]s)\n  are projections in which some of transitions might be dropped, such as\n  the projection of a composition to one of the components ([component_projection])\n  or the projection of the compositions of equivocators to the composition of\n  regular nodes using the particular [MachineDescriptor] which select the\n  first (original) node instance for each equivocator (e.g.,\n  [equivocators_no_equivocations_vlsm_X_vlsm_projection]).\n*)\n\nSection sec_pre_definitions.\n\nContext\n  {message : Type}\n  (TX TY : VLSMType message)\n  (label_project : @label _ TX -> option (@label _ TY))\n  (state_project : @state _ TX -> @state _ TY)\n  .\n\nDefinition pre_VLSM_projection_in_projection\n  (item : @transition_item _ TX)\n  : Prop :=\n  is_Some (label_project (l item)).\n\nDefinition pre_VLSM_projection_transition_item_project\n  (item : @transition_item _ TX)\n  : option (@transition_item _ TY)\n  :=\n  match label_project (l item) with\n  | None => None\n  | Some lY =>\n    Some {| l := lY; input := input item; destination := state_project (destination item);\n            output := output item |}\n  end.\n\nLemma pre_VLSM_projection_transition_item_project_is_Some\n  (item : @transition_item _ TX)\n  : pre_VLSM_projection_in_projection item ->\n    is_Some (pre_VLSM_projection_transition_item_project item).\nProof.\n  intros [lY HlY].\n  unfold pre_VLSM_projection_transition_item_project.\n  rewrite HlY.\n  by eexists.\nQed.\n\nLemma pre_VLSM_projection_transition_item_project_is_Some_rev\n  (item : @transition_item _ TX)\n  : is_Some (pre_VLSM_projection_transition_item_project item) ->\n    pre_VLSM_projection_in_projection item.\nProof.\n  intros [itemY HitemY].\n  unfold pre_VLSM_projection_transition_item_project in HitemY.\n  destruct (label_project (l item)) as [lY |] eqn: HlY; [| by congruence].\n  by exists lY.\nQed.\n\nLemma pre_VLSM_projection_transition_item_project_infinitely_often\n  (s : Streams.Stream (@transition_item _ TX))\n  : InfinitelyOften pre_VLSM_projection_in_projection s ->\n    InfinitelyOften (is_Some ∘ pre_VLSM_projection_transition_item_project) s.\nProof.\n  apply InfinitelyOften_impl.\n  intro item.\n  by apply pre_VLSM_projection_transition_item_project_is_Some.\nQed.\n\nLemma pre_VLSM_projection_transition_item_project_finitely_many\n  (s : Streams.Stream (@transition_item _ TX))\n  : FinitelyManyBound pre_VLSM_projection_in_projection s ->\n    FinitelyManyBound (is_Some ∘ pre_VLSM_projection_transition_item_project) s.\nProof.\n  apply FinitelyManyBound_impl_rev.\n  intro item.\n  by apply pre_VLSM_projection_transition_item_project_is_Some_rev.\nQed.\n\nDefinition pre_VLSM_projection_finite_trace_project\n  : list (@transition_item _ TX) -> list (@transition_item _ TY)\n  :=\n  map_option pre_VLSM_projection_transition_item_project.\n\nDefinition pre_VLSM_projection_infinite_trace_project\n  (s : Streams.Stream (@transition_item _ TX))\n  (Hs : InfinitelyOften  pre_VLSM_projection_in_projection s)\n  : Streams.Stream (@transition_item _ TY) :=\n  stream_map_option pre_VLSM_projection_transition_item_project s\n    (pre_VLSM_projection_transition_item_project_infinitely_often _ Hs).\n\nDefinition pre_VLSM_projection_infinite_finite_trace_project\n  (s : Streams.Stream (@transition_item _ TX))\n  (Hs : FinitelyManyBound pre_VLSM_projection_in_projection s)\n  : list (@transition_item _ TY) :=\n  pre_VLSM_projection_finite_trace_project (stream_prefix s (proj1_sig Hs)).\n\nDefinition pre_VLSM_projection_finite_trace_project_app\n  : forall l1 l2, pre_VLSM_projection_finite_trace_project (l1 ++ l2) =\n    pre_VLSM_projection_finite_trace_project l1 ++ pre_VLSM_projection_finite_trace_project l2\n  := map_option_app _.\n\nDefinition pre_VLSM_projection_finite_trace_project_app_rev\n  : forall l l1' l2', pre_VLSM_projection_finite_trace_project l = l1' ++ l2' ->\n    exists l1 l2, l = l1 ++ l2 /\\\n      pre_VLSM_projection_finite_trace_project l1 = l1' /\\\n      pre_VLSM_projection_finite_trace_project l2 = l2'\n  := map_option_app_rev _.\n\nDefinition pre_VLSM_projection_finite_trace_project_in_iff\n  : forall trX itemY, In itemY (pre_VLSM_projection_finite_trace_project trX) <->\n    exists itemX, In itemX trX /\\ pre_VLSM_projection_transition_item_project itemX = Some itemY\n  := in_map_option _.\n\nDefinition elem_of_pre_VLSM_projection_finite_trace_project\n  : forall trX itemY, itemY ∈ pre_VLSM_projection_finite_trace_project trX <->\n    exists itemX, itemX ∈ trX /\\ pre_VLSM_projection_transition_item_project itemX = Some itemY\n  := elem_of_map_option _.\n\nDefinition pre_VLSM_projection_finite_trace_project_in\n  : forall itemX itemY, pre_VLSM_projection_transition_item_project itemX = Some itemY ->\n    forall trX, In itemX trX -> In itemY (pre_VLSM_projection_finite_trace_project trX)\n  := in_map_option_rev _.\n\nEnd sec_pre_definitions.\n\nRecord VLSM_projection_type\n  {message : Type}\n  (X : VLSM message)\n  (TY : VLSMType message)\n  (label_project : vlabel X -> option (@label _ TY))\n  (state_project : vstate X -> @state _ TY)\n  (trace_project := pre_VLSM_projection_finite_trace_project (type X) TY label_project state_project)\n  : Prop :=\n{\n  final_state_project :\n    forall sX trX,\n      finite_valid_trace_from X sX trX ->\n        state_project (finite_trace_last sX trX) =\n        finite_trace_last (state_project sX) (trace_project trX);\n}.\n\n(** ** Projection definitions and properties *)\n\nSection sec_projection_type_properties.\n\nDefinition VLSM_partial_trace_project_from_projection\n  {message : Type}\n  {X : VLSM message}\n  {TY : VLSMType message}\n  (label_project : vlabel X -> option (@label _ TY))\n  (state_project : vstate X -> @state _ TY)\n  (trace_project := pre_VLSM_projection_finite_trace_project _ _ label_project state_project)\n  := fun str : vstate X * list (vtransition_item X) =>\n      let (s, tr) := str in Some (state_project s, trace_project tr).\n\nContext\n  {message : Type}\n  {X Y : VLSM message}\n  {label_project : vlabel X -> option (vlabel Y)}\n  {state_project : vstate X -> vstate Y}\n  (trace_project := pre_VLSM_projection_finite_trace_project _ _ label_project state_project)\n  (Hsimul : VLSM_projection_type X (type Y) label_project state_project)\n  .\n\n(**\n  Any [VLSM_projection_type] determines a [VLSM_partial_projection_type], allowing us\n  to lift to VLSM projection the generic results proved about VLSM partial projections.\n*)\nLemma VLSM_partial_projection_type_from_projection :\n  VLSM_partial_projection_type X Y\n    (VLSM_partial_trace_project_from_projection label_project state_project).\nProof.\n  split; intros; inversion H; subst; clear H.\n  exists (state_project s'X), (trace_project preX).  split.\n  - by cbn; rewrite pre_VLSM_projection_finite_trace_project_app.\n  - symmetry. apply (final_state_project _ _ _ _ Hsimul).\n    by apply (finite_valid_trace_from_app_iff  X) in H1; apply H1.\nQed.\n\nEnd sec_projection_type_properties.\n\nSection sec_projection_transition_consistency_None.\n\nContext\n  {message : Type}\n  (X : VLSM message)\n  (TY : VLSMType message)\n  (label_project : vlabel X -> option (@label _ TY))\n  (state_project : vstate X -> @state _ TY)\n  (trace_project := pre_VLSM_projection_finite_trace_project _ _ label_project state_project)\n  .\n\n(**\n  When a label cannot be projected, and thus the transition will not be\n  preserved by the projection, the state projections of the states between and\n  after the transition must coincide.\n*)\nDefinition weak_projection_transition_consistency_None : Prop :=\n  forall lX, label_project lX = None ->\n  forall s om s' om', input_valid_transition X lX (s, om) (s', om') ->\n      state_project s' = state_project s.\n\nDefinition strong_projection_transition_consistency_None : Prop :=\n  forall lX, label_project lX = None ->\n  forall s om s' om', vtransition X lX (s, om) = (s', om') ->\n    state_project s' = state_project s.\n\nLemma strong_projection_transition_consistency_None_weaken\n  : strong_projection_transition_consistency_None ->\n    weak_projection_transition_consistency_None.\nProof.\n  intros Hstrong lX Hl s om s' om' Ht.\n  by apply (Hstrong lX Hl _ _ _ _ (proj2 Ht)).\nQed.\n\nEnd sec_projection_transition_consistency_None.\n\nSection sec_VLSM_projection_definitions.\n\nContext\n  {message : Type}\n  (X Y : VLSM message)\n  (label_project : vlabel X -> option (vlabel Y))\n  (state_project : vstate X -> vstate Y)\n  (trace_project := pre_VLSM_projection_finite_trace_project _ _ label_project state_project)\n  .\n\n(**\n  Similarly to the [VLSM_partial_projection] case we distinguish two types of\n  projections: [VLSM_weak_projection] and [VLSM_projection], distinguished by the\n  fact that the weak projections are not required to preserve initial states.\n\n  Although we don't have proper examples of [VLSM_weak_projection]s, they are a\n  support base for [VLSM_weak_embedding]s for which we have proper examples.\n*)\nRecord VLSM_weak_projection : Prop :=\n{\n  weak_projection_type :> VLSM_projection_type X (type Y) label_project state_project;\n  weak_trace_project_preserves_valid_trace :\n    forall sX trX,\n      finite_valid_trace_from X sX trX ->\n      finite_valid_trace_from Y (state_project sX) (trace_project trX);\n}.\n\nRecord VLSM_projection : Prop :=\n{\n  projection_type :> VLSM_projection_type X (type Y) label_project state_project;\n  trace_project_preserves_valid_trace :\n    forall sX trX,\n      finite_valid_trace X sX trX -> finite_valid_trace Y (state_project sX) (trace_project trX);\n}.\n\nDefinition weak_projection_initial_state_preservation : Prop :=\n  forall s : state,\n    vinitial_state_prop X s -> valid_state_prop Y (state_project s).\n\nDefinition strong_projection_initial_state_preservation : Prop :=\n  forall s : state,\n    vinitial_state_prop X s -> vinitial_state_prop Y (state_project s).\n\nLemma strong_projection_initial_state_preservation_weaken\n  : strong_projection_initial_state_preservation ->\n    weak_projection_initial_state_preservation.\nProof.\n  intros Hstrong s Hs. apply Hstrong in Hs.\n  by apply initial_state_is_valid.\nQed.\n\nDefinition weak_projection_valid_preservation : Prop :=\n  forall lX lY (HlX : label_project lX = Some lY),\n  forall s om\n    (Hv : input_valid X lX (s, om))\n    (HsY : valid_state_prop Y (state_project s))\n    (HomY : option_valid_message_prop Y om),\n    vvalid Y lY ((state_project s), om).\n\nDefinition strong_projection_valid_preservation : Prop :=\n  forall lX lY, label_project lX = Some lY ->\n  forall s om,\n  vvalid X lX (s, om) -> vvalid Y lY ((state_project s), om).\n\nLemma strong_projection_valid_preservation_weaken\n  : strong_projection_valid_preservation ->\n    weak_projection_valid_preservation.\nProof.\n  intros Hstrong lX lY Hl s om Hpv Hs Hom.\n  by apply (Hstrong lX lY Hl), Hpv.\nQed.\n\nDefinition weak_projection_transition_preservation_Some : Prop :=\n  forall lX lY, label_project lX = Some lY ->\n  forall s om s' om', input_valid_transition X lX (s, om) (s', om') ->\n    vtransition Y lY (state_project s, om) = (state_project s', om').\n\nDefinition strong_projection_transition_preservation_Some : Prop :=\n  forall lX lY, label_project lX = Some lY ->\n  forall s om s' om', vtransition X lX (s, om) = (s', om') ->\n    vtransition Y lY (state_project s, om) = (state_project s', om').\n\nLemma strong_projection_transition_preservation_Some_weaken\n  : strong_projection_transition_preservation_Some ->\n    weak_projection_transition_preservation_Some.\nProof.\n  intros Hstrong lX lY Hl s om s' om' Ht.\n  by apply (Hstrong lX lY Hl), Ht.\nQed.\n\nDefinition weak_projection_valid_message_preservation : Prop :=\n  forall lX lY (HlX : label_project lX = Some lY),\n  forall s m\n    (Hv : input_valid X lX (s, Some m))\n    (HsY : valid_state_prop Y (state_project s)),\n    valid_message_prop Y m.\n\nDefinition strong_projection_valid_message_preservation : Prop :=\n  forall m : message,\n    valid_message_prop X m -> valid_message_prop Y m.\n\nLemma strong_projection_valid_message_preservation_weaken\n  : strong_projection_valid_message_preservation ->\n    weak_projection_valid_message_preservation.\nProof.\n  by intros Hstrong lX lY Hl  s m [_ [Hm%Hstrong _]] HsY.\nQed.\n\nEnd sec_VLSM_projection_definitions.\n\nSection sec_weak_projection_properties.\n\nDefinition VLSM_weak_projection_trace_project\n  {message : Type}\n  {X Y : VLSM message}\n  {label_project : vlabel X -> option (vlabel Y)}\n  {state_project : vstate X -> vstate Y}\n  (Hsimul : VLSM_weak_projection X Y label_project state_project)\n  : list (vtransition_item X) -> list (vtransition_item Y)\n  := pre_VLSM_projection_finite_trace_project _ _ label_project state_project.\n\nDefinition VLSM_weak_projection_in\n  {message : Type}\n  {X Y : VLSM message}\n  {label_project : vlabel X -> option (vlabel Y)}\n  {state_project : vstate X -> vstate Y}\n  (Hsimul : VLSM_weak_projection X Y label_project state_project)\n  := pre_VLSM_projection_in_projection _ _ label_project.\n\nDefinition VLSM_weak_projection_infinite_trace_project\n  {message : Type}\n  {X Y : VLSM message}\n  {label_project : vlabel X -> option (vlabel Y)}\n  {state_project : vstate X -> vstate Y}\n  (Hsimul : VLSM_weak_projection X Y label_project state_project)\n  (s : Streams.Stream (vtransition_item X))\n  (Hinf : InfinitelyOften (VLSM_weak_projection_in Hsimul) s)\n  : Streams.Stream (vtransition_item Y)\n  := pre_VLSM_projection_infinite_trace_project _ _ label_project state_project s Hinf.\n\nDefinition VLSM_weak_projection_infinite_finite_trace_project\n  {message : Type}\n  {X Y : VLSM message}\n  {label_project : vlabel X -> option (vlabel Y)}\n  {state_project : vstate X -> vstate Y}\n  (Hsimul : VLSM_weak_projection X Y label_project state_project)\n  (s : Streams.Stream (vtransition_item X))\n  (Hfin : FinitelyManyBound (VLSM_weak_projection_in Hsimul) s)\n  : list (vtransition_item Y)\n  := pre_VLSM_projection_infinite_finite_trace_project _ _ label_project state_project s Hfin.\n\nContext\n  {message : Type}\n  {X Y : VLSM message}\n  {label_project : vlabel X -> option (vlabel Y)}\n  {state_project : vstate X -> vstate Y}\n  (Hsimul : VLSM_weak_projection X Y label_project state_project)\n  .\n\nDefinition VLSM_weak_projection_trace_project_app\n  : forall l1 l2, VLSM_weak_projection_trace_project Hsimul (l1 ++ l2) =\n    VLSM_weak_projection_trace_project Hsimul l1 ++ VLSM_weak_projection_trace_project Hsimul l2\n  := pre_VLSM_projection_finite_trace_project_app _ _ label_project state_project.\n\nDefinition VLSM_weak_projection_trace_project_app_rev\n  : forall l l1' l2', VLSM_weak_projection_trace_project Hsimul l = l1' ++ l2' ->\n    exists l1 l2, l = l1 ++ l2 /\\\n      VLSM_weak_projection_trace_project Hsimul l1 = l1' /\\\n      VLSM_weak_projection_trace_project Hsimul l2 = l2'\n  := pre_VLSM_projection_finite_trace_project_app_rev _ _ label_project state_project.\n\nDefinition VLSM_weak_projection_finite_trace_last\n  : forall sX trX,\n    finite_valid_trace_from X sX trX ->\n    state_project (finite_trace_last sX trX) =\n    finite_trace_last (state_project sX) (VLSM_weak_projection_trace_project Hsimul trX)\n  := final_state_project _ _ _ _ Hsimul.\n\nDefinition VLSM_weak_projection_finite_valid_trace_from\n  : forall sX trX,\n    finite_valid_trace_from X sX trX ->\n      finite_valid_trace_from Y (state_project sX) (VLSM_weak_projection_trace_project Hsimul trX)\n  := weak_trace_project_preserves_valid_trace _ _ _ _ Hsimul.\n\nLemma VLSM_weak_projection_infinite_valid_trace_from\n  : forall sX trX (Hinf : InfinitelyOften (VLSM_weak_projection_in Hsimul) trX),\n    infinite_valid_trace_from X sX trX ->\n    infinite_valid_trace_from Y (state_project sX)\n      (VLSM_weak_projection_infinite_trace_project Hsimul trX Hinf).\nProof.\n  intros sX trX Hinf HtrX.\n  apply infinite_valid_trace_from_prefix_rev.\n  intros n.\n  specialize\n    (stream_map_option_prefix_ex (pre_VLSM_projection_transition_item_project _ _\n      label_project state_project) trX\n    (pre_VLSM_projection_transition_item_project_infinitely_often _ _\n      label_project state_project trX Hinf)\n    n)\n    as [m Hrew].\n  unfold VLSM_weak_projection_infinite_trace_project, pre_VLSM_projection_infinite_trace_project.\n  replace (stream_prefix _ _) with (VLSM_weak_projection_trace_project Hsimul (stream_prefix trX m)).\n  by apply VLSM_weak_projection_finite_valid_trace_from, infinite_valid_trace_from_prefix.\nQed.\n\nLemma VLSM_weak_projection_infinite_finite_valid_trace_from\n  : forall sX trX (Hfin : FinitelyManyBound (VLSM_weak_projection_in Hsimul) trX),\n    infinite_valid_trace_from X sX trX ->\n    finite_valid_trace_from Y (state_project sX)\n      (VLSM_weak_projection_infinite_finite_trace_project Hsimul trX Hfin).\nProof.\n  intros sX trX Hfin HtrX.\n  apply VLSM_weak_projection_finite_valid_trace_from.\n  by apply infinite_valid_trace_from_prefix with (n := `Hfin) in HtrX.\nQed.\n\n(**\n  Any [VLSM_projection] determines a [VLSM_partial_projection], allowing us\n  to lift to VLSM projection the generic results proved about VLSM partial projections.\n*)\nLemma VLSM_weak_partial_projection_from_projection :\n  VLSM_weak_partial_projection X Y\n    (VLSM_partial_trace_project_from_projection label_project state_project).\nProof.\n  split.\n  - by apply VLSM_partial_projection_type_from_projection, Hsimul.\n  - cbn; intros sX trX sY trY [= <- <-].\n    by apply VLSM_weak_projection_finite_valid_trace_from.\nQed.\n\nLemma VLSM_weak_projection_valid_state\n  : forall sX,\n    valid_state_prop X sX -> valid_state_prop Y (state_project sX).\nProof.\n  specialize VLSM_weak_partial_projection_from_projection as Hpart_simul.\n  specialize (VLSM_weak_partial_projection_valid_state Hpart_simul) as Hps.\n  by intro sX; eapply Hps.\nQed.\n\nLemma VLSM_weak_projection_input_valid_transition\n  : forall lX lY, label_project lX = Some lY ->\n    forall s im s' om,\n    input_valid_transition X lX (s, im) (s', om) ->\n    input_valid_transition Y lY (state_project s, im) (state_project s', om).\nProof.\n  specialize VLSM_weak_partial_projection_from_projection as Hpart_simul.\n  specialize (VLSM_weak_partial_projection_input_valid_transition Hpart_simul) as Hivt.\n  intros.\n  apply\n    (Hivt s {| l := lX; input := im; destination := s'; output := om |}\n      (state_project s) {| l := lY; input := im; destination := state_project s'; output := om |})\n  ; [| done].\n  by cbn; unfold pre_VLSM_projection_transition_item_project; cbn; rewrite H.\nQed.\n\nLemma VLSM_weak_projection_input_valid\n  : forall lX lY, label_project lX = Some lY ->\n    forall s im, input_valid X lX (s, im) -> input_valid Y lY (state_project s, im).\nProof.\n  intros lX lY Hpr sX im HvX.\n  destruct (vtransition X lX (sX, im)) eqn: HtX.\n  by eapply VLSM_weak_projection_input_valid_transition, input_valid_can_transition.\nQed.\n\nLemma VLSM_weak_projection_finite_valid_trace_from_to :\n  forall sX s'X trX,\n    finite_valid_trace_from_to X sX s'X trX ->\n      finite_valid_trace_from_to Y (state_project sX) (state_project s'X)\n        (VLSM_weak_projection_trace_project Hsimul trX).\nProof.\n  specialize VLSM_weak_partial_projection_from_projection as Hpart_simul.\n  specialize (VLSM_weak_partial_projection_finite_valid_trace_from Hpart_simul) as Htr.\n  intros sX s'X trX HtrX.\n  apply valid_trace_get_last in HtrX as Hs'X.\n  apply valid_trace_forget_last in HtrX. subst.\n  rewrite (final_state_project _ _ _ _ Hsimul); [| done].\n  by apply valid_trace_add_default_last; eauto.\nQed.\n\nLemma VLSM_weak_projection_in_futures\n  : forall s1 s2,\n    in_futures X s1 s2 -> in_futures Y (state_project s1) (state_project s2).\nProof.\n  intros s1 s2 [tr Htr].\n  exists (VLSM_weak_projection_trace_project Hsimul tr).\n  by apply VLSM_weak_projection_finite_valid_trace_from_to.\nQed.\n\nEnd sec_weak_projection_properties.\n\nSection sec_projection_properties.\n\nDefinition VLSM_projection_finite_trace_project\n  {message : Type}\n  {X Y : VLSM message}\n  {label_project : vlabel X -> option (vlabel Y)}\n  {state_project : vstate X -> vstate Y}\n  (Hsimul : VLSM_projection X Y label_project state_project)\n  : list (vtransition_item X) -> list (vtransition_item Y)\n  := pre_VLSM_projection_finite_trace_project _ _ label_project state_project.\n\nDefinition VLSM_projection_in\n  {message : Type}\n  {X Y : VLSM message}\n  {label_project : vlabel X -> option (vlabel Y)}\n  {state_project : vstate X -> vstate Y}\n  (Hsimul : VLSM_projection X Y label_project state_project)\n  := pre_VLSM_projection_in_projection _ _ label_project.\n\nDefinition VLSM_projection_infinite_trace_project\n  {message : Type}\n  {X Y : VLSM message}\n  {label_project : vlabel X -> option (vlabel Y)}\n  {state_project : vstate X -> vstate Y}\n  (Hsimul : VLSM_projection X Y label_project state_project)\n  (s : Streams.Stream (vtransition_item X))\n  (Hinf : InfinitelyOften (VLSM_projection_in Hsimul) s)\n  : Streams.Stream (vtransition_item Y)\n  := pre_VLSM_projection_infinite_trace_project _ _ label_project state_project s Hinf.\n\nDefinition VLSM_projection_infinite_finite_trace_project\n  {message : Type}\n  {X Y : VLSM message}\n  {label_project : vlabel X -> option (vlabel Y)}\n  {state_project : vstate X -> vstate Y}\n  (Hsimul : VLSM_projection X Y label_project state_project)\n  (s : Streams.Stream (vtransition_item X))\n  (Hfin : FinitelyManyBound (VLSM_projection_in Hsimul) s)\n  : list (vtransition_item Y)\n  := pre_VLSM_projection_infinite_finite_trace_project _ _ label_project state_project s Hfin.\n\nContext\n  {message : Type}\n  {X Y : VLSM message}\n  {label_project : vlabel X -> option (vlabel Y)}\n  {state_project : vstate X -> vstate Y}\n  (Hsimul : VLSM_projection X Y label_project state_project)\n  .\n\nDefinition VLSM_projection_finite_trace_project_app\n  : forall l1 l2, VLSM_projection_finite_trace_project Hsimul (l1 ++ l2) =\n    VLSM_projection_finite_trace_project Hsimul l1 ++ VLSM_projection_finite_trace_project Hsimul l2\n  := pre_VLSM_projection_finite_trace_project_app _ _ label_project state_project.\n\nDefinition VLSM_projection_finite_trace_project_app_rev\n  : forall l l1' l2', VLSM_projection_finite_trace_project Hsimul l = l1' ++ l2' ->\n    exists l1 l2,\n      l = l1 ++ l2 /\\\n      VLSM_projection_finite_trace_project Hsimul l1 = l1' /\\\n      VLSM_projection_finite_trace_project Hsimul l2 = l2'\n  := pre_VLSM_projection_finite_trace_project_app_rev _ _ label_project state_project.\n\nDefinition VLSM_projection_finite_trace_project_in\n  : forall itemX itemY,\n      pre_VLSM_projection_transition_item_project\n        _ _ label_project state_project itemX = Some itemY ->\n    forall trX,\n      In itemX trX -> In itemY (VLSM_projection_finite_trace_project Hsimul trX)\n  := pre_VLSM_projection_finite_trace_project_in _ _ label_project state_project.\n\nDefinition VLSM_projection_finite_trace_last\n  : forall sX trX,\n      finite_valid_trace_from X sX trX ->\n      state_project (finite_trace_last sX trX) = finite_trace_last (state_project sX)\n        (VLSM_projection_finite_trace_project Hsimul trX)\n  := final_state_project _ _ _ _ Hsimul.\n\nDefinition VLSM_projection_finite_valid_trace\n  : forall sX trX,\n      finite_valid_trace X sX trX -> finite_valid_trace Y (state_project sX)\n        (VLSM_projection_finite_trace_project Hsimul trX)\n  := trace_project_preserves_valid_trace _ _ _ _ Hsimul.\n\n(**\n  Any [VLSM_projection] determines a [VLSM_partial_projection], allowing us\n  to lift to VLSM projection the generic results proved about VLSM partial projections.\n*)\nLemma VLSM_partial_projection_from_projection :\n  VLSM_partial_projection X Y\n    (VLSM_partial_trace_project_from_projection label_project state_project).\nProof.\n  split.\n  - by apply VLSM_partial_projection_type_from_projection, Hsimul.\n  - cbn; intros sX trX sY trY [= <- <-].\n    by apply VLSM_projection_finite_valid_trace.\nQed.\n\nLemma VLSM_projection_finite_valid_trace_from\n  : forall sX trX,\n      finite_valid_trace_from X sX trX ->\n      finite_valid_trace_from Y (state_project sX) (VLSM_projection_finite_trace_project Hsimul trX).\nProof.\n  specialize VLSM_partial_projection_from_projection as Hpart_simul.\n  specialize (VLSM_partial_projection_finite_valid_trace_from Hpart_simul) as Hivt.\n  by intros sX trX; apply Hivt.\nQed.\n\nDefinition VLSM_projection_weaken : VLSM_weak_projection X Y label_project state_project :=\n  {| weak_projection_type := projection_type _ _ _ _ Hsimul\n  ;  weak_trace_project_preserves_valid_trace := VLSM_projection_finite_valid_trace_from\n  |}.\n\nDefinition VLSM_projection_valid_state\n  : forall sX,\n    valid_state_prop X sX -> valid_state_prop Y (state_project sX)\n  := VLSM_weak_projection_valid_state VLSM_projection_weaken.\n\nDefinition VLSM_projection_input_valid_transition\n  : forall lX lY, label_project lX = Some lY ->\n    forall s im s' om,\n    input_valid_transition X lX (s, im) (s', om) ->\n    input_valid_transition Y lY (state_project s, im) (state_project s', om)\n  := VLSM_weak_projection_input_valid_transition VLSM_projection_weaken.\n\nDefinition VLSM_projection_input_valid\n  := VLSM_weak_projection_input_valid VLSM_projection_weaken.\n\nDefinition VLSM_projection_finite_valid_trace_from_to\n  : forall sX s'X trX,\n      finite_valid_trace_from_to X sX s'X trX ->\n      finite_valid_trace_from_to Y (state_project sX) (state_project s'X)\n        (VLSM_projection_finite_trace_project Hsimul trX)\n  := VLSM_weak_projection_finite_valid_trace_from_to VLSM_projection_weaken.\n\nDefinition VLSM_projection_in_futures\n  : forall s1 s2,\n    in_futures X s1 s2 -> in_futures Y (state_project s1) (state_project s2)\n  := VLSM_weak_projection_in_futures VLSM_projection_weaken.\n\nDefinition VLSM_projection_infinite_valid_trace_from\n  : forall sX trX (Hinf : InfinitelyOften (VLSM_projection_in Hsimul) trX),\n    infinite_valid_trace_from X sX trX ->\n    infinite_valid_trace_from Y (state_project sX)\n      (VLSM_projection_infinite_trace_project Hsimul trX Hinf)\n    := VLSM_weak_projection_infinite_valid_trace_from VLSM_projection_weaken.\n\nDefinition VLSM_projection_infinite_finite_valid_trace_from\n  : forall sX trX (Hfin : FinitelyManyBound (VLSM_projection_in Hsimul) trX),\n    infinite_valid_trace_from X sX trX ->\n    finite_valid_trace_from Y (state_project sX)\n      (VLSM_projection_infinite_finite_trace_project Hsimul trX Hfin)\n    := VLSM_weak_projection_infinite_finite_valid_trace_from VLSM_projection_weaken.\n\nLemma VLSM_projection_initial_state\n  : forall sX, vinitial_state_prop X sX -> vinitial_state_prop Y (state_project sX).\nProof.\n  specialize VLSM_partial_projection_from_projection as Hpart_simul.\n  specialize (VLSM_partial_projection_initial_state Hpart_simul) as His.\n  by intro sX; eapply His.\nQed.\n\nLemma VLSM_projection_finite_valid_trace_init_to\n  : forall sX s'X trX,\n      finite_valid_trace_init_to X sX s'X trX ->\n      finite_valid_trace_init_to Y (state_project sX) (state_project s'X)\n        (VLSM_projection_finite_trace_project Hsimul trX).\nProof.\n  intros. destruct H as [H Hinit]. split.\n  - by apply VLSM_projection_finite_valid_trace_from_to.\n  - by apply VLSM_projection_initial_state.\nQed.\n\nLemma VLSM_projection_infinite_valid_trace\n  : forall sX trX (Hinf : InfinitelyOften (VLSM_projection_in Hsimul) trX),\n    infinite_valid_trace X sX trX ->\n    infinite_valid_trace Y (state_project sX)\n      (VLSM_projection_infinite_trace_project Hsimul trX Hinf).\nProof.\n  intros sX trX Hinf [HtrX HsX].\n  split.\n  - by apply VLSM_projection_infinite_valid_trace_from.\n  - by apply VLSM_projection_initial_state.\nQed.\n\nLemma VLSM_projection_infinite_finite_valid_trace\n  : forall sX trX (Hfin : FinitelyManyBound (VLSM_projection_in Hsimul) trX),\n    infinite_valid_trace X sX trX ->\n    finite_valid_trace Y (state_project sX)\n      (VLSM_projection_infinite_finite_trace_project Hsimul trX Hfin).\nProof.\n  intros sX trX Hfin [HtrX HsX].\n  split.\n  - by apply VLSM_projection_infinite_finite_valid_trace_from.\n  - by apply VLSM_projection_initial_state.\nQed.\n\n(** ** Projection friendliness\n\n  A projection is friendly if all the valid traces of the projection are\n  projections of the valid traces of the source VLSM.\n*)\n\nSection sec_projection_friendliness.\n\n(**\n  We axiomatize projection friendliness as the converse of\n  [VLSM_projection_finite_valid_trace]\n*)\nDefinition projection_friendly_prop\n  := forall\n    (sY : vstate Y)\n    (trY : list (vtransition_item Y))\n    (HtrY : finite_valid_trace Y sY trY),\n    exists (sX : vstate X) (trX : list (vtransition_item X)),\n      finite_valid_trace X sX trX\n      /\\ state_project sX = sY\n      /\\ VLSM_projection_finite_trace_project Hsimul trX = trY.\n\nLemma projection_friendly_in_futures\n  (Hfr : projection_friendly_prop)\n  (s1 s2 : vstate Y)\n  (Hfuture : in_futures Y s1 s2)\n  : exists (sX1 sX2 : vstate X),\n    state_project sX1 = s1 /\\ state_project sX2 = s2 /\\ in_futures X sX1 sX2.\nProof.\n  destruct Hfuture as [tr_s2 Hfuture].\n  apply finite_valid_trace_from_to_complete_left in Hfuture\n    as [is [tr_s1 [Htr Heq_s1]]].\n  apply valid_trace_get_last in Htr as Heq_s2.\n  apply valid_trace_forget_last in Htr.\n  apply Hfr in Htr as [isX [trX [Htr [His Htr_pr]]]].\n  apply VLSM_projection_finite_trace_project_app_rev in Htr_pr\n    as (trX_s1 & trX_s2 & HeqtrX & Htr_s1_pr & Htr_s2_pr).\n  subst.\n  destruct Htr as [HtrX HisX].\n  apply finite_valid_trace_from_app_iff in HtrX as HtrX12.\n  destruct HtrX12 as [HtrX1 HtrX2].\n  apply valid_trace_add_default_last in HtrX2.\n  exists (finite_trace_last isX trX_s1).\n  exists (finite_trace_last isX  (trX_s1 ++ trX_s2)).\n  rewrite !VLSM_projection_finite_trace_last,\n    VLSM_projection_finite_trace_project_app; [| done | done].\n  repeat split.\n  by rewrite finite_trace_last_app; eexists.\nQed.\n\n(**\n  A consequence of the [projection_friendly_prop]erty is that the valid\n  traces of the projection are precisely the projections of all the valid traces\n  of the source VLSM.\n*)\nLemma projection_friendly_trace_char\n  (Hfriendly : projection_friendly_prop)\n  : forall sY trY, finite_valid_trace Y sY trY <->\n    exists (sX : vstate X) (trX : list (vtransition_item X)),\n      finite_valid_trace X sX trX\n      /\\ state_project sX = sY\n      /\\ VLSM_projection_finite_trace_project Hsimul trX = trY.\nProof.\n  split; [by apply Hfriendly |].\n  intros [sX [trX [HtrX [<- <-]]]].\n  by apply VLSM_projection_finite_valid_trace.\nQed.\n\nEnd sec_projection_friendliness.\n\nEnd sec_projection_properties.\n\nEnd sec_VLSM_projection.\n\n(**\n  For VLSM <<X>> to project to a VLSM <<Y>>, the following set of conditions is sufficient:\n  - <<X>>'s [initial_state]s project to <<Y>>'s [initial state]s\n  - Every message <<m>> (including the empty one) which can be input to a\n    projectable [input_valid] transition in <<X>>, is a [valid_message]\n    in <<Y>>\n  - <<X>>'s [input_valid] is included in <<Y>>'s [valid].\n  - For all projectable [input_valid] inputs (in <<X>>), <<Y>>'s [transition]\n    acts like <<X>>'s [transition].\n  - All non-projectable transitions preserve the projected state\n*)\n\nSection sec_basic_VLSM_projection.\n\nSection sec_basic_VLSM_projection_type.\n\nContext\n  {message : Type}\n  (X : VLSM message)\n  (TY : VLSMType message)\n  (label_project : vlabel X -> option (@label _ TY))\n  (state_project : vstate X -> @state _ TY)\n  (Htransition_None : weak_projection_transition_consistency_None X TY label_project state_project)\n  .\n\nLemma basic_VLSM_projection_type\n  : VLSM_projection_type X TY label_project state_project.\nProof.\n  constructor.\n  intros is tr Htr.\n  induction Htr using finite_valid_trace_from_rev_ind\n  ; [done |].\n  rewrite (pre_VLSM_projection_finite_trace_project_app _ _ label_project state_project).\n  rewrite finite_trace_last_is_last.\n  rewrite finite_trace_last_app, <- IHHtr.\n  clear IHHtr.\n  simpl.\n  unfold pre_VLSM_projection_transition_item_project.\n  destruct (label_project _) as [lY |] eqn: Hl; [done |].\n  apply (Htransition_None _ Hl) in Hx.\n  by rewrite Hx.\nQed.\n\nEnd sec_basic_VLSM_projection_type.\n\nContext\n  {message : Type}\n  (X Y : VLSM message)\n  (label_project : vlabel X -> option (vlabel Y))\n  (state_project : vstate X -> vstate Y)\n  .\n\nContext\n  (Hvalid : weak_projection_valid_preservation X Y label_project state_project)\n  (Htransition_Some : weak_projection_transition_preservation_Some X Y label_project state_project)\n  (Htransition_None : weak_projection_transition_consistency_None _ _ label_project state_project)\n  (Htype : VLSM_projection_type X (type Y) label_project state_project :=\n    basic_VLSM_projection_type X (type Y) label_project state_project Htransition_None)\n  .\n\nSection sec_weak_projection.\n\nContext\n  (Hstate : weak_projection_initial_state_preservation X Y state_project)\n  (Hmessage : weak_projection_valid_message_preservation X Y label_project state_project)\n  .\n\n#[local] Lemma basic_VLSM_projection_finite_valid_trace_init_to\n  is s tr\n  (Htr : finite_valid_trace_init_to X is s tr)\n  : finite_valid_trace_from_to Y (state_project is) (state_project s)\n      (pre_VLSM_projection_finite_trace_project _ _ label_project state_project tr).\nProof.\n  induction Htr using finite_valid_trace_init_to_rev_strong_ind; [by constructor; apply Hstate |].\n  unfold pre_VLSM_projection_finite_trace_project.\n  rewrite map_option_app.\n  apply finite_valid_trace_from_to_app with (state_project s)\n  ; [done |].\n  simpl. unfold pre_VLSM_projection_transition_item_project.\n  simpl.\n  apply valid_trace_last_pstate in IHHtr1.\n  destruct (label_project l) as [lY |] eqn: Hl; cycle 1.\n  - by apply (Htransition_None _ Hl) in Ht; rewrite Ht; constructor.\n  - apply finite_valid_trace_from_to_singleton.\n    assert (Hiom : option_valid_message_prop Y iom).\n    {\n      destruct iom as [im |]; [| by apply option_valid_message_None].\n      by apply (Hmessage _ _ Hl _ _ (proj1 Ht)).\n    }\n    specialize (Hvalid _ _ Hl _ _ (proj1 Ht) IHHtr1 Hiom).\n    by apply (Htransition_Some _ _ Hl) in Ht.\nQed.\n\n#[local] Lemma basic_VLSM_projection_finite_valid_trace_from\n  (s : state)\n  (ls : list transition_item)\n  (Hpxt : finite_valid_trace_from X s ls)\n  : finite_valid_trace_from Y (state_project s)\n      (pre_VLSM_projection_finite_trace_project _ _ label_project state_project ls).\nProof.\n  apply valid_trace_add_default_last in Hpxt.\n  apply valid_trace_first_pstate in Hpxt as Hs.\n  apply valid_state_has_trace in Hs as [is_s [tr_s Hs]].\n  specialize (finite_valid_trace_from_to_app X _ _ _ _ _ (proj1 Hs) Hpxt) as Happ.\n  specialize (basic_VLSM_projection_finite_valid_trace_init_to _ _ _ (conj Happ (proj2 Hs)))\n    as Happ_pr.\n  rewrite (pre_VLSM_projection_finite_trace_project_app _ _ label_project state_project) in Happ_pr.\n  apply finite_valid_trace_from_to_app_split, proj2 in Happ_pr.\n  apply valid_trace_get_last in Hs as Heqs.\n  apply valid_trace_forget_last, proj1 in Hs.\n  rewrite <- (final_state_project X (type Y) label_project state_project Htype)\n    in Happ_pr by done.\n  by apply valid_trace_forget_last in Happ_pr; subst.\nQed.\n\nLemma basic_VLSM_weak_projection\n  : VLSM_weak_projection X Y label_project state_project.\nProof.\n  constructor; [done |].\n  apply basic_VLSM_projection_finite_valid_trace_from.\nQed.\n\nEnd sec_weak_projection.\n\nLemma basic_VLSM_weak_projection_strengthen\n  (Hweak : VLSM_weak_projection X Y label_project state_project)\n  (Hstate : strong_projection_initial_state_preservation X Y state_project)\n  : VLSM_projection X Y label_project state_project.\nProof.\n  constructor; [by apply Hweak |].\n  intros sX trX [HtrX HsX]; split.\n  - by apply (VLSM_weak_projection_finite_valid_trace_from Hweak).\n  - by apply Hstate.\nQed.\n\nLemma basic_VLSM_projection\n  (Hstate : strong_projection_initial_state_preservation X Y state_project)\n  (Hmessage : weak_projection_valid_message_preservation X Y label_project state_project)\n  : VLSM_projection X Y label_project state_project.\nProof.\n  apply basic_VLSM_weak_projection_strengthen; [| done].\n  apply basic_VLSM_weak_projection; [| done].\n  by apply strong_projection_initial_state_preservation_weaken.\nQed.\n\nEnd sec_basic_VLSM_projection.\n\nLemma basic_VLSM_strong_projection\n  {message : Type}\n  (X Y : VLSM message)\n  (label_project : vlabel X -> option (vlabel Y))\n  (state_project : vstate X -> vstate Y)\n  (Hvalid : strong_projection_valid_preservation X Y label_project state_project)\n  (Htransition_Some : strong_projection_transition_preservation_Some X Y label_project state_project)\n  (Htransition_None : strong_projection_transition_consistency_None _ _ label_project state_project)\n  (Hstate : strong_projection_initial_state_preservation X Y state_project)\n  (Hmessage : strong_projection_valid_message_preservation X Y)\n  : VLSM_projection X Y label_project state_project.\nProof.\n  apply basic_VLSM_projection.\n  - by apply strong_projection_valid_preservation_weaken.\n  - by apply strong_projection_transition_preservation_Some_weaken.\n  - by apply strong_projection_transition_consistency_None_weaken.\n  - done.\n  - by apply strong_projection_valid_message_preservation_weaken.\nQed.\n\nLemma basic_VLSM_projection_type_preloaded\n  {message : Type}\n  (X Y : VLSM message)\n  (label_project : vlabel X -> option (vlabel Y))\n  (state_project : vstate X -> vstate Y)\n  (Htransition_None : strong_projection_transition_consistency_None _ _ label_project state_project)\n  : VLSM_projection_type (pre_loaded_with_all_messages_vlsm X) (type Y) label_project state_project.\nProof.\n  constructor.\n  intros is tr Htr.\n  induction Htr using finite_valid_trace_from_rev_ind\n  ; [done |].\n  rewrite (@pre_VLSM_projection_finite_trace_project_app _\n    (type (pre_loaded_with_all_messages_vlsm X)) (type Y) label_project state_project).\n  rewrite finite_trace_last_is_last.\n  rewrite finite_trace_last_app, <- IHHtr.\n  clear IHHtr.\n  simpl.\n  unfold pre_VLSM_projection_transition_item_project.\n  destruct (label_project _) as [lY |] eqn: Hl; [done |].\n  apply proj2, (Htransition_None _ Hl) in Hx.\n  by rewrite Hx.\nQed.\n\nLemma basic_VLSM_projection_preloaded\n  {message : Type}\n  (X Y : VLSM message)\n  (label_project : vlabel X -> option (vlabel Y))\n  (state_project : vstate X -> vstate Y)\n  (Hvalid : strong_projection_valid_preservation X Y label_project state_project)\n  (Htransition_Some : strong_projection_transition_preservation_Some X Y label_project state_project)\n  (Htransition_None : strong_projection_transition_consistency_None _ _ label_project state_project)\n  (Hstate : strong_projection_initial_state_preservation X Y state_project)\n  : VLSM_projection\n      (pre_loaded_with_all_messages_vlsm X)\n      (pre_loaded_with_all_messages_vlsm Y) label_project state_project.\nProof.\n  specialize (basic_VLSM_projection_type_preloaded X Y label_project state_project Htransition_None)\n    as Htype.\n  constructor; [done |].\n  intros sX trX HtrX.\n  split; [| by apply Hstate; apply HtrX].\n  induction HtrX using finite_valid_trace_rev_ind.\n  - by constructor; apply initial_state_is_valid, Hstate.\n  - rewrite (@pre_VLSM_projection_finite_trace_project_app _\n      (type (pre_loaded_with_all_messages_vlsm X)) (type Y) label_project state_project).\n    apply (finite_valid_trace_from_app_iff (pre_loaded_with_all_messages_vlsm Y)).\n    split; [done |].\n    simpl. unfold pre_VLSM_projection_transition_item_project.\n    simpl.\n    apply finite_valid_trace_last_pstate in IHHtrX.\n    destruct Hx as [[_ [_ Hv]] Ht].\n    rewrite <- (final_state_project _ _ _ _ Htype) in IHHtrX |- * by apply HtrX.\n    destruct (label_project l) as [lY |] eqn: Hl.\n    + apply (finite_valid_trace_singleton (pre_loaded_with_all_messages_vlsm Y)).\n      assert (Hiom : option_valid_message_prop (pre_loaded_with_all_messages_vlsm Y) iom).\n      {\n        destruct iom as [im |]; [| by apply option_valid_message_None].\n        by apply (any_message_is_valid_in_preloaded Y).\n      }\n      apply (Hvalid _ _ Hl) in Hv.\n      by apply (Htransition_Some _ _ Hl) in Ht.\n    + by apply (finite_valid_trace_from_empty (pre_loaded_with_all_messages_vlsm Y)).\nQed.\n\nLemma basic_VLSM_projection_type_preloaded_with\n  {message : Type}\n  (X Y : VLSM message)\n  (P Q : message -> Prop)\n  (label_project : vlabel X -> option (vlabel Y))\n  (state_project : vstate X -> vstate Y)\n  (Htransition_None : strong_projection_transition_consistency_None _ _ label_project state_project)\n  : VLSM_projection_type (pre_loaded_vlsm X P) (type Y) label_project state_project.\nProof.\n  constructor.\n  intros is tr Htr.\n  induction Htr using finite_valid_trace_from_rev_ind\n  ; [done |].\n  rewrite (@pre_VLSM_projection_finite_trace_project_app\n    _ (type (pre_loaded_vlsm X P)) (type Y) label_project state_project).\n  rewrite finite_trace_last_is_last.\n  rewrite finite_trace_last_app, <- IHHtr.\n  clear IHHtr.\n  simpl.\n  unfold pre_VLSM_projection_transition_item_project.\n  destruct (label_project _) as [lY |] eqn: Hl; [done |].\n  apply proj2, (Htransition_None _ Hl) in Hx.\n  by rewrite Hx.\nQed.\n\nLemma basic_VLSM_projection_preloaded_with\n  {message : Type}\n  (X Y : VLSM message)\n  (P Q : message -> Prop)\n  (label_project : vlabel X -> option (vlabel Y))\n  (state_project : vstate X -> vstate Y)\n  (Hvalid : strong_projection_valid_preservation X Y label_project state_project)\n  (Htransition_Some : strong_projection_transition_preservation_Some X Y label_project state_project)\n  (Htransition_None : strong_projection_transition_consistency_None _ _ label_project state_project)\n  (Hstate : strong_projection_initial_state_preservation X Y state_project)\n  (Hmessage : weak_projection_valid_message_preservation\n                (pre_loaded_vlsm X P) (pre_loaded_vlsm Y Q) label_project state_project)\n  : VLSM_projection (pre_loaded_vlsm X P) (pre_loaded_vlsm Y Q) label_project state_project.\nProof.\n  specialize (basic_VLSM_projection_type_preloaded_with X Y P Q\n    label_project state_project Htransition_None) as Htype.\n  constructor; [done |].\n  intros sX trX HtrX.\n  split; [| by apply Hstate; apply HtrX].\n  induction HtrX using finite_valid_trace_rev_ind.\n  - by constructor; apply initial_state_is_valid, Hstate.\n  - rewrite (@pre_VLSM_projection_finite_trace_project_app _\n      (type (pre_loaded_vlsm X P)) (type Y) label_project state_project).\n    apply (finite_valid_trace_from_app_iff (pre_loaded_vlsm Y Q)).\n    split; [done |].\n    simpl. unfold pre_VLSM_projection_transition_item_project.\n    simpl.\n    apply finite_valid_trace_last_pstate in IHHtrX.\n    apply proj1 in Hx as Hpv.\n    destruct Hx as [[_ [_ Hv]] Ht].\n    rewrite <- (final_state_project _ _ _ _ Htype) in IHHtrX |- * by apply HtrX.\n    destruct (label_project l) as [lY |] eqn: Hl.\n    + apply (finite_valid_trace_singleton (pre_loaded_vlsm Y Q)).\n      assert (Hiom : option_valid_message_prop (pre_loaded_vlsm Y Q) iom).\n      { destruct iom as [im |]; [| by apply option_valid_message_None].\n        by apply (Hmessage _ _ Hl) in Hpv.\n      }\n      apply (Hvalid _ _ Hl) in Hv.\n      by apply (Htransition_Some _ _ Hl) in Ht.\n    + by apply (finite_valid_trace_from_empty (pre_loaded_vlsm Y Q)).\nQed.\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/VLSMProjections/VLSMTotalProjection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.29551396750527564}}
{"text": "From Categories Require Import Category.Main.\nFrom Categories Require Import Coq_Cats.Coq_Cat.\n\n(** The category of Types (Coq's \"Type\")*)\n\nProgram Definition Type_Cat : Category := Coq_Cat Type.\n", "meta": {"author": "amintimany", "repo": "Categories", "sha": "1839108875df0107fa4f6061c654003decda2d49", "save_path": "github-repos/coq/amintimany-Categories", "path": "github-repos/coq/amintimany-Categories/Categories-1839108875df0107fa4f6061c654003decda2d49/Coq_Cats/Type_Cat/Type_Cat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2955139675052756}}
{"text": "(*\n * Copyright 2015-2016 IBM Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *)\n\n(** This module provides support for bindings, which are association\nlists for which the keys are ordered and without duplicates.\n\nBindings are used as a representation for records and environments. *)\n\n\nRequire Import List.\nRequire Import Sumbool.\nRequire Import Arith.\nRequire Import Bool.\nRequire Import Permutation.\nRequire Import Equivalence.\nRequire Import EquivDec.\nRequire Import RelationClasses.\nRequire Import Orders.\nRequire Import Permutation.\nRequire Import LibUtilsCoqLibAdd.\nRequire Import LibUtilsListAdd.\nRequire Import LibUtilsSortingAdd.\nRequire Import LibUtilsAssoc.\nRequire Import LibUtilsSublist.\nRequire Import LibUtilsCompat.\nRequire Import String.\nRequire Import LibUtilsStringAdd.\n\nSection Bindings.\n\n  Class ODT {K:Type}\n    := mkODT { ODT_eqdec:>EqDec K eq;\n               ODT_lt:K -> K -> Prop;\n               ODT_lt_strorder:>StrictOrder ODT_lt;\n               ODT_lt_dec: forall (a b:K), {ODT_lt a b} + {~ODT_lt a b};\n               ODT_compare:K -> K -> comparison;\n               ODT_compare_spec: forall x y : K,\n                   CompareSpec (eq x y) (ODT_lt x y) (ODT_lt y x) (ODT_compare x y) }.\n\n  Generalizable Variables K.\n  Context `{odt:@ODT K}.\n\n  Lemma ODT_lt_irr (k:K) :\n    ~(ODT_lt k k).\n  Proof.\n    apply irreflexivity.\n  Qed.\n\n  Ltac dest_strlt :=\n    match goal with\n    | [|- context [ODT_lt_dec ?x ?y]] => destruct (ODT_lt_dec x y); simpl\n    | [H:ODT_lt ?x ?x|- _] => (assert False by (apply (ODT_lt_irr x); auto); contradiction)\n    end.\n\n  (* trichotemy *)\n  Lemma trichotemy a b : {ODT_lt a b} + {eq a b} + {ODT_lt b a}.\n  Proof.\n    generalize (ODT_compare_spec a b); intros nc.\n    destruct (ODT_compare a b); [left; right|left;left|right]; inversion nc; trivial.\n  Defined.\n\n  Lemma compare_refl_eq a: ODT_compare a a = Eq.\n  Proof.\n    destruct (ODT_compare_spec a a);[reflexivity|dest_strlt|dest_strlt].\n  Qed.\n\n  Lemma compare_eq_iff x y : (ODT_compare x y) = Eq <-> x=y.\n  Proof.\n    case ODT_compare_spec; intro H; split; try easy; intro EQ;\n      contradict H;rewrite EQ; apply irreflexivity.\n  Qed.\n  \n  Lemma ODT_lt_contr (x y : K) : ~ ODT_lt x y -> ~ ODT_lt y x -> x = y.\n  Proof.\n    destruct (trichotemy x y) as [[?|?]|?]; intuition.\n  Qed.\n  \n  (* Starting here ... *)\n\n  Definition rec_field_lt {A} (a b:K*A) :=\n    ODT_lt (fst a) (fst b).\n\n  Global Instance rec_field_lt_strict {A} : StrictOrder (@rec_field_lt A).\n  Proof.\n    unfold rec_field_lt.\n    inversion odt.\n    constructor.\n    + unfold Irreflexive, Reflexive, complement in *; intros.\n      destruct x; simpl in odt.\n      apply (StrictOrder_Irreflexive k H).\n    + unfold Transitive in *; intros.\n      destruct x; destruct y; destruct z; simpl in *.\n      apply (StrictOrder_Transitive k k0 k1 H H0).\n  Qed.\n\n  Lemma rec_field_lt_dec {A} (a b:K*A) :\n    {rec_field_lt a b} + {~rec_field_lt a b}.\n  Proof.\n    destruct a.\n    destruct b.\n    unfold rec_field_lt; simpl.\n    apply ODT_lt_dec.\n  Defined.\n\n  Lemma rec_field_lt_irr {A} (a:K*A) :\n    ~(rec_field_lt a a).\n  Proof.\n    apply StrictOrder_Irreflexive.\n  Qed.\n\n  Lemma Forall_rec_field_lt {A} (a:K*A) l :\n    Forall (rec_field_lt a) l <-> Forall (ODT_lt (fst a)) (domain l).\n  Proof.\n    destruct a; simpl.\n    induction l; simpl.\n    - intuition.\n    - destruct IHl as [H1 H2].\n      split; inversion 1; subst; constructor; eauto.\n  Qed.\n  \n  Definition rec_cons_sort {A} :=\n    @insertion_sort_insert (K*A) rec_field_lt rec_field_lt_dec.\n\n  Definition rec_sort {A} :=\n    @insertion_sort (K*A) rec_field_lt rec_field_lt_dec.\n\n  Definition rec_concat_sort {A} (l1 l2:list (K*A)) : (list (K*A)) :=\n    rec_sort (l1++l2).\n\n  (* Lifted from LibUtilsSortingAdd *)\n  \n  Lemma sorted_rec_nil {A} :\n    is_list_sorted ODT_lt_dec (@domain K A nil) = true.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Lemma sort_rec_single_type {A} (k:K) (a:A):\n    is_list_sorted ODT_lt_dec (domain ((k,a)::nil)) = true.\n  Proof.\n    reflexivity.\n  Defined.\n\n  Lemma field_less_is_neq (a1 a2:K) :\n    ODT_lt a1 a2 -> a1 <> a2.\n  Proof.\n    unfold not; intros.\n    subst; dest_strlt.\n  Qed.\n  \n  Lemma field_less_is_not_more (a1 a2:K) :\n    ODT_lt a1 a2 -> ~(ODT_lt a2 a1).\n  Proof.\n    elim ODT_lt_strorder; intros.\n    unfold Transitive, Irreflexive, Reflexive, complement in *.\n    unfold not; intros.\n    specialize (StrictOrder_Transitive a1 a2 a1 H H0).\n    specialize (StrictOrder_Irreflexive a1 StrictOrder_Transitive).\n    assumption.\n  Qed.\n\n  Lemma field_not_less_and_neq_is_more (a1 a2:K) :\n    ~(ODT_lt a1 a2) -> ~(eq a1 a2) -> ODT_lt a2 a1.\n  Proof.\n    unfold not; intros.\n    generalize (ODT_compare_spec a1 a2).\n    intros.\n    inversion H1.\n    congruence.\n    assert False.\n    apply H.\n    assumption.\n    contradiction.\n    assumption.\n  Qed.\n\n  Lemma rec_cons_lt {A} (l1:list (K*A)) (a1 a2:K*A) :\n    is_list_sorted ODT_lt_dec (domain (a2 :: l1)) = true ->\n    ODT_lt (fst a1) (fst a2) ->\n    is_list_sorted ODT_lt_dec (domain (a1 :: a2 :: l1)) = true.\n  Proof.\n    simpl; intros.\n    revert H0; elim (ODT_lt_dec (fst a1) (fst a2)); intros.\n    assumption.\n    contradiction.\n  Qed.\n\n  Lemma rec_sorted_skip_first {A} (l1:list (K*A)) (a:K*A) :\n    is_list_sorted ODT_lt_dec (domain (a :: l1)) = true ->\n    is_list_sorted ODT_lt_dec (domain l1) = true.\n  Proof.\n    simpl.\n    intros.\n    revert H; elim (domain l1); intros.\n    reflexivity.\n    destruct (ODT_lt_dec (fst a) a0); congruence.\n  Qed.    \n\n  Lemma rec_sorted_skip_second {A} (l:list (K*A)) (a1 a2:K*A) :\n    is_list_sorted ODT_lt_dec (domain (a1 :: a2 :: l)) = true ->\n    is_list_sorted ODT_lt_dec (domain (a1 :: l)) = true.\n  Proof.\n    intros; simpl in *.\n    revert H; destruct l; try reflexivity; simpl.\n    elim (ODT_lt_dec (fst a1) (fst a2));\n      elim (ODT_lt_dec (fst a2) (fst p));\n      elim (ODT_lt_dec (fst a1) (fst p));\n      intros; try congruence.\n    assert (ODT_lt (fst a1) (fst p))\n      by (apply transitivity with (y := (fst a2)); assumption).\n    contradiction.\n  Qed.\n\n  Lemma rec_sorted_skip_third {A} (l:list (K*A)) (a1 a2 a3:K*A) :\n    is_list_sorted ODT_lt_dec (domain (a1 :: a2 :: a3 :: l)) = true ->\n    is_list_sorted ODT_lt_dec (domain (a1 :: a2 :: l)) = true.\n  Proof.\n    intros; simpl in *.\n    revert H; destruct l; simpl.\n    - simpl.\n      elim (ODT_lt_dec (fst a1) (fst a2));\n        elim (ODT_lt_dec (fst a2) (fst a3));\n        elim (ODT_lt_dec (fst a1) (fst a3)); intros; try congruence.\n    - elim (ODT_lt_dec (fst a1) (fst a2));\n        elim (ODT_lt_dec (fst a2) (fst a3));\n        elim (ODT_lt_dec (fst a3) (fst p));\n        elim (ODT_lt_dec (fst a2) (fst p));\n        intros; try congruence.\n      assert (ODT_lt (fst a2) (fst p))\n        by (apply transitivity with (y := (fst a3)); assumption).\n      contradiction.\n  Qed.\n\n  Lemma rec_sorted_distinct {A} (l:list (K*A)) (a1 a2:K*A) :\n    is_list_sorted ODT_lt_dec (domain (a1 :: a2 :: l)) = true ->\n    (fst a1) <> (fst a2).\n  Proof.\n    intros.\n    induction l.\n    simpl in *.\n    revert H.\n    elim (ODT_lt_dec (fst a1) (fst a2)); intros.\n    apply field_less_is_neq ; assumption.\n    congruence.\n    apply IHl; clear IHl.\n    apply (rec_sorted_skip_third l a1 a2 a); assumption.\n  Qed.\n\n  Lemma rec_sorted_lt {A} (l:list (K*A)) (a1 a2:K*A) :\n    is_list_sorted ODT_lt_dec (domain (a1 :: a2 :: l)) = true ->\n    ODT_lt (fst a1) (fst a2).\n  Proof.\n    simpl.\n    elim (ODT_lt_dec (fst a1) (fst a2)); intros.\n    assumption.\n    congruence.\n  Qed.\n\n  Lemma sorted_cons_in {A} (l:list (K*A)) (a a':K*A) :\n    is_list_sorted ODT_lt_dec (domain (a :: l)) = true ->\n    In a' l ->\n    ODT_lt (fst a) (fst a').\n  Proof.\n    intros.\n    induction l.\n    - simpl in H0; contradiction.\n    - simpl in H0.\n      elim H0; clear H0; intros.\n      + rewrite H0 in *; clear H0 a0.\n        simpl in H.\n        destruct (ODT_lt_dec (fst a) (fst a')); try congruence.\n      + assert (is_list_sorted ODT_lt_dec (domain (a :: l)) = true)\n          by (apply rec_sorted_skip_second with (a2 := a0); assumption).\n        apply (IHl H1 H0).\n  Qed.\n\n  (* Back here... *)\n\n  Lemma rec_cons_lt_first {A} (l1:list (K*A)) (a1 a2:K*A) :\n    is_list_sorted ODT_lt_dec (domain (a2 :: l1)) = true ->\n    ODT_lt (fst a1) (fst a2) ->\n    rec_cons_sort a1 (a2 :: l1) = (a1 :: a2 :: l1).\n  Proof.\n    simpl; intros.\n    elim (rec_field_lt_dec a1 a2); intros.\n    reflexivity.\n    unfold rec_field_lt in *.\n    congruence.\n  Qed.\n\n  Lemma sort_sorted_is_id {A} (l:list (K*A)) :\n    is_list_sorted ODT_lt_dec (domain l) = true ->\n    rec_sort l = l.\n  Proof.\n    induction l; intros; simpl in *.\n    reflexivity.\n    assert (is_list_sorted ODT_lt_dec (domain l) = true).\n    destruct l; simpl in *; try reflexivity.\n    destruct (ODT_lt_dec (fst a) (fst p)); congruence.\n    specialize (IHl H0).\n    rewrite IHl; clear IHl.\n    destruct l; simpl in *; try reflexivity.\n    revert H.\n    destruct (ODT_lt_dec (fst a) (fst p)); intros.\n    destruct (rec_field_lt_dec a p); intros.\n    reflexivity.\n    unfold rec_field_lt in n.\n    congruence.\n    congruence.\n  Qed.\n\n  Lemma rec_concat_sort_concats {A} (l1 l2:list (K*A)) :\n    rec_concat_sort l1 l2 = rec_sort (l1++l2).\n  Proof.\n    reflexivity.\n  Qed.\n\n  Lemma rec_cons_sorted_id {A} (l:list (K*A)) (a:K*A) :\n    is_list_sorted ODT_lt_dec (domain (a :: l)) = true ->\n    rec_cons_sort a l = a::l.\n  Proof.\n    intros.\n    destruct l.\n    reflexivity.\n    assert (ODT_lt (fst a) (fst p))\n      by (apply (rec_sorted_lt l a p); assumption).\n    apply (rec_cons_lt_first l a p).\n    apply (rec_sorted_skip_first (p::l) a); assumption.\n    assumption.\n  Qed.\n  \n  Lemma rec_sorted_id {A} (l:list (K*A)) :\n    is_list_sorted ODT_lt_dec (domain l) = true ->\n    rec_sort l = l.\n  Proof.\n    induction l.\n    reflexivity.\n    simpl; intros.\n    assert (is_list_sorted ODT_lt_dec (domain l) = true).\n    revert H.\n    destruct l; try reflexivity.\n    simpl.\n    destruct (ODT_lt_dec (fst a) (fst p)); congruence.\n    specialize (IHl H0); clear H0.\n    rewrite IHl.\n    simpl.\n    assert (is_list_sorted ODT_lt_dec (domain (a :: l)) = true).\n    unfold is_list_sorted.\n    simpl.\n    revert H.\n    destruct l; try reflexivity.\n    intros.\n    simpl in *; revert H.\n    destruct (ODT_lt_dec (fst a) (fst p)); intros.\n    - revert H; destruct (domain l); try reflexivity.\n      destruct (ODT_lt_dec (fst p) k); try congruence.\n      intros.\n      simpl in H.\n      assumption.\n    - congruence.\n    - generalize (rec_cons_sorted_id l a H0); intros.\n      unfold rec_cons_sort in H1.\n      assumption.\n  Qed.\n\n  Lemma rec_cons_gt_first {A} (l' l:list (K*A)) (a1 a2:K*A) :\n    rec_cons_sort a1 l = l' ->\n    is_list_sorted ODT_lt_dec (domain (a2 :: l)) = true ->\n    ODT_lt (fst a2) (fst a1) ->\n    (exists a3, exists l'', rec_cons_sort a1 l = (a3 :: l'')\n                            /\\ ODT_lt (fst a2) (fst a3)).\n  Proof.\n    revert a1 a2 l'.\n    induction l; intros.\n    - simpl in *; intros; exists a1, nil; split; [reflexivity|assumption].\n    - simpl in *.\n      revert H; elim (rec_field_lt_dec a1 a); intros.\n      inversion H.\n      exists a1,(a::l).\n      split; [reflexivity|assumption].\n      revert H; elim (rec_field_lt_dec a a1); intros.\n      destruct l'; try congruence.\n      rewrite H in *.\n      exists p,l'.\n      + split; try reflexivity.\n        inversion H.\n        rewrite <- H3 in *; clear H3.\n        revert H0.\n        elim (ODT_lt_dec (fst a2) (fst a)); intros.\n        assumption.\n        congruence.\n      + exists a,l.\n        split. reflexivity.\n        revert H0.\n        elim (ODT_lt_dec (fst a2) (fst a)); intros.\n        assumption.\n        congruence.\n  Qed.\n\n  Lemma rec_cons_sorted {A} (l1 l2:list (K*A)) (a:K*A) :\n    is_list_sorted ODT_lt_dec (domain l1) = true ->\n    rec_cons_sort a l1 = l2 ->\n    is_list_sorted ODT_lt_dec (domain l2) = true.\n  Proof.\n    revert l2 a.\n    induction l1; intros.\n    simpl in *; rewrite <- H0; reflexivity.\n    simpl in *.\n    assert (is_list_sorted ODT_lt_dec (domain (a::l1)) = true)\n      by assumption.\n    revert H0.\n    elim (rec_field_lt_dec a0 a); intros.\n    rewrite <- H0.\n    apply rec_cons_lt; assumption.\n    rewrite <- H0.\n    destruct (rec_field_lt_dec a a0); intros. clear b.\n    - assert (exists a3, exists l'', rec_cons_sort a0 l1 = (a3 :: l'')\n                                     /\\ ODT_lt (fst a) (fst a3)).\n      apply (rec_cons_gt_first (rec_cons_sort a0 l1) l1).\n      reflexivity.\n      assumption.\n      assumption.\n      elim H2; clear H2; intros.\n      elim H2; clear H2; intros.\n      elim H2; clear H2; intros.\n      destruct l2; try congruence.\n      inversion H0.\n      rewrite <- H5 in *; clear H5.\n      specialize (IHl1 l2 a0).\n      assert (is_list_sorted ODT_lt_dec (domain l1) = true).\n      apply (rec_sorted_skip_first l1 a); assumption.\n      specialize (IHl1 H4 H6).\n      rewrite H2 in *.\n      rewrite <- H6 in *.\n      apply rec_cons_lt; assumption.\n    - assumption.\n  Qed.\n\n  Lemma rec_sort_sorted {A} (l1 l2:list (K*A)) :\n    rec_sort l1 = l2 -> is_list_sorted ODT_lt_dec (domain l2) = true.\n  Proof.\n    revert l2.\n    induction l1; intros.\n    simpl; inversion H; reflexivity.\n    simpl in *.\n    assert (exists l'', rec_sort l1 = l'').\n    revert H.\n    elim (rec_sort l1); intros.\n    exists nil; reflexivity.\n    exists (a0::l); reflexivity.\n    elim H0; intros; clear H0.\n    rewrite H1 in H.\n    assert (is_list_sorted ODT_lt_dec (domain x) = true).\n    apply (IHl1 x H1); assumption.\n    apply (rec_cons_sorted x l2 a); assumption.\n  Qed.\n\n  Lemma rec_sort_pf {A} {l1: list (K*A)} :\n    is_list_sorted ODT_lt_dec (domain (rec_sort l1)) = true.\n  Proof.\n    exact (rec_sort_sorted _ _ (eq_refl _)).\n  Qed.\n  \n  Lemma rec_concat_sort_sorted {A} (l1 l2 x:list (K*A)) :\n    rec_concat_sort l1 l2 = x ->\n    is_list_sorted ODT_lt_dec (domain x) = true.\n  Proof.\n    intros.\n    assert (rec_sort (l1++l2) = x).\n    rewrite <- rec_concat_sort_concats; assumption.\n    apply (rec_sort_sorted (l1++l2) x); assumption.\n  Qed.\n\n  Lemma same_domain_same_sorted {A} {B} (l1:list (K*A)) (l2:list (K*B)) :\n    domain l1 = domain l2 ->\n    is_list_sorted ODT_lt_dec (domain l1) = true ->\n    is_list_sorted ODT_lt_dec (domain l2) = true.\n  Proof.\n    intros.\n    rewrite <- H; assumption.\n  Qed.\n\n  Lemma same_domain_insert {A} {B}\n        (l1:list (K*A)) (l2:list (K*B))\n        (a:K*A) (b:K*B):\n    domain l1 = domain l2 ->\n    fst a = fst b ->\n    domain (rec_cons_sort a l1) = domain (rec_cons_sort b l2).\n  Proof.\n    intros.\n    revert l2 H.\n    induction l1.\n    induction l2; simpl in *; congruence.\n    intros; simpl in *.    \n    induction l2; simpl in *; try congruence.\n    clear IHl2.\n    inversion H.\n    elim (rec_field_lt_dec a a0); intros.\n    elim (rec_field_lt_dec b a1); intros.\n    simpl.\n    rewrite H2; rewrite H0; rewrite H3; reflexivity.\n    unfold rec_field_lt in *.\n    destruct a; destruct a0; destruct b; destruct a1; simpl in *.\n    subst. congruence.\n    unfold rec_field_lt in *.\n    destruct a; destruct a0; destruct b; destruct a1; simpl in *.\n    subst.\n    inversion H.\n    destruct (ODT_lt_dec k1 k2); try congruence.\n    destruct (ODT_lt_dec k2 k1); try congruence; simpl.\n    - rewrite (IHl1 l2 H1); reflexivity.\n    - rewrite H1; reflexivity.\n  Qed.\n\n  Lemma same_domain_rec_sort {A} {B}\n        (l1:list (K*A)) (l2:list (K*B)) :\n    domain l1 = domain l2 ->\n    domain (rec_sort l1) = domain (rec_sort l2).\n  Proof.\n    revert l2; induction l1; simpl; intros.\n    - symmetry in H; apply domain_nil in H; subst; simpl; trivial.\n    - destruct l2; simpl in *; try discriminate.\n      inversion H.\n      fold (@rec_cons_sort A).\n      fold (@rec_cons_sort B).\n      apply same_domain_insert; auto.\n  Qed.\n\n  Lemma insertion_sort_insert_nin_perm {A:Type} l a :\n    ~ In (fst a) (@domain _ A l) ->\n    Permutation (a::l) (insertion_sort_insert rec_field_lt_dec a l).\n  Proof.\n    induction l; simpl; auto.\n    intuition.\n    destruct (rec_field_lt_dec a a0); trivial.\n    generalize (field_not_less_and_neq_is_more _ _ n).\n    destruct (rec_field_lt_dec a0 a); intuition.\n    rewrite perm_swap.\n    rewrite Permutation_cons; try eassumption; trivial.\n  Qed.\n\n  Lemma insertion_sort_perm_proper {A:Type} (l l':list (K*A)) a :\n    ~ In (fst a) (domain l) ->\n    Permutation l l' ->\n    Permutation\n      (insertion_sort_insert rec_field_lt_dec a l)\n      (insertion_sort_insert rec_field_lt_dec a l').\n  Proof.\n    revert l l'.\n    induction l; simpl; intros.\n    - apply Permutation_nil in H0; subst; auto.\n    - assert (inl:In a0 l')\n        by (apply (Permutation_in _ H0); simpl; intuition).\n      destruct (in_split _ _ inl) as [l1 [l2 ?]]; subst.\n      rewrite <- Permutation_middle in H0.\n      apply Permutation_cons_inv in H0.\n      intuition.\n      destruct (rec_field_lt_dec a a0).\n      + rewrite H0.\n        rewrite <- insertion_sort_insert_nin_perm.\n        * apply Permutation_cons; trivial.\n          apply Permutation_middle.\n        * intros nin.\n          apply (@Permutation_in _ (domain (l1 ++ a0 :: l2)) (domain (a0::l))) in nin.\n          simpl in nin; intuition.\n          apply dom_perm. rewrite <- Permutation_middle.\n          rewrite H0; trivial.\n      + assert (rec_field_lt a0 a)\n          by (apply field_not_less_and_neq_is_more; auto).\n        destruct (rec_field_lt_dec a0 a); intuition.\n        rewrite (IHl _ H2 H0).\n        assert (nin:~ In (fst a) (domain l1)).\n        intro nin; apply H2.\n        eapply Permutation_in; [apply dom_perm;symmetry;apply H0|]. \n        unfold domain; rewrite map_app; apply in_or_app; intuition.\n        revert H1 n H nin. clear. revert l2 a a0.\n        induction l1; simpl; intros.\n        * destruct (rec_field_lt_dec a a0); intuition.\n          destruct (rec_field_lt_dec a0 a); intuition.\n        * intuition.\n          destruct (rec_field_lt_dec a0 a); intuition.\n          rewrite perm_swap. apply Permutation_cons; trivial.\n          rewrite perm_swap. apply Permutation_cons; trivial.\n          apply Permutation_middle.\n          assert (rec_field_lt a a0)\n            by (apply field_not_less_and_neq_is_more; auto).\n          destruct (rec_field_lt_dec a a0); intuition.\n          rewrite perm_swap.\n          rewrite IHl1; auto.\n  Qed.\n\n  Lemma rec_sort_perm  {A:Type} l :\n    NoDup (@domain _ A l) -> Permutation l (rec_sort l).\n  Proof.\n    induction l; simpl; auto.\n    inversion 1; subst.\n    rewrite insertion_sort_perm_proper; [| |symmetry; auto].\n    apply insertion_sort_insert_nin_perm; trivial.\n    intros nin; apply H2.\n    eapply Permutation_in; [|eapply nin].\n    symmetry. apply dom_perm.\n    auto.\n  Qed.\n\n  Lemma insertion_sort_insert_insertion_nin {A} (a:K*A) a0 l : \n    ~ rec_field_lt a0 a ->\n    ~ rec_field_lt a a0 ->\n    insertion_sort_insert rec_field_lt_dec a0\n                          (insertion_sort_insert rec_field_lt_dec a l)\n    = insertion_sort_insert rec_field_lt_dec a l.\n  Proof.\n    revert a a0. induction l; simpl; intros.\n    - destruct (rec_field_lt_dec a0 a); intuition.\n      destruct (rec_field_lt_dec a a0); intuition.\n    - destruct (rec_field_lt_dec a0 a); intuition.\n      + simpl.\n        destruct (rec_field_lt_dec a1 a0); intuition.\n        destruct (rec_field_lt_dec a0 a1); intuition.\n      + destruct (rec_field_lt_dec a a0); simpl.\n        * destruct (rec_field_lt_dec a1 a).\n          rewrite r in r0; intuition.\n          destruct (rec_field_lt_dec a a1); trivial.\n          f_equal; eauto.\n        * (* we crucially need trichotomy *)\n          destruct (trichotemy (fst a0) (fst a1)) as [[?|?]|?]; intuition.\n          destruct (trichotemy (fst a) (fst a0)) as [[?|?]|?]; intuition.\n          destruct a0; destruct a1; destruct a; simpl in *.\n          subst.\n          destruct (ODT_lt_dec k0 k0); try congruence.\n          assert False by (apply (ODT_lt_irr k0); auto).\n          contradiction.\n  Qed.\n\n  Lemma insertion_sort_insert_cons_app {A} (a:K*A) l l2 :\n    insertion_sort rec_field_lt_dec (insertion_sort_insert rec_field_lt_dec a l ++ l2) = insertion_sort rec_field_lt_dec (a::l ++ l2).\n  Proof.\n    revert a l2.\n    induction l; simpl; trivial; intros.\n    destruct (rec_field_lt_dec a0 a); simpl; trivial.\n    destruct (rec_field_lt_dec a a0); simpl; trivial.\n    - rewrite IHl; simpl. apply insertion_sort_insert_swap; eauto.\n      apply rec_field_lt_strict.\n    - rewrite insertion_sort_insert_insertion_nin; eauto.\n  Qed.\n\n  Lemma insertion_sort_insertion_sort_app1 {A} l1 l2 :\n    insertion_sort rec_field_lt_dec (insertion_sort (@rec_field_lt_dec A) l1 ++ l2) =\n    insertion_sort rec_field_lt_dec (l1 ++ l2).\n  Proof.\n    revert l2.\n    induction l1; simpl; trivial; intros.\n    rewrite insertion_sort_insert_cons_app.\n    simpl.\n    rewrite IHl1.\n    trivial.\n  Qed.\n\n  Lemma insertion_sort_insertion_sort_app {A} l1 l2 l3 :\n    insertion_sort rec_field_lt_dec (l1 ++ insertion_sort (@rec_field_lt_dec A) l2 ++ l3) =\n    insertion_sort rec_field_lt_dec (l1 ++ l2 ++ l3).\n  Proof.\n    induction l1; simpl.\n    - apply insertion_sort_insertion_sort_app1.\n    - rewrite IHl1; trivial.\n  Qed.\n\n  Lemma insertion_sort_eq_app1 {A l1 l1'} l2 :\n    insertion_sort (@rec_field_lt_dec A) l1 = insertion_sort rec_field_lt_dec l1' -> \n    insertion_sort rec_field_lt_dec (l1 ++ l2) =\n    insertion_sort rec_field_lt_dec (l1' ++ l2).\n  Proof.\n    intros.\n    rewrite <- (insertion_sort_insertion_sort_app1 l1 l2).\n    rewrite <- (insertion_sort_insertion_sort_app1 l1' l2).\n    rewrite H.\n    trivial.\n  Qed.\n\n  Lemma rec_sort_rec_sort_app1 {A} l1 l2 :\n    rec_sort ((@rec_sort A) l1 ++ l2) =\n    rec_sort (l1 ++ l2).\n  Proof.\n    apply insertion_sort_insertion_sort_app1.\n  Qed.\n\n  Lemma rec_sort_rec_sort_app {A} l1 l2 l3 :\n    rec_sort (l1 ++ (@rec_sort A) l2 ++ l3) =\n    rec_sort (l1 ++ l2 ++ l3).\n  Proof.\n    apply insertion_sort_insertion_sort_app.\n  Qed.\n\n  Lemma rec_sort_rec_sort_app2 {A} l1 l2 :\n    rec_sort (l1 ++ (@rec_sort A) l2) =\n    rec_sort (l1 ++ l2).\n  Proof.\n    generalize (rec_sort_rec_sort_app l1 l2 nil).\n    repeat rewrite app_nil_r.\n    trivial.\n  Qed.\n\n  Lemma rec_sort_eq_app1  {A l1 l1'} l2 :\n    (@rec_sort A) l1 = rec_sort l1' ->\n    rec_sort (l1 ++ l2) =\n    rec_sort (l1' ++ l2).\n  Proof.\n    apply insertion_sort_eq_app1.\n  Qed.\n\n  Lemma rec_cons_sort_Forall2 {A B} P l1 l2 a b :\n    Forall2 P l1 l2 ->\n    P a b ->\n    (domain l1) = (domain l2) ->\n    fst a = fst b ->\n    Forall2 P \n            (insertion_sort_insert (@rec_field_lt_dec A) a l1)\n            (insertion_sort_insert (@rec_field_lt_dec B) b l2).\n  Proof.\n    revert a b l2; induction l1; simpl; inversion 1; intros; subst; simpl; [eauto|].\n    destruct (rec_field_lt_dec a0 a); \n      destruct (rec_field_lt_dec b y); \n      unfold rec_field_lt in *; rewrite H7 in *;\n        simpl in *; inversion H6; rewrite H1 in *; intuition.\n    destruct (rec_field_lt_dec a a0);  unfold rec_field_lt in *;\n      rewrite H7,H1 in *;\n      destruct (rec_field_lt_dec y b);  unfold rec_field_lt in *; intuition.\n  Qed.\n\n  Lemma rec_sort_Forall2 {A B} P l1 l2 :\n    (domain l1) = (domain l2) ->\n    Forall2 P l1 l2 ->\n    Forall2 P (@rec_sort A l1) (@rec_sort B l2).\n  Proof.\n    revert l2; induction l1; simpl; inversion 2; subst; eauto.\n    simpl in *; inversion H.\n    apply rec_cons_sort_Forall2; auto.\n    apply same_domain_rec_sort; auto.\n  Qed.\n\n  Lemma rec_concat_sort_nil_r {A} g :\n    @rec_concat_sort A g nil = rec_sort g.\n  Proof.\n    unfold rec_concat_sort. rewrite app_nil_r. trivial.\n  Qed.\n\n  Lemma rec_concat_sort_nil_l {A} g :\n    @rec_concat_sort A nil g = rec_sort g.\n  Proof.\n    unfold rec_concat_sort. simpl. trivial.\n  Qed.\n\n  Lemma drec_sort_idempotent {A} l : @rec_sort A (rec_sort l) = rec_sort l.\n  Proof.\n    apply rec_sorted_id.\n    eapply rec_sort_sorted; eauto.\n  Qed.\n\n  Lemma insertion_sort_insert_equiv_domain {A:Type} x a (l:list (K*A)) :\n    In x\n       (domain (LibUtilsSortingAdd.insertion_sort_insert rec_field_lt_dec a l)) <->\n    fst a = x \\/ In x (domain l).\n  Proof.\n    induction l; simpl; [intuition|].\n    destruct a; destruct a0; simpl in *.\n    destruct (ODT_lt_dec k k0); simpl; [intuition|].\n    destruct (ODT_lt_dec k0 k); simpl; intuition. subst; clear H.\n    destruct (trichotemy x k0); intuition.\n  Qed.\n\n  Lemma drec_sort_equiv_domain {A} l : \n    equivlist (domain (@rec_sort A l)) (domain l).\n  Proof.\n    unfold equivlist.\n    induction l; simpl; [intuition|]; intros x.\n    rewrite <- IHl. apply insertion_sort_insert_equiv_domain.\n  Qed.\n\n  Hint Resolve ODT_lt_strorder : list.\n  \n  Lemma insertion_sort_insert_swap_neq {A} a1 (b1:A) a2 b2 l :\n    ~(eq a1 a2) ->\n    insertion_sort_insert rec_field_lt_dec (a1, b1)\n                          (insertion_sort_insert rec_field_lt_dec \n                                                 (a2, b2) l) =\n    insertion_sort_insert rec_field_lt_dec (a2, b2)\n                          (insertion_sort_insert rec_field_lt_dec \n                                                 (a1, b1) l).\n  Proof.\n    revert a1 b1 a2 b2. induction l; simpl; intros.\n    - destruct (ODT_lt_dec a1 a2); \n        destruct (ODT_lt_dec a2 a1); trivial.\n      + eelim @asymmetry; eauto.\n        unfold Asymmetric; intros.\n        apply (@asymmetry _ _ _ x y); assumption.\n      + destruct (trichotemy a1 a2) as [[?|?]|?];\n          intuition.\n    - destruct a; simpl.\n      Ltac t := try (solve[eelim @asymmetry; eauto]); intuition.\n      repeat dest_strlt; \n        intuition;\n        try solve[\n              rewrite o0 in *; t\n            | destruct (trichotemy a1 a2) as [[?|?]|?]; intuition].\n      rewrite o0 in o2.\n      dest_strlt.\n      rewrite IHl; [reflexivity|assumption].\n  Qed.\n\n  Lemma insertion_sort_insert_middle {A} l1 l2 a (b:A) :\n    ~ In a (domain l1) ->\n    LibUtilsSortingAdd.insertion_sort_insert rec_field_lt_dec (a, b)\n                                     (LibUtilsSortingAdd.insertion_sort rec_field_lt_dec (l1 ++ l2)) =\n    LibUtilsSortingAdd.insertion_sort rec_field_lt_dec (l1 ++ (a, b) :: l2).\n  Proof.\n    revert l2 a b.\n    induction l1; simpl; trivial; intros.\n    intuition.\n    rewrite <- IHl1; auto.\n    destruct a; simpl in *.\n    apply insertion_sort_insert_swap_neq; auto.\n  Qed.\n\n  Lemma drec_sort_perm_eq {A} l l' :\n    NoDup (@domain _ A l) ->\n    Permutation l l' -> \n    rec_sort l = rec_sort l'.\n  Proof.\n    unfold rec_sort.\n    revert l'. induction l; simpl; intros.\n    - apply Permutation_nil in H0; subst; simpl; trivial.\n    - inversion H; subst.\n      destruct a as [a b].\n      assert (inl:In (a,b) l')\n        by (apply (Permutation_in _ H0); simpl; intuition).\n      destruct (in_split _ _ inl) as [l1 [l2 ?]]; subst.\n      rewrite <- Permutation_middle in H0.\n      apply Permutation_cons_inv in H0.\n      inversion H; subst.\n      rewrite (IHl (l1 ++ l2)); auto.\n      apply insertion_sort_insert_middle.\n      intros nin; apply H5.\n      apply dom_perm in H0.\n      symmetry in H0.\n      eapply Permutation_in; try eapply H0.\n      rewrite domain_app, in_app_iff.\n      intuition.\n  Qed.\n\n  Lemma drec_sorted_perm_eq {A : Type} (l l' : list (K * A)) :\n    is_list_sorted ODT_lt_dec (domain l) = true ->\n    is_list_sorted ODT_lt_dec (domain l') = true ->\n    Permutation l l' ->\n    l = l'.\n  Proof.\n    intros.\n    assert (rec_sort l = rec_sort l').\n    - apply drec_sort_perm_eq; trivial.\n      apply (is_list_sorted_NoDup ODT_lt_dec); trivial.\n    - repeat rewrite sort_sorted_is_id in H2 by trivial.\n      trivial.\n  Qed.\n  \n  Lemma drec_concat_sort_app_comm {A} l l': \n    NoDup (@domain _ A (l ++l')) ->\n    rec_concat_sort l l' = rec_concat_sort l' l.\n  Proof.\n    intros.\n    unfold rec_concat_sort.\n    apply drec_sort_perm_eq; auto.\n    apply Permutation_app_comm.\n  Qed.\n\n  Lemma in_dom_rec_sort {B} {l x}:\n    In x (domain (rec_sort l)) <-> In x (@domain _ B l).\n  Proof.\n    intros.\n    apply  drec_sort_equiv_domain; trivial.\n  Qed.\n\n  Lemma drec_sort_sorted {A} l :\n    LibUtilsSortingAdd.is_list_sorted ODT_lt_dec\n                              (@domain _ A\n                                       (rec_sort l)) = true.\n  Proof.\n    eapply rec_sort_sorted; eauto.\n  Qed.\n\n  Lemma drec_concat_sort_sorted {A} l l' :\n    LibUtilsSortingAdd.is_list_sorted ODT_lt_dec\n                              (@domain _ A\n                                       (rec_concat_sort l l')) = true.\n  Proof.\n    unfold rec_concat_sort.\n    eapply rec_sort_sorted; eauto.\n  Qed.\n\n  Lemma drec_sort_drec_sort_concat {A} l l' :\n    (rec_sort (@rec_concat_sort A l l')) = rec_concat_sort l l'.\n  Proof.\n    unfold rec_sort, rec_concat_sort.\n    apply insertion_sort_idempotent.\n  Qed.\n\n  Lemma assoc_lookupr_insertion_sort_insert_neq {B:Type} a x (b:B) l :\n    ~(eq x a)->\n    assoc_lookupr ODT_eqdec \n                  (LibUtilsSortingAdd.insertion_sort_insert rec_field_lt_dec (a, b) l)\n                  x \n    = assoc_lookupr ODT_eqdec l x.\n  Proof.\n    revert a x b.\n    induction l; simpl; intros.\n    - destruct (ODT_eqdec x a); intuition.\n    - destruct a; simpl.\n      destruct (ODT_lt_dec a0 k);\n        destruct (ODT_lt_dec k a0); simpl.\n      + destruct (assoc_lookupr ODT_eqdec l x); trivial.\n        destruct (ODT_eqdec x k); trivial.\n        destruct (ODT_eqdec x a0); intuition.\n      + destruct (assoc_lookupr ODT_eqdec l x); trivial.\n        destruct (ODT_eqdec x k); trivial.\n        destruct (ODT_eqdec x a0); intuition.\n      + rewrite IHl; trivial.\n      + destruct (trichotemy a0 k); intuition.\n  Qed.\n\n  Lemma assoc_lookupr_insertion_sort_fresh {B:Type} x (d:B) b :\n    ~ In x (domain b) ->\n    assoc_lookupr ODT_eqdec\n                  (LibUtilsSortingAdd.insertion_sort rec_field_lt_dec (b ++ (x, d) :: nil)) x = \n    Some d.\n  Proof.\n    revert x d.\n    induction b; simpl; intuition.\n    - destruct (ODT_eqdec x x); intuition.\n    - rewrite assoc_lookupr_insertion_sort_insert_neq; auto.\n  Qed.\n\n  Lemma is_list_sorted_NoDup_strlt {A} l :\n    is_list_sorted ODT_lt_dec (@domain _ A l) = true ->\n    NoDup (domain l).\n  Proof.\n    eapply is_list_sorted_NoDup.\n    eapply ODT_lt_strorder.\n  Qed.\n\n  Lemma rec_sort_self_cons_middle {A} (l:list (K*A)) (a:K*A):\n    is_list_sorted ODT_lt_dec (domain (a::l)) = true ->\n    rec_sort (l ++ a :: l) = rec_sort ((a :: l) ++ l).\n  Proof.\n    unfold rec_sort; intros.\n    assert (l ++ a :: l = (l++(a::nil))++l) by apply app_cons_middle.\n    rewrite H0.\n    apply insertion_sort_eq_app1.\n    generalize (drec_sort_perm_eq (a :: l) (l++(a::nil))); intros.\n    unfold rec_sort in H1.\n    rewrite H1; try reflexivity.\n    apply is_list_sorted_NoDup_strlt; assumption.\n    rewrite Permutation_app_comm.\n    simpl.\n    reflexivity.\n  Qed.\n\n  Lemma rec_field_anti {A} a:\n    ~ (@rec_field_lt A) a a.\n  Proof.\n    generalize ODT_lt_strorder; intros.\n    unfold Irreflexive, Reflexive, complement in *.\n    destruct a; unfold rec_field_lt; simpl.\n    inversion H. apply StrictOrder_Irreflexive.\n  Qed.\n\n  Lemma lt_not_not k1 k2:\n    ~ODT_lt k1 k2 -> ~ODT_lt k2 k1 -> eq k1 k2.\n  Proof.\n    unfold not; intros.\n    generalize (trichotemy k1 k2); intros.\n    inversion H1.\n    elim H2; intros.\n    congruence.\n    assumption.\n    congruence.\n  Qed.\n  \n  Lemma rec_concat_sort_self {A} (l:list (K*A)):\n    is_list_sorted ODT_lt_dec (domain l) = true ->\n    rec_concat_sort l l = l.\n  Proof.\n    intros.\n    induction l; try reflexivity.\n    unfold rec_concat_sort.\n    assert (is_list_sorted ODT_lt_dec (domain l) = true)\n      by (apply (rec_sorted_skip_first l a); assumption).\n    specialize (IHl H0).\n    simpl.\n    rewrite rec_sort_self_cons_middle; try assumption.\n    simpl.\n    unfold rec_concat_sort in IHl.\n    rewrite IHl.\n    simpl.\n    rewrite insertion_sort_insert_insertion_nin.\n    generalize (rec_sorted_id (a :: l) H); intros.\n    simpl in H1.\n    assert (rec_sort l = l). apply rec_sorted_id; assumption.\n    rewrite H2 in H1; assumption.\n    apply rec_field_anti.\n    apply rec_field_anti.\n  Qed.\n\n  Lemma insert_first_into_app {A} (l l0:list (K*A)) (a:K*A):\n    is_list_sorted ODT_lt_dec (domain (a :: l)) = true ->\n    rec_sort (l ++ insertion_sort_insert rec_field_lt_dec a (rec_sort (l ++ l0))) =\n    insertion_sort_insert rec_field_lt_dec a (rec_sort (l ++ rec_sort (l ++ l0))).\n  Proof.\n    intros.\n    assert (NoDup (domain (a::l))) by (apply is_list_sorted_NoDup_strlt; assumption).\n    inversion H0; subst.\n    assert (is_list_sorted ODT_lt_dec (domain l) = true)\n      by (apply (rec_sorted_skip_first l a); assumption).\n    assert (is_list_sorted ODT_lt_dec (domain (rec_sort (l++l0))) = true).\n    apply (rec_sort_sorted (l++l0)); reflexivity.\n    revert H3.\n    generalize (rec_sort (l++l0)); intros.    \n    generalize (@rec_cons_sorted_id A l a H); intros.\n    generalize (@insertion_sort_insert_middle A l l1 (fst a) (snd a) H3); intros.\n    destruct a; simpl in *.\n    unfold rec_sort.\n    rewrite H6.\n    clear H5 H6 H H0 H3 H4 H1 H2.\n    induction l.\n    simpl.\n    generalize (insertion_sort_insert_cons_app (k, a) l1 nil); intros.\n    repeat rewrite app_nil_r in H.\n    rewrite H; reflexivity.\n    simpl. rewrite IHl. reflexivity.\n  Qed.\n\n  Lemma rec_concat_sort_idem {A} (l l0:list (K*A)):\n    is_list_sorted ODT_lt_dec (domain l) = true ->\n    is_list_sorted ODT_lt_dec (domain l0) = true ->\n    rec_concat_sort l (rec_concat_sort l l0) = rec_concat_sort l l0.\n  Proof.\n    intros.\n    assert (NoDup (domain l)) by (apply is_list_sorted_NoDup_strlt; assumption).\n    assert (NoDup (domain l0)) by (apply is_list_sorted_NoDup_strlt; assumption).\n    unfold rec_concat_sort.\n    induction l; simpl.\n    - rewrite drec_sort_idempotent; reflexivity.\n    - assert (is_list_sorted ODT_lt_dec (domain l) = true)\n        by (apply (rec_sorted_skip_first l a); assumption).\n      inversion H1; subst.\n      specialize (IHl H3 H7).\n      assert ((rec_sort\n                 (l ++ insertion_sort_insert rec_field_lt_dec a (rec_sort (l ++ l0))))\n              =\n              insertion_sort_insert rec_field_lt_dec a ((rec_sort (l ++ rec_sort (l ++ l0))))).\n      apply insert_first_into_app; assumption.\n      rewrite H4.\n      rewrite insertion_sort_insert_insertion_nin.\n      rewrite IHl.\n      reflexivity.\n      apply rec_field_anti.\n      apply rec_field_anti.\n  Qed.\n\n  Instance In_equivlist_proper {A}:\n    Proper (eq ==> equivlist ==> iff) (@In A).\n  Proof.\n    unfold Proper, respectful, equivlist; intros; subst; trivial.\n  Qed.\n\n  Lemma assoc_lookupr_insert B s (d:B) l x :\n    assoc_lookupr ODT_eqdec  \n                  (LibUtilsSortingAdd.insertion_sort_insert rec_field_lt_dec (s, d) l) x =\n    match assoc_lookupr ODT_eqdec l x with\n    | Some d' => Some d'\n    | None => if ODT_eqdec x s then Some d else None\n    end.\n  Proof.\n    revert s d x. induction l; simpl; trivial; intros.\n    destruct a.\n    destruct (ODT_lt_dec s k); simpl; trivial.\n    destruct (ODT_lt_dec k s); simpl; trivial.\n    - rewrite IHl; simpl.\n      destruct (assoc_lookupr ODT_eqdec l); trivial.\n      destruct (ODT_eqdec x s).\n      + subst. destruct (ODT_eqdec x k); intuition.\n        rewrite <- e0 in *. rewrite <- e in *.\n        dest_strlt.\n      + destruct (ODT_eqdec x k); trivial.\n    - destruct (trichotemy s k); intuition.\n      subst.\n      destruct (assoc_lookupr ODT_eqdec l x); try reflexivity.\n      destruct (ODT_eqdec x k); trivial.\n  Qed.\n\n  Lemma assoc_lookupr_drec_sort {A} l x :\n    assoc_lookupr ODT_eqdec (@rec_sort A l) x = \n    assoc_lookupr ODT_eqdec l x.\n  Proof.\n    revert x. induction l; simpl; trivial; intros.\n    destruct a; simpl.\n    rewrite assoc_lookupr_insert, IHl.\n    trivial.\n  Qed.\n\n  Lemma assoc_lookupr_drec_sort_app_nin {A} l l' x: \n    ~ In x (domain l') ->\n    assoc_lookupr ODT_eqdec (@rec_sort A (l ++ l')) x\n    = assoc_lookupr ODT_eqdec (rec_sort l) x.\n  Proof.\n    repeat rewrite assoc_lookupr_drec_sort.\n    intros.\n    rewrite (assoc_lookupr_app l l'); intros.\n    case_eq (assoc_lookupr ODT_eqdec l' x); trivial; intros.\n    apply assoc_lookupr_in in H0.\n    apply in_dom in H0; intuition.\n    idtac.\n    assert ((@assoc_lookupr K A\n                            (@Equivalence.equiv K (@eq K) (@eq_equivalence K))\n                            (@complement K\n                                         (@Equivalence.equiv K (@eq K) (@eq_equivalence K)))\n                            (@ODT_eqdec K odt) l' x) =\n            (@assoc_lookupr K A (@eq K) (fun x0 y : K => not (@eq K x0 y))\n                            (@ODT_eqdec K odt) l' x)) by reflexivity.\n    rewrite H1 in *.\n    rewrite H0; reflexivity.\n  Qed.\n\n  Lemma insertion_sort_insert_domain {B:Type} x a (b:B) l : \n    In x (domain\n            (LibUtilsSortingAdd.insertion_sort_insert rec_field_lt_dec \n                                              (a, b) l)) ->\n    a = x \\/ In x (domain l).\n  Proof.\n    revert x a b. induction l; simpl; intuition.\n    destruct (ODT_lt_dec a a0); simpl in *; [intuition|].\n    destruct (ODT_lt_dec a0 a); simpl in *; [|intuition].\n    intuition. destruct (IHl _ _ _ H0); auto.\n  Qed.\n\n  Lemma drec_sort_domain {A} x l :\n    In x (domain (@rec_sort A l)) -> In x (domain l).\n  Proof.\n    revert x.\n    induction l; simpl; intuition.\n    apply insertion_sort_insert_domain in H. intuition.\n  Qed.\n\n  Lemma drec_concat_sort_pullout {A} b x xv y yv : \n    NoDup (x::y::(domain b)) ->\n    (@ rec_concat_sort A (rec_concat_sort b ((x, xv) :: nil))\n       ((y, yv) :: nil))\n    =\n    (rec_concat_sort (rec_concat_sort b ((y, yv) :: nil))\n                     ((x, xv) :: nil)).\n  Proof.\n    intros.\n    inversion H; subst.\n    inversion H3; subst.\n    simpl in *.\n    apply drec_sort_perm_eq; simpl.\n    -  rewrite Permutation_app_comm; simpl.\n       constructor; simpl.\n       + intros nin. \n         unfold rec_concat_sort in nin;\n           apply drec_sort_domain in nin.\n         rewrite domain_app, in_app_iff in nin.\n         simpl in *.\n         intuition.\n       + unfold rec_concat_sort.\n         simpl in *.\n         rewrite <- rec_sort_perm;\n           rewrite Permutation_app_comm; simpl; constructor; intuition.\n    - unfold rec_concat_sort.\n      simpl. rewrite Permutation_app_comm. simpl.\n      rewrite <- rec_sort_perm.\n      rewrite Permutation_app_comm; simpl.\n      rewrite Permutation_app_comm.\n      simpl.\n      intuition.\n      rewrite <- rec_sort_perm.\n      rewrite Permutation_app_comm. simpl.\n      apply perm_swap.\n      rewrite domain_app; simpl.\n      assert (Permutation (y::domain b) (domain b++y::nil)).\n      rewrite Permutation_app_comm. reflexivity.\n      rewrite <- H2; assumption.\n      assert (NoDup (x :: domain b)).\n      constructor.\n      inversion H. subst.\n      simpl in H6.\n      unfold not in *.\n      intros. apply H6. right; assumption.\n      assumption.\n      rewrite domain_app; simpl.\n      assert (Permutation (x::domain b) (domain b++x::nil)).\n      rewrite Permutation_app_comm. reflexivity.\n      rewrite <- H1; assumption.\n  Qed.\n\n  Lemma sorted_cons_filter_in_domain {A} (l l':list (K*A)) f a :\n    filter f l = a :: l' -> In a l.\n  Proof.\n    induction l; intros.\n    simpl in H; congruence.\n    simpl in *.\n    destruct (f a0).\n    - inversion H; left; reflexivity.\n    - right; apply (IHl H).\n  Qed.\n  \n  Lemma filter_choice {A} (l:list(K*A)) f:\n    filter f l = nil \\/ (exists a, exists l', filter f l = a :: l').\n  Proof.\n    induction l.\n    left; reflexivity.\n    simpl in *.\n    elim IHl; clear IHl; intros.\n    rewrite H.\n    destruct (f a).\n    right; exists a; exists nil; reflexivity.\n    left; reflexivity.\n    elim H; clear H; intros.\n    elim H; clear H; intros.\n    rewrite H.\n    destruct (f a).\n    right; exists a; exists (x :: x0); reflexivity.\n    right; exists x; exists x0; reflexivity.\n  Qed.\n\n  Lemma sorted_over_filter {A} (l:list (K*A)) f:\n    is_list_sorted ODT_lt_dec (domain l) = true ->\n    is_list_sorted ODT_lt_dec (domain (filter f l)) = true.\n  Proof.\n    intros.\n    induction l.\n    reflexivity.\n    simpl.\n    case_eq (f a); intros.\n    - generalize (filter_choice l f); intros.\n      elim H1; clear H1; intros.\n      + rewrite H1 in *. reflexivity.\n      + elim H1; clear H1; intros.\n        elim H1; clear H1; intros.\n        rewrite H1 in *.\n        assert (In x l) by (apply (sorted_cons_filter_in_domain l x0 f); assumption).\n        assert (ODT_lt (fst a) (fst x)) by (apply (sorted_cons_in l a x); assumption).\n        apply rec_cons_lt.\n        apply IHl.\n        simpl in H.\n        destruct (domain l).\n        reflexivity.\n        destruct (ODT_lt_dec (fst a) k); try congruence; assumption.\n        assumption.\n    - apply IHl.\n      simpl in H.\n      destruct (domain l). reflexivity.\n      destruct (ODT_lt_dec (fst a) k).\n      assumption.\n      congruence.\n  Qed.\n\n  Lemma rec_sort_insert_filter_fst_true {A:Type} f  \n        (a:K*A) (l:list (K*A)) \n        (fstonly:forall a b c, f (a,b) = f (a,c)) :\n    StronglySorted rec_field_lt l ->\n    f a = true ->\n    filter f (insertion_sort_insert rec_field_lt_dec a l)\n    = insertion_sort_insert rec_field_lt_dec a (filter f l).\n  Proof.\n    revert a.\n    induction l; simpl; intros b lsort fb.\n    - rewrite fb; trivial.\n    - inversion lsort; subst.\n      case_eq (f a); simpl; intros fa.\n      +  destruct (rec_field_lt_dec b a); simpl.\n         * rewrite fb.\n           simpl. match_destr.\n         * rewrite <- IHl; trivial.\n           match_destr; simpl; rewrite fa; trivial.\n      + match_destr.\n        * simpl. rewrite fb, fa.\n          rewrite insertion_sort_insert_forall_lt; trivial.\n          apply Forall_filter.\n          revert H2.\n          apply Forall_impl_in; intros.\n          etransitivity; eauto.\n        * rewrite <- IHl; trivial.\n          match_destr; simpl; rewrite fa; trivial.\n          unfold rec_field_lt in *.\n          destruct (trichotemy (fst a) (fst b)) as [[?|?]|?]; try congruence.\n          destruct a; destruct b; simpl in *; subst.\n          specialize (fstonly k0 a a0). congruence.\n  Qed.\n  \n  Lemma rec_sort_insert_filter_fst_false {A:Type} f  \n        (a:K*A) (l:list (K*A)) \n        (fstonly:forall a b c, f (a,b) = f (a,c)) :\n    f a = false ->\n    filter f (insertion_sort_insert rec_field_lt_dec a l) =\n    filter f l.\n  Proof.\n    revert a.\n    induction l; simpl; intros ? fa.\n    - rewrite fa; trivial.\n    - match_destr; simpl.\n      + rewrite fa; trivial.\n      + match_destr; simpl.\n        rewrite IHl; trivial.\n  Qed.\n  \n  Lemma rec_sort_filter_fst_commute {A:Type} f (l:list (K*A))\n        (fstonly:forall a b c, f (a,b) = f (a,c)) :\n    filter f (rec_sort l)\n    = rec_sort (filter f l).\n  Proof.\n    induction l; simpl; trivial.\n    case_eq (f a); intros fa; simpl.\n    - rewrite <- IHl, rec_sort_insert_filter_fst_true; trivial.\n      eapply Sorted_StronglySorted.\n      + apply StrictOrder_Transitive.\n      + eapply insertion_sort_Sorted.\n    - rewrite <- IHl, rec_sort_insert_filter_fst_false; trivial.\n  Qed.\n  \n  Lemma forallb_rec_sort {A} f (l:list (K*A)) :\n    forallb f l = true ->\n    forallb f (rec_sort l) = true.\n  Proof.\n    repeat rewrite forallb_forall; intros.\n    apply H.\n    unfold rec_sort in *.\n    eapply in_insertion_sort; eauto.\n  Qed.\n\n  Lemma forallb_rec_sort_inv {A} f (l:list (K*A)) :\n    NoDup (domain l) ->\n    forallb f (rec_sort l) = true ->\n    forallb f l = true.\n  Proof.\n    repeat rewrite forallb_forall; intros.\n    apply H0.\n    eapply Permutation_in; try eassumption.\n    apply rec_sort_perm; trivial.\n  Qed.\n  \n  Lemma domain_rec_sort_insert {B} (a:K*B) l :\n    domain (insertion_sort_insert rec_field_lt_dec a l) =\n    insertion_sort_insert ODT_lt_dec (fst a) (domain l).\n  Proof.\n    revert a.\n    induction l; simpl; trivial; intros.\n    destruct a; destruct a0.\n    simpl.\n    match_destr.\n    match_destr.\n    simpl. rewrite IHl; trivial.\n  Qed.\n\n  Lemma domain_rec_sort {B} (l:list (K*B)) :\n    domain (rec_sort l) = insertion_sort ODT_lt_dec (domain l).\n  Proof.\n    unfold rec_sort.\n    induction l; simpl; trivial.\n    rewrite domain_rec_sort_insert, IHl; trivial.\n  Qed.\n\n  Lemma is_list_sorted_domain_rec_field {B} (l:list (K*B)) :\n    is_list_sorted rec_field_lt_dec l\n    = is_list_sorted ODT_lt_dec (domain l).\n  Proof.\n    induction l; simpl; trivial.\n    match_destr.\n    destruct a; destruct p; simpl.\n    match_destr.\n  Qed.\n\n  Lemma rec_sort_insert_in_dom {B} a (l:list (K*B)) : \n    In (fst a) (domain l) ->\n    is_list_sorted ODT_lt_dec (domain l) = true ->\n    insertion_sort_insert rec_field_lt_dec a l = l.\n  Proof.\n    induction l.\n    - intuition.\n    - intros.\n      destruct a; destruct a0; simpl.\n      simpl in H.\n      destruct H.\n      + subst. match_destr.\n        apply ODT_lt_irr in o.\n        intuition.\n      + rewrite IHl; trivial.\n        { match_destr.\n          - assert (is_list_sorted ODT_lt_dec (domain ((k,b)::(k0, b0) :: l)) = true).\n            + simpl; match_destr; intuition.\n            + eapply is_list_sorted_NoDup_strlt in H1.\n              simpl in H1. inversion H1; subst.\n              elim H4. simpl; intuition.\n          - match_destr.\n        }\n        apply is_list_sorted_cons_inv in H0; trivial.\n  Qed.\n  \n  Lemma in_rec_sort_insert {A} `{EqDec A eq} (x:K*A) (k:K) (a:A) l:\n    In x (insertion_sort_insert rec_field_lt_dec (k, a) l) ->\n    x = (k, a) \\/ In x l.\n  Proof.\n    revert x a. induction l; simpl; [intuition | ].\n    intros x a0.\n    destruct a; simpl in *.\n    destruct (ODT_lt_dec k k0); simpl; intros; trivial.\n    - elim H0; clear H0; intros; [left|]; auto.\n    - destruct (ODT_lt_dec k0 k); simpl; intros; intuition.\n      simpl in H0.\n      elim H0; clear H0; intros.\n      + intuition.\n      + destruct (IHl _ _ H0); intuition.\n  Qed.\n\n  Lemma rec_sort_filter_latter_from_former {B} s (l1 l2:list (K*B)) :\n    In s (domain l2) ->\n    rec_sort (l1 ++ l2) =\n    rec_sort (filter (fun x : K * B => s <>b fst x) l1 ++ l2).\n  Proof.\n    revert l2.\n    induction l1; simpl; trivial; intros.\n    rewrite IHl1; trivial.\n    match_case; intros eqq.\n    unfold nequiv_decb, equiv_decb in eqq.\n    destruct (equiv_dec s (fst a)); try discriminate.\n    red in e; subst.\n    apply rec_sort_insert_in_dom.\n    - rewrite drec_sort_equiv_domain.\n      rewrite domain_app, in_app_iff; intuition.\n    - apply rec_sort_pf.\n  Qed.\n\n  Section Forall.\n\n    Lemma Forall_sorted {A} (P:(K*A) -> Prop) (l:list (K*A)):\n      Forall P l -> Forall P (rec_sort l).\n    Proof.\n      apply Forall_insertion_sort.\n    Qed.\n\n  End Forall.\n  \n  Section CompatSort.\n\n    Lemma compatible_app_compatible {A} `{EqDec A eq} {l1 l2:list (K*A)} :\n      is_list_sorted ODT_lt_dec (domain l1) = true ->\n      is_list_sorted ODT_lt_dec (domain l2) = true ->\n      compatible l1 l2 = true ->\n      compatible (l1++l2) (l1++l2) = true.\n    Proof.\n      unfold compatible.\n      repeat rewrite forallb_forall; intros.\n      apply in_app_iff in H3.\n      unfold compatible_with in *.\n      match_case; intros.\n      match_destr; intros; unfold equiv, complement in *.\n      elim c; clear c.\n      destruct x.\n      apply assoc_lookupr_in in H4.\n      apply in_app_iff in H4; simpl in *.\n      apply is_list_sorted_NoDup_strlt in H0.\n      apply is_list_sorted_NoDup_strlt in H1.\n      intuition.\n      - generalize (nodup_in_eq H0 H3 H5); intros; subst; reflexivity.\n      - specialize (H2 _ H5). match_case_in H2; simpl in *; intros.\n        + rewrite H4 in H2. apply assoc_lookupr_in in H4.\n          generalize (nodup_in_eq H1 H3 H4); intros; subst.\n          match_destr_in H2.\n        + apply in_dom in H3. apply assoc_lookupr_none_nin in H4.\n          intuition.\n      - specialize (H2 _ H3). match_case_in H2; simpl in *; intros.\n        + rewrite H4 in H2. apply assoc_lookupr_in in H4.\n          generalize (nodup_in_eq H1 H5 H4); intros; subst.\n          match_destr_in H2.\n          congruence.\n        + apply in_dom in H5. apply assoc_lookupr_none_nin in H4.\n          intuition.\n      - generalize (nodup_in_eq H1 H3 H5); intros; subst; reflexivity.\n    Qed.\n    \n    Lemma compatible_asymmetric_over {A} `{EqDec A eq} {l:list(K*A)} :\n      compatible l l = true ->\n      asymmetric_over rec_field_lt l.\n    Proof.\n      unfold asymmetric_over; intros.\n      destruct x; destruct y; unfold rec_field_lt in *.\n      simpl in *.\n      generalize (lt_not_not k k0 H3 H4); intros eqq.\n      subst.\n      unfold compatible in *.\n      rewrite forallb_forall in H0.\n      generalize (H0 _ H1); simpl in *.\n      specialize (H0 _ H2); simpl in *; intros.\n      unfold compatible_with in *.\n      match_case_in H0; intros.\n      - rewrite H6 in *. match_destr_in H0; match_destr_in H5.\n        congruence.\n      - apply assoc_lookupr_none_nin in H6. apply in_dom in H2.\n        congruence.\n    Qed.\n\n    Lemma compatible_sort_equivlist {A} `{EqDec A eq} {l:list(K*A)} :\n      compatible l l = true ->\n      equivlist l (rec_sort l).\n    Proof.\n      split; intros.\n      - apply insertion_sort_in_strong; trivial.\n        apply compatible_asymmetric_over.\n        trivial.\n      - unfold rec_sort in *. unfold rec_sort in H0. eapply in_insertion_sort; eauto.\n    Qed.\n\n  End CompatSort.\n\n  Section sublist.\n    \n    Lemma sublist_rec_concat_sort_bounded {A} r srl :\n      incl (domain r) (domain srl) ->\n      domain (@rec_concat_sort A r srl) = domain (rec_sort srl).\n    Proof.\n      unfold rec_concat_sort.\n      repeat rewrite domain_rec_sort.\n      rewrite domain_app; intros.\n      apply insertion_sort_equivlist; [apply ODT_lt_contr | ].\n      rewrite app_commutative_equivlist.\n      rewrite app_contained_equivlist; [ reflexivity | ].\n      rewrite H; reflexivity.\n    Qed.\n\n    Lemma domain_rec_concat_sort_app_comm:\n      forall (A : Type) (l l' : list (K * A)),\n        domain (rec_concat_sort l l') = domain (rec_concat_sort l' l).\n    Proof.\n      intros.\n      unfold rec_concat_sort.\n      repeat rewrite domain_rec_sort.\n      apply insertion_sort_equivlist; [apply ODT_lt_contr | ].\n      repeat rewrite domain_app.\n      rewrite app_commutative_equivlist.\n      reflexivity.\n    Qed.\n\n    Lemma incl_sort_sublist {A B} a b :\n      incl (@domain _ A a) (@domain _ B b) ->        \n      sublist (domain (rec_sort a)) (domain (rec_sort b)).\n    Proof.\n      intros.\n      repeat erewrite domain_rec_sort.\n      apply Sorted_incl_sublist.\n      - apply insertion_sort_Sorted.\n      - apply insertion_sort_Sorted.\n      - intros. apply in_insertion_sort in H0.\n        specialize (H _ H0).\n        apply insertion_sort_in; [apply ODT_lt_contr | ].\n        trivial.\n    Qed.\n\n    Lemma rec_concat_sort_sublist {B} l1 l2 :\n      sublist (@domain _ B (rec_sort l1)) (domain (rec_concat_sort l1 l2)).\n    Proof.\n      apply incl_sort_sublist.\n      rewrite incl_appl; try reflexivity.\n      rewrite domain_app. reflexivity.\n    Qed.\n    \n    Lemma rec_concat_sort_sublist_sorted {B} l1 l2 :\n      is_list_sorted ODT_lt_dec (domain l1) = true ->\n      sublist (@domain _ B l1) (domain (rec_concat_sort l1 l2)).\n    Proof.\n      intros.\n      rewrite <- rec_concat_sort_sublist.\n      rewrite rec_sorted_id; trivial.\n      reflexivity.\n    Qed.\n\n  End sublist.\n\n  Global Instance assoc_lookupr_equiv_rec_sort  {A : Type} :\n    Proper (assoc_lookupr_equiv ==> assoc_lookupr_equiv) (@rec_sort A).\n  Proof.\n    unfold Proper, respectful, assoc_lookupr_equiv; intros.\n    repeat rewrite assoc_lookupr_drec_sort.\n    trivial.\n  Qed.\n\n  Section rev.\n    Lemma lookup_rev_rec_sort {B} (x:K) (l:list (K*B)) :\n      lookup ODT_eqdec (rev (rec_sort l)) x = lookup ODT_eqdec (rec_sort l) x.\n    Proof.\n      case_eq (lookup ODT_eqdec (rec_sort l) x); intros.\n      - apply (@lookup_some_nodup_perm _ _ _ (rec_sort l) (rev (rec_sort l))).\n        + apply StronglySorted_NoDup.\n          rewrite <- (sorted_StronglySorted ODT_lt_dec).\n          apply rec_sort_pf.\n        + apply Permutation.Permutation_rev.\n        + assumption.\n      - apply (@lookup_none_perm _ _ _ (rec_sort l) (rev (rec_sort l))).\n        + apply Permutation.Permutation_rev.\n        + assumption.\n    Qed.\n  End rev.\n\n  Lemma insertion_sort_nin_inv {B} (s:K) (x₁:B) l₁ x₂  l₂:\n    ~ In s (domain l₁) ->\n    ~ In s (domain l₂) ->\n    insertion_sort_insert rec_field_lt_dec (s, x₁) l₁ =\n    insertion_sort_insert rec_field_lt_dec (s, x₂) l₂ ->\n    x₁ = x₂ /\\ l₁ = l₂.\n  Proof.\n    intros nin1 nin2 eqq1.\n    generalize (insertion_sort_insert_nin_perm l₁ (s,x₁) nin1); intros perm1.\n    generalize (insertion_sort_insert_nin_perm l₂ (s,x₂) nin2); intros perm2.\n    rewrite eqq1 in perm1.\n    rewrite <- perm1 in perm2.\n    apply Permutation_cons_nin_map with (f:=fst) in perm2; simpl; trivial.\n    destruct perm2 as [eqq2 perm2].\n    invcs eqq2.\n    split; trivial.\n    apply insertion_sort_insert_nin_eq_inv in eqq1; trivial\n    ; intros inn; apply in_dom in inn; tauto.\n  Qed.\n\n  Lemma rec_sort_cons_nin_inv {B} (s:K) (x₁:B) l₁ x₂  l₂:\n    ~ In s (domain l₁) ->\n    ~ In s (domain l₂) ->\n    rec_sort ((s, x₁) :: l₁) =\n    rec_sort ((s, x₂) :: l₂) ->\n    x₁ = x₂ /\\ rec_sort l₁ = rec_sort l₂.\n  Proof.\n    simpl.\n    intros.\n    eapply insertion_sort_nin_inv; eauto\n    ; rewrite drec_sort_equiv_domain; trivial.\n  Qed.\n\nEnd Bindings.\n\nSection Map.\n\n  Lemma map_rec_sort {A B C D} `{odta:ODT A} `{odtb:ODT B} (f:A*C->B*D) (l:list(A*C))\n        (consistent:forall x y, rec_field_lt x y <->\n                                rec_field_lt (f x) (f y)) :\n    map f (rec_sort l) = rec_sort (map f l).\n  Proof.\n    unfold rec_sort.\n    apply map_insertion_sort.\n    trivial.\n  Qed.\nEnd Map.\n\nSection BindingsString.\n  \n  Global Program Instance ODT_string : (@ODT string)\n    := mkODT _ _ StringOrder.lt _ StringOrder.lt_dec StringOrder.compare StringOrder.compare_spec.\n\nEnd BindingsString.\n\nSection Edot.\n  (* note: right-rec so that new fields hide old fields *)\n  Definition edot {A} (r:list (string*A)) (a:string) : option A :=\n    assoc_lookupr ODT_eqdec r a.\n\n  Lemma edot_nodup_perm {A:Type} (l l':list (string*A)) x :\n    NoDup (domain l) -> Permutation l l' -> edot l x = edot l' x.\n  Proof.\n    apply assoc_lookupr_nodup_perm.\n  Qed.\n  \n  Lemma edot_fresh_concat {A} x (d:A) b :\n    ~ In x (domain b) ->\n    edot (rec_concat_sort b ((x,d)::nil)) x = Some d.\n  Proof.\n    intros.\n    apply (@assoc_lookupr_insertion_sort_fresh string ODT_string); trivial.\n  Qed.\n\nEnd Edot.\n\nHint Unfold rec_sort rec_concat_sort : list.\nHint Resolve drec_sort_sorted drec_concat_sort_sorted : list.\nHint Resolve is_list_sorted_NoDup_strlt : list.\n\nSection MergeBindings.\n  (* Merge record stuff *)\n\n  Definition merge_bindings {A} `{EqDec A eq} (l₁ l₂:list (string * A)) : option (list (string * A)) :=\n    if compatible l₁ l₂\n    then Some (rec_concat_sort l₁ l₂)\n    else None.\n\n  Lemma merge_bindings_nil_l {A} `{EqDec A eq} l : merge_bindings nil l = Some (rec_sort l).\n  Proof.\n    unfold merge_bindings.\n    simpl.\n    unfold rec_concat_sort; simpl.\n    trivial.\n  Qed.\n\n  Lemma merge_bindings_nil_r {A} `{EqDec A eq} l : merge_bindings l nil = Some (rec_sort l).\n  Proof.\n    unfold merge_bindings.\n    simpl.\n    rewrite compatible_nil_r.\n    unfold rec_concat_sort.\n    rewrite app_nil_r.\n    trivial.\n  Qed.\n\n  Lemma merge_bindings_single_nin {A} `{EqDec A eq} b x d :\n    ~ In x (domain b) ->\n    merge_bindings b ((x,d)::nil) =\n    Some (rec_concat_sort b ((x,d)::nil)).\n  Proof.\n    intro nin.\n    unfold merge_bindings.\n    rewrite compatible_single_nin; auto.\n  Qed.\n\n  Lemma merge_bindings_sorted {A} `{EqDec A eq} {g g1 g2} :\n    Some g = merge_bindings g1 g2 ->\n    is_list_sorted ODT_lt_dec (@domain string A g) = true.\n  Proof.\n    unfold merge_bindings. intros.\n    destruct (compatible g1 g2); try discriminate.\n    inversion H0; subst.\n    unfold rec_concat_sort, rec_concat_sort in *.\n    eauto with list.\n  Qed.\n\n  Lemma edot_merge_bindings {A} `{EqDec A eq} (l1 l2:list (string*A)) (s:string) (x:A) :\n    merge_bindings l1 ((s, x)::nil) = Some l2 ->\n    edot l2 s = Some x.\n  Proof.\n    intros.\n    unfold merge_bindings in *.\n    case_eq (compatible l1 ((s, x)::nil)); intros; rewrite H1 in *; try congruence.\n    inversion H0; clear H0.\n    unfold edot.\n    unfold rec_concat_sort in *.\n    rewrite (@assoc_lookupr_drec_sort string ODT_string) in *.\n    rewrite (@assoc_lookupr_app).\n    simpl.\n    destruct (string_eqdec s s); [reflexivity|congruence].\n  Qed.\n\n  Lemma merge_bindings_nodup {A} `{EqDec A eq} (l l0 l1:list (string*A)):\n    merge_bindings l l0 = Some l1 -> NoDup (domain l1).\n  Proof.\n    intros.\n    unfold merge_bindings in *.\n    destruct (compatible l l0); try congruence.\n    inversion H0.\n    apply is_list_sorted_NoDup_strlt.\n    apply (rec_concat_sort_sorted l l0).\n    reflexivity.\n  Qed.\n  \n  Lemma merge_bindings_compatible {A} `{EqDec A eq} (l l0 l1:list (string*A)):\n    merge_bindings l l0 = Some l1 -> compatible l l0 = true.\n  Proof.\n    intros.\n    unfold merge_bindings in H0.\n    destruct (compatible l l0); congruence.\n  Qed.\n\n  Lemma sorted_cons_is_compatible {A} `{EqDec A eq} (l:list (string*A)) (a:string*A):\n    is_list_sorted ODT_lt_dec (domain (a :: l)) = true ->\n    compatible_with (fst a) (snd a) l = true.\n  Proof.\n    intros.\n    assert (NoDup (domain (a :: l)))\n      by (apply is_list_sorted_NoDup_strlt; assumption).\n    unfold compatible_with.\n    destruct a; simpl.\n    inversion H1. subst.\n    assert (assoc_lookupr equiv_dec l s = None) by\n        (apply assoc_lookupr_nin_none; assumption).\n    rewrite H2.\n    reflexivity.\n  Qed.\n\n  Lemma compatible_self {A} `{EqDec A eq} (l:list (string*A)):\n    is_list_sorted ODT_lt_dec (domain l) = true ->\n    compatible l l = true.\n  Proof.\n    intros.\n    induction l; try reflexivity.\n    assert (is_list_sorted ODT_lt_dec (domain l) = true)\n      by (apply (@rec_sorted_skip_first string ODT_string _ l a); assumption).\n    assert (NoDup (domain (a::l)))\n      by (apply is_list_sorted_NoDup_strlt; assumption).\n    inversion H2. subst.\n    specialize (IHl H1).\n    simpl. rewrite andb_true_inversion.\n    destruct a; simpl.\n    unfold compatible_with; simpl.\n    assert (assoc_lookupr equiv_dec l s = None) by\n        (apply assoc_lookupr_nin_none; assumption).\n    rewrite H3.\n    destruct (equiv_dec s s); try congruence.\n    destruct (equiv_dec a a); try congruence.\n    split; try reflexivity.\n    apply compatible_cons_r; try assumption.\n    simpl.\n    unfold compatible_with.\n    assert (assoc_lookupr equiv_dec l s = None) by\n        (apply assoc_lookupr_nin_none; assumption).\n    rewrite H4; reflexivity.\n  Qed.\n\n  Lemma merge_self_sorted {A} `{EqDec A eq} (l:list (string*A)):\n    is_list_sorted ODT_lt_dec (domain l) = true ->\n    merge_bindings l l = Some l.\n  Proof.\n    intros.\n    unfold merge_bindings.\n    rewrite compatible_self; try assumption.\n    f_equal.\n    apply rec_concat_sort_self; assumption.\n  Qed.\n\n  Lemma merge_self_sorted_r {A} `{EqDec A eq} (l:list (string*A)):\n    is_list_sorted ODT_lt_dec (domain l) = true ->\n    merge_bindings l (rec_sort l) = Some (rec_sort l).\n  Proof.\n    intros.\n    rewrite rec_sorted_id; try assumption.\n    apply merge_self_sorted; assumption.\n  Qed.\n\n  Lemma same_domain_merge_bindings_eq\n        {A} `{EqDec A eq} (l₁ l₂ l₃:list (string*A)) :\n    NoDup (domain l₁) ->\n    domain l₁ = domain l₂ ->\n    merge_bindings l₁ l₂ = Some l₃ ->\n    l₁ = l₂.\n  Proof.\n    unfold merge_bindings.\n    match_case; intros compat nd eqd eqq.\n    invcs eqq.\n    apply (same_domain_compatible _ _ nd eqd compat).\n  Qed.\n\n  Definition compatible {A:Type} `{x:EqDec A eq} := @compatible string A _ _ _ _.\n  \n  Lemma merge_returns_compatible {A} `{equiv:EqDec A eq} (l1 l2 l3:list (string*A)):\n    is_list_sorted ODT_lt_dec (domain l1) = true ->\n    is_list_sorted ODT_lt_dec (domain l2) = true ->\n    compatible l1 l2 = true ->\n    rec_concat_sort l1 l2 = l3 ->\n    compatible l1 l3 = true.\n  Proof.\n    intros.\n    assert (NoDup (domain l1)) by (apply is_list_sorted_NoDup_strlt; assumption).\n    assert (NoDup (domain l2)) by (apply is_list_sorted_NoDup_strlt; assumption).\n    unfold merge_bindings in H2.\n    unfold compatible, LibUtilsCompat.compatible in *.\n    rewrite forallb_forall in H1.\n    rewrite forallb_forall; intros.\n    destruct x; simpl in *.\n    specialize (H1 (s,a) H5).\n    simpl in *.\n    rewrite <- H2.\n    unfold compatible_with in *.\n    unfold rec_concat_sort.\n    rewrite (@assoc_lookupr_drec_sort string ODT_string).\n    simpl in *; unfold equiv_dec, string_eqdec in *.\n    rewrite (@assoc_lookupr_app string).\n    case_eq (assoc_lookupr string_dec l2 s); intros.\n    assert ((@assoc_lookupr string A\n                            (@Equivalence.equiv string (@eq string)\n                                                (@eq_equivalence string))\n                            (@complement string\n                                         (@Equivalence.equiv string (@eq string)\n                                                             (@eq_equivalence string))) string_dec l2 s ) =\n            (@assoc_lookupr string A (@eq string)\n                            (fun s1 s2 : string => not (@eq string s1 s2)) string_dec l2 s)) by reflexivity.\n    rewrite H7 in *.\n    rewrite H6 in H1.\n    - assumption.\n    - assert (assoc_lookupr string_dec l1 s = Some a).\n      apply in_assoc_lookupr_nodup; assumption.\n      unfold string_eqdec.\n      rewrite H7.\n      destruct (equiv a a); congruence.\n  Qed.\n  \n  Lemma merge_idem {A} `{EqDec A eq} (l l0 l1:list (string*A)):\n    is_list_sorted ODT_lt_dec (domain l) = true ->\n    is_list_sorted ODT_lt_dec (domain l0) = true ->\n    merge_bindings l l0 = Some l1 ->\n    merge_bindings l l1 = Some l1.\n  Proof.\n    intros.\n    unfold merge_bindings in *.\n    case_eq (compatible l l0); intros;\n      unfold compatible in *; rewrite H3 in H2; try congruence.\n    inversion H2; clear H2.\n    assert (compatible l (rec_concat_sort l l0) = true)\n      by (apply (merge_returns_compatible l l0 (rec_concat_sort l l0) H0 H1 H3); reflexivity).\n    unfold compatible in *. rewrite H2.\n    rewrite rec_concat_sort_idem; try assumption; reflexivity.\n  Qed.\n\n(* merge_idem isn't true unless l is without duplicates! Here is a\n     counter example.\n   Open Scope string.\n   Definition tup1 := (\"a\",1) :: (\"b\",2) :: (\"a\", 3) :: nil.\n   Definition tup2 := (\"c\",2) :: nil.\n   Eval compute in (merge_bindings tup1 tup2).\n   Definition tup3 := [(\"a\", 3); (\"b\", 2); (\"c\", 2)].\n   Eval compute in (compatible tup1 tup3).\n *)\n\nEnd MergeBindings.\n\nHint Resolve @merge_bindings_sorted : list.\n\n", "meta": {"author": "CertRL", "repo": "CertRLanon", "sha": "ba50abfb13c9c49abda8ffaad23fe76dcd4bf6ec", "save_path": "github-repos/coq/CertRL-CertRLanon", "path": "github-repos/coq/CertRL-CertRLanon/CertRLanon-ba50abfb13c9c49abda8ffaad23fe76dcd4bf6ec/coq/lib_utils/LibUtilsBindings.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.2955139675052756}}
{"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.Common.CommonDefinitions.\nRequire Export depoolContract.Scenarios.Common.cutWithdrawalValueMove.\nRequire Export depoolContract.Scenarios.Common.UtilProofs.\nRequire Export depoolContract.Scenarios.Correctness.InvestParamsCorrect.\n\nDefinition _cutWithdrawalValueMoveUpdatedInvestParams\n    (i : RoundsBase_ι_InvestParams)\n    (a : Z)\n    (lwt : Z) :=\n    {$ {$ i with RoundsBase_ι_InvestParams_ι_amount := a $}\n            with RoundsBase_ι_InvestParams_ι_lastWithdrawalTime := lwt $}.\n\nDefinition cutWithdrawalValueMoveUpdatedInvestParams (l : Ledger) (i : RoundsBase_ι_InvestParams) :=\n    _cutWithdrawalValueMoveUpdatedInvestParams\n    i\n    (newAmount l i)\n    (newLastWithdrawalTime l i).\n\nLemma cutWithdrawalValueMove_locallyCorrect : forall l i,\n    investParamsCorrectLocally l i ->\n    investParamsCorrectLocally l (cutWithdrawalValueMoveUpdatedInvestParams l i).\nProof.\nintros. unfold cutWithdrawalValueMoveUpdatedInvestParams.\nunfold _cutWithdrawalValueMoveUpdatedInvestParams. unfold investParamsCorrectLocally in *.\nsplit. inversion H. assumption.\ninversion H. clear H. unfold _investParamsNowCorrect in *. simpl.\nunfold newLastWithdrawalTime. unfold periodQty. unfold _investParamsPositive in H1.\ninversion_clear H1. inversion_clear H2. inversion_clear H1. inversion_clear H4.\nsplit.\napply Z.le_trans with (n := (RoundsBase_ι_InvestParams_ι_lastWithdrawalTime\ni +\n(now l -\nRoundsBase_ι_InvestParams_ι_lastWithdrawalTime\n i) /\nRoundsBase_ι_InvestParams_ι_withdrawalPeriod\ni *\nRoundsBase_ι_InvestParams_ι_withdrawalPeriod i))\n(p := now l)\n(m := RoundsBase_ι_InvestParams_ι_lastWithdrawalTime\ni +\n(now l -\nRoundsBase_ι_InvestParams_ι_lastWithdrawalTime\n i)). apply Z.add_le_mono_l. rewrite Z.mul_comm. apply Z_mult_div_ge. lia. lia.\nunfold _investParamsPositive in *. inversion_clear H5.\nsplit. split. simpl. unfold newLastWithdrawalTime. apply Z.add_pos_nonneg. assumption.\napply Z.mul_nonneg_nonneg. unfold periodQty. unfold _investParamsNowCorrect in H0.\napply Z.div_pos. apply Z.le_0_sub. assumption. assumption. apply Z.lt_le_incl. assumption.\nsplit. simpl. assumption. split. simpl. assumption. simpl. assumption.\nunfold _investParamsAmountMinStake. simpl. unfold newAmount. unfold withdrawal.\ncase_eq(RoundsBase_ι_InvestParams_ι_amount i - initialWithdrawal l i <? m_minStake l).\nintros. setoid_rewrite H5. left. lia. intros. setoid_rewrite H5. right. apply Z.ltb_ge.\nassumption.\nQed.\n\nLemma cutWithdrawalValueMove_withdrawal_plus_newAmount : forall l i,\n    newAmount l i + withdrawal l i = RoundsBase_ι_InvestParams_ι_amount i.\nProof.\nintros. unfold newAmount. lia.\nQed.\n\nLemma cutWithdrawalValueMove_lastWithdrawalTime_later: forall l i,\n    investParamsCorrectLocally l i ->\n    RoundsBase_ι_InvestParams_ι_lastWithdrawalTime i <= newLastWithdrawalTime l i.\nProof.\nintros. unfold newLastWithdrawalTime. apply Z.le_sub_le_add_l. rewrite Z.sub_diag.\nunfold investParamsCorrectLocally in H. inversion_clear H. inversion_clear H1.\ninversion_clear H2. apply Z.mul_nonneg_nonneg. unfold _investParamsPositive in H1.\ninversion_clear H1. inversion_clear H4. inversion_clear H5.\nunfold periodQty. apply Z.div_pos. unfold _investParamsNowCorrect in H0.\napply Zle_minus_le_0. assumption. assumption. apply Z.lt_le_incl.\ninversion_clear H1. inversion_clear H4. assumption.\nQed.\n\nLemma cutWithdrawalValueMove_withdrawal_pos: forall l i,\n    investParamsCorrectLocally l i ->\n    0 < periodQty l i ->\n    0 < RoundsBase_ι_InvestParams_ι_amount i ->\n    0 < withdrawal l i.\nProof.\nintros. unfold withdrawal. case_eq\n(RoundsBase_ι_InvestParams_ι_amount i - initialWithdrawal l i <? m_minStake l).\nintros. setoid_rewrite H2. assumption. intros. setoid_rewrite H2.\nunfold investParamsCorrectLocally in H. inversion_clear H. unfold initialWithdrawal.\nunfold cutWithdrawalValueMove.DePoolFuncs.intMin. simpl.\ncase_eq(periodQty l i * RoundsBase_ι_InvestParams_ι_withdrawalValue i <=?\nRoundsBase_ι_InvestParams_ι_amount i) ; intros ; setoid_rewrite H. apply Z.mul_pos_pos.\nassumption. inversion_clear H4. inversion_clear H6. unfold _investParamsPositive in H4.\ninversion_clear H4. inversion_clear H8. inversion_clear H9. assumption. assumption.\nQed.\n\nLemma cutWithdrawalValueMove_lastWithdrawalTime_strictly_later: forall l i,\n    investParamsCorrectLocally l i ->\n    0 < withdrawal l i ->\n    RoundsBase_ι_InvestParams_ι_lastWithdrawalTime i < newLastWithdrawalTime l i.\nProof.\nintros. unfold investParamsCorrectLocally in H. inversion_clear H. inversion_clear H2.\nunfold withdrawal in H0. unfold _investParamsNowCorrect in H. inversion_clear H3.\nunfold _investParamsPositive in H2. inversion_clear H2. inversion_clear H5.\ninversion_clear H6.\nunfold newLastWithdrawalTime. rewrite Z.add_comm. apply Zlt_0_minus_lt. rewrite Z.add_simpl_r.\nrewrite Z.mul_comm. apply Z.mul_pos_pos. assumption.\ncase_eq( RoundsBase_ι_InvestParams_ι_amount i - initialWithdrawal l i <? m_minStake l).\nintros. setoid_rewrite H6 in H0. apply Zlt_is_lt_bool in H6.\ncase_eq(initialWithdrawal l i <? 0). intros. apply Zlt_is_lt_bool in H8.\nunfold initialWithdrawal in H8. unfold cutWithdrawalValueMove.DePoolFuncs.intMin in H8.\nsimpl in H8.\ncase_eq(periodQty l i * RoundsBase_ι_InvestParams_ι_withdrawalValue i <=?\nRoundsBase_ι_InvestParams_ι_amount i). intros. setoid_rewrite H9 in H8. apply Z.lt_mul_0 in H8.\ninversion H8. inversion H10. unfold periodQty in H11. apply div_neg_neg_or in H11.\ninversion H11. apply -> Z.lt_sub_0 in H13. apply Zlt_not_le in H13. contradiction.\napply Zlt_not_le in H13. apply Z.lt_le_incl in H2. contradiction. inversion H10. assumption.\nintros. setoid_rewrite H9 in H8. apply Zlt_not_le in H8. apply Z.lt_le_incl in H0. contradiction.\nintros. apply neg_lt0b_ge0 in H8. inversion H8. rewrite H9 in H6. rewrite Z.sub_0_r in H6.\nunfold _investParamsAmountMinStake in H4. inversion H4. setoid_rewrite <- H10 in H0. lia.\napply Zlt_not_le in H6. contradiction. unfold initialWithdrawal in H9.\nunfold cutWithdrawalValueMove.DePoolFuncs.intMin in H9. simpl in H9.\ncase_eq(periodQty l i * RoundsBase_ι_InvestParams_ι_withdrawalValue i <=?\n    RoundsBase_ι_InvestParams_ι_amount i). intros. setoid_rewrite H10 in H9.\napply Z.mul_pos_cancel_r in H9 ; assumption. intros. apply Z.leb_gt in H10.\napply Z.lt_trans with (n := 0)\n                    (m:= RoundsBase_ι_InvestParams_ι_amount i)\n                    (p := periodQty l i * RoundsBase_ι_InvestParams_ι_withdrawalValue i)\n                    in H0.\napply Z.mul_pos_cancel_r in H0 ; assumption. assumption. intros. setoid_rewrite H6 in H0.\nunfold initialWithdrawal in H0. unfold cutWithdrawalValueMove.DePoolFuncs.intMin in H0.\nsimpl in H0.\ncase_eq(periodQty l i * RoundsBase_ι_InvestParams_ι_withdrawalValue i <=?\n    RoundsBase_ι_InvestParams_ι_amount i). intros. setoid_rewrite H8 in H0.\napply Z.mul_pos_cancel_r in H0 ; assumption. intros. setoid_rewrite H8 in H0. apply Z.leb_gt in H8.\napply Z.lt_trans with (n := 0)\n                    (m:= RoundsBase_ι_InvestParams_ι_amount i)\n                    (p := periodQty l i * RoundsBase_ι_InvestParams_ι_withdrawalValue i)\n                    in H0.\napply Z.mul_pos_cancel_r in H0 ; assumption. assumption.\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/Scenarios/Common/cutWithdrawalValueProofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7057850154599563, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.29551000464263927}}
{"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.AST.\nRequire Import compcert.common.Values.\nRequire Import compcert.common.Memory.\nRequire Import compcert.common.Events.\nRequire Import compcert.common.Globalenvs.\n\nRequire Import sepcomp.mem_lemmas.\n\nNotation val_inject:=Val.inject.\n\n(*A value that is (if its a pointer) not dangling wrt m - a condition\n like this will probably be need to imposed on after-external return\n values (and thus also on the values returned by halted)*)\nDefinition val_valid (v:val) (m:mem):Prop :=\n     match v with Vptr b ofs => Mem.valid_block m b | _ => True\n     end.\n\n(*In fact val_valid is a slight relaxtion of valid_pointer*)\nLemma valid_ptr_val_valid: forall b ofs m,\n    Mem.valid_pointer m b ofs = true -> val_valid (Vptr b (Int.repr ofs)) m.\nProof. intros.\n  apply Mem.valid_pointer_nonempty_perm in H. eapply Mem.perm_valid_block. apply H.\nQed.\n\nLemma extends_valvalid: forall m1 m2 (Ext: Mem.extends m1 m2) v,\n        val_valid v m1 <-> val_valid v m2.\nProof. intros.\n  split; intros. destruct v; simpl in *; try econstructor.\n     eapply (Mem.valid_block_extends _ _ _ Ext). apply H.\n  destruct v; simpl in *; try econstructor.\n     eapply (Mem.valid_block_extends _ _ _ Ext). apply H.\nQed.\n\nLemma inject_valvalid: forall j m1 m2 (Inj: Mem.inject j m1 m2) v2 (V:val_valid v2 m2) v1,\n             val_inject j v1 v2 -> val_valid v1 m1.\nProof. intros.\n  inv H; repeat constructor.\n     simpl in *. eapply Mem.valid_block_inject_1; eassumption.\nQed.\n\n(*Preservation of val_valid along an injection only holds\n  if the LHS value is defined*)\nLemma inject_valvalid_1:\n  forall (j : meminj) (m1 m2 : mem),\n  Mem.inject j m1 m2 ->\n  forall v1 : val,\n  val_valid v1 m1 -> forall v2 : val, val_inject j v1 v2 ->\n  match v1 with Vundef => True\n      | _ => val_valid v2 m2\n  end.\nProof. intros.\n  destruct v1; auto; inv H1; auto.\n  simpl in *.\n  eapply Mem.valid_block_inject_2; eassumption.\nQed.\n\n(*memories that do not contain \"dangling pointers\"*)\nDefinition mem_wd m := Mem.inject_neutral (Mem.nextblock m) m.\n\nLemma align_chunk_0: forall chunk, (align_chunk chunk | 0).\nProof.\n  intros chunk. destruct chunk; simpl; apply Z.divide_0_r.\nQed.\n\nLemma mem_wdI: forall m,\n  (forall (b:block) ofs  (R:Mem.perm m b ofs Cur Readable),\n    memval_inject  (Mem.flat_inj (Mem.nextblock m))\n    (ZMap.get ofs (PMap.get b (Mem.mem_contents m)))\n    (ZMap.get ofs (PMap.get b (Mem.mem_contents m)))) -> mem_wd m.\nProof. intros.\n  split; intros.\n     apply flatinj_E in  H0. destruct H0 as [? [? ?]]; subst. rewrite Zplus_0_r. trivial.\n     apply flatinj_E in  H0. destruct H0 as [? [? ?]]; subst. apply align_chunk_0.\n     apply flatinj_E in  H0. destruct H0 as [? [? ?]]; subst. rewrite Zplus_0_r.\n        apply H. apply H1.\nQed.\n\nLemma mem_wd_E: forall m, mem_wd m ->  Mem.inject (Mem.flat_inj (Mem.nextblock m)) m m.\nProof. intros. apply Mem.neutral_inject. apply H. Qed.\n\nLemma meminj_split_flatinjR: forall j m m' (J:Mem.inject j m' m), mem_wd m ->\n     j = compose_meminj j (Mem.flat_inj (Mem.nextblock m)).\nProof. intros. apply mem_wd_E in H.\n   unfold  compose_meminj.\n   apply extensionality. intro b.\n   remember (j b).\n   destruct o; trivial. destruct p. unfold Mem.flat_inj in *.\n   destruct (plt b0 (Mem.nextblock m)).\n     rewrite Zplus_0_r. trivial.\n   inv J. apply eq_sym in Heqo. specialize (mi_mappedblocks _ _ _ Heqo).\n               exfalso. unfold Mem.valid_block in mi_mappedblocks. xomega.\nQed.\n\nLemma meminj_split_flatinjL: forall j m m' (J:Mem.inject j m m'), mem_wd m ->\n     j = compose_meminj (Mem.flat_inj (Mem.nextblock m)) j.\nProof. intros. apply mem_wd_E in H.\n   unfold  compose_meminj.\n   apply extensionality. intro b.\n   unfold Mem.flat_inj in *.\n   destruct (plt b (Mem.nextblock m)).\n     remember (j b). destruct o. destruct p0.  rewrite Zplus_0_l. trivial. trivial.\n  inv J. apply mi_freeblocks. assumption.\nQed.\n\nLemma mem_wd_inject_splitL: forall j m1 m2\n              (J:Mem.inject j m1 m2)  (WD: mem_wd m1),\n     Mem.inject (Mem.flat_inj (Mem.nextblock m1)) m1 m1\n     /\\ j = compose_meminj (Mem.flat_inj (Mem.nextblock m1)) j.\nProof. intros.\n    split. apply mem_wd_E. apply WD.\n    eapply (meminj_split_flatinjL _ _ _ J WD).\nQed.\n\nLemma mem_wd_inject_splitR: forall j m1 m2\n              (J:Mem.inject j m1 m2)  (WD: mem_wd m2),\n     Mem.inject (Mem.flat_inj (Mem.nextblock m2)) m2 m2\n     /\\ j = compose_meminj j (Mem.flat_inj (Mem.nextblock m2)).\nProof. intros.\n    split. apply mem_wd_E. apply WD.\n    eapply (meminj_split_flatinjR _ _ _ J WD).\nQed.\n\n(*Preservation of mem_wd by memory operations*)\nLemma mem_wd_empty: mem_wd Mem.empty.\nProof.  apply Mem.empty_inject_neutral. Qed.\n\nLemma  mem_wd_alloc: forall m b lo hi m' (ALL: Mem.alloc m lo hi = (m',b))\n     (WDm: mem_wd m), mem_wd m'.\nProof. intros. unfold mem_wd in *.\n  rewrite (Mem.nextblock_alloc _ _ _ _ _ ALL).\n  eapply (Mem.alloc_inject_neutral _ _ _ _ _ _ ALL); try omega.\n  inv WDm.\n         split; intros.\n             apply flatinj_E in H. destruct H as [? [? ?]]; subst. rewrite Zplus_0_r. assumption.\n             apply flatinj_E in H. destruct H as [? [? ?]]; subst. apply align_chunk_0.\n             apply flatinj_E in H. destruct H as [? [? ?]]; subst. rewrite Zplus_0_r.\n                 assert (X: Mem.flat_inj (Mem.nextblock m) b1 = Some (b1, 0)).\n                     apply flatinj_I. apply (Mem.perm_valid_block _ _ _ _ _ H0).\n                  specialize (mi_memval _ _ _ _ X H0). rewrite Zplus_0_r in mi_memval.\n                  eapply memval_inject_incr; try eassumption.\n                       intros bb; intros.\n                        eapply flatinj_mono; try eassumption; xomega.\n       xomega.\nQed.\n\nLemma  mem_wd_drop: forall m b lo hi p m' (DROP: Mem.drop_perm m b lo hi p = Some m')\n     (WDm: mem_wd m), Mem.valid_block m b -> mem_wd m'.\nProof. intros. unfold mem_wd in *.\n  rewrite (Mem.nextblock_drop _ _ _ _ _ _ DROP).\n  eapply (Mem.drop_inject_neutral _ _ _ _ _ _ _ DROP); trivial.\nQed.\n\nLemma free_neutral: forall (thr : block) (m : mem) (lo hi : Z) (b : block) (m' : Mem.mem')\n  (FREE: Mem.free m b lo hi = Some m'),\n  Mem.inject_neutral thr m -> Mem.inject_neutral thr m'.\nProof. intros. inv H.\n  split; intros.\n     apply flatinj_E in H. destruct H as [? [? ?]]; subst. rewrite Zplus_0_r. assumption.\n     apply flatinj_E in H. destruct H as [? [? ?]]; subst. apply align_chunk_0.\n     apply flatinj_E in H. destruct H as [? [? ?]]; subst. rewrite Zplus_0_r.\n        assert (X: Mem.flat_inj thr b1 = Some (b1,0)). apply flatinj_I. assumption.\n        assert (Y:= Mem.perm_free_3 _ _ _ _ _ FREE _ _ _ _ H0).\n         specialize (mi_memval _ _ _ _ X Y). rewrite Zplus_0_r in *.\n         rewrite (Mem.free_result _ _ _ _ _ FREE) in *. simpl in *. apply mi_memval.\nQed.\n\nLemma mem_wd_free: forall m b lo hi m' (WDm: mem_wd m)\n  (FREE: Mem.free m b lo hi = Some m'), mem_wd m'.\nProof. intros. unfold mem_wd in *.\n  eapply free_neutral. apply FREE.\n   rewrite (Mem.nextblock_free _ _ _ _ _ FREE). assumption.\nQed.\n\nLemma mem_wd_store: forall m b ofs v m' chunk (WDm: mem_wd m)\n  (ST: Mem.store chunk m b ofs v = Some m')\n  (V: val_valid v m), mem_wd m'.\nProof. intros. unfold mem_wd in *.\n  eapply Mem.store_inject_neutral. apply ST.\n      rewrite (Mem.nextblock_store _ _ _ _ _ _ ST). assumption.\n      assert (X:= Mem.store_valid_access_3 _ _ _ _ _ _ ST).\n          rewrite (Mem.nextblock_store _ _ _ _ _ _ ST).\n           apply (Mem.valid_access_implies _ _ _ _ _  Nonempty) in X.\n                apply Mem.valid_access_valid_block in X. apply X.\n            constructor.\n      rewrite (Mem.nextblock_store _ _ _ _ _ _ ST).\n          destruct v; try solve [constructor].\n            econstructor. eapply flatinj_I. apply V.\n                          rewrite Int.add_zero. trivial.\nQed.\n\nLemma extends_memwd:\nforall m1 m2 (Ext: Mem.extends m1 m2), mem_wd m2 -> mem_wd m1.\nProof.\n  intros. eapply mem_wdI. intros.\n  assert (Mem.perm m2 b ofs Cur Readable).\n    eapply (Mem.perm_extends _ _ _ _ _ _ Ext R).\n  assert (Mem.valid_block m2 b).\n     apply (Mem.perm_valid_block _ _ _ _ _ H0).\n  destruct Ext. rewrite mext_next.\n  assert (Mem.flat_inj (Mem.nextblock m2) b = Some (b,0)).\n    apply flatinj_I. apply H1.\n  destruct mext_inj. specialize (mi_memval b ofs b 0 (eq_refl _) R).\n  rewrite Zplus_0_r in mi_memval.\n  destruct H. specialize (mi_memval0 b ofs b 0 H2 H0).\n  rewrite Zplus_0_r in mi_memval0.\n  remember (ZMap.get ofs (PMap.get b (Mem.mem_contents m1))) as v.\n  destruct v. repeat econstructor.\n  econstructor.\n  econstructor.\n  destruct v; try constructor.\n  econstructor.\n    eapply flatinj_I. inv mi_memval.\n    inv H3. inv H5. rewrite Int.add_zero in H6.\n      rewrite <- H6 in mi_memval0. simpl in mi_memval0.\n     inv mi_memval0. inversion H3.\n      apply flatinj_E in H7. apply H7.\n   rewrite Int.add_zero. reflexivity.\nQed.\n\nRequire Import sepcomp.reach.\n\nInductive valid_genv {F V:Type} (ge:Genv.t F V) (m:mem) : Type :=\n  mk_valid_genv :\n    (forall b, isGlobalBlock ge b=true -> val_valid (Vptr b Int.zero) m) ->\n    (forall b f, Genv.find_funct_ptr ge b = Some f -> val_valid (Vptr b Int.zero) m) ->\n    valid_genv ge m.\n\nLemma valid_genv_alloc: forall {F V:Type} (ge:Genv.t F V) (m m1:mem) lo hi b\n    (ALLOC: Mem.alloc m lo hi = (m1,b)) (G: valid_genv ge m), valid_genv ge m1.\nProof. intros. case G; intros. constructor; intros.\n  apply (Mem.valid_block_alloc _ _ _ _ _ ALLOC).\n  apply (v _ H).\n  apply (Mem.valid_block_alloc _ _ _ _ _ ALLOC).\n  apply (v0 _ _ H).\nQed.\n\nLemma valid_genv_store: forall {F V:Type} (ge:Genv.t F V) m m1 b ofs v chunk\n    (STORE: Mem.store chunk m b ofs v = Some m1)\n     (G: valid_genv ge m), valid_genv ge m1.\nProof. intros. case G; intros. constructor; intros.\n  apply (Mem.store_valid_block_1 _ _ _ _ _ _ STORE).\n  apply (v0 _ H).\n  apply (Mem.store_valid_block_1 _ _ _ _ _ _ STORE).\n  apply (v1 _ _ H).\nQed.\n\nLemma valid_genv_store_zeros: forall {F V:Type} (ge:Genv.t F V) m m1 b y z\n    (STORE_ZERO: store_zeros m b y z = Some m1)\n    (G: valid_genv ge m), valid_genv ge m1.\nProof. intros. case G; intros. constructor; intros.\n  apply Genv.store_zeros_nextblock in STORE_ZERO.\n  specialize (v _ H); simpl in *.\n  unfold Mem.valid_block in *.\n  rewrite STORE_ZERO. apply G; auto.\n  specialize (v0 _ _ H); simpl in *.\n  apply Genv.store_zeros_nextblock in STORE_ZERO.\n  unfold Mem.valid_block in *.\n  rewrite STORE_ZERO. auto.\nQed.\n\nLemma mem_wd_store_zeros: forall m b p n m1\n    (STORE_ZERO: store_zeros m b p n = Some m1) (WD: mem_wd m), mem_wd m1.\nProof. intros until n. functional induction (store_zeros m b p n); intros.\n  inv STORE_ZERO; tauto.\n  apply (IHo _ STORE_ZERO); clear IHo.\n      eapply (mem_wd_store m). apply WD. apply e0. simpl; trivial.\n  inv STORE_ZERO.\nQed.\n\nLemma valid_genv_drop: forall {F V:Type} (ge:Genv.t F V) (m m1:mem) b lo hi p\n    (DROP: Mem.drop_perm m b lo hi p = Some m1) (G: valid_genv ge m),\n    valid_genv ge m1.\nProof. intros. case G; intros. constructor; intros.\n  apply (Mem.drop_perm_valid_block_1 _ _ _ _ _ _ DROP).\n  apply (v _ H); auto.\n  apply (Mem.drop_perm_valid_block_1 _ _ _ _ _ _ DROP).\n  apply (v0 _ _ H); auto.\nQed.\n\nLemma mem_wd_store_init_data: forall {F V} (ge: Genv.t F V) a (b:block) (z:Z)\n  m1 m2 (SID:Genv.store_init_data ge m1 b z a = Some m2),\n  valid_genv ge m1 -> mem_wd m1 -> mem_wd m2.\nProof. intros F V ge a.\n  destruct a; simpl; intros;\n      try apply (mem_wd_store _ _ _ _ _ _ H0 SID); simpl; trivial.\n   inv SID; trivial.\n   remember (Genv.find_symbol ge i) as d.\n     destruct d; inv SID.\n     eapply (mem_wd_store _ _ _ _ _ _ H0 H2).\n    apply eq_sym in Heqd.\n    destruct H.\n    apply v.\n    unfold isGlobalBlock.\n    rewrite orb_true_iff.\n    unfold genv2blocksBool; simpl.\n    apply Genv.find_invert_symbol in Heqd.\n    rewrite Heqd; left; auto.\nQed.\n\nLemma valid_genv_store_init_data:\n  forall {F V}  (ge: Genv.t F V) a (b:block) (z:Z) m1 m2\n  (SID: Genv.store_init_data ge m1 b z a = Some m2),\n  valid_genv ge m1 -> valid_genv ge m2.\nProof. intros F V ge a.\n  destruct a; simpl; intros; inv H; constructor;\n    try (intros b0 X; eapply Mem.store_valid_block_1 with (b':=b0); eauto;\n          apply H0; auto);\n    try (intros b0 ? X; eapply Mem.store_valid_block_1 with (b':=b0); eauto;\n          eapply H1; eauto);\n    try (inv SID; auto).\n  intros.\n  remember (Genv.find_symbol ge i) as d.\n  destruct d; inv H2.\n  eapply Mem.store_valid_block_1; eauto.\n  apply eq_sym in Heqd.\n  eapply H0; eauto.\n  revert H2. destruct (Genv.find_symbol ge i); intros; try congruence.\n  eapply Mem.store_valid_block_1; eauto.\n  eapply H1; eauto.\nQed.\n\nLemma mem_wd_store_init_datalist: forall {F V} (ge: Genv.t F V) l (b:block)\n  (z:Z) m1 m2 (SID: Genv.store_init_data_list ge m1 b z l = Some m2),\n  valid_genv ge m1 -> mem_wd m1 -> mem_wd m2.\nProof. intros F V ge l.\n  induction l; simpl; intros.\n    inv SID. trivial.\n  remember (Genv.store_init_data ge m1 b z a) as d.\n  destruct d; inv SID; apply eq_sym in Heqd.\n  apply (IHl _ _ _ _ H2); clear IHl H2.\n     eapply valid_genv_store_init_data. apply Heqd. apply H.\n  eapply mem_wd_store_init_data. apply Heqd. apply H. apply H0.\nQed.\n\nLemma valid_genv_store_init_datalist: forall {F V} (ge: Genv.t F V) l (b:block)\n  (z:Z) m1 m2 (SID: Genv.store_init_data_list ge m1 b z l = Some m2),\n   valid_genv ge m1 -> valid_genv ge m2.\nProof. intros F V ge l.\n  induction l; simpl; intros.\n    inv SID. trivial.\n  remember (Genv.store_init_data ge m1 b z a) as d.\n  destruct d; inv SID; apply eq_sym in Heqd.\n  apply (IHl _ _ _ _ H1); clear IHl H1.\n     eapply valid_genv_store_init_data. apply Heqd. apply H.\nQed.\n\nLemma mem_wd_alloc_global: forall  {F V} (ge: Genv.t F V) a m0 m1\n   (GA: Genv.alloc_global ge m0 a = Some m1),\n   mem_wd m0 -> valid_genv ge m0 -> mem_wd m1.\nProof. intros F V ge a.\ndestruct a; simpl. intros.\ndestruct g.\n  remember (Mem.alloc m0 0 1) as mm. destruct mm.\n    apply eq_sym in Heqmm.\n    specialize (mem_wd_alloc _ _ _ _ _ Heqmm). intros.\n     eapply (mem_wd_drop _ _ _ _ _  _ GA).\n    apply (H1 H).\n    apply (Mem.valid_new_block _ _ _ _ _ Heqmm).\nremember (Mem.alloc m0 0 (init_data_list_size (AST.gvar_init v)) ) as mm.\n  destruct mm. apply eq_sym in Heqmm.\n  remember (store_zeros m b 0 (init_data_list_size (AST.gvar_init v)))\n           as d.\n  destruct d; inv GA; apply eq_sym in Heqd.\n  remember (Genv.store_init_data_list ge m2 b 0 (AST.gvar_init v)) as dd.\n  destruct dd; inv H2; apply eq_sym in Heqdd.\n  eapply (mem_wd_drop _ _ _ _ _ _ H3); clear H3.\n    eapply (mem_wd_store_init_datalist _ _ _ _ _ _ Heqdd).\n    apply (valid_genv_store_zeros _ _ _ _ _ _ Heqd).\n    apply (valid_genv_alloc ge _ _ _ _ _ Heqmm H0).\n  apply (mem_wd_store_zeros _ _ _ _ _ Heqd).\n    apply (mem_wd_alloc _ _ _ _ _ Heqmm H).\n  unfold Mem.valid_block.\n     apply Genv.store_init_data_list_nextblock in Heqdd.\n           rewrite Heqdd. clear Heqdd.\n      apply Genv.store_zeros_nextblock in Heqd. rewrite Heqd; clear Heqd.\n      apply (Mem.valid_new_block _ _ _ _ _  Heqmm).\nQed.\n\nLemma valid_genv_alloc_global: forall  {F V} (ge: Genv.t F V) a m0 m1\n   (GA: Genv.alloc_global ge m0 a = Some m1),\n   valid_genv ge m0 -> valid_genv ge m1.\nProof. intros F V ge a.\ndestruct a; simpl. intros.\ndestruct g.\n  remember (Mem.alloc m0 0 1) as d. destruct d.\n    apply eq_sym in Heqd.\n    apply (valid_genv_drop _ _ _ _ _ _ _ GA).\n    apply (valid_genv_alloc _ _ _ _ _ _ Heqd H).\nremember (Mem.alloc m0 0 (init_data_list_size (AST.gvar_init v)) )\n         as Alloc.\n  destruct Alloc. apply eq_sym in HeqAlloc.\n  remember (store_zeros m b 0\n           (init_data_list_size (AST.gvar_init v))) as SZ.\n  destruct SZ; inv GA; apply eq_sym in HeqSZ.\n  remember (Genv.store_init_data_list ge m2 b 0 (AST.gvar_init v)) as Drop.\n  destruct Drop; inv H1; apply eq_sym in HeqDrop.\n  eapply (valid_genv_drop _ _ _ _ _ _ _ H2); clear H2.\n  eapply (valid_genv_store_init_datalist _ _ _ _ _ _ HeqDrop). clear HeqDrop.\n  apply (valid_genv_store_zeros _ _ _ _ _ _ HeqSZ).\n    apply (valid_genv_alloc _ _ _ _ _ _ HeqAlloc H).\nQed.\n\nLemma valid_genv_alloc_globals:\n   forall F V (ge: Genv.t F V) init_list m0 m\n   (GA: Genv.alloc_globals ge m0 init_list = Some m),\n   valid_genv ge m0 -> valid_genv ge m.\nProof. intros F V ge l.\ninduction l; intros; simpl in *.\n  inv GA. assumption.\nremember (Genv.alloc_global ge m0 a) as d.\n  destruct d; inv GA. apply eq_sym in Heqd.\n  eapply (IHl  _ _  H1). clear H1.\n    apply (valid_genv_alloc_global _ _ _ _ Heqd H).\nQed.\n\nLemma mem_wd_alloc_globals:\n   forall F V (ge: Genv.t F V) init_list m0 m\n   (GA: Genv.alloc_globals ge m0 init_list = Some m),\n   mem_wd m0 -> valid_genv ge m0 -> mem_wd m.\nProof. intros F V ge l.\ninduction l; intros; simpl in *.\n  inv GA. assumption.\nremember (Genv.alloc_global ge m0 a) as d.\n  destruct d; inv GA. apply eq_sym in Heqd.\neapply (IHl  _ _  H2).\n    apply (mem_wd_alloc_global ge _ _ _ Heqd H H0).\n    apply (valid_genv_alloc_global _ _ _ _ Heqd H0).\nQed.\n\n(*POPL-compcomp used the following lemma to prove mem_wd_load:\nLemma decode_val_pointer_inv:\n  forall chunk mvl b ofs,\n  decode_val chunk mvl = Vptr b ofs ->\n  chunk = Mint32 /\\ mvl = inj_value Q32 (Vptr b ofs).\n A version of this lemma is in\n  CompCert 2.3, Memdata.v,\n but missing from CompCert 2.4.  I'm not even sure\n it's true in CompCert 2.4.  -A.W.A.\n\nIn CompCert2.5, the proof of mem_wd_load uses the new load_ptr_is_fragment, recently added to mem_lemmas*)\nLemma mem_wd_load: forall m ch b ofs v\n  (LD: Mem.load ch m b ofs = Some v)\n  (WD : mem_wd m), val_valid v m.\nProof. intros.\n  destruct v; simpl; trivial.\n  destruct (load_ptr_is_fragment _ _ _ _ _ _ LD) as [q [n FRAG]].\n  destruct (Mem.load_valid_access _ _ _ _ _ LD) as [Perms Align].\n  apply Mem.load_result in LD.\n  destruct WD.\n  assert (Arith: ofs <= ofs < ofs + (size_chunk ch)). specialize (size_chunk_pos ch); omega.\n  specialize (Perms _ Arith).\n  assert (VB:= Mem.perm_valid_block _ _ _ _ _ Perms).\n  assert (Z:= flatinj_I (Mem.nextblock m) b VB).\n  specialize (mi_memval _ _ _ _ Z Perms).\n  rewrite Zplus_0_r in mi_memval. rewrite FRAG in mi_memval.\n  inversion mi_memval. subst.\n  inversion H0.\n  apply flatinj_E in H3. apply H3.\nQed.\n\nLemma mem_wd_storebytes: forall m b ofs bytes m' (WDm: mem_wd m)\n  (ST: Mem.storebytes m b ofs bytes = Some m')\n  (BytesValid: forall v, In v bytes ->\n               memval_inject (Mem.flat_inj (Mem.nextblock m)) v v),\n   mem_wd m'.\nProof. intros. apply mem_wdI. intros.\n  assert (F: Mem.flat_inj (Mem.nextblock m) b0 = Some (b0, 0)).\n        apply flatinj_I.\n        apply (Mem.storebytes_valid_block_2 _ _ _ _ _ ST).\n        eapply Mem.perm_valid_block; eassumption.\n  apply mem_wd_E in WDm.\n  assert (P:= Mem.perm_storebytes_2 _ _ _ _ _ ST _ _ _ _ R).\n  specialize (Mem.mi_memval _ _ _ (Mem.mi_inj _ _ _ WDm) _ _ _ _ F P).\n  rewrite Zplus_0_r.\n  intros MVI.\n  rewrite (Mem.nextblock_storebytes _ _ _ _ _ ST).\n  rewrite (Mem.storebytes_mem_contents _ _ _ _ _ ST).\n  remember (eq_block b0 b).\n  destruct s; subst; clear Heqs.\n  (*case b0=b*)\n    rewrite PMap.gss.\n    remember (zlt ofs0 ofs) as d.\n    destruct d; clear Heqd.\n    (*case ofs0 < ofs*)\n      rewrite Mem.setN_outside; try (left; assumption).\n      assumption.\n    (*case ofs0 >= ofs*)\n      remember (zlt ofs0 (ofs + (Z.of_nat (length bytes)))) as d.\n      destruct d; clear Heqd.\n      (*case <*)\n        apply BytesValid; clear BytesValid.\n        apply Mem.setN_in. omega.\n      (*case >= *)\n         rewrite Mem.setN_outside; try (right; assumption).\n      assumption.\n  (*case b0 <> b*)\n    rewrite PMap.gso; trivial.\nQed.\n\nLemma getN_aux: forall n p c B1 v B2, Mem.getN n p c = B1 ++ v::B2 ->\n    v = ZMap.get (p + Z.of_nat (length B1)) c.\nProof. intros n.\n  induction n; simpl; intros.\n    destruct B1; simpl in *. inv H. inv H.\n    destruct B1; simpl in *.\n      inv H. rewrite Zplus_0_r. trivial.\n      inv H. specialize (IHn _ _ _ _ _ H2). subst.\n        rewrite Zpos_P_of_succ_nat.\n        remember (Z.of_nat (length B1)) as m. clear Heqm H2. rewrite <- Z.add_1_l.\n         rewrite Zplus_assoc. trivial.\nQed.\n\nLemma getN_range: forall n ofs M bytes1 v bytes2,\n  Mem.getN n ofs M = bytes1 ++ v::bytes2 ->\n  (length bytes1 < n)%nat.\nProof. intros n.\n  induction n; simpl; intros.\n    destruct bytes1; inv H.\n    destruct bytes1; simpl in *; inv H.\n      omega.\n    specialize (IHn _ _ _ _ _ H2). omega.\nQed.\n\nLemma loadbytes_D: forall m b ofs n bytes\n      (LD: Mem.loadbytes m b ofs n = Some bytes),\n      Mem.range_perm m b ofs (ofs + n) Cur Readable /\\\n      bytes = Mem.getN (nat_of_Z n) ofs (PMap.get b (Mem.mem_contents m)).\nProof. intros.\n  Transparent Mem.loadbytes.\n  unfold Mem.loadbytes in LD.\n  Opaque Mem.loadbytes.\n  remember (Mem.range_perm_dec m b ofs (ofs + n) Cur Readable) as d.\n  destruct d; inv LD. auto.\nQed.\n\nLemma loadbytes_valid: forall m (WD: mem_wd m) b ofs' n bytes\n      (LD: Mem.loadbytes m b (Int.unsigned ofs') n = Some bytes)\n      v (B: In v bytes),\n      memval_inject (Mem.flat_inj (Mem.nextblock m)) v v.\nProof. intros.\n  destruct (loadbytes_D _ _ _ _ _ LD) as [Range BB]; subst.\n  assert (L:= Mem.loadbytes_length _ _ _ _ _ LD).\n  apply In_split in B. destruct B as [bytes1 [bytes2 B]]. subst.\n  assert (I: Int.unsigned ofs' <= (Int.unsigned ofs') + Z.of_nat (length bytes1) <\n                  Int.unsigned ofs' + n).\n    assert (II:= getN_range _ _ _ _ _ _ B).\n    clear Range LD B L.\n    split. omega.\n    assert (Z.of_nat (length bytes1) < Z.of_nat (nat_of_Z n)).\n        omega.\n    rewrite nat_of_Z_eq in H. omega. clear H.\n     unfold nat_of_Z in II.\n        destruct n. omega. specialize (Pos2Z.is_pos p); omega.\n        rewrite Z2Nat.inj_neg in II. destruct bytes1; simpl in II; inv II.\n  specialize (Range _ I).\n  assert (F: Mem.flat_inj (Mem.nextblock m) b = Some (b, 0)).\n    apply flatinj_I. apply Mem.perm_valid_block in Range. apply Range.\n    specialize (Mem.mi_memval _ _ _ WD _ _ _ _ F Range).\n    intros. rewrite Zplus_0_r in H.\n   apply getN_aux in B. subst. apply H.\nQed.\n\nLemma freelist_mem_wd: forall l m m'\n      (M: Mem.free_list m l = Some m')\n      (WD: mem_wd m), mem_wd m'.\nProof. intros l.\n  induction l; simpl; intros.\n    inv M; trivial.\n  destruct a. destruct p.\n  remember (Mem.free m b z0 z) as d.\n  destruct d; inv M; apply eq_sym in Heqd.\n  apply (IHl _ _ H0).\n  eapply mem_wd_free; eassumption.\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/mem_wd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2954263550278007}}
{"text": "Require Import Coqlib.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Globalenvs.\nRequire Import Events.\nRequire Import Smallstep.\nRequire Import Asm.\nRequire Import Floats.\nRequire Import Maps.\n\nRequire Import PeekLib.\nRequire Import PeekTactics.\nRequire Import SplitLib.\nRequire Import FindInstrLib.\nRequire Import Pred.\nRequire Import Use.\nRequire Import UseBasic.\nRequire Import Union.\nRequire Import PeekLiveness.\nRequire Import Zlen.\n\nLemma update_range :\n  forall c l z,\n    ((z < 0) \\/ (z >= zlen c)) ->\n    ZMap.get z l = ZMap.get z (update_liveness c z l).\nProof.\n  intros.\n  unfold update_liveness.\n  destruct (find_instr z c) eqn:?. \n  assert (exists i, find_instr z c = Some i).\n    exists i. assumption.\n  rewrite <- in_range_find_instr in H0. destruct H0. omega.\n  reflexivity.\nQed.  \n\nLemma update_neq:\n  forall ofs z c l,\n    ofs <> z ->\n    ZMap.get ofs (update_liveness c z l) = ZMap.get ofs l.\nProof.\n  intros.\n  unfold update_liveness.\n  repeat break_match;\n  unfold succ; try rewrite Heqo; simpl;\n  try rewrite ZMap.gso by auto; reflexivity.\nQed.\n\nLemma in_map_union_l_spec:\n  forall {A} is l (p : A) {eq},\n    In p (union_l eq (map (fun z0 => ZMap.get z0 l) is)) ->\n    exists i, (In i is /\\ In p (ZMap.get i l)).\nProof.\n  intros. induction is.\n  * simpl in H. inv H.\n  * destruct (in_dec eq p (ZMap.get a l)).\n    exists a. split. simpl. left. reflexivity. assumption.\n    simpl in H. apply union_correct in H.\n    destruct H. congruence.\n    specialize (IHis H). destruct IHis. destruct H0.\n    exists x. split. simpl. right. auto. auto.\nQed.\n\nLemma update_twice :\n  forall c z l p,\n    In p (ZMap.get z (update_liveness c z (update_liveness c z l))) <-> In p (ZMap.get z (update_liveness c z l)).\nProof.\n  intros. unfold update_liveness.\n  destruct (find_instr z c) eqn:?; \n  simpl; repeat break_match;\n  try rewrite ZMap.set2;\n  try reflexivity.\n\n  destruct (in_dec Z.eq_dec z l0).\n\n  split. intros.\n  repeat rewrite ZMap.gss in *.\n  unfold transfer in *.\n  rewrite <- add_in_spec in H.\n  destruct H. apply add_in_l. assumption.\n  rewrite <- rem_in in H. destruct H.\n  apply in_map_union_l_spec in H.\n  destruct H. destruct H.\n  destruct (zeq x z). subst x.\n  rewrite ZMap.gss in H1. assumption.\n  rewrite ZMap.gso in H1 by auto.\n  apply add_in_r. apply rem_in. split; auto.\n  eapply in_map_union_l; eauto. \n\n  intros. \n  repeat rewrite ZMap.gss in *.\n  unfold transfer in *.\n  destruct (in_dec preg_eq p (use i)).\n  apply add_in_l; assumption.\n  apply add_in_spec in H. destruct H. congruence.\n  apply rem_in in H. destruct H.\n  apply add_in_r. apply rem_in. split; auto.\n  apply in_map_union_l with (i1 := z).\n  intros. rewrite ZMap.gss.\n  apply add_in_r. apply rem_in. split; auto. auto.\n\n  rewrite not_in_map. reflexivity. assumption.\nQed.\n\nLemma update_indep :\n  forall z z0 c l sl,\n    z <> z0 ->\n    succ z0 c = Some sl ->\n    ~ In z sl ->\n    (forall p, In p (ZMap.get z0 (update_liveness c z0 (update_liveness c z l))) <-> In p (ZMap.get z0 (update_liveness c z0 l))).\nProof.\n  intros.\n  unfold update_liveness.\n  repeat break_match;\n    try (assert (succ z0 c = None) by (eapply no_succ_calls; eauto); congruence);\n    try congruence; try reflexivity;\n    repeat rewrite ZMap.gss;\n    unfold transfer; try rewrite map_get_not_in by (inv H0; auto);\n    repeat rewrite ZMap.gso;\n    try reflexivity; auto.\nQed.\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/PeekLivenessLib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.29542634919718497}}
{"text": "Set Implicit Arguments.\n\nRequire U.\nRequire Import monoid_expec.\nRequire Import expec.\nRequire Import qs_definitions.\nImport mon_nondet.\nRequire Import List.\nRequire Import util.\nRequire Import monads.\nRequire Import list_utils.\nRequire Import indices.\nRequire Import monoid_monad_trans.\nRequire Import sums_and_averages.\nRequire qs_parts.\nRequire Import Rdefinitions.\nRequire Import nat_seqs.\nRequire Import sort_order.\nRequire NDP.\nRequire Import nat_below.\nRequire Import Bvector.\nRequire vec.\n\nArguments length {A}.\nArguments fst {A} {B}.\n\nSection contents.\n\n  Variables (ee: E) (ol: list ee).\n\n  Lemma simpler_same_values l d c:\n    proj1_sig (simplerPartition ee (subscript d) (map (subscript (T:=ee) (ol:=ol)) l)) c =\n    map (subscript (T:=ee) (ol:=ol)) (proj1_sig (simplerPartition (UE ee ol) d l) c).\n  Proof with auto.\n    induction l...\n    simpl.\n    intros.\n    simpl.\n    rewrite IHl.\n    destruct (cmp_cmp (Ecmp ee (subscript a) (subscript d)) c)...\n  Qed.\n\n  Theorem qs_CM_U_map_cost_eq (l: list (Index ee ol)):\n    ne_tree.map (fst (A:=_:Set)(B:=_:Set)) (NDP.qs ee (map (@subscript ee ol) l))\n    = ne_tree.map (@length (_:Set) ∘ (@fst (_:Set) (_:Set))) (U.qs l).\n  Proof with auto.\n    unfold NDP.qs, U.qs.\n    pattern l, (qs (@U.cmp ee ol) U.pick l).\n    apply qs_parts.rect...\n      apply U.Mext.\n    clear l.\n    intros.\n    rewrite qs_parts.toBody.\n      Focus 2.\n      apply NDP.Mext.\n    rewrite vec.List_map.\n    rewrite (vec.vec_round_trip (vec.map (@subscript _ _) v) (qs_parts.body NDP.M NDP.pick (NDP.cmp ee))).\n    rewrite qs_parts.toBody_cons.\n    unfold qs_parts.selectPivotPart.\n    unfold qs_parts.partitionPart.\n    unfold qs_parts.lowRecPart.\n    simpl.\n    repeat rewrite ne_list.map_map.\n    f_equal.\n    unfold compose.\n    apply ne_list.map_ext.\n    intro.\n    repeat rewrite ne_tree_monad.map_bind.\n    repeat rewrite (@mon_assoc ne_tree_monad.M).\n    simpl.\n    repeat rewrite ne_tree_monad.map_bind.\n    repeat rewrite (@mon_assoc ne_tree_monad.M).\n    rewrite NDP.partition.\n    rewrite U.partition.\n    simpl.\n    repeat rewrite (@mon_assoc ne_tree_monad.M).\n    apply ne_tree_monad.bind_eq with nat (@fst nat (list ee)) (fun x: prod U.monoid (list (Index ee ol)) => length (fst x)).\n      simpl.\n      intros.\n      repeat rewrite (@mon_assoc ne_tree_monad.M).\n      simpl.\n      apply (ne_tree_monad.bind_eq) with nat (@fst nat (list ee)) (fun x: prod U.monoid (list (Index ee ol)) => length (fst x)).\n        intros.\n        simpl.\n        unfold compose.\n        simpl.\n        repeat rewrite app_length.\n        f_equal.\n        rewrite map_length.\n        repeat rewrite vec.length.\n        rewrite H0, H1...\n      unfold compose in H.\n      simpl monoid_type in *.\n      rewrite <- H.\n        f_equal.\n        rewrite vec.nth_map.\n        rewrite vec.remove_map.\n        rewrite <- vec.List_map.\n        rewrite simpler_same_values...\n      rewrite (@U.simplePartition_component (UE ee ol)).\n      rewrite length_filter.\n      apply le_lt_trans with (length (vec.remove v x))...\n      rewrite vec.length...\n    rewrite <- H.\n      f_equal.\n      rewrite vec.nth_map.\n      rewrite vec.remove_map.\n      rewrite <- vec.List_map.\n      rewrite simpler_same_values...\n    rewrite (@U.simplePartition_component (UE ee ol)).\n    rewrite length_filter.\n    apply le_lt_trans with (length (vec.remove v x))...\n    rewrite vec.length...\n  Qed.\n\n  Theorem qs_CM_U_expec_cost_eq (tl: list (Index ee ol)):\n    expec cost (NDP.qs ee (map (@subscript ee ol) tl))\n    = monoid_expec (m:=U.monoid) length (U.qs tl).\n  Proof with try reflexivity.\n    unfold monoid_expec.\n    unfold expec, compose.\n    intros.\n    f_equal.\n    rewrite <- (ne_tree.map_map (@fst NatAddMonoid (list ee)) Raxioms.INR).\n    rewrite (qs_CM_U_map_cost_eq tl). \n    rewrite ne_tree.map_map...\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_CM_U_expec_cost_eq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.295421970310303}}
{"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 uniq_tac machine_int multi_int.\nImport MachineInt.\nRequire Import mips_seplog mips_frame mips_tactics mips_contrib mapstos.\nRequire Import multi_zero_s_prg multi_zero_u_triple multi_negate_triple.\nImport expr_m.\nImport assert_m.\n\nLocal Open Scope heap_scope.\nLocal Open Scope mips_expr_scope.\nLocal Open Scope mips_assert_scope.\nLocal Open Scope mips_hoare_scope.\nLocal Open Scope machine_int_scope.\nLocal Open Scope zarith_ext_scope.\nLocal Open Scope uniq_scope.\n\nLemma multi_zero_s'_triple rx a0 a1 a2 a3 : uniq(rx, a0, a1, a2, a3, r0) ->\n  forall nk X vx ptr, size X = nk ->\n    u2Z vx + 4 * 2 < Zbeta 1 ->\n    u2Z ptr + 4 * Z_of_nat nk < Zbeta 1 ->\n  {{ fun s h => [ rx ]_s = vx /\\\n     (var_e rx |--> Z2u 32 (Z_of_nat nk) :: ptr :: nil ** int_e ptr |--> X) s h }}\n  multi_zero_s' rx a0 a1 a2 a3\n  {{ fun s h => [ rx ]_s = vx /\\\n      [ a0 ]_s = Z2u 32 (Z_of_nat nk) /\\\n     (var_e rx |--> Z2u 32 (Z_of_nat nk) :: ptr :: nil ** int_e ptr |--> nseq nk zero32) s h }}.\nProof.\nmove=> regs nk X vx ptr len_X vx_fit ptr_fit.\nrewrite /multi_zero_s.\n\n(** lw a0 zero16 rx *)\n\napply mips_contrib.hoare_lw_back_alt'' with (fun s h => [rx ]_ s = vx /\\\n  (var_e rx |--> Z2u 32 (Z_of_nat nk) :: ptr :: nil ** int_e ptr |--> X) s h /\\\n  u2Z [ a0 ]_ s = Z_of_nat nk).\nmove=> s h [Hx mem].\nexists (Z2u 32 (Z_of_nat nk)); split.\n- rewrite /= assert_m.conAE in mem.\n  move: mem; apply assert_m.monotony => // h'.\n  apply assert_m.mapsto_ext => //.\n  by rewrite sext_Z2u //= addi0.\n- rewrite /mips_contrib.update_store_lw.\n  repeat Reg_upd.\n  repeat (split=> //).\n  move: mem; apply assert_m.monotony => // h'.\n  apply assert_m.mapstos_ext => //=.\n  by Reg_upd.\n  apply assert_m.mapstos_ext => //.\n  rewrite Z2uK // -Zbeta1E.\n  split; first exact: Zle_0_nat.\n  move: (min_u2Z ptr) => ?; lia.\n\n(** lw a1 four16 rx *)\n\napply mips_contrib.hoare_lw_back_alt'' with (fun s h => [rx ]_ s = vx /\\\n  (var_e rx |--> Z2u 32 (Z_of_nat nk) :: ptr :: List.nil ** int_e ptr |--> X) s h /\\\n  u2Z [ a0 ]_ s = Z_of_nat nk /\\ [ a1 ]_ s = ptr).\nmove=> s h [Hx [mem Ha0]].\nexists ptr; split.\n- rewrite /= assert_m.conAE assert_m.conCE assert_m.conAE in mem.\n  move: mem; apply assert_m.monotony => // h' mem.\n  case: mem => h1 [h2 [Hdisj [Hunion [Hh1 [Hh2 H']]]]].\n  rewrite /assert_m.emp in H'; subst h2.\n  rewrite heap.unionhe in Hunion; subst h'.\n  move: Hh1; apply assert_m.mapsto_ext => //=.\n  by rewrite sext_Z2u //.\n- rewrite /mips_contrib.update_store_lw.\n  repeat Reg_upd.\n  repeat (split => //).\n  move: mem; apply assert_m.monotony => // h'.\n  apply assert_m.mapstos_ext => //=.\n  by Reg_upd.\n  by apply assert_m.mapstos_ext.\n\n(** multi_zero a0 a1 a2 a3 *)\n\napply (before_frame\n  (fun s h => [rx ]_ s = vx /\\ (var_e rx |--> Z2u 32 (Z_of_nat nk) :: ptr :: nil) s h)\n  (fun s h => [a1]_s = ptr /\\ u2Z [a0]_s = Z_of_nat nk /\\ (var_e a1 |--> X) s h)\n  (fun s h => [a1]_s = ptr /\\ u2Z [a0]_s = Z_of_nat nk /\\ (var_e a1 |--> nseq nk zero32) s h)).\n\n- apply mips_frame.frame_rule_R.\n  apply multi_zero_u_triple => //; by Uniq_uniq r0.\n  by Inde_frame.\n  by move=> ?; Inde_mult.\n- rewrite /while.entails => s h [Hx [mem [Ha0 Ha1]]].\n  case: mem => h1 [h2 [Hdisj [Hunion [Hh1 Hh2]]]].\n  Compose_sepcon h2 h1.\n  repeat (split=> //).\n  move: Hh2; by apply assert_m.mapstos_ext.\n  by repeat (split=> //).\n- rewrite /while.entails => s h mem.\n  case: mem => h1 [h2 [Hdisj [Hunion [[Ha1 [Ha0 Hh1]] [Hrx Hh2]]]]].\n  split; first by assumption.\n  split.\n    apply u2Z_inj.\n    rewrite Ha0 Z2uK //.\n    split; first by apply Zle_0_nat.\n    rewrite -Zbeta1E; move: (min_u2Z ptr) => ?; lia.\n  Compose_sepcon h2 h1; first by [].\n  move: Hh1; by apply assert_m.mapstos_ext.\nQed.\n\nLemma multi_zero_s_triple rx : uniq(rx, r0) -> forall X ptr slen,\n  {{ var_e rx |--> slen :: ptr :: nil ** int_e ptr |--> X }}\n  multi_zero_s rx\n  {{ var_e rx |--> zero32 :: ptr :: nil ** int_e ptr |--> X }}.\nProof.\nmove=> Hnodup X ptr slen.\nrewrite /multi_zero_s.\napply hoare_sw_back'.\nmove=> s h Hmem.\nexists (int_e slen).\nrewrite /= assert_m.conAE in Hmem.\nmove: Hmem; apply monotony => h'.\n  apply mapsto_ext => //.\n  by rewrite /= sext_Z2u // addi0.\napply currying => h'' Hmem.\nrewrite assert_m.conCE !assert_m.conAE in Hmem.\nmove: Hmem => /=.\nrewrite !assert_m.conAE.\napply monotony => h3 //.\napply mapsto_ext => /=.\n  by rewrite sext_Z2u // addi0.\nby rewrite store.get_r0.\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_s_triple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.4921881357207955, "lm_q1q2_score": 0.2954055896256033}}
{"text": "From Coq Require Import String List Peano Arith Program.Equality Nat\nPsatz Arith.PeanoNat Program.Equality.\n\nFrom DanTrick Require Import StackLogic DanLogHoare DanTrickLanguage EnvToStack StackLanguage DanLogProp LogicProp StackLangTheorems StackLogicBase.\nFrom DanTrick Require Import LogicTranslationBackwards StackLogicBase TranslationPure LogicTranslationAdequate LogicTrans.\nFrom DanTrick Require Export ProofSubstitution ImpVarMapTheorems DanLogSubstAdequate.\nFrom DanTrick Require Import DanImpHigherOrderRel DanImpHigherOrderRelTheorems CompilerCorrect StackFrame1 StackPure.\n\n(*\n * \n *)\n\nLocal Open Scope string_scope.\nLocal Open Scope nat_scope.\nLocal Open Scope list_scope.\nLocal Open Scope dantrick_scope.\n\nLemma same_after_popping_extend : \n  forall stk' n stk rho, \n  same_after_popping stk stk' n ->\n  same_after_popping (stk ++ rho) (stk' ++ rho) n.\nProof.\n  induction stk'; intros.\n  - invs H. constructor. apply eq_refl.\n  - invs H.\n    + invs H. constructor. apply eq_refl.\n    + specialize (IHstk' n0 stk rho H4).\n      assert (((a :: stk') ++ rho) = (a :: stk' ++ rho)) by auto.\n      rewrite H0.  \n      constructor.\n      apply IHstk'.\nQed.       \n\n\nCheck imp_stack_mutind. \n\nLemma stk_determ_extend : \n  (forall a fenv stk stk',\n    imp_stack_sem a fenv stk (stk') ->\n      forall rho,\n        imp_stack_sem a fenv (stk++rho) ((stk'++rho)))\n  /\\\n  (forall a fenv stk stk',\n      aexp_stack_sem a fenv stk stk' ->\n      forall rho stk'' n,\n        stk' = (stk'', n) ->\n        aexp_stack_sem a fenv (stk++rho) ((stk''++rho), n))\n  /\\\n  (forall a fenv stk stk',\n      bexp_stack_sem a fenv stk (stk') ->\n      forall rho stk'' n,\n        stk' = (stk'', n) ->\n        bexp_stack_sem a fenv (stk++rho) ((stk''++rho), n))\n  /\\\n  (forall a fenv stk stk',\n    args_stack_sem a fenv stk stk' ->\n    forall rho stk'' ns,\n      stk' = (stk'', ns) ->\n      args_stack_sem a fenv (stk++rho) ((stk''++rho, ns)))\n.\nProof.\n  pose (fun a fenv stk stk'=> \n    (fun (i : imp_stack_sem a fenv stk stk') => \n      forall rho, \n        imp_stack_sem a fenv (stk++rho) ((stk'++rho)))) \n    as P.\n  pose (fun a fenv stk stk' => \n    (fun (i0 : aexp_stack_sem a fenv stk stk') =>\n          forall rho stk'' n,\n            stk' = (stk'', n) ->\n              aexp_stack_sem a fenv (stk++rho) ((stk''++rho), n))) \n      as P0.  \n  pose (fun a fenv stk stk' => \n    (fun (i1 : bexp_stack_sem a fenv stk stk') =>\n          forall rho stk'' n,\n            stk' = (stk'', n) ->\n              bexp_stack_sem a fenv (stk++rho) ((stk''++rho), n))) \n      as P1.  \n  pose (fun a fenv stk stk' => \n    (fun (i1 : args_stack_sem a fenv stk stk') =>\n          forall rho stk'' n,\n            stk' = (stk'', n) ->\n              args_stack_sem a fenv (stk++rho) ((stk''++rho), n))) \n      as P2.  \n  apply (imp_stack_mutind P P0 P1 P2); unfold P, P0, P1, P2 in *; intros.\n  - constructor.\n  - econstructor.\n    + apply l. \n    + invs s.\n      --rewrite app_length. simpl. lia.\n      --rewrite app_length. simpl. lia.\n    + apply (H rho stk' c eq_refl). \n    + apply stack_mutated_at_index_preserved_by_superlist.\n      apply s.  \n  - rewrite e. constructor. apply eq_refl. \n  - rewrite e. econstructor. exists.\n  - econstructor.\n    apply H. apply H0.\n  - econstructor.\n    apply H. exists. apply H0.\n  - eapply Stack_if_false.\n    apply H. exists. apply H0. \n  - eapply Stack_while_done. apply H. apply eq_refl.\n  - eapply Stack_while_step.\n    + apply H. exists.\n    + apply H0.\n    + apply H1.\n  - invs H. constructor.\n  - invs H. constructor; try assumption.\n    + rewrite app_length. lia.\n    + pose proof (nth_error_app1 stk'' rho).\n      specialize (H0 (i - 1)). \n      destruct H0. lia. apply e.\n  - specialize (H rho stk1 n1 eq_refl).\n    specialize (H0 rho stk2 n2 eq_refl).\n    pose proof Stack_plus fenv (stk++rho) a1 a2 (stk1++rho) (stk2++rho) n1 n2 H H0.\n    invs H1. assumption.\n  - specialize (H rho stk1 n1 eq_refl).\n    specialize (H0 rho stk2 n2 eq_refl).\n    pose proof Stack_minus fenv (stk++rho) a1 a2 (stk1++rho) (stk2++rho) n1 n2 H H0.\n    invs H1. assumption.\n  - econstructor. \n    + apply e.\n    + apply e0.\n    + apply e1.\n    + apply e2.\n    + apply e3.\n    + apply H. exists.\n    + specialize (H0 rho). \n      assert (((vals ++ stk1) ++ rho) = (vals ++ stk1 ++ rho)) by (symmetry;apply app_assoc).\n      rewrite <- H3. apply H0.\n    + invs H2. apply H1. \n      exists.\n    + apply same_after_popping_extend. invs H2. assumption.\n  - invs H. apply Stack_true.\n  - invs H. apply Stack_false.\n  - econstructor.\n    + invs H0. apply H. exists.\n    + invs H0. apply eq_refl.\n  - econstructor. \n    + apply H. exists.\n    + invs H1. apply H0. exists.\n    + invs H1. apply eq_refl.\n  - econstructor. \n    + apply H. exists.\n    + invs H1. apply H0. exists.\n    + invs H1. apply eq_refl.\n  - econstructor.\n    + apply H. exists.\n    + invs H1. apply H0. exists.\n    + invs H1. apply eq_refl.\n  - econstructor.\n    + apply H. exists.\n    + invs H1. apply H0. exists.\n    + invs H1. apply eq_refl.\n  - invs H. constructor.\n  - invs H1. econstructor.\n    + apply H. exists.\n    + apply H0. apply eq_refl.\nQed. \n\n\nLemma aexp_stk_determ_extend : \n  forall a n stk fenv rho,\n    aexp_stack_sem a fenv stk (stk, n) ->\n    aexp_stack_sem a fenv (stk++rho) ((stk++rho), n).\nProof. \n  intros. \n  pose proof stk_determ_extend.\n  destruct H0. destruct H1. \n  clear H2.\n  apply (H1 a fenv stk (stk, n) H rho stk n eq_refl).    \nQed. \n\nLemma bexp_stk_determ_extend : \n  forall a n stk fenv rho,\n    bexp_stack_sem a fenv stk (stk, n) ->\n    bexp_stack_sem a fenv (stk++rho) ((stk++rho), n).\nProof. \n  intros. \n  pose proof stk_determ_extend.\n  destruct H0. destruct H1. destruct H2. \n  clear H3.\n  apply (H2 a fenv stk (stk, n) H rho stk n eq_refl).    \nQed. \n\nLemma args_stk_determ_extend : \n(forall a ns fenv stk stk' rho,\nargs_stack_sem a fenv stk (stk', ns) ->\nargs_stack_sem a fenv (stk++rho) ((stk'++rho, ns))).\nProof.\n  intros. pose proof stk_determ_extend.\n  destruct H0. destruct H1. destruct H2. \n  apply (H3 a fenv stk (stk', ns) H rho stk' ns eq_refl).\nQed.\n\nLemma nat_args_stk_determ_extend : \nforall a_list fenv stk rho vals, \n  (eval_prop_args_rel\n    (fun (natexpr : aexp_stack) (natval : nat) =>\n    aexp_stack_sem natexpr fenv stk (stk, natval)) a_list vals) ->\n  (eval_prop_args_rel\n  (fun (natexpr : aexp_stack) (natval : nat) =>\n   aexp_stack_sem natexpr fenv (stk ++ rho) (stk ++ rho, natval)) a_list vals).\nProof. \n  induction a_list; intros.\n  - invs H. constructor.\n  - invs H. specialize (IHa_list fenv stk rho vals0 H5). \n    constructor. apply (aexp_stk_determ_extend a val stk fenv rho H3).\n    apply IHa_list.\nQed. \n\nLemma bool_args_stk_determ_extend :\nforall a_list fenv stk rho vals, \n(eval_prop_args_rel (fun (boolexpr : bexp_stack) (boolval : bool) =>\nbexp_stack_sem boolexpr fenv (stk) (stk, boolval))\na_list vals) ->\n(eval_prop_args_rel (fun (boolexpr : bexp_stack) (boolval : bool) =>\nbexp_stack_sem boolexpr fenv (stk ++ rho) (stk ++ rho, boolval))\na_list vals).\nProof. \n  induction a_list; intros.\n  - invs H. constructor.\n  - invs H. specialize (IHa_list fenv stk rho vals0 H5). \n    constructor. apply (bexp_stk_determ_extend a val stk fenv rho H3).\n    apply IHa_list.\nQed.  \n", "meta": {"author": "uwplse", "repo": "potpie", "sha": "d4814d315ff9d450a8d91ed77b22340b0ff35690", "save_path": "github-repos/coq/uwplse-potpie", "path": "github-repos/coq/uwplse-potpie/potpie-d4814d315ff9d450a8d91ed77b22340b0ff35690/StackExtensionDeterministic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883449573377, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2954055825859018}}
{"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 Automaton Interpreter_correct Interpreter_complete.\nFrom Coq Require Import Syntax Arith.\n\nModule Make(Export Aut:Automaton.T).\nExport Aut.Gram.\nExport Aut.GramDefs.\n\nModule Import Inter := Interpreter.Make Aut.\nModule Correct := Interpreter_correct.Make Aut Inter.\nModule Complete := Interpreter_complete.Make Aut Inter.\n\nDefinition complete_validator:unit->bool := Complete.Valid.is_complete.\nDefinition safe_validator:unit->bool := ValidSafe.is_safe.\nDefinition parse (safe:safe_validator ()=true) init log_n_steps buffer :\n  parse_result (symbol_semantic_type (NT (start_nt init))):=\n  parse (ValidSafe.safe_is_validator safe) init buffer log_n_steps.\n\n(** Correction theorem. **)\nTheorem parse_correct\n  (safe:safe_validator ()= true) init log_n_steps buffer:\n  match parse safe init log_n_steps buffer with\n    | Parsed_pr sem buffer_new =>\n      exists word (pt : parse_tree (NT (start_nt init)) word),\n        buffer = (word ++ buffer_new)%buf /\\\n        pt_sem pt = sem\n    | _ => True\n  end.\nProof. apply Correct.parse_correct. Qed.\n\n(** Completeness theorem. **)\nTheorem parse_complete\n  (safe:safe_validator () = true) init log_n_steps word buffer_end:\n  complete_validator () = true ->\n  forall tree:parse_tree (NT (start_nt init)) word,\n  match parse safe init log_n_steps (word ++ buffer_end) with\n  | Fail_pr => False\n  | Parsed_pr sem_res buffer_end_res =>\n    sem_res = pt_sem tree /\\ buffer_end_res = buffer_end /\\\n    pt_size tree <= 2^log_n_steps\n  | Timeout_pr => 2^log_n_steps < pt_size tree\n  end.\nProof.\n  intros. now apply Complete.parse_complete, Complete.Valid.complete_is_validator.\nQed.\n\n(** Unambiguity theorem. **)\nTheorem unambiguity:\n  safe_validator () = true -> complete_validator () = true -> inhabited token ->\n  forall init word,\n  forall (tree1 tree2:parse_tree (NT (start_nt init)) word),\n    pt_sem tree1 = pt_sem tree2.\nProof.\n  intros Hsafe Hcomp [tok] init word tree1 tree2.\n  pose (buf_end := cofix buf_end := (tok :: buf_end)%buf).\n  assert (Hcomp1 := parse_complete Hsafe init (pt_size tree1) word buf_end\n                                   Hcomp tree1).\n  assert (Hcomp2 := parse_complete Hsafe init (pt_size tree1) word buf_end\n                                   Hcomp tree2).\n  destruct parse.\n  - destruct Hcomp1.\n  - exfalso. eapply PeanoNat.Nat.lt_irrefl. etransitivity; [|apply Hcomp1].\n    eapply Nat.pow_gt_lin_r. constructor.\n  - destruct Hcomp1 as [-> _], Hcomp2 as [-> _]. reflexivity.\nQed.\n\nEnd Make.\n", "meta": {"author": "AbsInt", "repo": "CompCert", "sha": "f4ddce910894bf6dbdf83c0642c4b275854b60dd", "save_path": "github-repos/coq/AbsInt-CompCert", "path": "github-repos/coq/AbsInt-CompCert/CompCert-f4ddce910894bf6dbdf83c0642c4b275854b60dd/MenhirLib/Main.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573377, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2954055825859018}}
{"text": "From Undecidability.TM Require Import TM_facts.\nFrom Undecidability.L.TM Require Import TMEncoding.\nFrom Complexity.L.TM Require Import TMflat TMflatEnc TMflatFun TapeDecode TMunflatten.\nFrom Undecidability.L.Datatypes Require Import LNat LProd Lists.\nFrom Complexity.Complexity Require Import NP LinTimeDecodable ONotation.\nFrom Undecidability.L Require Import Tactics.LTactics.\nFrom Undecidability.L Require Import Functions.Decoding.\nFrom Complexity.L Require Import TMflatFun TMflatComp.\nFrom Undecidability Require Import L.Functions.EqBool.\nFrom Undecidability Require Import L.Datatypes.LNat.\n\n(** Using this problem to establish NP-hardness as by Cook-levin would require us to construct TMs from L-terms. We don't want to do this. Instead, we define another problem (GenNPHalt_fixed_mTM) where the machine itself and some tape content is fixed, but a single tape has arbitrary content on it. *)\n\n(* Factorise proof over GenNP? *)\nDefinition TMGenNP' sig n : TM sig n * nat * nat -> Prop :=\n  fun '(M, k, steps) =>\n    exists tp, sizeOfmTapes tp <= k\n          /\\ exists f, loopM (initc M tp) steps = Some f.\n\nDefinition TMGenNP: flatTM*nat*nat -> Prop:=\n  fun '(M,maxSize, steps (*in unary*)) =>\n    (exists sig n (M':TM sig n), isFlatteningTMOf M M' /\\ TMGenNP' (M',maxSize,steps)).\n\nDefinition TM1GenNP : {'(M,_,_) | M.(TMflat.tapes) = 1} -> Prop :=\n  (fun '(exist (M,maxSize, steps (*in unary*)) _) => exists sig (M':TM sig 1), isFlatteningTMOf M M' /\\ TMGenNP' (M', maxSize, steps)).\n\nLemma inNP_TMgenericNPCompleteProblem: inNP TMGenNP.\nProof.\n  pose (R := fun '(M,maxSize, steps (*in unary*)) t =>\n               sizeOfmTapesFlat t <= maxSize /\\  \n               exists sig n (M':TM sig n),\n                 isFlatteningTMOf M M'\n                 /\\ exists t', isFlatteningTapesOf t t'\n                         /\\ (exists f, loopM (initc M' t') steps = Some f)).\n  apply inNP_intro with (R:= R).\n  now apply linDec_polyTimeComputable.\n  -destruct execFlat_poly as (f''&Hf''&polyf''&monof'').\n   evar (f':nat -> nat). [f']:intro x.\n   exists f'. repeat eapply conj.\n   { split. cbn. \n     eexists (fun '((M,maxSize,steps),t) =>\n                if (sizeOfmTapesFlat t <=? maxSize)\n                then match execFlatTM M t steps with\n                       Some _ => true\n                     | _ => false\n                     end\n                else false).\n     repeat eapply conj.\n     2:{intros [[[M maxSize] steps] t]. cbn.\n        destruct (Nat.leb_spec0 (sizeOfmTapesFlat t) (maxSize));cbn [negb andb].\n        2:{ split. 2:easy. intros (?&?&?&?&?&?&?&?). easy. }\n        specialize (execFlatTM_correct M t steps) as H.\n        destruct execFlatTM as [c| ] eqn:Hexec. all:split. 1,4:easy.\n        -intros. specialize (H c). destruct H as [H _]. specialize H with (1:= Logic.eq_refl) as (?&?&?&?&?&?&Hc&?&?).\n         split. easy.\n         do 4 esplit. eauto.\n            inv Hc. cbn in *.\n            do 2 esplit. eauto.\n               destruct x2. cbn in *.\n               eexists. rewrite <- H1. unfold initc. repeat f_equal. inv H. apply injective_index. congruence.\n               -intros (?&?&?&?&?&?&?&?&?). exfalso.\n                edestruct H as [_ H']. discriminate H'.\n                do 6 eexists. now eauto.\n                   split. now eauto using initFlat_correct.\n                   split. eauto. instantiate (1 := (_,_)).\n                   split;cbn. constructor.\n     } \n     extract. \n     recRel_prettify.\n     intros [[[M maxSize] steps] t] [].\n     split;[ |now repeat destruct _].\n     rewrite sizeOfmTapesFlat_timeBySize.\n     unfold leb_time. rewrite Nat.le_min_r.\n     unfold sizeOfmTapesFlat_timeSize.\n     remember (size (enc (M, maxSize, steps, t))) as x.\n\n     assert (Ht : size (enc t) <= x).\n     { subst x. rewrite !size_prod. cbn [fst snd]. lia. }\n     rewrite Ht.\n\n     assert (Hms : maxSize <= x).\n     { subst x. rewrite !size_prod. cbn [fst snd]. rewrite <- size_nat_enc_r. lia. }\n     rewrite Hms at 1.\n     \n     \n     destruct (Nat.leb_spec (sizeOfmTapesFlat t) maxSize).\n     rewrite Hf''. hnf in monof''. rewrite monof'' with (x':=x).\n     2:{rewrite H. subst x. rewrite !size_prod. cbn [fst snd]. rewrite <- !size_nat_enc_r. lia. }\n     destruct execFlatTM.\n     all:unfold f'.\n     reflexivity.\n     all:lia.\n   }\n   all:unfold f'.\n   all:smpl_inO.\n  -evar (f:nat -> nat). [f]:intro x.\n   exists f.\n   +intros [[TM maxSize] steps] y.  cbn.\n    intros (?&sig&n&M'&HM&t' & Ht' & HHalt) .\n    eexists _,_,_. split. easy. eexists. split. now erewrite <- sizeOfmTapesFlat_eq. easy.\n   +intros [[TM maxSize] steps]. cbn.\n    intros (sig&n&M'&HM&t' & Ht' & HHalt) .\n    eexists _. split.\n    *split. now erewrite sizeOfmTapesFlat_eq.\n     eauto 10 using mkIsFlatteningTapeOf.\n    *remember (size (enc (TM, maxSize, steps))) as x eqn:Hn.\n     rewrite size_flatTapes. 2:now apply mkIsFlatteningTapeOf.\n     rewrite Ht'.\n     assert (n <= x /\\ maxSize <= x /\\ | elem sig | <= x) as (->&->&->).\n     {inv HM;destruct TM; cbn in *. rewrite !size_prod,size_TM;cbn [fst snd].\n      repeat apply conj.\n      all:rewrite size_nat_enc_r at 1; subst;nia.\n     }\n     unfold f;reflexivity.\n   +unfold f;smpl_inO.\n   +unfold f;smpl_inO.\nQed.\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/TMGenNP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.29534388483648066}}
{"text": "\nRequire Export Iron.Language.SystemF2Cap.Step.TypeC.\nRequire Export Iron.Language.SystemF2Cap.Store.LiveS.\nRequire Export Iron.Language.SystemF2Cap.Store.LiveE.\n\n\n(* When a well typed expression transitions to the next state\n   then its type is preserved. *)\nTheorem preservation\n :  forall se sp sp' ss ss' fs fs' x x' t e\n ,  WfFS   se sp ss  fs\n -> LiveS ss fs -> LiveE  fs e\n -> TypeC  nil nil se sp fs  x   t  e    \n -> StepF  ss  sp  fs x  ss' sp' fs' x'   \n -> (exists se' e'\n    ,  WfFS  se' sp' ss' fs'\n    /\\ LiveS ss' fs'    \n    /\\ LiveE fs' e'\n    /\\ SubsVisibleT  nil sp' sp  e  e'\n    /\\ TypeC nil nil se' sp' fs' x' t e').\nProof.\n intros se sp sp' ss ss' fs fs' x x' t e.\n intros HH HLS HLE HC HS. \n gen t e.\n induction HS; intros.\n\n\n (*********************************************************)\n (* Pure evaluation. *)\n Case \"SfStep\". \n { inverts_typec. \n   exists se. \n   exists e. \n   intuition.\n\n   (* Original effect visibly subsumes effect of result. *)\n   - apply subsVisibleT_refl.\n     eauto.\n\n   (* Resulting configuration is well typed. *)\n   - eapply TcExp; eauto.\n     eapply stepp_preservation; eauto.\n }\n\n\n (*********************************************************)\n (* Push let context. *)\n Case \"SfLetPush\".\n { exists se.\n   exists e.\n   intuition.\n   \n   (* Frame stack with new FLet frame is well formed. *)\n   - inverts HH. split; auto.\n     unfold StoreP in *. rip.\n     + inverts H3. nope. eauto.\n     + inverts H3. nope. eauto.\n    \n   (* All store bindings mentioned by frame stack are still live. *)\n   - eapply liveS_push_flet; auto.\n\n   (* Original effect visibly subsumes effect of result. *)\n   - inverts_typec.\n     eapply subsVisibleT_refl; eauto.\n\n   (* Resulting configuation is well typed. *)\n   - inverts_typec.\n     eapply TcExp \n      with (t1 := t) (e1 := e0) (e2 := TSum e3 e2).\n      + eapply EqTrans.\n        * eapply EqSumAssoc; eauto.\n        * auto.\n      + auto.\n      + eapply TfConsLet; eauto.\n }\n\n\n (*********************************************************)\n (* Pop let context and substitute. *)\n Case \"SfLetPop\".\n { exists se.\n   exists e.\n   intuition.\n\n   (* Store is still well formed. *)\n   - inverts HH. split; auto.\n     unfold StoreP in *. \n     rip; firstorder.  \n\n   (* After popping top FLet frame, effects of result are still \n      to live regions. *)\n   - eapply liveE_pop_flet; eauto.\n\n   (* Original effect visibly subsumes effect of result. *)\n   - inverts_typec.\n     eapply subsVisibleT_refl; eauto.\n\n   (* Resulting configuration is well typed. *)\n   - inverts_typec.\n     eapply TcExp  \n      with (t1 := t3) (e1 := e0) (e2 := e3).\n      + eapply EqTrans.\n        * eapply equivT_sum_left; auto.\n          have (KindT nil sp e0 KEffect).\n          have (KindT nil sp e3 KEffect).\n          eapply KiSum; eauto.\n        * auto.\n      + eapply subst_val_exp; eauto.\n      + auto.\n } \n\n\n (*********************************************************)\n (* Create a private region. *)\n Case \"SfPrivatePush\".\n { inverts_typec.\n   set (r := TRgn p).\n   exists se.\n   exists (TSum (substTT 0 r e0) (substTT 0 r e2)).\n\n   have (SumKind KEffect).\n\n   have (KindT (nil :> (OCon, KRegion)) sp e0 KEffect).\n\n   have (KindT nil sp e1 KEffect)\n    by  (eapply equivT_kind_left; eauto).\n   have (ClosedT e1).\n\n   have (KindT nil sp e2 KEffect)\n    by  (eapply equivT_kind_left; eauto).\n   have (ClosedT e2).\n   intuition.\n\n   (* All store bindings mentioned by resulting frame stack\n      are still live. *)\n   - inverts HH.\n     subst p.\n     eapply liveS_push_fpriv_none_allocRegion; eauto.\n\n   (* Resulting effect is to live regions. *)\n   - eapply liveE_sum_above.\n     + eapply liveE_phase_change.\n\n       have HLL: (liftTT 1 0 e1 = maskOnVarT 0 e0)\n        by  (eapply lowerTT_some_liftTT; eauto).\n       rrwrite (liftTT 1 0 e1 = e1) in HLL.\n\n       have (SubsT nil sp e e1 KEffect) \n        by  (eapply EqSym in H0; eauto).\n\n       have (LiveE fs e1).\n\n       have HLW: (LiveE (fs :> FPriv None p ts) e1).\n       rewrite HLL in HLW.\n\n       have HL0: (LiveE (fs :> FPriv None p ts) e0) \n        by (eapply liveE_maskOnVarT; eauto).\n\n       trivial.\n\n     + have (SubsT nil sp e e2 KEffect)\n        by  (eapply EqSym in H0; eauto).\n\n       have (LiveE fs e2).\n       have (LiveE (fs :> FPriv None p ts) e2).\n       rrwrite (substTT 0 r e2 = e2); auto.\n       \n   (* Effect of result is subsumed by previous. *)\n   - rrwrite ( TSum (substTT 0 r e0) (substTT 0 r e2)\n             = substTT 0 r (TSum e0 e2)).\n     have (ClosedT e).\n     rgwrite (e = substTT 0 r e)\n      by (symmetry; eauto).\n\n     simpl.\n     set (sp' := SRegion p <: sp).\n     assert (SubsVisibleT nil sp' sp (substTT 0 r e) (substTT 0 r e0)).\n     { have HE: (EquivT       nil sp' e (TSum e1 e2) KEffect)\n        by (subst sp'; eauto).\n\n       have HS: (SubsT        nil sp' e e1 KEffect)\n        by (subst sp'; eauto).\n\n       apply lowerTT_some_liftTT in H5.\n       apply lowerTT_some_liftTT in H6.\n\n       assert   (SubsVisibleT nil sp' sp (liftTT 1 0 e) (liftTT 1 0 e1)) as HV.\n        rrwrite (liftTT 1 0 e  = e).\n        rrwrite (liftTT 1 0 e1 = e1).\n        eapply subsT_subsVisibleT.\n        auto.\n\n       rrwrite (substTT 0 r e  = e).\n       rrwrite (liftTT  1 0 e  = e) in HV.\n       rrwrite (liftTT  1 0 e1 = maskOnVarT 0 e0) in HV.    \n\n       eapply subsVisibleT_mask; eauto.\n     }\n\n     assert (SubsVisibleT nil sp' sp (substTT 0 r e) (substTT 0 r e2)).\n     { rrwrite (substTT 0 r e  = e).\n       rrwrite (substTT 0 r e2 = e2).\n\n       have HE: (EquivT nil sp' e (TSum e1 e2) KEffect)\n        by (subst sp'; eauto).\n        \n       eapply SbEquiv in HE.\n       eapply SbSumAboveRight in HE.\n       eapply subsT_subsVisibleT. auto. auto.\n     }\n \n     unfold SubsVisibleT.\n      simpl.\n      apply SbSumAbove; auto.\n\n   (* Result expression is well typed. *)\n   - rrwrite (substTT 0 r e2 = e2).\n     eapply TcExp \n       with (sp := SRegion p <: sp) \n            (t1 := substTT 0 r t0)\n            (e1 := substTT 0 r e0)\n            (e2 := substTT 0 r e2); auto.\n\n     (* Type of result is equivlent to before *)\n     + rrwrite (substTT 0 r e2 = e2).\n       eapply EqRefl.\n        eapply KiSum; auto.\n         * eapply subst_type_type. \n            eauto.\n            subst r. eauto.\n\n     (* Type is preserved after substituting region handle. *)\n     + rgwrite (nil = substTE 0 r nil).\n       rgwrite (se  = substTE 0 r se)\n        by (inverts HH; symmetry; auto).\n\n       eapply subst_type_exp with (k2 := KRegion).\n       * rrwrite (liftTE 0 nil = nil).\n         rrwrite (liftTE 0 se  = se) \n          by (inverts HH; auto).\n\n         eapply typex_stprops_snoc.\n         rrwrite (nil >< ts = ts) in H14.\n         eapply typex_tenv_effect_strengthen.\n          eauto. auto.\n\n       * subst r.\n         eapply KiRgn.\n         rgwrite (SRegion p <: sp = sp ++ (nil :> SRegion p)).\n         eapply in_app_right; auto.\n\n     (* New frame stack is well typed. *)\n     + eapply TfConsPriv; eauto 2.\n\n       (* Effect of frame stack is still to live regions *)\n       * rrwrite (substTT 0 r e2 = e2).\n         have    (SubsT nil sp e e2 KEffect) \n          by     (eapply EqSym in H0; eauto).\n         eapply  liveE_subsT; eauto.\n\n       (* Frame stack is well typed after substituting region handle.\n          The initial type and effect are closed, so substituting\n          the region handle into them doesn't do anything. *)\n       * assert (ClosedT t0).\n         { have HK: (KindT  (nil :> (OCon, KRegion)) sp t0 KData).\n           eapply kind_wfT in HK.\n           simpl in HK.\n\n           have (~FreeT 0 t0) \n            by (eapply lowerTT_freeT; eauto).\n           eapply freeT_wfT_drop; eauto.\n         }\n\n         rrwrite (substTT 0 r t0 = t0).\n         rrwrite (substTT 0 r e2 = e2).\n         rrwrite (t1 = t0)\n          by (eapply lowerTT_closedT; eauto).\n         eauto.\n }\n\n\n (*********************************************************)\n (* Pop a private region from the frame stack. *)\n Case \"SfPrivatePop\".\n { inverts_typec.\n\n   (* We can only pop if there is at least on region in the store. *)\n   destruct sp.\n\n   (* No regions in store. *)\n   - inverts HH. rip. \n     unfold StoreP in *. rip.\n     have (In (FPriv None p ts) (fs :> FPriv None p ts)).\n     have (In (SRegion p) nil) by firstorder.\n     nope.\n\n   (* At least one region in store. *)\n   - destruct s.\n     exists se.\n     exists e2.\n     intuition.\n\n     (* Frame stack is still well formed after popping the top FUse frame *)\n     + eapply wfFS_region_deallocate; eauto.\n\n     (* After popping top FUse,\n        all store bindings mentioned by frame stack are still live. *)\n     + eapply liveS_deallocRegion; eauto.\n\n     (* New effect subsumes old one. *)\n     + eapply subsT_subsVisibleT. \n       have (EquivT nil (sp :> SRegion n) e2 e KEffect).\n       eauto.\n\n     (* Resulting configuation is well typed. *)\n     + eapply TcExp \n         with (sp := sp :> SRegion n)\n              (e1 := TBot KEffect)\n              (e2 := e2); eauto.\n\n       eapply EqSym; eauto.\n }\n\n\n (*********************************************************)\n (* Push an extend frame on the stack. *)\n Case \"SfExtendPush\".\n { inverts_typec.\n   set (r1 := TRgn p1).\n   set (r2 := TRgn p2).\n   exists se.\n   exists (TSum (substTT 0 r2 e0) (TSum e2 (TAlloc r1))).\n   intuition.\n   \n   (* Updated store is well formed. *)\n   - inverts_kind. \n     eapply wfFS_push_priv_ext; auto.\n\n   (* Updated store is live relative to frame stack. *)\n   - inverts HH.\n     subst p2.\n     eapply liveS_push_fpriv_some_allocRegion; eauto.\n\n     assert (SubsT nil sp e (TAlloc (TRgn p1)) KEffect).\n     { have (SubsT nil sp e (TSum (TSum eL (TAlloc (TRgn p1))) e2) KEffect).\n       eapply SbSumAboveLeft; eauto.\n     }\n\n     have (LiveE fs (TAlloc (TRgn p1))).\n     eapply liveSP_from_effect; eauto.\n      snorm.\n     \n   (* Frame stack is live relative to effect. *)\n   - apply liveE_sum_above.\n     + assert (ClosedT eL).\n       { have (KindT nil sp (TSum (TSum eL (TAlloc (TRgn p1))) e2) KEffect).\n         inverts_kind. eauto.\n       }\n\n       have HLL: (liftTT 1 0 eL = maskOnVarT 0 e0)\n        by  (eapply lowerTT_some_liftTT; eauto).\n       rrwrite (liftTT 1 0 eL = eL) in HLL.\n\n       have (LiveE fs (TSum (TSum eL (TAlloc (TRgn p1))) e2))\n        by (eapply liveE_equivT_left; eauto).\n       have (LiveE fs eL).\n\n       apply liveE_phase_change.\n\n       have HLW: (LiveE (fs :> FPriv (Some p1) p2 nil) eL).\n       rewrite HLL in HLW.\n\n       eapply liveE_maskOnVarT; eauto.\n\n    + have (SubsT nil sp e (TSum (TSum eL (TAlloc (TRgn p1))) e2) KEffect).\n      apply liveE_sum_above.\n      * have (SubsT nil sp e e2 KEffect).\n        eapply liveE_subsT; eauto.\n      * have (SubsT nil sp e (TAlloc (TRgn p1)) KEffect).\n        eapply liveE_subsT; eauto.\n      \n   (* Effect of result is subsumed by previous. *)\n   - set (sp' := SRegion p2 <: sp).\n     have (KindT nil sp    (TSum (TSum eL (TAlloc (TRgn p1))) e2) KEffect).\n     have (SubsT nil sp' e (TSum (TSum eL (TAlloc (TRgn p1))) e2) KEffect)\n      by (subst sp'; eapply subsT_stprops_snoc; eauto).\n\n     inverts_kind.\n\n     assert (SubsVisibleT nil sp' sp e (substTT 0 r2 e0)) as HE1.\n     { eapply subsVisibleT_mask\n        with (p := p2); auto.\n\n       have HL: (liftTT 1 0 eL = maskOnVarT 0 e0)\n        by (apply lowerTT_some_liftTT; auto).\n\n       rewrite <- HL.\n       rgwrite (liftTT 1 0 eL = eL).\n       eapply subsT_subsVisibleT.\n       eapply SbSumAboveLeft; eauto.\n      }\n\n     assert (SubsVisibleT nil sp' sp e e2)          as HE2.\n     { eapply subsT_subsVisibleT.\n       eapply SbSumAboveRight; eauto.\n     }\n\n     assert (SubsVisibleT nil sp' sp e (TAlloc r1)) as HE3.\n     { subst r1.\n       eapply subsT_subsVisibleT.\n       eapply SbSumAboveLeft; eauto.\n     }\n     eauto.\n\n   (* Resulting state is well typed. *)\n   - eapply TcExp\n       with (e1 := substTT 0 r2 e0)\n            (e2 := TSum e2 (TAlloc r1))\n            (t1 := substTT 0 r2 t0).\n     (* Equivalence of result effect *)\n     + eapply EqRefl.\n       eapply KiSum; auto.\n       * subst r2.\n         have (KindT (nil :> (OCon, KRegion)) sp                 e0 KEffect).\n         have (KindT (nil :> (OCon, KRegion)) (SRegion p2 <: sp) e0 KEffect).\n         have (KindT nil (SRegion p2 <: sp) (TRgn p2) KRegion).\n         eapply subst_type_type. eauto. eauto.\n       * apply equivT_kind_left in H0.\n         inverts_kind. subst r1.\n         eapply KiSum; auto.\n         eapply KiCon1. snorm. eauto.\n   \n     (* Expression with new region subst is well typed. *)\n     + rgwrite (nil = substTE 0 r2 nil).\n       rgwrite (se  = substTE 0 r2 se)\n        by (inverts HH; symmetry; auto).\n\n       eapply subst_type_exp.\n       * eapply typex_stprops_snoc.\n         rgwrite (nil = liftTE 0 nil).\n         rgwrite (se  = liftTE 0 se)\n          by (inverts HH; symmetry; auto).\n         eauto.\n       * subst r2. eauto.\n\n     (* Extended frame stack is well typed. *)\n     + have (KindT (nil :> (OCon, KRegion)) sp t0 KData).\n       have (not (In (SRegion p2) sp))\n        by (subst p2; auto).\n       eapply TfConsExt; eauto.\n       * inverts_kind. eauto.\n       * eapply typeF_freshSuppFs; eauto.\n       * have (LiveE fs (TSum (TSum eL (TAlloc (TRgn p1))) e2))\n          by (eapply liveE_equivT_left; eauto).\n         eapply liveE_sum_above.\n          eapply liveE_sum_above_right; eauto.\n          eapply liveE_sum_above_left  in H4.\n          eapply liveE_sum_above_right in H4.\n          trivial.\n       * erewrite mergeT_substTT.\n         eapply typeF_stprops_snoc. auto.\n         eauto. eauto.\n  }\n\n (*********************************************************)\n (* Pop and extend frame from the stack, \n    and merge the new region with the old one. *)\n Case \"SfExtendPop\".\n { inverts_typec.\n   set (r1 := TRgn p1).\n   set (r2 := TRgn p2).\n   exists (mergeTE p1 p2 se).\n   exists e0.\n   intuition.\n\n   (* Updated store is well formed. *)\n   - rrwrite (map (mergeB p1 p2) ss = mergeBs p1 p2 ss).\n     eapply wfFS_pop_priv_ext; eauto.\n    \n   (* Updated store is live relative to frame stack. *)\n   - SCase \"LiveS\".\n     eapply liveS_mergeB.\n     + have (LiveSF ss (FPriv (Some p1) p2 ts)).\n       unfold LiveSF in H0.\n       unfold LiveSP. intros.\n       eapply H0 in H1. inverts H1. auto.\n     + have (LiveS ss fs).\n       auto.\n\n   (* Frame stack is live relative to effect. *) \n   - SCase \"LiveE\".\n     eapply liveE_sum_above_left; eauto.\n\n   (* Effect of result is subsumed by previous. *)\n   - SCase \"SubsVisibleT\".\n     eapply subsT_subsVisibleT.\n     set (e' := (TSum (TBot KEffect) (TSum e0 (TAlloc (TRgn p1))))).\n     have (KindT  nil sp e'   KEffect).\n     have (EquivT nil sp e e' KEffect).\n     eapply SbSumAboveRight; eauto.\n\n   (* Resulting state is well typed. *)\n   - SCase \"TypeC\".\n     eapply TcExp\n       with (t1 := mergeT p1 p2 t1)\n            (e1 := TBot KEffect)\n            (e2 := e0).\n\n     (* Equivalence of result effect. *)\n     + have (KindT nil sp (TSum (TBot KEffect) \n                          (TSum e0 (TAlloc (TRgn p1)))) KEffect).\n       inverts_kind.\n       eapply EqSym; eauto.\n\n     (* Result value is well typed. *)\n     + rgwrite (nil                    = mergeTE p1 p2 nil).\n       rgwrite (XVal (mergeV p1 p2 v1) = mergeX  p1 p2 (XVal v1)).\n       rgwrite (TBot KEffect           = mergeT  p1 p2 (TBot KEffect)).\n       eapply mergeX_typeX. auto. eauto.\n\n     (* Popped frame stack is well typed. *)\n     + rgwrite (nil = mergeTE p1 p2 nil).\n       eapply typeF_mergeTE; eauto.\n }\n\n\n (*********************************************************)\n (* Run a suspension. *)\n Case \"SfRun\".\n { inverts HC.\n   inverts H0. inverts H7.\n   exists se. exists (TSum e1 e2).\n\n   have (KindT nil sp e KEffect)            as KS2.\n   have (KindT nil sp (TSum e1 e2) KEffect) as KS1.\n   inverts_kind.\n\n   rip; try (inverts HH; auto).\n\n   (* Frame stack is live *)\n   - eapply liveE_equivT_left.\n      eapply H.\n      auto.\n\n   (* Effect of result is subsumed by previous. *)\n   - apply subsT_subsVisibleT.\n     apply SbEquiv. \n     apply EqSym; auto.\n\n   (* Resulting state is well typed. *)\n   - apply TcExp\n      with (t1 := t1)\n           (e1 := e1)\n           (e2 := e2); auto.\n }\n\n\n (*********************************************************)\n (* Allocate a reference. *)\n Case \"SfStoreAlloc\".\n { inverts HC.\n   inverts H0.\n   exists (TRef   (TRgn p1) t2 <: se).\n   exists e2.\n   intuition.\n\n   (* Store is well formed after adding a binding. *)\n   - remember (TRgn p1) as r.\n\n     have (SubsT nil sp e (TAlloc r) KEffect)\n      by  (eapply EqSym in H; eauto).\n\n     have (LiveE fs (TAlloc r)).\n     subst r.\n\n     eapply wfFS_stbind_snoc; auto.\n     inverts_kind. auto.\n\n   (* Resulting effects are to live regions. *)\n   - have  (SubsT nil sp e e2 KEffect)\n      by   (eapply EqSym in H; eauto).\n     eapply liveE_subsT; eauto.\n\n   (* Original effect visibly subsumes resulting one. *)\n   - eapply EqSym in H.\n      eapply subsT_subsVisibleT; eauto.\n      eauto. eauto.\n\n   (* Resulting configuation is well typed. *)\n   - eapply TcExp\n      with (t1 := TRef (TRgn p1) t2)\n           (e1 := TBot KEffect)\n           (e2 := e2).\n     + eapply EqSym.\n        * eauto. \n        * eapply KiSum; eauto.\n        * eapply equivT_sum_left; eauto.\n     + eapply TxVal.\n       eapply TvLoc.\n        have    (length se = length ss).\n        rrwrite (length ss = length se).\n        eauto. eauto.\n     + eapply typeF_stenv_snoc; eauto.\n }\n\n\n (*********************************************************)\n (* Read from a reference. *)\n Case \"SfStoreRead\".\n { inverts HC.\n   exists se.\n   exists e2. \n   intuition.\n\n   (* Resulting effects are to live regions. *)\n   - have  (SubsT nil sp e e2 KEffect)\n      by   (eapply EqSym in H0; eauto).\n     eapply liveE_subsT; eauto.\n\n   (* Original effect visibly subsumes resulting one. *)\n   - eapply EqSym in H0.\n      eapply subsT_subsVisibleT; eauto.\n      eauto. eauto.\n\n   (* Resulting configutation is well typed. *)\n   - eapply TcExp\n      with (t1 := t1)\n           (e1 := TBot KEffect)\n           (e2 := e2).\n     + eapply EqSym; eauto.\n     + inverts H1.\n       inverts H12.\n       eapply TxVal.\n        inverts HH. rip.\n        eapply storet_get_typev; eauto.\n     + eauto.\n }\n\n\n (*********************************************************)\n (* Write to a reference. *)\n Case \"SfStoreWrite\".\n { inverts HC.\n   exists se.\n   exists e2.\n   intuition.\n\n   (* Resulting store is well formed. *)\n   - inverts_type.\n     eapply wfFS_stbind_update; eauto.\n     inverts_kind; auto.\n\n   (* All store bindings mentioned by frame stack are still live. *)\n   - inverts_type.\n\n     have (SubsT nil sp e (TWrite (TRgn p)) KEffect)\n      by  (eapply EqSym in H0; eauto).\n\n     have (LiveE fs (TWrite (TRgn p)))\n      by  (eapply liveE_subsT; eauto).\n\n     have (rgnOfEffect (TWrite (TRgn p)) = Some p).\n     lets D: liveE_fpriv_in fs H4; auto.\n     destruct D as [m].\n     destruct H5 as [ts].\n\n     eapply liveS_stvalue_update.\n     exists m. eauto.\n     auto.\n\n   (* Resulting effects are to live regions. *)\n   - have  (SubsT nil sp e e2 KEffect)\n      by   (eapply EqSym in H0; eauto).\n     eapply liveE_subsT; eauto.\n\n   (* Original effect visibly subsumes resulting one. *)\n    - eapply EqSym in H0.\n      eapply subsT_subsVisibleT; eauto.\n       eauto. eauto.\n\n   (* Resulting configuration is well typed. *)\n   - eapply TcExp\n      with (t1 := t1)\n           (e1 := TBot KEffect)\n           (e2 := e2).\n     + eapply EqSym; eauto.\n     + inverts_type.\n       eapply TxVal.\n        inverts HH. rip.\n     + eauto.\n }\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/Preservation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.29534388483648066}}
{"text": "Require Export read. \nRequire Export write. \n \nSection TransitionFunction. \n \n(*********************************************************************) \n(*                   The Transition Relation                         *) \n(*********************************************************************) \n \nInductive TransFunc : ENTITY -> SFSstate -> Operation -> SFSstate -> Prop :=\n  | DoRead :\n      forall (eSub : ENTITY) (eObj : ENTITY) (n : nat) (out : Exc ENTCONT)\n        (s : SFSstate), read s eSub eObj n s out -> TransFunc eSub s Read s\n  | DoWrite :\n      forall (eSub : ENTITY) (eObj : ENTITY) (n : nat) (buf : ENTCONT)\n        (s t : SFSstate), write s eSub eObj n buf t -> TransFunc eSub s Write t. \n \nEnd TransitionFunction. ", "meta": {"author": "kloisiie", "repo": "NFSModel", "sha": "f4027dd372151748fa4ade472e41af4484133c95", "save_path": "github-repos/coq/kloisiie-NFSModel", "path": "github-repos/coq/kloisiie-NFSModel/NFSModel-f4027dd372151748fa4ade472e41af4484133c95/TransFunc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2953438785102821}}
{"text": "Require Import Core.Core Core.VstTactics Core.StructNormalizer VstLib\n        ErrorWithWriter.\nRequire Import VST.floyd.proofauto.\nRequire Import Clight.ber_tlv_length.\nRequire Import Core.Notations Core.SepLemmas Core.Tactics \nExec.Ber_tlv_length_serialize. \n\nInstance CompSpecs : compspecs. Proof. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. Proof. mk_varspecs prog. Defined.\n\nOpen Scope Z.\n\nDefinition der_tlv_length_serialize_spec : ident * funspec :=\n  DECLARE _der_tlv_length_serialize\n  WITH l : int, buf_b : block, buf_ofs : ptrofs, buf_size : Z\n  PRE[tint, tptr tvoid, tuint]\n    PROP(0 <= buf_size <= 32;\n         Ptrofs.unsigned buf_ofs + buf_size < Ptrofs.modulus)\n    PARAMS(Vint l; (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   \n    PROP()\n    LOCAL(temp ret_temp \n               (Vint (Int.repr (snd (length_serialize l (Int.repr buf_size))))))\n    SEP(let (ls, z) := length_serialize l (Int.repr buf_size) in\n        data_at Tsh (tarray tuchar buf_size)\n                (map Vint ls ++ 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 [der_tlv_length_serialize_spec]).\n\n\nTheorem ber_tlv_length_serialize_correct : \n  semax_body Vprog Gprog (normalize_function f_der_tlv_length_serialize composites)\n             der_tlv_length_serialize_spec.\nAdmitted.\n(*\n Proof.\n  start_function.\n  remember (default_val (tarray tuchar buf_size)) as default_list.\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 l) 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%int \n           then data_at_ Tsh (tarray tuchar buf_size) (Vptr buf_b buf_ofs) \n           else \n             (data_at Tsh tuchar (Vint (Int.zero_ext 8 (Int.zero_ext 8 l)))\n                      (Vptr buf_b buf_ofs) *\n              data_at Tsh (tarray tuchar (buf_size - 1)) \n                      (sublist 1 buf_size default_list)\n                      (Vptr buf_b (buf_ofs + Ptrofs.repr 1)%ptrofs)))).\n    + rewrite <- LB.   \n      erewrite split_data_at_sublist_tuchar with (j := 1).\n      erewrite sublist_one.\n      erewrite data_at_tuchar_singleton_array_eq. \n      Intros.\n      repeat forward.\n      rewrite_if_b.\n      entailer!.\n      all: subst; try nia;\n        unfold default_val;\n        simpl;\n        try erewrite Zlength_list_repeat;\n        try nia; auto.\n    + forward.\n      rewrite_if_b.\n      entailer!.\n    + \n      unfold POSTCONDITION.\n      unfold abbreviate. \n      break_let.\n      forward.      \n       assert ((127 >=? Int.signed l) = true) as C.\n       { rewrite Z.geb_le. nia. } \n      break_if; unfold length_serialize in *; rewrite C in *; \n        rewrite_if_b;\n        inversion Heqp. all: rewrite_if_b; entailer!.\n        assert (buf_size = 0%Z).\n        eapply repr_inj_unsigned; strip_repr.\n       autorewrite with sublist.\n       entailer!.\n        assert (buf_size <> 0%Z).\n        eapply repr_neq_e in n;\n        lia.\n       erewrite <- split_non_empty_list.\n       entailer!.\n       erewrite Int.zero_ext_idem.\n       reflexivity.\n       all: autorewrite with sublist;\n         simpl; auto;\n       try rewrite LB in *;\n       try setoid_rewrite H7;\n       try nia.\n  -  assert (127 >=? Int.signed l = false) as C.\n     { erewrite Z.geb_leb. Zbool_to_Prop. nia. }\n     repeat forward.\n     forward_loop \n      (EX i: Z,\n          PROP (i = 1 \\/ i = 2 \\/ i = 3 \\/ i = 4; \n                forall j, 0 <= j < i ->\n                     (l >> (Int.repr j * Int.repr 8) == 0)%int = false)\n          LOCAL (temp _len (Vint l);\n                 temp _i (Vint (Int.repr (i * 8)));\n                 temp _required_size (Vint (Int.repr i));\n                 temp _size (Vint (Int.repr buf_size));\n                 temp _buf (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 l in\n              PROP ()\n              LOCAL (temp _required_size (Vint (Int.repr r));\n                     temp _len (Vint l);\n                     temp _i (Vint ((Int.repr (r * 8))));\n                     temp _size (Vint (Int.repr buf_size));\n                     temp _buf (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     + (* Pre implies Inv *)\n       Exists 1%Z.\n       entailer!.\n       intros. replace x with 0 by nia.\n       erewrite Int.shr_zero. \n       erewrite Int.signed_eq.\n       destruct zeq; \n       try rewrite e in *; auto.\n     + (* Inv exec fn Break *)\n       Intros i.\n       forward_if; repeat forward.\n       forward_if;\n         repeat forward.\n       Exists (i + 1).\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 H3.\n       nia.\n       do 2 f_equal.\n       nia.\n       entailer!.\n       assert (required_size l = i) as RS.\n       eapply required_size_spec; auto.\n       autorewrite with norm.\n       eassumption.\n       subst.\n       intuition.\n       entailer!.\n       replace i with 4 in * by nia.\n       assert (required_size l = 4) as RS.\n       eapply required_size_spec; auto.\n       autorewrite with norm.\n       cbn.\n       erewrite shr_lt_zero_32.\n       break_if; auto.\n       unfold Int.lt in Heqb.\n       break_if; autorewrite with norm in *.\n       replace (Int.signed 0%int) with 0 in * by auto with ints.\n       nia.\n       congruence.\n       rewrite RS.\n       intuition.     \n     + Intros.\n       pose proof (req_size_32 l).\n       unfold POSTCONDITION.\n       unfold abbreviate. \n       break_let.\n       forward_if.\n       forward.\n       unfold length_serialize in *; rewrite C in *.\n       inversion Heqp.\n         rewrite_if_b.\n       entailer!. \n       repeat break_if; try congruence; try\n       inversion Heqp; try eassumption; auto.\n       break_if.\n       Zbool_to_Prop.\n       generalize Heqb.\n       strip_repr.\n       intro. lia.\n       inversion Heqp.\n       autorewrite with sublist.\n       erewrite sublist_same_gen; auto.\n       setoid_rewrite LB. lia.\n       erewrite <- Heqdefault_list.\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       all: try nia.\n       Intros. \n        assert (buf_size <> 0) as BUF by lia. \n       repeat forward.\n       normalize.\n       erewrite Int.zero_ext_idem.\n       remember (required_size l) as r.\n       remember (Int.zero_ext 8 (Int.repr (128 or r)))%int as e0.      \n       remember (Int.repr (r * 8 - 8))%int as i.     \n     forward_loop \n    (EX v : Z, EX ls : list int,\n    (PROP ((Int.unsigned Int.zero <= v)%Z; \n           (v <= required_size l)%Z;\n           ls = \n           serialize_length_loop_app (r - v)%Z (Z.to_nat v) l)\n     LOCAL (temp _buf (Vptr buf_b (buf_ofs + Ptrofs.repr 1 + Ptrofs.repr v)%ptrofs);\n            temp _i (Vint (Int.repr ((r * 8) - (v + 1) * 8)%Z)); \n            temp _end (Vptr buf_b (buf_ofs\n                      + Ptrofs.repr (1 + Int.unsigned (Int.repr r))))%ptrofs;\n            temp _t'1 (Vptr buf_b buf_ofs); \n            temp _required_size (Vint (Int.repr r));\n            temp _len (Vint l); temp _size (Vint (Int.repr buf_size)))\n     SEP (data_at Tsh tuchar (Vint e0) (Vptr buf_b buf_ofs);\n          data_at Tsh (tarray tuchar v) \n                  (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                  (Vptr buf_b (buf_ofs + Ptrofs.repr 1 + Ptrofs.repr v)%ptrofs))))\n     break: \n    (EX ls : list int, EX j : int,          \n    (PROP (let r := required_size l in\n           let n :=  (Z.to_nat r) in\n         ls = serialize_length_loop_app 0 n l)\n     LOCAL (temp _buf (Vptr buf_b (buf_ofs + Ptrofs.repr 1\n                                   + Ptrofs.repr (len ls))%ptrofs);\n            temp _i (Vint j);\n            temp _end (Vptr buf_b (buf_ofs + Ptrofs.repr (1 + r))%ptrofs);\n            temp _t'1 (Vptr buf_b buf_ofs);\n            temp _required_size (Vint (Int.repr r)); \n            temp _len (Vint l); temp _size (Vint (Int.repr buf_size)))\n     SEP (data_at Tsh tuchar (Vint e0) (Vptr buf_b buf_ofs);\n          data_at Tsh (tarray tuchar (len ls)) (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                  (Vptr buf_b (buf_ofs + Ptrofs.repr 1\n                               + Ptrofs.repr (len ls))%ptrofs)))). \n      * Exists 0%Z.\n        Exists (@nil int).                \n        erewrite data_at_tuchar_zero_array_eq.\n        entailer!.\n        replace (len (default_val (tarray tuchar buf_size))) \n           with buf_size by (setoid_rewrite LB; lia).\n        auto.\n        replace (len (default_val (tarray tuchar buf_size))) \n           with buf_size by (setoid_rewrite LB; lia).\n        entailer!.\n        cbn; auto.\n      * Intros v ls.\n        forward_if; try nia.\n        entailer!.\n        \n         assert (0 < (buf_size - v - 1)) as LD by admit.\n        assert (sizeof (tarray tuchar (len (default_val (tarray tuchar buf_size)) - v - 1)) > 0).\n        { simpl.\n          erewrite Zmax0r.\n          setoid_rewrite LB. \n          nia.\n          setoid_rewrite LB. \n          nia. }\n        unfold test_order_ptrs.\n        unfold sameblock.\n        subst.\n        destruct peq; [  |contradiction].\n        apply andp_right.\n        apply derives_trans \n          with (Q := valid_pointer \n                       (Vptr buf_b (buf_ofs + Ptrofs.repr (1 + v))%ptrofs)).\n        entailer!.\n        apply valid_pointer_weak.\n        apply derives_trans \n          with (Q := valid_pointer \n                       (Vptr buf_b (buf_ofs\n                                    + Ptrofs.repr (1 + required_size l))%ptrofs)).\n        eapply sepcon_valid_pointer2.\n        remember (default_val (tarray tuchar buf_size)) as default_list.\n        remember (required_size l) as r.\n        erewrite data_at_app_gen\n          with (j1 := 1 + r - (v + 1))\n               (j2 := buf_size - (1 + r))\n               (ls1 := sublist (v + 1) (1 + r) default_list)\n               (ls2 := sublist (1 + r) buf_size default_list). \n        assert ((buf_ofs + Ptrofs.repr (1 + v) + Ptrofs.repr (1 + r - (v + 1)))%ptrofs =\n        (buf_ofs + Ptrofs.repr (1 + r))%ptrofs) as PTR.\n        {  ptrofs_compute_add_mul; try rep_omega.\n           f_equal.\n           rep_omega. }\n        rewrite PTR.\n        assert (0 < ((buf_size - r - 1))) as LDD by admit.\n        assert (sizeof (tarray tuchar (buf_size - r - 1)) > 0).\n        { simpl.\n          erewrite Zmax0r; nia. }\n        entailer!.\n        1-5: replace (Int.unsigned 0%int) with 0%Z in * by auto with ints;\n          subst; try setoid_rewrite LB; autorewrite with sublist; try list_solve. \n        auto.\n        ptrofs_compute_add_mul; try rep_omega.\n        apply valid_pointer_weak.\n        ++\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        eapply typed_true_ptr_lt in H7.\n        assert (v < required_size l)%Z.\n        { replace (Int.unsigned 0%int) with 0 in * by auto with ints.\n          generalize H7. ptrofs_compute_add_mul. subst. nia.\n          all: subst; rep_omega_setup; auto with ints; \n            autorewrite with norm; try rep_omega; try nia. }\n        Intros.\n        assert (len default_list - (v + 1) - 1 =\n                len (sublist (v + 1 + 1) buf_size default_list)) as LEN.\n        { erewrite Zlength_sublist_correct.\n          nia.\n          replace (Int.unsigned 0%int) with 0%Z in * by auto with ints.\n          all: lia. }\n        forward.\n        entailer!.\n        unfold Int.iwordsize.\n        ints_compute_add_mul.\n        cbn - [required_size].\n        all: try rep_omega.\n        auto with ints.\n        repeat forward.\n        remember (Int.zero_ext 8 \n                               (l >> (Int.repr ((required_size l - (v + 1)) * 8))))%int\n          as e_v.\n        normalize.\n        Exists (v + 1) (ls ++ [e_v]).\n        assert  (v = len ls) as VLS.\n        { subst.\n          erewrite loop_len_req_size.\n          replace (Int.unsigned 0%int) with 0%Z in * by (autorewrite with norm; auto).        \n          erewrite Z2Nat_id'.\n          erewrite Zmax0r.\n          nia.\n          nia. }\n        entailer!.\n        split.\n        erewrite Z.add_1_r at 3.\n        erewrite Z2Nat.inj_succ.       \n        simpl. f_equal. rewrite H6 at 1. \n        replace (required_size l - len ls)  with (required_size l - (len ls + 1) + 1) by nia.\n        reflexivity.\n        replace (Int.unsigned 0%int) with 0%Z in * by (autorewrite with norm; auto).     \n        nia. auto with ints.\n        split. \n        do 3 f_equal. nia.\n        do 2 f_equal. nia.\n        repeat erewrite Int.zero_ext_idem.\n        \n        replace ((required_size l - ((len ls) + 1)) * 8)%Z with \n               (required_size l * 8 - ((len ls) + 1) * 8)%Z by nia. \n        remember\n          (Int.zero_ext 8\n                        (l >> Int.repr (required_size l * 8 - ((len ls) + 1) * 8)))%int\n                 as e_v.\n        unfold offset_val.\n        simpl.\n        replace (1 + (len ls)) with ((len ls) + 1) by nia.\n        erewrite <- data_at_tuchar_singleton_array_eq.\n        remember (default_val (tarray tuchar buf_size)) as default_list.\n\n        replace (buf_ofs + Ptrofs.repr (1 + ((len ls) + 1)))%ptrofs with\n            (buf_ofs + 1 + Ptrofs.repr ((len ls) + 1))%ptrofs. \n\n        replace (buf_ofs + Ptrofs.repr ((len ls) + 1) + 1)%ptrofs with\n            (buf_ofs + 1 + Ptrofs.repr ((len ls) + 1))%ptrofs.       \n \n        replace (buf_ofs + Ptrofs.repr ((len ls) + 1))%ptrofs with (buf_ofs + 1 + Ptrofs.repr (len ls))%ptrofs.\n\n        erewrite <- data_at_app.\n        erewrite <- data_at_app.\n        erewrite <- data_at_app.\n        erewrite map_app.\n        replace buf_size with  (len default_list). \n        \n        entailer!.\n        autorewrite with list sublist.\n        nia.\n        setoid_rewrite <- LEN.\n        lia.\n        \n        all: try setoid_rewrite <- LEN.\n        all: replace (Int.unsigned 0%int) with 0%Z in * by (autorewrite with norm; auto);\n          autorewrite with  sublist;\n          try rep_omega.\n        all: try setoid_rewrite LB.\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 lia.\n          eapply typed_true_ptr_lt in H7.\n        assert (v < required_size l)%Z.\n        { replace (Int.unsigned 0%int) with 0 in * by auto with ints.\n          generalize H7. ptrofs_compute_add_mul. subst. nia.\n          all: subst; rep_omega_setup; auto with ints; \n            autorewrite with norm; try rep_omega; try nia. }\n        lia.\n        \n         eapply typed_true_ptr_lt in H7.\n        assert (v < required_size l)%Z.\n        { replace (Int.unsigned 0%int) with 0 in * by auto with ints.\n          generalize H7. ptrofs_compute_add_mul. subst. nia.\n          all: subst; rep_omega_setup; auto with ints; \n            autorewrite with norm; try rep_omega; try nia. } \n        lia.\n         eapply typed_true_ptr_lt in H7.\n        assert (v < required_size l)%Z.\n        { replace (Int.unsigned 0%int) with 0 in * by auto with ints.\n          generalize H7. ptrofs_compute_add_mul. subst. nia.\n          all: subst; rep_omega_setup; auto with ints; \n            autorewrite with norm; try rep_omega; try nia. }\n         erewrite Zlength_sublist_correct. lia.\n        all: try lia.\n        setoid_rewrite LB. lia.\n         ++ \n        eapply typed_false_ptr_lt in H7.\n         assert (required_size l < buf_size) by nia.\n        assert (v >= required_size l)%Z. \n        { replace (Int.unsigned 0%int) with 0%Z in * by auto with ints.\n          generalize H7.\n          ptrofs_compute_add_mul.\n          subst.\n         \n          all: subst; rep_omega_setup;\n            auto with ints; autorewrite with norm; try rep_omega; try nia.\n        }\n        repeat forward.\n        assert (v = required_size l) as V.\n        subst. nia.\n        rewrite V.\n        rewrite Heqr.  \n        Exists ls (Int.repr ((r * 8) - (r + 1) * 8)%Z).\n        replace (required_size l - required_size l)%Z with 0%Z by nia.\n        entailer!.\n        split.\n         replace (required_size l - required_size l)%Z with 0%Z by nia.\n        reflexivity.\n        erewrite Zlength_map in H13.\n        setoid_rewrite H13.\n        reflexivity.\n        replace (required_size l - required_size l)%Z with 0%Z in * by nia.\n        remember (serialize_length_loop_app 0 \n                  (Z.to_nat (required_size l)) l) as ls.\n        assert (required_size l = len ls) as L.\n        {  erewrite Zlength_map in H13.\n           subst.\n           rewrite <- H13 at 1.\n            replace (required_size l - required_size l)%Z with 0 by nia.\n           reflexivity. }\n         replace (required_size l - required_size l)%Z with 0 by nia.\n         erewrite Zlength_map in H13.\n         rewrite L.\n         entailer!.\n      * Intros ls j.\n        unfold POSTCONDITION.\n        unfold abbreviate.\n        pose proof (req_size_32 l).\n        assert (required_size l < buf_size) by nia.\n        forward.\n        unfold length_serialize in *.\n        rewrite C in *.\n        rewrite Int.unsigned_repr_eq in Heqp.\n        rewrite Zmod_small in Heqp.\n        erewrite <- Z.ltb_lt in H3.\n        rewrite H3 in Heqp.\n        inversion Heqp.\n        unfold serialize_length_app.\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 <- H4.\n        replace (len ls + 1 +\n                 (buf_size\n                  - len ls - 1))%Z\n          with buf_size.\n        replace (len (Int.zero_ext 8 (Int.repr 128 or Int.repr (required_size l))%int :: ls)) with \n            (len ls + 1)%Z by\n            (autorewrite with sublist list norm;\n             nia).\n        autorewrite with sublist.\n        normalize.\n        entailer!.\n         all: (autorewrite with sublist list norm;\n                     try nia; auto).\n         erewrite Zlength_sublist_correct.\n        nia.\n        all: try (subst;\n        erewrite loop_len_req_size;\n        erewrite Z2Nat_id';\n        erewrite Zmax0r;\n        rep_omega).\n        setoid_rewrite LB. lia.\n        autorewrite with sublist.\n        erewrite Zlength_sublist_correct; try  lia.\n        subst.\n        erewrite loop_len_req_size.\n        erewrite Z2Nat_id'.\n        erewrite Zmax0r.\n        all: rep_omega.\n       * lia.\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_length_serialize.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2953438785102821}}
{"text": "Require Export high_mods.\nRequire Import SO_facts3 vsS_syn_sem consistent.\n\nFixpoint newnew_pre alpha lv ln : SecOrder :=\n  match lv, ln with\n  | nil, _ => alpha\n  | _, nil => alpha\n  | cons x lv', cons n ln' =>\n    replace_FOv (newnew_pre alpha lv' ln') x (Var n)\n  end.\n\nLemma newnew_pre_nil : forall l alpha,\n  newnew_pre alpha l nil = alpha.\nProof. induction l; intros alpha; auto. Qed.\n\nLemma want16 : forall l beta n xn ym,\n    ~ (Var xn) = (Var ym) ->\n    free_FO beta (Var ym) = false ->\n    ym <= n ->  In (Var ym) l ->\n    ~ In (Var ym) (FOvars_in\n        (newnew_pre beta (rem_FOv (Var xn) l)\n        (rev_seq (S n)\n        (length (rem_FOv (Var xn) l))))).\nProof.\n  induction l; intros beta n xn ym Hneq Hfree Hleb Hin2. contradiction.\n  simpl in Hin2. destruct Hin2.\n  + subst. simpl. rewrite FOvariable_dec_r; auto.\n    simpl.  rewrite rep__ren_list. apply rename_FOv_list_not_eq.\n    apply FOv_not. lia.\n  + simpl. destruct (FOvariable_dec (Var xn) a); subst.\n    simpl. apply IHl; auto.\n    simpl. rewrite rep__ren_list.\n    destruct (FOvariable_dec a (Var (S (n + length (rem_FOv (Var xn) l))))).\n      subst. rewrite rename_FOv_list_refl. apply IHl; auto.\n    destruct (FOvariable_dec (Var ym) a). subst.\n    apply rename_FOv_list_not_eq. apply FOv_not. lia.\n    rewrite is_in_FOvar_rename_FOv_list; auto.\n    apply FOv_not. lia.\nQed.\n\nLemma want15 : forall beta xn a alpha,\n  free_FO beta a = false ->\n  In a (FOvars_in beta) ->\n  SOQFree beta = true ->\n  ~ att_allFO_var alpha (Var xn) ->\n  ~ (Var xn) = a ->\n  In a (FOvars_in alpha) ->\n  ~ In  a (FOvars_in\n    (newnew_pre (instant_cons_empty' alpha beta)\n       (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' alpha beta)) )\n       (rev_seq (S (Nat.max (Nat.max (max_FOv alpha) (max_FOv beta)) xn))\n          (length\n             (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' alpha beta))))))).\nProof.\n  intros beta xn [ym] alpha Hfree Hin3 Hno Hat Hneq Hin2.\n  apply want16; auto.\n  apply free_FO_instant_cons_empty'_f; auto. \n  unfold max_FOv. apply want19_pre in Hin2. \n  lia. apply kk1; auto.\nQed.\n\nLemma want14 : forall l beta xn a alpha,\n  SOQFree beta = true ->\n  free_FO beta a = false ->\n  ~ Var xn = a ->\n  In a (FOvars_in beta) ->\n  incl l (FOvars_in alpha) ->\n  ~ att_allFO_var alpha (Var xn) ->\n  In a (FOvars_in alpha) ->\n  ~  att_allFO_var\n    (newnew_pre (instant_cons_empty' alpha beta)\n       (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' alpha beta)))\n       (rev_seq (S (Nat.max (Nat.max (max_FOv alpha) (max_FOv beta)) xn))\n          (length\n             (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' alpha beta)))))) a.\nProof.\n  intros l beta xn [ym] alpha Hno Hfree Hin Hneq Hin3 Hat Hin2.\n  apply in_FOvar_att_allFO_x.  apply want15; auto.\nQed.\n\nLemma aa23 : forall l alpha x n,\n  ~ l = nil ->\n  var_in_SO alpha x ->\n  ~ In x l ->\n  ~ att_allFO_var alpha x ->\n  (max_FOv alpha) <= n ->\n  ~ att_allFO_var (newnew_pre alpha l (rev_seq (S n) (length l))) x.\nProof.\n  induction l; intros alpha x n Hnil Hocc Hin Hat Hleb. auto.\n  simpl in *.\n  pose proof Hocc as Hocc'.   pose proof Hleb as Hleb'.\n  unfold var_in_SO in Hocc. unfold max_FOv in *.\n  case_eq l. \n  + intros Hnil2. rewrite Hnil2 in *. simpl.\n    rewrite <- plus_n_O.\n    apply rep_FOv_att_allFO; try assumption.\n    destruct x. intros H. inversion H. subst. \n    apply want19_pre in Hocc. lia.\n  + intros z l' Heq. apply rep_FOv_att_allFO.  \n    rewrite <- Heq. apply IHl; subst; firstorder.\n    intros HH. destruct x. inversion HH. subst. \n    apply want19_pre in Hocc. lia.\nQed.\n\nLemma aa23_EX : forall l alpha x n,\n  ~ l = nil ->\n  var_in_SO alpha x ->\n  ~ In x l ->\n  ~ att_exFO_var alpha x ->\n  (max_FOv alpha) <= n ->\n  ~ att_exFO_var (newnew_pre alpha l\n    (rev_seq (S n) (length l))) x.\nProof.\n  induction l; intros alpha x n Hnil Hocc Hin Hat Hleb.\n    simpl. assumption.\n\n    simpl. simpl in Hin. apply not_or_and in Hin.\n    case_eq l. intros Hnil2. rewrite Hnil2 in *. simpl.\n      rewrite <- plus_n_O.\n      apply rep_FOv_att_exFO; try assumption.\n      unfold var_in_SO in Hocc. unfold max_FOv in Hleb.\n      destruct x. apply want19_pre in Hocc. intros HH. inversion HH.\n      subst. firstorder.\n\n      intros z l' Heq. assert (~ l = nil) as HH.\n      intros HH2. rewrite HH2 in Heq. discriminate.\n      destruct Hin as [Hin' Hin].\n      specialize (IHl _ _ n HH Hocc Hin Hat Hleb).\n      apply rep_FOv_att_exFO. rewrite <- Heq. apply IHl.\n      rewrite <- Heq.\n      intros H. destruct x. inversion H as [H']. subst.\n      unfold max_FOv in Hleb. unfold var_in_SO in Hocc.\n      apply want19_pre in Hocc. firstorder.\nQed.\n\nLemma aa24 : forall l alpha beta ym n,\n  In (Var ym) (FOvars_in alpha) ->\n  ~ In (Var ym) (FOvars_in beta) ->\n  ~ In (Var ym) l ->  ym <= n ->\n~ att_allFO_var\n    (newnew_pre (instant_cons_empty' alpha beta) l\n       (rev_seq (S n) (length l))) (Var ym).\nProof.\n  induction l; intros alpha beta ym n H1 H2 H3 Hleb.\n    simpl. apply att_allFO_instant_cons_empty'.\n    apply in_FOvar_att_allFO_x. assumption.\n\n    simpl. apply rep_FOv_att_allFO. apply IHl; auto.\n    firstorder. intros HH. inversion HH. lia.\nQed.\n\nLemma kk14'  : forall lx ln x alpha,\n~ In x lx -> closed_except alpha x ->\n(S (max_FOv alpha)) <= (min_l ln) ->\nclosed_except (newnew_pre alpha lx ln) x.\nProof.\n  induction lx; intros ln [xn] alpha Hin Hc Hleb. auto.\n  simpl in *. destruct a as [ym].\n  destruct ln. assumption.\n  apply not_or_and in Hin. destruct Hin as [Hin1 Hin2].\n  case_eq (min_l (cons n ln)).\n    intros Hmn; rewrite Hmn in *. inversion Hleb. \n  intros m Hmn.\n  destruct (PeanoNat.Nat.eq_dec xn n) as [Hbeq2 | Hbeq2].\n  + subst. apply kk19 in Hc.\n    rewrite Hmn in Hleb.\n    destruct (min_l_cons ln n) as [H1 | H2].\n      rewrite H1 in Hmn. subst. lia. \n    rewrite H2 in Hmn. \n    apply min_l_leb_cons2 in H2. lia.\n  + apply kk15; try assumption. auto.\n    apply FOv_not. auto.\n    case_eq ln.\n      intros Hln. rewrite newnew_pre_nil.\n      assumption.\n    intros n' l' Hln. rewrite <- Hln.\n    apply IHlx; try assumption.\n    rewrite Hmn in Hleb.\n    destruct (min_l_cons  ln n) as [H1 | H2].\n    rewrite H1 in Hmn. \n    pose proof H1 as H1'.\n    apply min_l_leb_cons1 in H1. lia.\n    subst. discriminate. lia.\nQed.\n\nLemma aa3' : forall lx ln alpha,\n  length lx = length ln ->\n  (S (max_FOv alpha)) <= (min_l ln) ->\n   (max_FOv (newnew_pre alpha lx ln)) <=\n          (max (max_FOv alpha) (max_l ln)).\nProof.\n  induction lx; intros ln alpha Hl Hleb; simpl in *.\n  + destruct ln. 2 : discriminate. lia.\n  + destruct ln. discriminate.\n    simpl in *. case_eq ln.\n    ++ intros Hln; rewrite Hln in *.\n       destruct lx. 2 : discriminate.\n       simpl. destruct (in_dec FOvariable_dec a (FOvars_in alpha)).\n       rewrite aa18_t. lia. lia. firstorder.\n       rewrite rep_FOv_not_in. lia. firstorder.\n    ++ intros m lm Hln. rewrite <- Hln.\n       destruct (in_dec FOvariable_dec a (FOvars_in (newnew_pre alpha lx ln))).\n       eapply (PeanoNat.Nat.le_trans). apply le_max_FOv_replace_FOv.\n       assert (max_FOv (newnew_pre alpha lx ln) <= \n               Nat.max (max_FOv alpha) (max_l ln)) as Hass.\n         apply IHlx; firstorder. rewrite Hln in *. lia.\n       lia.\n       rewrite rep_FOv_not_in. eapply PeanoNat.Nat.le_trans.\n       apply IHlx; firstorder. rewrite Hln in *. lia. lia.\n       firstorder.\nQed.\n\nLemma aa : forall ln lx alpha n,\n  length lx = length ln ->\n  (S (max_FOv alpha)) <= (min_l ln)  ->\n   (S (max_l ln)) <= n ->\n   (S(max_FOv (newnew_pre alpha lx ln))) <= n.\nProof.\n  intros ln lx alpha n Hl H1 H2.\n  eapply PeanoNat.Nat.le_trans.\n  + apply le_n_S. apply aa3'; auto.\n  + pose proof (le_min__max_l ln). lia. \nQed.\n\nLemma newnew_pre_extra_n : forall lx l1 l2 alpha,\n  length lx = length l1 ->\n  newnew_pre alpha lx (app l1 l2) = newnew_pre alpha lx l1.\nProof.\n  induction lx; intros l1 l2 alpha Heq. auto.\n  destruct l1. simpl in *. discriminate.\n  simpl. rewrite IHlx. reflexivity.\n  simpl in *. inversion Heq. reflexivity.\nQed.\n\nLemma newnew_pre_extra_x : forall ln l1 l2 alpha,\n  length ln = length l1 ->\n  newnew_pre alpha (app l1 l2) ln = newnew_pre alpha l1 ln.\nProof.\n  induction ln; intros l1 l2 alpha Heq.\n    do 2 rewrite newnew_pre_nil. reflexivity.\n\n    destruct l1. simpl in *. discriminate.\n    simpl. rewrite IHln. reflexivity.\n    simpl in *. inversion Heq. reflexivity.\nQed.\n\nLemma kk10 : forall lx ln alpha x,\n  closed_except alpha x ->\n  ~ In x lx ->\n  (S (max_FOv alpha)) <= (min_l ln) ->\n  decr_strict ln ->\n  forall W Iv Ip Ir,\n  SOturnst W Iv Ip Ir alpha <->\n  SOturnst W Iv Ip Ir (newnew_pre alpha lx ln).\nProof.\n  induction lx; intros ln alpha x Hc Hin Hleb Hd W Iv Ip Ir.\n    simpl. apply iff_refl.\n  simpl. destruct ln. apply iff_refl.\n  simpl in Hin. apply not_or_and in Hin.\n  destruct Hin. case_eq ln. \n  + intros Hln. subst. rewrite newnew_pre_nil.\n    apply (kk10_nil _ x); auto. \n\n  + intros m ln' Hln. rewrite <- Hln.\n    assert ((S (max_FOv alpha)) <= (min_l ln)) as Hleb2.\n      simpl in *. subst. lia.\n    inversion Hd. subst. remember (m :: ln') as ln.\n    assert ((S(max_l ln)) <= n) as Hleb3.  lia.\n    destruct (FOvariable_dec a (Var n)); subst.\n      rewrite rep_FOv_rem. apply (IHlx _ _ x); auto.\n    split; intros SOt. \n    ++ destruct (aa11' (m :: ln') lx) as [[ln1 [ln2 [H1 H2]]] | [lx1 [lx2 [H1 H2]]]].\n         -- rewrite H2. rewrite newnew_pre_extra_n. 2 : assumption.\n            case_eq lx. \n            * intros Hlx. simpl. destruct x as [xn].\n              pose proof  (equiv_replace_FOv_free_FO_f alpha a (Var n)).\n              unfold replace_FOv in H5.\n              apply H5; try assumption.\n              apply aa14 with (x := (Var xn));\n              try assumption. auto.\n              apply Hc.\n              destruct (in_dec FOvariable_dec (Var xn) (FOvars_in alpha)).\n              apply want19_pre in i. intros HH. inversion HH. subst.\n              \n              unfold max_FOv in Hleb. clear -Hleb i. simpl in *.\n              lia. destruct Hc as [HH1 HH2]. apply free_FO_var_in in HH1.\n              contradiction.\n              intros HH. apply var_in_SO_max_FOv_gen2 in HH.\n              apply HH. simpl in Hleb. clear -Hleb.\n              destruct ln'; lia.\n\n            * intros y lx' Hlx. rewrite <- Hlx.\n              assert (~ var_in_SO (newnew_pre alpha lx ln1) (Var n)) as\n                  Has. destruct n. simpl in *. destruct ln'; inversion Hleb. \n                intros HH.  apply var_in_SO_max_FOv_gen2 in HH. apply HH.\n                apply aa; auto. rewrite H2 in *.\n                destruct ln2. simpl in *. rewrite app_nil_r in *. auto.\n                rewrite min_l_app in Hleb2.\n                lia. destruct ln1. rewrite Hlx in *. simpl in *. discriminate.\n                discriminate. discriminate.\n                apply aa16 with (l2 := ln2).  rewrite <- H2.  lia.\n              apply equiv_replace_FOv_free_FO_f; auto.\n              ** pose proof (kk14' lx ln1) as H3'.\n                 apply aa14 with (x := x); auto.\n                 apply H3'; try assumption.\n                 apply (aa15 _ _ ln2); auto.\n                 intros H'. rewrite H' in H1. simpl in H1.\n                 rewrite Hlx in H1. discriminate.\n                 rewrite <- H2. assumption.\n              ** apply var_in_SO_free_FO. assumption. \n              ** rewrite <- (newnew_pre_extra_n lx ln1 ln2).\n                 rewrite <- H2. apply (IHlx _ alpha x).\n                 all: try assumption. \n(* -- *)\n          -- rewrite H2. rewrite newnew_pre_extra_x. 2 : assumption.\n             assert (~ var_in_SO (newnew_pre alpha lx1 (m :: ln')) (Var n)) as\n                 Has. intros HH. destruct n. simpl in *.\n               apply var_in_SO_max_FOv_gen2 in HH. apply HH.\n               simpl in Hleb. lia.   apply var_in_SO_max_FOv_gen2 in HH.\n               apply HH. apply aa; auto. \n               apply equiv_replace_FOv_free_FO_f; auto.\n             --- pose proof (kk14' lx1 (m :: ln')) as H3'.\n                 apply aa14 with (x := x). apply H3'; try assumption.\n                 subst. clear -H0. firstorder. auto.\n             --- apply var_in_SO_free_FO. assumption. \n             --- rewrite <- (newnew_pre_extra_x _ _ lx2).\n                 rewrite <- H2. apply (IHlx (m :: ln') alpha x).\n                 all: try assumption.\n\n(* -- *)\n\n    ++  unfold lt in H3. remember (m :: ln') as ln.\n       destruct (aa11' ln lx) as [[ln1 [ln2 [H1 H2]]] | [lx1 [lx2 [H1 H2]]]].\n       - rewrite H2 in *. rewrite newnew_pre_extra_n in *. 2 : assumption.\n         case_eq lx.\n         -- intros Hlx. simpl. destruct x as [xn]. rewrite Hlx in *.\n            pose proof  (equiv_replace_FOv_free_FO_f alpha a (Var n)) as H5.\n            unfold replace_FOv in H5.\n            apply H5; try assumption.\n            apply aa14 with (x := (Var xn));\n              try assumption; auto.\n            rewrite <- H2 in *. \n            apply (aa17 _ ln n (Var xn)); try assumption. \n            intros HH. apply var_in_SO_max_FOv_gen2 in HH. apply HH.\n            rewrite <- H2 in *. clear -Hleb. simpl in *.\n            destruct ln; lia.\n         -- intros y lx' Hlx.\n            assert (~ var_in_SO (newnew_pre alpha lx ln1) (Var n)) as\n                Has. intros HH. apply var_in_SO_max_FOv_gen2 in HH. \n              apply HH. apply aa; auto. destruct ln1. simpl in *. \n              destruct lx; discriminate.\n              clear -Hleb H3. eapply PeanoNat.Nat.le_trans.\n              apply Hleb. change (n :: (n1 :: ln1) ++ ln2) with ((n :: (n1 :: ln1)) ++ ln2). \n              destruct ln2. rewrite app_nil_r in *. simpl. lia.\n              rewrite min_l_app. simpl. lia. discriminate. discriminate.\n              destruct ln1.  simpl in *. destruct ln2. simpl in *.\n              firstorder. simpl in *. destruct lx; discriminate.\n              apply (aa16 _ ln2). rewrite <- H2 in *. lia. \n            apply equiv_replace_FOv_free_FO_f in SOt; auto.\n            * rewrite <- (newnew_pre_extra_n _ ln1 ln2) in SOt.\n              rewrite <- H2 in *. apply (IHlx ln alpha x) in SOt.\n              all: try assumption. \n            * pose proof (kk14' lx ln1) as H4'.\n              apply aa14 with (x := x).\n              apply H4'; try assumption.\n              apply (aa15 _ _ ln2).\n              intros H'. rewrite H' in H1. simpl in H1.\n              rewrite Hlx in H1. discriminate.\n              assumption. auto.\n            * apply var_in_SO_free_FO. assumption.\n\n       - rewrite H2 in *. rewrite newnew_pre_extra_x in *. 2 : assumption.\n         assert (~ var_in_SO (newnew_pre alpha lx1 ln) (Var n)) as\n             Has. destruct n.\n           simpl in *. destruct ln; firstorder. \n           intros HH.  apply var_in_SO_max_FOv_gen2 in HH.\n           apply HH. apply aa; auto. \n         apply equiv_replace_FOv_free_FO_f in SOt; auto.\n         -- rewrite <- (newnew_pre_extra_x _ _ lx2) in SOt.\n            rewrite <- H2 in *. apply (IHlx ln alpha x).\n            all: try assumption. \n         -- pose proof (kk14' lx1 ln) as H4'.\n            apply aa14 with (x := x).\n            apply H4'; try assumption.\n            firstorder. auto.\n         -- apply var_in_SO_free_FO. assumption.\nQed.\n\nLemma newnew_pre_rename_FOv_list_l : forall lv ln alpha,\n  FOvars_in (newnew_pre alpha lv ln) = \n  rename_FOv_list_l (FOvars_in alpha) lv (FOvify ln). \nProof.\n  induction lv; intros ln alpha. auto.\n  simpl. destruct ln. auto.\n  simpl. rewrite rep__ren_list. rewrite IHlv. auto.\nQed.\n\nLemma SOQFree_newnew_pre : forall l1 l2 alpha,\n  SOQFree alpha = true ->\n  SOQFree (newnew_pre alpha l1 l2) = true.\nProof.\n  induction l1; intros l2 alpha H; auto.\n  simpl. destruct l2. assumption.\n  apply SOQFree_rep_FOv. auto. \nQed.\n\nLemma want3 : forall l alpha beta xn,\n  SOQFree beta = true ->\n  incl l (FOvars_in alpha) ->\n  ~ att_allFO_var alpha (Var xn) ->\n  closed_except beta (Var xn) ->\n  ~ att_allFO_var beta (Var xn) ->\n~ ex_att_allFO_lvar\n  (newnew_pre (instant_cons_empty' alpha beta)\n     (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' alpha beta)))\n     (rev_seq (S (Nat.max (Nat.max (max_FOv alpha) (max_FOv beta)) xn))\n        (length\n           (rem_FOv \n              (Var xn) (FOvars_in (instant_cons_empty' alpha beta)))))) l.\nProof.\n  induction l; intros alpha beta xn Hno Hin Hat Hcl Hat2.\n    intros H. inversion H.\n  simpl in *. pose proof (incl_hd _ _ _ _ Hin) as H4. apply incl_lcons in Hin. \n  intros H. inversion H; subst.\n  + destruct a as [ym]. \n    destruct (FOvariable_dec (Var ym) (Var xn)) as [Heq | Heq].\n    inversion Heq. subst.\n    case_eq ( rem_FOv (Var xn) (FOvars_in (instant_cons_empty' alpha beta))).\n      intros HH. rewrite HH in *. simpl in *.\n      eapply att_allFO_instant_cons_empty' in H2; auto.\n    intros mm lmm Hmm. \n    apply aa23 in H2; auto.\n    ++ rewrite Hmm . discriminate.\n    ++ apply var_in_SO_instant_cons_empty'.\n       inversion Hcl as [Hcl1 Hcl2].\n       pose proof (var_in_SO_free_FO beta (Var xn)) as H0. \n       rewrite Hcl1 in *. unfold var_in_SO in *.\n       destruct (in_dec FOvariable_dec (Var xn) (FOvars_in beta)) as [H2' | H2']. \n       auto. apply H0 in H2'. discriminate.\n    ++ apply is_in_FOvar_rem_FOv_f. \n    ++ apply att_allFO_instant_cons_empty'. auto.\n    ++ rewrite max_FOv_instant_cons_empty'.\n       unfold max_FOv. simpl.  lia.\n    ++ destruct (in_dec FOvariable_dec (Var ym) (FOvars_in beta)).\n    eapply want14 in H4; auto.\n    unfold max_FOv in *. simpl in *. \n    simpl in *. contradiction (H4 H2).\n    all : auto. inversion Hcl as [Hcl1 Hcl2].\n    apply Hcl2. auto. apply Hin.\n    eapply aa24. apply H4. apply n. 3 : apply H2.\n    intros HH. apply want13 in HH. unfold instant_cons_empty' in HH.\n    apply kk8 in HH; auto. auto.\n    pose proof (want19_pre _ _ H4).\n    unfold max_FOv in *. lia.\n  + apply IHl in H2; auto.\nQed.\n\nLemma lem3 : forall beta rel atm xn P,\n  REL rel = true ->\n  AT atm = true ->\n  SOQFree beta = true ->\n  closed_except beta (Var xn) ->\n  ~ att_allFO_var beta (Var xn) ->\n~ ex_att_allFO_lvar\n     (newnew_pre (instant_cons_empty' (conjSO rel atm) beta)\n        (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' (conjSO rel atm) beta)))\n        (rev_seq (S (Nat.max (Nat.max (Nat.max (max_FOv rel) (max_FOv atm)) (max_FOv beta)) xn))\n           (length\n              (rem_FOv  (Var xn) (FOvars_in (instant_cons_empty' (conjSO rel atm) beta))\n                )))) (FOv_att_P (conjSO rel atm) P).\nProof.\n  intros beta rel atm xn P HREL HAT Hno Hcl Hatt.\n  rewrite <- max_FOv_conjSO.\n  apply want3; try assumption. \n  apply incl_FOv_att_P. intros H.\n  inversion H; subst.\n  apply att_allFO_var_REL in H3; auto.\n  apply att_allFO_var_AT in H3; auto.\nQed.\n\nLemma lem3_atm : forall beta atm xn P,\n  AT atm = true ->\n  SOQFree beta = true ->\n  closed_except beta (Var xn) ->\n  ~ att_allFO_var beta (Var xn) ->\n~ ex_att_allFO_lvar\n     (newnew_pre (instant_cons_empty' atm beta)\n        (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' atm beta)))\n        (rev_seq (S (Nat.max (Nat.max (max_FOv atm) (max_FOv beta)) xn))\n           (length\n              (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' atm beta))\n                 )))) (FOv_att_P atm P).\nProof.\n  intros beta  atm xn P  HAT Hno Hcl Hatt.\n  apply want3; try assumption.  apply incl_FOv_att_P.\n  simpl. intros H. apply att_allFO_var_AT in H; auto.\nQed.\n\n\nLemma want15_EX : forall beta xn a alpha,\n  free_FO beta a = false ->\n  In a (FOvars_in beta) ->\n  SOQFree beta = true ->\n  ~ att_exFO_var alpha (Var xn) ->\n  ~ (Var xn) = a ->\n  In a (FOvars_in alpha) ->\n  ~ In a (FOvars_in\n    (newnew_pre (instant_cons_empty' alpha beta)\n       (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' alpha beta)))\n       (rev_seq (S (Nat.max (Nat.max (max_FOv alpha) (max_FOv beta)) xn))\n          (length\n             (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' alpha beta))))))).\nProof.\n  intros beta xn [ym] alpha Hfree Hin3 Hno Hat Hneq Hin2.\n  apply want16; try assumption.\n  apply free_FO_instant_cons_empty'_f; try assumption.\n  unfold max_FOv. apply want19_pre in Hin2. lia.\n  apply kk1; auto.\nQed.\n\nLemma want14_EX : forall l beta xn a alpha,\n  SOQFree beta = true ->\n  free_FO beta a = false ->\n  ~ Var xn = a ->\n  In a (FOvars_in beta) ->\n  incl l (FOvars_in alpha) ->\n  ~ att_exFO_var alpha (Var xn) ->\n  In a (FOvars_in alpha) ->\n ~ att_exFO_var\n    (newnew_pre (instant_cons_empty' alpha beta)\n       (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' alpha beta)))\n       (rev_seq (S (Nat.max (Nat.max (max_FOv alpha) (max_FOv beta)) xn))\n          (length\n             (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' alpha beta)) ))))\n    a.\nProof.\n  intros l beta xn [ym] alpha Hno Hfree Hin Hneq Hin3 Hat Hin2.\n  apply is_in_FOvar_att_exFO_var_neg.\n  apply want15_EX; try assumption.\nQed.\n\nLemma aa24_EX : forall l alpha beta ym n,\n  In (Var ym) (FOvars_in alpha) ->\n  ~ In (Var ym) (FOvars_in beta) ->\n  ~ In (Var ym) l ->\n  ym <= n ->\n~ att_exFO_var\n    (newnew_pre (instant_cons_empty' alpha beta) l\n       (rev_seq (S n) (length l))) (Var ym).\nProof.\n  induction l; intros alpha beta ym n H1 H2 H3 Hleb; simpl.\n  + apply att_exFO_instant_cons_empty'.\n    apply is_in_FOvar_att_exFO_var_neg. assumption.\n  + destruct (PeanoNat.Nat.eq_dec (S (n + length l)) ym).\n    subst. lia. \n    apply rep_FOv_att_exFO.\n    apply IHl; try assumption. \n    simpl in H3. firstorder.\n    apply FOv_not. auto.\nQed.\n\nLemma want3_EX : forall l alpha beta xn,\n  SOQFree beta = true ->\n  incl l (FOvars_in alpha) ->\n  ~ att_exFO_var alpha (Var xn) ->\n  closed_except beta (Var xn) ->\n  ~ att_exFO_var beta (Var xn) ->\n~ ex_att_exFO_lvar\n  (newnew_pre (instant_cons_empty' alpha beta)\n     (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' alpha beta)))\n     (rev_seq (S (Nat.max (Nat.max (max_FOv alpha) (max_FOv beta)) xn))\n        (length\n           (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' alpha beta))\n  )))) l.\nProof.\n  induction l; intros alpha beta xn Hno Hin Hat Hcl Hat2.\n  intros HH. inversion HH. pose proof (incl_hd _ _ _ _ Hin) as Hin'.\n  apply incl_lcons in Hin.  destruct a as [ym].\n  destruct (PeanoNat.Nat.eq_dec xn ym) as [Hbeq | Hbeq].\n  + subst ym.\n    case_eq (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' alpha beta))).\n    intros H. simpl.\n    intros HH. inversion HH; subst.\n    apply att_exFO_instant_cons_empty' in H2;  auto.\n    eapply IHl in Hat2; auto. rewrite H in Hat2.\n    simpl in Hat2. contradiction. auto. auto.\n    intros y l' Heq. rewrite <- Heq.\n    intros HH. inversion HH; subst. apply aa23_EX in H1; auto.\n    rewrite Heq. discriminate. \n    apply var_in_SO_instant_cons_empty'.\n    apply free_FO_var_in. apply Hcl. apply is_in_FOvar_rem_FOv_f.\n    apply att_exFO_instant_cons_empty'. assumption.\n    rewrite max_FOv_instant_cons_empty'. lia. \n    apply IHl in H1; auto. \n  + destruct (in_dec FOvariable_dec (Var ym) (FOvars_in beta)).\n    intros HH. inversion HH; subst.  \n    eapply want14_EX in H1; auto.\n    inversion Hcl as [Hcl1 Hcl2]. apply Hcl2. apply FOv_not. auto.\n    apply FOv_not. auto.  apply Hin.\n    apply IHl in H1; auto.\n    intros HH. inversion HH; subst.\n    eapply aa24_EX in H1; auto.\n    intros HH2. apply want13 in HH2.\n    eapply kk7. 2 : apply HH2. auto.\n    apply FOv_not. auto.\n    apply want19_pre in Hin'. unfold max_FOv. lia.\n    apply IHl in H1; auto.\nQed.\n\nLemma lem5 : forall beta rel atm xn P,\n  REL rel = true ->\n  AT atm = true ->\n  SOQFree beta = true ->\n  closed_except beta (Var xn) ->\n  ~ att_exFO_var beta (Var xn) ->\n~ ex_att_exFO_lvar\n     (newnew_pre (instant_cons_empty' (conjSO rel atm) beta)\n        (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' (conjSO rel atm) beta)))\n        (rev_seq (S (Nat.max (Nat.max (Nat.max (max_FOv rel) (max_FOv atm)) (max_FOv beta)) xn))\n           (length\n              (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' (conjSO rel atm) beta))\n                )))) (FOv_att_P (conjSO rel atm) P).\nProof.\n  intros beta rel atm xn P HREL HAT Hno Hcl Hatt.\n  rewrite <- max_FOv_conjSO.\n  apply want3_EX; try assumption.\n  apply incl_FOv_att_P.\n  intros HH; inversion HH; subst.\n  apply att_exFO_var_REL in H2; auto.\n  apply att_exFO_var_AT in H2; auto.\nQed. \n\nLemma lem5_atm : forall beta atm xn P,\n  AT atm = true ->\n  SOQFree beta = true ->\n  closed_except beta (Var xn) ->\n  ~att_exFO_var beta (Var xn) ->\n~ ex_att_exFO_lvar\n     (newnew_pre (instant_cons_empty' atm beta)\n        (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' atm beta)))\n        (rev_seq (S (Nat.max (Nat.max (max_FOv atm) (max_FOv beta)) xn))\n           (length\n              (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' atm beta))\n                )))) (FOv_att_P atm P).\nProof.\n  intros beta atm xn P  HAT Hno Hcl Hatt.\n  apply want3_EX; try assumption.\n  apply incl_FOv_att_P.\n  simpl. apply att_exFO_var_AT.\n  all : try assumption.\nQed.\n\nLemma lem2 : forall lP beta rel atm xn,\n  REL rel = true ->\n  AT atm = true ->\n  SOQFree beta = true ->\n  ~ att_allFO_var beta (Var xn) ->\n  closed_except beta (Var xn) ->\n~ ex_att_allFO_llvar\n  (newnew_pre (instant_cons_empty' (conjSO rel atm) beta)\n     (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' (conjSO rel atm) beta)))\n     (rev_seq\n        (S (Nat.max (Nat.max (Nat.max (max_FOv rel) (max_FOv atm)) (max_FOv beta)) xn))\n        (length (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' (conjSO rel atm) beta)) ))))\n  (FOv_att_P_l (conjSO rel atm) lP).\nProof.\n  induction lP; intros beta rel atm xn HREL HAT Hno Hat1 Hcl H.\n    inversion H.\n  simpl in *. inversion H; subst. \n  apply lem3 in H2; auto.\n  apply IHlP in H2 ; assumption.\nQed.\n\nLemma lem2_atm : forall lP beta atm xn,\n  AT atm = true ->\n  SOQFree beta = true ->\n  ~ att_allFO_var beta (Var xn) ->\n  closed_except beta (Var xn) ->\n~ ex_att_allFO_llvar\n  (newnew_pre (instant_cons_empty' atm beta)\n     (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' atm beta)))\n     (rev_seq\n        (S (Nat.max (Nat.max ( (max_FOv atm)) (max_FOv beta)) xn))\n        (length (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' atm beta))))))\n  (FOv_att_P_l atm lP).\nProof.\n  induction lP; intros beta atm xn HAT Hno Hat1 Hcl H.\n    inversion H.\n  simpl in *. inversion H; subst. \n  apply lem3_atm in H2; auto. \n  apply IHlP in H2 ; assumption.\nQed.\n\nLemma lem4a : forall lP beta rel atm xn,\n  REL rel = true ->\n  AT atm = true ->\n  SOQFree beta = true ->\n  ~ att_exFO_var beta (Var xn) ->\n  closed_except beta (Var xn) ->\n~ ex_att_exFO_llvar\n  (newnew_pre (instant_cons_empty' (conjSO rel atm) beta)\n     (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' (conjSO rel atm) beta)))\n     (rev_seq\n        (S (Nat.max (Nat.max (Nat.max (max_FOv rel) (max_FOv atm)) (max_FOv beta)) xn))\n        (length (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' (conjSO rel atm) beta))))))\n  (FOv_att_P_l (conjSO rel atm) lP).\nProof.\n  induction lP; intros beta rel atm xn HREL HAT Hno Hat1 Hcl.\n  intros HH. inversion HH.\n  simpl FOv_att_P_l. simpl.\n  pose proof lem5 as H3. simpl in H3.\n  intros HH. inversion HH; subst.\n  eapply H3 in H1; try assumption.\n  clear H3. apply IHlP in H1; assumption.\nQed.\n\nLemma lem4a_atm : forall lP beta atm xn,\n  AT atm = true ->\n  SOQFree beta = true ->\n  ~ att_exFO_var beta (Var xn) ->\n  closed_except beta (Var xn) ->\n~ ex_att_exFO_llvar\n  (newnew_pre (instant_cons_empty' atm beta)\n     (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' atm beta)))\n     (rev_seq\n        (S (Nat.max (Nat.max ( (max_FOv atm)) (max_FOv beta)) xn))\n        (length (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' atm beta))))))\n  (FOv_att_P_l atm lP).\nProof.\n  induction lP; intros beta atm xn HAT Hno Hat1 Hcl.\n  intros HH. inversion HH.\n  simpl FOv_att_P_l. simpl.\n  pose proof lem5_atm as H3. simpl in H3.\n  intros HH. inversion HH; subst.\n  eapply H3 in H1; try assumption.\n  clear H3. apply IHlP in H1; assumption.\nQed.\n\nLemma preds_in_newnew_pre : forall l1 l2 alpha,\n  preds_in (newnew_pre alpha l1 l2) = (preds_in alpha).\nProof.\n  induction l1; intros l2 alpha. auto.\n  simpl. destruct l2. reflexivity.\n  rewrite preds_in_rename_FOv. apply IHl1.\nQed.\n\nLemma hopeful2 : forall  lx rel atm y xn beta,\n  FO_frame_condition (replace_pred_l (list_closed_allFO (implSO\n    (conjSO rel atm)\n    (newnew_pre (instant_cons_empty' (conjSO rel atm) beta)  \n      (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' (conjSO rel atm) beta)))\n      (rev_seq (S (max (max_FOv (implSO (conjSO rel atm) beta)) xn))\n        (length       (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' (conjSO rel atm) beta))))))) lx)\n    (preds_in (list_closed_allFO\n      (implSO (conjSO rel atm) beta) lx)) (list_var (length (preds_in (list_closed_allFO\n      (implSO (conjSO rel atm) beta) lx))) y)\n    (vsS_syn_l (FOv_att_P_l (conjSO rel atm) (preds_in (list_closed_allFO\n      (implSO (conjSO rel atm) beta) lx))) y)) = true.\nProof.\n  intros lx rel atm y xn beta.\n  rewrite rep_pred_l_list_closed_allFO.\n  rewrite FO_frame_condition_list_closed_allFO.\n  rewrite rep_pred_l_implSO.\n  simpl. rewrite preds_in_list_closed_allFO.\n  rewrite please2.\n  rewrite please2. reflexivity.\n  rewrite preds_in_newnew_pre.\n  apply (incl_trans _ _ _ _ (something3 _ _)).\n  simpl. firstorder. \n  simpl.  firstorder. \nQed.\n\n\nLemma hopeful2_atm : forall  lx atm y xn beta,\n  FO_frame_condition (replace_pred_l (list_closed_allFO (implSO\n    atm\n    (newnew_pre (instant_cons_empty' atm beta)  \n      (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' atm beta)))\n      (rev_seq (S (max (max_FOv (implSO atm beta)) xn))\n        (length       (rem_FOv (Var xn) (FOvars_in (instant_cons_empty' atm beta))))))) lx)\n    (preds_in (list_closed_allFO\n      (implSO atm beta) lx)) (list_var (length (preds_in (list_closed_allFO\n      (implSO atm beta) lx))) y)\n    (vsS_syn_l (FOv_att_P_l atm (preds_in (list_closed_allFO\n      (implSO atm beta) lx))) y)) = true.\nProof.\n  intros lx atm y xn beta.\n  rewrite rep_pred_l_list_closed_allFO.\n  rewrite FO_frame_condition_list_closed_allFO.\n  rewrite rep_pred_l_implSO.\n  simpl. rewrite preds_in_list_closed_allFO.\n  rewrite please2.\n  rewrite please2. reflexivity.\n  rewrite preds_in_newnew_pre.\n  apply (incl_trans _ _ _ _ (something3 _ _)).\n  simpl. firstorder. \n  simpl. firstorder.\nQed.", "meta": {"author": "caitlindabrera", "repo": "Sahlqvist", "sha": "d0a755fb663a6cabc0babb691564cdf575fc8b36", "save_path": "github-repos/coq/caitlindabrera-Sahlqvist", "path": "github-repos/coq/caitlindabrera-Sahlqvist/Sahlqvist-d0a755fb663a6cabc0babb691564cdf575fc8b36/vsSahlq/coq_code/newnew.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2953438721840835}}
{"text": "Require Import Verdi.Verdi.\nRequire Import Verdi.LabeledNet.\nRequire Import Verdi.TotalMapSimulations.\nRequire Import Verdi.PartialMapSimulations.\nRequire Import Verdi.TotalMapExecutionSimulations.\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.\nRequire Import ssr.ssrbool.\n\nSet Implicit Arguments.\n\nClass LabeledMultiParamsPartialMapCongruency\n  (B0 : BaseParams) (B1 : BaseParams)\n  (P0 : LabeledMultiParams B0) (P1 : LabeledMultiParams B1)\n  (B : BaseParamsPartialMap B0 B1) \n  (N : MultiParamsNameTotalMap (@unlabeled_multi_params _ P0) (@unlabeled_multi_params _ P1))\n  (P : MultiParamsMsgPartialMap (@unlabeled_multi_params _ P0) (@unlabeled_multi_params _ P1))\n  (L : LabeledMultiParamsLabelTotalMap P0 P1) : Prop :=\n  {\n    pt_lb_label_silent_fst_snd : tot_map_label label_silent = label_silent ;\n    pt_lb_net_handlers_some : forall me src m st m' out st' ps lb,\n      pt_map_msg m = Some m' ->\n      lb_net_handlers (tot_map_name me) (tot_map_name src) m' (pt_map_data st) = (lb, out, st', ps) ->\n      lb <> label_silent /\\ tot_mapped_lb_net_handlers_label me src m st = lb ;\n    pt_lb_net_handlers_none : forall me src m st,\n      pt_map_msg m = None ->\n      tot_mapped_lb_net_handlers_label me src m st = label_silent ;\n    pt_lb_input_handlers_some : forall me inp st inp' out st' ps lb,\n      pt_map_input inp = Some inp' ->\n      lb_input_handlers (tot_map_name me) inp' (pt_map_data st) = (lb, out, st', ps) ->\n      lb <> label_silent /\\ tot_mapped_lb_input_handlers_label me inp st = lb ;\n    pt_lb_input_handlers_none : forall me inp st,\n      pt_map_input inp = None ->\n      tot_mapped_lb_input_handlers_label me inp st = label_silent\n  }.\n\nSection PartialMapExecutionSimulations.\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 : BaseParamsPartialMap base_fst base_snd}.\nContext {name_map : MultiParamsNameTotalMap (@unlabeled_multi_params _ labeled_multi_fst) (@unlabeled_multi_params _ labeled_multi_snd)}.\nContext {msg_map : MultiParamsMsgPartialMap (@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 : MultiParamsPartialMapCongruency base_map name_map msg_map}.\nContext {multi_map_lb_congr : LabeledMultiParamsPartialMapCongruency base_map name_map msg_map label_map}.\n\nHypothesis label_eq_dec : forall x y : label, {x = y} + {x <> y}.\n\nHypothesis tot_map_label_injective : \n  forall l l', tot_map_label l = tot_map_label l' -> l = l'.\n\nHypothesis label_tot_mapped :\n  forall l, exists l', l = tot_map_label l'.\n\n(* lb_step_failure *)\n\nTheorem lb_step_failure_pt_mapped_simulation_1_non_silent :\n  forall net net' failed failed' lb tr,\n    tot_map_label lb <> label_silent ->\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, pt_map_net net) (tot_map_label lb) (List.map tot_map_name failed', pt_map_net net') (filterMap pt_map_trace_occ tr).\nProof using name_map_bijective multi_map_lb_congr multi_map_congr.\nmove => net net' failed failed' lb tr H_neq H_step.\nhave H_neq': lb <> label_silent.\n  rewrite -pt_lb_label_silent_fst_snd in H_neq.\n  move => H_eq.\n  by rewrite H_eq in H_neq.\ninvcs H_step => //=.\n- destruct (pt_map_packet p) eqn:?; last first.\n    destruct p.\n    simpl in *.\n    break_match => //.\n    have H_q := @pt_lb_net_handlers_none _ _ _ _ _ _ _ _ multi_map_lb_congr pDst pSrc _ (nwState net pDst) Heqo0.\n    rewrite /tot_mapped_lb_net_handlers_label in H_q.\n    repeat break_let.\n    by tuple_inversion.\n  have H_eq_n: tot_map_name (pDst p) = pDst p0.\n    destruct p.\n    simpl in *.\n    break_match => //.\n    by find_injection.\n  rewrite H_eq_n.\n  apply (@LabeledStepFailure_deliver _ _ _ _ _ _ (filterMap pt_map_packet xs) (filterMap pt_map_packet ys) (filterMap pt_map_output out) (pt_map_data d) (filterMap (@pt_map_name_msg _ _ _ _ _ msg_map) l)).\n  * rewrite /pt_map_net /=.\n    find_rewrite.\n    by rewrite filterMap_app /= Heqo.\n  * rewrite -H_eq_n.\n    exact: not_in_failed_not_in.\n  * rewrite /pt_map_net /= -{2}H_eq_n tot_map_name_inv_inverse.\n    destruct p, p0.\n    simpl in *.\n    break_match => //.\n    find_injection.\n    clean.\n    have H_q := @pt_net_handlers_some _ _ _ _ _ _ _ multi_map_congr pDst pSrc pBody (nwState net pDst) _ Heqo0.\n    rewrite /pt_mapped_net_handlers /net_handlers /= /unlabeled_net_handlers in H_q.\n    repeat break_let.\n    repeat tuple_inversion.\n    have H_q' := @pt_lb_net_handlers_some _ _ _ _ _ _ _ _ multi_map_lb_congr _ _ _ _ _ _ _ _ _ Heqo0 Heqp1.\n    rewrite /tot_mapped_lb_net_handlers_label in H_q'.\n    repeat break_let.\n    break_and.\n    by repeat tuple_inversion.\n  * rewrite /pt_map_net /= 2!filterMap_app.\n    by rewrite (filterMap_pt_map_packet_map_eq_some _ _ Heqo) (pt_map_update_eq_some _ _ _ Heqo).\n- case H_i: pt_map_input => [inp'|]; last first.\n    have H_q := @pt_lb_input_handlers_none _ _ _ _ _ _ _ _ multi_map_lb_congr h _ (nwState net h) H_i.\n    rewrite /tot_mapped_lb_input_handlers_label /= in H_q.\n    repeat break_let.\n    by tuple_inversion.\n  apply (@LabeledStepFailure_input _ _ _ _ _ _ _ _ (pt_map_data d) (filterMap (@pt_map_name_msg _ _ _ _ _ msg_map) l)).\n  * exact: not_in_failed_not_in.\n  * have H_q := @pt_input_handlers_some _ _ _ _ _ _ _ multi_map_congr h _ (nwState net h) _ H_i.\n    rewrite /pt_mapped_input_handlers /input_handlers /= /unlabeled_input_handlers in H_q.\n    repeat break_let.\n    repeat tuple_inversion.\n    have H_q' := @pt_lb_input_handlers_some _ _ _ _ _ _ _ _ multi_map_lb_congr _ _ _ _ _ _ _ _ H_i Heqp1.\n    break_and.\n    unfold tot_mapped_lb_input_handlers_label in *.\n    repeat break_let.\n    repeat tuple_inversion.\n    by rewrite /pt_map_net /= tot_map_name_inv_inverse.\n  * rewrite /pt_map_net /=.\n    rewrite filterMap_app filterMap_pt_map_packet_map_eq.\n    by rewrite -(@pt_map_update_eq  _ _ _ _ _ _ name_map_bijective).\nQed.\n\nTheorem lb_step_failure_pt_mapped_simulation_1_silent :\n  forall net net' failed failed' lb tr,\n    tot_map_label lb = label_silent ->\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, pt_map_net net) label_silent (List.map tot_map_name failed', pt_map_net net') [] /\\ filterMap trace_non_empty_out (filterMap pt_map_trace_occ tr) = [].\nProof using multi_map_lb_congr multi_map_congr.\nmove => net net' failed failed' lb tr H_eq H_step.\ninvcs H_step => //=.\n- destruct (pt_map_packet p) eqn:?.\n    destruct p, p0.\n    simpl in *.\n    break_match_hyp => //.\n    find_injection.\n    have H_q := @pt_net_handlers_some _ _ _ _ _ _ _ multi_map_congr pDst pSrc pBody (nwState net pDst) _ Heqo0.\n    rewrite /pt_mapped_net_handlers /net_handlers /= /unlabeled_net_handlers in H_q.\n    repeat break_let.\n    repeat tuple_inversion.\n    have H_q' := @pt_lb_net_handlers_some _ _ _ _ _ _ _ _ multi_map_lb_congr _ _ _ _ _ _ _ _ _ Heqo0 Heqp1.\n    break_and.\n    unfold tot_mapped_lb_net_handlers_label in *.\n    repeat break_let.\n    by repeat tuple_inversion.\n  destruct p.\n  simpl in *.\n  break_match_hyp => //.\n  have H_q := @pt_net_handlers_none _ _ _ _ _ _ _ multi_map_congr pDst pSrc pBody (nwState net pDst) out d l Heqo0.\n  rewrite /net_handlers /= /unlabeled_net_handlers in H_q.\n  repeat break_let.\n  repeat tuple_inversion.\n  concludes.\n  break_and.\n  have H_q' := @pt_lb_net_handlers_none _ _ _ _ _ _ _ _ multi_map_lb_congr pDst pSrc _ (nwState net pDst) Heqo0.\n  rewrite /tot_mapped_lb_net_handlers_label in H_q'.\n  repeat break_let.\n  repeat tuple_inversion.\n  rewrite /pt_map_net /=.\n  rewrite filterMap_app.\n  rewrite filterMap_pt_map_name_msg_empty_eq //=.\n  rewrite H3.\n  rewrite filterMap_app /=.\n  repeat break_match => //.\n  rewrite -filterMap_app.\n  set s1 := fun _ => _.\n  set s2 := fun _ => _.\n  have H_eq_s: s1 = s2.\n    rewrite /s1 /s2.\n    apply functional_extensionality => n.\n    rewrite /update.\n    by break_if; first by rewrite H e.\n  rewrite -H_eq_s /s1 {s1 s2 H_eq_s}.\n  split => //.\n  exact: LabeledStepFailure_stutter.\n- case H_i: (pt_map_input inp) => [inp'|].\n    have H_q := @pt_input_handlers_some _ _ _ _ _ _ _ multi_map_congr h _ (nwState net h) _ H_i.\n    rewrite /pt_mapped_input_handlers /input_handlers /= /unlabeled_input_handlers in H_q.\n    repeat break_let.\n    repeat tuple_inversion.\n    have H_q' := @pt_lb_input_handlers_some _ _ _ _ _ _ _ _ multi_map_lb_congr _ _ _ _ _ _ _ _ H_i Heqp1.\n    break_and.\n    unfold tot_mapped_lb_input_handlers_label in *.\n    repeat break_let.\n    by tuple_inversion.\n  have H_q := @pt_input_handlers_none _ _ _ _ _ _ _ multi_map_congr h _ (nwState net h) out d l H_i.\n  rewrite /input_handlers /= /unlabeled_input_handlers in H_q.\n  repeat break_let.\n  repeat tuple_inversion.\n  concludes.\n  break_and.\n  have H_q' := @pt_lb_input_handlers_none _ _ _ _ _ _ _ _ multi_map_lb_congr h _ (nwState net h) H_i.\n  rewrite /tot_mapped_lb_input_handlers_label in H_q'.\n  repeat break_let.\n  repeat tuple_inversion.\n  rewrite /pt_map_net /=.\n  rewrite filterMap_app.\n  rewrite filterMap_pt_map_name_msg_empty_eq //=.\n  set s1 := fun _ => _.\n  set s2 := fun _ => _.\n  have H_eq_s: s1 = s2.\n    rewrite /s1 /s2.\n    apply functional_extensionality => n.\n    rewrite /update.\n    by break_if; first by rewrite H e.\n  rewrite -H_eq_s /s1 {s1 s2 H_eq_s}.\n  split; first exact: LabeledStepFailure_stutter.\n  by repeat find_rewrite.\n- split => //; exact: LabeledStepFailure_stutter.\nQed.\n\n(* lb_step_ordered_failure *)\n\nTheorem lb_step_ordered_failure_pt_mapped_simulation_1_non_silent :\n  forall net net' failed failed' lb tr,\n    tot_map_label lb <> label_silent ->\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, pt_map_onet net) (tot_map_label lb) (List.map tot_map_name failed', pt_map_onet net') (filterMap pt_map_trace_ev tr).\nProof using name_map_bijective multi_map_lb_congr multi_map_congr.\nmove => net net' failed failed' lb tr H_neq H_step.\nhave H_neq': lb <> label_silent.\n  rewrite -pt_lb_label_silent_fst_snd in H_neq.\n  move => H_eq.\n  by rewrite H_eq in H_neq.\ninvcs H_step => //=.\n- rewrite {2}/pt_map_onet /=.\n  case H_m: (@pt_map_msg _ _ _ _ msg_map m) => [m'|]; last first.\n    have H_q := @pt_lb_net_handlers_none _ _ _ _ _ _ _ _ multi_map_lb_congr to from _ (onwState net to) H_m.\n    rewrite /tot_mapped_lb_net_handlers_label in H_q.\n    repeat break_let.\n    by tuple_inversion.\n  apply (@LabeledStepOrderedFailure_deliver _ _ _ _ _ _ m' (filterMap (@pt_map_msg _ _ _ _ msg_map) ms) (filterMap pt_map_output out) (pt_map_data d) (filterMap (@pt_map_name_msg _ _ _ _ _ msg_map) l) (@tot_map_name _ _ _ _ name_map from) (@tot_map_name _ _ _ _ name_map to)).\n  * by rewrite /= 2!tot_map_name_inv_inverse /= H3 /= H_m.\n  * exact: not_in_failed_not_in.\n  * rewrite /pt_map_onet /= tot_map_name_inv_inverse.\n    have H_q := @pt_net_handlers_some _ _ _ _ _ _ _ multi_map_congr to from m (onwState net to) _ H_m.\n    rewrite /pt_mapped_net_handlers /net_handlers /= /unlabeled_net_handlers in H_q.\n    repeat break_let.\n    repeat tuple_inversion.\n    have H_q' := @pt_lb_net_handlers_some _ _ _ _ _ _ _ _ multi_map_lb_congr _ _ _ _ _ _ _ _ _ H_m Heqp1.\n    rewrite /tot_mapped_lb_net_handlers_label in H_q'.\n    repeat break_let.\n    break_and.\n    by repeat tuple_inversion.\n  * rewrite (@collate_pt_map_update2_eq _ _ _ _ name_map).\n    set f1 := fun _ => pt_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 -filterMap_pt_map_trace_ev_outputs_eq.\n- rewrite {2}/pt_map_onet /=.\n  case H_i: pt_map_input => [inp'|]; last first.\n    have H_q := @pt_lb_input_handlers_none _ _ _ _ _ _ _ _ multi_map_lb_congr h inp (onwState net h) H_i.\n    rewrite /tot_mapped_lb_input_handlers_label in H_q.\n    repeat break_let.\n    by tuple_inversion.\n  apply (@LabeledStepOrderedFailure_input _ _ (@tot_map_name _ _ _ _ name_map h) _ _ _ _ (filterMap pt_map_output out) inp' (pt_map_data d) (filterMap (@pt_map_name_msg _ _ _ _ _ msg_map) l)).\n  * exact: not_in_failed_not_in.\n  * rewrite /pt_map_onet /= tot_map_name_inv_inverse.\n    have H_q := @pt_input_handlers_some _ _ _ _ _ _ _ multi_map_congr h inp (onwState net h) _ H_i.\n    rewrite /pt_mapped_input_handlers /input_handlers /= /unlabeled_input_handlers in H_q.\n    repeat break_let.\n    repeat tuple_inversion.\n    have H_q' := @pt_lb_input_handlers_some _ _ _ _ _ _ _ _ multi_map_lb_congr _ _ _ _ _ _ _ _ H_i Heqp1.\n    rewrite /tot_mapped_lb_input_handlers_label in H_q'.\n    repeat break_let.\n    break_and.\n    by repeat tuple_inversion.\n  * rewrite {2}/pt_map_onet /=.\n    rewrite (@collate_pt_map_eq _ _ _ _ name_map).\n    set f1 := fun _ => pt_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 -(@filterMap_pt_map_trace_ev_outputs_eq _ _ _ _ _ name_map out h).\nQed.\n     \nTheorem lb_step_ordered_failure_pt_mapped_simulation_1_silent :\n  forall net net' failed failed' lb tr,\n    tot_map_label lb = label_silent ->\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, pt_map_onet net) label_silent (List.map tot_map_name failed', pt_map_onet net') [] /\\ filterMap pt_map_trace_ev tr = [].\nProof using name_map_bijective multi_map_lb_congr multi_map_congr.\nmove => net net' failed failed' lb tr H_eq H_step.\ninvcs H_step => //=.\n- rewrite {2}/pt_map_onet /=.\n  case H_m: (@pt_map_msg _ _ _ _ msg_map m) => [m'|].\n    have H_q := @pt_net_handlers_some _ _ _ _ _ _ _ multi_map_congr to from m (onwState net to) _ H_m.\n    rewrite /pt_mapped_net_handlers /net_handlers /= /unlabeled_net_handlers in H_q.\n    repeat break_let.\n    repeat tuple_inversion.\n    have H_q' := @pt_lb_net_handlers_some _ _ _ _ _ _ _ _ multi_map_lb_congr _ _ _ _ _ _ _ _ _ H_m Heqp1.\n    break_and.\n    unfold tot_mapped_lb_net_handlers_label in *.\n    repeat break_let.\n    by repeat tuple_inversion.\n  have H_q := @pt_net_handlers_none _ _ _ _ _ _ _ multi_map_congr to from m (onwState net to) out d l H_m.\n  rewrite /net_handlers /= /unlabeled_net_handlers in H_q.\n  repeat break_let.\n  repeat tuple_inversion.\n  concludes.\n  break_and.\n  have H_q' := @pt_lb_net_handlers_none _ _ _ _ _ _ _ _ multi_map_lb_congr to from _ (onwState net to) H_m.\n  rewrite /tot_mapped_lb_net_handlers_label in H_q'.\n  repeat break_let.\n  repeat tuple_inversion.\n  rewrite /pt_map_onet /=.\n  rewrite (@collate_pt_map_update2_eq _ _ _ _ name_map) /=.\n  rewrite H0 /=.\n  set p1 := fun _ _ => _.\n  set p2 := update2 _ _ _ _ _.\n  set s1 := fun _ => _.\n  set s2 := fun _ => _.\n  have H_eq_p: p1 = p2.\n    rewrite /p1 /p2 /update2.\n    apply functional_extensionality => src.\n    apply functional_extensionality => dst.\n    break_if => //.\n    break_and.\n    by rewrite -H2 -H5 2!tot_map_name_inv_inverse H3 /= H_m.\n  have H_eq_s: s1 = s2.\n    rewrite /s1 /s2 /update.\n    apply functional_extensionality => n.\n    break_if => //.\n    by rewrite H e.\n  rewrite H_eq_p H_eq_s.\n  split; first exact: LabeledStepOrderedFailure_stutter.\n  rewrite (@filterMap_pt_map_trace_ev_outputs_eq _ _ _ _ _ name_map out to).\n  by repeat find_rewrite.\n- case H_i: (pt_map_input inp) => [inp'|].\n    have H_q := @pt_input_handlers_some _ _ _ _ _ _ _ multi_map_congr h _ (onwState net h) _ H_i.\n    rewrite /pt_mapped_input_handlers /input_handlers /= /unlabeled_input_handlers in H_q.\n    repeat break_let.\n    repeat tuple_inversion.\n    have H_q' := @pt_lb_input_handlers_some _ _ _ _ _ _ _ _ multi_map_lb_congr _ _ _ _ _ _ _ _ H_i Heqp1.\n    break_and.\n    unfold tot_mapped_lb_input_handlers_label in *.\n    repeat break_let.\n    by tuple_inversion.\n  have H_q := @pt_input_handlers_none _ _ _ _ _ _ _ multi_map_congr h _ (onwState net h) out d l H_i.\n  rewrite /input_handlers /= /unlabeled_input_handlers in H_q.\n  repeat break_let.\n  repeat tuple_inversion.\n  concludes.\n  break_and.\n  have H_q' := @pt_lb_input_handlers_none _ _ _ _ _ _ _ _ multi_map_lb_congr h _ (onwState net h) H_i.\n  rewrite /tot_mapped_lb_input_handlers_label in H_q'.\n  repeat break_let.\n  repeat tuple_inversion.\n  rewrite /pt_map_onet /=.\n  rewrite (@collate_pt_map_eq _ _ _ _ name_map) H0 /=.\n  set s1 := fun _ => pt_map_data _.\n  set s2 := fun _ => pt_map_data _.\n  have H_eq_s: s1 = s2.\n    rewrite /s1 /s2.\n    apply functional_extensionality => n.\n    rewrite /update.\n    by break_if; first by rewrite H e.\n  rewrite -H_eq_s /s1 {s1 s2 H_eq_s}.\n  split; first exact: LabeledStepOrderedFailure_stutter.\n  rewrite (@filterMap_pt_map_trace_ev_outputs_eq _ _ _ _ _ name_map).\n  by repeat find_rewrite.\n- by split => //; exact: LabeledStepOrderedFailure_stutter.\nQed.\n\nDefinition pt_map_onet_event e :=\n{| evt_a := (List.map tot_map_name (fst e.(evt_a)), pt_map_onet (snd e.(evt_a))) ;\n   evt_l := tot_map_label e.(evt_l) ;\n   evt_trace := filterMap pt_map_trace_ev e.(evt_trace) |}.\n\nLemma pt_map_onet_event_Map_unfold : forall s,\n Cons (pt_map_onet_event (hd s)) (map pt_map_onet_event (tl s)) = map pt_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_pt_map_onet_infseq : forall s,\n  lb_step_execution lb_step_ordered_failure s ->\n  lb_step_execution lb_step_ordered_failure (map pt_map_onet_event s).\nProof using name_map_bijective multi_map_lb_congr multi_map_congr label_eq_dec.\ncofix c.\nmove => s H_exec.\nrewrite -pt_map_onet_event_Map_unfold {1}/pt_map_onet_event /=.\ninversion H_exec; subst => /=.\nrewrite -pt_map_onet_event_Map_unfold /= /pt_map_onet_event /=.\ncase (label_eq_dec (tot_map_label (evt_l e)) label_silent) => H_eq.\n  apply: Cons_lb_step_exec.\n  - rewrite H_eq.\n    destruct e, e'.\n    destruct evt_a, evt_a0.\n    simpl in *.\n    by eapply lb_step_ordered_failure_pt_mapped_simulation_1_silent; eauto.\n  - destruct e, e'.\n    destruct evt_a, evt_a0.\n    apply (lb_step_ordered_failure_pt_mapped_simulation_1_silent H_eq) in H.\n    break_and.\n    simpl in *.\n    rewrite H0 filterMap_app.\n    by aggressive_rewrite_goal.\n  - pose s' := Cons e' s0.\n    rewrite (pt_map_onet_event_Map_unfold s').\n    exact: c.\napply: Cons_lb_step_exec => /=.\n- destruct e, e'.\n  destruct evt_a, evt_a0.\n  simpl in *.\n  by eapply lb_step_ordered_failure_pt_mapped_simulation_1_non_silent; eauto.\n- by rewrite H0 filterMap_app.\n- pose s' := Cons e' s0.\n  rewrite (pt_map_onet_event_Map_unfold s').\n  exact: c.\nQed.\n\nLemma pt_map_onet_tot_map_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 pt_map_onet_event s).\nProof using.\nmove => l.\napply: always_map.\napply: eventually_map.\ncase => e s.\nrewrite /= /occurred /evt_l /=.\nmove => H_eq.\nby rewrite H_eq.\nQed.\n\nLemma pt_map_onet_tot_map_label_event_inf_often_occurred_conv :\n  forall l s,\n    inf_often (now (occurred (tot_map_label l))) (map pt_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- exact: extensional_now.\n- exact: extensional_now.\n- case => e s.\n  rewrite /= /occurred /=.\n  move => H_eq.\n  exact: tot_map_label_injective.\nQed.\n\nHypothesis lb_step_ordered_failure_strong_fairness_enabled_pt_map_onet_eventually :\n  forall l, tot_map_label l <> label_silent ->\n    forall s, lb_step_execution lb_step_ordered_failure s ->\n    strong_fairness lb_step_ordered_failure label_silent s ->\n    enabled lb_step_ordered_failure (tot_map_label l) (pt_map_onet_event (hd s)) ->\n    eventually (now (enabled lb_step_ordered_failure l)) s.\n\nLemma pt_map_onet_tot_map_labeled_event_inf_often_enabled :\n  forall l, tot_map_label l <> label_silent ->\n    forall s, lb_step_execution lb_step_ordered_failure s ->\n    strong_fairness lb_step_ordered_failure label_silent s ->\n    inf_often (now (enabled lb_step_ordered_failure (tot_map_label l))) (map pt_map_onet_event s) ->\n    inf_often (now (enabled lb_step_ordered_failure l)) s.\nProof using lb_step_ordered_failure_strong_fairness_enabled_pt_map_onet_eventually.\nmove => l H_neq s H_exec H_fair.\nhave H_a: ((lb_step_execution lb_step_ordered_failure) /\\_ (strong_fairness lb_step_ordered_failure label_silent)) s by auto.\nmove: H_a {H_exec H_fair}.\napply: always_map_conv_ext => {s}.\n  rewrite /and_tl /=.\n  move => x s0 [H_e H_w].\n  apply lb_step_execution_invar in H_e.\n  by apply strong_fairness_invar in H_w.\napply: eventually_map_conv_ext.\n- exact: extensional_now.\n- exact: extensional_now.\n- apply extensional_and_tl.\n  * exact: lb_step_execution_extensional.\n  * exact: strong_fairness_extensional.\n- rewrite /and_tl /=.\n  move => x s [H_e H_w].\n  apply lb_step_execution_invar in H_e.\n  by apply strong_fairness_invar in H_w.\n- rewrite /and_tl.\n  case => /= x s [H_a H_w] H_en.\n  exact: lb_step_ordered_failure_strong_fairness_enabled_pt_map_onet_eventually.\nQed.\n\nHypothesis lb_step_ordered_failure_weak_fairness_always_enabled_pt_map_onet_continuously : \n  forall l, tot_map_label l <> label_silent -> \n    forall s, lb_step_execution lb_step_ordered_failure s ->\n    weak_fairness lb_step_ordered_failure label_silent s ->\n    always (now (enabled lb_step_ordered_failure (tot_map_label l))) (map pt_map_onet_event s) ->\n    continuously (now (enabled lb_step_ordered_failure l)) s.\n\nLemma pt_map_onet_tot_map_labeled_event_state_continuously_enabled :\n  forall l, tot_map_label l <> label_silent ->    \n    forall s, lb_step_execution lb_step_ordered_failure s ->\n    weak_fairness lb_step_ordered_failure label_silent s ->\n    continuously (now (enabled lb_step_ordered_failure (tot_map_label l))) (map pt_map_onet_event s) ->\n    continuously (now (enabled lb_step_ordered_failure l)) s.\nProof using lb_step_ordered_failure_weak_fairness_always_enabled_pt_map_onet_continuously.\nmove => l H_neq s H_exec H_fair.\nhave H_a: ((lb_step_execution lb_step_ordered_failure) /\\_ (weak_fairness lb_step_ordered_failure label_silent)) s by auto.\nmove: H_a {H_exec H_fair}.\napply: eventually_map_conv_ext => {s}.\n- apply extensional_always.\n  exact: extensional_now.\n- apply extensional_always.\n  exact: extensional_now.\n- apply extensional_and_tl.\n  * exact: lb_step_execution_extensional.\n  * exact: weak_fairness_extensional.\n- rewrite /and_tl /=.\n  move => x s [H_e H_w].\n  apply lb_step_execution_invar in H_e.\n  by apply weak_fairness_invar in H_w.\n- case => x s [H_a H_w] H_al.\n  simpl in *.\n  exact: lb_step_ordered_failure_weak_fairness_always_enabled_pt_map_onet_continuously.\nQed.\n\nLemma pt_map_onet_tot_map_label_event_strong_fairness :\n  forall s, lb_step_execution lb_step_ordered_failure s ->\n       strong_fairness lb_step_ordered_failure label_silent s ->\n       strong_fairness lb_step_ordered_failure label_silent (map pt_map_onet_event s).\nProof using multi_map_lb_congr lb_step_ordered_failure_strong_fairness_enabled_pt_map_onet_eventually label_tot_mapped.\nmove => s.\nrewrite /strong_fairness => H_exec H_fair l H_neq H_en.\nhave [l' H_l] := label_tot_mapped l.\nrewrite H_l.\napply pt_map_onet_tot_map_label_event_inf_often_occurred.\napply H_fair; first by move => H_eq; rewrite H_eq pt_lb_label_silent_fst_snd in H_l.\nrewrite H_l in H_en.\nunfold inf_enabled in *.\napply: pt_map_onet_tot_map_labeled_event_inf_often_enabled => //.\nmove => H_eq.\nby rewrite -H_l in H_eq.\nQed.\n\nLemma pt_map_onet_tot_map_label_event_state_weak_fairness :\n  forall s, lb_step_execution lb_step_ordered_failure s ->\n       weak_fairness lb_step_ordered_failure label_silent s ->\n       weak_fairness lb_step_ordered_failure label_silent (map pt_map_onet_event s).\nProof using multi_map_lb_congr lb_step_ordered_failure_weak_fairness_always_enabled_pt_map_onet_continuously label_tot_mapped.\nmove => s.\nrewrite /weak_fairness => H_exec H_fair l H_neq H_en.\nhave [l' H_l] := label_tot_mapped l.\nrewrite H_l.\napply pt_map_onet_tot_map_label_event_inf_often_occurred.\napply H_fair; first by move => H_eq; rewrite H_eq pt_lb_label_silent_fst_snd in H_l.\nrewrite H_l in H_en.\nunfold cont_enabled in *.\napply: pt_map_onet_tot_map_labeled_event_state_continuously_enabled => //.\nmove => H_eq.\nby rewrite -H_l in H_eq.\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 : FailMsgParamsPartialMapCongruency fail_msg_fst fail_msg_snd msg_map}.\n\nLemma pt_map_onet_hd_step_ordered_failure_star : \n  forall e, event_step_star step_ordered_failure step_ordered_failure_init e ->\n       event_step_star step_ordered_failure step_ordered_failure_init (pt_map_onet_event e).\nProof using overlay_map_congr name_map_bijective multi_map_congr fail_msg_map_congr.\nmove => e.\nrewrite /= /pt_map_onet_event /= /event_step_star /=.\nmove => H_star.\ndestruct e, evt_a.\nsimpl in *.\nexact: step_ordered_failure_pt_mapped_simulation_star_1.\nQed.\n\nLemma pt_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 pt_map_onet_event s).\nProof using overlay_map_congr name_map_bijective multi_map_lb_congr multi_map_congr label_eq_dec fail_msg_map_congr.\ncase => e s H_star H_exec.\napply: step_ordered_failure_star_lb_step_execution; first exact: pt_map_onet_hd_step_ordered_failure_star.\nexact: lb_step_execution_lb_step_ordered_failure_pt_map_onet_infseq.\nQed.\n\n(* lb_step_ordered_dynamic_failure *)\n\nTheorem lb_step_ordered_dynamic_failure_pt_mapped_simulation_1_non_silent :\n  forall net net' failed failed' lb tr,\n    tot_map_label lb <> label_silent ->\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, pt_map_odnet net) (tot_map_label lb) (List.map tot_map_name failed', pt_map_odnet net') (filterMap pt_map_trace_ev tr).\nProof using name_map_bijective multi_map_lb_congr multi_map_congr.\nmove => net net' failed failed' lb tr H_neq H_step.\nhave H_neq': lb <> label_silent.\n  rewrite -pt_lb_label_silent_fst_snd in H_neq.\n  move => H_eq.\n  by rewrite H_eq in H_neq.\ninvcs H_step => //=.\n- rewrite {2}/pt_map_odnet /=.\n  case H_m: (@pt_map_msg _ _ _ _ msg_map m) => [m'|]; last first.\n    have H_q := @pt_lb_net_handlers_none _ _ _ _ _ _ _ _ multi_map_lb_congr to from _ d H_m.\n    rewrite /tot_mapped_lb_net_handlers_label in H_q.\n    repeat break_let.\n    by tuple_inversion.\n  apply (@LabeledStepOrderedDynamicFailure_deliver _ _ _ _ _ _ m' (filterMap (@pt_map_msg _ _ _ _ msg_map) ms) (filterMap pt_map_output out) (pt_map_data d) (pt_map_data d') (filterMap (@pt_map_name_msg _ _ _ _ _ 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  * by rewrite /pt_map_odnet /= tot_map_name_inv_inverse H5.\n  * by rewrite /pt_map_odnet /= 2!tot_map_name_inv_inverse H6 /= H_m.\n  * have H_q := @pt_net_handlers_some _ _ _ _ _ _ _ multi_map_congr to from m d _ H_m.\n    rewrite /pt_mapped_net_handlers /net_handlers /= /unlabeled_net_handlers in H_q.\n    repeat break_let.\n    repeat tuple_inversion.\n    have H_q' := @pt_lb_net_handlers_some _ _ _ _ _ _ _ _ multi_map_lb_congr _ _ _ _ _ _ _ _ _ H_m Heqp1.\n    rewrite /tot_mapped_lb_net_handlers_label in H_q'.\n    repeat break_let.\n    break_and.\n    by repeat tuple_inversion.\n  * rewrite {2}/pt_map_odnet /=.\n    rewrite (@collate_pt_map_update2_eq _ _ _ _ name_map).\n    set f1 := fun _ => match _ with _ => _ end.    \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 (@filterMap_pt_map_trace_ev_outputs_eq _ _ _ _ _ name_map).\n- rewrite {2}/pt_map_odnet /=.\n  case H_i: pt_map_input => [inp'|]; last first.\n    have H_q := @pt_lb_input_handlers_none _ _ _ _ _ _ _ _ multi_map_lb_congr h inp d H_i.\n    rewrite /tot_mapped_lb_input_handlers_label in H_q.\n    repeat break_let.\n    by tuple_inversion.\n  apply (@LabeledStepOrderedDynamicFailure_input _ _ (@tot_map_name _ _ _ _ name_map h) _ _ _ _ (filterMap pt_map_output out) inp' (pt_map_data d) (pt_map_data d') (filterMap (@pt_map_name_msg _ _ _ _ _ msg_map) l)).\n  * exact: not_in_failed_not_in.\n  * exact: in_failed_in.\n  * by rewrite /pt_map_odnet /= tot_map_name_inv_inverse H5.\n  * have H_q := @pt_input_handlers_some _ _ _ _ _ _ _ multi_map_congr h inp d _ H_i.\n    rewrite /pt_mapped_input_handlers /input_handlers /= /unlabeled_input_handlers in H_q.\n    repeat break_let.\n    repeat tuple_inversion.\n    have H_q' := @pt_lb_input_handlers_some _ _ _ _ _ _ _ _ multi_map_lb_congr _ _ _ _ _ _ _ _ H_i Heqp1.\n    rewrite /tot_mapped_lb_input_handlers_label in H_q'.\n    repeat break_let.\n    break_and.\n    by repeat tuple_inversion.\n  * rewrite {2}/pt_map_odnet /=.\n    rewrite (@collate_pt_map_eq _ _ _ _ name_map).\n    set f1 := fun _ => match _ with _ => _ end.\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 (@filterMap_pt_map_trace_ev_outputs_eq _ _ _ _ _ name_map).\nQed.\n\nTheorem lb_step_ordered_dynamic_failure_pt_mapped_simulation_1_silent :\n  forall net net' failed failed' lb tr,\n    tot_map_label lb = label_silent ->\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, pt_map_odnet net) label_silent (List.map tot_map_name failed', pt_map_odnet net') [] /\\ filterMap pt_map_trace_ev tr = [].\nProof using name_map_bijective multi_map_lb_congr multi_map_congr.\nmove => net net' failed failed' lb tr H_eq H_step.\ninvcs H_step => //=.\n- rewrite {2}/pt_map_odnet /=.\n  case H_m: (@pt_map_msg _ _ _ _ msg_map m) => [m'|].\n    have H_q := @pt_net_handlers_some _ _ _ _ _ _ _ multi_map_congr to from m d _ H_m.\n    rewrite /pt_mapped_net_handlers /net_handlers /= /unlabeled_net_handlers in H_q.\n    repeat break_let.\n    repeat tuple_inversion.\n    have H_q' := @pt_lb_net_handlers_some _ _ _ _ _ _ _ _ multi_map_lb_congr _ _ _ _ _ _ _ _ _ H_m Heqp1.\n    break_and.\n    unfold tot_mapped_lb_net_handlers_label in *.\n    repeat break_let.\n    by repeat tuple_inversion.\n  have H_q := @pt_net_handlers_none _ _ _ _ _ _ _ multi_map_congr to from m d out d' l H_m.\n  rewrite /net_handlers /= /unlabeled_net_handlers in H_q.\n  repeat break_let.\n  repeat tuple_inversion.\n  concludes.\n  break_and.\n  have H_q' := @pt_lb_net_handlers_none _ _ _ _ _ _ _ _ multi_map_lb_congr to from _ d H_m.\n  rewrite /tot_mapped_lb_net_handlers_label in H_q'.\n  repeat break_let.\n  repeat tuple_inversion.\n  rewrite /pt_map_odnet /=.\n  rewrite (@collate_pt_map_update2_eq _ _ _ _ name_map) /=.\n  rewrite H0 /=.\n  set p1 := fun _ _ => _.\n  set p2 := update2 _ _ _ _ _.\n  set s1 := fun _ => _.\n  set s2 := fun _ => _.\n  have H_eq_p: p1 = p2.\n    rewrite /p1 /p2 /update2.\n    apply functional_extensionality => src.\n    apply functional_extensionality => dst.\n    break_if => //.\n    break_and.\n    by rewrite -H2 -H7 2!tot_map_name_inv_inverse H6 /= H_m.\n  have H_eq_s: s1 = s2.\n    rewrite /s1 /s2 /update.\n    apply functional_extensionality => n.\n    break_if => //.\n    by rewrite e H5 H.\n  rewrite H_eq_p H_eq_s.\n  split; first exact: LabeledStepOrderedDynamicFailure_stutter.\n  rewrite (@filterMap_pt_map_trace_ev_outputs_eq _ _ _ _ _ name_map).\n  by repeat find_rewrite.\n- case H_i: (pt_map_input inp) => [inp'|].\n    have H_q := @pt_input_handlers_some _ _ _ _ _ _ _ multi_map_congr h _ d _ H_i.\n    rewrite /pt_mapped_input_handlers /input_handlers /= /unlabeled_input_handlers in H_q.\n    repeat break_let.\n    repeat tuple_inversion.\n    have H_q' := @pt_lb_input_handlers_some _ _ _ _ _ _ _ _ multi_map_lb_congr _ _ _ _ _ _ _ _ H_i Heqp1.\n    break_and.\n    unfold tot_mapped_lb_input_handlers_label in *.\n    repeat break_let.\n    by tuple_inversion.\n  have H_q := @pt_input_handlers_none _ _ _ _ _ _ _ multi_map_congr h _ d out d' l H_i.\n  rewrite /input_handlers /= /unlabeled_input_handlers in H_q.\n  repeat break_let.\n  repeat tuple_inversion.\n  concludes.\n  break_and.\n  have H_q' := @pt_lb_input_handlers_none _ _ _ _ _ _ _ _ multi_map_lb_congr h _ d H_i.\n  rewrite /tot_mapped_lb_input_handlers_label in H_q'.\n  repeat break_let.\n  repeat tuple_inversion.\n  rewrite /pt_map_odnet /=.\n  rewrite (@collate_pt_map_eq _ _ _ _ name_map) H0 /=.\n  set s1 := fun _ => match _ with _ => _ end.\n  set s2 := fun _ => match _ with _ => _ end.\n  have H_eq_s: s1 = s2.\n    rewrite /s1 /s2.\n    apply functional_extensionality => n.\n    rewrite /update.\n    by break_if; first by rewrite e H5 H.\n  rewrite -H_eq_s /s1 {s1 s2 H_eq_s}.\n  split; first exact: LabeledStepOrderedDynamicFailure_stutter.\n  rewrite (@filterMap_pt_map_trace_ev_outputs_eq _ _ _ _ _ name_map).\n  by repeat find_rewrite.\n- split => //; exact: LabeledStepOrderedDynamicFailure_stutter.\nQed.\n\nDefinition pt_map_odnet_event e :=\n{| evt_a := (List.map tot_map_name (fst e.(evt_a)), pt_map_odnet (snd e.(evt_a))) ;\n   evt_l := tot_map_label e.(evt_l) ;\n   evt_trace := filterMap pt_map_trace_ev e.(evt_trace) |}.\n\nLemma pt_map_odnet_event_Map_unfold : forall s,\n Cons (pt_map_odnet_event (hd s)) (map pt_map_odnet_event (tl s)) = map pt_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_pt_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 pt_map_odnet_event s).\nProof using name_map_bijective multi_map_lb_congr multi_map_congr label_eq_dec.\ncofix c.\nmove => s H_exec.\nrewrite -pt_map_odnet_event_Map_unfold {1}/pt_map_odnet_event /=.\ninversion H_exec; subst => /=.\nrewrite -pt_map_odnet_event_Map_unfold /= /pt_map_odnet_event /=.\ncase (label_eq_dec (tot_map_label (evt_l e)) label_silent) => H_eq.\n  apply: Cons_lb_step_exec => /=.\n  - rewrite H_eq.\n    destruct e, e'.\n    destruct evt_a, evt_a0.\n    simpl in *.\n    by eapply lb_step_ordered_dynamic_failure_pt_mapped_simulation_1_silent; eauto.\n  - destruct e, e'.\n    destruct evt_a, evt_a0.\n    simpl in *.\n    apply (lb_step_ordered_dynamic_failure_pt_mapped_simulation_1_silent H_eq) in H.\n    break_and.\n    simpl in *.\n    rewrite H0 filterMap_app.\n    by aggressive_rewrite_goal.\n  - pose s' := Cons e' s0.\n    rewrite (pt_map_odnet_event_Map_unfold s').\n    exact: c.\napply: Cons_lb_step_exec => /=.\n- destruct e, e'.\n  destruct evt_a, evt_a0.\n  simpl in *.\n  by eapply lb_step_ordered_dynamic_failure_pt_mapped_simulation_1_non_silent; eauto.\n- by rewrite H0 filterMap_app.\n- pose s' := Cons e' s0.\n  rewrite (pt_map_odnet_event_Map_unfold s').\n  exact: c.\nQed.\n\nLemma pt_map_odnet_tot_map_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 pt_map_odnet_event s).\nProof using.\nmove => l.\napply: always_map.\napply: eventually_map.\ncase => e s.\nrewrite /= /occurred /evt_l /=.\nmove => H_eq.\nby rewrite H_eq.\nQed.\n\nLemma pt_map_odnet_tot_map_label_event_inf_often_occurred_conv :\n  forall l s,\n    inf_often (now (occurred (tot_map_label l))) (map pt_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- exact: extensional_now.\n- exact: extensional_now.\n- case => e s.\n  rewrite /= /occurred /=.\n  move => H_eq.\n  exact: tot_map_label_injective.\nQed.\n\nHypothesis lb_step_ordered_dynamic_failure_strong_fairness_enabled_pt_map_onet_eventually :\n  forall l, tot_map_label l <> label_silent ->\n    forall s, lb_step_execution lb_step_ordered_dynamic_failure s ->\n    strong_fairness lb_step_ordered_dynamic_failure label_silent s ->\n    enabled lb_step_ordered_dynamic_failure (tot_map_label l) (pt_map_odnet_event (hd s)) ->\n    eventually (now (enabled lb_step_ordered_dynamic_failure l)) s.\n\nLemma pt_map_odnet_tot_map_labeled_event_inf_often_enabled :\n  forall l, tot_map_label l <> label_silent ->\n    forall s, lb_step_execution lb_step_ordered_dynamic_failure s ->\n    strong_fairness lb_step_ordered_dynamic_failure label_silent s ->\n    inf_often (now (enabled lb_step_ordered_dynamic_failure (tot_map_label l))) (map pt_map_odnet_event s) ->\n    inf_often (now (enabled lb_step_ordered_dynamic_failure l)) s.\nProof using lb_step_ordered_dynamic_failure_strong_fairness_enabled_pt_map_onet_eventually.\nmove => l H_neq s H_exec H_fair.\nhave H_a: ((lb_step_execution lb_step_ordered_dynamic_failure) /\\_ (strong_fairness lb_step_ordered_dynamic_failure label_silent)) s by auto.\nmove: H_a {H_exec H_fair}.\napply: always_map_conv_ext => {s}.\n  rewrite /and_tl /=.\n  move => x s0 [H_e H_w].\n  apply lb_step_execution_invar in H_e.\n  by apply strong_fairness_invar in H_w.\napply: eventually_map_conv_ext.\n- exact: extensional_now.\n- exact: extensional_now.\n- apply extensional_and_tl.\n  * exact: lb_step_execution_extensional.\n  * exact: strong_fairness_extensional.\n- rewrite /and_tl /=.\n  move => x s [H_e H_w].\n  apply lb_step_execution_invar in H_e.\n  by apply strong_fairness_invar in H_w.\n- rewrite /and_tl.\n  case => /= x s [H_a H_w] H_en.\n  exact: lb_step_ordered_dynamic_failure_strong_fairness_enabled_pt_map_onet_eventually.\nQed.\n\nHypothesis lb_step_ordered_dynamic_failure_weak_fairness_always_enabled_pt_map_onet_continuously : \n  forall l, tot_map_label l <> label_silent -> \n    forall s, lb_step_execution lb_step_ordered_dynamic_failure s ->\n    weak_fairness lb_step_ordered_dynamic_failure label_silent s ->\n    always (now (enabled lb_step_ordered_dynamic_failure (tot_map_label l))) (map pt_map_odnet_event s) ->\n    continuously (now (enabled lb_step_ordered_dynamic_failure l)) s.\n\nLemma pt_map_odnet_tot_map_labeled_event_state_continuously_enabled :\n  forall l, tot_map_label l <> label_silent ->    \n    forall s, lb_step_execution lb_step_ordered_dynamic_failure s ->\n    weak_fairness lb_step_ordered_dynamic_failure label_silent s ->\n    continuously (now (enabled lb_step_ordered_dynamic_failure (tot_map_label l))) (map pt_map_odnet_event s) ->\n    continuously (now (enabled lb_step_ordered_dynamic_failure l)) s.\nProof using lb_step_ordered_dynamic_failure_weak_fairness_always_enabled_pt_map_onet_continuously.\nmove => l H_neq s H_exec H_fair.\nhave H_a: ((lb_step_execution lb_step_ordered_dynamic_failure) /\\_ (weak_fairness lb_step_ordered_dynamic_failure label_silent)) s by auto.\nmove: H_a {H_exec H_fair}.\napply: eventually_map_conv_ext => {s}.\n- apply extensional_always.\n  exact: extensional_now.\n- apply extensional_always.\n  exact: extensional_now.\n- apply extensional_and_tl.\n  * exact: lb_step_execution_extensional.\n  * exact: weak_fairness_extensional.\n- rewrite /and_tl /=.\n  move => x s [H_e H_w].\n  apply lb_step_execution_invar in H_e.\n  by apply weak_fairness_invar in H_w.\n- case => x s [H_a H_w] H_al.\n  simpl in *.\n  exact: lb_step_ordered_dynamic_failure_weak_fairness_always_enabled_pt_map_onet_continuously.\nQed.\n\nLemma pt_map_odnet_tot_map_label_event_strong_fairness :\n  forall s, lb_step_execution lb_step_ordered_dynamic_failure s ->\n       strong_fairness lb_step_ordered_dynamic_failure label_silent s ->\n       strong_fairness lb_step_ordered_dynamic_failure label_silent (map pt_map_odnet_event s).\nProof using multi_map_lb_congr lb_step_ordered_dynamic_failure_strong_fairness_enabled_pt_map_onet_eventually label_tot_mapped.\nmove => s.\nrewrite /strong_fairness => H_exec H_fair l H_neq H_en.\nhave [l' H_l] := label_tot_mapped l.\nrewrite H_l.\napply pt_map_odnet_tot_map_label_event_inf_often_occurred.\napply H_fair; first by move => H_eq; rewrite H_eq pt_lb_label_silent_fst_snd in H_l.\nrewrite H_l in H_en.\nunfold inf_enabled in *.\napply: pt_map_odnet_tot_map_labeled_event_inf_often_enabled => //.\nmove => H_eq.\nby rewrite -H_l in H_eq.\nQed.\n\nLemma pt_map_odnet_tot_map_label_event_state_weak_fairness :\n  forall s, lb_step_execution lb_step_ordered_dynamic_failure s ->\n       weak_fairness lb_step_ordered_dynamic_failure label_silent s ->\n       weak_fairness lb_step_ordered_dynamic_failure label_silent (map pt_map_odnet_event s).\nProof using multi_map_lb_congr lb_step_ordered_dynamic_failure_weak_fairness_always_enabled_pt_map_onet_continuously label_tot_mapped.\nmove => s.\nrewrite /weak_fairness => H_exec H_fair l H_neq H_en.\nhave [l' H_l] := label_tot_mapped l.\nrewrite H_l.\napply pt_map_odnet_tot_map_label_event_inf_often_occurred.\napply H_fair; first by move => H_eq; rewrite H_eq pt_lb_label_silent_fst_snd in H_l.\nrewrite H_l in H_en.\nunfold cont_enabled in *.\napply: pt_map_odnet_tot_map_labeled_event_state_continuously_enabled => //.\nmove => H_eq.\nby rewrite -H_l in H_eq.\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 : NewMsgParamsPartialMapCongruency new_msg_fst new_msg_snd msg_map}.\n\nLemma pt_map_odnet_hd_step_ordered_dynamic_failure_star : \n  forall e, event_step_star step_ordered_dynamic_failure step_ordered_dynamic_failure_init e ->\n       event_step_star step_ordered_dynamic_failure step_ordered_dynamic_failure_init (pt_map_odnet_event e).\nProof using overlay_map_congr new_msg_map_congr name_map_bijective multi_map_congr fail_msg_map_congr.\nmove => e.\nrewrite /= /pt_map_odnet_event /= /event_step_star /=.\nmove => H_star.\nbreak_exists.\ndestruct e, evt_a.\nsimpl in *.\nexact: step_ordered_dynamic_failure_pt_mapped_simulation_star_1.\nQed.\n\nLemma pt_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 pt_map_odnet_event s).\nProof using overlay_map_congr new_msg_map_congr name_map_bijective multi_map_lb_congr multi_map_congr label_eq_dec fail_msg_map_congr.\ncase => e s H_star H_exec.\napply: step_ordered_dynamic_failure_star_lb_step_execution; first exact: pt_map_odnet_hd_step_ordered_dynamic_failure_star.\nexact: lb_step_execution_lb_step_ordered_dynamic_failure_pt_map_odnet_infseq.\nQed.\n\nEnd PartialMapExecutionSimulations.\n", "meta": {"author": "uwplse", "repo": "verdi", "sha": "4f1f3ed37e372c05ce0249a93162d0f25e3e20c4", "save_path": "github-repos/coq/uwplse-verdi", "path": "github-repos/coq/uwplse-verdi/verdi-4f1f3ed37e372c05ce0249a93162d0f25e3e20c4/core/PartialMapExecutionSimulations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.29523430967234754}}
{"text": "From Coq Require Import\n     ssreflect\n.\n\nFrom ExtensibleCompiler.Syntax.Terms Require Import\n     If2\n.\n\nFrom ExtensibleCompiler.Syntax.Types Require Import\n     BoolType\n.\n\nFrom ExtensibleCompiler.Theory Require Import\n     Algebra\n     Functor\n     IndexedAlgebra\n     IndexedFunctor\n     IndexedProofAlgebra\n     IndexedSubFunctor\n     ProgramAlgebra\n     SubFunctor\n     TypeSoundness\n     UniversalProperty\n.\n\nLocal Open Scope SubFunctor.\n\nSection If2.\n\n  Context\n\n    {T}\n    `{Functor T}\n    `{! T supports BoolType}\n\n    {E}\n    `{Functor E}\n    `{E supports If2}\n\n    {V}\n    `{Functor V}\n\n  .\n\n  Inductive WellTypedValue__If2\n            (WTV : (TypedExpr T V)-indexedProp)\n    : (TypedExpr T V)-indexedProp\n    :=\n    | WellTypedValue__if2 : forall t v,\n        WTV {| type := t; expr := v |} ->\n        WellTypedValue__If2 WTV {| type := t; expr := v |}\n  .\n\n  Global Instance IndexedFunctor_WellTypedValue__If2\n    : IndexedFunctor (TypedExpr T V) WellTypedValue__If2.\n  Proof.\n    constructor.\n    move => A B i IH [] [t UP__t] [v UP__v] /= => WTV__V.\n    econstructor => //; apply IH => //.\n  Qed.\n\n  Definition WellTypedValueInversionClear__If2\n             (WellTypedValue__V : (TypedExpr T V)-indexedProp)\n             (tv : TypedExpr T V)\n             (P : (TypedExpr T V)-indexedPropFunctor)\n             (IH : forall tau v,\n                 {| type := tau; expr := v |} = tv ->\n                 WellTypedValue__V {| type := tau; expr := v |} ->\n                 P WellTypedValue__V {| type := tau; expr := v |})\n             (WT : WellTypedValue__If2 WellTypedValue__V tv)\n    : P WellTypedValue__V tv\n    :=\n      match WT in (WellTypedValue__If2 _ p) return (p = tv -> P WellTypedValue__V tv) with\n      | WellTypedValue__if2 _ tau e wtv =>\n        fun EQ =>\n          eq_ind _ (fun p => P WellTypedValue__V p) (IH _ _ EQ wtv) tv EQ\n      end eq_refl.\n\n  (* Definition WellTypedValueInversionStatement__If2 *)\n  (*            (WellTypedValue__V : (TypedExpr T V)-indexedPropFunctor) *)\n  (*            (te : TypedExpr T V) *)\n  (*   := proj1_sig (type te) = boolType -> *)\n  (*      WellTypedValue__If2 (IndexedFix WellTypedValue__V) te. *)\n\n  (* Variant ForWellTypedValueInversion__If2 := . *)\n\n  (* Global Instance WellTypedValueInversion__If2 *)\n  (*        (WellTypedValue__V : (TypedExpr T V)-indexedPropFunctor) *)\n  (*        `{IndexedFunctor (TypedExpr T V) WellTypedValue__V} *)\n  (*        `{S : ! IndexedSubFunctor WellTypedValue__If2 WellTypedValue__V} *)\n  (*   : IndexedProofAlgebra ForWellTypedValueInversion__If2 *)\n  (*                         WellTypedValue__If2 *)\n  (*                         (WellTypedValueInversionStatement__If2 WellTypedValue__V). *)\n  (* Proof. *)\n  (*   constructor. *)\n  (*   move => tv [] t v //. *)\n  (* Qed. *)\n\n  (* Definition wellTypedValueInversion__If2 *)\n  (*            (WellTypedValue__V : (TypedExpr T V)-indexedPropFunctor) *)\n  (*            `{IndexedFunctor (TypedExpr T V) WellTypedValue__V} *)\n  (*            `{S : ! IndexedSubFunctor WellTypedValue__If2 WellTypedValue__V} *)\n  (*            `{A : ! IndexedProofAlgebra ForWellTypedValueInversion__If2 WellTypedValue__V *)\n  (*                    (WellTypedValueInversionStatement__If2 WellTypedValue__V)} *)\n  (*   :=  ifold (indexedProofAlgebra' A). *)\n\n  Inductive WellTypedExpr__If2\n            (WT : (TypedExpr T E)-indexedProp)\n    : (TypedExpr T E)-indexedProp\n    :=\n    | WellTypedExpr__if2 : forall t e condition thenBranch elseBranch,\n        proj1_sig e = if2F' condition thenBranch elseBranch ->\n        WT {| type := boolType';  expr := condition;  |} ->\n        WT {| type := t;          expr := thenBranch |} ->\n        WT {| type := t;          expr := elseBranch |} ->\n        WellTypedExpr__If2 WT {| type := t; expr := e |}\n  .\n\n  Global Instance IndexedFunctor_WellTypedExpr__If2\n    : IndexedFunctor (TypedExpr T E) WellTypedExpr__If2.\n  Proof.\n    constructor.\n    move => A B i IH [] [t UP__t] [e UP__e] /= => cond thenB elseB Eq__e.\n    move : Eq__e UP__e => -> => UP__e H__c H__t H__e.\n    econstructor => //; apply IH => //.\n  Qed.\n\n  Definition WellTypedExprInversionClear__If2\n             (WellTypedExpr__E : (TypedExpr T E)-indexedProp)\n             (te : TypedExpr T E)\n             (P : (TypedExpr T E)-indexedPropFunctor)\n             (IH : forall tau e cond thenB elseB,\n                 {| type := tau; expr := e |} = te ->\n                 proj1_sig e = if2F' cond thenB elseB ->\n                 P WellTypedExpr__E {| type := tau; expr := e |})\n             (WT : WellTypedExpr__If2 WellTypedExpr__E te)\n    : P WellTypedExpr__E te\n    :=\n      match WT in (WellTypedExpr__If2 _ p) return (p = te -> P WellTypedExpr__E te) with\n      | WellTypedExpr__if2 _ tau e cond thenB elseB E WT__c WT__t WT__e =>\n        fun EQ =>\n          eq_ind _ (fun p => P WellTypedExpr__E p) (IH _ _ _ _ _ EQ E) te EQ\n      end eq_refl.\n\n  Definition WellTypedExprInversionStatement__If2\n             (WellTypedExpr__E : (TypedExpr T E)-indexedPropFunctor)\n             (te : TypedExpr T E)\n    := proj1_sig (type te) = boolType ->\n       WellTypedExpr__If2 (IndexedFix WellTypedExpr__E) te.\n\n  Variant ForWellTypedExprInversion__If2 := .\n\n  Global Instance WellTypedExprInversion__If2\n         (WellTypedExpr__E : (TypedExpr T E)-indexedPropFunctor)\n         `{IndexedFunctor (TypedExpr T E) WellTypedExpr__E}\n         `{S : ! IndexedSubFunctor WellTypedExpr__If2 WellTypedExpr__E}\n    : IndexedProofAlgebra ForWellTypedExprInversion__If2\n                          WellTypedExpr__If2\n                          (WellTypedExprInversionStatement__If2 WellTypedExpr__E).\n  Proof.\n    constructor.\n    move => te [] t e cond thenB elseB P IH__c IH__t IH__e Q.\n    apply : (WellTypedExpr__if2 _ _ _ _ _ _ P).\n    apply (iInject (IH__c eq_refl)).\n    apply (iInject (IH__t Q)).\n    apply (iInject (IH__e Q)).\n  Qed.\n\nEnd If2.\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/Semantics/Static/WellTyped/If2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2952343096723475}}
{"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 TableAux.Specs.invalidate_page.\nRequire Import TableAux.LowSpecs.invalidate_page.\nRequire Import TableAux.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       barrier_spec\n       stage2_tlbi_ipa_spec\n    .\n\n  Lemma invalidate_page_spec_exists:\n    forall habd habd'  labd addr\n           (Hspec: invalidate_page_spec addr habd = Some habd')\n            (Hrel: relate_RData habd labd),\n    exists labd', invalidate_page_spec0 addr labd = Some labd' /\\ relate_RData habd' labd'.\n  Proof.\n    intros. destruct Hrel. inv id_rdata.\n    unfold invalidate_page_spec, invalidate_page_spec0 in *. repeat autounfold in *.\n    repeat simpl_hyp Hspec; inv Hspec.\n    eexists. split. reflexivity. constructor.\n    replace (4096 / 4096) with 1 by reflexivity.\n    match goal with\n    | |- _ {share: _ {tlbs: ?f1}} = _ {share: _ {tlbs: ?f2}} => assert(f1 = f2)\n    end.\n    apply func_eq. intros. repeat destruct_if; try reflexivity; repeat destruct_con; repeat destruct_dis; bool_rel; try omega.\n    rewrite H. 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/TableAux/RefProof/invalidate_page.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.29523430967234743}}
{"text": "Require Import Coq.Logic.Classical.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Sets.Ensembles.\nRequire 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.Relation_ext.\nRequire Import CertiGraph.hip.hip_graphmark.\nRequire Import CertiGraph.msl_ext.seplog.\nRequire Import CertiGraph.graph.graph_model.\nRequire Import CertiGraph.graph.weak_mark_lemmas.\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_computable.\nRequire Import CertiGraph.msl_application.Graph.\nRequire Import CertiGraph.msl_application.GraphBi.\nRequire Import CertiGraph.msl_application.Graph_Mark.\nRequire Import CertiGraph.msl_application.GraphBi_Mark.\nImport CertiGraph.msl_ext.seplog.OconNotation.\n\nContext {pSGG_Bi: pPointwiseGraph_Graph_Bi}.\nContext {sSGG_Bi: sPointwiseGraph_Graph_Bi bool unit}.\nContext {SGSA: PointwiseGraphStrongAssum SGP}.\n\nTactic Notation \"LEM\" constr(v) := (destruct (classic v); auto).\n\nModule GraphMark <: Mgraphmark.\n  Definition formula : Type := pred.\n  Definition node : Type := addr.\n  Definition null_node : node := null.\n  Definition valid : formula -> Prop := fun f => TT |-- f.\n  Definition ptto_node : node -> bool -> node -> node -> formula := fun v d l r => vertex_at v (d, l, r).\n  Definition A : Type := (@Graph _ bool unit unit).\n  Definition graph : node -> A -> formula := fun x g => (@reachable_vertices_at _ _ _ _ _ _ _ _ _ _ SGP _ x (Graph_LGraph g)).\n  Definition star : formula -> formula -> formula := sepcon.\n  Definition and : formula -> formula -> formula := andp.\n  Definition imp : formula -> formula -> formula := imp.\n  Definition ext : (bool -> formula) -> formula := exp.\n  Definition not : formula -> formula := fun f => prop (f |-- FF).\n  Definition eq : node -> node -> formula := fun a b => prop (a = b).\n  Definition mwand : formula -> formula -> formula := ewand.\n  Definition union : formula -> formula -> formula := ocon.\n  Definition neq : bool -> bool -> formula := fun a b => prop (~ a = b).\n  Definition mark : A -> node -> A -> formula := fun g1 n g2 => prop (mark n (Graph_LGraph g1) (Graph_LGraph g2)).\n\n  Definition eq_notreach : A -> node -> A -> formula :=\n    fun g1 n g2 => prop ((predicate_partial_labeledgraph (Graph_LGraph g1) (Complement _ (reachable (pg_lg (Graph_LGraph g1)) n))) ~=~ (predicate_partial_labeledgraph (Graph_LGraph g2) (Complement _ (reachable (pg_lg (Graph_LGraph g2)) n)))%LabeledGraph).\n\n  Definition subset_reach : A -> node -> A -> formula := fun g1 n g2 => prop (Included (reachable (pg_lg (Graph_LGraph g1)) n) (reachable (pg_lg (Graph_LGraph g2)) n)).\n\n  Definition lookup : A -> node -> bool -> node -> node -> formula :=\n    fun g x d l r => prop (vlabel (Graph_LGraph g) x = d /\\ vvalid (pg_lg (Graph_LGraph g)) x /\\\n                           vvalid (pg_lg (Graph_LGraph g)) l /\\ vvalid (pg_lg (Graph_LGraph g)) r /\\\n                           dst (pg_lg (Graph_LGraph g)) (x, L) = l /\\ dst (pg_lg (Graph_LGraph g)) (x, R) = r).\n\n  Definition update : A -> node -> bool -> A -> formula :=\n    fun g1 x d g2 => prop (Graph_vgen g1 x d = g2).\n\n  Lemma update_is_mark1: forall (l r: addr) (G G1: A) x,\n      vvalid (pg_lg (Graph_LGraph G)) x ->\n      dst (pg_lg (Graph_LGraph G)) (x, L) = l ->\n      dst (pg_lg (Graph_LGraph G)) (x, R) = r ->\n      Graph_vgen G x true = G1 ->\n      mark1 x (Graph_LGraph G) (Graph_LGraph G1).\n  Proof.\n    intros. unfold valid in H1.\n    rewrite <- H2. split; [|split]; simpl.\n    + split; [|split; [|split]]; simpl; intros; auto.\n      - unfold change_vvalid. intuition.\n      - unfold change_evalid. intuition.\n    + unfold update_vlabel. destruct (equiv_dec x x); intuition.\n    + intros. unfold update_vlabel. destruct (equiv_dec x n'); intuition.\n  Qed.\n\n  Lemma marked_node_marked: forall (G1: A) (n: addr) (G2: A) (x: addr) (v: bool),\n      vlabel (Graph_LGraph G1) x = true ->\n      WeakMarkGraph.mark n (Graph_LGraph G1) (Graph_LGraph G2) ->\n      vlabel (Graph_LGraph G2) x = true.\n  Proof.\n    intros. unfold WeakMarkGraph.mark. destruct H0 as [? ?]. specialize (H1 x).\n    simpl in H1. symmetry. rewrite H1. left; auto.\n  Qed.\n\n(* (*TODO: delete it *)\n  Lemma axiom_5 : forall v G1 G2 G G3 x l r,\n      valid (imp (and (lookup G x v l r)\n                      (and (update G x true G1)\n                           (and (neq v true) (and (mark G1 r G2) (mark G2 l G3)))))\n                 (and (mark G x G3) (lookup G3 x true l r))).\n  Proof.\n    intros. unfold valid, imp, and, lookup, neq, mark, update.\n    apply imp_andp_adjoint. normalize. destruct H as [? [? [? [? [? ?]]]]].\n    assert (mark1 x (Graph_LGraph G) (Graph_LGraph (Graph_vgen G x true))) by (apply (update_is_mark1 l r); auto).\n    apply andp_right; normalize.\n    + apply mark1_mark_list_mark with (r :: l :: nil); auto.\n      - simpl. unfold Complement. unfold In.\n        subst v. clear - H0. intuition.\n      - apply gamma_step_list' with false; auto. simpl.\n        do 2 (f_equal; auto). subst v. apply Bool.not_true_is_false in H0. auto.\n      - hnf. apply (compond_intro (compond_relation Logic.eq (mark1 x)) _ _ (Graph_LGraph (Graph_vgen G x true)) _).\n        apply (compond_intro Logic.eq (mark1 x) (Graph_LGraph G) (Graph_LGraph G) (Graph_LGraph (Graph_vgen G x true))); auto.\n        unfold mark_list. simpl. hnf.\n        apply (compond_intro\n                 (compond_relation Logic.eq (Graph_Mark.mark r)) _ _ (Graph_LGraph G2) _); auto.\n          apply (compond_intro Logic.eq (Graph_Mark.mark r) (Graph_LGraph (Graph_vgen G x true)) (Graph_LGraph (Graph_vgen G x true)) (Graph_LGraph G2)); auto.\n    + destruct H1, H2, H8. destruct H11 as [? ?]. split.\n      - apply (marked_node_marked G2 l); auto. apply (marked_node_marked (Graph_vgen G x true) r); auto. \n      - assert ((pg_lg (Graph_LGraph G)) ~=~ (pg_lg (Graph_LGraph G3))) by\n            (transitivity (pg_lg (Graph_LGraph (Graph_vgen G x true))); auto; transitivity (pg_lg (Graph_LGraph G2)); auto).\n        destruct H13 as [? [? [? ?]]]. split; [|split; [|split; [|split]]].\n        * specialize (H13 x); intuition.\n        * specialize (H13 l); intuition.\n        * specialize (H13 r); intuition.\n        * assert (evalid (pg_lg (Graph_LGraph G)) (x, L)) by\n              (apply (@left_valid _ _ _ _ _ _ _ (biGraph G)); auto).\n          subst l. symmetry. specialize (H16 (x, L)).\n          specialize (H14 (x, L)). intuition.\n        * assert (evalid (pg_lg (Graph_LGraph G)) (x, R)) by\n              (apply (@right_valid _ _ _ _ _ _ _ (biGraph G)); auto).\n          subst r. symmetry. specialize (H16 (x, R)).\n          specialize (H14 (x, R)). intuition.\n  Qed.\n  *)\n  Lemma axiom_1 : forall v G1 G2 G G3 x l r,\n      valid (imp (and (lookup G x v l r)\n                      (and (update G x true G1)\n                           (and (neq v true) (and (mark G1 l G2) (mark G2 r G3)))))\n                 (and (mark G x G3) (lookup G3 x true l r))).\n  Proof.\n    intros. unfold valid, imp, and, lookup, neq, mark, update.\n    apply imp_andp_adjoint. normalize. destruct H as [? [? [? [? [? ?]]]]].\n    assert (mark1 x (Graph_LGraph G) (Graph_LGraph (Graph_vgen G x true))) by (apply (update_is_mark1 l r); auto).\n    apply andp_right; normalize.\n    + apply mark1_mark_list_mark with (l :: r :: nil); auto.\n      - simpl. unfold Complement. unfold In.\n        subst v. clear - H0. intuition.\n      - apply gamma_step_list with false; auto. simpl.\n        do 2 (f_equal; auto). subst v. apply Bool.not_true_is_false in H0. auto.\n      - hnf. apply (compond_intro (compond_relation Logic.eq (mark1 x)) _ _ (Graph_LGraph (Graph_vgen G x true)) _).\n        apply (compond_intro Logic.eq (mark1 x) (Graph_LGraph G) (Graph_LGraph G) (Graph_LGraph (Graph_vgen G x true))); auto.\n        unfold mark_list. simpl. hnf.\n        apply (compond_intro\n                 (compond_relation Logic.eq (Graph_Mark.mark l)) _ _ (Graph_LGraph G2) _); auto.\n          apply (compond_intro Logic.eq (Graph_Mark.mark l) (Graph_LGraph (Graph_vgen G x true)) (Graph_LGraph (Graph_vgen G x true)) (Graph_LGraph G2)); auto.\n    + destruct H1, H2, H8. destruct H11 as [? ?]. split.\n      - apply (marked_node_marked G2 r); auto. apply (marked_node_marked (Graph_vgen G x true) l); auto. \n      - assert ((pg_lg (Graph_LGraph G)) ~=~ (pg_lg (Graph_LGraph G3))) by\n            (transitivity (pg_lg (Graph_LGraph (Graph_vgen G x true))); auto; transitivity (pg_lg (Graph_LGraph G2)); auto).\n        destruct H13 as [? [? [? ?]]]. split; [|split; [|split; [|split]]].\n        * specialize (H13 x); intuition.\n        * specialize (H13 l); intuition.\n        * specialize (H13 r); intuition.\n        * assert (evalid (pg_lg (Graph_LGraph G)) (x, L)) by\n              (apply (@left_valid _ _ _ _ _ _ _ (biGraph G)); auto).\n          subst l. symmetry. specialize (H16 (x, L)).\n          specialize (H14 (x, L)). intuition.\n        * assert (evalid (pg_lg (Graph_LGraph G)) (x, R)) by\n              (apply (@right_valid _ _ _ _ _ _ _ (biGraph G)); auto).\n          subst r. symmetry. specialize (H16 (x, R)).\n          specialize (H14 (x, R)). intuition.\n  Qed.\n\n  Lemma axiom_2 : forall v G x G1 y l r, valid (imp (and (mark G x G1) (lookup G y v l r)) (and (subset_reach G x G1) (and (eq_notreach G x G1) (ext (fun Anon_15 => (lookup G1 y Anon_15 l r)))))).\n  Proof.\n    intros. unfold valid, imp, and, mark, lookup, subset_reach, eq_notreach.\n    apply imp_andp_adjoint. normalize. destruct H0 as [? [? [? [? [? ?]]]]].\n    apply andp_right; [|apply andp_right].\n    + apply TT_prop_right. destruct H. apply (reachable_ind.si_reachable _ _ x) in H6.\n      destruct H6. auto.\n    + apply TT_prop_right. destruct H.\n      destruct H.\n      split; [| split].\n      - simpl. rewrite H6; reflexivity.\n      - simpl; intros ? [? ?] [? ?].\n        apply vlabel_eq.\n        rewrite H7.\n        assert (~ (pg_lg (Graph_LGraph G)) |= x ~o~> v0\n          satisfying (WeakMarkGraph.unmarked (Graph_LGraph G))); [| tauto].\n        intro.\n        apply reachable_by_is_reachable in H12.\n        apply H9; auto.\n      - simpl; intros ? [? ?] [? ?].\n        match goal with | |- ?A = ?B => destruct A, B; auto end.\n      (* rewrite H6; reflexivity. *)\n(*\nSearchAbout predicate_partialgraph (_ ~=~ _).\nLocate si_stronger_partialgraph.\n       reflexivity.\n      unfold vertices_identical2.\n      split; [apply Ensembles_ext.Intersection_proper |].\n      1: rewrite Same_set_spec; intro; hnf; apply (proj1 H6).\n      1: rewrite H6; reflexivity.\n      rewrite vertices_identical_spec; intros.\n      specialize (H7 x0).\n      simpl in H7 |- *; unfold node in *.\n      rewrite Intersection_spec in H8; destruct H8.\n      f_equal; [f_equal |].\n      - assert (~ reachable_by (pg_lg (Graph_LGraph G)) x (WeakMarkGraph.unmarked (Graph_LGraph G)) x0).\n        1: {\n          intro.\n          apply reachable_by_is_reachable in H10; auto.\n        }\n        assert (true <> false) by congruence.\n        destruct (vlabel (Graph_LGraph G) x0), (vlabel (Graph_LGraph G1) x0); try tauto.\n      - apply (si_dst1 _ _ _ H6).\n        apply (@left_valid _ _ _ _ _ _ (pg_lg (Graph_LGraph G)) (biGraph G)); auto.\n      - apply (si_dst1 _ _ _ H6).\n        apply (@right_valid _ _ _ _ _ _ (pg_lg (Graph_LGraph G)) (biGraph G)); auto.\n*)\n    + unfold ext. destruct H as [[? ?] ?]. specialize (H6 y). simpl in H6.\n      destruct H7 as [? [? [? ?]]].\n      LEM ((pg_lg (Graph_LGraph G)) |= x ~o~> y satisfying (WeakMarkGraph.unmarked (Graph_LGraph G))).\n      - assert (vlabel (Graph_LGraph G1) y = true) by (symmetry; rewrite H6; right; auto).\n        apply (exp_right true). normalize. split; [|split;[|split;[|split; [|split]]]]; auto.\n        * specialize (H7 y); intuition.\n        * specialize (H7 l); intuition.\n        * specialize (H7 r); intuition.\n        * assert (evalid (pg_lg (Graph_LGraph G)) (y, L)) by\n              (apply (@left_valid _ _ _ _ _ _ _ (biGraph G)); auto).\n          subst l. symmetry. specialize (H10 (y, L)).\n          specialize (H8 (y, L)). intuition.\n        * assert (evalid (pg_lg (Graph_LGraph G)) (y, R)) by\n              (apply (@right_valid _ _ _ _ _ _ _ (biGraph G)); auto).\n          subst r. symmetry. specialize (H10 (y, R)).\n          specialize (H8 (y, R)). intuition.\n      - apply (exp_right v). normalize. split; [|split;[|split;[|split; [|split]]]].\n        * destruct (Bool.bool_dec v true).\n          1: rewrite e in *; symmetry; rewrite H6; left; auto.\n          apply Bool.not_true_is_false in n. rewrite n in *. clear n.\n          apply Bool.not_true_is_false. intro. symmetry in H12. rewrite H6 in H12.\n          destruct H12; [|intuition]. apply Bool.diff_true_false. clear - H0 H12.\n          rewrite H12. rewrite <- H0. auto.\n        * specialize (H7 y); intuition.\n        * specialize (H7 l); intuition.\n        * specialize (H7 r); intuition.\n        * assert (evalid (pg_lg (Graph_LGraph G)) (y, L)) by\n              (apply (@left_valid _ _ _ _ _ _ _ (biGraph G)); auto).\n          subst l. symmetry. specialize (H10 (y, L)).\n          specialize (H8 (y, L)). intuition.\n        * assert (evalid (pg_lg (Graph_LGraph G)) (y, R)) by\n              (apply (@right_valid _ _ _ _ _ _ _ (biGraph G)); auto).\n          subst r. symmetry. specialize (H10 (y, R)).\n          specialize (H8 (y, R)). intuition.\n  Qed.\n\n  Lemma axiom_3 : forall l r x G, valid (imp (lookup G x true l r) (mark G x G)).\n  Proof.\n    intros. unfold valid, imp, lookup, mark. rewrite <- iter_sepcon.prop_impl_imp. normalize.\n    destruct H as [? [? [? [? [? ?]]]]]. hnf. split; [|reflexivity].\n    split; [|split]; [reflexivity | intros..]; [intuition|destruct H5; auto].\n    apply reachable_by_head_prop in H5. simpl in H5. unfold Complement in H5. unfold In in H5.\n    exfalso; auto.\n  Qed.\n\n  Lemma axiom_4 : forall G, valid (mark G null_node G).\n  Proof.\n    intros. unfold valid, mark, null_node. normalize. hnf. split; [|reflexivity].\n    hnf. split; [|intros; split; intros]; [reflexivity | intuition |]. destruct H; auto.\n    exfalso. apply reachable_by_head_valid in H.\n    apply (@valid_not_null _ _ _ _ _ _ (maGraph G) _) in H; auto. reflexivity.\n  Qed.\n\n  Lemma lookup_graph_unfold: forall (G: A) x v l r,\n      vlabel (Graph_LGraph G) x = v -> vvalid (pg_lg (Graph_LGraph G)) x -> vvalid (pg_lg (Graph_LGraph G)) l ->\n      vvalid (pg_lg (Graph_LGraph G)) r -> dst (pg_lg (Graph_LGraph G)) (x, L) = l ->\n      dst (pg_lg (Graph_LGraph G)) (x, R) = r -> (graph x G = ptto_node x v l r ⊗ graph l G ⊗ graph r G).\n  Proof.\n    intros. unfold graph. unfold ptto_node. apply bi_graph_unfold; auto.\n    simpl. f_equal; [f_equal|]; auto.\n  Qed.\n\n  Lemma graph_graphs_eq_l:\n    forall (G: A) v x l r, vlabel (Graph_LGraph G) x = v -> vvalid (pg_lg (Graph_LGraph G)) x ->\n                           vvalid (pg_lg (Graph_LGraph G)) l -> vvalid (pg_lg (Graph_LGraph G)) r ->\n                           dst (pg_lg (Graph_LGraph G)) (x, L) = l -> dst (pg_lg (Graph_LGraph G)) (x, R) = r ->\n                           (ptto_node x v l r ⊗ (graph l G ⊗ graph r G)) =\n                           graph l G ⊗ graphs (x :: l :: r :: nil) (Graph_LGraph G).\n  Proof.\n    intros. simpl. rewrite ocon_emp. do 3 rewrite <- ocon_assoc.\n    rewrite (ocon_comm (graph l G) (graph x G)).\n    rewrite (ocon_assoc (graph x G) (graph l G) (graph l G)).\n    rewrite <- log_normalize.precise_ocon_self.\n    2: apply (bi_graph_precise_left _ x); auto.\n    rewrite (lookup_graph_unfold _ x v l r); auto.\n    rewrite (ocon_assoc (ptto_node x v l r) (graph l G) (graph r G)).\n    rewrite ocon_assoc.\n    rewrite (ocon_assoc (ptto_node x v l r) (graph l G ⊗ graph r G)\n                        (graph l G ⊗ graph r G)).\n    rewrite <- log_normalize.precise_ocon_self; auto. apply precise_ocon.\n    + apply (bi_graph_precise_left _ x); auto.\n    + apply (bi_graph_precise_right _ x); auto.\n  Qed.\n\n  Lemma lem_subgraphupdate_l : forall G v G1 x v1 l r,\n      valid (imp (and (star (graph l G1) (mwand (graph l G) (union (ptto_node x v l r) (union (graph l G) (graph r G)))))\n                      (and (subset_reach G l G1) (and (eq_notreach G l G1) (and (lookup G x v l r) (lookup G1 x v1 l r)))))\n                 (union (ptto_node x v1 l r) (union (graph l G1) (graph r G1)))).\n  Proof.\n    intros. unfold valid, imp, and, star, mwand, union, subset_reach, eq_notreach, lookup.\n    apply imp_andp_adjoint. normalize. apply precise_wand_ewand.\n    + apply precise_graph. apply RGF. left; intuition.\n    + destruct H1 as [? [? [? [? [? ?]]]]]. destruct H2 as [? [? [? [? [? ?]]]]].\n      rewrite (graph_graphs_eq_l G v x l r); auto. rewrite (graph_graphs_eq_l G1 v1 x l r); auto.\n      assert (forall (g: A), graph l g = graphs (l :: nil) (Graph_LGraph g)) by (intros; simpl; rewrite ocon_emp; auto).\n      rewrite (H13 G). rewrite (H13 G1). apply subgraph_update; auto.\n      - intros. left. simpl in H14. destruct H14 as [? | [? | [? | [? | ?]]]]; [subst x0 ..|exfalso]; auto.\n      - intros. left. simpl in H14. destruct H14 as [? | [? | [? | [? | ?]]]]; [subst x0 ..|exfalso]; auto.\n      - rewrite !reachable_through_set_single'; auto.\n  Qed.\n\n  Lemma graph_graphs_eq_r:\n    forall (G: A) v x l r, vlabel (Graph_LGraph G) x = v -> vvalid (pg_lg (Graph_LGraph G)) x ->\n                           vvalid (pg_lg (Graph_LGraph G)) l -> vvalid (pg_lg (Graph_LGraph G)) r ->\n                           dst (pg_lg (Graph_LGraph G)) (x, L) = l -> dst (pg_lg (Graph_LGraph G)) (x, R) = r ->\n                           (ptto_node x v l r ⊗ (graph l G ⊗ graph r G)) =\n                           graph r G ⊗ graphs (x :: l :: r :: nil) (Graph_LGraph G).\n  Proof.\n    intros. simpl. rewrite ocon_emp. do 3 rewrite <- ocon_assoc.\n    rewrite (ocon_comm (graph r G) (graph x G)).\n    rewrite (ocon_assoc (graph x G) (graph r G) (graph l G)).\n    rewrite (ocon_comm (graph r G) (graph l G)).\n    rewrite <- (ocon_assoc (graph x G) (graph l G) (graph r G)).\n    rewrite (ocon_assoc (graph x G ⊗ graph l G) (graph r G) (graph r G)).\n    rewrite <- log_normalize.precise_ocon_self.\n    2: apply (bi_graph_precise_right _ x); auto.\n    rewrite (lookup_graph_unfold _ x v l r); auto.\n    rewrite (ocon_assoc (ptto_node x v l r) (graph l G) (graph r G)).\n    rewrite ocon_assoc.\n    rewrite (ocon_assoc (ptto_node x v l r) (graph l G ⊗ graph r G)\n                        (graph l G ⊗ graph r G)).\n    rewrite <- log_normalize.precise_ocon_self; auto. apply precise_ocon.\n    + apply (bi_graph_precise_left _ x); auto.\n    + apply (bi_graph_precise_right _ x); auto.\n  Qed.\n\n  Lemma lem_subgraphupdate_r : forall G v G1 x v1 l r, valid (imp (and (star (graph r G1) (mwand (graph r G) (union (ptto_node x v l r) (union (graph l G) (graph r G))))) (and (subset_reach G r G1) (and (eq_notreach G r G1) (and (lookup G x v l r) (lookup G1 x v1 l r))))) (union (ptto_node x v1 l r) (union (graph l G1) (graph r G1)))).\n  Proof.\n    intros. unfold valid, imp, and, star, mwand, union, subset_reach, eq_notreach, lookup.\n    apply imp_andp_adjoint. normalize. apply precise_wand_ewand.\n    + apply precise_graph. apply RGF. left; intuition.\n    + destruct H1 as [? [? [? [? [? ?]]]]]. destruct H2 as [? [? [? [? [? ?]]]]].\n      rewrite (graph_graphs_eq_r G v x l r); auto. rewrite (graph_graphs_eq_r G1 v1 x l r); auto.\n      assert (forall (g: A), graph r g = graphs (r :: nil) (Graph_LGraph g)) by (intros; simpl; rewrite ocon_emp; auto).\n      rewrite (H13 G). rewrite (H13 G1). apply subgraph_update; auto.\n      - intros. left. simpl in H14. destruct H14 as [? | [? | [? | [? | ?]]]]; [subst x0 ..|exfalso]; auto.\n      - intros. left. simpl in H14. destruct H14 as [? | [? | [? | [? | ?]]]]; [subst x0 ..|exfalso]; auto.\n      - rewrite !reachable_through_set_single'; auto.\n  Qed.\n\n  Lemma lem_pttoupdate : forall v l r G x v1 G1, valid (imp (and (star (ptto_node x v1 l r) (mwand (ptto_node x v l r) (union (ptto_node x v l r) (union (graph l G) (graph r G))))) (and (lookup G x v l r) (update G x v1 G1))) (union (ptto_node x v1 l r) (union (graph l G1) (graph r G1)))).\n  Proof.\n    intros. unfold valid, imp, and, star, mwand, union, subset_reach, eq_notreach, lookup, update.\n    apply imp_andp_adjoint. normalize. apply precise_wand_ewand.\n    + unfold ptto_node. apply log_normalize.mapsto_precise.\n    + destruct H as [? [? [? [? [? ?]]]]]. rewrite <- ocon_assoc. rewrite <- (lookup_graph_unfold G x v l r); auto.\n      rewrite <- ocon_assoc.\n      assert (vgamma (LGraph_SGraph (Graph_LGraph G)) x = (v, l, r)). {\n        simpl. f_equal; [f_equal |]; auto.\n      } \n      pose proof (Graph_vgen_vgamma G x v v1 l r H5).\n      rewrite <- (lookup_graph_unfold (Graph_vgen G x v1) x v1 l r);\n        [| inversion H6 | ..|inversion H6|inversion H6]; auto.\n      2: rewrite H8; auto.\n      apply va_reachable_root_update_ramify; auto.\n  Qed.\n\nEnd GraphMark.\n", "meta": {"author": "anshumanmohan", "repo": "CertiDPK", "sha": "28afacefb162a27e74d744095229d9e4541e3d79", "save_path": "github-repos/coq/anshumanmohan-CertiDPK", "path": "github-repos/coq/anshumanmohan-CertiDPK/CertiDPK-28afacefb162a27e74d744095229d9e4541e3d79/hip/hip_graphmark_proofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2952343035371218}}
{"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 realm_destroy_ops_spec (g_rtt: Pointer) (g_rec_list: Pointer) (g_rd: Pointer) (adt: RData) : option RData :=\n    when adt == query_oracle adt;\n    rely (peq (base g_rtt) ginfo_loc);\n    rely (peq (base g_rec_list) ginfo_loc);\n    rely (peq (base g_rd) ginfo_loc);\n    let rtt_gidx := offset g_rtt in\n    let rec_list_gidx := offset g_rec_list in\n    let rd_gidx := offset g_rd in\n    rely is_gidx rtt_gidx; rely is_gidx rec_list_gidx; rely is_gidx rd_gidx;\n    let grd := (gs (share adt)) @ rd_gidx in\n    let grtt := (gs (share adt)) @ rtt_gidx in\n    let grecl := (gs (share adt)) @ rec_list_gidx in\n    rely prop_dec (glock grd = Some CPU_ID);\n    rely prop_dec (glock grtt = Some CPU_ID);\n    rely prop_dec (glock grecl = None);\n    rely (gtype grecl =? GRANULE_STATE_REC_LIST);\n    rely (gtype grd =? GRANULE_STATE_RD);\n    rely (gtype grtt =? GRANULE_STATE_TABLE);\n    rely prop_dec ((buffer (priv adt)) @ SLOT_RD = None);\n    rely prop_dec ((buffer (priv adt)) @ SLOT_REC_LIST = None);\n    rely prop_dec ((buffer (priv adt)) @ SLOT_TABLE = None);\n    let grd' := grd {gnorm: zero_granule_data_normal} {grec: zero_granule_data_rec}\n                    {ginfo: (ginfo grd) {g_tag: GRANULE_STATE_DELEGATED}} in\n    let grecl' := grecl {gnorm: zero_granule_data_normal} {grec: zero_granule_data_rec}\n                        {ginfo: (ginfo grecl) {g_tag: GRANULE_STATE_DELEGATED}} in\n    let grtt' := grtt {gnorm: zero_granule_data_normal} {grec: zero_granule_data_rec}\n                      {ginfo: (ginfo grtt) {g_rd: 0} {g_tag: GRANULE_STATE_DELEGATED}} in\n    let e := EVT CPU_ID (ACQ rec_list_gidx) in\n    let e1 := EVT CPU_ID (REL rtt_gidx grtt') in\n    let e' := EVT CPU_ID (REL rec_list_gidx (grecl' {glock: Some CPU_ID})) in\n    Some adt {log: e' :: e1 :: e :: (log adt)}\n         {share: (share adt) {gs: (gs (share adt)) # rtt_gidx == (grtt' {gtype: GRANULE_STATE_DELEGATED} {glock: None})\n                                                   # rec_list_gidx == (grecl' {gtype: GRANULE_STATE_DELEGATED})\n                                                   # rd_gidx == grd'}}.\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/realm_destroy_ops.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.29523243283841155}}
{"text": "From Coq Require Import String List ZArith Lia.\nFrom compcert Require Import Coqlib Integers Floats AST Ctypes Cop Clight Clightdefs.\nFrom compcert Require Import Maps Values ClightBigstep Events.\n\nRequire Import Clight.max.\n\nOpen Scope Z_scope.\n\nDefinition max_fspec := Z.max.\n\nTheorem f_max_correct (ge : genv) (e : env) (m : Memory.Mem.mem) :\n  forall (ste : temp_env) (n1 n2 : Z),\n    (* starting environment *)\n    ste ! _n1 = Some (Vint (Int.repr n1)) ->\n    ste ! _n2 = Some (Vint (Int.repr n2)) ->\n\n    (* bounds on coq representation *)\n    Int.min_signed <= n1 <= Int.max_signed ->\n    Int.min_signed <= n2 <= Int.max_signed ->\n\n    (* correct return *)\n    exists (t : trace) (rte : temp_env),\n      exec_stmt ge e ste m f_max.(fn_body) t rte m\n        (Out_return (Some ((Vint (Int.repr (max_fspec n1 n2)), tint)))).\nProof.\n  (* the two branches of this proof are exactly the same,\n     but have been left as is for simplicity *)\n  intros.\n  (* introduce existential variables *)\n  destruct (Z_le_dec n1 n2).\n  all: repeat eexists.\n  - econstructor. (* seq *)\n    + (* seq1 - ifthenelse *)\n      econstructor. (* if *)\n      * (* condition *)\n        repeat econstructor.\n        eassumption.\n        eassumption.\n        simpl.\n        econstructor.\n      * (* condition bool *)\n        simpl.\n        unfold Int.lt.\n        repeat rewrite Int.signed_repr by assumption.\n        destruct zlt; try omega.\n        econstructor.\n      * (* set result *)\n        destruct negb eqn:N; inversion_clear N.\n        repeat econstructor.\n        eassumption.\n    + (* seq2 - return *)\n      econstructor.\n      econstructor.\n      rewrite PTree.gss.\n      try rewrite Z.max_l by lia.\n      try rewrite Z.max_r by lia.\n      reflexivity.\n  - econstructor. (* seq *)\n    + (* seq1 - ifthenelse *)\n      econstructor. (* if *)\n      * (* condition *)\n        repeat econstructor.\n        eassumption.\n        eassumption.\n        simpl.\n        econstructor.\n      * (* condition bool *)\n        simpl.\n        unfold Int.lt.\n        repeat rewrite Int.signed_repr by assumption.\n        destruct zlt; try omega.\n        econstructor.\n      * (* set result *)\n        destruct negb eqn:N; inversion_clear N.\n        repeat econstructor.\n        eassumption.\n    + (* seq2 - return *)\n      econstructor.\n      econstructor.\n      rewrite PTree.gss.\n      try rewrite Z.max_l by lia.\n      try rewrite Z.max_r by lia.\n      reflexivity.\nQed.\n", "meta": {"author": "asosyuk", "repo": "asn1verification", "sha": "55395d63c2dcd512a28d9cd42d788e12f91e7641", "save_path": "github-repos/coq/asosyuk-asn1verification", "path": "github-repos/coq/asosyuk-asn1verification/asn1verification-55395d63c2dcd512a28d9cd42d788e12f91e7641/doc/tutorial/max.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.29523243283841155}}
{"text": "(* monae: Monadic equational reasoning in Coq                                 *)\n(* Copyright (C) 2020 monae authors, license: LGPL-2.1-or-later               *)\nFrom mathcomp Require Import all_ssreflect.\nFrom HB Require Import structures.\nRequire Import imonae_lib ihierarchy imonad_lib imonad_transformer.\n\n(******************************************************************************)\n(*   Uniform Lifting of Sigma-operations Along Functorial Monad Transformers  *)\n(*                                                                            *)\n(* This file corresponds to the formalization of [Mauro Jaskelioff,           *)\n(* Modular Monad Transformers, ESOP 2009] (from Sect. 5, definition 23).      *)\n(*                                                                            *)\n(*            codensityT == codensity monad transformer                       *)\n(*              slifting == definition of a sigma-operation using a           *)\n(*                          sigma-operation and a functorial monad            *)\n(*                          transformer                                       *)\n(* uniform_sigma_lifting == Theorem: given a functorial monad transformer t,  *)\n(*                          slifting is a lifting along Lift t                *)\n(*       slifting_stateT == lifting of a sigma-operation along stateT         *)\n(*      slifting_exceptT == lifting of a sigma-operation along exceptT        *)\n(*         slifting_envT == lifting of a sigma-operation along envT           *)\n(*      slifting_outputT == lifting of a sigma-operation along outputT        *)\n(*   slifting_alifting_* == Lemmas: slifting and alifting of algebraic        *)\n(*                          operations coincide                               *)\n(*              local_*E == Lemmas: liftings of local                         *)\n(*             handle_*E == Lemmas: liftings of handle                        *)\n(*              flush_*E == Lemmas: liftings of flush                         *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLocal Open Scope monae_scope.\n\nDefinition MK (m : UU0 -> UU0) (A : UU0) := forall (B : UU0), (A -> m B) -> m B.\n\nSection codensity.\nVariable (M : monad).\n\nDefinition retK : FId ~~> MK M :=\n  fun (A : UU0) (a : A) (B : UU0) (k : A -> M B) => k a.\n\nDefinition bindK (A B : UU0) (m : MK M A) f : MK M B :=\n  fun (C : UU0) (k : B -> M C) => m C (fun a : A => (f a) C k).\n\nLet left_neutral : BindLaws.left_neutral bindK retK.\nProof.\nby move=> A B a f; rewrite /bindK /=; apply funext_dep => C; exact: funext.\nQed.\n\nLet right_neutral : BindLaws.right_neutral bindK retK.\nProof.\nby move=> A m; rewrite /bindK /retK; apply funext_dep => C; exact: funext.\nQed.\n\nLemma associative : BindLaws.associative bindK.\nProof. by move=> A B C m f g; rewrite /bindK; exact: funext_dep. Qed.\n\nHB.instance Definition _ :=\n  isMonad_ret_bind.Build (MK M) left_neutral right_neutral associative.\n\nDefinition liftK : M ~~> MK M :=\n  fun (A : UU0) (m : M A) (B : UU0) (k : A -> M B) => m >>= k.\n\nLet retliftK : MonadMLaws.ret liftK.\nProof.\nmove=> A; rewrite /liftK/= /retK/=; apply funext => a.\nby apply funext_dep => B /=; apply: funext => b; rewrite bindretf.\nQed.\n\nLet bindliftK : MonadMLaws.bind liftK.\nProof.\nmove=> A B m f; rewrite /liftK; apply funext_dep => C /=.\nby apply funext => g; rewrite bindA.\nQed.\n\nHB.instance Definition _ := isMonadM_ret_bind.Build\n  M [the monad of MK M] liftK retliftK bindliftK.\n\nEnd codensity.\n\nDefinition codensityT := fun M : monad => [the monad of MK M].\n\nHB.instance Definition _ :=\n  isMonadT.Build codensityT (fun M => [the monadM _ _ of @liftK M]).\n\nSection kappa.\nVariables (M : monad) (E : functor) (op : E.-operation M).\n\nDefinition kappa' : E ~~> codensityT M :=\n  fun (A : UU0) (s : E A) (B : UU0) (k : A -> M B) =>\n    op B ((E # k) s).\n\nLemma naturality_kappa' : naturality _ _ kappa'.\nProof.\nmove=> A B h; rewrite /kappa'; apply funext => ea; rewrite [in RHS]/=.\ntransitivity (fun B0 (k : B -> M B0) => op B0 ((E # (k \\o h)) ea)) => //.\nby apply funext_dep => C; apply funext => D; rewrite functor_o.\nQed.\n\nHB.instance Definition _ := isNatural.Build\n  _ (codensityT M) kappa' naturality_kappa'.\n\nDefinition kappa := [the _ ~> _ of kappa'].\n\nLemma kappaE X : kappa X =\n  fun (s : E X) (B : UU0) (k : X -> M B) => op B ((E # k) s).\nProof. by []. Qed.\n\nEnd kappa.\n\nDefinition naturality_MK (M : functor) (A : UU0) (m : MK M A) :=\n  naturality [the functor of exponential_F A \\o M] M m.\n\nSection from.\nVariables (M : monad).\n\nDefinition from_component : codensityT M ~~> M :=\n  fun (A : UU0) (c : codensityT M A) => c A Ret.\n\nHypothesis naturality_MK : forall (A : UU0) (m : MK M A),\n  naturality_MK m.\n\nLemma natural_from_component : naturality (codensityT M) M from_component.\nProof.\nmove=> A B h; apply funext => m /=.\nrewrite [RHS](_ : _ = m B (Ret \\o h)) //. (* by definition of from *)\nrewrite -natural.\nrewrite [LHS](_ : _ = (M # h \\o m A) Ret) //. (* by definition of from *)\nby rewrite naturality_MK.\nQed.\n\nHB.instance Definition _ :=\n  isNatural.Build _ M from_component natural_from_component.\n\nDefinition from := [the _ ~> _ of from_component].\n\nLemma from_component_liftK A :\n  @from_component A \\o Lift [the monadT of codensityT] M A = id.\nProof.\nby apply funext => m /=; rewrite /from_component/= /liftK /= bindmret.\nQed.\n\nEnd from.\n\nSection psi_kappa.\nVariables (E : functor) (M : monad) (op : E.-operation M).\n\nDefinition psik : E.-aoperation (codensityT M) := psi (kappa op).\n\nLemma psikE (A : UU0) : op A = (@from_component M A) \\o (@psik A) \\o\n  ((E ## Lift [the monadT of codensityT] M) A).\nProof.\napply funext => m /=.\nrewrite /from_component /psik /= /psi' /kappa' /fun_app_nt /=.\nrewrite /bindK /=.\nrewrite -[in RHS]compE.\nrewrite -[in RHS]compE.\nrewrite -compA.\nrewrite -functor_o.\nrewrite from_component_liftK.\nrewrite functor_id.\nby rewrite compfid.\nQed.\n\nEnd psi_kappa.\n\nSection uniform_sigma_lifting.\nVariables (E : functor) (M : monad) (op : E.-operation M) (t : fmt).\nHypothesis naturality_MK : forall (A : UU0) (m : MK M A), naturality_MK m.\n\nLet op1 : t (codensityT M) ~> t M := hmap t (from naturality_MK).\nLet op2 := alifting (psik op) (Lift t _).\nLet op3 : [the functor of E \\o t M] ~> [the functor of E \\o t (codensityT M)] :=\n  E ## hmap t (Lift [the monadT of codensityT] M).\n\nDefinition slifting : E.-operation (t M) := op1 \\v op2 \\v op3.\n\nTheorem uniform_sigma_lifting : lifting_monadT op slifting.\nProof.\nrewrite /lifting_monadT /slifting => X.\napply/esym.\ntransitivity ((op1 \\v op2) X \\o op3 X \\o E # Lift t M X).\n  by rewrite (vassoc op1) vcompE/= !vcompE.\nrewrite -compA.\ntransitivity ((op1 \\v op2) X \\o\n    ((E # Lift t (codensityT M) X) \\o\n    (E # Lift [the monadT of codensityT] M X))).\n  congr (_ \\o _); rewrite /op3.\n  by rewrite -functor_o -natural_hmapE functor_app_naturalE -(@functor_o E).\ntransitivity (op1 X \\o\n  (op2 X \\o E # Lift t (codensityT M) X) \\o E # Lift [the monadT of codensityT] M X).\n  by rewrite vcompE -compA.\nrewrite -uniform_algebraic_lifting.\ntransitivity (Lift t M X \\o from naturality_MK X \\o (psik op) X \\o\n  E # Lift [the monadT of codensityT] M X).\n  congr (_ \\o _).\n  by rewrite compA natural_hmapE.\nrewrite -2!compA.\ncongr (_ \\o _).\nby rewrite compA -psikE.\nQed.\nEnd uniform_sigma_lifting.\n\n(* example 29 *)\nSection slifting_instances.\n\nVariables (E : functor) (M : monad) (op : E.-operation M).\nHypothesis naturality_MK : forall (A : UU0) (m : MK M A), naturality_MK m.\n\nSection slifting_stateT.\nVariable S : UU0.\n\nLet tau (X : UU0) s (f : S -> M (X * S)%type) := f s.\n\nLet op' : E \\o stateT S M ~~> stateT S M :=\n  fun (X : UU0) t s => op (X * S)%type ((E # tau s) t).\n\nLemma slifting_stateT (X : UU0) :\n  (slifting op [the fmt of stateT S] naturality_MK) X = @op' _.\nProof.\napply funext => emx.\nrewrite /op'.\napply funext => s.\nrewrite /slifting.\nrewrite 2!vcompE.\nset h := hmap _.\nrewrite [in RHS](psikE op).\nrewrite 2!functor_app_naturalE.\nrewrite /=.\ncongr (from_component _).\napply funext_dep => A; apply funext => f.\nrewrite {1}/psi' /=.\nrewrite /bindS /=.\nrewrite vcompE/=.\nrewrite /liftS /=.\nrewrite bindA.\nset ret_id := (X in _ >>= X).\nhave -> : ret_id = fun (x : MS S (codensityT M) X) (C : UU0) => (fun t => x s C t).\n  by apply funext.\nrewrite /psi' /= /bindK /kappa' /=.\ncongr (op A).\nrewrite -2![in LHS](compE _ _ emx) -2![in RHS](compE _ _ emx).\nby rewrite -!functor_o.\nQed.\n\nEnd slifting_stateT.\n\nSection slifting_exceptT.\nVariable Z : UU0.\n\nLet op' : E \\o exceptT Z M ~~> exceptT Z M := fun (Y : UU0) => @op _.\n\nLemma slifting_exceptT (X : UU0) :\n  (slifting op [the fmt of exceptT Z] naturality_MK) X = @op' X.\nProof.\napply funext => emx.\nrewrite /op'.\nrewrite (psikE op (Z + X)%type).\nrewrite /slifting.\nrewrite 2!vcompE.\nset h := hmap _.\nrewrite /=.\nf_equal.\nrewrite /psi' /=.\nrewrite /bindX bindE /=.\napply funext_dep => A; apply funext => k.\nrewrite vcompE/=.\nrewrite /liftX /=.\nrewrite bindE /= /bindK /=.\nrewrite /psi' /= /bindK /=.\nrewrite /kappa' /=.\ncongr (op _ _).\nrewrite -(compE (E # _)).\nby rewrite -functor_o.\nQed.\n\nEnd slifting_exceptT.\n\nSection slifting_envT.\nVariable Env : UU0.\n\nLet tau (X : UU0) e (f : Env -> M X) := f e.\n\nLet op' : E \\o envT Env M ~~> envT Env M :=\n  fun (X : UU0) t => fun e => op X ((E # tau e) t).\n\nLemma slifting_envT (X : UU0) :\n  (slifting op [the fmt of envT Env] naturality_MK) X = @op' _.\nProof.\napply funext => emx.\nrewrite /op'.\napply funext => s.\nrewrite /slifting.\nrewrite 2!vcompE.\nset h := hmap _.\nrewrite (psikE op).\nrewrite 2!functor_app_naturalE.\nrewrite /=.\ncongr (from_component _).\napply funext_dep => A; apply funext => f.\nrewrite {1}/psi' /=.\nrewrite /bindEnv /=.\nrewrite vcompE/=.\nrewrite bindE /= /bindK.\nrewrite fmapE /bindK.\nrewrite /liftEnv /=.\nrewrite -(compE _ _ emx) -functor_o.\nrewrite -[in RHS](compE _ _ emx) -functor_o.\nrewrite /psi' /= /bindK /= /kappa' /=.\ncongr (op A).\nrewrite -(compE _ _ emx) -[in RHS](compE _ _ emx).\nby rewrite -2!functor_o.\nQed.\n\nEnd slifting_envT.\n\nSection slifting_outputT.\nVariable R : UU0.\n\nLet op' : E \\o outputT R M ~~> outputT R M :=\n  fun (X : UU0) => @op (X * seq R)%type.\n\nLemma slifting_outputT (X : UU0) :\n  (slifting op [the fmt of outputT R] naturality_MK) X = @op' _.\nProof.\napply funext => emx.\nrewrite /op'.\nrewrite /slifting.\nrewrite 2!vcompE.\nset h := hmap _.\nrewrite (psikE op).\nrewrite 2!functor_app_naturalE.\nrewrite /=.\nf_equal.\nrewrite /psi' /= /bindK /bindO /= bindE /= /bindK /=.\napply funext_dep => A; apply funext => f.\nrewrite fmapE /bindK.\nrewrite vcompE/=.\nrewrite /liftO /=.\nrewrite -(compE _ _ emx) -functor_o.\nrewrite bindE /= /bindK /=.\nrewrite fmapE.\nrewrite /bindK.\nrewrite /psi' /= /bindK /= /kappa' /=.\ncongr (op A).\nrewrite -(compE _ _ emx) -[in RHS](compE _ _ emx).\nrewrite -2!functor_o.\ncongr ((E # _) _).\napply funext => rmx /=.\nrewrite /retK /= bindE fmapE /= /bindK.\ncongr (Lift [the monadT of codensityT] M _ _ _ _).\nby apply funext => -[].\nQed.\n\nEnd slifting_outputT.\n\nEnd slifting_instances.\n\n(* proposition 28 *)\nSection slifting_alifting_coincide.\n\nVariables (E : functor) (M : monad) (aop : E.-aoperation M).\nHypothesis naturality_MK : forall (A : UU0) (m : MK M A),\n  naturality_MK m.\n\nLemma slifting_alifting_stateFMT (S : UU0) (t := [the fmt of stateT S]) :\n  slifting aop t naturality_MK = alifting aop (Lift t M).\nProof.\napply nattrans_ext => X.\nrewrite (slifting_stateT aop naturality_MK S).\napply funext => m; apply funext => s.\nrewrite /alifting.\nrewrite /=.\nrewrite psiE /=.\nrewrite /bindS.\nrewrite vcompE/=.\nrewrite /liftS/=.\nrewrite 2!algebraic.\ncongr (aop _ _).\nrewrite -[RHS](compE _ (E # _)).\nrewrite -functor_o.\nrewrite -[RHS](compE _ (E # _)).\nrewrite -functor_o.\ncongr ((E # _) m).\napply funext => x /=.\nby rewrite 2!bindretf.\nQed.\n\nLemma slifting_alifting_exceptFMT (Z : UU0) (t := [the fmt of exceptT Z]) :\n  slifting aop t naturality_MK = alifting aop (Lift t M).\nProof.\napply nattrans_ext => X.\nrewrite (slifting_exceptT aop naturality_MK Z).\napply funext => m.\nrewrite /alifting.\nrewrite /=.\nrewrite psiE /= /bindX.\nrewrite vcompE/=.\nrewrite /liftX.\nrewrite 2!algebraic.\ncongr (aop _ _).\nrewrite -[RHS](compE _ (E # _)).\nrewrite -functor_o.\nrewrite -[RHS](compE _ (E # _)).\nrewrite -functor_o.\nrewrite (_ : _ \\o Ret = id) ?functor_id //.\napply funext => n /=.\nby rewrite 2!bindretf.\nQed.\n\nLemma slifting_alifting_envFMT (Env : UU0) (t := [the fmt of envT Env]) :\n  slifting aop t naturality_MK = alifting aop (Lift t M).\nProof.\napply nattrans_ext => X.\nrewrite (slifting_envT aop naturality_MK Env).\napply funext => m; apply funext => e.\nrewrite /alifting.\nrewrite /=.\nrewrite psiE /= /bindEnv.\nrewrite vcompE/=.\nrewrite /liftEnv.\nrewrite algebraic.\ncongr (aop _ _).\nrewrite -[RHS](compE _ (E # _)).\nrewrite -functor_o.\ncongr ((E # _) m).\napply funext => x /=.\nby rewrite bindretf.\nQed.\n\nLemma slifting_alifting_outputFMT (R : UU0) (t := [the fmt of outputT R]) :\n  slifting aop t naturality_MK = alifting aop (Lift t M).\nProof.\napply nattrans_ext => X.\nrewrite (slifting_outputT aop naturality_MK R).\napply funext => m.\nrewrite /alifting.\nrewrite /=.\nrewrite psiE /= /bindO.\nrewrite vcompE/=.\nrewrite /liftO.\nrewrite 2!algebraic.\ncongr (aop _ _).\nrewrite -[RHS](compE _ (E # _)).\nrewrite -functor_o.\nrewrite -[RHS](compE _ (E # _)).\nrewrite -functor_o.\nrewrite (_ : _ \\o Ret = id) ?functor_id //.\napply funext => n /=.\nrewrite 2!bindretf.\nOpen (X in _ >>= X).\n  by case : x => ? ?; rewrite cat0s.\nby rewrite bindmret.\nQed.\n\nEnd slifting_alifting_coincide.\n\nRequire Import imonad_model.\n\n(* example 30 *)\nSection slifting_local.\nVariable Env : UU0.\nLet E := [the functor of Local.acto Env].\nLet M := [the monad of EnvironmentMonad.acto Env].\nLet local : E.-operation M := local_op Env.\nHypothesis naturality_MK : forall (A : UU0) (m : MK M A), naturality_MK m.\n\nSection slifting_local_FMT.\nVariable T : fmt.\n\nDefinition localKT (f : Env -> Env) : T (codensityT M) ~~> T (codensityT M) :=\n  fun (X : UU0) t => Join\n    (Lift T (codensityT M) (T (codensityT M) X) (fun Y k => local Y (f, k t))).\n\nDefinition localT (f : Env -> Env) : T M ~~> T M :=\n  fun X t => let t' := hmap T (Lift [the monadT of codensityT] M) X t in\n  hmap T (from naturality_MK) X (localKT f t').\n\nEnd slifting_local_FMT.\n\nSection slifting_local_stateT.\nVariable S : UU0.\n\nDefinition local_stateT (f : Env -> Env) : stateT S M ~~> stateT S M :=\n  fun X t s e => t s (f e).\n\nLet local_stateT' : (E \\o stateT S M) ~~> (stateT S M) :=\n  fun X => uncurry (@local_stateT ^~ X).\n\nLemma local_stateTE (X : UU0) :\n  (slifting local [the fmt of stateT S] naturality_MK) X = @local_stateT' X.\nProof. by rewrite slifting_stateT; apply funext => -[]. Qed.\nEnd slifting_local_stateT.\n\nSection slifting_local_exceptT.\nVariable Z : UU0.\nDefinition local_exceptT (f : Env -> Env) : exceptT Z M ~~> exceptT Z M :=\n  fun X t e => t (f e).\n\nLet local_exceptT' : (E \\o exceptT Z M) ~~> (exceptT Z M) :=\n  fun X => uncurry (@local_exceptT ^~ X).\n\nLemma local_exceptTE (X : UU0) :\n  (slifting local [the fmt of exceptT Z] naturality_MK) X = @local_exceptT' X.\nProof. by rewrite slifting_exceptT; apply funext => -[]. Qed.\n\nEnd slifting_local_exceptT.\n\nSection slifting_local_envT.\nVariable Z : UU0.\nDefinition local_envT (f : Env -> Env) : envT Z M ~~> envT Z M :=\n  fun X t e e' => t e (f e').\n\nLet local_envT' : E \\o envT Z M ~~> envT Z M :=\n  fun X => uncurry (@local_envT ^~ X).\n\nLemma local_envTE (X : UU0) :\n  (slifting local [the fmt of envT Z] naturality_MK) X = @local_envT' X.\nProof.\nrewrite slifting_envT.\nby apply funext => -[].\nQed.\nEnd slifting_local_envT.\n\nSection slifting_local_outputT.\nVariable R : UU0.\nDefinition local_outputT (f : Env -> Env) : outputT R M ~~> outputT R M :=\n  fun (X : UU0) t e => t (f e).\n\nLet local_outputT' : E \\o outputT R M ~~> outputT R M :=\n  fun (X : UU0) => uncurry (@local_outputT ^~ X).\n\nLemma local_outputTE (X : UU0) :\n  (slifting local [the fmt of outputT R] naturality_MK) X = @local_outputT' X.\nProof. by rewrite slifting_outputT; apply funext => -[]. Qed.\nEnd slifting_local_outputT.\n\nEnd slifting_local.\n\n(* example 31 *)\nSection slifting_handle. (* except monad with Z = unit *)\nLet E := [the functor of Handle.acto unit].\nLet M := [the monad of ExceptMonad.acto unit].\nLet handle : E.-operation M := @handle_op unit.\nHypothesis naturality_MK : forall (A : UU0) (m : MK M A),\n  naturality_MK m.\n\nSection slifting_handle_stateT.\nVariable S : UU0.\nDefinition handle_stateT (X : UU0) (t : stateT S M X) (h : unit -> stateT S M X)\n  : stateT S M X := fun s => match t s with\n    | inl z(*unit*) => h z s\n    | inr x => inr x\n    end.\n\nLet handle_stateT' : (E \\o stateT S M) ~~> (stateT S M) :=\n  fun (X : UU0) => uncurry (@handle_stateT X).\n\nLemma handle_stateTE (X : UU0) :\n  (slifting handle [the fmt of stateT S] naturality_MK) X = @handle_stateT' X.\nProof. by rewrite slifting_stateT; apply funext => -[m f]. Qed.\nEnd slifting_handle_stateT.\n\nSection slifting_handle_exceptT.\nVariable Z : UU0.\nDefinition handle_exceptT (X : UU0) (t : exceptT Z M X)\n  (h : unit -> exceptT Z M X) : exceptT Z M X := match t with\n    | inl z(*unit*) => h z\n    | inr x => inr x\n    end.\n\nLet handle_exceptT' : E \\o exceptT Z M ~~> exceptT Z M :=\n  fun (X : UU0) => uncurry (@handle_exceptT X).\n\nLemma handle_exceptTE (X : UU0) :\n  (slifting handle [the fmt of exceptT Z] naturality_MK) X = @handle_exceptT' X.\nProof. by rewrite slifting_exceptT; exact: funext. Qed.\nEnd slifting_handle_exceptT.\n\nSection slifting_handle_envT.\nVariable Z : UU0.\nDefinition handle_envT (X : UU0) (t : envT Z M X) (h : unit -> envT Z M X)\n  : envT Z M X := fun e => match t e with\n    | inl z(*unit*) => h z e\n    | inr x => inr x\n    end.\n\nLet handle_envT' : E \\o envT Z M ~~> envT Z M :=\n  fun (X : UU0) => uncurry (@handle_envT X).\n\nLemma handle_envTE (X : UU0) :\n  (slifting handle [the fmt of envT Z] naturality_MK) X = @handle_envT' X.\nProof.\nby rewrite slifting_envT; apply funext => -[m f]; exact: funext.\nQed.\nEnd slifting_handle_envT.\n\nSection slifting_handle_outputT.\nVariable R : UU0.\nDefinition handle_outputT (X : UU0) (t : outputT R M X)\n  (h : unit -> outputT R M X) : outputT R M X := match t with\n    | inl z(*unit*) => h z\n    | inr x => inr x\n    end.\n\nLet handle_outputT' : E \\o outputT R M ~~> outputT R M :=\n  fun (X : UU0) => uncurry (@handle_outputT X).\n\nLemma handle_outputTE (X : UU0) :\n  (slifting handle [the fmt of outputT R] naturality_MK) X = @handle_outputT' X.\nProof. by rewrite slifting_outputT; apply funext => -[]. Qed.\nEnd slifting_handle_outputT.\n\nEnd slifting_handle.\n\n(* example 32 *)\nSection slifting_flush.\nVariable R : UU0.\nLet E := [the functor of Flush.acto].\nLet M := [the monad of OutputMonad.acto R].\nLet flush : E.-operation M := flush_op R.\nHypothesis naturality_MK : forall (A : UU0) (m : MK M A),\n  naturality_MK m.\n\nSection slifting_flush_stateT.\nVariable S : UU0.\nDefinition flush_stateT : stateT S M ~~> stateT S M :=\n  fun (X : UU0) t s => let: (x, _) := t s in (x, [::]).\n\nLemma flush_stateTE (X : UU0) :\n  (slifting flush [the fmt of stateT S] naturality_MK) X = @flush_stateT X.\nProof. by rewrite slifting_stateT. Qed.\nEnd slifting_flush_stateT.\n\nSection slifting_flush_exceptT.\nVariable Z : UU0.\nDefinition flush_exceptT (X : UU0) (t : exceptT Z M X) (h : Z -> exceptT Z M X)\n    : exceptT Z M X :=\n  let: (c, _) := t in (c, [::]).\n\nLet flush_exceptT' : E \\o exceptT Z M ~~> exceptT Z M :=\n  fun (X : UU0) c => let : (x, _) := c in (x, [::]).\n\nLemma flush_exceptTE (X : UU0) :\n  (slifting flush [the fmt of exceptT Z] naturality_MK) X = @flush_exceptT' X.\nProof. by rewrite slifting_exceptT. Qed.\nEnd slifting_flush_exceptT.\n\nSection slifting_flush_envT.\nVariable Z : UU0.\nDefinition flush_envT : envT Z M ~~>  envT Z M :=\n  fun (X : UU0) t e => let: (x, _) := t e in (x, [::]).\n\nLemma flush_envTE (X : UU0) :\n  (slifting flush [the fmt of envT Z] naturality_MK) X = @flush_envT X.\nProof. by rewrite slifting_envT. Qed.\nEnd slifting_flush_envT.\n\nSection slifting_flush_outputT.\nVariable Z : UU0.\nDefinition flush_outputT (X : UU0) (t : outputT R M X) (h : Z -> outputT R M X)\n  : outputT R M X := let: (p, w) := t in (p, [::]).\n\nLet flush_outputT' : E \\o outputT R M ~~> outputT R M :=\n  fun (X : UU0) e => let: (pw, w') := e in (pw, [::]).\n\nLemma flush_outputTE (X : UU0) :\n  (slifting flush [the fmt of outputT R] naturality_MK) X = @flush_outputT' X.\nProof. by rewrite slifting_outputT; exact: funext. Qed.\nEnd slifting_flush_outputT.\n\nEnd slifting_flush.\n", "meta": {"author": "affeldt-aist", "repo": "monae", "sha": "48f0671720f55f4f7408de425fc51804c0515a87", "save_path": "github-repos/coq/affeldt-aist-monae", "path": "github-repos/coq/affeldt-aist-monae/monae-48f0671720f55f4f7408de425fc51804c0515a87/impredicative_set/ifmt_lifting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.29523243283841155}}
{"text": "Require Import ExtLib.Tactics.\nRequire Import MirrorCore.RTac.Core.\nRequire Import MirrorCore.RTac.CoreK.\n\nRequire Import MirrorCore.Util.Forwardy.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nSection parameterized.\n  Context {typ : Set}.\n  Context {expr : Set}.\n\n  Context {RType_typ : RType typ}.\n  Context {RTypeOk_typ : RTypeOk}.\n  Context {Expr_expr : Expr typ expr}.\n  Context {Typ0_Prop : Typ0 _ Prop}.\n  Context {ExprUVar_expr : ExprUVar expr}.\n\n  Definition THEN (c1 : rtac typ expr)\n             (c2 : rtacK typ expr)\n  : rtac typ expr :=\n    fun ctx sub g =>\n      match c1 ctx sub g with\n        | More_ sub' g' => c2 _ sub' g'\n        | Solved sub => Solved sub\n        | Fail => Fail\n      end.\n\n  Theorem THEN_sound\n  : forall (tac1 : rtac typ expr) (tac2 : rtacK typ expr),\n      rtac_sound tac1 ->\n      rtacK_sound tac2 ->\n      rtac_sound (THEN tac1 tac2).\n  Proof.\n    unfold THEN.\n    intros.\n    red. intros. subst.\n    specialize (H ctx s g _ eq_refl).\n    match goal with\n      | |- context [ match ?X with _ => _ end ] =>\n        destruct X; auto\n    end.\n    eapply rtac_spec_trans; eauto.\n    eapply H0. reflexivity.\n  Qed.\n\nEnd parameterized.\n\nTypeclasses Opaque THEN.\nHint Opaque THEN : typeclass_instances.\n\nArguments THEN {typ expr} _%rtac _%rtacK _ _ _ : rename.\n\nNotation \"X  ;; Y\" := (@THEN _ _ X%rtac Y%rtacK) (at level 70, right associativity) : rtac_scope.\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/Then.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2951926135382616}}
{"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 csubst3.\nRequire Export alphaeq3.\n\n\nLemma aeq_lsubstc_mk_subtype_ex {o} :\n  forall (t1 t2 : @NTerm o)\n         (sub : CSubstitution)\n         (w : wf_term (mk_subtype t1 t2)) (c : cover_vars (mk_subtype t1 t2) sub),\n  {w1 : wf_term t1\n   & {w2 : wf_term t2\n   & {c1 : cover_vars t1 sub\n   & {c2 : cover_vars t2 sub\n   & alphaeqc (lsubstc (mk_subtype t1 t2) w sub c)\n              (mkc_subtype (lsubstc t1 w1 sub c1) (lsubstc t2 w2 sub c2)) }}}}.\nProof.\n  introv.\n  pose proof (lsubstc_mk_subtype_ex t1 t2 sub w c) as h.\n  exrepnd.\n  exists w1 w2 c1 c2.\n  rw h1.\n  unfold alphaeqc; simpl.\n  unfold mk_subtype, mk_vsubtype, mk_member, mk_equality, mk_function.\n  repeat prove_alpha_eq4.\n  pose proof (ex_fresh_var (all_vars (csubst t2 sub))) as fvs.\n  exrepnd.\n  apply (al_bterm_aux [v]); simpl; auto.\n  { apply disjoint_singleton_l.\n    allrw in_app_iff; allrw not_over_or; sp. }\n  repeat (rw @lsubst_aux_trivial_cl_term2; eauto 3 with slow);\n  apply cover_vars_iff_closed_lsubstc; 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/csubst4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.29519261353826154}}
{"text": "(**\nCoLoR, a Coq library on rewriting and termination.\nSee the COPYRIGHTS and LICENSE files.\n\n- Frederic Blanqui, 2008-02-22, 2009-10-20 (rpo)\n\nconvert CoLoR terms into Coccinelle terms \n*)\n\nSet Implicit Arguments.\n\nFrom CoLoR Require Import LogicUtil ATerm VecUtil.\nFrom CoLoR Require VecUtil more_list APosition AContext ordered_set.\nFrom Coq Require Inverse_Image Max.\n\n(***********************************************************************)\n(** convert a CoLoR signature into a Coccinelle signature *)\n\nFrom CoLoR Require Import term_spec EqUtil.\n\nModule Make_Signature (Import S : SIG) <: Signature.\n  Module Symb <: decidable_set.S.\n    Definition A := symbol Sig.\n    Definition eq_bool := @beq_symb Sig.\n    Lemma eq_bool_ok : forall a1 a2,\n      match eq_bool a1 a2 with true => a1 = a2 | false => ~ a1 = a2 end.\n    Proof.\n      intros a1 a2. unfold eq_bool. case_beq_symb Sig a1 a2. refl.\n      rewrite <- (beq_ko (@beq_symb_ok Sig)). hyp.\n    Qed.\n  End Symb.\n  Definition arity (f : Sig) := Free (arity f).\nEnd Make_Signature.\n\n(***********************************************************************)\n(** convert CoLoR variables to Coccinelle variables *)\n\nFrom CoLoR Require Import NatUtil.\n\nModule Var <: decidable_set.S.\n  Definition A := nat.\n  Definition eq_bool := beq_nat.\n  Lemma eq_bool_ok : forall a1 a2,\n    match eq_bool a1 a2 with true => a1 = a2 | false => ~ a1 = a2 end.\n  Proof.\n    intros a1 a2. unfold eq_bool. case_beq_nat a1 a2. refl.\n    rewrite <- (beq_ko beq_nat_ok). hyp.\n  Qed.\nEnd Var.\n\n(***********************************************************************)\n(** convert CoLoR terms into Coccinelle terms *)\n\nFrom Coq Require Import List Relations.\nFrom CoLoR Require Import term SN ASubstitution.\n\nModule Make_Term (Import S : SIG) <: Term.\n\n  Notation aterm := (term Sig). Notation aterms := (vector aterm).\n  Notation AVar := ATerm.Var.\n\n  Module Sig := Make_Signature S.\n\n  Include (term.Make' Sig Var).\n\n  Fixpoint term_of_aterm (t : aterm) :=\n    match t with\n      | AVar x => Var x\n      | Fun f ts =>\n        let fix terms_of_aterms n (ts : aterms n) :=\n          match ts with\n            | Vnil => nil\n            | Vcons u us => term_of_aterm u :: terms_of_aterms _ us\n          end in Term f (terms_of_aterms (arity f) ts)\n    end.\n\n  Fixpoint terms_of_aterms n (ts : aterms n) :=\n    match ts with\n      | Vnil => nil\n      | Vcons u us => term_of_aterm u :: terms_of_aterms us\n    end.\n\n  Lemma terms_of_aterms_eq : forall n (ts : aterms n),\n    (fix terms_of_aterms n (ts : aterms n) :=\n      match ts with\n        | Vnil => nil\n        | Vcons u us => term_of_aterm u :: terms_of_aterms _ us\n      end) n ts = terms_of_aterms ts.\n\n  Proof. induction ts; simpl; intros. refl. rewrite IHts. refl. Qed.\n\n  Lemma term_of_aterm_fun : forall f ts,\n    term_of_aterm (Fun f ts) = Term f (terms_of_aterms ts).\n\n  Proof. intros. simpl. rewrite terms_of_aterms_eq. refl. Qed.\n\n  Import VecUtil.\n\n  Lemma terms_of_aterms_cast : forall n (ts : aterms n) p (e : n=p),\n    terms_of_aterms (Vcast ts e) = terms_of_aterms ts.\n\n  Proof.\n    induction ts; destruct p; simpl; intros; try discr.\n    rewrite Vcast_refl. refl.\n    inversion e. subst p. rewrite Vcast_cons. simpl.\n    rewrite IHts. refl.\n  Qed.\n\n  Lemma terms_of_aterms_app : forall n (ts : aterms n) p (us : aterms p),\n    terms_of_aterms (Vapp ts us) = terms_of_aterms ts ++ terms_of_aterms us.\n\n  Proof. induction ts; simpl; intros. refl. rewrite IHts. refl. Qed.\n\n  Lemma length_terms_of_aterms : forall n (ts : aterms n),\n    length (terms_of_aterms ts) = n.\n\n  Proof. induction ts; simpl; intros. refl. rewrite IHts. refl. Qed.\n\n  Fixpoint sub_of_asub (s : ASubstitution.substitution Sig) n :=\n    match n with\n      | 0 => nil\n      | S n' => (n', term_of_aterm (s n')) :: sub_of_asub s n'\n    end.\n\nImport more_list.\n\nNotation find := (@find _ eq_var_bool _).\n\n  Lemma find_sub_of_asub : forall s n v, find v (sub_of_asub s n) =\n    if bgt_nat n v then Some (term_of_aterm (s v)) else None.\n\n  Proof.\n    induction n; intros. refl. simpl sub_of_asub. simpl more_list.find.\n    rewrite IHn. unfold eq_var_bool. case_beq_nat v n.\n    assert (bgt_nat (S v) v = true). rewrite bgt_nat_ok. lia. rewrite H. refl.\n    case_eq (bgt_nat n v); intros; case_eq (bgt_nat (S n) v); intros.\n    refl. rewrite bgt_nat_ok in H0. rewrite bgt_nat_ko in H1. lia.\n    rewrite bgt_nat_ok in H1. rewrite bgt_nat_ko in H0.\n    rewrite (beq_ko beq_nat_ok) in H. lia. refl.\n  Qed.\n\n  Lemma term_of_aterm_sub : forall s k t, k > maxvar t ->\n    term_of_aterm (sub s t) = apply_subst (sub_of_asub s k) (term_of_aterm t).\n\n  Proof.\n    intros s k t; pattern t; apply ATerm.term_ind\n      with (Q := fun n (ts : aterms n) =>\n        k > maxvars ts -> terms_of_aterms (Vmap (sub s) ts) =\n        map (apply_subst (sub_of_asub s k)) (terms_of_aterms ts)); clear t.\n    simpl. intros. rewrite find_sub_of_asub. case_eq (bgt_nat k x); intros.\n    refl. rewrite bgt_nat_ko in H0. lia.\n    intros. simpl sub. rewrite !term_of_aterm_fun. simpl.\n    f_equal. apply H. hyp.\n    refl. intros t n ts. simpl. rewrite maxvars_cons, gt_max.\n    intros. destruct H1. rewrite H. 2: hyp. rewrite H0. 2: hyp. refl.\n  Qed.\n\n  Import APosition AContext.\n\n  Lemma term_of_aterm_fill : forall u t c, term_of_aterm (fill c t) =\n    replace_at_pos (term_of_aterm (fill c u)) (term_of_aterm t) (pos_context c).\n\n  Proof.\n    induction c; intros. refl. simpl fill. simpl pos_context.\n    rewrite !term_of_aterm_fun, replace_at_pos_unfold.\n    f_equal.\n    rewrite !terms_of_aterms_cast, !terms_of_aterms_app. simpl.\n    rewrite replace_at_pos_list_replace_at_pos_in_subterm, <- IHc. refl.\n    rewrite length_terms_of_aterms. refl.\n  Qed.\n\n  Lemma is_a_pos_context : forall u c,\n    is_a_pos (term_of_aterm (fill c u)) (pos_context c) = true.\n\n  Proof.\n    induction c; intros. refl. simpl fill. rewrite term_of_aterm_fun. simpl.\n    rewrite terms_of_aterms_cast, terms_of_aterms_app. simpl.\n    assert (nth_error (terms_of_aterms t ++ term_of_aterm (fill c u) ::\n      terms_of_aterms t0) i = nth_error (terms_of_aterms t ++ term_of_aterm\n        (fill c u) :: terms_of_aterms t0) (length (terms_of_aterms t))).\n    f_equal. rewrite length_terms_of_aterms. refl.\n    rewrite H, nth_error_at_pos. hyp.\n  Qed.\n\nEnd Make_Term.\n\n(***********************************************************************)\n(** module type for using Coccinelle's RPO *)\n\nFrom CoLoR Require Import rpo rpo_extension.\n\nModule Type PRECEDENCE.\n  Parameter Sig : Signature.\n  Parameter status : Sig -> status_type.\n  Parameter prec_nat : Sig -> nat.\n  Parameter bb : nat.\n  Parameter prec_eq_status :\n    forall f g, prec_eq prec_nat f g -> status f = status g.\nEnd PRECEDENCE.\n\n(***********************************************************************)\n(** convert Coccinelle RPO into a CoLoR WeakRedPair *)\n\nFrom CoLoR Require Import ARedPair ARelation RelUtil BoolUtil.\n\nModule WP_RPO (Import P : PRECEDENCE) <: WeakRedPair.\n\n  Definition Prec := Precedence status prec_nat prec_eq_status.\n\n  Module S. Definition Sig := Sig. End S.\n\n  Module Import Term := Make_Term S.\n\n  Module Import Rpo := rpo.Make Term.\n\n  Notation rpo := (rpo Prec P.bb).\n\n  Definition Sig := Sig.\n  Definition succ := transp (Rof rpo term_of_aterm).\n\n  Import Inverse_Image.\n\n  Lemma wf_succ : WF succ.\n\n  Proof.\n    apply wf_WF_transp. apply wf_inverse_image with (f:=term_of_aterm).\n    apply wf_rpo. apply (prec_wf prec_nat).\n  Qed.\n\n  Import Max.\n\n  Lemma sc_succ : substitution_closed succ.\n\n  Proof.\n    intros t u s h. unfold succ, transp, Rof. set (k:=max(maxvar t)(maxvar u)).\n    rewrite term_of_aterm_sub with (k:=S k). 2: apply le_n_S; apply le_max_r.\n    rewrite term_of_aterm_sub with (k:=S k). 2: apply le_n_S; apply le_max_l.\n    apply rpo_subst. hyp.\n  Qed.\n\n  Notation empty_rpo_infos := (empty_rpo_infos Prec P.bb).\n  Notation rpo_eval := (rpo_eval empty_rpo_infos P.bb).\n  Notation rpo_eval_is_sound := (rpo_eval_is_sound_weak empty_rpo_infos P.bb).\n\n  Import ordered_set.\n\n  Definition bsucc t u :=\n    match rpo_eval (term_of_aterm t) (term_of_aterm u) with\n      | Some Greater_than => true\n      | _ => false\n    end.\n\n  Lemma bsucc_ok : forall t u, bsucc t u = true -> succ t u.\n\n  Proof.\n    intros t u. unfold bsucc.\n    gen (rpo_eval_is_sound (term_of_aterm t) (term_of_aterm u)).\n    case (rpo_eval (term_of_aterm t) (term_of_aterm u)); try discr.\n    destruct c; try discr. unfold succ, transp, Rof. auto.\n  Qed.\n\n  Lemma bsucc_sub : rel_of_bool bsucc << succ.\n\n  Proof. intros t u. unfold rel. intro h. apply bsucc_ok. hyp. Qed.\n\n  Definition equiv_aterm := Rof (equiv Prec) term_of_aterm.\n\n  Definition succeq := succ U equiv_aterm.\n\n  Lemma sc_succeq : substitution_closed succeq.\n\n  Proof.\n    intros t u s [h|h]. left. apply sc_succ. hyp. right.\n    unfold equiv_aterm, Rof. set (k := max (maxvar t) (maxvar u)).\n    rewrite term_of_aterm_sub with (k:=S k). 2: apply le_n_S; apply le_max_l.\n    rewrite term_of_aterm_sub with (k:=S k). 2: apply le_n_S; apply le_max_r.\n    apply equiv_subst. hyp.\n  Qed.\n\n  Lemma cc_succ : context_closed succ.\n\n  Proof.\n    intros t u c h. unfold succ, transp, Rof.\n    rewrite term_of_aterm_fill with (u := AVar 0) (t:=t),\n            term_of_aterm_fill with (u := AVar 0) (t:=u).\n    apply rpo_add_context. hyp. apply is_a_pos_context.\n  Qed.\n\n  Lemma cc_equiv_aterm : context_closed equiv_aterm.\n\n  Proof.\n    intros t u c h. unfold equiv_aterm, Rof.\n    rewrite term_of_aterm_fill with (u := AVar 0) (t:=t),\n            term_of_aterm_fill with (u := AVar 0) (t:=u).\n    apply equiv_add_context. hyp. apply is_a_pos_context.\n  Qed.\n\n  Lemma cc_succeq : context_closed succeq.\n\n  Proof.\n    intros t u c [h|h]. left. apply cc_succ. hyp.\n    right. apply cc_equiv_aterm. hyp.\n  Qed.\n\n  Lemma refl_succeq : reflexive succeq.\n\n  Proof.\n    intro t. right. apply Eq.\n  Qed.\n\n  Lemma succ_succeq_compat : absorbs_left succ succeq.\n\n  Proof.\n    intros t v [u [[h1|h1] h2]]. apply rpo_trans with (term_of_aterm u); hyp.\n    unfold succ, transp, Rof. rewrite equiv_rpo_equiv_1. apply h2. hyp.\n  Qed.\n\n  Definition bsucceq t u :=\n    match rpo_eval (term_of_aterm t) (term_of_aterm u) with\n      | Some Greater_than | Some Equivalent => true\n      | _ => false\n    end.\n\n  Lemma bsucceq_ok : forall t u, bsucceq t u = true -> succeq t u.\n\n  Proof.\n    intros t u. unfold bsucceq.\n    gen (rpo_eval_is_sound (term_of_aterm t) (term_of_aterm u)).\n    case (rpo_eval (term_of_aterm t) (term_of_aterm u)); try discr.\n    destruct c; try discr; unfold succeq, Relation_Operators.union,\n      equiv_aterm, succ, transp, Rof; auto.\n  Qed.\n\n  Definition bsucceq_sub : rel_of_bool bsucceq << succeq.\n\n  Proof. intros t u. unfold rel. intro h. apply bsucceq_ok. hyp. Qed.\n\n  Lemma trans_succ : transitive succ.\n\n  Proof.\n    unfold succ. apply transp_trans. apply Rof_trans.\n    intros t u v htu huv. apply rpo_trans with u; hyp.\n  Qed.\n\n  Lemma trans_equiv_aterm : transitive equiv_aterm.\n\n  Proof.\n    unfold equiv_aterm. apply Rof_trans.\n    apply (@RelationClasses.Equivalence_Transitive _ _ (equiv_equiv Prec)).\n  Qed.\n\n  Lemma trans_succeq : transitive succeq.\n\n  Proof.\n    unfold succeq, Relation_Operators.union, transitive. intuition.\n    left. apply trans_succ with y; hyp.\n    left. revert H. unfold equiv_aterm, succ, transp, Rof. intro.\n    rewrite <- equiv_rpo_equiv_2. apply H1. hyp.\n    left. revert H1. unfold equiv_aterm, succ, transp, Rof. intro.\n    rewrite equiv_rpo_equiv_1. apply H. hyp.\n    right. apply trans_equiv_aterm with y; hyp.\n  Qed.\n\nEnd WP_RPO.\n\n(***********************************************************************)\n(** decide compatibility of statuses wrt precedences *)\n\nDefinition beq_status s1 s2 :=\n  match s1, s2 with\n    | Lex, Lex\n    | Mul, Mul => true\n    | _, _ => false\n  end.\n\nLemma beq_status_ok : forall s1 s2, beq_status s1 s2 = true <-> s1 = s2.\n\nProof.\nbeq_symb_ok.\nQed.\n\nSection prec_eq_status.\n\n  Variables (Sig : Signature) (status : Sig -> status_type)\n    (prec_nat : Sig -> nat).\n\n  Lemma prec_eq_ok : forall f g,\n    prec_eq_bool prec_nat f g = true <-> prec_eq prec_nat f g.\n\n  Proof.\n    intros f g. gen (prec_eq_bool_ok prec_nat f g). intuition.\n    rewrite H1 in H. hyp. case_eq (prec_eq_bool prec_nat f g); intros.\n    refl. rewrite H2 in H. absurd (prec_eq prec_nat f g); hyp.\n  Qed.\n\n  Definition bprec_eq_status_symb f g :=\n    implb (prec_eq_bool prec_nat f g) (beq_status (status f) (status g)).\n\n  Lemma bprec_eq_status_symb_ok : forall f g,\n    bprec_eq_status_symb f g = true\n    <-> (prec_eq prec_nat f g -> status f = status g).\n\n  Proof.\n    intros f g. unfold bprec_eq_status_symb, implb.\n    case_eq (prec_eq_bool prec_nat f g); intros.\n    rewrite prec_eq_ok in H. rewrite beq_status_ok. intuition.\n    intuition. rewrite <- prec_eq_ok, H in H1. discr.\n  Qed.\n\n  Section bprec_eq_status_aux1.\n\n    Variable f : Sig.\n\n    Fixpoint bprec_eq_status_aux1 b gs :=\n      match gs with\n        | nil => b\n        | g :: gs' => bprec_eq_status_aux1 (b && bprec_eq_status_symb f g) gs'\n      end.\n\n    Lemma bprec_eq_status_aux1_true : forall gs b,\n      bprec_eq_status_aux1 b gs = true -> b = true.\n\n    Proof.\n      induction gs; simpl; intros. hyp.\n      cut (b && bprec_eq_status_symb f a = true). rewrite andb_eq. intuition.\n      apply IHgs. hyp.\n    Qed.\n\n    Arguments bprec_eq_status_aux1_true [gs b] _.\n\n    Lemma bprec_eq_status_aux1_ok : forall gs b,\n      bprec_eq_status_aux1 b gs = true ->\n      forall g, In g gs -> prec_eq prec_nat f g -> status f = status g.\n\n    Proof.\n      induction gs; simpl; intros. contr. destruct H0.\n      subst g. ded (bprec_eq_status_aux1_true H). rewrite andb_eq in H0.\n      destruct H0. rewrite bprec_eq_status_symb_ok in H2. intuition.\n      eapply IHgs. apply H. hyp. hyp.\n    Qed.\n\n  End bprec_eq_status_aux1.\n\n  Arguments bprec_eq_status_aux1_ok [f gs b] _ _ _ _.\n\n  Fixpoint bprec_eq_status_aux2 b fs :=\n    match fs with\n      | nil => b\n      | f :: fs' => bprec_eq_status_aux2 (bprec_eq_status_aux1 f b fs') fs'\n    end.\n\n  Lemma bprec_eq_status_aux2_true : forall fs b,\n    bprec_eq_status_aux2 b fs = true -> b = true.\n\n  Proof.\n    induction fs; simpl; intros. hyp. eapply bprec_eq_status_aux1_true.\n    apply IHfs. apply H.\n  Qed.\n\n  Arguments bprec_eq_status_aux2_true [fs b] _.\n\n  Lemma bprec_eq_status_aux2_ok : forall fs b,\n    bprec_eq_status_aux2 b fs = true -> forall f g, In f fs -> In g fs ->\n      prec_eq prec_nat f g -> status f = status g.\n\n  Proof.\n    induction fs; simpl; intros. contr. destruct H0; destruct H1.\n    subst f. subst g. refl.\n    subst f. ded (bprec_eq_status_aux2_true H).\n    apply (bprec_eq_status_aux1_ok H0); hyp.\n    subst g. ded (bprec_eq_status_aux2_true H).\n    sym. apply (bprec_eq_status_aux1_ok H1). hyp. apply prec_eq_sym. hyp.\n    eapply IHfs; ehyp.\n  Qed.\n  \n  Definition bprec_eq_status := bprec_eq_status_aux2 true.\n\n  Variable (Fs : list Sig) (Fs_ok : forall f, In f Fs).\n\n  Lemma bprec_eq_status_ok : bprec_eq_status Fs = true ->\n    forall f g, prec_eq prec_nat f g -> status f = status g.\n\n  Proof.\n    intros. eapply bprec_eq_status_aux2_ok. ehyp.\n    apply Fs_ok. apply Fs_ok. hyp.\n  Qed.\n\nEnd prec_eq_status.\n\nArguments bprec_eq_status_ok [Sig] _ _ [Fs] _ _ _ _ _.\n\nLtac prec_eq_status s p o := apply (bprec_eq_status_ok s p o); check_eq\n  || fail 10 \"statuses incompatible with precedences\".\n", "meta": {"author": "fblanqui", "repo": "color", "sha": "f2ef98f7d13c5d71dd2a614ed2e6721703a34532", "save_path": "github-repos/coq/fblanqui-color", "path": "github-repos/coq/fblanqui-color/color-f2ef98f7d13c5d71dd2a614ed2e6721703a34532/Conversion/Coccinelle.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2951926061713522}}
{"text": "Require Export PredMonad.Ordered4.Monad.\n\nImport OTNotations.\n\n\n(***\n *** Monads with State Effects\n ***)\n\n(* State effects = get and put *)\nClass MonadStateOps `(MOps:MonadOps) `(St:OType) : Type :=\n  {\n    getM : M @t@ St ;\n    putM : St -o> M @t@ OTunit\n  }.\n\nClass MonadState `{MonadStateOps} : Prop :=\n  {\n    monad_state_monad :> Monad MOps;\n\n    monad_state_get :\n      forall `{A:OType} (m : M @t@ A),\n        bindM @o@ getM @o@ (mkOTerm _ (fun _ => m)) =o= m ;\n\n    monad_state_get_put :\n      forall `{A:OType} (f : St -o> OTunit -o> M @t@ A),\n        bindM @o@ getM @o@\n              (mkOTerm (St -o> M @t@ A)\n                       (fun s => bindM @o@ (putM @o@ s) @o@ (f @o@ s)))\n        =o= bindM @o@ getM @o@\n                  (mkOTerm (St -o> M @t@ A) (fun s => f @o@ s @o@ tt)) ;\n\n    monad_state_put_get :\n      forall `{A:OType} s (f : OTunit -o> St -o> M @t@ A),\n        bindM @o@ (putM @o@ s) @o@\n              (mkOTerm (OTunit -o> M @t@ A) (fun u => bindM @o@ getM @o@ (f @o@ u)))\n        =o= bindM @o@ (putM @o@ s) @o@\n                  (mkOTerm (OTunit -o> M @t@ A) (fun u => f @o@ u @o@ s)) ;\n\n    monad_state_put_put :\n      forall `{A:OType} s1 s2 (f : OTunit -o> OTunit -o> M @t@ A),\n        bindM @o@ (putM @o@ s1) @o@\n              (mkOTerm (OTunit -o> M @t@ A)\n                       (fun u => bindM @o@ (putM @o@ s2) @o@ (f @o@ u)))\n        =o= bindM @o@ (putM @o@ s2) @o@ (f @o@ tt)\n  }.\n\n\n(***\n *** The State Monad Transformer\n ***)\n\nInstance StateT `(St:OType) `(MOps:MonadOps) :\n  OTypeF (fun `(A:OType) => Pfun St (M @t@ (St *o* A)))\n         (fun `(A:OType) => OTarrow_R St (M @t@ (St *o* A))) :=\n  fun `(A:OType) => St -o> M @t@ (St *o* A).\n\nSet Printing All.\nTypeclasses eauto := debug.\nInstance StateT_MonadOps `(St:OType) `(MOps:MonadOps) : MonadOps (StateT St MOps) :=\n  {returnM :=\n     fun `(A:OType) =>\n       mkOTerm (A -o> St -o> M @t@ (St *o* A))\n               (fun x s => returnM @o@ (s, x));\n   bindM :=\n     fun A B m f =>\n       fun s => do s_x <- m s; f (snd s_x) (fst s_x);\n   lrM := fun {A} _ => LR_Op_fun }.\n\n(* The Monad instance for StateT *)\nGlobal Instance StateT_Monad : Monad (StateT).\nProof.\n  constructor; intros; unfold StateT, returnM, bindM, lrM, StateT_MonadOps.\n  - auto with typeclass_instances.\n  - prove_lr_proper.\n  - prove_lr_proper.\n  - intros R1 R2 subR; apply LRFun_Proper_subrelation; apply monad_proper_lrM;\n      apply LRPair_Proper_subrelation; try assumption; reflexivity.\n  - prove_lr.\n  - transitivity (fun s => do s_x <- m s; returnM s_x).\n    + split; build_lr_fun; apply monad_proper_bind; prove_lr.\n    + prove_lr; autorewrite with LR; prove_lr.\n  - prove_lr.\nQed.\n\nGlobal Instance StateT_MonadStateOps : MonadStateOps S StateT :=\n  { getM := fun s => returnM (s, s)\n  ; putM := fun s _ => returnM (s, tt)\n  }.\n\nGlobal Instance StateT_MonadState : MonadState S StateT.\nProof.\n  constructor; intros;\n    unfold StateT, returnM, bindM, lrM, getM, putM,\n    StateT_MonadOps, StateT_MonadStateOps.\n  - auto with typeclass_instances.\n  - prove_lr_proper.\n  - prove_lr_proper.\n  - prove_lr.\n  - prove_lr.\n  - prove_lr.\n  - prove_lr.\nQed.\n\nEnd StateT.\n", "meta": {"author": "eddywestbrook", "repo": "predicate-monads", "sha": "2e4ac28d8f5e4b3080bdde5dafdb106c569197d4", "save_path": "github-repos/coq/eddywestbrook-predicate-monads", "path": "github-repos/coq/eddywestbrook-predicate-monads/predicate-monads-2e4ac28d8f5e4b3080bdde5dafdb106c569197d4/theories/archival/Ordered4/MonadState.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2951926061713521}}
{"text": "(**********************************************************************)\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 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(*                  LambdaFactor Calculus                             *)\n(*                                                                    *)\n(* is implemented in Coq by adapting the implementation of            *) \n(* Lambda Calculus  from Project Coq                                  *)\n(* 2015                                                               *)\n(**********************************************************************)\n\n(**********************************************************************)\n(*                           General.v                                *)\n(*                                                                    *)\n(*                          Barry Jay                                 *)\n(*                                                                    *)\n(**********************************************************************)\n\nRequire Import Omega.\nRequire Import ArithRing. \n\n(* some general-purpose tactics *) \n\nLtac eapply2 H := eapply H; eauto.\n\n\nLtac split_all := simpl; intros; \nmatch goal with \n| H : _ /\\ _ |- _ => inversion_clear H; split_all\n| H : if ?b then False else False |-_=> generalize H; clear H; case b; split_all\n| |- if ?b then True else True => case b; auto\n| H : false = true |-_=> inversion H\n| H : exists _, _ |- _ => inversion H; clear H; split_all \n| _ =>  try (split; split_all); try contradiction\nend; try congruence; auto.\n\nLtac noway := intros; assert False by omega; contradiction. \n\nLtac exist x := exists x; split_all. \n\nLtac gen_case H W := \n  generalize H; clear H; case W; split_all. \n\nLtac gen2_case H0 H1 W := \n  generalize H0 H1; clear H0 H1; case W; split_all.\n\nLtac gen3_case H0 H1 H2 W := \n  generalize H0 H1 H2; clear H0 H1 H2; case W; split_all.\n\nLtac gen4_case H0 H1 H2 H3 W := \n  generalize H0 H1 H2 H3; clear H0 H1 H2 H3; case W; split_all.\n\nLtac gen_inv H W := \n  generalize H; clear H; inversion W; split_all. \n\nLtac gen2_inv H0 H1 W := \n  generalize H0 H1; clear H0 H1; inversion W; split_all.\n\nLtac gen3_inv H0 H1 H2 W := \n  generalize H0 H1 H2; clear H0 H1 H2; inversion W; split_all.\n\nLtac gen4_inv H0 H1 H2 H3 W := \n  generalize H0 H1 H2 H3; clear H0 H1 H2 H3; inversion W; split_all.\n\n\nLtac gen_case_inv H M := gen_case H M; inversion H; auto.\n\nLtac invsub := match goal with | H : _ = _ |- _ => inversion H; subst; clear H; invsub | _ => split_all end. \n\n\n(* some arithmetic *) \n\nLtac dropS := \nmatch goal with \n| |- S ?m <= S?n => cut(m<= n); [split_all; omega |]  \n| |- S ?m < S?n => cut(m< n); [split_all; omega |] \n| |- S ?m >= S?n => cut(m>= n); [split_all; omega |]  \n| |- S ?m > S?n => cut(m> n); [split_all; omega |] \nend. \n\n\nLemma times_distributive : forall m n p, (m+n) * p = m*p + n * p. \nProof. split_all. ring. Qed. \n\nLemma times_distributive2 : \nforall m n p q, (m+n) * (p+q) = m*p + n * p + m*q + n*q. \nProof. split_all. ring. Qed. \n\nLemma times_positive: forall m n, m>0 -> n>0 -> m*n >0 . \nProof. \nsplit_all. gen_case H m; gen_case H0 n; split_all; try noway. \ncase (n1 + n0 * S n1); split_all; omega. \nQed. \n\n\n\nLemma  times_monotonic:  forall m1 m2 n1 n2, 0< m1 -> 0 < m2 -> m1 < n1 -> m2 < n2 -> m1 * m2 < n1 * n2. \nProof. \nsplit_all.  \nreplace n1 with (n1 - m1 + m1) by omega. \nreplace n2 with (n2 - m2 + m2) by omega. \nrewrite times_distributive2. \ncut(0 < (n1 - m1) * (n2 - m2) + m1 * (n2 - m2) + (n1 - m1) * m2). \nsplit_all; omega. \nreplace m1 with (1+ (pred m1)) by omega. \nreplace (n2 - m2) with (1+ (pred (n2 - m2))) by omega. \nrewrite times_distributive2. \nsimpl. \ncase((pred m1 * 1 + (pred (n2 - m2) + 0) + pred m1 * pred (n2 - m2))); \ncase((n1 - S (pred m1)) * S (pred (n2 - m2))); \ncase((n1 - S (pred m1)) * m2); split_all; omega. \nQed. \n\nLemma  times_monotonic2:  forall m1 m2 n1 n2, 0< m1 -> 0 < m2 -> m1 <= n1 -> m2 < n2 -> m1 * m2 < n1 * n2. \nProof. \nsplit_all.  \nreplace n1 with (n1 - m1 + m1) by omega. \nreplace n2 with (n2 - m2 + m2) by omega. \nrewrite times_distributive2. \nassert(0 < (n1 - m1) * (n2 - m2) + m1 * (n2 - m2) + (n1 - m1) * m2). \nreplace m1 with (1+ (pred m1)) by omega. \nreplace (n2 - m2) with (1+ (pred (n2 - m2))) by omega. \nrewrite times_distributive2. \nsimpl. \ncase((pred m1 * 1 + (pred (n2 - m2) + 0) + pred m1 * pred (n2 - m2))); \ncase((n1 - S (pred m1)) * S (pred (n2 - m2))); \ncase((n1 - S (pred m1)) * m2); split_all; omega. \ngen_case H3 ((n1 - m1) * (n2 - m2) + m1 * (n2 - m2) + (n1 - m1) * m2); split_all; try noway.  omega. \nQed. \n\n\nFixpoint exp (m n:nat) {struct n}: nat :=\nmatch n with\n| O => 1\n| S n => m * exp m n\nend.\n\nNotation \"x ^ y\" := (exp x y).\n\nLemma exp_positive: forall n m, m>0 -> exp m n >0 .\nProof. \ninduction n; split_all. \nassert(m^n >0) by eapply2 IHn.\neapply2 times_positive.  \nQed. \n\n\nLemma max_is_max : forall m n, max m n >= m /\\ max m n >= n.\nProof. \ndouble induction m n; split_all; try omega. \nelim (H0 n); split_all; omega. \nelim (H0 n); split_all; omega. \nQed. \n\n\nLemma max_succ: forall m n, S (max m n) = max (S m) (S n). \nProof. double induction m n; split_all.  Qed. \n\nLemma max_pred: forall m n, pred (max m n) = max (pred m) (pred n). \nProof. double induction m n; split_all. case n; split_all. Qed. \n\nLemma max_max : forall m n p, m >= max n p -> m>= n /\\ m>= p.\nProof. \ninduction m; intros n p. case n; case p; split_all; subst; try noway; try omega. \nintros. \nassert(m >= pred (max n p)) by omega. \nrewrite max_pred in H0. \nelim (IHm (pred n) (pred p)); split_all; omega. \nQed. \n\nLemma max_max2 : forall m n k, k>= m -> k>= n -> k>= max m n. \nProof. \ndouble induction m n; split_all. \nassert(pred k >= max n1 n) .  eapply2 H0. omega. omega. omega. \nQed. \n\nLemma max_zero : forall m, max m 0 = m. \nProof. induction m; split_all. Qed.\n\nLemma max_plus: forall m n k, max m n +k = max (m+k) (n+k). \nProof.\ndouble induction m n; split_all. \ninduction k; split_all.  \nassert(max k (S (n0+k)) >= S(n0+k)) by eapply2 max_is_max.  \nassert(S(n0+k) >= max k (S(n0+k))) . eapply2 max_max2. \nomega. \nomega. \ncase k; split_all. \nassert(max (n+S n1) n1 >= n+ S n1) by  eapply2 max_is_max.  \nassert(n+ S n1 >= max (n+S n1) n1) . eapply2 max_max2. \nomega. \nomega. \nQed. \n\nLemma max_minus: forall m n k, max m n -k = max (m-k) (n-k). \nProof.\ndouble induction m n; split_all.\ncase k; split_all. \nrewrite max_zero. omega.\ncase k; split_all. \nQed. \n\nLemma max_monotonic : forall m1 m2 n1 n2, m1 >= n1 -> m2 >= n2 -> max m1 m2 >= max n1 n2. \nProof. \ndouble induction m1 m2; split_all. \nassert (n1 = 0) by omega; subst. \nassert (n2 = 0) by omega; subst. \nsplit_all. \nassert (n1 = 0) by omega; subst. split_all. \nassert (n2 = 0) by omega; subst. \nassert(max n1 0 = n1) . case n1; split_all. \nrewrite H2; auto.  \nassert(n0 >= pred n1) by omega.\ncut(max n0 n >= pred (max n1 n2)).  \nintro.  \nomega. \nrewrite max_pred. \neapply2 H0. \nomega. \nQed. \n\nLemma max_succ_zero : forall k n, max k (S n) = 0 -> False .\nProof. split_all. assert(max k (S n) >= S n) by eapply2 max_is_max. noway. Qed. \nLtac max_out := \nmatch goal with \n| H : max _ (S _) = 0  |- _ => assert False by (eapply2 max_succ_zero); noway\n| H : max ?m ?n = 0 |- _ => \nassert (m = 0) by (assert (max m n >= m) by eapply2 max_is_max; omega);\nassert (n = 0) by (assert (max m n >= n) by eapply2 max_is_max; omega);\nclear H; try omega; try noway\n| H : max ?m ?n <= 0 |- _ => \nassert (m = 0) by (assert (max m n >= m) by eapply2 max_is_max; omega);\nassert (n = 0) by (assert (max m n >= n) by eapply2 max_is_max; omega);\nclear H; try omega; try noway\nend. \n\n\n\nLemma min_is_min : forall m n, min m n <= m /\\ min m n <= n.\nProof. \ndouble induction m n; split_all; try omega. \nelim (H0 n); split_all; omega. \nelim (H0 n); split_all; omega. \nQed. \n\n\nLemma min_succ: forall m n, S (min m n) = min (S m) (S n). \nProof. double induction m n; split_all.  Qed. \n\nLemma min_pred: forall m n, pred (min m n) = min (pred m) (pred n). \nProof. double induction m n; split_all. case n; split_all. Qed. \n\nLemma min_zero : forall m, min m 0 = 0. \nProof. induction m; split_all. Qed.\n\nLemma min_min : forall m n p, m <= min n p -> m<= n /\\ m<= p.\nProof. \ninduction m; split_all; try omega. \ngen_case H n; gen_case H p; try noway. \nassert(m<= min n0 n1) by omega. \nassert(m<= n0 /\\ m<= n1) by eapply2 IHm; split_all; omega. \ngen_case H p; try noway.\nrewrite min_zero in *. \nnoway. \nassert(m<= pred (min n (S n0))) by omega. \nrewrite min_pred in H0. \nsimpl in *. \nelim (IHm (pred n) n0); split_all. \nomega. \nQed. \n\nLemma min_min2 : forall m n k, k<= m -> k<= n -> k<= min m n. \nProof. \ndouble induction m n; split_all. \nassert(pred k <= min n1 n) .  eapply2 H0. omega. omega. omega. \nQed. \n\n\nLemma min_plus: forall m n k, min m n +k = min (m+k) (n+k). \nProof.\ndouble induction m n; split_all. \ninduction k; split_all.  \nassert(min k (S (n0+k)) <= k) by eapply2 min_is_min.  \nassert(k <= min k (S(n0+k))) . eapply2 min_min2. \nomega. \nomega. \ncase k; split_all. \nassert(min (n+S n1) n1 <= n1) by  eapply2 min_is_min.  \nassert(n1 <= min (n+S n1) n1) . eapply2 min_min2. \nomega. \nomega. \nQed. \n\nLemma min_minus: forall m n k, min m n -k = min (m-k) (n-k). \nProof.\ndouble induction m n; split_all.\ncase k; split_all. \nrewrite min_zero. omega.\ncase k; split_all. \nQed. \n\nLemma min_monotonic : forall m1 m2 n1 n2, m1 <= n1 -> m2 <= n2 -> min m1 m2 <= min n1 n2. \nProof. \ndouble induction m1 m2; split_all; try omega.\ngen_case H1 n1; try noway. \ngen_case H2 n2; try noway. \nassert(min n0 n <= min n3 n4). \neapply2 H0; try omega. \nomega. \nQed. \n\n\nLemma decidable_nats : forall (m n: nat), m=n \\/ m<>n. \nProof. \n double induction m n. \nleft; split_all. \nsplit_all; right; congruence. \nsplit_all; right; congruence. \nsplit_all. \nelim(H0 n); split_all. \nQed. \n\n", "meta": {"author": "Barry-Jay", "repo": "lambdaSF", "sha": "22a80d136e2986387e6c1e27b3872b39c974bcc1", "save_path": "github-repos/coq/Barry-Jay-lambdaSF", "path": "github-repos/coq/Barry-Jay-lambdaSF/lambdaSF-22a80d136e2986387e6c1e27b3872b39c974bcc1/General.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.2951926061713521}}
{"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.\nArguments gf : clear implicits.\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\nArguments paco3_acc            [ T0 T1 T2 ].\nArguments paco3_mon            [ T0 T1 T2 ].\nArguments paco3_mult_strong    [ T0 T1 T2 ].\nArguments paco3_mult           [ T0 T1 T2 ].\nArguments paco3_fold           [ T0 T1 T2 ].\nArguments 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.\nArguments gf_0 : clear implicits.\nArguments gf_1 : clear implicits.\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\nArguments paco3_2_0_acc            [ T0 T1 T2 ].\nArguments paco3_2_1_acc            [ T0 T1 T2 ].\nArguments paco3_2_0_mon            [ T0 T1 T2 ].\nArguments paco3_2_1_mon            [ T0 T1 T2 ].\nArguments paco3_2_0_mult_strong    [ T0 T1 T2 ].\nArguments paco3_2_1_mult_strong    [ T0 T1 T2 ].\nArguments paco3_2_0_mult           [ T0 T1 T2 ].\nArguments paco3_2_1_mult           [ T0 T1 T2 ].\nArguments paco3_2_0_fold           [ T0 T1 T2 ].\nArguments paco3_2_1_fold           [ T0 T1 T2 ].\nArguments paco3_2_0_unfold         [ T0 T1 T2 ].\nArguments 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.\nArguments gf_0 : clear implicits.\nArguments gf_1 : clear implicits.\nArguments gf_2 : clear implicits.\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\nArguments paco3_3_0_acc            [ T0 T1 T2 ].\nArguments paco3_3_1_acc            [ T0 T1 T2 ].\nArguments paco3_3_2_acc            [ T0 T1 T2 ].\nArguments paco3_3_0_mon            [ T0 T1 T2 ].\nArguments paco3_3_1_mon            [ T0 T1 T2 ].\nArguments paco3_3_2_mon            [ T0 T1 T2 ].\nArguments paco3_3_0_mult_strong    [ T0 T1 T2 ].\nArguments paco3_3_1_mult_strong    [ T0 T1 T2 ].\nArguments paco3_3_2_mult_strong    [ T0 T1 T2 ].\nArguments paco3_3_0_mult           [ T0 T1 T2 ].\nArguments paco3_3_1_mult           [ T0 T1 T2 ].\nArguments paco3_3_2_mult           [ T0 T1 T2 ].\nArguments paco3_3_0_fold           [ T0 T1 T2 ].\nArguments paco3_3_1_fold           [ T0 T1 T2 ].\nArguments paco3_3_2_fold           [ T0 T1 T2 ].\nArguments paco3_3_0_unfold         [ T0 T1 T2 ].\nArguments paco3_3_1_unfold         [ T0 T1 T2 ].\nArguments 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": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/concurrency/paco_old/src/paco3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.295059339335678}}
{"text": "(* Flat Combiner *)\nFrom iris.program_logic Require Export weakestpre.\nFrom iris.heap_lang Require Export lang.\nFrom iris.heap_lang Require Import proofmode notation.\nFrom iris.heap_lang.lib Require Import spin_lock.\nFrom iris.algebra Require Import auth frac agree excl agree gset gmap.\nFrom iris.base_logic Require Import big_op saved_prop.\nFrom iris_atomic Require Import misc peritem sync.\n\nDefinition doOp : val :=\n  λ: \"p\",\n     match: !\"p\" with\n       InjL \"req\" => \"p\" <- InjR ((Fst \"req\") (Snd \"req\"))\n     | InjR \"_\" => #()\n     end.\n\nDefinition try_srv : val :=\n  λ: \"lk\" \"s\",\n    if: try_acquire \"lk\"\n      then let: \"hd\" := !\"s\" in\n           iter \"hd\" doOp;;\n           release \"lk\"\n      else #().\n\nDefinition loop: val :=\n  rec: \"loop\" \"p\" \"s\" \"lk\" :=\n    match: !\"p\" with\n    InjL \"_\" =>\n        try_srv \"lk\" \"s\";;\n        \"loop\" \"p\" \"s\" \"lk\"\n    | InjR \"r\" => \"r\"\n    end.\n\nDefinition install : val :=\n  λ: \"f\" \"x\" \"s\",\n     let: \"p\" := ref (InjL (\"f\", \"x\")) in\n     push \"s\" \"p\";;\n     \"p\".\n\nDefinition mk_flat : val :=\n  λ: <>,\n   let: \"lk\" := newlock #() in\n   let: \"s\" := new_stack #() in\n   λ: \"f\" \"x\",\n      let: \"p\" := install \"f\" \"x\" \"s\" in\n      let: \"r\" := loop \"p\" \"s\" \"lk\" in\n      \"r\".\n\nDefinition reqR := prodR fracR (agreeR valC). (* request x should be kept same *)\nDefinition toks : Type := gname * gname * gname * gname * gname. (* a bunch of tokens to do state transition *)\nClass flatG Σ := FlatG {\n  req_G :> inG Σ reqR;\n  sp_G  :> savedPropG Σ (ofe_funCF val idCF)\n}.\n\nDefinition flatΣ : gFunctors :=\n  #[ GFunctor (constRF reqR);\n     savedPropΣ (ofe_funCF val idCF) ].\n\nInstance subG_flatΣ {Σ} : subG flatΣ Σ → flatG Σ.\nProof. intros [?%subG_inG [? _]%subG_inv]%subG_inv. split; apply _. Qed.\n\nSection proof.\n  Context `{!heapG Σ, !lockG Σ, !flatG Σ} (N: namespace).\n\n  Definition init_s (ts: toks) :=\n    let '(_, γ1, γ3, _, _) := ts in (own γ1 (Excl ()) ∗ own γ3 (Excl ()))%I.\n\n  Definition installed_s R (ts: toks) (f x: val) :=\n    let '(γx, γ1, _, γ4, γq) := ts in\n    (∃ (P: val → iProp Σ) Q,\n       own γx ((1/2)%Qp, to_agree x) ∗ P x ∗ ({{ R ∗ P x }} f x {{ v, R ∗ Q x v }}) ∗\n       saved_prop_own γq (Q x) ∗ own γ1 (Excl ()) ∗ own γ4 (Excl ()))%I.\n\n  Definition received_s (ts: toks) (x: val) γr :=\n    let '(γx, _, _, γ4, _) := ts in\n    (own γx ((1/2/2)%Qp, to_agree x) ∗ own γr (Excl ()) ∗ own γ4 (Excl ()))%I.\n\n  Definition finished_s (ts: toks) (x y: val) :=\n    let '(γx, γ1, _, γ4, γq) := ts in\n    (∃ Q: val → val → iProp Σ,\n       own γx ((1/2)%Qp, to_agree x) ∗ saved_prop_own γq (Q x) ∗\n       Q x y ∗ own γ1 (Excl ()) ∗ own γ4 (Excl ()))%I.\n  \n  Definition p_inv R (γm γr: gname) (ts: toks) (p : loc) :=\n    ( (* INIT *)\n      (∃ y: val, p ↦ InjRV y ∗ init_s ts) ∨\n      (* INSTALLED *)\n      (∃ f x: val, p ↦ InjLV (f, x) ∗ installed_s R ts f x) ∨\n      (* RECEIVED *)\n      (∃ f x: val, p ↦ InjLV (f, x) ∗ received_s ts x γr) ∨\n      (* FINISHED *)\n      (∃ x y: val, p ↦ InjRV y ∗ finished_s ts x y))%I.\n\n  Definition p_inv' R γm γr : val → iProp Σ :=\n    (λ v: val, ∃ ts (p: loc), ⌜v = #p⌝ ∗ inv N (p_inv R γm γr ts p))%I.\n\n  Definition srv_bag R γm γr s := (∃ xs, is_bag_R N (p_inv' R γm γr) xs s)%I.\n\n  Definition installed_recp (ts: toks) (x: val) (Q: val → iProp Σ) :=\n    let '(γx, _, γ3, _, γq) := ts in\n    (own γ3 (Excl ()) ∗ own γx ((1/2)%Qp, to_agree x) ∗ saved_prop_own γq Q)%I.\n\n  Lemma install_spec R P Q (f x: val) (γm γr: gname) (s: loc):\n    {{{ inv N (srv_bag R γm γr s) ∗ P ∗ ({{ R ∗ P }} f x {{ v, R ∗ Q v }}) }}}\n      install f x #s\n    {{{ p ts, RET #p; installed_recp ts x Q ∗ inv N (p_inv R γm γr ts p) }}}.\n  Proof.\n    iIntros (Φ) \"(#? & HP & Hf) HΦ\".\n    wp_seq. wp_let. wp_let. wp_alloc p as \"Hl\".\n    iApply fupd_wp.\n    iMod (own_alloc (Excl ())) as (γ1) \"Ho1\"; first done.\n    iMod (own_alloc (Excl ())) as (γ3) \"Ho3\"; first done.\n    iMod (own_alloc (Excl ())) as (γ4) \"Ho4\"; first done.\n    iMod (own_alloc (1%Qp, to_agree x)) as (γx) \"Hx\"; first done.\n    iMod (saved_prop_alloc (F:=(ofe_funCF val idCF)) Q) as (γq) \"#?\".\n    iDestruct (own_update with \"Hx\") as \">[Hx1 Hx2]\"; first by apply pair_l_frac_op_1'.\n    iModIntro. wp_let. wp_bind (push _ _).\n    iMod (inv_alloc N _ (p_inv R γm γr (γx, γ1, γ3, γ4, γq) p)\n          with \"[-HΦ Hx2 Ho3]\") as \"#HRx\"; first eauto.\n    { iNext. iRight. iLeft. iExists f, x. iFrame.\n      iExists (λ _, P), (λ _ v, Q v).\n      iFrame. iFrame \"#\". }\n    iApply (push_spec N (p_inv' R γm γr) s #p\n            with \"[-HΦ Hx2 Ho3]\")=>//.\n    { iFrame \"#\". iExists (γx, γ1, γ3, γ4, γq), p.\n      iSplitR; first done. iFrame \"#\". }\n    iNext. iIntros \"?\".\n    wp_seq. iApply (\"HΦ\" $! p (γx, γ1, γ3, γ4, γq)).\n    iFrame. iFrame \"#\".\n  Qed.\n\n  Lemma doOp_f_spec R γm γr (p: loc) ts:\n    f_spec N (p_inv R γm γr ts p) doOp (own γr (Excl ()) ∗ R)%I #p.\n  Proof.\n    iIntros (Φ) \"(#H1 & Hor & HR) HΦ\".\n    wp_rec. wp_bind (! _)%E.\n    iInv N as \"Hp\" \"Hclose\".\n    iDestruct \"Hp\" as \"[Hp | [Hp | [Hp | Hp]]]\"; subst.\n    - iDestruct \"Hp\" as (y) \"[>Hp Hts]\".\n      wp_load. iMod (\"Hclose\" with \"[-Hor HR HΦ]\").\n      { iNext. iFrame \"#\". iLeft. iExists y. iFrame. }\n      iModIntro. wp_match. iApply (\"HΦ\" with \"[Hor HR]\"). iFrame.\n    - destruct ts as [[[[γx γ1] γ3] γ4] γq].\n      iDestruct \"Hp\" as (f x) \"(>Hp & Hts)\".\n      iDestruct \"Hts\" as (P Q) \"(>Hx & Hpx & Hf' & HoQ & >Ho1 & >Ho4)\".\n      iAssert (|==> own γx (((1/2/2)%Qp, to_agree x) ⋅\n                            ((1/2/2)%Qp, to_agree x)))%I with \"[Hx]\" as \">[Hx1 Hx2]\".\n      { iDestruct (own_update with \"Hx\") as \"?\"; last by iAssumption.\n        rewrite -{1}(Qp_div_2 (1/2)%Qp).\n        by apply pair_l_frac_op'. }\n      wp_load. iMod (\"Hclose\" with \"[-Hf' Ho1 Hx2 HoQ HR HΦ Hpx]\").\n      { iNext. iFrame. iFrame \"#\". iRight. iRight. iLeft. iExists f, x. iFrame. }\n      iModIntro. wp_match. wp_proj. wp_proj.\n      wp_bind (f _). iApply wp_wand_r. iSplitL \"Hpx Hf' HR\".\n      { iApply \"Hf'\". iFrame. }\n      iIntros (v) \"[HR HQ]\". wp_value.\n      iInv N as \"Hx\" \"Hclose\".\n      iDestruct \"Hx\" as \"[Hp | [Hp | [Hp | Hp]]]\"; subst.\n      * iDestruct \"Hp\" as (?) \"(_ & >Ho1' & _)\".\n        iApply excl_falso. iFrame.\n      * iDestruct \"Hp\" as (? ?) \"[>? Hs]\". iDestruct \"Hs\" as (? ?) \"(_ & _ & _ & _ & >Ho1' & _)\".\n        iApply excl_falso. iFrame.\n      * iDestruct \"Hp\" as (? x5) \">(Hp & Hx & Hor & Ho4)\".\n        wp_store. iDestruct (m_frag_agree' with \"[Hx Hx2]\") as \"[Hx %]\"; first iFrame.\n        subst. rewrite Qp_div_2. iMod (\"Hclose\" with \"[-HR Hor HΦ]\").\n        { iNext. iDestruct \"Hp\" as \"[Hp1 Hp2]\". iRight. iRight.\n          iRight. iExists x5, v. iFrame. iExists Q. iFrame. }\n        iApply \"HΦ\". iFrame.\n      * iDestruct \"Hp\" as (? ?) \"[? Hs]\". iDestruct \"Hs\" as (?) \"(_ & _ & _ & >Ho1' & _)\".\n        iApply excl_falso. iFrame.\n    - destruct ts as [[[[γx γ1] γ3] γ4] γq]. iDestruct \"Hp\" as (? x) \"(_ & _ & >Ho2' & _)\".\n      iApply excl_falso. iFrame.\n    - destruct ts as [[[[γx γ1] γ3] γ4] γq]. iDestruct \"Hp\" as (x' y) \"[Hp Hs]\".\n        iDestruct \"Hs\" as (Q) \"(>Hx & HoQ & HQxy & >Ho1 & >Ho4)\".\n        wp_load. iMod (\"Hclose\" with \"[-HΦ HR Hor]\").\n        { iNext. iRight. iRight. iRight. iExists x', y. iFrame. iExists Q. iFrame. }\n        iModIntro. wp_match. iApply \"HΦ\". iFrame.\n  Qed.\n\n  Definition own_γ3 (ts: toks) := let '(_, _, γ3, _, _) := ts in own γ3 (Excl ()).\n  Definition finished_recp (ts: toks) (x y: val) :=\n    let '(γx, _, _, _, γq) := ts in\n    (∃ Q, own γx ((1 / 2)%Qp, to_agree x) ∗ saved_prop_own γq (Q x) ∗ Q x y)%I.\n\n  Lemma loop_iter_doOp_spec R (γm γr: gname) xs:\n  ∀ (hd: loc),\n    {{{ is_list_R N (p_inv' R γm γr) hd xs ∗ own γr (Excl ()) ∗ R }}}\n      iter #hd doOp\n    {{{ RET #(); own γr (Excl ()) ∗ R }}}.\n  Proof.\n    induction xs as [|x xs' IHxs].\n    - iIntros (hd Φ) \"[Hxs ?] HΦ\".\n      simpl. wp_rec. wp_value. wp_let.\n      iDestruct \"Hxs\" as (?) \"Hhd\".\n      wp_load. wp_match. by iApply \"HΦ\".\n    - iIntros (hd Φ) \"[Hxs HRf] HΦ\". simpl.\n      iDestruct \"Hxs\" as (hd' ?) \"(Hhd & #Hinv & Hxs')\".\n      wp_rec. wp_value. wp_let. wp_bind (! _)%E.\n      iInv N as \"H\" \"Hclose\".\n      iDestruct \"H\" as (ts p) \"[>% #?]\". subst.\n      wp_load. iMod (\"Hclose\" with \"[]\").\n      { iNext. iExists ts, p. eauto. }\n      iModIntro. wp_match. wp_proj. wp_bind (doOp _).\n      iDestruct (doOp_f_spec R γm γr p ts) as \"Hf\".\n      iApply (\"Hf\" with \"[HRf]\").\n      { iFrame. iFrame \"#\". }\n      iNext. iIntros \"HRf\".\n      wp_seq. wp_proj. iApply (IHxs with \"[-HΦ]\")=>//.\n      iFrame \"#\"; first by iFrame. eauto.\n  Qed.\n\n  Lemma try_srv_spec R (s: loc) (lk: val) (γr γm γlk: gname) Φ :\n    inv N (srv_bag R γm γr s) ∗\n    is_lock N γlk lk (own γr (Excl ()) ∗ R) ∗ Φ #()\n    ⊢ WP try_srv lk #s {{ Φ }}.\n  Proof.\n    iIntros \"(#? & #? & HΦ)\". wp_seq. wp_let.\n    wp_bind (try_acquire _). iApply (try_acquire_spec with \"[]\"); first done.\n    iNext. iIntros ([]); last by (iIntros; wp_if).\n    iIntros \"[Hlocked [Ho2 HR]]\".\n    wp_if. wp_bind (! _)%E.\n    iInv N as \"H\" \"Hclose\".\n    iDestruct \"H\" as (xs' hd') \"[>Hs Hxs]\".\n    wp_load. iDestruct (dup_is_list_R with \"[Hxs]\") as \">[Hxs1 Hxs2]\"; first by iFrame.\n    iMod (\"Hclose\" with \"[Hs Hxs1]\").\n    { iNext. iFrame. iExists xs', hd'. by iFrame. }\n    iModIntro. wp_let. wp_bind (iter _ _).\n    iApply wp_wand_r. iSplitL \"HR Ho2 Hxs2\".\n    { iApply (loop_iter_doOp_spec R _ _ _ _ (λ _, own γr (Excl ()) ∗ R)%I with \"[-]\")=>//.\n      iFrame \"#\". iFrame. eauto. }\n    iIntros (f') \"[Ho HR]\". wp_seq.\n    iApply (release_spec with \"[Hlocked Ho HR]\"); first iFrame \"#∗\".\n    iNext. iIntros. done.\n  Qed.\n\n  Lemma loop_spec R (p s: loc) (lk: val)\n        (γs γr γm γlk: gname) (ts: toks):\n    {{{ inv N (srv_bag R γm γr s) ∗ inv N (p_inv R γm γr ts p) ∗\n        is_lock N γlk lk (own γr (Excl ()) ∗ R) ∗ own_γ3 ts }}}\n      loop #p #s lk\n    {{{ x y, RET y; finished_recp ts x y }}}.\n  Proof.\n    iIntros (Φ) \"(#? & #? & #? & Ho3) HΦ\".\n    iLöb as \"IH\". wp_rec. repeat wp_let.\n    wp_bind (! _)%E. iInv N as \"Hp\" \"Hclose\".\n    destruct ts as [[[[γx γ1] γ3] γ4] γq].\n    iDestruct \"Hp\" as \"[Hp | [Hp | [ Hp | Hp]]]\".\n    + iDestruct \"Hp\" as (?) \"(_ & _ & >Ho3')\".\n      iApply excl_falso. iFrame.\n    + iDestruct \"Hp\" as (f x) \"(>Hp & Hs')\".\n      wp_load. iMod (\"Hclose\" with \"[Hp Hs']\").\n      { iNext. iFrame. iRight. iLeft. iExists f, x. iFrame. }\n      iModIntro. wp_match. wp_bind (try_srv _ _). iApply try_srv_spec=>//.\n      iFrame \"#\". wp_seq. iApply (\"IH\" with \"Ho3\"); eauto.\n    + iDestruct \"Hp\" as (f x) \"(Hp & Hx & Ho2 & Ho4)\".\n      wp_load. iMod (\"Hclose\" with \"[-Ho3 HΦ]\").\n      { iNext. iFrame. iRight. iRight. iLeft. iExists f, x. iFrame. }\n      iModIntro. wp_match.\n      wp_bind (try_srv _ _). iApply try_srv_spec=>//.\n      iFrame \"#\". wp_seq. iApply (\"IH\" with \"Ho3\"); eauto.\n    + iDestruct \"Hp\" as (x y) \"[>Hp Hs']\".\n      iDestruct \"Hs'\" as (Q) \"(>Hx & HoQ & HQ & >Ho1 & >Ho4)\".\n      wp_load. iMod (\"Hclose\" with \"[-Ho4 HΦ Hx HoQ HQ]\").\n      { iNext. iFrame. iLeft. iExists y. iFrame. }\n      iModIntro. wp_match. iApply (\"HΦ\" with \"[-]\"). iFrame.\n      iExists Q. iFrame.\n  Qed.\n\n  Lemma mk_flat_spec (γm: gname): mk_syncer_spec mk_flat.\n  Proof.\n    iIntros (R Φ) \"HR HΦ\".\n    iMod (own_alloc (Excl ())) as (γr) \"Ho2\"; first done.\n    wp_seq. wp_bind (newlock _).\n    iApply (newlock_spec _ (own γr (Excl ()) ∗ R)%I with \"[$Ho2 $HR]\")=>//.\n    iNext. iIntros (lk γlk) \"#Hlk\".\n    wp_let. wp_bind (new_stack _).\n    iApply (new_bag_spec N (p_inv' R γm γr))=>//.\n    iNext. iIntros (s) \"#Hss\".\n    wp_let. iApply \"HΦ\". rewrite /synced.\n    iAlways. iIntros (f). wp_let. iAlways.\n    iIntros (P Q x) \"#Hf\".\n    iIntros \"!# Hp\". wp_let. wp_bind (install _ _ _).\n    iApply (install_spec R P Q f x γm γr s with \"[-]\")=>//.\n    { iFrame. iFrame \"#\". eauto. }\n    iNext. iIntros (p [[[[γx γ1] γ3] γ4] γq]) \"[(Ho3 & Hx & HoQ) #?]\".\n    wp_let. wp_bind (loop _ _ _).\n    iApply (loop_spec with \"[-Hx HoQ]\")=>//.\n    { iFrame \"#\". iFrame. }\n    iNext. iIntros (? ?) \"Hs\".\n    iDestruct \"Hs\" as (Q') \"(Hx' & HoQ' & HQ')\".\n    destruct (decide (x = a)) as [->|Hneq].\n    - iDestruct (saved_prop_agree with \"[HoQ HoQ']\") as \"Heq\"; first by iFrame.\n      wp_let. iDestruct (uPred.cofe_funC_equivI with \"Heq\") as \"Heq\".\n      iSpecialize (\"Heq\" $! a0). by iRewrite \"Heq\" in \"HQ'\".\n    - iExFalso. iCombine \"Hx\" \"Hx'\" as \"Hx\".\n      iDestruct (own_valid with \"Hx\") as %[_ H1].\n      rewrite pair_op //=  in H1=>//. apply to_agree_comp_valid in H1.\n      fold_leibniz. done.\n  Qed.\n\nEnd proof.\n", "meta": {"author": "izgzhen", "repo": "iris-atomic", "sha": "0a1c826e3860fc18c0b8b5a785c93b345eebfe35", "save_path": "github-repos/coq/izgzhen-iris-atomic", "path": "github-repos/coq/izgzhen-iris-atomic/iris-atomic-0a1c826e3860fc18c0b8b5a785c93b345eebfe35/theories/flat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2948981631986741}}
{"text": "(** * Sum (coproduct) algebraic CPO. *)\n\nSet Implicit Arguments.\nSet Contextual Implicit.\n\nFrom Coq Require Import\n  Basics\n  Equivalence\n  Lia\n  Morphisms\n  Equality\n  List\n  Nat\n.\nLocal Open Scope program_scope.\nLocal Open Scope equiv_scope.\nImport ListNotations.\n\nFrom Coq Require Import\n  Reals\n  Raxioms\n  Rpower\n  FunctionalExtensionality\n  ClassicalChoice\n.\n\nFrom algco Require Import aCPO axioms conat cpo eR misc order tactics.\n\nLocal Open Scope order_scope.\n\nCreate HintDb sum.\n\n#[global]\n  Instance Compact_sum {A B} `{Compact A} `{Compact B} : Compact (A + B).\nProof.\n  constructor.\n  intros [a | b].\n  - intros f Hf Hsup.\n    destruct H0.\n    set (f' := fun i => match f i with\n                     | inl x => x\n                     | inr _ => a\n                     end).\n    assert (Hf': directed f').\n    { intros i j; specialize (Hf i j); destruct Hf as [k [Hk Hk']].\n      unfold f'.\n      exists k.\n      destruct (f k).\n      2: { assert (f i ⊑ inl a) by apply Hsup.\n           destruct (f i).\n           - inv Hk.\n           - inv H0. }\n      destruct (f i).\n      2: { inv Hk. }\n      destruct (f j).\n      2: { inv Hk'. }\n      split; auto. }\n    specialize (compact_spec a f' Hf' (inl_supremum _ _ Hsup)).\n    destruct compact_spec as [i Hi].\n    unfold f' in Hi.\n    exists i.\n    destruct (f i) eqn:Hfi; subst; auto.\n    assert (HC: inr b ⊑ inl a).\n    { rewrite <- Hfi; apply Hsup. }\n    inv HC.\n  - intros f Hf Hsup.\n    destruct H2.\n    set (f' := fun i => match f i with\n                     | inl _ => b\n                     | inr y => y\n                     end).\n    assert (Hf': directed f').\n    { intros i j; specialize (Hf i j); destruct Hf as [k [Hk Hk']].\n      unfold f'.\n      exists k.\n      destruct (f k).\n      { assert (f i ⊑ inr b) by apply Hsup.\n        destruct (f i).\n        - inv H2.\n        - inv Hk. }\n      destruct (f i).\n      { inv Hk. }\n      destruct (f j).\n      { inv Hk'. }\n      split; auto. }\n    specialize (compact_spec b f' Hf' (inr_supremum _ _ Hsup)).\n    destruct compact_spec as [i Hi].\n    unfold f' in Hi.\n    exists i.\n    destruct (f i) eqn:Hfi; subst; auto.\n    assert (HC: inl a ⊑ inr b).\n    { rewrite <- Hfi; apply Hsup. }\n    inv HC.\nQed.\n\nDefinition sum_incl {A bA B bB} (inclA : bA -> A) (inclB : bB -> B) (x : bA + bB) : A + B :=\n  match x with\n  | inl a => inl (inclA a)\n  | inr b => inr (inclB b)\n  end.\n\nDefinition sum_ideal {A bA B bB} (idealA : A -> nat -> bA) (idealB : B -> nat -> bB)\n  (x : A + B) (i : nat) : bA + bB :=\n  match x with\n  | inl a => inl (idealA a i)\n  | inr b => inr (idealB b i)\n  end.\n\n#[global]\n Instance Dense_sum {A bA B bB} `{Dense A bA} `{Dense B bB} : Dense (A + B) (bA + bB) :=\n  { incl := sum_incl incl incl\n  ; ideal := sum_ideal ideal ideal }.\n\n#[global]\n  Instance aCPO_sum {A bA B bB} `{aCPO A bA} `{aCPO B bB} : aCPO (A + B) (bA + bB).\nProof.\n  constructor; simpl.\n  - intros [a|b] [a'|b']; split; try intros [].\n    + destruct H; apply incl_order.\n    + destruct H; apply incl_order.\n    + destruct H0; apply incl_order.\n    + destruct H0; apply incl_order.\n  - intros [a|b].\n    + destruct H; apply chain_ideal.\n    + destruct H0; apply chain_ideal.\n  - intros [a|b] [a'|b']; try intros [].\n    + destruct H; apply monotone_ideal.\n    + destruct H0; apply monotone_ideal.\n  - unfold flip; intros i ch Hch [a|b] Hsup; simpl.\n    + destruct H.\n      specialize (continuous_ideal i).\n      simpl in continuous_ideal; unfold flip in continuous_ideal.\n      set (ch' := fun i => match ch i with\n                       | inl x => x\n                       | inr _ => a\n                       end).\n      assert (Hch': directed ch').\n      { intros n m; specialize (Hch n m); destruct Hch as [k [Hk Hk']].\n        unfold ch'.\n        exists k.\n        destruct (ch k).\n        2: { assert (ch n ⊑ inl a) by apply Hsup.\n             destruct (ch n).\n             - inv Hk.\n             - inv H. }\n        destruct (ch n).\n        2: { inv Hk. }\n        destruct (ch m).\n        2: { inv Hk'. }\n        split; auto. }\n      specialize (continuous_ideal ch' Hch' a (inl_supremum _ _ Hsup)).\n      split.\n      * intro j; simpl; unfold compose.\n        unfold sum_le.\n        destruct (ch j) eqn:Hchj; simpl.\n        2: { assert (HC: inr b ⊑ inl a).\n             { rewrite <- Hchj; apply Hsup. }\n             inv HC. }\n        apply monotone_ideal.\n        assert (Heq: @inl A B a0 ⊑ inl a).\n        { rewrite <- Hchj; apply Hsup. }\n        apply Heq.\n      * intros [a'|b'] Hub.\n        { simpl; unfold sum_le.\n          eapply continuous_ideal.\n          intro j; unfold compose.\n          specialize (Hub j); unfold compose in Hub.\n          unfold ch'.\n          destruct (ch j) eqn:Hchj.\n          2: { assert (HC: inr b ⊑ inl a).\n               { rewrite <- Hchj; apply Hsup. }\n               inv HC. }\n          rewrite <- Hchj in Hub.\n          simpl in Hub.\n          unfold sum_le in Hub.\n          rewrite Hchj in Hub; apply Hub. }\n        { unfold compose, sum_ideal in Hub.\n          specialize (Hub O); simpl in Hub.\n          destruct (ch O) eqn:HchO.\n          { destruct Hub. }\n          assert (HC: inr b ⊑ inl a).\n          { rewrite <- HchO; apply Hsup. }\n          inv HC. }\n    + destruct H0.\n      specialize (continuous_ideal i).\n      simpl in continuous_ideal; unfold flip in continuous_ideal.\n      set (ch' := fun i => match ch i with\n                       | inl _ => b\n                       | inr y => y\n                       end).\n      assert (Hch': directed ch').\n      { intros n m; specialize (Hch n m); destruct Hch as [k [Hk Hk']].\n        unfold ch'.\n        exists k.\n        destruct (ch k).\n        { assert (ch n ⊑ inr b) by apply Hsup.\n          destruct (ch n).\n          - inv H0.\n          - inv Hk. }\n        destruct (ch n).\n        { inv Hk. }\n        destruct (ch m).\n        { inv Hk'. }\n        split; auto. }\n      specialize (continuous_ideal ch' Hch' b (inr_supremum _ _ Hsup)).\n      split.\n      * intro j; simpl; unfold compose.\n        unfold sum_le.\n        destruct (ch j) eqn:Hchj; simpl.\n        { assert (HC: inl a ⊑ inr b).\n          { rewrite <- Hchj; apply Hsup. }\n          inv HC. }\n        apply monotone_ideal.\n        assert (Heq: @inr A B b0 ⊑ inr b).\n        { rewrite <- Hchj; apply Hsup. }\n        apply Heq.\n      * intros [a'|b'] Hub.\n        { unfold compose, sum_ideal in Hub.\n          specialize (Hub O); simpl in Hub.\n          destruct (ch O) eqn:HchO.\n          2: { destruct Hub. }\n          assert (HC: inl a ⊑ inr b).\n          { rewrite <- HchO; apply Hsup. }\n          inv HC. }\n        { simpl; unfold sum_le.\n          eapply continuous_ideal.\n          intro j; unfold compose.\n          specialize (Hub j); unfold compose in Hub.\n          unfold ch'.\n          destruct (ch j) eqn:Hchj.\n          { assert (HC: inl a ⊑ inr b).\n            { rewrite <- Hchj; apply Hsup. }\n            inv HC. }\n          rewrite <- Hchj in Hub.\n          simpl in Hub.\n          unfold sum_le in Hub.\n          rewrite Hchj in Hub; apply Hub. }\n  - intros [a|b].\n    + apply supremum_inl.\n      destruct H; eauto.\n    + apply supremum_inr.\n      destruct H0; eauto.\nQed.\n", "meta": {"author": "bagnalla", "repo": "algco", "sha": "433836e4a0743c0443d530913769a00549b6993a", "save_path": "github-repos/coq/bagnalla-algco", "path": "github-repos/coq/bagnalla-algco/algco-433836e4a0743c0443d530913769a00549b6993a/sum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2948898932605641}}
{"text": "(*\n  Implementation based on Egg: https://dl.acm.org/doi/pdf/10.1145/3434304\n *)\nSet 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 Pyrosome.Theory Require Import Core.\n(*Import Core.Notations.*)\n\n\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   Big TODO:\n   Do I need to include the sorts in the terms?\n   reasons I currently include them:\n   1. so I can answer queries of the form \"What is the type of the term with id x\"\n   2. (intuitively) so that I can track conversions when destructing wf terms\n\n   For 1:\n   - Used for typechecking\n   - can be re-constituted by adding the sort from the node's term rule\n   - should just be a hashcons lookup, O(n). Worse than O(1), but probably fine\n\n   For 2:\n   If for each instance of a conversion, we add the lhs and rhs sorts \n   and rewrite until they are equal, then we should be able to produce a wfness proof\n   for any term in the egraph if we can prove 2 invariants:\n\n   (for sorts)\n   Invariant 1: let id1 <- add(t1); id2 <- add(t2). If id1 = id2 then c |- t1 = t2.\n\n   (for terms)\n   Invariant 2: If find(add(e1)) = find (add(e2)), c |- e1 : t1, and c |- e2 : t2, \n   then c |- t1 = t2 and c|- e1 = e2 : t1\n\n\n   *)\n  \n  Variant enode :=\n    | con_node : idx -> list idx -> enode\n    (*TODO: separate constructor for sorts?  | scon_node : list idx -> enode *)\n    | var_node : (*(* sort id*) idx ->*) (* var *) idx -> enode.\n\n  (* TODO: make sets fast*)\n\n  Fixpoint list_eqb {A} `{Eqb A} (l1 l2 : list A) :=\n    match l1, l2 with\n    | [], [] => true\n    | a1::l1, a2::l2 =>\n        (eqb a1 a2) && (list_eqb l1 l2)\n    | _, _ => false\n    end.\n\n  Axiom TODO: forall {A} , A.\n\n  (* TODO: move to Utils.v once implemented *)\n\n  #[refine] Instance list_Eqb {A} `{Eqb A} : Eqb (list A) :=\n    {\n      eqb := list_eqb\n    }.\n  all: apply TODO.\n  Defined.\n\n  #[refine] Instance enode_eqb : Eqb enode :=\n    {\n      eqb n1 n2 :=\n      match n1, n2 with\n      | var_node x, var_node y => eqb x y\n      | con_node n1 s1, con_node n2 s2 =>\n          (eqb n1 n2) && (eqb s1 s2)\n      | _,_=>false\n      end;\n    }.\n  all: apply TODO.\n  Defined.\n\n  Fixpoint named_list_put {A B} `{Eqb A} (l : @Utils.named_list A B) k v :=\n    match l with\n    | [] => [(k,v)]\n    | (k',v')::l =>\n        if eqb k k' then (k,v)::l else (k',v')::(named_list_put l k v)\n    end.\n\n  Fixpoint named_list_remove {A B} `{Eqb A} (l : @Utils.named_list A B) k :=\n    match l with\n    | [] => []\n    | (k',v')::l =>\n        if eqb k k' then l else (k',v')::(named_list_remove l k)\n    end.\n  \n  Section __.\n    (* Not fast, but will run*)\n    Local Instance named_list_map A B `{Eqb A} : map.map A B :=\n      {\n        rep := @Utils.named_list A B;\n        get := named_list_lookup_err;\n        empty := [];\n        put := named_list_put;\n        remove := named_list_remove;\n        fold _ f acc l := List.fold_left (fun acc '(k, v) => f acc k v) l acc;\n      }.\n  End __.\n\n  Definition node_set := set_from_map (@named_list_map enode unit _).\n  Definition node_map := (@named_list_map enode idx _).\n\n\n  (* TODO : separate sort eclasses? it would avoid awkwardness around esort dummy value\n   *)\n  Record eclass : Type :=\n    MkEClass {\n        nodes : node_set;\n        parents : node_map;\n        (* value is unused if the class represents a sort\n         TODO: is this the best way? could also fix it as 0\n        \n        esort : idx;*)\n      }.\n\n  Context (eclass_map : map.map idx eclass).\n\n  (*{idx_map : map.map idx idx}*)\n\n  (* Fix a specific context that the egraph is operating in.\n     This means that we can't reuse egraphs between rules\n     in a proof of compiler correctness,\n     but it is difficult to do so even when tracking multiple contexts.\n\n     On user programs this is generally the empty context.\n   *)\n  Record egraph :=\n    MkEGraph {\n        (* TODO: context sorts added to the egraph at initialization *)\n        ectx : named_list idx;\n        id_equiv : union_find;\n        eclasses : eclass_map;\n        hashcons : node_map;\n        worklist : list idx\n      }.\n\n\n  (*Definition union '(ns1,ps1) '(ns2,ps2) : t :=\n    (NodeSets.union ns1 ns2, (*TODO: need map union?*)map.union ps1 ps2).*)\n\n  Definition eclass_empty : eclass :=\n    MkEClass map.empty map.empty.\n\n  (* more common to call than empty *)\n  (* Assumes no parents *)\n  Definition eclass_singleton n : eclass := \n    MkEClass (map.singleton n tt) map.empty.\n\n  Definition eclass_add_parent '(MkEClass ns ps) '(pn,pi) : eclass :=\n    MkEClass ns (map.put ps pn pi).\n  \n  (*TODO: use coq-record-update? *)\n  Definition set_class_parents '(MkEClass ns _) ps :=\n    MkEClass ns ps.\n\n  Definition empty_egraph :=\n    MkEGraph [] UnionFind.empty map.empty map.empty [].\n  \n  \n  Section EGraphOps.\n    Import StateMonad.\n\n    Local Notation \"'ST'\" := (ST egraph).\n\n    Definition find a : ST idx :=\n      fun '(MkEGraph ctx U M H W) =>\n        let (U, i) := UnionFind.find U a in\n        (MkEGraph ctx U M H W,i).\n\n    Definition alloc : ST idx :=\n      fun '(MkEGraph ctx U M H W) =>\n        let (U, i) := UnionFind.alloc U in\n        (MkEGraph ctx U M H W,i).\n\n    Definition hashcons_lookup (n : enode) : ST (option idx) :=\n      fun g =>\n        let mi := map.get g.(hashcons) n in\n        (g, mi).\n\n    Definition set_hashcons n i : ST unit :=\n      fun '(MkEGraph ctx U M H W) =>\n        let H := map.put H n i in\n        (MkEGraph ctx U M H W,tt).\n    \n    Definition remove_hashcons n : ST unit :=\n      fun '(MkEGraph ctx U M H W) =>\n        let H := map.remove H n in\n        (MkEGraph ctx U M H W,tt).\n    \n    Definition set_eclass (i: idx) (c : eclass) : ST unit :=\n      fun '(MkEGraph ctx U M H W) =>\n        let M := map.put M i c in\n        (MkEGraph ctx U M H W,tt).\n\n    Definition union_ids a b : ST idx :=\n      fun '(MkEGraph ctx U M H W) =>\n        let (U, i) := UnionFind.union U a b in\n        (MkEGraph ctx U M H W, i).\n\n    (* return a default value rather than none\n     for ease-of-use\n     *)\n    Definition get_eclass (i : idx) : ST eclass :=\n      (*TODO: using a meaningless default here.\n      Decide if an option is better.\n      If I want empty as the default,\n      I need to decide that ctx and srt don't matter if empty,\n      which seems wrong\n       *)\n      fun g => (g, unwrap_with_default eclass_empty (map.get g.(eclasses) i)).\n\n    Definition add_to_worklist (i : idx) : ST unit :=\n      fun '(MkEGraph ctx U M H W) =>\n        let W := i::W in\n        (MkEGraph ctx U M H W, tt).\n\n    (* Returns the worklist for iteration and removes it from the egraph *)\n    Definition pull_worklist : ST (list idx) :=\n      fun '(MkEGraph ctx U M H W) =>\n        (MkEGraph ctx U M H [], W).\n\n    \n    (* Returns the egraph's context *)\n    Definition get_ectx : ST (named_list idx) :=\n      fun g => (g, g.(ectx)).\n    \n    Definition ectx_cons x (i: idx) : ST unit :=\n      fun '(MkEGraph ctx U M H W) =>\n        let ctx := (x,i)::ctx in\n        (MkEGraph ctx U M H W,tt).\n    \n    Definition is_worklist_empty : ST bool :=\n      fun g => (g, match g.(worklist) with [] => true | _ => false end).    \n\n    (*adds (n,p) as a parent to i*)\n    Definition add_parent n p i : ST unit :=\n      @! let ci <- get_eclass i in\n         (set_eclass i (eclass_add_parent ci (n,p))).\n    \n    Definition canonicalize n : ST enode :=\n      match n with     \n      | con_node name args =>\n          @! let args <- list_Mmap find args in       \n             ret con_node name args\n      | var_node x =>\n          @! ret var_node x\n      end.\n\n    \n    Definition eqb_ids a b : ST bool :=\n      @! let fa <- (find a) in\n         let fb <- (find b) in\n         ret eqb fa fb.\n\n    \n    Definition lookup n : ST (option idx) :=\n      @! let n <- canonicalize n in\n         (hashcons_lookup n).\n\n    Definition add_parent_to_children n i : ST unit :=\n      match n with\n      | con_node name args =>\n          @! let args <- list_Miter (add_parent n i) args in\n             ret tt\n      | var_node x => @! ret tt\n      end.\n\n    (*\n      Adds a node to the egraph without checking whether it is valid in the language\n     *)\n    Definition add_node_unchecked (n : enode) : ST idx :=\n      @! let mn <- lookup n in\n         match mn with\n         | Some i => @! ret i\n         | None => \n             @! let i <- alloc in\n                let tt <- set_eclass i (eclass_singleton n) in\n                let tt <- add_parent_to_children n i in\n                let tt <- set_hashcons n i in\n                ret i\n         end.\n\n    \n\n    Definition merge (a b : idx) : ST idx :=\n      @! let ca <- find a in\n         let cb <- find b in\n         if eqb ca cb\n         then ret ca\n         else let i <- union_ids a b in\n              let tt <- add_to_worklist i in\n              ret i.\n\n\n    (*TODO: think about parents wrt srt, ctx\n    if c |- e : t, then e is a parent of t\n    need to set those somewhere\n     *)\n    Definition repair (i : idx) : ST unit :=\n      @! let c <- get_eclass i in\n         let tt <- @! for pn pi from c.(parents) in\n         let tt <- remove_hashcons pn in\n         let pn <- canonicalize pn in\n         let ci <- find pi in\n         (set_hashcons pn ci) in\n           let new_parents <-\n                 @! for/fold pn pi\n                    from c.(parents)\n                             [[new_parents := (map.empty : node_map)]] in\n           let pn <- canonicalize pn in\n           match map.get new_parents pn : option idx return ST map.rep with\n             \n           | Some np => Mseq (merge pi np) (@! ret new_parents)\n           | None =>\n               @! let ci <- find pi in\n                  ret (map.put new_parents pn ci)\n           end in\n             (set_eclass i (set_class_parents c new_parents)).\n\n    Definition rebuild_aux : N -> ST unit :=\n      N.recursion\n        (Mret tt)\n        (fun _ rec =>\n           @! let (is_empty : bool) <- is_worklist_empty in\n              if is_empty then ret tt\n              else\n                let tt <- rec in\n                let W <- pull_worklist in\n                (*TODO: should worklist and/or cW be a set? Egg has a dedup step.\n                For now we are not deduplicating here, but we probably should at some poidx\n                 *)\n                let cW <- list_Mmap find W in\n                (list_Miter repair cW)).\n    \n    (* TODO: need to track  I = ~=\\=_node to use as fuel\n     *)\n    Definition rebuild : ST unit :=\n      @! let incong_bound := 100 in\n         (rebuild_aux 100).\n\n\n    Context (idx_set : set idx).\n\n    (*TODO: move to Utils once implemented *)\n    #[refine] Instance pair_Eqb {A} `{Eqb A} {B} `{Eqb B} : Eqb (A * B) :=\n      {\n        eqb '(a1,a2) '(b1,b2) := (eqb a1 b1) && (eqb a2 b2);\n      }.\n    all: apply TODO.\n    Defined.\n\n    Context (eqn_set : set (idx*idx)).\n    \n    Section WithLang.\n\n      Context (l : lang).\n\n\n      (*TODO: profile state monad and writer monad performance *)\n      Definition Checker A := ST (option (A * eqn_set)).\n      \n      (*TODO:\n          machinery for monad transformers?\n       *)\n      Instance state_monad : Monad Checker :=\n        {\n          Mret _ a := fun s => (s,Some (a,map.empty));\n          Mbind _ _ f ma :=\n          fun s =>\n            let (s,ma) := ma s in\n            match ma with\n            | Some (a,eqns) =>\n                let (s, ma) := f a s in\n                (s, option_map (pair_map_snd (union eqns)) ma)\n            | None => (s, None) end\n        }.\n\n      Definition require_equal p : Checker unit :=\n        Mret (M:=ST) (Some (tt, map.singleton p tt)).\n\n      Definition liftST {A} : ST A -> Checker A :=\n        Mfmap (fun a => Some (a,map.empty)).\n      Definition liftOpt {A} (ma : option A) : Checker A :=\n        Mret (M:=ST) (option_map (fun a => (a,map.empty)) ma).\n\n      Instance ST_default {A} `{WithDefault A} : WithDefault (ST A) :=\n        fun s => (s,default).\n      \n      \n      Section Inner.\n        Context (add_sort' : named_list (idx * idx) -> sort -> Checker idx).\n\n        (* breaks the term down into nodes, computes their sorts,\n         and adds them to the egraph.\n         Returns the top-level node's id and a set of all sort ids\n         that must be equated for the added term to typecheck.\n         Using a set takes advantage of subterm duplicaton to reduce\n         the number of generated goals.\n\n         Invariants:\n         If this returns Some v, then:\n         - The added term is well-scoped with respect to the egraph's context\n         - The added term's constructors are all term constructors of the language\n         - All constructors are used with the appropriate arity\n\n         Thus, if for all (i1, i2) in the eqn_set we have find i1 = find i2,\n         then the added term is well-typed.\n         *)\n        (*\n          TODO: make sort to be checked against an input, not an output?\n         *)\n        Section Inner2.\n          Context (add_term' : term -> Checker (idx * idx)).\n\n          (*TODO: return pair of lists or list of pairs?*)\n          Fixpoint add_args' (s : list term) (c : ctx) {struct s}\n            : Checker (list (idx * idx)) :=\n            match s, c with\n            | [],[] => @! ret []\n            | e::s, (_,t)::c =>\n                @! let sci <- add_args' s c in\n                   let (ei, ti) <- add_term' e in\n                   (* sort given by c *)\n                   let ti' <- add_sort' (with_names_from c sci) t in\n                   let tt <- require_equal (ti, ti') in\n                   ret (ei, ti)::sci\n            | _,_ => @! ret None\n            end.\n        End Inner2.\n\n        \n        (*  sub is a map from vars to id pairs with the egraph's ctx as its domain.\n            We need this argument for processing sorts from the language\n            \n            The range is pairs of (eid,tid) where eid is a term id and tid\n            is a sort id.\n         *)\n        Context (sub_and_ctx : named_list (idx * idx)).\n        \n        Fixpoint add_term' (e : term) {struct e} : Checker (idx * idx) :=\n          match e with\n          | var x =>\n              @! let x' <- liftST (add_node_unchecked (var_node x)) in\n                 (liftOpt (named_list_lookup_err sub_and_ctx x'))\n          | con n s =>\n              @! let term_rule c _ t <?- liftOpt (named_list_lookup_err l n) in\n                 let sci  <- add_args' add_term' s c in\n                 (* sort generated from sort of n rule *)\n                 let t_id <- add_sort' (with_names_from c sci) t in\n                 let i <- liftST (add_node_unchecked\n                                    (con_node n (map fst sci))) in\n                 ret (i,t_id)\n          end.\n      End Inner.\n\n      Let add_args'\n          (add_sort' : named_list (idx * idx) -> sort -> Checker idx)\n          (sub_and_ctx : named_list (idx * idx))\n        : list term -> ctx -> Checker (list (idx * idx)) :=\n            add_args' add_sort' (add_term' add_sort' sub_and_ctx).\n      \n      (*Use fuel here equal to the length of the language.\n        This is sufficient since the fuel is used when a term checks its sort,\n        given in either t or c of a rule c|- (n x...) : t\n        and all sorts must be defined before they are used.\n        \n        TODO: check that it's actually sufficient\n       *)\n      Fixpoint add_sort' (fuel : nat)\n               (sub_and_ctx : named_list (idx * idx))\n               (t : sort) : Checker idx :=\n        match fuel with\n        | O => @! ret None (* Hitting this case means the input was malformed *)\n        | S fuel' =>\n            match t with\n            | scon n s =>\n                @! let sort_rule c _ <?- liftOpt (named_list_lookup_err l n) in\n                   let sci  <- add_args' (add_sort' fuel') sub_and_ctx s c in\n                   let i <- liftST (add_node_unchecked\n                                      (con_node n (map fst sci))) in\n                   ret i\n            end            \n        end.\n\n      Fixpoint sub_and_ctx_from_ectx (acc : idx) (ectx : named_list idx)\n        : named_list (idx * idx) :=\n        match ectx with\n        | [] => []\n        | (x,ti)::ectx' =>\n            (x,(acc,ti))::(sub_and_ctx_from_ectx (succ acc) ectx')\n        end.\n      \n      Definition add_sort (t : sort) : Checker idx :=\n        @! let ectx <- liftST get_ectx in\n           (add_sort' (length l) (sub_and_ctx_from_ectx zero ectx) t).\n\n      Definition add_term (e : term) : Checker (idx*idx) :=\n        @! let ectx <- liftST get_ectx in\n           (add_term' (add_sort' (length l)) (sub_and_ctx_from_ectx zero ectx) e).\n\n      Fixpoint add_term_unchecked (e : term) {struct e} : ST idx :=\n        match e with\n        | var x => add_node_unchecked (var_node x)\n        | con n s =>\n            @! let si  <- list_Mmap add_term_unchecked s in\n               (add_node_unchecked (con_node n si))\n        end.\n      \n      Definition add_sort_unchecked (t: sort) : ST idx :=\n        match t with\n        | scon n s =>\n            @! let si  <- list_Mmap add_term_unchecked s in\n               (add_node_unchecked (con_node n si))\n        end.\n\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              (qt_nil : 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      Section UncheckedSub.\n        \n        Context (sub : arg_map).\n        \n        Fixpoint add_term_unchecked_sub (e : term) {struct e} : ST idx :=\n          match e with\n          | var x =>\n              @! ret unwrap_with_default default (map.get sub x)\n          | con n s =>\n              @! let si  <- list_Mmap add_term_unchecked_sub s in\n                 (add_node_unchecked (con_node n si))\n          end.\n        \n        Definition add_sort_unchecked_sub (t: sort) : ST idx :=\n          match t with\n          | scon n s =>\n              @! let si  <- list_Mmap add_term_unchecked_sub s in\n                 (add_node_unchecked (con_node n si))\n          end.\n\n      End UncheckedSub.\n\n      (*\n      Notes about the safety of adding unchecked nodes:\n      - If the node is wf, then it can be kept as-added\n        + Specifically, it can keep its sort since by proving it wf,\n          the egraph will unify its written sort with the other side of any\n          conversion in the wfness proof\n      - If the node is equated with another node, that means they have the same sort\n      Hope: If the node is not wf, then it cannot be equated with a wf node\n\n      If we take this as true, then consider the following algorithm:\n      - add all nodes/terms unchecked\n      - record (TODO: how) all equations that must be proven\n      - iterate to saturation (or step bound)\n      - check that all equations satisfy reflexivity\n       *)\n\n\n      Section EqualitySaturation.\n        Context {A} (update : A -> ST A) (pred : A -> bool).\n\n\n\n        Definition get_eclasses : ST eclass_map :=\n          fun g => (g, g.(eclasses)).\n\n\n        Definition db_append (m : db) x v :=\n          match map.get m x with\n          | None => map.put m x (map.singleton v tt)\n          | Some l => map.put m x (add_elt l v)\n          end.\n        \n        \n        Definition generate_db : ST db :=\n          @! let classes <- get_eclasses in\n             for/fold i cls from classes [[acc:=map.empty]] in\n               (* all nodes in a class have identical index up to find *)\n               let i' <- find i in\n               for/fold node _ from cls.(nodes) [[acc:=acc]] in\n                 match node with\n                 | con_node n s =>\n                     @!let s' : list idx <- list_Mmap find s in\n                       ret db_append acc n (i'::s')\n                 | var_node x =>\n                     (*TODO: how to index into DB for vars vs con?\n                       for now, require them to use disjoint names\n                       works, but feels awkward and causes issues later\n\n                       The best thing would be to index based off of\n                       bool * positive rather than positive\n                      *)\n                     @! ret db_append acc x [i]\n                        \n                 end.\n        \n        \n        (* returns (max_var, root, list of atoms)*)\n        Fixpoint compile_term_aux (max_var : idx) p : idx * idx * list (atom _) :=\n          match p with\n          | con f s =>\n              let '(max_var, s_vars, atoms) :=\n                fold_left (fun '(max_var, s_vars, atoms) p =>\n                             let '(max_var, x, atoms') :=\n                               compile_term_aux max_var p in\n                             (max_var,x::s_vars, atoms'++atoms))\n                          s\n                          (max_var, [], []) in\n              let x := succ max_var in\n              (x, x, (f,s_vars)::atoms)\n          | var x => (max_var, x, [])\n          end.\n\n        (* returns (max_var, root, list of atoms)*)\n        Definition compile_sort_aux (max_var : idx) p :=\n          match p with\n          | scon f s =>\n              let '(max_var, s_vars, atoms) :=\n                fold_left (fun '(max_var, s_vars, atoms) p =>\n                             let '(max_var, x, atoms') :=\n                               compile_term_aux max_var p in\n                             (max_var,x::s_vars, atoms'++atoms))\n                          s\n                          (max_var, [], []) in\n              let x := succ max_var in\n              (x, x, (f,s_vars)::atoms)\n          end.\n\n        (*TODO: move to natlike.v*)\n        Definition max {A} `{Natlike A} (a b : A) : A :=\n          if ltb b a then a else b.\n        \n        Definition compile_term_pattern (p : term) : query _ :=\n          (*TODO: remove duplicates in fv *)\n          let vars := fv p in\n          let max_var := fold_left max vars zero in\n          let '(_,root, atoms) := compile_term_aux max_var p in\n          Build_query _ (root::vars) atoms.\n        \n        Definition compile_sort_pattern (p : sort) : query _ :=\n          (*TODO: remove duplicates in fv *)\n          let vars := fv_sort p in\n          let max_var := fold_left max vars zero in\n          let '(_,root, atoms) := compile_sort_aux max_var p in\n          Build_query _ (root::vars) atoms.\n\n        Local Notation generic_join :=\n          (generic_join idx idx\n                        idx_set query_trie qt_unconstrained _ qt_tree qt_nil\n                        values_of_next_var choose_next_val relation db arg_map).\n        \n        Definition ematch (d : db) (p : term) :=\n          let q := compile_term_pattern p in\n          generic_join d q.\n        \n        Definition ematch_sort (d : db) (p : sort) :=\n          let q := compile_sort_pattern p in\n          generic_join d q.\n        \n\n        (*TODO: currently only rewrites left-to-right.\n        Evaluate whether this is sufficient.\n         *)\n        Definition try_rewrite (d : db) (r : rule) : ST unit :=\n          match r with\n          (* TODO: what to do with C? Needs to be used by ematch.\n\n           Consider heap lookup miss,\n           where a, inequality premise is not used in the equation.\n           How to handle this?\n           - implement pluggable term generators/deciders for specific sorts?\n           Hard to deal with; ignore for now?\n           How does egg deal with side conditions?\n\n           Vague idea: if using relational e-matching, turn C into part of the query.\n           \n\n           *)\n          | sort_eq_rule c t1 t2 =>\n              list_Miter (fun sub =>\n                            @! let cid <- add_sort_unchecked_sub sub t1 in\n                               let cid' <- add_sort_unchecked_sub sub t2 in\n                               let _ <- merge cid cid' in\n                               ret tt)\n                         (ematch_sort d t1)\n          | term_eq_rule c e1 e2 t =>\n              (* TODO: add_unchecked seems like it would expect the rhs to include sorts.\n               Do we need a lang with all-annotated terms?\n               \n               TODO: expose add_with_subst to use here\n               TODO: is it safe to add unchecked here?\n                     - means that there might be conversions in added term\n                       that are not represented in the egraph\n                     (only applies if sorts are removed from nodes)\n               *)\n              list_Miter (fun sub =>\n                            @! let cid <- add_term_unchecked_sub sub e1 in\n                               let cid' <- add_term_unchecked_sub sub e2 in\n                               let _ <- merge cid cid' in\n                               ret tt)\n                         (ematch d e1)\n          | _ => @!ret tt (* not a rewrite rule *)\n          end.\n        \n        (*\n      Iteratively applies rewrite rules to the egraph\n      until either:\n      - the egraph is saturated (*TODO: implement*)\n      - the accumulator satisfies the predicate\n      - the fuel runs out\n\n      TODO: encode the termination type in the output?\n      TODO: fuel : N\n         *)\n        Fixpoint equality_saturation (acc: A) (fuel : nat) : ST A :=\n          match fuel with\n          | O => @! ret acc\n          | S fuel' =>\n              if pred acc then @! ret acc\n              else\n                @! let db <- generate_db in\n                   (*TODO: filter lang once before this fixpoint starts *)\n                   (* Main rewrite loop\n                    Since DB is separate, we  don't have to separate reads and writes\n                    and still only need one rebuild\n                    *)\n                   let tt <- list_Miter (try_rewrite db) (map snd l) in\n                   let tt <- rebuild in\n                   let acc' <- update acc in\n                   (equality_saturation acc' fuel')\n          end.\n        \n      End EqualitySaturation.\n\n      (*TODO: move to Monad.v*)\n      \n      Definition map_Mandmap {K V}\n                 {MP : map.map K V}\n                 (f : K -> V -> ST bool)\n                 (p : @map.rep _ _ MP) : ST bool :=\n        map_Mfold (fun k v b => @! let b' <-  (f k v) in ret (andb b' b)) p true.\n\n      \n\n      Definition is_empty {A} := (existsb (A:=A) (fun _ => true)).\n      Definition is_empty_map {K V} {m : map.map K V} :=\n        (map.forallb (map:=m) (fun _ _ => false)).\n      \n      (* should be called under a try_with_backtrack?*)\n      Definition resolve_checker' {A} (c : Checker A)  (fuel : nat): ST (option A) :=\n        @! let meqns : (option (_ * eqn_set)) <- c in\n           match meqns with\n           | Some (a, eqns) =>\n               @! let eqns' : eqn_set <-\n                                equality_saturation\n                                  (fun eqns : eqn_set =>\n                                     map_Mfold (fun '(a,b) _ eqns =>\n                                                  (@! let a' <- find a in\n                                                      let b' <- find b in\n                                                      if eqb a' b' then ret eqns\n                                                      else ret add_elt eqns (a',b')))\n                                               eqns\n                                               map.empty)\n                                  (*Note: this is delicate since the map is non-canonical\n                            (e.g. when a |-> Empty)\n                                   *)\n                                  is_empty_map\n                                  eqns\n                                  fuel in\n                  ret if is_empty_map eqns' then Some a else None\n           | None => @! ret None\n           end.\n\n      Let fuel := 100%nat.\n      \n      Definition add_and_check_term (e : term) : ST (option (idx *idx)) :=\n        try_with_backtrack (resolve_checker' (add_term e) fuel).\n\n      (*TODO: should this check that x is fresh?*)\n      Definition add_and_check_ctx_cons x t : ST bool :=\n        @! let midx <- try_with_backtrack (resolve_checker' (add_sort t) fuel) in\n           match midx with\n           | Some idx =>\n               @! let x' <- add_node_unchecked (var_node x) in\n                  let _ <- ectx_cons x' idx in\n                  ret true\n           | None => @!ret false\n           end.\n\n      \n      (* assumes saturation *)\n      Definition saturated_compare_eq i1 i2 : ST bool :=\n        @! let ci1 <- find i1 in\n           let ci2 <- find i2 in\n           ret (eqb i1 i2).\n      \n\n      \n      Fixpoint check_ctx' (c : ctx) : option egraph :=\n        match c with\n        | [] => Some empty_egraph\n        | (x,t)::c =>\n            @! let ! compute_fresh x c in\n               let g <- check_ctx' c in\n               let (g',b) := add_and_check_ctx_cons x t g in\n               let ! b in\n               ret g'\n        end.\n\n      Definition check_ctx c := if check_ctx' c then true else false.\n      \n      \n    End WithLang.\n\n    \n    \n  End EGraphOps.\n\nEnd __.\n\nModule PositiveInstantiation.\n\n  Import RelationalDB.PositiveInstantiation.\n  \n  Definition eclass_map := TrieMap.map (@eclass positive _).\n\n  Definition idx_set := trie_set.\n\n  \n  (* TODO: make pair sets just like pair maps to avoid set_from_map*)\n  Instance eqn_set : set (positive*positive) :=\n    set_from_map (@pair_map _ _ _ trie_set (TrieMap.map _)).\n\n\n  From Named Require Import SimpleVSubst SimpleVSTLC.\n\n  (*TODO: move to Renaming.v*)\n  Section Renaming.\n    Context {A B : Type}\n            `{Eqb A}\n            `{Natlike B}.\n    Import StateMonad.\n\n    Definition fresh_stb : ST B B :=\n      fun b => (succ b, b).\n\n    Section WithConstrMap.\n      Context (constr_map : @Utils.named_list A B).\n\n      \n      Section WithVarMap.\n        Context (var_map : @Utils.named_list A B).\n\n        Fixpoint rename_term e :=\n          match e with\n          | var x => var (named_list_lookup default var_map x)\n          | con n s => con (named_list_lookup default constr_map n) (map rename_term s)\n          end.\n\n        Definition rename_sort t :=\n          match t with\n          | scon n s => scon (named_list_lookup default constr_map n) (map rename_term s)\n          end.\n\n      End WithVarMap.\n      \n      Definition fresh_stnlb : ST (@Utils.named_list A B * B) B :=\n        fun '(s,b) => (s,succ b, b).\n      \n      Definition get_var_map : ST (@Utils.named_list A B * B) _ :=\n        fun '(s,b) => (s,b, s).\n      \n      Definition set_var x xb : ST (@Utils.named_list A B * B) _ :=\n        fun '(s,b) => ((x,xb)::s,b, tt).\n      \n      Fixpoint auto_rename_ctx c : ST (@Utils.named_list A B * B) (Term.ctx B) :=\n        match c with\n        | [] => @!ret []\n        | (x,t)::c =>\n            @! let c' <- auto_rename_ctx c in\n               let var_map <- get_var_map in\n               let t' := rename_sort var_map t in\n               let xb <- fresh_stnlb in\n               let _ <- set_var x xb in\n               ret (xb,t')::c'\n        end.\n\n\n      Definition rename_args vs (args : list A) : list B :=\n        map (named_list_lookup default vs) args.\n      \n      Definition auto_rename_rule r fresh_id : _ * Rule.rule _ :=\n        match r with\n        | sort_rule c args =>\n            let '(vs, fresh_id', c') := auto_rename_ctx c ([],fresh_id) in\n            let args' := rename_args vs args in\n            (fresh_id', sort_rule c' args')\n        | term_rule c args t =>\n            let '(vs, fresh_id', c') := auto_rename_ctx c ([],fresh_id) in\n            let args' := rename_args vs args in\n            let t' := rename_sort vs t in\n            (fresh_id', term_rule c' args' t')\n        | sort_eq_rule c t1 t2 =>\n            let '(vs, fresh_id', c') := auto_rename_ctx c ([],fresh_id) in\n            let t1' := rename_sort vs t1 in\n            let t2' := rename_sort vs t2 in\n            (fresh_id', sort_eq_rule c' t1' t2')\n        | term_eq_rule c e1 e2 t =>\n            let '(vs, fresh_id', c') := auto_rename_ctx c ([],fresh_id) in\n            let e1' := rename_term vs e1 in\n            let e2' := rename_term vs e2 in\n            let t' := rename_sort vs t in\n            (fresh_id', term_eq_rule c' e1' e2' t')\n        end.\n\n    End WithConstrMap.\n\n    \n    Definition get_constr_map : ST (@Utils.named_list A B * B) _ :=\n      fun '(s,b) => (s,b, s).\n    Definition set_constr x xb : ST (@Utils.named_list A B * B) _ :=\n      fun '(s,b) => ((x,xb)::s,b, tt).\n\n    Definition lift_auto_rename_rule r\n      : ST (@Utils.named_list A B * B) (Rule.rule _) :=\n      fun '(sb,fr) =>\n        let '(fr',r') := auto_rename_rule sb r fr in\n        (sb,fr',r').\n    \n    Fixpoint rename_lang_ext l : ST (@Utils.named_list A B * B) (Rule.lang _) :=\n      match l with\n      | [] => @!ret []\n      | (x,r)::l =>\n          @! let l' <- rename_lang_ext l in\n             let r' <- lift_auto_rename_rule r in\n             let x' <- fresh_stnlb in\n             let _ <- set_constr x x' in\n             ret (x',r')::l'\n      end.\n\n    Definition rename_lang (l : Rule.lang A) : Rule.lang _ :=\n      snd (rename_lang_ext l ([],zero)).\n\n    Definition rename_constr_subst (l : Rule.lang A) :=\n      fst (fst (rename_lang_ext l ([],zero))).\n\n    \n    Definition rename_ctx (constr_map : @Utils.named_list A B)\n               (ctx : Term.ctx _) fr :=\n      snd (auto_rename_ctx constr_map ctx ([],fr)).\n    \n  End Renaming.\n\n\n  Import Term.Notations.\n\n  Definition pos_value_subst : Rule.lang positive :=\n    Eval compute in (rename_lang value_subst).\n  (*TODO: are vars different?*)\n  Definition constr_rename : named_list positive :=\n    Eval compute in (rename_constr_subst value_subst).\n\n  Definition test_ctx :=\n    Eval compute in (rename_ctx constr_rename\n                                {{c \"G\" : #\"env\",\n                                      \"A\" : #\"ty\",\n                                        \"B\" : #\"ty\"}}\n                                100).\n\n  Definition check_ctx' l :=\n    check_ctx' (idx:=positive) (array := TrieMap.TrieArrayList.trie_array)\n               eclass_map eqn_set l\n               qt_unconstrained _ qt_tree qt_nil\n               values_of_next_var choose_next_val relation db arg_map.\n  \n  Definition add_and_check_term l :=\n    add_and_check_term (idx:=positive) (array := TrieMap.TrieArrayList.trie_array)\n                       (eclass_map:=eclass_map) eqn_set l\n                       qt_unconstrained _ qt_tree qt_nil\n                       values_of_next_var choose_next_val relation db arg_map.\n  \n  Definition add_term :=\n    add_term (idx:=positive) (array := TrieMap.TrieArrayList.trie_array)\n             (eclass_map:=eclass_map) eqn_set.\n  \n  Definition find :=\n    find (idx:=positive) (array := TrieMap.TrieArrayList.trie_array)\n             (eclass_map:=eclass_map).\n  \n  Definition initial_egraph :=\n    Eval compute in\n      (match check_ctx' pos_value_subst test_ctx with\n       | Some g => g\n       | None => empty_egraph _\n       end).\n\n  Definition test_ctx_var_map :=\n    [(\"B\", 102);(\"A\",101);(\"G\",100)].\n\n  Definition test_term :=\n    Eval compute in\n      (rename_term constr_rename test_ctx_var_map\n                   {{e #\"ext\" \"G\" \"G\"}}).\n\n  (*Print test_term.*)\n  (*TODO: should return none\n\n add_term eqns look right,\n but checking still passes. Why?\n   *)\n  Definition egraph1 :=\n    Eval compute in (fst (add_and_check_term\n                            pos_value_subst\n                            test_term\n                            initial_egraph)).\n  Eval compute in (add_term\n                     pos_value_subst\n                     test_term\n                     initial_egraph).\n\n\n  (*TODO: move to extramaps/Triemap *)\n  Definition as_list {A} :=\n    TrieMap.trie_fold (B:=A) (fun m k v => (k,v)::m) [].\n\n  (*Compute\n    (Utils.named_map as_list (as_list ( Canonical.PTree.Nodes\n                                          (Canonical.PTree.Node010\n                                             (Canonical.PTree.Nodes\n                                                (Canonical.PTree.Node011 tt\n                                                                         (Canonical.PTree.Node100 (Canonical.PTree.Node010 tt)))))))).*)\n\n\n  (*Testing running this on something more complicated*)\n\n\n  Definition term1 :=\n    Eval compute in\n      (rename_term constr_rename test_ctx_var_map\n                   {{e #\"cmp\" \"G1\" \"G2\" (#\"ext\" \"G3\" \"A\") \"f\" (#\"snoc\" \"G2\" \"G3\" \"A\" \"g\" \"v\")}}).\n\n  (*Print test_term.*) (*{{e #61 100 100}}*)\n  (*TODO: should return none\n\n add_term eqns look right,\n but checking still passes. Why?\n   *)\n    Eval compute in (add_term\n                            pos_value_subst\n                            test_term\n                            initial_egraph).\n  Definition egraph2 :=\n    Eval compute in (fst (add_and_check_term\n                            pos_value_subst\n                            test_term\n                            initial_egraph)).\n  (*Print egraph2.*)\n\nEnd PositiveInstantiation.\n\n\n\n\n\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/Defs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.2948898862989504}}
{"text": "From Coq Require Import ssreflect.\nFrom Equations Require Import Equations.\nFrom MetaCoq.Utils Require Import utils.\nFrom MetaCoq.PCUIC Require Import PCUICAst PCUICAstUtils PCUICTyping PCUICProgram.\n\nDefinition isConstruct t :=\n   match t with tConstruct _ _ _ => true | _ => false end.\n\n Definition isFix t :=\n  match t with tFix _ _ => true | _ => false end.\n\nDefinition isRel t :=\n    match t with tRel _ => true | _ => false end.\n\nSection expanded.\n\nVariable Σ : global_env.\n\nLocal Unset Elimination Schemes.\n\nInductive expanded (Γ : list nat) : term -> Prop :=\n| expanded_tRel (n : nat) m args : nth_error Γ n = Some m -> forall Hle : m <= #|args|, Forall (expanded Γ) args -> expanded Γ (mkApps (tRel n) args)\n| expanded_tVar (id : ident) : expanded Γ (tVar id)\n| expanded_tEvar (ev : nat) (args : list term) : Forall (expanded Γ) args -> expanded Γ (tEvar ev args)\n| expanded_tSort (s : Universe.t) : expanded Γ (tSort s)\n| expanded_tProd (na : aname) (ty : term) (body : term) : expanded Γ (tProd na ty body)\n| expanded_tLambda (na : aname) (ty : term) (body : term) : expanded (0 :: Γ) body -> expanded Γ (tLambda na ty body)\n| expanded_tLetIn (na : aname) (def : term) (def_ty : term) (body : term) : expanded Γ def -> expanded (0 :: Γ) body -> expanded Γ (tLetIn na def def_ty body)\n| expanded_mkApps (f : term) (args : list term) : ~ (isConstruct f || isFix f || isRel f) -> expanded Γ f -> Forall (expanded Γ) args -> expanded Γ (mkApps f args)\n| expanded_tConst (c : kername) (u : Instance.t) : expanded Γ (tConst c u)\n| expanded_tInd (ind : inductive) (u : Instance.t) : expanded Γ (tInd ind u)\n| expanded_tCase (ci : case_info) (type_info:predicate term)\n        (discr:term) (branches : list (branch term)) : expanded Γ discr ->\n        Forall (expanded Γ) type_info.(pparams) ->\n        Forall (fun br =>\n          ∥ All_fold (fun Δ d => ForOption (fun b => expanded (repeat 0 #|Δ| ++ repeat 0 #|type_info.(pparams)|) b) d.(decl_body)) br.(bcontext) ∥ /\\\n          expanded (repeat 0 #|br.(bcontext)| ++ Γ) br.(bbody)) branches ->\n        expanded Γ (tCase ci type_info discr branches)\n| expanded_tProj (proj : projection) (t : term) : expanded Γ t -> expanded Γ (tProj proj t)\n| expanded_tFix (mfix : mfixpoint term) (idx : nat) args d :\n  Forall (fun d => isLambda d.(dbody) /\\ let ctx := rev_map (fun  d => 1 + d.(rarg)) mfix in expanded (ctx ++ Γ) d.(dbody)) mfix ->\n  Forall (expanded Γ) args ->\n  args <> [] ->\n  nth_error mfix idx = Some d ->\n  #|args| > d.(rarg) ->\n  expanded Γ (mkApps (tFix mfix idx) args)\n| expanded_tCoFix (mfix : mfixpoint term) (idx : nat) :   Forall (fun d => expanded (repeat 0 #|mfix| ++ Γ) d.(dbody)) mfix -> expanded Γ (tCoFix mfix idx)\n| expanded_tConstruct_app ind c u mind idecl cdecl args :\n    declared_constructor Σ (ind, c) mind idecl cdecl ->\n    #|args| >= (ind_npars mind + context_assumptions (cstr_args cdecl)) ->\n    Forall (expanded Γ) args ->\n    expanded Γ (mkApps (tConstruct ind c u) args)\n| expanded_tPrim p : expanded Γ (tPrim p).\n\nEnd expanded.\nDerive Signature for expanded.\n\nDefinition expanded_context Σ Γ ctx :=\n  ∥ All_fold (fun Δ d => ForOption (expanded Σ (repeat 0 #|Δ| ++ Γ)) d.(decl_body)) ctx ∥.\n\nLemma expanded_ind :\n  forall (Σ : global_env) (P : list nat -> term -> Prop),\n  (forall (Γ : list nat) (n m : nat) (args : list term),\n  nth_error Γ n = Some m ->\n  m <= #|args| -> Forall (expanded Σ Γ) args -> Forall (P Γ) args -> P Γ (mkApps (tRel n) args)) ->\n  (forall (Γ : list nat) (id : ident), P Γ (tVar id)) ->\n  (forall (Γ : list nat) (ev : nat) (args : list term),\n  Forall (expanded Σ Γ) args -> Forall (P Γ) args -> P Γ (tEvar ev args)) ->\n  (forall (Γ : list nat) (s : Universe.t), P Γ (tSort s)) ->\n  (forall (Γ : list nat) (na : aname) (ty body : term), P Γ (tProd na ty body)) ->\n  (forall (Γ : list nat) (na : aname) (ty body : term),\n  expanded Σ (0 :: Γ) body -> P (0 :: Γ) body -> P Γ (tLambda na ty body)) ->\n  (forall (Γ : list nat) (na : aname) (def def_ty body : term),\n  expanded Σ Γ def ->\n  P Γ def ->\n  expanded Σ (0 :: Γ) body ->\n  P (0 :: Γ) body -> P Γ (tLetIn na def def_ty body)) ->\n  (forall (Γ : list nat) (f6 : term) (args : list term),\n  ~ (isConstruct f6 || isFix f6 || isRel f6) ->\n  expanded Σ Γ f6 ->\n  P Γ f6 -> Forall (expanded Σ Γ) args -> Forall (P Γ) args -> P Γ (mkApps f6 args)) ->\n  (forall (Γ : list nat) (c : kername) (u : Instance.t), P Γ (tConst c u)) ->\n  (forall (Γ : list nat) (ind : inductive) (u : Instance.t), P Γ (tInd ind u)) ->\n  (forall (Γ : list nat) (ci : case_info) (type_info : predicate term)\n    (discr : term) (branches : list (branch term)),\n  expanded Σ Γ discr ->\n  P Γ discr ->\n  Forall (expanded Σ Γ) type_info.(pparams) ->\n  Forall (P Γ) type_info.(pparams) ->\n  Forall\n    (fun br : branch term =>\n    expanded_context Σ (repeat 0 #|type_info.(pparams)|)  br.(bcontext) /\\\n    expanded Σ (repeat 0 #|bcontext br| ++ Γ) (bbody br)) branches ->\n    Forall\n    (fun br : branch term =>\n      ∥ All_fold (fun Δ d => ForOption (fun b => P (repeat 0 (#|Δ| + #|type_info.(pparams)|)) b) d.(decl_body)) br.(bcontext) ∥ /\\\n      P (repeat 0 #|bcontext br| ++ Γ) (bbody br)) branches ->\n      P Γ (tCase ci type_info discr branches)) ->\n  (forall (Γ : list nat) (proj : projection) (t : term),\n  expanded Σ Γ t -> P Γ t -> P Γ (tProj proj t)) ->\n  (forall (Γ : list nat) (mfix : mfixpoint term) (idx : nat)\n    (args : list term) (d : def term),\n  Forall\n    (fun d0 : def term =>\n      isLambda d0.(dbody) /\\ let ctx := rev_map (fun d1 : def term => 1 + rarg d1) mfix in\n      expanded Σ (ctx ++ Γ) (dbody d0)) mfix ->\n  Forall\n      (fun d0 : def term =>\n      let ctx := rev_map (fun d1 : def term => 1 + rarg d1) mfix in\n      P (ctx ++ Γ) (dbody d0)) mfix ->\n  Forall (expanded Σ Γ) args -> Forall (P Γ) args ->\n  args <> [] ->\n  nth_error mfix idx = Some d ->\n  #|args| > rarg d -> P Γ (mkApps (tFix mfix idx) args)) ->\n  (forall (Γ : list nat) (mfix : mfixpoint term) (idx : nat),\n  Forall (fun d : def term => expanded Σ (repeat 0 #|mfix| ++ Γ) (dbody d))\n    mfix ->  Forall (fun d : def term => P (repeat 0 #|mfix| ++ Γ) (dbody d))\n    mfix  -> P Γ (tCoFix mfix idx)) ->\n  (forall (Γ : list nat) (ind : inductive) (c : nat)\n    (u : Instance.t) (mind : mutual_inductive_body)\n    (idecl : one_inductive_body) (cdecl : constructor_body)\n    (args : list term),\n  declared_constructor Σ (ind, c) mind idecl cdecl ->\n  #|args| >= ind_npars mind + context_assumptions (cstr_args cdecl) ->\n  Forall (expanded Σ Γ) args -> Forall (P Γ) args -> P Γ (mkApps (tConstruct ind c u) args)) ->\n  (forall Γ p, P Γ (tPrim p)) ->\n  forall (Γ : list nat) (t : term), expanded Σ Γ t -> P Γ t.\nProof.\n  intros Σ P HRel HVar HEvar HSort HProd HLamdba HLetIn HApp HConst HInd HCase HProj HFix HCoFix HConstruct HPrim.\n  fix f 3.\n  intros Γ t Hexp.  destruct Hexp; eauto.\n  - eapply HRel; eauto. clear - f H0. induction H0; econstructor; eauto.\n  - eapply HEvar; eauto. clear - f H. induction H; econstructor; eauto.\n  - eapply HApp; eauto. clear - f H0. induction H0; econstructor; eauto.\n  - eapply HCase; eauto. induction H; econstructor; eauto.\n    clear -H1 f. induction H1; constructor; auto.\n    clear -H0 f.\n    revert H0. induction 1; constructor; auto.\n    split. destruct H as [[] ?]; constructor; auto.\n    clear -X f. induction X; constructor; auto. destruct p; constructor; auto.\n    apply f. rewrite repeat_app. exact H.\n    eapply f, H.\n  - assert (Forall (P Γ) args). { clear - H0 f. induction H0; econstructor; eauto. }\n    eapply HFix; eauto.\n    revert H. clear - f.\n    generalize mfix at 1 3. intros mfix0 H. induction H; econstructor; cbn in *; intuition eauto; split.\n  - eapply HCoFix; eauto.\n    revert H. clear - f.\n    generalize mfix at 1 3. intros mfix0 H.  induction H; econstructor; cbn in *; eauto; split.\n  - eapply HConstruct; eauto.\n    clear - H1 f. induction H1; econstructor; eauto.\nQed.\n\nFrom MetaCoq.PCUIC Require Import PCUICInductiveInversion PCUICLiftSubst PCUICSigmaCalculus.\n\nRecord expanded_constant_decl Σ (cb : constant_body) : Prop :=\n  { expanded_body : on_Some_or_None (expanded Σ []) cb.(cst_body); }.\n    (* expanded_type : expanded Σ [] cb.(Ast.Env.cst_type) }. *)\n\nRecord expanded_constructor_decl Σ mdecl cdecl :=\n  { expanded_cstr_args : expanded_context Σ (repeat 0 (#|mdecl.(ind_params)| + #|mdecl.(ind_bodies)|)) cdecl.(cstr_args) }.\n    (* expanded_cstr_indices : All (expanded Σ []) cdecl.(cstr_indices); *)\n    (* expanded_cstr_type : expanded Σ (repeat 0 #|mdecl.(ind_bodies)|) cdecl.(cstr_type) }. *)\n\nRecord expanded_inductive_decl Σ mdecl idecl :=\n  { (* expanded_ind_type : expanded Σ [] idecl.(ind_type); *)\n    expanded_ind_ctors : Forall (expanded_constructor_decl Σ mdecl) idecl.(ind_ctors) }.\n\nRecord expanded_minductive_decl Σ mdecl :=\n  { expanded_params : expanded_context Σ [] mdecl.(ind_params);\n    expanded_ind_bodies : Forall (expanded_inductive_decl Σ mdecl) mdecl.(ind_bodies) }.\n\nDefinition expanded_decl Σ d :=\n  match d with\n  | ConstantDecl cb => expanded_constant_decl Σ cb\n  | InductiveDecl idecl => expanded_minductive_decl Σ idecl\n  end.\n\nInductive expanded_global_declarations (univs : ContextSet.t) retro : forall (Σ : global_declarations), Prop :=\n| expanded_global_nil : expanded_global_declarations univs retro []\n| expanded_global_cons decl Σ : expanded_global_declarations univs retro Σ ->\n  expanded_decl {| universes := univs; declarations := Σ; retroknowledge := retro |} decl.2 ->\n  expanded_global_declarations univs retro (decl :: Σ).\n\nDefinition expanded_global_env (g : global_env) :=\n  expanded_global_declarations g.(universes) g.(retroknowledge) g.(declarations).\n\nDefinition expanded_pcuic_program (p : pcuic_program) :=\n  expanded_global_env p.1 /\\ expanded p.1 [] p.2.\n\n\nLemma All_tip {A} {P : A -> Type} {a : A} : P a <~> All P [a].\nProof. split; intros. repeat constructor; auto. now depelim X. Qed.\n\nLemma expanded_mkApps_expanded {Σ Γ f args} :\n  expanded Σ Γ f -> All (expanded Σ Γ) args ->\n  expanded Σ Γ (mkApps f args).\nProof.\n  intros.\n  destruct (isConstruct f || isFix f || isRel f) eqn:eqc.\n  destruct f => //.\n  - depelim H; solve_discr. eapply expanded_tRel; tea. cbn in Hle. lia. solve_all.\n    destruct args0 using rev_case; cbn in *; subst. cbn in H. congruence.\n    rewrite mkApps_app in H2; noconf H2.\n  - depelim H; solve_discr.\n    destruct args0 using rev_case; cbn in *; subst. cbn in H. congruence.\n    rewrite mkApps_app in H2; noconf H2.\n    eapply expanded_tConstruct_app; tea. cbn in H0. lia. solve_all.\n  - depelim H; solve_discr.\n    destruct args0 using rev_case; cbn in *; subst. cbn in H. congruence.\n    rewrite mkApps_app in H2; noconf H2.\n  - eapply expanded_mkApps. now rewrite eqc. auto. solve_all.\nQed.\n\nLemma expanded_lift Σ n k b Γ Δ Δ' :\n  #|Γ| = k ->\n  #|Δ'| = n ->\n  expanded Σ (Γ ++ Δ) b ->\n  expanded Σ (Γ ++ Δ' ++ Δ) (lift n k b).\nProof.\n  intros Hk Hn.\n  remember (Γ ++ Δ)%list as Γ_.\n  intros exp; revert Γ n k Hn Hk HeqΓ_.\n  induction exp using expanded_ind; intros Γ' n' k Hn Hk ->.\n  all:try solve[ cbn; econstructor => // ].\n  2,7:try solve [cbn; econstructor => //; solve_all ].\n  - subst n'. rewrite lift_mkApps /=.\n    destruct (Nat.leb_spec k n).\n    * rewrite nth_error_app_ge in H. lia.\n      eapply expanded_tRel.\n      rewrite nth_error_app_ge; [lia|].\n      rewrite nth_error_app_ge; [lia|]. erewrite <- H. lia_f_equal.\n      now len. solve_all.\n    * eapply expanded_tRel.\n      rewrite nth_error_app_lt in H; [lia|].\n      rewrite nth_error_app_lt; [lia|]. tea. now len. solve_all.\n  - cbn. econstructor.\n    eapply (IHexp (0 :: Γ') n' (S k)); cbn; auto; lia.\n  - cbn. econstructor. apply IHexp1; auto.\n    eapply (IHexp2 (0 :: Γ') n' (S k)); cbn; auto; lia.\n  - rewrite lift_mkApps.\n    destruct (isConstruct (lift n' k f6) || isFix (lift n' k f6) || isRel (lift n' k f6)) eqn:eqc.\n    specialize (IHexp  _ _ _ Hn Hk eq_refl).\n    eapply expanded_mkApps_expanded => //. solve_all.\n    eapply expanded_mkApps => //. now rewrite eqc. now eapply IHexp. solve_all.\n  - cbn. econstructor. eauto. solve_all. cbn. solve_all.\n    solve_all.\n    specialize (H1 (repeat 0 #|bcontext x| ++ Γ') n' (#|bcontext x| + k) Hn).\n    forward H1. len.\n    forward H1. now rewrite app_assoc.\n    rewrite /id. rewrite app_assoc. apply H1.\n  - rewrite lift_mkApps. cbn.\n    eapply expanded_tFix.\n    + solve_all.\n      specialize (a\n      (rev_map (fun d0 : def term => S (rarg d0))\n      (map (map_def (lift n' k) (lift n' (#|mfix| + k))) mfix) ++ Γ') n' (#|mfix| + k) Hn).\n      forward a. { rewrite rev_map_spec; len. }\n      forward a. { rewrite app_assoc. f_equal. f_equal.\n        rewrite !rev_map_spec. f_equal. now rewrite map_map_compose /=. }\n      rewrite app_assoc. eapply a.\n    + solve_all.\n    + destruct args => //.\n    + rewrite nth_error_map /= H4 //.\n    + len.\n  - cbn. constructor.\n    solve_all.\n    specialize (a (repeat 0 #|mfix| ++ Γ') n' (#|mfix| + k) Hn).\n    forward a. { len. }\n    forward a. { rewrite app_assoc //. }\n    rewrite app_assoc. eapply a.\n  - rewrite lift_mkApps. cbn.\n    eapply expanded_tConstruct_app; tea. now len.\n    solve_all.\nQed.\n\nLemma expanded_subst Σ a k b Γ Δ :\n    #|Γ| = k ->\n  Forall (expanded Σ Δ) a ->\n  expanded Σ (Γ ++ repeat 0 #|a| ++ Δ) b ->\n  expanded Σ (Γ ++ Δ) (subst a k b).\nProof.\n  intros Hk H.\n  remember (Γ ++ _ ++ Δ)%list as Γ_.\n  intros exp; revert Γ k Hk HeqΓ_.\n  induction exp using expanded_ind; intros Γ' k Hk ->.\n  all:try solve[ cbn; econstructor => // ].\n  2,7:solve[ cbn; econstructor => //; solve_all ].\n  - rewrite subst_mkApps /=.\n    destruct (Nat.leb_spec k n).\n    destruct (nth_error a _) eqn:hnth.\n    * eapply expanded_mkApps_expanded.\n      eapply nth_error_forall in H; tea.\n      eapply (expanded_lift Σ k 0 _ [] Δ Γ'); auto.\n      solve_all.\n    * rewrite nth_error_app_ge in H0. lia.\n      eapply nth_error_None in hnth.\n      rewrite nth_error_app_ge in H0. rewrite repeat_length. lia.\n      rewrite repeat_length in H0.\n      eapply expanded_tRel. rewrite nth_error_app_ge. lia. erewrite <- H0.\n      lia_f_equal. len. solve_all.\n    * rewrite nth_error_app_lt in H0. lia.\n      eapply expanded_tRel. rewrite nth_error_app_lt. lia. tea. now len.\n      solve_all.\n  - cbn. econstructor.\n    eapply (IHexp (0 :: Γ') (S k)); cbn; auto; lia.\n  - cbn. econstructor. apply IHexp1; auto.\n    eapply (IHexp2 (0 :: Γ') (S k)); cbn; auto; lia.\n  - rewrite subst_mkApps.\n    destruct (isConstruct (subst a k f6) || isFix (subst a k f6) || isRel (subst a k f6)) eqn:eqc.\n    specialize (IHexp  _ _ Hk eq_refl).\n    eapply expanded_mkApps_expanded => //. solve_all.\n    eapply expanded_mkApps => //. now rewrite eqc. now eapply IHexp. solve_all.\n  - cbn. econstructor. eauto. cbn. solve_all. solve_all.\n    specialize (H2 (repeat 0 #|bcontext x| ++ Γ') (#|bcontext x| + k)).\n    forward H2 by len.\n    forward H2. now rewrite app_assoc.\n    rewrite /id. rewrite app_assoc. apply H2.\n  - rewrite subst_mkApps. cbn.\n    eapply expanded_tFix.\n    + solve_all. now eapply isLambda_subst.\n      specialize (a0\n      (rev_map (fun d0 : def term => S (rarg d0))\n      (map (map_def (subst a k) (subst a (#|mfix| + k))) mfix) ++ Γ') (#|mfix| + k)).\n      forward a0 by len.\n      forward a0. { rewrite app_assoc. f_equal. f_equal.\n        rewrite !rev_map_spec. f_equal. now rewrite map_map_compose /=. }\n      rewrite app_assoc. eapply a0.\n    + solve_all.\n    + now destruct args.\n    + rewrite nth_error_map /= H5 //.\n    + len.\n  - cbn. constructor.\n    solve_all.\n    specialize (a0 (repeat 0 #|mfix| ++ Γ') (#|mfix| + k)).\n    forward a0 by len.\n    forward a0. { rewrite app_assoc //. }\n    rewrite app_assoc. eapply a0.\n  - rewrite subst_mkApps. cbn.\n    eapply expanded_tConstruct_app; tea. now len.\n    solve_all.\nQed.\n\nLemma All_fold_tip {A : Type} (P : list A -> A -> Type) {x} : All_fold P [x] -> P [] x.\nProof.\n  intros a; now depelim a.\nQed.\n\nLemma expanded_let_expansion Σ (Δ : context) Γ t :\n  expanded_context Σ Γ Δ ->\n  expanded Σ (repeat 0 #|Δ| ++ Γ) t ->\n  expanded Σ (repeat 0 (context_assumptions Δ) ++ Γ) (expand_lets Δ t).\nProof.\n  intros [ha].\n  revert Γ t ha.\n  induction Δ using PCUICInduction.ctx_length_rev_ind.\n  - cbn; intros. now rewrite expand_lets_nil.\n  - intros Γ' t ha; destruct d as [na [b|] ty]; cbn; len; cbn.\n    * rewrite expand_lets_vdef /= //.\n      intros exp. relativize (context_assumptions Γ).\n      eapply H. now len.\n      { eapply All_fold_app_inv in ha as [].\n        depelim a. depelim a. cbn in *.\n        rewrite /subst_context.\n        eapply PCUICParallelReduction.All_fold_fold_context_k.\n        eapply All_fold_impl; tea. cbn; intros.\n        depelim f.\n        destruct decl_body => //; constructor. depelim H1.\n        len in H1. cbn in H1.\n        cbn. len. eapply expanded_subst. now rewrite repeat_length. eauto.\n        auto. cbn. now rewrite repeat_app /= -app_assoc /= in H1. }\n      len.\n      rewrite repeat_app -app_assoc /= in exp.\n      eapply All_fold_app_inv in ha as []. eapply All_fold_tip in a. cbn in a. depelim a.\n      eapply expanded_subst. rewrite repeat_length //. constructor; auto.\n      cbn. exact exp. now len.\n    * rewrite expand_lets_vass /= //.\n      rewrite !repeat_app -!app_assoc.\n      intros exp. relativize (context_assumptions Γ).\n      eapply H. lia.\n      { eapply All_fold_app_inv in ha as [].\n        depelim a. cbn in f. depelim a.\n        eapply All_fold_impl; tea. cbn; intros.\n        destruct decl_body => //; constructor. depelim H0. len in H0. cbn in H0.\n        now rewrite repeat_app /= -app_assoc /= in H0. }\n      exact exp. lia.\nQed.\n\nRequire Import PCUICUnivSubst.\n\nLemma subst_instance_isConstruct t u : isConstruct t@[u] = isConstruct t.\nProof. destruct t => //. Qed.\nLemma subst_instance_isRel t u : isRel t@[u] = isRel t.\nProof. destruct t => //. Qed.\nLemma subst_instance_isFix t u : isFix t@[u] = isFix t.\nProof. destruct t => //. Qed.\nLemma subst_instance_isLambda t u : isLambda t@[u] = isLambda t.\nProof. destruct t => //. Qed.\n\nLemma expanded_subst_instance Σ Γ t u : expanded Σ Γ t -> expanded Σ Γ t@[u].\nProof.\n  induction 1 using PCUICEtaExpand.expanded_ind; cbn.\n  all:intros; rewrite ?subst_instance_mkApps.\n  all:try solve [econstructor; eauto 1].\n  - econstructor; eauto. now rewrite map_length. solve_all.\n  - econstructor; eauto. solve_all.\n  - econstructor; eauto. 2:solve_all.\n    rewrite subst_instance_isConstruct subst_instance_isFix subst_instance_isRel //.\n  - econstructor; eauto. cbn. solve_all.\n    solve_all.\n  - cbn; eapply expanded_tFix. solve_all. rewrite subst_instance_isLambda //.\n    rewrite rev_map_spec map_map_compose -rev_map_spec //.\n    solve_all. now destruct args => //.\n    rewrite nth_error_map H4 //.\n    now len.\n  - econstructor; eauto. solve_all.\n  - eapply expanded_tConstruct_app; tea. now len. solve_all.\nQed.\n\nLemma expanded_weakening Σ Γ t : expanded Σ Γ t -> forall Γ', expanded Σ (Γ ++ Γ') t.\nProof.\n  induction 1 using PCUICEtaExpand.expanded_ind; cbn.\n  1:{ intros. eapply expanded_tRel; tea. rewrite nth_error_app_lt.\n     now eapply nth_error_Some_length in H. assumption.\n    solve_all. }\n  all:intros; try solve [econstructor; eauto 1; solve_all; try now rewrite app_assoc].\nQed.\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/PCUICEtaExpand.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.2948898862989504}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import vcfloat.VCFloat.\nRequire Import vcfloat.FPCompCert.\n\nRequire Import DDModels.\nRequire Import TwoSum.\n\n#[export] Instance CompSpecs : \n  compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nOpen Scope logic.\n\nDefinition st := Tstruct __1017 noattr.\n\nDefinition f2val (pq: ftype Tdouble * ftype Tdouble) : val*val :=\n (Vfloat (fst pq), Vfloat (snd pq)).\n\nDefinition TwoSum_spec := \n  DECLARE _TwoSum\n  WITH s: val, a : ftype Tdouble, b : ftype Tdouble\n  PRE [ tptr st, tdouble, tdouble ] (* c lang types *)\n    PROP()\n    PARAMS (s; Vfloat a; Vfloat b)\n    SEP(data_at_ Tsh st s) (* preds on mem *)\n  POST [ tvoid ]\n    PROP()\n    RETURN()\n    SEP(data_at Tsh st (f2val (TwoSumF a b)) s).\n\n(* Collect the function-API specs together into Gprog: list funspec *)\nDefinition Gprog : funspecs := [TwoSum_spec].\n\n(* The function satisfies its API spec (with a semax-body proof) *)\nLemma body_twoSum: semax_body Vprog Gprog f_TwoSum TwoSum_spec.\nProof.\nstart_function.\nforward.\nforward.\nforward.\nforward.\nforward.\nforward.\nforward.\nforward.\nautorewrite with float_elim in *. (* for view only *)\nunfold f2val, TwoSumF, fst, snd.\nentailer!.\nQed.\n\n\n\n\n", "meta": {"author": "VeriNum", "repo": "double-double", "sha": "a73bb5752bdd67b29cf036e63b2fb090f59f1cc9", "save_path": "github-repos/coq/VeriNum-double-double", "path": "github-repos/coq/VeriNum-double-double/double-double-a73bb5752bdd67b29cf036e63b2fb090f59f1cc9/verif_TwoSum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2948360892779615}}
{"text": "From iris.algebra Require Export frac auth.\nFrom iris.algebra Require Export updates local_updates.\nFrom iris.proofmode Require Import classes.\n\nDefinition frac_authR (A : cmraT) : cmraT :=\n  authR (optionUR (prodR fracR A)).\nDefinition frac_authUR (A : cmraT) : ucmraT :=\n  authUR (optionUR (prodR fracR A)).\n\nDefinition frac_auth_auth {A : cmraT} (x : A) : frac_authR A :=\n  ● (Some (1%Qp,x)).\nDefinition frac_auth_frag {A : cmraT} (q : frac) (x : A) : frac_authR A :=\n  ◯ (Some (q,x)).\n\nTypeclasses Opaque frac_auth_auth frac_auth_frag.\n\nInstance: Params (@frac_auth_auth) 1.\nInstance: Params (@frac_auth_frag) 2.\n\nNotation \"●! a\" := (frac_auth_auth a) (at level 10).\nNotation \"◯!{ q } a\" := (frac_auth_frag q a) (at level 10, format \"◯!{ q }  a\").\nNotation \"◯! a\" := (frac_auth_frag 1 a) (at level 10).\n\nSection frac_auth.\n  Context {A : cmraT}.\n  Implicit Types a b : A.\n\n  Global Instance frac_auth_auth_ne : NonExpansive (@frac_auth_auth A).\n  Proof. solve_proper. Qed.\n  Global Instance frac_auth_auth_proper : Proper ((≡) ==> (≡)) (@frac_auth_auth A).\n  Proof. solve_proper. Qed.\n  Global Instance frac_auth_frag_ne q : NonExpansive (@frac_auth_frag A q).\n  Proof. solve_proper. Qed.\n  Global Instance frac_auth_frag_proper q : Proper ((≡) ==> (≡)) (@frac_auth_frag A q).\n  Proof. solve_proper. Qed.\n\n  Global Instance frac_auth_auth_discrete a : Discrete a → Discrete (●! a).\n  Proof. intros; apply Auth_discrete; apply _. Qed.\n  Global Instance frac_auth_frag_discrete a : Discrete a → Discrete (◯! a).\n  Proof. intros; apply Auth_discrete, Some_discrete; apply _. Qed.\n\n  Lemma frac_auth_validN n a : ✓{n} a → ✓{n} (●! a ⋅ ◯! a).\n  Proof. done. Qed.\n  Lemma frac_auth_valid a : ✓ a → ✓ (●! a ⋅ ◯! a).\n  Proof. done. Qed.\n\n  Lemma frac_auth_agreeN n a b : ✓{n} (●! a ⋅ ◯! b) → a ≡{n}≡ b.\n  Proof.\n    rewrite auth_validN_eq /= => -[Hincl Hvalid].\n    by move: Hincl=> /Some_includedN_exclusive /(_ Hvalid ) [??].\n  Qed.\n  Lemma frac_auth_agree a b : ✓ (●! a ⋅ ◯! b) → a ≡ b.\n  Proof.\n    intros. apply equiv_dist=> n. by apply frac_auth_agreeN, cmra_valid_validN.\n  Qed.\n  Lemma frac_auth_agreeL `{!LeibnizEquiv A} a b : ✓ (●! a ⋅ ◯! b) → a = b.\n  Proof. intros. by apply leibniz_equiv, frac_auth_agree. Qed.\n\n  Lemma frac_auth_includedN n q a b : ✓{n} (●! a ⋅ ◯!{q} b) → Some b ≼{n} Some a.\n  Proof. by rewrite auth_validN_eq /= => -[/Some_pair_includedN [_ ?] _]. Qed.\n  Lemma frac_auth_included `{CmraDiscrete A} q a b :\n    ✓ (●! a ⋅ ◯!{q} b) → Some b ≼ Some a.\n  Proof. by rewrite auth_valid_discrete /= => -[/Some_pair_included [_ ?] _]. Qed.\n  Lemma frac_auth_includedN_total `{CmraTotal A} n q a b :\n    ✓{n} (●! a ⋅ ◯!{q} b) → b ≼{n} a.\n  Proof. intros. by eapply Some_includedN_total, frac_auth_includedN. Qed.\n  Lemma frac_auth_included_total `{CmraDiscrete A, CmraTotal A} q a b :\n    ✓ (●! a ⋅ ◯!{q} b) → b ≼ a.\n  Proof. intros. by eapply Some_included_total, frac_auth_included. Qed.\n\n  Lemma frac_auth_auth_validN n a : ✓{n} (●! a) ↔ ✓{n} a.\n  Proof.\n    split; [by intros [_ [??]]|].\n    by repeat split; simpl; auto using ucmra_unit_leastN.\n  Qed.\n  Lemma frac_auth_auth_valid a : ✓ (●! a) ↔ ✓ a.\n  Proof. rewrite !cmra_valid_validN. by setoid_rewrite frac_auth_auth_validN. Qed.\n\n  Lemma frac_auth_frag_validN n q a : ✓{n} (◯!{q} a) ↔ ✓{n} q ∧ ✓{n} a.\n  Proof. done. Qed.\n  Lemma frac_auth_frag_valid q a : ✓ (◯!{q} a) ↔ ✓ q ∧ ✓ a.\n  Proof. done. Qed.\n\n  Lemma frag_auth_op q1 q2 a1 a2 : ◯!{q1+q2} (a1 ⋅ a2) ≡ ◯!{q1} a1 ⋅ ◯!{q2} a2.\n  Proof. done. Qed.\n\n  Lemma frac_auth_frag_validN_op_1_l n q a b : ✓{n} (◯!{1} a ⋅ ◯!{q} b) → False.\n  Proof. rewrite -frag_auth_op frac_auth_frag_validN=> -[/exclusiveN_l []]. Qed.\n  Lemma frac_auth_frag_valid_op_1_l q a b : ✓ (◯!{1} a ⋅ ◯!{q} b) → False.\n  Proof. rewrite -frag_auth_op frac_auth_frag_valid=> -[/exclusive_l []]. Qed.\n\n  Global Instance is_op_frac_auth (q q1 q2 : frac) (a a1 a2 : A) :\n    IsOp q q1 q2 → IsOp a a1 a2 → IsOp' (◯!{q} a) (◯!{q1} a1) (◯!{q2} a2).\n  Proof. by rewrite /IsOp' /IsOp=> /leibniz_equiv_iff -> ->. Qed.\n\n  Global Instance is_op_frac_auth_core_id (q q1 q2 : frac) (a  : A) :\n    CoreId a → IsOp q q1 q2 → IsOp' (◯!{q} a) (◯!{q1} a) (◯!{q2} a).\n  Proof.\n    rewrite /IsOp' /IsOp=> ? /leibniz_equiv_iff ->.\n    by rewrite -frag_auth_op -core_id_dup.\n  Qed.\n\n  Lemma frac_auth_update q a b a' b' :\n    (a,b) ~l~> (a',b') → ●! a ⋅ ◯!{q} b ~~> ●! a' ⋅ ◯!{q} b'.\n  Proof.\n    intros. by apply auth_update, option_local_update, prod_local_update_2.\n  Qed.\nEnd frac_auth.\n", "meta": {"author": "jtassarotti", "repo": "polaris", "sha": "c7873f05214351d54cacf3d8482625ee33ad3288", "save_path": "github-repos/coq/jtassarotti-polaris", "path": "github-repos/coq/jtassarotti-polaris/polaris-c7873f05214351d54cacf3d8482625ee33ad3288/theories/algebra/frac_auth.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2948360819866952}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nRequire Import Bool.\nRequire Import Arith.\nRequire Import NArith.\nRequire Import Ndec.\nRequire Import ZArith.\nRequire Import Classical_Prop.\nFrom IntMap Require Import Allmaps.\nFrom TreeAutomata Require Import lattice_fixpoint.\nFrom TreeAutomata Require Import bases.\nFrom TreeAutomata Require Import defs.\nFrom TreeAutomata Require Import semantics.\nFrom TreeAutomata Require Import pl_path.\n\n\n\nFixpoint pl_non_empty (m : Map bool) (p : prec_list) {struct p} : bool :=\nmatch p with\n| prec_empty => true\n| prec_cons a la ls =>\nmatch ls with\n| prec_empty =>\nmatch MapGet bool m a with\n| Some b => b && pl_non_empty m la\n| None => false\nend\n| prec_cons _ _ _ =>\nmatch MapGet bool m a with\n| Some b => pl_non_empty m ls || b && pl_non_empty m la\n| None => pl_non_empty m ls\nend\nend\nend.\n\nFixpoint st_non_empty (m : Map bool) (s : state) {struct s} : bool :=\nmatch s with\n| M0 => false\n| M1 _ p => pl_non_empty m p\n| M2 a b => st_non_empty m a || st_non_empty m b\nend.\n\nFixpoint dta_app_ne_aux (d : preDTA) (m r : Map bool) {struct r} :\nMap bool :=\nmatch d, r with\n| M0, _ => M0 bool\n| M1 a s, M0 => M0 bool\n| M1 a s, M1 a' b =>\nif N.eqb a a' then M1 bool a (b || st_non_empty m s) else M0 bool\n| M1 a s, M2 _ _ => M0 bool\n| M2 d0 d1, M0 => M0 bool\n| M2 d0 d1, M1 _ _ => M0 bool\n| M2 d0 d1, M2 r0 r1 =>\nM2 bool (dta_app_ne_aux d0 m r0) (dta_app_ne_aux d1 m r1)\nend.\n\nDefinition dta_app_ne (d : preDTA) (m : Map bool) :\nMap bool := dta_app_ne_aux d m m.\n\nDefinition dta_non_empty_states (d : preDTA) : Map bool :=\npower (Map bool) (dta_app_ne d) (map_mini state d) (S (MapCard state d)).\n\nDefinition dta_states_non_empty (d : DTA) : Map bool :=\nmatch d with\n| dta p a => dta_non_empty_states p\nend.\n\nDefinition dta_non_empty_states_lazy (d : preDTA) :\nMap bool :=\nlazy_power bool eqm_bool (dta_app_ne d) (map_mini state d)\n(S (MapCard state d)).\n\nDefinition dta_states_non_empty_lazy (d : DTA) : Map bool :=\nmatch d with\n| dta p a => dta_non_empty_states_lazy p\nend.\n\nLemma dta_states_non_empty_lazy_eg_dta_states_non_empty :\nforall d : DTA, dta_states_non_empty_lazy d = dta_states_non_empty d.\nProof. hammer_hook \"empty_test\" \"empty_test.dta_states_non_empty_lazy_eg_dta_states_non_empty\".\nsimple induction d. simpl in |- *. intros. unfold dta_non_empty_states_lazy, dta_non_empty_states in |- *. apply\n(lazy_power_eg_power bool eqm_bool (dta_app_ne p)\n(map_mini state p) (S (MapCard state p))).\nsplit. exact (eqm_bool_equal a0 b). intros. rewrite H.\nexact (equal_eqm_bool b).\nQed.\n\n\n\nLemma dta_app_ne_aux_def_ok :\nforall (d : preDTA) (m : Map bool),\ndef_ok_app bool (ensemble_base state d) (dta_app_ne_aux d m).\nProof. hammer_hook \"empty_test\" \"empty_test.dta_app_ne_aux_def_ok\".\nsimple induction d. intros. unfold def_ok_app in |- *. intros. induction  x as [| a a0| x1 Hrecx1 x0 Hrecx0].\nsimpl in |- *. unfold ensemble_base in |- *. exact I. unfold ensemble_base in |- *. simpl in |- *.\nexact I. simpl in |- *. unfold ensemble_base in |- *. simpl in |- *. exact I. intros.\nunfold def_ok_app in |- *. intros. unfold ensemble_base in |- *. unfold ensemble_base in H. induction  x as [| a1 a2| x1 Hrecx1 x0 Hrecx0]. simpl in H. inversion H. simpl in H. simpl in |- *. rewrite H.\nrewrite (Neqb_correct a1). simpl in |- *. reflexivity. simpl in H. inversion H.\nintros. unfold def_ok_app in |- *. unfold ensemble_base in |- *. intros. induction  x as [| a a0| x1 Hrecx1 x0 Hrecx0].\nsimpl in H1. inversion H1. simpl in H1. inversion H1. simpl in |- *. split.\nunfold def_ok_app in H. unfold ensemble_base in H. simpl in H1.\nelim H1. intros. exact (H m1 x1 H2). unfold def_ok_app in H0.\nunfold ensemble_base in H0. elim H1. intros. exact (H0 m1 x0 H3).\nQed.\n\nLemma dta_app_ne_def_ok :\nforall d : preDTA, def_ok_app bool (ensemble_base state d) (dta_app_ne d).\nProof. hammer_hook \"empty_test\" \"empty_test.dta_app_ne_def_ok\".\nintros. unfold dta_app_ne in |- *. unfold def_ok_app in |- *. intros. exact (dta_app_ne_aux_def_ok d x x H).\nQed.\n\n\n\nLemma dta_app_ne_inc_0 :\nforall (p : prec_list) (m0 m1 : Map bool),\nlem m0 m1 -> leb (pl_non_empty m0 p) (pl_non_empty m1 p).\nProof. hammer_hook \"empty_test\" \"empty_test.dta_app_ne_inc_0\".\nsimple induction p. intros. induction  p1 as [a0 p1_1 Hrecp1_1 p1_0 Hrecp1_0| ]. elim (option_sum bool (MapGet bool m0 a)); intro y. elim y. intros x y0. elim (option_sum bool (MapGet bool m1 a)); intro y1. elim y1. intros x0 y2. replace (pl_non_empty m0 (prec_cons a p0 (prec_cons a0 p1_1 p1_0))) with\n(pl_non_empty m0 (prec_cons a0 p1_1 p1_0) || x && pl_non_empty m0 p0). replace (pl_non_empty m1 (prec_cons a p0 (prec_cons a0 p1_1 p1_0))) with\n(pl_non_empty m1 (prec_cons a0 p1_1 p1_0) || x0 && pl_non_empty m1 p0). apply\n(leb_transitive\n(pl_non_empty m0 (prec_cons a0 p1_1 p1_0) || x && pl_non_empty m0 p0)\n(pl_non_empty m0 (prec_cons a0 p1_1 p1_0) || x0 && pl_non_empty m1 p0)\n(pl_non_empty m1 (prec_cons a0 p1_1 p1_0) || x0 && pl_non_empty m1 p0)).\napply\n(orb_incr (pl_non_empty m0 (prec_cons a0 p1_1 p1_0))\n(pl_non_empty m0 (prec_cons a0 p1_1 p1_0)) (x && pl_non_empty m0 p0)\n(x0 && pl_non_empty m1 p0)). exact (leb_reflexive _).\napply (andb_incr x x0 (pl_non_empty m0 p0) (pl_non_empty m1 p0)).\nexact (lem_get_leb m0 m1 a x x0 H1 y0 y2). exact (H _ _ H1).\napply\n(orb_incr (pl_non_empty m0 (prec_cons a0 p1_1 p1_0))\n(pl_non_empty m1 (prec_cons a0 p1_1 p1_0)) (x0 && pl_non_empty m1 p0)\n(x0 && pl_non_empty m1 p0)). exact (H0 _ _ H1). exact (leb_reflexive _). simpl in |- *. rewrite y2. reflexivity. simpl in |- *. rewrite y0.\nreflexivity. elim (domain_equal_mapget bool bool m0 m1 a x). intros.\nrewrite H2 in y1. inversion y1. exact (lem_domain_equal m0 m1 H1).\nexact y0. elim (option_sum bool (MapGet bool m1 a)); intro y0. elim y0; intros x y1. elim (domain_equal_mapget bool bool m1 m0 a x); intros. rewrite H2 in y. inversion y. exact (domain_equal_symmetric bool bool _ _ (lem_domain_equal _ _ H1)). exact y1. replace (pl_non_empty m0 (prec_cons a p0 (prec_cons a0 p1_1 p1_0))) with\n(pl_non_empty m0 (prec_cons a0 p1_1 p1_0)). replace (pl_non_empty m1 (prec_cons a p0 (prec_cons a0 p1_1 p1_0))) with\n(pl_non_empty m1 (prec_cons a0 p1_1 p1_0)).\nexact (H0 _ _ H1). simpl in |- *. rewrite y0. reflexivity. simpl in |- *. rewrite y.\nreflexivity. elim (option_sum bool (MapGet bool m0 a)); intro y.\nelim (option_sum bool (MapGet bool m1 a)); intro y0. elim y; intros x y1.\nelim y0; intros x0 y2. replace (pl_non_empty m0 (prec_cons a p0 prec_empty)) with\n(x && pl_non_empty m0 p0). replace (pl_non_empty m1 (prec_cons a p0 prec_empty)) with\n(x0 && pl_non_empty m1 p0). apply\n(leb_transitive (x && pl_non_empty m0 p0) (x0 && pl_non_empty m0 p0)\n(x0 && pl_non_empty m1 p0)). apply (andb_inc_l (pl_non_empty m0 p0) x x0). exact (lem_get_leb _ _ _ _ _ H1 y1 y2). apply (andb_inc_r x0 (pl_non_empty m0 p0) (pl_non_empty m1 p0)). exact (H _ _ H1). simpl in |- *.\nrewrite y2. reflexivity. simpl in |- *. rewrite y1. reflexivity. elim y. intros x y1.\nelim (domain_equal_mapget bool bool m0 m1 a x). intros. rewrite H2 in y0.\ninversion y0. exact (lem_domain_equal _ _ H1). exact y1. elim (option_sum bool (MapGet bool m1 a)); intro y0. elim y0. intros x y1. elim (domain_equal_mapget bool bool m1 m0 a x). intros. rewrite H2 in y. inversion y.\nexact (domain_equal_symmetric bool bool _ _ (lem_domain_equal _ _ H1)).\nexact y1. simpl in |- *. rewrite y. rewrite y0. exact I. simpl in |- *. intros. exact I.\nQed.\n\nLemma dta_app_ne_inc_1 :\nforall (s : state) (m0 m1 : Map bool),\nlem m0 m1 -> leb (st_non_empty m0 s) (st_non_empty m1 s).\nProof. hammer_hook \"empty_test\" \"empty_test.dta_app_ne_inc_1\".\nsimple induction s. intros. simpl in |- *. exact I. intros. simpl in |- *.\nexact (dta_app_ne_inc_0 a0 m0 m1 H). intros. simpl in |- *.\nexact (orb_incr _ _ _ _ (H _ _ H1) (H0 _ _ H1)).\nQed.\n\nLemma dta_app_ne_inc_2 :\nforall (d : preDTA) (m0 m1 m : Map bool),\nlem m0 m1 -> lem (dta_app_ne_aux d m0 m) (dta_app_ne_aux d m1 m).\nProof. hammer_hook \"empty_test\" \"empty_test.dta_app_ne_inc_2\".\nsimple induction d. simple induction m. intros. simpl in |- *. exact I. intros.\nsimpl in |- *. exact I. intros. simpl in |- *. exact I. simple induction m. intros.\nsimpl in |- *. exact I. simpl in |- *. intros. elim (bool_is_true_or_false (N.eqb a a1)); intros; rewrite H0. simpl in |- *. rewrite (Neqb_correct a). exact (orb_inc_r _ _ _ (dta_app_ne_inc_1 a0 m0 m1 H)).\nexact I. intros. simpl in |- *. exact I. simple induction m3. intros. simpl in |- *.\nexact I. intros. simpl in |- *. exact I. intros. simpl in |- *. split.\nexact (H _ _ _ H3). exact (H0 _ _ _ H3).\nQed.\n\nLemma dta_app_ne_inc_3 :\nforall (m0 m1 m : Map bool) (d : preDTA),\nlem m0 m1 -> lem (dta_app_ne_aux d m m0) (dta_app_ne_aux d m m1).\nProof. hammer_hook \"empty_test\" \"empty_test.dta_app_ne_inc_3\".\nsimple induction m0. simple induction m1; intros. induction  d as [| a a0| d1 Hrecd1 d0 Hrecd0]; simpl in |- *; exact I.\ninversion H. inversion H1. simple induction m1; intros. inversion H.\ninduction  d as [| a3 a4| d1 Hrecd1 d0 Hrecd0]; simpl in |- *. exact I. simpl in H. elim (bool_is_true_or_false (N.eqb a a1)); intro; rewrite H0 in H. rewrite (Neqb_complete _ _ H0).\nelim (bool_is_true_or_false (N.eqb a3 a1)); intro; rewrite H1. simpl in |- *.\nrewrite (Neqb_correct a3). exact (orb_inc_l _ _ _ H). exact I. elim H.\nexact I. inversion H1. simple induction m2; intros. inversion H1. inversion H1.\nelim H3; intros. induction  d as [| a a0| d1 Hrecd1 d0 Hrecd0]; simpl in |- *. exact I. exact I. split. exact (H _ _ _ H4). exact (H0 _ _ _ H5).\nQed.\n\nLemma dta_app_ne_inc :\nforall d : preDTA, increasing_app bool lem (dta_app_ne d).\nProof. hammer_hook \"empty_test\" \"empty_test.dta_app_ne_inc\".\nintros. unfold increasing_app in |- *. unfold dta_app_ne in |- *. intros.\nexact\n(lem_transitive _ _ _ (dta_app_ne_inc_2 d x y x H)\n(dta_app_ne_inc_3 x y y d H)).\nQed.\n\nInductive pl_path_true : pl_path -> Map bool -> Prop :=\n| plp_true_nil : forall m : Map bool, pl_path_true pl_path_nil m\n| plp_true_cons :\nforall (m : Map bool) (a : ad) (pl : pl_path),\npl_path_true pl m ->\nMapGet bool m a = Some true -> pl_path_true (pl_path_cons a pl) m.\n\nDefinition pl_non_empty_path_true_def_0 (pl : pl_path)\n(p : prec_list) : Prop :=\nforall m : Map bool,\npl_path_incl pl p -> pl_path_true pl m -> pl_non_empty m p = true.\n\nLemma pl_non_empty_path_true_0 :\npl_non_empty_path_true_def_0 pl_path_nil prec_empty.\nProof. hammer_hook \"empty_test\" \"empty_test.pl_non_empty_path_true_0\".\nunfold pl_non_empty_path_true_def_0 in |- *. simpl in |- *. intros.\nreflexivity.\nQed.\n\nLemma pl_non_empty_path_true_1 :\nforall (plp : pl_path) (a : ad) (la ls : prec_list),\npl_path_incl plp la ->\npl_non_empty_path_true_def_0 plp la ->\npl_non_empty_path_true_def_0 (pl_path_cons a plp) (prec_cons a la ls).\nProof. hammer_hook \"empty_test\" \"empty_test.pl_non_empty_path_true_1\".\nunfold pl_non_empty_path_true_def_0 in |- *. intros. inversion H2.\nsimpl in |- *. rewrite H7. elim (pl_sum ls); intros. rewrite H8.\nexact (H0 m H H5). elim H8. intros. elim H9. intros. elim H10.\nintros. rewrite H11. rewrite (H0 m H H5). elim (bool_is_true_or_false (pl_non_empty m (prec_cons x x0 x1))); intro;\nrewrite H12; reflexivity.\nQed.\n\nLemma pl_non_empty_path_true_2 :\nforall (plp : pl_path) (a : ad) (la ls : prec_list),\npl_path_incl plp ls ->\npl_non_empty_path_true_def_0 plp ls ->\nplp <> pl_path_nil -> pl_non_empty_path_true_def_0 plp (prec_cons a la ls).\nProof. hammer_hook \"empty_test\" \"empty_test.pl_non_empty_path_true_2\".\nunfold pl_non_empty_path_true_def_0 in |- *. intros. induction  plp as [| a0 plp Hrecplp].\nelim (H1 (refl_equal _)). inversion H3. simpl in |- *. elim (pl_sum ls); intros. rewrite H9 in H. inversion H. elim H9.\nintros. elim H10. intros. elim H11. intros. rewrite H12.\nrewrite <- H12. rewrite (H0 m H H3). elim (option_sum bool (MapGet bool m a)); intro y. elim y. intros x2 y0. rewrite y0.\nelim (bool_is_true_or_false (x2 && pl_non_empty m la)); intro; rewrite H13;\nreflexivity. rewrite y. reflexivity.\nQed.\n\nLemma pl_non_empty_path_true :\nforall (pl : pl_path) (p : prec_list) (m : Map bool),\npl_path_incl pl p -> pl_path_true pl m -> pl_non_empty m p = true.\nProof. hammer_hook \"empty_test\" \"empty_test.pl_non_empty_path_true\".\nintros. exact\n(pl_path_incl_ind pl_non_empty_path_true_def_0 pl_non_empty_path_true_0\npl_non_empty_path_true_1 pl_non_empty_path_true_2 pl p H m H H0).\nQed.\n\nLemma pl_non_empty_path_true_rev :\nforall (p : prec_list) (m : Map bool),\npl_non_empty m p = true ->\nexists plp : pl_path, pl_path_incl plp p /\\ pl_path_true plp m.\nProof. hammer_hook \"empty_test\" \"empty_test.pl_non_empty_path_true_rev\".\nsimple induction p. intros. simpl in H1. elim (pl_sum p1); intros.\nrewrite H2 in H1. elim (option_sum bool (MapGet bool m a)); intro y. elim y. intros x y0. rewrite y0 in H1. elim (bool_is_true_or_false x); intro; rewrite H3 in H1. elim (bool_is_true_or_false (pl_non_empty m p0)); intros. elim (H m H4). intros. elim H5. intros. split with (pl_path_cons a x0). split. exact (pl_path_incl_cons x0 a p0 p1 H6).\nrewrite H3 in y0. exact (plp_true_cons m a x0 H7 y0).\nrewrite H4 in H1. inversion H1. elim (bool_is_true_or_false (pl_non_empty m p0)); intro; rewrite H4 in H1;\ninversion H1.\nrewrite y in H1. inversion H1. elim H2. intros. elim H3. intros.\nelim H4. intros. rewrite H5 in H1. rewrite <- H5 in H1. elim (option_sum bool (MapGet bool m a)); intro y. elim y. intros x2 y0.\nrewrite y0 in H1. elim (bool_is_true_or_false (pl_non_empty m p1)); intros. elim (H0 m H6); intros. split with x3. split.\nelim H7. intros. apply (pl_path_incl_next x3 a p0 p1 H8). intro.\nrewrite H10 in H8. rewrite H5 in H8. inversion H8. exact (H16 (refl_equal _)). elim H7; intros. assumption.\nrewrite H6 in H1. elim (bool_is_true_or_false (x2 && pl_non_empty m p0)); intros;\nrewrite H7 in H1. elim (bool_is_true_or_false x2); intros; rewrite H8 in H7. rewrite H8 in y0. elim (bool_is_true_or_false (pl_non_empty m p0)); intros.\nelim (H m H9); intros. split with (pl_path_cons a x3). split.\nelim H10. intros. exact (pl_path_incl_cons x3 a p0 p1 H11).\nelim H10. intros. exact (plp_true_cons m a x3 H12 y0). rewrite H9 in H7. inversion H7. elim (bool_is_true_or_false (pl_non_empty m p0)); intros; rewrite H9 in H7;\ninversion H7. inversion H1.\nrewrite y in H1. elim (H0 _ H1). intros. split with x2. split.\napply (pl_path_incl_next x2 a p0 p1). elim H6. intros. assumption.\nintro. rewrite H7 in H6. elim H6. intros. inversion H8. rewrite <- H11 in H5. inversion H5. exact (H11 (refl_equal _)).\nelim H6; intros. assumption. intros. split with pl_path_nil.\nsplit. exact pl_path_incl_nil. exact (plp_true_nil m).\nQed.\n\nLemma st_non_empty_0 :\nforall (m : Map bool) (s : state) (p : prec_list) (a : ad),\nMapGet prec_list s a = Some p ->\npl_non_empty m p = true -> st_non_empty m s = true.\nProof. hammer_hook \"empty_test\" \"empty_test.st_non_empty_0\".\nsimple induction s; intros. inversion H. simpl in |- *. simpl in H. elim (bool_is_true_or_false (N.eqb a a1)); intro; rewrite H1 in H;\ninversion H. exact H0. simpl in |- *. induction  a as [| p0]. simpl in H1. rewrite (H p N0 H1 H2). simpl in |- *. reflexivity. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]; simpl in H1.\nrewrite (H0 _ _ H1 H2). elim (bool_is_true_or_false (st_non_empty m m0)); intro; rewrite H3;\nreflexivity. rewrite (H _ _ H1 H2).\nreflexivity. rewrite (H0 _ _ H1 H2). elim (bool_is_true_or_false (st_non_empty m m0)); intro; rewrite H3;\nreflexivity.\nQed.\n\nLemma st_non_empty_1 :\nforall (d : preDTA) (m r : Map bool) (a : ad) (l : state),\nMapGet state d a = Some l ->\ndomain_equal state bool d r ->\nst_non_empty m l = true ->\nMapGet bool (dta_app_ne_aux d m r) a = Some true.\nProof. hammer_hook \"empty_test\" \"empty_test.st_non_empty_1\".\nsimple induction d. intros. inversion H. intros. induction  r as [| a2 a3| r1 Hrecr1 r0 Hrecr0].\ninversion H0. simpl in |- *. simpl in H0. simpl in H. rewrite H0.\nrewrite (Neqb_correct a2). simpl in |- *. rewrite H0 in H. elim (bool_is_true_or_false (N.eqb a2 a1)); intro; rewrite H2 in H.\ninversion H. rewrite H2. rewrite H1. elim (bool_is_true_or_false a3); intros; rewrite H3; reflexivity. inversion H. inversion H0.\nintros. induction  r as [| a0 a1| r1 Hrecr1 r0 Hrecr0]. inversion H2. inversion H2. elim H2; intros.\ninduction  a as [| p]. simpl in |- *. simpl in H1. apply (H m1 r1 N0 l H1 H4).\nexact H3. induction  p as [p Hrecp| p Hrecp| ]; simpl in |- *; simpl in H1. elim H2. intros.\nexact (H0 _ _ _ _ H1 H7 H3). exact (H _ _ _ _ H1 H4 H3).\nexact (H0 _ _ _ _ H1 H5 H3).\nQed.\n\n\n\nDefinition dt_non_empty_def_0 (d : preDTA) (a : ad)\n(t : term) (pr : reconnaissance d a t) :=\nforall n : nat,\nterm_high t <= n ->\nMapGet bool (power (Map bool) (dta_app_ne d) (map_mini state d) n) a =\nSome true.\n\nDefinition dt_non_empty_def_1 (d : preDTA) (s : state)\n(t : term) (pr : state_reconnait d s t) :=\nforall n : nat,\nterm_high t <= S n ->\nst_non_empty (power (Map bool) (dta_app_ne d) (map_mini state d) n) s =\ntrue.\n\nDefinition dt_non_empty_def_2 (d : preDTA) (p : prec_list)\n(t : term_list) (pr : liste_reconnait d p t) :=\nforall n : nat,\nterm_high_0 t <= n ->\npl_non_empty (power (Map bool) (dta_app_ne d) (map_mini state d) n) p =\ntrue.\n\nLemma dt_non_empty_0 :\nforall (d : preDTA) (a : ad) (t : term) (ladj : state)\n(e : MapGet state d a = Some ladj) (s : state_reconnait d ladj t),\ndt_non_empty_def_1 d ladj t s ->\ndt_non_empty_def_0 d a t (rec_dta d a t ladj e s).\nProof. hammer_hook \"empty_test\" \"empty_test.dt_non_empty_0\".\nunfold dt_non_empty_def_1, dt_non_empty_def_0 in |- *. intros. elim (nat_sum n); intros. rewrite H1 in H0. induction  t as (a0, t). simpl in H0.\nelim (le_Sn_O _ H0). elim H1. intros. rewrite H2. simpl in |- *. rewrite H2 in H0. replace\n(dta_app_ne d (power (Map bool) (dta_app_ne d) (map_mini state d) x)) with\n(dta_app_ne_aux d (power (Map bool) (dta_app_ne d) (map_mini state d) x)\n(power (Map bool) (dta_app_ne d) (map_mini state d) x)). apply\n(st_non_empty_1 d (power (Map bool) (dta_app_ne d) (map_mini state d) x)\n(power (Map bool) (dta_app_ne d) (map_mini state d) x) a ladj e). exact\n(power_def_ok bool (ensemble_base state d) (dta_app_ne d)\n(map_mini state d) x (dta_app_ne_def_ok d) (map_mini_appartient state d)). exact (H x H0). reflexivity.\nQed.\n\nLemma dt_non_empty_1 :\nforall (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),\ndt_non_empty_def_2 d l tl l0 ->\ndt_non_empty_def_1 d s (app c tl) (rec_st d s c tl l e l0).\nProof. hammer_hook \"empty_test\" \"empty_test.dt_non_empty_1\".\nunfold dt_non_empty_def_1 in |- *. unfold dt_non_empty_def_2 in |- *. intros.\nsimpl in H0. fold term_high_0 in H0. apply\n(st_non_empty_0 (power (Map bool) (dta_app_ne d) (map_mini state d) n) s l\nc e).\nexact (H n (le_S_n _ _ H0)).\nQed.\n\nLemma dt_non_empty_2 :\nforall d : preDTA, dt_non_empty_def_2 d prec_empty tnil (rec_empty d).\nProof. hammer_hook \"empty_test\" \"empty_test.dt_non_empty_2\".\nunfold dt_non_empty_def_2 in |- *. intros. simpl in |- *. reflexivity.\nQed.\n\nLemma dt_non_empty_3 :\nforall (d : preDTA) (a : ad) (la ls : prec_list) (hd : term)\n(tl : term_list) (r : reconnaissance d a hd),\ndt_non_empty_def_0 d a hd r ->\nforall l : liste_reconnait d la tl,\ndt_non_empty_def_2 d la tl l ->\ndt_non_empty_def_2 d (prec_cons a la ls) (tcons hd tl)\n(rec_consi d a la ls hd tl r l).\nProof. hammer_hook \"empty_test\" \"empty_test.dt_non_empty_3\".\nunfold dt_non_empty_def_0, dt_non_empty_def_2 in |- *. intros. simpl in H1.\nfold term_high in H1. elim\n(pl_non_empty_path_true_rev la\n(power (Map bool) (dta_app_ne d) (map_mini state d) n)\n(H0 n (le_trans (term_high_0 tl) _ _ (le_max_r _ _) H1))). intros. elim H2. intros.\napply\n(pl_non_empty_path_true (pl_path_cons a x) (prec_cons a la ls)\n(power (Map bool) (dta_app_ne d) (map_mini state d) n)). exact (pl_path_incl_cons x a la ls H3). apply\n(plp_true_cons (power (Map bool) (dta_app_ne d) (map_mini state d) n) a x). exact H4. exact (H _ (le_trans _ _ _ (le_max_l _ _) H1)).\nQed.\n\nLemma dt_non_empty_4 :\nforall (d : preDTA) (a : ad) (la ls : prec_list) (hd : term)\n(tl : term_list) (l : liste_reconnait d ls (tcons hd tl)),\ndt_non_empty_def_2 d ls (tcons hd tl) l ->\ndt_non_empty_def_2 d (prec_cons a la ls) (tcons hd tl)\n(rec_consn d a la ls hd tl l).\nProof. hammer_hook \"empty_test\" \"empty_test.dt_non_empty_4\".\nunfold dt_non_empty_def_2 in |- *. intros. elim (pl_non_empty_path_true_rev _ _ (H n H0)). intros. elim H1. intros. apply\n(pl_non_empty_path_true x (prec_cons a la ls)\n(power (Map bool) (dta_app_ne d) (map_mini state d) n)). apply (pl_path_incl_next x a la ls H2). intro. rewrite H4 in H3.\nrewrite H4 in H2. inversion H2. rewrite <- H6 in l. inversion l.\nelim (H6 (refl_equal _)). exact H3.\nQed.\n\nLemma dt_non_empty_5 :\nforall (d : preDTA) (a : ad) (t : term),\nreconnaissance d a t ->\nforall n : nat,\nterm_high t <= n ->\nMapGet bool (power (Map bool) (dta_app_ne d) (map_mini state d) n) a =\nSome true.\nProof. hammer_hook \"empty_test\" \"empty_test.dt_non_empty_5\".\nexact\n(mreconnaissance_ind dt_non_empty_def_0 dt_non_empty_def_1\ndt_non_empty_def_2 dt_non_empty_0 dt_non_empty_1 dt_non_empty_2\ndt_non_empty_3 dt_non_empty_4).\nQed.\n\nLemma dt_non_empty_6 :\nforall (p : preDTA) (p0 : prec_list) (t : term_list)\n(l : liste_reconnait p p0 t), dt_non_empty_def_2 p p0 t l.\nProof. hammer_hook \"empty_test\" \"empty_test.dt_non_empty_6\".\nexact\n(mlrec_ind dt_non_empty_def_0 dt_non_empty_def_1 dt_non_empty_def_2\ndt_non_empty_0 dt_non_empty_1 dt_non_empty_2 dt_non_empty_3\ndt_non_empty_4).\nQed.\n\nLemma dt_non_empty_d :\nforall (d : preDTA) (a : ad) (t : term),\nreconnaissance d a t ->\nexists n : nat,\nMapGet bool (power (Map bool) (dta_app_ne d) (map_mini state d) n) a =\nSome true.\nProof. hammer_hook \"empty_test\" \"empty_test.dt_non_empty_d\".\nintros. split with (term_high t). exact (dt_non_empty_5 d a t H (term_high t) (le_n_n _)).\nQed.\n\nLemma dt_non_empty_7 :\nforall (d : preDTA) (p : prec_list) (t : term_list),\nliste_reconnait d p t ->\npl_non_empty\n(power (Map bool) (dta_app_ne d) (map_mini state d) (term_high_0 t)) p =\ntrue.\nProof. hammer_hook \"empty_test\" \"empty_test.dt_non_empty_7\".\nintros. exact (dt_non_empty_6 d p t H (term_high_0 t) (le_n_n _)).\nQed.\n\n\n\nLemma dt_non_empty_r_0 :\nforall (d : preDTA) (m r : Map bool) (a : ad) (l : state),\nMapGet state d a = Some l ->\ndomain_equal state bool d r ->\nMapGet bool (dta_app_ne_aux d m r) a = Some true ->\nMapGet bool r a = Some true \\/ st_non_empty m l = true.\nProof. hammer_hook \"empty_test\" \"empty_test.dt_non_empty_r_0\".\nsimple induction d. intros. inversion H. intros. induction  r as [| a2 a3| r1 Hrecr1 r0 Hrecr0].\ninversion H0. simpl in H0. rewrite H0 in H. rewrite H0 in H1.\nsimpl in H. elim (bool_is_true_or_false (N.eqb a2 a1)); intro; rewrite H2 in H. inversion H. simpl in H1. rewrite (Neqb_correct a2) in H1. simpl in H1. rewrite H2 in H1. inversion H1. rewrite H5.\nsimpl in |- *. rewrite H2. elim (bool_is_true_or_false a3); intros; rewrite H3. left. reflexivity. rewrite H3 in H5. simpl in H5.\nrewrite H4 in H5. right. exact H5. inversion H. inversion H0.\nintros. induction  r as [| a0 a1| r1 Hrecr1 r0 Hrecr0]. inversion H2. inversion H2. induction  a as [| p].\nsimpl in H1. simpl in |- *. simpl in H3. simpl in H2. elim H2. intros.\nexact (H _ _ _ _ H1 H4 H3). elim H2. intros. induction  p as [p Hrecp| p Hrecp| ]; simpl in |- *; simpl in H1;\nsimpl in H3. exact (H0 _ _ _ _ H1 H5 H3). exact (H _ _ _ _ H1 H4 H3). exact (H0 _ _ _ _ H1 H5 H3).\nQed.\n\nLemma dt_non_empty_r_1 :\nforall (s : state) (m : Map bool),\nst_non_empty m s = true ->\nexists c : ad,\n(exists p : prec_list,\nMapGet prec_list s c = Some p /\\ pl_non_empty m p = true).\nProof. hammer_hook \"empty_test\" \"empty_test.dt_non_empty_r_1\".\nsimple induction s; intros. simpl in H. inversion H. simpl in H.\nsplit with a. split with a0. split. simpl in |- *. rewrite (Neqb_correct a). reflexivity. exact H. simpl in H1.\nelim (bool_is_true_or_false (st_non_empty m1 m)); intros.\nelim (H m1 H2). intros. elim H3. intros. elim H4. intros.\ninduction  x as [| p]. split with N0. split with x0. simpl in |- *. split; assumption. split with (Npos (xO p)). split with x0. simpl in |- *.\nsplit; assumption. rewrite H2 in H1. simpl in H1. elim (H0 _ H1). intros. elim H3. intros. elim H4. intros. induction  x as [| p].\nsplit with (Npos 1). simpl in |- *. split with x0. split; assumption.\nsplit with (Npos (xI p)). split with x0. simpl in |- *. split; assumption.\nQed.\n\nLemma dt_non_empty_r_2 :\nforall (p : prec_list) (m : Map bool),\npl_non_empty m p = true ->\nexists pl : pl_path, pl_path_true pl m /\\ pl_path_incl pl p.\nProof. hammer_hook \"empty_test\" \"empty_test.dt_non_empty_r_2\".\nsimple induction p. intros. simpl in H1. elim (pl_sum p1). intros.\nrewrite H2 in H1. elim (option_sum bool (MapGet bool m a)).\nintro y. elim y. intros x y0. rewrite y0 in H1. elim (bool_is_true_or_false x); intros; rewrite H3 in H1; simpl in H1.\nelim (H m H1). intros. elim H4. intros. rewrite H3 in y0.\nsplit with (pl_path_cons a x0). split. exact (plp_true_cons m a x0 H5 y0). exact (pl_path_incl_cons x0 a p0 p1 H6). inversion H1. intro y. rewrite y in H1. inversion H1. intros. elim H2.\nintros. elim H3. intros. elim H4. intros. rewrite H5 in H1.\nelim (option_sum bool (MapGet bool m a)); intro y. elim y. intros x2 y0.\nrewrite y0 in H1. rewrite <- H5 in H1. elim (bool_is_true_or_false (pl_non_empty m p1)); intros. elim (H0 _ H6). intros. elim H7.\nintros. split with x3. split. exact H8. apply (pl_path_incl_next x3 a p0 p1 H9). intro. rewrite H10 in H9. inversion H9. rewrite <- H12 in H5. inversion H5. elim (H12 (refl_equal _)).\nrewrite H6 in H1. simpl in H1. elim (bool_is_true_or_false x2); intro. rewrite H7 in y0. elim (bool_is_true_or_false (pl_non_empty m p0)); intro. elim (H _ H8). intros. elim H9. intros. split with (pl_path_cons a x3). split. exact (plp_true_cons _ _ _ H10 y0).\nexact (pl_path_incl_cons x3 a p0 p1 H11). rewrite H8 in H1.\nrewrite H7 in H1. inversion H1. rewrite H7 in H1. inversion H1.\nrewrite y in H1. rewrite <- H5 in H1. elim (H0 _ H1). intros.\nelim H6. intros. split with x2. split. exact H7. apply (pl_path_incl_next x2 a p0 p1 H8). intro. rewrite H9 in H8.\ninversion H8. rewrite <- H11 in H5. inversion H5. elim H11.\nreflexivity. intros. split with pl_path_nil. split. exact (plp_true_nil m). exact pl_path_incl_nil.\nQed.\n\nDefinition dt_non_empty_r_def_0 (n : nat) : Prop :=\nforall (d : preDTA) (a : ad),\nMapGet bool (power (Map bool) (dta_app_ne d) (map_mini state d) n) a =\nSome true -> exists t : term, reconnaissance d a t.\n\nLemma dt_non_empty_r_3 : dt_non_empty_r_def_0 0.\nProof. hammer_hook \"empty_test\" \"empty_test.dt_non_empty_r_3\".\nunfold dt_non_empty_r_def_0 in |- *. simpl in |- *. intros. cut (true <> false).\nintro. elim (H0 (map_mini_mapget_false state d a true H)).\nintro. inversion H0.\nQed.\n\nLemma dt_non_empty_r_4 :\nforall (p : prec_list) (n : nat) (d : preDTA) (pl : pl_path),\ndt_non_empty_r_def_0 n ->\npl_path_true pl (power (Map bool) (dta_app_ne d) (map_mini state d) n) ->\npl_path_incl pl p -> exists tl : term_list, liste_reconnait d p tl.\nProof. hammer_hook \"empty_test\" \"empty_test.dt_non_empty_r_4\".\nunfold dt_non_empty_r_def_0 in |- *. simple induction p. intros.\ninversion H2. inversion H3.\nrewrite <- H4 in H7. inversion H7.\nelim H11; auto.\nelim (H1 _ _ H5). intros. inversion H3. rewrite <- H10 in H6.\ninversion H6. rewrite <- H10 in H2.\ninversion H2. elim (H n d plp H1 H18 H11).\nintros. split with (tcons x x0).\nrewrite H15 in H8. rewrite H9 in H8.\nexact (rec_consi d a p0 p1 x x0 H8 H21).\nelim (H0 n d pl H1 H2 H12). intros. induction  x0 as [| t x0 Hrecx0].\ninversion H15. rewrite <- H17 in H12. inversion H12. elim H14; auto.\nsplit with (tcons t x0). exact (rec_consn d a p0 p1 t x0 H15).\nintros. inversion H1. split with tnil. exact (rec_empty d).\nQed.\n\nLemma dt_non_empty_r_5 :\nforall n : nat, dt_non_empty_r_def_0 n -> dt_non_empty_r_def_0 (S n).\nProof. hammer_hook \"empty_test\" \"empty_test.dt_non_empty_r_5\".\nunfold dt_non_empty_r_def_0 in |- *. intros. elim\n(domain_equal_mapget bool state\n(power (Map bool) (dta_app_ne d) (map_mini state d) (S n)) d a true). intros. unfold dta_app_ne in H0.  simpl in H0. elim\n(dt_non_empty_r_0 d\n(power (Map bool) (fun m : Map bool => dta_app_ne_aux d m m)\n(map_mini state d) n)\n(power (Map bool) (fun m : Map bool => dta_app_ne_aux d m m)\n(map_mini state d) n) a x H1); intros. exact (H d a H2). elim (dt_non_empty_r_1 _ _ H2). intros. elim H3. intros. elim H4. intros. elim (dt_non_empty_r_2 _ _ H6). intros. elim H7. intros.\nelim (dt_non_empty_r_4 x1 n d x2 H H8 H9). intros.\nsplit with (app x0 x3). exact (rec_dta d a (app x0 x3) x H1 (rec_st d x x0 x3 x1 H5 H10)). apply\n(power_def_ok bool (ensemble_base state d) (dta_app_ne d)\n(map_mini state d) n).\nexact (dta_app_ne_def_ok d). exact (map_mini_appartient state d). exact H0. apply\n(domain_equal_symmetric state bool d\n(power (Map bool) (dta_app_ne d) (map_mini state d) (S n))). exact\n(power_def_ok bool (ensemble_base state d) (dta_app_ne d)\n(map_mini state d) (S n) (dta_app_ne_def_ok d)\n(map_mini_appartient state d)). exact H0.\nQed.\n\nLemma dt_non_empty_r :\nforall (n : nat) (d : preDTA) (a : ad),\nMapGet bool (power (Map bool) (dta_app_ne d) (map_mini state d) n) a =\nSome true -> exists t : term, reconnaissance d a t.\nProof. hammer_hook \"empty_test\" \"empty_test.dt_non_empty_r\".\nexact (nat_ind dt_non_empty_r_def_0 dt_non_empty_r_3 dt_non_empty_r_5).\nQed.\n\nLemma dt_non_empty_fix_0 :\nforall d : preDTA,\nlower_fix_point bool (ensemble_base state d) lem (dta_app_ne d)\n(dta_non_empty_states d).\nProof. hammer_hook \"empty_test\" \"empty_test.dt_non_empty_fix_0\".\nunfold dta_non_empty_states in |- *.\nintros. exact\n(iteres_lower_fix_point bool (ensemble_base state d) lem\n(dta_app_ne d) (map_mini state d) (S (MapCard state d))\n(S (MapCard state d)) (map_mini_mini state d)\n(dta_app_ne_def_ok d) (dta_app_ne_inc d) (lattice_bounded state d)\n(le_n_n _)).\nQed.\n\nLemma dt_non_empty_fix_1 :\nforall (d : preDTA) (a : ad) (n : nat),\nMapGet bool (power (Map bool) (dta_app_ne d) (map_mini state d) n) a =\nSome true -> MapGet bool (dta_non_empty_states d) a = Some true.\nProof. hammer_hook \"empty_test\" \"empty_test.dt_non_empty_fix_1\".\nintros. elim\n(domain_equal_mapget bool bool\n(power (Map bool) (dta_app_ne d) (map_mini state d) n)\n(dta_non_empty_states d) a true).\nintros. elim (bool_is_true_or_false x); intro; rewrite H1 in H0.\nexact H0. elim (dt_non_empty_fix_0 d). intros. unfold inf_fix_points in H3. elim\n(lem_get_leb _ _ _ _ _\n(iteres_inf_fps bool (ensemble_base state d) lem\n(dta_app_ne d) (map_mini state d) (dta_non_empty_states d) n\n(map_mini_mini state d) H2 (dta_app_ne_inc d)) H H0). apply\n(domain_equal_transitive bool state bool\n(power (Map bool) (dta_app_ne d) (map_mini state d) n) d\n(dta_non_empty_states d)). exact\n(domain_equal_symmetric state bool _ _\n(power_def_ok bool (ensemble_base state d) (dta_app_ne d)\n(map_mini state d) n (dta_app_ne_def_ok d)\n(map_mini_appartient state d))). unfold dta_non_empty_states in |- *.\nexact\n(power_def_ok bool (ensemble_base state d) (dta_app_ne d)\n(map_mini state d) (S (MapCard state d)) (dta_app_ne_def_ok d)\n(map_mini_appartient state d)). exact H.\nQed.\n\nLemma dt_non_empty_fix_2 :\nforall (d : preDTA) (a : ad),\nMapGet bool (dta_non_empty_states d) a = Some true ->\nexists n : nat,\nMapGet bool (power (Map bool) (dta_app_ne d) (map_mini state d) n) a =\nSome true.\nProof. hammer_hook \"empty_test\" \"empty_test.dt_non_empty_fix_2\".\nunfold dta_non_empty_states in |- *. intros. split with (S (MapCard state d)). exact H.\nQed.\n\n\n\nLemma dt_non_empty_fix :\nforall (d : preDTA) (a : ad),\nMapGet bool (dta_non_empty_states d) a = Some true <->\n(exists t : term, reconnaissance d a t).\nProof. hammer_hook \"empty_test\" \"empty_test.dt_non_empty_fix\".\nintros. split. intros. elim (dt_non_empty_fix_2 d a H).\nintros. exact (dt_non_empty_r _ _ _ H0). intros. elim H.\nintros. elim (dt_non_empty_d d a x H0). intros. exact (dt_non_empty_fix_1 _ _ _ H1).\nQed.\n\nLemma dt_non_empty_lazy_fix :\nforall (d : preDTA) (a : ad),\nMapGet bool (dta_non_empty_states_lazy d) a = Some true <->\n(exists t : term, reconnaissance d a t).\nProof. hammer_hook \"empty_test\" \"empty_test.dt_non_empty_lazy_fix\".\nintro. unfold dta_non_empty_states_lazy in |- *. rewrite\n(lazy_power_eg_power bool eqm_bool (dta_app_ne d)\n(map_mini state d) (S (MapCard state d))). exact (dt_non_empty_fix d). split. exact (eqm_bool_equal a b). intro. rewrite H. exact (equal_eqm_bool b).\nQed.\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/tree-automata/empty_test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2948360746954289}}
{"text": "Require Import floyd.proofauto.\nImport ListNotations.\nLocal Open Scope logic.\n\nRequire Import hmac_drbg.\nRequire Import spec_hmac_drbg.\nRequire Import HMAC_DRBG_update.\nRequire Import sha.HMAC256_functional_prog.\nRequire Import sha.spec_sha.\n\nFixpoint HMAC_DRBG_update_round (HMAC: list Z -> list Z -> list Z) (provided_data K V: list Z) (round: nat): (list Z * list Z) :=\n  match round with\n    | O => (K, V)\n    | S round' =>\n      let (K, V) := HMAC_DRBG_update_round HMAC provided_data K V round' in\n      let K := HMAC (V ++ [Z.of_nat round'] ++ provided_data) K in\n      let V := HMAC V K in\n      (K, V)\n  end.\n\nDefinition HMAC_DRBG_update_concrete (HMAC: list Z -> list Z -> list Z) (provided_data K V: list Z): (list Z * list Z) :=\n  let rounds := match provided_data with\n                  | [] => 1%nat\n                  | _ => 2%nat\n                end in\n  HMAC_DRBG_update_round HMAC provided_data K V rounds.\n\nTheorem HMAC_DRBG_update_concrete_correct:\n  forall HMAC provided_data K V, HMAC_DRBG_update HMAC provided_data K V = HMAC_DRBG_update_concrete HMAC provided_data K V.\nProof.\n  intros.\n  destruct provided_data; reflexivity.\nQed.\n\nDefinition update_rounds (non_empty_additional: bool): Z :=\n  if non_empty_additional then 2 else 1.\n\nLemma HMAC_DRBG_update_round_incremental:\n  forall key V initial_state_abs contents n,\n    (key, V) = HMAC_DRBG_update_round HMAC256 contents\n                           (hmac256drbgabs_key initial_state_abs)\n                           (hmac256drbgabs_value initial_state_abs) n ->\n    (HMAC256 (V ++ (Z.of_nat n) :: contents) key,\n     HMAC256 V (HMAC256 (V ++ (Z.of_nat n) :: contents) key)) =\n    HMAC_DRBG_update_round HMAC256 contents\n                           (hmac256drbgabs_key initial_state_abs)\n                           (hmac256drbgabs_value initial_state_abs) (n + 1).\nProof.\n  intros.\n  rewrite plus_comm.\n  simpl.\n  rewrite <- H.\n  reflexivity.\nQed.\n\nLemma HMAC_DRBG_update_round_incremental_Z:\n  forall key V initial_state_abs contents i,\n    0 <= i ->\n    (key, V) = HMAC_DRBG_update_round HMAC256 contents\n                           (hmac256drbgabs_key initial_state_abs)\n                           (hmac256drbgabs_value initial_state_abs) (Z.to_nat i) ->\n    (HMAC256 (V ++ i :: contents) key,\n     HMAC256 V (HMAC256 (V ++ i :: contents) key)) =\n    HMAC_DRBG_update_round HMAC256 contents\n                           (hmac256drbgabs_key initial_state_abs)\n                           (hmac256drbgabs_value initial_state_abs) (Z.to_nat (i + 1)).\nProof.\n  intros.\n  rewrite <- (Z2Nat.id i) at 1 2 by assumption.\n  rewrite Z2Nat.inj_add by (try assumption; try omega).\n  simpl.\n  apply HMAC_DRBG_update_round_incremental; assumption.\nQed.\n\nLemma body_hmac_drbg_update: semax_body HmacDrbgVarSpecs HmacDrbgFunSpecs \n       f_mbedtls_hmac_drbg_update hmac_drbg_update_spec.\nProof.\n  start_function.\n  name ctx' _ctx.\n  name add_len' _add_len.\n  name additional' _additional.\n  rename lvar0 into sep.\n  rename lvar1 into K.\n\n  (* info = md_ctx.md_info *)\n  forward.\n\n  (* md_len = mbedtls_md_get_size( info ); *)\n  forward_call tt.\n\n  Intros md_len.\n\n  (* rounds = ( additional != NULL && add_len != 0 ) ? 2 : 1; *)\n  remember (if eq_dec add_len 0 then false else if eq_dec additional nullval then false else true) as non_empty_additional.\n  forward_if (\n      PROP  ()\n      LOCAL  (temp _md_len md_len; lvar _K (tarray tuchar 32) K;\n      temp _ctx ctx;\n      lvar _sep (tarray tuchar 1) sep;\n      temp _additional additional; temp _add_len (Vint (Int.repr add_len));\n      temp 140%positive (Val.of_bool non_empty_additional);\n      gvar sha._K256 kv\n             )\n      SEP  ((data_at_ Tsh (tarray tuchar 32) K);\n      (data_at_ Tsh (tarray tuchar 1) sep);\n      (data_at Tsh (tarray tuchar add_len)\n          (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\n          (hmac256drbgstate_md_info_pointer initial_state));\n      (K_vector kv)\n       )\n    ).\n  {\n    (* show that add_len <> 0 implies the post condition *)\n    forward.\n    {\n      entailer!.\n      assert (sizeof cenv_cs (tarray tuchar (Zlength contents)) > 0).\n      {\n        simpl.\n        destruct contents.\n        assert (contra: False) by (apply H5; reflexivity); inversion contra.\n        clear.\n        repeat rewrite Zlength_map. rewrite Zlength_cons.\n        assert (0 <= Zlength contents) by (apply Zlength_nonneg).\n        destruct (Zlength contents).\n        simpl; omega.\n        hnf; auto.\n        assert (contra: False) by (apply H; reflexivity); inversion contra.\n      }\n      apply denote_tc_comparable_split; auto 50 with valid_pointer.\n      (* TODO regressoin, this should have solved it *) \n      (*\n      apply sepcon_valid_pointer1.\n      apply sepcon_valid_pointer1.\n      apply sepcon_valid_pointer1.\n      apply sepcon_valid_pointer1.\n      apply sepcon_valid_pointer1.\n      apply sepcon_valid_pointer2.\n      apply data_at_valid_ptr; auto. *)\n    }\n    entailer!.\n    repeat rewrite Zlength_map in *.\n    destruct (eq_dec (Zlength contents) 0) as [zlength_eq | zlength_neq].\n    assert (contra: False) by (apply H5; apply zlength_eq); inversion contra.\n    destruct additional'; try solve [inversion TC1]. \n    {\n      inv TC1.\n      destruct (eq_dec (Vint Int.zero) nullval) as [additional_eq | additional_neq].\n      auto.\n      assert (contra: False) by (apply additional_neq; reflexivity); inversion contra.\n    }\n    {\n      destruct (eq_dec (Vptr b i) nullval) as [additional_eq | additional_neq].\n      inversion additional_eq.\n      auto.\n    }\n  }\n\n  {\n    (* show that add_len = 0 implies the post condition *)\n    forward.\n    entailer!. rewrite H5.\n    auto.\n  }\n\n  remember (update_rounds non_empty_additional) as rounds. unfold update_rounds in Heqrounds.\n  \n  forward_if (\n      PROP  ()\n      LOCAL  (temp _md_len md_len; lvar _K (tarray tuchar 32) K;\n      temp _ctx ctx;\n      lvar _sep (tarray tuchar 1) sep;\n      temp _additional additional; temp _add_len (Vint (Int.repr add_len));\n      temp 141%positive (Vint (Int.repr rounds));\n      gvar sha._K256 kv\n             )\n      SEP  ((data_at_ Tsh (tarray tuchar 32) K);\n      (data_at_ Tsh (tarray tuchar 1) sep);\n      (data_at Tsh (tarray tuchar add_len)\n          (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\n                (hmac256drbgstate_md_info_pointer initial_state)); \n      (K_vector kv)\n      )\n  ).\n  {\n    (* non_empty_additional = true *)\n    forward.\n    entailer!.\n  }\n  {\n    (* non_empty_additional = false *)\n    forward.\n    entailer!.\n  }\n  forward.\n\n  remember (hmac256drbgabs_key initial_state_abs) as initial_key.\n  remember (hmac256drbgabs_value initial_state_abs) as initial_value.\n  (* verif_sha_final2.v, @exp (environ -> mpred) *)\n  (* for ( sep_value = 0; sep_value < rounds; sep_value++ ) *)\n  Time forward_for_simple_bound rounds (\n                              EX i: Z,\n      PROP  (\n      (* (key, value) = HMAC_DRBG_update_round HMAC256 (map Int.signed contents) old_key old_value 0 (Z.to_nat i);\n      (*\n      le i (update_rounds non_empty_additional);\n       *)\n      key = hmac256drbgabs_key final_state_abs;\n      value = hmac256drbgabs_value final_state_abs;\n      hmac256drbgabs_metadata_same final_state_abs state_abs *)\n        ) \n      LOCAL (\n       temp _md_len md_len;\n       temp _ctx ctx;\n       lvar _K (tarray tuchar 32) K; lvar _sep (tarray tuchar 1) sep;\n       temp _additional additional; temp _add_len (Vint (Int.repr add_len));\n       gvar sha._K256 kv\n         )\n      SEP  (\n        (EX key: list Z, EX value: list Z, EX final_state_abs: hmac256drbgabs,\n          !!(\n              (key, value) = HMAC_DRBG_update_round HMAC256 contents initial_key initial_value (Z.to_nat i)\n              /\\ key = hmac256drbgabs_key final_state_abs\n              /\\ value = hmac256drbgabs_value final_state_abs\n              /\\ hmac256drbgabs_metadata_same final_state_abs initial_state_abs\n              /\\ Zlength value = Z.of_nat SHA256.DigestLength\n              /\\ Forall general_lemmas.isbyteZ value\n            ) &&\n           (hmac_drbg_update_post final_state_abs initial_state ctx info_contents)\n         );\n        (* `(update_relate_final_state ctx final_state_abs); *)\n        (data_at_ Tsh (tarray tuchar 32) K);\n        (data_at Tsh (tarray tuchar add_len) (map Vint (map Int.repr contents)) additional);\n        (data_at_ Tsh (tarray tuchar 1) sep );\n        (K_vector kv)\n         )\n  ). (* 2 *)\n  {\n    (* Int.min_signed <= 0 <= rounds *)\n    rewrite Heqrounds; destruct non_empty_additional; auto.\n  }\n  {\n    (* rounds <= Int.max_signed *)\n    rewrite Heqrounds; destruct non_empty_additional; auto.\n  }\n  {\n    (* pre conditions imply loop invariant *)\n    unfold hmac_drbg_update_post.\n    Exists (hmac256drbgabs_key initial_state_abs) (hmac256drbgabs_value initial_state_abs) initial_state_abs.\n    destruct initial_state_abs.\n    destruct initial_state as [md_ctx0' [V0' [reseed_counter0' [entropy_len0' [prediction_resistance0' reseed_interval0']]]]].\n    unfold hmac256drbgabs_to_state.\n    entailer!.\n  }\n  {\n    (* loop body *)\n    change (`(eq (Vint (Int.repr rounds))) (eval_expr (Etempvar _rounds tint))) with (temp _rounds (Vint (Int.repr rounds))).\n    unfold hmac_drbg_update_post. unfold hmac256drbgabs_to_state.\n    Intros key value state_abs.\n    unfold_data_at 1%nat.\n    rewrite (field_at_data_at _ _ [StructField _md_ctx]); simpl.\n    rewrite (field_at_data_at _ _ [StructField _V]); simpl.\n\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    assert (Hfield_V: forall ctx', isptr ctx' -> field_compatible t_struct_hmac256drbg_context_st [StructField _V] ctx' -> offset_val (Int.repr 12) ctx' = field_address t_struct_hmac256drbg_context_st [StructField _V] ctx').\n    {\n      intros ctx'' Hisptr Hfc.\n      unfold field_address.\n      destruct (field_compatible_dec t_struct_hmac256drbg_context_st); [reflexivity|contradiction].\n    }\n    destruct state_abs.\n    destruct initial_state as [md_ctx [V' [reseed_counter' [entropy_len' [prediction_resistance' reseed_interval']]]]]. simpl in H7; subst key0.\n    unfold hmac256drbg_relate. unfold md_full.\n    Intros.\n    simpl in H8.\n    subst value.\n    assert (Hmdlen_V: md_len = Vint (Int.repr (Zlength V))) by (subst md_len; rewrite H10; reflexivity).\n\n    (* sep[0] = sep_value; *)\n    forward.\n\n    (* mbedtls_md_hmac_reset( &ctx->md_ctx ); *)\n    Time forward_call (field_address t_struct_hmac256drbg_context_st [StructField _md_ctx] ctx, md_ctx, key, kv). (* 79 *)\n    {\n      entailer!.\n    }\n    Intros v; subst v.\n\n    (* mbedtls_md_hmac_update( &ctx->md_ctx, ctx->V, md_len ); *)\n    Time forward_call (key, field_address t_struct_hmac256drbg_context_st [StructField _md_ctx] ctx, md_ctx, field_address t_struct_hmac256drbg_context_st [StructField _V] ctx, @nil Z, V, kv). (* 83 *)\n    {\n      entailer!.\n      rewrite H10; reflexivity.\n    }\n    {\n      rewrite H10.\n      change (Z.of_nat SHA256.DigestLength) with 32.\n      cancel.\n    }\n    {\n      rewrite H10.\n      idtac.\n      repeat split; [hnf;auto | hnf;auto | assumption].\n    }\n    Intros v; subst v.\n      \n    unfold upd_Znth.\n    unfold sublist. simpl.\n    assert (Hiuchar: Int.zero_ext 8 (Int.repr i) = Int.repr i).\n    {\n      clear - H5 Heqrounds. destruct non_empty_additional; subst;\n      apply zero_ext_inrange;\n      rewrite hmac_pure_lemmas.unsigned_repr_isbyte by (hnf; omega); simpl; omega.\n    }\n    rewrite Hiuchar.\n\n    (* mbedtls_md_hmac_update( &ctx->md_ctx, sep, 1 ); *)\n    Time forward_call (key, field_address t_struct_hmac256drbg_context_st [StructField _md_ctx] ctx, md_ctx, sep, V, [i], kv). (* 62 *)\n    {\n      entailer!.\n    }\n    {\n      (* prove the PROP clauses *)\n      rewrite H10.\n      change (Zlength [i]) with 1.\n      repeat split; [hnf;auto | hnf;auto | ].\n      unfold general_lemmas.isbyteZ.\n      repeat constructor.\n      omega.\n      destruct non_empty_additional; subst rounds; omega.\n    }\n    Intros v; subst v.\n      \n    (* if( rounds == 2 ) *)\n    Time forward_if (\n      PROP  ()\n      LOCAL  (temp _sep_value (Vint (Int.repr i));\n      temp _rounds (Vint (Int.repr rounds)); temp _md_len md_len;\n      temp _ctx ctx; lvar _K (tarray tuchar (Zlength V)) K;\n      lvar _sep (tarray tuchar 1) sep; temp _additional additional;\n      temp _add_len (Vint (Int.repr add_len)); gvar sha._K256 kv)\n      SEP  ((md_relate (hABS key (V ++ [i] ++ contents)) md_ctx);\n      (data_at Tsh t_struct_md_ctx_st md_ctx\n          (field_address t_struct_hmac256drbg_context_st\n             [StructField _md_ctx] ctx));\n      (data_at Tsh (tarray tuchar (Zlength [i])) [Vint (Int.repr i)] sep);\n      (K_vector kv);\n      (data_at Tsh (tarray tuchar (Zlength V)) (map Vint (map Int.repr V))\n          (field_address t_struct_hmac256drbg_context_st [StructField _V] ctx));\n      (field_at Tsh t_struct_hmac256drbg_context_st\n          [StructField _reseed_counter] (Vint (Int.repr reseed_counter)) ctx);\n      (field_at Tsh t_struct_hmac256drbg_context_st\n          [StructField _entropy_len] (Vint (Int.repr entropy_len)) ctx);\n      (field_at Tsh t_struct_hmac256drbg_context_st\n          [StructField _prediction_resistance] (Val.of_bool prediction_resistance) ctx);\n      (field_at Tsh t_struct_hmac256drbg_context_st\n          [StructField _reseed_interval] (Vint (Int.repr reseed_interval))\n          ctx);\n      (data_at Tsh t_struct_mbedtls_md_info info_contents\n          (hmac256drbgstate_md_info_pointer\n             (md_ctx,\n         (V',\n         (reseed_counter',\n         (entropy_len', (Val.of_bool prediction_resistance, reseed_interval')))))));\n      (data_at_ Tsh (tarray tuchar (Zlength V)) K);\n      (data_at Tsh (tarray tuchar (Zlength contents))\n          (map Vint (map Int.repr contents)) additional)) \n    ). (* 42 *)\n    {\n      \n      (* rounds = 2 case *)\n      rewrite H1.\n\n      (* mbedtls_md_hmac_update( &ctx->md_ctx, additional, add_len ); *)\n      Time forward_call (key, field_address t_struct_hmac256drbg_context_st [StructField _md_ctx] ctx, md_ctx, additional, V ++ [i], contents, kv). (* 63 *)\n      {\n        (* prove the parameters match up *)\n        entailer!.\n      }\n      {\n        (* prove the PROP clause matches *)\n        rewrite H1 in *. repeat split; [omega | omega | | assumption].\n        rewrite Zlength_app; rewrite H10.\n        simpl. remember (Zlength contents) as n; clear - H.\n        destruct H. rewrite <- Zplus_assoc.\n        unfold Int.max_unsigned in H0.\n        rewrite hmac_pure_lemmas.IntModulus32 in H0; rewrite two_power_pos_equiv.\n        simpl. simpl in H0.\n        assert (H1: Z.pow_pos 2 61 = 2305843009213693952) by reflexivity; rewrite H1; clear H1.\n        omega.\n      }\n      (* prove the post condition of the if statement *)\n      rewrite <- app_assoc.\n      Intros v.\n      rewrite H10.\n      entailer!.\n    }\n    {\n      (* rounds <> 2 case *)\n      forward.\n      rewrite H10.\n      entailer!.\n      destruct contents.\n      entailer!.\n\n      (* contents not empty, which is a contradiction *)\n      rewrite Zlength_cons in H7.\n      destruct (eq_dec (Z.succ (Zlength contents)) 0) as [Zlength_eq | Zlength_neq].\n      assert (0 <= Zlength contents) by (apply Zlength_nonneg).\n      destruct (Zlength contents); [inversion Zlength_eq| omega | omega].\n\n      assert (Hisptr: isptr additional') by auto.\n      destruct (eq_dec additional' nullval) as [additional_null | additional_not_null].\n      subst. inversion Hisptr.\n      assert (contra: False) by (apply H7; reflexivity); inversion contra.\n    }\n    rewrite H10.\n\n    (* mbedtls_md_hmac_finish( &ctx->md_ctx, K ); *)\n    rewrite data_at__memory_block. change (sizeof cenv_cs (tarray tuchar 32)) with 32.\n    Intros.\n    Time forward_call ((V ++ [i] ++ contents), key, field_address t_struct_hmac256drbg_context_st [StructField _md_ctx] ctx, md_ctx, K, Tsh, kv). (* 62 *)\n    {\n      (* prove the parameters match up *)\n      entailer!.\n    }\n    {\n      change (sizeof cenv_cs (tarray tuchar (Z.of_nat SHA256.DigestLength))) with 32.\n      cancel.\n    }\n    Intros new_key.\n\n    assert_PROP (isptr K) as HisptrK by entailer!. \n    destruct K; try solve [inversion HisptrK].\n    replace_SEP 1 (UNDER_SPEC.EMPTY (snd (snd md_ctx))) by (entailer!; apply UNDER_SPEC.FULL_EMPTY).\n\n    (* mbedtls_md_hmac_starts( &ctx->md_ctx, K, md_len ); *)\n    Time forward_call (field_address t_struct_hmac256drbg_context_st [StructField _md_ctx] ctx, md_ctx, (Zlength (HMAC256 (V ++ [i] ++ contents) key)), HMAC256 (V ++ [i] ++ contents) key, kv, b, i0). (* 75 *)\n    {\n      (* prove the function parameters match up *)\n      entailer!. rewrite hmac_common_lemmas.HMAC_Zlength. reflexivity.\n    }\n    {\n      split.\n      {\n        (* prove that output of HMAC can serve as its key *)\n        unfold spec_hmacNK.has_lengthK; simpl.\n        repeat split; try reflexivity; rewrite hmac_common_lemmas.HMAC_Zlength;\n        hnf; auto.\n      }\n      {\n        (* prove that the output of HMAC are bytes *)\n        apply hmac_common_lemmas.isbyte_hmac.\n      }\n    }\n    Intros v; subst v.\n\n    (* mbedtls_md_hmac_update( &ctx->md_ctx, ctx->V, md_len ); *)\n    Time forward_call (HMAC256 (V ++ [i] ++ contents) key, field_address t_struct_hmac256drbg_context_st [StructField _md_ctx] ctx, md_ctx, field_address t_struct_hmac256drbg_context_st [StructField _V] ctx, @nil Z, V, kv). (* 72 *)\n    {\n      (* prove the function parameters match up *)\n      entailer!. rewrite H10; reflexivity.\n    }\n    {\n      (* prove the function SEP clauses match up *)\n      rewrite H10; cancel.\n    }\n    {\n      (* prove the PROP clauses *)\n      rewrite H10.\n      repeat split; [hnf;auto | hnf;auto | assumption].\n    }\n    Intros v; subst v.\n    rewrite H10.\n    normalize.\n    replace_SEP 2 (memory_block Tsh (sizeof cenv_cs (tarray tuchar 32)) (field_address t_struct_hmac256drbg_context_st [StructField _V] ctx)) by (entailer!; apply data_at_memory_block).\n    simpl.\n    (* mbedtls_md_hmac_finish( &ctx->md_ctx, ctx->V ); *)\n    Time forward_call (V, HMAC256 (V ++ i::contents) key, field_address t_struct_hmac256drbg_context_st [StructField _md_ctx] ctx, md_ctx, field_address t_struct_hmac256drbg_context_st [StructField _V] ctx, Tsh, kv). (* 75 *)\n    {\n      (* prove the function parameters match up *)\n      entailer!.\n    }\n    Intros new_V.\n    unfold hmac_drbg_update_post, hmac256drbgabs_to_state.\n    Exists (HMAC256 (V ++ [i] ++ contents) key) (HMAC256 V (HMAC256 (V ++ [i] ++ contents) key))    (HMAC256DRBGabs (HMAC256 (V ++ [i] ++ contents) key) (HMAC256 V (HMAC256 (V ++ [i] ++ contents) key)) reseed_counter entropy_len prediction_resistance reseed_interval).\n    Time entailer!. (* 335 ! *)\n    {\n      split; [| apply hmac_common_lemmas.HMAC_Zlength].\n      (* prove that the new key and value is what we expect *)\n      clear - H5 H6; destruct H5; simpl in H6.\n      apply HMAC_DRBG_update_round_incremental_Z; assumption.\n    }\n    unfold hmac256drbgstate_md_FULL.\n    unfold_data_at 4%nat.\n    unfold hmac256drbg_relate;\n    rewrite (field_at_data_at _ _ [StructField _md_ctx]);\n    rewrite (field_at_data_at _ _ [StructField _V]); simpl.\n    repeat rewrite hmac_common_lemmas.HMAC_Zlength.\n    unfold md_full.\n    Time entailer!. (* 15 *)\n  }\n  (* return *)\n  forward.\n\n  (* prove function post condition *)\n  Exists K sep.\n  unfold hmac256drbgabs_hmac_drbg_update.\n  unfold HMAC256_DRBG_functional_prog.HMAC256_DRBG_update.\n  destruct initial_state_abs.\n  rewrite HMAC_DRBG_update_concrete_correct.\n  Time entailer!. (* 29 *)\n  {\n    (*\n    rename H1 into Hupdate_rounds.\n    rename H6 into Hmetadata.\n    destruct final_state_abs; unfold hmac256drbgabs_metadata_same in Hmetadata.\n    destruct Hmetadata as [Hreseed_counter [Hentropy_len [Hpr Hrseed_interval]]]; subst.\n*)\n    destruct contents; unfold HMAC_DRBG_update_concrete;\n    simpl;\n    split; try apply hmac_common_lemmas.HMAC_Zlength; try apply hmac_common_lemmas.isbyte_hmac.\n  }\n  rename H1 into Hupdate_rounds.\n  rename H6 into Hmetadata.\n  destruct final_state_abs; unfold hmac256drbgabs_metadata_same in Hmetadata.\n  destruct Hmetadata as [Hreseed_counter [Hentropy_len [Hpr Hrseed_interval]]]; subst.\n  replace (HMAC_DRBG_update_concrete HMAC256 contents key V) with (key0, V0).\n  cancel.\n  unfold hmac256drbgabs_key, hmac256drbgabs_value in Hupdate_rounds.\n  rewrite Hupdate_rounds. unfold HMAC_DRBG_update_concrete.\n  replace (Z.to_nat\n        (if if eq_dec (Zlength contents) 0\n            then false\n            else if eq_dec additional' nullval then false else true\n         then 2\n         else 1)) with (match contents with | [] => 1%nat | _ => 2%nat end).\n  reflexivity.\n  destruct contents.\n  {\n    reflexivity.\n  }\n  {\n    destruct (eq_dec (Zlength (z :: contents)) 0) as [Zlength_eq | Zlength_neq].\n    rewrite Zlength_cons, Zlength_correct in Zlength_eq; omega.\n    destruct (eq_dec additional' nullval) as [additional_eq | additional_neq].\n    subst. repeat rewrite Zlength_map in H10; inversion H10 as [isptr_null H']; inversion isptr_null.\n    reflexivity.\n  }\nTime Qed. (* 1018 !!! *)", "meta": {"author": "k-qy", "repo": "HMAC-DRBG", "sha": "2fc871f5b715f703eef3e855fca3df282090d2a5", "save_path": "github-repos/coq/k-qy-HMAC-DRBG", "path": "github-repos/coq/k-qy-HMAC-DRBG/HMAC-DRBG-2fc871f5b715f703eef3e855fca3df282090d2a5/specs/verif_hmac_drbg_update.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.679178686187839, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.29475096109538573}}
{"text": "From Undecidability.L Require Export Tactics.Computable.\n\n(* ** Time bounds *)\n\nFixpoint timeComplexity t (tt: TT t) : Type :=\n  match tt with\n    ! _ => unit\n  | @TyArr t1 t2 tt1 tt2 => t1 -> timeComplexity tt1 -> (nat*timeComplexity tt2)\n  end.\n\nArguments timeComplexity : clear implicits.\nArguments timeComplexity _ {_}.\n\nFixpoint computesTime {t} (ty : TT t) :  forall (x:t) (xInt :term) (xTime :timeComplexity t), Type :=\n  match ty with\n    !_ => fun x xInt _=> xInt = enc x\n  | @TyArr t1 t2 tt1 tt2 =>\n    fun f fInt fTime =>\n      proc fInt * \n      forall (y : t1) yInt (yTime:timeComplexity t1),\n        computesTime y yInt yTime\n        -> let fyTime := fTime y yTime in\n          {v : term & (redLe (fst fyTime) (app fInt yInt) v) * computesTime (f y) v (snd fyTime)}\n  end%type.\n\nArguments computesTime {_} _ _ _ _.\n\nClass computableTime {X : Type} (ty : TT X) (x : X) evalTime: Type :=\n  {\n    extT : extracted x;\n    extTCorrect : computesTime ty x extT evalTime\n  }.\n\n\nGlobal Arguments computableTime {X} {ty} x.\nGlobal Arguments extT {X} {ty} x {_ computableTime} : simpl never.\nGlobal Arguments extTCorrect {X} ty x {_ computableTime} : simpl never.\nDefinition evalTime X ty x evalTime (computableTime : @computableTime X ty x evalTime):=evalTime.\nGlobal Arguments evalTime {X} {ty} x {evalTime computableTime}.\n\n#[export] Hint Extern 3 (@extracted ?t ?f) => let ty := constr:(_ : TT t) in notypeclasses refine (extT (ty:=ty) f) : typeclass_instances.\n#[export] Hint Mode computableTime + - + -: typeclass_instances. (* treat argument as input and force evar-freeness*)\n\n(* A Notation to allow inference of the TT parameter for function types. Coq checks that functions only appear at positions where functions are allowed before it inferes holes, so t complains that f \"is a product while it is expected to be '@timeComplexity (forall _ : _, _) ?ty'\". *)\nNotation \"'computableTime'' f\" := (@computableTime _ ltac:(let t:=type of f in refine (_ : TT t);exact _) f) (at level 0,only parsing).\n\n(* TODO in 8.11: use bidirectional hints Arguments computableTime _ _ _ & _. *)\n                                                                                                             \nLocal Fixpoint notHigherOrder t (ty : TT t) :=\n  match ty with\n    TyArr _ _ (TyB _ _) ty2 => notHigherOrder ty2 \n  | TyB _ _ => True\n  | _ => False\n  end.\n\nLocal Lemma computesTime_computes_intern s t (ty: TT t) f evalTime:\n  notHigherOrder ty -> computesTime ty f s evalTime -> computes ty f s.\nProof.\n  revert s f.\n  induction ty;intros s f H int. \n  - exact int. \n  -destruct ty1; cbn in H. 2:tauto.\n   clear IHty1.\n   cbn. destruct int as [ps ints]. cbn in ints.\n   split. tauto.\n   intros. subst.\n   edestruct (ints a _ tt eq_refl) as(v&R'&?).\n   exists v. split. eapply redLe_star_subrelation. all:eauto.\nDefined. (* because ? *)\n\nLemma computableTime_computable X (ty : TT X) (x:X) fT :\n  notHigherOrder ty -> computableTime x fT -> computable x.\nProof.\n  intros H I. eexists (extT x). destruct I. eapply computesTime_computes_intern. all:eauto.\nDefined. (* because ? *)\n\n#[export] Hint Extern 10 (@computable ?t ?ty ?f) =>\n(solve [let H:= fresh \"H\" in eassert (H : @computableTime t ty f _) by exact _;\n                        ( (exact (computableTime_computable (ty:=ty) Logic.I H))|| idtac \"Can not derive computable instance from computableTime for higher-order-function\" f)]): typeclass_instances.\n\nLemma computesTimeProc t (ty : TT t) (f : t) fInt fT:\n  computesTime ty f fInt fT-> proc fInt.\nProof.\n  destruct ty.\n  -intros ->. unfold enc. now destruct R. \n  -now intros [? _].\nQed.\n\nLemma proc_extT {X : Type} (ty : TT X) (x : X) fT ( H : computableTime x fT) : proc (extT x).\nProof.\n  unfold extT. destruct H as [? H]. now eapply computesTimeProc in H.\nQed.\n\nInstance reg_is_extT ty (R : registered ty) (x : ty): computableTime x tt.\nProof.\n  exists (enc x). split;constructor. \nDefined. (* because ? *)\n\nLemma computesTimeTyB (t:Type) (x:t) `{registered t}: computesTime (TyB t) x (extT x) tt.\nProof.\n  unfold extT. now destruct H.\nQed.\n\nInstance extTApp' t1 t2 {tt1:TT t1} {tt2 : TT t2} (f: t1 -> t2) (x:t1) fT xT (Hf : computableTime f fT) (Hx : computableTime x xT) : computableTime (f x) (snd (fT x xT)).\nProof. \n  destruct Hf as [fInt H], Hx as [xInt xInts].\n  eexists (projT1 ((snd H) x xInt xT xInts)). \n  destruct H as [p fInts]. cbn in *. \n  destruct (fInts x xInt xT xInts) as (v&E&fxInts). \n  eassumption. \nDefined. (* because ? *)\n\nLemma extTApp t1 t2 {tt1:TT t1} {tt2 : TT t2} (f: t1 -> t2) (x:t1) fT xT (Hf : computableTime f fT) (Hx : computableTime x xT) :\n  app (extT f) (extT x) >(<= fst (evalTime f x (evalTime x))) extT (f x).\nProof.\n  unfold extT.\n  destruct Hf as [fInt [fP fInts]], Hx as [xInt xInts]. cbn.\n  destruct (fInts x xInt xT xInts) as (v&E&fxInts). apply E.\nQed.\n\nLemma extT_is_enc t1 (R:registered t1) (x: t1) xT (Hf : computableTime x xT) :\n  @extT _ _ x xT Hf = enc x.\nProof.\n  unfold extT. \n  destruct Hf. assumption.\nDefined. (* because ? *)\n\nLemma computesTimeTyArr_helper t1 t2 (tt1 : TT t1) (tt2 : TT t2) f fInt time fT:\n  proc fInt\n  ->\n  (forall (y : t1) yT,\n      (time y yT<= fst (fT y yT)) * \n  forall (yInt : term),\n    computesTime tt1 y yInt yT\n    -> {v : term & evalLe (time y yT) (app fInt yInt) v * (proc v -> computesTime tt2 (f y) v (snd (fT y yT)))})%type\n-> computesTime (tt1 ~> tt2) f fInt fT.\nProof.\n  intros H0 H. split. tauto.\n  intros y yInt yT yInts.\n  specialize (H y yT) as (lt&H).\n  edestruct H as (v&E&Hv). eassumption.\n  exists v.\n  split. rewrite <- lt. now apply E. \n  apply Hv.\n  apply evalLe_eval_subrelation in E. split. rewrite <- E. apply app_closed. apply H0. apply computesTimeProc in yInts. apply yInts. apply E. \nQed.\n\nDefinition computesTimeIf {t} (ty : TT t) (f:t) (fInt : term) (P:timeComplexity t-> Prop) : Type :=\n  forall fT, P fT -> computesTime ty f fInt fT.\nArguments computesTimeIf {_} _ _ _ _.\n\n\nLemma computesTimeIfStart t1 (tt1 : TT t1) (f : t1) (fInt : term) P fT:\n  computesTimeIf tt1 f fInt P -> P fT -> computesTime tt1 f fInt fT.\nProof.\n  intros ?. cbn. eauto.\nQed.\n\nDefinition computesTimeExp {t} (ty : TT t) (f:t) (s:term) (i:nat) (fInt : term) (fT:timeComplexity t) : Type :=\n  evalLe i s fInt * computesTime ty f fInt fT.\n\nArguments computesTimeExp {_} _ _ _ _ _ _.\n  \nLemma computesTimeExpStart t1 (tt1 : TT t1) (f : t1) (fInt : term) fT:\n  proc fInt ->\n  {v :term & computesTimeExp tt1 f fInt 0 v fT}  -> computesTime tt1 f fInt fT.\nProof.\n  intros ? (?&[e lam]&?). decide (fInt=x). subst x. assumption.\n  edestruct n. destruct e as ([]&?&?). assumption. inv H0. \nQed.\n\nLemma computesTimeExpStep t1 t2 (tt1 : TT t1) (tt2 : TT t2) (f : t1 -> t2) (s:term) k k' fInt fT:\n  k' = k -> evalIn k' s fInt -> closed s -> \n  (forall (y : t1) (yInt : term) yT, computesTime tt1 y yInt yT\n                                -> {v : term & computesTimeExp tt2 (f y) (app s yInt) (fst (fT y yT) +k) v (snd (fT y yT))}%type) ->\n  computesTimeExp (tt1 ~> tt2) f s k fInt fT.\n\nProof.\n  intros -> (R1&p1) ? H. split. split. eexists;split. 2:eassumption. lia. tauto. split. split. 2:tauto. rewrite <- R1. tauto. \n  intros y yInt yT yInted.\n  edestruct (H y yInt yT yInted) as (v&H2&?).\n  eexists v. split.\n  edestruct (evalLe_trans_rev) as (H3&R3). exact H2. apply pow_step_congL. eassumption. reflexivity.\n  destruct fT. cbn in *. replace (n+k-k) with n in R3 by lia. apply R3. tauto. \nQed.\n\n\nLemma computesTimeExt X (tt : TT X) (x x' : X) s fT:\n  extEq x x' -> computesTime tt x s fT -> computesTime tt x' s fT.\nProof.\n  induction tt in x,x',s,fT |-*;intros eq.\n  -inv eq. tauto.\n  -cbn in eq|-*. intros [H1 H2]. split. 1:tauto.\n   intros y t yT ints.\n   specialize (H2 y t yT ints ) as (v&R&H2).\n   exists v. split. 1:assumption.\n   eapply IHtt2. 2:now eassumption.\n   apply eq.\nQed.\n\nLemma computableTimeExt X (tt : TT X) (x x' : X) fT:\n  extEq x x' -> computableTime x fT -> computableTime x' fT.\nProof.\n  intros ? [s ?]. eexists. eauto using computesTimeExt.\nDefined. (* because ? *)\n\nFixpoint changeResType_TimeComplexity t1 (tt1 : TT t1) Y {R: registered Y} {struct tt1}:\n  forall (fT: timeComplexity t1) , @timeComplexity _ (projT2 (changeResType tt1 (TyB Y))):= (\n  match tt1 with\n    @TyB t1 _ => fun fT => fT\n  | TyArr _ _ tt11 tt12 => fun fT x xT => (fst (fT x xT),changeResType_TimeComplexity (snd (fT x xT)))\n  end).\n\nLemma cast_registeredAs_TimeComplexity t1 (tt1 : TT t1) Y (R: registered Y) fT (cast : projT1 (resType tt1) -> Y) (f:t1)\n      (Hc : injective cast) :\n  projT2 (resType tt1) = registerAs cast Hc ->\n  computableTime (ty:=projT2 (changeResType tt1 (TyB Y))) (insertCast R cast f) (changeResType_TimeComplexity fT)->\n  computableTime f fT.\nProof.\n  intros H [s ints].\n  eexists s.\n  induction tt1 in cast,f,fT,H,s,ints,Hc |- *.\n  -cbn in H,ints|-*;unfold enc in *. rewrite H. exact ints.\n  -destruct ints as (?&ints). split. assumption.\n   intros x s__x int__x T__x.\n   specialize (ints x s__x int__x T__x) as (v &?&ints).\n   exists v. split. tauto.\n   eapply IHtt1_2. all:eassumption.\nQed.\n    \nDefinition cnst {X} (x:X):nat. Proof. exact 0. Qed.\n\nDefinition callTime X (fT : X -> unit -> nat * unit) x: nat := fst (fT x tt). \nArguments callTime / {_}.\n \nDefinition callTime2 X Y\n           (fT : X -> unit -> nat * (Y -> unit -> nat * unit)) x y : nat :=\n  let '(k,f):= fT x tt in k + fst (f y tt).\nArguments callTime2 / {_ _}.\n\n\nFixpoint timeComplexity_leq (t : Type) (tt : TT t) {struct tt} : timeComplexity t -> timeComplexity t -> Prop :=\n  match tt in (TT t) return timeComplexity t -> timeComplexity t -> Prop with\n  | ! t0 => fun _ _ => True\n  | @TyArr t1 t2 _ tt2 =>\n    fun f f' : timeComplexity (_ -> _) => forall (x:t1) xT, (fst (f x xT)) <= (fst (f' x xT)) /\\ timeComplexity_leq (snd (f x xT)) (snd (f' x xT))\n  end.\n\nLemma computesTime_timeLeq X (tt : TT X) x s fT fT':\n  timeComplexity_leq fT fT' -> computesTime tt x s fT -> computesTime tt x s fT'.\nProof.\n  induction tt in x,s,fT,fT' |-*;intros eq.\n  -inv eq. tauto.\n  -cbn in eq|-*. intros [H1 H2]. split. 1:tauto.\n   intros y t yT ints.\n   specialize (H2 y t yT ints ) as (v&R&H2).\n   exists v. specialize (eq y yT) as (Hleq&?). split.\n   +rewrite <- Hleq. eassumption.\n   +eauto.\nQed.\n\nLemma computableTime_timeLeq X (tt : TT X) (x:X) fT fT':\n  timeComplexity_leq fT fT' -> computableTime x fT -> computableTime x fT'.\nProof.\n  intros ? []. eexists. eapply computesTime_timeLeq. all:easy.\nQed.\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/Tactics/ComputableTime.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.2946826981270091}}
{"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. *)\n\nRequire Import Coqlib Maps Integers Floats Lattice Kildall.\nRequire Import AST Linking.\nRequire Import Values Events Memory Globalenvs Smallstep.\nRequire Compopts Machregs.\nRequire Import Op Registers RTL.\nRequire Import Liveness ValueDomain ValueAOp ValueAnalysis.\nRequire Import ConstpropOp ConstpropOpproof Constprop.\n\nSection WITHROMEMFOR.\nContext `{romem_for_instance: ROMemFor}.\n\nDefinition match_prog (prog tprog: program) :=\n  match_program (fun cu f tf => tf = transf_fundef (romem_for cu) f) eq prog tprog.\n\nLemma transf_program_match:\n  forall prog, match_prog prog (transf_program prog).\nProof.\n  intros. eapply match_transform_program_contextual. auto.\nQed.\n\nEnd WITHROMEMFOR.\n\nSection PRESERVATION.\nContext `{external_calls_prf: ExternalCalls}.\n\nVariable prog: program.\nVariable tprog: program.\nLet ge := Genv.globalenv prog.\nLet tge := Genv.globalenv tprog.\n\nSection WITHROMEMFOR.\nContext `{romem_for_instance: ROMemFor}.\n\nHypothesis TRANSL: match_prog prog tprog.\n\n(** * Correctness of the code transformation *)\n\n(** We now show that the transformed code after constant propagation\n  has the same semantics as the original code. *)\n\nLemma symbols_preserved:\n  forall (s: ident), Genv.find_symbol tge s = Genv.find_symbol ge s.\nProof (Genv.find_symbol_match TRANSL).\n\nLemma senv_preserved:\n  Senv.equiv ge tge.\nProof (Genv.senv_match TRANSL).\n\nLemma genv_next_preserved:\n  Genv.genv_next tge = Genv.genv_next ge.\nProof.\n  apply senv_preserved.\nQed.\n\nLemma functions_translated:\n  forall (v: val) (f: fundef),\n  Genv.find_funct ge v = Some f ->\n  exists cunit, Genv.find_funct tge v = Some (transf_fundef (romem_for cunit) f) /\\ linkorder cunit prog.\nProof.\n  intros. exploit (Genv.find_funct_match TRANSL); eauto.\n  intros (cu & tf & A & B & C). subst tf. exists cu; auto.\nQed.\n\nLemma function_ptr_translated:\n  forall (b: block) (f: fundef),\n  Genv.find_funct_ptr ge b = Some f ->\n  exists cunit, Genv.find_funct_ptr tge b = Some (transf_fundef (romem_for cunit) f) /\\ linkorder cunit prog.\nProof.\n  intros. exploit (Genv.find_funct_ptr_match TRANSL); eauto.\n  intros (cu & tf & A & B & C). subst tf. exists cu; auto.\nQed.\n\nLemma sig_function_translated:\n  forall rm f,\n  funsig (transf_fundef rm f) = funsig f.\nProof.\n  intros. destruct f; reflexivity.\nQed.\n\nLemma init_regs_lessdef:\n  forall rl vl1 vl2,\n  Val.lessdef_list vl1 vl2 ->\n  regs_lessdef (init_regs vl1 rl) (init_regs vl2 rl).\nProof.\n  induction rl; simpl; intros.\n  red; intros. rewrite Regmap.gi. auto.\n  inv H. red; intros. rewrite Regmap.gi. auto.\n  apply set_reg_lessdef; auto.\nQed.\n\nLemma transf_ros_correct:\n  forall bc rs ae ros f rs',\n  genv_match bc ge ->\n  ematch bc rs ae ->\n  find_function ge ros rs = Some f ->\n  regs_lessdef rs rs' ->\n  exists cunit,\n     find_function tge (transf_ros ae ros) rs' = Some (transf_fundef (romem_for cunit) f)\n  /\\ linkorder cunit prog.\nProof.\n  intros until rs'; intros GE EM FF RLD. destruct ros; simpl in *.\n- (* function pointer *)\n  generalize (EM r); fold (areg ae r); intro VM. generalize (RLD r); intro LD.\n  assert (DEFAULT:\n    exists cunit,\n       find_function tge (inl _ r) rs' = Some (transf_fundef (romem_for cunit) f)\n    /\\ linkorder cunit prog).\n  {\n    simpl. inv LD. apply functions_translated; auto. rewrite <- H0 in FF; discriminate.\n  }\n  destruct (areg ae r); auto. destruct p; auto.\n  predSpec Ptrofs.eq Ptrofs.eq_spec ofs Ptrofs.zero; intros; auto.\n  subst ofs. exploit vmatch_ptr_gl; eauto. intros LD'. inv LD'; try discriminate.\n  rewrite H1 in FF. unfold Genv.symbol_address in FF.\n  simpl. rewrite symbols_preserved.\n  destruct (Genv.find_symbol ge id) as [b|]; try discriminate.\n  simpl in FF. rewrite dec_eq_true in FF.\n  apply function_ptr_translated; auto.\n  rewrite <- H0 in FF; discriminate.\n- (* function symbol *)\n  rewrite symbols_preserved.\n  destruct (Genv.find_symbol ge i) as [b|]; try discriminate.\n  apply function_ptr_translated; auto.\nQed.\n\nLemma const_for_result_correct:\n  forall a op bc v sp m,\n  const_for_result a = Some op ->\n  vmatch bc v a ->\n  bc sp = BCstack ->\n  genv_match bc ge ->\n  exists v', eval_operation tge (Vptr sp Ptrofs.zero) op nil m = Some v' /\\ Val.lessdef v v'.\nProof.\n  intros. exploit ConstpropOpproof.const_for_result_correct; eauto. intros (v' & A & B).\n  exists v'; split.\n  rewrite <- A; apply eval_operation_preserved. exact symbols_preserved.\n  auto.\nQed.\n\nInductive match_pc (f: function) (rs: regset) (m: mem): nat -> node -> node -> Prop :=\n  | match_pc_base: forall n pc,\n      match_pc f rs m n pc pc\n  | match_pc_nop: forall n pc s pcx,\n      f.(fn_code)!pc = Some (Inop s) ->\n      match_pc f rs m n s pcx ->\n      match_pc f rs m (S n) pc pcx\n  | match_pc_cond: forall n pc cond args s1 s2 pcx,\n      f.(fn_code)!pc = Some (Icond cond args s1 s2) ->\n      (forall b,\n        eval_condition cond rs##args m = Some b ->\n        match_pc f rs m n (if b then s1 else s2) pcx) ->\n      match_pc f rs m (S n) pc pcx.\n\nLemma match_successor_rec:\n  forall f rs m bc ae,\n  ematch bc rs ae ->\n  forall n pc,\n  match_pc f rs m n pc (successor_rec n f ae pc).\nProof.\n  induction n; simpl; intros.\n- apply match_pc_base.\n- destruct (fn_code f)!pc as [[]|] eqn:INSTR; try apply match_pc_base.\n+ eapply match_pc_nop; eauto.\n+ destruct (resolve_branch (eval_static_condition c (aregs ae l))) as [b|] eqn:STATIC;\n  try apply match_pc_base.\n  eapply match_pc_cond; eauto. intros b' DYNAMIC.\n  assert (b = b').\n  { eapply resolve_branch_sound; eauto.\n    rewrite <- DYNAMIC. apply eval_static_condition_sound with bc.\n    apply aregs_sound; auto. }\n  subst b'. apply IHn.\nQed.\n\nLemma match_successor:\n  forall f rs m bc ae pc,\n  ematch bc rs ae -> match_pc f rs m num_iter pc (successor f ae pc).\nProof.\n  intros. eapply match_successor_rec; eauto.\nQed.\n\nLemma builtin_arg_reduction_correct:\n  forall bc sp m rs ae, ematch bc rs ae ->\n  forall a v,\n  eval_builtin_arg ge (fun r => rs#r) sp m a v ->\n  eval_builtin_arg ge (fun r => rs#r) sp m (builtin_arg_reduction ae a) v.\nProof.\n  induction 2; simpl; eauto with barg.\n- specialize (H x). unfold areg. destruct (AE.get x ae); try constructor.\n  + inv H. constructor.\n  + inv H. constructor.\n  + destruct (Compopts.generate_float_constants tt); [inv H|idtac]; constructor.\n  + destruct (Compopts.generate_float_constants tt); [inv H|idtac]; constructor.\n- destruct (builtin_arg_reduction ae hi); auto with barg.\n  destruct (builtin_arg_reduction ae lo); auto with barg.\n  inv IHeval_builtin_arg1; inv IHeval_builtin_arg2. constructor.\nQed.\n\nLemma builtin_arg_strength_reduction_correct:\n  forall bc sp m rs ae a v c,\n  ematch bc rs ae ->\n  eval_builtin_arg ge (fun r => rs#r) sp m a v ->\n  eval_builtin_arg ge (fun r => rs#r) sp m (builtin_arg_strength_reduction ae a c) v.\nProof.\n  intros. unfold builtin_arg_strength_reduction.\n  destruct (builtin_arg_ok (builtin_arg_reduction ae a) c).\n  eapply builtin_arg_reduction_correct; eauto.\n  auto.\nQed.\n\nLemma builtin_args_strength_reduction_correct:\n  forall bc sp m rs ae, ematch bc rs ae ->\n  forall al vl,\n  eval_builtin_args ge (fun r => rs#r) sp m al vl ->\n  forall cl,\n  eval_builtin_args ge (fun r => rs#r) sp m (builtin_args_strength_reduction ae al cl) vl.\nProof.\n  induction 2; simpl; constructor.\n  eapply builtin_arg_strength_reduction_correct; eauto.\n  apply IHlist_forall2.\nQed.\n\nLemma debug_strength_reduction_correct:\n  forall bc sp m rs ae, ematch bc rs ae ->\n  forall al vl,\n  eval_builtin_args ge (fun r => rs#r) sp m al vl ->\n  exists vl', eval_builtin_args ge (fun r => rs#r) sp m (debug_strength_reduction ae al) vl'.\nProof.\n  induction 2; simpl.\n- exists (@nil val); constructor.\n- destruct IHlist_forall2 as (vl' & A).\n  assert (eval_builtin_args ge (fun r => rs#r) sp m\n             (a1 :: debug_strength_reduction ae al) (b1 :: vl'))\n  by (constructor; eauto).\n  destruct a1; try (econstructor; eassumption).\n  destruct (builtin_arg_reduction ae (BA x)); repeat (eauto; econstructor).\nQed.\n\nLemma builtin_strength_reduction_correct:\n  forall sp bc ae rs ef args vargs m t vres m',\n  ematch bc rs ae ->\n  eval_builtin_args ge (fun r => rs#r) sp m args vargs ->\n  external_call ef ge vargs m t vres m' ->\n  exists vargs',\n     eval_builtin_args ge (fun r => rs#r) sp m (builtin_strength_reduction ae ef args) vargs'\n  /\\ external_call ef ge vargs' m t vres m'.\nProof.\n  intros.\n  assert (DEFAULT: forall cl,\n    exists vargs',\n       eval_builtin_args ge (fun r => rs#r) sp m (builtin_args_strength_reduction ae args cl) vargs'\n    /\\ external_call ef ge vargs' m t vres m').\n  { exists vargs; split; auto. eapply builtin_args_strength_reduction_correct; eauto. }\n  unfold builtin_strength_reduction.\n  destruct ef; auto.\n  exploit debug_strength_reduction_correct; eauto. intros (vargs' & P).\n  exists vargs'; split; auto.\n  inv H1; constructor.\nQed.\n\n(** The proof of semantic preservation is a simulation argument\n  based on \"option\" diagrams of the following form:\n<<\n                 n\n       st1 --------------- st2\n        |                   |\n       t|                   |t or (? and n' < n)\n        |                   |\n        v                   v\n       st1'--------------- st2'\n                 n'\n>>\n  The left vertical arrow represents a transition in the\n  original RTL code.  The top horizontal bar is the [match_states]\n  invariant between the initial state [st1] in the original RTL code\n  and an initial state [st2] in the transformed code.\n  This invariant expresses that all code fragments appearing in [st2]\n  are obtained by [transf_code] transformation of the corresponding\n  fragments in [st1].  Moreover, the state [st1] must match its compile-time\n  approximations at the current program point.\n  These two parts of the diagram are the hypotheses.  In conclusions,\n  we want to prove the other two parts: the right vertical arrow,\n  which is a transition in the transformed RTL code, and the bottom\n  horizontal bar, which means that the [match_state] predicate holds\n  between the final states [st1'] and [st2']. *)\n\nInductive match_stackframes: stackframe -> stackframe -> Prop :=\n   match_stackframe_intro:\n      forall res sp pc rs f rs' cu,\n      linkorder cu prog ->\n      regs_lessdef rs rs' ->\n    match_stackframes\n        (Stackframe res f sp pc rs)\n        (Stackframe res (transf_function (romem_for cu) f) sp pc rs').\n\nInductive match_states: nat -> state -> state -> Prop :=\n  | match_states_intro:\n      forall s sp pc rs m f s' pc' rs' m' cu n\n           (LINK: linkorder cu prog)\n           (STACKS: list_forall2 match_stackframes s s')\n           (PC: match_pc f rs m n pc pc')\n           (REGS: regs_lessdef rs rs')\n           (MEM: Mem.extends m m'),\n      match_states n (State s f sp pc rs m)\n                    (State s' (transf_function (romem_for cu) f) sp pc' rs' m')\n  | match_states_call:\n      forall s f args m s' args' m' cu\n           (LINK: linkorder cu prog)\n           (STACKS: list_forall2 match_stackframes s s')\n           (ARGS: Val.lessdef_list args args')\n           (MEM: Mem.extends m m'),\n      match_states O (Callstate s f args m)\n                     (Callstate s' (transf_fundef (romem_for cu) f) args' m')\n  | match_states_return:\n      forall s v m s' v' m'\n           (STACKS: list_forall2 match_stackframes s s')\n           (RES: Val.lessdef v v')\n           (MEM: Mem.extends m m'),\n      list_forall2 match_stackframes s s' ->\n      match_states O (Returnstate s v m)\n                     (Returnstate s' v' m').\n\nLemma match_states_succ:\n  forall s f sp pc rs m s' rs' m' cu,\n  linkorder cu prog ->\n  list_forall2 match_stackframes s s' ->\n  regs_lessdef rs rs' ->\n  Mem.extends m m' ->\n  match_states O (State s f sp pc rs m)\n                 (State s' (transf_function (romem_for cu) f) sp pc rs' m').\nProof.\n  intros. apply match_states_intro; auto. constructor.\nQed.\n\nLemma transf_instr_at:\n  forall rm f pc i,\n  f.(fn_code)!pc = Some i ->\n  (transf_function rm f).(fn_code)!pc = Some(transf_instr f (analyze rm f) rm pc i).\nProof.\n  intros. simpl. rewrite PTree.gmap. rewrite H. auto.\nQed.\n\nLtac TransfInstr :=\n  match goal with\n  | H1: (PTree.get ?pc (fn_code ?f) = Some ?instr),\n    H2: (analyze ?rm ?f)#?pc = VA.State ?ae ?am |- _ =>\n      generalize (transf_instr_at rm _ _ _ H1); unfold transf_instr; rewrite H2\n  end.\n\n(** The proof of simulation proceeds by case analysis on the transition\n  taken in the source code. *)\n\nLemma transf_step_correct:\n  forall s1 t s2,\n  step ge s1 t s2 ->\n  forall n1 s1' (SS: sound_state prog s1) (MS: match_states n1 s1 s1'),\n  (exists n2, exists s2', step tge s1' t s2' /\\ match_states n2 s2 s2')\n  \\/ (exists n2, n2 < n1 /\\ t = E0 /\\ match_states n2 s2 s1')%nat.\nProof.\n  induction 1; intros; inv MS; try InvSoundState; try (inv PC; try congruence).\n\n- (* Inop, preserved *)\n  rename pc'0 into pc. TransfInstr; intros.\n  left; econstructor; econstructor; split.\n  eapply exec_Inop; eauto.\n  eapply match_states_succ; eauto.\n\n- (* Inop, skipped over *)\n  assert (s0 = pc') by congruence. subst s0.\n  right; exists n; split. omega. split. auto.\n  apply match_states_intro; auto.\n\n- (* Iop *)\n  rename pc'0 into pc. TransfInstr.\n  set (a := eval_static_operation op (aregs ae args)).\n  set (ae' := AE.set res a ae).\n  assert (VMATCH: vmatch bc v a) by (eapply eval_static_operation_sound; eauto with va).\n  assert (MATCH': ematch bc (rs#res <- v) ae') by (eapply ematch_update; eauto).\n  destruct (const_for_result a) as [cop|] eqn:?; intros.\n+ (* constant is propagated *)\n  exploit const_for_result_correct; eauto. intros (v' & A & B).\n  left; econstructor; econstructor; split.\n  eapply exec_Iop; eauto.\n  apply match_states_intro; auto.\n  eapply match_successor; eauto.\n  apply set_reg_lessdef; auto.\n+ (* operator is strength-reduced *)\n  assert(OP:\n     let (op', args') := op_strength_reduction op args (aregs ae args) in\n     exists v',\n        eval_operation ge (Vptr sp0 Ptrofs.zero) op' rs ## args' m = Some v' /\\\n        Val.lessdef v v').\n  { eapply op_strength_reduction_correct with (ae0 := ae); eauto with va. }\n  destruct (op_strength_reduction op args (aregs ae args)) as [op' args'].\n  destruct OP as [v' [EV' LD']].\n  assert (EV'': exists v'', eval_operation ge (Vptr sp0 Ptrofs.zero) op' rs'##args' m' = Some v'' /\\ Val.lessdef v' v'').\n  { eapply eval_operation_lessdef; eauto. eapply regs_lessdef_regs; eauto. }\n  destruct EV'' as [v'' [EV'' LD'']].\n  left; econstructor; econstructor; split.\n  eapply exec_Iop; eauto.\n  erewrite eval_operation_preserved. eexact EV''. exact symbols_preserved.\n  apply match_states_intro; auto.\n  eapply match_successor; eauto.\n  apply set_reg_lessdef; auto. eapply Val.lessdef_trans; eauto.\n\n- (* Iload *)\n  rename pc'0 into pc. TransfInstr.\n  set (aa := eval_static_addressing addr (aregs ae args)).\n  assert (VM1: vmatch bc a aa) by (eapply eval_static_addressing_sound; eauto with va).\n  set (av := loadv chunk (romem_for cu) am aa).\n  assert (VM2: vmatch bc v av) by (eapply loadv_sound; eauto).\n  destruct (const_for_result av) as [cop|] eqn:?; intros.\n+ (* constant-propagated *)\n  exploit const_for_result_correct; eauto. intros (v' & A & B).\n  left; econstructor; econstructor; split.\n  eapply exec_Iop; eauto.\n  eapply match_states_succ; eauto.\n  apply set_reg_lessdef; auto.\n+ (* strength-reduced *)\n  assert (ADDR:\n     let (addr', args') := addr_strength_reduction addr args (aregs ae args) in\n     exists a',\n        eval_addressing ge (Vptr sp0 Ptrofs.zero) addr' rs ## args' = Some a' /\\\n        Val.lessdef a a').\n  { eapply addr_strength_reduction_correct with (ae := ae); eauto with va. }\n  destruct (addr_strength_reduction addr args (aregs ae args)) as [addr' args'].\n  destruct ADDR as (a' & P & Q).\n  exploit eval_addressing_lessdef. eapply regs_lessdef_regs; eauto. eexact P.\n  intros (a'' & U & V).\n  assert (W: eval_addressing tge (Vptr sp0 Ptrofs.zero) addr' rs'##args' = Some a'').\n  { rewrite <- U. apply eval_addressing_preserved. exact symbols_preserved. }\n  exploit Mem.loadv_extends. eauto. eauto. apply Val.lessdef_trans with a'; eauto.\n  intros (v' & X & Y).\n  left; econstructor; econstructor; split.\n  eapply exec_Iload; eauto.\n  eapply match_states_succ; eauto. apply set_reg_lessdef; auto.\n\n- (* Istore *)\n  rename pc'0 into pc. TransfInstr.\n  assert (ADDR:\n     let (addr', args') := addr_strength_reduction addr args (aregs ae args) in\n     exists a',\n        eval_addressing ge (Vptr sp0 Ptrofs.zero) addr' rs ## args' = Some a' /\\\n        Val.lessdef a a').\n  { eapply addr_strength_reduction_correct with (ae := ae); eauto with va. }\n  destruct (addr_strength_reduction addr args (aregs ae args)) as [addr' args'].\n  destruct ADDR as (a' & P & Q).\n  exploit eval_addressing_lessdef. eapply regs_lessdef_regs; eauto. eexact P.\n  intros (a'' & U & V).\n  assert (W: eval_addressing tge (Vptr sp0 Ptrofs.zero) addr' rs'##args' = Some a'').\n  { rewrite <- U. apply eval_addressing_preserved. exact symbols_preserved. }\n  exploit Mem.storev_extends. eauto. eauto. apply Val.lessdef_trans with a'; eauto. apply REGS.\n  intros (m2' & X & Y).\n  left; econstructor; econstructor; split.\n  eapply exec_Istore; eauto.\n  eapply match_states_succ; eauto.\n\n- (* Icall *)\n  rename pc'0 into pc.\n  exploit transf_ros_correct; eauto. intros (cu' & FIND & LINK').\n  TransfInstr; intro.\n  left; econstructor; econstructor; split.\n  eapply exec_Icall; eauto. apply sig_function_translated; auto.\n  constructor; auto. constructor; auto.\n  econstructor; eauto.\n  apply regs_lessdef_regs; auto.\n\n- (* Itailcall *)\n  exploit Mem.free_parallel_extends; eauto. intros [m2' [A B]].\n  exploit transf_ros_correct; eauto. intros (cu' & FIND & LINK').\n  TransfInstr; intro.\n  left; econstructor; econstructor; split.\n  eapply exec_Itailcall; eauto. apply sig_function_translated; auto.\n  constructor; auto.\n  apply regs_lessdef_regs; auto.\n\n- (* Ibuiltin *)\n  rename pc'0 into pc. TransfInstr; intros.\nOpaque builtin_strength_reduction.\n  exploit builtin_strength_reduction_correct; eauto. intros (vargs' & P & Q).\n  exploit (eval_builtin_args_lessdef (ge := ge) (e1 := fun r => rs#r) (fun r => rs'#r)).\n    apply REGS. eauto. eexact P.\n  intros (vargs'' & U & V).\n  exploit external_call_mem_extends; eauto.\n  intros [v' [m2' [A [B [C D]]]]].\n  left; econstructor; econstructor; split.\n  eapply exec_Ibuiltin; eauto.\n  eapply eval_builtin_args_preserved. eexact symbols_preserved. eauto.\n  eapply external_call_symbols_preserved; eauto. apply senv_preserved.\n  eapply match_states_succ; eauto.\n  apply set_res_lessdef; auto.\n\n- (* Icond, preserved *)\n  rename pc'0 into pc. TransfInstr.\n  set (ac := eval_static_condition cond (aregs ae args)).\n  assert (C: cmatch (eval_condition cond rs ## args m) ac)\n  by (eapply eval_static_condition_sound; eauto with va).\n  rewrite H0 in C.\n  generalize (cond_strength_reduction_correct bc ae rs m EM cond args (aregs ae args) (refl_equal _)).\n  destruct (cond_strength_reduction cond args (aregs ae args)) as [cond' args'].\n  intros EV1 TCODE.\n  left; exists O; exists (State s' (transf_function (romem_for cu) f) (Vptr sp0 Ptrofs.zero) (if b then ifso else ifnot) rs' m'); split.\n  destruct (resolve_branch ac) eqn: RB.\n  assert (b0 = b) by (eapply resolve_branch_sound; eauto). subst b0.\n  destruct b; eapply exec_Inop; eauto.\n  eapply exec_Icond; eauto.\n  eapply eval_condition_lessdef with (vl1 := rs##args'); eauto. eapply regs_lessdef_regs; eauto. congruence.\n  eapply match_states_succ; eauto.\n\n- (* Icond, skipped over *)\n  rewrite H1 in H; inv H.\n  right; exists n; split. omega. split. auto.\n  econstructor; eauto.\n\n- (* Ijumptable *)\n  rename pc'0 into pc.\n  assert (A: (fn_code (transf_function (romem_for cu) f))!pc = Some(Ijumptable arg tbl)\n             \\/ (fn_code (transf_function (romem_for cu) f))!pc = Some(Inop pc')).\n  { TransfInstr.\n    destruct (areg ae arg) eqn:A; auto.\n    generalize (EM arg). fold (areg ae arg); rewrite A.\n    intros V; inv V. replace n0 with n by congruence.\n    rewrite H1. auto. }\n  assert (rs'#arg = Vint n).\n  { generalize (REGS arg). rewrite H0. intros LD; inv LD; auto. }\n  left; exists O; exists (State s' (transf_function (romem_for cu) f) (Vptr sp0 Ptrofs.zero) pc' rs' m'); split.\n  destruct A. eapply exec_Ijumptable; eauto. eapply exec_Inop; eauto.\n  eapply match_states_succ; eauto.\n\n- (* Ireturn *)\n  exploit Mem.free_parallel_extends; eauto. intros [m2' [A B]].\n  left; exists O; exists (Returnstate s' (regmap_optget or Vundef rs') m2'); split.\n  eapply exec_Ireturn; eauto. TransfInstr; auto.\n  constructor; auto.\n  destruct or; simpl; auto.\n\n- (* internal function *)\n  exploit Mem.alloc_extends. eauto. eauto. apply Zle_refl. apply Zle_refl.\n  intros [m2' [A B]].\n  simpl. unfold transf_function.\n  left; exists O; econstructor; split.\n  eapply exec_function_internal; simpl; eauto.\n  simpl. econstructor; eauto.\n  constructor.\n  apply init_regs_lessdef; auto.\n\n- (* external function *)\n  exploit external_call_mem_extends; eauto.\n  intros [v' [m2' [A [B [C D]]]]].\n  simpl. left; econstructor; econstructor; split.\n  eapply exec_function_external; eauto.\n  eapply external_call_symbols_preserved; eauto. apply senv_preserved.\n  constructor; auto.\n\n- (* return *)\n  inv H4. inv H1.\n  left; exists O; econstructor; split.\n  eapply exec_return; eauto.\n  econstructor; eauto. constructor. apply set_reg_lessdef; auto.\nQed.\n\nEnd WITHROMEMFOR.\n\nLocal Existing Instance romem_for_wp_instance.\n\nHypothesis TRANSL: match_prog prog tprog.\n\nLemma transf_initial_states:\n  forall st1, initial_state prog st1 ->\n  exists n, exists st2, initial_state tprog st2 /\\ match_states n st1 st2.\nProof.\n  intros. inversion H.\n  exploit function_ptr_translated; eauto. intros (cu & FIND & LINK).\n  exists O; exists (Callstate nil (transf_fundef (romem_for cu) f) nil m0); split.\n  econstructor; eauto.\n  apply (Genv.init_mem_match TRANSL); auto.\n  replace (prog_main tprog) with (prog_main prog).\n  rewrite symbols_preserved. eauto.\n  assumption.\n  symmetry; eapply match_program_main; eauto.\n  rewrite <- H3. apply sig_function_translated.\n  constructor. auto. constructor. constructor. apply Mem.extends_refl.\nQed.\n\nLemma transf_final_states:\n  forall n st1 st2 r,\n  match_states n 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(** The preservation of the observable behavior of the program then\n  follows. *)\n\nTheorem transf_program_correct:\n  forward_simulation (RTL.semantics prog) (RTL.semantics tprog).\nProof.\n  apply Forward_simulation with lt (fun n s1 s2 => sound_state prog s1 /\\ match_states n s1 s2); constructor.\n- apply lt_wf.\n- simpl; intros. exploit transf_initial_states; eauto. intros (n & st2 & A & B).\n  exists n, 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.\n  exploit transf_step_correct; eauto.\n  intros [ [n2 [s2' [A B]]] | [n2 [A [B C]]]].\n  exists n2; exists s2'; split; auto. left; apply plus_one; auto.\n  exists n2; exists s2; split; auto. right; split; auto. subst t; apply star_refl.\n- apply senv_preserved.\n  assumption.\nQed.\n\nEnd PRESERVATION.\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/Constpropproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.29468269002949976}}
{"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 Implicit Arguments.\nUnset Strict Implicit.\nRequire Export Fpart.\nRequire Export Inter.\nRequire Export Arith.\nSection fparts2_def.\nVariable E : Setoid.\n\nDefinition disjoint (A B : part_set E) := Equal (inter A B) (empty E).\n\nLemma disjoint_comp :\n forall A A' B B' : part_set E,\n Equal A A' -> Equal B B' -> disjoint A B -> disjoint A' B'.\nunfold disjoint in |- *.\nintros A A' B B' H' H'0 H'1; try assumption.\napply Trans with (inter A B).\nauto with *.\nauto with *.\nQed.\n\nLemma empty_not_in :\n forall A : part_set E, Equal A (empty E) -> forall x : E, ~ in_part x A.\nintros A; case A; intros a pa; simpl in |- *.\nunfold eq_part, empty in |- *; simpl in |- *.\nintuition.\nintros.\nelim (H x); auto with *.\nQed.\n\nLemma disjoint_inclus :\n forall A B C : part_set E, included A B -> disjoint B C -> disjoint A C.\nunfold included, disjoint in |- *.\nintros A B C H' H'0; try assumption.\napply not_in_empty.\nunfold not in |- *; intros.\ncut (in_part x (inter B C)).\ngeneralize (empty_not_in (A:=inter B C) H'0).\nunfold not in |- *; intros.\napply H0 with (x := x).\nauto with *.\nauto with *.\napply in_part_inter.\napply H'.\napply in_part_inter_l with C.\nauto with *.\napply in_part_inter_r with A.\nauto with *.\nQed.\n\nLemma included_add_part :\n forall (A : part_set E) (x : E), included A (add_part A x).\nintros A x; red in |- *.\nunfold add_part in |- *.\nauto with *.\nQed.\nHint Resolve included_add_part: algebra.\n\nLemma union_not_in :\n forall (A B : part_set E) (x : E),\n ~ in_part x A -> ~ in_part x B -> ~ in_part x (union A B).\nunfold not in |- *; intros.\ncut (in_part x A \\/ in_part x B).\nintros H'; try assumption.\nintuition.\nauto with *.\nQed.\nHint Resolve union_not_in: algebra.\n\nLemma disjoint_not_in_r :\n forall (A B : part_set E) (x : E),\n disjoint A B -> in_part x A -> ~ in_part x B.\nunfold disjoint in |- *.\nunfold not in |- *; intros.\ncut (in_part x (empty E)).\nauto with *.\napply in_part_comp_r with (inter A B).\nauto with *.\nauto with *.\nQed.\n\nLemma cardinal_union_disjoint :\n forall (a b : nat) (A B : part_set E),\n cardinal A a -> cardinal B b -> disjoint A B -> cardinal (union A B) (a + b).\nsimple induction a.\nintros.\napply cardinal_comp_l with (union (empty E) B); auto with *.\napply union_comp; auto with *.\napply Sym.\nauto with *.\napply cardinal_comp_l with B; auto with *.\nintros.\ninversion H0.\nsimpl in |- *.\napply cardinal_add with (union B0 B) x; auto with *.\napply H; auto with *.\napply disjoint_inclus with (add_part B0 x); auto with *.\napply disjoint_comp with A B; auto with *.\napply union_not_in; auto with *.\napply disjoint_not_in_r with A; auto with *.\napply in_part_comp_r with (add_part B0 x); auto with *.\napply Trans with (union (add_part B0 x) B); auto with *.\nunfold add_part in |- *.\napply Trans with (union B0 (union (single x) B)); auto with *.\napply Trans with (union B0 (union B (single x))); auto with *.\nQed.\nHint Resolve cardinal_union_disjoint: algebra.\n\nLemma in_eq_part :\n forall A B : part_set E,\n (forall x : E, in_part x A -> in_part x B) ->\n (forall x : E, in_part x B -> in_part x A) -> Equal A B.\nintros A B.\ncase A; case B; simpl in |- *.\nintros a pa b pb.\nunfold eq_part in |- *; simpl in |- *.\nintuition.\nQed.\n\nLemma diff_in_l :\n forall (A B : part_set E) (x : E), in_part x (diff A B) -> in_part x A.\nintros A B.\ncase A; case B; simpl in |- *.\nintros a pa b pb.\nunfold eq_part in |- *; simpl in |- *.\nintuition.\nQed.\n\nLemma diff_in_r :\n forall (A B : part_set E) (x : E), in_part x (diff A B) -> ~ in_part x B.\nintros A B.\ncase A; case B; simpl in |- *.\nintros a pa b pb.\nunfold eq_part in |- *; simpl in |- *.\nintuition.\nQed.\n\nLemma in_diff :\n forall (A B : part_set E) (x : E),\n in_part x A -> ~ in_part x B -> in_part x (diff A B).\nintros A B.\ncase A; case B; simpl in |- *.\nintros a pa b pb.\nunfold eq_part in |- *; simpl in |- *.\nintuition.\nQed.\nHint Resolve in_diff: algebra.\n\nLemma union_diff :\n forall A B : part_set E, Equal (union A (diff B A)) (union A B).\nintros A B; try assumption.\napply in_eq_part.\nintros x H'; try assumption.\nelim (in_part_union H').\nauto with *.\nintros H'0; try assumption.\ncut (in_part x B).\nauto with *.\nexact (diff_in_l H'0).\nintros x H'; try assumption.\nelim (in_part_union H').\nauto with *.\nintros H'0; try assumption.\nelim (classic (in_part x A)).\nauto with *.\nintros H'1; try assumption.\ncut (in_part x (diff B A)).\nauto with *.\nauto with *.\nQed.\nHint Resolve union_diff: algebra.\n\nLemma disjoint_diff : forall A B : part_set E, disjoint A (diff B A).\nred in |- *.\nintros A B; try assumption.\napply not_in_empty.\nintros x; red in |- *; intros H'; try exact H'.\nabsurd (in_part x A).\napply diff_in_r with B.\nauto with *.\napply in_part_inter_r with A; auto with *.\napply in_part_inter_l with (diff B A); auto with *.\nQed.\nHint Resolve disjoint_diff: algebra.\n\nLemma cardinal_union :\n forall (a b : nat) (A B : part_set E),\n cardinal A a -> cardinal (diff B A) b -> cardinal (union A B) (a + b).\nintros.\napply cardinal_comp_l with (union A (diff B A)); auto with *.\nQed.\nHint Resolve cardinal_union: algebra.\n\nLemma empty_diff : forall A : part_set E, Equal (diff (empty E) A) (empty E).\nintros A; try assumption.\napply in_eq_part.\nintro.\nintros H'; try assumption.\napply diff_in_l with A; auto with *.\nintros x H'; try assumption.\nabsurd (in_part x (empty E)); auto with *.\nQed.\nHint Resolve empty_diff: algebra.\n\nLemma empty_inter :\n forall A : part_set E, Equal (inter (empty E) A) (empty E).\nintros A; try assumption.\napply in_eq_part.\nintros x H'; try assumption.\napply in_part_inter_l with A; auto with *.\nintros x H'; try assumption.\nabsurd (in_part x (empty E)); auto with *.\nQed.\nHint Resolve empty_inter: algebra.\n\nLemma in_part_trans_eq :\n forall (A : part_set E) (x y : E), in_part x A -> Equal y x -> in_part y A.\nintros A; case A; simpl in |- *.\nintros a pa.\nintros x y H' H'0; try assumption.\napply pa with x; auto with *.\nQed.\n\nLemma diff_add_part :\n forall (A B0 B : part_set E) (x : E),\n ~ in_part x B0 ->\n Equal A (add_part B0 x) -> in_part x B -> Equal (diff B0 B) (diff A B).\nintros A B0 B x H' H'0 H'1; try assumption.\napply in_eq_part.\nintros x0 H'2; try assumption.\napply in_diff.\napply in_part_comp_r with (add_part B0 x).\ncut (in_part x0 B0).\nunfold add_part in |- *.\nauto with *.\napply diff_in_l with B; auto with *.\nauto with *.\napply diff_in_r with B0; auto with *.\nintros x0 H'2; try assumption.\nelim (classic (Equal x0 x)).\nintros H'3; try assumption.\nabsurd (in_part x B); auto with *.\ncut (in_part x (diff A B)).\nintros H'4; try assumption.\napply diff_in_r with A; auto with *.\napply in_part_trans_eq with x0; auto with *.\nintros H'3; try assumption.\napply in_diff.\napply add_part_in_el_diff with x; auto with *.\napply in_part_comp_r with A; auto with *.\napply diff_in_l with B; auto with *.\napply diff_in_r with A; auto with *.\nQed.\n\nLemma diff_not_in :\n forall (A B : part_set E) (x : E), ~ in_part x A -> ~ in_part x (diff A B).\nunfold not in |- *; intros.\napply H.\napply diff_in_l with B; auto with *.\nQed.\nHint Resolve diff_not_in: algebra.\n\nLemma inter_not_in :\n forall (A B : part_set E) (x : E), ~ in_part x A -> ~ in_part x (inter A B).\nunfold not in |- *; intros.\napply H.\napply in_part_inter_l with B; auto with *.\nQed.\nHint Resolve inter_not_in: algebra.\n(* OK *)\n\nLemma inter_add_part :\n forall (A B0 B : part_set E) (x : E),\n ~ in_part x B0 ->\n Equal A (add_part B0 x) ->\n in_part x B -> Equal (inter A B) (add_part (inter B0 B) x).\nunfold add_part in |- *.\nintros A B0 B x H' H'0 H'1; try assumption.\napply Trans with (inter (union B0 (single x)) B).\nauto with *.\napply Trans with (union (inter B0 B) (inter (single x) B)).\nauto with *.\napply union_comp; auto with *.\napply in_eq_part.\nintros x0 H'2; try assumption.\napply in_part_inter_l with B; auto with *.\nintros x0 H'2; try assumption.\napply in_part_inter; auto with *.\napply in_part_trans_eq with x; auto with *.\nQed.\nHint Resolve inter_add_part: algebra.\n\nLemma diff_add_part_not_in :\n forall (A B0 B : part_set E) (x : E),\n ~ in_part x B0 ->\n Equal A (add_part B0 x) ->\n ~ in_part x B -> Equal (diff A B) (add_part (diff B0 B) x).\nintros A B0 B x H' H'0 H'1; try assumption.\napply in_eq_part.\nintros x0 H'2; try assumption.\nelim (classic (Equal x0 x)).\nintros H'3; try assumption.\napply in_part_trans_eq with x; auto with *.\nintros H'3; try assumption.\nunfold add_part in |- *.\napply in_part_union_or.\nleft.\napply in_diff.\napply add_part_in_el_diff with x; auto with *.\napply in_part_comp_r with A; auto with *.\napply diff_in_l with B; auto with *.\napply diff_in_r with A; auto with *.\nintros x0 H'2; try assumption.\napply in_diff.\napply in_part_comp_r with (add_part B0 x); auto with *.\nelim (classic (Equal x0 x)).\nintros H'3; try assumption.\napply in_part_trans_eq with x; auto with *.\nintros H'3; try assumption.\nunfold add_part in |- *.\napply in_part_union_or.\nleft.\nunfold add_part in H'2.\nelim (in_part_union H'2).\nintros H'4; try assumption.\napply diff_in_l with B; auto with *.\nintros H'4; try assumption.\nabsurd (in_part x0 (single x)); auto with *.\nelim (classic (Equal x0 x)).\nintros H'3; try assumption.\nunfold not in |- *; intros.\nunfold not in H'1.\napply H'1.\napply in_part_trans_eq with x0; auto with *.\nintros H'3; try assumption.\napply diff_in_r with B0; auto with *.\napply add_part_in_el_diff with x; auto with *.\nQed.\nHint Resolve diff_add_part_not_in: algebra.\n\nLemma inter_add_part_not_in :\n forall (A B0 B : part_set E) (x : E),\n ~ in_part x B0 ->\n Equal A (add_part B0 x) -> ~ in_part x B -> Equal (inter B0 B) (inter A B).\nunfold add_part in |- *.\nintros A B0 B x H' H'0 H'1; try assumption.\napply Trans with (inter (union B0 (single x)) B).\nauto with *.\napply Trans with (union (inter B0 B) (inter (single x) B)).\napply Trans with (union (inter B0 B) (empty E)).\nauto with *.\napply union_comp; auto with *.\napply Sym.\napply in_eq_part.\nintros x0 H'2; try assumption.\ncut (Equal x x0).\nintros H'3; try assumption.\nabsurd (in_part x0 B).\nunfold not in |- *; intro.\nunfold not in H'1.\napply H'1.\napply in_part_trans_eq with x0; auto with *.\napply in_part_inter_r with (single x).\nauto with *.\ncut (in_part x0 (single x)).\nauto with *.\napply in_part_inter_l with B.\nauto with *.\nintros x0 H'2; try assumption.\nabsurd (in_part x0 (empty E)); auto with *.\nauto with *.\nauto with *.\nQed.\n\nLemma cardinal_diff :\n forall (a : nat) (A B : part_set E),\n cardinal A a ->\n exists b : nat,\n   (exists c : nat,\n      cardinal (diff A B) b /\\ cardinal (inter A B) c /\\ a = b + c).\nsimple induction a; intros.\nexists 0; intros.\nexists 0; intros.\nsimpl in |- *.\nsplit.\napply cardinal_empty.\napply Trans with (diff (empty E) B); auto with *.\nsplit.\napply cardinal_empty.\napply Trans with (inter (empty E) B); auto with *.\nauto with *.\ninversion H0.\nelim (H B0 B); intros.\ncase H6; clear H6; intros.\ncase H6; clear H6; intros.\ncase H7; clear H7; intros.\ncase (classic (in_part x B)); intros.\nexists x0.\nexists (S x1).\nsplit.\napply cardinal_comp_l with (diff B0 B); auto with *.\napply diff_add_part with x; auto with *.\nsplit.\napply cardinal_add with (inter B0 B) x; auto with *.\nrewrite H8.\nauto with *.\nexists (S x0).\nexists x1.\nsplit.\napply cardinal_add with (diff B0 B) x; auto with *.\nsplit.\napply cardinal_comp_l with (inter B0 B); auto with *.\napply inter_add_part_not_in with x; auto with *.\nrewrite H8; auto with *.\nauto with *.\nQed.\n\nLemma cardinal_union_inter :\n forall (A B : part_set E) (a b c : nat),\n cardinal A a ->\n cardinal B b -> cardinal (inter A B) c -> cardinal (union A B) (a + b - c).\nintros.\ncase (cardinal_diff A H0); intros.\ncase H2; clear H2; intros.\ncase H2; clear H2; intros.\ncase H3; clear H3; intros.\napply cardinal_comp with (union A (diff B A)) (a + x); auto with *.\nrewrite H4.\nreplace c with x0.\nrewrite plus_assoc.\nreplace (a + x + x0) with (x0 + (a + x)); auto with *.\napply (cardinal_unique H3); auto with *.\napply cardinal_comp_l with (inter A B); auto with *.\nQed.\nHint Resolve cardinal_union_inter: algebra.\nEnd fparts2_def.\n", "meta": {"author": "coq-contribs", "repo": "algebra", "sha": "4006abe46420df0394e20f0fb19279f64bb8501e", "save_path": "github-repos/coq/coq-contribs-algebra", "path": "github-repos/coq/coq-contribs-algebra/algebra-4006abe46420df0394e20f0fb19279f64bb8501e/Fpart2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.2946826900294997}}
{"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 computation3.\n\n\nLemma oappl_OLL_cons {T} :\n  forall l : list (OList T),\n    oappl (OLL [] :: l) = oappl l.\nProof. sp. Qed.\nHint Rewrite @oappl_OLL_cons : slow.\n\nLemma oeqset_osubset {T} :\n  forall (o1 o2 o3 : OList T),\n    oeqset o1 o2 -> osubset o2 o3 -> osubset o1 o3.\nProof.\n  introv h1 h2.\n  eapply osubset_trans;[|eauto]; eauto 3 with slow.\nQed.\n\nLemma subset_not_in :\n  forall (T : tuniv) (s1 s2 : list T) (x : T),\n    subset s1 s2 -> !LIn x s2 -> !LIn x s1.\nProof.\n  introv ss h i.\n  apply ss in i; sp.\nQed.\n\nDefinition get_utokens_step_seq_arg1 {o}\n           (f : @ntseq o)\n           (t : @NTerm o) :=\n  match t with\n    | oterm (Can (Nint z)) _ =>\n      if Z_le_gt_dec 0 z\n      then get_utokens_step_seq (f (Z.to_nat z))\n      else []\n    | _ => []\n  end.\n\nLemma fold_get_utokens_step_seq_arg1 {o} :\n  forall (f : @ntseq o)\n         (t : @NTerm o),\n    match t with\n      | oterm (Can (Nint z)) _ =>\n        if Z_le_gt_dec 0 z\n        then get_utokens_step_seq (f (Z.to_nat z))\n        else []\n      | _ => []\n    end = get_utokens_step_seq_arg1 f t.\nProof. sp. Qed.\n\nDefinition get_utokens_step_seq_bterm {o}\n           (f : @ntseq o)\n           (b : @BTerm o) :=\n  match b with\n    | bterm [] (oterm (Can (Nint z)) _) =>\n      if Z_le_gt_dec 0 z\n      then get_utokens_step_seq (f (Z.to_nat z))\n      else []\n    | _ => []\n  end.\n\nLemma fold_get_utokens_step_seq_bterm {o} :\n  forall (f : @ntseq o)\n         (b : @BTerm o),\n    match b with\n      | bterm [] (oterm (Can (Nint z)) _) =>\n        if Z_le_gt_dec 0 z\n        then get_utokens_step_seq (f (Z.to_nat z))\n        else []\n      | _ => []\n    end = get_utokens_step_seq_bterm f b.\nProof. sp. Qed.\n\nDefinition get_utokens_step_seq_bterms {o}\n           (f  : @ntseq o)\n           (bs : list (@BTerm o)) :=\n  match bs with\n    | bterm [] (oterm (Can (Nint z)) _) :: _ =>\n      if Z_le_gt_dec 0 z\n      then get_utokens_step_seq (f (Z.to_nat z))\n      else []\n    | _ => []\n  end.\n\nLemma fold_get_utokens_step_seq_bterms {o} :\n  forall f (bs : list (@BTerm o)),\n    match bs with\n      | bterm [] (oterm (Can (Nint z)) _) :: _ =>\n        if Z_le_gt_dec 0 z\n        then get_utokens_step_seq (f (Z.to_nat z))\n        else []\n      | _ => []\n    end = get_utokens_step_seq_bterms f bs.\nProof. sp. Qed.\n\nDefinition get_utokens_step_seq_ncan {o}\n           (f    : @ntseq o)\n           (ncan : NonCanonicalOp)\n           (bs   : list (@BTerm o)) :=\n  match ncan with\n    | NApply  => get_utokens_step_seq_bterms f bs\n    | NEApply => get_utokens_step_seq_bterms f bs\n    | _ => []\n  end.\n\nLemma fold_get_utokens_step_seq_ncan {o} :\n  forall f ncan (bs : list (@BTerm o)),\n    match ncan with\n      | NApply  => get_utokens_step_seq_bterms f bs\n      | NEApply => get_utokens_step_seq_bterms f bs\n      | _ => []\n    end = get_utokens_step_seq_ncan f ncan bs.\nProof. sp. Qed.\n\nLemma lsubst_aux_equal_mk_nat {o} :\n  forall (t : @NTerm o) sub n u,\n    nr_ut_sub u sub\n    -> lsubst_aux t sub = mk_nat n\n    -> t = mk_nat n.\nProof.\n  introv nrut e.\n  destruct t as [v|f|op bs]; allsimpl; ginv.\n  - remember (sub_find sub v) as  sf; symmetry in Heqsf; destruct sf; subst; ginv.\n    eapply nr_ut_some_implies in Heqsf; eauto; exrepnd; ginv.\n  - inversion e as [e1]; subst; clear e.\n    destruct bs; allsimpl; ginv.\nQed.\n\nLemma oappl_OLS_singleton {T} :\n  forall (f : nat -> OList T), oappl [OLS f] = OLS f.\nProof. sp. Qed.\nHint Rewrite @oappl_OLS_singleton : slow.\n\nLemma nt_wf_Exc {o} :\n  forall (bs : list (@BTerm o)),\n    nt_wf (oterm Exc bs)\n    <=> {a : NTerm\n         & {b : NTerm\n         & bs = [nobnd a, nobnd b]\n         # nt_wf a\n         # nt_wf b}}.\nProof.\n  introv; split; intro h.\n  - inversion h as [|?|? ? imp]; subst; allsimpl.\n    repeat (destruct bs; allsimpl; ginv).\n    destruct b as [l1 t1].\n    destruct b0 as [l2 t2].\n    destruct l1; allsimpl; ginv.\n    destruct l2; allsimpl; ginv.\n    pose proof (imp (bterm [] t1)) as h1; autodimp h1 hyp.\n    pose proof (imp (bterm [] t2)) as h2; autodimp h2 hyp.\n    allrw @bt_wf_iff.\n    unfold nobnd.\n    eexists; eexists; dands; eauto.\n  - exrepnd; subst.\n    constructor; simpl; tcsp.\n    introv i; repndors; subst; tcsp; apply bt_wf_iff; auto.\nQed.\n\nLemma nt_wf_NFix {o} :\n  forall (bs : list (@BTerm o)),\n    nt_wf (oterm (NCan NFix) bs)\n    <=> {a : NTerm\n         & bs = [nobnd a]\n         # nt_wf a}.\nProof.\n  introv; split; intro h.\n  - inversion h as [|?|? ? imp]; subst; allsimpl.\n    repeat (destruct bs; allsimpl; ginv).\n    destruct b as [l1 t1].\n    destruct l1; allsimpl; ginv.\n    pose proof (imp (bterm [] t1)) as h1; autodimp h1 hyp.\n    allrw @bt_wf_iff.\n    unfold nobnd.\n    eexists; dands; eauto.\n  - exrepnd; subst.\n    constructor; simpl; tcsp.\n    introv i; repndors; subst; tcsp; apply bt_wf_iff; auto.\nQed.\n\nLemma wf_isexc_implies {o} :\n  forall (t : @NTerm o),\n    nt_wf t\n    -> isexc t\n    -> {a, e : NTerm $ t = mk_exception a e}.\nProof.\n  introv wf ise.\n  unfold isexc in ise.\n  destruct t as [v|f|op bs]; allsimpl; tcsp.\n  destruct op as [can|ncan|exc|abs]; allsimpl; tcsp; GC.\n  apply nt_wf_Exc in wf; exrepnd; subst.\n  eexists; eexists; reflexivity.\nQed.\n\nLemma nt_wf_NCbv {o} :\n  forall (bs : list (@BTerm o)),\n    nt_wf (oterm (NCan NCbv) bs)\n    <=> {v : NVar\n         & {a : NTerm\n         & {b : NTerm\n         & bs = [nobnd a, bterm [v] b]\n         # nt_wf a\n         # nt_wf b }}}.\nProof.\n  introv; split; intro h.\n  - inversion h as [|?|? ? imp]; subst; allsimpl.\n    repeat (destruct bs; allsimpl; ginv).\n    destruct b as [l1 t1].\n    destruct b0 as [l2 t2].\n    destruct l1; allsimpl; ginv.\n    destruct l2 as [|v l2]; allsimpl; ginv.\n    destruct l2; allsimpl; ginv.\n    pose proof (imp (bterm [] t1)) as h1; autodimp h1 hyp.\n    pose proof (imp (bterm [v] t2)) as h2; autodimp h2 hyp.\n    allrw @bt_wf_iff.\n    unfold nobnd.\n    eexists; dands; eauto.\n  - exrepnd; subst.\n    constructor; simpl; tcsp.\n    introv i; repndors; subst; tcsp; apply bt_wf_iff; auto.\nQed.\n\nLemma nt_wf_NTryCatch {o} :\n  forall (bs : list (@BTerm o)),\n    nt_wf (oterm (NCan NTryCatch) bs)\n    <=> {v : NVar\n         & {a : NTerm\n         & {b : NTerm\n         & {c : NTerm\n         & bs = [nobnd a, nobnd b, bterm [v] c]\n         # nt_wf a\n         # nt_wf b\n         # nt_wf c }}}}.\nProof.\n  introv; split; intro h.\n  - inversion h as [|?|? ? imp]; subst; allsimpl.\n    repeat (destruct bs; allsimpl; ginv).\n    destruct b as [l1 t1].\n    destruct b0 as [l2 t2].\n    destruct b1 as [l3 t3].\n    destruct l1; allsimpl; ginv.\n    destruct l2; allsimpl; ginv.\n    destruct l3 as [|v l3]; allsimpl; ginv.\n    destruct l3; allsimpl; ginv.\n    pose proof (imp (bterm [] t1)) as h1; autodimp h1 hyp.\n    pose proof (imp (bterm [] t2)) as h2; autodimp h2 hyp.\n    pose proof (imp (bterm [v] t3)) as h3; autodimp h3 hyp.\n    allrw @bt_wf_iff.\n    unfold nobnd.\n    eexists; eexists; eexists; eexists; dands; eauto.\n  - exrepnd; subst.\n    constructor; simpl; tcsp.\n    introv i; repndors; subst; tcsp; apply bt_wf_iff; auto.\nQed.\n\nLemma get_cutokens_onil_eq {o} :\n  forall (t : @NTerm o),\n    oapp (get_cutokens t) onil = get_cutokens t.\nProof.\n  introv; rw <- @get_cutokens_onil; auto.\nQed.\nHint Rewrite @get_cutokens_onil_eq : slow.\n\nLemma iscan_lsubst_aux_nr_ut_sub_eq_doms {o} :\n  forall (t u : @NTerm o) sub sub',\n    nr_ut_sub u sub\n    -> nr_ut_sub u sub'\n    -> dom_sub sub = dom_sub sub'\n    -> iscan (lsubst_aux t sub)\n    -> iscan (lsubst_aux t sub').\nProof.\n  introv nrut1 nrut2 eqdoms isc.\n  destruct t as [v|f|op bs]; allsimpl; tcsp.\n  remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf; allsimpl; tcsp.\n  pose proof (sub_find_some_eq_doms_nr_ut_sub sub sub' v u) as h.\n  repeat (autodimp h hyp).\n  rw Heqsf in h; exrepnd.\n  rw h0; simpl; tcsp.\nQed.\nHint Resolve iscan_lsubst_aux_nr_ut_sub_eq_doms : slow.\n\nLemma osubset_oapp_left_iff {T} :\n  forall o o1 o2 : OList T,\n    osubset (oapp o1 o2) o <=> (osubset o1 o # osubset o2 o).\nProof.\n  introv; split; intro h; repnd; try (apply osubset_oapp_left; auto).\n  dands; introv i; apply h; apply in_olist_oapp; sp.\nQed.\n\nLemma subset_flat_map_get_utokens_b {o} :\n  forall (l : list (@BTerm o)),\n    subset (flat_map get_utokens_b l)\n           (flat_map get_utokens_step_seq_b l).\nProof.\n  introv.\n  apply subset_flat_map2; introv i.\n  destruct x; simpl; eauto 3 with slow.\nQed.\nHint Resolve subset_flat_map_get_utokens_b : slow.\n\nDefinition get_utokens_step_seq_bterms_seq {o}\n           (bs : list (@BTerm o)) :=\n  match bs with\n    | bterm [] (sterm f) :: bterm [] (oterm (Can (Nint z)) _) :: _ =>\n      if Z_le_gt_dec 0 z\n      then get_utokens_step_seq (f (Z.to_nat z))\n      else []\n    | _ => []\n  end.\n\nLemma fold_get_utokens_step_seq_bterms_seq {o} :\n  forall (bs : list (@BTerm o)),\n    match bs with\n      | bterm [] (sterm f) :: bterm [] (oterm (Can (Nint z)) _) :: _ =>\n        if Z_le_gt_dec 0 z\n        then get_utokens_step_seq (f (Z.to_nat z))\n        else []\n      | _ => []\n    end = get_utokens_step_seq_bterms_seq bs.\nProof. sp. Qed.\n\nDefinition get_utokens_step_seq_ncan_seq {o}\n           (ncan : NonCanonicalOp)\n           (bs   : list (@BTerm o)) :=\n  match ncan with\n    | NApply  => get_utokens_step_seq_bterms_seq bs\n    | NEApply => get_utokens_step_seq_bterms_seq bs\n    | _ => []\n  end.\n\nLemma fold_get_utokens_step_seq_ncan_seq {o} :\n  forall ncan (bs : list (@BTerm o)),\n    match ncan with\n      | NApply  => get_utokens_step_seq_bterms_seq bs\n      | NEApply => get_utokens_step_seq_bterms_seq bs\n      | _ => []\n    end = get_utokens_step_seq_ncan_seq ncan bs.\nProof. sp. Qed.\n\nDefinition ncan_nil {T} (ncan : NonCanonicalOp) : list T :=\n  match ncan with\n    | NApply => []\n    | _ => []\n  end.\n\nLemma fold_ncan_nil {T} :\n  forall ncan,\n    match ncan with\n      | NApply => []\n      | _ => []\n    end = ([] : list T).\nProof.\n  introv; destruct ncan; sp.\nQed.\nHint Rewrite @fold_ncan_nil : slow.\n\nLemma sub_find_sub_filter_singleton_eq {o} :\n  forall (sub : @Sub o) (v : NVar),\n    sub_find (sub_filter sub [v]) v = None.\nProof.\n  introv.\n  rw @sub_find_sub_filter_eq; allrw memvar_singleton; boolvar; auto.\nQed.\nHint Rewrite @sub_find_sub_filter_singleton_eq : slow.\n\nDefinition get_utokens_step_seq_op_seq {o}\n           (op : @Opid o)\n           (bs : list (@BTerm o)) :=\n  match op with\n    | NCan NApply  => get_utokens_step_seq_bterms_seq bs\n    | NCan NEApply => get_utokens_step_seq_bterms_seq bs\n    | _ => []\n  end.\n\nLemma fold_get_utokens_step_seq_op_seq {o} :\n  forall op (bs : list (@BTerm o)),\n    match op with\n      | NCan NApply  => get_utokens_step_seq_bterms_seq bs\n      | NCan NEApply => get_utokens_step_seq_bterms_seq bs\n      | _ => []\n    end = get_utokens_step_seq_op_seq op bs.\nProof. sp. Qed.\n\nLemma subset_get_utokens_step_seq_lsubst_aux {o} :\n  forall (t : @NTerm o) sub,\n    subset (get_utokens_step_seq t) (get_utokens_step_seq (lsubst_aux t sub)).\nProof.\n  nterm_ind1 t as [v|f ind|op bs ind] Case; introv; simpl; auto.\n  Case \"oterm\".\n  allrw @fold_get_utokens_step_seq_bterms_seq.\n  allrw @fold_get_utokens_step_seq_op_seq.\n  allrw subset_app; dands; eauto 3 with slow.\n  - apply subset_app_l.\n    apply subset_app_r.\n    allrw flat_map_map; unfold compose.\n    apply subset_flat_map2; introv i.\n    destruct x as [l t]; allsimpl.\n    eapply ind; eauto.\n  - apply subset_app_l.\n    apply subset_app_l.\n    dopid op as [can|ncan|exc|abs] SCase; simpl; auto;[].\n    SCase \"NCan\".\n    allrw @fold_get_utokens_step_seq_ncan_seq.\n    destruct ncan; simpl; auto;[|].\n    + destruct bs; simpl; auto;[].\n      destruct b as [l t]; simpl;[].\n      destruct l; simpl; auto;[].\n      destruct t as [v|f|op bs1]; simpl; autorewrite with slow in *; auto;[].\n      destruct bs; simpl; auto;[].\n      destruct b as [l t].\n      destruct l; simpl; auto;[].\n      destruct t as [v|f1|op bs1]; simpl; autorewrite with slow in *; auto.\n    + destruct bs; simpl; auto;[].\n      destruct b as [l t]; simpl;[].\n      destruct l; simpl; auto;[].\n      destruct t as [v|f|op bs1]; simpl; autorewrite with slow in *; auto;[].\n      destruct bs; simpl; auto;[].\n      destruct b as [l t].\n      destruct l; simpl; auto;[].\n      destruct t as [v|f1|op bs1]; simpl; autorewrite with slow in *; auto.\nQed.\n\nDefinition is_utok_sub {o} (sub : @Sub o) :=\n  forall v t, LIn (v,t) sub -> is_utok t.\n\nLemma is_utok_sub_cons {o} :\n  forall v (t : @NTerm o) sub,\n    is_utok_sub ((v, t) :: sub) <=> (is_utok t # is_utok_sub sub).\nProof.\n  introv.\n  unfold is_utok_sub; simpl; split; introv h; repnd; dands; introv.\n  - eapply h; eauto.\n  - intro i; eapply h; eauto.\n  - intro i; repndors; ginv; auto.\n    eapply h; eauto.\nQed.\n\nLemma in_is_utok_sub {o} :\n  forall (sub : @Sub o) v t,\n    is_utok_sub sub\n    -> LIn (v, t) sub\n    -> is_utok t.\nProof.\n  introv i j; apply i in j; auto.\nQed.\n\nLemma implies_is_utok_sub {o} :\n  forall (sub : @Sub o) l, is_utok_sub sub -> is_utok_sub (sub_filter sub l).\nProof.\n  introv isu i.\n  allrw @in_sub_filter; repnd.\n  apply isu in i0; sp.\nQed.\nHint Resolve implies_is_utok_sub : slow.\n\nLemma eqset_flat_map_get_utokens_step_seq_b_is_utok_sub {o} :\n  forall (bs : list (@BTerm o)) sub,\n    (forall (nt nt' : NTerm) (lv : list NVar),\n       LIn (bterm lv nt) bs\n       -> (osize nt') <=< (osize nt)\n       -> forall sub : @Sub o,\n            is_utok_sub sub\n            -> eqset (get_utokens_step_seq (lsubst_aux nt' sub))\n                     (get_utokens_step_seq nt' ++ get_utokens_sub (sub_keep_first sub (free_vars nt'))))\n    -> is_utok_sub sub\n    -> eqset\n         (flat_map get_utokens_step_seq_b\n                   (map (fun t => lsubst_bterm_aux t sub) bs))\n         (flat_map get_utokens_step_seq_b bs ++\n                   get_utokens_sub (sub_keep_first sub (flat_map free_vars_bterm bs))).\nProof.\n  introv ind isu.\n  allrw flat_map_map; unfold compose.\n  introv; split; intro i.\n\n  - rw lin_flat_map in i; exrepnd.\n    destruct x0 as [l t]; allsimpl.\n    eapply ind in i0; eauto 3 with slow.\n    allrw in_app_iff; repndors.\n\n    { left.\n      rw lin_flat_map.\n      eexists; dands; eauto. }\n\n    { right.\n      allrw @in_get_utokens_sub; exrepnd.\n      exists v t0; dands; auto.\n      allrw @in_sub_keep_first; repnd.\n      allrw @sub_find_sub_filter_some; repnd; dands; auto.\n      rw lin_flat_map.\n      eexists; dands; eauto; simpl.\n      allrw in_remove_nvars; dands; auto. }\n\n  - allrw in_app_iff; allrw lin_flat_map.\n    repndors; exrepnd.\n\n    { eexists; dands; eauto.\n      destruct x0 as [l t]; allsimpl.\n      eapply ind; eauto 3 with slow.\n      allrw in_app_iff; tcsp. }\n\n    { allrw @in_range_iff; exrepnd.\n      allrw @in_sub_keep_first; repnd.\n      allrw lin_flat_map; exrepnd.\n      eexists; dands; eauto.\n      destruct x1 as [l t]; allsimpl.\n      allrw in_remove_nvars; repnd.\n      eapply ind; eauto 3 with slow.\n      allrw in_app_iff.\n      right.\n      unfold get_utokens_sub.\n      rw lin_flat_map; eexists; dands; eauto.\n      allrw @in_range_iff; exists v.\n      allrw @in_sub_keep_first; dands; auto.\n      rw @sub_find_sub_filter_eq; boolvar; tcsp. }\nQed.\n\nLemma get_utokens_sub_sub_keep_first2 {o} :\n  forall (sub : @Sub o) (l1 l2 : list NVar),\n    subset l1 l2\n    -> subset\n         (get_utokens_sub (sub_keep_first sub l1))\n         (get_utokens_sub (sub_keep_first sub l2)).\nProof.\n  introv i j.\n  allunfold @get_utokens_sub.\n  allrw lin_flat_map; exrepnd.\n  eexists; dands; eauto.\n  allrw @in_range_iff; exrepnd.\n  exists v.\n  allrw @in_sub_keep_first; repnd; dands; auto.\nQed.\n\nLemma get_utokens_step_seq_lsubst_aux_is_utok_sub_aux1 {o} :\n  forall a (sub : @Sub o) v l vs,\n    is_utok_sub sub\n    -> sub_find sub v = Some (mk_utoken a)\n    -> eqset (l ++ get_utokens_sub (sub_keep_first sub (v :: vs)))\n             (a :: l ++ get_utokens_sub (sub_keep_first sub vs)).\nProof.\n  introv isu e; allrw in_app_iff; split; introv h;\n  allsimpl; allrw in_app_iff; repndors; tcsp; allsimpl.\n\n  - allunfold @get_utokens_sub.\n    allrw lin_flat_map; exrepnd.\n    allrw @in_range_iff; exrepnd.\n    allrw @in_sub_keep_first; repnd.\n    allsimpl; repndors; subst; tcsp.\n\n    + rw h1 in e; ginv; allsimpl; repndors; tcsp.\n\n    + right.\n      right.\n      exists x0; dands; auto.\n      rw @in_range_iff.\n      exists v0.\n      rw @in_sub_keep_first; dands; auto.\n\n  - subst.\n    right.\n    allunfold @get_utokens_sub.\n    allrw lin_flat_map.\n    exists (mk_utoken x); simpl; dands; tcsp.\n    allrw @in_range_iff.\n    exists v.\n    allrw @in_sub_keep_first; simpl; dands; tcsp.\n\n  - allunfold @get_utokens_sub.\n    allrw lin_flat_map; exrepnd.\n    allrw @in_range_iff; exrepnd.\n    allrw @in_sub_keep_first; repnd.\n    right.\n    exists x0; dands; auto.\n    rw @in_range_iff.\n    exists v0.\n    rw @in_sub_keep_first; dands; simpl; tcsp.\nQed.\n\nLemma get_utokens_step_seq_lsubst_aux_is_utok_sub_aux2 {o} :\n  forall (sub : @Sub o) v l vs,\n    is_utok_sub sub\n    -> sub_find sub v = None\n    -> eqset (l ++ get_utokens_sub (sub_keep_first sub (v :: vs)))\n             (l ++ get_utokens_sub (sub_keep_first sub vs)).\nProof.\n  introv isu e; allrw in_app_iff; split; introv h;\n  allsimpl; allrw in_app_iff; repndors; tcsp; allsimpl.\n\n  - allunfold @get_utokens_sub.\n    allrw lin_flat_map; exrepnd.\n    allrw @in_range_iff; exrepnd.\n    allrw @in_sub_keep_first; repnd.\n    allsimpl; repndors; subst; tcsp.\n\n    + rw h1 in e; ginv; allsimpl; repndors; tcsp.\n\n    + right.\n      exists x0; dands; auto.\n      rw @in_range_iff.\n      exists v0.\n      rw @in_sub_keep_first; dands; auto.\n\n  - allunfold @get_utokens_sub.\n    allrw lin_flat_map; exrepnd.\n    allrw @in_range_iff; exrepnd.\n    allrw @in_sub_keep_first; repnd.\n    right.\n    exists x0; dands; auto.\n    rw @in_range_iff.\n    exists v0.\n    rw @in_sub_keep_first; dands; simpl; tcsp.\nQed.\n\nLemma implies_eqset_cons {T} :\n  forall (x : T) l1 l2,\n    eqset l1 l2\n    -> eqset (x :: l1) (x :: l2).\nProof.\n  introv e; introv; split; intro h; allsimpl; repndors; tcsp; right; apply e; auto.\nQed.\n\nLemma eqset_app_move2 :\n  forall {T} (a b c : list T),\n    eqset ((a ++ b) ++ c) ((a ++ c) ++ b).\nProof.\n  introv; introv; split; intro i; allrw in_app_iff; sp.\nQed.\n\nLemma nr_ut_sub_is_utok_sub {o} :\n  forall sub (t : @NTerm o),\n    nr_ut_sub t sub\n    -> is_utok_sub sub.\nProof.\n  induction sub; introv h; eauto 3 with slow.\n  - introv i; allsimpl; tcsp.\n  - destruct a as [v u].\n    apply is_utok_sub_cons.\n    apply nr_ut_sub_cons_iff in h; exrepnd; subst.\n    apply IHsub in h0; simpl; dands; auto.\nQed.\nHint Resolve nr_ut_sub_is_utok_sub : slow.\n\nLemma get_utokens_step_seq_lsubst_aux_is_utok_sub {o} :\n  forall (t : @NTerm o) (sub : Substitution),\n    is_utok_sub sub\n    -> eqset\n         (get_utokens_step_seq (lsubst_aux t sub))\n         (get_utokens_step_seq t ++ get_utokens_sub (sub_keep_first sub (free_vars t))).\nProof.\n  nterm_ind1s t as [v|f ind|op bs ind] Case; introv isus; simpl; autorewrite with slow; auto.\n\n  - Case \"vterm\".\n    rw @sub_keep_singleton.\n    remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf;\n    simpl; autorewrite with slow; auto.\n    rw @get_utokens_sub_cons; autorewrite with slow; eauto 3 with slow.\n    apply sub_find_some in Heqsf.\n    apply isus in Heqsf.\n    apply is_utok_implies in Heqsf; exrepnd; subst; simpl; auto.\n\n  - Case \"oterm\".\n    dopid op as [can|ncan|exc|abs] SCase; simpl; autorewrite with slow;\n    try (complete (apply eqset_flat_map_get_utokens_step_seq_b_is_utok_sub; auto));[|].\n\n    + rw <- app_assoc.\n      apply eqset_app_if; auto.\n      apply eqset_flat_map_get_utokens_step_seq_b_is_utok_sub; auto.\n\n    + destruct ncan; allsimpl; autorewrite with slow in *;\n      try (complete (apply eqset_flat_map_get_utokens_step_seq_b_is_utok_sub; auto));\n      allrw @fold_get_utokens_step_seq_bterms_seq;[|].\n\n      * eapply eqset_trans;[|apply eqset_sym;apply eqset_app_move2].\n        apply eqset_app_if.\n\n        { apply eqset_flat_map_get_utokens_step_seq_b_is_utok_sub; auto. }\n\n        { destruct bs as [|b bs]; simpl; auto.\n          destruct b as [l t]; simpl.\n          destruct l as [|v l]; allsimpl; auto; autorewrite with slow.\n          destruct t as [v|f|op bs1]; allsimpl; auto;[|].\n\n          - remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf;\n            allsimpl; autorewrite with slow; auto;[].\n            applydup @sub_find_some in Heqsf as j.\n            apply isus in j.\n            apply is_utok_implies in j; exrepnd; subst; allsimpl; autorewrite with slow in *; auto.\n\n          - destruct bs as [|b bs]; allsimpl; auto;[].\n            destruct b as [l t]; allsimpl.\n            destruct l as [|v l]; allsimpl; autorewrite with slow; auto;[].\n            destruct t as [v|f1|op bs1]; allsimpl; auto;[].\n            remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf;\n            allsimpl; autorewrite with slow; auto;[].\n            applydup @sub_find_some in Heqsf as j.\n            apply isus in j.\n            apply is_utok_implies in j; exrepnd; subst; allsimpl; autorewrite with slow in *; auto.\n        }\n\n      * eapply eqset_trans;[|apply eqset_sym;apply eqset_app_move2].\n        apply eqset_app_if.\n\n        { apply eqset_flat_map_get_utokens_step_seq_b_is_utok_sub; auto. }\n\n        { destruct bs as [|b bs]; simpl; auto.\n          destruct b as [l t]; simpl.\n          destruct l as [|v l]; allsimpl; auto; autorewrite with slow.\n          destruct t as [v|f|op bs1]; allsimpl; auto;[|].\n\n          - remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf;\n            allsimpl; autorewrite with slow; auto;[].\n            applydup @sub_find_some in Heqsf as j.\n            apply isus in j.\n            apply is_utok_implies in j; exrepnd; subst; allsimpl; autorewrite with slow in *; auto.\n\n          - destruct bs as [|b bs]; allsimpl; auto;[].\n            destruct b as [l t]; allsimpl.\n            destruct l as [|v l]; allsimpl; autorewrite with slow; auto;[].\n            destruct t as [v|f1|op bs1]; allsimpl; auto;[].\n            remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf;\n            allsimpl; autorewrite with slow; auto;[].\n            applydup @sub_find_some in Heqsf as j.\n            apply isus in j.\n            apply is_utok_implies in j; exrepnd; subst; allsimpl; autorewrite with slow in *; auto.\n        }\nQed.\n\nLemma get_utokens_so_subset_get_cutokens_so {o} :\n  forall (t : @SOTerm o),\n    subseto (get_utokens_so t) (get_cutokens_so t).\nProof.\n  soterm_ind1s t as [v ts ind|op bs ind] Case; simpl.\n\n  - Case \"sovar\".\n    eapply subseto_oeqset;[|apply oeqset_sym;apply oeqset_oappl_OLL].\n    apply subseto_flat_map2; auto.\n\n  - Case \"soterm\".\n    eapply subseto_oeqset;[|apply oeqset_sym;apply oeqset_oappl_OLL].\n    apply subseto_app_l; dands; apply implies_subseto_app_r.\n\n    + left; apply subseto_refl.\n\n    + right.\n      apply subseto_flat_map2; auto.\n      introv i.\n      destruct x as [l t]; allsimpl.\n      eapply ind; eauto.\nQed.\n\nLemma not_in_olist {T} :\n  forall (v : T), !in_olist v onil.\nProof.\n  introv h.\n  inversion h; subst; exrepnd; allsimpl; tcsp.\nQed.\n\nLemma no_utokens_implies_get_utokens_so_nil {o} :\n  forall (t : @SOTerm o),\n    no_utokens t\n    -> get_utokens_so t = [].\nProof.\n  introv h.\n  unfold no_utokens in h; auto.\nQed.\n\nLemma compute_step_subst_utoken {o} :\n  forall lib (t u : @NTerm o) sub,\n    nt_wf t\n    -> compute_step lib (lsubst t sub) = csuccess u\n    -> nr_ut_sub t sub\n    -> disjoint (get_utokens_sub sub) (get_utokens t)\n    -> {w : NTerm\n        & alpha_eq u (lsubst w sub)\n        # disjoint (get_utokens_sub sub) (get_utokens w)\n        # subvars (free_vars w) (free_vars t)\n        # subset (get_utokens w) (get_utokens t)\n        # (forall sub',\n             nr_ut_sub t sub'\n             -> dom_sub sub = dom_sub sub'\n             -> disjoint (get_utokens_sub sub') (get_utokens t)\n             -> {s : NTerm\n                 & compute_step lib (lsubst t sub') = csuccess s\n                 # alpha_eq s (lsubst w sub')})}.\nProof.\n  nterm_ind1s t as [v|f ind|op bs ind] Case; introv wf comp nrut disj; tcsp.\n\n  - Case \"vterm\".\n    unflsubst in comp; eauto with slow.\n    allsimpl.\n    remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf.\n\n    + applydup @sub_find_some in Heqsf.\n      eapply in_nr_ut_sub in Heqsf0; eauto; exrepnd; subst.\n      csunf comp; allsimpl; ginv.\n      exists (@mk_var o v).\n      unflsubst; simpl; rw Heqsf; dands; eauto 3 with slow.\n      introv nrut' eqdoms disj'.\n      pose proof (sub_find_some_eq_doms_nr_ut_sub sub sub' v (vterm v)) as h.\n      repeat (autodimp h hyp).\n      rw Heqsf in h; exrepnd.\n      unflsubst; simpl; rw h0.\n      csunf; simpl.\n      eexists; dands; eauto.\n      unflsubst; simpl; rw h0; auto.\n\n    + csunf comp; allsimpl; ginv.\n\n  - Case \"sterm\".\n    allsimpl.\n    unflsubst in comp; allsimpl.\n    csunf comp; allsimpl; ginv.\n    exists (sterm f); simpl.\n    unflsubst; simpl.\n    dands; eauto 3 with slow.\n    introv nrut' eqdoms' disj'.\n    unflsubst; simpl.\n    csunf; simpl.\n    eexists; dands; eauto.\n\n  - Case \"oterm\".\n    dopid op as [can|ncan|exc|abs] SCase.\n\n    + SCase \"Can\".\n      unflsubst in comp; allsimpl.\n      csunf comp; allsimpl; ginv.\n      exists (oterm (Can can) bs).\n      allrw app_nil_r; allsimpl.\n      unflsubst; allsimpl; dands; eauto 3 with slow.\n\n      introv nrut' eqdoms disj'.\n      repeat unflsubst; simpl; csunf; simpl.\n      eexists; dands; eauto.\n\n    + SCase \"NCan\".\n      destruct bs; try (complete (allsimpl; ginv)).\n      destruct b as [l t]; try (complete (allsimpl; ginv)).\n      destruct l; try (complete (allsimpl; ginv)).\n\n      { destruct t as [x|f|op bts]; try (complete (allsimpl; ginv));\n        [ | | ].\n\n        { unflsubst in comp; allsimpl.\n          allrw @sub_filter_nil_r.\n          remember (sub_find sub x) as sf; symmetry in Heqsf; destruct sf;\n          [|csunf comp; allsimpl; ginv].\n\n          applydup @sub_find_some in Heqsf.\n          eapply in_nr_ut_sub in Heqsf0; eauto; exrepnd; subst.\n          apply compute_step_ncan_vterm_success in comp.\n          repndors; exrepnd; subst.\n\n          - exists (@mk_axiom o); allsimpl.\n            rw @cl_lsubst_trivial; simpl; dands; eauto with slow.\n            introv nrut' eqdoms disj'.\n            exists (@mk_axiom o); allsimpl.\n            rw (@cl_lsubst_trivial o mk_axiom); simpl; dands; eauto 3 with slow.\n            unflsubst; simpl; allrw @sub_filter_nil_r.\n            pose proof (sub_find_some_eq_doms_nr_ut_sub sub sub' x (oterm (NCan NParallel) (bterm [] (vterm x) :: bs))) as h; repeat (autodimp h hyp).\n            rw Heqsf in h; exrepnd; rw h0.\n            csunf; simpl.\n            unfold compute_step_parallel; auto.\n\n          - destruct bs; allsimpl; cpx; GC.\n            exists (@mk_apply o (mk_var x) (mk_fix (mk_var x))).\n            unflsubst; simpl; allrw @sub_filter_nil_r; allrw; dands; eauto 3 with slow.\n            introv nrut' eqdoms disj'.\n            repeat unflsubst; simpl; allrw @sub_filter_nil_r.\n            pose proof (sub_find_some_eq_doms_nr_ut_sub sub sub' x (oterm (NCan NFix) [bterm [] (vterm x)])) as h; repeat (autodimp h hyp).\n            rw Heqsf in h; exrepnd; rw h0.\n            csunf; simpl.\n            eexists; dands; eauto.\n\n          - destruct bs; allsimpl; cpx.\n            destruct bs; allsimpl; cpx.\n            destruct b0 as [l t].\n            destruct l; allsimpl; cpx.\n\n            exists (lsubst t [(x0, mk_var x)]).\n            dands; allrw app_nil_r.\n\n            + eapply alpha_eq_trans;[|apply alpha_eq_sym; apply combine_1var_sub]; eauto 2 with slow.\n              simpl.\n              unflsubst (@mk_var o x); simpl; rw Heqsf.\n              rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow.\n              unfold subst; rw <- @cl_lsubst_app; eauto 3 with slow; simpl.\n              apply alpha_eq_lsubst_if_ext_eq; auto.\n              introv i; simpl.\n              rw @sub_find_app; rw @sub_find_sub_filter_eq; rw memvar_singleton.\n              boolvar; simpl; boolvar; simpl; tcsp.\n              remember (sub_find sub v) as sf; destruct sf; allsimpl; auto.\n\n            + eapply disjoint_eqset_r;[apply eqset_sym; apply get_utokens_lsubst|].\n              eapply subset_disjoint_r; eauto 3 with slow.\n              apply app_subset; dands; eauto 3 with slow.\n              eapply subset_trans;[apply get_utokens_sub_sub_keep_first|].\n              unfold get_utokens_sub; simpl; auto.\n\n            + eapply subvars_eqvars;[|apply eqvars_sym; apply eqvars_free_vars_disjoint]; simpl.\n              unfold dom_sub; simpl; boolvar; simpl; allrw app_nil_r; eauto with slow.\n\n            + autorewrite with slow.\n              eapply subset_eqset_l;[apply eqset_sym;apply get_utokens_lsubst|].\n              unfold get_cutokens_sub; simpl; boolvar; simpl;\n              autorewrite with slow; eauto 3 with slow.\n\n            + introv nrut' eqdoms disj'.\n              unflsubst; simpl; allrw @sub_filter_nil_r.\n              pose proof (sub_find_some_eq_doms_nr_ut_sub\n                            sub sub' x\n                            (oterm (NCan NCbv) [bterm [] (vterm x), bterm [x0] t])) as h; repeat (autodimp h hyp).\n              rw Heqsf in h; exrepnd; rw h0.\n              csunf; simpl.\n              eexists; dands; eauto.\n              unfold apply_bterm; simpl.\n              rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow.\n              eapply alpha_eq_trans;[|apply alpha_eq_sym; apply combine_1var_sub]; eauto 2 with slow; simpl.\n              fold_terms; rw <- @cl_lsubst_app; eauto 3 with slow; simpl.\n              unflsubst (@mk_var o x); simpl; rw h0.\n              apply alpha_eq_lsubst_if_ext_eq; auto.\n              introv i; simpl.\n              rw @sub_find_app; rw @sub_find_sub_filter_eq; rw memvar_singleton.\n              boolvar; simpl; boolvar; simpl; tcsp.\n              remember (sub_find sub' v) as sf; destruct sf; allsimpl; auto.\n\n          - repeat (destruct bs; allsimpl; ginv).\n            destruct b0 as [l1 t1]; allsimpl.\n            destruct b1 as [l2 t2]; allsimpl.\n            allunfold @nobnd.\n            destruct l1, l2; allsimpl; ginv.\n            allrw @sub_filter_nil_r; allrw app_nil_r; allrw remove_nvars_nil_l.\n\n            exists (mk_atom_eq t1 t1 (mk_var x) mk_bot).\n            unflsubst; simpl.\n            allrw @sub_filter_nil_r; allrw app_nil_r; allrw remove_nvars_nil_l;\n            allrw @sub_find_sub_filter_eq;\n            allrw; dands; eauto 3 with slow.\n\n            { allrw disjoint_app_r; repnd; dands; eauto 3 with slow. }\n\n            { allrw subvars_app_l; dands; eauto 3 with slow. }\n\n            introv nrut' eqdoms disj'.\n            unflsubst; simpl; allrw @sub_filter_nil_r.\n            pose proof (sub_find_some_eq_doms_nr_ut_sub\n                          sub sub' x\n                          (oterm (NCan NTryCatch) [bterm [] (vterm x), bterm [] t1, bterm [x0] t2])) as h; repeat (autodimp h hyp).\n            rw Heqsf in h; exrepnd; rw h0.\n            csunf; simpl.\n            eexists; dands; eauto; fold_terms.\n            unflsubst; simpl;\n            allrw @sub_filter_nil_r;\n            allrw @sub_find_sub_filter_eq;\n            allrw memvar_singleton;\n            allrw <- beq_var_refl;\n            allrw; auto.\n\n          - repndors; exrepnd; subst.\n\n            + repeat (destruct bs; allsimpl; ginv).\n              destruct b as [l1 u1].\n              destruct b0 as [l2 u2].\n              destruct b1 as [l3 u3]; allsimpl.\n              destruct l1, l2, l3; allsimpl; boolvar; ginv;[].\n              allrw @sub_filter_nil_r; allrw app_nil_r.\n              allunfold @nobnd.\n              repeat (apply cons_inj in comp1; repnd); GC; ginv.\n              inversion comp0 as [epk]; clear comp0.\n              fold_terms.\n\n              repndors; repnd; subst; allrw @sub_filter_nil_r.\n\n              * exists u2.\n                unflsubst; dands; eauto 4 with slow.\n\n                introv nrut' eqdoms disj'.\n                pose proof (sub_find_some_eq_doms_nr_ut_sub\n                              sub sub' x\n                              (oterm (NCan (NCompOp CompOpEq))\n                                     [nobnd (mk_var x), nobnd u1, nobnd u2, nobnd u3])) as h; repeat (autodimp h hyp).\n                rw Heqsf in h; exrepnd.\n                unflsubst; simpl; allrw @sub_filter_nil_r; allrw.\n                assert (disjoint (get_utokens_sub sub) (get_utokens u1)) as ni2.\n                { allrw disjoint_app_r; sp. }\n                applydup @sub_find_some in Heqsf.\n                unfold get_utokens_sub in ni2.\n                apply in_sub_eta in Heqsf0; repnd.\n                disj_flat_map; allsimpl; allrw disjoint_singleton_l.\n                eapply lsubst_aux_utoken_eq_utoken_implies in Heqsf2; eauto; exrepnd; subst; allsimpl; allrw Heqsf2; GC.\n                pose proof (nr_ut_sub_some_eq\n                              sub v x a (oterm (NCan (NCompOp CompOpEq))\n                                               [nobnd (mk_var x), nobnd (mk_var v), nobnd u2, nobnd u3]))\n                  as k; repeat (autodimp k hyp); subst; simpl; tcsp.\n                allrw; csunf; simpl; boolvar; allsimpl; tcsp; GC.\n                dcwf h; allsimpl.\n                unfold compute_step_comp; simpl; boolvar; tcsp; GC.\n                eexists; dands; eauto.\n                unflsubst; auto.\n\n              * exists u3.\n                unflsubst; dands; eauto 4 with slow.\n\n                introv nrut' eqdoms disj'.\n                pose proof (sub_find_some_eq_doms_nr_ut_sub\n                              sub sub' x\n                              (oterm (NCan (NCompOp CompOpEq))\n                                     [nobnd (mk_var x), nobnd u1, nobnd u2, nobnd u3])) as h; repeat (autodimp h hyp).\n                rw Heqsf in h; exrepnd.\n                unflsubst; simpl; allrw @sub_filter_nil_r; allrw app_nil_r; allrw.\n                allapply @lsubst_aux_pk2term_eq_utoken_implies_or; repndors; exrepnd; subst; allsimpl.\n\n                { dup epk1 as e.\n                  eapply nr_ut_some_implies in e;[|exact nrut].\n                  destruct e as [a' e].\n                  allapply @pk2term_utoken; subst; allsimpl.\n                  assert (a' <> a) as d by (intro e; subst; tcsp).\n\n                  pose proof (nr_ut_sub_some_diff\n                                sub v x a' a\n                                (oterm (NCan (NCompOp CompOpEq))\n                                       [nobnd (mk_var x), nobnd (mk_var v), nobnd u2, nobnd u3])) as h; repeat (autodimp h hyp).\n                  pose proof (sub_find_some_eq_doms_nr_ut_sub\n                                sub sub' v\n                                (oterm (NCan (NCompOp CompOpEq))\n                                       [nobnd (mk_var x), nobnd (mk_var v), nobnd u2, nobnd u3])) as k; repeat (autodimp k hyp).\n                  assert (sub_find sub v = Some (mk_utoken a')) as e by auto; allrw e; GC; exrepnd; rw k0.\n                  pose proof (nr_ut_sub_some_diff2\n                                sub' v x a1 a0\n                                (oterm (NCan (NCompOp CompOpEq))\n                                       [nobnd (mk_var x), nobnd (mk_var v), nobnd u2, nobnd u3])) as hh;\n                    repeat (autodimp hh hyp); allsimpl; tcsp.\n                  csunf; simpl; boolvar; allsimpl; tcsp; GC.\n                  dcwf q; allsimpl.\n                  unfold compute_step_comp; simpl; boolvar; ginv; tcsp.\n                  eexists; dands; eauto; unflsubst.\n                }\n\n                { allrw @lsubst_aux_pk2term.\n                  allrw @pk2term_eq; allsimpl; allrw app_nil_r.\n                  csunf; simpl.\n                  dcwf h.\n                  unfold compute_step_comp; simpl.\n                  allrw @get_param_from_cop_pk2can.\n                  boolvar; subst; eexists; dands; eauto; unflsubst.\n                  allsimpl.\n                  allrw disjoint_cons_r; repnd.\n                  apply sub_find_some in h0.\n                  rw @in_get_utokens_sub in disj'; destruct disj'.\n                  eexists; eexists; dands; eauto; simpl; auto.\n                }\n\n            + destruct bs; allsimpl; cpx.\n              destruct b as [l t].\n              destruct l; allsimpl; cpx; fold_terms; ginv.\n              allrw @sub_filter_nil_r.\n              pose proof (ind t t []) as h; repeat (autodimp h hyp); clear ind; eauto 3 with slow.\n              rw <- @cl_lsubst_lsubst_aux in comp1; eauto with slow.\n\n              allrw @nt_wf_NCompOp; exrepnd; ginv; allsimpl; autorewrite with slow in *.\n              allrw disjoint_app_r; repnd.\n\n              pose proof (h x0 sub) as k; clear h; repeat (autodimp k hyp).\n              { eapply nr_ut_sub_change_term;[|idtac|eauto];\n                allsimpl; allrw remove_nvars_nil_l; eauto with slow. }\n              exrepnd.\n\n              exists (oterm (NCan (NCompOp CompOpEq))\n                            (nobnd (mk_var x) :: nobnd w :: nobnd t3 :: nobnd t4 ::[])).\n              unflsubst; simpl; autorewrite with slow in *; allrw @sub_filter_nil_r; allrw.\n              dands; eauto 4 with slow.\n\n              * prove_alpha_eq4; allrw map_length.\n                introv k; destruct n; cpx.\n                destruct n; cpx.\n                apply alphaeqbt_nilv2.\n                unflsubst in k1.\n\n              * rw disjoint_app_r; dands; auto.\n                allrw disjoint_app_r; dands; eauto 3 with slow.\n\n              * introv nrut' eqdoms disj'.\n                unflsubst; simpl; allrw @sub_filter_nil_r.\n                pose proof (sub_find_some_eq_doms_nr_ut_sub\n                              sub sub' x\n                              (oterm (NCan (NCompOp CompOpEq))\n                                     (nobnd (mk_var x)\n                                            :: nobnd t2\n                                            :: nobnd t3\n                                            :: nobnd t4\n                                            :: []))) as h; repeat (autodimp h hyp).\n                rw Heqsf in h; exrepnd; allrw.\n                pose proof (k0 sub') as h; clear k0; repeat (autodimp h hyp).\n                { eapply nr_ut_sub_change_term;[|idtac|eauto];\n                  allsimpl; allrw remove_nvars_nil_l; eauto with slow. }\n                { allsimpl; introv i j; apply disj' in i.\n                  allrw in_app_iff; sp. }\n                exrepnd.\n                eapply isnoncan_like_lsubst_aux_nr_ut_implies in comp3; eauto.\n                unfold mk_utoken.\n                rw @compute_step_ncompop_ncanlike2; eauto with slow; boolvar; allsimpl; tcsp;[].\n                unflsubst in h2; fold_terms; rw h2.\n                eexists; dands; auto.\n                unflsubst; simpl; allrw @sub_filter_nil_r; allrw.\n\n                prove_alpha_eq4; allrw map_length.\n                introv k; destruct n; cpx.\n                destruct n; cpx.\n                apply alphaeqbt_nilv2.\n                unflsubst in h1.\n\n            + apply isexc_implies2 in comp2; exrepnd; subst.\n              destruct bs; allsimpl; ginv.\n              destruct b as [l1 t1].\n              destruct l1; allsimpl; ginv.\n              fold_terms; cpx.\n              allrw @sub_filter_nil_r.\n              destruct t1; allsimpl; ginv.\n              { remember (sub_find sub n) as sfn; symmetry in Heqsfn; destruct sfn; ginv.\n                apply sub_find_some in Heqsfn.\n                eapply in_nr_ut_sub in Heqsfn; eauto; exrepnd; ginv; auto. }\n              exists (oterm Exc l0).\n              unflsubst; simpl; dands; eauto 4 with slow.\n\n              introv nrut' eqdoms disj'.\n              pose proof (sub_find_some_eq_doms_nr_ut_sub\n                            sub sub' x\n                            (oterm (NCan (NCompOp CompOpEq))\n                                   (nobnd (mk_var x) :: nobnd (oterm Exc l0) :: bs))) as h; repeat (autodimp h hyp).\n              rw Heqsf in h; exrepnd; allrw.\n\n              unflsubst; simpl; allrw @sub_filter_nil_r; allrw.\n              csunf; simpl; boolvar; allsimpl; tcsp; GC.\n              eexists; dands; eauto.\n              unflsubst.\n\n          - repeat (destruct bs; allsimpl; ginv).\n            destruct b as [l1 u1].\n            destruct b0 as [l2 u2]; allsimpl.\n            destruct l1, l2; ginv; boolvar; tcsp; GC; fold_terms; ginv.\n            repndors; repnd; subst; allrw @sub_filter_nil_r.\n\n            + exists u1; unflsubst; dands; eauto 4 with slow.\n\n              introv nrut' eqdoms disj'.\n              unflsubst; simpl; boolvar.\n              allrw @sub_filter_nil_r.\n              pose proof (sub_find_some_eq_doms_nr_ut_sub\n                            sub sub' x\n                            (oterm (NCan (NCanTest CanIsuatom))\n                                   [nobnd (mk_var x), nobnd u1, nobnd u2])) as h; repeat (autodimp h hyp).\n              rw Heqsf in h; exrepnd; allrw.\n              csunf; simpl; eexists; dands; eauto.\n              unflsubst.\n\n            + exists u2; unflsubst; dands; eauto with slow.\n\n              introv nrut' eqdoms disj'.\n              unflsubst; simpl; boolvar.\n              allrw @sub_filter_nil_r.\n              pose proof (sub_find_some_eq_doms_nr_ut_sub\n                            sub sub' x\n                            (oterm (NCan (NCanTest x0))\n                                   [nobnd (mk_var x), nobnd u1, nobnd u2])) as h; repeat (autodimp h hyp).\n              rw Heqsf in h; exrepnd; allrw.\n              csunf; simpl; eexists; dands; eauto.\n              unflsubst.\n              destruct x0; sp.\n        }\n\n        { unflsubst in comp; allsimpl.\n          allrw @fold_get_utokens_step_seq_bterms.\n          allrw @fold_get_utokens_step_seq_ncan.\n          csunf comp; allsimpl.\n          dopid_noncan ncan SSCase; allsimpl; ginv.\n\n          - SSCase \"NApply\".\n            apply compute_step_seq_apply_success in comp; exrepnd; subst; allsimpl.\n            repeat (destruct bs; allsimpl; ginv).\n            allrw @fold_get_utokens_step_seq_bterm.\n            destruct b as [l t]; allsimpl.\n            allrw @fold_get_utokens_step_seq_arg1.\n            allunfold @nobnd.\n            destruct l; allsimpl; ginv.\n            autorewrite with slow in *.\n\n            exists (mk_eapply (mk_ntseq f) t).\n            unflsubst; simpl; autorewrite with slow in *; fold_terms.\n            allrw disjoint_app_r; repnd.\n            dands; eauto 3 with slow.\n\n            introv nrut' eqdoms' disj'.\n            unflsubst; simpl; autorewrite with slow in *.\n            csunf; simpl.\n            eexists; dands; eauto.\n            unflsubst; simpl; autorewrite with slow in *.\n            eauto 3 with slow.\n\n          - SSCase \"NEApply\".\n            apply compute_step_eapply_success in comp; exrepnd; subst.\n            allunfold @nobnd.\n            destruct bs; allsimpl; ginv.\n            allrw @fold_get_utokens_step_seq_bterm.\n            destruct b as [vs t]; allsimpl.\n            allrw @fold_get_utokens_step_seq_arg1.\n            destruct vs; allsimpl; ginv.\n            autorewrite with slow in *.\n            allrw disjoint_app_r; repnd.\n\n            repndors; exrepnd; subst; allsimpl.\n\n            + apply compute_step_eapply2_success in comp1; repnd.\n              destruct bs; allsimpl; ginv; autorewrite with slow in *.\n              repndors; exrepnd; subst; ginv;[]; allsimpl.\n\n              allrw @nt_wf_eapply_iff; exrepnd; ginv; allsimpl.\n              allrw @nt_wf_sterm_iff.\n              pose proof (wf2 n) as seq; repnd; clear wf2.\n\n              exists (f0 n).\n              unflsubst.\n              eapply lsubst_aux_equal_mk_nat in comp4; eauto;[]; subst; allsimpl; GC.\n              boolvar; try omega;[].\n              allrw @Znat.Nat2Z.id.\n              unfold oatoms.\n              autorewrite with slow in *.\n              rw @lsubst_aux_trivial_cl_term2; auto;[].\n              try (rewrite seq).\n              try (rewrite seq1).\n              dands; eauto 3 with slow.\n\n              * introv nrut' eqdoms' disj'.\n                unflsubst; simpl.\n                csunf; simpl.\n                dcwf h;[].\n                unfold compute_step_eapply2; simpl; boolvar; try omega;[]; GC.\n                allrw @Znat.Nat2Z.id.\n                eexists; dands; eauto.\n                unflsubst.\n                rw @lsubst_aux_trivial_cl_term2; auto.\n\n            + eapply isexc_lsubst_aux_nr_ut_sub in comp0; eauto;[].\n              allrw @nt_wf_eapply_iff; exrepnd; ginv; allsimpl.\n              allrw @nt_wf_sterm_iff; autorewrite with slow in *.\n              apply wf_isexc_implies in comp0; auto;[].\n              exrepnd; subst; allsimpl; autorewrite with slow in *.\n              exists (mk_exception a e); simpl; autorewrite with slow in *.\n              unflsubst; simpl; autorewrite with slow in *.\n              allrw disjoint_app_r.\n              allrw subvars_app_l; repnd.\n              allrw @oeqset_oappl_cons.\n              dands; eauto 3 with slow;[].\n\n              introv nrut' eqdoms' diff'.\n              allrw disjoint_app_r; repnd.\n              unflsubst; simpl; autorewrite with slow in *.\n              csunf; simpl.\n              dcwf h;[].\n              eexists; dands; eauto.\n              unflsubst; simpl; autorewrite with slow in *; eauto 3 with slow.\n\n            + allrw @nt_wf_eapply_iff; exrepnd; ginv; allsimpl.\n              allrw @nt_wf_sterm_iff; autorewrite with slow in *.\n              pose proof (ind b b []) as h; clear ind; repeat (autodimp h hyp); eauto 3 with slow.\n              pose proof (h x sub) as ih; clear h; repeat (autodimp ih hyp); eauto 3 with slow.\n              { unflsubst; auto. }\n              { eapply nr_ut_sub_change_term;[| |exact nrut]; simpl; autorewrite with slow; auto. }\n              exrepnd;[].\n\n              exists (mk_eapply (mk_ntseq f) w); simpl; autorewrite with slow.\n              unflsubst; simpl; autorewrite with slow.\n              unfold oatoms.\n              allrw @oeqset_oappl_cons; autorewrite with slow.\n              unflsubst in ih1.\n              dands; repeat (apply osubset_oapp_left); eauto 3 with slow.\n              { prove_alpha_eq3. }\n\n              introv nrut' eqdoms' disj'.\n              unflsubst; simpl; autorewrite with slow in *.\n              eapply isnoncan_like_lsubst_aux_nr_ut_implies in comp3; eauto;[].\n              fold_terms; unfold mk_eapply.\n              rw @compute_step_eapply_iscan_isnoncan_like; simpl; eauto 3 with slow;[].\n              pose proof (ih0 sub') as h'; clear ih0.\n              repeat (autodimp h' hyp); eauto 3 with slow.\n              { eapply nr_ut_sub_change_term;[| |exact nrut']; simpl; autorewrite with slow; auto. }\n              exrepnd.\n              unflsubst in h'1.\n              rw h'1.\n              eexists; dands; eauto.\n              unflsubst; simpl; autorewrite with slow.\n              unflsubst in h'0.\n              prove_alpha_eq3.\n\n          - SSCase \"NFix\".\n            autorewrite with slow in *.\n            apply compute_step_fix_success in comp; repnd; subst.\n            destruct bs; allsimpl; ginv.\n            apply nt_wf_NFix in wf; exrepnd; subst; allunfold @nobnd; ginv.\n\n            exists (mk_apply (mk_ntseq f) (mk_fix (mk_ntseq f))).\n            unflsubst; simpl.\n            autorewrite with slow.\n            allrw @oeqset_oappl_cons; autorewrite with slow.\n            dands; repeat (apply osubset_oapp_left); eauto 3 with slow.\n\n            introv nrut' eqdoms' disj'.\n            unflsubst; simpl.\n            csunf; simpl.\n            eexists; dands; eauto.\n\n          - SSCase \"NCbv\".\n            autorewrite with slow in *.\n            apply nt_wf_NCbv in wf; exrepnd; allunfold @nobnd; ginv.\n            unfold apply_bterm; simpl.\n            repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n\n            exists (subst b v (mk_ntseq f)).\n            allsimpl; autorewrite with slow in *.\n\n            dands; eauto 3 with slow.\n\n            + pose proof (combine_sub_nest b (sub_filter sub [v]) [(v, mk_ntseq f)]) as aeq1.\n              rw @lsubst_sub_shallow_cl_sub in aeq1; eauto 3 with slow.\n              pose proof (combine_sub_nest b [(v,mk_ntseq f)] sub) as aeq2.\n              allrw @fold_subst.\n              eapply alpha_eq_trans;[clear aeq2|apply alpha_eq_sym;exact aeq2].\n              eapply alpha_eq_trans;[exact aeq1|clear aeq1].\n              apply alpha_eq_lsubst_if_ext_eq; auto.\n              unfold ext_alpha_eq_subs; simpl; introv i.\n              rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n              boolvar; simpl; boolvar; simpl; tcsp; GC.\n              remember (sub_find sub v0) as sf; destruct sf; simpl; tcsp.\n\n            + eapply disjoint_eqset_r;[apply eqset_sym; apply get_utokens_subst|].\n              boolvar; allrw disjoint_app_r; dands; eauto 3 with slow.\n\n            + eapply subvars_eqvars;[|apply eqvars_sym;apply eqvars_free_vars_disjoint].\n              allsimpl.\n              apply subvars_app_l; dands; auto.\n              boolvar; simpl; auto.\n\n            + eapply subset_eqset_l;[apply eqset_sym;apply get_utokens_subst|].\n              boolvar; simpl; autorewrite with slow; auto.\n\n            + introv nrut' eqdoms' disj'.\n              unflsubst; simpl.\n              csunf; simpl.\n              unfold apply_bterm; simpl.\n              eexists; dands; eauto.\n              repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n\n              pose proof (combine_sub_nest b (sub_filter sub' [v]) [(v, mk_ntseq f)]) as aeq1.\n              rw @lsubst_sub_shallow_cl_sub in aeq1; eauto 3 with slow;[].\n              pose proof (combine_sub_nest b [(v,mk_ntseq f)] sub') as aeq2.\n              allrw @fold_subst.\n              eapply alpha_eq_trans;[clear aeq2|apply alpha_eq_sym;exact aeq2].\n              eapply alpha_eq_trans;[exact aeq1|clear aeq1].\n              apply alpha_eq_lsubst_if_ext_eq; auto.\n              unfold ext_alpha_eq_subs; simpl; introv i.\n              rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n              boolvar; simpl; boolvar; simpl; tcsp; GC.\n              remember (sub_find sub' v0) as sf; destruct sf; simpl; tcsp.\n\n          - SSCase \"NTryCatch\".\n            allsimpl; autorewrite with slow in *.\n            allrw @nt_wf_NTryCatch; exrepnd; allunfold @nobnd; ginv.\n            allsimpl; autorewrite with slow in *.\n            exists (mk_atom_eq b b (mk_ntseq f) mk_bot).\n            unflsubst; simpl; autorewrite with slow in *.\n            allrw @sub_find_sub_filter_eq.\n            allrw memvar_singleton; boolvar; tcsp;[]; fold_terms.\n            allrw subvars_app_l.\n            allrw disjoint_app_r; repnd.\n            allrw @oeqset_oappl_cons.\n            dands; repeat (apply osubset_oapp_left); dands; eauto 4 with slow.\n\n            introv nrut' eqdoms' disj'.\n            unflsubst; simpl; autorewrite with slow in *.\n            csunf; simpl.\n            unflsubst; simpl; autorewrite with slow in *.\n            allrw @sub_find_sub_filter_eq.\n            allrw memvar_singleton; boolvar; tcsp;[]; fold_terms.\n            eexists; dands; eauto 3 with slow.\n\n          - SSCase \"NCanTest\".\n            apply compute_step_seq_can_test_success in comp; exrepnd; subst.\n            allrw @nt_wf_NCanTest; exrepnd; allunfold @nobnd; ginv; allsimpl.\n            autorewrite with slow in *.\n            allrw disjoint_app_r; repnd.\n\n            exists t3.\n            unflsubst.\n            dands; eauto 3 with slow.\n\n            introv nrut' eqdoms' disj'.\n            allrw disjoint_app_r.\n            unflsubst; simpl; autorewrite with slow in *.\n            csunf; simpl.\n            eexists; dands; eauto.\n            unflsubst; auto.\n        }\n\n        dopid op as [can2|ncan2|exc2|abs2] SSCase.\n\n        * SSCase \"Can\".\n          dopid_noncan ncan SSSCase.\n\n          { SSSCase \"NApply\".\n\n            clear ind; unflsubst in comp; allsimpl; csunf comp; simpl in comp.\n            apply compute_step_apply_success in comp; repndors; exrepnd; subst; fold_terms.\n\n            { repeat (destruct bs; allsimpl; ginv).\n              repeat (destruct bts; allsimpl; ginv).\n              destruct b0 as [l1 u1].\n              destruct b1 as [l2 u2].\n              destruct l1; allsimpl; ginv; fold_terms; cpx.\n              allrw @sub_filter_nil_r.\n\n              - exists (subst u2 v u1).\n                rw <- @cl_lsubst_lsubst_aux; try (complete (boolvar; eauto with slow)).\n                unfold subst.\n                autorewrite with slow in *.\n                dands; eauto 3 with slow.\n\n                + pose proof (combine_sub_nest u2 [(v, u1)] sub) as h.\n                  eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                  pose proof (combine_sub_nest u2 (sub_filter sub [v]) [(v, lsubst_aux u1 sub)]) as h.\n                  eapply alpha_eq_trans;[apply h|]; clear h.\n                  simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                  apply alpha_eq_lsubst_if_ext_eq; auto.\n                  rw <- @cl_lsubst_lsubst_aux; eauto with slow.\n                  unfold ext_alpha_eq_subs; simpl; introv i.\n                  rw @sub_find_app; rw @sub_find_sub_filter_eq; rw memvar_singleton.\n                  boolvar; simpl; boolvar; simpl; tcsp.\n                  remember (sub_find sub v0) as sf; destruct sf; simpl; tcsp.\n\n                + eapply subset_disjoint_r;[exact disj|]; simpl.\n                  eapply subset_eqset_l;[apply eqset_sym; apply get_utokens_lsubst|].\n                  simpl; boolvar; unfold get_utokens_sub; simpl; allrw app_nil_r; eauto with slow.\n\n                + allrw remove_nvars_nil_l; allrw app_nil_r.\n                  eapply subvars_eqvars;[|apply eqvars_sym; apply eqvars_free_vars_disjoint].\n                  simpl; boolvar; simpl; allrw app_nil_r; eauto with slow.\n\n                + autorewrite with slow.\n                  eapply subset_eqset_l;[apply eqset_sym;apply get_utokens_lsubst|].\n                  apply subset_app; dands; eauto 3 with slow.\n                  unfold get_utokens_sub; simpl; boolvar; simpl;\n                  autorewrite with slow; eauto 3 with slow.\n\n                + introv nrut' eqdoms diff'.\n                  unflsubst; simpl; allrw @sub_filter_nil_r.\n                  csunf; simpl.\n                  allrw <- @cl_lsubst_lsubst_aux; eauto with slow.\n                  eexists; dands; eauto.\n                  unfold apply_bterm; simpl.\n\n                  pose proof (combine_sub_nest u2 [(v,u1)] sub') as h.\n                  eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                  pose proof (combine_sub_nest u2 (sub_filter sub' [v]) [(v, lsubst u1 sub')]) as h.\n                  eapply alpha_eq_trans;[apply h|]; clear h.\n                  simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                  apply alpha_eq_lsubst_if_ext_eq; auto.\n                  unfold ext_alpha_eq_subs; simpl; introv i.\n                  rw @sub_find_app; rw @sub_find_sub_filter_eq; rw memvar_singleton.\n                  boolvar; simpl; boolvar; simpl; tcsp.\n                  remember (sub_find sub' v0) as sf; destruct sf; simpl; tcsp.\n            }\n\n            { destruct bts; ginv.\n              repeat (destruct bs; allsimpl; ginv).\n              destruct b as [l t].\n              destruct l; allsimpl; ginv.\n              allrw @sub_filter_nil_r; fold_terms; ginv.\n              allrw app_nil_r; allrw remove_nvars_nil_l.\n\n              exists (mk_apseq f t).\n              simpl; autorewrite with slow in *.\n              dands; eauto 3 with slow.\n\n              - unflsubst; simpl.\n                allrw @sub_filter_nil_r; fold_terms; auto.\n\n              - introv nrut' eqdoms diff'.\n                unflsubst; simpl; allrw @sub_filter_nil_r; fold_terms.\n                csunf; simpl.\n                eexists; dands; eauto.\n\n                unflsubst; simpl.\n                allrw @sub_filter_nil_r; fold_terms; auto.\n            }\n          }\n\n          { SSSCase \"NEApply\".\n\n            unflsubst in comp; allsimpl.\n            apply nt_wf_eapply_iff in wf; exrepnd; ginv.\n            csunf comp; allsimpl.\n            eapply compute_step_eapply_success in comp; exrepnd.\n            allunfold @nobnd; allsimpl; ginv; autorewrite with slow in *.\n            allrw disjoint_app_r; repnd.\n\n            repndors; exrepnd; subst.\n\n            - apply compute_step_eapply2_success in comp1; repnd; GC.\n              repndors; exrepnd; allsimpl; subst; ginv.\n\n              + repeat (destruct bts; allsimpl; ginv;[]).\n                destruct b1; allsimpl; ginv.\n                unfold mk_lam in comp3; ginv; autorewrite with slow in *.\n                unfold apply_bterm; simpl.\n                repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n\n                exists (subst n v b).\n                allsimpl; autorewrite with slow in *.\n\n                dands; eauto 3 with slow.\n\n                * eapply alpha_eq_trans;[apply combine_sub_nest|].\n                  eapply alpha_eq_trans;[|apply alpha_eq_sym; apply combine_sub_nest].\n                  simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow;[].\n                  apply alpha_eq_lsubst_if_ext_eq; auto.\n                  unfold ext_alpha_eq_subs; simpl; introv i.\n                  rw @sub_find_app; allrw @sub_find_sub_filter_eq; allrw memvar_cons.\n                  boolvar; simpl; boolvar; simpl; tcsp; GC;[].\n                  remember (sub_find sub v0) as sf; destruct sf; simpl; tcsp.\n\n                * eapply disjoint_eqset_r;[apply eqset_sym;apply get_utokens_subst|].\n                  allrw disjoint_app_r; dands; eauto 3 with slow.\n                  boolvar; eauto 3 with slow.\n\n                * eapply subvars_eqvars;[|apply eqvars_sym; apply eqvars_free_vars_disjoint].\n                  simpl; allrw subvars_app_l; dands; eauto 3 with slow.\n                  boolvar; simpl; autorewrite with slow; eauto 3 with slow.\n\n                * autorewrite with slow.\n                  eapply subset_eqset_l;[apply eqset_sym;apply get_utokens_lsubst|].\n                  apply subset_app; dands; eauto 3 with slow.\n                  unfold get_utokens_sub; simpl; boolvar; simpl;\n                  autorewrite with slow; eauto 3 with slow.\n\n                * introv nrut' eqdoms diff'.\n                  unflsubst; simpl; autorewrite with slow in *.\n                  fold_terms; unfold mk_eapply.\n                  rw @compute_step_eapply_lam_iscan; eauto 3 with slow;[].\n                  eexists; dands; eauto.\n                  repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow;[]).\n\n                  eapply alpha_eq_trans;[|apply alpha_eq_sym; apply combine_sub_nest].\n                  eapply alpha_eq_trans;[apply combine_sub_nest|].\n                  simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow;[].\n                  apply alpha_eq_lsubst_if_ext_eq; auto.\n                  unfold ext_alpha_eq_subs; simpl; introv i.\n                  rw @sub_find_app; rw @sub_find_sub_filter_eq; rw memvar_singleton.\n                  boolvar; simpl; boolvar; simpl; tcsp.\n                  remember (sub_find sub' v0) as sf; destruct sf; simpl; tcsp.\n\n            - eapply isexc_lsubst_aux_nr_ut_sub in comp0; eauto;[].\n              apply wf_isexc_implies in comp0; exrepnd; subst; allsimpl; autorewrite with slow in *; auto;[].\n              allrw disjoint_app_r; repnd.\n              exists (mk_exception a e); unflsubst; simpl; autorewrite with slow in *.\n              allrw disjoint_app_r.\n              allrw subvars_app_l.\n              allrw @oappl_app_as_oapp.\n              allrw @oeqset_oappl_cons; autorewrite with slow in *.\n              dands; eauto 3 with slow.\n\n              introv nrut' eqdoms' disj'.\n              allrw disjoint_app_r; repnd.\n              unflsubst; simpl; autorewrite with slow in *.\n              fold_terms; unfold mk_eapply.\n              rw @compute_step_eapply_iscan_isexc; simpl; eauto 3 with slow;\n              [|eapply eapply_wf_def_len_implies;[|eauto];\n                allrw map_map; unfold compose;\n                apply eq_maps; introv i; destruct x; simpl; unfold num_bvars; simpl; auto].\n              eexists; dands; eauto.\n              unflsubst; simpl; autorewrite with slow in *; auto.\n\n            - pose proof (ind b b []) as h; clear ind.\n              repeat (autodimp h hyp); eauto 3 with slow;[].\n              pose proof (h x sub) as ih; clear h.\n              rw <- @cl_lsubst_lsubst_aux in comp1; eauto 3 with slow;[].\n              repeat (autodimp ih hyp); eauto 3 with slow.\n              { eapply nr_ut_sub_change_term;[| |exact nrut]; simpl;\n                autorewrite with slow in *; eauto 3 with slow. }\n              exrepnd.\n\n              exists (mk_eapply (oterm (Can can2) bts) w).\n              unflsubst; simpl; autorewrite with slow in *.\n              allrw disjoint_app_r; repnd.\n              allrw subvars_app_l.\n              allrw @oappl_app_as_oapp.\n              allrw @oeqset_oappl_cons; autorewrite with slow in *.\n              rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow;[].\n              dands; eauto 3 with slow.\n\n              + prove_alpha_eq3.\n\n              + introv nrut' eqdoms' disj'.\n                unflsubst; simpl; autorewrite with slow in *.\n                eapply isnoncan_like_lsubst_aux_nr_ut_implies in comp3; eauto;[].\n                fold_terms; unfold mk_eapply.\n                rw @compute_step_eapply_iscan_isnoncan_like; simpl; eauto 3 with slow;\n                [|eapply eapply_wf_def_len_implies;[|eauto];\n                  allrw map_map; unfold compose;\n                  apply eq_maps; introv i; destruct x0; simpl; unfold num_bvars; simpl; auto];\n                [].\n                pose proof (ih0 sub') as h'; clear ih0.\n                repeat (autodimp h' hyp); eauto 3 with slow.\n                { eapply nr_ut_sub_change_term;[| |exact nrut']; simpl;\n                  autorewrite with slow; eauto 3 with slow. }\n                exrepnd.\n                unflsubst in h'1.\n                rw h'1.\n                eexists; dands; eauto.\n                unflsubst; simpl; autorewrite with slow.\n                unflsubst in h'0.\n                prove_alpha_eq3.\n          }\n\n          { SSSCase \"NApseq\".\n\n            clear ind.\n            unflsubst in comp; allsimpl.\n            csunf comp; allsimpl.\n            apply compute_step_apseq_success in comp; exrepnd; subst; allsimpl.\n            repeat (destruct bts; allsimpl; ginv).\n            repeat (destruct bs; allsimpl; ginv).\n            fold_terms.\n\n            exists (@mk_nat o (n n0)).\n            unflsubst; simpl; fold_terms.\n            autorewrite with slow.\n            dands; eauto 3 with slow.\n            introv nrut' eqdoms diff'.\n            unflsubst; simpl.\n            csunf; simpl.\n            boolvar; try omega.\n            rw @Znat.Nat2Z.id.\n            eexists; dands; eauto.\n          }\n\n          { SSSCase \"NFix\".\n\n            clear ind; unflsubst in comp; allsimpl; csunf comp; simpl in comp.\n            apply compute_step_fix_success in comp; exrepnd; subst; fold_terms.\n            repeat (destruct bs; allsimpl; ginv).\n            allrw @sub_filter_nil_r.\n            exists (mk_apply (oterm (Can can2) bts) (mk_fix (oterm (Can can2) bts))).\n            unflsubst; simpl; autorewrite with slow.\n            allrw @oappl_app_as_oapp.\n            allrw @oeqset_oappl_cons; autorewrite with slow in *.\n            allrw @osubset_oapp_left_iff.\n            allrw disjoint_app_r; repnd.\n            allrw subset_app.\n\n            dands; eauto 3 with slow.\n\n            { introv nrut' eqdoms diff'.\n              unflsubst; simpl; allrw @sub_filter_nil_r.\n              csunf; simpl.\n              eexists; dands; eauto.\n              unflsubst; simpl; allrw @sub_filter_nil_r; auto.\n            }\n          }\n\n          { SSSCase \"NSpread\".\n\n            clear ind; unflsubst in comp; allsimpl; csunf comp; simpl in comp.\n            apply compute_step_spread_success in comp; exrepnd; subst; fold_terms.\n            repeat (destruct bs; allsimpl; ginv).\n            repeat (destruct bts; allsimpl; ginv).\n            destruct b0 as [l1 u1].\n            destruct b1 as [l2 u2].\n            destruct b2 as [l3 u3].\n            destruct l1; allsimpl; ginv; fold_terms; cpx.\n            autorewrite with slow in *.\n            allunfold @nobnd; ginv; allsimpl.\n\n            - exists (lsubst u1 [(va,u2),(vb,u3)]).\n              repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n              dands.\n\n              + pose proof (combine_sub_nest u1 [(va,u2),(vb,u3)] sub) as h.\n                eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                pose proof (combine_sub_nest u1 (sub_filter sub [va,vb]) [(va,lsubst u2 sub),(vb,lsubst u3 sub)]) as h.\n                eapply alpha_eq_trans;[apply h|]; clear h.\n                simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                apply alpha_eq_lsubst_if_ext_eq; auto.\n                unfold ext_alpha_eq_subs; simpl; introv i.\n                rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n                boolvar; simpl; boolvar; simpl; tcsp.\n                remember (sub_find sub v) as sf; destruct sf; simpl; tcsp.\n\n              + eapply subset_disjoint_r;[exact disj|]; simpl.\n                eapply subset_eqset_l;[apply eqset_sym; apply get_utokens_lsubst|].\n                simpl; boolvar; unfold get_utokens_sub; simpl; allrw app_nil_r;\n                allrw subset_app; dands; eauto with slow.\n\n              + allrw remove_nvars_nil_l; allrw app_nil_r.\n                eapply subvars_eqvars;[|apply eqvars_sym; apply eqvars_free_vars_disjoint].\n                simpl; boolvar; simpl; allrw app_nil_r; eauto with slow.\n\n              + eapply subset_eqset_l;[apply eqset_sym;apply get_utokens_lsubst|].\n                apply subset_app; dands; eauto 3 with slow.\n                unfold get_utokens_sub; simpl; boolvar; simpl;\n                autorewrite with slow; eauto 3 with slow.\n\n              + introv nrut' eqdoms diff'.\n                unflsubst; simpl.\n                csunf; simpl; allrw @sub_filter_nil_r.\n                eexists; dands; eauto.\n                unfold apply_bterm; simpl; allrw @lsubst_aux_nil.\n                repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n\n                pose proof (combine_sub_nest u1 [(va,u2),(vb,u3)] sub') as h.\n                eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                pose proof (combine_sub_nest u1 (sub_filter sub' [va,vb]) [(va,lsubst u2 sub'),(vb,lsubst u3 sub')]) as h.\n                eapply alpha_eq_trans;[apply h|]; clear h.\n                simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                apply alpha_eq_lsubst_if_ext_eq; auto.\n                unfold ext_alpha_eq_subs; simpl; introv i.\n                rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n                boolvar; simpl; boolvar; simpl; tcsp.\n                remember (sub_find sub' v) as sf; destruct sf; simpl; tcsp.\n          }\n\n          { SSSCase \"NDsup\".\n\n            clear ind; unflsubst in comp; allsimpl; csunf comp; simpl in comp.\n            apply compute_step_dsup_success in comp; exrepnd; subst; fold_terms.\n            repeat (destruct bs; allsimpl; ginv).\n            repeat (destruct bts; allsimpl; ginv).\n            destruct b0 as [l1 u1].\n            destruct b1 as [l2 u2].\n            destruct b2 as [l3 u3].\n            destruct l1; allsimpl; ginv; fold_terms; cpx.\n            autorewrite with slow in *.\n            allunfold @nobnd; ginv; allsimpl.\n\n            - exists (lsubst u1 [(va,u2),(vb,u3)]).\n              repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n              dands.\n\n              + pose proof (combine_sub_nest u1 [(va,u2),(vb,u3)] sub) as h.\n                eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                pose proof (combine_sub_nest u1 (sub_filter sub [va,vb]) [(va,lsubst u2 sub),(vb,lsubst u3 sub)]) as h.\n                eapply alpha_eq_trans;[apply h|]; clear h.\n                simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                apply alpha_eq_lsubst_if_ext_eq; auto.\n                unfold ext_alpha_eq_subs; simpl; introv i.\n                rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n                boolvar; simpl; boolvar; simpl; tcsp.\n                remember (sub_find sub v) as sf; destruct sf; simpl; tcsp.\n\n              + eapply subset_disjoint_r;[exact disj|]; simpl.\n                eapply subset_eqset_l;[apply eqset_sym; apply get_utokens_lsubst|].\n                simpl; boolvar; unfold get_utokens_sub; simpl; allrw app_nil_r;\n                allrw subset_app; dands; eauto with slow.\n\n              + allrw remove_nvars_nil_l; allrw app_nil_r.\n                eapply subvars_eqvars;[|apply eqvars_sym; apply eqvars_free_vars_disjoint].\n                simpl; boolvar; simpl; allrw app_nil_r; eauto with slow.\n\n              + eapply subset_eqset_l;[apply eqset_sym;apply get_utokens_lsubst|].\n                apply subset_app; dands; eauto 3 with slow.\n                unfold get_utokens_sub; simpl; boolvar; simpl;\n                autorewrite with slow; eauto 3 with slow.\n\n              + introv nrut' eqdoms diff'.\n                unflsubst; simpl.\n                csunf; simpl; allrw @sub_filter_nil_r.\n                eexists; dands; eauto.\n                unfold apply_bterm; simpl; allrw @lsubst_aux_nil.\n                repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n\n                pose proof (combine_sub_nest u1 [(va,u2),(vb,u3)] sub') as h.\n                eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                pose proof (combine_sub_nest u1 (sub_filter sub' [va,vb]) [(va,lsubst u2 sub'),(vb,lsubst u3 sub')]) as h.\n                eapply alpha_eq_trans;[apply h|]; clear h.\n                simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                apply alpha_eq_lsubst_if_ext_eq; auto.\n                unfold ext_alpha_eq_subs; simpl; introv i.\n                rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n                boolvar; simpl; boolvar; simpl; tcsp.\n                remember (sub_find sub' v) as sf; destruct sf; simpl; tcsp.\n          }\n\n          { SSSCase \"NDecide\".\n\n            clear ind; unflsubst in comp; allsimpl; csunf comp; simpl in comp.\n            apply compute_step_decide_success in comp; exrepnd; subst; fold_terms.\n            repeat (destruct bs; allsimpl; ginv).\n            repeat (destruct bts; allsimpl; ginv).\n            destruct b0 as [l1 u1].\n            destruct b1 as [l2 u2].\n            destruct b as [l3 u3].\n            destruct l1; allsimpl; ginv; fold_terms; cpx.\n            autorewrite with slow in *.\n            allunfold @nobnd; ginv; allsimpl.\n\n            repndors; repnd; subst; ginv; cpx; allrw memvar_singleton.\n\n            - exists (subst u3 v1 u2).\n              unfold subst.\n              repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n              dands.\n\n              + pose proof (combine_sub_nest u3 [(v1,u2)] sub) as h.\n                eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                pose proof (combine_sub_nest u3 (sub_filter sub [v1]) [(v1,lsubst u2 sub)]) as h.\n                eapply alpha_eq_trans;[apply h|]; clear h.\n                simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                apply alpha_eq_lsubst_if_ext_eq; auto.\n                unfold ext_alpha_eq_subs; simpl; introv i.\n                rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n                boolvar; simpl; boolvar; simpl; tcsp.\n                remember (sub_find sub v) as sf; destruct sf; simpl; tcsp.\n\n              + eapply subset_disjoint_r;[exact disj|]; simpl.\n                eapply subset_eqset_l;[apply eqset_sym; apply get_utokens_lsubst|].\n                simpl; boolvar; unfold get_utokens_sub; simpl; allrw app_nil_r;\n                allrw subset_app; dands; eauto with slow.\n\n              + allrw remove_nvars_nil_l; allrw app_nil_r.\n                eapply subvars_eqvars;[|apply eqvars_sym; apply eqvars_free_vars_disjoint].\n                simpl; boolvar; simpl; allrw app_nil_r; eauto with slow.\n\n              + eapply subset_eqset_l;[apply eqset_sym;apply get_utokens_lsubst|].\n                apply subset_app; dands; eauto 3 with slow.\n                unfold get_utokens_sub; simpl; boolvar; simpl;\n                autorewrite with slow; eauto 3 with slow.\n\n              + introv nrut' eqdoms diff'.\n                unflsubst; simpl.\n                allrw @sub_filter_nil_r; allsimpl.\n                csunf; simpl.\n                eexists; dands; eauto.\n                unfold apply_bterm; simpl; allrw @lsubst_aux_nil.\n                repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n\n                pose proof (combine_sub_nest u3 [(v1,u2)] sub') as h.\n                eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                pose proof (combine_sub_nest u3 (sub_filter sub' [v1]) [(v1,lsubst u2 sub')]) as h.\n                eapply alpha_eq_trans;[apply h|]; clear h.\n                simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                apply alpha_eq_lsubst_if_ext_eq; auto.\n                unfold ext_alpha_eq_subs; simpl; introv i.\n                rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n                boolvar; simpl; boolvar; simpl; tcsp.\n                remember (sub_find sub' v) as sf; destruct sf; simpl; tcsp.\n\n            - exists (subst u1 v2 u2).\n              unfold subst.\n              repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n              dands.\n\n              + pose proof (combine_sub_nest u1 [(v2,u2)] sub) as h.\n                eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                pose proof (combine_sub_nest u1 (sub_filter sub [v2]) [(v2,lsubst u2 sub)]) as h.\n                eapply alpha_eq_trans;[apply h|]; clear h.\n                simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                apply alpha_eq_lsubst_if_ext_eq; auto.\n                unfold ext_alpha_eq_subs; simpl; introv i.\n                rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n                boolvar; simpl; boolvar; simpl; tcsp.\n                remember (sub_find sub v) as sf; destruct sf; simpl; tcsp.\n\n              + eapply subset_disjoint_r;[exact disj|]; simpl.\n                eapply subset_eqset_l;[apply eqset_sym; apply get_utokens_lsubst|].\n                simpl; boolvar; unfold get_utokens_sub; simpl; allrw app_nil_r;\n                allrw subset_app; dands; eauto with slow.\n\n              + allrw remove_nvars_nil_l; allrw app_nil_r.\n                eapply subvars_eqvars;[|apply eqvars_sym; apply eqvars_free_vars_disjoint].\n                simpl; boolvar; simpl; allrw app_nil_r; eauto with slow.\n\n              + eapply subset_eqset_l;[apply eqset_sym;apply get_utokens_lsubst|].\n                apply subset_app; dands; eauto 3 with slow.\n                unfold get_utokens_sub; simpl; boolvar; simpl;\n                autorewrite with slow; eauto 3 with slow.\n\n              + introv nrut' eqdoms diff'.\n                unflsubst; simpl.\n                allrw @sub_filter_nil_r; allsimpl.\n                csunf; simpl.\n                eexists; dands; eauto.\n                unfold apply_bterm; simpl; allrw @lsubst_aux_nil.\n                repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n\n                pose proof (combine_sub_nest u1 [(v2,u2)] sub') as h.\n                eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                pose proof (combine_sub_nest u1 (sub_filter sub' [v2]) [(v2,lsubst u2 sub')]) as h.\n                eapply alpha_eq_trans;[apply h|]; clear h.\n                simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                apply alpha_eq_lsubst_if_ext_eq; auto.\n                unfold ext_alpha_eq_subs; simpl; introv i.\n                rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n                boolvar; simpl; boolvar; simpl; tcsp.\n                remember (sub_find sub' v) as sf; destruct sf; simpl; tcsp.\n          }\n\n          { SSSCase \"NCbv\".\n\n            clear ind; unflsubst in comp; allsimpl; csunf comp; simpl in comp.\n            apply compute_step_cbv_success in comp; exrepnd; subst; fold_terms.\n            repeat (destruct bs; allsimpl; ginv).\n            destruct b as [l1 u1].\n            destruct l1; allsimpl; ginv; fold_terms; cpx.\n            autorewrite with slow in *.\n\n            - exists (subst u1 v (oterm (Can can2) bts)).\n              repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n              unfold subst.\n              dands.\n\n              + pose proof (combine_sub_nest u1 [(v,oterm (Can can2) bts)] sub) as h.\n                eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                pose proof (combine_sub_nest u1 (sub_filter sub [v]) [(v, lsubst_aux (oterm (Can can2) bts) sub)]) as h.\n                eapply alpha_eq_trans;[apply h|]; clear h.\n                repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n                simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                apply alpha_eq_lsubst_if_ext_eq; auto.\n                unfold ext_alpha_eq_subs; simpl; introv i.\n                rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n                boolvar; simpl; boolvar; simpl; tcsp.\n                remember (sub_find sub v0) as sf; destruct sf; simpl; tcsp.\n\n              + eapply subset_disjoint_r;[exact disj|]; simpl.\n                eapply subset_eqset_l;[apply eqset_sym; apply get_utokens_lsubst|].\n                simpl; boolvar; unfold get_utokens_sub; simpl; allrw app_nil_r;\n                allrw subset_app; dands; eauto 3 with slow.\n\n              + allrw remove_nvars_nil_l; allrw app_nil_r.\n                eapply subvars_eqvars;[|apply eqvars_sym; apply eqvars_free_vars_disjoint].\n                simpl; boolvar; simpl; allrw app_nil_r; eauto with slow.\n\n              + eapply subset_eqset_l;[apply eqset_sym;apply get_utokens_lsubst|].\n                apply subset_app; dands; eauto 3 with slow.\n                unfold get_utokens_sub; simpl; boolvar; simpl;\n                autorewrite with slow; eauto 3 with slow.\n\n              + introv nrut' eqdoms diff'.\n                unflsubst; simpl.\n                allrw @sub_filter_nil_r.\n                csunf; simpl.\n                eexists; dands; eauto.\n                unfold apply_bterm; simpl; allrw @lsubst_aux_nil.\n                repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n\n                pose proof (combine_sub_nest u1 [(v,oterm (Can can2) bts)] sub') as h.\n                eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                pose proof (combine_sub_nest u1 (sub_filter sub' [v]) [(v, lsubst_aux (oterm (Can can2) bts) sub')]) as h.\n                eapply alpha_eq_trans;[apply h|]; clear h.\n                repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n                simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                apply alpha_eq_lsubst_if_ext_eq; auto.\n                unfold ext_alpha_eq_subs; simpl; introv i.\n                rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n                boolvar; simpl; boolvar; simpl; tcsp.\n                remember (sub_find sub' v0) as sf; destruct sf; simpl; tcsp.\n          }\n\n          { SSSCase \"NSleep\".\n\n            clear ind; unflsubst in comp; allsimpl; csunf comp; simpl in comp.\n            apply compute_step_sleep_success in comp; exrepnd; subst; fold_terms.\n            repeat (destruct bs; allsimpl; ginv).\n            repeat (destruct bts; allsimpl; ginv).\n\n            - exists (@mk_axiom o).\n              unflsubst; simpl; dands; eauto 3 with slow.\n\n              introv nrut' eqdoms diff'.\n              repeat (unflsubst; simpl).\n              csunf; simpl.\n              unfold compute_step_sleep; simpl.\n              eexists; dands; eauto.\n          }\n\n          { SSSCase \"NTUni\".\n\n            clear ind; unflsubst in comp; allsimpl; csunf comp; simpl in comp.\n            apply compute_step_tuni_success in comp; exrepnd; subst; fold_terms.\n            repeat (destruct bs; allsimpl; ginv).\n            repeat (destruct bts; allsimpl; ginv).\n\n            - exists (@mk_uni o n).\n              unflsubst; simpl; dands; eauto 3 with slow.\n\n              introv nrut' eqdoms diff'.\n              repeat (unflsubst; simpl).\n              csunf; simpl.\n              unfold compute_step_tuni; simpl.\n              boolvar; try omega.\n              eexists; dands; eauto.\n              rw Znat.Nat2Z.id; auto.\n          }\n\n          { SSSCase \"NMinus\".\n\n            clear ind; unflsubst in comp; allsimpl; csunf comp; simpl in comp.\n            apply compute_step_minus_success in comp; exrepnd; subst; fold_terms.\n            repeat (destruct bs; allsimpl; ginv).\n            repeat (destruct bts; allsimpl; ginv).\n\n            - exists (@mk_integer o (- z)).\n              unflsubst; simpl; dands; eauto 3 with slow.\n\n              introv nrut' eqdoms diff'.\n              repeat (unflsubst; simpl).\n              csunf; simpl.\n              unfold compute_step_minus; simpl.\n              eexists; dands; eauto.\n          }\n\n          { SSSCase \"NFresh\".\n\n            clear ind; unflsubst in comp; allsimpl; csunf comp; simpl in comp; ginv.\n          }\n\n          { SSSCase \"NTryCatch\".\n\n            clear ind; unflsubst in comp; allsimpl; csunf comp; simpl in comp.\n            allrw @sub_filter_nil_r.\n            apply compute_step_try_success in comp; exrepnd; subst; fold_terms.\n            repeat (destruct bs; allsimpl; ginv).\n            destruct b as [l1 u1].\n            destruct b0 as [l2 u2].\n            destruct l1; allsimpl; ginv; fold_terms; cpx.\n\n            - exists (mk_atom_eq u1 u1 (oterm (Can can2) bts) mk_bot).\n              unflsubst; simpl.\n              allrw @sub_filter_nil_r; allrw app_nil_r; allrw @remove_nvars_nil_l.\n              allrw @sub_find_sub_filter_eq; allrw memvar_singleton.\n              allrw <- beq_var_refl; simpl; fold_terms.\n              allrw subvars_app_l.\n              allrw subset_app.\n              allrw disjoint_app_r; repnd.\n              allrw @oappl_app_as_oapp; autorewrite with slow in *.\n              allrw @oeqset_oappl_cons; autorewrite with slow in *.\n              allrw @osubset_oapp_left_iff; autorewrite with slow.\n              dands; eauto 3 with slow.\n\n              introv nrut' eqdoms diff'.\n              unflsubst; simpl; allrw @sub_filter_nil_r.\n              csunf; simpl.\n              eexists; dands; eauto.\n              unflsubst.\n              simpl.\n              allrw @sub_filter_nil_r; allrw app_nil_r; allrw @remove_nvars_nil_l.\n              allrw @sub_find_sub_filter_eq; allrw memvar_singleton.\n              allrw <- beq_var_refl; auto.\n          }\n\n          { SSSCase \"NParallel\".\n            unflsubst in comp; allsimpl.\n            csunf comp; allsimpl.\n            apply compute_step_parallel_success in comp; subst; allsimpl.\n            exists (@mk_axiom o).\n            unflsubst; simpl; fold_terms.\n            dands; autorewrite with slow in *; eauto 3 with slow.\n            introv nrut' eqdoms disj'.\n            exists (@mk_axiom o); allsimpl.\n            rw (@cl_lsubst_trivial o mk_axiom); simpl; dands; eauto 3 with slow.\n            unflsubst.\n          }\n\n          { SSSCase \"NCompOp\".\n\n            unflsubst in comp; allsimpl.\n            allrw @sub_filter_nil_r.\n            apply compute_step_ncompop_can1_success in comp; repnd.\n            repndors; exrepnd; subst.\n\n            - (* Can case *)\n              repeat (destruct bs; allsimpl; ginv).\n              destruct b as [l1 u1].\n              destruct b0 as [l2 u2].\n              destruct b1 as [l3 u3].\n              destruct l1; allsimpl; ginv; fold_terms.\n              allrw @sub_filter_nil_r; allrw app_nil_r.\n              allunfold @nobnd.\n              repeat (apply cons_inj in comp1; repnd); GC; ginv.\n              inversion comp2 as [epk]; clear comp2.\n              fold_terms.\n              apply compute_step_compop_success_can_can in comp1; exrepnd; subst; GC.\n              repeat (destruct bts; allsimpl; ginv).\n              autorewrite with slow in *.\n              repndors; exrepnd; subst;\n              allrw @get_param_from_cop_some; subst; allsimpl; fold_terms.\n\n              + allapply @lsubst_aux_eq_spcan_implies; repndors; exrepnd; allsimpl;\n                subst; allsimpl; fold_terms; boolvar; ginv.\n\n                * assert (sub_find sub v = Some (mk_integer n2)) as e by auto.\n                  apply sub_find_some in e.\n                  eapply in_nr_ut_sub in e; eauto; exrepnd; ginv.\n\n                * assert (sub_find sub v = Some (mk_integer n2)) as e by auto.\n                  apply sub_find_some in e.\n                  eapply in_nr_ut_sub in e; eauto; exrepnd; ginv.\n\n                * exists u2; unflsubst; allsimpl; autorewrite with slow in *.\n                  allrw @oappl_app_as_oapp; autorewrite with slow in *.\n                  allrw @oeqset_oappl_cons; autorewrite with slow in *.\n                  allrw @osubset_oapp_left_iff; autorewrite with slow.\n                  dands; eauto 4 with slow.\n\n                  introv nrut' eqdoms diff'; unflsubst; simpl; fold_terms.\n                  allrw @sub_filter_nil_r.\n                  csunf; simpl; eexists; dands; eauto.\n                  boolvar; allsimpl; tcsp; GC.\n                  dcwf h; allsimpl;[].\n                  unfold compute_step_comp; simpl.\n                  boolvar; tcsp; try omega.\n                  unflsubst.\n\n                * exists u3; unflsubst; allsimpl; autorewrite with slow in *.\n                  allrw @oappl_app_as_oapp; autorewrite with slow in *.\n                  allrw @oeqset_oappl_cons; autorewrite with slow in *.\n                  allrw @osubset_oapp_left_iff; autorewrite with slow.\n                  dands; eauto 4 with slow.\n\n                  introv nrut' eqdoms diff'; unflsubst; simpl; fold_terms.\n                  allrw @sub_filter_nil_r.\n                  csunf; simpl; boolvar; allsimpl; tcsp; GC.\n                  dcwf h; allsimpl;[].\n                  unfold compute_step_comp; simpl.\n                  boolvar; tcsp; try omega.\n                  eexists; dands; eauto.\n                  unflsubst.\n\n              + allapply @lsubst_aux_eq_spcan_implies; repndors; exrepnd; allsimpl; subst; allsimpl.\n\n                * dup epk1 as sf.\n                  eapply nr_ut_some_implies in sf; eauto; exrepnd;[].\n                  rw <- @pk2term_eq in sf0.\n                  apply pk2term_utoken in sf0; subst; allsimpl; fold_terms.\n\n                  exists (if param_kind_deq pk1 (PKa a) then u2 else u3).\n                  allrw disjoint_app_r; repnd.\n                  autorewrite with slow in *.\n                  allrw @oappl_app_as_oapp; autorewrite with slow in *.\n                  allrw @oeqset_oappl_cons; autorewrite with slow in *.\n                  allrw @osubset_oapp_left_iff; autorewrite with slow.\n                  dands; boolvar; subst; eauto 3 with slow; try unflsubst;allsimpl;[|].\n\n                  { allrw disjoint_singleton_r.\n                    apply sub_find_some in epk1.\n                    rw @in_get_utokens_sub in disj0; destruct disj0.\n                    eexists; eexists; dands; eauto; simpl; auto. }\n\n                  { introv nrut' eqdoms diff'; unflsubst; simpl; fold_terms.\n                    allrw @sub_filter_nil_r; allsimpl.\n\n                    pose proof (sub_find_some_eq_doms_nr_ut_sub sub sub' v) as h.\n                    applydup h in nrut'; auto; clear h;[].\n                    rw epk1 in nrut'0; exrepnd.\n                    rw nrut'1; allsimpl.\n\n                    csunf; simpl.\n                    dcwf h; allsimpl;[].\n                    unfold compute_step_comp; simpl.\n                    allrw @get_param_from_cop_pk2can.\n                    unflsubst.\n                    boolvar; eexists; dands; eauto.\n\n                    subst; allsimpl.\n                    allrw disjoint_cons_r; repnd.\n                    apply sub_find_some in nrut'1.\n                    rw @in_get_utokens_sub in diff'; destruct diff'.\n                    eexists; eexists; dands; eauto; simpl; auto. }\n\n                * exists (if param_kind_deq pk1 pk2 then u2 else u3).\n                  allrw disjoint_app_r; repnd.\n                  autorewrite with slow in *.\n                  repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n                  repeat (allrw @oeqset_oappl_cons; autorewrite with slow in *).\n                  allrw @osubset_oapp_left_iff; autorewrite with slow.\n                  dands; boolvar; subst; eauto 4 with slow; try unflsubst;allsimpl.\n\n                  { introv nrut' eqdoms diff'; unflsubst; simpl; fold_terms.\n                    allrw @sub_filter_nil_r; allsimpl.\n                    csunf; simpl.\n                    dcwf h; allsimpl;[].\n                    unfold compute_step_comp; simpl.\n                    allrw @get_param_from_cop_pk2can; boolvar; tcsp.\n                    eexists; dands; eauto.\n                    unflsubst. }\n\n                  { introv nrut' eqdoms diff'; unflsubst; simpl; fold_terms.\n                    allrw @sub_filter_nil_r; allsimpl.\n                    csunf; simpl.\n                    dcwf h; allsimpl;[].\n                    unfold compute_step_comp; simpl.\n                    allrw @get_param_from_cop_pk2can; boolvar; tcsp.\n                    eexists; dands; eauto.\n                    unflsubst. }\n\n            - (* NCan/Abs Case *)\n              destruct bs; allsimpl; ginv.\n              destruct b as [l1 u1].\n              destruct l1; allsimpl; ginv; fold_terms; cpx; allsimpl.\n              allrw @sub_filter_nil_r.\n              pose proof (ind u1 u1 []) as h.\n              repeat (autodimp h hyp); clear ind; eauto 3 with slow.\n              rw <- @cl_lsubst_lsubst_aux in comp4; eauto 3 with slow.\n              allrw @nt_wf_NCompOp; exrepnd; ginv; allsimpl.\n              autorewrite with slow in *.\n              allrw disjoint_app_r; repnd.\n\n              pose proof (h t' sub) as k; clear h.\n              repeat (autodimp k hyp).\n              { eapply nr_ut_sub_change_term;[|idtac|eauto];\n                allsimpl; allrw remove_nvars_nil_l; eauto with slow. }\n              exrepnd.\n              exists (oterm (NCan (NCompOp c))\n                            (nobnd (oterm (Can can2) bts)\n                                   :: nobnd w\n                                   :: nobnd t3\n                                   :: nobnd t4\n                                   :: [])).\n              unflsubst; simpl.\n              repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n              repeat (allrw @oeqset_oappl_cons; autorewrite with slow in *).\n              allrw @osubset_oapp_left_iff; autorewrite with slow.\n              allrw subset_app.\n              dands; autorewrite with slow; eauto 4 with slow.\n\n              + prove_alpha_eq4; introv h; allrw map_length.\n                destruct n; cpx.\n                destruct n; cpx.\n                apply alphaeqbt_nilv2.\n                unflsubst in k1.\n\n              + repeat (rw disjoint_app_r); dands; eauto with slow;\n                eapply subset_disjoint_r; try (exact disj); simpl;\n                eauto with slow.\n\n              + introv nrut' eqdoms diff'.\n                unflsubst; simpl.\n                allrw @sub_filter_nil_r.\n                eapply isnoncan_like_lsubst_aux_nr_ut_implies in comp3; eauto.\n                rw @compute_step_ncompop_ncanlike2; boolvar; allsimpl; tcsp; eauto with slow.\n                dcwf h;[].\n                pose proof (k0 sub') as h; repeat (autodimp h hyp).\n                { eapply nr_ut_sub_change_term;[|idtac|eauto];\n                  allsimpl; allrw remove_nvars_nil_l; eauto with slow. }\n                { allsimpl; allrw disjoint_app_r; sp. }\n                exrepnd.\n                unflsubst in h1; rw h1.\n                eexists; dands; eauto.\n                unflsubst; simpl; allrw @sub_filter_nil_r.\n                prove_alpha_eq4; introv h; allrw map_length.\n                destruct n; cpx.\n                destruct n; cpx.\n                apply alphaeqbt_nilv2.\n                unflsubst in h0.\n\n            - (* Exc Case *)\n              destruct bs; allsimpl; cpx;[].\n              destruct b as [l1 u1].\n              destruct l1; allsimpl; ginv; fold_terms; cpx; allsimpl;[].\n              allrw @sub_filter_nil_r.\n              assert (isexc u1) as ise.\n              { eapply isexc_lsubst_aux_nr_ut_sub in comp1; eauto. }\n              apply isexc_implies2 in ise; exrepnd; subst; allsimpl; GC.\n              exists (oterm Exc l); unflsubst; simpl.\n              repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n              repeat (allrw @oeqset_oappl_cons; autorewrite with slow in *).\n              repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n              allrw @osubset_oapp_left_iff; autorewrite with slow.\n              dands; autorewrite with slow; eauto 4 with slow.\n\n              introv nrut' eqdoms diff'.\n              unflsubst; simpl; csunf; simpl; boolvar; allsimpl; tcsp.\n              dcwf h;[].\n              eexists; dands; eauto.\n              allrw @sub_filter_nil_r.\n              unflsubst.\n          }\n\n          { SSSCase \"NArithOp\".\n\n            unflsubst in comp; allsimpl.\n            apply compute_step_narithop_can1_success in comp; repnd.\n            repndors; exrepnd; subst.\n\n            - (* Can case *)\n              repeat (destruct bs; allsimpl; ginv);[].\n              destruct b as [l1 u1].\n              destruct l1; allsimpl; ginv; fold_terms; cpx; allsimpl;[].\n              allrw @sub_filter_nil_r.\n              apply compute_step_arithop_success_can_can in comp1; exrepnd; subst; GC.\n              repeat (destruct bts; allsimpl; ginv).\n              autorewrite with slow in *.\n              repndors; exrepnd; subst;\n              allapply @get_param_from_cop_pki;\n              allapply @get_param_from_cop_pka;\n              allapply @get_param_from_cop_pks;\n              subst; allsimpl; GC; fold_terms.\n\n              assert (lsubst_aux u1 sub = mk_integer n2) as e by auto.\n              allrw e; GC.\n\n              allapply @lsubst_aux_eq_spcan_implies; repndors; exrepnd; allsimpl;\n              subst; allsimpl; fold_terms; boolvar; ginv.\n\n              * assert (sub_find sub v = Some (mk_integer n2)) as e by auto.\n                apply sub_find_some in e.\n                eapply in_nr_ut_sub in e; eauto; exrepnd; ginv.\n\n              * exists (@mk_integer o (get_arith_op a n1 n2)); unflsubst; dands; simpl; eauto 3 with slow.\n                introv nrut' eqdoms diff'; unflsubst; simpl; fold_terms.\n                csunf; simpl; boolvar; allsimpl; tcsp; GC.\n                dcwf h;allsimpl;[].\n                eexists; dands; eauto.\n\n            - (* NCan/Abs Case *)\n              destruct bs; allsimpl; ginv.\n              destruct b as [l1 u1].\n              destruct l1; allsimpl; ginv; fold_terms; cpx; allsimpl.\n              allrw @sub_filter_nil_r.\n              pose proof (ind u1 u1 []) as h.\n              repeat (autodimp h hyp); clear ind; eauto 3 with slow.\n              rw <- @cl_lsubst_lsubst_aux in comp4; eauto 3 with slow.\n              allrw @nt_wf_NArithOp; exrepnd; ginv; allsimpl.\n              autorewrite with slow in *.\n              allrw disjoint_app_r; repnd.\n\n              pose proof (h t' sub) as k; clear h.\n              repeat (autodimp k hyp).\n              { eapply nr_ut_sub_change_term;[|idtac|eauto];\n                allsimpl; allrw remove_nvars_nil_l; eauto with slow. }\n              exrepnd.\n              exists (oterm (NCan (NArithOp a))\n                            (nobnd (oterm (Can can2) bts)\n                                   :: nobnd w\n                                   :: [])).\n              unflsubst; simpl.\n              repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n              repeat (allrw @oeqset_oappl_cons; autorewrite with slow in *).\n              allrw @osubset_oapp_left_iff; autorewrite with slow.\n              dands; autorewrite with slow; eauto 4 with slow.\n\n              + prove_alpha_eq4; introv h; allrw map_length; destruct n; cpx.\n                destruct n; cpx.\n                apply alphaeqbt_nilv2.\n                unflsubst in k1.\n\n              + repeat (rw disjoint_app_r); dands; eauto with slow;\n                eapply subset_disjoint_r; try (exact disj); simpl;\n                eauto with slow.\n\n              + introv nrut' eqdoms diff'.\n                unflsubst; simpl; allrw @sub_filter_nil_r.\n                eapply isnoncan_like_lsubst_aux_nr_ut_implies in comp3; eauto.\n                rw @compute_step_narithop_ncanlike2; boolvar; allsimpl; tcsp; eauto with slow.\n                pose proof (k0 sub') as h; repeat (autodimp h hyp).\n                { eapply nr_ut_sub_change_term;[|idtac|eauto];\n                  allsimpl; allrw remove_nvars_nil_l; eauto with slow. }\n                { allsimpl; allrw disjoint_app_r; sp. }\n                exrepnd.\n                unflsubst in h1; rw h1.\n                dcwf h; allsimpl; [].\n                eexists; dands; eauto.\n                unflsubst; simpl; allrw @sub_filter_nil_r.\n                prove_alpha_eq4; introv h; allrw map_length.\n                destruct n; cpx.\n                destruct n; cpx.\n                apply alphaeqbt_nilv2.\n                unflsubst in h0.\n\n            - (* Exc Case *)\n              destruct bs; allsimpl; cpx.\n              destruct b as [l1 u1].\n              destruct l1; allsimpl; ginv; fold_terms; cpx; allsimpl.\n              allrw @sub_filter_nil_r.\n              assert (isexc u1) as ise.\n              { eapply isexc_lsubst_aux_nr_ut_sub in comp1; eauto. }\n              apply isexc_implies2 in ise; exrepnd; subst; allsimpl; GC.\n              exists (oterm Exc l); unflsubst; simpl.\n              repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n              repeat (allrw @oeqset_oappl_cons; autorewrite with slow in *).\n              repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n              allrw @osubset_oapp_left_iff; autorewrite with slow.\n              dands; autorewrite with slow; eauto 4 with slow.\n\n              introv nrut' eqdoms diff'.\n              unflsubst; simpl; csunf; simpl; boolvar; allsimpl; tcsp.\n              dcwf h; allsimpl; [].\n              eexists; dands; eauto.\n              allrw @sub_filter_nil_r.\n              unflsubst.\n          }\n\n          { SSSCase \"NCanTest\".\n\n            unflsubst in comp; allsimpl; csunf comp; allsimpl.\n            autorewrite with slow in *.\n            apply compute_step_can_test_success in comp; exrepnd.\n            repeat (destruct bs; allsimpl; ginv).\n            destruct b as [l1 u1].\n            destruct b0 as [l2 u2].\n            destruct l1; allsimpl; ginv; fold_terms; cpx; allsimpl.\n            allrw @sub_filter_nil_r.\n            exists (if canonical_form_test_for c can2 then u1 else u2).\n            repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n            repeat (allrw @oeqset_oappl_cons; autorewrite with slow in *).\n            repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n            allrw @osubset_oapp_left_iff; autorewrite with slow.\n            allrw disjoint_app_r; repnd.\n            unflsubst; simpl; dands; autorewrite with slow; eauto 4 with slow;\n            try (complete (remember (canonical_form_test_for c can2) as cft; destruct cft; eauto 3 with slow));\n            [].\n\n            introv nrut' eqdoms diff'.\n            unflsubst; simpl; csunf; simpl.\n            allrw @sub_filter_nil_r.\n            eexists; dands; eauto.\n            unflsubst.\n            remember (canonical_form_test_for c can2) as cft; destruct cft; auto.\n          }\n\n        * SSCase \"NCan\".\n          unflsubst in comp; allsimpl.\n\n          allrw @fold_get_utokens_step_seq_bterms_seq.\n          allrw @fold_get_utokens_step_seq_ncan_seq.\n          autorewrite with slow in *.\n          allrw disjoint_app_r; repnd.\n\n          rw @compute_step_ncan_ncan in comp.\n\n          remember (compute_step\n                      lib\n                      (oterm (NCan ncan2)\n                             (map (fun t : BTerm => lsubst_bterm_aux t sub)\n                                  bts))) as c; symmetry in Heqc; destruct c; ginv;[].\n\n          pose proof (ind (oterm (NCan ncan2) bts) (oterm (NCan ncan2) bts) []) as h.\n          repeat (autodimp h hyp); clear ind; eauto 3 with slow.\n\n          pose proof (h n sub) as k; clear h.\n          unflsubst in k; allsimpl.\n          allrw @fold_get_utokens_step_seq_bterms_seq.\n          allrw @fold_get_utokens_step_seq_ncan_seq.\n          autorewrite with slow in *.\n          allrw disjoint_app_r.\n          applydup @nt_wf_oterm_fst in wf.\n\n          repeat (autodimp k hyp);[|].\n          { eapply nr_ut_sub_change_term;[|idtac|eauto];\n            allsimpl; allrw remove_nvars_nil_l; eauto with slow. }\n          exrepnd.\n          exists (oterm (NCan ncan) (nobnd w :: bs)).\n          unflsubst; simpl.\n          autorewrite with slow in *.\n          allrw disjoint_app_r.\n          allrw subvars_app_l.\n          repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n          repeat (allrw @oeqset_oappl_cons; autorewrite with slow in *).\n          repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n          allrw @osubset_oapp_left_iff; autorewrite with slow.\n          dands; autorewrite with slow in *; eauto 3 with slow.\n\n          { prove_alpha_eq4; introv k; destruct n0; cpx.\n            apply alphaeqbt_nilv2.\n            unflsubst in k1. }\n\n          { introv nrut' eqdoms diff'.\n            pose proof (k0 sub') as h.\n            repeat (autodimp h hyp).\n            { eapply nr_ut_sub_change_term;[|idtac|eauto];\n              allsimpl; allrw remove_nvars_nil_l; eauto with slow. }\n            { allsimpl; allrw disjoint_app_r; sp. }\n            exrepnd.\n            unflsubst; simpl.\n            rw @compute_step_ncan_ncan.\n            allrw @sub_filter_nil_r.\n            unflsubst in h1; allsimpl; rw h1.\n            eexists; dands; eauto.\n            unflsubst; unflsubst in h0; simpl; allrw @sub_filter_nil_r.\n            prove_alpha_eq4; introv k; destruct n0; cpx.\n            apply alphaeqbt_nilv2; auto.\n          }\n\n        * SSCase \"Exc\".\n          unflsubst in comp; csunf comp; allsimpl.\n\n          autorewrite with slow in *.\n          allrw disjoint_app_r; repnd.\n\n          apply compute_step_catch_success in comp; repnd; repndors; exrepnd; subst.\n\n          { repeat (destruct bs; allsimpl; ginv).\n            repeat (destruct bts; allsimpl; ginv).\n            destruct b0 as [l1 u1].\n            destruct b1 as [l2 u2].\n            destruct b2 as [l3 u3].\n            destruct b3 as [l4 u4].\n            destruct l1; allsimpl; ginv; fold_terms; cpx; allsimpl.\n            autorewrite with slow in *.\n\n            exists (mk_atom_eq u1 u3 (subst u2 v u4) (mk_exception u3 u4)).\n            repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n            unfold subst.\n\n            allsimpl; autorewrite with slow in *.\n            allrw disjoint_app_r; repnd.\n            allrw subvars_app_l.\n            repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n            repeat (allrw @oeqset_oappl_cons; autorewrite with slow in *).\n            repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n            allrw @osubset_oapp_left_iff; autorewrite with slow.\n            allrw subset_app.\n\n            dands; eauto 4 with slow; fold_terms.\n\n            + eapply alpha_eq_trans;\n              [|apply alpha_eq_sym; apply alpha_eq_mk_atom_eq_lsubst].\n              apply implies_alpha_eq_mk_atom_eq; auto.\n\n              * pose proof (combine_sub_nest u2 [(v,u4)] sub) as h.\n                eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                pose proof (combine_sub_nest u2 (sub_filter sub [v]) [(v, lsubst u4 sub)]) as h.\n                eapply alpha_eq_trans;[apply h|]; clear h.\n                simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                apply alpha_eq_lsubst_if_ext_eq; auto.\n                unfold ext_alpha_eq_subs; simpl; introv i.\n                rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n                boolvar; simpl; boolvar; simpl; tcsp.\n                remember (sub_find sub v0) as sf; destruct sf; simpl; tcsp.\n\n              * eapply alpha_eq_trans;\n                [|apply alpha_eq_sym; apply alpha_eq_mk_exception_lsubst].\n                apply implies_alphaeq_exception; auto.\n\n            + eapply disjoint_eqset_r;[apply eqset_sym; apply get_utokens_lsubst|].\n              allrw disjoint_app_r; dands; eauto 3 with slow;[].\n              eapply subset_disjoint_r;[|apply get_utokens_sub_sub_keep_first].\n              unfold get_utokens_sub at 2; simpl; autorewrite with slow; eauto 3 with slow.\n\n            + simpl; allrw remove_nvars_nil_l; allrw app_nil_r.\n              allrw subvars_app_l; dands; eauto 4 with slow.\n              eapply subvars_eqvars;[|apply eqvars_sym; apply eqvars_free_vars_disjoint].\n              allsimpl; boolvar; allsimpl; allrw app_nil_r;\n              allrw subvars_app_l; dands; eauto with slow.\n\n            + eapply subset_eqset_l;[apply eqset_sym;apply get_utokens_lsubst|].\n              apply subset_app; dands; eauto 3 with slow.\n              unfold get_utokens_sub; simpl; boolvar; simpl;\n              autorewrite with slow; eauto 3 with slow.\n\n            + introv nrut' eqdoms diff'.\n              unflsubst; simpl.\n              csunf; simpl.\n              allrw @sub_filter_nil_r.\n              repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n              eexists; dands; eauto.\n\n              eapply alpha_eq_trans;\n                [|apply alpha_eq_sym; apply alpha_eq_mk_atom_eq_lsubst].\n              apply implies_alpha_eq_mk_atom_eq; auto.\n\n              * pose proof (combine_sub_nest u2 [(v,u4)] sub') as h.\n                eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                pose proof (combine_sub_nest u2 (sub_filter sub' [v]) [(v, lsubst u4 sub')]) as h.\n                eapply alpha_eq_trans;[apply h|]; clear h.\n                simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                apply alpha_eq_lsubst_if_ext_eq; auto.\n                unfold ext_alpha_eq_subs; simpl; introv i.\n                rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n                boolvar; simpl; boolvar; simpl; tcsp.\n                remember (sub_find sub' v0) as sf; destruct sf; simpl; tcsp.\n\n              * eapply alpha_eq_trans;\n                [|apply alpha_eq_sym; apply alpha_eq_mk_exception_lsubst].\n                apply implies_alphaeq_exception; auto.\n          }\n\n          { exists (oterm Exc bts); unflsubst; simpl.\n            allrw @oappl_app_as_oapp; autorewrite with slow in *.\n            dands; eauto 3 with slow.\n\n            introv nrut' eqdoms diff'.\n            unflsubst; simpl.\n            csunf; simpl.\n            rw @compute_step_catch_if_diff; auto.\n            allrw @sub_filter_nil_r.\n            eexists; dands; eauto.\n            unflsubst.\n          }\n\n        * SSCase \"Abs\".\n          unflsubst in comp; allsimpl.\n\n          autorewrite with slow in *.\n          allrw disjoint_app_r; repnd.\n\n          rw @compute_step_ncan_abs in comp.\n\n          remember (compute_step_lib\n                      lib abs2\n                      (map (fun t : BTerm => lsubst_bterm_aux t sub)\n                           bts)) as c; symmetry in Heqc; destruct c; ginv.\n          pose proof (ind (oterm (Abs abs2) bts) (oterm (Abs abs2) bts) []) as h.\n          repeat (autodimp h hyp); clear ind; eauto 3 with slow.\n\n          pose proof (h n sub) as k; clear h.\n          unflsubst in k; allsimpl.\n          autorewrite with slow in *.\n          allrw disjoint_app_r.\n          applydup @nt_wf_oterm_fst in wf.\n\n          repeat (autodimp k hyp);[|].\n          { eapply nr_ut_sub_change_term;[|idtac|eauto];\n            allsimpl; allrw remove_nvars_nil_l; eauto with slow. }\n          exrepnd.\n          exists (oterm (NCan ncan) (nobnd w :: bs)).\n          unflsubst; simpl.\n          autorewrite with slow in *.\n          allrw disjoint_app_r.\n          allrw subvars_app_l.\n          repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n          repeat (allrw @oeqset_oappl_cons; autorewrite with slow in *).\n          repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n          allrw @osubset_oapp_left_iff; autorewrite with slow.\n          dands; autorewrite with slow in *; eauto 3 with slow.\n\n          { prove_alpha_eq4; introv k; destruct n0; cpx.\n            apply alphaeqbt_nilv2.\n            unflsubst in k1. }\n\n          { introv nrut' eqdoms diff'.\n            pose proof (k0 sub') as h.\n            repeat (autodimp h hyp).\n            { eapply nr_ut_sub_change_term;[|idtac|eauto];\n              allsimpl; allrw remove_nvars_nil_l; eauto with slow. }\n            { allsimpl; allrw disjoint_app_r; sp. }\n            exrepnd.\n            unflsubst; simpl.\n            rw @compute_step_ncan_abs.\n            allrw @sub_filter_nil_r.\n            unflsubst in h1; csunf h1; allsimpl; rw h1.\n            eexists; dands; eauto.\n            unflsubst; unflsubst in h0; simpl.\n            prove_alpha_eq4; introv k; destruct n0; cpx.\n            allrw @sub_filter_nil_r.\n            apply alphaeqbt_nilv2; auto.\n          }\n      }\n\n      { (* Fresh case *)\n        unflsubst in comp; csunf comp; allsimpl.\n        autorewrite with slow in *.\n        apply compute_step_fresh_success in comp; exrepnd; subst; allsimpl.\n        repeat (destruct bs; allsimpl; ginv); autorewrite with slow in *.\n        allrw @nt_wf_fresh.\n\n        repndors; exrepnd; subst.\n\n        - apply lsubst_aux_eq_vterm_implies in comp0; repndors; exrepnd; subst; allsimpl.\n          { apply sub_find_some in comp0.\n            apply in_cl_sub in comp0; eauto with slow.\n            allunfold @closed; allsimpl; sp. }\n\n          exists (@mk_fresh o n (mk_var n)); unflsubst; simpl.\n          autorewrite with slow in *.\n          dands; eauto 3 with slow.\n\n          introv ntuf' eqdoms diff'.\n          unflsubst; csunf.\n          simpl; rw @sub_find_sub_filter_eq; rw memvar_singleton; boolvar; tcsp.\n          exists (@mk_fresh o n (mk_var n)); dands; auto.\n          rw @cl_lsubst_trivial; simpl; eauto 3 with slow.\n          autorewrite with slow in *; simpl; auto.\n\n        - apply isvalue_like_lsubst_aux_implies in comp0;\n          repndors; exrepnd; subst; allsimpl; fold_terms.\n\n          + exists (pushdown_fresh n t).\n            rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow.\n            rw @get_utokens_pushdown_fresh.\n            rw @free_vars_pushdown_fresh.\n            dands; eauto 3 with slow.\n\n            * apply alpha_eq_sym.\n              apply cl_lsubst_pushdown_fresh; eauto 3 with slow.\n\n            * introv nrut' eqdoms' disj'.\n              unflsubst; simpl.\n              rw @compute_step_fresh_if_isvalue_like2; eauto 3 with slow.\n              eexists; dands; eauto.\n              rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow.\n              apply alpha_eq_sym.\n              apply cl_lsubst_pushdown_fresh; eauto with slow.\n\n          + allrw.\n            rw @sub_find_sub_filter_eq in comp1; rw memvar_singleton in comp1.\n            boolvar; ginv.\n            applydup @sub_find_some in comp1 as sf.\n            apply (in_nr_ut_sub _ _ _ (mk_fresh n (mk_var v))) in sf; auto.\n            exrepnd; subst.\n            allsimpl; fold_terms.\n            exists (@mk_var o v).\n            unflsubst; simpl; fold_terms.\n            allrw.\n            dands; eauto 3 with slow.\n\n            { rw subvars_prop; simpl; introv i; repndors; tcsp; subst.\n              rw in_remove_nvars; simpl; sp. }\n\n            { introv nrut' eqdoms' disj'.\n              unflsubst; simpl.\n              rw @sub_find_sub_filter_eq; rw memvar_singleton.\n              boolvar; tcsp.\n              pose proof (sub_find_some_eq_doms_nr_ut_sub sub sub' v (mk_fresh n (mk_var v))) as h.\n              repeat (autodimp h hyp).\n              rw comp1 in h; exrepnd.\n              rw h0.\n              csunf; simpl; fold_terms.\n              eexists; dands; eauto.\n              unflsubst; simpl; allrw; auto.\n            }\n\n        - apply (isnoncan_like_lsubst_aux_nr_ut_implies _ _ (oterm (NCan NFresh) [bterm [n] t])) in comp1;\n          [|apply nr_ut_sub_sub_filter_disj; auto; simpl;\n            rw app_nil_r; rw disjoint_singleton_l; rw in_remove_nvar;\n            complete sp].\n          repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n          repeat (rw <- @cl_lsubst_lsubst_aux in comp2; eauto 3 with slow).\n          remember (get_fresh_atom (lsubst t (sub_filter sub [n]))) as a'.\n          unfold subst in comp2.\n\n          pose proof (cl_lsubst_app t (sub_filter sub [n]) [(n,mk_utoken a')]) as h.\n          repeat (autodimp h hyp); eauto 3 with slow; rw <- h in comp2; clear h.\n\n          pose proof (ind t t [n]) as h.\n          repeat (autodimp h hyp); eauto 3 with slow.\n\n          pose proof (get_fresh_atom_prop (lsubst t (sub_filter sub [n]))) as fap.\n          rw <- Heqa' in fap.\n\n          pose proof (h x (sub_filter sub [n] ++ [(n, mk_utoken a')])) as k; clear h.\n          repeat (autodimp k hyp); eauto 3 with slow.\n\n          { apply implies_nr_ut_sub_app; eauto with slow.\n            - apply (nr_ut_sub_sub_filter_change_term_disj _ _ (mk_fresh n t)); allsimpl; tcsp; allrw app_nil_r; auto.\n              { apply disjoint_singleton_l; rw in_remove_nvars; simpl; sp. }\n              { rw subvars_prop; introv i; rw in_app_iff; rw in_remove_nvars; simpl.\n                destruct (deq_nvar x0 n); tcsp.\n                left; sp. }\n          }\n\n          { rw @get_utokens_sub_app; rw @get_utokens_sub_cons; rw @get_utokens_sub_nil; rw app_nil_r; simpl.\n            rw disjoint_app_l; rw disjoint_singleton_l; dands; eauto 3 with slow.\n            - apply (subset_disjoint _ _ (get_utokens_sub sub)); eauto 3 with slow.\n              apply get_utokens_sub_filter_subset.\n            - intro i; destruct fap.\n              unflsubst.\n              apply get_utokens_lsubst_aux; auto.\n              rw in_app_iff; sp.\n          }\n\n          exrepnd.\n          exists (mk_fresh n w); dands; allsimpl;\n          autorewrite with slow; eauto 3 with slow.\n\n          + pose proof (implies_alpha_eq_mk_fresh_subst_utokens\n                          n a' x\n                          (lsubst w (sub_filter sub [n] ++ [(n, mk_utoken a')]))\n                          k1) as h.\n            eapply alpha_eq_trans;[exact h|clear h].\n            allrw @get_utokens_sub_app; allrw @get_utokens_sub_cons; allrw @get_utokens_sub_nil.\n            allrw app_nil_r; allsimpl.\n            allrw disjoint_app_l; allrw disjoint_singleton_l; repnd.\n\n            pose proof (cl_lsubst_app w (sub_filter sub [n]) [(n,mk_utoken a')]) as h.\n            repeat (autodimp h hyp); eauto 3 with slow.\n            rw h; clear h; allrw @fold_subst.\n            eapply alpha_eq_trans;\n              [apply implies_alpha_eq_mk_fresh; apply simple_alphaeq_subst_utokens_subst|];\n              [|repeat unflsubst];[].\n\n            intro h.\n            allrw @get_utokens_lsubst; allrw in_app_iff; allrw not_over_or; repnd.\n            repndors; tcsp;[].\n\n            destruct fap.\n            allrw @in_get_utokens_sub; exrepnd.\n            exists v t0; dands; auto;[].\n            allrw @in_sub_keep_first; repnd; dands; auto.\n            rw subvars_prop in k3; apply k3 in h0; auto.\n\n          + apply subars_remove_nvars_lr; auto.\n\n          + introv nrut' eqdoms diff'.\n            unflsubst; simpl.\n            rw @compute_step_fresh_if_isnoncan_like; eauto with slow.\n            remember (get_fresh_atom (lsubst_aux t (sub_filter sub' [n]))) as a''.\n            unfold subst; repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n            rw <- @cl_lsubst_app; eauto with slow.\n\n            pose proof (get_fresh_atom_prop (lsubst_aux t (sub_filter sub' [n]))) as fap'.\n            rw <- Heqa'' in fap'; repnd.\n            repeat (rw <- @cl_lsubst_lsubst_aux in fap'; eauto 3 with slow).\n\n            pose proof (k0 (sub_filter sub' [n] ++ [(n, mk_utoken a'')])) as h.\n            repeat (autodimp h hyp).\n\n            { apply implies_nr_ut_sub_app; eauto with slow.\n              - apply (nr_ut_sub_sub_filter_change_term_disj _ _ (mk_fresh n t)); allsimpl; tcsp; allrw app_nil_r; auto.\n                { apply disjoint_singleton_l; rw in_remove_nvars; simpl; sp. }\n                { rw subvars_prop; introv i; rw in_app_iff; rw in_remove_nvars; simpl.\n                  destruct (deq_nvar x0 n); tcsp.\n                  left; sp. }\n            }\n\n            { allrw @dom_sub_app; simpl; allrw <- @dom_sub_sub_filter; allrw; auto. }\n\n            { rw @get_utokens_sub_app; rw @get_utokens_sub_cons; rw @get_utokens_sub_nil; rw app_nil_r; simpl.\n              rw disjoint_app_l; rw disjoint_singleton_l; dands.\n              - apply (subset_disjoint _ _ (get_utokens_sub sub')); eauto with slow.\n                apply get_utokens_sub_filter_subset.\n              - intro i; destruct fap'.\n                unflsubst.\n                apply get_utokens_lsubst_aux; eauto 3 with slow.\n                rw in_app_iff; tcsp.\n            }\n\n            exrepnd.\n            rw h1; simpl.\n            eexists; dands; eauto.\n\n            pose proof (implies_alpha_eq_mk_fresh_subst_utokens\n                          n a'' s\n                          (lsubst w (sub_filter sub' [n] ++ [(n, mk_utoken a'')]))\n                          h0) as h.\n            eapply alpha_eq_trans;[exact h|clear h].\n\n            pose proof (cl_lsubst_app w (sub_filter sub' [n]) [(n,mk_utoken a'')]) as h.\n            repeat (autodimp h hyp); eauto 3 with slow.\n            rw h; clear h; allrw @fold_subst.\n            eapply alpha_eq_trans;[apply implies_alpha_eq_mk_fresh; apply simple_alphaeq_subst_utokens_subst|].\n\n            { intro h; destruct fap'.\n              allrw @get_utokens_lsubst; allrw in_app_iff; allrw not_over_or; repnd.\n              repndors; tcsp.\n              allrw @in_get_utokens_sub; exrepnd.\n              right.\n              exists v t0; dands; auto.\n              allrw @in_sub_keep_first; repnd; dands; auto.\n              rw subvars_prop in k3; apply k3 in h2; auto. }\n\n            repeat unflsubst.\n      }\n\n    + SCase \"Exc\".\n      unflsubst in comp; csunf comp; allsimpl; ginv.\n      exists (oterm Exc bs); unflsubst; simpl; dands; eauto with slow.\n\n      { introv nrut' eqdoms diff'.\n        unflsubst; csunf; simpl; eexists; dands; eauto. }\n\n    + SCase \"Abs\".\n      unflsubst in comp; csunf comp; allsimpl; ginv.\n      apply compute_step_lib_success in comp; exrepnd; subst.\n\n      pose proof (found_entry_change_bs abs oa2 vars rhs lib (lsubst_bterms_aux bs sub) correct bs comp0) as fe.\n      autodimp fe hyp.\n      { unfold lsubst_bterms_aux; rw map_map; unfold compose.\n        apply eq_maps; introv i; destruct x as [l t]; simpl.\n        unfold num_bvars; simpl; auto. }\n      apply found_entry_implies_matching_entry in fe; auto.\n      unfold matching_entry in fe; repnd.\n\n      exists (mk_instance vars bs rhs); unflsubst; simpl; dands;\n      autorewrite with slow; eauto with slow.\n\n      { pose proof (alpha_eq_lsubst_aux_mk_instance rhs vars bs sub) as h.\n        repeat (autodimp h hyp); eauto with slow. }\n\n      { eapply subset_disjoint_r;[|apply get_utokens_mk_instance]; auto.\n        eapply subset_disjoint_r;[exact disj|].\n        autorewrite with slow.\n        unfold correct_abs in correct; repnd.\n        dup correct as c.\n        apply no_utokens_implies_get_utokens_so_nil in c.\n        rw c; simpl.\n        apply subset_flat_map2; introv i; destruct x; simpl; eauto 3 with slow. }\n\n      { eapply subvars_trans;[apply subvars_free_vars_mk_instance|]; auto.\n        unfold correct_abs in correct; sp. }\n\n      { eapply subset_trans;[apply get_utokens_mk_instance|]; auto.\n        unfold correct_abs in correct; repnd.\n        dup correct as c.\n        apply no_utokens_implies_get_utokens_so_nil in c.\n        rw c; simpl.\n        apply subset_flat_map2; introv i; destruct x; simpl; eauto 3 with slow. }\n\n      { introv nrut' eqdoms diff'.\n        unflsubst; csunf; simpl.\n\n        pose proof (found_entry_change_bs abs oa2 vars rhs lib (lsubst_bterms_aux bs sub) correct (lsubst_bterms_aux bs sub') comp0) as fe'.\n        autodimp fe' hyp.\n        { unfold lsubst_bterms_aux; allrw map_map; unfold compose.\n          apply eq_maps; introv i; destruct x as [l t]; simpl.\n          unfold num_bvars; simpl; auto. }\n        apply found_entry_implies_compute_step_lib_success in fe'.\n        unfold lsubst_bterms_aux in fe'; rw fe'.\n        eexists; dands; eauto.\n        unflsubst.\n        fold (lsubst_bterms_aux bs sub').\n        apply alpha_eq_lsubst_aux_mk_instance; eauto with slow.\n      }\nQed.\n\nLemma compute_step_preserves_utokens {o} :\n  forall lib (t u : @NTerm o),\n    nt_wf t\n    -> compute_step lib t = csuccess u\n    -> subset (get_utokens u) (get_utokens t).\nProof.\n  introv wf comp.\n  pose proof (compute_step_subst_utoken lib t u []) as h.\n  autorewrite with slow in *.\n  repeat (autodimp h hyp); exrepnd; autorewrite with slow in *.\n  apply alphaeq_preserves_utokens in h1; rw h1; auto.\nQed.\n\n(*\nLemma compute_step_preserves_utokens {o} :\n  forall lib (t u : @NTerm o),\n    compute_step lib t = csuccess u\n    -> subset (get_utokens u) (get_utokens t).\nProof.\n  introv comp.\n  apply compute_step_preserves in comp; repnd.\n  introv i.\n  apply comp in i; 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/computation_preserve3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.2946826820682014}}
{"text": "(** This file contains the declarative and algorithmic subtyping formalization.\n    The algorithmic system is proved to be sound and complete w.r.t the\n    declarative one (in Thereoem dsub2asub).\n    Some inversion lemmas (end with _inv) are provided to justify the algorithm.\n *)\n\nRequire Import LibTactics.\nRequire Import Coq.micromega.Lia.\nRequire Import LN_Lemmas.\nRequire Export Definitions.\n\n\n(************************ Notations related to types **************************)\nNotation \"[ z ~~> u ] t\" := (typsubst_typ u z t) (at level 0).\nNotation \"t ^-^ u\"       := (open_typ_wrt_typ t u) (at level 67).\nNotation \"t -^ x\"        := (open_typ_wrt_typ t (t_tvar_f x))(at level 67).\nNotation \"[[ A ]]\"       := (typefv_typ A) (at level 0).\nNotation \"A <: B\"        := (declarative_subtyping A B)\n                              (at level 65, B at next level, no associativity) : type_scope.\n\n(************************************ Ltac ************************************)\n\n(* redefine gather_atoms for pick fresh *)\nLtac gather_atoms ::= (* for type var *)\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 : list (var * typ) => dom x) in\n  let E := gather_atoms_with (fun x : typ => typefv_typ x) in\n  constr:(A `union` B `union` C `union` E).\n\n(* autorewrite with open *)\nCreate HintDb open.\n\nLemma open_into_and : forall B C X, (t_and B C) -^ X = t_and (B -^ X) (C -^ X).\nProof. eauto. Qed.\n\nLemma open_into_or : forall B C X, (t_or B C) -^ X = t_or (B -^ X) (C -^ X).\nProof. eauto. Qed.\n\nLemma open_into_top : forall X, t_top -^ X = t_top.\nProof. eauto. Qed.\n\nLemma open_into_bot : forall X, t_bot -^ X = t_bot.\nProof. eauto. Qed.\n\n#[export] Hint Rewrite open_into_and open_into_or open_into_top open_into_bot : open.\n\n\n(* try solve the goal by contradiction *)\nCreate HintDb FalseHd.\nLtac solve_false := try intro; try solve [false; eauto 4 with FalseHd].\n\n(* destrcut conjunctions *)\nLtac destruct_conj :=\n  repeat match goal with H: ?T |- _ =>\n                         lazymatch T with\n                         | exists _ , _ => destruct H\n                         | _ /\\ _ => destruct H\n                         end\n    end.\n\nLtac detect_fresh_var_and_do t :=\n  match goal with\n  | Fr : ?x `notin` ?L1 |- _ => t x\n  | _ =>\n    let x := fresh \"x\" in\n    pick fresh x; t x\n  end.\n\nLtac instantiate_cofinite_with H X :=\n  match type of H with\n  | forall x, x `notin` ?L -> _ =>\n    let H1 := fresh \"H\" in\n    assert (H1 : X `notin` L) by solve_notin;\n    specialize (H X H1); clear H1\n  | X `notin` ?L -> _ =>\n    let H1 := fresh \"H\" in\n    assert (H1 : X `notin` L) by solve_notin;\n    specialize (H H1); clear H1\n  end.\n\nLtac specialize_with X :=\n  repeat match goal with\n  | H : forall X : typevar, _ |- _ => specialize (H X)\n  end.\n\nLtac instantiate_cofinites_with x :=\n  repeat match goal with\n  | H : forall x, x `notin` ?L -> _ |- _ =>\n    instantiate_cofinite_with H x\n  | H : x `notin` ?L -> _ |- _ =>\n    instantiate_cofinite_with H x\n         end;\n  destruct_conj.\n\nLtac instantiate_cofinites :=\n  detect_fresh_var_and_do instantiate_cofinites_with.\n\nLtac applys_and_instantiate_cofinites_with H x :=\n  applys H x; try solve_notin; instantiate_cofinites_with x.\n\nLtac pick_fresh_applys_and_instantiate_cofinites H :=\n  let X:= fresh in\n  pick fresh X; applys_and_instantiate_cofinites_with H X.\n\nLtac detect_fresh_var_and_apply H :=\n  let f x := applys_and_instantiate_cofinites_with H x in\n  detect_fresh_var_and_do f.\n\n\n(******************************* type sizes ***********************************)\n(** defines size on types and proves some related\nlemmas. It aims to make later proofs easier if they do\ninduction on the size of types *)\n\nLemma splu_decrease_size: forall A B C,\n    splu A B C -> size_typ B < size_typ A /\\ size_typ C < size_typ A.\nProof with (pose proof (size_typ_min); simpl in *; try lia).\n  introv H.\n  induction H; simpl in *; eauto...\n  pick fresh X. forwards* (?&?): H0.\n  rewrite 2 size_typ_open_typ_wrt_typ_var in H3.\n  rewrite 2 size_typ_open_typ_wrt_typ_var in H2.\n  eauto...\nQed.\n\nLemma spli_decrease_size: forall A B C,\n    spli A B C -> size_typ B < size_typ A /\\ size_typ C < size_typ A.\nProof with (pose proof (size_typ_min); simpl in *; try lia).\n  introv H.\n  induction H; simpl in *; eauto...\n  - forwards (?&?): splu_decrease_size H0...\n  - pick fresh X. forwards* (?&?): H0.\n    rewrite 2 size_typ_open_typ_wrt_typ_var in H3.\n    rewrite 2 size_typ_open_typ_wrt_typ_var in H2.\n    eauto...\nQed.\n\nLtac spl_size :=\n  try repeat match goal with\n         | [ H: splu _ _ _ |- _ ] =>\n           ( lets (?&?): splu_decrease_size H; clear H)\n         | [ H: spli _ _ _ |- _ ] =>\n           ( lets (?&?): spli_decrease_size H; clear H)\n             end.\n\n(********************************************)\n(*                                          *)\n(*               Ltac elia                  *)\n(*  enhanced lia with split_decrease_size   *)\n(*                                          *)\n(********************************************)\nLtac elia :=\n  try solve [pose proof (size_typ_min);\n             let x := fresh \"x\" in\n             pick fresh x; try instantiate_cofinites_with x; (* forall x, x `notin` .. -> spli .. *)\n             spl_size; simpl in *; simpl;\n             try repeat rewrite size_typ_open_typ_wrt_typ_var in *; (* spl A-^X ... *)\n             try lia].\n(* eauto with typSize lngen ? *)\n\nLtac indTypSize s :=\n  assert (SizeInd: exists i, s < i) by eauto;\n  destruct SizeInd as [i SizeInd];\n  repeat match goal with | [ h : typ |- _ ] => (gen h) end;\n  induction i as [|i IH]; [\n    intros; match goal with | [ H : _ < 0 |- _ ] => inverts H end\n  | intros ].\n\n\n(********************************************)\n(*                                          *)\n(*            Ltac solve_false              *)\n(*  try solve the goal by contradiction     *)\n(*                                          *)\n(********************************************)\n\n#[export] Hint Extern 1 => progress instantiate_cofinites : FalseHd.\n\n(* splittable types and ordinary types do not overlap *)\nLemma splu_ord_false : forall A B C,\n    splu A B C -> ordu A -> False.\nProof with solve_false.\n  introv Spl Ord. gen B C.\n  induction Ord; intros; inverts* Spl...\nQed.\n\nLemma spli_ord_false : forall A B C,\n    spli A B C -> ordi A -> False.\nProof.\n  introv Spl Ord. gen B C.\n  induction Ord; intros; inverts* Spl.\n  eauto using splu_ord_false. solve_false.\nQed.\n\nLtac find_contradiction_on_split :=\n  match goal with\n  | [ H1: splu ?T _ _ , H2: ordu ?T |- _ ] => applys~ splu_ord_false H1 H2\n  | [ H1: spli ?T _ _ , H2: ordi ?T |- _ ] => applys~ spli_ord_false H1 H2\n  | [ H: ordu _ |- _ ] => inverts H; fail\n  | [ H: splu _ _ _ |- _ ] => inverts H; fail\n  | [ H: ordi _ |- _ ] => inverts H; fail\n  | [ H: spli _ _ _ |- _ ] => inverts H; fail\n  end.\n\n#[export] Hint Extern 1 => find_contradiction_on_split : FalseHd.\n\n#[export] Hint Extern 1 => applys splu_ord_false; [ eassumption | ] : FalseHd.\n\n#[export] Hint Extern 1 => applys spli_ord_false; [ eassumption | ] : FalseHd.\n\n\n(*********************** locally closed types and terms ***********************)\n\nLemma lc_forall_inv : forall A X,\n    lc_typ (t_forall A) -> lc_typ (A -^ X).\nProof. intros. inverts~ H. Qed.\n\n#[export] Hint Immediate lc_forall_inv : core.\n\nLtac solve_lc_by_inv A :=\n  match goal with\n  | H: lc_typ A |- _ => exact H\n  | H: lc_typ (_ -^ _) |- _ => match type of H with context[ A ] => autorewrite with open in H end\n  | H: lc_typ (t_or _ _) |- _ => match type of H with context[ A ] => inverts H end\n  | H: lc_typ (t_and _ _) |- _ => match type of H with context[ A ] => inverts H end\n  | H: lc_typ (t_rcd _ _) |- _ => match type of H with context[ A ] => inverts H end\n  | H: lc_typ (t_arrow _ _) |- _ => match type of H with context[ A ] => inverts H end\n  | H: lc_typ (t_forall _) |- _ => match type of H with context[ A ] => inverts H end\n  end.\n\n#[export] Hint Extern 1 (lc_typ ?A ) => progress repeat solve_lc_by_inv A : core.\n#[export] Hint Extern 1 (lc_typ (?A -^ _) ) => progress instantiate_cofinites : core.\n#[export] Hint Extern 1 (lc_typ (?A -^ _) ) => progress repeat solve_lc_by_inv A : core.\n#[export] Hint Extern 1 (lc_typ (?A -^ ?X) ) =>\n            match goal with\n              H: forall x, lc_typ _ |- _ =>\n              match type of H with context [A] => specialize (H X) end\n            end : core.\n\nLemma ordu_lc : forall A, ordu A -> lc_typ A.\nProof. introv H. induction~ H. Qed.\n\nLemma ordi_lc : forall A, ordi A -> lc_typ A.\nProof. introv H. induction~ H. eauto using ordu_lc. Qed.\n\nLemma orduFty_lc : forall Fty, UnionOrdinaryFty Fty -> lc_Fty Fty.\nProof with eauto using ordu_lc. introv H. induction H... Qed.\n\nLemma splu_lc : forall A B C, splu A B C-> lc_typ A /\\ lc_typ B /\\ lc_typ C.\nProof.\n  introv H.\n  induction H; repeat split; firstorder using ordu_lc, ordi_lc.\nQed.\n\nLemma spli_lc : forall A B C, spli A B C -> lc_typ A /\\ lc_typ B /\\ lc_typ C.\nProof with firstorder using ordu_lc, ordi_lc, splu_lc.\n  introv H.\n  induction H; repeat split~; constructor...\nQed.\n\nLemma declarative_subtyping_lc : forall A B, declarative_subtyping A B -> lc_typ A /\\ lc_typ B.\nProof.\n  introv H. induction H; destruct_conj; split*.\n  all: eauto.\n  all: inverts H; inverts H0; econstructor;\n    intros; autorewrite with open; eauto.\nQed.\n\nLemma algo_sub_lc : forall A B, algo_sub A B -> lc_typ A /\\ lc_typ B.\nProof with firstorder using ordu_lc, ordi_lc, splu_lc, spli_lc.\n  introv H.\n  induction~ H; split; destruct_conj...\nQed.\n\nLemma new_splu_lc : forall A B C, new_splu A B C-> lc_typ A /\\ lc_typ B /\\ lc_typ C.\nProof. introv H. induction* H. splits; eauto. Qed.\n\nLemma new_spli_lc : forall A B C, new_spli A B C-> lc_typ A /\\ lc_typ B /\\ lc_typ C.\nProof with firstorder using new_splu_lc.\n  introv H.\n  induction~ H; split; destruct_conj...\nQed.\n\n\nLtac solve_lc_by_regularity A :=\n  match goal with\n  | H: ordu _ |- _ => match type of H with context[ A ] => apply ordu_lc in H end\n  | H: ordi _ |- _ => match type of H with context[ A ] => apply ordi_lc in H end\n  | H: UnionOrdinaryFty _ |- _ => match type of H with context[ A ] => apply orduFty_lc in H end\n  | H: splu _ _ _ |- _ => match type of H with context[ A ] => apply splu_lc in H end\n  | H: spli _ _ _ |- _ => match type of H with context[ A ] => apply spli_lc in H end\n  | H: algo_sub _ _ |- _ => match type of H with context[ A ] => apply algo_sub_lc in H end\n  | H: new_splu _ _ _ |- _ => match type of H with context[ A ] => apply new_splu_lc in H end\n  | H: new_spli _ _ _ |- _ => match type of H with context[ A ] => apply new_spli_lc in H end\n  | H: declarative_subtyping _ _ |- _ => match type of H with context[ A ] => apply declarative_subtyping_lc in H end\n  end;\n  destruct_conj.\n\n#[export] Hint Extern 1 (lc_typ ?A ) => progress solve_lc_by_regularity A : core.\n#[export] Hint Extern 1 (lc_typ (?A -^ _) ) => progress solve_lc_by_regularity A : core.\n\n(* destruct hypotheses *)\nLtac inverts_all_lc :=\n  repeat lazymatch goal with\n         | H: lc_typ (t_or _ _) |- _ => inverts H\n         | H: lc_typ (t_and _ _) |- _ => inverts H\n         | H: lc_typ (t_rcd _ _) |- _ => inverts H\n         | H: lc_typ (t_arrow _ _) |- _ => inverts H\n         | H: lc_typ (t_forall _) |- _ => inverts H\n         end.\n\nLtac inverts_all_ord :=\nrepeat lazymatch goal with\n| H: ordi (t_and _ _) |- _ => inverts H\n| H: ordu (t_and _ _) |- _ => inverts H\n| H: ordi (t_or _ _) |- _ => inverts H\n| H: ordu (t_or _ _) |- _ => inverts H\n| H: ordi (t_rcd _ _) |- _ => inverts H\n| H: ordu (t_rcd _ _) |- _ => inverts H\n| H: ordi (t_arrow _ _) |- _ => inverts H\n| H: ordu (t_arrow _ _) |- _ => inverts H\n| H: ordi (t_forall _) |- _ => inverts H\n| H: ordu (t_forall _) |- _ => inverts H\nend.\n\n\nLtac inverts_all_spl :=\nrepeat lazymatch goal with\n| H: spli (t_and _ _) _ _ |- _ => inverts H\n| H: splu (t_and _ _) _ _ |- _ => inverts H\n| H: spli (t_or _ _) _ _ |- _ => inverts H\n| H: splu (t_or _ _) _ _ |- _ => inverts H\n| H: spli (t_rcd _ _) _ _ |- _ => inverts H\n| H: splu (t_rcd _ _) _ _ |- _ => inverts H\n| H: spli (t_arrow _ _) _ _ |- _ => inverts H\n| H: splu (t_arrow _ _) _ _ |- _ => inverts H\n| H: spli (t_forall _) _ _ |- _ => inverts H\n| H: splu (t_forall _) _ _ |- _ => inverts H\nend.\n\n(********************* lc & rename & subst **********************************)\n\nLemma lc_typ_rename : forall A X Y,\n    X \\notin (typefv_typ A) -> lc_typ (A -^ X) -> lc_typ (A -^ Y).\nProof with (simpl in *; eauto).\n  introv Fr Lc.\n  assert (H: lc_typ [X ~~> (t_tvar_f Y)] (A -^ X)).\n  applys~ typsubst_typ_lc_typ.\n  simpl in H. rewrite typsubst_typ_spec in H.\n  rewrite close_typ_wrt_typ_open_typ_wrt_typ in H...\nQed.\n\nLtac solve_lc_4 :=\n  progress (* in case X is Y *)\n    ( match goal with\n      | |- lc_typ (?A -^ ?y) => unfold open_typ_wrt_typ; simpl\n      end;\n      try econstructor;\n      match goal with\n      | H: ?y `notin` _ |- lc_typ (open_typ_wrt_typ_rec 0 (t_tvar_f ?x) ?A) => applys lc_typ_rename y; [solve_notin | ]\n      end ).\n\n#[export] Hint Extern 1 (lc_typ _) => progress solve_lc_4 : core.\n\n(* rename / typsubst in ord & split *)\n#[local] Hint Resolve typsubst_typ_lc_typ : core.\n\n(*********************************)\n(* some useful lemmas            *)\n(* for proving typsubst lemmas:  *)\n(* lc_t_forall_exists            *)\n(* typsubst_typ_spec             *)\n(* typsubst_typ_open_typ_wrt_typ *)\n(*********************************)\n\n(* mimic typsubst_lc *)\nLemma rename_ordu : forall A X Y,\n  ordu A ->\n  ordu ( [X ~~> (t_tvar_f Y)] A ).\nProof with (simpl in *; eauto).\n  introv Ord. gen X Y. induction Ord; intros...\n  - destruct (X==X0)...\n  - applys~ (OrdU_forall (L \\u {{X}})).\n    introv Fr. forwards* Ord: H0 X0 X Y.\n    rewrite typsubst_typ_open_typ_wrt_typ in Ord...\n    case_eq (@eq_dec typevar EqDec_eq_of_X X0 X); intuition...\n    rewrite H1 in Ord...\nQed.\n\nLemma rename_ordi : forall A X Y,\n  ordi A ->\n  ordi ( [X ~~> (t_tvar_f Y)] A ).\nProof with (simpl in *; eauto using rename_ordu).\n  introv Ord. gen X Y. induction Ord; intros...\n  - destruct (X==X0)...\n  - applys~ (OrdI_forall (L \\u {{X}})).\n    introv Fr. forwards* Ord: H0 X0 X Y.\n    rewrite typsubst_typ_open_typ_wrt_typ in Ord...\n    case_eq (@eq_dec typevar EqDec_eq_of_X X0 X); intuition...\n    rewrite H1 in Ord...\nQed.\n\n#[export] Hint Immediate rename_ordu rename_ordi : core.\n\nLemma rename_splu : forall A B C X Y,\n  splu A B C->\n  splu ([X ~~> (t_tvar_f Y)] A) ([X ~~> (t_tvar_f Y)] B) ([X ~~> (t_tvar_f Y)] C).\nProof with (simpl in *; eauto).\n  introv Spl. gen X Y.\n  induction Spl; intros...\n  - applys~ (SpU_forall (L \\u {{X}})).\n    introv Fr. forwards* Spl: H0 X0 X Y.\n    rewrite 3 typsubst_typ_open_typ_wrt_typ in Spl...\n    case_eq (@eq_dec typevar EqDec_eq_of_X X0 X); intuition...\n    rewrite H1 in Spl...\nQed.\n\nLemma rename_spli : forall A B C X Y,\n  spli A B C->\n  spli ([X ~~> (t_tvar_f Y)] A) ([X ~~> (t_tvar_f Y)] B) ([X ~~> (t_tvar_f Y)] C).\nProof with (simpl in *; eauto using rename_ordi, rename_splu).\n  introv Spl. gen X Y.\n  induction Spl; intros...\n  - applys~ (SpI_forall (L \\u {{X}})).\n    introv Fr. forwards* Spl: H0 X0 X Y.\n    rewrite 3 typsubst_typ_open_typ_wrt_typ in Spl...\n    case_eq (@eq_dec typevar EqDec_eq_of_X X0 X); intuition...\n    rewrite H1 in Spl...\nQed.\n\nLemma rename_algo_sub : forall A B X Y,\n  algo_sub A B ->\n  algo_sub ([X ~~> (t_tvar_f Y)] A) ([X ~~> (t_tvar_f Y)] B).\nProof with (simpl in *; eauto using rename_spli, rename_splu).\n  introv s. gen X Y.\n  induction s; intros...\n  - applys~ (ASub_forall (L \\u {{X}})).\n    introv Fr. forwards* HS: H0 X0 X Y.\n    rewrite 2 typsubst_typ_open_typ_wrt_typ in HS...\n    case_eq (@eq_dec typevar EqDec_eq_of_X X0 X); intuition...\n    rewrite H1 in HS...\nQed.\n\n#[export] Hint Immediate rename_ordu rename_ordi\n rename_spli rename_splu rename_algo_sub : core.\n\nLemma ordu_rename_open : forall A X Y,\n    X \\notin (typefv_typ A) -> ordu( A -^ X ) -> ordu( A -^ Y ).\nProof with (simpl in *; eauto).\n  introv Fr Lc.\n  assert (H: ordu[X ~~> (t_tvar_f Y)] (A -^ X) ).\n  applys~ rename_ordu.\n  simpl in H. rewrite typsubst_typ_spec in H.\n  rewrite close_typ_wrt_typ_open_typ_wrt_typ in H...\nQed.\n\nLemma ordi_rename_open : forall A X Y,\n    X \\notin (typefv_typ A) -> ordi ( A -^ X ) -> ordi ( A -^ Y ).\nProof with (simpl in *; eauto).\n  introv Fr Lc.\n  assert (H: ordi [X ~~> (t_tvar_f Y)] (A -^ X) ).\n  applys~ rename_ordi.\n  simpl in H. rewrite typsubst_typ_spec in H.\n  rewrite close_typ_wrt_typ_open_typ_wrt_typ in H...\nQed.\n\nLemma splu_rename_open : forall A B C X Y,\n    X \\notin (typefv_typ A) \\u (typefv_typ B) \\u (typefv_typ C)->\n    splu ( A -^ X ) ( B -^ X ) ( C -^ X ) ->\n    splu ( A -^ Y ) ( B -^ Y ) ( C -^ Y ).\nProof with (simpl in *; eauto).\n  introv Fr Lc.\n  assert (H: splu [X ~~> (t_tvar_f Y)] (A -^ X) [X ~~> (t_tvar_f Y)] (B -^ X) [X ~~> (t_tvar_f Y)] (C -^ X)).\n  applys~ rename_splu.\n  simpl in H. rewrite 3 typsubst_typ_spec in H.\n  rewrite 3 close_typ_wrt_typ_open_typ_wrt_typ in H...\nQed.\n\nLemma spli_rename_open : forall A B C X Y,\n    X \\notin (typefv_typ A) \\u (typefv_typ B) \\u (typefv_typ C)->\n    spli ( A -^ X ) ( B -^ X ) ( C -^ X ) ->\n    spli ( A -^ Y ) ( B -^ Y ) ( C -^ Y ).\nProof with (simpl in *; eauto).\n  introv Fr Lc.\n  assert (H: spli [X ~~> (t_tvar_f Y)] (A -^ X) [X ~~> (t_tvar_f Y)] (B -^ X) [X ~~> (t_tvar_f Y)] (C -^ X)).\n  applys~ rename_spli.\n  simpl in H. rewrite 3 typsubst_typ_spec in H.\n  rewrite 3 close_typ_wrt_typ_open_typ_wrt_typ in H...\nQed.\n\nLemma algo_sub_rename_open : forall A B X Y,\n    X \\notin (typefv_typ A) \\u (typefv_typ B) ->\n    algo_sub ( A -^ X ) ( B -^ X ) ->\n    algo_sub ( A -^ Y ) ( B -^ Y ).\nProof with (simpl in *; eauto).\n  introv Fr Lc.\n  assert (H: algo_sub [X ~~> (t_tvar_f Y)] (A -^ X) [X ~~> (t_tvar_f Y)] (B -^ X)).\n  applys~ rename_algo_sub.\n  simpl in H. rewrite 2 typsubst_typ_spec in H.\n  rewrite 2 close_typ_wrt_typ_open_typ_wrt_typ in H...\nQed.\n\n#[export]\nHint Extern 1 (ordu ( ?A -^ ?Y )) =>\n  match goal with\n  | H: ordu ( A -^ ?X ) |- _ => let Fr := fresh in\n                               assert (Fr: X \\notin (typefv_typ A)) by solve_notin;\n                                 applys ordu_rename_open Fr H\n  end : core.\n\n#[export]\nHint Extern 1 (ordi ( ?A -^ ?Y )) =>\n  match goal with\n  | H: ordi ( A -^ ?X ) |- _ => let Fr := fresh in\n                               assert (Fr: X \\notin (typefv_typ A)) by solve_notin;\n                                 applys ordi_rename_open Fr H\n  end : core.\n\n#[export]\nHint Extern 1 (splu ( ?A -^ ?Y ) _ _) =>\n  match goal with\n| H: splu ( A -^ ?X ) ( ?B -^ ?X ) ( ?C -^ ?X ) |- _ => applys splu_rename_open H; solve_notin\nend : core.\n\n#[export]\nHint Extern 1 (spli ( ?A -^ ?Y ) _ _) =>\n  match goal with\n| H: spli ( A -^ ?X ) ( ?B -^ ?X ) ( ?C -^ ?X ) |- _ => applys spli_rename_open H; solve_notin\nend : core.\n\n#[export]\nHint Extern 1 (algo_sub ( ?A -^ ?Y ) _ ) =>\n  match goal with\n| H: algo_sub ( A -^ ?X ) ( ?B -^ ?X ) |- _ => applys algo_sub_rename_open H; solve_notin\n  end : core.\n\n#[local] Hint Immediate ordi_rename_open ordu_rename_open spli_rename_open\n splu_rename_open algo_sub_rename_open : core.\n\n\nLemma ordu_forall_exists : forall X B,\n  X `notin` typefv_typ B ->\n  ordu (open_typ_wrt_typ B (t_tvar_f X)) ->\n  ordu (t_forall B).\nProof with (simpl in *; eauto).\n  introv Fr Ord.\n  applys~ OrdU_forall (typefv_typ B).\nQed.\n\nLemma ordi_forall_exists : forall X B,\n  X `notin` typefv_typ B ->\n  ordi (open_typ_wrt_typ B (t_tvar_f X)) ->\n  ordi (t_forall B).\nProof with (simpl in *; eauto).\n  introv Fr Ord.\n  applys~ OrdI_forall (typefv_typ B).\nQed.\n\n#[export]\nHint Extern 1 =>\nmatch goal with\n| H: ordi (open_typ_wrt_typ ?B (t_tvar_f ?X)) |- ordi (t_forall _ ?B) =>\n  applys~ ordi_forall_exists H; solve_notin\nend : core.\n\n#[export]\nHint Extern 1 =>\nmatch goal with\n| H: ordu (open_typ_wrt_typ ?B (t_tvar_f ?X)) |- ordu (t_forall _ ?B) =>\n  applys~ ordu_forall_exists H; solve_notin\nend : core.\n\n\nLemma splu_fv_1 : forall A B C,\n    splu A B C -> (typefv_typ B) [<=] (typefv_typ A).\nProof with (subst; simpl in *).\n  introv Hspl.\n  induction Hspl; simpl in *; try fsetdec.\n  remember ((typefv_typ A) \\u (typefv_typ A1)).\n  pick fresh X.\n  forwards~ Aux1: H0 X.\n  lets* Aux2: typefv_typ_open_typ_wrt_typ_upper A (t_tvar_f X).\n  lets* Aux3: typefv_typ_open_typ_wrt_typ_lower A1 (t_tvar_f X).\n  assert (HS: typefv_typ A1 [<=] union (typefv_typ (t_tvar_f X)) (typefv_typ A)) by fsetdec.\n  clear Aux1 Aux2 Aux3...\n  fsetdec.\nQed.\n\nLemma splu_fv_2 : forall A B C,\n    splu A B C -> (typefv_typ C) [<=] (typefv_typ A).\nProof with (subst; simpl in *).\n  introv Hspl.\n  induction Hspl; simpl in *; try fsetdec.\n  remember ((typefv_typ A) \\u (typefv_typ A2)).\n  pick fresh X.\n  forwards~ Aux1: H0 X.\n  lets* Aux2: typefv_typ_open_typ_wrt_typ_upper A (t_tvar_f X).\n  lets* Aux3: typefv_typ_open_typ_wrt_typ_lower A2 (t_tvar_f X).\n  assert (HS: typefv_typ A2 [<=] union (typefv_typ (t_tvar_f X)) (typefv_typ A)) by fsetdec.\n  clear Aux1 Aux2 Aux3...\n  fsetdec.\nQed.\n\nLemma splu_forall_exists : forall X B B1 B2,\n  X `notin` typefv_typ B ->\n  splu (B -^ X) B1 B2->\n  splu (t_forall B) (t_forall (close_typ_wrt_typ X B1)) (t_forall (close_typ_wrt_typ X B2)).\nProof with (simpl in *; eauto).\n  introv Fr H.\n  rewrite <- (open_typ_wrt_typ_close_typ_wrt_typ B1 X) in H.\n  rewrite <- (open_typ_wrt_typ_close_typ_wrt_typ B2 X) in H.\n  applys SpU_forall. intros. applys splu_rename_open H.\n  repeat rewrite typefv_typ_close_typ_wrt_typ.\n  solve_notin.\n  Unshelve. applys empty.\nQed.\n\nLemma spli_fv_1 : forall A B C,\n    spli A B C -> (typefv_typ B) [<=] (typefv_typ A).\nProof with (subst; simpl in *).\n  introv Hspl.\n  induction Hspl; simpl in *; try fsetdec.\n  - lets: splu_fv_1 H0. fsetdec.\n  -\n  remember ((typefv_typ A) \\u (typefv_typ A1)).\n  pick fresh X.\n  forwards~ Aux1: H0 X.\n  lets* Aux2: typefv_typ_open_typ_wrt_typ_upper A (t_tvar_f X).\n  lets* Aux3: typefv_typ_open_typ_wrt_typ_lower A1 (t_tvar_f X).\n  assert (HS: typefv_typ A1 [<=] union (typefv_typ (t_tvar_f X)) (typefv_typ A)) by fsetdec.\n  clear Aux1 Aux2 Aux3...\n  fsetdec.\nQed.\n\nLemma spli_fv_2 : forall A B C,\n    spli A B C -> (typefv_typ C) [<=] (typefv_typ A).\nProof with (subst; simpl in *).\n  introv Hspl.\n  induction Hspl; simpl in *; try fsetdec.\n  - lets: splu_fv_2 H0. fsetdec.\n  -\n  remember ((typefv_typ A) \\u (typefv_typ A2)).\n  pick fresh X.\n  forwards~ Aux1: H0 X.\n  lets* Aux2: typefv_typ_open_typ_wrt_typ_upper A (t_tvar_f X).\n  lets* Aux3: typefv_typ_open_typ_wrt_typ_lower A2 (t_tvar_f X).\n  assert (HS: typefv_typ A2 [<=] union (typefv_typ (t_tvar_f X)) (typefv_typ A)) by fsetdec.\n  clear Aux1 Aux2 Aux3...\n  fsetdec.\nQed.\n\nLemma spli_forall_exists : forall X B B1 B2,\n  X `notin` typefv_typ B ->\n  spli (B -^ X) B1 B2->\n  spli (t_forall B) (t_forall (close_typ_wrt_typ X B1)) (t_forall (close_typ_wrt_typ X B2)).\nProof with (simpl in *; eauto).\n  introv Fr H.\n  rewrite <- (open_typ_wrt_typ_close_typ_wrt_typ B1 X) in H.\n  rewrite <- (open_typ_wrt_typ_close_typ_wrt_typ B2 X) in H.\n  applys SpI_forall. intros. applys spli_rename_open H.\n  repeat rewrite typefv_typ_close_typ_wrt_typ.\n  solve_notin.\n  Unshelve. applys empty.\nQed.\n\n#[export]\nHint Extern 1 =>\nmatch goal with\n| H: spli (?B -^ ?X) ?B1 ?B2 |-\n  spli (t_forall ?B) (t_forall ?A (close_typ_wrt_typ ?X ?B1)) (t_forall ?A (close_typ_wrt_typ ?X ?B2)) =>\n  applys spli_forall_exists H; solve_notin\n| H: splu (?B -^ ?X) ?B1 ?B2 |-\n  splu (t_forall ?B) (t_forall ?A (close_typ_wrt_typ ?X ?B1)) (t_forall ?A (close_typ_wrt_typ ?X ?B2)) =>\n  applys splu_forall_exists H; solve_notin\n| H: spli (?B -^ ?X) _ _ |-\n  spli (t_forall ?B) _ _ =>\n  apply spli_forall_exists in H; try rewrite close_typ_wrt_typ_open_typ_wrt_typ in *; try solve_notin\n| H: splu (?B -^ ?X) _ _ |-\n  splu (t_forall ?B) _ _ =>\n  apply splu_forall_exists in H; try rewrite close_typ_wrt_typ_open_typ_wrt_typ in *; try solve_notin\nend : core.\n\n\n(*********************************** ord & split *******************************)\n#[export] Hint Extern 1 (ordi _) =>\nprogress match goal with\n         | H: forall X : atom, X `notin` _ -> ordi (?B -^ X) |- ordi (t_forall ?B) => applys OrdI_forall H\n         | |- ordi (t_forall _) => detect_fresh_var_and_apply ordi_forall_exists\n(*         | _ => applys OrdI_var + applys OrdI_top + applys OrdI_bot + applys OrdI_arrow + applys OrdI_forall *)\n         end : core.\n\n#[export] Hint Extern 1 (ordu _) =>\nprogress match goal with\n         | H: forall X : atom, X `notin` _ -> ordu (?B -^ X) |- ordu (t_forall ?B) => applys OrdU_forall H\n         | |- ordu (t_forall _) => detect_fresh_var_and_apply ordu_forall_exists\n (*         | _ => applys OrdU_var + applys OrdU_top + applys OrdU_bot + applys OrdU_arrow + applys OrdU_forall  *)\n         end : core.\n\n\n#[export] Hint Extern 0 (spli (t_and _ _) _ _) => applys SpI_and : core.\n#[export] Hint Extern 0 (splu (t_or _ _) _ _) => applys SpU_or : core.\n#[export] Hint Extern 0 (spli (t_arrow _ (t_and _ _)) _ _) => applys SpI_arrow : core.\n(*\n#[export] Hint Extern 1 (spli (t_arrow (t_or _ _) _) _ _) => applys SpI_arrowUnion : core.\n#[export] Hint Extern 1 (spli _ _ _) => applys SpI_arrow + applys SpI_in + applys SpI_and : core.\n#[export] Hint Extern 1 (splu _ _ _) => applys SpU_in + applys SpU_or : core.\n\n#[export] Hint Extern 1 (spli (t_forall _)  _ _) => applys SpI_forall : core.\n#[export] Hint Extern 1 (splu (t_forall _)  _ _) => applys SpU_forall : core.\n*)\n\n(* Types are Either Ordinary or Splittable *)\nLemma ordu_or_split: forall A,\n    lc_typ A -> ordu A \\/ exists B C, splu A B C.\nProof with (subst~; simpl in *; eauto).\n  introv Lc. induction Lc...\n  - forwards* [?|(?&?&?)]: IHLc.\n  - (* and *)\n    forwards* [?|(?&?&?)]: IHLc1.\n    forwards* [?|(?&?&?)]: IHLc2.\n  - (* forall *)\n    pick fresh x for [[B]].\n    forwards* [?|(?&?&?)]: H0 x.\nDefined.\n\nLemma ordi_or_split: forall A,\n    lc_typ A -> ordi A \\/ exists B C, spli A B C.\nProof with (subst~; simpl in *; eauto).\n  introv Lc. induction Lc...\n  - forwards* [?|(?&?&?)]: IHLc.\n  - (* and *)\n    forwards* [?|(?&?&?)]: IHLc1.\n    forwards* [?|(?&?&?)]: IHLc2.\n  - (* arrow *)\n    forwards* [?|(?&?&?)]: IHLc2.\n    forwards* [?|(?&?&?)]: ordu_or_split A.\n  - (* forall *)\n    pick fresh x for [[B]].\n    forwards* [?|(?&?&?)]: H0 x.\nDefined.\n\n(* lemmas for ordinary *)\nLemma spli_keep_ord_l : forall A B C,\n   spli A B C -> ordu A -> ordu B.\nProof.\n  introv Hspl Hord.\n  inductions Hspl; try destruct m; inverts Hord; eauto with *.\nQed.\n\nLemma spli_keep_ord_r : forall A B C,\n   spli A B C -> ordu A -> ordu C.\nProof.\n  introv Hspl Hord.\n  inductions Hspl; try destruct m; inverts Hord; eauto with *.\nQed.\n\nLemma splu_keep_ord_l : forall A B C,\n   splu A B C -> ordi A -> ordi B.\nProof.\n  introv Hspl Hord.\n  inductions Hspl; try destruct m; inverts Hord; eauto with *.\nQed.\n\nLemma splu_keep_ord_r : forall A B C,\n   splu A B C -> ordi A -> ordi C.\nProof.\n  introv Hspl Hord.\n  inductions Hspl; try destruct m; inverts Hord; eauto with *.\nQed.\n\n#[export] Hint Extern 1 (ordi _) => applys splu_keep_ord_l; [ eassumption | ] : core.\n#[export] Hint Extern 1 (ordi _) => applys splu_keep_ord_r; [ eassumption | ] : core.\n#[export] Hint Extern 1 (ordu _) => applys spli_keep_ord_l; [ eassumption | ] : core.\n#[export] Hint Extern 1 (ordu _) => applys spli_keep_ord_r; [ eassumption | ] : core.\n\n(*********************** binding ********************************)\n\nLtac close_typ_var X :=\n  repeat match goal with\n         | H: ?A = ?B -^ X |- _ =>\n           let H' := fresh \"Heq\" in\n           forwards~ H': close_typ_wrt_typ_open_typ_wrt_typ B;\n           rewrite <- H in H'; clear H\n         end.\n\nLtac simpl_rename H :=\n  match type of H with\n  | context [ [?X ~~> _] (_ -^ ?X) ] =>\n    rewrite typsubst_typ_spec in H; rewrite close_typ_wrt_typ_open_typ_wrt_typ in H\n  | context [ [?X ~~> _] ?A ] =>\n    rewrite <- (open_typ_wrt_typ_close_typ_wrt_typ A X) in H;\n    rewrite typsubst_typ_spec in H; rewrite close_typ_wrt_typ_open_typ_wrt_typ in H\n  end.\n\nLtac simpl_rename_goal :=\n  match goal with\n  | |- context [ [?X ~~> _] (_ -^ ?X) ] =>\n    rewrite typsubst_typ_spec; rewrite close_typ_wrt_typ_open_typ_wrt_typ\n  | |- context [ [?X ~~> _] ?A ] =>\n    rewrite <- (open_typ_wrt_typ_close_typ_wrt_typ A X);\n    rewrite typsubst_typ_spec; rewrite close_typ_wrt_typ_open_typ_wrt_typ\n  end.\n\nLocal Ltac open_typ_by_var_in_goal A X :=\n    let HR := fresh \"Heq\" in\n    assert (HR: A = close_typ_wrt_typ X (A -^X));\n    try solve [rewrite close_typ_wrt_typ_open_typ_wrt_typ; auto];\n    rewrite HR.\n\n(* Splitting types is deterministic *)\n(********************************************)\n(*                                          *)\n(*          Lemma split_unique              *)\n(*                                          *)\n(********************************************)\nLemma splu_unique : forall T A1 A2 B1 B2,\n    splu T A1 B1 -> splu T A2 B2 -> A1 = A2 /\\ B1 = B2.\nProof with eauto.\n  introv s1 s2. gen A2 B2.\n  induction s1; intros;\n    inverts* s2;\n    try solve [forwards* (eq1&eq2): IHs1; subst; split*]; solve_false.\n  pick fresh X.\n  forwards* HS: H2 X.\n  forwards* (eq1&eq2): H0 HS.\n  open_typ_by_var_in_goal A1 X.\n  open_typ_by_var_in_goal A2 X.\n  open_typ_by_var_in_goal A4 X.\n  open_typ_by_var_in_goal A5 X.\n  rewrite eq1. rewrite eq2. split*.\nQed.\n\nLemma spli_unique : forall T A1 A2 B1 B2,\n    spli T A1 B1 -> spli T A2 B2 -> A1 = A2 /\\ B1 = B2.\nProof with eauto.\n  introv s1 s2. gen A2 B2.\n  induction s1; intros;\n    inverts* s2;\n    try solve [forwards* (eq1&eq2): IHs1; subst; split*]; solve_false.\n  - forwards~ (?&?): splu_unique H0 H6. subst~.\n  -\n    pick fresh X.\n    forwards* HS: H2 X.\n    forwards* (eq1&eq2): H0 HS.\n    open_typ_by_var_in_goal A1 X.\n    open_typ_by_var_in_goal A2 X.\n    open_typ_by_var_in_goal A4 X.\n    open_typ_by_var_in_goal A5 X.\n    rewrite eq1. rewrite eq2. split*.\nQed.\n\n(********************************************)\n(*                                          *)\n(*             Ltac auto_unify              *)\n(*                                          *)\n(*  extends choose_unify                    *)\n(*  no solve_false at the end                *)\n(*                                          *)\n(********************************************)\nLtac auto_unify :=\n  simpl in *;\n  try solve [applys SpI_and];\n  try solve [applys SpU_or];\n  try repeat match goal with\n             | [ H1: spli (t_and _ _)  _ _  |- _ ] =>\n               inverts H1\n             | [ H1: splu (t_or _ _)  _ _  |- _ ] =>\n               inverts H1\n             | [ H1: spli ?A  _ _ , H2: spli ?A _ _ |- _ ] =>\n               (forwards (?&?): spli_unique H1 H2;\n                subst; clear H2)\n             | [ H1: splu ?A  _ _ , H2: splu ?A _ _ |- _ ] =>\n               (forwards (?&?): splu_unique H1 H2;\n                subst; clear H2)\n         end.\n\n\nLtac basic_auto :=\n  destruct_conj; auto_unify;\n  try exists; try splits;\n  try reflexivity;\n  try lazymatch goal with\n      | |- lc_typ _ => eauto\n      | |- spli _ _ _ => try eapply spli_rename_open; try eassumption; econstructor; try eassumption;\n                         eauto\n      | |- splu _ _ _ => try eapply splu_rename_open; try eassumption; econstructor; try eassumption;\n                         eauto\n    end; try eassumption; elia.\n\n(*****************************************************************************)\n\nLtac solve_algo_sub :=\nmatch goal with\n| |- algo_sub (t_tvar_f _) (t_tvar_f _) => simple apply ASub_refl\n| |- algo_sub _ t_top => simple apply ASub_top\n| |- algo_sub t_bot _ => simple apply ASub_bot\n| |- algo_sub (t_and ?A ?B) (t_and ?A ?B) => applys ASub_and; [ | applys ASub_andl | applys ASub_andr ]\n| |- algo_sub _ (t_and _ _) => applys ASub_and\n| H1: spli ?A ?A1 ?A2 |- algo_sub _ ?A => applys ASub_and H1\n| H: algo_sub ?A ?C |- algo_sub (t_and ?A _) ?C => applys ASub_andl H\n| H: algo_sub ?B ?C |- algo_sub (t_and _ ?B) ?C => applys ASub_andr H\n| |- algo_sub (t_and ?A _) ?A => applys ASub_andl\n| |- algo_sub (t_and _ ?A) ?A => applys ASub_andr\n| H1: spli ?A ?A1 ?A2 , H2: algo_sub ?A1 ?C |- algo_sub ?A ?C => applys ASub_andl H1 H2\n| H1: spli ?A ?A1 ?A2 , H2: algo_sub ?A2 ?C |- algo_sub ?A ?C => applys ASub_andr H1 H2\n\n| |- algo_sub (t_or ?A ?B) (t_or ?A ?B) => applys ASub_or; [ | applys ASub_or | applys ASub_or ]\n| |- algo_sub (t_or _ _) _ => applys ASub_or\n| H1: splu ?A ?A1 ?A2 |- algo_sub ?A _ => applys ASub_or H1\n| H: algo_sub ?C ?A |- algo_sub ?C (t_or ?A _) => applys ASub_orl H\n| H: algo_sub ?C ?B |- algo_sub ?C (t_or _ ?B) => applys ASub_orr H\n| |- algo_sub ?A (t_or ?A _) => applys ASub_orl\n| |- algo_sub ?A (t_or _ ?A) => applys ASub_orr\n| H1: splu ?A ?A1 ?A2 , H2: algo_sub ?C ?A1 |- algo_sub ?C ?A => applys ASub_orl H1 H2\n| H1: splu ?A ?A1 ?A2 , H2: algo_sub ?C ?A2 |- algo_sub ?C ?A => applys ASub_orr H1 H2\n| |- algo_sub (t_arrow _ _) (t_arrow _ _) => simple apply ASub_arrow\n| |- algo_sub (t_forall _) (t_forall _) => simple apply ASub_forall\n| |- algo_sub (t_rcd _ _) (t_rcd _ _) => simple apply ASub_rcd\nend.\n\n#[local] Hint Extern 1 (algo_sub _ _) => solve_algo_sub : core.\n\n(* algorithm correctness *)\n\n(* Lemma Inversion of Subtyping [1] *)\nLemma algo_sub_rcd_inv : forall l1 l2 A B,\n    algo_sub (t_rcd l1 A) (t_rcd l2 B) -> l1=l2 /\\ algo_sub A B.\nProof.\n  introv H.\n  indTypSize (size_typ A + size_typ B).\n  inverts H; inverts_all_spl; inverts_all_ord; try assumption;\n    repeat match goal with\n           | H: algo_sub (t_rcd _ _) (t_rcd _ _) |- _ => forwards (?&?): IH H; elia; clear H\n           end.\n  all: eauto.\nQed.\n\nLemma algo_sub_forall_inv : forall A B X,\n    algo_sub (t_forall A) (t_forall B) -> algo_sub (A -^ X) (B -^ X).\nProof with (try eassumption).\n  intros.\n  indTypSize (size_typ A + size_typ B).\n  inverts H; inverts_all_spl; inverts_all_lc; try assumption;\n    repeat match goal with\n           | H: algo_sub (t_forall _) (t_forall _) |- _ => forwards: IH H; elia; clear H\n           end.\n  1: eauto.\n  all: pick_fresh Y; instantiate_cofinites_with Y...\n  1: try solve [applys~ algo_sub_rename_open].\n  all:  repeat match goal with\n           | H: spli (_ -^ ?Y) _ _ |- _ => forwards~: spli_rename_open X H; clear H\n           | H: splu (_ -^ ?Y) _ _ |- _ => forwards~: splu_rename_open X H; clear H\n           end.\nQed.\n\nLemma algo_sub_arrow_inv : forall A B C D,\n    algo_sub (t_arrow A B) (t_arrow C D) -> (algo_sub C A) /\\ (algo_sub B D).\nProof with (try eassumption).\n  introv s.\n  indTypSize (size_typ (t_arrow A B) + size_typ (t_arrow C D)).\n  inverts s; inverts_all_spl; inverts_all_ord; try assumption;\n    repeat match goal with\n           | H: algo_sub (t_arrow _ _) (t_arrow _ _) |- _ => forwards (?&?): IH H; elia; clear H\n           end; inverts_all_lc.\n  all: split*.\nQed.\n\n(* A very useful inversion lemma when the type T is both intersection- and\n   union- splittable *)\nLemma double_split : forall T A1 A2 B1 B2,\n    splu T A1 A2 -> spli T B1 B2 ->\n    ((exists C1 C2, spli A1 C1 C2 /\\ splu B1 C1 A2 /\\ splu B2 C2 A2) \\/\n    (exists C1 C2, spli A2 C1 C2 /\\ splu B1 A1 C1 /\\ splu B2 A1 C2)) \\/\n    ((exists C1 C2, splu B1 C1 C2 /\\ spli A1 C1 B2 /\\ spli A2 C2 B2) \\/\n    (exists C1 C2, splu B2 C1 C2 /\\ spli A1 B1 C1 /\\ spli A2 B1 C2)).\nProof with exists; repeat split*.\n  introv Hu Hi.\n  indTypSize (size_typ T).\n  inverts keep Hu; inverts keep Hi.\n  - (* spli or *) left. left...\n  - (* spli or *) left. right...\n  - (* splu and *) right. left...\n  - (* splu and *) right. right...\n  - (* forall *) pick fresh X. instantiate_cofinites_with X.\n    forwards [ [?|?] | [?|?] ] : IH (A -^ X); try eassumption; elia; destruct_conj.\n    left; left... left; right... right; left... right; right...\n  - (* rcd *) inverts_all_spl.\n   forwards [ [?|?] | [?|?] ] : IH A; try eassumption; elia; destruct_conj.\n   left; left... left; right... right; left... right; right...\nQed.\n\n\nLemma algo_sub_or_inv : forall A A1 A2 B,\n    algo_sub A B -> splu A A1 A2 ->\n    algo_sub A1 B /\\ algo_sub A2 B.\nProof with (auto_unify; auto; try eassumption; elia; try solve [split; auto]; eauto 4).\n  introv Hsub Hspl.\n  indTypSize (size_typ A + size_typ B).\n  inverts Hsub; inverts_all_spl; inverts_all_ord; solve_false; auto_unify; auto.\n  - split*.\n  - (* forall *)\n    split; applys ASub_forall (L `union` L0); intros X Fry; instantiate_cofinites_with X.\n    all: match goal with\n              H1 : algo_sub ?A ?B, H2 : splu ?A _ _ |- _ => forwards(?&?): IH H2 H1; elia\n         end; eauto.\n    - (* rcd *)\n    match goal with\n              H1 : algo_sub ?A ?B, H2 : splu ?A _ _ |- _ => forwards(?&?): IH H2 H1; elia\n    end; split; eauto.\n  - (* spli B *)\n    repeat match goal with\n              H1 : algo_sub ?A ?B, H2 : splu ?A _ _ |- _ => forwards(?&?): IH H2 H1; clear H1; elia\n           end; split; eauto.\n  -  (* double split A *)\n    forwards [ [?|?] | [?|?] ]: double_split Hspl; try eassumption; destruct_conj;\n      try solve [\n            match goal with\n              H1 : algo_sub ?A ?B, H2 : splu ?A _ _ |- _ => forwards(?&?): IH H2 H1; elia\n            end; split; eauto].\n    split*.\n  -  (* double split A *)\n    forwards [ [?|?] | [?|?] ]: double_split Hspl; try eassumption; destruct_conj;\n      try solve [\n            match goal with\n              H1 : algo_sub ?A ?B, H2 : splu ?A _ _ |- _ => forwards(?&?): IH H2 H1; elia\n            end; split; eauto].\n    split*.\n  - (* splu B *)\n    repeat match goal with\n              H1 : algo_sub ?A ?B, H2 : splu ?A _ _ |- _ => forwards(?&?): IH H2 H1; clear H1; elia\n           end; split; eauto.\n  - (* splu B *)\n    repeat match goal with\n              H1 : algo_sub ?A ?B, H2 : splu ?A _ _ |- _ => forwards(?&?): IH H2 H1; clear H1; elia\n           end; split; eauto.\nQed.\n\nLemma algo_sub_orlr_inv : forall A B B1 B2,\n    algo_sub A B -> ordu A -> splu B B1 B2 ->\n    algo_sub A B1 \\/ algo_sub A B2.\nProof with (solve_false; auto_unify; try eassumption; elia; eauto 3).\n  introv Hsub Hspl.\n  indTypSize (size_typ A + size_typ B).\n  inverts Hsub; inverts_all_spl; inverts_all_ord; solve_false; auto_unify; auto.\n  - (* forall *)\n    pick fresh X. instantiate_cofinites_with X.\n    match goal with\n              H0: ordu ?A, H1 : algo_sub ?A ?B, H2 : splu ?B _ _ |- _ => forwards [?|?]: IH H0 H1 H2; elia\n    end; eauto.\n    - (* rcd *)\n      match goal with\n        H0: ordu ?A, H1 : algo_sub ?A ?B, H2 : splu ?B _ _ |- _ => forwards [?|?]: IH H0 H1 H2; elia\n      end; eauto.\n  - (* double split *)\n    forwards [ [?|?] | [?|?] ]: double_split H; try eassumption; destruct_conj;\n      repeat match goal with\n               H0: ordu ?A, H1 : algo_sub ?A ?B, H2 : splu ?B _ _ |- _ => forwards [?|?]: IH H0 H1 H2; clear H1; elia\n             end; eauto.\n  - forwards [?|?]: IH H1...\n  - forwards [?|?]: IH H1...\n    Unshelve. all: apply empty.\nQed.\n\n(* Lemma Inversion of Subtyping [2] *)\nLemma algo_sub_and_inv : forall A B B1 B2,\n    algo_sub A B -> spli B B1 B2 -> algo_sub A B1 /\\ algo_sub A B2.\nProof with (try eassumption).\n  introv Hsub Hspl.\n  indTypSize (size_typ A + size_typ B).\n  inverts Hsub; inverts_all_spl; inverts_all_ord; solve_false; auto_unify; auto;\n    repeat match goal with\n              H1 : algo_sub ?A ?B, H2 : spli ?B _ _ |- _ => forwards(?&?): IH H1 H2; clear H1; elia\n    end.\n  - split*.\n  - split; applys* ASub_arrow.\n  - forwards (?&?): algo_sub_or_inv H... split; applys* ASub_arrow.\n  - (* forall *)\n    split; applys ASub_forall (L `union` L0); intros X Fry; instantiate_cofinites_with X.\n    all: match goal with\n              H1 : algo_sub ?A ?B, H2 : spli ?B _ _ |- _ => forwards(?&?): IH H1 H2; elia\n         end; eauto.\n  - (* rcd *) split*.\n  - (* spli B *) split~.\n  - (* spli B *) split~.\n  - (* spli B *) split~.\n  - (* double split B *)\n    forwards [ [?|?] | [?|?] ]: double_split Hspl; try eassumption; destruct_conj;\n      try solve [\n            match goal with\n              H1 : algo_sub ?A ?B, H2 : spli ?B _ _ |- _ => forwards(?&?): IH H1 H2; clear H1; elia\n            end; split; eauto].\n    split*.\n  - (* double split B *)\n    forwards [ [?|?] | [?|?] ]: double_split Hspl; try eassumption; destruct_conj;\n      try solve [\n            match goal with\n              H1 : algo_sub ?A ?B, H2 : spli ?B _ _ |- _ => forwards(?&?): IH H1 H2; clear H1; elia\n            end; split; eauto].\n    split*.\nQed.\n\nLemma algo_sub_andlr_inv : forall A B A1 A2,\n    algo_sub A B -> spli A A1 A2 -> ordi B ->\n    algo_sub A1 B \\/ algo_sub A2 B.\nProof with (try eassumption; elia).\n  introv Hsub Hspl.\n  indTypSize (size_typ A + size_typ B).\n  inverts Hsub; inverts_all_spl; inverts_all_ord; solve_false; auto_unify; auto;\n    repeat match goal with\n              H0: ordi ?B, H1 : algo_sub ?A ?B, H2 : spli ?A _ _ |- _ => forwards [?|?]: IH H1 H2 H0; clear H1; elia\n    end.\n  - (* arrow *) eauto. - (* arrow *) eauto.\n  - forwards [?|?]: algo_sub_orlr_inv H7... all: eauto.\n  - (* forall *)\n    pick fresh X. instantiate_cofinites_with X.\n    match goal with\n              H0: ordi ?B, H1 : algo_sub ?A ?B, H2 : spli ?A _ _ |- _ => forwards [?|?]: IH H1 H2 H0; clear H1; elia\n    end; eauto.\n  - (* rcd *) eauto. - (* rcd *) eauto.\n  - (* double split *)\n    forwards [ [?|?] | [?|?] ]: double_split Hspl; try eassumption; destruct_conj;\n      repeat match goal with\n               H0: ordi ?B, H1 : algo_sub ?A ?B, H2 : spli ?A _ _ |- _ => forwards [?|?]: IH H1 H2 H0; clear H1; elia\n             end; eauto.\n  - forwards [?|?]: IH H1... all: eauto.\n  - forwards [?|?]: IH H1... all: eauto.\n    Unshelve. all: apply empty.\nQed.\n\nLemma botlike_inv : forall A B,\n    algo_sub (t_and A B) t_bot -> algo_sub A t_bot \\/ algo_sub B t_bot.\nProof with inverts_all_spl; solve_false.\n  introv Sub.\n  inductions Sub...\n  all: auto.\n  all: forwards [?|?]: IHSub1; try reflexivity; try eassumption; elia.\n  all: forwards [?|?]: IHSub2; try reflexivity; try eassumption; elia.\n  all: try solve [left*].\n  all: try solve [right*].\nQed.\n\n(********************************************)\n(*                                          *)\n(*             Ltac auto_inv                *)\n(*                                          *)\n(*  extends choose_unify                    *)\n(*  no solve_false at the end               *)\n(*                                          *)\n(********************************************)\nLtac auto_inv :=\n  repeat try lazymatch goal with\n         | [ H1: algo_sub (t_arrow _ _) (t_arrow _ _) |- _ ] =>\n           try (forwards~ (?&?): algo_sub_arrow_inv H1; clear H1)\n         | [ H1: algo_sub (t_forall _) (t_forall _) |- _ ] =>\n           try (forwards~ : algo_sub_forall_inv H1; clear H1)\n         | [ H1: algo_sub (t_rcd _ _) (t_rcd _ _) |- _ ] =>\n           try (forwards~ (?&?): algo_sub_rcd_inv H1; subst; clear H1)\n         | [ H1: algo_sub ?A (t_and _ _) |- _ ] =>\n           try (forwards~ (?&?): algo_sub_and_inv H1; clear H1)\n      end;\n  repeat try lazymatch goal with\n         | [ H1: algo_sub ?A ?B, H2: spli ?B _ _ |- _ ] =>\n           try (forwards~ (?&?): algo_sub_and_inv H1 H2; clear H1)\n         | [ H1: algo_sub ?A (t_and _ _) |- _ ] =>\n           try (forwards~ (?&?): algo_sub_and_inv H1; clear H1)\n      end;\n  repeat try lazymatch goal with\n         | [ Hord: ordi ?B, H1: algo_sub ?A ?B, H2: spli ?A _ _ |- _ ] =>\n           try (forwards~ [?|?]: algo_sub_andlr_inv H1 H2 Hord; clear H1)\n         | [ Hord: ordi ?B, H1: algo_sub (t_and  _ _)  ?B |- _ ] =>\n           try (forwards~ [?|?]: algo_sub_andlr_inv H1 Hord; clear H1)\n      end;\n  repeat try lazymatch goal with\n         | [ H1: algo_sub ?A ?B, H2: splu ?A _ _ |- _ ] =>\n           try (forwards~ (?&?): algo_sub_or_inv H1 H2; clear H1)\n         | [ H1: algo_sub (t_or _ _) ?B |- _ ] =>\n           try (forwards~ (?&?): algo_sub_or_inv H1; clear H1)\n         end;\n  repeat try lazymatch goal with\n         | [ Hord: ordu ?A, H1: algo_sub ?A ?B, H2: splu ?B _ _ |- _ ] =>\n           try (forwards~ [?|?]: algo_sub_orlr_inv H1 Hord H2; clear H1)\n         | [ Hord: ordu ?A, H1: algo_sub ?A (t_or _ _) |- _ ] =>\n           try (forwards~ [?|?]: algo_sub_orlr_inv H1 Hord; clear H1)\n             end.\n\nLemma trans_via_top : forall A B,\n    algo_sub t_top B -> lc_typ A -> algo_sub A B.\nProof.\n  introv s c.\n  inductions s; eauto; solve_false.\nQed.\n\nLocal Ltac algo_trans_autoIH :=\n  match goal with\n  | [ IH: forall A B : typ, _ , H1: algo_sub ?A  ?B , H2: algo_sub ?B  ?C |- algo_sub ?A  ?C ] =>\n    (applys~ IH H1 H2; elia; auto)\n  | [ IH: forall A B : typ, _ , H1: algo_sub ?A  ?B  |- algo_sub ?A  ?C ] =>\n    (applys~ IH H1; elia; try constructor~)\n  | [ IH: forall A B : typ, _ , H2: algo_sub ?B  ?C |- algo_sub ?A  ?C ] =>\n    (applys~ IH H2; elia; try constructor~)\n  end.\n\nLemma algo_trans : forall A B C, algo_sub A B -> algo_sub B C -> algo_sub A C.\nProof with (solve_false; auto_unify; try (intros Fry; instantiate_cofinites); try eassumption; auto; auto_inv; try solve algo_trans_autoIH).\n  introv s1 s2.\n  indTypSize (size_typ A + size_typ B + size_typ C).\n\n  lets [Hi|(?&?&Hi)]: ordi_or_split C...\n  - lets [Hu|(?&?&Hu)]: ordu_or_split A...\n    + lets [Hi'|(?&?&Hi')]: ordi_or_split B...\n      lets [Hu'|(?&?&Hu')]: ordu_or_split B...\n      lets [Hi''|(?&?&Hi'')]: ordi_or_split A...\n      * (* double ord A B *)\n        inverts s1; auto_unify...\n        ** (* top *) applys~ trans_via_top.\n        ** (* arrow *) inverts~ s2...\n           *** applys ASub_arrow...\n           *** applys ASub_orl...\n           *** applys ASub_orr...\n        ** (* forall *) inverts~ s2...\n           *** applys ASub_forall...\n           *** applys ASub_forall (L `union` L0)...\n           *** applys ASub_orl... algo_trans_autoIH. applys ASub_forall...\n           *** applys ASub_orr... algo_trans_autoIH. applys ASub_forall...\n        ** (* rcd *) inverts~ s2...\n           *** applys ASub_rcd...\n           *** applys ASub_orl...\n           *** applys ASub_orr...\n      * applys ASub_andl...\n      * applys ASub_andr...\n    + lets [Hi'|(?&?&Hi')]: ordi_or_split A...\n      * applys ASub_or Hu...\n      * assert (algo_sub x C)...\n        assert (algo_sub x0 C)...\n  - applys ASub_and Hi...\nQed.\n\n\nLemma algo_sub_distArrU: forall A B C,\n    lc_typ A -> lc_typ B -> lc_typ C -> algo_sub (t_and (t_arrow A C) (t_arrow B C)) (t_arrow (t_or A B) C).\nProof with (try eassumption; elia; eauto 3).\n  introv.\n  indTypSize (size_typ C).\n  lets~ [Hi1|(?&?&Hi1)]: ordi_or_split C.\n  - applys* ASub_and; [ applys* ASub_andl | applys* ASub_andr ].\n  - (* split C x x0 *)\n    forwards Hs1: IH A B x... forwards Hs2: IH A B x0...\n    applys ASub_and...\n    + applys algo_trans Hs1. applys ASub_and. eauto. applys* ASub_andl. applys* ASub_andr.\n    + applys algo_trans Hs2. applys ASub_and. eauto. applys* ASub_andl. applys* ASub_andr.\nQed.\n\n#[local] Hint Resolve algo_sub_distArrU : core.\n\nLemma label_dec : forall l1 l2: l, {l1=l2}+{~l1=l2}.\nProof.\n  repeat decide equality.\nDefined.\n\n(* decidability of subtyping algorithm *)\nTheorem decidability : forall A B,\n    lc_typ A -> lc_typ B -> algo_sub A B \\/ not (algo_sub A B).\nProof with (elia; inverts_all_lc; try eassumption; simpl in *; solve_false; try solve [right; intros HF; auto_inv; inverts HF; simpl in *; solve_false]; eauto).\n  introv.\n  indTypSize (size_typ A + size_typ B).\n  lets [Hi|(?&?&Hi)] : ordi_or_split B. easy.\n  - lets [Hi'|(?&?&Hi')]: ordi_or_split A. easy.\n    + lets [Hu|(?&?&Hu)]: ordu_or_split A. easy.\n      * lets [Hu'|(?&?&Hu')]: ordu_or_split B. easy.\n        ** (* all ordinary *)\n          destruct A; destruct B...\n          *** (* fvar *) case_eq (@eq_dec typevar EqDec_eq_of_X X0 X); intros.\n              **** subst*.\n              **** right... inverts H2...\n          *** (* rcd *) case_eq (@eq_dec l label_dec l5 l0); intros.\n              **** subst*. forwards [IHA1|IHA1] : IH A B...\n              **** right... inverts H0...\n          *** (* arrow *)\n            forwards [IHA1|IHA1] : IH B1 A1...\n            forwards [IHA2|IHA2] : IH A2 B2...\n          *** (* forall *) pick fresh x. specialize (H1 x). specialize (H2 x).\n              forwards [IHA1|IHA1] : IH (A -^ x) (B -^ x)...\n              (* right. intros HF. forwards~: algo_sub_forall_inv HF. *)\n        ** (* spl > B, S-orl/r *)\n          forwards [IHA1|IHA1] : IH A x...\n          forwards [IHA2|IHA2] : IH A x0...\n      * forwards [IHA1|IHA1] : IH x B...\n        forwards [IHA2|IHA2] : IH x0 B...\n    + (* spl < A, S-andl/r *)\n      forwards [IHA1|IHA1] : IH x B...\n      forwards [IHA2|IHA2] : IH x0 B...\n  - (* spl < B, S-and *)\n    forwards [IHA1|IHA1] : IH A x...\n    forwards [IHA2|IHA2] : IH A x0...\n  Unshelve. applys empty.\nDefined.\n\n(* admissible rules *)\nLemma DSub_CovInterL : forall (A C B:typ),\n    lc_typ C -> declarative_subtyping A B ->\n    declarative_subtyping (t_and A C) (t_and B C).\nProof.\n  introv Lc HS.\n  applys~ DSub_InterR.\nQed.\n\nLemma DSub_CovInterR : forall (C A B:typ),\n     lc_typ C -> declarative_subtyping A B ->\n     declarative_subtyping (t_and C A) (t_and C B).\nProof.\n  introv Lc HS.\n  applys~ DSub_InterR.\nQed.\n\nLemma DSub_CovUnionL : forall (A C B:typ),\n     lc_typ C -> declarative_subtyping A B ->\n     declarative_subtyping (t_or A C) (t_or B C).\nProof.\n  introv Lc HS.\n  applys* DSub_UnionL.\nQed.\n\nLemma DSub_CovUnionR : forall (C A B:typ),\n     lc_typ C -> declarative_subtyping A B ->\n     declarative_subtyping (t_or C A) (t_or C B).\nProof.\n  introv Lc HS.\n  applys~ DSub_UnionL.\nQed.\n\nLemma DSub_CovDistIUnionL : forall (A C B:typ),\n    lc_typ A -> lc_typ B -> lc_typ C ->\n    declarative_subtyping (t_and  (t_or A C) (t_or B C) ) (t_or (t_and A B) C).\nProof.\n  introv Lc1 Lc2 Lc3.\n  applys DSub_Trans.\n  applys* DSub_CovDistUInterL.\n  applys DSub_UnionL.\n  - applys DSub_Trans (t_and (t_or B C) A).\n    + applys~ DSub_InterR.\n    + applys DSub_Trans.\n      applys~ DSub_CovDistUInterL.\n      applys~ DSub_UnionL.\n  - applys~ DSub_UnionRR.\nQed.\n\nLemma DSub_CovDistIUnionR : forall (C A B:typ),\n    lc_typ C -> lc_typ A -> lc_typ B ->\n    declarative_subtyping (t_and  (t_or C A) (t_or C B) ) (t_or C (t_and A B) ).\nProof.\n  introv Lc1 Lc2 Lc3.\n  applys DSub_Trans.\n  applys* DSub_CovDistUInterL.\n  applys DSub_UnionL.\n  - applys~ DSub_UnionRL.\n  - applys DSub_Trans (t_and (t_or C B) A).\n    + applys~ DSub_InterR.\n    + applys DSub_Trans.\n      applys~ DSub_CovDistUInterL.\n      applys~ DSub_UnionL.\nQed.\n\nLemma DSub_CovDistUInterR : forall (C A B:typ),\n    lc_typ A -> lc_typ C -> lc_typ B ->\n     declarative_subtyping (t_and C (t_or A B) ) (t_or  (t_and C A) (t_and C B) ).\nProof.\n  introv Lc1 Lc2 Lc3.\n  applys DSub_Trans (t_and (t_or A B) C).\n  - applys~ DSub_InterR.\n  - applys DSub_Trans.\n    applys~ DSub_CovDistUInterL.\n    applys DSub_UnionL.\n    + applys~ DSub_UnionRL.\n    + applys~ DSub_UnionRR.\nQed.\n\n#[export] Hint Resolve DSub_CovInterL DSub_CovInterR DSub_CovUnionL DSub_CovUnionR DSub_CovDistIUnionL DSub_CovDistIUnionR DSub_CovDistUInterR : core.\n\nLemma dsub_splu: forall A B C,\n    splu A B C -> declarative_subtyping B A /\\ declarative_subtyping C A.\nProof.\n  introv H.\n  induction H; try solve [intuition; eauto 3].\n  - split; applys DSub_CovAll; intros X Fry; instantiate_cofinites_with X;\n    eauto.\nQed.\n\nLemma dsub_spli: forall A B C,\n    spli A B C -> declarative_subtyping A B /\\ declarative_subtyping A C.\nProof.\n  introv H.\n  induction H; try forwards: dsub_splu H0;  try solve [intuition; eauto 3].\n  - split; applys DSub_CovAll; intros X Fry; instantiate_cofinites_with X;\n    eauto.\nQed.\n\nLemma dsub_symm_and: forall A B,\n    lc_typ A -> lc_typ B -> declarative_subtyping (t_and A B) (t_and B A).\nProof.\n  intros. applys~ DSub_InterR.\nQed.\n\nLemma dsub_symm_or: forall A B,\n    lc_typ A -> lc_typ B -> declarative_subtyping (t_or A B) (t_or B A).\nProof.\n  intros. applys~ DSub_UnionL.\nQed.\n\nLemma dsub_or: forall A B C,\n    splu A B C -> declarative_subtyping A (t_or B C).\nProof.\n  introv H.\n  induction H.\n  - eauto.\n  - applys DSub_Trans. 2: { applys~ DSub_CovDistUInterL. } eauto.\n  - applys DSub_Trans. 2: { applys~ DSub_CovDistUInterR. } eauto.\n  - applys DSub_Trans. applys DSub_CovAll (t_or A1 A2).\n    intros X Fry. unfolds open_typ_wrt_typ. simpl. auto.\n    applys~ DSub_CovDistUAll.\n  - applys DSub_Trans. applys~ DSub_CovIn (t_or A1 A2).\n    applys~ DSub_CovDistUIn.\nQed.\n\nLemma dsub_and: forall A B C,\n    spli A B C -> declarative_subtyping (t_and B C) A.\nProof.\n  introv H.\n  induction H.\n  - eauto.\n  - applys DSub_Trans. applys~ DSub_CovDistIUnionL. applys* DSub_UnionL.\n  - applys DSub_Trans. applys~ DSub_CovDistIUnionR. applys* DSub_UnionL.\n  - applys DSub_Trans. applys~ DSub_CovDistIArr. eauto.\n  - applys DSub_Trans. applys~ DSub_FunDistI. applys~ DSub_FunCon.\n    eauto using dsub_or.\n  - applys DSub_Trans.\n    2: { applys DSub_CovAll (t_and A1 A2).\n         intros X Fry. unfolds open_typ_wrt_typ. simpl. auto. }\n    applys~ DSub_CovDistIAll.\n  - applys DSub_Trans.\n    2: { applys~ DSub_CovIn (t_and A1 A2). }\n    applys~ DSub_CovDistIIn.\nQed.\n\n#[local] Hint Resolve dsub_and dsub_or : core.\n\nLemma asub_symm_and: forall A B,\n    lc_typ A -> lc_typ B -> algo_sub (t_and A B) (t_and B A).\nProof.\n  intros. applys~ ASub_and.\nQed.\n\nLemma asub_symm_or: forall A B,\n    lc_typ A -> lc_typ B -> algo_sub (t_or A B) (t_or B A).\nProof.\n  intros. applys~ ASub_or.\nQed.\n\nLtac split_inter_constructors :=\n  applys* SpI_and + applys* SpI_orl +\n  applys* SpI_in + applys* SpI_arrow + applys* SpI_orl +\n  (applys* SpI_forall; intros; autorewrite with open; auto).\nLtac split_union_constructors :=\n  applys* SpU_or + applys* SpU_andl + applys* SpU_in +\n  (applys* SpU_forall; intros; autorewrite with open; auto).\n\nLtac swap_or_r := applys algo_trans; [ | applys asub_symm_or ].\nLtac swap_and_l := applys algo_trans; [ (applys asub_symm_and) | ].\nLtac split_r := applys ASub_and; try split_inter_constructors.\nLtac split_l := applys ASub_or; try split_union_constructors.\nLtac use_left_l := applys ASub_andl; try split_inter_constructors.\nLtac use_right_l := applys ASub_andr; try split_inter_constructors.\nLtac use_left_r := applys ASub_orl; try split_union_constructors.\nLtac use_right_r := applys ASub_orr; try split_union_constructors.\n\nLtac match_or := split_l; [ use_left_r | use_right_r].\nLtac match_and := split_r; [ use_left_l | use_right_l].\nLtac match_or_rev := split_l; [ use_right_r |  use_left_r ].\nLtac match_and_rev := split_r; [ use_right_l | use_left_l ].\nLtac swap_or_l := applys algo_trans; [ applys asub_symm_or | ].\nLtac swap_and_r := applys algo_trans; [ | (applys asub_symm_and) ].\n\n\nTheorem dsub2asub: forall A B,\n    declarative_subtyping A B <-> algo_sub A B.\nProof with (simpl in *; try applys SpI_and; try applys SpU_or; try eassumption; eauto 4).\n  split; introv H.\n  - induction H; eauto.\n    all: try solve [ match goal with\n        | H1: algo_sub ?A ?B, H2: algo_sub ?B ?C |- algo_sub ?A ?C => applys algo_trans H1 H2\n        | |- algo_sub (t_and _ _) (t_and _ _) => match_and; auto\n        | |- algo_sub (t_and (t_or _ _) (t_or _ _)) (t_or (t_and _ _) _) =>\n          match_and; auto\n        | |- algo_sub (t_and (t_or _ _) (t_or _ _)) (t_or _ (t_and _ _)) =>\n          swap_or_r; auto; match_and; match_or_rev; auto\n\n        | |- algo_sub _ (t_or _ _) => match_or; try applys ASub_refl; auto\n        | |- algo_sub (t_or _ _) (_ (t_or _ _)) => match_or; auto\n        | |- algo_sub (t_and (t_or _ _) _) (t_or (t_and _ _) (t_and _ _)) =>\n          match_or; auto\n        | |- algo_sub (t_and _ (t_or _ _)) (t_or (t_and _ _) (t_and _ _)) =>\n          swap_and_l; auto; match_or; match_and_rev; auto\n\n        | |- algo_sub (t_and _ _) (_ (t_and _ _)) => match_and; auto\n        | |- algo_sub (t_or _ _) (_ _ (t_or _ _)) => match_or; auto\n                     end ].\n    Unshelve. all: applys empty.\n  - induction H; auto.\n    + (* arrow *) applys DSub_Trans. applys~ DSub_CovArr IHalgo_sub2. applys~ DSub_FunCon IHalgo_sub1.\n    + (* forall *) applys* DSub_CovAll.\n    + (* and *) applys DSub_Trans (t_and B1 B2)...\n    + (* andl *) forwards (?&?): dsub_spli H. applys DSub_Trans IHalgo_sub...\n    + (* andr *) forwards (?&?): dsub_spli H. applys DSub_Trans IHalgo_sub...\n    + (* or *) applys DSub_Trans (t_or A1 A2)...\n    + (* orl *) forwards (?&?): dsub_splu H. applys DSub_Trans IHalgo_sub...\n    + (* orr *) forwards (?&?): dsub_splu H. applys DSub_Trans IHalgo_sub...\nQed.\n\n\nLemma sub_dec : forall A B,\n    lc_typ A -> lc_typ B -> declarative_subtyping A B \\/ ~ (declarative_subtyping A B).\nProof.\n  intros.\n  forwards~ [?|?]: decidability A B.\n  left. applys~ dsub2asub.\n  right. intro HF. apply dsub2asub in HF. eauto.\nQed.\n\n\n#[export] Hint Extern 1 (lc_typ (t_forall _)) =>\nlet Y:= fresh \"Y\" in pick_fresh Y; instantiate_cofinites_with Y; applys lc_t_forall_exists Y : core.\n\n\nLtac inv_arrow :=\n  repeat match goal with\n         | H: algo_sub (t_arrow _ _) (t_arrow _ _) |- _ => forwards (?&?): algo_sub_arrow_inv H; clear H\n         | H: declarative_subtyping (t_arrow _ _) (t_arrow _ _) |- _ => apply dsub2asub in H\n         end.\n\nLtac inv_forall :=\n  repeat match goal with\n         | H: algo_sub (t_forall _) (t_forall _) |- _ => forwards : algo_sub_forall_inv H; clear H\n         | H: declarative_subtyping (t_forall _) (t_forall _) |- _ => apply dsub2asub in H\n         end.\n\n\nLtac convert2asub :=\n  repeat match goal with\n           H: declarative_subtyping _ _ |- _ => apply dsub2asub in H\n           | |- declarative_subtyping _ _ => apply dsub2asub\n         end.\n\nLtac convert2dsub :=\n  repeat match goal with\n           | H: algo_sub _ _ |- _ => apply dsub2asub in H\n           | |- algo_sub _ _ => apply dsub2asub\n         end.\n\n(* Some impossible cases *)\nLemma sub_inv_1 : forall X B D,\n    algo_sub (t_tvar_f X) (t_arrow B D) -> False.\nProof.\n  introv H. indTypSize (size_typ (t_arrow B D)).\n  inverts H; solve_false.\n  all: inverts H0; applys IH; try eassumption; elia.\nQed.\n\nLemma sub_inv_2 : forall l5 A B D,\n    algo_sub (t_rcd l5 A) (t_arrow B D) -> False.\nProof.\n  introv H. indTypSize (size_typ (t_rcd l5 A) + size_typ (t_arrow B D)).\n  inverts H; solve_false.\n  all: inverts H0; applys IH; try eassumption; elia.\nQed.\n\nLemma sub_inv_3 : forall B D,\n    algo_sub t_top (t_arrow B D) -> False.\nProof.\n  introv H. indTypSize (size_typ (t_arrow B D)).\n  inverts H; solve_false.\n  all: inverts H0; applys IH; try eassumption; elia.\nQed.\n\nLemma sub_inv_4 : forall A B D,\n    algo_sub (t_forall A) (t_arrow B D) -> False.\nProof.\n  introv H. indTypSize (size_typ (t_forall A) + size_typ (t_arrow B D)).\n  inverts H; solve_false.\n  all: inverts H0; applys IH; try eassumption; elia.\nQed.\n\nLemma sub_inv_5 : forall X B,\n    algo_sub (t_tvar_f X) (t_forall B) -> False.\nProof.\n  introv H. indTypSize (size_typ (t_forall B)).\n  inverts H; solve_false.\n  all: inverts H0; applys IH; try eassumption; elia.\nQed.\n\nLemma sub_inv_6 : forall l5 A B,\n    algo_sub (t_rcd l5 A) (t_forall B) -> False.\nProof.\n  introv H. indTypSize (size_typ (t_rcd l5 A) + size_typ (t_forall B)).\n  inverts H; solve_false.\n  all: inverts H0; applys IH; try eassumption; elia.\nQed.\n\nLemma sub_inv_7 : forall B,\n    algo_sub t_top (t_forall B) -> False.\nProof.\n  introv H. indTypSize (size_typ (t_forall B)).\n  inverts H; solve_false.\n  all: inverts H0; applys IH; try eassumption; elia.\nQed.\n\nLemma sub_inv_8 : forall A B D,\n    algo_sub (t_arrow B D) (t_forall A) -> False.\nProof.\n  introv H. indTypSize (size_typ (t_forall A) + size_typ (t_arrow B D)).\n  inverts H; solve_false.\n  all: inverts H0; applys IH; try eassumption; elia.\nQed.\n\nLemma sub_inv_9 : forall l5 A X,\n    algo_sub (t_rcd l5 A) (t_tvar_f X) -> False.\nProof.\n  introv H.\n  indTypSize (size_typ (t_rcd l5 A)).\n  inverts H; solve_false.\n  all: inverts H0; applys IH; try eassumption; elia.\nQed.\n\n#[export] Hint Extern 1 False => lazymatch goal with\n   | H: algo_sub (t_tvar_f _) (t_arrow _ _) |- _ => applys sub_inv_1 H\n   | H: algo_sub (t_rcd _ _) (t_arrow _ _) |- _ => applys sub_inv_2 H\n   | H: algo_sub t_top (t_arrow _ _) |- _ => applys sub_inv_3 H\n   | H: algo_sub (t_forall _) (t_arrow _ _) |- _ => applys sub_inv_4 H\n   | H: algo_sub (t_tvar_f _) (t_forall _) |- _ => applys sub_inv_5 H\n   | H: algo_sub (t_rcd _ _) (t_forall _) |- _ => applys sub_inv_6 H\n   | H: algo_sub t_top (t_forall _) |- _ => applys sub_inv_7 H\n   | H: algo_sub (t_arrow _ _) (t_forall _) |- _ => applys sub_inv_8 H\n   | H: algo_sub (t_rcd _ _) (t_tvar_f _) |- _ => applys sub_inv_9 H\n                            end : FalseHd.\n\nLemma sub_inv_10 : forall A B D l,\n    algo_sub (t_arrow B D) (t_rcd l A) -> False.\nProof.\n  introv H.\n  indTypSize (size_typ (t_rcd l A) + size_typ (t_arrow B D)).\n  inverts H; solve_false.\n  all: inverts H0; applys IH; try eassumption; elia.\nQed.\nLemma sub_inv_11 : forall A B l,\n    algo_sub (t_forall B) (t_rcd l A) -> False.\nProof.\n  introv H.\n  indTypSize (size_typ (t_rcd l A) + size_typ (t_forall B)).\n  inverts H; solve_false.\n  all: inverts H0; applys IH; try eassumption; elia.\nQed.\n\nLemma sub_inv_12 : forall l A,\n    algo_sub t_top (t_rcd l A) -> False.\nProof.\n  introv H. indTypSize (size_typ (t_rcd l A)).\n  inverts H; solve_false.\n  all: inverts H0; applys IH; try eassumption; elia.\nQed.\n\n#[export] Hint Immediate sub_inv_10 sub_inv_11 sub_inv_12 : FalseHd.\n\nLemma sub_inv_13 :\n    algo_sub t_top t_bot -> False.\nProof.\n  introv H.\n  inverts H; solve_false.\nQed.\n\nLemma sub_inv_14 : forall A B,\n    algo_sub (t_arrow A B) t_bot -> False.\nProof.\n  introv H.\n  inductions H; inverts_all_spl; solve_false.\nQed.\n\nLemma sub_inv_15 : forall l A,\n    algo_sub (t_rcd l A) t_bot -> False.\nProof.\n  introv H.\n  inductions H; inverts_all_spl; solve_false.\nQed.\n\nLemma sub_inv_16 : forall A,\n    algo_sub (t_forall A) t_bot -> False.\nProof.\n  introv H.\n  inductions H; inverts_all_spl; solve_false.\nQed.\n\n#[export] Hint Immediate sub_inv_13 sub_inv_14 sub_inv_15 sub_inv_16 : FalseHd.\n\n(******** nondeterministic split & alternative subtyping definition *******)\n\nLemma new_splu_decrease_size: forall A B C,\n    new_splu A B C -> size_typ B < size_typ A /\\ size_typ C < size_typ A.\nProof with (pose proof (size_typ_min); simpl in *; try lia).\n  introv H.\n  induction H; simpl in *; eauto...\n  pick fresh X. forwards* (?&?): H0.\n  rewrite 2 size_typ_open_typ_wrt_typ_var in H3.\n  rewrite 2 size_typ_open_typ_wrt_typ_var in H2.\n  eauto...\nQed.\n\nLemma new_spli_decrease_size: forall A B C,\n    new_spli A B C -> size_typ B < size_typ A /\\ size_typ C < size_typ A.\nProof with (pose proof (size_typ_min); simpl in *; try lia).\n  introv H.\n  induction H; simpl in *; eauto...\n  - forwards (?&?): new_splu_decrease_size H0...\n  - pick fresh X. forwards* (?&?): H0.\n    rewrite 2 size_typ_open_typ_wrt_typ_var in H3.\n    rewrite 2 size_typ_open_typ_wrt_typ_var in H2.\n    eauto...\nQed.\n\nLtac new_spl_size :=\n  repeat match goal with\n         | [ H: new_splu _ _ _ |- _ ] =>\n           ( lets (?&?): new_splu_decrease_size H; clear H)\n         | [ H: new_spli _ _ _ |- _ ] =>\n           ( lets (?&?): new_spli_decrease_size H; clear H)\n         end.\n\nLtac new_elia :=\n  try solve [pose proof (size_typ_min);\n             let x := fresh \"x\" in\n             pick fresh x; instantiate_cofinites_with x; (* forall x, x `notin` .. -> spli .. *)\n             spl_size; new_spl_size; simpl in *; simpl;\n             try repeat rewrite size_typ_open_typ_wrt_typ_var in *; (* spl A-^X ... *)\n             try lia].\n\n(******* relates to original definitions ********)\n\nLemma splu2nsplu : forall A B1 B2,\n    splu A B1 B2 -> new_splu A B1 B2.\nProof.\n  introv H. induction* H.\nQed.\n\nLemma spli2nspli : forall A B1 B2,\n    spli A B1 B2 -> new_spli A B1 B2.\nProof.\n  introv H. induction~ H.\n  - apply splu2nsplu in H0. eauto.\n  - econstructor. intros. instantiate_cofinites. easy.\nQed.\n\n#[export] Hint Resolve splu2nsplu spli2nspli : core.\n\nNotation \"A <:: B\" := (algo_sub A B) (at level 15).\nNotation \"A ~~ B\" := ((algo_sub A B) /\\ (algo_sub B A)) (at level 15).\nNotation \"A & B\" := (t_and A B) (at level 10).\nNotation \"A | B\" := (t_or A B) (at level 11).\n\nLemma nsplu2splu : forall A B1 B2,\n    new_splu A B1 B2 ->\n    exists C1 C2, splu A C1 C2.\nProof with destruct_conj; eauto.\n  introv H. induction H...\n  - destruct* (ordu_or_split A)...\n  - pick fresh Y for (L `union` [[A]]). instantiate_cofinites. exists.\n    applys splu_forall_exists Y...\nQed.\n\nLemma nspli2spli : forall A B1 B2,\n    new_spli A B1 B2 ->\n    exists C1 C2, spli A C1 C2.\nProof with destruct_conj; eauto.\n  introv H. induction H...\n  - destruct* (ordi_or_split A)...\n  - destruct* (ordi_or_split B)...\n    + apply nsplu2splu in H0...\n  - pick fresh Y for (L `union` [[A]]). instantiate_cofinites. exists.\n    applys spli_forall_exists Y...\nQed.\n\nLtac gets_all_lc :=\n  repeat match goal with\n         | H: ordi _ |- _ => lets: ordi_lc H; assumption\n         | H: ordu _ |- _ => lets: ordi_lc H; assumption\n         | H: splu _ _ _ |- _ => lets (?&?&?): splu_lc H; assumption\n         | H: spli _ _ _ |- _ => lets (?&?&?): spli_lc H; assumption\n         | H: algo_sub _ _ |- _ => lets (?&?): algo_sub_lc H; assumption\n         end.\n\nLemma open_into_var : forall X Y, t_tvar_f Y -^ X = t_tvar_f Y.\nProof. eauto. Qed.\n\n#[export] Hint Rewrite open_into_var : open.\n\nLemma nsplu_isomorphic : forall A B1 B2,\n    new_splu A B1 B2 -> A ~~ B1|B2.\nProof with try applys ASub_refl; try match goal with |- lc_typ _ => eauto with lngen end.\n  introv H. split; induction~ H.\n  - split_r.\n    + swap_or_r... split_r.\n      swap_or_r... applys* ASub_andl. applys* ASub_andr.\n    + applys* ASub_orl.\n  - swap_and_l... split_r.\n    + applys* ASub_orl.\n    + swap_or_r... split_r. applys* ASub_andr.\n      swap_or_r... applys* ASub_andl.\n  - applys algo_trans; [ | applys dsub2asub; applys DSub_CovDistUAll ]...\n    econstructor. intros. instantiate_cofinites.\n    applys algo_trans H0. autorewrite with open.\n    auto.\n  - applys algo_trans; [ | applys dsub2asub; applys DSub_CovDistUIn ]...\n    econstructor. easy.\n  - split_l.\n    + split_r.\n      * use_left_l. applys algo_trans IHnew_splu. use_left_r...\n      * use_right_l...\n    + split_r.\n      * use_left_l. applys algo_trans IHnew_splu. use_right_r...\n      * use_right_l...\n  - split_l.\n    + split_r.\n      * use_left_l...\n      * applys algo_trans IHnew_splu. use_left_r... use_right_l...\n    + split_r.\n      * use_left_l...\n      * applys algo_trans IHnew_splu. use_right_r... use_right_l...\n  - applys algo_trans (t_forall (A1|A2))...\n    + split_l; auto;\n      applys ASub_forall; intros; instantiate_cofinites;\n       autorewrite with open...\n      use_left_r... use_right_r...\n    + applys ASub_forall; intros; instantiate_cofinites;\n        autorewrite with open... easy.\n  - applys algo_trans (t_rcd l5 (A1|A2))...\n    + split_l; applys ASub_rcd. use_left_r... use_right_r...\n    + applys ASub_rcd. easy.\nQed.\n\nLemma nspli_isomorphic : forall A B1 B2,\n    new_spli A B1 B2 -> A ~~ B1&B2.\nProof with eauto using ASub_refl.\n  introv Hs. induction Hs.\n  - split*.\n  - destruct IHHs.\n    split; applys algo_trans ((A1&A2)|B).\n    + match_or...\n    + match_and...\n    + match_and...\n    + match_or...\n  - destruct IHHs. split.\n    + applys algo_trans (A|B1&B2).\n      * match_or...\n      * swap_or_l... split_l.\n        use_right_r. swap_and_r...\n        use_right_r.\n        match_and_rev...\n        use_left_r. swap_and_r... use_left_r.\n        split_r...\n    + applys algo_trans (A|B1&B2).\n      * swap_or_r...\n        split_l. swap_and_l... split_l.\n        use_right_r. use_left_l...\n        use_right_l. use_right_r...\n        swap_and_l... split_l.\n        use_left_l. use_right_r...\n        use_left_r. match_and_rev...\n      * match_or...\n  - destruct IHHs. split; applys algo_trans (t_arrow A (B1&B2)).\n    + econstructor...\n    + match_and...\n    + split_r. eauto.\n      use_left_l...\n      use_right_l...\n    + econstructor...\n  - apply nsplu_isomorphic in H0.\n    destruct H0. split; applys algo_trans (t_arrow (A1|A2) B).\n    + econstructor...\n    + split_r; constructor~.\n    + convert2dsub. applys* DSub_FunDistI.\n    + constructor~.\n  - split; applys algo_trans (t_forall (A1&A2)).\n    + econstructor. intros. instantiate_cofinites. autorewrite with open. easy.\n    + split_r; auto; econstructor; intros; autorewrite with open. use_left_l... use_right_l...\n    + convert2dsub. applys~ DSub_CovDistIAll.\n    + econstructor. intros. instantiate_cofinites. autorewrite with open. easy.\n  - destruct IHHs. split; applys algo_trans (t_rcd l5 (A1&A2)).\n    + econstructor...\n    + match_and...\n    + split_r. eauto.\n      use_left_l...\n      use_right_l...\n    + econstructor...\nQed.\n\nLemma asub2nsub : forall A B,\n    algo_sub A B <-> new_sub A B.\nProof with new_elia; try easy.\n  introv; split; intro H.\n  - induction H.\n    all: now eauto.\n  - indTypSize (size_typ A + size_typ B). inverts H.\n    1-3: eauto.\n    1,3-9: repeat match goal with\n                | H: new_sub _ _ |- _ => forwards~ : IH H; new_elia; clear H\n                  end.\n    + (* and *) applys~ algo_trans (B1&B2).\n      forwards~ (?&?): nspli_isomorphic H0.\n    + (* andl *) applys~ algo_trans (A1&A2).\n      forwards~ (?&?): nspli_isomorphic H0.\n    + (* andr *) applys~ algo_trans (A1&A2). forwards~ (?&?): nspli_isomorphic H0.\n    + (* or *) applys~ algo_trans (A1|A2).\n      forwards~ (?&?): nsplu_isomorphic H0.\n    + (* orl *) applys~ algo_trans (B1|B2).\n      forwards~ (?&?): nsplu_isomorphic H0.\n    + (* orr *) applys~ algo_trans (B1|B2).\n      forwards~ (?&?): nsplu_isomorphic H0.\n    + applys ASub_forall (L `union` [[A0]] `union` [[B0]]). intros X Fry.\n      instantiate_cofinites. applys~ IH; elia.\nQed.\n\n(*********************** binding ********************************)\n\nLemma typsubst_typ_splu : forall A B C X U,\n    new_splu A B C -> lc_typ U ->\n    new_splu ([X ~~> U] A) ([X ~~> U] B) ([X ~~> U] C).\nProof with eauto with lngen.\n  introv spl lc. induction spl; simpl.\n  all: auto...\n  -\n    applys NSpU_forall (L `union` [[A]] `union` [[A1]] `union` [[A2]] `union` {{X}}).\n    intros Y Fry. instantiate_cofinites_with Y.\n    rewrite 3 typsubst_typ_open_typ_wrt_typ in H0...\n    rewrite (typsubst_typ_fresh_eq (t_tvar_f Y) U X) in H0...\nQed.\n\nLemma typsubst_typ_spli : forall A B C X U,\n    new_spli A B C -> lc_typ U ->\n    new_spli ([X ~~> U] A) ([X ~~> U] B) ([X ~~> U] C).\nProof with eauto using typsubst_typ_splu with lngen.\n  introv spl lc. induction spl; simpl.\n  1-4, 7: auto...\n  - applys NSpI_arrowUnion...\n  - applys NSpI_forall (L `union` [[A]] `union` [[A1]] `union` [[A2]] `union` {{X}}).\n    intros Y Fry. instantiate_cofinites_with Y.\n    rewrite 3 typsubst_typ_open_typ_wrt_typ in H0...\n    rewrite (typsubst_typ_fresh_eq (t_tvar_f Y) U X) in H0...\nQed.\n\nLemma typsubst_typ_new_sub : forall A B C X,\n  new_sub A B -> lc_typ C ->\n  new_sub ([X ~~> C] A) ([X ~~> C] B).\nProof with (simpl in *; eauto with lngen; eauto using typsubst_typ_lc_typ, typsubst_typ_spli, typsubst_typ_splu).\n  introv s lc.\n  indTypSize (size_typ A + size_typ B).\n  inverts s; simpl.\n  - applys NSub_refl...\n  - applys~ NSub_top...\n  - applys~ NSub_bot...\n  - applys~ NSub_arrow... all: applys IH; elia...\n  - applys~ NSub_forall (L `union` {{X}} `union` [[C]])...\n    intros Y HF. instantiate_cofinites_with Y.\n    rewrite 2 typsubst_typ_open_typ_wrt_typ_var...\n    applys IH; elia...\n  - applys~ NSub_rcd... applys IH; new_elia...\n  - applys~ NSub_and. applys typsubst_typ_spli H...\n    all: applys IH; new_elia...\n  - applys~ NSub_andl. applys typsubst_typ_spli H...\n    all: applys IH; new_elia...\n  - applys~ NSub_andr. applys typsubst_typ_spli H...\n    all: applys IH; new_elia...\n  - applys~ NSub_or. applys typsubst_typ_splu H...\n    all: applys IH; new_elia...\n  - applys~ NSub_orl. applys typsubst_typ_splu H...\n    all: applys IH; new_elia...\n  - applys~ NSub_orr. applys typsubst_typ_splu H...\n    all: applys IH; new_elia...\nQed.\n\n\nLemma typsubst_typ_algo_sub : forall A B C X,\n  algo_sub A B -> lc_typ C ->\n  algo_sub ([X ~~> C] A) ([X ~~> C] B).\nProof.\n  intros.\n  apply asub2nsub. apply asub2nsub in H.\n  applys~ typsubst_typ_new_sub.\nQed.\n\nLtac solve_dsub := repeat match goal with\n                          | H: declarative_subtyping _ _ |- _ => apply dsub2asub in H\n                          | |- declarative_subtyping _ _ => apply dsub2asub\n                          end; try solve (solve_algo_sub).\n\nLemma nsub_splitu : forall A B B1 B2,\n    ~ declarative_subtyping B A -> splu B B1 B2 -> lc_typ A ->\n    ~ declarative_subtyping B1 A \\/ ~ declarative_subtyping B2 A.\nProof.\n  introv HN HS HL.\n  destruct (sub_dec B1 A); eauto.\n  destruct (sub_dec B2 A); eauto.\n  exfalso. applys HN.\n  apply dsub2asub in H, H0. applys~ dsub2asub.\nQed.\n\n\n(*****************************************************************************)\nDefinition iso A B := A <: B /\\ B <: A.\n\nNotation \"A ~= B\"        := (iso A B)\n                              (at level 65, B at next level, no associativity) : type_scope.\n\nLemma iso_subst_sub : forall A B C,\n    A <: B -> A ~= C -> C <: B.\nProof.\n  introv H1 (H2&H3). convert2asub. applys algo_trans; try eassumption.\nQed.\n\nLemma iso_lc : forall A B,\n    A ~= B -> lc_typ A /\\ lc_typ B.\nProof.\n  introv (H1&H2). eauto.\nQed.\n\nLtac iso_inverts_all_lc := repeat lazymatch goal with\n                             | H: _ ~= _ |- _ => forwards (?&?): iso_lc H; clear H\n                             end;\n                           inverts_all_lc.\n\nLemma iso_symm : forall A B,\n    A ~= B -> B ~= A.\nProof.\n  introv (H1&H2).\n  split~.\nQed.\n\nLemma iso_refl : forall A,\n    lc_typ A -> A ~= A.\nProof.\n  introv H. induction H; split.\n  all: applys~ DSub_Refl.\nQed.\n\nLemma iso_trans : forall A B C,\n    A ~= B -> B ~= C -> A ~= C.\nProof. introv (?&?) (?&?).\n       split; applys DSub_Trans; eassumption.\nQed.\n\nLemma iso_or : forall A B C,\n    A ~= B -> A ~= C -> A ~= B|C.\nProof.\n  introv (H1&H2) (H3&H4).\n  all: split; constructor~.\nQed.\nLemma iso_or_2 : forall A B C,\n    A ~= C -> B ~= C -> A|B ~= C.\nProof.\n  introv H1 H2. eauto using iso_or, iso_symm.\nQed.\n\nLemma iso_or_match : forall A1 A2 B1 B2,\n    A1 ~= B1 -> A2 ~= B2 -> A1|A2 ~= B1|B2.\nProof.\n  introv (H1&H2) (H3&H4).\n  all: split; convert2asub; match_or; auto.\nQed.\n\nLemma iso_and : forall A B C,\n    A ~= B -> A ~= C -> A ~= B&C.\nProof.\n  introv (H1&H2) (H3&H4).\n  all: split; constructor~.\nQed.\n\nLemma iso_and_match : forall A1 A2 B1 B2,\n    A1 ~= B1 -> A2 ~= B2 -> A1&A2 ~= B1&B2.\nProof.\n  introv (H1&H2) (H3&H4).\n  all: split; convert2asub; match_and; auto.\nQed.\n\nLemma iso_shuffle : forall A B C D,\n    lc_typ A -> lc_typ B -> lc_typ C -> lc_typ D ->\n    (A | B) | (C | D) ~= (A | C) | (B | D).\nProof.\n  intros. split.\n  - applys DSub_UnionL.\n    convert2asub; match_or; applys* ASub_orl.\n    convert2asub; match_or; applys* ASub_orr.\n  - applys DSub_UnionL.\n    convert2asub; match_or; applys* ASub_orl.\n    convert2asub; match_or; applys* ASub_orr.\nQed.\n\nLemma iso_dist_1 : forall A B C,\n    lc_typ A -> lc_typ B -> lc_typ C ->\n    (A | B) & C ~= (A & C) | (B & C).\nProof.\n  intros. split.\n  all: convert2asub; match_or; eauto.\nQed.\n\nLemma iso_dist_2 : forall A B C,\n    lc_typ A -> lc_typ B -> lc_typ C ->\n    C & (A | B) ~= (C & A) | (C & B).\nProof with try solve [eassumption || constructor; eassumption].\n  intros. split.\n  - convert2asub. swap_and_l...\n    match_or; swap_and_l; eauto.\n  - convert2asub. swap_and_r...\n    match_or; swap_and_r; eauto.\nQed.\n\nLemma iso_absorb_1 : forall A B,\n    lc_typ A -> lc_typ B -> A ~= A | A & B.\nProof.\n  introv HA HB. splits.\n  - applys* DSub_UnionRL.\n  - applys* DSub_UnionL.\nQed.\n\nLemma iso_absorb_2 : forall A B,\n    lc_typ A -> lc_typ B -> A ~= A & B | A.\nProof.\n  introv HA HB. splits.\n  - applys* DSub_UnionRR.\n  - applys* DSub_UnionL.\nQed.\n\nLemma iso_absorb_3 : forall A B,\n    lc_typ A -> lc_typ B -> A ~= A | B & A.\nProof.\n  introv HA HB. splits.\n  - applys* DSub_UnionRL.\n  - applys* DSub_UnionL.\nQed.\n\nLemma iso_absorb_4 : forall A B,\n    lc_typ A -> lc_typ B -> A ~= B & A | A.\nProof.\n  introv HA HB. splits.\n  - applys* DSub_UnionRR.\n  - applys* DSub_UnionL.\nQed.\n\nLemma iso_dup_1 : forall A B C,\n    A ~= B -> A ~= C -> A ~= B | C.\nProof.\n  introv (?&?) (?&?). splits.\n  - applys~ DSub_UnionRL.\n  - applys* DSub_UnionL.\nQed.\n\n#[export] Hint Resolve iso_refl : core.\n\n#[export] Hint Immediate iso_symm iso_trans iso_or iso_or_2 iso_and\n  iso_or_match iso_and_match : core.\n\nLemma iso_asub2dsub : forall A B,\n    A ~~ B <-> A ~= B.\nProof.\n  split; intros (H1&H2); split; convert2dsub; easy.\nQed.\n\nLemma new_splu_iso : forall A B C,\n    new_splu A B C -> A ~= B | C.\nProof.\n  introv H. applys iso_asub2dsub.\n  applys* nsplu_isomorphic.\nQed.\n\nLemma splu_iso : forall A B C,\n    splu A B C -> A ~= B | C.\nProof.\n  introv H. applys* new_splu_iso.\nQed.\n\n#[export] Hint Resolve new_splu_iso splu_iso : core.\n", "meta": {"author": "XSnow", "repo": "bowtie_coq", "sha": "9e963e7afbd5da832534c1c40cbcf5dd28e69ee7", "save_path": "github-repos/coq/XSnow-bowtie_coq", "path": "github-repos/coq/XSnow-bowtie_coq/bowtie_coq-9e963e7afbd5da832534c1c40cbcf5dd28e69ee7/coq/DistSubtyping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.2946826820682014}}
{"text": "Require Export Task.driver_requires.\nImport ListNotations.\nImport FloatIO.\nImport DScopeNotations.\nOpen Scope D_scope.\n\n(* Inductive type used to name state variables. *)\nInductive stateVar : Set := \n| SvT\n| SvX\n| SvXD\n| SvXDD\n| SvZ\n| SvZD\n| SvTHETA\n| SvTHETA_DOT\n| SvTHETA_DOT_CMD\n| SvQ_S\n| SvQ_S_MEAS\n| SvVELOCITY\n| SvGUIDANCE_GAIN\n| SvTHETA_IC_DG\n| SvT_STOP\n| SvDT\n| SvDT_MAX\n| SvDT_MIN\n| SvDT_PRINT.\n\nLemma state_var_eq: forall (r1 r2: stateVar), {r1 = r2} + {r1 <> r2}.\nProof. decide equality. Defined.\nGlobal Opaque state_var_eq.\n\n\nDefinition svIndex (Sv: stateVar) : positive :=\n  match Sv with\n  | SvT => 1\n  | SvX => 2\n  | SvXD => 3\n  | SvXDD => 4\n  | SvZ => 5\n  | SvZD => 6\n  | SvTHETA => 7\n  | SvTHETA_DOT => 8\n  | SvTHETA_DOT_CMD => 9\n  | SvQ_S => 10\n  | SvQ_S_MEAS => 11\n  | SvVELOCITY => 12\n  | SvGUIDANCE_GAIN => 13\n  | SvTHETA_IC_DG => 14\n  | SvT_STOP => 15\n  | SvDT => 16\n  | SvDT_MAX => 17\n  | SvDT_MIN => 18\n  | SvDT_PRINT => 19\n  end.\n\n\nDefinition svStrList :=\n  [\n    (SvT, \"T\");\n    (SvX, \"X\");\n    (SvXD, \"XD\");\n    (SvXDD, \"XDD\");\n    (SvZ, \"Z\");\n    (SvZD, \"ZD\");\n    (SvTHETA, \"THETA\");\n    (SvTHETA_DOT, \"THETA_DOT\");\n    (SvTHETA_DOT_CMD, \"THETA_DOT_CMD\");\n    (SvQ_S, \"Q_S\");\n    (SvQ_S_MEAS, \"Q_S_MEAS\");\n    (SvVELOCITY, \"VELOCITY\");\n    (SvGUIDANCE_GAIN, \"GUIDANCE_GAIN\");\n    (SvTHETA_IC_DG, \"THETA_IC_DG\");\n    (SvT_STOP, \"T_STOP\");\n    (SvDT, \"DT\");\n    (SvDT_MAX, \"DT_MAX\");\n    (SvDT_MIN, \"DT_MIN\");\n    (SvDT_PRINT, \"DT_PRINT\")\n  ].\n\nDefinition model_default_values (_: unit) :=\n  [\n    (SvT,             \"0.0\"#D);\n    (SvX,             \"-500.0\"#D);\n    (SvXD,            \"0.0\"#D);\n    (SvXDD,           \"0.0\"#D);\n    (SvZ,             \"-100.0\"#D);\n    (SvZD,            \"0.0\"#D);\n    (SvTHETA,         \"0.0\"#D);\n    (SvTHETA_DOT,     \"0.0\"#D);\n    (SvTHETA_DOT_CMD, \"0.0\"#D);\n    (SvQ_S,           \"0.0\"#D);\n    (SvQ_S_MEAS,      \"0.0\"#D);\n    (SvVELOCITY,      \"100.0\"#D);\n    (SvGUIDANCE_GAIN, \"3.0\"#D);\n    (SvTHETA_IC_DG,   \"0.0\"#D);\n    (SvT_STOP,        \"10.0\"#D);\n    (SvDT,            \"0.005\"#D);\n    (SvDT_MAX,        \"0.005\"#D);\n    (SvDT_MIN,        \"0.005\"#D);\n    (SvDT_PRINT,      \"0.01\"#D)\n  ].\n\nDefinition modelOutputs : list stateVar := [SvT; SvX; SvZ;SvTHETA; SvXD; SvZD; SvQ_S].\n\nDefinition modelPairs : list (stateVar * stateVar) :=\n  [(SvX, SvXD); (SvZ, SvZD); (SvTHETA, SvTHETA_DOT)].\n", "meta": {"author": "richardlford", "repo": "digsim", "sha": "4da30b04be3c66762050e56f1eb5a533d6d806d7", "save_path": "github-repos/coq/richardlford-digsim", "path": "github-repos/coq/richardlford-digsim/digsim-4da30b04be3c66762050e56f1eb5a533d6d806d7/formal/coqimp/task06/model_data.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.2946291360881454}}
{"text": "Require Import Grisette.Eval.\nRequire Import Grisette.SymBoolOp.\nRequire Import Grisette.Invariant.\nRequire Import Grisette.Union.\nRequire Import Grisette.GeneralTactics.\nRequire Import Grisette.MergingStrategy.\nRequire Import Grisette.SubStrategy.\nRequire Import Lia.\nRequire Import Coq.Arith.PeanoNat.\n\nLtac remove_star :=\n  match goal with\n  | [ H: MrgIf _ _ _ _ ==>(_)* EvalValue _ _ |- _] => apply eval_star_mrgif in H\n  | [ H: SSMrgIf _ _ _ _ ==>(_)* EvalValue _ _ |- _ ] => apply eval_star_ss in H\n  | [ H: ISMrgIf _ _ _ _ ==>(_)* EvalValue _ _ |- _ ] => apply eval_star_is in H\n  | [ H: SIMrgIf _ _ _ _ ==>(_)* EvalValue _ _ |- _ ] => apply eval_star_si in H\n  | [ H: IIMrgIf _ _ _ _ ==>(_)* EvalValue _ _ |- _ ] => apply eval_star_ii in H\n  end.\n\nLtac find_same :=\n  match goal with\n    | [ H1 : ?x = _, H2 : ?x = _ |- _ ] => rewrite H1 in H2; invcd H2\n    | [ H1 : ?x = _, H2 : _ = ?x |- _ ] => rewrite H1 in H2; invcd H2\n    | [ H1 : _ = ?x, H2 : _ = ?x |- _ ] => rewrite <- H1 in H2; invcd H2\n  end.\n\nLemma union_sub_rewrite_t :\n  forall {T} c (t1 t2 f : Union T), If c t1 f = If c t2 f <-> t1 = t2.\nProof.\n  intros.\n  split; intros.\n  invcd H; auto.\n  subst. auto.\nQed.\n\nLemma union_sub_rewrite_f :\n  forall {T} c (t f1 f2 : Union T), If c t f1 = If c t f2 <-> f1 = f2.\nProof.\n  intros.\n  split; intros.\n  invcd H; auto.\n  subst. auto.\nQed.\n\nLemma union_sub_rewrite_tf :\n  forall {T} c (t1 t2 f1 f2 : Union T), If c t1 f1 = If c t2 f2 <-> t1 = t2 /\\ f1 = f2.\nProof.\n  intros.\n  split; intros.\n  invcd H; auto.\n  intuition; subst; auto.\nQed.\n\nTheorem determinstic': forall {T n t} {ms : MergingStrategy T n} {step1 step2},\n  EvalTermsGood ms t ->\n  forall {u1 u2},\n  t ==>(step1)* (EvalValue ms u1) ->\n  t ==>(step2)* (EvalValue ms u2) ->\n  u1 = u2 /\\ step1 = step2.\nProof.\n  intros.\n  assert (good:exists n1 (ms1 : MergingStrategy T n1), EvalTermsGood ms1 t).\n  { exists n, ms. assumption. }\n  generalize dependent n.\n  generalize dependent u1.\n  generalize dependent u2.\n  generalize dependent step1.\n  generalize dependent step2.\n  apply EvalTerms_ind' with (t := t); intros; subst; eauto.\n  all: inversion_initial_eval_good; simpl in *; try solve [exfalso; eauto].\n  all: repeat remove_star.\n  { specialize (value_evaluate_to_value H1).\n    specialize (value_evaluate_to_value H2).\n    intros.\n    intuition; try lia.\n    invcd H6.\n    invcd H3.\n    auto.\n  }\n  { destruct b;\n    invcd H3; simpl in *; try solve [exfalso; auto];\n    invcd H4; simpl in *; try solve [exfalso; auto];\n    auto.\n  }\n  { invcd H4; simpl in *; try solve [exfalso; auto]. \n    invcd H5; simpl in *; try solve [exfalso; auto]. \n    rewrite H12 in H14. invcd H14. auto.\n  }\n  1-4: invcd H3; simpl in *; try solve [exfalso; auto];\n    invcd H4; simpl in *; try solve [exfalso; auto];\n    destruct ms; simpl in *; try solve [exfalso; auto];\n    assert (Hd:d + 1 = d0 + 1 <-> d + 0 = d0 + 0) by lia; rewrite Hd;\n    eapply H1; eauto with eval; invcd H2; econstructor; eauto with union.\n  Ltac preprocess :=\n    match goal with\n    | [ H1 : EvalTermsGood ?ms ?t,\n        H2 : ?t ==>(_)* EvalValue ?ms ?u1,\n        H3 : ?t ==>(_)* EvalValue ?ms ?u2 |- _ ] =>\n      invcd H1; repeat remove_star; invcd H2; try solve_aiu; invcd H3; try solve_aiu;\n      repeat aiu_simplify; repeat find_same\n    end.\n  all: preprocess; auto 1.\n\n  Ltac try1 :=\n    match goal with\n    | [ H : forall step2 step1 u2 u1 n ms, _ -> _ ==>(step1)* _ -> _ ==>(step2)* _ -> u1 = u2 /\\ step1 = step2 |- _] =>\n      eapply H\n    end.\n\n  all: try solve [intuition; try lia; try f_equal; eauto].\n  all: try solve [\n    assert (Hd:d0 + 1 = d + 1 <-> d0 + 0 = d + 0) by lia; rewrite Hd;\n    try rewrite union_sub_rewrite_t; try rewrite union_sub_rewrite_f;\n    try1; eauto 2 with eval; econstructor; eauto 2 with union inv].\n\n  (* SSEq *)\n  { assert (Hd:d0 + 1 = d + 1 <-> d0 + 0 = d + 0) by lia; rewrite Hd;\n    eapply H3; eauto with eval.\n    assert (ProperStrategy P0 (SortedStrategy n ind sub0)) by eauto 2 with inv.\n    specialize (all_in_union_left_most' H0); simpl; intros.\n    specialize (proper_ms_sub_from_subfunc H4 H5 H2) as [Psub ?].\n    assert (HieraricalMergingInv Psub s1 t0) by eauto 2 with subinv.\n    assert (HieraricalMergingInv Psub s1 f) by eauto 2 with subinv.\n    econstructor; eauto.\n  }\n\n  (* SIEq *)\n  { assert (Hd:d0 + 1 = d + 1 <-> d0 + 0 = d + 0) by lia; rewrite Hd;\n    rewrite union_sub_rewrite_t.\n    eapply H5; eauto with eval.\n    assert (ProperStrategy P0 (SortedStrategy n ind sub0)) by eauto 2 with inv.\n    specialize (all_in_union_left_most' H0); simpl; intros.\n    specialize (proper_ms_sub_from_subfunc H6 H7 H4) as [Psub ?].\n    assert (HieraricalMergingInv Psub s1 t0) by eauto 2 with subinv.\n    assert (HieraricalMergingInv Psub s1 ft) by eauto 3 with subinv inv.\n    econstructor; eauto.\n  }\n\n  (* ISEq *)\n  { assert (Hd:d0 + 1 = d + 1 <-> d0 + 0 = d + 0) by lia; rewrite Hd;\n    rewrite union_sub_rewrite_t.\n    eapply H5; eauto 2 with eval.\n    assert (ProperStrategy P0 (SortedStrategy n ind sub0)) by eauto 2 with inv.\n    specialize (all_in_union_left_most' H0); simpl; intros.\n    specialize (proper_ms_sub_from_subfunc H6 H7 H4) as [Psub ?].\n    assert (HieraricalMergingInv Psub s1 tt) by eauto 3 with subinv inv.\n    assert (HieraricalMergingInv Psub s1 f) by eauto 2 with subinv.\n    econstructor; eauto.\n  }\n\n  (* IIEq *)\n  { assert ((t'0 = t' /\\ d0 + 0 = d1 + 0) /\\ (f'0 = f' /\\ d3 + 0 = d2 + 0)).\n    { split.\n      - eapply H7; eauto 2 with eval.\n        assert (ProperStrategy P0 (SortedStrategy n ind sub0)) by eauto 2 with inv.\n        specialize (all_in_union_left_most' H0); simpl; intros.\n        specialize (proper_ms_sub_from_subfunc H9 H10 H6) as [Psub ?].\n        assert (HieraricalMergingInv Psub s1 tt) by eauto 3 with subinv inv.\n        assert (HieraricalMergingInv Psub s1 ft) by eauto 3 with subinv inv.\n        econstructor; eauto.\n      - eapply H8; eauto 2 with eval.\n        econstructor; eauto with inv.\n    }\n    intuition.\n    - f_equal; auto.\n    - lia.\n  }\nQed.\n\n", "meta": {"author": "lsrcz", "repo": "grisette-coq", "sha": "60ee0f350fe85f07348f4827436a5c4953ff5474", "save_path": "github-repos/coq/lsrcz-grisette-coq", "path": "github-repos/coq/lsrcz-grisette-coq/grisette-coq-60ee0f350fe85f07348f4827436a5c4953ff5474/theories/Deterministic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.2946291360881454}}
{"text": "From iris_examples.logrel.F_mu_ref_conc Require Export lang.\n\nInductive type :=\n  | TUnit : type\n  | TNat : type\n  | TBool : 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  | TForall (τ : {bind 1 of type})\n  | Tref (τ : type).\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\nFixpoint binop_res_type (op : binop) : type :=\n  match op with\n  | Add => TNat | Sub => TNat | Mult => TNat\n  | Eq => TBool | Le => TBool | Lt => TBool\n  end.\n\nInductive EqType : type → Prop :=\n  | EqTUnit : EqType TUnit\n  | EqTNat : EqType TNat\n  | EqTBool : EqType TBool\n  | EQRef τ : EqType (Tref τ).\n\nReserved Notation \"Γ ⊢ₜ e : τ\" (at level 74, e, τ at next level).\n\nInductive typed (Γ : list type) : expr → type → Prop :=\n  | Var_typed x τ : Γ !! x = Some τ → Γ ⊢ₜ Var x : τ\n  | Unit_typed : Γ ⊢ₜ Unit : TUnit\n  | Nat_typed n : Γ ⊢ₜ #n n : TNat\n  | Bool_typed b : Γ ⊢ₜ #♭ b : TBool\n  | BinOp_typed op e1 e2 :\n     Γ ⊢ₜ e1 : TNat → Γ ⊢ₜ e2 : TNat → Γ ⊢ₜ BinOp op e1 e2 : binop_res_type op\n  | Pair_typed e1 e2 τ1 τ2 : Γ ⊢ₜ 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 τ3 :\n     Γ ⊢ₜ e0 : TSum τ1 τ2 → τ1 :: Γ ⊢ₜ e1 : τ3 → τ2 :: Γ ⊢ₜ e2 : τ3 →\n     Γ ⊢ₜ Case e0 e1 e2 : τ3\n  | If_typed e0 e1 e2 τ :\n     Γ ⊢ₜ e0 : TBool → Γ ⊢ₜ e1 : τ → Γ ⊢ₜ e2 : τ → Γ ⊢ₜ If e0 e1 e2 : τ\n  | Rec_typed e τ1 τ2 :\n     TArrow τ1 τ2 :: τ1 :: Γ ⊢ₜ e : τ2 → Γ ⊢ₜ Rec e : TArrow τ1 τ2\n  | Lam_typed e τ1 τ2 :\n      τ1 :: Γ ⊢ₜ e : τ2 → Γ ⊢ₜ Lam e : TArrow τ1 τ2\n  | LetIn_typed e1 e2 τ1 τ2 :\n      Γ ⊢ₜ e1 : τ1 → τ1 :: Γ ⊢ₜ e2 : τ2 → Γ ⊢ₜ LetIn e1 e2 : τ2\n  | Seq_typed e1 e2 τ1 τ2 :\n      Γ ⊢ₜ e1 : τ1 → Γ ⊢ₜ e2 : τ2 → Γ ⊢ₜ Seq e1 e2 : τ2\n  | App_typed e1 e2 τ1 τ2 :\n     Γ ⊢ₜ e1 : TArrow τ1 τ2 → Γ ⊢ₜ e2 : τ1 → Γ ⊢ₜ App e1 e2 : τ2\n  | TLam_typed e τ :\n     subst (ren (+1)) <$> Γ ⊢ₜ e : τ → Γ ⊢ₜ TLam e : TForall τ\n  | TApp_typed e τ τ' : Γ ⊢ₜ e : TForall τ → Γ ⊢ₜ TApp e : τ.[τ'/]\n  | TFold e τ : Γ ⊢ₜ e : τ.[TRec τ/] → Γ ⊢ₜ Fold e : TRec τ\n  | TUnfold e τ : Γ ⊢ₜ e : TRec τ → Γ ⊢ₜ Unfold e : τ.[TRec τ/]\n  | TFork e : Γ ⊢ₜ e : TUnit → Γ ⊢ₜ Fork e : TUnit\n  | TAlloc e τ : Γ ⊢ₜ e : τ → Γ ⊢ₜ Alloc e : Tref τ\n  | TLoad e τ : Γ ⊢ₜ e : Tref τ → Γ ⊢ₜ Load e : τ\n  | TStore e e' τ : Γ ⊢ₜ e : Tref τ → Γ ⊢ₜ e' : τ → Γ ⊢ₜ Store e e' : TUnit\n  | TCAS e1 e2 e3 τ :\n     EqType τ → Γ ⊢ₜ e1 : Tref τ → Γ ⊢ₜ e2 : τ → Γ ⊢ₜ e3 : τ →\n     Γ ⊢ₜ CAS e1 e2 e3 : TBool\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 (∀ x Γ, x < length (subst (ren (+1)) <$> Γ) → x < length Γ).\n  { intros ??. by rewrite fmap_length. } \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.\nLemma n_closed_invariant n (e : expr) s1 s2 :\n  (∀ f, e.[upn n f] = e) → (∀ x, x < n → s1 x = s2 x) → e.[s1] = e.[s2].\nProof.\n  intros Hnc. specialize (Hnc (ren (+1))).\n  revert n Hnc s1 s2.\n  induction e => m Hmc s1 s2 H1; asimpl in *; try f_equal;\n    try (match goal with H : _ |- _ => eapply H end; eauto;\n         try inversion Hmc; try match goal with H : _ |- _ => by rewrite H end;\n         fail).\n  - apply H1. rewrite iter_up in Hmc. destruct lt_dec; try lia.\n    asimpl in *. injection Hmc as Hmc. unfold var in *. omega.\n  - unfold upn in *.\n    change (e.[up (up (upn m (ren (+1))))]) with\n    (e.[iter (S (S m)) up (ren (+1))]) in *.\n    apply (IHe (S (S m))).\n    + inversion Hmc; match goal with H : _ |- _ => (by rewrite H) end.\n    + intros [|[|x]] H2; [by cbv|by cbv |].\n      asimpl; rewrite H1; auto with lia.\n  - apply (IHe (S m)).\n    + inversion Hmc; match goal with H : _ |- _ => (by rewrite H) end.\n    + intros [|x] H2; [by cbv |].\n      asimpl; rewrite H1; auto with lia.\n  - apply (IHe0 (S m)).\n    + inversion Hmc; match goal with H : _ |- _ => (by rewrite H) end.\n    + intros [|x] H2; [by cbv |].\n      asimpl; rewrite H1; auto with lia.\n  - change (e1.[up (upn m (ren (+1)))]) with\n    (e1.[iter (S m) up (ren (+1))]) in *.\n    apply (IHe0 (S m)).\n    + inversion Hmc; match goal with H : _ |- _ => (by rewrite H) end.\n    + intros [|x] H2; [by cbv |].\n      asimpl; rewrite H1; auto with lia.\n  - change (e2.[up (upn m (ren (+1)))]) with\n    (e2.[upn (S m) (ren (+1))]) in *.\n    apply (IHe1 (S m)).\n    + inversion Hmc; match goal with H : _ |- _ => (by rewrite H) end.\n    + intros [|x] H2; [by cbv |].\n      asimpl; rewrite H1; auto with lia.\nQed.\n\nFixpoint env_subst (vs : list val) : var → expr :=\n  match vs with\n  | [] => ids\n  | v :: vs' => (of_val 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\nLemma typed_n_closed Γ τ e : Γ ⊢ₜ e : τ → (∀ f, e.[upn (length Γ) f] = e).\nProof.\n  intros H. induction H => f; asimpl; simpl in *; auto with f_equal.\n  - apply lookup_lt_Some in H. rewrite iter_up. destruct lt_dec; auto with lia.\n  - f_equal. apply IHtyped.\n  - by f_equal; rewrite map_length in IHtyped.\nQed.\n\n(** Weakening *)\nLemma context_gen_weakening ξ Γ' Γ e τ :\n  Γ' ++ Γ ⊢ₜ e : τ →\n  Γ' ++ ξ ++ Γ ⊢ₜ e.[upn (length Γ') (ren (+ (length ξ)))] : τ.\nProof.\n  intros H1.\n  remember (Γ' ++ Γ) as Ξ. revert Γ' Γ ξ HeqΞ.\n  induction H1 => Γ1 Γ2 ξ HeqΞ; subst; asimpl in *; eauto using typed.\n  - rewrite iter_up; destruct lt_dec as [Hl | Hl].\n    + constructor. rewrite lookup_app_l; trivial. by rewrite lookup_app_l in H.\n    + asimpl. constructor. rewrite lookup_app_r; auto with lia.\n      rewrite lookup_app_r; auto with lia.\n      rewrite lookup_app_r in H; auto with lia.\n      match goal with\n        |- _ !! ?A = _ => by replace A with (x - length Γ1) by lia\n      end.\n  - econstructor; eauto. by apply (IHtyped2 (_::_)). by apply (IHtyped3 (_::_)).\n  - constructor. by apply (IHtyped (_ :: _ :: _)).\n  - constructor. by apply (IHtyped (_ :: _)).\n  - econstructor; eauto. by apply (IHtyped2 (_::_)).\n  - constructor.\n    specialize (IHtyped\n      (subst (ren (+1)) <$> Γ1) (subst (ren (+1)) <$> Γ2) (subst (ren (+1)) <$> ξ)).\n    asimpl in *. rewrite ?map_length in IHtyped.\n    repeat rewrite fmap_app. apply IHtyped.\n    by repeat rewrite fmap_app.\nQed.\n\nLemma context_weakening ξ Γ e τ :\n  Γ ⊢ₜ e : τ → ξ ++ Γ ⊢ₜ e.[(ren (+ (length ξ)))] : τ.\nProof. eapply (context_gen_weakening _ []). Qed.\n\nLemma closed_context_weakening ξ Γ e τ :\n  (∀ f, e.[f] = e) → Γ ⊢ₜ e : τ → ξ ++ Γ ⊢ₜ e : τ.\nProof. intros H1 H2. erewrite <- H1. by eapply context_weakening. Qed.\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/logrel/F_mu_ref_conc/typing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.29462913608814534}}
{"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 alphaeq2.\n\nLemma wf_sub_csub2sub {p} :\n  forall sub, wf_sub (@csub2sub p sub).\nProof.\n  introv lin.\n  apply in_csub2sub in lin.\n  unfold isprogram in lin; sp.\nQed.\nHint Immediate wf_sub_csub2sub.\n\nTheorem csubst_preserves_wf_term {p} :\n  forall sub t,\n    @wf_term p t\n    -> wf_term (csubst t sub).\nProof.\n  introv wt.\n  unfold csubst.\n  apply lsubst_preserves_wf_term; sp.\nQed.\n\nLemma csubst_wf_term {p} :\n  forall t sub,\n    wf_term (@csubst p t sub)\n    -> wf_term t.\nProof.\n  sp.\n  allrw @wf_term_eq.\n  apply @lsubst_nt_wf with (sub := csub2sub sub); sp.\nQed.\n\nLemma lsubstc_csubst_ex {o} :\n  forall (t : @NTerm o) sub1 sub2 w p,\n    {w' : wf_term t & {p' : cover_vars t (sub1 ++ sub2) &\n      lsubstc (csubst t sub1) w sub2 p = lsubstc t w' (sub1 ++ sub2) p'}}.\nProof.\n  sp.\n  assert (nt_wf (csubst t sub1)) as wf by (rw @nt_wf_eq; sp).\n\n  apply lsubst_nt_wf in wf.\n  rw @nt_wf_eq in wf.\n\n  assert (cover_vars t (sub1 ++ sub2)) as c.\n  allrw @cover_vars_eq.\n  apply free_vars_csubst_sub in p.\n  allrw @dom_csub_app; sp.\n\n  exists wf c.\n\n  unfold lsubstc.\n  apply cterm_eq; simpl.\n  apply csubst_app.\nQed.\n\nLemma lsubstc_csubst_eq {o} :\n  forall t sub1 sub2 w w' p p',\n      lsubstc (@csubst o t sub1) w sub2 p = lsubstc t w' (sub1 ++ sub2) p'.\nProof.\n  intros.\n  generalize (lsubstc_csubst_ex t sub1 sub2 w p); sp.\n  rw e.\n  apply lsubstc_eq; auto.\nQed.\n\nLemma lsubstc_csubst_ex2 {o} :\n  forall t sub1 sub2 w p,\n    {w' : wf_term (@csubst o t sub1) &\n    {p' : cover_vars (csubst t sub1) sub2 &\n      lsubstc (csubst t sub1) w' sub2 p' = lsubstc t w (sub1 ++ sub2) p}}.\nProof.\n  sp.\n  assert (wf_term (csubst t sub1)) as w'.\n  apply wf_term_csubst; sp.\n  assert (cover_vars (csubst t sub1) sub2) as p'.\n  rw <- @cover_vars_csubst; sp.\n  exists w' p'.\n  apply lsubstc_csubst_eq.\nQed.\n\nLemma lsubstc_mk_axiom {o} :\n  forall p sub c,\n    lsubstc mk_axiom p sub c = @mkc_axiom o.\nProof.\n  unfold lsubstc, mkc_axiom; sp.\n  apply cterm_eq; sp.\nQed.\n\nLemma csubst_mk_bottom {p} :\n  forall sub, @csubst p mk_bottom sub = mk_bottom.\nProof. intro.\n apply @csubst_trivial . simpl. eauto.\nQed.\n\nLemma lsubstc_mk_bottom {o} :\n  forall p sub c,\n    lsubstc mk_bottom p sub c = @mkc_bottom o.\nProof.\n  unfold lsubstc, mkc_bottom; sp.\n  apply cterm_eq; sp. simpl. apply csubst_mk_bottom.\nQed.\n\nLemma lsubstc_mk_uni {o} :\n  forall i p sub c,\n    lsubstc (mk_uni i) p sub c = @mkc_uni o i.\nProof.\n  unfold lsubstc, mkc_uni; sp.\n  apply cterm_eq; sp.\nQed.\n\nLemma lsubstc_mk_base {o} :\n  forall p sub c,\n    lsubstc mk_base p sub c = @mkc_base o.\nProof.\n  unfold lsubstc, mkc_base, mkc_base; sp.\n  apply cterm_eq; sp.\nQed.\n\nLemma lsubstc_mk_atom {o} :\n  forall p sub c,\n    lsubstc mk_atom p sub c = @mkc_atom o.\nProof.\n  unfold lsubstc, mkc_atom, mkc_atom; sp.\n  apply cterm_eq; sp.\nQed.\n\nLemma lsubstc_mk_uatom {o} :\n  forall p sub c,\n    lsubstc mk_uatom p sub c = @mkc_uatom o.\nProof.\n  unfold lsubstc, mkc_uatom, mkc_uatom; sp.\n  apply cterm_eq; sp.\nQed.\n\nLemma lsubstc_mk_token {o} :\n  forall s p sub c,\n    lsubstc (mk_token s) p sub c = @mkc_token o s.\nProof.\n  unfold lsubstc, mkc_token; sp.\n  apply cterm_eq; sp.\nQed.\n\nLemma lsubstc_mk_utoken {o} :\n  forall s p sub c,\n    lsubstc (mk_utoken s) p sub c = @mkc_utoken o s.\nProof.\n  unfold lsubstc, mkc_utoken; sp.\n  apply cterm_eq; sp.\nQed.\n\nLemma csubst_mk_false {o} :\n  forall sub, csubst mk_false sub = @mk_false o.\nProof.\n  intro; unfold csubst; simpl; fold @mk_axiom.\n  change_to_lsubst_aux4; simpl.\n  repeat (rewrite sub_filter_nil_r).\n  assert (sub_find (csub2sub sub) nvarx = None [+] LIn nvarx [nvarx]) as or by (simpl; sp).\n  rw <- @sub_find_sub_filter_none in or.\n  rewrite or; sp.\nQed.\n\nLemma lsubstc_mk_false {o} :\n  forall p sub c,\n    lsubstc mk_false p sub c = @mkc_false o.\nProof.\n  unfold lsubstc, mkc_false; sp.\n  apply cterm_eq; simpl.\n  apply csubst_mk_false; auto.\nQed.\n\nLemma lsubstc_mk_free_from_atom {o} :\n  forall t1 t2 T sub,\n  forall w1 : @wf_term o t1,\n  forall w2 : wf_term t2,\n  forall wT : wf_term T,\n  forall w  : wf_term (mk_free_from_atom t1 t2 T),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars t2 sub,\n  forall cT : cover_vars T sub,\n  forall c  : cover_vars (mk_free_from_atom t1 t2 T) sub,\n    lsubstc (mk_free_from_atom t1 t2 T) w sub c\n    = mkc_free_from_atom (lsubstc t1 w1 sub c1)\n                   (lsubstc t2 w2 sub c2)\n                   (lsubstc T wT sub cT).\nProof.\n  sp; unfold lsubstc; simpl.\n  assert (csubst (mk_free_from_atom t1 t2 T) sub\n          = mk_free_from_atom (csubst t1 sub) (csubst t2 sub) (csubst T sub))\n         by (unfold csubst; simpl;\n             change_to_lsubst_aux4; simpl;\n             rw @sub_filter_nil_r;\n             allrw @fold_nobnd;\n             rw @fold_free_from_atom; sp).\n  apply cterm_eq; auto.\nQed.\n\nLemma lsubstc_mk_free_from_atom_ex {o} :\n  forall t1 t2 T sub,\n  forall w  : wf_term (@mk_free_from_atom o t1 t2 T),\n  forall c  : cover_vars (mk_free_from_atom t1 t2 T) sub,\n  {w1 : wf_term t1\n   & {w2 : wf_term t2\n   & {wT : wf_term T\n   & {c1 : cover_vars t1 sub\n   & {c2 : cover_vars t2 sub\n   & {cT : cover_vars T sub\n      & lsubstc (mk_free_from_atom t1 t2 T) w sub c\n           = mkc_free_from_atom (lsubstc t1 w1 sub c1)\n                          (lsubstc t2 w2 sub c2)\n                          (lsubstc T wT sub cT)}}}}}}.\nProof.\n  sp.\n\n  assert (wf_term t1) as w1.\n  { allrw <- @wf_free_from_atom_iff; sp. }\n\n  assert (wf_term t2) as w2.\n  { allrw <- @wf_free_from_atom_iff; sp. }\n\n  assert (wf_term T) as w3.\n  { allrw <- @wf_free_from_atom_iff; sp. }\n\n  assert (cover_vars t1 sub) as c1.\n  { unfold cover_vars in c; allsimpl.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  assert (cover_vars t2 sub) as c2.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  assert (cover_vars T sub) as c3.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists w1 w2 w3 c1 c2 c3.\n  apply lsubstc_mk_free_from_atom.\nQed.\n\nLemma lsubstc_mk_equality {o} :\n  forall t1 t2 T sub,\n  forall w1 : @wf_term o t1,\n  forall w2 : wf_term t2,\n  forall wT : wf_term T,\n  forall w  : wf_term (mk_equality t1 t2 T),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars t2 sub,\n  forall cT : cover_vars T sub,\n  forall c  : cover_vars (mk_equality t1 t2 T) sub,\n    lsubstc (mk_equality t1 t2 T) w sub c\n    = mkc_equality (lsubstc t1 w1 sub c1)\n                   (lsubstc t2 w2 sub c2)\n                   (lsubstc T wT sub cT).\nProof.\n  sp; unfold lsubstc; simpl.\n  assert (csubst (mk_equality t1 t2 T) sub\n          = mk_equality (csubst t1 sub) (csubst t2 sub) (csubst T sub))\n         by (unfold csubst; simpl;\n             change_to_lsubst_aux4; simpl;\n             rw @sub_filter_nil_r;\n             allrw @fold_nobnd;\n             rw @fold_equality; sp).\n  apply cterm_eq; auto.\nQed.\n\nLemma lsubstc_mk_equality_ex {o} :\n  forall t1 t2 T sub,\n  forall w  : wf_term (@mk_equality o t1 t2 T),\n  forall c  : cover_vars (mk_equality t1 t2 T) sub,\n  {w1 : wf_term t1\n   & {w2 : wf_term t2\n   & {wT : wf_term T\n   & {c1 : cover_vars t1 sub\n   & {c2 : cover_vars t2 sub\n   & {cT : cover_vars T sub\n      & lsubstc (mk_equality t1 t2 T) w sub c\n           = mkc_equality (lsubstc t1 w1 sub c1)\n                          (lsubstc t2 w2 sub c2)\n                          (lsubstc T wT sub cT)}}}}}}.\nProof.\n  sp.\n\n  assert (wf_term t1) as w1.\n  { allrw <- @wf_equality_iff; sp. }\n\n  assert (wf_term t2) as w2.\n  { allrw <- @wf_equality_iff; sp. }\n\n  assert (wf_term T) as w3.\n  { allrw <- @wf_equality_iff; sp. }\n\n  assert (cover_vars t1 sub) as c1.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  assert (cover_vars t2 sub) as c2.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  assert (cover_vars T sub) as c3.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists w1 w2 w3 c1 c2 c3.\n  apply lsubstc_mk_equality.\nQed.\n\nLemma lsubstc_mk_member {o} :\n  forall t T sub,\n  forall wt : wf_term t,\n  forall wT : @wf_term o T,\n  forall w  : wf_term (mk_member t T),\n  forall ct : cover_vars t sub,\n  forall cT : cover_vars T sub,\n  forall c  : cover_vars (mk_member t T) sub,\n    lsubstc (mk_member t T) w sub c\n    = mkc_member (lsubstc t wt sub ct)\n                 (lsubstc T wT sub cT).\nProof.\n  unfold mk_member; sp.\n  rw <- @fold_mkc_member.\n  apply lsubstc_mk_equality.\nQed.\n\nLemma lsubstc_mk_member_ex {o} :\n  forall t T sub,\n  forall w  : wf_term (@mk_member o t T),\n  forall c  : cover_vars (mk_member t T) sub,\n    {wt : wf_term t\n     & {wT : wf_term T\n     & {ct : cover_vars t sub\n     & {cT : cover_vars T sub\n        & lsubstc (mk_member t T) w sub c\n             = mkc_member (lsubstc t wt sub ct)\n                          (lsubstc T wT sub cT)}}}}.\nProof.\n  unfold mk_member; sp.\n  generalize (lsubstc_mk_equality_ex t t T sub w c); sp.\n  rewrite @lsubstc_replace with (w2 := w2) (p2 := c2) in e.\n  exists w2 wT c2 cT; sp.\n  rw <- @fold_mkc_member; sp.\nQed.\n\nLemma lsubstc_mk_tequality {o} :\n  forall t1 t2 sub,\n  forall w1 : wf_term t1,\n  forall w2 : @wf_term o t2,\n  forall w  : wf_term (mk_tequality t1 t2),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars t2 sub,\n  forall c  : cover_vars (mk_tequality t1 t2) sub,\n    lsubstc (mk_tequality t1 t2) w sub c\n    = mkc_tequality (lsubstc t1 w1 sub c1)\n                    (lsubstc t2 w2 sub c2).\nProof.\n  sp; unfold lsubstc; simpl.\n  assert (csubst (mk_tequality t1 t2) sub\n          = mk_tequality (csubst t1 sub) (csubst t2 sub))\n         by (unfold csubst; simpl;\n             change_to_lsubst_aux4; simpl;\n             rw @sub_filter_nil_r; sp).\n  apply cterm_eq; auto.\nQed.\n\nLemma lsubstc_mk_tequality_ex {o} :\n  forall t1 t2 sub,\n  forall w  : wf_term (@mk_tequality o t1 t2),\n  forall c  : cover_vars (mk_tequality t1 t2) sub,\n  {w1 : wf_term t1\n   & {w2 : wf_term t2\n   & {c1 : cover_vars t1 sub\n   & {c2 : cover_vars t2 sub\n      & lsubstc (mk_tequality t1 t2) w sub c\n           = mkc_tequality (lsubstc t1 w1 sub c1)\n                           (lsubstc t2 w2 sub c2)}}}}.\nProof.\n  sp.\n\n  assert (wf_term t1) as w1.\n  { allrw <- @wf_tequality_iff; sp. }\n\n  assert (wf_term t2) as w2.\n  { allrw <- @wf_tequality_iff; sp. }\n\n  assert (cover_vars t1 sub) as c1.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  assert (cover_vars t2 sub) as c2.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists w1 w2 c1 c2.\n  apply lsubstc_mk_tequality.\nQed.\n\nLemma lsubstc_mk_type {o} :\n  forall t sub,\n  forall wt : @wf_term o t,\n  forall w  : wf_term (mk_type t),\n  forall ct : cover_vars t sub,\n  forall c  : cover_vars (mk_type t) sub,\n    lsubstc (mk_type t) w sub c\n    = mkc_type (lsubstc t wt sub ct).\nProof.\n  unfold mk_type; sp.\n  rw <- @fold_mkc_type.\n  apply lsubstc_mk_tequality.\nQed.\n\nLemma lsubstc_mk_type_ex {o} :\n  forall t sub,\n  forall w  : wf_term (@mk_type o t),\n  forall c  : cover_vars (mk_type t) sub,\n    {wt : wf_term t\n     & {ct : cover_vars t sub\n        & lsubstc (mk_type t) w sub c\n             = mkc_type (lsubstc t wt sub ct)}}.\nProof.\n  unfold mk_type; sp.\n  generalize (lsubstc_mk_tequality_ex t t sub w c); sp.\n  rewrite @lsubstc_replace with (w2 := w2) (p2 := c2) in e.\n  exists w2 c2; sp.\n  rw <- @fold_mkc_type; sp.\nQed.\n\nLemma lsubstc_mk_approx {o} :\n  forall t1 t2 sub,\n  forall w1 : wf_term t1,\n  forall w2 : @wf_term o t2,\n  forall w  : wf_term (mk_approx t1 t2),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars t2 sub,\n  forall c  : cover_vars (mk_approx t1 t2) sub,\n    lsubstc (mk_approx t1 t2) w sub c\n    = mkc_approx (lsubstc t1 w1 sub c1)\n                 (lsubstc t2 w2 sub c2).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r.\n  allrw @fold_nobnd.\n  rw @fold_approx; sp.\nQed.\n\nLemma lsubstc_mk_approx_ex {o} :\n  forall t1 t2 sub,\n  forall w  : wf_term (@mk_approx o t1 t2),\n  forall c  : cover_vars (mk_approx t1 t2) sub,\n    {w1 : wf_term t1\n     & {w2 : wf_term t2\n     & {c1 : cover_vars t1 sub\n     & {c2 : cover_vars t2 sub\n        & lsubstc (mk_approx t1 t2) w sub c\n             = mkc_approx (lsubstc t1 w1 sub c1)\n                        (lsubstc t2 w2 sub c2)}}}}.\nProof.\n  sp.\n\n  assert (wf_term t1) as w1.\n  { allrw <- @wf_approx_iff; sp. }\n\n  assert (wf_term t2) as w2.\n  { allrw <- @wf_approx_iff; sp. }\n\n  assert (cover_vars t1 sub) as c1.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  assert (cover_vars t2 sub) as c2.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists w1 w2 c1 c2.\n  apply lsubstc_mk_approx.\nQed.\n\nLemma lsubstc_mk_cequiv {o} :\n  forall t1 t2 sub,\n  forall w1 : wf_term t1,\n  forall w2 : @wf_term o t2,\n  forall w  : wf_term (mk_cequiv t1 t2),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars t2 sub,\n  forall c  : cover_vars (mk_cequiv t1 t2) sub,\n    lsubstc (mk_cequiv t1 t2) w sub c\n    = mkc_cequiv (lsubstc t1 w1 sub c1)\n                  (lsubstc t2 w2 sub c2).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r.\n  allrw @fold_nobnd.\n  rw @fold_cequiv; sp.\nQed.\n\nLemma lsubstc_mk_cequiv_ex {p} :\n  forall t1 t2 sub,\n  forall w  : wf_term (@mk_cequiv p t1 t2),\n  forall c  : cover_vars (mk_cequiv t1 t2) sub,\n    {w1 : wf_term t1\n     & {w2 : wf_term t2\n     & {c1 : cover_vars t1 sub\n     & {c2 : cover_vars t2 sub\n        & lsubstc (mk_cequiv t1 t2) w sub c\n             = mkc_cequiv (lsubstc t1 w1 sub c1)\n                           (lsubstc t2 w2 sub c2)}}}}.\nProof.\n  sp.\n\n  assert (wf_term t1) as w1.\n  { allrw <- @wf_cequiv_iff; sp. }\n\n  assert (wf_term t2) as w2.\n  { allrw <- @wf_cequiv_iff; sp. }\n\n  assert (cover_vars t1 sub) as c1.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  assert (cover_vars t2 sub) as c2.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists w1 w2 c1 c2.\n  apply lsubstc_mk_cequiv.\nQed.\n\nLemma lsubstc_mk_pair {p} :\n  forall t1 t2 sub,\n  forall w1 : wf_term t1,\n  forall w2 : @wf_term p t2,\n  forall w  : wf_term (mk_pair t1 t2),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars t2 sub,\n  forall c  : cover_vars (mk_pair t1 t2) sub,\n    lsubstc (mk_pair t1 t2) w sub c\n    = mkc_pair (lsubstc t1 w1 sub c1)\n               (lsubstc t2 w2 sub c2).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r.\n  allrw @fold_nobnd.\n  rw @fold_pair; sp.\nQed.\n\nLemma lsubstc_mk_pair_ex {p} :\n  forall t1 t2 sub,\n  forall w  : wf_term (@mk_pair p t1 t2),\n  forall c  : cover_vars (mk_pair t1 t2) sub,\n    {w1 : wf_term t1\n     & {w2 : wf_term t2\n     & {c1 : cover_vars t1 sub\n     & {c2 : cover_vars t2 sub\n        & lsubstc (mk_pair t1 t2) w sub c\n             = mkc_pair (lsubstc t1 w1 sub c1)\n                        (lsubstc t2 w2 sub c2)}}}}.\nProof.\n  sp.\n\n  assert (wf_term t1) as w1.\n  { allrw @wf_pair; sp. }\n\n  assert (wf_term t2) as w2.\n  { allrw @wf_pair; sp. }\n\n  assert (cover_vars t1 sub) as c1.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  assert (cover_vars t2 sub) as c2.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists w1 w2 c1 c2.\n  apply lsubstc_mk_pair.\nQed.\n\nLemma lsubstc_mk_sup {p} :\n  forall t1 t2 sub,\n  forall w1 : wf_term t1,\n  forall w2 : @wf_term p t2,\n  forall w  : wf_term (mk_sup t1 t2),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars t2 sub,\n  forall c  : cover_vars (mk_sup t1 t2) sub,\n    lsubstc (mk_sup t1 t2) w sub c\n    = mkc_sup (lsubstc t1 w1 sub c1)\n              (lsubstc t2 w2 sub c2).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r.\n  allrw @fold_nobnd.\n  rw @fold_sup; sp.\nQed.\n\nLemma lsubstc_mk_sup_ex {p} :\n  forall t1 t2 sub,\n  forall w  : wf_term (@mk_sup p t1 t2),\n  forall c  : cover_vars (mk_sup t1 t2) sub,\n    {w1 : wf_term t1\n     & {w2 : wf_term t2\n     & {c1 : cover_vars t1 sub\n     & {c2 : cover_vars t2 sub\n        & lsubstc (mk_sup t1 t2) w sub c\n             = mkc_sup (lsubstc t1 w1 sub c1)\n                       (lsubstc t2 w2 sub c2)}}}}.\nProof.\n  sp.\n\n  assert (wf_term t1) as w1.\n  { allrw @wf_sup_iff; sp. }\n\n  assert (wf_term t2) as w2.\n  { allrw @wf_sup_iff; sp. }\n\n  assert (cover_vars t1 sub) as c1.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  assert (cover_vars t2 sub) as c2.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists w1 w2 c1 c2.\n  apply lsubstc_mk_sup.\nQed.\n\nLemma lsubstc_mk_texc {o} :\n  forall (t1 t2 : @NTerm o) sub,\n  forall w1 : wf_term t1,\n  forall w2 : wf_term t2,\n  forall w  : wf_term (mk_texc t1 t2),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars t2 sub,\n  forall c  : cover_vars (mk_texc t1 t2) sub,\n    lsubstc (mk_texc t1 t2) w sub c\n    = mkc_texc (lsubstc t1 w1 sub c1)\n               (lsubstc t2 w2 sub c2).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  allrw @fold_nobnd.\n  rw @sub_filter_nil_r; sp.\nQed.\n\nLemma wf_texc {p} :\n  forall a b : @NTerm p, wf_term (mk_texc a b) <=> (wf_term a # wf_term b).\nProof.\n  introv; split; intro w; repnd.\n  rw @wf_term_eq in w.\n  inversion w as [|?| o l bw e]; subst.\n  generalize (bw (nobnd a)) (bw (nobnd b)); simpl; intros bw1 bw2.\n  autodimp bw1 hyp.\n  autodimp bw2 hyp.\n  inversion bw1; subst.\n  inversion bw2; subst.\n  allrw @nt_wf_eq; sp.\n  apply nt_wf_eq.\n  constructor; simpl; sp; subst; constructor; rw @nt_wf_eq; sp.\nQed.\n\nLemma lsubstc_mk_texc_ex {o} :\n  forall (t1 t2 : @NTerm o) sub,\n  forall w  : wf_term (mk_texc t1 t2),\n  forall c  : cover_vars (mk_texc t1 t2) sub,\n    {w1 : wf_term t1\n     & {w2 : wf_term t2\n     & {c1 : cover_vars t1 sub\n     & {c2 : cover_vars t2 sub\n     & lsubstc (mk_texc t1 t2) w sub c\n       = mkc_texc (lsubstc t1 w1 sub c1)\n                  (lsubstc t2 w2 sub c2)}}}}.\nProof.\n  sp.\n\n  assert (wf_term t1) as w1.\n  { allrw @wf_texc; sp. }\n\n  assert (wf_term t2) as w2.\n  { allrw @wf_texc; sp. }\n\n  assert (cover_vars t1 sub) as c1.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  assert (cover_vars t2 sub) as c2.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n  repeat (rw @over_vars_app_l in c); sp. }\n\n  exists w1 w2 c1 c2.\n  apply lsubstc_mk_texc.\nQed.\n\nLemma lsubstc_mk_union {p} :\n  forall t1 t2 sub,\n  forall w1 : wf_term t1,\n  forall w2 : @wf_term p t2,\n  forall w  : wf_term (mk_union t1 t2),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars t2 sub,\n  forall c  : cover_vars (mk_union t1 t2) sub,\n    lsubstc (mk_union t1 t2) w sub c\n    = mkc_union (lsubstc t1 w1 sub c1)\n                (lsubstc t2 w2 sub c2).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  allrw @fold_nobnd.\n  rw @sub_filter_nil_r; sp.\nQed.\n\nLemma wf_union {p} :\n  forall a b : @NTerm p, wf_term (mk_union a b) <=> (wf_term a # wf_term b).\nProof.\n  introv; split; intro w; repnd.\n  rw @wf_term_eq in w.\n  inversion w as [|?| o l bw e]; subst.\n  generalize (bw (nobnd a)) (bw (nobnd b)); simpl; intros bw1 bw2.\n  autodimp bw1 hyp.\n  autodimp bw2 hyp.\n  inversion bw1; subst.\n  inversion bw2; subst.\n  allrw @nt_wf_eq; sp.\n  apply nt_wf_eq.\n  constructor; simpl; sp; subst; constructor; rw @nt_wf_eq; sp.\nQed.\n\nLemma lsubstc_mk_union_ex {p} :\n  forall t1 t2 sub,\n  forall w  : wf_term (@mk_union p t1 t2),\n  forall c  : cover_vars (mk_union t1 t2) sub,\n    {w1 : wf_term t1\n     & {w2 : wf_term t2\n     & {c1 : cover_vars t1 sub\n     & {c2 : cover_vars t2 sub\n        & lsubstc (mk_union t1 t2) w sub c\n          = mkc_union (lsubstc t1 w1 sub c1)\n                      (lsubstc t2 w2 sub c2)}}}}.\nProof.\n  sp.\n\n  assert (wf_term t1) as w1.\n  { allrw @wf_union; sp. }\n\n  assert (wf_term t2) as w2.\n  { allrw @wf_union; sp. }\n\n  assert (cover_vars t1 sub) as c1.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  assert (cover_vars t2 sub) as c2.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists w1 w2 c1 c2.\n  apply lsubstc_mk_union.\nQed.\n\nLemma lsubstc_mk_pertype {p} :\n  forall R sub,\n  forall w  : @wf_term p R,\n  forall w' : wf_term (mk_pertype R),\n  forall c  : cover_vars R sub,\n  forall c' : cover_vars (mk_pertype R) sub,\n    lsubstc (mk_pertype R) w' sub c'\n    = mkc_pertype (lsubstc R w sub c).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r.\n  allrw @fold_nobnd.\n  rw @fold_pertype; sp.\nQed.\n\nLemma lsubstc_mk_pertype_ex {p} :\n  forall R sub,\n  forall w : wf_term (@mk_pertype p R),\n  forall c : cover_vars (mk_pertype R) sub,\n    {w1 : wf_term R\n     & {c1 : cover_vars R sub\n        & lsubstc (mk_pertype R) w sub c\n             = mkc_pertype (lsubstc R w1 sub c1)}}.\nProof.\n  sp.\n\n  assert (wf_term R) as w1.\n  { allrw <- @wf_pertype_iff; sp. }\n\n  assert (cover_vars R sub) as c1.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists w1 c1.\n  apply lsubstc_mk_pertype.\nQed.\n\nLemma lsubstc_mk_exception {p} :\n  forall (a R : @NTerm p) sub,\n  forall wa : wf_term a,\n  forall w  : wf_term R,\n  forall w' : wf_term (mk_exception a R),\n  forall c  : cover_vars R sub,\n  forall ca : cover_vars a sub,\n  forall c' : cover_vars (mk_exception a R) sub,\n    lsubstc (mk_exception a R) w' sub c'\n    = mkc_exception (lsubstc a wa sub ca) (lsubstc R w sub c).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd.\n  rw @fold_exception; sp.\nQed.\n\nLemma wf_exception_iff {p} :\n  forall a b : @NTerm p, wf_term (mk_exception a b) <=> (wf_term a # wf_term b).\nProof.\n  introv; split; intro w; repnd.\n  rw @wf_term_eq in w.\n  inversion w as [|?| o l bw e]; subst.\n  generalize (bw (nobnd a)) (bw (nobnd b)); simpl; intros bw1 bw2.\n  autodimp bw1 hyp.\n  autodimp bw2 hyp.\n  inversion bw1; subst.\n  inversion bw2; subst.\n  allrw @nt_wf_eq; sp.\n  apply nt_wf_eq.\n  constructor; simpl; sp; subst; constructor; rw @nt_wf_eq; sp.\nQed.\n\nLemma lsubstc_mk_exception_ex {p} :\n  forall a R sub,\n  forall w : wf_term (@mk_exception p a R),\n  forall c : cover_vars (mk_exception a R) sub,\n    {w1 : wf_term a\n     & {w2 : wf_term R\n     & {c1 : cover_vars a sub\n     & {c2 : cover_vars R sub\n     & lsubstc (mk_exception a R) w sub c\n       = mkc_exception (lsubstc a w1 sub c1) (lsubstc R w2 sub c2)}}}}.\nProof.\n  sp.\n\n  assert (wf_term a) as w1.\n  { allrw @wf_exception_iff; sp. }\n\n  assert (wf_term R) as w2.\n  { allrw @wf_exception_iff; sp. }\n\n  assert (cover_vars a sub) as c1.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  assert (cover_vars R sub) as c2.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists w1 w2 c1 c2.\n  apply lsubstc_mk_exception.\nQed.\n\nLemma lsubstc_mk_sleep {p} :\n  forall R sub,\n  forall w  : @wf_term p R,\n  forall w' : wf_term (mk_sleep R),\n  forall c  : cover_vars R sub,\n  forall c' : cover_vars (mk_sleep R) sub,\n    lsubstc (mk_sleep R) w' sub c'\n    = mkc_sleep (lsubstc R w sub c).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd.\n  rw @fold_sleep; sp.\nQed.\n\nLemma wf_sleep_iff {p} :\n  forall a : @NTerm p, wf_term (mk_sleep a) <=> wf_term a.\nProof.\n  introv; split; intro w; repnd.\n  rw @wf_term_eq in w.\n  inversion w as [|?| o l bw e]; subst.\n  generalize (bw (nobnd a)); simpl; intros bw1.\n  autodimp bw1 hyp.\n  inversion bw1; subst.\n  allrw @nt_wf_eq; sp.\n  apply nt_wf_eq.\n  constructor; simpl; sp; subst; constructor; rw @nt_wf_eq; sp.\nQed.\n\nLemma lsubstc_mk_sleep_ex {p} :\n  forall R sub,\n  forall w : wf_term (@mk_sleep p R),\n  forall c : cover_vars (mk_sleep R) sub,\n    {w1 : wf_term R\n     & {c1 : cover_vars R sub\n        & lsubstc (mk_sleep R) w sub c\n          = mkc_sleep (lsubstc R w1 sub c1)}}.\nProof.\n  sp.\n\n  assert (wf_term R) as w1.\n  { allrw @wf_sleep_iff; sp. }\n\n  assert (cover_vars R sub) as c1.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists w1 c1.\n  apply lsubstc_mk_sleep.\nQed.\n\nLemma lsubstc_mk_squash {p} :\n  forall R sub,\n  forall w  : @wf_term p R,\n  forall w' : wf_term (mk_squash R),\n  forall c  : cover_vars R sub,\n  forall c' : cover_vars (mk_squash R) sub,\n    lsubstc (mk_squash R) w' sub c'\n    = mkc_squash (lsubstc R w sub c).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd. sp.\nQed.\n\nLemma lsubstc_mk_squash_ex {p} :\n  forall R sub,\n  forall w : wf_term (@mk_squash p R),\n  forall c : cover_vars (mk_squash R) sub,\n    {w1 : wf_term R\n     & {c1 : cover_vars R sub\n        & lsubstc (mk_squash R) w sub c\n          = mkc_squash (lsubstc R w1 sub c1)}}.\nProof.\n  sp.\n\n  assert (wf_term R) as w1.\n  { allrw @wf_squash; sp. }\n\n  assert (cover_vars R sub) as c1.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists w1 c1.\n  apply lsubstc_mk_squash.\nQed.\n\nLemma lsubstc_mk_ipertype {p} :\n  forall R sub,\n  forall w  : @wf_term p R,\n  forall w' : wf_term (mk_ipertype R),\n  forall c  : cover_vars R sub,\n  forall c' : cover_vars (mk_ipertype R) sub,\n    lsubstc (mk_ipertype R) w' sub c'\n    = mkc_ipertype (lsubstc R w sub c).\nProof.\n  sp; unfold lsubstc; simpl.\n  assert (csubst (mk_ipertype R) sub = mk_ipertype (csubst R sub))\n         by (unfold csubst; simpl;\n             change_to_lsubst_aux4; simpl;\n             rw @sub_filter_nil_r; allrw @fold_nobnd;\n             rw @fold_ipertype; sp).\n  apply cterm_eq; sp.\nQed.\n\nLemma lsubstc_mk_ipertype_ex {p} :\n  forall R sub,\n  forall w : wf_term (@mk_ipertype p R),\n  forall c : cover_vars (mk_ipertype R) sub,\n    {w1 : wf_term R\n     & {c1 : cover_vars R sub\n        & lsubstc (mk_ipertype R) w sub c\n             = mkc_ipertype (lsubstc R w1 sub c1)}}.\nProof.\n  sp.\n\n  assert (wf_term R) as w1.\n  { allrw <- @wf_ipertype_iff; sp. }\n\n  assert (cover_vars R sub) as c1.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists w1 c1.\n  apply lsubstc_mk_ipertype.\nQed.\n\nLemma lsubstc_mk_spertype {p} :\n  forall R sub,\n  forall w  : @wf_term p R,\n  forall w' : wf_term (mk_spertype R),\n  forall c  : cover_vars R sub,\n  forall c' : cover_vars (mk_spertype R) sub,\n    lsubstc (mk_spertype R) w' sub c'\n    = mkc_spertype (lsubstc R w sub c).\nProof.\n  sp; unfold lsubstc; simpl.\n  assert (csubst (mk_spertype R) sub = mk_spertype (csubst R sub))\n         by (unfold csubst; simpl;\n             change_to_lsubst_aux4; simpl;\n             rw @sub_filter_nil_r; allrw @fold_nobnd;\n             rw @fold_spertype; sp).\n  apply cterm_eq; sp.\nQed.\n\nLemma lsubstc_mk_spertype_ex {p} :\n  forall R sub,\n  forall w : wf_term (@mk_spertype p R),\n  forall c : cover_vars (mk_spertype R) sub,\n    {w1 : wf_term R\n     & {c1 : cover_vars R sub\n        & lsubstc (mk_spertype R) w sub c\n          = mkc_spertype (lsubstc R w1 sub c1)}}.\nProof.\n  sp.\n\n  assert (wf_term R) as wf.\n  { allrw <- @wf_spertype_iff; sp. }\n\n  assert (cover_vars R sub) as cv.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists wf cv.\n  apply lsubstc_mk_spertype.\nQed.\n\nLemma lsubstc_mk_tuni {p} :\n  forall R sub,\n  forall w  : @wf_term p R,\n  forall w' : wf_term (mk_tuni R),\n  forall c  : cover_vars R sub,\n  forall c' : cover_vars (mk_tuni R) sub,\n    lsubstc (mk_tuni R) w' sub c'\n    = mkc_tuni (lsubstc R w sub c).\nProof.\n  sp; unfold lsubstc; simpl.\n  assert (csubst (mk_tuni R) sub = mk_tuni (csubst R sub))\n         by (unfold csubst; simpl;\n             change_to_lsubst_aux4; simpl;\n             rw @sub_filter_nil_r; allrw @fold_nobnd;\n             rw @fold_tuni; sp).\n  apply cterm_eq; sp.\nQed.\n\nLemma lsubstc_mk_tuni_ex {p} :\n  forall R sub,\n  forall w : wf_term (@mk_tuni p R),\n  forall c : cover_vars (mk_tuni R) sub,\n    {w1 : wf_term R\n     & {c1 : cover_vars R sub\n        & lsubstc (mk_tuni R) w sub c\n          = mkc_tuni (lsubstc R w1 sub c1)}}.\nProof.\n  sp.\n\n  assert (wf_term R) as wf.\n  { allrw <- @wf_tuni_iff; sp. }\n\n  assert (cover_vars R sub) as cv.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists wf cv.\n  apply lsubstc_mk_tuni.\nQed.\n\n(*\nLemma lsubstc_mk_esquash :\n  forall R sub,\n  forall w  : wf_term R,\n  forall w' : wf_term (mk_esquash R),\n  forall c  : cover_vars R sub,\n  forall c' : cover_vars (mk_esquash R) sub,\n    lsubstc (mk_esquash R) w' sub c'\n    = mkc_esquash (lsubstc R w sub c).\nProof.\n  sp; unfold lsubstc; simpl.\n  assert (csubst (mk_esquash R) sub = mk_esquash (csubst R sub))\n         by (unfold csubst; simpl;\n             change_to_lsubst_aux4; simpl;\n             rw @sub_filter_nil_r; allrw @fold_nobnd.\n             rw fold_esquash; sp).\n\n  rewrite dep_pair_eq with (eq0 := H)\n          (pb := isprog_esquash (csubst R sub)\n                                (isprog_csubst R sub w c)); sp.\n  apply UIP_dec.\n  apply bool_dec.\nQed.\n\nLemma lsubstc_mk_esquash_ex :\n  forall R sub,\n  forall w : wf_term (mk_esquash R),\n  forall c : cover_vars (mk_esquash R) sub,\n    {w1 : wf_term R\n     & {c1 : cover_vars R sub\n        & lsubstc (mk_esquash R) w sub c\n             = mkc_esquash (lsubstc R w1 sub c1)}}.\nProof.\n  sp.\n\n  assert (wf_term R).\n  unfold wf_term in w.\n  simpl in w.\n  allrw andb_true; sp.\n\n  assert (cover_vars R sub).\n  unfold cover_vars in c.\n  simpl in c.\n  repeat (rw remove_nvars_nil_l in c).\n  rw app_nil_r in c.\n  repeat (rw @over_vars_app_l in c); sp.\n\n  exists H H0.\n  apply lsubstc_mk_esquash.\nQed.\n*)\n\nLemma lsubstc_mk_apply {p} :\n  forall t1 t2 sub,\n  forall w1 : wf_term t1,\n  forall w2 : @wf_term p t2,\n  forall w  : wf_term (mk_apply t1 t2),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars t2 sub,\n  forall c  : cover_vars (mk_apply t1 t2) sub,\n    lsubstc (mk_apply t1 t2) w sub c\n    = mkc_apply (lsubstc t1 w1 sub c1)\n                (lsubstc t2 w2 sub c2).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd.\n  rw @fold_apply; sp.\nQed.\n\nLemma lsubstc_mk_apply_ex {p} :\n  forall t1 t2 sub,\n  forall w  : wf_term (@mk_apply p t1 t2),\n  forall c  : cover_vars (mk_apply t1 t2) sub,\n    {w1 : wf_term t1\n     & {w2 : wf_term t2\n     & {c1 : cover_vars t1 sub\n     & {c2 : cover_vars t2 sub\n        & lsubstc (mk_apply t1 t2) w sub c\n             = mkc_apply (lsubstc t1 w1 sub c1)\n                         (lsubstc t2 w2 sub c2)}}}}.\nProof.\n  sp.\n\n  assert (wf_term t1) as w1.\n  { allrw <- @wf_apply_iff; sp. }\n\n  assert (wf_term t2) as w2.\n  { allrw <- @wf_apply_iff; sp. }\n\n  assert (cover_vars t1 sub) as c1.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  assert (cover_vars t2 sub) as c2.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists w1 w2 c1 c2.\n  apply lsubstc_mk_apply.\nQed.\n\nLemma lsubstc_mk_apply2 {p} :\n  forall t1 t2 t3 sub,\n  forall w1 : wf_term t1,\n  forall w2 : wf_term t2,\n  forall w3 : @wf_term p t3,\n  forall w  : wf_term (mk_apply2 t1 t2 t3),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars t2 sub,\n  forall c3 : cover_vars t3 sub,\n  forall c  : cover_vars (mk_apply2 t1 t2 t3) sub,\n    lsubstc (mk_apply2 t1 t2 t3) w sub c\n    = mkc_apply2 (lsubstc t1 w1 sub c1)\n                 (lsubstc t2 w2 sub c2)\n                 (lsubstc t3 w3 sub c3).\nProof.\n  unfold mk_apply2; sp.\n  rw @mkc_apply2_eq.\n\n  assert (wf_term (mk_apply t1 t2)) as w12 by (apply wf_apply; sp).\n\n  assert (cover_vars (mk_apply t1 t2) sub) as c12 by (rw @cover_vars_apply; sp).\n\n  rewrite @lsubstc_mk_apply with (w1 := w12) (w2 := w3) (c1 := c12) (c2 := c3); sp.\n  rewrite @lsubstc_mk_apply with (w1 := w1) (w2 := w2) (c1 := c1) (c2 := c2); sp.\nQed.\n\nLemma lsubstc_mk_apply2_ex {p} :\n  forall t1 t2 t3 sub,\n  forall w  : wf_term (@mk_apply2 p t1 t2 t3),\n  forall c  : cover_vars (mk_apply2 t1 t2 t3) sub,\n    {w1 : wf_term t1\n     & {w2 : wf_term t2\n     & {w3 : wf_term t3\n     & {c1 : cover_vars t1 sub\n     & {c2 : cover_vars t2 sub\n     & {c3 : cover_vars t3 sub\n        & lsubstc (mk_apply2 t1 t2 t3) w sub c\n          = mkc_apply2 (lsubstc t1 w1 sub c1)\n                       (lsubstc t2 w2 sub c2)\n                       (lsubstc t3 w3 sub c3)}}}}}}.\nProof.\n  sp.\n\n  assert (wf_term t1) as w1.\n  { allrw <- @wf_apply2_iff; sp. }\n\n  assert (wf_term t2) as w2.\n  { allrw <- @wf_apply2_iff; sp. }\n\n  assert (wf_term t3) as w3.\n  { allrw <- @wf_apply2_iff; sp. }\n\n  assert (cover_vars t1 sub) as c1.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  assert (cover_vars t2 sub) as c2.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  assert (cover_vars t3 sub) as c3.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists w1 w2 w3 c1 c2 c3.\n  apply lsubstc_mk_apply2.\nQed.\n\nLemma isprog_vars_csubst {p} :\n  forall t   : NTerm,\n  forall sub : @CSub p,\n  forall vs  : list NVar,\n    wf_term t\n    -> cover_vars_upto t sub vs\n    -> isprog_vars vs (csubst t sub).\nProof.\n  introv wf cv.\n  apply isprog_vars_eq.\n  unfold cover_vars_upto in cv.\n  rw @free_vars_csubst.\n  rw @dom_csub_eq.\n  rw @subvars_remove_nvars.\n  dands; auto.\n  allrw @wf_term_eq.\n  unfold csubst.\n  apply lsubst_wf_if_eauto; auto.\nQed.\n\nLemma csubst_var_not_in {p} :\n  forall v sub,\n    ! LIn v (dom_csub sub)\n    -> csubst (mk_var v) sub = @mk_var p v.\nProof.\n  intros.\n  unfold csubst; simpl.\n  rw <- @dom_csub_eq in H.\n  rw <- @sub_find_none_iff in H.\n  change_to_lsubst_aux4; simpl.\n  rw H; sp.\nQed.\n\nDefinition lsubstc_vars {p}\n           (t   : NTerm)\n           (w   : wf_term t)\n           (sub : @CSub p)\n           (vs  : list NVar)\n           (p   : cover_vars_upto t sub vs) : CVTerm vs :=\n  exist (isprog_vars vs)\n        (csubst t sub)\n        (isprog_vars_csubst t sub vs w p).\n\nLemma lsubstc_vars_var_not_in {p} :\n  forall v sub w c,\n    lsubstc_vars (mk_var v) w (csub_filter sub [v]) [v] c\n    = @mkc_var p v.\nProof.\n  introv.\n  apply cvterm_eq; simpl.\n  apply csubst_var_not_in.\n  rw @dom_csub_csub_filter; rw in_remove_nvars; simpl; tcsp.\nQed.\n\nLemma lsubstc_vars_mk_axiom {p} :\n  forall sub w v,\n  forall c : cover_vars_upto mk_axiom sub [v],\n    lsubstc_vars mk_axiom w sub [v] c\n    = @mkcv_axiom p v.\nProof.\n  introv; apply cvterm_eq; simpl; auto.\nQed.\n\nLemma lsubstc_mk_cbv {p} :\n  forall t1 v t2 sub,\n  forall w1 : wf_term t1,\n  forall w2 : @wf_term p t2,\n  forall w  : wf_term (mk_cbv t1 v t2),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars_upto t2 (csub_filter sub [v]) [v],\n  forall c  : cover_vars (mk_cbv t1 v t2) sub,\n    lsubstc (mk_cbv t1 v t2) w sub c\n    = mkc_cbv (lsubstc t1 w1 sub c1)\n              v\n              (lsubstc_vars t2 w2 (csub_filter sub [v]) [v] c2).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd.\n  rw @sub_filter_csub2sub.\n  rw @fold_cbv; sp.\nQed.\n\nLemma lsubstc_mk_cbv_ex {p} :\n  forall t1 v t2 sub,\n  forall w  : wf_term (@mk_cbv p t1 v t2),\n  forall c  : cover_vars (mk_cbv t1 v t2) sub,\n    {w1 : wf_term t1\n     & {w2 : wf_term t2\n     & {c1 : cover_vars t1 sub\n     & {c2 : cover_vars_upto t2 (csub_filter sub [v]) [v]\n        & lsubstc (mk_cbv t1 v t2) w sub c\n             = mkc_cbv (lsubstc t1 w1 sub c1)\n                       v\n                       (lsubstc_vars t2 w2 (csub_filter sub [v]) [v] c2)}}}}.\nProof.\n  sp.\n\n  duplicate w.\n  rw <- @wf_cbv_iff in w; sp.\n\n  duplicate c.\n  rw @cover_vars_cbv in c; sp.\n\n  exists w1 w c1 c.\n  apply lsubstc_mk_cbv.\nQed.\n\nLemma lsubstc_mk_halts {p} :\n  forall t sub,\n  forall wt : @wf_term p t,\n  forall w  : wf_term (mk_halts t),\n  forall ct : cover_vars t sub,\n  forall c  : cover_vars (mk_halts t) sub,\n    lsubstc (mk_halts t) w sub c\n    = mkc_halts (lsubstc t wt sub ct).\nProof.\n  unfold mk_halts; sp.\n  rw <- @fold_mkc_halts.\n  generalize (lsubstc_mk_approx_ex\n                mk_axiom\n                (mk_cbv t nvarx mk_axiom)\n                sub\n                w\n                c); sp.\n  rw e; clear e.\n  rw @lsubstc_mk_axiom.\n  generalize (lsubstc_mk_cbv_ex\n                t nvarx mk_axiom\n                sub\n                w2 c2); sp.\n  rw e; clear e.\n  rewrite @lsubstc_replace with (w2 := wt) (p2 := ct).\n  rw @lsubstc_vars_mk_axiom; sp.\nQed.\n\nLemma lsubstc_mk_halts_ex {p} :\n  forall t sub,\n  forall w  : wf_term (@mk_halts p t),\n  forall c  : cover_vars (mk_halts t) sub,\n    {wt : wf_term t\n     & {ct : cover_vars t sub\n        & lsubstc (mk_halts t) w sub c\n             = mkc_halts (lsubstc t wt sub ct)}}.\nProof.\n  sp.\n  duplicate w; duplicate c.\n  rw <- @wf_halts_iff in w.\n  rw @cover_vars_halts in c.\n  exists w c.\n  apply lsubstc_mk_halts.\nQed.\n\nLemma lsubstc_mk_spread {p} :\n  forall t1 x y t2 sub,\n  forall w1 : wf_term t1,\n  forall w2 : @wf_term p t2,\n  forall w  : wf_term (mk_spread t1 x y t2),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars_upto t2 (csub_filter sub [x,y]) [x,y],\n  forall c  : cover_vars (mk_spread t1 x y t2) sub,\n    lsubstc (mk_spread t1 x y t2) w sub c\n    = mkc_spread (lsubstc t1 w1 sub c1)\n                 x y\n                 (lsubstc_vars t2 w2 (csub_filter sub [x,y]) [x,y] c2).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd.\n  rw @sub_filter_csub2sub.\n  rw @fold_spread; sp.\nQed.\n\nLemma lsubstc_mk_spread_ex {p} :\n  forall t1 x y t2 sub,\n  forall w  : wf_term (@mk_spread p t1 x y t2),\n  forall c  : cover_vars (mk_spread t1 x y t2) sub,\n    {w1 : wf_term t1\n     & {w2 : wf_term t2\n     & {c1 : cover_vars t1 sub\n     & {c2 : cover_vars_upto t2 (csub_filter sub [x,y]) [x,y]\n        & lsubstc (mk_spread t1 x y t2) w sub c\n          = mkc_spread (lsubstc t1 w1 sub c1)\n                       x y\n                       (lsubstc_vars t2 w2 (csub_filter sub [x,y]) [x,y] c2)}}}}.\nProof.\n  sp.\n\n  duplicate w.\n  rw @wf_spread in w; sp.\n\n  duplicate c.\n  rw @cover_vars_spread in c; sp.\n\n  exists w1 w c1 c.\n  apply lsubstc_mk_spread.\nQed.\n\nLemma lsubstc_mk_function {p} :\n  forall t1 v t2 sub,\n  forall w1 : wf_term t1,\n  forall w2 : @wf_term p t2,\n  forall w  : wf_term (mk_function t1 v t2),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars_upto t2 (csub_filter sub [v]) [v],\n  forall c  : cover_vars (mk_function t1 v t2) sub,\n    lsubstc (mk_function t1 v t2) w sub c\n    = mkc_function (lsubstc t1 w1 sub c1)\n              v\n              (lsubstc_vars t2 w2 (csub_filter sub [v]) [v] c2).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd.\n  rw @sub_filter_csub2sub.\n  rw @fold_function; sp.\nQed.\n\nLemma lsubstc_mk_function_ex {p} :\n  forall t1 v t2 sub,\n  forall w  : wf_term (@mk_function p t1 v t2),\n  forall c  : cover_vars (mk_function t1 v t2) sub,\n    {w1 : wf_term t1\n     & {w2 : wf_term t2\n     & {c1 : cover_vars t1 sub\n     & {c2 : cover_vars_upto t2 (csub_filter sub [v]) [v]\n        & lsubstc (mk_function t1 v t2) w sub c\n             = mkc_function (lsubstc t1 w1 sub c1)\n                            v\n                            (lsubstc_vars t2 w2 (csub_filter sub [v]) [v] c2)}}}}.\nProof.\n  sp.\n\n  duplicate w.\n  rw <- @wf_function_iff in w; sp.\n\n  duplicate c.\n  rw @cover_vars_function in c; sp.\n\n  exists w1 w c1 c.\n  apply lsubstc_mk_function.\nQed.\n\nLemma lsubstc_mk_product {p} :\n  forall t1 v t2 sub,\n  forall w1 : wf_term t1,\n  forall w2 : @wf_term p t2,\n  forall w  : wf_term (mk_product t1 v t2),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars_upto t2 (csub_filter sub [v]) [v],\n  forall c  : cover_vars (mk_product t1 v t2) sub,\n    lsubstc (mk_product t1 v t2) w sub c\n    = mkc_product (lsubstc t1 w1 sub c1)\n                  v\n                  (lsubstc_vars t2 w2 (csub_filter sub [v]) [v] c2).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd.\n  rw @sub_filter_csub2sub.\n  rw @fold_product; sp.\nQed.\n\nLemma lsubstc_mk_product_ex {p} :\n  forall t1 v t2 sub,\n  forall w  : wf_term (@mk_product p t1 v t2),\n  forall c  : cover_vars (mk_product t1 v t2) sub,\n    {w1 : wf_term t1\n     & {w2 : wf_term t2\n     & {c1 : cover_vars t1 sub\n     & {c2 : cover_vars_upto t2 (csub_filter sub [v]) [v]\n        & lsubstc (mk_product t1 v t2) w sub c\n             = mkc_product (lsubstc t1 w1 sub c1)\n                            v\n                            (lsubstc_vars t2 w2 (csub_filter sub [v]) [v] c2)}}}}.\nProof.\n  sp.\n\n  duplicate w.\n  rw <- @wf_product_iff in w; sp.\n\n  duplicate c.\n  rw @cover_vars_product in c; sp.\n\n  exists w1 w c1 c.\n  apply lsubstc_mk_product.\nQed.\n\nLemma lsubstc_mk_isect {p} :\n  forall t1 v t2 sub,\n  forall w1 : wf_term t1,\n  forall w2 : @wf_term p t2,\n  forall w  : wf_term (mk_isect t1 v t2),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars_upto t2 (csub_filter sub [v]) [v],\n  forall c  : cover_vars (mk_isect t1 v t2) sub,\n    lsubstc (mk_isect t1 v t2) w sub c\n    = mkc_isect (lsubstc t1 w1 sub c1)\n                v\n                (lsubstc_vars t2 w2 (csub_filter sub [v]) [v] c2).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd.\n  rw @sub_filter_csub2sub.\n  rw @fold_isect; sp.\nQed.\n\nLemma lsubstc_mk_isect_ex {p} :\n  forall t1 v t2 sub,\n  forall w  : wf_term (@mk_isect p t1 v t2),\n  forall c  : cover_vars (mk_isect t1 v t2) sub,\n    {w1 : wf_term t1\n     & {w2 : wf_term t2\n     & {c1 : cover_vars t1 sub\n     & {c2 : cover_vars_upto t2 (csub_filter sub [v]) [v]\n        & lsubstc (mk_isect t1 v t2) w sub c\n             = mkc_isect (lsubstc t1 w1 sub c1)\n                         v\n                         (lsubstc_vars t2 w2 (csub_filter sub [v]) [v] c2)}}}}.\nProof.\n  sp.\n\n  duplicate w.\n  rw <- @wf_isect_iff in w; sp.\n\n  duplicate c.\n  rw @cover_vars_isect in c; sp.\n\n  exists w1 w c1 c.\n  apply lsubstc_mk_isect.\nQed.\n\nLemma lsubstc_mk_top {o} :\n  forall p sub c,\n    lsubstc mk_top p sub c = @mkc_top o.\nProof.\n  introv.\n  unfold mk_top, mkc_top.\n  generalize (lsubstc_mk_isect_ex\n                mk_false nvarx mk_false sub p c); intro k; exrepnd.\n  rw k1.\n  rw @lsubstc_mk_false.\n  assert (mk_cv [nvarx] mkc_false\n          = lsubstc_vars mk_false w2 (csub_filter sub [nvarx]) [nvarx] c2)\n    as eq by (apply cvterm_eq; simpl; rw @csubst_mk_false; sp).\n  rw <- eq; sp.\nQed.\n\nLemma lsubstc_mk_uall {p} :\n  forall t1 v t2 sub,\n  forall w1 : wf_term t1,\n  forall w2 : @wf_term p t2,\n  forall w  : wf_term (mk_uall t1 v t2),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars_upto t2 (csub_filter sub [v]) [v],\n  forall c  : cover_vars (mk_uall t1 v t2) sub,\n    lsubstc (mk_uall t1 v t2) w sub c\n    = mkc_uall (lsubstc t1 w1 sub c1)\n                v\n                (lsubstc_vars t2 w2 (csub_filter sub [v]) [v] c2).\nProof.\n  introv.\n  apply lsubstc_mk_isect.\nQed.\n\nLemma lsubstc_mk_uall_ex {p} :\n  forall t1 v t2 sub,\n  forall w  : wf_term (@mk_uall p t1 v t2),\n  forall c  : cover_vars (mk_uall t1 v t2) sub,\n    {w1 : wf_term t1\n     & {w2 : wf_term t2\n     & {c1 : cover_vars t1 sub\n     & {c2 : cover_vars_upto t2 (csub_filter sub [v]) [v]\n        & lsubstc (mk_uall t1 v t2) w sub c\n             = mkc_uall (lsubstc t1 w1 sub c1)\n                         v\n                         (lsubstc_vars t2 w2 (csub_filter sub [v]) [v] c2)}}}}.\nProof.\n  sp.\n  apply lsubstc_mk_isect_ex.\nQed.\n\nLemma lsubstc_mk_disect {p} :\n  forall t1 v t2 sub,\n  forall w1 : wf_term t1,\n  forall w2 : @wf_term p t2,\n  forall w  : wf_term (mk_disect t1 v t2),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars_upto t2 (csub_filter sub [v]) [v],\n  forall c  : cover_vars (mk_disect t1 v t2) sub,\n    lsubstc (mk_disect t1 v t2) w sub c\n    = mkc_disect (lsubstc t1 w1 sub c1)\n                 v\n                 (lsubstc_vars t2 w2 (csub_filter sub [v]) [v] c2).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd.\n  rw @sub_filter_csub2sub.\n  rw @fold_disect; sp.\nQed.\n\nLemma lsubstc_mk_disect_ex {p} :\n  forall t1 v t2 sub,\n  forall w  : wf_term (@mk_disect p t1 v t2),\n  forall c  : cover_vars (mk_disect t1 v t2) sub,\n    {w1 : wf_term t1\n     & {w2 : wf_term t2\n     & {c1 : cover_vars t1 sub\n     & {c2 : cover_vars_upto t2 (csub_filter sub [v]) [v]\n        & lsubstc (mk_disect t1 v t2) w sub c\n             = mkc_disect (lsubstc t1 w1 sub c1)\n                         v\n                         (lsubstc_vars t2 w2 (csub_filter sub [v]) [v] c2)}}}}.\nProof.\n  sp.\n\n  duplicate w.\n  rw <- @wf_disect_iff in w; sp.\n\n  duplicate c.\n  rw @cover_vars_disect in c; sp.\n\n  exists w1 w c1 c.\n  apply lsubstc_mk_disect.\nQed.\n\nLemma lsubstc_mk_eisect {p} :\n  forall t1 v t2 sub,\n  forall w1 : wf_term t1,\n  forall w2 : @wf_term p t2,\n  forall w  : wf_term (mk_eisect t1 v t2),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars_upto t2 (csub_filter sub [v]) [v],\n  forall c  : cover_vars (mk_eisect t1 v t2) sub,\n    lsubstc (mk_eisect t1 v t2) w sub c\n    = mkc_eisect (lsubstc t1 w1 sub c1)\n                v\n                (lsubstc_vars t2 w2 (csub_filter sub [v]) [v] c2).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd.\n  rw @sub_filter_csub2sub.\n  rw @fold_eisect; sp.\nQed.\n\nLemma lsubstc_mk_eisect_ex {p} :\n  forall t1 v t2 sub,\n  forall w  : wf_term (@mk_eisect p t1 v t2),\n  forall c  : cover_vars (mk_eisect t1 v t2) sub,\n    {w1 : wf_term t1\n     & {w2 : wf_term t2\n     & {c1 : cover_vars t1 sub\n     & {c2 : cover_vars_upto t2 (csub_filter sub [v]) [v]\n        & lsubstc (mk_eisect t1 v t2) w sub c\n             = mkc_eisect (lsubstc t1 w1 sub c1)\n                          v\n                          (lsubstc_vars t2 w2 (csub_filter sub [v]) [v] c2)}}}}.\nProof.\n  sp.\n\n  duplicate w.\n  rw <- @wf_eisect_iff in w; sp.\n\n  duplicate c.\n  rw @cover_vars_eisect in c; sp.\n\n  exists w1 w c1 c.\n  apply lsubstc_mk_eisect.\nQed.\n\nLemma lsubstc_mk_set {p} :\n  forall t1 v t2 sub,\n  forall w1 : wf_term t1,\n  forall w2 : @wf_term p t2,\n  forall w  : wf_term (mk_set t1 v t2),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars_upto t2 (csub_filter sub [v]) [v],\n  forall c  : cover_vars (mk_set t1 v t2) sub,\n    lsubstc (mk_set t1 v t2) w sub c\n    = mkc_set (lsubstc t1 w1 sub c1)\n              v\n              (lsubstc_vars t2 w2 (csub_filter sub [v]) [v] c2).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd.\n  rw @sub_filter_csub2sub.\n  rw @fold_set; sp.\nQed.\n\nLemma lsubstc_mk_set_ex {p} :\n  forall t1 v t2 sub,\n  forall w  : wf_term (@mk_set p t1 v t2),\n  forall c  : cover_vars (mk_set t1 v t2) sub,\n    {w1 : wf_term t1\n     & {w2 : wf_term t2\n     & {c1 : cover_vars t1 sub\n     & {c2 : cover_vars_upto t2 (csub_filter sub [v]) [v]\n        & lsubstc (mk_set t1 v t2) w sub c\n             = mkc_set (lsubstc t1 w1 sub c1)\n                       v\n                       (lsubstc_vars t2 w2 (csub_filter sub [v]) [v] c2)}}}}.\nProof.\n  sp.\n\n  duplicate w.\n  rw <- @wf_set_iff in w; sp.\n\n  duplicate c.\n  rw @cover_vars_set in c; sp.\n\n  exists w1 w c1 c.\n  apply lsubstc_mk_set.\nQed.\n\nLemma lsubstc_mk_tunion {p} :\n  forall t1 v t2 sub,\n  forall w1 : wf_term t1,\n  forall w2 : @wf_term p t2,\n  forall w  : wf_term (mk_tunion t1 v t2),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars_upto t2 (csub_filter sub [v]) [v],\n  forall c  : cover_vars (mk_tunion t1 v t2) sub,\n    lsubstc (mk_tunion t1 v t2) w sub c\n    = mkc_tunion (lsubstc t1 w1 sub c1)\n              v\n              (lsubstc_vars t2 w2 (csub_filter sub [v]) [v] c2).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd.\n  rw @sub_filter_csub2sub.\n  rw @fold_tunion; sp.\nQed.\n\nLemma lsubstc_mk_tunion_ex {p} :\n  forall t1 v t2 sub,\n  forall w  : wf_term (@mk_tunion p t1 v t2),\n  forall c  : cover_vars (mk_tunion t1 v t2) sub,\n    {w1 : wf_term t1\n     & {w2 : wf_term t2\n     & {c1 : cover_vars t1 sub\n     & {c2 : cover_vars_upto t2 (csub_filter sub [v]) [v]\n        & lsubstc (mk_tunion t1 v t2) w sub c\n             = mkc_tunion (lsubstc t1 w1 sub c1)\n                       v\n                       (lsubstc_vars t2 w2 (csub_filter sub [v]) [v] c2)}}}}.\nProof.\n  sp.\n\n  duplicate w.\n  rw <- @wf_tunion_iff in w; sp.\n\n  duplicate c.\n  rw @cover_vars_tunion in c; sp.\n\n  exists w1 w c1 c.\n  apply lsubstc_mk_tunion.\nQed.\n\nLemma lsubstc_mk_quotient {p} :\n  forall t1 v1 v2 t2 sub,\n  forall w1 : wf_term t1,\n  forall w2 : @wf_term p t2,\n  forall w  : wf_term (mk_quotient t1 v1 v2 t2),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars_upto t2 (csub_filter sub [v1,v2]) [v1,v2],\n  forall c  : cover_vars (mk_quotient t1 v1 v2 t2) sub,\n    lsubstc (mk_quotient t1 v1 v2 t2) w sub c\n    = mkc_quotient (lsubstc t1 w1 sub c1)\n                   v1 v2\n                   (lsubstc_vars t2 w2 (csub_filter sub [v1,v2]) [v1,v2] c2).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd.\n  rw @sub_filter_csub2sub.\n  rw @fold_quotient; sp.\nQed.\n\nLemma lsubstc_mk_quotient_ex {p} :\n  forall t1 v1 v2 t2 sub,\n  forall w  : wf_term (@mk_quotient p t1 v1 v2 t2),\n  forall c  : cover_vars (mk_quotient t1 v1 v2 t2) sub,\n    {w1 : wf_term t1\n     & {w2 : wf_term t2\n     & {c1 : cover_vars t1 sub\n     & {c2 : cover_vars_upto t2 (csub_filter sub [v1,v2]) [v1,v2]\n        & lsubstc (mk_quotient t1 v1 v2 t2) w sub c\n             = mkc_quotient (lsubstc t1 w1 sub c1)\n                            v1 v2\n                            (lsubstc_vars t2 w2 (csub_filter sub [v1,v2]) [v1,v2] c2)}}}}.\nProof.\n  sp.\n\n  duplicate w.\n  rw <- @wf_quotient_iff in w; sp.\n\n  duplicate c.\n  rw @cover_vars_quotient in c; sp.\n\n  exists w1 w c1 c.\n  apply lsubstc_mk_quotient.\nQed.\n\nLemma lsubstc_mk_w {p} :\n  forall t1 v t2 sub,\n  forall w1 : wf_term t1,\n  forall w2 : @wf_term p t2,\n  forall w  : wf_term (mk_w t1 v t2),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars_upto t2 (csub_filter sub [v]) [v],\n  forall c  : cover_vars (mk_w t1 v t2) sub,\n    lsubstc (mk_w t1 v t2) w sub c\n    = mkc_w\n        (lsubstc t1 w1 sub c1)\n        v\n        (lsubstc_vars t2 w2 (csub_filter sub [v]) [v] c2).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd.\n  rw @sub_filter_csub2sub.\n  rw @fold_w; sp.\nQed.\n\nLemma lsubstc_mk_w_ex {p} :\n  forall t1 v t2 sub,\n  forall w : wf_term (@mk_w p t1 v t2),\n  forall c : cover_vars (mk_w t1 v t2) sub,\n    {w1 : wf_term t1\n     & {w2 : wf_term t2\n     & {c1 : cover_vars t1 sub\n     & {c2 : cover_vars_upto t2 (csub_filter sub [v]) [v]\n     & lsubstc (mk_w t1 v t2) w sub c\n       = mkc_w (lsubstc t1 w1 sub c1)\n               v\n               (lsubstc_vars t2 w2 (csub_filter sub [v]) [v] c2)}}}}.\nProof.\n  sp.\n\n  duplicate w.\n  rw <- @wf_w_iff in w; sp.\n\n  duplicate c.\n  rw @cover_vars_w in c; sp.\n\n  exists w1 w c1 c.\n  apply lsubstc_mk_w.\nQed.\n\nLemma lsubstc_mk_m {p} :\n  forall t1 v t2 sub,\n  forall w1 : wf_term t1,\n  forall w2 : @wf_term p t2,\n  forall w  : wf_term (mk_m t1 v t2),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars_upto t2 (csub_filter sub [v]) [v],\n  forall c  : cover_vars (mk_m t1 v t2) sub,\n    lsubstc (mk_m t1 v t2) w sub c\n    = mkc_m\n        (lsubstc t1 w1 sub c1)\n        v\n        (lsubstc_vars t2 w2 (csub_filter sub [v]) [v] c2).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd.\n  rw @sub_filter_csub2sub.\n  rw @fold_m; sp.\nQed.\n\nLemma lsubstc_mk_m_ex {p} :\n  forall t1 v t2 sub,\n  forall w : wf_term (@mk_m p t1 v t2),\n  forall c : cover_vars (mk_m t1 v t2) sub,\n    {w1 : wf_term t1\n     & {w2 : wf_term t2\n     & {c1 : cover_vars t1 sub\n     & {c2 : cover_vars_upto t2 (csub_filter sub [v]) [v]\n     & lsubstc (mk_m t1 v t2) w sub c\n       = mkc_m (lsubstc t1 w1 sub c1)\n               v\n               (lsubstc_vars t2 w2 (csub_filter sub [v]) [v] c2)}}}}.\nProof.\n  sp.\n\n  duplicate w.\n  rw <- @wf_m_iff in w; sp.\n\n  duplicate c.\n  rw @cover_vars_m in c; sp.\n\n  exists w1 w c1 c.\n  apply lsubstc_mk_m.\nQed.\n\nLemma lsubstc_mk_pw {o} :\n  forall P ap A bp ba B cp ca cb C p sub,\n  forall wP : wf_term P,\n  forall wA : wf_term A,\n  forall wB : wf_term B,\n  forall wC : wf_term C,\n  forall wp : @wf_term o p,\n  forall w  : wf_term (mk_pw P ap A bp ba B cp ca cb C p),\n  forall cvP : cover_vars P sub,\n  forall cvA : cover_vars_upto A (csub_filter sub [ap]) [ap],\n  forall cvB : cover_vars_upto B (csub_filter sub [bp,ba]) [bp,ba],\n  forall cvC : cover_vars_upto C (csub_filter sub [cp,ca,cb]) [cp,ca,cb],\n  forall cvp : cover_vars p sub,\n  forall cv  : cover_vars (mk_pw P ap A bp ba B cp ca cb C p) sub,\n    lsubstc (mk_pw P ap A bp ba B cp ca cb C p) w sub cv\n    = mkc_pw\n        (lsubstc P wP sub cvP)\n        ap\n        (lsubstc_vars A wA (csub_filter sub [ap]) [ap] cvA)\n        bp ba\n        (lsubstc_vars B wB (csub_filter sub [bp,ba]) [bp,ba] cvB)\n        cp ca cb\n        (lsubstc_vars C wC (csub_filter sub [cp,ca,cb]) [cp,ca,cb] cvC)\n        (lsubstc p wp sub cvp).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  allrw @sub_filter_nil_r; allrw @fold_nobnd.\n  allrw @sub_filter_csub2sub.\n  rw @fold_pw; sp.\nQed.\n\nLemma lsubstc_mk_pw_ex {o} :\n  forall P ap A bp ba B cp ca cb C p sub,\n  forall w : wf_term (@mk_pw o P ap A bp ba B cp ca cb C p),\n  forall c : cover_vars (mk_pw P ap A bp ba B cp ca cb C p) sub,\n    {wP : wf_term P\n     & {wA : wf_term A\n     & {wB : wf_term B\n     & {wC : wf_term C\n     & {wp : wf_term p\n     & {cvP : cover_vars P sub\n     & {cvA : cover_vars_upto A (csub_filter sub [ap]) [ap]\n     & {cvB : cover_vars_upto B (csub_filter sub [bp,ba]) [bp,ba]\n     & {cvC : cover_vars_upto C (csub_filter sub [cp,ca,cb]) [cp,ca,cb]\n     & {cvp : cover_vars p sub\n     & lsubstc (mk_pw P ap A bp ba B cp ca cb C p) w sub c\n       = mkc_pw\n           (lsubstc P wP sub cvP)\n           ap\n           (lsubstc_vars A wA (csub_filter sub [ap]) [ap] cvA)\n           bp ba\n           (lsubstc_vars B wB (csub_filter sub [bp,ba]) [bp,ba] cvB)\n           cp ca cb\n           (lsubstc_vars C wC (csub_filter sub [cp,ca,cb]) [cp,ca,cb] cvC)\n           (lsubstc p wp sub cvp)}}}}}}}}}}.\nProof.\n  sp.\n\n  duplicate w.\n  apply wf_pw_iff in w; sp.\n\n  duplicate c.\n  apply cover_vars_pw in c; sp.\n\n  exists w1 w2 w3 w4 w.\n  exists c1 c2 c3 c4 c.\n  apply lsubstc_mk_pw.\nQed.\n\nLemma lsubstc_mk_pm {o} :\n  forall P ap A bp ba B cp ca cb C p sub,\n  forall wP : wf_term P,\n  forall wA : wf_term A,\n  forall wB : wf_term B,\n  forall wC : wf_term C,\n  forall wp : @wf_term o p,\n  forall w  : wf_term (mk_pm P ap A bp ba B cp ca cb C p),\n  forall cvP : cover_vars P sub,\n  forall cvA : cover_vars_upto A (csub_filter sub [ap]) [ap],\n  forall cvB : cover_vars_upto B (csub_filter sub [bp,ba]) [bp,ba],\n  forall cvC : cover_vars_upto C (csub_filter sub [cp,ca,cb]) [cp,ca,cb],\n  forall cvp : cover_vars p sub,\n  forall cv  : cover_vars (mk_pm P ap A bp ba B cp ca cb C p) sub,\n    lsubstc (mk_pm P ap A bp ba B cp ca cb C p) w sub cv\n    = mkc_pm\n        (lsubstc P wP sub cvP)\n        ap\n        (lsubstc_vars A wA (csub_filter sub [ap]) [ap] cvA)\n        bp ba\n        (lsubstc_vars B wB (csub_filter sub [bp,ba]) [bp,ba] cvB)\n        cp ca cb\n        (lsubstc_vars C wC (csub_filter sub [cp,ca,cb]) [cp,ca,cb] cvC)\n        (lsubstc p wp sub cvp).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  allrw @sub_filter_nil_r; allrw @fold_nobnd.\n  allrw @sub_filter_csub2sub; sp.\nQed.\n\nLemma lsubstc_mk_pm_ex {o} :\n  forall P ap A bp ba B cp ca cb C p sub,\n  forall w : wf_term (@mk_pm o P ap A bp ba B cp ca cb C p),\n  forall c : cover_vars (mk_pm P ap A bp ba B cp ca cb C p) sub,\n    {wP : wf_term P\n     & {wA : wf_term A\n     & {wB : wf_term B\n     & {wC : wf_term C\n     & {wp : wf_term p\n     & {cvP : cover_vars P sub\n     & {cvA : cover_vars_upto A (csub_filter sub [ap]) [ap]\n     & {cvB : cover_vars_upto B (csub_filter sub [bp,ba]) [bp,ba]\n     & {cvC : cover_vars_upto C (csub_filter sub [cp,ca,cb]) [cp,ca,cb]\n     & {cvp : cover_vars p sub\n     & lsubstc (mk_pm P ap A bp ba B cp ca cb C p) w sub c\n       = mkc_pm\n           (lsubstc P wP sub cvP)\n           ap\n           (lsubstc_vars A wA (csub_filter sub [ap]) [ap] cvA)\n           bp ba\n           (lsubstc_vars B wB (csub_filter sub [bp,ba]) [bp,ba] cvB)\n           cp ca cb\n           (lsubstc_vars C wC (csub_filter sub [cp,ca,cb]) [cp,ca,cb] cvC)\n           (lsubstc p wp sub cvp)}}}}}}}}}}.\nProof.\n  sp.\n\n  duplicate w.\n  apply wf_pm_iff in w; sp.\n\n  duplicate c.\n  apply cover_vars_pm in c; sp.\n\n  exists w1 w2 w3 w4 w.\n  exists c1 c2 c3 c4 c.\n  apply lsubstc_mk_pm.\nQed.\n\nLemma lsubstc_mk_lam {p} :\n  forall v b sub,\n  forall w1 : wf_term b,\n  forall w  : wf_term (mk_lam v b),\n  forall c1 : cover_vars_upto b (@csub_filter p sub [v]) [v],\n  forall c  : cover_vars (mk_lam v b) sub,\n    lsubstc (mk_lam v b) w sub c\n    = mkc_lam v (lsubstc_vars b w1 (csub_filter sub [v]) [v] c1).\nProof.\n  unfold lsubstc; simpl; sp.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_csub2sub.\n  rw @fold_lam; sp.\nQed.\n\nLemma lsubstc_mk_lam_ex {p} :\n  forall v b sub,\n  forall w  : wf_term (@mk_lam p v b),\n  forall c  : cover_vars (mk_lam v b) sub,\n    {w' : wf_term b\n     & {c' : cover_vars_upto b (csub_filter sub [v]) [v]\n        & lsubstc (mk_lam v b) w sub c\n             = mkc_lam v (lsubstc_vars b w' (csub_filter sub [v]) [v] c')}}.\nProof.\n  sp.\n\n  duplicate w.\n  rw <- @wf_lam_iff in w; sp.\n\n  duplicate c.\n  rw @cover_vars_lam in c; sp.\n\n  exists w c.\n  apply lsubstc_mk_lam.\nQed.\n\nLemma lsubstc_mk_id {p} :\n  forall sub w c,\n    lsubstc mk_id w sub c = @mkc_id p.\nProof.\n  sp.\n  unfold mkc_id, mk_id.\n  generalize (lsubstc_mk_lam_ex nvarx (mk_var nvarx) sub w c); sp.\n  rw e; clear e.\n  rw @lsubstc_vars_var_not_in; sp.\nQed.\n\nLemma lsubstc_mk_subtype {p} :\n  forall t1 t2 sub,\n  forall w1 : wf_term t1,\n  forall w2 : @wf_term p t2,\n  forall w  : wf_term (mk_subtype t1 t2),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars t2 sub,\n  forall c  : cover_vars (mk_subtype t1 t2) sub,\n    lsubstc (mk_subtype t1 t2) w sub c\n    = mkc_vsubtype (lsubstc t1 w1 sub c1)\n                   (newvar t2)\n                   (lsubstc t2 w2 sub c2).\nProof.\n  unfold mk_subtype, mk_vsubtype; sp.\n\n  generalize (lsubstc_mk_member_ex\n                mk_id\n                (mk_function t1 (newvar t2) t2)\n                sub\n                w\n                c); sp.\n  allrw.\n\n  rw @lsubstc_mk_id.\n  rw <- @fold_mkc_vsubtype.\n\n  generalize (lsubstc_mk_function_ex\n                t1\n                (newvar t2)\n                t2\n                sub\n                wT\n                cT); sp.\n  allrw; clear_irr.\n\n  assert (lsubstc_vars t2 w2 (csub_filter sub [newvar t2]) [newvar t2] c3\n          = cvterm_var (newvar t2) (lsubstc t2 w2 sub c2)) as eq;\n    try (rw eq; auto).\n\n  apply cvterm_eq; simpl.\n  apply csubst_csub_filter; allrw disjoint_singleton_r.\n  apply newvar_prop.\nQed.\n\nLemma lsubstc_mk_subtype_ex {p} :\n  forall t1 t2 sub,\n  forall w  : wf_term (@mk_subtype p t1 t2),\n  forall c  : cover_vars (mk_subtype t1 t2) sub,\n    {w1 : wf_term t1\n     & {w2 : wf_term t2\n     & {c1 : cover_vars t1 sub\n     & {c2 : cover_vars t2 sub\n        & lsubstc (mk_subtype t1 t2) w sub c\n             = mkc_vsubtype (lsubstc t1 w1 sub c1)\n                            (newvar t2)\n                            (lsubstc t2 w2 sub c2)}}}}.\nProof.\n  sp.\n\n  duplicate w.\n  rw <- @wf_subtype_iff in w; sp.\n\n  duplicate c.\n  rw @cover_vars_subtype in c; sp.\n\n  exists w1 w c1 c.\n  apply lsubstc_mk_subtype.\nQed.\n\nLemma sp_lsubstc_mk_subtype {p} :\n  forall t1 t2 sub,\n  forall w1 : wf_term t1,\n  forall w2 : @wf_term p t2,\n  forall w  : wf_term (mk_subtype t1 t2),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars t2 sub,\n  forall c  : cover_vars (mk_subtype t1 t2) sub,\n    ! LIn nvarx (free_vars t2)\n    -> lsubstc (mk_subtype t1 t2) w sub c\n       = mkc_subtype (lsubstc t1 w1 sub c1)\n                     (lsubstc t2 w2 sub c2).\nProof.\n  intros.\n  generalize (lsubstc_mk_subtype_ex t1 t2 sub w c); sp; clear_irr.\n  allrw.\n  remember (lsubstc t1 w1 sub c1); clear Heqc0.\n  remember (lsubstc t2 w2 sub c2); clear Heqc3.\n  destruct c0, c3.\n  unfold mkc_subtype, mkc_vsubtype, mk_subtype.\n  rw @newvar_not_in_free_vars; sp.\n  assert (mk_vsubtype x nvarx x0 = mk_vsubtype x (newvar x0) x0).\n  rw @newvar_prog; sp.\n  apply cterm_eq; sp.\nQed.\n\nLemma sp_lsubstc_mk_subtype_ex {p} :\n  forall t1 t2 sub,\n  forall w  : wf_term (@mk_subtype p t1 t2),\n  forall c  : cover_vars (mk_subtype t1 t2) sub,\n    {w1 : wf_term t1\n     & {w2 : wf_term t2\n     & {c1 : cover_vars t1 sub\n     & {c2 : cover_vars t2 sub\n        & !LIn nvarx (free_vars t2)\n             -> lsubstc (mk_subtype t1 t2) w sub c\n                = mkc_subtype (lsubstc t1 w1 sub c1)\n                              (lsubstc t2 w2 sub c2)}}}}.\nProof.\n  sp.\n\n  duplicate w.\n  rw <- @wf_subtype_iff in w; sp.\n\n  duplicate c.\n  rw @cover_vars_subtype in c; sp.\n\n  exists w1 w c1 c.\n  apply sp_lsubstc_mk_subtype.\nQed.\n\nLemma subset_free_vars_csub_app {p} :\n  forall t sub1 sub2,\n    disjoint (free_vars t) (@dom_csub p sub2)\n    -> csubst t (sub1 ++ sub2) = csubst t sub1.\nProof.\n  unfold csubst; sp.\n  rw <- @csub2sub_app.\n  apply subset_free_vars_sub_app; sp.\n  allrw in_app_iff; sp; allapply @in_csub2sub; sp.\n  rw @dom_csub_eq; auto.\nQed.\n\nLemma subset_free_vars_csub_snoc {p} :\n  forall t sub v u,\n    ! LIn v (@free_vars p t)\n    -> csubst t (snoc sub (v,u)) = csubst t sub.\nProof.\n  intros.\n  rw snoc_as_append.\n  rw @subset_free_vars_csub_app; simpl; auto.\n  unfold disjoint; simpl; sp; subst; sp.\nQed.\n\nLemma subset_free_vars_csub_snoc_app {p} :\n  forall t sub1 sub2 v u,\n    ! LIn v (@free_vars p t)\n    -> csubst t (snoc sub1 (v,u) ++ sub2) = csubst t (sub1 ++ sub2).\nProof.\n  intros.\n  repeat (rw <- @csubst_app).\n  rw @subset_free_vars_csub_snoc; sp.\nQed.\n\nLemma cover_vars_app_disjoint {p} :\n  forall t sub1 sub2,\n    @cover_vars p t (sub1 ++ sub2)\n    -> disjoint (free_vars t) (dom_csub sub2)\n    -> cover_vars t sub1.\nProof.\n  sp.\n  allrw @cover_vars_eq.\n  rw @dom_csub_app in H.\n  allrw subvars_eq.\n  unfold subset; unfold subset in H; sp.\n  apply_in_hyp pp.\n  allrw in_app_iff; sp.\n  unfold disjoint in H0.\n  apply H0 in X; sp.\nQed.\n\nLemma cover_vars_snoc_disjoint {p} :\n  forall t sub v u,\n    @cover_vars p t (snoc sub (v,u))\n    -> ! LIn v (free_vars t)\n    -> cover_vars t sub.\nProof.\n  intros.\n  allrw snoc_as_append.\n  apply cover_vars_app_disjoint in H; sp.\n  simpl; unfold disjoint; simpl; sp; subst; sp.\nQed.\n\nLemma subset_free_vars_lsubstc_app {o} :\n  forall t sub1 sub2 p c,\n  forall d : disjoint (free_vars t) (@dom_csub o sub2),\n    lsubstc t p (sub1 ++ sub2) c\n    = lsubstc t p sub1 (cover_vars_app_disjoint t sub1 sub2 c d).\nProof.\n  unfold lsubstc; sp.\n  apply cterm_eq; simpl.\n  apply subset_free_vars_csub_app; sp.\nQed.\n\nLemma subset_free_vars_lsubstc_app_ex {o} :\n  forall t sub1 sub2 p c,\n  forall d : disjoint (free_vars t) (@dom_csub o sub2),\n    {c' : cover_vars t sub1\n     & lsubstc t p (sub1 ++ sub2) c\n          = lsubstc t p sub1 c'}.\nProof.\n  sp.\n  exists (cover_vars_app_disjoint t sub1 sub2 c d).\n  apply subset_free_vars_lsubstc_app.\nQed.\n\nLemma subset_free_vars_lsubstc_snoc {o} :\n  forall t sub v u p c,\n  forall d : ! LIn v (@free_vars o t),\n    lsubstc t p (snoc sub (v,u)) c\n    = lsubstc t p sub (cover_vars_snoc_disjoint t sub v u c d).\nProof.\n  unfold lsubstc; sp.\n  apply cterm_eq; simpl.\n  apply subset_free_vars_csub_snoc; auto.\nQed.\n\nLemma subset_free_vars_lsubstc_snoc_ex {o} :\n  forall t sub v u p c,\n  forall d : ! LIn v (@free_vars o t),\n    {c' : cover_vars t sub\n     & lsubstc t p (snoc sub (v,u)) c\n          = lsubstc t p sub c'}.\nProof.\n  sp.\n  exists (cover_vars_snoc_disjoint t sub v u c d).\n  apply subset_free_vars_lsubstc_snoc.\nQed.\n\nLemma csubst_snoc_var {o} :\n  forall sub v u,\n    ! LIn v (@dom_csub o sub)\n    -> csubst (mk_var v) (snoc sub (v,u)) = get_cterm u.\nProof.\n  intros.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw snoc_as_append.\n  rw <- @csub2sub_app; simpl.\n  rw @sub_find_app.\n  rw <- @dom_csub_eq in H.\n  rw <- @sub_find_none_iff in H.\n  rw H.\n  simpl.\n  rw <- beq_var_refl; auto.\nQed.\n\nLemma lsubstc_snoc_var {o} :\n  forall sub v u p c,\n    ! LIn v (@dom_csub o sub)\n    -> lsubstc (mk_var v) p (snoc sub (v,u)) c = u.\nProof.\n  unfold lsubstc; sp.\n\n  destruct u.\n\n  assert (exist (fun t : NTerm => isprog t) x i =\n          exist (fun t : NTerm => isprog t)\n                (get_cterm (exist (fun t : NTerm => isprog t) x i))\n                i) by (simpl; sp).\n\n  rw H0.\n\n  apply cterm_eq; simpl.\n  apply csubst_snoc_var; auto.\nQed.\n\nLemma csubst_snoc_var2 {p} :\n  forall x sub v u,\n    LIn x (@dom_csub p sub)\n    -> csubst (mk_var x) (snoc sub (v,u))\n       = csubst (mk_var x) sub.\nProof.\n  intros.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw snoc_as_append.\n  rw <- @csub2sub_app; simpl.\n  rw @sub_find_app.\n  allrw <- @dom_csub_eq.\n  allapply @in_dom_sub_exists; sp.\n  allrw; sp.\nQed.\n\nLemma lsubstc_snoc_var2 {o} :\n  forall x sub v u p c,\n  forall i : LIn x (@dom_csub o sub),\n    lsubstc (mk_var x) p (snoc sub (v,u)) c\n    = lsubstc (mk_var x) p sub (cover_vars_var x sub i).\nProof.\n  unfold lsubstc; sp.\n  apply cterm_eq; simpl.\n  apply csubst_snoc_var2; auto.\nQed.\n\nLemma lsubstc_snoc_var2_ex {o} :\n  forall x sub v u p c,\n  forall i : LIn x (@dom_csub o sub),\n    {c' : cover_vars (mk_var x) sub\n     & lsubstc (mk_var x) p (snoc sub (v,u)) c\n       = lsubstc (mk_var x) p sub c'}.\nProof.\n  intros.\n  exists (cover_vars_var x sub i).\n  apply lsubstc_snoc_var2.\nQed.\n\nLemma csubst_subst_snoc_eq {o} :\n  forall s b x y a,\n    !LIn y (bound_vars b)\n    -> !LIn y (@dom_csub o s)\n    -> (y <> x -> !LIn y (free_vars b))\n    -> csubst (subst b x (mk_var y)) (snoc s (y, a))\n       = csubst (csubst b (csub_filter s [x])) [(x, a)].\nProof.\n  introv niybb niys niyfb.\n  rewrite csubst_app.\n  unfold subst, csubst.\n  try (rw lsubstn_lsubst; try (complete (simpl; rw disjoint_singleton_r; sp))).\n  rewrite simple_lsubst_lsubst;\n    try (complete (sp; allapply @in_csub2sub; sp));\n    try (complete (simpl; sp; cpx; simpl; apply disjoint_singleton_l; auto)).\n  rewrite lsubst_sub_singleton.\n  rewrite fold_csubst.\n  rewrite csubst_snoc_var; auto.\n  rewrite <- csub2sub_app; simpl.\n  rewrite <- snoc_as_append.\n  rewrite <- lsubst_swap;\n    try (complete (sp; allapply @in_csub2sub; sp));\n    try (complete (rewrite @dom_csub_eq; rewrite @dom_csub_csub_filter; rw @in_remove_nvars; simpl; sp)).\n  repeat (rewrite <- csub2sub_cons).\n  repeat (rewrite fold_csubst).\n  destruct (eq_var_dec y x); subst.\n  (* if they're equal it's easy *)\n  rewrite csubst_cons_trim.\n  rewrite csub_filter_snoc1; sp.\n  (* if they're not: *)\n  rewrite <- csubst_csub_filter with (l := [y]);\n    try (complete (rw disjoint_sym; rw disjoint_singleton_l; sp)).\n  assert (x <> y) as d by auto; simpl.\n  apply memvar_singleton_diff_r in d; rewrite d.\n  rewrite csub_filter_snoc1; sp.\n  rewrite csubst_cons_trim.\n  rewrite <- csub_filter_app_r; simpl.\n  symmetry.\n  rewrite <- csubst_csub_filter with (l := [y]); simpl;\n    try (complete (rw disjoint_sym; rw disjoint_singleton_l; sp)).\n  rewrite d.\n  rewrite csub_filter_swap.\n  rewrite <- csub_filter_app_r; sp.\nQed.\n\nLemma csubst_subst_snoc_eq2 {o} :\n  forall s b x y a,\n    !LIn y (bound_vars b)\n    -> !LIn y (@dom_csub o s)\n    -> (y <> x -> !LIn y (free_vars b))\n    -> csubst (subst b x (mk_var y)) (snoc s (y, a))\n       = csubst b (snoc (csub_filter s [x]) (x, a)).\nProof.\n  introv niybb niys niyfb.\n  rw @csubst_subst_snoc_eq; sp.\n  rw @csubst_app.\n  rw snoc_as_append; sp.\nQed.\n\nLemma csubst_subst_snoc_eq3 {o} :\n  forall s b x y a,\n    !LIn y (bound_vars b)\n    -> !LIn y (@dom_csub o s)\n    -> (y <> x -> !LIn y (free_vars b))\n    -> csubst (subst b x (mk_var y)) (snoc s (y, a))\n       = csubst b ((x,a) :: s).\nProof.\n  introv niybb niys niyfb.\n  rw @csubst_subst_snoc_eq2; sp.\n  rw <- @csubst_swap.\n  rw <- @csubst_cons_trim; sp.\n  rw @dom_csub_csub_filter; rw in_remove_nvars; simpl; sp.\nQed.\n\nLemma lsubstc_subst_snoc_eq {o} :\n  forall s b x y a w1 w2 c1 c2,\n    !LIn y (bound_vars b)\n    -> !LIn y (@dom_csub o s)\n    -> (y <> x -> !LIn y (free_vars b))\n    -> lsubstc (subst b x (mk_var y)) w1 (snoc s (y, a)) c1\n       = substc a x (lsubstc_vars b w2 (csub_filter s [x]) [x] c2).\nProof.\n  intros.\n  rewrite substc_eq_lsubstc; simpl.\n  apply lsubstc_eq_if_csubst.\n  apply csubst_subst_snoc_eq; sp.\nQed.\n\nLemma simple_lsubstc_subst {o} :\n  forall t x B ws s cs wt ct wb cb,\n    disjoint (@free_vars o t) (bound_vars B)\n    -> lsubstc (subst B x t) ws s cs\n       = substc (lsubstc t wt s ct) x\n                (lsubstc_vars B wb (csub_filter s [x]) [x] cb).\nProof.\n  introv disj.\n  rw @substc_eq_lsubstc.\n  apply lsubstc_eq_if_csubst; simpl.\n\n  unfold csubst, subst; simpl.\n  allrw @fold_subst.\n  allrw @fold_csubst.\n\n  apply simple_csubst_subst; sp.\nQed.\n\nLemma isprog_vars_lsubst {o} :\n  forall vs t sub,\n    (forall t, LIn t (@range o sub) -> isprogram t)\n    -> isprog_vars (vs ++ dom_sub sub) t\n    -> isprog_vars vs (lsubst t sub).\nProof.\n  introv csub isp.\n  allrw @isprog_vars_eq; repnd.\n  allrw subvars_prop.\n  dands.\n\n  introv i.\n  rw @isprogram_lsubst2 in i.\n  allrw in_remove_nvars; repnd.\n  discover; allrw in_app_iff; sp.\n\n  introv j.\n  apply csub.\n  rw @in_range_iff; exists v; sp.\n\n  generalize (lsubst_wf_iff sub); intro e.\n  dest_imp e hyp.\n  apply prog_sub_implies_wf.\n  rw <- @prog_sub_eq; sp.\n  rw <- e; sp.\nQed.\n\nLemma isprog_vars_app_implies_isprog_vars_csubst {o} :\n  forall vs t sub,\n    isprog_vars (vs ++ @dom_csub o sub) t\n    -> isprog_vars vs (csubst t sub).\nProof.\n  introv isp.\n  unfold csubst.\n  apply isprog_vars_lsubst; sp.\n  allrw @in_range_iff; sp.\n  allapply @in_csub2sub; sp.\n  rw @dom_csub_eq; sp.\nQed.\n\nLemma isprog_vars_csubst_iff {o} :\n  forall vs t sub,\n    isprog_vars (vs ++ @dom_csub o sub) t\n    <=> isprog_vars vs (csubst t sub).\nProof.\n  introv; split; intro k.\n  apply isprog_vars_app_implies_isprog_vars_csubst; sp.\n  unfold csubst in k.\n\n  allrw @isprog_vars_eq; repnd.\n  generalize (lsubst_wf_iff (csub2sub sub)); intro e.\n  dest_imp e hyp.\n  generalize (e t); clear e; intro e.\n  rw <- e in k; sp.\n\n  generalize (isprogram_lsubst2 t (csub2sub sub)); intro i.\n  dest_imp i hyp.\n  introv j; allapply @in_csub2sub; sp.\n  rw i in k0.\n  allrw subvars_prop.\n  introv j.\n  generalize (k0 x); intro l.\n  allrw in_app_iff.\n  allrw in_remove_nvars.\n  allrw @dom_csub_eq.\n  destruct (in_deq NVar deq_nvar x (dom_csub sub)); tcsp.\nQed.\n\nLemma lsubstc2_lsubstc {o} :\n  forall bp ba B p a wp wB s cvp cvB va w c,\n    disjoint (free_vars p) (bound_vars B)\n    -> !LIn va (bound_vars B)\n    -> !LIn va (dom_csub s)\n    -> !(ba = bp)\n    -> lsubstc2 bp (lsubstc p wp s cvp) ba a\n                (lsubstc_vars B wB (csub_filter s [bp, ba]) [bp, ba] cvB)\n       = lsubstc (lsubst B [(bp, p), (ba, @mk_var o va)]) w (snoc s (va, a)) c.\nProof.\n  introv disj1 disj2 disj3 disj4.\n  assert (!LIn va (free_vars p))\n         as nivap\n         by (allrw @cover_vars_eq; allrw subvars_prop; intro k; discover; sp).\n\n  assert (isprogram (csubst p s))\n         as isp\n         by (apply isprogram_csubst; sp; rw @nt_wf_eq; sp).\n\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n\n  repeat (rw @simple_lsubst_lsubst; simpl);\n    try (complete (sp; cpx; simpl; rw disjoint_singleton_l; sp));\n    try (complete (sp; allapply @in_csub2sub; sp; allunfold @isprogram; sp; allrw; sp)).\n\n  rw <- @sub_filter_csub2sub.\n  rw <- @sub_filter_lsubst_sub; simpl.\n\n  rw @lsubst_sub_trivial_closed1;\n    try (complete (simpl; sp; cpx; allapply @in_csub2sub; sp)).\n\n  generalize (lsubst_shift B\n                           (sub_filter (csub2sub s) [bp, ba])\n                           [(bp, csubst p s), (ba, get_cterm a)]\n                           []).\n  intro eq.\n\n  dest_imp eq hyp.\n  simpl; introv i; allrw in_app_iff; allsimpl; sp; cpx;\n  allrw @in_sub_filter; sp; allapply @in_csub2sub; sp.\n\n  dest_imp eq hyp.\n  simpl; rw <- @dom_sub_sub_filter; unfold disjoint; introv i;\n  allrw in_remove_nvars; sp.\n\n  allrw app_nil_r.\n  rw eq; clear eq; simpl.\n\n  assert (csubst p s = lsubst p (csub2sub (snoc s (va, a)))) as eq1.\n  (* begin proof of assert *)\n  unfold csubst; rw @csub2sub_snoc.\n  generalize (subset_free_vars_sub_app p (csub2sub s) [(va, get_cterm a)]); intro eq.\n  dest_imp eq hyp.\n  introv i; allrw in_app_iff; allrw in_single_iff; sp; cpx; allapply @in_csub2sub; sp.\n  dest_imp eq hyp.\n  simpl; rw disjoint_singleton_r; sp.\n  rw snoc_as_append; rw eq; sp.\n  (* end proof of assert *)\n\n  rw <- eq1; clear eq1.\n\n  assert (get_cterm a = lsubst (mk_var va) (csub2sub (snoc s (va, a)))) as eq2.\n  rw @csub2sub_snoc.\n  change_to_lsubst_aux4; simpl; sp.\n  rw @sub_find_snoc.\n  boolvar.\n  assert (!LIn va (dom_sub (csub2sub s))) as niva by (rw @dom_csub_eq; sp).\n  rw <- @sub_find_none_iff in niva; rw niva; sp.\n\n  rw <- eq2; clear eq2.\n\n  rw @csub2sub_snoc.\n\n  assert (forall T (l : list T) x y, x :: y :: l = [x,y] ++ l) as eqc by sp.\n\n  symmetry.\n  rw eqc.\n  rw @lsubst_aux_app_sub_filter; simpl;\n    try (complete (allrw @prog_sub_cons; sp; unfold prog_sub, sub_range_sat; simpl; sp));\n    try (complete (apply @prog_sub_sub_filter; sp));\n    try (complete (rw @prog_sub_snoc; sp)).\n\n  rw @sub_filter_snoc; boolvar; sp.\n  allrw not_over_or; repnd.\n\n  allunfold @cover_vars_upto.\n  allrw subvars_prop.\n\n  generalize (in_deq NVar deq_nvar va (free_vars B)); intro i; destruct i as [i|i];\n  try (complete (discover; allsimpl; sp; allrw @dom_csub_csub_filter;\n                 allrw in_remove_nvars; repnd; sp)).\n\n  generalize (lsubst_sub_filter\n                B\n                ((bp, csubst p s)\n                   :: (ba, get_cterm a)\n                   :: snoc (sub_filter (csub2sub s) [bp, ba]) (va, get_cterm a))\n                [va]); simpl; boolvar; try (complete sp); intro eq.\n  dest_imp eq hyp.\n  introv k; sp; cpx; allrw in_snoc; sp; cpx; allrw @in_sub_filter; repnd.\n  allapply @in_csub2sub; sp.\n  dest_imp eq hyp.\n  rw disjoint_singleton_r; sp.\n  rw <- eq; clear eq.\n  rw @sub_filter_snoc; boolvar; sp; allrw not_over_or; sp.\n  rw <- @sub_filter_app_r; simpl.\n\n  symmetry.\n  generalize (lsubst_sub_filter\n                B\n                ((bp, csubst p s)\n                   :: (ba, get_cterm a)\n                   :: sub_filter (csub2sub s) [bp, ba])\n                [va]); simpl; boolvar; try (complete sp); intro eq.\n  dest_imp eq hyp.\n  introv k; sp; cpx; allrw in_snoc; sp; cpx; allrw @in_sub_filter; repnd.\n  allapply @in_csub2sub; sp.\n  dest_imp eq hyp.\n  rw disjoint_singleton_r; sp.\n  rw <- eq; clear eq.\n  rw <- @sub_filter_app_r; simpl; sp.\nQed.\n\nLemma cover_vars_lsubst_if {o} :\n  forall sub s t,\n    subvars (free_vars t) (dom_sub s ++ @dom_csub o sub)\n    -> (forall v u, LIn (v,u) s -> cover_vars u sub)\n    -> cover_vars (lsubst t s) sub.\nProof.\n  introv sv cv.\n  rw @cover_vars_eq; allrw subvars_prop; introv i.\n\n  generalize (eqvars_free_vars_disjoint t s); intro eqv.\n  rw eqvars_prop in eqv.\n  apply eqv in i; clear eqv.\n  allrw in_app_iff; allrw in_remove_nvars; sp; discover; allrw in_app_iff; sp.\n  allrw @in_sub_free_vars_iff; exrepnd.\n  allrw @in_sub_keep_first; repnd; discover; allrw in_app_iff; sp;\n  allapply @sub_find_some; discover;\n  allrw @cover_vars_eq; allrw subvars_prop;\n  discover; sp.\nQed.\n\nLemma cover_vars_upto_lsubst_if {o} :\n  forall sub s t vs,\n    subvars (free_vars t) (vs ++ dom_sub s ++ @dom_csub o sub)\n    -> (forall v u, LIn (v,u) s -> cover_vars_upto u sub vs)\n    -> cover_vars_upto (lsubst t s) sub vs.\nProof.\n  introv sv cv.\n  allunfold @cover_vars_upto; allrw subvars_prop; introv i.\n\n  generalize (eqvars_free_vars_disjoint t s); intro eqv.\n  rw eqvars_prop in eqv.\n  apply eqv in i; clear eqv.\n  allrw in_app_iff; allrw in_remove_nvars; sp; discover; allrw in_app_iff; sp.\n  allrw @in_sub_free_vars_iff; exrepnd.\n  allrw @in_sub_keep_first; repnd; discover; allrw in_app_iff; sp;\n  allapply @sub_find_some; discover;\n  allrw @cover_vars_eq; allrw subvars_prop;\n  discover; sp; allrw in_app_iff; sp.\nQed.\n\nLemma cover_vars_upto_app_disjoint {o} :\n  forall t sub1 sub2 vs,\n    @cover_vars_upto o t (sub1 ++ sub2) vs\n    -> disjoint (free_vars t) (dom_csub sub2)\n    -> cover_vars_upto t sub1 vs.\nProof.\n  introv cvu disj.\n  allunfold @cover_vars_upto.\n  allrw subvars_prop.\n  rw @dom_csub_app in cvu.\n  introv i.\n  applydup cvu in i; allrw in_app_iff; repdors; try (complete sp).\n  apply disj in i0; sp.\nQed.\n\nLemma cover_vars_upto_snoc_disjoint {o} :\n  forall t sub v u vs,\n    @cover_vars_upto o t (snoc sub (v,u)) vs\n    -> ! LIn v (free_vars t)\n    -> cover_vars_upto t sub vs.\nProof.\n  introv cvu nit.\n  allrw snoc_as_append.\n  apply cover_vars_upto_app_disjoint in cvu; sp.\n  simpl; unfold disjoint; simpl; sp; subst; sp.\nQed.\n\nLemma subset_free_vars_lsubstc_vars_snoc {o} :\n  forall t sub v u p vs c,\n  forall d : ! LIn v (@free_vars o t),\n    lsubstc_vars t p (snoc sub (v,u)) vs c\n    = lsubstc_vars t p sub vs (cover_vars_upto_snoc_disjoint t sub v u vs c d).\nProof.\n  introv; apply cvterm_eq; simpl; auto.\n  apply subset_free_vars_csub_snoc; auto.\nQed.\n\nLemma subset_free_vars_lsubstc_vars_snoc_ex {o} :\n  forall t sub v u p vs c,\n  forall d : ! LIn v (@free_vars o t),\n    {c' : cover_vars_upto t sub vs\n     & lsubstc_vars t p (snoc sub (v,u)) vs c\n          = lsubstc_vars t p sub vs c'}.\nProof.\n  sp.\n  exists (cover_vars_upto_snoc_disjoint t sub v u vs c d).\n  apply subset_free_vars_lsubstc_vars_snoc.\nQed.\n\nLemma csub_filter_snoc {o} :\n  forall sub v t vars,\n    @csub_filter o (snoc sub (v, t)) vars\n    = if memvar v vars\n      then csub_filter sub vars\n      else snoc (csub_filter sub vars) (v, t).\nProof.\n  induction sub; simpl; sp; allsimpl.\n  rewrite IHsub; boolvar; sp.\nQed.\n\nLemma lsubstc_vars_csub_filter_snoc {o} :\n  forall t wt s v u vs cv cv',\n    (!LIn v vs -> !LIn v (free_vars t))\n    -> lsubstc_vars t wt (@csub_filter o (snoc s (v, u)) vs) vs cv\n       = lsubstc_vars t wt (csub_filter s vs) vs cv'.\nProof.\n  introv hyp.\n  revert cv.\n  rw @csub_filter_snoc; introv.\n  boolvar; clear_irr; sp.\n  generalize (subset_free_vars_lsubstc_vars_snoc_ex t (csub_filter s vs) v u wt vs cv).\n  intro k; dest_imp k h; exrepnd; clear_irr; sp.\nQed.\n\nLemma lsubstc_vars_csub_filter_snoc_ex {o} :\n  forall t wt s v u vs cv,\n    (!LIn v vs -> !LIn v (free_vars t))\n    -> {cv' : cover_vars_upto t (@csub_filter o s vs) vs\n        & lsubstc_vars t wt (csub_filter (snoc s (v, u)) vs) vs cv\n          = lsubstc_vars t wt (csub_filter s vs) vs cv'}.\nProof.\n  introv hyp.\n  assert (cover_vars_upto t (csub_filter s vs) vs) as cv'.\n  (* begin proof of assert *)\n  allunfold @cover_vars_upto.\n  allrw subvars_prop; introv i.\n  applydup cv in i as i0.\n  allrw in_app_iff; repdors; sp.\n  revert i0.\n  rw @csub_filter_snoc; boolvar; intro i0; sp.\n  rw @dom_csub_snoc in i0; simpl in i0; rw in_snoc in i0; repdors; subst; sp.\n  (* end proof of assert *)\n\n  exists cv'.\n  apply lsubstc_vars_csub_filter_snoc; sp.\nQed.\n\nLemma csubst_mk_apply {o} :\n  forall f a s,\n    csubst (@mk_apply o f a) s = mk_apply (csubst f s) (csubst a s).\nProof.\n  intros.\n  unfold csubst.\n  change_to_lsubst_aux4; simpl; sp.\n  allrw @fold_nobnd.\n  rw @fold_apply.\n  rw @sub_filter_nil_r; allrw @fold_nobnd. sp.\nQed.\n\nLemma fold_csubst1 {o} :\n  forall t v u, lsubst t [(v, @get_cterm o u)] = csubst t [(v,u)].\nProof.\n  introv.\n  unfold csubst; simpl; sp.\nQed.\n\nLemma csubst_mk_var_in {o} :\n  forall v t,\n    csubst (@mk_var o v) [(v, t)] = get_cterm t.\nProof.\n  introv; unfold csubst.\n  change_to_lsubst_aux4; simpl; boolvar; sp.\nQed.\n\nLemma cover_vars_implies_cover_vars_upto {o} :\n  forall t vs sub1 sub2,\n    @cover_vars o t (sub1 ++ sub2)\n    -> dom_csub sub2 = vs\n    -> cover_vars_upto t (csub_filter sub1 vs) vs.\nProof.\n  introv cv domeq; subst.\n  unfold cover_vars_upto.\n  rw @cover_vars_eq in cv.\n  prove_subvars cv.\n  allrw @dom_csub_app.\n  allrw in_app_iff; allrw @dom_csub_csub_filter; allrw in_remove_nvars; sp.\n  destruct (in_deq NVar deq_nvar v (dom_csub sub2)); sp.\nQed.\n\nLemma cover_vars_if_subvars {o} :\n  forall t sub1 sub2,\n    subvars (dom_csub sub1) (@dom_csub o sub2)\n    -> cover_vars t sub1\n    -> cover_vars t sub2.\nProof.\n  introv sv cv.\n  allrw @cover_vars_eq.\n  apply subvars_trans with (vs2 := dom_csub sub1); sp.\nQed.\n\nLemma simple_substc {o} :\n  forall t x B ws s cs wb cb,\n    lsubstc (@csubst o B [(x, t)]) ws s cs\n    = substc t x (lsubstc_vars B wb (csub_filter s [x]) [x] cb).\nProof.\n  introv.\n\n  assert (csubst B [(x, t)] = subst B x (get_cterm t))\n    as eq by (unfold csubst; simpl;rw @fold_subst; sp).\n  revert ws cs.\n  rw eq; clear eq; introv.\n\n  generalize (simple_lsubstc_subst\n                (get_cterm t) x B ws s cs\n                (wf_cterm t) (cover_vars_cterm t s)\n                wb cb); intro k.\n\n  dest_imp k hyp; try (complete (rw @free_vars_cterm; sp)).\n  rw k; clear k.\n\n  rw @lsubstc_cterm; sp.\nQed.\n\nLemma simple_substc2 {o} :\n  forall t x u s w c cu,\n    !LIn x (@dom_csub o s)\n    -> lsubstc u w (snoc s (x,t)) c\n       = substc t x (lsubstc_vars u w (csub_filter s [x]) [x] cu).\nProof.\n  introv nixs.\n\n  assert (wf_term (csubst u [(x, t)])) as wc by (apply csubst_preserves_wf_term; sp).\n  assert (cover_vars (csubst u [(x, t)]) s) as cc by (apply cover_vars_csubst3; simpl; sp).\n\n  generalize (simple_substc t x u wc s cc w cu); intro eq.\n  rewrite <- eq; clear eq.\n\n  generalize (lsubstc_csubst_ex u [(x,t)] s wc cc); intro eq; exrepnd; clear_irr; allrw.\n\n  revert c.\n  rw snoc_as_append; introv.\n  generalize (lsubstc_shift_ex u s [(x,t)] [] w).\n  allrw app_nil_r; simpl; intro k.\n  generalize (k c); clear k; intro k.\n  dest_imp k hyp.\n  rw disjoint_singleton_r; sp.\n  exrepnd; clear_irr; sp.\nQed.\n\nLemma cover_vars_change_sub {o} :\n  forall t sub1 sub2,\n    dom_csub sub1 = @dom_csub o sub2\n    -> cover_vars t sub1\n    -> cover_vars t sub2.\nProof.\n  introv eq cv.\n  allrw @cover_vars_eq.\n  allrw subvars_prop; allsimpl.\n  introv i; discover; allrw <-; sp.\nQed.\n\nLemma lsubstc_vars_disjoint {o} :\n  forall t w s vs c,\n    disjoint (@free_vars o t) vs\n    -> {c' : cover_vars t s\n        $ lsubstc_vars t w s vs c = mk_cv vs (lsubstc t w s c')}.\nProof.\n  introv disj.\n\n  assert (cover_vars t s) as cov.\n  rw @cover_vars_eq.\n  unfold cover_vars_upto in c.\n  allrw subvars_prop; introv i.\n  applydup c in i as j; allrw in_app_iff.\n  apply disj in i; sp.\n\n  exists cov.\n  apply cvterm_eq; simpl; sp.\nQed.\n\nLemma lsubstc_csub_filter_eq {o} :\n  forall t w s vs c,\n    {c' : @cover_vars o t s $ lsubstc t w (csub_filter s vs) c = lsubstc t w s c'}.\nProof.\n  introv.\n\n  assert (cover_vars t s) as cov.\n  allrw @cover_vars_eq; allrw subvars_prop; introv i.\n  apply c in i; allrw @dom_csub_csub_filter; allrw in_remove_nvars; sp.\n\n  exists cov.\n  apply cterm_eq; simpl.\n  apply csubst_csub_filter.\n  introv i.\n  rw @cover_vars_eq in c.\n  rw subvars_prop in c.\n  apply c in i.\n  rw @dom_csub_csub_filter in i.\n  rw in_remove_nvars in i; sp.\nQed.\n\nLemma lsubstc_mk_partial {o} :\n  forall R sub,\n  forall w  : @wf_term o R,\n  forall w' : wf_term (mk_partial R),\n  forall c  : cover_vars R sub,\n  forall c' : cover_vars (mk_partial R) sub,\n    lsubstc (mk_partial R) w' sub c'\n    = mkc_partial (lsubstc R w sub c).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd.\n  rw @fold_partial; sp.\nQed.\n\nLemma lsubstc_mk_partial_ex {o} :\n  forall R sub,\n  forall w : wf_term (@mk_partial o R),\n  forall c : cover_vars (mk_partial R) sub,\n    {w1 : wf_term R\n     & {c1 : cover_vars R sub\n        & lsubstc (mk_partial R) w sub c\n             = mkc_partial (lsubstc R w1 sub c1)}}.\nProof.\n  sp.\n\n  assert (wf_term R) as w1.\n  { allrw <- @wf_partial_iff; sp. }\n\n  assert (cover_vars R sub) as c1.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists w1 c1.\n  apply lsubstc_mk_partial.\nQed.\n\nLemma lsubstc_mk_admiss {o} :\n  forall R sub,\n  forall w  : @wf_term o R,\n  forall w' : wf_term (mk_admiss R),\n  forall c  : cover_vars R sub,\n  forall c' : cover_vars (mk_admiss R) sub,\n    lsubstc (mk_admiss R) w' sub c'\n    = mkc_admiss (lsubstc R w sub c).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd.\n  rw @fold_admiss; sp.\nQed.\n\nLemma lsubstc_mk_mono {o} :\n  forall R sub,\n  forall w  : @wf_term o R,\n  forall w' : wf_term (mk_mono R),\n  forall c  : cover_vars R sub,\n  forall c' : cover_vars (mk_mono R) sub,\n    lsubstc (mk_mono R) w' sub c'\n    = mkc_mono (lsubstc R w sub c).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd.\n  rw @fold_mono; sp.\nQed.\n\nLemma csubst_mk_id {o} :\n  forall (sub : @CSub o), csubst mk_id sub = mk_id.\nProof.\n  introv.\n  unfold csubst, lsubst.\n  rw <- @sub_free_vars_is_flat_map_free_vars_range.\n  rw @sub_free_vars_csub2sub; simpl.\n  rw @sub_find_sub_filter; simpl; tcsp.\nQed.\n\nLemma csubst_mk_fun {o} :\n  forall (A B : @NTerm o) sub,\n    alpha_eq (csubst (mk_fun A B) sub)\n             (mk_fun (csubst A sub) (csubst B sub)).\nProof.\n  introv.\n  unfold mk_fun, csubst, lsubst.\n  rw <- @sub_free_vars_is_flat_map_free_vars_range.\n  rw @sub_free_vars_csub2sub; simpl.\n  boolvar; try (complete (provefalse; sp)).\n  unfold mk_function, nobnd; simpl.\n  rw @sub_filter_nil_r.\n  prove_alpha_eq3.\n  remember (csub2sub sub) as csub.\n  pose proof (newvar_prop B) as ni.\n  pose proof (newvar_prop (lsubst_aux B (csub2sub sub))) as ni2.\n  rw @lsubst_aux_sub_filter; auto; disjoint_reasoningv; auto;[].\n  apply alpha_eq_bterm_congr2; spc;[].\n  apply disjoint_app_r_same.\n  revert ni2.\n  repeat (rw @isprogram_lsubst_aux2);\n    try (complete (subst; introv i; apply in_csub2sub in i; auto));[].\n  introv ni2 i j.\n  allrw in_app_iff; allsimpl.\n  allrw in_remove_nvars; repnd.\n  repndors; subst; tcsp.\nQed.\n\nLemma lsubstc_mk_fun {o} :\n  forall A B sub,\n  forall wA : wf_term A,\n  forall wB : @wf_term o B,\n  forall w  : wf_term (mk_fun A B),\n  forall cA : cover_vars A sub,\n  forall cB : cover_vars B sub,\n  forall c  : cover_vars (mk_fun A B) sub,\n    alphaeqc (lsubstc (mk_fun A B) w sub c)\n             (mkc_fun (lsubstc A wA sub cA)\n                      (lsubstc B wB sub cB)).\nProof.\n  unfold mk_member.\n  introv.\n  unfold alphaeqc; simpl.\n  apply csubst_mk_fun.\nQed.\n\nLemma lsubstc_mk_fun_ex {o} :\n  forall A B sub,\n  forall w : wf_term (@mk_fun o A B),\n  forall c  : cover_vars (mk_fun A B) sub,\n    {wA : wf_term A\n     & {wB : wf_term B\n     & {cA : cover_vars A sub\n     & {cB : cover_vars B sub\n     & alphaeqc (lsubstc (mk_fun A B) w sub c)\n                (mkc_fun (lsubstc A wA sub cA)\n                         (lsubstc B wB sub cB))}}}}.\nProof.\n  sp.\n\n  assert (wf_term A) as wa.\n  { allrw @wf_fun_iff; sp. }\n\n  assert (wf_term B) as wb.\n  { allrw @wf_fun_iff; sp. }\n\n  assert (cover_vars A sub) as ca.\n  { rw @cover_vars_fun in c; sp. }\n\n  assert (cover_vars B sub) as cb.\n  { rw @cover_vars_fun in c; sp. }\n\n  exists wa wb ca cb.\n  apply lsubstc_mk_fun.\nQed.\n\nLemma lsubstc_mk_subtype_rel {o} :\n  forall A B sub,\n  forall wA : wf_term A,\n  forall wB : @wf_term o B,\n  forall w  : wf_term (mk_subtype_rel A B),\n  forall cA : cover_vars A sub,\n  forall cB : cover_vars B sub,\n  forall c  : cover_vars (mk_subtype_rel A B) sub,\n    alphaeqc (lsubstc (mk_subtype_rel A B) w sub c)\n             (mkc_subtype_rel (lsubstc A wA sub cA)\n                              (lsubstc B wB sub cB)).\nProof.\n  introv.\n  unfold mk_subtype_rel.\n\n  pose proof (lsubstc_mk_member_ex mk_id (mk_fun A B) sub w c) as q; exrepnd.\n  rw q1; clear q1.\n\n  unfold alphaeqc; simpl.\n  unfold mk_subtype_rel.\n  rw @csubst_mk_id.\n  unfold mk_member, mk_equality.\n  prove_alpha_eq3.\n  apply csubst_mk_fun.\nQed.\n\nLemma cover_vars_subtype_rel {p} :\n  forall (a b : @NTerm p) sub,\n    cover_vars (mk_subtype_rel a b) sub\n    <=> cover_vars a sub\n        # cover_vars b sub.\nProof.\n  introv.\n  rw @cover_vars_member.\n  rw @cover_vars_fun.\n  split; intro k; repnd; dands; auto.\nQed.\n\nLemma lsubstc_mk_subtype_rel_ex {o} :\n  forall A B sub,\n  forall w : wf_term (@mk_subtype_rel o A B),\n  forall c  : cover_vars (mk_subtype_rel A B) sub,\n    {wA : wf_term A\n     & {wB : wf_term B\n     & {cA : cover_vars A sub\n     & {cB : cover_vars B sub\n     & alphaeqc (lsubstc (mk_subtype_rel A B) w sub c)\n                (mkc_subtype_rel (lsubstc A wA sub cA)\n                                 (lsubstc B wB sub cB))}}}}.\nProof.\n  sp.\n\n  assert (wf_term A) as wa.\n  { allrw @wf_subtype_rel_iff; sp. }\n\n  assert (wf_term B) as wb.\n  { allrw @wf_subtype_rel_iff; sp. }\n\n  assert (cover_vars A sub) as ca.\n  { rw @cover_vars_subtype_rel in c; sp. }\n\n  assert (cover_vars B sub) as cb.\n  { rw @cover_vars_subtype_rel in c; sp. }\n\n  exists wa wb ca cb.\n  apply lsubstc_mk_subtype_rel.\nQed.\n\nLemma lsubstc_mk_ufun {o} :\n  forall A B sub,\n  forall wA : wf_term A,\n  forall wB : @wf_term o B,\n  forall w  : wf_term (mk_ufun A B),\n  forall cA : cover_vars A sub,\n  forall cB : cover_vars B sub,\n  forall c  : cover_vars (mk_ufun A B) sub,\n    alphaeqc (lsubstc (mk_ufun A B) w sub c)\n             (mkc_ufun (lsubstc A wA sub cA)\n                       (lsubstc B wB sub cB)).\nProof.\n  unfold mk_member.\n  introv.\n  rw <- @fold_mkc_ufun.\n  remember (cnewvar (lsubstc B wB sub cB)) as nv.\n  unfold mkc_isect.\n  allunfold @lsubstc.\n  allunfold @csubst.\n  unfold alphaeqc.\n  simpl. allunfold @cnewvar. allsimpl.\n  unfold mk_fun.\n  pose proof (prog_sub_csub2sub sub) as Hpr.\n  remember (csub2sub sub) as csub.\n  change_to_lsubst_aux4.\n  unfold mk_function, nobnd.\n  simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd.\n  unfold mk_isect.\n  prove_alpha_eq3.\n  remember (csub2sub sub) as csub.\n  pose proof (newvar_prop B).\n  rw @lsubst_aux_sub_filter; auto; disjoint_reasoningv; auto;[].\n  apply alpha_eq_bterm_congr2; spc;[].\n  apply disjoint_app_r_same.\n  rw <- @lsubst_lsubst_aux_prog_sub; auto.\n  allrw @wf_term_eq.\n  rw @cover_vars_eq in cB.\n  rw subvars_prop in cB.\n  dimp (isprogram_lsubst B csub); auto; [|subst; rw @dom_csub_eq; auto].\n  simpl_sub4.\n  cpx.\nQed.\n\nLemma lsubstc_mk_ufun_ex {o} :\n  forall A B sub,\n  forall w : wf_term (@mk_ufun o A B),\n  forall c  : cover_vars (mk_ufun A B) sub,\n    {wA : wf_term A\n     & {wB : wf_term B\n     & {cA : cover_vars A sub\n     & {cB : cover_vars B sub\n     & alphaeqc (lsubstc (mk_ufun A B) w sub c)\n                (mkc_ufun (lsubstc A wA sub cA)\n                          (lsubstc B wB sub cB))}}}}.\nProof.\n  sp.\n\n  assert (wf_term A) as wa.\n  { allrw @wf_ufun; sp. }\n\n  assert (wf_term B) as wb.\n  { allrw @wf_ufun; sp. }\n\n  assert (cover_vars A sub) as ca.\n  { rw @cover_vars_ufun in c; sp. }\n\n  assert (cover_vars B sub) as cb.\n  { rw @cover_vars_ufun in c; sp. }\n\n  exists wa wb ca cb.\n  apply lsubstc_mk_ufun.\nQed.\n\nLemma lsubstc_mk_eufun {o} :\n  forall A B sub,\n  forall wA : wf_term A,\n  forall wB : @wf_term o B,\n  forall w  : wf_term (mk_eufun A B),\n  forall cA : cover_vars A sub,\n  forall cB : cover_vars B sub,\n  forall c  : cover_vars (mk_eufun A B) sub,\n    alphaeqc (lsubstc (mk_eufun A B) w sub c)\n             (mkc_eufun (lsubstc A wA sub cA)\n                        (lsubstc B wB sub cB)).\nProof.\n  unfold mk_member.\n  introv.\n  rw <- @fold_mkc_eufun.\n  remember (cnewvar (lsubstc B wB sub cB)) as nv.\n  unfold mkc_isect.\n  allunfold @lsubstc.\n  allunfold @csubst.\n  unfold alphaeqc.\n  simpl. allunfold @cnewvar. allsimpl.\n  unfold mk_fun.\n  pose proof (prog_sub_csub2sub sub) as Hpr.\n  remember (csub2sub sub) as csub.\n  change_to_lsubst_aux4.\n  unfold mk_function, nobnd.\n  simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd.\n  unfold mk_eisect.\n  prove_alpha_eq3.\n  remember (csub2sub sub) as csub.\n  pose proof (newvar_prop B).\n  rw @lsubst_aux_sub_filter; auto; disjoint_reasoningv; auto;[].\n  apply alpha_eq_bterm_congr2; spc;[].\n  apply disjoint_app_r_same.\n  rw <- @lsubst_lsubst_aux_prog_sub; auto.\n  allrw @wf_term_eq.\n  rw @cover_vars_eq in cB.\n  rw subvars_prop in cB.\n  dimp (isprogram_lsubst B csub); auto; [|subst; rw @dom_csub_eq; auto].\n  simpl_sub4.\n  cpx.\nQed.\n\nLemma lsubstc_mk_eufun_ex {o} :\n  forall A B sub,\n  forall w : wf_term (@mk_eufun o A B),\n  forall c  : cover_vars (mk_eufun A B) sub,\n    {wA : wf_term A\n     & {wB : wf_term B\n     & {cA : cover_vars A sub\n     & {cB : cover_vars B sub\n     & alphaeqc (lsubstc (mk_eufun A B) w sub c)\n                (mkc_eufun (lsubstc A wA sub cA)\n                           (lsubstc B wB sub cB))}}}}.\nProof.\n  sp.\n\n  assert (wf_term A) as wa.\n  { allrw @wf_eufun; sp. }\n\n  assert (wf_term B) as wb.\n  { allrw @wf_eufun; sp. }\n\n  assert (cover_vars A sub) as ca.\n  { rw @cover_vars_eufun in c; sp. }\n\n  assert (cover_vars B sub) as cb.\n  { rw @cover_vars_eufun in c; sp. }\n\n  exists wa wb ca cb.\n  apply lsubstc_mk_eufun.\nQed.\n\nLemma lsubstc_mk_prod {o} :\n  forall A B sub,\n  forall wA : wf_term A,\n  forall wB : @wf_term o B,\n  forall w  : wf_term (mk_prod A B),\n  forall cA : cover_vars A sub,\n  forall cB : cover_vars B sub,\n  forall c  : cover_vars (mk_prod A B) sub,\n    alphaeqc (lsubstc (mk_prod A B) w sub c)\n             (mkc_prod (lsubstc A wA sub cA)\n                       (lsubstc B wB sub cB)).\nProof.\n  unfold mk_member.\n  introv.\n  rw <- @fold_mkc_prod.\n  remember (cnewvar (lsubstc B wB sub cB)) as nv.\n  unfold mkc_product.\n  allunfold @lsubstc.\n  allunfold @csubst.\n  unfold alphaeqc.\n  simpl. allunfold @cnewvar. allsimpl.\n  unfold mk_prod.\n  pose proof (prog_sub_csub2sub sub) as Hpr.\n  remember (csub2sub sub) as csub.\n  change_to_lsubst_aux4.\n  unfold mk_product, nobnd.\n  simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd.\n  prove_alpha_eq3.\n  remember (csub2sub sub) as csub.\n  pose proof (newvar_prop B).\n  rw @lsubst_aux_sub_filter; auto; disjoint_reasoningv; auto;[].\n  apply alpha_eq_bterm_congr2; spc;[].\n  apply disjoint_app_r_same.\n  rw <- @lsubst_lsubst_aux_prog_sub; auto.\n  allrw @wf_term_eq.\n  rw @cover_vars_eq in cB.\n  rw subvars_prop in cB.\n  dimp (isprogram_lsubst B csub); auto; [|subst; rw @dom_csub_eq; auto].\n  simpl_sub4.\n  cpx.\nQed.\n\nLemma lsubstc_mk_prod_ex {o} :\n  forall A B sub,\n  forall w : wf_term (@mk_prod o A B),\n  forall c  : cover_vars (mk_prod A B) sub,\n    {wA : wf_term A\n     & {wB : wf_term B\n     & {cA : cover_vars A sub\n     & {cB : cover_vars B sub\n     & alphaeqc (lsubstc (mk_prod A B) w sub c)\n                (mkc_prod (lsubstc A wA sub cA)\n                          (lsubstc B wB sub cB))}}}}.\nProof.\n  sp.\n\n  assert (wf_term A) as wa.\n  { allrw @wf_prod; sp. }\n\n  assert (wf_term B) as wb.\n  { allrw @wf_prod; sp. }\n\n  assert (cover_vars A sub) as ca.\n  { rw @cover_vars_prod in c; sp. }\n\n  assert (cover_vars B sub) as cb.\n  { rw @cover_vars_prod in c; sp. }\n\n  exists wa wb ca cb.\n  apply lsubstc_mk_prod.\nQed.\n\nLemma lsubstc_mk_iff {o} :\n  forall A B sub,\n  forall wA : wf_term A,\n  forall wB : @wf_term o B,\n  forall w  : wf_term (mk_iff A B),\n  forall cA : cover_vars A sub,\n  forall cB : cover_vars B sub,\n  forall c  : cover_vars (mk_iff A B) sub,\n    alphaeqc (lsubstc (mk_iff A B) w sub c)\n             (mkc_iff (lsubstc A wA sub cA)\n                      (lsubstc B wB sub cB)).\nProof.\n  unfold mk_iff, mkc_iff.\n  introv.\n\n  unfold alphaeqc; simpl.\n  unfold csubst.\n  change_to_lsubst_aux4.\n  unfold mk_prod, mk_fun, nobnd.\n  simpl.\n  allrw @sub_filter_nil_r; allrw @fold_nobnd.\n  unfold mk_product, mk_function, nobnd.\n\n  prove_alpha_eq3.\n\n  prove_alpha_eq3.\n\n  pose proof (newvar_prop B).\n  rw @lsubst_aux_sub_filter; auto; disjoint_reasoningv; auto.\n  apply alpha_eq_bterm_congr2; spc.\n\n  apply disjoint_app_r_same.\n  rw disjoint_app_l; dands; rw disjoint_singleton_l;\n  try (apply @newvar_prop).\n  rw @isprogram_lsubst_aux2.\n  rw in_remove_nvars; dands; intro k; repnd; apply newvar_prop in k0; sp.\n  introv k.\n  apply in_csub2sub in k; auto.\n\n  apply alpha_eq_bterm_congr2; spc.\n\n  prove_alpha_eq3.\n\n  rw @lsubst_aux_sub_filter; auto.\n  disjoint_reasoningv; auto.\n  apply subvars_not_in with (vs1 := free_vars (mk_fun B A)).\n  rw @free_vars_fun.\n  apply subvars_app_trivial_l.\n  apply newvar_prop.\n\n  apply alpha_eq_bterm_congr2; spc.\n  allrw @fold_nobnd.\n  rw @fold_function; fold (mk_fun B A).\n  rw <- @sub_filter_app_r.\n  rw @lsubst_aux_sub_filter; auto.\n  disjoint_reasoningv; auto; try (apply newvar_prop).\n  apply subvars_not_in with (vs1 := free_vars (mk_fun B A)); try (apply newvar_prop).\n  rw @free_vars_fun.\n  apply subvars_app_trivial_r.\n\n  disjoint_reasoningv; auto; try (apply newvar_prop).\n  allrw @fold_nobnd.\n  rw @fold_function; fold (mk_fun B A).\n  rw <- @sub_filter_app_r.\n  rw @lsubst_aux_sub_filter; auto; try disjoint_reasoningv; auto; try (apply newvar_prop).\n  rw @isprogram_lsubst_aux2.\n  rw in_remove_nvars; intro k; repnd; apply newvar_prop in k0; sp.\n  introv k; apply in_csub2sub in k; auto.\n  apply subvars_not_in with (vs1 := free_vars (mk_fun B A)); try (apply newvar_prop).\n  rw @free_vars_fun; apply subvars_app_trivial_r.\n\n  allrw @fold_nobnd.\n  rw @fold_function; fold (mk_fun B A).\n  rw <- @sub_filter_app_r.\n  rw @lsubst_aux_sub_filter; auto; try disjoint_reasoningv; auto; try (apply newvar_prop).\n  apply subvars_not_in with (vs1 := free_vars (mk_fun B A)); try (apply newvar_prop).\n  rw @free_vars_fun; apply subvars_app_trivial_r.\n\n  rw @isprogram_lsubst_aux2.\n  rw in_remove_nvars; intro k; repnd; apply newvar_prop in k0; sp.\n  introv k; apply in_csub2sub in k; auto.\n\n  disjoint_reasoningv; simpl; auto; rw remove_nvars_nil_l; rw app_nil_r;\n  allrw @fold_nobnd;\n  rw @fold_function; fold (mk_fun B A);\n  try (rw in_app_iff; rw not_over_or; dands).\n\n  rw @lsubst_aux_sub_filter; auto; try disjoint_reasoningv; auto; try (apply newvar_prop).\n  rw @isprogram_lsubst_aux2.\n  rw in_remove_nvars; intro k; repnd.\n  assert (subvars (free_vars B) (free_vars (mk_fun B A))) as sv.\n  rw @free_vars_fun; apply subvars_app_trivial_l.\n  rw subvars_prop in sv.\n  apply sv in k0; apply newvar_prop in k0; sp.\n  introv k; apply in_csub2sub in k; sp.\n  apply subvars_not_in with (vs1 := free_vars (mk_fun B A)); try (apply newvar_prop).\n  rw @free_vars_fun; apply subvars_app_trivial_l.\n\n  rw in_remove_nvars.\n  apply not_over_not_lin_nvar; left.\n  rw @lsubst_aux_sub_filter; auto; try disjoint_reasoningv; auto; try (apply newvar_prop).\n  rw @isprogram_lsubst_aux2.\n  rw in_remove_nvars; intro k; repnd.\n  assert (subvars (free_vars A) (free_vars (mk_fun B A))) as sv.\n  rw @free_vars_fun; apply subvars_app_trivial_r.\n  rw subvars_prop in sv.\n  apply sv in k0; apply newvar_prop in k0; sp.\n  introv k; apply in_sub_filter in k; repnd; apply in_csub2sub in k0; sp.\n\n  allrw @fold_nobnd;\n  rw @fold_function;\n    fold (mk_fun B A);\n    fold (mk_fun (lsubst_aux B (csub2sub sub)) (lsubst_aux A (csub2sub sub))).\n  rw @lsubst_aux_sub_filter; auto; try disjoint_reasoningv; auto; try (apply newvar_prop).\n  apply subvars_not_in with (vs1 := free_vars (mk_fun (lsubst_aux B (csub2sub sub)) (lsubst_aux A (csub2sub sub)))); try (apply newvar_prop).\n  rw @free_vars_fun; apply subvars_app_trivial_l.\n  apply subvars_not_in with (vs1 := free_vars (mk_fun B A)); try (apply newvar_prop).\n  rw @free_vars_fun; apply subvars_app_trivial_l.\n  rw in_remove_nvars.\n  apply not_over_not_lin_nvar; left.\n  rw <- @sub_filter_app_r.\n  rw @lsubst_aux_sub_filter; auto; try disjoint_reasoningv; auto; try (apply newvar_prop).\n  apply subvars_not_in with (vs1 := free_vars (mk_fun (lsubst_aux B (csub2sub sub)) (lsubst_aux A (csub2sub sub)))); try (apply newvar_prop).\n  rw @free_vars_fun; apply subvars_app_trivial_r.\n  apply subvars_not_in with (vs1 := free_vars (mk_fun B A)); try (apply newvar_prop).\n  rw @free_vars_fun; apply subvars_app_trivial_r.\n\n  rw @isprogram_lsubst_aux2.\n  rw in_remove_nvars; intro k; repnd.\n  assert (subvars (free_vars B) (free_vars (mk_fun B A))) as sv.\n  rw @free_vars_fun; apply subvars_app_trivial_l.\n  rw subvars_prop in sv.\n  apply sv in k0; apply newvar_prop in k0; sp.\n  introv k; apply in_csub2sub in k; sp.\n\n  rw in_remove_nvars.\n  apply not_over_not_lin_nvar; left.\n  rw @isprogram_lsubst_aux2.\n  rw in_remove_nvars; intro k; repnd.\n  assert (subvars (free_vars A) (free_vars (mk_fun B A))) as sv.\n  rw @free_vars_fun; apply subvars_app_trivial_r.\n  rw subvars_prop in sv.\n  apply sv in k0; apply newvar_prop in k0; sp.\n  introv k; apply in_csub2sub in k; sp.\n\n  apply subvars_not_in with (vs1 := free_vars (mk_fun (lsubst_aux B (csub2sub sub)) (lsubst_aux A (csub2sub sub)))); try (apply newvar_prop).\n  rw @free_vars_fun; apply subvars_app_trivial_l.\n\n  rw in_remove_nvars.\n  apply not_over_not_lin_nvar; left.\n  apply subvars_not_in with (vs1 := free_vars (mk_fun (lsubst_aux B (csub2sub sub)) (lsubst_aux A (csub2sub sub)))); try (apply newvar_prop).\n  rw @free_vars_fun; apply subvars_app_trivial_r.\nQed.\n\nLemma cover_vars_iff {o} :\n  forall a b sub,\n    cover_vars (@mk_iff o a b) sub\n    <=> cover_vars a sub\n        # cover_vars b sub.\nProof.\n  introv.\n  rw @cover_vars_prod.\n  allrw @cover_vars_fun.\n  split; sp.\nQed.\n\nLemma wf_iff {o} :\n  forall (a b : @NTerm o),\n    wf_term (mk_iff a b) <=> (wf_term a # wf_term b).\nProof.\n  introv.\n  unfold mk_iff.\n  rw @wf_prod.\n  allrw @wf_fun.\n  split; sp.\nQed.\n\nLemma lsubstc_mk_iff_ex {o} :\n  forall A B sub,\n  forall w : wf_term (@mk_iff o A B),\n  forall c  : cover_vars (mk_iff A B) sub,\n    {wA : wf_term A\n     & {wB : wf_term B\n     & {cA : cover_vars A sub\n     & {cB : cover_vars B sub\n     & alphaeqc (lsubstc (mk_iff A B) w sub c)\n                (mkc_iff (lsubstc A wA sub cA)\n                         (lsubstc B wB sub cB))}}}}.\nProof.\n  sp.\n\n  assert (wf_term A) as wa.\n  { allrw @wf_iff; sp. }\n\n  assert (wf_term B) as wb.\n  { allrw @wf_iff; sp. }\n\n  assert (cover_vars A sub) as ca.\n  { rw @cover_vars_iff in c; sp. }\n\n  assert (cover_vars B sub) as cb.\n  { rw @cover_vars_iff in c; sp. }\n\n  exists wa wb ca cb.\n  apply lsubstc_mk_iff.\nQed.\n\nLemma wf_admiss_iff {p} :\n  forall a : @NTerm p, wf_term (mk_admiss a) <=> wf_term a.\nProof.\n  introv; split; intro w; repnd.\n  rw @wf_term_eq in w.\n  inversion w as [|?| o l bw e]; subst.\n  generalize (bw (nobnd a)); simpl; intros bw1.\n  autodimp bw1 hyp.\n  inversion bw1; subst.\n  allrw @nt_wf_eq; sp.\n  apply nt_wf_eq.\n  constructor; simpl; sp; subst; constructor; rw @nt_wf_eq; sp.\nQed.\n\nLemma lsubstc_mk_admiss_ex {o} :\n  forall R sub,\n  forall w : wf_term (@mk_admiss o R),\n  forall c : cover_vars (mk_admiss R) sub,\n    {w1 : wf_term R\n     & {c1 : cover_vars R sub\n        & lsubstc (mk_admiss R) w sub c\n             = mkc_admiss (lsubstc R w1 sub c1)}}.\nProof.\n  sp.\n\n  assert (wf_term R) as w1.\n  { allrw @wf_admiss_iff; sp. }\n\n  assert (cover_vars R sub) as c1.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists w1 c1.\n  apply lsubstc_mk_admiss.\nQed.\n\nLemma wf_mono_iff {p} :\n  forall a : @NTerm p, wf_term (mk_mono a) <=> wf_term a.\nProof.\n  introv; split; intro w; repnd.\n  rw @wf_term_eq in w.\n  inversion w as [|?| o l bw e]; subst.\n  generalize (bw (nobnd a)); simpl; intros bw1.\n  autodimp bw1 hyp.\n  inversion bw1; subst.\n  allrw @nt_wf_eq; sp.\n  apply nt_wf_eq.\n  constructor; simpl; sp; subst; constructor; rw @nt_wf_eq; sp.\nQed.\n\nLemma lsubstc_mk_mono_ex {o} :\n  forall R sub,\n  forall w : wf_term (@mk_mono o R),\n  forall c : cover_vars (mk_mono R) sub,\n    {w1 : wf_term R\n     & {c1 : cover_vars R sub\n        & lsubstc (mk_mono R) w sub c\n             = mkc_mono (lsubstc R w1 sub c1)}}.\nProof.\n  sp.\n\n  assert (wf_term R) as w1.\n  { allrw @wf_mono_iff; sp. }\n\n  assert (cover_vars R sub) as c1.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists w1 c1.\n  apply lsubstc_mk_mono.\nQed.\n\nLemma lsubstc_mk_or {o} :\n  forall t1 t2 sub,\n  forall w1 : wf_term t1,\n  forall w2 : @wf_term o t2,\n  forall w  : wf_term (mk_or t1 t2),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars t2 sub,\n  forall c  : cover_vars (mk_or t1 t2) sub,\n    lsubstc (mk_or t1 t2) w sub c\n    = mkc_or (lsubstc t1 w1 sub c1)\n             (lsubstc t2 w2 sub c2).\nProof.\n  sp.\n  apply lsubstc_mk_union.\nQed.\n\nLemma lsubstc_mk_or_ex {o} :\n  forall t1 t2 sub,\n  forall w  : wf_term (@mk_or o t1 t2),\n  forall c  : cover_vars (mk_or t1 t2) sub,\n    {w1 : wf_term t1\n     & {w2 : wf_term t2\n     & {c1 : cover_vars t1 sub\n     & {c2 : cover_vars t2 sub\n        & lsubstc (mk_or t1 t2) w sub c\n          = mkc_or (lsubstc t1 w1 sub c1)\n                   (lsubstc t2 w2 sub c2)}}}}.\nProof.\n  sp.\n  apply lsubstc_mk_union_ex.\nQed.\n\nLemma lsubstc_mk_not {o} :\n  forall t1 sub,\n  forall w1 : @wf_term o t1,\n  forall w  : wf_term (mk_not t1),\n  forall c1 : cover_vars t1 sub,\n  forall c  : cover_vars (mk_not t1) sub,\n    lsubstc (mk_not t1) w sub c\n    = mkc_not (lsubstc t1 w1 sub c1).\nProof.\n  introv.\n  unfold mk_not, mk_fun.\n  generalize (newvar_not_in_free_vars (@mk_void o)); intro ev.\n  simpl in ev; dest_imp ev hyp; rw ev.\n\n  assert (wf_term (mk_function t1 nvarx mk_void)) as wff by (apply wf_function; sp).\n  assert (cover_vars_upto mk_void (csub_filter sub [nvarx]) [nvarx]) as cvv by (unfold cover_vars_upto; simpl; sp).\n  assert (cover_vars (mk_function t1 nvarx mk_void) sub) as cvf by (apply cover_vars_function; sp).\n  generalize (lsubstc_mk_function t1 nvarx mk_void sub w1 wf_void wff c1 cvv cvf); intro e.\n  clear_irr.\n  rw e.\n\n  apply cterm_eq; simpl.\n  unfold mk_fun.\n  rw ev.\n  assert (csubst mk_void (csub_filter sub [nvarx]) = mk_void) as e2;\n    try (complete (rw e2; sp)).\n  unfold csubst.\n  change_to_lsubst_aux4; simpl.\n  allrw @sub_filter_nil_r; allrw @fold_nobnd.\n  rw <- @sub_filter_csub2sub.\n  rw <- @sub_filter_app_r; simpl.\n  generalize (sub_find_sub_filter_none [nvarx, nvarx] nvarx (csub2sub sub)); intro e3.\n  destruct e3 as [ea eb].\n  clear ea; autodimp eb hyp; try (complete (simpl; sp)).\n  rw eb; sp.\nQed.\n\nLemma lsubstc_mk_not_ex {o} :\n  forall t1 sub,\n  forall w : wf_term (@mk_not o t1),\n  forall c : cover_vars (mk_not t1) sub,\n    {w1 : wf_term t1\n     & {c1 : cover_vars t1 sub\n        & lsubstc (mk_not t1) w sub c\n             = mkc_not (lsubstc t1 w1 sub c1)}}.\nProof.\n  sp.\n\n  duplicate w.\n  rw @wf_not in w; sp.\n\n  duplicate c.\n  rw @cover_vars_not in c; sp.\n\n  exists w c.\n  apply lsubstc_mk_not.\nQed.\n\nLemma subst_preserves_wf_term {o} :\n  forall t v u, @wf_term o u -> wf_term t -> wf_term (subst t v u).\nProof.\n  introv wu wt.\n  apply lsubst_preserves_wf_term; auto.\n  unfold wf_sub, sub_range_sat; simpl; sp; cpx.\n  apply nt_wf_eq; sp.\nQed.\n\nLemma covered_subst {o} :\n  forall t v u vs,\n    covered t (v :: vs)\n    -> @covered o u vs\n    -> covered (subst t v u) vs.\nProof.\n  introv ct cu.\n  allunfold @covered.\n  generalize (eqvars_free_vars_disjoint t [(v,u)]); intro eqvs.\n  apply eqvars_sym in eqvs.\n  apply subvars_eqvars with (s2 := vs) in eqvs; auto.\n  simpl; boolvar; simpl; rw app_nil_r;\n  try (rw subvars_app_l); rw subvars_remove_nvars; dands; auto;\n  rw subvars_swap_r; simpl; auto.\nQed.\n\nLemma covered_snoc_weak {o} :\n  forall t v vs, @covered o t vs -> covered t (snoc vs v).\nProof.\n  introv c.\n  allunfold @covered.\n  provesv.\n  apply in_snoc; sp.\nQed.\n\nLemma lsubstc_mk_fix {o} :\n  forall R sub,\n  forall w  : @wf_term o R,\n  forall w' : wf_term (mk_fix R),\n  forall c  : cover_vars R sub,\n  forall c' : cover_vars (mk_fix R) sub,\n    lsubstc (mk_fix R) w' sub c'\n    = mkc_fix (lsubstc R w sub c).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd.\n  unfold mk_fix. refl.\nQed.\n\nLemma lsubstc_mk_fix_ex {o} :\n  forall f sub,\n  forall w : wf_term (@mk_fix o f),\n  forall c : cover_vars (mk_fix f) sub,\n    {w1 : wf_term f\n     & {c1 : cover_vars f sub\n        & lsubstc (mk_fix f) w sub c\n             = mkc_fix (lsubstc f w1 sub c1)}}.\nProof.\n  sp.\n\n  assert (wf_term f) as w1.\n  { allrw @wf_fix_iff; sp. }\n\n  assert (cover_vars f sub) as c1.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists w1 c1.\n  apply lsubstc_mk_fix.\nQed.\n\nLemma csubst_mk_zero {o} :\n  forall sub, csubst mk_zero sub = @mk_zero o.\nProof.\n  sp.\nQed.\n\nLemma lsubstc_mk_zero {o} :\n  forall p sub c,\n    lsubstc mk_zero p sub c = @mkc_zero o.\nProof.\n  unfold lsubstc, mkc_zero; sp.\n  apply cterm_eq; sp.\nQed.\n\nLemma lsubstc_mk_int {o} :\n  forall p sub c,\n    lsubstc mk_int p sub c = @mkc_int o.\nProof.\n  unfold lsubstc, mkc_zero; sp.\n  apply cterm_eq.\n  simpl.\n  auto.\nQed.\n\nLemma lsubstc_mk_bot {o} :\n  forall w s c, lsubstc mk_bot w s c = @mkc_bot o.\nProof.\n  intros.\n  apply cterm_eq; simpl.\n  apply csubst_trivial; simpl; auto.\nQed.\n\nLemma csubst_mk_lam {o} :\n  forall v b sub,\n    csubst (@mk_lam o v b) sub\n    = mk_lam v (csubst b (csub_filter sub [v])).\nProof.\n  introv.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_csub2sub; sp.\nQed.\n\nLemma csubst_mk_isect {o} :\n  forall a v b sub,\n    csubst (@mk_isect o a v b) sub\n    = mk_isect (csubst a sub) v (csubst b (csub_filter sub [v])).\nProof.\n  introv.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd.\n  rw @sub_filter_csub2sub; sp.\nQed.\n\nLemma csubst_mk_equality {o} :\n  forall a b A sub,\n    csubst (@mk_equality o a b A) sub\n    = mk_equality (csubst a sub) (csubst b sub) (csubst A sub).\nProof.\n  introv.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd. sp.\nQed.\n\nLemma csubst_mk_tequality {o} :\n  forall a b sub,\n    csubst (@mk_tequality o a b) sub\n    = mk_tequality (csubst a sub) (csubst b sub).\nProof.\n  introv.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd. sp.\nQed.\n\nLemma csubst_mk_var_out {o} :\n  forall v s,\n    !LIn v (dom_csub s)\n    -> csubst (mk_var v) s = @mk_var o v.\nProof.\n  introv ni; simpl.\n  unfold csubst.\n  change_to_lsubst_aux4.\n  apply lsubst_aux_var_csub2sub_out; sp.\nQed.\n\nLemma csubst_mk_var_out2 {o} :\n  forall v s vs,\n    LIn v vs\n    -> csubst (mk_var v) (csub_filter s vs) = @mk_var o v.\nProof.\n  introv ni; simpl.\n  apply csubst_mk_var_out.\n  rw @dom_csub_csub_filter.\n  rw in_remove_nvars; sp.\nQed.\n\nLemma csubst_cons_var {o} :\n  forall sub v u,\n    csubst (@mk_var o v) ((v,u) :: sub) = get_cterm u.\nProof.\n  intros.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  boolvar; sp.\n  apply disjoint_nil_l.\nQed.\n\nLemma lsubstc_cons_var {o} :\n  forall sub v u p c,\n    lsubstc (@mk_var o v) p ((v,u) :: sub) c = u.\nProof.\n  unfold lsubstc; sp.\n\n  destruct u.\n\n  assert (exist (fun t : NTerm => isprog t) x i =\n          exist (fun t : NTerm => isprog t)\n                (get_cterm (exist (fun t : NTerm => isprog t) x i))\n                i) as h by (simpl; sp).\n\n  rw h.\n\n  apply cterm_eq; simpl.\n  apply csubst_cons_var; auto.\nQed.\n\nLemma csubst_cons_var2 {o} :\n  forall x sub v u,\n    x <> v\n    -> csubst (@mk_var o x) ((v,u) :: sub)\n       = csubst (mk_var x) sub.\nProof.\n  intros.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  boolvar; sp.\n  apply disjoint_nil_l.\nQed.\n\nLemma cover_vars_cons {o} :\n  forall v sub a b,\n    cover_vars (@mk_var o v) ((a,b) :: sub)\n    -> v <> a\n    -> cover_vars (mk_var v) sub.\nProof.\n  introv cv d.\n  allrw @cover_vars_eq; simpl.\n  provesv; allrw in_single_iff; subst.\n  allsimpl; sp.\nQed.\n\nLemma lsubstc_cons_var2 {o} :\n  forall x sub v u p c,\n  forall i : x <> v,\n    lsubstc (@mk_var o x) p ((v,u) :: sub) c\n    = lsubstc (mk_var x) p sub (cover_vars_cons x sub v u c i).\nProof.\n  unfold lsubstc; sp.\n  apply cterm_eq; simpl.\n  apply csubst_cons_var2; auto.\nQed.\n\nLemma lsubstc_cons_var2_ex {o} :\n  forall x sub v u p c,\n  forall i : x <> v,\n    {c' : cover_vars (@mk_var o x) sub\n     & lsubstc (mk_var x) p ((v,u) :: sub) c\n       = lsubstc (mk_var x) p sub c'}.\nProof.\n  intros.\n  exists (cover_vars_cons x sub v u c i).\n  apply lsubstc_cons_var2.\nQed.\n\nLemma subset_free_vars_lsubstc_cons {o} :\n  forall t sub v u p c,\n  forall d : !LIn v (@free_vars o t),\n    lsubstc t p ((v,u) :: sub) c\n    = lsubstc t p sub (cover_vars_cons_disjoint t sub v u c d).\nProof.\n  unfold lsubstc; sp.\n  apply cterm_eq; simpl.\n  apply subset_free_vars_csub_cons; auto.\nQed.\n\nLemma subset_free_vars_lsubstc_cons_ex {o} :\n  forall t sub v u p c,\n  forall d : !LIn v (@free_vars o t),\n    {c' : cover_vars t sub\n     & lsubstc t p ((v,u) :: sub) c\n       = lsubstc t p sub c'}.\nProof.\n  sp.\n  exists (cover_vars_cons_disjoint t sub v u c d).\n  apply subset_free_vars_lsubstc_cons.\nQed.\n\nLemma lsubstc_mk_ispair {o} :\n  forall t1 t2 t3 sub,\n  forall w1 : wf_term t1,\n  forall w2 : wf_term t2,\n  forall w3 : @wf_term o t3,\n  forall w  : wf_term (mk_ispair t1 t2 t3),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars t2 sub,\n  forall c3 : cover_vars t3 sub,\n  forall c  : cover_vars (mk_ispair t1 t2 t3) sub,\n    lsubstc (mk_ispair t1 t2 t3) w sub c\n    = mkc_ispair (lsubstc t1 w1 sub c1)\n                 (lsubstc t2 w2 sub c2)\n                 (lsubstc t3 w3 sub c3).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl;\n  change_to_lsubst_aux4; simpl;\n  rw @sub_filter_nil_r; allrw @fold_nobnd.\n  rw @fold_ispair; sp.\nQed.\n\nLemma fold_can_test {p} :\n  forall test (a b c : @NTerm p),\n    oterm (NCan (NCanTest test)) [ nobnd a, nobnd b, nobnd c ]\n    = mk_can_test test a b c.\nProof. sp. Qed.\n\nLemma lsubstc_mk_can_test {o} :\n  forall test t1 t2 t3 sub,\n  forall w1 : wf_term t1,\n  forall w2 : wf_term t2,\n  forall w3 : @wf_term o t3,\n  forall w  : wf_term (mk_can_test test t1 t2 t3),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars t2 sub,\n  forall c3 : cover_vars t3 sub,\n  forall c  : cover_vars (mk_can_test test t1 t2 t3) sub,\n    lsubstc (mk_can_test test t1 t2 t3) w sub c\n    = mkc_can_test test (lsubstc t1 w1 sub c1)\n                 (lsubstc t2 w2 sub c2)\n                 (lsubstc t3 w3 sub c3).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl;\n  change_to_lsubst_aux4; simpl;\n  rw @sub_filter_nil_r; allrw @fold_nobnd.\n  rw @fold_can_test; sp.\nQed.\n\nLemma lsubstc_mk_ispair_ex {o} :\n  forall t1 t2 t3 sub,\n  forall w  : wf_term (@mk_ispair o t1 t2 t3),\n  forall c  : cover_vars (mk_ispair t1 t2 t3) sub,\n  {w1 : wf_term t1\n   & {w2 : wf_term t2\n   & {w3 : wf_term t3\n   & {c1 : cover_vars t1 sub\n   & {c2 : cover_vars t2 sub\n   & {c3 : cover_vars t3 sub\n      & lsubstc (mk_ispair t1 t2 t3) w sub c\n           = mkc_ispair (lsubstc t1 w1 sub c1)\n                        (lsubstc t2 w2 sub c2)\n                        (lsubstc t3 w3 sub c3)}}}}}}.\nProof.\n  sp.\n\n  assert (wf_term t1) as w1.\n  { allrw <- @wf_ispair_iff; sp. }\n\n  assert (wf_term t2) as w2.\n  { allrw <- @wf_ispair_iff; sp. }\n\n  assert (wf_term t3) as w3.\n  { allrw <- @wf_ispair_iff; sp. }\n\n  assert (cover_vars t1 sub) as c1.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  assert (cover_vars t2 sub) as c2.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  assert (cover_vars t3 sub) as c3.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists w1 w2 w3 c1 c2 c3.\n  apply lsubstc_mk_ispair.\nQed.\n\n\nLemma lsubstc_mk_can_test_ex {o} :\n  forall test t1 t2 t3 sub,\n  forall w  : wf_term (@mk_can_test o test t1 t2 t3),\n  forall c  : cover_vars (mk_can_test test t1 t2 t3) sub,\n  {w1 : wf_term t1\n   & {w2 : wf_term t2\n   & {w3 : wf_term t3\n   & {c1 : cover_vars t1 sub\n   & {c2 : cover_vars t2 sub\n   & {c3 : cover_vars t3 sub\n      & lsubstc (mk_can_test test t1 t2 t3) w sub c\n           = mkc_can_test test (lsubstc t1 w1 sub c1)\n                        (lsubstc t2 w2 sub c2)\n                        (lsubstc t3 w3 sub c3)}}}}}}.\nProof.\n  sp.\n\n  assert (wf_term t1) as w1.\n  { allrw @wf_can_test_iff; sp. }\n\n  assert (wf_term t2) as w2.\n  { allrw @wf_can_test_iff; sp. }\n\n  assert (wf_term t3) as w3.\n  { allrw @wf_can_test_iff; sp. }\n\n  assert (cover_vars t1 sub) as c1.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c);sp. }\n\n  assert (cover_vars t2 sub) as c2.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  assert (cover_vars t3 sub) as c3.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists w1 w2 w3 c1 c2 c3.\n  apply lsubstc_mk_can_test.\nQed.\n\nLemma lsubstc_mk_eta_pair {o} :\n  forall t sub,\n  forall w  : @wf_term o t,\n  forall w' : wf_term (mk_eta_pair t),\n  forall c  : cover_vars t sub,\n  forall c' : cover_vars (mk_eta_pair t) sub,\n    lsubstc (mk_eta_pair t) w' sub c'\n    = mkc_eta_pair (lsubstc t w sub c).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  allrw @sub_filter_nil_r; allrw @fold_nobnd.\n  generalize (sub_find_sub_filter_none [nvarx, nvary] nvarx (csub2sub sub)); intro e.\n  destruct e as [e1 e2].\n  clear e1; autodimp e2 hyp; try (complete (simpl; sp)).\n  rw e2; clear e2.\n  generalize (sub_find_sub_filter_none [nvarx, nvary] nvary (csub2sub sub)); intro e.\n  destruct e as [e1 e2].\n  clear e1; autodimp e2 hyp; try (complete (simpl; sp)).\n  rw e2; clear e2.\n  allrw @fold_spread.\n  allrw @fold_pair.\n  allrw @fold_pi1.\n  allrw @fold_pi2.\n  rw @fold_eta_pair; sp.\nQed.\n\nLemma lsubstc_mk_eta_pair_ex {o} :\n  forall t sub,\n  forall w : wf_term (@mk_eta_pair o t),\n  forall c : cover_vars (mk_eta_pair t) sub,\n    {w1 : wf_term t\n     & {c1 : cover_vars t sub\n        & lsubstc (mk_eta_pair t) w sub c\n             = mkc_eta_pair (lsubstc t w1 sub c1)}}.\nProof.\n  sp.\n\n  assert (wf_term t) as w1.\n  { allrw @wf_eta_pair; sp. }\n\n  assert (cover_vars t sub) as c1.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists w1 c1.\n  apply lsubstc_mk_eta_pair.\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/csubst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5544704649604274, "lm_q1q2_score": 0.29453990824588394}}
{"text": "(* ---------------------------------------------------------------------\n\n   This file is part of a repository containing the definitions and \n   proof scripts related to the formalization of the Chomsky Normal\n   Form for context-free grammars in Coq. Specifically, the following \n   results were obtained:\n   \n   (i) context-free grammar simplification \n   (i) context-free grammar Chomsky normalization and \n   \n   More information can be found in the paper \"Formalization of \n   the Chomsky Normal Form for Context-Free Grammars\", submitted \n   to SBMF 2019.\n   \n   The file README.md describes the contents of each file and \n   provides instructions on how to compile them.\n   \n   Marcus Vinícius Midena Ramos\n   mvmramos@gmail.com\n\n   --------------------------------------------------------------------- *)\n\n(* --------------------------------------------------------------------- *)\n(* SIMPLIFICATION - EMPTY RULES                                          *)\n(* --------------------------------------------------------------------- *)\n\nRequire Import List.\nRequire Import Ring.\nRequire Import Omega.\nRequire Import Decidable.\n\nRequire Import misc_arith.\nRequire Import misc_list.\nRequire Import cfg.\nRequire Import useless.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport ListNotations.\nOpen Scope list_scope.\n\n(* --------------------------------------------------------------------- *)\n(* SIMPLIFICATION - EMPTY RULES - DEFINITIONS                            *)\n(* --------------------------------------------------------------------- *)\n\nSection EmptyRules_1_Definitions.\n\nVariables non_terminal terminal: Type.\n\nInductive non_terminal': Type:=\n| Lift_nt: non_terminal -> non_terminal'\n| New_ss. \n\nNotation symbol:= (non_terminal + terminal)%type.\nNotation symbol':= (non_terminal' + terminal)%type.\nNotation nlist:= (list non_terminal).\nNotation nlist':= (list non_terminal').\nNotation tlist:= (list terminal).\nNotation sentence := (list terminal).\nNotation sf := (list (non_terminal + terminal)).\nNotation sf' := (list (non_terminal' + terminal)).\nNotation term_lift:= ((terminal_lift non_terminal) terminal).\n\nDefinition symbol_lift (s: symbol): symbol':=\nmatch s with\n| inl n => inl (Lift_nt n)\n| inr t => inr t\nend.\n\nLemma symbol_lift_inj:\ninjective _ _ symbol_lift.\nProof.\nunfold injective.\nintros e1 e2 H.\ndestruct e1, e2.\n- simpl in H.\n  inversion H.\n  reflexivity.\n- simpl in H.\n  inversion H.\n- simpl in H.\n  inversion H.\n- simpl in H.\n  inversion H.\n  reflexivity.\nQed.\n\nLemma symbol_lift_equiv_terminal_lift:\nforall s: sentence,\n(map symbol_lift (map term_lift s)) = (map (@terminal_lift _ _) s).\nProof.\ninduction s.\n- simpl. \n  reflexivity.\n- simpl. \n  rewrite IHs.\n  change (terminal_lift non_terminal' a) with (inr non_terminal' a).\n  reflexivity.\nQed.\n\nDefinition sf_lift (s: sf): sf':=\nmap symbol_lift s.\n\nDefinition sf_list_lift (l: list sf): list sf':=\nmap sf_lift l.\n\nLemma symbol_lift_exists:\nforall a': symbol', \na' <> (inl New_ss) ->\nexists a: symbol,\na' = symbol_lift a.\nProof.\nintros a'.\ndestruct a'.\n- destruct n.\n  + exists (inl n).  \n    simpl.\n    reflexivity.\n  + intros H. \n    destruct H. \n    reflexivity. \n- exists (inr t).\n  simpl. \n  reflexivity. \nQed.\n\nLemma sf_lift_exists:\nforall s': sf',\n~ In (inl New_ss) s' ->\nexists s: sf,\ns' = sf_lift s.\nProof.\nintros s' H.\ninduction s'.\n- exists [].\n  simpl.\n  reflexivity.\n- assert (H1: ~ In (inl New_ss) s'). \n    {\n    intros H1. \n    apply H. \n    apply in_cons. \n    exact H1. \n    }\n  specialize (IHs' H1). \n  destruct IHs' as [s H2].\n  assert (H3: a <> (inl New_ss) -> exists b: symbol, a = symbol_lift b).\n    {\n    intros H3. \n    apply symbol_lift_exists.\n    exact H3.\n    }\n  simpl in H.\n  apply not_or in H.\n  destruct H as [H _].\n  specialize (H3 H).\n  destruct H3 as [b H3].\n  exists (b :: s).\n  simpl. \n  rewrite <- H3.\n  apply app_eq.\n  exact H2.\nQed.\n\nInductive g_emp_rules (g: cfg _ _): non_terminal' -> sf' -> Prop :=\n| Lift_direct : \n       forall left: non_terminal,\n       forall right: sf,\n       right <> [] -> rules g left right ->\n       g_emp_rules g (Lift_nt left) (map symbol_lift right)\n| Lift_indirect:\n       forall left: non_terminal,\n       forall right: sf,\n       g_emp_rules g (Lift_nt left) (map symbol_lift right)->\n       forall s1 s2: sf, \n       forall s: non_terminal,\n       right = s1 ++ (inl s) :: s2 ->\n       empty g (inl s) ->\n       s1 ++ s2 <> [] ->\n       g_emp_rules g (Lift_nt left) (map symbol_lift (s1 ++ s2))\n| Lift_start_emp: \n       g_emp_rules g New_ss [inl (Lift_nt (start_symbol g))]. \n\nLemma g_emp_finite:\nforall g: cfg _ _,\nexists n: nat,\nexists ntl: nlist',\nexists tl: tlist,\nIn New_ss ntl /\\\nforall left: non_terminal',\nforall right: sf',\ng_emp_rules g left right ->\n(length right <= n) /\\\n(In left ntl) /\\\n(forall s: non_terminal', In (inl s) right -> In s ntl) /\\\n(forall s: terminal, In (inr s) right -> In s tl).\nProof.\nintros g.\ndestruct (rules_finite g) as [n [ntl [tl H1]]].\nexists (S n), (New_ss :: map Lift_nt ntl), tl.\nsplit.\n- destruct H1 as [H1 _].\n  simpl. \n  left. \n  reflexivity. \n- intros left right H2.\n  destruct H1 as [H1' H1].\n  induction H2.\n  + specialize (H1 left right H0).\n    destruct H1 as [H4 [H5 H6]].\n    split.\n    * apply length_map_le.\n      omega. \n    * {\n      split.\n      - simpl. \n        right. \n        apply in_map. \n        exact H5.\n      - split. \n        + intros s HH.\n          destruct s.\n          * simpl. \n            right.\n            apply in_map.\n            apply H6.\n            apply in_map_iff in HH.\n            destruct HH as [x [HH1 HH2]].\n            {\n            destruct x.\n            - simpl in HH1.\n              inversion HH1.\n              subst.\n              exact HH2.\n            - simpl in HH1.\n              inversion HH1.\n            }\n          * simpl. \n            left. \n            reflexivity. \n        + intros s HH.\n          apply H6.\n          apply in_map_iff in HH.\n          destruct HH as [x [HH1 HH2]].\n          destruct x.\n          * simpl in HH1.\n            inversion HH1.\n          * simpl in HH1.\n            inversion HH1.\n            subst.\n            exact HH2.\n      }\n  + subst.\n    destruct IHg_emp_rules as [H4 [H5 H6]].\n    split.\n    * apply length_map_le. \n      rewrite map_app in H4.\n      simpl in H4.\n      apply length_cons_le in H4.\n      {\n      replace (map symbol_lift s1 ++ map symbol_lift s2) with (map symbol_lift (s1 ++ s2)) in H4.\n      - apply length_map_le_inv in H4.\n        exact H4.\n      - apply map_app.\n      }\n    * {\n      split.\n      - exact H5.\n      - split.\n        + intros s0 H7.\n          apply H6.\n          rewrite map_app in H7.\n          apply in_app_or in H7.\n          rewrite map_app. \n          apply in_or_app.\n          destruct H7 as [H7 | H7].\n          * left.\n            exact H7.\n          * right.\n            simpl.\n            right. \n            exact H7.\n        + destruct H6 as [_ H6].\n          intros s0 H7.\n          apply H6.\n          rewrite map_app in H7.\n          apply in_app_or in H7.\n          rewrite map_app. \n          apply in_or_app.\n          destruct H7 as [H7 | H7].\n          * left.\n            exact H7.\n          * right.\n            simpl.\n            right. \n            exact H7.\n      }\n  + split.\n    * simpl.\n      omega.\n    * {\n      split.\n      - simpl.\n        left.\n        reflexivity.\n      - split.\n        + intros s H2.\n          simpl in H2.\n          destruct H2 as [H2 | H2].\n          * inversion H2.\n            simpl.\n            right.\n            apply in_map.\n            exact H1'.\n          * contradiction.\n        + intros s H. \n          simpl in H.\n          destruct H as [H | H].\n          * inversion H.\n          * contradiction.\n      }\nQed.\n\nDefinition g_emp (g: cfg non_terminal terminal): cfg non_terminal' terminal := {|\nstart_symbol:= New_ss;\nrules:= g_emp_rules g;\nrules_finite:= g_emp_finite g\n|}.\n\nEnd EmptyRules_1_Definitions.\n\n(* --------------------------------------------------------------------- *)\n(* SIMPLIFICATION - EMPTY RULES - LEMMAS AND THEOREMS                    *)\n(* --------------------------------------------------------------------- *)\n\nSection EmptyRules_1_Lemmas.\n\nVariables non_terminal non_terminal1 non_terminal2 terminal: Type.\n\nNotation symbol:= (non_terminal + terminal)%type.\nNotation symbol':= (non_terminal' + terminal)%type.\nNotation nlist:= (list non_terminal).\nNotation nlist':= (list non_terminal' _).\nNotation tlist:= (list terminal).\nNotation sentence := (list terminal).\nNotation sf := (list (non_terminal + terminal)).\nNotation sf' := (list ((non_terminal' non_terminal) + terminal)).\nNotation term_lift:= ((terminal_lift non_terminal) terminal).\n\nLemma produces_non_empty_equiv_non_empty:\nforall g: cfg non_terminal terminal,\nproduces_non_empty g -> non_empty g.\nProof.\nintros g H.\nunfold non_empty. \nunfold useful.\nunfold produces_non_empty in H.\ndestruct H as [s [H1 H2]].\nexists s.\nexact H1.\nQed.\n\nLemma non_empty_equiv_or:\nforall g: cfg non_terminal terminal,\nnon_empty g -> (produces_empty g \\/ produces_non_empty g).\nProof.\nintros g H.\nunfold non_empty in H.\nunfold useful in H.\ndestruct H as [s H1].\nassert (H2: s = [] \\/ s <> []).\n  {\n  apply nil_not_nil.\n  }\ndestruct H2 as [H2 | H2].\n- subst.\n  left.\n  exact H1.\n- right.\n  exists s.\n  exact (conj H1 H2).\nQed.\n\nLemma start_symbol_not_in_rhs_g_emp: \nforall g: cfg non_terminal terminal,\nstart_symbol_not_in_rhs (g_emp g).\nProof.\nintros g.\nunfold start_symbol_not_in_rhs.\nintros left right H1 H2.\ninversion H1.\n- subst. \n  simpl in H2. \n  apply in_split in H2. \n  destruct H2 as [l1 [l2 H2]].\n  symmetry in H2. \n  apply map_expand in H2.\n  destruct H2 as [s1' [s2' [H3 [H4 H5]]]].\n  destruct s2'.\n  + inversion H5.\n  + simpl in H5.\n    inversion H5.\n    destruct s.\n    * simpl in H6.\n      inversion H6.\n    * simpl in H6.\n      inversion H6.\n- subst.\n  simpl in H2. \n  apply in_split in H2. \n  destruct H2 as [l1 [l2 H2]].\n  symmetry in H2. \n  apply map_expand in H2.\n  destruct H2 as [s1' [s2' [H5 [H6 H7]]]].\n  destruct s2'.\n  + inversion H7.\n  + simpl in H7.\n    inversion H7.\n    destruct s0.\n    * simpl in H2.\n      inversion H2.\n    * simpl in H2.\n      inversion H2.\n- rewrite <- H0 in H2. \n  simpl in H2.\n  destruct H2 as [H2 | H2].\n  + inversion H2.\n  + contradiction.\nQed.\n\nLemma g_emp_not_derives_empty:\nforall g: cfg non_terminal terminal,\nforall n: (non_terminal' _),\n~ derives (g_emp g) [inl n] [].\nProof.\nintros g n H.\ninversion H.\nclear H.\nsubst.\nsimpl in H3.\ninversion H3.\n- subst.\n  apply app_eq_nil in H0.\n  destruct H0 as [_ H0].\n  apply app_eq_nil in H0.\n  destruct H0 as [H0 _].\n  apply map_eq_nil in H0. \n  contradiction.\n- subst.\n  apply app_eq_nil in H0.\n  destruct H0 as [_ H0].\n  apply app_eq_nil in H0.\n  destruct H0 as [H0 _].\n  rewrite H0 in H3.\n  inversion H3.\n  + subst.\n    apply map_eq_nil in H6.\n    contradiction. \n  + apply map_eq_nil in H6.\n    contradiction. \n- subst.\n  destruct s2.\n  + inversion H0.\n  + inversion H0.\nQed.\n\nLemma g_emp_has_no_empty_rules:\nforall g: cfg non_terminal terminal,\nhas_no_empty_rules (g_emp g).\nProof.\nintros g.\nunfold has_no_empty_rules.\nintros left right H.\ninversion H.\n- apply map_not_nil_inv. \n  exact H0.\n- apply map_not_nil_inv. \n  exact H3.\n- apply not_eq_sym.\n  apply nil_cons.\nQed.\n\nLemma in_left_not_empty:\nforall g: cfg non_terminal terminal,\nforall x: non_terminal' _,\nforall right: sf',\nrules (g_emp g) x right -> ~ empty (g_emp g) (inl x).\nProof.\nintros g x right H1 H2.\nsimpl in H1.\ninversion H1.\n- clear H1.\n  subst.\n  apply g_emp_not_derives_empty in H2.\n  contradiction.\n- clear H1. \n  subst.\n  apply g_emp_not_derives_empty in H2.\n  contradiction.\n- subst.\n  apply g_emp_not_derives_empty in H2.\n  contradiction.\nQed.\n\nLemma in_right_not_empty:\nforall g: cfg non_terminal terminal,\nforall x n: non_terminal' _,\nforall right: sf',\nrules (g_emp g) x right -> In (inl n) right -> ~ empty (g_emp g) (inl n).\nProof.\nintros g x n right H1 H2 H3.\nsimpl in H1.\ninversion H1.\n- clear H1.\n  subst.\n  apply g_emp_not_derives_empty in H3.\n  contradiction.\n- clear H1. \n  subst.\n  apply g_emp_not_derives_empty in H3.\n  contradiction.\n- subst.\n  apply g_emp_not_derives_empty in H3.\n  contradiction.\nQed.\n\nLemma g_emp_has_no_nullable_symbols:\nforall g: cfg non_terminal terminal,\nhas_no_nullable_symbols (g_emp g).\nProof.\nintros g.\nunfold has_no_nullable_symbols.\nintros s H1.\ndestruct s as [nt | t].\n- apply g_emp_not_derives_empty in H1.\n  contradiction.\n- unfold empty in H1.\n  inversion H1.\n  apply app_eq_nil in H.\n  destruct H as [_ H].\n  apply app_eq_nil in H.\n  destruct H as [H _].\n  subst.\n  apply g_emp_has_no_empty_rules in H3.\n  destruct H3.\n  reflexivity.\nQed.  \n\nLemma rules_g_emp_g:\nforall g: cfg non_terminal terminal,\nforall left: non_terminal,\nforall right: sf,\nrules (g_emp g) (Lift_nt left) (map (@symbol_lift _ _) right) ->\nrules g left right \\/ derives g [inl left] right.\nProof.\nintros g left right H.\nsimpl in H.\nremember (Lift_nt left) as w1.\nremember (map (symbol_lift (terminal:=terminal)) right) as w2.\ngeneralize left right Heqw1 Heqw2. \nclear left right Heqw1 Heqw2.\ninduction H.\n- intros left0 right0 Heqw1 Heqw2.\n  inversion Heqw1.\n  apply map_eq in Heqw2.\n  + subst.\n    left.\n    exact H0.\n  + apply symbol_lift_inj.\n- intros left0 right0 Heqw1 Heqw2.\n  inversion Heqw1.\n  apply map_eq in Heqw2.\n  + subst.\n    specialize (IHg_emp_rules left0 (s1 ++ inl s :: s2)).   \n    specialize (IHg_emp_rules (eq_refl (Lift_nt left0))).\n    specialize (IHg_emp_rules (eq_refl (map (symbol_lift (terminal:=terminal)) (s1 ++ inl s :: s2)))).\n    destruct IHg_emp_rules as [HH | HH].\n    * right.\n      {\n      replace (s1 ++ s2) with (s1 ++ [] ++ s2).\n      - apply derives_subs with (s3:=[inl s]).\n        + apply derives_start.\n          exact HH.\n        + exact H1. \n      - simpl.   \n        reflexivity.\n      }\n    * right.\n      {       \n      replace (s1 ++ s2) with (s1 ++ [] ++ s2).\n      - apply derives_subs with (s3:=[inl s]).\n        + exact HH.\n        + exact H1.\n      - simpl.\n        reflexivity.\n      }\n  + apply symbol_lift_inj.  \n- intros left right H1 H2.\n  inversion H1.\nQed.\n\nLemma derives_g_emp_g:\nforall g: cfg _ _,\nforall n: non_terminal,\nforall s: sf,\nderives (g_emp g) [inl (Lift_nt n)] (map (@symbol_lift _ _) s) -> derives g [inl n] s.\nProof.\nintros g n s H.\nremember [inl (Lift_nt n)] as w1. \nremember (map (symbol_lift (terminal:=terminal)) s) as w2.\ngeneralize n s Heqw1 Heqw2.\nclear s n Heqw1 Heqw2.\ninduction H.\n- intros n0 s1 Heqw1 Heqw2. \n  subst.\n  destruct s1.\n  + simpl in Heqw2.\n    inversion Heqw2.\n  + destruct s.\n    * simpl in Heqw2. \n      inversion Heqw2.\n      symmetry in H1.\n      apply map_eq_nil in H1.\n      subst.\n      apply derives_refl.\n    * simpl in Heqw2.\n      inversion Heqw2.\n- intros n s Heqw1 Heqw2.\n  destruct left.\n  + assert (H1: exists r: sf, right = sf_lift r). \n      {\n      apply sf_lift_exists.\n      intros H7.\n      apply in_split in H7.\n      destruct H7 as [l1 [l2 H7]].\n      subst.\n      apply map_expand in Heqw2.\n      destruct Heqw2 as [s1' [s2' [_ [_ H1]]]].\n      symmetry in H1.\n      apply map_expand in H1.\n      destruct H1 as [s1'0 [s2'0 [H1 [H2 H3]]]].\n      symmetry in H2.\n      apply map_expand in H2.\n      destruct H2 as [s1'1 [s2'1 [H4 [H5 H6]]]].\n      destruct s2'1.\n      - inversion H6.\n      - destruct s0. \n        + inversion H6.\n        + inversion H6.\n      }\n    destruct H1 as [r H1].\n    subst.\n    apply map_expand in Heqw2.\n    destruct Heqw2 as [s1' [s2' [H1 [H2 H3]]]].\n    symmetry in H3.\n    apply map_expand in H3.\n    destruct H3 as [s1'0 [s2'0 [H4 [H5 H6]]]].\n    rewrite H1.\n    rewrite H4.\n    apply rules_g_emp_g in H0.\n    destruct H0 as [H0 | H0].\n    * specialize (IHderives n).\n      unfold sf_lift in H5.\n      {\n      apply map_eq in H5.\n      - subst. \n        specialize (IHderives (s1' ++ (inl n0) :: s2'0)).\n        apply derives_step with (left:= n0).\n        + apply IHderives.\n          * reflexivity.\n          * change (s1' ++ inl n0 :: s2'0) with (s1' ++ [inl n0] ++ s2'0).\n            repeat rewrite map_app.\n            reflexivity.\n        + exact H0.\n      - apply symbol_lift_inj.\n      }\n    * specialize (IHderives n).\n      unfold sf_lift in H5.\n      {\n      apply map_eq in H5.\n      - subst. \n        specialize (IHderives (s1' ++ (inl n0) :: s2'0)).\n        apply derives_subs with (s3:= [inl n0]).\n        + apply IHderives.\n          * reflexivity.\n          * change (s1' ++ inl n0 :: s2'0) with (s1' ++ [inl n0] ++ s2'0).\n            repeat rewrite map_app.\n            reflexivity.\n        + exact H0.\n      - apply symbol_lift_inj.\n      }\n  + rewrite Heqw1 in H. \n    apply exists_rule' in H.\n    destruct H as [H | H].\n    * destruct H as [H _].\n      inversion H.\n    * destruct H as [left [right0 [H H1]]].\n      apply start_symbol_not_in_rhs_g_emp in H.\n      simpl in H.\n      contradiction.\nQed.\n\nLemma rules_g_g_emp:\nforall g: cfg _ _, \nforall left: non_terminal,\nforall right: sf,\nright <> [] ->\nrules g left right ->\nrules (g_emp g) (Lift_nt left) (map (@symbol_lift _ _) right).\nProof.\nintros g left right H.\nsimpl.\napply Lift_direct.\nexact H.\nQed.\n\nInductive sfmatch g: sf -> list sf -> Prop :=\n| sfmatch_nil: \n    sfmatch g [] []\n| sfmatch_term: \n    forall t xs xxs,\n    sfmatch g xs xxs -> sfmatch g (inr t :: xs) ([inr t] :: xxs)\n| sfmatch_nonterm: \n   forall nt xs xxs p,\n    (p = [] -> empty g (inl nt)) ->\n    (p <> [] -> derives (g_emp g) [inl (Lift_nt nt)] (map (@symbol_lift _ _) p)) ->\n    sfmatch g xs xxs -> sfmatch g (inl nt :: xs) (p :: xxs).\n\nFixpoint flatten (l: list sf): sf :=\nmatch l with\n| [] => []\n| x :: xs => x ++ flatten xs\nend.\n\nFixpoint elim_emp (l: sf) (ll: list sf): sf :=\nmatch l with\n| [] => []\n| (x :: xs) => match ll with\n               | [] => l\n               | [] :: ll' => elim_emp xs ll'\n               | p :: ll' => x :: elim_emp xs ll'\n               end\nend.\n\nLemma sfmatch_left_nil:\nforall g: cfg _ _,\nforall l: list sf,\nsfmatch g [] l ->\nl = [].\nProof.\nintros g l H.\ninversion H.\nreflexivity.\nQed.\n\nLemma elim_emp_not_nil:\nforall right: sf,\nforall split: list sf,\nelim_emp right split <> [] ->\nright <> [].\nProof.\nintros right split H.\ndestruct right.\n- simpl in H.\n  destruct H.\n  reflexivity.\n- apply not_eq_sym.\n  apply nil_cons.\nQed.\n\nLemma flatten_map:\nforall x: list sf,\nforall y: sentence,\nflatten x = map term_lift y ->\ny <> [] ->\nx <> [].\nProof.\nintros x y H1 H2.\ndestruct x.\n- simpl in H1.\n  symmetry in H1. \n  apply map_eq_nil in H1.\n  subst.\n  destruct H2.\n  reflexivity.\n- apply not_eq_sym.\n  apply nil_cons.\nQed.\n\nLemma flatten_not_nil:\nforall x: sf,\nflatten [x] <> [] ->\nx <> [].\nintros x H.\ndestruct x.\n- simpl in H.\n  destruct H.\n  reflexivity.\n- apply not_eq_sym.\n  apply nil_cons.\nQed.\n\nLemma flatten_not_nil_exists:\nforall x: list sf,\nflatten x <> [] ->\nexists x1 x3: list sf,\nexists x2: sf,\nx = x1 ++ [x2] ++ x3 /\\\nx2 <> [].\nProof.\ninduction x.\n- intro H.\n  simpl in H.\n  destruct H.\n  reflexivity.\n- intro H.\n  simpl in H.\n  apply app_not_nil in H.\n  destruct H as [H | H].\n  + exists [], x, a.\n    split. \n    * simpl.  \n      reflexivity.\n    * exact H.\n  + specialize (IHx H).\n    destruct IHx as [x1 [x3 [x2 [H1 H2]]]].\n    subst.\n    exists (a :: x1), x3, x2.\n    split. \n    * simpl. \n      reflexivity.\n    * exact H2. \nQed.\n\nLemma sfmatch_derives:\nforall g: cfg _ _,\nforall l1 l2: sf,\nforall l: list sf,\nforall x: non_terminal + terminal,\nsfmatch g (l1 ++ [x] ++ l2) l ->\nexists p: sf,\nexists l3 l4: list sf,\nl = l3 ++ [p] ++ l4 /\\\nsfmatch g l1 l3 /\\\nderives g [x] p /\\\nsfmatch g l2 l4.\nProof.\nintros g l1.\ninduction l1.\n- intros l2 l x H.\n  simpl in H.\n  inversion H.\n  + (* terminal *)\n    subst.\n    exists [inr t], [], xxs.\n    split.\n    * simpl. \n      reflexivity.\n    * {\n      split.\n      - constructor.\n      - split.\n        + constructor.\n        + exact H3.\n      }\n  + (* non-terminal *)\n    subst.\n    exists p, [], xxs.\n    split.\n    * simpl.\n      reflexivity.\n    * {\n      split. \n      - constructor. \n      - split. \n        + assert (H6: p = [] \\/ p <> []).\n            {\n            apply nil_not_nil.\n            }\n          destruct H6 as [H6 | H6].\n          * subst. \n            specialize (H2 (eq_refl [])).\n            exact H2.\n          * apply derives_g_emp_g.\n            apply H3.\n            exact H6.\n        + exact H5.\n      } \n- intros l2 l x H.\n  inversion H.\n  clear H. \n  + (* terminal *)\n    subst.\n    specialize (IHl1 l2 xxs x H3).\n    destruct IHl1 as [p [l3 [l4 [H11 [H12 [H13 H14]]]]]].\n    exists p, ([inr t] :: l3), l4.\n    split. \n    * simpl.\n      rewrite H11.\n      reflexivity.\n    * {\n      split. \n      - apply sfmatch_term.\n        exact H12.\n      - split.\n        + exact H13.\n        + exact H14.\n      }\n  + (* non-terminal *)\n    subst. \n    specialize (IHl1 l2 xxs x H5).\n    destruct IHl1 as [p' [l3 [l4 [H11 [H12 [H13 H14]]]]]].\n    exists p', ([p] ++ l3), l4.\n    split.\n    * simpl. \n      rewrite H11.\n      reflexivity.\n    * {\n      split.\n      - apply sfmatch_nonterm.\n        + exact H2.\n        + exact H3.\n        + exact H12.\n      - split. \n        + exact H13.\n        + exact H14.\n      }\nQed.\n\nLemma sfmatch_derives_inv:\nforall g: cfg _ _,\nforall l: sf,\nforall l3 l4: list sf,\nforall p: sf,\nsfmatch g l (l3 ++ [p] ++ l4) ->\nexists x: non_terminal + terminal,\nexists l1 l2: sf,\nl = l1 ++ [x] ++ l2 /\\\nsfmatch g l1 l3 /\\\nsfmatch g [x] [p] /\\\nsfmatch g l2 l4.\nProof.\nintros g l l3 l4 p H.\nremember (l3 ++ [p] ++ l4) as w.\ngeneralize dependent l4.\ngeneralize dependent l3.\ngeneralize dependent p.\ninduction H.\n- (* empty *)\n  intros p l3 l4 H. \n  destruct l3.\n  + inversion H.\n  + inversion H.\n- (* terminal *)\n  intros p l3 l4 H1. \n  destruct l3.\n  + simpl in H1.\n    inversion H1.\n    exists (inr t), [], xs.\n    split. \n    * simpl. \n      reflexivity.\n    * {\n      split.\n      - constructor.\n      - split.\n        + constructor.\n          constructor.\n        + rewrite <- H3.\n          exact H.\n      }\n  + inversion H1.\n    clear H1.\n    subst.\n    specialize (IHsfmatch p l3 l4 (eq_refl (l3 ++ p :: l4))).\n    destruct IHsfmatch as [x [l1 [l2 [H1 [H2 [H3 H4]]]]]].\n    rewrite H1. \n    exists x, (inr t :: l1), l2.\n    split.\n    * simpl. \n      reflexivity.\n    * {\n      split.\n      - apply sfmatch_term.\n        exact H2.\n      - split.\n        + exact H3.\n        + exact H4.\n      }\n- (* non-terminal *)\n  intros p0 l3 l4 H2.\n  destruct l3.\n  inversion H2.\n  clear H2.\n  subst.\n  + assert (H5: p0 = [] \\/ p0 <> []).\n      {\n      apply nil_not_nil.\n      }\n    destruct H5 as [H5 | H5].\n    * subst. \n      exists (inl nt), [], xs.\n      {\n      split. \n      - simpl. \n        reflexivity.\n      - split.\n        + constructor.\n        + split.\n          * {\n            constructor.\n            - exact H.\n            - exact H0.\n            - constructor.\n            }\n          * exact H1.\n      }\n    * exists (inl nt), [], xs.\n      {\n      split. \n      - simpl. \n        reflexivity.\n      - split.\n        + constructor.\n        + split.\n          * {\n            constructor.\n            - exact H.\n            - exact H0.\n            - constructor.\n            }\n          * exact H1.\n      }\n  + assert (H5: p = [] \\/ p <> []).\n      {\n      apply nil_not_nil.\n      }\n    destruct H5 as [H5 | H5].\n    * inversion H2. \n      subst. \n      clear H2. \n      specialize (IHsfmatch p0 l3 l4).\n      specialize (IHsfmatch (eq_refl (l3 ++ p0 :: l4))).\n      destruct IHsfmatch as [x [l1 [l2 [H2 [H3 [H4 H5]]]]]].\n      rewrite H2.\n      exists x, (inl nt :: l1), l2.\n      {\n      split. \n      - simpl. \n        reflexivity.\n      - split.\n        + apply sfmatch_nonterm.\n          * exact H.\n          * exact H0.\n          * exact H3.\n        + split.\n          * exact H4.\n          * exact H5.\n      }\n    * inversion H2.\n      clear H2.\n      subst.\n      specialize (IHsfmatch p0 l3 l4).\n      specialize (IHsfmatch (eq_refl (l3 ++ p0 :: l4))).\n      destruct IHsfmatch as [x [l1 [l2 [H2 [H3 [H4 H6]]]]]].\n      rewrite H2.\n      exists x, (inl nt :: l1), l2.\n      {\n      split. \n      - simpl. \n        reflexivity.\n      - split.\n        + apply sfmatch_nonterm.\n          * exact H.\n          * exact H0.\n          * exact H3.\n        + split.\n          * exact H4.\n          * exact H6.\n      }\nQed.\n\nLemma sfmatch_elim_emp_not_nil:\nforall g: cfg _ _,\nforall x: non_terminal + terminal,\nforall p: sf,\nsfmatch g [x] [p] ->\np <> [] ->\nelim_emp [x] [p] <> [].\nProof.\nintros g x p H1 H2.\ninversion H1.\n- simpl.\n  apply not_eq_sym. \n  apply nil_cons.\n- subst.\n  destruct p.\n  + destruct H2.\n    reflexivity.\n  + simpl.\n    apply not_eq_sym.\n    apply nil_cons.\nQed. \n\nLemma sfmatch_combine:\nforall g: cfg _ _,\nforall l1 l3: sf,\nforall l2 l4: list sf,\nsfmatch g l1 l2 ->\nsfmatch g l3 l4 ->\nsfmatch g (l1 ++ l3) (l2 ++ l4).\nProof.\nintros g l1 l3 l2 l4 H1.\ninduction H1.\n- simpl. \n  auto.\n- intros H2.\n  specialize (IHsfmatch H2).\n  apply sfmatch_term with (t:= t) in IHsfmatch.\n  exact IHsfmatch.\n- intros H2.\n  specialize (IHsfmatch H2).\n  assert (H3: p = [] \\/ p <> []).\n    {\n    apply nil_not_nil.\n    }\n  destruct H3 as [H3 | H3].\n  + specialize (H H3).\n    apply sfmatch_nonterm with (nt:= nt) (p:= p) in IHsfmatch.\n    * exact IHsfmatch.\n    * intros _.\n      exact H.\n    * exact H0.\n  + specialize (H0 H3).\n    apply sfmatch_nonterm with (nt:= nt) (p:= p) in IHsfmatch.\n    * exact IHsfmatch.\n    * exact H.\n    * intros _.\n      exact H0.\nQed.\n\nLemma elim_emp_split:\nforall g: cfg _ _,\nforall l1 l3: sf,\nforall l2 l4: list sf,\nsfmatch g l1 l2 ->\nsfmatch g l3 l4 ->\nelim_emp (l1 ++ l3) (l2 ++ l4) = (elim_emp l1 l2) ++ (elim_emp l3 l4).\nProof.\nintros g l1 l3 l2 l4 H.\ngeneralize dependent l4.\ngeneralize dependent l3.\ninduction H.\n- subst.\n  intros. \n  simpl. \n  reflexivity.\n- intros. \n  simpl.\n  apply app_eq.\n  apply IHsfmatch.\n  exact H0.\n- intros l3 l4 H2.\n  assert (H3: p = [] \\/ p <> []).\n    {\n    apply nil_not_nil.\n    }\n  destruct H3 as [H3 | H3].\n  + subst.\n    simpl.\n    apply IHsfmatch.\n    exact H2.\n  + destruct p. \n    * destruct H3. \n      reflexivity.\n    * simpl. \n      apply app_eq.\n      apply IHsfmatch.\n      exact H2.\nQed.\n\nLemma elim_emp_not_nil_add_left:\nforall g: cfg _ _,\nforall l1 l1': sf,\nforall l2 l2': list sf,\nsfmatch g l1 l2 ->\nelim_emp l1 l2 <> [] ->\nsfmatch g l1' l2' ->\nelim_emp (l1' ++ l1) (l2' ++ l2) <> [].\nProof.\nintros g l1 l1' l2 l2' H.\ngeneralize dependent l2'.\ngeneralize dependent l1'.\ninversion H.\n- intros.\n  simpl in H2.\n  destruct H2.\n  reflexivity.\n- intros.\n  rewrite elim_emp_split with (g:= g).\n  + apply app_not_nil_inv.\n    right.\n    exact H3.\n  + exact H4.\n  + apply sfmatch_term.\n    exact H0.\n- intros.\n  rewrite elim_emp_split with (g:= g).\n  + apply app_not_nil_inv.\n    right.\n    exact H5.\n  + exact H6.\n  + apply sfmatch_nonterm.\n    * exact H0.\n    * exact H1.\n    * exact H2.\nQed.\n\nLemma elim_emp_not_nil_add_right:\nforall g: cfg _ _,\nforall l1 l1': sf,\nforall l2 l2': list sf,\nsfmatch g l1 l2 ->\nelim_emp l1 l2 <> [] ->\nsfmatch g l1' l2' ->\nelim_emp (l1 ++ l1') (l2 ++ l2') <> [].\nProof.\nintros g l1 l1' l2 l2' H.\ngeneralize dependent l2'.\ngeneralize dependent l1'.\ninversion H.\n- intros.\n  simpl in H2.\n  destruct H2.\n  reflexivity.\n- intros.\n  rewrite elim_emp_split with (g:= g).\n  + apply app_not_nil_inv.\n    left.\n    exact H3.\n  + rewrite H1. \n    rewrite H2. \n    exact H.\n  + exact H4.\n- intros.\n  rewrite elim_emp_split with (g:= g).\n  + apply app_not_nil_inv.\n    left.\n    exact H5.\n  + rewrite H3. \n    rewrite H4. \n    exact H.\n  + exact H6. \nQed.\n\nLemma elim_emp_not_emp:\nforall g: cfg _ _,\nforall l1 l2: sf,\nforall x: non_terminal + terminal,\nforall l3 l4: list sf,\nforall p: sf,\nsfmatch g l1 l3 ->\nsfmatch g [x] [p] ->\nsfmatch g l2 l4 ->\np <> [] ->\nelim_emp (l1 ++ [x] ++ l2) (l3 ++ [p] ++ l4) <> [].\nProof.\nintros g l1 l2 x l3 l4 p H2 H3 H4 H5.\ndestruct x.\n- (* non-terminal *)\n  assert (H3':= H3). \n  apply sfmatch_elim_emp_not_nil in H3.\n  + assert (H3'':= H3').\n    apply elim_emp_not_nil_add_left with (l1':= l1) (l2':= l3) in H3'.\n    * {\n      apply elim_emp_not_nil_add_right with (g:= g) (l1':= l2) (l2':= l4) in H3'.\n      - repeat rewrite <- app_assoc in H3'. \n        exact H3'.\n      - apply sfmatch_combine.\n        + exact H2.\n        + exact H3''. \n      - exact H4.\n      }\n    * exact H3.\n    * exact H2.\n  + exact H5.\n- (* terminal *)\n  assert (H3':= H3).\n  apply sfmatch_elim_emp_not_nil in H3.\n  + assert (H3'':= H3').\n    apply elim_emp_not_nil_add_left with (g:= g) (l1':= l1) (l2':= l3) in H3'.\n    * {\n      apply elim_emp_not_nil_add_right with (g:= g) (l1':= l2) (l2':= l4) in H3'.\n      - repeat rewrite <- app_assoc in H3'. \n        exact H3'.\n      - apply sfmatch_combine.\n        + exact H2.\n        + exact H3''. \n      - exact H4.\n      }\n    * exact H3.\n    * exact H2.\n  + exact H5.\nQed.\n\nLemma flatten_elim_emp:\nforall x: sf,\nforall y: list sf,\nforall g: cfg _ _,\nsfmatch g x y ->\nflatten y <> [] ->\nelim_emp x y  <> [].\nProof.\nintros x y g H3 H4.\napply flatten_not_nil_exists in H4.\ndestruct H4 as [x1 [x2 [x3 [H5 H6]]]].\nassert (H3':= H3).\nrewrite H5 in H3. \napply sfmatch_derives_inv in H3.\ndestruct H3 as [x0 [l1 [l2 [H11 [H12 [H13 H14]]]]]].\nsubst.\napply elim_emp_not_emp with (g:= g).\n- exact H12.\n- exact H13.\n- exact H14.\n- exact H6.\nQed.\n\nLemma sfmatch_derives_first:\nforall g: cfg _ _,\nforall l1: sf,\nforall l2: list sf,\nsfmatch g l1 l2 ->\n(l1 = [] /\\ l2 = []) \\/\n(exists a1: non_terminal + terminal,\n exists l1': sf,\n exists a2: sf,\n exists l2': list sf,\n l1 = a1 :: l1' /\\\n l2 = a2 :: l2' /\\\n derives g [a1] a2 /\\ sfmatch g l1' l2').\nProof.\nintros g l1 l2 H.\nassert (H1: l1 = [] \\/ l1 <> []).\n  {\n  apply nil_not_nil.\n  }\ndestruct H1 as [H1 | H1].\n- left.\n  subst.\n  inversion H.\n  auto.\n- right.\n  destruct l1.\n  + destruct H1.\n    reflexivity.\n  + clear H1.\n    change (s :: l1) with ([] ++ [s] ++ l1) in H.\n    apply sfmatch_derives in H.\n    destruct H as [p [l3 [l4 [H2 [H3 [H4 H5]]]]]].\n    apply sfmatch_left_nil in H3.\n    exists s, l1, p, l4.\n    split. \n    * reflexivity.\n    * {\n      split.\n      - rewrite H3 in H2.\n        exact H2.\n      - split.\n        + exact H4.\n        + exact H5.\n      }\nQed.  \n\nLemma right_emp_prop_aux:\nforall g left r2 rl2,\nsfmatch g r2 rl2 ->\nforall r1 rl1,\nsfmatch g r1 rl1 ->\nelim_emp (r1 ++ r2) (rl1 ++ rl2) <> [] ->\nrules (g_emp g) (Lift_nt left) (map (@symbol_lift _ _) r1 ++ map (@symbol_lift _ _) r2) ->\nrules (g_emp g) (Lift_nt left) (map (@symbol_lift _ _) r1 ++ map (@symbol_lift _ _) (elim_emp r2 rl2)).\nProof.\nintros g left r2 rl2 HH.\nelim HH.\n- (* empty *)\n  intros.\n  rewrite app_nil_r in *. \n  auto.\n- (* terminal *)\n  intros.\n  simpl.\n  replace (r1 ++ inr t :: elim_emp xs xxs) with ((r1 ++ [inr t]) ++ elim_emp xs xxs).\n  + change (map (symbol_lift (terminal:=terminal)) r1 ++  inr t ::  map (symbol_lift (terminal:=terminal)) (elim_emp xs xxs)) with\n           (map (symbol_lift (terminal:=terminal)) r1 ++ [inr t] ++ map (symbol_lift (terminal:=terminal)) (elim_emp xs xxs)).\n    rewrite app_assoc.\n   \n    specialize (H0 (r1 ++ [inr t]) (rl1 ++ [[inr t]])).\n    rewrite map_app in H0. \n    apply H0.\n    * apply sfmatch_combine. \n      auto.\n      constructor.\n      constructor.\n    * repeat rewrite <- app_assoc. \n      simpl. \n      auto.\n    * rewrite <- app_assoc. \n      auto.\n  + repeat rewrite <- app_assoc. \n    simpl. \n    auto.\n- (* non-terminal *)\n  intros.\n  simpl.\n  destruct p.\n  + (* empty *)\n    apply H2 with rl1. \n    * auto.\n    * {\n      rewrite elim_emp_split with (g:=g) in H4. \n      - simpl in H4.\n        rewrite <- elim_emp_split with (g:=g) in H4; auto.\n      - auto.\n      - constructor.\n        + auto.\n        + auto.\n        + auto.\n      }\n    * simpl. \n      { \n      replace (map (symbol_lift (terminal:=terminal)) r1 ++ map (symbol_lift (terminal:=terminal)) xs) with\n             (map (symbol_lift (terminal:=terminal)) (r1 ++ xs)).\n      - econstructor 2.   \n        + replace (map (symbol_lift (terminal:=terminal)) r1 ++ map (symbol_lift (terminal:=terminal)) (inl nt :: xs)) with\n                  (map (symbol_lift (terminal:=terminal)) (r1 ++ inl nt :: xs)) in H5.\n          * exact H5.\n          * rewrite map_app.\n            reflexivity.\n        + reflexivity.\n        + apply H. \n          auto.\n        + red.\n          intros.\n          apply app_eq_nil in H6. \n          destruct H6. \n          subst.\n          elim H4. \n          simpl.\n          inversion_clear H3. \n          reflexivity.\n      - rewrite map_app.\n        reflexivity.\n      }\n  + (* not empty *)\n    simpl. \n    replace (map (symbol_lift (terminal:=terminal)) r1 ++  inl (Lift_nt nt) ::  map (symbol_lift (terminal:=terminal)) (elim_emp xs xxs)) with\n            (map (symbol_lift (terminal:=terminal)) (r1 ++ [inl nt]) ++ map (symbol_lift (terminal:=terminal)) (elim_emp xs xxs)).\n    * {\n      specialize (H2 (r1 ++ [inl nt]) (rl1 ++ [s :: p])). \n      apply H2.\n      - apply sfmatch_combine. \n        + auto.\n        + constructor. \n          * auto.\n          * auto. \n          * constructor.\n      - repeat rewrite <- app_assoc. \n        simpl. \n        auto.\n      - rewrite map_app.\n        simpl in H5.\n        change (map (symbol_lift (terminal:=terminal)) r1 ++  inl (Lift_nt nt) ::  map (symbol_lift (terminal:=terminal)) xs) with\n               (map (symbol_lift (terminal:=terminal)) r1 ++ [inl (Lift_nt nt)] ++ map (symbol_lift (terminal:=terminal)) xs) in H5.\n        simpl. \n        rewrite <- app_assoc.\n        exact H5.\n      }\n    * repeat rewrite map_app. \n      simpl. \n      change (map (symbol_lift (terminal:=terminal)) r1 ++  inl (Lift_nt nt) ::  map (symbol_lift (terminal:=terminal)) (elim_emp xs xxs)) with\n             (map (symbol_lift (terminal:=terminal)) r1 ++ [inl (Lift_nt nt)] ++ map (symbol_lift (terminal:=terminal)) (elim_emp xs xxs)).\n      rewrite <- app_assoc. \n      reflexivity.\nQed.\n\nLemma right_emp_prop:\nforall (g: cfg _ _),\nforall left: non_terminal,\nforall right: sf,\nforall right_list: list sf,\nrules g left right ->\nsfmatch g right right_list ->\nelim_emp right right_list <> [] ->\nrules (g_emp g) (Lift_nt left) (map (@symbol_lift _ _) (elim_emp right right_list)).\nProof.\nintros.\nassert (Hemp: rules (g_emp g) (Lift_nt left) (map (@symbol_lift _ _) right)).\n  { \n  apply rules_g_g_emp.\n  - apply elim_emp_not_nil with (split:= right_list).\n    exact H1.\n  - exact H.\n  }\nchange (map (symbol_lift (terminal:=terminal)) (elim_emp right right_list)) with (map (symbol_lift (terminal:=terminal)) [] ++ map (symbol_lift (terminal:=terminal)) (elim_emp right right_list)).\napply right_emp_prop_aux with [].\n- auto.\n- constructor.\n- assumption.\n- assumption.\nQed.\n\nLemma derives_g_g_emp:\nforall g: cfg _ _,\nforall n: non_terminal,\nforall s: sentence,\ns <> [] ->\nderives g [inl n] (map term_lift s) -> derives (g_emp g) [inl (Lift_nt n)] (map (@symbol_lift _ _) (map term_lift s)).\nProof.\nintros g n s H1 H2.\nrewrite derives_equiv_derives6 in H2.\ndestruct H2 as [i H3].\ngeneralize dependent n.\ngeneralize dependent s.\ngeneralize (le_refl i). \ngeneralize i at 1 3 as i'.\ninduction i.\n- intros i' Hi' s H1 n H2. \n  apply le_n_0_eq in Hi'. \n  subst.\n  apply derives6_0_eq in H2. \n  destruct s.\n  + simpl in H2.\n    inversion H2.\n  + simpl in H2.\n    inversion H2.\n- intros i' Hi' s H1 n H2.\n  inversion H2.\n  + apply derives_refl.\n  + assert (H10: s1 = [] /\\ s2 = []).\n      {  \n      destruct s1.\n      - split.\n        + reflexivity.    \n        + inversion H.   \n          reflexivity.\n      - inversion H.\n        destruct s1.\n        + inversion H8.\n        + inversion H8.\n      }\n    destruct H10 as [H11 H12].\n    subst.\n    rewrite app_nil_l in H.\n    rewrite <- H in H2.\n    simpl in H4.\n    rewrite app_nil_r in H4.\n    clear H2.\n    (* estrutura intermédia que particiona as derivações do rhs da regra *)\n    assert (H10: exists right2: list sf,\n                 sfmatch g right right2 /\\\n                 flatten right2 = map term_lift s).\n      {\n      apply le_S_n in Hi'.\n      generalize i0 Hi' s H4. \n      clear i0 Hi' H4 H0 s H1.\n      elim right.\n      - (* nil case *)\n        intros.\n        inversion H4.\n        + symmetry in H3.  \n          apply map_eq_nil in H3.\n          subst.\n          exists []. \n          split. \n          * constructor.\n          * simpl. \n            reflexivity.\n        + apply app_eq_nil in H0.\n          destruct H0 as [_ H0]. \n          inversion H0.\n      - (* cons case *)\n        intros.\n        destruct a.\n        + (* non_terminal *)\n          change (inl n0 :: l) with ([inl n0] ++ l) in H4.\n          generalize H4. \n          intros H4'.\n          apply derives6_split in H4'.\n          destruct H4' as [s1' [s2' [n1 [n2 [HH1 [HH2 [HH3 HH4]]]]]]].\n          symmetry in HH1. \n          apply map_expand in HH1. \n          destruct HH1 as [s0a [s0b [? [? ?]]]]. \n          subst.\n          assert (Hn2: n2 <= i) by omega.\n          specialize (H0 n2 Hn2 s0b HH4). \n          destruct H0 as [right2' [H1 H2]].\n          exists ((map term_lift s0a) :: right2').\n          simpl.\n          rewrite H2.\n          simpl. \n          split.\n          * assert (H20: s0a = [] \\/ s0a <> []).\n              {\n              apply nil_not_nil.\n              }\n            {\n            constructor.\n            - destruct H20 as [H20 | H20].\n              + subst. \n                simpl.\n                intros _.\n                assert (H5: exists n1: nat, derives6 g n1 [inl n0] (map term_lift [])).\n                  {\n                  exists n1.\n                  exact HH3.\n                  }\n                rewrite <- derives_equiv_derives6 in H5.\n                exact H5.\n              + intros. \n                apply map_eq_nil in H0.\n                rewrite H0 in H20. \n                destruct H20.\n                reflexivity.\n            - destruct H20 as [H20 | H20].\n              + intros.\n                rewrite H20 in H0.\n                simpl in H0.\n                destruct H0.\n                reflexivity.\n              + intros.\n                assert (H10: n1 <= i).  \n                  {\n                  omega. \n                  }\n              specialize (IHi n1 H10 s0a H20 n0 HH3). \n              exact IHi.\n            - exact H1.\n            }\n          * rewrite map_app. \n            reflexivity.\n        + (* terminal *)\n          generalize H4.\n          change (inr t :: l) with ((map term_lift [t]) ++ l).\n          intros H4'. \n          apply derives6_t_list_left in H4'.\n          destruct H4' as [s' Hs'].\n          rewrite Hs' in H4.\n          replace (inr t :: l) with (map term_lift [t] ++ l) in H4; [|reflexivity]. \n          apply derives6_tl_tl in H4.\n          generalize Hs'.\n          apply map_map_app in Hs'. \n          destruct Hs' as [s'' Hs''].\n          rewrite Hs'' in H4.\n          specialize (@H0 _ Hi' s'' H4). \n          destruct H0 as [right2' [HH1 HH2]].\n          intros.\n          exists ([inr t] :: right2').\n          simpl.\n          rewrite Hs'. \n          unfold terminal_lift. \n          split. \n          * apply sfmatch_term.\n            exact HH1.\n          * simpl. \n            rewrite Hs''.\n            rewrite <- HH2.\n            reflexivity.\n      }\n    clear IHi. \n    destruct H10 as [right2 [HH1 HH2]].\n    pose (right':= map (@symbol_lift _ _) (elim_emp right right2)).\n    assert (H11: rules (g_emp g) (Lift_nt n) right').\n      { \n      apply right_emp_prop. \n      - inversion H. \n        rewrite <- H3. \n        exact H0.\n      - exact HH1. \n      - apply flatten_elim_emp with (g:= g). \n        + exact HH1.\n        + rewrite HH2. \n          apply map_not_nil_inv. \n          exact H1. \n      }\n    apply derives_trans with (s2:= right').\n    * apply derives_start. \n      exact H11.\n    * (* indução sobre right..., usando [sfmatch] para lidar com não terminais *)\n      unfold right'.\n      generalize s right2 HH1 HH2. \n      clear s H1 right2 HH1 HH2 right' H11 H4 H0.\n      {\n      elim right.\n      - simpl. \n        intros.\n        inversion HH1.\n        subst. \n        simpl in HH2.\n        inversion HH2.\n        constructor.\n      - simpl. \n        intros.\n        inversion HH1.\n        + (* terminal *)\n          subst. \n          simpl in HH2.\n          destruct s. \n          * inversion HH2.\n          * simpl.\n            change (inr t :: elim_emp l xxs) with ([inr t]++elim_emp l xxs).\n            change (term_lift t0 :: map term_lift s) with ([inr t0]++ map term_lift s).\n            inversion HH2.\n            rewrite <- H2.\n            change ((inr t :: map (symbol_lift (terminal:=terminal)) (elim_emp l xxs))) with (([inr t] ++ map (symbol_lift (terminal:=terminal)) (elim_emp l xxs))).\n            change ((inr t :: map (symbol_lift (terminal:=terminal)) (flatten xxs))) with (([inr t] ++ map (symbol_lift (terminal:=terminal)) (flatten xxs))).\n            apply derives_context_free_add_left.\n            rewrite H3.\n            {\n            apply H0.\n            - exact H4.\n            - exact H3.\n            }\n        + (* non_terminal *)\n          destruct p.\n          * (* nullable *)\n            subst.\n            {\n            apply H0.\n            - exact H6. \n            - exact HH2.\n            }\n          * (* non-nullable *)\n            subst. \n            apply map_expand in HH2.\n            destruct HH2 as [sa [sb [Hs [Hs1 Hs2]]]]; subst s.\n            rewrite map_app.\n            change (inl nt :: elim_emp l xxs) with ([inl nt] ++ elim_emp l xxs).\n            repeat rewrite map_app.\n            apply derives_combine.\n            {\n            split. \n            - rewrite Hs1.\n              apply H4.\n              apply not_eq_sym.\n              apply nil_cons.\n            - apply H0 with (right2:= xxs) (s:= sb).\n              + exact H6.\n              + symmetry.\n                fold flatten in Hs2.\n                exact Hs2.\n            }\n      }\nQed.\n\nTheorem g_emp_correct: \nforall g: cfg non_terminal terminal,\ng_equiv_without_empty (g_emp g) g /\\\nhas_no_empty_rules (g_emp g) /\\\nstart_symbol_not_in_rhs (g_emp g).\nProof.\nintro g.\nsplit.\n- unfold g_equiv_without_empty.\n  intros s H.\n  unfold produces.\n  unfold generates.\n  split.\n  + simpl.\n    intros H2.\n    apply exists_rule in H2.\n    destruct H2 as [H2 | H2].\n    * {\n      inversion H2.\n      destruct s.\n      - inversion H0.\n      - simpl in H0.\n        inversion H0.        \n      }\n    * destruct H2 as [right [H2 H3]].\n      inversion H2.\n      {\n      destruct right.\n      - inversion H1.\n      - inversion H1.\n        destruct s0. \n        + inversion H4.\n          subst.\n          apply derives_g_emp_g.\n          rewrite symbol_lift_equiv_terminal_lift.\n          exact H3.\n        + inversion H4. \n      }\n  + simpl.\n    intros H2. \n    apply derives_trans with (s2:= [inl (Lift_nt (start_symbol g))]).\n    * apply derives_start.\n      apply Lift_start_emp.\n    * rewrite <- symbol_lift_equiv_terminal_lift.\n      {\n      apply derives_g_g_emp.\n      - exact H.\n      - exact H2.\n      }\n- split.\n  + unfold has_no_empty_rules.\n    intros left right H.\n    destruct right.\n    * {\n      inversion H.\n      - apply map_eq_nil in H0.\n        contradiction.\n      - apply map_eq_nil in H0.\n        contradiction.\n      }\n    * apply not_eq_sym.\n      apply nil_cons.\n  + apply start_symbol_not_in_rhs_g_emp.\nQed.\n\nEnd EmptyRules_1_Lemmas.\n\n(* --------------------------------------------------------------------- *)\n(* SIMPLIFICATION - EMPTY RULES - DEFINITIONS TO INCLUDE EMPTY STRING    *)\n(* --------------------------------------------------------------------- *)\n\nSection EmptyRules_2_Definitions.\n\nVariables non_terminal terminal: Type.\n\nNotation symbol:= (non_terminal + terminal)%type.\nNotation symbol':= (non_terminal' + terminal)%type.\nNotation nlist:= (list non_terminal).\nNotation nlist':= (list (non_terminal' non_terminal)).\nNotation tlist:= (list terminal).\nNotation sentence := (list terminal).\nNotation sf := (list (non_terminal + terminal)).\nNotation sf' := (list ((non_terminal' non_terminal) + terminal)).\nNotation term_lift:= ((terminal_lift non_terminal) terminal).\n\nInductive g_emp'_rules (g: cfg _ _): non_terminal' non_terminal -> sf' -> Prop :=\n| Lift_all:\n       forall left: non_terminal' _,\n       forall right: sf',\n       rules (g_emp g) left right ->\n       g_emp'_rules g left right\n| Lift_empty:\n       empty g (inl (start_symbol g)) -> g_emp'_rules g (start_symbol (g_emp g)) [].\n\nLemma in_inl_map_exists:\nforall s': non_terminal' _,\nforall l: sf,\nIn (inl s') (map (@symbol_lift _ _) l) ->\nexists s: non_terminal,\ns' = Lift_nt s /\\\nIn (inl s) l.\nProof.\nintros s' l H.\napply in_split in H.\ndestruct H as [l1 [l2 H]].\nsymmetry in H.\napply map_expand in H.\ndestruct H as [s1' [s2' [H1 [H2 H3]]]].\nchange (inl s' :: l2) with ([inl s'] ++ l2) in H3.\nsymmetry in H3.\napply map_expand in H3.\ndestruct H3 as [s1'0 [s2'0 [H4 [H5 H6]]]].\ndestruct s1'0.\n- inversion H5.\n- inversion H5.\n  destruct s.\n  + simpl in H0. \n    inversion H0. \n    exists n.\n    split. \n    * reflexivity.\n    * rewrite H1. \n      apply in_or_app.\n      right.\n      rewrite H4.\n      apply in_or_app.\n      left.\n      simpl. \n      left.\n      reflexivity.\n  + simpl in H0.\n    inversion H0.\nQed.\n\nLemma in_inr_map_exists:\nforall s': terminal,\nforall l: sf,\nIn (inr s') (map (@symbol_lift _ _) l) ->\nexists s: terminal,\ns' = s /\\\nIn (inr s) l.\nProof.\nintros s' l H.\napply in_split in H.\ndestruct H as [l1 [l2 H]].\nsymmetry in H.\napply map_expand in H.\ndestruct H as [s1' [s2' [H1 [H2 H3]]]].\nchange (inr s' :: l2) with ([inr s'] ++ l2) in H3.\nsymmetry in H3.\napply map_expand in H3.\ndestruct H3 as [s1'0 [s2'0 [H4 [H5 H6]]]].\ndestruct s1'0.\n- inversion H5.\n- inversion H5.\n  destruct s.\n  + simpl in H0. \n    inversion H0.\n  + exists t.\n    split. \n    * simpl in H0. \n      inversion H0. \n      reflexivity.\n    * simpl in H5.\n      inversion H5.\n      subst.\n      apply in_or_app.\n      right.\n      simpl. \n      left.\n      reflexivity.\nQed.\n\nLemma in_lift_map:\nforall n: non_terminal,\nforall ntl: nlist,\nIn n ntl ->\nIn (Lift_nt n) (map (@Lift_nt _) ntl).\nProof.\nintros n ntl H.\ninduction ntl.\n- simpl in H.\n  contradiction.\n- simpl. \n  simpl in H.\n  destruct H as [H | H].\n  + left.\n    subst.\n    reflexivity.\n  + right.\n    apply IHntl.\n    exact H.\nQed.\n\nLemma g_emp_length_min:\nforall g: cfg _ _,\nforall left : non_terminal' _,\nforall right : sf',\ng_emp_rules g left right ->\nlength right >= 1.\nProof.\nintros g left right H.\ninversion H.\n- subst. \n  apply not_nil in H0.\n  rewrite map_length. \n  omega.\n- subst.\n  destruct s1, s2.\n  + destruct H3.\n    reflexivity.\n  + subst. \n    simpl. \n    omega.\n  + subst. \n    simpl. \n    omega.\n  + subst. \n    simpl.\n    omega.\n- simpl. \n  omega.\nQed.\n\nLemma g_emp'_finite:\nforall g: cfg _ _,\nexists n: nat,\nexists ntl: nlist',\nexists tl: tlist,\nIn (New_ss _) ntl /\\\nforall left: non_terminal' _,\nforall right: sf',\ng_emp'_rules g left right ->\n(length right <= n) /\\\n(In left ntl) /\\\n(forall s: non_terminal' _, In (inl s) right -> In s ntl) /\\\n(forall s: terminal, In (inr s) right -> In s tl).\nProof.\nintros g.\ndestruct (rules_finite (g_emp g)) as [n [ntl [tl H1]]].\ndestruct H1 as [H H1].\nexists (S n), (New_ss _ :: ntl), tl.\nsplit.\n- simpl; left; reflexivity.\n- intros left right H2.\n  inversion H2.\n  + subst. \n    specialize (H1 left right H0).\n    destruct H1 as [H3 [H4 H5]].\n    split. \n    * omega.\n    * {\n      split.\n      - apply in_cons.\n        exact H4.\n      - split.\n        + destruct H5 as [H5 _].\n          intros s' H6.\n          apply in_cons.\n          apply H5.\n          exact H6.\n        + destruct H5 as [_ H5].\n          intros s H6.\n          apply H5.\n          exact H6.\n      } \n  + subst.\n    split.\n    * simpl. \n      omega.\n    * {\n      split. \n      - simpl. \n        left. \n        reflexivity.\n      - split.\n        + intros s H3.\n          simpl in H3.\n          contradiction.\n        + intros s H3.\n          simpl in H3.\n          contradiction.\n      }\nQed.\n\nDefinition g_emp' (g: cfg non_terminal terminal): cfg (non_terminal' _) terminal := {|\nstart_symbol:= New_ss _;\nrules:= g_emp'_rules g;\nrules_finite:= g_emp'_finite g\n|}.\n\nDefinition New_ss_not_in_sf (s: sf'): Prop:=\n~ In (inl (New_ss _)) s.\n\nDefinition New_ss_not_in_sflist (l': list sf'): Prop:=\nforall s': sf',\nIn s' l' ->\nNew_ss_not_in_sf s'.\n\nEnd EmptyRules_2_Definitions.\n\n(* --------------------------------------------------------------------- *)\n(* SIMPLIFICATION - EMPTY RULES - LEMMAS TO INCLUDE EMPTY STRING         *)\n(* --------------------------------------------------------------------- *)\n\nSection EmptyRules_2_Lemmas.\n\nVariables non_terminal terminal: Type.\n\nNotation symbol:= (non_terminal + terminal)%type.\nNotation symbol':= ((non_terminal' _) + terminal)%type.\nNotation nlist:= (list non_terminal).\nNotation nlist':= (list (non_terminal' non_terminal)).\nNotation tlist:= (list terminal).\nNotation sentence := (list terminal).\nNotation sf := (list (non_terminal + terminal)).\nNotation sf' := (list ((non_terminal' non_terminal) + terminal)).\nNotation term_lift:= ((terminal_lift non_terminal) terminal).\nNotation term_lift':= ((terminal_lift (non_terminal' non_terminal)) terminal).\n\nLemma start_symbol_not_in_rhs_g_emp': \nforall g: cfg non_terminal terminal,\nstart_symbol_not_in_rhs (g_emp' g).\nProof.\nintros g.\nunfold start_symbol_not_in_rhs.\nintros left right H1 H2.\nsimpl in H2. \ninversion H1. \n- subst.\n  assert (H3: start_symbol_not_in_rhs (g_emp g)).\n    {\n    apply start_symbol_not_in_rhs_g_emp.\n    }\n  specialize (H3 left right H).\n  apply H3.\n  simpl.\n  exact H2.\n- subst.\n  simpl in H2.\n  contradiction.\nQed.\n\nLemma New_ss_not_in_right_g_emp'_v1:\nforall g: cfg _ _,\nforall left: non_terminal' _,\nforall s1 s2: sf',\n~ rules (g_emp' g) left (s1 ++ [inl (start_symbol (g_emp' g))] ++ s2).\nProof.\nintros g left s1 s2 H.\ninversion H.\nclear H.\n- simpl in H0.  \n  assert (H3: start_symbol_not_in_rhs (g_emp g)).\n    {\n    apply start_symbol_not_in_rhs_g_emp.\n    }\n  specialize (H3 left (s1 ++ inl (New_ss non_terminal) :: s2) H0).\n  apply H3.\n  simpl. \n  apply in_or_app.\n  right. \n  simpl. \n  left.\n  reflexivity.\n- destruct s1.\n  + inversion H0.\n  + inversion H0.\nQed.\n\nLemma New_ss_not_in_right_g_emp'_v2:\nforall g: cfg _ _,\nforall left: non_terminal' _,\nforall right: sf',\nrules (g_emp' g) left right ->\nNew_ss_not_in_sf right.\nProof.\nintros g left right H1 H2.\napply in_split in H2.\ndestruct H2 as [l1 [l2 H3]].\nrewrite H3 in H1.\nchange ((l1 ++ inl (New_ss _) :: l2)) with ((l1 ++ [inl (New_ss _)] ++ l2)) in H1.\napply New_ss_not_in_right_g_emp'_v1 in H1.\ncontradiction.\nQed.\n\nLemma hd_lift_equiv_lift_hd:\nforall l: list sf,\nhd [] (sf_list_lift l) = sf_lift (hd [] l).\nProof.\ndestruct l.\n- simpl. \n  reflexivity.\n- simpl. \n  reflexivity.\nQed.\n\nLemma last_lift_equiv_lift_last:\nforall l: list sf,\nlast (sf_list_lift l) [] = sf_lift (last l []).\nProof.\ninduction l.\n- simpl. \n  reflexivity.\n- simpl sf_list_lift.\n  assert (H: l = [] \\/ l <> []).\n    {\n    apply nil_not_nil.\n    }\n  destruct H as [H | H].\n  + subst.\n    simpl. \n    reflexivity.\n  + assert (H2: sf_list_lift l <> []).\n      {\n      destruct l.\n      - destruct H.\n        reflexivity.\n      - simpl. \n        apply not_eq_sym.\n        apply nil_cons.\n      }\n    repeat rewrite last_cons.\n    * exact IHl.\n    * exact H.\n    * exact H2.\nQed.\n\nLemma map_lift_equiv_lift_map:\nforall s: sentence,\nsf_lift (map term_lift s) =\nmap term_lift' s.\nProof.\nintros s.\ninduction s.\n- simpl. \n  reflexivity.\n- simpl map.\n  simpl sf_lift. \n  change (term_lift' a) with (@inr (non_terminal' non_terminal) terminal a).\n  apply app_eq.\n  exact IHs.\nQed.\n\nLemma sf_lift_app_distrib:\nforall s1 s2: sf,\nsf_lift (s1 ++ s2) = sf_lift s1 ++ sf_lift s2.\nProof.\ninduction s1.\n- intros s2.\n  simpl. \n  reflexivity.\n- intros s2.\n  simpl. \n  apply app_eq.\n  apply IHs1.\nQed.\n\nLemma sf_lift_eq_nil:\nforall l: sf,\nsf_lift l = [] -> l = [].\nProof.\ndestruct l.\n- simpl. \n  auto.\n- simpl. \n  intros H.\n  change (symbol_lift s :: sf_lift l) with ([symbol_lift s] ++ sf_lift l) in H.\n  apply app_eq_nil in H.\n  destruct H as [H _].\n  inversion H.\nQed.\n\nLemma sf_list_lift_eq_nil:\nforall l: list sf,\nsf_list_lift l = [] -> l = [].\nProof.\ndestruct l.\n- simpl. \n  auto.\n- simpl. \n  intros H.\n  change (sf_lift l :: sf_list_lift l0) with ([sf_lift l] ++ sf_list_lift l0) in H.\n  apply app_eq_nil in H.\n  destruct H as [H _].\n  inversion H.\nQed.\n\nLemma symbol_lift_eq:\nforall a b: symbol,\nsymbol_lift a = symbol_lift b ->\na = b.\nProof.\nintros a b H.\ndestruct a, b.\n- simpl in H.\n  inversion H.\n  reflexivity. \n- simpl in H. \n  inversion H.\n- simpl in H. \n  inversion H.\n- simpl in H.\n  inversion H.\n  reflexivity. \nQed.\n\nLemma sf_lift_eq:\nforall l1 l2: sf,\nsf_lift l1 = sf_lift l2 ->\nl1 = l2.\nProof.\ninduction l1.\n- intros l2 H. \n  simpl in H. \n  symmetry in H. \n  apply sf_lift_eq_nil in H. \n  symmetry. \n  assumption. \n- intros l2 H.\n  simpl in H.\n  destruct l2.\n  + inversion H.\n  + simpl in H.\n    inversion H.\n    specialize (IHl1 l2 H2).\n    rewrite IHl1.\n    apply symbol_lift_eq with (b:= s) in H1.\n    rewrite H1.\n    reflexivity.\nQed.\n\nLemma sf_list_lift_eq:\nforall l1 l2: list sf,\nsf_list_lift l1 = sf_list_lift l2 ->\nl1 = l2.\nProof.\ninduction l1, l2.\n- auto. \n- simpl.\n  intros H.\n  symmetry in H.\n  change (sf_lift l :: sf_list_lift l2) with ([sf_lift l] ++ sf_list_lift l2) in H.\n  apply app_eq_nil in H. \n  destruct H as [H1 _]. \n  inversion H1.\n- simpl.\n  intros H.\n  change (sf_lift a :: sf_list_lift l1) with ([sf_lift a] ++ sf_list_lift l1) in H.\n  apply app_eq_nil in H. \n  destruct H as [H1 _]. \n  inversion H1.\n- intros H.\n  simpl in H.\n  inversion H. \n  specialize (IHl1 l2 H2).\n  rewrite IHl1.\n  apply sf_lift_eq in H1.\n  rewrite H1.\n  reflexivity.\nQed.\n\nLemma derives_g_emp'_or:\nforall g: cfg _ _,\nforall s: sentence,\nderives (g_emp' g) [inl (start_symbol (g_emp' g))] (map term_lift' s) ->\ns = [] \\/\nderives (g_emp' g) [inl (start_symbol (g_emp g))] (map term_lift' s).\nProof.\nintros g s H.\ndestruct s.\n- left.\n  reflexivity.\n- right.\n  apply exists_rule in H.\n  destruct H.\n  + inversion H.\n    inversion H0.\n  + destruct H as [right [H1 H2]].\n    inversion H1.\n    * subst.\n      { \n      apply derives_trans with (s2:= right).\n      - apply derives_start.\n        exact H1.\n      - exact H2. \n      }\n    * subst.\n      {\n      apply not_derives in H2.\n      - contradiction.\n      - simpl. \n        apply not_eq_sym. \n        apply nil_cons. \n      }\nQed.\n\nLemma derives_g_emp'_empty:\nforall g: cfg non_terminal terminal,\nderives (g_emp' g) [inl (start_symbol (g_emp' g))] [] ->\nrules (g_emp' g) (start_symbol (g_emp' g)) [].\nProof.\nintros g H.\nchange [] with (map term_lift' []) in H.\napply exists_rule in H.\ndestruct H as [H | H].\n- exact H.\n- destruct H as [right [H1 H2]].\n  inversion H2.\n  + simpl in H0. \n    subst.\n    exact H1.\n  + apply app_eq_nil in H.\n    destruct H as [H H5].\n    apply app_eq_nil in H5.\n    destruct H5 as [H5 H6].\n    subst.\n    simpl.\n    inversion H4.\n    * subst.\n      apply g_emp_has_no_empty_rules in H.\n      destruct H.\n      reflexivity.\n    * apply Lift_empty. \n      exact H.\nQed.\n\nLemma hd_lift_hd:\nforall n: non_terminal,\nforall l': list sf',\nforall l: list sf,\nhd [] l' = [inl (Lift_nt n)] ->\nl' = sf_list_lift l ->\nhd [] l = [inl n].\nProof.\nintros n l' l H1 H2.\nrewrite H2 in H1.\nrewrite hd_lift_equiv_lift_hd in H1.\nchange [inl (Lift_nt n)] with (sf_lift ([inl terminal n])) in H1.\napply sf_lift_eq in H1.\nexact H1.\nQed.  \n\nLemma last_lift_last:\nforall l': list sf',\nforall l: list sf,\nforall s: sentence,\nlast l' [] = map term_lift' s ->\nl' = sf_list_lift l ->\nlast l [] = map term_lift s.\nProof.\nintros l' l s H1 H2.\nrewrite H2 in H1.\nclear H2 l'.\nrewrite last_lift_equiv_lift_last in H1.\nrewrite <- map_lift_equiv_lift_map in H1.\napply sf_lift_eq in H1.\nexact H1.\nQed.\n\nLemma New_ss_not_in_sf_cat:\nforall l1 l2: sf',\nNew_ss_not_in_sf l1 ->\nNew_ss_not_in_sf l2 ->\nNew_ss_not_in_sf (l1 ++ l2).\nProof.\nintros l1.\ndestruct l1.\n- intros l2 H1 H2.\n  simpl. \n  exact H2.\n- intros l2 H1 H2.\n  unfold New_ss_not_in_sf.\n  intros H3. \n  apply in_app_or in H3.\n  destruct H3 as [H3 | H3].\n  + specialize (H1 H3).\n    contradiction.\n  + specialize (H2 H3).\n    contradiction.\nQed.\n\nLemma New_ss_not_in_sf_split:\nforall l1 l2: sf',\nNew_ss_not_in_sf (l1 ++ l2) ->\nNew_ss_not_in_sf l1 /\\\nNew_ss_not_in_sf l2.\nProof.\nintros l1.\ndestruct l1.\n- intros l2 H.\n  split.\n  + unfold New_ss_not_in_sf.\n    simpl.\n    auto.\n  + exact H.\n- intros l2 H1.\n  split.\n  + intros H2. \n    unfold New_ss_not_in_sf in H1.\n    simpl in H1.\n    apply H1.\n    change (s :: l1) with ([s] ++ l1) in H2.\n    apply in_app_or in H2.\n    destruct H2 as [H2 | H2].\n    * left.\n      simpl in H2. \n      {\n      destruct H2 as [H2 | H2].\n      - exact H2.\n      - contradiction.\n      }\n    * right.\n      apply in_or_app.\n      left.\n      exact H2.\n  + unfold New_ss_not_in_sf in H1. \n    unfold New_ss_not_in_sf.\n    intros H2.\n    apply H1.\n    apply in_or_app.\n    right.\n    exact H2.\nQed.\n\nLemma New_ss_not_in_sflist_cat:\nforall l1 l2: list sf',\nNew_ss_not_in_sflist l1 ->\nNew_ss_not_in_sflist l2 ->\nNew_ss_not_in_sflist (l1 ++ l2).\nProof.\nintros l1.\ndestruct l1.\n- intros l2 H1 H2.\n  simpl. \n  exact H2.\n- intros l2 H1 H2.\n  unfold New_ss_not_in_sflist.\n  intros s' H3. \n  apply in_app_or in H3.\n  destruct H3 as [H3 | H3].\n  + specialize (H1 s' H3).\n    exact H1.\n  + specialize (H2 s' H3).\n    exact H2.\nQed.\n\nLemma New_ss_not_in_sflist_split:\nforall l1 l2: list sf',\nNew_ss_not_in_sflist (l1 ++ l2) ->\nNew_ss_not_in_sflist l1 /\\\nNew_ss_not_in_sflist l2.\nProof.\nintros l1.\ndestruct l1.\n- intros l2 H.\n  split.\n  + unfold New_ss_not_in_sflist.\n    intros s' H1.\n    simpl in H1.\n    contradiction.\n  + exact H.\n- intros l2 H1.\n  split.\n  + intros s' H2. \n    unfold New_ss_not_in_sflist in H1.\n    simpl in H1.\n    apply H1.\n    change (l :: l1) with ([l] ++ l1) in H2.\n    apply in_app_or in H2.\n    destruct H2 as [H2 | H2].\n    * left.\n      simpl in H2. \n      {\n      destruct H2 as [H2 | H2].\n      - exact H2.\n      - contradiction.\n      }\n    * right.\n      apply in_or_app.\n      left.\n      exact H2.\n  + unfold New_ss_not_in_sflist in H1. \n    unfold New_ss_not_in_sflist.\n    intros s' H2.\n    apply H1.\n    apply in_or_app.\n    right.\n    exact H2.\nQed.\n\nLemma New_ss_not_in_map:\nforall s: sf,\nNew_ss_not_in_sf (sf_lift s).\nProof.\nintros s.\ninduction s.\n- simpl.\n  unfold New_ss_not_in_sf.\n  simpl.\n  auto.\n- simpl.\n  unfold New_ss_not_in_sf.\n  intros H.\n  change (symbol_lift a :: sf_lift s) with ([symbol_lift a] ++ sf_lift s) in H.\n  apply in_app_or in H.\n  destruct H as [H | H].\n  + simpl in H.\n    destruct H as [H | H].\n    * {\n      destruct a.\n      - simpl in H.\n        discriminate H.\n      - simpl in H.\n        inversion H.\n      }\n    * contradiction.\n  + apply IHs.\n    exact H. \nQed.\n\nLemma sf_lift_cat:\nforall l: sf,\nforall l1 l2: sf',\nsf_lift l = l1 ++ l2 ->\nexists l1' l2',\nl = l1' ++ l2' /\\\nl1 = sf_lift l1' /\\\nl2 = sf_lift l2'.\nProof.\ninduction l, l1.\n- intros l2 H.\n  exists [], [].\n  auto. \n- intros l2 H.\n  simpl in H.\n  inversion H.\n- intros l2 H. \n  simpl in H.\n  destruct l2. \n  + inversion H.\n  + inversion H.\n    specialize (IHl [] l2 H2).\n    destruct IHl as [l1' [l2' [H3 [H4 H5]]]].\n    exists [], (a :: l).\n    split.\n    * reflexivity.\n    * {\n      split. \n      - reflexivity.\n      - simpl.\n        reflexivity.\n      }\n- intros l2 H.\n  simpl in H.\n  inversion H.\n  specialize (IHl l1 l2 H2).\n  destruct IHl as [l1' [l2' [H3 [H4 H5]]]].\n  exists (a :: l1'), l2'.\n  split.\n  + rewrite H3.\n    reflexivity.\n  + split.\n    * simpl.\n      rewrite H4.\n      reflexivity.\n    * exact H5.\nQed.\n\nLemma sf_lift_eq_nt:\nforall l: sf,\nforall a: non_terminal' _,\nsf_lift l = [inl a] ->\nexists b: non_terminal,\nl = [inl b].\nProof.\nintros l a H.\ndestruct l.\n- simpl in H.\n  inversion H.\n- simpl in H.\n  inversion H.\n  apply sf_lift_eq_nil in H2.\n  rewrite H2.\n  destruct s. \n  + exists n.\n    reflexivity.\n  + inversion H1.\nQed.\n\nLemma New_ss_not_in_rhs:\nforall g: cfg non_terminal terminal,\nforall s1 s2: sf',\ns1 ++ s2 <> [] ->\n~ derives (g_emp' g) [inl (start_symbol (g_emp' g))] (s1 ++ inl (start_symbol (g_emp' g)) :: s2).\nProof.\nintros g.\nassert (H: start_symbol_not_in_rhs (g_emp' g)).\n  {\n  apply start_symbol_not_in_rhs_g_emp'.\n  }\nintros s1 s2 H1 H2.\napply exists_rule' in H2.\ndestruct H2 as [H2 | H2].\n- destruct H2 as [_ [H3 H4]].\n  subst.\n  destruct H1.\n  reflexivity.\n- destruct H2 as [left [right [H3 H4]]].\n  specialize (H left right H3).\n  simpl in H.\n  contradiction.\nQed.\n\nLemma g_emp_equiv_g_emp'_aux_1:\nforall g: cfg _ _,\nforall s: sf',\ns <> [] ->\nderives (g_emp' g) [inl (start_symbol (g_emp' g))] s ->\nderives (g_emp g) [inl (start_symbol (g_emp g))] s.\nProof.\nsimpl.\nintros g s H1 H2.\nremember [inl (New_ss non_terminal)] as w.\ninduction H2.\n- apply derives_refl.\n- apply derives_trans with (s2:= (s2 ++ inl left :: s3)).\n  + apply IHderives.\n    * apply not_eq_sym.\n      apply app_cons_not_nil.\n    * exact Heqw.\n  + inversion H. \n    * apply derives_rule.\n      exact H0.\n    * subst.\n      simpl in H2.\n      {\n      apply New_ss_not_in_rhs in H2. \n      - contradiction.\n      - exact H1.\n      }\nQed.\n\nLemma g_emp_equiv_g_emp'_aux_2:\nforall g: cfg _ _,\nforall s: sf',\nderives (g_emp g) [inl (start_symbol (g_emp g))] s ->\nderives (g_emp' g) [inl (start_symbol (g_emp' g))] s.\nProof.\nsimpl.\nintros g s H.\nremember [inl (New_ss non_terminal)] as w1. \ninduction H.\n- apply derives_refl.\n- apply derives_trans with (s2:= (s2 ++ inl left :: s3)).\n  + apply IHderives.\n    exact Heqw1.\n  + apply derives_rule.\n    apply Lift_all.\n    exact H0.\nQed.\n\nLemma g_emp_equiv_g_emp':\nforall g: cfg _ _,\nforall s: sentence,\n(s <> [] -> \n derives (g_emp' g) [inl (start_symbol (g_emp' g))] (map term_lift' s) ->\n derives (g_emp  g) [inl (start_symbol (g_emp  g))] (map term_lift' s)) \n/\\\n(derives (g_emp  g) [inl (start_symbol (g_emp  g))] (map term_lift' s) ->\n derives (g_emp' g) [inl (start_symbol (g_emp' g))] (map term_lift' s)).\nProof.\nintros g s.\nsplit.\n- intros H1 H2. \n  apply derives_g_emp'_or in H2.\n  destruct H2 as [H2 | H2].\n  + subst.\n    destruct H1.\n    reflexivity.\n  + apply g_emp_equiv_g_emp'_aux_1.\n    * apply map_not_nil_inv. \n      exact H1.\n    * exact H2.\n- intros H.\n  apply g_emp_equiv_g_emp'_aux_2.\n  exact H.\nQed.\n\nLemma lift_terminal_lift:\nforall s: sentence,\nsf_lift (map term_lift s) = map term_lift' s.\nProof.\nintros s.\ninduction s.\n-simpl. \n reflexivity.\n- simpl.\n  apply app_eq.\n  exact IHs.\nQed.\n\nLemma g_emp'_has_one_empty_rule:\nforall g: cfg non_terminal terminal,\ngenerates_empty g -> has_one_empty_rule (g_emp' g).\nProof.\nunfold generates_empty.\nintros g H1.\nunfold has_one_empty_rule.\nintros left right H2.\ninversion H2.\n- subst.\n  right.\n  apply g_emp_has_no_empty_rules in H.\n  exact H.\n- left.\n  subst.\n  simpl.\n  auto.\nQed.\n\nLemma g_emp'_has_no_empty_rules:\nforall g: cfg non_terminal terminal,\n~ generates_empty g -> has_no_empty_rules (g_emp' g).\nProof.\nunfold generates_empty.\nintros g H.\nintros left right H1.\ninversion H1.\n- inversion H0.\n  + apply map_not_nil_inv.\n    exact H4.\n  + apply map_not_nil_inv.\n    exact H7.\n  + apply not_eq_sym.\n    apply nil_cons.\n- subst.\n  contradiction.\nQed.\n\nTheorem g_emp'_correct: \nforall g: cfg non_terminal terminal,\ng_equiv (g_emp' g) g /\\\n(produces_empty g -> has_one_empty_rule (g_emp' g)) /\\ \n(~ produces_empty g -> has_no_empty_rules (g_emp' g)) /\\\nstart_symbol_not_in_rhs (g_emp' g).\nProof.\nintros g.\nsplit.\n- unfold g_equiv.\n  intros s.\n  unfold produces.\n  unfold generates.\n  split.\n  + intros H.\n    assert (H0: s = [] \\/ s <> []). \n      {\n      apply nil_not_nil.\n      }\n    destruct H0 as [H0 | H0].\n    * subst.\n      inversion H.\n      apply app_eq_nil in H0.\n      destruct H0 as [_ H0].\n      apply app_eq_nil in H0.\n      destruct H0 as [H0 _].\n      subst.\n      {\n      inversion H3.\n      - apply g_emp_has_no_empty_rules in H0.\n        destruct H0.\n        reflexivity.\n      - exact H0.\n      }\n    * {\n      apply g_emp_equiv_g_emp' in H.\n      - apply derives_g_emp_g.\n        apply exists_rule in H.\n        destruct H as [H | H].\n        + simpl in H.\n          inversion H. \n          destruct s. \n          * inversion H1.\n          * inversion H1. \n        + destruct H as [right [H1 H2]].  \n          inversion H1. \n          destruct right.\n          * inversion H3.\n          * inversion H3.\n            subst.\n            rewrite symbol_lift_equiv_terminal_lift.\n            exact H2.\n      - exact H0.\n      }\n  + intros H.\n    assert (H0: s = [] \\/ s <> []). \n      {\n      apply nil_not_nil.\n      }\n    destruct H0 as [H0 | H0].\n    * subst.\n      simpl.\n      apply derives_start.\n      apply Lift_empty.\n      exact H.\n    * {\n      apply derives_g_g_emp in H.\n      - apply g_emp_equiv_g_emp'.\n        simpl.\n        apply derives_trans with (s2:= [inl (Lift_nt (start_symbol g))]).\n        + apply derives_start.\n          apply Lift_start_emp.\n        + rewrite symbol_lift_equiv_terminal_lift in H.\n          exact H.\n      - exact H0.\n      }\n- split.\n  + (* g does generate empty *)\n    apply g_emp'_has_one_empty_rule.\n  + split. \n    * (* g does not generate empty *)\n      apply g_emp'_has_no_empty_rules.\n    * apply start_symbol_not_in_rhs_g_emp'.\nQed.\n\nVariables non_terminal' non_terminal'': Type.\n\nLemma remove_empty:\nforall g1: cfg non_terminal' terminal,\nforall g2: cfg non_terminal'' terminal,\ng_equiv g1 g2 ->\ng_equiv_without_empty g1 g2.\nProof.\nintros g1 g2 H1.\nunfold g_equiv in H1.\nunfold g_equiv_without_empty.\nintros s H2.\napply H1.\nQed.\n\nEnd EmptyRules_2_Lemmas.\n\nSection EmptyRules_3_Lemmas.\n\nVariables non_terminal terminal: Type.\n\nLemma no_empty_rules_no_empty:\nforall g: cfg non_terminal terminal,\nhas_no_empty_rules g ->\n~ derives g [inl (start_symbol g)] [].\nProof.\nintros g H1 H2.\nunfold has_no_empty_rules in H1.\ninversion H2.\napply app_eq_nil in H.\ndestruct H as [_ H].\napply app_eq_nil in H.\ndestruct H as [H _].\nsubst.\nspecialize (H1 left [] H4).\ndestruct H1.\nreflexivity.\nQed.\n\nEnd EmptyRules_3_Lemmas.\n\nSection EmptyRules_4_Lemmas.\n\nVariables non_terminal non_terminal' non_terminal'' terminal: Type.\n\nNotation sf:= (list (non_terminal + terminal))%type.\n\nLemma with_without_empty:\nforall g1: cfg non_terminal' terminal,\nforall g2: cfg non_terminal'' terminal,\nhas_no_empty_rules g1 ->\nhas_no_empty_rules g2 ->\n(g_equiv g1 g2 <-> g_equiv_without_empty g1 g2).\nProof.\nintros g1 g2 H1 H2.\nsplit.\n- intros H3.\n  apply remove_empty.\n  exact H3.\n- intros H3.\n  unfold g_equiv_without_empty in H3.\n  unfold g_equiv.\n  intros s.\n  unfold produces.\n  unfold generates.\n  destruct s.\n  + split.\n    * intros H4.\n      apply no_empty_rules_no_empty in H1.\n      specialize (H1 H4).\n      contradiction.\n    * intros H4.\n      apply no_empty_rules_no_empty in H2.\n      specialize (H2 H4).\n      contradiction.\n  + apply H3.\n    apply not_eq_sym.\n    apply nil_cons. \nQed.\n\nEnd EmptyRules_4_Lemmas.\n", "meta": {"author": "mvmramos", "repo": "chomsky", "sha": "5601fdd3d6845c8bb1a750469747b6e0bc73b679", "save_path": "github-repos/coq/mvmramos-chomsky", "path": "github-repos/coq/mvmramos-chomsky/chomsky-5601fdd3d6845c8bb1a750469747b6e0bc73b679/emptyrules.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.2945399082458839}}
{"text": "(* ** Imports and settings *)\nFrom mathcomp Require Import word_ssrZ.\nRequire Import expr ZArith sem_op_typed compiler_util.\nImport all_ssreflect all_algebra.\nImport Utf8.\nImport oseq.\nRequire Import flag_combination.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLocal Open Scope seq_scope.\nLocal Open Scope vmap_scope.\nLocal Open Scope Z_scope.\n\n\nSection WITH_PARAMS.\n\nContext {fcp : FlagCombinationParams}.\n\nDefinition e2bool (e:pexpr) : exec bool := \n  match e with\n  | Pbool b => ok b\n  | _       => type_error\n  end.\n\nDefinition e2int (e:pexpr) : exec Z := \n  match e with\n  | Pconst z => ok z\n  | _        => type_error\n  end.\n\nDefinition e2word (sz:wsize) (e:pexpr) : exec (word sz) := \n  match is_wconst sz e with\n  | Some w => ok w\n  | None   => type_error\n  end.\n \nDefinition of_expr (t:stype) : pexpr -> exec (sem_t t) :=\n  match t return pexpr -> exec (sem_t t) with\n  | sbool   => e2bool\n  | sint    => e2int\n  | sarr n  => fun _ => type_error \n  | sword sz => e2word sz\n  end.\n\nDefinition to_expr (t:stype) : sem_t t -> exec pexpr := \n  match t return sem_t t -> exec pexpr with\n  | sbool => fun b => ok (Pbool b)\n  | sint  => fun z => ok (Pconst z)\n  | sarr _ => fun _ => type_error\n  | sword sz => fun w => ok (wconst w)\n  end.\n\nDefinition ssem_sop1 (o: sop1) (e: pexpr) : pexpr := \n  let r := \n    Let x := of_expr _ e in\n    to_expr (sem_sop1_typed o x) in\n  match r with \n  | Ok e => e\n  | _ => Papp1 o e\n  end.\n\nDefinition ssem_sop2 (o: sop2) (e1 e2: pexpr) : pexpr := \n  let r := \n    Let x1 := of_expr _ e1 in\n    Let x2 := of_expr _ e2 in\n    Let v  := sem_sop2_typed o x1 x2 in\n    to_expr v in \n  match r with \n  | Ok e => e\n  | _ => Papp2 o e1 e2\n  end.\n\n(* -------------------------------------------------------------------------- *)\n(* ** Smart constructors                                                      *)\n(* -------------------------------------------------------------------------- *)\n\nFixpoint snot (e:pexpr) :=\n  match e with\n  | Pbool b      => ~~b\n  | Papp1 Onot e => e\n  | Papp2 Oand e1 e2 => Papp2 Oor (snot e1) (snot e2)\n  | Papp2 Oor  e1 e2 => Papp2 Oand (snot e1) (snot e2)\n  | Pif t e e1 e2 => Pif t e (snot e1) (snot e2)\n  | _             => Papp1 Onot e\n  end.\n\nDefinition sneg_int (e: pexpr) :=\n  match e with\n  | Pconst z => Pconst (- z)\n  | Papp1 (Oneg Op_int) e' => e'\n  | _ => Papp1 (Oneg Op_int) e\n  end.\n\nDefinition s_op1 o e :=\n  match o with\n  | Onot        => snot e\n  | Oneg Op_int => sneg_int e\n  | _           => ssem_sop1 o e\n  end.\n \n(* ------------------------------------------------------------------------ *)\n\nDefinition sbeq e1 e2 := \n  match is_bool e1, is_bool e2 with\n  | Some b1, Some b2 => Pbool (b1 == b2)\n  | Some b, _ => if b then e2 else snot e2 \n  | _, Some b => if b then e1 else snot e1 \n  | _, _      => Papp2 Obeq e1 e2\n  end.\n  \nDefinition sand e1 e2 :=\n  match is_bool e1, is_bool e2 with\n  | Some b, _ => if b then e2 else false\n  | _, Some b => if b then e1 else false\n  | _, _      => Papp2 Oand e1 e2\n  end.\n\nDefinition sor e1 e2 :=\n   match is_bool e1, is_bool e2 with\n  | Some b, _ => if b then Pbool true else e2\n  | _, Some b => if b then Pbool true else e1\n  | _, _       => Papp2 Oor e1 e2\n  end.\n\n(* ------------------------------------------------------------------------ *)\n\nDefinition sadd_int e1 e2 :=\n  match is_const e1, is_const e2 with\n  | Some n1, Some n2 => Pconst (n1 + n2)\n  | Some n, _ =>\n    if (n == 0)%Z then e2 else Papp2 (Oadd Op_int) e1 e2\n  | _, Some n =>\n    if (n == 0)%Z then e1 else Papp2 (Oadd Op_int) e1 e2\n  | _, _ => Papp2 (Oadd Op_int) e1 e2\n  end.\n\nDefinition sadd_w sz e1 e2 :=\n  match is_wconst sz e1, is_wconst sz e2 with\n  | Some n1, Some n2 => wconst (n1 + n2)\n  | Some n, _ => if n == 0%R then e2 else Papp2 (Oadd (Op_w sz)) e1 e2\n  | _, Some n => if n == 0%R then e1 else Papp2 (Oadd (Op_w sz)) e1 e2\n  | _, _ => Papp2 (Oadd (Op_w sz)) e1 e2\n  end.\n\nDefinition sadd ty :=\n  match ty with\n  | Op_int => sadd_int\n  | Op_w sz => sadd_w sz\n  end.\n\nDefinition ssub_int e1 e2 :=\n  match is_const e1, is_const e2 with\n  | Some n1, Some n2 => Pconst (n1 - n2)\n  | _, Some n =>\n    if (n == 0)%Z then e1 else Papp2 (Osub Op_int) e1 e2\n  | _, _ => Papp2 (Osub Op_int) e1 e2\n  end.\n\nDefinition ssub_w sz e1 e2 :=\n  match is_wconst sz e1, is_wconst sz e2 with\n  | Some n1, Some n2 => wconst (n1 - n2)\n  | _, Some n => if n == 0%R then e1 else Papp2 (Osub (Op_w sz)) e1 e2\n  | _, _ => Papp2 (Osub (Op_w sz)) e1 e2\n  end.\n\nDefinition ssub ty :=\n  match ty with\n  | Op_int => ssub_int\n  | Op_w sz => ssub_w sz\n  end.\n\nDefinition smul_int e1 e2 :=\n  match is_const e1, is_const e2 with\n  | Some n1, Some n2 => Pconst (n1 * n2)\n  | Some n, _ =>\n    if (n == 0)%Z then Pconst 0\n    else if (n == 1)%Z then e2\n    else Papp2 (Omul Op_int) e1 e2\n  | _, Some n =>\n    if (n == 0)%Z then Pconst 0\n    else if (n == 1)%Z then e1\n    else Papp2 (Omul Op_int) e1 e2\n  | _, _ => Papp2 (Omul Op_int) e1 e2\n  end.\n\nDefinition smul_w sz e1 e2 :=\n  match is_wconst sz e1, is_wconst sz e2 with\n  | Some n1, Some n2 => wconst (n1 * n2)\n  | Some n, _ =>\n    if n == 0%R then @wconst sz 0\n    else if n == 1%R then e2\n    else Papp2 (Omul (Op_w sz)) (wconst n) e2\n  | _, Some n =>\n    if n == 0%R then @wconst sz 0\n    else if n == 1%R then e1\n    else Papp2 (Omul (Op_w sz)) e1 (wconst n)\n  | _, _ => Papp2 (Omul (Op_w sz)) e1 e2\n  end.\n\nDefinition smul ty :=\n  match ty with\n  | Op_int => smul_int\n  | Op_w sz => smul_w sz\n  end.\n\nDefinition s_eq ty e1 e2 :=\n  if eq_expr e1 e2 then Pbool true\n  else\n    match ty with\n    | Op_int =>\n      match is_const e1, is_const e2 with\n      | Some i1, Some i2 => Pbool (i1 == i2)\n      | _, _             => Papp2 (Oeq ty) e1 e2\n      end\n    | Op_w sz =>\n      match is_wconst sz e1, is_wconst sz e2 with\n      | Some i1, Some i2 => Pbool (i1 == i2)\n      | _, _             => Papp2 (Oeq ty) e1 e2\n      end\n    end.\n\nDefinition sneq ty e1 e2 :=\n  match is_bool (s_eq ty e1 e2) with\n  | Some b => Pbool (~~ b)\n  | None      => Papp2 (Oneq ty) e1 e2\n  end.\n\nDefinition is_cmp_const (ty: cmp_kind) (e: pexpr) : option Z :=\n  match ty with\n  | Cmp_int => is_const e\n  | Cmp_w sg sz =>\n    is_wconst sz e >>= λ w,\n    Some match sg with\n    | Signed => wsigned w\n    | Unsigned => wunsigned w\n    end\n  end%O.\n\nDefinition slt ty e1 e2 :=\n  if eq_expr e1 e2 then Pbool false\n  else match is_cmp_const ty e1, is_cmp_const ty e2 with\n  | Some n1, Some n2 => Pbool (n1 <? n2)%Z\n  | _      , _       => Papp2 (Olt ty) e1 e2\n  end.\n\nDefinition sle ty e1 e2 :=\n  if eq_expr e1 e2 then Pbool true\n  else match is_cmp_const ty e1, is_cmp_const ty e2 with\n  | Some n1, Some n2 => Pbool (n1 <=? n2)%Z\n  | _      , _       => Papp2 (Ole ty) e1 e2\n  end.\n\nDefinition sgt ty e1 e2 :=\n  if eq_expr e1 e2 then Pbool false\n  else match is_cmp_const ty e1, is_cmp_const ty e2 with\n  | Some n1, Some n2 => Pbool (n1 >? n2)%Z\n  | _      , _       => Papp2 (Ogt ty) e1 e2\n  end.\n\nDefinition sge ty e1 e2 :=\n  if eq_expr e1 e2 then Pbool true\n  else match is_cmp_const ty e1, is_cmp_const ty e2 with\n  | Some n1, Some n2 => Pbool (n1 >=? n2)%Z\n  | _      , _       => Papp2 (Oge ty) e1 e2\n  end.\n\n\nDefinition s_op2 o e1 e2 :=\n  match o with\n  | Obeq    => sbeq e1 e2 \n  | Oand    => sand e1 e2\n  | Oor     => sor  e1 e2\n  | Oadd ty => sadd ty e1 e2\n  | Osub ty => ssub ty e1 e2\n  | Omul ty => smul ty e1 e2\n  | Oeq  ty => s_eq ty e1 e2\n  | Oneq ty => sneq ty e1 e2\n  | Olt  ty => slt  ty e1 e2\n  | Ole  ty => sle  ty e1 e2\n  | Ogt  ty => sgt  ty e1 e2\n  | Oge  ty => sge  ty e1 e2\n  | _       => ssem_sop2 o e1 e2\n  end.\n\nDefinition app_sopn := app_sopn of_expr.\n\nArguments app_sopn {A} ts _ _.\n\nDefinition s_opN (op:opN) (es:pexprs) : pexpr :=\n  match app_sopn _ (sem_opN_typed op) es with\n  | Ok r =>\n    match op return sem_t (type_of_opN op).2 -> _ with\n    | Opack ws _ => fun w => Papp1 (Oword_of_int ws) (Pconst (wunsigned w))\n    | Ocombine_flags _ => fun b => Pbool b\n    end r\n  | _ => PappN op es\n  end.\n\nDefinition s_if t e e1 e2 :=\n  match is_bool e with\n  | Some b => if b then e1 else e2\n  | None   => Pif t e e1 e2\n  end.\n\n(* ** constant propagation\n * -------------------------------------------------------------------- *)\n\nVariant const_v :=\n  | Cbool of bool\n  | Cint of Z\n  | Cword sz `(word sz).\n\nDefinition const_v_beq (c1 c2: const_v) : bool :=\n  match c1, c2 with\n  | Cbool b1, Cbool b2 => b1 == b2\n  | Cint z1, Cint z2 => z1 == z2\n  | Cword sz1 w1, Cword sz2 w2 =>\n    match wsize_eq_dec sz1 sz2 with\n    | left e => eq_rect _ word w1 _ e == w2\n    | _ => false\n    end\n  | _, _ => false\n  end.\n\nLemma const_v_eq_axiom : Equality.axiom const_v_beq.\nProof.\ncase => [ b1 | z1 | sz1 w1 ] [ b2 | z2 | sz2 w2] /=; try (constructor; congruence).\n+ case: eqP => [ -> | ne ]; constructor; congruence.\n+ case: eqP => [ -> | ne ]; constructor; congruence.\ncase: wsize_eq_dec => [ ? | ne ]; last (constructor; congruence).\nsubst => /=.\nby apply:(iffP idP) => [ /eqP | [] ] ->.\nQed.\n\nDefinition const_v_eqMixin     := Equality.Mixin const_v_eq_axiom.\nCanonical  const_v_eqType      := Eval hnf in EqType const_v const_v_eqMixin.\n\nLocal Notation cpm := (Mvar.t const_v).\n\nDefinition const v :=\n  match v with\n  | Cbool b => Pbool b\n  | Cint z  => Pconst z\n  | Cword sz z => wconst z\n  end.\n\nFixpoint const_prop_e (m:cpm) e :=\n  match e with\n  | Pconst _\n  | Pbool  _\n  | Parr_init _\n    => e\n  | Pvar  x       => \n    if is_lvar x then\n      if Mvar.get m x.(gv) is Some n then const n else e      \n    else e\n  | Pget aa sz x e => Pget aa sz x (const_prop_e m e)\n  | Psub aa sz len x e => Psub aa sz len x (const_prop_e m e)\n  | Pload sz x e  => Pload sz x (const_prop_e m e)\n  | Papp1 o e     => s_op1 o (const_prop_e m e)\n  | Papp2 o e1 e2 => s_op2 o (const_prop_e m e1)  (const_prop_e m e2)\n  | PappN op es   => s_opN op (map (const_prop_e m) es)\n  | Pif t e e1 e2 => s_if t (const_prop_e m e) (const_prop_e m e1) (const_prop_e m e2)\n  end.\n\nDefinition empty_cpm : cpm := @Mvar.empty const_v.\n\nDefinition merge_cpm : cpm -> cpm -> cpm :=\n  Mvar.map2 (fun _ (o1 o2: option const_v) =>\n   match o1, o2 with\n   | Some n1, Some n2 =>\n     if (n1 == n2)%Z then Some n1\n     else None\n   | _, _ => None\n   end).\n\nDefinition remove_cpm (m:cpm) (s:Sv.t): cpm :=\n  Sv.fold (fun x m => Mvar.remove m x) s m.\n\nDefinition const_prop_rv (m:cpm) (rv:lval) : cpm * lval :=\n  match rv with\n  | Lnone _ _       => (m, rv)\n  | Lvar  x         => (Mvar.remove m x, rv)\n  | Lmem  sz x e    => (m, Lmem sz x (const_prop_e m e))\n  | Laset aa sz x e => (Mvar.remove m x, Laset aa sz x (const_prop_e m e))\n  | Lasub aa sz len x e => (Mvar.remove m x, Lasub aa sz len x (const_prop_e m e))\n  end.\n\nFixpoint const_prop_rvs (m:cpm) (rvs:lvals) : cpm * lvals :=\n  match rvs with\n  | [::] => (m, [::])\n  | rv::rvs =>\n    let (m,rv)  := const_prop_rv m rv in\n    let (m,rvs) := const_prop_rvs m rvs in\n    (m, rv::rvs)\n  end.\n\nDefinition wsize_of_stype (ty: stype) : wsize :=\n  if ty is sword sz then sz else U64.\n\nDefinition add_cpm (m:cpm) (rv:lval) tag ty e :=\n  if rv is Lvar x then\n    if tag is AT_inline then\n      match e with\n      | Pbool b  => Mvar.set m x (Cbool b)\n      | Pconst z =>  Mvar.set m x (Cint z)\n      | Papp1 (Oword_of_int sz') (Pconst z) =>\n        let szty := wsize_of_stype ty in\n        let w := zero_extend szty (wrepr sz' z) in\n        let w :=\n            let szx := wsize_of_stype (vtype x) in\n            if (szty ≤ szx)%CMP\n            then Cword w\n            else Cword (zero_extend szx w) in\n        Mvar.set m x w\n      | _ => m\n      end\n    else m\n  else m.\n\nSection ASM_OP.\n\nContext `{asmop:asmOp}.\n\nSection CMD.\n\n  Variable const_prop_i : cpm -> instr -> cpm * cmd.\n\n  Fixpoint const_prop (m:cpm) (c:cmd) : cpm * cmd :=\n    match c with\n    | [::] => (m, [::])\n    | i::c =>\n      let (m,ic) := const_prop_i m i in\n      let (m, c) := const_prop m c in\n      (m, ic ++ c)\n    end.\n\nEnd CMD.\n\nFixpoint const_prop_ir (m:cpm) ii (ir:instr_r) : cpm * cmd :=\n  match ir with\n  | Cassgn x tag ty e =>\n    let e := const_prop_e m e in\n    let (m,x) := const_prop_rv m x in\n    let m := add_cpm m x tag ty e in\n    (m, [:: MkI ii (Cassgn x tag ty e)])\n\n  | Copn xs t o es =>\n    (* TODO: Improve this *)\n    let es := map (const_prop_e m) es in\n    let (m,xs) := const_prop_rvs m xs in\n    (m, [:: MkI ii (Copn xs t o es) ])\n\n  | Csyscall xs o es =>\n    let es := map (const_prop_e m) es in\n    let (m,xs) := const_prop_rvs m xs in\n    (m, [:: MkI ii (Csyscall xs o es) ])\n\n  | Cif b c1 c2 =>\n    let b := const_prop_e m b in\n    match is_bool b with\n    | Some b =>\n      let c := if b then c1 else c2 in\n      const_prop const_prop_i m c\n    | None =>\n      let (m1,c1) := const_prop const_prop_i m c1 in\n      let (m2,c2) := const_prop const_prop_i m c2 in\n      (merge_cpm m1 m2, [:: MkI ii (Cif b c1 c2) ])\n    end\n\n  | Cfor x (dir, e1, e2) c =>\n    let e1 := const_prop_e m e1 in\n    let e2 := const_prop_e m e2 in\n    let m := remove_cpm m (write_i ir) in\n    let (_,c) := const_prop const_prop_i m c in\n    (m, [:: MkI ii (Cfor x (dir, e1, e2) c) ])\n\n  | Cwhile a c e c' =>\n    let m := remove_cpm m (write_i ir) in\n    let (m',c) := const_prop const_prop_i m c in\n    let e := const_prop_e m' e in\n    let (_,c') := const_prop const_prop_i m' c' in\n    let cw :=\n      match is_bool e with\n      | Some false => c\n      | _          => [:: MkI ii (Cwhile a c e c')]\n      end in\n    (m', cw)\n\n  | Ccall fi xs f es =>\n    let es := map (const_prop_e m) es in\n    let (m,xs) := const_prop_rvs m xs in\n    (m, [:: MkI ii (Ccall fi xs f es) ])\n\n  end\n\nwith const_prop_i (m:cpm) (i:instr) : cpm * cmd :=\n  let (ii,ir) := i in\n  const_prop_ir m ii ir.\n\nSection Section.\n\nContext {T} {pT:progT T}.\n\nDefinition const_prop_fun (f:fundef) :=\n  let 'MkFun ii si p c so r ev := f in\n  let (_, c) := const_prop const_prop_i empty_cpm c in\n  MkFun ii si p c so r ev.\n\nDefinition const_prop_prog (p:prog) : prog := map_prog const_prop_fun p.\n\nEnd Section.\n\nEnd ASM_OP.\nEnd WITH_PARAMS.\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/constant_prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.2945399082458839}}
{"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.Classes.Morphisms.\nRequire Import Fiat.Parsers.Reflective.Syntax Fiat.Parsers.Reflective.Semantics.\nRequire Import Fiat.Parsers.Reflective.PartialUnfold.\nRequire Import Fiat.Parsers.Reflective.SyntaxEquivalence.\nRequire Import Fiat.Parsers.Reflective.Morphisms.\nRequire Import Fiat.Common.List.ListFacts.\nRequire Import Fiat.Common.Equality.\n\nFixpoint related {T} : interp_TypeCode T -> normalized_of interp_TypeCode T -> Prop\n  := match T return interp_TypeCode T -> normalized_of interp_TypeCode T -> Prop with\n     | csimple T' => fun b e => b = interp_Term e\n     | (dom --> ran)%typecode\n       => fun f1 f2 => forall x1 x2, related x1 x2 -> related (f1 x1) (f2 x2)\n     end.\n\nLocal Ltac concretize := cbv zeta.\nLocal Ltac simpler' := concretize; simpl in *; try subst; intros; auto; try subst; intros; auto;\n  try congruence; try omega; try (elimtype False; omega).\nLocal Ltac simplerGoal :=\n  idtac;\n  match goal with\n  | [ H : False |- _ ] => destruct H\n  | [ x : unit |- _ ] => destruct x\n  | [ x : (_ * _)%type |- _ ] => destruct x\n  | [ H : ex _ |- _ ] => destruct H\n  | [ H : _ /\\ _ |- _ ] => destruct H\n  | [ H : _ \\/ _ |- _ ] => destruct H\n  | _ => progress unfold eq_rect in *\n  | [ H : (_ + _)%type -> _ |- _ ]\n    => pose proof (fun x => H (inl x));\n       pose proof (fun x => H (inr x));\n       clear H\n  | [ H : forall x : ?A = clist ?A, _ |- _ ] => clear H\n  | [ H : forall x : csimple ?A = csimple (clist ?A), _ |- _ ] => clear H\n  | [ H : False -> _ |- _ ] => clear H\n  | [ H : sigT ?P -> _ |- _ ] => specialize (fun x p => H (existT P x p))\n  | [ H : sig ?P -> _ |- _ ] => specialize (fun x p => H (exist P x p))\n  | [ H : ?x = ?x -> _ |- _ ] => specialize (H eq_refl)\n  | [ H : forall a b c, (_ + _)%type -> _ |- _ ]\n    => pose proof (fun a b c x => H a b c (inl x));\n       pose proof (fun a b c x => H a b c (inr x));\n       clear H\n  | [ H : forall a b c, False -> _ |- _ ] => clear H\n  | [ H : forall a b c, sigT _ -> _ |- _ ] => specialize (fun a b c x p => H a b c (existT _ x p))\n  | [ H : forall a b c, sig _ -> _ |- _ ] => specialize (fun a b c x p => H a b c (exist _ x p))\n  | [ H : forall a b c (d : ?x = a), _ |- _ ] => specialize (fun b c => H _ b c eq_refl)\n  | [ H : ?P -> _ |- _ ] =>\n    let H' := fresh \"H'\" in\n    assert (H' : P); [ solve [ auto ]\n                     | generalize (H H'); clear H H'; intro H ]\n  | [ H : ?x = ?y |- _ ]\n    => pose proof (pr2_path H);\n       generalize dependent (pr1_path H);\n       clear H;\n       intros ??\n    | [ H : forall a b, _ /\\ _ -> _ |- _ ]\n      => specialize (fun a b c d => H a b (conj c d))\n    | [ H : forall a b (c : ?v = a), _ |- _ ]\n      => specialize (fun b => H _ b eq_refl)\n    | [ H : forall a (b : ?v = a), _ |- _ ]\n      => specialize (H _ eq_refl)\n    | [ H : ?A -> ?B, H' : ?A |- _ ] => specialize (H H')\n  (*| [ H : existT ?F ?T ?X = existT _ ?T ?Y |- _ ] =>\n                        generalize (inj_pair2 _ F _ X Y H); clear H*)\n  | [ H : Some ?X = Some ?Y |- _ ] =>\n    lazymatch X with\n    | Y => clear H\n    | _ => injection H; try clear H; intro\n    end\n  | [ H : option_map _ ?x = Some _ |- _ ]\n    => destruct x eqn:?; unfold option_map at 1 in H\n  | [ H : Some _ = option_map _ ?x |- _ ]\n    => destruct x eqn:?; unfold option_map at 1 in H\n  (*| [ H : an_arg _ _ = an_arg _ _ |- _ ]\n    => apply args_for_encode in H; unfold args_for_code in H\n  | [ H : noargsv = noargsv |- _ ] => clear H\n  | [ H : @args_for_equiv _ _ _ (carrow _ _) _ _ |- _ ]\n    => apply invert_args_for_equiv in H; cbv beta iota in H\n  | [ H : @args_for_equiv _ _ _ (csimple _) _ _ |- _ ]\n    => apply invert_args_for_equiv in H; cbv beta iota in H*)\n  | [ |- _ /\\ _ ] => split\n\n  | [ |- context[if ?E then _ else _] ] => destruct E eqn:?\n  (*| [ |- context[match ?pf with refl_equal => _ end] ] => rewrite (UIP_refl _ _ pf)*)\n  | [ H : context[if ?E then _ else _] |- _ ] => destruct E eqn:?\n  | [ |- (_, _) = (_, _) ] => apply f_equal2\n  | [ |- cons _ _ = cons _ _ ] => apply f_equal2\n  (*| [ |- an_argv _ _ = an_argv _ _ ] => apply f_equal2*)\n  | _ => progress simpl\n  | [ |- context[interp_Term_gen ?f ?v] ]\n    => change (interp_Term_gen f v)\n       with (@interp_Term_gen_step f (@interp_Term_gen f) _ v)\n  | [ |- context[option_map _ ?x] ]\n    => destruct x eqn:?; simpl\n  (*| _ => progress unfold interp_args_for, interp_Term in **)\n  end.\nLocal Ltac simpler := simpler'; repeat (simplerGoal; simpler').\nLocal Ltac simpler_args_for' :=\n  idtac;\n  match goal with\n  | [ args : args_for _ (carrow ?A ?B) |- _ ]\n    => let H := fresh in\n       pose proof (invert_args_for_ex args) as H; cbv beta iota in H;\n       destruct H as [? [? ?]]; subst args\n  | [ args : args_for _ (csimple ?B) |- _ ]\n    => let H := fresh in\n       pose proof (invert_args_for_ex args) as H; cbv beta iota in H;\n       subst args\n  end.\nLocal Ltac simpler_args_for := repeat simpler_args_for'.\n\n\nLemma push_var : forall t v1 v2 t' v1' v2' G,\n  vars v1' v2' = vars v1 v2\n  \\/ List.In (vars v1 v2) G\n  -> (forall t'' v1'' v2'', List.In (vars v1'' v2'') G -> @related t'' v1'' v2'')\n  -> @related t' v1' v2'\n  -> @related t v1 v2.\nProof.\n  simpler.\nQed.\n\nLemma constantOf_correct\n  : forall {T} (t : Term interp_TypeCode T) v\n           (H : constantOf t = Some v),\n    interp_Term t = interp_constantOf v.\nProof.\n  unfold interp_Term;\n  intros T t; induction t;\n  repeat match goal with\n         | [ t : RLiteralTerm _ |- _ ] => destruct t\n         | [ t : RLiteralConstructor _ |- _ ] => destruct t\n         | [ H : constantOf ?bv = Some ?dv, H' : forall a b c d, constantOf b = Some d -> _ |- _ ]\n           => pose proof (fun c => H' _ bv c dv H); clear H\n         | _ => progress simpler_args_for\n         | _ => progress simpler\n         end.\nQed.\n\nLocal Ltac simpler_constantOf\n  := repeat match goal with\n            | [ H : constantOf ?t = Some ?v |- _ ]\n              => apply (@constantOf_correct _ t v) in H\n            end.\n\nLemma fold_left_app {A B A' B'}\n      (f : A -> B -> A) (ls : list B) (init : A)\n      (g : A' -> B' -> A') (ha : A -> A') (hb : B -> B')\n      (H : forall x y, g (ha x) (hb y) = ha (f x y))\n  : List.fold_left g (List.map hb ls) (ha init)\n    = ha (List.fold_left f ls init).\nProof.\n  revert init; induction ls as [|x xs IHxs]; simpl; [ reflexivity | ]; intros.\n  rewrite <- IHxs, H; reflexivity.\nQed.\n\nLemma bool_rect_nodep_const {P x b}\n  : BoolFacts.Bool.bool_rect_nodep P x x b = x.\nProof. destruct b; reflexivity. Qed.\n\nCreate HintDb partial_unfold_hints discriminated.\n\nHint Rewrite <- @interp_Term_syntactify_list @interp_Term_syntactify_nat @List.map_rev : partial_unfold_hints.\nHint Rewrite @nth'_nth List.map_nth List.map_map List.map_length List.map_id @combine_map_r @combine_map_l @first_index_default_map Bool.orb_true_r Bool.orb_true_l Bool.andb_true_l Bool.andb_true_r Bool.orb_false_r Bool.orb_false_l Bool.andb_false_l Bool.andb_false_r BoolFacts.andbr_andb BoolFacts.orbr_orb @bool_rect_nodep_const @BoolFacts.uneta_bool_rect_nodep : partial_unfold_hints.\nHint Resolve map_ext_in fold_left_app (@constantOf_correct cbool) @first_index_default_first_index_partial : partial_unfold_hints.\n\nLocal Ltac meaning_tac_helper' :=\n  idtac;\n  match goal with\n  | [ |- ?x = ?y ] => reflexivity\n  | [ H : forall a b (c : a = _), _ |- _ ] => specialize (fun b => H _ b eq_refl)\n  | [ H : forall a b c (d : b = _), _ |- _ ] => specialize (fun a c => H a _ c eq_refl)\n  | [ H : forall x y, _ = _ |- _ ] => setoid_rewrite <- H\n  | [ |- context[Common.apply_n ?n ?f ?x] ]\n    => clear;\n       let IH := fresh \"IH\" in\n       generalize x; induction n as [|? IH]; simpl;\n       [ reflexivity\n       | intro; rewrite <- IH; unfold interp_Term; simpl;\n         first [ reflexivity\n               | omega ] ]\n  | [ |- context[Operations.List.list_caset_nodep _ _ ?ls] ]\n    => is_var ls; destruct ls\n  | [ |- Operations.List.list_caset_nodep _ _ ?ls = Operations.List.list_caset_nodep _ _ ?ls ]\n    => destruct ls\n  | [ H : ?x = _ |- context[?x] ] => rewrite H\n  | [ |- context[Reflective.ritem_rect_nodep _ _ ?x] ]\n    => destruct x eqn:?; simpl\n  | [ H : forall x, _ = _ |- _ ] => rewrite <- H; reflexivity\n  | [ H : forall x, _ = _ |- _ ] => setoid_rewrite <- H; reflexivity\n  | [ |- context[match ?x with Some _ => _ | None => _ end] ]\n    => destruct x eqn:?\n  end.\nLocal Ltac meaning_tac_helper := repeat meaning_tac_helper'.\n\nLocal Ltac meaning_tac :=\n  repeat first [ progress autorewrite with partial_unfold_hints\n               | progress eauto with partial_unfold_hints\n               | progress rewrite_strat (topdown (hints partial_unfold_hints))\n               | progress meaning_tac_helper\n               | progress simpl_interp_Term_in_all ].\n\nLocal Hint Extern 1 (@related ?T ?X (reflect (RVar ?Y))) =>\nchange (@related T (interp_Term (RVar X)) (reflect (RVar Y))).\nLocal Hint Extern 1 (@related _ (interp_Term_gen ?iRLT ?A ?X1) _) =>\n  change (interp_Term_gen iRLT A X1)\n  with (interp_Term_gen iRLT (RApp A (RVar X1))).\nLemma reify_and_reflect_correct : forall t,\n    (forall v r,\n        @related t v r\n        -> Proper_relation_for _ v (interp_Term (reify _ r)))\n    /\\ (forall a a',\n           @Proper_relation_for t (interp_Term a) (interp_Term a')\n           -> @related t (interp_Term a) (reflect a')).\nProof.\n  unfold interp_Term;\n  induction t; simpler; unfold respectful; eauto.\nQed.\n\nLemma reify_correct : forall t v r,\n  @related t v r\n  -> Proper_relation_for _ v (interp_Term (reify _ r)).\nProof.\n  generalize reify_and_reflect_correct; firstorder.\nQed.\n\nLemma args_for_related_related_map {T v1 v2} (f := @meaning _)\n  : (args_for_related\n       (T := T)\n       (fun T (m : Term interp_TypeCode T) (n : Term (normalized_of interp_TypeCode) T)\n        => related (interp_Term m) (f T n))\n       v1 v2)\n    -> (args_for_related (fun T => Proper_relation_for T)\n                          (map_args_for (@interp_Term) v1)\n                          (map_args_for (@interp_Term) (unmeanings (meanings f v2)))).\nProof.\n  subst f; revert v2.\n  induction v1; intro;\n    pose proof (invert_args_for_ex v2) as H'; simpl in *;\n      [ destruct H' as [? [? ?]] | subst; split; reflexivity ];\n      subst; simpl in *.\n  intros [H0 H1]; split; try assumption;\n    [ | apply IHv1; assumption ]; clear IHv1.\n  apply reify_and_reflect_correct; assumption.\nQed.\n\nLemma interp_apply_meaning_helper\n      T f f' (Hf : @related T f f')\n      args args'\n      (Hargs : args_for_related (fun T' m n => related (interp_Term m) (meaning n)) args args')\n  : apply_args_for f (map_args_for (fun _ t => interp_Term t) args)\n    = interp_Term (apply_meaning_helper (meanings (@meaning interp_TypeCode) args') f').\nProof.\n  apply args_for_related_noind_ind in Hargs.\n  revert f f' Hf.\n  induction Hargs; [ | solve [ simpl; trivial ] ].\n  apply args_for_related_noind_ind in Hargs.\n  simpl in *.\n  eauto with nocore.\nQed.\n\nLocal Ltac simpler_meaning :=\n  repeat match goal with\n         | _ => progress simpler_constantOf\n         | _ => progress simpler_args_for\n         | _ => progress simpl_interp_Term_in_all\n         | _ => progress simpler\n         | _ => progress simpl in *\n         | [ H : ?x = _ |- context[?x] ] => rewrite H\n         | [ H : context[match constantOf ?x with _ => _ end] |- _ ]\n           => destruct (constantOf x) eqn:?\n         | [ H : match ?T with cbool => _ | _ => _ end _ = Some _ |- _ ]\n           => is_var T; destruct T\n         end.\n\nLemma list_rect_nodep_meaning_correct {A : SimpleTypeCode} {P} f f' n n'\n      (Hn : @related P n n')\n      (Hf : @related (A --> clist A --> P --> P) f f')\n      (ls : list (Term interp_TypeCode A))\n  : related (Operations.List.list_rect_nodep n f (List.map (@interp_Term _) ls))\n            (Operations.List.list_rect_nodep n' (fun x xs => f' x (Syntactify.syntactify_list xs)) ls).\nProof.\n  induction ls; simpl in *; [ assumption | ].\n  apply Hf; eauto using eq_refl, @interp_Term_syntactify_list with nocore.\nQed.\n\nHint Resolve @list_rect_nodep_meaning_correct : partial_unfold_hints.\n\nLemma specific_meaning_correct\n      t r val v1 v2\n      (Hrel : args_for_related\n                (fun T' m n => @related T' (interp_Term m) (meaning n)) v1 v2)\n      (Heq : specific_meaning r (meanings (@meaning interp_TypeCode) v2) = Some val)\n  : interp_Term (@RLiteralApp _ t r v1) = interp_Term val.\nProof.\n  destruct r; simpl in Heq;\n    unfold specific_meaning_apply1, specific_meaning_apply2 in *;\n    try solve [ simpler_meaning; meaning_tac ].\n  { simpler_meaning; meaning_tac.\n    apply interp_apply_meaning_helper; simpl; try assumption; [].\n    apply list_rect_nodep_meaning_correct; simpl; eauto with nocore.\n    simpler_meaning; meaning_tac. }\n  { simpler_meaning; meaning_tac.\n    rewrite Plus.plus_comm; meaning_tac. }\nQed.\n\nLocal Hint Resolve push_var.\nLemma meaning_correct\n  : forall G t e1 e2,\n    Term_equiv G e1 e2\n    -> (forall t' v1 v2, List.In (vars v1 v2) G\n                         -> @related t' v1 v2)\n    -> @related t (interp_Term e1) (meaning e2).\nProof.\n  unfold interp_Term;\n    induction 1 (*using Term_equiv_ind_in*); try solve [ simpler; eauto ].\n  { simpler.\n    repeat match goal with\n           | [ H : args_for_related_ind _ _ _ |- _ ]\n             => apply args_for_related_noind_ind in H\n           | [ H : args_for_related (fun x y z => ?P -> _) _ _ |- _ ]\n             => setoid_rewrite <- args_for_related_impl in H\n           | _ => progress simpl_interp_Term_in_all\n           | [ H : ?A -> ?B, H' : ?A |- _ ] => specialize (H H')\n           | [ f : RLiteralTerm _ |- _ ] => destruct f\n           | [ |- apply_args_for _ _ = apply_args_for _ _ ]\n             => apply apply_args_for_Proper;\n                  [ apply RLiteralTerm_Proper | apply args_for_related_related_map; assumption ]\n           | [ |- context[specific_meaning ?r ?x] ]\n             => destruct (specific_meaning r x) eqn:?\n           end.\n    eapply specific_meaning_correct; eassumption. }\nQed.\n\nLemma nil_context : forall t v1 v2,\n  List.In (vars v1 v2) nil\n  -> @related t v1 v2.\nProof.\n  simpl; tauto.\nQed.\n\nLocal Hint Resolve nil_context meaning_correct reify_correct.\nTheorem polynormalize_correct : forall t (E : polyTerm t),\n    Term_equiv nil (E interp_TypeCode) (E (normalized_of interp_TypeCode))\n    -> Proper_relation_for _ (interp_Term (E _)) (interp_Term (polynormalize E _)).\nProof.\n  unfold interp_Term, polynormalize, normalize; eauto.\nQed.\n", "meta": {"author": "scuellar", "repo": "narcissus_errors", "sha": "8c547389030165e8620b43bb38ad87b9b65e5471", "save_path": "github-repos/coq/scuellar-narcissus_errors", "path": "github-repos/coq/scuellar-narcissus_errors/narcissus_errors-8c547389030165e8620b43bb38ad87b9b65e5471/src/Parsers/Reflective/LogicalRelations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.2945399082458839}}
{"text": "From Coq Require Import List String.\nRequire Import FSet Config L10.AST.\n\nSection Callset.\n\nContext {C: VyperConfig}.\n\n(** Get the set of functions called by an expression. *)\nFixpoint expr_callset (e: expr)\n: string_set\n:= let _ := string_set_impl in\n   match e with\n   | Const _ | LocalVar _ | StorageVar _ => empty\n   | UnOp _ a => expr_callset a\n   | BinOp _ a b\n   | LogicalOr a b\n   | LogicalAnd a b => union (expr_callset a) (expr_callset b)\n   | IfThenElse a b c => union (expr_callset a) (union (expr_callset b) (expr_callset c))\n   | PrivateOrBuiltinCall name args =>\n      let fix expr_list_callset (exprs: list expr)\n          := match exprs with\n             | nil => empty\n             | (h :: t)%list => union (expr_callset h) (expr_list_callset t)\n             end\n      in add (expr_list_callset args) name\n   end.\nFixpoint expr_list_callset (exprs: list expr)\n: string_set\n:= let _ := string_set_impl in\n   match exprs with\n   | nil => empty\n   | (h :: t)%list => union (expr_callset h) (expr_list_callset t)\n   end.\n\nDefinition small_stmt_callset (s: small_stmt)\n:= let _ := string_set_impl in\n   match s with\n   | Pass | Break | Continue | Return None | Revert => empty\n   | Return (Some e) | Raise e | Assert e None | ExprStmt e =>\n       expr_callset e\n   | Assign lhs rhs | BinOpAssign lhs _ rhs => expr_callset rhs\n   | Assert cond (Some error) => union (expr_callset cond) (expr_callset error)\n   end.\n\nFixpoint stmt_callset (s: stmt)\n:= let _ := string_set_impl in\n   let fix stmt_list_callset (stmts: list stmt) \n       := match stmts with\n          | nil => empty\n          | (h :: t)%list => union (stmt_callset h) (stmt_list_callset t)\n          end\n   in match s with\n   | SmallStmt a => small_stmt_callset a\n   | LocalVarDecl _ None => empty\n   | LocalVarDecl _ (Some e) => expr_callset e\n   | IfElseStmt cond yes None => union (expr_callset cond) (stmt_list_callset yes)\n   | IfElseStmt cond yes (Some no) => union (expr_callset cond)\n                                            (union (stmt_list_callset yes) (stmt_list_callset no))\n   | FixedRangeLoop var start _ body => stmt_list_callset body\n   | FixedCountLoop var start _ body => union (expr_callset start) (stmt_list_callset body)\n   end.\n\nFixpoint stmt_list_callset (stmts: list stmt)\n:= let _ := string_set_impl in\n   match stmts with\n   | nil => empty\n   | (h :: t)%list => union (stmt_callset h) (stmt_list_callset t)\n   end.\n\nDefinition stmt_list_callset' (stmts: list stmt)\n:= let _ := string_set_impl in fold_right union empty (map stmt_callset stmts).\n\nLtac descend H \n:= subst; cbn in H;\n   repeat try rewrite union_subset_and in H;\n   repeat rewrite Bool.andb_true_iff in H;\n   try tauto.\n\nLemma stmt_list_callset_alt (s: list stmt):\n  stmt_list_callset s = stmt_list_callset' s.\nProof.\ninduction s. { easy. }\ncbn. f_equal. apply IHs.\nQed.\n\nDefinition decl_callset (d: decl)\n:= let _ := string_set_impl in match d with\n   | StorageVarDecl _ => empty\n   | FunDecl name args body => stmt_list_callset body\n   end.\n\nLemma callset_descend_unop {e a: expr} {op: unop}\n                           {allowed_calls: string_set}\n                           (E: e = UnOp op a)\n                           (ok: let _ := string_set_impl in\n                                FSet.is_subset (expr_callset e) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (expr_callset a) allowed_calls = true.\nProof.\ndescend ok.\nQed.\n\nLemma callset_descend_binop_left {e a b: expr} {op: binop}\n                                 {allowed_calls: string_set}\n                                 (E: e = BinOp op a b)\n                                 (ok: let _ := string_set_impl in\n                                      FSet.is_subset (expr_callset e) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (expr_callset a) allowed_calls = true.\nProof.\ndescend ok.\nQed.\n\nLemma callset_descend_binop_right {e a b: expr} {op: binop}\n                                  {allowed_calls: string_set}\n                                  (E: e = BinOp op a b)\n                                  (ok: let _ := string_set_impl in\n                                       FSet.is_subset (expr_callset e) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (expr_callset b) allowed_calls = true.\nProof.\ndescend ok.\nQed.\n\nLemma callset_leaf {e: expr} {name: string} {args: list expr}\n                   {allowed_calls: string_set}\n                   (E: e = PrivateOrBuiltinCall name args)\n                   (ok: let _ := string_set_impl in\n                         FSet.is_subset (expr_callset e) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.has allowed_calls name = true.\nProof.\nsubst e. cbn in ok.\nrewrite FSet.is_subset_ok in ok.\nassert (Ok := ok name). clear ok.\nrewrite FSet.add_ok in Ok.\ndestruct (string_dec name name). 2:{ tauto. }\ncbn.\ndestruct (FSet.has allowed_calls name). { trivial. }\ncbn in Ok. discriminate.\nQed.\n\nLemma callset_descend_args {e: expr} {name: string} {args: list expr}\n                           {allowed_calls: string_set}\n                           (E: e = PrivateOrBuiltinCall name args)\n                           (ok: let _ := string_set_impl in\n                                FSet.is_subset (expr_callset e) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (expr_list_callset args) allowed_calls = true.\nProof.\nsubst e. cbn in *.\nunfold expr_list_callset.\napply (FSet.is_subset_trans (FSet.add_subset _ _) ok).\nQed.\n\n\nLemma callset_descend_head {h: expr} {t e: list expr}\n                           {allowed_calls: string_set}\n                           (E: e = (h :: t)%list)\n                           (ok: let _ := string_set_impl in\n                           FSet.is_subset (expr_list_callset e) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (expr_callset h) allowed_calls = true.\nProof.\ndescend ok.\nQed.\n\nLemma callset_descend_tail {h: expr} {t e: list expr}\n                           {allowed_calls: string_set}\n                           (E: e = (h :: t)%list)\n                           (ok: let _ := string_set_impl in\n                           FSet.is_subset (expr_list_callset e) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (expr_list_callset t) allowed_calls = true.\nProof.\ndescend ok.\nQed.\n\nLemma callset_descend_if_cond {cond yes no e: expr}\n                              {allowed_calls: string_set}\n                              (E: e = IfThenElse cond yes no)\n                              (ok: let _ := string_set_impl in\n                                   FSet.is_subset (expr_callset e) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (expr_callset cond) allowed_calls = true.\nProof.\ndescend ok.\nQed.\n\nLemma callset_descend_if_then {cond yes no e: expr}\n                              {allowed_calls: string_set}\n                              (E: e = IfThenElse cond yes no)\n                              (ok: let _ := string_set_impl in\n                                   FSet.is_subset (expr_callset e) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (expr_callset yes) allowed_calls = true.\nProof.\ndescend ok.\nQed.\n\nLemma callset_descend_if_else {cond yes no e: expr}\n                              {allowed_calls: string_set}\n                              (E: e = IfThenElse cond yes no)\n                              (ok: let _ := string_set_impl in\n                                   FSet.is_subset (expr_callset e) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (expr_callset no) allowed_calls = true.\nProof.\ndescend ok.\nQed.\n\nLemma callset_descend_and_left {a b e: expr}\n                               {allowed_calls: string_set}\n                               (E: e = LogicalAnd a b)\n                               (ok: let _ := string_set_impl in\n                                    FSet.is_subset (expr_callset e) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (expr_callset a) allowed_calls = true.\nProof.\ndescend ok.\nQed.\n\nLemma callset_descend_and_right {a b e: expr}\n                                {allowed_calls: string_set}\n                                (E: e = LogicalAnd a b)\n                                (ok: let _ := string_set_impl in\n                                     FSet.is_subset (expr_callset e) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (expr_callset b) allowed_calls = true.\nProof.\ndescend ok.\nQed.\n\nLemma callset_descend_or_left {a b e: expr}\n                              {allowed_calls: string_set}\n                              (E: e = LogicalOr a b)\n                              (ok: let _ := string_set_impl in\n                                   FSet.is_subset (expr_callset e) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (expr_callset a) allowed_calls = true.\nProof.\ndescend ok.\nQed.\n\nLemma callset_descend_or_right {a b e: expr}\n                               {allowed_calls: string_set}\n                               (E: e = LogicalOr a b)\n                               (ok: let _ := string_set_impl in\n                                    FSet.is_subset (expr_callset e) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (expr_callset b) allowed_calls = true.\nProof.\ndescend ok.\nQed.\n\nLemma callset_descend_return {s: small_stmt} {e: expr}\n                             {allowed_calls: string_set}\n                             (E: s = Return (Some e))\n                             (ok: let _ := string_set_impl in\n                                  FSet.is_subset (small_stmt_callset s) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (expr_callset e) allowed_calls = true.\nProof.\ndescend ok.\nQed.\n\nLemma callset_descend_raise {s: small_stmt} {e: expr}\n                            {allowed_calls: string_set}\n                            (E: s = Raise e)\n                            (ok: let _ := string_set_impl in\n                                 FSet.is_subset (small_stmt_callset s) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (expr_callset e) allowed_calls = true.\nProof.\ndescend ok.\nQed.\n\nLemma callset_descend_expr_stmt {s: small_stmt} {e: expr}\n                                {allowed_calls: string_set}\n                                (E: s = ExprStmt e)\n                                (ok: let _ := string_set_impl in\n                                     FSet.is_subset (small_stmt_callset s) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (expr_callset e) allowed_calls = true.\nProof.\ndescend ok.\nQed.\n\nLemma callset_descend_assert_cond {s: small_stmt} {cond: expr} {maybe_e: option expr}\n                                  {allowed_calls: string_set}\n                                  (E: s = Assert cond maybe_e)\n                                  (ok: let _ := string_set_impl in\n                                       FSet.is_subset (small_stmt_callset s) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (expr_callset cond) allowed_calls = true.\nProof.\nsubst. cbn in *. destruct maybe_e; cbn in ok; descend ok.\nQed.\n\nLemma callset_descend_assert_error {s: small_stmt} {cond e: expr} {maybe_e: option expr}\n                                   {allowed_calls: string_set}\n                                   (E: s = Assert cond maybe_e)\n                                   (Ee: maybe_e = Some e)\n                                   (ok: let _ := string_set_impl in\n                                        FSet.is_subset (small_stmt_callset s) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (expr_callset e) allowed_calls = true.\nProof.\ndescend ok.\nQed.\n\nLemma callset_descend_assign_rhs {s: small_stmt} {lhs: assignable} {rhs: expr}\n                                 {allowed_calls: string_set}\n                                 (E: s = Assign lhs rhs)\n                                 (ok: let _ := string_set_impl in\n                                      FSet.is_subset (small_stmt_callset s) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (expr_callset rhs) allowed_calls = true.\nProof.\ndescend ok.\nQed.\n\nLemma callset_descend_binop_assign_rhs {s: small_stmt} {lhs: assignable} {rhs: expr}\n                                       {allowed_calls: string_set}\n                                       {op: binop}\n                                       (E: s = BinOpAssign lhs op rhs)\n                                       (ok: let _ := string_set_impl in\n                                            FSet.is_subset (small_stmt_callset s) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (expr_callset rhs) allowed_calls = true.\nProof.\ndescend ok.\nQed.\n\nLemma callset_descend_small_stmt {s: stmt} {ss: small_stmt}\n                                 {allowed_calls: string_set}\n                                 (E: s = SmallStmt ss)\n                                 (ok: let _ := string_set_impl in\n                                      FSet.is_subset (stmt_callset s) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (small_stmt_callset ss) allowed_calls = true.\nProof.\ndescend ok.\nQed.\n\nLemma callset_descend_stmt_if_cond {cond: expr} {yes: list stmt} {no: option (list stmt)} {s: stmt}\n                                   {allowed_calls: string_set}\n                                   (E: s = IfElseStmt cond yes no)\n                                   (ok: let _ := string_set_impl in\n                                        FSet.is_subset (stmt_callset s) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (expr_callset cond) allowed_calls = true.\nProof.\ndestruct no; descend ok.\nQed.\n\nLemma callset_descend_stmt_if_then {cond: expr} {yes: list stmt} {no: option (list stmt)} {s: stmt}\n                                   {allowed_calls: string_set}\n                                   (E: s = IfElseStmt cond yes no)\n                                   (ok: let _ := string_set_impl in\n                                        FSet.is_subset (stmt_callset s) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (stmt_list_callset yes) allowed_calls = true.\nProof.\ndestruct no; descend ok.\nQed.\n\nLemma callset_descend_stmt_if_else {cond: expr} {yes no: list stmt}\n                                   {maybe_no: option (list stmt)} {s: stmt}\n                                   {allowed_calls: string_set}\n                                   (E: s = IfElseStmt cond yes maybe_no)\n                                   (Eno: maybe_no = Some no)\n                                   (ok: let _ := string_set_impl in\n                                        FSet.is_subset (stmt_callset s) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (stmt_list_callset no) allowed_calls = true.\nProof.\nsubst. cbn in *. descend ok.\nQed.\n\nLemma callset_descend_init_expr {stmts t: list stmt} {s: stmt} {init: expr}\n                                {allowed_calls: string_set}\n                                (E: stmts = s :: t)\n                                (Evar: is_local_var_decl s = true)\n                                (Einit: snd (var_decl_unpack s Evar) = Some init)\n                                (ok: let _ := string_set_impl in\n                                     FSet.is_subset (stmt_list_callset stmts) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (expr_callset init) allowed_calls = true.\nProof.\ncbn in *. destruct s; cbn in Evar; try discriminate.\ncbn in *. subst. descend ok.\nQed.\n\nLemma callset_descend_stmt_head {stmts tail: list stmt} {head: stmt}\n                                {allowed_calls: string_set}\n                                (E: stmts = head :: tail)\n                                (ok: let _ := string_set_impl in\n                                     FSet.is_subset (stmt_list_callset stmts) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (stmt_callset head) allowed_calls = true.\nProof.\ndescend ok.\nQed.\n\nLemma callset_descend_stmt_tail {stmts tail: list stmt} {head: stmt}\n                                {allowed_calls: string_set}\n                                (E: stmts = head :: tail)\n                                (ok: let _ := string_set_impl in\n                                     FSet.is_subset (stmt_list_callset stmts) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (stmt_list_callset tail) allowed_calls = true.\nProof.\ndescend ok.\nQed.\n\nLemma callset_descend_fixed_range_loop_body {s: stmt} {body: list stmt} {var start stop}\n                                            {allowed_calls: string_set}\n                                            (E: s = FixedRangeLoop var start stop body)\n                                (ok: let _ := string_set_impl in\n                                     FSet.is_subset (stmt_callset s) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (stmt_list_callset body) allowed_calls = true.\nProof.\ndescend ok.\nQed.\n\nLemma callset_descend_fixed_count_loop_body {s: stmt} {body: list stmt} {var start stop}\n                                            {allowed_calls: string_set}\n                                            (E: s = FixedCountLoop var start stop body)\n                                (ok: let _ := string_set_impl in\n                                     FSet.is_subset (stmt_callset s) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (stmt_list_callset body) allowed_calls = true.\nProof.\ndescend ok.\nQed.\n\nLemma callset_descend_fixed_count_loop_start {s: stmt} {body: list stmt} {var start count}\n                                             {allowed_calls: string_set}\n                                             (E: s = FixedCountLoop var start count body)\n                                (ok: let _ := string_set_impl in\n                                     FSet.is_subset (stmt_callset s) allowed_calls = true):\n  let _ := string_set_impl in\n  FSet.is_subset (expr_callset start) allowed_calls = true.\nProof.\ndescend ok.\nQed.\n\nEnd Callset.\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/L10/Callset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.2945399082458839}}
{"text": "Require Import List Arith Bool.\nRequire Import Expr Env.\nRequire Import Reflection.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\n(** Provers that establish [expr]-encoded facts *)\n\nDefinition ProverCorrect types (fs : functions types) (summary : Type)\n    (** Some prover work only needs to be done once per set of hypotheses,\n       so we do it once and save the outcome in a summary of this type. *)\n  (valid : env types -> env types -> summary -> Prop)\n  (prover : summary -> expr types -> bool) : Prop :=\n  forall vars uvars sum,\n    valid uvars vars sum ->\n    forall goal, \n      prover sum goal = true ->\n      ValidProp fs uvars vars goal ->\n      Provable fs uvars vars goal.\n\nRecord ProverT (types : list type) : Type :=\n{ Facts : Type\n; Summarize : exprs types -> Facts\n; Learn : Facts -> exprs types -> Facts\n; Prove : Facts -> expr types -> bool\n}.\n\nRecord ProverT_correct (types : list type) (P : ProverT types) (funcs : functions types) : Type :=\n{ Valid : env types -> env types -> Facts P -> Prop\n; Valid_weaken : forall u g f ue ge,\n  Valid u g f -> Valid (u ++ ue) (g ++ ge) f\n; Summarize_correct : forall uvars vars hyps, \n  AllProvable funcs uvars vars hyps ->\n  Valid uvars vars (Summarize P hyps)\n; Learn_correct : forall uvars vars facts,\n  Valid uvars vars facts -> forall hyps,\n  AllProvable funcs uvars vars hyps ->\n  Valid uvars vars (Learn P facts hyps)\n; Prove_correct : ProverCorrect funcs Valid (Prove P)\n}.\n\nRecord ProverPackage : Type :=\n{ ProverTypes : Repr type\n; ProverFuncs : forall ts, Repr (signature (repr ProverTypes ts))\n; Prover : forall ts, ProverT (repr ProverTypes ts)\n; Prover_correct : forall ts fs, \n  ProverT_correct (Prover ts) (repr (ProverFuncs ts) fs)\n}.\n\n\n(** Generic lemmas/tactis to prove things about provers **)\n\nHint Rewrite EquivDec_refl_left SemiDec_EquivDec_refl_left : provers.\n\n(* Everything looks like a nail?  Try this hammer. *)\nLtac t1 := match goal with\n             | _ => discriminate\n             | _ => progress (hnf in *; simpl in *; intuition; subst)\n             | [ x := _ : _ |- _ ] => subst x || (progress (unfold x in * ))\n             | [ H : ex _ |- _ ] => destruct H\n             | [ H : context[nth_error (updateAt ?new ?ls ?n) ?n] |- _ ] =>\n               rewrite (nth_error_updateAt new ls n) in H\n                 || rewrite nth_error_updateAt in H\n             | [ s : signature _ |- _ ] => destruct s\n             | [ H : Some _ = Some _ |- _ ] => injection H; clear H\n             | [ H : _ = Some _ |- _ ] => rewrite H in *\n             | [ H : _ === _ |- _ ] => rewrite H in *\n\n             | [ |- context[match ?E with\n                              | Const _ _ => _\n                              | Var _ => _\n                              | UVar _ => _\n                              | Func _ _ => _\n                              | Equal _ _ _ => _\n                              | Not _ => _\n                            end] ] => destruct E\n             | [ |- context[match ?E with\n                              | None => _\n                              | Some _ => _\n                            end] ] => destruct E\n             | [ |- context[if ?E then _ else _] ] => \n               consider E; intro\n             | [ |- context[match ?E with\n                              | nil => _\n                              | _ :: _ => _\n                            end] ] => destruct E\n             | [ H : _ || _ = true |- _ ] => apply orb_true_iff in H; destruct H\n             | [ _ : context[match ?E with\n                               | Const _ _ => _\n                               | Var _ => _\n                               | UVar _ => _\n                               | Func _ _ => _\n                               | Equal _ _ _ => _\n                               | Not _ => _\n                             end] |- _ ] => destruct E\n             | [ _ : context[match ?E with\n                               | nil => _\n                               | _ :: _ => _\n                             end] |- _ ] => destruct E\n             | [ H : context[if ?E then _ else _] |- _ ] => \n               revert H; consider E; try do 2 intro\n             | [ _ : context[match ?E with\n                               | left _ => _\n                               | right _ => _\n                             end] |- _ ] => destruct E\n             | [ _ : context[match ?E with\n                               | tvProp => _\n                               | tvType _ => _\n                             end] |- _ ] => destruct E\n             | [ _ : context[match ?E with\n                               | None => _\n                               | Some _ => _\n                             end] |- _ ] => match E with\n                                              | context[match ?E with\n                                                          | None => _\n                                                          | Some _ => _\n                                                  end] => fail 1\n                                              | _ => destruct E\n                                            end\n\n             | [ _ : context[match ?E with (_, _) => _ end] |- _ ] => destruct E\n           end.\n\nLtac t := repeat t1; eauto.\n\n(** Composite Prover **)\nSection composite.\n  Variable types : list type.\n  Variables pl pr : ProverT types.\n\n  Definition composite_ProverT : ProverT types :=\n  {| Facts := Facts pl * Facts pr\n   ; Summarize := fun hyps =>\n     (Summarize pl hyps, Summarize pr hyps)\n   ; Learn := fun facts hyps =>\n     let (fl,fr) := facts in\n     (Learn pl fl hyps, Learn pr fr hyps)\n   ; Prove := fun facts goal =>\n     let (fl,fr) := facts in\n     (Prove pl fl goal) || (Prove pr fr goal)\n   |}.\n\n  Variable funcs : functions types.\n  Variable pl_correct : ProverT_correct pl funcs.\n  Variable pr_correct : ProverT_correct pr funcs.\n\n  Theorem composite_ProverT_correct : ProverT_correct composite_ProverT funcs.\n    \n    refine (\n      {| Valid := fun uvars vars (facts : Facts composite_ProverT) =>\n        let (fl,fr) := facts in\n          Valid pl_correct uvars vars fl /\\ Valid pr_correct uvars vars fr\n      |}); destruct pl_correct; destruct pr_correct; simpl; try destruct facts; intuition eauto.\n    unfold ProverCorrect. destruct sum; intuition.\n    apply orb_true_iff in H.\n    destruct H; eauto.\n  Qed.\nEnd composite.", "meta": {"author": "csgordon", "repo": "bedrock", "sha": "debab1b6e491b7c5e83bd3b1fe5d0e4c4e728d12", "save_path": "github-repos/coq/csgordon-bedrock", "path": "github-repos/coq/csgordon-bedrock/bedrock-debab1b6e491b7c5e83bd3b1fe5d0e4c4e728d12/src/Prover.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251201477015, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.29449895632211864}}
{"text": "Require Import GL4ip_PSGL4ip_calcs.\nRequire Import List.\nExport ListNotations.\n\nRequire Import genT gen.\nRequire Import ddT.\nRequire Import gen_tacs.\nRequire Import gen_seq.\nRequire Import List_lemmasT.\nRequire Import existsT.\nRequire Import univ_gen_ext.\nRequire Import GL4ip_PSGL4ip_list_lems.\nRequire Import dd_fc.\nRequire Import PeanoNat.\nRequire Import strong_inductionT.\nRequire Import GL4ip_exch.\nRequire Import GL4ip_wkn.\nRequire Import GL4ip_PSGL4ip_remove_list.\nRequire Import GL4ip_PSGL4ip_dec.\nRequire Import GL4ip_ImpL_adm.\nRequire Import GL4ip_inv_ImpR.\nRequire Import Lia.\n\n\nTheorem ImpImpL_inv_L :  forall n s (D0 : derrec GL4ip_rules (fun _ => False) s) A B C D Γ0 Γ1,\n                              (n = derrec_height D0) ->\n                              (s = (Γ0 ++ (A  → B) → D :: Γ1, C)) ->\n                              derrec GL4ip_rules (fun _ => False) (Γ0 ++ A :: B → D :: B → D :: Γ1, C).\nProof.\nassert (DersNilF: dersrec GL4ip_rules (fun _ : Seq  => False) []).\napply dersrec_nil.\n(* Setting up the strong induction on the height. *)\npose (strong_inductionT (fun (x:nat) => forall s (D0 : derrec GL4ip_rules (fun _ => False) s) A B C D Γ0 Γ1,\n                              (x = derrec_height D0) ->\n                              (s = (Γ0 ++ (A  → B) → D :: Γ1, C)) ->\n                              derrec GL4ip_rules (fun _ => False) (Γ0 ++ A :: B → D :: B → D :: Γ1, C))).\napply d. intros n IH. clear d.\n(* Now we do the actual proof-theoretical work. *)\nintros s D0. remember D0 as D0'. destruct D0.\n(* D0 is a leaf *)\n- destruct f.\n(* D0 is ends with an application of rule *)\n- intros A B C D Γ0 Γ1 hei eq. inversion g ; subst.\n  (* IdP *)\n  * inversion H. subst. assert (InT # P (Γ0 ++  (A  → B) → D :: Γ1)).\n    rewrite <- H2. apply InT_or_app. right. apply InT_eq. assert (InT # P (Γ0 ++ A :: B → D :: B → D :: Γ1)).\n    apply InT_app_or in H0. destruct H0. apply InT_or_app. auto. apply InT_or_app. right. inversion i.\n    subst. inversion H1. subst. repeat apply InT_cons. auto.\n    apply InT_split in H1. destruct H1. destruct s. rewrite e. assert (IdPRule [] (x ++ # P :: x0, # P)).\n    apply IdPRule_I. apply IdP in H1.\n    pose (derI (rules:=GL4ip_rules) (prems:=fun _ : Seq => False)\n    (ps:=[]) (x ++ # P :: x0, # P) H1 DersNilF). auto.\n  (* BotL *)\n  * inversion H. subst. assert (InT (⊥) (Γ0 ++  (A  → B) → D :: Γ1)).\n    rewrite <- H2. apply InT_or_app. right. apply InT_eq. assert (InT (⊥) (Γ0 ++ A :: B → D :: B → D :: Γ1)).\n    apply InT_app_or in H0. destruct H0. apply InT_or_app. auto. apply InT_or_app. right. inversion i.\n    subst. inversion H1. subst. repeat apply InT_cons. auto. apply InT_split in H1. destruct H1. destruct s. rewrite e.\n    assert (BotLRule [] (x ++ ⊥ :: x0, C)). apply BotLRule_I. apply BotL in H1.\n    pose (derI (rules:=GL4ip_rules) (prems:=fun _ : Seq => False)\n    (ps:=[]) (x ++ ⊥ :: x0, C) H1 DersNilF). auto.\n   (* AndR *)\n  * inversion H. subst. assert (J30: dersrec_height d = dersrec_height d). reflexivity.\n    pose (@dersrec_derrec2_height (dersrec_height d) _ _ _ _ _ d J30). repeat destruct s. simpl.\n    simpl in IH.\n    assert (J2: derrec_height x < S (dersrec_height d)). lia.\n    assert (J3: derrec_height x = derrec_height x). reflexivity.\n    assert (J4 : (Γ0 ++  (A  → B) → D :: Γ1, A0) = (Γ0 ++  (A  → B) → D :: Γ1, A0)). auto.\n    pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n    assert (J5: derrec_height x0 < S (dersrec_height d)). lia.\n    assert (J6: derrec_height x0 = derrec_height x0). reflexivity.\n    assert (J7 : (Γ0 ++  (A  → B) → D :: Γ1, B0) = (Γ0 ++  (A  → B) → D :: Γ1, B0)). auto.\n    pose (IH _ J5 _ x0 _ _ _ _ _ _ J6 J7).\n    assert (AndRRule [(Γ0 ++ A :: B → D :: B → D :: Γ1, A0); (Γ0 ++ A :: B → D :: B → D :: Γ1, B0)]\n    (Γ0 ++ A :: B → D :: B → D :: Γ1, A0 ∧ B0)). apply AndRRule_I. pose (dlCons d1 DersNilF). pose (dlCons d0 d2).\n    apply AndR in H0.\n    pose (derI (rules:=GL4ip_rules) (prems:=fun _ : Seq => False)\n   (ps:=[(Γ0 ++ A :: B → D :: B → D :: Γ1, A0); (Γ0 ++ A :: B → D :: B → D :: Γ1, B0)])\n    (Γ0 ++ A :: B → D :: B → D :: Γ1, A0 ∧ B0) H0 d3). auto.\n  (* AndL *)\n  * inversion H. subst. apply list_split_form in H2. destruct H2. repeat destruct s ; repeat destruct p ; subst.\n   + inversion e0.\n   + assert (J30: dersrec_height d = dersrec_height d). reflexivity.\n      pose (@dersrec_derrec_height (dersrec_height d) _ _ _ _ d J30). destruct s.\n      assert (J2: derrec_height x < S (dersrec_height d)). lia.\n      assert (J3: derrec_height x = derrec_height x). reflexivity.\n      assert (J4 : (((Γ0 ++ [ (A  → B) → D]) ++ x0) ++ A0 :: B0 :: Γ3, C) = (Γ0 ++  (A  → B) → D :: x0 ++ A0 :: B0 :: Γ3, C)).\n      repeat rewrite <- app_assoc. auto.\n      pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n      assert (AndLRule [((Γ0 ++ A :: B → D :: B → D :: x0) ++ A0 :: B0 :: Γ3, C)]\n       ((Γ0 ++ A :: B → D :: B → D :: x0) ++ A0 ∧ B0 :: Γ3, C)). apply AndLRule_I. repeat rewrite <- app_assoc in H0. simpl in H0.\n       pose (dlCons d0 DersNilF). apply AndL in H0.\n       pose (derI (rules:=GL4ip_rules) (prems:=fun _ : Seq => False)\n       (ps:=[(Γ0 ++ A :: B → D :: B → D :: x0 ++ A0 :: B0 :: Γ3, C)])\n       (Γ0 ++ A :: B → D :: B → D :: x0 ++ A0 ∧ B0 :: Γ3, C) H0 d1). auto.\n  +  repeat destruct s. repeat destruct p ; subst.\n      assert (J30: dersrec_height d = dersrec_height d). reflexivity.\n      pose (@dersrec_derrec_height (dersrec_height d) _ _ _ _ d J30). destruct s.\n      assert (J2: derrec_height x0 < S (dersrec_height d)). lia.\n      assert (J3: derrec_height x0 = derrec_height x0). reflexivity.\n      assert (J4 : (Γ2 ++ A0 :: B0 :: x ++  (A  → B) → D :: Γ1, C) = ((Γ2 ++ A0 :: B0 :: x) ++  (A  → B) → D :: Γ1, C)).\n      repeat rewrite <- app_assoc. auto. pose (IH _ J2 _ x0 _ _ _ _ _ _ J3 J4).\n      pose (dlCons d0 DersNilF).\n      assert (AndLRule [((Γ2 ++ A0 :: B0 :: x) ++ A :: B → D :: B → D :: Γ1, C)]\n       ((Γ2 ++ A0 ∧ B0 :: x) ++ A :: B → D :: B → D :: Γ1, C)). repeat rewrite <- app_assoc. apply AndLRule_I.\n       apply AndL in H0.\n      pose (derI (rules:=GL4ip_rules) (prems:=fun _ : Seq => False)\n      (ps:=[((Γ2 ++ A0 :: B0 :: x) ++ A :: B → D :: B → D :: Γ1, C)])\n      ((Γ2 ++ A0 ∧ B0 :: x) ++ A :: B → D :: B → D :: Γ1, C) H0 d1). auto.\n  (* OrR1 *)\n  * inversion H. subst. assert (J30: dersrec_height d = dersrec_height d). reflexivity.\n    pose (@dersrec_derrec_height (dersrec_height d) _ _ _ _ d J30). repeat destruct s. simpl.\n    assert (J2: derrec_height x < S (dersrec_height d)). lia.\n    assert (J3: derrec_height x = derrec_height x). reflexivity.\n    assert (J4 : (Γ0 ++  (A  → B) → D :: Γ1, A0) = (Γ0 ++  (A  → B) → D :: Γ1, A0)). auto.\n    pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n    assert (OrR1Rule [(Γ0 ++ A :: B → D :: B → D :: Γ1, A0)]\n    (Γ0 ++ A :: B → D :: B → D :: Γ1, Or A0 B0)). apply OrR1Rule_I. pose (dlCons d0 DersNilF).\n    apply OrR1 in H0.\n    pose (derI (rules:=GL4ip_rules) (prems:=fun _ : Seq => False)\n    (ps:=[(Γ0 ++ A :: B → D :: B → D :: Γ1, A0)])\n    (Γ0 ++ A :: B → D :: B → D  :: Γ1, Or A0 B0) H0 d1). auto.\n  (* OrR2 *)\n  * inversion H. subst. assert (J30: dersrec_height d = dersrec_height d). reflexivity.\n    pose (@dersrec_derrec_height (dersrec_height d) _ _ _ _ d J30). repeat destruct s. simpl.\n    assert (J2: derrec_height x < S (dersrec_height d)). lia.\n    assert (J3: derrec_height x = derrec_height x). reflexivity.\n    assert (J4 : (Γ0 ++  (A  → B) → D :: Γ1, B0) = (Γ0 ++  (A  → B) → D :: Γ1, B0)). auto.\n    pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n    assert (OrR2Rule [(Γ0 ++ A :: B → D :: B → D :: Γ1, B0)]\n    (Γ0 ++ A :: B → D :: B → D :: Γ1, Or A0 B0)). apply OrR2Rule_I. pose (dlCons d0 DersNilF).\n    apply OrR2 in H0.\n    pose (derI (rules:=GL4ip_rules) (prems:=fun _ : Seq => False)\n    (ps:=[(Γ0 ++ A :: B → D :: B → D :: Γ1, B0)])\n    (Γ0 ++ A :: B → D :: B → D  :: Γ1, Or A0 B0) H0 d1). auto.\n  (* OrL *)\n  * inversion H. subst. apply list_split_form in H2. destruct H2. repeat destruct s ; repeat destruct p ; subst.\n   + inversion e0.\n   + assert (J30: dersrec_height d = dersrec_height d). reflexivity.\n      pose (@dersrec_derrec2_height (dersrec_height d) _ _ _ _ _ d J30). repeat destruct s. simpl.\n      assert (J2: derrec_height x < S (dersrec_height d)). lia.\n      assert (J3: derrec_height x = derrec_height x). reflexivity.\n      assert (J4 : (((Γ0 ++ [ (A  → B) → D]) ++ x0) ++ A0 :: Γ3, C) = (Γ0 ++  (A  → B) → D :: (x0 ++ A0 :: Γ3), C)). repeat rewrite <- app_assoc. auto.\n      pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n      assert (J5: derrec_height x1 < S (dersrec_height d)). lia.\n      assert (J6: derrec_height x1 = derrec_height x1). reflexivity.\n      assert (J7 : (((Γ0 ++ [ (A  → B) → D]) ++ x0) ++ B0 :: Γ3, C) = (Γ0 ++  (A  → B) → D :: (x0 ++ B0 :: Γ3), C)). repeat rewrite <- app_assoc. auto.\n      pose (IH _ J5 _ x1 _ _ _ _ _ _ J6 J7).\n      assert (OrLRule [((Γ0 ++ A :: B → D :: B → D :: x0) ++ A0 :: Γ3, C);((Γ0 ++ A :: B → D :: B → D :: x0) ++ B0 :: Γ3, C)]\n      ((Γ0 ++ A :: B → D :: B → D :: x0) ++ A0 ∨ B0 :: Γ3, C)). apply OrLRule_I. apply OrL in H0.\n      repeat rewrite <- app_assoc in H0. simpl in H0.\n      pose (dlCons d1 DersNilF). pose (dlCons d0 d2).\n      pose (derI (rules:=GL4ip_rules) (prems:=fun _ : Seq => False)\n      (ps:=[(Γ0 ++ A :: B → D :: B → D :: x0 ++ A0 :: Γ3, C); (Γ0 ++ A :: B → D :: B → D :: x0 ++ B0 :: Γ3, C)])\n      (Γ0 ++ A :: B → D :: B → D :: x0 ++ A0 ∨ B0 :: Γ3, C) H0 d3). auto.\n   + repeat destruct s. repeat destruct p ; subst. assert (J30: dersrec_height d = dersrec_height d). reflexivity.\n      pose (@dersrec_derrec2_height (dersrec_height d) _ _ _ _ _ d J30). repeat destruct s.\n      assert (J2: derrec_height x0 < S (dersrec_height d)). lia.\n      assert (J3: derrec_height x0 = derrec_height x0). reflexivity.\n      assert (J4 :(Γ2 ++ A0 :: x ++  (A  → B) → D :: Γ1, C) = ((Γ2 ++ A0 :: x) ++  (A  → B) → D :: Γ1, C)). repeat rewrite <- app_assoc. auto.\n      pose (IH _ J2 _ x0 _ _ _ _ _ _ J3 J4).\n      assert (J5: derrec_height x1 < S (dersrec_height d)). lia.\n      assert (J6: derrec_height x1 = derrec_height x1). reflexivity.\n      assert (J7 : (Γ2 ++ B0 :: x ++  (A  → B) → D :: Γ1, C) = ((Γ2 ++ B0 :: x) ++  (A  → B) → D :: Γ1, C)). repeat rewrite <- app_assoc. auto.\n      pose (IH _ J5 _ x1 _ _ _ _ _ _ J6 J7).\n      assert (OrLRule [((Γ2 ++ A0 :: x) ++ A :: B → D :: B → D :: Γ1, C);((Γ2 ++ B0 :: x) ++ A :: B → D :: B → D :: Γ1, C)]\n      ((Γ2 ++ A0 ∨ B0 :: x) ++ A :: B → D :: B → D :: Γ1, C)). repeat rewrite <- app_assoc. apply OrLRule_I. apply OrL in H0.\n      pose (dlCons d1 DersNilF). pose (dlCons d0 d2).\n      pose (derI (rules:=GL4ip_rules) (prems:=fun _ : Seq => False)\n      (ps:=[((Γ2 ++ A0 :: x) ++ A :: B → D :: B → D :: Γ1, C); ((Γ2 ++ B0 :: x) ++ A :: B → D :: B → D :: Γ1, C)])\n      ((Γ2 ++ A0 ∨ B0 :: x) ++ A :: B → D :: B → D :: Γ1, C) H0 d3). auto.\n  (* ImpR *)\n  * inversion H. subst. assert (J30: dersrec_height d = dersrec_height d). reflexivity.\n    pose (@dersrec_derrec_height (dersrec_height d) _ _ _ _ d J30). destruct s.\n    assert (J50: derrec_height x = derrec_height x). auto.\n    assert (J51: list_exch_L (Γ2 ++ A0 :: Γ3, B0) (A0 :: Γ0 ++  (A  → B) → D :: Γ1, B0)).\n    assert (Γ2 ++ A0 :: Γ3 = [] ++ [] ++ Γ2 ++ [A0] ++ Γ3). auto. rewrite H0.\n    assert (A0 :: Γ0 ++  (A  → B) → D :: Γ1 = [] ++ [A0] ++ Γ2 ++ [] ++ Γ3). rewrite <- H2. auto. rewrite H1.\n    apply list_exch_LI.\n    pose (GL4ip_hpadm_list_exch_L (derrec_height x) _ x J50 _ J51). destruct s.\n    assert (J2: derrec_height x0 < S (dersrec_height d)). lia.\n    assert (J3: derrec_height x0 = derrec_height x0). reflexivity.\n    assert (J4: (A0 :: Γ0 ++  (A  → B) → D :: Γ1, B0) = ((A0 :: Γ0) ++  (A  → B) → D :: Γ1, B0)). repeat rewrite <- app_assoc. auto.\n    pose (IH _ J2 _ x0 _ _ _ _ _ _ J3 J4).\n    assert (ImpRRule [(([] ++ A0 :: Γ0) ++ A :: B → D :: B → D :: Γ1, B0)] ([] ++ Γ0 ++ A :: B → D :: B → D :: Γ1, A0 → B0)). repeat rewrite <- app_assoc. apply ImpRRule_I.\n    simpl in H0. apply ImpR in H0. pose (dlCons d0 DersNilF).\n    pose (derI (rules:=GL4ip_rules) (prems:=fun _ : Seq => False)\n    (ps:=[((A0 :: Γ0) ++ A :: B → D :: B → D :: Γ1, B0)]) (Γ0 ++ A :: B → D :: B → D :: Γ1, A0 → B0) H0 d1). auto.\n  (* AtomImpL1 *)\n  * inversion H. subst. assert (J30: dersrec_height d = dersrec_height d). reflexivity.\n    pose (@dersrec_derrec_height (dersrec_height d) _ _ _ _ d J30). destruct s.\n    apply list_split_form in H2. destruct H2. repeat destruct s ; repeat destruct p ; subst.\n   + inversion e1.\n   + assert (J2: derrec_height x < S (dersrec_height d)). lia.\n       assert (J3: derrec_height x = derrec_height x). reflexivity.\n       assert (J4: (((Γ0 ++ [ (A  → B) → D]) ++ x1) ++ # P :: Γ3 ++ A0 :: Γ4, C) = (Γ0 ++  (A  → B) → D :: x1 ++ # P :: Γ3 ++ A0 :: Γ4, C)). repeat rewrite <- app_assoc. auto.\n       pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n       assert (AtomImpL1Rule [((Γ0 ++ A :: B → D :: B → D :: x1) ++ # P :: Γ3 ++ A0 :: Γ4, C)]\n       ((Γ0 ++ A :: B → D :: B → D :: x1) ++ # P :: Γ3 ++ # P → A0 :: Γ4, C)). apply AtomImpL1Rule_I.\n       repeat rewrite <- app_assoc in H0. apply AtomImpL1 in H0.\n       pose (dlCons d0 DersNilF).\n       pose (derI (rules:=GL4ip_rules) (prems:=fun _ : Seq => False)\n       (ps:=[(Γ0 ++ A :: B → D :: B → D :: x1 ++ # P :: Γ3 ++ A0 :: Γ4, C)])\n       (Γ0 ++ A :: B → D :: B → D :: x1 ++ # P :: Γ3 ++ # P → A0 :: Γ4, C) H0 d1). auto.\n   + repeat destruct s. repeat destruct p ; subst.\n      apply list_split_form in e1. destruct e1. repeat destruct s ; repeat destruct p ; subst.\n      { inversion e1. }\n      { assert (J2: derrec_height x < S (dersrec_height d)). lia.\n         assert (J3: derrec_height x = derrec_height x). reflexivity.\n         assert (J4: (Γ2 ++ # P :: ((x0 ++ [ (A  → B) → D]) ++ x2) ++ A0 :: Γ4, C) = ((Γ2 ++ # P :: x0) ++  (A  → B) → D :: x2 ++ A0 :: Γ4, C)). repeat rewrite <- app_assoc. auto.\n         pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n         assert (AtomImpL1Rule [((Γ2 ++ # P :: x0) ++ A :: B → D :: B → D :: x2 ++ A0 :: Γ4, C)]\n         ((Γ2 ++ # P :: x0) ++ A :: B → D :: B → D :: x2 ++ # P → A0 :: Γ4, C)).\n         assert ((Γ2 ++ # P :: x0) ++ A :: B → D :: B → D :: x2 ++ A0 :: Γ4 = Γ2 ++ # P :: (x0 ++ A :: B → D :: B → D :: x2) ++ A0 :: Γ4). repeat rewrite <- app_assoc. auto.\n         rewrite H0.\n         assert ((Γ2 ++ # P :: x0) ++ A :: B → D :: B → D :: x2 ++ # P → A0 :: Γ4 = Γ2 ++ # P :: (x0 ++ A :: B → D :: B → D :: x2) ++ # P → A0 :: Γ4). repeat rewrite <- app_assoc. auto.\n         rewrite H1. apply AtomImpL1Rule_I. apply AtomImpL1 in H0. pose (dlCons d0 DersNilF).\n         pose (derI (rules:=GL4ip_rules) (prems:=fun _ : Seq => False)\n         (ps:=[((Γ2 ++ # P :: x0) ++ A :: B → D :: B → D :: x2 ++ A0 :: Γ4, C)])\n         ((Γ2 ++ # P :: x0) ++ A :: B → D :: B → D :: x2 ++ # P → A0 :: Γ4, C) H0 d1). auto. }\n      { repeat destruct s. repeat destruct p ; subst.\n         assert (J2: derrec_height x < S (dersrec_height d)). lia.\n         assert (J3: derrec_height x = derrec_height x). reflexivity.\n         assert (J4: (Γ2 ++ # P :: Γ3 ++ A0 :: x1 ++  (A  → B) → D :: Γ1, C) = ((Γ2 ++ # P :: Γ3 ++ A0 :: x1) ++  (A  → B) → D :: Γ1, C)).\n         repeat rewrite <- app_assoc ; simpl ; repeat rewrite <- app_assoc ; auto.\n         pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n         assert (AtomImpL1Rule [((Γ2 ++ # P :: Γ3 ++ A0 :: x1) ++ A :: B → D :: B → D :: Γ1, C)]\n         ((Γ2 ++ # P :: Γ3 ++ # P → A0 :: x1) ++ A :: B → D :: B → D :: Γ1, C)). repeat rewrite <- app_assoc. simpl. repeat rewrite <- app_assoc.\n         apply AtomImpL1Rule_I. apply AtomImpL1 in H0. pose (dlCons d0 DersNilF).\n         pose (derI (rules:=GL4ip_rules) (prems:=fun _ : Seq => False)\n         (ps:=[((Γ2 ++ # P :: Γ3 ++ A0 :: x1) ++ A :: B → D :: B → D :: Γ1, C)])\n         ((Γ2 ++ # P :: Γ3 ++ # P → A0 :: x1) ++ A :: B → D :: B → D :: Γ1, C) H0 d1). auto. }\n  (* AtomImpL2 *)\n  * inversion H. subst. assert (J30: dersrec_height d = dersrec_height d). reflexivity.\n    pose (@dersrec_derrec_height (dersrec_height d) _ _ _ _ d J30). destruct s.\n    apply list_split_form in H2. destruct H2. repeat destruct s ; repeat destruct p ; subst.\n   + inversion e1.\n   + assert (J2: derrec_height x < S (dersrec_height d)). lia.\n       assert (J3: derrec_height x = derrec_height x). reflexivity.\n       assert (J4: (((Γ0 ++ [ (A  → B) → D]) ++ x1) ++ A0 :: Γ3 ++ # P :: Γ4, C) = (Γ0 ++  (A  → B) → D :: x1 ++ A0 :: Γ3 ++ # P :: Γ4, C)). repeat rewrite <- app_assoc. auto.\n       pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n       assert (AtomImpL2Rule [((Γ0 ++ A :: B → D :: B → D :: x1) ++ A0 :: Γ3 ++ # P :: Γ4, C)]\n       ((Γ0 ++ A :: B → D :: B → D :: x1) ++ # P → A0 :: Γ3 ++ # P :: Γ4, C)). apply AtomImpL2Rule_I.\n       repeat rewrite <- app_assoc in H0. apply AtomImpL2 in H0.\n       pose (dlCons d0 DersNilF).\n       pose (derI (rules:=GL4ip_rules) (prems:=fun _ : Seq => False)\n       (ps:=[(Γ0 ++ A :: B → D :: B → D :: x1 ++ A0 :: Γ3 ++ # P :: Γ4, C)])\n       (Γ0 ++ A :: B → D :: B → D :: x1 ++ # P → A0 :: Γ3 ++ # P :: Γ4, C) H0 d1). auto.\n   + repeat destruct s. repeat destruct p ; subst.\n      apply list_split_form in e1. destruct e1. repeat destruct s ; repeat destruct p ; subst.\n      { inversion e1. }\n      { assert (J2: derrec_height x < S (dersrec_height d)). lia.\n         assert (J3: derrec_height x = derrec_height x). reflexivity.\n         assert (J4: (Γ2 ++ A0 :: ((x0 ++ [ (A  → B) → D]) ++ x2) ++ # P :: Γ4, C) = ((Γ2 ++ A0 :: x0) ++  (A  → B) → D :: x2 ++ # P :: Γ4, C)). repeat rewrite <- app_assoc. auto.\n         pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n         assert (AtomImpL2Rule [((Γ2 ++ A0 :: x0) ++ A :: B → D :: B → D :: x2 ++ # P :: Γ4, C)]\n         ((Γ2 ++ # P → A0 :: x0) ++ A :: B → D :: B → D :: x2 ++ # P :: Γ4, C)).\n         assert ((Γ2 ++ A0 :: x0) ++ A :: B → D :: B → D :: x2 ++ # P :: Γ4 = Γ2 ++ A0 :: (x0 ++ A :: B → D :: B → D :: x2) ++ # P :: Γ4). repeat rewrite <- app_assoc. auto.\n         rewrite H0.\n         assert ((Γ2 ++ # P → A0 :: x0) ++ A :: B → D :: B → D :: x2 ++ # P  :: Γ4 = Γ2 ++ # P → A0 :: (x0 ++ A :: B → D :: B → D :: x2) ++ # P :: Γ4). repeat rewrite <- app_assoc. auto.\n         rewrite H1. apply AtomImpL2Rule_I. apply AtomImpL2 in H0. pose (dlCons d0 DersNilF).\n         pose (derI (rules:=GL4ip_rules) (prems:=fun _ : Seq => False)\n         (ps:=[((Γ2 ++ A0 :: x0) ++ A :: B → D :: B → D :: x2 ++ # P :: Γ4, C)])\n         ((Γ2 ++ # P → A0 :: x0) ++ A :: B → D :: B → D :: x2 ++ # P :: Γ4, C) H0 d1). auto. }\n      { repeat destruct s. repeat destruct p ; subst.\n         assert (J2: derrec_height x < S (dersrec_height d)). lia.\n         assert (J3: derrec_height x = derrec_height x). reflexivity.\n         assert (J4: (Γ2 ++ A0 :: Γ3 ++ # P :: x1 ++  (A  → B) → D :: Γ1, C) = ((Γ2 ++ A0 :: Γ3 ++ # P :: x1) ++  (A  → B) → D :: Γ1, C)).\n         repeat rewrite <- app_assoc ; simpl ; repeat rewrite <- app_assoc ; auto.\n         pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n         assert (AtomImpL2Rule [((Γ2 ++ A0 :: Γ3 ++ # P :: x1) ++ A :: B → D :: B → D :: Γ1, C)]\n         ((Γ2 ++ # P → A0 :: Γ3 ++ # P :: x1) ++ A :: B → D :: B → D :: Γ1, C)). repeat rewrite <- app_assoc. simpl. repeat rewrite <- app_assoc.\n         apply AtomImpL2Rule_I. apply AtomImpL2 in H0. pose (dlCons d0 DersNilF).\n         pose (derI (rules:=GL4ip_rules) (prems:=fun _ : Seq => False)\n         (ps:=[((Γ2 ++ A0 :: Γ3 ++ # P :: x1) ++ A :: B → D :: B → D :: Γ1, C)])\n         ((Γ2 ++ # P → A0 :: Γ3 ++ # P :: x1) ++ A :: B → D :: B → D :: Γ1, C) H0 d1). auto. }\n (* AndImpL *)\n  * inversion H. subst. assert (J30: dersrec_height d = dersrec_height d). reflexivity.\n    pose (@dersrec_derrec_height (dersrec_height d) _ _ _ _ d J30). destruct s.\n    apply list_split_form in H2. destruct H2. repeat destruct s ; repeat destruct p ; subst.\n   + inversion e1.\n   +  assert (J2: derrec_height x < S (dersrec_height d)). lia.\n       assert (J3: derrec_height x = derrec_height x). reflexivity.\n       assert (J4: (((Γ0 ++ [ (A  → B) → D]) ++ x1) ++ A0 → B0 → C0 :: Γ3, C) = (Γ0 ++  (A  → B) → D :: x1 ++ A0 → B0 → C0 :: Γ3, C)). repeat rewrite <- app_assoc. auto.\n       pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n       assert (AndImpLRule [((Γ0 ++ A :: B → D :: B → D :: x1) ++ A0 → B0 → C0 :: Γ3, C)]\n       ((Γ0 ++ A :: B → D :: B → D :: x1) ++ (A0 ∧ B0) → C0 :: Γ3, C)). apply AndImpLRule_I.\n       repeat rewrite <- app_assoc in H0. apply AndImpL in H0.\n       pose (dlCons d0 DersNilF).\n       pose (derI (rules:=GL4ip_rules) (prems:=fun _ : Seq => False)\n       (ps:=[(Γ0 ++ A :: B → D :: B → D :: x1 ++ A0 → B0 → C0 :: Γ3, C)])\n       (Γ0 ++ A :: B → D :: B → D :: x1 ++ (A0 ∧ B0) → C0 :: Γ3, C) H0 d1). auto.\n   +  repeat destruct s. repeat destruct p ; subst.\n       assert (J2: derrec_height x < S (dersrec_height d)). lia.\n       assert (J3: derrec_height x = derrec_height x). reflexivity.\n       assert (J4: (Γ2 ++ A0 → B0 → C0 :: x0 ++  (A  → B) → D :: Γ1, C) = ((Γ2 ++ A0 → B0 → C0 :: x0) ++  (A  → B) → D :: Γ1, C)). repeat rewrite <- app_assoc. auto.\n       pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n       assert (AndImpLRule [((Γ2 ++ A0 → B0 → C0 :: x0) ++ A :: B → D :: B → D :: Γ1, C)]\n       ((Γ2 ++ (A0 ∧ B0) → C0 :: x0) ++ A :: B → D :: B → D :: Γ1, C)). repeat rewrite <- app_assoc. apply AndImpLRule_I.\n       apply AndImpL in H0. pose (dlCons d0 DersNilF).\n       pose (derI (rules:=GL4ip_rules) (prems:=fun _ : Seq => False)\n       (ps:=[((Γ2 ++ A0 → B0 → C0 :: x0) ++ A :: B → D :: B → D :: Γ1, C)])\n       ((Γ2 ++ (A0 ∧ B0) → C0 :: x0) ++ A :: B → D :: B → D :: Γ1, C) H0 d1). auto.\n  (* OrImpL *)\n  * inversion H. subst. assert (J30: dersrec_height d = dersrec_height d). reflexivity. simpl.\n     pose (@dersrec_derrec_height (dersrec_height d) _ _ _ _ d J30). destruct s.\n     apply list_split_form in H2. destruct H2. repeat destruct s ; repeat destruct p ; subst.\n   + inversion e1.\n   +  assert (J2: derrec_height x < S (dersrec_height d)). lia.\n       assert (J3: derrec_height x = derrec_height x). reflexivity.\n       assert (J4: (((Γ0 ++ [ (A  → B) → D]) ++ x1) ++ A0 → C0 :: Γ3 ++ B0 → C0 :: Γ4, C) = (Γ0 ++  (A  → B) → D ::  x1 ++ A0 → C0 :: Γ3 ++ B0 → C0 :: Γ4, C)).\n       repeat rewrite <- app_assoc. auto.\n       pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n       assert (OrImpLRule [((Γ0 ++ A :: B → D :: B → D :: x1) ++ A0 → C0 :: Γ3 ++ B0 → C0 :: Γ4, C)]\n       ((Γ0 ++ A :: B → D :: B → D :: x1) ++ (A0 ∨ B0) → C0 :: Γ3 ++ Γ4, C)). apply OrImpLRule_I.\n       repeat rewrite <- app_assoc in H0. apply OrImpL in H0.\n       pose (dlCons d0 DersNilF).\n       pose (derI (rules:=GL4ip_rules) (prems:=fun _ : Seq => False)\n       (ps:=[(Γ0 ++ A :: B → D :: B → D :: x1 ++ A0 → C0 :: Γ3 ++ B0 → C0 :: Γ4, C)])\n       (Γ0 ++ A :: B → D :: B → D :: x1 ++ (A0 ∨ B0) → C0 :: Γ3 ++ Γ4, C) H0 d1). auto.\n   +  repeat destruct s. repeat destruct p ; subst.\n       assert (J50: derrec_height x = derrec_height x). auto.\n       assert (J51: list_exch_L (Γ2 ++ A0 → C0 :: Γ3 ++ B0 → C0 :: Γ4, C) (Γ2 ++ A0 → C0 :: B0 → C0 :: x0 ++  (A  → B) → D :: Γ1, C)).\n       assert (Γ2 ++ A0 → C0 :: Γ3 ++ B0 → C0 :: Γ4 = (Γ2 ++ [A0 → C0]) ++ [] ++ Γ3 ++ [B0 → C0] ++ Γ4).\n       repeat rewrite <- app_assoc. auto. rewrite H0.\n       assert (Γ2 ++ A0 → C0 :: B0 → C0 :: x0 ++  (A  → B) → D :: Γ1 = (Γ2 ++ [A0 → C0]) ++ [B0 → C0] ++ Γ3 ++ [] ++ Γ4).\n       rewrite <- e1 ; repeat rewrite <- app_assoc ; auto. rewrite H1. apply list_exch_LI.\n       pose (GL4ip_hpadm_list_exch_L (derrec_height x) _ x J50 _ J51). destruct s.\n       assert (J2: derrec_height x1 < S (dersrec_height d)). lia.\n       assert (J3: derrec_height x1 = derrec_height x1). reflexivity.\n       assert (J4: (Γ2 ++ A0 → C0 :: B0 → C0 :: x0 ++  (A  → B) → D :: Γ1, C) = ((Γ2 ++ A0 → C0 :: B0 → C0 :: x0) ++  (A  → B) → D :: Γ1, C)). repeat rewrite <- app_assoc. auto.\n       pose (IH _ J2 _ x1 _ _ _ _ _ _ J3 J4).\n       assert (OrImpLRule [((Γ2 ++ A0 → C0 :: B0 → C0 :: x0) ++ A :: B → D :: B → D :: Γ1, C)]\n       ((Γ2 ++ (A0 ∨ B0) → C0 :: x0) ++ A :: B → D :: B → D :: Γ1, C)).\n       assert ((Γ2 ++ A0 → C0 :: B0 → C0 :: x0) ++ A :: B → D :: B → D :: Γ1 = Γ2 ++ A0 → C0 :: [] ++ B0 → C0 :: x0 ++ A :: B → D :: B → D :: Γ1).\n       repeat rewrite <- app_assoc ; simpl ; repeat rewrite <- app_assoc ; auto. rewrite H0.\n       assert ((Γ2 ++ (A0 ∨ B0) → C0 :: x0) ++ A :: B → D :: B → D :: Γ1 = Γ2 ++ (A0 ∨ B0) → C0 :: [] ++ x0 ++ A :: B → D :: B → D :: Γ1).\n       repeat rewrite <- app_assoc ; simpl ; repeat rewrite <- app_assoc ; auto. rewrite H1.\n       apply OrImpLRule_I.  apply OrImpL in H0. pose (dlCons d0 DersNilF).\n       pose (derI (rules:=GL4ip_rules) (prems:=fun _ : Seq => False)\n       (ps:=[((Γ2 ++ A0 → C0 :: B0 → C0 :: x0) ++ A :: B → D :: B → D :: Γ1, C)])\n       ((Γ2 ++ (A0 ∨ B0) → C0 :: x0) ++ A :: B → D :: B → D :: Γ1, C) H0 d1). auto.\n  (* ImpImpL *)\n * inversion H. subst. assert (J30: dersrec_height d = dersrec_height d). reflexivity.\n    pose (@dersrec_derrec2_height (dersrec_height d) _ _ _ _ _ d J30). repeat destruct s. simpl.\n    apply list_split_form in H2. destruct H2. repeat destruct s ; repeat destruct p ; subst.\n   + inversion e1. subst.\n      assert (J1: ImpRRule [(Γ0 ++ A:: B → D :: Γ1, B)] (Γ0 ++ B → D :: Γ1, A → B)). apply ImpRRule_I.\n      pose (ImpR_inv _ _ x J1).\n      assert (J2: wkn_L (B → D) (Γ0 ++ D :: Γ1, C) (Γ0 ++ B → D :: D :: Γ1, C)). apply wkn_LI.\n      pose (GL4ip_adm_wkn_L x0 J2).\n      assert (J3: wkn_L A (Γ0 ++ B → D :: D :: Γ1, C) ((Γ0 ++ A :: [B → D]) ++ D :: Γ1, C)). repeat rewrite <- app_assoc. apply wkn_LI.\n      pose (GL4ip_adm_wkn_L d1 J3).\n      assert (Γ0 ++ A :: B → D :: Γ1 = (Γ0 ++ A :: [B → D]) ++ Γ1). repeat rewrite <- app_assoc ; simpl ; auto. rewrite H0 in d0.\n      assert (J4: derrec_height d0 = derrec_height d0). auto.\n      assert (J5: ((Γ0 ++ [A; B → D]) ++ Γ1, B) = ((Γ0 ++ [A; B → D]) ++ Γ1, B)). auto.\n      pose (ImpL_adm _ _ _ _ _ _ _ _ J4 J5 d2). repeat rewrite <- app_assoc in d3 ; simpl in d3. auto.\n   +  assert (J2: derrec_height x < S (dersrec_height d)). lia.\n       assert (J3: derrec_height x = derrec_height x). reflexivity.\n       assert (J4: (((Γ0 ++ [ (A  → B) → D]) ++ x2) ++ B0 → C0 :: Γ3, A0 → B0) = (Γ0 ++  (A  → B) → D :: x2 ++ B0 → C0 :: Γ3, A0 → B0)).\n       repeat rewrite <- app_assoc. auto.\n       pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n       assert (J5: derrec_height x0 < S (dersrec_height d)). lia.\n       assert (J6: derrec_height x0 = derrec_height x0). reflexivity.\n       assert (J7: (((Γ0 ++ [ (A  → B) → D]) ++ x2) ++ C0 :: Γ3, C) = (Γ0 ++  (A  → B) → D :: x2 ++ C0 :: Γ3, C)).\n       repeat rewrite <- app_assoc. auto.\n       pose (IH _ J5 _ x0 _ _ _ _ _ _ J6 J7).\n       assert (ImpImpLRule [((Γ0 ++ A :: B → D :: B → D :: x2) ++ B0 → C0 :: Γ3, A0 → B0);((Γ0 ++ A :: B → D :: B → D :: x2) ++ C0 :: Γ3, C)]\n       ((Γ0 ++ A :: B → D :: B → D :: x2) ++ (A0 → B0) → C0 :: Γ3, C)). apply ImpImpLRule_I.\n       repeat rewrite <- app_assoc in H0. apply ImpImpL in H0.\n       pose (dlCons d1 DersNilF). pose (dlCons d0 d2).\n       pose (derI (rules:=GL4ip_rules) (prems:=fun _ : Seq => False)\n       (ps:=[(Γ0 ++ A :: B → D :: B → D :: x2 ++ B0 → C0 :: Γ3, A0 → B0); (Γ0 ++ A :: B → D :: B → D :: x2 ++ C0 :: Γ3, C)])\n       (Γ0 ++ A :: B → D :: B → D :: x2 ++ (A0 → B0) → C0 :: Γ3, C) H0 d3). auto.\n   +  repeat destruct s. repeat destruct p ; subst.\n       assert (J2: derrec_height x < S (dersrec_height d)). lia.\n       assert (J3: derrec_height x = derrec_height x). reflexivity.\n       assert (J4: (Γ2 ++ B0 → C0 :: x1 ++  (A  → B) → D :: Γ1, A0 → B0) = ((Γ2 ++ B0 → C0 :: x1) ++  (A  → B) → D :: Γ1, A0 → B0)). repeat rewrite <- app_assoc. auto.\n       pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n       assert (J5: derrec_height x0 < S (dersrec_height d)). lia.\n       assert (J6: derrec_height x0 = derrec_height x0). reflexivity.\n       assert (J7: (Γ2 ++ C0 :: x1 ++  (A  → B) → D :: Γ1, C) = ((Γ2 ++ C0 :: x1) ++  (A  → B) → D :: Γ1, C)).\n       repeat rewrite <- app_assoc. auto.\n       pose (IH _ J5 _ x0 _ _ _ _ _ _ J6 J7).\n       assert (ImpImpLRule [((Γ2 ++ B0 → C0 :: x1) ++ A :: B → D :: B → D :: Γ1, A0 → B0);((Γ2 ++ C0 :: x1) ++ A :: B → D :: B → D :: Γ1, C)]\n       ((Γ2 ++ (A0 → B0) → C0 :: x1) ++ A :: B → D :: B → D :: Γ1, C)). repeat rewrite <- app_assoc. apply ImpImpLRule_I.\n       apply ImpImpL in H0. pose (dlCons d1 DersNilF). pose (dlCons d0 d2).\n       pose (derI (rules:=GL4ip_rules) (prems:=fun _ : Seq => False)\n       (ps:=[((Γ2 ++ B0 → C0 :: x1) ++ A :: B → D :: B → D :: Γ1, A0 → B0); ((Γ2 ++ C0 :: x1) ++ A :: B → D :: B → D :: Γ1, C)])\n       ((Γ2 ++ (A0 → B0) → C0 :: x1) ++ A :: B → D :: B → D :: Γ1, C) H0 d3). auto.\n  (* BoxImpL *)\n * inversion X. subst. assert (J30: dersrec_height d = dersrec_height d). reflexivity.\n    pose (@dersrec_derrec2_height (dersrec_height d) _ _ _ _ _ d J30). repeat destruct s. simpl.\n    apply univ_gen_ext_splitR in X0. destruct X0. destruct s. repeat destruct p ; subst.\n    apply list_split_form in H. destruct H. repeat destruct s ; repeat destruct p ; subst.\n   + inversion e1.\n   +  apply univ_gen_ext_splitR in u. destruct u. destruct s. repeat destruct p ; subst.\n       apply univ_gen_ext_splitR in u. destruct u. destruct s. repeat destruct p ; subst.\n       inversion u2. subst. exfalso. assert (In ( (A  → B) → D) (((x1 ++  (A  → B) → D :: l) ++ x5) ++ x2)).\n       apply in_or_app ; left ; apply in_or_app ; left ; apply in_or_app ; right ; apply in_eq.\n       apply H1 in H. destruct H. inversion H. subst. inversion X0. subst.\n       assert (J5: derrec_height x0 < S (dersrec_height d)). lia.\n       assert (J6: derrec_height x0 = derrec_height x0). reflexivity.\n       assert (J7: (((Γ0 ++ [ (A  → B) → D]) ++ x4) ++ B0 :: Γ3, C) = (Γ0 ++  (A  → B) → D :: x4 ++ B0 :: Γ3, C)).\n       repeat rewrite <- app_assoc. auto.\n       pose (IH _ J5 _ x0 _ _ _ _ _ _ J6 J7).\n       assert (BoxImpLRule [(XBoxed_list (x1 ++ (top_boxes [A]) ++ x5 ++ x2) ++ [Box A0], A0);((Γ0 ++ A :: B → D :: B → D :: x4) ++ B0 :: Γ3, C)]\n       ((Γ0 ++ A :: B → D :: B → D :: x4) ++ Box A0 → B0 :: Γ3, C)).\n       { destruct (dec_is_boxedT A).\n          - apply BoxImpLRule_I ; auto. destruct i. subst. simpl. repeat rewrite <- app_assoc in H1 ; simpl in H1.\n            intro. intros. apply in_app_or in H. destruct H. apply H1. apply in_or_app ; auto.\n            inversion H. subst. exists x3. auto. apply in_app_or in H0 ; destruct H0. apply H1.\n            apply in_or_app ; right ; apply in_or_app ; auto. apply H1.\n            apply in_or_app ; right ; apply in_or_app ;  auto.\n            assert (top_boxes [A] = [A]). destruct i ; subst ; simpl ; auto.\n            rewrite H. simpl. repeat rewrite <- app_assoc ; simpl. repeat apply univ_gen_ext_combine ; auto.\n            apply univ_gen_ext_cons ; auto. repeat apply univ_gen_ext_extra ; try intro ; try destruct X1 ; try inversion H0 ; auto.\n            apply univ_gen_ext_combine ; auto.\n          - assert (top_boxes [A] = []).\n            destruct A ; auto ; exfalso ; apply f ; exists A ; auto. rewrite H ; auto. simpl.\n            apply BoxImpLRule_I ; simpl  ; repeat rewrite <- app_assoc in H1 ; simpl in H1 ; auto.\n            rewrite <- app_assoc ; simpl.\n            repeat apply univ_gen_ext_combine ; auto. repeat apply univ_gen_ext_extra ; auto.\n            intro. destruct X1. inversion H0. intro. destruct X1. inversion H0. apply univ_gen_ext_combine ; auto. }\n       assert (existsT2 (D2 : derrec GL4ip_rules (fun _ : Seq => False) (XBoxed_list (x1 ++ top_boxes [A] ++ x5 ++ x2) ++ [Box A0], A0)),\n       derrec_height D2 <= derrec_height x).\n       { destruct (dec_is_boxedT A).\n          - assert (top_boxes [A] = [A]). destruct i. subst ; auto. rewrite H. repeat rewrite XBox_app_distrib. repeat rewrite <- app_assoc.\n            assert (J1: derrec_height x = derrec_height x). auto.\n            pose (@GL4ip_list_wkn_L _ _ _ _ _ J1 (XBoxed_list [A])). destruct s.\n            assert (J2: derrec_height x3 = derrec_height x3). auto.\n            assert (J3: list_exch_L (XBoxed_list (((x1 ++ []) ++ x5) ++ x2) ++ XBoxed_list [A] ++ [Box A0], A0) (XBoxed_list x1 ++ XBoxed_list [A] ++ XBoxed_list x5 ++ XBoxed_list x2 ++ [Box A0], A0)).\n            repeat rewrite XBox_app_distrib. repeat rewrite <- app_assoc.\n            assert (XBoxed_list x1 ++ XBoxed_list [] ++ XBoxed_list x5 ++ XBoxed_list x2 ++ XBoxed_list [A] ++ [Box A0] = XBoxed_list x1 ++ [] ++ (XBoxed_list x5 ++ XBoxed_list x2) ++ XBoxed_list [A] ++ [Box A0]).\n            repeat rewrite <- app_assoc ; simpl ; auto. rewrite H0.\n            assert (XBoxed_list x1 ++ XBoxed_list [A] ++ XBoxed_list x5 ++ XBoxed_list x2 ++ [Box A0] = XBoxed_list x1 ++ XBoxed_list [A] ++ (XBoxed_list x5 ++ XBoxed_list x2) ++ [] ++ [Box A0]).\n            repeat rewrite <- app_assoc ; simpl ; auto. rewrite H3. apply list_exch_LI.\n            pose (GL4ip_hpadm_list_exch_L _ _ _ J2 _ J3). destruct s. exists x6. lia.\n          - assert (top_boxes [A] = []).\n            destruct A ; auto ; exfalso ; apply f ; exists A ; auto. rewrite H ; auto. simpl.\n            assert (x1 ++ x5 ++ x2 = ((x1 ++ []) ++ x5) ++ x2). repeat rewrite <- app_assoc ; simpl ; auto. rewrite H0.\n            exists x. lia. }\n       destruct X2. apply BoxImpL in X1.\n       pose (dlCons d0 DersNilF). pose (dlCons x3 d1). repeat rewrite <- app_assoc in X1.\n       pose (derI (rules:=GL4ip_rules) (prems:=fun _ : Seq => False)\n       (ps:=[(XBoxed_list (x1 ++ top_boxes [A] ++ x5 ++ x2) ++ [Box A0], A0); (Γ0 ++ A :: B → D :: B → D :: x4 ++ B0 :: Γ3, C)])\n       (Γ0 ++ A :: B → D :: B → D :: x4 ++ Box A0 → B0 :: Γ3, C) X1 d2). auto.\n   +  repeat destruct s. repeat destruct p ; subst.\n       apply univ_gen_ext_splitR in u0. destruct u0. destruct s. repeat destruct p ; subst.\n       inversion u1. subst. exfalso. assert (In ( (A  → B) → D) (x1 ++ x4 ++  (A  → B) → D :: l)).\n       apply in_or_app ; right ; apply in_or_app ; right ; apply in_eq.\n       apply H1 in H. destruct H. inversion H. subst.\n       assert (J5: derrec_height x0 < S (dersrec_height d)). lia.\n       assert (J6: derrec_height x0 = derrec_height x0). reflexivity.\n       assert (J7: (Γ2 ++ B0 :: x3 ++  (A  → B) → D :: Γ1, C) = ((Γ2 ++ B0 :: x3) ++  (A  → B) → D :: Γ1, C)).\n       repeat rewrite <- app_assoc. auto.\n       pose (IH _ J5 _ x0 _ _ _ _ _ _ J6 J7).\n       assert (BoxImpLRule [(XBoxed_list (x1 ++ x4 ++ (top_boxes [A]) ++ x5) ++ [Box A0], A0);((Γ2 ++ B0 :: x3) ++ A :: B → D :: B → D :: Γ1, C)]\n       ((Γ2 ++ Box A0 → B0 :: x3) ++ A :: B → D :: B → D :: Γ1, C)).\n       { destruct (dec_is_boxedT A).\n          - repeat rewrite <- app_assoc. simpl. apply BoxImpLRule_I ; auto. destruct i. subst. simpl.\n            intro. intros. apply in_app_or in H. destruct H. apply H1. apply in_or_app ; auto.\n            apply in_app_or in H ; destruct H. apply H1.\n            apply in_or_app ; right ; apply in_or_app ; auto. inversion H. subst. exists x2. auto. apply H1.\n            apply in_or_app ; right ; apply in_or_app ;  auto.\n            assert (match A with\n                     | Box A1 => [Box A1]\n                     | _ => []\n                     end = [A]). destruct i ; subst ; simpl ; auto.\n            rewrite H. simpl. repeat rewrite <- app_assoc ; simpl. repeat apply univ_gen_ext_combine ; auto.\n            apply univ_gen_ext_cons ; auto. repeat apply univ_gen_ext_extra ; try intro ; try destruct X1 ; try inversion H0 ; auto.\n          - assert (top_boxes [A] = []).\n            destruct A ; auto ; exfalso ; apply f ; exists A ; auto. rewrite H ; auto. simpl. repeat rewrite <- app_assoc ; simpl.\n            apply BoxImpLRule_I ; simpl  ; repeat rewrite <- app_assoc in H1 ; simpl in H1 ; auto.\n            repeat apply univ_gen_ext_combine ; auto. repeat apply univ_gen_ext_extra ; auto.\n            intro. destruct X1. inversion H0. intro. destruct X1. inversion H0. }\n       assert (existsT2 (D2 : derrec GL4ip_rules (fun _ : Seq => False) (XBoxed_list (x1 ++ x4 ++ top_boxes [A] ++ x5) ++ [Box A0], A0)),\n       derrec_height D2 <= derrec_height x).\n       { destruct (dec_is_boxedT A).\n          - assert (top_boxes [A] = [A]). destruct i. subst ; auto. rewrite H. repeat rewrite XBox_app_distrib. repeat rewrite <- app_assoc.\n            assert (J1: derrec_height x = derrec_height x). auto.\n            pose (@GL4ip_list_wkn_L _ _ _ _ _ J1 (XBoxed_list [A])). destruct s.\n            assert (J2: derrec_height x2 = derrec_height x2). auto.\n            assert (J3: list_exch_L (XBoxed_list (x1 ++ x4 ++ x5) ++ XBoxed_list [A] ++ [Box A0], A0) (XBoxed_list x1 ++ XBoxed_list x4 ++ XBoxed_list [A] ++ XBoxed_list x5 ++ [Box A0], A0)).\n            repeat rewrite XBox_app_distrib. repeat rewrite <- app_assoc.\n            assert (XBoxed_list x1 ++ XBoxed_list x4 ++ XBoxed_list x5 ++ XBoxed_list [A] ++ [Box A0] = (XBoxed_list x1 ++ XBoxed_list x4) ++ [] ++ XBoxed_list x5 ++ XBoxed_list [A] ++ [Box A0]).\n            repeat rewrite <- app_assoc ; simpl ; auto. rewrite H0.\n            assert (XBoxed_list x1 ++ XBoxed_list x4 ++ XBoxed_list [A] ++ XBoxed_list x5 ++ [Box A0] = (XBoxed_list x1 ++ XBoxed_list x4) ++ XBoxed_list [A] ++ XBoxed_list x5 ++ [] ++ [Box A0]).\n            repeat rewrite <- app_assoc ; simpl ; auto. rewrite H3. apply list_exch_LI.\n            pose (GL4ip_hpadm_list_exch_L _ _ _ J2 _ J3). destruct s. exists x6. lia.\n          - assert (top_boxes [A] = []).\n            destruct A ; auto ; exfalso ; apply f ; exists A ; auto. rewrite H ; auto. simpl. exists x. lia. }\n       destruct X2. apply BoxImpL in X1.\n       pose (dlCons d0 DersNilF). pose (dlCons x2 d1). repeat rewrite <- app_assoc in X1. repeat rewrite <- app_assoc. simpl. simpl in X1.\n       assert (match A with\n                                  | Box A => [Box A]\n                                  | _ => []\n                                  end = top_boxes [A]). simpl. auto. rewrite H in X1. repeat rewrite <- app_assoc in d2.\n       pose (derI (rules:=GL4ip_rules) (prems:=fun _ : Seq => False)\n       (ps:=[(XBoxed_list (x1 ++ x4 ++ top_boxes [A] ++ x5) ++ [Box A0], A0); (Γ2 ++ B0 :: x3 ++ A :: B → D :: B → D :: Γ1, C)])\n       (Γ2 ++ Box A0 → B0 :: x3 ++ A :: B → D :: B → D :: Γ1, C) X1 d2). auto.\n  (* GLR *)\n  * inversion X. subst. simpl. apply univ_gen_ext_splitR in X0. destruct X0. destruct s. repeat destruct p ; subst.\n    inversion u0. subst. exfalso. assert (In ( (A  → B) → D) (x ++  (A  → B) → D :: l)). apply in_or_app ; right ; apply in_eq.\n    apply H1 in H. destruct H. inversion H. subst.\n    assert (GLRRule [(XBoxed_list (x ++ x0) ++ [Box A0], A0)] (Γ0 ++ Γ1, Box A0)). apply GLRRule_I ; auto.\n    apply univ_gen_ext_combine ; auto. apply GLR in X1.\n    pose (derI (rules:=GL4ip_rules) (prems:=fun _ : Seq => False)\n    (ps:=[(XBoxed_list (x ++ x0) ++ [Box A0], A0)]) (Γ0 ++ Γ1, Box A0) X1 d).\n    assert (J1: wkn_L (B → D) (Γ0 ++ Γ1, Box A0) (Γ0 ++ B → D :: Γ1, Box A0)). apply wkn_LI.\n    pose (@GL4ip_adm_wkn_L _ d0 _ _ J1).\n    assert (J2: wkn_L (B → D) (Γ0 ++ B → D :: Γ1, Box A0) (Γ0 ++ B → D :: B → D :: Γ1, Box A0)). apply wkn_LI.\n    pose (@GL4ip_adm_wkn_L _ d1 _ _ J2).\n    assert (J3: wkn_L A (Γ0 ++ B → D :: B → D :: Γ1, Box A0) (Γ0 ++ A :: B → D :: B → D :: Γ1, Box A0)). apply wkn_LI.\n    pose (@GL4ip_adm_wkn_L _ d2 _ _ J3). auto.\nQed.\n\n\n\n\n\n\n\n", "meta": {"author": "ianshil", "repo": "PhD_thesis", "sha": "af4940397f0d95c1d63a196ab29a3b9f715d9f4e", "save_path": "github-repos/coq/ianshil-PhD_thesis", "path": "github-repos/coq/ianshil-PhD_thesis/PhD_thesis-af4940397f0d95c1d63a196ab29a3b9f715d9f4e/Cut_Elim_iGLS/GL4ip_inv_ImpImpL_L.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.29449895007702226}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.ZArith.ZArith.\nRequire Import bedrock2.Semantics.\nRequire Import bedrock2.Syntax.\nRequire Import bedrock2.ProgramLogic.\nRequire Import bedrock2.WeakestPrecondition.\nRequire Import bedrock2.WeakestPreconditionProperties.\nRequire Import coqutil.Word.Interface.\nRequire Import coqutil.Word.Properties.\nRequire Import coqutil.Word.Bitwidth.\nRequire Import coqutil.Map.Interface.\nRequire Import coqutil.Tactics.letexists.\nRequire Import coqutil.Tactics.Tactics.\nRequire Import Cava.Util.Tactics.\nLocal Open Scope Z_scope.\n\n(* Proofs about cmd.while *)\n\nSection Proofs.\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: 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  Fixpoint repeat_logic_step\n           (logic : trace -> mem -> locals ->\n                    (trace -> mem -> locals -> Prop) -> Prop)\n           (n : nat) post : trace -> mem -> locals -> Prop :=\n    match n with\n    | O => post\n    | S n => fun t m l => logic t m l (repeat_logic_step logic n post)\n    end.\n\n  Lemma unroll_while functions conde body t m l\n        (iterations : nat)\n        (post : trace -> mem -> locals -> Prop) :\n    repeat_logic_step\n      (fun t m l post =>\n         exists cond,\n           dexpr m l conde cond\n           /\\ word.unsigned cond <> 0\n           /\\ cmd (call functions) body t m l post)\n      iterations (fun t m l =>\n                    exists cond,\n                      dexpr m l conde cond\n                      /\\ word.unsigned cond = 0\n                      /\\ post t m l) t m l ->\n    cmd (call functions) (cmd.while conde body) t m l post.\n  Proof.\n    lazymatch goal with\n      |- repeat_logic_step ?logic _ ?post _ _ _ -> _ =>\n      set (step:=logic);\n        set (P:=post)\n    end.\n    intros. exists nat, lt, (fun i => repeat_logic_step step i P).\n    ssplit.\n    { exact lt_wf. }\n    { eauto. }\n    { intro i. destruct i; cbn [repeat_logic_step].\n      { (* i=0 case (contradiction) *)\n        subst P. repeat straightline.\n        eexists; ssplit; eauto; congruence. }\n      { (* i <> 0 case *)\n        subst step. repeat straightline.\n        eexists; ssplit; eauto; try congruence; [ ].\n        repeat straightline.\n        eapply Proper_cmd; [ apply Proper_call | | eassumption ].\n        repeat intro. exists i. ssplit; eauto. } }\n  Qed.\n\n  (* This lemma handles conditional statements without breaking the entire\n     remainder of the function into two goals *)\n  Lemma cond_nosplit functions conde ct cf cnext t m l\n        (post post_cond : trace -> mem -> locals -> Prop) :\n    cmd (call functions) (cmd.cond conde ct cf) t m l post_cond ->\n    (forall t m l, post_cond t m l -> cmd (call functions) cnext t m l post) ->\n    cmd (call functions) (cmd.seq (cmd.cond conde ct cf) cnext) t m l post.\n  Proof.\n    cbn [cmd cmd_body]. intros; logical_simplify.\n    eexists; ssplit; intros; eauto; [ | ].\n    { eapply Proper_cmd; [ apply Proper_call | | solve [eauto] ].\n      repeat intro. eauto. }\n    { eapply Proper_cmd; [ apply Proper_call | | solve [eauto] ].\n      repeat intro. eauto. }\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/WhileProperties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.29449895007702226}}
{"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_destroy.\nRequire Import TableDataOpsIntro.LowSpecs.data_destroy.\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       find_lock_granule_spec\n       pgte_write_spec\n       granule_put_spec\n       granule_memzero_spec\n       granule_set_state_spec\n       granule_unlock_spec\n       buffer_unmap_spec\n    .\n\n  Lemma data_destroy_spec_exists:\n    forall habd habd'  labd g_rd map_addr res\n      (Hspec: data_destroy_spec g_rd map_addr habd = Some (habd', res))\n      (Hrel: relate_RData habd labd),\n    exists labd', data_destroy_spec0 g_rd map_addr labd = Some (labd', res) /\\ relate_RData habd' labd'.\n  Proof.\n    assert(ne51: 5 <> 1) by (red; intro T; inv T).\n    Local Opaque peq ptr_eq.\n    intros. destruct Hrel. inv id_rdata. destruct g_rd.\n    unfold data_destroy_spec, data_destroy_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. simpl in *.\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      assert(nez: llt_gidx <> data_gidx) 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; repeat simpl_field; repeat swap_fields; simpl; repeat solve_table_range).\n      repeat (solve_bool_range; grewrite). repeat (rewrite ZMap.gss in * ); simpl in *.\n      grewrite. simpl in *. repeat (repeat solve_table_range; solve_bool_range; grewrite).\n      repeat (grewrite; try simpl_htarget; repeat simpl_field; repeat swap_fields; simpl).\n      solve_bool_range. grewrite. repeat (try solve_peq; try solve_ptr_eq; simpl).\n      extract_if. reflexivity. grewrite.\n      eexists; split. reflexivity. constructor.\n      repeat (try rewrite (zmap_comm _ _ ne51);\n              try rewrite (zmap_comm _ _ nez)).\n      bool_rel. replace (3 * 72057594037927936) with 216172782113783808 by reflexivity.\n      grewrite; rewrite <- Prop0, <- C40.\n      repeat (repeat simpl_field; repeat swap_fields; repeat simpl_field; simpl_htarget; simpl).\n      reflexivity.\n    - repeat destruct_con. simpl_query_oracle. simpl in *. extract_prop_dec.\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 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; repeat simpl_field; repeat swap_fields; simpl; repeat solve_table_range).\n      repeat (solve_bool_range; grewrite). repeat (rewrite ZMap.gss in * ); simpl in *.\n      grewrite. simpl in *. repeat (repeat solve_table_range; solve_bool_range; grewrite).\n      repeat (grewrite; try simpl_htarget; repeat simpl_field; repeat swap_fields; simpl).\n      inversion Hspec. clear Hspec. eexists; split.  reflexivity. constructor.\n      repeat rewrite (zmap_comm _ _ ne51).\n      bool_rel. replace (3 * 72057594037927936) with 216172782113783808 by reflexivity.\n      clear H0 H1. grewrite; rewrite <- Prop0, <- C33. repeat simpl_field.\n      repeat swap_fields; repeat simpl_field; simpl_htarget; simpl. 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_destroy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.29449895007702226}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.floyd.library.\nRequire Import VST.progs.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\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  rewrite sepcon_comm.\n  apply derives_refl.\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. 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": "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_object.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.29449895007702226}}
{"text": "Require Import Mtac2.Mtac2.\nImport T.\n\nExample test_selector1 : forall n, n >= 0.\nMProof.\n  destructn 0 &> S.first (apply le_0_n).\nAbort.\n\nExample test_selector2 : forall n, n >= 0.\nMProof.\n  destructn 0 &> S.rev &> S.last (apply le_0_n).\nAbort.\n\nExample test_selector3 : forall n, n >= 0.\nMProof.\n  destructn 0 |1> apply le_0_n.\nAbort.\n\nExample test_selector4 : forall n, n >= 0.\nMProof.\n  destructn 0 &> S.rev l> apply le_0_n.\nAbort.\n\nExample test_selector5 : forall n, n >= 0.\nMProof.\n  destructn 0 &> S.rev |2> apply le_0_n.\nAbort.\n\nExample test_selector6 : forall n, n >= 0.\nMProof.\n  (destructn 0 &> S.rev |2> apply le_0_n) |1> idtac.\nAbort.\n\nExample test_selector7 : forall n, n >= 0.\nMProof.\n  Fail (destructn 0 &> S.rev |2> apply le_0_n) |2> print_goal.\nAbort.\n", "meta": {"author": "Mtac2", "repo": "Mtac2", "sha": "d16c2e682d5ab18ed77b13b4fd60a42a65c4f958", "save_path": "github-repos/coq/Mtac2-Mtac2", "path": "github-repos/coq/Mtac2-Mtac2/Mtac2-d16c2e682d5ab18ed77b13b4fd60a42a65c4f958/tests/selectors.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.29447342047348296}}
{"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.\nFrom mathcomp Require Import div path tuple.\nRequire Import Init_ext ssrZ ZArith_ext String_ext Max_ext.\nRequire Import machine_int seq_ext ssrnat_ext tuple_ext path_ext.\nRequire order finmap.\nImport MachineInt.\n\nRequire Import C_types C_types_fp C_value C_expr C_expr_equiv.\n\nLocal Close Scope Z_scope.\nLocal Open Scope C_types_scope.\nLocal Open Scope C_value_scope.\nLocal Open Scope C_expr_scope.\nLocal Open Scope machine_int_scope.\n\n(** ground arithmetic expressions *)\n\nLemma cat_nil {A: Type}: forall (l1: seq A) l2, l1 ++ l2 = nil -> l1 = nil /\\ l2 = nil.\nelim => //=.\nDefined.\n\nDefinition ground_exp  {g} {sigma : g.-env} {t : g.-typ} :\n  forall (e : exp sigma t) (H: vars e = nil), t.-phy.\ninduction e; simpl.\n- done.\n- move => H; exact p.\n- move => /cat_nil [] H1 H2.\n  exact ([ bop_n _ t b ([ IHe1 H1 ]c) ([ IHe2 H2 ]c) ]_ (store0 sigma)).\n- move => H.\n  exact (eval (store0 sigma) (bopk_n _ t b [IHe H ]c n)).\n- move => /cat_nil [] H1 H2.\n  exact (eval (store0 sigma) (bop_r _ t b ([ IHe1 H1 ]c) ([ IHe2 H2 ]c))).\n- move => /cat_nil [] H1 H2.\n  exact (eval (store0 sigma) ([ IHe1 H1 ]c \\+ [ IHe2 H2 ]c)).\n- move => H.\n  exact (eval (store0 sigma) (safe_cast _ t t' [IHe H ]c i)).\n- move => H.\n  exact (eval (store0 sigma) (unsafe_cast _ t t' [IHe H ]c i)).\n- move => H'.\n  exact (eval (store0 sigma) (fldp _ f [IHe H' ]c H e0)).\n- move => /cat_nil [] H1 H2.\n  exact (eval (store0 sigma) ([ IHe1 H1 ]c \\= [ IHe2 H2 ]c)).\n- move => /cat_nil [] H1 / cat_nil [] H2 H3.\n  exact (eval (store0 sigma) (ifte_e _ t ([ IHe1 H1 ]c) ([ IHe2 H2 ]c) ([ IHe3 H3 ]c))).\nDefined.\nGlobal Opaque ground_exp.\n\nNotation \"'[' e ']ge'\" := (@ground_exp _ _ _ e (Logic.eq_refl _)) (at level 9, only parsing) : C_expr_scope.\nNotation \"'[' e ']ge'\" := (ground_exp e _) (at level 9, format \"'[' [  e  ]ge ']'\"): C_expr_scope.\n\nLemma ground_exp_sem {g} {ts : g.-env} (s : store ts) {ty : g.-typ} :\n  forall (e : exp ts ty) (H : vars e = nil), [ e ]_s = ground_exp e H.\nTransparent ground_exp.\ninduction e => //=.\n- move/cat_nil => [] H1 H2.\n  by rewrite -(IHe1 H1) -(IHe2 H2).\n- move => H; by rewrite -(IHe H).\n- move/cat_nil => [] H1 H2.\n  by rewrite -(IHe1 H1) -(IHe2 H2).\n- move/cat_nil => [] H1 H2.\n  by rewrite -(IHe1 H1) -(IHe2 H2).\n- move => H; by rewrite -(IHe H).\n- move => H; by rewrite -(IHe H).\n- move => H'; by rewrite -(IHe H').\n- move/cat_nil => [] H1 H2.\n  by rewrite -(IHe1 H1) -(IHe2 H2).\n- move/cat_nil => [] H1 /cat_nil [] H2 H3.\n  by rewrite -(IHe1 H1) -(IHe2 H2) -(IHe3 H3).\nOpaque ground_exp.\nQed.\n\nLemma ground_exp_c_inj {g} {sigma : g.-env} {t} (pv1 pv2 : t.-phy) H1 H2 :\n  ground_exp ([ pv1 ]c : exp sigma t) H1 = ground_exp ([ pv2 ]c : exp sigma t) H2 ->\n  pv1 = pv2.\nProof. done. Qed.\n\nLemma ge_cast_sint_cst_8c g (sigma : g.-env) (a : int 8) H :\n  ground_exp ((int) ([ a ]pc : exp sigma (g.-ityp: uchar)) ) H = [ zext 24 a ]p.\nProof.\nTransparent eval beval.\nrewrite /si32_of_phy /=.\nby apply mkPhy_irrelevance.\nOpaque eval beval.\nQed.\n\nLemma ge_cast_sint_cst_sint g (sigma : g.-env) (pv : (g.-ityp: sint).-phy) H :\n  ground_exp ((int) ([ pv ]c : exp sigma (g.-ityp: sint))) H = pv.\nProof. done. Qed.\n\n(* similar to ge_cst_e but in ge_cst_e c is a phyval *)\nLemma sequiv_ge {g} {ts : g.-env} ty (e : exp ts ty) (H : vars e = nil) :\n  [ ground_exp e H ]c =s e.\nProof.\nTransparent eval.\nmove=> s /=.\nby rewrite ground_exp_sem.\nOpaque eval.\nQed.\n\nLemma ge_cst_e {g sigma} {ty : g.-typ} (pv : ty.-phy) H : @ground_exp _ sigma _ [ pv ]c H = pv.\nProof. done. Qed.\n\nLemma i32_ge_s_cst_e {g} {sigma : g.-env} n H :\n  si32<=phy (ground_exp ([ n ]sc : exp sigma _) H) = Z2s 32 n.\nProof. by rewrite ge_cst_e (si32_of_phy_sc _ _ (store0 sigma)). Qed.\n\nLemma i8_ge_8_cst_e {g} sigma z H :\n  i8<=phy (@ground_exp g sigma _ [ z ]pc H) = z.\nProof. by rewrite ge_cst_e phy_of_ui8K. Qed.\n\nLocal Open Scope zarith_ext_scope.\n\nLemma sequiv_s2Z_si32_of_phy {g} {ts : g.-env} e H :\n  ([s2Z (si32<=phy (ground_exp e H) )]sc : exp ts _ ) =s e.\nProof.\nmove=> s.\nrewrite (ground_exp_sem _ e H).\nset X := ground_exp e H.\ndestruct X.\nunfold si32_of_phy; simpl.\nmove: (oi32_of_i8_Some _ Hphy) => [] x Hx.\nrewrite Hx /= /phy_of_si32.\napply mkPhy_irrelevance => /=.\nrewrite -(oi32_of_i8_bij _ _ Hx).\nTransparent eval.\nby rewrite /= Z2s_s2Z.\nOpaque eval.\nQed.\n\nLemma s2Z_ge_s_cst_e {g sigma} z H : (- 2 ^^ 31 <= z < 2 ^^ 31)%Z ->\n  s2Z (si32<=phy (@ground_exp g sigma _ [ z ]sc H)) = z.\nProof. move=> Hz. by rewrite i32_ge_s_cst_e Z2sK. Qed.\n\nLemma u2Z_ge_s_cst_e {g sigma} z H : (0 <= z < 2 ^^ 31)%Z ->\n  u2Z (si32<=phy (@ground_exp g sigma _ [ z ]sc H)) = z.\nProof.\ncase=> Hz0 Hz1.\nrewrite i32_ge_s_cst_e-s2Z_u2Z_pos.\nrewrite Z2sK //; split => //; exact: (@leZ_trans Z0).\nrewrite Z2sK //; split => //; exact: (@leZ_trans Z0).\nQed.\n\nLemma si32_of_phy_gb_add_e {g} {sigma : g.-env} (a b : exp sigma _) H Ha Hb :\n  si32<=phy (ground_exp (a \\+ b) H) =\n  si32<=phy (ground_exp a Ha) `+ si32<=phy (ground_exp b Hb).\nProof.\nby rewrite -(ground_exp_sem (store0 sigma)) si32_of_phy_binop_ne 2!(ground_exp_sem (store0 sigma)).\nQed.\n\nLemma si32_of_phy_gb_or_e {g} {sigma : g.-env} (a b : exp sigma _) H Ha Hb :\n  si32<=phy (ground_exp (a \\| b) H) =\n  si32<=phy (ground_exp a Ha) `|` si32<=phy (ground_exp b Hb).\nProof.\nby rewrite -(ground_exp_sem (store0 sigma)) si32_of_phy_binop_ne 2!(ground_exp_sem (store0 sigma)).\nQed.\n\n(* NB: generaliser? *)\nLemma sint_shl_e_to_i32_ge g (sigma : g.-env) (a : int 8) H :\n  si32<=phy (ground_exp ((int) ([ a ]pc : exp sigma (g.-ityp: uchar)) \\<< [ 8 ]sc : exp sigma _) H) =\n  zext 16 a `|| Z2u 8 0.\nProof.\nTransparent eval beval.\nrewrite /si32_of_phy /= i8_of_i32Ko /= !i8_of_i32K /= Z2s_Z2u_k // Z2uK //.\napply u2Z_inj.\nrewrite (@u2Z_shl _ _ _ 8) //.\n- by rewrite (u2Z_concat (zext 16 a)) Z2uK // !u2Z_zext addZ0 (u2Z_zext (8 * (4 - 1)) a).\n- rewrite (u2Z_zext (8 * (4 - 1)) a).\n  by apply max_u2Z.\nOpaque eval beval.\nQed.\n\nLocal Open Scope Z_scope.\n\nLemma i8_of_phy_ifte {g sigma} (a b c d : _) H :\n  i8<=phy (@ground_exp g sigma _ ([ a ]c \\<= [ b ]c \\? [ c ]c \\: [ d ]c) H) =\n  if Z<=u (i8<=phy a) <=? Z<=u (i8<=phy b) then i8<=phy c else i8<=phy d.\nProof.\nTransparent eval.\nrewrite -(ground_exp_sem (store0 sigma)) /=.\ndestruct a as [a Ha] => //=.\nhave Ha' : size a = 1%nat by rewrite Ha sizeof_ityp.\nhave Ha'Ha : Ha' = Ha by apply eq_irrelevance.\nsubst Ha.\ndestruct a as [|a []] => //=.\ndestruct b as [b Hb] => //=.\nhave Hb' : size b = 1%nat by rewrite Hb sizeof_ityp.\nhave Hb'Hb : Hb' = Hb by apply eq_irrelevance.\nsubst Hb.\ndestruct b as [|b []] => //=.\nset a1 := Z<=u _.\nset b1 := Z<=u _.\ncase: ifP.\n  rewrite /is_zero.\n  case: ifP => // _ /eqP.\n  case.\n  move/int_break_inj => abs.\n  exfalso.\n  lapply abs => //.\n  by apply Z2u_dis.\ncase: ifP => // _.\nby rewrite is_zero_0.\nOpaque eval.\nQed.\n\nLocal Close Scope Z_scope.\n\n(** ground boolean expressions *)\n\nLemma ground_bexp_helper1 {g} {sigma : g.-env} (e : exp sigma (ityp: uint)) : bvars (exp2bexp sigma e) = nil -> vars e = nil.\nProof. done. Qed.\n\nLemma ground_bexp_helper2 {g} {sigma : g.-env} (b : bexp sigma) : bvars (bneg sigma b) = nil -> bvars b = nil.\nProof. done. Qed.\n\nFixpoint ground_bexp {g} {sigma : g.-env} (b : bexp sigma) : bvars b = nil -> bool :=\nmatch b as b0 return bvars b0 = nil -> bool with\n| exp2bexp e => fun H => ~~ is_zero (ground_exp e (ground_bexp_helper1 e H))\n| bneg b' => fun H => ~~ ground_bexp b' (ground_bexp_helper2 b' H)\nend.\nGlobal Opaque ground_bexp.\n\nLemma gb_bneg {g} {sigma: g.-env} (b : bexp sigma) H : ground_bexp (\\~b b) H = ~~ ground_bexp b H.\nProof.\ncongr (~~ _ _ _ _ _).\nby apply eq_irrelevance.\nQed.\n\nLemma ground_bexp_sem  {g} {sigma : g.-env} (s : store sigma) :\n  forall (b : bexp sigma) (H : bvars b = nil), [ b ]b_ s = ground_bexp b H.\nProof.\nTransparent beval.\ninduction b => //=.\n- move => H.\n  rewrite ground_exp_sem /=.\n  congr (~~ _ [ _ ]ge).\n  by apply eq_irrelevance.\n- move => H; by rewrite IHb gb_bneg.\nOpaque beval.\nQed.\n\nNotation \"'[' e ']gb'\" := (@ground_bexp _ _ e erefl) (at level 9, only parsing) : C_expr_scope.\nNotation \"'[' e ']gb'\" := (ground_bexp e _) (at level 9): C_expr_scope.\n\nSection ground_bexp_prop.\n\nVariables (g : wfctxt) (sigma : g.-env).\n\nLemma bneg_0uc H : @ground_bexp _ sigma (\\~b \\b [ 0 ]uc) H.\nProof.\nTransparent beval.\nby rewrite -(ground_bexp_sem (store0 sigma)) /= is_zero_0.\nOpaque beval.\nQed.\n\nLemma oneuc H : @ground_bexp _ sigma ( \\b [ 1 ]uc ) H.\nProof.\nTransparent beval.\nby rewrite -(ground_bexp_sem (store0 sigma)) /= not_is_zero_1.\nOpaque beval.\nQed.\n\nLemma gb_eq_p {t} (a b : exp sigma (:* t)) H H1 H2 :\n  ground_bexp ( \\b a \\= b ) H = (ground_exp a H1 == ground_exp b H2).\nProof.\nby rewrite -(ground_bexp_sem (store0 sigma) _ H) beval_eq_p_eq -!(ground_exp_sem (store0 _)).\nQed.\n\nLemma and_gb (e1 e2 : exp sigma (ityp: uint)) H H1 H2 :\n  ground_bexp (\\b e1 \\&& e2) H = ground_bexp (\\b e1) H1 && ground_bexp (\\b e2) H2.\nProof.\nTransparent eval beval.\nrewrite -!(ground_bexp_sem (store0 sigma)) /=.\nmove He1 : ( [ e1 ]_(store0 _) ) => [he1 Hhe1].\nmove He2 : ( [ e2 ]_(store0 _) ) => [he2 Hhe2].\nset tmp1 := eq_ind_r _ _ _. rewrite (_ : tmp1 = Hhe1); last by apply eq_irrelevance.\nset tmp2 := eq_ind_r _ _ _. rewrite (_ : tmp2 = Hhe2); last by apply eq_irrelevance.\ncase: ifP => [Hcase | /negbT].\n  rewrite is_zero_0; symmetry; apply/negbTE.\n  rewrite negb_and 2!negbK /is_zero /=.\n  apply/orP.\n  case/orP : Hcase => /eqP Hcase; [left | right].\n    apply/eqP.\n    apply mkPhy_irrelevance => /=.\n    symmetry; apply i32_of_i8_bij with Hhe1.\n    apply u2Z_inj.\n    by rewrite Hcase Z2uK.\n  apply/eqP.\n  apply mkPhy_irrelevance => /=.\n  symmetry; apply i32_of_i8_bij with Hhe2.\n  apply u2Z_inj; by rewrite Hcase Z2uK.\nrewrite not_is_zero_1 negb_or; case/andP => Ha Hb.\nsymmetry; apply/andP; split.\n  move: Ha; apply contra.\n  rewrite /is_zero; case/eqP => ?; subst he1.\n  by rewrite i8_of_i32K Z2uK.\nmove: Hb; apply contra.\nrewrite /is_zero; case/eqP => ?; subst he2.\nby rewrite i8_of_i32K Z2uK.\nOpaque eval beval.\nQed.\n\nLemma and_8c (a b : int 8) H :\n  ground_exp ([ a ]pc \\& [ b ]pc : exp sigma (g.-ityp: uchar)) H =\n  ground_exp ([ a `& b ]pc : exp sigma _) H.\nProof. by []. Qed.\n\nEnd ground_bexp_prop.\n\nSection ground_bexp_eq.\n\nVariables (g : wfctxt) (sigma : g.-env) (t : integral) (a b : exp sigma (ityp: t)).\nHypotheses (Ha : vars a = nil) (Hb : vars b = nil).\n\nLemma gb_eq_e H : ground_bexp (\\b a \\= b) H = (ground_exp a Ha == ground_exp b Hb).\nProof. by rewrite -(ground_bexp_sem (store0 _) _ H) beval_eq_e_eq -!(ground_exp_sem (store0 _)). Qed.\n\nLemma gb_neq H H' : ground_bexp (\\b a \\!= b) H = ~~ ground_bexp (\\b a \\= b) H'.\nProof. by rewrite -!(ground_bexp_sem (store0 sigma)) beval_neq_not_eq beval_eq_e_eq. Qed.\n\nLemma gb_bneg_bop_r_lt H H' : ground_bexp (\\~b \\b a \\< b) H = ground_bexp (\\b a \\>= b) H'.\nProof. by rewrite -!(ground_bexp_sem (store0 sigma)) CgeqNlt. Qed.\n\nLemma gb_bneg_bop_r_ge H H' : ground_bexp (\\~b \\b a \\>= b) H = ground_bexp (\\b a \\< b) H'.\nProof. by rewrite -!(ground_bexp_sem (store0 sigma)) CgeqNlt bnegK. Qed.\n\nLemma gb_bneg_bop_r_gt H H' : ground_bexp (\\~b \\b a \\> b) H = ground_bexp (\\b a \\<= b) H'.\nProof. by rewrite -!(ground_bexp_sem (store0 sigma)) -CleqNgt. Qed.\n\nLemma gb_ge_lt H H' : ground_bexp (\\b a \\>= b) H = ground_bexp (\\b b \\<= a) H'.\nProof. by rewrite -!(ground_bexp_sem (store0 sigma)) sequiv_ge_sym. Qed.\n\nEnd ground_bexp_eq.\n\nLocal Open Scope zarith_ext_scope.\nLocal Open Scope Z_scope.\n\nSection ground_bexp_Zlt_Zle.\n\nVariables (g : wfctxt) (sigma : g.-env) (e1 e2 : exp sigma (ityp: sint)).\nHypotheses (H1 : vars e1 = nil) (H2 : vars e2 = nil).\n\n(* NB: lower bounds could be generalized to - 2 ^^ 31 *)\nLemma le_n_gb H : 0 <= Z<=s (si32<=phy (ground_exp e1 H1)) < 2 ^^ 31 ->\n  0 <= Z<=s (si32<=phy (ground_exp e2 H2)) < 2 ^^ 31 ->\n  ground_bexp (\\b e1 \\<= e2) H -> si32<=phy (ground_exp e1 H1) `<= si32<=phy (ground_exp e2 H2).\nProof.\nmove=> K1 K2.\nrewrite -!(ground_bexp_sem (store0 sigma)) -!(ground_exp_sem (store0 sigma)).\nmove/bop_re_le_Zle => K.\napply Zle2le_n.\ncase: K1; move/s2Z_u2Z_pos => K1 _.\nrewrite -!(ground_exp_sem (store0 sigma)) in K1.\ncase: K2; move/s2Z_u2Z_pos => K2 _.\nrewrite -!(ground_exp_sem (store0 sigma)) in K2.\ncongruence.\nQed.\n\nLemma lt_n_gb H : 0 <= Z<=s (si32<=phy (ground_exp e1 H1)) < 2 ^^ 31 ->\n  0 <= Z<=s (si32<=phy (ground_exp e2 H2)) < 2 ^^ 31 ->\n  ground_bexp (\\b e1 \\< e2) H -> si32<=phy (ground_exp e1 H1) `< si32<=phy (ground_exp e2 H2).\nProof.\nmove=> K1 K2.\nrewrite -!(ground_bexp_sem (store0 sigma)) -!(ground_exp_sem (store0 sigma)).\nmove/bop_re_lt_Zlt =>  K.\napply Zlt2lt_n.\ncase: K1; move/s2Z_u2Z_pos => K1 _.\nrewrite -!(ground_exp_sem (store0 sigma)) in K1.\ncase: K2; move/s2Z_u2Z_pos => K2 _.\nrewrite -!(ground_exp_sem (store0 sigma)) in K2.\ncongruence.\nQed.\n\nLemma Zlt_gb H : ground_bexp (\\b e1 \\< e2) H ->\n  0 <= Z<=s (si32<=phy (ground_exp e1 H1)) < 2 ^^ 31 ->\n  0 <= Z<=s (si32<=phy (ground_exp e2 H2)) < 2 ^^ 31 ->\n  Z<=s (si32<=phy (ground_exp e1 H1)) < Z<=s (si32<=phy (ground_exp e2 H2)).\nProof.\nmove=> K K1 K2.\nrewrite -1!(ground_bexp_sem (store0 sigma)) in K.\nrewrite -2!(ground_exp_sem (store0 sigma)).\nby apply bop_re_lt_Zlt.\nQed.\n\nLemma Zle_gb H : ground_bexp (\\b e1 \\<= e2) H ->\n  s2Z (si32<=phy (ground_exp e1 H1)) <= s2Z (si32<=phy (ground_exp e2 H2)).\nProof.\nmove=> H'.\nrewrite -2!(ground_exp_sem (store0 sigma)).\napply bop_re_le_Zle.\nby rewrite -(ground_bexp_sem (store0 sigma)) in H'.\nQed.\n\nLemma Zle_gb_inv H :\n  Z<=s (si32<=phy (ground_exp e1 H1)) <= Z<=s (si32<=phy (ground_exp e2 H2)) ->\n  ground_bexp (\\b e1 \\<= e2) H.\nProof.\nTransparent eval beval.\nrewrite -(ground_bexp_sem (store0 sigma)) -2!(ground_exp_sem (store0 sigma)) /=.\nmove He1 : ( [ e1 ]_ _) => [e1s0 He1s0].\nmove He2 : ( [ e2 ]_ _) => [e2s0 He2s0] K.\ncase: ifP; first by rewrite not_is_zero_1.\nrewrite /si32_of_phy /= in K.\nhave He1s0' : size e1s0 = 4%nat by rewrite He1s0 sizeof_ityp.\ncase/oi32_of_i8_Some : He1s0' => x Hx.\nrewrite Hx /= in K.\nhave He2s0' : size e2s0 = 4%nat by rewrite He2s0 sizeof_ityp.\ncase/oi32_of_i8_Some : He2s0' => y Hy.\nrewrite Hy /= in K.\nrewrite (i32_of_i8_bij3 _ _ _ Hx) (i32_of_i8_bij3 _ _ _ Hy).\nmove/leZP => abs; contradiction.\nOpaque eval beval.\nQed.\n\n(* almost the same proof as Zle_gb_inv *)\nLemma Zlt_gb_inv H :\n   Z<=s (si32<=phy (ground_exp e1 H1)) < Z<=s (si32<=phy (ground_exp e2 H2)) ->\n   ground_bexp (\\b e1 \\< e2) H.\nProof.\nTransparent eval beval.\nrewrite -(ground_bexp_sem (store0 sigma)) -2!(ground_exp_sem (store0 sigma)) /=.\nmove He1 : ( [ e1 ]_ _) => [e1s0 He1s0].\nmove He2 : ( [ e2 ]_ _) => [e2s0 He2s0] => K.\ncase: ifP; first by rewrite not_is_zero_1.\nrewrite /si32_of_phy /= in K.\nhave He1s0' : size e1s0 = 4%nat by rewrite He1s0 sizeof_ityp.\ncase/oi32_of_i8_Some : He1s0' => x Hx.\nrewrite Hx /= in K.\nhave He2s0' : size e2s0 = 4%nat by rewrite He2s0 sizeof_ityp.\ncase/oi32_of_i8_Some : He2s0' => y Hy.\nrewrite Hy /= in K.\nrewrite (i32_of_i8_bij3 _ _ _ Hx) (i32_of_i8_bij3 _ _ _ Hy).\nmove/ltZP => abs; contradiction.\nOpaque eval beval.\nQed.\n\nLemma ground_bexp_lt0n H :\n  0 < Z<=s (si32<=phy (ground_exp e1 H1)) -> ground_bexp (\\b [ 0 ]sc \\< e1) H.\nProof.\nmove=> H0.\nTransparent beval eval.\nrewrite -(ground_bexp_sem (store0 sigma) (\\b [ 0 ]sc \\< e1)) /=.\nmove He1 : ([ e1 ]_ _) => [l1 Hl1].\nrewrite i8_of_i32K Z2sK //.\ncase: ifP; first by rewrite not_is_zero_1.\nrewrite -(ground_exp_sem (store0 sigma)) He1 /= in H0.\nset lhs := si32<=phy _ in H0.\nset rhs := i32<=i8 _ _.\nsuff: lhs = rhs by move=> <- /ltZP.\nrewrite /lhs /rhs {lhs rhs H0} /si32_of_phy /oi32_of_i8.\nhave : List.length l1 = 4%nat.\n  clear He1; by rewrite sizeof_ityp /= in Hl1.\ncase/(int_flat_Some erefl) => x Hx.\nrewrite Hx /= /i32_of_i8.\nby symmetry; apply int_flat_int_flat_ok.\nOpaque beval eval.\nQed.\n\nLemma ground_bexp_le0n H :\n  0 <= Z<=s (si32<=phy (ground_exp e1 H1)) -> ground_bexp (\\b [ 0 ]sc \\<= e1) H.\nProof.\nmove=> H0.\nTransparent beval eval.\nrewrite -(ground_bexp_sem (store0 sigma) (\\b [ 0 ]sc \\<= e1)) /=.\nmove He1 : ([ e1 ]_ _) => [l1 Hl1].\nrewrite i8_of_i32K Z2sK //.\ncase: ifP; first by rewrite not_is_zero_1.\nrewrite -(ground_exp_sem (store0 sigma)) He1 /= in H0.\nset lhs := si32<=phy _ in H0.\nset rhs := i32<=i8 _ _.\nsuff: lhs = rhs by move=> <- /leZP.\nrewrite /lhs /rhs {lhs rhs H0} /si32_of_phy /oi32_of_i8.\nhave : List.length l1 = 4%nat.\n  clear He1; by rewrite sizeof_ityp /= in Hl1.\ncase/(int_flat_Some erefl) => x Hx.\nrewrite Hx /= /i32_of_i8.\nby symmetry; apply int_flat_int_flat_ok.\nOpaque beval eval.\nQed.\n\nEnd ground_bexp_Zlt_Zle.\n\nDefinition ground_bexp_relation {g} {sigma : g.-env} :\n  Relations.Relation_Definitions.relation (forall (b : bexp sigma) (Hb : bvars b = nil), Prop).\nred.\napply Morphisms.respectful_hetero.\nexact bequiv.\nmove=> x y.\napply Morphisms.respectful_hetero.\nexact (fun _ _ => True).\nmove=> Hx Hy.\nexact iff.\nDefined.\n\nInstance ground_bexp_morphism {g} {sigma : g.-env} :\n  Morphisms.Proper ground_bexp_relation (@ground_bexp _ sigma).\nmove=> b1 b2 Hb /= Hb1 Hb2 _ /=.\nby rewrite -(ground_bexp_sem (store0 _)) -(ground_bexp_sem (store0 _)) Hb.\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/seplogC/C_expr_ground.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5, "lm_q1q2_score": 0.294444565383916}}
{"text": "\nRequire Import VST.floyd.proofauto.\nRequire Import common_predicates.\nRequire Import min2.\nFrom SSL_VST Require Import core.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\n\n\n\n\n\n\n\n\n\n\n\n\nDefinition min2_spec :=\n  DECLARE _min2\n   WITH r: val, x: val, y: val\n   PRE [ (tptr (Tunion _sslval noattr)), tint, tint ]\n   PROP( is_pointer_or_null((r : val)); ssl_is_valid_int((x : val)); ssl_is_valid_int((y : val)) )\n   PARAMS(r; x; y)\n   SEP ((data_at Tsh (tarray (Tunion _sslval noattr) 1) [(inr nullval)] (r : val)))\n   POST[ tvoid ]\n   EX m: Z,\n   PROP( ((m : Z) <= (force_signed_int (x : val))); ((m : Z) <= (force_signed_int (y : val))) )\n   LOCAL()\n   SEP ((data_at Tsh (tarray (Tunion _sslval noattr) 1) [(inl ((Vint (Int.repr m)) : val))] (r : val))).\n\n\n\n\n\n\nDefinition Gprog : funspecs :=\n  ltac:(with_library prog [min2_spec]).\n\n\nLemma body_min2 : semax_body Vprog Gprog f_min2 min2_spec.\nProof.\n\nstart_function.\nssl_open_context.\nforward_if.\n\n - {\nassert_PROP (isptr r). { entailer!. }\nforward.\nforward; entailer!.\nExists (x : Z).\nssl_entailer.\n\n}\n - {\nassert_PROP (isptr r). { entailer!. }\nforward.\nforward; entailer!.\nExists (y : Z).\nssl_entailer.\n\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/benchmarks/ints/verif_min2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891163376236, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2944445581688118}}
{"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\nDefinition load8 id ofs :=\n (Sset id\n      (Ederef\n        (Ebinop Oadd\n          (Efield\n            (Ederef (Etempvar _ctx (tptr t_struct_SHA256state_st))\n              t_struct_SHA256state_st) _h (tarray tuint 8))\n          (Econst_int (Int.repr ofs) tint) (tptr tuint)) tuint)).\n\nLemma Znth_is_int:\n forall i r,\n  0 <=  i < Zlength r ->\n  is_int I32 Unsigned (Znth i (map Vint r)).\nProof.\nintros.\nunfold Znth.\nrewrite if_false by lia.\nrewrite (nth_map' Vint Vundef Int.zero).\napply I.\ndestruct H as [H0 H]; rewrite Zlength_correct in H.\nrewrite <- (Z2Nat.id i) in H; auto.\napply Nat2Z.inj_lt in H; auto.\nQed.\n\nLemma sha256_block_load8:\n  forall (Espec : OracleKind)\n     (data: val) (r_h: list int) (ctx: val) gv (wsh: share)\n   (Hwsh: writable_share wsh)\n   (H5 : length r_h = 8%nat),\n     semax\n         (func_tycontext f_sha256_block_data_order Vprog Gtot nil)\n  (PROP  ()\n   LOCAL  (temp _data data; gvars gv; temp _ctx ctx; temp _in data)\n   SEP  (field_at wsh t_struct_SHA256state_st  [StructField _h] (map Vint r_h) ctx))\n   (Ssequence (load8 _a 0)\n     (Ssequence (load8 _b 1)\n     (Ssequence (load8 _c 2)\n     (Ssequence (load8 _d 3)\n     (Ssequence (load8 _e 4)\n     (Ssequence (load8 _f 5)\n     (Ssequence (load8 _g 6)\n     (Ssequence (load8 _h 7)\n         Sskip))))))))\n  (normal_ret_assert\n  (PROP  ()\n   LOCAL  (temp _a (Vint (nthi r_h 0));\n                temp _b (Vint (nthi r_h 1));\n                temp _c (Vint (nthi r_h 2));\n                temp _d (Vint (nthi r_h 3));\n                temp _e (Vint (nthi r_h 4));\n                temp _f (Vint (nthi r_h 5));\n                temp _g (Vint (nthi r_h 6));\n                temp _h (Vint (nthi r_h 7));\n                temp _data data; temp _ctx ctx; temp _in data;\n                gvars gv)\n   SEP  (field_at wsh t_struct_SHA256state_st  [StructField _h] (map Vint r_h) ctx))).\nProof.\nintros.\nunfold load8.\nabbreviate_semax.\nassert (H5': Zlength r_h = 8%Z)\n  by (rewrite Zlength_correct; rewrite H5; reflexivity).\ndo 8 forward.\nentailer!.\nQed.\n\nDefinition get_h (n: Z) :=\n    Sset _t\n        (Ederef\n           (Ebinop Oadd\n              (Efield\n                 (Ederef (Etempvar _ctx (tptr t_struct_SHA256state_st))\n                    t_struct_SHA256state_st) _h (tarray tuint 8))\n              (Econst_int (Int.repr n) tint) (tptr tuint)) tuint).\n\nDefinition add_h (n: Z) (i: ident) :=\n   Sassign\n       (Ederef\n          (Ebinop Oadd\n             (Efield\n                (Ederef (Etempvar _ctx (tptr t_struct_SHA256state_st))\n                   t_struct_SHA256state_st) _h (tarray tuint 8))\n             (Econst_int (Int.repr n) tint) (tptr tuint)) tuint)\n       (Ebinop Oadd (Etempvar _t tuint) (Etempvar i tuint) tuint).\n\nDefinition add_them_back :=\n [get_h 0; add_h 0 _a;\n  get_h 1; add_h 1 _b;\n  get_h 2; add_h 2 _c;\n  get_h 3; add_h 3 _d;\n  get_h 4; add_h 4 _e;\n  get_h 5; add_h 5 _f;\n  get_h 6; add_h 6 _g;\n  get_h 7; add_h 7 _h].\n\nFixpoint add_upto (k: nat) (u v: list int) {struct k} :=\n match k with\n | O => u\n | S k' => match u,v with\n                | u1::us, v1::vs => Int.add u1 v1 :: add_upto k' us vs\n                | _, _ => u\n                end\n end.\n\nLemma length_add_upto:\n  forall i r s,\n   length r = length s  ->\n   length (add_upto i r s) = length r.\nProof.\ninduction i; destruct r,s; intros;\n inv H; simpl; auto.\nQed.\n\n\nLemma force_lengthn_short:\n  forall {A} i (b: list A) v,\n     (i <= length b)%nat -> force_lengthn i b v = firstn i b.\nProof.\ninduction i; destruct b; intros.\nreflexivity.\nreflexivity.\ninv H.\nsimpl. f_equal. apply IHi. simpl in H. lia.\nQed.\n\nLemma add_upto_S:\n  forall (atoh regs : list int) (i : nat),\n  length atoh = 8%nat ->\n  length regs = 8%nat ->\n   (i < 8)%nat ->\n  map Vint (add_upto (S i) regs atoh) =\n  upd_Znth (Z.of_nat i) (map Vint (add_upto i regs atoh))\n   (Vint\n     (Int.add (nthi (add_upto i regs atoh) (Z.of_nat i))\n        (nthi atoh (Z.of_nat i)))).\nProof.\nintros. rename H1 into H4.\n assert ( i < length (add_upto i regs atoh))%nat\n    by (rewrite length_add_upto; lia).\n rewrite upd_Znth_old_upd_Znth. 2 : {\n   rewrite Zlength_map. rewrite Zlength_correct.\n   lia.\n }\n unfold old_upd_Znth.\n rewrite !sublist_map, <- map_cons, <- map_app.\n f_equal.\n\nassert (H18: length regs = length atoh) by congruence.\nassert (H19: (i < length regs)%nat) by lia.\nclear - H18 H19.\nrevert regs atoh H18 H19; induction i; destruct regs,atoh; intros;\ntry solve [inv H19]; inv H18.\nsimpl.\nf_equal.\nchange (i::regs) with ([i]++regs).\nautorewrite with sublist. auto.\nsimpl in H19.\nchange (add_upto (S (S i)) (i0 :: regs) (i1 :: atoh))\n  with (Int.add i0 i1 :: add_upto (S i) regs atoh).\nsimpl in H19.\nrewrite (IHi regs atoh); auto; [ | lia].\nclear IHi.\nsimpl add_upto.\nrewrite (sublist_split 0 1 (Z.of_nat (S i))); try lia.\nchange (@sublist int 0 1) with (@sublist int 0 (0+1)).\nrewrite sublist_len_1; try lia.\nrewrite inj_S.\nsimpl.\nautorewrite with sublist.\nf_equal.\nf_equal.\nchange (cons (Int.add i0 i1)) with (app [Int.add i0 i1]).\nrewrite sublist_app2 by (autorewrite with sublist; lia).\nf_equal.\nautorewrite with sublist; lia.\nf_equal.\nf_equal.\nunfold nthi.\nrewrite Z2Nat.inj_succ by lia.\nreflexivity.\nunfold nthi.\nrewrite Z2Nat.inj_succ by lia.\nreflexivity.\nchange (cons (Int.add i0 i1)) with (app [Int.add i0 i1]).\nrewrite sublist_app2 by (autorewrite with sublist; lia).\nf_equal.\nautorewrite with sublist; lia.\nautorewrite with sublist; lia.\nautorewrite with sublist. Omega1.\nrewrite inj_S.\nsplit; try lia.\nrewrite Zlength_cons.\nunfold Z.succ.\napply Zplus_le_compat_r.\nrewrite Zlength_correct.\nrewrite length_add_upto; auto.\napply Nat2Z.inj_le; auto.\nlia.\nQed.\n\nLemma upd_reptype_array_gso: (* perhaps move to floyd? *)\n forall t (a: list (reptype t)) v i j,\n    0 <= j < Zlength a ->\n    0 <= i < Zlength a ->\n    i<>j ->\n    Znth i (upd_Znth j a v) = Znth i a.\nProof.\nintros.\nunfold_upd_Znth_old.\nassert (i<j \\/ i>j) by lia.\nclear H1; destruct H2.\nautorewrite with sublist; auto.\nautorewrite with sublist; auto.\nchange (cons v) with (app [v]).\nautorewrite with sublist; auto.\nf_equal; lia.\nQed.\n\nLemma int_add_upto:\n  forall (regs atoh: list int),\n   Datatypes.length regs = 8%nat ->\n   Datatypes.length atoh = 8%nat ->\n   forall (j:nat)  (i:Z),\n     j = Z.to_nat i ->\n     0 <= i < 8 ->\n     is_int I32 Unsigned (Znth i (map Vint (add_upto j  regs atoh))).\nProof.\nintros until 2.\n  assert (ZR: Zlength regs = 8) by ( rewrite Zlength_correct, H; reflexivity).\n  induction j; intros.\n  simpl. apply Znth_is_int; lia.\n  unfold Znth.\n  rewrite if_false by lia.\n rewrite nth_map' with (d' := Int.zero).\n  apply I.\n  rewrite length_add_upto by lia.\n  rewrite H. apply Nat2Z.inj_lt.\n  rewrite Z2Nat.id by lia. apply H2.\nQed.\n\n\nLemma add_s:\n  forall (regs atoh: list int),\n   Datatypes.length regs = 8%nat ->\n   Datatypes.length atoh = 8%nat ->\n forall i i',\n    (i < 8)%nat ->\n    i' = Z.of_nat i ->\n    upd_Znth i' (map Vint (add_upto i regs atoh))\n             (Vint\n                (Int.add\n                   (Znth i' (add_upto i regs atoh))\n                   (nthi atoh i'))) =\n     map Vint (add_upto (S i) regs atoh).\nProof.\nintros.\nassert (is_int I32 Unsigned (Znth i' (map Vint (add_upto i regs atoh)))).\n apply  Znth_is_int.   rewrite Zlength_correct, length_add_upto, H.\n change (Z.of_nat 8) with 8; lia. rewrite H,H0;  auto.\nsubst i'.\nrewrite add_upto_S; try lia.\nf_equal.\ndestruct (Znth (Z.of_nat i) (map Vint (add_upto i regs atoh)));\n   try contradiction H3.\nsimpl.\nf_equal. f_equal.\nunfold Znth. rewrite if_false by lia.\nunfold nthi.\nrewrite Nat2Z.id. auto.\nQed.\n\nLemma add_upto_8:\n  forall (regs atoh: list int),\n   Datatypes.length regs = 8%nat ->\n   Datatypes.length atoh = 8%nat ->\n    add_upto 8 regs atoh = map2 Int.add regs atoh.\nProof.\nintros.\ndestruct atoh as [ | a [ | b [ | c [ | d [ | e [ | f [ | g [ | h [ | ]]]]]]]]]; inv H0.\ndestruct regs as [ | a' [ | b' [ | c' [ | d' [ | e' [ | f' [ | g' [ | h' [ | ]]]]]]]]]; inv H.\nsimpl; auto.\nQed.\n\nLemma add_them_back_proof:\n  forall (Espec : OracleKind)\n     (regs regs': list int) (ctx: val) gv (wsh: share) (Hwsh: writable_share wsh),\n     length regs = 8%nat ->\n     length regs' = 8%nat ->\n     semax  (func_tycontext f_sha256_block_data_order Vprog Gtot nil)\n   (PROP  ()\n   LOCAL  (temp _ctx ctx;\n                temp _a  (Vint (nthi regs' 0));\n                temp _b  (Vint (nthi regs' 1));\n                temp _c  (Vint (nthi regs' 2));\n                temp _d  (Vint (nthi regs' 3));\n                temp _e  (Vint (nthi regs' 4));\n                temp _f  (Vint (nthi regs' 5));\n                temp _g  (Vint (nthi regs' 6));\n                temp _h  (Vint (nthi regs' 7));\n                gvars gv)\n   SEP\n   (field_at wsh t_struct_SHA256state_st  [StructField _h] (map Vint regs) ctx))\n   (sequence add_them_back Sskip)\n  (normal_ret_assert\n   (PROP() LOCAL(temp _ctx ctx; gvars gv)\n    SEP (field_at wsh t_struct_SHA256state_st  [StructField _h]\n                (map Vint (map2 Int.add regs regs')) ctx))).\nProof.\nintros.\nrename regs' into atoh.\nunfold sequence, add_them_back.\nchange regs with  (add_upto 0 regs atoh) at 1.\nunfold get_h, add_h.\nabbreviate_semax.\nassert (ZR: Zlength regs = 8) by (rewrite Zlength_correct, H; reflexivity).\nassert (INT_ADD_UPTO := int_add_upto _ _ H H0).\nassert (ADD_S := add_s _ _ H H0).\n\nOpaque add_upto.\nassert (forall i i', i'=Z.of_nat i -> 0<= i' <8 -> 0 <= i' < Zlength (add_upto i regs atoh)). {\n intros;\n rewrite Zlength_correct; rewrite length_add_upto by lia;\n rewrite H; simpl; lia.\n}\nassert (0<=0) by computable.\nforward.\nforward.\nautorewrite with sublist.\nrewrite ADD_S by (try reflexivity; clear; lia).\nforward; forward.\nautorewrite with sublist.\nsimpl upd_Znth; rewrite ADD_S by (try reflexivity; clear; lia).\nforward; forward.\nautorewrite with sublist.\nsimpl upd_Znth; rewrite ADD_S by (try reflexivity; clear; lia).\nforward; forward.\nautorewrite with sublist.\nsimpl upd_Znth; rewrite ADD_S by (try reflexivity; clear; lia).\nforward; forward.\nautorewrite with sublist.\nsimpl upd_Znth; rewrite ADD_S by (try reflexivity; clear; lia).\nforward; forward.\nautorewrite with sublist.\nsimpl upd_Znth; rewrite ADD_S by (try reflexivity; clear; lia).\nforward; forward.\nautorewrite with sublist.\nsimpl upd_Znth; rewrite ADD_S by (try reflexivity; clear; lia).\nforward; forward.\nautorewrite with sublist.\nsimpl upd_Znth; rewrite ADD_S by (try reflexivity; clear; lia).\nrewrite (add_upto_8 _ _ H H0).\nentailer!.\nQed.\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/sha/verif_sha_bdo8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.2944150573125936}}
{"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 Smallest %\\ensuremath{\\frac13^{2n^2+n}}% *)\n(** printing eta_0 %\\ensuremath{\\eta_0}% #&eta;<SUB>0</SUB># *)\n\nRequire Export CoRN.complex.NRootCC.\nRequire Export CoRN.complex.AbsCC.\nRequire Export CoRN.fta.MainLemma.\n\n(**\n** Kneser Lemma *)\n\nSection Kneser_Lemma.\n\n(**\n%\\begin{convention}% Let [b : nat->CC], [n : nat] and [c : IR]\nsuch that [0 < n], [b_0 := b 0], [b_n := (b n) [=] [1]] and\n[(AbsCC b_0) [<] c].\n%\\end{convention}%\n*)\n\nVariable b : nat -> CC.\nVariable n : nat.\nHypothesis gt_n_0 : 0 < n.\n(* begin hide *)\nLet b_0 := b 0.\nLet b_n := b n.\n(* end hide *)\nHypothesis b_n_1 : b_n [=] [1].\nVariable c : IR.\nHypothesis b_0_lt_c : AbsCC b_0 [<] c.\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 - [Smallest := Small[*]Smaller]\n - [q := [1][-]Smallest]\n - [a i := AbsCC (b i)]\n\n%\\end{convention}%\n*)\n\n(* begin hide *)\nLet two_n := 2 * n.\nLet Small := p3m n.\nLet Smaller := p3m (two_n * n).\nLet Smallest := Small[*]Smaller.\nLet q := [1][-]Smallest.\n(* end hide *)\n\nLemma b_0'_exists : forall eta : IR, [0] [<] eta -> {b_0' : CC | AbsCC (b_0'[-]b_0) [<=] eta | b_0' [#] [0]}.\nProof.\n intros.\n exact (Cexis_AFS_CC [0] b_0 eta X).\nQed.\n\nLet eta_0 := ((c[-]AbsCC b_0) [/]FourNZ) [/]TwoNZ.\n\nLemma eta_0_pos : [0] [<] eta_0.\nProof.\n unfold eta_0 in |- *.\n apply pos_div_two.\n apply pos_div_four.\n apply shift_zero_less_minus.\n assumption.\nQed.\n\nLemma eta_exists : {eta : IR | [0] [<] eta |\n {b_0' : CC | AbsCC (b_0'[-]b_0) [<=] eta | b_0' [#] [0] and AbsCC b_0'[+]Three[*]eta [<] c}}.\nProof.\n exists eta_0.\n  exact eta_0_pos.\n generalize (b_0'_exists eta_0 eta_0_pos).\n intro H.\n elim H.\n intros b_0' H0 H1.\n exists b_0'.\n  assumption.\n split. assumption.\n  apply leEq_less_trans with ((AbsCC b_0[+]c) [/]TwoNZ).\n  2: apply Average_less_Greatest; auto.\n apply shift_plus_leEq.\n apply leEq_wdl with (AbsCC (b_0'[-]b_0[+]b_0)).\n  2: apply AbsCC_wd; rational.\n apply leEq_transitive with (AbsCC (b_0'[-]b_0) [+]AbsCC b_0).\n  apply triangle.\n apply leEq_transitive with (eta_0[+]AbsCC b_0).\n  apply plus_resp_leEq; auto.\n apply eq_imp_leEq.\n unfold eta_0 in |- *; rational.\nQed.\n\nLemma eps_exists_1 : forall eps x y : IR, [0] [<] eps -> [0] [<] x -> [0] [<] y ->\n {eps' : IR | [0] [<] eps' | eps' [<=] eps /\\ x[*]eps' [<=] y}.\nProof.\n intros eps x y Heps Hx Hy.\n cut ([0] [<] Half[*]eps). intro H2.\n  cut (x [#] [0]). intro H3.\n   2: apply pos_ap_zero; auto.\n  elim (less_cotransitive_unfolded _ _ _ H2 ((y[/] x[//]H3) [-]Half[*]eps)); intro H5.\n   exists (Half[*]eps).\n    auto.\n   split. apply less_leEq; apply half_3. auto.\n    astepr (x[*] (y[/] x[//]H3)).\n   apply less_leEq.\n   apply mult_resp_less_lft; auto.\n   astepl ([0][+]Half[*]eps).\n   apply shift_plus_less; auto.\n  cut ([0] [<] (y[/] x[//]H3)). intro H4.\n   2: apply div_resp_pos; auto.\n  exists (Half[*] (y[/] x[//]H3)).\n   apply mult_resp_pos. apply pos_half. auto.\n    split. apply leEq_transitive with (y[/] x[//]H3).\n   apply less_leEq; apply half_3; auto.\n   apply less_leEq.\n   astepr ([1][*]eps).\n   astepr ((Half[+]Half) [*]eps).\n   astepr (Half[*]eps[+]Half[*]eps).\n   apply shift_less_plus'; auto.\n  rstepl (Half[*]y).\n  apply less_leEq; apply half_3; auto.\n apply mult_resp_pos; auto.\n apply pos_half.\nQed.\n\n(* less_cotransitive_unfolded on\n  {[0]  [<]  y[/]x[//]H3[-]Half[*]eps} +\n  {y[/]x[//]H3[-]Half[*]eps  [<]  Half[*]eps}. *)\n\nLemma eps_exists : forall eta a_0 : IR, [0] [<] eta -> [0] [<] a_0 ->\n {eps : IR | [0] [<] eps | Two[*] (Three[^]n[+][1]) [*]eps [<=] eta /\\ Three[*]eps [<=] Smaller[*]a_0 /\\ eps [<=] a_0}.\nProof.\n intros eta a_0 Heta Ha_0.\n elim (eps_exists_1 ((Smaller[*]a_0) [/]ThreeNZ) (Three[^]n[+][1]) (eta [/]TwoNZ)).\n    intros eps H H0.\n    elim H0; intros H1 H2.\n    exists eps.\n     auto.\n    split.\n     astepl (Two[*] ((Three[^]n[+][1]) [*]eps)).\n     apply shift_mult_leEq' with (two_ap_zero IR); auto.\n     apply pos_two.\n    split.\n     apply shift_mult_leEq' with (three_ap_zero IR); auto.\n     apply pos_three.\n    eapply leEq_transitive.\n     apply H1.\n    apply shift_div_leEq'.\n     apply pos_three.\n    apply mult_resp_leEq_rht.\n     unfold Smaller in |- *; apply leEq_transitive with OneR. apply p3m_small.\n      apply less_leEq; apply one_less_three.\n    apply less_leEq; auto.\n   apply pos_div_three.\n   apply mult_resp_pos; auto.\n   unfold Smaller in |- *; apply p3m_pos.\n  apply plus_resp_pos.\n   apply nexp_resp_pos.\n   apply pos_three.\n  apply pos_one.\n apply pos_div_two; auto.\nQed.\n\n(* begin hide *)\nLet a (i : nat) : IR := AbsCC (b i).\n(* end hide *)\n\nLemma z_exists : forall (b_0' : CC) (k : nat) (r eta : IR), let a_0 := AbsCC b_0' in\n [0] [<] a_0 -> [0] [<] a k -> 1 <= k -> k <= n -> [0] [<=] r -> [0] [<] eta ->\n AbsCC (b_0'[-]b_0) [<=] eta -> a k[*]r[^]k [<=] a_0 ->\n {z : CC | AbsCC z [=] r | AbsCC (b_0[+]b k[*]z[^]k) [<=] a_0[-]a k[*]r[^]k[+]eta}.\nProof.\n (* begin hide *)\n intros b_0' k r eta a_0 H H0 H1 H2 H3 H4 H5 H6.\n cut (AbsCC b_0' [#] [0]). intro H7.\n  2: apply pos_ap_zero; auto.\n cut (cc_IR (AbsCC b_0') [#] [0]). intro H8.\n  2: astepr (cc_IR [0]); apply cc_IR_resp_ap; auto.\n cut (a k [#] [0]). intro H9.\n  2: apply pos_ap_zero; auto.\n cut (b k [#] [0]). intro H10.\n  2: apply AbsCC_ap_zero; apply ap_symmetric_unfolded; auto.\n cut (0 < k). intro H11.\n  2: auto with arith.\n cut ( [--] ((cc_IR (a k) [/] cc_IR (AbsCC b_0') [//]H8) [*] (b_0'[/] b k[//]H10)) [#]\n   [0]). intro H12.\n  elim (CnrootCC [--] ((cc_IR (a k) [/] cc_IR (AbsCC b_0') [//]H8) [*] (b_0'[/] b k[//]H10))\n    H12 k H11).\n  intros w H13.\n  cut (AbsCC w [=] [1]). intro H14.\n   exists (cc_IR r[*]w).\n    astepl (AbsCC (cc_IR r) [*]AbsCC w).\n    astepl (r[*]AbsCC w).\n    Step_final (r[*][1]).\n   apply leEq_transitive with (AbsCC (b_0'[+]b k[*] (cc_IR r[*]w) [^]k) [+]AbsCC (b_0[-]b_0')).\n    apply leEq_wdl with (AbsCC (b_0'[+]b k[*] (cc_IR r[*]w) [^]k[+] (b_0[-]b_0'))).\n     apply triangle.\n    apply AbsCC_wd; rational.\n   apply leEq_wdl with (AbsCC b_0'[-]a k[*]r[^]k[+]AbsCC (b_0[-]b_0')).\n    apply plus_resp_leEq_lft.\n    astepl (AbsCC [--] (b_0[-]b_0')).\n    apply leEq_wdl with (AbsCC (b_0'[-]b_0)); auto.\n    apply AbsCC_wd; rational.\n   apply bin_op_wd_unfolded.\n    2: algebra.\n   apply eq_transitive_unfolded with (AbsCC ((b_0'[/] cc_IR (AbsCC b_0') [//]H8) [*]\n     (cc_IR (AbsCC b_0') [-]cc_IR (a k) [*]cc_IR r[^]k))).\n    astepl ([1][*] (AbsCC b_0'[-]a k[*]r[^]k)).\n    astepr (AbsCC (b_0'[/] cc_IR (AbsCC b_0') [//]H8) [*]\n      AbsCC (cc_IR (AbsCC b_0') [-]cc_IR (a k) [*]cc_IR r[^]k)).\n    apply bin_op_wd_unfolded.\n     astepl (AbsCC b_0'[/] AbsCC b_0'[//]H7).\n     apply eq_symmetric_unfolded.\n     apply cc_div_abs'.\n     apply AbsCC_nonneg.\n    apply eq_transitive_unfolded with (AbsCC (cc_IR (AbsCC b_0') [-]cc_IR (a k) [*]cc_IR (r[^]k))).\n     2: apply AbsCC_wd; algebra.\n    astepr (AbsCC (cc_IR (AbsCC b_0') [-]cc_IR (a k[*]r[^]k))).\n    astepr (AbsCC (cc_IR (AbsCC b_0'[-]a k[*]r[^]k))).\n    cut ([0] [<=] AbsCC b_0'[-]a k[*]r[^]k). algebra.\n     apply shift_leEq_lft; auto.\n   apply AbsCC_wd.\n   rstepl (b_0'[+] b k[*] (cc_IR r[^]k[*]\n     [--] ((cc_IR (a k) [/] cc_IR (AbsCC b_0') [//]H8) [*] (b_0'[/] b k[//]H10)))).\n   apply bin_op_wd_unfolded. algebra.\n    apply bin_op_wd_unfolded. algebra.\n    Step_final (cc_IR r[^]k[*]w[^]k).\n  apply root_one with k; auto.\n   apply AbsCC_nonneg.\n  astepl (AbsCC (w[^]k)).\n  astepl (AbsCC [--] ((cc_IR (a k) [/] cc_IR (AbsCC b_0') [//]H8) [*] (b_0'[/] b k[//]H10))).\n  astepl (AbsCC ((cc_IR (a k) [/] cc_IR (AbsCC b_0') [//]H8) [*] (b_0'[/] b k[//]H10))).\n  astepl (AbsCC (cc_IR (a k) [/] cc_IR (AbsCC b_0') [//]H8) [*] AbsCC (b_0'[/] b k[//]H10)).\n  astepl (AbsCC (cc_IR (a k) [/] cc_IR (AbsCC b_0') [//]H8) [*] AbsCC (b_0'[/] b k[//]H10)).\n  cut ([0] [<=] AbsCC b_0'). intro. 2: apply AbsCC_nonneg.\n   astepl ((AbsCC (cc_IR (a k)) [/] AbsCC b_0'[//]H7) [*]AbsCC (b_0'[/] b k[//]H10)).\n  astepl ((AbsCC (cc_IR (a k)) [/] AbsCC b_0'[//]H7) [*]AbsCC (b_0'[/] b k[//]H10)).\n  cut ([0] [<=] a k). intro. 2: apply less_leEq; auto.\n   astepl ((a k[/] AbsCC b_0'[//]H7) [*]AbsCC (b_0'[/] b k[//]H10)).\n  astepl ((a k[/] AbsCC b_0'[//]H7) [*] (AbsCC b_0'[/] AbsCC (b k) [//]H9)).\n  unfold a in |- *; rational.\n apply ap_wdl_unfolded with (cc_IR [--] (a k[/] AbsCC b_0'[//]H7) [*] (b_0'[/] b k[//]H10)).\n  apply mult_resp_ap_zero.\n   astepr (cc_IR [0]).\n   apply cc_IR_resp_ap.\n   apply inv_resp_ap_zero.\n   apply div_resp_ap_zero_rev; auto.\n  apply div_resp_ap_zero_rev.\n  apply AbsCC_ap_zero.\n  apply ap_symmetric_unfolded; auto.\n apply eq_transitive_unfolded with ( [--] (cc_IR (a k[/] AbsCC b_0'[//]H7)) [*] (b_0'[/] b k[//]H10)).\n  apply mult_wdl.\n  astepl (cc_IR ([0][-] (a k[/] AbsCC b_0'[//]H7))). astepr ([0][-]cc_IR (a k[/] AbsCC b_0'[//]H7)).\n  Step_final (cc_IR [0][-]cc_IR (a k[/] AbsCC b_0'[//]H7)).\n astepl (([0][-]cc_IR (a k[/] AbsCC b_0'[//]H7)) [*] (b_0'[/] b k[//]H10)).\n astepl ((cc_IR [0][-]cc_IR (a k[/] AbsCC b_0'[//]H7)) [*] (b_0'[/] b k[//]H10)).\n astepl (cc_IR [0][*] (b_0'[/] b k[//]H10) [-]\n   cc_IR (a k[/] AbsCC b_0'[//]H7) [*] (b_0'[/] b k[//]H10)).\n astepl ([0][*] (b_0'[/] b k[//]H10) [-] cc_IR (a k[/] AbsCC b_0'[//]H7) [*] (b_0'[/] b k[//]H10)).\n astepl ([0][-]cc_IR (a k[/] AbsCC b_0'[//]H7) [*] (b_0'[/] b k[//]H10)).\n astepl ( [--] (cc_IR (a k[/] AbsCC b_0'[//]H7) [*] (b_0'[/] b k[//]H10))).\n apply un_op_wd_unfolded.\n apply mult_wdl.\n unfold cc_IR in |- *; simpl in |- *; split; simpl in |- *; rational.\nQed.\n(* end hide *)\n\nLemma Kneser_1' : Half [<=] q.\nProof.\n unfold q in |- *.\n apply shift_leEq_minus.\n astepl (Smallest[+]Half).\n apply shift_plus_leEq.\n unfold Half in |- *.\n rstepr ([1] [/]TwoNZ:IR).\n unfold Smallest, Small, Smaller in |- *.\n generalize (p3m_smaller n gt_n_0).\n intro Hn.\n generalize (p3m_smaller (two_n * n)).\n intro H2nn.\n apply leEq_transitive with (Half[*] (Half:IR)).\n  apply mult_resp_leEq_both; auto.\n    apply less_leEq; apply p3m_pos.\n   apply less_leEq; apply p3m_pos.\n  apply H2nn.\n  unfold two_n in |- *.\n  elim gt_n_0. auto with arith.\n   intros. simpl in |- *. auto with arith.\n  rstepr ([1] [/]TwoNZ[*]OneR).\n apply less_leEq.\n apply mult_resp_less_lft.\n  exact (half_lt1 _).\n exact (pos_half _).\nQed.\n\nLemma Kneser_1'' : q [<] [1].\nProof.\n unfold q in |- *.\n apply shift_minus_less'.\n rstepl ([0][+]OneR).\n apply plus_resp_less_rht.\n unfold Smallest, Small, Smaller in |- *.\n apply mult_resp_pos; apply p3m_pos.\nQed.\n\nLemma Kneser_1 : forall a_0 eta eps : IR, [0] [<] eta -> [0] [<] eps ->\n a_0[+]Three[*]eta [<] c -> Two[*] (Three[^]n[+][1]) [*]eps [<=] eta -> q[*]a_0[+]Three[^]n[*]eps[+]eps[+]eta [<] q[*]c.\nProof.\n intros.\n cut ([1] [/]TwoNZ[*] (Two[*]Three[^]n[*]eps[+]Two[*]eps[+]Two[*]eta) [<=]\n   q[*] (Two[*]Three[^]n[*]eps[+]Two[*]eps[+]Two[*]eta)).\n  intro Hm.\n  apply leEq_less_trans with (q[*] (a_0[+]Two[*]Three[^]n[*]eps[+]Two[*]eps[+]Two[*]eta)).\n   rstepr (q[*]a_0[+]q[*] (Two[*]Three[^]n[*]eps[+]Two[*]eps[+]Two[*]eta)).\n   rstepl (q[*]a_0[+][1] [/]TwoNZ[*] (Two[*]Three[^]n[*]eps[+]Two[*]eps[+]Two[*]eta)).\n   apply plus_resp_leEq_lft; auto.\n  apply mult_resp_less_lft.\n   apply leEq_less_trans with (a_0[+]Three[*]eta); auto.\n   rstepl (a_0[+] (Two[*]Three[^]n[*]eps[+]Two[*]eps[+]Two[*]eta)).\n   apply plus_resp_leEq_lft.\n   rstepl (Two[*] (Three[^]n[+][1]) [*]eps[+]Two[*]eta).\n   rstepr (eta[+]Two[*]eta).\n   apply plus_resp_leEq; auto.\n  apply less_leEq_trans with (Half:IR).\n   apply pos_half. exact Kneser_1'.\n  apply mult_resp_leEq_rht. exact Kneser_1'.\n  apply less_leEq.\n apply less_leEq_trans with ([0][+]Two[*]eta).\n  rstepr (Two[*]eta).\n  apply mult_resp_pos; auto.\n  apply pos_two.\n apply less_leEq.\n apply plus_resp_less_rht.\n apply less_transitive_unfolded with ([0][+]Two[*]eps).\n  rstepr (Two[*]eps).\n  apply mult_resp_pos; auto.\n  apply pos_two.\n apply plus_resp_less_rht.\n repeat apply mult_resp_pos; auto.\n  apply pos_two.\n apply nexp_resp_pos; apply pos_three.\nQed.\n\nSection with_CRing. (* We need a context so we can declare the ring structure. *)\n\n  Variable R: CRing.\n\n  Add Ring R: (CRing_Ring R).\n\n  Lemma Kneser_2a : forall (m n i : nat) (f : nat -> R), 1 <= i ->\n   Sum m n f [=] f m[+]f i[+] (Sum (S m) (pred i) f[+]Sum (S i) n f).\n  Proof.\n   intros.\n   astepl (f m[+]Sum (S m) n0 f).\n   astepl (f m[+] (Sum (S m) i f[+]Sum (S i) n0 f)).\n   astepl (f m[+] (Sum (S m) (pred i) f[+]f i[+]Sum (S i) n0 f)).\n   ring.\n  Qed.\n\nEnd with_CRing.\n\nLemma Kneser_2b : forall (k : nat) (z : CC), 1 <= k ->\n let p_ := fun i => b i[*]z[^]i in\n Sum 0 n (fun i => b i[*]z[^]i) [=] b_0[+]b k[*]z[^]k[+] (Sum 1 (pred k) p_[+]Sum (S k) n p_).\nProof.\n (* begin hide *)\n intros.\n unfold p_ in |- *.\n unfold b_0 in |- *.\n apply eq_transitive_unfolded\n   with (b 0[*]z[^]0[+]b k[*]z[^]k[+] (Sum 1 (pred k) p_[+]Sum (S k) n p_)); unfold p_ in |- *.\n  apply Kneser_2a with (f := fun i : nat => b i[*]z[^]i).\n  auto.\n rational.\nQed.\n(* end hide *)\n\nLemma Kneser_2c : forall (m n : nat) (z : CC), m <= S n ->\n let r := AbsCC z in\n AbsCC (Sum m n (fun i => b i[*]z[^]i)) [<=] Sum m n (fun i => a i[*]r[^]i).\nProof.\n (* begin hide *)\n intros.\n unfold r in |- *.\n apply leEq_wdr with (Sum m n0 (fun i : nat => AbsCC (b i[*]z[^]i))).\n  apply triangle_Sum with (z := fun i : nat => b i[*]z[^]i). auto.\n  apply Sum_wd.\n intros.\n unfold a in |- *.\n Step_final (AbsCC (b i) [*]AbsCC (z[^]i)).\nQed.\n(* end hide *)\n\nLemma Kneser_2 : forall (k : nat) (z : CC), 1 <= k -> k <= n ->\n let r := AbsCC z in let p_ := fun i => a i[*]r[^]i in\n AbsCC (Sum 0 n (fun i => b i[*]z[^]i)) [<=]\n  AbsCC (b_0[+]b k[*]z[^]k) [+] (Sum 1 (pred k) p_[+]Sum (S k) n p_).\nProof.\n (* begin hide *)\n intros.\n unfold p_, r in |- *.\n set (p_' := fun i : nat => b i[*]z[^]i) in *.\n apply leEq_wdl with (AbsCC (b_0[+]b k[*]z[^]k[+] (Sum 1 (pred k) p_'[+]Sum (S k) n p_')));\n   unfold p_' in |- *.\n  apply leEq_transitive with\n    (AbsCC (b_0[+]b k[*]z[^]k) [+]AbsCC (Sum 1 (pred k) p_'[+]Sum (S k) n p_')); unfold p_' in |- *.\n   apply triangle.\n  apply plus_resp_leEq_lft.\n  apply leEq_transitive with (AbsCC (Sum 1 (pred k) p_') [+]AbsCC (Sum (S k) n p_'));\n    unfold p_' in |- *.\n   apply triangle.\n  apply plus_resp_leEq_both.\n   apply Kneser_2c. auto with arith.\n   apply Kneser_2c. auto with arith.\n  apply AbsCC_wd.\n apply eq_symmetric_unfolded.\n apply Kneser_2b.\n auto.\nQed.\n(* end hide *)\nLemma Kneser_3 : {z : CC | AbsCC z[^]n [<=] c | AbsCC (Sum 0 n (fun i => b i[*]z[^]i)) [<] q[*]c}.\nProof.\n elim eta_exists. intros eta H0 H1.\n elim H1. intros b_0' H3 H4. elim H4. intros H5 H6.\n clear H1 H4.\n cut ([0] [<] AbsCC b_0'). intro H7.\n  2: apply AbsCC_pos; auto.\n elim (eps_exists eta (AbsCC b_0') H0 H7). intros eps H9 H10. elim H10. intros H11 H12. elim H12. intros H13 H14.\n clear H10 H12.\n cut (forall k : nat, [0] [<=] a k). intro H15.\n  2: intro; unfold a in |- *; apply AbsCC_nonneg.\n cut (a n [=] [1]). intro H16.\n  2: unfold a in |- *; Step_final (AbsCC [1]).\n elim (Main a n gt_n_0 eps H9 H15 H16 (AbsCC b_0') H14).\n intro r. intros H18 H19.\n elim H19. intros k H20.\n elim H20. intros H21 H22. elim H22. intros H23 H24. elim H24. intros H25 H26.\n elim H26. intros H27 H28. elim H28. intros H29 H30.\n clear H19 H20 H22 H24 H26 H28.\n cut ([0] [<] a k). intro H31.\n  elim (z_exists b_0' k r eta H7 H31 H21 H23 H18 H0 H3 H30). intro z. intros H33 H34.\n  exists z.\n   astepl (r[^]n).\n   apply leEq_transitive with (AbsCC b_0'); auto.\n   apply leEq_transitive with (AbsCC b_0'[+]Three[*]eta).\n    2: apply less_leEq; auto.\n   astepl (AbsCC b_0'[+][0]).\n   apply plus_resp_leEq_lft.\n   apply less_leEq.\n   apply mult_resp_pos; auto.\n   apply pos_three.\n  set (r' := AbsCC z) in *. unfold r' in H33, H34.\n  set (p_' := fun i : nat => a i[*]r'[^]i) in *.\n  apply leEq_less_trans with (eps[+] (q[*]AbsCC b_0'[+]Three[^]n[*]eps[+]eta)).\n   2: rstepl (q[*]AbsCC b_0'[+]Three[^]n[*]eps[+]eps[+]eta); apply Kneser_1; auto.\n  apply leEq_transitive with (AbsCC (b_0[+]b k[*]z[^]k) [+] (Sum 1 (pred k) p_'[+]Sum (S k) n p_'));\n    unfold p_', r' in |- *.\n   apply Kneser_2; auto.\n  set (p_'' := fun i : nat => a i[*]r[^]i) in *.\n  apply leEq_wdl with (AbsCC (b_0[+]b k[*]z[^]k) [+] (Sum 1 (pred k) p_''[+]Sum (S k) n p_''));\n    unfold p_'' in |- *.\n   2: apply bin_op_wd_unfolded; [ algebra | apply bin_op_wd_unfolded; apply Sum_wd; algebra ].\n  apply leEq_transitive with (AbsCC (b_0[+]b k[*]z[^]k) [+]\n    (([1][-]Small) [*] (a k[*]r[^]k) [+]Three[^]n[*]eps)).\n   apply plus_resp_leEq_lft; auto.\n  apply leEq_transitive with (AbsCC b_0'[-]AbsCC (b k) [*]r[^]k[+]eta[+]\n    (([1][-]Small) [*] (a k[*]r[^]k) [+]Three[^]n[*]eps)).\n   apply plus_resp_leEq; auto.\n  unfold a in |- *.\n  rstepl (AbsCC b_0'[+]Three[^]n[*]eps[+]eta[-]Small[*] (AbsCC (b k) [*]r[^]k)).\n  apply leEq_transitive with (AbsCC b_0'[+]Three[^]n[*]eps[+]eta[-]\n    Small[*] (Smaller[*]AbsCC b_0'[-]Two[*]eps)).\n   apply minus_resp_leEq_rht.\n   apply mult_resp_leEq_lft; auto.\n   unfold Small in |- *.\n   apply less_leEq; apply p3m_pos.\n  apply leEq_wdl with (Small[*]Two[*]eps[+] (q[*]AbsCC b_0'[+]Three[^]n[*]eps[+]eta)).\n   2: unfold q, Smallest in |- *; rational.\n  apply plus_resp_leEq.\n  astepr ([1][*]eps).\n  apply mult_resp_leEq_rht.\n   2: apply less_leEq; auto.\n  astepr (Half[*] (Two:IR)).\n  apply mult_resp_leEq_rht.\n   unfold Small in |- *; apply p3m_smaller; auto.\n  apply less_leEq; apply pos_two.\n apply mult_cancel_pos_lft with (r[^]k).\n  2: apply nexp_resp_nonneg; auto.\n apply less_leEq_trans with eps; auto.\n eapply leEq_transitive.\n  2: apply H29.\n apply shift_leEq_minus.\n rstepl (Three[*]eps). auto.\nQed.\n\nEnd Kneser_Lemma.\n\nLemma Kneser : forall n : nat, 0 < n -> {q : IR | [0] [<=] q |\n q [<] [1] and (forall p : cpoly CC, monic n p -> forall c : IR,\n  AbsCC p ! [0] [<] c -> {z : CC | AbsCC z[^]n [<=] c | AbsCC p ! z [<] q[*]c})}.\nProof.\n intros n H.\n exists ([1][-]p3m n[*]p3m (2 * n * n)).\n  apply less_leEq.\n  apply less_leEq_trans with (Half:IR).\n   apply pos_half.\n  apply Kneser_1'; auto.\n split. apply Kneser_1''.\n  intros p H0 c H1.\n elim H0. intros H2 H3.\n cut (nth_coeff n p [=] [1]). intro H4.\n  2: auto.\n elim (Kneser_3 (fun i : nat => nth_coeff i p) n H H4 c). intros z H6 H7.\n  2: astepl (AbsCC p ! [0]); auto.\n exists z.\n  auto.\n astepl (AbsCC (Sum 0 n (fun i : nat => nth_coeff i p[*]z[^]i))); auto.\nQed.\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/KneserLemma.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.29441504956189296}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Main.\nRequire Import Functor.Functor Functor.Functor_Ops\n        Functor.Representable.Hom_Func.\nRequire Import Functor.Functor_Extender.\nRequire Import NatTrans.NatTrans NatTrans.Operations\n        NatTrans.Func_Cat NatTrans.NatIso.\nRequire Import Ext_Cons.Prod_Cat.Prod_Cat Ext_Cons.Prod_Cat.Operations\n        Ext_Cons.Prod_Cat.Nat_Facts.\nRequire Import Adjunction.Adjunction.\nRequire Import KanExt.Local  KanExt.LocalFacts.Uniqueness.\nRequire Import Basic_Cons.Terminal.\n\nLocal Open Scope functor_scope.\n\n(** This module contains conversion from local kan extension defiend as cones\nto local kan extensions defined through hom functor. *)\n\nSection Local_Right_KanExt_to_Hom_Local_Right_KanExt.\n  Context {C C' : Category} {p : C –≻ C'}\n          {D : Category} {F : C –≻ D}\n          (lrke : Local_Right_KanExt p F).\n\n  (** The left to right side of Hom_Local_Right_KanExt isomorphism. *)\n  Program Definition Local_Right_KanExt_to_Hom_Local_Right_KanExt_Iso_LR :\n    (((@Fix_Bi_Func_2 _ (Func_Cat C D) _ F (Hom_Func (Func_Cat C D)))\n        ∘ (Left_Functor_Extender p D)^op)\n       –≻ (@Fix_Bi_Func_2 _ (Func_Cat C' D) _ lrke (Hom_Func (Func_Cat C' D))))%nattrans :=\n    {|\n      Trans :=  fun c h => LRKE_morph_ex lrke {|cone_apex := c; cone_edge := h|}\n    |}.\n\n  Next Obligation.\n  Proof.\n    extensionality x.\n    repeat rewrite NatTrans_id_unit_left.\n    match goal with\n      [|- cone_morph (LRKE_morph_ex lrke ?A) = ?X] =>\n      match X with\n        ((cone_morph ?C) ∘ ?B)%nattrans =>\n        change X with\n        (cone_morph\n           (LoKan_Cone_Morph_compose\n              _\n              _\n              (Build_LoKan_Cone_Morph p F A {|cone_apex := c; cone_edge := x|} h eq_refl) C\n           )\n        )\n      end\n    end.\n    apply LRKE_morph_unique.\n  Qed.\n\n  Next Obligation.\n  Proof.\n    symmetry.\n    apply Local_Right_KanExt_to_Hom_Local_Right_KanExt_Iso_LR_obligation_1.\n  Qed.\n\n  (** The right to left side of Hom_Local_Right_KanExt isomorphism. *)\n  Program Definition Local_Right_KanExt_to_Hom_Local_Right_KanExt_Iso_RL :\n    ((@Fix_Bi_Func_2 _ (Func_Cat C' D) _ lrke (Hom_Func (Func_Cat C' D)))\n       –≻ ((@Fix_Bi_Func_2 _ (Func_Cat C D) _ F (Hom_Func (Func_Cat C D)))\n             ∘ (Left_Functor_Extender p D)^op\n             ))%nattrans\n    :=\n    {|\n      Trans :=  fun c h => (lrke ∘ (h ∘_h (NatTrans_id p)))%nattrans\n    |}.\n \n  Next Obligation.\n  Proof.\n    extensionality x.\n    repeat rewrite NatTrans_id_unit_left.\n    rewrite NatTrans_compose_assoc.\n    rewrite NatTrans_comp_hor_comp.\n    rewrite NatTrans_id_unit_right.\n    trivial.\n  Qed.\n\n  Next Obligation.\n  Proof.\n    symmetry.\n    apply Local_Right_KanExt_to_Hom_Local_Right_KanExt_Iso_RL_obligation_1.\n  Qed.\n\n    (** Conversion from Local_Right_KanExt Hom_Local_Right_KanExt isomorphism. *)\n  Program Definition Local_Right_KanExt_to_Hom_Local_Right_KanExt :\n    Hom_Local_Right_KanExt p F :=\n    {|\n      HLRKE := (cone_apex (LRKE lrke));\n      HLRKE_Iso :=\n        {|\n          iso_morphism := Local_Right_KanExt_to_Hom_Local_Right_KanExt_Iso_LR;\n          inverse_morphism := Local_Right_KanExt_to_Hom_Local_Right_KanExt_Iso_RL\n        |}\n    |}.\n\n  Next Obligation.\n  Proof.\n    apply NatTrans_eq_simplify.\n    extensionality h; extensionality x.\n    symmetry.\n    apply (cone_morph_com (LRKE_morph_ex lrke {| cone_apex := h; cone_edge := x |})).\n  Qed.\n\n  Next Obligation.\n  Proof.\n    apply NatTrans_eq_simplify.\n    extensionality h; extensionality x.\n    cbn in *.\n    match goal with\n      [|- cone_morph (LRKE_morph_ex lrke ?A) = ?X] =>\n      change X with (cone_morph (Build_LoKan_Cone_Morph p F A lrke x eq_refl));\n        apply (LRKE_morph_unique lrke A)\n    end.\n  Qed.\n\nEnd Local_Right_KanExt_to_Hom_Local_Right_KanExt.", "meta": {"author": "amintimany", "repo": "Categories-HoTT", "sha": "fd6018c7abd496b44fd31b1119f6b31795c251d8", "save_path": "github-repos/coq/amintimany-Categories-HoTT", "path": "github-repos/coq/amintimany-Categories-HoTT/Categories-HoTT-fd6018c7abd496b44fd31b1119f6b31795c251d8/KanExt/LocalFacts/ConesToHom.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723316991792861, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.29436261710007205}}
{"text": "(** shows that action-based strong functors can be perceived as strong monoidal functors from the monoidal category that is acting on the underlying categories to a suitable monoidal category\n\nThis means that the requirement on strength is that it behaves as a ``homomorphism'' w.r.t. the\nmonoidal structures. More precisely, we construct transformations in both directions between parameterized distributivity (in a slightly massaged form to accommodate reasoning through bicategories) and displayed sections that are a formalization-friendly form of strong monoidal functors that are right inverses of the projection from the target displayed category. The result makes use of displayed monoidal categories.\n\nThe non-monoidal basic situation is now presented in [UniMath.CategoryTheory.categories.Dialgebras].\n\nAuthor: Ralph Matthes 2021, 2022\n\n *)\n\nRequire Import UniMath.Foundations.PartD.\nRequire Import UniMath.MoreFoundations.All.\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.Core.Isos.\nRequire Import UniMath.CategoryTheory.Core.NaturalTransformations.\nRequire Import UniMath.CategoryTheory.FunctorCategory.\nRequire Import UniMath.CategoryTheory.whiskering.\nRequire Import UniMath.CategoryTheory.categories.Dialgebras.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Core.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Total.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Constructions.\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.\nRequire Import UniMath.Bicategories.MonoidalCategories.Actions.\nRequire Import UniMath.Bicategories.MonoidalCategories.ActionBasedStrength.\nRequire Import UniMath.Bicategories.MonoidalCategories.WhiskeredMonoidalFromBicategory.\nRequire Import UniMath.Bicategories.Core.Bicat.\nRequire Import UniMath.Bicategories.Core.BicategoryLaws.\nRequire Import UniMath.Bicategories.Core.Unitors.\nRequire Import UniMath.Bicategories.Core.Invertible_2cells.\nRequire Import UniMath.Bicategories.Core.Examples.BicatOfCats.\n\nImport Bicat.Notations.\nImport BifunctorNotations.\nImport DisplayedBifunctorNotations.\nImport MonoidalNotations.\n\nLocal Open Scope cat.\n\nSection UpstreamInBicat.\n\n  Context {C0 : category}. (** an \"ordinary\" category for the source *)\n  Context {C : bicat}.\n  Context (a a' : ob C).\n\n  Context (H H' : C0 ⟶ hom a a').\n\n  Definition trafotargetbicat_disp: disp_cat C0 := dialgebra_disp_cat H H'.\n\n  Lemma trafotargetbicat_disp_cells_isaprop (x y : C0) (f : C0 ⟦ x, y ⟧)\n        (xx : trafotargetbicat_disp x) (yy : trafotargetbicat_disp y):\n    isaprop (xx -->[ f] yy).\n  Proof.\n    intros Hyp Hyp'.\n    apply (hom a a').\n  Qed.\n\n  Definition trafotargetbicat_cat: category := total_category trafotargetbicat_disp.\n\n  Definition forget_from_trafotargetbicat: trafotargetbicat_cat ⟶ C0 := pr1_category trafotargetbicat_disp.\n\n  Definition nat_trans_to_section_bicat (η: H ⟹ H'):\n    @section_disp C0 trafotargetbicat_disp := nat_trans_to_section H H' η.\n\n  Definition section_to_nat_trans_bicat:\n    @section_disp C0 trafotargetbicat_disp -> H ⟹ H' := section_to_nat_trans H H'.\n\nEnd UpstreamInBicat.\n\nSection Main.\n\n  Context {V : category}.\n  Context (Mon_V : monoidal V).\n\n  Notation \"X ⊗ Y\" := (X ⊗_{ Mon_V } Y).\n\n  Section ActionViaBicat.\n\n    Context {C : bicat}.\n    Context (a0 : ob C).\n\n    Context {FA: functor V (category_from_bicat_and_ob a0)}.\n    Context (FAm: fmonoidal Mon_V (monoidal_from_bicat_and_ob a0) FA).\n\n    (** currently no development on the abstract level *)\n\n  End ActionViaBicat.\n\n  Section FunctorViaBicat.\n\n    Context {C : bicat}.\n    Context {a0 a0' : ob C}.\n\n    Context {FA: functor V (category_from_bicat_and_ob a0)}.\n    Context {FA': functor V (category_from_bicat_and_ob a0')}.\n\n    Context (FAm: fmonoidal Mon_V (monoidal_from_bicat_and_ob a0) FA).\n    Context (FA'm: fmonoidal Mon_V (monoidal_from_bicat_and_ob a0') FA').\n\n    Context (G : hom a0 a0').\n\n    Definition H : functor V (hom a0 a0') :=\n       functor_compose FA' (lwhisker_functor G).\n\n    Definition H' : functor V (hom a0 a0') :=\n      functor_compose FA (rwhisker_functor G).\n\n    Lemma Hok (v: V) : H v = G · FA' v.\n    Proof.\n      apply idpath.\n    Defined.\n\n    Lemma Hmorok (v v': V) (f: v --> v'): # H f = G ◃ # FA' f.\n    Proof.\n      apply idpath.\n    Qed.\n\n    Lemma H'ok (v: V) : H' v = FA v · G.\n    Proof.\n      apply idpath.\n    Defined.\n\n    Lemma H'morok (v v': V) (f: v --> v'): # H' f = # FA f ▹ G.\n    Proof.\n      apply idpath.\n    Qed.\n\n    Definition montrafotargetbicat_disp: disp_cat V := trafotargetbicat_disp a0 a0' H H'.\n    Definition montrafotargetbicat_cat: category := trafotargetbicat_cat a0 a0' H H'.\n\n    Definition param_distr_bicat_triangle_eq_variant0_RHS : trafotargetbicat_disp a0 a0' H H' I_{Mon_V} :=\n      G ◃ (pr1 (fmonoidal_preservesunitstrongly FA'm))\n          • (((runitor G : G · I_{ monoidal_from_bicat_and_ob a0'} ==> G)\n          • (linvunitor G : G ==> I_{ monoidal_from_bicat_and_ob a0} · G))\n          • ((fmonoidal_preservesunit FAm) ▹ G)).\n(*    Proof.\n      set (t1 := lwhisker G (pr1 (fmonoidal_preservesunitstrongly FA'm))).\n      set (t2 := rwhisker G (fmonoidal_preservesunit FAm)).\n      refine (vcomp2 t1 _).\n      refine (vcomp2 _ t2).\n      apply (vcomp2(g:=G)).\n      - cbn. apply runitor.\n      - cbn. apply linvunitor.\n    Defined. *)\n\n    Definition montrafotargetbicat_disp_unit: montrafotargetbicat_disp I_{Mon_V} :=\n      param_distr_bicat_triangle_eq_variant0_RHS.\n\n    Definition montrafotargetbicat_unit: montrafotargetbicat_cat := I_{Mon_V},, montrafotargetbicat_disp_unit.\n\n    Definition param_distr_bicat_pentagon_eq_body_RHS (v w : V)\n      (dv: montrafotargetbicat_disp v) (dw: montrafotargetbicat_disp w) : H v · FA' w ==> FA (v ⊗ w) · G :=\n      ((dv ▹ FA' w)\n         • ((rassociator (FA v) G (FA' w) : H' v · FA' w ==> FA v · H w)\n         • (FA v ◃ dw)))\n         • ((lassociator (FA v) (FA w) G : FA v · H' w ==> FA v ⊗_{ monoidal_from_bicat_and_ob a0} FA w · G)\n         • (fmonoidal_preservestensordata FAm v w ▹ G)).\n(*    Proof.\n      set (aux1 := rwhisker (FA' w) dv).\n      set (aux2 := lwhisker (FA v) dw).\n      transparent assert (auxr : (H v · FA' w ==> FA v · H' w)).\n      { refine (vcomp2 aux1 _).\n        refine (vcomp2 _ aux2).\n        cbn.\n        apply rassociator.\n      }\n      set (aux3 := rwhisker G (fmonoidal_preservestensordata FAm v w)).\n      refine (vcomp2 auxr _).\n      refine (vcomp2 _ aux3).\n      cbn.\n      apply lassociator.\n    Defined. *)\n\n    Definition param_distr_bicat_pentagon_eq_body_variant_RHS (v w : V)\n      (dv: montrafotargetbicat_disp v) (dw: montrafotargetbicat_disp w) : montrafotargetbicat_disp (v ⊗ w) :=\n      (G ◃ pr1 (fmonoidal_preservestensorstrongly FA'm v w))\n        • ((lassociator G (FA' v) (FA' w) : G · FA' v ⊗_{ monoidal_from_bicat_and_ob a0'} FA' w ==> H v · FA' w)\n        • param_distr_bicat_pentagon_eq_body_RHS v w dv dw).\n(*    Proof.\n      set (aux1inv := lwhisker G (pr1 (fmonoidal_preservestensorstrongly FA'm v w))).\n      refine (vcomp2 aux1inv _).\n      refine (vcomp2 _ (param_distr_bicat_pentagon_eq_body_RHS v w dv dw)).\n      cbn.\n      apply lassociator.\n    Defined. *)\n\n    (** a number of auxiliary isomorphisms to ease the lemmas on arrow reversion *)\n    Definition lwhisker_with_μ_inv_inv2cell (v w : V): invertible_2cell (G · FA' (v ⊗ w)) (G · (FA' v · FA' w)).\n    Proof.\n      use make_invertible_2cell.\n      - exact (lwhisker G (pr1 (fmonoidal_preservestensorstrongly FA'm v w))).\n      - is_iso.\n        change (is_z_isomorphism (pr1 (fmonoidal_preservestensorstrongly FA'm v w))).\n        apply is_z_isomorphism_inv.\n    Defined.\n\n    Definition rwhisker_lwhisker_with_μ_inv_inv2cell (v1 v2 v3 : V):\n      invertible_2cell (G · (FA' (v1 ⊗ v2) · FA' v3)) (G · (FA' v1 · FA' v2 · FA' v3)).\n    Proof.\n      use make_invertible_2cell.\n      - exact (G ◃ (pr1 (fmonoidal_preservestensorstrongly FA'm v1 v2) ▹ FA' v3)).\n      - is_iso.\n        change (is_z_isomorphism  (pr1 (fmonoidal_preservestensorstrongly FA'm v1 v2))).\n        apply is_z_isomorphism_inv.\n    Defined.\n\n    Definition lwhisker_rwhisker_with_ϵ_inv_inv2cell (v : V):\n      invertible_2cell (G · FA' I_{Mon_V} · FA' v) (G · id₁ a0' · FA' v).\n    Proof.\n      use make_invertible_2cell.\n      - exact ((G ◃ pr1 (fmonoidal_preservesunitstrongly FA'm)) ▹ FA' v).\n      - is_iso.\n        change (is_z_isomorphism (pr1 (fmonoidal_preservesunitstrongly FA'm))).\n        apply is_z_isomorphism_inv.\n    Defined.\n\n    Definition rwhisker_with_linvunitor_inv2cell (v : V): invertible_2cell (G · FA' v) (id₁ a0 · G · FA' v).\n    Proof.\n      use make_invertible_2cell.\n      - exact (linvunitor G ▹ FA' v).\n      - is_iso.\n    Defined.\n\n    Definition lwhisker_with_linvunitor_inv2cell (v : V):\n      invertible_2cell (FA v · G) (FA v · (id₁ a0 · G)).\n    Proof.\n      use make_invertible_2cell.\n      - exact (FA v ◃ linvunitor G).\n      - is_iso.\n    Defined.\n\n    Definition lwhisker_with_invlunitor_inv2cell (v : V):\n      invertible_2cell (G · (pr11 FA') v) (G · (pr11 FA') (I_{Mon_V} ⊗ v)).\n    Proof.\n      use make_invertible_2cell.\n      - exact (G ◃ # FA' (pr1 (pr2 (leftunitor_nat_z_iso Mon_V) v))).\n      - is_iso.\n        change (is_z_isomorphism (# FA' (pr1 (pr2 (leftunitor_nat_z_iso Mon_V) v)))).\n        apply functor_on_is_z_isomorphism.\n        apply (is_z_iso_inv_from_z_iso (nat_z_iso_pointwise_z_iso (leftunitor_nat_z_iso Mon_V) v)).\n    Defined.\n\n    Definition rwhisker_with_invlunitor_inv2cell (v : V):\n      invertible_2cell (FA v · G) (FA (I_{Mon_V} ⊗ v) · G).\n    Proof.\n      use make_invertible_2cell.\n      - exact (# FA (pr1 (pr2 (leftunitor_nat_z_iso Mon_V) v)) ▹ G).\n      - is_iso.\n        change (is_z_isomorphism (# FA (pr1 (pr2 (leftunitor_nat_z_iso Mon_V) v)))).\n        apply functor_on_is_z_isomorphism.\n        apply (is_z_iso_inv_from_z_iso (nat_z_iso_pointwise_z_iso (leftunitor_nat_z_iso Mon_V) v)).\n    Defined.\n\n    Definition lwhisker_with_invrunitor_inv2cell (v : V):\n      invertible_2cell (G · FA' v) (G · FA'(v ⊗ I_{Mon_V})).\n    Proof.\n      use make_invertible_2cell.\n      - exact (G ◃ # FA' (pr1 (pr2 (rightunitor_nat_z_iso Mon_V) v))).\n      - is_iso.\n        change (is_z_isomorphism (# FA' (pr1 (pr2 (rightunitor_nat_z_iso Mon_V) v)))).\n        apply functor_on_is_z_isomorphism.\n        apply (is_z_iso_inv_from_z_iso (nat_z_iso_pointwise_z_iso (rightunitor_nat_z_iso Mon_V) v)).\n    Defined.\n\n    Definition rwhisker_with_invrunitor_inv2cell (v : V):\n      invertible_2cell (FA v · G) (FA (v ⊗ I_{Mon_V}) · G).\n    Proof.\n      use make_invertible_2cell.\n      - exact (# FA (pr1 (pr2 (rightunitor_nat_z_iso Mon_V) v)) ▹ G).\n      - is_iso.\n        change (is_z_isomorphism (# FA (pr1 (pr2 (rightunitor_nat_z_iso Mon_V) v)))).\n        apply functor_on_is_z_isomorphism.\n        apply (is_z_iso_inv_from_z_iso (nat_z_iso_pointwise_z_iso (rightunitor_nat_z_iso Mon_V) v)).\n    Defined.\n\n    Definition lwhisker_with_ϵ_inv2cell (v : V):\n      invertible_2cell (FA' v · id₁ a0') (FA' v · FA' I_{Mon_V}).\n    Proof.\n      use make_invertible_2cell.\n      - exact (FA' v ◃ fmonoidal_preservesunit FA'm).\n      - is_iso.\n        change (is_z_isomorphism (fmonoidal_preservesunit FA'm)).\n        apply fmonoidal_preservesunitstrongly.\n    Defined.\n\n    Definition lwhisker_with_ϵ_inv2cell_bis:\n      invertible_2cell (G · FA' I_{ Mon_V}) (G · I_{ monoidal_from_bicat_and_ob a0'}).\n    Proof.\n      use make_invertible_2cell.\n      - exact (G ◃ pr1 (fmonoidal_preservesunitstrongly FA'm)).\n      - is_iso.\n        change (is_z_isomorphism (pr1 (fmonoidal_preservesunitstrongly FA'm))).\n        apply is_z_isomorphism_inv.\n    Defined.\n\n    Definition rwhisker_with_invassociator_inv2cell (v1 v2 v3 : V):\n      invertible_2cell (FA (v1 ⊗ (v2 ⊗ v3)) · G) (FA ((v1 ⊗ v2) ⊗ v3) · G).\n    Proof.\n      use make_invertible_2cell.\n      - exact (# FA (αinv_{Mon_V} v1 v2 v3) ▹ G).\n      - is_iso.\n        change (is_z_isomorphism (# FA (αinv_{Mon_V} v1 v2 v3))).\n        apply functor_on_is_z_isomorphism.\n        exists (α_{Mon_V} v1 v2 v3).\n        destruct (monoidal_associatorisolaw Mon_V v1 v2 v3).\n        split; assumption.\n    Defined.\n    (** end of auxiliary definitions of isomorphisms *)\n\n    (** the main lemma for the construction of the tensor - for reasons of exploiting legacy code, this is the general lemma and not its two instances that come right afterwards *)\n    Lemma montrafotargetbicat_tensor_comp_aux (v w v' w': V) (f: V⟦v,v'⟧) (g: V⟦w,w'⟧)\n          (η : montrafotargetbicat_disp v) (π : montrafotargetbicat_disp w)\n          (η' : montrafotargetbicat_disp v') (π' : montrafotargetbicat_disp w')\n          (Hyp: η  -->[ f] η') (Hyp': π -->[ g] π'):\n      param_distr_bicat_pentagon_eq_body_variant_RHS v w η π\n      -->[ f ⊗^{Mon_V} g]\n      param_distr_bicat_pentagon_eq_body_variant_RHS v' w' η' π'.\n    Proof.\n      hnf in Hyp, Hyp' |- *.\n      unfold param_distr_bicat_pentagon_eq_body_variant_RHS, param_distr_bicat_pentagon_eq_body_RHS.\n      match goal with | [ |- (?Hαinv • (?Hassoc1 • ((?Hγ • (?Hassoc2 • ?Hδ)) • (?Hassoc3 • ?Hβ)))) · ?Hε = _ ] =>\n                          set (αinv := Hαinv); set (γ := Hγ); set (δ:= Hδ); set (β := Hβ); set (ε1 := Hε) end.\n      cbn in αinv, β.\n      match goal with | [ |- _ = ?Hε · (?Hαinv • (?Hassoc4 • ((?Hγ • (?Hassoc5 • ?Hδ) • (?Hassoc6 • ?Hβ))))) ] =>\n                          set (αinv' := Hαinv); set (γ' := Hγ); set (δ':= Hδ); set (β' := Hβ); set (ε2 := Hε) end.\n      cbn in αinv', β'.\n      set (αinviso := lwhisker_with_μ_inv_inv2cell v w).\n      cbn in αinviso.\n      etrans.\n      { apply pathsinv0. apply vassocr. }\n      apply (lhs_left_invert_cell _ _ _ αinviso).\n      apply pathsinv0.\n      unfold inv_cell.\n      set (α := lwhisker G (fmonoidal_preservestensordata FA'm v w)).\n      cbn in α.\n      match goal with | [ |- ?Hαcand • _ = _ ] => set (αcand := Hαcand) end.\n      change αcand with α.\n      clear αcand.\n      assert (μFA'natinst := full_naturality_condition (pr2 (preservestensor_is_nattrans (fmonoidal_preservestensornatleft FA'm) (fmonoidal_preservestensornatright FA'm))) f g).\n      cbn in μFA'natinst.\n      unfold make_binat_trans_data in μFA'natinst.\n      assert (μFAnatinst := full_naturality_condition (pr2 (preservestensor_is_nattrans (fmonoidal_preservestensornatleft FAm) (fmonoidal_preservestensornatright FAm))) f g).\n      cbn in μFAnatinst.\n      unfold make_binat_trans_data in μFAnatinst.\n      unfold H in ε2. cbn in ε2.\n      etrans.\n      { apply vassocr. }\n      apply (maponpaths (lwhisker G)) in μFA'natinst.\n      apply pathsinv0 in μFA'natinst.\n      etrans.\n      { apply maponpaths_2.\n        apply lwhisker_vcomp. }\n      etrans.\n      { apply maponpaths_2.\n        unfold functoronmorphisms1. rewrite (functor_comp FA').\n        exact μFA'natinst. }\n      clear ε2 μFA'natinst.\n      etrans.\n      { apply maponpaths_2.\n        apply pathsinv0.\n        apply lwhisker_vcomp. }\n      etrans.\n      { apply pathsinv0. apply vassocr. }\n      etrans.\n      { apply maponpaths.\n        rewrite vassocr.\n        apply maponpaths_2.\n        unfold αinv'.\n        apply lwhisker_vcomp.\n      }\n      etrans.\n      { apply maponpaths.\n        apply maponpaths_2.\n        apply maponpaths.\n        apply (pr12 (fmonoidal_preservestensorstrongly FA'm v' w')). }\n      clear αinv αinv' αinviso α.\n      unfold H' in ε1. cbn in ε1.\n      cbn.\n      rewrite lwhisker_id2.\n      rewrite id2_left.\n      match goal with | [ |- ?Hσ • _ = _ ] => set (σ' := Hσ) end.\n      etrans.\n      2: { repeat rewrite <- vassocr. apply idpath. }\n      apply (maponpaths (rwhisker G)) in μFAnatinst.\n      etrans.\n      2: { do 5 apply maponpaths.\n           apply pathsinv0. apply rwhisker_vcomp. }\n      etrans.\n      2: { do 5 apply maponpaths.\n           unfold functoronmorphisms1. rewrite (functor_comp FA).\n           exact μFAnatinst. }\n      clear β μFAnatinst ε1.\n      etrans.\n      2: { do 5 apply maponpaths.\n           apply rwhisker_vcomp. }\n      match goal with | [ |- _ =  _ • (_ • (_ • (_ • (_ • (_ • ?Hβ'twin))))) ] => set (β'twin := Hβ'twin) end.\n      change β'twin with β'.\n      clear β'twin.\n      repeat rewrite vassocr.\n      apply maponpaths_2.\n      clear β'.\n      unfold σ'.\n      assert (hcomp_aux:= hcomp_hcomp' (# FA' f) (# FA' g)).\n      unfold hcomp, hcomp' in hcomp_aux.\n      etrans.\n      { do 5 apply maponpaths_2. apply maponpaths. apply hcomp_aux. }\n      clear hcomp_aux σ'.\n      rewrite <- lwhisker_vcomp.\n      match goal with | [ |- (((((?Hσ'1 • ?Hσ'2) • _) • _) • _) • _) • _  = _ • ?Hσ ]\n                        => set (σ'1 := Hσ'1); set (σ'2 := Hσ'2); set (σ := Hσ) end.\n      change (η • # H' f = # H f • η') in Hyp.\n      apply (maponpaths (rwhisker (FA' w'))) in Hyp.\n      do 2 rewrite <- rwhisker_vcomp in Hyp.\n      apply pathsinv0 in Hyp.\n      assert (Hypvariant: σ'2 • lassociator G (FA' v') (FA' w') • γ' =\n        lassociator G (FA' v) (FA' w') • (rwhisker (FA' w') η • rwhisker (FA' w') (# H' f))).\n      { apply (maponpaths (vcomp2 (lassociator G (FA' v) (FA' w')))) in Hyp.\n        etrans.\n        2: { exact Hyp. }\n        rewrite vassocr.\n        apply maponpaths_2.\n        rewrite Hmorok.\n        apply rwhisker_lwhisker.\n      }\n      clear Hyp.\n      intermediate_path (σ'1 • ((σ'2 • lassociator G (FA' v') (FA' w')) • γ') •\n                             rassociator (FA v') G (FA' w') • δ' • lassociator (FA v') (FA w') G).\n      { repeat rewrite <- vassocr.\n        apply idpath. }\n      rewrite Hypvariant.\n      clear σ'2 γ' Hypvariant. (* until here mostly in parallel with earlier proof in CAT *)\n      assert (σ'1ok : σ'1 • lassociator G (FA' v) (FA' w') =\n                        lassociator G (FA' v) (FA' w) • (H v ◃ # FA' g)).\n      (* associators needed in addition to devel. in CAT *)\n      { apply lwhisker_lwhisker. }\n      etrans.\n      { repeat rewrite vassocr. rewrite σ'1ok. apply idpath. }\n      clear σ'1 σ'1ok.\n      repeat rewrite <- vassocr.\n      apply maponpaths.\n      etrans.\n      { repeat rewrite vassocr.\n        do 4 apply maponpaths_2.\n        apply pathsinv0.\n        apply hcomp_hcomp'. }\n      unfold hcomp.\n      repeat rewrite <- vassocr.\n      apply maponpaths.\n      clear γ.\n      change (π • # H' g = # H g • π') in Hyp'.\n      apply (maponpaths (lwhisker (FA v))) in Hyp'.\n      do 2 rewrite <- lwhisker_vcomp in Hyp'.\n      rewrite H'morok in Hyp'.\n      assert (Hyp'variant: δ • lassociator (FA v) (FA w) G • ((FA v ◃ # FA g) ▹ G) =\n                             ((FA v ◃ # H g) • (FA v ◃ π')) • lassociator (FA v) (FA w') G).\n      (* close to what was called Hypvariant in the devel. in CAT *)\n      { apply (maponpaths (fun x => x • lassociator (FA v) (FA w') G)) in Hyp'.\n        etrans.\n        { rewrite <- vassocr. apply maponpaths. apply pathsinv0. apply rwhisker_lwhisker. }\n        rewrite vassocr. exact Hyp'.\n      }\n      clear Hyp'.\n      set (σbetter := hcomp' (# FA f) (# FA g) ▹ G).\n      assert (σbetterok : σ = σbetter).\n      { apply maponpaths. apply hcomp_hcomp'. }\n      rewrite σbetterok.\n      clear σ σbetterok.\n      unfold hcomp' in σbetter.\n      set (σbetter' := ((FA v ◃ # FA g) ▹ G ) • ((# FA f ▹ FA w') ▹ G)).\n      assert (σbetter'ok : σbetter = σbetter').\n      { apply pathsinv0, rwhisker_vcomp. }\n      rewrite σbetter'ok. clear σbetter σbetter'ok.\n      etrans.\n      2: { apply maponpaths. unfold σbetter'. repeat rewrite vassocr. apply maponpaths_2.\n           apply pathsinv0. exact Hyp'variant. }\n      clear Hyp'variant σbetter' δ. (* now very close to the situation in the CAT development where δ was cleared *)\n      etrans.\n      2: { repeat rewrite vassocr. apply idpath. }\n      match goal with | [ |- _ = (((_ • ?Hν'variant) • ?Hδ'π') • _) • _]\n                        => set (ν'variant := Hν'variant); set (δ'π' := Hδ'π') end.\n      assert (ν'variantok: ν'variant • lassociator (FA v) G (FA' w') =\n                             lassociator (FA v) G (FA' w) • (H' v ◃ # FA' g)).\n      { unfold ν'variant. rewrite Hmorok. apply lwhisker_lwhisker. }\n      etrans.\n      2: { repeat rewrite <- vassocr. apply idpath. }\n      apply pathsinv0.\n      use lhs_left_invert_cell.\n      { apply is_invertible_2cell_rassociator. }\n      etrans.\n      2: { repeat rewrite vassocr.\n           do 4 apply maponpaths_2.\n           exact ν'variantok. }\n      repeat rewrite <- vassocr.\n      apply maponpaths.\n      clear ν'variant ν'variantok.\n      etrans.\n      { apply maponpaths.\n        apply rwhisker_rwhisker. }\n      repeat rewrite vassocr.\n      apply maponpaths_2.\n      rewrite H'morok.\n      etrans.\n      { apply pathsinv0. apply hcomp_hcomp'. }\n      clear δ'π'.\n      unfold hcomp.\n      apply maponpaths_2.\n      clear δ'.\n      cbn.\n      rewrite rwhisker_rwhisker.\n      rewrite <- vassocr.\n      etrans.\n      { apply pathsinv0, id2_right. }\n      apply maponpaths.\n      apply pathsinv0.\n      apply (vcomp_rinv (is_invertible_2cell_lassociator _ _ _)).\n    Qed.\n\n    (** the first dependently-typed ingredient of the displayed bifunctor for the tensor construction *)\n    Lemma montrafotargetbicat_tensor_comp_aux_inst1 (v w w' : V) (g : V ⟦ w, w' ⟧)\n          (η : G · FA' v ==> FA v · G) (π : G · FA' w ==> FA w · G) (π' : G · FA' w' ==> FA w' · G):\n      π • (# FA g ▹ G) = (G ◃ # FA' g) • π'\n      → param_distr_bicat_pentagon_eq_body_variant_RHS v w η π • (# FA (v ⊗^{ Mon_V}_{l} g) ▹ G) =\n          (G ◃ # FA' (v ⊗^{ Mon_V}_{l} g)) • param_distr_bicat_pentagon_eq_body_variant_RHS v w' η π'.\n    Proof.\n      intro Hyp'.\n      rewrite <- (when_bifunctor_becomes_leftwhiskering Mon_V).\n      change (montrafotargetbicat_disp v) in η.\n      exact (montrafotargetbicat_tensor_comp_aux v w v w' (identity v) g η π η π' (id_disp η) Hyp').\n    Qed.\n    (** the second dependently-typed ingredient of the displayed bifunctor for the tensor construction *)\n    Lemma montrafotargetbicat_tensor_comp_aux_inst2 (v v' w : V) (f : V ⟦ v, v' ⟧)\n          (η : G · FA' v ==> FA v · G) (η' : G · FA' v' ==> FA v' · G) (π : G · FA' w ==> FA w · G):\n      η • (# FA f ▹ G) = (G ◃ # FA' f) • η'\n      → param_distr_bicat_pentagon_eq_body_variant_RHS v w η π • (# FA (f ⊗^{ Mon_V}_{r} w) ▹ G) =\n          (G ◃ # FA' (f ⊗^{ Mon_V}_{r} w)) • param_distr_bicat_pentagon_eq_body_variant_RHS v' w η' π.\n    Proof.\n      intro Hyp.\n      rewrite <- (when_bifunctor_becomes_rightwhiskering Mon_V).\n      change (montrafotargetbicat_disp w) in π.\n      exact (montrafotargetbicat_tensor_comp_aux v w v' w f (identity w) η π η' π Hyp (id_disp π)).\n    Qed.\n    Definition montrafotargetbicat_disp_tensor: disp_tensor montrafotargetbicat_disp Mon_V.\n    Proof.\n      use make_disp_bifunctor.\n      - use make_disp_bifunctor_data.\n        + intros v w η π.\n          exact (param_distr_bicat_pentagon_eq_body_variant_RHS v w η π).\n        + cbn.\n          intros v w w' g η π π' Hyp'.\n          apply montrafotargetbicat_tensor_comp_aux_inst1; assumption.\n        + cbn.\n          intros v v' w f η η' π Hyp.\n          apply montrafotargetbicat_tensor_comp_aux_inst2; assumption.\n      - red. repeat split; red; intros; apply trafotargetbicat_disp_cells_isaprop.\n    Defined.\n    (** the following are called data elements, but they have no computational content *)\n    Lemma montrafotargetbicat_disp_leftunitor_data: disp_leftunitor_data montrafotargetbicat_disp_tensor montrafotargetbicat_disp_unit.\n    Proof.\n      hnf.\n      intros v η.\n      cbn.\n      (** now comes an adaptation of the code of [montrafotargetbicat_left_unitor_aux1] from the former approach to monoidal categories *)\n      unfold param_distr_bicat_pentagon_eq_body_variant_RHS, montrafotargetbicat_disp_unit,\n        param_distr_bicat_triangle_eq_variant0_RHS, param_distr_bicat_pentagon_eq_body_RHS.\n      do 3 rewrite <- rwhisker_vcomp.\n      repeat rewrite <- vassocr.\n      match goal with | [ |- ?Hl1 • (_ • (?Hl2 • (_ • (_ • (?Hl3 • (_ • (?Hl4 • (_ • (?Hl5 • ?Hl6))))))))) = ?Hr1 • _]\n                        => set (l1 := Hl1); set (l2 := Hl2); set (l3 := Hl3); set (l4 := Hl4);\n                          set (l5 := Hl5); set (l6 := Hl6); set (r1 := Hr1) end.\n      change (H v ==> H' v) in η.\n      set (l1iso := lwhisker_with_μ_inv_inv2cell I_{Mon_V} v).\n      apply (lhs_left_invert_cell _ _ _ l1iso).\n      cbn.\n      apply (lhs_left_invert_cell _ _ _ (is_invertible_2cell_lassociator _ _ _)).\n      cbn.\n      set (l2iso := lwhisker_rwhisker_with_ϵ_inv_inv2cell v).\n      apply (lhs_left_invert_cell _ _ _ l2iso).\n      cbn.\n      etrans.\n      2: { repeat rewrite vassocr.\n           rewrite <- rwhisker_lwhisker_rassociator.\n           apply maponpaths_2.\n           repeat rewrite <- vassocr.\n           apply maponpaths.\n           unfold r1.\n           do 2 rewrite lwhisker_vcomp.\n           apply maponpaths.\n           rewrite vassocr.\n           assert (lax_monoidal_functor_unital_inst := fmonoidal_preservesleftunitality FA'm v).\n           cbn in lax_monoidal_functor_unital_inst.\n           apply pathsinv0.\n           exact lax_monoidal_functor_unital_inst.\n      }\n      clear l1 l2 l1iso l2iso r1.\n      etrans.\n      { do 2 apply maponpaths.\n        rewrite vassocr.\n        apply maponpaths_2.\n        apply rwhisker_rwhisker_alt. }\n      clear l3.\n      cbn.\n      etrans.\n      { do 2 apply maponpaths.\n        repeat rewrite vassocr.\n        do 3 apply maponpaths_2.\n        rewrite <- vassocr.\n        apply maponpaths.\n        apply hcomp_hcomp'. }\n      clear l4.\n      unfold hcomp'.\n      etrans.\n      { repeat rewrite <- vassocr.\n        do 4 apply maponpaths.\n        rewrite vassocr.\n        rewrite <- rwhisker_rwhisker.\n        repeat rewrite <- vassocr.\n        apply maponpaths.\n        unfold l5, l6.\n        do 2 rewrite rwhisker_vcomp.\n        apply maponpaths.\n        apply pathsinv0.\n        rewrite vassocr.\n        assert (lax_monoidal_functor_unital_inst := fmonoidal_preservesleftunitality FAm v).\n        cbn in lax_monoidal_functor_unital_inst.\n        apply pathsinv0.\n        exact lax_monoidal_functor_unital_inst.\n      }\n      clear l5 l6. (* now only admin tasks in bicategory *)\n      rewrite lunitor_lwhisker.\n      apply maponpaths.\n      apply (lhs_left_invert_cell _ _ _ (rwhisker_with_linvunitor_inv2cell v)).\n      cbn.\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    Qed.\n    Lemma montrafotargetbicat_disp_rightunitor_data: disp_rightunitor_data montrafotargetbicat_disp_tensor montrafotargetbicat_disp_unit.\n    Proof.\n      hnf.\n      intros v η.\n      cbn.\n      (** now comes an adaptation of the code of [montrafotargetbicat_right_unitor_aux1] from the former approach to monoidal categories *)\n      unfold param_distr_bicat_pentagon_eq_body_variant_RHS, montrafotargetbicat_disp_unit,\n        param_distr_bicat_triangle_eq_variant0_RHS, param_distr_bicat_pentagon_eq_body_RHS.\n      do 3 rewrite <- lwhisker_vcomp.\n      repeat rewrite <- vassocr.\n      match goal with | [ |- ?Hl1 • (_ • (?Hl2 • (_ • (?Hl3 • (_ • (_ • (?Hl4 • (_ • (?Hl5 • ?Hl6))))))))) = ?Hr1 • _]\n                        => set (l1 := Hl1); set (l2 := Hl2); set (l3 := Hl3); set (l4 := Hl4);\n                          set (l5 := Hl5); set (l6 := Hl6); set (r1 := Hr1) end.\n      change (H v ==> H' v) in η.\n      set (l1iso := lwhisker_with_μ_inv_inv2cell v I_{Mon_V}).\n      apply (lhs_left_invert_cell _ _ _ l1iso).\n      cbn.\n      clear l1 l1iso.\n      apply (lhs_left_invert_cell _ _ _ (is_invertible_2cell_lassociator _ _ _)).\n      cbn.\n      etrans.\n      2: { apply maponpaths.\n           rewrite vassocr.\n           apply maponpaths_2.\n           unfold r1.\n           rewrite lwhisker_vcomp.\n           apply maponpaths.\n           assert (lax_monoidal_functor_unital_inst := fmonoidal_preservesrightunitality FA'm v).\n           cbn in lax_monoidal_functor_unital_inst.\n           apply pathsinv0 in lax_monoidal_functor_unital_inst.\n           set (aux1iso := lwhisker_with_ϵ_inv2cell v).\n           rewrite <- vassocr in lax_monoidal_functor_unital_inst.\n           apply pathsinv0 in lax_monoidal_functor_unital_inst.\n           apply (rhs_left_inv_cell _ _ _ aux1iso) in lax_monoidal_functor_unital_inst.\n           unfold inv_cell in lax_monoidal_functor_unital_inst.\n           apply pathsinv0.\n           exact lax_monoidal_functor_unital_inst.\n      }\n      cbn.\n      clear r1.\n      etrans.\n      2: { rewrite vassocr.\n           apply maponpaths_2.\n           rewrite <- lwhisker_vcomp.\n           rewrite vassocr.\n           apply maponpaths_2.\n           apply pathsinv0.\n           apply lwhisker_lwhisker_rassociator. }\n      etrans.\n      2: { repeat rewrite <- vassocr.\n           apply maponpaths.\n           rewrite vassocr.\n           apply maponpaths_2.\n           apply pathsinv0, runitor_triangle. }\n      rewrite <- vcomp_runitor.\n      etrans.\n      2: { rewrite vassocr.\n           apply maponpaths_2.\n           apply hcomp_hcomp'. }\n      unfold hcomp.\n      etrans.\n      2: { repeat rewrite <- vassocr. apply idpath. }\n      apply maponpaths.\n      clear l2.\n      etrans.\n      { repeat rewrite vassocr.\n        do 6 apply maponpaths_2.\n        apply lwhisker_lwhisker_rassociator. }\n      repeat rewrite <- vassocr.\n      apply maponpaths.\n      clear l3.\n      cbn.\n      etrans.\n      { repeat rewrite vassocr.\n        do 5 apply maponpaths_2.\n        apply runitor_triangle. }\n      etrans.\n      2: { apply id2_right. }\n      repeat rewrite <- vassocr.\n      apply maponpaths.\n      etrans.\n      { apply maponpaths.\n        rewrite vassocr.\n        apply maponpaths_2.\n        apply rwhisker_lwhisker. }\n      cbn.\n      clear l4.\n      etrans.\n      { apply maponpaths.\n        rewrite <- vassocr.\n        apply maponpaths.\n        unfold l5, l6.\n        do 2 rewrite rwhisker_vcomp.\n        apply maponpaths.\n        assert (lax_monoidal_functor_unital_inst := fmonoidal_preservesrightunitality FAm v).\n        cbn in lax_monoidal_functor_unital_inst.\n        apply pathsinv0.\n        rewrite vassocr.\n        apply pathsinv0.\n        exact lax_monoidal_functor_unital_inst.\n      }\n      clear l5 l6. (* now only pure bicategory reasoning *)\n      set (auxiso := lwhisker_with_linvunitor_inv2cell v).\n      apply (lhs_left_invert_cell _ _ _ auxiso).\n      cbn.\n      rewrite id2_right.\n      clear auxiso.\n      apply runitor_rwhisker.\n    Qed.\n    Definition montrafotargetbicat_disp_associator_data: disp_associator_data montrafotargetbicat_disp_tensor.\n    Proof.\n      intros v1 v2 v3 η1 η2 η3.\n      cbn. (** now comes an adaptation of the code of [montrafotargetbicat_associator_aux1] from the former approach to monoidal categories *)\n      unfold param_distr_bicat_pentagon_eq_body_variant_RHS, montrafotargetbicat_disp_unit,\n        param_distr_bicat_triangle_eq_variant0_RHS, param_distr_bicat_pentagon_eq_body_RHS.\n      do 6 rewrite <- lwhisker_vcomp.\n      do 6 rewrite <- rwhisker_vcomp.\n      repeat rewrite <- vassocr.\n      match goal with | [ |- ?Hl1 • (_ • (?Hl2 • (_ • (?Hl3 • (_ • (?Hl4 • (_ • (?Hl5 • (_ • (?Hl6 • (_ • (?Hl7 • ?Hl8)))))))))))) = _]\n                        => set (l1 := Hl1); set (l2 := Hl2); set (l3 := Hl3); set (l4 := Hl4);\n                          set (l5 := Hl5); set (l6 := Hl6); set (l7 := Hl7); set (l8 := Hl8) end.\n      match goal with | [ |- _ = ?Hr1 • (?Hr2 • (_ • (?Hr3 • (_ • (?Hr4 • (_ • (?Hr5 • (_ • (?Hr6 • (_ • (?Hr7 • (_ • ?Hr8))))))))))))]\n                        => set (r1 := Hr1); set (r2 := Hr2); set (r3 := Hr3); set (r4 := Hr4);\n                          set (r5 := Hr5); set (r6 := Hr6); set (r7 := Hr7); set (r8 := Hr8) end.\n      change (H v1 ==> H' v1) in η1; change (H v2 ==> H' v2) in η2; change (H v3 ==> H' v3) in η3.\n      set (l1iso := lwhisker_with_μ_inv_inv2cell (v1 ⊗ v2) v3).\n      apply (lhs_left_invert_cell _ _ _ l1iso).\n      cbn.\n      clear l1 l1iso.\n      match goal with | [ |- _ = ?Hl1inv • _] => set (l1inv := Hl1inv) end.\n      etrans.\n      { rewrite vassocr.\n        apply maponpaths_2.\n        apply pathsinv0.\n        apply rwhisker_lwhisker. }\n      clear l2.\n      etrans.\n      { repeat rewrite <- vassocr. apply idpath. }\n      match goal with | [ |- ?Hl2' • _ = _] => set (l2' := Hl2') end.\n      cbn in l2'.\n      set (l2'iso := rwhisker_lwhisker_with_μ_inv_inv2cell v1 v2 v3).\n      apply (lhs_left_invert_cell _ _ _ l2'iso).\n      cbn.\n      clear l2' l2'iso.\n      etrans.\n      2: { repeat rewrite vassocr.\n           do 13 apply maponpaths_2.\n           unfold l1inv, r1.\n           do 2 rewrite lwhisker_vcomp.\n           apply maponpaths.\n           assert (lax_monoidal_functor_assoc_inst := fmonoidal_preservesassociativity FA'm v1 v2 v3).\n           cbn in lax_monoidal_functor_assoc_inst.\n           apply pathsinv0.\n           exact lax_monoidal_functor_assoc_inst.\n      }\n      clear l1inv r1.\n      etrans.\n      2: { do 13 apply maponpaths_2.\n           do 2 rewrite <- lwhisker_vcomp.\n           apply idpath. }\n      etrans.\n      2: { do 12 apply maponpaths_2.\n           repeat rewrite <- vassocr.\n           do 2 apply maponpaths.\n           unfold r2.\n           rewrite lwhisker_vcomp.\n           apply maponpaths.\n           set (auxbeinginverse := pr12 (fmonoidal_preservestensorstrongly FA'm v1 (v2 ⊗_{ Mon_V} v3))).\n           cbn in auxbeinginverse.\n           apply pathsinv0, auxbeinginverse. }\n      cbn.\n      clear r2.\n      rewrite lwhisker_id2.\n      rewrite id2_right.\n      etrans.\n      2: { do 10 apply maponpaths_2.\n           repeat rewrite <- vassocr.\n           apply maponpaths.\n           rewrite vassocr.\n           rewrite lwhisker_lwhisker.\n           rewrite <- vassocr.\n           apply maponpaths.\n           apply hcomp_hcomp'. }\n      unfold hcomp.\n      clear r3.\n      etrans.\n      2: { repeat rewrite <- vassocr. apply idpath. }\n      match goal with | [ |- _ = _ • (_ • (?Hr1'' • (?Hr3' • _)))]\n                        => set (r1'' := Hr1''); set (r3' := Hr3') end.\n      cbn in l5.\n      (*\n         lassociator (FA v1) (FA v2) G ▹ FA' v3 starts with FA v1 · (FA v2 · G) · FA' v3\n         l5 starts with FA v1 · FA v2 · G · FA' v3\n         FA v1 ◃ rassociator (FA v2) G (FA' v3) starts with FA v1 · (FA v2 · G · FA' v3)\n         r6 starts with FA v1 · (FA v2 · H v3)\n       *)\n      match goal with | [ |- _ • (  _ • ( _ • ( _ • ( _ • ?Hltail))))  =\n                              _ • (  _ • ( _ • ( _ • (  _ • ( _ • ( _ • ( _ • ?Hrtail)))))))]\n                        => set (ltail := Hltail); set (rtail := Hrtail) end.\n      assert (tailseq: lassociator (FA v1) (FA v2 · G) (FA' v3) • ltail = rtail).\n      2: { rewrite <- tailseq.\n           repeat rewrite vassocr.\n           apply maponpaths_2.\n           clear l5 l6 l7 l8 r6 r7 r8 ltail rtail tailseq η3.\n           (* l3 is close to r1'', l4 is close to r5, and r3' is close\n              to the inverse of r4 - we first treat the latter *)\n           etrans.\n           2: { repeat rewrite <- vassocr.\n                do 3 apply maponpaths.\n                repeat rewrite vassocr.\n                do 3 apply maponpaths_2.\n                rewrite <- vassocr.\n                unfold r4.\n                rewrite lwhisker_lwhisker_rassociator.\n                rewrite vassocr.\n                apply maponpaths_2.\n                unfold r3'.\n                rewrite lwhisker_vcomp.\n                apply maponpaths.\n                set (auxbeinginverse := pr12 (fmonoidal_preservestensorstrongly FA'm v2 v3)).\n                cbn in auxbeinginverse.\n                apply pathsinv0, auxbeinginverse. }\n           cbn.\n           clear r3' r4.\n           rewrite lwhisker_id2.\n           rewrite id2_left.\n           (* now plain reasoning in one bicategory *)\n           etrans.\n           2: { repeat rewrite <- vassocr.\n                do 5 apply maponpaths.\n                apply pathsinv0, rwhisker_lwhisker. }\n           clear r5.\n           etrans.\n           2: { repeat rewrite vassocr. apply idpath. }\n           apply maponpaths_2.\n           clear l4.\n           assert (l3ok := rwhisker_rwhisker (FA' v2) (FA' v3) η1).\n           apply (rhs_left_inv_cell _ _ _ (is_invertible_2cell_lassociator _ _ _)) in l3ok.\n           cbn in l3ok.\n           assert (l3okbetter: l3 = rassociator (G · FA' v1) (FA' v2) (FA' v3)\n                                                • (r1'' • lassociator (FA v1 · G) (FA' v2) (FA' v3))).\n           { apply l3ok. }\n           rewrite l3okbetter.\n           clear l3 l3ok l3okbetter.\n           repeat rewrite <- vassocr.\n           match goal with | [ |- _ • ( _ • ( _ • ( _ • ?Hltail2)))  = _ • ( _ • ( _ • ?Hrtail2))]\n                             => set (ltail2 := Hltail2); set (rtail2 := Hrtail2) end.\n           assert (tails2eq: ltail2 = rtail2).\n           2: { rewrite tails2eq.\n                repeat rewrite vassocr.\n                do 2 apply maponpaths_2.\n                clear r1'' ltail2 rtail2 tails2eq.\n                rewrite <- hcomp_identity_left.\n                rewrite <- hcomp_identity_right.\n                apply pathsinv0.\n                assert (pentagon_inst := inverse_pentagon_5 (FA' v3) (FA' v2) (FA' v1) G).\n                cbn in pentagon_inst.\n                etrans.\n                { exact pentagon_inst. }\n                repeat rewrite vassocr.\n                apply idpath.\n                (* to find the right pentagon law - there are: associativity_pentagon, pentagon, pentagon_2,\n                   inverse_pentagon, inverse_pentagon_2, inverse_pentagon_3, inverse_pentagon_4,\n                   inverse_pentagon_5, inverse_pentagon_6 *)\n           }\n           unfold ltail2, rtail2.\n           clear ltail2 rtail2 η1 η2 r1''.\n           assert (pentagon_inst := inverse_pentagon_4 (FA' v3) (FA' v2) G (FA v1)).\n           apply pathsinv0 in pentagon_inst.\n           rewrite vassocr in pentagon_inst.\n           apply (rhs_right_inv_cell _ _ _ (is_invertible_2cell_rassociator _ _ _)) in pentagon_inst.\n           cbn in pentagon_inst.\n           rewrite <- vassocr in pentagon_inst.\n           rewrite hcomp_identity_left in pentagon_inst.\n           rewrite hcomp_identity_right in pentagon_inst.\n           exact pentagon_inst.\n      }\n      (* now the second half of the proof - however with no need for inversion of \"monoidal\" arrows *)\n      clear l3 l4 r4 r5 r1'' r3' η1 η2.\n      unfold ltail; clear ltail.\n      etrans.\n      { do 2 apply maponpaths.\n        repeat rewrite vassocr.\n        do 3 apply maponpaths_2.\n        unfold l5.\n        rewrite rwhisker_rwhisker_alt.\n        rewrite <- vassocr.\n        apply maponpaths.\n        apply hcomp_hcomp'. }\n      clear l5 l6.\n      unfold hcomp'.\n      etrans.\n      { do 2 apply maponpaths.\n        repeat rewrite <- vassocr.\n        do 2 apply maponpaths.\n        repeat rewrite vassocr.\n        do 2 apply maponpaths_2.\n        apply pathsinv0, rwhisker_rwhisker. }\n      etrans.\n      { repeat rewrite <- vassocr.\n        do 5 apply maponpaths.\n        unfold l7, l8.\n        do 2 rewrite rwhisker_vcomp.\n        apply maponpaths.\n        assert (lax_monoidal_functor_assoc_inst := fmonoidal_preservesassociativity FAm v1 v2 v3).\n        cbn in lax_monoidal_functor_assoc_inst.\n        apply pathsinv0.\n        rewrite <- vassocr in lax_monoidal_functor_assoc_inst.\n        apply pathsinv0.\n        exact lax_monoidal_functor_assoc_inst.\n      }\n      clear l7 l8.\n      unfold rtail; clear rtail.\n      do 2 rewrite <- rwhisker_vcomp.\n      repeat rewrite vassocr.\n      apply maponpaths_2.\n      clear r8.\n      etrans.\n      2: { repeat rewrite <- vassocr.\n           do 3 apply maponpaths.\n           apply pathsinv0, rwhisker_lwhisker. }\n      clear r7.\n      etrans.\n      2: { repeat rewrite vassocr. apply idpath. }\n      apply maponpaths_2.\n      cbn.\n      (* now plain reasoning in one bicategory *)\n      assert (r6ok := lwhisker_lwhisker (FA v1) (FA v2) η3).\n      apply (rhs_right_inv_cell _ _ _ (is_invertible_2cell_lassociator _ _ _)) in r6ok.\n      cbn in r6ok.\n      assert (r6okbetter: r6 = (lassociator (FA v1) (FA v2) (G · FA' v3)\n                                            • (FA v1 · FA v2 ◃ η3))\n                                 • rassociator (FA v1) (FA v2) (FA v3 · G)).\n      { apply r6ok. }\n      rewrite r6okbetter.\n      clear r6 r6ok r6okbetter.\n      repeat rewrite <- vassocr.\n      match goal with | [ |- _ • ( _ • ( _ • ( _ • ?Hltail2)))  = _ • ( _ • ( _ • ?Hrtail2))]\n                        => set (ltail2 := Hltail2); set (rtail2 := Hrtail2) end.\n      assert (tails2eq: ltail2 = rtail2).\n      2: { rewrite tails2eq.\n           repeat rewrite vassocr.\n           do 2 apply maponpaths_2.\n           clear ltail2 rtail2 tails2eq.\n           rewrite <- hcomp_identity_left.\n           rewrite <- hcomp_identity_right.\n           apply pathsinv0.\n           assert (pentagon_inst := inverse_pentagon_5 (FA' v3) G (FA v2) (FA v1)).\n           etrans.\n           { exact pentagon_inst. }\n           repeat rewrite vassocr.\n           apply idpath.\n      }\n      unfold ltail2, rtail2.\n      rewrite <- hcomp_identity_left.\n      rewrite <- hcomp_identity_right.\n      clear ltail2 rtail2 η3.\n      assert (pentagon_inst := inverse_pentagon_4 G (FA v3) (FA v2) (FA v1)).\n      apply pathsinv0 in pentagon_inst.\n      rewrite vassocr in pentagon_inst.\n      apply (rhs_right_inv_cell _ _ _ (is_invertible_2cell_rassociator _ _ _)) in pentagon_inst.\n      cbn in pentagon_inst.\n      rewrite <- vassocr in pentagon_inst.\n      exact pentagon_inst.\n    Qed.\n\n    Lemma montrafotargetbicat_disp_associatorinv_data: disp_associatorinv_data montrafotargetbicat_disp_tensor.\n    Proof.\n      intros v1 v2 v3 η1 η2 η3.\n      cbn. (** now comes an adaptation of the code of [montrafotargetbicat_associator_aux2] from the former approach to monoidal categories *)\n      unfold param_distr_bicat_pentagon_eq_body_variant_RHS, montrafotargetbicat_disp_unit,\n        param_distr_bicat_triangle_eq_variant0_RHS, param_distr_bicat_pentagon_eq_body_RHS.\n      do 6 rewrite <- lwhisker_vcomp.\n      do 6 rewrite <- rwhisker_vcomp.\n      repeat rewrite <- vassocr.\n      match goal with | [ |- ?Hl1 • (_ • (?Hl2 • (_ • (?Hl3 • (_ • (?Hl4 • (_ • (?Hl5 • (_ • (?Hl6 • (_ • (?Hl7 • ?Hl8)))))))))))) = _]\n                        => set (l1 := Hl1); set (l2 := Hl2); set (l3 := Hl3); set (l4 := Hl4);\n                          set (l5 := Hl5); set (l6 := Hl6); set (l7 := Hl7); set (l8 := Hl8) end.\n      match goal with | [ |- _ = ?Hr1 • (?Hr2 • (_ • (?Hr3 • (_ • (?Hr4 • (_ • (?Hr5 • (_ • (?Hr6 • (_ • (?Hr7 • (_ • ?Hr8))))))))))))]\n                        => set (r1 := Hr1); set (r2 := Hr2); set (r3 := Hr3); set (r4 := Hr4);\n                          set (r5 := Hr5); set (r6 := Hr6); set (r7 := Hr7); set (r8 := Hr8) end.\n      change (H v1 ==> H' v1) in η1; change (H v2 ==> H' v2) in η2; change (H v3 ==> H' v3) in η3.\n      (* cbn in * |- *. *)\n      set (l8iso := rwhisker_with_invassociator_inv2cell v1 v2 v3).\n      etrans.\n      { repeat rewrite vassocr. apply idpath. }\n      apply (lhs_right_invert_cell _ _ _ l8iso).\n      cbn.\n      match goal with | [ |-  _ = _ • ?Hl8inv ] => set (l8inv := Hl8inv) end.\n      clear l8 l8iso.\n      etrans.\n      2: { repeat rewrite vassocr.\n           do 3 apply maponpaths_2.\n           repeat rewrite <- vassocr.\n           do 9 apply maponpaths.\n           rewrite vassocr.\n           etrans.\n           2: { apply maponpaths_2.\n                apply pathsinv0, rwhisker_rwhisker_alt. }\n           cbn.\n           repeat rewrite <- vassocr.\n           apply maponpaths.\n           apply pathsinv0, hcomp_hcomp'. }\n      unfold hcomp'.\n      clear r6 r7.\n      etrans.\n      2: { repeat rewrite <- vassocr.\n           do 11 apply maponpaths.\n           rewrite vassocr.\n           rewrite <- rwhisker_rwhisker.\n           rewrite <- vassocr.\n           apply maponpaths.\n           unfold r8, l8inv.\n           do 2 rewrite rwhisker_vcomp.\n           apply maponpaths.\n           assert (lax_monoidal_functor_assoc_inst := fmonoidal_preservesassociativity FAm v1 v2 v3).\n           cbn in lax_monoidal_functor_assoc_inst.\n           apply pathsinv0.\n           rewrite <- vassocr in lax_monoidal_functor_assoc_inst.\n           exact lax_monoidal_functor_assoc_inst.\n      }\n      clear r8 l8inv.\n      do 2 rewrite <- rwhisker_vcomp.\n      etrans.\n      2: { repeat rewrite vassocr. apply idpath. }\n      apply maponpaths_2.\n      clear l7.\n      etrans.\n      { rewrite <- vassocr.\n        apply maponpaths.\n        apply rwhisker_lwhisker. }\n      clear l6.\n      repeat rewrite vassocr.\n      apply maponpaths_2.\n      cbn.\n      match goal with | [ |- ((((?Hlhead • _) • _) • _) • _) • _  =\n                              (((((?Hrhead  • _) • _) • _) • _) • _) • _ ]\n                        => set (lhead := Hlhead); set (rhead := Hrhead) end.\n      assert (headsok: lhead  = rhead • rassociator (FA v1) (G · FA' v2) (FA' v3)).\n      2: { (* first deal with the reasoning confined to the bicategory *)\n        rewrite headsok.\n        repeat rewrite <- vassocr.\n        apply maponpaths.\n        clear η1 l1 l2 l3 r1 r2 r3 r4 lhead rhead headsok.\n        etrans.\n        { rewrite vassocr.\n          apply maponpaths_2.\n          apply rwhisker_lwhisker_rassociator. }\n        etrans.\n        { repeat rewrite <- vassocr. apply idpath. }\n        apply maponpaths.\n        clear η2 l4 r5.\n        (* now as for r6 in the proof of [montrafotargetbicat_associator_aux1] *)\n        assert (l5ok := lwhisker_lwhisker (FA v1) (FA v2) η3).\n        apply (rhs_right_inv_cell _ _ _ (is_invertible_2cell_lassociator _ _ _)) in l5ok.\n        cbn in l5ok.\n        assert (l5okbetter: l5 = (lassociator (FA v1) (FA v2) (G · FA' v3)\n                                              • (FA v1 · FA v2 ◃ η3))\n                                   • rassociator (FA v1) (FA v2) (FA v3 · G)).\n        { apply l5ok. }\n        rewrite l5okbetter.\n        clear l5 l5ok l5okbetter.\n        repeat rewrite <- vassocr.\n        match goal with | [ |- _ • ( _ • ( _ • ( _ • ?Hltail2)))  =\n                                _ • ( _ • ( _ • ?Hrtail2))]\n                          => set (ltail2 := Hltail2); set (rtail2 := Hrtail2) end.\n        assert (tails2eq: ltail2 = rtail2).\n        2: { rewrite tails2eq.\n             repeat rewrite vassocr.\n             do 2 apply maponpaths_2.\n             clear ltail2 rtail2 tails2eq.\n             rewrite <- hcomp_identity_left.\n             rewrite <- hcomp_identity_right.\n             assert (pentagon_inst := inverse_pentagon_5 (FA' v3) G (FA v2) (FA v1)).\n             apply pathsinv0, (rhs_left_inv_cell _ _ _ (is_invertible_2cell_lassociator _ _ _)) in pentagon_inst.\n             apply pathsinv0 in pentagon_inst.\n             cbn in pentagon_inst.\n             rewrite vassocr in pentagon_inst.\n             exact pentagon_inst.\n        }\n        unfold ltail2, rtail2.\n        rewrite <- hcomp_identity_left.\n        rewrite <- hcomp_identity_right.\n        clear ltail2 rtail2 η3.\n        assert (pentagon_inst := inverse_pentagon_4 G (FA v3) (FA v2) (FA v1)).\n        apply pathsinv0 in pentagon_inst.\n        rewrite vassocr in pentagon_inst.\n        apply (rhs_right_inv_cell _ _ _ (is_invertible_2cell_rassociator _ _ _)) in pentagon_inst.\n        cbn in pentagon_inst.\n        rewrite <- vassocr in pentagon_inst.\n        apply pathsinv0 in pentagon_inst.\n        exact pentagon_inst.\n      }\n      clear η2 η3 l4 l5 r5.\n      (* now the second half of the proof - however with even more need for inversion of \"monoidal\" arrows *)\n      unfold lhead. clear lhead.\n      etrans.\n      { apply maponpaths_2.\n        repeat rewrite <- vassocr.\n        do 2 apply maponpaths.\n        unfold l3.\n        rewrite lwhisker_lwhisker_rassociator.\n        rewrite vassocr.\n        apply maponpaths_2.\n        apply hcomp_hcomp'. }\n      unfold hcomp'.\n      clear l2 l3.\n      cbn.\n      unfold rhead. clear rhead.\n      (* now as for l5 *)\n      assert (r4ok := rwhisker_rwhisker (FA' v2) (FA' v3) η1).\n      apply (rhs_left_inv_cell _ _ _ (is_invertible_2cell_lassociator _ _ _)) in r4ok.\n      cbn in r4ok.\n      assert (r4okbetter: r4 = rassociator (G · FA' v1) (FA' v2) (FA' v3)\n        • ((η1 ▹ FA' v2 · FA' v3) • lassociator (FA v1 · G) (FA' v2) (FA' v3))).\n      { apply r4ok. }\n      rewrite r4okbetter.\n      clear r4 r4ok r4okbetter.\n      repeat rewrite <- vassocr.\n      match goal with | [ |- _ • ( _ • ( _ • ( _ • ?Hltail3)))  =\n                              _ • ( _ • ( _ • ( _ • (_ • ( _ • ( _ • ?Hrtail3))))))]\n                        => set (ltail3 := Hltail3); set (rtail3 := Hrtail3) end.\n      assert (tails3eq: ltail3 = rtail3).\n      { (* first deal with the reasoning confined to the bicategory *)\n        unfold ltail3, rtail3.\n        rewrite <- hcomp_identity_left.\n        rewrite <- hcomp_identity_right.\n        apply inverse_pentagon_4.\n      }\n      rewrite tails3eq.\n      repeat rewrite vassocr.\n      do 2 apply maponpaths_2.\n      clear η1 ltail3 rtail3 tails3eq.\n      etrans.\n      2: { do 2 apply maponpaths_2.\n           rewrite <- vassocr.\n           apply maponpaths.\n           apply rwhisker_lwhisker. }\n      clear r3.\n      etrans.\n      { rewrite <- vassocr.\n        apply maponpaths.\n        apply pathsinv0, lwhisker_lwhisker. }\n      repeat rewrite vassocr.\n      unfold l1, r1, r2.\n      do 3 rewrite lwhisker_vcomp.\n      clear l1 r1 r2.\n      match goal with | [ |- ?Hlhead2 • _  = ((?Hrhead2  • _) • _) • _ ]\n                        => set (lhead2 := Hlhead2); set (rhead2 := Hrhead2) end.\n      assert (heads2ok: lhead2 = rhead2 • (G ◃ rassociator (FA' v1) (FA' v2) (FA' v3))).\n      2: { (* first deal with the reasoning confined to the bicategory *)\n        rewrite heads2ok.\n        repeat rewrite <- vassocr.\n        apply maponpaths.\n        clear lhead2 rhead2 heads2ok.\n        cbn.\n        rewrite <- hcomp_identity_left.\n        rewrite <- hcomp_identity_right.\n        apply inverse_pentagon_5.\n      }\n      unfold rhead2.\n      rewrite lwhisker_vcomp.\n      apply maponpaths.\n      clear lhead2 rhead2.\n      assert (lax_monoidal_functor_assoc_inst := fmonoidal_preservesassociativity FA'm v1 v2 v3).\n      cbn in lax_monoidal_functor_assoc_inst.\n      transparent assert (aux1iso : (invertible_2cell (FA' (v1 ⊗ (v2 ⊗ v3)))\n                                                      (FA' v1 · FA' (v2 ⊗ v3)))).\n      { use make_invertible_2cell.\n        - exact (pr1 (fmonoidal_preservestensorstrongly FA'm v1 (v2 ⊗ v3))).\n        - change (is_z_isomorphism (pr1 (fmonoidal_preservestensorstrongly FA'm v1 (v2 ⊗ v3)))).\n          apply is_z_isomorphism_inv.\n      }\n      apply (lhs_left_invert_cell _ _ _ aux1iso).\n      cbn.\n      etrans.\n      2: { repeat rewrite vassocr. apply idpath. }\n      apply pathsinv0, lassociator_to_rassociator_post.\n      transparent assert (aux2iso : (invertible_2cell (FA' (v1 ⊗ v2) · FA' v3)\n                                                      ((FA' v1 · FA' v2) · FA' v3))).\n      { use make_invertible_2cell.\n        - exact ((pr1 (fmonoidal_preservestensorstrongly FA'm v1 v2)) ▹ FA' v3).\n        - is_iso.\n          change (is_z_isomorphism  (pr1 (fmonoidal_preservestensorstrongly FA'm v1 v2))).\n          apply is_z_isomorphism_inv.\n      }\n      apply (lhs_right_invert_cell _ _ _ aux2iso).\n      cbn.\n      transparent assert (aux3iso : (invertible_2cell (FA' ((v1 ⊗ v2) ⊗ v3))\n                                                      (FA' (v1 ⊗ v2) · FA' v3))).\n      { use make_invertible_2cell.\n        - exact (pr1 (fmonoidal_preservestensorstrongly FA'm (v1 ⊗ v2) v3)).\n        - change (is_z_isomorphism (pr1 (fmonoidal_preservestensorstrongly FA'm (v1 ⊗_{ Mon_V} v2) v3))).\n          apply is_z_isomorphism_inv.\n      }\n      apply (lhs_right_invert_cell _ _ _ aux3iso).\n      cbn.\n      transparent assert (aux4iso : (invertible_2cell (FA' (v1 ⊗ (v2 ⊗ v3)))\n                                                      (FA' ((v1 ⊗ v2) ⊗ v3)))).\n      { use make_invertible_2cell.\n        - exact (# FA' (αinv_{ Mon_V} v1 v2 v3)).\n        - change (is_z_isomorphism (# FA' (αinv_{ Mon_V} v1 v2 v3))).\n          apply functor_on_is_z_isomorphism.\n          exists (α_{ Mon_V} v1 v2 v3).\n          destruct (monoidal_associatorisolaw Mon_V v1 v2 v3); split; assumption.\n      }\n      apply (lhs_right_invert_cell _ _ _ aux4iso).\n      cbn.\n      repeat rewrite <- vassocr.\n      transparent assert (aux5iso : (invertible_2cell (FA' v1 · FA' (v2 ⊗ v3))\n                                                      (FA' v1 · (FA' v2 · FA' v3)))).\n      { use make_invertible_2cell.\n        - exact (FA' v1 ◃ (pr1 (fmonoidal_preservestensorstrongly FA'm v2 v3))).\n        - is_iso.\n          change (is_z_isomorphism (pr1 (fmonoidal_preservestensorstrongly FA'm v2 v3))).\n          apply is_z_isomorphism_inv.\n      }\n      apply pathsinv0, (lhs_left_invert_cell _ _ _ aux5iso).\n      cbn.\n      clear aux1iso aux2iso aux3iso aux4iso aux5iso.\n      apply pathsinv0, rassociator_to_lassociator_pre.\n      apply pathsinv0.\n      repeat rewrite vassocr.\n      exact lax_monoidal_functor_assoc_inst.\n     Qed.\n\n    Lemma montrafotargetbicat_disp_associator_iso: disp_associator_iso montrafotargetbicat_disp_associator_data montrafotargetbicat_disp_associatorinv_data.\n    Proof.\n      intros v1 v2 v3 η1 η2 η3.\n      (** now we benefit from working in a displayed monoidal category *)\n      split; apply trafotargetbicat_disp_cells_isaprop.\n    Qed.\n\n    Lemma montrafotargetbicat_disp_associator_law: disp_associator_law montrafotargetbicat_disp_associator_data montrafotargetbicat_disp_associatorinv_data.\n    Proof.\n      (** now we benefit from working in a displayed monoidal category *)\n      repeat (split; try (red; intros; apply trafotargetbicat_disp_cells_isaprop)); try apply trafotargetbicat_disp_cells_isaprop.\n    Qed.\n\n    Lemma montrafotargetbicat_disp_leftunitorinv_data: disp_leftunitorinv_data montrafotargetbicat_disp_tensor montrafotargetbicat_disp_unit.\n    Proof.\n      intros v η.\n      cbn. (** now comes an adaptation of the code of [montrafotargetbicat_left_unitor_aux2] from the former approach to monoidal categories *)\n      unfold param_distr_bicat_pentagon_eq_body_variant_RHS, montrafotargetbicat_disp_unit,\n        param_distr_bicat_triangle_eq_variant0_RHS, param_distr_bicat_pentagon_eq_body_RHS.\n      do 3 rewrite <- rwhisker_vcomp.\n      repeat rewrite <- vassocr.\n      apply pathsinv0.\n      match goal with | [ |- ?Hl1 • (?Hl2 • (_ • (?Hl3 • (_ • (_ • (?Hl4 • (_ • (?Hl5 • (_ • ?Hl6))))))))) = _ • ?Hr2]\n                        => set (l1 := Hl1); set (l2 := Hl2); set (l3 := Hl3); set (l4 := Hl4);\n                          set (l5 := Hl5); set (l6 := Hl6); set (r2 := Hr2) end.\n      change (H v ==> H' v) in η.\n      set (l1iso := lwhisker_with_invlunitor_inv2cell v).\n      apply (lhs_left_invert_cell _ _ _ l1iso).\n      cbn.\n      set (l2iso := lwhisker_with_μ_inv_inv2cell I_{Mon_V} v).\n      apply (lhs_left_invert_cell _ _ _ l2iso).\n      cbn.\n      apply (lhs_left_invert_cell _ _ _ (is_invertible_2cell_lassociator _ _ _)).\n      cbn.\n      set (l3iso := lwhisker_rwhisker_with_ϵ_inv_inv2cell v).\n      apply (lhs_left_invert_cell _ _ _ l3iso).\n      cbn.\n      match goal with | [ |- _ = ?Hl3inv • (_ • (?Hl2inv • (?Hl1inv • _)))]\n                        => set (l1inv := Hl1inv); set (l2inv := Hl2inv); set (l3inv := Hl3inv) end.\n      clear l1 l2 l3 l1iso l2iso l3iso.\n      etrans.\n      2: { repeat rewrite vassocr.\n           do 4 apply maponpaths_2.\n           unfold l3inv.\n           apply rwhisker_lwhisker_rassociator. }\n      etrans.\n      2: { do 2 apply maponpaths_2.\n           repeat rewrite <- vassocr.\n           apply maponpaths.\n           unfold l2inv, l1inv.\n           do 2 rewrite lwhisker_vcomp.\n           apply maponpaths.\n           rewrite vassocr.\n           assert (lax_monoidal_functor_unital_inst := fmonoidal_preservesleftunitality FA'm v).\n           cbn in lax_monoidal_functor_unital_inst.\n           apply pathsinv0.\n           exact lax_monoidal_functor_unital_inst.\n      }\n      clear l1inv l2inv l3inv.\n      etrans.\n      { do 2 apply maponpaths.\n        repeat rewrite vassocr.\n        do 3 apply maponpaths_2.\n        apply rwhisker_rwhisker_alt. }\n      cbn.\n      etrans.\n      { do 2 apply maponpaths.\n        do 2 apply maponpaths_2.\n        rewrite <- vassocr.\n        apply maponpaths.\n        apply hcomp_hcomp'. }\n      clear l4 l5.\n      unfold hcomp'.\n      set (r2iso := rwhisker_with_invlunitor_inv2cell v).\n      apply pathsinv0.\n      apply (lhs_right_invert_cell _ _ _ r2iso).\n      apply pathsinv0.\n      cbn.\n      clear r2 r2iso.\n      etrans.\n      { repeat rewrite <- vassocr.\n        do 4 apply maponpaths.\n        rewrite vassocr.\n        rewrite <- rwhisker_rwhisker.\n        repeat rewrite <- vassocr.\n        apply maponpaths.\n        unfold l6.\n        do 2 rewrite rwhisker_vcomp.\n        apply maponpaths.\n        apply pathsinv0.\n        rewrite vassocr.\n        assert (lax_monoidal_functor_unital_inst := fmonoidal_preservesleftunitality FAm v).\n        cbn in lax_monoidal_functor_unital_inst.\n        apply pathsinv0.\n        exact lax_monoidal_functor_unital_inst.\n      }\n      clear l6. (* now only admin tasks in bicategory: the goal is the same as at that\n                   position in [montrafotargetbicat_left_unitor_aux1] *)\n      rewrite lunitor_lwhisker.\n      apply maponpaths.\n      apply (lhs_left_invert_cell _ _ _ (rwhisker_with_linvunitor_inv2cell v)).\n      cbn.\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    Qed.\n\n    Lemma montrafotargetbicat_disp_leftunitor_iso: disp_leftunitor_iso montrafotargetbicat_disp_leftunitor_data montrafotargetbicat_disp_leftunitorinv_data.\n    Proof.\n      intros v η.\n      (** now we benefit from working in a displayed monoidal category *) split; apply trafotargetbicat_disp_cells_isaprop.\n    Qed.\n\n    Lemma montrafotargetbicat_disp_leftunitor_law: disp_leftunitor_law montrafotargetbicat_disp_leftunitor_data montrafotargetbicat_disp_leftunitorinv_data.\n    Proof.\n      split.\n      - red. intros. apply trafotargetbicat_disp_cells_isaprop.\n      - exact montrafotargetbicat_disp_leftunitor_iso.\n    Qed.\n\n    Lemma montrafotargetbicat_disp_rightunitorinv_data: disp_rightunitorinv_data montrafotargetbicat_disp_tensor montrafotargetbicat_disp_unit.\n    Proof.\n      intros v η.\n      apply pathsinv0. cbn. (** now comes an adaptation of the code of [montrafotargetbicat_right_unitor_aux2] from the former approach to monoidal categories *)\n      unfold param_distr_bicat_pentagon_eq_body_variant_RHS, montrafotargetbicat_disp_unit,\n        param_distr_bicat_triangle_eq_variant0_RHS, param_distr_bicat_pentagon_eq_body_RHS.\n      do 3 rewrite <- lwhisker_vcomp.\n      repeat rewrite <- vassocr.\n      match goal with | [ |- ?Hl1 • (?Hl2 • (_ • (?Hl3 • (_ • (?Hl4 • (_ • (_ • (?Hl5 • (_ • ?Hl6))))))))) = _ • ?Hr2]\n                        => set (l1 := Hl1); set (l2 := Hl2); set (l3 := Hl3); set (l4 := Hl4);\n                          set (l5 := Hl5); set (l6 := Hl6); set (r2 := Hr2) end.\n      change (H v ==> H' v) in η.\n      set (l1iso := lwhisker_with_invrunitor_inv2cell v).\n      apply (lhs_left_invert_cell _ _ _ l1iso).\n      cbn.\n      clear l1 l1iso.\n      set (l2iso := lwhisker_with_μ_inv_inv2cell v I_{Mon_V}).\n      apply (lhs_left_invert_cell _ _ _ l2iso).\n      cbn.\n      clear l2 l2iso.\n      apply (lhs_left_invert_cell _ _ _ (is_invertible_2cell_lassociator _ _ _)).\n      cbn.\n      etrans.\n      2: { repeat rewrite <- vassocr.\n           apply maponpaths.\n           rewrite vassocr.\n           apply maponpaths_2.\n           rewrite lwhisker_vcomp.\n           apply maponpaths.\n           assert (lax_monoidal_functor_unital_inst := fmonoidal_preservesrightunitality FA'm v).\n           cbn in lax_monoidal_functor_unital_inst.\n           apply pathsinv0 in lax_monoidal_functor_unital_inst.\n           set (aux1iso := lwhisker_with_ϵ_inv2cell v).\n           rewrite <- vassocr in lax_monoidal_functor_unital_inst.\n           apply pathsinv0 in lax_monoidal_functor_unital_inst.\n           apply (rhs_left_inv_cell _ _ _ aux1iso) in lax_monoidal_functor_unital_inst.\n           unfold inv_cell in lax_monoidal_functor_unital_inst.\n           apply pathsinv0.\n           exact lax_monoidal_functor_unital_inst.\n      }\n      cbn. (* same goal as in [montrafotargetbicat_right_unitor_aux1],\n              except l_i -> l_{i+1} for i=2,3,4,5, and l6 becomes r2 on the other side *)\n      etrans.\n      2: { rewrite vassocr.\n           apply maponpaths_2.\n           rewrite <- lwhisker_vcomp.\n           rewrite vassocr.\n           apply maponpaths_2.\n           apply pathsinv0.\n           apply lwhisker_lwhisker_rassociator. }\n      etrans.\n      2: { repeat rewrite <- vassocr.\n           apply maponpaths.\n           rewrite vassocr.\n           apply maponpaths_2.\n           apply pathsinv0, runitor_triangle. }\n      etrans.\n      2: { apply maponpaths.\n           rewrite vassocr.\n           rewrite <- vcomp_runitor.\n           apply idpath. }\n      etrans.\n      2: { rewrite vassocr.\n           apply maponpaths_2.\n           rewrite vassocr.\n           apply maponpaths_2.\n           apply hcomp_hcomp'. }\n      unfold hcomp.\n      etrans.\n      2: { repeat rewrite <- vassocr. apply idpath. }\n      apply maponpaths.\n      clear l3.\n      etrans.\n      { repeat rewrite vassocr.\n        do 5 apply maponpaths_2.\n        apply lwhisker_lwhisker_rassociator. }\n      repeat rewrite <- vassocr.\n      apply maponpaths.\n      clear l4.\n      cbn.\n      etrans.\n      { repeat rewrite vassocr.\n        do 4 apply maponpaths_2.\n        apply runitor_triangle. }\n      (* now we put an end to the diversion from the goal in [montrafotargetbicat_right_unitor_aux1] *)\n      set (r2iso := rwhisker_with_invrunitor_inv2cell v).\n      apply pathsinv0, (lhs_right_invert_cell _ _ _ r2iso), pathsinv0.\n      cbn.\n      clear r2 r2iso.\n      (* resume analogous proof *)\n      etrans.\n      2: { apply id2_right. }\n      repeat rewrite <- vassocr.\n      apply maponpaths.\n      etrans.\n      { apply maponpaths.\n        rewrite vassocr.\n        apply maponpaths_2.\n        apply rwhisker_lwhisker. }\n      cbn.\n      clear l5.\n      etrans.\n      { apply maponpaths.\n        rewrite <- vassocr.\n        apply maponpaths.\n        unfold l6.\n        do 2 rewrite rwhisker_vcomp.\n        apply maponpaths.\n        assert (lax_monoidal_functor_unital_inst := fmonoidal_preservesrightunitality FAm v).\n        cbn in lax_monoidal_functor_unital_inst.\n        apply pathsinv0 in lax_monoidal_functor_unital_inst.\n        rewrite vassocr.\n        apply pathsinv0.\n        exact lax_monoidal_functor_unital_inst.\n      }\n      clear l6. (* now only pure bicategory reasoning *)\n      set (auxiso := lwhisker_with_linvunitor_inv2cell v).\n      apply (lhs_left_invert_cell _ _ _ auxiso).\n      cbn.\n      rewrite id2_right.\n      clear auxiso.\n      apply runitor_rwhisker.\n    Qed.\n\n    Lemma montrafotargetbicat_disp_rightunitor_iso: disp_rightunitor_iso montrafotargetbicat_disp_rightunitor_data montrafotargetbicat_disp_rightunitorinv_data.\n    Proof.\n      intros v η.\n      (** now we benefit from working in a displayed monoidal category *) split; apply trafotargetbicat_disp_cells_isaprop.\n    Qed.\n\n    Lemma montrafotargetbicat_disp_rightunitor_law: disp_rightunitor_law montrafotargetbicat_disp_rightunitor_data montrafotargetbicat_disp_rightunitorinv_data.\n    Proof.\n      split.\n      - red. intros. apply trafotargetbicat_disp_cells_isaprop.\n      - exact montrafotargetbicat_disp_rightunitor_iso.\n    Qed.\n\n    Definition montrafotargetbicat_disp_monoidal_data: disp_monoidal_data montrafotargetbicat_disp Mon_V.\n    Proof.\n      exists montrafotargetbicat_disp_tensor.\n      exists montrafotargetbicat_disp_unit.\n      exists montrafotargetbicat_disp_leftunitor_data.\n      exists montrafotargetbicat_disp_leftunitorinv_data.\n      exists montrafotargetbicat_disp_rightunitor_data.\n      exists montrafotargetbicat_disp_rightunitorinv_data.\n      exists montrafotargetbicat_disp_associator_data.\n      exact montrafotargetbicat_disp_associatorinv_data.\n    Defined.\n\n    Definition montrafotargetbicat_disp_monoidal: disp_monoidal montrafotargetbicat_disp Mon_V.\n    Proof.\n      exists montrafotargetbicat_disp_monoidal_data.\n      split.\n      { exact montrafotargetbicat_disp_leftunitor_law. }\n      split; [ exact montrafotargetbicat_disp_rightunitor_law |].\n      split; [ exact montrafotargetbicat_disp_associator_law |].\n      (** now we benefit from working in a displayed monoidal category *)\n      split; red; intros; apply trafotargetbicat_disp_cells_isaprop.\n    Defined.\n\n    Definition parameterized_distributivity_bicat_nat : UU := H ⟹ H'.\n    Definition parameterized_distributivity_bicat_nat_funclass (δ : parameterized_distributivity_bicat_nat):\n      ∏ v : V, H v --> H' v := pr1 δ.\n    Coercion parameterized_distributivity_bicat_nat_funclass : parameterized_distributivity_bicat_nat >-> Funclass.\n\n    Definition param_distr_bicat_triangle_eq_variant0 (δ : parameterized_distributivity_bicat_nat): UU :=\n      δ I_{Mon_V} = param_distr_bicat_triangle_eq_variant0_RHS.\n\n    Definition param_distr_bicat_triangle_eq (δ : parameterized_distributivity_bicat_nat): UU :=\n      (G ◃ fmonoidal_preservesunit FA'm)  • δ I_{Mon_V}  =\n        ((runitor G : G · I_{ monoidal_from_bicat_and_ob a0'} ==> G)\n           • (linvunitor G : G ==> I_{ monoidal_from_bicat_and_ob a0} · G))\n          • (fmonoidal_preservesunit FAm ▹ G).\n\n    Lemma param_distr_bicat_triangle_eq_variant0_follows (δ : parameterized_distributivity_bicat_nat):\n      param_distr_bicat_triangle_eq δ -> param_distr_bicat_triangle_eq_variant0 δ.\n    Proof.\n      intro Hyp.\n      red.\n      unfold param_distr_bicat_triangle_eq_variant0_RHS.\n      apply pathsinv0, (lhs_left_invert_cell _ _ _ lwhisker_with_ϵ_inv2cell_bis).\n      apply pathsinv0.\n      exact Hyp.\n    Qed.\n\n    Lemma param_distr_bicat_triangle_eq_variant0_implies (δ : parameterized_distributivity_bicat_nat):\n      param_distr_bicat_triangle_eq_variant0 δ -> param_distr_bicat_triangle_eq δ.\n    Proof.\n      intro Hyp.\n      red in Hyp.\n      unfold param_distr_bicat_triangle_eq_variant0_RHS in Hyp.\n      apply pathsinv0, (rhs_left_inv_cell _ _ _ lwhisker_with_ϵ_inv2cell_bis), pathsinv0 in Hyp.\n      exact Hyp.\n    Qed.\n\n    Definition param_distr_bicat_pentagon_eq_body_variant (δ : parameterized_distributivity_bicat_nat) (v w : V): UU :=\n      δ (v ⊗ w) = param_distr_bicat_pentagon_eq_body_variant_RHS v w (δ v) (δ w).\n\n    Definition param_distr_bicat_pentagon_eq_variant (δ : parameterized_distributivity_bicat_nat): UU := ∏ (v w : V),\n        param_distr_bicat_pentagon_eq_body_variant δ v w.\n\n    Definition param_distr_bicat_pentagon_eq_body (δ : parameterized_distributivity_bicat_nat) (v w : V): UU :=\n      ((rassociator G (FA' v) (FA' w) : H v · FA' w ==> G · FA' v ⊗_{ monoidal_from_bicat_and_ob a0'} FA' w)\n         • (G ◃ (fmonoidal_preservestensordata FA'm v w)))\n         • δ (v ⊗ w)\n      = param_distr_bicat_pentagon_eq_body_RHS v w (δ v) (δ w).\n\n    Definition param_distr_bicat_pentagon_eq (δ : parameterized_distributivity_bicat_nat): UU := ∏ (v w : V),\n        param_distr_bicat_pentagon_eq_body δ v w.\n\n    Lemma param_distr_bicat_pentagon_eq_body_variant_follows (δ : parameterized_distributivity_bicat_nat) (v w : V):\n      param_distr_bicat_pentagon_eq_body δ v w -> param_distr_bicat_pentagon_eq_body_variant δ v w.\n    Proof.\n      intro Hyp.\n      red.\n      unfold param_distr_bicat_pentagon_eq_body_variant_RHS.\n      apply pathsinv0, (lhs_left_invert_cell _ _ _ (lwhisker_with_μ_inv_inv2cell v w)).\n      apply (lhs_left_invert_cell _ _ _ (is_invertible_2cell_lassociator _ _ _)).\n      apply pathsinv0.\n      etrans.\n      2: { exact Hyp. }\n      apply vassocr.\n    Qed.\n\n    Lemma param_distr_bicat_pentagon_eq_body_variant_implies (δ : parameterized_distributivity_bicat_nat) (v w : V):\n      param_distr_bicat_pentagon_eq_body_variant δ v w -> param_distr_bicat_pentagon_eq_body δ v w.\n    Proof.\n      intro Hyp.\n      red in Hyp.\n      unfold param_distr_bicat_pentagon_eq_body_variant_RHS in Hyp.\n      apply pathsinv0, (rhs_left_inv_cell _ _ _ (lwhisker_with_μ_inv_inv2cell v w)) in Hyp.\n      apply (rhs_left_inv_cell _ _ _ (is_invertible_2cell_lassociator _ _ _)), pathsinv0 in Hyp.\n      etrans.\n      2: { exact Hyp. }\n      apply vassocl.\n    Qed.\n\n    Lemma isaprop_param_distr_bicat_triangle_eq (δ : parameterized_distributivity_bicat_nat): isaprop (param_distr_bicat_triangle_eq δ).\n    Proof.\n      apply C.\n    Qed.\n\n    Lemma isaprop_param_distr_bicat_pentagon_eq (δ : parameterized_distributivity_bicat_nat): isaprop (param_distr_bicat_pentagon_eq δ).\n    Proof.\n      red.\n      apply impred; intros v.\n      apply impred; intros w.\n      apply cellset_property.\n    Qed.\n\n\n    Section IntoMonoidalSectionBicat.\n\n      Context (δ: parameterized_distributivity_bicat_nat).\n      Context (δtr_eq: param_distr_bicat_triangle_eq_variant0 δ)\n              (δpe_eq: param_distr_bicat_pentagon_eq_variant δ).\n\n      (** using sections already for this direction *)\n      Lemma param_distr_bicat_to_monoidal_section_data:\n        smonoidal_data Mon_V montrafotargetbicat_disp_monoidal\n                       (nat_trans_to_section_bicat a0 a0' H H' δ).\n      Proof.\n        split.\n        - intros v w. cbn.\n          rewrite (functor_id FA), (functor_id FA').\n          cbn.\n          rewrite lwhisker_id2, id2_rwhisker.\n          rewrite id2_left, id2_right.\n          apply pathsinv0, δpe_eq.\n        - cbn.\n          rewrite (functor_id FA), (functor_id FA').\n          cbn.\n          rewrite lwhisker_id2, id2_rwhisker.\n          rewrite id2_left, id2_right.\n          apply pathsinv0, δtr_eq.\n      Qed.\n      (** the two equations were thus exactly the ingredients for the data of a monoidal section *)\n\n      Lemma param_distr_bicat_to_monoidal_section_laws: smonoidal_laxlaws Mon_V montrafotargetbicat_disp_monoidal param_distr_bicat_to_monoidal_section_data.\n      Proof.\n        repeat split; red; intros; apply trafotargetbicat_disp_cells_isaprop.\n      Qed.\n\n      Lemma param_distr_bicat_to_monoidal_section_strongtensor:\n        smonoidal_strongtensor Mon_V montrafotargetbicat_disp_monoidal\n                               (smonoidal_preserves_tensor Mon_V montrafotargetbicat_disp_monoidal\n                                                           param_distr_bicat_to_monoidal_section_data).\n      Proof.\n        intros v w.\n        use tpair.\n        - cbn. (** now as for [param_distr_bicat_to_monoidal_section_data] *)\n          rewrite (functor_id FA), (functor_id FA').\n          cbn.\n          rewrite lwhisker_id2, id2_rwhisker.\n          rewrite id2_left, id2_right.\n          apply δpe_eq.\n        - split; apply trafotargetbicat_disp_cells_isaprop.\n      Qed.\n\n      Lemma param_distr_bicat_to_monoidal_section_strongunit:\n        smonoidal_strongunit Mon_V montrafotargetbicat_disp_monoidal\n                             (smonoidal_preserves_unit Mon_V montrafotargetbicat_disp_monoidal\n                                                       param_distr_bicat_to_monoidal_section_data).\n      Proof.\n        use tpair.\n        - cbn.\n          rewrite (functor_id FA), (functor_id FA').\n          cbn.\n          rewrite lwhisker_id2, id2_rwhisker.\n          rewrite id2_left, id2_right.\n          apply δtr_eq.\n        - split; apply trafotargetbicat_disp_cells_isaprop.\n      Qed.\n\n      Definition param_distr_bicat_to_monoidal_section:\n        smonoidal Mon_V montrafotargetbicat_disp_monoidal (nat_trans_to_section_bicat a0 a0' H H' δ).\n      Proof.\n        use tpair.\n        - exact (param_distr_bicat_to_monoidal_section_data,,param_distr_bicat_to_monoidal_section_laws).\n        - split.\n          + exact param_distr_bicat_to_monoidal_section_strongtensor.\n          + exact param_distr_bicat_to_monoidal_section_strongunit.\n      Defined.\n\n\n    End IntoMonoidalSectionBicat.\n\n(* not migrated, and also parameterized_distributivity_bicat not yet defined (taking into account the variants!)\nDefinition smf_from_param_distr_bicat:\n  parameterized_distributivity_bicat -> strong_monoidal_functor Mon_V montrafotargetbicat_moncat.\nProof.\n  intro δs.\n  induction δs as [δ [δtr_eq δpe_eq]].\n  exact (smf_from_param_distr_parts_bicat δ δtr_eq δpe_eq).\nDefined.\n *)\n\n    (** the other direction, essentially dependent on sections *)\n    Section FromMonoidalSectionBicat.\n\n      Context (sd: section_disp montrafotargetbicat_disp).\n      Context (ms: smonoidal_data Mon_V montrafotargetbicat_disp_monoidal sd).\n      (** since the laws were anyway trivial to establish, we do not need more than [smonoidal_data] *)\n\n      Definition δ_from_ms: H ⟹ H' := section_to_nat_trans_bicat _ _ _ _ sd.\n\n      Lemma δtr_eq_from_ms: param_distr_bicat_triangle_eq_variant0 δ_from_ms.\n      Proof.\n        red.\n        assert (aux := smonoidal_preserves_unit _ _ ms).\n        cbn in aux.\n        rewrite (functor_id FA), (functor_id FA') in aux.\n        cbn in aux.\n        rewrite lwhisker_id2, id2_rwhisker in aux.\n        rewrite id2_left, id2_right in aux.\n        apply pathsinv0. exact aux.\n      Qed.\n\n      Lemma δpe_eq_from_ms: param_distr_bicat_pentagon_eq_variant δ_from_ms.\n      Proof.\n        intros v w.\n        assert (aux := smonoidal_preserves_tensor _ _ ms v w).\n        cbn in aux.\n        rewrite (functor_id FA), (functor_id FA') in aux.\n        cbn in aux.\n        rewrite lwhisker_id2, id2_rwhisker in aux.\n        rewrite id2_left, id2_right in aux.\n        apply pathsinv0. exact aux.\n      Qed.\n\n    End FromMonoidalSectionBicat.\n\n    Section RoundtripForSDData.\n\n      Local Definition source_type: UU := ∑ δ: parameterized_distributivity_bicat_nat,\n            param_distr_bicat_triangle_eq_variant0 δ ×\n              param_distr_bicat_pentagon_eq_variant δ.\n      Local Definition target_type: UU := ∑ sd: section_disp montrafotargetbicat_disp,\n            smonoidal_data Mon_V montrafotargetbicat_disp_monoidal sd.\n\n      Local Definition source_to_target : source_type -> target_type.\n      Proof.\n        intro ass. destruct ass as [δ [δtr_eq δpe_eq]].\n        exists (nat_trans_to_section_bicat a0 a0' H H' δ).\n        apply param_distr_bicat_to_monoidal_section_data; [exact δtr_eq | exact δpe_eq].\n      Defined.\n\n      Local Definition target_to_source : target_type -> source_type.\n      Proof.\n        intro ass. destruct ass as [sd ms].\n        exists (δ_from_ms sd).\n        split; [apply δtr_eq_from_ms | apply δpe_eq_from_ms]; exact ms.\n      Defined.\n\n      Local Lemma roundtrip1 (ass: source_type): target_to_source (source_to_target ass) = ass.\n      Proof.\n        destruct ass as [δ [δtr_eq δpe_eq]].\n        use total2_paths_f.\n        - cbn.\n          unfold δ_from_ms.\n          apply UniMath.CategoryTheory.categories.Dialgebras.roundtrip1_with_sections.\n        - cbn.\n          match goal with |- @paths ?ID _ _ => set (goaltype := ID); simpl in goaltype end.\n          assert (Hprop: isaprop goaltype).\n          2: { apply Hprop. }\n          apply isapropdirprod.\n          + unfold param_distr_bicat_triangle_eq_variant0.\n            apply C.\n          + unfold param_distr_bicat_pentagon_eq_variant.\n            apply impred. intro v.\n            apply impred. intro w.\n            apply C.\n      Qed.\n\n      Local Lemma roundtrip2 (ass: target_type): source_to_target (target_to_source ass) = ass.\n      Proof.\n        destruct ass as [sd ms].\n        use total2_paths_f.\n        - cbn.\n          unfold δ_from_ms.\n          apply UniMath.CategoryTheory.categories.Dialgebras.roundtrip2_with_sections.\n        - cbn.\n          match goal with |- @paths ?ID _ _ => set (goaltype := ID); simpl in goaltype end.\n          assert (Hprop: isaprop goaltype).\n          2: { apply Hprop. }\n          apply isapropdirprod.\n          + unfold section_preserves_tensor_data.\n            apply impred. intro v.\n            apply impred. intro w.\n            apply trafotargetbicat_disp_cells_isaprop.\n          + unfold section_preserves_unit.\n            apply trafotargetbicat_disp_cells_isaprop.\n      Qed.\n\n    End RoundtripForSDData.\n\n\n  End FunctorViaBicat.\n\n  Section Functor.\n\n    Context {A A': category}.\n\n    Context {FA: functor V (cat_of_endofunctors A)}.\n    Context {FA': functor V (cat_of_endofunctors A')}.\n\n    Context (FAm: fmonoidal Mon_V (monoidal_of_endofunctors A) FA).\n    Context (FA'm: fmonoidal Mon_V (monoidal_of_endofunctors A') FA').\n\n    Context (G : A ⟶ A').\n\n    Let H : V ⟶ [A, A'] := param_distributivity'_dom(FA':=FA') A A' G.\n    Let H' : V ⟶ [A, A'] := param_distributivity'_codom(FA:=FA) A A' G.\n\n    Goal H = Main.H(C:=bicat_of_cats)(FA':=FA') G.\n    Proof.\n      apply idpath.\n    Qed.\n\n    Goal H' = Main.H'(C:=bicat_of_cats)(FA:=FA) G.\n    Proof.\n      apply idpath.\n    Qed.\n\n    Definition parameterized_distributivity'_nat_as_instance\n               (δtr: parameterized_distributivity'_nat(FA:=FA)(FA':=FA') A A' G):\n      parameterized_distributivity_bicat_nat(FA:=FA)(FA':=FA') G := δtr.\n\n    Definition montrafotarget_disp: disp_cat V :=\n      montrafotargetbicat_disp(C:=bicat_of_cats)(FA:=FA)(FA':=FA') G.\n\n    Definition montrafotarget_totalcat: category :=\n      total_category montrafotarget_disp.\n\n    Goal montrafotarget_disp = trafotargetbicat_disp(C:=bicat_of_cats) A A' H H'.\n    Proof.\n      apply idpath.\n    Qed.\n\n   Definition montrafotarget_disp_monoidal: disp_monoidal montrafotarget_disp Mon_V\n     := montrafotargetbicat_disp_monoidal(C:=bicat_of_cats)(a0:=A)(a0':=A') FAm FA'm G.\n\n   Definition montrafotarget_monoidal: monoidal montrafotarget_totalcat :=\n     total_monoidal montrafotarget_disp_monoidal.\n\n    Section IntoMonoidalSection.\n\n      Context (δs : parameterized_distributivity' Mon_V A A' FAm FA'm G).\n      Let δ : parameterized_distributivity'_nat A A' G := pr1 δs.\n      Let δtr_eq : param_distr'_triangle_eq Mon_V A A' FAm FA'm G (pr1 δs) := pr12 δs.\n      Let δpe_eq : param_distr'_pentagon_eq Mon_V A A' FAm FA'm G (pr1 δs) := pr22 δs.\n\n      Definition montrafotarget_section_disp : section_disp montrafotarget_disp\n        := nat_trans_to_section_bicat(C0:=V)(C:=bicat_of_cats) A A' H H' δ.\n\n      Lemma δtr_eq': param_distr_bicat_triangle_eq_variant0 FAm FA'm G δ.\n      Proof.\n        apply param_distr'_triangle_eq_variant0_follows in δtr_eq.\n        red in δtr_eq |- *.\n        unfold param_distr'_triangle_eq_variant0_RHS in δtr_eq.\n        unfold param_distr_bicat_triangle_eq_variant0_RHS.\n        cbn in δtr_eq |- *.\n        etrans.\n        { exact δtr_eq. }\n        rewrite (nat_trans_comp_id_right A' (functor_composite G (functor_identity A')) G).\n        (* show_id_type. *)\n        apply (nat_trans_eq A').\n        intro a.\n        cbn.\n        apply maponpaths, pathsinv0, id_left.\n      Qed.\n\n      Lemma δpe_eq': param_distr_bicat_pentagon_eq_variant FAm FA'm G δ.\n      Proof.\n        intros v w.\n        set (δpe_eq_inst := δpe_eq v w).\n        apply param_distr'_pentagon_eq_body_variant_follows in δpe_eq_inst.\n        unfold param_distr_bicat_pentagon_eq_body_variant_RHS, param_distr_bicat_pentagon_eq_body_RHS.\n        unfold param_distr'_pentagon_eq_body_variant, param_distr'_pentagon_eq_body_variant_RHS in δpe_eq_inst.\n        cbn in δpe_eq_inst |- *.\n        etrans.\n        { exact δpe_eq_inst. }\n        clear δpe_eq_inst.\n        apply (nat_trans_eq A').\n        intro a.\n        cbn.\n        apply maponpaths.\n        do 3 rewrite id_left.\n        apply idpath.\n      Qed.\n\n      Definition param_distr'_to_monoidal_section_data:\n        smonoidal_data Mon_V montrafotarget_disp_monoidal montrafotarget_section_disp :=\n        param_distr_bicat_to_monoidal_section_data(C:=bicat_of_cats) FAm FA'm G\n                             (parameterized_distributivity'_nat_as_instance δ) δtr_eq' δpe_eq'.\n\n      Definition param_distr'_to_monoidal_section_laws:\n        smonoidal_laxlaws Mon_V montrafotarget_disp_monoidal\n                          param_distr'_to_monoidal_section_data :=\n        param_distr_bicat_to_monoidal_section_laws FAm FA'm G δ δtr_eq' δpe_eq'.\n\n      Definition param_distr'_to_monoidal_section_strongtensor:\n        smonoidal_strongtensor Mon_V montrafotarget_disp_monoidal\n                               (smonoidal_preserves_tensor Mon_V\n                                                           montrafotarget_disp_monoidal\n                                                           param_distr'_to_monoidal_section_data) :=\n        param_distr_bicat_to_monoidal_section_strongtensor FAm FA'm G δ δtr_eq' δpe_eq'.\n\n      Definition param_distr'_to_monoidal_section_strongunit:\n        smonoidal_strongunit Mon_V montrafotarget_disp_monoidal\n                             (smonoidal_preserves_unit Mon_V\n                                                       montrafotarget_disp_monoidal\n                                                       param_distr'_to_monoidal_section_data) :=\n        param_distr_bicat_to_monoidal_section_strongunit FAm FA'm G δ δtr_eq' δpe_eq'.\n\n      Definition param_distr'_to_functor: V ⟶ montrafotarget_totalcat :=\n        section_functor montrafotarget_section_disp.\n\n      Definition param_distr'_to_smf: fmonoidal Mon_V montrafotarget_monoidal param_distr'_to_functor.\n      Proof.\n        apply sectionfunctor_fmonoidal.\n        use tpair.\n        - use tpair.\n          + apply param_distr'_to_monoidal_section_data.\n          + apply param_distr'_to_monoidal_section_laws.\n        - split.\n          + apply param_distr'_to_monoidal_section_strongtensor.\n          + apply param_distr'_to_monoidal_section_strongunit.\n      Defined.\n\nEnd IntoMonoidalSection.\n\nSection FromMonoidalSection.\n\n      Context {sd: section_disp montrafotarget_disp}.\n      Context (ms: smonoidal_data Mon_V montrafotarget_disp_monoidal sd).\n      (** since the laws were anyway trivial to establish, we do not need more than [smonoidal_data] *)\n\n      Definition δ'_from_ms: H ⟹ H' := section_to_nat_trans_bicat _ _ _ _ sd.\n\n      Lemma δtr'_eq_from_ms: param_distr'_triangle_eq Mon_V A A' FAm FA'm G δ'_from_ms.\n      Proof.\n        apply param_distr'_triangle_eq_variant0_implies.\n        assert (aux := δtr_eq_from_ms(C:=bicat_of_cats) FAm FA'm G sd ms).\n        unfold param_distr'_triangle_eq_variant0.\n        unfold param_distr'_triangle_eq_variant0_RHS.\n        red in aux.\n        unfold param_distr_bicat_triangle_eq_variant0_RHS in aux.\n        etrans.\n        { exact aux. }\n        cbn.\n        rewrite (nat_trans_comp_id_right A' (functor_composite G (functor_identity A')) G).\n        apply (nat_trans_eq A').\n        intro a.\n        cbn.\n        apply maponpaths, id_left.\n      Qed.\n\n      Lemma δpe'_eq_from_ms: param_distr'_pentagon_eq Mon_V A A' FAm FA'm G δ'_from_ms.\n      Proof.\n        intros v w.\n        apply param_distr'_pentagon_eq_body_variant_implies.\n        assert (aux := δpe_eq_from_ms(C:=bicat_of_cats) FAm FA'm G sd ms v w).\n        red.\n        etrans.\n        { exact aux. }\n        clear aux.\n        unfold param_distr_bicat_pentagon_eq_body_variant_RHS, param_distr_bicat_pentagon_eq_body_RHS.\n        unfold param_distr'_pentagon_eq_body_variant_RHS.\n        apply (nat_trans_eq A').\n        intro a.\n        cbn.\n        apply maponpaths.\n        do 3 rewrite id_left.\n        apply idpath.\n      Qed.\n\n\nEnd FromMonoidalSection.\n\nEnd Functor.\n\nEnd Main.\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/ActionBasedStrongFunctorsWhiskeredMonoidal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723316991792861, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.29436261710007205}}
{"text": "Require Import CSPEC.\nRequire Import MailServerAPI.\nRequire Import MailFSPathAPI.\n\n\nModule MailFSMergedOp <: Ops.\n\n  Definition extopT := MailServerAPI.MailServerOp.extopT.\n\n  Inductive xOp : Type -> Type :=\n  | Create : forall (fn : string * string * string), xOp bool\n  | Write : forall (fn : string * string * string) (data : string), xOp bool\n  | Link : forall (fn : string * string * string) (fn : string * string * string), xOp bool\n  | Unlink : forall (fn : string * string * string), xOp unit\n\n  | GetTID : xOp nat\n  | Random : xOp nat\n\n  | List : forall (dir : string * string), xOp (list string)\n  | Read : forall (fn : string * string * string), xOp (option string)\n\n  | Lock : forall (u : string), xOp unit\n  | Unlock : forall (u : string), xOp unit\n  | Exists : forall (u : string), xOp (CheckResult UserIdx.indexValid)\n\n  | Ext : forall `(op : extopT T), xOp T\n  .\n\n  Definition Op := xOp.\n\nEnd MailFSMergedOp.\n\n\nModule MailFSMergedState <: State.\n\n  Definition fs_contents := FMap.t (string * string * string) string.\n  Definition locked_map := FMap.t string bool.\n\n  Record state_rec := mk_state {\n    fs : fs_contents;\n    locked : locked_map;\n  }.\n\n  Definition State := state_rec.\n  Definition initP (s : State) :=\n    (forall u,\n      UserIdx.indexValid u ->\n      FMap.MapsTo u false (locked s)) /\\\n    fs s = FMap.empty.\n\nEnd MailFSMergedState.\n\n\nDefinition filter_dir (dirname : string * string) (fs : MailFSMergedState.fs_contents) :=\n  FMap.filter (fun '(dn, fn) => if dn == dirname then true else false) fs.\n\nDefinition drop_dirname (fs : MailFSMergedState.fs_contents) :=\n  FMap.map_keys (fun '(dn, fn) => fn) fs.\n\n\nModule MailFSMergedAPI <: Layer MailFSMergedOp MailFSMergedState.\n\n  Import MailFSMergedOp.\n  Import MailFSMergedState.\n\n  (* TCB: these are the atomic semantics of the low-level operation the mail\n  server is implemented on top of. There is no Coq implementation of these\n  operations; it is trusted that the Haskell implementation in\n  mail-test/lib/Interpreter.hs, when run on a file system, obeys these\n  semantics. *)\n  Inductive xstep : forall T, Op T -> nat -> State -> T -> State -> list event -> Prop :=\n  | StepCreateOK : forall fs tid tmpfn lock,\n    xstep (Create tmpfn) tid\n      (mk_state fs lock)\n      true\n      (mk_state (FMap.add tmpfn empty_string fs) lock)\n      nil\n  | StepCreateErr : forall fs tid tmpfn lock,\n    xstep (Create tmpfn) tid\n      (mk_state fs lock)\n      false\n      (mk_state fs lock)\n      nil\n  | StepWriteOK : forall fs tid tmpfn data lock,\n    FMap.MapsTo tmpfn empty_string fs ->\n    xstep (Write tmpfn data) tid\n      (mk_state fs lock)\n      true\n      (mk_state (FMap.add tmpfn data fs) lock)\n      nil\n  | StepWriteErr1 : forall fs tid tmpfn data lock,\n    xstep (Write tmpfn data) tid\n      (mk_state fs lock)\n      false\n      (mk_state fs lock)\n      nil\n  | StepWriteErr2 : forall fs tid tmpfn data data' lock,\n    FMap.MapsTo tmpfn empty_string fs ->\n    xstep (Write tmpfn data) tid\n      (mk_state fs lock)\n      false\n      (mk_state (FMap.add tmpfn data' fs) lock)\n      nil\n  | StepUnlink : forall fs tid fn lock,\n    xstep (Unlink fn) tid\n      (mk_state fs lock)\n      tt\n      (mk_state (FMap.remove fn fs) lock)\n      nil\n  | StepLinkOK : forall fs tid mailfn data tmpfn lock,\n    FMap.MapsTo tmpfn data fs ->\n    ~ FMap.In mailfn fs ->\n    xstep (Link tmpfn mailfn) tid\n      (mk_state fs lock)\n      true\n      (mk_state (FMap.add mailfn data fs) lock)\n      nil\n  | StepLinkErr : forall fs tid mailfn tmpfn lock,\n    xstep (Link tmpfn mailfn) tid\n      (mk_state fs lock)\n      false\n      (mk_state fs lock)\n      nil\n\n  | StepList : forall fs tid r dirname lock,\n    FMap.is_permutation_key r (drop_dirname (filter_dir dirname fs)) ->\n    xstep (List dirname) tid\n      (mk_state fs lock)\n      r\n      (mk_state fs lock)\n      nil\n\n  | StepGetTID : forall s tid,\n    xstep GetTID tid\n      s\n      tid\n      s\n      nil\n  | StepRandom : forall s tid r,\n    xstep Random tid\n      s\n      r\n      s\n      nil\n\n  | StepReadOK : forall fn fs tid m lock,\n    FMap.MapsTo fn m fs ->\n    xstep (Read fn) tid\n      (mk_state fs lock)\n      (Some m)\n      (mk_state fs lock)\n      nil\n  | StepReadNone : forall fn fs tid lock,\n    ~ FMap.In fn fs ->\n    xstep (Read fn) tid\n      (mk_state fs lock)\n      None\n      (mk_state fs lock)\n      nil\n\n  | StepLock : forall fs tid u locked,\n    FMap.MapsTo u false locked ->\n    xstep (Lock u) tid\n      (mk_state fs locked)\n      tt\n      (mk_state fs (FMap.add u true locked))\n      nil\n  | StepLockErr : forall fs tid u locked,\n    ~ FMap.In u locked ->\n    xstep (Lock u) tid\n      (mk_state fs locked)\n      tt\n      (mk_state fs locked)\n      nil\n  | StepUnlock : forall fs tid u locked,\n    xstep (Unlock u) tid\n      (mk_state fs locked)\n      tt\n      (mk_state fs (FMap.add u false locked))\n      nil\n\n  | StepExistsOK : forall fs tid u P locked,\n    FMap.In u locked ->\n    xstep (Exists u) tid\n      (mk_state fs locked)\n      (Present (exist _ u P))\n      (mk_state fs locked)\n      nil\n  | StepExistsErr : forall fs tid u locked,\n    ~ FMap.In u locked ->\n    xstep (Exists u) tid\n      (mk_state fs locked)\n      Missing\n      (mk_state fs locked)\n      nil\n\n  | StepExt : forall s tid `(extop : extopT 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 MailFSMergedAPI.\n\n\nModule MailFSMergedAbsAPI <: Layer MailFSPathHOp MailFSMergedState.\n\n  Import MailFSPathOp.\n  Import MailFSPathHOp.\n  Import MailFSMergedState.\n\n  Inductive xstep : forall T, Op T -> nat -> State -> T -> State -> list event -> Prop :=\n  | StepCreateOK : forall fs tid dir fn lock u P,\n    xstep (Slice (exist _ u P) (Create (dir, fn))) tid\n      (mk_state fs lock)\n      true\n      (mk_state (FMap.add (u, dir, fn) empty_string fs) lock)\n      nil\n  | StepCreateErr : forall fs tid dir fn lock u P,\n    xstep (Slice (exist _ u P) (Create (dir, fn))) tid\n      (mk_state fs lock)\n      false\n      (mk_state fs lock)\n      nil\n  | StepWriteOK : forall fs tid dir fn data lock u P,\n    FMap.MapsTo (u, dir, fn) empty_string fs ->\n    xstep (Slice (exist _ u P) (Write (dir, fn) data)) tid\n      (mk_state fs lock)\n      true\n      (mk_state (FMap.add (u, dir, fn) data fs) lock)\n      nil\n  | StepWriteErr1 : forall fs tid dir fn data lock u P,\n    xstep (Slice (exist _ u P) (Write (dir, fn) data)) tid\n      (mk_state fs lock)\n      false\n      (mk_state fs lock)\n      nil\n  | StepWriteErr2 : forall fs tid dir fn data data' lock u P,\n    FMap.MapsTo (u, dir, fn) empty_string fs ->\n    xstep (Slice (exist _ u P) (Write (dir, fn) data)) tid\n      (mk_state fs lock)\n      false\n      (mk_state (FMap.add (u, dir, fn) data' fs) lock)\n      nil\n  | StepUnlink : forall fs tid dir fn lock u P,\n    xstep (Slice (exist _ u P) (Unlink (dir, fn))) tid\n      (mk_state fs lock)\n      tt\n      (mk_state (FMap.remove (u, dir, fn) fs) lock)\n      nil\n  | StepLinkOK : forall fs tid srcdir srcfn data dstdir dstfn lock u P,\n    FMap.MapsTo (u, srcdir, srcfn) data fs ->\n    ~ FMap.In (u, dstdir, dstfn) fs ->\n    xstep (Slice (exist _ u P) (Link (srcdir, srcfn) (dstdir, dstfn))) tid\n      (mk_state fs lock)\n      true\n      (mk_state (FMap.add (u, dstdir, dstfn) data fs) lock)\n      nil\n  | StepLinkErr : forall fs tid srcdir srcfn dstdir dstfn lock u P,\n    xstep (Slice (exist _ u P) (Link (srcdir, srcfn) (dstdir, dstfn))) tid\n      (mk_state fs lock)\n      false\n      (mk_state fs lock)\n      nil\n\n  | StepList : forall fs tid r dirname lock u P,\n    FMap.is_permutation_key r (drop_dirname (filter_dir (u, dirname) fs)) ->\n    xstep (Slice (exist _ u P) (List dirname)) tid\n      (mk_state fs lock)\n      r\n      (mk_state fs lock)\n      nil\n\n  | StepGetTID : forall s tid u P,\n    xstep (Slice (exist _ u P) GetTID) tid\n      s\n      tid\n      s\n      nil\n  | StepRandom : forall s tid r u P,\n    xstep (Slice (exist _ u P) Random) tid\n      s\n      r\n      s\n      nil\n\n  | StepReadOK : forall dir fn fs tid m lock u P,\n    FMap.MapsTo (u, dir, fn) m fs ->\n    xstep (Slice (exist _ u P) (Read (dir, fn))) tid\n      (mk_state fs lock)\n      (Some m)\n      (mk_state fs lock)\n      nil\n  | StepReadNone : forall dir fn fs tid lock u P,\n    ~ FMap.In (u, dir, fn) fs ->\n    xstep (Slice (exist _ u P) (Read (dir, fn))) tid\n      (mk_state fs lock)\n      None\n      (mk_state fs lock)\n      nil\n\n  | StepLock : forall fs tid u locked P,\n    FMap.MapsTo u false locked ->\n    xstep (Slice (exist _ u P) Lock) tid\n      (mk_state fs locked)\n      tt\n      (mk_state fs (FMap.add u true locked))\n      nil\n  | StepLockErr : forall fs tid u locked P,\n    ~ FMap.In u locked ->\n    xstep (Slice (exist _ u P) Lock) tid\n      (mk_state fs locked)\n      tt\n      (mk_state fs locked)\n      nil\n  | StepUnlock : forall fs tid u locked P,\n    xstep (Slice (exist _ u P) Unlock) tid\n      (mk_state fs locked)\n      tt\n      (mk_state fs (FMap.add u false locked))\n      nil\n\n  | StepExistsOK : forall fs tid u P locked,\n    FMap.In u locked ->\n    xstep (CheckSlice u) tid\n      (mk_state fs locked)\n      (Present (exist _ u P))\n      (mk_state fs locked)\n      nil\n  | StepExistsErr : forall fs tid u locked,\n    ~ FMap.In u locked ->\n    xstep (CheckSlice u) tid\n      (mk_state fs locked)\n      Missing\n      (mk_state fs locked)\n      nil\n\n  | StepExt : forall s tid `(extop : extopT T) r u P,\n    xstep (Slice (exist _ u P) (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 MailFSMergedAbsAPI.\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/MailFSMergedAPI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.294362617100072}}
{"text": "Require Import Blech.Defaults.\n\nRequire Import Blech.Bishop.\nRequire Import Blech.Category.\nRequire Import Blech.Category.Funct.\nRequire Import Blech.Category.Bsh.\n\nDefinition CoPSh (C: Category): Category := Funct C Bsh.\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/Category/CoPSh.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2943399442988436}}
{"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 eqtype.\nFrom LemmaOverloading\nRequire Import heaps.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(******************************************************************************)\n(* noaliasR :                                                                 *)\n(*    lemma automated with Canonical Structures to prove/rewrite expressions  *)\n(*    with the form                                                           *)\n(*      x1 != x2                                                              *)\n(*    for x1, x2 : ptr. Usage:                                                *)\n(*      rewrite/apply: (noaliasR D)                                           *)\n(*    where D : def h, and exists expressions h1 h2 in h, where               *)\n(*    hi = xi :-> vi for i in [1,2] and some v1 v2                            *)\n(*                                                                            *)\n(* The lemma uses several structures. They are defined in different modules.  *)\n(* - The module Scan stores in a list all the pointers in h                   *)\n(* - The module Search finds a pointer in a list                              *)\n(* - The module Search2 finds for two distinct pointers in a list             *)\n(* - The module NoAlias combines the above to prove our goal                  *)\n(******************************************************************************)\n\n(* Collect pointers in a heap *)\nModule Scan.\nSection ScanSection.\n(* The algorithm is defined as follows:\n   - if the heap is h1 :+ h2, then recurse over h1 and h2 and concatenate the\n     results.\n   - if the heap is x :-> v, then return [x]\n   - otherwise, return []\n*)\n\n(* Structure to control the flow of the algorithm *)\nStructure tagged_heap := Tag {untag : heap}.\nLocal Coercion untag : tagged_heap >-> heap.\n\nDefinition default_tag := Tag.\nDefinition ptr_tag := default_tag.\nCanonical Structure union_tag h := ptr_tag h.\n\nDefinition axiom h s :=\n  def h -> uniq s /\\ forall x, x \\in s -> x \\in dom h.\n\n(* Main structure *)\nStructure form s := Form {heap_of : tagged_heap; _ : axiom heap_of s}.\nLocal Coercion heap_of : form >-> tagged_heap.\n\nLemma union_pf s1 s2 (h1 : form s1) (h2 : form s2) :\n        axiom (union_tag (h1 :+ h2)) (s1 ++ s2).\nProof.\nmove:h1 h2=>[[i1]] H1 [[i2]] H2; rewrite /axiom /= in H1 H2 * => D.\ncase/(_ (defUnl D)): H1=>U1 H1; case/(_ (defUnr D)): H2=>U2 H2.\nsplit=>[|x]; last first.\n- rewrite mem_cat; case/orP; [move/H1 | move/H2];\n  by rewrite domUn !inE /= D => -> //=; rewrite orbT.\nrewrite cat_uniq U1 U2 andbT -all_predC.\napply/allP=>x; move/H2=>H3; apply: (introN idP); move/H1=>H4.\nby case: defUn D=>// _ _; move/(_ _ H4); rewrite H3.\nQed.\n\nCanonical Structure union_form s1 s2 h1 h2 :=\n  Form (@union_pf s1 s2 h1 h2).\n\nLemma ptr_pf A x (v : A) : axiom (ptr_tag (x :-> v)) [:: x].\nProof.\nrewrite /axiom /= defPt => D; split=>//.\nby move=>y; rewrite inE; move/eqP=>->; rewrite domPt inE /= eq_refl D.\nQed.\n\nCanonical Structure ptr_form A x (v : A) :=\n  Form (@ptr_pf A x v).\n\nLemma default_pf h : axiom (default_tag h) [::].\nProof. by move=>D; split. Qed.\n\nCanonical Structure default_form h := Form (@default_pf h).\n\nLemma scanE s (h : form s) x : def h -> x \\in s -> x \\in dom h.\nProof. by case: h=>hp /= A D H; exact: ((proj2 (A D)) _ H). Qed.\n\nEnd ScanSection.\n\n(* Pack the exports, as they are not automatically exported by Coq *)\nModule Exports.\nCanonical Structure union_tag.\nCanonical Structure union_form.\nCanonical Structure ptr_form.\nCanonical Structure default_form.\nCoercion untag : tagged_heap >-> heap.\nCoercion heap_of : form >-> tagged_heap.\nEnd Exports.\n\nEnd Scan.\n\nExport Scan.Exports.\n\nExample ex_scan x y h :\n          let: hp := (y :-> 1 :+ h :+ x :-> 2) in def hp -> x \\in dom hp.\nProof.\nmove=>D; apply: Scan.scanE=>//=.\nby rewrite ?in_cons ?eqxx ?orbT.\nAbort.\n\n(* Search a pointer in a list. Could be generalize to any type *)\nModule Search.\nSection SearchSection.\n(* The algorithm is defined as follow:\n   - test if the list is (x :: s) for x being the element we are looking for\n   - if the list is (y :: s), then recurse using s\n*)\n\n(* Stucture for controlling the flow of the algorithm *)\nStructure tagged_seq := Tag {untag : seq ptr}.\nLocal Coercion untag : tagged_seq >-> seq.\n\nDefinition recurse_tag := Tag.\nCanonical Structure found_tag s := recurse_tag s.\n\nDefinition axiom x (s : tagged_seq) := x \\in untag s.\n\n(* Main structure *)\nStructure form x := Form {seq_of : tagged_seq; _ : axiom x seq_of}.\nLocal Coercion seq_of : form >-> tagged_seq.\n\nLemma found_pf x s : axiom x (found_tag (x :: s)).\nProof. by rewrite /axiom inE eq_refl. Qed.\n\nCanonical Structure found_form x s :=\n  Form (found_pf x s).\n\nLemma recurse_pf x y (f : form x) : axiom x (recurse_tag (y :: f)).\nProof. by move:f=>[[s]]; rewrite /axiom /= inE orbC => ->. Qed.\n\nCanonical Structure recurse_form x y (f : form x) :=\n  Form (recurse_pf y f).\n\nLemma findE x (f : form x) : x \\in untag f.\nProof. by move:f=>[s]; apply. Qed.\n\nEnd SearchSection.\n\nModule Exports.\nCanonical Structure found_tag.\nCanonical Structure found_form.\nCanonical Structure recurse_form.\nCoercion untag : tagged_seq >-> seq.\nCoercion seq_of : form >-> tagged_seq.\nEnd Exports.\n\nEnd Search.\n\nExport Search.Exports.\n\nExample ex_find (x y z : ptr) : x \\in [:: z; x; y].\nby apply: Search.findE.\nAbort.\n\n(* Search for two different pointers in a list *)\nModule Search2.\nSection Search2Section.\n(* The algorithm works as follow: Let x and y be the pointers we are looking for\n   - If we found x, then search for y using the previous module\n   - If we found y, then search for x using the previous module\n   - If, instead, we found some pointer z, then recurse\n*)\n\n(* Stucture for controlling the flow of the algorithm *)\nStructure tagged_seq := Tag {untag : seq ptr}.\nLocal Coercion untag : tagged_seq >-> seq.\n\nDefinition foundz_tag := Tag.\nDefinition foundy_tag := foundz_tag.\nCanonical Structure foundx_tag s := foundy_tag s.\n\nDefinition axiom (x y : ptr) (s : tagged_seq) :=\n  [/\\ x \\in untag s, y \\in untag s & uniq s -> x != y].\n\n(* Main structure *)\nStructure form x y := Form {seq_of : tagged_seq; _ : axiom x y seq_of}.\nLocal Coercion seq_of : form >-> tagged_seq.\n\nLemma foundx_pf x y (s : Search.form y) : axiom x y (foundx_tag (x :: s)).\nProof.\nmove: s=>[[s]]; rewrite /Search.axiom /= /axiom !inE eq_refl /= => H1.\nby rewrite H1 orbT; split=>//; case/andP=>H2 _; case: eqP H1 H2=>// -> ->.\nQed.\n\nCanonical Structure foundx_form x y (s : Search.form y) :=\n  Form (foundx_pf x s).\n\nLemma foundy_pf x y (s : Search.form x) : axiom x y (foundy_tag (y :: s)).\nProof.\nmove: s=>[[s]]; rewrite /Search.axiom /= /axiom !inE eq_refl /= => H1.\nby rewrite H1 orbT; split=>//; case/andP=>H2 _; case: eqP H1 H2=>// -> ->.\nQed.\n\nCanonical Structure foundy_form x y (s : Search.form x) :=\n  Form (foundy_pf y s).\n\nLemma foundz_pf x y z (s : form x y) : axiom x y (foundz_tag (z :: s)).\nProof.\nmove: s=>[[s]]; case=>/= H1 H2 H3.\nrewrite /axiom /= !inE /= H1 H2 !orbT; split=>//.\nby case/andP=>_; apply: H3.\nQed.\n\nCanonical Structure foundz_form x y z (s : form x y) :=\n  Form (foundz_pf z s).\n\nLemma find2E x y (s : form x y) : uniq s -> x != y.\nProof. by move: s=>[s /= [_ _]]; apply. Qed.\n\nEnd Search2Section.\n\nModule Exports.\nCanonical Structure foundx_tag.\nCanonical Structure foundx_form.\nCanonical Structure foundy_form.\nCanonical Structure foundz_form.\nCoercion untag : tagged_seq >-> seq.\nCoercion seq_of : form >-> tagged_seq.\nEnd Exports.\n\nEnd Search2.\n\nExport Search2.Exports.\n\nExample ex_find2 (x y z : ptr) : uniq [:: z; x; y] -> x != y.\nmove=>H.\nmove: (Search2.find2E H).\nAbort.\n\n(* Now package everything together *)\nModule NoAlias.\nSection NoAliasSection.\n(* The paper describes the reason for this module *)\n\nStructure tagged_ptr (y : ptr) := Tag {untag : ptr}.\nLocal Coercion untag : tagged_ptr >-> ptr.\n\n(* Force the unification of y with what appears in the goal *)\nDefinition singleton y := @Tag y y.\n\n(* Main structure *)\nStructure form x y (s : seq ptr) :=\n  Form {y_of : tagged_ptr y;\n        _ : uniq s -> x != untag y_of}.\nLocal Coercion y_of : form >-> tagged_ptr.\n\nArguments Form : clear implicits.\n\nLemma noalias_pf (x y : ptr) (f : Search2.form x y) :\n        uniq f -> x != singleton y.\nProof. by move: f=>[[s]][]. Qed.\n\nCanonical Structure start x y (f : Search2.form x y) :=\n  Form x y f (singleton y) (@noalias_pf x y f).\n\nEnd NoAliasSection.\n\nModule Exports.\nCanonical Structure singleton.\nCanonical Structure start.\nCoercion untag : tagged_ptr >-> ptr.\nCoercion y_of : form >-> tagged_ptr.\nEnd Exports.\n\nEnd NoAlias.\n\nExport NoAlias.Exports.\n\nLemma noaliasR s x y (f : Scan.form s) (g : NoAlias.form x y s) :\n               def f -> x != NoAlias.y_of g.\nProof. by move: f g=>[[h]] H1 [[y']] /= H2; case/H1=>U _; apply: H2. Qed.\n\nArguments noaliasR {s x y f g}.\n\nExample exnc A (x1 x2 x3 x4 : ptr) (v1 v2 : A) (h1 h2 : heap) :\n  def (h1 :+ x2 :-> 1 :+ h2 :+ x1 :-> v2 :+ (x3 :-> v1 :+ empty)) ->\n     (x1 != x2) /\\\n     (x1 != x2) && (x2 != x3) && (x3 != x1) /\\\n     (x2 == x3) = false /\\ (x1 == x2) = false /\\\n     ((x1 != x2) && (x2 != x3)) = (x1 != x2) /\\\n     ((x1 != x2) && (x2 != x3)) = (x1 != x2) /\\\n     ((x1 != x2) && (x2 != x3)) = (x1 != x2) /\\\n     ((x1 != x2) && (x2 != x3)) = (x1 != x2) /\\\n     (x1 != x2) && (x2 != x3) && (x1 != x4) && (x3 != x1).\n\nProof.\nmove=>D.\nsplit.\n- by apply: (noaliasR D).\nsplit.\n  (* backwards reasoning works *)\n- by rewrite !(noaliasR D).\nsplit.\n  (* subterm selection works *)\n- by rewrite [x2 == x3](negbTE (noaliasR D)).\nsplit.\n- (* composition works *)\n  by rewrite (negbTE (noaliasR D)).\nsplit.\n- by rewrite [x2 != x3](noaliasR D) andbT.\nsplit.\n- by rewrite (noaliasR (x := x2) D) andbT.\nsplit.\n- by rewrite (noaliasR (y := x3) D) andbT.\nsplit.\n- by rewrite (noaliasR (x := x2) (y := x3) D) andbT.\n(* rewriting skips the subgoals that don't apply *)\n(* just as it should *)\nrewrite !(negbTE (noaliasR D)).\nadmit.\nAbort.\n\n\n\nLemma noaliasR_fwd1 s (f : Scan.form s) (D : def f) x y (g : Search2.form x y) :\n  s = g ->\n  x != y.\nProof.\ncase: g=>[l/=[_ _]] H U.\napply: H.\nmove: U=><-.\ncase: f D=>[h/=].\nmove=>H D; by case: H.\nQed.\n\nArguments noaliasR_fwd1 [s f] D x y [g].\n\nNotation noaliasR_fwd D x y := (noaliasR_fwd1 D x y (Logic.eq_refl _)).\nNotation \"()\" := (Logic.eq_refl _).\n\nExample exnc A (x1 x2 x3 x4 : ptr) (v1 v2 : A) (h1 h2 : heap) :\n  def (h1 :+ x2 :-> 1 :+ h2 :+ x1 :-> v2 :+ (x3 :-> v1 :+ empty)) ->\n     (x1 != x2) /\\\n     (x1 != x2) && (x2 != x3) && (x3 != x1) /\\\n     (x2 == x3) = false /\\ (x1 == x2) = false.\nProof.\nmove=>D.\nsplit.\n- apply: (noaliasR_fwd1 D x1 x2 ()).\nsplit.\n  set H := noaliasR_fwd1 D.\n  by rewrite (H x1 x2 _ ()) (H x2 x3 _ ()) (H x3 x1 _ ()).\nsplit.\n  (* subterm selection works *)\n- by rewrite [x2 == x3](negbTE (noaliasR_fwd D x2 x3)).\n- (* composition works *)\n  by rewrite (negbTE (noaliasR_fwd D x1 x2)).\nAbort.\n\n\n\nLemma scan_it s (f : Scan.form s) : def f -> uniq s.\ncase: f=>/= h A D.\nby case: A.\nQed.\nArguments scan_it [s f].\n\nDefinition search_them x y g := @Search2.find2E x y g.\nArguments search_them x y [g].\n\nExample without_notation\n A (x1 x2 x3 : ptr) (v1 v2 v3 : A) (h1 h2 : heap) :\n def (h1 :+ (x1 :-> v1 :+ x2 :-> v2) :+ (h2 :+ x3 :-> v3))\n -> (x1 != x3).\nProof.\nmove=>D.\nby apply: (search_them x1 x3 (scan_it D)).\nAbort.\n\nLemma noaliasR_fwd_wrong1 x y (g : Search2.form x y) (f : Scan.form g) : def f -> x != y.\ncase: f=>h /= A D.\nmove: (A D)=>{A D} [U _].\ncase: g U=>s /= [_ _].\nby apply.\nQed.\n\n(*\nLemma noaliasR_fwd_wrong2 s (f : Scan.form s) (d : def f) x y (g : Search2.form x y)\n  : (@search_them x y g (@scan_it s f d)).\n*)\nNotation noaliasR_fwd' x y D := (search_them x y (scan_it D)).\n\nExample exnc A (x1 x2 x3 x4 : ptr) (v1 v2 : A) (h1 h2 : heap) :\n  def (h1 :+ x2 :-> 1 :+ h2 :+ x1 :-> v2 :+ (x3 :-> v1 :+ empty)) ->\n     (x1 != x2) /\\\n     (x1 != x2) && (x2 != x3) && (x3 != x1) /\\\n     (x2 == x3) = false /\\ (x1 == x2) = false.\nProof.\nmove=>D.\nsplit.\n  apply: (noaliasR_fwd' x1 x2 D).\nsplit.\n- by rewrite (noaliasR_fwd' x1 x2 D) (noaliasR_fwd' x2 x3 D) (noaliasR_fwd' x3 x1 D).\nsplit.\n  (* subterm selection works *)\n- by rewrite [x2 == x3](negbTE (noaliasR_fwd' x2 x3 D)).\n- (* composition works *)\n  by rewrite (negbTE (noaliasR_fwd' x1 x2 D)).\nAbort.\n\n(* Main structure *)\nStructure check (x y : ptr) (s : seq ptr) :=\n  Check {y_of :> ptr;\n         _ : y_of = y;\n         _ : uniq s -> x != y_of}.\n\nProgram\nCanonical Structure start x y (f : Search2.form x y) :=\n  @Check x y f y (Logic.eq_refl _) _.\nNext Obligation.\ncase: f H=>[s H /= U].\nby case: H=>_ _; apply.\nQed.\n\n\nLemma noaliasR_fwd3 s (f : Scan.form s) (D : def f) x y\n  (g : check x y s) : x != y_of g.\nProof.\ncase: f D=>h A /= D.\ncase: A g=>// U _ [y' /= ->].\nby apply.\nQed.\n\nArguments noaliasR_fwd3 [s f] D x y {g}.\n\nExample triggered\n A (x1 x2 x3 : ptr) (v1 v2 v3 : A) (h1 h2 : heap) :\n def (h1 :+ (x1 :-> v1 :+ x2 :-> v2) :+ (h2 :+ x3 :-> v3))\n -> (x1 != x3) && (x2 != x3) && (x1 != x2).\nProof.\nmove=>D.\nhave F := noaliasR_fwd3 D.\nby rewrite !(F _ x3) (F _ x2).\nAbort.\n\n(* Main structure *)\nStructure check' (x : ptr) (s : seq ptr) :=\n  Check' {y_of' :> ptr;\n         _ : uniq s -> x != y_of'}.\n\nProgram\nCanonical Structure start' x y (f : Search2.form x y) :=\n  @Check' x f y _.\nNext Obligation.\ncase: f H=>[s H /= U].\nby case: H=>_ _; apply.\nQed.\n\n\nLemma noaliasR_fwd3' s (f : Scan.form s) (D : def f) x\n  (g : check' x s) : x != y_of' g.\nProof.\ncase: f D=>h A /= D.\ncase: A g=>// U _[y' /= ->] //.\nQed.\n\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/noalias.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.29433993741567555}}
{"text": "(** * Implementation of Section 3.7 *)\nRequire Import Rpos.\nRequire Import RL.hr.term.\nRequire Import RL.hr.semantic.\nRequire Import RL.hr.hseq.\nRequire Import RL.hr.hr.\nRequire Import RL.hr.tech_lemmas.\n\nRequire Import CMorphisms.\nRequire Import Lra.\n\nRequire Import RL.OLlibs.List_Type.\nRequire Import RL.OLlibs.List_more.\nRequire Import RL.OLlibs.Permutation_Type.\nRequire Import RL.OLlibs.Permutation_Type_more.\nRequire Import RL.OLlibs.Permutation_Type_solve.\n\n(** Proof of Lemma 3.40 *)\nLemma hrr_mul_vec : forall L,\n    HR_T (map (fun x => snd x) L) ->\n    HR_T (map (fun x => seq_mul_vec (fst x) (snd x)) L).\nProof.\n  intros L pi.\n  remember (map (fun x => snd x) L) as G.\n  revert L HeqG; induction pi; intros L HeqG.\n  - destruct L; [ | destruct L]; try now inversion HeqG.\n    destruct p as [r T]; destruct T; try now inversion HeqG.\n    simpl; rewrite seq_mul_vec_nil_r; apply hrr_INIT.\n  - destruct L; try now inversion HeqG.\n    simpl; apply hrr_W.\n    apply IHpi.\n    simpl in HeqG; inversion HeqG.\n    reflexivity.\n  - destruct L; try now inversion HeqG.\n    simpl; apply hrr_C.\n    change (seq_mul_vec (fst p) (snd p)\n                    :: seq_mul_vec (fst p) (snd p) :: map (fun x => seq_mul_vec (fst x) (snd x)) L)\n      with\n        (map (fun x => seq_mul_vec (fst x) (snd x)) (p :: p :: L)).\n    apply IHpi.\n    simpl in HeqG; inversion HeqG.\n    reflexivity.\n  - destruct L; [ | destruct L]; try destruct p as [r1 T1']; try destruct p0 as [r2 T2']; inversion HeqG; subst.\n    destruct r1 ; [ | destruct r2].\n    + simpl.\n      apply hrr_ex_hseq with ((seq_mul_vec r2 T2' :: map (fun x : list Rpos * sequent => seq_mul_vec (fst x) (snd x)) L) ++ (nil :: nil)); [ Permutation_Type_solve |] .\n      apply hrr_W_gen.\n      apply hrr_INIT.\n    + simpl.\n      apply hrr_ex_hseq with ((seq_mul_vec (r :: r1) T1' :: map (fun x : list Rpos * sequent => seq_mul_vec (fst x) (snd x)) L) ++ (nil :: nil)); [ Permutation_Type_solve |] .\n      apply hrr_W_gen.\n      apply hrr_INIT.\n    + simpl.\n      unfold HR_T; change hr_frag_T with (hr_frag_add_T hr_frag_T).\n      apply hrr_T_vec with (r0 :: r2); try now auto.\n      eapply hrr_ex_hseq ; [ apply Permutation_Type_swap | ].\n      change hr_frag_T with (hr_frag_add_T hr_frag_T).\n      apply hrr_T_vec with (r :: r1); try now auto.\n      eapply hrr_ex_hseq ; [ apply Permutation_Type_swap | ].\n      apply hrr_S.\n      apply hrr_ex_seq with (seq_mul_vec (vec_mul_vec (r :: r1) (r0 :: r2)) (T1' ++ T2')).\n      { etransitivity; [ symmetry; apply seq_mul_vec_twice | ].\n        etransitivity ; [ apply seq_mul_vec_perm_r; apply (seq_mul_vec_app_r _ _ (r0 :: r2)) | ].\n        etransitivity ; [ apply seq_mul_vec_app_r | ].\n        etransitivity ; [ apply Permutation_Type_app ; [ apply seq_mul_vec_twice_comm | reflexivity ] | ].\n        Permutation_Type_solve. }\n      change (seq_mul_vec (vec_mul_vec (r :: r1) (r0 :: r2)) (T1' ++ T2') :: map (fun x => seq_mul_vec (fst x) (snd x)) L)\n        with\n          (map (fun x => seq_mul_vec (fst x) (snd x)) ((vec_mul_vec (r :: r1) (r0 :: r2) , T1' ++ T2') :: L)).\n      apply IHpi; reflexivity.\n  - inversion f.\n  - destruct L; try destruct p as [r1 T1]; inversion HeqG; subst.    \n    simpl.\n    apply hrr_T with r; try assumption.\n    rewrite seq_mul_seq_mul_vec.\n    change (seq_mul_vec r1 (seq_mul r T1) :: map (fun x : list Rpos * sequent => seq_mul_vec (fst x) (snd x)) L)\n      with (map (fun x : list Rpos * sequent => seq_mul_vec (fst x) (snd x)) ((r1, seq_mul r T1) :: L)).\n    apply IHpi.\n    reflexivity.\n  - destruct L; try destruct p as [r1 T1]; inversion HeqG; subst.    \n    simpl.\n    apply hrr_ex_seq with (vec (vec_mul_vec r1 s) (HR_covar n) ++ vec (vec_mul_vec r1 r) (HR_var n) ++ seq_mul_vec r1 T).\n    { etransitivity ; [ | symmetry ; apply seq_mul_vec_app_r].\n      etransitivity ; [ | symmetry; apply Permutation_Type_app; try apply seq_mul_vec_app_r; reflexivity ].\n      apply Permutation_Type_app ; [ | apply Permutation_Type_app]; try rewrite seq_mul_vec_vec_mul_vec; reflexivity. }\n    apply hrr_ID.\n    { rewrite ? sum_vec_vec_mul_vec.\n      nra. }\n    change (seq_mul_vec r1 T :: map (fun x : list Rpos * sequent => seq_mul_vec (fst x) (snd x)) L) with (map (fun x => seq_mul_vec (fst x) (snd x)) ((r1, T) :: L)).\n    apply IHpi; reflexivity.\n  - destruct L; try destruct p as [r1 T1]; inversion HeqG; subst.\n    simpl.\n    eapply hrr_ex_seq ; [ symmetry; apply seq_mul_vec_app_r | ].\n    rewrite seq_mul_vec_vec_mul_vec.\n    apply hrr_Z.\n    change (seq_mul_vec r1 T :: map (fun x : list Rpos * sequent => seq_mul_vec (fst x) (snd x)) L) with (map (fun x => seq_mul_vec (fst x) (snd x)) ((r1, T) :: L)).\n    apply IHpi; reflexivity.\n  - destruct L; try destruct p as [r1 T1]; inversion HeqG; subst.\n    simpl.\n    eapply hrr_ex_seq ; [ symmetry; apply seq_mul_vec_app_r | ].\n    rewrite seq_mul_vec_vec_mul_vec.\n    apply hrr_plus.\n    rewrite <- ? seq_mul_vec_vec_mul_vec.\n    apply hrr_ex_seq with (seq_mul_vec r1 (vec r A ++ vec r B ++ T)).\n    { etransitivity ; [apply seq_mul_vec_app_r | ].\n      apply Permutation_Type_app; try apply seq_mul_vec_app_r; reflexivity. }\n    change (seq_mul_vec r1 (vec r A ++ vec r B ++ T) :: map (fun x : list Rpos * sequent => seq_mul_vec (fst x) (snd x)) L) with (map (fun x => seq_mul_vec (fst x) (snd x)) ((r1, vec r A ++ vec r B ++ T) :: L)).\n    apply IHpi; reflexivity.\n  - destruct L; try destruct p as [r1 T1]; inversion HeqG; subst.\n    simpl.\n    eapply hrr_ex_seq ; [ symmetry; apply seq_mul_vec_app_r | ].\n    rewrite seq_mul_vec_vec_mul_vec.\n    apply hrr_mul.\n    rewrite <- vec_mul_vec_mul_vec_comm.\n    rewrite <- ? seq_mul_vec_vec_mul_vec.\n    eapply hrr_ex_seq ; [ apply seq_mul_vec_app_r | ].\n    change (seq_mul_vec r1 (vec (mul_vec r0 r) A ++ T) :: map (fun x : list Rpos * sequent => seq_mul_vec (fst x) (snd x)) L) with (map (fun x => seq_mul_vec (fst x) (snd x)) ((r1, vec (mul_vec r0 r) A ++ T) :: L)).\n    apply IHpi; reflexivity.\n  - destruct L; try destruct p as [r1 T1]; inversion HeqG; subst.\n    simpl.\n    eapply hrr_ex_seq ; [ symmetry; apply seq_mul_vec_app_r | ].\n    rewrite seq_mul_vec_vec_mul_vec.\n    apply hrr_max.\n    rewrite <- ? seq_mul_vec_vec_mul_vec.\n    eapply hrr_ex_seq ; [ apply seq_mul_vec_app_r | ].\n    eapply hrr_ex_hseq ; [ apply Permutation_Type_swap | ].\n    eapply hrr_ex_seq ; [ apply seq_mul_vec_app_r | ].\n    eapply hrr_ex_hseq ; [ apply Permutation_Type_swap | ].\n    change (seq_mul_vec r1 (vec r B ++ T) :: seq_mul_vec r1 (vec r A ++ T) :: map (fun x : list Rpos * sequent => seq_mul_vec (fst x) (snd x)) L) with (map (fun x => seq_mul_vec (fst x) (snd x)) ((r1, vec r B ++ T) :: (r1, vec r A ++ T) :: L)).\n    apply IHpi; reflexivity.\n  - destruct L; try destruct p as [r1 T1]; inversion HeqG; subst.\n    simpl.\n    eapply hrr_ex_seq ; [ symmetry; apply seq_mul_vec_app_r | ].\n    rewrite seq_mul_vec_vec_mul_vec.\n    apply hrr_min;\n      rewrite <- ? seq_mul_vec_vec_mul_vec;\n      (eapply hrr_ex_seq ; [ apply seq_mul_vec_app_r | ]);\n      [ change (seq_mul_vec r1 (vec r A ++ T) :: map (fun x : list Rpos * sequent => seq_mul_vec (fst x) (snd x)) L) with (map (fun x => seq_mul_vec (fst x) (snd x)) ((r1, vec r A ++ T) :: L)) ; apply IHpi1\n      | change (seq_mul_vec r1 (vec r B ++ T) :: map (fun x : list Rpos * sequent => seq_mul_vec (fst x) (snd x)) L) with (map (fun x => seq_mul_vec (fst x) (snd x)) ((r1, vec r B ++ T) :: L)) ; apply IHpi2 ];\n      reflexivity.\n  - destruct L; try destruct p0 as [r1 T1']; inversion HeqG; subst.\n    simpl.\n    eapply hrr_ex_seq ; [ apply seq_mul_vec_perm_r; apply p | ].\n    change (seq_mul_vec r1 T1 :: map (fun x : list Rpos * sequent => seq_mul_vec (fst x) (snd x)) L)\n      with\n        (map (fun x : list Rpos * sequent => seq_mul_vec (fst x) (snd x)) ((r1 , T1) :: L)).\n    apply IHpi; reflexivity.\n  - subst.\n    apply Permutation_Type_map_inv in p as [L' Heq Hperm].\n    eapply hrr_ex_hseq ; [ apply Permutation_Type_map ; symmetry; apply Hperm | ].\n    apply IHpi.\n    apply Heq.\n  - inversion f.\nQed.\n\n(** Proof of Lemma 3.39 *)\nLemma hrr_M_gen : forall L H D,\n    HR_T (map (fun x => snd x) L) ->\n    HR_T (D :: H) ->\n    HR_T (map (fun x => snd x ++ seq_mul_vec (fst x) D) L ++ H).\nProof.\n  intros L H D pi pi2.\n  remember (map (fun x => snd x) L) as G.\n  revert L HeqG.\n  induction pi; intros L HeqG.\n  - destruct L; try (destruct p as [r1 T1]; destruct T1); inversion HeqG; simpl.\n    destruct L; inversion H1; simpl.\n    assert {L & prod\n                  (H = map (fun x => snd x) L)\n                  (H = map (fun x => seq_mul_vec (fst x) (snd x)) L)} as [L [Heq1 Heq2]].\n    { clear; induction H.\n      - split with nil; split; reflexivity.\n      - destruct IHlist as [L [H1 H2]].\n        split with (((One :: nil), a) :: L).\n        simpl; split ; [ rewrite H1; reflexivity |  rewrite H2].\n        rewrite app_nil_r; rewrite seq_mul_One.\n        reflexivity. }\n    rewrite Heq2.\n    change (seq_mul_vec r1 D :: map (fun x : list Rpos * sequent => seq_mul_vec (fst x) (snd x)) L)\n      with\n        (map (fun x : list Rpos * sequent => seq_mul_vec (fst x) (snd x)) ((r1 , D) :: L)).\n    apply hrr_mul_vec.\n    simpl; rewrite <- Heq1.\n    apply pi2.\n  - destruct L; try destruct p as [r1 T1]; inversion HeqG; subst; simpl.\n    apply hrr_W.\n    apply IHpi; reflexivity.\n  - destruct L; try destruct p as [r1 T1]; inversion HeqG; subst; simpl.\n    apply hrr_C.\n    change ((T1 ++ seq_mul_vec r1 D)\n              :: (T1 ++ seq_mul_vec r1 D)\n              :: map (fun x : list Rpos * list (Rpos * term) => snd x ++ seq_mul_vec (fst x) D) L ++ H)\n      with\n        (map (fun x : list Rpos * list (Rpos * term) => snd x ++ seq_mul_vec (fst x) D) ((r1, T1) :: (r1 , T1) :: L) ++ H).\n    apply IHpi; reflexivity.\n  - destruct L; [ | destruct L]; try destruct p as [r1 T1']; try destruct p0 as [r2 T2']; inversion HeqG; subst; simpl.\n    apply hrr_S.\n    apply hrr_ex_seq with ((T1' ++ T2') ++ seq_mul_vec (r1 ++ r2) D).\n    { rewrite seq_mul_vec_app_l.\n      Permutation_Type_solve. }\n    change (((T1' ++ T2') ++ seq_mul_vec (r1 ++ r2) D)\n              :: map (fun x : list Rpos * list (Rpos * term) => snd x ++ seq_mul_vec (fst x) D) L ++ H)\n      with\n        (map (fun x : list Rpos * list (Rpos * term) => snd x ++ seq_mul_vec (fst x) D) ((r1 ++ r2, T1' ++ T2') :: L) ++ H).\n    apply IHpi; reflexivity.\n  - inversion f.\n  - destruct L; try destruct p as [r1 T1]; inversion HeqG; subst; simpl.\n    apply hrr_T with r; try assumption.\n    rewrite seq_mul_app; rewrite seq_mul_seq_mul_vec_2.\n    change ((seq_mul r T1 ++ seq_mul_vec (mul_vec r r1) D)\n              :: map (fun x : list Rpos * list (Rpos * term) => snd x ++ seq_mul_vec (fst x) D) L ++ H)\n      with\n        (map (fun x : list Rpos * list (Rpos * term) => snd x ++ seq_mul_vec (fst x) D) ((mul_vec r r1, seq_mul r T1) :: L) ++ H).\n    apply IHpi; reflexivity.\n  - destruct L; try destruct p as [r1 T1]; inversion HeqG; subst; simpl.\n    rewrite <- ? app_assoc; apply hrr_ID; try assumption.\n    change ((T ++ seq_mul_vec r1 D)\n              :: map (fun x : list Rpos * list (Rpos * term) => snd x ++ seq_mul_vec (fst x) D) L ++ H)\n      with\n        (map (fun x : list Rpos * list (Rpos * term) => snd x ++ seq_mul_vec (fst x) D) ((r1, T) :: L) ++ H).\n    apply IHpi; reflexivity.\n  - destruct L; try destruct p as [r1 T1]; inversion HeqG; subst; simpl.\n    rewrite <- ? app_assoc; apply hrr_Z; try assumption.\n    change ((T ++ seq_mul_vec r1 D)\n              :: map (fun x : list Rpos * list (Rpos * term) => snd x ++ seq_mul_vec (fst x) D) L ++ H)\n      with\n        (map (fun x : list Rpos * list (Rpos * term) => snd x ++ seq_mul_vec (fst x) D) ((r1, T) :: L) ++ H).\n    apply IHpi; reflexivity.\n  - destruct L; try destruct p as [r1 T1]; inversion HeqG; subst; simpl.\n    rewrite <- ? app_assoc; apply hrr_plus; try assumption.\n    replace ((vec r A ++ vec r B ++ T ++ seq_mul_vec r1 D)\n              :: map (fun x : list Rpos * list (Rpos * term) => snd x ++ seq_mul_vec (fst x) D) L ++ H)\n      with\n        (map (fun x : list Rpos * list (Rpos * term) => snd x ++ seq_mul_vec (fst x) D) ((r1, vec r A ++ vec r B ++ T) :: L) ++ H) by (simpl; rewrite <- ? app_assoc; reflexivity).\n    apply IHpi; reflexivity.\n  - destruct L; try destruct p as [r1 T1]; inversion HeqG; subst; simpl.\n    rewrite <- ? app_assoc; apply hrr_mul; try assumption.\n    replace ((vec (mul_vec r0 r) A ++ T ++ seq_mul_vec r1 D)\n              :: map (fun x : list Rpos * list (Rpos * term) => snd x ++ seq_mul_vec (fst x) D) L ++ H)\n      with\n        (map (fun x : list Rpos * list (Rpos * term) => snd x ++ seq_mul_vec (fst x) D) ((r1, vec (mul_vec r0 r) A ++ T) :: L) ++ H) by (simpl; rewrite <- ? app_assoc; reflexivity).\n    apply IHpi; reflexivity.\n  - destruct L; try destruct p as [r1 T1]; inversion HeqG; subst; simpl.\n    rewrite <- ? app_assoc; apply hrr_max; try assumption.\n    replace ((vec r B ++ T ++ seq_mul_vec r1 D) :: (vec r A ++ T ++ seq_mul_vec r1 D)\n              :: map (fun x : list Rpos * list (Rpos * term) => snd x ++ seq_mul_vec (fst x) D) L ++ H)\n      with\n        (map (fun x : list Rpos * list (Rpos * term) => snd x ++ seq_mul_vec (fst x) D) ((r1, vec r B ++ T) :: (r1, vec r A ++ T) :: L) ++ H) by (simpl; rewrite <- ? app_assoc; reflexivity).\n    apply IHpi; reflexivity.\n  - destruct L; try destruct p as [r1 T1]; inversion HeqG; subst; simpl.\n    rewrite <- ? app_assoc; apply hrr_min; try assumption;\n      [ replace ((vec r A ++ T ++ seq_mul_vec r1 D) :: map (fun x : list Rpos * list (Rpos * term) => snd x ++ seq_mul_vec (fst x) D) L ++ H)\n          with (map (fun x : list Rpos * list (Rpos * term) => snd x ++ seq_mul_vec (fst x) D) ((r1, vec r A ++ T) :: L) ++ H) by (simpl; rewrite <- ? app_assoc; reflexivity); apply IHpi1\n       | replace ((vec r B ++ T ++ seq_mul_vec r1 D) :: map (fun x : list Rpos * list (Rpos * term) => snd x ++ seq_mul_vec (fst x) D) L ++ H)\n           with (map (fun x : list Rpos * list (Rpos * term) => snd x ++ seq_mul_vec (fst x) D) ((r1, vec r B ++ T) :: L) ++ H)  by (simpl; rewrite <- ? app_assoc; reflexivity); apply IHpi2];\n      reflexivity.\n  - destruct L; try destruct p0 as [r1 T1']; inversion HeqG; subst; simpl.\n    eapply hrr_ex_seq ; [ apply Permutation_Type_app ; [ apply p | reflexivity] | ].\n    change ((T1 ++ seq_mul_vec r1 D) :: map (fun x : list Rpos * list (Rpos * term) => snd x ++ seq_mul_vec (fst x) D) L ++ H)\n      with (map (fun x : list Rpos * list (Rpos * term) => snd x ++ seq_mul_vec (fst x) D) ((r1, T1) :: L) ++ H).\n    apply IHpi; reflexivity.\n  - subst.\n    apply Permutation_Type_map_inv in p as [L' Heq Hperm].\n    eapply hrr_ex_hseq ; [ apply Permutation_Type_app ; [ apply Permutation_Type_map ; symmetry; apply Hperm | reflexivity ] | ].\n    apply IHpi.\n    apply Heq.\n  - inversion f.\nQed.\n\n(** Proof of Theorem 3.12 *)\nLemma hrr_M_elim : forall G,\n    HR_T_M G ->\n    HR_T G.\nProof.\n  intros G pi; induction pi; try now constructor.\n  - assert {L & prod\n                  (G = map (fun x => snd x) L)\n                  (G = map (fun x => snd x ++ seq_mul_vec (fst x) T2) L)} as [L [Heq1 Heq2]].\n    { clear; induction G.\n      - split with nil; split; reflexivity.\n      - destruct IHG as [L [H1 H2]].\n        split with ((nil, a) :: L).\n        simpl; split ; [ rewrite H1; reflexivity |  rewrite H2].\n        rewrite app_nil_r; reflexivity. }\n    apply hrr_ex_hseq with (G ++ ((T1 ++ T2) :: nil)); [ Permutation_Type_solve | ].\n    change (hr_frag_T) with hr_frag_T; apply hrr_C_gen.\n    apply hrr_ex_hseq with (((T1 ++ T2) :: G) ++ G); [ Permutation_Type_solve | ].\n    pattern G at 1; rewrite Heq2.\n    replace ((T1 ++ T2)\n               :: map (fun x : list Rpos * list (Rpos * term) => snd x ++ seq_mul_vec (fst x) T2) L)\n      with (map (fun x : list Rpos * list (Rpos * term) => snd x ++ seq_mul_vec (fst x) T2) ((One :: nil , T1) :: L)) by (simpl; rewrite app_nil_r; now rewrite seq_mul_One).\n    apply hrr_M_gen; try assumption.\n    simpl.\n    rewrite <- Heq1; apply IHpi1.\n  - now apply hrr_T with r.\n  - now apply hrr_ex_seq with T1.\n  - now apply hrr_ex_hseq with G.\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/hr/M_elim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631556226292, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2943399305325074}}
{"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 DePoolProxyContractProofs (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(* DePoolProxyContract_Ф_Constructor5 *)\n\nLemma DePoolProxyContract_Ф_Constructor5_exec : forall (l: Ledger) ,\nlet b := default in \nlet ok := false in\nlet b' := builder_store b ( eval_state ( msg_sender ) l )  0 in \nlet publicKey := tvm_hash ( toCell b' ) in\nlet ok' := ( ok || ( ( eval_state ( tvm_pubkey ) l ) =? publicKey ) )%bool in \nlet b'' := default in \nlet b''' := builder_store b'' ( eval_state ( msg_sender ) l ) 1 in\nlet publicKey' := tvm_hash ( toCell b''' )  in\nlet ok'' := ( ok' || ( ( eval_state ( tvm_pubkey ) l ) =? publicKey' ) )%bool in\nlet req : bool := ( ok'' ) in\n\nexec_state ( ↓ DePoolProxyContract_Ф_constructor5 ) l =\n                 if req then {$ l With DePoolProxyContract_ι_m_dePool := eval_state msg_sender l $}\n                        else l.\nProof.   \n   intros. \n   destruct l. \n   destruct Ledger_ι_VMState.\n   compute. destructIf; auto. \nQed. \n \nLemma DePoolProxyContract_Ф_Constructor5_eval : forall (l: Ledger) ,\n                          \nlet b := default in \nlet ok := false in\nlet b' := builder_store b ( eval_state msg_sender l ) 0 in \nlet publicKey := tvm_hash ( toCell b' ) in\nlet ok' := ( ok || (eval_state tvm_pubkey l =? publicKey) )%bool in \nlet b'' := default in \nlet b''' := builder_store b'' ( eval_state msg_sender l ) 1 in\nlet publicKey' := tvm_hash ( toCell b''' )  in\nlet ok'' := ( ok' || ( eval_state tvm_pubkey l =? publicKey' ) )%bool in\nlet req : bool := ( ok'' ) in\n\neval_state (↓ DePoolProxyContract_Ф_constructor5 ) l =  \n    if req then Value I\n           else Error DePoolProxyContract_ι_ERROR_IS_NOT_DEPOOL . \nProof. \n  intros. \n  destruct l.\n  compute. destructIf; auto. \nQed. \n \n(* DePoolProxyContract_Ф_process_new_stake *)\n\nLemma DePoolProxyContract_Ф_process_new_stake_exec : forall ( Л_queryId : XInteger64 ) \n                                                             ( Л_validatorKey : XInteger256 ) \n                                                             ( Л_stakeAt : XInteger32 ) \n                                                             ( Л_maxFactor : XInteger32 ) \n                                                             ( Л_adnlAddr : XInteger256 ) \n                                                             ( Л_signature :  XList XInteger8 ) \n                                                             ( Л_elector : XAddress ) \n                                                             (l: Ledger) ,\nlet msgSender := eval_state msg_sender l in\nlet dePoolAddress := eval_state (↑10 ε DePoolProxyContract_ι_m_dePool) l in\nlet msgValue := eval_state msg_value l in\nlet proxyFee := DePoolLib_ι_PROXY_FEE in  \nlet carry := msgValue - proxyFee in \nlet oldMessages := eval_state (↑16 ε VMState_ι_messages) l in \nlet newMessage :ContractsFunctionWithMessage  := {| contractAddress :=  Л_elector;\n                      contractFunction := IElector_И_process_new_stakeF Л_queryId Л_validatorKey Л_stakeAt Л_maxFactor Л_adnlAddr  Л_signature ;\n                      contractMessage :=  {| messageValue := carry;\n                                            messageFlag := 0 ;\n                                            messageBounce := false |} |} in \nlet balance := eval_state ( tvm_balance ) l in\nlet minBalance := DePoolLib_ι_MIN_PROXY_BALANCE in\nlet req2 : bool := balance >=? carry + minBalance in\n\n    exec_state ( ↓ DePoolProxyContract_Ф_process_new_stake Л_queryId Л_validatorKey Л_stakeAt Л_maxFactor Л_adnlAddr Л_signature Л_elector ) l =\n\n    if ( msgSender =? dePoolAddress) then\n      if req2 then  {$ l With VMState_ι_messages := newMessage :: oldMessages $} \n      else l \n    else l.  \n Proof. \n   intros. \n   destruct l. destruct Ledger_ι_VMState , Ledger_ι_DePoolProxyContract(* , Ledger_ι_DePoolLib *).\n   compute. \n   repeat destructIf; auto. \n Qed.\n\nLemma DePoolProxyContract_Ф_process_new_stake_eval : forall ( Л_queryId : XInteger64 ) \n                                                             ( Л_validatorKey : XInteger256 ) \n                                                             ( Л_stakeAt : XInteger32 ) \n                                                             ( Л_maxFactor : XInteger32 ) \n                                                             ( Л_adnlAddr : XInteger256 ) \n                                                             ( Л_signature : XList XInteger8 ) \n                                                             ( Л_elector : XAddress ) \n                                                             (l: Ledger) ,\nlet msgSender := eval_state msg_sender l in\nlet dePoolAddress := eval_state (↑10 D2! DePoolProxyContract_ι_m_dePool) l in\nlet error1 := DePoolProxyContract_ι_ERROR_IS_NOT_DEPOOL in\nlet error2 := DePoolProxyContract_ι_ERROR_BAD_BALANCE in\nlet msgValue := eval_state msg_value l in\nlet proxyFee := DePoolLib_ι_PROXY_FEE in \nlet carry := msgValue - proxyFee in \nlet balance := eval_state ( tvm_balance ) l in\nlet minBalance := DePoolLib_ι_MIN_PROXY_BALANCE in\nlet req2 : bool := balance >=? carry + minBalance in\n\n    eval_state (↓ DePoolProxyContract_Ф_process_new_stake Л_queryId Л_validatorKey Л_stakeAt Л_maxFactor Л_adnlAddr Л_signature Л_elector ) l = \n\n    if (msgSender =? dePoolAddress) then \n      if req2 then Value I\n              else Error error2\n    else Error error1 . \n Proof. \n  intros. \n  destruct l. destruct Ledger_ι_VMState , Ledger_ι_DePoolProxyContract (*, Ledger_ι_DePoolLib*).\n  compute. \n  repeat destructIf; auto. \n Qed. \n \n\n(* DePoolProxyContract_Ф_onStakeAccept *)\n\nLemma DePoolProxyContract_Ф_onStakeAccept_exec : forall ( Л_queryId : XInteger64 ) ( Л_comment : XInteger32 ) (l: Ledger) , \nlet dePoolAddress := eval_state (↑10 D2! DePoolProxyContract_ι_m_dePool) l in\nlet msgValue := eval_state msg_value l in\nlet proxyFee := DePoolLib_ι_PROXY_FEE in\nlet value := msgValue - proxyFee in\nlet msgSender := eval_state msg_sender l in\nlet oldMessages := eval_state (↑16 D2! VMState_ι_messages) l in\nlet newMessage  := {| contractAddress  := dePoolAddress;\n                      contractFunction := DePoolContract_Ф_onStakeAcceptF Л_queryId Л_comment msgSender ;\n                      contractMessage  := {$ default with messageValue := value $} |} in \n                                                    \n    exec_state (↓ DePoolProxyContract_Ф_onStakeAccept Л_queryId Л_comment ) l =  {$ l With VMState_ι_messages := newMessage :: oldMessages $}.  \nProof. \n  intros. auto. \nQed. \n \nLemma DePoolProxyContract_Ф_onStakeAccept_eval : forall ( Л_queryId : XInteger64 ) ( Л_comment : XInteger32 ) (l: Ledger) , \n \t eval_state (↓ DePoolProxyContract_Ф_onStakeAccept Л_queryId Л_comment ) l = I . \nProof. \n  intros. auto.  \nQed. \n\n\n(* DePoolProxyContract_Ф_onStakeReject *) \n\nLemma DePoolProxyContract_Ф_onStakeReject_exec : forall ( Л_queryId : XInteger64 ) ( Л_comment : XInteger32 ) (l: Ledger) , \nlet dePoolAddress := eval_state (↑10 D2! DePoolProxyContract_ι_m_dePool) l in\nlet msgValue := eval_state msg_value l in\nlet proxyFee := DePoolLib_ι_PROXY_FEE in\nlet value := msgValue - proxyFee in\nlet msgSender := eval_state msg_sender l in\nlet oldMessages := eval_state (↑16 D2! VMState_ι_messages) l in\nlet newMessage  := {| contractAddress  := dePoolAddress;\n                      contractFunction := DePoolContract_Ф_onStakeRejectF Л_queryId Л_comment msgSender ;\n                      contractMessage  := {$ default with messageValue := value $} |} in                                                  \n      \n    exec_state ( ↓ DePoolProxyContract_Ф_onStakeReject Л_queryId Л_comment ) l = {$ l With VMState_ι_messages := newMessage :: oldMessages $}. \n Proof. \n   intros. auto. \n Qed. \n \n Lemma DePoolProxyContract_Ф_onStakeReject_eval : forall ( Л_queryId : XInteger64 ) \n                                                         ( Л_comment : XInteger32 ) \n                                                         (l: Ledger) , \n \t eval_state ( ↓ DePoolProxyContract_Ф_onStakeReject Л_queryId Л_comment ) l = I . \n Proof. \n   intros. auto. \n Qed. \n \n\n(* DePoolProxyContract_Ф_recover_stake *) \n         \nLemma DePoolProxyContract_Ф_recover_stake_exec : forall ( Л_queryId : XInteger64 ) \n                                                        ( Л_elector : XAddress ) \n                                                        (l: Ledger) ,\nlet dePoolAddress := eval_state (↑10 ε DePoolProxyContract_ι_m_dePool) l in\nlet msgValue := eval_state msg_value l in\nlet proxyFee := DePoolLib_ι_PROXY_FEE in\nlet value := msgValue - proxyFee in\nlet msgSender := eval_state msg_sender l in\nlet oldMessages := eval_state (↑16 ε VMState_ι_messages) l in\nlet newMessage  := {| contractAddress  := Л_elector;\n                      contractFunction := IElector_И_recover_stakeF Л_queryId ;\n                      contractMessage  := {$ default with messageValue := value $} |} in  \nlet carry := msgValue - proxyFee in \nlet balance := eval_state ( tvm_balance ) l in\nlet minBalance := DePoolLib_ι_MIN_PROXY_BALANCE in\nlet req2 : bool := balance >=? carry + minBalance in\n    \n    exec_state ( ↓ DePoolProxyContract_Ф_recover_stake Л_queryId Л_elector ) l = \n    if (msgSender =? dePoolAddress) \n        then if req2 \n            then {$ l With VMState_ι_messages := newMessage :: oldMessages $} \n            else l\n        else l.  \n Proof. \n  intros.\n  destruct l. \n  compute; repeat destructIf; auto. \n Qed. \n \nLemma DePoolProxyContract_Ф_recover_stake_eval : forall ( Л_queryId : XInteger64 ) \n                                                        ( Л_elector : XAddress ) \n                                                        (l: Ledger),\nlet msgSender := eval_state msg_sender l in\nlet dePoolAddress := eval_state (↑10 D2! DePoolProxyContract_ι_m_dePool) l in\nlet error1 := DePoolProxyContract_ι_ERROR_IS_NOT_DEPOOL in \nlet error2 := DePoolProxyContract_ι_ERROR_BAD_BALANCE in \nlet proxyFee := DePoolLib_ι_PROXY_FEE in\nlet msgValue := eval_state msg_value l in\nlet carry := msgValue - proxyFee in \nlet balance := eval_state ( tvm_balance ) l in\nlet minBalance := DePoolLib_ι_MIN_PROXY_BALANCE in\nlet req2 : bool := balance >=? carry + minBalance in\n \n    eval_state (DePoolProxyContract_Ф_recover_stake Л_queryId Л_elector ) l = \n    if (msgSender =? dePoolAddress) then \n       if req2 then xValue I \n               else xError error2 \n    else xError error1 . \n Proof. \n  intros.\n  destruct l. \n  compute; repeat destructIf; auto.\n Qed. \n\n\n(* DePoolProxyContract_Ф_onSuccessToRecoverStake *) \n\nLemma DePoolProxyContract_Ф_onSuccessToRecoverStake_exec : forall ( Л_queryId : XInteger64 ) (l: Ledger) , \nlet dePoolAddress := eval_state (↑10 D2! DePoolProxyContract_ι_m_dePool) l in\nlet msgValue := eval_state msg_value l in\nlet proxyFee := DePoolLib_ι_PROXY_FEE in\nlet value := msgValue - proxyFee in\nlet msgSender := eval_state msg_sender l in\nlet oldMessages := eval_state (↑16 D2! VMState_ι_messages) l in\nlet newMessage  := {| contractAddress  := dePoolAddress;\n                      contractFunction := DePoolContract_Ф_onSuccessToRecoverStakeF Л_queryId msgSender ;\n                      contractMessage  := {$ default with messageValue := value $} |} in \n\n    exec_state (DePoolProxyContract_Ф_onSuccessToRecoverStake Л_queryId) l =  \n               {$ l With VMState_ι_messages := newMessage :: oldMessages $}.  \n Proof. \n  intros.  auto.\n Qed. \n \n Lemma DePoolProxyContract_Ф_onSuccessToRecoverStake_eval : forall ( Л_queryId : XInteger64 ) (l: Ledger) , \n \t eval_state (DePoolProxyContract_Ф_onSuccessToRecoverStake Л_queryId ) l = I . \n Proof. \n   intros. auto. \n Qed. \n\n\n\n(* DePoolProxyContract_Ф_getProxyInfo *) \n\n\nLemma DePoolProxyContract_Ф_getProxyInfo_exec : forall (l: Ledger) , \n \t exec_state ( ↓ DePoolProxyContract_Ф_getProxyInfo ) l = l .  \nProof. \n    intros. destruct l; compute; auto. \nQed. \n \nLemma DePoolProxyContract_Ф_getProxyInfo_eval : forall (l: Ledger) , \n                           (*  LedgerT ( XAddress # XInteger64 ) *)\nlet dePool := eval_state (↑10 ε DePoolProxyContract_ι_m_dePool) l in\nlet minBalance := DePoolLib_ι_MIN_PROXY_BALANCE in\n\n    eval_state ( ↓ DePoolProxyContract_Ф_getProxyInfo ) l = (dePool, minBalance). \nProof. \n  intros. destruct l ; compute ; auto. \nQed. \n \nEnd DePoolProxyContractProofs.", "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/DePoolProxyContractProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2943048736351415}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nFrom extructures Require Import ord fmap.\nFrom CoqUtils Require Import hseq word.\n\nRequire Import lib.utils common.types.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport DoNotation.\n\nModule Symbolic.\n\n(* BCP/AAA: Should some of this be shared with the concrete machine? *)\n\n(* CH: These could move to types.v?  But they would be useful only if\n       we want to make the concrete machine dependently typed too; and\n       we probably don't want to do that. *)\n\nInductive tag_kind : Type := R | M | P.\n\nModule Import TagKindEq.\nDefinition tag_kind_eq (tk1 tk2 : tag_kind) : bool :=\n  match tk1, tk2 with\n  | R, R | M, M | P, P => true | _, _ => false\n  end.\n\nLemma tag_kind_eqP : Equality.axiom tag_kind_eq.\nProof. by do !case; constructor. Qed.\n\nDefinition tag_kind_eqMixin := EqMixin tag_kind_eqP.\nCanonical tag_kind_eqType := Eval hnf in EqType tag_kind tag_kind_eqMixin.\nEnd TagKindEq.\n\nDefinition inputs (op : opcode) : seq tag_kind :=\n  match op with\n  | NOP     => [:: ]\n  | CONST   => [:: R]\n  | MOV     => [:: R;R]\n  | BINOP _ => [:: R;R;R]\n  | LOAD    => [:: R;M;R]\n  | STORE   => [:: R;R;M]\n  | JUMP    => [:: R]\n  | BNZ     => [:: R]\n  | JAL     => [:: R;R]\n  (* the other opcodes are not used by the symbolic machine *)\n  | JUMPEPC => [:: P]\n  | ADDRULE => [::]\n  | GETTAG  => [:: R;R]\n  | PUTTAG  => [:: R;R;R]\n  | HALT    => [::] (* CH: in a way this is used by symbolic machine;\n                           it just causes it to get stuck as it should *)\n  end.\n\n(* Returns true iff an opcode can only be executed by the monitor *)\nDefinition privileged_op (op : vopcode) : bool :=\n  match op with\n  | JUMPEPC\n  | ADDRULE\n  | GETTAG\n  | PUTTAG => true\n  | _ => false\n  end.\n\nDefinition vinputs (vop : vopcode) : seq tag_kind :=\n  match vop with\n  | OP op => inputs op\n  | SERVICE => [::]\n  end.\n\nDefinition outputs (op : opcode) : option tag_kind :=\n  match op with\n  | NOP     => None\n  | CONST   => Some R\n  | MOV     => Some R\n  | BINOP _ => Some R\n  | LOAD    => Some R\n  | STORE   => Some M\n  | JUMP    => None\n  | BNZ     => None\n  | JAL     => Some R\n  (* the other opcodes are not used by the symbolic machine *)\n  | JUMPEPC => None\n  | ADDRULE => None\n  | GETTAG  => Some R\n  | PUTTAG  => None\n  | HALT    => None\n  end.\n\nSection WithTagTypes.\n\nStructure tag_types := {\n  pc_tag_type : eqType;\n  reg_tag_type : eqType;\n  mem_tag_type : eqType;\n  entry_tag_type : eqType\n}.\n\nVariable tty : tag_types.\n\nDefinition tag_type tk :=\n  match tk with\n  | P => pc_tag_type tty\n  | R => reg_tag_type tty\n  | M => mem_tag_type tty\n  end.\n\nDefinition instr_tag (op : vopcode) :=\n  match op with\n  | SERVICE => entry_tag_type tty\n  | _ => mem_tag_type tty\n  end.\n\nRecord ivec : Type := IVec {\n  op  : vopcode;\n  tpc : tag_type P;\n  ti  : instr_tag op;\n  ts  : hseq tag_type (vinputs op)\n}.\n\nLemma ivec_eq_inv op op' tpc tpc' ti ti' ts ts'\n                  (p : @IVec op tpc ti ts = @IVec op' tpc' ti' ts') :\n  [/\\ op = op', tpc = tpc',\n      Tagged instr_tag ti = Tagged instr_tag ti' &\n      Tagged (hseq tag_type \\o vinputs) ts = existT _ op' ts'].\nProof. inversion p. by constructor. Qed.\n\nDefinition type_of_result (o : option tag_kind) :=\n  odflt [eqType of unit] (option_map tag_type o).\n\nRecord ovec (op : opcode) : Type := OVec {\n  trpc : tag_type P;\n  tr   : type_of_result (outputs op)\n}.\n\nDefinition vovec (vop : vopcode) : Type :=\n  match vop with\n  | OP op => ovec op\n  | SERVICE => unit\n  end.\n\nEnd WithTagTypes.\n\nArguments IVec {_} _ _ _ _.\n\nOpen Scope bool_scope.\n\nSection WithClasses.\n\nContext (mt : machine_types)\n        {ops : machine_ops mt}.\n\nClass params := {\n  ttypes :> tag_types;\n\n  transfer : forall (iv : ivec ttypes), option (vovec ttypes (op iv));\n\n  internal_state : eqType\n}.\n\nContext {sp : params}.\n\nOpen Scope word_scope.\n\nLocal Notation word := (mword mt).\nLet atom := (atom word).\nLocal Notation \"x .+1\" := (x + 1).\n\nLocal Notation memory := {fmap word -> atom (tag_type ttypes M)}.\nLocal Notation registers := {fmap reg mt -> atom (tag_type ttypes R)}.\n\nRecord state := State {\n  mem : memory;\n  regs : registers;\n  pc : atom (tag_type ttypes P);\n  internal : internal_state\n}.\n\nDefinition pcv (s : state) := vala (pc s).\nDefinition pct (s : state) := taga (pc s).\n\nLemma state_eta st :\n  st = State (mem st) (regs st) (pcv st)@(pct st) (internal st).\nProof. by case: st=> ? ? [? ?] ?. Qed.\n\n(* CH: TODO: should make the entry_tags part of the state\n   (for compartmentalization they need to be mutable) *)\nRecord syscall := Syscall {\n  entry_tag : entry_tag_type ttypes;\n  sem : state -> option state\n}.\n\nDefinition syscall_table := {fmap mword mt -> syscall}.\n\nVariable table : syscall_table.\n\nDefinition run_syscall (sc : syscall) (st : state) : option state :=\n  match transfer (IVec SERVICE (taga (pc st)) (entry_tag sc) [hseq]) with\n  | Some _ => sem sc st\n  | None => None\n  end.\n\nDefinition next_state (st : state) (iv : ivec ttypes)\n                      (k : vovec ttypes (op iv) -> option state) : option state :=\n  do! ov <- transfer iv;\n    k ov.\n\nDefinition next_state_reg_and_pc (st : state) (iv : @ivec ttypes)\n  (r : reg mt) (x : word) (pc' : word) : option state :=\n  next_state st (\n    match op iv as o return vovec _ o -> option state with\n    | OP op => fun ov =>\n      match outputs op as o return (type_of_result _ o -> option state) with\n        | Some R => fun tr' =>\n            do! regs' <- updm (regs st) r x@tr';\n            Some (State (mem st) regs' pc'@(trpc ov) (internal st))\n        | _ => fun _ => None\n      end (tr ov)\n    | SERVICE => fun _ => None\n    end\n  ).\n\nDefinition next_state_reg (st : state) (mvec : @ivec ttypes) 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) (iv : @ivec ttypes)\n  (x : word) : option state :=\n  next_state st (\n    match op iv as o return vovec _ o -> option state with\n    | OP op => fun ov =>\n                 Some (State (mem st) (regs st) x@(trpc ov) (internal st))\n    | SERVICE => fun _ => None\n    end\n  ).\n\nInductive step (st st' : state) : Prop :=\n| step_nop : forall mem reg pc tpc i ti extra\n    (ST   : st = State mem reg pc@tpc extra)\n    (PC   : mem pc = Some i@ti)\n    (INST : decode_instr i = Some (Nop _)),\n    let mvec := IVec NOP tpc ti [hseq] in forall\n    (NEXT : next_state_pc st mvec (pc.+1) = Some st'),    step st st'\n| step_const : forall mem reg pc tpc i ti n r old (told : tag_type ttypes R) extra\n    (ST   : st = State mem reg pc@tpc extra)\n    (PC   : mem pc = Some i@ti)\n    (INST : decode_instr i = Some (Const n r))\n    (OLD  : reg r = Some old@told),\n    let mvec := IVec CONST tpc ti [hseq told] in forall\n    (NEXT : next_state_reg st mvec r (swcast n) = Some st'),   step st st'\n| step_mov : forall mem reg pc tpc i ti r1 w1 t1 r2 old told extra\n    (ST   : st = State mem reg pc@tpc extra)\n    (PC   : mem pc = Some i@ti)\n    (INST : decode_instr i = Some (Mov r1 r2))\n    (R1W  : reg r1 = Some w1@t1)\n    (OLD  : reg r2 = Some old@told),\n    let mvec := IVec MOV tpc ti [hseq t1; told] in forall\n    (NEXT : next_state_reg st mvec r2 w1 = Some st'),   step st st'\n| step_binop : forall mem reg pc tpc i ti op r1 r2 r3 w1 w2 t1 t2 old told extra\n    (ST   : st = State mem reg pc@tpc extra)\n    (PC   : mem pc = Some i@ti)\n    (INST : decode_instr i = Some (Binop op r1 r2 r3))\n    (R1W  : reg r1 = Some w1@t1)\n    (R2W  : reg r2 = Some w2@t2)\n    (OLD  : reg r3 = Some old@told),\n    let mvec := IVec (BINOP op) tpc ti [hseq t1; t2; told] in forall\n    (NEXT : next_state_reg st mvec r3 (binop_denote op w1 w2) = Some st'),\n      step st st'\n| step_load : forall mem reg pc tpc i ti r1 r2 w1 w2 t1 t2 old told extra\n    (ST   : st = State mem reg pc@tpc extra)\n    (PC   : mem pc = Some i@ti)\n    (INST : decode_instr i = Some (Load r1 r2))\n    (R1W  : reg r1 = Some w1@t1)\n    (MEM1 : mem w1 = Some w2@t2)\n    (OLD  : reg r2 = Some old@told),\n    let mvec := IVec LOAD tpc ti [hseq t1; t2; told] in forall\n    (NEXT : next_state_reg st mvec r2 w2 = Some st'),    step st st'\n| step_store : forall mem reg pc i r1 r2 w1 w2 tpc ti t1 t2 old told extra\n    (ST   : st = State mem reg pc@tpc extra)\n    (PC   : mem pc = Some i@ti)\n    (INST : decode_instr i = Some (Store r1 r2))\n    (R1W  : reg r1 = Some w1@t1)\n    (R2W  : reg r2 = Some w2@t2)\n    (OLD  : mem w1 = Some old@told),\n    let mvec := IVec STORE tpc ti [hseq t1; t2; told] in forall\n    (NEXT : @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)) = Some st'),\n              step st st'\n| step_jump : forall mem reg pc i r w tpc ti t1 extra\n    (ST   : st = State mem reg pc@tpc extra)\n    (PC   : mem pc = Some i@ti)\n    (INST : decode_instr i = Some (Jump r))\n    (RW   : reg r = Some w@t1),\n    let mvec := IVec JUMP tpc ti [hseq t1] in forall\n    (NEXT : next_state_pc st mvec w = Some st'),    step st st'\n| step_bnz : forall mem reg pc i r n w tpc ti t1 extra\n    (ST   : st = State mem reg pc@tpc extra)\n    (PC   : mem pc = Some i@ti)\n    (INST : decode_instr i = Some (Bnz r n))\n    (RW   : reg r = Some w@t1),\n     let mvec := IVec BNZ tpc ti [hseq t1] in\n     let pc' := pc + (if w == 0%w\n                      then 1%w else swcast n) in forall\n    (NEXT : next_state_pc st mvec pc' = Some st'),     step st st'\n| step_jal : forall mem reg pc i r w tpc ti t1 old told extra\n    (ST : st = State mem reg pc@tpc extra)\n    (PC : mem pc = Some i@ti)\n    (INST : decode_instr i = Some (Jal r))\n    (RW : reg r = Some w@t1)\n    (OLD : reg ra = Some old@told),\n     let mvec := IVec JAL tpc ti [hseq t1; told] in forall\n    (NEXT : next_state_reg_and_pc st mvec ra (pc.+1) w = Some st'), step st st'\n| step_syscall : forall mem reg pc sc tpc extra\n    (ST : st = State mem reg pc@tpc extra)\n    (PC : mem pc = None)\n    (GETCALL : table pc = Some sc)\n    (CALL : run_syscall sc st = Some st'), step st st'.\n\nEnd WithClasses.\n\nNotation memory mt s := {fmap mword mt -> atom (mword mt) (@tag_type (@ttypes s) M)}.\nNotation registers mt s := {fmap reg mt -> atom (mword mt) (@tag_type (@ttypes s) R)}.\n\nEnd Symbolic.\n\nModule Exports.\n\nImport Symbolic.\n\nDefinition state_eqb mt p : rel (@state mt p) :=\n  [rel s1 s2 | [&& mem s1 == mem s2,\n                   regs s1 == regs s2,\n                   pc s1 == pc s2 &\n                   internal s1 == internal s2 ] ].\n\nLemma state_eqbP mt p : Equality.axiom (@state_eqb mt p).\nProof.\n  move => [? ? ? ?] [? ? ? ?].\n  apply (iffP and4P); simpl.\n  - by move => [/eqP -> /eqP -> /eqP -> /eqP ->].\n  - by move => [-> -> -> ->].\nQed.\n\nDefinition state_eqMixin mt p := EqMixin (@state_eqbP mt p).\nCanonical state_eqType mt p := Eval hnf in EqType _ (@state_eqMixin mt p).\n\nExport TagKindEq.\n\nEnd Exports.\n\nExport Exports.\n\nArguments Symbolic.state mt {_}.\nArguments Symbolic.State {_ _} _ _ _ _.\nArguments Symbolic.syscall mt {_}.\nArguments Symbolic.syscall_table mt {_}.\nArguments Symbolic.IVec {tty} op _ _ _.\nArguments Symbolic.OVec {tty op} _ _.\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/symbolic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2943048615275116}}
{"text": "Require Import Coq.Program.Equality.\nRequire Export Coq.Program.Tactics.\nRequire Export DeclarationEvaluation.\nSet Implicit Arguments.\n\n(******************************************************************************)\n(* Weakening lemmas                                                           *)\n(******************************************************************************)\n\nLemma shift_value {t} :\n  ∀ {c}, Value t → Value (shiftTm c t).\nProof.\n  induction t; simpl; intros; try contradiction; destruct_conjs; auto.\nQed.\n\nLemma tshift_value {t} :\n  ∀ {c}, Value t → Value (tshiftTm c t).\nProof.\n  induction t; simpl; intros; try contradiction; destruct_conjs; auto.\nQed.\n\nLemma weaken_value u :\n  ∀ {t}, Value t → Value (weakenTm t u).\nProof.\n  induction u as [|[]]; simpl; auto using shift_value, tshift_value.\nQed.\n\n(******************************************************************************)\n(* Progress                                                                   *)\n(******************************************************************************)\n\nLemma can_form_tarr {Γ t T1 T2} (v: Value t) (wt: Typing Γ t (tarr T1 T2)) :\n  ∃ t2, t = abs T1 t2.\nProof.\n  depind wt; try contradiction; exists t; reflexivity.\nQed.\n\nLemma can_form_tall {Γ t T} (v: Value t) (wt: Typing Γ t (tall T)) :\n  ∃ t1, t = tabs t1.\nProof.\n  depind wt; try contradiction; exists t; reflexivity.\nQed.\n\nLemma can_form_texist {Γ t T} (v: Value t) (wt: Typing Γ t (texist T)) :\n  ∃ T11 t12, t = pack T11 t12 (texist T).\nProof.\n  depind wt; try contradiction; exists U, t2; reflexivity.\nQed.\n\nLemma can_form_tprod {Γ t T1 T2} (v: Value t) (wt: Typing Γ t (tprod T1 T2)) :\n  ∃ t1 t2, t = prod t1 t2 ∧ Typing Γ t1 T1 ∧ Typing Γ t2 T2.\nProof.\n  depind wt; try contradiction; exists t1, t2; auto.\nQed.\n\nLemma matching_defined {Γ p T1 Δ} (wp: PTyping Γ p T1 Δ) :\n  ∀ {t1}, Value t1 → Typing Γ t1 T1 → ∀ t2, ∃ t2', Match p t1 t2 t2'.\nProof.\n  induction wp; intros t1 v1 wt1 t2; isimpl.\n  - exists (substTm X0 t1 t2).\n    refine M_Var.\n  - destruct (can_form_tprod v1 wt1) as (t11 & t12 & eq & wt11 & wt12); subst.\n    destruct v1 as [v11 v12].\n    apply (weaken_Typing G) in wt12.\n    assert (val12' : Value (weakenTm t12 (domainEnv G)))\n       by (apply weaken_value; auto).\n    rewrite <- (domain_PTyping_bindPat _ _ _ _  wp1) in *.\n    destruct (IHwp2 (weakenTm t12 (domainEnv G)) val12' wt12 t2) as [t2' m2].\n    destruct (IHwp1 _ v11 wt11 t2') as [t2'' m1].\n    rewrite (domain_PTyping_bindPat _ _ _ _ wp1) in m2.\n    exists t2''.\n    exact (M_Prod m2 m1).\nQed.\n\nLemma progress {t U} (wt: Typing empty t U) :\n  Value t ∨ ∃ t', red t t'.\nProof with try (subst; eauto using red).\n  depind wt; simpl; auto.\n  - destruct IHwt1 as [v1|[t1' r1]]...\n    destruct IHwt2 as [v2|[t2' r2]]...\n    destruct (can_form_tarr v1 wt1)...\n  - destruct IHwt as [vt|[t1' r1]]...\n    destruct (can_form_tall vt wt)...\n  - destruct IHwt as [vt|[t1' r1]]...\n  - destruct IHwt1 as [v1|[t1' r1]]...\n    destruct (can_form_texist v1 wt1) as [? [? ?]]...\n  - destruct IHwt1 as [v1|[t1' r1]]...\n    destruct IHwt2 as [v2|[t2' r2]]...\n  - destruct IHwt1 as [v1|[t1' r1]]...\n    destruct (matching_defined wtp v1 wt1 t2)...\nQed.\n\n(******************************************************************************)\n(* Preservation                                                               *)\n(******************************************************************************)\n\nLemma local_preservation_lett {p t1 t2 t2'} (m: Match p t1 t2 t2') :\n  ∀ {Γ T1 T2 Δ}, PTyping Γ p T1 Δ → Typing Γ t1 T1 →\n    Typing (appendEnv Γ Δ) t2 (weakenTy T2 (domainEnv Δ)) → Typing Γ t2' T2.\nProof.\n  induction m; intros Γ T1 T2 Δ wp wt1 wt2; isimpl.\n  - dependent destruction wp; simpl in *.\n    eauto using subst_evar_Typing with infra.\n  - dependent destruction wp. dependent destruction wt1. isimpl.\n    eapply IHm2; eauto.\n    eapply IHm1; eauto.\n    rewrite <- (domain_PTyping_bindPat _ _ _ _ wp1) in *.\n    eauto using weaken_Typing with infra.\nQed.\n\nLemma preservation {Γ t U} (wt: Typing Γ t U) :\n  ∀ {t'}, red t t' → Typing Γ t' U.\nProof.\n  induction wt; intros t' r; inversion r; subst; eauto using Typing.\n  - inversion wt1; eauto using subst_evar_Typing with subst.\n  - inversion wt; eauto using subst_etvar_Typing with subst.\n  - inversion wt1; subst; clear wt1; rewrite tsubstTm_substTm0_comm; isimpl.\n    eapply subst_evar_Typing; eauto with infra.\n    generalize (subst_etvar_Typing _ _ H47 _ _ _ wt2\n                 (evar G2 (tsubstTy X0 T11 T12)) (XS tm X0)).\n    isimpl; eauto with infra.\n  - eapply local_preservation_lett; eauto; isimpl.\n    rewrite <- (domain_PTyping_bindPat _ _ _ _ wtp) in *; eauto.\nQed.\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/casestudy/needle/fexistsprod/MetaTheory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.2942546279364071}}
{"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 Lia.\nRequire Import DataRuntime.\nRequire Import NRA.\n\nSection NRASize.\n  Context {fruntime:foreign_runtime}.\n\n  Fixpoint nra_size (a:nra) : nat :=\n    match a with\n    | NRAGetConstant s => 1\n    | NRAID => 1\n    | NRAConst d => 1\n    | NRABinop op a₁ a₂ => S (nra_size a₁ + nra_size a₂)\n    | NRAUnop op a₁ => S (nra_size a₁)\n    | NRAMap a₁ a₂ => S (nra_size a₁ + nra_size a₂)\n    | NRAMapProduct a₁ a₂ => S (nra_size a₁ + nra_size a₂)\n    | NRAProduct a₁ a₂ => S (nra_size a₁ + nra_size a₂)\n    | NRASelect a₁ a₂ => S (nra_size a₁ + nra_size a₂)\n    | NRADefault a₁ a₂ => S (nra_size a₁ + nra_size a₂)\n    | NRAEither a₁ a₂=> S (nra_size a₁ + nra_size a₂)\n    | NRAEitherConcat a₁ a₂ => S (nra_size a₁ + nra_size a₂)\n    | NRAApp a₁ a₂ => S (nra_size a₁ + nra_size a₂)\n    end.\n\n  Lemma nra_size_nzero (a:nra) : nra_size a <> 0.\n  Proof.\n    induction a; simpl; lia.\n  Qed.\n\n  Fixpoint nra_depth (a:nra) : nat :=\n    (* Better to start at zero, level one is at least one nested plan *)\n    match a with\n    | NRAGetConstant s => 0\n    | NRAID => 0\n    | NRAConst d => 0\n    | NRABinop op a₁ a₂ => max (nra_depth a₁) (nra_depth a₂)\n    | NRAUnop op a₁ => nra_depth a₁\n    | NRAMap a₁ a₂ => max (S (nra_depth a₁)) (nra_depth a₂)\n    | NRAMapProduct a₁ a₂ => max (S (nra_depth a₁)) (nra_depth a₂)\n    | NRAProduct a₁ a₂ => max (nra_depth a₁) (nra_depth a₂)\n    | NRASelect a₁ a₂ => max (S (nra_depth a₁)) (nra_depth a₂)\n    | NRADefault a₁ a₂ => max (nra_depth a₁) (nra_depth a₂)\n    | NRAEither a₁ a₂=> max (nra_depth a₁) (nra_depth a₂)\n    | NRAEitherConcat a₁ a₂ => max (nra_depth a₁) (nra_depth a₂)\n    | NRAApp a₁ a₂ => max (nra_depth a₁) (nra_depth a₂)\n    end.\n\nEnd NRASize.\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/Lang/NRASize.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.29425461257848506}}
{"text": "(******************************************************************************)\n(** * C11 is weaker than IMM_S   *)\n(******************************************************************************)\n\nRequire Import Classical Peano_dec.\nFrom hahn Require Import Hahn.\n\nRequire Import Events.\nRequire Import Execution.\nRequire Import Execution_eco.\nRequire Import imm_bob imm_s_ppo.\nRequire Import imm_s_hb.\nRequire Import imm_s C11.\n\nSet Implicit Arguments.\n\nSection C11_TO_IMM_S.\n\nVariable G : execution.\n\n(******************************************************************************)\n(** relations are contained in the corresponding ones **  *)\n(******************************************************************************)\n\nLemma s_imm_consistentimplies_c11_consistent (WF: Wf G) sc\n      (IPC : imm_s.imm_psc_consistent G sc) :\n  c11_consistent G.\nProof using.\n  cdes IPC. cdes IC. red. splits; auto.\nQed.\n\nEnd C11_TO_IMM_S.", "meta": {"author": "weakmemory", "repo": "imm", "sha": "7942cc3f204cabca065b8fbf749323c398bc0973", "save_path": "github-repos/coq/weakmemory-imm", "path": "github-repos/coq/weakmemory-imm/imm-7942cc3f204cabca065b8fbf749323c398bc0973/src/c11/C11Toimm_s.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593452091673, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.29422624734834735}}
{"text": "Require Import Classical Peano_dec Setoid PeanoNat.\nFrom hahn Require Import Hahn.\nRequire Import Omega.\n\nRequire Import Events.\nRequire Import Execution.\nRequire Import imm_s.\nRequire Import TraversalConfig.\nRequire Import Traversal.\nRequire Import SimTraversal.\nRequire Import SimTraversalProperties.\n\nSet Implicit Arguments.\nRemove Hints plus_n_O.\n\nDefinition countP (f: actid -> Prop) l :=\n  length (filterP f l).\n\nAdd Parametric Morphism : countP with signature\n    set_subset ==> eq ==> le as countP_mori.\nProof using.\n  ins. unfold countP.\n  induction y0.\n  { simpls. }\n  ins. desf; simpls.\n  1,3: omega.\n  exfalso. apply n. by apply H.\nQed.\n\nAdd Parametric Morphism : countP with signature\n    set_equiv ==> eq ==> eq as countP_more.\nProof using.\n  ins. unfold countP.\n  erewrite filterP_set_equiv; eauto.\nQed.\n\nSection TraversalCounting.\n  Variable G : execution.\n  Variable sc : relation actid.\n  Variable WF : Wf G.\n  \n  Notation \"'E'\" := G.(acts_set).\n  Notation \"'lab'\" := G.(lab).\n  Notation \"'W'\" := (fun x => is_true (is_w lab x)).\n  Notation \"'Rel'\" := (fun x => is_true (is_rel lab x)).\n  Notation \"'rmw'\" := G.(rmw).\n\n  Definition trav_steps_left (T : trav_config) :=\n    countP (set_compl (covered T)) G.(acts) +\n    countP (W ∩₁ set_compl (issued T)) G.(acts).\n  \n  Lemma trav_steps_left_decrease (T T' : trav_config)\n        (STEP : trav_step G sc T T') :\n    trav_steps_left T > trav_steps_left T'.\n  Proof using.\n    red in STEP. desc. red in STEP.\n    desf.\n    { unfold trav_steps_left.\n      rewrite ISSEQ.\n      assert (countP (set_compl (covered T)) (acts G) >\n              countP (set_compl (covered T')) (acts G)) as HH.\n      2: omega.\n      rewrite COVEQ.\n      unfold countP.\n      assert (List.In e (acts G)) as LL.\n      { apply COV. }\n      induction (acts G).\n      { done. }\n      destruct l as [|h l].\n      { assert (a = e); subst.\n        { inv LL. }\n        simpls. desf.\n        exfalso. apply s0. by right. }\n      destruct LL as [|H]; subst.\n      2: { apply IHl in H. clear IHl.\n           simpls. desf; simpls; try omega.\n           all: try by (exfalso; apply s0; left; apply NNPP).\n             by exfalso; apply s; left; apply NNPP. }\n      clear IHl.\n      assert (exists l', l' = h :: l) as [l' HH] by eauto.\n      rewrite <- HH. clear h l HH.\n      simpls. desf; simpls.\n      { exfalso. apply s0. by right. }\n      assert (length (filterP (set_compl (covered T ∪₁ eq e)) l') <=\n              length (filterP (set_compl (covered T)) l')).\n      2: omega.\n      eapply countP_mori; auto.\n      basic_solver. }\n    unfold trav_steps_left.\n    rewrite COVEQ.\n    assert (countP (W ∩₁ set_compl (issued T )) (acts G) >\n            countP (W ∩₁ set_compl (issued T')) (acts G)) as HH.\n    2: omega.\n    rewrite ISSEQ.\n    unfold countP.\n    assert (List.In e (acts G)) as LL.\n    { apply ISS. }\n    assert (W e) as WE.\n    { apply ISS. }\n    induction (acts G).\n    { done. }\n    destruct l as [|h l].\n    { assert (a = e); subst.\n      { inv LL. }\n      simpls. desf.\n      { exfalso. apply s0. by right. }\n      all: by exfalso; apply n; split. }\n    destruct LL as [|H]; subst.\n    2: { apply IHl in H. clear IHl.\n         simpls. desf; simpls; try omega.\n         1-2: by exfalso; apply n; destruct s0 as [H1 H2];\n           split; auto; intros HH; apply H2; left.\n         all: by exfalso; apply n; destruct s as [H1 H2];\n           split; auto; intros HH; apply H2; left. }\n    clear IHl.\n    assert (exists l', l' = h :: l) as [l' HH] by eauto.\n    rewrite <- HH. clear h l HH.\n    simpls. desf; simpls.\n    { exfalso. apply s0. by right. }\n    2: { exfalso. apply s. by right. }\n    2: { exfalso. apply n. by split. }\n    assert (length (filterP (W ∩₁ set_compl (issued T ∪₁ eq e)) l') <=\n            length (filterP (W ∩₁ set_compl (issued T)) l')).\n    2: omega.\n    eapply countP_mori; auto.\n    basic_solver.\n  Qed.\n\n  Lemma trav_steps_left_decrease_sim (T T' : trav_config)\n        (STEP : sim_trav_step G sc T T') :\n    trav_steps_left T > trav_steps_left T'.\n  Proof using.\n    red in STEP. desc.\n    destruct STEP.\n    1-4: by apply trav_steps_left_decrease; red; eauto.\n    { eapply lt_trans.\n      all: apply trav_steps_left_decrease; red; eauto. }\n    { eapply lt_trans.\n      all: apply trav_steps_left_decrease; red; eauto. }\n    eapply lt_trans.\n    eapply lt_trans.\n    all: apply trav_steps_left_decrease; red; eauto.\n  Qed.\n  \n  Lemma trav_steps_left_null_cov (T : trav_config)\n        (NULL : trav_steps_left T = 0) :\n    E ⊆₁ covered T.\n  Proof using.\n    unfold trav_steps_left in *.\n    assert (countP (set_compl (covered T)) (acts G) = 0) as HH by omega.\n    clear NULL.\n    unfold countP in *.\n    apply length_zero_iff_nil in HH.\n    intros x EX.\n    destruct (classic (covered T x)) as [|NN]; auto.\n    exfalso. \n    assert (In x (filterP (set_compl (covered T)) (acts G))) as UU.\n    2: { rewrite HH in UU. inv UU. }\n    apply in_filterP_iff. by split.\n  Qed.\n\n  Lemma trav_steps_left_ncov_nnull (T : trav_config) e\n        (EE : E e) (NCOV : ~ covered T e):\n    trav_steps_left T <> 0.\n  Proof using.\n    destruct (classic (trav_steps_left T = 0)) as [EQ|NEQ]; auto.\n    exfalso. apply NCOV. apply trav_steps_left_null_cov; auto.\n  Qed.\n\n  Lemma trav_steps_left_nnull_ncov (T : trav_config) (TCCOH : tc_coherent G sc T)\n        (NNULL : trav_steps_left T > 0):\n    exists e, E e /\\ ~ covered T e.\n  Proof using.\n    unfold trav_steps_left in *.\n    assert (countP (set_compl (covered T)) (acts G) > 0 \\/\n            countP (W ∩₁ set_compl (issued T)) (acts G) > 0) as YY by omega.\n    assert (countP (set_compl (covered T)) (acts G) > 0) as HH.\n    { destruct YY as [|YY]; auto.\n      assert (countP (set_compl (covered T)) (acts G) >=\n              countP (W ∩₁ set_compl (issued T)) (acts G)).\n      2: omega.\n      apply countP_mori; auto.\n      intros x [WX NN] COV.\n      apply NN. eapply w_covered_issued; eauto. by split. }\n    clear YY.\n    unfold countP in HH.\n    assert (exists h l, filterP (set_compl (covered T)) (acts G) = h :: l) as YY.\n    { destruct (filterP (set_compl (covered T)) (acts G)); eauto.\n      inv HH. }\n    desc. exists h.\n    assert (In h (filterP (set_compl (covered T)) (acts G))) as GG.\n    { rewrite YY. red. by left. }\n    apply in_filterP_iff in GG. simpls.\n  Qed.\n\n  Lemma trav_steps_left_decrease_sim_trans (T T' : trav_config)\n        (STEPS : (sim_trav_step G sc)⁺ T T') :\n    trav_steps_left T > trav_steps_left T'.\n  Proof using.\n    induction STEPS.\n    { by apply trav_steps_left_decrease_sim. }\n    eapply lt_trans; eauto.\n  Qed.\n\n  Theorem nat_ind_lt (P : nat -> Prop)\n          (HPi : forall n, (forall m, m < n -> P m) -> P n) :\n    forall n, P n.\n  Proof using.\n    set (Q n := forall m, m <= n -> P m).\n    assert (forall n, Q n) as HH.\n    2: { ins. apply (HH n). omega. }\n    ins. induction n.\n    { unfold Q. ins. inv H. apply HPi. ins. inv H0. }\n    unfold Q in *. ins.\n    apply le_lt_eq_dec in H.\n    destruct H as [Hl | Heq].\n    { unfold lt in Hl. apply le_S_n in Hl. by apply IHn. }\n    rewrite Heq. apply HPi. ins.\n    apply le_S_n in H. by apply IHn.\n  Qed.\n\n  Lemma sim_traversal_helper T\n        (IMMCON : imm_consistent G sc)\n        (TCCOH : tc_coherent G sc T)\n        (RELCOV :  W ∩₁ Rel ∩₁ issued T ⊆₁ covered T)\n        (RMWCOV : forall r w (RMW : rmw r w), covered T r <-> covered T w) :\n    exists T', (sim_trav_step G sc)＊ T T' /\\ (G.(acts_set) ⊆₁ covered T').\n  Proof using WF.\n    assert\n      (exists T' : trav_config, (sim_trav_step G sc)＊ T T' /\\ trav_steps_left T' = 0).\n    2: { desc. eexists. splits; eauto. by apply trav_steps_left_null_cov. }\n    assert (exists n, n = trav_steps_left T) as [n NN] by eauto.\n    generalize dependent T. generalize dependent n.\n    set (P n :=\n           forall T,\n             tc_coherent G sc T ->\n             W ∩₁ Rel ∩₁ issued T ⊆₁ covered T ->\n             (forall r w, rmw r w -> covered T r <-> covered T w) ->\n             n = trav_steps_left T ->\n             exists T', (sim_trav_step G sc)＊ T T' /\\ trav_steps_left T' = 0).\n    assert (forall n, P n) as YY.\n    2: by apply YY.\n    apply nat_ind_lt. unfold P. \n    ins.\n    destruct (classic (trav_steps_left T = 0)) as [EQ|NEQ].\n    { eexists. splits; eauto. apply rt_refl. }\n    assert (trav_steps_left T > 0) as HH by omega.\n    eapply trav_steps_left_nnull_ncov in HH; auto.\n    desc. eapply exists_next in HH0; eauto. desc.\n    eapply exists_trav_step in HH1; eauto.\n    desc.\n    apply exists_sim_trav_step in HH1; eauto. desc.\n    clear T'. subst.\n    specialize (H (trav_steps_left T'')).\n    edestruct H as [T' [II OO]].\n    { by apply trav_steps_left_decrease_sim. }\n    { eapply sim_trav_step_coherence; eauto. }\n    { eapply sim_trav_step_rel_covered; eauto. }\n    { eapply sim_trav_step_rmw_covered; eauto. }\n    { done. }\n    exists T'. splits; auto. apply rt_begin.\n    right. eexists. eauto.\n  Qed.\n\n  Lemma sim_traversal (IMMCON : imm_consistent G sc) :\n    exists T, (sim_trav_step G sc)＊ (init_trav G) T /\\ (G.(acts_set) ⊆₁ covered T).\n  Proof using WF.\n    apply sim_traversal_helper; auto.\n    { by apply init_trav_coherent. }\n    { unfold init_trav. simpls. basic_solver. }\n    ins. split; intros [HH AA].\n    { apply WF.(init_w) in HH.\n      apply (dom_l WF.(wf_rmwD)) in RMW. apply seq_eqv_l in RMW.\n      type_solver. }\n    apply WF.(rmw_in_sb) in RMW. apply no_sb_to_init in RMW.\n    apply seq_eqv_r in RMW. desf.\n  Qed.\n\n  Notation \"'NTid_' t\" := (fun x => tid x <> t) (at level 1).\n  Notation \"'Tid_' t\"  := (fun x => tid x =  t) (at level 1).\n\n  Lemma sim_step_cov_full_thread T T' thread thread'\n        (TCCOH : tc_coherent G sc T)\n        (TS : isim_trav_step G sc thread' T T')\n        (NCOV : NTid_ thread ∩₁ G.(acts_set) ⊆₁ covered T) :\n    thread' = thread.\n  Proof using.\n    destruct (classic (thread' = thread)) as [|NEQ]; [by subst|].\n    exfalso.\n    apply sim_trav_step_to_step in TS; auto. desf.\n    red in TS. desf.\n    { apply NEXT. apply NCOV. split; eauto. apply COV. }\n    apply NISS. eapply w_covered_issued; eauto.\n    split; auto.\n    { apply ISS. }\n    apply NCOV. split; auto. apply ISS.\n  Qed.\n\n  Lemma sim_step_cov_full_traversal T thread\n        (IMMCON : imm_consistent G sc)\n        (TCCOH : tc_coherent G sc T) (NCOV : NTid_ thread ∩₁ G.(acts_set) ⊆₁ covered T)\n        (RELCOV : W ∩₁ Rel ∩₁ issued T ⊆₁ covered T)\n        (RMWCOV : forall r w : actid, rmw r w -> covered T r <-> covered T w) : \n    exists T', (isim_trav_step G sc thread)＊ T T' /\\ (G.(acts_set) ⊆₁ covered T').\n  Proof using WF.\n    edestruct sim_traversal_helper as [T']; eauto.\n    desc. exists T'. splits; auto.\n    clear H0.\n    induction H.\n    2: ins; apply rt_refl.\n    { ins. apply rt_step. destruct H as [thread' H].\n      assert (thread' = thread); [|by subst].\n      eapply sim_step_cov_full_thread; eauto. }\n    ins. \n    set (NCOV' := NCOV).\n    apply IHclos_refl_trans1 in NCOV'; auto.\n    eapply rt_trans; eauto.\n    eapply IHclos_refl_trans2.\n    { eapply sim_trav_steps_coherence; eauto. }\n    { etransitivity; eauto.\n      eapply sim_trav_steps_covered_le; eauto. }\n    { eapply sim_trav_steps_rel_covered; eauto. }\n    eapply sim_trav_steps_rmw_covered; eauto.\n  Qed.\nEnd TraversalCounting.\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/traversal/TraversalCounting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2942262407273221}}
{"text": "Require Import FcEtt.sigs.\n\n\nRequire Import FcEtt.utils.\nRequire Import FcEtt.ett_inf_cs.\nRequire Import FcEtt.ett_ind.\nRequire Import FcEtt.imports.\nRequire Import FcEtt.tactics.\nRequire Import FcEtt.erase_syntax.\nRequire Import FcEtt.ext_red.  (* weakening for available cos *)\nRequire Import FcEtt.fc_invert FcEtt.fc_unique.\nRequire Import FcEtt.ett_par.\nRequire Import FcEtt.toplevel.\nRequire Import FcEtt.fc_context_fv.\n\n\nModule erase (wf : fc_wf_sig) (weak : fc_weak_sig) (subst : fc_subst_sig)\n             (e_invert : ext_invert_sig).\n\nInclude e_invert.\n\nModule e_red := ext_red e_invert.\nImport e_red.\n\nImport wf weak subst.\n\nModule invert := fc_invert wf weak subst.\nModule unique := fc_unique wf subst.\nImport invert unique.\n\nSet Implicit Arguments.\nSet Bullet Behavior \"Strict Subproofs\".\n\n\n\nHint Constructors Typing PropWff Iso DefEq Ctx.\n\nLtac dispatch_rho  :=\n  match goal with\n  |  H11 : ∀ x : atom,\n      ¬ x `in` ?L0 →\n             RhoCheck ?rho x (erase_tm (open_tm_wrt_tm ?b1 (a_Var_f x)))\n             |-\n             ∀ x : atom,\n               ¬ x `in` ?LL → RhoCheck ?rho x (open_tm_wrt_tm (erase_tm ?b1) (a_Var_f x))\n           =>\n   let Fr := fresh in\n   let r' := fresh in\n   intros x; intros;\n   assert (FrL0 : x `notin` L0); eauto;\n   move: (H11 x FrL0) => r';\n   autorewcshyp r';\n   rewrite -open_tm_erase_tm in r'; eapply r'\nend.\n\n\n(* ------------------------------------------ *)\n\n\nLemma erase_mutual :\n  (forall G a A, AnnTyping G a A ->\n          Typing (erase_context G) (erase a) (erase A)) /\\\n  (forall G phi, AnnPropWff G phi ->\n          PropWff (erase_context G) (erase phi)) /\\\n  (forall G D g p1 p2, AnnIso G D g p1 p2 ->\n          Iso (erase_context G) D\n              (erase_constraint p1) (erase_constraint p2)) /\\\n  (forall G D g a b,\n      AnnDefEq G D g a b ->\n      forall A, AnnTyping G a A ->\n             DefEq (erase_context G) D (erase a) (erase b) (erase A)) /\\\n  (forall G, AnnCtx G -> Ctx (erase_context G) /\\\n    forall c t, binds c t G -> binds c (erase_sort t) (erase_context G)).\nProof.\n  eapply ann_typing_wff_iso_defeq_mutual.\n  all:  intros; split_hyp; try solve [simpl; split_hyp; auto; eauto 2].\n  - eapply E_Var; auto.\n    rewrite -[Tm (erase _)]/(erase_sort (Tm _)) /erase_context.\n    apply binds_map_2.\n    auto.\n  - simpl. pick fresh x and apply E_Pi; auto.\n    replace (a_Var_f x) with (erase (a_Var_f x)); auto.\n    rewrite open_tm_erase_tm.\n    rewrite_env (erase_context ((x ~ Tm A) ++ G)).\n    eapply H. auto.\n  - simpl.\n    pick fresh x and apply E_Abs; auto.\n    assert (FrL : x `notin` L). auto.\n    pose (J := H0 x FrL).\n    rewrite <- open_tm_erase_tm in J.\n    rewrite <- open_tm_erase_tm in J.\n    unfold erase_context in J.\n    rewrite map_app in J.\n    simpl in J. auto.\n    assert (FrL : x `notin` L). auto.\n    move: (r x FrL) => r'.\n    autorewcshyp r'.\n    rewrite -open_tm_erase_tm in r'.\n    eapply r'.\n  - rewrite -open_tm_erase_tm.\n    simpl in H. simpl.\n    destruct rho; simpl; eauto.\n  - (* cast *)\n    simpl. autorewcs.\n    eapply E_Conv; eauto 1.\n    rewrite <- erase_dom.\n    pose KA := AnnTyping_regularity a0. clearbody KA.\n    eapply (H0 a_Star).\n    auto.\n  - simpl. pick fresh x and apply E_CPi; eauto.\n    autorewcs.\n    rewrite (open_co_erase_tm2 (g_Var_f x)).\n    rewrite_env (erase_context ((x ~ Co phi) ++ G)).\n    eauto.\n  - pick fresh x and apply E_CAbs; auto.\n    assert (FrL : x `notin` L). auto.\n    pose (J := H0 x FrL).\n    rewrite (open_co_erase_tm2 (g_Var_f x)).\n    rewrite (open_co_erase_tm2 (g_Var_f x)).\n    auto.\n  - rewrite -(open_co_erase_tm2 _ _ g_Triv) /=.\n    pose K := AnnTyping_regularity a0. clearbody K. inversion K. inversion H4. subst.\n    eapply E_CApp. simpl in H. eauto.\n    rewrite <- erase_dom.\n    eapply H0; eauto.\n  - simpl. eapply E_Fam; eauto.\n    unfold toplevel.\n    unfold erase_sig.\n    replace (Ax (erase_tm a) (erase_tm A)) with (erase_csort (Ax a A)); auto.\n  - simpl.\n    econstructor; autorewcs.\n    + eauto.\n    + autorewcshyp e.\n        by rewrite e.\n    + eapply Typing_regularity; eauto 1.\n  - assert (Ctx (erase_context G)). eauto.\n    simpl in *. inversion a1. inversion a2. subst.\n    eapply E_PropCong. eapply H; eauto. rewrite H10. eapply H0; eauto.\n  - destruct (AnnDefEq_regularity a) as [S1 [S2 [g' [AT1 [AT2 _]]]]].\n    inversion AT1. inversion AT2. subst.\n    destruct phi1. destruct phi2. simpl in *.\n    eapply E_CPiFst. eapply (H a_Star); eauto.\n  - eapply sym_iso. auto.\n  - simpl. rewrite e. rewrite e0.\n    inversion a0.\n    inversion H0. subst.\n    simpl in *. eapply E_IsoConv; eauto 1.\n    eapply (H a_Star).  eapply AnnTyping_regularity. eauto.\n    inversion H1. subst.\n    eapply E_Wff; eauto 1. eapply E_Conv; eauto 1.\n    eapply E_Sym. eapply DefEq_weaken_available. eapply (H a_Star). eauto 1.\n    eapply AnnTyping_regularity. eauto.\n     eapply E_Conv; eauto 1.\n    eapply E_Sym. eapply DefEq_weaken_available. eapply (H a_Star). eauto 1.\n    eapply AnnTyping_regularity. eauto.\n  - pose K:= (binds_to_AnnPropWff _ _ _ _ a0 b0). clearbody K. inversion K. subst.\n    resolve_unique_nosubst.\n    pose M := H1 c (Co (Eq a b A0)) b0.\n    eapply E_Assn; eauto.\n  - simpl.\n    resolve_unique_nosubst.\n    subst.\n    eapply E_Refl; auto.\n  - resolve_unique_nosubst.\n    assert (K :Ctx (erase_context G)) . eauto.\n    pose R1 := AnnTyping_regularity a0.\n    pose R2 := AnnTyping_regularity a1.\n    simpl. rewrite -e.\n    eapply E_Refl; eauto.\n  - eapply E_Sym.\n    resolve_unique_nosubst.\n    pose R1 := AnnTyping_regularity a0.\n    pose R2 := AnnTyping_regularity a1.\n    pose K1 := H1 a_Star R1. clearbody K1. simpl in K1.\n    pose K2 := H2 B a0. clearbody K2.\n    eapply DefEq_conv. eauto.\n  rewrite <- erase_dom. auto.\n  - (* trans *)\n    destruct (AnnDefEq_regularity a0) as [S1 [S2 [g4 [T1 [T2 DE]]]]].\n    destruct (AnnDefEq_regularity a2) as [S1' [S2' [g4' [T1' [T2' DE']]]]].\n    resolve_unique_nosubst.\n    resolve_unique_nosubst.\n    resolve_unique_nosubst.\n    resolve_unique_nosubst.\n    eapply E_Trans. eauto.\n    eapply DefEq_conv. eauto.\n    rewrite <- erase_dom.\n    eapply E_Sym. eapply (H3 a_Star).\n    eapply AnnTyping_regularity. eauto.\n  - simpl.\n    assert (Ctx (erase_context G)). eauto.\n    resolve_unique_nosubst.\n    eapply E_Beta. auto. auto. rewrite e. eauto. eauto.\n  - (* pi-cong*)\n    assert (A = a_Star). eapply AnnTyping_unique; eauto. subst.\n    simpl.\n    inversion a1. subst.\n    eapply (E_PiCong (L \\u L0)); try solve [simpl in *; eauto 2].\n    + eapply (H a_Star). auto.\n    + intros x Fr. assert (FrL : x `notin` L). auto.\n      pose K := H0 x FrL a_Star. clearbody K. clear H0.\n      rewrite -open_tm_erase_tm in K.\n      simpl.\n      simpl in K.\n      have: a_Var_f x  = erase (a_Var_f x) by done.\n      move=> ->.\n      rewrite (open_tm_erase_tm B3) e.\n      rewrite -(open_tm_erase_tm B2). simpl.\n      have: a_Var_f x  = erase (a_Var_f x) by done.\n      move=> ->.\n      rewrite (open_tm_erase_tm B2).\n      simpl.\n      eapply K.\n      eapply H8. auto. auto.\n   + simpl in H1. eapply invert_a_Pi. eauto.\n  - simpl.\n    inversion H4. subst. simpl.\n    eapply (E_AbsCong (L \\u L0)) ; auto.\n    intros x Fr.\n    assert (FrL : x `notin` L). auto. assert (FrL0 : x `notin` L0). auto.\n    assert (EQ: (erase (open_tm_wrt_tm b3 (a_Var_f x))) =\n                (erase (open_tm_wrt_tm b2 (a_Var_f x)))).\n       rewrite e.\n       rewrite <- open_tm_erase_tm.\n       rewrite <- open_tm_erase_tm.\n       simpl. auto. auto.\n    replace (a_Var_f x) with (erase (a_Var_f x)).\n    rewrite open_tm_erase_tm.\n    rewrite open_tm_erase_tm.\n    rewrite open_tm_erase_tm.\n    rewrite EQ.\n    eapply (H0 x FrL (open_tm_wrt_tm B0 (a_Var_f x))).\n    eapply H11; simpl; auto.\n    simpl. auto.\n    dispatch_rho.\n    dispatch_rho.\n  - simpl in *.\n    resolve_unique_nosubst.\n    destruct rho.\n    + inversion a3. subst.\n    rewrite <- open_tm_erase_tm.\n    eapply E_AppCong.\n    eapply (H (a_Pi Rel A0 B0)). eauto.\n    eapply H0. auto.\n    + inversion a3. subst.\n      rewrite <- open_tm_erase_tm.\n      move: (H _ H9) => h0.\n      move: (H0 _ H10) => h1.\n      move: (DefEq_regularity h1) => p1.\n      inversion p1.\n      eapply E_IAppCong; eauto.\n  - simpl in *.\n\n    destruct (AnnDefEq_regularity a) as [S1 [S2 [g' [TA1 [TA2 _]]]]].\n    inversion TA1. subst.\n    resolve_unique_nosubst.\n    inversion TA2. subst.\n    simpl.\n    eapply E_PiFst. eapply (H a_Star). eauto.\n  - rewrite <- open_tm_erase_tm.\n    rewrite <- open_tm_erase_tm.\n    simpl in *.\n    destruct (AnnDefEq_regularity a) as [S1 [S2 [g' [TA1 [TA2 _]]]]].\n    inversion TA1.\n    assert (AnnTyping G (open_tm_wrt_tm B1 a1) a_Star).\n    { pick fresh y.\n      rewrite (tm_subst_tm_tm_intro y).\n      replace a_Star with (tm_subst_tm_tm a1 y a_Star).\n      eapply AnnTyping_tm_subst; auto.\n      simpl. auto. auto. }\n    resolve_unique_nosubst.\n    eapply E_PiSnd; eauto 1.\n    eapply (H a_Star). eauto.\n    eapply (H0 A1). eauto.\n  - (* CPiCong *)\n    simpl.\n    assert (a_Star = A). eapply (AnnTyping_unique a1). eauto. subst. clear H3.\n    inversion a1.\n    inversion a2. subst.\n    eapply (E_CPiCong (L \\u dom G \\u L0 \\u L1)); try solve [simpl in *; eauto 2].\n    + intros c Fr. assert (FrL : c `notin` L). auto.\n      pose K := a0 c FrL. clearbody K.\n      rewrite (open_co_erase_tm2 (g_Var_f c)).\n      rewrite (open_co_erase_tm2 g_Triv).\n      assert (EQ: (erase (open_tm_wrt_co B3 (g_Var_f c))) =\n                  (erase (open_tm_wrt_co B2 (g_Var_f c)))).\n      rewrite e.\n      rewrite <- open_co_erase_tm.\n      rewrite <- open_co_erase_tm. auto. auto.\n      rewrite <- (open_co_erase_tm2 g_Triv B3 (g_Var_f c)).\n      rewrite (open_co_erase_tm2 (g_Var_f c)).\n      rewrite EQ.\n      eapply (H0 c FrL a_Star); auto.\n    + simpl in H1. eapply invert_a_CPi. eauto.\n  - simpl.\n    inversion H5. subst.\n    simpl.\n    eapply (E_CAbsCong (L \\u dom G \\u L0)).\n    + intros c Fr. assert (FrL : c `notin` L). auto.\n      pose K := a0 c FrL. clearbody K.\n      rewrite (open_co_erase_tm2 (g_Var_f c)).\n      rewrite (open_co_erase_tm2 g_Triv).\n      assert (EQ: (erase (open_tm_wrt_co a3 (g_Var_f c))) =\n                  (erase (open_tm_wrt_co a2 (g_Var_f c)))).\n      rewrite e.\n      rewrite <- open_co_erase_tm.\n      rewrite <- open_co_erase_tm. auto. auto.\n      rewrite <- (open_co_erase_tm2 g_Triv a3 (g_Var_f c)).\n      rewrite (open_co_erase_tm2 (g_Var_f c)).\n      rewrite EQ.\n      rewrite (open_co_erase_tm2 (g_Var_f c) B0).\n      eapply (H0 c FrL (open_tm_wrt_co B0 (g_Var_f c))).\n      eauto.\n    + simpl in H1.\n      have CT: Ctx (erase_context G) by eauto 2.\n      move: (Typing_regularity H1) => TCPi.\n      destruct (invert_a_CPi TCPi) as (_ & _ & P).\n      eauto.\n  - simpl.\n\n    inversion H5. subst.\n    inversion a5. subst.\n    resolve_unique_subst.\n    resolve_unique_subst.\n\n    inversion H6. subst. clear H6. clear H7. clear H11.\n    inversion a6. subst.\n    autorewcs.\n    rewrite <- (open_co_erase_tm2 _ _ g_Triv).\n    apply AnnDefEq_weaken_available in a0.\n    apply AnnDefEq_weaken_available in a4.\n    resolve_unique_subst.\n    resolve_unique_subst.\n    pose K := AnnTyping_regularity H9. clearbody K.  inversion K.\n    inversion H10. subst.\n    pose K1 := AnnTyping_regularity H8. clearbody K1. inversion K1.\n    inversion H12. subst.\n    eapply E_CAppCong.\n    move: (H _ H9) => h0. eapply h0. fold erase_tm.\n    eapply DefEq_weaken_available. eauto.\n  - simpl in H.\n    rewrite <- (@open_co_erase_tm2  _ _ g_Triv).\n    rewrite <- (@open_co_erase_tm2  _ _ g_Triv).\n    simpl.\n    destruct (AnnDefEq_regularity a0) as [S1 [S2 [g [AT1 [AT2 _]]]]].\n    inversion AT1. subst.\n    inversion H6. subst.\n     assert (AnnTyping G (open_tm_wrt_co B1 g2) a_Star).\n    { pick fresh y.\n      rewrite (co_subst_co_tm_intro y).\n      replace a_Star with (co_subst_co_tm g2 y a_Star).\n      eapply AnnTyping_co_subst; auto.\n      simpl. eauto. simpl. auto. auto. }\n    resolve_unique_nosubst.\n    eapply E_CPiSnd.\n    eapply (H a_Star). auto. rewrite -erase_dom. auto.\n    inversion AT2. inversion H7.\n    rewrite -erase_dom. auto.\n  - destruct (AnnIso_regularity a1) as [W1 W2]. inversion W1.  inversion W2. subst.\n    resolve_unique_nosubst.\n    eapply E_Cast. eauto. eauto.\n  - destruct (AnnIso_regularity a0) as [W1 W2]. inversion W1.  inversion W2. subst.\n    move: (AnnTyping_regularity H5) => ?.\n    resolve_unique_nosubst. simpl.\n    eapply E_IsoSnd. eauto.\n\n  - rewrite <- dom_map with (f:=erase_sort) in n.\n    unfold erase_context in *.\n    split.\n    eapply E_ConsTm; auto.\n    intros.\n    destruct (@binds_cons_1 _ c x _ (Tm A) G H2) as [[E1 E2] | E3].\n    + subst. simpl. eauto.\n    + simpl. eapply binds_cons_3. auto.\n  - rewrite <- dom_map with (f:=erase_sort) in n.\n    unfold erase_context in *.\n    split.\n    eapply E_ConsCo; auto.\n    intros.\n    destruct (@binds_cons_1 _ c0 c _ (Co phi) G H2) as [[E1 E2] | E3].\n    + subst. simpl. eauto.\n    + simpl. eapply binds_cons_3. auto.\nQed.\n\n\nDefinition AnnTyping_erase :\n  (forall G a A, AnnTyping G a A ->\n            Typing (erase_context G) (erase a) (erase A)) := first erase_mutual.\nDefinition AnnPropWff_erase :\n  (forall G phi, AnnPropWff G phi ->\n            PropWff (erase_context G) (erase phi)) := second erase_mutual.\nDefinition AnnIso_erase :\n  (forall G D g p1 p2, AnnIso G D g p1 p2 ->\n          Iso (erase_context G) D\n              (erase_constraint p1) (erase_constraint p2)) := third erase_mutual.\nDefinition AnnDefEq_erase :\n  (forall G D g a b,\n      AnnDefEq G D g a b ->\n      forall A, AnnTyping G a A ->\n           DefEq (erase_context G) D (erase a) (erase b) (erase A)) := fourth erase_mutual.\nDefinition AnnCtx_erase :\n  (forall G, AnnCtx G -> Ctx (erase_context G) /\\\n    forall c t, binds c t G -> binds c (erase_sort t) (erase_context G)) := fifth erase_mutual.\n\n\n\nLemma erasure_a_Star :\n  forall G a A, AnnTyping G a A -> erase A = a_Star ->\n           exists a', erase a = erase a' /\\ AnnTyping G a' a_Star.\nProof.\n  intros G a A H H0.\n  remember (g_Refl2 A a_Star (g_Refl a_Star)) as g.\n  pose K := AnnTyping_regularity H.\n  have L: AnnCtx G by eauto with ctx_wff.\n  assert (AnnDefEq G (dom G) g A a_Star).\n  { rewrite Heqg. eauto. }\n  assert (AnnTyping G a_Star a_Star). eauto.\n  exists (a_Conv a g). repeat split. eauto.\nQed.\n\nLemma erasure_cvt :\n    forall G a A, AnnTyping G a A -> forall B, erase A = erase B -> AnnTyping G B a_Star ->\n                                    exists a', erase a = erase a' /\\ AnnTyping G a' B.\n  Proof.\n    intros G a A H B e TB.\n    pose K := AnnTyping_regularity H. clearbody K.\n    remember (g_Refl2 A B (g_Refl a_Star)) as g.\n    assert (AnnDefEq G (dom G) g A B).\n    { rewrite Heqg. eapply An_EraseEq. eauto. eauto. eauto. eapply An_Refl. eapply An_Star.\n      eauto with ctx_wff. }\n    remember (a_Conv a (g_Refl2 A B (g_Refl a_Star))) as a0'.\n    assert (ATA' : AnnTyping G a0' B).\n    { rewrite Heqa0'. rewrite <- Heqg. eapply An_Conv. eauto. eauto. eauto. }\n    exists (a_Conv a g). eauto.\n  Qed.\n\n\nLemma AnnDefEq_invertb : forall G D g a b, AnnDefEq G D g a b ->\n  exists A b' g, AnnTyping G a A /\\ AnnTyping G b' A /\\ erase b' = erase b /\\ AnnDefEq G D g b b'.\n  Proof.\n    intros G D g a b DE.\n    destruct (AnnDefEq_regularity DE) as [SA [SB [g4 [AT0' [ATB0' SAB]]]]].\n    exists SA. eexists. eexists.\n    assert (AnnTyping G (a_Conv b (g_Sym g4)) SA).\n    {     eapply An_Conv. eapply ATB0'.\n          eapply An_Sym.\n          eapply AnnTyping_regularity. eauto.\n          eapply AnnTyping_regularity. eauto.\n          eapply An_Refl. eapply An_Star.\n          eauto with ctx_wff. eauto.\n          eapply AnnTyping_regularity. eauto.\n    }\n    split. auto. split. eauto.\n    split. simpl. auto.\n    eapply An_EraseEq. eauto. eauto. simpl. eauto.\n    eapply An_Sym.\n    eapply AnnTyping_regularity. eauto.\n    eapply AnnTyping_regularity. eauto.\n    eapply An_Refl. eapply An_Star.\n    eauto with ctx_wff. eauto.\n  Qed.\n\n\n  (*  ----------------------------------------------------------- *)\n\n\n\nLemma erasure_AnnDefEq : forall G D g A'' B'' S A' B',\n      AnnDefEq G D g A'' B'' ->\n      AnnTyping G A'' S -> erase S = a_Star ->\n      erase A'' = erase A' -> erase B'' = erase B' ->\n      AnnTyping G A' a_Star -> AnnTyping G B' a_Star ->\n      exists g', AnnDefEq G D g' A' B'.\nProof.\n  intros G D g A'' B'' S A' B' H H0 H1 H2 H3 H4 H5.\n  destruct (AnnDefEq_invertb H) as (S' & b'' & g' & TA'' & Tb' & Eb' & DEB).\n  resolve_unique_nosubst.\n  move :(AnnTyping_regularity H0) => R0.\n  move :(AnnTyping_regularity Tb') => R1.\n  have CTX : AnnCtx G by eauto with ctx_wff.\n  assert (TEMP : exists g, AnnDefEq G D g A' A'').\n  { eexists.\n    eapply An_EraseEq. eauto. eauto. eauto.\n    eapply An_EraseEq. eapply An_Star. auto. eauto. eauto.\n    eapply An_Refl. eauto. }\n  destruct TEMP as (gA & DEA).\n  assert (TEMP : exists g, AnnDefEq G D g b'' B').\n  { eexists.\n    eapply An_EraseEq. eauto. eauto. autorewcs. congruence.\n    eapply An_EraseEq. eauto. eauto. eauto.\n    eapply An_Refl. eauto. }\n  destruct TEMP as (gB & DEB2).\n  destruct (An_Trans' DEA H) as [gX TR1].\n  destruct (An_Trans' TR1 DEB) as [gX2 TR2].\n  destruct (An_Trans' TR2 DEB2) as [gX3 TR3].\n  exists gX3. exact TR3.\nQed.\n\n\nLemma AnnDefEq_invert_a_Star : forall G0 D g1 A1' A2' S,\n      AnnDefEq G0 D g1 A1' A2' ->\n      AnnTyping G0 A1' S ->\n      erase S = a_Star ->\n      exists A1'', exists A2'', exists g, erase A1'' = erase A1'\n                       /\\ erase A2'' = erase A2'\n                       /\\ AnnDefEq G0 D g A1'' A2''\n                       /\\ AnnTyping G0 A1'' a_Star\n                       /\\ AnnTyping G0 A2'' a_Star.\n  Proof.\n    intros G0 D g1 A1' A2' S DE T EA3.\n  destruct (erasure_a_Star T EA3) as (A1'' & EA1'' & TA1').\n  assert (exists g, AnnDefEq G0 D g A1'' A1').\n  { eexists. eapply An_EraseEq with (A := a_Star); eauto 1.\n    assert (AnnCtx G0). eauto with ctx_wff.\n    eapply An_EraseEq with (A := a_Star). eauto.\n    eapply AnnTyping_regularity; eauto 1.\n    eauto. eapply An_Refl.  eauto.\n  }\n\n  destruct H as [g2 DE1].\n  destruct (An_Trans' DE1 DE) as [g3 DE2].\n  destruct (AnnDefEq_invertb DE2) as (A1''' & A2'' & g4 & ? & T2 & E1 & DE3).\n  resolve_unique_nosubst.\n  destruct (An_Trans' DE2 DE3) as [g5 DE4].\n  exists A1'', A2'', g5.\n  repeat split; eauto.\n  Qed.\n\n\n\n  (*  ----------------------------------------------------------- *)\n\n(* TODO: Would there be a good way to split this proof into smaller parts? *)\nLemma annotation_mutual :\n  (forall G a A, Typing G a A ->\n     forall G0, erase_context G0 = G -> AnnCtx G0 ->\n     exists a0 A0,\n         (erase a0) = a /\\\n         (erase A0) = A /\\\n         AnnTyping G0 a0 A0) /\\\n  (forall G phi, PropWff G phi ->\n     forall G0, erase_context G0 = G -> AnnCtx G0 ->\n     exists phi0,\n          erase_constraint phi0 = phi /\\\n          AnnPropWff G0 phi0) /\\\n  (forall G D p1 p2, Iso G D p1 p2 ->\n     forall G0, erase_context G0 = G -> AnnCtx G0 ->\n     exists g0 p1' p2',\n       (erase_constraint p1') = p1 /\\\n       (erase_constraint p2') = p2 /\\\n       AnnIso G0 D g0 p1' p2') /\\\n  (forall G D a b A, DefEq G D a b A ->\n     forall G0, erase_context G0 = G -> AnnCtx G0 ->\n     exists g a0 b0 A0,\n       (erase a0) = a /\\\n       (erase b0) = b /\\\n       (erase A0) = A /\\\n       AnnDefEq G0 D g a0 b0 /\\ AnnTyping G0 a0 A0 /\\ AnnTyping G0 b0 A0) /\\\n  (forall G, Ctx G -> True).\nProof.\n  eapply typing_wff_iso_defeq_mutual; intros; auto.\n- exists a_Star. exists a_Star.\n  repeat split. auto.\n- rename H0 into EQ.\n  unfold erase_context in EQ.\n  rewrite <- EQ in b.\n  apply binds_map_3 in b.\n  destruct b as [s' [EQ2 b]].\n  destruct s'; simpl in EQ2; inversion EQ2.\n  exists (a_Var_f x).\n  exists A0.\n  unfold erase_context.\n  simpl. split; auto.\n- (* E_Pi *)\n  clear t. clear t0.\n  pick fresh x.\n  assert (FrL : x `notin` L). auto.\n  destruct (H0 G0 H1 H2) as [A0 [S0 [EQ1 [EQ2 AT]]]]. clear H0.\n  destruct (erasure_a_Star AT EQ2) as [A0' [EQ3 AS]].\n  assert (EQA : erase A0' = A). rewrite <- EQ3. auto.\n  assert (AN: AnnCtx ((x ~ Tm A0') ++ G0)). eauto with ctx_wff.\n  assert (E : erase_context ([(x, Tm A0')] ++ G0) = [(x, Tm A)] ++ G).\n  { unfold erase_context. simpl in *.\n    unfold erase_context in H1. congruence. }\n  destruct (H x FrL _ E AN) as [B0 [S [E2 [E3 AT2]]]]. clear H. clear E. clear AN.\n  destruct (erasure_a_Star AT2 E3) as [B0' [E4 AT4]].\n  exists (a_Pi rho A0' (close_tm_wrt_tm x B0')).\n  exists a_Star.\n  repeat split.\n  { simpl.  f_equal; auto. autorewcs.\n    rewrite <- (close_tm_erase_tm x B0').\n    rewrite <- E4. rewrite E2. simpl.\n    rewrite close_tm_wrt_tm_open_tm_wrt_tm; auto. }\n  { eapply An_Pi_exists with (x:=x); eauto.\n    autorewrite with lngen. fsetdec.\n    rewrite open_tm_wrt_tm_close_tm_wrt_tm.\n    eauto. }\n- (* E_Abs *)\n  destruct (H0 G0 H1 H2) as [A0 [s0 [E1 [E2 AT]]]]. clear H0.\n  destruct (erasure_a_Star AT E2) as [A0' [EQ3 AS]].\n  assert (EQA : erase A0' = A). rewrite <- EQ3. auto.\n  pick fresh x. assert (FrL : x `notin` L). auto.\n  assert (AN: AnnCtx ((x ~ Tm A0') ++ G0)). eauto with ctx_wff.\n  assert (E : erase_context ([(x, Tm A0')] ++ G0) = [(x, Tm A)] ++ G).\n     rewrite <- H1. unfold erase_context. simpl in *. congruence.\n  destruct (H x FrL _ E AN) as [b0 [B0 [E3 [E4 AT_2]]]]. clear H. clear E.\n  exists (a_Abs rho A0' (close_tm_wrt_tm x b0)).\n  exists (a_Pi rho A0' (close_tm_wrt_tm x B0)).\n  split. simpl in *. subst. f_equal.\n  (* Little hack because we need a better control of how simpl simplifies erase (and its monomorphic versions) *)\n  set (k := close_tm_erase_tm). simpl in k. unfold close_tm_wrt_tm.\n  rewrite <- k; auto. rewrite E3.\n  (* assert (k' : forall x', close_tm_wrt_tm_rec 0 x x' = close_tm_wrt_tm x x') by done; rewrite_and_clear k'. *)\n  rewrite close_tm_wrt_tm_open_tm_wrt_tm; auto.\n  split.\n  simpl. subst. f_equal. autorewcs. congruence.\n  (* FIXME: general solution *)\n  (* have: (forall x (t : tm), close_tm x t = close_tm_rec 0 x t) by reflexivity. move=> ->.*)\n  rewrite <- close_tm_erase_tm. rewrite E4. simpl.\n  (* assert (k' : forall x', close_tm_wrt_tm_rec 0 x x' = close_tm_wrt_tm x x') by done; rewrite_and_clear k'. *)\n  rewrite close_tm_wrt_tm_open_tm_wrt_tm; auto.\n  apply An_Abs_exists with (x := x); auto.\n  apply notin_union_3; auto.\n  apply notin_union_3; auto.\n  autorewrite with lngen; auto.\n  autorewrite with lngen; auto.\n  rewrite open_tm_wrt_tm_close_tm_wrt_tm; auto.\n  rewrite open_tm_wrt_tm_close_tm_wrt_tm; auto.\n  rewrite open_tm_wrt_tm_close_tm_wrt_tm; auto.\n  autorewcs. rewrite E3.\n  eapply r; auto.\n- (* E_App *)\n  destruct (H G0 H1 H2) as [a0 [AB0 [F1 [F2 Ty2]]]]. clear H.\n  destruct (H0 G0 H1 H2) as [b0 [A0 [M1 [M2 Ty3]]]]. clear H0.\n  assert (K : AnnTyping G0 AB0 a_Star). eapply AnnTyping_regularity; eauto.\n  destruct (erase_pi F2 K) as [PA [PB [EAB [EPA [EPB TYB]]]]].\n  inversion TYB. subst.\n  assert (N : AnnTyping G0 A0 a_Star). eapply AnnTyping_regularity; eauto.\n  destruct (erasure_cvt Ty2 EAB) as [a0' [g ATA']]; eauto.\n  destruct (erasure_cvt Ty3 (symmetry EPA)) as [b0' [g' ATB']]; eauto.\n  exists (a_App a0' Rel b0').\n  exists (open_tm_wrt_tm PB b0').\n  simpl. rewrite <- open_tm_erase_tm.\n  simpl in *.\n  repeat split.\n  congruence.\n  congruence.\n  eauto.\n- (* E_IApp case *)\n  destruct (H G0 H1 H2) as [a0 [AB0 [F1 [F2 Ty2]]]]. clear H.\n  destruct (H0 G0 H1 H2) as [b0 [A0 [M1 [M2 Ty3]]]]. clear H0.\n  assert (K : AnnTyping G0 AB0 a_Star). eapply AnnTyping_regularity; eauto.\n  destruct (erase_pi F2 K) as [PA [PB [EAB [EPA [EPB TYB]]]]].\n  inversion TYB. subst.\n  assert (N : AnnTyping G0 A0 a_Star). eapply AnnTyping_regularity; eauto.\n  destruct (erasure_cvt Ty2 EAB) as [a0' [g ATA']]; eauto.\n  destruct (erasure_cvt Ty3 (symmetry EPA)) as [b0' [g' ATB']]; eauto.\n  exists (a_App a0' Irrel b0').\n  exists (open_tm_wrt_tm PB b0').\n  simpl. rewrite <- open_tm_erase_tm.\n  simpl in *.\n  repeat split.\n  congruence.\n  congruence.\n  eauto.\n- (* ex_conv case *)\n  destruct (H G0 H2) as [a0 [A0 [E1 [E2 Ty]]]]; auto. clear H.\n  destruct (H0 G0 H2 H3) as\n      [g [A0' [B0' [S [Ea [Eb [Es [DE [Z Z']]]]]]]]]; auto; clear H0.\n  subst.\n  replace a_Star with (erase a_Star) in Es; [|simpl;auto].\n  destruct (erasure_cvt Z Es) as [A0'' [AS1 AS2]]. eapply An_Star. assumption.\n  assert (Ea' : erase A0 = erase A0''). rewrite -AS1. auto.\n  destruct (erasure_cvt Ty Ea') as [a'' [Ea0 Ta0]]. eauto.\n  destruct (AnnDefEq_invertb DE) as [SA [B0'' [g5 [AT1 [AT2 [Eb SS]]]]]].\n  resolve_unique_nosubst.\n\n  destruct (erasure_a_Star AT2 Es) as (B0 & EB0 & TB0).\n\n  pose A0S := AnnTyping_regularity Ty. clearbody A0S.\n  rewrite -erase_dom in DE.\n  assert (E1 :exists g, AnnDefEq G0 (dom G0) g A0 A0').\n  { eexists.\n    eapply An_EraseEq. eauto. eauto. eauto.\n    eapply An_EraseEq. eauto. eapply AnnTyping_regularity. eauto. eauto.\n    eapply An_Refl. eauto.\n  }\n  destruct E1.\n  assert (E2 : exists g, AnnDefEq G0 (dom G0) g A0' A0'').\n  { eexists.\n    eapply An_EraseEq. eauto. eapply AnnTyping_regularity. eauto.\n    eauto.\n    eapply An_EraseEq. eapply AnnTyping_regularity. eauto.\n    eapply An_Star. eauto.\n    eauto.\n    eapply An_Refl. eauto.\n  }\n  destruct E2.\n  assert (E3 : exists g, AnnDefEq G0 (dom G0) g A0'' B0'').\n  {\n    destruct (An_Sym' H0).\n    rewrite -erase_dom in SS.\n    destruct (An_Trans' DE SS); try eassumption.\n    eapply An_Trans' with (a1 := A0'); try eassumption.\n  }\n  destruct E3 as [g'' EQ].\n  assert (E4 : exists g, AnnDefEq G0 (dom G0) g B0'' B0).\n  {\n    eexists. eapply An_EraseEq. eauto. eauto. eauto.\n    eapply An_EraseEq. eapply AnnTyping_regularity. eauto.\n    eapply An_Star. eauto. eauto.\n    eapply An_Refl; eauto.\n  }\n  destruct E4 as (gg & EE).\n  destruct (An_Trans' EQ EE).\n  eexists (a_Conv a'' x1). eexists B0.\n  split. eauto. split. congruence.\n  eapply An_Conv. eauto. eauto. eauto.\n- (* CPi *)\n  pick fresh c. assert (FrL : c `notin` L). auto.\n  destruct (H0 G0 H1 H2) as [phi0 [EQ1 AT]]. clear H0.\n  assert (AN: AnnCtx ((c ~ Co phi0) ++ G0)). eauto with ctx_wff.\n  assert (E : erase_context ([(c, Co phi0)] ++ G0) = [(c, Co phi)] ++ G).\n  unfold erase_context. simpl. rewrite EQ1.\n  unfold erase_context in H1. rewrite H1. auto.\n  destruct (H c FrL _ E AN) as [b0 [S0 [E2 [E3 AT2]]]]. clear H.\n  clear E. clear AN.\n  destruct (erasure_a_Star AT2) as [b0' [EB N1]]; eauto.\n  exists (a_CPi phi0 (close_tm_wrt_co c b0')).\n  exists a_Star.\n  split.\n  simpl. f_equal. auto.\n  autorewcs.\n  rewrite <- close_co_erase_tm.\n  rewrite <- EB. rewrite E2. simpl.\n  rewrite close_tm_wrt_co_open_tm_wrt_co; auto.\n  split. auto.\n  eapply An_CPi_exists with (c := c); eauto.\n  apply notin_union_3; auto.\n  pose K := fv_co_co_tm_close_tm_wrt_co b0' c. clearbody K.\n  unfold AtomSetImpl.Equal in K.\n  rewrite K. fsetdec.\n  rewrite open_tm_wrt_co_close_tm_wrt_co.\n  auto.\n- (* abs *)\n  destruct (H0 G0 H1 H2) as [A0 [E1 AT]]. clear H0. clear t.\n  pick fresh x. assert (FrL : x `notin` L). auto.\n  assert (AN: AnnCtx ((x ~ Co A0) ++ G0)). eauto with ctx_wff.\n  assert (E : erase_context ([(x, Co A0)] ++ G0) = [(x, Co phi)] ++ G).\n     rewrite <- H1. unfold erase_context. simpl. rewrite E1. auto.\n  destruct (H x FrL _ E AN) as [b0 [B0 [E3 [E4 AT_2]]]]. clear H. clear E.\n  exists (a_CAbs A0 (close_tm_wrt_co x b0)).\n  exists (a_CPi A0 (close_tm_wrt_co x B0)).\n  split. simpl. subst. f_equal. autorewcs.\n  rewrite <- close_co_erase_tm; auto. rewrite E3.\n  simpl.\n  rewrite close_tm_wrt_co_open_tm_wrt_co; auto.\n  split.\n  simpl. subst. f_equal. autorewcs.\n  rewrite <- close_co_erase_tm. rewrite E4.\n  simpl.\n  rewrite close_tm_wrt_co_open_tm_wrt_co; auto.\n  apply An_CAbs_exists with (c := x); auto.\n  { apply notin_union_3; auto.\n    apply notin_union_3; auto.\n    pose K := fv_co_co_tm_close_tm_wrt_co b0 x. clearbody K.\n    unfold AtomSetImpl.Equal in K.\n    rewrite K. auto.\n    pose K := fv_co_co_tm_close_tm_wrt_co B0 x. clearbody K.\n    unfold AtomSetImpl.Equal in K.\n    rewrite K. auto.\n  }\n  rewrite open_tm_wrt_co_close_tm_wrt_co; auto.\n  rewrite open_tm_wrt_co_close_tm_wrt_co; auto.\n- (* CApp *)\n  clear d. clear t.\n  destruct (H G0 H1 H2) as [a0 [A0 [E1 [E2 Ty]]]]. clear H.\n  destruct (H0 G0 H1 H2) as [g [A0' [B0' [Ea' [Eb DE ]]]]]. clear H0.\n  destruct DE as [Eb0 [EA [EQ [AT _]]]].\n  pose K := AnnTyping_regularity Ty.\n  destruct (erase_cpi E2 K) as [phi2 [B2 [E3 [Ep [EB2 AP]]]]].\n  destruct phi2.\n  simpl in *. inversion Ep. clear Ep.\n  subst.\n  rename A1 into A2.\n  rename a2 into A1.\n  rename b0 into B.\n  destruct (erasure_cvt Ty) with (B := a_CPi (Eq A1 B A2) B2) as [a0' [TA' EA']]; eauto.\n  inversion AP. inversion H4. subst.\n  inversion H6. subst.\n  assert (K1 : exists g, AnnDefEq G0 (dom G0) g A1 B0'). {\n    eapply An_Trans' with (a1 := A0').\n    eapply An_EraseEq. eauto. eauto. eauto.\n    eapply An_EraseEq. eapply AnnTyping_regularity. eauto.\n    eapply AnnTyping_regularity. eauto. eauto.\n    eauto.\n    rewrite -erase_dom in EQ.\n    eapply EQ.\n  }\n  destruct K1.\n  destruct (AnnDefEq_regularity H) as [C1 [C2 [gB [T1 [T2 DE2]]]]].\n  resolve_unique_subst.\n  destruct (An_Sym' DE2).\n  assert (K3 : exists g, AnnDefEq G0 (dom G0) g C2 B0). {\n    eapply An_Trans' with (a1 := C1).\n    eauto.\n    eapply An_EraseEq. eapply AnnTyping_regularity. eauto.\n    eapply AnnTyping_regularity. eauto. eauto. eauto.\n  }\n  destruct K3.\n  assert (K4 : exists g, AnnDefEq G0 (dom G0) g B0' B). {\n    eexists. eapply An_EraseEq. eapply T2. eapply H11. eauto.\n    eauto.\n  }\n  destruct K4.\n  assert (K2 : exists g, AnnDefEq G0 (dom G0) g A1 B). {\n    eapply An_Trans' with (a1 := B0').\n    eauto. eauto.\n  }\n  destruct K2 as [g' Y].\n  exists (a_CApp a0' g').\n  exists (open_tm_wrt_co B2 g').\n  subst. simpl.\n  rewrite <- open_co_erase_tm.\n  rewrite no_co_in_erased_tm.\n  repeat split. autorewcs. congruence.\n  eauto.\n- destruct (H0 nil eq_refl) as (a0 & A0 & E1 & E2 & Ty). auto.\n  unfold toplevel in b. unfold erase_sig in b.\n  destruct (@binds_map_3 _ _ F (Ax a A) erase_csort an_toplevel b).\n  split_hyp. destruct x; inversion H3.\n  exists (a_Fam F). exists A1. repeat split; auto.\n  eapply An_Fam; eauto.\n  eapply AnnTyping_regularity.\n  eapply an_toplevel_closed. eauto.\n- destruct (H G0 H2 H3) as [a0 [A0 [E1 [E2 Ty]]]]. clear H.\n  destruct (H0 G0 H2 H3) as [b0 [A1 [E3 [E4 TyB]]]]. clear H0.\n  clear H1.\n  subst.\n  exists (Eq a0 b0 A0). simpl. split. auto. eauto.\n- (* PropCong *)\n  clear d. clear d0.\n  rename A1 into a0. rename A2 into b0.\n  rename B1 into a1. rename B2 into b1.\n  destruct (H G0 H1 H2) as [g0 [a0' [b0' [A' [Ea0 [Eb0 [EA0 [DE0 [T0 _]]]]]]]]]. clear H.\n  destruct (H0 G0 H1 H2) as [g1 [a1' [b1' [B' [Ea1 [Eb1 [EA1 [DE1 [T1 _]]]]]]]]]. clear H0.\n  move :(AnnTyping_regularity T0) => R0.\n  move :(AnnTyping_regularity T1) => R1.\n\n  assert (TEMP: exists g, AnnDefEq G0 (dom G0) g A' B').\n  { eexists.  eapply An_EraseEq. eauto. eauto.\n    autorewcs. congruence.\n    eapply An_Refl. eauto. }\n  destruct TEMP as (gX & EqA'B').\n\n  destruct (An_Sym' EqA'B') as (gY & EqB'A').\n  remember (a_Conv a1' gY) as a1''.\n  assert (AnnTyping G0 a1'' A'). rewrite Heqa1''; eapply An_Conv; eassumption.\n  assert (erase a1'' = a1). rewrite Heqa1''. simpl. autorewcs. congruence.\n  assert (AnnPropWff G0 (Eq a0' a1'' A')). {\n    econstructor. eauto. eauto. autorewcs. congruence.\n  }\n\n  (* Now need b0'' : A'. get it from a0' ~ b0' *)\n  destruct (AnnDefEq_invertb DE0) as [AA0' [b0'' [gb0 [TA0 [TB0 [E DE0']]]]]].\n  resolve_unique_nosubst.\n\n  (* Now we need b1'' : A' get it from a1' ~ b1' ?? *)\n  assert (TEMP : exists g, AnnDefEq G0 D g a1'' a1'). {\n    eexists.\n    eapply An_EraseEq. eauto. eauto. autorewcs. congruence. eauto.\n  }\n  destruct TEMP as (gZ & Eqa1''a1').\n  destruct (An_Trans' Eqa1''a1' DE1) as (gY1 & Eqa1''b1').\n  destruct (AnnDefEq_invertb Eqa1''b1') as [AA1'' [b1'' [gb1 [TA1 [TB1 [E1 DE1']]]]]].\n  resolve_unique_nosubst.\n\n  assert (AnnPropWff G0 (Eq b0'' b1'' A')). econstructor. eauto. eauto. autorewcs. congruence.\n\n  assert (TEMP : exists g, AnnDefEq G0 D g a0' b0''). eapply (An_Trans' DE0 DE0').\n  destruct TEMP as [gY2 Eqa0'b0''].\n\n  assert (TEMP : exists g, AnnDefEq G0 D g a1'' b1''). eapply (An_Trans' Eqa1''b1' DE1').\n  destruct TEMP as [gY3 Eqa1''b1''].\n\n  eexists. exists (Eq a0' a1'' A'). exists (Eq b0'' b1'' A').\n  split.\n  simpl. autorewcs. f_equal; auto.\n  split. simpl. autorewcs. f_equal; try congruence.\n  simpl. autorewcs. f_equal; auto.\n  econstructor; eauto.\n- clear d. clear p0. clear p.\n  destruct (H G0 H2 H3) as (g & A' & B' & S & EA & EB & ES & DE & TA & TB). clear H.\n  destruct (H0 G0 H2 H3) as (phi0 & Ep0 & WF0). clear H0.\n  destruct (H1 G0 H2 H3) as (phi1 & Ep1 & WF1). clear H1.\n  destruct phi0 as [A1a A2a A''].\n  destruct phi1 as [A1b A2b B''].\n  simpl in Ep0. inversion Ep0. clear Ep0.\n  simpl in Ep1. inversion Ep1. clear Ep1.\n  inversion WF0. subst.\n  inversion WF1. subst.\n  move: (AnnTyping_regularity H8) => R1.\n  move: (AnnTyping_regularity H9) => R2.\n  move: (AnnTyping_regularity H11) => R3.\n  move: (AnnTyping_regularity H12) => R4.\n\n  destruct (AnnDefEq_invert_a_Star DE TA ES) as\n      (A''' & B''' & g2 & EA2 & EB2 & DE2 & TAS & TBS).\n\n  simpl in *.\n  destruct (erasure_cvt H12) with (B:= A'')   as (A2a' & E2a & T2a); eauto 1.\n  (* p1 is (Eq A1a a2a' A''). Want other side to also have type A'' *)\n  assert (TMP: exists g, AnnDefEq G0 D g A''' A'').\n  { eexists.\n    eapply An_EraseEq; eauto 1. congruence. eapply An_Refl; eauto 2. }\n  destruct TMP as (ga & EAAA).\n\n  (* convert type of A1b from B'' to A'' *)\n  assert (TMP : exists g, AnnDefEq G0 D g B'' A'').\n  { eexists. eapply An_Trans2 with (a1 := B''').\n    eapply An_EraseEq; eauto 1. congruence. eapply An_Refl; eauto 2.\n    eapply An_Trans2 with (a1 := A''').\n    eapply An_Sym2; eauto 1.\n    eapply An_EraseEq; eauto 1. congruence. eapply An_Refl; eauto 2. }\n  destruct TMP as (gb & EBA).\n\n  (* convert type of A2b from B to A'' *)\n  assert (TMP : exists g, AnnDefEq G0 D g B A'').\n  { eexists. eapply An_Trans2 with (a1 := B''); eauto 1.\n    eapply An_EraseEq; eauto 1. eapply An_Refl; eauto 2. }\n  destruct TMP as (gc & EBBA).\n\n  eexists. exists (Eq A1a A2a A''). exists (Eq A1b A2b B'').\n  repeat split; auto.\n  simpl; auto.\n  f_equal. congruence. congruence.\n  eapply An_IsoConv.\n  eapply An_Sym2. eauto 1.\n  eapply An_Wff; eauto 1.\n  eapply An_Wff; eauto 1.\n  congruence.\n  congruence.\n- (* CPiFst *)\n  clear d.\n  destruct (H G0 H0 H1) as [g [a0 [b0 [A0' [E1 [E2 [E3 [DE [Ty UT]]]]]]]]]. clear H.\n  subst.\n  destruct (AnnDefEq_regularity DE) as [A0 [B0 [g0 [TA0 [TB0 DE0]]]]].\n  destruct (erase_cpi E1 TA0) as [phi1' [B1' [E [Ephi [EB T1]]]]].\n  destruct (erase_cpi E2 TB0) as [phi2' [B2' [E' [Ephi' [EB' T2]]]]].\n  resolve_unique_nosubst.\n  resolve_unique_nosubst.\n  destruct (An_Refl_Star D E T1 Ty E3).\n  assert (TB1 : AnnTyping G0 (a_Conv b0 (g_Sym g0)) A0').\n  { eapply An_Conv. eauto. eapply An_Sym.\n    eapply AnnTyping_regularity. eauto.\n    eapply AnnTyping_regularity. eauto.\n    eapply An_Refl. eapply An_Star.\n    eauto.\n    eauto.\n    eapply AnnTyping_regularity. eauto.\n  }\n  assert (E4 : erase (a_Conv b0 (g_Sym g0)) = erase (a_CPi phi2' B2')).\n  { simpl. autorewcs. rewrite E'. auto. }\n  destruct (An_Refl_Star D E4 T2 TB1 E3).\n  assert (exists g, AnnDefEq G0 D g (a_CPi phi1' B1') (a_CPi phi2' B2')).\n  { eapply erasure_AnnDefEq with (A'' := a0) (B'' := b0); auto.\n    eauto. eauto. eauto.  }\n  destruct H2.\n  destruct phi1. destruct phi2.\n  eexists.\n  exists phi1', phi2'.\n  destruct phi1'. destruct phi2'. simpl in *.\n  repeat split. congruence. congruence.\n  eapply An_CPiFst. eapply H2.\n- (* assn *)\n  rewrite <- H0 in b0.\n\n  destruct (binds_map_3 _ _ _ _ b0) as [s [E2 E3]].\n  destruct s; try (simpl in E2; inversion E2).\n  destruct phi. simpl in E2. inversion E2.\n  subst. clear E2.\n  move: (binds_to_AnnPropWff _ _ _ _ H1 E3) => K.\n  inversion K. subst.\n  move: (AnnTyping_regularity H6) => TA1.\n  move: (AnnTyping_regularity H7) => TB0.\n\n  assert (exists g, AnnDefEq G0 (dom G0) g B A0). {\n    eexists. eapply An_EraseEq; eauto 1.\n    eapply An_Refl; eauto 2.\n  }\n  destruct H0 as [g' DE].\n  assert (AnnTyping G0 (a_Conv b1 g') A0).  eapply An_Conv; eauto 1.\n  eexists. exists a0, (a_Conv b1 g'), A0. repeat split.\n  eapply An_Trans2 with (a1 := b1); eauto 1.\n  eapply An_Assn; eauto.\n  eapply An_EraseEq; eauto.\n  eauto.\n  eauto.\n- (* refl *)\n  destruct (H G0 H0 H1) as [a0' [A0 [E1 [E2 Ty ]]]]. clear H.\n  eexists. exists a0', a0', A0. repeat split; auto. eapply An_Refl. eauto.\n- (* sym *)\n  destruct (H G0 H0 H1) as [g [a0 [b0 [A0 [E1 [E2 [E3 [DE [Ty TU]]]]]]]]]. clear H.\n  destruct (AnnDefEq_invertb DE) as [A0' [b0' [g' [T1 [T2 [T3 T4]]]]]].\n  resolve_unique_nosubst.\n  assert (exists g, AnnDefEq G0 D g b0' a0).  {\n    destruct (An_Sym' DE).\n    destruct (An_Sym' T4).\n    eapply (An_Trans' H2 H).\n  }\n  destruct H.\n  eexists. exists b0'. exists a0. exists A0. repeat split; auto. congruence. eassumption.\n- (* Trans *)\n  destruct (H G0 H1 H2) as (g0 & a' & a1' & A0 & E1 & E2 & E3 & DE & Ty & TyU). clear H.\n  destruct (H0 G0 H1 H2) as (g1 & a1'' & b' & A1 & E4 & E5 & E6 & DE1 & Ty1 & TyU1). clear H0.\n  destruct (AnnDefEq_invertb DE) as (A' & a1''' & g2 & T1 & T2 & E7 & DE2).\n  destruct (AnnDefEq_invertb DE1) as (B' & b'' & g3 & T3 & T4 & E8 & DE3).\n  subst.\n  destruct (An_Trans' DE DE2).\n  destruct (An_Trans' DE1 DE3).\n  resolve_unique_nosubst.\n  resolve_unique_nosubst.\n  assert (exists g, AnnDefEq G0 D g a1''' a1'').\n  {\n    eexists.\n    eapply An_EraseEq. eauto. eauto. autorewcs. congruence.\n    eapply An_EraseEq. eapply AnnTyping_regularity. eauto.\n     eapply AnnTyping_regularity. eauto. eauto.\n     eauto.\n  }\n  destruct H1.\n  destruct (An_Trans' H H1).\n  destruct (An_Trans' H3 H0).\n  destruct (AnnDefEq_invertb H4) as (? & b''' & ? & T3' & T4' & E8' & DE3').\n  resolve_unique_nosubst.\n  eexists. exists a'. exists b'''. exists A0. repeat split; auto. congruence.\n  eapply An_Trans2 with (a1 := b''); eauto 1.\n- (* step case *)\n  destruct (H G0 H1 H2) as [a1' [A1 [E1 [E2 Ty]]]]. clear H.\n  destruct (H0 G0 H1 H2) as [a2' [A2 [E1' [E2' Ty']]]]. clear H0.\n  subst.\n  assert (exists g, AnnDefEq G0 D g A2 A1).\n  { eexists. eapply An_EraseEq.  eapply AnnTyping_regularity. eauto.\n    eapply AnnTyping_regularity. eauto. eauto 1.\n    eapply An_Refl. eauto 2. }\n  destruct H.\n  assert (AnnTyping G0 (a_Conv a2' x) A1).\n  { eapply An_Conv; eauto 1.\n    eapply AnnDefEq_weaken_available; eauto 1.\n    eapply AnnTyping_regularity. eauto. }\n  eexists. exists a1', (a_Conv a2' x), A1.\n  repeat split; eauto 1.\n  eapply An_Beta; eauto 1.\n- (* pi-cong *)\n  clear d. clear d0.\n  clear H1. rename H2 into H1. rename H3 into H2. rename H4 into H3. rename H5 into H4.\n  destruct (H G0 H3 H4) as (g1 & A1' & A2' & S & EA1 & EA2 & EA3 & DE & T & U). clear H.\n  clear H1. clear H2.\n  destruct (AnnDefEq_invert_a_Star DE T EA3) as (A1'' & A2'' & g5 & EA5 & EA4 & DE4 & TA1' & TA2').\n  assert (erase A1'' = A1). congruence.\n  assert (erase A2'' = A2). congruence.\n\n  clear dependent A1'. clear dependent A2'. clear dependent S.\n\n  pick fresh x1.\n  assert (FrL : x1 `notin` L). auto.\n  assert (CTX1 : AnnCtx ([(x1, Tm A1'')] ++ G0)). eauto with ctx_wff.\n\n  destruct (H0 x1 FrL ([(x1,Tm A1'')] ++ G0)) as (g2 & B1' & B2' & S & EB1 & EB2 & ES & DEB & DT & _); auto.\n  { simpl. autorewcs. congruence. } clear H0.\n\n  destruct (AnnDefEq_invert_a_Star DEB DT ES)  as (B1'' & B2'' & g6 & EB3 & EB4 & DE5 & TB1' & TB2'); auto.\n  assert (erase B1'' = open_tm_wrt_tm B1 (a_Var_f x1)). congruence.\n  assert (erase B2'' = open_tm_wrt_tm B2 (a_Var_f x1)). congruence.\n  clear dependent B1'. clear dependent B2'. clear dependent S.\n\n  pick fresh x2.\n  remember (close_tm_wrt_tm x1 B2'') as CB2.\n  remember (open_tm_wrt_tm CB2 (a_Conv (a_Var_f x2) (g_Sym g5))) as B3.\n\n\n  assert (CTX2 : AnnCtx ([(x2, Tm A2'')] ++ G0)). eauto with ctx_wff.\n  assert (CTX3 : AnnCtx ([(x2, Tm A2'')] ++ [(x1, Tm A1'')] ++ G0)).\n  {  eapply An_ConsTm; eauto with ctx_wff.\n     eapply (AnnTyping_weakening _ [(x1, Tm A1'')] nil); simpl; eauto with ctx_wff. }\n\n\n  assert (AnnTyping G0 (a_Pi rho A1'' (close_tm_wrt_tm x1 B1'')) a_Star).\n  { eapply An_Pi_exists with (x := x1).\n    autorewrite with lngen. clear dependent x2. auto.\n    autorewrite with lngen. auto.\n    auto. }\n\n  assert (AnnTyping G0 (a_Pi rho A2'' (close_tm_wrt_tm x2 B3)) a_Star).\n  { eapply An_Pi_exists with (x := x2).\n       autorewrite with lngen. auto.\n       rewrite HeqB3. rewrite HeqCB2.\n       autorewrite with lngen.\n       rewrite -tm_subst_tm_tm_spec.\n       replace a_Star with (tm_subst_tm_tm (a_Conv (a_Var_f x2) (g_Sym g5)) x1 a_Star); [|simpl; auto].\n       eapply AnnTyping_tm_subst; eauto.\n       eapply AnnTyping_weakening with (F := ([(x1, Tm A1'')])); eauto.\n       eapply An_ConsTm; eauto.\n       eapply AnnTyping_weakening with (F := nil); eauto.\n       eapply An_Conv; eauto.\n       eapply AnnDefEq_weakening with (F := nil)(G0 := G0).\n       eapply (fourth ann_weaken_available_mutual) with (D := dom G0).\n       eapply AnnDefEq_weaken_available.\n       eauto.\n       simpl. clear Fr. clear Fr0. fsetdec.\n       eauto. simpl_env. auto.\n       eapply AnnTyping_weakening with (F := nil); eauto.\n       eauto. }\n\n  exists (g_PiCong rho g5 (close_co_wrt_tm x1 g6)),\n  (a_Pi rho A1'' (close_tm_wrt_tm x1 B1'')),\n  (a_Pi rho A2'' (close_tm_wrt_tm x2 B3)),\n  a_Star.\n\n  repeat split; auto.\n  + simpl. rewrite <- close_tm_erase_tm; auto. rewrite H0.\n    simpl. rewrite close_tm_wrt_tm_open_tm_wrt_tm; auto. rewrite -H. auto.\n  + simpl. f_equal. auto. rewrite <- close_tm_erase_tm; auto. rewrite HeqB3.\n    rewrite HeqCB2.\n    rewrite <- open_tm_erase_tm.\n    rewrite <- close_tm_erase_tm.\n    rewrite H2. simpl.\n    rewrite close_tm_wrt_tm_open_tm_wrt_tm; auto.\n    rewrite close_tm_wrt_tm_open_tm_wrt_tm; auto.\n    autorewrite with lngen.\n    apply notin_remove_2.\n    pose KK := fv_tm_tm_tm_open_tm_wrt_tm_upper B2 (a_Var_f x1). clearbody KK.\n    unfold AtomSetImpl.Subset in KK. unfold not.\n    intros NN. apply KK in NN.\n    apply notin_union in NN. inversion NN. clear KK.\n    simpl. auto. auto.\n  + eapply An_PiCong_exists with (x1 := x1) (x2 := x2) (B2 := CB2); auto.\n    ++ rewrite HeqCB2. autorewrite with lngen. auto.\n    ++ rewrite HeqB3. rewrite HeqCB2. autorewrite with lngen.\n      apply notin_union; auto.\n    ++ rewrite HeqCB2. autorewrite with lngen. auto.\n    ++ autorewrite with lngen. auto.\n    ++ rewrite HeqCB2. autorewrite with lngen.\n       move: (AnnDefEq_context_fv DE5) => /= ?.\n       clear Fr Fr0.\n       apply An_Pi_exists with (x:=x1).\n       +++ apply notin_union. inversion CTX1. auto.\n           autorewrite with lngen. fsetdec.\n       +++ autorewrite with lngen. auto.\n       +++ auto.\n- (* abs-cong *)\n  clear d. rename H1 into H3. rename H2 into H4.\n  destruct (H0 G0 H3 H4) as (A1' & S1 & EA1 & ES & AT). clear H0.\n  subst.\n  destruct (erasure_a_Star AT ES) as (A1 & EA5 & AT1).\n  (*\n  destruct (AnnDefEq_invert_a_Star DE AT ES) as (A1 & A2 & gg & EA5 & EA6 & H & AT1 & AT2).\n  rewrite -EA5.\n  rewrite -EA6.\n  rewrite -EA5 in H0.\n  clear dependent A1'. clear dependent A2'. clear dependent S.\n  *)\n  pick fresh x1.\n  assert (FrL : x1 `notin` L). auto.\n  destruct (H x1 FrL ([(x1,Tm A1)] ++ G0)) as (g2 & b1' & b2' & B' & EB1 & EB2 & S & DEB & TB & TB2); auto. simpl. autorewcs. congruence.\n\n  pick fresh x2.\n  remember (close_tm_wrt_tm x1 b2') as b2''.\n  remember (g_Refl A1) as gg.\n  assert (AnnDefEq G0 D gg A1 A1). { rewrite Heqgg. eauto 3. }\n  remember (open_tm_wrt_tm b2'' (a_Conv (a_Var_f x2) (g_Sym gg))) as b3.\n  remember (open_tm_wrt_tm (close_tm_wrt_tm x1 B')\n                           (a_Conv (a_Var_f x2) (g_Sym gg))) as B3.\n\n  assert (AnnTyping G0 (a_Abs rho A1 (close_tm_wrt_tm x1 b1'))\n                    (a_Pi rho A1 (close_tm_wrt_tm x1 B'))).\n  { eapply An_Abs_exists with (x := x1).\n    + autorewrite with lngen. clear dependent x2. auto.\n    + auto.\n    + autorewrite with lngen. auto.\n    + autorewrite with lngen. autorewcs. rewrite EB1. auto.\n  }\n\n  assert (CTX2 : AnnCtx ([(x2, Tm A1)] ++ G0)). eauto with ctx_wff.\n  assert (CTX3 : AnnCtx ([(x2, Tm A1)] ++ [(x1, Tm A1)] ++ G0)).\n  {  eapply An_ConsTm; eauto.\n     eapply (AnnTyping_weakening _ [(x1, Tm A1)] nil); simpl; eauto with ctx_wff.\n  }\n\n  assert (AnnTyping G0 (a_Abs rho A1 (close_tm_wrt_tm x2 b3))\n                    (a_Pi rho A1 (close_tm_wrt_tm x2 B3))).\n  { eapply An_Abs_exists with (x := x2).\n    + autorewrite with lngen. auto.\n    + auto.\n    + rewrite Heqb3. rewrite HeqB3. rewrite Heqb2''. autorewrite with lngen.\n      rewrite (tm_subst_tm_tm_intro x1).\n      rewrite -(tm_subst_tm_tm_spec B').\n      eapply AnnTyping_tm_subst; eauto 1.\n      autorewrite with lngen.\n      eapply AnnTyping_weakening; eauto 1.\n      eapply An_ConsTm; eauto 1.\n      eapply AnnTyping_weakening with (F:=nil); eauto 1.\n      simpl. eauto.\n      eapply An_Conv. eapply An_Var; eauto.\n      eapply An_Sym2.\n      eapply AnnDefEq_weakening with (F:=nil); eauto 1.\n      simpl.\n      eapply (fourth ann_weaken_available_mutual) with (D:= dom G0).\n      eapply AnnDefEq_weaken_available. eauto.\n      clear Fr Fr0. fsetdec.\n      eapply AnnTyping_weakening with (F:=nil); eauto 1.\n      autorewrite with lngen. eauto.\n    + rewrite Heqb3.  rewrite Heqb2''. autorewrite with lngen.\n      rewrite (tm_subst_tm_tm_intro x1); auto.\n      autorewrite with lngen.\n      autorewcs. rewrite -subst_tm_erase_tm; auto. simpl.\n      autorewcs. rewrite EB2.\n      rewrite -(tm_subst_tm_tm_intro x1); auto.\n      autorewrite with lngen. auto.\n  }\n  assert (TMP: exists g, AnnDefEq G0 D g (a_Pi rho A1 (close_tm_wrt_tm x1 B'))\n                        (a_Pi rho A1 (close_tm_wrt_tm x2 B3))).\n  { eexists. eapply An_PiCong_exists with (x1:=x1) (x2:=x2)\n                                                   (B2 := close_tm_wrt_tm x1 B')\n    (g1:= gg) (g2 := (close_co_wrt_tm x1 (g_Refl B'))).\n    + simpl. autorewrite with lngen. clear Fr0. auto.\n    + autorewrite with lngen.\n      apply notin_union. auto.\n      rewrite Heqgg. auto.\n    + auto.\n    + autorewrite with lngen.\n      eapply An_Refl.\n      eapply AnnTyping_regularity. eauto 1.\n    + autorewrite with lngen. auto.\n    + eapply AnnTyping_regularity. eauto 1.\n    + eapply AnnTyping_regularity. eauto 1.\n    + autorewrite with lngen.\n      move: (AnnTyping_context_fv TB) => /= ?.\n      clear Fr Fr0.\n      apply An_Pi_exists with (x := x1).\n      apply notin_union. inversion CTX3. inversion H7. auto.\n      autorewrite with lngen. fsetdec.\n      autorewrite with lngen.\n      eapply AnnTyping_regularity. eauto.\n      inversion CTX2. auto.\n  }\n  destruct TMP as [gpi Epipi].\n  assert (AnnTyping G0 (a_Conv (a_Abs rho A1 (close_tm_wrt_tm x2 b3)) (g_Sym gpi))\n                    (a_Pi rho A1 (close_tm_wrt_tm x1 B'))).\n  { eapply An_Conv. eauto 1. eapply An_Sym2.\n    eapply AnnDefEq_weaken_available; eauto 1.\n    eapply AnnTyping_regularity. eauto 1. }\n eexists. exists\n  (a_Abs rho A1 (close_tm_wrt_tm x1 b1')),\n  (a_Conv (a_Abs rho A1 (close_tm_wrt_tm x2 b3)) (g_Sym gpi)),\n  (a_Pi rho A1 (close_tm_wrt_tm x1 B')).\n  repeat split; eauto 1.\n  { simpl. f_equal. rewrite <- close_tm_erase_tm; auto. rewrite EB1.\n    simpl. rewrite close_tm_wrt_tm_open_tm_wrt_tm; auto. }\n  { simpl. f_equal. auto. rewrite <- close_tm_erase_tm; auto.\n           rewrite Heqb3. rewrite Heqb2''.\n           rewrite <- open_tm_erase_tm.\n           rewrite <- close_tm_erase_tm.\n           rewrite EB2. simpl.\n           rewrite close_tm_wrt_tm_open_tm_wrt_tm; auto.\n           rewrite close_tm_wrt_tm_open_tm_wrt_tm; auto.\n           autorewrite with lngen.\n           apply notin_remove_2.\n           pose KK := fv_tm_tm_tm_open_tm_wrt_tm_upper b2 (a_Var_f x1). clearbody KK.\n           unfold AtomSetImpl.Subset in KK. unfold not.\n           intros NN. apply KK in NN.\n           apply notin_union in NN. inversion NN. clear KK.\n           simpl. auto. auto.\n  }\n  { simpl. f_equal. autorewcs. congruence.\n    autorewcs. rewrite -close_tm_erase_tm; auto. rewrite S.\n    simpl. rewrite close_tm_wrt_tm_open_tm_wrt_tm; auto. }\n  { eapply An_Trans2 with (a1 := (a_Abs rho A1 (close_tm_wrt_tm x2 b3))).\n    { eapply An_AbsCong_exists with (x1:=x1)(x2:=x2)(b2 := b2'')\n          (g1 := gg) (g2 := (close_co_wrt_tm x1 g2))\n          (B := a_Pi rho A1 (close_tm_wrt_tm x1 B')).\n    + rewrite Heqb2''. autorewrite with lngen. auto.\n    + rewrite Heqb3. rewrite Heqb2''. autorewrite with lngen.\n      apply notin_union; auto. rewrite Heqgg. auto.\n    + auto.\n    + rewrite Heqb2''.\n      autorewrite with lngen. auto.\n    + autorewrite with lngen. auto.\n    + auto.\n    + auto.\n    + autorewrite with lngen. autorewcs. rewrite EB1. auto.\n    + rewrite Heqb3. rewrite Heqb2''.\n      autorewrite with lngen.\n      rewrite (tm_subst_tm_tm_intro x1); auto.\n      autorewrite with lngen.\n      autorewcs. rewrite -subst_tm_erase_tm; auto. simpl.\n      autorewcs. rewrite EB2.\n      rewrite -(tm_subst_tm_tm_intro x1); auto.\n      autorewrite with lngen. auto.\n    + rewrite Heqb2''. autorewrite with lngen.\n      clear Fr Fr0.\n      move: (AnnTyping_context_fv TB2) => /= ?.\n      inversion CTX3. inversion H8. subst.\n      eapply An_Abs_exists with (x:= x1).\n      autorewrite with lngen.\n      fsetdec.\n      auto.\n      autorewrite with lngen.\n      auto.\n      autorewrite with lngen.\n      { apply An_Abs_inversion in H2.\n        destruct H2 as [BB [h0 [h1 h2]]].\n        move: (h2 x1 ltac:(auto)) => [h3 _].\n        rewrite <- open_tm_erase_tm in h3.\n        rewrite <- close_tm_erase_tm in h3.\n        rewrite <- open_tm_erase_tm in h3.\n        rewrite <- close_tm_erase_tm in h3.\n        simpl in h3.\n        replace (a_Var_f x2) with (erase_tm (a_Var_f x2)) in h3.\n        replace (a_Var_f x1) with (erase_tm (a_Var_f x1)) in h3.\n        autorewcshyp h3.\n        rewrite close_tm_erase_tm in h3.\n        rewrite open_tm_erase_tm in h3.\n        replace (a_Var_f x2) with (erase_tm (a_Var_f x2)) in h3.\n        rewrite close_tm_erase_tm in h3.\n        rewrite open_tm_erase_tm in h3.\n        simpl in h3.\n        rewrite close_tm_wrt_tm_open_tm_wrt_tm in h3.\n        rewrite open_tm_wrt_tm_close_tm_wrt_tm in h3.\n        auto.\n        autorewrite with lngen.\n        move: (AnnTyping_context_fv TB2) => [h5 _].\n        simpl in h5. rewrite h5.\n        simpl in H10.\n        fsetdec.\n        auto.\n        auto.\n        auto.\n      }\n    }\n    eapply An_EraseEq; eauto 1.\n    eapply An_Sym. eauto 1.\n    eapply AnnTyping_regularity. eauto 1.\n    eapply AnnTyping_regularity. eauto 1.\n    eapply An_Refl; eauto 2.\n    eapply AnnDefEq_weaken_available; eauto 1.\n  }\n  Unshelve.\n  eauto.\n  eauto.\n- (* appcong *)\n  destruct (H G0 H1 H2) as [g1 [a1' [b1' [AB1 [EA1 [EA2 [ET1 [DE1 [TAB1 _]]]]]]]]]. clear H.\n  destruct (H0 G0 H1 H2) as [g2 [a2' [b2' [A1 [EA3 [EA4 [ET2 [DE2 [TA1 _]]]]]]]]]. clear H0.\n  move: (AnnTyping_regularity TAB1) => TPi.\n  destruct (erase_pi ET1 TPi) as (A' & B' & E1 & E2 & E3 & TP).\n  inversion  TP. subst.\n\n  destruct (AnnDefEq_regularity DE2) as (A2' & B2' & g3 & ? & Tb2' & DEa2b1).\n  resolve_unique_nosubst.\n\n  destruct (erasure_cvt TAB1 E1) as (a1'' & E5 & Ta1''); eauto.\n  assert (exists g, AnnDefEq G0 D g a1'' a1').\n  { eexists. eapply An_EraseEq. eauto.  eauto. autorewcs. congruence.\n    eapply An_EraseEq. eapply AnnTyping_regularity. eauto.\n    eapply AnnTyping_regularity. eauto. eauto.\n    eapply An_Refl. eauto. }\n  destruct H as [g4 DEa1''a1'].\n  move: (An_Trans2 DEa1''a1' DE1) => DE4.\n\n  destruct (erasure_cvt TA1) with (B := A') as (a2'' & E4 & Ta2''); eauto.\n  assert (exists g, AnnDefEq G0 D g a2'' a2').\n  { eexists. eapply An_EraseEq. eauto.  eauto. autorewcs. congruence.\n    eapply An_EraseEq. eapply AnnTyping_regularity. eauto.\n    eapply AnnTyping_regularity. eauto. eauto.\n    eapply An_Refl. eauto. }\n  destruct H as [g5 DEa2''a2'].\n  move: (An_Trans2 DEa2''a2' DE2) => DE3.\n\n  destruct (AnnDefEq_invertb DE4) as (AB1' & b1'' & g6 & TA1' & TB1' & EB & DE5).\n  resolve_unique_nosubst.\n\n  destruct (AnnDefEq_invertb DE3) as (A1'' & b2'' & g7 & TA1'' & TB2'' & EB1 & DE6).\n  resolve_unique_nosubst.\n\n  assert (TT : AnnTyping G0 (a_App a1'' Rel a2'') (open_tm_wrt_tm B' a2'')).\n  { eapply An_App. eauto. eauto. }\n\n  assert (AnnTyping G0 (a_App b1'' Rel b2'') (open_tm_wrt_tm B' b2'')).\n  { eapply An_App. eauto. eauto. }\n\n  assert (exists g, AnnDefEq G0 D g a2'' b2'').\n  { eexists. eapply An_Trans2. eauto. eauto. }\n  destruct H0 as [g8 Eab].\n\n  assert (exists g, AnnDefEq G0 D g (open_tm_wrt_tm B' a2'') (open_tm_wrt_tm B' b2'')).\n  { eexists. eapply An_PiSnd; eauto 1.\n    eapply An_Refl. eapply AnnTyping_regularity. eauto 1. }\n  destruct H0 as [g9 HBB].\n\n  assert (AnnTyping G0 (a_Conv (a_App b1'' Rel b2'') (g_Sym g9)) (open_tm_wrt_tm B' a2'')).\n  { eapply An_Conv; eauto 1. eapply An_Sym2.\n    eapply AnnDefEq_weaken_available; eauto 1.\n    eapply AnnTyping_regularity. eauto. }\n\n  eexists.\n  exists (a_App a1'' Rel a2'').\n  exists (a_Conv (a_App b1'' Rel b2'') (g_Sym g9)).\n  exists (open_tm_wrt_tm B' a2'').\n  repeat split.\n  simpl. autorewcs. congruence.\n  simpl. autorewcs. congruence.\n  rewrite -open_tm_erase_tm.\n  f_equal. auto.\n  { eapply An_Trans2 with (a1 := (a_App b1'' Rel b2'')).\n    eapply An_AppCong; eauto 1.\n    eapply An_Trans2 with (a1 := b1'); eauto 2.\n    eapply AnnDefEq_weaken_available; eauto 1.\n    eapply An_EraseEq; eauto 2.\n    eapply An_Sym.\n    eapply AnnTyping_regularity. eauto.\n    eapply AnnTyping_regularity. eauto.\n    eapply An_Refl. eauto 2.\n    eapply AnnDefEq_weaken_available; eauto 1.\n    }\n  eauto.\n  eauto.\n- (* iappcong *)\n  destruct (H G0 H1 H2) as [g1 [a1' [b1' [AB1 [EA1 [EA2 [ET1 [DE1 [TAB1 _]]]]]]]]]. clear H.\n  destruct (H0 G0 H1 H2) as (a2' & A1 & EA3 & ET2 & TA1). clear H0.\n  move: (AnnTyping_regularity TAB1) => TPi.\n  destruct (erase_pi ET1 TPi) as (A' & B' & E1 & E2 & E3 & TP).\n  inversion  TP. subst.\n\n  destruct (erasure_cvt TAB1 E1) as (a1'' & E5 & Ta1''); eauto.\n  assert (exists g, AnnDefEq G0 D g a1'' a1').\n  { eexists. eapply An_EraseEq. eauto.  eauto. autorewcs. congruence.\n    eapply An_EraseEq. eapply AnnTyping_regularity. eauto.\n    eapply AnnTyping_regularity. eauto. eauto.\n    eapply An_Refl. eauto. }\n  destruct H as [g4 DEa1''a1'].\n  move: (An_Trans2 DEa1''a1' DE1) => DE4.\n\n  destruct (erasure_cvt TA1) with (B := A') as (a2'' & E4 & Ta2''); eauto.\n  assert (exists g, AnnDefEq G0 D g a2'' a2').\n  { eexists. eapply An_EraseEq. eauto.  eauto. autorewcs. congruence.\n    eapply An_EraseEq. eapply AnnTyping_regularity. eauto.\n    eapply AnnTyping_regularity. eauto. eauto.\n    eapply An_Refl. eauto. }\n  destruct H as [g5 DEa2''a2'].\n\n  destruct (AnnDefEq_invertb DE4) as (AB1' & b1'' & g6 & TA1' & TB1' & EB & DE5).\n  resolve_unique_nosubst.\n\n  assert (TT : AnnTyping G0 (a_App a1'' Irrel a2'') (open_tm_wrt_tm B' a2'')).\n  { eapply An_App. eauto. eauto. }\n\n  assert (AnnTyping G0 (a_App b1'' Irrel a2'') (open_tm_wrt_tm B' a2'')).\n  { eapply An_App. eauto. eauto. }\n\n  eexists.\n  exists (a_App a1'' Irrel a2'').\n  exists (a_App b1'' Irrel a2'').\n  exists (open_tm_wrt_tm B' a2'').\n  repeat split.\n  simpl. autorewcs. congruence.\n  simpl. autorewcs. congruence.\n  rewrite -open_tm_erase_tm.\n  f_equal. auto.\n  { eapply An_Trans2 with (a1 := (a_App b1'' Irrel a2'')).\n    eapply An_AppCong; eauto 1.\n    eapply An_Trans2 with (a1 := b1'); eauto 2.\n    eapply An_Refl; eauto 2.\n    eapply An_Refl; eauto 2.\n    eapply AnnTyping_regularity. eauto 2.\n    eapply An_Refl; eauto 2.\n    }\n  eauto.\n  eauto.\n- destruct (H G0 H0 H1) as [g [AB1 [AB2 [S1 [E1 [E2 [E3 [DE [T1 _]]]]]]]]].\n  clear H.\n  destruct (AnnDefEq_regularity DE) as [S2 [S2' [g1 [T2 [T3 DE2]]]]].\n  resolve_unique_nosubst.\n  destruct (erase_pi E1 T1) as [A1' [B1' [F1 [F2 [F3 AT]]]]].\n  destruct (erase_pi E2 T3) as [A2' [B2' [F1' [F2' [F3' AT']]]]].\n  subst.\n  destruct (erasure_AnnDefEq DE T1 E3 F1 F1' AT AT')\n    as (g2 & DE3).\n  inversion AT. inversion AT'. subst.\n  eexists. exists A1', A2', a_Star.\n  repeat split. eauto. eauto. auto.\n- (* PiSnd *)\n  clear d. clear d0.\n  destruct (H G0 H1 H2) as [g [AB1 [AB2 [S1 [E1 [E2 [E3 [DE1 [AT1 _]]]]]]]]]. clear H.\n  destruct (H0 G0 H1 H2) as [g1 [a1' [a2' [S2 [E1' [E2' [E3' [DE2 [AT2 _]]]]]]]]]. clear H0.\n  destruct (AnnDefEq_regularity DE1) as [SS1 [SS2 [g4 [T3 [T4 DE3]]]]].\n  destruct (erase_pi E1 T3) as [A14 [A24 [F1 [F2 [F3 AT]]]]].\n  destruct (erase_pi E2 T4) as [A15 [A25 [F1' [F2' [F3' AT']]]]].\n  inversion AT. subst.\n  inversion AT'. subst.\n\n  (* Get equality between Pi types *)\n  destruct (erasure_AnnDefEq DE1 AT1 E3 F1 F1' AT) as (g6 & DE5). eauto.\n  resolve_unique_nosubst.\n\n  (* a1 of domain type A14 *)\n  destruct (erasure_cvt AT2 (symmetry F2)) as [a1 [EA1 TA1]]. eauto.\n  (* a2 of domain type A15 *)\n  destruct (AnnDefEq_invertb DE2) as (S3 & a2'' & g7 & T5 & T6 & ? & DE6).\n  resolve_unique_nosubst.\n  destruct (erasure_cvt T6 (symmetry F2)) as [a2''' [EA2 TA2]]. eauto.\n  assert (AnnDefEq G0 D (g_PiFst g6) A14 A15).\n  { eapply An_PiFst. eauto. }\n  remember (a_Conv a2''' (g_PiFst g6)) as a2.\n  assert (AnnTyping G0 a2 A15).\n  { rewrite Heqa2. eapply An_Conv; eauto.\n    eapply AnnDefEq_weaken_available. eauto. }\n  (* a1 ~ a2 *)\n  assert (TEMP : exists g, AnnDefEq G0 D g a1 a1').\n  { eexists. eapply An_EraseEq; eauto 1.\n    eapply An_EraseEq; eauto 1.\n    eapply AnnTyping_regularity; eauto.\n    eapply An_Refl. eauto. }\n  destruct TEMP as (? & Ha1a1').\n\n  assert (TEMP : exists g, AnnDefEq G0 D g a2'' a2''').\n  {  eexists.\n    eapply An_EraseEq; eauto 1.\n    eapply An_EraseEq; eauto 1.\n    eapply AnnTyping_regularity; eauto.\n    eapply An_Refl. eauto. }\n  destruct TEMP as (? & Ha2''a2''').\n  assert (TEMP : exists g, AnnDefEq G0 D g a2''' a2).\n  { rewrite Heqa2.\n    eexists.\n    eapply An_EraseEq. eauto.\n    rewrite -Heqa2. eauto.\n    eauto.\n    eapply AnnDefEq_weaken_available. eauto.\n  }\n  destruct TEMP as (? & Ha2'''a2).\n  move: (An_Trans2 Ha1a1' DE2) => Ha1a2'.\n  move: (An_Trans2 Ha1a2' DE6) => Ha1a2''.\n  move: (An_Trans2 Ha1a2'' Ha2''a2''') => Ha1a2'''.\n  move: (An_Trans2 Ha1a2''' Ha2'''a2) => Ha1a2.\n  eexists.\n  exists (open_tm_wrt_tm  A24 a1).\n  exists (open_tm_wrt_tm  A25 a2).\n  exists a_Star.\n  repeat split.\n  rewrite <- open_tm_erase_tm. congruence.\n  rewrite <-  open_tm_erase_tm. rewrite Heqa2. simpl.\n  f_equal. autorewcs. congruence.\n  eapply An_PiSnd; eauto.\n  pick fresh x2 for (L \\u fv_tm_tm_tm A24).\n  rewrite (tm_subst_tm_tm_intro x2); auto.\n  replace a_Star with (tm_subst_tm_tm a1 x2 a_Star).\n  eapply AnnTyping_tm_subst.\n  eapply H4. auto. auto. simpl. auto.\n  pick fresh x2 for (L0 \\u fv_tm_tm_tm A25).\n  rewrite (tm_subst_tm_tm_intro x2); auto.\n  replace a_Star with (tm_subst_tm_tm a2 x2 a_Star).\n  eapply AnnTyping_tm_subst.\n  eapply H3. auto. auto. simpl. auto.\n- (* CPiCong *)\n  idtac. rename A into B1. rename B into B2.\n  clear H1. rename H2 into H1. rename H3 into H2. rename H4 into H3. rename H5 into H4.\n  clear d. clear i.\n  destruct (H G0 H3 H4) as (g1 & phi1' & phi2' & EP1 & EP2 & IP). clear H.\n  clear H1 H2. rename H3 into H1. rename H4 into H2.\n  destruct (AnnIso_regularity IP) as [WFF1 WFF2].\n  inversion WFF1. inversion WFF2. subst.\n\n  move: (AnnTyping_regularity H) => ?.\n  move: (AnnTyping_regularity H7) => ?.\n  move: (AnnTyping_regularity H3) => ?.\n  move: (AnnTyping_regularity H8) => ?.\n\n  assert (exists g, AnnDefEq G0 D g A0 B0).\n  { eexists. eapply An_EraseEq; eauto 1. eauto. }\n  destruct H1 as [g2 EA0B0].\n  assert (exists g, AnnDefEq G0 D g A B).\n  { eexists. eapply An_EraseEq; eauto 1. eauto. }\n  destruct H1 as [g3 EAB].\n\n  pick fresh x1.\n  assert (FrL : x1 `notin` L). auto.\n  assert (CTX1 : AnnCtx ([(x1, Co (Eq a b A))] ++ G0)). eauto with ctx_wff.\n\n  destruct (H0 x1 FrL ([(x1,Co (Eq a b A))] ++ G0)) as (g4 & B1' & B2' & S & EB1 & EB2 & ES & DEB & DT & _); auto.\n  clear H0.\n\n  destruct (AnnDefEq_invert_a_Star DEB DT ES)  as (B1'' & B2'' & g6 & EB3 & EB4 & DE5 & TB1' & TB2'); auto.\n  assert (erase B1'' = open_tm_wrt_co B1 (g_Var_f x1)). congruence.\n  assert (erase B2'' = open_tm_wrt_co B2 (g_Var_f x1)). congruence.\n  clear dependent B1'. clear dependent B2'. clear dependent S.\n\n  pose AVOID := erase B2''.\n  pick fresh x2.\n  remember (close_tm_wrt_co x1 B2'') as CB2.\n  remember (open_tm_wrt_co CB2 (g_Cast (g_Var_f x2) (g_Sym g1))) as B3.\n\n\n  assert (CTX2 : AnnCtx ([(x2, Co (Eq a0 b0 A0))] ++ G0)). eauto with ctx_wff.\n  assert (CTX3 : AnnCtx ([(x2, Co (Eq a0 b0 A0))] ++ [(x1, Co (Eq a b A))] ++ G0)).\n  {  eapply An_ConsCo; eauto.\n     eapply (AnnPropWff_weakening _ [(x1, Co (Eq a b A))] nil); simpl; eauto. }\n\n\n  assert (AnnTyping G0 (a_CPi (Eq a b A) (close_tm_wrt_co x1 B1'')) a_Star).\n  { eapply An_CPi_exists with (c := x1).\n    autorewrite with lngen. clear dependent x2. auto.\n    autorewrite with lngen. auto.\n    autorewrite with lngen. eauto.\n  }\n\n  assert (AnnTyping G0 (a_CPi (Eq a0 b0 A0) (close_tm_wrt_co x2 B3)) a_Star).\n  { eapply An_CPi_exists with (c := x2).\n    autorewrite with lngen. auto.\n    eauto.\n    rewrite HeqB3. rewrite HeqCB2.\n    autorewrite with lngen.\n    rewrite -co_subst_co_tm_spec.\n    replace a_Star with (co_subst_co_tm (g_Cast (g_Var_f x2) (g_Sym g1)) x1 a_Star); [|simpl; auto].\n    eapply AnnTyping_co_subst with (D := dom ([(x2, Co (Eq a0 b0 A0))] ++ G0)); eauto.\n    eapply AnnTyping_weakening with (F := ([(x1, Co (Eq a b A))])); eauto 1.\n    eapply An_ConsCo; eauto.\n    eapply AnnPropWff_weakening with (F := nil); eauto.\n    eapply An_Cast; eauto 2.\n    eapply An_Assn; eauto.\n    simpl. simpl_env.\n    eapply AnnIso_weakening with (F := nil)(G0 := G0).\n    eapply (third ann_weaken_available_mutual) with (D := dom G0).\n    eapply AnnIso_weaken_available.\n    eauto.\n    simpl. clear Fr Fr0. fsetdec.\n    eauto. simpl_env. auto.\n }\n\n\n  exists (g_CPiCong g1 (close_co_wrt_co x1 g6)),\n  (a_CPi (Eq a b A) (close_tm_wrt_co x1 B1'')),\n  (a_CPi (Eq a0 b0 A0) (close_tm_wrt_co x2 B3)),\n  a_Star.\n\n  repeat split.\n  + simpl. rewrite <- close_co_erase_tm; auto. rewrite H0.\n    simpl. rewrite close_tm_wrt_co_open_tm_wrt_co; auto.\n  + simpl. f_equal. rewrite <- close_co_erase_tm; auto. rewrite HeqB3.\n    rewrite HeqCB2.\n    rewrite <- (open_co_erase_tm2 _ _ (g_Var_f x2)).\n    simpl. rewrite close_tm_wrt_co_open_tm_wrt_co.\n    rewrite <- close_co_erase_tm.\n    rewrite H1.\n    simpl. rewrite close_tm_wrt_co_open_tm_wrt_co.\n    auto.\n    clear Fr0. auto.\n    rewrite <- close_co_erase_tm.\n    autorewrite with lngen.\n    apply notin_remove_2.\n    auto.\n  + eapply An_CPiCong_exists with (c1 := x1) (c2 := x2) (B2 := CB2).\n    ++ auto.\n    ++ rewrite HeqCB2. autorewrite with lngen. auto.\n    ++ rewrite HeqB3. rewrite HeqCB2. autorewrite with lngen.\n      apply notin_union; auto.\n    ++ rewrite HeqCB2. autorewrite with lngen. auto.\n    ++ rewrite HeqB3. rewrite HeqCB2. autorewrite with lngen.\n       auto.\n    ++ auto.\n    ++ auto.\n    ++ rewrite HeqCB2. autorewrite with lngen.\n       clear Fr Fr0.\n       move: (AnnDefEq_context_fv DE5) => /= ?.\n       inversion CTX1. subst.\n       eapply An_CPi_exists with (c:=x1).\n       autorewrite with lngen.\n       fsetdec.\n       auto.\n       autorewrite with lngen.\n       auto.\n  + auto.\n  + auto.\n- (* CAbsCong *)\n  rename a into B1. rename b into B2. rename B into S.\n  (*clear H1. rename H2 into H1. rename H3 into H2.*)\n  destruct (H0 G0 H1 H2) as (phi1' & EP1 & WFF1). clear H0.\n  inversion WFF1. subst.\n\n  move: (AnnTyping_regularity H0) => ?.\n  move: (AnnTyping_regularity H3) => ?.\n\n  assert (exists g, AnnDefEq G0 D g A B).\n  { eexists. eapply An_EraseEq; eauto 1. eauto. }\n  destruct H1 as [g3 EAB].\n\n  pick fresh x1.\n  assert (FrL : x1 `notin` L). auto.\n  assert (CTX1 : AnnCtx ([(x1, Co (Eq a b A))] ++ G0)). eauto with ctx_wff.\n\n  destruct (H x1 FrL ([(x1,Co (Eq a b A))] ++ G0)) as (g4 & B1' & B2' & C1 & EB1 & EB2 & ES & DEB & DT & DU); auto.\n  clear H.\n\n  destruct (AnnDefEq_regularity DEB) as (? & C2 & g &  ? & TB2 & DEC).\n  resolve_unique_nosubst.\n  resolve_unique_nosubst.\n\n\n  pose AVOID := erase B2'.\n  pick fresh x2.\n  remember (close_tm_wrt_co x1 B2') as CB2.\n  have refl: exists g, AnnIso G0 D g (Eq a b A) (Eq a b A).\n  { eexists. apply An_PropCong. eapply An_Refl. eassumption. eapply An_Refl. eassumption.\n    apply WFF1. apply WFF1. }\n    destruct refl as [g1 refl].\n    remember (open_tm_wrt_co CB2 (g_Cast (g_Var_f x2) (g_Sym g1))) as B3.\n    remember (open_tm_wrt_co (close_tm_wrt_co x1 C1)\n                           (g_Cast (g_Var_f x2) (g_Sym g1))) as C3.\n\n  assert (CTX2 : AnnCtx ([(x2, Co (Eq a b A))] ++ G0)). eauto 2 with ctx_wff.\n  assert (CTX3 : AnnCtx ([(x2, Co (Eq a b A))] ++ [(x1, Co (Eq a b A))] ++ G0)).\n  {  eapply An_ConsCo; eauto 1.\n     eapply (AnnPropWff_weakening _ [(x1, Co (Eq a b A))] nil); simpl; eauto. }\n\n    assert (AnnTyping G0 (a_CAbs (Eq a b A)\n                               (close_tm_wrt_co x1 B1')) (a_CPi (Eq a b A) (close_tm_wrt_co x1 C1))).\n  { eapply An_CAbs_exists with (c := x1).\n    autorewrite with lngen. clear dependent x2.\n    apply notin_union; auto.\n    auto.\n    autorewrite with lngen. auto.\n  }\n\n\n  assert (AnnTyping G0 (a_CAbs (Eq a b A) (close_tm_wrt_co x2 B3))\n                      (a_CPi (Eq a b A) (close_tm_wrt_co x2 C3))).\n  { eapply An_CAbs_exists with (c := x2).\n    autorewrite with lngen. auto.\n    eauto.\n    rewrite HeqB3. rewrite HeqCB2. rewrite HeqC3.\n    autorewrite with lngen.\n    rewrite -co_subst_co_tm_spec.\n    rewrite -co_subst_co_tm_spec.\n    eapply AnnTyping_co_subst with (D := dom ([(x2, Co (Eq a b A))] ++ G0)); eauto.\n    eapply AnnTyping_weakening with (F := ([(x1, Co (Eq a b A))])); eauto 1.\n    eapply An_ConsCo; eauto.\n    eapply AnnPropWff_weakening with (F := nil); eauto.\n    eapply An_Cast; eauto 2.\n    eapply An_Assn; eauto.\n    simpl; eauto 2.\n    simpl_env.\n    eapply AnnIso_weakening with (F := nil)(G0 := G0).\n    eapply (third ann_weaken_available_mutual) with (D := dom G0).\n    eapply AnnIso_weaken_available.\n    eauto.\n    simpl. clear Fr Fr0. fsetdec.\n    eauto. simpl_env. auto.\n  }\n\n  assert (exists g, AnnDefEq ([(x1, Co (Eq a b A))] ++ G0) (dom G0) g C1 C1).\n  { eexists. eapply An_Refl.\n    eapply AnnTyping_regularity. eauto 1. }\n  destruct H5 as [ grefl EC1C1].\n  assert (exists g, AnnDefEq G0 (dom G0) g\n                        (a_CPi (Eq a b A) (close_tm_wrt_co x1 C1))\n                        (a_CPi (Eq a b A) (close_tm_wrt_co x2 C3))).\n  {\n    eexists. eapply An_CPiCong_exists with\n             (c1 := x1)\n               (c2 := x2)\n               (B2 := close_tm_wrt_co x1 C1)\n               (g3 := close_co_wrt_co x1 grefl).\n    + eapply AnnIso_weaken_available. eauto 1.\n    + simpl. autorewrite with lngen. clear Fr0. auto.\n    + autorewrite with lngen.\n      apply notin_union.\n      pose M := AnnIso_context_fv refl.\n      clearbody M.\n      destruct M as [_ [h4 _]].\n      unfold \"[<=]\" in h4.\n      move => h6.\n      have h1: x2 `notin` dom G0; auto.\n      auto 3.\n    + autorewrite with lngen. eauto 1.\n    + rewrite HeqC3. autorewrite with lngen. auto.\n    + eapply AnnTyping_regularity; eauto 1.\n    + eapply AnnTyping_regularity; eauto 1.\n    + autorewrite with lngen.\n      clear Fr Fr0.\n      move: (AnnTyping_context_fv DT) => /= ?.\n      inversion CTX3. inversion H8. subst.\n      eapply An_CPi_exists with (c:=x1).\n      autorewrite with lngen.\n      fsetdec.\n      auto.\n      autorewrite with lngen.\n      eapply AnnTyping_regularity. eauto.\n  }\n  destruct H5 as [g5 Epipi].\n\n  assert (AnnTyping G0\n                    (a_Conv (a_CAbs (Eq a b A) (close_tm_wrt_co x2 B3))\n                            (g_Sym g5))\n                    (a_CPi (Eq a b A) (close_tm_wrt_co x1 C1))).\n  { eapply An_Conv; eauto 1.\n    eapply An_Sym2; auto.\n    eapply AnnTyping_regularity; eauto 1. }\n\n  eexists.\n  exists (a_CAbs (Eq a b A) (close_tm_wrt_co x1 B1')),\n  (a_Conv (a_CAbs (Eq a b A) (close_tm_wrt_co x2 B3)) (g_Sym g5)),\n  (a_CPi (Eq a b A) (close_tm_wrt_co x1 C1)).\n\n  repeat split.\n  + simpl. rewrite <- close_co_erase_tm; auto. rewrite EB1.\n    simpl. rewrite close_tm_wrt_co_open_tm_wrt_co; auto.\n  + simpl. f_equal. rewrite <- close_co_erase_tm; auto. rewrite HeqB3.\n    rewrite HeqCB2.\n    rewrite <- (open_co_erase_tm2 _ _ (g_Var_f x2)).\n    simpl. rewrite close_tm_wrt_co_open_tm_wrt_co.\n    rewrite <- close_co_erase_tm.\n    rewrite EB2.\n    simpl. rewrite close_tm_wrt_co_open_tm_wrt_co.\n    auto.\n    clear Fr0. auto.\n    rewrite <- close_co_erase_tm.\n    autorewrite with lngen.\n    apply notin_remove_2.\n    auto.\n  + simpl. f_equal.\n    rewrite <- close_co_erase_tm; auto. rewrite ES.\n    simpl. rewrite close_tm_wrt_co_open_tm_wrt_co; auto.\n\n  + eapply An_Trans2 with (a1 := (a_CAbs (Eq a b A)(close_tm_wrt_co x2 B3))).\n    eapply An_CAbsCong_exists with (c1 := x1) (c2 := x2) (a2 := CB2)\n       (g3 := close_co_wrt_co x1 g4)\n       (B := a_CPi (Eq a b A) (close_tm_wrt_co x1 C1));\n      eauto 1.\n    ++ rewrite HeqCB2. autorewrite with lngen. auto.\n    ++ autorewrite with lngen.\n       apply notin_union.\n       pose M := AnnIso_context_fv refl.\n       clearbody M.\n       destruct M as [_ [h4 _]].\n       unfold \"[<=]\" in h4.\n       move => h6.\n       have h1: x2 `notin` dom G0; auto.\n       rewrite HeqCB2. autorewrite with lngen.\n       auto 3.\n    ++ rewrite HeqCB2. autorewrite with lngen. auto.\n    ++ rewrite HeqB3. rewrite HeqCB2. autorewrite with lngen.\n       auto.\n    ++ autorewrite with lngen.\n       clear Fr Fr0.\n       subst CB2.\n       inversion CTX3. inversion H9. subst.\n       eapply An_CAbs_exists with (c:=x1).\n       autorewrite with lngen. fsetdec.\n       auto.\n       autorewrite with lngen. auto.\n    ++ eapply An_EraseEq; eauto 1.\n       eapply An_Sym2; eauto 1.\n  + eauto 1.\n  + eauto 1.\n    Unshelve.\n    eauto 1.\n    eauto 1.\n- (* CAppCong *)\n  clear d.\n\n  destruct (H G0 H1 H2) as [g1 [a1' [b1' [AB1 [EA1 [EA2 [ET1 [DE1 [TAB1 _]]]]]]]]]. clear H.\n  move: (AnnTyping_regularity TAB1) => TPi.\n  destruct (erase_cpi ET1 TPi) as (A' & B' & E1 & E2 & E3 & TP).\n  inversion  TP.\n\n  destruct A' as [a2'' b2'']. simpl in E2. inversion E2. clear E2.\n  inversion H5.\n\n  destruct (H0 G0 H1 H2) as [g2 [a2' [b2' [A1' [EA3 [EA4 [ET2 [DE2 [TA1 _]]]]]]]]]. clear H0.\n  subst.\n\n  move: (AnnTyping_regularity H14) => SA1.\n  move: (AnnTyping_regularity H15) => ?.\n  move: (AnnTyping_regularity TA1) => SA1'.\n\n (* Make sure func has the cpi-type *)\n destruct (erasure_cvt TAB1 E1) as (a1'' & E5 & Ta1''); eauto.\n  assert (exists g, AnnDefEq G0 D g a1'' a1').\n  { eexists. eapply An_EraseEq. eauto.  eauto. autorewcs. congruence.\n    eapply An_EraseEq. eapply AnnTyping_regularity. eauto.\n    eapply AnnTyping_regularity. eauto. eauto.\n    eapply An_Refl. eauto. }\n  destruct H as [g4 DEa1''a1'].\n  move: (An_Trans2 DEa1''a1' DE1) => DE4.\n\n  (* Find the coercion that corresponds to that prop.  *)\n  destruct (AnnDefEq_regularity DE2) as (? & B2' & g3 & ? & Tb2' & DEa2b1).\n  move: (AnnTyping_regularity Tb2') => ?.\n  resolve_unique_nosubst.\n\n  assert (exists g, AnnDefEq G0 (dom G0) g a2'' a2').\n  { eexists. eapply An_EraseEq; eauto 1.\n    eapply An_EraseEq; eauto 1. eapply An_Refl. eauto. }\n  destruct H as [g5 Ea2''a2'].\n\n\n  assert (exists g, AnnDefEq G0 (dom G0) g A0 B1).\n  { eexists. eapply An_EraseEq; eauto 1. eapply An_Refl. eauto. }\n  destruct H as [g6 EA1B1].\n\n  assert (exists g, AnnDefEq G0 (dom G0) g A1' A0).\n  { eexists. eapply An_EraseEq; eauto 1. eapply An_Refl. eauto. }\n  destruct H as [g7 EA1'A1].\n\n  (* Make b'' have the same type as b2' *)\n\n  assert (exists g, AnnDefEq G0 (dom G0) g b2' b2'').\n  { eexists. eapply An_EraseEq; eauto 1.\n    eapply An_Trans2 with (a1 := A1').\n    eapply An_Sym2; eauto 1.\n    eapply An_Trans2 with (a1 := A0);\n      eauto 1.\n      }\n  destruct H as [g8 Eb2'b2''].\n\n  rewrite -erase_dom in DE2.\n  move: (An_Trans2 Ea2''a2' (An_Trans2 DE2 Eb2'b2'')) => Ea2''b2''.\n  remember (g_Trans g5 (g_Trans g2 g8)) as g9.\n\n  (* Find b1' type as a CPi type *)\n  destruct (AnnDefEq_invertb DE4) as (? & b1'' & g10 & ? & Tb1'' & E6 & DEBB).\n  resolve_unique_nosubst.\n\n  assert (TT : AnnTyping G0 (a_CApp a1'' g9) (open_tm_wrt_co B' g9)).\n  { eapply An_CApp. eauto. eauto. }\n\n  assert (AnnTyping G0 (a_CApp b1'' g9) (open_tm_wrt_co B' g9)).\n  { eapply An_CApp. eauto. eauto. }\n\n  eexists.\n  exists (a_CApp a1'' g9).\n  exists (a_CApp b1'' g9).\n  exists (open_tm_wrt_co B' g9).\n  repeat split.\n  simpl. f_equal. eauto 1.\n  simpl. f_equal. eauto 2.\n  rewrite <- (open_co_erase_tm2 _ _ g_Triv). auto.\n\n  eapply An_CAppCong; eauto 2.\n  eapply An_Trans2 with (a1 := b1'); eauto 1.\n  eapply An_Refl. eapply AnnTyping_regularity; eauto 1.\n  assumption.\n  assumption.\n- (* CPiSnd *)\n  clear d. clear d1. clear d0.\n  rename a1' into b1. rename a2' into b2. rename A' into B.\n  destruct (H G0 H2 H3) as [g [AB1 [AB2 [S1 [E1 [E2 [E3 [DE1 [T1 _]]]]]]]]]. clear H.\n  destruct (H0 G0 H2 H3) as [g1 [a1' [a2' [A' [EA11 [EA21 [E31 [DEA [T1A _]]]]]]]]]. clear H0.\n  destruct (H1 G0 H2 H3) as [g1' [b1' [b2' [B' [EA11' [EA21' [E31' [DEA' [T1A' _]]]]]]]]]. clear H1.\n\n  destruct (AnnDefEq_regularity DE1) as [S1' [S2' [g4 [T3 [T4 DE3]]]]].\n  destruct (AnnDefEq_regularity DEA) as [S1'' [S2'' [g5 [T3' [T4' DE3']]]]].\n  destruct (AnnDefEq_regularity DEA') as [S1''' [S2''' [g5' [T3'' [T4'' DE3'']]]]].\n  resolve_unique_nosubst.\n  resolve_unique_nosubst.\n  resolve_unique_nosubst.\n\n  move: (AnnTyping_regularity T1A) => ?.\n  move: (AnnTyping_regularity T1A') => ?.\n  move: (AnnTyping_regularity T4) => ?.\n  move: (AnnTyping_regularity T4') => ?.\n\n  destruct (erase_cpi E1 T1) as [phi1' [B1' [F1 [F2 [F3 AT]]]]].\n  destruct (erase_cpi E2 T4) as [phi2' [B2' [F1' [F2' [F3' AT']]]]].\n  destruct phi1' as [a1'' a2'' A'']. simpl in F2. inversion F2. clear F2.\n  destruct phi2' as [b1'' b2'' B'']. simpl in F2'. inversion F2'. clear F2'.\n\n  destruct (erasure_AnnDefEq DE1 T1 E3  F1 F1' AT AT') as [g2 DE2].\n  inversion AT. inversion AT'.\n  inversion H10. inversion H15.\n  subst.\n\n  (* Have the equality between the CPi types. Now we need to get the\n     coercions to match them.\n   *)\n  assert (TMP : exists g, AnnDefEq G0 D g a1'' a1').\n  { eexists. eapply An_EraseEq; eauto 1.\n    eapply An_EraseEq.\n    eapply AnnTyping_regularity; eauto 1.\n    eapply AnnTyping_regularity; eauto 1.\n    eauto 1.\n    eapply An_Refl; eauto 2. }\n  destruct TMP as [g3 Ea1''a1'].\n  assert (TMP : exists g, AnnDefEq G0 (dom G0) g A'' B4).\n  { eexists. eapply An_EraseEq.\n    eapply AnnTyping_regularity; eauto 1.\n    eapply AnnTyping_regularity; eauto 1.\n    eauto 1.\n    eapply An_Refl; eauto 2. }\n  destruct TMP as [g6 EA''B4].\n assert (TMP : exists g, AnnDefEq G0 (dom G0) g A' A'').\n  { eexists. eapply An_EraseEq.\n    eapply AnnTyping_regularity; eauto 1.\n    eapply AnnTyping_regularity; eauto 1.\n    eauto 1.\n    eapply An_Refl; eauto 2. }\n  destruct TMP as [g7 EA'A''].\n\n  move: (An_Trans2 (An_Sym2 DE3') (An_Trans2 EA'A'' EA''B4)) => ?.\n  assert (TMP : exists g, AnnDefEq G0 D g a2' a2'').\n  { eexists. eapply An_EraseEq; eauto 1. }\n  destruct TMP as [g8 Ea2'a2''].\n\n  move: (AnnDefEq_weaken_available Ea1''a1') => y.\n  rewrite erase_dom in y.\n  move: (AnnDefEq_weaken_available Ea2'a2'') => x.\n  rewrite erase_dom in x.\n  move: (An_Trans2 y (An_Trans2 DEA x)) => Ea1''a2''.\n\n  assert (TMP : exists g, AnnDefEq G0 D g b1'' b1').\n  { eexists. eapply An_EraseEq; eauto 1.\n    eapply An_EraseEq.\n    eapply AnnTyping_regularity; eauto 1.\n    eapply AnnTyping_regularity; eauto 1.\n    eauto 1.\n    eapply An_Refl; eauto 2. }\n  destruct TMP as [g9 Eb1'Eb1''].\n  (* WANT S''' B5 *)\n\n\n  assert (TMP : exists g, AnnDefEq G0 (dom G0) g B'' B5).\n  { eexists. eapply An_EraseEq.\n    eapply AnnTyping_regularity; eauto 1.\n    eapply AnnTyping_regularity; eauto 1.\n    eauto 1.\n    eapply An_Refl; eauto 2. }\n  destruct TMP as [g10 EB''B5].\n assert (TMP : exists g, AnnDefEq G0 (dom G0) g B' B'').\n  { eexists. eapply An_EraseEq.\n    eapply AnnTyping_regularity; eauto 1.\n    eapply AnnTyping_regularity; eauto 1.\n    eauto 1.\n    eapply An_Refl; eauto 2. }\n  destruct TMP as [g11 EB'B''].\n\n  move: (An_Trans2 (An_Sym2 DE3'') (An_Trans2 EB'B'' EB''B5)) => ?.\n  assert (TMP : exists g, AnnDefEq G0 D g b2' b2'').\n  { eexists. eapply An_EraseEq; eauto 1. }\n  destruct TMP as [g12 Eb2'b2''].\n\n  assert (TMP : exists g, AnnDefEq G0 D g b1'' b1').\n  { eexists. eapply An_EraseEq; eauto 1.\n    eapply An_EraseEq.\n    eapply AnnTyping_regularity; eauto 1.\n    eapply AnnTyping_regularity; eauto 1.\n    eauto 1.\n    eapply An_Refl; eauto 2. }\n  destruct TMP as [g13 Eb1''b1'].\n\n\n  move: (AnnDefEq_weaken_available Eb2'b2'') => y1.\n  rewrite erase_dom in y1.\n  move: (AnnDefEq_weaken_available Eb1''b1') => x1.\n  rewrite erase_dom in x1.\n\n  move: (An_Trans2 x1 (An_Trans2 DEA' y1)) => Eb1''b2''.\n  clear x1. clear y1.\n  eexists.\n  exists\n    (open_tm_wrt_co B1' (g_Trans g3 (g_Trans g1 g8))),\n    (open_tm_wrt_co B2' (g_Trans g13 (g_Trans g1' g12))), a_Star.\n  repeat split.\n  + simpl. rewrite <- open_co_erase_tm2 with (g := g_Triv). auto.\n  + simpl. rewrite <- open_co_erase_tm2 with (g := g_Triv). auto.\n  + eapply An_CPiSnd; eauto. rewrite erase_dom. auto.\n    rewrite erase_dom. auto.\n  + pick fresh x1 for (L \\u fv_co_co_tm B1').\n    rewrite (co_subst_co_tm_intro x1).\n    replace a_Star with (co_subst_co_tm (g_Trans g3 (g_Trans g1 g8)) x1 a_Star).\n    eapply AnnTyping_co_subst.\n    eauto.\n    eauto.\n    simpl. auto. auto.\n  + pick fresh x1 for (L0 \\u fv_co_co_tm B2').\n    rewrite (co_subst_co_tm_intro x1).\n    replace a_Star with (co_subst_co_tm (g_Trans g13 (g_Trans g1' g12)) x1 a_Star).\n    eapply AnnTyping_co_subst.\n    eapply H16; eauto 1.\n    eauto 1.\n    simpl. auto.\n    auto.\n- (* Cast *)\n  clear i. clear d.\n  destruct (H G0 H1 H2) as [g [a0' [b0' [A0' [EA [EB [S2 [DE [T1 _]]]]]]]]]. clear H.\n  destruct (H0 G0 H1 H2) as [g1 [phi' [phi2' [EP1 [EP2 IP]]]]]. clear H0.\n  destruct (AnnIso_regularity IP) as [WFF1 WFF2].\n  inversion WFF1. inversion WFF2. subst.\n  move: (AnnTyping_regularity H) => ?.\n  move: (AnnTyping_regularity H0) => ?.\n  move: (AnnTyping_regularity H6) => ?.\n  move: (AnnTyping_regularity H7) => ?.\n  assert (EA0A1 : AnnDefEq G0 D (g_IsoSnd g1) A0 A1).\n  {  eapply An_IsoSnd. eauto. }\n  assert (exists g, AnnDefEq G0 D g B B0).\n  { eapply (erasure_AnnDefEq EA0A1); eauto 1. }\n  destruct H1 as [g2 EBB0].\n\n  destruct (AnnDefEq_regularity DE) as [C [D1 [g3 [TC [TD CD]]]]].\n  simpl in EP1. inversion EP1.\n  simpl in EP2. inversion EP2. subst. clear EP2. clear EP1.\n  resolve_unique_nosubst.\n\n\n  assert (exists g, AnnDefEq G0 D g a0 a0').\n  { eexists.\n    eapply An_EraseEq. eauto. eauto. eauto.\n    eapply An_EraseEq. eapply AnnTyping_regularity. eauto.\n    eapply AnnTyping_regularity. eauto. eauto.\n    eapply An_Refl. eauto. }\n  destruct H1 as [g4 Ea0a0'].\n\n  assert (exists g, AnnDefEq G0 D g B0 A1).\n  { eexists.\n    eapply An_EraseEq. eauto. eapply AnnTyping_regularity. eauto. eauto.\n    eapply An_Refl. eauto. }\n  destruct H1 as [g5 EB0A1].\n\n  assert (exists g, AnnDefEq G0 D g A0 A0').\n  { eexists.\n    eapply An_EraseEq. eauto. eapply AnnTyping_regularity. eauto. eauto.\n    eauto. }\n  destruct H1 as [g6 EA0A0'].\n\n  move: (An_Trans2 (An_Trans2 EB0A1 (An_Sym2 EA0A1)) EA0A0') => EB0A0'.\n  move: (An_Trans2 (AnnDefEq_weaken_available EB0A0') CD) => EB0D1.\n  move: (An_Trans2 (AnnDefEq_weaken_available EBB0) EB0D1) => EBD1.\n\n  assert (exists g, AnnDefEq G0 D g b0 b0').\n  { eexists.\n    eapply An_EraseEq. eauto. eauto. eauto. eauto.\n  }\n  destruct H1 as [g7 Eb0b0'].\n  (* assert (exists g, AnnIso G0 D g (Eq a0 b0 A0) (Eq a1 (a_Conv b1 g5) A0)) *)\n\n  eexists. exists a1, (a_Conv b1 g5), A1.\n  repeat split.\n  eapply An_Trans2 with (a1 := b1).\n  eapply (An_Cast _ _ _ _ _ _ _ _ _ _ _ IP); eauto 1.\n  eapply An_EraseEq. eauto 1.\n  eapply An_Conv with (B := A1); eauto 1.\n  eapply AnnDefEq_weaken_available; eauto 1.\n  simpl. auto.\n  eapply AnnDefEq_weaken_available; eauto 1.\n  eauto 1.\n  eapply An_Conv with (B := A1); eauto 1.\n  eapply AnnDefEq_weaken_available; eauto 1.\n  Unshelve.\n  Focus 2.\n  eapply (An_Trans2 (An_Trans2 Ea0a0' DE) (An_Sym2 Eb0b0')).\n- (* EqConv *)\n  clear d. clear d0.\n  destruct (H G0 H1 H2) as [g [a0' [b0' [A0' [EA [EB [S2 [DE [T1 U1]]]]]]]]]. clear H.\n  destruct (H0 G0 H1 H2) as [g1 [A' [B' [S' [EP1 [EP2 [ES [DE2 [T2 U2]]]]]]]]]. clear H0.\n  subst. rewrite -erase_dom in DE2.\n\n  assert (exists g, AnnDefEq G0 D g A0' A').\n  { eexists.\n    eapply An_EraseEq. eauto. eapply AnnTyping_regularity. eauto. eauto.\n    eauto.  eapply An_EraseEq.\n    eapply An_Star. eauto 1. eapply AnnTyping_regularity. eauto.\n    autorewcs. eauto 1.\n    eapply An_Refl. eauto. }\n  destruct H as [g2 EA0'A'].\n\n  move: (An_Trans2 (AnnDefEq_weaken_available EA0'A') DE2) => EA0'B'.\n  move: (AnnTyping_regularity T1) => TA0'.\n  destruct (AnnDefEq_invertb EA0'B') as (S'' & B'' & g3 & TS & TB & EB & DB'B'').\n  resolve_unique_nosubst.\n\n  move: (An_Trans2 EA0'B' DB'B'') => EA0'B''.\n  assert (exists g, AnnDefEq G0 D g (a_Conv a0' (g_Trans (g_Trans g2 g1) g3)) a0').\n  { eexists. eapply An_EraseEq; eauto 1.\n    eapply An_Conv; eauto 1. eapply An_Sym2. eauto.\n  }\n  destruct H as [g4 Ea0'].\n  eexists. exists (a_Conv a0' (g_Trans (g_Trans g2 g1) g3)),\n              (a_Conv b0' (g_Trans (g_Trans g2 g1) g3)), B''.\n  repeat split; auto.\n  eapply An_Trans2 with (a1 := a0'); eauto 1.\n  eapply An_Trans2 with (a1 := b0'); eauto 1.\n  eapply An_EraseEq; eauto 1. eapply An_Conv; eauto 1.\n  eapply An_Conv; eauto 1.\n  eapply An_Conv; eauto 1.\n- clear i.\n  destruct (H G0 H0 H1) as [g1 [phi' [phi2' [EP1 [EP2 IP]]]]]. clear H.\n  destruct (AnnIso_regularity IP) as [WFF1 WFF2].\n  inversion WFF1. inversion WFF2. subst.\n  move: (AnnTyping_regularity H) => ?.\n  move: (AnnTyping_regularity H6) => ?.\n  simpl in EP1. inversion EP1.\n  simpl in EP2. inversion EP2. subst. clear EP2. clear EP1.\n\n  eexists. exists A0, A1, a_Star.\n  repeat split; eauto 1.\n  eapply An_IsoSnd. eauto.\nQed.\n\n\n\n\n\n\n\n\n\nEnd erase.\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/old/erase.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2942262341062967}}
{"text": "From Relational Require Import OrderEnrichedCategory GenericRulesSimple.\n\nSet Warnings \"-notation-overridden,-ambiguous-paths\".\nFrom mathcomp Require Import all_ssreflect all_algebra reals distr realsum\n  ssrnat ssreflect ssrfun ssrbool ssrnum eqtype choice seq.\nSet Warnings \"notation-overridden,ambiguous-paths\".\n\nFrom Crypt Require Import Axioms ChoiceAsOrd SubDistr Couplings\n  UniformDistrLemmas FreeProbProg Theta_dens RulesStateProb UniformStateProb\n  pkg_core_definition choice_type pkg_composition pkg_rhl\n  Package Prelude RandomOracle.\n\nFrom Coq Require Import Utf8.\nFrom extructures Require Import ord fset fmap.\n\nFrom Equations Require Import Equations.\nRequire Equations.Prop.DepElim.\n\nSet Equations With UIP.\n\nSet Bullet Behavior \"Strict Subproofs\".\nSet Default Goal Selector \"!\".\nSet Primitive Projections.\n\nImport Num.Def.\nImport Num.Theory.\nImport Order.POrderTheory.\n\nImport PackageNotation.\n\nSection Executor.\n\n  Context (sample : ∀ (e : choice_type), nat → option (nat * e)).\n\n  Inductive NatState :=\n  | NSUnit\n  | NSNat (n : nat)\n  | NSOption (A : option NatState)\n  | NSProd (A B : NatState).\n\n  Equations? nat_ch_aux (x : NatState) (l : choice_type) : option (Value l) :=\n    nat_ch_aux (NSUnit) 'unit := Some Datatypes.tt ;\n    nat_ch_aux (NSNat n) 'nat := Some n ;\n    nat_ch_aux (NSNat n) 'bool := Some (Nat.odd n) ;\n    nat_ch_aux (NSNat n) 'fin n' := Some _ ;\n    nat_ch_aux (NSOption (Some a)) ('option l) := Some (nat_ch_aux a l) ;\n    nat_ch_aux (NSOption None) ('option l) := Some None ;\n    nat_ch_aux (NSProd a b) (l1 × l2) with (nat_ch_aux a l1, nat_ch_aux b l2) := {\n         nat_ch_aux (NSProd a b) (l1 × l2) (Some v1, Some v2) := Some (v1, v2) ;\n         nat_ch_aux (NSProd a b) (l1 × l2) _ := None ;\n      } ;\n    nat_ch_aux _ _ := None.\n  Proof.\n    - eapply @Ordinal.\n      instantiate (1 := n %% n').\n      apply ltn_pmod.\n      apply cond_pos0.\n  Defined.\n\n  Definition nat_ch (x : option NatState) (l : choice_type) : option (Value l) :=\n    match x with\n    | Some v => nat_ch_aux v l\n    | None => None\n    end.\n\n  Equations ch_nat (l : choice_type) (v : l) : option NatState :=\n    ch_nat 'unit v := Some NSUnit ;\n    ch_nat 'nat v := Some (NSNat v) ;\n    ch_nat 'bool v := Some (NSNat v) ;\n    ch_nat 'fin n v := Some (NSNat v) ;\n    ch_nat (l1 × l2) (pair v1 v2) :=\n      match (ch_nat l1 v1, ch_nat l2 v2) with\n        | (Some v, Some v') => Some (NSProd v v')\n        | _ => None\n      end ;\n    ch_nat 'option l (Some v) :=\n      match (ch_nat l v) with\n        | Some v' => Some (NSOption (Some v'))\n        | _ => None\n      end ;\n    ch_nat 'option l None := Some (NSOption None) ;\n    ch_nat _ _ := None.\n\n  Lemma ch_nat_ch l v:\n    match (ch_nat l v) with\n      | Some k => nat_ch (Some k) l = Some v\n      | _ => true\n    end.\n  Proof.\n    induction l.\n    - rewrite ch_nat_equation_1.\n      simpl.\n      rewrite nat_ch_aux_equation_1.\n      by destruct v.\n    - rewrite ch_nat_equation_2.\n      simpl.\n      rewrite nat_ch_aux_equation_9.\n      reflexivity.\n    - rewrite ch_nat_equation_3.\n      simpl.\n      rewrite nat_ch_aux_equation_10.\n      destruct v ; reflexivity.\n    - destruct v.\n      rewrite ch_nat_equation_4.\n      simpl.\n      specialize (IHl1 s).\n      specialize (IHl2 s0).\n      move: IHl1 IHl2.\n      case (ch_nat l1 s) ;\n      case (ch_nat l2 s0).\n      + simpl.\n        intros.\n        rewrite nat_ch_aux_equation_32.\n        by rewrite IHl1 IHl2.\n      + by simpl ; intros ; try inversion IHl1 ; try inversion IHl2.\n      + by simpl ; intros ; try inversion IHl1 ; try inversion IHl2.\n      + by simpl ; intros ; try inversion IHl1 ; try inversion IHl2.\n    - rewrite ch_nat_equation_5.\n      done.\n    - destruct v eqn:e ; simpl.\n      + rewrite ch_nat_equation_6.\n        specialize (IHl s).\n        case (ch_nat l s) eqn:e'.\n        ++ simpl.\n           intros.\n           rewrite nat_ch_aux_equation_20.\n           f_equal.\n           done.\n        ++ done.\n      + rewrite ch_nat_equation_7.\n        done.\n    - rewrite ch_nat_equation_8.\n      simpl.\n      rewrite nat_ch_aux_equation_14.\n      f_equal.\n      unfold nat_ch_aux_obligation_1.\n      have lv := ltn_ord v.\n      apply /eqP.\n      erewrite <- inj_eq.\n      2: apply ord_inj.\n      simpl.\n      rewrite modn_small.\n      2: assumption.\n      done.\n  Qed.\n\n  Definition new_state\n             (st : Location → option NatState) (l : Location) (v : l) : (Location → option NatState)\n    :=\n    fun (l' : Location) =>\n      if l.π2 == l'.π2\n      then (ch_nat l v)\n      else st l'.\n\n  (* I don't understand why it's needed again. *)\n  Import pkg_core_definition.\n\n  Fixpoint Run_aux {A : choiceType}\n           (c : raw_code A) (seed : nat) (st : Location → option NatState)\n    : option A :=\n    match c with\n    | ret x => Some x\n    | sampler o k =>\n        match sample (projT1 o) seed with\n        | Some (seed', x) => Run_aux (k x) seed' st\n        | _ => None\n        end\n    | opr o x k => None (* Calls should be inlined before we can run the program *)\n    | putr l v k => Run_aux k seed (new_state st l v)\n    | getr l k =>\n        match nat_ch (st l) l with\n          | Some v => Run_aux (k v) seed st\n          | None => None\n        end\n    end.\n\n  Definition Run {A} :=\n    (fun c seed => @Run_aux A c seed (fun (l : Location) => Some NSUnit)).\n\nEnd Executor.\n\n#[program] Fixpoint sampler (e : choice_type) seed : option (nat * e):=\n  match e with\n    chUnit => Some (seed, Datatypes.tt)\n  | chNat => Some ((seed + 1)%N, seed)\n  | chBool => Some ((seed + 1)%N, Nat.even seed)\n  | chProd A B =>\n      match sampler A seed with\n      | Some (seed' , x) => match sampler B seed' with\n                           | Some (seed'', y) => Some (seed'', (x, y))\n                           | _ => None\n                           end\n      | _ => None\n      end\n  | chMap A B => None\n  | chOption A =>\n      match sampler A seed with\n      | Some (seed', x) => Some (seed', Some x)\n      | _ => None\n      end\n  | chFin n => Some ((seed + 1)%N, _)\n  end.\nNext Obligation.\n  eapply Ordinal.\n  instantiate (1 := (seed %% n)%N).\n  rewrite ltn_mod.\n  apply n.\nDefined.\n\nSection Test.\n\n  Definition loc : Location :=  ('nat ; 1)%N.\n  Definition locs : {fset Location} := fset [:: loc].\n\n  Definition test_prog_sub (x : nat):\n    code fset0 [interface] 'nat :=\n    {code\n       k ← sample uniform 20 ;;\n       let y := (x + k)%N in\n       ret y\n    }.\n\n  #[program] Definition test_prog (x : nat):\n    code locs [interface] 'nat :=\n    {code\n       k ← test_prog_sub x ;;\n       #put loc := k ;;\n       k' ← get loc ;;\n       ret k'\n    }.\n  Next Obligation.\n    ssprove_valid.\n  Defined.\n\n  (* Compute (Run sampler (test_prog 2) 54). *)\n\n  Lemma interpretation_test1:\n    ∀ seed input,\n      (Run sampler (test_prog input) seed) = Some (input + seed %% 20)%N.\n  Proof.\n    done.\n  Qed.\n\n  Definition E :=\n    [interface\n      #val #[ 0 ] : 'nat → 'nat\n    ].\n\n  Definition test_pack:\n    package locs [interface] E :=\n    [package\n      #def #[ 0 ] (x : 'nat) : 'nat\n      {\n        k ← sample uniform 20 ;;\n        let y := (x + k)%N in\n        #put loc := y ;;\n        y' ← get loc ;;\n        ret y'\n      }\n    ].\n\nEnd Test.\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/examples/Executor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.29414716376084565}}
{"text": "Require Import ssreflect ssrfun ssrbool finfun fintype ssrnat eqtype seq tuple.\nRequire Import bitsrep bitsprops.\nRequire Import program.\n\nRequire Import stringbuff.\nRequire Import compiler.\n\n(* ATBR *)\n(*Require Import ATBR.Common.*)\nRequire Import ATBR.Classes.\nRequire Import ATBR.Graph.\nRequire Import ATBR.DecideKleeneAlgebra.\nRequire Import ATBR.DKA_Definitions.\nClose Scope A_scope.\n\n(* BinPos *)\nRequire Import BinNums BinPos.\n\n\n\n(****************************************************************)\n(* Interface with RelationAlgebra                               *)\n(****************************************************************)\n\nSection Compile.\n\nVariables\n  (r: regex)\n  (alphabet: seq DWORD).\n\nDefinition dfa_r: DFA.t := X_to_DFA r.\n\nLemma dfa_br: DFA.bounded dfa_r.\nProof.\n  apply X_to_DFA_bounded.\nQed.\n\n(*Coercion Pos.to_nat : positive >-> nat.*)\n(*Coercion Pos.of_nat : nat >-> positive.*)\n\nNotation char := positive.\n\nDefinition char_of_DWORD (n: DWORD) : char := Pos.of_nat (toNat n).\nDefinition DWORD_of_char (p: char): DWORD := #((Pos.to_nat p)).\n\n(*\nLemma char_of_DWORDK (c: DWORD):\n  c \\in alphabet -> DWORD_of_char (char_of_DWORD c) = c.\nProof.\n  move=> H; apply alphabet_char in H.\n  rewrite /char_of_DWORD/DWORD_of_char.\n  rewrite (Pnat.Nat2Pos.id);\n    first by apply  toNatK.\n  set x := toNat c.\n  rewrite -(toNat_fromNat0 32).\n  rewrite /x {x}.\n  rewrite /not=> H'.\n  apply  toNat_inj in H'.\n  apply H.\n  assumption.\nQed.\n*)\n\n(*\nCoercion char_of_DWORD : DWORD >-> char.\nCoercion DWORD_of_char : char >-> DWORD.\n*)\n\nDefinition dfa_size: nat := (Pos.to_nat (DFA.size dfa_r)).-1.\n\nNotation state := positive.\n\n\nLemma ord_of_belongHelp (s: state): DFA.belong s dfa_r -> (Pos.to_nat s).-1 < dfa_size.\nProof.\n  move=> H.\n  apply/ltP.\n  rewrite /dfa_size.\n  apply Lt.lt_pred.\n  rewrite prednK;\n    last by apply/ltP;\n            apply Pnat.Pos2Nat.is_pos.\n  rewrite -Pnat.Pos2Nat.inj_lt.\n  exact: H.\nQed.\n\nDefinition ord_of_belong (s: state)(H: DFA.belong s dfa_r): 'I_dfa_size :=\n  Ordinal (ord_of_belongHelp s H).\n\nLemma ord_of_belongK: forall s q, state_of_nat (nat_of_ord (ord_of_belong s q)) = s.\nProof.\n  move=> s q.\n  rewrite /ord_of_belong/=/state_of_nat.\n  rewrite Pos.of_nat_succ prednK;\n    last by apply/ltP;\n            apply Pnat.Pos2Nat.is_pos.\n  by rewrite Pnat.Pos2Nat.id.\nQed.\n\nDefinition DFA_init: 'I_dfa_size := ord_of_belong (DFA.initial dfa_r) (DFA.bounded_initial dfa_br).\n\nDefinition accept (s: 'I_dfa_size): bool := StateSet.mem s (DFA.finaux dfa_r).\n\nDefinition trans (s: 'I_dfa_size)(v: DWORD): 'I_dfa_size :=\n  ord_of_belong (DFA.delta dfa_r (Pos.of_nat (toNat v) (* this is safe because v <> #0 *)) s)\n                (DFA.bounded_delta dfa_br _ _).\n\nDefinition lang' (s: 'I_dfa_size)(w: seq DWORD): bool :=\n  lang alphabet accept trans s w.\n\n\n\nLemma in_mem t s : StateSet.mem t s <-> StateSet.In t s.\nProof.\n  split; [apply StateSet.mem_1 | apply StateSet.mem_2].\nQed.\n\nLemma equiv_read_lang\n      (w: seq DWORD)\n      (s: state)(q: DFA.belong s dfa_r) :\n   StateSet.mem\n     (DKA_DFA_Language.read dfa_r [seq char_of_DWORD c | c <- w] s)\n     (DFA.finaux dfa_r) /\\ (all (fun a => a \\in alphabet) w)\n   <-> lang' (ord_of_belong s q) w.\nProof.\n  elim: w s q=> [s q|a w IH s q].\n  * (* CASE: w ~ [::] *)\n    rewrite /map/lang'/lang/accept/DKA_DFA_Language.read /=.\n    rewrite /statesetelt_of_nat/state_of_nat.\n    rewrite Pos.of_nat_succ.\n    rewrite prednK;\n         last by apply/ltP;\n                 apply Pnat.Pos2Nat.is_pos.\n    rewrite Pnat.Pos2Nat.id.\n    by split; [ move=> [a _]; assumption\n              | move=> a; split; assumption || done].\n\n  * (* CASE: w ~ i :: a *)\n    rewrite [map _ (_ :: _)]/=.\n    rewrite /lang' [lang _ _ _ _ (_ :: _)]/=.\n    rewrite [DKA_DFA_Language.read _ (_ :: _) _]/=.\n    rewrite [all _ (_ :: _)]/=.\n\n    rewrite [(trans (ord_of_belong s q) a)]/trans.\n    rewrite ord_of_belongK.\n    rewrite /char_of_DWORD.\n\n    split.\n\n    - (* CASE: read -> lang *)\n      move=> [HMem /andP [a_in_alphabet all_in_w]].\n      apply/andP; split; first by assumption.\n\n      move: IH=> /(_ (DFA.delta dfa_r (char_of_DWORD a) s)\n                  (DFA.bounded_delta dfa_br (char_of_DWORD a) s)) IH.\n\n      by apply IH; split; by assumption.\n\n    - (* CASE: lang -> read *)\n      move=> /andP [a_in_alpha in_lang].\n\n      apply IH in in_lang.\n      move: in_lang=> [in_mem all_in_w].\n\n      by split; try (apply/andP; split); assumption.\nQed.\n\nLemma lang_in_alphabet (s: 'I_dfa_size)(w: seq DWORD):\n  lang' s w -> all (fun a => a \\in alphabet) w.\nProof.\n  elim: w s=> [_ _|a w IH s H] //=.\n  rewrite [lang' _ (_ :: _)]/= in H.\n  move/andP: H=> [a_in_alphabet lang_w].\n  apply/andP; split; first by assumption.\n  move: IH=> /(_ (trans s a) lang_w).\n  done.\nQed.\n\nVariable\n  (alphabet_compat:\n     forall c, c \\in alphabet ->\n                     below (char_of_DWORD c) (DFA.max_label dfa_r)).\n\nLemma lang_is_bounded (w: seq DWORD):\n  lang' DFA_init w -> DKA_DFA_Language.bounded_word dfa_r [seq char_of_DWORD c | c <- w].\nProof.\n  rewrite /DKA_DFA_Language.bounded_word.\n  move=> w_in_lang c c_in_w.\n  have w_in_alphabet: all (fun a => a \\in alphabet) w\n    by apply lang_in_alphabet with DFA_init;\n       assumption.\n  clear w_in_lang.\n  elim: w w_in_alphabet c_in_w=> [_ _|a w IH w_in_alphabet c_in_w]//=.\n\n  rewrite [map _ (_ :: _)]/= in c_in_w.\n  rewrite [List.In _ (_ :: _)]/= in c_in_w.\n\n  rewrite [all _ (_ :: _)]/= in w_in_alphabet.\n  move: w_in_alphabet=> /andP [a_in_alphabet w_in_alphabet].\n  move: c_in_w=> [<- | c_in_w].\n\n  * (* CASE: below (char_of_DWORD a) (DFA.max_label dfa_r)\n             with a \\in alphabet *)\n    apply: alphabet_compat.\n    by done.\n\n  * (* CASE: below c (DFA.max_label dfa_r)\n             with c \\in w *)\n    move: IH=> /(_ w_in_alphabet c_in_w).\n    by done.\nQed.\n\nLemma equiv_DFA_language\n      (w: seq DWORD) :\n  DKA_DFA_Language.DFA_language dfa_r [seq char_of_DWORD c | c <- w] /\\ (all (fun a => a \\in alphabet) w)\n  <-> lang' DFA_init w.\nProof.\n  rewrite /DKA_DFA_Language.DFA_language.\n  split.\n    * (* CASE: read -> lang *)\n      move=> [[read _] bounded].\n      rewrite /DFA_init.\n      rewrite -(equiv_read_lang w (DFA.initial dfa_r) ((DFA.bounded_initial dfa_br))).\n      rewrite in_mem.\n      by split; assumption.\n\n    * (* CASE: lang -> read *)\n      move=> inLang.\n      rewrite -in_mem and_assoc\n              [_ /\\ all _ _]and_comm -and_assoc.\n      split;\n        first by rewrite (equiv_read_lang w (DFA.initial dfa_r) ((DFA.bounded_initial dfa_br)));\n                 assumption.\n      by apply lang_is_bounded; assumption.\nQed.\n\n\nLemma test: (DKA_DFA_Language.DFA_language (X_to_DFA r) ==\n            DKA_DFA_Language.regex_language r)%A.\napply equal_trans with (DKA_DFA_Language.regex_language (DFA.eval (X_to_DFA r))); last first.\napply DKA_DFA_Language.regex_language_graph_functor.\napply X_to_DFA_correct.\nrewrite DKA_DFA_Language.language_DFA_eval.\nreflexivity.\nexact: dfa_br.\nQed.\n\nLemma compiler_correct (w: seq DWORD):\n      lang' DFA_init w <->\n         DKA_DFA_Language.regex_language r (map char_of_DWORD w)\n      /\\ (all (fun a => a \\in alphabet) w).\nProof.\n  rewrite -(test (map char_of_DWORD w)).\n  rewrite /dfa_r.\n  rewrite -equiv_DFA_language.\n  done.\nQed.\n\n\nDefinition X_to_x86 (acc rej: DWORD): program :=\n  compiler acc rej DFA_init alphabet accept trans.\n\nEnd Compile.\n\n(*\nDefinition X_to_x86\n             (r: regex)\n             (acc rej: DWORD): program :=\n  DFA_to_x86 (X_to_DFA r) acc rej.\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/lib/regexp/interfaceATBR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2941185807760946}}
{"text": "\nRequire Import Axioms.\nRequire Import Tactics.\nRequire Import Sigma.\nRequire Import Equality.\nRequire Import Relation.\nRequire Import Syntax.\nRequire Import Ofe.\nRequire Import Uniform.\nRequire Import Spaces.\nRequire Import Dynamic.\nRequire Import Hygiene.\nRequire Import Equivalence.\nRequire Import Intensional.\nRequire Import Ordinal.\nRequire Import Candidate.\nRequire Import System.\nRequire Import MapTerm.\nRequire Import Extend.\nRequire Import Model.\nRequire Import Standard.\nRequire Import Truncate.\nRequire Import Equivalences.\nRequire Import Ceiling.\nRequire Import SemanticsProperty.\n\n\nDefinition eqtype_property w (R R' : wiurel w) : nat -> Prop\n  :=\n  fun j => iutruncate (S j) R = iutruncate (S j) R'.\n\n\nLemma eqtype_property_downward :\n  forall w R R' j,\n    eqtype_property w R R' (S j)\n    -> eqtype_property w R R' j.\nProof.\nunfold eqtype_property.\nintros w R R' j Heq.\nso (f_equal (iutruncate (S j)) Heq) as Heq'.\nrewrite -> !iutruncate_combine_le in Heq'; auto.\nQed.\n\n\nDefinition eqtype_urel w i (R R' : wiurel w) : wurel w :=\n  property_urel (eqtype_property w R R') w i (eqtype_property_downward w R R').\n\n\nDefinition iueqtype w i (R R' : wiurel w) : wiurel w\n  :=\n  (eqtype_urel w i R R',\n   meta_pair\n     (meta_iurel R)\n     (meta_iurel R')).\n\n\nLemma iueqtype_inj :\n  forall w i R1 R1' R2 R2',\n    iueqtype w i R1 R2 = iueqtype w i R1' R2'\n    -> R1 = R1' /\\ R2 = R2'.\nProof.\nintros w i R1 R1' R2 R2' Heq.\nso (f_equal snd Heq) as Heq'.\ncbn in Heq'.\nso (meta_pair_inj _#5 Heq') as (Heq1 & Heq2).\nsplit.\n  {\n  eapply meta_iurel_inj; eauto.\n  }\n\n  {\n  eapply meta_iurel_inj; 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/SemanticsEqtype.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.29411858077609454}}
{"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.\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 Coq.Structures.Equalities.\nRequire Import Coq.Logic.Eqdep.\nImport ListNotations.\n\nModule Hoare_Test_FstShadow <: IdModType.\n\nModule FstShadow := THoare IdModP.\nExport FstShadow.\n\nDefinition Id := FstShadow.Id.\nDefinition IdEqDec := FstShadow.IdEqDec.\nDefinition IdEq := FstShadow.IdEq.\nDefinition W := FstShadow.W.\nDefinition Loc_PI := FstShadow.Loc_PI.\nDefinition BInit := FstShadow.BInit.\nDefinition WP := FstShadow.WP.\n\n(**************************************************)\n\n(****** Hoare logic *)\n\nNotation \"{{ P }} fenv >> env >> e {{ Q }}\" := (THoareTriple_Eval P Q fenv env e ) \n(at level 90) : state_scope.\n\nOpen Scope state_scope.\n\n\n\nDefinition wp (P : Value -> W -> Prop) (fenv: funEnv) (env: valEnv) (e : Exp) :\n  W -> Prop := fun s => forall (v:Value) (s': W),\nEClosure fenv env (Conf Exp s e) (Conf Exp s' (Val v)) -> P v s'.\n\nLemma wpIsPrecondition (P : Value -> W -> Prop) (fenv: funEnv) (env: valEnv) (e : Exp) :\n  {{ wp P fenv env e }} fenv >> env >> e {{ P }}.\nProof.\nunfold THoareTriple_Eval.\nintros ftenv tenv k1 k2 t k3 s s' v H1 H2.\nunfold wp in H2.\neapply H2.\nauto.\nQed.\n\nLemma weakenEval (P Q : W -> Prop) (R : Value -> W -> Prop) (fenv: funEnv) (env: valEnv) (e : Exp) :\n  {{ Q }} fenv >> env >> e {{ R }} -> (forall s, P s -> Q s) -> {{ P }} fenv >> env >> e {{ R }}.\nProof.\nintros.\nunfold THoareTriple_Eval in *.\nintros.\neapply H;\neauto.\nQed.\n\nDefinition wpPrms (P : list Value -> W -> Prop) (fenv: funEnv) (env: valEnv) (ps: Prms):\n  W -> Prop := fun s => forall (vs: list Value) (s': W),\nPrmsClosure fenv env (Conf Prms s ps) (Conf Prms s' (PS (map Val vs))) -> P vs s'.\n\nLemma wpIsPreconditionPrms (P : list Value -> W -> Prop) (fenv: funEnv) (env: valEnv) (ps: Prms):\n  THoarePrmsTriple_Eval (wpPrms P fenv env ps) P fenv env ps.\nProof.\nunfold THoarePrmsTriple_Eval.\nintros ftenv tenv k1 k2 t k3 s s' v H1 H2.\nunfold wpPrms in H2.\neapply H2.\nauto.\nQed.\n\nLemma weakenPrms (P Q : W -> Prop) (R : list Value -> W -> Prop) (fenv: funEnv) (env: valEnv) (ps: Prms):\n  THoarePrmsTriple_Eval Q R fenv env ps ->\n (forall s, P s -> Q s) -> THoarePrmsTriple_Eval P R fenv env ps .\nProof.\nintros.\nunfold THoarePrmsTriple_Eval in *.\nintros.\neapply H;\neauto.\nQed.\n\n(******* Program *)\n\n(** getSh1idx : returns first shadow *)\n\nDefinition getSh1idx : Exp := Val (cst index sh1idx). (** Return in the original definition *)\n\n(** ReadPhysical -page -index : reads physical address *)\n\nDefinition xf_read (p: page) : XFun (option index) (option page) := {|\n   b_mod := fun s oi => (s,match oi with |None => None |Some i => readPhysicalInternal p i (memory s) end)\n|}.\n\nInstance VT_index : ValTyp index.\nInstance VT_option_index : ValTyp (option index).\nInstance VT_option_page : ValTyp (option page).\n\nDefinition ReadPhysical (p:page) (x:Id) : Exp :=\n  Modify (option index) (option page) VT_option_index VT_option_page (xf_read p) (Var x).  \n\n(** Succ -index : calculates the successor of an index *)                 \n\nDefinition xf_succ : XFun index (option index) := {|\n   b_mod := fun s (idx:index) =>  (s, succIndexInternal idx)\n|}.\n\nDefinition Succ (x:Id) : Exp :=\n  Modify index (option index) VT_index VT_option_index xf_succ (Var x).\n\n(** getFstShadow -page : returns the adress of the 1st shadow *)\n\n(* Bind Approach *)\n\nDefinition getFstShadowBind (p:page) : Exp :=\n BindS \"x\" getSh1idx \n           (BindS \"y\" (Succ \"x\") \n                      (ReadPhysical p \"y\")\n           ).\n\n(* Apply Approch *)\n\nDefinition indexType := vtyp index. \nDefinition optionIndexType := vtyp (option index). \n\nDefinition ReadPhysicalQF (p:page) := QF \n(FC emptyE [(\"x\",optionIndexType)] (ReadPhysical p \"x\") (Val (cst (option page) None)) \"ReadPhysical\" 0).\n\nDefinition SuccQF := QF \n(FC emptyE [(\"y\",indexType)] (Succ \"y\") (Val (cst (option index) None)) \"Succ\" 0).\n\nDefinition getFstShadowApply (p:page) :Exp :=\nApply (ReadPhysicalQF p) (PS [\n                         Apply SuccQF (PS [getSh1idx])\n                      ]). \n\n\n(*Bind approach & Deep definition of Successor*) \n\nInstance VT_nat : ValTyp nat.\nInstance VT_bool : ValTyp bool.\n\nDefinition xf_LtDec (n: nat) : XFun nat bool := {|\n   b_mod := fun s i => (s,if lt_dec i n then true else false)\n|}.\n\nDefinition LtDec (x:Id) (n:nat): Exp :=\n  Modify nat bool VT_nat VT_bool (xf_LtDec n) (Var x). \n\nDefinition xf_prj1 : XFun index nat := {|\n   b_mod := fun s (idx:index) => (s,let (i,_) := idx in i)\n|}.\n\nDefinition prj1 (x:Id) : Exp :=\n  Modify index nat VT_index VT_nat xf_prj1 (Var x).  \n\nDefinition xf_SomeCindex : XFun nat (option index) := {|\n   b_mod := fun s i => (s,Some (CIndex i))\n|}.\n\nDefinition SomeCindex (x:Id) : Exp :=\n  Modify nat (option index) VT_nat VT_option_index  xf_SomeCindex (Var x).\n\nDefinition SomeCindexQF := QF \n(FC emptyE [(\"i\",Nat)] (SomeCindex \"i\") (Val (cst (option index) None)) \"SomeCindex\" 0).\n\nDefinition xf_SuccD : XFun nat nat := {|\n   b_mod := fun s i => (s,S i)\n|}.\n\nDefinition SuccR (x:Id) : Exp :=\n  Modify nat nat VT_nat VT_nat xf_SuccD (Var x).\n\n\nDefinition SuccD (x:Id) :Exp :=\nBindS \"i\" (prj1 x) \n          (IfThenElse (LtDec \"i\" tableSize) \n                      (Apply SomeCindexQF\n                             (PS[SuccR \"i\"])\n                      ) \n                      (Val(cst (option index) None))\n          ).\n\n\nDefinition getFstShadowBindDeep (p:page) : Exp :=\n BindS \"x\" getSh1idx \n           (BindS \"y\" (SuccD \"x\") \n                      (ReadPhysical p \"y\")\n           ).\n\n(*Bind approach & Deep definition of Succ with recursive plus function*) \n\n\nDefinition plusR' (f: Id) (x:Id) : Exp :=\n      Apply (FVar f) (PS [VLift (Var x)]). \n\nDefinition plusR (n:nat) := QF \n(FC emptyE [(\"i\",Nat)] (VLift(Var \"i\")) (BindS \"p\" (plusR' \"plusR\" \"i\") (SuccR \"p\")) \"plusR\" n).\n\nDefinition SuccRec (x:Id) :Exp :=\nBindS \"i\" (prj1 x) \n          (IfThenElse (LtDec \"i\" tableSize) \n                      (Apply SomeCindexQF \n                             (PS[Apply (plusR 1) \n                                       (PS[VLift(Var \"i\")])\n                                ])\n                      ) \n                      (Val(cst (option index) None))\n          ).\n\n\nDefinition getFstShadowBindDeepRec (p:page) : Exp :=\n BindS \"x\" getSh1idx \n           (BindS \"y\" (SuccRec \"x\") \n                      (ReadPhysical p \"y\")\n           ).\n\n\n(******* State properties *)\n\nDefinition isVA (p:page) (i:index) (s:W): Prop := match (lookup p i (s.(memory)) beqPage beqIndex) with \n             |Some (VA _) => True\n             |_ => False\n             end.\n\nDefinition nextEntryIsPP (p:page) (idx:index) (p':Value) (s:W) : Prop:= \nmatch succIndexInternal idx with \n| Some i => match lookup p i (memory s) beqPage beqIndex with \n                  | Some (PP table) => p' = cst (option page) (Some table)\n                  |_ => False \n                  end\n| _ => False \nend.\n\nDefinition partitionDescriptorEntry (s:W) := \nforall (p : page),  \n  In p (getPartitions multiplexer s) -> forall (idx : index), \n    (idx = PDidx \\/ idx = sh1idx \\/ idx = sh2idx \\/ idx = sh3idx \\/ idx = PPRidx  \\/ idx = PRidx ) ->\n    idx < tableSize - 1  /\\ isVA p idx  s /\\ exists (p1:page) , nextEntryIsPP p idx (cst (option page) (Some p1)) s  /\\  \n    (cst page p1) <> (cst page defaultPage).\n\n\n(******* Useful Lemmas *)\n\n(** about getSh1idx *)\n\nLemma getSh1idxW (P: Value -> W -> Prop) (fenv: funEnv) (env: valEnv) :\n  {{wp P fenv env getSh1idx}} fenv >> env >> getSh1idx {{P}}.\nProof.\napply wpIsPrecondition.\nQed.\n\nLemma getSh1idxWp P fenv env :\n{{P}} fenv >> env >> getSh1idx \n{{fun (idxSh1 : Value) (s : state) => P s  /\\ idxSh1 = cst index sh1idx }}.\nProof.\neapply weakenEval.\neapply getSh1idxW.\nintros. \nunfold wp.\nintros.\nunfold getSh1idx in X.\ninversion X;subst.\nauto.\ninversion X0.\nQed.\n\nLemma getSh1idxWp' P fenv env :\nHoarePrmsTriple_Eval P \n(fun (idxSh1 : list Value) (s : state) => P s  /\\ idxSh1 = [cst index sh1idx]) fenv env [getSh1idx].\nProof.\nunfold HoarePrmsTriple_Eval.\nintros.\ninversion X;subst.\nintuition.\nunfold map in H5.\ninduction vs.\ninversion X;subst.\ninversion X0;subst.\ninversion X2.\ninversion X2.\ninversion H5;subst.\nsimpl in *.\ndestruct vs.\nauto.\ninversion H2.\ninversion X0;subst.\ninversion X2.\ninversion X2.\nQed.\n\n(** about Succ *)\n\nLemma succW  (x : Id) (P: Value -> W -> Prop) (v:Value) (fenv: funEnv) (env: valEnv) :\nforall (idx:index), {{fun s => idx < (tableSize -1) /\\ forall  l : idx + 1 < tableSize , \n    P (cst (option index) (succIndexInternal idx)) s /\\ v = cst index idx }}  \nfenv >> (x,v)::env >> Succ x {{ P }}.\nProof.\nintros.\nunfold THoareTriple_Eval.\nintros.\nintuition.\ndestruct H1 as [H1 H1'].\nomega.\ninversion X;subst.\ninversion X0;subst.\nrepeat apply inj_pair2 in H7;subst.\ninversion X2;subst.\ninversion X3;subst.\ninversion H;subst.\ndestruct IdModP.IdEqDec in H3.\ninversion H3;subst.\nclear H3 e X3 H XF1.\ninversion X1;subst.\ninversion X3;subst.\nrepeat apply inj_pair2 in H7.\nrepeat apply inj_pair2 in H9.\nsubst.\nunfold b_exec,b_eval,xf_succ,b_mod in *.\nsimpl in *.\ninversion X4;subst.\napply H1.\ninversion X5.\ninversion X5.\ncontradiction.\nQed.\n\nLemma succWp (x:Id) (v:Value) P (fenv: funEnv) (env: valEnv) :\nforall (idx:index), {{fun s => P s  /\\ idx < tableSize - 1 /\\ v=cst index idx}} fenv >> (x,v)::env >> Succ x \n{{fun (idxsuc : Value) (s : state) => P s  /\\ idxsuc = cst (option index) (succIndexInternal idx) /\\ exists i, idxsuc = cst (option index) (Some i)}}.\nProof.\nintros.\neapply weakenEval.\neapply succW.\nintros.\nsimpl.\nsplit.\ninstantiate (1:=idx).  \nintuition.\nintros.\nintuition.\ndestruct idx.\nexists (CIndex (i + 1)).\nf_equal.\nunfold succIndexInternal.\ncase_eq (lt_dec i tableSize).\nintros.\nauto.\nintros.\ncontradiction.\nQed.\n\nLemma succDW  (x : Id) (P: Value -> W -> Prop) (v:Value) (fenv: funEnv) (env: valEnv) :\nforall (idx:index), {{fun s => idx < (tableSize -1) /\\ forall  l : idx + 1 < tableSize , \n    P (cst (option index) (succIndexInternal idx)) s /\\ v = cst index idx }}  \nfenv >> (x,v)::env >> SuccD x {{ P }}.\nProof.\nintros.\nunfold THoareTriple_Eval.\nintros.\nclear k3 t k2 k1 tenv ftenv.\nintuition.\ndestruct H1 as [H1 H1'].\nomega.\ninversion X;subst.\ninversion X0;subst.\ninversion X2;subst.\nrepeat apply inj_pair2 in H7;subst.\ninversion X3;subst.\ninversion X4;subst.\ninversion H;subst.\ndestruct IdModP.IdEqDec in H3.\ninversion H3;subst.\nclear H3 e X4 H XF1.\ninversion X1;subst.\ninversion X4;subst.\ninversion X6;subst.\nrepeat apply inj_pair2 in H7.\nrepeat apply inj_pair2 in H9.\nsubst.\nunfold xf_prj1 at 3 in X6.\nunfold b_exec,b_eval,b_mod in *.\nsimpl in *.\ndestruct idx.\ninversion X5;subst.\ninversion X7;subst.\ninversion X8;subst.\ninversion X9;subst.\nsimpl in *.\ninversion X11;subst.\ninversion X12;subst.\nrepeat apply inj_pair2 in H7.\nsubst.\ninversion X13;subst.\ninversion X14;subst.\ninversion H;subst.\nclear H X14 XF2.\ninversion X10;subst.\ninversion X14;subst.\nsimpl in *.\ninversion X16;subst.\ninversion X17;subst.\nrepeat apply inj_pair2 in H7.\nrepeat apply inj_pair2 in H10.\nsubst.\nunfold xf_LtDec at 3 in X17.\nunfold b_exec,b_eval,b_mod in *.\nsimpl in *.\ncase_eq (lt_dec i tableSize).\nintros.\nrewrite H in X17, H1.\ninversion X15;subst.\ninversion X18;subst.\nsimpl in *.\ninversion X20; subst.\ninversion X19;subst.\ninversion X21;subst.\nsimpl in *.\ninversion X23;subst.\ninversion H10;subst.\ndestruct vs.\ninversion H2.\ninversion H2.\ninversion X24;subst.\ninversion X25;subst.\nrepeat apply inj_pair2 in H11.\nsubst.\ninversion X26;subst.\ninversion X27;subst.\ninversion H2;subst.\nclear X27 H2 XF3.\ninversion X22;subst.\ninversion X27;subst.\nsimpl in *.\ninversion X29;subst.\ninversion H10;subst.\ndestruct vs.\ninversion H2.\ninversion H2.\ninversion X30;subst.\ninversion X31;subst.\nrepeat apply inj_pair2 in H11.\nrepeat apply inj_pair2 in H13.\nsubst.\nunfold xf_SuccD at 3 in X31.\nunfold b_exec,b_eval,xf_SuccD,b_mod in *.\nsimpl in *.\ninversion X28;subst.\ninversion X32;subst.\nsimpl in *.\ninversion X34;subst.\ninversion H10;subst.\ndestruct vs.\ninversion H2.\ninversion H2;subst.\ndestruct vs.\nunfold mkVEnv in *.\nsimpl in *.\ninversion X33;subst.\ninversion X35;subst.\ninversion X37;subst.\nsimpl in *.\ninversion X38;subst.\nrepeat apply inj_pair2 in H15.\nsubst.\ninversion X39;subst.\ninversion X40;subst.\ninversion H3;subst.\nclear X40 H3 XF4 H5.\ninversion X36;subst.\ninversion X40;subst.\ninversion X42;subst.\nsimpl in *.\ninversion X43;subst.\nrepeat apply inj_pair2 in H14.\nrepeat apply inj_pair2 in H16.\nsubst.\nunfold xf_SomeCindex at 3 in X43.\nunfold b_exec,b_eval,b_mod in *.\nsimpl in *.\ninversion X41;subst.\ninversion X44;subst.\nsimpl in *.\ninversion X46;subst.\ninversion X45;subst.\ninversion X47;subst.\ninversion X48;subst.\nassert (Z : S i = i+1). \nomega.\nrewrite Z.\nauto.\ninversion X49.\ninversion X49.\ninversion X47.\ninversion X44.\ninversion H5.\ninversion X35;subst.\ninversion X36.\ninversion X36.\ninversion X35.\ninversion X32.\ninversion X30.\ninversion X24.\nrepeat apply inj_pair2 in H6.\nrewrite H in H6.\ninversion H6.\nrewrite H in X21.\ninversion X21.\nintros.\ncontradiction.\ninversion X18.\ninversion X9.\ninversion X7.\ncontradiction.\nQed.\n\nLemma succDWp (x:Id) (v:Value) P (fenv: funEnv) (env: valEnv) :\nforall (idx:index), {{fun s => P s  /\\ idx < tableSize - 1 /\\ v=cst index idx}} fenv >> (x,v)::env >> SuccD x \n{{fun (idxsuc : Value) (s : state) => P s  /\\ idxsuc = cst (option index) (succIndexInternal idx) /\\ exists i, idxsuc = cst (option index) (Some i)}}.\nProof.\nintros.\neapply weakenEval.\neapply succDW.\nintros.\nsimpl.\nsplit.\ninstantiate (1:=idx).  \nintuition.\nintros.\nintuition.\ndestruct idx.\nexists (CIndex (i + 1)).\nf_equal.\nunfold succIndexInternal.\ncase_eq (lt_dec i tableSize).\nintros.\nauto.\nintros.\ncontradiction.\nQed.\n\n\nLemma succRecW  (x : Id) (P: Value -> W -> Prop) (v:Value) (fenv: funEnv) (env: valEnv) :\nforall (idx:index), {{fun s => idx < (tableSize -1) /\\ forall  l : idx + 1 < tableSize , \n    P (cst (option index) (succIndexInternal idx)) s /\\ v = cst index idx }}  \nfenv >> (x,v)::env >> SuccRec x {{ P }}.\nProof.\nintros.\ndestruct idx.\nsimpl.\nunfold SuccRec.\neapply BindS_VHTT1.\n(** prj1 *)\nunfold THoareTriple_Eval.\nintros.\ninstantiate (1:= fun v0 s => {| i := i; Hi := Hi |} < (tableSize -1) /\\ forall  l : {| i := i; Hi := Hi |} + 1 < tableSize , \n    P (cst (option index) (succIndexInternal {| i := i; Hi := Hi |})) s /\\ v = cst index {| i := i; Hi := Hi |}\n            /\\ v0 = cst nat i).\ndestruct H.\ndestruct H0.\nomega.\nsubst.\ninversion X;subst.\ninversion X0;subst.\nrepeat apply inj_pair2 in H7.\ninversion X2;subst.\ninversion X3;subst.\ninversion H1;subst.\ncase_eq (IdModP.IdEqDec x x);intros; try contradiction.\nrewrite H2 in H3.\ninversion H3;subst.\ninversion X1;subst.\ninversion X4;subst.\nrepeat apply inj_pair2 in H10.\nrepeat apply inj_pair2 in H12.\nsubst.\nunfold b_eval, b_exec, xf_prj1, b_mod in *.\nsimpl in *.\ninversion X5;subst.\nintuition.\ninversion X6.\ninversion X6.\nintros; simpl.\neapply IfTheElse_VHTT1.\n(** LtDec *)\nunfold THoareTriple_Eval.\nintros.\ninstantiate (1:= fun v1 s => {| i := i; Hi := Hi |} < (tableSize -1) \n            /\\ forall  l : {| i := i; Hi := Hi |} + 1 < tableSize , \n                 P (cst (option index) (succIndexInternal {| i := i; Hi := Hi |})) s \n            /\\ v = cst index {| i := i; Hi := Hi |}\n            /\\ v0 = cst nat i \n            /\\ v1 = cst bool (if lt_dec i tableSize then true else false)).\nsimpl.\nsplit.\nintuition.\nintros.\ndestruct H.\ndestruct H0.\nomega.\ndestruct H1.\nsubst.\ninversion X;subst.\ninversion X0;subst.\nrepeat apply inj_pair2 in H7.\nsubst.\ninversion X2;subst.\ninversion X3;subst.\ninversion H1;subst.\nclear X3 H1 XF1 k3 k2 k1 t ftenv tenv.\ninversion X1;subst.\ninversion X3;subst.\nrepeat apply inj_pair2 in H7.\nrepeat apply inj_pair2 in H9.\nsubst.\nunfold b_eval, b_exec, xf_LtDec, b_mod in *.\nsimpl in *.\ninversion X4;subst.\nintuition.\ninversion X5.\ninversion X5.\nsimpl.\neapply Apply_VHTT1.\neapply Prms_VHTT1.\neapply Apply_VHTT1.\neapply Prms_VHTT1.\n(* Var i *)\ninstantiate (1:= fun v1 s => {| i := i; Hi := Hi |} < (tableSize -1) \n            /\\ forall  l : {| i := i; Hi := Hi |} + 1 < tableSize , \n                 P (cst (option index) (succIndexInternal {| i := i; Hi := Hi |})) s \n            /\\ v = cst index {| i := i; Hi := Hi |}\n            /\\ v0 = cst nat i \n            /\\ v1 = v0).\nunfold THoareTriple_Eval.\nintros.\ndestruct H.\nsplit.\nintuition.\nintros.\ndestruct H0.\nomega.\ndestruct H1.\ndestruct H2.\nsubst.\ninversion X;subst.\ninversion X0;subst.\ninversion X2;subst.\ninversion X3;subst.\ninversion H1;subst.\ninversion X1;subst.\ninversion X4;subst.\ninversion X5;subst.\nintuition.\ninversion X6.\ninversion X6.\nintros.\nsimpl.\n(** PS *)\nunfold THoarePrmsTriple_Eval.\nintros.\ndestruct H.\ndestruct H0.\nomega.\ndestruct H1.\ndestruct H2.\nsubst.\ncase_eq (lt_dec i tableSize); intros; try contradiction.\nrewrite H1 in H0.\nclear H1 l.\ninversion X;subst.\ndestruct vs; inversion H6.\ninversion X;subst.\ninstantiate (1:= fun vs s => {| i := i; Hi := Hi |} < (tableSize -1) \n            /\\ forall  l : {| i := i; Hi := Hi |} + 1 < tableSize , \n                 P (cst (option index) (Some (CIndex (i + 1)))) s \n            /\\ v = cst index {| i := i; Hi := Hi |}\n            /\\ v0 = cst nat i \n            /\\ vs = [cst nat i]).\nsimpl; intuition.\ninversion X0.\ninversion X0.\nintuition.\nunfold mkVEnv;simpl.\ndestruct vs.\nunfold THoareTriple_Eval.\nintros.\nintuition.\ndestruct H1.\nomega.\nintuition.\ninversion H4.\neapply BindS_VHTT1.\n(** plus R' *)\nunfold THoareTriple_Eval.\nintros.\nintuition.\ndestruct H1.\nomega.\nintuition.\ninversion H4;subst.\nclear H4 k3 k2 k1 t tenv ftenv.\ninversion X;subst.\ninversion X0;subst.\ninversion X2;subst.\ninversion X3;subst.\ninversion H1;subst.\ninversion X1;subst.\ninversion X4;subst.\ninversion H12;subst.\ndestruct vs.\ninversion H2.\ninversion H2.\ninversion X6;subst.\ninversion X7;subst.\ninversion X8;subst.\ninversion X9;subst.\ninversion H2;subst.\nclear H1 H2 X3 X9.\ninversion X5;subst.\ninversion X3;subst.\ninversion H11;subst.\ndestruct vs.\ninversion H1.\ninversion H1.\ninversion X10;subst.\ninversion X11;subst.\ninversion X9;subst.\ninversion X12;subst.\ninversion H11;subst.\ndestruct vs.\ninversion H1.\ninversion H1;subst.\ndestruct vs; inversion H4.\nclear H4 H11 H12 H1.\ninversion X13;subst.\ninversion X14;subst.\nunfold mkVEnv in *; simpl in *.\ninversion X16;subst.\ninversion X17;subst.\ninversion X18;subst.\ninversion H1;subst.\nclear X18 H1.\ninversion X5;subst.\ninversion X18;subst.\ninversion H11;subst.\ndestruct vs.\ninversion H1.\ninversion H1.\ninversion X20;subst.\ninversion X21;subst.\ninversion X19;subst.\ninversion X22;subst.\ninversion H11;subst.\ndestruct vs.\ninversion H1.\ninversion H1;subst.\ndestruct vs; inversion H4.\nclear H4 H11 H12 H1.\nunfold mkVEnv in *; simpl in *.\ninversion X23;subst.\ninversion X24;subst.\ninversion X26;subst.\ninversion X27;subst.\ninversion X28;subst.\nsimpl in *.\ninversion H1;subst.\nclear H1 X28.\ninversion X27;subst.\ninversion X25;subst.\ninversion X29;subst.\ninversion X31;subst.\ninversion X30;subst.\ninversion X32;subst.\ninversion X33;subst.\nclear X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 \n      X11 X12 X13 X14 X15 X16 X17 X18 X19 X20 \n      X21 X22 X23 X24 X25 X26 X27 X28 X29 X30 \n      X31 X32 X33.\ninstantiate (1:= fun v2 s => {| i := i; Hi := Hi |} < (tableSize -1) \n            /\\ forall  l : {| i := i; Hi := Hi |} + 1 < tableSize , \n                 P (cst (option index) (Some (CIndex (i + 1)))) s \n            /\\ v = cst index {| i := i; Hi := Hi |}\n            /\\ v0 = cst nat i \n            /\\ v1 = cst nat i\n            /\\ vs = []\n            /\\ v2 = cst nat i).\nsimpl;intuition.\ninversion X34.\ninversion X34.\ninversion X32.\ninversion X24;subst.\ninversion X25.\ninversion X25.\ninversion X24.\ninversion X22.\ninversion X20.\ninversion X14;subst.\ninversion X15.\ninversion X15.\ninversion X14.\ninversion X12.\ninversion X10.\ninversion X6.\n(** SuccR *)\nintros;simpl.\nunfold THoareTriple_Eval.\nintros.\nclear k3 k2 k1 t tenv ftenv.\nintuition.\ndestruct H1.\nomega.\nintuition.\nsubst.\ninversion X;subst.\ninversion X0;subst.\nrepeat apply inj_pair2 in H7.\nsubst.\ninversion X2;subst.\ninversion X3;subst.\ninversion H1;subst.\nclear X3 H1 XF1.\ninversion X1;subst.\ninversion X3;subst.\nrepeat apply inj_pair2 in H7.\nrepeat apply inj_pair2 in H9.\nsubst.\nunfold b_eval, b_exec, xf_SuccD, b_mod in *.\nsimpl in *.\ninversion X4;subst.\ninstantiate (1:= fun v3 s => {| i := i; Hi := Hi |} < (tableSize -1) \n            /\\ forall  l : {| i := i; Hi := Hi |} + 1 < tableSize , \n                 P (cst (option index) (Some (CIndex (i + 1)))) s \n            /\\ v = cst index {| i := i; Hi := Hi |}\n            /\\ v3 = cst nat (S i)).\nintuition.\ninversion X5.\ninversion X5.\nintros; simpl.\n(** PS *)\nunfold THoarePrmsTriple_Eval.\nintros.\ndestruct H.\ndestruct H0.\nomega.\ndestruct H1.\nsubst.\nclear k3 k2 k1 pt tenv ftenv.\ninversion X;subst.\ndestruct vs; inversion H6.\ninversion X;subst.\ninstantiate (1:= fun vs s => {| i := i; Hi := Hi |} < (tableSize -1) \n            /\\ forall  l : {| i := i; Hi := Hi |} + 1 < tableSize , \n                 P (cst (option index) (Some (CIndex (i + 1)))) s \n            /\\ v = cst index {| i := i; Hi := Hi |}\n            /\\ vs = [cst nat (S i)]).\nsimpl; intuition.\ninversion X0.\ninversion X0.\nintros; intuition.\nunfold mkVEnv in *.\nsimpl in *.\ndestruct vs.\nunfold THoareTriple_Eval.\nintros.\nintuition.\ndestruct H1.\nomega.\nintuition.\ninversion H3.\n(** SomeCindex *)\nunfold THoareTriple_Eval.\nintros.\ndestruct H.\ndestruct H0.\nomega.\ndestruct H1.\ninversion H2;subst.\nclear H2 k3 k2 k1 t tenv ftenv.\ninversion X;subst.\ninversion X0;subst.\nrepeat apply inj_pair2 in H7.\nsubst.\ninversion X2;subst.\ninversion X3;subst.\ninversion H1;subst.\nclear X3 H1 XF1.\ninversion X1;subst.\ninversion X3;subst.\nrepeat apply inj_pair2 in H7.\nrepeat apply inj_pair2 in H9.\nsubst.\nunfold b_eval,b_exec,xf_SomeCindex,b_mod in *.\nsimpl in *.\ninversion X4;subst.\nassert (Succ_trivial : S i = i + 1) by omega.\nrewrite Succ_trivial.\nauto.\ninversion X5.\ninversion X5.\n(** impossible case *)\nunfold THoareTriple_Eval.\nintros.\nintuition.\ndestruct H1.\nomega.\nintuition.\ncase_eq (lt_dec i tableSize); intros; try contradiction.\nrewrite H3 in H4.\nunfold cst in H4.\napply inj_pair2 in H4.\ninversion H4.\nQed.\n\n(*Proof without Hoare Lemmas\n\nLemma succRecWByInversion  (x : Id) (P: Value -> W -> Prop) (v:Value) (fenv: funEnv) (env: valEnv) :\nforall (idx:index), {{fun s => idx < (tableSize -1) /\\ forall  l : idx + 1 < tableSize , \n    P (cst (option index) (succIndexInternal idx)) s /\\ v = cst index idx }}  \nfenv >> (x,v)::env >> SuccRec x {{ P }}.\nProof.\nintros.\nunfold THoareTriple_Eval.\nintros.\nclear k3 t k2 k1 tenv ftenv.\nintuition.\ndestruct H1 as [H1 H1'].\nomega.\ninversion X;subst.\ninversion X0;subst.\ninversion X2;subst.\nrepeat apply inj_pair2 in H7;subst.\ninversion X3;subst.\ninversion X4;subst.\ninversion H;subst.\ndestruct IdModP.IdEqDec in H3;try contradiction.\ninversion H3;subst.\nclear H3 e X4 H XF1.\ninversion X1;subst.\ninversion X4;subst.\ninversion X6;subst.\nrepeat apply inj_pair2 in H7.\nrepeat apply inj_pair2 in H9.\nsubst.\nunfold b_exec,b_eval,xf_prj1, b_mod in *.\nsimpl in *.\ndestruct idx.\ninversion X5;subst.\ninversion X7;subst.\ninversion X8;subst.\ninversion X9;subst.\nsimpl in *.\ninversion X11;subst.\ninversion X12;subst.\nrepeat apply inj_pair2 in H7.\nsubst.\ninversion X13;subst.\ninversion X14;subst.\ninversion H;subst.\nclear H X14 XF2.\ninversion X10;subst.\ninversion X14;subst.\nsimpl in *.\ninversion X16;subst.\ninversion X17;subst.\nrepeat apply inj_pair2 in H7.\nrepeat apply inj_pair2 in H10.\nsubst.\nunfold b_exec,b_eval,xf_LtDec,b_mod in *.\nsimpl in *.\ncase_eq (lt_dec i tableSize);intros; try contradiction.\nrewrite H in X17,H1.\ninversion X15;subst.\ninversion X18;subst.\nsimpl in *.\ninversion X20; subst.\nclear H6.\ninversion X19;subst.\ninversion X21;subst.\nsimpl in *.\ninversion X23;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2.\ninversion X24;subst.\ninversion X25;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2.\ninversion X26;subst.\ninversion X27;subst.\ninversion X28;subst.\ninversion X29;subst.\ninversion H2;subst.\nclear X29 H2.\ninversion X22;subst.\ninversion X29;subst.\ninversion X31;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2.\nsimpl in *.\ninversion X32;subst.\ninversion X33;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2.\nunfold mkVEnv in *.\nsimpl in *.\ninversion X34;subst.\ninversion X35;subst.\ninversion X30;subst.\ninversion X36;subst.\nsimpl in *.\ninversion X38;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2.\ninversion X39;subst.\ninversion X40;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2;subst.\ndestruct vs; inversion H5.\nunfold mkVEnv in *.\nsimpl in *.\nclear H5 H7 H17 H2.\ninversion X37;subst.\ninversion X41;subst.\ninversion X43;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2.\ninversion X44;subst.\ninversion X45;subst.\ninversion X46;subst.\nsimpl in *.\ninversion X47;subst.\ninversion X48;subst.\ninversion X49;subst.\ninversion H2;subst.\nclear X49 H2.\ninversion X42;subst.\ninversion X49;subst.\ninversion X51;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2.\ninversion X52;subst.\ninversion X53;subst.\ninversion X54;subst.\ninversion X55;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2.\nsimpl in *.\ninversion X56;subst.\ninversion X57;subst.\ninversion X58;subst.\ninversion X59;subst.\ninversion H2;subst.\nclear X59 H2.\ninversion X50;subst.\ninversion X59;subst.\ninversion X61;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2.\nsimpl in *.\ninversion X62;subst.\ninversion X63;subst.\nsimpl in *.\ninversion X64;subst.\ninversion X65;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2.\nsimpl in *.\ninversion X66;subst.\ninversion X67;subst.\ninversion X60;subst.\ninversion X68;subst.\ninversion X70;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2.\nsimpl in *.\ninversion X71;subst.\ninversion X72;subst.\ninversion X73;subst.\ninversion X74;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2;subst.\ndestruct vs; inversion H5.\nunfold mkVEnv in *.\nsimpl in *.\nclear H5 H7 H16 H2.\ninversion X69;subst.\ninversion X75;subst.\ninversion X77;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2.\ninversion X78;subst.\ninversion X79;subst.\ninversion X80;subst.\ninversion X81;subst.\nsimpl in *.\ninversion X60;subst.\ninversion X82;subst.\ninversion X84;subst.\ninversion X85;subst.\nsimpl in *.\ninversion X86;subst.\ninversion H2;subst.\nclear X86 H2.\ninversion X83;subst.\ninversion X85;subst.\ninversion X88;subst.\ninversion H2;subst.\nclear X88 H2.\ninversion X83;subst.\ninversion X88;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2.\ninversion X89;subst.\ninversion X90;subst.\nsimpl in *.\ninversion X91;subst.\ninversion X92;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2;subst.\ndestruct vs; inversion H5.\nunfold mkVEnv in *.\nsimpl in *.\nclear H5 H7 H16 H2.\ninversion X86;subst.\ninversion X93;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2.\ninversion X94;subst.\ninversion X95;subst.\nsimpl in *.\ninversion X96;subst.\ninversion X97;subst.\nsimpl in *.\ninversion X98;subst.\ninversion X99;subst.\ninversion X100;subst.\ninversion H2;subst.\nclear X100 H2.\ninversion X87;subst.\ninversion X100;subst.\ninversion X102;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2.\ninversion X103;subst.\ninversion X104;subst.\ninversion X105;subst.\nsimpl in *.\nclear X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 \n      X11 X12 X13 X14 X15 X16 X17 X18 X19 X20 \n      X21 X22 X23 X24 X25 X26 X27 X28 X29 X30 \n      X31 X32 X33 X34 X35 X36 X36 X38 X39 X40\n      X41 X42 X43 X44 X45 X46 X47 X48 X49 X50.\ninversion X106;subst.\nsimpl in *.\ninversion X1;subst.\ninversion X101;subst.\ninversion X2;subst.\ninversion X4;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2.\ninversion X5;subst.\ninversion X6;subst.\ninversion X7;subst.\nsimpl in *.\ninversion X8;subst.\ninversion X3;subst.\ninversion X9;subst.\ninversion X11;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2.\ninversion X12;subst.\ninversion X13;subst.\ninversion X14;subst.\nsimpl in *.\ninversion X10;subst.\ninversion X15;subst.\ninversion X17;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2.\ninversion X18;subst.\ninversion X19;subst.\nsimpl in *.\ninversion X20;subst.\ninversion X21;subst.\nrepeat apply inj_pair2 in H10.\nsubst.\ninversion X22;subst.\nsimpl in *.\ninversion X23;subst.\ninversion H2;subst.\nclear X23 H2 XF3.\ninversion X16;subst.\ninversion X23;subst.\ninversion X25;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2.\ninversion X26;subst.\ninversion X27;subst.\ninversion X28;subst.\nsimpl in *.\ninversion X29;subst.\nrepeat apply inj_pair2 in H10.\nrepeat apply inj_pair2 in H12.\nsubst.\nunfold b_exec,b_eval,xf_SuccD,b_mod in *.\nsimpl in *.\ninversion X16;subst.\ninversion X30;subst.\nclear X51 X52 X53 X54 X55 X56 X57 X58 X59 X60\n      X61 X62 X63 X64 X65 X66 X67 X68 X69 X70\n      X71 X72 X73 X74 X75 X76 X77 X78 X79 X80\n      X81 X82 X83 X84 X85 X86 X87 X88 X89 X90\n      X91 X92 X93 X94 X95 X96 X97 X98 X99 X100\n      X101 X102 X103 X104 X105 X106.\ninversion X32;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2.\ninversion X33;subst.\ninversion X34;subst.\nsimpl in *.\ninversion X35;subst.\ninversion X36;subst.\nrepeat apply inj_pair2 in H10.\nrepeat apply inj_pair2 in H13.\nsubst.\nunfold b_exec,b_eval,b_mod in *.\nsimpl in *.\ninversion X24;subst.\ninversion X38;subst.\ninversion X40;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2.\ninversion X41;subst.\ninversion X42;subst.\ninversion X43;subst.\ninversion X39;subst.\ninversion X44;subst.\ninversion X46;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2.\ninversion X47;subst.\ninversion X48;subst.\ninversion X39;subst.\ninversion X49;subst.\ninversion X51;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2.\ninversion X52;subst.\ninversion X53;subst.\nsimpl in *.\nclear X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 \n      X11 X12 X13 X14 X15 X16 X17 X18 X19 X20 \n      X21 X22 X23 X24 X25 X26 X27 X28 X29 X30. \ninversion X50;subst.\ninversion X1;subst.\ninversion X3;subst.\ninversion H7;subst.\ndestruct vs.\ninversion H2.\ninversion H2;subst.\ndestruct vs; inversion H5.\nunfold mkVEnv in *.\nsimpl in *.\nclear H5 H7 H18 H2.\ninversion X2;subst.\ninversion X4;subst.\nsimpl in *.\ninversion X5;subst.\ninversion X6;subst.\ninversion X9;subst.\nrepeat apply inj_pair2 in H10.\nsubst.\ninversion X10;subst.\ninversion X11;subst.\ninversion H2;subst.\nclear X11 H2 XF5.\ninversion X7;subst.\ninversion X11;subst.\ninversion X12;subst.\nrepeat apply inj_pair2 in H10.\nrepeat apply inj_pair2 in H14.\nsubst.\nunfold b_exec,b_eval,xf_SomeCindex,b_mod in *.\nsimpl in *.\ninversion X8;subst.\ninversion X13;subst.\ninversion X15;subst.\nsimpl in *.\ninversion X14;subst.\ninversion X16;subst.\ninversion X17;subst.\nassert (Z : S i = i+1). \nomega.\nrewrite Z.\nauto.\ninversion X18.\ninversion X18.\ninversion X16.\ninversion X13.\ninversion X4;subst.\ninversion X5.\ninversion X5.\ninversion X4.\ninversion X54.\ninversion X52.\ninversion X49.\ninversion X47.\ninversion X44.\ninversion X41.\ninversion X38.\ninversion X33.\ninversion X30.\ninversion X26.\ninversion X18.\ninversion X15.\ninversion X12.\ninversion X9.\ninversion X5.\ninversion X2.\ninversion X103.\ninversion X94.\ninversion X93;subst.\ninversion X94.\ninversion X94.\ninversion X93.\ninversion X89.\ninversion X78.\ninversion X75;subst.\ninversion X76.\ninversion X76.\ninversion X75.\ninversion X71.\ninversion X68.\ninversion X66.\ninversion X62.\ninversion X56.\ninversion X52.\ninversion X44.\ninversion X41;subst.\ninversion X42.\ninversion X42.\ninversion X41.\ninversion X39.\ninversion X36.\ninversion X34.\ninversion X32.\ninversion X26.\ninversion X24.\nrepeat apply inj_pair2 in H6.\nrewrite H in H6; inversion H6.\nrewrite H in X21; inversion X21.\ninversion X18.\ninversion X9.\ninversion X7.\nQed.\n*)\n\nLemma succRecWp (x:Id) (v:Value) P (fenv: funEnv) (env: valEnv) :\nforall (idx:index), {{fun s => P s  /\\ idx < tableSize - 1 /\\ v=cst index idx}} fenv >> (x,v)::env >> SuccRec x \n{{fun (idxsuc : Value) (s : state) => P s  /\\ idxsuc = cst (option index) (succIndexInternal idx) /\\ exists i, idxsuc = cst (option index) (Some i)}}.\nProof.\nintros.\neapply weakenEval.\neapply succRecW.\nintros.\nsimpl.\nsplit.\ninstantiate (1:=idx).  \nintuition.\nintros.\nintuition.\ndestruct idx.\nexists (CIndex (i + 1)).\nf_equal.\nunfold succIndexInternal.\ncase_eq (lt_dec i tableSize).\nintros.\nauto.\nintros.\ncontradiction.\nQed.\n\nLemma succW' (P: list Value -> W -> Prop)(fenv: funEnv) (env: valEnv) :\nforall (idx:index), \nTHoarePrmsTriple_Eval (fun s => idx < tableSize -1 /\\ forall  l : idx + 1 < tableSize , \n    P ([cst (option index) (succIndexInternal idx)]) s ) P\nfenv env (PS [Apply SuccQF (PS [Val (cst index idx)])]).\nProof.\nintros.\nunfold THoarePrmsTriple_Eval.\nintros.\nclear k3 pt k2 k1 ftenv tenv.\nintuition.\ninversion X;subst.\ndestruct vs.\ninversion H6.\ninversion H6.\ninversion X0;subst.\ninversion X2;subst.\nsimpl in *.\ninversion H6;subst.\ndestruct vs0.\ninversion H.\ninversion H.\ninduction vs0.\nsimpl in *.\nsubst.\nclear H13 H H4 H6.\nunfold mkVEnv in *.\nsimpl in *.\ninversion X1; subst.\ndestruct vs.\ninversion H6.\ninversion H6.\ninversion X3; subst.\ninversion X5; subst.\nsimpl in *.\ninversion X6; subst.\nrepeat apply inj_pair2 in H7.\nsubst.\ninversion X7; subst.\ninversion X8; subst.\ninversion H; subst.\nclear X8 H XF1.\ninversion X6; subst.\nrepeat apply inj_pair2 in H7.\nrepeat apply inj_pair2 in H11.\nsubst.\ninversion X4; subst.\ninduction vs.\ninversion H6.\ninversion H6.\ninversion X9; subst.\ninversion X11; subst.\nsimpl in *.\ninversion X12; subst.\nrepeat apply inj_pair2 in H7.\nrepeat apply inj_pair2 in H9.\nsubst.\nunfold xf_succ at 2 3 in X12.\nunfold b_exec, b_eval, b_mod in X12.\nsimpl in *.\ninversion X10; subst.\ndestruct vs.\ninversion H6.\ninversion H6.\ninversion X13; subst.\nunfold xf_succ, b_exec, b_eval, b_mod in X15.\nsimpl in *.\ninversion X15; subst.\ninversion X14; subst.\ndestruct vs.\ninversion H6.\ninversion H6;subst.\ndestruct vs.\napply H1.\nomega.\ninversion H3.\ninversion X16; subst.\ninversion X18.\ninversion X18.\ninversion X16.\ninversion X13.\ninversion H4.\ninversion X3;subst.\ninversion X4.\ninversion X4.\ninversion X3.\nQed.\n\n\nLemma succWp' partition P fenv env :\nforall vs (idx:index), THoarePrmsTriple_Eval \n  (fun (s:W) => P s  /\\ partitionDescriptorEntry s /\\ \n                          In partition (getPartitions multiplexer s) /\\  \n      idx < tableSize - 1 /\\ vs=[cst index idx])\n  (fun vs s =>  P s /\\ partitionDescriptorEntry s /\\ \n                          In partition (getPartitions multiplexer s) /\\ \n   (exists i : index, succIndexInternal idx = Some i /\\ vs = [cst (option index) (Some i)]))\n  fenv env (PS [Apply SuccQF (PS [Val (cst index idx)])]).\nProof.\nintros.\neapply weakenPrms.\neapply succW'.\nintros.\nsimpl.\nintuition.\nexists (CIndex (idx + 1)).\nintuition.\nunfold succIndexInternal.\ndestruct idx.\ncase_eq (lt_dec i tableSize).\nintros.\nauto.\nintros.\ncontradiction.\nf_equal.\nf_equal.\nunfold succIndexInternal.\ndestruct idx.\ncase_eq (lt_dec i tableSize).\nintros.\nauto.\nintros.\ncontradiction.\nQed.\n\n\n(******* about readPhysical *)\n\nLemma readPhysicalW (y:Id) table (v:Value) (P' : Value -> W -> Prop) (fenv: funEnv) (env: valEnv) :\n {{fun s =>  exists idxsucc p1, v = cst (option index) (Some idxsucc)\n              /\\ readPhysicalInternal table idxsucc (memory s) = Some p1 \n              /\\ P' (cst (option page) (Some p1)) s}} \nfenv >> (y,v)::env >> ReadPhysical table y {{P'}}.\nProof.\nintros.\nunfold THoareTriple_Eval.\nintros.\nintuition.\ndestruct H.\ndestruct H.\nintuition.\ninversion H0;subst.\nclear k3 t k2 k1 ftenv tenv H1.\ninversion X;subst.\ninversion X0;subst.\nrepeat apply inj_pair2 in H7.\nsubst.\ninversion X2;subst.\ninversion X3;subst.\ninversion H0;subst.\ndestruct IdEqDec in H3.\ninversion H3;subst.\nclear H3 e X3 H0 XF1. \ninversion X0;subst.\nrepeat apply inj_pair2 in H7.\nrepeat apply inj_pair2 in H11.\nsubst.\ninversion X1;subst.\ninversion X4;subst.\nrepeat apply inj_pair2 in H7.\napply inj_pair2 in H9.\nsubst.\nunfold xf_read at 2 in X4.\nunfold b_eval,b_exec,b_mod in X4.\nsimpl in *.\nrewrite H in X4.\nunfold xf_read,b_eval,b_exec,b_mod in X5.\nsimpl in *.\nrewrite H in X5.\ninversion X5;subst.\nauto.\ninversion X6.\ninversion X6.\ncontradiction.\nQed.\n\n\nLemma readPhysicalW' (y:Id) table (vs: list Value) (P' : Value -> W -> Prop) (fenv: funEnv) :\n {{fun s =>  exists idxsucc p1, vs = [cst (option index) (Some idxsucc)]\n              /\\ readPhysicalInternal table idxsucc (memory s) = Some p1 \n              /\\ P' (cst (option page) (Some p1)) s}} \nfenv >> (mkVEnv [(y, optionIndexType)] vs) >> ReadPhysical table y {{P'}}.\nProof.\nintros.\nunfold THoareTriple_Eval.\nintros.\nintuition.\ndestruct H.\ndestruct H.\nintuition.\ninversion H0;subst.\nunfold mkVEnv in *.\nsimpl in *.\nclear k3 t k2 k1 ftenv tenv H1.\ninversion X;subst.\ninversion X0;subst.\nrepeat apply inj_pair2 in H7.\nsubst.\ninversion X2;subst.\ninversion X3;subst.\ninversion H0;subst.\ndestruct IdEqDec in H3.\ninversion H3;subst.\nclear H3 e X3 H0 XF1. \ninversion X0;subst.\nrepeat apply inj_pair2 in H7.\nrepeat apply inj_pair2 in H11.\nsubst.\ninversion X1;subst.\ninversion X4;subst.\nrepeat apply inj_pair2 in H7.\napply inj_pair2 in H9.\nsubst.\nunfold xf_read at 2 in X4.\nunfold b_eval,b_exec,b_mod in X4.\nsimpl in *.\nrewrite H in X4.\nunfold xf_read,b_eval,b_exec,b_mod in X5.\nsimpl in *.\nrewrite H in X5.\ninversion X5;subst.\nauto.\ninversion X6.\ninversion X6.\ncontradiction.\nQed.\n\n\n(******* Hoare Triple *)\n\n(* For Bind Approach *)\n\nLemma getFstShadowBindH (partition : page) (P : W -> Prop) (fenv: funEnv) (env: valEnv) :\n{{fun s => P s  /\\ partitionDescriptorEntry s /\\ In partition (getPartitions multiplexer s)}}\nfenv >> env >> (getFstShadowBind partition) \n{{fun sh1 s => P s /\\ nextEntryIsPP partition sh1idx sh1 s}}.\nProof.\nunfold getFstShadowBind.\neapply BindS_VHTT1.\neapply getSh1idxWp.\nsimpl; intros.\neapply BindS_VHTT1.\neapply weakenEval.\neapply succWp. simpl.\nsimpl; intros; intuition.\ninstantiate (1:=(fun s => P s /\\ partitionDescriptorEntry s /\\ \n                          In partition (getPartitions multiplexer s))).\nsimpl. intuition.\ninstantiate (1:=sh1idx).\neapply H0 in H3.\nspecialize H3 with sh1idx.\neapply H3.\nauto. auto.\nsimpl; intros.\neapply weakenEval.\neapply readPhysicalW.\nsimpl;intros.\nintuition.\ndestruct H3.\nexists x.\nunfold partitionDescriptorEntry in H1.\napply H1 with partition sh1idx in H4.\nclear H1.\nintuition.\ndestruct H5.\nexists x0.\nintuition.\nunfold nextEntryIsPP in H4.\nunfold readPhysicalInternal.\nsubst.\ninversion H2.\nrepeat apply inj_pair2 in H3.\nunfold nextEntryIsPP in H5.\nrewrite H3 in H5.\ndestruct (lookup partition x (memory s) beqPage beqIndex).\nunfold cst in H5.\ndestruct v0;try contradiction.\napply inj_pairT2 in H5.\ninversion H5.\nauto.\nunfold isVA in H4.\ndestruct (lookup partition sh1idx (memory s) beqPage beqIndex) in H2;try contradiction.\nauto.\nQed.\n\n(* For Bind Approach with Deep successor function *)\n\nLemma getFstShadowBindDeepH (partition : page) (P : W -> Prop) (fenv: funEnv) (env: valEnv) :\n{{fun s => P s  /\\ partitionDescriptorEntry s /\\ In partition (getPartitions multiplexer s)}}\nfenv >> env >> (getFstShadowBindDeep partition) \n{{fun sh1 s => P s /\\ nextEntryIsPP partition sh1idx sh1 s}}.\nProof.\nunfold getFstShadowBindDeep.\neapply BindS_VHTT1.\neapply getSh1idxWp.\nsimpl; intros.\neapply BindS_VHTT1.\neapply weakenEval.\neapply succDWp. simpl.\nsimpl; intros; intuition.\ninstantiate (1:=(fun s => P s /\\ partitionDescriptorEntry s /\\ \n                          In partition (getPartitions multiplexer s))).\nsimpl. intuition.\ninstantiate (1:=sh1idx).\neapply H0 in H3.\nspecialize H3 with sh1idx.\neapply H3.\nauto. auto.\nsimpl; intros.\neapply weakenEval.\neapply readPhysicalW.\nsimpl;intros.\nintuition.\ndestruct H3.\nexists x.\nunfold partitionDescriptorEntry in H1.\napply H1 with partition sh1idx in H4.\nclear H1.\nintuition.\ndestruct H5.\nexists x0.\nintuition.\nunfold nextEntryIsPP in H4.\nunfold readPhysicalInternal.\nsubst.\ninversion H2.\nrepeat apply inj_pair2 in H3.\nunfold nextEntryIsPP in H5.\nrewrite H3 in H5.\ndestruct (lookup partition x (memory s) beqPage beqIndex).\nunfold cst in H5.\ndestruct v0;try contradiction.\napply inj_pairT2 in H5.\ninversion H5.\nauto.\nunfold isVA in H4.\ndestruct (lookup partition sh1idx (memory s) beqPage beqIndex) in H2;try contradiction.\nauto.\nQed.\n\n(*Bind approach & Deep definition of Succ with recursive plus function*) \n\nLemma getFstShadowBindDeepRecH (partition : page) (P : W -> Prop) (fenv: funEnv) (env: valEnv) :\n{{fun s => P s  /\\ partitionDescriptorEntry s /\\ In partition (getPartitions multiplexer s)}}\nfenv >> env >> (getFstShadowBindDeepRec partition) \n{{fun sh1 s => P s /\\ nextEntryIsPP partition sh1idx sh1 s}}.\nProof.\nunfold getFstShadowBindDeep.\neapply BindS_VHTT1.\neapply getSh1idxWp.\nsimpl; intros.\neapply BindS_VHTT1.\neapply weakenEval.\neapply succRecWp. simpl.\nsimpl; intros; intuition.\ninstantiate (1:=(fun s => P s /\\ partitionDescriptorEntry s /\\ \n                          In partition (getPartitions multiplexer s))).\nsimpl. intuition.\ninstantiate (1:=sh1idx).\neapply H0 in H3.\nspecialize H3 with sh1idx.\neapply H3.\nauto. auto.\nsimpl; intros.\neapply weakenEval.\neapply readPhysicalW.\nsimpl;intros.\nintuition.\ndestruct H3.\nexists x.\nunfold partitionDescriptorEntry in H1.\napply H1 with partition sh1idx in H4.\nclear H1.\nintuition.\ndestruct H5.\nexists x0.\nintuition.\nunfold nextEntryIsPP in H4.\nunfold readPhysicalInternal.\nsubst.\ninversion H2.\nrepeat apply inj_pair2 in H3.\nunfold nextEntryIsPP in H5.\nrewrite H3 in H5.\ndestruct (lookup partition x (memory s) beqPage beqIndex).\nunfold cst in H5.\ndestruct v0;try contradiction.\napply inj_pairT2 in H5.\ninversion H5.\nauto.\nunfold isVA in H4.\ndestruct (lookup partition sh1idx (memory s) beqPage beqIndex) in H2;try contradiction.\nauto.\nQed.\n\n(* For Apply Approach *)\n\nLemma getFstShadowApplyH (partition : page) (P : W -> Prop) (fenv: funEnv) (env: valEnv) :\n{{fun s => P s  /\\ partitionDescriptorEntry s /\\ In partition (getPartitions multiplexer s)}}\nfenv >> env >> (getFstShadowApply partition) \n{{fun sh1 s => P s /\\ nextEntryIsPP partition sh1idx sh1 s}}.\nProof.\nunfold getFstShadowApply.\neapply Apply_VHTT1.\neapply weakenPrms.\nunfold getSh1idx.\neapply succWp'.\nsimpl; intros.\nintuition.\ninstantiate (1:=P).\nauto.\neauto.\neapply H in H2.\nspecialize H2 with sh1idx.\neapply H2.\nauto.\nintuition.\neapply weakenEval.\neapply readPhysicalW'.\nsimpl; intros.\nintuition.\ndestruct H3.\nexists x.\nunfold partitionDescriptorEntry in H.\napply H with partition sh1idx in H1.\nclear H.\nintuition.\ndestruct H5.\nexists x0.\nintuition.\nunfold nextEntryIsPP in H5.\nunfold readPhysicalInternal.\nrewrite H1 in H5.\ndestruct (lookup partition x (memory s) beqPage beqIndex).\nunfold cst in H5.\ndestruct v;try contradiction.\napply inj_pairT2 in H5.\ninversion H5.\nauto.\nunfold isVA in H2.\ndestruct (lookup partition sh1idx (memory s) beqPage beqIndex) in H2;try contradiction.\nauto.\nQed.\n\nLemma getFstShadowApplyH' (partition : page) (P : W -> Prop) (fenv: funEnv) (env: valEnv) :\n{{fun s => P s  /\\ partitionDescriptorEntry s /\\ In partition (getPartitions multiplexer s)}}\nfenv >> env >> (getFstShadowApply partition) \n{{fun sh1 s => P s /\\ nextEntryIsPP partition sh1idx sh1 s}}.\nProof.\nunfold getFstShadowApply.\neapply Apply_VHTT1.\neapply Prms_VHTT1.\neapply Apply_VHTT1.\neapply Prms_VHTT1.\neapply getSh1idxWp.\nintros; unfold THoarePrmsTriple_Eval; intros;simpl.\ninversion X;subst.\ndestruct vs; inversion H5.\ninstantiate (1:= fun vs s => P s /\\ partitionDescriptorEntry s /\\\n     In partition (getPartitions multiplexer s) /\\ vs = [cst index sh1idx]).\nintuition. f_equal. auto.\ninversion X0.\nintuition.\ndestruct vs.\nunfold THoareTriple_Eval; intros.\nintuition. inversion H3.\ndestruct vs.\nFocus 2.\nunfold THoareTriple_Eval; intros.\nintuition. inversion H3.\nunfold mkVEnv. simpl.\neapply weakenEval.\neapply succWp.\nsimpl; intros. \ninstantiate (1:= sh1idx).\ninstantiate (1:= fun s => P s /\\\n    partitionDescriptorEntry s /\\\n    In partition (getPartitions multiplexer s)).\nsimpl. intuition.\neapply H in H1.\nspecialize H1 with sh1idx.\neapply H1.\nauto.\ninversion H3; intuition.\nintros; simpl.\nunfold THoarePrmsTriple_Eval; intros.\ninversion X; subst.\ndestruct vs; inversion H5.\ninstantiate (1:= fun vs s => P s /\\ partitionDescriptorEntry s /\\\n     In partition (getPartitions multiplexer s) \n     /\\ (exists i : index,\n     succIndexInternal sh1idx = Some i /\\ vs = [cst (option index) (Some i)]) \n    ).\nintuition.\ndestruct H3.\nexists x.\nintuition.\nrewrite H0 in H2.\ninversion H2; subst.\nrepeat apply inj_pair2 in H6.\nauto.\nf_equal.\nauto.\ninversion X0.\nintuition.\ndestruct vs.\nunfold THoareTriple_Eval; intros.\ndestruct H as [a [b [c d]]].\ndestruct d. destruct H.\ninversion H0.\ndestruct vs.\nFocus 2.\nunfold THoareTriple_Eval; intros.\ndestruct H as [a [b [c d]]].\ndestruct d. destruct H.\ninversion H0.\nunfold mkVEnv; simpl.\neapply weakenEval.\neapply readPhysicalW.\nsimpl; intros.\nintuition.\ndestruct H3.\nexists x.\nunfold partitionDescriptorEntry in H.\napply H with partition sh1idx in H1.\nclear H.\nintuition.\ndestruct H5.\nexists x0.\nintuition.\ninversion H4;subst. auto.\nunfold nextEntryIsPP in H5.\nunfold readPhysicalInternal.\nrewrite H1 in H5.\ndestruct (lookup partition x (memory s) beqPage beqIndex).\ndestruct v0;try contradiction.\nunfold cst in H5.\napply inj_pairT2 in H5.\ninversion H5.\nauto.\nunfold isVA in H2.\ndestruct (lookup partition sh1idx (memory s) beqPage beqIndex) in H2;try contradiction.\nauto.\nQed.\n\n\nEnd Hoare_Test_FstShadow.\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_getFstShadow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.29405870526097366}}
{"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.\n\n(******************************************************************************)\n(* Reducibility of configurations number 546 to 549, whose indices in         *)\n(* the_configs range over segment [545, 549).                                 *)\n(******************************************************************************)\n\nLemma red545to549 : reducible_in_range 545 549 the_configs.\nProof. CheckReducible. Qed.\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/job546to549.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.2940586976544659}}
{"text": "(** Typing rules for standard PTS.*)\nRequire Import PTS_term.\nRequire Import PTS_red.\nRequire Import PTS_env.\nRequire Import PTS_base.\nRequire Import List.\nRequire Import Peano_dec.\nRequire Import Compare_dec.\nRequire Import Lt Le Gt Plus Minus.\n\nModule ut_typ_mod (X:term_sig) (Y:pts_sig X) (TM: ut_term_mod X) (EM: ut_env_mod X TM) (RM: ut_red_mod X TM).\n  Import X Y TM EM RM.\n\n(** Typing judgements:*)\nReserved Notation \"Γ ⊢ t : T\" (at level 80, t, T at level 30, no associativity) .\nReserved Notation \"Γ ⊣ \" (at level 80, no associativity).\n\nInductive wf : Env -> Prop :=\n | wf_nil  : nil ⊣\n | wf_cons : forall Γ A s, Γ ⊢ A : !s -> A::Γ ⊣\nwhere \"Γ ⊣\" := (wf Γ) : UT_scope\nwith typ : Env -> Term -> Term -> Prop :=\n | cSort : forall Γ s t, Ax s t -> Γ ⊣ -> Γ  ⊢ !s : !t\n | cVar  : forall Γ A v, Γ ⊣ -> A ↓ v  ⊂ Γ -> Γ ⊢ #v : A \n | cPi   : forall Γ A B s t u, Rel s t u -> Γ ⊢ A : !s -> A::Γ ⊢ B : !t -> \n   Γ ⊢  Π(A), B : !u \n | cLa   : forall Γ A B M s1 s2 s3, Rel s1 s2 s3 -> Γ ⊢ A : !s1 -> \n   A::Γ ⊢ B : !s2 -> A::Γ ⊢ M : B -> Γ ⊢ λ[A], M : Π(A), B\n | cApp  : forall Γ M N A B , Γ ⊢ M : Π(A), B -> Γ ⊢ N : A -> Γ ⊢ M · N : B[←N]\n | Cnv   : forall Γ M A B s, A ≡ B  -> Γ ⊢ M : A -> Γ ⊢ B : !s -> Γ ⊢ M : B\nwhere \"Γ ⊢ t : T\" := (typ Γ t T) : UT_scope.\n\nHint Constructors wf typ.\n\nOpen Scope UT_scope.\n\n(* begin hide *)\nScheme typ_ind' := Induction for typ Sort Prop\n      with wf_ind' := Induction for wf Sort Prop.\n\nCombined Scheme typ_induc from typ_ind', wf_ind'.\n(* end hide *)\n\n(** Basic properties of PTS.\n  Context Validity: if a judgment is valid, its context is well-formed.*)\nLemma wf_typ : forall Γ t T, Γ ⊢ t : T -> Γ ⊣.\ninduction 1; eauto.\nQed.\n\nHint Resolve wf_typ.\n\n(** Inversion Lemmas , one for each kind of term \n  from a typing derivation of some particular term, we can \ninfer informations about its type and subterms.*)\n\nLemma gen_sort : forall Γ s T, Γ ⊢ !s : T -> exists t, T ≡ !t /\\ Ax s t.\nintros. remember !s as S. revert s HeqS. induction H; intros; subst; try discriminate.\ninjection HeqS; intros; subst; clear HeqS. exists t; intuition.\ndestruct (IHtyp1 s0) as (t & ? & ?); trivial. exists t; split.\neauto. trivial.\nQed.\n\n\nLemma gen_var : forall Γ x A, Γ ⊢ #x : A -> exists A', A ≡ A' /\\ A' ↓ x ⊂ Γ .\nintros. remember #x as X. revert x HeqX. induction H; intros; subst; try discriminate.\ninjection HeqX; intros; subst; clear HeqX.\nexists A; intuition.\ndestruct (IHtyp1 x) as (A' & ? & ?); trivial. exists A'; split. eauto. trivial.\nQed.\n\nLemma gen_pi : forall Γ A B T, Γ ⊢ Π(A),B : T -> exists s1, exists s2, exists s3, \n    T ≡ !s3 /\\ Rel s1 s2 s3 /\\ Γ ⊢ A : !s1  /\\ A::Γ ⊢ B : !s2 .\nintros. remember (Π(A),B) as P. revert A B HeqP. induction H; intros; subst; try discriminate.\nclear IHtyp1 IHtyp2. injection HeqP; intros; subst; clear HeqP.\nexists s; exists t; exists u; intuition.\ndestruct (IHtyp1 A0 B0) as (a & b & c & ? & ? & ? &  ?); trivial. exists a; exists b; exists c; split.\neauto. intuition.\nQed.\n\n\nLemma gen_la : forall Γ A M T, Γ ⊢ λ[A],M : T -> exists s1, exists s2, exists s3, exists B, \n    T ≡ Π(A), B /\\ Rel s1 s2 s3 /\\ Γ ⊢ A : !s1 /\\ A::Γ ⊢ M : B /\\ A::Γ ⊢ B : !s2.\nintros. remember (λ[A],M) as L. revert A M HeqL. induction H; intros ; subst; try discriminate.\nclear IHtyp1 IHtyp2 IHtyp3. injection HeqL; intros; subst; clear HeqL.\nexists s1; exists s2; exists s3; exists B; intuition.\ndestruct (IHtyp1 A0 M0) as (a & b & c & D &? &? & ? & ? & ?); trivial.\nexists a; exists b; exists c; exists D; split. eauto. intuition.\nQed.\n\nLemma gen_app : forall Γ M N T, Γ ⊢ M · N : T -> exists A, exists B, T ≡ B[← N] /\\ Γ ⊢ M : Π(A),B /\\ Γ ⊢ N : A.\nintros. remember (M·N) as A. revert M N HeqA. induction H; intros; subst; try discriminate.\nclear IHtyp1 IHtyp2. injection HeqA; intros; subst; clear HeqA.\nexists A; exists B; intuition.\ndestruct (IHtyp1 M0 N) as (K & L & ? & ?& ?); trivial. exists K; exists L; split.\neauto. intuition.\nQed.\n\n(** Weakening Property: if a judgement is valid, we can insert a well-typed term\n  in the context, it will remain valid. This is where the type checking for \n  inserting items in a context is done.*)\nTheorem weakening: (forall Δ M T, Δ ⊢ M : T -> forall Γ A s n Δ', ins_in_env Γ A n Δ Δ' ->   Γ ⊢ A : !s -> \n                 Δ' ⊢ M ↑ 1 # n : T ↑ 1 # n ) /\\\n(forall Γ, Γ ⊣ -> forall Δ Γ' n A , ins_in_env Δ A n Γ Γ' -> forall s, Δ ⊢ A : !s -> Γ' ⊣).\napply typ_induc; simpl in *; intros.\n(*1*)\neauto.\n(*2*)\ndestruct (le_gt_dec n v).\nconstructor. eapply H; eauto. destruct i as (AA & ?& ?). exists AA; split. rewrite H2.\nchange (S (S v)) with (1+ S v). rewrite liftP3; simpl; intuition. eapply ins_item_ge. apply H0. trivial. trivial.\nconstructor. eapply H; eauto.  eapply ins_item_lift_lt. apply H0. trivial. trivial.\n(*3*)\neconstructor. apply r. eauto. eapply H0. constructor; apply H1. apply H2.\n(*4*)\neconstructor. apply r. eapply H; eauto. eapply H0; eauto. eapply H1; eauto.\n(*5*)\nchange n with (0+n). rewrite substP1. simpl.\neconstructor. eapply H; eauto. eapply H0; eauto.\n(*6*)\napply Cnv with (A↑ 1 # n) s; intuition.\neapply H; eauto. eapply H0; eauto.\n(* wf *)\ninversion H; subst; clear H.\napply wf_cons with s; trivial.\n(**)\ninversion  H0; subst; clear H0.\napply wf_cons with s0; trivial. \napply wf_cons with s; trivial. change !s with !s ↑ 1 # n0.\neapply H.  apply H6. apply H1.\nQed.\n\n\nTheorem thinning :\n   forall Γ M T A s,\n      Γ ⊢ M : T -> \n   Γ ⊢ A : !s ->\n   A::Γ ⊢ M ↑ 1 : T ↑ 1.\nintros.\ndestruct weakening.\neapply H1. apply H. constructor. apply H0.\nQed.\n\nTheorem thinning_n : forall n Δ Δ',\n   trunc n Δ Δ' ->\n   forall M T , Δ' ⊢ M : T  -> Δ ⊣ ->\n               Δ ⊢ M ↑ n : T ↑ n.\nintro n; induction n; intros.\ninversion H; subst; clear H.\nrewrite 2! lift0; trivial.\ninversion H; subst; clear H.\nchange (S n) with (1+n).\nreplace (M ↑ (1+n)) with ((M ↑ n )↑ 1) by (apply lift_lift).\nreplace (T ↑ (1+n)) with ((T ↑ n) ↑ 1) by (apply lift_lift).\ninversion H1; subst; clear H1.\napply thinning with s; trivial.\neapply IHn. apply H3. trivial. eauto.\nQed.\n\n\n(** Substitution Property: if a judgment is valid and we replace a variable by a\n  well-typed term of the same type, it will remain valid.*)\n(* begin hide *)\nLemma sub_trunc : forall Δ a A n Γ Γ', sub_in_env Δ a A n Γ Γ' -> trunc n Γ' Δ.\ninduction 1.\napply trunc_O.\napply trunc_S. trivial.\nQed.\n(* end hide *)\n\nTheorem substitution : (forall Γ M T , Γ  ⊢ M : T  -> forall Δ P A, Δ  ⊢ P : A -> \n forall Γ' n , sub_in_env Δ P A n Γ Γ' -> Γ ⊣  -> Γ' ⊢ M [ n ←P ]  : T [ n ←P ] ) /\\\n                       (forall Γ ,  Γ ⊣ -> forall Δ P A n Γ' , Δ ⊢ P : A ->  \n  sub_in_env  Δ P A n Γ Γ' ->  Γ' ⊣).\napply typ_induc; simpl; intros.\n(*1*)\neauto.\n(*2*)\ndestruct lt_eq_lt_dec as [ [] | ].\nconstructor. eapply H; eauto. eapply nth_sub_item_inf. apply H1. intuition. trivial.\ndestruct i as (AA & ?& ?). subst. rewrite substP3; intuition. \nrewrite <- (nth_sub_eq H1 H4). eapply thinning_n. eapply sub_trunc. apply H1. trivial.\neapply H; eauto. constructor. eapply H; eauto. destruct i as (AA & ? &?). subst.\nrewrite substP3; intuition. exists AA; split. replace (S (v-1)) with v. trivial.\nrewrite minus_Sn_m. intuition. destruct v. apply lt_n_O in l; elim l. intuition.\neapply nth_sub_sup. apply H1. destruct v. apply lt_n_O in l; elim l. simpl. rewrite <- minus_n_O.\nintuition. rewrite <- pred_of_minus. rewrite <- (S_pred v n l). trivial.\n(*4*)\neconstructor. apply r. eapply H; eauto. eapply H0; eauto.\n(*5*)\neconstructor. apply r. eapply H; eauto. eapply H0; eauto. eapply H1; eauto.\n(*6*)\nrewrite subst_travers. econstructor.\nreplace (n+1) with (S n) by (rewrite plus_comm; trivial). eapply H; eauto.\nreplace (n+1) with (S n) by (rewrite plus_comm; trivial). eapply H0; eauto.\n(*7*)\neconstructor.  apply Betac_subst2. apply b. eapply H; eauto. eapply H0; eauto.\n(* wf *)\ninversion H0.\ninversion H1; subst; clear H1. eauto.\neconstructor. eapply H. apply H0. trivial. eauto. \nQed.\n\n(** Well-formation of contexts: if a context is valid, every term inside\n  is well-typed by a sort.*)\nLemma wf_item : forall Γ A n, A ↓ n ∈ Γ ->\n   forall  Γ', Γ ⊣ ->  trunc (S n) Γ Γ' -> exists s, Γ' ⊢ A : !s.\ninduction 1; intros.\ninversion H0; subst; clear H0.\ninversion H5; subst; clear H5.\ninversion H; subst.\nexists s; trivial.\ninversion H1; subst; clear H1.\ninversion H0; subst.\napply IHitem; trivial. eauto. \nQed.\n\nLemma wf_item_lift : forall Γ A n ,Γ ⊣  -> A ↓ n ⊂ Γ ->\n  exists s,  Γ ⊢ A  : !s.\nintros.\ndestruct H0 as (u & ? & ?).\nsubst.\nassert (exists Γ' , trunc (S n) Γ Γ') by (apply item_trunc with u; trivial).\ndestruct H0 as (Γ' & ?).\ndestruct (wf_item Γ u n H1 Γ' H H0) as (t &  ?).\nexists t. change !t with (!t ↑(S n)).\neapply thinning_n. apply H0. trivial. trivial.\nQed.\n\n(** Type Correction: if a judgment is valid, the type is either welltyped\n  itself, or syntacticaly a sort. This distinction comes from the fact\n  that we abstracted the typing of sorts with [Ax] and that they may be some\n  untyped sorts (also called top-sorts).*)\nTheorem TypeCorrect : forall Γ M T, Γ ⊢ M : T  -> \n (exists s, T = !s) \\/ (exists s, Γ ⊢ T : !s).\nintros; induction H.\n(*1*)\nleft; exists t; reflexivity.\n(*2*)\napply wf_item_lift in H0. right; trivial. trivial.\n(*4*)\nleft; exists u; trivial.\n(*5*)\nright; exists s3; apply cPi with s1 s2; trivial.\n(*6*)\ndestruct IHtyp1. destruct H1; discriminate. destruct H1 as (u & ?).\napply gen_pi in H1 as (s1 & s2 & s3 & h); decompose [and] h; clear h.\nright; exists s2.\nchange (!s2) with (!s2 [← N]). eapply substitution. apply H5. apply H0. constructor.\neauto.\n(*8*)\nright; exists s; trivial.\nQed.\n\nEnd ut_typ_mod.\n", "meta": {"author": "ppedrot", "repo": "vitef", "sha": "695b0ac92de8911872d60834f6dcee5034fa88dc", "save_path": "github-repos/coq/ppedrot-vitef", "path": "github-repos/coq/ppedrot-vitef/vitef-695b0ac92de8911872d60834f6dcee5034fa88dc/ZF/PTS/PTS_type.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.2940586976544659}}
{"text": "(* begin hide *)\nFrom Coq Require Import\n     RelationClasses\n     Morphisms.\n\nFrom Vellvm Require Import Utils.NoEvent.\n\nFrom Paco Require Import paco.\n\nFrom ITree Require Import\n     ITree\n     ITreeFacts\n     Eq.Eqit.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nImport MonadNotation.\nOpen Scope monad_scope.\n\n(* end hide *)\n\n(** * Commutation of computations described as [itree]s\n  This file develops some theory to justify when two computations described as\n  interaction trees can be commuted, i.e. looks for sufficient condition under \n  which we have: [t1 ;; t2 ≈ t2 ;; t1].\n\n  We prove the obvious result that it always hold for computations that have no \n  effects (E == void1) and computes no meaningful value (R == unit): [trivial_commut].\n  While it is not surprising, it is not a completely trivial fact as it must\n  account for divergence of either of the computation. \n\n  We also establish more interesting results for computations involving a state.\n  These lemmas are currently used in Helix in order to justify that the order of\n  iteration of bounded loops over appropriate bodies can be reversed.\n\n*)\n\nLemma itree_eta_cont : forall {E A B} (t : itree E A) (k : A -> itree E B),\n    x <- t;; k x ≅ x <- t;; (fun y => {| _observe := observe (k y) |}) x.\nProof.\n  intros.\n  eapply eq_itree_clo_bind; [reflexivity | intros ? ? <-].\n  rewrite itree_eta at 1; reflexivity.\nQed.\n\nLemma trivial_commut_gen : forall (t1 t2 t3 t4 : unit -> itree void1 unit),\n    (forall x, t1 x ≈ t4 x) ->\n    (forall x, t2 x ≈ t3 x) ->\n    x <- t1 tt;; t2 x ≈ x <- t3 tt;; t4 x.\nProof.\n  cbn.\n  einit; ecofix CIH.\n  intros * EQ1 EQ2.\n  setoid_rewrite (itree_eta (t1 tt)) at 1.\n  destruct (observe (t1 tt)) eqn:EQ.\n  - rewrite bind_ret_l.\n    rewrite <- bind_ret_r at 1.\n    ebind; econstructor.\n    destruct r; apply EQ2.\n    intros [] [] _.\n    efinal.\n    rewrite <- (EQ1 tt).\n    rewrite (itree_eta (t1 tt)), EQ.\n    destruct r; reflexivity.\n  - rewrite (itree_eta (t3 tt)).\n    destruct (observe (t3 tt)) eqn:EQ'.\n    + destruct r.\n      rewrite bind_ret_l.\n      rewrite <- (bind_ret_r (t4 tt)). \n      ebind; econstructor.\n      rewrite <- EQ1.\n      rewrite (itree_eta (t1 tt)), EQ; reflexivity.\n      intros [] [] _.\n      edrop.\n      rewrite EQ2, itree_eta, EQ'.\n      reflexivity.\n    + rewrite !bind_tau.\n      estep.\n      ebase; right.\n      specialize (CIH (fun _ => t) t2 (fun _ => t0) t4).\n      apply CIH.\n      intros [].\n      rewrite <- EQ1.\n      rewrite (itree_eta (t1 tt)), EQ.\n      rewrite tau_eutt; reflexivity.\n      intros [].\n      rewrite EQ2.\n      rewrite (itree_eta (t3 tt)), EQ'.\n      rewrite tau_eutt; reflexivity.\n    + inv e.\n  - inv e.\nQed.\n\nLemma trivial_commut : forall (t t' : unit -> itree void1 unit),\n    x <- t tt;; t' x ≈ x <- t' tt;; t x.\nProof.\n  intros; apply trivial_commut_gen; intros; reflexivity.\nQed.\n\nFrom Vellvm Require Import\n     Utils.PostConditions.\n\nRequire Import Coq.Logic.FunctionalExtensionality.\n\nLemma eutt_post_bind_het :\n  forall (E : Type -> Type) (A : Type) (QQ : A -> A -> Prop) (Q1 Q2 : A -> Prop)\n    (t1 t2 : A -> itree E A) (k1 : A -> itree E A) (k2 : A -> itree E A) (a0 : A),\n    t1 a0 ⤳ Q1 ->\n    t2 a0 ⤳ Q2 ->\n    (forall u1 u2, eutt (fun x y => Q1 x /\\ Q2 y) (t1 u1) (t2 u2)) ->\n    (forall u1 u2 : A, Q1 u1 -> Q2 u2 -> eutt QQ (k1 u1) (k2 u2)) ->\n    eutt QQ (x <- t1 a0;; k1 x) (x <- t2 a0;; k2 x).\nProof.\n  intros * POST1 POST2 EQ1 EQ2.\n  apply eutt_clo_bind with (UU := fun x y => Q1 x /\\ Q2 y); [ | intuition].\n  apply eutt_conj.\n  rewrite has_post_post_strong in POST1.\n  rewrite has_post_post_strong in POST2.\n  unfold has_post_strong in *.\n  eapply eqit_mon; eauto. 2 : apply EQ1. intuition. destruct PR. auto.\n  eapply eqit_mon; eauto. 2 : apply EQ1. intuition. destruct PR. auto.\nQed.\n\n(* We can commute computations where each atom coterminates with each other *)\nLemma commut_gen_coterminating_atoms :\n  forall {A : Type}\n    (Q1 Q2 : A -> Prop) (QQ : A -> A -> Prop) (a0 : A)\n    (t1 t2 t3 t4 : A -> itree void1 A),\n    (forall x, t1 x ≈ t4 x) ->\n    (forall x, t2 x ≈ t3 x) ->\n    (t1 a0 ⤳ Q1) ->\n    (t3 a0 ⤳ Q2) ->\n    (forall a1 a2, eutt (fun x y => Q1 x /\\ Q2 y) (t1 a1) (t3 a2)) ->\n    (forall a1 a2, Q1 a1 -> Q2 a2 -> eutt QQ (t2 a1) (t4 a2)) ->\n    eutt QQ ('a <- t1 a0;; t2 a) ('a <- t3 a0;; t4 a).\nProof.\n  cbn.\n  einit. ecofix CIH.\n  intros * EQ1 EQ2 EQ3 PC1 PC2 H.\n  setoid_rewrite (itree_eta (t1 a0)) at 1.\n  destruct (observe (t1 a0)) eqn: EQ; [ | | inv e].\n  - ebind; econstructor; cycle 1.\n    Unshelve. 3 : exact (fun x y => Q1 x /\\ Q2 y).\n    + intros. destruct H0. efinal.\n    + clear H.\n      rewrite <- bind_ret_r.\n      setoid_rewrite <- bind_ret_r at 4.\n      rewrite <- EQ. rewrite <- itree_eta.\n      eapply eutt_post_bind_het; eauto.\n      intros. eauto. apply eqit_Ret; eauto.\n  - rewrite (itree_eta (t3 a0)).\n    destruct (observe (t3 a0)) eqn: EQ'; [ | | inv e].\n    + ebind; econstructor; cycle 1.\n      Unshelve. 3 : exact (fun x y => Q1 x /\\ Q2 y).\n      * intros. destruct H0. efinal.\n      * clear H. rewrite <- bind_ret_r.\n        setoid_rewrite <- bind_ret_r at 5.\n        rewrite <- EQ. rewrite <- itree_eta.\n        rewrite <- EQ'. rewrite <- itree_eta.\n        eapply eutt_post_bind_het; eauto.\n        intros. apply eqit_Ret; eauto.\n    + rewrite !bind_tau.\n\n      assert (t1 a0 ≈ t). rewrite itree_eta. rewrite EQ.\n      apply eqit_Tau_l. reflexivity.\n\n      assert (t3 a0 ≈ t0). rewrite itree_eta. rewrite EQ'.\n      apply eqit_Tau_l. reflexivity.\n\n      clear CIH0.\n\n      estep.\n      ebind; econstructor; cycle 1.\n\n      Unshelve. 3 : exact (fun x y => Q1 x /\\ Q2 y).\n      * intros. destruct H2. efinal.\n      * rewrite <- bind_ret_r.\n        setoid_rewrite <- bind_ret_r at 4.\n        rewrite <- H0,<- H1.\n        eapply eutt_post_bind_het; eauto.\n        intros. apply eqit_Ret; eauto.\nQed.\n\nLemma commut_gen :\n  forall {A : Type}\n    (Q1 Q2 : A -> Prop) (QQ : A -> A -> Prop)\n    (t1 t3 : itree void1 A)\n    (t2 t4 : A -> itree void1 A),\n    (forall x, Q2 x -> t1 ≈ t4 x) ->\n    (forall x, Q1 x -> t2 x ≈ t3) ->\n    (t1 ⤳ Q1) ->\n    (t3 ⤳ Q2) ->\n    (forall a, Q1 a -> t2 a ⤳ (fun x => QQ x a)) ->\n    (forall a, Q2 a -> t4 a ⤳ (fun x => QQ a x)) ->\n    eutt QQ (a <- t1;; t2 a) (a <- t3;; t4 a).\nProof.\n  cbn.\n  einit. ecofix CIH.\n  intros * EQ1 EQ2 PC1 PC2 F1 F2.\n  setoid_rewrite (itree_eta t1) at 1.\n  destruct (observe t1) eqn: EQ; [ | | inv e].\n\n  - (* Ret *)\n    (* Need this rewriting to reason about co-termination on t2 and t3. *)\n    rewrite bind_ret_l. rewrite <- bind_ret_r at 1.\n\n    ebind; econstructor.\n    + (* Prefix *)\n      Unshelve.\n      2 : { exact (fun x y => x = y /\\ Q2 x). }\n      rewrite EQ2; cycle 1.\n      setoid_rewrite (itree_eta t1) in PC1.\n      rewrite EQ in PC1. apply eqit_Ret in PC1. auto.\n      rewrite has_post_post_strong in PC2.\n      apply PC2.\n    + (* Continuation. Equate t1 and t4. *)\n      intros * [<- HQ]. efinal.\n      setoid_rewrite (itree_eta t1) in EQ1.\n      rewrite EQ in EQ1. rewrite <- EQ1; auto.\n      apply eqit_Ret.\n      specialize (F2 _ HQ).\n      rewrite <- EQ1 in F2; auto. apply eqit_inv_Ret in F2. auto.\n\n  - (* Tau *)\n    rewrite (itree_eta t3).\n    destruct (observe t3) eqn: EQ'; [ | | inv e].\n    + rewrite bind_ret_l. setoid_rewrite <- bind_ret_r at 5.\n      ebind; econstructor.\n      * (* Prefix *)\n        Unshelve.\n        2 : { exact (fun x y => x = y /\\ Q1 x). }\n\n        rewrite <- EQ1; cycle 1.\n        setoid_rewrite (itree_eta t3) in PC2.\n        rewrite EQ' in PC2. apply eqit_Ret in PC2. auto.\n\n        setoid_rewrite (itree_eta t1). setoid_rewrite (itree_eta t1) in PC1.\n        rewrite has_post_post_strong in PC1.\n        rewrite EQ. apply eqit_Tau. rewrite EQ in PC1.\n        apply eqit_inv_Tau_l in PC1.\n        apply eqit_inv_Tau_r in PC1. \n        apply PC1.\n\n      * (* Continuation. Equate t2 and t3. *)\n        intros * [<- HQ]. efinal.\n        setoid_rewrite (itree_eta t3) in EQ2.\n        rewrite EQ' in EQ2. rewrite EQ2; auto.\n        apply eqit_Ret.\n        specialize (F1 _ HQ).\n        rewrite EQ2 in F1; auto. apply eqit_inv_Ret in F1. auto.\n\n    + rewrite !bind_tau.\n\n      assert (t1 ≈ t). rewrite itree_eta. rewrite EQ.\n      apply eqit_Tau_l. reflexivity.\n\n      assert (t3 ≈ t0). rewrite itree_eta. rewrite EQ'.\n      apply eqit_Tau_l. reflexivity.\n\n      clear CIH0.\n\n      estep.\n      ebase; right.\n      eapply CIH; eauto.\n      setoid_rewrite <- H. auto.\n      setoid_rewrite <- H0. auto.\n      rewrite <- H. auto. rewrite <- H0. auto.\nQed.\n\nLemma eutt_inv_ret_l :\n  forall E A Q r t1, eutt (E := E) (fun x y : A => Q x) (Ret r) t1 -> Q r.\nProof.\n  intros.\n  punfold H.\n  unfold eqit_ in H.\n  remember (observe (Ret r)) as x.\n  revert Heqx .\n  induction H; intros EQ; try now inv EQ.\n  - apply IHeqitF; auto.\nQed.\n\nLemma eutt_inv_ret_r :\n  forall E A Q r t1, eutt (E := E) (fun x y : A => Q y) t1 (Ret r) -> Q r.\nProof.\n  intros.\n  punfold H.\n  unfold eqit_ in H.\n  remember (observe (Ret r)) as x.\n  revert Heqx .\n  induction H; intros EQ; try now inv EQ.\n  - apply IHeqitF; auto.\nQed.\n\nLemma commut_gen' :\n  forall {A : Type}\n    (Q1 Q2 : A -> Prop) (QQ : A -> Prop)\n    (t1 t3 : itree void1 A)\n    (t2 t4 : A -> itree void1 A),\n    (forall i, eutt (fun x y => Q1 x /\\ Q1 y) t1 (t4 i)) ->\n    (forall i, eutt (fun x y => Q2 x /\\ Q2 y) t3 (t2 i)) ->\n      (forall a, Q1 a -> eutt (fun x y => QQ x /\\ QQ y) t3 (t2 a)) ->\n      (forall a, Q2 a -> eutt (fun x y => QQ x /\\ QQ y) t1 (t4 a)) ->\n    eutt (fun x y => QQ x /\\ QQ y) (a <- t1 ;; t2 a) (a <- t3 ;; t4 a).\nProof.\n  cbn.\n\n  einit. ecofix CIH.\n  intros * EQ1 EQ2 * PC1 PC2.\n  setoid_rewrite (itree_eta t1) at 1.\n  destruct (observe t1) eqn: EQ; [ | | inv e].\n\n  clear CIH0.\n  - (* Ret *)\n    (* Need this rewriting to reason about co-termination on t2 and t3. *)\n\n    rewrite bind_ret_l.\n\n    setoid_rewrite (itree_eta t1) in EQ1. rewrite EQ in EQ1.\n\n    rewrite <- bind_ret_r.\n    ebind. econstructor.\n    Unshelve. 3 : exact (fun x y => QQ x /\\ Q2 y).\n\n    {\n      specialize (EQ1 r).\n\n      apply eutt_conj; cycle 1.\n      eapply eqit_mon; auto. 2 : eapply eqit_flip; apply EQ2. intuition. destruct PR. auto.\n      eapply eqit_mon; auto.\n      2 : eapply eqit_flip; eapply PC1. intros * []; auto.\n\n      setoid_rewrite (itree_eta (t4 r)) in EQ1.\n      destruct (observe (t4 r)) eqn: EQ'; [ | | inv e].\n      apply eqit_inv_Ret in EQ1. destruct EQ1. auto.\n\n      Set Nested Proofs Allowed.\n\n      eapply eutt_inv_ret_l. eapply eqit_mon; auto.\n      2 : eauto.\n      intros * []; auto.\n    }\n\n    intros * [].\n\n    efinal.\n\n    specialize (EQ1 u2).\n\n    setoid_rewrite (itree_eta (t4 u2)).\n    setoid_rewrite (itree_eta (t4 u2)) in EQ1.\n    destruct (observe (t4 u2)) eqn: EQ'; [ | | inv e].\n    apply eqit_Ret. split; eauto.\n    apply eqit_inv_Ret in EQ1. destruct EQ1.\n    specialize (PC2 _ H0).\n    setoid_rewrite (itree_eta (t4 u2)) in PC2.\n    setoid_rewrite (itree_eta t1) in PC2.\n    rewrite EQ', EQ in PC2. apply eqit_inv_Ret in PC2. destruct PC2. auto.\n\n\n    specialize (PC2 _ H0).\n    setoid_rewrite (itree_eta t1) in PC2.\n    rewrite EQ in PC2.\n    setoid_rewrite (itree_eta (t4 u2)) in PC2.\n    rewrite EQ' in PC2.\n\n    eapply eqit_mon; auto; cycle 1.\n    eapply eqit_trans; cycle 2.\n    apply eqit_Ret. Unshelve. 7 : exact (fun x y => QQ x /\\ QQ y). cbn. split; auto.\n    eapply eutt_inv_ret_l. eapply eqit_mon; auto; cycle 1. eapply PC2.\n    intros * []; auto. apply PC2.\n    intros * []; auto. destruct REL1, REL2. split; auto.\n\n  - (* Tau *)\n    clear CIH0.\n\n    (* specialize (EQ1 i). *)\n    setoid_rewrite (itree_eta t3).\n    destruct (observe t3) eqn: EQ'; [ | | inv e]; cycle 1.\n\n    + rewrite !bind_tau.\n\n      assert (t1 ≈ t). rewrite itree_eta. rewrite EQ.\n      apply eqit_Tau_l. reflexivity.\n\n      assert (t3 ≈ t0). rewrite itree_eta. rewrite EQ'.\n      apply eqit_Tau_l. reflexivity.\n\n      estep.\n\n      ebase; right.\n      eapply CIH; eauto.\n      intros; rewrite <- H; eauto.\n      intros; rewrite <- H0; eauto.\n      intros; rewrite <- H0; eauto.\n      intros; rewrite <- H; eauto.\n\n    + rewrite bind_ret_l.\n      setoid_rewrite (itree_eta t1) in EQ1. rewrite EQ in EQ1.\n\n      setoid_rewrite <- bind_ret_r at 5.\n      ebind. econstructor.\n      Unshelve. 3 : exact (fun x y => Q1 x /\\ QQ y).\n\n      apply eutt_conj; cycle 1.\n      specialize (PC2 r). setoid_rewrite (itree_eta t1) in PC2.\n      rewrite EQ in PC2.\n      eapply eqit_mon; auto.\n      Unshelve.\n      2 : eapply eqit_flip. 2 : unfold flip.\n      5 : exact (fun _ x => QQ x). cbn. intros; auto.\n      apply eqit_flip. eapply eqit_mon; auto. 2 : eapply PC2.\n      intros * []; intuition.\n\n      setoid_rewrite (itree_eta t3) in EQ2.\n      rewrite EQ' in EQ2. eapply eutt_inv_ret_l.\n      eapply eqit_mon; auto. 2 : eapply EQ2.\n      intros * []; eauto.\n\n      eapply eqit_mon; auto; cycle 1.\n      apply EQ1. intros * []; auto.\n\n      intros * [].\n\n      efinal.\n\n      specialize (EQ1 u2).\n      setoid_rewrite (itree_eta (t2 u1)).\n      destruct (observe (t2 u1)) eqn: EQ''; [ | | inv e].\n      apply eqit_Ret. split; eauto.\n      specialize (EQ2 u1). setoid_rewrite (itree_eta (t2 u1)) in EQ2.\n      rewrite EQ'' in EQ2.\n      specialize (PC1 _ H).\n\n      setoid_rewrite (itree_eta (t2 u1)) in PC1.\n      rewrite EQ'' in PC1. clear EQ2.\n\n      eapply eutt_inv_ret_r. eapply eqit_mon; eauto; cycle 1.\n      intros * []; auto.\n\n      specialize (PC1 _ H).\n      setoid_rewrite (itree_eta (t2 u1)) in PC1.\n      rewrite EQ'' in PC1.\n      setoid_rewrite (itree_eta t3) in PC1.\n      rewrite EQ' in PC1.\n\n      eapply eqit_mon; auto; cycle 1.\n      eapply eqit_trans; cycle 2.\n      2 : apply eqit_Ret. Unshelve. 9 : exact (fun x y => QQ x /\\ QQ y). 2 : split ; auto.\n      2 : {\n        eapply eutt_inv_ret_l. eapply eqit_mon; auto; cycle 1. eapply PC1.\n        intros * []; auto.\n      }\n      apply eqit_flip. apply PC1. 2 : auto.\n      intros * []; auto. destruct REL1, REL2. split; auto.\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/Utils/Commutation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.2940586976544659}}
{"text": "From ExtLib Require Import\n     Structures.Functor\n     Structures.Monad.\n\nFrom CTree Require Import\n     Eq.\n\nImport MonadNotation.\nOpen Scope monad_scope.\nNotation BrSF := (BrF true).\nNotation BrDF := (BrF false).\n\nDefinition brs_elim {E X} (t : ctree E X) : ctree E X :=\n\tCTree.iter (fun t =>\n\t\t\t\t        match observe t with\n\t\t\t\t        | RetF r => ret (inr r)\n\t\t\t\t        | BrDF n k =>\n                    BrD n (fun x => ret (inl (k x)))\n\t\t\t\t        | BrSF n k =>\n                    BrD n (fun x => Step (ret (inl (k x))))\n\t\t\t\t        | VisF e k => bind (mtrigger _ e) (fun x => ret (inl (k x)))\n\t\t\t\t        end) t.\n\nLemma unfold_brs_elim {E X} (t : ctree E X) :\n  brs_elim t ≅\n  match observe t with\n\t| RetF r => ret r\n\t| BrDF n k =>\n      BrD n (fun x => Guard (brs_elim (k x)))\n\t| BrSF n k =>\n      BrD n (fun x => Step (Guard (brs_elim (k x))))\n\t| VisF e k => bind (mtrigger _ e) (fun x => Guard (brs_elim (k x)))\n\tend.\nProof.\n  unfold brs_elim at 1.\n  rewrite unfold_iter.\n  desobs t; cbn.\n  - now rewrite bind_ret_l.\n  - unfold mtrigger; rewrite bind_bind, !bind_trigger.\n    step; constructor; intros ?.\n    rewrite bind_ret_l.\n    reflexivity.\n  - destruct vis.\n    + rewrite bind_br.\n      step; constructor; intros ?.\n      rewrite bind_Step; step; constructor; intros ?.\n      rewrite bind_ret_l.\n      step; constructor; auto.\n    + rewrite bind_br.\n      step; constructor; intros ?.\n      rewrite bind_ret_l.\n      step; constructor; auto.\nQed.\n\nLemma trans_brs_elim_inv_strong :\n  forall {E X} (t u v : ctree E X) l,\n    (v ≅ brs_elim t \\/ v ≅ Guard (brs_elim t)) ->\n    trans l v u ->\n    exists t', trans l t t'\n          /\\ (u ≅ brs_elim t' \\/ u ≅ Guard (brs_elim t')).\nProof.\n  intros * EQ TR.\n  revert t EQ.\n  unfold trans in TR; repeat red in TR.\n  dependent induction TR.\n  - intros ? [EQ | EQ].\n    + rewrite ctree_eta, <- x, unfold_brs_elim in EQ.\n      setoid_rewrite (ctree_eta t).\n      desobs t; try now step in EQ; inv EQ.\n      destruct vis.\n      * pose proof equ_br_invT _ _ EQ as [<- _].\n        apply equ_br_invE with (x := x0) in EQ .\n        rewrite EQ in TR.\n        apply trans_step_inv in TR as [EQ' ->].\n        eexists; split; eauto.\n        etrans.\n\n      * pose proof equ_br_invT _ _ EQ as [<- _].\n        apply equ_br_invE with (x := x0) in EQ .\n        specialize (IHTR _ _ eq_refl eq_refl).\n        edestruct IHTR as (t' & ? & ?); eauto.\n        exists t'.\n        split.\n        eapply trans_brD with (x := x0); eauto.\n        eauto.\n\n    + rewrite ctree_eta, <- x in EQ.\n      pose proof equ_br_invT _ _ EQ as [-> _].\n      apply equ_br_invE with (x := x0) in EQ .\n      specialize (IHTR _ _ eq_refl eq_refl).\n      edestruct IHTR as (t' & ? & ?); eauto.\n\n  - (* G(t) ≅ BrS k : absurd *)\n    intros ? [EQ | EQ].\n    + rewrite ctree_eta, <- x1, unfold_brs_elim in EQ.\n      desobs t0; try now step in EQ; inv EQ.\n      destruct vis; try now step in EQ; inv EQ.\n    + rewrite ctree_eta, <- x1 in EQ.\n      now step in EQ; inv EQ.\n\n  - (* G(t) ≅ Vis e k : t ≅ Vis e k', k x ≅ Guard (G (k' x)) *)\n    intros ? [EQ | EQ].\n    + setoid_rewrite (ctree_eta t0).\n      rewrite ctree_eta, <- x1, unfold_brs_elim in EQ.\n      rewrite (ctree_eta t), x in H.\n      clear t x.\n      desobs t0; try now step in EQ; inv EQ.\n      2:destruct vis; try now step in EQ; inv EQ.\n      cbn in *.\n      unfold mtrigger in EQ; rewrite bind_trigger in EQ.\n      pose proof equ_vis_invT _ _ _ _ EQ; subst.\n      pose proof equ_vis_invE _ _ _ _ EQ as [-> EQ'].\n      eexists; split.\n      etrans.\n      rewrite <- ctree_eta in H.\n      rewrite <- H.\n      rewrite EQ'.\n      auto.\n    + rewrite ctree_eta, <- x1 in EQ.\n      now step in EQ; inv EQ.\n\n  - (* G(t) ≅ Ret x : t ≅ Ret x *)\n    intros ? [EQ | EQ].\n    + setoid_rewrite (ctree_eta t).\n      rewrite ctree_eta, <- x0, unfold_brs_elim in EQ.\n      desobs t; try now step in EQ; inv EQ.\n      2:destruct vis; try now step in EQ; inv EQ.\n      step in EQ; inv EQ.\n      eexists; split.\n      etrans.\n      left.\n      rewrite ctree_eta, <- x, unfold_brs_elim.\n      cbn.\n      rewrite ! brD0_always_stuck.\n      reflexivity.\n    + rewrite ctree_eta, <- x0 in EQ.\n      now step in EQ; inv EQ.\nQed.\n\nLemma trans_brs_elim_inv :\n  forall E X (t u : ctree E X) l,\n    trans l (brs_elim t) u ->\n    exists t', trans l t t'\n          /\\ u ~ brs_elim t'.\nProof.\n  intros.\n  edestruct @trans_brs_elim_inv_strong as (t' & TR & EQ); [|eassumption|].\n  left; eauto.\n  exists t'; split; auto.\n  destruct EQ as [EQ |EQ]; rewrite EQ; auto.\n  rewrite sb_guard; auto.\nQed.\n\nLtac fold_bind :=\n  repeat match goal with\n           |- context [CTree.subst ?k ?t] => fold (CTree.bind t k)\n         end.\n\n#[global] Instance brs_elim_equ E X : Proper (equ eq ==> equ eq) (@brs_elim E X).\nProof.\n  do 2 red.\n  coinduction ? IH.\n  intros * EQ.\n  step in EQ.\n  rewrite ! unfold_brs_elim.\n  cbn*.\n  inv EQ; auto.\n  - cbn.\n    constructor; intros ?.\n    fold_bind; rewrite ! bind_ret_l.\n    step; constructor; intros _.\n    auto.\n  - destruct b; cbn.\n    all: constructor; intros ?.\n    all: repeat (step; constructor; intros ?).\n    all: auto.\nQed.\n\nOpaque CTree.bind.\nLemma trans_brs_elim_strong :\n  forall E X (t u : ctree E X) l,\n    trans l t u ->\n    exists u',\n      trans l (brs_elim t) u'\n      /\\ (u' ≅ brs_elim u\n         \\/ u' ≅ Guard (brs_elim u)).\nProof.\n  intros * TR.\n  (* revert t EQ. *)\n  unfold trans in TR; repeat red in TR.\n  dependent induction TR; intros.\n  - (* destruct EQ as [EQ | EQ]. *)\n    edestruct IHTR as (u' & TR' & EQ'); eauto.\n    setoid_rewrite unfold_brs_elim at 1; rewrite <- x.\n    exists u'; split.\n    eapply trans_brD with (x := x0); [| reflexivity].\n    now apply trans_guard.\n    auto.\n  - setoid_rewrite unfold_brs_elim at 1; rewrite <- x1.\n    eexists; split.\n    eapply trans_brD with (x := x0); [| reflexivity].\n    etrans.\n    right.\n    step; constructor; intros ?.\n    rewrite H.\n    rewrite (ctree_eta t0),x,<- ctree_eta.\n    auto.\n  - setoid_rewrite unfold_brs_elim at 1; rewrite <- x1.\n    eexists; split.\n    unfold mtrigger, MonadTrigger_ctree; cbn.\n    rewrite bind_trigger.\n    etrans.\n    right.\n    step; constructor; intros ?.\n    rewrite H.\n    rewrite (ctree_eta t0),x,<- ctree_eta.\n    auto.\n  - setoid_rewrite unfold_brs_elim at 1; rewrite <- x0.\n    eexists; split.\n    (*\n      Why do I need to cbn even if I add:\n      Hint Unfold ret Monad_ctree : trans.\n     *)\n    cbn; etrans.\n    left.\n    rewrite unfold_brs_elim, <- x; cbn.\n    now rewrite ! brD0_always_stuck.\nQed.\n\nLemma trans_brs_elim :\n  forall E X (t u : ctree E X) l,\n    trans l t u ->\n    exists u',\n      trans l (brs_elim t) u'\n      /\\ u' ~ brs_elim u.\nProof.\n  intros * TR.\n  edestruct trans_brs_elim_strong as (u' & TR' & EQ'); eauto.\n  exists u'; split; auto.\n  destruct EQ' as [EQ' | EQ']; rewrite EQ'; auto.\n  now rewrite sb_guard.\nQed.\n\nLtac sret  := apply step_sb_ret.\nLtac svis  := apply step_sb_vis.\nLtac sStep := apply step_sb_step.\nLtac sstep := sret || svis || sStep.\n\nLemma brs_elim_is_bisimilar {E X} : forall (t : ctree E X),\n    brs_elim t ~ t.\nProof.\n  coinduction ? IH.\n  intros t.\n  rewrite (ctree_eta t) at 2.\n  rewrite unfold_brs_elim.\n  desobs t.\n  - now cbn.\n  - cbn*.\n    unfold mtrigger; rewrite bind_trigger.\n    sstep; intros ?.\n    rewrite sb_guard.\n    apply IH.\n  - destruct vis.\n    + cbn.\n      split; intros ? ? TR.\n      * inv_trans.\n        subst.\n        eexists.\n        eapply trans_brS with (x := n0).\n        rewrite EQ.\n        rewrite sb_guard.\n        apply IH.\n      * cbn.\n        inv_trans; subst.\n        eexists.\n        eapply trans_brD with (x := n0).\n        2:etrans.\n        etrans.\n        rewrite sb_guard.\n        rewrite EQ; apply IH.\n    + split.\n      * intros ? ? TR.\n        cbn.\n        inv_trans.\n        edestruct trans_brs_elim_inv as (u' & TR' & EQ'); eauto.\n        eexists.\n        eapply trans_brD with (x := n0); [| reflexivity].\n        eassumption.\n        rewrite EQ'; auto.\n      * cbn; intros ? ? TR.\n        inv_trans.\n        edestruct trans_brs_elim as (u' & TR' & EQ'); eauto.\n        eexists.\n        eapply trans_brD with (x := n0); [| reflexivity].\n        apply trans_guard.\n        eauto.\n        rewrite EQ'; auto.\nQed.\n", "meta": {"author": "ctrees-popl23", "repo": "ctrees-popl23", "sha": "f3cf2d6325e7e75e12d67bf263b6b5e0ec775b98", "save_path": "github-repos/coq/ctrees-popl23-ctrees-popl23", "path": "github-repos/coq/ctrees-popl23-ctrees-popl23/ctrees-popl23-f3cf2d6325e7e75e12d67bf263b6b5e0ec775b98/theories/Misc/brSElim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.294045617964153}}
{"text": "Set Implicit Arguments.\n\nRequire Import Coq.Lists.List.\nRequire Import Bag.TotalOrder.\nRequire Import Bag.Bag2.\nRequire Import Common.Types.\nRequire Import FwOF.FwOFSignatures.\n\nLocal Open Scope list_scope.\nLocal Open Scope equiv_scope.\nLocal Open Scope bag_scope.\n\nModule Make (Atoms_ : ATOMS) <: MACHINE.\n\n  Module Atoms := Atoms_.\n  Import Atoms.\n\n  Existing Instances TotalOrder_packet TotalOrder_switchId TotalOrder_portId\n    TotalOrder_flowTable TotalOrder_flowMod TotalOrder_fromSwitch\n    TotalOrder_fromController.\n\n  (* Field names have two purposes. Coq creates selectors with these names,\n     and also uses them to generate variable names in proofs. We spend\n     more time in FwOF proofs, so we pick short names here. *)\n  Record switch := Switch {\n    swId : switchId;\n    pts : list portId;\n    tbl : flowTable;\n    inp : bag (PairOrdering portId_le packet_le);\n    outp :  bag (PairOrdering portId_le packet_le);\n    ctrlm : bag fromController_le;\n    switchm : bag fromSwitch_le\n  }.\n\n  (* TODO(arjun): fix *)\n  Inductive switch_le : switch -> switch -> Prop :=\n  | SwitchLe : forall sw1 sw2,\n      switchId_le (swId sw1) (swId sw2) ->\n      switch_le sw1 sw2.\n\n  Axiom Instance TotalOrder_switch : TotalOrder switch_le.\n  \n  Record dataLink := DataLink {\n    src : switchId * portId;\n    pks : list packet;\n    dst : switchId * portId\n  }.\n  \n  Record openFlowLink := OpenFlowLink {\n    of_to : switchId;\n    of_switchm : list fromSwitch;\n    of_ctrlm : list fromController\n  }.\n\n  Definition observation := (switchId * portId * packet) %type.\n\n  (* NOTE(arjun): Ask me in person why exactly I picked these levels. *)\n  Reserved Notation \"SwitchStep[ sw ; obs ; sw0 ]\"\n    (at level 70, no associativity).\n  Reserved Notation \"ControllerOpenFlow[ c ; l ; obs ; c0 ; l0 ]\"\n    (at level 70, no associativity).\n  Reserved Notation \"TopoStep[ sw ; link ; obs ; sw0 ; link0 ]\"\n    (at level 70, no associativity).\n  Reserved Notation \"SwitchOpenFlow[ s ; l ; obs ; s0 ; l0 ]\"\n    (at level 70, no associativity).\n\n  Inductive NotBarrierRequest : fromController -> Prop :=\n  | PacketOut_NotBarrierRequest : forall pt pk,\n      NotBarrierRequest (PacketOut pt pk)\n  | FlowMod_NotBarrierRequest : forall fm,\n      NotBarrierRequest (FlowMod fm).\n\n  (** Devices of the same type do not interact in a single\n      step. Therefore, we never have to permute the lists below. If we\n      instead had just one list of all devices, we would have to worry\n      about permuting the list or define symmetric step-rules. *)\n  Record state := State {\n    switches : bag switch_le;\n    links : list dataLink;\n    ofLinks : list openFlowLink;\n    ctrl : controller\n  }.\n\n  Inductive step : state -> option observation -> state -> Prop :=\n  | PktProcess : forall swId pts tbl pt pk inp outp ctrlm switchm outp'\n                        pksToCtrl,\n    process_packet tbl pt pk = (outp', pksToCtrl) ->\n    SwitchStep[\n      Switch swId pts tbl ({|(pt,pk)|} <+> inp) outp ctrlm switchm;\n      Some (swId,pt,pk);\n      Switch swId pts tbl inp (from_list outp' <+> outp) \n        ctrlm (from_list (map (PacketIn pt) pksToCtrl) <+> switchm)\n    ]\n  | ModifyFlowTable : forall swId pts tbl inp outp fm ctrlm switchm,\n    SwitchStep[\n      Switch swId pts tbl inp outp ({|FlowMod fm|} <+> ctrlm) switchm;\n      None;\n      Switch swId pts (modify_flow_table fm tbl) inp outp ctrlm switchm\n    ]\n  | SendPacketOut : forall pt pts swId tbl inp outp pk ctrlm switchm,\n    SwitchStep[\n      Switch swId pts tbl inp outp  ({|PacketOut pt pk|} <+> ctrlm) switchm;\n      None;\n      Switch swId pts tbl inp ({| (pt,pk) |} <+> outp) ctrlm switchm\n    ]\n  | SendDataLink : forall swId pts tbl inp pt pk outp ctrlm switchm pks dst,\n    TopoStep[\n      Switch swId pts tbl inp ({|(pt,pk)|} <+> outp) ctrlm switchm;\n      DataLink (swId,pt) pks dst;\n      None;\n      Switch swId pts tbl inp outp ctrlm switchm;\n      DataLink (swId,pt) (pk :: pks) dst\n    ]\n  | RecvDataLink : forall swId pts tbl inp outp ctrlm switchm src pks pk pt,\n    TopoStep[\n      Switch swId pts tbl inp outp ctrlm switchm;\n      DataLink src  (pks ++ [pk]) (swId,pt);\n      None;\n      Switch swId pts tbl ({|(pt,pk)|} <+> inp) outp ctrlm switchm;\n      DataLink src pks (swId,pt)\n    ]\n  | Step_controller : forall sws links ofLinks ctrl ctrl',\n    controller_step ctrl ctrl' ->\n    step (State sws links ofLinks ctrl)\n         None\n         (State sws links ofLinks ctrl')\n  | ControllerRecv : forall ctrl msg ctrl' swId fromSwitch fromCtrl,\n    controller_recv ctrl swId msg ctrl' ->\n    ControllerOpenFlow[\n      ctrl;\n      OpenFlowLink swId (fromSwitch ++ [msg]) fromCtrl;\n      None;\n      ctrl';\n      OpenFlowLink swId fromSwitch fromCtrl\n    ]\n  | ControllerSend : forall ctrl msg ctrl' swId fromSwitch fromCtrl,\n    controller_send ctrl ctrl' swId msg ->\n    ControllerOpenFlow[\n      ctrl ;\n      (OpenFlowLink swId fromSwitch fromCtrl);\n      None;\n      ctrl';\n      (OpenFlowLink swId fromSwitch (msg :: fromCtrl)) ]\n  | SendToController : forall swId pts tbl inp outp ctrlm msg switchm fromSwitch\n      fromCtrl,\n    SwitchOpenFlow[\n      Switch swId pts tbl inp outp ctrlm ({| msg |} <+> switchm);\n      OpenFlowLink swId fromSwitch fromCtrl;\n      None;\n      Switch swId pts tbl inp outp ctrlm switchm;\n      OpenFlowLink swId (msg :: fromSwitch) fromCtrl\n    ]\n  | RecvBarrier : forall swId pts tbl inp outp switchm fromSwitch fromCtrl\n      xid,\n    SwitchOpenFlow[\n      Switch swId pts tbl inp outp empty switchm;\n      OpenFlowLink swId fromSwitch (fromCtrl ++ [BarrierRequest xid]);\n      None;\n      Switch swId pts tbl inp outp empty\n             ({| BarrierReply xid |} <+> switchm);\n      OpenFlowLink swId fromSwitch fromCtrl\n    ]\n  | RecvFromController : forall swId pts tbl inp outp ctrlm switchm\n      fromSwitch fromCtrl msg,\n    NotBarrierRequest msg ->\n    SwitchOpenFlow[\n      Switch swId pts tbl inp outp ctrlm switchm;\n      OpenFlowLink swId fromSwitch (fromCtrl ++ [msg]);\n      None;\n      Switch swId pts tbl inp outp ({| msg |} <+> ctrlm) switchm;\n      OpenFlowLink swId fromSwitch fromCtrl\n    ]\n      where\n  \"ControllerOpenFlow[ c ; l ; obs ; c0 ; l0 ]\" := \n    (forall sws links ofLinks ofLinks',\n      step (State sws links (ofLinks ++ l :: ofLinks') c) \n           obs \n           (State sws links (ofLinks ++ l0 :: ofLinks') c0))\n    and\n  \"TopoStep[ sw ; link ; obs ; sw0 ; link0 ]\" :=\n    (forall sws links links0 ofLinks ctrl,\n      step \n      (State (({|sw|}) <+> sws) (links ++ link :: links0) ofLinks ctrl)\n      obs\n      (State (({|sw0|}) <+> sws) (links ++ link0 :: links0) ofLinks ctrl))\n    and\n  \"SwitchStep[ sw ; obs ; sw0 ]\" :=\n    (forall sws links ofLinks ctrl,\n      step \n        (State (({|sw|}) <+> sws) links ofLinks ctrl)\n        obs\n        (State (({|sw0|}) <+> sws) links ofLinks ctrl))\n    and\n  \"SwitchOpenFlow[ sw ; of ; obs ; sw0 ; of0 ]\" :=\n    (forall sws links ofLinks ofLinks0 ctrl,\n      step\n        (State (({|sw|}) <+> sws) links (ofLinks ++ of :: ofLinks0) ctrl)\n        obs\n        (State (({|sw0|}) <+> sws) links (ofLinks ++ of0 :: ofLinks0) ctrl)).\n\n\n  Definition swPtPks : Type :=\n    bag (PairOrdering (PairOrdering switchId_le portId_le)\n                      packet_le).\n\n  Definition abst_state := swPtPks.\n\n  Definition transfer (sw : switchId) (ptpk : portId * packet) :=\n    match ptpk with\n      | (pt,pk) =>\n        match topo (sw,pt) with\n          | Some (sw',pt') => \n            @singleton _ \n               (PairOrdering \n                  (PairOrdering switchId_le portId_le) packet_le)\n               (sw',pt',pk) \n          | None => {| |}\n        end\n    end.\n\n  Definition select_packet_out (sw : switchId) (msg : fromController) :=\n    match msg with\n      | PacketOut pt pk => transfer sw (pt,pk)\n      | _ => {| |}\n    end.\n\n  Definition select_packet_in (sw : switchId) (msg : fromSwitch) :=\n    match msg with\n      | PacketIn pt pk => unions (map (transfer sw) (abst_func sw pt pk))\n      | _ => {| |}\n    end.\n\n  Definition FlowTableSafe (sw : switchId) (tbl : flowTable) : Prop :=\n    forall pt pk forwardedPkts packetIns,\n      process_packet tbl pt pk = (forwardedPkts, packetIns) ->\n      unions (map (transfer sw) forwardedPkts) <+>\n      unions (map (select_packet_in sw) (map (PacketIn pt) packetIns)) =\n      unions (map (transfer sw) (abst_func sw pt pk)).\n\n  Inductive NotFlowMod : fromController -> Prop :=\n  | NotFlowMod_BarrierRequest : forall n, NotFlowMod (BarrierRequest n)\n  | NotFlowMod_PacketOut : forall pt pk, NotFlowMod (PacketOut pt pk).\n\n  Inductive FlowModSafe : switchId -> flowTable -> bag fromController_le -> Prop :=\n  | NoFlowModsInBuffer : forall swId tbl ctrlm,\n      (forall msg, In msg (to_list ctrlm) -> NotFlowMod msg) ->\n      FlowTableSafe swId tbl ->\n      FlowModSafe swId tbl ctrlm\n  | OneFlowModsInBuffer : forall swId tbl ctrlm f,\n      (forall msg, In msg (to_list ctrlm) -> NotFlowMod msg) ->\n      FlowTableSafe swId tbl ->\n      FlowTableSafe swId (modify_flow_table f tbl) ->\n      FlowModSafe swId tbl (({|FlowMod f|}) <+> ctrlm).\n \n  Definition FlowTablesSafe (sws : bag switch_le) : Prop :=\n    forall swId pts tbl inp outp ctrlm switchm,\n      In (Switch swId pts tbl inp outp ctrlm switchm) (to_list sws) ->\n      FlowModSafe swId tbl ctrlm.\n\n  Definition SwitchesHaveOpenFlowLinks (sws : bag switch_le) ofLinks :=\n    forall sw,\n      In sw (to_list sws) ->\n      exists ofLink,\n        In ofLink ofLinks /\\\n        swId sw = of_to ofLink.\n\nEnd Make.\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/FwOF/FwOFMachine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.294045617964153}}
{"text": "From Minirust.def Require Import ty encoding thm wf le utils.\nFrom Minirust.proof Require Import defs.\nFrom Minirust.proof.lemma Require Import utils subslice le.\nRequire Import List Nat PeanoNat Bool Lia ssreflect.\nImport ListNotations.\n\nSection tuple.\n\nContext {memory: Memory}.\nContext {fields: Fields}.\nContext {size: Size}.\n\nNotation t := (TTuple fields size).\nContext (props_IH : Forall (fun ty : Ty => wf ty -> Props ty) (map snd fields)).\nContext (Hwf: wf t).\n\nLemma fields_fit_size_l : fields_fit_size fields size.\napply Hwf.\nQed.\n\n(* the `i < size` argument is not really required here. It's only for historical reasons *)\nLemma fields_disjoint_l : forall i j1 j2, i < size -> j1 < length fields -> j2 < length fields -> j1 <> j2 ->\ncontains i (interval_of_field (nth j1 fields (0,TBool))) = true ->\ncontains i (interval_of_field (nth j2 fields (0, TBool))) = false.\nProof.\nintros.\ninversion Hwf.\ninversion H5.\ninversion H7.\napply (H9 i j1 j2); auto.\nQed.\n\nLemma props_fields : Forall Props (map snd fields).\nProof.\nassert (Forall wf (map snd fields)). {\n  inversion Hwf as (_ & _ & H & _).\n  clear Hwf.\n  induction fields. { apply Forall_nil. }\n  simpl.\n  destruct a as [_left x].\n  simpl in H.\n  apply Forall_cons.\n  { inversion H. auto. }\n\n  apply IHf.\n  { simpl in props_IH. inversion props_IH. auto. }\n  { inversion H. auto. }\n}\n\nclear Hwf.\ninduction fields. { apply Forall_nil. }\n\napply Forall_cons.\n{ inversion props_IH. apply H2. inversion H. auto. }\n\napply IHf.\n{ inversion props_IH. auto. }\n{ inversion H. auto. }\nQed.\n\n\nLemma dec_to_enc {vals l} a\n(Hl: length l = size)\n(Ha: length a = size)\n(H : transpose (map (decode_tuple_field decode l) fields) = Some vals)\n: exists l', encode_tuple_fields a fields encode vals = Some l' /\\ length l' = size.\nProof.\npose proof props_fields as Hprops.\npose proof fields_fit_size_l as Hfit.\n\nclear Hwf.\nclear props_IH.\n\ngeneralize dependent fields.\ngeneralize dependent a.\n\ninduction vals as [|v vals IH]. {\n  intros. destruct fields0. { simpl. eexists _. auto. }\n  pose proof transpose_len H.\n  rewrite map_length in H0.\n  discriminate H0.\n}\n\nintros a Ha fs H Hprops Hfit.\ndestruct fs as [|[off ty] fs].\n{ pose proof transpose_len H. discriminate H0. }\n\nsimpl.\n\nassert (exists ll, decode ty ll = Some v). {\n  simpl in H.\n  set D := (subslice_with_length _ _ _) in H.\n  destruct (decode ty D) eqn:E; cycle 1. { discriminate H. }\n  set tr := transpose _ in H.\n  destruct tr; cycle 1. { simpl in H. discriminate H. }\n  simpl in H.\n  exists D.\n  rewrite E.\n  inversion H. auto.\n}\n\nassert (Props ty). { inversion Hprops. auto. }\n\ndestruct (PR_RT1 _ H1 v H0) as (ll & Henc & _).\nrewrite Henc.\nsimpl.\n\nset a' := (write_subslice_at_index _ _ _).\nrefine (IH a' _ fs _ _ _ ).\n{ apply write_subslice_length. auto.\n{ inversion Hfit.\n  simpl in H4.\n  rewrite Ha.\n  rewrite (PR_ENCODE_LEN _ H1 v ll Henc).\n  auto.\n}\n}\n{ simpl in H.\n  destruct (decode ty (subslice_with_length l off (ty_size ty))); cycle 1. { discriminate H. }\n  destruct (transpose (map (decode_tuple_field decode l) fs)); cycle 1. { discriminate H. }\n  inversion H.\n  auto.\n}\n{ inversion Hprops. auto. }\n{ inversion Hfit. auto. }\nQed.\n\nLemma tuple_dec [l v] (H: decode t l = Some v) :\n  length l = size /\\\n  exists vals,\n  transpose (map (decode_tuple_field decode l) fields) = Some vals /\\\n  v = VTuple vals /\\\n  exists l', encode t v = Some l' /\\ length l' = size.\nProof.\nunfold decode in H. fold decode in H. unfold decode_tuple in H.\nset tr := transpose _ in H.\ndestruct tr as [vals|] eqn:Htr; cycle 1. { discriminate H. }\n\nsimpl in H.\ndestruct (Nat.eqb_spec (length l) size); cycle 1. { discriminate H. }\n\nsplit. { auto. }\nexists vals.\nsimpl in H. inversion H. clear H v H1.\n\nset H1 := transpose _ = Some vals.\nassert (H1). { auto. }\nunfold H1 in *. clear H1.\n\nsplit; auto.\nsplit; auto.\n\nunfold encode. fold encode. unfold encode_tuple.\n\nunfold assuming.\nsimpl.\n\nassert (length vals = length fields). {\n  rewrite <- (transpose_len H).\n  apply map_length.\n}\n\ndestruct (Nat.eqb_spec (length vals) (length fields)); cycle 1. { lia. }\n\nsimpl.\n\nrefine (dec_to_enc _ e _ H).\napply repeat_length.\nQed.\n\nLemma tuple_encode_len : encode_len t.\nProof.\nintros v l Henc.\nunfold encode in Henc. fold encode in Henc. unfold encode_tuple in Henc.\ndestruct v as [| | |vals|]; try discriminate Henc.\nsimpl in Henc.\nunfold assuming in Henc.\ndestruct (length vals =? length fields); try discriminate Henc.\nsimpl in Henc.\n\n(* note that we cannot prove `length vals = length fields` *)\n(* it's not a problem though, encode_tuple_fields terminates when one of the lists is empty *)\n\nassert (forall a, length a = size -> forall ll, encode_tuple_fields a fields encode vals = Some ll -> length ll = size); cycle 1. {\n  simpl.\n  refine (H (repeat Uninit size) _ l Henc).\n  apply repeat_length.\n}\n\npose proof fields_fit_size_l as Hfit.\npose proof props_fields as Hprops.\nclear props_IH Hwf Henc.\ngeneralize dependent vals.\n\ninduction fields as [|[off sub_ty] fs IH].\n{ intros. simpl in H0. inversion H0. rewrite <- H2. auto. }\n\nintros.\ndestruct vals as [|v vals].\n{ simpl in H0. inversion H0. rewrite <- H2. auto. }\n\nsimpl in H0.\ndestruct (encode sub_ty v) eqn:E; cycle 1.\n{ simpl in H0. discriminate H0. }\n\nsimpl in H0.\nrefine (IH _ _ vals (write_subslice_at_index a off l0) _ _ _); auto.\n{ inversion Hfit. auto. }\n{ inversion Hprops. auto. }\napply write_subslice_length; auto.\ninversion Hfit.\nsimpl in H3.\nrewrite H.\ninversion Hprops.\nrewrite (PR_ENCODE_LEN _ H7 _ _ E).\nauto.\nQed.\n\nLemma encode_nth_some {l off sub_ty j vals} def\n  (Hj : j < length fields)\n  (Hvals_len : length vals = length fields)\n  (Hfieldsj : nth j fields (0, TBool) = (off, sub_ty))\n  (H : encode_tuple_fields (repeat Uninit size) fields encode vals = Some l)\n: exists subl, encode sub_ty (nth j vals def) = Some subl.\nProof.\npose proof (repeat_length Uninit size) as Ha.\npose proof props_fields as Hprops.\npose proof fields_fit_size_l as Hfit.\n\nclear props_IH Hwf.\n\ngeneralize dependent (repeat Uninit size).\ngeneralize dependent vals.\ngeneralize dependent j.\ninduction fields as [|[off' sub_ty'] fs IH].\n{ simpl in *. lia. }\n\nintros.\ndestruct vals as [|v vals].\n{ simpl in *. lia. }\n\ndestruct j as [|j]. {\n  simpl in *.\n  destruct (encode sub_ty' v) eqn:E; try discriminate.\n  simpl in H.\n  exists l1.\n  inversion Hfieldsj.\n  rewrite <- H2.\n  auto.\n}\n\nsimpl.\nsimpl in H.\ndestruct (encode sub_ty' v) eqn:E; try discriminate.\nsimpl in H.\nrefine (IH _ _ j _ _ vals _ _ H _); auto.\n{ inversion Hprops. auto. }\n{ inversion Hfit. auto. }\n{ simpl in *. lia. }\n\napply write_subslice_length. { auto. }\nrewrite Ha.\nassert (length l1 = ty_size sub_ty') as ->. {\n  inversion Hprops.\n  apply (PR_ENCODE_LEN _ H2 _ _ E).\n}\ninversion Hfit.\nsimpl in H2.\nauto.\nQed.\n\nLemma encode_nth_rest {fs i vals a r l}\n  (Hfit: fields_fit_size fs size)\n  (Hprops: Forall Props (map snd fs))\n  (H : existsb (contains i) (map interval_of_field fs) = false)\n  (Hi: i < size)\n  (Ha_len : length a = size)\n  (Hlens : length vals = length fs)\n  (Hr: nth i a Uninit = r)\n  (Henc: encode_tuple_fields a fs encode vals = Some l)\n: nth i l Uninit = r.\nProof.\nclear props_IH Hwf.\n\ngeneralize dependent vals.\ngeneralize dependent a.\n\ninduction fs as [|[off sub_ty] fs IH].\n{ intros. simpl in Henc. inversion Henc. rewrite <- H1. auto. }\n\nintros.\ndestruct vals as [|v vals].\n{ simpl in *. discriminate. }\n\nsimpl in Henc.\ndestruct (encode sub_ty v) eqn:E'; try discriminate.\nsimpl in Henc.\n\nsimpl in H.\ndestruct (contains i (off, ty_size sub_ty)) eqn:E; try discriminate.\nsimpl in H.\n\nassert (length l0 = ty_size sub_ty) as Hl0. {\n  inversion Hprops.\n  apply (PR_ENCODE_LEN _ H2 _ _ E').\n}\n\nrefine (IH _ _ _ (write_subslice_at_index a off l0) _ _ vals _ _); auto.\n{ inversion Hfit. auto. }\n{ inversion Hprops. auto. }\n{ apply write_subslice_length; auto.\n  rewrite Hl0.\n  inversion Hfit.\n  simpl in H2.\n  rewrite Ha_len.\n  auto.\n}\n{ rewrite <- Hl0 in E.\n  rewrite <- Hr.\n  refine (subslice_write_nth_miss _ E).\n  rewrite Hl0.\n  rewrite Ha_len.\n  inversion Hfit.\n  simpl in H2.\n  auto.\n}\nQed.\n\nLemma encode_nth_miss {i vals l}\n  (H : existsb (contains i) (map interval_of_field fields) = false)\n  (Hi: i < size)\n  (Hlens : length vals = length fields)\n  (Henc: encode_tuple_fields (repeat Uninit size) fields encode vals = Some l)\n: nth i l Uninit = Uninit.\nProof.\nrefine (encode_nth_rest fields_fit_size_l props_fields H Hi _ Hlens _ Henc).\n{ apply repeat_length. }\n{ apply nth_repeat. }\nQed.\n\nLemma encode_nth_hit {i l j vals} def\n  (Hj : j < length fields)\n  (Hvals_len : length vals = length fields)\n  (H : encode_tuple_fields (repeat Uninit size) fields encode vals = Some l)\n  (Hcont : contains i (interval_of_field (nth j fields (0,TBool))) = true)\n: let (off, sub_ty) := nth j fields (0, TBool) in\nexists subl, encode sub_ty (nth j vals def) = Some subl /\\  nth i l Uninit = nth (i-off) subl Uninit.\nProof.\npose proof (repeat_length Uninit size) as Ha.\npose proof props_fields as Hprops.\npose proof fields_fit_size_l as Hfit.\npose proof fields_disjoint_l as Hdisj.\n\nclear props_IH Hwf.\n\ngeneralize dependent (repeat Uninit size).\ngeneralize dependent vals.\ngeneralize dependent j.\n\ninduction fields as [|f fs IH].\n{ intros. simpl in Hj. lia. }\n\nintros j Hj Hcont vals Hvals_len a H0 Ha.\n\ndestruct f as [off sub_ty] eqn:F.\n\ndestruct j as [|j]; cycle 1. {\n  destruct vals as [|v vals]. { simpl in Hvals_len. lia. }\n  simpl.\n  simpl in H0.\n  destruct (encode sub_ty v) eqn:E; cycle 1.\n  { simpl in H0. discriminate H0. }\n  refine (IH _ _ _ j _ _ vals _ (write_subslice_at_index a off l0) _ _); auto.\n  { inversion Hprops. auto. }\n  { inversion Hfit. auto. }\n  { intros i' j1 j2 Hi' Hj1 Hj2 Hdiff Ht.\n    refine (Hdisj i' (S j1) (S j2) Hi' _ _ _ _); simpl; try lia.\n    auto.\n  }\n  { simpl in Hj. lia. }\n  { apply write_subslice_length; auto.\n    rewrite Ha.\n    inversion Hprops.\n    rewrite (PR_ENCODE_LEN _ H2 _ _ E).\n    inversion Hfit.\n    simpl in H6.\n    auto.\n  }\n}\n\ndestruct vals as [|v vals].\n{ simpl in *. discriminate Hvals_len. }\n\ndestruct (encode sub_ty v) eqn:E; cycle 1.\n{ simpl in *. rewrite E in H0. discriminate. }\n\nexists l0.\nsplit. { auto. }\nsimpl in H0.\n\nassert (length l0 = ty_size sub_ty) as Hl0. {\n  inversion Hprops.\n  apply (PR_ENCODE_LEN _ H2 _ _ E).\n}\n\nassert (off + length l0 <= length a) as Hfitl0. {\n  rewrite Ha.\n  rewrite Hl0.\n  inversion Hfit.\n  apply H2.\n}\n\nassert (nth i (write_subslice_at_index a off l0) Uninit = nth (i - off) l0 Uninit). {\n  apply subslice_write_nth_hit; auto.\n  { rewrite Hl0. auto. }\n}\n\nrewrite E in H0.\nsimpl in H0.\n\nassert (i < size) as Hi. {\n  unfold contains in Hcont.\n  simpl in Hcont.\n  destruct (andb_prop _ _ Hcont) as [_ Hil].\n  destruct (Nat.ltb_spec i (off + ty_size sub_ty)); try discriminate Hil.\n  assert (off + ty_size sub_ty <= size); cycle 1. { lia. }\n  rewrite Ha in Hfitl0.\n  rewrite <- Hl0.\n  auto.\n}\n\nassert (length vals = length fs) as Hvfs_len.\n{ simpl in Hvals_len. lia. }\n\nrefine (encode_nth_rest _ _ _ Hi _ Hvfs_len H _); auto; cycle 3.\n{ apply write_subslice_length; auto. }\n{ inversion Hfit. auto. }\n{ inversion Hprops. auto. }\n\nclear - Hdisj Hcont Hi.\nsimpl in Hcont.\n\nassert (forall j, j < length fs -> contains i (interval_of_field (nth j fs (0,TBool))) = false). {\n  intros j Hj.\n  refine (Hdisj i 0 (S j) Hi _ _ _ _); try (simpl; lia).\n  simpl. auto.\n}\nclear - H.\n\ninduction fs as [|[off sub_ty] fs IH].\n{ simpl. auto. }\n\nsimpl.\nassert (contains i (off, ty_size sub_ty) = false) as ->. {\n  refine (H 0 _).\n  simpl. lia.\n}\nsimpl.\napply IH.\nintros j Hj.\nrefine (H (S j) _).\nsimpl. lia.\nQed.\n\nLemma subslice_encode {l off sub_ty j vals def}\n  (Hj : j < length fields)\n  (Hvals_len : length vals = length fields)\n  (Hfieldsj : nth j fields (0, TBool) = (off, sub_ty))\n  (Hl: length l = size)\n  (H : encode_tuple_fields (repeat Uninit size) fields encode vals = Some l)\n: Some (subslice_with_length l off (ty_size sub_ty)) = encode sub_ty (nth j vals def).\nProof.\ndestruct (encode_nth_some def Hj Hvals_len Hfieldsj H) as (l' & Henc).\nrewrite Henc.\nf_equal.\n\nassert (length (subslice_with_length l off (ty_size sub_ty)) = ty_size sub_ty). {\n  rewrite subslice_length; auto.\n  rewrite Hl.\n  pose proof fields_fit_size_l as Hfit.\n  pose proof (proj1 (Forall_nth _ _) Hfit) as Hfit_nth.\n  assert (sub_ty = nth j (map snd fields) TBool) as ->. {\n    rewrite (map_nth_switchd (0,TBool) _); auto.\n    rewrite Hfieldsj.\n    auto.\n  }\n  pose proof (Hfit_nth j (0,TBool) Hj).\n  rewrite Hfieldsj in H0.\n  simpl in H0.\n  auto.\n}\n\nassert (length l' = ty_size sub_ty). {\n  pose proof props_fields as Hprops.\n  pose proof (proj1 (Forall_nth _ _) Hprops) as Hprops_nth.\n  assert (sub_ty = nth j (map snd fields) TBool) as ->. {\n    rewrite (map_nth_switchd (0,TBool) _); auto.\n    rewrite Hfieldsj.\n    auto.\n  }\n  assert (j < length (map snd fields)) as HF.\n  { rewrite map_length. auto. }\n\n  pose proof (Hprops_nth j TBool HF).\n  apply (PR_ENCODE_LEN _ H1 _ _ Henc).\n}\n\nrefine (nth_ext _ _ Uninit Uninit _ _).\n{ rewrite H1. auto. }\nintros i Hi.\n\nassert (i < ty_size sub_ty).\n{ rewrite <- H0. auto. }\n\nrewrite subslice_nth; auto. {\n  rewrite Hl.\n  pose proof fields_fit_size_l as Hfit.\n  pose proof (proj1 (Forall_nth _ _) Hfit) as Hfit_nth.\n  assert (sub_ty = nth j (map snd fields) TBool) as ->. {\n    rewrite (map_nth_switchd (0,TBool) _); auto.\n    rewrite Hfieldsj.\n    auto.\n  }\n  pose proof (Hfit_nth j (0,TBool) Hj).\n  simpl in H3.\n  rewrite Hfieldsj in H3.\n  simpl in H3.\n  auto.\n}\n\nassert (contains (i+off) (interval_of_field (nth j fields (0, TBool))) = true). {\n  rewrite Hfieldsj.\n  unfold contains.\n  simpl.\n  destruct (Nat.leb_spec off (i + off)); try lia.\n  simpl.\n  destruct (Nat.ltb_spec (i + off) (off + ty_size sub_ty)); lia.\n}\n\npose proof (encode_nth_hit def Hj Hvals_len H H3).\nrewrite Hfieldsj in H4.\ndestruct H4 as (l'' & Henc' & ->).\nassert (l' = l'') as ->.\n{ rewrite Henc' in Henc. inversion Henc. auto. }\nf_equal.\nlia.\nQed.\n\nLemma tuple_rt1 : rt1 t.\nintros v [l Hdec].\ndestruct (tuple_dec Hdec) as (Hlen & vals & Htr & -> & l' & Henc & Hlen').\nexists l'.\nsplit. { auto. }\nunfold decode. fold decode. unfold decode_tuple.\n\nassert (length vals = length fields) as Hvals_len. {\n  rewrite <- (transpose_len Htr).\n  rewrite map_length.\n  auto.\n}\n\nassert (transpose (map (decode_tuple_field decode l') fields) = Some vals); cycle 1. {\n  rewrite H.\n  simpl.\n  rewrite (tuple_encode_len _ _ Henc).\n  simpl.\n  rewrite Nat.eqb_refl.\n  auto.\n}\n\nassert (encode_tuple_fields (repeat Uninit size) fields encode vals = Some l'). {\n  unfold encode in Henc. fold encode in Henc. unfold encode_tuple in Henc.\n  simpl in Henc.\n  unfold assuming in Henc.\n  rewrite Hvals_len in Henc.\n  rewrite Nat.eqb_refl in Henc.\n  simpl in Henc.\n  auto.\n}\n\napply (transpose_nth_ext (VBool true)).\n{ rewrite map_length. auto. }\n\nintros def j Hj.\nrewrite map_length in Hj.\nrewrite (map_nth_switchd (0,TBool)); auto.\ndestruct (nth j fields (0, TBool)) as [off sub_ty] eqn:Hfieldsj.\nunfold decode_tuple_field.\nrewrite Hfieldsj.\n\nassert (rt1 sub_ty) as Hsub_rt1. {\n  pose proof props_fields as Hprops.\n  pose proof (proj1 (Forall_nth _ _) Hprops) as Hprops_nth.\n  assert (sub_ty = nth j (map snd fields) TBool) as ->. {\n    rewrite (map_nth_switchd (0,TBool) _); auto.\n    rewrite Hfieldsj.\n    auto.\n  }\n  refine (PR_RT1 _ (Hprops_nth j _ _)).\n  rewrite map_length. auto.\n}\n\nassert (Some (subslice_with_length l' off (ty_size sub_ty)) = encode sub_ty (nth j vals def)); cycle 1. {\n  assert (decode_tuple_field decode l (nth j fields (0,TBool)) = Some (nth j vals def)). {\n    pose proof (transpose_nth Htr).\n    rewrite <- H1; cycle 1. { rewrite map_length. auto. }\n    rewrite (map_nth_switchd (0,TBool)); auto.\n  }\n  assert (is_valid_for sub_ty (nth j vals def)). {\n    unfold decode_tuple_field in H1.\n    rewrite Hfieldsj in H1.\n    eexists _.\n    apply H1.\n  }\n  destruct (Hsub_rt1 _ H2) as (lsub & Hsubenc & Hsubdec).\n  assert (lsub = subslice_with_length l' off (ty_size sub_ty)) as <-; cycle 1. { auto. }\n  rewrite <- H0 in Hsubenc.\n  inversion Hsubenc.\n  auto.\n}\n\napply subslice_encode; auto.\nQed.\n\nLemma tuple_rt2 : rt2 t.\nintros l v Hdec.\ndestruct (tuple_dec Hdec) as (Hlen & vals & Htr & -> & l' & Henc & Hlen').\nexists l'.\nsplit. { auto. }\napply (le_nth Uninit). { lia. } \nintros i Hi.\n\npose proof fields_fit_size_l as Hfit.\npose proof (proj1 (Forall_nth _ _) Hfit) as Hfit_nth.\n\npose proof props_fields as Hprops.\npose proof (proj1 (Forall_nth _ _) Hprops) as Hprops_nth.\n\nassert (length vals = length fields) as Hvals_len. {\n  pose proof transpose_len Htr.\n  rewrite <- H.\n  rewrite map_length.\n  auto.\n}\n\ndestruct (existsb (contains i) (map interval_of_field fields)) eqn:Hex; cycle 1. {\n  unfold encode in Henc. fold encode in Henc. unfold encode_tuple in Henc.\n  simpl in Henc.\n  unfold assuming in Henc.\n  rewrite Hvals_len in Henc.\n  rewrite (Nat.eqb_refl (length fields)) in Henc.\n  simpl in Henc.\n  rewrite (encode_nth_miss Hex _ Hvals_len Henc).\n  { rewrite <- Hlen'. auto. }\n  simpl.\n  auto.\n}\n\ndestruct (proj1 (existsb_exists _ _) Hex) as (interval & Hin & Hcont).\ndestruct (In_nth _ _ (0,0) Hin) as [j [Hj Hnth]].\nrewrite map_length in Hj.\n\nunfold encode in Henc. fold encode in Henc. unfold encode_tuple in Henc.\nsimpl in Henc.\nunfold assuming in Henc.\nrewrite Hvals_len in Henc.\nrewrite (Nat.eqb_refl (length fields)) in Henc.\nsimpl in Henc.\n\ndestruct (nth j fields (0, TBool)) as [off sub_ty] eqn:Hdestr.\n\nassert (off + ty_size sub_ty <= size) as Hfitsub. {\n  pose proof Hfit_nth j (0, TBool) Hj.\n  rewrite Hdestr in H.\n  simpl in H.\n  auto.\n}\n\nassert (interval = (off, ty_size sub_ty)) as ->. {\n  rewrite (map_nth_switchd (0, TBool)) in Hnth; auto.\n  rewrite Hdestr in Hnth.\n  auto.\n}\n\nassert (contains i (interval_of_field (nth j fields (0, TBool))) = true) as Hcont'. {\n  rewrite <- Hcont.\n  f_equal.\n  rewrite Hdestr.\n  auto.\n}\n\nassert (off <= i /\\ i < off + ty_size sub_ty) as [Ho1 Ho2]. {\n  unfold contains in Hcont.\n  simpl in Hcont.\n  destruct (andb_prop _ _ Hcont) as [A B].\n  split.\n  { destruct (Nat.leb_spec off i); lia. }\n  { destruct (Nat.ltb_spec i (off + ty_size sub_ty)); lia. }\n}\n\npose proof (encode_nth_hit (VBool true) Hj Hvals_len Henc Hcont') as F.\nrewrite Hdestr in F.\ndestruct F as (subl & Hsubenc & ->).\n\nassert (j < length (map (decode_tuple_field decode l) fields)) as H''.\n{ rewrite map_length. auto. }\npose proof (transpose_nth Htr (VBool true) j H'').\nrewrite (map_nth_switchd (0,TBool) Hj) in H.\nunfold decode_tuple_field in H.\nrewrite Hdestr in H.\nsimpl in H.\nreplace (nth i l Uninit) with (nth (i-off+off) l Uninit); cycle 1.\n{ f_equal. lia. }\n\nrewrite <- (@subslice_nth _ off (ty_size sub_ty) (i-off) l Uninit); try lia.\napply le_nth_rev. { apply le_abstract_byte_refl. }\nremember (nth j vals (VBool true)) as v.\nassert (Props sub_ty) as Hsubprops. {\n  assert (j < length (map snd fields)) as H'. { rewrite map_length. auto. }\n  pose proof (Hprops_nth j TBool H').\n  rewrite (map_nth_switchd (0,TBool)) in H0; auto.\n  rewrite Hdestr in H0.\n  auto.\n}\n\ndestruct (PR_RT2 _ Hsubprops _ _ H) as (ll & B & C).\nassert (subl = ll) as ->. {\n  rewrite B in Hsubenc.\n  inversion Hsubenc.\n  auto.\n}\n\nauto.\nQed.\n\nLemma tuple_mono1 : mono1 t.\nintros v1 v2 Hle [l1 Hdec1] [l2 Hdec2].\ndestruct (tuple_dec Hdec1) as (Hlen1 & vals1 & Htr1 & -> & l1' & Henc1 & Hlen1').\ndestruct (tuple_dec Hdec2) as (Hlen2 & vals2 & Htr2 & -> & l2' & Henc2 & Hlen2').\nexists l1', l2'.\nsplit. { auto. }\nsplit. { auto. }\n\napply (le_nth Uninit). { lia. }\nintros i Hi.\n\nassert (length vals1 = length fields) as Hvals_len1. {\n  apply transpose_len in Htr1.\n  rewrite map_length in Htr1.\n  auto.\n}\n\nassert (length vals2 = length fields) as Hvals_len2. {\n  apply transpose_len in Htr2.\n  rewrite map_length in Htr2.\n  auto.\n}\n\nassert (encode_tuple_fields (repeat Uninit size) fields encode vals1 = Some l1') as Henc1'. {\n  unfold encode in Henc1. fold encode in Henc1. unfold encode_tuple in Henc1.\n  simpl in Henc1.\n  unfold assuming in Henc1.\n  rewrite Hvals_len1 in Henc1.\n  rewrite (Nat.eqb_refl (length fields)) in Henc1.\n  simpl in Henc1.\n  auto.\n}\n\nassert (encode_tuple_fields (repeat Uninit size) fields encode vals2 = Some l2') as Henc2'. {\n  unfold encode in Henc2. fold encode in Henc2. unfold encode_tuple in Henc2.\n  simpl in Henc2.\n  unfold assuming in Henc2.\n  rewrite Hvals_len2 in Henc2.\n  rewrite (Nat.eqb_refl (length fields)) in Henc2.\n  simpl in Henc2.\n  auto.\n}\n\ndestruct (existsb (contains i) (map interval_of_field fields)) eqn:Hex; cycle 1. {\n  rewrite (encode_nth_miss Hex _ Hvals_len1 Henc1').\n  { rewrite <- Hlen1'. auto. }\n  simpl.\n  auto.\n}\n\ndestruct (proj1 (existsb_exists _ _) Hex) as (interval & Hin & Hcont).\ndestruct (In_nth _ _ (0,0) Hin) as [j [Hj Hnth]].\nrewrite map_length in Hj.\n\ndestruct (nth j fields (0, TBool)) as [off sub_ty] eqn:Hdestr.\n\nassert (interval = (off, ty_size sub_ty)) as ->. {\n  rewrite (map_nth_switchd (0, TBool)) in Hnth; auto.\n  rewrite Hdestr in Hnth.\n  auto.\n}\n\nassert (contains i (interval_of_field (nth j fields (0, TBool))) = true) as Hcont'. {\n  rewrite Hdestr.\n  auto.\n}\n\npose proof encode_nth_hit (VBool true) Hj Hvals_len1 Henc1' Hcont' as F1.\nrewrite Hdestr in F1.\ndestruct F1 as (subl1 & Hsubenc1 & ->).\n\npose proof encode_nth_hit (VBool true) Hj Hvals_len2 Henc2' Hcont' as F2.\nrewrite Hdestr in F2.\ndestruct F2 as (subl2 & Hsubenc2 & ->).\n\napply le_nth_rev. { apply le_abstract_byte_refl. }\n\nassert (Props sub_ty) as Hsubprops. {\n  pose proof props_fields as Hprops.\n  pose proof (proj1 (Forall_nth _ _) Hprops) as Hprops_nth.\n  assert (j < length (map snd fields)). { rewrite map_length. auto. }\n  pose proof (Hprops_nth j TBool H).\n  rewrite (map_nth_switchd (0,TBool)) in H0.\n  rewrite map_length in H; auto.\n  rewrite Hdestr in H0.\n  auto.\n}\n\nassert (decode sub_ty (subslice_with_length l1 off (ty_size sub_ty)) = Some (nth j vals1 (VBool true))) as Hdec1_. {\n  assert (j < length (map (decode_tuple_field decode l1) fields)). { rewrite map_length. auto. }\n  pose proof transpose_nth Htr1 (VBool true) j H.\n  rewrite (map_nth_switchd (0, TBool)) in H0; auto.\n  unfold decode_tuple_field in H0.\n  rewrite Hdestr in H0.\n  auto.\n}\n\nassert (is_valid_for sub_ty (nth j vals1 (VBool true))) as Hval1. {\n  exists (subslice_with_length l1 off (ty_size sub_ty)).\n  auto.\n}\n\nassert (decode sub_ty (subslice_with_length l2 off (ty_size sub_ty)) = Some (nth j vals2 (VBool true))) as Hdec2_. {\n  assert (j < length (map (decode_tuple_field decode l2) fields)). { rewrite map_length. auto. }\n  pose proof transpose_nth Htr2 (VBool true) j H.\n  rewrite (map_nth_switchd (0, TBool)) in H0; auto.\n  unfold decode_tuple_field in H0.\n  rewrite Hdestr in H0.\n  auto.\n}\n\nassert (is_valid_for sub_ty (nth j vals2 (VBool true))) as Hval2. {\n  exists (subslice_with_length l2 off (ty_size sub_ty)).\n  auto.\n}\n\nassert (le (nth j vals1 (VBool true)) (nth j vals2 (VBool true))) as Hle_vs. {\n  assert (le vals1 vals2). { auto. }\n  assert (length vals1 = length vals2). { apply (le_len H). }\n  assert (j < length vals1). { rewrite Hvals_len1. auto. }\n  refine (@le_nth_rev _ j _ _ _ (VBool true) _ H).\n  apply le_val_refl.\n}\n\nremember (nth j vals1 (VBool true)) as v1.\nremember (nth j vals2 (VBool true)) as v2.\n\ndestruct (PR_MONO1 _ Hsubprops v1 v2 Hle_vs Hval1 Hval2) as (ll1 & ll2 & He1 & He2 & Hle').\nassert (subl1 = ll1) as -> . { rewrite He1 in Hsubenc1. inversion Hsubenc1. auto. }\nassert (subl2 = ll2) as -> . { rewrite He2 in Hsubenc2. inversion Hsubenc2. auto. }\nauto.\nQed.\n\nLemma tuple_mono2 : mono2 t.\nintros l1 l2 Hle.\ndestruct (decode t l1) eqn:Hdec1; try (simpl; done).\ndestruct (tuple_dec Hdec1) as (Hlen1 & vals1 & Htr1 & -> & l1' & Henc1 & Hlen1').\nunfold decode. fold decode. unfold decode_tuple.\n\nassert (exists vals2, transpose (map (decode_tuple_field decode l2) fields) = Some vals2 /\\ le vals1 vals2) as (vals2 & Htr & Hle'); cycle 1. {\n  rewrite Htr.\n  assert (length l2 =? size = true) as ->. {\n    pose proof le_len Hle.\n    rewrite <- H.\n    rewrite Hlen1.\n    apply Nat.eqb_refl.\n  }\n  simpl.\n  auto.\n}\n\npose proof props_fields as Hprops.\npose proof fields_fit_size_l as Hfit.\n\nclear Hwf props_IH Henc1 l1' Hlen1' Hdec1.\n\nassert (length vals1 = length fields) as Hval_len1. {\n  pose proof (transpose_len Htr1).\n  rewrite map_length in H.\n  auto.\n}\n\ngeneralize dependent vals1.\n\ninduction fields as [|[off sub_ty] fs IH].\n{ intros. exists []. split. { auto. } destruct vals1; try discriminate. simpl. auto. }\n\nintros.\nsimpl map.\nsimpl map in Htr1.\n\ndestruct vals1 as [|v1 vals1]. { discriminate. }\nsimpl in Htr1.\n\ndestruct (decode sub_ty (subslice_with_length l1 off (ty_size sub_ty))) as [v1_|] eqn:E1; try discriminate.\ndestruct (transpose (map (decode_tuple_field decode l1) fs)) as [vals1_|] eqn:E2; try discriminate.\n\nsimpl in Htr1.\nassert (v1_ = v1) as ->. { inversion Htr1. auto. }\nassert (vals1_ = vals1) as ->. { inversion Htr1. auto. }\n\nassert (exists v2, decode sub_ty (subslice_with_length l2 off (ty_size sub_ty)) = Some v2 /\\ le v1 v2) as (v2 & Hdec_v2 & Hlev); cycle 1. {\n  rewrite Hdec_v2.\n  assert (Some vals1 = Some vals1). { auto. }\n  assert (length vals1 = length fs). { simpl in Hval_len1. lia. }\n  assert (Forall Props (map snd fs)) as Hp. { inversion Hprops. auto. }\n  assert (fields_fit_size fs size) as Hf. { inversion Hfit. auto. }\n  destruct (IH Hp Hf vals1 H H0) as (vals2 & Htr2 & Hle_vals2).\n  exists (v2 :: vals2).\n  split. { simpl. rewrite Htr2. simpl. auto. }\n  simpl. auto.\n}\n\nassert (length l2 = size) as Hlen2. {\n  rewrite <- (le_len Hle).\n  auto.\n}\n\nassert (size >= off + ty_size sub_ty) as Hsubfit.\n{ inversion Hfit. auto. }\n\nassert (le (subslice_with_length l1 off (ty_size sub_ty)) (subslice_with_length l2 off (ty_size sub_ty))). {\n  apply (le_nth Uninit). {\n    rewrite subslice_length. { rewrite Hlen1. auto. }\n    rewrite subslice_length. { rewrite Hlen2. auto. }\n    auto.\n  }\n  intros i Hi.\n  assert (length l1 >= off + ty_size sub_ty).\n  { rewrite Hlen1. auto. }\n\n  assert (i < ty_size sub_ty) as Hi2. {\n    rewrite (subslice_length H) in Hi.\n    auto.\n  }\n  rewrite subslice_nth. { auto. } { rewrite Hlen1. auto. }\n  rewrite subslice_nth. { auto. } { rewrite Hlen2. auto. }\n  apply le_nth_rev; auto.\n  apply le_abstract_byte_refl.\n}\nassert (Props sub_ty) as Hsubprops. { inversion Hprops. auto. }\n\npose proof PR_MONO2 _ Hsubprops _ _ H.\nrewrite E1 in H0.\ndestruct (decode sub_ty (subslice_with_length l2 off (ty_size sub_ty))); cycle 1. { contradiction. }\nexists v. split. { auto. }\nauto.\nQed.\n\nLemma tuple_props : Props t.\nProof.\nsplit.\n- auto.\n- apply tuple_rt1.\n- apply tuple_rt2.\n- apply tuple_mono1.\n- apply tuple_mono2.\n- apply tuple_encode_len.\nQed.\n\nEnd tuple.\n", "meta": {"author": "memoryleak47", "repo": "coq-minirust", "sha": "b5f0e4b7902c67cd83673272848850ad716cef32", "save_path": "github-repos/coq/memoryleak47-coq-minirust", "path": "github-repos/coq/memoryleak47-coq-minirust/coq-minirust-b5f0e4b7902c67cd83673272848850ad716cef32/proof/tuple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2940182503091819}}
{"text": "Require Import\n  Coq.Arith.Arith\n  Coq.ZArith.ZArith\n  Coq.micromega.Lia\n  Coq.Strings.String\n  Hask.Control.Monad\n  Data.Monoid\n  Data.PartialMap\n  EnsemblesExt\n  Lib\n  Ltac\n  RWSP.\n\nSet Universe Polymorphism.\n\nFrom Equations Require Import Equations.\nSet Equations With UIP.\n\nDerive NoConfusion NoConfusionHom Subterm EqDec for Ascii.ascii.\nDerive NoConfusion NoConfusionHom Subterm EqDec for string.\nDerive NoConfusion NoConfusionHom Subterm EqDec for Z.\nNext Obligation. now apply Z.eq_dec. Defined.\nDerive NoConfusion NoConfusionHom Subterm EqDec for nat.\nDerive NoConfusion NoConfusionHom Subterm EqDec for bool.\n\nGeneralizable All Variables.\n\n(** A partial magma defines a constrained version of its binary operation.\n    This operation is typically not associative, since order of operation can\n    matter. *)\nClass PartialMagma (A : Type) := {\n  pappendLim (x y : A) : option A;\n}.\n\nInstance nat_PartialMagma (limit : nat) : PartialMagma nat := {\n  pappendLim := λ (x y : nat),\n    let z := x + y in\n    if limit <? z\n    then None\n    else Some z\n}.\n\nSection Pact.\n\nImport ListNotations.\n\nInductive Ty : Set :=\n  | TUnit\n  | TPair : Ty → Ty → Ty\n  | TString\n  | TInteger\n  | TDecimal\n  | TBool\n  | TTime\n  (* | TKeyset *)\n  (* | TGuard *)\n  | TList : Ty → Ty\n  (* | TObject *)\n  (* | TFunc *)\n  (* | TPact *)\n  (* | TTable *)\n  (* | TSchema *)\n.\n\nDerive NoConfusion NoConfusionHom Subterm EqDec for Ty.\n\nFixpoint denoteTy (t : Ty) : Set :=\n  match t with\n  | TUnit     => unit\n  | TPair x y => denoteTy x * denoteTy y\n  | TString   => string\n  | TInteger  => Z\n  | TDecimal  => nat\n  | TBool     => bool\n  | TTime     => nat\n  | TList t   => list (denoteTy t)\n  end.\n\nDeclare Scope Type_scope.\nBind Scope Type_scope with Ty.\nDelimit Scope Ty_scope with ty.\n\nNotation \"⟦ t ⟧\" := (denoteTy t%ty) (at level 9) : type_scope.\n\n(* This couldn't be derived due to the recursion at [VList]. *)\nEquations Value_EqDec t : EqDec ⟦t⟧ :=\n  Value_EqDec TUnit tt tt := left _;\n  Value_EqDec (TPair t1 t2) (x1, y1) (x2, y2)\n    with @eq_dec _ (Value_EqDec t1) x1 x2 := {\n      | left  _ with @eq_dec _ (Value_EqDec (t2)) y1 y2 := {\n        | left _  => left _\n        | right _ => right _\n      }\n      | right _ => right _\n  };\n  Value_EqDec TString s1 s2\n    with eq_dec s1 s2 := {\n      | left _  => left _\n      | right _ => right _\n    };\n  Value_EqDec TInteger i1 i2\n    with eq_dec i1 i2 := {\n      | left _  => left _\n      | right _ => right _\n    };\n  Value_EqDec TDecimal d1 d2\n    with eq_dec d1 d2 := {\n      | left _  => left _\n      | right _ => right _\n    };\n  Value_EqDec TBool b1 b2\n    with eq_dec b1 b2 := {\n      | left _  => left _\n      | right _ => right _\n    };\n  Value_EqDec TTime t1 t2\n    with eq_dec t1 t2 := {\n      | left _  => left _\n      | right _ => right _\n    };\n  Value_EqDec (TList _)   ([]) ([]) := left _;\n  Value_EqDec (TList _)   ((_ :: _)) ([]) := right _;\n  Value_EqDec (TList _)   ([]) ((_ :: _)) := right _;\n  Value_EqDec (TList ty)  ((x1 :: xs1)) ((y1 :: ys1))\n    with @eq_dec _ (Value_EqDec ty) x1 y1 := {\n      | left _  with @eq_dec _ (list_eqdec (Value_EqDec ty)) xs1 ys1 := {\n        | left _  => left _\n        | right _ => right _\n      }\n      | right _ => right _\n    }.\n\n#[export]\nInstance Value_EqDec' {t} : EqDec ⟦t⟧ := Value_EqDec t.\n\n(******************************************************************************\n * Capability Semantics\n *)\n\nRecord CapSig : Set := {\n  name : string;\n  paramTy : Ty\n}.\n\nDerive NoConfusion NoConfusionHom Subterm EqDec for CapSig.\n\nRecord Cap (s : CapSig) : Set := MkCap {\n  param : ⟦paramTy s⟧\n}.\n\nDerive NoConfusion NoConfusionHom Subterm EqDec for Cap.\n\nRecord MCapSig : Set := {\n  baseSig : CapSig;\n  valueTy : Ty\n}.\n\nDerive NoConfusion NoConfusionHom Subterm EqDec for MCapSig.\n\nRecord MCap (s : MCapSig) : Set := MkMCap {\n  base : Cap (baseSig s);\n  value : ⟦valueTy s⟧\n}.\n\nDerive NoConfusion NoConfusionHom Subterm EqDec for MCap.\n\nInductive ACap : Set :=\n  | Unmanaged {csig : CapSig}  : Cap csig  → ACap\n  | Managed   {csig : MCapSig} : MCap csig → ACap.\n\nDerive NoConfusion NoConfusionHom Subterm EqDec for ACap.\n\nRecord PactEnv := {\n  granted : Ensemble ACap;\n}.\n\nRecord PactState := {\n  resources : Ensemble { s : MCapSig & ⟦valueTy s⟧ };\n}.\n\nRecord PactLog := MkPactLog {}.\n\n#[export]\nProgram Instance PactLog_Semigroup : Semigroup PactLog := {\n  mappend := λ _ _, MkPactLog\n}.\n\n#[export]\nProgram Instance PactLog_Monoid : Monoid PactLog := {\n  mempty := MkPactLog\n}.\nNext Obligation.\n  destruct a.\n  split; intros.\nQed.\nNext Obligation.\n  destruct a.\n  split; intros.\nQed.\n\nDefinition PactM := @RWSP PactEnv PactState PactLog.\n\nRecord DefCap `(s : CapSig) : Type := {\n  predicate : Cap s → PactM (Ensemble ACap)\n}.\n\nDerive NoConfusion NoConfusionHom Subterm for DefCap.\n\nArguments predicate {s} _.\n\nRecord DefMCap `(s : MCapSig) : Type := {\n  base_def : DefCap (baseSig s);\n  manager  : ⟦valueTy s⟧ → ⟦valueTy s⟧ → PactM ⟦valueTy s⟧\n}.\n\nDerive NoConfusion NoConfusionHom Subterm for DefMCap.\n\nArguments manager {s} _.\n\nImport EqNotations.\n\n(* The functions below all take a [DefCap] because name resolution must happen\n   in the parser, since capability predicates can themselves refer to the\n   current module. *)\n\nDefinition install_capability `(D : DefMCap s) (c : MCap s) : PactM () :=\n  let '(MkMCap _ (MkCap _ arg) val) := c in\n\n  (* jww (2022-07-15): This should only be possible to do in specific\n     contexts, otherwise a user could install as much resource as they needed.\n\n     jww (2022-07-15): What if the resource had already been installed? *)\n\n  (* \"Installing\" a capability means assigning a resource amount associated\n     with that capability, that is consumed by future calls to\n     [with_capability]. *)\n  modify (λ st, {| resources := insert_dep s val (resources st) |}).\n\nDefinition __claim_resource `(D : DefMCap s) (c : MCap s) : PactM () :=\n  let '(MkMCap _ (MkCap _ arg) val) := c in\n\n  (* Check the current amount of resource associated with this capability, and\n     whether the requested amount is available. If so, update the available\n     amount. Note: unit is used to represent unmanaged capabilities. *)\n  st   <- get ;\n  mng  <- demand (find_dep s (resources st)) ;\n  mng' <- manager D mng val ;\n  put {| resources := insert_dep s mng' (resources st) |}.\n\n(** [with_capability] grants a capability [C] to the evaluation of [f].\n\n    There are three results of this operation:\n\n    1. a predicate is evaluated to determine if the operation can proceed,\n       which raises an exception if not;\n\n    2. [f] is able to evaluate more permissively;\n\n    3. a resource is consumed in order to grant the capability.\n\n    (2) is easily modeled by imagining that [with_capability] introduces a\n    dynamic boolean variable (in the Lisp sense) for each capability [C] and\n    sets it to true for the scope of evaluating [f], if the predicate in (1)\n    succeeds. Later, [require_capability] tests if this boolean is true and\n    raises an exception otherwise. There is no other functionality for\n    unmanaged capabilities.\n\n    A managed capability provides the same, but in addition deducts from a\n    stateful resource after the predicate, but before defining and setting the\n    dynamic boolean. If there is not enough resource available, it raises an\n    exception. [install_capability] sets the initial amount of the\n    resource. *)\nDefinition with_capability__unmanaged `(D : DefCap s) (c : Cap s)\n           `(f : PactM a) : PactM a :=\n  let acap := Unmanaged c in\n\n  (* Check whether the capability has already been granted. If so, this\n     operation is a no-op. *)\n  env <- ask ;\n  b   <- decide (acap ∈ granted env) ;\n  if b : bool\n  then f\n  else\n    let '(MkCap _ arg) := c in\n\n    (* If the predicate passes, we are good to grant the capability. Note that\n       the predicate may return a list of other capabilities to be \"composed\"\n       with this one. *)\n    compCaps <- predicate D c ;\n\n    (* The process of \"granting\" consists merely of making the capability\n       visible in the reader environment to the provided expression. *)\n    local (λ r, {| granted := Add _ (compCaps ∪ granted r) acap |}) f.\n\nDefinition with_capability__managed `(D : DefMCap s) (c : MCap s)\n           `(f : PactM a) : PactM a :=\n  let acap := Managed c in\n\n  (* Check whether the capability has already been granted. If so, this\n     operation is a no-op. *)\n  env <- ask ;\n  b   <- decide (acap ∈ granted env) ;\n  if b : bool\n  then f\n  else\n    let '(MkMCap _ (MkCap _ arg) val) := c in\n\n    (* If the predicate passes, we are good to grant the capability. Note that\n       the predicate may return a list of other capabilities to be \"composed\"\n       with this one. *)\n    (* jww (2022-07-18): Can the predicate for a managed capability also see\n       the value passed to [with-capability]? *)\n    compCaps <- predicate (base_def s D) (base _ c) ;\n\n    __c\n\n    (* The process of \"granting\" consists merely of making the capability\n       visible in the reader environment to the provided expression. *)\n    local (λ r, {|  granted := Add _ (compCaps ∪ granted r) acap |}) f.\n\nDefinition require_capability (c : ACap) : PactM () :=\n  (* Note that the request resource amount must match the original\n     with-capability exactly.\n\n     jww (2022-07-15): Is this intended? *)\n\n  (* Requiring a capability means checking whether it has been granted at any\n     point within the current scope of evaluation. *)\n  env <- ask ;\n  require (c ∈ granted env).\n\nEnd Pact.\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/old/PactSem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.29401824317072395}}
{"text": "From iris.algebra Require Export cmra.\nFrom iris.bi Require Import notation.\n\nRecord uPred (M : ucmra) : Type := UPred {\n  uPred_holds :> M → Prop;\n  uPred_proper : Proper ((≡) ==> iff) uPred_holds\n}.\nBind Scope bi_scope with uPred.\nArguments uPred_holds {_} _%I _ : simpl never.\nAdd Printing Constructor uPred.\nGlobal Instance: Params (@uPred_holds) 2 := {}.\nGlobal Existing Instance uPred_proper.\n\nSection ofe.\n  Context {M : ucmra}.\n\n  Inductive uPred_equiv' (P Q : uPred M) : Prop :=\n    { uPred_in_equiv : ∀ x, ✓ x → P x ↔ Q x }.\n  Instance uPred_equiv : Equiv (uPred M) := uPred_equiv'.\n\n  Instance uPred_equivalence : Equivalence uPred_equiv.\n  Proof.\n    split.\n    + by intros P; split=> x ?.\n    + by intros P Q HPQ; split=> x ?; symmetry; apply HPQ.\n    + intros P Q Q' HP HQ; split=> x ?.\n      by trans (Q x);[apply HP|apply HQ].\n  Qed.\n\n  Canonical Structure uPredO : ofe := discreteO (uPred M).\nEnd ofe.\nArguments uPredO : clear implicits.\n\n(** logical entailement *)\nInductive uPred_entails {M} (P Q : uPred M) : Prop :=\n  { uPred_in_entails : ∀ x, ✓ x → P x → Q x }.\n\n(** logical connectives *)\nProgram Definition uPred_emp_def {M} : uPred M :=\n  {| uPred_holds x := x ≡ ε |}.\nSolve Obligations with solve_proper.\n\nDefinition uPred_emp_aux : seal (@uPred_emp_def). Proof. by eexists. Qed.\nDefinition uPred_emp := uPred_emp_aux.(unseal).\nArguments uPred_emp {M}.\nDefinition uPred_emp_eq :\n  @uPred_emp = @uPred_emp_def := uPred_emp_aux.(seal_eq).\n\nDefinition uPred_pure_def {M} (φ : Prop) : uPred M :=\n  {| uPred_holds x := φ |}.\nDefinition uPred_pure_aux : seal (@uPred_pure_def). Proof. by eexists. Qed.\nDefinition uPred_pure := uPred_pure_aux.(unseal).\nArguments uPred_pure {M}.\nDefinition uPred_pure_eq :\n  @uPred_pure = @uPred_pure_def := uPred_pure_aux.(seal_eq).\n\nProgram Definition uPred_and_def {M} (P Q : uPred M) : uPred M :=\n  {| uPred_holds x := P x ∧ Q x |}.\nSolve Obligations with solve_proper.\nDefinition uPred_and_aux : seal (@uPred_and_def). Proof. by eexists. Qed.\nDefinition uPred_and := uPred_and_aux.(unseal).\nArguments uPred_and {M}.\nDefinition uPred_and_eq: @uPred_and = @uPred_and_def := uPred_and_aux.(seal_eq).\n\nProgram Definition uPred_or_def {M} (P Q : uPred M) : uPred M :=\n  {| uPred_holds x := P x ∨ Q x |}.\nSolve Obligations with solve_proper.\nDefinition uPred_or_aux : seal (@uPred_or_def). Proof. by eexists. Qed.\nDefinition uPred_or := uPred_or_aux.(unseal).\nArguments uPred_or {M}.\nDefinition uPred_or_eq: @uPred_or = @uPred_or_def := uPred_or_aux.(seal_eq).\n\nProgram Definition uPred_impl_def {M} (P Q : uPred M) : uPred M :=\n  {| uPred_holds x := P x → Q x |}.\nNext Obligation.\n  intros M P Q x1 x2 Hx. by rewrite Hx.\nQed.\nDefinition uPred_impl_aux : seal (@uPred_impl_def). Proof. by eexists. Qed.\nDefinition uPred_impl := uPred_impl_aux.(unseal).\nArguments uPred_impl {M}.\nDefinition uPred_impl_eq :\n  @uPred_impl = @uPred_impl_def := uPred_impl_aux.(seal_eq).\n\nProgram Definition uPred_forall_def {M A} (Ψ : A → uPred M) : uPred M :=\n  {| uPred_holds x := ∀ a, Ψ a x |}.\nNext Obligation.\n  intros M P Q x1 x2 Hx. by setoid_rewrite Hx.\nQed.\nDefinition uPred_forall_aux : seal (@uPred_forall_def). Proof. by eexists. Qed.\nDefinition uPred_forall := uPred_forall_aux.(unseal).\nArguments uPred_forall {M A}.\nDefinition uPred_forall_eq :\n  @uPred_forall = @uPred_forall_def := uPred_forall_aux.(seal_eq).\n\nProgram Definition uPred_exist_def {M A} (Ψ : A → uPred M) : uPred M :=\n  {| uPred_holds x := ∃ a, Ψ a x |}.\nNext Obligation.\n  intros M P Q x1 x2 Hx. by setoid_rewrite Hx.\nQed.\nDefinition uPred_exist_aux : seal (@uPred_exist_def). Proof. by eexists. Qed.\nDefinition uPred_exist := uPred_exist_aux.(unseal).\nArguments uPred_exist {M A}.\nDefinition uPred_exist_eq: @uPred_exist = @uPred_exist_def := uPred_exist_aux.(seal_eq).\n\nProgram Definition uPred_sep_def {M} (P Q : uPred M) : uPred M :=\n  {| uPred_holds x := ∃ x1 x2, x ≡ x1 ⋅ x2 ∧ P x1 ∧ Q x2 |}.\nSolve Obligations with solve_proper.\nDefinition uPred_sep_aux : seal (@uPred_sep_def). Proof. by eexists. Qed.\nDefinition uPred_sep := uPred_sep_aux.(unseal).\nArguments uPred_sep {M}.\nDefinition uPred_sep_eq: @uPred_sep = @uPred_sep_def := uPred_sep_aux.(seal_eq).\n\nProgram Definition uPred_wand_def {M} (P Q : uPred M) : uPred M :=\n  {| uPred_holds x := ∀ x',\n       ✓ (x ⋅ x') → P x' → Q (x ⋅ x') |}.\nNext Obligation.\n  intros M P Q x1 x2 Hx. by setoid_rewrite Hx.\nQed.\nDefinition uPred_wand_aux : seal (@uPred_wand_def). Proof. by eexists. Qed.\nDefinition uPred_wand := uPred_wand_aux.(unseal).\nArguments uPred_wand {M}.\nDefinition uPred_wand_eq :\n  @uPred_wand = @uPred_wand_def := uPred_wand_aux.(seal_eq).\n\n(* Core is strange in a linear setting,\n    so we have substituted core x ↦ ε in the following definition.\n    This is essentially plainly. *)\nDefinition uPred_persistently_def {M} (P : uPred M) : uPred M :=\n  {| uPred_holds x := P ε |}.\nDefinition uPred_persistently_aux : seal (@uPred_persistently_def). Proof. by eexists. Qed.\nDefinition uPred_persistently := uPred_persistently_aux.(unseal).\nArguments uPred_persistently {M}.\nDefinition uPred_persistently_eq :\n  @uPred_persistently = @uPred_persistently_def := uPred_persistently_aux.(seal_eq).\n\nProgram Definition uPred_ownM_def {M : ucmra} (a : M) : uPred M :=\n  {| uPred_holds x := a ≡ x |}.\nSolve Obligations with solve_proper.\nDefinition uPred_ownM_aux : seal (@uPred_ownM_def). Proof. by eexists. Qed.\nDefinition uPred_ownM := uPred_ownM_aux.(unseal).\nArguments uPred_ownM {M}.\nDefinition uPred_ownM_eq :\n  @uPred_ownM = @uPred_ownM_def := uPred_ownM_aux.(seal_eq).\n\n(** Primitive logical rules.\n    These are not directly usable later because they do not refer to the BI\n    connectives. *)\nModule uPred_primitive.\nDefinition unseal_eqs :=\n  (uPred_emp_eq, uPred_pure_eq, uPred_and_eq, uPred_or_eq, uPred_impl_eq, uPred_forall_eq,\n  uPred_exist_eq, uPred_sep_eq, uPred_wand_eq,\n  uPred_persistently_eq, uPred_ownM_eq).\nLtac unseal :=\n  rewrite !unseal_eqs /=.\n\nSection primitive.\nContext {M : ucmra}.\nImplicit Types φ : Prop.\nImplicit Types P Q : uPred M.\nImplicit Types A : Type.\nArguments uPred_holds {_} !_ _ /.\nLocal Hint Immediate uPred_in_entails : core.\n\nNotation \"P ⊢ Q\" := (@uPred_entails M P%I Q%I) : stdpp_scope.\nNotation \"(⊢)\" := (@uPred_entails M) (only parsing) : stdpp_scope.\nNotation \"P ⊣⊢ Q\" := (@uPred_equiv M P%I Q%I) : stdpp_scope.\nNotation \"(⊣⊢)\" := (@uPred_equiv M) (only parsing) : stdpp_scope.\n\nNotation \"'emp'\" := uPred_emp : bi_scope.\nNotation \"'True'\" := (uPred_pure True) : bi_scope.\nNotation \"'False'\" := (uPred_pure False) : bi_scope.\nNotation \"'⌜' φ '⌝'\" := (uPred_pure φ%type%stdpp) : bi_scope.\nInfix \"∧\" := uPred_and : bi_scope.\nInfix \"∨\" := uPred_or : bi_scope.\nInfix \"→\" := uPred_impl : bi_scope.\nNotation \"∀ x .. y , P\" :=\n  (uPred_forall (λ x, .. (uPred_forall (λ y, P)) ..)) : bi_scope.\nNotation \"∃ x .. y , P\" :=\n  (uPred_exist (λ x, .. (uPred_exist (λ y, P)) ..)) : bi_scope.\nInfix \"∗\" := uPred_sep : bi_scope.\nInfix \"-∗\" := uPred_wand : bi_scope.\nNotation \"<pers> P\" := (uPred_persistently P) : bi_scope.\n\n(** Entailment *)\nLemma entails_po : PreOrder (⊢).\nProof.\n  split.\n  - by intros P; split=> x ?.\n  - intros P Q Q' HP HQ. split=> x ? ?. by apply HQ, HP.\nQed.\nLemma entails_anti_sym : AntiSymm (⊣⊢) (⊢).\nProof. intros P Q HPQ HQP; split=> x n; by split; [apply HPQ|apply HQP]. Qed.\nLemma equiv_spec P Q : (P ⊣⊢ Q) ↔ (P ⊢ Q) ∧ (Q ⊢ P).\nProof.\n  split.\n  - intros HPQ; split; split=> x i; apply HPQ; done.\n  - intros [??]. exact: entails_anti_sym.\nQed.\nLemma equiv_entails P Q : (P ⊣⊢ Q) ↔ (P ⊢ Q) ∧ (Q ⊢ P).\nProof.\n  split.\n  - intros HPQ; split; split=> x i; by apply HPQ.\n  - intros [??]. exact: entails_anti_sym.\nQed.\n\n(** Non-expansiveness and setoid morphisms *)\nLemma pure_ne n : Proper (iff ==> dist n) (@uPred_pure M).\nProof. intros φ1 φ2 Hφ. unseal. split. intros ??. simpl. done. Qed.\n\nLemma and_ne : NonExpansive2 (@uPred_and M).\nProof.\n  intros n P P' HP Q Q' HQ; unseal; split=> x ?.\n  split; (intros [??]; split; [by apply HP|by apply HQ]).\nQed.\n\nLemma or_ne : NonExpansive2 (@uPred_or M).\nProof.\n  intros n P P' HP Q Q' HQ; split=> x ?.\n  unseal; split; (intros [?|?]; [left; by apply HP|right; by apply HQ]).\nQed.\n\nLemma impl_ne :\n  NonExpansive2 (@uPred_impl M).\nProof.\n  intros n P P' HP Q Q' HQ; split=> x ?.\n  unseal; split; intros HPQ ?; apply HQ, HPQ, HP; eauto using cmra_validN_le.\nQed.\n\nLemma sep_ne : NonExpansive2 (@uPred_sep M).\nProof.\n  intros n P P' HP Q Q' HQ; split=> x ?.\n  unseal; split; intros (x1&x2&?&?&?); ofe_subst x;\n    exists x1, x2; split_and!; try (apply HP || apply HQ); setoid_subst;\n    eauto using cmra_valid_op_l, cmra_valid_op_r.\nQed.\n\nLemma wand_ne :\n  NonExpansive2 (@uPred_wand M).\nProof.\n  intros n P P' HP Q Q' HQ; split=> x ?; unseal; split; intros HPQ x' ??;\n    apply HQ, HPQ, HP; eauto using cmra_valid_op_r.\nQed.\n\nLemma forall_ne A n :\n  Proper (pointwise_relation _ (dist n) ==> dist n) (@uPred_forall M A).\nProof.\n  by intros Ψ1 Ψ2 HΨ; unseal; split=> n' x; split; intros HP a; apply HΨ.\nQed.\n\nLemma exist_ne A n :\n  Proper (pointwise_relation _ (dist n) ==> dist n) (@uPred_exist M A).\nProof.\n  intros Ψ1 Ψ2 HΨ.\n  unseal; split=> x ?; split; intros [a ?]; exists a; by apply HΨ.\nQed.\n\nLemma persistently_ne : NonExpansive (@uPred_persistently M).\nProof.\n  intros P1 P2 Hp H.\n  unseal. split=> x?. simpl. split; apply H; eauto using ucmra_unit_valid.\nQed.\n\nLemma pure_proper : Proper (iff ==> (≡)) (@uPred_pure M).\nProof. unseal. done. Qed.\n\nLemma and_proper : Proper ((≡) ==> (≡) ==> (≡)) (@uPred_and M).\nProof.\n  unseal. intros ?? [] ?? []. split. naive_solver.\nQed.\n\nLemma or_proper : Proper ((≡) ==> (≡) ==> (≡)) (@uPred_or M).\nProof.\n  unseal. intros ?? [] ?? []. split. naive_solver.\nQed.\n\nLemma impl_proper : Proper ((≡) ==> (≡) ==> (≡)) (@uPred_impl M).\nProof.\n  unseal. intros ?? [] ?? []. split. naive_solver.\nQed.\n\nLemma sep_proper : Proper ((≡) ==> (≡) ==> (≡)) (@uPred_sep M).\nProof.\n  unseal. intros ?? [] ?? []. split. simpl.\n  intros ??. split; intros (? & ? & ? & ? & ?).\n  - setoid_subst. naive_solver (eauto using cmra_valid_op_l, cmra_valid_op_r).\n  - setoid_subst. naive_solver (eauto using cmra_valid_op_l, cmra_valid_op_r).\nQed.\n\nLemma wand_proper : Proper ((≡) ==> (≡) ==> (≡)) (@uPred_wand M).\nProof.\n  unseal. intros ?? [] ?? []. split. naive_solver (eauto using cmra_valid_op_l, cmra_valid_op_r).\nQed.\n\nLemma forall_proper A :\n  Proper (pointwise_relation _ (≡) ==> (≡)) (@uPred_forall M A).\nProof.\n  by intros Ψ1 Ψ2 HΨ; unseal; split=> n' x; split; intros HP a; apply HΨ.\nQed.\n\nLemma exist_proper A :\n  Proper (pointwise_relation _ (≡) ==> (≡)) (@uPred_exist M A).\nProof.\n  intros Ψ1 Ψ2 HΨ.\n  unseal; split=> x ?; split; intros [a ?]; exists a; by apply HΨ.\nQed.\n\nLemma persistently_proper : Proper ((≡) ==> (≡)) (@uPred_persistently M).\nProof.\n  intros ???. unseal. split. intros ??. simpl. destruct H as [H].\n  eauto using ucmra_unit_valid.\nQed.\n\nLemma ownM_proper : Proper ((≡) ==> (≡)) (@uPred_ownM M).\nProof.\n  intros ???. unseal. split=> ??. setoid_subst. done.\nQed.\n\n\n(** Introduction and elimination rules *)\nLemma pure_intro φ P : φ → P ⊢ ⌜φ⌝.\nProof. by intros ?; unseal; split. Qed.\nLemma pure_elim' φ P : (φ → True ⊢ P) → ⌜φ⌝ ⊢ P.\nProof. unseal; intros HP; split=> x ??. by apply HP. Qed.\nLemma pure_forall_2 {A} (φ : A → Prop) : (∀ x : A, ⌜φ x⌝) ⊢ ⌜∀ x : A, φ x⌝.\nProof. by unseal. Qed.\n\nLemma and_elim_l P Q : P ∧ Q ⊢ P.\nProof. by unseal; split=> x ? [??]. Qed.\nLemma and_elim_r P Q : P ∧ Q ⊢ Q.\nProof. by unseal; split=> x ? [??]. Qed.\nLemma and_intro P Q R : (P ⊢ Q) → (P ⊢ R) → P ⊢ Q ∧ R.\nProof. intros HQ HR; unseal; split=> x ??; by split; [apply HQ|apply HR]. Qed.\n\nLemma or_intro_l P Q : P ⊢ P ∨ Q.\nProof. unseal; split=> x ??; left; auto. Qed.\nLemma or_intro_r P Q : Q ⊢ P ∨ Q.\nProof. unseal; split=> x ??; right; auto. Qed.\nLemma or_elim P Q R : (P ⊢ R) → (Q ⊢ R) → P ∨ Q ⊢ R.\nProof.\n  intros HP HQ; unseal; split=> x ? [?|?].\n  - by apply HP.\n  - by apply HQ.\nQed.\n\nLemma impl_intro_r P Q R : (P ∧ Q ⊢ R) → P ⊢ Q → R.\nProof.\n  unseal; intros HQ; split=> ????.\n  apply HQ; naive_solver eauto using uPred_mono, cmra_included_includedN, cmra_validN_le.\nQed.\nLemma impl_elim_l' P Q R : (P ⊢ Q → R) → P ∧ Q ⊢ R.\nProof.\n  unseal; intros HP ; split=> x ? [??].\n  apply HP; auto.\nQed.\n\nLemma forall_intro {A} P (Ψ : A → uPred M): (∀ a, P ⊢ Ψ a) → P ⊢ ∀ a, Ψ a.\nProof. unseal; intros HPΨ; split=> x ?? a; by apply HPΨ. Qed.\nLemma forall_elim {A} {Ψ : A → uPred M} a : (∀ a, Ψ a) ⊢ Ψ a.\nProof. unseal; split=> x ? HP; apply HP. Qed.\n\nLemma exist_intro {A} {Ψ : A → uPred M} a : Ψ a ⊢ ∃ a, Ψ a.\nProof. unseal; split=> x ??; by exists a. Qed.\nLemma exist_elim {A} (Φ : A → uPred M) Q : (∀ a, Φ a ⊢ Q) → (∃ a, Φ a) ⊢ Q.\nProof. unseal; intros HΦΨ; split=> x ? [a ?]; by apply HΦΨ with a. Qed.\n\n(** BI connectives *)\nLemma sep_mono P P' Q Q' : (P ⊢ Q) → (P' ⊢ Q') → P ∗ P' ⊢ Q ∗ Q'.\nProof.\n  intros HQ HQ'; unseal.\n  split; intros x ? (x1&x2&?&?&?); exists x1,x2; setoid_subst; split;\n    eauto 7 using cmra_valid_op_l, cmra_valid_op_r, uPred_in_entails.\nQed.\nLemma emp_sep_1 P : P ⊢ emp ∗ P.\nProof.\n  unseal; split; intros x ??. exists ε, x. rewrite left_id; simpl; eauto.\nQed.\nLemma emp_sep_2 P : emp ∗ P ⊢ P.\nProof.\n  unseal; split; intros x ? (x1&x2&?&?&?); setoid_subst.\n  by rewrite left_id.\nQed.\nLemma sep_comm' P Q : P ∗ Q ⊢ Q ∗ P.\nProof.\n  unseal; split; intros x ? (x1&x2&?&?&?); exists x2, x1; by rewrite (comm op).\nQed.\nLemma sep_assoc' P Q R : (P ∗ Q) ∗ R ⊢ P ∗ (Q ∗ R).\nProof.\n  unseal; split; intros x ? (x1&x2&Hx&(y1&y2&Hy&?&?)&?).\n  exists y1, (y2 ⋅ x2); split_and?; auto.\n  + by rewrite (assoc op) -Hy -Hx.\n  + by exists y2, x2.\nQed.\nLemma wand_intro_r P Q R : (P ∗ Q ⊢ R) → P ⊢ Q -∗ R.\nProof.\n  unseal=> HPQR; split=> x ?? x' ??; apply HPQR; auto.\n  exists x, x'; split_and?; auto.\nQed.\nLemma wand_elim_l' P Q R : (P ⊢ Q -∗ R) → P ∗ Q ⊢ R.\nProof.\n  unseal =>HPQR. split; intros x ? (?&?&?&?&?). setoid_subst.\n  eapply HPQR; eauto using cmra_valid_op_l.\nQed.\n\n(** Persistently *)\nLemma persistently_mono P Q : (P ⊢ Q) → <pers> P ⊢ <pers> Q.\nProof. intros HP; unseal; split=> x ? /=. apply HP, ucmra_unit_valid. Qed.\n\nLemma persistently_idemp_2 P : <pers> P ⊢ <pers> <pers> P.\nProof. unseal; split=> x ?? //. Qed.\n\nLemma persistently_emp_2 : emp ⊢ <pers> emp.\nProof. unseal; by split => n x ? /=. Qed.\n\nLemma persistently_and_2 (P Q : uPred M) : (<pers> P ∧ <pers> Q) ⊢ (<pers> (P ∧ Q)).\nProof. by unseal. Qed.\n\n\nLemma persistently_forall_2 {A} (Ψ : A → uPred M) : (∀ a, <pers> Ψ a) ⊢ (<pers> ∀ a, Ψ a).\nProof. by unseal. Qed.\nLemma persistently_exist_1 {A} (Ψ : A → uPred M) : (<pers> ∃ a, Ψ a) ⊢ (∃ a, <pers> Ψ a).\nProof. by unseal. Qed.\n\nLemma persistently_absorbing P Q : <pers> P ∗ Q ⊢ <pers> P.\nProof. unseal; split=> n x ? /=. naive_solver. Qed.\n\nLemma persistently_and_sep_elim P Q : <pers> P ∧ Q ⊢ P ∗ Q.\nProof.\n  unseal; split=> x ? [??]; exists ε, x; simpl in *. by rewrite left_id.\nQed.\n\n\nLemma persistently_impl_persistently P Q : (<pers> P → <pers> Q) ⊢ <pers> (<pers> P → Q).\nProof.\n  unseal; split=> /= x ? HPQ x'. naive_solver.\nQed.\n\n(** Own *)\nLemma ownM_op (a1 a2 : M) :\n  uPred_ownM (a1 ⋅ a2) ⊣⊢ uPred_ownM a1 ∗ uPred_ownM a2.\nProof.\n  unseal; split=> x ?; split.\n  - intros H. exists a1, a2. simpl in H.\n    split. { by rewrite H. }\n    split; by simpl.\n  - simpl. by intros (x1&x2 & -> & -> & ->).\nQed.\n\nLemma ownM_unit : uPred_ownM ε ⊣⊢ emp.\nProof. unseal. split; naive_solver. Qed.\n\nLemma ownM_valid x : uPred_ownM x ⊢ ⌜ ✓ x ⌝.\nProof.\n  unseal. split. simpl. intros. setoid_subst. done.\nQed.\n\n(** Consistency/soundness statement *)\n(** The lemmas [pure_soundness] and [internal_eq_soundness] should become an\ninstance of [siProp] soundness in the future. *)\nLemma pure_soundness φ : (emp ⊢ ⌜ φ ⌝) → φ.\nProof. unseal=> -[H]. by apply (H ε); simpl; eauto using ucmra_unit_valid. Qed.\n\nEnd primitive.\nEnd uPred_primitive.", "meta": {"author": "julesjacobs", "repo": "cgraphs", "sha": "1ae9907995a3f7bfd01171538e3b99494e359cc9", "save_path": "github-repos/coq/julesjacobs-cgraphs", "path": "github-repos/coq/julesjacobs-cgraphs/cgraphs-1ae9907995a3f7bfd01171538e3b99494e359cc9/theories/cgraphs/upred.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.29401824317072395}}
{"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 NatTrans.Main.\nFrom Categories Require Import Adjunction.Adjunction Adjunction.Duality.\nFrom Categories Require Import Ext_Cons.Comma.\nFrom Categories Require Import Basic_Cons.Terminal Basic_Cons.Facts.Term_IsoCat.\nFrom Categories Require Import Cat.Cat_Iso.\nFrom Categories Require Import Archetypal.Discr.Discr Archetypal.Discr.NatFacts.\n\n(** A functor G : D –≻ C has a left adjoint if and only if\nthe comma category (Comma (Func_From_SingletonCat x) G) has\nan initial object for any (x : C).\n\nDually, a functor F : C –≻ D has a right adjoint if and only\nif the comma category (Comma F (Func_From_SingletonCat x))\nhas a terminal object for any (x : D).\n *)\n\n(**\nIf the comma category (Comma (Func_From_SingletonCat x) G) has\nan initial object for any (x : C). Then G : D –≻ C has\na left adjoint.\n*)\n\nSection Universal_Morphism_Right_Adjonit.\n  Context\n    {C D : Category}\n    (G : (D --> C)%functor)\n    (HU_init : ∀ (x : C), (𝟘_ (Comma (Const_Func 1 x) G))%object ).\n\n  Local Definition Universal_Morphism_Lem :\n    ∀ c a h, CMH_right (t_morph (HU_init c) a) = CMH_right h.\n  Proof.\n    intros c a h.\n    apply f_equal.\n    apply (t_morph_unique (HU_init c)).\n  Qed.\n\n  Local Ltac smart_apply_Universal_Morphism_Lem :=\n    match goal with\n      [|- CMH_right ?A = ?B] =>\n      match type of A with\n        ?W =>\n        let M :=\n            (eval cbn in W)\n        in\n        match M with\n          Comma_Hom _ _ ?X ?Y =>\n          evar (U : Comma_Hom _ _ X Y);\n            replace B with (CMH_right ?U);\n            [\n              eapply\n                (\n                  Universal_Morphism_Lem\n                    _\n                    Y\n                    (\n                      Build_Comma_Hom\n                        _\n                        _\n                        X\n                        Y\n                        tt\n                        B\n                        _\n                    )\n                )\n            |\n            reflexivity\n            ]\n        end\n      end\n    end.\n\n  Program Definition Universal_Morphism_Right_Adjonit_Func : (C --> D)%functor\n    :=\n      {|\n        FO :=\n          fun c =>\n            CMO_trg (terminal (HU_init c));\n        FA :=\n          fun c c' h =>\n            CMH_right\n              (t_morph\n                 (HU_init c)\n                 (@Build_Comma_Obj\n                    _\n                    _\n                    _\n                    (Const_Func 1 c)\n                    G\n                    tt\n                    (CMO_trg (terminal (HU_init c')))\n                    ((CMO_hom (terminal (HU_init c'))) ∘ h)%morphism\n                 )\n              )\n      |}.\n\n  Next Obligation.\n  Proof.\n    smart_apply_Universal_Morphism_Lem.\n    Unshelve.\n    cbn; auto.\n  Qed.\n\n  Next Obligation.\n  Proof.\n    smart_apply_Universal_Morphism_Lem.\n    Unshelve.\n    {\n      cbn.\n      rewrite F_compose.\n      rewrite assoc.\n      simpl_ids;\n      match goal with\n      [|- ((G _a) ((CMH_right ?A)) ∘ ((G _a) (CMH_right ?B)) ∘ _)%morphism = _] =>\n        cbn_rewrite (CMH_com B);\n          do 2 rewrite assoc_sym;\n          cbn_rewrite (CMH_com A); auto\n      end.\n    }\n  Qed.\n\n\n  Local Obligation Tactic := idtac.\n\n  Program Definition Universal_Morphism_Right_Adjonit_unit :\n    (Functor_id C --> G ∘ Universal_Morphism_Right_Adjonit_Func)%nattrans\n    :=\n      {|\n        Trans := fun c => CMO_hom (terminal (HU_init c))\n      |}\n  .\n\n  Next Obligation.\n  Proof.\n    intros c c' h.\n    cbn.\n    match goal with\n      [|- _ = (G _a (CMH_right ?A) ∘ _)%morphism] =>\n      cbn_rewrite (CMH_com A)\n    end.\n    auto.\n  Qed.\n\n  Next Obligation.\n  Proof.\n    symmetry.\n    apply Universal_Morphism_Right_Adjonit_unit_obligation_1.\n  Qed.\n\n    \n  Program Definition Universal_Morphism_Right_Adjonit :\n    (Universal_Morphism_Right_Adjonit_Func ⊣ G)%functor\n    :=\n      {|\n        adj_unit := Universal_Morphism_Right_Adjonit_unit;\n        adj_morph_ex :=\n          fun c d f =>\n            CMH_right\n              (t_morph\n                 (HU_init c)\n                 (@Build_Comma_Obj\n                    _\n                    _\n                    _\n                    (Const_Func 1 c)\n                    G\n                    tt\n                    d\n                    f\n                 )\n              )\n      |}\n  .\n\n  Next Obligation.\n  Proof.\n    intros c d f.\n    cbn in *.\n    match goal with\n      [|- _ = (G _a (CMH_right ?A) ∘ _)%morphism] =>\n      cbn_rewrite (CMH_com A)\n    end.\n    auto.\n  Qed.\n\n  Next Obligation.\n  Proof.\n    intros c d f g h H1 H2.\n    cbn in *.\n    rewrite <- (id_unit_right _ _ f) in H1, H2.\n    symmetry in H1, H2.\n    set (W :=\n           @Build_Comma_Obj\n             _\n             _\n             _\n             (Const_Func 1 c)\n             G\n             tt\n             d\n             f\n        )\n    .\n    let tac u H\n        :=\n        (\n          change u with\n          (\n            CMH_right\n              (  \n                Build_Comma_Hom\n                  _\n                  _\n                  (terminal (HU_init c))\n                  W\n                  tt\n                  u\n                  H\n              )\n          )\n        )\n    in\n    tac g H1;\n      tac h H2\n    .\n    transitivity (CMH_right (t_morph (HU_init c) W));\n      [symmetry|];\n      apply (Universal_Morphism_Lem c W)\n    .\n  Qed.\n\nEnd Universal_Morphism_Right_Adjonit.\n\n(**\nif a functor G : D –≻ C has a left adjoint then the comma\ncategory (Comma (Func_From_SingletonCat x) G) has\nan initial object for any (x : C).\n*)\nSection Right_Adjoint_Universal_Morphism.\n  Context\n    {C D : Category}\n    {F : (C --> D)%functor}\n    {G : (D --> C)%functor}\n    (Adj : (F ⊣ G)%functor)\n    (x : C).\n\n  Program Definition Right_Adjoint_Universal_Morphism_terminal :\n    (Comma (Const_Func 1 x) G)\n    :=\n      {|\n        CMO_src := tt;\n        CMO_trg := (F _o x)%object;\n        CMO_hom := Trans (adj_unit Adj) x\n      |}.\n\n  Program Definition Right_Adjoint_Universal_Morphism_t_morph\n          (u : (Comma (Const_Func 1 x) G))\n    :\n      Comma_Hom _ _ Right_Adjoint_Universal_Morphism_terminal u\n    :=\n      {|\n        CMH_left := tt;\n        CMH_right :=\n          @adj_morph_ex\n            _\n            _\n            _\n            _\n            Adj\n            x\n            (CMO_trg u)\n            (CMO_hom u)\n      |}.\n\n  Next Obligation.\n  Proof.\n    simpl_ids.\n    symmetry.\n    apply (@adj_morph_com _ _ _ _ Adj).\n  Qed.\n\n  Program Definition Right_Adjoint_Universal_Morphism :\n    (𝟘_ (Comma (Const_Func 1 x) G))%object\n    :=\n      {|\n        terminal := Right_Adjoint_Universal_Morphism_terminal;\n        t_morph := Right_Adjoint_Universal_Morphism_t_morph\n      |}.\n\n  Next Obligation.\n  Proof.\n    assert (Hf := CMH_com f).\n    assert (Hg := CMH_com g).\n    cbn in *.\n    simpl_ids in Hf; simpl_ids in Hg.\n    symmetry in Hf, Hg.\n    apply Comma_Hom_eq_simplify.\n    match goal with\n      [|- ?A = ?B] =>\n      destruct A; destruct B; trivial\n    end.\n    eapply (@adj_morph_unique _ _ _ _ Adj); eauto.\n  Qed.\n\nEnd Right_Adjoint_Universal_Morphism.\n\n(**\nIf the comma category (Comma F (Func_From_SingletonCat x)) has\nan initial object for any (x : D). Then F : D –≻ C has\na right adjoint.\n*)\nSection Universal_Morphism_Left_Adjonit.\n  Context\n    {C D : Category}\n    (F : (C --> D)%functor)\n    (HU_term : ∀ (x : D), (𝟙_ (Comma F (Const_Func 1 x)))%object).\n\n  Definition Universal_Morphism_Left_Adjonit_HU_init\n             (x : (D^op)%category)\n    :\n      (𝟘_ (Comma ((@Const_Func 1 (D ^op) x)) (F^op)))%object\n    :=\n      Term_IsoCat\n        (\n          Opposite_Cat_Iso\n            (\n              Isomorphism_Compose\n                (Comma_Opposite_Iso F (@Const_Func 1 D x))\n                (Comma_Left_Func_Iso\n                   (@Func_From_SingletonCat_Opposite D x) (F ^op))\n            )\n        )\n        (HU_term x).\n\n  Definition Universal_Morphism_Left_Adjonit\n    :\n      (F ⊣ (\n               Universal_Morphism_Right_Adjonit_Func\n                 (F ^op)\n                 Universal_Morphism_Left_Adjonit_HU_init\n             )^op\n      )%functor\n    :=\n      Adjunct_Duality\n        (\n          @Universal_Morphism_Right_Adjonit\n            (D^op)\n            (C^op)\n            (F^op)\n            Universal_Morphism_Left_Adjonit_HU_init\n        )\n  .\n\nEnd Universal_Morphism_Left_Adjonit.\n\n(**\nif a functor F : C –≻ D has a right adjoint then the comma\ncategory (Comma F (Func_From_SingletonCat x)) has\nan terminal object for any (x : D).\n*)\nSection Left_Adjoint_Universal_Morphism.\n  Context\n    {C D : Category}\n    {F : (C --> D)%functor}\n    {G : (D --> C)%functor}\n    (Adj : (F ⊣ G)%functor)\n    (x : D).\n\n  Definition Left_Adjoint_Universal_Morphism\n    : (𝟙_ (Comma F (Const_Func 1 x)))%object\n    :=\n      Term_IsoCat\n        (\n          Opposite_Cat_Iso\n            (\n              Isomorphism_Compose\n                (\n                  Comma_Left_Func_Iso\n                    (Inverse_Isomorphism (@Func_From_SingletonCat_Opposite D x))\n                    (F ^op)\n                )\n                (Inverse_Isomorphism\n                   (Comma_Opposite_Iso F (@Const_Func 1 D x)))\n            )\n        )\n        (Right_Adjoint_Universal_Morphism (Adjunct_Duality Adj) x)\n  .\n\nEnd Left_Adjoint_Universal_Morphism.\n", "meta": {"author": "amintimany", "repo": "Categories", "sha": "1839108875df0107fa4f6061c654003decda2d49", "save_path": "github-repos/coq/amintimany-Categories", "path": "github-repos/coq/amintimany-Categories/Categories-1839108875df0107fa4f6061c654003decda2d49/Adjunction/Univ_Morph.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.29401824317072395}}
{"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 Implicit Arguments.\nUnset Strict Implicit.\n\nRequire Import Arith.\nRequire Export universe.\n\n\n\nLtac cw := autorewrite with cw; try tv; try am. \n\n\nModule Category.\nExport Universe. \n\nModule Notations.\n\n\n\n\n\nDefinition Objects  := R (o_(b_(j_ DOT ))).\nDefinition Composition := R (c_(m_(p_ DOT ))).\nDefinition Identity := R (i_(d_ (t_ DOT ))).\nDefinition Structure := R (s_ (t_ (r_ DOT))). \n(*** the latter is a placeholder for any additional\nstructure we might want to put on ****)\n\n\nDefinition objects a := V Objects a.\nDefinition morphisms a := V Underlying a.\nDefinition composition a := V Composition a.\nDefinition identity a  := V Identity a. \nDefinition structure a := V Structure a.\n\n\n\n\n\n\nDefinition create (o m:E) (c : E2) (i:E1) (s:E):=\ndenote Objects o (\ndenote Underlying m (\ndenote Composition \n(L m (fun u => L (Z m (fun v => source u = target v)) (c u))) (\ndenote Identity (L o i) (\ndenote Structure s (\nstop))))). \n\n\n\n\n\nLemma objects_create :forall o m c i s, objects (create o m c i s) = o. \nir; uf objects; uf create. drw. \nQed. \n\n\nLemma morphisms_create : forall o m c i s, morphisms \n(create o m c i s) = m. \nir; uf morphisms; uf create. drw. \nQed. \n\nLemma structure_create : forall o m c i s,\nstructure (create o m c i s) = s.\nProof.\nir; uf structure; uf create. drw.\nQed. \n\n\nLemma composition_create : forall o m c i s,\ncomposition (create o m c i s) = \nL m (fun u => (L (Z m (fun v => source u = target v)) (c u))).\nProof.\nir. uf create. uf composition. drw.\nQed.\n\n\n\nLemma identity_create : forall o m c i s,\nidentity (create o m c i s)  = L o i.\nProof.\nir. uf create. uf identity. drw. \nQed.\n\n\nHint Rewrite objects_create morphisms_create composition_create\nidentity_create : cw.\n\nDefinition comp a u v := V v (V u (composition a)).\nDefinition id a x := V x (identity a).\n\nDefinition like a := a = create (objects a)\n(morphisms a) (comp a) (id a) (structure a).\n\nLemma create_extensionality : forall o m c i  s o1 m1 c1 i1 s1,\no = o1 -> m = m1 -> \n(forall u v, inc u m -> inc v m -> source u = target v \n-> c u v = c1 u v) ->\n(forall x, inc x o -> i x = i1 x) ->\ns = s1 -> \ncreate o m c i s = create o1 m1 c1 i1 s1.\nProof.\nir. wr H. wr H0. \nassert (lem1: \nL m (fun u => L (Z m (fun v => source u = target v)) (c u)) =\nL m (fun u => L (Z m (fun v => source u = target v)) (c1 u))). \nap Function.create_extensionality. tv. \nir. ap Function.create_extensionality. tv. \nir. ap H1. am. Ztac. Ztac. \n\nassert (lem2: L o i = L o i1).\nap Function.create_extensionality. tv.\nau. \nuf create. rw lem1. rw lem2. rw H3. reflexivity. \nQed. \n\nLemma create_like : forall o m c i s,\nlike (create o m c i s).\nProof.\nir. uf like. ap create_extensionality. \nrw objects_create; tv. rw morphisms_create; tv. \nir. \nuf comp. \nrw composition_create. \nrw create_V_rewrite. rw create_V_rewrite. \ntv. Ztac. am. ir. \nuf id. rw identity_create. \nrw create_V_rewrite. tv. am. \nrw structure_create. tv. Qed. \n\nDefinition is_ob a x := inc x (objects a).\nDefinition is_mor a u := inc u (morphisms a).\n\n\n\nEnd Notations.\nExport Notations.\n\n\n\nLemma is_ob_create : forall o m c i  s x,\nis_ob (create o m c i s) x = (inc x o).\nProof.\nir. \nuf is_ob. cw. \nQed. \n\nLemma is_mor_create : forall o m c i s u,\nis_mor (create o m c i s) u = (inc u m).\nProof.\nir. uf is_mor. cw. \nQed. \n\nLemma comp_create : forall o m c i s u v,\ninc u m -> inc v m -> source u = target v -> \ncomp (create o m c i s) u v = c u v.\nProof.\nir. uf comp. cw. aw. \nZtac. \nQed. \n\nLemma id_create : forall o m c i s x,\ninc x o -> \nid (create o m c i s) x = i x.\nProof.\nir. uf id. cw. aw. \nQed. \n\n\n(**** axioms ****)\n\nDefinition are_composable a f g :=\nis_mor a f &\nis_mor a g &\nsource f = target g.\n\n\nDefinition is_ob_facts a x :=\nis_ob a x &\nis_mor a (id a x) &\nsource (id a x) = x &\ntarget (id a x) = x &\n(forall f, is_mor a f-> source f = x -> comp a f (id a x) = f) &\n(forall f, is_mor a f-> target f = x -> comp a (id a x) f = f).\n\n\nDefinition is_mor_facts a f:=\nis_mor a f & \nis_ob a (source f) & \nis_ob a (target f) &\ncomp a (id a (target f)) f = f &\ncomp a f (id a (source f)) = f &\nArrow.like f.\n\nDefinition are_composable_facts a f g:=\nare_composable a f g &\nis_mor a (comp a f g) &\nsource (comp a f g) = source g &\ntarget (comp a f g) = target f.\n\nDefinition axioms a := \n(forall x, is_ob a x = is_ob_facts a x) &\n(forall u, is_mor a u = is_mor_facts a u) &\n(forall u v, are_composable a u v = are_composable_facts a u v) &\n(forall u v w, are_composable a u v -> are_composable a v w ->\n   (comp a (comp a u v) w) = (comp a u (comp a v w))) &\nlike a.\n\nDefinition composable a u v :=\naxioms a & are_composable a u v.\n\nDefinition mor a u := axioms a & is_mor a u.\n\nDefinition ob a x := axioms a & is_ob a x.\n\nDefinition mor_facts c u := \nmor c u &\nob c (source u) &\nob c (target u) &\ncomp c (id c (target u)) u = u &\ncomp c u (id c (source u)) = u &\nArrow.like u.\n\nLemma mor_facts_rw : forall c u,\nmor c u = mor_facts c u. \nProof.\nir. ap iff_eq; ir. \ncp H; uh H; ee. cp H; uh H; ee. \nrwi H3 H1. uh H1; ee. \nuhg; xd. uhg; xd. uhg; xd. uh H; ee; am. \nQed. \n\nDefinition ob_facts c x :=\nob c x &\nmor c (id c x) &\ncomposable c (id c x) (id c x) &\nsource (id c x) = x &\ntarget (id c x) = x &\ncomp c (id c x) (id c x) = (id c x)&\n(forall u, mor c u -> source u = x -> comp c u (id c x) = u)&\n(forall u, mor c u -> target u = x -> comp c (id c x) u = u).\n\nLemma ob_facts_rw : forall c x,\nob c x = ob_facts c x. \nProof. \nir. ap iff_eq; ir. cp H; uh H; ee. \ncp H; uh H; ee. clear H6. cp H1; uh H1; ee. \nrwi H H6. uh H6; ee. \nuhg; xd. uhg; xd. \nuhg; xd. uhg; xd. \nrw H8; rw H9; tv. \nir. ap H10. lu. am. \nir. ap H11; lu. lu. \nQed. \n\nDefinition composable_facts c u v :=\naxioms c &\nare_composable c u v &\nmor c u &\nmor c v &\nmor c (comp c u v)&\nsource u = target v & \nsource (comp c u v) = source v &\ntarget (comp c u v) = target u. \n\nLemma composable_facts_rw : forall c u v,\ncomposable c u v = composable_facts c u v.\nProof.\nir; ap iff_eq; ir. cp H; uh H; ee. \ncp H; uh H; ee. clear H6. \nuhg; dj; try am. \nuhg; ee. am. lu. uhg; ee; lu. \nrwi H4 H1. uh H1; ee. uhg; ee; try am. \nuh H7; ee; am. \nrwi H4 H7. uh H7. ee. am. \nrwi H4 H7. uh H7. ee. am. \nuhg; uh H; xd. \nQed. \n\nLemma show_composable : forall c u v,\nmor c u -> mor c v -> source u = target v ->\ncomposable c u v.\nProof.\nir. cp H; uh H; ee. cp H; uh H; ee. \nuhg; ee. am. uh H0; ee. uhg; ee; try am.  \nQed. \n\nLemma show_composable_facts : forall c u v,\nmor c u -> mor c v -> source u = target v ->\ncomposable_facts c u v.\nProof.\nir. wr composable_facts_rw; ap show_composable; am. \nQed. \n\nDefinition associativity_facts c u v w :=\ncomposable_facts c u v &\ncomposable_facts c v w &\ncomposable_facts c u (comp c v w) &\ncomposable_facts c (comp c u v) w &\ncomp c u (comp c v w) = comp c (comp c u v) w.\n\nLemma show_associativity_facts : forall c u v w,\ncomposable c u v -> composable c v w -> \nassociativity_facts c u v w. \nProof.\nir. cp H; uh H; ee. \ncp H; uh H; ee. clear H7. \nuhg.\ndo 4 (wr composable_facts_rw). \nee; try am. \nrwi composable_facts_rw H0;\nrwi composable_facts_rw H1. \nuh H0; uh H1; ee.\nap show_composable. \nam. am. \nrw H20. am. \nap show_composable. \nrwi composable_facts_rw H1; uh H1; ee; am. \nrwi composable_facts_rw H0; uh H0; ee; am.\nrwi composable_facts_rw H1; uh H1; ee.\nrw H12. \nuh H0; ee. uh H14; ee. am. \nsy; ap H6. am. uh H0; ee; am. \nQed. \n\nDefinition morphism_property (o m:E) (c:E2) (i:E1) u:=\ninc u m  & inc (source u) o & inc (target u) o &\nc u (i (source u)) = u &\nc (i (target u)) u = u &\nArrow.like u.\n\nDefinition object_property (o m:E) (i:E1) x :=\ninc x o & inc (i x) m & source (i x) = x & target (i x) = x. \n\nDefinition composable_property (m:E) (c:E2)  u v:=\ninc u m & inc v m & source u = target v & \ninc (c u v) m &\nsource (c u v) = source v &\ntarget (c u v) = target u.\n\n\nDefinition property (o m:E) (c:E2) (i:E1) :=\n(forall x, inc x o = object_property o m i x) &\n(forall u, inc u m = morphism_property o m c i u) &\n(forall u v, inc u m -> inc v m -> source u = target v ->\n   composable_property m c  u v) &\n(forall u v w, inc u m -> inc v m -> inc w m -> \n   source u = target v -> source v = target w ->\n   c (c u v) w = c u (c v w)).\n\nLemma are_composable_create_rw : forall o m c i s u v,\nare_composable (create o m c i s) u v = \n(inc u m & inc v m & source u = target v).\nProof.\nir. ap iff_eq; ir. uh H.\nrwi is_mor_create H. rwi is_mor_create H. xd. \nuhg. do 2 (rw is_mor_create). xd. \nQed. \n\nLemma create_axioms : forall o m (c : E2) (i:E1) (s:E),\nproperty o m c i ->\naxioms (create o m c i s).\nProof.\nir. \nset (k:=(create o m c i s)).\n\n\nassert (lem1 : forall u v, are_composable k u v = \n(inc u m & inc v m & source u = target v)).\nir. ap iff_eq; ir. ufi k H0. \nrwi are_composable_create_rw H0. \nxd.\nuf k. rw are_composable_create_rw. \nxd. \nuh H; ee. \n\n\nassert (lem2: forall u, is_mor k u = inc u m). \nir. ap iff_eq; ir. ufi k H3. \nrwi is_mor_create H3. am. \nuf k; rw is_mor_create; am. \n\nassert (lem3: forall u v, inc u m -> inc v m -> \nsource u = target v -> comp k u v = c u v).\nir. uf k. rw comp_create; tv. \n\n\nassert (lem5: forall x, inc x o -> id k x = i x).\nir. uf k. rw id_create. tv. am. \n\nassert (lem6: forall (x:E), is_ob k x = inc x o).\nir; ap iff_eq; ir. ufi k H3. rwi is_ob_create H3. am.\nuf k; rw is_ob_create; am. \n\n\n(*** the proof of axioms ***)\n(*** mor facts ***)\nuhg; ee; ir. \nap iff_eq; ir. cp H3; rwi lem6 H3. \nrwi H H3. uh H3; ee. \nuhg; dj. am. rw lem2. rw lem5. am. am.\nrw lem5; am. \nrw lem5; am. rw lem5. rw lem3. \nrwi lem2 H12. rwi H0 H12. uh H12; ee.\nwr H13. am. wr lem2. am. \nwr lem5. wr lem2. am. am. rw H7. am. \nam. rw lem3. rw lem5. rwi lem2 H13. \nrwi H0 H13. uh H13; ee. wr H14. \nam. lu. wr lem2. am. wr lem2. am. \nrw H10. sy; am. lu. \n\nap iff_eq; ir. rwi lem2 H3. \nrwi H0 H3. uh H3; ee. \nuhg; ee. rw lem2; am. rw lem6; am. rw lem6; am. \nrw lem3. rw lem5. am. am. \nrww lem5. rwi H H5. lu. am. \nrww lem5. rwi H0 H3. uh H3; ee. \nrwi H H10. uh H10; ee. am. \n\nrww lem3. rw lem5. am. am. \nrw lem5. rwi H H4. uh H4; ee. \nam. am. rw lem5. rwi H H4. \nuh H4; ee. sy; am. am. am.  \nlu. \n\n\nap iff_eq; ir. cp H3; uh H3; ee. \nrwi lem2 H3. rwi lem2 H5. \nutil (H1 u v). am. am. am. \nuh H7; ee. \nuhg; xd. rw lem2. rww lem3. \nrww lem3. rww lem3. lu. \n\n(*** associativity ***)\nassert (inc u m). \nwr lem2; lu. \nassert (inc v m). \nwr lem2; lu. \nassert (inc w m). \nwr lem2; lu. \nassert (source u = target v). lu.\nassert (source v = target w). lu. \nrww lem3. rww lem3. rww lem3. rww lem3. \nrwi lem1 H3; rwi lem1 H4; ee. \nap H2; try am. \nrww lem3. cp (H1 _ _ H6 H7 H9). \nlu. \nrww lem3. cp (H1 _ _ H5 H6 H8). \nutil (H1 v w). am. am. am. \nuh H11; ee. rw H16. am. \n\nutil (H1 u v). am. am. am. \nrw lem3. uh H10; ee. am. am. am. am. \nrww lem3. util (H1 u v). am. am. am. \nuh H10; ee. rw H14. am. \n\nuf k. \nap create_like. \nQed. \n\n\n\nLemma ob_existence_rw : forall a x,\nob a x = (exists f, (mor a f & source f = x)).\nProof.\nir. ap iff_eq; ir. \nrwi ob_facts_rw H. uh H; ee. sh (id a x); xd. \nnin H. ee. rwi mor_facts_rw H. uh H; ee. wr H0; am. \nQed. \n\nLemma left_id: forall a b x u,\nob a x -> mor a u -> target u = x -> a = b ->\ncomp a (id b x) u = u.\nProof.\nir. rwi mor_facts_rw H0; uh H0; ee.\nwr H2; wr H1; am.  \nQed.\n\nLemma right_id : forall a b x u, \nob a x -> mor a u -> source u = x -> a= b ->\ncomp a u (id b x) = u.\nProof.\nir. rwi mor_facts_rw H0; uh H0; ee.\nwr H2; wr H1; am.\nQed. \n\nLemma left_id_unique : forall a e x,\naxioms a -> mor a e -> \nsource e = x ->\n(forall f, composable a e f -> comp a e f = f) ->\ne = id a x.\nProof.\nir. \nrwi mor_facts_rw H0. wr H1. uh H0; ee.\ntransitivity (comp a e (id a x)). \nrw right_id; try tv; try lu. wr H1; am.\nwr H2. wr H1; tv. ap show_composable. \nam. rwi ob_facts_rw H3; uh H3; ee; am. \nrwi ob_facts_rw H3; uh H3; ee; sy; am.  \nQed. \n\nLemma right_id_unique : forall a e x,\naxioms a -> mor a e -> \ntarget e = x ->\n(forall f, composable a f e -> comp a f e = f) ->\ne = id a x.\nProof.\nir. \nrwi mor_facts_rw H0. wr H1. uh H0; ee.\ntransitivity (comp a (id a (target e)) e). \nrw left_id; try tv; try lu. \nap H2. ap show_composable. \nrwi ob_facts_rw H4; uh H4; ee; am. am. \nrwi ob_facts_rw H4; uh H4; ee; am.  \nQed. \n\nDefinition same_data (o m : E) (c : E2) (i: E1)\n(o1 m1 : E) (c1 : E2) (i1: E1):=\n(forall x, inc x o = inc x o1) &\n(forall u, inc u m = inc u m1) &\n(forall u v, inc u m -> inc v m -> source u = target v -> c u v = c1 u v) &\n(forall x, inc  x o -> i x = i1 x).\n\n\nLemma ob_create : forall o m c i s x,\nproperty o m c i-> ob (create o m c i s) x = inc x o. \nProof.\nir. \nset (k:= create o m c i s). \nassert (lem0 : axioms k). \nuf k; ap create_axioms; am. \nassert (lem1 : forall x, ob k x = is_ob k x).\nir. ap iff_eq; ir. lu. uhg; ee; am. \nrw lem1. uf k; rw is_ob_create; tv. \nQed. \n\nLemma mor_create : forall o m c i s u,\nproperty o m c i-> mor (create o m c i s) u = inc u m. \nProof.\nir. \nset (k:= create o m c i s). \nassert (lem0 : axioms k). \nuf k; ap create_axioms; am. \nassert (lem1 : forall u, mor k u = is_mor k u).\nir. ap iff_eq; ir. lu. uhg; ee; am. \nrw lem1. uf k; rw is_mor_create; tv. \nQed. \n\nLemma uncomp : forall a b u v u1 v1,\na = b -> u = u1 -> v = v1 -> comp a u v = comp b u1 v1.\nProof.\nir. rw H; rw H0; rw H1; tv. \nQed. \n\nLemma U_morphisms : forall a,\n(U a) = morphisms a. \nProof.\nir. tv. \nQed. \n\nLemma is_mor_mor : forall a u,\naxioms a -> is_mor a u -> mor a u.\nProof.\nir. uh H; ee. \nrwi H1 H0. uhg; uh H0; xd. \nuhg; au. \nQed.\n\nLemma is_ob_ob : forall a x,\naxioms a -> is_ob a x -> ob a x.\nProof.\nir. uh H; ee. \nrwi H H0. uhg; uh H0; xd. \nuhg; au. \nQed. \n\nLemma ob_is_ob : forall a x,\nob a x -> is_ob a x.\nProof.\nir. lu. \nQed.\n\nLemma mor_id : forall a x,\nob a x -> mor a (id a x).\nProof.\nir. rwi ob_facts_rw H; uh H; ee. am. \nQed.\n\nLemma mor_id_rw : forall a x,\nob a x -> mor a (id a x) = True.\nProof.\nir. ap iff_eq; ir; try tv. app mor_id. \nQed. \n\nLemma source_id : forall a x,\nob a x -> source (id a x) = x.\nProof.\nir. rwi ob_facts_rw H; uh H; ee. am. \nQed.\n\nLemma target_id : forall a x,\nob a x -> target (id a x) = x.\nProof.\nir. rwi ob_facts_rw H; uh H; ee. am. \nQed. \n\nLemma ob_source : forall a u,\nmor a u -> ob a (source u) = True.\nProof.\nir. rwi mor_facts_rw H; uh H; ee. \nap iff_eq; ir; try tv; try am. \nQed.\n\nLemma ob_target : forall a u,\nmor a u -> ob a (target u) = True.\nProof.\nir. rwi mor_facts_rw H; uh H; ee. \nap iff_eq; ir; try tv; try am.  \nQed. \n\nLemma mor_comp : forall a b u v,\nmor a u -> mor a v -> \nsource u = target v -> a = b -> mor a (comp b u v)= True.\nProof.\nir. wr H2. assert (composable_facts a u v).\nap show_composable_facts; am. \nap iff_eq; ir; try tv; try am. lu. \nQed.\n\n\nLemma source_comp : forall a u v,\nmor a u -> mor a v -> \nsource u = target v -> source (comp a u v) = source v.\nProof.\nir. assert (composable_facts a u v).\nap show_composable_facts; am. lu. \nQed.\n\n\nLemma target_comp : forall a u v,\nmor a u -> mor a v -> \nsource u = target v ->target (comp a u v) = target u.\nProof.\nir. assert (composable_facts a u v).\nap show_composable_facts; am. lu. \nQed.\n\n\nLemma assoc : forall a b u v w,\nmor a u -> mor a v -> mor a w ->\nsource u = target v -> source v = target w ->\na= b ->\ncomp a (comp b u v) w = comp a u (comp b v w).\nProof.\nir. wr H4. \nassert (associativity_facts a u v w). \nap show_associativity_facts; ap show_composable;\nam.   \nuh H5; ee. sy; am. \nQed. \n\n\n\nLemma mor_arrow_like : forall a u,\nmor a u -> Arrow.like u. \nProof.\nir. rwi mor_facts_rw H. lu. \nQed. \n \n\nHint Rewrite left_id right_id mor_id_rw source_id target_id\nob_source ob_target mor_comp source_comp target_comp : cw. \n\nLemma mor_inc_U : forall a u,\nmor a u -> inc u (U a).\nProof.\nir. change (is_mor a u); lu. \nQed.\n\nLemma mor_is_mor : forall a u,\nmor a u -> is_mor a u.\nProof.\nir. lu.\nQed.\n\n\n\n\n\nDefinition opp' a :=\nNotations.create (objects a) (Image.create (morphisms a) flip)\n(fun u v => flip (comp a (flip v) (flip u)))\n(fun x => flip (id a x)) (structure a).\n\nLemma is_ob_opp' : forall a x,\nis_ob (opp' a) x = is_ob a x.\nProof.\nir. uf opp'. rw is_ob_create. tv. \nQed.\n\nLemma structure_opp' : forall a, structure (opp' a) =\nstructure a. \nProof.\nir. uf opp'. rww structure_create. \nQed. \n\nLemma inc_image_create_flip : forall a u,\ninc u (Image.create (morphisms a) flip) = is_mor (opp' a) u.\nProof.\nir. uf opp'. rw is_mor_create. tv. \nQed.\n\nLemma is_mor_opp' : forall a u,\nis_mor (opp' a) u = is_mor a (flip u).\nProof.\nir. uf opp'. rw is_mor_create. \nrw Image.inc_rw. app iff_eq; ir. \nnin H. ee. wr H0. rw flip_flip. \nam. \nsh (flip u). ee. am. rww flip_flip. \nQed.\n\n\nLemma comp_opp' : forall a u v,\nis_mor (opp' a) u -> is_mor (opp' a) v -> \nsource u = target v -> \ncomp (opp' a) u v = flip (comp a (flip v) (flip u)).\nProof.\nir. uf opp'. rw comp_create. tv. \nrww inc_image_create_flip. \nrww inc_image_create_flip. am. \nQed.\n\nLemma id_opp' : forall a x,\nis_ob (opp' a) x -> \nid (opp' a) x = flip (id a x).\nProof.\nir. uf opp'. rw id_create. tv. \nufi opp' H. rwi is_ob_create H. am. \nQed. \n\nLemma opp'_opp' : forall a, \naxioms a -> opp' (opp' a) = a.\nProof.\nir. assert (like a). \nlu.  uh H0. \ntransitivity (create (objects a) (morphisms a) (comp a) (id a)\n(structure a)).\nassert (Image.create (Image.create (morphisms a) flip) flip \n= morphisms a). \nap extensionality; uhg; ir. rwi Image.inc_rw H1.\nnin H1. ee. rwi Image.inc_rw H1. nin H1. ee. \nwr H2. wr H3. rw flip_flip. am. \nap Image.show_inc. sh (flip x). ee. \nap Image.show_inc. sh x. ee. am. tv. \nrww flip_flip. \n\nuf opp'. ap create_extensionality. \nrww objects_create. rw morphisms_create.\nam. \nrw morphisms_create. rw H1. ir. \nrw comp_create. rw flip_flip. rw flip_flip. rww flip_flip.\nap Image.show_inc. sh v; ee; try am. tv. \nap Image.show_inc. sh u; ee; try tv; try am. \nrw source_flip. rw target_flip. sy; am. \napply mor_arrow_like with a. app is_mor_mor. \napply mor_arrow_like with a. app is_mor_mor. \nrw objects_create. ir. \nrw id_create. rww flip_flip. am. rww structure_create.\nsy; am. \nQed. \n\n\n\nLemma opp'_axioms : forall a, \naxioms a -> axioms (opp' a).\nProof.\nir. \nassert (morli : forall u, is_mor a u -> Arrow.like u). \nir. uh H; ee. rwi H1 H0. uh H0; ee. am. \nassert (obidli : forall x, is_ob a x -> Arrow.like (id a x)). \nir. uh H. ee. rwi H H0. uh H0. ee. \nap morli. am. \nassert (flifli : forall u, flip (flip u) = u). \nir. rw flip_flip. tv. \n\n \n\nuf opp'. ap create_axioms. \nassert (ax : axioms a).\nam. \nuh H; ee. \nassert (alike : like a).\nam. clear H3. \nuhg; dj;\ntry (ap iff_eq; ir). \n\nassert (ob a x). apply is_ob_ob. am. am. \nuhg; ee. am. \nap Image.show_inc. sh (id a x). ee. \nap mor_is_mor. ap mor_id. ap is_ob_ob. am. \nam. tv. rw source_flip. rww target_id. \nap obidli. am. \nrw target_flip. rww source_id. app obidli. \nlu. \n\nassert (mor a (flip u)). \nrwi Image.inc_rw H4. nin H4; ee. \nap is_mor_mor. am. wr H5. rw flip_flip.\nam. \n\n\nuhg; ee. am. wr (flifli u). \nrw source_flip. \nuh H5; ee. rwi H0 H6. lu. \nap morli. lu. \nwr source_flip. \nap ob_is_ob. rww ob_source. \nrw like_flip. ap morli. lu. \nrw flip_flip. rw left_id. rww flip_flip. \nwr target_flip. rww ob_target. \nrw like_flip. ap morli. lu. \nam. rww target_flip. \nrw like_flip. ap morli. lu. tv. \nrw flip_flip. rw right_id. rww flip_flip.\nwr source_flip. rww ob_source. \nrw like_flip. ap morli. lu. \nam. rww source_flip. \nrw like_flip. ap morli. lu. tv. \nrw like_flip. ap morli. lu. \nlu. \n\nassert (mor a (flip u)). \nrwi Image.inc_rw H5. nin H5; ee. wr H8. rw flip_flip.\napp is_mor_mor. \nassert (mor a (flip v)). \nrwi Image.inc_rw H6. nin H6; ee. wr H9. rw flip_flip.\napp is_mor_mor. \nassert (Arrow.like u). \nrw like_flip. ap morli. ap mor_is_mor. am. \nassert (Arrow.like v). \nrw like_flip. ap morli. ap mor_is_mor. am. \n\nuhg; ee. am. am. am. \nap Image.show_inc. \nsh (comp a (flip v) (flip u)). ee. \nap mor_is_mor. rw mor_comp. tv. \nam. am. rw source_flip. rw target_flip. sy; am. \nrw like_flip. ap morli. ap mor_is_mor. tv. \nrw like_flip. ap morli. ap mor_is_mor. am. tv. \ntv. rw source_flip. rw target_comp. rww target_flip.\n\nam. am. rw source_flip. rw target_flip. sy; am. am. am.\nap morli. ap mor_is_mor. rw mor_comp. \ntv. am. am. \n rw source_flip. rw target_flip. sy; am. \n\ntv. am. tv. \nrw target_flip. rw source_comp. rww source_flip. \n\nam. am. rw source_flip. rww target_flip. \nsy; am. am. \n\nap morli. ap mor_is_mor. rw mor_comp. \ntv. am. am. \n rww source_flip. rww target_flip. sy; am. \n\ntv. \nrw flip_flip. rw flip_flip. \n\nassert (mor a (flip u)). \nrwi Image.inc_rw H6. nin H6; ee. wr H11. rw flip_flip.\napp is_mor_mor. \nassert (mor a (flip v)). \nrwi Image.inc_rw H7. nin H7; ee. wr H12. rw flip_flip.\napp is_mor_mor. \nassert (mor a (flip w)). \nrwi Image.inc_rw H8. nin H8; ee. wr H13. rw flip_flip.\napp is_mor_mor. \nassert (Arrow.like u). \nrw like_flip. ap morli. ap mor_is_mor. am. \nassert (Arrow.like v). \nrw like_flip. ap morli. ap mor_is_mor. am. \nassert (Arrow.like w). \nrw like_flip. ap morli. ap mor_is_mor. am. \n\nrw assoc. tv. am. am. am. \nrww source_flip. rww target_flip. sy; am. \nsy; rww source_flip; rww target_flip. tv. \nQed. \n\n\nDefinition opp a := Y (axioms a) (opp' a) a.\n\nLemma axioms_opp : forall a,\naxioms (opp a) = axioms a.\nProof.\nir. apply by_cases with (axioms a); ir.\nassert (opp a = opp' a). \nuf opp. ap (Y_if  H). tv. \nrw H0. \nap iff_eq; ir. am. ap opp'_axioms. am. \nassert (opp a = a). \nuf opp. ap (Y_if_not H). tv. rww H0. \nQed. \n\nLemma opp_axioms : forall a, axioms a -> axioms (opp a).\nProof.\nir. rww axioms_opp. \nQed. \n\nLemma opp_opp : forall a, opp (opp a) = a.\nProof.\nir. apply by_cases with (axioms a); ir. \nassert (opp a = opp' a).\nuf opp. ap (Y_if  H). tv. \nrw H0. \nassert (axioms (opp' a)). ap opp'_axioms. am. \nassert (opp (opp' a) = opp' (opp' a)).\nuf opp. ap (Y_if  H1). reflexivity. \nrw H2. rw opp'_opp'. tv. am. \nassert (opp a = a). \nuf opp. ap (Y_if_not H). tv. rw H0. \nuf opp. ap (Y_if_not H). tv.\nQed. \n\nLemma structure_opp : forall a, structure (opp a) = structure a.\nProof.\nir. \napply by_cases with (axioms a); ir. \nassert (opp a = opp' a).\nuf opp. ap (Y_if  H). tv. \nrw H0. rww structure_opp'. \nassert (opp a = a). \nuf opp. ap (Y_if_not H). tv.\nrww H0. \nQed. \n\nLemma ob_opp' : forall a x,\naxioms a -> \nob (opp' a) x = ob a x.\nProof.\nir. \nsy. ap iff_eq; ir. \nuhg; ee. ap opp'_axioms. lu. \nrw is_ob_opp'. lu. \nuhg; ee. am. \nwr is_ob_opp'. lu. \nQed. \n\nLemma mor_opp' : forall a u,\naxioms a -> \nmor (opp' a) u = mor a (flip u).\nProof.\nir. \nassert (lem : forall b v, axioms b -> \nmor (opp' b) v -> mor b (flip v)).\nir. uhg; ee. am. uh H1; ee. \nrwi is_mor_opp' H2. am. \nap iff_eq; ir. au. \nassert (u = flip (flip u)). \nrw flip_flip; tv. \nuhg; ee. ap opp'_axioms. am. \nrw is_mor_opp'. app  mor_is_mor. \nQed. \n\nLemma unfold_opp : forall a, axioms a -> \nopp a = opp' a.\nProof.\nir. uf opp. ap (Y_if H). tv. \nQed.\n\n\nLemma ob_opp : forall a x,\nob (opp a) x = ob a x.\nProof.\nir. ap iff_eq; ir. \nassert (axioms a). wr axioms_opp. uh H; ee; am. \nrwi unfold_opp H. rwi ob_opp' H. am. \nam. am. \nassert (axioms a). uh H; ee; am. \nrww unfold_opp. rww ob_opp'. \nQed. \n\nLemma mor_opp : forall a u,\nmor (opp a) u = mor a (flip u).\nProof.\nir. ap iff_eq; ir. \nassert (axioms a). wr axioms_opp. uh H; ee; am. \nrwi unfold_opp H. rwi mor_opp' H. am. \nam. am. \nassert (axioms a). uh H; ee; am. \nrww unfold_opp. rww mor_opp'. \nQed. \n\nLemma comp_opp : forall a u v,\nmor (opp a) u -> mor (opp a) v -> source u = target v ->\ncomp (opp a) u v = flip (comp a (flip v) (flip u)).\nProof.\nir. assert (axioms a). \nwr axioms_opp. uh H; ee; am. \nrw unfold_opp. rw comp_opp'. \ntv. ap mor_is_mor. wrr unfold_opp. \nap mor_is_mor. wrr  unfold_opp. tv. am. \nQed.\n\n\nLemma id_opp : forall a x,\nob (opp a) x -> \nid (opp a) x = flip (id a x).\nProof.\nir. assert (axioms a). \nwr axioms_opp. uh H; ee; am. \nrw unfold_opp. rww id_opp'. ap ob_is_ob. \nwrr unfold_opp. am.  \nQed. \n\n\nLemma composable_opp : forall a u v,\naxioms a -> \ncomposable (opp a) u v = composable a (flip v) (flip u).\nProof.\nir. ap iff_eq; ir. \nrwi composable_facts_rw H0; ap show_composable;  \ntry (wr mor_opp; lu); try (rw mor_opp; lu). \nrw source_flip. rw target_flip; try (sy; lu). \napply mor_arrow_like with (opp a); lu. \napply mor_arrow_like with (opp a); lu. \nrwi composable_facts_rw H0. ap show_composable. \nuh H0; ee. rww mor_opp. rww mor_opp. \nlu. uh H0; ee. \nwr source_flip. wr target_flip. \nsy; am. rw like_flip. apply mor_arrow_like with a; lu. \nrw like_flip; apply mor_arrow_like with a; lu. \nQed. \n\n\n\nDefinition are_inverse a u v :=\nmor a u & mor a v &\nsource u = target v &\nsource v = target u &\ncomp a u v = id a (source v) &\ncomp a v u = id a (source u).\n\n\n\nLemma are_inverse_symm :forall a u v,\nare_inverse a u v -> are_inverse a v u.\nProof.\nir. uh H; ee. uhg; ee; try am. \nQed. \n\nDefinition invertible a u := \nexists v, are_inverse a u v.\n\nDefinition inverse a u := choose (are_inverse a u).\n\nLemma invertible_inverse :\nforall a u, invertible a u -> are_inverse a u (inverse a u).\nProof.\nir. exact (choose_pr H). \nQed.\n\nLemma inverse_unique : forall a u v w,\nare_inverse a u v -> are_inverse a u w -> v = w.\nProof.\nir. uh H; uh H0; ee. \ntransitivity (comp a (comp a v u) w).\nrw assoc. rw H4.\nrw right_id. tv. \nuh H0; ee. cw. am.  rww H3. tv. \nam. am. am. am. am. tv. \nrw H10. cw. cw.  sy; am. \nQed. \n\nLemma inverse_uni : forall v w,\n(exists a, exists u, (are_inverse a u v & are_inverse a u w)) ->\nv = w. \nProof.\nir. nin H. nin H. ee. \nexact (inverse_unique H H0). \nQed. \n\nLemma inverse_eq : forall a u v,\nare_inverse a u v -> inverse a u = v. \nProof.\nir. ap inverse_uni. sh a. sh u. ee.\nap invertible_inverse. uhg. sh v; am. am. \nQed. \n\nLemma inverse_invertible : forall a u,\ninvertible a u -> invertible a (inverse a u).\nProof.\nir. uhg. sh u. ap are_inverse_symm. \nap invertible_inverse. am. \nQed.\n\nLemma inverse_inverse : forall a u,\ninvertible a u -> inverse a (inverse a u) = u.\nProof.\nir. apply inverse_unique with a (inverse a u). \nap invertible_inverse. ap inverse_invertible. am. \nap are_inverse_symm. ap invertible_inverse. am. \nQed. \n\nLemma source_inverse : forall a u,\ninvertible a u -> source (inverse a u) = target u.\nProof.\nir. cp (invertible_inverse H). uh H0; ee. \nlu. \nQed.\n\nLemma target_inverse : forall a u,\ninvertible a u -> target (inverse a u) = source u.\nProof.\nir. cp (invertible_inverse H). uh H0; ee. \nsy; lu. \nQed.\n\nLemma left_inverse : forall a u,\ninvertible a u -> comp a (inverse a u) u = id a (source u).\nProof.\nir. cp (invertible_inverse H). uh H0; ee. am. \nQed.\n\nLemma right_inverse : forall a u,\ninvertible a u -> comp a u (inverse a u) = id a (target u).\nProof.\nir. cp (invertible_inverse H). uh H0; ee. \nrwi source_inverse H4. am. am.  \nQed. \n\n\n\nLemma mor_inverse : forall a u,\ninvertible a u -> \nmor a (inverse a u).\nProof.\nir. cp (invertible_inverse H). uh H0; ee. lu. \nQed.\n\nLemma mor_inverse_rw : forall a b u,\ninvertible a u -> a = b -> \nmor a (inverse b u) = True.\nProof.\nir. app iff_eq; ir. wr H0. app mor_inverse. \nQed.\n\nHint Rewrite source_inverse target_inverse left_inverse\nright_inverse mor_inverse_rw :cw.\n\nLemma composable_inverse_left : forall a u,\ninvertible a u -> composable a (inverse a u) u.\nProof.\nir. cp (invertible_inverse H). uh H0; ee.\nap show_composable; lu. \nQed.\n\nLemma composable_inverse_right : forall a u,\ninvertible a u -> composable a u (inverse a u).\nProof.\nir. cp (invertible_inverse H). uh H0; ee.\nap show_composable; lu.\nQed. \n\nLemma composable_inverse : forall a u v,\ncomposable a u v -> invertible a u -> invertible a v ->\ncomposable a (inverse a v) (inverse a u).\nProof.\nir. \ncp (invertible_inverse H0).\ncp (invertible_inverse H1). \ncp H. rwi composable_facts_rw H; uh H; ee. \nap show_composable. lu. lu. \nrw source_inverse; try am. rw target_inverse; try am. \nsy; am. \nQed. \n\nLemma invertible_comp_are_inverse : forall a u v,\ncomposable a u v -> invertible a u -> invertible a v ->\nare_inverse a (comp a u v) (comp a (inverse a v) (inverse a u)).\nProof.\nir. \ncp (invertible_inverse H0).\ncp (invertible_inverse H1). \ncp H. rwi composable_facts_rw H; uh H; ee. \n\n\nuhg; ee; try am. cw. lu. lu.  \ncw. \nsy; lu. \ncw.  lu. lu. cw. sy; lu. \ncw. lu. lu. cw. sy; lu. \ncw. \nrw assoc. \nassert (comp a v (comp a (inverse a v) (inverse a u))=\ninverse a u).\nwr assoc. cw. \ncw. cw. cw. cw. cw. lu. cw. cw.  sy; lu. tv. \nrw H12. cw. lu. lu. cw. lu. lu. \ncw. sy; lu. lu. cw. lu. lu. cw. \nsy; lu. tv. lu. lu. cw. sy; lu. \nrw assoc. \nassert (comp a (inverse a u) (comp a u v) = v).\nwrr assoc. cw. cw. sy; lu. cw. cw. \nrw H12. cw. cw. cw. cw. cw. sy; lu. cw. tv. \nQed. \n\nLemma invertible_comp : forall a u v,\ncomposable a u v -> invertible a u -> invertible a v ->\ninvertible a (comp a u v).\nProof.\nir. uhg; sh (comp a (inverse a v) (inverse a u)). \nap invertible_comp_are_inverse; am. \nQed.\n\nLemma inverse_comp : forall a u v,\ncomposable a u v -> invertible a u -> invertible a v ->\ninverse a (comp a u v) = comp a (inverse a v) (inverse a u).\nProof.\nir. ap inverse_eq. ap invertible_comp_are_inverse; am. \nQed. \n\n\nLemma identity_are_inverse : forall a x,\nob a x -> are_inverse a (id a x) (id a x). \nProof.\nir. rwi ob_facts_rw H. uh H; ee. \nuhg; ee; try am. cw. cw. cw. cw. \nQed. \n\nLemma inverse_id : forall a x,\nob a x -> inverse a (id a x) = id a x.\nProof.\nir. ap inverse_eq. ap identity_are_inverse; am. \nQed. \n\nHint Rewrite inverse_id : cw.\n\nLtac alike :=\nmatch goal with \nid1 : (mor _ ?X1) |- (Arrow.like ?X1) =>\nexact (mor_arrow_like id1) |\n_=>fail \nend. \n\n\nEnd Category.\n\n\n\n\n", "meta": {"author": "coq-contribs", "repo": "cats-in-zfc", "sha": "aa7067a8d0a243caec7288dffd1e0a86c65ece0e", "save_path": "github-repos/coq/coq-contribs-cats-in-zfc", "path": "github-repos/coq/coq-contribs-cats-in-zfc/cats-in-zfc-aa7067a8d0a243caec7288dffd1e0a86c65ece0e/category.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.29401823603226596}}
{"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 A B C D E F X Dprime : Universe, ((wd_ A B /\\ (wd_ A D /\\ (wd_ B C /\\ (wd_ D E /\\ (wd_ D Dprime /\\ (wd_ C Dprime /\\ (wd_ A C /\\ (wd_ B D /\\ (wd_ E F /\\ (wd_ E C /\\ (wd_ C D /\\ (wd_ F C /\\ (wd_ F D /\\ (wd_ X C /\\ (wd_ X D /\\ (wd_ E A /\\ (wd_ B F /\\ (col_ A B C /\\ (col_ A B D /\\ (col_ A E F /\\ (col_ B E F /\\ col_ D C Dprime))))))))))))))))))))) -> col_ A B E)).\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_0752.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2938945071075044}}
{"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 A B C D0 D Y0 Y X : Universe, ((wd_ B A /\\ (wd_ A D0 /\\ (wd_ B D0 /\\ (wd_ B C /\\ (wd_ A C /\\ (wd_ B D /\\ (wd_ C D /\\ (wd_ Y B /\\ (wd_ Y A /\\ (wd_ D A /\\ (wd_ Y X /\\ (wd_ Y0 D /\\ (wd_ B Y0 /\\ (wd_ A Y0 /\\ (wd_ Y D /\\ (col_ B C Y /\\ (col_ Y0 D Y /\\ (col_ A B X /\\ (col_ B D Y /\\ col_ B D0 D))))))))))))))))))) -> col_ B C D)).\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_0400.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.29389450271214534}}
{"text": "From mathcomp.ssreflect Require Import ssreflect ssrnat seq eqtype ssrbool.\nFrom mathcomp.algebra Require Import ssrint ssralg.\nFrom Coq.Strings Require Import Ascii String.\nRequire Import Coq.Program.Program.\nRequire Import Program.\nRequire Import UtilString.\nRequire Import ProofIrrelevance.\nImport intZmod.  \nRequire Import Common Types Memory Extraction.\n\n\n       \nRecord var_descr := declare_var { var_name: string; var_type: ctype; location: nat }.\n       Definition var_descr_beq (x y: var_descr) : bool :=\n         (var_name x == var_name y)  && (var_type x == var_type y) && (location x == location y).\n       Theorem var_descr_eq_dec: eq_dec var_descr.\n         rewrite /eq_dec.\n         decide equality.\n         decide equality.\n         apply ctype_eq_dec.\n         apply string_eq_dec.\n       Qed.\n\n       Definition var_descr_eqP := reflect_from_dec var_descr_eq_dec.\n       \n       Canonical var_descr_eqMixin := EqMixin var_descr_eqP.\n       Canonical var_descr_eqType := EqType var_descr var_descr_eqMixin.\n\n  \nInductive binop : Set := | Add | Sub | Mul | Div | LAnd | LOr | Eq .\n       Scheme Equality for binop.\n       Definition binop_eqP := reflect_from_dec binop_eq_dec.\n       Canonical binop_eqMixin := EqMixin binop_eqP.\n       Canonical binop_eqType := EqType binop binop_eqMixin.\n       \nInductive unop: Set := | Neg | Invert | Not | Convert (to:ctype) | Amp | Asterisk .\n       Definition unop_beq (x y : unop) : bool :=\n         match x, y with\n           | Neg, Neg  |Invert, Invert | Not, Not | Amp, Amp | Asterisk, Asterisk => true\n           | Convert t1, Convert t2 => t1 == t2\n           | _, _ => false\n         end.\n\n       Lemma unop_eqP: Equality.axiom unop_beq.\n         move=> x y.\n         case Heq: (unop_beq _ _); move: Heq. \n         case x; case y =>//=; try by constructor.\n         move=> t0 t1. by move /eqP =>->; constructor.\n         case x; case y => //=; try by constructor.\n         move=> t0 t1  /eqP => Hneq. constructor. by case.\n       Qed.\n       Canonical unop_eqMixin := EqMixin unop_eqP.\n       Canonical unop_eqType := EqType unop unop_eqMixin.\n       Definition unop_eq_dec := dec_from_reflect unop_eqP.\n\nInductive expr :=\n       | Lit   (t:ctype) (_:coq_type(t))\n       | EDeallocated (t:ctype)\n       | EGarbage (t:ctype)\n       | Var   (_:string)\n       | Binop (_:binop) (_ _: expr)\n       | Unop  (_:unop)  (_: expr).\n\nInductive statement :=\n       | Skip\n       | Call : string -> seq expr -> statement (* return values do not exist *)\n       | Assign: expr -> expr -> statement\n       | Alloc: storage -> ctype -> option string -> nat -> statement\n       | If: expr -> statement -> statement -> statement\n       | While: expr -> statement -> statement\n       | CodeBlock: seq statement -> statement\n       | Debug\n       | Enter\n       | Leave .\n\nRecord function := mk_fun {\n                       fun_id: nat;\n                       fun_name: string;\n                       args: seq (string * ctype);\n                       body: statement;\n                       fun_location: nat}. (* all functions are void; if they return smth it is written by pointer passed as arg *)\n\nRecord static_ctx : Set := mk_stat_ctx { functions: seq function; variables: seq ( seq var_descr ) }.\n       Definition stat_ctx_empty:= mk_stat_ctx [::] [::].\n       Definition stat_ctx_mod (s:static_ctx)\n                  (mfuns: seq function -> seq function) (mvars: seq (seq var_descr)  -> seq (seq var_descr )) :=\n         mk_stat_ctx (mfuns $ functions s) (mvars $ variables s).\n\nRecord dynamic_ctx : Set := mk_dyn_ctx { memory: seq block; call_stack: seq statement }.\n       Definition dyn_ctx_mod (d:dynamic_ctx)\n                  (mmem: seq block -> seq block) (mcs: seq statement -> seq statement) :=\n         mk_dyn_ctx (mmem $ memory d) (mcs $ call_stack d).\n  \n       Definition dynamic_ctx_empty := mk_dyn_ctx [::] [::].\n       Definition dyn_ctx_push (d:dynamic_ctx) (s:statement) : dynamic_ctx := mk_dyn_ctx (memory d) (s::call_stack d).\n       Definition get_var (sc:static_ctx) (name:string) : option var_descr :=\n         option_find (fun p: var_descr => var_name p == name) (flatten (variables sc)).\n       Definition get_fun (sc:static_ctx) (name:string) : option function :=\n         option_find (fun p: function => fun_name p == name) (functions sc).\n\nFixpoint type_solver {sc: static_ctx}  (e: expr) : ctype:=\n  let slv := @type_solver sc  in\n  match e with\n    | Lit t _ => t\n    | EDeallocated t => t\n    | EGarbage t => t\n    | Var name => match get_var sc name with\n                    | Some v => Pointer $ var_type v\n                    | None => ErrorType\n                  end\n    | Binop _ l r => eq_value_or_error_arith (slv l) (slv r) (fun t _ => t) ErrorType\n    | Unop Asterisk op => match slv op with\n                            | Pointer t => t\n                            | _ => Bot\n                          end\n    | Unop _ o => slv o\n  end.\n\n\n\n\nDefinition binop_interp (t:ctype) (op: binop) : int -> int -> value :=\n  match t with\n    | Int num => match op with\n                   | Add => fun x y=> Value (Int num) $ addz x y\n                   | Sub => fun x y=> Value (Int num) $ addz x (oppz y)\n                   | Mul => fun x y => Value (Int num) $ intRing.mulz x y\n                   | Eq  => fun x y=> Value (Int num) $ Posz $ if x == y then 1 else 0\n                   | _ => fun _ _ => Error\n                 end\n    | _ => fun _ _ => Error\n  end.\n\nDefinition unop_interp (t:ctype) (op:unop) : int -> value  :=\n  match t with\n    | Int kind =>\n      match op with\n        | Neg => fun x => Value (Int kind) $ oppz x\n        | Not => fun x => Value (Int kind) $ Posz $ if sgz x == 0 then 1 else 0\n        | _ => fun _ => Error\n      end\n    | _ => fun _ => Error\n  end.\n  \nDefinition find_block (m: dynamic_ctx) (i: nat)  : option block :=\n  option_find (fun b=> block_id b == i) $ memory m.\n\nDefinition dereference (dyn:dynamic_ctx) (v:value) : value :=\n  match v with\n    | Value (Pointer pt) (Goodptr i o) =>\n      match option_nth (memory dyn) i with\n        | Some (mk_block lo _i sz block_type contents) =>\n          if block_type == pt then nth Error contents o else Error\n        | None => Error\n      end\n    | _ => Error\n  end.\n\nFixpoint iexpr (stat:static_ctx) (dyn: dynamic_ctx) (e:expr) : value :=\n  let interp := iexpr stat dyn in\n  let type := @type_solver stat in\n  let vars := flatten $ variables stat in\n  let blocks := memory dyn in\n  match e with\n    | Lit t v => Value t v\n    | EDeallocated t => Deallocated\n    | EGarbage t => Garbage\n    | Var name => match get_var stat name  with\n                    | Some (declare_var n t loc) =>\n                      match find_block dyn loc with\n                        | Some b =>\n                          if el_type b == t\n                          then Value (Pointer t) (Goodptr t loc 0)\n                          else Error\n                        | None => Error\n                      end\n                    | None => Error\n                  end\n    | Binop opcode l r =>\n      match interp l, interp r with\n        | Value (Int kx) x, Value (Int ky) y =>\n          eq_value_or_error_arith (Int kx) (Int ky) (fun tx ty => binop_interp (type e) opcode x y) Error\n        | _, _ => Error\n      end\n    | Unop Asterisk op => match interp op with\n                            | Value (Pointer pt) p => dereference dyn (interp op)\n                            |_ => Error\n                          end\n    | Unop code op =>\n      match interp op with\n        | Value (Int kind) v => unop_interp (type e) code v\n        |_ => Error\n      end\n  end.\n\n      Definition alloc_block {dc: dynamic_ctx} (b:block) : dynamic_ctx := mk_dyn_ctx ( (memory dc) ++ [:: b] ) (call_stack dc).\n\n      Definition next_block_id (s:dynamic_ctx) : nat := size $ memory $ s.\n\n      Fixpoint garbage_values (sz: nat) : seq value :=\n        match sz with | n .+1 => Garbage :: (garbage_values n) | 0 => [::] end.\n\n      Definition bind_var (v:var_descr) (i:nat) (ctx:static_ctx) :=\n        mk_stat_ctx (functions ctx) $ match variables ctx with\n                                        | [::] => [:: [:: v] ]\n                                        | cons x xs => cons (cons v x) xs\n                                      end.\n      \n      \nInductive prog_state :=\n      | Good: static_ctx -> dynamic_ctx -> prog_state\n      | Bad : static_ctx -> dynamic_ctx -> statement -> prog_state.\n      \n      Definition stat_init := mk_stat_ctx nil [:: nil (*[:: declare_var \"Unit\" Unit 0 ] *) ].\n      Definition get_stat p := match p with | Good s _ | Bad s _ _ => s end.\n      Definition get_dyn p := match p with | Good _ d| Bad _ d _ => d end.\n\n      Definition add_static_ctx (s:prog_state) :=\n        match s with\n          | Good stat dyn => Good (mk_stat_ctx (functions stat) ( [::] :: variables stat) ) dyn\n          | Bad _ _ _ as s => s\n        end.\n      \n      Definition remove_static_ctx (s:prog_state) :=\n        match s with | Good stat dyn =>\n                       match variables stat with\n                         | [::] => s\n                         | vs::vvs => Good (mk_stat_ctx (functions stat) vvs) dyn\n                       end\n                  | s => s\n        end.\n\nDefinition block_mod (b: block) (idx: nat) (e: value) : block? :=\n        if idx * ( SizeOf (el_type b)) >= block_size b then None else\n          match e with\n            | Value t v =>\n              match el_type b == t with\n                | true => Some $ mk_block\n                               (region b)\n                               (block_id b)\n                               (block_size b)\n                               (el_type b)\n                               (set_nth Error (contents b) idx (Value t v))\n                | false => None\n              end\n            | Garbage as e\n            | Deallocated as e=>  Some $ mk_block\n                               (region b)\n                               (block_id b)\n                               (block_size b)\n                               (el_type b)\n                               (set_nth Error (contents b) idx e)\n            | Error => None\n        end.\n\nDefinition ex_block := mk_block Stack 0 64 Int64 (garbage_values 8).\nEval compute in block_mod ex_block 1 (Value Int64 3).\n\nDefinition ErrorBlock := mk_block Data 0 0 ErrorType [::].\n\nDefinition mem_write (dyn: dynamic_ctx)  (bid:nat) (pos: nat) (val:value) : dynamic_ctx? :=\n  let m := memory dyn in\n  let oldblock := option_nth m bid in\n  let can_write v tp := match v with\n                          | Value t v => t == tp\n                          | Garbage \n                          | Deallocated => true\n                          | Error => false\n                        end in\n  match oldblock with\n    | Some oldblock =>\n      if can_write val $ el_type oldblock then\n        option_map (fun newblock=> dyn_ctx_mod dyn (fun _=> set_nth ErrorBlock m bid newblock) id) $  block_mod oldblock pos val\n      else None\n    | None => None\n  end.\n\nDefinition add_var (vd:var_descr) (c: static_ctx):=\n  mk_stat_ctx\n    (functions c)\n    match variables c with\n      | [::] => [:: [:: vd ]]\n      | cons x xs => cons (cons vd x) xs\n    end\n.\n\nDefinition is_value_true {c:static_ctx} (v: value) : option bool:=\n  match v with\n    | Value (Int kind) z => Some $ sgz z != 0\n    | Value (Pointer _) Nullptr => Some false\n    | Value (Pointer _) (Goodptr _ _) => Some true \n    | _ => None \n  end.\n\n(*Lemma value_inj a  v1 v2: Value a v1 = Value a b c v2 -> v1 = v2.\n  move=> H.\n  inversion H.\n  by depcomp H1.\nDefined.  *)\n  \nDefinition eval ps e: value :=\n  iexpr (get_stat ps) (get_dyn ps) e.\n\n\nTheorem carrier_eq_dec: forall t, eq_dec (coq_type t).\n  rewrite /eq_dec.\n  case; try by apply unit_eq_dec.\n  - case; apply int_eq_dec.\n  - apply ptr_eq_dec.\n  - move=> *. apply (seq_eq_dec _ nat_eq_dec). \nQed.\n\n\n\n     Theorem expr_eq_dec : eq_dec expr.\n       have Hlst: forall (A:Type) (a:A) l,  a :: l = l -> False. by  move=> A a; elim =>//=; move=> a0 l0 IH [] =><-. \n       rewrite /eq_dec.\n       fix 1.\n       move => x y.\n       case x; case y; try by right.\n       - move => t c t0 c0.\n         case Ht:(t == t0).\n         + move /eqP in Ht; subst.\n           move: (carrier_eq_dec t0 c0 c).\n           case; [by left; subst\n                 | by right; move =>[]=> H; depcomp H].\n         + by move /eqP in Ht; right; case; move=> He; symmetry in He.\n       - move=> t0 t; move: (ctype_eq_dec t0 t) =>[].\n         by move => ->; left.\n         by move=> H; right; case=> H'; symmetry in H'. \n       - move=> t0 t; move: (ctype_eq_dec t0 t) =>[].\n           by move => ->; left.\n           by move=> H; right; case=> H'; symmetry in H'.\n       - by move=> s0 s; move: (string_eq_dec s s0) => []; by[left; subst| right; case]. \n       - move=> op2 x2 y2 op1 x1 y1.\n         move: (binop_eq_dec op1 op2) => [Hop|Hop]; \n           move: (expr_eq_dec x1 x2) => [Hx|Hx];\n           move: (expr_eq_dec y1 y2) => [Hy|Hy]; try by right;case.\n           by rewrite Hx Hy Hop; left. \n       - move=> op1 x1  op2 x2.\n         move:(expr_eq_dec x2 x1) => [Hx|Hx]; move:(unop_eq_dec op2 op1) => [Hop|Hop]; subst; try by [right;case].\n           by left.\n     Qed.  \n\n     Definition expr_eqP := reflect_from_dec expr_eq_dec.\n     \n     Canonical expr_eqMixin := EqMixin expr_eqP.\n     Canonical expr_eqType := EqType expr expr_eqMixin.\n     \n     Theorem statement_eq_dec: eq_dec statement.\n       rewrite /eq_dec.   \n       fix 1.\n       have option_eq_dec t: eq_dec t ->  eq_dec (option t). by rewrite /eq_dec =>H; decide equality.\n       decide equality.\n       apply ( seq_eq_dec _ expr_eq_dec).\n       apply string_eq_dec.\n       apply expr_eq_dec.\n       apply expr_eq_dec.\n       apply nat_eq_dec.\n       apply (option_eq_dec _ string_eq_dec).\n       apply ctype_eq_dec.\n       apply storage_eq_dec.\n       apply expr_eq_dec.\n       apply expr_eq_dec.\n       elim: l l0.\n         by case; [left | right].\n         move=> a l H l0.\n         case l0. by right.\n         move=> s l1.\n         move: (H l1) => [H0|H0]; move: (statement_eq_dec a s) => [H1|H1]; subst; \n           try by [left| right; case].\n     Defined.\n\n     Definition statement_eqP := reflect_from_dec statement_eq_dec.\n     \n     Canonical statement_eqMixin := EqMixin statement_eqP.\n     Canonical statement_eqType := EqType statement statement_eqMixin.\n\n     (* Todo: make the lists potentially infinite? *)\n\n     (* Add: \n* Check if expression types are corresponding to arguments;\n* Throw in assignments \n*)\n     \n\nDefinition LitFromExpr (ps: prog_state) (e:expr): expr ?:=\n  match eval ps e  with\n    | Value t v => Some $ Lit t v \n    | Garbage =>  None \n    | Deallocate => None \n  end .\n\n\nDefinition prologue_arg (ps: prog_state) (name:string) (t:ctype) (e:expr) :=\n  option_map (fun l =>  [:: Alloc Stack t (Some name) 1; Assign (Var name) l] ) $ LitFromExpr ps e.\n\nDefinition prologue_args (ps:prog_state) (f:function) (es: seq expr) :=\n  let vals :=  map (fun a => prologue_arg ps (fst (fst a)) (snd (fst a)) (snd a)) $ zip (args f) es in\n  foldl cat_if_some (Some nil) vals.\n\nDefinition prologue_for (ps: prog_state) (f:function) (argvals: seq expr) : option ( seq statement)  :=\n  option_map (cons Enter) $ prologue_args ps f argvals.\n(*\nDefinition epilogue_arg (ps: prog_state) (name:string) (t:ctype) (e:expr) :=\n  Some [:: Assign (Var name) (EDeallocated t)] .\n\n\nDefinition epilogue_args (ps:prog_state) (f:function) (es: seq expr) :=\n  let vals :=  map (fun a => epilogue_arg ps (fst (fst a)) (snd (fst a)) (snd a)) $ zip (args f) es in\n  foldl cat_if_some (Some nil) vals.\n *)\n\nDefinition epilogue_for (ps: prog_state) (f:function) (argvals: seq expr) : option ( seq statement)  := Some [:: Leave].\n(*  option_map (fun x => x ++ [:: Leave]) $ epilogue_args ps f argvals. *)\n\nDefinition fun_by_address {t} (p: ptr t) (stat:static_ctx) (dyn:dynamic_ctx) : function? :=\n  match p with \n    | Goodptr b o => option_find (fun f=> fun_location f == b) $ functions stat\n    | _ => None\n  end.\nDefinition extract_some {T} (x:  T ? ? ) : T? :=\n  match x with\n    |Some x => x\n    | None => None\n  end.\n\nFixpoint interpreter_step (s: prog_state) : prog_state :=\n  match s with\n    | Good _ (mk_dyn_ctx _ nil) => s\n    | Good ((mk_stat_ctx funs vars) as oldstat) ((mk_dyn_ctx mem (st::ss)) as olddyn) =>\n      let dyn := mk_dyn_ctx mem ss in\n      let bad := Bad oldstat olddyn st in\n    match st with\n      | Skip => Good oldstat dyn\n      | Call fname fargs =>\n        match get_fun oldstat fname with\n          | Some f =>\n            match prologue_for s f fargs, epilogue_for s f fargs with\n              | Some prologue, Some epilogue =>\n                Good oldstat $ dyn_ctx_mod dyn id (fun x => prologue ++ body f :: epilogue ++ x)\n              | _, _ => bad\n            end\n          | None => bad\n        end\n      | Debug => s         \n      | Assign w val  =>\n        match eval s w, eval s val with\n          | Value (Pointer t)  (Goodptr to off), Value vtype v =>                           \n            if vtype == t then\n                match mem_write dyn to off  (Value _ v ) with\n                      | Some d => Good oldstat d\n                      | None => bad\n                end\n                  else bad\n          | Value (Pointer t) (Goodptr to off) , Deallocated as v\n          | Value (Pointer t) (Goodptr to off) , Garbage as v=>\n                match mem_write dyn to off  v with\n                      | Some d => Good oldstat d\n                      | None => bad\n                end\n            \n          | _, _ => bad\n        end                      \n      | Alloc loc type o_name sz =>\n        let block_id := next_block_id dyn in\n        let newdyn := dyn_ctx_mod dyn (fun m=> m ++ [:: mk_block loc block_id (sz* SizeOf type) type (garbage_values sz)]) id  in\n        match o_name with\n          | None => Good oldstat newdyn\n          | Some name => Good (add_var (declare_var name type block_id) oldstat ) newdyn\n        end\n      | If cond _then _else => let cont := match @is_value_true oldstat $ eval s cond with\n                                 | Some true => _then\n                                 | _ => _else\n                               end in\n                                 Good oldstat $ dyn_ctx_mod dyn id (cons cont)\n      | While cond body => match @is_value_true oldstat $ eval s cond with\n                             | Some true => Good oldstat $ dyn_ctx_mod olddyn id (cons body)\n                             | _ => Good oldstat dyn\n                           end\n      | CodeBlock sts => let bc := [:: Enter] ++ sts ++ [::Leave] in\n                         let newdyn := dyn_ctx_mod dyn id (cat bc) in\n                         Good oldstat newdyn\n      | Enter => add_static_ctx $ Good oldstat dyn\n      | Leave =>let newdyn :=\n                    match variables $ oldstat with\n                      | v::vv =>\n                        @foldl  (var_descr) (option dynamic_ctx)\n                               (fun sd v => extract_some $ option_map (fun sd=>mem_write sd (location v) 0 Deallocated) sd) (Some dyn) v\n                      | nil => None\n                    end in\n                match newdyn with\n                  | Some newdyn => remove_static_ctx $ Good oldstat newdyn\n                  | None => bad\n                end\n    end\n    | Bad stat dyn state => s\n  end.\n\n\nDefinition init_state_for (s:statement) := Good (stat_ctx_mod stat_init (fun _=> [:: mk_fun 0 \"main\" nil s 0 ] ) id ) $\n                                                mk_dyn_ctx  nil [:: s] .\n                                                \n\n\nFixpoint interpret (steps:nat) (state: prog_state) :=\n  match steps with | 0 => state\n                | S steps => match state with\n                               |Bad _ _ _ => state\n                               |Good _ _ => interpret steps $ interpreter_step state\n                             end\n  end.\n\nDefinition statement_state (s:prog_state) (st:statement) := match s with\n                                                              | Good x dc => Good x $ dyn_ctx_mod dc id (cons st)\n                                                              | Bad x x0 x1 => s\n                                                            end.\nDefinition isbad s := match s with | Bad _ _ _ => true | _ => false end.\n\nDefinition start_from_0th_fun (c:static_ctx): dynamic_ctx :=\n  match ohead $ functions c with\n    | None => dynamic_ctx_empty\n    | Some main => dyn_ctx_push dynamic_ctx_empty (body main)\n  end.\nDefinition init_state_for_prog (sc: static_ctx) := Good sc (start_from_0th_fun sc).\n\n\nDefinition LocVar t name := Alloc Stack t (Some name%string) 1. \n\nNotation \"{{  x1 ; .. ; xn }}\" := (CodeBlock(  cons x1  .. (cons xn nil) ..) ) (at level 35, left associativity) : c. \nNotation \"'int8 x \" := (LocVar Int8 x) (at level 200, no associativity) :c.\nNotation \"'uint8 x \" := (LocVar UInt8 x) (at level 200, no associativity) :c.\nNotation \"'int16 x \" := (LocVar Int16 x) (at level 200, no associativity) :c.\nNotation \"'uint16 x \" := (LocVar UInt16 x) (at level 200, no associativity) :c.\nNotation \"'int32 x \" := (LocVar Int32 x) (at level 200, no associativity) :c.\nNotation \"'uint32 x \" := (LocVar UInt32 x) (at level 200, no associativity) :c.\nNotation \"'int64 x \" := (LocVar Int64 x) (at level 200, no associativity) :c.\nNotation \"'uint64 x \" := (LocVar UInt64 x) (at level 200, no associativity) :c. \n\n\nNotation \"' v := value\" := (Assign v (value) ) (at level 200, no associativity) :c.\nNotation \" /* v \" := (Unop Asterisk v) (at level 200, right associativity) :c.\nNotation \" /i n  \" := (Lit Int64 n) (at level 210, no associativity) :c.\nDelimit Scope c with c.\nOpen Scope string.\nOpen Scope c.\n\nDefinition GetVar s := ( Unop Asterisk ( Var s ) ).\nDefinition Arg := Var.\nDefinition AddrVar := Var.\n\n\nDefinition test_assign := {{\n                           'int8 \"x\";\n                           ' Var \"x\" := /i 4 \n                            }}.\n\nDefinition sample_call : static_ctx :=\n  mk_stat_ctx [::\n                 mk_fun 0 \"main\" [::] ({{\n                                           'int64 \"x\";\n                                           Call \"f\" [:: Var \"x\"]\n                                         }}) 0;\n                mk_fun 1 \"f\" [:: (\"x\", (Pointer Int64)) ]\n                       ({{\n                           ' Var \"x\"  := /i 2\n                          }}) 1 ]\n              nil.\n(* \nif (x == 1) res <- 1 else \n{\nalloc y;\ny <- x;\ny <- fact (x - 1) \nres <- res * y\n}\n*)\nDefinition sample_fact : static_ctx :=\n  mk_stat_ctx [::\n                 mk_fun 0 \"main\" [::] ({{\n                                           'int64 \"x\";\n                                           ' Var \"x\" := /i 1;\n                                           Call \"f\" [:: AddrVar \"x\"; /i 6 ];\n                                           Debug\n                                         }}) 0;\n                \n                mk_fun 1 \"f\" [:: (\"res\", (Pointer Int64)); (\"x\", Int64) ]\n                       ({{\n                            If (Binop Eq ( GetVar \"x\" ) ( /i 0 ) )\n                               (' /* (Var \"res\") :=  /i 1 )\n                               ({{\n                                    'int64 \"y\";\n                                    ' AddrVar \"y\" := GetVar \"x\";\n                                   Call \"f\" [::AddrVar \"y\"; Binop Sub (GetVar \"x\") (/i (Posz 1)) ];\n                                   \n                                   Assign ( /* Var \"res\"  ) $ Binop Mul ( /* (GetVar \"res\") ) (GetVar \"y\")\n                                          }})\n                          }}) 1 ]\n              nil.\n\n\nDefinition halts (ps: prog_state):= exists n:nat, call_stack ( get_dyn ( interpret n ps )) = nil.\n  \n  \n\nFixpoint unsome {T} (s:seq (option T) ) :=\n  match s with\n    | (Some s ):: ss => s :: unsome ss\n    | None :: _=>  nil\n    | nil => nil\n  end.\n\nFixpoint unsome3 {T A B} (s:seq (A * B * (option T)) ) :=\n  match s with\n    | (x, y, Some s ):: ss => (x,y,s) :: unsome3 ss\n    | _ => nil\n  end.\n\nDefinition dumpvars (ps: prog_state) :=\n  let stat := get_stat ps in\n  let cntns (n:nat) := option_map contents $ find_block (get_dyn ps) n in\n  let varinfo :=  get_var stat in\n  let varnames := undup $ map var_name $  flatten (variables  stat) in\n  let vards := map varinfo varnames in\nunsome3 $  unsome $  map (option_map (fun vd => (var_name vd, var_type vd,  cntns $ location vd))) vards.\nDefinition is_good ps := match ps with | Good _ _  => true | _ => false end.\n\nLet f := fun steps=>\n        let state := interpret steps $ init_state_for_prog sample_fact in state.\n(*        (is_good state, dumpvars state, get_dyn state).*) \nCompute f  1 .\nCompute f  2 .\nCompute f  3 .\nCompute f  4 .\nCompute f  5 .\nCompute f  6 .\nCompute f  7 .\nCompute f  8 .\nCompute f  500.\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/coqnd/Core.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.29389388734383376}}
{"text": "(* Celsius project *)\n(* Clément Blaudeau - Lamp@EPFL & Inria 2020-2022 *)\n(* ------------------------------------------------------------------------ *)\n(* This files the core principles in their typing sense, along with lemmas and tactics *)\n\nFrom Celsius Require Export Typing Wellformedness.\nImplicit Type (σ: Store) (ρ ω: Env) (l: Loc) (L: LocSet) (Σ: StoreTyping) (T: Tpe) (μ: Mode) (Γ: EnvTyping).\n\n(* ------------------------------------------------------------------------ *)\n(** * Main definitions *)\n\n(* ------------------------------------------------------------------------ *)\n(** ** Monotonicity *)\nDefinition monotonicity Σ1 Σ2 :=\n  forall l, l < dom Σ1 -> (exists T1 T2, getType Σ1 l = Some T1 /\\ getType Σ2 l = Some T2 /\\ T2 <: T1).\nNotation \"Σ1 ≼ Σ2\" := (monotonicity Σ1 Σ2) (at level 60).\n\n(* ------------------------------------------------------------------------ *)\n(** ** Authority *)\nDefinition authority_st Σ1 Σ2 :=\n  forall l C Ω, getType Σ1 l = Some (C, cool Ω) -> getType Σ2 l = Some (C, cool Ω).\nGlobal Instance notation_stackability_store : notation_authority StoreTyping :=\n  { authority_ := authority_st }.\n\n(* ------------------------------------------------------------------------ *)\n(** ** Value typing (with variants) *)\nInductive value_typing : StoreTyping -> Loc -> Tpe -> Prop :=\n| vt_sub : forall Σ l T1 T2,\n    getType Σ l = Some T1 ->\n    (T1 <: T2) -> value_typing Σ l T2.\nGlobal Instance notation_value_typing_Tpe : notation_dash_colon StoreTyping Loc Tpe :=\n  { dash_colon_ := value_typing }.\nGlobal Hint Unfold notation_value_typing_Tpe: notations.\n\nDefinition value_typing_mode Σ l μ :=\n  exists C, Σ ⊨ l : (C, μ).\nGlobal Instance notation_value_typing_Mode : notation_dash_colon StoreTyping Loc Mode :=\n  { dash_colon_ := value_typing_mode }.\nGlobal Hint Unfold notation_value_typing_Mode: notations.\n\nDefinition value_typing_cln Σ l C :=\n  exists μ, Σ ⊨ l : (C, μ).\nGlobal Instance notation_value_typing_ClN : notation_dash_colon StoreTyping Loc ClN :=\n  { dash_colon_ := value_typing_cln }.\nGlobal Hint Unfold notation_value_typing_ClN: notations.\n\nDefinition value_typing_mode_locset Σ L μ :=\n  forall (l: Loc), (In Loc L l) -> Σ ⊨ l : μ.\nGlobal Instance notation_value_typing_mode_LocSet : notation_dash_colon StoreTyping LocSet Mode :=\n  { dash_colon_ := value_typing_mode_locset }.\nGlobal Hint Unfold notation_value_typing_mode_LocSet: notations.\n\nDefinition value_typing_locset Σ (ll: list Loc) (vl: list Tpe) :=\n  Forall2 (fun (l: Loc) (T:Tpe) => Σ ⊨ l : T) ll vl.\nGlobal Instance notation_value_typing_LocSet : notation_dash_colon StoreTyping (list Loc) (list Tpe) :=\n  { dash_colon_ := value_typing_locset }.\nGlobal Hint Unfold notation_value_typing_LocSet: notations.\n\nLemma value_typing_dom : forall Σ l T,\n    Σ ⊨ l : T -> l < dom Σ.\nProof with eauto using getType_dom.\n  intros ...\n  inverts H...\nQed.\nGlobal Hint Resolve value_typing_dom: typ.\n\n(* ------------------------------------------------------------------------ *)\n(** ** Stackability *)\nDefinition stackability_st Σ1 Σ2 :=\n  forall l, l < dom Σ2 -> (Σ2 ⊨ l : warm) \\/ (l < dom Σ1).\nGlobal Instance notation_stackability_StoreTyping : notation_stackability StoreTyping :=\n  { stackability_ := stackability_st }.\nGlobal Hint Unfold notation_stackability_StoreTyping : notations.\n\n(* ------------------------------------------------------------------------ *)\n(** ** Object typing **)\nInductive object_typing : StoreTyping -> Obj -> Tpe -> Prop :=\n\n| ot_hot : forall Σ C ω Args Flds Mtds,\n    ct C = class Args Flds Mtds ->\n    (forall f,\n        f < length Flds ->\n        exists v D μ,\n          fieldType C f = Some (D, μ) /\\\n          getVal ω f = Some v /\\ (Σ ⊨ v : (D, hot))) ->\n    object_typing Σ (C,ω) (C, hot)\n\n| ot_warm : forall Σ C ω Args Flds Mtds,\n    ct C = class Args Flds Mtds ->\n    (forall f,\n        f < length Flds ->\n        exists v D μ,\n          fieldType C f = Some (D, μ) /\\\n          getVal ω f = Some v /\\ (Σ ⊨ v : (D, μ))) ->\n    object_typing Σ (C,ω) (C, warm)\n\n| ot_cool : forall Σ C ω n Args Flds Mtds,\n    ct C = class Args Flds Mtds ->\n    (forall f,\n        f < n ->\n        exists v D μ,\n          fieldType C f = Some (D, μ) /\\\n          getVal ω f = Some v /\\ (Σ ⊨ v : (D, μ))) ->\n    object_typing Σ (C,ω) (C, cool n)\n\n| ot_cold : forall Σ C ω,\n    object_typing Σ (C,ω) (C, cold).\n\nGlobal Instance notation_object_typing : notation_dash_colon StoreTyping Obj Tpe :=\n  { dash_colon_ := object_typing }.\nGlobal Hint Unfold notation_object_typing: notations.\n\n(* ------------------------------------------------------------------------ *)\n(** ** Store_typing *)\n(** Here is the link between the abstract environment of types and the store used in execution *)\n\nDefinition store_typing Σ σ :=\n  dom σ = dom Σ /\\\n  forall l, l < dom Σ ->\n       exists C ω μ, getObj σ l = Some (C,ω) /\\\n                  getType Σ l = Some (C, μ) /\\\n                  Σ ⊨ (C, ω) : (C, μ).\nGlobal Instance notation_store_typing: notation_dash StoreTyping Store :=\n  { dash_ := store_typing }.\nGlobal Hint Unfold notation_store_typing: notations.\nGlobal Hint Unfold notation_store_typing store_typing: typ.\n\nLemma storeTyping_dom:\n  forall Σ σ,\n    Σ ⊨ σ -> dom σ = dom Σ.\nProof with (eauto with typ lia).\n  intros ...\n  inverts H...\nQed.\nGlobal Hint Resolve storeTyping_dom: typ.\n\n(* ------------------------------------------------------------------------ *)\n(** ** Environment typing *)\nInductive env_typing : StoreTyping -> Env -> EnvTyping -> Prop :=\n| et_nil : forall Σ, env_typing Σ nil nil\n| et_cons : forall Σ ρ Γ l T,\n    env_typing Σ ρ Γ ->\n    (Σ ⊨ l : T) ->\n    env_typing  Σ (l :: ρ) (T :: Γ).\nGlobal Instance notation_env_typing: notation_dash_colon StoreTyping Env EnvTyping :=\n  { dash_colon_ := env_typing }.\nGlobal Hint Unfold notation_env_typing: notations.\n\n\n(* ------------------------------------------------------------------------ *)\n(** * Tactics *)\nLtac meta :=\n  repeat\n    match goal with\n    (* Cross rewrites *)\n    | H: getObj ?σ ?l = Some ?O,\n        H': getObj ?σ ?l = Some ?O' |- _ => rewrite H' in H; inverts H\n    | H: getType ?Σ ?l = Some ?T,\n        H': getType ?Σ ?l = Some ?T' |- _ => rewrite H' in H; inverts H\n    | H: getVal ?ρ ?f = Some ?l,\n        H': getVal ?ρ ?f = Some ?l' |- _ => rewrite H' in H; inverts H\n\n    (* Dom hypothesis *)\n    | H: getType ?Σ ?l = Some ?T |- _ =>\n        match goal with\n        | H': Σ ⊨ ?σ, H'': l < dom ?σ' |- _ => fail 1\n        | H': Σ ⊨ ?σ, H'': S l <= dom ?σ' |- _ => fail 1\n        | _ =>\n            let fresh := fresh \"H__dom\" in\n            add_hypothesis fresh (getType_dom l T Σ H)\n        end\n    | H: getVal ?ρ ?f = Some ?l |- _ =>\n        match goal with\n        | H': S f <= dom ρ |- _ => fail 1\n        | H': f < dom ρ |- _ => fail 1\n        | _ => let fresh := fresh \"H__dom\" in\n              add_hypothesis fresh (getVal_dom ρ f l H)\n        end\n\n    (* Destructs *)\n    | H: ?Σ ⊨ ?l : ?x |- _ =>\n        match type of l with\n        | Loc => match type of x with\n                | Mode => let C := fresh \"C\" in destruct H as [C H]\n                | (ClN*Mode)%type =>\n                    inverts H\n                end\n        end\n    | o:Obj |- _ => let C := fresh \"C\" in\n                  let ω := fresh \"ω\" in\n                  destruct o as [C ω]\n    | T:Tpe |- _ => let C := fresh \"C\" in\n                  let μ := fresh \"μ\" in\n                  destruct T as [C μ]\n    | H: ?μ ⊑ hot |- _ =>\n        let H__eq := fresh \"H__eq\" in\n        assert (H__eq: μ = hot) by (invert H; steps); subst;\n        clear H\n    | H: hot ⊑ ?μ |- _ => clear H\n    | H: ((?C, ?μ) <: (?C', ?μ')) |- _ => inverts H\n    | H: ?Σ ⊨ ?σ |- context [ dom ?Σ ] => rewrite <- (proj1 H)\n    | H: ?Σ ⊨ ?σ, H':context [ dom ?Σ ] |- _ => rewrite <- (proj1 H) in H'\n    end ; sort; cross_rewrites;\n  try lia.\n\nLtac meta_clean :=\n  move_top StoreTyping;\n  move_top EnvTyping;\n  move_top Env;\n  move_top Store;\n  move_top (list Loc);\n  move_top Loc;\n  move_top (list Tpe);\n  move_top Mode; move_top ClN; move_top Expr.\n\n\nLtac storeTyping_update :=\n  repeat (match goal with\n          | H1: ?Σ ⊨ ?σ,\n              H2: getObj ?σ ?l = Some (?C, ?ω) |- _ =>\n              match goal with\n              | H3: getType Σ l = Some (C, ?μ) |- _ => fail 1\n              | _ => let H_obj := fresh \"H__getObj\" in\n                    let H_tpe := fresh \"H__getType\" in\n                    let H_vt := fresh \"H__vt\" in\n                    destruct ((proj2 H1) l (ltac:(rewrite <-(proj1 H1); apply (getObj_dom l _ σ H2)))) as\n                      (?C & ?ω & ?μ & H_obj & H_tpe & H_vt);\n                    symmetry in H_obj;\n                    rewrite H2 in H_obj; inverts H_obj\n              end\n          | H1: ?Σ ⊨ ?σ,\n              H2: getType ?Σ ?l = Some (?C, ?μ) |- _ =>\n              match goal with\n              | H3: getObj ?σ l = Some (C, ?ω) |- _ => fail 1\n              | _ => let H_obj := fresh \"H__getObj\" in\n                    let H_tpe := fresh \"H__getType\" in\n                    let H_vt := fresh \"H__vt\" in\n                    destruct ((proj2 H1) l (ltac:(rewrite <-(proj1 H1); apply (getObj_dom l _ σ H2)))) as\n                      (?C & ?ω & ?μ & H_obj & H_tpe & H_vt);\n                    symmetry in H_tpe;\n                    rewrite H2 in H_tpe; inverts H_tpe\n              end\n          end; cross_rewrites).\n\n(* ------------------------------------------------------------------------ *)\n(** * Monotonicity results *)\n\nLemma monotonicity_dom : forall Σ1 Σ2,\n    Σ1 ≼ Σ2 -> (dom Σ1 <= dom Σ2).\nProof with meta; eauto with lia updates .\n  intros.\n  destruct Σ1; steps...\n  specialize (H (dom Σ1)) as (? & ? & ?); steps ...\nQed.\nGlobal Hint Resolve monotonicity_dom: typ.\n\nLemma value_typing_monotonicity: forall Σ1 Σ2 l T,\n    Σ1 ≼ Σ2 -> Σ1 ⊨ l : T -> Σ2 ⊨ l : T.\nProof with (meta; eauto with lia typ).\n  intros ...\n  specialize (H l H0) as [T1 [T2 [Hs1 [Hs2 H__sub]]]] ...\n  eapply vt_sub ...\nQed.\nGlobal Hint Resolve value_typing_monotonicity: typ.\n\nLemma env_typing_monotonicity: forall Σ1 Σ2 Γ ρ,\n    Σ1 ≼ Σ2 -> Σ1 ⊨ ρ : Γ -> Σ2 ⊨ ρ : Γ.\nProof.\n  intros.\n  autounfold with notations in H0. simpl in H0.\n  induction H0.\n  - steps.\n  - specialize (IHenv_typing H).\n    apply et_cons; steps; eauto with typ.\nQed.\nGlobal Hint Resolve env_typing_monotonicity: typ.\n\nLemma object_typing_monotonicity: forall Σ1 Σ2 (o: Obj) T,\n    Σ1 ≼ Σ2 -> Σ1 ⊨ o : T -> Σ2 ⊨ o : T.\nProof with (meta; eauto 3 with lia typ).\n  intros ...\n  inversion H0; steps.\n\n  - eapply ot_hot; intros...\n    specialize (H7 f); steps.\n    exists v D μ; splits => //.\n    exists (D, hot)...\n    lets ([ ] & [ ] & ? & ? & ?): H H6...\n\n  - eapply ot_warm; intros...\n    specialize (H7 f); steps.\n    exists v, D, μ; splits ...\n    lets ([ ] & [ ] & ? & ? & ?): H H6...\n    eexists...\n\n  - eapply ot_cool; intros...\n    specialize (H7 f); steps.\n    exists v, D, μ; steps ...\n    lets ([ ] & [ ] & ? & ? & ?): H H6.\n    eexists...\nQed.\nGlobal Hint Resolve object_typing_monotonicity: typ.\n\nLemma mn_refl: forall Σ,\n    Σ ≼ Σ.\nProof with (meta; eauto with ss typ).\n  intros Σ l; steps ...\n  lets [? ?]: getType_Some H...\nQed.\nGlobal Hint Resolve mn_refl : typ.\n\nLemma mn_trans: forall Σ1 Σ2 Σ3,\n    Σ1 ≼ Σ2 -> Σ2 ≼ Σ3 -> Σ1 ≼ Σ3.\nProof with (meta; eauto with lia typ).\n  intros.\n  intros l; steps.\n  specialize (H l H1); steps.\n  specialize (H0 l) as [ ]; steps...\n  eexists; eexists...\nQed.\nGlobal Hint Resolve mn_trans: typ.\n\nLemma mn_hot: forall Σ1 Σ2 l,\n    Σ1 ≼ Σ2 ->\n    (Σ1 ⊨ l : hot) ->\n    (Σ2 ⊨ l : hot).\nProof.\n  intros; meta.\n  specialize (H l H0); steps; meta.\n  exists C.\n  eapply vt_sub; eauto with typ.\nQed.\nGlobal Hint Resolve mn_hot: typ.\n\nLemma mn_hot_set: forall Σ1 Σ2 (L: LocSet),\n    Σ1 ≼ Σ2 ->\n    (Σ1 ⊨ L : hot) ->\n    (Σ2 ⊨ L : hot).\nProof.\n  intros; meta.\n  intros l.\n  specialize (H0  l); eauto with typ.\nQed.\n\n\n(* ------------------------------------------------------------------------ *)\n(** ** Inversion lemma for environment access *)\n(* We define it here (and not in Typing.v) because it relies on typing of values *)\n\nLemma env_regularity: forall Γ Σ ρ x U T,\n    Σ ⊨ ρ : Γ ->\n    ((Γ, U) ⊢ (e_var x) : T) ->\n    exists l, getVal ρ x = Some l /\\ Σ ⊨ l : T.\nProof.\n  intros ...\n  remember (e_var x) as e.\n  induction H0; try congruence.\n  - specialize (IHexpr_typing H Heqe) as [l [H__val Ht]].\n    exists l; steps.\n    inverts Ht.\n    eapply vt_sub; eauto with typ.\n  - inverts Heqe.\n    gen T x.\n    autounfold with notations in H. simpl in *.\n    induction H; intros; destruct x; steps; eauto.\nQed.\n\n(* ------------------------------------------------------------------------ *)\n(** ** Hot preservation results **)\n(* Similar to the hot preservation result (in Localreasoning.v) but for typing *)\n\nLemma hot_transitivity : forall Σ σ l l',\n    wf σ ->\n    (Σ ⊨ l : hot) ->\n    (Σ ⊨ σ) ->\n    (σ ⊨ l ⇝ l') ->\n    (Σ ⊨ l' : hot).\nProof with (storeTyping_update; meta; eauto 2 with lia typ).\n  intros.\n  gen Σ.\n  induction H2; steps...\n  inverts H__vt ...\n  lets [? _]: H H1.\n  lets: H3 H9.\n  lets: getVal_dom H2...\n  lets (?v & ?D & ?μ & ? & ? & ?): H10 f...\n  exists D, (D, hot)...\nQed.\n\nLemma hot_transitivity_set : forall Σ σ L l,\n    wf σ ->\n    (Σ ⊨ L : hot) ->\n    (Σ ⊨ σ) ->\n    (σ ⊨ L ⇝ l) ->\n    (Σ ⊨ l : hot).\nProof with (storeTyping_update; meta; eauto 2 with lia typ).\n  intros. rch_set.\n  eapply hot_transitivity...\nQed.\n\n(* ------------------------------------------------------------------------ *)\n(** ** Authority results *)\n\nLemma aty_st_refl: forall Σ, Σ ▷ Σ.\nProof with (meta; eauto with typ lia).\n  intros Σ l H.\n  destruct (getType Σ l) eqn:E; eauto.\nQed.\nGlobal Hint Resolve aty_st_refl : typ.\n\nLemma aty_st_trans: forall Σ1 Σ2 Σ3,\n    Σ1 ▷ Σ2 ->\n    Σ2 ▷ Σ3 ->\n    Σ1 ▷ Σ3.\nProof with steps.\n  intros. intros l ...\nQed.\nGlobal Hint Resolve aty_st_trans : typ.\n\n(* ------------------------------------------------------------------------ *)\n(** ** Stackability results *)\n\nLemma stk_st_refl: forall Σ, Σ ≪ Σ.\nProof.\n  intros Σ l H. right => //.\nQed.\nGlobal Hint Resolve stk_st_refl : typ.\n\nLemma stk_st_trans: forall Σ1 Σ2 Σ3,\n    Σ1 ≪ Σ2 ->\n    Σ2 ≪ Σ3 ->\n    Σ2 ≼ Σ3 ->\n    Σ1 ≪ Σ3.\nProof.\n  intros.\n  intros l ?.\n  specialize (H0 l) as [ ]; eauto.\n  specialize (H l H0) as [ ]; eauto.\n  inverts H.\n  inverts H3.\n  left.\n  specialize (H1 l) as [ ]; steps.\n  rewrite H3 in H; steps.\n  repeat eexists; eauto with typ.\nQed.\nGlobal Hint Resolve stk_st_trans : typ.\n\n(* ------------------------------------------------------------------------ *)\n(** ** Selection result *)\n\nLemma cool_selection : forall Σ σ C l Ω ω f T,\n    Σ ⊨ σ ->\n    Σ ⊨ l : (C, cool Ω) ->\n    getObj σ l = Some (C, ω) ->\n    fieldType C f = Some T ->\n    f < Ω ->\n    exists v,\n      getVal ω f = Some v /\\\n        Σ ⊨ v : T.\nProof with (meta; eauto 4 with typ lia).\n  intros ...\n  lets [ ]: (proj2 H) l ... steps ...\n  inverts H7; inverts H9 ...\n  - specialize (H11 f) as (v & D & ? & ? & ? & ?)...\n    exists v; splits...\n    eexists...\n  - specialize (H10 f) as (v & D & ? & ? & ? & ?)...\n    exists v; splits...\n    eexists...\n  - specialize (H10 f) as (v & D & ? & ? & ? & ?)...\n    exists v; splits...\n    eexists...\n  - specialize (H12 f) as (v & D & ? & ? & ? & ?)...\n    exists v; splits...\n    eexists...\nQed.\n\n(* ------------------------------------------------------------------------ *)\n(** ** Upgrading lemmas *)\n(* Those two crucial results allow the typing information to be upgraded during typing : - as every\nmandatory field initializer is evaluated (cool n to cool (n+1)) - as the object finishes evaluation\n(cool to warm)\n\n The last upgrading lemma is the local reasoning for typing, which upgrades objects to hot.\n *)\n\nLemma field_initialization: forall C I x σ ω T Σ v,\n    wf σ ->\n    Σ ⊨ σ ->\n    getObj σ I = Some (C, ω) ->\n    x <= dom ω ->\n    getType Σ I = Some (C, cool x) ->\n    fieldType C x = Some T ->\n    (Σ ⊨ v : T) ->\n    forall σ' Σ',\n      assign_new I x v σ = Some σ' ->\n      Σ' = [I ↦ (C, cool (S x))]Σ ->\n      (Σ' ⊨ σ') /\\ Σ ≼ Σ' /\\ Σ ≪ Σ'.\nProof with (updates; meta; eauto 3 with typ lia).\n  intros. subst.\n  assert (H__fo: forall A B C : Prop , (B -> A) -> B -> C -> A /\\ B /\\ C) by firstorder.\n  apply H__fo; clear H__fo; steps.\n  - (* ⊨ *)\n    split... { symmetry; eapply assign_new_dom... }\n    intros l H__l.\n    lets (?C & ?ω & ?μ & ? & ? & ?): (proj2 H0) l...\n    rewrite /assign_new H1 in H6.\n    destruct_eq (I = l); subst...\n    + (* I = l *)\n      destruct_if_eqb; inverts H6.\n      * (* x = dom ω : a new field is added *)\n        clear x.\n        exists C, (ω++[v]), (cool (S (dom ω))); splits...\n        ct_lookup C.\n        lets: fieldType_some H4...\n        eapply ot_cool ; [eassumption| updates; try lia].\n        intros.\n        assert (f = dom ω \\/ f < dom ω) as [|] by lia; subst.\n        -- exists v, c, m; splits...\n           destruct_eq (l = v); subst...\n           ++ exists (c, cool (S dom ω))...\n              apply s_typ_mode, s_mode_trans with (cool (dom ω))...\n           ++ exists (c, μ)...\n        -- lets: fieldType_some H4...\n           lets (?D & ?μ & ?): fieldType_exists f...\n           lets (v0 & ?): getVal_Some H6.\n           exists v0 D μ0; splits... rewrite getVal_last2...\n           inverts H13.\n           lets (?v1 & ?D & ?μ & ? & ? & ?): H22 H6...\n           destruct_eq (l = v0); subst...\n           ++ exists (C, cool (S dom ω))...\n              apply s_typ_mode, s_mode_trans with (cool (dom ω))...\n           ++ exists (D0, μ2)...\n      * (* the field x is updated *)\n        exists C, ([x ↦ v]ω), (cool (S x)); splits...\n        inverts H13.\n        lets [? _]: H l H10. lets : H1 H15...\n        eapply ot_cool; try eassumption; try lia.\n        intros.\n        destruct_eq (x = f); subst...\n        -- destruct_eq (l = v); subst;\n             exists v, c, m; splits; eauto; eexists...\n           apply s_typ_mode, s_mode_trans with (cool f)...\n        -- lets (?v1 & ?D & ?μ & ? & ? & ?): H16 f...\n           exists v1, D, μ0; splits...\n           destruct_eq (l = v1); subst; eexists...\n           apply s_typ_mode, s_mode_trans with (cool x)...\n\n    + repeat eexists...\n      destruct_if_eqb; inverts H6...\n\n  - (* ≼ *)\n    intros l H__l.\n    rewrite /assign_new H1 in H6.\n    destruct_eq (I = l); subst...\n    + destruct_if_eqb; inverts H6.\n      * clear x.\n        exists (C, cool (dom ω)), (C, cool (S dom ω)); splits ...\n      * lets [?T ?]: getType_Some Σ l...\n        exists (C, cool x), (C, cool (S x)); splits...\n    + lets [?T ?]: getType_Some Σ l...\n      repeat eexists...\n\n  - (* ≪ *)\n    intros l H__l. right...\nQed.\n\nLemma promotion: forall Σ1 Σ2 C I σ2 Args Flds Mtds,\n    Σ1 ▷ Σ2 ->\n    Σ1 ≼ Σ2 ->\n    Σ1 ≪ [I ↦ (C, warm)] Σ2 ->\n    ct C = class Args Flds Mtds ->\n    I >= dom Σ1 ->\n    getType Σ2 I = Some (C, cool (dom Flds)) ->\n    Σ2 ⊨ σ2 ->\n    forall Σ3,\n      Σ3 = [I ↦ (C, warm)]Σ2 ->\n      Σ1 ▷ Σ3 /\\\n        Σ1 ≼ Σ3 /\\\n        Σ1 ≪ Σ3 /\\\n        Σ3 ⊨ σ2.\nProof with (updates; meta; eauto 3 with typ lia).\n  intros. subst.\n  apply proj2 with (Σ2 ≼ [I ↦ (C, warm)] (Σ2)).\n  assert (H__fo: forall A B C D E: Prop, B -> (A -> C) -> (A -> C -> E) -> D -> A -> A /\\ B /\\ C /\\ D /\\ E) by firstorder.\n  apply H__fo; clear H__fo; intros.\n\n  - (* ▷ *)\n    intros l H__l Ω ?.\n    destruct_eq (I = l); subst...\n\n  - (* ≼ *)\n    intros l H__l.\n    lets ([C0 μ] & ?): getType_Some H__l.\n    lets ([C1 μ1] & ?): getType_Some Σ2 l...\n    lets (?T & ?T & ? &? &?): H0 H__l...\n    exists (C0, μ).\n    destruct_eq (I = l); subst.\n    + exists (C, warm); split...\n    + exists (C0, μ1); split...\n\n  - (* ⊨ *)\n    split...\n    intros l H__l.\n    lets: monotonicity_dom H6...\n    lets (C0 & ω & ?): getObj_Some H__l...\n    lets (?C & ?ω & ?μ & ? & ? & ?) : (proj2 H5) l...\n    destruct_eq (I = l); subst...\n    + exists C, ω, warm; splits; auto.\n      eapply ot_warm; [eassumption |].\n      intros f ?.\n      inverts H13.\n      lets (?v & D & μ' & ? & ? & ?): H18 f H4...\n      exists v D μ' ; splits...\n      destruct_eq (l = v); subst; eexists...\n    + exists C0, ω, μ; splits...\n\n  - (* ≪ *)\n    intros l H__l...\n    destruct (H1 l)...\n\n  - (* ≼ *)\n    intros l H__l.\n    lets ([C0 μ] & ?): getType_Some H__l.\n    exists (C0, μ).\n    destruct_eq (I = l); subst;\n      eexists; split...\nQed.\n\n\n(* ------------------------------------------------------------------------ *)\n(** ** Object typing domains *)\n(* The object typing imposes conditions on the size of local environments in the store *)\n\nLemma ot_cool_dom: forall Σ σ l C ω Ω,\n    wf σ ->\n    Σ ⊨ σ ->\n    getObj σ l = Some (C, ω) ->\n    Σ ⊨ (C, ω) : (C, cool Ω) ->\n    Ω <= dom ω.\nProof with (meta; eauto with typ lia).\n  intros.\n  inverts H2.\n  destruct Ω...\n  lets: (proj1 (H l _ _ H1)) H7.\n  lets [ ]: H8 Ω; steps...\n  lets: getVal_dom H3...\nQed.\n\nLemma ot_warm_dom: forall Σ σ l C ω Args Flds Mtds,\n    ct C = class Args Flds Mtds ->\n    wf σ ->\n    Σ ⊨ σ ->\n    getObj σ l = Some (C, ω) ->\n    Σ ⊨ (C, ω) : (C, warm)->\n    dom ω = dom Flds.\nProof with (meta; eauto with typ lia).\n  intros.\n  inverts H2.\n  inverts H3.\n  lets: (proj1 (H0 l _ _ H5)) H7...\n  destruct (dom Flds0)...\n  lets [ ]: H8 n; steps...\n  lets: getVal_dom H3...\nQed.\n\nLemma ot_hot_dom: forall Σ σ l C ω Args Flds Mtds,\n    ct C = class Args Flds Mtds ->\n    wf σ ->\n    Σ ⊨ σ ->\n    getObj σ l = Some (C, ω) ->\n    Σ ⊨ (C, ω) : (C, hot) ->\n    dom ω = dom Flds.\nProof with (meta; eauto with typ lia).\n  intros.\n  inverts H2.\n  inverts H3.\n  lets: (proj1 (H0 l _ _ H5)) H7...\n  destruct (dom Flds0)...\n  lets [ ]: H8 n; steps...\n  lets: getVal_dom H3...\nQed.\n\n(* ------------------------------------------------------------------------ *)\n(** ** Other technical results *)\n\nLemma env_typing_subs: forall Γ1 Γ2 Σ vl,\n    Σ ⊨ vl : Γ2 ->\n    S_Typs Γ1 Γ2 ->\n    Σ ⊨ vl : Γ2.\nProof.\n  induction Γ1; intros.\n  - inverts H0; eauto with typ.\n  - inverts H0; meta.\n    inverts H; simpl in *.\n    eapply IHΓ1 in H6; eauto.\n    eapply et_cons; simpl in *; eauto with typ.\nQed.\nGlobal Hint Resolve env_typing_subs: typ.\n\nLemma storeTyping_assgn:\n  forall Σ σ l f v0 v C D ω μ μ0 μ__f,\n    Σ ⊨ σ ->\n    getObj σ l = Some (C, ω) ->\n    getVal ω f = Some v0 ->\n    fieldType C f = Some (D, μ__f) ->\n    getType Σ v0 = Some (D, μ0) ->\n    getType Σ v = Some (D, μ) ->\n    μ ⊑ μ0 ->\n    wf σ ->\n    Σ ⊨ ([l ↦ (C, [f ↦ v]ω)]σ).\nProof with (updates; meta; eauto 3 with typ updates).\n  intros.\n  split...\n  intros l' H__l'.\n  lets (C' & ω' & μ' & ? & ? & ?): (proj2 H) l'...\n  destruct_eq (l = l'); subst...\n  - exists C, [f ↦ v]ω, μ'; splits...\n    destruct (ct C) as [Args Flds Mtds] eqn:H__ct.\n    assert (f < dom Flds)...\n    inverts H11.\n    + eapply ot_hot; [eassumption|].\n      intros.\n      lets (?v & ?D & ?μ & ?&?&?): H17 f...\n      lets (?v & ?D & ?μ & ?&?&?): H17 f0...\n      destruct_eq (f = f0); subst...\n      exists v, D0, μ; splits...\n      eexists...\n    + eapply ot_warm; [eassumption |].\n      intros.\n      lets (?v & ?D & ?μ & ?&?&?): H17 f...\n      lets (?v & ?D & ?μ & ?&?&?): H17 f0...\n      destruct_eq (f = f0); subst...\n      exists v, D0, μ2; splits...\n      eexists...\n    + eapply ot_cool; updates; try reflexivity...\n      intros.\n      lets (?v & ?D & ?μ & ?&?&?): H17 f0...\n      destruct_eq (f = f0); subst...\n      exists v, D, μ1; splits...\n      eexists...\n    + apply ot_cold.\n  - exists C', ω', μ'; splits...\nQed.\n\n\nLemma P_Hots_env:\n  forall Args l args_val Σ1,\n    P_hots Args ->\n    Σ1 ⊨ args_val : Args ->\n    l ∈ codom args_val ->\n    Σ1 ⊨ l : hot.\nProof with (meta; eauto with typ).\n  induction Args; intros; steps;\n    inverts H0; inverts H1; simpl in * ...\n  - inverts H.\n    unfold P_hot in H6; steps ...\n    exists c. eapply vt_sub ...\n  - inverts H ...\nQed.\nGlobal Hint Resolve P_Hots_env: typ.\n", "meta": {"author": "clementblaudeau", "repo": "celsius", "sha": "33a7f479025f94551b6c7a96807f05469dcae595", "save_path": "github-repos/coq/clementblaudeau-celsius", "path": "github-repos/coq/clementblaudeau-celsius/celsius-33a7f479025f94551b6c7a96807f05469dcae595/src/MetaTheory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2938658682999014}}
{"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 msl.Extensionality.\n\nRequire Import sepcomp.mem_lemmas.\nRequire Import sepcomp.semantics.\n\nRequire Import concurrency.machine_semantics.\n\nRequire Import 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": "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/machine_semantics_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.29382737609670473}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.floyd.library.\nRequire Import VST.progs.objectSelfFancy.\n\n(*Version 1 -- leave specs of foo methods unchanged, and require neither funcspec_sub nor \nanything else. Just replictae the spec/proof structure of foo in fancy foo and see whether\nthe client has enough knowledge to call the correct function*)\n\n(*Require Import VST.floyd.Funspec_old_Notation.*)\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\nSection FOO.\n\n(*Andrew's definition\nDefinition object_invariant := list Z -> val -> mpred.*)\n\n(*But the uncurried version is easier for the HOrec construction*)\nDefinition ObjInv : Type:= (list Z * val).\nDefinition object_invariant := ObjInv -> mpred.\n\nDefinition tobject := tptr (Tstruct _object noattr).\n\nDefinition reset_spec (instance: object_invariant) :=\n  WITH hs:ObjInv (*modified*)\n  PRE [ (*_self OF*) tobject]\n          PROP (isptr (snd hs) (*NEW*))\n          PARAMS (snd hs) GLOBALS ()\n          SEP (instance hs)\n  POST [ tvoid ]\n          PROP() LOCAL () SEP(instance (nil, snd hs)).\n\nDefinition twiddle_spec (instance: object_invariant) :=\n  WITH hs: ObjInv, i: Z (*modified*)\n  PRE [ (*_self OF*) tobject, (*_i OF*) tint]\n          PROP (0 < i <= Int.max_signed / 4;\n                0 <= fold_right Z.add 0 (fst hs) <= Int.max_signed / 4; \n               isptr (snd hs) (*NEW*))\n          PARAMS (snd hs; Vint (Int.repr i)) GLOBALS ()\n          SEP (instance hs)\n  POST [ tint ]\n      EX v: Z, \n          PROP(2* fold_right Z.add 0 (fst hs) < v <= 2* fold_right Z.add 0 (i::(fst hs)))\n          LOCAL (temp ret_temp (Vint (Int.repr v))) \n          SEP(instance (i::(fst hs), snd hs)).\n\nDefinition object_methods (instance: object_invariant) (mtable: val) : mpred :=\n  EX sh: share, EX reset: val, EX twiddle: val, EX twiddleR:val,\n  !! readable_share sh && \n  func_ptr' (reset_spec instance) reset *\n  func_ptr' (twiddle_spec instance) twiddle *\n  func_ptr' (twiddle_spec instance) twiddleR *\n  data_at sh (Tstruct _methods noattr) (reset,(twiddle, twiddleR)) 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 twiddleR.\nentailer!.\nQed.\nLocal Hint Resolve object_methods_local_facts : saturate_local.\n\n(*Moved here from further below, and added twiddleR*)\nLemma make_object_methods:\n  forall sh instance reset twiddle twiddleR mtable,\n  readable_share sh ->\n  func_ptr' (reset_spec instance) reset *\n  func_ptr' (twiddle_spec instance) twiddle *\n  func_ptr' (twiddle_spec instance) twiddleR * \n  data_at sh (Tstruct _methods noattr) (reset, (twiddle, twiddleR)) mtable\n  |-- object_methods instance mtable.\nProof.\n  intros.\n  unfold object_methods.\n  Exists sh reset twiddle twiddleR.\n  entailer!.\nQed.\n\nLemma make_object_methods_later:\n  forall sh instance reset twiddle twiddleR mtable,\n  readable_share sh ->\n  func_ptr' (reset_spec instance) reset *\n  func_ptr' (twiddle_spec instance) twiddle *\n  func_ptr' (twiddle_spec instance) twiddleR * \n  data_at sh (Tstruct _methods noattr) (reset, (twiddle, twiddleR)) mtable\n  |-- |> object_methods instance mtable.\nProof.\nintros. eapply derives_trans. apply make_object_methods; trivial. apply now_later.\nQed.\n\n(*Andrew's definition\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\nSection ObjMpred.\nVariable instance: object_invariant.\n\nDefinition F (X: ObjInv -> mpred) (hs: ObjInv): mpred :=\n   ((EX mtable: val, !!(isptr mtable) (*This has to hold NOW, not ust LATER*)&&\n     (|> object_methods X mtable) *\n     field_at Ews (Tstruct _object noattr) [StructField _mtable] mtable (snd hs)) *\n   instance hs)%logic.\n\nDefinition HOcontractive1 {A: Type}{NA: NatDed A}{IA: Indir A}{RI: RecIndir A}{X: Type}\n     (f: (X -> A) -> (X -> A)) := \n forall P Q : X -> A,\n ALL x : X, |> fash (P x <--> Q x)\n |-- ALL x : X, fash (f P x --> f Q x).\n\nLemma HOcontractive_i1:\n forall  (A: Type)(NA: NatDed A){IA: Indir A}{RI: RecIndir A}{X: Type}\n     (f: (X -> A) -> (X -> A)),\n  HOcontractive1 f -> HOcontractive f.\nProof.\nintros.\nred in H|-*.\nintros.\neapply derives_trans.\napply andp_right.\napply H.\nspecialize (H Q P).\neapply derives_trans.\n2: apply H.\napply allp_derives; intros.\napply later_derives.\napply fash_derives.\nrewrite andp_comm.\nauto.\napply allp_right; intro.\nrewrite fash_andp.\napply andp_right.\napply andp_left1.\napply allp_left with v; auto.\napply andp_left2.\napply allp_left with v; auto.\nQed.\n\nLemma HOcontrF\n     (*Need sth like this (HI: HOcontractive (fun (_ : ObjInv -> mpred) (x : ObjInv) => instance x))*):\n      HOcontractive F.\nProof.\nunfold F.\napply HOcontractive_i1.\nred; intros.\napply allp_right; intro oi.\napply subp_sepcon_mpred; [ | apply subp_refl].\napply subp_exp; intro v.\napply subp_sepcon_mpred; [ | apply subp_refl].\nclear oi.\napply subp_andp; [ apply subp_refl | ].\nrewrite <- subp_later.\nrewrite <- later_allp.\napply later_derives.\nunfold object_methods.\napply subp_exp; intro sh.\napply subp_exp; intro reset.\napply subp_exp; intro twiddle.\napply subp_exp; intro twiddleR.\napply subp_sepcon_mpred; [ | apply subp_refl].\nrepeat simple apply subp_sepcon_mpred;\ntry (simple apply subp_andp; [simple apply subp_refl | ]).\n+\nunfold func_ptr'.\napply subp_andp; [ | apply subp_refl].\nclear - instance.\neapply derives_trans; [ | apply fash_func_ptr_ND].\napply allp_right; intro oi.\napply andp_right.\n*\napply allp_right; intro rho.\napply subp_i1.\nrewrite unfash_allp.\nset (zz := allp _).\nunfold convertPre.\nunfold PROPx, PARAMSx, GLOBALSx, LOCALx, SEPx, local, lift1; simpl.\nunfold_lift.\nnormalize.\nrewrite prop_true_andp by tauto.\nsubst zz.\neapply derives_trans.\napply andp_derives; [ | apply derives_refl].\napply allp_left with oi.\napply unfash_fash.\neapply derives_trans.\napply andp_derives.\napply andp_left2. apply derives_refl. apply derives_refl.\nrewrite andp_comm. apply modus_ponens.\n*\napply allp_right; intro rho.\napply subp_i1.\nrewrite unfash_allp.\nset (zz := allp _).\nunfold convertPre.\nunfold PROPx, LOCALx, SEPx, local, lift1; simpl.\nunfold_lift.\nnormalize.\nsubst zz.\neapply derives_trans.\napply andp_derives; [ | apply derives_refl].\napply allp_left with ([], snd oi).\napply unfash_fash.\neapply derives_trans.\napply andp_derives.\napply andp_left1. apply derives_refl. apply derives_refl.\nrewrite andp_comm. apply modus_ponens.\n+\nunfold func_ptr'.\napply subp_andp; [ | apply subp_refl].\nclear - instance.\neapply derives_trans; [ | apply fash_func_ptr_ND].\napply allp_right; intros [hs i].\napply andp_right.\n*\napply allp_right; intro rho.\napply subp_i1.\nrewrite unfash_allp.\nset (zz := allp _).\nunfold convertPre.\nunfold PROPx, PARAMSx, GLOBALSx, LOCALx, SEPx, local, lift1; simpl.\nunfold_lift.\nnormalize.\nrewrite prop_true_andp by tauto.\nsubst zz.\neapply derives_trans.\napply andp_derives; [ | apply derives_refl].\napply allp_left with hs.\napply unfash_fash.\neapply derives_trans.\napply andp_derives.\napply andp_left2. apply derives_refl. apply derives_refl.\nrewrite andp_comm. apply modus_ponens.\n*\napply allp_right; intro rho.\napply subp_i1.\nrewrite unfash_allp.\nset (zz := allp _).\nunfold PROPx, LOCALx, SEPx, local, lift1; simpl.\nunfold_lift.\nnormalize.\nsubst zz.\napply exp_right with x.\nnormalize.\nrewrite prop_true_andp by tauto.\neapply derives_trans.\napply andp_derives; [ | apply derives_refl].\napply allp_left with (i::fst hs, snd hs).\napply unfash_fash.\neapply derives_trans.\napply andp_derives.\napply andp_left1. apply derives_refl. apply derives_refl.\nrewrite andp_comm. apply modus_ponens.\n+\nunfold func_ptr'.\napply subp_andp; [ | apply subp_refl].\nclear - instance.\neapply derives_trans; [ | apply fash_func_ptr_ND].\napply allp_right; intros [hs i].\napply andp_right.\n*\napply allp_right; intro rho.\napply subp_i1.\nrewrite unfash_allp.\nset (zz := allp _).\nunfold convertPre.\nunfold PROPx, PARAMSx, GLOBALSx, LOCALx, SEPx, local, lift1; simpl.\nunfold_lift.\nnormalize.\nrewrite prop_true_andp by tauto.\nsubst zz.\neapply derives_trans.\napply andp_derives; [ | apply derives_refl].\napply allp_left with hs.\napply unfash_fash.\neapply derives_trans.\napply andp_derives.\napply andp_left2. apply derives_refl. apply derives_refl.\nrewrite andp_comm. apply modus_ponens.\n*\napply allp_right; intro rho.\napply subp_i1.\nrewrite unfash_allp.\nset (zz := allp _).\nunfold PROPx, LOCALx, SEPx, local, lift1; simpl.\nunfold_lift.\nnormalize.\nsubst zz.\napply exp_right with x.\nnormalize.\nrewrite prop_true_andp by tauto.\neapply derives_trans.\napply andp_derives; [ | apply derives_refl].\napply allp_left with (i::fst hs, snd hs).\napply unfash_fash.\neapply derives_trans.\napply andp_derives.\napply andp_left1. apply derives_refl. apply derives_refl.\nrewrite andp_comm. apply modus_ponens.\nQed.\n\nDefinition obj_mpred:ObjInv -> mpred := (HORec F). (*ie same type as Andrew's object_mpred.*)\n\nLemma ObjMpred_fold_unfold: \nHOcontractive (fun (_ : ObjInv -> mpred) (x : ObjInv) => instance x) ->\nobj_mpred = \nfun hs => \n  ((EX mtable: val,!!(isptr mtable) &&\n     (|> object_methods obj_mpred mtable) *\n     field_at Ews (Tstruct _object noattr) [StructField _mtable] mtable (snd hs)) *\n   instance hs)%logic.\nProof.\n  intros; unfold obj_mpred at 1.\n  rewrite HORec_fold_unfold; [ reflexivity | apply HOcontrF]; trivial.\nQed.\nLemma ObjMpred_fold_unfold' hs: \nHOcontractive (fun (_ : ObjInv -> mpred) (x : ObjInv) => instance x) ->\nobj_mpred hs = \n  ((EX mtable: val, !!(isptr mtable) &&\n     (|> object_methods obj_mpred mtable) *\n     field_at Ews (Tstruct _object noattr) [StructField _mtable] mtable (snd hs)) *\n   instance hs)%logic.\nProof.\n  intros. rewrite ObjMpred_fold_unfold, <- ObjMpred_fold_unfold; trivial. \nQed.\n\nLemma ObjMpred_isptr\n   (H: HOcontractive (fun (_ : ObjInv -> mpred) (x : ObjInv) => instance x))\n    hs: obj_mpred hs |-- !!(isptr (snd hs)).\nProof. rewrite ObjMpred_fold_unfold' by trivial; Intros m. entailer!. Qed.\n\nEnd ObjMpred.\n\nDefinition object_mpred: object_invariant := fun hs =>\n  EX instance, !!(HOcontractive (fun (_ : ObjInv -> mpred) (x : ObjInv) => instance x)) &&\n               obj_mpred instance hs.\n(*This now plays the role of Andrew's obj_mpred*)\n\nLemma object_mpred_isptr hs: object_mpred hs |-- !!(isptr (snd hs)).\nProof. unfold object_mpred; Intros inst. apply ObjMpred_isptr; trivial. Qed.\n\nLemma obj_mpred_entails_object_mpred inst hs\n  (H: HOcontractive (fun (_ : ObjInv -> mpred) (x : ObjInv) => inst x)):\n  obj_mpred inst hs |-- object_mpred hs.\nProof. unfold object_mpred. Exists inst. entailer!. Qed.\n\n(*Andrew's specs \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)\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 foo_twiddleR_spec :=\n DECLARE _foo_twiddleR  (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*)(nil, p); object_methods foo_invariant (gv _foo_methods)).\n\n*)\n\nSection NewSpecs.\nDefinition foo_data : object_invariant :=\n  (fun (x:ObjInv) => \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 (fst x))))) (snd x)\n      *  malloc_token Ews (Tstruct _foo_object noattr) (snd x)).\nLemma foo_data_HOcontr: HOcontractive (fun (_ : ObjInv -> mpred) (x : ObjInv) => foo_data x).\nProof.\n  assert (predicates_rec.HOcontractive (fun (_ : ObjInv -> mpred) (x : ObjInv) => foo_data x)). 2: apply H.\n  unfold foo_data.\n  unfold withspacer; simpl.\n  apply Trashcan.sepcon_HOcontractive.\n  apply Trashcan.const_HOcontractive.\n  apply Trashcan.const_HOcontractive.\nQed.\n\nDefinition foo_obj_invariant :object_invariant := obj_mpred foo_data.\n\n(*New lemma!*)\nLemma foo_obj_invariant_fold_unfold: foo_obj_invariant =\n fun hs =>\n  ((EX mtable: val, !!(isptr mtable) &&\n     (|>object_methods foo_obj_invariant  mtable) *\n     field_at Ews (Tstruct _object noattr) [StructField _mtable] mtable (snd hs)) *\n   foo_data hs)%logic.\nProof.\n  unfold foo_obj_invariant.\n  rewrite <- ObjMpred_fold_unfold. trivial. apply foo_data_HOcontr.\nQed.\n\n(*Sometimes this variant is preferable, sometimes the one above*)\nLemma foo_obj_invariant_fold_unfold' hs: foo_obj_invariant hs =\n  ((EX mtable: val, !!(isptr mtable) &&\n     (|>object_methods foo_obj_invariant  mtable) *\n     field_at Ews (Tstruct _object noattr) [StructField _mtable] mtable (snd hs)) *\n   foo_data hs)%logic.\nProof. rewrite foo_obj_invariant_fold_unfold. rewrite <- foo_obj_invariant_fold_unfold; trivial. Qed.\n\nLemma foo_data_isptr hs: foo_data hs = !!(isptr (snd hs)) && foo_data hs.\napply pred_ext; entailer.\nunfold foo_data. entailer!. destruct (snd hs); simpl in *; trivial;  contradiction.\nQed.\n\n\nDefinition foo_reset_spec :=\n DECLARE _foo_reset (reset_spec foo_obj_invariant).\n\nDefinition foo_twiddle_spec :=\n DECLARE _foo_twiddle  (twiddle_spec foo_obj_invariant).\n\nDefinition foo_twiddleR_spec :=\n DECLARE _foo_twiddleR  (twiddle_spec foo_obj_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_obj_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_obj_invariant (gv _foo_methods)).\nEnd NewSpecs.\n\nDefinition FooGprog : funspecs :=   ltac:(with_library prog [\n    foo_reset_spec; foo_twiddle_spec; foo_twiddleR_spec; make_foo_spec(*; main_spec*)]).\n\nLemma body_foo_reset: semax_body Vprog FooGprog f_foo_reset foo_reset_spec.\nProof.\nstart_function. \n(*New:*) rewrite foo_obj_invariant_fold_unfold. Intros m; unfold foo_data.\nunfold withspacer; simpl; Intros.\nforward.  (* self->data=0; *)\nentailer!.\n(*New:*) rewrite foo_obj_invariant_fold_unfold, <- foo_obj_invariant_fold_unfold. Exists m; unfold foo_data.\nall: unfold withspacer; simpl; entailer!.  (* needed if Archi.ptr64=true *)\nQed.\n\nLemma body_foo_reset_alternativeproof: semax_body Vprog FooGprog f_foo_reset foo_reset_spec.\nProof.\n(*New*) unfold foo_reset_spec. rewrite foo_obj_invariant_fold_unfold; unfold reset_spec.\nstart_function. \n(*New:*) Intros m; unfold foo_data.\nunfold withspacer; simpl; Intros.\nforward.  (* self->data=0; *)\nentailer!.\n(*New:*) Exists m; unfold foo_data.\nall: unfold withspacer; simpl; entailer!.  (* needed if Archi.ptr64=true *)\nQed.\n\nLemma body_foo_twiddle: semax_body Vprog FooGprog f_foo_twiddle foo_twiddle_spec.\nProof.\n(*New*) unfold foo_twiddle_spec. rewrite foo_obj_invariant_fold_unfold; unfold twiddle_spec.\nstart_function.\n(*New:*) Intros m; unfold foo_data.\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*)(fst hs)) as h.\n  entailer!. }\nforward.  (* return d+i; *)\n{ simpl.\n  set (j:= Int.max_signed / 4) in *; compute in j; subst j.\n  forget (fold_right Z.add 0 (*history*)(fst hs)) as h.\n  entailer!. }\nExists (2 * fold_right Z.add 0 (*history*)(fst hs) + i).\n(*New:*) Exists m; unfold foo_data.\nsimpl;\nentailer!.\nrewrite Z.mul_add_distr_l, Z.add_comm.\nunfold withspacer; simpl.\nentailer!.\nQed.\n\nLemma body_foo_twiddleR: semax_body Vprog FooGprog f_foo_twiddleR foo_twiddleR_spec.\nProof.\n(*New*) unfold foo_twiddleR_spec. rewrite foo_obj_invariant_fold_unfold; unfold twiddle_spec.\nstart_function.\n(*New:*) Intros m; unfold foo_data.\nunfold withspacer; simpl.\nIntros.\nforward.  (* d = self->data; *)\n\n(*The new function call*)\nforward.\nunfold object_methods. Intros sh r t tR.\nforward. (*_s_reset = (_mtable -> _reset);*)\nforward_call hs. \n{ rewrite foo_obj_invariant_fold_unfold'.\n  Exists m. unfold foo_data, withspacer; simpl. entailer!.\n  sep_apply make_object_methods_later. cancel. }\n(*The spec has folded the object, so need to unfold again*)\ndeadvars!. clear - H H0.\nrewrite foo_obj_invariant_fold_unfold. Intros m. unfold foo_data, withspacer; Intros; simpl.\n\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*)(fst hs)) as h.\n  rewrite field_at_isptr; Intros.\n  entailer!. }\nforward.  (* return d+i; *)\n{ simpl.\n  set (j:= Int.max_signed / 4) in *; compute in j; subst j.\n  forget (fold_right Z.add 0 (*history*)(fst hs)) as h.\n  entailer!. }\nExists (2 * fold_right Z.add 0 (*history*)(fst hs) + i).\n(*New:*) Exists m; unfold foo_data.\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 twiddleR.\n\nExists (fst (slice.cleave sh)) reset twiddle twiddleR.\nExists (snd (slice.cleave sh)) reset twiddle twiddleR.\nrewrite (split_func_ptr' (reset_spec instance) reset) at 1.\nrewrite (split_func_ptr' (twiddle_spec instance) twiddle) at 1.\nrewrite (split_func_ptr' (twiddle_spec instance) twiddleR) 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\n(* Isolate a lemma from Andrew's proof of body_make_foo; TODO: simplify the following proof. *)\nLemma MC_FC p (H: malloc_compatible (sizeof (Tstruct _foo_object noattr)) p):\n      field_compatible (Tstruct _object noattr) [StructField _mtable] p.\nProof.\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\nLemma body_make_foo: semax_body Vprog FooGprog 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_obj_invariant (gv _foo_methods))).\n*\nchange (Memory.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.\nsep_apply (split_object_methods foo_obj_invariant (gv _foo_methods)).\nentailer!.\nunfold object_mpred.\n\n(*slight variation of Andrew's proof from here on*)\nExists foo_data. entailer!. 1: solve [apply foo_data_HOcontr].\nrewrite ObjMpred_fold_unfold by (apply foo_data_HOcontr).\nExists (gv _foo_methods). simpl. normalize.\nrewrite ! sepcon_assoc. apply sepcon_derives. apply now_later.\nunfold foo_data; simpl. unfold withspacer; simpl.\ncancel.\nunfold_data_at (field_at _ _ nil _ p).\ncancel.\nclear -H.\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.\napply MC_FC; trivial.\nQed.\n\nEnd FOO.\n\nSection FancyFoo.\n\nDefinition fObjInv : Type:= ((list Z * Z) * val).\nDefinition fobject_invariant := fObjInv -> mpred.\n\n(*not replcatedDefinition tobject := tptr (Tstruct _object noattr).*)\n\nDefinition freset_spec (instance: fobject_invariant) :=\n  WITH hs:fObjInv (*modified*)\n  PRE [ (*_self OF*) tobject]\n          PROP (isptr (snd hs) (*NEW*))\n          PARAMS (snd hs) GLOBALS ()\n          SEP (instance hs)\n  POST [ tvoid ]\n          PROP() LOCAL () SEP(instance ((nil, snd(fst hs)), snd hs)).\n\nDefinition ftwiddle_spec (instance: fobject_invariant) :=\n  WITH hs: fObjInv, i: Z\n  PRE [ (*_self OF*) tobject, (*_i OF*) tint]\n          PROP (0 < i <= Int.max_signed / 4;\n                0 <= fold_right Z.add 0 (fst (fst hs)) <= Int.max_signed / 4; \n               isptr (snd hs) (*NEW*))\n          PARAMS (snd hs; Vint (Int.repr i)) GLOBALS ()\n          SEP (instance hs)\n  POST [ tint ]\n      EX v: Z, \n          PROP(2* fold_right Z.add 0 (fst (fst hs)) < v <= 2* fold_right Z.add 0 (i::(fst (fst hs))))\n          LOCAL (temp ret_temp (Vint (Int.repr v))) \n          SEP(instance ((i::(fst (fst hs)), snd(fst hs)), snd hs)).\n\nDefinition fsetcolor_spec (instance: fobject_invariant) :=\n  WITH hs:fObjInv, c:Z\n  PRE [ (*_self OF*) tobject, (*_c OF*) tint]\n          PROP (isptr (snd hs) (*NEW*))\n          PARAMS (snd hs; Vint(Int.repr c)) GLOBALS ()\n          SEP (instance hs)\n  POST [ tvoid ]\n          PROP() LOCAL () SEP(instance ((fst(fst hs), c), snd hs)).\n\nDefinition fgetcolor_spec (instance: fobject_invariant) :=\n  WITH hs: fObjInv\n  PRE [ (*_self OF*) tobject]\n          PROP (isptr (snd hs) (*NEW*))\n          PARAMS (snd hs) GLOBALS ()\n          SEP (instance hs)\n  POST [ tint ]\n          PROP()\n          LOCAL (temp ret_temp (Vint (Int.repr (snd(fst hs))))) \n          SEP(instance hs).\nCheck reset_spec. Print ObjInv.\n\nDefinition fobject_invariant_of_inv (INV:object_invariant):fobject_invariant.\nProof. intros [[hs c] p]. apply (INV (hs,p)). Defined.\n\nLemma reset_spec_local_sub INV: funspec_sub (reset_spec INV)\n                                            (freset_spec (fobject_invariant_of_inv INV)).\nProof. do_funspec_sub. destruct w as [[hs c] p]; simpl. Exists (hs,p) emp; simpl. entailer!. Qed.\n\nLemma twiddle_spec_local_sub INV: funspec_sub (twiddle_spec INV)\n                                              (ftwiddle_spec (fobject_invariant_of_inv INV)).\nProof. do_funspec_sub. destruct w as [[[hs c] p] i]; simpl. \n  Exists ((hs,p),i) emp; entailer!.\n  intros. Exists x0. entailer!.\nQed.\n\nDefinition fobject_methods (instance: fobject_invariant) (mtable: val) : mpred :=\n  EX sh: share, EX reset: val, EX twiddle: val, EX twiddleR:val, EX setcol: val, EX getcol:val,\n  !! readable_share sh && \n  func_ptr' (freset_spec instance) reset *\n  func_ptr' (ftwiddle_spec instance) twiddle *\n  func_ptr' (ftwiddle_spec instance) twiddleR *\n  func_ptr' (fsetcolor_spec instance) setcol *\n  func_ptr' (fgetcolor_spec instance) getcol *\n  data_at sh (Tstruct _fancymethods noattr) (reset,(twiddle, (twiddleR, (setcol, getcol)))) mtable.\n\nLemma fobject_methods_local_facts: forall instance p,\n  fobject_methods instance p |-- !! isptr p.\nProof.\nintros.\nunfold fobject_methods.\nIntros sh reset twiddle twiddleR setcol getcol.\nentailer!.\nQed.\nLocal Hint Resolve fobject_methods_local_facts : saturate_local.\n\nLemma make_fobject_methods:\n  forall sh instance reset twiddle twiddleR setcol getcol mtable,\n  readable_share sh ->\n  func_ptr' (freset_spec instance) reset *\n  func_ptr' (ftwiddle_spec instance) twiddle *\n  func_ptr' (ftwiddle_spec instance) twiddleR * \n  func_ptr' (fsetcolor_spec instance) setcol *\n  func_ptr' (fgetcolor_spec instance) getcol *\n  data_at sh (Tstruct _fancymethods noattr) (reset,(twiddle, (twiddleR, (setcol, getcol)))) mtable\n  |-- fobject_methods instance mtable.\nProof.\n  intros.\n  unfold fobject_methods.\n  Exists sh reset twiddle twiddleR setcol getcol.\n  entailer!.\nQed.\n\nLemma make_fobject_methods_later:\n  forall sh instance reset twiddle twiddleR setcol getcol mtable,\n  readable_share sh ->\n  func_ptr' (freset_spec instance) reset *\n  func_ptr' (ftwiddle_spec instance) twiddle *\n  func_ptr' (ftwiddle_spec instance) twiddleR * \n  func_ptr' (fsetcolor_spec instance) setcol *\n  func_ptr' (fgetcolor_spec instance) getcol *\n  data_at sh (Tstruct _fancymethods noattr) (reset,(twiddle, (twiddleR, (setcol, getcol)))) mtable\n  |-- |> fobject_methods instance mtable.\nProof.\nintros. eapply derives_trans. apply make_fobject_methods; trivial. apply now_later.\nQed.\n\nSection FObjMpred.\nVariable instance: fobject_invariant.\n\nDefinition G (X: fObjInv -> mpred) (hs: fObjInv): mpred :=\n   ((EX mtable: val, !!(isptr mtable) (*This has to hold NOW, not ust LATER*)&&\n     (|> fobject_methods X mtable) *\n     field_at Ews (Tstruct _object noattr) [StructField _mtable] mtable (snd hs)) *\n   instance hs)%logic.\n\nLemma HOcontrG\n     (*Need sth like this (HI: HOcontractive (fun (_ : ObjInv -> mpred) (x : ObjInv) => instance x))*):\n      HOcontractive G.\nProof.\nunfold F.\napply HOcontractive_i1.\nred; intros.\napply allp_right; intro oi.\napply subp_sepcon_mpred; [ | apply subp_refl].\napply subp_exp; intro v.\napply subp_sepcon_mpred; [ | apply subp_refl].\nclear oi.\napply subp_andp; [ apply subp_refl | ].\nrewrite <- subp_later.\nrewrite <- later_allp.\napply later_derives.\nunfold fobject_methods.\napply subp_exp; intro sh.\napply subp_exp; intro reset.\napply subp_exp; intro twiddle.\napply subp_exp; intro twiddleR.\napply subp_exp; intro setCol.\napply subp_exp; intro getCol.\napply subp_sepcon_mpred; [ | apply subp_refl].\nrepeat simple apply subp_sepcon_mpred;\ntry (simple apply subp_andp; [simple apply subp_refl | ]).\n+\nunfold func_ptr'.\napply subp_andp; [ | apply subp_refl].\nclear - instance.\neapply derives_trans; [ | apply fash_func_ptr_ND].\napply allp_right; intro oi.\napply andp_right.\n*\napply allp_right; intro rho.\napply subp_i1.\nrewrite unfash_allp.\nset (zz := allp _).\nunfold convertPre.\nunfold PROPx, PARAMSx, GLOBALSx, LOCALx, SEPx, local, lift1; simpl.\nunfold_lift.\nnormalize.\nrewrite prop_true_andp by tauto.\nsubst zz.\neapply derives_trans.\napply andp_derives; [ | apply derives_refl].\napply allp_left with oi.\napply unfash_fash.\neapply derives_trans.\napply andp_derives.\napply andp_left2. apply derives_refl. apply derives_refl.\nrewrite andp_comm. apply modus_ponens.\n*\napply allp_right; intro rho.\napply subp_i1.\nrewrite unfash_allp.\nset (zz := allp _).\nunfold convertPre.\nunfold PROPx, LOCALx, SEPx, local, lift1; simpl.\nunfold_lift.\nnormalize.\nsubst zz.\neapply derives_trans.\napply andp_derives; [ | apply derives_refl].\napply allp_left with ([], snd (fst oi), snd oi).\napply unfash_fash.\neapply derives_trans.\napply andp_derives.\napply andp_left1. apply derives_refl. apply derives_refl.\nrewrite andp_comm. apply modus_ponens.\n+\nunfold func_ptr'.\napply subp_andp; [ | apply subp_refl].\nclear - instance.\neapply derives_trans; [ | apply fash_func_ptr_ND].\napply allp_right; intros [hs i].\napply andp_right.\n*\napply allp_right; intro rho.\napply subp_i1.\nrewrite unfash_allp.\nset (zz := allp _).\nunfold convertPre.\nunfold PROPx, PARAMSx, GLOBALSx, LOCALx, SEPx, local, lift1; simpl.\nunfold_lift.\nnormalize.\nrewrite prop_true_andp by tauto.\nsubst zz.\neapply derives_trans.\napply andp_derives; [ | apply derives_refl].\napply allp_left with hs.\napply unfash_fash.\neapply derives_trans.\napply andp_derives.\napply andp_left2. apply derives_refl. apply derives_refl.\nrewrite andp_comm. apply modus_ponens.\n*\napply allp_right; intro rho.\napply subp_i1.\nrewrite unfash_allp.\nset (zz := allp _).\nunfold PROPx, LOCALx, SEPx, local, lift1; simpl.\nunfold_lift.\nnormalize.\nsubst zz.\napply exp_right with x.\nnormalize.\nrewrite prop_true_andp by tauto.\neapply derives_trans.\napply andp_derives; [ | apply derives_refl].\napply allp_left with (i :: fst (fst hs), snd (fst hs), snd hs).\napply unfash_fash.\neapply derives_trans.\napply andp_derives.\napply andp_left1. apply derives_refl. apply derives_refl.\nrewrite andp_comm. apply modus_ponens.\n+\nunfold func_ptr'.\napply subp_andp; [ | apply subp_refl].\nclear - instance.\neapply derives_trans; [ | apply fash_func_ptr_ND].\napply allp_right; intros [hs i].\napply andp_right.\n*\napply allp_right; intro rho.\napply subp_i1.\nrewrite unfash_allp.\nset (zz := allp _).\nunfold convertPre.\nunfold PROPx, PARAMSx, GLOBALSx, LOCALx, SEPx, local, lift1; simpl.\nunfold_lift.\nnormalize.\nrewrite prop_true_andp by tauto.\nsubst zz.\neapply derives_trans.\napply andp_derives; [ | apply derives_refl].\napply allp_left with hs.\napply unfash_fash.\neapply derives_trans.\napply andp_derives.\napply andp_left2. apply derives_refl. apply derives_refl.\nrewrite andp_comm. apply modus_ponens.\n*\napply allp_right; intro rho.\napply subp_i1.\nrewrite unfash_allp.\nset (zz := allp _).\nunfold PROPx, LOCALx, SEPx, local, lift1; simpl.\nunfold_lift.\nnormalize.\nsubst zz.\napply exp_right with x.\nnormalize.\nrewrite prop_true_andp by tauto.\neapply derives_trans.\napply andp_derives; [ | apply derives_refl].\napply allp_left with (i :: fst (fst hs), snd (fst hs), snd hs).\napply unfash_fash.\neapply derives_trans.\napply andp_derives.\napply andp_left1. apply derives_refl. apply derives_refl.\nrewrite andp_comm. apply modus_ponens.\n+\nunfold func_ptr'.\napply subp_andp; [ | apply subp_refl].\nclear - instance.\neapply derives_trans; [ | apply fash_func_ptr_ND].\napply allp_right; intros [hs i].\napply andp_right.\n*\napply allp_right; intro rho.\napply subp_i1.\nrewrite unfash_allp.\nset (zz := allp _).\nunfold convertPre.\nunfold PROPx, PARAMSx, GLOBALSx, LOCALx, SEPx, local, lift1; simpl.\nunfold_lift.\nnormalize.\nrewrite prop_true_andp by tauto.\nsubst zz.\neapply derives_trans.\napply andp_derives; [ | apply derives_refl].\napply allp_left with hs.\napply unfash_fash.\neapply derives_trans.\napply andp_derives.\napply andp_left2. apply derives_refl. apply derives_refl.\nrewrite andp_comm. apply modus_ponens.\n*\napply allp_right; intro rho.\napply subp_i1.\nrewrite unfash_allp.\nset (zz := allp _).\nunfold PROPx, LOCALx, SEPx, local, lift1; simpl.\nunfold_lift.\nnormalize.\nsubst zz. (*\napply exp_right with x.\nnormalize.\nrewrite prop_true_andp by tauto.*)\neapply derives_trans.\napply andp_derives; [ | apply derives_refl].\napply allp_left with (fst (fst hs), i, snd hs).\napply unfash_fash.\neapply derives_trans.\napply andp_derives.\napply andp_left1. apply derives_refl. apply derives_refl.\nrewrite andp_comm. apply modus_ponens.\n+\nunfold func_ptr'.\napply subp_andp; [ | apply subp_refl].\nclear - instance.\neapply derives_trans; [ | apply fash_func_ptr_ND].\napply allp_right; intros [hs i].\napply andp_right.\n*\napply allp_right; intro rho.\napply subp_i1.\nrewrite unfash_allp.\nset (zz := allp _).\nunfold convertPre.\nunfold PROPx, PARAMSx, GLOBALSx, LOCALx, SEPx, local, lift1; simpl.\nunfold_lift.\nnormalize.\nrewrite prop_true_andp by tauto.\nsubst zz.\neapply derives_trans.\napply andp_derives; [ | apply derives_refl].\napply allp_left with (hs,i).\napply unfash_fash.\neapply derives_trans.\napply andp_derives.\napply andp_left2. apply derives_refl. apply derives_refl.\nrewrite andp_comm. apply modus_ponens.\n*\napply allp_right; intro rho.\napply subp_i1.\nrewrite unfash_allp.\nset (zz := allp _).\nunfold PROPx, LOCALx, SEPx, local, lift1; simpl.\nunfold_lift.\nnormalize.\nsubst zz. (*\napply exp_right with x.\nnormalize.\nrewrite prop_true_andp by tauto.*)\neapply derives_trans.\napply andp_derives; [ | apply derives_refl].\napply allp_left with (hs,i).\napply unfash_fash.\neapply derives_trans.\napply andp_derives.\napply andp_left1. apply derives_refl. apply derives_refl.\nrewrite andp_comm. apply modus_ponens.\nQed.\n\nDefinition fobj_mpred:fObjInv -> mpred := (HORec G). (*ie same type as Andrew's object_mpred.*)\n\nLemma fObjMpred_fold_unfold: \nHOcontractive (fun (_ : fObjInv -> mpred) (x : fObjInv) => instance x) ->\nfobj_mpred = \nfun hs => \n  ((EX mtable: val,!!(isptr mtable) &&\n     (|> fobject_methods fobj_mpred mtable) *\n     field_at Ews (Tstruct _object noattr) [StructField _mtable] mtable (snd hs)) *\n   instance hs)%logic.\nProof.\n  intros; unfold fobj_mpred at 1.\n  rewrite HORec_fold_unfold; [ reflexivity | apply HOcontrG]; trivial.\nQed.\nLemma fObjMpred_fold_unfold' hs: \nHOcontractive (fun (_ : fObjInv -> mpred) (x : fObjInv) => instance x) ->\nfobj_mpred hs = \n  ((EX mtable: val, !!(isptr mtable) &&\n     (|> fobject_methods fobj_mpred mtable) *\n     field_at Ews (Tstruct _object noattr) [StructField _mtable] mtable (snd hs)) *\n   instance hs)%logic.\nProof.\n  intros. rewrite fObjMpred_fold_unfold, <- fObjMpred_fold_unfold; trivial. \nQed.\n\nLemma fObjMpred_isptr\n   (H: HOcontractive (fun (_ : fObjInv -> mpred) (x : fObjInv) => instance x))\n    hs: fobj_mpred hs |-- !!(isptr (snd hs)).\nProof. rewrite fObjMpred_fold_unfold' by trivial; Intros m. entailer!. Qed.\n\nEnd FObjMpred.\n\nDefinition fobject_mpred: fobject_invariant := fun hs =>\n  EX instance, !!(HOcontractive (fun (_ : fObjInv -> mpred) (x : fObjInv) => instance x)) &&\n               fobj_mpred instance hs.\n(*This now plays the role of Andrew's obj_mpred*)\n\nLemma fobject_mpred_isptr hs: fobject_mpred hs |-- !!(isptr (snd hs)).\nProof. unfold fobject_mpred; Intros inst. apply fObjMpred_isptr; trivial. Qed.\n\nLemma fobj_mpred_entails_object_mpred inst hs\n  (H: HOcontractive (fun (_ : fObjInv -> mpred) (x : fObjInv) => inst x)):\n  fobj_mpred inst hs |-- fobject_mpred hs.\nProof. unfold object_mpred. Exists inst. entailer!. Qed.\n\nSection FancySpecs.\n\n(*We use (Tstruct _foo_object noattr) (superclass) for the field_at for _data\n  and (Tstruct _fancyfoo_object noattr) for the field_at for _color*)\nDefinition fancyfoo_data : fobject_invariant :=\n  (fun (x:fObjInv) => \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 (fst (fst x)))))) (snd x) \n   * withspacer Ews (sizeof size_t + 2*sizeof tint) (3 * sizeof size_t) (field_at Ews (Tstruct _fancyfoo_object noattr)\n            [StructField _color] (Vint (Int.repr (snd(fst x))))) (snd x)\n      *  malloc_token Ews (Tstruct _fancyfoo_object noattr) (snd x)).\nLemma fancyfoo_data_HOcontr: HOcontractive (fun (_ : fObjInv -> mpred) (x : fObjInv) => fancyfoo_data x).\nProof.\n  assert (predicates_rec.HOcontractive (fun (_ : fObjInv -> mpred) (x : fObjInv) => fancyfoo_data x)). 2: apply H.\n  unfold fancyfoo_data.\n  unfold withspacer; simpl.\n  apply Trashcan.sepcon_HOcontractive.\n  apply Trashcan.const_HOcontractive.\n  apply Trashcan.const_HOcontractive.\nQed.\n\nDefinition fancyfoo_obj_invariant :fobject_invariant := fobj_mpred fancyfoo_data.\n\n(*New lemma!*)\nLemma fancyfoo_obj_invariant_fold_unfold: fancyfoo_obj_invariant =\n fun hs =>\n  ((EX mtable: val, !!(isptr mtable) &&\n     (|>fobject_methods fancyfoo_obj_invariant  mtable) *\n     field_at Ews (Tstruct _object noattr) [StructField _mtable] mtable (snd hs)) *\n   fancyfoo_data hs)%logic.\nProof.\n  unfold fancyfoo_obj_invariant.\n  rewrite <- fObjMpred_fold_unfold. trivial. apply fancyfoo_data_HOcontr.\nQed.\n\n(*Sometimes this variant is preferable, sometimes the one above*)\nLemma fancyfoo_obj_invariant_fold_unfold' hs: fancyfoo_obj_invariant hs =\n  ((EX mtable: val, !!(isptr mtable) &&\n     (|>fobject_methods fancyfoo_obj_invariant  mtable) *\n     field_at Ews (Tstruct _object noattr) [StructField _mtable] mtable (snd hs)) *\n   fancyfoo_data hs)%logic.\nProof. rewrite fancyfoo_obj_invariant_fold_unfold. rewrite <- fancyfoo_obj_invariant_fold_unfold; trivial. Qed.\n\nLemma fancyfoo_data_isptr hs: fancyfoo_data hs = !!(isptr (snd hs)) && fancyfoo_data hs.\napply pred_ext; entailer.\nunfold fancyfoo_data. entailer!. destruct (snd hs); simpl in *; trivial;  contradiction.\nQed.\n\n\n(*The three inherited functions are equipped with fancy specs*)\nDefinition ffoo_reset_spec :=\n DECLARE _foo_reset (freset_spec fancyfoo_obj_invariant).\n\nDefinition ffoo_twiddle_spec :=\n DECLARE _foo_twiddle  (ftwiddle_spec fancyfoo_obj_invariant).\n\nDefinition ffoo_twiddleR_spec :=\n DECLARE _foo_twiddleR  (ftwiddle_spec fancyfoo_obj_invariant).\n\nDefinition ffoo_setcolor_spec :=\n DECLARE _setcolor  (fsetcolor_spec fancyfoo_obj_invariant).\n\nDefinition ffoo_getcolor_spec :=\n DECLARE _getcolor  (fgetcolor_spec fancyfoo_obj_invariant).\n\nDefinition make_fancyfoo_spec :=\n DECLARE _make_fancyfoo\n WITH gv: globals, c:Z\n PRE [(*_c OF*) tint ]\n    PROP () PARAMS (Vint(Int.repr c)) GLOBALS (gv) \n    SEP (mem_mgr gv; fobject_methods fancyfoo_obj_invariant (gv _fancyfoo_methods))\n POST [ tobject ]\n    EX p: val, PROP () LOCAL (temp ret_temp p)\n     SEP (mem_mgr gv; fobject_mpred ((nil,c),p); fobject_methods fancyfoo_obj_invariant (gv _fancyfoo_methods)).\n\nDefinition make_fancyfooTyped_spec :=\n DECLARE _make_fancyfooTyped\n WITH gv: globals, c:Z\n PRE [ (*_c OF*) tint ]\n    PROP () PARAMS (Vint(Int.repr c)) GLOBALS (gv) \n    SEP (mem_mgr gv; fobject_methods fancyfoo_obj_invariant (gv _fancyfoo_methods))\n POST [ tptr (Tstruct _fancyfoo_object noattr) ]\n    EX p: val, PROP () LOCAL (temp ret_temp p)\n     SEP (mem_mgr gv; fobject_mpred ((nil,c),p); fobject_methods fancyfoo_obj_invariant (gv _fancyfoo_methods)).\n\nEnd FancySpecs.\n\nDefinition FancyGprog : funspecs :=   ltac:(with_library prog [\n    ffoo_reset_spec; ffoo_twiddle_spec; ffoo_twiddleR_spec;\n    ffoo_setcolor_spec; ffoo_getcolor_spec;\n    make_fancyfoo_spec; make_fancyfooTyped_spec(*; main_spec*)]).\n\nLemma body_fancyfoo_reset: semax_body Vprog FancyGprog f_foo_reset ffoo_reset_spec.\nProof.\nstart_function. \n(*New:*) rewrite fancyfoo_obj_invariant_fold_unfold. Intros m; unfold fancyfoo_data.\nunfold withspacer; simpl; Intros.\nforward.  (* self->data=0; *)\nentailer!.\n(*New:*) rewrite fancyfoo_obj_invariant_fold_unfold, <- fancyfoo_obj_invariant_fold_unfold. Exists m; unfold fancyfoo_data.\nall: unfold withspacer; simpl; entailer!.  (* needed if Archi.ptr64=true *)\nQed.\n\nLemma body_fancyfoo_twiddle: semax_body Vprog FancyGprog f_foo_twiddle ffoo_twiddle_spec.\nProof.\nstart_function.\n(*New:*) rewrite fancyfoo_obj_invariant_fold_unfold. Intros m; unfold fancyfoo_data.\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 (*(fst hs)*)(fst(fst hs))) as h.\n  entailer!. }\nforward.  (* return d+i; *)\n{ simpl.\n  set (j:= Int.max_signed / 4) in *; compute in j; subst j.\n  forget (fold_right Z.add 0 (*(fst hs)*) (fst(fst hs))) as h.\n  entailer!. }\nExists (2 * fold_right Z.add 0 (*(fst hs)*) (fst(fst hs)) + i).\n(*New:*) rewrite fancyfoo_obj_invariant_fold_unfold, <- fancyfoo_obj_invariant_fold_unfold.\nExists m; unfold fancyfoo_data.\nsimpl;\nentailer!.\nrewrite Z.mul_add_distr_l, Z.add_comm.\nunfold withspacer; simpl.\nentailer!.\nQed.\n\n(*A key lemma relating the two classes*)\nLemma FC_fancymethods f m (L: legal_field (nested_field_type (Tstruct _methods noattr) []) (StructField f))\n        (FC: field_compatible (Tstruct _fancymethods noattr) [StructField f] m):\n        field_compatible (Tstruct _methods noattr) [StructField f] m.\nProof. \n  destruct FC as [X1 [X2 [SZ [AL [X5 X6]]]]].\n  destruct m; try inv X1. clear - L SZ AL.\n  repeat split; auto.\n  + simpl in *.  unfold sizeof in *; simpl in *; lia.\n  + clear L SZ. inv AL. inv H. inv H1. \n    eapply align_compatible_rec_Tstruct; [reflexivity |].\n    simpl co_members in *; intros. specialize (H3 i0 t0).\n    simpl in H.\n    if_tac in H.\n    { inv H. specialize (H3 _ (eq_refl _) (eq_refl _)).\n      inv H3. inv H0. inv H. simpl in H1.\n      eapply align_compatible_rec_by_value.\n      reflexivity. apply H1. }\n    clear H1. \n    if_tac in H.\n    { inv H. specialize (H3 _ (eq_refl _) (eq_refl _)).\n      inv H3. inv H0. inv H. simpl in H1.\n      eapply align_compatible_rec_by_value.\n      reflexivity. apply H1. }\n    clear H1. \n    if_tac in H.\n    { inv H. specialize (H3 _ (eq_refl _) (eq_refl _)).\n      inv H3. inv H0. inv H. simpl in H1.\n      eapply align_compatible_rec_by_value.\n      reflexivity. apply H1. }\n    inv H.\nQed.\n\nLemma body_fancyfoo_twiddleR: semax_body Vprog FancyGprog f_foo_twiddleR ffoo_twiddleR_spec.\nProof.\nstart_function.\n(*New:*) rewrite fancyfoo_obj_invariant_fold_unfold. Intros m; unfold fancyfoo_data.\nunfold withspacer; simpl.\nIntros.\nforward.  (* d = self->data; *)\n\n(*The new function call*)\nforward.\nunfold fobject_methods. Intros sh r t tR g s.\n\n(*New HERE*)\nunfold_data_at (data_at sh (Tstruct _fancymethods noattr) _ _).\nrewrite (field_at_compatible' sh (Tstruct _fancymethods noattr) [StructField _reset]); Intros. rename H3 into FCmethod.\nreplace_SEP 5 (field_at sh (Tstruct _methods noattr) [StructField _reset] r m).\n{ clear - FCmethod. entailer!. clear - FCmethod. unfold field_at; simpl; entailer!. \n  apply FC_fancymethods; trivial. left; auto. }\n\nforward. (*_s_reset = (_mtable -> _reset);*)\nforward_call hs. \n{ (*NEW side condition - again a property of subclasses*)\n  rewrite fancyfoo_obj_invariant_fold_unfold'.\n  Exists m. unfold fancyfoo_data, withspacer; simpl. entailer!.\n  eapply derives_trans. \n  2:{ apply sepcon_derives.\n      apply ( make_fobject_methods_later sh fancyfoo_obj_invariant r t tR g s m); trivial.\n      apply derives_refl. } \n  cancel. unfold_data_at (data_at sh (Tstruct _fancymethods noattr) _ _ ).\n  cancel. unfold field_at; simpl; entailer!. }\n(*The spec has folded the object, so need to unfold again*)\ndeadvars!. clear - H H0.\nrewrite fancyfoo_obj_invariant_fold_unfold. Intros m. unfold fancyfoo_data, withspacer; Intros; simpl.\n\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 (*(fst hs)*)(fst(fst hs))) as h.\n  rewrite field_at_isptr; Intros.\n  entailer!. }\nforward.  (* return d+i; *)\n{ simpl.\n  set (j:= Int.max_signed / 4) in *; compute in j; subst j.\n  forget (fold_right Z.add 0 (*(fst hs)*)(fst(fst hs))) as h.\n  entailer!. }\nExists (2 * fold_right Z.add 0 (*(fst hs)*)(fst(fst hs)) + i).\n(*New:*) rewrite fancyfoo_obj_invariant_fold_unfold, <- fancyfoo_obj_invariant_fold_unfold.\nExists m; unfold fancyfoo_data.\nsimpl;\nentailer!.\nrewrite Z.mul_add_distr_l, Z.add_comm.\nunfold withspacer; simpl.\nentailer!.\nQed.\n\nLemma body_ffoo_setcolor: semax_body Vprog FancyGprog f_setcolor ffoo_setcolor_spec.\nProof.\nstart_function. \n(*New:*) rewrite fancyfoo_obj_invariant_fold_unfold. Intros m; unfold fancyfoo_data.\nunfold withspacer; simpl; Intros.\nforward.  (* self->color=0; *)\nentailer!.\n(*New:*) rewrite fancyfoo_obj_invariant_fold_unfold, <- fancyfoo_obj_invariant_fold_unfold. Exists m; unfold fancyfoo_data.\nall: unfold withspacer; simpl; entailer!.  (* needed if Archi.ptr64=true *)\nQed.\n\nLemma body_ffoo_getcolor: semax_body Vprog FancyGprog f_getcolor ffoo_getcolor_spec.\nProof.\nstart_function. \n(*New:*) rewrite fancyfoo_obj_invariant_fold_unfold. Intros m; unfold fancyfoo_data.\nunfold withspacer; simpl; Intros.\nforward.  (* _t'1 = ((tptr (Tstruct _fancyfoo_object noattr)) _self -> _color); *)\nforward.\nentailer!.\n(*New:*) rewrite fancyfoo_obj_invariant_fold_unfold, <- fancyfoo_obj_invariant_fold_unfold. Exists m; unfold fancyfoo_data.\nall: unfold withspacer; simpl; entailer!.  (* needed if Archi.ptr64=true *)\nQed.\n\nLemma split_fobject_methods:\n  forall instance m, \n    fobject_methods instance m |-- fobject_methods instance m * fobject_methods instance m.\nProof.\nintros.\nunfold fobject_methods.\nIntros sh reset twiddle twiddleR setC getC.\n\nExists (fst (slice.cleave sh)) reset twiddle twiddleR setC getC.\nExists (snd (slice.cleave sh)) reset twiddle twiddleR setC getC.\nrewrite (split_func_ptr' (freset_spec instance) reset) at 1.\nrewrite (split_func_ptr' (ftwiddle_spec instance) twiddle) at 1.\nrewrite (split_func_ptr' (ftwiddle_spec instance) twiddleR) at 1.\nrewrite (split_func_ptr' (fsetcolor_spec instance) setC) at 1.\nrewrite (split_func_ptr' (fgetcolor_spec instance) getC) 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_fancyfoo: semax_body Vprog FancyGprog f_make_fancyfoo make_fancyfoo_spec.\nProof.\nunfold make_fancyfoo_spec.\nstart_function.\nforward_call (Tstruct _fancyfoo_object noattr, gv).\nIntros p.\nforward_if\n  (PROP ( )\n   LOCAL (temp _p p; temp _c (Vint (Int.repr c)); gvars gv)\n   SEP (mem_mgr gv;\n          malloc_token Ews (Tstruct _fancyfoo_object noattr) p;\n          data_at_ Ews (Tstruct _fancyfoo_object noattr) p;\n          fobject_methods fancyfoo_obj_invariant (gv _fancyfoo_methods))).\n*\nchange (Memory.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 = &fancyfoo_methods; *)\nforward. (* p->data = 0; *)\nforward. (* p->color = c;*)\nforward. (* return (struct object * ) p; *)\nExists p.\nsep_apply (split_fobject_methods fancyfoo_obj_invariant (gv _fancyfoo_methods)).\nentailer!.\nunfold fobject_mpred.\n\n(*slight variation of Andrew's proof from here on*)\nExists fancyfoo_data. entailer!. 1: solve [apply fancyfoo_data_HOcontr].\nrewrite fObjMpred_fold_unfold by (apply fancyfoo_data_HOcontr).\nExists (gv _fancyfoo_methods). simpl. normalize.\nrewrite ! sepcon_assoc. apply sepcon_derives. apply now_later.\nunfold fancyfoo_data; simpl. unfold withspacer; simpl.\ncancel.\nunfold_data_at (field_at _ _ nil _ p).\ncancel.\nassert_PROP (isptr p) by entailer!. destruct p; inv H2. entailer!.\napply sepcon_derives.\n+ clear - H2. unfold field_at; simpl; entailer!.\n  - unfold field_compatible. destruct H2 as [_ [_ [SZ [AL _]]]].\n    repeat split; trivial.\n    ++ red. red in SZ. simpl sizeof in *. lia.\n    ++ clear SZ. inv AL. inv H.\n       eapply align_compatible_rec_Tstruct; [reflexivity | intros]. specialize (H3 i0).\n       simpl co_members in *; intros. inv H. \n       if_tac in H4; inv H4.\n       inv H0. inv H1. specialize (H3 _ 0 (eq_refl _) (eq_refl _)).\n       inv H3. inv H. econstructor. reflexivity. trivial.\n    ++ simpl. left; auto.\n  - unfold at_offset. entailer!. unfold data_at_rec. simpl.\n    unfold mapsto; simpl. if_tac; entailer!.\n+ clear - H4. unfold field_at; simpl; entailer!.\n  - unfold field_compatible. destruct H4 as [_ [_ [SZ [AL _]]]].\n    repeat split; trivial.\n    ++ red. red in SZ. simpl sizeof in *. lia.\n    ++ clear SZ; inv AL. inv H.\n       eapply align_compatible_rec_Tstruct; [reflexivity | intros]. specialize (H3 i0).\n       simpl co_members in *; intros. inv H. \n       if_tac in H4; inv H4.\n       { inv H0. inv H1. specialize (H3 _ 0 (eq_refl _) (eq_refl _)).\n          inv H3. inv H. econstructor. reflexivity. trivial. }\n       clear H.\n       if_tac in H5; inv H5.\n       { inv H0. inv H1. specialize (H3 _ 4 (eq_refl _) (eq_refl _)).\n          inv H3. inv H. econstructor. reflexivity. trivial. }\n    ++ simpl. right; left; auto.\nQed.\n\n(*EXACT SAME PROOF SCRIPT AS Lemma body_make_fancyfoo*)\nLemma body_make_fancyfooTyped: semax_body Vprog FancyGprog f_make_fancyfooTyped make_fancyfooTyped_spec.\nProof.\nunfold make_fancyfooTyped_spec.\nstart_function.\nforward_call (Tstruct _fancyfoo_object noattr, gv).\nIntros p.\nforward_if\n  (PROP ( )\n   LOCAL (temp _p p; temp _c (Vint (Int.repr c)); gvars gv)\n   SEP (mem_mgr gv;\n          malloc_token Ews (Tstruct _fancyfoo_object noattr) p;\n          data_at_ Ews (Tstruct _fancyfoo_object noattr) p;\n          fobject_methods fancyfoo_obj_invariant (gv _fancyfoo_methods))).\n*\nchange (Memory.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 = &fancyfoo_methods; *)\nforward. (* p->data = 0; *)\nforward. (* p->color = c;*)\nforward. (* return (struct object * ) p; *)\nExists p.\nsep_apply (split_fobject_methods fancyfoo_obj_invariant (gv _fancyfoo_methods)).\nentailer!.\nunfold fobject_mpred.\n\n(*slight variation of Andrew's proof from here on*)\nExists fancyfoo_data. entailer!. 1: solve [apply fancyfoo_data_HOcontr].\nrewrite fObjMpred_fold_unfold by (apply fancyfoo_data_HOcontr).\nExists (gv _fancyfoo_methods). simpl. normalize.\nrewrite ! sepcon_assoc. apply sepcon_derives. apply now_later.\nunfold fancyfoo_data; simpl. unfold withspacer; simpl.\ncancel.\nunfold_data_at (field_at _ _ nil _ p).\ncancel.\n\n(*TODO: There's at least one variation of Lemma MC_FC in here...*)\nassert_PROP (isptr p) by entailer!. destruct p; inv H2. entailer!.\napply sepcon_derives.\n+ clear - H2. unfold field_at; simpl; entailer!.\n  - unfold field_compatible. destruct H2 as [_ [_ [SZ [AL _]]]].\n    repeat split; trivial.\n    ++ red. red in SZ. simpl sizeof in *. lia.\n    ++ clear SZ. inv AL. inv H.\n       eapply align_compatible_rec_Tstruct; [reflexivity | intros]. specialize (H3 i0).\n       simpl co_members in *; intros. inv H. \n       if_tac in H4; inv H4.\n       inv H0. inv H1. specialize (H3 _ 0 (eq_refl _) (eq_refl _)).\n       inv H3. inv H. econstructor. reflexivity. trivial.\n    ++ simpl. left; auto.\n  - unfold at_offset. entailer!. unfold data_at_rec. simpl.\n    unfold mapsto; simpl. if_tac; entailer!.\n+ clear (*- H4*). unfold field_at; simpl; entailer!.\n  - unfold field_compatible. destruct H as [_ [_ [SZ [AL _]]]].\n    repeat split; trivial.\n    ++ red. red in SZ. simpl sizeof in *. lia.\n    ++ clear SZ; inv AL. inv H.\n       eapply align_compatible_rec_Tstruct; [reflexivity | intros]. specialize (H3 i0).\n       simpl co_members in *; intros. inv H. \n       if_tac in H4; inv H4.\n       { inv H0. inv H1. specialize (H3 _ 0 (eq_refl _) (eq_refl _)).\n          inv H3. inv H. econstructor. reflexivity. trivial. }\n       clear H.\n       if_tac in H5; inv H5.\n       { inv H0. inv H1. specialize (H3 _ 4 (eq_refl _) (eq_refl _)).\n          inv H3. inv H. econstructor. reflexivity. trivial. }\n    ++ simpl. right; left; auto.\nQed.\n\nEnd FancyFoo.\n\nSection Putting_It_All_Together.\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) LOCAL (temp ret_temp (Vint (Int.repr (i+13)))) SEP(TT).\n\nDefinition reset_intersection: funspec.\nProof.\neapply (binary_intersection' (reset_spec foo_obj_invariant) (freset_spec fancyfoo_obj_invariant)); reflexivity.\nDefined.\nDefinition twiddle_intersection: funspec.\nProof.\neapply (binary_intersection' (twiddle_spec foo_obj_invariant) (ftwiddle_spec fancyfoo_obj_invariant)); reflexivity.\nDefined.\n\nLemma reset_sub_foo: funspec_sub reset_intersection (reset_spec foo_obj_invariant).\nProof. \napply (binaryintersection_sub (reset_spec foo_obj_invariant) (freset_spec fancyfoo_obj_invariant)).\napply binary_intersection'_sound.\nQed.\nLemma reset_sub_fancy: funspec_sub reset_intersection (freset_spec fancyfoo_obj_invariant).\nProof. \napply (binaryintersection_sub (reset_spec foo_obj_invariant) (freset_spec fancyfoo_obj_invariant)).\napply binary_intersection'_sound.\nQed.\n\nLemma twiddle_sub_foo: funspec_sub twiddle_intersection (twiddle_spec foo_obj_invariant).\nProof. \napply (binaryintersection_sub (twiddle_spec foo_obj_invariant) (ftwiddle_spec fancyfoo_obj_invariant)).\napply binary_intersection'_sound.\nQed.\nLemma twiddle_sub_fancy: funspec_sub twiddle_intersection (ftwiddle_spec fancyfoo_obj_invariant).\nProof. \napply (binaryintersection_sub (twiddle_spec foo_obj_invariant) (ftwiddle_spec fancyfoo_obj_invariant)).\napply binary_intersection'_sound.\nQed.\n\nDefinition Gprog : funspecs :=   ltac:(with_library prog [\n    (_foo_reset, reset_intersection); (_foo_twiddle, twiddle_intersection); (_foo_twiddleR, twiddle_intersection);\n    (*foo_reset_spec; foo_twiddle_spec; foo_twiddleR_spec; *)make_foo_spec; \n    (*ffoo_reset_spec; ffoo_twiddle_spec; ffoo_twiddleR_spec; *)\n    ffoo_setcolor_spec; ffoo_getcolor_spec;\n    make_fancyfoo_spec; make_fancyfooTyped_spec; main_spec]).\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\n(* 0. This part should be handled automatically by start_function *) simpl.\ngather_SEP (mapsto _ _ (offset_val 8 (gv _foo_methods)) _) \n           (mapsto _ _ (offset_val 4 (gv _foo_methods)) _)\n           (data_at _ _ _ (gv _foo_methods));\nreplace_SEP 0 (data_at Ews (Tstruct _methods noattr) \n   (gv _foo_reset, (gv _foo_twiddle, gv _foo_twiddleR)) (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 <- mapsto_field_at with (gfs := [StructField _twiddleR]) (v:= (gv _foo_twiddleR))\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}\ngather_SEP (mapsto _ _ (offset_val 16 (gv _fancyfoo_methods)) _) \n           (mapsto _ _ (offset_val 12 (gv _fancyfoo_methods)) _)\n           (mapsto _ _ (offset_val 8 (gv _fancyfoo_methods)) _) \n           (mapsto _ _ (offset_val 4 (gv _fancyfoo_methods)) _)\n           (data_at _ _ _ (gv _fancyfoo_methods));\nreplace_SEP 0 (data_at Ews (Tstruct _fancymethods noattr) \n   (gv _foo_reset, (gv _foo_twiddle, (gv _foo_twiddleR, (gv _setcolor, gv _getcolor)))) (gv _fancyfoo_methods)). {\n  entailer!.\n  unfold_data_at (data_at _ (Tstruct _fancymethods _) _ (gv _fancyfoo_methods)).\n  rewrite <- mapsto_field_at with (gfs := [StructField _twiddle]) (v:= (gv _foo_twiddle))\n  by  auto with field_compatible. \n  rewrite <- mapsto_field_at with (gfs := [StructField _twiddleR]) (v:= (gv _foo_twiddleR))\n  by  auto with field_compatible.\n  rewrite <- mapsto_field_at with (gfs := [StructField _setcolor]) (v:= (gv _setcolor))\n  by  auto with field_compatible. \n  rewrite <- mapsto_field_at with (gfs := [StructField _getcolor]) (v:= (gv _getcolor))\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(* 1a. Prove that [methods] is a proper method table for foo-objects, and that\n        fancymethods is a proper method table for fancyfoo-objects *)\n\nmake_func_ptr _foo_reset.\nreplace_SEP 0 (func_ptr' (reset_spec foo_obj_invariant) (gv _foo_reset) *\n               func_ptr' (freset_spec fancyfoo_obj_invariant) (gv _foo_reset)).\n{ entailer!. rewrite split_func_ptr'. apply sepcon_derives; apply func_ptr'_mono.\n  apply reset_sub_foo. apply reset_sub_fancy. }\nmake_func_ptr _foo_twiddle.\nreplace_SEP 0 (func_ptr' (twiddle_spec foo_obj_invariant) (gv _foo_twiddle) *\n               func_ptr' (ftwiddle_spec fancyfoo_obj_invariant) (gv _foo_twiddle)).\n{ entailer!. rewrite split_func_ptr'. apply sepcon_derives; apply func_ptr'_mono.\n  apply twiddle_sub_foo. apply twiddle_sub_fancy. }\nmake_func_ptr _foo_twiddleR.\nreplace_SEP 0 (func_ptr' (twiddle_spec foo_obj_invariant) (gv _foo_twiddleR) *\n               func_ptr' (ftwiddle_spec fancyfoo_obj_invariant) (gv _foo_twiddleR)).\n{ entailer!. rewrite split_func_ptr'. apply sepcon_derives; apply func_ptr'_mono.\n  apply twiddle_sub_foo. apply twiddle_sub_fancy. }\nsep_apply (make_object_methods Ews foo_obj_invariant (gv _foo_reset) (gv _foo_twiddle) (gv _foo_twiddleR) (gv _foo_methods)); auto.\n\nmake_func_ptr _setcolor.\nmake_func_ptr _getcolor.\nsep_apply (make_fobject_methods Ews fancyfoo_obj_invariant (gv _foo_reset) (gv _foo_twiddle) (gv _foo_twiddleR) (gv _setcolor) (gv _getcolor)(gv _fancyfoo_methods)); auto.\n\n(* 2. Build an instance of class [foo], called [p] *)\nforward_call (* p = make_foo(); *)\n        gv.\nIntros p.\n\n(* 4. Build an instance of class [fancyfoo], called [q] *)\nforward_call (* q = make_fancyfoo(); *)\n        (gv,4).\nIntros q.\n(*New*) freeze [0;2; 4;5 ] FR1. (*Hide the global method tables, memmgr, and the has_ext *)\n\nassert_PROP (p<>Vundef) as pNotVundef 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(*TODO: Adapt\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, p.reset *)\n(*NEW*) assert_PROP (isptr p) as isptrP by (sep_apply object_mpred_isptr; entailer!).\nunfold object_mpred.\n\n(*WAS:Intros instance mtable0.*)\n(*Now*) Intros instance. rename H into HOC. rewrite ObjMpred_fold_unfold by trivial. Intros mtable0; simpl.\n\nforward. (*  mtable = p->mtable; *)\nunfold object_methods at 1.\nIntros sh r0 t0 tR0.\nforward. (* p_reset = mtable->reset; *)\nforward_call (* p_reset(p); *)\n      (@nil Z,p).\n{ (*NEW subgoal*)\n   sep_apply make_object_methods_later.\n   rewrite ObjMpred_fold_unfold, <- ObjMpred_fold_unfold by trivial.\n   Exists mtable0. entailer!. } \n(* WAS (*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).*)\n\n(*Now: folding partially done by forward_call (and the preceding new subgoal*)\nsep_apply obj_mpred_entails_object_mpred; simpl.\n\ndeadvars!. clear.\n\n(* 5. second method-call, q.reset *)\n(*NEW*) assert_PROP (isptr q) as isptrQ by (sep_apply fobject_mpred_isptr; entailer!).\nunfold fobject_mpred.\n\n(*WAS:Intros instance mtable0.*)\n(*Now*) Intros instance. rename H into HOC. rewrite fObjMpred_fold_unfold by trivial. Intros mtable0; simpl.\n\nforward. (*_t'9 = (_q -> _mtable);*)\nforward. (*_mtable = (tptr (Tstruct _fancymethods noattr)) _t'9;*)\n\nunfold fobject_methods at 1.\nIntros sh r0 t0 tR0 sC gC.\nforward. (* q_reset = qmtable->reset; *)\nforward_call (* q_reset(q); *)\n      ((@nil Z,4),q).\n{ (*NEW subgoal*)\n   sep_apply make_fobject_methods_later.\n   rewrite fObjMpred_fold_unfold, <- fObjMpred_fold_unfold by trivial.\n   Exists mtable0. entailer!. } \n(* WAS (*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).*)\n\n(*Now: folding partially done by forward_call (and the preceding new subgoal*)\nsep_apply fobj_mpred_entails_object_mpred; simpl.\n\ndeadvars!. clear.\n\n(* 6. second method-call on q, q->getcolor *)\n(*NEW*) assert_PROP (isptr q) as isptrQ by (sep_apply fobject_mpred_isptr; entailer!).\nunfold fobject_mpred.\n\n(*WAS:Intros instance mtable0.*)\n(*Now*) Intros instance. rename H into HOC. rewrite fObjMpred_fold_unfold by trivial. Intros mtable0; simpl.\n\nforward. (*_t'8 = (_q -> _mtable);*)\nforward. (*_mtable = (tptr (Tstruct _fancymethods noattr)) _t'8;*)\n\nunfold fobject_methods at 1.\nIntros sh r0 t0 tR0 sC gC.\nforward. (* q_getcolor = qmtable->getcolor; *)\nforward_call (* q_reset(q); *)\n      ((@nil Z,4),q).\n{ (*NEW subgoal*)\n   sep_apply make_fobject_methods_later.\n   rewrite fObjMpred_fold_unfold, <- fObjMpred_fold_unfold by trivial.\n   Exists mtable0. entailer!. } \n(* WAS (*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).*)\n\n(*Now: folding partially done by forward_call (and the preceding new subgoal*)\nsep_apply fobj_mpred_entails_object_mpred; simpl.\n\ndeadvars!. clear.\n\n(* 7. second method-call on p, p->twiddleR*)\n(*NEW*) assert_PROP (isptr p) as isptrP by (sep_apply object_mpred_isptr; entailer!).\nunfold object_mpred.\n\n(*WAS:Intros instance mtable0.*)\n(*Now*) Intros instance. rename H into HOC. rewrite ObjMpred_fold_unfold by trivial. Intros mtable0; simpl.\n\nforward.  (* pmtable = p->mtable; *)\nunfold object_methods at 1.\nIntros sh r0 t0 tR0.\nforward.   (* p_twiddle = pmtable->twiddleR; *)\n(*Now redundant: assert_PROP (p<>Vundef) by entailer!.*)\nforward_call (* i = p_twiddle(p,3); *)\n      ((@nil Z,p), 3).\n{ (*NEW subgoal*)\n   sep_apply make_object_methods_later.\n   rewrite ObjMpred_fold_unfold, <- ObjMpred_fold_unfold by trivial.\n   Exists mtable0. entailer!. }\n{ simpl. repeat split; try trivial; 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).*)\nsep_apply obj_mpred_entails_object_mpred; simpl.\ndeadvars!. rename H0 into Hi. clear - Hi.\n\n(* 8. Build an typed instance of class [fancyfoo], called [p] *)\nthaw FR1.\nforward_call (*t'5 = _make_fancyfooTyped([((9)*)\n        (gv, 9).\nIntros u. freeze [0; 2; 5;6] FR1. (*Hide the global method tables, the memmgr, and and the has_ext *)\nfreeze [2;3] PQ. (*Hide the other objects p and q*)\n\n(* 9. first method-call on u, u->reset *)\n(*NEW*) assert_PROP (isptr u) as isptrU by (sep_apply fobject_mpred_isptr; entailer!).\nunfold fobject_mpred.\n\n(*WAS:Intros instance mtable0.*)\n(*Now*) Intros instance. rename H into HOC. rewrite fObjMpred_fold_unfold by trivial. Intros mtable0; simpl.\n\nforward. (*_t'7 = ((tptr (Tstruct _object noattr)) _u -> _mtable);*)\nforward. (* _umtable = (tptr (Tstruct _fancymethods noattr)) _t'7;*)\n\nunfold fobject_methods at 1.\nIntros sh r0 t0 tR0 sC gC.\nforward. (* u_reset = (_umtable -> _reset); *)\nforward_call (* u_reset(u); *)\n      ((@nil Z,9),u).\n{ (*NEW subgoal*)\n   sep_apply make_fobject_methods_later.\n   rewrite fObjMpred_fold_unfold, <- fObjMpred_fold_unfold by trivial.\n   Exists mtable0. entailer!. } \n(* WAS (*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).*)\n\n(*Now: folding partially done by forward_call (and the preceding new subgoal*)\nsep_apply fobj_mpred_entails_object_mpred; simpl.\n\ndeadvars!. clear -Hi.\n\n(* 10. second method-call on u, u->getcolor *)\n(*NEW*) assert_PROP (isptr u) as isptrU by (sep_apply fobject_mpred_isptr; entailer!).\nunfold fobject_mpred.\n\n(*WAS:Intros instance mtable0.*)\n(*Now*) Intros instance. rename H into HOC. rewrite fObjMpred_fold_unfold by trivial. Intros mtable0; simpl.\n\nforward. (*_t'7 = ((tptr (Tstruct _object noattr)) _u -> _mtable);*)\nforward. (* _umtable = (tptr (Tstruct _fancymethods noattr)) _t'7;*)\n\nunfold fobject_methods at 1.\nIntros sh r0 t0 tR0 sC gC.\nforward. (* u_getcolor = (_umtable -> _getcolor); *)\nforward_call (* u_getcolor(u); *)\n      ((@nil Z,9),u).\n{ (*NEW subgoal*)\n   sep_apply make_fobject_methods_later.\n   rewrite fObjMpred_fold_unfold, <- fObjMpred_fold_unfold by trivial.\n   Exists mtable0. entailer!. } \n(* WAS (*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).*)\n\n(*Now: folding partially done by forward_call (and the preceding new subgoal*)\nsep_apply fobj_mpred_entails_object_mpred; simpl.\n\ndeadvars!. clear -Hi.\n\n(* 11. return *)\nforward.  (* return i; *)\nExists i; entailer!. f_equal. f_equal. lia.\nQed.\n\nEnd Putting_It_All_Together.\nParameter QQ:mpred.\nLemma funspec_sub_reset_foo_fancy: funspec_sub (reset_spec foo_obj_invariant) (freset_spec fancyfoo_obj_invariant).\nProof. eapply funspec_sub_trans. apply reset_spec_local_sub. unfold fobject_invariant_of_inv.\n do_funspec_sub.\n  rewrite fancyfoo_obj_invariant_fold_unfold' at 1. (*foo_obj_invariant_fold_unfold;*) Intros m.\n  Exists w QQ. destruct w as [[hs c] p]; simpl in *. entailer!.\n + intros. rewrite foo_obj_invariant_fold_unfold', fancyfoo_obj_invariant_fold_unfold'.\n   normalize. Exists mtable. entailer!. unfold fancyfoo_data, foo_data, withspacer; simpl.\n   cancel. (*QQ = field_at color, later funspecs for setC, getC*) admit.\n + rewrite foo_obj_invariant_fold_unfold'. Exists m.\n   entailer!. unfold fancyfoo_data, foo_data, withspacer; simpl.\n   cancel.\nAbort. (*same issue as below: method table needs to be co and contravariant*)\n(* entailment / \"proof-theoretic behavioral subtyping' not suitable\"*)\n\nLemma funspec_sub_reset_foo_fancy: funspec_sub (reset_spec foo_obj_invariant) (freset_spec fancyfoo_obj_invariant).\nProof. do_funspec_sub. simpl in H. inv H. inv H6.\n  destruct w as [[hs c] q]. \n  rewrite fancyfoo_obj_invariant_fold_unfold' at 1. (*foo_obj_invariant_fold_unfold;*) Intros m.\n  simpl in H0, H4.\n  Exists (hs, q). entailer.\n  unfold fancyfoo_data, foo_data, withspacer; simpl. entailer!.\n  unfold fobject_methods. \n  rewrite later_exp'; normalize. rename x into sh.\n  rewrite later_exp'; normalize. rename x into r.\n  rewrite later_exp'; normalize. rename x into t.\n  rewrite later_exp'; normalize. rename x into tR.\n  rewrite later_exp'; normalize. rename x into sC.\n  rewrite later_exp'; normalize. rename x into gC.\n  Exists ((\n     field_at Ews (Tstruct _fancyfoo_object noattr) [StructField _color] (Vint (Int.repr c)) q *\n     (|> (func_ptr' (fsetcolor_spec fancyfoo_obj_invariant) sC *\n          func_ptr' (fgetcolor_spec fancyfoo_obj_invariant) gC))) * \n     ((malloc_token Ews (Tstruct _foo_object noattr) q) -* malloc_token Ews (Tstruct _fancyfoo_object noattr) q)).\n  rewrite later_andp. rewrite ! later_sepcon. Intros.\n  entailer. apply andp_right.\n  + entailer!. intros. rewrite fancyfoo_obj_invariant_fold_unfold'; simpl.\n    Exists m. entailer!. (*\n    sep_apply wand_frame_elim''. cancel.\n(*    eapply derives_trans. apply sepcon_derives. apply now_later. apply derives_refl.*)\n    rewrite  <- ! later_sepcon. \n    apply later_derives. Exists sh r t tR sC gC. entailer!. admit. (*readable_share*)\n    unfold object_methods. admit.\n  + entailer!. cancel. normalize.*)\nAbort.", "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_objectSelfFancy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.29382737609670473}}
{"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 JSON.\n\nSection JSONNorm.\n  Fixpoint normalize_json (d:json) : json :=\n    match d with\n    | jobject rl => jobject (rec_sort (map (fun x => (fst x, normalize_json (snd x))) rl))\n    | jarray l => jarray (map normalize_json l)\n    | _ => d\n    end.\n\n  Inductive json_normalized : json -> Prop :=\n  | jnnull :\n      json_normalized jnull\n  | jnnumber n :\n      json_normalized (jnumber n)\n  | jnbool b :\n      json_normalized (jbool b)\n  | jnstring s :\n      json_normalized (jstring s)\n  | jnarray dl :\n      Forall (fun x => json_normalized x) dl -> json_normalized (jarray dl)\n  | jnobject dl :\n      Forall (fun d => json_normalized (snd d)) dl ->\n      (is_list_sorted ODT_lt_dec (domain dl) = true) ->\n      json_normalized (jobject dl).\n\n  Theorem normalize_normalizes :\n    forall (d:json), json_normalized (normalize_json d).\n  Proof.\n    induction d using jsonInd2; simpl.\n    - apply jnnull.\n    - apply jnnumber.\n    - apply jnbool.\n    - apply jnstring.\n    - apply jnarray.\n      apply Forall_forall; intros.\n      induction c; elim H0; intros.\n      rewrite <- H1.\n      apply (H a); left; reflexivity.\n      assert (forall x:json, In x c -> json_normalized (normalize_json x))\n        by (intros; apply (H x0); right; assumption).\n      specialize (IHc H2 H1).\n      assumption.\n    - apply jnobject.\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 : json),\n                   In (x, y) r -> json_normalized (normalize_json 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 * json => (fst x, normalize_json (snd x))) r)).\n        reflexivity.\n  Qed.\n\n  Theorem normalize_normalized_eq {d}:\n    json_normalized d ->\n    normalize_json d = d.\n  Proof.\n    induction d using jsonInd2; simpl; trivial.\n    - intros.\n      rewrite (@map_eq _ _ normalize_json 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 * json => (fst x, normalize_json (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  Qed.\n\n  Lemma map_normalize_normalized_eq c :\n    Forall (fun x => json_normalized (snd x)) c ->\n    (map\n       (fun x0 : string * json => (fst x0, normalize_json (snd x0)))\n       c) = c.\n  Proof.\n    induction c; simpl; trivial.\n    destruct a; inversion 1; simpl in *; subst.\n    rewrite normalize_normalized_eq; trivial.\n    rewrite IHc; trivial.\n  Qed.\n\n\n  Corollary normalize_idem d :\n    normalize_json (normalize_json d) = normalize_json d.\n  Proof.\n    apply normalize_normalized_eq.\n    apply normalize_normalizes.\n  Qed.\n\n  Corollary normalize_json_eq_normalized {d} :\n    normalize_json d = d -> json_normalized d.\n  Proof.\n    intros.\n    generalize (normalize_normalizes d).\n    congruence.\n  Qed.\n  \n  Theorem normalized_json_dec d : {json_normalized d} + {~ json_normalized d}.\n  Proof.\n    destruct (normalize_json d == d); unfold equiv, complement in *.\n    - left. apply normalize_json_eq_normalized; trivial.\n    - right. intro dn; elim c. apply normalize_normalized_eq; trivial.\n  Defined.\n\n  Lemma json_normalized_jarray a l :\n    (json_normalized a /\\ json_normalized (jarray l)) <->\n    json_normalized (jarray (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 json_normalized_rec_sort_app l1 l2 :\n    json_normalized (jobject l1) ->\n    json_normalized (jobject l2) ->\n    json_normalized (jobject (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 json_normalized_rec_concat_sort l1 l2 :\n    json_normalized (jobject l1) ->\n    json_normalized (jobject l2) ->\n    json_normalized (jobject (rec_concat_sort l1 l2)).\n  Proof.\n    apply json_normalized_rec_sort_app.\n  Qed.\n\n  Lemma json_normalized_jarray_in x l :\n    In x l ->\n    json_normalized (jarray l) ->\n    json_normalized x.\n  Proof.\n    inversion 2; subst.\n    rewrite Forall_forall in H2.\n    eauto.\n  Qed.\n\n  Lemma jnobject_nil : json_normalized (jobject nil).\n  Proof.\n    econstructor; trivial.\n  Qed.\n\n  Lemma jnobject_sort_content c :\n    Forall (fun d : string * json => json_normalized (snd d)) c ->\n    Forall (fun d : string * json => json_normalized (snd d)) (rec_sort c).\n  Proof.\n    intros F.\n    apply Forall_sorted; trivial.\n  Qed.\n\n  Lemma jnobject_sort c :\n    Forall (fun d : string * json => json_normalized (snd d)) c ->\n    json_normalized (jobject (rec_sort c)).\n  Proof.\n    intros F; econstructor; trivial with qcert.\n    apply Forall_sorted; trivial.\n  Qed.\n\n  Lemma json_normalized_jarray_Forall l :\n    json_normalized (jarray l) <-> Forall json_normalized l.\n  Proof.\n    split; intros H.\n    - invcs H; trivial.\n    - constructor; trivial.\n  Qed.\n  \nEnd JSONNorm.\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/JSON/Model/JSONNorm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.2938273760967047}}
{"text": "Require Import\n  Hask.Control.Monad\n  Hask.Data.Maybe\n  Coq.Lists.List.\n\nGeneralizable All Variables.\nSet Primitive Projections.\nSet Universe Polymorphism.\nUnset Transparent Obligations.\n\nImport ListNotations.\n\nDefinition Effect := (Type -> Type) -> Type.\n\nInductive Effects (m : Type -> Type) : list Effect -> Type :=\n  | NilE : Effects m []\n  | ConsE effects : forall effect : Effect,\n      effect m -> Effects m effects -> Effects m (effect :: effects).\n\nArguments ConsE : default implicits.\n\nDefinition combine `(e : effect m) `(xs : Effects m effects) :\n  Effects m (effect :: effects) := ConsE _ e xs.\n\nInfix \".:\" := combine (at level 48, right associativity).\n\nClass Handles (fs : list Effect) (effect : Effect) := {\n  getEffect : forall m, Effects m fs -> effect m\n}.\n\n#[export]\nInstance Handles_hd {fs : list Effect}  {f : Effect} :\n  Handles (f :: fs) f.\nProof.\n  constructor; intros.\n  inversion X.\n  exact X0.\nDefined.\n\n#[export]\nInstance Handles_tl `{_ : Handles fs f} : Handles (x :: fs) f.\nProof.\n  constructor; intros.\n  inversion H.\n  apply getEffect0.\n  inversion X.\n  exact X1.\nDefined.\n\nAxiom IO : Type -> Type.\nAxiom IO_Functor : Functor IO.\nAxiom IO_Applicative : Applicative IO.\nAxiom IO_Monad : Monad IO.\n\nDefinition Kleisli m (A B : Type) := A -> m B.\n\nArguments Kleisli m A B.\n\nDefinition TFree `(xs : list Effect) a :=\n  Kleisli IO (Effects IO xs) a.\n\nDefinition Eff := TFree.\n\nArguments Eff xs a.\n\nDefinition liftF `{Handles effects effect}\n  `(getOp : effect IO -> IO a) : Eff effects a :=\n  fun effects => getOp (getEffect IO effects).\n\nDefinition interpret `(interpreter : Effects IO effects)\n  `(program : Eff effects a) : IO a := program interpreter.\n\n#[export]\nInstance Impl_Functor {A} : Functor (fun B => A -> B) := {\n  fmap := fun A B f run => fun xs => f (run xs)\n}.\n\n#[export]\nInstance Impl_Applicative {A} : Applicative (fun B => A -> B) := {\n  pure := fun _ x => fun xs => x;\n  ap   := fun A B runf runx => fun xs => runf xs (runx xs)\n}.\n\n#[export]\nInstance Impl_Monad {A} : Monad (fun B => A -> B) := {\n  join := fun A run => fun xs => run xs xs\n}.\n\n#[export]\nInstance Kleisli_Functor `{Monad m} {A} : Functor (Kleisli m A) :=\n  Compose_Functor.\n\n#[export]\nInstance Kleisli_Applicative `{Applicative m} : Applicative (Kleisli m A) :=\n  fun _ => @Compose_Applicative _ _ Impl_Applicative _.\n\n#[export]\nProgram Instance Kleisli_Monad_Distributes `{Monad m} {A} :\n  @Monad_Distributes _ (@Impl_Monad A) m _ := {\n  prod := _\n}.\nObligation 1.\n  exact (join (fmap (fun k => k X0) X)).\nDefined.\n\n(* Instance Kleisli_Monad `{Monad m} {A} : Monad (Kleisli m A) := Compose_Monad. *)\n\n#[export]\nInstance TFree_Functor `(xs : list Effect) : Functor (TFree xs) := {\n  fmap := fun A B f run => fun xs => fmap f (run xs)\n}.\n\n#[export]\nInstance TFree_Applicative `(xs : list Effect) : Applicative (TFree xs) := {\n  pure := fun _ x => fun xs => pure x;\n  ap   := fun A B runf runx => fun xs => runf xs <*> runx xs\n}.\n\n#[export]\nInstance TFree_Monad `(xs : list Effect) : Monad (TFree xs) := {\n  join := fun A run => fun xs => run xs >>= fun f => f xs\n}.\n\nRecord Abortive (m : Type -> Type) := {\n  abortE : m unit\n}.\n\nDefinition abort `{Handles r Abortive} : Eff r unit :=\n  liftF abortE.\n\nRecord Reader (e : Type) (m : Type -> Type) := {\n  askE : m e\n}.\n\nDefinition ask `{Handles r (Reader e)} : Eff r e :=\n  liftF (askE e).\n\nRequire Import Arith.\n\nSet Printing Universes.\n\nDefinition example1 `{Handles r (Reader nat)} `{Handles r Abortive} :\n  Eff r nat :=\n  (fun x y => y + 15) <$> abort <*> ask.\n\nDefinition maybeInterpreter : Effects Maybe [Reader nat; Abortive] :=\n  combine {| askE   := Just 10 |} (combine {| abortE := Nothing |} (NilE _)).\n\nDefinition run {a} : Eff [Reader nat; Abortive] a -> Maybe a :=\n  interpret maybeInterpreter.\n\nExample run_example1 : run example1 = Nothing.\nProof. reflexivity. Qed.\n\nDefinition example2 `{Handles r (Reader nat)} : Eff r nat :=\n  fmap (plus 15) ask.\n\nExample run_example2 : run example2 = Just 25.\nProof. reflexivity. Qed.\n\n(*\nDefinition example3 `{Handles r (Reader nat)} `{Handles r Abortive} :\n  Eff r nat :=\n  v <- ask;\n  if leb v 15\n  then abort ;; pure 0\n  else pure (v+1).\n\nExample run_example3 : run example3 = None.\nProof. reflexivity. Qed.\n*)\n", "meta": {"author": "jwiegley", "repo": "coq-haskell", "sha": "56a185af5767177d410113a03bd765135e07c9ca", "save_path": "github-repos/coq/jwiegley-coq-haskell", "path": "github-repos/coq/jwiegley-coq-haskell/coq-haskell-56a185af5767177d410113a03bd765135e07c9ca/src/Control/Monad/EffPlain.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.29382736856332925}}
{"text": "Require Import Lia ZArith List.\nRequire Import Cdcl.Itauto.\nOpen Scope Z_scope.\n\nUnset Lia Cache.\nSet Itauto Theory Time.\n\nLtac mp :=  repeat match goal with\n         | H :?A , H1 : ?A -> ?B |- _ => specialize (H1 H)\n         end.\n\nLtac sub :=  repeat match goal with\n                    | H :?A -> False , H1 : ?A -> ?B |- _ => clear H1\n                    end.\n\n\nGoal  forall (word : Type) (left right : word) (xs : list word)\n    (r8 : Z) (v : nat) (x : list word) (x1 x2 : word)\n    (r7 q r r6 q0 r0 r2 : Z) (w2z : word -> Z)\n    (width q1 r1 q2 r3 q3 r4 r5 q4 q5 q6 q7 q8 : Z),\n    r8 = 8 * Z.of_nat (Datatypes.length xs) ->\n  r7 = 8 * Z.of_nat (Datatypes.length x) ->\n  Datatypes.length x = v ->\n  r7 <> 0 ->\n  (2 ^ r6 <> 0 -> r7 = 2 ^ r6 * q + r) ->\n  (0 < 2 ^ r6 -> 0 <= r < 2 ^ r6) ->\n  (2 ^ r6 < 0 -> 2 ^ r6 < r <= 0) ->\n  (2 ^ r6 = 0 -> q = 0) ->\n  (2 ^ r6 = 0 -> r = 0) ->\n  (2 ^ width <> 0 -> r2 - w2z x1 = 2 ^ width * q0 + r0) ->\n  (0 < 2 ^ width -> 0 <= r0 < 2 ^ width) ->\n  (2 ^ width < 0 -> 2 ^ width < r0 <= 0) ->\n  (2 ^ width = 0 -> q0 = 0) ->\n  (2 ^ width = 0 -> r0 = 0) ->\n  (2 ^ width <> 0 -> 8 = 2 ^ width * q1 + r1) ->\n  (0 < 2 ^ width -> 0 <= r1 < 2 ^ width) ->\n  (2 ^ width < 0 -> 2 ^ width < r1 <= 0) ->\n  (2 ^ width = 0 -> q1 = 0) ->\n  (2 ^ width = 0 -> r1 = 0) ->\n  (2 ^ width <> 0 -> w2z x1 + r3 = 2 ^ width * q2 + r2) ->\n  (0 < 2 ^ width -> 0 <= r2 < 2 ^ width) ->\n  (2 ^ width < 0 -> 2 ^ width < r2 <= 0) ->\n  (2 ^ width = 0 -> q2 = 0) ->\n  (2 ^ width = 0 -> r2 = 0) ->\n  (2 ^ width <> 0 -> r4 * 2 ^ r5 = 2 ^ width * q3 + r3) ->\n  (0 < 2 ^ width -> 0 <= r3 < 2 ^ width) ->\n  (2 ^ width < 0 -> 2 ^ width < r3 <= 0) ->\n  (2 ^ width = 0 -> q3 = 0) ->\n  (2 ^ width = 0 -> r3 = 0) ->\n  (2 ^ width <> 0 -> q = 2 ^ width * q4 + r4) ->\n  (0 < 2 ^ width -> 0 <= r4 < 2 ^ width) ->\n  (2 ^ width < 0 -> 2 ^ width < r4 <= 0) ->\n  (2 ^ width = 0 -> q4 = 0) ->\n  (2 ^ width = 0 -> r4 = 0) ->\n  (2 ^ width <> 0 -> 3 = 2 ^ width * q5 + r5) ->\n  (0 < 2 ^ width -> 0 <= r5 < 2 ^ width) ->\n  (2 ^ width < 0 -> 2 ^ width < r5 <= 0) ->\n  (2 ^ width = 0 -> q5 = 0) ->\n  (2 ^ width = 0 -> r5 = 0) ->\n  (2 ^ width <> 0 -> 4 = 2 ^ width * q6 + r6) ->\n  (0 < 2 ^ width -> 0 <= r6 < 2 ^ width) ->\n  (2 ^ width < 0 -> 2 ^ width < r6 <= 0) ->\n  (2 ^ width = 0 -> q6 = 0) ->\n  (2 ^ width = 0 -> r6 = 0) ->\n  (2 ^ width <> 0 -> w2z x2 - w2z x1 = 2 ^ width * q7 + r7) ->\n  (0 < 2 ^ width -> 0 <= r7 < 2 ^ width) ->\n  (2 ^ width < 0 -> 2 ^ width < r7 <= 0) ->\n  (2 ^ width = 0 -> q7 = 0) ->\n  (2 ^ width = 0 -> r7 = 0) ->\n  (2 ^ width <> 0 -> w2z right - w2z left = 2 ^ width * q8 + r8) ->\n  (0 < 2 ^ width -> 0 <= r8 < 2 ^ width) ->\n  (2 ^ width < 0 -> 2 ^ width < r8 <= 0) ->\n  (2 ^ width = 0 -> q8 = 0) ->\n  (2 ^ width = 0 -> r8 = 0) ->\n  r0 < r1 * Z.of_nat (Datatypes.length x).\nProof.\n  intros.\n  Time Fail itauto lia.\n  (* Manual decomposition *)\n  assert (CASE : 2 ^ width < 0 \\/ 2^width = 0 \\/ 0 < 2^width) by lia.\n  destruct CASE as [C1 | [C1 | C1]].\n  - assert (NZ : 2 ^ width <> 0) by (clear - C1 ; lia).\n    mp.\n    unfold not in NZ.\n    sub.\n    lia.\n  - mp.\n    assert (0 < 2 ^ width -> False) by (clear - C1; lia).\n    assert (2 ^ width <> 0 -> False) by (clear - C1; lia).\n    assert (0 < 2 ^ width  -> False) by (clear - C1; lia).\n    assert (2 ^ width < 0 -> False) by (clear - C1; lia).\n    sub.\n    lia.\n  -\n    assert (2 ^ width = 0 -> False) by (clear - C1; lia).\n    assert (2 ^ width <> 0) by (clear - C1; lia).\n    assert (2 ^ width < 0 -> False) by (clear - C1; lia).\n    mp.  sub.\n    Fail lia.\nAbort.\n", "meta": {"author": "proux01", "repo": "itauto", "sha": "40b66e957de9a7ca075133345cbc9af4f2eadb93", "save_path": "github-repos/coq/proux01-itauto", "path": "github-repos/coq/proux01-itauto/itauto-40b66e957de9a7ca075133345cbc9af4f2eadb93/issues/issue_16.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.29380696474090334}}
{"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_destroy1_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_int64 _map_addr;\n      when' _t'1, adt == data_destroy_spec (_g_rd_base, _g_rd_ofst) (VZ64 _map_addr) 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_destroy1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2937560023106945}}
{"text": "Require Import List.\n\nSet Implicit Arguments.\n\nDefinition err : Type := unit. \n\nInductive res (A: Type) : Type :=\n| OK: A -> res A\n| Error: err -> res A. \n\nArguments Error [A].\n\nSet Printing Universes.\n\nSection FOO.\n\nInductive ftyp : Type :=\n  | Funit : ftyp \n  | Ffun : list ftyp -> ftyp \n  | Fref : area -> ftyp\nwith area : Type := \n  | Stored : ftyp -> area        \n.\n\nPrint ftyp.\n(* yields:\nInductive ftyp : Type (* Top.27429 *) :=\n    Funit : ftyp | Ffun : list ftyp -> ftyp | Fref : area -> ftyp\n  with area : Type (* Set *) :=  Stored : ftyp -> area\n*)\n\nFixpoint tc_wf_type (ftype: ftyp) {struct ftype}: res unit :=\n  match ftype with\n    | Funit => OK tt\n    | Ffun args => \n       ((fix tc_wf_types (ftypes: list ftyp){struct ftypes}: res unit :=\n           match ftypes with\n             | nil => OK tt\n             | t::ts =>\n                 match tc_wf_type t with\n                   | OK tt => tc_wf_types ts\n                   | Error m => Error m \n                 end \n           end) args) \n     | Fref a => tc_wf_area a\n   end\nwith tc_wf_area (ar:area): res unit :=\n  match ar with\n    | Stored c => tc_wf_type c\n  end.\n\nEnd FOO.\n\nPrint ftyp.\n(* yields:\nInductive ftyp : Type (* Top.27465 *) :=\n    Funit : ftyp | Ffun : list ftyp -> ftyp | Fref : area -> ftyp\n  with area : Set :=  Stored : ftyp -> area\n*)\n\nFixpoint tc_wf_type' (ftype: ftyp) {struct ftype}: res unit :=\n  match ftype with\n    | Funit => OK tt\n    | Ffun args => \n       ((fix tc_wf_types (ftypes: list ftyp){struct ftypes}: res unit :=\n           match ftypes with\n             | nil => OK tt\n             | t::ts =>\n                 match tc_wf_type' t with\n                   | OK tt => tc_wf_types ts\n                   | Error m => Error m \n                 end \n           end) args) \n     | Fref a => tc_wf_area' a\n   end\nwith tc_wf_area' (ar:area): res unit :=\n  match ar with\n    | Stored c => tc_wf_type' c\n  end.\n\n(* yields:\nError:\nIncorrect elimination of \"ar\" in the inductive type \"area\":\nthe return type has sort \"Type (* max(Set, Top.27424) *)\" while it\nshould be \"Prop\" or \"Set\".\nElimination of an inductive object of sort Set\nis not allowed on a predicate in sort Type\nbecause strong elimination on non-small inductive types leads to paradoxes.\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/2584.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.2937560023106945}}
{"text": "From mathcomp Require Import ssreflect ssrbool ssrnat eqtype ssrfun seq path.\nFrom Coq Require Import Eqdep Relation_Operators.\nFrom pcm Require Import axioms pred prelude ordtype finmap pcm unionmap heap.\nFrom DiSeL Require Import Freshness State EqTypeX DepMaps Protocols.\nFrom DiSeL Require Import Worlds NetworkSem Rely Actions Injection Process.\nFrom DiSeL Require Import Always HoareTriples InferenceRules.\nObligation Tactic := Tactics.program_simpl.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nModule TPCProtocol.\n\nModule States.\n\nDefinition data := seq nid.\n\n(* Coordinator states *)\nInductive CState :=\n(* Waiting at a current stage *)\n| CInit\n(* Sent prepare message to some nodes at a current stage *)\n| CSentPrep of data & seq nid\n(* Received results from some nodes, bool for commit/abort *)\n| CWaitPrepResponse of data & seq (nid * bool)\n(* Send commit/abort requests *)\n| CSentCommit of data & seq nid\n| CSentAbort of data & seq nid\n(* Waiting for acks on Commit with some already collected *)\n| CWaitAckCommit of data & seq nid\n(* Waiting for acks on Abort with some already collected *)\n| CWaitAckAbort of data & seq nid.\n\nInductive PState :=\n| PInit\n| PGotRequest of data\n| PRespondedYes of data | PRespondedNo of data\n| PCommitted of data | PAborted of data.\n\n(* Pointers to the state and log components *)\nDefinition st := ptr_nat 1.\nDefinition log := ptr_nat 2.\n\n(* Type of data to perform a transaction over is encoded via seq nat *)\nDefinition Log := seq (bool * (seq nat)).\n\n(* Pairing with the current stage of type nat *)\nDefinition CStateT := (nat * CState)%type.\nDefinition PStateT := (nat * PState)%type.\n\n\nEnd States.\n\nImport States.\n\nSection TPCProtocol.\n\n(* Coordinator node *)\nVariable cn : nid.\n(* Participant nodes *)\nVariable pts : seq nid.\n\n(* Other nodes *)\nVariable others : seq nid.\n\nHypothesis Hnin : cn \\notin pts.\nHypothesis Puniq : uniq pts.\n\n(* Local state contains the C/P state and the log *)\n\n(* TODO: think of the open design with the possibility to refine the state *)\nDefinition localCoh (n : nid) : Pred heap :=\n  [Pred h | valid h /\\\n   if n == cn\n   then exists (s : CStateT) (l : Log),\n       h = st :-> s \\+ log :-> l\n   else if n \\in pts\n   then exists (s : PStateT) (l : Log),\n       h = st :-> s \\+ log :-> l\n   else log \\notin dom h].\n\n(* Involved nodes *)\nDefinition nodes := [:: cn] ++ pts ++ others.\n\nDefinition prep_req : nat := 0.\nDefinition prep_yes : nat := 1.\nDefinition prep_no : nat := 2.\nDefinition commit_req : nat := 3.\nDefinition abort_req : nat := 4.\nDefinition commit_ack : nat := 5.\nDefinition abort_ack : nat := 6.\n\n(* Interaction with the clients *)\nDefinition eval_req : nat := 7.\nDefinition eval_resp : nat := 8.\n\nDefinition ttag := nat.\nDefinition payload := seq nat.\n\nDefinition tags : seq ttag :=\n  [:: prep_req;\n     prep_yes;\n     prep_no;\n     commit_req;\n     abort_req;\n     commit_ack;\n     abort_ack;\n     eval_req;\n     eval_resp].\n\nDefinition tagFromParticipant (t : nat) : bool :=\n  (t \\in [:: prep_yes; prep_no; commit_ack; abort_ack]).\n\n(* Messages from participants only keep current stage/era number y *)\nDefinition msgFromParticipant (tms : TaggedMessage) (y : nat) : bool :=\n    tagFromParticipant (tag tms)\n    && (tms_cont tms == [:: y]).\n\nDefinition tagFromCoordinator (t : nat) : bool :=\n  (t \\in [:: prep_req; commit_req; abort_req]).\n\n(* Messages from coordinator contain stuff to be committed *)\nDefinition msgFromCoordinator (tms : TaggedMessage) (y : nat) : Prop :=\n  let: body := tms_cont tms in\n  if tag tms == prep_req\n  then exists data, body = y :: data\n  else if tag tms == commit_req\n       then body = [:: y]\n       else if tag tms == abort_req\n            then body = [:: y]\n            else False.\n\nDefinition cohMsg (ms: msg TaggedMessage) (y : nat) : Prop :=\n  if from ms == cn\n  then to ms \\in pts /\\ msgFromCoordinator (content ms) y\n  else if from ms \\in pts\n       then to ms == cn /\\ msgFromParticipant (content ms) y\n       else True.\n\nDefinition soupCoh : Pred soup :=\n  [Pred s | valid s /\\\n            forall m ms, find m s = Some ms -> exists y, cohMsg ms y].\n\nDefinition tpc_coh d : Prop :=\n  let: dl := dstate d in\n  let: ds := dsoup d in\n  [/\\ soupCoh ds, dom dl =i nodes,\n   valid dl &\n   forall n, n \\in nodes -> localCoh n (getLocal n d)].\n\n(* Axioms of the coherence predicate *)\nLemma l1 d: tpc_coh d -> valid (dstate d).\nProof. by case. Qed.\n\nLemma l2 d: tpc_coh d -> valid (dsoup d).\nProof. by case; case. Qed.\n\nLemma l3 d: tpc_coh d -> dom (dstate d) =i nodes.\nProof. by case. Qed.\n\n(* Wrapping up the coherence predicate *)\nDefinition TPCCoh := CohPred (CohPredMixin l1 l2 l3).\n\n\nSection TransitionLemmas.\n\nLemma send_soupCoh d m :\n    soupCoh (dsoup d) -> (exists y, cohMsg m y) -> soupCoh (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\nLemma trans_updDom this d s :\n  this \\in nodes -> TPCCoh 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\nLemma consume_coh d m : TPCCoh d -> soupCoh (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 this_not_pts this : this \\in pts -> this == cn = false.\nProof.\nby move=>H; apply/negP=>/eqP=>Z; subst this; rewrite H in (Hnin).\nQed.\n\nLemma this_not_pts' this : this == cn -> this \\notin pts.\nProof. by move/eqP->; apply: Hnin. Qed.\n\nEnd TransitionLemmas.\n\n\n(****************************************************)\n(********* Getter lemmas for local state ************)\n(****************************************************)\n\nLemma locCn n d (C : TPCCoh d):\n  n \\in nodes ->\n  valid (getLocal n d) /\\\n  if n == cn\n  then exists (s : CStateT) (l : Log),\n      getLocal n d = st :-> s \\+ log :-> l\n  else if n \\in pts\n       then exists (s : PStateT) (l : Log),\n           getLocal n d = st :-> s \\+ log :-> l\n       else log \\notin dom (getLocal n d).\nProof.\nby case: C=>_ _ _ /(_ n)G; move: G; rewrite /localCoh/=.\nQed.\n\nLemma cohStC d (C : TPCCoh d) s:\n  find st (getLocal cn d) = Some s ->\n  dyn_tp s = CStateT.\nProof.\nhave pf: cn \\in nodes by rewrite inE eqxx.\nmove: (locCn C pf); rewrite eqxx; move =>[V][s'][l']Z; rewrite Z in V *.\nrewrite findPtUn //.\nby case=><-/=.\nQed.\n\nLemma cohStP n d (C : TPCCoh d) (H : n \\in pts) s:\n  find st (getLocal n d) = Some s ->\n  dyn_tp s = PStateT.\nProof.\nhave pf: n \\in nodes by rewrite inE/=orbC mem_cat H.\nmove: (locCn C pf); rewrite H=>[[V]].\ncase E: (n == cn); last first.\n- move=>[s'][l']Z; rewrite Z in V *.\n  by rewrite findUnL//; rewrite domPt inE/= findPt/=; case=><-.\nby move/eqP: E=>E; subst n; move: Hnin; rewrite H.\nQed.\n\nDefinition getStC d (C : TPCCoh d) : CStateT :=\n  match find st (getLocal cn d) as f return _ = f -> _ with\n    Some v => fun epf => icast (sym_eq (cohStC C epf)) (dyn_val v)\n  | _ => fun epf => (0, CInit)\n  end (erefl _).\n\nLemma getStC_K d (C : TPCCoh d) m (l : Log):\n  getLocal cn d = st :-> m \\+ log :-> l -> getStC C = m.\nProof.\nmove=>E; rewrite /getStC/=.\nhave pf : cn \\in nodes by rewrite inE eqxx.\nhave V: valid (getLocal cn d) by case: (locCn C pf).\nmove: (cohStC C); rewrite !E=>/= H.\nby apply: eqc.\nQed.\n\nProgram Definition getStP n d (C : TPCCoh d) (pf : n \\in nodes) : PStateT.\nProof.\ncase X: (n \\in pts); last by exact: (0, PInit).\nexact: (match find st (getLocal n d) as f return _ = f -> _ with\n          Some v => fun epf => icast (sym_eq (cohStP C X epf)) (dyn_val v)\n        | _ => fun epf => (0, PInit)\n        end (erefl _)).\nDefined.\n\nLemma getStP_K n d (C : TPCCoh d) (pf : n \\in nodes) m (l : Log):\n  n \\in pts -> getLocal n d = st :-> m \\+ log :-> l -> getStP C pf = m.\nProof.\nmove=>X E; rewrite /getStP/=.\nhave V: valid (getLocal n d) by case: (locCn C pf).\nrewrite E in V.\nmove: (cohStP C); case B: (n \\in pts)=>//=; last by rewrite X in B.\nmove=>H; move: (H (erefl true))=>{H}; rewrite E=>/=H.\nby apply: eqc.\nQed.\n\n(* Log getter *)\n\nLemma cohStL d (C : TPCCoh d) n (H : n \\in nodes) l:\n  find log (getLocal n d) = Some l -> dyn_tp l = Log.\nProof.\nmove: (locCn C H)=>[V].\ncase B: (n == cn)=>/=.\n- move=>[s'][l']Z; rewrite Z in V *;\n  by rewrite joinC in V *; rewrite findPtUn //; case=><-/=.\nrewrite inE in H; case/orP: H; first by rewrite B.\nrewrite/= mem_cat; case X: (n \\in pts)=>/=_.\n- move=>[s'][l']Z; rewrite Z in V *;\n  by rewrite joinC in V *; rewrite findPtUn //; case=><-/=.\nby move=>H; move/find_some=>Y; rewrite Y in H.\nQed.\n\nDefinition getStL n d (C : TPCCoh d) (pf : n \\in nodes) : Log :=\n  match find log (getLocal n d) as f return _ = f -> _ with\n    Some v => fun epf => icast (sym_eq (cohStL C pf epf)) (dyn_val v)\n  | _ => fun epf => [::]\n  end (erefl _).\n\n(* TODO: get rid of duplication *)\nLemma getStL_Kc n d (C : TPCCoh d) (pf : n \\in nodes) (m : CStateT) (l : Log):\n  getLocal n d = st :-> m \\+ log :-> l -> getStL C pf = l.\nProof.\nmove=>E; rewrite /getStL/=.\nhave V: valid (getLocal n d) by case: (locCn C pf).\nby rewrite E in V; move: (cohStL C pf); rewrite !E/==>H; apply: eqc.\nQed.\n\nLemma getStL_Kp n d (C : TPCCoh d) (pf : n \\in nodes) (m : PStateT) (l : Log):\n  getLocal n d = st :-> m \\+ log :-> l -> getStL C pf = l.\nProof.\nmove=>E; rewrite /getStL/=.\nhave V: valid (getLocal n d) by case: (locCn C pf).\nby rewrite E in V; move: (cohStL C pf); rewrite !E/==>H; apply: eqc.\nQed.\n\nLemma cn_in : cn \\in nodes.\nProof. by rewrite mem_cat inE eqxx. Qed.\n\nLemma pts_in n: n \\in pts -> n \\in nodes.\nProof. by rewrite /nodes !mem_cat orbC=>->. Qed.\n\nLemma cn_pts_in this : this \\in cn :: pts -> this \\in nodes.\nProof. by rewrite /nodes catA/= -cat_cons mem_cat=>->. Qed.\n\nLemma getStCE l i j pf pf' :\n  getLocal cn (getStatelet j l) = getLocal cn (getStatelet i l) ->\n  @getStC (getStatelet j l) pf' = @getStC (getStatelet i l) pf.\nProof.\ncase: {-1}(pf)=>_ _ _/(_ _ cn_in)[]V; rewrite eqxx=>[[cs]][lg]E.\nby rewrite (getStC_K _ E); rewrite E=>E'; rewrite (getStC_K _ E').\nQed.\n\nLemma getStPE l n i j C C' pf :\n  n \\in pts ->\n  getLocal n (getStatelet j l) = getLocal n (getStatelet i l) ->\n  @getStP n (getStatelet j l) C' pf = @getStP n (getStatelet i l) C pf.\nProof.\nmove=>I; case: {-1}(C)=>_ _ _/(_ _ pf)[]V; rewrite I.\ncase: ifP; first by move/eqP=>Z; subst n; move: (Hnin); rewrite I.\nmove=>_[ps][lg] E.\nby rewrite (getStP_K _ pf I E);rewrite E=>E'; rewrite (getStP_K _ pf I E').\nQed.\n\nLemma getStLE l this i j pf pf' :\n  forall (N : this \\in cn :: pts),\n  getLocal this (getStatelet j l) = getLocal this (getStatelet i l) ->\n  @getStL _ (getStatelet j l) pf' (cn_pts_in N) =\n  @getStL _ (getStatelet i l) pf (cn_pts_in N).\nProof.\nmove=>N; case: {-1}(pf)=>_ _ _/(_ _ (cn_pts_in N))[]V.\nmove: (N)=>N'. rewrite inE in N; case/orP: N.\n- move/eqP=>Z; subst this; rewrite eqxx=>[[cs]][lg]E.\n  rewrite (@getStL_Kc _ _ pf (cn_pts_in N') cs lg)//.\n  by rewrite E=>E'; rewrite (@getStL_Kc _ _ pf' (cn_pts_in N') cs lg)//.\nmove=>Z; rewrite (this_not_pts Z) Z=>[[cs]][lg]E.\nrewrite (@getStL_Kp _ _ pf (cn_pts_in N') cs lg)//.\nby rewrite E=>E'; rewrite (@getStL_Kp _ _ pf' (cn_pts_in N') cs lg)//.\nQed.\n\n\n(****************************************************************)\n(****************************************************************)\n\n(*** Per-node state transition systems ***)\n\n(* Coordinator transitions *)\n\n(* Changes in the Coordinator state/log triggered upon send *)\nDefinition cstep_send (cs: CStateT) (to : nid) (d : data) (l : Log) :\n  CStateT * Log :=\n  (* Only accept good destinations *)\n  if to \\in pts then\n    let: (e, s) := cs in\n    match s with\n    | CInit =>\n      if pts == [:: to]\n      then (e, CWaitPrepResponse d [::], l)\n      else (e, CSentPrep d [:: to], l)\n    (* Sending pre-messages *)\n    | CSentPrep d' tos =>\n      (* Do not duplicate prepare-requests *)\n      if perm_eq (to :: tos) pts\n      (* If all sent, switch to the receiving state *)\n      then (e, CWaitPrepResponse d' [::], l)\n      else (e, CSentPrep d' (to :: tos), l)\n    | CWaitPrepResponse d' res =>\n      (* Switch into sending commit or abort-messages mode *)\n      if (perm_eq (map fst res) pts)\n      then if all (fun r => r) (map snd res)\n           then if pts == [:: to]\n                then (e, CWaitAckCommit d' [::], l)\n                else (e, CSentCommit d' [:: to], l)\n           else if pts == [:: to]\n                then (e, CWaitAckAbort d' [::], l)\n                else (e, CSentAbort  d' [:: to], l)\n      else (cs, l)\n    | CSentCommit d' tos =>\n      (* Sending commit messages *)\n      if perm_eq (to :: tos) pts\n      then (e, CWaitAckCommit d' [::], l)\n      else (e, CSentCommit d' (to :: tos), l)\n    | CSentAbort d' tos =>\n      if perm_eq (to :: tos) pts\n      then (e, CWaitAckAbort d' [::], l)\n      else (e, CSentAbort d' (to :: tos), l)\n    | _ => (cs, l)\n    end\n  else (cs, l).\n\n\nDefinition c_matches_tag s mtag : bool :=\n  match  s with\n  | CWaitPrepResponse _ _ => (mtag == prep_yes) || (mtag == prep_no)\n  | CWaitAckCommit _ _ => mtag == commit_ack\n  | CWaitAckAbort _ _ => mtag == abort_ack\n  | _ => false\n  end.\n\n\n(* Changes in the Coordinator state/log triggered upon receive *)\nDefinition cstep_recv' (cs : CStateT) (from : nid) (mtag : ttag)\n           (mbody : payload) (l : Log) : CStateT * Log  :=\n  let: (e, s) := cs in\n  match s with\n  | CWaitPrepResponse d' res =>\n    (* All responses already collected or\n       already received from this participant  *)\n    if (from \\in (map fst res))\n    then (cs, l)\n    (* Save result *)\n    else (e, CWaitPrepResponse d' ((from, mtag == prep_yes) :: res), l)\n  | CWaitAckCommit d' res =>\n    if from \\in res then (cs, l)\n    else if (perm_eq (from :: res) pts)\n         then ((e.+1, CInit), rcons l (true, d'))\n         else (e, CWaitAckCommit d' (from :: res), l)\n  | CWaitAckAbort d' res =>\n    if from \\in res then (cs, l)\n    else if (perm_eq (from :: res) pts)\n         then ((e.+1, CInit), rcons l (false, d'))\n         else (e, CWaitAckAbort d' (from :: res), l)\n  | _ => (cs, l)\n  end.\n\n\nDefinition cstep_recv (cs: CStateT) (from : nid) (mtag : ttag)\n           (mbody : payload) (l : Log) : CStateT * Log  :=\n  if (from \\notin pts) then (cs, l)\n  else let: (e, s) := cs in\n    (* Ignore messages from irrelevant rounds *)\n    if (head 0 mbody != e) then (cs, l) else\n      cstep_recv' cs from mtag mbody l\n.\n\n(*\n\nThere should be 3 send-transitions for the coordinator:\n\n- send-prepare\n- send-commit\n- send-abort\n\nThere should be 4 receive-transitions for the coordinator:\n\n- receive-prepare-yes\n- receive-prepare-no\n- receive-ack-commit\n- receive-ack-abort\n*)\n\n\nSection CoordinatorGenericSendTransitions.\n\nNotation coh := TPCCoh.\n\nDefinition HCn this to := (this == cn /\\ to \\in pts).\nDefinition mkLocal {T} (sl : T * Log) := st :-> sl.1 \\+ log :-> sl.2.\n\nVariable stag : ttag.\n\n(* Precondition -- this is the way one can define multiple send-transitions *)\nVariable prec : CStateT -> nid -> payload -> Prop.\n\n(* Making sure that the precondition is legit *)\nHypothesis cn_prec_safe :\n  forall this to s m,\n    HCn this to -> prec s to m -> cohMsg (Msg (TMsg stag m) this to true) s.1.\n\nDefinition cn_safe (this n : nid)\n           (d : dstatelet) (msg : data) :=\n  HCn this n /\\\n  exists (C : coh d), prec (getStC C) n msg.\n\nLemma cn_safe_coh this to d m : cn_safe this to d m -> coh d.\nProof. by case=>_[]. Qed.\n\nLemma cn_this_in this to : HCn this to -> this \\in nodes.\nProof. by case=>/eqP->; rewrite inE eqxx. Qed.\n\nLemma cn_to_in this to : HCn this to -> to \\in nodes.\nProof. by case=>_; rewrite /nodes inE/= mem_cat orbC=>->. Qed.\n\nLemma cn_safe_in this to d m : cn_safe this to d m ->\n                                  this \\in nodes /\\ to \\in nodes.\nProof.\nby case=>[]=>G _; move/cn_to_in: (G)->; case: G=>/eqP-> _; rewrite inE eqxx.\nQed.\n\nDefinition cn_step (this to : nid) (d : dstatelet)\n           (msg : seq nat)\n           (pf : cn_safe this to d msg) :=\n  let C := cn_safe_coh pf in\n  let s := getStC C in\n  let l := getStL C (cn_this_in (proj1 pf)) in\n  Some (mkLocal (cstep_send s to (behead msg) l)).\n\nLemma cn_step_coh : s_step_coh_t coh stag cn_step.\nProof.\nmove=>this to d msg pf h[]->{h}.\nhave C : (coh d) by case: pf=>?[].\nhave E: this = cn by case: pf=>[][]/eqP.\nsplit=>/=.\n- apply: send_soupCoh; first by case:(cn_safe_coh pf).\n  exists (getStC (cn_safe_coh pf)).1.\n  case: (pf)=>H[C']P/=; move: (conj H _)=>pf'.\n  by move: (cn_prec_safe H P); rewrite -(pf_irr C' (cn_safe_coh pf')).\n- by apply: trans_updDom=>//; case: (cn_safe_in pf).\n- by rewrite validU; apply: cohVl C.\nmove=>n Ni. rewrite /localCoh/=.\nrewrite /getLocal/=findU; case: ifP=>B; last by case: C=>_ _ _/(_ n Ni).\nmove/eqP: B=>Z; subst n this; rewrite eqxx (cohVl C)/=.\nby split; rewrite ?validPtUn//; last by eexists _, _.\nQed.\n\nLemma cn_safe_def this to d msg :\n      cn_safe this to d msg <->\n      exists b pf, @cn_step this to d msg pf = Some b.\nProof.\nsplit=>[pf/=|]; last by case=>?[].\nset b := let C := cn_safe_coh pf in\n         let s := getStC C in\n         let l := getStL C (cn_this_in (proj1 pf)) in\n         mkLocal (cstep_send s to (behead msg) l).\nby exists b, pf.\nQed.\n\nDefinition cn_send_trans :=\n  SendTrans cn_safe_coh cn_safe_in cn_safe_def cn_step_coh.\n\nEnd CoordinatorGenericSendTransitions.\n\nSection CoordinatorSendTransitions.\n\n(* Send-Prep transition *)\nDefinition send_prep_prec (p : CStateT) to (m : payload) :=\n  (exists n, p = (n, CInit) /\\ exists d, m = n :: d) \\/\n  exists n d ps, [/\\ p = (n, CSentPrep d ps), m = n :: d & to \\notin ps].\n\nProgram Definition cn_send_prep_trans : send_trans TPCCoh :=\n  @cn_send_trans prep_req send_prep_prec _.\nNext Obligation.\ncase: H=>/eqP->H; rewrite /cohMsg eqxx; split=>//=.\ncase: H0; first by case=>n[->{s}][d->{m}]/=; eexists _.\nby case=>n[d][ps][->{s}]->; eexists _.\nQed.\n\n(* Send-Commit transition *)\nDefinition send_commit_prec (p :  CStateT) to (m : payload) :=\n  (exists n d res,\n    [/\\ p = (n, CWaitPrepResponse d res), m = [::n],\n     perm_eq (map fst res) pts & all (fun r => r) (map snd res)])\n  \\/ exists n d ps, [/\\ p = (n, CSentCommit d ps), m = [::n] & to \\notin ps].\n\nProgram Definition cn_send_commit_trans : send_trans TPCCoh :=\n  @cn_send_trans commit_req send_commit_prec _.\nNext Obligation.\ncase: H=>/eqP->H; rewrite /cohMsg eqxx; split=>//=.\ncase: H0; by case=>n[d][res][->{s}]/=->.\nQed.\n\n(* Send-Abort transition *)\nDefinition send_abort_prec (p : CStateT) to (m : payload) :=\n  (exists n d res,\n    [/\\ p = (n, CWaitPrepResponse d res), m = [::n],\n        perm_eq (map fst res) pts & has (fun r => negb r) (map snd res)]) \\/\n    exists n d ps, [/\\ p = (n, CSentAbort d ps), m = [::n] & to \\notin ps].\n\nProgram Definition cn_send_abort_trans : send_trans TPCCoh :=\n  @cn_send_trans abort_req send_abort_prec _.\nNext Obligation.\ncase: H=>/eqP->H; rewrite /cohMsg eqxx; split=>//=.\nby case:H0;move=>[n][d][res][->{s}]/=->.\nQed.\n\nEnd CoordinatorSendTransitions.\n\nSection CoordinatorGenericReceiveTransitions.\n\nNotation coh := TPCCoh.\n\n(* Send-prepare *)\nVariable rc_tag : ttag.\nVariable rc_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 == cn)\n    then let s := getStC pf in\n         let l := @getStL this d pf pt in\n         mkLocal (cstep_recv s from rc_tag m l)\n    else getLocal this d.\n\nLemma rc_step_coh : r_step_coh_t rc_wf rc_tag rc_step.\nProof.\nmove=>d from this m C pf tms D F Wf T/=.\nrewrite /rc_step; case X: (this == cn); last first.\n- split=>/=; first by apply: consume_coh.\n  + by apply: trans_updDom.\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: trans_updDom.\n- by rewrite validU; apply: cohVl C.\nmove=>n Ni/=; rewrite /localCoh/=.\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)/=.\nby split; rewrite ?hvalidPtUn//; last by eexists _, _.\nQed.\n\n(* generic receive-transition *)\nDefinition rc_recv_trans := ReceiveTrans rc_step_coh.\n\nEnd CoordinatorGenericReceiveTransitions.\n\nSection CoordinatorReceiveTransitions.\n\nDefinition cn_msg_wf d (C : TPCCoh d) (this from : nid) :=\n  [pred m : TaggedMessage | c_matches_tag (getStC C).2 (tag m)].\n\nDefinition cn_receive_prep_yes_trans := rc_recv_trans prep_yes cn_msg_wf.\nDefinition cn_receive_prep_no_trans := rc_recv_trans prep_no cn_msg_wf.\n\nDefinition cn_receive_commit_ack_trans := rc_recv_trans commit_ack cn_msg_wf.\nDefinition cn_receive_abort_ack_trans := rc_recv_trans abort_ack cn_msg_wf.\n\nEnd CoordinatorReceiveTransitions.\n\n(* Participant transitions *)\n\n(* State component *)\nDefinition pstep_send (cs: PStateT) (l : Log) (commit : bool) : PStateT * Log :=\n  let: (e, s) := cs in\n  match s with\n  | PGotRequest d =>\n    if commit then (e, PRespondedYes d, l) else (e, PRespondedNo d, l)\n  | PCommitted d => (e.+1, PInit, l)\n  | PAborted d => (e.+1, PInit, l)\n  | _ => (cs, l)\n  end.\n\nDefinition p_matches_tag s mtag : bool :=\n  match s with\n  | PInit => mtag == prep_req\n  (* Just because I responded Yes, doesn't mean everyone else did.\n     So the transaction might have been aborted. *)\n  | PRespondedYes _ => (mtag == commit_req) || (mtag == abort_req)\n  | PRespondedNo _ => mtag == abort_req\n  | _ => false\n  end.\n\nDefinition pstep_recv (ps: PStateT) (from : nid) (mtag : ttag)\n           (mbody : payload) (l : Log) : PStateT * Log :=\n  if (negb (p_matches_tag ps.2 mtag)) || (from != cn) || (head 0 mbody != ps.1)\n  then (ps, l)\n  else let: (e, s) := ps in\n       match s with\n       | PInit => (e, PGotRequest (behead mbody), l)\n       | PRespondedYes d =>\n         if mtag == commit_req\n         then (e, PCommitted d, rcons l (true, d))\n         else\n           (* Even though I said Yes, the coordinator decided to abort. *)\n           (e, PAborted d, rcons l (false, d))\n       | PRespondedNo d => (e, PAborted d, rcons l (false, d))\n       | _ => (ps, l)\n       end.\n\n\nSection ParticipantGenericSendTransitions.\n\nNotation coh := TPCCoh.\n\nDefinition HPn this to := (this \\in pts /\\ to == cn).\n\nVariable ptag : ttag.\n\n(* Precondition -- this is the way one can define multiple send-transitions *)\nVariable prec : PStateT -> payload -> Prop.\n\n(* Making sure that the precondition is legit *)\nHypothesis pn_prec_safe :\n  forall this to s m,\n    HPn this to -> prec s m -> cohMsg (Msg (TMsg ptag m) this to true) s.1.\n\nLemma pn_this_in this to : HPn this to -> this \\in nodes.\nProof. by case; rewrite /nodes inE/= mem_cat=>->_/=; rewrite orbC. Qed.\n\nDefinition pn_safe (this n : nid)\n           (d : dstatelet) (msg : data) :=\n  HPn this n /\\\n  exists (Hp : HPn this n) (C : coh d), prec (getStP C (pn_this_in Hp)) msg.\n\nLemma pn_safe_coh this to d m : pn_safe this to d m -> coh d.\nProof. by case=>_; case=>?[]. Qed.\n\nLemma pn_to_in this to : HCn this to -> to \\in nodes.\nProof. by case=>_; rewrite /nodes inE/= mem_cat orbC=>->. Qed.\n\nLemma pn_safe_in this to d m : pn_safe this to d m ->\n                               this \\in nodes /\\ to \\in nodes.\nProof.\nby case; case=>H1/eqP->[X]_; move/pn_this_in: (X)=>->; rewrite /nodes inE eqxx/=.\nQed.\n\nVariable commit : bool.\n\nDefinition pn_step (this to : nid) (d : dstatelet)\n           (msg : seq nat)\n           (pf : pn_safe this to d msg) :=\n  let C := pn_safe_coh pf in\n  let s := getStP C (pn_this_in (proj1 pf)) in\n  let l := getStL C (pn_this_in (proj1 pf)) in\n  Some (mkLocal (pstep_send s l commit)).\n\nLemma pn_step_coh : s_step_coh_t coh ptag pn_step.\nProof.\nmove=>this to d msg pf h[]->{h}.\nhave C : (coh d) by case: pf=>?[?][].\nhave E: this \\in pts by case: pf=>[][].\nsplit=>/=.\n- apply: send_soupCoh; first by case:(pn_safe_coh pf).\n  exists (getStP C (pn_this_in (proj1 pf))).1.\n  case: (pf)=>H[H'][C']P/=; move: (conj H _)=>pf'.\n  move: (pn_prec_safe H P); rewrite (pf_irr C' C)/=.\n  by rewrite (pf_irr (pn_this_in H') _)//; apply: pn_this_in.\n- by apply: trans_updDom=>//; case: (pn_safe_in pf).\n- by rewrite validU; apply: cohVl C.\nmove=>n Ni. rewrite /localCoh/=.\nrewrite /getLocal/=findU; case: ifP=>B/=; last by case: C=>_ _ _/(_ n Ni).\nmove/eqP: B=>Z; subst n=>/=.\nhave X : this == cn = false by apply/negP=>/eqP Z; subst this; move: E (Hnin)=>->.\nrewrite X (cohVl C)/=; split=>//.\nmove: (pstep_send _ _ _)=>ps; rewrite E.\nrewrite ?validPtUn//; last by eexists _, _.\nQed.\n\nLemma pn_safe_def this to d msg :\n      pn_safe this to d msg <->\n      exists b pf, @pn_step this to d msg pf = Some b.\nProof.\nsplit=>[pf/=|]; last by case=>?[].\nset b := let C := pn_safe_coh pf in\n         let s := getStP C (pn_this_in (proj1 pf)) in\n         let l := getStL C (pn_this_in (proj1 pf)) in\n         mkLocal (pstep_send s l commit).\nby exists b, pf.\nQed.\n\nDefinition pn_send_trans :=\n  SendTrans pn_safe_coh pn_safe_in pn_safe_def pn_step_coh.\n\nEnd ParticipantGenericSendTransitions.\n\nSection ParticipantSendTransitions.\n\n(* Generic send-transition for the participant transition *)\nDefinition send_prep_resp_prec (ps : data -> PState)\n           (p : PStateT) (m : payload) :=\n  exists n d, p = (n, ps d) /\\  m = [:: n].\n\nProgram Definition pn_gen_send_trans (t : ttag)\n        (T: t \\in [:: prep_yes; prep_no; commit_ack; abort_ack])\n        (ps : data -> PState) c :=\n  @pn_send_trans t (send_prep_resp_prec ps) _ c.\nNext Obligation.\ncase: H=>H/eqP->{to}.\nrewrite /cohMsg (this_not_pts H) H eqxx/=; split=>//.\nby apply/andP; split=>//=; case: H0=>[?][?][->]/eqP.\nQed.\n\n(* Prep-Yes transition *)\nProgram Definition pn_send_yes_trans :=\n  @pn_gen_send_trans prep_yes _ PGotRequest true.\n\n(* Prep-No transition *)\nProgram Definition pn_send_no_trans :=\n  @pn_gen_send_trans prep_no _ PGotRequest false.\n\n(* Commit-Ack transition *)\nProgram Definition pn_commit_ack_trans :=\n  @pn_gen_send_trans commit_ack _ PCommitted true.\n\n(* Abort-Ack transition *)\nProgram Definition pn_abort_ack_trans :=\n  @pn_gen_send_trans abort_ack _ PAborted false.\n\nEnd ParticipantSendTransitions.\n\n\nSection ParticipantGenericReceiveTransitions.\n\nNotation coh := TPCCoh.\n\n(* Send-prepare *)\nVariable rp_tag : ttag.\nVariable rp_wf : forall d, coh d -> nid -> nid -> pred payload.\n\nDefinition rp_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 pts)\n    then let s := getStP pf pt in\n         let l := @getStL this d pf pt in\n         mkLocal (pstep_recv s from rp_tag m l)\n    else getLocal this d.\n\nLemma rp_step_coh : r_step_coh_t rp_wf rp_tag rp_step.\nProof.\nmove=>d from this m C pf tms D F Wf T/=.\nrewrite /rp_step; case X: (this \\in pts); last first.\n- split=>/=; first by apply: consume_coh.\n  + by apply: trans_updDom.\n  + by rewrite validU; apply: cohVl C.\n    have Y: forall z : nat_eqType, z \\in nodes -> localCoh 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: trans_updDom.\n- by rewrite validU; apply: cohVl C.\nmove=>n Ni/=; rewrite /localCoh/=.\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 by rewrite ?hvalidPtUn.\nby move/eqP: X => X; rewrite (this_not_pts X) X; eexists _, _.\nQed.\n\n(* Generic participan receive-transition *)\nDefinition rp_recv_trans := ReceiveTrans rp_step_coh.\n\nEnd ParticipantGenericReceiveTransitions.\n\nSection ParticipantReceiveTransitions.\n\nDefinition pn_msg_wf d (_ : TPCCoh d) (this from : nid) :=\n  [pred p : payload | true].\n\n(* Participant - got prepare request *)\nDefinition pn_receive_got_prep_trans := rp_recv_trans prep_req pn_msg_wf.\n\n(* Participant - got commit command *)\nDefinition pn_receive_commit_ack_trans := rp_recv_trans commit_req pn_msg_wf.\n\n(* Participant - got abort command *)\nDefinition pn_receive_abort_ack_trans := rp_recv_trans abort_req pn_msg_wf.\n\nEnd ParticipantReceiveTransitions.\n\n\n(* Putting it all together *)\nSection Protocol.\n\nVariable l : Label.\n\n(* All send-transitions *)\nDefinition tpc_sends :=\n  [::\n     cn_send_prep_trans;\n     cn_send_commit_trans;\n     cn_send_abort_trans;\n\n     pn_send_yes_trans;\n     pn_send_no_trans;\n     pn_commit_ack_trans;\n     pn_abort_ack_trans\n  ].\n\n(* All receive-transitions *)\nDefinition tpc_receives :=\n  [::\n     cn_receive_prep_yes_trans;\n     cn_receive_prep_no_trans;\n     cn_receive_commit_ack_trans;\n     cn_receive_abort_ack_trans;\n\n     pn_receive_got_prep_trans;\n     pn_receive_commit_ack_trans;\n     pn_receive_abort_ack_trans\n  ].\n\n\nProgram Definition TwoPhaseCommitProtocol : protocol :=\n  @Protocol _ l _ tpc_sends tpc_receives _ _.\n\n\nEnd Protocol.\nEnd TPCProtocol.\n\nModule Exports.\nSection Exports.\n\nDefinition TwoPhaseCommitProtocol := TwoPhaseCommitProtocol.\n\n(* Variable l : Label. *)\n(* Variable cn : nid. *)\n(* Variable pts : seq nid. *)\n(* Variable others : seq nid. *)\n\n(* Hypothesis Hnin : cn \\notin pts. *)\n\nDefinition cn_send_prep_trans := cn_send_prep_trans.\nDefinition cn_send_commit_trans := cn_send_commit_trans.\nDefinition cn_send_abort_trans := cn_send_abort_trans.\n\nDefinition pn_send_yes_trans := pn_send_yes_trans.\nDefinition pn_send_no_trans := pn_send_no_trans.\nDefinition pn_commit_ack_trans := pn_commit_ack_trans.\nDefinition pn_abort_ack_trans := pn_abort_ack_trans.\n\nDefinition cn_receive_prep_yes_trans := cn_receive_prep_yes_trans.\nDefinition cn_receive_prep_no_trans := cn_receive_prep_no_trans.\nDefinition cn_receive_commit_ack_trans := cn_receive_commit_ack_trans.\nDefinition cn_receive_abort_ack_trans := cn_receive_abort_ack_trans.\n\nDefinition pn_receive_got_prep_trans := pn_receive_got_prep_trans.\nDefinition pn_receive_commit_ack_trans := pn_receive_commit_ack_trans.\nDefinition pn_receive_abort_ack_trans := pn_receive_abort_ack_trans.\n\n(* TPC Tags *)\nDefinition prep_req := prep_req.\nDefinition prep_yes := prep_yes.\nDefinition prep_no := prep_no.\nDefinition commit_req := commit_req.\nDefinition abort_req := abort_req.\nDefinition commit_ack := commit_ack.\nDefinition abort_ack := abort_ack.\n\n(* Getters *)\nDefinition getStC := getStC.\nDefinition getStP := getStP.\nDefinition getStL := getStL.\n\nDefinition getStCE := getStCE.\nDefinition getStPE := getStPE.\nDefinition getStCL := getStLE.\n\nEnd Exports.\nEnd Exports.\n\nEnd TPCProtocol.\n\nExport TPCProtocol.States.\nExport TPCProtocol.Exports.\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/TwoPhaseCommit/TwoPhaseProtocol.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.29368188519411215}}
{"text": "(**#+TITLE: laoziSolution.v\n\nProph\n\nhttps://github.com/1337777/laozi/blob/master/laoziSolution2.v\n\nsolves some question of LAOZI [fn:1] which is how to program polymorph coparametrism\nfunctors ( \"comonad\" ) ... Whatever is discovered, its format, its communication is\nsimultaneously some predictable logical discovery and some random dia-para-logical\ndiscovery.\n\nIn particular this text programs the grammatical / inductive (therefore free) \ndescription of polymorph coparametrism functor and the conversion \nrelations over the generated morphisms. This text is based on earlier texts which \ndescribe functional-monoidal logic and the decidable coherence of this logic.\n\nNext this text programs the iterated comultiplication (DeClassifying) and the\ncorresponding deduced conversion relations over the morphisms. Then the reduction\nrelation and degradation lemmas are programmed and deduced.\n\nFinally the solution morphisms are programmed with their (dependent-)destruction\nlemmas such to inner-instantiate the object-indices. And the (non-congruent)\nresolution by cut elimination / desintegration technique is programmed and deduced :\nthis deduction is mostly-automated.\n\nFor instant first impression, the common saying that the counit inner-cancels the\ncomultiplication is written as :\n\n#+BEGIN_EXAMPLE\n| IterCancelInner :\n    forall {trf : obV log -> obV log}\n      (Vb Vb' : obV log) (vb : V(0 Vb' |- Vb )0)\n      (W W_dft : obV log) (V0Vb' : obV log) (Vs : list (obV log))\n      (vs : (hlist (toArrowV (trf:=trf)) (chain Vs)))\n      (va : V(0 trf(last W_dft Vs) |- W )0)\n      (v0b : V(0 V0Vb' |- (0 trf(head W_dft Vs) & Vb' )0 )0)\n      (B : obMod) (A : obMod) (b : 'D(0 Vb |- [0 B ~> A ]0 )0)\n      (A' : obMod)(a : 'D(0 W |- [0 A ~> A' ]0 )0),\n      ( v0b o>| ( vb o>' b)  o>D (iterDeClassifying (V_dft := W_dft) vs ( va o>' a)) )\n        <~~ ( v0b o>| (vb o>| b o>Mod 'declfy )\n                o>D (iterDeClassifying (V_dft := W_dft) vs (va o>| 'clfy o>Mod a) )\n            : 'D(0 V0Vb' |- [0 B ~> 'D0| (iterDeClass0 (length Vs).-1 A') ]0)0 )\n#+END_EXAMPLE\n\nOutline :\n\n  * Grammatical description of polymorph coparametrism functor\n  ** Importing the functional-monoidal logic\n  ** Base generating graph\n  ** Grammatical generation of the morhisms\n  ** Decoding into the common sense : grammatical is indeed free\n  ** Some notations\n  ** More functional-monoidal logic\n  ** The generated conversion relations over the morphisms\n\n  * Iterated constructors\n  ** Indexed list, lemmas\n  ** Chained lists, lemmas\n  ** Iterated constructors\n\n  * Grade\n\n  * Reduction\n  ** Grammatical generation of the reduction relation\n  ** Degradation lemmas\n\n  * Solution\n  ** Grammatical generation of the solution morphisms\n  ** Containment of the solution morphisms into all the morphisms\n  ** Destruction of morphisms with inner-instantiation of object-indices\n  ** Iterated =DeClassifying= prefix\n\n  * Resolution\n\nReviews :\n\n[fn:1] ~1337777.OOO~ [[https://github.com/1337777/laozi/blob/master/laoziSolution2.v]]\n\n-----\n\nMay some additional empty-rooms in the public UBC campus have their doors unlocked during July 15 \nfor the public 1337777 School ?\n\nThe public 1337777 School is seeking ministerial-review-and-payments as school for the public, \ncomparable to https://team.inria.fr/marelle/coq-winter-school-2017/ . Such 1337777 School shall\ntruly hold the motivation of maximizing the mathematical memory and sensibility of each\n and all of the public, contrary to the common falsification of the other \nministerial-reports which in reality have none such motivation and even may sans-detours\n elect-by-random ...\n\npaypal 1337777.OOO@gmail.com , wechatpay 2796386464@qq.com , irc #OOO1337777\n\n\n* Grammatical description of polymorph coparametrism functor\n\n** Importing the functional-monoidal logic\n\nImporting the functional-monoidal logic, the ssreflect grammar and deduction tactics\nand math definitions, the congruent rewriting tactics, and the linear arithmetic\ndecidability-solver. (Memo that ~COQ~ --version > 8.5)\n\n#+BEGIN_SRC coq :exports both :results silent **)\n\nRequire Import borceuxSolution_half_old.\nRequire Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp Require Import ssrbool ssrfun eqtype ssrnat seq.\nRequire Import Setoid.\nRequire Omega.\n\nSet Implicit Arguments.\nUnset Strict Implicits.\nUnset Printing Implicit Defensive.\n\n(**#+END_SRC\n\n** Base generating graph\n\n#+BEGIN_SRC coq :exports both :results silent **)\n\nModule COPARAM.\n\n  Import LOGIC.\n  Import LOGIC.Ex_Notations3.\n\n  Parameter obMod_gen : Set.\n  Parameter Mod_gen : forall {log : logic}, obV log -> obMod_gen -> obMod_gen -> Set.\n  \n  Inductive obMod : Set :=\n  | GenObMod : forall A : obMod_gen, obMod\n  | DeClass0 : forall A : obMod, obMod.\n\n  Notation \"#0| A\" := (GenObMod A) (at level 4, right associativity).\n  Notation \"'D0| A\" := (DeClass0 A) (at level 4, right associativity).\n\n(**#+END_SRC\n\n** Grammatical generation of the morphisms\n\nThe grammatical description of polymorph coparametrism functor, primo the morphisms :\n\n#+BEGIN_SRC coq :exports both :results silent **)\n  \n  Reserved Notation \"''Mod' (0 V |- [0 A1 ~> A2 ]0 )0\"\n           (at level 25, format \"''Mod' (0  V  |-  [0  A1  ~>  A2  ]0 )0\").\n  Reserved Notation \"''D' (0 V |- [0 A1 ~> A2 ]0 )0\"\n           (at level 25, format \"''D' (0  V  |-  [0  A1  ~>  A2  ]0 )0\").\n\n  Inductive Mod00 {log : logic} : obV log -> obMod -> obMod -> Type :=\n\n  | PolyV_Mod : forall (V V' : obV log),\n      V(0 V' |- V )0 -> forall (A1 A2 : obMod), 'Mod(0 V |- [0 A1 ~> A2 ]0 )0 ->\n                                         'Mod(0 V' |- [0 A1 ~> A2 ]0 )0\n\n  | GenArrowsMod : forall (V V' : obV log), forall A1 A2 : obMod_gen\n      , Mod_gen V A1 A2 -> V(0 V' |- V )0 -> \n        'Mod(0 V' |- [0 (#0| A1) ~> (#0| A2) ]0 )0\n\n  | UnitMod : forall (V : obV log), forall {A : obMod}\n      ,  V(0 V |- log.-I )0 -> 'Mod(0 V |- [0 A ~> A ]0 )0\n\n  | PolyMod : forall (V : obV log) (A2 : obMod) (A1 : obMod)\n    , 'Mod(0 V |- [0 A2 ~> A1 ]0 )0 -> forall A1' : obMod, forall (W WV : obV log),\n          V(0 WV |- (0 W & V )0 )0 ->\n          'Mod(0 W |- [0 A1 ~> A1' ]0 )0 -> 'Mod(0 WV |- [0 A2 ~> A1' ]0 )0\n\n  | UnitDeClass : forall (A : obMod) (A' : obMod) (W W' : obV log)\n    , V(0 W' |- (0 W & log.-I)0 )0 ->\n      'Mod(0 W |- [0 A ~> A' ]0 )0 -> 'D(0 W' |- [0 'D0| A ~> A' ]0 )0\n\n  | PolyDeClass : forall (V : obV log) (B : obMod) (A : obMod),\n      'D(0 V |- [0 B ~> A ]0 )0 -> forall A' : obMod, forall (W WV : obV log),\n          V(0 WV |- (0 W & V )0 )0 ->\n          'Mod(0 W |- [0 A ~> A' ]0 )0 -> 'D(0 WV |- [0 B ~> A' ]0 )0\n\n  (* common CoUnit, errata: Unit *)\n  | Classifying : forall (V V' : obV log), forall (A1 A2 : obMod),\n        V(0 V' |- V )0 ->\n        'Mod(0 V |- [0 A1 ~> A2 ]0 )0 -> 'Mod(0 V' |- [0 ('D0| A1) ~> A2 ]0 )0\n\n  | DeClassifying : forall (V V' : obV log), forall (A1 A2 : obMod),\n        V(0 V' |- V )0 -> \n        'D(0 V |- [0 A1 ~> A2 ]0 )0 -> 'D(0 V' |- [0 A1 ~> ('D0| A2) ]0 )0\n\n  where\n  \"''Mod' (0 V |- [0 A1 ~> A2 ]0 )0\"\n    := (@Mod00 _ V A1 A2) and \"''D' (0 V |- [0 A1 ~> A2 ]0 )0\"\n         := (@Mod00 _ V A1 ('D0| A2)).\n    \n(**#+END_SRC\n\n** Decoding into the common sense : grammatical is indeed free\n\nHow to decode from the grammatical description to the non-grammatical description such\nto deduce that it is indeed some instance of polymorph coparametrism functor, in the\ncommon sense :\n\n#+BEGIN_SRC coq :exports both :results silent **)\n  \n  Parameter Mod'00 : forall {log : logic}, obMod -> obMod -> obV log.\n  Parameter decode : forall {log : logic}, forall {A1 A2 : obMod},\n      forall {V : obV log}, 'Mod(0 V |- [0 A1 ~> A2 ]0 )0 -> V(0 V |- Mod'00 A1 A2 )0 .\n  Parameter encode : forall {log : logic}, forall {A1 A2 : obMod},\n      forall {V : obV log}, V(0 V |- Mod'00 A1 A2 )0 -> 'Mod(0 V |- [0 A1 ~> A2 ]0 )0 .\n  Axiom decodeK : forall {log : logic}, forall (A1 A2 : obMod) (V : obV log),\n        cancel (@decode _ A1 A2 V) (@encode _ A1 A2 V).\n  Axiom encodeK : forall {log : logic}, forall (A1 A2 : obMod) (V : obV log),\n        cancel (@encode _ A1 A2 V) (@decode _ A1 A2 V).\n\n  Axiom decode_metaPoly : forall {log : logic}, forall (A1 A2 : obMod),\n      forall (V V' : obV log) (v : V(0 V' |- V )0), forall f : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0,\n          ( v o> (decode f) )\n            ~~ ( decode (PolyV_Mod v f)\n                 : log.-V(0 V' |- Mod'00 A1 A2 )0 ) .\n(**#+END_SRC\n\n** Some notations\n\n#+BEGIN_SRC coq :exports both :results silent **)\n  \n  Definition PolyV_Mod_rewrite log V V' A1 A2 v a :=\n    (@PolyV_Mod log V V' v A1 A2 a).\n  Notation \"v o>' a\" := (@PolyV_Mod_rewrite _ _ _ _ _ v a)\n                          (at level 25, right associativity, format \"v  o>'  a\").\n  Notation \"v o>| #1| a\" :=\n    (@GenArrowsMod _ _ _ _ _ a v) (at level 25, right associativity).\n  Notation \"v o>| 'uMod'\" := (@UnitMod _ _ _ v)(at level 25).\n  Notation \"v o>| @ 'uMod' A\" :=\n    (@UnitMod _ _ A v) (at level 25, only parsing).\n  Definition PolyMod_rewrite log V A2 A1 A1' W WV wv a_ a' :=\n    (@PolyMod log V A2 A1 a_ A1' W WV wv a').\n  Notation \"v o>| a_ o>Mod a'\" :=\n    (@PolyMod_rewrite _ _ _ _ _ _ _ v a_ a')\n      (at level 25, right associativity, a_ at next level, format \"v  o>|  a_  o>Mod  a'\").\n  Notation \"v o>| ''D1|' a\" := (@UnitDeClass _ _ _ _ _ v a)\n                                 (at level 25, right associativity).\n  Definition PolyDeClass_rewrite log V B A A' W WV wv b a :=\n    (@PolyDeClass log V B A b A' W WV wv a).\n  Notation \"v o>| b o>D a\" :=\n    (@PolyDeClass_rewrite _ _ _ _ _ _ _ v b a)\n      (at level 25, right associativity, b at next level, format \"v  o>|  b  o>D  a\").\n  Notation \"v o>| 'clfy o>Mod a'\" :=\n    (@Classifying _ _ _ _ _ v a') (at level 25, right associativity).\n  Notation \"v o>| a_ o>Mod 'declfy\" :=\n    (@DeClassifying _ _ _ _ _ v a_) (at level 25, a_ at next level, right associativity).\n\n(**#+END_SRC\n\n** More functional-monoidal logic\n\nMore description of the functional-monoidal logic which is assumed. These equations\nare decidable by coherence lemmas ...\n\n#+BEGIN_SRC coq :exports both :results silent **)\n  \n  Parameter PolyV_unitPre :\n    forall {log : logic} {V V' : obV log} (v : log.-V(0 V |- V')0), log.-1 o> v ~~ v.\n  Parameter PolyV_unitPost :\n    forall {log : logic} {V V' : obV log} (v : log.-V(0 V |- V')0), v o> log.-1 ~~ v.\n\n  Definition desIdenObLK :\n    forall {log : logic} {V : obV log}, log.-V(0 log.-(0 log.-I & V )0 |- V )0\n    := fun log V => Des (log.-uV) .\n  Parameter desIdenObLKV :\n    forall {log : logic} {V : obV log}, log.-V(0 V |- log.-(0 log.-I & V )0 )0 .\n\n  Axiom desIdenObLK_K : forall {log : logic} {V : obV log},\n      log.-1 ~~ (@desIdenObLK log V) o> (@desIdenObLKV log V).\n\n  Axiom desIdenObLKV_K : forall {log : logic} {V : obV log},\n      log.-1 ~~ (@desIdenObLKV log V) o> (@desIdenObLK log V).\n\n  Axiom desIdenObLKV_Assoc_Rev_desIdenObLK : forall {log : logic} (V W : obV log),\n      log.-1 ~~ ( ( log.-(1 desIdenObLKV & V )0 o> Assoc_Rev ) o> desIdenObLK\n                  : log.-V(0 log.-(0 W & V )0 |- log.-(0 W & V )0 )0 ).\n  \n  Parameter desIdenObRK :\n    forall {log : logic} {V : obV log}, log.-V(0 log.-(0 V & log.-I )0 |- V )0.\n\n  Parameter desIdenObRKV :\n    forall {log : logic} {V : obV log}, log.-V(0 V |- log.-(0 V & log.-I )0 )0. \n  \n  Parameter desV01 : forall {log : logic} {V2 V2' V1 : obV log},\n      log.-V(0 V2 |- V2' )0 -> log.-V(0 log.-(0 V1 & V2 )0 |- log.-(0 V1 & V2' )0 )0.\n  Notation  \"dat .-(0 V1 & v )1\" := (@desV01 dat _ _ V1 v)\n                                      (at level 30, format \"dat .-(0  V1  &  v  )1\").\n  Notation  \"(0 V1 & v )1\" := (_ .-(0 V1 & v )1)\n                                (at level 30, format \"(0  V1  &  v  )1\").\n  Axiom desV01_consV10 :\n    forall {log : logic} (V2 V2' V1 : obV log) (v : log.-V(0 V2' |- V2 )0) (W : obV log)\n      (w : log.-V(0 log.-(0 V1 & V2 )0 |- W )0),\n      Des( [1 v ~> W ]0 <o (Cons w) ) ~~ w <o log.-(0 V1 & v )1 .\n\n  Axiom desIdenObLKV_IdenOb_Assoc_Rev_desIdenObLK : forall {log : logic} (V : obV log),\n      log.-1 ~~ ( ( (log.-(1 desIdenObLKV & V )0)\n                      o> Assoc_Rev ) o> (log.-(0 log.-I & desIdenObLK )1)\n                  : log.-V(0 log.-(0 log.-I & V )0 |- log.-(0 log.-I & V )0 )0 ).\n\n(**#+END_SRC\n\n** The generated conversion relations over the morhisms\n\nThe grammatical description of polymorph coparametrism functor, secondo the conversion\nrelations over the morphisms :\n\n#+BEGIN_SRC coq :exports both :results silent **)\n  \n  Reserved Notation \"f2 ~~~ f1\" (at level 70).\n\n  Inductive convMod {log : logic} : forall (V : obV log) (A1 A2 : obMod),\n      'Mod(0 V |- [0 A1 ~> A2 ]0 )0 -> 'Mod(0 V |- [0 A1 ~> A2 ]0 )0 -> Prop :=\n\n  | Mod_ReflV : forall (V : obV log) (A1 A2 : obMod) (a : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0),\n      a ~~~ a\n\n  | Mod_TransV : forall (V : obV log) (A1 A2 : obMod)\n               (uTrans a : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0),\n      uTrans ~~~ a -> forall (a0 : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0),\n        a0 ~~~ uTrans -> a0 ~~~ a\n\n  | Mod_SymV : forall (V : obV log) (A1 A2 : obMod) (a a0 : 'Mod(0 V |- [0 A1 ~> A2]0 )0),\n      a ~~~ a0 -> a0 ~~~ a\n\n  | PolyV_Mod_cong : forall (A1 A2 : obMod) (V V' : obV log) (v v0 : V(0 V' |- V )0)\n                       (a a0 : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0),\n      v0 ~~ v -> a0 ~~~ a -> ( v0 o>' a0 ) ~~~ ( v o>' a )\n\n  | GenArrowsMod_cong : forall (V V' : obV log), forall (A1 A2 : obMod_gen) (aGen : Mod_gen V A1 A2)\n      , forall (v v0 : V(0 V' |- V )0), v0 ~~ v -> v0 o>| #1| aGen ~~~ v o>| #1| aGen\n\n  | UnitMod_cong : forall (V : obV log), forall {A : obMod} (v v0 : V(0 V |- log.-I )0),\n        v0 ~~ v -> v0 o>| @uMod A ~~~ v o>| @uMod A\n\n  | Mod_cong :\n      forall (V : obV log) (A A' : obMod) (a_ a_0 : 'Mod(0 V |- [0 A ~> A' ]0 )0),\n      forall (W : obV log) (A'' : obMod) (a' a'0 : 'Mod(0 W |- [0 A' ~> A'' ]0 )0),\n      forall (WV : obV log) (v v0 : V(0 WV |- (0 W & V )0 )0),\n        v0 ~~ v -> a_0 ~~~ a_ -> a'0 ~~~ a' -> ( v0 o>| a_0 o>Mod a'0 ) ~~~ ( v o>| a_ o>Mod a' )\n\n  | UnitDeClass_cong :\n      forall (A : obMod) (A' : obMod) (W W' : obV log) (v v0 : V(0 W' |- (0 W & log.-I )0 )0) (a a0 : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n        v0 ~~ v -> a0 ~~~ a -> ( v0 o>| 'D1| a0 ) ~~~ ( v o>| 'D1| a )\n\n  | PolyDeClass_cong :\n      forall (V : obV log) (B : obMod) (A : obMod) (b b0 : 'D(0 V |- [0 B ~> A ]0 )0),\n      forall (W : obV log) (A' : obMod) (a a0 : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n      forall (WV : obV log) (v v0 : V(0 WV |- (0 W & V )0 )0),\n        v0 ~~ v -> b0 ~~~ b -> a0 ~~~ a -> ( v0 o>| b0 o>D a0 ) ~~~ ( v o>| b o>D a )\n\n  | Classifying_cong :\n      forall (V V' : obV log) (v v0 : V(0 V' |- V )0) (A1 A2 : obMod) (a a0 : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0),\n        v0 ~~ v -> a0 ~~~ a -> (v0 o>| 'clfy o>Mod a0 ) ~~~ (v o>| 'clfy o>Mod a )\n\n  | DeClassifying_cong :\n      forall (V V' : obV log) (v v0 : V(0 V' |- V )0) (A1 A2 : obMod) (a a0 : 'D(0 V |- [0 A1 ~> A2 ]0 )0),\n        v0 ~~ v -> a0 ~~~ a -> (v0 o>| a0 o>Mod 'declfy ) ~~~ (v o>| a o>Mod 'declfy )\n\n  | GenArrowsMod_arrowLog : forall (V V' V'' : obV log) (A1 A2 : obMod_gen) (aGen : Mod_gen V A1 A2)\n                              (v : V(0 V' |- V )0) (v' : V(0 V'' |- V' )0),\n      ( ( v' o> v) o>| #1| aGen )\n        ~~~ (v' o>' (v o>| #1| aGen)\n            : 'Mod(0 V'' |- [0 #0| A1 ~> #0| A2 ]0)0 )\n\n  | UnitMod_arrowLog : forall (V V' : obV log) (A : obMod) (v : V(0 V |- log.-I )0)\n                         (v' : V(0 V' |- V )0),\n      ( ( v' o> v ) o>| @uMod A )\n        ~~~ (v' o>' (v o>| @uMod A)\n            : 'Mod(0 V' |- [0 A ~> A ]0)0 )\n\n  | Mod_arrowLog :\n      forall (V : obV log) (A0 : obMod) (A : obMod)\n        (a_ : 'Mod(0 V |- [0 A0 ~> A ]0 )0),\n      forall (W : obV log) (A' : obMod) (a' : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n      forall (WV : obV log) (v : V(0 WV |- (0 W & V )0 )0),\n      forall (WV0 : obV log) (v0 : V(0 WV0 |- WV )0),\n        ( ( v0 o> v ) o>| a_ o>Mod a' )\n          ~~~ ( v0 o>' ( v o>| a_ o>Mod a' )\n                : 'Mod(0 WV0 |- [0 A0 ~> A' ]0)0 )\n\n  | Mod_arrowPre :\n      forall (V V' : obV log) (v : V(0 V' |- V )0) (A0 : obMod) (A : obMod)\n        (a_ : 'Mod(0 V |- [0 A0 ~> A ]0 )0),\n      forall (W : obV log) (A' : obMod) (a' : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n      forall (WV' : obV log) (v0 : V(0 WV' |- (0 W & V' )0 )0),\n        ( ( v0 o> log.-(0 _ & v )1 ) o>| a_ o>Mod a' )\n          ~~~ ( v0 o>| ( v o>' a_ ) o>Mod a'\n                : 'Mod(0 WV' |- [0 A0 ~> A' ]0)0 )\n\n  | Mod_arrowPost :\n      forall (V : obV log) (A0 : obMod) (A : obMod) (a_ : 'Mod(0 V |- [0 A0 ~> A ]0 )0),\n      forall (W W' : obV log) (w : V(0 W' |- W )0) (A' : obMod)\n        (a' : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n      forall (W'V : obV log) (w0 : V(0 W'V |- (0 W' & V )0 )0),\n        ( ( w0 o> log.-(1 w & _ )0 ) o>| a_ o>Mod a' )\n          ~~~ ( w0 o>| a_ o>Mod ( w o>' a' )\n                : 'Mod(0 W'V |- [0 A0 ~> A' ]0)0 )\n\n  | UnitDeClass_arrowLog :\n      forall (W W' W'' : obV log) (w : V(0 W' |- (0 W & log.-I )0 )0)\n        (w' : V(0 W'' |- W' )0)\n          (A A' : obMod) (a : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n        ( ( w' o> w ) o>| 'D1| a )\n          ~~~ (  w' o>' ( w o>| 'D1| a )\n                : 'D(0 W'' |- [0 'D0| A ~> A' ]0)0 )\n\n  | UnitDeClass_arrow :\n      forall (W W' W'' : obV log) (w : V(0 W' |- W )0)\n        (w' : V(0 W'' |- (0 W' & log.-I )0 )0)\n          (A A' : obMod) (a : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n        ( ( w' o> log.-(1 w & log.-I )0 ) o>| 'D1| a )\n          ~~~ (  w' o>| 'D1| ( w o>' a)\n                : 'D(0 W'' |- [0 'D0| A ~> A' ]0)0 )\n\n  | DeClass_arrowLog :\n      forall (V : obV log) (B : obMod) (A : obMod)\n        (b : 'D(0 V |- [0 B ~> A ]0 )0),\n      forall (W : obV log) (A' : obMod) (a : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n      forall (WV : obV log) (v : V(0 WV |- (0 W & V )0 )0),\n      forall (WV0 : obV log) (v0 : V(0 WV0 |- WV )0),\n        ( ( v0 o> v ) o>| b o>D a )\n          ~~~ ( v0 o>' ( v o>| b o>D a )\n                : 'D(0 WV0 |- [0 B ~> A' ]0)0 )\n\n  | DeClass_arrowPre :\n      forall (V V' : obV log) (v : V(0 V' |- V )0) (B : obMod) (A : obMod)\n        (b : 'D(0 V |- [0 B ~> A ]0 )0),\n      forall (W : obV log) (A' : obMod) (a : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n      forall (WV' : obV log) (v0 : V(0 WV' |- (0 W & V' )0 )0),\n        ( ( v0 o> log.-(0 _ & v )1 ) o>| b o>D a )\n          ~~~ ( v0 o>| ( v o>' b ) o>D a\n                : 'D(0 WV' |- [0 B ~> A' ]0)0 )\n\n  | DeClass_arrowPost :\n      forall (V : obV log) (B : obMod) (A : obMod) (b : 'D(0 V |- [0 B ~> A ]0 )0),\n      forall (W W' : obV log) (w : V(0 W' |- W )0) (A' : obMod)\n        (a : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n      forall (W'V : obV log) (w0 : V(0 W'V |- (0 W' & V )0 )0),\n        ( ( w0 o> log.-(1 w & _ )0 ) o>| b o>D a )\n          ~~~ ( w0 o>| b o>D ( w o>' a )\n                : 'D(0 W'V |- [0 B ~> A' ]0)0 )\n\n  | Classifying_arrowLog : forall (V V' V'' : obV log) (v : V(0 V' |- V )0) (v0 : V(0 V'' |- V' )0)\n                             (A1 A2 : obMod)\n                          (a : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0),\n      ( ( v0 o> v ) o>| 'clfy o>Mod a )\n        ~~~ ( v0 o>' ( v o>| 'clfy o>Mod a ) \n              : 'Mod(0 V'' |- [0 'D0| A1 ~> A2 ]0)0 )\n\n  | Classifying_arrow : forall (V V' V'' : obV log) (v : V(0 V' |- V )0)\n                          (v0 : V(0 V'' |- V' )0) (A1 A2 : obMod)\n                          (a : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0),\n        ( ( v0 o> v ) o>| 'clfy o>Mod a )\n          ~~~ ( v0 o>| 'clfy o>Mod ( v o>' a )\n                : 'Mod(0 V'' |- [0 'D0| A1 ~> A2 ]0)0 )\n\n  | DeClassifying_arrowLog :\n      forall (V V' V'' : obV log) (v : V(0 V' |- V )0) (v0 : V(0 V'' |- V' )0) (A1 A2 : obMod)\n        (a : 'D(0 V |- [0 A1 ~> A2 ]0 )0),\n        ( ( v0 o> v ) o>| a o>Mod 'declfy )\n        ~~~ ( v0 o>' ( v o>| a o>Mod 'declfy )\n                : 'D(0 V'' |- [0 A1 ~> 'D0| A2 ]0)0 )\n\n  | DeClassifying_arrow :\n      forall (V V' V'' : obV log) (v : V(0 V' |- V )0) (v0 : V(0 V'' |- V' )0) (A1 A2 : obMod)\n        (a : 'D(0 V |- [0 A1 ~> A2 ]0 )0),\n      ( ( v0 o> v ) o>| a o>Mod 'declfy )\n        ~~~ ( v0 o>| ( v o>' a ) o>Mod 'declfy\n              : 'D(0 V'' |- [0 A1 ~> 'D0| A2 ]0)0 )\n\n  | PolyV_Mod_arrowLog :\n      forall (V'' V' : obV log) (v' : V(0 V'' |- V' )0) (V : obV log)\n        (v : V(0 V' |- V )0) (A1 A2 : obMod) (a : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0),\n        ( ( v' o> v ) o>' a )\n          ~~~ ( v' o>' ( v o>' a )\n                : 'Mod(0 V'' |- [0 A1 ~> A2 ]0)0 )\n\n  (* non for reduction *)\n  | Mod_morphism :\n      forall (V : obV log) (B : obMod) (A : obMod) (b : 'Mod(0 V |- [0 B ~> A ]0 )0)\n        (W_ : obV log) (A' : obMod) (a_ : 'Mod(0 W_ |- [0 A ~> A' ]0 )0)\n        (W' : obV log) (A'' : obMod) (a' : 'Mod(0 W' |- [0 A' ~> A'' ]0 )0),\n      forall (W_V : obV log) (v : V(0 W_V |- (0 W_ & V )0 )0),\n      forall (W'W_V : obV log) (v0 : V(0 W'W_V |- (0 W' & W_V )0 )0),\n        ( ( v0 o> (0 W' & v )1 o> Assoc ) o>| b o>Mod ( log.-1 o>| a_ o>Mod a' ) )\n          ~~~ ( v0 o>| ( v o>| b o>Mod a_ ) o>Mod a'\n                : 'Mod(0 W'W_V |- [0 B ~> A'' ]0)0 )\n\n  | DeClass_morphismPost :\n      forall (A : obMod)\n        (W_ W_' : obV log) (v : V(0 W_' |- (0 W_ & log.-I )0 )0) (A' : obMod) (a_ : 'Mod(0 W_ |- [0 A ~> A' ]0 )0)\n        (W' : obV log) (A'' : obMod) (a' : 'Mod(0 W' |- [0 A' ~> A'' ]0 )0),\n      forall (W'W_' : obV log) (v0 : V(0 W'W_' |- (0 W' & W_' )0 )0),\n        ( ( v0 o> desIdenObRKV ) o>| 'D1| ( (log.-1) o>| ( ( v o> desIdenObRK ) o>' a_ ) o>Mod a' )  )\n          ~~~ ( v0 o>| ( v o>| 'D1| a_ ) o>D a'\n                : 'D(0 W'W_' |- [0 'D0| A ~> A'' ]0)0 )\n\n  | DeClass_morphismPre :\n      forall (A : obMod) (V' : obV log) (B' : obMod) (b' : 'D(0 V' |- [0 B' ~> A ]0 )0),\n      forall (W W' : obV log) (v : V(0 W' |- (0 W & log.-I )0 )0) (A' : obMod) (a : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n      forall (W'V' : obV log) (v0 : V(0 W'V' |- (0 W' & V' )0 )0),\n        ( v0  o>| b' o>D ( ( v o> desIdenObRK )  o>' a ) )\n          ~~~ ( v0 o>| b' o>Mod ( v o>| 'D1| a )\n                : 'D(0 W'V' |- [0 B' ~> A' ]0)0 )\n\n  | PolyV_Mod_unit :\n      forall (V : obV log) (A1 A2 : obMod) (a : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0),\n        ( a ) ~~~ ( log.-1 o>' a\n                    : 'Mod(0 V |- [0 A1 ~> A2 ]0)0 )\n\n  | Mod_unit :\n      forall (A : obMod) (V : obV log) (v : V(0 V |- log.-I )0)\n        (W : obV log) (A' : obMod) (a : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n      forall (WV : obV log) (v0 : V(0 WV |- (0 W & V )0 )0),\n        ( ( v0 o> log.-(0 W & v )1 o> desIdenObRK ) o>' a )\n          ~~~ ( v0 o>| ( v o>| uMod ) o>Mod a\n                : 'Mod(0 WV |- [0 A ~> A' ]0)0 )\n\n  | Mod_inputUnitMod :\n      forall (V : obV log) (B : obMod) (A : obMod) (b : 'Mod(0 V |- [0 B ~> A ]0 )0),\n      forall (W : obV log) (w : V(0 W |- log.-I )0),\n      forall (WV : obV log) (w0 : V(0 WV |- (0 W & V )0 )0),\n        ( ( w0 o> log.-(1 w & V )0 o> desIdenObLK ) o>' b )\n          ~~~  ( w0 o>| b o>Mod ( w o>| uMod )\n                 : 'Mod(0 WV |- [0 B ~> A ]0)0 )\n\n  | DeClass_unit :\n      forall (V : obV log) (v : V(0 V |- log.-I )0) (A : obMod) (A' : obMod) (W : obV log) (a : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n      forall (WV : obV log) (v0 : V(0 WV |- (0 W & V )0 )0),\n        ( ( v0 o> log.-(0 W & v )1 ) o>| 'D1| a )\n          ~~~ ( v0 o>| ( v o>| uMod ) o>D a\n                : 'D(0 WV |- [0 'D0| A ~> A' ]0 )0 )\n\n  | DeClass_inputUnitMod :\n      forall (V : obV log) (B : obMod) (A : obMod) (b : 'D(0 V |- [0 B ~> A ]0 )0),\n        forall (W : obV log) (w : V(0 W |- log.-I )0),\n      forall (WV : obV log) (w0 : V(0 WV |- (0 W & V )0 )0),\n        ( ( w0 o> ( log.-(1 w & _ )0 ) o> desIdenObLK ) o>' b )\n          ~~~ ( w0 o>| b o>D ( w o>| uMod )\n                : 'D(0 WV |- [0 B ~> A ]0)0 )\n\n  | Classifying_morphismPre :\n      forall (V V' : obV log) (v : V(0 V' |- V )0 ) (A1 A2 : obMod) (a_ : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0)\n        (W : obV log) (A3 : obMod) (a' : 'Mod(0 W |- [0 A2 ~> A3 ]0 )0),\n      forall (WV' : obV log) (v0 : V(0 WV' |- (0 W & V' )0 )0),\n        ( ( log.-1 ) o>| 'clfy o>Mod ( ( v0 o> (0 _ & v )1 ) o>| a_ o>Mod a' ) )\n          ~~~ ( v0 o>| (v o>| 'clfy o>Mod a_ ) o>Mod a'\n                : 'Mod(0 WV' |- [0 'D0| A1 ~> A3 ]0)0 )\n\n  (* non-necessary, deductible *)\n  | Classifying_morphismPre_DeClass :\n      forall (V V' : obV log) (v : V(0 V' |- V )0 ) (A1 A2 : obMod) (b : 'D(0 V |- [0 A1 ~> A2 ]0 )0)\n        (W : obV log) (A3 : obMod) (a' : 'Mod(0 W |- [0 A2 ~> A3 ]0 )0),\n      forall (WV' : obV log) (v0 : V(0 WV' |- (0 W & V' )0 )0),\n        ( ( log.-1 ) o>| 'clfy o>Mod ( ( v0 o> (0 _ & v )1 ) o>| b o>D a' ) )\n          ~~~ ( v0 o>| (v o>| 'clfy o>Mod b ) o>D a'\n              : 'D(0 WV' |- [0 'D0| A1 ~> A3 ]0)0 )\n\n  | Classifying_morphismPost :\n      forall (V V' : obV log) (v : V(0 V' |- (0 V & log.-I )0 )0) (A1 A2 : obMod) (a_ : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0)\n        (W W' : obV log) (w : V(0 W' |- W )0) (A3 : obMod) (a' : 'Mod(0 W |- [0 A2 ~> A3 ]0 )0),\n      forall (W'V' : obV log) (v0 : V(0 W'V' |- (0 W' & V' )0 )0),\n        ( ( log.-1 )\n            o>| 'clfy o>Mod ( v0 o>| ( ( v o> desIdenObRK ) o>' a_ ) o>Mod (w o>' a') ) )\n          ~~~ ( v0 o>| ( v o>| 'D1| a_ ) o>Mod ( w o>| 'clfy o>Mod a' )\n                : 'Mod(0 W'V' |- [0 'D0| A1 ~> A3 ]0)0 ) \n\n  | DeClassifying_morphismPost :\n      forall (V : obV log) (A1 A2 : obMod) (b_ : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0)\n        (W W' : obV log) (w : V(0 W' |- W )0) (A3 : obMod) (b' : 'D(0 W |- [0 A2 ~> A3 ]0 )0),\n      forall (W'V : obV log) (w0 : V(0 W'V |- (0 W' & V )0 )0),\n        ( log.-1 o>| ( ( w0 o> (1 w & _ )0 ) o>| b_ o>Mod b' ) o>Mod 'declfy )\n          ~~~ ( w0 o>| b_ o>Mod ( w o>| b' o>Mod 'declfy )\n                : 'D(0 W'V |- [0 A1 ~> 'D0| A3 ]0)0 )\n\n  | DeClassifying_morphismPre :\n      forall (V V' : obV log) (v : V(0 V' |- V )0) (A1 A2 : obMod) (b_ : 'D(0 V |- [0 A1 ~> A2 ]0 )0)\n        (W W' : obV log) (w : V(0 W' |- (0 W & log.-I )0 )0) (A4 : obMod) (b' : 'Mod(0 W |- [0 A2 ~> A4 ]0 )0),\n      forall (W'V' : obV log) (wv : V(0 W'V' |- (0 W' & V' )0 )0),\n        ( log.-1 o>| ( wv o>| ( v o>' b_ ) o>D ( ( w o> desIdenObRK ) o>' b') ) o>Mod 'declfy )\n          ~~~ ( wv o>| ( v o>| b_ o>Mod 'declfy ) o>D ( w o>| 'D1| b' )\n              : 'D(0 W'V' |- [0 A1 ~> 'D0| A4 ]0)0 )\n\n  | CancelOuter : forall (V V' : obV log) (v : V(0 V' |- V )0) (B : obMod) (A : obMod)\n                    (b : 'D(0 V |- [0 B ~> A ]0 )0) (A' : obMod)\n                    (W W' : obV log) (w : V(0 W' |- W )0) (a : 'Mod(0 W |- [0 'D0| A ~> A' ]0 )0),\n      forall (W'V' : obV log) (wv : V(0 W'V' |- (0 W' & V' )0 )0),\n     ( wv o>| ( v o>' b ) o>Mod ( w o>' a ) )\n       ~~~ ( wv o>| ( v o>| b o>Mod 'declfy ) o>Mod ( w o>| 'clfy o>Mod a )\n                          : 'Mod(0 W'V' |- [0 B ~> A' ]0)0 )\n\n  | CancelInner : forall (V V' : obV log) (v : V(0 V' |- V )0) (B : obMod) (A : obMod)\n                    (b : 'D(0 V |- [0 B ~> A ]0 )0) (A' : obMod)\n                    (W W' : obV log) (w : V(0 W' |- W )0) (a : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n      forall (W'V' : obV log) (wv : V(0 W'V' |- (0 W' & V' )0 )0),\n      ( wv o>| (v o>' b) o>D (w o>' a) )\n        ~~~ ( wv o>| (v o>| b o>Mod 'declfy ) o>D (w o>| 'clfy o>Mod a )\n                        : 'D(0 W'V' |- [0 B ~> A' ]0)0 )\n\n  | PermOuterInner : forall (V V' : obV log) (v : V(0 V' |- V )0) (B : obMod) (A : obMod)\n                       (b : 'D(0 V |- [0 B ~> A ]0 )0) (W W' : obV log) (w : V(0 W' |- W )0)\n                       (u : V(0 W |- log.-I )0),\n      forall (W'V' : obV log) (wv : V(0 W'V' |- (0 W' & V' )0 )0),\n      ( wv o>| ( ( log.-(1 w & _ )0 o> log.-(1 u & _ )0 o> desIdenObLK ) o>| ( v o>' b ) o>Mod 'declfy ) o>Mod 'declfy )\n        ~~~ ( wv o>| ( v o>| b o>Mod 'declfy ) o>D ( w o>| (u o>| uMod) o>Mod 'declfy )\n              : 'D(0 W'V' |- [0 B ~> 'D0| 'D0| A ]0)0 )\n\n  where \"f2 ~~~ f1\" := (@convMod _ _ _ _ f2 f1).\n\n  Hint Constructors convMod.\n\n  Hint Extern 4 (_ ~~?lo` _) => eapply (@ReflV lo _).\n  Ltac rewriterMod := repeat match goal with | [ HH : @eq (Mod00 _ _ _) _ _  |- _ ] =>  try rewrite -> HH in *; clear HH end. \n\n(**#+END_SRC\n\nDescriptions for the congruent rewriting tactics :\n\n#+BEGIN_SRC coq :exports both :results silent **)\n\n  Add Parametric Relation {log : logic} (V : obV log) (A1 A2 : obMod) :\n    ('Mod(0 V |- [0 A1 ~> A2 ]0 )0) (@convMod log V A1 A2)\n        reflexivity proved by (@Mod_ReflV log V A1 A2)\n        symmetry proved by (@Mod_SymV log V A1 A2)\n        transitivity proved by\n        (fun x y z r1 r2 =>  ((@Mod_TransV log V A1 A2) y z r2 x r1))\n          as convMod_rewrite.\n\n  Add Parametric Relation {log : logic} (V1 V2 : obV log) :\n    (log.-V(0 V1 |- V2 )0) (@convV log V1 V2)\n      reflexivity proved by (@ReflV log log V1 V2)\n      symmetry proved by (fun x => (@SymV log log V1 V2)^~ x)\n      transitivity proved by\n      (fun x y z r1 r2 =>  ((@TransV log log V1 V2) y z r2 x r1))\n        as convV_rewrite.\n\n  Add Parametric Morphism {log : logic} (V V' : obV log) (A1 A2 : obMod) :\n    (@PolyV_Mod_rewrite log V V' A1 A2) with\n      signature ((@convV log V' V)\n                   ==> (@convMod log V A1 A2)\n                   ==> (@convMod log V' A1 A2))\n        as PolyV_Mod_cong_rewrite.\n      by move => *; apply: PolyV_Mod_cong. Qed.\n\n  Add Parametric Morphism {log : logic} (V V' : obV log) (A1 A2 : obMod_gen)\n      (aGen : Mod_gen V A1 A2) :\n    (@GenArrowsMod log V V' A1 A2 aGen) with\n      signature ((@convV log V' V)\n                   ==> (@convMod log V' (#0| A1) (#0| A2)))\n        as GenArrowsMod_cong_rewrite.\n      by move => *; apply: GenArrowsMod_cong. Qed.\n\n  Add Parametric Morphism {log : logic} (V : obV log) (A : obMod)\n    : (@UnitMod log V A) with\n      signature ((@convV log V log.-I)\n                   ==> (@convMod log V A A))\n        as UnitMod_cong_rewrite.\n      by move => *; apply: UnitMod_cong. Qed.\n\n  Add Parametric Morphism {log : logic} (V : obV log) (A A' : obMod)\n      (W : obV log) (A'' : obMod) (WV : obV log) :\n    (@PolyMod_rewrite log V A A' A'' W WV ) with\n      signature ((@convV log WV ((0 W & V)0) )\n                 ==>(@convMod log V A A')\n                 ==> (@convMod log W A' A'')\n                 ==> (@convMod log WV A A''))\n        as Mod_cong_rewrite.\n      by move => *; apply: Mod_cong. Qed.\n\n  Add Parametric Morphism {log : logic} (A A' : obMod) (W W' : obV log) :\n    (@UnitDeClass log A A' W W') with\n      signature ( (@convV log W' ((0 W & log.-I )0) )\n                    ==> (@convMod log W A A')\n                    ==> (@convMod log W' ('D0| A) ('D0| A')))\n        as UnitDeClass_cong_rewrite.\n      by move => *; apply: UnitDeClass_cong. Qed.\n\n  Add Parametric Morphism {log : logic} (V : obV log) (B A A' : obMod) (W WV : obV log) :\n    (@PolyDeClass_rewrite log V B A A' W WV) with\n      signature ((@convV log WV ((0 W & V )0) )\n                   ==> (@convMod log V B ('D0| A))\n                   ==> (@convMod log W A A')\n                   ==> (@convMod log WV B ('D0| A')))\n        as PolyDeClass_cong_rewrite.\n      by move => *; apply: PolyDeClass_cong. Qed.\n\n  Add Parametric Morphism {log : logic} (V V' : obV log) (A1 A2 : obMod) :\n    (@Classifying log V V' A1 A2) with\n      signature ((@convV log V' V)\n                   ==> (@convMod log V A1 A2)\n                   ==> (@convMod log V' ('D0| A1) A2))\n        as Classifying_cong_rewrite.\n      by move => *; apply: Classifying_cong. Qed.\n\n  Add Parametric Morphism {log : logic} (V V' : obV log) (A1 A2 : obMod) :\n    (@DeClassifying log V V' A1 A2) with\n      signature ((@convV log V' V)\n                   ==> (@convMod log V A1 ('D0| A2))\n                   ==> (@convMod log V' A1 ('D0| ('D0| A2))))\n        as DeClassifying_cong_rewrite.\n      by move => *; apply: DeClassifying_cong. Qed.\n\n(**#+END_SRC\n\n* Iterated constructors\n\n** Indexed list, lemmas\n\nSome definitions :\n\n#+BEGIN_SRC coq :exports both :results silent **)\n\n  Module Import Destruct_hlist.\n\n    Inductive hlist (A : Type) (B  : A -> Type)\n    : list A -> Type :=\n    | HNil : hlist B nil\n    | HCons : forall (x : A) (ls : list A), B x -> hlist B ls -> hlist B (x :: ls).\n\n    Implicit Arguments HNil [A B].\n    Implicit Arguments HCons [A B x ls].\n\n    Infix \":::\" := HCons (right associativity, at level 60).\n\n    Section Section1.\n      Variable (A : Type) (B1 B2 : A -> Type).\n      Variable f : forall x, B1 x -> B2 x.\n\n      Fixpoint hmap (ls : list A) (hl : hlist B1 ls) : hlist B2 ls :=\n        match hl with\n        | HNil => HNil\n        | HCons _ _ x hl' => f x ::: hmap hl'\n        end.\n    End Section1.\n\n    Implicit Arguments hmap [A B1 B2 ls].\n\n(**#+END_SRC\n\nLemmas for (dependent-)destruction by inner instantiations of indices :\n\n#+BEGIN_SRC coq :exports both :results silent **)\n\n    Section Section2.\n\n    Variables (A : Type) (B  : A -> Type).\n\n    Inductive hlist_nil : hlist B ( [::]) -> Type :=\n    | Hlist_nil : hlist_nil (HNil : hlist B [::]).\n\n    Inductive hlist_cons : forall (a : A) (ls' : list A), hlist B (a :: ls') -> Type :=\n    | Hlist_cons : forall a ls' (ba : B a) (hls' : hlist B ls'),\n          @hlist_cons a ls' (ba ::: hls' : hlist B ([:: a & ls'])).\n\n    Definition hlist_destructP_type : forall (ls : list A) (hls : hlist B ls), Type.\n    Proof.\n      move => ls. case : ls => [ | a ls'] hls.\n      - refine (@hlist_nil hls).\n      - refine (@hlist_cons a ls' hls).\n    Defined.\n\n    Definition hlist_destructP : forall (ls : list A) (hls : hlist B ls),\n        @hlist_destructP_type ls hls.\n    Proof.\n      move => ls hls. case: ls / hls.\n      rewrite /hlist_destructP_type /=.\n      - constructor.\n      - constructor.\n    Defined.\n\n    (* type indeed computes: ... \n    Definition hlist_cons_destructP (a : A) (ls' : list A)\n               (hls : hlist B (a :: ls')) :\n      (@hlist_cons a ls' hls).\n    Proof.\n      apply: (hlist_destructP hls ).\n    Defined. *)\n\n    Definition hlist_eta_type : forall  (ls : list A) (hls : hlist B ( ls)), Type.\n    Proof.\n      move => ls hls. refine (hls = _ ). move: hls. case: ls.\n      - move => _ . exact: HNil.\n      - move => a ls' hls'. refine (_ ::: _).\n        + case: a ls' hls' / (hlist_destructP hls') => a ls' ba _.\n          exact: ba. (* hhd *)\n        + case: a ls' hls' / (hlist_destructP hls') => a ls' _ hls'.\n          exact: hls'. (* htl *)\n    Defined. \n\n    Lemma hlist_eta : forall  (ls : list A) (hls : hlist B ( ls)),\n        @hlist_eta_type ls hls.\n    Proof.\n      move => ls hls. case: ls / hls.\n      rewrite /hlist_eta_type. reflexivity.\n      rewrite /hlist_eta_type. reflexivity.\n    Defined.\n\n    (* memo: may .. *)\n    Definition tl_hlist_type : forall  (ls : list A) (hls : hlist B ( ls)), Type.\n    Proof.\n      move => ls. case: ls.\n      - move => _ . refine (hlist B [::]).\n      - move => a ls' hls'. refine (hlist B ls').\n    Defined.\n\n    Definition tl_hlist : forall  (ls : list A) (hls : hlist B ( ls)), tl_hlist_type hls.\n    Proof.\n      move => ls. case: ls => /=.\n      - move => hls. exact: hls.\n      - move => a ls' hls. case: a ls' hls / (hlist_destructP hls) => a ls' _ hls'.\n        exact: hls'.\n    Defined.\n    \n    End Section2.\n\n  End Destruct_hlist.\n  \n(**#+END_SRC\n\n** Chained lists, lemmas\n\nSome definitions :\n\n#+BEGIN_SRC coq :exports both :results silent **)\n  \n  Fixpoint chain (T : Type) (ls : list T) {struct ls} : list (prod T T) :=\n    match ls with\n    | nil => nil\n    | cons t0 ls' => match ls' with\n                    | nil => nil\n                    | cons t1 ls'' => (t0, t1) :: chain ls'\n                    end \n    end.\n\n  Arguments chain : simpl nomatch.\n  Eval compute in chain [:: 0; 11; 2; 3].\n\n  Inductive chain_graph (T : Type) : list T -> list (prod T T) -> Type :=\n  | Chain_nil :  chain_graph [::] (chain [::])\n  | Chain_cons_nil :  forall t0 : T, chain_graph [:: t0] (chain [:: t0])\n  | Chain_cons_cons : forall (t0 t1 : T) (ls'' : list T),\n        chain_graph (t1 :: ls'') (chain ([:: t1 & ls'']))\n        -> chain_graph (t0 :: t1 :: ls'') ((t0 , t1) :: chain ([:: t1 & ls''])) .\n\n  Lemma chain_graphP (T : Type) :\n    forall  (ls : list T), chain_graph ls (chain ls).\n  Proof.\n    induction ls as [|t0 ls']. constructor 1.\n    destruct ls' as [|t1 ls'']. constructor 2.\n    simpl.  constructor 3. exact:  IHls'.\n  Defined.\n\n  Definition toArrowV {log : logic} {trf : obV log -> obV log}\n             (V1V2 : prod (obV log) (obV log))\n    := V(0 trf V1V2.1 |- trf V1V2.2 )0.\n  \n  Definition arrowList {log : logic} {trf : obV log -> obV log} ls\n    := (hlist (@toArrowV log trf) (chain ls)).\n\n(**#+END_SRC\n\nLemmas for (dependent-)destruction by inner instantiations of indices :\n\n#+BEGIN_SRC coq :exports both :results silent **)\n\n  Module Import Destruct_arrowList.\n    \n    Inductive arrowList_nil {log : logic} {trf : obV log -> obV log}\n    : hlist (toArrowV (trf:=trf)) (chain [::]) -> Type :=\n    | ArrowList_nil : arrowList_nil (HNil : arrowList [::]).\n\n    Inductive arrowList_cons_nil {log : logic} {trf : obV log -> obV log}\n      : forall V0 : (obV log), hlist (toArrowV (trf:=trf)) (chain [:: V0]) -> Type :=\n    | ArrowList_cons_nil : forall V0, @arrowList_cons_nil log trf V0 (HNil : arrowList [:: V0]).\n\n    Inductive arrowList_cons_cons {log : logic} {trf : obV log -> obV log}\n      : forall (V0 V1 : obV log) (Vs'' : list (obV log)),\n        hlist (toArrowV (trf:=trf)) ((V0 , V1) :: (chain (V1 :: Vs''))) -> Type :=\n    | ArrowList_cons_cons :\n        forall V0 V1 Vs'' (v01 : toArrowV (V0 , V1))\n          (vs' : hlist (toArrowV (trf:=trf)) (chain [:: V1 & Vs''])),\n          @arrowList_cons_cons log trf V0 V1 Vs''\n          (v01 ::: vs' : hlist (toArrowV (trf:=trf)) ((V0 , V1) :: (chain [:: V1 & Vs'']))).\n\n    Definition arrowList_destructP_type {log : logic}{trf : obV log -> obV log} :\n      forall (Vs : list (obV log)) (vs : hlist (toArrowV (trf:=trf)) (chain Vs)), Type.\n    Proof.\n      move => Vs. case: Vs (chain Vs) / (chain_graphP Vs) =>\n                 [ | V0 | V0 V1 Vs'' V1Vs''_chain_graph ] vs.\n      - refine (@arrowList_nil log trf vs).\n      - refine (@arrowList_cons_nil log trf V0 vs).\n      - refine (@arrowList_cons_cons log trf V0 V1 Vs'' vs).\n    Defined.\n\n    Definition arrowList_destructP {log : logic}{trf : obV log -> obV log} :\n      forall (Vs : list (obV log)) (vs : hlist (toArrowV (trf:=trf)) (chain Vs)),\n        @arrowList_destructP_type log trf Vs vs.\n    Proof.\n      move => Vs. rewrite /arrowList_destructP_type.\n      case: Vs (chain Vs) / (chain_graphP Vs) =>\n      [ | V0 | V0 V1 Vs'' V1Vs''_chain_graph ] vs.\n      - case : vs / (hlist_destructP vs). constructor.\n      - case : vs / (hlist_destructP vs). constructor.\n      - (* /!\\ *) rewrite (hlist_eta vs). constructor.\n    Defined.\n\n    (* indeed computes: \n    Definition arrowList_cons_cons_destructP {log : logic}{trf : obV log -> obV log} :\n      forall V0 V1 Vs'' (vs : hlist (toArrowV (trf:=trf)) (chain [:: V0, V1 & Vs''])),\n        @arrowList_cons_cons log trf V0 V1 Vs'' vs.\n    Proof.\n      move => V0 V1 Vs'' vs. exact: (arrowList_destructP vs).\n    Defined. *)\n\n  End Destruct_arrowList.\n\n  Inductive arrowList_prop {log : logic} {trf : obV log -> obV log}\n    : forall ls : list (obV log),\n      hlist (toArrowV (trf:=trf)) (chain ls) -> Type :=\n  | ArrowList_nil : arrowList_prop (HNil : arrowList [::])\n  | ArrowList_cons_nil : forall V0, arrowList_prop (HNil : arrowList [:: V0])\n  | ArrowList_cons_cons :\n      forall V0 V1 (v01 : toArrowV (V0, V1)) Vs'' (vs' : arrowList (V1 :: Vs'')),\n        arrowList_prop vs' ->\n        arrowList_prop (v01 ::: vs' : arrowList (V0 :: V1 :: Vs'')).\n\n  Lemma arrowListP {log : logic}{trf : obV log -> obV log} :\n    forall (Vs : list (obV log)) (vs :arrowList Vs),\n      (@arrowList_prop log trf Vs vs).\n  Proof.\n    move => Vs. move: (chain_graphP Vs) => Vs_chainInputP.\n    elim : Vs {-}(chain Vs) / Vs_chainInputP.\n    - move => vs. case: (arrowList_destructP vs).\n      apply: ArrowList_nil.\n    - move => V0 vs. case: V0 vs / (arrowList_destructP vs) => V0.\n      apply: ArrowList_cons_nil.\n    - intros V0 V1 Vs'' (*ch_V1Vs''_P*) _ IHVs' vs''. move: IHVs'.\n      case: V0 V1 Vs'' vs'' / (arrowList_destructP vs'') =>\n      V0 V1 Vs'' v01 vs' IHVs'.\n      apply: (ArrowList_cons_cons v01 (IHVs' vs')).\n  Defined.\n\n(**#+END_SRC\n\n** Iterated constructors\n\nSome definitions :\n\n#+BEGIN_SRC coq :exports both :results silent **)\n    \n  Definition iterDeClass0 (n : nat) : obMod -> obMod\n    := iter n DeClass0 .\n\n  Definition iterDeClassifying {log : logic} {trf : obV log -> obV log}\n             (V_dft : obV log) (B A : obMod) \n    : forall (Vs : list (obV log)) (vs : (hlist (toArrowV (trf:=trf)) (chain Vs)))\n        (b : 'D(0 trf (last V_dft Vs) |- [0 B ~> A ]0 )0),\n      'D(0 trf(head V_dft Vs) |- [0 B ~> iterDeClass0 (length Vs).-1 A ]0 )0.\n  Proof.\n    move => Vs vs. move: (arrowListP (trf:=trf) vs) => vs_arrowListP.\n    elim : vs_arrowListP => /= .\n    - move => b; exact: b.\n    - move => V0 b; exact: b.\n    - move => V0 V1 v01 Vs'' vs' vs'_arrowListP vs'_IH b.\n      refine (v01 o>| (vs'_IH b)  o>Mod 'declfy).\n  Defined.\n\n  Notation \"vs o>|| a o>Mod ''declfy\" :=\n    (@iterDeClassifying _ _ _ _ _ _ vs a)\n      (at level 25, a at next level, right associativity).\n  \n  Definition iterDeClassifying_rewrite_type {log : logic}{trf : obV log -> obV log}\n             (V_dft : obV log)\n             (B A : obMod) (Vs : list (obV log)) (vs : (hlist (toArrowV (trf:=trf)) (chain Vs))) : Prop.\n  Proof.\n    case: (arrowListP vs).\n    - refine ( forall (b : 'D(0 trf(last V_dft [::]) |- [0 B ~> A ]0 )0),\n                 iterDeClassifying (V_dft := V_dft) (HNil : arrowList ([::])) b = b ).\n    - move => V0.\n      refine ( forall (b : 'D(0 trf(last V0 [::]) |- [0 B ~> A ]0 )0),\n                 iterDeClassifying (V_dft := V_dft) (HNil : arrowList ([:: V0])) b = b ).\n    - move => V0 V1 v01 Vs'' vs' _ .\n      refine ( forall (b : 'D(0 trf(last V1 Vs'') |- [0 B ~> A ]0 )0),\n            iterDeClassifying (V_dft := V_dft) (v01 ::: vs' : arrowList (V0 :: V1 :: Vs'')) b\n            = v01 o>| ( iterDeClassifying (V_dft := V_dft) vs' b ) o>Mod 'declfy ).\n  Defined.\n\n(**#+END_SRC\n\nSome lemmas for the rewrite tactics :\n\n#+BEGIN_SRC coq :exports both :results silent **)\n\n  Lemma iterDeClassifying_rewrite {log : logic}{trf : obV log -> obV log} {V_dft : obV log} {B A : obMod} \n        (Vs : list (obV log)) (vs : arrowList Vs) :\n    @iterDeClassifying_rewrite_type log trf V_dft B A Vs vs.\n  Proof.\n    rewrite /iterDeClassifying_rewrite_type.\n    case: (arrowListP vs); reflexivity.\n  Defined.\n\n  Notation RHSc := (X in _ ~~~ X)%pattern.\n  Notation LHSc := (X in X ~~~ _)%pattern.\n\n  Definition tac_arrows := (@Mod_arrowPre, @Mod_arrowPost,\n                            @UnitDeClass_arrow, @DeClass_arrowPre,\n                            @DeClass_arrowPost, @Classifying_arrow, @DeClassifying_arrow).\n\n(**#+END_SRC\n\nSome deduced conversion relations over the generated morphisms :\n\n#+BEGIN_SRC coq :exports both :results silent **)\n\n  Hint Extern 4 (_ ~~?lo` _) => eapply (@SymV lo _) : logic_hints.\n  Hint Resolve PolyV_unitPost : logic_hints.\n  Hint Resolve PolyV_unitPre : logic_hints.\n\n  Lemma GenArrowsMod_arrowLog_id {log : logic} :\n    forall (V' V'' : obV log) (A1 A2 : obMod_gen) (aGen : Mod_gen V' A1 A2)\n      (v' : V(0 V'' |- V' )0),\n      ( ( v' ) o>| #1| aGen )\n        ~~~ (v' o>' (log.-1 o>| #1| aGen) ).\n  Proof. eauto with logic_hints.   Qed.\n\n  Lemma UnitMod_arrowLog_id {log : logic} :\n    forall (V' : obV log) (A : obMod)\n      (v' : V(0 V' |- log.-I )0),\n      ( ( v' ) o>| @uMod A )\n        ~~~ (v' o>' (log.-1 o>| @uMod A) ).\n  Proof. eauto with logic_hints. Qed.\n\n  Lemma Mod_arrowLog_id {log : logic} :\n    forall (V : obV log) (A0 : obMod) (A : obMod)\n      (a_ : 'Mod(0 V |- [0 A0 ~> A ]0 )0),\n    forall (W : obV log) (A' : obMod) (a' : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n    forall (WV0 : obV log) (v0 : V(0 WV0 |- (0 W & V )0 )0),\n      ( ( v0 ) o>| a_ o>Mod a' )\n        ~~~ ( v0 o>' ( log.-1 o>| a_ o>Mod a' ) ).\n  Proof. eauto with logic_hints.  Qed.\n\n  Lemma UnitDeClass_arrowLog_id {log : logic} :\n    forall (W W'' : obV log)\n      (w' : V(0 W'' |- (0 W & log.-I )0 )0)\n      (A A' : obMod) (a : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n      ( ( w' ) o>| 'D1| a )\n        ~~~ (  w' o>' ( log.-1 o>| 'D1| a ) ).\n  Proof. eauto with logic_hints.  Qed.\n  \n  Lemma  DeClass_arrowLog_id {log : logic} :\n    forall (V : obV log) (B : obMod) (A : obMod)\n      (b : 'D(0 V |- [0 B ~> A ]0 )0),\n    forall (W : obV log) (A' : obMod) (a : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n    forall (WV0 : obV log) (v0 : V(0 WV0 |- (0 W & V )0  )0),\n      ( ( v0  ) o>| b o>D a )\n        ~~~ ( v0 o>' ( log.-1 o>| b o>D a ) ).\n  Proof. eauto with logic_hints.  Qed.\n\n  Lemma Classifying_arrowLog_id {log : logic} :\n    forall (V' V'' : obV log) (v0 : V(0 V'' |- V' )0)\n      (A1 A2 : obMod)\n      (a : 'Mod(0 V' |- [0 A1 ~> A2 ]0 )0),\n      ( ( v0 ) o>| 'clfy o>Mod a )\n        ~~~ ( v0 o>' ( log.-1 o>| 'clfy o>Mod a ) ).\n  Proof. eauto with logic_hints.  Qed.\n\n  Lemma DeClassifying_arrowLog_id {log : logic} :\n    forall (V' V'' : obV log)  (v0 : V(0 V'' |- V' )0) (A1 A2 : obMod)\n      (a : 'D(0 V' |- [0 A1 ~> A2 ]0 )0),\n      ( ( v0 ) o>| a o>Mod 'declfy )\n        ~~~ ( v0 o>' ( log.-1 o>| a o>Mod 'declfy ) ).\n  Proof. eauto with logic_hints.  Qed.\n\n(**#+END_SRC\n\nSome purely-logical lemmas :\n\n#+BEGIN_SRC coq :exports both :results silent **)\n\n  Lemma logic_decidable0 : forall {log : logic} (V : obV log),\n      log.-1 ~~log` desIdenObLKV o>`log`>\n         log.-(1 log.-1 & V )0 o>`log`> desIdenObLK .\n  Admitted.\n  Hint Resolve logic_decidable0 : logic_hints.\n\n  Lemma logic_decidable1 : forall {log : logic}\n                             (V W _WV WV : obV log)\n                             (w : log.-V(0 WV |- log.-(0 W & V )0 )0)\n                             (w0 : log.-V(0 _WV |- WV )0),\n      w0 o>`log`> w ~~log` log.-1 o>`log`> (w0 o>`log`> w) o>`log`> log.-(1 log.-1 & V )0.\n  Admitted.\n  Hint Resolve logic_decidable1 : logic_hints.\n  \n  Lemma logic_decidable2 : forall {log : logic}\n                             (V W WV' : obV log)\n                             (v0 : log.-V(0 WV' |- log.-(0 W & V )0 )0),\n      v0 ~~log` (v0 o>`log`> log.-(1 desIdenObRKV & V )0)\n         o>`log`> log.-(1 log.-1 o>`log`> desIdenObRK & V )0.\n  Admitted.\n  Hint Resolve logic_decidable2 : logic_hints.\n\n  Lemma logic_decidable3 : forall {log : logic}\n                             (W' W_ W'W_ : obV log)\n                             (v : log.-V(0 W'W_ |- log.-(0 W' & W_ )0 )0)\n                             (W'W_I : obV log)\n                             (v0 : log.-V(0 W'W_I |- log.-(0 W'W_ & log.-I )0 )0),\n      v0 o>`log`> log.-(1 v & log.-I )0 ~~log`\n         ((v0 o>`log`> log.-(1 v & log.-I )0 o>`log`> Assoc_Rev) o>`log`> desIdenObRKV)\n         o>`log`> log.-(1 log.-1 o>`log`> (0 W' & log.-1 o>`log`> desIdenObRK )1 & log.-I )0.\n  Admitted.\n  Hint Resolve logic_decidable3 : logic_hints.\n\n  Lemma logic_decidable4 : forall {log : logic}\n                             (V W_ W' W'W_ : obV log)\n                             (v : log.-V(0 W'W_ |- log.-(0 W' & W_ )0 )0)\n                             (W'W_V : obV log)\n                             (v0 : log.-V(0 W'W_V |- log.-(0 W'W_ & V )0 )0),\n      v0 o>`log`> log.-(1 v & V )0 ~~log` (v0 o>`log`> log.-(1 v & V )0 o>`log`> Assoc_Rev)\n         o>`log`> (0 W' & log.-1 )1 o>`log`> Assoc .\n  Admitted.\n  Hint Resolve logic_decidable4 : logic_hints.\n\n  Lemma logic_decidable7 :\n    forall {log : logic} (Vb Vb' : obV log) (vb : log.-V(0 Vb' |- Vb )0) (V0Vb' trfV0 trfV1 : obV log)\n      (v01 : log.-V(0 trfV0 |- trfV1 )0) (v0b : log.-V(0 V0Vb' |- log.-(0 trfV0 & Vb' )0 )0),\n      \n(v0b o>`log`> (0 trfV0 & vb )1) o>`log`> log.-(1 v01 & Vb )0 ~~log`\n(((((v0b o>`log`> log.-(1 desIdenObRKV & Vb' )0) o>`log`> \nlog.-(1 (log.-1 o>`log`> log.-(1 v01 o>`log`> desIdenObLKV & log.-I )0 \no>`log`> Assoc_Rev) o>`log`> \nlog.-(1 desIdenObRKV & log.-(0 trfV1 & log.-I )0 )0 & Vb' )0 \no>`log`> Assoc_Rev) o>`log`> (0 log.-(0 log.-I & log.-I )0 & \n(log.-1 o>`log`> log.-(1 log.-1 o>`log`> desIdenObRK & Vb' )0) \no>`log`> log.-(1 desIdenObRKV & Vb' )0 )1 o>`log`> Assoc) \no>`log`> (0 log.-(0 log.-(0 log.-I & log.-I )0 & \nlog.-(0 trfV1 & log.-I )0 )0 & vb )1) o>`log`> \nlog.-(1 (log.-1 o>`log`> desIdenObRKV) o>`log`> desIdenObRK & Vb )0) \no>`log`> log.-(1 (log.-1 o>`log`> ((log.-1 o>`log`> \nlog.-(1 log.-1 o>`log`> desIdenObRK & log.-(0 trfV1 & log.-I )0 )0) \no>`log`> log.-(1 log.-1 & log.-(0 trfV1 & log.-I )0 )0) \no>`log`> log.-(1 log.-1 & log.-(0 trfV1 & log.-I )0 )0 \no>`log`> desIdenObLK) o>`log`> log.-1 o>`log`> desIdenObRK & Vb )0 .\n\n  Admitted.\n  Hint Resolve logic_decidable7 : logic_hints.\n\n(**#+END_SRC\n\nSome more deduced conversion relations over the morphisms, this time the\norientation-of-the-most-general is reversed\n\n#+BEGIN_SRC coq :exports both :results silent **)\n\n  Lemma Mod_inputUnitMod_rev {log : logic} :\n    forall (V : obV log) (B : obMod) (A : obMod) (b : 'Mod(0 V |- [0 B ~> A ]0 )0),\n      ( b )\n        ~~~  ( desIdenObLKV o>| b o>Mod ( log.-1 o>| uMod ) ).\n  Proof. eauto with logic_hints. (* intros. rewrite -Mod_inputUnitMod. rewrite [LHSc]PolyV_Mod_unit.\n               eapply PolyV_Mod_cong; [| reflexivity].\n               clear. exact: logic_decidable0. *) Qed.  \n  \n  Lemma DeClassifying_morphismPost_rev {log : logic} :\n    forall (V : obV log) (A1 A2 : obMod) (b_ : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0)\n      (W _WV : obV log)  (A3 : obMod) (b' : 'D(0 W |- [0 A2 ~> A3 ]0 )0),\n    forall (WV : obV log) (w : V(0 WV |- (0 W & V )0 )0) (w0 : V(0 _WV |- WV )0),\n      ( w0 o>| ( w  o>| b_ o>Mod b' ) o>Mod 'declfy )\n        ~~~ ( (w0 o> w) o>| b_ o>Mod ( log.-1 o>| b' o>Mod 'declfy ) ).\n  Proof. \n    intros. rewrite -[in RHSc]DeClassifying_morphismPost. rewrite [in LHSc]Mod_arrowLog_id. rewrite -[in LHSc]DeClassifying_arrow.\n    rewrite [in RHSc]Mod_arrowLog_id. rewrite -[in RHSc]DeClassifying_arrow. eauto with logic_hints.\n  Qed.\n  \n  Lemma DeClass_morphismPre_rev {log : logic} :\n    forall (A : obMod) (V : obV log) (B : obMod) (b' : 'D(0 V |- [0 B ~> A ]0 )0),\n    forall (W : obV log)  (A' : obMod) (a : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n    forall (WV' : obV log) (v0 : V(0 WV' |- (0 W & V )0 )0),\n      ( v0  o>| b' o>D ( a ) )\n        ~~~ ( (v0 o> ((1 desIdenObRKV & _  )0))  o>| b' o>Mod ( log.-1 o>| 'D1| a )\n              : 'D(0 WV' |- [0 B ~> A' ]0)0 ).\n  Proof.\n    intros. rewrite -[in RHSc]DeClass_morphismPre.\n    rewrite -DeClass_arrowPost. eauto with logic_hints.\n  Qed.\n  \n  Lemma DeClass_morphismPost_rev {log : logic}:\n    forall (A : obMod)\n      (W' W_ W'W_ : obV log) (v : V(0 W'W_ |- (0 W' & W_ )0 )0) (A' : obMod) (a_ : 'Mod(0 W_ |- [0 A ~> A' ]0 )0)\n      (A'' : obMod) (a' : 'Mod(0 W' |- [0 A' ~> A'' ]0 )0),\n    forall (W'W_I : obV log) (v0 : V(0 W'W_I |- (0 W'W_ & log.-I )0 )0),\n      ( v0 o>| 'D1| ( v o>| a_ o>Mod a' ) )\n        ~~~ ( (v0 o> (1 v & _ )0 o> Assoc_Rev) o>| ( (log.-1) o>| 'D1| a_ ) o>D a'\n              : 'D(0 W'W_I |- [0 'D0| A ~> A'' ]0)0 ).\n  Proof.\n    intros. rewrite -[in RHSc]DeClass_morphismPost.\n    rewrite -[in RHSc]Mod_arrowPre.   rewrite [in RHSc]Mod_arrowLog_id. rewrite -[in RHSc]UnitDeClass_arrow. rewrite [in LHSc]Mod_arrowLog_id. rewrite -[in LHSc]UnitDeClass_arrow.\n    eauto with logic_hints.\n  Qed.\n\n  Lemma Mod_morphism_rev :\n    forall {log : logic} (V : obV log) (B : obMod) (A : obMod) (b : 'Mod(0 V |- [0 B ~> A ]0 )0)\n      (W_ : obV log) (A' : obMod) (a_ : 'Mod(0 W_ |- [0 A ~> A' ]0 )0)\n      (W' : obV log) (A'' : obMod) (a' : 'Mod(0 W' |- [0 A' ~> A'' ]0 )0),\n    forall (W'W_ : obV log) (v : V(0 W'W_ |- (0 W' & W_ )0 )0),\n    forall (W'W_V : obV log) (v0 : V(0 W'W_V |- (0 W'W_ & V )0 )0),\n      ( v0 o>| b o>Mod ( v o>| a_ o>Mod a' ) )\n        ~~~ ( (v0 o> (1 v & _ )0 o> Assoc_Rev) o>| ( (log.-1) o>| b o>Mod a_ ) o>Mod a' ).\n  Proof.\n    intros. rewrite -Mod_morphism.\n    rewrite [X in _ o>| _ o>Mod X ~~~ _]Mod_arrowLog_id.\n    rewrite -[in LHSc]Mod_arrowPost. eauto with logic_hints.\n  Qed.\n\n(**#+END_SRC\n\nFinally the deduced corresponding conversion relations for the iterated constructors :\n\n#+BEGIN_SRC coq :exports both :results silent **)\n\n  Module Import Iter_deduce.\n\n    Module Import Ex_Notations.\n\n    Delimit Scope short_scope with short.\n    Open Scope short_scope.\n\n    Notation \"$ o>' a\" := (_ o>' a) (at level 25) : short_scope.\n    Notation \"$ o>| #1| a\" := (_ o>| #1| a) (at level 25) : short_scope.\n    Notation \"$ o>| 'uMod'\" := (_ o>| uMod)(at level 25) : short_scope.\n    Notation \"$ o>| a_ o>Mod a'\" := (_ o>| a_ o>Mod a') (at level 25) : short_scope.\n    Notation \"$ o>| ''D1|' a\" := (_ o>| 'D1| a) (at level 25) : short_scope.\n    Notation \"$ o>| b o>D a\" := (_ o>| b o>D a) (at level 25) : short_scope.\n    Notation \"$ o>| 'clfy o>Mod a'\" := (_ o>| 'clfy o>Mod a') (at level 25) : short_scope.\n    Notation \"$ o>| a_ o>Mod 'declfy\" := (_ o>| a_ o>Mod 'declfy) (at level 25) : short_scope.\n\n    End Ex_Notations.\n    \n  Lemma iterCancelInner {log : logic} {trf : obV log -> obV log} :\n        forall (Vs : list (obV log)) (vs : (hlist (toArrowV (trf:=trf)) (chain Vs)))\n        (Vb Vb' : obV log) (vb : V(0 Vb' |- Vb )0)\n        (W W_dft : obV log) (V0Vb' : obV log)\n        (va : V(0 trf(last W_dft Vs) |- W )0)\n        (v0b : V(0 V0Vb' |- (0 trf(head W_dft Vs) & Vb' )0 )0)\n        (B : obMod) (A : obMod) (b : 'D(0 Vb |- [0 B ~> A ]0 )0)\n        (A' : obMod)(a : 'D(0 W |- [0 A ~> A' ]0 )0),\n    ( v0b o>| ( vb o>' b)  o>D (iterDeClassifying (V_dft := W_dft) vs ( va o>' a)) )\n      ~~~ ( v0b o>| (vb o>| b o>Mod 'declfy )\n                o>D (iterDeClassifying (V_dft := W_dft) vs (va o>| 'clfy o>Mod a) )\n            : 'D(0 V0Vb' |- [0 B ~> 'D0| (iterDeClass0 (length Vs).-1 A') ]0)0 ).\n  Proof.\n    move => Vs; elim : Vs => [ | V0 Vs' ].\n    - move => vs. case:  vs / (arrowList_destructP vs); intros.\n      do 2 rewrite (iterDeClassifying_rewrite (HNil : arrowList [::])).\n        apply: CancelInner.\n    - case: Vs' => [ | V1 Vs''] IHVs'.\n      + move => vs. case:  V0 vs / (arrowList_destructP vs); intros.\n        do 2 rewrite (iterDeClassifying_rewrite (HNil : arrowList [:: V0])).\n        apply: CancelInner.\n      + move => vs; move : IHVs'. case:  V0 V1 Vs'' vs / (arrowList_destructP vs).\n        move => V0 V1 Vs'' v01 vs' IHVs' Vb Vb' vb W W_dft V0Vb' va v0b B A b A' a.\n        do 2 rewrite (iterDeClassifying_rewrite (v01 ::: vs' : arrowList [:: V0 , V1 & Vs''])) /=.\n\n        rewrite [(_ o>|| _ o>Mod ''declfy) in RHSc]\n                Mod_inputUnitMod_rev.\n\n        rewrite [_ o>| _ o>Mod 'declfy as X in _ ~~~ (_ o>| _ o>D X )]\n                (DeClassifying_morphismPost_rev (log:=log)).\n        rewrite [in RHSc]DeClass_morphismPre_rev.\n        rewrite [in RHSc]DeClass_morphismPost_rev.\n        rewrite [in RHSc]DeClass_morphismPre_rev.\n        rewrite [in RHSc]Mod_morphism_rev.\n\n        rewrite -[X in _ ~~~ (_ o>| X o>Mod _)]DeClass_morphismPre.\n        rewrite -[in RHSc]DeClass_arrowPost.\n        rewrite -[in RHSc]IHVs'.\n\n        rewrite [in RHSc]DeClass_morphismPre_rev.\n        rewrite -[in RHSc]Mod_morphism.\n        rewrite -[in RHSc]DeClass_morphismPre.\n        rewrite -[in RHSc]DeClass_morphismPost.\n        rewrite -[in RHSc]Mod_arrowPost.\n        rewrite -[in RHSc]DeClassifying_morphismPost.\n        rewrite -[in RHSc]Mod_inputUnitMod.\n        rewrite -[in RHSc]DeClass_morphismPre.\n\n        rewrite -!tac_arrows.\n        rewrite [in RHSc]DeClassifying_arrowLog_id -[in RHSc]DeClass_arrowPost.\n        rewrite [in LHSc]DeClassifying_arrowLog_id -[in LHSc]DeClass_arrowPost.\n        apply: PolyDeClass_cong; [ | reflexivity | reflexivity].\n\n        clear. simpl in *. clear. revert dependent trf. rewrite /toArrowV. simpl.\n        move => trf. move: (trf V0) (trf V1) => trfV0 trfV1. intros; clear.\n        exact: logic_decidable7.\n  Qed.\n  Hint Resolve iterCancelInner.\n  \n  Lemma iterPermOuterInner_DeClass {log : logic}{trf : obV log -> obV log}\n        (Wb Wa : obV log) (Vs : list (obV log)) (W_dft: obV log) (Wba : obV log)\n        (Wb' : obV log) (wb : V(0 Wb' |- Wb )0)\n        (trf':=fun z => (0 (trf z) & Wb' )0)\n        (vs : (hlist (toArrowV (trf:=trf)) (chain Vs)))\n        (wa : V(0 trf(last W_dft Vs) |- (0 Wa & log.-I )0 )0)\n        (wba : V(0 Wba |- (0 trf(head W_dft Vs) & Wb' )0 )0)\n        (B : obMod) (A : obMod) (b : 'D(0 Wb |- [0 B ~> A ]0 )0)\n        (A' : obMod) (a : 'Mod(0 Wa |- [0 A ~> A' ]0 )0) :\n    ( wba o>| (iterDeClassifying (V_dft:=W_dft)\n                                 (hmap (B2:=toArrowV (trf:=trf')) (fun U1U2 u => ((1 u & Wb')0)) vs)\n                                 ( ( (1 wa o> desIdenObRK & _ )0 o> (0 _ & wb)1 ) o>| b o>D a ))\n          o>Mod 'declfy )\n      ~~~ ( wba o>| ( wb o>| b o>Mod 'declfy )\n                o>D (iterDeClassifying (V_dft:=W_dft) vs ( wa o>| 'D1| a ))\n            : 'D(0 Wba |- [0 B ~> 'D0| (iterDeClass0 (length Vs).-1 A') ]0)0 ) .\n  Admitted. (* same deduction form *)\n  Hint Resolve iterPermOuterInner_DeClass.\n  \n  Lemma iterPermOuterInner {log : logic}{trf : obV log -> obV log}\n        (Wb : obV log) (Vs : list (obV log)) (W_dft: obV log) (Wba : obV log)\n        (Wb' : obV log) (wb : V(0 Wb' |- Wb )0)\n        (trf':=fun z => (0 (trf z) & Wb' )0)\n        (vs : (hlist (toArrowV (trf:=trf)) (chain Vs)))\n        (wa : V(0 trf(last W_dft Vs) |- log.-I )0)\n        (wba : V(0 Wba |- (0 trf(head W_dft Vs) & Wb' )0 )0)\n        (B : obMod) (A : obMod) (b : 'D(0 Wb |- [0 B ~> A ]0 )0) :\n    ( wba o>| (iterDeClassifying (V_dft:=W_dft)\n                                 (hmap (B2:=toArrowV (trf:=trf')) (fun U1U2 u => ((1 u & Wb')0)) vs)\n                                 ( ( (1 wa  & _ )0 o> (0 _ & wb)1 o> desIdenObLK ) o>' b ))\n          o>Mod 'declfy )\n      ~~~ ( wba o>| ( wb o>| b o>Mod 'declfy )\n                o>D (iterDeClassifying (V_dft:=W_dft) vs ( wa o>| uMod ))\n            : 'D(0 Wba |- [0 B ~> 'D0| (iterDeClass0 (length Vs).-1 A) ]0)0 ) .\n  Admitted. (* same deduction form *)\n  Hint Resolve iterPermOuterInner.\n\n(**#+END_SRC\n\n** COMMENT Old example attempt\n\n#+BEGIN_SRC coq :exports both :results silent **)\n\n  (* ============\n     here are the old complete-deductions when only the logical arrows which\n     are identity are enabled\n\n  Definition iterDeClassifying {log : logic} (V : obV log) (B A : obMod)\n             (b : 'D(0 V |- [0 B ~> A ]0 )0)\n    : forall n : nat, 'D(0 V |- [0 B ~> iterDeClass0 n A ]0 )0 :=\n    fix iterDeClassifying n :=\n      match n return 'D(0 V |- [0 B ~> iterDeClass0 n A ]0 )0 with\n      | O => b\n      | S n => (iterDeClassifying n) o>Mod 'declfy\n      end .\n\n  Notation RHSc := (X in _ ~~~ X)%pattern.\n  Notation LHSc := (X in X ~~~ _)%pattern.\n\n  Lemma iterCancelInner {log : logic} (V : obV log) (B : obMod) (A : obMod)\n        (b : 'D(0 V |- [0 B ~> A ]0 )0) (A' : obMod)\n        (W : obV log) (a : 'D(0 W |- [0 A ~> A' ]0 )0) : forall n : nat,\n      (b o>D (iterDeClassifying a n))\n        ~~~ ((b o>Mod 'declfy) o>D (iterDeClassifying ('clfy o>Mod a) n)) .\n  Proof.\n    elim => [ | n IHn /= ]; first by apply: CancelInner.\n\n    rewrite [iterDeClassifying _ _ in RHSc]PolyV_Mod_unit.\n    rewrite [in RHSc]desIdenObLKV_K.\n    rewrite [in RHSc]PolyV_Mod_arrow.\n    rewrite [in RHSc]Mod_inputUnitMod.\n    rewrite -[in RHSc]DeClassifying_arrow.\n    rewrite -[in RHSc]DeClass_arrowPost.\n    rewrite [in RHSc]DeClassifying_morphismPost.\n    rewrite [_ o>D _ in RHSc]PolyV_Mod_unit.\n    rewrite [in RHSc]Assoc_Rev_Assoc.\n    rewrite -[(Assoc <`log`<o Assoc_Rev) in RHSc]polyV_relT_constant_rel_identitary.\n    rewrite [in RHSc]PolyV_Mod_arrow.\n    rewrite [in RHSc]DeClass_morphismPost.\n    rewrite -[in RHSc]IHn.\n    rewrite -[in RHSc]DeClass_morphismPost.\n    rewrite -[in RHSc]DeClassifying_morphismPost.\n    rewrite -[Assoc_Rev o>' Assoc o>' _ in RHSc]PolyV_Mod_arrow.\n    rewrite [Assoc_Rev o>`log`> Assoc in RHSc](@polyV_relT_constant_rel_identitary log).\n    rewrite -[Assoc <`log`<o Assoc_Rev in RHSc](@Assoc_Rev_Assoc log log).\n    rewrite -[in RHSc]PolyV_Mod_unit.\n\n    rewrite [iterDeClassifying _ _ in LHSc]PolyV_Mod_unit.\n    rewrite [in LHSc]desIdenObLKV_K.\n    rewrite [in LHSc]PolyV_Mod_arrow.\n    rewrite [_ o>' iterDeClassifying _ _ in LHSc]Mod_inputUnitMod.\n    rewrite -[in LHSc]DeClassifying_arrow.\n    rewrite -[in LHSc]DeClass_arrowPost.\n\n    reflexivity.\n  Qed.\n  \n  Print iterCancelInner. (* 374 lines *)\n\n  Lemma iterCancelInner_altdeduce {log : logic} (V : obV log) (B : obMod) (A : obMod)\n        (b : 'D(0 V |- [0 B ~> A ]0 )0) (A' : obMod)\n        (W : obV log) (a : 'D(0 W |- [0 A ~> A' ]0 )0) : forall n : nat,\n      (b o>D (iterDeClassifying a n))\n        ~~~ ((b o>Mod 'declfy) o>D (iterDeClassifying ('clfy o>Mod a) n)) .\n  Proof.\n    elim => [ | n IHn /= ]; first by apply: CancelInner.\n\n    eapply Mod_TransV; [ eapply PolyDeClass_cong; [eapply Mod_ReflV|];\n                         eapply DeClassifying_cong;\n                         eapply Mod_SymV, PolyV_Mod_unit | ].\n\n    eapply Mod_TransV; [ eapply PolyDeClass_cong; [eapply Mod_ReflV|];\n                         eapply DeClassifying_cong;\n                         eapply PolyV_Mod_cong; [|eapply Mod_ReflV];\n                         eapply SymV, desIdenObLKV_K | ].\n    \n    eapply Mod_TransV; [ eapply PolyDeClass_cong; [eapply Mod_ReflV|];\n                         eapply DeClassifying_cong;\n                         eapply Mod_SymV, PolyV_Mod_arrow | ].\n\n    eapply Mod_TransV; [ eapply PolyDeClass_cong; [eapply Mod_ReflV|];\n                         eapply DeClassifying_cong;\n                         eapply PolyV_Mod_cong; [eapply ReflV|];\n                         eapply Mod_SymV, Mod_inputUnitMod | ].\n\n    eapply Mod_TransV; [ eapply PolyDeClass_cong; [eapply Mod_ReflV|];\n                         eapply DeClassifying_arrow | ] .\n\n    eapply Mod_TransV; [ eapply DeClass_arrowPost | ] .\n\n    eapply Mod_TransV; [ eapply PolyV_Mod_cong; [eapply ReflV|];\n                         eapply PolyDeClass_cong; [eapply Mod_ReflV|];\n                         eapply Mod_SymV, DeClassifying_morphismPost | ].\n\n    eapply Mod_TransV; [ eapply PolyV_Mod_cong; [eapply ReflV|];\n                         eapply Mod_SymV, PolyV_Mod_unit | ].\n\n    eapply Mod_TransV; [ eapply PolyV_Mod_cong; [eapply ReflV|];\n                         eapply PolyV_Mod_cong; [|eapply Mod_ReflV];\n                         eapply SymV, Assoc_Rev_Assoc | ].\n\n    eapply Mod_TransV; [ eapply PolyV_Mod_cong; [eapply ReflV|];\n                         eapply PolyV_Mod_cong; [|eapply Mod_ReflV];\n                         eapply polyV_relT_constant_rel_identitary | ].\n\n    eapply Mod_TransV; [ eapply PolyV_Mod_cong; [eapply ReflV|];\n                         eapply Mod_SymV, PolyV_Mod_arrow | ].\n\n    eapply Mod_TransV; [ eapply PolyV_Mod_cong; [eapply ReflV|];\n                         eapply PolyV_Mod_cong; [eapply ReflV|];\n                         eapply Mod_SymV, DeClass_morphismPost | ].\n\n    eapply Mod_TransV; [ eapply PolyV_Mod_cong; [eapply ReflV|];\n                         eapply PolyV_Mod_cong; [eapply ReflV|];\n                         eapply PolyDeClass_cong; [|eapply Mod_ReflV];\n                         eapply IHn | ].\n\n    eapply Mod_TransV; [ eapply PolyV_Mod_cong; [eapply ReflV|];\n                         eapply PolyV_Mod_cong; [eapply ReflV|];\n                         eapply  DeClass_morphismPost | ].\n\n    eapply Mod_TransV; [ eapply PolyV_Mod_cong; [eapply ReflV|];\n                         eapply PolyV_Mod_cong; [eapply ReflV|];\n                         eapply PolyV_Mod_cong; [eapply ReflV|];\n                         eapply PolyDeClass_cong; [eapply Mod_ReflV|];\n                         eapply DeClassifying_morphismPost | ].\n\n    eapply Mod_TransV; [ | eapply PolyDeClass_cong; [eapply Mod_ReflV|];\n                           eapply DeClassifying_cong;\n                           eapply PolyV_Mod_unit ].\n\n    eapply Mod_TransV; [ | eapply PolyDeClass_cong; [eapply Mod_ReflV|];\n                           eapply DeClassifying_cong;\n                           eapply PolyV_Mod_cong; [|eapply Mod_ReflV];\n                           eapply desIdenObLKV_K ].\n\n    eapply Mod_TransV; [ | eapply PolyDeClass_cong; [eapply Mod_ReflV|];\n                           eapply DeClassifying_cong;\n                           eapply PolyV_Mod_arrow ].\n\n    eapply Mod_TransV; [ | eapply PolyDeClass_cong; [eapply Mod_ReflV|];\n                           eapply DeClassifying_cong;\n                           eapply PolyV_Mod_cong; [eapply ReflV|];\n                           eapply Mod_inputUnitMod ].\n\n    eapply Mod_TransV; [ | eapply PolyDeClass_cong; [eapply Mod_ReflV|];\n                           eapply Mod_SymV, DeClassifying_arrow ].\n\n    eapply Mod_TransV; [ | eapply Mod_SymV, DeClass_arrowPost ].\n\n    eapply PolyV_Mod_cong; [eapply ReflV|].\n    eapply Mod_TransV; [ eapply PolyV_Mod_arrow | ].\n    eapply Mod_TransV; [ eapply PolyV_Mod_cong; [|eapply Mod_ReflV];\n                         eapply SymV, polyV_relT_constant_rel_identitary | ].\n    eapply Mod_TransV; [ eapply PolyV_Mod_cong; [|eapply Mod_ReflV];\n                         eapply Assoc_Rev_Assoc | ].\n    eapply PolyV_Mod_unit.\n  Qed.\n\n  Print iterCancelInner_altdeduce.  (* 162 lines *)\n\n  Lemma iterPermOuterInner_DeClass {log : logic}\n        (V : obV log) (B : obMod) (A : obMod)\n        (b : 'D(0 V |- [0 B ~> A ]0 )0) (A' : obMod)\n        (a_ : 'D(0 V |- [0 'D0| A ~> A' ]0 )0) (A'' : obMod)\n        (a' : 'Mod(0 V |- [0 A' ~> A'' ]0 )0) : forall n : nat,\n        ( ( iterDeClassifying ( b o>Mod ( a_ o>D a' ) ) n ) o>Mod 'declfy )\n          ~~~ ( ( b o>Mod 'declfy ) o>D (iterDeClassifying ( a_ o>D a' ) n)\n                : 'D(0 (0 (0 V & V )0 & V )0 |- [0 B ~> 'D0| (iterDeClass0 n A'') ]0)0 ).\n  Proof.\n    elim => [ | n IHn /= ]; first by apply: DeClassifying_morphismPre.\n\n    rewrite [iterDeClassifying _ _ in RHSc]PolyV_Mod_unit.\n    rewrite [in RHSc]desIdenObLKV_K.\n    rewrite [in RHSc]PolyV_Mod_arrow.\n    rewrite [in RHSc]Mod_inputUnitMod.\n    rewrite -[in RHSc]DeClassifying_arrow.\n    rewrite -[in RHSc]DeClass_arrowPost.\n    rewrite [in RHSc]DeClassifying_morphismPost.\n    rewrite [_ o>D _ in RHSc]PolyV_Mod_unit.\n    rewrite [in RHSc]Assoc_Rev_Assoc.\n    rewrite -[(Assoc <`log`<o Assoc_Rev) in RHSc]polyV_relT_constant_rel_identitary.\n    rewrite [in RHSc]PolyV_Mod_arrow.\n    rewrite [in RHSc]DeClass_morphismPost.\n    rewrite -[in RHSc]IHn.\n    rewrite -[in RHSc]PermOuterInner.\n    rewrite -2![in RHSc]PolyV_Mod_arrow.\n    rewrite -[X in _ ~~~ (X o>' _) ]desIdenObLKV_Assoc_Rev_desIdenObLK.\n    rewrite -[in RHSc]PolyV_Mod_unit; reflexivity.\n  Qed.\n\n  Lemma iterPermOuterInner {log : logic}\n        (V : obV log) (B : obMod) (A : obMod)\n        (b : 'D(0 V |- [0 B ~> A ]0 )0) : forall n : nat,\n        ( desIdenObLK o>' ( (iterDeClassifying b n) o>Mod 'declfy ) )\n          ~~~ ( ( b o>Mod 'declfy ) o>D (iterDeClassifying uMod n)\n                : 'D(0 (0 log.-I & V )0 |- [0 B ~> 'D0| (iterDeClass0 n A) ]0)0 ).\n  Proof.\n    elim => [ /= | n IHn /= ]; first by rewrite -DeClass_inputUnitMod; reflexivity.\n\n    rewrite [iterDeClassifying _ _ in RHSc]PolyV_Mod_unit.\n    rewrite [in RHSc]desIdenObLKV_K.\n    rewrite [in RHSc]PolyV_Mod_arrow.\n    rewrite [in RHSc]Mod_inputUnitMod.\n    rewrite -[in RHSc]DeClassifying_arrow.\n    rewrite -[in RHSc]DeClass_arrowPost.\n    rewrite [in RHSc]DeClassifying_morphismPost.\n    rewrite [_ o>D _ in RHSc]PolyV_Mod_unit.\n    rewrite [in RHSc]Assoc_Rev_Assoc.\n    rewrite -[(Assoc <`log`<o Assoc_Rev) in RHSc]polyV_relT_constant_rel_identitary.\n    rewrite [in RHSc]PolyV_Mod_arrow.\n    rewrite [in RHSc]DeClass_morphismPost.\n    rewrite -[in RHSc]IHn.\n    rewrite -[in RHSc]DeClass_arrowPre.\n    rewrite -2![in RHSc]PolyV_Mod_arrow.\n    rewrite -[X in _ ~~~ (X o>' _) ]desIdenObLKV_IdenOb_Assoc_Rev_desIdenObLK.\n    rewrite -[in RHSc]PolyV_Mod_unit.\n    rewrite -[in RHSc]PermOuterInner; reflexivity.\n  Qed.\n\n   =========== *)\n\n  End Iter_deduce.\n\n(**#+END_SRC\n\n* Grade\n\nDefinitions ...\n\n#+BEGIN_SRC coq :exports both :results silent **)\n  \n  Definition grade {log : logic} :\n    forall (V : obV log) (A1 A2 : obMod), 'Mod(0 V |- [0 A1 ~> A2 ]0 )0 -> nat.\n  Proof.\n    move => V A1 A2 a; elim : V A1 A2 / a.\n    - intros; refine (S _); assumption (* intros; assumption *) . (* PolyV_Mod *)\n    - intros; exact (S O). (* GenArrowsMod *)\n    - intros; exact (S (S O)). (* UnitMod *)\n    - move => ? ? ? a_ grade_a_ ? ? ? ? a' grade_a';\n               refine (S  (S (grade_a_ + grade_a')%coq_nat)). (* PolyMod *)\n    - intros; refine (S  (S (S (S _)))); assumption. (* UnitDeClass *)\n    - move => ? ? ? b grade_b ? ? ? ? a grade_a;\n               refine (S  (S (S (grade_b + grade_a)%coq_nat))). (* PolyDeClass *)\n    - intros; refine ( (S  (S _))); assumption. (* Classifying *)\n    - intros; refine ( (S  (S _))); assumption. (* DeClassifying *)\n  Defined.\n\n  Definition gradeCom {log : logic} :\n    forall (V : obV log) (A1 A2 : obMod), 'Mod(0 V |- [0 A1 ~> A2 ]0 )0 -> nat.\n  Proof.\n    move => V A1 A2 a; elim : V A1 A2 / a.\n    - intros; assumption. (* PolyV_Mod *)\n    - intros; exact (O). (* GenArrowsMod *)\n    - intros; exact (O). (* UnitMod *)\n    - move => ? ? ? a_ gradeCom_a_ ? ? ? v a' gradeCom_a';\n               refine (gradeCom_a_ + (gradeCom_a' + (grade ( v o>| a_ o>Mod a')))%coq_nat)%coq_nat.\n    (* PolyMod *)\n    - intros; assumption. (* UnitDeClass *)\n    - move => ? ? ? b gradeCom_b ? ? ? v a gradeCom_a;\n               refine (gradeCom_b + (gradeCom_a )%coq_nat)%coq_nat.\n    (* PolyDeClass *)\n    - intros; assumption. (* Classifying *)\n    - intros; assumption. (* DeClassifying *)\n  Defined.\n\n  Definition gradeDeClass {log : logic} :\n    forall (V : obV log) (A1 A2 : obMod), 'Mod(0 V |- [0 A1 ~> A2 ]0 )0 -> nat.\n  Proof.\n    move => V A1 A2 a; elim : V A1 A2 / a.\n    - intros; assumption. (* PolyV_Mod *)\n    - intros; exact (O). (* GenArrowsMod *)\n    - intros; exact (O). (* UnitMod *)\n    - move => ? ? ? a_ gradeDeClass_a_ ? ? ? v a' gradeDeClass_a';\n               refine (gradeDeClass_a_ + (gradeDeClass_a')%coq_nat)%coq_nat.\n    (* PolyMod *)\n    - intros; assumption. (* UnitDeClass *)\n    - move => ? ? ? b gradeDeClass_b ? ? ? v a gradeDeClass_a;\n               refine (gradeDeClass_b + (gradeDeClass_a + (grade (v o>| b o>D a)))%coq_nat)%coq_nat.\n    (* PolyDeClass *)\n    - intros; assumption. (* Classifying *)\n    - intros; assumption. (* DeClassifying *)\n  Defined.\n\n  Definition gradeTotal {log : logic} (V : obV log) (A1 A2 : obMod) :\n    'Mod(0 V |- [0 A1 ~> A2 ]0 )0 -> nat.\n  Proof.\n    move => a; refine ( (grade a) + ( (gradeCom a) + (gradeDeClass a) )%coq_nat )%coq_nat.\n  Defined.\n\n(**#+END_SRC\n\nSome lemmas :\n\n#+BEGIN_SRC coq :exports both :results silent **)\n\n  Lemma grade_iterDeClassifying {log : logic} {trf : obV log -> obV log}\n        (V_dft : obV log) (B A : obMod) \n        (Vs : list (obV log)) (vs : (hlist (toArrowV (trf:=trf)) (chain Vs))) :\n    forall (b : 'D(0 trf (last V_dft Vs) |- [0 B ~> A ]0 )0),\n    grade (iterDeClassifying vs b) = ((2 * (length (chain Vs)))%coq_nat + grade b)%coq_nat.\n  Proof.\n    move: (arrowListP (trf:=trf) vs) => vs_arrowListP.\n    elim : vs_arrowListP.\n    - reflexivity.\n    - reflexivity.\n    - move => V0 V1 v01 Vs'' vs' vs'_arrowListP IHvs' b.\n      rewrite (iterDeClassifying_rewrite (v01 ::: vs' : arrowList [:: V0, V1 & Vs''])) /= ||\n              rewrite /= -/(iterDeClassifying vs' b) .\n      rewrite IHvs' /=; Omega.omega.\n  Qed.\n  Hint Rewrite (@grade_iterDeClassifying).\n\n  Lemma gradeCom_iterDeClassifying {log : logic} {trf : obV log -> obV log}\n        (V_dft : obV log) (B A : obMod) \n        (Vs : list (obV log)) (vs : (hlist (toArrowV (trf:=trf)) (chain Vs))) :\n    forall (b : 'D(0 trf (last V_dft Vs) |- [0 B ~> A ]0 )0),\n    gradeCom (iterDeClassifying vs b) = (gradeCom b).\n  Proof.\n    move: (arrowListP (trf:=trf) vs) => vs_arrowListP.\n    elim : vs_arrowListP.\n    - reflexivity.\n    - reflexivity.\n    - move => V0 V1 v01 Vs'' vs' vs'_arrowListP IHvs' b.\n      rewrite (iterDeClassifying_rewrite (v01 ::: vs' : arrowList [:: V0, V1 & Vs''])) /= ||\n              rewrite /= -/(iterDeClassifying vs' b) .\n      rewrite IHvs' /=; reflexivity.\n  Qed.\n  Hint Rewrite (@gradeCom_iterDeClassifying).\n\n  Lemma gradeDeClass_iterDeClassifying {log : logic} {trf : obV log -> obV log}\n        (V_dft : obV log) (B A : obMod) \n        (Vs : list (obV log)) (vs : (hlist (toArrowV (trf:=trf)) (chain Vs))) :\n    forall (b : 'D(0 trf (last V_dft Vs) |- [0 B ~> A ]0 )0),\n    gradeDeClass (iterDeClassifying vs b) = (gradeDeClass b).\n  Proof.\n    move: (arrowListP (trf:=trf) vs) => vs_arrowListP.\n    elim : vs_arrowListP.\n    - reflexivity.\n    - reflexivity.\n    - move => V0 V1 v01 Vs'' vs' vs'_arrowListP IHvs' b.\n      rewrite (iterDeClassifying_rewrite (v01 ::: vs' : arrowList [:: V0, V1 & Vs''])) /= ||\n              rewrite /= -/(iterDeClassifying vs' b) .\n      rewrite IHvs' /=; reflexivity.\n  Qed.\n  Hint Rewrite (@gradeDeClass_iterDeClassifying).\n\n(**#+END_SRC\n\n* Reduction\n\n** Grammatical generation of the reduction relation\n\nGenerating the reduction relations, memo that the conversion relation =Mod_morphism=\nfor associativity, is not contained in the reduction relations :\n\n#+BEGIN_SRC coq :exports both :results silent **)\n\n  Module Red.\n    \n    Reserved Notation \"f2 <~~ f1\" (at level 70).\n\n    Inductive convMod {log : logic} : forall (V : obV log) (A1 A2 : obMod),\n        'Mod(0 V |- [0 A1 ~> A2 ]0 )0 -> 'Mod(0 V |- [0 A1 ~> A2 ]0 )0 -> Prop :=\n\n    | Mod_TransV : forall (V : obV log) (A1 A2 : obMod)\n                     (uTrans a : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0),\n        uTrans <~~ a -> forall (a0 : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0),\n          a0 <~~ uTrans -> a0 <~~ a\n\n    | PolyV_Mod_cong : forall (A1 A2 : obMod) (V V' : obV log) (v v0 : V(0 V' |- V )0)\n                         (a a0 : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0),\n        v0 ~~ v -> a0 <~~ a -> ( v0 o>' a0 ) <~~ ( v o>' a )\n\n    | Mod_cong_Pre :\n        forall (V : obV log) (A A' : obMod) (a_ a_0 : 'Mod(0 V |- [0 A ~> A' ]0 )0),\n        forall (W : obV log) (A'' : obMod) (a' : 'Mod(0 W |- [0 A' ~> A'' ]0 )0),\n        forall (WV : obV log) (v v0 : V(0 WV |- (0 W & V )0 )0),\n          v0 ~~ v -> a_0 <~~ a_ -> ( v0 o>| a_0 o>Mod a' ) <~~ ( v o>| a_ o>Mod a' )\n\n    | Mod_cong_Post :\n        forall (V : obV log) (A A' : obMod) (a_ : 'Mod(0 V |- [0 A ~> A' ]0 )0),\n        forall (W : obV log) (A'' : obMod) (a' a'0 : 'Mod(0 W |- [0 A' ~> A'' ]0 )0),\n        forall (WV : obV log) (v v0 : V(0 WV |- (0 W & V )0 )0),\n          v0 ~~ v -> a'0 <~~ a' -> ( v0 o>| a_ o>Mod a'0 ) <~~ ( v o>| a_ o>Mod a' )\n\n    | UnitDeClass_cong :\n        forall (A : obMod) (A' : obMod) (W W' : obV log) (v v0 : V(0 W' |- (0 W & log.-I )0 )0) (a a0 : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n          v0 ~~ v -> a0 <~~ a -> ( v0 o>| 'D1| a0 ) <~~ ( v o>| 'D1| a )\n\n    | PolyDeClass_cong_Pre :\n        forall (V : obV log) (B : obMod) (A : obMod) (b b0 : 'D(0 V |- [0 B ~> A ]0 )0),\n        forall (W : obV log) (A' : obMod) (a : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n      forall (WV : obV log) (v v0 : V(0 WV |- (0 W & V )0 )0),\n          v0 ~~ v -> b0 <~~ b -> ( v0 o>| b0 o>D a ) <~~ ( v o>| b o>D a )\n\n    | PolyDeClass_cong_Post :\n        forall (V : obV log) (B : obMod) (A : obMod) (b : 'D(0 V |- [0 B ~> A ]0 )0),\n        forall (W : obV log) (A' : obMod) (a a0 : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n      forall (WV : obV log) (v v0 : V(0 WV |- (0 W & V )0 )0),\n          v0 ~~ v -> a0 <~~ a -> ( v0 o>| b o>D a0 ) <~~ ( v o>| b o>D a )\n\n    | Classifying_cong :\n      forall (V V' : obV log) (v v0 : V(0 V' |- V )0) (A1 A2 : obMod) (a a0 : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0),\n        v0 ~~ v -> a0 <~~ a -> (v0 o>| 'clfy o>Mod a0 ) <~~ (v o>| 'clfy o>Mod a )\n\n    | DeClassifying_cong :\n      forall (V V' : obV log) (v v0 : V(0 V' |- V )0) (A1 A2 : obMod) (a a0 : 'D(0 V |- [0 A1 ~> A2 ]0 )0),\n        v0 ~~ v -> a0 <~~ a -> (v0 o>| a0 o>Mod 'declfy ) <~~ (v o>| a o>Mod 'declfy )\n\n    | GenArrowsMod_arrowLog : forall (V V' V'' : obV log) (A1 A2 : obMod_gen)\n                                (aGen : Mod_gen V A1 A2) (v : V(0 V' |- V )0)\n                                (v' : V(0 V'' |- V' )0) ,\n        ( ( v' o> v) o>| #1| aGen )\n          <~~ (v' o>' (v o>| #1| aGen)\n               : 'Mod(0 V'' |- [0 #0| A1 ~> #0| A2 ]0)0 )\n\n    | UnitMod_arrowLog : forall (V V' : obV log) (A : obMod) (v : V(0 V |- log.-I )0)\n                        (v' : V(0 V' |- V )0),\n        ( ( v' o> v ) o>| @uMod A )\n          <~~ (v' o>' (v o>| @uMod A)\n               : 'Mod(0 V' |- [0 A ~> A ]0)0 )\n\n    | Mod_arrowLog :\n        forall (V : obV log) (A0 : obMod) (A : obMod)\n          (a_ : 'Mod(0 V |- [0 A0 ~> A ]0 )0),\n        forall (W : obV log) (A' : obMod) (a' : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n        forall (WV : obV log) (v : V(0 WV |- (0 W & V )0 )0),\n        forall (WV0 : obV log) (v0 : V(0 WV0 |- WV )0),\n          ( ( v0 o> v ) o>| a_ o>Mod a' )\n            <~~ ( v0 o>' ( v o>| a_ o>Mod a' )\n                  : 'Mod(0 WV0 |- [0 A0 ~> A' ]0)0 )\n\n    | Mod_arrowPre :\n        forall (V V' : obV log) (v : V(0 V' |- V )0) (A0 : obMod) (A : obMod)\n          (a_ : 'Mod(0 V |- [0 A0 ~> A ]0 )0),\n        forall (W : obV log) (A' : obMod) (a' : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n        forall (WV' : obV log) (v0 : V(0 WV' |- (0 W & V' )0 )0),\n          ( ( v0 o> log.-(0 _ & v )1 ) o>| a_ o>Mod a' )\n            <~~ ( v0 o>| ( v o>' a_ ) o>Mod a'\n                  : 'Mod(0 WV' |- [0 A0 ~> A' ]0)0 )\n\n    | Mod_arrowPost :\n        forall (V : obV log) (A0 : obMod) (A : obMod) (a_ : 'Mod(0 V |- [0 A0 ~> A ]0 )0),\n        forall (W W' : obV log) (w : V(0 W' |- W )0) (A' : obMod)\n          (a' : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n        forall (W'V : obV log) (w0 : V(0 W'V |- (0 W' & V )0 )0),\n          ( ( w0 o> log.-(1 w & _ )0 ) o>| a_ o>Mod a' )\n            <~~ ( w0 o>| a_ o>Mod ( w o>' a' )\n                  : 'Mod(0 W'V |- [0 A0 ~> A' ]0)0 )\n\n    | UnitDeClass_arrowLog :\n        forall (W W' W'' : obV log) (w : V(0 W' |- (0 W & log.-I )0 )0)\n          (w' : V(0 W'' |- W' )0)\n          (A A' : obMod) (a : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n          ( ( w' o> w ) o>| 'D1| a )\n            <~~ (  w' o>' ( w o>| 'D1| a )\n                   : 'D(0 W'' |- [0 'D0| A ~> A' ]0)0 )\n\n    | UnitDeClass_arrow :\n        forall (W W' W'' : obV log) (w : V(0 W' |- W )0)\n          (w' : V(0 W'' |- (0 W' & log.-I )0 )0)\n          (A A' : obMod) (a : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n          ( ( w' o> log.-(1 w & log.-I )0 ) o>| 'D1| a )\n            <~~ (  w' o>| 'D1| ( w o>' a)\n                               : 'D(0 W'' |- [0 'D0| A ~> A' ]0)0 )\n\n    | DeClass_arrowLog :\n        forall (V : obV log) (B : obMod) (A : obMod)\n          (b : 'D(0 V |- [0 B ~> A ]0 )0),\n        forall (W : obV log) (A' : obMod) (a : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n        forall (WV : obV log) (v : V(0 WV |- (0 W & V )0 )0),\n        forall (WV0 : obV log) (v0 : V(0 WV0 |- WV )0),\n          ( ( v0 o> v ) o>| b o>D a )\n            <~~ ( v0 o>' ( v o>| b o>D a )\n                : 'D(0 WV0 |- [0 B ~> A' ]0)0 )\n\n    | DeClass_arrowPre :\n        forall (V V' : obV log) (v : V(0 V' |- V )0) (B : obMod) (A : obMod)\n          (b : 'D(0 V |- [0 B ~> A ]0 )0),\n        forall (W : obV log) (A' : obMod) (a : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n        forall (WV' : obV log) (v0 : V(0 WV' |- (0 W & V' )0 )0),\n          ( ( v0 o> log.-(0 _ & v )1 ) o>| b o>D a )\n            <~~ ( v0 o>| ( v o>' b ) o>D a\n                : 'D(0 WV' |- [0 B ~> A' ]0)0 )\n\n    | DeClass_arrowPost :\n        forall (V : obV log) (B : obMod) (A : obMod) (b : 'D(0 V |- [0 B ~> A ]0 )0),\n        forall (W W' : obV log) (w : V(0 W' |- W )0) (A' : obMod)\n          (a : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n        forall (W'V : obV log) (w0 : V(0 W'V |- (0 W' & V )0 )0),\n          ( ( w0 o> log.-(1 w & _ )0 ) o>| b o>D a )\n            <~~ ( w0 o>| b o>D ( w o>' a )\n                  : 'D(0 W'V |- [0 B ~> A' ]0)0 )\n\n    | Classifying_arrowLog : forall (V V' V'' : obV log) (v : V(0 V' |- V )0) (v0 : V(0 V'' |- V' )0)\n                               (A1 A2 : obMod)\n                               (a : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0),\n        ( ( v0 o> v ) o>| 'clfy o>Mod a )\n          <~~ ( v0 o>' ( v o>| 'clfy o>Mod a ) \n                : 'Mod(0 V'' |- [0 'D0| A1 ~> A2 ]0)0 )\n\n    | Classifying_arrow : forall (V V' V'' : obV log) (v : V(0 V' |- V )0)\n                            (v0 : V(0 V'' |- V' )0) (A1 A2 : obMod)\n                            (a : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0),\n        ( ( v0 o> v ) o>| 'clfy o>Mod a )\n          <~~ ( v0 o>| 'clfy o>Mod ( v o>' a )\n                : 'Mod(0 V'' |- [0 'D0| A1 ~> A2 ]0)0 )\n\n    | DeClassifying_arrowLog :\n        forall (V V' V'' : obV log) (v : V(0 V' |- V )0) (v0 : V(0 V'' |- V' )0) (A1 A2 : obMod)\n          (a : 'D(0 V |- [0 A1 ~> A2 ]0 )0),\n          ( ( v0 o> v ) o>| a o>Mod 'declfy )\n            <~~ ( v0 o>' ( v o>| a o>Mod 'declfy )\n                  : 'D(0 V'' |- [0 A1 ~> 'D0| A2 ]0)0 )\n\n    | DeClassifying_arrow :\n        forall (V V' V'' : obV log) (v : V(0 V' |- V )0) (v0 : V(0 V'' |- V' )0) (A1 A2 : obMod)\n          (a : 'D(0 V |- [0 A1 ~> A2 ]0 )0),\n          ( ( v0 o> v ) o>| a o>Mod 'declfy )\n            <~~ ( v0 o>| ( v o>' a ) o>Mod 'declfy\n                  : 'D(0 V'' |- [0 A1 ~> 'D0| A2 ]0)0 )\n\n    | PolyV_Mod_arrowLog :\n        forall (V'' V' : obV log) (v' : V(0 V'' |- V' )0) (V : obV log)\n          (v : V(0 V' |- V )0) (A1 A2 : obMod) (a : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0),\n          ( ( v' o> v ) o>' a )\n            <~~ ( v' o>' ( v o>' a )\n                  : 'Mod(0 V'' |- [0 A1 ~> A2 ]0)0 )\n\n    | DeClass_morphismPost :\n        forall (A : obMod)\n          (W_ W_' : obV log) (v : V(0 W_' |- (0 W_ & log.-I )0 )0) (A' : obMod) (a_ : 'Mod(0 W_ |- [0 A ~> A' ]0 )0)\n          (W' : obV log) (A'' : obMod) (a' : 'Mod(0 W' |- [0 A' ~> A'' ]0 )0),\n        forall (W'W_' : obV log) (v0 : V(0 W'W_' |- (0 W' & W_' )0 )0),\n          ( ( v0 o> desIdenObRKV ) o>| 'D1| ( (log.-1) o>| ( ( v o> desIdenObRK ) o>' a_ ) o>Mod a' )  )\n            <~~ ( v0 o>| ( v o>| 'D1| a_ ) o>D a'\n                  : 'D(0 W'W_' |- [0 'D0| A ~> A'' ]0)0 )\n\n    | DeClass_morphismPre :\n        forall (A : obMod) (V' : obV log) (B' : obMod) (b' : 'D(0 V' |- [0 B' ~> A ]0 )0),\n        forall (W W' : obV log) (v : V(0 W' |- (0 W & log.-I )0 )0) (A' : obMod) (a : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n        forall (W'V' : obV log) (v0 : V(0 W'V' |- (0 W' & V' )0 )0),\n          ( v0  o>| b' o>D ( ( v o> desIdenObRK )  o>' a ) )\n            <~~ ( v0 o>| b' o>Mod ( v o>| 'D1| a )\n                  : 'D(0 W'V' |- [0 B' ~> A' ]0)0 )\n\n    | PolyV_Mod_unit :\n        forall (V : obV log) (A1 A2 : obMod) (a : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0),\n          ( a ) <~~ ( log.-1 o>' a\n                      : 'Mod(0 V |- [0 A1 ~> A2 ]0)0 )\n\n    | Mod_unit :\n        forall (A : obMod) (V : obV log) (v : V(0 V |- log.-I )0)\n          (W : obV log) (A' : obMod) (a : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n        forall (WV : obV log) (v0 : V(0 WV |- (0 W & V )0 )0),\n          ( ( v0 o> log.-(0 W & v )1 o> desIdenObRK ) o>' a )\n            <~~ ( v0 o>| ( v o>| uMod ) o>Mod a\n                  : 'Mod(0 WV |- [0 A ~> A' ]0)0 )\n\n    | Mod_inputUnitMod :\n        forall (V : obV log) (B : obMod) (A : obMod) (b : 'Mod(0 V |- [0 B ~> A ]0 )0),\n        forall (W : obV log) (w : V(0 W |- log.-I )0),\n        forall (WV : obV log) (w0 : V(0 WV |- (0 W & V )0 )0),\n          ( ( w0 o> log.-(1 w & V )0 o> desIdenObLK ) o>' b )\n            <~~  ( w0 o>| b o>Mod ( w o>| uMod )\n                   : 'Mod(0 WV |- [0 B ~> A ]0)0 )\n\n    | DeClass_unit :\n        forall (V : obV log) (v : V(0 V |- log.-I )0) (A : obMod) (A' : obMod) (W : obV log) (a : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n        forall (WV : obV log) (v0 : V(0 WV |- (0 W & V )0 )0),\n          ( ( v0 o> log.-(0 W & v )1 ) o>| 'D1| a )\n            <~~ ( v0 o>| ( v o>| uMod ) o>D a\n                  : 'D(0 WV |- [0 'D0| A ~> A' ]0 )0 )\n\n    | DeClass_inputUnitMod :\n        forall (V : obV log) (B : obMod) (A : obMod) (b : 'D(0 V |- [0 B ~> A ]0 )0),\n        forall (W : obV log) (w : V(0 W |- log.-I )0),\n        forall (WV : obV log) (w0 : V(0 WV |- (0 W & V )0 )0),\n          ( ( w0 o> ( log.-(1 w & _ )0 ) o> desIdenObLK ) o>' b )\n            <~~ ( w0 o>| b o>D ( w o>| uMod )\n                  : 'D(0 WV |- [0 B ~> A ]0)0 )\n\n    | Classifying_morphismPre :\n        forall (V V' : obV log) (v : V(0 V' |- V )0 ) (A1 A2 : obMod) (a_ : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0)\n          (W : obV log) (A3 : obMod) (a' : 'Mod(0 W |- [0 A2 ~> A3 ]0 )0),\n        forall (WV' : obV log) (v0 : V(0 WV' |- (0 W & V' )0 )0),\n          ( ( log.-1 ) o>| 'clfy o>Mod ( ( v0 o> (0 _ & v )1 ) o>| a_ o>Mod a' ) )\n            <~~ ( v0 o>| (v o>| 'clfy o>Mod a_ ) o>Mod a'\n                  : 'Mod(0 WV' |- [0 'D0| A1 ~> A3 ]0)0 )\n\n    | Classifying_morphismPre_DeClass :\n        forall (V V' : obV log) (v : V(0 V' |- V )0 ) (A1 A2 : obMod) (b : 'D(0 V |- [0 A1 ~> A2 ]0 )0)\n          (W : obV log) (A3 : obMod) (a' : 'Mod(0 W |- [0 A2 ~> A3 ]0 )0),\n        forall (WV' : obV log) (v0 : V(0 WV' |- (0 W & V' )0 )0),\n          ( ( log.-1 ) o>| 'clfy o>Mod ( ( v0 o> (0 _ & v )1 ) o>| b o>D a' ) )\n            <~~ ( v0 o>| (v o>| 'clfy o>Mod b ) o>D a'\n                  : 'D(0 WV' |- [0 'D0| A1 ~> A3 ]0)0 )\n\n    | Classifying_morphismPost :\n        forall (V V' : obV log) (v : V(0 V' |- (0 V & log.-I )0 )0) (A1 A2 : obMod) (a_ : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0)\n          (W W' : obV log) (w : V(0 W' |- W )0) (A3 : obMod) (a' : 'Mod(0 W |- [0 A2 ~> A3 ]0 )0),\n      forall (W'V' : obV log) (v0 : V(0 W'V' |- (0 W' & V' )0 )0),\n        ( ( log.-1 )\n            o>| 'clfy o>Mod ( v0 o>| ( ( v o> desIdenObRK ) o>' a_ ) o>Mod (w o>' a') ) )\n          <~~ ( v0 o>| ( v o>| 'D1| a_ ) o>Mod ( w o>| 'clfy o>Mod a' )\n                : 'Mod(0 W'V' |- [0 'D0| A1 ~> A3 ]0)0 ) \n\n    | DeClassifying_morphismPost :\n        forall (V : obV log) (A1 A2 : obMod) (b_ : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0)\n          (W W' : obV log) (w : V(0 W' |- W )0) (A3 : obMod) (b' : 'D(0 W |- [0 A2 ~> A3 ]0 )0),\n        forall (W'V : obV log) (w0 : V(0 W'V |- (0 W' & V )0 )0),\n          ( ( log.-1 ) o>| ( ( w0 o> (1 w & _ )0 ) o>| b_ o>Mod b' ) o>Mod 'declfy )\n            <~~ ( w0 o>| b_ o>Mod ( w o>| b' o>Mod 'declfy )\n                  : 'D(0 W'V |- [0 A1 ~> 'D0| A3 ]0)0 )\n\n    | DeClassifying_morphismPre :\n        forall (V V' : obV log) (v : V(0 V' |- V )0) (A1 A2 : obMod) (b_ : 'D(0 V |- [0 A1 ~> A2 ]0 )0)\n          (W W' : obV log) (w : V(0 W' |- (0 W & log.-I )0 )0) (A4 : obMod) (b' : 'Mod(0 W |- [0 A2 ~> A4 ]0 )0),\n        forall (W'V' : obV log) (wv : V(0 W'V' |- (0 W' & V' )0 )0),\n          ( log.-1 o>| ( wv o>| ( v o>' b_ ) o>D ( ( w o> desIdenObRK ) o>' b') ) o>Mod 'declfy )\n            <~~ ( wv o>| ( v o>| b_ o>Mod 'declfy ) o>D ( w o>| 'D1| b' )\n                  : 'D(0 W'V' |- [0 A1 ~> 'D0| A4 ]0)0 )\n\n    | CancelOuter : forall (V V' : obV log) (v : V(0 V' |- V )0) (B : obMod) (A : obMod)\n                      (b : 'D(0 V |- [0 B ~> A ]0 )0) (A' : obMod)\n                      (W W' : obV log) (w : V(0 W' |- W )0) (a : 'Mod(0 W |- [0 'D0| A ~> A' ]0 )0),\n        forall (W'V' : obV log) (wv : V(0 W'V' |- (0 W' & V' )0 )0),\n          ( wv o>| ( v o>' b ) o>Mod ( w o>' a ) )\n            <~~ ( wv o>| ( v o>| b o>Mod 'declfy ) o>Mod ( w o>| 'clfy o>Mod a )\n                  : 'Mod(0 W'V' |- [0 B ~> A' ]0)0 )\n\n    | CancelInner : forall (V V' : obV log) (v : V(0 V' |- V )0) (B : obMod) (A : obMod)\n                      (b : 'D(0 V |- [0 B ~> A ]0 )0) (A' : obMod)\n                      (W W' : obV log) (w : V(0 W' |- W )0) (a : 'Mod(0 W |- [0 A ~> A' ]0 )0),\n        forall (W'V' : obV log) (wv : V(0 W'V' |- (0 W' & V' )0 )0),\n          ( wv o>| (v o>' b) o>D (w o>' a) )\n            <~~ ( wv o>| (v o>| b o>Mod 'declfy ) o>D (w o>| 'clfy o>Mod a )\n                  : 'D(0 W'V' |- [0 B ~> A' ]0)0 )\n\n    | PermOuterInner : forall (V V' : obV log) (v : V(0 V' |- V )0) (B : obMod) (A : obMod)\n                         (b : 'D(0 V |- [0 B ~> A ]0 )0) (W W' : obV log) (w : V(0 W' |- W )0)\n                         (u : V(0 W |- log.-I )0),\n        forall (W'V' : obV log) (wv : V(0 W'V' |- (0 W' & V' )0 )0),\n          ( wv o>| ( ( log.-(1 w & _ )0 o> log.-(1 u & _ )0 o> desIdenObLK ) o>| ( v o>' b ) o>Mod 'declfy ) o>Mod 'declfy )\n            <~~ ( wv o>| ( v o>| b o>Mod 'declfy ) o>D ( w o>| (u o>| uMod) o>Mod 'declfy )\n                  : 'D(0 W'V' |- [0 B ~> 'D0| 'D0| A ]0)0 )\n\n    | IterPermOuterInner :\n        forall {trf : obV log -> obV log}\n          (Wb : obV log) (Vs : list (obV log)) (W_dft: obV log) (Wba : obV log)\n          (Wb' : obV log) (wb : V(0 Wb' |- Wb )0)\n          (trf':=fun z => (0 (trf z) & Wb' )0)\n          (vs : (hlist (toArrowV (trf:=trf)) (chain Vs)))\n          (wa : V(0 trf(last W_dft Vs) |- log.-I )0)\n          (wba : V(0 Wba |- (0 trf(head W_dft Vs) & Wb' )0 )0)\n          (B : obMod) (A : obMod) (b : 'D(0 Wb |- [0 B ~> A ]0 )0),\n          ( wba o>| (iterDeClassifying (V_dft:=W_dft)\n            (hmap (B2:=toArrowV (trf:=trf')) (fun U1U2 u => ((1 u & Wb')0)) vs)\n            ( ( (1 wa  & _ )0 o> (0 _ & wb)1 o> desIdenObLK ) o>' b ))\n                o>Mod 'declfy )\n            <~~ ( wba o>| ( wb o>| b o>Mod 'declfy )\n                    o>D (iterDeClassifying (V_dft:=W_dft) vs ( wa o>| uMod ))\n                : 'D(0 Wba |- [0 B ~> 'D0| (iterDeClass0 (length Vs).-1 A) ]0)0 )\n\n    | IterPermOuterInner_DeClass :\n        forall {trf : obV log -> obV log}\n          (Wb Wa : obV log) (Vs : list (obV log)) (W_dft: obV log) (Wba : obV log)\n          (Wb' : obV log) (wb : V(0 Wb' |- Wb )0)\n          (trf':=fun z => (0 (trf z) & Wb' )0)\n          (vs : (hlist (toArrowV (trf:=trf)) (chain Vs)))\n          (wa : V(0 trf(last W_dft Vs) |- (0 Wa & log.-I )0 )0)\n          (wba : V(0 Wba |- (0 trf(head W_dft Vs) & Wb' )0 )0)\n          (B : obMod) (A : obMod) (b : 'D(0 Wb |- [0 B ~> A ]0 )0)\n          (A' : obMod) (a : 'Mod(0 Wa |- [0 A ~> A' ]0 )0),\n            ( wba o>| (iterDeClassifying (V_dft:=W_dft)\n              (hmap (B2:=toArrowV (trf:=trf')) (fun U1U2 u => ((1 u & Wb')0)) vs)\n              ( ( (1 wa o> desIdenObRK & _ )0 o> (0 _ & wb)1 ) o>| b o>D a ))\n                  o>Mod 'declfy )\n              <~~ ( wba o>| ( wb o>| b o>Mod 'declfy )\n                      o>D (iterDeClassifying (V_dft:=W_dft) vs ( wa o>| 'D1| a ))\n                  : 'D(0 Wba |- [0 B ~> 'D0| (iterDeClass0 (length Vs).-1 A') ]0)0 )\n\n    | IterCancelInner :\n        forall {trf : obV log -> obV log}\n          (Vb Vb' : obV log) (vb : V(0 Vb' |- Vb )0)\n          (W W_dft : obV log) (V0Vb' : obV log) (Vs : list (obV log))\n          (vs : (hlist (toArrowV (trf:=trf)) (chain Vs)))\n          (va : V(0 trf(last W_dft Vs) |- W )0)\n          (v0b : V(0 V0Vb' |- (0 trf(head W_dft Vs) & Vb' )0 )0)\n          (B : obMod) (A : obMod) (b : 'D(0 Vb |- [0 B ~> A ]0 )0)\n          (A' : obMod)(a : 'D(0 W |- [0 A ~> A' ]0 )0),\n          ( v0b o>| ( vb o>' b)  o>D (iterDeClassifying (V_dft := W_dft) vs ( va o>' a)) )\n            <~~ ( v0b o>| (vb o>| b o>Mod 'declfy )\n                    o>D (iterDeClassifying (V_dft := W_dft) vs (va o>| 'clfy o>Mod a) )\n                : 'D(0 V0Vb' |- [0 B ~> 'D0| (iterDeClass0 (length Vs).-1 A') ]0)0 )\n\n    where \"f2 <~~ f1\" := (@convMod _ _ _ _ f2 f1).\n\n    Module Export Ex_Notations.\n\n      Notation \"f2 <~~ f1\" := (@convMod _ _ _ _ f2 f1).\n      Hint Constructors convMod.\n      Hint Extern 0 (_ <~~ _) =>\n      ( exact: (@Red.IterPermOuterInner _ id) ) : iter_hints.\n      Hint Extern 0 (_ <~~ _) =>\n      ( exact: (@Red.IterPermOuterInner_DeClass _ id) ) : iter_hints.\n      Hint Extern 0 (_ <~~ _) =>\n      ( exact: (@Red.IterCancelInner _ id) ) : iter_hints.\n\n      Add Parametric Relation {log : logic} (V : obV log) (A1 A2 : obMod) :\n        ('Mod(0 V |- [0 A1 ~> A2 ]0 )0) (@convMod log V A1 A2)\n          transitivity proved by\n          (fun x y z r1 r2 =>  ((@Mod_TransV log V A1 A2) y z r2 x r1))\n            as convMod_rewrite.\n      \n    End Ex_Notations.\n\n(**#+END_SRC\n\n** Degradation lemmas\n\n#+BEGIN_SRC coq :exports both :results silent **)\n\n    Lemma Red_convMod_convMod {log : logic} :\n      forall (V : obV log) (A1 A2 : obMod) (a aDeg : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0),\n        aDeg <~~ a -> aDeg ~~~ a.\n    Proof.\n      move => V A1 A2 a aDeg. elim; eauto. Show.\n    Qed.\n\n    Lemma degrade {log : logic} :\n      forall (V : obV log) (A1 A2 : obMod) (aDeg a : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0),\n        aDeg <~~ a ->\n        ((grade aDeg) <= (grade a))%coq_nat\n        /\\ ( ( (gradeTotal aDeg) < (gradeTotal a) )%coq_nat ).\n    Proof.\n      (move => V A1 A2 aDeg a red_a); elim : V A1 A2 aDeg a / red_a;\n        try solve [ ( rewrite /gradeTotal /= => * );\n                    repeat rewrite !(grade_iterDeClassifying,\n                                     gradeCom_iterDeClassifying,\n                                     gradeDeClass_iterDeClassifying) /= ;\n                    abstract intuition Omega.omega ].\n    Qed.\n    Hint Resolve degrade.\n\n    Lemma degradeTotal {log : logic} :\n      forall (V : obV log) (A1 A2 : obMod) (aDeg a : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0),\n        aDeg <~~ a -> ( (gradeTotal aDeg) < (gradeTotal a) )%coq_nat.\n    Proof.\n      eapply degrade.\n    Qed.\n    Hint Resolve degradeTotal.\n\n    Lemma degrade_gt0 {log : logic} :\n      forall (V : obV log) (A1 A2 : obMod) (a : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0),\n        ((S O) <= grade a )%coq_nat.\n    Proof.\n      move=> V A1 A2 a; apply/leP; elim : a; simpl; auto. (* alt: Omega.omega. *)\n    Qed.\n    Hint Resolve degrade_gt0.\n\n    Lemma degradeTotal_gt0 {log : logic} :\n      forall (V : obV log) (A1 A2 : obMod) (a : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0),\n        ((S O) <= gradeTotal a )%coq_nat.\n    Proof.\n      move=> V A1 A2 a; move: (degrade_gt0 a);\n              rewrite /gradeTotal; move => * ; Omega.omega.\n    Qed.\n\n  End Red.\n\n(**#+END_SRC\n\n* Solution\n\n** Grammatical generation of the solution morphisms\n\n#+BEGIN_SRC coq :exports both :results silent **)\n  \n  Module Sol.\n\n    Section Section1.\n\n    Delimit Scope gen_scope with gen.\n\n    Inductive Mod_genAtomic {log : logic} : obV log -> obMod_gen -> obMod_gen -> Type :=\n\n    | GenArrowsMod : forall (V V' : obV log), forall A1 A2 : obMod_gen\n        , Mod_gen V A1 A2 -> \n          V(0 V' |- V )0 -> 'Mod(0 V' |- [0 A1 ~> A2 ]0 )0\n\n    | PolyMod : forall (V : obV log) (A2 : obMod_gen) (A1 : obMod_gen)\n      , 'Mod(0 V |- [0 A2 ~> A1 ]0 )0 -> forall A1' : obMod_gen, forall (W WV : obV log),\n            V(0 WV |- (0 W & V )0 )0 ->\n            'Mod(0 W |- [0 A1 ~> A1' ]0 )0 -> 'Mod(0 WV |- [0 A2 ~> A1' ]0 )0\n    where\n    \"''Mod' (0 V |- [0 A1 ~> A2 ]0 )0\"\n      := (@Mod_genAtomic _ V A1 A2) : gen_scope.\n\n    Inductive Mod00 {log : logic} : obV log -> obMod -> obMod -> Type :=\n\n    | GenAtomicArrowsMod : forall (V : obV log), forall A1 A2 : obMod_gen\n        , ( 'Mod(0 V |- [0 A1 ~> A2 ]0 )0 ) %gen -> 'Mod(0 V |- [0 (#0| A1) ~> (#0| A2) ]0 )0\n\n    | UnitMod : forall (V : obV log), forall {A : obMod}\n        ,  V(0 V |- log.-I )0 -> 'Mod(0 V |- [0 A ~> A ]0 )0\n\n    | UnitDeClass : forall (A : obMod) (A' : obMod) (W W' : obV log)\n      , V(0 W' |- (0 W & log.-I)0 )0 ->\n        'Mod(0 W |- [0 A ~> A' ]0 )0 -> 'D(0 W' |- [0 'D0| A ~> A' ]0 )0\n\n    | Classifying : forall (V V' : obV log), forall (A1 A2 : obMod),\n          V(0 V' |- V )0 ->\n          'Mod(0 V |- [0 A1 ~> A2 ]0 )0 -> 'Mod(0 V' |- [0 ('D0| A1) ~> A2 ]0 )0\n\n    | DeClassifying : forall (V V' : obV log), forall (A1 A2 : obMod),\n          V(0 V' |- V )0 -> \n          'D(0 V |- [0 A1 ~> A2 ]0 )0 -> 'D(0 V' |- [0 A1 ~> ('D0| A2) ]0 )0\n\n    where\n    \"''Mod' (0 V |- [0 A1 ~> A2 ]0 )0\"\n      := (@Mod00 _ V A1 A2) and \"''D' (0 V |- [0 A1 ~> A2 ]0 )0\"\n           := (@Mod00 _ V A1 ('D0| A2)).\n\n    End Section1.\n    \n    Module Import Ex_Notations0.\n      Delimit Scope sol_scope with sol.\n      Coercion GenAtomicArrowsMod : Mod_genAtomic >-> Mod00.\n      Notation \"''Mod' (0 V |- [0 A1 ~> A2 ]0 )0\"\n        := (@Mod00 _ V A1 A2) : sol_scope.\n      Notation \"''D' (0 V |- [0 A1 ~> A2 ]0 )0\"\n        := (@Mod00 _ V A1 ('D0| A2)) : sol_scope.\n      Notation \"v o>| #1| a\" :=\n        (@GenArrowsMod _ _ _ _ _ a v) (at level 25, right associativity) : sol_scope.\n      Notation \"v o>| a_ o>Mod a'\" :=\n        (@PolyMod _ _ _ _ a_ _ _ _ v a')\n          (at level 25, right associativity, a_ at next level, format \"v  o>|  a_  o>Mod  a'\") : sol_scope.\n      Notation \"v o>| 'uMod'\" := (@UnitMod _ _ _ v)(at level 25) : sol_scope.\n      Notation \"v o>| @ 'uMod' A\" :=\n        (@UnitMod _ _ A v) (at level 25, only parsing) : sol_scope.\n      Notation \"v o>| ''D1|' a\" := (@UnitDeClass _ _ _ _ _ v a)\n                                     (at level 25, right associativity) : sol_scope.\n      Notation \"v o>| 'clfy o>Mod a'\" :=\n        (@Classifying _ _ _ _ _ v a') (at level 25, right associativity) : sol_scope.\n      Notation \"v o>| a_ o>Mod 'declfy\" :=\n        (@DeClassifying _ _ _ _ _ v a_) (at level 25, a_ at next level, right associativity) : sol_scope.\n    End Ex_Notations0.\n\n(**#+END_SRC\n\n** Containment of the solution morphisms into all the morphisms\n\n#+BEGIN_SRC coq :exports both :results silent **)\n\n    Definition iterDeClassifyingSol {log : logic} {trf : obV log -> obV log}\n               (V_dft : obV log) (B A : obMod) \n      : forall (Vs : list (obV log)) (vs : (hlist (toArrowV (trf:=trf)) (chain Vs)))\n          (b : 'D(0 trf (last V_dft Vs) |- [0 B ~> A ]0 )0 % sol),\n        'D(0 trf(head V_dft Vs) |- [0 B ~> iterDeClass0 (length Vs).-1 A ]0 )0 %sol .\n    Proof.\n      move => Vs vs. move: (arrowListP (trf:=trf) vs). elim => /= .\n      - move => b; exact: b.\n      - move => V0 b; exact: b.\n      - move => V0 V1 v01 Vs'' vs' vs'_arrowListP vs'_IH b.\n        refine (v01 o>| (vs'_IH b)  o>Mod 'declfy)%sol.\n    Defined.\n\n    Module Import Ex_Notations.\n      Export Ex_Notations0.\n      Notation \"vs o>|| a o>Mod ''declfy\" :=\n        (@iterDeClassifyingSol _ _ _ _ _ _ vs a)\n          (at level 25, a at next level, right associativity) : sol_scope.\n    End Ex_Notations.\n\n    Definition toMod_gen {log : logic} : forall (V : obV log) (A1 A2 : obMod_gen),\n        Mod_genAtomic V A1 A2 -> 'Mod(0 V |- [0 #0| A1 ~> #0| A2 ]0 )0.\n    Proof.\n      move => V A1 A2 a; elim : V A1 A2 / a =>\n      [ V V' A1 A2 aGen v (* (v o>| #1| aGen)%sol *)\n      | V A2 A1 a_GenAtom a_GenAtom_toMod A1' W WV wv a'GenAtom a'GenAtom_toMod\n          (* (a_GenAtom o>Mod a'GenAtom)%sol *)\n          ] ;\n        [ apply: (v o>| #1| aGen)\n        | apply: (wv o>| a_GenAtom_toMod o>Mod a'GenAtom_toMod) ].\n    Defined.\n\n    Definition toMod {log : logic} : forall (V : obV log) (A1 A2 : obMod),\n        'Mod(0 V |- [0 A1 ~> A2 ]0 )0 % sol -> 'Mod(0 V |- [0 A1 ~> A2 ]0 )0.\n    Proof.\n        (move => V A1 A2 a); elim : V A1 A2 / a =>\n        [ V A1 A2 a (* GenAtomicArrowsMod *)\n        | V A v (* (v o>| @uMod A)%sol *)\n        | A A' W W' v aSol aSol_toMod  (* (v o>| 'D1| aSol)%sol *)\n        | V V' A1 A2 v aSol aSol_toMod  (* (v o>| 'clfy o>Mod aSol)%sol *)\n        | V V' A1 A2 v aSol aSol_toMod  (* (v o>| aSol o>Mod 'declfy)%sol *)\n        ] ;\n          [ apply: toMod_gen a\n          | apply: (v o>| @uMod A)\n          | apply: (v o>| 'D1| aSol_toMod)\n          | apply: (v o>| 'clfy o>Mod aSol_toMod)\n          | apply: (v o>| aSol_toMod o>Mod 'declfy) ].\n    Defined.\n\n    Lemma toMod_iterDeClassifyingSol {log : logic} {trf : obV log -> obV log}\n               (V_dft : obV log) (B A : obMod) \n      : forall (Vs : list (obV log)) (vs : (hlist (toArrowV (trf:=trf)) (chain Vs)))\n          (b : 'D(0 trf (last V_dft Vs) |- [0 B ~> A ]0 )0 % sol),\n        toMod (vs o>|| b o>Mod ''declfy)%sol = vs o>|| toMod b o>Mod ''declfy.\n    Proof.\n      move => Vs vs; elim: Vs vs / (arrowListP vs).\n      - reflexivity.\n      - reflexivity.\n      - move => V0 V1 v01 Vs' vs' vs'_arrowListP IH_vs'_arrowListP b.\n        rewrite (iterDeClassifying_rewrite (v01 ::: vs' : arrowList (V0 :: V1 :: Vs'))).\n        rewrite -IH_vs'_arrowListP. reflexivity.      \n    Defined.\n\n(**#+END_SRC\n\n** Destruction of morphisms with inner-instantiation of object-indices\n\nLemmas for (dependent-)destruction by inner instantiations of indices (objects).\n\nWhere the domain of the morphism is some object of the generator graph :\n\n#+BEGIN_SRC coq :exports both :results silent **)\n    \n    Module Destruct_domGen.\n\n      Inductive Mod00_domGen {log : logic}\n      : forall (V : obV log) (A1 : obMod_gen) (A2 : obMod),\n        ( 'Mod(0 V |- [0 #0| A1 ~> A2 ]0 )0 %sol ) -> Type :=\n\n      | GenAtomicArrowsMod : forall (V : obV log) (A1 A2 : obMod_gen)\n                               (aGen : Mod_genAtomic V A1 A2),\n          Mod00_domGen (GenAtomicArrowsMod aGen)\n\n      | UnitMod : forall (V : obV log) {A : obMod_gen} (v : V(0 V |- log.-I )0),\n          Mod00_domGen (v o>| @uMod (#0| A) )%sol\n\n      | DeClassifying : forall (V V' : obV log) (A1 : obMod_gen) (A2 : obMod)\n                          (v : V(0 V' |- V )0)\n                          (a : 'D(0 V |- [0 #0| A1 ~> A2 ]0 )0 %sol ),\n          Mod00_domGen (v o>| a o>Mod 'declfy)%sol.\n\n      Lemma Mod00_domGenP {log : logic}\n        : forall (V : obV log) (A1 : obMod) (A2 : obMod)\n            ( a : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0 %sol ),\n          match A1 as A1 return 'Mod(0 V |- [0 A1 ~> A2 ]0 )0 %sol -> Type with\n          | 'D0| A1 => fun _ => unit\n          | #0| A1 => fun a => @Mod00_domGen log V A1 A2 a\n          end a.\n      Proof.\n        intros. case: V A1 A2 / a.\n        - constructor 1.\n        - intros. destruct A. constructor 2. exact: tt.\n        - intros. exact: tt.\n        - intros. exact: tt.\n        - intros. destruct A1. constructor 3. exact: tt.\n      Defined.\n\n    End Destruct_domGen.\n\n(**#+END_SRC\n\nWhere the domain of the morphism is some functor-onto-object construction :\n\n#+BEGIN_SRC coq :exports both :results silent **)\n\n    Module Destruct_domDeClass.\n\n      Inductive Mod00_domDeClass {log : logic}\n      : forall (V : obV log) (A1 : obMod) (A2 : obMod),\n        ( 'Mod(0 V |- [0 'D0| A1 ~> A2 ]0 )0 %sol ) -> Type :=\n                                                             \n      | UnitMod : forall (V : obV log) {A : obMod} (v : V(0 V |- log.-I )0),\n          Mod00_domDeClass (v o>| @uMod ('D0| A))%sol\n                                                     \n      | UnitDeClass : forall (A : obMod) (A' : obMod) (W W' : obV log)\n                        ( v : V(0 W' |- (0 W & log.-I)0 )0) (a : 'Mod(0 W |- [0 A ~> A' ]0 )0 %sol),\n          Mod00_domDeClass (v o>| 'D1| a)%sol\n\n      | Classifying : forall (V V' : obV log) (A1 A2 : obMod)\n                        (v : V(0 V' |- V )0) (a : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0 %sol),\n          Mod00_domDeClass (v o>| 'clfy o>Mod a)%sol\n\n      | DeClassifying :\n          forall (V V' : obV log) (A1 : obMod) (A2 : obMod) (v : V(0 V' |- V )0)\n            (a : 'D(0 V |- [0 'D0| A1 ~> A2 ]0 )0 %sol ),\n            Mod00_domDeClass (v o>| a o>Mod 'declfy)%sol.\n\n      Lemma Mod00_domDeClassP {log : logic}\n        : forall (V : obV log) (A1 : obMod) (A2 : obMod)\n            ( a : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0 %sol ),\n          match A1 as A1 return 'Mod(0 V |- [0 A1 ~> A2 ]0 )0 %sol -> Type with\n          | 'D0| A1 => fun a => @Mod00_domDeClass log V A1 A2 a\n          | #0| A1 => fun _ => unit\n          end a.\n      Proof.\n        intros. case: V A1 A2 / a.\n        - intros. exact: tt.\n        - move => V A v. destruct A. exact: tt. constructor 1.\n        - intros. constructor 2.\n        - move => V V' A1 A2 v a. constructor 3.\n        - move => V V' A1 A2 v a. destruct A1. exact: tt. constructor 4. \n      Defined.\n\n    End Destruct_domDeClass.\n\n(**#+END_SRC\n\nWhere the domain of the morphism is deeper two functor-onto-object constructions :\n\n#+BEGIN_SRC coq :exports both :results silent **)\n\n    Module Destruct_dom2DeClass.\n\n      Inductive Mod00_dom2DeClass {log : logic}\n      : forall (V : obV log) (A1 : obMod) (A2 : obMod),\n        ( 'Mod(0 V |- [0 'D0| ('D0| A1) ~> A2 ]0 )0 %sol ) -> Type :=\n                                                             \n      | UnitMod : forall (V : obV log) {A : obMod} (v : V(0 V |- log.-I )0),\n          Mod00_dom2DeClass (v o>| @uMod ('D0| ('D0| A)))%sol\n                                                     \n      | UnitDeClass : forall (A : obMod) (A' : obMod) (W W' : obV log)\n                        ( v : V(0 W' |- (0 W & log.-I)0 )0) (a : 'Mod(0 W |- [0 'D0| A ~> A' ]0 )0 %sol),\n          Mod00_dom2DeClass (v o>| 'D1| a)%sol\n\n      | Classifying : forall (V V' : obV log) (A1 A2 : obMod)\n                        (v : V(0 V' |- V )0) (a : 'Mod(0 V |- [0 'D0| A1 ~> A2 ]0 )0 %sol),\n          Mod00_dom2DeClass (v o>| 'clfy o>Mod a)%sol\n\n      | DeClassifying :\n          forall (V V' : obV log) (A1 : obMod) (A2 : obMod) (v : V(0 V' |- V )0)\n            (a : 'D(0 V |- [0 'D0| ('D0| A1) ~> A2 ]0 )0 %sol ),\n            Mod00_dom2DeClass (v o>| a o>Mod 'declfy)%sol.\n\n      Lemma Mod00_dom2DeClassP {log : logic}\n        : forall (V : obV log) (A1 : obMod) (A2 : obMod)\n            ( a : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0 %sol ),\n          match A1 as A1 return 'Mod(0 V |- [0 A1 ~> A2 ]0 )0 %sol -> Type with\n          | 'D0| A1 => fun a =>\n                        match A1 as A1 return 'Mod(0 V |- [0 'D0| A1 ~> A2 ]0 )0 %sol -> Type with\n                        | 'D0| A1 => fun a => @Mod00_dom2DeClass log V A1 A2 a\n                        | #0| A1 => fun _ => unit\n                        end a\n          | #0| A1 => fun _ => unit\n          end a.\n      Proof.\n        intros. case: V A1 A2 / a.\n        - intros. exact: tt.\n        - move => V A v. destruct A as [|A]; [exact: tt | destruct A; [exact: tt | constructor 1]].\n        - move => A A' W W' v a. destruct A; [exact: tt | constructor 2].\n        - move => V V' A1 A2 v a. destruct A1; [exact: tt | constructor 3].\n        - move => V V' A1 A2 v a. destruct A1 as [|A1]; [exact: tt | destruct A1; [exact: tt | constructor 4]].\n      Defined.\n\n    End Destruct_dom2DeClass.\n\n(**#+END_SRC\n\nWhere the codomain of the morphism is some functor-onto-object construction :\n\n#+BEGIN_SRC coq :exports both :results silent **)\n\n    Module Destruct_codomDeClass.\n\n      Inductive Mod00_codomDeClass {log : logic}\n      : forall (V : obV log) (A1 : obMod) (A2 : obMod),\n        ( 'Mod(0 V |- [0 A1 ~> 'D0| A2 ]0 )0 %sol ) -> Type :=\n                                                             \n      | UnitMod : forall (V : obV log) {A : obMod} (v : V(0 V |- log.-I )0),\n          Mod00_codomDeClass (v o>| @uMod ('D0| A))%sol\n                                                     \n      | UnitDeClass : forall (A : obMod) (A' : obMod) (W W' : obV log)\n                        ( v : V(0 W' |- (0 W & log.-I)0 )0) (a : 'Mod(0 W |- [0 A ~> A' ]0 )0 %sol),\n          Mod00_codomDeClass (v o>| 'D1| a)%sol\n\n      | Classifying : forall (V V' : obV log) (A1 A2 : obMod)\n                        (v : V(0 V' |- V )0) (a : 'Mod(0 V |- [0 A1 ~> 'D0| A2 ]0 )0 %sol),\n          Mod00_codomDeClass (v o>| 'clfy o>Mod a)%sol\n\n      | DeClassifying :\n          forall (V V' : obV log) (A1 : obMod) (A2 : obMod) (v : V(0 V' |- V )0)\n            (a : 'D(0 V |- [0 A1 ~> A2 ]0 )0 %sol ),\n            Mod00_codomDeClass (v o>| a o>Mod 'declfy)%sol.\n\n      Lemma Mod00_codomDeClassP {log : logic}\n        : forall (V : obV log) (A1 : obMod) (A2 : obMod)\n            ( a : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0 %sol ),\n          match A2 as A2 return 'Mod(0 V |- [0 A1 ~> A2 ]0 )0 %sol -> Type with\n          | 'D0| A2 => fun a => @Mod00_codomDeClass log V A1 A2 a\n          | #0| A2 => fun _ => unit\n          end a.\n      Proof.\n        intros. case: V A1 A2 / a.\n        - intros. exact: tt.\n        - move => V A v. destruct A. exact: tt. constructor 1.\n        - intros. constructor 2.\n        - move => V V' A1 A2 v a. destruct A2. intros; exact: tt. constructor 3.\n        - move => V V' A1 A2 v a. constructor 4. \n      Defined.\n\n    End Destruct_codomDeClass.\n\n(**#+END_SRC\n\nWhere both domain and codomain of the morphism are some functor-onto-object\nconstructions :\n\n#+BEGIN_SRC coq :exports both :results silent **)\n\n    Module Destruct_domCodomDeClass.\n\n      Inductive Mod00_domCodomDeClass {log : logic}\n      : forall (V : obV log) (A1 : obMod) (A2 : obMod),\n        ( 'Mod(0 V |- [0 'D0| A1 ~> 'D0| A2 ]0 )0 %sol ) -> Type :=\n                                                             \n      | UnitMod : forall (V : obV log) {A : obMod} (v : V(0 V |- log.-I )0),\n          Mod00_domCodomDeClass (v o>| @uMod ('D0| A))%sol\n                                                     \n      | UnitDeClass : forall (A : obMod) (A' : obMod) (W W' : obV log)\n                        ( v : V(0 W' |- (0 W & log.-I)0 )0) (a : 'Mod(0 W |- [0 A ~> A' ]0 )0 %sol),\n          Mod00_domCodomDeClass (v o>| 'D1| a)%sol\n\n      | Classifying : forall (V V' : obV log) (A1 A2 : obMod)\n                        (v : V(0 V' |- V )0) (a : 'Mod(0 V |- [0 A1 ~> 'D0| A2 ]0 )0 %sol),\n          Mod00_domCodomDeClass (v o>| 'clfy o>Mod a)%sol\n\n      | DeClassifying :\n          forall (V V' : obV log) (A1 : obMod) (A2 : obMod) (v : V(0 V' |- V )0)\n            (a : 'D(0 V |- [0 'D0| A1 ~> A2 ]0 )0 %sol ),\n            Mod00_domCodomDeClass a ->\n            Mod00_domCodomDeClass (v o>| a o>Mod 'declfy)%sol.\n\n      Lemma Mod00_domCodomDeClassP {log : logic}\n        : forall (V : obV log) (A1 : obMod) (A2 : obMod)\n            ( a : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0 %sol ),\n          match A1 as A1 return 'Mod(0 V |- [0 A1 ~> A2 ]0 )0 %sol -> Type with\n          | 'D0| A1 => fun a =>\n                        match A2 as A2 return 'Mod(0 V |- [0 'D0| A1 ~> A2 ]0 )0 %sol -> Type with\n                        | 'D0| A2 => fun a => @Mod00_domCodomDeClass log V A1 A2 a\n                        | #0| A2 => fun _ => unit\n                        end a\n          | #0| A1 => fun _ => unit\n          end a.\n      Proof.\n        intros. elim: V A1 A2 / a.\n        - intros. exact: tt.\n        - move => V A v. destruct A. exact: tt. constructor 1.\n        - intros. constructor 2.\n        - move => V V' A1 A2 v a _ . destruct A2. exact: tt. constructor 3.\n        - move => V V' A1 A2 v a IHa. destruct A1. exact: tt. constructor 4.\n          exact: IHa.\n      Defined.\n\n    End Destruct_domCodomDeClass.\n\n(**#+END_SRC\n\n** Iterated =DeClassifying= prefix\n\nAny solution morphism may be written as some decomposition with maximal prefix of\niterated =DeClassifying= constructors :\n\n#+BEGIN_SRC coq :exports both :results silent **)\n\n    Module Destruct_iterDeClassifying.\n\n      Inductive codomDeClass_prefixDeClassifying_Sol {log : logic} : forall (V : obV log) (A1 A2 : obMod),\n        'Mod(0 V |- [0 'D0| A1 ~> 'D0| A2 ]0 )0 % sol -> Type :=\n\n      | IterDeClassifying_UnitMod : \n          forall (V_dft : obV log) (A : obMod) \n           (Vs : list (obV log)) (vs : (hlist (toArrowV (trf:=fun z => z)) (chain Vs)))\n           (va : V(0 last V_dft Vs |- log.-I )0),\n           codomDeClass_prefixDeClassifying_Sol (iterDeClassifyingSol (V_dft:=V_dft) vs\n           ( va o>| @uMod ('D0| A) )%sol)\n\n      | IterDeClassifying_UnitDeClass : \n         forall (V_dft : obV log) (A A' : obMod) \n           (Vs : list (obV log)) (vs : (hlist (toArrowV (trf:=fun z => z)) (chain Vs)))\n           (Va : obV log) (va : V(0 last V_dft Vs |- (0 Va & log.-I)0 )0)\n           (a : 'Mod(0 Va |- [0 A ~> A' ]0 )0 %sol ),\n           codomDeClass_prefixDeClassifying_Sol (iterDeClassifyingSol (V_dft:=V_dft) vs\n           ( va o>| 'D1| a )%sol)\n\n      | IterDeClassifying_Classifying : \n         forall (V_dft : obV log) (A1 A2 : obMod) \n           (Vs : list (obV log)) (vs : (hlist (toArrowV (trf:=fun z => z)) (chain Vs)))\n           (Va : obV log) (va : V(0 last V_dft Vs |- Va )0)\n           (a : 'D(0 Va |- [0 A1 ~> A2 ]0 )0 %sol ),\n           codomDeClass_prefixDeClassifying_Sol (iterDeClassifyingSol (V_dft:=V_dft) vs\n           ( va o>| 'clfy o>Mod a )%sol) .\n\n      Inductive prefixDeClassifying_Sol {log : logic} : forall (V : obV log) (A1 A2 : obMod),\n        'Mod(0 V |- [0 'D0| A1 ~> A2 ]0 )0 % sol -> Type :=\n                                                      \n      | UnitMod : forall (V : obV log) {A : obMod} (v : V(0 V |- log.-I )0),\n          prefixDeClassifying_Sol (v o>| @uMod ('D0| A) )%sol\n                                   \n      | UnitDeClass :\n          forall (A : obMod) (A' : obMod) (W W' : obV log)\n            (v : V(0 W' |- (0 W & log.-I)0 )0) (a : 'Mod(0 W |- [0 A ~> A' ]0 )0 %sol),\n            prefixDeClassifying_Sol (v o>| 'D1| a)%sol\n                                        \n      | Classifying : forall (V V' : obV log) (A1 A2 : obMod) (v : V(0 V' |- V )0)\n                        (a : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0 %sol),\n          prefixDeClassifying_Sol (v o>| 'clfy o>Mod a)%sol \n\n      | CodomDeClass_prefixDeClassifying_Sol :\n          forall (V : obV log) (A1 A2 : obMod) (a : 'Mod(0 V |- [0 'D0| A1 ~> 'D0| A2 ]0 )0 % sol),\n            @codomDeClass_prefixDeClassifying_Sol log V A1 A2 a\n            -> prefixDeClassifying_Sol a .\n\n      Lemma prefixP0 {log : logic} (V : obV log) (A1 A2 : obMod)\n            (a : 'Mod(0 V |- [0 'D0| A1 ~> 'D0| A2 ]0 )0 % sol) :\n        codomDeClass_prefixDeClassifying_Sol a.\n      Proof.\n        elim : V A1 A2 a / (Destruct_domCodomDeClass.Mod00_domCodomDeClassP a). \n        - move => V A v. About IterDeClassifying_UnitMod.\n          eapply (IterDeClassifying_UnitMod (V_dft:=V) (Vs:=[::]) A HNil v).\n        - move => A A' W W' v a.\n          eapply (IterDeClassifying_UnitDeClass (V_dft:=W') (Vs:=[::]) HNil v a).\n        - move => V V' A1 A2 v a.\n          eapply (IterDeClassifying_Classifying (V_dft:=V') (Vs:=[::]) HNil v a).\n        - move => V V' A1 A2 v a (*a_domCodom*) _ IH_a_domCodom.\n          (*Set Printing Implicit. Show.*)\n          move: V' v. case: V A1 A2 a / IH_a_domCodom.\n          + move => V_dft A [ | V0 Vs'] vs;\n                     [ rewrite (hlist_eta vs) /= | ];\n                     move => va V' v.\n            eapply (IterDeClassifying_UnitMod (V_dft:=V_dft)\n                   (Vs:=[:: V' ; (head V_dft [::])]) A\n                   ((v : toArrowV (trf:=fun z => z) (V', (head V_dft [::])) ) ::: HNil) va).\n            eapply (IterDeClassifying_UnitMod (V_dft:=V_dft)\n                   (Vs:=[:: V', V0 & Vs']) A\n                   ((v : toArrowV (trf:=fun z => z) (V', (head V_dft [:: V0 & Vs'])) ) ::: vs) va).\n          + move => V_dft A A' [ | V0 Vs'] vs;\n                     [ rewrite (hlist_eta vs) /= | ];\n                     move => Va va a V' v.\n            eapply (IterDeClassifying_UnitDeClass (V_dft:=V_dft)\n                   (Vs:=[:: V' ; (head V_dft [::])])\n                   ((v : toArrowV (trf:=fun z => z) (V', (head V_dft [::])) ) ::: HNil) va a).\n            eapply (IterDeClassifying_UnitDeClass (V_dft:=V_dft)\n                   (Vs:=[:: V', V0 & Vs'])\n                   ((v : toArrowV (trf:=fun z => z) (V', (head V_dft [:: V0 & Vs'])) ) ::: vs) va a).\n          + move => V_dft A1 A2 [ | V0 Vs'] vs;\n                     [ rewrite (hlist_eta vs) /= | ];\n                     move => Va va a V' v.\n            eapply (IterDeClassifying_Classifying (V_dft:=V_dft)\n                   (Vs:=[:: V' ; (head V_dft [::])])\n                   ((v : toArrowV (trf:=fun z => z) (V', (head V_dft [::])) ) ::: HNil) va a).\n            eapply (IterDeClassifying_Classifying (V_dft:=V_dft)\n                   (Vs:=[:: V', V0 & Vs'])\n                   ((v : toArrowV (trf:=fun z => z) (V', (head V_dft [:: V0 & Vs'])) ) ::: vs) va a).\n      Defined.\n\n      Lemma prefixP {log : logic} (V : obV log) (A1 A2 : obMod)\n            (a : 'Mod(0 V |- [0 'D0| A1 ~> A2 ]0 )0 % sol) :\n        prefixDeClassifying_Sol a.\n      Proof.\n        elim : V A1 A2 a / (Destruct_domDeClass.Mod00_domDeClassP a). \n        - constructor 1.\n        - constructor 2.\n        - constructor 3.\n        - move => V V' A1 A2 v a. constructor 4. apply: Destruct_iterDeClassifying.prefixP0.\n      Defined.\n\n    End Destruct_iterDeClassifying.\n\n  End Sol.\n\n(**#+END_SRC\n\n* Resolution\n\nAny morphism is or may be reduced to some solution morphism. Memo that this resolution\nis non-congruent which is that it is total / global cut elimination /\ndesintegration. Oneself may later attempt to program the congruent-resolution\ntechnique such to get specifications for computational reflection and confluence and\ndecidability ...\n\nThis deduction is mostly-automated via these tactics which are inquired many times :\n\n#+BEGIN_SRC coq :exports both :results silent **)\n\n  Ltac tac_degrade H_gradeTotal a_Sol_prop a'Sol_prop :=\n    destruct a_Sol_prop as [a_Sol_prop |a_Sol_prop];\n    [ move : (Red.degrade a_Sol_prop);\n      destruct a'Sol_prop as [a'Sol_prop |a'Sol_prop];\n      [ move : (Red.degrade a'Sol_prop)\n      | subst ]\n    | subst;\n      destruct a'Sol_prop as [a'Sol_prop |a'Sol_prop];\n      [ move : (Red.degrade a'Sol_prop)\n      | subst ]\n    ];\n    move : H_gradeTotal; clear; rewrite /gradeTotal /= ;\n    repeat rewrite Sol.toMod_iterDeClassifyingSol /= ;\n    repeat rewrite !(grade_iterDeClassifying,\n                     gradeCom_iterDeClassifying,\n                     gradeDeClass_iterDeClassifying) /= ;\n    move => * ; abstract intuition Omega.omega.\n\n  Ltac tac_reduce :=\n    simpl in *; abstract (\n    intuition (eauto with iter_hints; try subst; rewriterMod; try congruence;\n                               eauto 12 with iter_hints)).\n\n  Section Section1.\n\n  Import Sol.Ex_Notations.\n  Import Red.Ex_Notations.\n  Context {log : logic}.\n\n(**#+END_SRC\n\nFinally :\n\n#+BEGIN_SRC coq :exports both :results silent **)\n\n  Fixpoint solveMod len {struct len} :\n    forall (V : obV log) (A1 A2 : obMod) (a : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0)\n      (H_gradeTotal : (gradeTotal a <= len)%coq_nat),\n      { aSol : 'Mod(0 V |- [0 A1 ~> A2 ]0 )0 %sol\n      | ( (Sol.toMod aSol) <~~ a ) \\/ ( (Sol.toMod aSol) = a ) }.\n  Proof.\n    case : len => [ | len ].\n\n    (* n is O *)\n    - clear; ( move => V A1 A2 a H_gradeTotal ); exfalso;\n        move : (Red.degradeTotal_gt0 a) => H_degradeTotal_gt0; abstract Omega.omega.\n\n    (* n is (S n) *)\n    - move => V A1 A2 a; case : V A1 A2 / a =>\n      [ V V' v A1 A2 a (* v o>' a *)\n      | V V' A1 A2 aGen v (* v o>| #1| aGen *)\n      | V A v (* v o>| @uMod A *)\n      | V A2 A1 a_ A1' W WV wv a' (* wv o>| a_ o>Mod a' *)\n      | A A' W W' v a (* v o>| 'D1| a *)\n      | V B A b A' W WV wv a (* wv o>| b o>D a *)\n      | V V' A1 A2 v a (* v o>| 'clfy o>Mod a *)\n      | V V' A1 A2 v a (* v o>| a o>Mod 'dlclfy *) ].\n\n      (* a is v o>' a *)\n      + rewrite -/(v o>' a) => H_gradeTotal.\n        case : (solveMod len _ _ _ a) =>\n        [ | aSol aSol_prop ].\n        * move : H_gradeTotal; clear;\n            rewrite /gradeTotal /=; move => *; abstract Omega.omega.\n        * { destruct aSol as [ (*V A1 A2 aGenAtom*)\n                            _ _ _ [ V _V' A1 A2 aGen _v  (* (_v o>| #1| aGen)%sol *)\n                                     | V A2 A1 a_GenAtom A1' W WV wv a'GenAtom\n                                         (* (wv o>| a_GenAtom o>Mod a'GenAtom)%sol *)\n                                     ]\n                             | V A _v (* (_v o>| @uMod A)%sol *)\n                             | A A' W W' _v aSol   (* (_v o>| 'D1| aSol)%sol *)\n                             | V _V' A1 A2 _v aSol  (* (_v o>| 'clfy o>Mod aSol)%sol *)\n                             | V _V' A1 A2 _v aSol  (* (_v o>| aSol o>Mod 'declfy)%sol *) ].\n\n            (* a to v o>' (_v o>| #1| aGen)%sol *)\n            - exists ( (v o> _v) o>| #1| aGen )%sol.\n              clear -aSol_prop. tac_reduce.\n                \n            (* a to v o>' (wv o>| a_GenAtom o>Mod a'GenAtom)%sol *)\n            - exists ( (v o> wv) o>| a_GenAtom o>Mod a'GenAtom )%sol .\n              clear -aSol_prop. tac_reduce.\n              (* clear -aSol_prop.\n              simpl in *; abstract (\n                  intuition (eauto; try subst; rewriterMod; try congruence; try (transitivity\n                  ((v o>' wv) o>| (Sol.toMod_gen a_GenAtom) o>Mod (Sol.toMod_gen a'GenAtom));\n                  eauto); eauto 12)). *)\n                \n            (* a to v o>' (_v o>| @uMod A)%sol *)\n            - exists ( (v o> _v) o>| uMod )%sol.\n              clear -aSol_prop. tac_reduce.\n\n            (* a to v o>' (_v o>| 'D1| aSol)%sol *)\n            - exists ( (v o> _v) o>| 'D1| aSol )%sol.\n              clear -aSol_prop. tac_reduce.\n\n            (* a to v o>' (_v o>| 'clfy o>Mod aSol)%sol *)\n            - exists ( (v o> _v) o>| 'clfy o>Mod aSol )%sol.\n              clear -aSol_prop. tac_reduce.\n\n            (* a to v o>' (_v o>| aSol o>Mod 'declfy)%sol *)\n            - exists ( (v o> _v) o>| aSol o>Mod 'declfy )%sol.\n              clear -aSol_prop. tac_reduce.\n              (* move : aSol_prop; clear;\n                case => aSol_prop;\n                         first by left; transitivity (v o>' (Sol.toMod ( _v o>| aSol o>Mod 'declfy )%sol));\n                           [ apply: Red.DeClassifying_arrowLog |\n                             apply: Red.PolyV_Mod_cong; [apply: ReflV | ] ].\n                by left; rewrite -aSol_prop; apply: Red.DeClassifying_arrowLog. *)\n          }\n\n      (* a is v o>| #1| aGen *)\n      + move => H_gradeTotal. exists (v o>| #1| aGen)%sol. right. reflexivity.\n\n      (* a is v o>| @uMod A *)\n      + move => H_gradeTotal. exists (v o>| uMod)%sol. right. reflexivity.\n\n      (* a is wv o>| a_ o>Mod a' *)\n      + rewrite -/(wv o>| a_ o>Mod a') => H_gradeTotal. all: cycle 1. \n\n      (* a is v o>| 'D1| a *)\n      + move => H_gradeTotal.\n        case : (solveMod len _ _ _ a) =>\n        [ | aSol aSol_prop ].\n        * move : H_gradeTotal; clear;\n            rewrite /gradeTotal /=; move => *; abstract Omega.omega.\n        * exists (v o>| 'D1| aSol)%sol.\n          clear -aSol_prop. tac_reduce.\n\n      (* a is wv o>| b o>D a *)\n      + rewrite -/(wv o>| b o>D a) => H_gradeTotal. all: cycle 1. \n\n      (* a is v o>| 'clfy o>Mod a *)\n      + move => H_gradeTotal.\n        case : (solveMod len _ _ _ a) =>\n        [ | aSol aSol_prop ].\n        * move : H_gradeTotal; clear;\n            rewrite /gradeTotal /=; move => *; abstract Omega.omega.\n        * exists (v o>| 'clfy o>Mod aSol)%sol.\n          clear -aSol_prop. tac_reduce.\n\n      (* a is v o>| a o>Mod 'declfy *)\n      + move => H_gradeTotal.\n        case : (solveMod len _ _ _ a) =>\n        [ | aSol aSol_prop ].\n        * move : H_gradeTotal; clear; rewrite /gradeTotal /=; move => *; abstract Omega.omega.\n        * exists (v o>| aSol o>Mod 'declfy)%sol.\n          clear -aSol_prop. tac_reduce.\n          (* move : aSol_prop; clear;\n            case => aSol_prop;\n                     first by left; apply: Red.DeClassifying_cong; [apply: ReflV |].\n            by right; rewrite -aSol_prop. *)\n\n      (* a is (wv o>| a_ o>Mod a') *)\n      + case : (solveMod len _ _ _ a_) =>\n        [ | a_Sol a_Sol_prop ];\n          [ move : H_gradeTotal; clear;\n            rewrite /gradeTotal /=; move => *; abstract Omega.omega | ].\n        case : (solveMod len _ _ _ a') =>\n        [ | a'Sol a'Sol_prop ];\n          [ move : H_gradeTotal; clear;\n            rewrite /gradeTotal /=; move => *; abstract Omega.omega | ].\n\n        (* a is (wv o>| a_ o>Mod a') , to (wv o>| a_Sol o>Mod a'Sol) *)\n        destruct a_Sol as\n            [ V A1 A2 a_GenAtom  (* a_GenAtom : ('Mod(0 _ |- [0 _ ~> _ ]0 )0 %sol) *)\n            | V A v  (* (v o>| @uMod A)%sol *)\n            | A A' _W W' v a_Sol'   (* (v o>| 'D1| aSol)%sol *)\n            | V V' A1 A2 v a_Sol'  (* (v o>| 'clfy o>Mod aSol)%sol *)\n            | V V' A1 A2 v a_Sol'  (* (v o>| aSol o>Mod 'declfy)%sol *) ].\n\n        (* a is (wv o>| a_ o>Mod a') , to (wv o>| a_Sol o>Mod a'Sol)  , is (wv o>| (a_GenAtom) o>Mod a'Sol) *)\n        * { clear - solveMod H_gradeTotal a_Sol_prop a'Sol_prop.\n            move: (Sol.Destruct_domGen.Mod00_domGenP a'Sol) => a'Sol_domGenP.\n            destruct a'Sol_domGenP as\n                [ _V _A1 A2 a'GenAtom  (* a'GenAtom : ('Mod(0 _ |- [0 _ ~> _ ]0 )0 %sol) *)\n                | _V A v  (* (v o>| @uMod A)%sol *)\n                | _V V' _A1 A2 v a'Sol'  (* (v o>| a'Sol o>Mod 'declfy)%sol *) ].\n\n            (* a is (wv o>| a_ o>Mod a') , to (wv o>| a_Sol o>Mod a'Sol)  , is (wv o>| (a_GenAtom) o>Mod a'Sol) , is  (wv o>| (a_GenAtom) o>Mod a'GenAtom)  *)\n            - exists (wv o>| a_GenAtom o>Mod a'GenAtom)%sol.\n              clear -a_Sol_prop a'Sol_prop. tac_reduce.\n                (* intuition (simpl; eauto; try subst; try congruence;\n                    try transitivity (wv o>| (Sol.toMod a_GenAtom) o>Mod a');\n                    simpl; eauto 12). *)\n\n            (* a is (wv o>| a_ o>Mod a') , to (wv o>| a_Sol o>Mod a'Sol)  , is (wv o>| (a_GenAtom) o>Mod a'Sol) , is  (wv o>| (a_GenAtom) o>Mod (v o>| uMod))  *)\n            - destruct a_GenAtom as\n                  [ V V' A1 A2 a_Gen _v  (* (_v o>| #1| a_Gen)%sol *)\n                  | V A2 A1 a_GenAtom_ A1' W _WV _v a_GenAtom'  (* (_v o>| a_GenAtom_ o>Mod a'GenAtom')%sol *) ].\n\n              (* a is (wv o>| a_ o>Mod a') , to (wv o>| a_Sol o>Mod a'Sol)  , is (wv o>| (a_GenAtom) o>Mod a'Sol) , is  (wv o>| (_v o>| #1| a_Gen) o>Mod (v o>| uMod))  *)\n              + exists ( ( ( (wv o> log.-(1 v & _ )0 o> desIdenObLK) o> _v )\n                        o>| #1| a_Gen)%sol ) .\n                clear -a_Sol_prop a'Sol_prop. tac_reduce.\n                (* intuition (simpl; eauto; try subst; try congruence;\n                           try transitivity (wv o>| (Sol.toMod (p o>| #1| m)%sol) o>Mod a');\n                           try intuition (simpl; eauto; transitivity (wv o>| (Sol.toMod (p o>| #1| m)%sol) o>Mod Sol.toMod (_v o>| uMod)%sol); simpl; eauto );\n                           simpl; eauto 12). *)\n                \n              (* a is (wv o>| a_ o>Mod a') , to (wv o>| a_Sol o>Mod a'Sol)  , is (wv o>| (a_GenAtom) o>Mod a'Sol) , is  (wv o>| (_v o>| a_GenAtom_ o>Mod a_GenAtom') o>Mod (v o>| uMod))  *)\n              + exists ( ( ( (wv o> log.-(1 v & _ )0 o> desIdenObLK) o> _v )\n                        o>| a_GenAtom_ o>Mod a_GenAtom')%sol ) .\n                clear -a_Sol_prop a'Sol_prop. tac_reduce.\n                (* intuition (simpl; eauto; try subst; try congruence;\n                           try transitivity (wv o>| (Sol.toMod (p o>| #1| m)%sol) o>Mod a');\n                           try intuition (simpl; eauto; transitivity (wv o>| (Sol.toMod (p o>| a_GenAtom1 o>Mod a_GenAtom2)%sol) o>Mod Sol.toMod (_v o>| uMod)%sol); simpl; eauto );\n                           simpl; eauto 12). *)\n\n            (* a is (wv o>| a_ o>Mod a') , to (wv o>| a_Sol o>Mod a'Sol)  , is (wv o>| (a_GenAtom) o>Mod a'Sol) , is  (wv o>| (a_GenAtom) o>Mod ((v o>| a'Sol' o>Mod 'declfy))  *)\n            - case : (solveMod len _ _ _ ((wv o> log.-(1 v & _ )0)\n                        o>| (Sol.toMod a_GenAtom) o>Mod (Sol.toMod a'Sol'))) =>\n              [ | a_o_a'Sol a_o_a'Sol_prop ].\n              + tac_degrade H_gradeTotal a_Sol_prop a'Sol_prop.\n              + exists ( (log.-1) o>| a_o_a'Sol o>Mod 'declfy )%sol .\n                clear -a_Sol_prop a'Sol_prop a_o_a'Sol_prop. tac_reduce.\n          }\n\n        (* a is (wv o>| a_ o>Mod a') , to (wv o>| a_Sol o>Mod a'Sol)  , is (wv o>| (v o>| uMod ) o>Mod a'Sol) *)\n        * { case : (solveMod len _ _ _ ((wv o> log.-(0 _ & v)1 o> desIdenObRK)\n                                          o>' (Sol.toMod a'Sol))) =>\n            [ | a_Sol_o_a'Sol a_Sol_o_a'Sol_prop ].\n            - tac_degrade H_gradeTotal a_Sol_prop a'Sol_prop.\n            - exists (a_Sol_o_a'Sol).\n              clear -a_Sol_prop a'Sol_prop a_Sol_o_a'Sol_prop. tac_reduce.\n              (* clear -a_Sol_prop a'Sol_prop a_Sol_o_a'Sol_prop;\n              simpl in *;\n                intuition (eauto; try subst; rewriter; try congruence; try (transitivity\n                ((wv o> log.-(0 _ & v)1 o> desIdenObRK) o>' (Sol.toMod a'Sol));\n                eauto); eauto 12). *)\n          }\n          \n        (* a is (wv o>| a_ o>Mod a') , to (wv o>| a_Sol o>Mod a'Sol)  , is (wv o>| (v o>| 'D1| a_Sol') o>Mod a'Sol) *)\n        * { move: (Sol.Destruct_domDeClass.Mod00_domDeClassP a'Sol) => a'Sol_domDeClassP.\n            destruct a'Sol_domDeClassP as\n                [ V _A _v  (* _v o>| @uMod _A %sol *)\n                | _A A' W _W' _v a'Sol' (* _v o>| 'D1| a'Sol' %sol *)\n                | V V' A1 A2 _v a'Sol' (* _v o>| 'clfy o>Mod a'Sol' %sol *)\n                | V V' A1 A2 _v a'Sol' (* _v o>| a'Sol' o>Mod 'declfy %sol *) ].\n\n            (* a is (wv o>| a_ o>Mod a') , to (wv o>| a_Sol o>Mod a'Sol)  , is (wv o>| (v o>| 'D1| a_Sol') o>Mod a'Sol)  , is (wv o>| (v o>| 'D1| a_Sol') o>Mod (_v o>| @uMod _A)) *)\n            - case : (solveMod len _ _ _ ((wv o> log.-(1 _v & _ )0 o> desIdenObLK)\n                                          o>' (Sol.toMod (v o>| 'D1| a_Sol')%sol))) =>\n              [ | a_Sol_o_a'Sol a_Sol_o_a'Sol_prop ].\n              + tac_degrade H_gradeTotal a_Sol_prop a'Sol_prop.\n              + exists (a_Sol_o_a'Sol).\n                clear -a_Sol_prop a'Sol_prop a_Sol_o_a'Sol_prop. tac_reduce.\n\n            (* a is (wv o>| a_ o>Mod a') , to (wv o>| a_Sol o>Mod a'Sol)  , is (wv o>| (v o>| 'D1| a_Sol') o>Mod a'Sol)  , is (wv o>| (v o>| 'D1| a_Sol') o>Mod (_v o>| 'D1| a'Sol')) *)\n            - case : (solveMod len _ _ _ (wv o>| (Sol.toMod (v o>| 'D1| a_Sol')%sol)\n                                  o>D ((_v o>desIdenObRK) o>' (Sol.toMod a'Sol')))) =>\n              [ | a_Sol_o_a'Sol a_Sol_o_a'Sol_prop ].\n              + tac_degrade H_gradeTotal a_Sol_prop a'Sol_prop.\n              + exists (a_Sol_o_a'Sol).\n                clear -a_Sol_prop a'Sol_prop a_Sol_o_a'Sol_prop. tac_reduce.\n\n            (* a is (wv o>| a_ o>Mod a') , to (wv o>| a_Sol o>Mod a'Sol)  , is (wv o>| (v o>| 'D1| a_Sol') o>Mod a'Sol)  , is (wv o>| (v o>| 'D1| a_Sol') o>Mod (_v o>| 'clfy o>Mod a'Sol')) *)\n            - case : (solveMod len _ _ _\n              ((log.-1) o>| 'clfy o>Mod (wv o>| ((v o> desIdenObRK) o>' (Sol.toMod a_Sol'))\n                                            o>Mod (_v o>' (Sol.toMod a'Sol'))))) =>\n              [ | a_Sol_o_a'Sol a_Sol_o_a'Sol_prop ].\n              + tac_degrade H_gradeTotal a_Sol_prop a'Sol_prop.\n              + exists (a_Sol_o_a'Sol).\n                clear -a_Sol_prop a'Sol_prop a_Sol_o_a'Sol_prop. tac_reduce.\n\n            (* a is (wv o>| a_ o>Mod a') , to (wv o>| a_Sol o>Mod a'Sol)  , is (wv o>| (v o>| 'D1| a_Sol') o>Mod a'Sol)  , is (wv o>| (v o>| 'D1| a_Sol') o>Mod (_v o>| a'Sol' o>Mod 'declfy)) *)\n            - case : (solveMod len _ _ _\n              ((log.-1) o>| ((wv o> (1 _v & _ )0) o>| (Sol.toMod (v o>| 'D1| a_Sol')%sol)\n                                                  o>Mod (Sol.toMod a'Sol')) o>Mod 'declfy)) =>\n              [ | a_Sol_o_a'Sol a_Sol_o_a'Sol_prop ].\n              + tac_degrade H_gradeTotal a_Sol_prop a'Sol_prop.\n              + exists (a_Sol_o_a'Sol).\n                clear -a_Sol_prop a'Sol_prop a_Sol_o_a'Sol_prop. tac_reduce.\n          }\n          \n        (* a is (wv o>| a_ o>Mod a') , to (wv o>| a_Sol o>Mod a'Sol)  , is (wv o>| (v o>| 'clfy o>Mod a_Sol') o>Mod a'Sol) *)\n        * { case : (solveMod len _ _ _\n                 ((log.-1) o>| 'clfy o>Mod ((wv o> (0 _ & v )1) o>| (Sol.toMod a_Sol')\n                                                      o>Mod (Sol.toMod a'Sol)))) =>\n            [ | a_Sol_o_a'Sol a_Sol_o_a'Sol_prop ].\n            - tac_degrade H_gradeTotal a_Sol_prop a'Sol_prop.\n            - exists (a_Sol_o_a'Sol).\n              clear -a_Sol_prop a'Sol_prop a_Sol_o_a'Sol_prop. tac_reduce.\n          }\n          \n        (* a is (wv o>| a_ o>Mod a') , to (wv o>| a_Sol o>Mod a'Sol)  , is (wv o>| (v o>| a_Sol' o>Mod 'declfy) o>Mod a'Sol) *)\n        * { move: (Sol.Destruct_dom2DeClass.Mod00_dom2DeClassP a'Sol) => a'Sol_dom2DeClassP.\n            destruct a'Sol_dom2DeClassP as\n                [ _V A _v  (* _v o>| @uMod A %sol *)\n                | A A' W W' _v a'Sol' (* _v o>| 'D1| a'Sol' %sol *)\n                | _V _V' _A1 A2 _v a'Sol' (* _v o>| 'clfy o>Mod a'Sol' %sol *)\n                | _V _V' _A1 A2 _v a'Sol' (* _v o>| a'Sol' o>Mod 'declfy %sol *) ].\n\n            (* a is (wv o>| a_ o>Mod a') , to (wv o>| a_Sol o>Mod a'Sol)  , is (wv o>| (v o>| a_Sol' o>Mod 'declfy) o>Mod (_v o>| @uMod A)) *)\n            - case : (solveMod len _ _ _\n                               ((wv o> log.-(1 _v & _ )0 o> desIdenObLK)\n                                  o>' (v o>| (Sol.toMod a_Sol') o>Mod 'declfy))) =>\n              [ | a_Sol_o_a'Sol a_Sol_o_a'Sol_prop ].\n              + tac_degrade H_gradeTotal a_Sol_prop a'Sol_prop.\n              + exists (a_Sol_o_a'Sol).\n                clear -a_Sol_prop a'Sol_prop a_Sol_o_a'Sol_prop. tac_reduce.\n\n            (* a is (wv o>| a_ o>Mod a') , to (wv o>| a_Sol o>Mod a'Sol)  , is (wv o>| (v o>| a_Sol' o>Mod 'declfy) o>Mod (_v o>| 'D1| a'Sol')) *)\n            - case : (solveMod len _ _ _\n                              (wv o>| (Sol.toMod (v o>| a_Sol' o>Mod 'declfy)%sol)\n                                  o>D ((_v o> desIdenObRK) o>' (Sol.toMod a'Sol')))) =>\n              [ | a_Sol_o_a'Sol a_Sol_o_a'Sol_prop ].\n              + tac_degrade H_gradeTotal a_Sol_prop a'Sol_prop.\n              + exists (a_Sol_o_a'Sol).\n                clear -a_Sol_prop a'Sol_prop a_Sol_o_a'Sol_prop. tac_reduce.\n\n            (* a is (wv o>| a_ o>Mod a') , to (wv o>| a_Sol o>Mod a'Sol)  , is (wv o>| (v o>| a_Sol' o>Mod 'declfy) o>Mod (_v o>| 'clfy o>Mod a'Sol')) *)\n            - case : (solveMod len _ _ _\n                               (wv o>| (v o>' (Sol.toMod a_Sol'))\n                                   o>Mod (_v o>' (Sol.toMod a'Sol')))) =>\n              [ | a_Sol_o_a'Sol a_Sol_o_a'Sol_prop ].\n              + tac_degrade H_gradeTotal a_Sol_prop a'Sol_prop.\n              + exists (a_Sol_o_a'Sol).\n                clear -a_Sol_prop a'Sol_prop a_Sol_o_a'Sol_prop. tac_reduce.\n\n              (* a is (wv o>| a_ o>Mod a') , to (wv o>| a_Sol o>Mod a'Sol)  , is (wv o>| (v o>| a_Sol' o>Mod 'declfy) o>Mod (_v o>| a'Sol' o>Mod 'declfy)) *)\n            - case : (solveMod len _ _ _\n                     ((log.-1) o>| ((wv o> (1 _v & _ )0)\n                                      o>| (Sol.toMod (v o>| a_Sol' o>Mod 'declfy)%sol)\n                                      o>Mod (Sol.toMod a'Sol')) o>Mod 'declfy)) =>\n              [ | a_Sol_o_a'Sol a_Sol_o_a'Sol_prop ].\n              + tac_degrade H_gradeTotal a_Sol_prop a'Sol_prop.\n              + exists (a_Sol_o_a'Sol).\n                clear -a_Sol_prop a'Sol_prop a_Sol_o_a'Sol_prop. tac_reduce.\n          }\n\n      (* a is (wv o>| b o>D a) *)\n      + case : (solveMod len _ _ _ b) =>\n        [ | bSol bSol_prop ];\n          [ move : H_gradeTotal; clear; rewrite /gradeTotal /=; move => *; Omega.omega | ].\n        case : (solveMod len _ _ _ a) =>\n        [ | aSol aSol_prop ];\n          [ move : H_gradeTotal; clear; rewrite /gradeTotal /=; move => *; Omega.omega | ].\n        move: (Sol.Destruct_codomDeClass.Mod00_codomDeClassP bSol) => bSol_codomDeClassP.\n        destruct bSol_codomDeClassP as\n            [ V A v  (* v o>| @uMod A %sol *)\n            | A _A' _W W' v bSol' (* v o>| 'D1| bSol' %sol *)\n            | V V' A1 A2 v bSol' (* v o>| 'clfy o>Mod bSol' %sol *)\n            | V V' A1 A2 v bSol' (* v o>| bSol' o>Mod 'declfy %sol *) ].\n\n        (* a is (wv o>| b o>D a) , to (wv o>| bSol o>D aSol)  , is (wv o>| (v o>| @uMod A) o>D aSol) *)\n        * { case : (solveMod len _ _ _\n                     ((wv o> log.-(0 _ & v )1) o>| 'D1| (Sol.toMod aSol))) =>\n              [ | bSol_oD_aSol bSol_oD_aSol_prop ].\n              - tac_degrade H_gradeTotal bSol_prop aSol_prop.\n              - exists (bSol_oD_aSol).\n                clear -bSol_prop aSol_prop bSol_oD_aSol_prop. tac_reduce.\n          }\n          \n        (* a is (wv o>| b o>D a) , to (wv o>| bSol o>D aSol)  , is (wv o>| (v o>| 'D1| bSol') o>D aSol) *)\n        * { case : (solveMod len _ _ _\n                   ((wv o> desIdenObRKV) o>| 'D1| ((log.-1) o>|\n                                     ((v o> desIdenObRK) o>' (Sol.toMod bSol'))\n                                     o>Mod (Sol.toMod aSol)))) =>\n              [ | bSol_oD_aSol bSol_oD_aSol_prop ].\n              - tac_degrade H_gradeTotal bSol_prop aSol_prop.\n              - exists (bSol_oD_aSol).\n                clear -bSol_prop aSol_prop bSol_oD_aSol_prop. tac_reduce.\n          }\n\n        (* a is (wv o>| b o>D a) , to (wv o>| bSol o>D aSol)  , is (wv o>| (v o>| 'clfy o>Mod bSol') o>D aSol) *)\n        * { case : (solveMod len _ _ _\n              ((log.-1) o>| 'clfy o>Mod ((wv o> (0 _ & v )1) o>| (Sol.toMod bSol')\n                                                             o>D (Sol.toMod aSol)))) =>\n              [ | bSol_oD_aSol bSol_oD_aSol_prop ].\n              - tac_degrade H_gradeTotal bSol_prop aSol_prop.\n              - exists (bSol_oD_aSol).\n                clear -bSol_prop aSol_prop bSol_oD_aSol_prop. tac_reduce.\n          }\n\n        (* a is (wv o>| b o>D a) , to (wv o>| bSol o>D aSol)  , is (wv o>| (v o>| bSol' o>Mod 'declfy) o>D aSol) *)\n        * { move: (Sol.Destruct_iterDeClassifying.prefixP aSol) => aSol_prefixP.\n            destruct aSol_prefixP as\n                [ _V A _v  (* _v o>| @uMod A %sol *)\n                | A A' W W' _v aSol'  (* _v o>| 'D1| aSol' %sol *)\n                | _V _V' _A1 A2 _v aSol'  (* _v o>| 'clfy o>Mod aSol' %sol *)\n                | _ _ _ _\n                    [ V_dft A Vs vs vaSol'  (* vs o>|| (vaSol' o>| @uMod A) ''declfy %sol *)\n                    | V_dft A A' Vs vs Va vaSol' aSol'  (* vs o>|| (vaSol' o>| 'D1| aSol') ''declfy %sol *)\n                    | V_dft _A1 A2 Vs vs Va vaSol' aSol'  (* vs o>|| (vaSol' o>| 'clfy o>Mod aSol') ''declfy %sol *) ] ].\n                 \n            (* a is (wv o>| b o>D a) , to (wv o>| bSol o>D aSol)  , is (wv o>| (v o>| bSol' o>Mod 'declfy) o>D aSol)  , is (wv o>| (v o>| bSol' o>Mod 'declfy) o>D (_v o>| @uMod A)) *)\n            - case : (solveMod len _ _ _\n                               ((wv o> log.-(1 _v & _ )0 o> desIdenObLK)\n                                  o>' (v o>| (Sol.toMod bSol') o>Mod 'declfy))) =>\n              [ | bSol_oD_aSol bSol_oD_aSol_prop ].\n              + tac_degrade H_gradeTotal bSol_prop aSol_prop.\n              + exists (bSol_oD_aSol).\n                clear -bSol_prop aSol_prop bSol_oD_aSol_prop. tac_reduce.\n                \n            (* a is (wv o>| b o>D a) , to (wv o>| bSol o>D aSol)  , is (wv o>| (v o>| bSol' o>Mod 'declfy) o>D aSol)  , is (wv o>| (v o>| bSol' o>Mod 'declfy) o>D (_v o>| 'D1| aSol')) *)\n            - case : (solveMod len _ _ _\n                      ((log.-1) o>| (wv o>| (v o>' (Sol.toMod bSol'))\n                                      o>D ((_v o> desIdenObRK) o>' (Sol.toMod aSol')))\n                                o>Mod 'declfy)) =>\n              [ | bSol_oD_aSol bSol_oD_aSol_prop ].\n              + tac_degrade H_gradeTotal bSol_prop aSol_prop.\n              + exists (bSol_oD_aSol).\n                clear -bSol_prop aSol_prop bSol_oD_aSol_prop. tac_reduce.\n\n            (* a is (wv o>| b o>D a) , to (wv o>| bSol o>D aSol)  , is (wv o>| (v o>| bSol' o>Mod 'declfy) o>D aSol)  , is (wv o>| (v o>| bSol' o>Mod 'declfy) o>D (_v o>| 'clfy o>Mod aSol')) *)\n            - case : (solveMod len _ _ _\n                      (wv o>| (v o>' (Sol.toMod bSol')) o>D (_v o>' (Sol.toMod aSol')))) =>\n              [ | bSol_oD_aSol bSol_oD_aSol_prop ].\n              + tac_degrade H_gradeTotal bSol_prop aSol_prop.\n              + exists (bSol_oD_aSol).\n                clear -bSol_prop aSol_prop bSol_oD_aSol_prop. tac_reduce.\n\n            (* a is (wv o>| b o>D a) , to (wv o>| bSol o>D aSol)  , is (wv o>| (v o>| bSol' o>Mod 'declfy) o>D aSol)  , is (wv o>| (v o>| bSol' o>Mod 'declfy) o>D (vs o>|| (vaSol' o>| uMod) o>Mod ''declfy)) *)\n            - case : (solveMod len _ _ _\n                      (wv\n                         o>| (hmap (fun U1U2 u => ((1 u & _ )0)) vs\n                              o>|| ((log.-(1 vaSol' & _ )0 o> (0 log.-I & v )1 o> desIdenObLK) o>' (Sol.toMod bSol'))\n                              o>Mod ''declfy) o>Mod 'declfy)) =>\n              [ | bSol_oD_aSol bSol_oD_aSol_prop ].\n              + tac_degrade H_gradeTotal bSol_prop aSol_prop.\n\n              + exists (bSol_oD_aSol).\n                move: bSol_prop aSol_prop bSol_oD_aSol_prop ; clear.\n                simpl; repeat rewrite Sol.toMod_iterDeClassifyingSol /= . tac_reduce.\n\n            - case : (solveMod len _ _ _\n                      (wv o>| (hmap (fun U1U2 u => ((1 u & _)0)) vs\n                                    o>|| ((log.-(1 vaSol' o> desIdenObRK & _ )0 o> (0 _ & v )1) o>| (Sol.toMod bSol') o>D (Sol.toMod aSol'))\n                                    o>Mod ''declfy) o>Mod 'declfy)) =>\n              [ | bSol_oD_aSol bSol_oD_aSol_prop ].\n              + tac_degrade H_gradeTotal bSol_prop aSol_prop.\n              + exists (bSol_oD_aSol).\n                move: bSol_prop aSol_prop bSol_oD_aSol_prop ; clear.\n                simpl; repeat rewrite Sol.toMod_iterDeClassifyingSol /= . tac_reduce.\n\n            (* a is (wv o>| b o>D a) , to (wv o>| bSol o>D aSol)  , is (wv o>| (v o>| bSol' o>Mod 'declfy) o>D aSol)  , is (wv o>| (v o>| bSol' o>Mod 'declfy) o>D (vs o>|| (vaSol' o>| 'clfy o>Mod aSol') o>Mod ''declfy)) *)\n            - case : (solveMod len _ _ _\n                  (wv o>| (v o>' (Sol.toMod bSol'))\n                      o>D (vs o>|| ( vaSol' o>' (Sol.toMod aSol')) o>Mod ''declfy))) =>\n              [ | bSol_oD_aSol bSol_oD_aSol_prop ].\n              + tac_degrade H_gradeTotal bSol_prop aSol_prop.\n              + exists (bSol_oD_aSol).\n                move: bSol_prop aSol_prop bSol_oD_aSol_prop ; clear.\n                simpl; repeat rewrite Sol.toMod_iterDeClassifyingSol /= . tac_reduce.\n          }\n\n  Defined.\n\n  End Section1.\n\nEnd COPARAM.\n\n(**#+END_SRC\n\nVoila. **)\n", "meta": {"author": "1337777", "repo": "laozi", "sha": "8374bfbe4dcbe9dbcaa8f6b01eb1be8bf465eebb", "save_path": "github-repos/coq/1337777-laozi", "path": "github-repos/coq/1337777-laozi/laozi-8374bfbe4dcbe9dbcaa8f6b01eb1be8bf465eebb/laoziSolution2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.29368188519411204}}
{"text": "Require Import Coqlib ITreelib ImpPrelude STS Behavior.\nRequire Import ModSem Skeleton PCM STB OpenDef.\nRequire Import Open.\nRequire Import Mem0 Mem1 Stack3A.\nRequire Import Imp StackImp EchoImp EchoMainImp ClientImp.\n\nSet Implicit Arguments.\n\n\n\nDefinition EchoGRA: GRA.t := GRA.of_list [Mem1.memRA; stkRA].\nLocal Existing Instance EchoGRA.\n\nInstance memRA_inG: @GRA.inG Mem1.memRA EchoGRA.\nProof.\n  exists 0. ss. Show Proof.\nDefined.\nLocal Existing Instance memRA_inG.\n\nInstance stkRA_inG: @GRA.inG stkRA EchoGRA.\nProof.\n  exists 1. ss.\nDefined.\nLocal Existing Instance stkRA_inG.\n\n\n\n(* Imp program *)\nRequire Import Mem0 StackImp EchoImp EchoMainImp ClientImp.\nSection ECHOIMP.\n  Definition echo_progs := [Stack_prog; Echo_prog; EchoMain_prog; Client_prog].\n  Definition echo_imp: ModL.t :=\n    Mod.add_list (Mem (fun _ => false) :: map ImpMod.get_mod echo_progs).\n\n  Definition echo_imp_itr := ModSemL.initial_itr (ModL.enclose echo_imp) None.\nEnd ECHOIMP.\n\n\nRequire Import Mem0 Stack0 Echo0 EchoMain0 Client0.\nSection ECHOIMPL.\n  Definition echo_impl: ModL.t :=\n    Mod.add_list [Mem (fun _ => false); Stack; Echo; Main; Client].\n\n  Definition echo_impl_itr := ModSemL.initial_itr (ModL.enclose echo_impl) None.\nEnd ECHOIMPL.\n\n\nRequire Import MemOpen Stack3A Echo1 EchoMain0 Client0.\n(* spec program *)\nRequire Import Stack2.\nSection ECHOSPEC.\n  Definition echo_spec: ModL.t :=\n    Mod.add_list [\n        Mem0.Mem (fun _ => true);\n      Stack2.Stack;\n      KMod.transl_src (fun _ => [\"Echo\"]) KEcho;\n      Main; Client\n      ].\n\n  Definition echo_spec_itr := ModSemL.initial_itr (ModL.enclose echo_spec) None.\nEnd ECHOSPEC.\n\n\n\nRequire Import Mem0Openproof MemOpen0proof.\nRequire Import StackImp0proof Stack01proof Stack12proof Stack23Aproof.\nRequire Import EchoMainImp0proof EchoImp0proof.\nRequire Import ClientImp0proof Echo01proof.\nRequire Import Echo1mon Stack32proof.\nSection PROOF.\n  Theorem echo_correct:\n    refines2 [Mem0.Mem (fun _ => false); StackImp.Stack; EchoImp.Echo]\n             [Mem0.Mem (fun _ => true); Stack2.Stack; KMod.transl_src (fun _ => [\"Echo\"]) KEcho].\n  Proof.\n    transitivity (KMod.transl_tgt_list [KMem (fun _ => true) (fun _ => true); Stack1.KStack]++[EchoImp.Echo]).\n    { eapply refines2_cons.\n      { eapply Mem0Openproof.correct. i; ss. }\n      eapply refines2_cons; [|refl].\n      { etrans.\n        { eapply StackImp0proof.correct. }\n        { eapply Stack01proof.correct. i.\n          etrans; [|eapply to_closed_stb_weaker]. stb_incl_tac; tauto. }\n      }\n    }\n    etrans.\n    { eapply refines2_app; [|refl].\n      eapply adequacy_open. i. exists ε. split.\n      { g_wf_tac. repeat (i; splits; ur; ss).\n        { r. esplits; et. rewrite URA.unit_idl. refl. }\n        { unfold initial_mem_mr. des_ifs; ss. }\n      }\n      { ii. ss. }\n    }\n    eapply refines2_cons.\n    { eapply MemOpen0proof.correct. }\n    transitivity (KMod.transl_tgt_list [Stack3A.KStack; KEcho]).\n    { eapply refines2_cons.\n      { etrans.\n        { eapply Stack12proof.correct. }\n        { eapply Stack23Aproof.correct. }\n      }\n      { etrans.\n        { eapply EchoImp0proof.correct. }\n        { eapply Echo01proof.correct.\n          stb_context_incl_tac; tauto. }\n      }\n    }\n    etrans.\n    { eapply adequacy_open. i. exists ε. split.\n      { g_wf_tac; repeat (i; splits; ur; ss). refl. }\n      { ii. ss. }\n    }\n    { eapply refines2_cons.\n      { eapply Stack32proof.correct. }\n      eapply refines2_cons; [|refl].\n      { eapply Echo1mon.correct. ii. ss. des; auto. }\n    }\n  Qed.\n\n  Corollary echo_closed_correct:\n    refines_closed echo_imp echo_spec.\n  Proof.\n    eapply refines_close. hexploit refines2_app.\n    { eapply echo_correct. }\n    { eapply refines2_cons.\n      { eapply EchoMainImp0proof.correct. }\n      { eapply ClientImp0proof.correct. }\n    }\n    ss.\n  Qed.\nEnd PROOF.\n\n\nRequire Import SimSTS2 Imp2Csharpminor Imp2Asm.\nRequire Import Imp2AsmProof.\nSection PROOF.\n  Context `{builtins : builtinsTy}.\n  Hypothesis source_linking: exists impl, link_imps echo_progs = Some impl.\n\n  Theorem echo_compile_correct\n          (asms : Coqlib.nlist Asm.program)\n          (COMP: Forall2 (fun imp asm => compile_imp imp = Errors.OK asm) echo_progs asms)\n    :\n      exists asml, (Linking.link_list asms = Some asml) /\\\n                   (improves2_program (ModL.compile echo_spec) (Asm.semantics asml)).\n  Proof.\n    hexploit compile_behavior_improves; [et|et|]. i. des. esplits; [et|].\n    eapply improves_combine; [|et]. eapply echo_closed_correct.\n  Qed.\nEnd PROOF.\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/EchoAll.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.29368187884040703}}
{"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.ListValidator.EquivocationAwareComposition\n  VLSM.ObservableEquivocation\n  .\n\n(** * VLSM List Validator Common Futures *)\n\n(**\nAlso see:\n   - [Observations.v] for the observation model used here\n   - [EquivocationAwareListValidator.v] for the used estimators\n   - [EquivocationAwareComposition.v] for results concerning this type of composition\n   - [Equivocation.v] and [ListValidator.v] for some general\n     facts about List Validators. *)\n\nSection CommonFutures.\n\n(**\n   ** The Common Futures Theorem for List Validators.\n\n   The following is an informal sketch of the Common Futures Theorem for List Validators.\n\n   Consider a composition <<X>> of List Validator nodes, each using an [equivocation_aware_estimator].\n   The aim is to prove that for any given protocol [vstate X] <<s>>, there exists a [vstate X] <<s'>>\n   such that:\n   (1) <<s'>> is a future state of <<s>>.\n   (2) The set of honest nodes in <<s'>> is identical to the set of honest nodes in <<s>>.\n       Formally, we have <<set_eq (GH s') (GH s)>>.\n   (3) All honest nodes have the same estimator in <<s'>>.\n\n   We will focus on the strategy for achieving (3), noting along the way that we're not breaking (1)\n   or (2). We achieve (3) by making sure that all estimators of honest nodes take the same input\n   in <<s'>>. Given that they are [equivocation_aware_estimator]s and, thus, ignore projections onto\n   nodes which they can locally prove equivocating, we can further split this goal in two:\n   (3.1) The honest nodes should see the same set of equivocating nodes locally.\n   (3.2) For each locally-honest-appearing node <<h>>, all honest nodes have identical projections onto\n       <<h>>\n\n   The most natural way to achieve (3.1) is to ensure that for all honest nodes <<i>>,\n   << set_eq (LH [i] s') (HH s') >>, i.e the set of locally-honest-looking nodes for each node\n   is equal to the set of nodes which would seem honest if we were to unite all observations\n   from honest nodes. << incl (HH s') (LH [i] s') >> holds trivially for any <<s'>>. For the other\n   direction, we will require honest nodes to share observations among themselves. This gives an initial\n   structure of our common future-finding algorithm:\n\n   Send Phase : All nodes in <<GH s>> do a send/update operation.\n   Receive Phase' : All nodes in <<GH s>> receive all messages sent in the Send Phase.\n\n   The point is that by sending and receiving these messages, honest nodes will be up-to-date\n   regarding each other, hence knowing what state everyone had back in <<s>> and thus obtaining\n   the observations held at that point as well. We can show that this process is protocol and\n   that the new observations introduced into the pool can't really contain new information and thus\n   do not alter <<GH s>> (or even <<HH s>>).\n\n   What about (3.2)? Our current algorithm doesn't necessarily solve (3.2), because there\n   may exist nodes in <<(HH s)>> which are outside of <<(GH s)>> and projections onto\n   these indices remain unaffected by our algorithm (so if they weren't precisely equal\n   in the beginning, we have a problem).\n\n   The solution is to generalize the Receive Phase as such:\n\n   Receive Phase : For all <<i>> in <<GH s>>, for all <<j>>, <<i>> will receive the message\n                   <<(j, top_s)>> where <<top_s>> is a state satisfying the following:\n                   - there exists <<k>> in <<GH s>> such that <<project (s k) j = top_s>>.\n                   - there is no other projection of this form which is greater than <<top_s>>\n                   - it is valid for <<i>> to receive <<top_s>>.\n\n   In other words, each honest <<i>> tries to update its <<j>> component to the freshest/most advanced\n   projection any honest validator has onto <<j>>. If there are several different maximal projections\n   (which can happen if <<j>> is equivocating), we select an arbitrary one that we can receive.\n   Note that it can happen that <<i>> sticks to its own projection onto <<j>>.\n\n   In the end what happens is that if <<j>> is in <<HH s'>>, then there can be a single topmost\n   projection, so everyone received the same thing. So if these projections should differ, we\n   can obtain a contradiction. Note also that our new Receive Phase still does what it did\n   initially for the honest validators: if <<j>> is in <<GH s>>, the topmost projection is simply\n   the message sent in the sending phase.\n*)\n\n\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 hbo_cobs' := (@hbo_cobs index i0 index_listing Hfinite idec Mindex Rindex).\n  Local Notation in_listing := (proj2 Hfinite).\n  Local Notation component_list s li := (List.map s li).\n\n  (* TODO: Delete this when possible. *)\n  Local 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  (* Returns a boolean <<b>> such that it is valid to perform an update transition\n     using <<b>> in state <<s who>> *)\n\n  Definition feasible_update_value (s : (@state index index_listing)) (who : index) : bool :=\n    match s with\n    | Bottom => false\n    | Something c is => match @bool_decide (@equivocation_aware_estimator index who index_listing Hfinite decide_eq _ _ s false)\n                                           (equivocation_aware_estimator_dec s false) with\n                        | true => false\n                        | false => true\n                        end\n    end.\n\n  (* Such a boolean doesn't exist if a node sees everyone as equivocating, so we need a hypothesis\n     to exclude this possibility. *)\n\n  Definition not_all_equivocating\n    (s : (@state index index_listing))\n    (who : index)\n    : Prop\n    := @no_equivocating_decisions index index_listing idec s\n      (@equivocating_validators (@state index index_listing) index Mindex Rindex (Hbasic who) s) <> [].\n\n  Definition no_component_fully_equivocating\n    (s : vstate X)\n    (li : list index) : Prop\n    := forall (i : index), In i li -> not_all_equivocating (s i) i.\n\n  Lemma feasible_update_value_correct\n    (s : (@state index index_listing))\n    (who : index)\n    (Hne : not_all_equivocating s who) :\n    (@equivocation_aware_estimator index who index_listing Hfinite decide_eq _ _ s (feasible_update_value s who)).\n  Proof.\n   destruct (feasible_update_value s who) eqn : eq_fv.\n   - unfold feasible_update_value in eq_fv.\n     destruct s;[intuition congruence|].\n     destruct (bool_decide (equivocation_aware_estimator (Something b is) false)) eqn : eq_ewb.\n     + intuition congruence.\n     + rewrite bool_decide_eq_false in eq_ewb.\n       apply ea_estimator_total in eq_ewb.\n       all : intuition.\n   - unfold feasible_update_value in eq_fv.\n     destruct s;[intuition|].\n     destruct (bool_decide (equivocation_aware_estimator (Something b is) false)) eqn : eq_ewb.\n     rewrite bool_decide_eq_true in eq_ewb. intuition.\n     intuition congruence.\n  Qed.\n\n  Definition feasible_update_single (s : (@state index index_listing)) (who : index) : plan_item :=\n    let cv := feasible_update_value s who in\n    let res := @list_transition index who _ _ (update cv) (s, None) in\n    @Build_plan_item _ (type (IM_index who)) (update cv) None.\n\n  Definition feasible_update_composite (s : vstate X) (who : index) : vplan_item X :=\n    lift_to_composite_plan_item IM_index who (feasible_update_single (s who) who).\n\n  (* Updates using the feasible value are protocol. *)\n\n  Lemma feasible_update_protocol\n    (s : vstate X)\n    (Hprs : protocol_state_prop _ s)\n    (who : index)\n    (Hne : not_all_equivocating (s who) who)\n    (item := feasible_update_composite s who) :\n    protocol_valid X (label_a item) (s, input_a item).\n  Proof.\n    unfold protocol_transition.\n    repeat split.\n    assumption.\n    simpl.\n    apply option_protocol_message_None.\n    apply feasible_update_value_correct with (s := s who) (who := who).\n    assumption.\n  Qed.\n\n  Definition chain_updates (li : list index) (s : vstate X) : plan X :=\n    List.map (feasible_update_composite s) li.\n\n  Lemma chain_updates_projections_out\n    (s : vstate X)\n    (li : list index)\n    (i : index)\n    (Hi : ~In i li)\n    (s' := snd (apply_plan X s (chain_updates li s))) :\n    (s' i) = (s i).\n  Proof.\n    apply irrelevant_components.\n    intros contra.\n    apply in_map_iff in contra.\n    destruct contra as [x [Heqproj contra]].\n    apply in_map_iff in contra.\n    destruct contra as [a [Heqlabel contra]].\n    unfold chain_updates in contra.\n    apply in_map_iff in contra.\n    destruct contra as [j [Hfease Hj]].\n    rewrite <- Heqlabel in Heqproj.\n    rewrite <- Hfease in Heqproj.\n    unfold feasible_update_composite in Heqproj.\n    simpl in Heqproj.\n    rewrite Heqproj in Hj.\n    intuition.\n  Qed.\n\n  (* Main lemma about the sending phase. *)\n\n  Lemma chain_updates_protocol\n    (s : vstate X)\n    (Hprs : protocol_state_prop _ s)\n    (li : list index)\n    (Hnodup : NoDup li)\n    (Hhonest : incl li (GH s))\n    (Hnf : no_component_fully_equivocating s li) :\n    let res := snd (apply_plan X s (chain_updates li s)) in\n    finite_protocol_plan_from _ s (chain_updates li s) /\\\n    (forall (i : index), In i li -> project (res i) i = s i) /\\\n    set_eq (GE res) (GE s).\n  Proof.\n    unfold no_component_fully_equivocating in Hnf.\n    generalize dependent s.\n    induction li as [|i li].\n    - intros.\n      simpl.\n      split.\n      + apply finite_ptrace_empty.\n        assumption.\n      + split; [intuition|].\n        simpl in res.\n        unfold res. intuition.\n    - intros.\n      remember (feasible_update_composite s i) as a.\n      specialize (Hnf i) as Hnfi.\n      spec Hnfi. {\n        intuition.\n      }\n      remember (vtransition X (label_a a) (s, input_a a)) as res_a.\n\n      assert (protocol_transition X (label_a a) (s, input_a a) res_a). {\n        rewrite Heqa.\n        unfold protocol_transition.\n        split.\n        - apply feasible_update_protocol.\n          all : assumption.\n        - rewrite Heqres_a.\n          unfold vtransition.\n          rewrite Heqa.\n          reflexivity.\n      }\n\n      unfold chain_updates.\n      replace (i :: li) with ([i] ++ li) by intuition.\n      rewrite map_app.\n\n      remember (snd (apply_plan X s (map (feasible_update_composite s) [i]))) as s'.\n\n      apply NoDup_cons_iff in Hnodup.\n      destruct Hnodup as [Hnoa Hnoli].\n      specialize (IHli Hnoli s').\n\n      spec IHli. {\n        rewrite Heqs'.\n        apply apply_plan_last_protocol.\n        assumption.\n        simpl.\n        apply finite_protocol_plan_from_one.\n        unfold protocol_transition in H.\n        rewrite <- Heqa.\n        unfold protocol_transition.\n        intuition.\n      }\n\n      assert (Hindif : forall (i : index), In i li -> s' i = s i). {\n        intros.\n        rewrite Heqs'.\n        apply irrelevant_components_one.\n        simpl.\n        intros contra.\n        rewrite contra in H0.\n        intuition.\n      }\n\n      assert (HGEs' : set_eq (GE s') (GE s)). {\n        unfold set_eq.\n        simpl in Heqs'.\n        rewrite Heqs'.\n        split.\n        + apply @GE_existing_same.\n          intuition.\n        + apply @GE_existing_same_rev.\n          intuition.\n          unfold GE.\n          rewrite <- wH_wE'.\n          apply Hhonest. intuition.\n      }\n\n      spec IHli. {\n        unfold incl in *.\n        intros idx Hidx.\n        unfold GE.\n        apply wH_wE'.\n        specialize (Hhonest idx).\n        setoid_rewrite HGEs'.\n        apply wH_wE'.\n        apply Hhonest.\n        intuition.\n      }\n\n      spec IHli. {\n        intros.\n        destruct (decide (i1 = i)).\n        + rewrite e in H0; intuition.\n        + specialize (Hindif i1 H0).\n          rewrite Hindif.\n          apply Hnf.\n          simpl.\n          right; intuition.\n      }\n\n      assert (Hchain : (map (feasible_update_composite s) li) = (map (feasible_update_composite s') li)). {\n        apply map_ext_in; intros j Hjli.\n        unfold feasible_update_composite.\n        replace (s' j) with (s j).\n        reflexivity.\n        symmetry.\n        apply Hindif.\n        intuition.\n      }\n\n      simpl in IHli.\n      split.\n      + apply finite_protocol_plan_from_app_iff.\n        split.\n        * unfold feasible_update_composite; simpl.\n          apply finite_protocol_plan_from_one.\n          unfold protocol_transition.\n          split.\n          apply feasible_update_protocol.\n          all : intuition.\n        * rewrite Heqs' in IHli at 1.\n          unfold chain_updates in IHli.\n          rewrite Hchain; intuition.\n      + unfold res; simpl.\n        change (feasible_update_composite s i :: chain_updates li s) with\n                ([feasible_update_composite s i] ++ chain_updates li s).\n        rewrite (apply_plan_app X).\n        destruct (apply_plan X s [feasible_update_composite s i]) as (tr_short, res_short) eqn : eq_short.\n        assert (res_short = snd (apply_plan X s [feasible_update_composite s i])) by (rewrite eq_short; intuition).\n        destruct (apply_plan X res_short (chain_updates li s)) as (tr_long, res_long) eqn : eq_long.\n        assert (res_long = snd (apply_plan X res_short (chain_updates li s))) by (rewrite eq_long; intuition).\n\n        assert (s' = res_short). {\n          rewrite Heqs'.\n          rewrite H0.\n          simpl.\n          reflexivity.\n        }\n\n        assert (Hsame : res_long i = res_short i). {\n          rewrite H1.\n          unfold chain_updates.\n          rewrite Hchain.\n          rewrite H2.\n          apply chain_updates_projections_out.\n          assumption.\n        }\n\n        split.\n        intros j Hjli.\n        * destruct (decide (j = i)).\n          -- simpl.\n             subst j.\n             rewrite Hsame.\n             rewrite H0.\n             unfold apply_plan.\n             unfold _apply_plan_folder; simpl.\n             rewrite state_update_eq.\n             rewrite <- update_consensus_clean with (value := (feasible_update_value (s i) i)).\n             rewrite (@project_same index index_listing Hfinite).\n             reflexivity.\n             apply protocol_state_component_no_bottom; intuition.\n          -- destruct IHli as [_ [IHli _]].\n             specialize (IHli j).\n             spec_save IHli. {\n               destruct Hjli;[intuition congruence|intuition].\n             }\n             specialize (Hindif j H3).\n             rewrite <- Hindif.\n             rewrite <- IHli.\n             simpl.\n             f_equal.\n             unfold chain_updates.\n             rewrite <- Hchain.\n             rewrite H2.\n             rewrite H1.\n             unfold chain_updates.\n             reflexivity.\n        * simpl.\n          assert (Hge_short : set_eq (GE res_short) (GE s)). {\n            remember (update_consensus (update_state (s i) (s i) i) (feasible_update_value (s i) i)) as new_si.\n            remember (state_update IM_index s i new_si) as new_s.\n            assert (Hu: res_short = new_s). {\n              rewrite H0.\n              rewrite Heqnew_s.\n              unfold apply_plan.\n              unfold feasible_update_composite; simpl.\n              rewrite Heqnew_si.\n              reflexivity.\n            }\n            specialize (GE_existing_same s Hprs (feasible_update_value (s i) i) i) as Hexist.\n            specialize (GE_existing_same_rev s Hprs (feasible_update_value (s i) i) i) as Hexist'.\n\n            spec Hexist'. {\n              unfold GE.\n              apply wH_wE'.\n              intuition.\n            }\n            simpl in Hexist, Hexist'.\n\n            rewrite Hu.\n            rewrite Heqnew_s.\n            rewrite Heqnew_si.\n            unfold set_eq.\n            split;[apply Hexist|apply Hexist'].\n          }\n\n          assert (Hge_long : set_eq (GE res_long) (GE res_short)). {\n            destruct IHli as [_ [_ IHli]].\n            unfold chain_updates in IHli.\n            rewrite <- Hchain in IHli.\n            rewrite H2 in IHli.\n            unfold chain_updates in H1.\n            rewrite H1.\n            apply IHli.\n          }\n\n          apply set_eq_tran with (s2 := (GE res_short)).\n          assumption.\n          assumption.\n  Qed.\n\n  (** Some wrappers for clarity of expoisition going forward. *)\n\n  Definition send_phase_plan (s : vstate X) : plan X :=\n    chain_updates (GH s) s.\n\n  Definition send_phase (s : vstate X) : list (vtransition_item X) * vstate X :=\n    apply_plan X s (send_phase_plan s).\n\n  Definition send_phase_result\n    (s : vstate X) :=\n    snd (send_phase s).\n\n  Definition send_phase_transitions\n    (s : vstate X) :=\n    fst (send_phase s).\n\n  Remark send_phase_protocol\n    (s : vstate X)\n    (Hprs : protocol_state_prop X s)\n    (Hnf : no_component_fully_equivocating s (GH s)) :\n    finite_protocol_plan_from X s (send_phase_plan s).\n  Proof.\n    unfold send_phase_plan.\n    specialize (chain_updates_protocol s Hprs (GH s) (GH_NoDup s)) as Hchain.\n    spec Hchain. intuition.\n    specialize (Hchain Hnf). simpl in Hchain.\n    unfold send_phase_result.\n    destruct Hchain as [Hchain1 [Hchain2 Hchain3]].\n    intuition.\n  Qed.\n\n  Corollary send_phase_result_protocol\n    (s : vstate X)\n    (Hprs : protocol_state_prop X s)\n    (Hnf : no_component_fully_equivocating s (GH s))\n    (res_send := send_phase_result s) :\n    protocol_state_prop X res_send.\n  Proof.\n    apply apply_plan_last_protocol.\n    intuition.\n    apply send_phase_protocol.\n    all : intuition.\n  Qed.\n\n  Remark send_phase_GE\n    (s : vstate X)\n    (Hprs : protocol_state_prop X s)\n    (Hnf : no_component_fully_equivocating s (GH s)) :\n    set_eq (GE (send_phase_result s)) (GE s).\n  Proof.\n    unfold send_phase_plan.\n    specialize (chain_updates_protocol s Hprs (GH s) (GH_NoDup s)) as Hchain.\n    spec Hchain. intuition.\n    specialize (Hchain Hnf). simpl in Hchain.\n    unfold send_phase_result.\n    destruct Hchain as [Hchain1 [Hchain2 Hchain3]].\n    unfold send_phase. intuition.\n  Qed.\n\n  Remark send_phase_future\n    (s : vstate X)\n    (Hnf : no_component_fully_equivocating s (GH s))\n    (Hspr : protocol_state_prop _ s) :\n    in_futures _ s (send_phase_result s).\n  Proof.\n    unfold in_futures.\n    exists (send_phase_transitions s).\n    apply ptrace_add_last.\n    apply send_phase_protocol;assumption.\n    unfold send_phase_transitions.\n    unfold send_phase_result.\n    apply (apply_plan_last X).\n  Qed.\n\n  Remark send_phase_result_projections\n    (s : vstate X)\n    (Hprss : protocol_state_prop _ s)\n    (Hnf : no_component_fully_equivocating s (GH s))\n    (i : index)\n    (Hin : In i (GH s))\n    (s' := send_phase_result s) :\n    project (s' i) i = (s i).\n  Proof.\n    apply chain_updates_protocol.\n    intuition.\n    apply GH_NoDup.\n    all : intuition.\n  Qed.\n\n  Remark non_self_projections_same_after_send_phase\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (Hnf : no_component_fully_equivocating s (GH s))\n    (res_send := send_phase_result s) :\n    forall (i j : index), i <> j -> project (res_send i) j = project (s i) j.\n  Proof.\n    intros.\n    specialize (non_self_projections_same_after_sends s Hpr (send_phase_plan s)) as Hsame.\n    spec Hsame. {\n      apply send_phase_protocol.\n      intuition.\n      intuition.\n    }\n    spec Hsame. {\n      intros.\n      apply in_map_iff in H0.\n      destruct H0 as [k [Heq Hink]].\n      unfold feasible_update_composite in Heq.\n      unfold feasible_update_single in Heq.\n      simpl in Heq.\n      rewrite <- Heq.\n      simpl.\n      exists (feasible_update_value (s k) k).\n      intuition.\n    }\n    specialize (Hsame i j H).\n    intuition.\n  Qed.\n\n  Definition lift_to_receive_item (to from : index) (s : state): vplan_item (IM_index to) :=\n    @Build_plan_item _ (type (IM_index to)) receive (Some (from, s)).\n\n  (** Construct a [plan X] such that <s to> will receive the messages\n     in <ls>. *)\n\n  Definition sync_plan (to from : index) (ls : list state) : (plan X) :=\n    let tmp := List.map (lift_to_receive_item to from) ls in\n    List.map (lift_to_composite_plan_item IM_index to) tmp.\n\n  (** Construct a plan which syncs up <<project (s to) from>> with\n     <<project s' from>> via receiving messages. If the states' <<from>> histories\n     don't match, None is returned.\n     See [Lib/ListExtras.v] for [complete_suffix]. *)\n\n  Definition sync (s : vstate X) (s': state) (to from : index) : option (plan X) :=\n    let history_s := get_history (s to) from in\n    let history_s' := get_history s' from in\n    let rem_states := complete_suffix history_s' history_s in\n    match rem_states with\n    | None => None\n    | Some ss => let rem_plan := sync_plan to from (rev ss) in\n                 Some rem_plan\n    end.\n\n  (** The syncing plan is protocol and it does what is expected.\n    Note the index <<inter>>, which denotes the validator which\n    owns the projection we will choose to sync to. *)\n\n  Lemma one_sender_receive_protocol\n    (s s': vstate X)\n    (Hpr : protocol_state_prop X s)\n    (Hpr' : protocol_state_prop X s')\n    (to inter from : index)\n    (Hhist : get_history (s inter) from = get_history (s' inter) from)\n    (Hdif : to <> from)\n    (a : plan X)\n    (Hsync : sync s (s' inter) to from = Some a) :\n    let res := snd (apply_plan X s a) in\n    finite_protocol_plan_from X s a /\\\n    (project (res to) from = project (s' inter) from).\n   Proof.\n    generalize dependent s.\n    induction a.\n    - intros. simpl in *.\n      unfold finite_protocol_plan_from. simpl.\n      repeat split.\n        + apply finite_ptrace_empty.\n          assumption.\n        + unfold res.\n          unfold sync in Hsync.\n          destruct (complete_suffix (get_history (s' inter) from) (get_history (s to) from)) eqn : eq_cs.\n          2 : discriminate Hsync.\n          apply complete_suffix_correct in eq_cs.\n          assert (l = []). {\n            inversion Hsync.\n            unfold sync_plan in H0.\n            apply map_eq_nil in H0.\n            apply map_eq_nil in H0.\n            destruct (decide (length l = 0)).\n            - apply length_zero_iff_nil in e. intuition.\n            - apply length_zero_iff_nil in H0. rewrite rev_length in H0. congruence.\n          }\n          rewrite H in eq_cs. simpl in eq_cs.\n          symmetry in eq_cs.\n          apply (@eq_history_eq_project index index_listing Hfinite) in eq_cs.\n          assumption.\n    - intros. simpl in *.\n\n      change (a :: a0) with ([a] ++ a0).\n      rewrite <- finite_protocol_plan_from_app_iff.\n\n      unfold sync in Hsync.\n      destruct (complete_suffix (get_history (s' inter) from) (get_history (s to) from)) eqn : eq_cs. 2: discriminate Hsync.\n\n      inversion Hsync.\n      unfold sync_plan in H0.\n      apply map_eq_cons in H0.\n      destruct H0 as [a1 [tl [H0 [Hh Htl]]]].\n      apply map_eq_cons in H0.\n      destruct H0 as [sa [tls [H0 [Hh' Htl']]]].\n      assert (eq_cs_orig := eq_cs).\n      apply complete_suffix_correct in eq_cs.\n      replace (sa :: tls) with ([sa] ++ tls) in H0. 2: auto.\n      apply rev_eq_app in H0. simpl in H0.\n\n      rewrite H0 in eq_cs.\n      assert (eq_cs' := eq_cs).\n      rewrite <- app_assoc in eq_cs.\n      apply (@unfold_history index index_listing Hfinite) in eq_cs.\n\n      assert (Hecs: project (s to) from = project sa from). {\n        apply (@eq_history_eq_project index index_listing Hfinite _ (s to) sa from).\n        assumption.\n      }\n\n      assert (Hinsa: In sa (get_history (s' inter) from)). {\n        rewrite eq_cs'.\n        rewrite <- app_assoc.\n        apply in_elt.\n      }\n\n      destruct a.\n      destruct (vtransition X label_a (s, input_a)) eqn : eq_vtrans. simpl.\n\n      unfold lift_to_receive_item in Hh'.\n      rewrite <- Hh' in Hh.\n      unfold lift_to_composite_plan_item in Hh.\n\n      assert (Hinp: input_a = Some (from, sa)). {\n        inversion Hh.\n        reflexivity.\n      }\n\n      assert (protocol_transition X label_a (s, input_a) (s0, o)). {\n        unfold protocol_transition.\n        repeat split.\n        - assumption.\n        - subst input_a.\n          apply option_protocol_message_Some.\n          destruct (decide (inter = from)).\n          + specialize (sent_component_protocol_composed IM_index (free_constraint IM_index) Hfinite has_been_sent_capabilities (fun m => Some (fst m)) s') as Hope.\n            spec Hope. assumption.\n            specialize (Hope inter (from, sa)).\n            apply Hope.\n            unfold has_been_sent.\n            simpl.\n            unfold send_oracle; simpl.\n            rewrite decide_True.\n            apply Is_true_eq_left.\n            rewrite existsb_exists.\n            exists sa.\n            split.\n            rewrite <- e in Hinsa.\n            rewrite <- e.\n            assumption.\n            unfold state_eqb. rewrite eq_dec_if_true. all : auto.\n          + specialize (received_component_protocol_composed IM_index (free_constraint IM_index) Hfinite has_been_received_capabilities s') as Hope.\n            spec Hope. assumption.\n            specialize (Hope inter (from, sa)).\n            apply Hope.\n            unfold has_been_received.\n            simpl.\n            unfold receive_oracle; simpl.\n            rewrite decide_False.\n            apply Is_true_eq_left.\n            apply existsb_exists.\n            exists sa.\n            split.\n            assumption.\n            unfold state_eqb. rewrite eq_dec_if_true. all : auto.\n        - simpl in *.\n          inversion Hh.\n          unfold vvalid.\n          apply (@no_bottom_in_history index index_listing Hfinite) in Hinsa.\n          unfold valid. simpl.\n          repeat split.\n          all : intuition.\n        - intuition.\n      }\n\n      subst input_a.\n      unfold res.\n\n      specialize (IHa s0).\n      spec IHa.\n      apply protocol_transition_destination in H.\n      assumption.\n\n      assert (Hs0 : s0 = (state_update IM_index s to (update_state (s to) sa from))). {\n        destruct H as [_ H].\n        unfold transition in H.\n        simpl in H. unfold vtransition in H. unfold transition in H. simpl in H.\n        inversion Hh.\n        rewrite <- H2 in H.\n        inversion H.\n        intuition.\n      }\n\n      assert (Honefold: get_history (s0 to) from = [sa] ++ get_history (s to) from). {\n          assert (project (s0 to) from = sa). {\n              rewrite Hs0. rewrite state_update_eq.\n              apply (@project_same index index_listing Hfinite).\n              apply protocol_state_component_no_bottom. intuition.\n          }\n            subst sa.\n            rewrite eq_cs.\n            apply (@unfold_history_cons index index_listing Hfinite).\n            apply (@no_bottom_in_history index index_listing Hfinite) in Hinsa.\n            assumption.\n        }\n\n      assert (Hneed : s0 inter = s inter). {\n        rewrite Hs0.\n        destruct (decide(to = inter)).\n        - subst inter.\n          rewrite Hhist in eq_cs'.\n          clear -eq_cs'.\n          remember (length (get_history (s' to) from)) as len.\n          assert (length (get_history (s' to) from) = length ((rev tls ++ [sa]) ++ get_history (s' to) from)). {\n            rewrite <- eq_cs'.\n            intuition.\n          }\n          rewrite <- Heqlen in H.\n          rewrite app_length in H.\n          rewrite <- Heqlen in H.\n          rewrite app_length in H.\n          simpl in H.\n          lia.\n        - rewrite state_update_neq.\n          all : intuition.\n      }\n\n      spec IHa. {\n        rewrite Hneed.\n        intuition.\n      }\n\n      spec IHa. {\n        unfold sync.\n        destruct (complete_suffix (get_history (s' inter) from) (get_history (s0 to) from)) eqn : eq_cs2.\n        f_equal.\n          unfold sync_plan.\n          rewrite <- Htl.\n          rewrite <- Htl'.\n          repeat f_equal.\n          apply complete_suffix_correct in eq_cs2.\n          rewrite Honefold in eq_cs2.\n          rewrite eq_cs' in eq_cs2.\n          rewrite app_assoc in eq_cs2.\n          apply app_inv_tail in eq_cs2.\n          apply app_inj_tail in eq_cs2.\n          destruct eq_cs2.\n          rewrite <- H1.\n          apply rev_involutive.\n        + rewrite Honefold in eq_cs2.\n          rewrite eq_cs' in eq_cs2.\n          rewrite <- app_assoc in eq_cs2.\n          assert (complete_suffix (rev tls ++ [sa] ++ get_history (s to) from)\n           ([sa] ++ get_history (s to) from) = Some (rev tls)). {\n            apply complete_suffix_correct.\n            reflexivity.\n          }\n          rewrite H1 in eq_cs2.\n          discriminate eq_cs2.\n      }\n      unfold finite_protocol_plan_from at 1.\n      unfold apply_plan, _apply_plan. simpl in *.\n      rewrite fold_right_app. simpl.\n      match goal with\n      |- context [let (_,_) := let (_,_) := ?t in _ in _] =>\n        replace t with (s0, o)\n      end.\n      simpl in *.\n      repeat split.\n      + apply first_transition_valid. assumption.\n      + apply IHa.\n      + destruct IHa as [_ IHa].\n        rewrite <- IHa.\n        unfold apply_plan, _apply_plan. simpl.\n        f_equal.\n        specialize (@_apply_plan_folder_additive _ (type X) (vtransition X) s0 (rev a0) ) as Hadd.\n\n        match goal with\n        |- context[[?item]] => specialize (Hadd [item])\n        end.\n        simpl in Hadd. simpl.\n        match goal with\n        |- _ = snd (let (final, items) := ?f in _) to =>\n          destruct f as (tr', dest') eqn : eqf2\n        end.\n        match type of Hadd with\n        | let (_,_) := ?f in _ => replace f with (tr', dest') in Hadd\n        end.\n        simpl in *.\n        match goal with\n        |- snd (let (final, items) := ?f in _) to = _ =>\n          match type of Hadd with _ = ?r =>\n            replace f  with r\n          end\n        end.\n        reflexivity.\n    Qed.\n\n   (** We look for suitable projections among the honest validators *)\n\n    Definition get_candidates\n      (s : vstate X) :\n      list state\n      :=\n    component_list s (GH s).\n\n    Existing Instance state_lt'_dec.\n    Existing Instance state_lt_ext_dec.\n\n    (** Retain only projections which are maximal, i.e, no other projections\n       compare greater to them. *)\n\n    Definition get_topmost_candidates\n      (s : vstate X)\n      (target : index) :\n      list state\n      :=\n      get_maximal_elements (fun s s' => bool_decide (state_lt_ext target (project s target) (project s' target))) (get_candidates s).\n\n    (** If <<i>> is honest, all candidate projections onto <<i>> compare less than\n       <<(s i)>> *)\n\n    Lemma honest_self_projections_maximal1\n      (s : vstate X)\n      (Hpr : protocol_state_prop X s)\n      (i j : index)\n      (Hhonest : In i (GH s)) :\n      state_lt_ext i (project (s j) i) (s i).\n    Proof.\n      assert (Hsnb : forall (i : index), (s i) <> Bottom). {\n        intros.\n        apply protocol_state_component_no_bottom.\n        intuition.\n      }\n    unfold state_lt_ext.\n    destruct (s i) eqn : eq_si;[specialize (Hsnb i);congruence|].\n    destruct (project (s j) i) eqn : eq_pji;[left; intuition congruence|].\n    destruct (decide (state_lt' i (project (s j) i) (s i)));right; rewrite <- eq_si; rewrite <- eq_pji.\n    - intuition.\n    - assert (He : In i (GE s)). {\n        apply GE_direct.\n        unfold cequiv_evidence.\n        unfold equivocation_evidence.\n        setoid_rewrite hbo_cobs'.\n        exists (SimpObs State' i (s i)).\n        unfold get_simp_event_subject_some. simpl.\n        split.\n        - apply in_cobs_states'.\n          apply state_obs_present. apply in_listing.\n        - split;[intuition|].\n          exists (SimpObs Message' i (project (s j) i)). simpl.\n          split.\n          + apply in_cobs_messages'.\n            apply cobs_single_m.\n            exists j. split;[apply in_listing|].\n            apply refold_simp_lv_observations1.\n            apply Hsnb.\n            rewrite eq_pji. congruence.\n            intuition.\n          + split;[intuition|].\n            unfold simp_lv_event_lt.\n            unfold comparable.\n            rewrite decide_True by intuition.\n            intros contra.\n            destruct contra.\n            * congruence.\n            * rewrite decide_True in H by intuition.\n              destruct H;[intuition|].\n              intuition.\n      }\n      unfold GH in Hhonest.\n      apply wH_wE' in Hhonest. intuition.\n  Qed.\n\n  (** Similar statement, stating a <= relation with <<project (s i) i>>. *)\n\n  Lemma honest_self_projections_maximal2\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (i j : index)\n    (Hhonest : In i (GH s)) :\n    project (s j) i = project (s i) i \\/ state_lt_ext i (project (s j) i) (project (s i) i).\n  Proof.\n    assert (Hsnb : forall (i : index), (s i) <> Bottom). {\n      intros.\n      apply protocol_state_component_no_bottom.\n      intuition.\n    }\n    unfold state_lt_ext.\n    destruct (s i) eqn : eq_si;[specialize (Hsnb i);congruence|]. rewrite <- eq_si.\n\n    specialize (honest_self_projections_maximal1 s Hpr i j Hhonest) as Hh.\n    destruct (project (s i) i) eqn : eq_pii.\n    - destruct (project (s j) i) eqn : eq_pji.\n      + left. intuition.\n      + rewrite <- eq_pji in *.\n        unfold state_lt_ext in Hh.\n        destruct Hh;[intuition congruence|].\n        unfold state_lt' in H.\n        rewrite unfold_history_bottom in H by intuition.\n        intuition.\n    - unfold state_lt_ext in Hh.\n      destruct Hh;[intuition congruence|].\n      rewrite <- eq_pii in *.\n      destruct (project (s j) i) eqn : eq_pji;[right;left;intuition congruence|].\n      rewrite <- eq_pji in *.\n      destruct (decide (project (s j) i = project (s i) i));[left;intuition|].\n      right. right.\n\n      unfold state_lt' in H.\n      apply in_split in H as H2.\n      destruct H2 as [left1 [right1 Heq1]].\n      apply (@unfold_history index index_listing Hfinite) in Heq1 as Heq1'.\n      rewrite Heq1' in Heq1.\n      rewrite (@unfold_history_cons index index_listing Hfinite) in Heq1 by (intuition congruence).\n      destruct left1.\n      + simpl in Heq1. inversion Heq1. congruence.\n      + inversion Heq1.\n        unfold state_lt'.\n        rewrite H2.\n        apply in_app_iff. right. intuition.\n  Qed.\n\n  Lemma honest_always_candidate_for_self\n      (s : vstate X)\n      (Hpr : protocol_state_prop X s)\n      (i : index)\n      (Hhonest : In i (GH s)) :\n      In (s i) (get_topmost_candidates s i).\n  Proof.\n     - unfold get_topmost_candidates.\n      unfold get_maximal_elements.\n      apply filter_In.\n      split.\n      + unfold get_candidates. apply in_map_iff. exists i. intuition.\n      + rewrite forallb_forall. intros.\n        rewrite negb_true_iff.\n        rewrite bool_decide_eq_false.\n        apply in_map_iff in H.\n        destruct H as [j [Heqj Hinj]]. subst x.\n        specialize (honest_self_projections_maximal2 s Hpr i j Hhonest) as Hh.\n        intros contra.\n        destruct Hh.\n        * unfold state_lt_ext in contra.\n          destruct contra;[intuition congruence|].\n          rewrite H in H0.\n          unfold state_lt' in H0.\n          apply (@history_no_self_reference index index_listing Hfinite) in H0.\n          intuition.\n        * apply (@state_lt_ext_antisymmetric index index_listing Hfinite) in H.\n          intuition.\n  Qed.\n\n  Lemma all_candidates_for_honest_equiv\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (i : index)\n    (Hhonest : In i (GH s)) :\n    forall (s' : (@state index index_listing)),\n    In s' (get_topmost_candidates s i) -> project s' i = project (s i) i.\n  Proof.\n    intros.\n    unfold get_topmost_candidates in H.\n    unfold get_maximal_elements in H.\n    apply filter_In in H.\n    destruct H as [Hin H].\n    rewrite forallb_forall in H.\n    specialize (H (s i)).\n    spec H. {\n      apply in_map_iff. exists i. intuition.\n    }\n    rewrite negb_true_iff in H.\n    rewrite bool_decide_eq_false in H.\n    destruct (decide (project (s i) i = project s' i));[intuition|].\n\n    apply in_map_iff in Hin.\n    destruct Hin as [j [Heqj Hj]].\n    subst s'.\n    specialize (honest_self_projections_maximal2 s Hpr i j Hhonest) as Hh.\n    destruct Hh;[intuition congruence|].\n    intuition.\n  Qed.\n\n  (** Find the state we want to sync to.\n     Choose a candidate for which syncing is valid. If none exists, default to your\n     own projection. *)\n\n    Definition get_matching_state\n      (s : vstate X)\n      (to from : index) : state :=\n      let candidates := (get_topmost_candidates s from) in\n      let found := List.find (fun s' => bool_decide (state_lt_ext from (project (s to) from) s')) candidates in\n      match found with\n      | Some s' => s'\n      | None => (s to)\n      end.\n\n    Remark get_matching_state_correct1\n      (s : vstate X)\n      (to from : index) :\n      exists (inter : index), (get_matching_state s to from) = (s inter) /\\\n      (inter = to \\/ (In inter (GH s))).\n    Proof.\n      unfold get_matching_state.\n      destruct (find (fun s' : state => bool_decide (state_lt_ext from (project (s to) from) s'))\n      (get_topmost_candidates s from)) eqn : eq_find.\n      - apply find_some in eq_find.\n        destruct eq_find as [eq_find _].\n        unfold get_topmost_candidates in eq_find.\n        unfold get_maximal_elements in eq_find.\n        apply filter_In in eq_find.\n        destruct eq_find as [eq_find _].\n        unfold get_candidates in eq_find.\n        unfold component_list in eq_find.\n        apply in_map_iff in eq_find.\n        destruct eq_find as [inter Hinter].\n        exists inter. intuition.\n      - exists to. intuition.\n    Qed.\n\n    Remark get_matching_state_correct2\n      (s : vstate X)\n      (to from : index)\n      (Hin : In to (GH s)) :\n      exists (inter : index), In inter (GH s) /\\ (get_matching_state s to from) = (s inter).\n    Proof.\n      specialize (get_matching_state_correct1 s to from) as H1.\n      destruct H1 as [inter Hinter].\n      exists inter.\n      destruct Hinter as [Hmatch Hinter].\n      destruct Hinter;[subst to;intuition|intuition].\n    Qed.\n\n    (** The following results are used to show that there exists at least\n       one maximal candidate. We do this by relating the comparison operator\n       to comparing history lengths between candidates. The maximal candidate\n       will have the longest <<from>> history. *)\n\n    Definition top_history\n      (s : vstate X)\n      (from : index) :=\n      let history_lengths := List.map (fun s' : state => length (get_history s' from)) (get_candidates s) in\n      let max_length := list_max history_lengths in\n      filter (fun s' : state => beq_nat (length (get_history s' from)) max_length) (get_candidates s).\n\n    Lemma top_history_something\n      (s : vstate X)\n      (H : GH s <> [])\n      (from : index) :\n      exists (s' : state), In s' (top_history s from).\n    Proof.\n      unfold top_history.\n      specialize (list_max_exists2 (List.map (fun s' : state => length (get_history s' from)) (get_candidates s))) as Hmax.\n      spec Hmax. {\n        destruct (map (fun s' : state => length (get_history s' from)) (get_candidates s)) eqn : eq.\n        apply map_eq_nil in eq.\n        unfold get_candidates in eq.\n        apply map_eq_nil in eq. intuition congruence.\n        intuition congruence.\n      }\n      apply in_map_iff in Hmax.\n      destruct Hmax.\n      exists x. apply filter_In. split;[intuition|].\n      rewrite beq_nat_true_iff. intuition.\n    Qed.\n\n    Lemma topmost_candidates_nonempty\n      (s : vstate X)\n      (from : index)\n      (Hne : GH s <> []) :\n      exists (s' : state), In s' (get_topmost_candidates s from).\n    Proof.\n      specialize (top_history_something s Hne from) as Htop_hist.\n      destruct Htop_hist as [s' Htop].\n      exists s'.\n      unfold get_topmost_candidates.\n      apply filter_In.\n      unfold top_history in Htop.\n      apply filter_In in Htop.\n      split;[intuition|].\n      destruct Htop as [_ Htop].\n      rewrite beq_nat_true_iff in Htop.\n      rewrite forallb_forall.\n      intros.\n      rewrite negb_true_iff.\n      rewrite bool_decide_eq_false.\n      intros contra.\n      specialize (list_max_le (map (fun s'0 : state => length (get_history s'0 from)) (get_candidates s))) as Hmax.\n      specialize (Hmax (length (get_history s' from))).\n      rewrite Htop in Hmax.\n      destruct Hmax as [Hmax _]. spec Hmax. lia.\n      rewrite Forall_forall in Hmax.\n      specialize (Hmax (length (get_history x from))).\n      spec Hmax. {\n        apply in_map_iff.\n        exists x. intuition.\n      }\n      rewrite <- Htop in Hmax.\n      unfold state_lt_ext in contra.\n      destruct contra.\n      - assert (get_history s' from = []) by (apply unfold_history_bottom;intuition).\n        rewrite H1 in Hmax. simpl in Hmax.\n        rewrite (@unfold_history_cons index index_listing Hfinite) in Hmax.\n        simpl in Hmax. lia. intuition.\n      - unfold state_lt' in H0.\n        apply in_split in H0.\n        destruct H0 as [left [right Hhist]].\n        replace (left ++ project s' from :: right) with (left ++ [project s' from] ++ right) in Hhist.\n        2 : intuition.\n        specialize (@unfold_history index index_listing Hfinite _ (project x from) (project s' from) from) as Hunf.\n        specialize (Hunf left right Hhist).\n        rewrite Hunf in Hhist.\n        assert (length (get_history (project x from) from) > length (get_history (project s' from) from)). {\n          rewrite Hhist.\n          simpl.\n          rewrite app_length. simpl. lia.\n        }\n\n        destruct (project x from) eqn : eq_b;[simpl in *;lia|].\n        rewrite (@unfold_history_cons index index_listing Hfinite) in Hmax by (intuition congruence).\n        simpl in Hmax.\n        destruct (project s' from) eqn : eq_b2.\n        + assert (get_history s' from = []) by (apply unfold_history_bottom;intuition).\n          rewrite H1 in Hmax. simpl in Hmax. lia.\n        + assert (get_history s' from = (project s' from) :: get_history (project s' from) from). {\n            apply (@unfold_history_cons index index_listing Hfinite). intuition congruence.\n          }\n          rewrite H1 in Hmax.\n          simpl in Hmax.\n          rewrite eq_b in Hmax. rewrite eq_b2 in Hmax.\n          lia.\n    Qed.\n\n    Remark get_matching_state_correct3\n      (s : vstate X)\n      (to from : index)\n      (Hin : In to (GH s))\n      (Hcomp : forall (i j : index),\n               In i (GH s) ->\n               In j (GH s) ->\n               comparable (state_lt_ext from) (project (s i) from) (project (s j) from)) :\n      In (get_matching_state s to from) (get_topmost_candidates s from).\n    Proof.\n      unfold get_matching_state.\n      destruct (find (fun s' : state => bool_decide (state_lt_ext from (project (s to) from) s'))\n      (get_topmost_candidates s from)) eqn : eq_find.\n      - apply find_some in eq_find. intuition.\n      - unfold get_topmost_candidates.\n        unfold get_maximal_elements.\n        apply filter_In.\n        split.\n        + apply in_map_iff. exists to. intuition.\n        + rewrite forallb_forall. intros.\n          rewrite negb_true_iff.\n          rewrite bool_decide_eq_false.\n          intros contra.\n          specialize (find_none (fun s' : state => bool_decide (state_lt_ext from (project (s to) from) s'))) as Hnone.\n          specialize (Hnone (get_topmost_candidates s from) eq_find).\n\n          apply in_map_iff in H.\n          destruct H as [k [Hk Hk']].\n\n          specialize (topmost_candidates_nonempty s from) as Htop.\n          spec Htop. destruct (GH s); intuition congruence.\n          destruct Htop as [s' Htop].\n          specialize (Hnone s' Htop).\n          simpl in Hnone. rewrite bool_decide_eq_false in Hnone.\n\n          unfold get_topmost_candidates in Htop.\n          unfold get_maximal_elements in Htop.\n\n          apply filter_In in Htop.\n          destruct Htop as [Hins' Htop].\n          rewrite forallb_forall in Htop.\n\n          apply in_map_iff in Hins'.\n          destruct Hins' as [l [Heql Hinl]].\n          specialize (Hcomp k l Hk' Hinl).\n          subst x. subst s'.\n          specialize (Htop (s k)).\n          spec Htop. apply in_map_iff. exists k; intuition.\n          rewrite negb_true_iff in Htop.\n          rewrite bool_decide_eq_false in Htop.\n          unfold comparable in Hcomp.\n          destruct Hcomp as [Hcomp|Hcomp].\n          * rewrite Hcomp in contra.\n            apply (@state_lt_ext_proj index index_listing Hfinite) in contra.\n            intuition.\n          * destruct Hcomp as [Hcomp|Hcomp].\n            -- assert (state_lt_ext from (project (s to) from) (project (s l) from)). {\n                apply (@state_lt_ext_tran index index_listing Hfinite) with (s2 := (project (s k) from)); intuition.\n              }\n              apply (@state_lt_ext_proj index index_listing Hfinite) in H.\n              intuition.\n            -- intuition.\n   Qed.\n\n   Lemma get_matching_state_for_honest\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (i j : index)\n    (Hhonest : In i (GH s)) :\n    project (get_matching_state s j i) i = project (s i) i.\n  Proof.\n    unfold get_matching_state.\n    destruct (find (fun s' : state => bool_decide (state_lt_ext i (project (s j) i) s'))\n    (get_topmost_candidates s i)) eqn : eq_find.\n    - apply find_some in eq_find.\n      destruct eq_find as [Hin Hcomp].\n      rewrite bool_decide_eq_true in Hcomp.\n      specialize (all_candidates_for_honest_equiv s Hpr i Hhonest).\n      intros.\n      specialize (H s0 Hin).\n      intuition.\n    - specialize (find_none (fun s' : state => bool_decide (state_lt_ext i (project (s j) i) s'))) as Hnone.\n      specialize (Hnone (get_topmost_candidates s i) eq_find).\n      specialize (Hnone (s i)).\n\n      assert (In (s i) (get_topmost_candidates s i)). {\n         apply honest_always_candidate_for_self.\n         intuition.\n         intuition.\n      }\n\n      specialize (Hnone H).\n      simpl in Hnone.\n      rewrite bool_decide_eq_false in Hnone.\n      specialize (honest_self_projections_maximal1 s Hpr i j Hhonest) as Hh.\n      intuition.\n  Qed.\n\n    Definition get_matching_plan\n      (s : vstate X)\n      (from to : index) : plan X :=\n      match (sync s (get_matching_state s to from) to from) with\n      | None => []\n      | Some a => a\n      end.\n\n    Lemma sync_some\n      (s : vstate X)\n      (from to : index) :\n      sync s (get_matching_state s to from) to from <> None.\n    Proof.\n      intros contra.\n      unfold get_matching_state in contra.\n      destruct (find (fun s' : state => bool_decide (state_lt_ext from (project (s to) from) s'))\n               (get_topmost_candidates s from)) eqn : eq_find.\n      - apply find_some in eq_find.\n        destruct eq_find as [_ eq_find].\n        unfold sync in contra.\n        destruct (complete_suffix (get_history s0 from) (get_history (s to) from)) eqn : eq_suf.\n        discriminate contra.\n        unfold state_ltb' in eq_find.\n        rewrite bool_decide_eq_true in eq_find.\n        unfold state_lt_ext in eq_find.\n        destruct eq_find as [eq_find|eq_find].\n        + destruct eq_find as [Hb _].\n          apply unfold_history_bottom in Hb.\n          rewrite Hb in eq_suf.\n          rewrite complete_suffix_empty in eq_suf.\n          congruence.\n        + unfold state_lt' in eq_find.\n          assert (eq_find' := eq_find).\n          apply in_split in eq_find.\n          destruct eq_find as [pref [suff Heq]].\n          apply (@unfold_history index index_listing) in Heq as Hsufhist.\n          rewrite Hsufhist in Heq.\n          apply complete_suffix_correct in Heq.\n          assert ((project (s to) from :: get_history (project (s to) from) from) = get_history (s to) from). {\n            symmetry.\n            apply (@unfold_history_cons index index_listing).\n            assumption.\n            apply (@no_bottom_in_history index index_listing Hfinite idec s0 _ from).\n            intuition.\n          }\n        rewrite H in Heq.\n        rewrite Heq in eq_suf.\n        discriminate eq_suf.\n        intuition.\n       - unfold sync in contra.\n         destruct (complete_suffix (get_history (s to) from) (get_history (s to) from)) eqn : eq_suf.\n         + discriminate contra.\n         + assert (get_history (s to) from = [] ++ (get_history (s to) from)). {\n            intuition.\n           }\n           apply complete_suffix_correct in H.\n           rewrite H in eq_suf.\n           discriminate eq_suf.\n    Qed.\n\n    Lemma get_matching_plan_effect\n      (s : vstate X)\n      (Hprs : protocol_state_prop X s)\n      (s' : state)\n      (from to : index)\n      (Hdif : from <> to)\n      (Hmatch : get_matching_state s to from = s') :\n      let res := snd (apply_plan X s (get_matching_plan s from to)) in\n      finite_protocol_plan_from X s (get_matching_plan s from to) /\\\n      project (res to) from = project s' from.\n    Proof.\n      simpl.\n      unfold get_matching_plan.\n      rewrite Hmatch.\n      destruct (sync s s' to from) eqn : eq_sync.\n      - unfold sync in eq_sync.\n        destruct (complete_suffix (get_history s' from) (get_history (s to) from)) eqn : eq_suf;[|congruence].\n        assert (eq_suf_original := eq_suf).\n        apply complete_suffix_correct in eq_suf.\n        inversion eq_sync.\n        specialize (one_sender_receive_protocol s s Hprs Hprs to) as Hone.\n        unfold get_matching_state in Hmatch.\n        destruct (find (fun s'0 : state => bool_decide (state_lt_ext from (project (s to) from) s'0))\n             (get_topmost_candidates s from)) eqn : eq_find.\n        + apply find_some in eq_find.\n          destruct eq_find as [eq_find _].\n          unfold get_topmost_candidates in eq_find.\n          unfold get_maximal_elements in eq_find.\n          apply filter_In in eq_find.\n          destruct eq_find as [eq_find _].\n          unfold get_candidates in eq_find.\n          unfold component_list in eq_find.\n          apply in_map_iff in eq_find.\n          destruct eq_find as [inter [Hinter _]].\n\n          specialize (Hone inter from eq_refl).\n          spec Hone. {\n            intuition.\n          }\n\n          specialize (Hone (sync_plan to from (rev l))).\n\n          spec Hone. {\n             unfold sync.\n             rewrite <- Hmatch in eq_suf_original.\n             rewrite <- Hinter in eq_suf_original.\n             rewrite eq_suf_original.\n             reflexivity.\n          }\n          simpl in Hone.\n          rewrite <- Hmatch.\n          rewrite <- Hinter.\n          intuition.\n        + rewrite <- Hmatch.\n          rewrite <- Hmatch in eq_suf.\n          assert (Hempty: l = []). {\n            replace (get_history (s to) from) with ([] ++ (get_history (s to) from)) in eq_suf at 1.\n            apply app_inv_tail in eq_suf.\n            all : intuition.\n          }\n          rewrite Hempty.\n          simpl.\n          unfold sync_plan; simpl.\n          intuition.\n          apply finite_protocol_plan_empty.\n          assumption.\n      - rewrite <- Hmatch in eq_sync.\n        apply sync_some in eq_sync.\n        intuition.\n    Qed.\n\n    (** Results of this type are useful for quickly unpacking\n       information about the constructed plan. *)\n\n    Remark get_matching_plan_info\n      (s : vstate X)\n      (from to : index)\n      (ai : plan_item)\n      (Hin : In ai (get_matching_plan s from to)) :\n      let component := projT1 (label_a ai) in\n      let label := projT2 (label_a ai) in\n      label = receive /\\\n      component = to /\\\n      (exists (so : state), (input_a ai = Some (from, so)) /\\ In (SimpObs Message' from so) (cobs_messages s from)).\n    Proof.\n      unfold get_matching_plan in Hin.\n      remember (get_matching_state s to from) as s0.\n      destruct (sync s s0 to from) eqn : eq_sync.\n        + unfold sync in eq_sync.\n          destruct (complete_suffix (get_history s0 from) (get_history (s to) from)) eqn : eq_hist;[|congruence].\n          inversion eq_sync.\n          unfold sync_plan in H0.\n          rewrite <- H0 in Hin.\n          apply in_map_iff in Hin.\n          destruct Hin as [x [Hlift Hinx]].\n\n          apply in_map_iff in Hinx.\n          destruct Hinx as [so [Hlift_rec Hinso]].\n          unfold lift_to_receive_item in Hlift_rec.\n          subst x.\n          unfold lift_to_composite_plan_item in Hlift.\n          rewrite <- Hlift. simpl.\n          split;[intuition|].\n          split;[intuition|].\n          exists so. split;[intuition|].\n          apply in_rev in Hinso.\n          apply complete_suffix_correct in eq_hist.\n          assert (In so (get_history s0 from)). {\n            rewrite eq_hist.\n            apply in_app_iff. left.\n            intuition.\n          }\n          rewrite Heqs0 in H.\n          specialize (get_matching_state_correct1 s to from) as Hinter.\n          destruct Hinter as [inter [Heq_inter _]].\n          rewrite Heq_inter in H.\n          apply (@in_history_in_observations index index_listing Hfinite) in H.\n          apply cobs_single_m.\n          exists inter. intuition.\n          apply in_listing.\n        + contradict Hin.\n    Qed.\n\n    (** Construct a plan in which indices in <<li>> sync their\n       <<from>> projections. *)\n\n    Definition get_receives_for\n      (s : vstate X)\n      (li : list index)\n      (from : index) : plan X :=\n      let matching_plans := List.map (get_matching_plan s from) li in\n      List.concat matching_plans.\n\n    Remark get_receives_for_info\n      (s : vstate X)\n      (li : list index)\n      (from : index)\n      (ai : vplan_item X)\n      (Hin : In ai (get_receives_for s li from)) :\n      let component := projT1 (label_a ai) in\n      let label := projT2 (label_a ai) in\n      label = receive /\\\n      In component li /\\\n      (exists (so : state), (input_a ai = Some (from, so)) /\\ In (SimpObs Message' from so) (cobs_messages s from)).\n    Proof.\n      unfold get_receives_for in Hin.\n      apply in_concat in Hin.\n      destruct Hin as [smaller [Hin_smaller Hin_ai]].\n\n      apply in_map_iff in Hin_smaller.\n      destruct Hin_smaller as [i [Heq_matching Hini]].\n\n      rewrite <- Heq_matching in Hin_ai.\n      apply get_matching_plan_info in Hin_ai.\n      simpl in *.\n      split;[intuition|].\n      split.\n      - destruct Hin_ai as [_ [Hin_ai]].\n        rewrite Hin_ai. intuition.\n      - destruct Hin_ai as [_ [_ Hin_ai]].\n        destruct Hin_ai as [so Hso].\n        exists so. intuition.\n    Qed.\n\n    Lemma get_receives_for_correct\n        (s : vstate X)\n        (Hpr : protocol_state_prop X s)\n        (li : list index)\n        (from : index)\n        (Hnodup : NoDup li)\n        (Hnf : ~ In from li) :\n        let res := snd (apply_plan X s (get_receives_for s li from)) in\n        finite_protocol_plan_from X s (get_receives_for s li from) /\\\n        forall (i : index), In i li -> project (res i) from = project (get_matching_state s i from) from.\n    Proof.\n      induction li using rev_ind; intros.\n      - unfold get_receives_for. simpl.\n        split.\n        apply finite_protocol_plan_empty.\n        assumption.\n        intuition.\n      - unfold res.\n        unfold get_receives_for.\n        rewrite map_app.\n        rewrite concat_app. simpl in *.\n        rewrite app_nil_r.\n\n        rewrite apply_plan_app.\n\n        destruct (apply_plan X s (concat (map (get_matching_plan s from) li))) as (tr_long, res_long) eqn : eq_long.\n        destruct (apply_plan X res_long (get_matching_plan s from x)) as (tr_short, res_short) eqn : eq_short.\n        simpl.\n\n        assert (Hres_long : res_long = snd (apply_plan X s (concat (map (get_matching_plan s from) li)))). {\n          rewrite eq_long. intuition.\n        }\n\n        assert (Hres_short : res_short = snd ((apply_plan X res_long (get_matching_plan s from x)))). {\n          rewrite eq_short. intuition.\n        }\n\n        assert (Hnodup_li : NoDup li). {\n          apply NoDup_rev in Hnodup.\n          rewrite rev_app_distr in Hnodup.\n          simpl in Hnodup.\n          apply NoDup_cons_iff in Hnodup.\n          destruct Hnodup as [_ Hnodup].\n          apply NoDup_rev in Hnodup.\n          rewrite rev_involutive in Hnodup.\n          intuition.\n        }\n\n        assert (Hnf_li : ~In from li). {\n          intros contra.\n          contradict Hnf.\n          apply in_app_iff.\n          left. intuition.\n        }\n\n        assert (Hnxf : x <> from). {\n          intros contra.\n          rewrite contra in Hnf.\n          intuition.\n        }\n\n        assert (Hnx_li : ~In x li). {\n          intros contra.\n          apply in_split in contra.\n          destruct contra as [lf [rt Heq]].\n          rewrite Heq in Hnodup.\n          apply NoDup_remove_2 in Hnodup.\n          contradict Hnodup.\n          rewrite app_nil_r.\n          apply in_app_iff.\n          right. intuition.\n        }\n\n        specialize (IHli Hnodup_li Hnf_li).\n\n        assert (Hrem : forall (i : index), ~In i li -> res_long i = s i). {\n          intros.\n          rewrite Hres_long.\n          apply irrelevant_components.\n          intros contra.\n          apply in_map_iff in contra.\n          destruct contra as [some [Hproj Hinsome]].\n\n          apply in_map_iff in Hinsome.\n          destruct Hinsome as [pi [Hlabel Inpi]].\n          apply in_concat in Inpi.\n          destruct Inpi as [lpi [Hlpi Hinlpi]].\n          apply in_map_iff in Hlpi.\n          destruct Hlpi as [j [Hmatch Hwhat]].\n          rewrite <- Hmatch in Hinlpi.\n          apply get_matching_plan_info in Hinlpi.\n          rewrite <- Hlabel in Hproj.\n          assert (i = j). {\n            rewrite <- Hproj.\n            intuition.\n          }\n          clear Hproj. clear Hinlpi.\n          subst i.\n          intuition.\n        }\n\n        destruct IHli as [IHli_proto IHli_proj].\n\n        assert (Hpr_long : protocol_state_prop X res_long). {\n          apply apply_plan_last_protocol in IHli_proto.\n          subst res_long.\n          all : intuition.\n        }\n\n        assert (Hmatch_idx : incl (map (projT1 (P:=fun n : index => vlabel (IM_index n)))\n               (map label_a (get_matching_plan s from x))) [x]). {\n           unfold incl.\n           intros.\n           apply in_map_iff in H.\n           destruct H as [smth [Hproj Hinsmth]].\n           apply in_map_iff in Hinsmth.\n           destruct Hinsmth as [pi [Hlabel Hinpi]].\n           apply get_matching_plan_info in Hinpi.\n           rewrite <- Hlabel in Hproj.\n           destruct Hinpi as [_ [Hinpi _]].\n           subst a. subst x.\n           intuition.\n        }\n\n        assert (Hrem2 : forall (i : index), In i li -> res_long i = res_short i). {\n          intros.\n          assert (~In i [x]). {\n            intros contra.\n            destruct contra; [|intuition]. subst i.\n            intuition.\n          }\n          subst res_long. subst res_short.\n          symmetry.\n          apply irrelevant_components.\n          intros contra.\n          assert (In i [x]). {\n            unfold incl in Hmatch_idx.\n            specialize (Hmatch_idx i contra).\n            intuition.\n          }\n          intuition.\n        }\n\n        specialize (get_matching_plan_effect s Hpr (get_matching_state s x from) from x) as Heff.\n        spec Heff. intuition.\n        specialize (Heff eq_refl).\n\n        simpl in Heff.\n        destruct Heff as [Heff Heff2].\n\n        apply relevant_components with (s' := res_long) (li0 := [x]) in Heff.\n\n        2, 4 : intuition.\n        2 : {\n          intros.\n          simpl in H. destruct H;[|intuition].\n          subst i.\n          specialize (Hrem x Hnx_li). intuition.\n        }\n\n        rewrite Hres_long in Heff.\n        destruct Heff as [Heff_proto Heff_proj].\n\n        split.\n        + apply finite_protocol_plan_from_app_iff.\n          split.\n          * unfold get_receives_for in IHli_proto. intuition.\n          * intuition.\n        + intros.\n          apply in_app_iff in H.\n          destruct H as [H|H].\n          * specialize (IHli_proj i H).\n            rewrite <- IHli_proj.\n            specialize (Hrem2 i H).\n            rewrite <- Hrem2.\n            rewrite Hres_long.\n            intuition.\n          * simpl in H. destruct H; [|intuition].\n            subst i.\n            subst res_short. subst res_long.\n            specialize (Heff_proj x).\n            spec Heff_proj. intuition. simpl in Heff_proj.\n            rewrite <- Heff2.\n            f_equal. simpl. assumption.\n    Qed.\n\n    Definition is_receive_plan\n      (a : plan X) : Prop :=\n      forall (ai : vplan_item X),\n        In ai a -> projT2 (label_a ai) = receive.\n\n    Definition is_receive_plan_app\n      (a b : plan X) :\n      is_receive_plan a /\\ is_receive_plan b <-> is_receive_plan (a ++ b).\n    Proof.\n      unfold is_receive_plan.\n      split; intros.\n      - destruct H as [Hl Hr].\n        apply in_app_iff in H0.\n        destruct H0.\n        + specialize (Hl ai). intuition.\n        + specialize (Hr ai). intuition.\n      - split; intros.\n        + specialize (H ai).\n          spec H. apply in_app_iff. left. intuition.\n          intuition.\n        + specialize (H ai).\n          spec H. apply in_app_iff. right. intuition.\n          intuition.\n    Qed.\n\n    Lemma receive_for_is_receive_plan\n      (s : vstate X)\n      (from : index)\n      (li : list index) :\n      is_receive_plan (get_receives_for s li from).\n    Proof.\n      unfold is_receive_plan. intros.\n      apply get_receives_for_info in H.\n      intuition.\n    Qed.\n    (** Receiving plans which don't involve the <<j>>'th components of nodes\n       leave them unaffected. *)\n\n    Lemma receives_neq\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      (i j : index)\n      (Hreceive : is_receive_plan a)\n      (Hj : forall (ai : vplan_item X),\n            In ai a ->\n            (exists (m : message), (input_a ai = Some m) /\\ (fst m) <> j))\n      (res := snd (apply_plan X s a)) :\n      project (res i) j = project (s i) j.\n    Proof.\n      induction a using rev_ind.\n      - intuition.\n      - apply finite_protocol_plan_from_app_iff in Hpra.\n\n        destruct Hpra as [Hpra_long Hpra_short].\n        specialize (IHa Hpra_long); simpl in *.\n        apply is_receive_plan_app in Hreceive.\n\n        destruct Hreceive as [Hreceive_long Hreceive_short].\n        specialize (IHa Hreceive_long); simpl.\n\n        spec IHa. {\n          intros.\n          specialize (Hj ai).\n          spec Hj. apply in_app_iff. left. intuition.\n          intuition.\n        }\n\n        rewrite <- IHa.\n        unfold res.\n        rewrite apply_plan_app.\n        destruct (apply_plan X s a) as [tr_long res_long].\n        simpl in *.\n        unfold apply_plan, _apply_plan, _apply_plan_folder.\n        destruct x. simpl.\n\n        unfold finite_protocol_plan_from in Hpra_short.\n        unfold apply_plan,_apply_plan, _apply_plan_folder in Hpra_short.\n        simpl in Hpra_short.\n        destruct (vtransition X label_a (res_long, input_a)) eqn : eq_trans.\n        simpl.\n        simpl in Hpra_short.\n        apply first_transition_valid in Hpra_short. simpl in Hpra_short.\n\n        destruct Hpra_short as [Hprtr Htrans].\n\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        remember label_a as label_a'.\n        destruct label_a as [idx li].\n\n        destruct li eqn : eq_li.\n        + unfold is_receive_plan in Hreceive_short.\n          specialize (Hreceive_short {| label_a := label_a'; input_a := input_a |}).\n          move Hreceive_short at bottom.\n          simpl in Hreceive_short.\n          spec Hreceive_short. intuition.\n          subst label_a'. simpl in Hreceive_short.\n          congruence.\n        + destruct input_a eqn : eq_input.\n          * rewrite Heqlabel_a' in eq_trans.\n            inversion eq_trans.\n            destruct (decide (i = idx)).\n            -- rewrite e. rewrite state_update_eq.\n              rewrite (@project_different index index_listing).\n              reflexivity.\n              intuition.\n              intros contra. {\n                specialize (Hj {| label_a := label_a'; input_a := Some m |}).\n                simpl in Hj.\n                spec Hj. apply in_app_iff. right. intuition.\n                destruct Hj as [m' [Hsome Hdif]].\n                inversion Hsome. subst m'. intuition.\n              }\n              clear -Hprtr.\n              apply protocol_state_component_no_bottom.\n              unfold protocol_valid in Hprtr.\n              intuition.\n          -- rewrite state_update_neq.\n             reflexivity.\n             assumption.\n         * unfold protocol_valid in Hprtr.\n           unfold valid in Hprtr.\n           rewrite Heqlabel_a' in Hprtr.\n           simpl in Hprtr.\n           unfold constrained_composite_valid in Hprtr.\n           unfold free_constraint in Hprtr.\n           unfold composite_valid in Hprtr.\n           unfold vvalid in Hprtr.\n           unfold valid in Hprtr.\n           simpl in Hprtr.\n           intuition.\n    Qed.\n\n    Lemma relevant_component_transition_lv\n      (s s' : vstate X)\n      (Hprs : protocol_state_prop X s)\n      (Hprs' : protocol_state_prop X s')\n      (l : vlabel X)\n      (input : message)\n      (i := projT1 l)\n      (Hsame : project (s i) (fst input) = project (s' i) (fst input))\n      (Hvalid: protocol_valid X l (s, Some input)) :\n      protocol_valid X l (s', Some input).\n    Proof.\n      unfold protocol_valid in *.\n      intuition.\n      clear X0 X1.\n      unfold valid in *.\n      simpl in *.\n      unfold constrained_composite_valid in *.\n      unfold composite_valid in *.\n      unfold vvalid in *.\n      intuition.\n      unfold valid in *.\n      unfold machine in *.\n      simpl in *.\n      destruct l as [j lj].\n      destruct lj eqn : eq_lj.\n      - destruct H0 as [_ Hd].\n        discriminate Hd.\n      - split ;[|intuition].\n        simpl in i.\n        subst i.\n        rewrite <- Hsame.\n        intuition.\n    Qed.\n\n    Lemma relevant_components_lv\n      (s s' : vstate X)\n      (Hprs : protocol_state_prop X s)\n      (Hprs' : protocol_state_prop X s')\n      (a : plan X)\n      (Hrec : is_receive_plan a)\n      (Hpr : finite_protocol_plan_from X s a)\n      (f : index)\n      (Hli : forall (ai : vplan_item X),\n             In ai a -> (exists (m : message),\n             input_a ai = Some m /\\ fst m = f))\n      (Hsame : forall (i : index), project (s i) f = project (s' i) f) :\n      let res' := snd (apply_plan X s' a) in\n      let res := snd (apply_plan X s a) in\n      finite_protocol_plan_from X s' a /\\\n      forall (i : index), project (res' i) f = project (res i) f.\n    Proof.\n      induction a using rev_ind.\n      - simpl.\n        split. apply finite_protocol_plan_empty.\n        assumption.\n        intros.\n        specialize (Hsame i).\n        intuition.\n      - simpl.\n\n        apply is_receive_plan_app in Hrec.\n        destruct Hrec as [Hrec_long Hrec_short].\n        apply finite_protocol_plan_from_app_iff in Hpr.\n        destruct Hpr as [Hpr_long Hpr_short].\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        simpl.\n\n        spec IHa. intuition.\n        spec IHa. intuition.\n\n        spec IHa. {\n          clear -Hli.\n          intros. specialize (Hli ai).\n          spec Hli. apply in_app_iff. left. intuition.\n          intuition.\n        }\n\n        simpl in IHa.\n        destruct IHa as [Iha_pr Iha_proj].\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        simpl in *.\n\n        assert (res_long = snd (apply_plan X s a)). {\n          rewrite eq_long.\n          intuition.\n        }\n\n        assert (res_short = snd (apply_plan X res_long [x])). {\n          rewrite eq_short.\n          intuition.\n        }\n\n        assert (res_long' = snd (apply_plan X s' a)). {\n          rewrite eq_long'.\n          intuition.\n        }\n\n        assert (res_short' = snd (apply_plan X res_long' [x])). {\n          rewrite eq_short'.\n          intuition.\n        }\n\n        replace res_short' with (snd (apply_plan X res_long' [x])).\n        replace res_short with (snd (apply_plan X res_long [x])).\n\n        unfold apply_plan, _apply_plan, _apply_plan_folder.\n        specialize (Hrec_short x).\n        remember x as x'.\n        destruct x as [label_x input_x].\n        simpl.\n\n        assert (Hprs_long : protocol_state_prop X res_long). {\n          rewrite H.\n          apply apply_plan_last_protocol.\n          assumption.\n          assumption.\n        }\n\n        assert (Hprs'_long : protocol_state_prop X res_long'). {\n          rewrite H1.\n          apply apply_plan_last_protocol.\n          assumption.\n          assumption.\n        }\n\n        unfold finite_protocol_plan_from in Hpr_short.\n        unfold apply_plan, _apply_plan, _apply_plan_folder in Hpr_short.\n        simpl in Hpr_short.\n        rewrite Heqx' in Hpr_short.\n        rewrite Heqx'.\n\n        destruct (vtransition X label_x (res_long, input_x)) eqn : trans.\n\n        apply first_transition_valid in Hpr_short. simpl in Hpr_short.\n\n        simpl in *.\n        destruct (vtransition X label_x (res_long', input_x)) eqn : trans'.\n        simpl.\n\n        remember Hpr_short as Hprotocol_trans.\n        destruct Hpr_short as [Hprotocol_valid Htrans].\n\n        unfold vtransition in trans, trans'.\n        unfold transition in trans, trans'.\n        simpl in *.\n        unfold vtransition in trans, trans'.\n        destruct label_x as [j label_x].\n        simpl in trans, trans'.\n\n        destruct label_x eqn : eq_label.\n        {\n          subst x'.\n          unfold is_receive_plan in Hrec_short.\n          simpl in Hrec_short.\n          spec Hrec_short. intuition.\n          congruence.\n       }\n\n        destruct input_x eqn : eq_input.\n        2 : {\n          unfold protocol_valid in Hprotocol_valid.\n          unfold constrained_composite_valid in Hprotocol_valid.\n          unfold composite_valid in Hprotocol_valid.\n          unfold vvalid in Hprotocol_valid.\n          unfold valid in Hprotocol_valid.\n          simpl in Hprotocol_valid.\n          destruct Hprotocol_valid as [e [b [c d]]].\n          intuition.\n        }\n\n       assert (Hm : fst m = f). {\n          simpl in *.\n          specialize (Hli x').\n          move Hli at bottom.\n          spec Hli. apply in_app_iff. right. intuition.\n          destruct Hli as [m' [Heqm' Heqf]].\n          rewrite Heqx' in Heqm'.\n          simpl in Heqm'. inversion Heqm'.\n          intuition.\n       }\n\n        split.\n        + apply finite_protocol_plan_from_app_iff.\n          split.\n          * assumption.\n          * unfold finite_protocol_plan_from.\n            simpl. rewrite eq_long'. simpl.\n            apply first_transition_valid. simpl.\n            split;[|intuition].\n            destruct Hprotocol_trans as [Hprotocol_trans tmp].\n            specialize (relevant_component_transition_lv res_long res_long') as Hrel.\n            specialize (Hrel Hprs_long Hprs'_long (existT (fun n : index => vlabel (IM_index n)) j receive) m).\n            rewrite H1 in Hrel.\n            rewrite eq_long' in Hrel. simpl in Hrel.\n            apply Hrel; [|assumption]. simpl.\n            specialize (Iha_proj j).\n            rewrite Hm.\n            symmetry.\n            intuition.\n        + intros.\n          subst x'. simpl in *.\n          specialize (Iha_proj i).\n         * inversion trans.\n           inversion trans'.\n           destruct (decide (i = j)).\n           -- rewrite e.\n              rewrite state_update_eq.\n              rewrite state_update_eq.\n              rewrite e in Iha_proj.\n              clear -Iha_proj Hprs_long Hprs'_long.\n              destruct (decide (f = (fst m))).\n              ** rewrite <- e.\n                 rewrite (@project_same index index_listing Hfinite).\n                 rewrite (@project_same index index_listing Hfinite).\n                 reflexivity.\n                 all : (apply protocol_state_component_no_bottom; assumption).\n              ** rewrite !(@project_different index index_listing Hfinite); [assumption| assumption | | assumption |].\n                 (apply protocol_state_component_no_bottom; assumption).\n                 (apply protocol_state_component_no_bottom; assumption).\n          -- rewrite state_update_neq by assumption.\n             rewrite state_update_neq by assumption.\n             intuition.\n    Qed.\n\n    Definition others (i : index) (s : vstate X) :=\n      set_remove idec i (GH s).\n\n    Remark NoDup_others\n      (i : index) (s : vstate X) :\n      NoDup (others i s).\n    Proof.\n      unfold others.\n      apply set_remove_nodup.\n      apply GH_NoDup.\n    Qed.\n\n    Remark others_correct\n      (i : index)\n      (s : vstate X) :\n      ~ In i (others i s).\n    Proof.\n      unfold others.\n      intros contra.\n      apply set_remove_2 in contra.\n      intuition.\n      apply GH_NoDup.\n    Qed.\n\n    Definition get_receives_all\n      (s : vstate X)\n      (lfrom : set index) : plan X :=\n      let receive_fors := List.map (fun (i : index) => get_receives_for s (others i s) i) lfrom in\n      List.concat receive_fors.\n\n    Remark get_receives_all_info\n      (s : vstate X)\n      (lfrom : list index)\n      (ai : vplan_item X)\n      (Hin : In ai (get_receives_all s lfrom)) :\n      let label := projT2 (label_a ai) in\n      label = receive /\\\n      (exists (so : state) (from : index), (input_a ai = Some (from, so)) /\\ In from lfrom /\\ In (SimpObs Message' from so) (cobs_messages s from)).\n    Proof.\n      unfold get_receives_all in Hin.\n      apply in_concat in Hin.\n      destruct Hin as [smaller [Hin_smaller Hin_ai]].\n\n      apply in_map_iff in Hin_smaller.\n      destruct Hin_smaller as [from [Hrec Hinfrom]].\n      rewrite <- Hrec in Hin_ai.\n      apply get_receives_for_info in Hin_ai.\n      simpl in *.\n      split;[intuition|].\n      destruct Hin_ai as [_ [_ Hin_ai]].\n      destruct Hin_ai as [so Hso].\n      exists so. exists from.\n      intuition.\n    Qed.\n\n    Lemma get_receives_all_protocol\n      (s : vstate X)\n      (lfrom : set index)\n      (Hnodup : NoDup lfrom)\n      (Hprs : protocol_state_prop X s) :\n      let res := snd (apply_plan X s (get_receives_all s lfrom)) in\n      finite_protocol_plan_from X s (get_receives_all s lfrom) /\\\n      forall (f i : index),\n      In f lfrom ->\n      i <> f ->\n      In i (GH s) ->\n      project (res i) f = project (get_matching_state s i f) f.\n    Proof.\n      induction lfrom using rev_ind; unfold get_receives_all.\n      - split; simpl.\n        + apply finite_protocol_plan_empty. assumption.\n        + intuition.\n      - simpl.\n        apply NoDup_rev in Hnodup.\n        rewrite rev_unit in Hnodup.\n        apply NoDup_cons_iff in Hnodup.\n        destruct Hnodup as [notX Hnodup].\n        apply NoDup_rev in Hnodup.\n        rewrite rev_involutive in Hnodup.\n\n        specialize (IHlfrom Hnodup).\n        simpl in IHlfrom.\n\n        destruct IHlfrom as [IHprotocol IHproject].\n        rewrite map_app.\n        rewrite concat_app.\n        rewrite apply_plan_app.\n\n        match goal with\n        |- context[apply_plan X s ?a] =>\n           destruct (apply_plan X s a) as [tr_long res_long] eqn : eq_long\n        end.\n\n        match goal with\n        |- context [apply_plan X res_long ?a] =>\n           destruct (apply_plan X res_long a) as [tr_short res_short] eqn : eq_short\n        end.\n        simpl in *.\n\n        rewrite app_nil_r in *.\n\n        assert (res_short = snd (apply_plan X res_long (get_receives_for s (others x s) x))). {\n          simpl.\n          rewrite eq_short.\n          intuition.\n        }\n\n        assert (res_long = snd (apply_plan X s (concat (map (fun i : index => get_receives_for s (others i s) i) lfrom)))). {\n          match goal with\n          |- context[apply_plan X s ?a] =>\n             replace (apply_plan X s a) with (tr_long, res_long)\n          end.\n          intuition.\n        }\n\n        assert (Hrec_long':  is_receive_plan (get_receives_all s lfrom)). {\n          unfold is_receive_plan. intros.\n          apply get_receives_all_info in H1.\n          intuition.\n        }\n\n        assert (Hrec_short : is_receive_plan (get_receives_for s (others x s) x)). {\n          apply receive_for_is_receive_plan.\n        }\n\n        assert (Hprs_long : protocol_state_prop X res_long). {\n          rewrite H0.\n          apply apply_plan_last_protocol.\n          assumption.\n          assumption.\n        }\n\n        assert (Hx_after_long : forall (i : index), project (res_long i) x = project (s i) x). {\n          intros.\n          replace res_long with\n            (snd (apply_plan X s (concat (map (fun i : index => get_receives_for s (others i s) i) lfrom)))).\n          apply receives_neq.\n          assumption.\n          assumption.\n          assumption.\n          intros.\n          apply in_concat in H1.\n          destruct H1 as [le [Hinle Hinai]].\n          apply in_map_iff in Hinle.\n          destruct Hinle as [k [Hgr Hink]].\n          rewrite <- Hgr in Hinai.\n          apply get_receives_for_info in Hinai.\n          destruct Hinai as [_ [_ Hinai]].\n          destruct Hinai as [so [Hinso Hinso']].\n          exists (k, so). split;[intuition|].\n          simpl.\n          destruct (decide (k = x));[|intuition].\n          subst x. apply in_rev in Hink. intuition.\n        }\n\n        assert (Hsource: finite_protocol_plan_from X s (get_receives_for s (others x s) x)). {\n          apply get_receives_for_correct.\n          assumption.\n          apply NoDup_others.\n          apply others_correct.\n        }\n\n        specialize (relevant_components_lv s res_long Hprs Hprs_long (get_receives_for s (others x s) x)) as Hrel.\n        specialize (Hrel Hrec_short Hsource x).\n\n        spec Hrel. {\n          intros.\n          apply get_receives_for_info in H1.\n          destruct H1 as [_ [_ H1]].\n          destruct H1 as [so [Heqso Heqso']].\n          exists (x, so). intuition.\n        }\n\n        spec Hrel. {\n          intros.\n          specialize (Hx_after_long i).\n          symmetry.\n          assumption.\n        }\n\n        simpl in Hrel.\n        rewrite eq_short in Hrel.\n\n        assert (Hfinite_short : finite_protocol_plan_from X res_long (get_receives_for s (others x s) x)). {\n          intuition.\n        }\n\n        split.\n        + apply finite_protocol_plan_from_app_iff.\n          unfold finite_protocol_plan_from. simpl. rewrite eq_long.\n          split.\n          * unfold finite_protocol_plan_from in IHprotocol.\n            replace tr_long with (fst (apply_plan X s (get_receives_all s lfrom))).\n            assumption.\n            unfold get_receives_all.\n            simpl. rewrite eq_long. reflexivity.\n          * rewrite H0 in Hfinite_short. simpl. simpl in Hfinite_short.\n            rewrite eq_long in Hfinite_short.\n            apply Hfinite_short.\n        +\n             intros.\n             destruct (decide (f = x)).\n              -- rewrite H.\n                destruct Hrel as [_ Hrel].\n                specialize (Hrel i).\n                rewrite e.\n                simpl. rewrite eq_short.\n                rewrite Hrel.\n                apply get_receives_for_correct.\n                assumption.\n                apply NoDup_others.\n                apply others_correct.\n                unfold others.\n                apply set_remove_3.\n                intuition.\n                subst f. intuition.\n              -- apply in_app_iff in H1.\n                simpl in H1.\n                destruct H1.\n                specialize (IHproject f i H1).\n                spec IHproject. {\n                  intuition.\n                }\n                spec IHproject. {\n                  intuition.\n                }\n                rewrite <- IHproject.\n                unfold get_receives_all.\n                replace (snd (apply_plan X s (concat (map (fun i1 : index => get_receives_for s (others i1 s) i1) lfrom)))) with res_long by intuition.\n                rewrite H.\n                simpl. rewrite eq_long. simpl.\n                apply receives_neq.\n                assumption.\n                assumption.\n                assumption.\n                intros.\n                apply get_receives_for_info in H4.\n                destruct H4 as [_ [_ H4]].\n                destruct H4 as [so [Heqso Heqso']].\n                exists (x, so). intuition.\n                intuition.\n    Qed.\n\n    Definition receive_phase_plan (s : vstate X) := (get_receives_all s index_listing).\n    Definition receive_phase (s : vstate X) := apply_plan X s (receive_phase_plan s).\n    Definition receive_phase_result (s : vstate X) := snd (receive_phase s).\n    Definition receive_phase_transitions (s : vstate X) := fst (receive_phase s).\n\n    Lemma receive_phase_protocol\n      (s : vstate X)\n      (Hprs : protocol_state_prop X s):\n      finite_protocol_plan_from X s (receive_phase_plan s).\n    Proof.\n      unfold receive_phase_plan.\n      apply get_receives_all_protocol.\n      apply (proj1 Hfinite).\n      intuition.\n    Qed.\n\n    Remark receive_phase_result_protocol\n      (s : vstate X)\n      (Hprs : protocol_state_prop X s)\n      (res_receive := receive_phase_result s) :\n      protocol_state_prop X res_receive.\n    Proof.\n      apply apply_plan_last_protocol.\n      intuition.\n      apply receive_phase_protocol.\n      all : intuition.\n    Qed.\n\n    Lemma receive_phase_GE\n      (s : vstate X)\n      (Hprs : protocol_state_prop X s)\n      (res_receive := receive_phase_result s) :\n      set_eq (GE res_receive) (GE s).\n    Proof.\n      specialize (receive_plan_preserves_equivocation s Hprs (receive_phase_plan s)) as Hep.\n      spec Hep. apply receive_phase_protocol. intuition.\n      spec Hep. {\n        intros.\n        unfold receive_phase_plan in H.\n        apply get_receives_all_info in H.\n        split;[intuition|].\n        destruct H as [_ H].\n        destruct H as [so [from H]].\n        exists so. exists from. intuition.\n      }\n      simpl in Hep.\n      apply set_eq_comm.\n      intuition.\n    Qed.\n\n    Remark receive_phase_future\n      (s : vstate X)\n      (Hspr : protocol_state_prop _ s) :\n      in_futures _ s (receive_phase_result s).\n    Proof.\n      unfold in_futures.\n      exists (receive_phase_transitions s).\n      apply ptrace_add_last.\n      apply receive_phase_protocol;assumption.\n      unfold receive_phase_transitions.\n      unfold receive_phase_result.\n      apply apply_plan_last.\n    Qed.\n\n    Remark self_projections_same_after_receive_phase\n      (s : vstate X)\n      (Hpr : protocol_state_prop X s)\n      (res_receive := receive_phase_result s) :\n      forall (i : index), project (res_receive i) i = project (s i) i.\n    Proof.\n      intros.\n      specialize (self_projections_same_after_receives s Hpr) as Hsame.\n      specialize (Hsame (receive_phase_plan s)).\n      spec Hsame. apply receive_phase_protocol. intuition.\n\n      spec Hsame. {\n        intros.\n        unfold receive_phase_plan in H.\n        apply get_receives_all_info in H.\n        intuition.\n      }\n      specialize (Hsame i).\n      intuition.\n    Qed.\n\n    Definition common_future (s : vstate X) := receive_phase_result (send_phase_result s).\n\n    Lemma common_future_in_futures\n      (s : vstate X)\n      (Hpr : protocol_state_prop X s)\n      (Hnf : no_component_fully_equivocating s (GH s)) :\n      in_futures X s (common_future s).\n    Proof.\n      specialize (@in_futures_trans message X s (send_phase_result s) (common_future s)) as Htrans.\n      apply Htrans.\n      apply send_phase_future.\n      intuition.\n      intuition.\n      unfold common_future.\n      apply receive_phase_future.\n      apply send_phase_result_protocol.\n      all : intuition.\n    Qed.\n\n    Lemma common_future_no_extra_equivocation\n      (s : vstate X)\n      (Hpr : protocol_state_prop X s)\n      (Hnf : no_component_fully_equivocating s (GH s)) :\n      set_eq (GE (common_future s)) (GE s).\n    Proof.\n      apply set_eq_tran with (s2 := GE (send_phase_result s)).\n      apply receive_phase_GE.\n      apply send_phase_result_protocol.\n      intuition. intuition.\n      apply send_phase_GE.\n      intuition. intuition.\n    Qed.\n\n    Remark common_future_result_protocol\n      (s : vstate X)\n      (Hpr : protocol_state_prop X s)\n      (Hnf : no_component_fully_equivocating s (GH s))\n      (res := common_future s) :\n      protocol_state_prop X res.\n    Proof.\n      unfold res.\n      unfold common_future.\n      apply receive_phase_result_protocol.\n      apply send_phase_result_protocol.\n      all : intuition.\n    Qed.\n\n    Corollary GH_eq1\n      (s : vstate X)\n      (Hpr : protocol_state_prop X s)\n      (Hnf : no_component_fully_equivocating s (GH s))\n      (res_send := send_phase_result s)\n      (res := common_future s) :\n      (GH s) = (GH res_send).\n    Proof.\n      apply HE_eq_equiv.\n      specialize (send_phase_GE s Hpr Hnf) as He.\n      unfold GE in He.\n      apply wE_eq_equality in He.\n      intuition.\n    Qed.\n\n    Corollary GH_eq2\n      (s : vstate X)\n      (Hpr : protocol_state_prop X s)\n      (Hnf : no_component_fully_equivocating s (GH s))\n      (res_send := send_phase_result s)\n      (res := common_future s) :\n      (GH s) = (GH res).\n    Proof.\n      apply HE_eq_equiv.\n      specialize (common_future_no_extra_equivocation s Hpr Hnf) as He.\n      unfold GE in He.\n      apply wE_eq_equality in He.\n      intuition.\n    Qed.\n\n    Corollary GH_eq3\n      (s : vstate X)\n      (Hpr : protocol_state_prop X s)\n      (Hnf : no_component_fully_equivocating s (GH s))\n      (res_send := send_phase_result s)\n      (res := common_future s) :\n      (GH res_send) = (GH res).\n    Proof.\n      apply HE_eq_equiv.\n      specialize (receive_phase_GE res_send) as He.\n      spec He. apply send_phase_result_protocol; intuition.\n      unfold GE in He.\n      apply wE_eq_equality in He.\n      intuition.\n    Qed.\n\n    Lemma hh_something\n      (s : vstate X)\n      (Hpr : protocol_state_prop X s)\n      (res := receive_phase_result s) :\n      incl (HH res) (HH s).\n    Proof.\n      unfold incl. intros.\n      assert (HsameGH : GH res = GH s). {\n        unfold res.\n        specialize (receive_phase_GE s Hpr) as Hseteq.\n        simpl in Hseteq.\n        apply filter_set_eq in Hseteq.\n        apply HE_eq_equiv.\n        intuition.\n      }\n\n      assert (~ In a (HE s)). {\n        intros contra.\n        assert (contra' := contra).\n        unfold HE in contra.\n        apply GE_direct in contra.\n        unfold cequiv_evidence in contra.\n        unfold equivocation_evidence in contra.\n        setoid_rewrite hbo_cobs' in contra.\n\n        destruct contra as [e1 [He1 [He1' [e2 [He2 [He2' Hcomp]]]]]].\n        specialize (@in_future_message_obs _ _ _ _ _ _ _ (GH s) s res a) as Hfuture.\n        spec Hfuture. {\n          unfold res.\n          apply receive_phase_future.\n          intuition.\n        }\n\n        assert (In a (HE res)). {\n          unfold HE.\n          apply GE_direct.\n          unfold cequiv_evidence.\n          unfold equivocation_evidence.\n          setoid_rewrite hbo_cobs'.\n          unfold get_simp_event_subject_some in He1'.\n          inversion He1'.\n          exists e1.\n          split.\n          - setoid_rewrite cobs_messages_states in He1.\n            apply set_union_iff in He1.\n            destruct He1 as [He1|He1].\n            + apply cobs_single_s in He1.\n              destruct He1 as [k [Hk Hk']].\n              unfold simp_lv_state_observations in Hk'.\n              rewrite H1 in Hk'.\n              rewrite decide_False in Hk'.\n              intuition.\n              specialize (ws_incl_wE s index_listing (GH s)) as Hincl.\n              spec Hincl. unfold incl. intros. apply in_listing.\n              destruct (decide (a = k)).\n              * subst k. unfold GH in Hk. apply wH_wE' in Hk. intuition.\n              * intuition.\n            + setoid_rewrite cobs_messages_states.\n              apply set_union_iff.\n              right.\n              specialize (Hfuture e1).\n              inversion He1'. rewrite H1.\n              rewrite H1 in He1.\n              specialize (Hfuture He1).\n              unfold wcobs_messages.\n              rewrite HsameGH.\n              intuition.\n          - split;[intuition|].\n            exists e2.\n            split.\n            unfold get_simp_event_subject_some in He2'.\n            inversion He2'.\n            + setoid_rewrite cobs_messages_states in He2.\n            apply set_union_iff in He2.\n            destruct He2 as [He2|He2].\n            * apply cobs_single_s in He2.\n              destruct He2 as [k [Hk Hk']].\n              unfold simp_lv_state_observations in Hk'.\n              rewrite H2 in Hk'.\n              rewrite decide_False in Hk'.\n              intuition.\n              specialize (ws_incl_wE s index_listing (GH s)) as Hincl.\n              spec Hincl. unfold incl. intros. apply in_listing.\n              destruct (decide (a = k)).\n              -- subst k. unfold GH in Hk. apply wH_wE' in Hk. intuition.\n              -- intuition.\n            * setoid_rewrite cobs_messages_states.\n              apply set_union_iff.\n              right.\n              specialize (Hfuture e2).\n              rewrite H2.\n              rewrite H2 in He2.\n              specialize (Hfuture He2).\n              unfold wcobs_messages.\n              rewrite HsameGH.\n              intuition.\n            + split.\n              -- unfold get_simp_event_subject_some.\n                 f_equal.\n                 inversion He2'.\n                 rewrite H2, H1. intuition.\n              -- intuition.\n        }\n        unfold HH in H.\n        apply wH_wE' in H.\n        intuition.\n      }\n      unfold HH.\n      apply wH_wE'.\n      intuition.\n    Qed.\n\n  Lemma honest_receive_honest\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (Hnf : no_component_fully_equivocating s (GH s))\n    (res_send := send_phase_result s)\n    (res := common_future s) :\n    forall (i j : index), In i (GH res) -> In j (GH res) -> project (res i) j = project (res j) j.\n  Proof.\n    intros.\n    destruct (decide (i = j));[subst i;intuition|].\n\n    assert (Hsend_pr : protocol_state_prop X res_send). {\n      apply send_phase_result_protocol.\n      all : intuition.\n    }\n\n    assert (In i (GH s) /\\ In j (GH s)) by (setoid_rewrite GH_eq2;intuition).\n    assert (HiGH : In i (GH (send_phase_result s))) by (setoid_rewrite <- GH_eq1;intuition).\n\n    specialize (get_receives_all_protocol (send_phase_result s) index_listing (proj1 Hfinite) Hsend_pr) as Hrec.\n    simpl in Hrec. destruct Hrec as [Hrec_pr Hrec].\n    specialize (Hrec j i).\n    spec Hrec. apply in_listing.\n    specialize (Hrec n).\n    unfold res in H.\n\n    specialize (Hrec HiGH).\n    unfold res at 1.\n    unfold common_future.\n    unfold receive_phase_result.\n    unfold receive_phase.\n    unfold receive_phase_plan.\n    simpl. rewrite Hrec.\n    rewrite get_matching_state_for_honest.\n    rewrite <- self_projections_same_after_receive_phase.\n    intuition.\n    1, 2 : intuition.\n    setoid_rewrite <- GH_eq1; intuition.\n  Qed.\n\n  Lemma all_projections_old1\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (Hnf : no_component_fully_equivocating s (GH s))\n    (res_send := send_phase_result s)\n    (res := common_future s)\n    (i j : index)\n    (Hdif : i <> j)\n    (Hi : In i (GH res)) :\n    (project (res i) j = (s j) /\\ (In j (GH res))) \\/\n    (exists (inter : index), In inter (GH res) /\\\n    project (s inter) j = project (res i) j).\n  Proof.\n    assert (Hspr: protocol_state_prop X res_send) by (apply send_phase_result_protocol;intuition).\n    assert (In i (GH res_send)). {\n      unfold res_send.\n      rewrite GH_eq3; intuition.\n    }\n\n    assert (project (res i) j = project (get_matching_state (res_send) i j) j). {\n      unfold res.\n      unfold common_future.\n      specialize (get_receives_all_protocol res_send index_listing (proj1 Hfinite) Hspr) as Hrec.\n      destruct Hrec as [_ Hrec].\n      specialize (Hrec j i (in_listing j)).\n      spec Hrec. intuition.\n      specialize (Hrec H).\n      apply Hrec.\n    }\n    specialize (get_matching_state_correct2 res_send i j H) as Hinter.\n    destruct Hinter as [inter [HinterGH Hmatch]].\n\n    destruct (decide (inter = j)).\n    - subst inter.\n      left.\n      rewrite Hmatch in H0.\n      unfold res_send in H0.\n      rewrite send_phase_result_projections in H0.\n      2 , 3 : intuition.\n      2 : {\n        rewrite GH_eq1; intuition.\n      }\n      split.\n      + intuition.\n      + unfold res. rewrite <- GH_eq3; intuition.\n    - right.\n      exists inter.\n      split.\n      + unfold res. rewrite <- GH_eq3; intuition.\n      + assert (project (s inter) j = project (res_send inter) j). {\n          specialize (non_self_projections_same_after_send_phase s Hpr Hnf inter j n).\n          intuition.\n        }\n        rewrite Hmatch in H0.\n        rewrite H0.\n        intuition.\n  Qed.\n\n  Lemma all_projections_old2\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (Hnf : no_component_fully_equivocating s (GH s))\n    (res_send := send_phase_result s)\n    (res := common_future s)\n    (i j : index)\n    (Hi : In i (GH res))\n    (Hk : ~ In j (GH res)) :\n    exists (inter : index), In inter (GH res) /\\\n    project (s inter) j = project (res i) j.\n  Proof.\n\n    assert (Hdif : i <> j). {\n      destruct (decide (i = j));[subst i;intuition|intuition].\n    }\n\n    assert (Hspr: protocol_state_prop X res_send) by (apply send_phase_result_protocol;intuition).\n    assert (In i (GH res_send)). {\n      unfold res_send.\n      rewrite GH_eq3; intuition.\n    }\n\n    assert (project (res i) j = project (get_matching_state (res_send) i j) j). {\n      unfold res.\n      unfold common_future.\n      specialize (get_receives_all_protocol res_send index_listing (proj1 Hfinite) Hspr) as Hrec.\n      destruct Hrec as [_ Hrec].\n      specialize (Hrec j i (in_listing j)).\n      spec Hrec. intuition.\n      specialize (Hrec H).\n      apply Hrec.\n    }\n    specialize (get_matching_state_correct2 res_send i j H) as Hinter.\n    destruct Hinter as [inter [HinterGH Hmatch]].\n\n    assert (inter <> j). {\n      destruct (decide (inter = j)).\n      - subst inter.\n        unfold res_send in HinterGH.\n        rewrite GH_eq3 in HinterGH; intuition.\n      - intuition.\n    }\n\n    exists inter.\n    split.\n    + unfold res. rewrite <- GH_eq3; intuition.\n    + assert (project (s inter) j = project (res_send inter) j). {\n        specialize (non_self_projections_same_after_send_phase s Hpr Hnf inter j H1).\n        intuition.\n      }\n      rewrite Hmatch in H0.\n      rewrite H0.\n      intuition.\n  Qed.\n\n  Lemma all_message_observations_old\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (Hnf : no_component_fully_equivocating s (GH s))\n    (res_send := send_phase_result s)\n    (res := common_future s)\n    (target : index)\n    (Htarget : ~In target (GH res))\n    (e : simp_lv_event) :\n    In e (hcobs_messages res target) ->\n    In e (hcobs_messages s target).\n  Proof.\n    intros.\n    assert (H' := H).\n    apply (@cobs_single_m _ _ index_listing Hfinite _ _ _ _) in H.\n    destruct H as [k [Hink Hine]].\n\n    assert (Hspr : protocol_state_prop X res_send). {\n      apply send_phase_result_protocol; intuition.\n    }\n\n    assert (In k (GH res_send)). {\n      unfold res_send.\n      rewrite GH_eq3; intuition.\n    }\n\n    assert (Hdif : target <> k). {\n      destruct (decide (k = target)).\n      - subst k. intuition.\n      - intuition.\n    }\n\n    apply (@unfold_simp_lv_observations index index_listing Hfinite) in Hine.\n    2 : {\n      apply protocol_state_component_no_bottom.\n      apply common_future_result_protocol; intuition.\n    }\n    apply cobs_single_m.\n\n    destruct Hine as [Hine|Hine].\n    - specialize (all_projections_old2 s Hpr Hnf k target Hink Htarget) as Hinter.\n      destruct Hinter as [inter [HinterGH Hproject]].\n      exists inter.\n      split.\n      + rewrite GH_eq2; intuition.\n      + unfold res in Hine.\n        rewrite <- Hproject in Hine.\n        apply refold_simp_lv_observations1.\n        apply protocol_state_component_no_bottom; intuition.\n        apply (@cobs_single_m _ _ index_listing Hfinite _ _ _ _) in H'.\n        destruct H' as [inter2 Hrest].\n        destruct Hrest as [_ Hrest].\n        apply (@in_message_observations_nb index index_listing Hfinite) in Hrest.\n        rewrite Hine in Hrest. simpl in Hrest.\n        intuition.\n        intuition.\n    - destruct Hine as [l Hinel].\n      destruct (decide (k = l)).\n      + subst l.\n        unfold res in Hinel.\n        unfold common_future in Hinel.\n        rewrite self_projections_same_after_receive_phase in Hinel by intuition.\n        rewrite send_phase_result_projections in Hinel.\n        2, 3 : intuition.\n        2 : (rewrite GH_eq2; intuition).\n        exists k.\n        split.\n        * rewrite GH_eq1; intuition.\n        * intuition.\n      + specialize (all_projections_old1 s Hpr Hnf k l n Hink) as Hinter.\n        destruct Hinter.\n        * unfold res in Hinel.\n          destruct H0 as [H0 HlGH].\n          rewrite H0 in Hinel.\n          exists l.\n          rewrite GH_eq2; intuition.\n        * destruct H0 as [inter2 [Hinter2GH Hproj]].\n          unfold res in Hinel.\n          rewrite <- Hproj in Hinel.\n          exists inter2.\n          split.\n          -- rewrite GH_eq2; intuition.\n          -- apply (@refold_simp_lv_observations2 index index_listing Hfinite).\n             apply protocol_state_component_no_bottom.\n             intuition.\n             exists l. intuition.\n  Qed.\n\n  Lemma all_message_observations_in_new_projections\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (Hnf : no_component_fully_equivocating s (GH s))\n    (res_send := send_phase_result s)\n    (res := common_future s)\n    (i target : index)\n    (Hi : In i (GH res))\n    (Htarget : ~In target (GH res))\n    (e : simp_lv_event) :\n    In e (hcobs_messages s target) ->\n    In e (simp_lv_message_observations (res i) target).\n  Proof.\n    intros.\n    apply (@cobs_single_m _ _ index_listing Hfinite _ _ _ _) in H.\n    destruct H as [j [HjGH Hine]].\n    apply (@refold_simp_lv_observations2 index index_listing Hfinite).\n    apply protocol_state_component_no_bottom; apply common_future_result_protocol; intuition.\n    exists j.\n    specialize (honest_receive_honest s Hpr Hnf i j Hi) as Hhonest.\n    spec Hhonest. rewrite <- GH_eq2; intuition.\n    unfold res. rewrite Hhonest.\n    unfold common_future.\n    rewrite self_projections_same_after_receive_phase by (apply send_phase_result_protocol;intuition).\n    rewrite send_phase_result_projections; intuition.\n  Qed.\n\n  Lemma local_and_honest\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (Hnf : no_component_fully_equivocating s (GH s))\n    (res_send := send_phase_result s)\n    (res := common_future s)\n    (i : index)\n    (Hi : In i (GH res)) :\n    set_eq (HE res) (LE i res).\n  Proof.\n    apply set_eq_extract_forall.\n    intros v.\n    split; intros.\n    - assert (Hdif : ~ In v (GH res)). {\n        intros contra.\n        specialize (ws_incl_wE res index_listing (GH res)) as Hincl.\n        spec Hincl. unfold incl. intros. apply in_listing.\n        specialize (Hincl v).\n        unfold HE in H.\n        specialize (Hincl H).\n        unfold GH in contra.\n        apply wH_wE' in contra.\n        intuition.\n      }\n      unfold HE in H.\n      unfold LE.\n      apply GE_direct in H.\n      unfold cequiv_evidence in H.\n      unfold equivocation_evidence in H.\n      setoid_rewrite hbo_cobs' in H.\n\n      destruct H as [e1 [He1 [He1' [e2 [He2 [He2']]]]]].\n      setoid_rewrite cobs_messages_states in He1.\n      setoid_rewrite cobs_messages_states in He2.\n\n      apply set_union_iff in He1.\n      apply set_union_iff in He2.\n\n      destruct He1 as [He1|He1].\n      + unfold wcobs_states in He1.\n        apply set_union_in_iterated in He1.\n        rewrite Exists_exists in He1.\n        destruct He1 as [le [Heq_le Hin_e1]].\n        apply in_map_iff in Heq_le.\n        destruct Heq_le as [j [Heqj Hinj]].\n        unfold simp_lv_state_observations in Heqj.\n        inversion He1'.\n        rewrite H1 in Heqj.\n        destruct (decide (v = j));[subst v;intuition|].\n        subst le. intuition.\n     + destruct He2 as [He2|He2].\n       * unfold wcobs_states in He2.\n         apply set_union_in_iterated in He2.\n         rewrite Exists_exists in He2.\n         destruct He2 as [le [Heq_le Hin_e2]].\n         apply in_map_iff in Heq_le.\n         destruct Heq_le as [j [Heqj Hinj]].\n         unfold simp_lv_state_observations in Heqj.\n         inversion He2'.\n         rewrite H1 in Heqj.\n         destruct (decide (v = j));[subst v;intuition|].\n         subst le. intuition.\n       * apply GE_direct.\n         unfold cequiv_evidence.\n         unfold equivocation_evidence.\n         setoid_rewrite hbo_cobs'.\n         inversion He1'.\n         inversion He2'.\n         exists e1.\n         split.\n         -- apply all_message_observations_old in He1.\n            apply all_message_observations_in_new_projections with (i := i) in He1.\n            unfold wcobs. unfold composite_state_events_fn. simpl. unfold Hstate_events_fn.\n            unfold res. apply in_simp_lv_message_observations'. intuition.\n            intuition. intuition. intuition. rewrite H1.\n            intuition. intuition. intuition. rewrite H1. intuition.\n         -- split;[intuition|].\n            exists e2.\n            split.\n            ++ apply all_message_observations_old in He2.\n               apply all_message_observations_in_new_projections with (i := i) in He2.\n               unfold wcobs. unfold composite_state_events_fn. simpl. unfold Hstate_events_fn.\n               unfold res. apply in_simp_lv_message_observations'. intuition.\n               intuition. intuition. intuition. rewrite H2.\n               intuition. intuition. intuition. rewrite H2. intuition.\n            ++ rewrite He2'. rewrite H1. intuition.\n    - specialize (ws_incl_wE res (GH res) [i]) as Hincl.\n      spec Hincl. {\n        unfold incl. intros.\n        destruct H0;[|intuition]. subst a. intuition.\n      }\n      specialize (Hincl v).\n      specialize (Hincl H).\n      intuition.\n  Qed.\n\n  Corollary local_and_honest_equal\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (Hnf : no_component_fully_equivocating s (GH s))\n    (res_send := send_phase_result s)\n    (res := common_future s)\n    (i : index)\n    (Hi : In i (GH res)) :\n    (HE res) = (LE i res).\n  Proof.\n    apply filter_set_eq.\n    specialize (local_and_honest s Hpr Hnf i Hi).\n    intuition.\n  Qed.\n\n  Lemma honest_hh_projections_comparable\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (h1 h2 hh : index)\n    (Hgh : In h1 (GH s) /\\ In h2 (GH s))\n    (Hhh : In hh (HH s)) :\n    comparable (state_lt_ext hh) (project (s h1) hh) (project (s h2) hh).\n  Proof.\n    unfold comparable.\n    destruct (decide (project (s h1) hh = project (s h2) hh));[left;intuition|].\n    right.\n\n    destruct (project (s h1) hh) eqn : eq1.\n    - left. unfold state_lt_ext. intuition.\n    - destruct (project (s h2) hh) eqn : eq2.\n      + right. unfold state_lt_ext. intuition.\n      + rewrite <- eq1. rewrite <- eq2.\n\n        assert (Hcomp : comparable (state_lt' hh) (project (s h1) hh) (project (s h2) hh)). {\n          destruct (decide (comparable (state_lt' hh) (project (s h1) hh) (project (s h2) hh)));[intuition|].\n          assert (In hh (HE s)). {\n            unfold HE.\n            apply GE_direct.\n            unfold cequiv_evidence.\n            unfold equivocation_evidence.\n            setoid_rewrite hbo_cobs'.\n\n            exists (SimpObs Message' hh (project (s h1) hh)).\n            simpl. split.\n            - apply in_cobs_messages'.\n              apply cobs_single_m.\n              exists h1. split;[intuition|].\n              apply refold_simp_lv_observations1.\n              apply protocol_state_component_no_bottom; intuition.\n              intuition congruence. intuition.\n            - split;[simpl;intuition|].\n              exists (SimpObs Message' hh (project (s h2) hh)).\n              simpl. split.\n              + apply in_cobs_messages'.\n                apply cobs_single_m.\n                exists h2. split;[intuition|].\n                apply refold_simp_lv_observations1.\n                apply protocol_state_component_no_bottom; intuition.\n                intuition congruence. intuition.\n              + split;[simpl;intuition|].\n                intros contra.\n                unfold comparable in contra.\n                unfold simp_lv_event_lt in contra.\n                rewrite decide_True in contra by intuition.\n                rewrite decide_True in contra by intuition.\n                destruct contra.\n                * inversion H. intuition congruence.\n                * unfold comparable in n0.\n                  contradict n0.\n                  right. intuition.\n          }\n          unfold HH in Hhh.\n          apply wH_wE' in Hhh.\n          unfold HE in H. intuition.\n        }\n\n        unfold comparable in Hcomp.\n        destruct Hcomp;[intuition congruence|].\n        destruct H.\n        * left. unfold state_lt_ext. intuition.\n        * right. unfold state_lt_ext. intuition.\n  Qed.\n\n  Lemma comparable_projections_match\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (h1 h2 hh : index)\n    (Hgh : In h1 (GH s) /\\ In h2 (GH s))\n    (Hhh : In hh (HH s))\n    (projh1 := project (get_matching_state s h1 hh) hh)\n    (projh2 := project (get_matching_state s h2 hh) hh) :\n    projh1 = projh2.\n  Proof.\n    specialize (get_matching_state_correct2 s h1 hh) as Hmatch1.\n    specialize (get_matching_state_correct2 s h2 hh) as Hmatch2.\n    spec Hmatch1. intuition. spec Hmatch2. intuition.\n    destruct Hmatch1 as [i [GHi Hmatch1]].\n    destruct Hmatch2 as [j [GHj Hmatch2]].\n\n    assert (Hcomp': comparable (state_lt_ext hh) projh1 projh2). {\n      unfold projh1, projh2.\n      rewrite Hmatch1. rewrite Hmatch2.\n      apply honest_hh_projections_comparable; intuition.\n    }\n\n    unfold projh1 in *.\n    unfold projh2 in *.\n    specialize (get_matching_state_correct3 s h1 hh) as Htop1.\n    specialize (get_matching_state_correct3 s h2 hh) as Htop2.\n    spec Htop1. intuition. spec Htop2. intuition.\n\n    unfold comparable in Hcomp'.\n    destruct Hcomp' as [|Hcomp'];[intuition|].\n    destruct Hcomp'.\n    - unfold get_topmost_candidates in Htop1.\n      unfold get_maximal_elements in Htop1.\n      apply filter_In in Htop1.\n      destruct Htop1 as [_ Htop1].\n      rewrite forallb_forall in Htop1.\n      specialize (Htop1 (s j)).\n      spec Htop1.\n      apply in_map_iff. exists j. intuition.\n      rewrite negb_true_iff in Htop1.\n      rewrite bool_decide_eq_false in Htop1.\n      rewrite Hmatch2 in H.\n      intuition.\n      intros. apply honest_hh_projections_comparable; intuition.\n    - unfold get_topmost_candidates in Htop2.\n      unfold get_maximal_elements in Htop2.\n      apply filter_In in Htop2.\n      destruct Htop2 as [_ Htop2].\n      rewrite forallb_forall in Htop2.\n      specialize (Htop2 (s i)).\n      spec Htop2.\n      apply in_map_iff. exists i. intuition.\n      rewrite negb_true_iff in Htop2.\n      rewrite bool_decide_eq_false in Htop2.\n      rewrite Hmatch1 in H.\n      intuition.\n      intros. apply honest_hh_projections_comparable; intuition.\n   Qed.\n\n  Lemma honest_equiv_proj_same\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (Hnf : no_component_fully_equivocating s (GH s))\n    (res_send := send_phase_result s)\n    (res := common_future s) :\n    forall (h1 h2 hh : index),\n    In h1 (GH res) ->\n    In h2 (GH res) ->\n    In hh (HH res) ->\n    project (res h1) hh = project (res h2) hh.\n  Proof.\n    intros.\n\n    destruct (decide (h1 = hh)).\n    subst hh.\n    specialize (honest_receive_honest s Hpr Hnf h2 h1).\n    intuition.\n    destruct (decide (h2 = hh)).\n    subst hh.\n    specialize (honest_receive_honest s Hpr Hnf h1 h2).\n    intuition.\n\n    destruct (decide (project (res h1) hh = project (res h2) hh));[intuition|].\n    exfalso.\n\n    specialize (get_receives_all_protocol res_send index_listing (proj1 Hfinite)) as Hmatch.\n    spec Hmatch. apply send_phase_result_protocol. intuition. intuition.\n    destruct Hmatch as [_ Hmatch].\n\n    specialize (Hmatch hh h1) as Hmatch1.\n    spec Hmatch1. apply in_listing. spec Hmatch1. intuition.\n    spec Hmatch1. unfold res_send. rewrite GH_eq3 by intuition. intuition.\n    specialize (Hmatch hh h2) as Hmatch2.\n    spec Hmatch2. apply in_listing. spec Hmatch2. intuition.\n    spec Hmatch2. unfold res_send. rewrite GH_eq3 by intuition. intuition.\n\n    unfold res in n1. unfold common_future in n1. unfold receive_phase_result in n1.\n    unfold res_send in Hmatch1, Hmatch2.\n    unfold receive_phase in n1.\n    unfold receive_phase_plan in n1.\n    rewrite Hmatch1 in n1.\n    rewrite Hmatch2 in n1.\n\n    specialize (comparable_projections_match res_send) as Hcomp.\n    spec Hcomp. apply send_phase_result_protocol; intuition.\n    specialize (Hcomp h1 h2 hh).\n    spec Hcomp. {\n      unfold res_send.\n      rewrite GH_eq3 by intuition.\n      unfold res in H, H0. intuition.\n    }\n    spec Hcomp. {\n      apply hh_something.\n      apply send_phase_result_protocol; intuition.\n      intuition.\n    }\n    intuition.\n  Qed.\n\n  Lemma eqv_aware_something\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (i : index) :\n    LE i s = (@equivocating_validators _ _ _ _ (Hbasic i) (s i)).\n  Proof.\n    unfold equivocating_validators.\n    unfold LE. unfold wE.\n    unfold state_validators. simpl. unfold get_validators.\n    apply filter_ext_in. intros.\n\n    unfold equivocation_evidence.\n    rewrite bool_decide_decide.\n    rewrite bool_decide_decide.\n    apply decide_iff.\n    split; intros.\n    - destruct H0 as [e1 [He1 [He1' [e2 [He2 [He2' Hcomp]]]]]].\n      exists e1.\n      split.\n      + unfold has_been_observed. simpl.\n        unfold observable_events_has_been_observed.\n        unfold state_observable_events_fn.\n        setoid_rewrite hbo_cobs' in He1.\n        apply cobs_single in He1.\n        destruct He1 as [j [Heqj]].\n        destruct Heqj;[|intuition]. subst j.\n        apply set_union_in_iterated.\n        rewrite Exists_exists.\n        exists ((@simp_lv_observations index i index_listing _) (s i) (get_simp_event_subject e1)).\n        split.\n        * apply in_map_iff. exists (get_simp_event_subject e1). split;[intuition|apply in_listing].\n        * intuition.\n      + split;[intuition|].\n        exists e2.\n        split.\n        * unfold has_been_observed. simpl.\n        unfold observable_events_has_been_observed.\n        unfold state_observable_events_fn.\n        setoid_rewrite hbo_cobs' in He2.\n        apply cobs_single in He2.\n        destruct He2 as [j [Heqj]].\n        destruct Heqj;[|intuition]. subst j.\n        apply set_union_in_iterated.\n        rewrite Exists_exists.\n        exists ((@simp_lv_observations index i index_listing _) (s i) (get_simp_event_subject e2)).\n        split.\n        -- apply in_map_iff. exists (get_simp_event_subject e2). split;[intuition|apply in_listing].\n        -- intuition.\n        * split;intuition.\n    - destruct H0 as [e1 [He1 [He1' [e2 [He2 [He2' Hcomp]]]]]].\n      exists e1.\n      setoid_rewrite hbo_cobs'.\n      split.\n      + unfold has_been_observed in He1.\n        simpl in He1.\n        unfold observable_events_has_been_observed in He1.\n        unfold state_observable_events_fn in He1.\n        apply set_union_in_iterated in He1.\n        rewrite Exists_exists in He1.\n        destruct He1 as [le [Hle Hine1]].\n        apply in_map_iff in Hle.\n        destruct Hle as [j [Hsimp Hinj]].\n        rewrite <- Hsimp in Hine1.\n        apply in_simp_lv_observations in Hine1 as Hine1'.\n        subst j.\n        apply cobs_single. exists i. intuition.\n      + split;[intuition|].\n        exists e2.\n        split.\n        * unfold has_been_observed in He2.\n          simpl in He2.\n          unfold observable_events_has_been_observed in He2.\n          unfold state_observable_events_fn in He2.\n          apply set_union_in_iterated in He2.\n          rewrite Exists_exists in He2.\n          destruct He2 as [le [Hle Hine2]].\n          apply in_map_iff in Hle.\n          destruct Hle as [j [Hsimp Hinj]].\n          rewrite <- Hsimp in Hine2.\n          apply in_simp_lv_observations in Hine2 as Hine2'.\n          subst j.\n          apply cobs_single. exists i. intuition.\n        * split;intuition.\n    Qed.\n\n  Lemma eqv_aware_something2\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (Hnf : no_component_fully_equivocating s (GH s))\n    (res_send := send_phase_result s)\n    (res := common_future s)\n    (i j : index)\n    (Hin : In i (GH res) /\\ In j (GH res)) :\n    no_equivocating_decisions (res i) (HE res) =\n    no_equivocating_decisions (res j) (HE res).\n  Proof.\n    unfold no_equivocating_decisions.\n    assert (res i <> Bottom /\\ res j <> Bottom). {\n      split;apply protocol_state_component_no_bottom;\n      apply common_future_result_protocol; intuition.\n     }\n     destruct (res i) eqn : eq_resi;[intuition congruence|].\n     destruct (res j) eqn : eq_resj;[intuition congruence|].\n     rewrite <- eq_resi. rewrite <- eq_resj.\n     f_equal.\n     unfold get_no_equivocating_states.\n     apply map_ext_in.\n     intros.\n     - specialize (@wH_wE _ _ _ _ _ _ _ (GH res) res) as Hdiff.\n       unfold HE in H0.\n       destruct Hdiff as [_ Hdiff].\n       specialize (Hdiff a H0).\n       apply honest_equiv_proj_same.\n       all : intuition.\n  Qed.\n\n  Lemma honest_nodes_same_estimators\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (Hnf : no_component_fully_equivocating s (GH s))\n    (res_send := send_phase_result s)\n    (res := common_future s) :\n    forall (i j : index) (b : bool),\n    In i (GH res) ->\n    In j (GH res) ->\n    (est' i (res i) b) <-> (est' j (res j) b).\n  Proof.\n    intros.\n    unfold est'.\n    unfold equivocation_aware_estimator.\n    assert (res i <> Bottom /\\ res j <> Bottom). {\n      split; apply protocol_state_component_no_bottom; apply common_future_result_protocol; intuition.\n    }\n    destruct (res i) eqn : resi;[intuition congruence|].\n    destruct (res j) eqn : resj;[intuition congruence|].\n\n    rewrite <- resi. rewrite <- resj.\n\n    specialize (local_and_honest s Hpr Hnf) as Hlocal. simpl in Hlocal.\n    specialize (Hlocal i H) as Hlocali.\n    specialize (Hlocal j H0) as Hlocalj.\n    unfold res.\n\n    replace (equivocating_validators (common_future s i)) with (LE i res).\n    replace (equivocating_validators (common_future s j)) with (LE j res).\n    2, 3 : (apply eqv_aware_something; apply common_future_result_protocol; intuition).\n\n    unfold res.\n    rewrite <- local_and_honest_equal by intuition.\n    rewrite <- local_and_honest_equal by intuition.\n\n    unfold res in resi. unfold res in resj.\n    rewrite resi. rewrite resj. rewrite <- resi. rewrite <- resj.\n    rewrite eqv_aware_something2 with (j := j) by intuition.\n    intuition.\n  Qed.\n\n  Lemma ncfe\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s) :\n    no_component_fully_equivocating s (GH s).\n  Proof.\n    unfold no_component_fully_equivocating.\n    intros.\n    unfold not_all_equivocating.\n    unfold no_equivocating_decisions.\n    destruct (s i) eqn : eq_si.\n    - apply protocol_state_component_no_bottom in eq_si; intuition.\n    - destruct (map decision\n      (get_no_equivocating_states (Something b is) (equivocating_validators (Something b is)))) eqn : eq_m.\n      + apply map_eq_nil in eq_m.\n        unfold get_no_equivocating_states in eq_m.\n        apply map_eq_nil in eq_m.\n        rewrite <- eq_si in eq_m.\n        rewrite <- eqv_aware_something in eq_m.\n        2 : intuition.\n        assert (forall (j : index), In j (LE i s)). {\n          intros.\n          apply wE_wH'.\n          intros contra.\n          setoid_rewrite wH_wE in contra.\n          unfold LE in eq_m.\n          rewrite eq_m in contra.\n          intuition.\n        }\n        specialize (ws_incl_wE s index_listing [i]) as Hincl.\n        spec Hincl. {\n          unfold incl. intros.\n          apply in_listing.\n        }\n        unfold LE in H0.\n        assert (forall (j : index), In j (GE s)). {\n          unfold GE. intros.\n          specialize (H0 j).\n          specialize (Hincl j H0).\n          intuition.\n        }\n        specialize (H1 i).\n        unfold GH in H.\n        apply wH_wE' in H.\n        intuition.\n      + congruence.\n  Qed.\n\n  Theorem common_futures\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s) :\n    exists (s' : vstate X),\n    in_futures X s s' /\\\n    GH s = GH s' /\\\n    (forall (i j : index) (b : bool),\n     In i (GH s') ->\n     In j (GH s') ->\n     (est' i (s' i) b) <-> (est' j (s' j) b)).\n  Proof.\n    specialize (ncfe s Hpr) as Hncfe.\n    exists (common_future s).\n    split.\n    - apply common_future_in_futures; intuition.\n    - split.\n      + apply GH_eq2; intuition.\n      + apply honest_nodes_same_estimators; intuition.\n  Qed.\n\nEnd CommonFutures.\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/CommonFutures.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2936222112460766}}
{"text": "Require Import Coq.Program.Basics.\nRequire Import LogicalRelations.\nRequire Import SimulationRelation.\nRequire Import SimrelToolkit.\nRequire Import Structures.\nRequire Import OptionOrders.\nRequire Import compcert.lib.Floats.\nRequire Import compcert.common.Values.\nRequire Export liblayers.compcertx.SimValues.\nRequire Export liblayers.lib.ExtensionalityAxioms.\n\n(** * [simrel_strong_id], a stronger version of [simrel_id],\n      to prove that any primitive stable under [simrel_strong_id]\n      makes [ec_valid_block] hold.\n *)\n\nSection STRONG_IDENTITY.\n  Context `{Hmem: BaseMemoryModel}.\n  Context {D: layerdata}.\n  Local Opaque mwd_ops.\n\n  Inductive simrel_strong_id_match_mem (b: block): relation (mwd D) :=\n    match_mem_intro_simrel_strong_id m:\n      b = Mem.nextblock m ->\n      simrel_strong_id_match_mem b m m.\n\n  Lemma match_mem_incr_elim_simrel_strong_id\n        b1 m1 m1'\n        b2 m2 m2':\n    Ple b1 b2 ->\n    simrel_strong_id_match_mem b1 m1 m1' ->\n    simrel_strong_id_match_mem b2 m2 m2' ->\n    (forall b, Mem.valid_block m1 b -> Mem.valid_block m2 b) /\\\n    (forall b, Mem.valid_block m1' b -> Mem.valid_block m2' b).\n  Proof.\n    inversion 2; subst.\n    inversion 1; subst.\n    unfold Mem.valid_block.\n    intuition xomega.\n  Qed.\n  \n  Definition simrel_strong_id_ops: simrel_components D D :=\n    {|\n      simrel_world := block;\n      simrel_acc := {| le := Ple |};\n      simrel_new_glbl := nil;\n      simrel_undef_matches_values_bool := false;\n      simrel_undef_matches_block p b := False;\n      simrel_meminj p := inject_id;\n      match_mem := simrel_strong_id_match_mem\n    |}.\n\n  Local Instance simrel_strong_id_corefl:\n    CoreflexiveInjection D D simrel_strong_id_ops.\n  Proof.\n    split.\n    - reflexivity.\n    - reflexivity.\n    - tauto.\n  Qed.\n\n  Lemma match_block_sameofs_simrel_strong_id p:\n    match_block_sameofs simrel_strong_id_ops p = eq.\n  Proof.\n    apply eqrel_eq; split.\n    - inversion 1.\n      reflexivity.\n    - intros b _ [].\n      reflexivity.\n  Qed.\n\n  Lemma match_block_simrel_strong_id p:\n    match_block simrel_strong_id_ops p = eq.\n  Proof.\n    apply eqrel_eq; split.\n    - intros b1 b2 [ofs H].\n      inversion H; congruence.\n    - intros b _ [].\n      exists 0%Z.\n      reflexivity.\n  Qed.\n\n  Lemma match_ptr_simrel_strong_id p:\n    match_ptr simrel_strong_id_ops p = eq.\n  Proof.\n    eapply eqrel_eq.\n    split.\n    - destruct 1.\n      inversion H; subst.\n      rewrite Z.add_0_r.\n      reflexivity.\n    - intros [b ofs] y [].\n      rewrite <- (Z.add_0_r ofs) at 2.\n      constructor.\n      reflexivity.\n  Qed.\n\n  Lemma match_ptrbits_simrel_strong_id p:\n    match_ptrbits simrel_strong_id_ops p = eq.\n  Proof.\n    apply eqrel_eq; split.\n    - destruct 1.\n      inversion H; subst.\n      change (Ptrofs.repr 0) with Ptrofs.zero.\n      rewrite Ptrofs.add_zero.\n      reflexivity.\n    - intros [b ofs] y [].\n      rewrite <- (Ptrofs.add_zero ofs) at 2.\n      change Ptrofs.zero with (Ptrofs.repr 0).\n      constructor.\n      reflexivity.\n  Qed.\n\n  Lemma match_ptrrange_simrel_strong_id p:\n    match_ptrrange simrel_strong_id_ops p = eq.\n  Proof.\n    eapply eqrel_eq.\n    split.\n    - destruct 1.\n      inversion H; subst.\n      rewrite match_ptr_simrel_strong_id in H.\n      congruence.\n    - intros [[b lo] hi] _ [].\n      replace hi with (lo + (hi - lo))%Z by omega.\n      constructor.\n      rewrite match_ptr_simrel_strong_id.\n      reflexivity.\n  Qed.\n\n  Lemma match_val_simrel_strong_id p:\n    match_val simrel_strong_id_ops p = eq.\n  Proof.\n    apply eqrel_eq; split.\n    - destruct 1; try contradiction; try discriminate; try reflexivity.\n      rewrite match_ptrbits_simrel_strong_id in H.\n      congruence.\n    - intros v _ [].\n      destruct v; constructor.\n      rewrite match_ptrbits_simrel_strong_id.\n      reflexivity.\n  Qed.\n\n  Lemma match_memval_simrel_strong_id p:\n    match_memval simrel_strong_id_ops p = eq.\n  Proof.\n    apply eqrel_eq; split.\n    - destruct 1; try contradiction; try discriminate; try reflexivity.\n      rewrite match_val_simrel_strong_id in H.\n      congruence.\n    - intros v _ [].\n      destruct v; constructor.\n      rewrite match_val_simrel_strong_id.\n      reflexivity.\n  Qed.\n\n  Local Instance simrel_strong_id_prf:\n    CoreflexiveSimulationRelation D D simrel_strong_id_ops.\n  Proof.\n    constructor.\n\n    + (* [simrel_acc_preorder] *)\n      split.\n    - red. apply Ple_refl.\n    - red. apply Ple_trans.\n\n    + (* [simrel_acc_meminj] *)\n      repeat red. simpl. repeat constructor.\n\n    + (* [simrel_undef_matches_block_not_weak_valid] *)\n      simpl.\n      inversion 1; subst.\n      congruence.\n\n    + (* [simrel_undef_matches_block_invalid] *)\n      simpl.\n      inversion 1; subst.\n      congruence.\n\n    + (* [match_global_block_sameofs] *)\n      discriminate.\n\n    + (* [Genv.init_mem] *)\n      intros F V p1 p2 Hp.\n      eapply genv_init_mem_simrel; eauto.\n      * apply SimrelCategory.simrel_id_init_mem.\n      * simpl.\n        intros m _ [[] Hnb].\n        exists glob_threshold.\n        red in Hnb.\n        constructor.\n        destruct Hnb.\n        reflexivity.\n\n    + (* [simrel_alloc] *)\n      repeat red.\n      intros p m_ m.\n      inversion 1; subst.\n      exists (Psucc (Mem.nextblock m)).\n      split.\n      {\n        apply Ple_succ.\n      }\n      split; try reflexivity.\n      constructor.\n      symmetry.\n      destruct (Mem.alloc _ _ _) eqn:ALLOC.\n      simpl.\n      eapply Mem.nextblock_alloc; eauto.\n\n    + (* [simrel_free] *)\n      intros w m1 m2 Hm b1 b2 Hb lo hi.\n      destruct Hm; subst.\n      apply coreflexivity in Hb; subst.\n      destruct (Mem.free _ _ _ _) eqn:FREE; constructor.\n      exists (Mem.nextblock m).\n      split; try reflexivity.\n      constructor.\n      symmetry; eapply Mem.nextblock_free; eauto.\n\n    + (* [simrel_load] *)\n      intros w chunk m1 m2 Hm b1 b2 Hb ofs.\n      destruct Hm; subst.\n      apply coreflexivity in Hb; subst.\n      rewrite match_val_simrel_strong_id.\n      reflexivity.\n\n    + (* [simrel_store] *)\n      intros w chunk m1 m2 Hm b1 b2 Hb ofs v1 v2 Hv.\n      destruct Hm; subst.\n      apply coreflexivity in Hb; subst.\n      apply coreflexivity in Hv; subst.\n      destruct (Mem.store _ _ _ _ _) eqn:STORE; constructor.\n      exists (Mem.nextblock m).\n      split; try reflexivity.\n      constructor.\n      symmetry; eapply Mem.nextblock_store; eauto.\n\n    + (* [simrel_loadbytes] *)\n      intros w m1 m2 Hm b1 b2 Hb ofs sz.\n      destruct Hm; subst.\n      apply coreflexivity in Hb; subst.\n      rewrite match_memval_simrel_strong_id.\n      reflexivity.\n\n    + (* [simrel_storebytes] *)\n      intros w m1 m2 Hm b1 b2 Hb ofs vs1 vs2 Hvs.\n      destruct Hm; subst.\n      apply coreflexivity in Hb; subst.\n      apply coreflexivity in Hvs; subst.\n    destruct (Mem.storebytes _ _ _ _) eqn:STORE; constructor.\n    exists (Mem.nextblock m).\n    split; try reflexivity.\n    constructor.\n    symmetry; eapply Mem.nextblock_storebytes; eauto.\n\n    + (* [simrel_perm] *)\n      intros w m1 m2 Hm b1 b2 Hb ofs k pe.\n      destruct Hm; subst.\n      apply coreflexivity in Hb; subst.\n      reflexivity.\n\n    + (* [simrel_valid_block] *)\n      inversion 1.\n      reflexivity.\n  Qed.\n\n  Definition simrel_strong_id: simrel D D :=\n    {|\n      simrel_ops := simrel_strong_id_ops\n    |}.\n\nEnd STRONG_IDENTITY.\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/simrel/SimrelStrongId.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.29360728207179854}}
{"text": "Set Implicit Arguments.\nSet Bullet Behavior \"Strict Subproofs\".\n\nRequire Import String List.\nImport ListNotations.\nOpen Scope string.\nOpen Scope list.\nFrom Utils Require Import Utils Monad Gensym.\nFrom Named Require Import Core Compilers Elab ElabCompilers.\nImport Core.Notations.\n\n\n(*TODO: move to utils*)\nFixpoint no_repeats {A} (l : list A) :=\n  match l with\n  | [] => True\n  | n::l' => ~ In n l' /\\ no_repeats l'\n  end.\n  \n(*TODO: move to utils?*)\nDefinition bijective_on {A B} (f : A -> B) l : Prop :=\n  no_repeats (map f l).\n\n(*Arguments bijective_on {_} {_} _ !_ /. *)\n\n(*TODO: move to utils*)\n#[export] Hint Resolve in_map : utils.\n\nLemma bijective_fn_injective {A B} (f : A -> B) l\n  : bijective_on f l ->\n    forall x y, In x l ->\n                In y l ->\n                f x = f y -> x = y.\nProof.\n  induction l; basic_goal_prep; basic_utils_firstorder_crush.\n  {\n    rewrite H2 in H.\n    basic_utils_crush.\n  }\n  {\n    rewrite <-H2 in H.\n    basic_utils_crush.\n  }\nQed.\n\n\nSection WithVar.\n  Context (V1 : Type)\n          {V1_Eqb : Eqb V1}\n          {V1_default : WithDefault V1}.\n  Context (V2 : Type)\n          {V2_Eqb : Eqb V2}\n          {V2_default : WithDefault V2}.\n\n\nSection RenameFromFn.\n  (*TODO: renamings from V1 to V2*)\n  Context (f : V1 -> V2).\n\n  Fixpoint compiler_from_fn (l : lang V1) : compiler V2 :=\n    match l with\n    | [] => []\n    | (n,sort_rule c args)::l =>\n        (f n, sort_case (map f (map fst c)) (scon (f n) (map var (map f args))))::(compiler_from_fn l)\n    | (n,term_rule c args _)::l =>\n        (f n, term_case (map f (map fst c)) (con (f n) (map var (map f args))))::(compiler_from_fn l)\n    | _::l => compiler_from_fn l\n    end.\n\n  Fixpoint elab_compiler_from_fn (l : lang V1) :=\n    match l with\n    | [] => []\n    | (n,sort_rule c _)::l =>\n        let args := map f (map fst c) in\n        (f n, sort_case args (scon (f n) (map var args)))\n          ::(elab_compiler_from_fn l)\n    | (n,term_rule c _ _)::l =>\n        let args := map f (map fst c) in\n        (f n, term_case args (con (f n) (map var args)))\n          ::(elab_compiler_from_fn l)\n    | _::l => elab_compiler_from_fn l\n    end.\n\n  Fixpoint rename_term e :=\n    match e with\n    | var x => var (f x)\n    | con n s => con (f n) (map rename_term s)\n    end.\n\n  Definition rename_sort t :=\n    match t with\n    | scon n s => scon (f n) (map rename_term s)\n    end.\n\n  Definition rename_and_map {A B} (g : A -> B): named_list A -> named_list B :=\n    map (fun '(n,v)=> (f n, g v)).\n             \n  Definition rename_ctx (c : ctx V1) : ctx V2 := rename_and_map rename_sort c.\n  \n  Definition rename_subst (s : subst V1) : subst V2 := rename_and_map rename_term s.\n  Definition rename_args (s : list (term V1)) := map rename_term s.\n\n  Lemma rename_subst_lookup (s : subst V1) n\n    : rename_term (subst_lookup s n) = subst_lookup (rename_subst s) (f n).\n  Proof.\n    induction s; basic_goal_prep; basic_term_crush.\n    my_case H (eqb n v);\n      basic_term_crush.\n    my_case H' (eqb (f n) (f v));\n      basic_term_crush.\n    TODO: need bijectivity\n  Qed.\n  Hint Rewrite rename_subst_lookup : term.\n  \n  Lemma rename_term_subst_comm e s\n    : rename_term e[/s/] = (rename_term e)[/rename_subst s/].\n  Proof.\n    induction e; basic_goal_prep; basic_term_crush.\n    revert dependent l.\n    induction l; basic_goal_prep; basic_term_crush.\n  Qed.\n  Hint Rewrite rename_term_subst_comm : term.\n\n  \n  Lemma rename_args_subst_comm e s\n    : rename_args e[/s/] = (rename_args e)[/rename_subst s/].\n  Proof.\n    induction e; basic_goal_prep; basic_term_crush.\n  Qed.\n  Hint Rewrite rename_args_subst_comm : term.\n\n  \n  Lemma rename_sort_subst_comm e s\n    : rename_sort e[/s/] = (rename_sort e)[/rename_subst s/].\n  Proof.\n    induction e; basic_goal_prep; basic_term_crush.\n  Qed.\n  Hint Rewrite rename_sort_subst_comm : term.\n\n  \n  Lemma rename_subst_subst_comm e s\n    : rename_subst e[/s/] = (rename_subst e)[/rename_subst s/].\n  Proof.\n    induction e; basic_goal_prep; fold_Substable; basic_term_crush.\n  Qed.\n  Hint Rewrite rename_subst_subst_comm : term.\n\n  \n  Lemma rename_subst_with_names_from A (c : named_list A) s\n    : rename_subst (with_names_from c s) = with_names_from c (rename_args s).\n  Proof.\n    revert s.\n    induction c;\n      destruct s;\n      basic_goal_prep; basic_term_crush.\n  Qed.\n  Hint Rewrite rename_subst_with_names_from : term.\n    \n  \n  Definition rename_rule r :=\n    match r with\n    | sort_rule c args => sort_rule (rename_ctx c) args\n    | term_rule c args t => term_rule (rename_ctx c) args (rename_sort t)\n    | sort_eq_rule c t1 t2 => sort_eq_rule (rename_ctx c) (rename_sort t1) (rename_sort t2)\n    | term_eq_rule c e1 e2 t => term_eq_rule (rename_ctx c) (rename_term e1) (rename_term e2) (rename_sort t)\n    end.\n\n  Definition rename_lang (l : lang) : lang :=\n    map (fun '(n,r) => (f n,rename_rule r)) l.\n\n  \n  Local Lemma in_rename l n r\n    : In (n,r) l -> In (f n, rename_rule r) (rename_lang l).\n  Proof.\n    unfold rename_lang.\n    intro.\n    eapply in_map in H.\n    exact H.\n  Qed.\n  Local Hint Resolve in_rename : lang_core.\n\n  Lemma with_names_from_rename_ctx A c (s : list A)\n    : with_names_from (rename_ctx c) s = with_names_from c s.\n  Proof.\n    revert s.\n    induction c; destruct s; basic_goal_prep; basic_term_crush.\n  Qed.\n  \n  Local Lemma rename_mono l\n    : (forall c t1 t2,\n          eq_sort l c t1 t2 ->\n          eq_sort (rename_lang l) (rename_ctx c) (rename_sort t1) (rename_sort t2))\n      /\\ (forall c t e1 e2,\n             eq_term l c t e1 e2 ->\n             eq_term (rename_lang l) (rename_ctx c) (rename_sort t) (rename_term e1) (rename_term e2))\n      /\\ (forall c c' s1 s2,\n             eq_subst l c c' s1 s2 ->\n             eq_subst (rename_lang l) (rename_ctx c) (rename_ctx c') (rename_subst s1) (rename_subst s2))\n      /\\ (forall c t,\n             wf_sort l c t ->\n             wf_sort (rename_lang l) (rename_ctx c) (rename_sort t))\n      /\\ (forall c e t,\n             wf_term l c e t ->\n             wf_term (rename_lang l) (rename_ctx c) (rename_term e) (rename_sort t))\n      /\\ (forall c s c',\n             wf_args l c s c' ->\n             wf_args (rename_lang l) (rename_ctx c) (rename_args s) (rename_ctx c'))\n      /\\ (forall c,\n             wf_ctx l c ->\n             wf_ctx (rename_lang l) (rename_ctx c)).\n  Proof.\n    apply judge_ind; basic_goal_prep;\n      try match goal with\n            [ H : In _ l |- _] =>\n            apply in_rename in H; simpl in H\n          end;      \n      basic_core_firstorder_crush.\n    {\n      rewrite <- with_names_from_rename_ctx.\n      basic_core_firstorder_crush.\n    }\n    {\n      eapply in_map in H.\n      constructor.\n      exact H.\n    }\n    {\n      constructor.\n      {\n        basic_core_firstorder_crush.\n        rewrite with_names_from_rename_ctx.\n        basic_core_crush.\n      }\n      basic_core_crush.\n    }\n    {\n      unfold rename_ctx.\n      rewrite fresh_named_map.\n      assumption.\n    }\n  Qed.\n                                                   \n  Local Lemma elab_rename_mono l\n    : (forall c t et,\n          elab_sort l c t et ->\n          elab_sort (rename_lang l) (rename_ctx c) (rename_sort t) (rename_sort et))\n      /\\ (forall c e ee t,\n             elab_term l c e ee t ->\n             elab_term (rename_lang l) (rename_ctx c) (rename_term e) (rename_term ee) (rename_sort t))\n      /\\ (forall c s args es c',\n             elab_args l c s args es c' ->\n             elab_args (rename_lang l)  (rename_ctx c) (rename_args s) args (rename_args es) (rename_ctx c'))\n      /\\ (forall c ec,\n             elab_ctx l c ec ->\n             elab_ctx (rename_lang l) (rename_ctx c) (rename_ctx ec)).\n  Proof using.\n    apply elab_ind; basic_goal_prep; \n      try match goal with\n            [ H : In _ l |- _] =>\n            apply in_rename in H; simpl in H\n          end;      \n      basic_core_firstorder_crush.\n    {\n      rewrite <- with_names_from_rename_ctx.\n      basic_core_firstorder_crush.\n    }\n    {\n      apply (proj1 (rename_mono l)) in H1.\n      basic_core_firstorder_crush.      \n    }\n    {\n      eapply in_map in H.\n      constructor.\n      exact H.\n    }\n    {\n      constructor.\n      {\n        basic_core_firstorder_crush.\n        rewrite with_names_from_rename_ctx.\n        basic_core_crush.\n      }\n      { basic_core_crush. }\n    }\n    {\n      constructor.\n      { basic_core_crush.\n     (* TODO: rw backwards, apply earlier lem*)\n  Abort.                  \n\n\nEnd RenameFromFn.\n\nHint Rewrite rename_subst_lookup : term.\n\n(*         \nDefinition elab_sort_lang_rename_monotonicity f l\n  := proj1 (elab_rename_mono f l).\n#[export] Hint Resolve elab_sort_lang_rename_monotonicity : lang_core.\n\nDefinition elab_term_lang_rename_monotonicity f l\n  := proj1 (proj2 (elab_rename_mono f l)).\n#[export] Hint Resolve elab_term_lang_rename_monotonicity : lang_core.\n\nDefinition elab_args_lang_rename_monotonicity f l\n  := proj1 (proj2 (proj2 (elab_rename_mono f l))).\n#[export] Hint Resolve elab_args_lang_rename_monotonicity : lang_core.\n\nDefinition elab_ctx_lang_rename_monotonicity f l\n  := proj2 (proj2 (proj2 (elab_rename_mono f l))).\n#[export] Hint Resolve elab_ctx_lang_rename_monotonicity : lang_core.\n*)\n\nDefinition eq_sort_lang_monotonicity_rename f l\n  := proj1 (rename_mono f l).\nHint Resolve eq_sort_lang_monotonicity_rename : lang_core.\n\nDefinition eq_term_lang_monotonicity_rename f l\n  := proj1 (proj2 (rename_mono f l)).\nHint Resolve eq_term_lang_monotonicity_rename : lang_core.\n\nDefinition eq_subst_lang_monotonicity_rename f l\n  := proj1 (proj2 (proj2 (rename_mono f l))).\nHint Resolve eq_subst_lang_monotonicity_rename : lang_core.\n\nDefinition wf_sort_lang_monotonicity_rename f l\n  := proj1 (proj2 (proj2 (proj2 (rename_mono f l)))).\nHint Resolve wf_sort_lang_monotonicity_rename : lang_core.\n\nDefinition wf_term_lang_monotonicity_rename f l\n  := proj1 (proj2 (proj2 (proj2 (proj2 (rename_mono f l))))).\nHint Resolve wf_term_lang_monotonicity_rename : lang_core.\n\nDefinition wf_args_lang_monotonicity_rename f l\n  := proj1 (proj2 (proj2 (proj2 (proj2 (proj2 (rename_mono f l)))))).\nHint Resolve wf_args_lang_monotonicity_rename : lang_core.\n\nDefinition wf_ctx_lang_monotonicity_rename f l\n  := proj2 (proj2 (proj2 (proj2 (proj2 (proj2 (rename_mono f l)))))).\nHint Resolve wf_ctx_lang_monotonicity_rename : lang_core.\n\nLemma wf_rule_lang_monotonicity_rename f l r\n  : wf_rule l r -> wf_rule (rename_lang f l) (rename_rule f r).\nProof.\n  inversion 1; basic_goal_prep; unfold rename_ctx; basic_core_firstorder_crush.\n  all: rewrite !named_map_fst_eq; auto.\nQed.\nHint Resolve wf_rule_lang_monotonicity_rename : lang_core.\n\nLocal Lemma fresh_rename f n l\n  : bijective_on f (n::map fst l) -> fresh n l -> fresh (f n) (rename_lang f l).\nProof.\n  unfold bijective_on.\n  simpl.\n  induction l; basic_goal_prep.\n  { basic_term_crush. }\n  { firstorder. }\nQed.\n\nLemma wf_lang_rename f l\n  : bijective_on f (map fst l) -> wf_lang l -> wf_lang (rename_lang f l).\nProof.\n  induction 2; basic_goal_prep; basic_core_firstorder_crush.\n  apply  fresh_rename; eauto.\n  unfold bijective_on.\n  simpl.\n  firstorder.\nQed.  \nHint Resolve wf_lang_rename : lang_core.\n\n  \n(*TODO: compilers part *)\n(*\nTheorem renaming_preserving f tgt cmp l\n  : incl (rename_lang f l) tgt -> elab_preserving_compiler cmp tgt (compiler_from_fn f l) (elab_compiler_from_fn f l) l.\nProof.\n  induction l; basic_goal_prep.\n  basic_core_crush.\n  destruct r; basic_goal_prep; basic_core_crush.\n  {\n    constructor; auto.\n    \n    basic_core_crush.\n    \n    TODO: need renaming for Elab.elab\n*)\n\nEnd RenameFromFn.\n\nSection RenameFromList.\n  Context (rn : @named_list V V'\n  \n\nFail\nEnd WithVar.\n(*TODO: export hints*)\n", "meta": {"author": "DIJamner", "repo": "pyrosome", "sha": "a8d7f0aa3141b35a3c59d8d72aadf47a3b0c5df6", "save_path": "github-repos/coq/DIJamner-pyrosome", "path": "github-repos/coq/DIJamner-pyrosome/pyrosome-a8d7f0aa3141b35a3c59d8d72aadf47a3b0c5df6/WIP/Renaming.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.293560766853691}}
{"text": "Require Import Coqlib.\nRequire Import Errors.\nRequire Import Integers.\nRequire Import Tree.\nRequire Import String.\nRequire Import Asm.\n\nRequire TransExpression.\nRequire TransBranchInfo.\n\nLocal Open Scope error_monad_scope.\n\nSet Implicit Arguments.\n\nFixpoint cons_branch_info_list (cl : list (list condition)) (sl : list statement) : res (list branch_info) :=\n  match cl with\n  | nil =>\n    OK nil\n  | hd :: tl =>\n    do v2 <- cons_branch_info_list tl sl;\n    OK ({| cond := hd; stmt := sl |} :: v2)\n  end.\n\nDefinition trans_if_branch (id : identifier) (ib : if_branch) (fl : list field) : res (list branch_info) :=\n  match ib with\n  | If_Branch expr stmt_list =>\n    do expr_list <- TransExpression.reorder_expression expr;\n    do cond_list_list <- TransExpression.protocol_expression_list_to_condition_list id expr_list fl;\n    cons_branch_info_list cond_list_list stmt_list\n  end.\n\n\nFixpoint trans_if_branch_list (id : identifier) (ibl : list if_branch) (fl : list field) : res (list branch_info) :=\n  match ibl with\n  | nil =>\n    OK nil\n  | hd :: tl =>\n    do v1 <- trans_if_branch id hd fl;\n    do v2 <- trans_if_branch_list id tl fl;\n    OK (v1 ++ v2)\n  end.\n\nDefinition trans_protocol_statement (id : identifier) (s : select_statement) (fl : list field) : res (list branch_info) :=\n  match s with\n  | As_If if_stmt =>\n    match if_stmt with\n    | If_Statement if_branch_list else_branch =>\n      trans_if_branch_list id if_branch_list fl\n    end\n  | As_Simple simple_stmt =>\n    OK ({| cond := nil; stmt := (simple_stmt :: nil) |} :: nil)\n  end.\n    \n\nFixpoint trans_protocol_statement_list (id : identifier) (sl : list select_statement) (fl : list field) : res (list branch_info) :=\n  match sl with\n  | nil =>\n    OK nil\n  | hd :: tl =>\n    do v1 <- trans_protocol_statement id hd fl;\n    do v2 <- trans_protocol_statement_list id tl fl;\n    TransBranchInfo.multiply_branch_info v1 v2\n  end.\n\nDefinition translate (id : identifier) (sl : list select_statement) (fl : list field) : res (list branch_info) :=\n  trans_protocol_statement_list id sl fl.\n", "meta": {"author": "leeehh", "repo": "P3_language_compiler", "sha": "a86073c084e75053a63421cc005fb6552a0f518d", "save_path": "github-repos/coq/leeehh-P3_language_compiler", "path": "github-repos/coq/leeehh-P3_language_compiler/P3_language_compiler-a86073c084e75053a63421cc005fb6552a0f518d/translator/TransProtoStatement.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.293560766853691}}
{"text": "Require Import VerdiRaft.Raft.\nRequire Import VerdiRaft.CommonTheorems.\nRequire Import VerdiRaft.SpecLemmas.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nRequire Import VerdiRaft.TermsAndIndicesFromOneLogInterface.\nRequire Import VerdiRaft.CurrentTermGtZeroInterface.\n\nSection TermsAndIndicesFromOneLog.\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 {ctgzi : current_term_gt_zero_interface}.\n\n  Definition terms_and_indices_from_one_log_ind (net : network) : Prop :=\n    terms_and_indices_from_one_log net /\\ terms_and_indices_from_one_log_nw net.\n\n  Lemma terms_and_indices_from_one_log_ind_init :\n    raft_net_invariant_init terms_and_indices_from_one_log_ind.\n  Proof using. \n    split.\n    - unfold terms_and_indices_from_one_log, terms_and_indices_from_one. simpl. contradiction.\n    - unfold terms_and_indices_from_one_log_nw, terms_and_indices_from_one. simpl. contradiction.\n  Qed.\n\n  Lemma taifol_no_append_entries :\n    forall ps' net ms p t leaderId prevLogIndex prevLogTerm entries leaderCommit h,\n      (forall (p : packet), In p ps' -> In p (nwPackets net) \\/ In p (send_packets h ms)) ->\n      (forall m, In m ms -> ~ is_append_entries (snd m)) ->\n      In p ps' ->\n      pBody p = AppendEntries t leaderId prevLogIndex prevLogTerm entries leaderCommit ->\n      terms_and_indices_from_one_log_nw net ->\n      terms_and_indices_from_one entries.\n  Proof using. \n    intros. find_apply_hyp_hyp. break_or_hyp; eauto. unfold send_packets in *. do_in_map.\n    find_apply_hyp_hyp. unfold not in *. find_false.\n    subst. simpl in *. repeat find_rewrite. eauto 10.\n  Qed.\n\n  Lemma terms_and_indices_from_one_log_ind_client_request :\n    raft_net_invariant_client_request terms_and_indices_from_one_log_ind.\n  Proof using ctgzi. \n    red. unfold terms_and_indices_from_one_log_ind. split; red; simpl in *; intuition.\n    - find_higher_order_rewrite. update_destruct; subst; rewrite_update; auto.\n      find_apply_lem_hyp handleClientRequest_log. intuition.\n      + repeat find_rewrite. auto.\n      + break_exists. intuition.\n        unfold terms_and_indices_from_one_log, terms_and_indices_from_one in *.\n        intros. repeat find_rewrite. simpl in *. break_or_hyp.\n        * intuition. find_apply_lem_hyp current_term_gt_zero_invariant. find_rewrite.\n          eapply_prop current_term_gt_zero. congruence.\n        * eauto.\n    - eapply taifol_no_append_entries; pose handleClientRequest_no_append_entries; eauto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_log_ind_timeout :\n    raft_net_invariant_timeout terms_and_indices_from_one_log_ind.\n  Proof using. \n    red. unfold terms_and_indices_from_one_log_ind. split; red; simpl in *; intuition.\n    - find_higher_order_rewrite. update_destruct; subst; rewrite_update; auto.\n      find_apply_lem_hyp handleTimeout_log_same. find_rewrite. auto.\n    - eapply taifol_no_append_entries; pose handleTimeout_packets; eauto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_app :\n    forall xs ys,\n      terms_and_indices_from_one xs ->\n      terms_and_indices_from_one ys ->\n      terms_and_indices_from_one (xs ++ ys).\n  Proof using. \n    induction xs.\n    - auto.\n    - unfold terms_and_indices_from_one in *. simpl. intros. break_or_hyp; eauto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_In :\n    forall (xs ys : list entry),\n      (forall x, In x xs -> In x ys) ->\n      terms_and_indices_from_one ys ->\n      terms_and_indices_from_one xs.\n  Proof using. \n    unfold terms_and_indices_from_one. eauto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_log_ind_append_entries :\n    raft_net_invariant_append_entries terms_and_indices_from_one_log_ind.\n  Proof using. \n    red. unfold terms_and_indices_from_one_log_ind. split; red; simpl in *; intuition.\n    - find_higher_order_rewrite. update_destruct; subst; rewrite_update; auto.\n      find_apply_lem_hyp handleAppendEntries_log. intuition.\n      + find_rewrite. auto.\n      + subst. unfold terms_and_indices_from_one_log_nw in *. eauto.\n      + break_exists. intuition. subst. find_rewrite. apply terms_and_indices_from_one_app.\n        * eauto.\n        * eapply terms_and_indices_from_one_In; [eapply removeAfterIndex_in | eauto].\n    - unfold terms_and_indices_from_one_log_nw in *. find_apply_hyp_hyp. intuition; eauto.\n      find_apply_lem_hyp handleAppendEntries_not_append_entries.\n      exfalso. apply H. repeat eexists. subst. eauto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_log_ind_append_entries_reply :\n    raft_net_invariant_append_entries_reply terms_and_indices_from_one_log_ind.\n  Proof using. \n    red. unfold terms_and_indices_from_one_log_ind. split; red; simpl in *; intuition.\n    - find_higher_order_rewrite. update_destruct; subst; rewrite_update; auto.\n      find_apply_lem_hyp handleAppendEntriesReply_log. find_rewrite. auto.\n    - find_apply_hyp_hyp. intuition; eauto. do_in_map.\n      find_apply_lem_hyp handleAppendEntriesReply_packets; eauto. subst. contradiction.\n  Qed.\n\n  Lemma terms_and_indices_from_one_log_ind_request_vote :\n    raft_net_invariant_request_vote terms_and_indices_from_one_log_ind.\n  Proof using. \n    red. unfold terms_and_indices_from_one_log_ind. split; red; simpl in *; intuition.\n    - find_higher_order_rewrite. update_destruct; subst; rewrite_update; auto.\n      find_apply_lem_hyp handleRequestVote_log. find_rewrite. auto.\n    - find_apply_hyp_hyp. intuition; eauto. find_apply_lem_hyp handleRequestVote_no_append_entries.\n      unfold not in *. find_false. repeat eexists. subst. eauto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_log_ind_request_vote_reply :\n    raft_net_invariant_request_vote_reply terms_and_indices_from_one_log_ind.\n  Proof using. \n    red. unfold terms_and_indices_from_one_log_ind. split; red; simpl in *; intuition.\n    - find_higher_order_rewrite. update_destruct; rewrite_update; auto.\n      find_apply_lem_hyp handleRequestVoteReply_log. subst. find_rewrite. auto.\n    - eauto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_log_ind_do_leader :\n    raft_net_invariant_do_leader terms_and_indices_from_one_log_ind.\n  Proof using. \n    red. unfold terms_and_indices_from_one_log_ind. split; red; simpl in *; intuition.\n    - find_higher_order_rewrite. update_destruct; subst; rewrite_update; auto.\n      find_apply_lem_hyp doLeader_log. find_rewrite. auto.\n    - find_apply_hyp_hyp. intuition; eauto.\n      unfold doLeader in *. repeat break_match; tuple_inversion; subst; try contradiction.\n      repeat do_in_map. unfold replicaMessage in *. subst. simpl in *. find_inversion.\n      eapply terms_and_indices_from_one_In. apply findGtIndex_in. auto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_log_ind_do_generic_server :\n    raft_net_invariant_do_generic_server terms_and_indices_from_one_log_ind.\n  Proof using. \n    red. unfold terms_and_indices_from_one_log_ind. split; red; simpl in *; intuition.\n    - find_higher_order_rewrite. update_destruct; subst; rewrite_update; auto.\n      find_apply_lem_hyp doGenericServer_log. find_rewrite. auto.\n    - find_apply_lem_hyp doGenericServer_packets. find_apply_hyp_hyp. subst. intuition; eauto.\n      do_in_map. contradiction.\n  Qed.\n\n  Lemma terms_and_indices_from_one_log_ind_state_same_packet_subset :\n    raft_net_invariant_state_same_packet_subset terms_and_indices_from_one_log_ind.\n  Proof using. \n    red. unfold terms_and_indices_from_one_log_ind. split; red; simpl in *; intuition.\n    - find_reverse_higher_order_rewrite. auto.\n    - eauto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_log_ind_reboot :\n    raft_net_invariant_reboot terms_and_indices_from_one_log_ind.\n  Proof using. \n    red. unfold terms_and_indices_from_one_log_ind. split; red; simpl in *; intuition.\n    - find_higher_order_rewrite. update_destruct; subst; rewrite_update; auto.\n      unfold reboot. eauto.\n    - find_reverse_rewrite. eauto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_log_ind_invariant :\n    forall net,\n      raft_intermediate_reachable net ->\n      terms_and_indices_from_one_log_ind net.\n  Proof using ctgzi. \n    intros.\n    apply raft_net_invariant; auto.\n    - apply terms_and_indices_from_one_log_ind_init.\n    - apply terms_and_indices_from_one_log_ind_client_request.\n    - apply terms_and_indices_from_one_log_ind_timeout.\n    - apply terms_and_indices_from_one_log_ind_append_entries.\n    - apply terms_and_indices_from_one_log_ind_append_entries_reply.\n    - apply terms_and_indices_from_one_log_ind_request_vote.\n    - apply terms_and_indices_from_one_log_ind_request_vote_reply.\n    - apply terms_and_indices_from_one_log_ind_do_leader.\n    - apply terms_and_indices_from_one_log_ind_do_generic_server.\n    - apply terms_and_indices_from_one_log_ind_state_same_packet_subset.\n    - apply terms_and_indices_from_one_log_ind_reboot.\n  Qed.\n\n  Instance taifoli : terms_and_indices_from_one_log_interface.\n  Proof.\n    split.\n    - apply terms_and_indices_from_one_log_ind_invariant.\n    - apply terms_and_indices_from_one_log_ind_invariant.\n  Qed.\nEnd TermsAndIndicesFromOneLog.\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/TermsAndIndicesFromOneLogProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331606115021, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.29355732540343704}}
{"text": "From Coq Require Import Strings.String Strings.Ascii.\n\nFrom Equations Require Import Equations.\n\nFrom stdpp Require Import base finite gmap mapset listset_nodup numbers.\n\nFrom MatchingLogic Require Import Syntax DerivedOperators_Syntax ProofSystem.\n\nFrom MatchingLogicProver Require Import Named.\n\nModule MetaMath.\n\n  Inductive IncludeStmt := include_stmt (s : string).\n\n  Inductive MathSymbol := ms (s : string).\n  Inductive Constant := constant (ms : MathSymbol).\n  Inductive ConstantStmt := constant_stmt (cs : list Constant).\n  Inductive Variabl := variable (s : string).\n  Inductive VariableStmt := vs (lv : list Variabl).\n  Inductive DisjointStmt := ds (lv : list Variabl).\n  Inductive TypeCode := tc (c : Constant).\n\n  \n  Inductive Label := lbl (s : string).\n  \n  Inductive FloatingStmt := fs (l : Label) (tc : TypeCode) (var : Variabl).\n  Inductive EssentialStmt := es (l : Label) (tc : TypeCode) (lms : list MathSymbol).\n  \n  \n  Inductive HypothesisStmt :=\n  | hs_floating (fs : FloatingStmt)\n  | hs_essential (es : EssentialStmt)\n  .\n\n  Inductive AxiomStmt := axs (l : Label) (tc : TypeCode) (lms : list MathSymbol).\n\n  Inductive MMProof := pf (ll : list Label).\n  \n  Inductive ProvableStmt := ps (l : Label) (tc : TypeCode) (lms : list MathSymbol) (pf : MMProof).\n  \n  Inductive AssertStmt :=\n  | as_axiom (axs : AxiomStmt)\n  | as_provable (ps : ProvableStmt)\n  .\n  \n  Inductive Stmt :=\n  | stmt_block (ls : list Stmt)\n  | stmt_variable_stmt (vs : VariableStmt)\n  | stmt_disj_stmt (ds : DisjointStmt)\n  | stmt_hyp_stmt (hs : HypothesisStmt)\n  | stmt_assert_stmt (ass : AssertStmt).\n  \n  Inductive OutermostScopeStmt :=\n  | oss_inc (incs : IncludeStmt)\n  | oss_cs (cs : ConstantStmt)\n  | oss_s (st : Stmt)\n  .\n  \n  Definition Database := list OutermostScopeStmt.\n\n  (* Concrete syntax printing. *)\n  \n  Definition IncludeStmt_toString (x : IncludeStmt) :=\n    match x with\n    | include_stmt s => append \"$[ \" (append s \" $]\")\n    end.\n  \n\n  Definition MathSymbol_toString (x : MathSymbol) :=\n    match x with\n    | ms s => s\n    end.\n  \n  Definition Constant_toString (x : Constant) :=\n    match x with\n    | constant s => MathSymbol_toString s\n    end.\n\n  Definition appendWith between x y :=\n    append x (append between y).\n  \n  Definition ConstantStmt_toString (x : ConstantStmt) : string :=\n    match x with\n    | constant_stmt cs => append \"$c \" (append (foldr (appendWith \" \"%string) \"\"%string (map Constant_toString cs)) \" $.\")\n    end.\n  \n  Definition Variabl_toString (x : Variabl) :=\n    match x with\n    | variable s => s\n    end.\n  \n  Definition VariableStmt_toString (x : VariableStmt) : string :=\n    match x with\n    | vs lv => append \"$v \" (append (foldr (appendWith \" \"%string) \"\"%string (map Variabl_toString lv)) \" $.\")\n    end.\n  \n\n  Definition DisjointStmt_toString (x : DisjointStmt) : string :=\n    match x with\n    | ds lv => append \"$d \" (append (foldr (appendWith \" \"%string) \"\"%string (map Variabl_toString lv)) \" $.\")\n    end.\n  \n  Definition TypeCode_toString (x : TypeCode) : string :=\n    match x with\n    | tc c => Constant_toString c\n    end.\n\n  Definition Label_toString (x : Label) : string :=\n    match x with\n    | lbl s => s\n    end.\n\n\n  Definition FloatingStmt_toString (x : FloatingStmt) : string :=\n    match x with\n    | fs l t var => append\n                      (Label_toString l)\n                      (append\n                         \" $f \"\n                         (append\n                            (appendWith \" \" (TypeCode_toString t) (Variabl_toString var))\n                            \" $.\"\n                         )\n                      )\n    end.\n\n    Definition EssentialStmt_toString (x : EssentialStmt) : string :=\n    match x with\n    | es l t lms => append\n                      (Label_toString l)\n                      (append\n                         \" $e \"\n                         (append\n                            (appendWith \" \"\n                               (TypeCode_toString t)\n                               (foldr (appendWith \" \"%string) \"\"%string (map MathSymbol_toString lms))\n                            )\n                            \" $.\"\n                         )\n                      )\n    end.\n\n    Definition HypothesisStmt_toString (x : HypothesisStmt) : string :=\n      match x with\n      | hs_floating f => FloatingStmt_toString f\n      | hs_essential e => EssentialStmt_toString e\n      end.\n\n\n\n    Definition AxiomStmt_toString (x : AxiomStmt) : string :=\n    match x with\n    | axs l t lms => append\n                      (Label_toString l)\n                      (append\n                         \" $a \"\n                         (append\n                            (appendWith \" \"\n                               (TypeCode_toString t)\n                               (foldr (appendWith \" \"%string) \"\"%string (map MathSymbol_toString lms))\n                            )\n                            \" $.\"\n                         )\n                      )\n    end.\n\n    Definition MMProof_toString (x : MMProof) : string :=\n      match x with\n      | pf ll =>  foldr (appendWith \" \"%string) \"\"%string (map Label_toString ll)\n      end.\n\n    Definition ProvableStmt_toString (x : ProvableStmt) : string :=\n      match x with\n      | ps l t lms p\n        => append\n             (Label_toString l)\n             (append\n                \" $p \"\n                (append\n                   (append\n                      (append (TypeCode_toString t) \" \")\n                      (foldr (appendWith \" \"%string) \"\"%string (map MathSymbol_toString lms))\n                   )\n                   (append \" $= \" (append (MMProof_toString p)  \" $.\"))\n                )\n             )\n      end.\n\n    Definition AssertStmt_toString (x : AssertStmt) : string :=\n      match x with\n      | as_axiom astmt => AxiomStmt_toString astmt\n      | as_provable p => ProvableStmt_toString p\n      end.\n\n    Fixpoint Stmt_toString (x : Stmt) : string :=\n      match x with\n      | stmt_block l\n        => append \"${ \"\n                  (append\n                     (foldr (appendWith \" \"%string) \"\"%string (map Stmt_toString l))\n                     \" $}\")\n      | stmt_variable_stmt v => VariableStmt_toString v\n      | stmt_disj_stmt d => DisjointStmt_toString d\n      | stmt_hyp_stmt h => HypothesisStmt_toString h\n      | stmt_assert_stmt astmt => AssertStmt_toString astmt\n      end.\n\n    Definition OutermostScopeStmt_toString (x : OutermostScopeStmt) : string :=\n      match x with\n      | oss_inc i => IncludeStmt_toString i\n      | oss_cs c => ConstantStmt_toString c\n      | oss_s s => Stmt_toString s\n      end.\n\n    Definition Database_toString (x : Database) : string :=\n      foldr (appendWith \"\n\"%string) \"\n\"%string (map OutermostScopeStmt_toString x).\n\n    Fixpoint Private_MathSymbol_from_string (s : string) : string :=\n      match s with\n      | EmptyString => \"\"\n      | String v s' =>\n        let n := nat_of_ascii v in\n        let rest := (Private_MathSymbol_from_string s') in\n        if decide (v = \"$\"%char) then\n          \"\\DLR\" ++ rest\n        else\n          if (decide (v = \"\\\"%char)) then\n            \"\\BSP\" ++ rest\n          else\n            if (decide (v = \" \"%char)) then\n              \"\\SPC\" ++ rest\n            else\n              if (n <? 33) || (126 <? n)\n              then \"$$$GENERATE_SYNTAX_ERROR$$$\" (* TODO metamath can't handle characters in this range *)\n              else\n                String v rest\n      end.\n\n    (*Compute (Private_MathSymbol_from_string \"Ah$oj sve\\te\").*)\n    \n    Definition MathSymbol_from_string (s : string) : MathSymbol :=\n      ms (Private_MathSymbol_from_string s).\n\nEnd MetaMath.\n\nImport MetaMath.\nSection gen.\n  Context\n    {signature : Signature}\n    {symbols_countable : Countable symbols}\n    (symbolPrinter : symbols -> string)\n    (evarPrinter : @evar variables -> string)\n    (svarPrinter : @svar variables -> string)\n  .\n  \n  Definition something (x : evar) := evarPrinter x.\n  \n  Definition constantForSymbol (s : symbols) : OutermostScopeStmt :=\n    oss_cs (constant_stmt [constant (ms (symbolPrinter s))]).\n\n  Definition axiomForSymbol (s : symbols) : OutermostScopeStmt :=\n    oss_s (stmt_assert_stmt (as_axiom (axs\n                                         (lbl (symbolPrinter s ++ \"-is-pattern\"))\n                                         (tc (constant (ms \"#Pattern\")))\n                                         [(ms (symbolPrinter s))]\n          ))).\n\n  Definition constantAndAxiomForSymbol (s : symbols) : Database :=\n    [constantForSymbol s; axiomForSymbol s].\n\n  Definition SymSet := listset_nodup symbols.\n  Definition NEvarSet := listset_nodup evar.\n  Definition NSvarSet := listset_nodup svar.\n\n\n  Fixpoint symbols_of (p : NamedPattern) : SymSet :=\n    match p with\n    | npatt_bott | npatt_evar _ | npatt_svar _ => ∅\n    | npatt_sym s => {[ s ]}\n    | npatt_imp p1 p2 => symbols_of p1 ∪ symbols_of p2\n    | npatt_app p1 p2 => symbols_of p1 ∪ symbols_of p2\n    | npatt_exists _ p' => symbols_of p'\n    | npatt_mu _ p' => symbols_of p'\n    end.\n\n  Fixpoint nevars_of (p : NamedPattern) : NEvarSet :=\n    match p with\n    | npatt_bott | npatt_svar _ | npatt_sym _ => ∅\n    | npatt_evar x => {[x]}\n    | npatt_imp p1 p2 => nevars_of p1 ∪ nevars_of p2\n    | npatt_app p1 p2 => nevars_of p1 ∪ nevars_of p2\n    | npatt_exists x p' => {[x]} ∪ nevars_of p'\n    | npatt_mu _ p' => nevars_of p'\n    end.\n\n  Fixpoint nsvars_of (p : NamedPattern) : NSvarSet :=\n    match p with\n    | npatt_bott | npatt_evar _ | npatt_sym _ => ∅\n    | npatt_svar X => {[X]}\n    | npatt_imp p1 p2 => nsvars_of p1 ∪ nsvars_of p2\n    | npatt_app p1 p2 => nsvars_of p1 ∪ nsvars_of p2\n    | npatt_exists _ p' => nsvars_of p'\n    | npatt_mu X p' => {[X]} ∪ nsvars_of p'\n    end.\n\n  Definition printEvar (x : evar) : string := \"evar-\" ++ (evarPrinter x).\n  Definition isElementVar (x : evar) : Label := lbl ((printEvar x) ++ \"-is-element-var\").\n\n  Definition printSvar (X : svar) : string := \"svar-\" ++ (svarPrinter X).\n  Definition isSetVar (X : svar) : Label := lbl ((printSvar X) ++ \"-is-set-var\").\n  \n  Definition frameAsElementVariable (x : evar) : OutermostScopeStmt :=\n    oss_s (stmt_hyp_stmt (hs_floating\n                            (fs\n                               (isElementVar x)\n                               (tc (constant (ms \"#ElementVariable\")))\n                               (variable (printEvar x))))).\n\n  Definition frameAsSetVariable (X : svar) : OutermostScopeStmt :=\n    oss_s (stmt_hyp_stmt (hs_floating\n                            (fs\n                               (isSetVar X)\n                               (tc (constant (ms \"#SetVariable\")))\n                               (variable (printSvar X))))).\n  \n  Definition dependenciesForPattern (p : NamedPattern) : Database :=\n    let sms := listset_nodup_car (symbols_of p) in\n    let nevs := listset_nodup_car (nevars_of p) in\n    let nsvs := listset_nodup_car (nsvars_of p) in\n    (concat (map constantAndAxiomForSymbol sms))\n      ++ (if decide (0 < length nevs) then\n            [(oss_s (stmt_variable_stmt (vs (map (variable ∘ printEvar) nevs))))]\n          else []\n         )\n      ++ (if decide (0 < length nsvs) then\n            [(oss_s (stmt_variable_stmt (vs (map (variable ∘ printSvar) nsvs))))]\n          else []\n         )\n      ++ (if decide (1 < length nevs) then\n            [(oss_s (stmt_disj_stmt (ds (map (variable ∘ printEvar) nevs))))]\n          else []\n         )\n      ++ (if decide (1 < length nsvs) then\n            [(oss_s (stmt_disj_stmt (ds (map (variable ∘ printSvar) nsvs))))]\n          else []\n         )\n      ++ (map frameAsElementVariable nevs)\n      ++ (map frameAsSetVariable nsvs)\n  .\n\n  Fixpoint pattern2mm (p : NamedPattern) : list MathSymbol :=\n    match p with\n    | npatt_sym s => [ms (symbolPrinter s)] (* TODO: use printSymbol *)\n    | npatt_evar x => [ms (printEvar x)]\n    | npatt_svar X => [ms (printSvar X)]\n    | npatt_imp p1 p2 =>\n      let ms1 := pattern2mm p1 in\n      let ms2 := pattern2mm p2 in\n      [(ms \"(\"); (ms \"\\imp\")] ++ ms1 ++ ms2 ++ [ (ms \")\")]\n    | npatt_app p1 p2 =>\n      let ms1 := pattern2mm p1 in\n      let ms2 := pattern2mm p2 in\n      [(ms \"(\"); (ms \"\\app\")] ++ ms1 ++ ms2 ++ [ (ms \")\")]\n    | npatt_bott => [(ms \"\\bot\")]\n    | npatt_exists x p' =>\n      let msx := [ms (printEvar x)] in\n      let msp' := pattern2mm p' in\n      [(ms \"(\"); (ms \"\\exists\")] ++ msx ++ msp' ++ [(ms \")\")]\n    | npatt_mu X p' =>\n      let msX := [ms (printSvar X)] in\n      let msp' := pattern2mm p' in\n      [(ms \"(\"); (ms \"\\exists\")] ++ msX ++ msp' ++ [(ms \")\")]\n    end.\n\n  Fixpoint pattern2proof (p : NamedPattern) : list Label :=\n    match p with\n    | npatt_sym s => [(lbl (symbolPrinter s ++ \"-is-pattern\"))]\n    | npatt_evar x => [(isElementVar x); (lbl \"element-var-is-var\"); (lbl \"var-is-pattern\")]\n    | npatt_svar X => [(isSetVar X); (lbl \"set-var-is-var\"); (lbl \"var-is-pattern\")]                        \n    | npatt_imp p1 p2 =>\n      let ms1 := pattern2proof p1 in\n      let ms2 := pattern2proof p2 in\n      ms1 ++ ms2 ++ [(lbl \"imp-is-pattern\")]\n    | npatt_app p1 p2 =>\n      let ms1 := pattern2proof p1 in\n      let ms2 := pattern2proof p2 in\n      ms1 ++ ms2 ++ [(lbl \"app-is-pattern\")]\n    | npatt_bott => [(lbl \"bot-is-pattern\")]\n    | npatt_exists x p' =>\n      let lsx := [(isElementVar x)] in\n      let lsp' := pattern2proof p' in\n      lsp' ++ lsx ++ [(lbl \"exists-is-pattern\")]\n    | npatt_mu X p' =>\n      let lsX := [(isSetVar X)] in\n      let lsp' := pattern2proof p' in\n      lsp' ++ lsX ++ [(lbl \"mu-is-pattern\")]\n    end.\n\n  Fixpoint proof_size' Γ (ϕ : Pattern) (pf : ML_proof_system Γ ϕ) : nat :=\n    match pf with\n    | hypothesis _ _ _ _ => 1\n    | P1 _ _ _ _ _ => 1\n    | P2 _ _ _ _ _ _ _ => 1\n    | P3 _ _ _ => 1\n    | Modus_ponens _ _ _ pf1 pf2 => 1 + proof_size' _ _ pf1 + proof_size' _ _ pf2\n    | Ex_quan _ _ _ _ => 1\n    | Ex_gen _ _ _ _ _ _ pf' _ => 1 + proof_size' _ _ pf'\n    | Prop_bott_left _ _ _ => 1\n    | Prop_bott_right _ _ _ => 1\n    | Prop_disj_left _ _ _ _ _ _ _ => 1\n    | Prop_disj_right _ _ _ _ _ _ _ => 1\n    | Prop_ex_left _ _ _ _ _ => 1\n    | Prop_ex_right _ _ _ _ _ => 1\n    | Framing_left _ _ _ _ _ pf' => 1 + proof_size' _ _ pf'\n    | Framing_right _ _ _ _ _ pf' => 1 + proof_size' _ _ pf'\n    | Svar_subst _ _ _ _ _ _ pf' => 1 + proof_size' _ _ pf'\n    | Pre_fixp _ _ _ => 1\n    | Knaster_tarski _ _ _ _ pf' => 1 + proof_size' _ _ pf'\n    | Existence _ => 1\n    | Singleton_ctx _ _ _ _ _ _ => 1\n    end.\n\n  Definition proof_size'' Γ (x : {ϕ : Pattern & ML_proof_system Γ ϕ}) :=\n    proof_size' Γ (projT1 x) (projT2 x).\n\n  Definition proof2proof'_stack Γ := list ({ϕ : Pattern & ML_proof_system Γ ϕ} + Label).\n  \n  Definition proof2proof'_stack_size Γ (s : proof2proof'_stack Γ)\n    := (fold_right\n          plus\n          0\n          (map\n             (fun it =>\n                match it with\n                | inl p => 2 * proof_size'' Γ p\n                | inr _ => 1          \n                end\n             )\n             s\n          )\n       ).\n\n  (* (exists x, x) -> exists x, (exists y, y)  *)\n  (* (exists, 0) -> (exists, exists, 0)  *)\n  (* (exists x, x) -> (phi -> (exists y, y)) *)\n\n  Print Ex_quan.\n\n Equations? proof2proof'\n            Γ\n            (acc : list Label)\n            (pfs : list ({ϕ : Pattern & ML_proof_system Γ ϕ} + Label))\n    : list Label\n    by wf (proof2proof'_stack_size Γ pfs) lt :=\n    \n    proof2proof' Γ acc [] := reverse acc ;\n    \n    proof2proof' Γ acc ((inr l)::pfs')\n      := proof2proof' Γ (l::acc) pfs' ;\n    \n    proof2proof' Γ acc ((inl (existT ϕ (P1 _ p q _ _)))::pfs')\n      := proof2proof'\n           Γ\n           ([lbl \"proof-rule-prop-1\"]\n              ++ (reverse (pattern2proof (to_NamedPattern2 q)))\n              ++ (reverse (pattern2proof (to_NamedPattern2 p)))\n              ++ acc)\n           pfs' ;\n    \n    proof2proof' Γ acc ((inl (existT ϕ (P2 _ p q r _ _ _)))::pfs')\n      := proof2proof'\n           Γ\n           ([lbl \"proof-rule-prop-2\"]\n              ++ (reverse (pattern2proof (to_NamedPattern2 r)))\n              ++ (reverse (pattern2proof (to_NamedPattern2 q)))\n              ++ (reverse (pattern2proof (to_NamedPattern2 p)))\n              ++ acc)\n           pfs' ;\n    \n    proof2proof' Γ acc ((inl (existT ϕ (P3 _ p _)))::pfs')\n      := proof2proof'\n           Γ\n           ([lbl \"proof-rule-prop-3\"]\n              ++ (reverse (pattern2proof (to_NamedPattern2 p)))\n              ++ acc)\n           pfs' ;\n\n    proof2proof' Γ acc ((inl (existT _ (Modus_ponens _ p q pfp pfpiq)))::pfs')\n      := proof2proof'\n           Γ\n           ((reverse (pattern2proof (to_NamedPattern2 q)))\n              ++ (reverse (pattern2proof (to_NamedPattern2 p)))\n              ++ acc)\n           ((inl (existT _ pfpiq))::(inl (existT _ pfp))::(inr (lbl \"proof-rule-mp\"))::pfs') ;\n\n    proof2proof' Γ acc ((inl (existT ϕ (Ex_quan _ p y _)))::pfs')\n      := proof2proof'\n           Γ\n           ([lbl \"proof-rule-exists\"]\n              ++ (reverse (pattern2proof (to_NamedPattern2 (instantiate p (patt_free_evar y)))))\n              ++ (reverse (pattern2proof (to_NamedPattern2 p)))\n              ++ acc)\n           pfs' ;\n\n    proof2proof' Γ prefix ((inl _)::_) := []\n  .\n  Proof.\n    - unfold proof2proof'_stack_size. simpl. lia.\n    - unfold proof2proof'_stack_size. simpl. lia.\n    - unfold proof2proof'_stack_size. simpl. lia.\n    - unfold proof2proof'_stack_size.\n      rewrite !map_cons. simpl.\n      unfold proof_size''. simpl.\n      simpl.\n      remember (proof_size' Γ (patt_imp p q) pfpiq) as A.\n      remember (proof_size' Γ p pfp) as B.\n      remember ((foldr Init.Nat.add 0\n                       (map\n                          (λ it : {ϕ : Pattern & ML_proof_system Γ ϕ} + Label,\n                                  match it with\n                                  | inl p0 => proof_size' Γ (projT1 p0) (projT2 p0) + (proof_size' Γ (projT1 p0) (projT2 p0) + 0)\n                                  | inr _ => 1\n                                  end) pfs'))) as C.\n      lia.\n    - unfold proof2proof'_stack_size. simpl. lia.\n    - unfold proof2proof'_stack_size. simpl. lia.\n  Defined.\n\n  Definition proof2proof Γ (ϕ : Pattern) (pf : ML_proof_system Γ ϕ) : list Label :=\n    proof2proof' Γ [] [(inl (existT ϕ pf))].\n  \n  \n  (*\n  Fixpoint proof2proof (Γ : Theory) (ϕ : Pattern) (pf : ML_proof_system Γ ϕ) : list Label :=\n    match pf as _ return list Label with\n    | P1 _ p q wfp wfq => pattern2proof p ++ pattern2proof q ++ [lbl \"proof-rule-prop-1\"]\n    | P2 _ p q r wfp wfq wfr =>\n      pattern2proof p ++ pattern2proof q ++ pattern2proof r ++ [lbl \"proof-rule-prop-2\"]\n    | P3 _ p wfp => pattern2proof p ++ [lbl \"proof-rule-prop-3\"]\n    | Modus_ponens _ p q wfp wfpiq pfp pfpiq =>\n      (pattern2proof p)\n        ++ (pattern2proof q)\n        ++ (proof2proof Γ _ pfpiq)\n        ++ (proof2proof Γ _ pfp)\n        ++ [lbl \"proof-rule-mp\"]\n    | _ => []\n    end.\n   *)\n  \n  Definition proof2database Γ (ϕ : Pattern) (proof : ML_proof_system Γ ϕ) : Database :=\n    let named := to_NamedPattern2 ϕ in\n    [oss_inc (include_stmt \"mm/matching-logic.mm\")] ++\n    (dependenciesForPattern named)\n      ++ [oss_s (stmt_assert_stmt (as_provable (ps\n                                                  (lbl \"the-proof\")\n                                                  (tc (constant (ms \"|-\")))\n                                                  (pattern2mm named)\n                                                  (pf (proof2proof Γ ϕ proof))\n         )))].\n  \n  \nEnd gen.\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/MMProofExtractor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.29355731834207455}}
{"text": "(******************************************************************************\nSeptember 2004\nAuthors: Jean-Yves Vion-dury and Pierre Geneves \n\njean-yves.vion-dury@xrce.xerox.com\nWAM Research Project, INRIA Rhone-Alpes and Xerox Research Center Europe\n\npierre.geneves@inrialpes.fr\nWAM Research Project, INRIA Rhone-Alpes\n\nPlease do not reuse or publish this code without explicit consent from authors.\n*******************************************************************************)\nRequire Import setOrder.\nRequire Export XPath.\nRequire Import xnodes.\nRequire Import XPathInduction.\n(* Require XPathBasicProp.*)\nRequire Import Mapping.\nRequire Import graphInt.\nRequire Export nat_basics.\nRequire Import XPequiv.\n\nRequire Import XPathGrammar.\n\n(* ========================================================================================*)\n(* This part defines all axioms of the theory in two mutually inductive definitions        *)\n(*\tthis allows usefull inversions (see Inversion tactic)                              *)\n(* ========================================================================================*)\n \nInductive Qualif : XPath -> Prop :=\n    is_qualif : forall (p : XPath) (q : XQualif), Qualif (qualif p q).\n\n\n\nInductive Ple : XPath -> XPath -> Prop :=\n \n  (* basics *)\n  | p_void : forall p : XPath, Ple void p\n  | p_top : Ple top top\n  \n  (* -------- step comparison ------------- *)\n      \n  | p_step :\n      forall (a1 a2 : Axis) (n1 n2 : NodeTest),\n      axis_le a1 a2 ->\n      ntest_le a2 n1 n2 ->\n      Ple (a1:::n1) (a2:::n2)\n      \n      (* ---- slash based rules ------ *)\n      \n| p_desc :\n      forall (p1 p2 : XPath) (n2 : NodeTest) (q:XQualif),\n      Ple p1 (descendant:::%node()) ->\n      Ple p2 (qualif (descendant:::n2) q) ->\n      Ple (p1/p2) (qualif (descendant:::n2) q)\n      \n      (* -------- relative-absolute absolute comparisons -------------------------- *)\n  | p_abs:\n\tforall (p : XPath) (q1 q2:XQualif) (n2 : NodeTest),\n\tQipl (path (descendant:::%node()/p)) q1 ->\n\tPle p (qualif (descendant:::n2) q2)  ->\n\tPle p ((qualif top q1)/(qualif (descendant:::n2) q2))\n      (* ----------- *)\n|  p_slash :\n      forall p11 p12 p21 p22 : XPath,      \n      Ple (qualif p11 (#p12))   (qualif p21 (#p22)) ->\n      Ple p12 p22 ->\n      Ple (p11/p12) (p21/p22)\n\n\n      \n      (* ------- intersection rules -------- *)\n  | p_inter_R:\n      forall p1 p2 p : XPath,\n      Ple p p1 ->\n      Ple p p2 ->\n      Ple p (inter p1 p2)\n  | p_inter_L:\n      forall p1 p2 p : XPath,\n      Ple p1 p ->\n      Ple (inter p1 p2) p\n      \n      (* ------- union rules -------- *) \n  | p_union_L :\n      forall p11 p12 p2 : XPath,\n      Ple p11 p2 -> Ple p12 p2 -> Ple (union p11 p12) p2\n\n  | p_union_R :\n      forall p1 p21 p22 : XPath,\n      Ple p1 p21 -> Ple p1 (union p21 p22)\n      \n      (* -------- qualif comparison ------------- *)\n  | p_qual :\n      forall p1 p2 : XPath,\n      forall q1 q2 : XQualif,\n      Ple p1 p2 -> Qipl q1 q2 -> Ple (qualif p1 q1) (qualif p2 q2)\n\n\n \n          \nwith Qipl : XQualif -> XQualif -> Prop :=\n\n  | q_leq (* e1 *) :\n      forall p11 p12 p21 p22 : XPath,\n      Ple p21 p11 -> Ple p12 p22 -> Qipl (leq p11 p12) (leq p21 p22)\n\n  | q_not (* e2 *): \n      forall q1 q2 : XQualif, Qipl q2 q1 -> Qipl (not q1) (not q2)\n\n  | q_true (* e3a *) : \n      forall q : XQualif, Qipl q _true\n\n  | q_false (* e3b *) : \n      forall q : XQualif, Qipl _false q\n\n  | q_and_L (* e4 *) : \n      forall q11 q12 q2 : XQualif, \n      Qipl q11 q2 -> Qipl (q11 and q12) q2\n\n  | q_and_R (* e5 *) :\n      forall q1 q21 q22 : XQualif,\n      Qipl q1 q21 -> Qipl q1 q22 -> \n      Qipl q1 (q21 and q22)\n\n  | q_or_R (* e6 *) : \n      forall q1 q21 q22 : XQualif, \n      Qipl q1 q21 -> \n      Qipl q1 (q21 or q22)\n\n  | q_or_L (* e7 *) :\n      forall q11 q12 q2 : XQualif,\n      Qipl q11 q2 -> Qipl q12 q2 ->\n      Qipl (q11 or q12) q2\n\n(*      \n  | f2 :\n      forall (p1 p2 : XPath) (q1 q2 : XQualif),\n      Qipl (leq p1 void) (leq p2 void) ->\n      Qipl (leq (qualif p1 q1) void) (leq (qualif p2 q2) void)\n  | f3 :\n      forall (p1 p2 : XPath) (q1 q2 : XQualif),\n      Ple p1 p2 ->\n      Qipl (not q1) (not q2) ->\n      Qipl (leq (qualif p1 q1) void) (leq (qualif p2 q2) void)\n*)\n  | q_child_desc (* f4 *) :\n      forall nt : NodeTest,\n\t(ntest_le descendant nt _element) ->\n      Qipl (leq (step child _any) void) (leq (step descendant nt) void)\n      \n  \n      (* the corresponding propositional equality *)\nwith Peq : XPath -> XPath -> Prop :=\n\n  |  p_eq : forall p1 p2 : XPath, Ple p1 p2 -> Ple p2 p1 -> Peq p1 p2\n.\n\n \n     \n\n\nNotation \"p1 ≤ p2\" := (Ple p1 p2) (at level 90, no associativity) : Xrel.\nNotation \"q1 ⇨ q2\" := (Qipl q1 q2) (at level 90, no associativity) : Xrel.\nNotation \"p1 ≈ p2\" := (Peq p1 p2) (at level 90, no associativity) : Xrel.\n\n\nOpen Scope Xp.\nOpen Scope Xrel.\n\n (*======= generic usage of equiv ======= *)\nAxiom p_gene_L  :\n      forall p1 p3:XPath,\n      (exists p2:XPath,   (p1 ⇾ p2)    /\\   ( p2 ≤ p3) ) ->\n      p1 ≤ p3\n      .\n\nAxiom p_gene_R  : \n      forall p1 p3:XPath,\n      (exists p2:XPath,   (p3 ⇾ p2)   /\\    (p1 ≤ p2) ) ->\n      p1 ≤ p3\n\t.\n\nAxiom q_gene_L : \n      forall q1 q3:XQualif,\n      (exists q2:XQualif, (q1 ⇐⇒ q2)   /\\   (q2 ⇨ q3) ) ->\n      q1 ⇨ q3\n\t.\n      \nAxiom q_gene_R :\n      forall q1 q3:XQualif,\n      (exists q2:XQualif,  (q3 ⇐⇒ q2)  /\\  (q1 ⇨ q2) ) ->      \n      q1 ⇨ q3\n\t.\n     \nDefinition ple_reflexive (p1 p2:XPath):Prop :=     p1=p2 -> p1 ≤ p2.\nDefinition qipl_reflexive (q1 q2:XQualif):Prop :=  q1=q2 -> q1 ⇨ q2.\n\nLtac t1 :=\n   match goal with  IHn1:_ |- _ =>\n   simpl in |- *;\n     intro p2; case p2; simpl in |- *;\n     [\n\t   intro; apply IHn1;auto with arith\n\t | intro; apply IHn1; auto with arith\n\t | intros; unfold ple_reflexive in |- *; intros; discriminate\n\t | intros; unfold ple_reflexive in |- *; intros; discriminate\n\t | intros; unfold ple_reflexive in |- *; intros; discriminate\n\t | intros; unfold ple_reflexive in |- *; intros; discriminate\n\t | intros; unfold ple_reflexive in |- *; intros; discriminate\n\t ]\n     end.\n\nLtac redMax H :=\n  LeS;\n  rewrite max_idem in H;\n  rewrite max_idem;\n      apply H \n  ||  (match goal with  \n      H:max ?a ?b <= ?n |- ?a <= ?n  => eapply max_le_L\n      |  H:max ?a ?b <= ?n |- ?b  <= ?n  => eapply max_le_R\n     end;apply H)\n  .\n\n\nLemma Ple_Qipl_reflexive:\n    (forall p1 p2:XPath, (ple_reflexive p1 p2)) /\\\n    (forall q1 q2:XQualif, (qipl_reflexive q1 q2)).\n\napply HGen22.\ninduction n.\n (* base cases *)\n simpl in |- *.\n   unfold Hyp22 in |- *.\n   split.\n  intros p1 p2; case p1; case p2; intros;\n   match goal with\n   | H:(_ <= 0) |- _ => inversion H\n   end.\n   unfold ple_reflexive in |- *; intros; constructor.\n   unfold ple_reflexive in |- *; intros; discriminate.\n   unfold ple_reflexive in |- *; intros; discriminate.\n   unfold ple_reflexive in |- *; intros; constructor.\n   \n  intros q1 q2; case q1; case q2; intros;\n   match goal with\n   | H:(_ <= 0) |- _ => inversion H\n   end.\n   unfold qipl_reflexive in |- *; intros; constructor.\n   unfold qipl_reflexive in |- *; intros; discriminate.\n   unfold qipl_reflexive in |- *; intros; discriminate.\n   unfold qipl_reflexive in |- *; intros; constructor.\n   \n(* Inductive step *)   \nunfold Hyp22 in IHn |- *.\n   elim IHn; intros IHn1 IHn2.\n   clear IHn.\n   split.\n(* ---- path *)\n  intro p1; case p1.\n   (* void p2 *)\n   t1.\n   (* top p2 *)\n   t1.\n   (* union p2 *)\n   unfold ple_reflexive in |- *.\n   intros.\n   rewrite <- H0.\n   rewrite <- H0 in H.\n   simpl in H.\n   apply p_union_L; [ apply p_union_R | apply p_gene_R;exists (union x0 x);split;[apply red_gen;rewrite Pequiv_symmetric | apply p_union_R ] ].\n    (* Ple x x *)\n    apply IHn1;[redMax H | reflexivity].\n    constructor.\n    (* Ple x0 x0 *)\n    apply IHn1;[redMax H | reflexivity].\n   (* inter p2 *)\n   unfold ple_reflexive in |- *.\n   intros.\n   rewrite <- H0.\n   rewrite <- H0 in H.\n   simpl in H.\n  apply p_inter_R;[apply p_inter_L | apply p_gene_L;exists (inter x0 x);split;[apply red_gen;rewrite Pequiv_symmetric | apply p_inter_L] ].\n\n  apply IHn1;[redMax H | reflexivity].\n  constructor.\n  apply IHn1;[redMax H | reflexivity].\n \n (* slash p2 *)\n  unfold ple_reflexive in |- *.\n   intros.\n   rewrite <- H0.\n   rewrite <- H0 in H.\n   simpl in H.\n  apply p_slash.\n  constructor.\n  apply IHn1;[redMax H | reflexivity].\n  unfold path;constructor;constructor.\n  apply IHn1;[redMax H | reflexivity].\n  constructor.\n  apply IHn1;[redMax H | reflexivity].\n\n   (* qualif p2 *)\n unfold ple_reflexive in |- *.\n   intros.\n  rewrite <- H0.\n   rewrite <- H0 in H.\n  simpl in H.\n  apply p_qual;[apply IHn1 | apply IHn2];redMax H || reflexivity.\n\n   (* step p2 *)\nunfold ple_reflexive in |- *.\n   intros.\n  rewrite <- H0.\n   rewrite <- H0 in H.\n  simpl in H.\n constructor.\n   case a;simpl;trivial.\n   case n0;simpl;trivial.\n  (* ------ qualifiers *)\n  intros q1 q2;case q1;unfold qipl_reflexive; intros;inversion H0;rewrite <- H0 in H;clear H0 H1;simpl in H. \n (* not *)\n constructor;\n apply IHn2;[redMax H | reflexivity].\n (* and *)\n  apply q_and_R;[apply q_and_L | apply q_gene_L].\n  apply IHn2;[redMax H | reflexivity].\n exists (x0 and x);split;constructor.\n  apply IHn2;[redMax H | reflexivity].\n(* or *)\napply q_or_L;[apply q_or_R | apply q_gene_R].\n  apply IHn2; [redMax H | reflexivity].\n exists (x0 or x);split;[constructor | apply q_or_R ].\n  apply IHn2; [redMax H | reflexivity].\n\n (* leq *)\nconstructor.\n   apply IHn1;[redMax H| reflexivity].\n   apply IHn1;[redMax H| reflexivity].\n(* _true *)\nconstructor.\n (* _false *)\nconstructor.\nQed.\n\n\nTheorem Ple_reflexive: forall p:XPath, p ≤ p.\nassert (H:= Ple_Qipl_reflexive).\nelim H;intros H1 H2 p;apply H1.\nreflexivity.\nQed.\n\nTheorem Qipl_reflexive: forall q:XQualif, q ⇨ q.\nassert (H:= Ple_Qipl_reflexive).\nelim H;intros H1 H2 q;apply H2.\nreflexivity.\nQed.\n\n\nConjecture Ple_transitive: forall p1 p2 p3:XPath, p1 ≤ p2  ->  p2 ≤ p3  ->  p1 ≤ p3.\n\n(* I don't known if this proof has any value...seems too much regular *)\nLemma equiv_eq_sound:\n    forall p1 p2:XPath,\n    (p1 ⇽⇾ p2)  ->  p1 ≈ p2\n    .\nintros p1 p2 H.\ninversion H;\nmatch goal with \n  |- ?a ≈ ?b => \n  split;[ apply p_gene_L | apply p_gene_R];\n  exists b;(split;[apply red_gen;constructor | apply Ple_reflexive ]);trivial\nend.\nQed.\n\n\n\n\n\n", "meta": {"author": "mattam82", "repo": "typex", "sha": "37a01ce082e63a304fddadbc60ec281057fa6e1a", "save_path": "github-repos/coq/mattam82-typex", "path": "github-repos/coq/mattam82-typex/typex-37a01ce082e63a304fddadbc60ec281057fa6e1a/theories/XPath/SXPath/Containment/XPCAxioms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.29355731834207455}}
{"text": "Require Import Metalib.Metatheory.\nRequire Import Metalib.LibTactics.\nRequire Import Coq.Program.Equality.\nRequire Import Coq.Program.Tactics.\nRequire Import Strings.String.\nRequire Import Lia.\n\nRequire Import Language.\nRequire Import Tactical.\nRequire Import Subtyping.Subtyping.\nRequire Import Subtyping.Splitable.\nRequire Import Subtyping.Toplike.\nRequire Import Subtyping.Unisub.\nRequire Import Appsub.\n\nRequire Import Value.\nRequire Import Disjoint.\nRequire Import PrincipalTyping.\nRequire Import Consistent.\nRequire Import Typing.\nRequire Import Casting.\nRequire Import LocallyNameless.\nRequire Import Application.\n\n(** * Definition *)\n\nInductive step : term -> term -> Prop :=\n| St_Lit : forall n,\n    step (Lit n) (Ann (Lit n) Int)\n| St_Lam : forall e A B,\n    step (Lam A e B) (Ann (Lam A e B) (Arr A B))\n| St_Spl : forall p A A1 A2,\n    pvalue p ->\n    splitable A A1 A2 ->\n    step (Ann p A) (Mrg (Ann p A1) (Ann p A2))\n| St_App : forall f v e,\n    value f -> value v ->\n    papp f (Av v) e ->\n    step (App f v) e\n| St_Prj : forall l v e,\n    value v ->\n    papp v (Al l) e ->\n    step (Prj v l) e    \n| St_Val : forall v v' A,\n    value v ->\n    casting v A v' ->\n    step (Ann v A) v'\n| St_Ann : forall e e' A,\n    not (pvalue e) ->\n    step e e' ->\n    step (Ann e A) (Ann e' A)\n| St_App_L : forall e1 e1' e2,\n    lc e2 ->\n    step e1 e1' ->\n    step (App e1 e2) (App e1' e2)\n| St_App_R : forall v e2 e2',\n    value v ->\n    step e2 e2' ->\n    step (App v e2) (App v e2')\n| St_Rcd : forall l e e',\n    step e e' ->\n    step (Fld l e) (Fld l e')\n| St_Prj_L : forall e e' l,\n    step e e' ->\n    step (Prj e l) (Prj e' l)\n| St_Mrg : forall e1 e1' e2 e2',\n    step e1 e1' ->\n    step e2 e2' ->\n    step (Mrg e1 e2) (Mrg e1' e2')         \n| St_Mrg_L : forall e1 v e1',\n    value v ->\n    step e1 e1' ->\n    step (Mrg e1 v) (Mrg e1' v)\n| St_Mrg_R : forall v e2 e2',\n    value v ->\n    step e2 e2' ->\n    step (Mrg v e2) (Mrg v e2').\n\nHint Constructors step : core.\n\nNotation \"e ⟾ e'\" := (step e e') (at level 68).\n\n(** * Value *)\n\nLemma value_no_step :\n  forall v,\n    value v -> forall e, ~ step v e.\nProof.\n  introv Val.\n  induction v; intros; eauto.\n  - intros St.\n    dependent destruction Val. dependent destruction St; eauto.\n    + eapply IHv1; eauto.\n    + eapply IHv1; eauto.\n    + eapply IHv2; eauto.\n  - dependent destruction Val.\n    destruct H.\n    + intros St. dependent destruction St; eauto.\n    + intros St. dependent destruction St; eauto.\n  - intros St.\n    dependent destruction St.\n    dependent destruction Val.\n    pose proof (IHv Val e'). contradiction.\nQed.\n\nLemma step_lc :\n  forall e e',\n    lc e -> step e e' -> lc e'.\nProof.\n  introv Lc St. gen e'.\n  induction Lc; intros;\n    try solve [dependent destruction St; eauto 3].\n  - dependent destruction St. eapply Lc_Ann. eapply Lc_Lam; eauto.\n  - Case \"App\".\n    dependent destruction St; try solve [econstructor; eauto].\n    pose proof (papp_lc_v e1 e2 e). eauto 3.\n  - dependent destruction St; econstructor; eauto.\n  - dependent destruction St.\n    + econstructor; eapply Lc_Ann; eapply lc_pvalue; eauto.\n    + eapply casting_lc; eauto.\n    + econstructor. eauto.\n  - dependent destruction St. econstructor. eauto.\n  - Case \"Prj\".\n    dependent destruction St; try solve [econstructor; eauto].\n    pose proof (papp_lc_l e l e0). eauto 3.\nQed.\n\nLemma step_uvalue :\n  forall u u',\n    uvalue u -> step u u' -> uvalue u'.\nProof.\n  introv Uv St. gen u'.\n  induction Uv; intros.\n  - dependent destruction St; eauto.\n    eapply Uv_Ann. eapply step_lc; eauto.\n  - dependent destruction St; eauto.\n  - dependent destruction St; eauto.\nQed.\n\nHint Resolve step_uvalue : core.\n\n(** * Determinism *)\n\nSection determinism.\n\nLtac solver1 := try solve [match goal with\n                           | [Val: value ?v, St: step ?v _ |- _] =>\n                               (pose proof (value_no_step _ Val _ St); contradiction)\n                           end].\n\nTheorem determinism:\n  forall e e1 e2 A,\n    typing nil e Inf A ->\n    step e e1 -> step e e2 -> e1 = e2.\nProof.\n  introv Typ St1 St2. gen e2 A.\n  dependent induction St1; intros.\n  - dependent destruction St2; eauto.\n  - dependent destruction St2; eauto.\n  - dependent destruction St2; eauto.\n    subst_splitable. reflexivity.\n  - dependent destruction St2; solver1.\n    dependent destruction Typ.\n    pose proof (papp_determinism_v f v e e0).\n    eapply uunisub_sound_appsub in H5; eauto.\n  - dependent destruction St2; solver1.\n    dependent destruction Typ.\n    pose proof (papp_determinism_l v l e e0).\n    eapply uunisub_sound_appsub in H3; eauto.\n  - dependent destruction St2; eauto; solver1.\n    dependent destruction Typ.\n    dependent destruction Typ.\n    eapply casting_determinism; eauto.\n  - dependent destruction St2; eauto; solver1.\n    f_equal. dependent destruction Typ.\n    dependent destruction Typ; eauto.\n  - dependent destruction St2; solver1.\n    f_equal. dependent destruction Typ; eauto.\n  - dependent destruction St2; solver1.\n    f_equal. dependent destruction Typ; eauto.\n  - dependent destruction St2; solver1.\n    dependent destruction Typ;\n      f_equal; eauto.\n  - dependent destruction St2; solver1.\n    dependent destruction Typ;\n      f_equal; eauto.\n  - dependent destruction St2; solver1.\n    dependent destruction Typ;\n      f_equal; eauto.\n  - dependent destruction St2; solver1.\n    dependent destruction Typ;\n      f_equal; eauto.\n  - dependent destruction St2; solver1.\n    dependent destruction Typ;\n      f_equal; eauto.\nQed.\n\nEnd determinism.\n\n(** * Consistent *)\n\nInductive step_or_value : term -> term -> Prop :=\n| Sv_V : forall v, value v -> step_or_value v v\n| Sv_S : forall e1 e2, step e1 e2 -> step_or_value e1 e2.\n\nHint Constructors step_or_value : core.\n\nLemma size_term_lg_z :\n  forall e, size_term e > 0.\nProof.\n  introv.\n  dependent induction e; try solve [eauto | simpl; lia].\nQed.\n\nHint Resolve size_term_lg_z : core.\n\nLemma size_term_lg_z_any1 :\n  forall e1 e2,\n    size_term e1 < (size_term e2 + size_term e1).\nProof.\n  introv.\n  assert (size_term e2 > 0). eapply size_term_lg_z.\n  lia.\nQed.\n\nLemma size_term_lg_z_any2 :\n  forall e1 e2,\n    size_term e1 < (size_term e1 + size_term e2).\nProof.\n  introv.\n  assert (size_term e2 > 0). eapply size_term_lg_z.\n  lia.\nQed.\n\nHint Resolve size_term_lg_z_any1 : core.\nHint Resolve size_term_lg_z_any2 : core.\n\nSection step_consistent.\n\nLtac solver1 := match goal with\n                | [St: step (Ann (Lam _ _ _) _) _ |- _] => (dependent destruction St; eauto)\n                end.\n\nLtac solver2 := match goal with\n                | [St: step (Ann _ _) _ |- _] => (dependent destruction St; eauto)\n                end.\n\nLtac solver3 := match goal with\n                | [Val: value ?v, St: step ?v _ |- _] =>\n                    (pose proof (value_no_step _ Val _ St); contradiction)\n                end.\n\nLtac solver4 IHC IH :=\n  eapply IHC; eauto; intros; match goal with\n                             | St: step ?e ?e' |- _ => eapply (IH e e'); eauto; simpl; lia\n                             end.\n\nLemma step_consistent :\n  forall e1 e2 e1' e2' A B,\n    uvalue e1 -> uvalue e2 ->\n    typing nil e1 Inf A -> typing nil e2 Inf B ->\n    consistent e1 e2 ->\n    step_or_value e1 e1' -> step_or_value e2 e2' ->\n    (forall e e' A, size_term e < (size_term e1 + size_term e2) ->\n        typing nil e Inf A -> step e e' -> (exists C, typing nil e' Inf C /\\ isosub C A)) ->\n    consistent e1' e2'.\nProof.\n  introv Uv1 Uv2 Typ1 Typ2 Con Sv1 Sv2 IH. gen A B e1' e2'.\n  dependent induction Con; intros; eauto.\n  - Case \"Lam Lam\".\n    dependent destruction Sv1; dependent destruction Sv2; eauto; try solve [solver1].\n    dependent destruction Typ1. dependent destruction Typ2.\n    solver1. solver1. eapply Con_Mrg_L; eauto.\n  - Case \"Anno Anno\".\n    dependent destruction Sv1; dependent destruction Sv2; eauto; try solve [solver2].\n    dependent destruction Typ1. dependent destruction Typ2.\n    solver2.\n    * solver2. eapply Con_Mrg_L; eauto.\n    * solver2; try solve [solver3].\n      dependent destruction Typ1.\n      pose proof (casting_preservation e v' B0 A) as Cp1.\n      dependent destruction Typ2.\n      pose proof (casting_preservation e v'0 B A0) as Cp2.\n      destruct Cp1; destruct Cp2; eauto. destruct_conjs.\n      eapply casting_consistent; eauto.      \n    * solver2; try solve [solver3].\n      dependent destruction Typ1. dependent destruction Typ2.\n      assert (e' = e'0). eapply determinism; eauto. subst. econstructor; eauto.\n      eapply step_lc; eauto.\n  - Case \"Rcd Rcd\".\n    dependent destruction Uv1. dependent destruction Uv2.\n    dependent destruction Typ1. dependent destruction Typ2.\n    dependent destruction Sv1; dependent destruction Sv2; eauto.\n    + match goal with\n      | St: step _ _, Val: value (Fld _ _) |- _ => dependent destruction St; dependent destruction Val\n      end.\n      eapply Con_Rcd. eapply IHCon; eauto 3. intros. eapply (IH e e'0); eauto. simpl in *. lia.\n    + match goal with\n      | St: step _ _, Val: value (Fld _ _) |- _ => dependent destruction St; dependent destruction Val\n      end.\n      eapply Con_Rcd. eapply IHCon; eauto 3. intros. eapply (IH e e'0); eauto. simpl in *. lia.\n    + match goal with\n      | St1: step _ _, St2: step _ _ |- _ => dependent destruction St1; dependent destruction St2\n      end.\n      eapply Con_Rcd. eapply IHCon; eauto 3. intros. eapply (IH e e'1); eauto. simpl in *. lia.\n  - Case \"Disjoint\".    \n    dependent destruction Sv1; dependent destruction Sv2; eauto.\n    + pose proof (step_uvalue _ _ Uv2 H3).\n      eapply IH in H3; eauto; try lia.\n      destruct H3 as [x Typ]; destruct Typ as [Typ Isub].\n      eapply typing_to_ptype in Typ; eauto.\n      eapply typing_to_ptype in Typ2; eauto. subst_ptype.\n      eapply Con_Dj; eauto. eapply disjoint_iso_l; eauto.\n    + pose proof (step_uvalue _ _ Uv1 H2).\n      eapply IH in H2; eauto; try lia.\n      destruct H2 as [x Typ]; destruct Typ as [Typ Isub].\n      eapply typing_to_ptype in Typ; eauto.\n      eapply typing_to_ptype in Typ1; eauto. subst_ptype.\n      eapply Con_Dj; eauto. eapply disjoint_iso_l; eauto.\n    + pose proof (step_uvalue _ _ Uv1 H2).\n      pose proof (step_uvalue _ _ Uv2 H3).\n      eapply IH in H2; eauto; try lia.\n      eapply IH in H3; eauto; try lia.\n      destruct_conjs.\n      eapply typing_to_ptype in Typ1; eauto.\n      eapply typing_to_ptype in Typ2; eauto. repeat subst_ptype.\n      eapply Con_Dj; eauto. eapply disjoint_iso_l; eauto.\n  - Case \"Merge L\".\n    dependent destruction Sv1; eauto 3.\n    + dependent destruction Typ1;\n        eapply Con_Mrg_L; try solve [solver4 IHCon1 IH | solver4 IHCon2 IH].\n    + dependent destruction Typ1;\n        match goal with\n        | St: step (Mrg _ _) _ |- _ => dependent destruction St\n        end; eapply Con_Mrg_L; try solve [solver4 IHCon1 IH | solver4 IHCon2 IH].\n  - Case \"Merge R\".\n    dependent destruction Sv2; eauto 3.\n    + dependent destruction Typ2;\n        eapply Con_Mrg_R; try solve [solver4 IHCon1 IH | solver4 IHCon2 IH].\n    + dependent destruction Typ2;\n        match goal with\n        | St: step (Mrg _ _) _ |- _ => dependent destruction St\n        end; eapply Con_Mrg_R; try solve [solver4 IHCon1 IH | solver4 IHCon2 IH].\nQed.\n    \nEnd step_consistent.\n\n(** * Preservation *)\n\nLtac ind_term_size s :=\n  assert (SizeInd: exists i, s < i) by eauto;\n  destruct SizeInd as [i SizeInd];\n  repeat match goal with | [ h : term |- _ ] => (gen h) end;\n  induction i as [|i IH]; [\n      intros; match goal with | [ H : _ < 0 |- _ ] => (dependent destruction H) end\n    | intros ].\n\nTheorem preservation :\n  forall e e' A,\n    typing nil e Inf A ->\n    step e e' ->\n    (exists B, typing nil e' Inf B /\\ isosub B A).\nProof.\n  introv Typ St. gen e' A.\n  ind_term_size (size_term e). (* shelved item *)\n  dependent destruction Typ; simpl in SizeInd.\n  - Case \"Lit\".\n    dependent destruction St; eauto.\n    exists Int; eauto.\n  - Case \"Var\".\n    dependent destruction St.\n  - Case \"Lam\".\n    dependent destruction St; eauto.\n    exists (Arr A B). split; eauto.\n  - Case \"Rcd\".\n    dependent destruction St; eauto.\n    exploit (IH e); eauto; try lia. intros IH'. destruct_conjs.\n    eexists. split; eauto.\n  - Case \"Ann\".\n    dependent destruction St.\n    + SCase \"Split\".\n      dependent destruction Typ.\n      exists (And A1 A2). split; eauto.\n      pose proof (sub_inv_splitable_r A B A1 A2) as Sub. destruct Sub; eauto.\n      eapply Ty_Mrg_Uv; eauto.\n    + SCase \"Value\".\n      dependent destruction Typ.\n      eapply casting_preservation; eauto.\n    + SCase \"Ann\".\n      dependent destruction Typ.\n      eapply IH in St; eauto; try lia.\n      destruct St as [C Typ']. destruct Typ' as [Typ'1 Typ'2].\n      pose proof (isosub_to_sub1 _ _ Typ'2).\n      exists B. split; eauto. eapply Ty_Ann; eauto; try solve [eapply sub_transitivity; eauto].\n      eapply Ty_Sub; eauto. eapply sub_transitivity; eauto.     \n  - Case \"App\".\n    dependent destruction St.\n    + pose proof (papp_preservation_v e1 e2 e) as P.\n      eapply P; eauto. now eapply uunisub_sound_appsub.\n    + eapply IH in St; eauto; try lia. destruct_conjs.\n      eapply uunisub_sound_appsub in H0.\n      eapply appsub_iso_v in H0; eauto. destruct_conjs.\n      eapply uunisub_complete_appsub in H3.\n      eexists; eauto.\n    + eapply IH in St; eauto; try lia. destruct_conjs.\n      eapply uunisub_sound_appsub in H0.\n      eapply appsub_iso_v in H0; eauto. destruct_conjs.\n      eapply uunisub_complete_appsub in H3.\n      eexists; eauto.\n  - Case \"Prj\".\n    dependent destruction St.\n    + eapply uunisub_sound_appsub in H1.\n      pose proof (papp_preservation_l e l e0) as P.\n      eapply P; eauto.\n    + eapply uunisub_sound_appsub in H.\n      eapply IH in St; eauto; try lia. destruct_conjs.\n      eapply appsub_iso_l in H; eauto. destruct_conjs.\n      eapply uunisub_complete_appsub in H2.\n      eexists; eauto.\n  - Case \"Merge\".\n    dependent destruction St.\n    + eapply IH in St1; eauto; try lia.\n      eapply IH in St2; eauto; try lia. destruct_conjs.      \n      eapply disjoint_iso_l in H; eauto.\n    + eapply IH in St; eauto; try lia. destruct_conjs.\n      eapply disjoint_iso_l in H0; eauto.\n    + eapply IH in St; eauto; try lia. destruct_conjs.\n      eapply disjoint_iso_l in H0; eauto.\n  - Case \"Merge U\".\n    dependent destruction St.    \n    + (* TODO: Automation *)\n      assert (exists C, (typing nil e1' Inf C) /\\ (isosub C A)) by (eapply IH; eauto; lia).\n      assert (exists C, (typing nil e2' Inf C) /\\ (isosub C B)) by (eapply IH; eauto; lia).\n      destruct_conjs. exists (And H3 H4).\n      pose proof (step_uvalue _ _ H0 St1).\n      pose proof (step_uvalue _ _ H1 St2).\n      split; eauto. eapply Ty_Mrg_Uv; eauto.\n      pose proof (Sv_S _ _ St1) as Sov1.\n      pose proof (Sv_S _ _ St2) as Sov2.\n      pose proof (step_consistent u1 u2 e1' e2' A B H0 H1 Typ1 Typ2 H2 Sov1 Sov2) as Sc.\n      eapply Sc. intros. eapply IH; eauto. lia.\n    + assert (exists C, (typing nil e1' Inf C) /\\ (isosub C A)) by (eapply IH; eauto; lia).\n      destruct_conjs. exists (And H4 B).\n      pose proof (step_uvalue _ _ H1 St).\n      split; eauto. eapply Ty_Mrg_Uv; eauto.\n      pose proof (Sv_S _ _ St) as Sov1.\n      pose proof (Sv_V _ H) as Sov2.\n      pose proof (step_consistent u1 u2 e1' u2 A B H1 H2 Typ1 Typ2 H3 Sov1 Sov2) as Sc.\n      eapply Sc; eauto. intros. eapply IH; eauto. lia.\n    + assert (exists C, (typing nil e2' Inf C) /\\ (isosub C B)) by (eapply IH; eauto; lia).\n      destruct_conjs. exists (And A H4).\n      pose proof (step_uvalue _ _ H2 St).\n      split; eauto. eapply Ty_Mrg_Uv; eauto.\n      pose proof (Sv_V _ H) as Sov1.\n      pose proof (Sv_S _ _ St) as Sov2.\n      pose proof (step_consistent u1 u2 u1 e2' A B H1 H2 Typ1 Typ2 H3 Sov1 Sov2) as Sc.\n      eapply Sc; eauto. intros. eapply IH; eauto. lia.\n      Unshelve. eauto.\nQed.\n\n(** * Progress *)\n\nTheorem progress :\n  forall e A dir,\n    typing nil e dir A ->\n    value e \\/ exists e', step e e'.\nProof.\n  introv Typ.\n  dependent induction Typ; eauto 3.\n  - Case \"Rcd\".\n    destruct IHTyp as [Val | St] ; eauto.\n    right. destruct St. exists (Fld l x); eauto.    \n  - Case \"Anno\".\n    destruct IHTyp as [Val | St] ; eauto.\n    + right. eapply casting_progress in Typ; eauto. destruct Typ.\n      exists x. eapply St_Val; eauto.\n    + destruct (pvalue_decidable e) as [Pv | nPv];\n        destruct (splitable_or_ordinary A) as [Spl | Ord]; eauto.\n      * destruct Pv; right; destruct_conjs; eexists; eauto.\n      * destruct St. right. eexists; eauto.\n      * destruct St. right. eexists; eauto.\n  - Case \"App\".\n    eapply uunisub_sound_appsub in H.\n    right. destruct IHTyp1; destruct IHTyp2; eauto 3; try solve [destruct_conjs; eauto].\n    pose proof (papp_progress_v e1 e2 A B C) as Pa. destruct Pa; eauto.\n  - Case \"Prj\".\n    eapply uunisub_sound_appsub in H.\n    right. destruct IHTyp; eauto 3; try solve [destruct_conjs; eauto].\n    pose proof (papp_progress_l e A B l) as Pa. destruct Pa; eauto.\n  - Case \"Merge\".\n    destruct IHTyp1; destruct IHTyp2; eauto 3; try solve [destruct_conjs; eauto].\n  - Case \"Merge V\".\n    destruct IHTyp1; destruct IHTyp2; eauto 3; try solve [destruct_conjs; eauto].\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/archive2/core+bidir+record+unified/Proof/Reduction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.29355731834207455}}
{"text": "(************************************************************************)\n(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)\n(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2010     *)\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 95, no associativity).\nReserved Notation \"x /\\ y\" (at level 80, 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 than \"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\nDelimit Scope type_scope with type.\nDelimit Scope core_scope with core.\n\nOpen Scope core_scope.\nOpen Scope type_scope.\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/theories/Init/Notations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331319177486, "lm_q2_score": 0.4921881357207955, "lm_q1q2_score": 0.293557311280712}}
{"text": "Require Import LCSyntax.\nRequire Import STLCDefinition.\nRequire Import STLCTypeSoundness.\nRequire Import LCReduction.\nRequire Import MySequences.\nRequire Import MyTactics.\n\nFail Inductive R : ty -> term -> Prop :=\n| Rvar : forall x t,\n  (forall Gamma, jt Gamma t (TyVar x)) ->\n  halts cbv t ->\n  R (TyVar x) t\n| Rapp : forall t T1 T2,\n  halts cbv t ->\n  (forall Gamma, jt Gamma t (TyFun T1 T2)) ->\n  (forall s, R T1 s -> R T2 (App t s)) ->\n  R (TyFun T1 T2) t\n.\n\n\nFixpoint R (T: ty) (t: term) : Prop :=\n  (forall Gamma, jt Gamma t T) /\\ closed t /\\ halts cbv t /\\\n  match T with\n  | TyVar _ => True\n  | TyFun T1 T2 =>\n    (forall s, R T1 s -> R T2 (App t s))\n  | TyOption T => True\n  end\n.\n\n\nLemma R_unfold:\n  forall T t, R T t = (\n  (forall Gamma, jt Gamma t T) /\\ closed t /\\ halts cbv t /\\\n  match T with\n  | TyVar _ => True\n  | TyFun T1 T2 =>\n    (forall s, R T1 s -> R T2 (App t s))\n  | TyOption T => True\n  end)\n.\nProof.\n  intros; case T; simpl; try reflexivity.\nQed.\n  \n\nLemma R_halts: forall T t, R T t -> halts cbv t.\nProof.\n  induction T; intros; unfold R in *; unpack; eauto.\nQed.\n\nLemma R_typable: forall T t, R T t -> forall Gamma, jt Gamma t T.\nProof.\n  induction T; intros; unfold R in *; unpack; eauto.\nQed.\n\nLemma cbv_preserves_halt:\n  forall t t', cbv t t' -> halts cbv t -> halts cbv t'.\nProof.\n  unfold halts.\n  intros; unpack.\n  induction H0.\n  * unfold irred in *.\n    false; eapply H1; eauto.\n  * forwards: cbv_deterministic H H0; subst.\n    eauto.\nQed.\n\nLemma cbv_preserves_closed:\n  forall t t', cbv t t' -> closed t -> closed t'.\nProof.\n  intros.\n  induction H;\n    try solve [ false; eauto 3 with obvious ];\n    try solve [ unfold closed in *; fv; repeat split; unpack; eauto ].\n  * unfold closed in *; fv.\n    admit.\n  * unfold closed in *; fv.\n    admit.\n  * unfold closed in *; fv.\n    admit.\nAdmitted.\n\n\n\n\nLemma cbv_preserves_R:\n  forall T t t', cbv t t' -> R T t -> R T t'.\nProof.\n  induction T; intros; unfold R in *.\n  * unpack; repeat split; intros;\n    eauto using\n      jt_preservation,\n      cbv_preserves_closed,\n      cbv_preserves_halt.\n  * fold R in *; unpack; repeat split; intros;\n    eauto using\n      jt_preservation,\n      cbv_preserves_closed,\n      cbv_preserves_halt.\n    - eapply IHT2.\n      { eapply RedAppL; simpl; eauto. }\n      eauto.\n  * admit.\nAdmitted.\n\nLemma cbvstar_preserves_R:\n  forall T t t', star cbv t t' -> R T t -> R T t'.\nProof.\n  intros.\n  induction H; eauto using cbv_preserves_R.\nQed.\n\nLemma halt_inv:\n  forall t t', cbv t t' -> halts cbv t' -> halts cbv t.\nProof.\n  unfold halts; intros; unpack.\n  eexists; split; eauto. eauto with sequences.\nQed.\n\nLemma empty_typed_is_closed:\n  forall t T, (forall Gamma, jt Gamma t T) -> closed t.\nProof.\n  admit.\nAdmitted.\n\n\n\n\n\nLemma cbv_preserves_R_inv:\n  forall T t t', (forall Gamma, jt Gamma t T) -> cbv t t' -> R T t' -> R T t.\nProof.\n  induction T; intros; unfold R in *.\n  * unpack; repeat split; intros;\n    eauto using\n      jt_preservation,\n      cbv_preserves_closed,\n      cbv_preserves_halt,\n      empty_typed_is_closed,\n      halt_inv.\n  * fold R in *; unpack; repeat split; intros;\n    eauto using\n      jt_preservation,\n      cbv_preserves_closed,\n      cbv_preserves_halt,\n      empty_typed_is_closed,\n      halt_inv.\n    - eapply IHT2.\n      unfold R in H5; induction T1; unpack; fold R in *.\n      { admit. } { admit. } { admit. }\n      { eapply RedAppL; simpl; eauto. }\n      eauto.\n  * admit.\nAdmitted.\n\nPrint Acc.\nInductive Acc (A : Type) (R : A -> A -> Prop) (x : A) : Prop :=\n  Acc_intro: (forall y: A, R y x -> Acc A R y) -> Acc A R x.\n\n(* RPO *)\n\n\nLemma strong: forall Gamma T t, jt Gamma t T -> R T t.\nProof.\n  intros.\n  induction T.\n  * admit.\n  * admit.\n  * admit.\nAdmitted.\n(*\n  * econstructor.\n    induction H; subst; tryfalse.\n    - econstructor.\n      exists (Var x0); split; eauto with sequences.\n      unfold irred; repeat intro. invert_cbv.\n    - exists (Lam t); split; eauto with sequences.\n      unfold irred; repeat intro. invert_cbv.\n*)", "meta": {"author": "CatalaLang", "repo": "catala-formalization", "sha": "30edf137f1e250a61b46ab1aef03273d9d33b8a0", "save_path": "github-repos/coq/CatalaLang-catala-formalization", "path": "github-repos/coq/CatalaLang-catala-formalization/catala-formalization-30edf137f1e250a61b46ab1aef03273d9d33b8a0/theories/lcalc/LCNormalization.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2935211519297387}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Aniceto.Graphs.Graph.\nRequire Import Aniceto.Graphs.FGraph.\nRequire Import Aniceto.Graphs.DAG.\nRequire Import Omega.\n\nRequire CG.\nRequire Import SafeJoins.\nRequire Import Tid.\nRequire Import Node.\n\nRequire Import Coq.Structures.OrderedTypeEx.\nModule MN := FMapAVL.Make Nat_as_OT.\nModule MN_Facts := FMapFacts.Facts MN.\nModule MN_Props := FMapFacts.Properties MN.\nRequire Import Aniceto.Map.\nModule MN_Extra := MapUtil MN.\n\nModule Events.\n\n  (** Reduces the known-set interpreting events of type [CG.event]. *)\n\n  Section Defs.\n    Notation known_set := (list (tid * tid)).\n\n    Inductive SJ: CG.trace -> known_set -> Prop :=\n    | sj_nil:\n      SJ nil nil\n    | sj_init:\n      forall k x t,\n      SJ t k ->\n      SJ ((x, CG.INIT)::t) k\n    | sj_fork:\n      forall k k' x y t,\n      SJ t k ->\n      SafeJoins.CheckOp k {| op_t := FORK; op_src := x; op_dst := y |} k' ->\n      SJ ((x, CG.FORK y)::t) k'\n    | sj_join:\n      forall k k' x y t,\n      SJ t k ->\n      SafeJoins.CheckOp k {| op_t := JOIN; op_src := x; op_dst := y |} k' ->\n      SJ ((x, CG.JOIN y)::t) k'\n    | sj_continue:\n      forall k x t,\n      SJ t k ->\n      SJ ((x, CG.CONTINUE)::t) k.\n\n  End Defs.\n(*\n  Ltac simpl_red :=\n  repeat match goal with\n  | [ H : Reduces _ (_, CG.JOIN _) _ |- _ ] =>\n     inversion H; subst; clear H;\n     match goal with\n     | [ H1 : SafeJoins.CheckOp _ {| op_t := JOIN; op_src := _; op_dst := _ |} _ |- _ ] =>\n       inversion H1; subst; clear H1\n     end\n  | [ H: Reduces _ (_, CG.CONTINUE) _ |- _ ] =>\n    inversion H; subst; clear H\n  | [ H: Reduces _ (_, CG.INIT) _ |- _ ] =>\n    inversion H; subst; clear H\n  | [ H : Reduces _ (_, CG.FORK _) _ |- _ ] =>\n     inversion H; subst; clear H;\n     match goal with\n     | [ H1 : SafeJoins.CheckOp _ {| op_t := FORK; op_src := _; op_dst := _ |} _ |- _ ] =>\n       inversion H1; subst; clear H1\n     end\n  end.\n*)\nEnd Events.\n\nSection Props.\n\n  Notation known_set := (list (tid * tid)).\n\n  Inductive command :=\n  | Cons: tid -> node -> command\n  | Copy : node -> command\n  | Append: node -> node -> command\n  | Nil: command.\n\n  Definition cg_safe_joins := list command.\n\n  Inductive CanJoin : node -> tid -> cg_safe_joins -> Prop :=\n  | can_join_cons:\n    forall l n c x,\n    CanJoin n x l ->\n    CanJoin n x (c :: l)\n  | can_join_eq:\n    forall l n x,\n    CanJoin (fresh l) x (Cons x n::l)\n  | can_join_neq:\n    forall l y n x,\n    CanJoin n x l ->\n    x <> y ->\n    CanJoin (fresh l) x (Cons y n :: l)\n  | can_join_copy:\n    forall n l x,\n    CanJoin n x l ->\n    CanJoin (fresh l) x (Copy n :: l)\n  | can_join_append_left:\n    forall x n' l n,\n    CanJoin n x l ->\n    CanJoin (fresh l) x (Append n n' :: l)\n  | can_join_append_right:\n    forall n' l n x,\n    CanJoin n' x l ->\n    CanJoin (fresh l) x (Append n n' :: l).\n\n  Inductive Free x (l:cg_safe_joins) : Prop :=\n  | free_def:\n    forall n,\n    List.In (Cons x n) l ->\n    Free x l.\n\n  Inductive Knows (vs:list tid) (sj:cg_safe_joins): tid * tid -> Prop :=\n  | knows_def:\n    forall x y nx,\n    MapsTo x nx vs ->\n    CanJoin nx y sj ->\n    Knows vs sj (x, y).\n\n  Definition EdgeToKnows vs sj k :=\n    forall p,\n    List.In p k ->\n    Knows vs sj p.\n\n  Definition KnowsToEdge vs sj k :=\n    forall p,\n    Knows vs sj p ->\n    List.In p k.\n\n  Definition FreeInGraph vs sj :=\n    forall x,\n    Free x sj ->\n    List.In x vs.\nEnd Props.\n\n  Inductive SJ : CG.trace -> CG.computation_graph -> cg_safe_joins -> Prop :=\n\n  | sj_nil:\n    SJ nil (nil, nil) nil\n\n  | sj_init:\n    forall x cg cg' t sj,\n    SJ t cg sj ->\n    CG.CG ((x, CG.INIT)::t) cg' ->\n    SJ ((x, CG.INIT)::t) cg' (Nil::sj)\n\n  (**\n    Case Fork:\n    \n    x -- fork --> y\n     \\\n      `-- continue --> x'\n  \n    We know that `x` is connected to y through a `fork` edge\n    and that `x` is connected to `x'` through a `continue` edge.\n    Let `ty` be the name of task associated with node `y`.\n    \n    The result is:\n\n     - x' is defined as `Cons ty x`, which means that the names of `x'` are defined as \n       the names from `x` and also `ty`.\n      \n     - y is defined as `Copy x` which means that it contains the same names as in `x`.\n   *)\n\n  | sj_fork:\n    forall x y x' ty vs es a b t cg sj,\n    SJ t cg sj ->\n    CG.CG ((a, CG.FORK b)::t) (ty::vs, CG.F (x,y)::CG.C (x,x')::es) ->\n    SJ ((a, CG.FORK b)::t) (ty::vs, CG.F (x,y)::CG.C (x,x')::es) (Copy x::Cons ty x::sj)\n\n  | sj_join:\n    forall x y x' ty vs es a b t sj cg,\n    SJ t cg sj ->\n    CG.CG ((a, CG.JOIN b)::t) (vs, CG.J (y,x') :: CG.C (x,x')::es) ->\n    MapsTo ty y vs ->\n    CanJoin x ty sj -> (* check: ty \\in x *)\n    SJ ((a, CG.JOIN b)::t) (vs, CG.J (y,x') :: CG.C (x,x')::es) (Append x y :: sj)\n\n  | sj_continue:\n    forall x x' a es vs sj t cg,\n    SJ t cg sj ->\n    CG.CG ((a, CG.CONTINUE)::t) (vs, CG.C (x,x')::es) ->\n    SJ ((a, CG.CONTINUE)::t) (vs, CG.C (x,x')::es) (Copy x :: sj).\n\n\n  Ltac do_simpl :=\n  match goal with\n  | [ H: SJ ((_,CG.INIT) :: _) _ _ |- _ ] => inversion H; subst; clear H\n  | [ H: SJ ((_,CG.FORK _) :: _) _ _ |- _ ] => inversion H; subst; clear H\n  | [ H: SJ ((_,CG.JOIN _) :: _) _ _ |- _ ] => inversion H; subst; clear H\n  | [ H: SJ ((_,CG.CONTINUE) :: _) _ _ |- _ ] => inversion H; subst; clear H\n  end.\n\nSection SJ_TO_CG.\n  Lemma sj_to_cg:\n    forall t cg sj,\n    SJ t cg sj ->\n    CG.CG t cg.\n  Proof.\n    intros.\n    inversion H; subst; auto using CG.cg_nil.\n  Qed.\n\n  Lemma sj_cg_fun:\n    forall t cg1 cg2 sj,\n    SJ t cg1 sj ->\n    CG.CG t cg2 ->\n    cg1 = cg2.\n  Proof.\n    eauto using sj_to_cg, CG.cg_fun.\n  Qed.\nEnd SJ_TO_CG.\n\n  Ltac simpl_sj :=\n  repeat match goal with\n  | [ H1 : SJ ?t ?cg1 _, H2: CG.CG ?t ?cg2 |- _ ] =>\n    assert (cg1 = cg2) by eauto using sj_cg_fun; subst;\n    clear H2\n  end.\n\n  Ltac simpl_red :=\n    CG.simpl_red;\n    try simpl_sj.\n\nSection LengthPreserves.\n\n  (* -------------------------------------------------- *)\n\n  Lemma sj_to_length:\n    forall t cg sj,\n    SJ t cg sj ->\n    length (fst cg) = length sj.\n  Proof.\n    induction t; intros; inversion H; subst; clear H; simpl; auto;\n    simpl_red;\n    try (inversion H5; subst; simpl_node; clear H5);\n    apply IHt in H2; simpl; auto with *.\n  Qed.\n\n  Lemma sj_to_length_0:\n    forall t vs es sj,\n    SJ t (vs, es) sj ->\n    length vs = length sj.\n  Proof.\n    intros.\n    assert (length (fst (vs, es)) = length sj) by eauto using sj_to_length.\n    simpl in *.\n    assumption.\n  Qed.\n\nEnd LengthPreserves.\n\nSection FreeInGraph.\n\n  (* -------------------------------------------------- *)\n\n  Lemma sj_to_free_in_graph:\n    forall t cg sj,\n    SJ t cg sj ->\n    FreeInGraph (fst cg) sj.\n  Proof.\n    induction t; intros. {\n      inversion H; subst.\n      unfold FreeInGraph; simpl; intros.\n      inversion H0.\n      inversion H1.\n    }\n    inversion H; subst; clear H; simpl_red; simpl in *;\n    apply IHt in H2; simpl in *; unfold FreeInGraph in *; intros;\n    inversion H; subst; clear H;\n    inversion H0; subst; clear H0;\n    eauto using in_cons, free_def;\n    inversion H; subst; clear H.\n    - inversion H0; subst; clear H0.\n      auto using in_eq.\n    - eauto using in_cons, free_def.\n  Qed.\n\n  Lemma sj_free_in_nodes:\n    forall t vs es sj x,\n    SJ t (vs, es) sj ->\n    Free x sj ->\n    List.In x vs.\n  Proof.\n    intros.\n    assert (Hf: FreeInGraph (fst (vs, es)) sj) by\n    eauto using sj_to_free_in_graph.\n    auto.\n  Qed.\n\nEnd FreeInGraph.\n\nSection ESafeJoins.\n\n  Let free_cons:\n    forall x sj c,\n    Free x sj ->\n    Free x (c::sj).\n  Proof.\n    intros.\n    inversion H.\n    eauto using List.in_cons, free_def.\n  Qed.\n\n  Let free_eq:\n    forall x n sj,\n    Free x (Cons x n :: sj).\n  Proof.\n    eauto using free_def, List.in_eq.\n  Qed.\n\n  Lemma can_join_to_free:\n    forall sj x n ,\n    CanJoin n x sj ->\n    Free x sj.\n  Proof.\n    induction sj; intros. {\n      inversion H.\n    }\n    inversion H; subst; clear H; eauto.\n  Qed.\n\n  Lemma can_join_absurd_lt:\n    forall sj n b,\n    NODE.lt (fresh sj) n ->\n    ~ CanJoin n b sj.\n  Proof.\n    unfold NODE.lt, fresh, not; intros.\n    induction H0; simpl in *; auto with *.\n  Qed.\n\n  Let can_join_lt_fresh:\n    forall sj n b,\n    CanJoin n b sj ->\n    NODE.lt n (fresh sj).\n  Proof.\n    intros.\n    unfold NODE.lt, fresh.\n    induction H; simpl in *; auto with *.\n  Qed.\n\n  Lemma can_join_absurd_fresh:\n    forall sj b,\n    ~ CanJoin (fresh sj) b sj.\n  Proof.\n    intros.\n    unfold not; intros.\n    apply can_join_lt_fresh in H.\n    unfold NODE.lt, fresh, not in *.\n    omega.\n  Qed.\n\n  Lemma can_join_lt:\n    forall x n sj c,\n    NODE.lt n (fresh sj) ->\n    CanJoin n x (c :: sj) ->\n    CanJoin n x sj.\n  Proof.\n    intros.\n    inversion H0; subst; try apply Lt.lt_irrefl in H; auto; contradiction.\n  Qed.\n\n  Lemma can_join_inv_cons_1:\n    forall sj x y n,\n    CanJoin (fresh sj) x (Cons y n :: sj) ->\n    x = y \\/ (CanJoin n x sj /\\ x <> y).\n  Proof.\n    intros.\n    inversion H; clear H.\n    - subst; apply can_join_absurd_fresh in H3; contradiction.\n    - intuition.\n    - subst.\n      intuition.\n  Qed.\n\n  Lemma can_join_inv_cons_2:\n    forall n x y sj,\n    CanJoin n x (Cons y n :: sj) ->\n    (x = y /\\ CanJoin n y sj) \\/ (x <> y /\\ CanJoin n x sj) \\/ (x = y /\\ n = fresh sj).\n  Proof.\n    intros.\n    destruct (tid_eq_dec x y);\n    inversion H; subst; clear H; auto.\n  Qed.\n\n  Lemma can_join_inv_append:\n    forall x nx ny sj,\n    CanJoin (fresh sj) x (Append nx ny :: sj) ->\n    CanJoin nx x sj \\/ CanJoin ny x sj.\n  Proof.\n    intros.\n    inversion H; clear H.\n    - subst; apply can_join_absurd_fresh in H3; contradiction.\n    - intuition.\n    - intuition.\n  Qed.\n\n  Lemma can_join_inv_copy_1:\n    forall sj x n,\n    CanJoin (fresh sj) x (Copy n :: sj) ->\n    CanJoin n x sj.\n  Proof.\n    intros.\n    inversion H; clear H.\n    - subst; apply can_join_absurd_fresh in H3; contradiction.\n    - auto.\n  Qed.\n\n  Lemma can_join_inv_copy_2:\n    forall n x sj,\n    CanJoin n x (Copy n :: sj) ->\n    CanJoin n x sj.\n  Proof.\n    intros.\n    inversion H; subst; clear H; assumption.\n  Qed.\n\n  Lemma knows_cons:\n    forall vs sj a b c x,\n    Knows vs sj (a, b) ->\n    x <> a ->\n    Knows (x :: vs) (c :: sj) (a, b).\n  Proof.\n    intros.\n    inversion H; subst; clear H.\n    simpl in *.\n    eauto using knows_def, can_join_cons, maps_to_cons.\n  Qed.\n\n  Lemma knows_cons_neq:\n    forall x y z n sj vs,\n    x <> y ->\n    y <> z ->\n    MapsTo x n vs ->\n    Knows vs sj (x, z) ->\n    length vs = length sj ->\n    Knows (x :: vs) (Cons y n :: sj) (x, z).\n  Proof.\n    intros.\n    inversion_clear H2.\n    simpl_node.\n    apply knows_def with (nx:=fresh vs).\n    - auto using maps_to_eq.\n    - apply maps_to_length_rw in H3.\n      rewrite H3.\n      apply can_join_neq; auto.\n  Qed.\n\n  Lemma knows_neq:\n    forall vs sj a b x c,\n    Knows vs sj (a, b) ->\n    a <> x ->\n    Knows (x :: vs) (c :: sj) (a, b).\n  Proof.\n    intros.\n    inversion H; subst; clear H.\n    eauto using knows_def, maps_to_cons, can_join_cons.\n  Qed.\n\n  Lemma knows_eq:\n    forall a vs b n sj,\n    length vs = length sj ->\n    Knows (a :: vs) (Cons b n :: sj) (a, b).\n  Proof.\n    intros.\n    apply knows_def with (nx:=fresh vs).\n    - auto using maps_to_eq.\n    - apply maps_to_length_rw in H.\n      rewrite H.\n      apply can_join_eq.\n  Qed.\n\n  Lemma knows_copy:\n    forall vs sj x y z n,\n    length vs = length sj ->\n    MapsTo x n vs ->\n    Knows vs sj (x, y) ->\n    Knows (z :: vs) (Copy n :: sj) (z, y).\n  Proof.\n    intros.\n    inversion H1; subst; clear H1.\n    apply knows_def with (nx:=fresh vs).\n    - auto using maps_to_eq.\n    - apply maps_to_length_rw in H.\n      rewrite H.\n      apply can_join_copy.\n      assert (nx = n) by eauto using maps_to_fun_2; subst.\n      assumption.\n  Qed.\n\n  Lemma knows_append_right:\n    forall y ny nx x vs b sj,\n    length vs = length sj ->\n    MapsTo y ny vs ->\n    Knows vs sj (y, b) ->\n    Knows (x :: vs) (Append nx ny :: sj) (x, b).\n  Proof.\n    intros.\n    inversion H1; subst; clear H1.\n    assert (nx0 = ny) by eauto using maps_to_fun_2; subst.\n    apply knows_def with (nx:=fresh vs).\n    - auto using maps_to_eq.\n    - apply maps_to_length_rw in H.\n      rewrite H.\n      apply can_join_append_right.\n      assumption.\n  Qed.\n\n  Lemma knows_append_left:\n    forall ny nx x vs b sj,\n    length vs = length sj ->\n    MapsTo x nx vs ->\n    Knows vs sj (x, b) ->\n    Knows (x :: vs) (Append nx ny :: sj) (x, b).\n  Proof.\n    intros.\n    inversion H1; subst; clear H1.\n    assert (nx0 = nx) by eauto using maps_to_fun_2; subst.\n    apply knows_def with (nx:=fresh vs).\n    - auto using maps_to_eq.\n    - apply maps_to_length_rw in H.\n      rewrite H.\n      apply can_join_append_left.\n      assumption.\n  Qed.\n\n  Lemma knows_to_free:\n    forall sj vs x y,\n    Knows vs sj (x, y) ->\n    Free y sj.\n  Proof.\n    induction sj; intros; inversion_clear H. {\n      inversion H1.\n    }\n    inversion_clear H1; eauto using free_cons, knows_def, can_join_to_free.\n  Qed.\n\n  Lemma knows_to_in_l:\n    forall x y vs sj,\n    Knows vs sj (x, y) ->\n    List.In x vs.\n  Proof.\n    intros.\n    inversion H; subst.\n    eauto using maps_to_to_in.\n  Qed.\n\n  Lemma knows_to_in_r:\n    forall x y vs sj t es,\n    SJ t (vs, es) sj ->\n    Knows vs sj (x, y) ->\n    List.In y vs.\n  Proof.\n    intros.\n    eapply sj_free_in_nodes; eauto using knows_to_free.\n  Qed.\n\n  Let knows_continue:\n    forall sj vs a b x nx,\n    MapsTo x nx vs ->\n    Knows vs sj (a, b) ->\n    length sj = length vs ->\n    Knows (x :: vs) (Copy nx :: sj) (a, b).\n  Proof.\n    intros.\n    destruct (tid_eq_dec a x). {\n      subst.\n      eauto using knows_copy.\n    }\n    auto using knows_neq.\n  Qed.\n\n  Lemma knows_fork_1:\n    forall vs es sj x y z n t,\n    SJ t (vs, es) sj ->\n    ~ List.In y vs ->\n    MapsTo x n vs ->\n    Knows vs sj (x, z) ->\n    x <> y ->\n    Knows (x :: vs) (Cons y n :: sj) (x, z).\n  Proof.\n    intros.\n    apply knows_cons_neq; auto; eauto using sj_to_length_0.\n    unfold not; intros; subst.\n    eapply knows_to_in_r in H2; eauto.\n  Qed.\n\n  Lemma knows_fork_2:\n    forall x y z vs n sj t es,\n    SJ t (vs, es) sj ->\n    ~ List.In z vs ->\n    MapsTo x n vs ->\n    x <> z ->\n    Knows vs sj (x, y) ->\n    Knows (z :: x :: vs) (Copy n :: Cons z n :: sj) (z, y).\n  Proof.\n    intros.\n    assert (Knows (x::vs) (Cons z n :: sj) (x, y)) by eauto using knows_fork_1.\n    apply knows_def with (nx:=fresh (x::vs)); auto using maps_to_eq.\n    assert (R: fresh (x::vs) = fresh (Cons z n :: sj)). {\n      apply maps_to_length_rw.\n      assert (R: length vs = length sj) by eauto using sj_to_length_0.\n      simpl; rewrite R; trivial.\n    }\n    rewrite R.\n    apply can_join_copy.\n    apply can_join_cons.\n    inversion H3; subst.\n    simpl_node.\n    assumption.\n  Qed.\n\n  Lemma knows_fork_3:\n    forall x y vs es sj t n,\n    SJ t (vs, es) sj ->\n    x <> y ->\n    Knows (y :: x :: vs) (Copy n :: Cons y n :: sj) (x, y).\n  Proof.\n    intros.\n    apply knows_cons; auto.\n    apply knows_eq; eauto using sj_to_length_0.\n  Qed.\n\n  Lemma knows_fork_4:\n    forall t vs es sj a b n y x,\n    SJ t (vs, es) sj ->\n    ~ List.In y vs ->\n    MapsTo x n vs ->\n    Knows vs sj (a, b) ->\n    Knows (y :: x :: vs) (Copy n :: Cons y n :: sj) (a, b).\n  Proof.\n    intros.\n    assert (y <> a). {\n      unfold not; intros; subst.\n      apply knows_to_in_l in H2.\n      contradiction.\n    }\n    apply knows_cons; auto.\n    destruct (tid_eq_dec x a). {\n      subst.\n      assert (y <> b). {\n        unfold not; intros; subst.\n        eapply knows_to_in_r in H2; eauto.\n      }\n      apply knows_cons_neq; eauto using sj_to_length_0.\n    }\n    apply knows_cons; auto.\n  Qed.\n\n  Lemma knows_init:\n    forall a b sj vs x,\n    ~ List.In x vs ->\n    Knows vs sj (a, b) ->\n    Knows (x :: vs) (Nil :: sj) (a, b).\n  Proof.\n    intros.\n    inversion H0; subst; clear H0.\n    apply knows_def with (nx:=nx).\n    - apply maps_to_cons; auto.\n      unfold not; intros; subst.\n      apply maps_to_to_in in H3.\n      contradiction.\n    - auto using can_join_cons.\n  Qed.\n\n  Lemma knows_inv_init:\n    forall x p vs sj,\n    length vs = length sj ->\n    Knows (x :: vs) (Nil :: sj) p ->\n    Knows vs sj p.\n  Proof.\n    intros.\n    inversion H0; subst; clear H0.\n    apply maps_to_inv in H1.\n    destruct H1 as [(?,?)|(?,mt)].\n    - subst.\n      apply maps_to_length_rw in H.\n      rewrite H in *.\n      inversion H2; subst.\n      apply can_join_absurd_fresh in H4.\n      contradiction.\n    - inversion H2; subst; clear H2.\n      eauto using knows_def.\n  Qed.\n\n  Lemma knows_inv_fork:\n    forall vs sj n x y a b,\n    length vs = length sj ->\n    Knows (y :: x :: vs) (Copy n :: Cons y n :: sj) (a, b) ->\n    (a = y /\\ CanJoin (fresh (x::vs)) b (Copy n :: Cons y n :: sj)) \\/\n    (a <> y /\\ a = x /\\ (CanJoin (fresh vs) b (Copy n :: Cons y n :: sj))) \\/\n    (a <> y /\\ a <> x /\\ Knows vs sj (a,b)).\n  Proof.\n    intros.\n    inversion H0; subst; clear H0.\n    apply maps_to_inv in H3.\n    assert (R: fresh (x::vs) = fresh (Cons y n :: sj)). {\n      assert (R: length (x::vs) = length (Cons y n :: sj)). {\n        simpl.\n        rewrite H.\n        trivial.\n      }\n      auto using maps_to_length_rw.\n    }\n    destruct H3 as [(?,?)|(?,mt)]. {\n      left.\n      subst.\n      auto.\n    }\n    right.\n    apply maps_to_inv in mt.\n    destruct mt as [(?,?)|(?,mt)]. {\n      subst.\n      auto.\n    }\n    inversion H4; subst; clear H4. {\n      inversion H6; subst; clear H6.\n      - right.\n        split; auto; split; eauto using knows_def.\n      - apply maps_to_length_rw in H.\n        rewrite <- H in *.\n        simpl_node.\n      - apply maps_to_length_rw in H.\n        rewrite <- H in *.\n        simpl_node.\n    }\n    rewrite <- R in *.\n    rewrite fresh_cons_rw_next in *.\n    simpl_node.\n  Qed.\n\n  Lemma can_join_to_in:\n    forall vs es t sj x n,\n    SJ t (vs,es) sj ->\n    CanJoin n x sj ->\n    List.In x vs.\n  Proof.\n    eauto using can_join_to_free, sj_free_in_nodes.\n  Qed.\n\n  Definition KnowsTrans vs sj :=\n    forall x y z,\n    Knows vs sj (x, y) ->\n    Knows vs sj (y, z) ->\n    Knows vs sj (x, z).\n\n  Lemma can_join_inv_cons_3:\n    forall n x y sj,\n    n <> fresh sj ->\n    CanJoin n x (Cons y n :: sj) ->\n    CanJoin n x sj.\n  Proof.\n    intros.\n    apply can_join_inv_cons_2 in H0.\n    destruct H0 as [(?,?)|[(?,?)|(?,?)]].\n    - subst; auto.\n    - auto.\n    - contradiction.\n  Qed.\n\n  Lemma can_join_inv_fork_1:\n    forall x y n sj,\n    CanJoin (fresh sj) x (Copy n :: Cons y n :: sj) ->\n    x = y \\/ CanJoin n x sj.\n  Proof.\n    intros.\n    inversion H; subst; clear H. {\n      apply can_join_inv_cons_1 in H3.\n      destruct H3 as [?|(?,?)]; subst; auto.\n    }\n    simpl in *.\n    omega.\n  Qed.\n\n  Lemma knows_append_2:\n    forall a b nx ny sj vs x y,\n    length vs = length sj ->\n    MapsTo x nx vs ->\n    Knows vs sj (a, b) ->\n    Knows vs sj (x, y) ->\n    Knows (x :: vs) (Append nx ny :: sj) (a, b).\n  Proof.\n    intros.\n    destruct (tid_eq_dec x a). {\n      subst.\n      inversion H1; inversion H2; subst; clear H1 H2.\n      simpl_node.\n      apply knows_def with (nx:=fresh sj).\n      + apply maps_to_length_rw in H.\n        rewrite <- H.\n        auto using maps_to_eq.\n      + auto using can_join_append_left.\n    }\n    auto using knows_cons.\n  Qed.\n\n  Lemma sj_to_edge_to_knows:\n    forall t k cg sj,\n    Events.SJ t k ->\n    SJ t cg sj ->\n    EdgeToKnows (fst cg) sj k.\n  Proof.\n    induction t; intros. {\n      inversion H0; subst; clear H0.\n      inversion H; subst; clear H.\n      unfold EdgeToKnows; simpl; intros.\n      contradiction.\n    }\n    inversion H0; subst; clear H0; simpl_red;\n    inversion H;subst; clear H; simpl in *;\n    rename sj0 into sj;\n    try (rename vs0 into vs);\n    try (rename k0 into k_; rename k into k'; rename k_ into k);\n    (assert (He: EdgeToKnows (fst (vs, es)) sj k) by auto; simpl in *);\n    unfold EdgeToKnows in *; intros;try (apply He in H);\n    destruct p as (c,d).\n    - apply knows_cons; auto.\n      unfold not; intros; subst.\n      apply knows_to_in_l in H.\n      contradiction.\n    - inversion H6; subst; clear H6.\n      apply fork_inv_in in H.\n      destruct H as [(?,?)|[(?,?)|?]]; subst;\n      eauto using knows_fork_2, knows_fork_3, knows_fork_4.\n    - inversion H7; subst; clear H7.\n      apply join_inv_in in H.\n      unfold FGraph.Edge in *.\n      apply He in H4.\n      destruct H as [(?,Hi)|Hi]; subst;\n      apply He in Hi; clear He IHt.\n      + eapply knows_append_right; eauto using sj_to_length_0.\n      + eauto using knows_append_2, sj_to_length_0.\n    - destruct (tid_eq_dec a0 c). {\n        subst.\n        apply knows_def with (nx:=fresh vs); auto using maps_to_eq.\n        assert (R: fresh vs = fresh sj). {\n          eauto using maps_to_length_rw, sj_to_length_0.\n        }\n        rewrite R.\n        apply can_join_copy.\n        inversion H; subst; clear H.\n        simpl_node.\n        auto.\n      }\n      auto using knows_cons.\n  Qed.\n\n  Lemma sj_edge_to_knows_0:\n    forall t k vs es sj p,\n    Events.SJ t k ->\n    SJ t (vs,es) sj ->\n    List.In p k ->\n    Knows vs sj p.\n  Proof.\n    assert (X:= sj_to_edge_to_knows).\n    unfold EdgeToKnows in *.\n    intros.\n    eapply X in H1; eauto.\n    simpl in *.\n    assumption.\n  Qed.\n\nEnd ESafeJoins.\n\nSection KnowsToEdge.\n  (* -------------------------------------------------- *)\n\n  Let nat_absurd_succ:\n    forall n,\n    n <> S n.\n  Proof.\n    intros.\n    unfold not; intros.\n    induction n.\n    - inversion H.\n    - inversion H; auto.\n  Qed.\n\n  Lemma knows_inv_append:\n    forall x n1 n2 a b sj vs,\n    length vs = length sj ->\n    Knows (x :: vs) (Append n1 n2 :: sj) (a,b) ->\n    (a = x /\\ (CanJoin n1 b sj \\/ CanJoin n2 b sj))\n    \\/\n    (a <> x /\\ Knows vs sj (a, b)).\n  Proof.\n    intros.\n    apply maps_to_length_rw in H.\n    inversion H0; subst; clear H0.\n    apply maps_to_inv in H3.\n    destruct H3 as [(?,?)|(?,?)]. {\n      subst.\n      rewrite H in *.\n      apply can_join_inv_append in H4.\n      intuition.\n    }\n    inversion H4; subst; clear H4.\n    - eauto using knows_def.\n    - rewrite <- H in *.\n      simpl_node.\n    - rewrite <- H in *.\n      simpl_node.\n  Qed.\n\n  Lemma knows_inv_copy:\n    forall x vs sj a b n,\n    length vs = length sj ->\n    Knows (x :: vs) (Copy n :: sj) (a,b) ->\n    (a = x /\\ CanJoin n b sj) \\/\n    (a <> x /\\ Knows vs sj (a,b)).\n  Proof.\n    intros.\n    apply maps_to_length_rw in H.\n    inversion H0; subst; clear H0.\n    apply maps_to_inv in H3.\n    destruct H3 as [(?,?)|(?,?)].\n    + subst.\n      rewrite H in *.\n      apply can_join_inv_copy_1 in H4.\n      auto.\n    + inversion H4; subst; clear H4. {\n        eauto using knows_def.\n      }\n      rewrite <- H in *.\n      simpl_node.\n  Qed.\n\n  Lemma sj_to_knows_to_edge:\n    forall t cg k sj,\n    Events.SJ t k ->\n    SJ t cg sj ->\n    KnowsToEdge (fst cg) sj k.\n  Proof.\n    induction t; intros. {\n      inversion H; subst.\n      inversion H0; subst.\n      unfold KnowsToEdge; intros.\n      inversion H1; subst; simpl in *.\n      inversion H2.\n    }\n    inversion H0; subst; clear H0; simpl_red;\n    inversion H;subst; clear H; simpl in *;\n    rename sj0 into sj;\n    try (rename vs0 into vs);\n    try (rename k0 into k_; rename k into k'; rename k_ into k);\n    unfold KnowsToEdge in *; intros.\n    - apply knows_inv_init in H; eauto using sj_to_length_0.\n    - destruct p as (a,b).\n      inversion H6; subst; clear H6.\n      assert (R: fresh (a0::vs) = fresh (Cons ty x :: sj)). {\n        assert (length (a0::vs) = length (Cons ty x :: sj)). {\n          simpl.\n          erewrite sj_to_length_0; eauto.\n        }\n        auto using maps_to_length_rw.\n      }\n      assert (R2: fresh vs = fresh sj) by eauto using sj_to_length_0, maps_to_length_rw.\n      apply knows_inv_fork in H; eauto using sj_to_length_0.\n      destruct H as [(?,?)|[(?,(?,?))|(?,(?,?))]]; subst.\n      + rewrite R in *.\n        apply can_join_inv_copy_1 in H0.\n        apply can_join_inv_cons_2 in H0.\n        destruct H0 as [(?,?)|[(?,?)|(?,?)]]; subst.\n        * eapply can_join_to_in in H0; eauto.\n          contradiction.\n        * eauto using in_fork_2, knows_def.\n        * rewrite <- R2 in *.\n          simpl_node.\n      + rewrite R2 in *.\n        apply can_join_inv_fork_1 in H1.\n        destruct H1 as [?|?]. {\n          subst.\n          auto using in_fork_5.\n        }\n        eauto using in_fork, knows_def.\n      + eauto using in_fork.\n    - inversion H7; subst; clear H7.\n      destruct p as (c,d).\n      apply knows_inv_append in H; eauto using sj_to_length_0.\n      destruct H as [(?,[?|?])|(?,?)];\n      subst; eauto using knows_def, in_join_2, in_join.\n    - destruct p as (a,b).\n      apply knows_inv_copy in H; eauto using sj_to_length_0.\n      destruct H as [(?,?)|(?,?)].\n      + subst.\n        eauto using knows_def.\n      + eauto.\n  Qed.\n\n  Lemma sj_to_knows_to_edge_0:\n    forall t vs es k sj p,\n    Events.SJ t k ->\n    SJ t (vs, es) sj ->\n    Knows vs sj p ->\n    List.In p k.\n  Proof.\n    intros.\n    assert (Hk: KnowsToEdge (fst (vs,es)) sj k)\n    by eauto using sj_to_knows_to_edge.\n    auto.\n  Qed.\nEnd KnowsToEdge.\n\nSection Incl.\n  (* ------------------------------------------ *)\n\n  Definition Incl cg sj :=\n  forall n1 n2 x,\n  List.In (n1, n2) (CG.cg_edges cg) ->\n  CanJoin n1 x sj ->\n  CanJoin n2 x sj.\n\n  Let in_length_absurd:\n    forall vs es n,\n    CG.EdgeToNode (vs, es) ->\n    ~ List.In (fresh vs, n) (map CG.e_edge es).\n  Proof.\n    intros.\n    intuition.\n    assert (Hx:List.In (fresh vs, n) (CG.cg_edges es)) by auto.\n    eapply CG.node_lt_length_left in Hx; eauto.\n    simpl in Hx.\n    unfold NODE.lt in *.\n    omega.\n  Qed.\n\n  Lemma sj_to_incl:\n    forall t cg k sj,\n    Events.SJ t k ->\n    SJ t cg sj ->\n    Incl (snd cg) sj.\n  Proof.\n    induction t; intros. {\n      inversion H; subst; clear H.\n      inversion H0; subst; clear H0.\n      simpl; unfold Incl; intros.\n      inversion H.\n    }\n    inversion H0; subst; clear H0; simpl_red;\n    inversion H;subst; clear H; simpl in *;\n    rename sj0 into sj;\n    try (rename vs0 into vs);\n    try (rename k0 into k_; rename k into k'; rename k_ into k);\n    unfold Incl in *; intros.\n    - inversion H0; subst; clear H0.\n      eauto using can_join_cons.\n    - inversion H6; subst; clear H6; simpl_node.\n      simpl in *.\n      assert (R: fresh (a0::vs) = fresh (Cons ty x :: sj)). {\n        assert (length (a0::vs) = length (Cons ty x :: sj)). {\n          simpl.\n          erewrite sj_to_length_0; eauto.\n        }\n        auto using maps_to_length_rw.\n      }\n      assert (R2: fresh vs = fresh sj) by eauto using sj_to_length_0, maps_to_length_rw.\n      destruct H as [Heq|[Heq|?]];\n      try (inversion Heq; subst; clear Heq).\n      + rewrite R. apply can_join_copy.\n        apply can_join_inv_copy_2 in H0.\n        apply can_join_inv_cons_2 in H0.\n        destruct H0 as [(?,?)|[(?,?)|(?,?)]]; subst;\n        auto using can_join_cons.\n        rewrite <- R2 in *.\n        simpl_node.\n      + rewrite R2.\n        apply can_join_cons.\n        apply can_join_inv_copy_2 in H0.\n        apply can_join_inv_cons_2 in H0.\n        destruct H0 as [(?,?)|[(?,?)|(?,?)]]; subst;\n        auto using can_join_eq, can_join_neq.\n      + inversion H0; subst; clear H0. {\n          inversion H7; subst; clear H7.\n          - eapply IHt in H6; eauto.\n            auto using can_join_cons.\n          - rewrite <- R2 in *.\n            eapply CG.cg_edge_to_node_l in H; eauto using sj_to_cg.\n            simpl_node.\n          - rewrite <- R2 in *.\n            eapply CG.cg_edge_to_node_l in H; eauto using sj_to_cg.\n            simpl_node.\n        }\n        rewrite <- R in *.\n        eapply CG.cg_edge_to_node_l in H; eauto using sj_to_cg.\n        simpl_node.\n    - simpl in *.\n      assert (R: fresh (a0::vs) = fresh (Append x y :: sj)). {\n        assert (length (a0::vs) = length (Append x y :: sj)). {\n          simpl.\n          erewrite sj_to_length_0; eauto.\n        }\n        auto using maps_to_length_rw.\n      }\n      assert (R2: fresh vs = fresh sj) by eauto using sj_to_length_0, maps_to_length_rw.\n      inversion H7; subst; clear H7.\n      destruct H as [He|[He|Hi]];\n      try (inversion He; subst; clear He);\n      try (rewrite R2).\n      + inversion H0; subst; clear H0;\n        eauto using can_join_append_right, can_join_append_left.\n      + inversion H0; subst; clear H0;\n        eauto using can_join_append_right, can_join_append_left.\n      + apply can_join_cons.\n        inversion H0; subst; clear H0.\n        * eauto.\n        * rewrite <- R2 in *.\n          eapply CG.cg_edge_to_node_l in Hi; eauto using sj_to_cg.\n          simpl_node.\n        * rewrite <- R2 in *.\n          eapply CG.cg_edge_to_node_l in Hi; eauto using sj_to_cg.\n          simpl_node.\n    - simpl in *.\n      assert (R: fresh (a0::vs) = fresh (Copy x :: sj)). {\n        assert (length (a0::vs) = length (Copy x :: sj)). {\n          simpl.\n          erewrite sj_to_length_0; eauto.\n        }\n        auto using maps_to_length_rw.\n      }\n      assert (R2: fresh vs = fresh sj) by eauto using sj_to_length_0, maps_to_length_rw.\n      destruct H as [He|Hi]. {\n        inversion He; subst; clear He.\n        rewrite R2.\n        auto using can_join_copy, can_join_inv_copy_2.\n      }\n      inversion H0; subst; clear H0. {\n        eauto using can_join_cons.\n      }\n      rewrite <- R2 in *.\n      eapply CG.cg_edge_to_node_l in Hi; eauto using sj_to_cg.\n      simpl_node.\n  Qed.\n\n  Let hb_edge_in:\n    forall cg sj n1 n2 x,\n    Incl cg sj ->\n    CanJoin n1 x sj ->\n    CG.HB_Edge cg (n1, n2) ->\n    CanJoin n2 x sj.\n  Proof.\n    intros.\n    rewrite CG.hb_edge_spec in *.\n    eauto.\n  Qed.\n\n  Let InEdge sj x (e:node*node) := CanJoin (fst e) x sj /\\ CanJoin (snd e) x sj.\n\n  Let in_edge:\n    forall sj cg a b x,\n    Incl cg sj ->\n    CG.HB_Edge cg (a, b) ->\n    CanJoin a x sj ->\n    InEdge sj x (a, b).\n  Proof.\n    intros.\n    unfold InEdge.\n    simpl.\n    eauto.\n  Qed.\n\n  Let wb_in_0:\n    forall cg  sj w x a b,\n    Incl cg sj ->\n    CanJoin a x sj ->\n    Walk2 (CG.HB_Edge cg) a b w ->\n    Walk2 (InEdge sj x) a b w.\n  Proof.\n    induction w; intros. {\n      apply walk2_nil_inv in H1.\n      contradiction.\n    }\n    inversion H1; subst; clear H1.\n    inversion H4; subst; clear H4.\n    destruct a as (a, c).\n    apply starts_with_eq in H2; symmetry in H2; subst.\n    destruct w as [|(c',d)].\n    - apply ends_with_eq in H3.\n      subst.\n      eauto using edge_to_walk2.\n    - apply ends_with_inv in H3.\n      apply linked_inv in H8; subst.\n      apply walk2_cons.\n      + eauto using starts_with_def, walk2_def.\n      + eauto.\n  Qed.\n\n  Lemma incl_hb:\n    forall cg sj n1 n2 x,\n    Incl cg sj ->\n    CanJoin n1 x sj ->\n    CG.HB cg n1 n2 ->\n    CanJoin n2 x sj.\n  Proof.\n    intros.\n    unfold CG.HB in *.\n    inversion H1.\n    apply wb_in_0 with (sj:=sj) (x:=x) in H2; auto.\n    inversion H2; subst.\n    destruct H4 as ((v1,v2),(Hx,Hy)); subst.\n    apply end_to_edge with (Edge := InEdge sj x) in Hx; auto.\n    simpl.\n    destruct Hx.\n    simpl in *.\n    auto.\n  Qed.\n\nEnd Incl.\n\nSection SJ.\n\n  (** Main theorem part 1:\n   Shows that we can build an annotated CG with SJ information\n   from a SJ trace and a CG. *)\n\n  Theorem events_sj_to_sj:\n    forall t k cg,\n    Events.SJ t k ->\n    CG.CG t cg ->\n    exists sj, SJ t cg sj.\n  Proof.\n    induction t; intros. {\n      inversion H; subst; clear H.\n      inversion H0; subst; clear H0.\n      eauto using sj_nil.\n    }\n    inversion H0; subst; clear H0;\n    inversion H; subst; clear H; simpl_red;\n    try (\n      assert (Hsj: exists sj, SJ t (vs,es) sj) by eauto;\n      destruct Hsj as (sj, Hsj)\n    ).\n    - eapply CG.cg_init in H3; eauto.\n      exists (Nil ::  sj).\n      eauto using sj_init.\n    - eapply CG.cg_fork in H3; eauto.\n      exists (Copy nx :: Cons y nx :: sj).\n      eauto using sj_fork.\n    - eapply CG.cg_join in H3; eauto.\n      exists (Append nx ny :: sj).\n      eapply sj_join; eauto.\n      inversion H10; subst.\n      unfold FGraph.Edge in *.\n      eapply sj_edge_to_knows_0 in H2; eauto.\n      inversion H2; subst.\n      simpl_node.\n    - eapply CG.cg_continue in H3; eauto.\n      exists (Copy prev :: sj).\n      eauto using sj_continue.\n  Qed.\n\n  (** Main theorem part 2: from an annotated CG+SJ we can build a\n  trace-valid SJ. *)\n\n  Let sj_to_events_sj_0:\n    forall t sj cg,\n    CG.CG t cg ->\n    SJ t cg sj ->\n    exists k, Events.SJ t k.\n  Proof.\n    induction t; intros. {\n      inversion H; subst; clear H.\n      inversion H0; subst; clear H0.\n      eauto using Events.sj_nil.\n    }\n    inversion H; subst; clear H;\n    inversion H0; subst; clear H0; simpl_red.\n    - apply IHt in H2; eauto using sj_to_cg; destruct H2 as (k, Hk).\n      eauto using Events.sj_init.\n    - assert (Hsj := H16).\n      apply IHt in H16; eauto using sj_to_cg; destruct H16 as (k, Hk).\n      assert (exists k', CheckOp k (SJ_Notations.F x y) k'). {\n        exists (fork x y k).\n        apply check_fork.\n        - unfold not; intros; subst.\n          apply maps_to_to_in in H5.\n          contradiction.\n        - unfold not; intros N.\n          destruct N as (e, (?,He)).\n          unfold FGraph.Edge in *.\n          destruct e as (a,b).\n          inversion He; simpl in *; subst.\n          + eapply sj_edge_to_knows_0 in H0; eauto.\n            apply knows_to_in_l in H0.\n            contradiction.\n          + eapply sj_edge_to_knows_0 in H0; eauto.\n            eapply knows_to_in_r in H0; eauto.\n      }\n      destruct H0 as (k', ?).\n      eauto using Events.sj_fork.\n    - assert (Hsj := H15).\n      apply IHt in Hsj; eauto using sj_to_cg.\n      destruct Hsj as (k, ?); auto.\n      assert (Hk: exists k', CheckOp k (SJ_Notations.J x ty) k'). {\n        exists (join x ty k).\n        apply check_join.\n        assert (Hk: Knows vs sj0 (x, ty)) by eauto using knows_def.\n        eapply sj_to_knows_to_edge_0 in Hk; eauto.\n      }\n      destruct Hk as (k', Hk).\n      eauto using Events.sj_join.\n    - apply IHt in H10; eauto using sj_to_cg; destruct H10 as (k, Hk).\n      eauto using Events.sj_continue.\n  Qed.\n\n  Theorem sj_to_events_sj:\n    forall t sj cg,\n    SJ t cg sj ->\n    exists k, Events.SJ t k.\n  Proof.\n    eauto using sj_to_cg.\n  Qed.\n\n  Theorem hb_spec:\n    forall t cg n1 n2 x sj,\n    SJ t cg sj ->\n    CanJoin n1 x sj ->\n    CG.HB (snd cg) n1 n2 ->\n    CanJoin n2 x sj.\n  Proof.\n    intros.\n    eapply incl_hb; eauto.\n    assert (Hsj: exists k, Events.SJ t k). {\n      eapply sj_to_events_sj; eauto.\n    }\n    destruct Hsj as (k, Hsj).\n    eauto using sj_to_incl.\n  Qed.\n  \nEnd SJ.\n\nSection Alt.\n(*\n  Let sj_fresh_rw:\n    forall vs es k sj,\n    SJ (vs, es) k sj ->\n    fresh vs = fresh sj.\n  Proof.\n    intros.\n    inversion H.\n    simpl in *.\n    auto using maps_to_length_rw.\n  Qed.\n*)\n\n  Let can_join_to_node_0:\n    forall n x sj,\n    CanJoin n x sj ->\n    Node n sj.\n  Proof.\n    intros.\n    induction H; auto using node_cons, node_eq.\n  Qed.\n\n  Lemma sj_can_join_to_node:\n    forall t vs es sj x n,\n    SJ t (vs,es) sj ->\n    CanJoin n x sj ->\n    Node n vs.\n  Proof.\n    intros.\n    apply can_join_to_node_0 in H0.\n    apply node_tr with (a:=sj); auto.\n    symmetry.\n    eauto using sj_to_length_0.\n  Qed.\n\n  Let fresh_absurd_eq:\n    forall {A} vs (x:A),\n     ~ fresh vs = fresh (x :: vs).\n  Proof.\n    induction vs; intros. {\n      unfold not; intros N.\n      inversion N.\n    }\n    unfold fresh in *.\n    simpl in *.\n    unfold not; intros N.\n    inversion N.\n    omega.\n  Qed.\n\n  Inductive HBCanJoin t (cg:CG.computation_graph) : node -> tid -> Prop :=\n  | hb_can_join_hb:\n    forall y nx ny,\n    CG.SpawnPoint y ny t cg ->\n    CG.HB (snd cg) ny nx ->\n    HBCanJoin t cg nx y\n  | hb_can_join_eq:\n    forall y n,\n    CG.SpawnPoint y n t cg ->\n    HBCanJoin t cg n y.\n\n  Let hb_can_join_neq:\n    forall vs es n x y e e' z t,\n    x <> y ->\n    HBCanJoin t (vs, es) n x ->\n    HBCanJoin ((z, CG.FORK y)::t) (y :: z:: vs, CG.F e :: CG.C e' :: es) n x.\n  Proof.\n    intros.\n    inversion H0; subst; clear H0;\n    simpl in *;\n    eauto using hb_can_join_hb, hb_can_join_eq, CG.spawn_point_neq, CG.hb_impl_cons.\n  Qed.\n\n  Let hb_can_join_continue:\n    forall vs es n z y e t,\n    HBCanJoin t (vs, es) n z ->\n    HBCanJoin ((y,CG.CONTINUE)::t) (y :: vs, CG.C e :: es) n z.\n  Proof.\n    intros.\n    inversion H; subst; clear H;\n    simpl in *;\n    eauto using hb_can_join_hb, hb_can_join_eq, CG.spawn_point_continue, CG.hb_impl_cons.\n  Qed.\n\n  Let hb_can_join_join:\n    forall vs es n x y z e e' t,\n    HBCanJoin t (vs, es) n z ->\n    HBCanJoin ((x,CG.JOIN y)::t) (x :: vs, CG.J e :: CG.C e' :: es) n z.\n  Proof.\n    intros.\n    inversion H; subst; clear H;\n    simpl in *;\n    eauto using hb_can_join_hb, hb_can_join_eq, CG.spawn_point_join, CG.hb_impl_cons.\n  Qed.\n\n  Let hb_can_join_spawn:\n    forall n x y vs es t,\n    ~ List.In y vs ->\n    MapsTo x n vs ->\n    HBCanJoin ((x, CG.FORK y)::t) (y :: x :: vs, CG.F (n, fresh (x :: vs)) :: CG.C (n, fresh vs) :: es) (fresh vs) y.\n  Proof.\n    auto using CG.spawn_point_eq, CG.spawn_point_eq, CG.spawn_point_continue, hb_can_join_eq.\n  Qed.\n\n  Let hb_can_join_trans:\n    forall t cg n n' x,\n    HBCanJoin t cg n x ->\n    CG.HB (snd cg) n n' ->\n    HBCanJoin t cg n' x.\n  Proof.\n    intros.\n    inversion H; subst; clear H;\n    eauto using hb_can_join_hb, CG.hb_trans.\n  Qed.\n\n  Let spawn_point_absurd_nil:\n    forall x n cg,\n    ~ CG.SpawnPoint x n nil cg.\n  Proof.\n    unfold not; intros.\n    inversion H.\n  Qed.\n\n  Let spawn_point_cons:\n    forall x n vs es y e' e z t,\n    CG.SpawnPoint x n t (vs, es) ->\n    CG.SpawnPoint x n ((y, CG.JOIN z)::t) (y :: vs, CG.J e' :: CG.C e :: es).\n  Proof.\n    auto using CG.spawn_point_join.\n  Qed.\n\n  Let hb_can_join_cons:\n    forall vs es n x e' e y t z,\n    HBCanJoin t (vs, es) n x ->\n    HBCanJoin ((y, CG.JOIN z)::t) (y :: vs, CG.J e' :: CG.C e :: es) n x.\n  Proof.\n    intros.\n    inversion H; subst; clear H; simpl in *. {\n      eauto using CG.hb_cons, hb_can_join_hb.\n    }\n    auto using hb_can_join_eq.\n  Qed.\n\n  Let hb_can_join_cons_c:\n    forall vs es a b y x t,\n    HBCanJoin t (vs, es) a x ->\n    HBCanJoin ((y, CG.CONTINUE)::t) (y :: vs, CG.C (a, b) :: es) b x.\n  Proof.\n    intros.\n    inversion H; subst; clear H. {\n      simpl in *.\n      apply hb_can_join_hb with (ny:=ny).\n      + eauto using CG.spawn_point_continue.\n      + simpl in *.\n        remember ((_,_)::es) as es'.\n        assert (CG.HB es' ny a) by (subst; auto using CG.hb_cons).\n        assert (CG.HB es' a b) by (subst;auto using CG.edge_to_hb).\n        eauto using CG.hb_trans.\n    }\n    apply hb_can_join_hb with (ny:=a); simpl;\n    auto using CG.spawn_point_continue, CG.edge_to_hb.\n  Qed.\n(*\n  Let hb_can_join_cons_j:\n    forall vs es a b y x t z,\n    HBCanJoin t (y :: vs, es) a x ->\n    HBCanJoin ((z, CG.JOIN y)::t) (y :: vs, CG.J (a, b) :: es) b x.\n  Proof.\n    intros.\n    inversion H; subst; clear H. {\n      simpl in *.\n      apply hb_can_join_hb with (ny:=ny).\n      + eapply CG.spawn_point_join.\n      + simpl in *.\n        remember ((_,_)::es) as es'.\n        assert (CG.HB es' ny a) by (subst; auto using CG.hb_cons).\n        assert (CG.HB es' a b) by (subst;auto using CG.edge_to_hb).\n        eauto using CG.hb_trans.\n    }\n    apply hb_can_join_hb with (ny:=a); simpl;\n    auto using CG.spawn_point_join, CG.edge_to_hb.\n  Qed.\n*)\n\n  Let hb_can_join_cons_v:\n    forall vs es n x z t,\n    ~ List.In x vs ->\n    HBCanJoin t (vs, es) n z ->\n    HBCanJoin ((x,CG.INIT)::t) (x :: vs, es) n z.\n  Proof.\n    intros.\n    inversion H0; subst; clear H0; simpl in *. {\n      apply hb_can_join_hb with (ny:=ny); simpl; auto using CG.spawn_point_init.\n    }\n    auto using CG.spawn_point_init, hb_can_join_eq.\n  Qed.\n\n  Let spawn_point_to_edge:\n    forall t es x n vs,\n    CG.SpawnPoint x n t (vs, es) ->\n    exists n', List.In (CG.C (n', n)) es.\n  Proof.\n    induction t; intros. {\n      inversion H; subst.\n    }\n    inversion H; subst; clear H.\n    - eauto.\n    - exists n'.\n      auto using in_eq, in_cons.\n    - apply IHt in H5.\n      destruct H5 as (nx, Hi).\n      eauto using in_cons.\n    - apply IHt in H1.\n      destruct H1 as (nx, Hi).\n      eauto using in_cons.\n    - apply IHt in H1.\n      destruct H1 as (nx, Hi).\n      eauto using in_cons.\n  Qed.\n\n  Let spawn_point_to_node:\n    forall es x n vs t,\n    CG.CG t (vs, es) ->\n    CG.SpawnPoint x n t (vs, es) ->\n    Node n vs.\n  Proof.\n    intros.\n    apply spawn_point_to_edge in H0.\n    destruct H0 as (n0, He).\n    assert (Hx: CG.HB_Edge es (n0, n)). {\n      eauto using CG.hb_edge_def, CG.edge_eq.\n    }\n    eauto using CG.cg_hb_edge_to_node_r.\n  Qed.\n\n  Let hb_can_join_to_node:\n    forall t vs es n x,\n    CG.CG t (vs, es) ->\n    HBCanJoin t (vs, es) n x ->\n    Node n vs.\n  Proof.\n    intros.\n    inversion H0; subst; clear H0; simpl in *. {\n      eapply CG.hb_to_node_snd with (vs:=vs) in H2; eauto.\n    }\n    eauto using spawn_point_to_node.\n  Qed.\n(*\n  Let hb_absurd_fresh_lhs:\n    forall nx x (vs:list tid) es (n:node),\n    DAG (FGraph.Edge (cg_edges (F (nx, node_next (fresh vs)) :: C (nx, fresh vs) :: es))) ->\n    EdgeToNode (vs, es) ->\n    MapsTo x nx vs ->\n    ~ HB (F (nx, node_next (fresh vs)) :: C (nx, fresh vs) :: es) (fresh vs) n.\n  Proof.\n    intros.\n    assert (Ha : DAG (FGraph.Edge (cg_edges (C (nx, fresh vs) :: es)))) by\n    eauto using f_dag_inv_cons.\n    assert (Hb : DAG (FGraph.Edge (cg_edges es))) by\n    eauto using f_dag_inv_cons.\n    unfold not; intros N.\n    apply hb_inv_cons in N; auto.\n    destruct N as [Hy|[(?,[?|Hy])|[(?,Hy)|(Hy,?)]]]; subst;\n    simpl_node; auto;\n    apply hb_inv_cons in Hy; auto;\n    destruct Hy as [Hx|[(?,[?|Hx])|[(?,Hx)|(Hx,?)]]]; subst; simpl_node;\n    hb_simpl.\n  Qed.\n*)\n  (* -------------------------------------- *)\n\n(*\n\n\n  Let spawn_point_to_in:\n    forall es vs x n t,\n    CG.SpawnPoint x n t (vs, es) ->\n    List.In x vs.\n  Proof.\n    induction es; intros. {\n      apply spawn_point_absurd_nil in H.\n      contradiction.\n    }\n    inversion H; subst; clear H; eauto using in_cons, in_eq.\n  Qed.\n\n  Let hb_can_join_to_in:\n    forall vs es n x,\n    HBCanJoin (vs, es) n x ->\n    List.In x vs.\n  Proof.\n    intros.\n    inversion H; subst; clear H; eauto.\n  Qed.\n\n\n  Notation KnowsEquiv1 sj cg :=\n  (forall n x, CanJoin n x sj -> HBCanJoin cg n x).\n\n  Let KnowsEquiv2 sj cg :=\n  (forall n x, HBCanJoin cg n x -> CanJoin n x sj).\n\n  Definition FirstHB (cg:CG.computation_graph) :=\n    forall x n1 n2,\n    First x n1 (fst cg) ->\n    MapsTo x n2 (fst cg) ->\n    n1 <> n2 ->\n    CG.HB (snd cg) n1 n2.\n\n  Let can_join_pres_fork:\n    forall n cg sj z sj' cg' x y,\n    length (fst cg) = length sj ->\n    KnowsEquiv1 sj cg ->\n    CG.Reduces cg (x, CG.FORK y) cg' ->\n    Reduces sj (x, CG.FORK y) cg' sj' ->\n    CanJoin n z sj' ->\n    HBCanJoin cg' n z.\n  Proof.\n    intros.\n    simpl_red.\n    rename prev into nz.\n    rename H0 into Hind.\n    rename H into Heq.\n    inversion H3; subst; clear H3; simpl in *. {\n      inversion H2; subst; clear H2; simpl in *.\n      - apply Hind in H3.\n        assert (z <> y). {\n          unfold not; intros N; subst.\n          apply hb_can_join_to_in in H3.\n          contradiction.\n        }\n        auto.\n      - apply maps_to_length_rw in Heq.\n        rewrite <- Heq in *.\n        auto.\n      - apply Hind in H4.\n        apply maps_to_length_rw in Heq.\n        rewrite <- Heq in *.\n        apply hb_can_join_trans with (n:=nz); simpl; auto.\n        eauto using hb_edge_to_hb, hb_edge_def, edge_eq, in_cons, in_eq.\n    }\n    apply can_join_inv_cons_2 in H2.\n    assert (R: length (x :: vs) = length (Cons y nz :: sj)) by (simpl; auto).\n    apply maps_to_length_rw in R.\n    rewrite <- R.\n    destruct H2 as [(?,Hc)|[(?,Hc)|(?,?)]]; subst.\n    - apply Hind in Hc.\n      apply hb_can_join_to_in in Hc.\n      contradiction.\n    - apply Hind in Hc.\n      apply hb_can_join_trans with (n:=nz); simpl;\n      eauto using hb_edge_to_hb, hb_edge_def, edge_eq, in_cons, in_eq.\n    - apply maps_to_length_rw in Heq.\n      rewrite <- Heq in *.\n      simpl_node.\n  Qed.\n\n  Let can_join_pres_join:\n    forall n cg sj z sj' cg' x y,\n    length (fst cg) = length sj ->\n    KnowsEquiv1 sj cg ->\n    CG.Reduces cg (x, CG.JOIN y) cg' ->\n    Reduces sj (x, CG.JOIN y) cg' sj' ->\n    CanJoin n z sj' ->\n    HBCanJoin cg' n z.\n  Proof.\n    intros.\n    simpl_red.\n    rename prev into nz.\n    rename H0 into Hind.\n    rename H into Heq.\n    apply Hind in H19.\n    apply maps_to_length_rw in Heq.\n    inversion H3; subst; clear H3; simpl in *;\n          try rewrite <- Heq; auto.\n  Qed.\n\n  Let can_join_pres_continue:\n    forall n cg sj z sj' cg' x,\n    length (fst cg) = length sj ->\n    KnowsEquiv1 sj cg ->\n    CG.Reduces cg (x, CG.CONTINUE) cg' ->\n    Reduces sj (x, CG.CONTINUE) cg' sj' ->\n    CanJoin n z sj' ->\n    HBCanJoin cg' n z.\n  Proof.\n    intros.\n    simpl_red.\n    rename prev into nz.\n    rename H0 into Hind.\n    rename H into Heq.\n    simpl in *.\n    apply maps_to_length_rw in Heq.\n    inversion H3; subst; clear H3; simpl in *;\n    try rewrite Heq; auto.\n  Qed.\n\n  Let can_join_pres_init:\n    forall n cg sj z sj' cg' x,\n    length (fst cg) = length sj ->\n    KnowsEquiv1 sj cg ->\n    CG.Reduces cg (x, CG.INIT) cg' ->\n    Reduces sj (x, CG.INIT) cg' sj' ->\n    CanJoin n z sj' ->\n    HBCanJoin cg' n z.\n  Proof.\n    intros.\n    simpl_red.\n    rename H0 into Hind.\n    rename H into Heq.\n    simpl in *.\n    apply maps_to_length_rw in Heq.\n    inversion H3; subst; clear H3; simpl in *.\n    apply Hind in H2.\n    try rewrite Heq; auto.\n  Qed.\n\n  Let can_join_pres_fork_2 cg k sj\n    (Hsj: SJ cg k sj)\n    (Heq: length (fst cg) = length sj)\n    (Hke: KnowsEquiv2 sj cg)\n    (Hen: EdgeToNode cg)\n    sj' cg' x y\n    (Hcr: CG.Reduces cg (x, CG.FORK y) cg')\n    (Hr: Reduces sj (x, CG.FORK y) cg' sj')\n    (Hd: DAG (FGraph.Edge (cg_edges (snd cg')))):\n    forall n z,\n    HBCanJoin cg' n z ->\n    CanJoin n z sj'.\n  Proof.\n    intros.\n    simpl_red.\n    inversion H; subst; clear H;\n    simpl in *. {\n      rename ny0 into nz.\n      rewrite fresh_cons_rw_next in *.\n      clear nx; rename prev into nx.\n      apply maps_to_length_rw in Heq.\n      inversion H0; subst; clear H0. {\n        eapply hb_absurd_fresh_lhs in H1; eauto.\n        contradiction.\n      }\n      inversion H9; subst; clear H9. (* SpawnPoint *)\n      assert (Hc: HBCanJoin (vs, es) nz z). {\n        auto using hb_can_join_eq.\n      }\n      apply hb_inv_cons in H1; auto.\n      apply f_dag_inv_cons in Hd.\n      destruct H1 as [Hy|[(?,[?|Hy])|[(?,Hy)|(?,Hy)]]]; subst;\n      try rewrite Heq.\n      - apply Hke in Hc.\n        apply hb_inv_cons in Hy; auto.\n        destruct Hy as [Hx|[(?,[?|Hx])|[(?,Hx)|(Hx,?)]]]; subst; try (rewrite Heq);\n        eauto using hb_spec, can_join_cons, can_join_neq; hb_simpl.\n      - rewrite <- fresh_cons_rw_next with (x:=Cons y nz).\n        assert (Hc0: HBCanJoin (vs, es) nz z). {\n          auto using hb_can_join_eq .\n        }\n        auto using can_join_copy, can_join_cons.\n      - apply hb_inv_cons in Hy; auto.\n        rewrite <- fresh_cons_rw_next with (x:=Cons y nx).\n        apply can_join_copy.\n        destruct Hy as [Hx|[(?,[?|Hx])|[(?,Hx)|(Hx,?)]]]; subst;\n        simpl_node; hb_simpl;\n        eauto using hb_can_join_hb, can_join_cons.\n      - apply hb_inv_cons in Hy; auto.\n        destruct Hy as [Hx|[(?,[?|Hx])|[(?,Hx)|(Hx,?)]]]; subst; try (rewrite Heq);\n        simpl_node; hb_simpl.\n      - apply hb_inv_cons in Hy; auto.\n        destruct Hy as [Hx|[(?,[?|Hx])|[(?,Hx)|(Hx,?)]]]; subst; try (rewrite Heq);\n        simpl_node; hb_simpl.\n    }\n    apply maps_to_length_rw in Heq.\n    inversion H0; subst; clear H0. {\n      rewrite Heq.\n      apply can_join_cons.\n      apply can_join_eq.\n    }\n    inversion H8; subst; clear H8.\n    assert (Hc: HBCanJoin (vs,es) n z). {\n      auto using hb_can_join_eq.\n    }\n    apply Hke in Hc.\n    auto using can_join_cons, can_join_neq.\n  Qed.\n\n  Let can_join_pres_join_2 cg k sj\n    (Hsj: SJ cg k sj)\n    (Heq: length (fst cg) = length sj)\n    (Hke: KnowsEquiv2 sj cg)\n    (Hen: EdgeToNode cg)\n    sj' cg' x y\n    (Hcr: CG.Reduces cg (x, CG.JOIN y) cg')\n    (Hr: Reduces sj (x, CG.JOIN y) cg' sj')\n    (Hd: DAG (FGraph.Edge (cg_edges (snd cg')))):\n    forall n z,\n    HBCanJoin cg' n z ->\n    CanJoin n z sj'.\n  Proof.\n    intros.\n    simpl_red.\n    inversion H; subst; clear H;\n    simpl in *. {\n      rename ny0 into c.\n      rename prev into a.\n      rename ny into b.\n      apply maps_to_length_rw in Heq.\n      inversion H0; subst; clear H0.\n      inversion H3; subst; clear H3.\n      apply hb_inv_cons in H1; auto.\n      apply f_dag_inv_cons in Hd.\n      destruct H1 as [Hy|[(?,[?|Hy])|[(?,Hy)|(Hy,?)]]]; subst.\n      + apply hb_inv_cons in Hy; auto.\n        destruct Hy as [Hx|[(?,[?|Hx])|[(?,Hx)|(Hx,?)]]]; subst;\n        try rewrite Heq;\n        hb_simpl;\n        eauto using\n          can_join_append_right, can_join_append_left,\n          hb_can_join_hb, can_join_cons, hb_can_join_eq.\n      + rewrite Heq.\n        eauto using\n          can_join_append_right, can_join_append_left,\n          hb_can_join_hb, can_join_cons, hb_can_join_eq.\n      + apply hb_inv_cons in Hy; auto.\n        destruct Hy as [Hx|[(?,[?|Hx])|[(?,Hx)|(Hx,?)]]]; subst;\n        try rewrite Heq;\n        hb_simpl;\n        eauto using\n          can_join_append_right, can_join_append_left,\n          hb_can_join_hb, can_join_cons, hb_can_join_eq.\n      + apply hb_inv_cons in Hy; auto.\n        destruct Hy as [Hx|[(?,[?|Hx])|[(?,Hx)|(Hx,?)]]]; subst;\n        try rewrite Heq;\n        hb_simpl; simpl_node.\n      + apply hb_inv_cons in H; auto.\n        destruct H as [Hx|[(?,[?|Hx])|[(?,Hx)|(Hx,?)]]]; subst;\n        try rewrite Heq;\n        hb_simpl; simpl_node.\n    }\n    inversion H0; subst; clear H0.\n    inversion H1; subst; clear H1.\n    eauto using\n      can_join_append_right, can_join_append_left,\n      hb_can_join_hb, can_join_cons, hb_can_join_eq.\n  Qed.\n\n  Let can_join_pres_continue_2 cg k sj\n    (Hsj: SJ cg k sj)\n    (Heq: length (fst cg) = length sj)\n    (Hke: KnowsEquiv2 sj cg)\n    (Hen: EdgeToNode cg)\n    sj' cg' x\n    (Hcr: CG.Reduces cg (x, CG.CONTINUE) cg')\n    (Hr: Reduces sj (x, CG.CONTINUE) cg' sj')\n    (Hd: DAG (FGraph.Edge (cg_edges (snd cg')))):\n    forall n z,\n    HBCanJoin cg' n z ->\n    CanJoin n z sj'.\n  Proof.\n    intros.\n    simpl_red.\n    inversion H; subst; clear H;\n    simpl in *. {\n      apply maps_to_length_rw in Heq.\n      inversion H0; subst; clear H0.\n      apply hb_inv_cons in H2; auto.\n      destruct H2 as [Hy|[(?,[?|Hy])|[(?,Hy)|(Hy,?)]]]; subst;\n      try rewrite Heq;\n      hb_simpl;\n      eauto using\n          can_join_copy,\n          hb_can_join_hb, can_join_cons, hb_can_join_eq.\n    }\n    inversion H0; subst; clear H0.\n    eauto using\n        can_join_copy,\n        hb_can_join_hb, can_join_cons, hb_can_join_eq.\n  Qed.\n\n  Definition KnowsEquiv sj cg :=\n  forall n x, CanJoin n x sj <-> HBCanJoin cg n x.\n\n  Let knows_equiv_to_1:\n    forall sj cg,\n    KnowsEquiv sj cg ->\n    KnowsEquiv1 sj cg.\n  Proof.\n    intros.\n    apply H in H0.\n    assumption.\n  Qed.\n\n  Let knows_equiv_to_2:\n    forall sj cg,\n    KnowsEquiv sj cg ->\n    KnowsEquiv2 sj cg.\n  Proof.\n    unfold KnowsEquiv2.\n    intros.\n    apply H in H0.\n    assumption.\n  Qed.\n\n  Theorem hb_can_join_preserves cg k sj\n    (Hsj: SJ cg k sj)\n    (Hke: KnowsEquiv sj cg)\n    (Hlt: LtEdges (cg_edges (snd cg))):\n    forall i sj' cg',\n    CG.Reduces cg i cg' ->\n    Reduces sj i cg' sj' ->\n    KnowsEquiv sj' cg'.\n  Proof.\n    intros.\n    unfold KnowsEquiv.\n    intros.\n    destruct i.\n    assert (Hlt2: LtEdges (cg_edges (snd cg'))) by eauto using lt_edges_reduces.\n    apply cg_dag in Hlt2.\n    inversion Hsj.\n    split; intros.\n    + destruct o.\n      * \n      * eapply can_join_pres_fork; eauto.\n      * eapply can_join_pres_join; eauto.\n      * eapply can_join_pres_continue; eauto.\n    + destruct o.\n      * eapply can_join_pres_fork_2; eauto.\n      * eapply can_join_pres_join_2; eauto.\n      * eapply can_join_pres_continue_2; eauto.\n  Qed.\n\n  Lemma sj_make_cg:\n    forall a,\n    SJ (make_cg a) nil (Nil :: nil).\n  Proof.\n    intros.\n    apply sj_def; auto using make_edge_to_node; unfold make_cg; simpl; auto\n    using free_in_graph_nil, knows_to_edge_nil, incl_nil, edge_to_knows_nil.\n  Qed.\n\n  Lemma knows_equiv_nil:\n    forall a,\n    KnowsEquiv (Nil :: nil) (make_cg a).\n  Proof.\n    intros.\n    unfold KnowsEquiv.\n    split; intros.\n    - inversion H; subst; clear H.\n      inversion H3; subst; clear H3.\n    - inversion H; subst; clear H. {\n        inversion H0.\n      }\n      inversion H0.\n  Qed.\n\n  (** Build a SJ from a CG *)\n\n  Let sj_spec:\n    forall a t cg k,\n    CG.CG t cg ->\n    Events.SJ t k ->\n    exists sj, SJ cg k sj /\\ KnowsEquiv sj cg.\n  Proof.\n    induction t; intros. {\n      inversion H; subst; clear H.\n      inversion H0; subst; clear H0.\n      eauto using sj_make_cg, knows_equiv_nil.\n    }\n    inversion H; subst; clear H.\n    assert (Hcg := H3).\n    inversion H0; subst; clear H0.\n    eapply IHt in H3; eauto.\n    destruct H3 as (sj, (Hsj,Hk)).\n    assert (Hr: exists sj', Reduces sj a0 cg sj'). {\n      inversion Hsj.\n      eauto.\n    }\n    destruct Hr as (sj', Hr).\n    apply CG.run_to_lt_edges in Hcg.\n    eauto using sj_reduces, hb_can_join_preserves.\n  Qed.\n  *)\nEnd Alt.\n\n", "meta": {"author": "cogumbreiro", "repo": "gorn-coq", "sha": "ee4384d7ae8513c314ffb25027c4249903c6275b", "save_path": "github-repos/coq/cogumbreiro-gorn-coq", "path": "github-repos/coq/cogumbreiro-gorn-coq/gorn-coq-ee4384d7ae8513c314ffb25027c4249903c6275b/src/SJ_CG.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.4687906266262438, "lm_q1q2_score": 0.29352114538869767}}
{"text": "(*\nCopyright © 2020 Vincent Semeria\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*)\n\n\nRequire Import QArith.\nRequire Import ConstructiveReals.\nRequire Import ConstructiveAbs.\nRequire Import ConstructiveMinMax.\nRequire Import ConstructiveSum.\nRequire Import ConstructivePower.\nRequire Import ConstructiveLimits.\nRequire Import ConstructivePartialFunctions.\nRequire Import CMTbase.\nRequire Import CMTIntegrableFunctions.\nRequire Import CMTFullSets.\nRequire Import CMTIntegrableSets.\nRequire Import CMTprofile.\n\nLocal Open Scope ConstructiveReals.\n\n\n(* A function f is measurable when it is integrable on any\n   integrable rectangle A * [-k,k]. *)\nDefinition MeasurableFunction {IS : IntegrationSpace}\n           (f : PartialFunction (X (ElemFunc IS))) : Type\n  := forall (A : (X (ElemFunc IS)) -> Prop) (k : positive),\n    IntegrableSet A\n    -> IntegrableFunction (XmaxConst (XminConst (Xmult (CharacFunc A) f)\n                                               (CR_of_Q _ (Z.pos k # 1)))\n                                    (CR_of_Q _ (Z.neg k # 1))).\n\nLemma MeasurableFunctionExtensional\n  : forall {IS : IntegrationSpace}\n           (f g : PartialFunction (X (ElemFunc IS))),\n    PartialRestriction f g\n    -> MeasurableFunction f\n    -> MeasurableFunction g.\nProof.\n  intros IS f g [d c] fMes A k Aint.\n  apply (IntegrableFunctionExtensional\n           (XmaxConst (XminConst (Xmult (CharacFunc A) f)\n                                 (CR_of_Q (RealT (ElemFunc IS)) (Z.pos k # 1)))\n                      (CR_of_Q (RealT (ElemFunc IS)) (Z.neg k # 1)))).\n  2: exact (fMes A k Aint).\n  split.\n  - intros x xdf. simpl in xdf. destruct xdf.\n    split. exact s. exact (d x d0).\n  - intros. simpl. destruct xD, xG.\n    rewrite (c x d1 (d x d1)), (DomainProp g x (d x d1) d3).\n    destruct d0. destruct d2. reflexivity. contradiction.\n    destruct d2. contradiction. reflexivity.\nQed.\n\nLemma MeasurableFunctionFull\n  : forall {IS : IntegrationSpace}\n      (f : PartialFunction (X (ElemFunc IS))),\n    MeasurableFunction f\n    -> almost_everywhere (Domain f).\nProof.\n  intros IS f fMes.\n  destruct (@PositiveMeasureSubsetExists IS) as [A Aint Apos].\n  specialize (fMes A 1%positive Aint).\n  exists (XmaxConst (XminConst (Xmult (CharacFunc A) f) (CR_of_Q (RealT (ElemFunc IS)) 1))\n              (CR_of_Q (RealT (ElemFunc IS)) (-1))).\n  split. exact fMes.\n  intros x xD. apply xD.\nQed.\n\nLemma IntegrableMeasurable\n  : forall {IS : IntegrationSpace}\n      (f : PartialFunction (X (ElemFunc IS))),\n    IntegrableFunction f\n    -> MeasurableFunction f.\nProof.\n  intros IS f fInt A k Aint. \n  apply IntegrableMaxConst. apply IntegrableMinConst.\n  exact (RestrictedIntegrable fInt Aint).\n  apply CR_of_Q_pos. reflexivity.\n  apply (CRlt_le_trans _ (CR_of_Q _ 0)). apply CR_of_Q_lt. reflexivity.\n  apply CRle_refl.\nQed.\n\nLemma MeasurableConst\n  : forall {IS : IntegrationSpace}\n      (a : CRcarrier (RealT (ElemFunc IS))),\n    MeasurableFunction (Xconst (X (ElemFunc IS)) a).\nProof.\n  intros IS a A k Aint. apply IntegrableMaxConst.\n  apply IntegrableMinConst.\n  apply (IntegrableFunctionExtensional (Xscale a (CharacFunc A))).\n  - split. intros x xdf.\n    split. exact xdf. simpl. trivial. intros. simpl.\n    destruct xG. destruct xD. destruct d. apply CRmult_comm.\n    contradiction. destruct d. contradiction. apply CRmult_comm.\n  - apply IntegrableScale, Aint.\n  - apply CR_of_Q_lt. reflexivity.\n  - apply CR_of_Q_lt. reflexivity.\nQed.\n\nDefinition MeasurableSet {IS : IntegrationSpace}\n           (A : (X (ElemFunc IS)) -> Prop) : Type\n  := MeasurableFunction (CharacFunc A).\n\nLemma MeasurableSetEquiv\n  : forall {IS : IntegrationSpace}\n      (A : (X (ElemFunc IS)) -> Prop),\n    prod (MeasurableSet A\n          -> (forall B : (X (ElemFunc IS)) -> Prop,\n                IntegrableSet B -> IntegrableFunction (Xmult (CharacFunc A) (CharacFunc B))))\n         ((forall B : (X (ElemFunc IS)) -> Prop,\n                IntegrableSet B -> IntegrableFunction (Xmult (CharacFunc A) (CharacFunc B))) -> MeasurableSet A).\nProof.\n  intros IS A.\n  assert (forall B x xD xG k,\n             partialApply (Xmult (CharacFunc A) (CharacFunc B)) x xD ==\n  partialApply\n    (XmaxConst\n       (XminConst (Xmult (CharacFunc B) (CharacFunc A))\n          (CR_of_Q (RealT (ElemFunc IS)) (Z.pos k # 1)))\n       (CR_of_Q (RealT (ElemFunc IS)) (Z.neg k # 1))) x xG).\n  { intros. rewrite applyXmaxConst, CRmax_left.\n    rewrite applyXminConst, CRmin_left. destruct xD, xG.\n    simpl. destruct d. destruct d2. 2: contradiction.\n    destruct d0. destruct d1. 2: contradiction. reflexivity.\n    destruct d1. contradiction. apply CRmult_comm.\n    rewrite CRmult_0_l. destruct d2. contradiction.\n    rewrite CRmult_0_r. reflexivity.\n    apply (CRle_trans _ 1). simpl. destruct xG.\n    destruct d. destruct d0. rewrite CRmult_1_l. apply CRle_refl.\n    rewrite CRmult_1_l. apply CRlt_asym, CRzero_lt_one. rewrite CRmult_0_l.\n    apply CRlt_asym, CRzero_lt_one. \n    apply CR_of_Q_le. unfold Qle, Qnum, Qden. rewrite Z.mul_1_l, Z.mul_1_r.\n    destruct k; discriminate.\n    apply (CRle_trans _ 0). apply CR_of_Q_le. discriminate.\n    apply CRmin_glb. simpl. destruct xG, d. rewrite CRmult_1_l.\n    destruct d0. apply CRlt_asym, CRzero_lt_one. apply CRle_refl.\n    rewrite CRmult_0_l. apply CRle_refl. apply CR_of_Q_le. discriminate. }\n  split.\n  - intros Ames B Bint. specialize (Ames B 1%positive Bint).\n    refine (IntegrableFunctionExtensional _ _ _ Ames). split.\n    + intros x xdf. destruct xdf. split. exact d0. exact d.\n    + intros x xD xG. symmetry. apply H.\n  - intros H0 B k Bint. specialize (H0 B Bint).\n    refine (IntegrableFunctionExtensional _ _ _ H0). split.\n    + intros x xdf. destruct xdf. split. exact d0. exact d.\n    + intros x xD xG. apply H.\nQed.\n\n\nLemma IntegrableMeasurableSet\n  : forall {IS : IntegrationSpace}\n      (A : X (ElemFunc IS) -> Prop),\n    IntegrableSet A -> MeasurableSet A.\nProof.\n  intros IS A Aint B k Bint.\n  apply IntegrableMaxConst. apply IntegrableMinConst.\n  apply (IntegrableExtensionalAE (CharacFunc (fun x => B x /\\ A x))).\n  - exists (Xplus (CharacFunc A) (CharacFunc B)).\n    split. exact (IntegrablePlus _ _ Aint Bint).\n    intros. split. apply H. apply H.\n  - exists (CharacFunc A). split. exact Aint.\n    intros. simpl. destruct dG. clear H. destruct d0.\n    + (* In a *) rewrite CRmult_1_r.\n      destruct d, dF. reflexivity. contradict n. split; assumption.\n      destruct a0. contradiction. reflexivity.\n    + (* Not in a *) rewrite CRmult_0_r.\n      destruct dF. destruct a. contradiction. reflexivity.\n  - exact (IntegrableSetIntersect _ _ Bint Aint).\n  - apply CR_of_Q_pos. reflexivity.\n  - apply (CRlt_le_trans _ (CR_of_Q _ 0)).\n    apply CR_of_Q_lt. reflexivity. apply CRle_refl.\nQed.\n\n(* In finite integration spaces, like probability spaces, measurable is\n   equivalent to integrable. *)\nLemma MeasurableIntegrableSubset\n  : forall {IS : IntegrationSpace}\n      (A B : X (ElemFunc IS) -> Prop),\n    IntegrableSet B\n    -> MeasurableSet A\n    -> (forall x : X (ElemFunc IS), A x -> B x)\n    -> IntegrableSet A.\nProof.\n  intros IS A B Bint Ames incl.\n  specialize (Ames B 1%positive Bint).\n  refine (IntegrableFunctionExtensional _ _ _ Ames). split.\n  - intros x xdf. exact (snd xdf).\n  - intros. destruct xG.\n    + (* in A *)\n      simpl. destruct xD. destruct d.\n      2: contradict n; exact (incl x a). destruct d0.\n      rewrite CRmult_1_l, CRmin_left, CRmax_left. reflexivity.\n      apply CR_of_Q_le. discriminate.\n      apply CRle_refl. contradiction.\n    + (* not in A *)\n      simpl. destruct xD. destruct d0. contradiction.\n      rewrite CRmult_0_r, CRmin_left, CRmax_left. reflexivity.\n      apply CR_of_Q_le. discriminate.\n      apply CR_of_Q_le. discriminate.\nQed.\n\nLemma TruncOpp : forall {R : ConstructiveReals} (x : CRcarrier R) (k : positive),\n    - CRmax (CRmin x (CR_of_Q _ (Z.pos k # 1)))\n            (CR_of_Q _ (Z.neg k # 1))\n    == CRmax (CRmin (-x) (CR_of_Q _ (Z.pos k # 1)))\n             (CR_of_Q _ (Z.neg k # 1)).\nProof.\n  intros. destruct (CRltLinear R).\n  setoid_replace (-x) with (-(1) * x).\n  destruct (s (CR_of_Q R (Z.neg k # 1)) x 0).\n  apply CR_of_Q_lt. reflexivity.\n  rewrite CRmax_left, (CRmin_left (- (1) * x)).\n  - setoid_replace (CR_of_Q R (Z.neg k # 1))\n      with (-(1) * CR_of_Q R (Z.pos k # 1)).\n    rewrite CRmax_min_mult_neg. rewrite <- CRopp_mult_distr_l.\n    rewrite CRmult_1_l. reflexivity.\n    apply (CRplus_le_reg_l 1). rewrite CRplus_opp_r, CRplus_0_r.\n    apply CRlt_asym, CRzero_lt_one.\n    rewrite <- CRopp_mult_distr_l, CRmult_1_l, <- CR_of_Q_opp.\n    apply CR_of_Q_morph. reflexivity.\n  - rewrite <- CRopp_mult_distr_l, CRmult_1_l.\n    rewrite <- (CRopp_involutive (CR_of_Q R (Z.pos k # 1))).\n    apply CRopp_ge_le_contravar. rewrite <- CR_of_Q_opp.\n    apply (CRle_trans _ (CR_of_Q R (Z.neg k # 1))).\n    apply CR_of_Q_le. apply Qle_refl. apply CRlt_asym, c.\n  - apply CRmin_glb. apply CRlt_asym, c. apply CR_of_Q_le. discriminate.\n  - rewrite CRmin_left, (CRmax_left (CRmin (- (1) * x) (CR_of_Q R (Z.pos k # 1)))).\n    setoid_replace (CR_of_Q R (Z.pos k # 1))\n      with (-(1) * CR_of_Q R (Z.neg k # 1)).\n    rewrite CRmin_max_mult_neg, <- CRopp_mult_distr_l, CRmult_1_l. reflexivity.\n    apply (CRplus_le_reg_l 1). rewrite CRplus_opp_r, CRplus_0_r.\n    apply CRlt_asym, CRzero_lt_one.\n    rewrite <- CRopp_mult_distr_l, CRmult_1_l, <- CR_of_Q_opp.\n    apply CR_of_Q_morph. reflexivity.\n    apply CRmin_glb. apply (CRle_trans _ 0).\n    apply CR_of_Q_le. discriminate.\n    rewrite <- CRopp_mult_distr_l, CRmult_1_l, <- CRopp_0.\n    apply CRopp_ge_le_contravar, CRlt_asym, c.\n    apply CR_of_Q_le. discriminate.\n    apply (CRle_trans _ 0). apply CRlt_asym, c.\n    apply CR_of_Q_le. discriminate.\n  - rewrite <- CRopp_mult_distr_l, CRmult_1_l. reflexivity.\nQed.\n\nLemma TruncPosNeg : forall {R : ConstructiveReals} (y : CRcarrier R) (k : positive),\n   CRmax (CRmin (CRmax 0 y) (CR_of_Q R (Z.pos k # 1)))\n    (CR_of_Q R (Z.neg k # 1)) +\n  CRmax (CRmin (CRmin 0 y) (CR_of_Q R (Z.pos k # 1)))\n    (CR_of_Q R (Z.neg k # 1)) ==\n  CRmax (CRmin y (CR_of_Q R (Z.pos k # 1)))\n    (CR_of_Q R (Z.neg k # 1)).\nProof.\n  intros.\n  rewrite (CRmax_left (CRmin (CRmax 0 y) (CR_of_Q R (Z.pos k # 1)))).\n  rewrite (CRmin_left (CRmin 0 y)).\n  - destruct (CRltLinear R).\n    destruct (s (CR_of_Q R (Z.neg k # 1)) y 0).\n    + apply CR_of_Q_lt. reflexivity.\n    + rewrite (CRmax_left (CRmin y (CR_of_Q R (Z.pos k # 1)))).\n      rewrite (CRmax_left (CRmin 0 y)).\n      destruct (s 0 y (CR_of_Q R (Z.pos k # 1))).\n      apply CR_of_Q_lt. reflexivity.\n      rewrite CRmax_right, (CRmin_left 0 y). rewrite CRplus_0_r. reflexivity.\n      apply CRlt_asym, c0. apply CRlt_asym, c0.\n      rewrite (CRmin_left y), CRmin_left.\n      unfold CRmax, CRmin.\n      rewrite CRplus_0_l, <- CRmult_plus_distr_r.\n      unfold CRminus. rewrite CRplus_assoc, <- (CRplus_comm (- CRabs R (y + - 0))).\n      rewrite <- (CRplus_assoc (CRabs R (y + - 0))), CRplus_opp_r, CRplus_0_l.\n      apply (CRmult_eq_reg_r (CR_of_Q R 2)).\n      left. apply CR_of_Q_lt. reflexivity.\n      rewrite CRmult_assoc, <- CR_of_Q_mult.\n      setoid_replace ((1 # 2) * 2)%Q with 1%Q. 2: reflexivity.\n      rewrite (CR_of_Q_plus R 1 1), CRmult_1_r, CRmult_plus_distr_l.\n      rewrite CRmult_1_r. reflexivity.\n      apply CRmax_lub. apply CR_of_Q_le. discriminate.\n      apply CRlt_asym, c0. apply CRlt_asym, c0.\n      apply CRmin_glb. apply CR_of_Q_le. discriminate.\n      apply CRlt_asym, c. apply CRmin_glb.\n      apply CRlt_asym, c. apply CR_of_Q_le. discriminate.\n    + rewrite (CRmax_left 0 y). rewrite (CRmin_right 0 y).\n      rewrite CRmin_left, CRplus_0_l. rewrite CRmin_left. reflexivity.\n      apply (CRle_trans _ 0). apply CRlt_asym, c.\n      apply CR_of_Q_le. discriminate.\n      apply CR_of_Q_le. discriminate.\n      apply CRlt_asym, c. apply CRlt_asym, c.\n  - apply (CRle_trans _ 0). apply CRmin_l.\n    apply CR_of_Q_le. discriminate.\n  - apply CRmin_glb. apply (CRle_trans _ 0).\n    apply CR_of_Q_le. discriminate. apply CRmax_l.\n    apply CR_of_Q_le. discriminate.\nQed.\n\nDefinition MeasurablePosNegParts {IS : IntegrationSpace}\n           (f : PartialFunction (X (ElemFunc IS)))\n  : MeasurableFunction (XposPart f)\n    -> MeasurableFunction (XnegPart f)\n    -> MeasurableFunction f.\nProof.\n  intros fMes gMes A k Aint.\n  apply (IntegrableFunctionExtensional\n           (Xminus\n              (XmaxConst (XminConst (Xmult (CharacFunc A) (XposPart f))\n                                    (CR_of_Q (RealT (ElemFunc IS)) (Z.pos k # 1)))\n                         (CR_of_Q (RealT (ElemFunc IS)) (Z.neg k # 1)))\n              (XmaxConst (XminConst (Xmult (CharacFunc A) (XnegPart f))\n                                    (CR_of_Q (RealT (ElemFunc IS)) (Z.pos k # 1)))\n                         (CR_of_Q (RealT (ElemFunc IS)) (Z.neg k # 1))))).\n  - split. intros x xdf. simpl. simpl in xdf. destruct xdf. split.\n    apply p. apply p. intros. simpl.\n    destruct xD, d, d0, d1, d2, xG.\n    setoid_replace (if d5 then CR_of_Q (RealT (ElemFunc IS)) 1 else 0)\n      with (if d then CR_of_Q (RealT (ElemFunc IS)) 1 else 0).\n    setoid_replace (if d0 then CR_of_Q (RealT (ElemFunc IS)) 1 else 0)\n      with (if d then CR_of_Q (RealT (ElemFunc IS)) 1 else 0).\n    destruct d.\n    + rewrite CRmult_1_l, CRmult_1_l, CRmult_1_l.\n      rewrite (DomainProp f x d6 d1), (DomainProp f x d4 d1),\n      (DomainProp f x d2 d1), (DomainProp f x d3 d1). clear d6 d4 d3 d2.\n      generalize (partialApply f x d1). intro y.\n      rewrite (CRmult_comm (CR_of_Q (RealT (ElemFunc IS)) (1 # 2))).\n      rewrite <- CRposPartAbsMax.\n      rewrite (CRmult_comm (CR_of_Q (RealT (ElemFunc IS)) (1 # 2))).\n      do 2 rewrite <- CRopp_mult_distr_l. do 2 rewrite CRmult_1_l.\n      rewrite TruncOpp, CRopp_mult_distr_l, CRopp_plus_distr.\n      rewrite CRopp_involutive, <- (CRplus_comm y).\n      pose proof (CRnegPartAbsMin y). unfold CRminus in H.\n      rewrite <- H. clear H. apply TruncPosNeg.\n    + rewrite CRmult_0_l, CRmult_0_l, CRmult_0_l.\n      rewrite CRmin_left, CRmax_left, CRplus_0_l, CRmult_0_r. reflexivity.\n      apply CR_of_Q_le. discriminate.\n      apply CR_of_Q_le. discriminate.\n    + destruct d0. destruct d. reflexivity. contradiction. destruct d.\n      contradiction. reflexivity.\n    + destruct d5. destruct d. reflexivity. contradiction. destruct d.\n      contradiction. reflexivity.\n  - apply IntegrableMinus. apply fMes, Aint. apply gMes, Aint.\nQed.\n\nLemma CR_cv_max : forall {R : ConstructiveReals} (un : nat -> CRcarrier R) (l a : CRcarrier R),\n    CR_cv R un l\n    -> CR_cv R (fun n : nat => CRmax (un n) a)\n             (CRmax l a).\nProof.\n  intros. intro p. specialize (H p) as [n H].\n  exists n. intros.\n  apply (CRle_trans _ _ _ (CRmax_contract _ _ a)).\n  exact (H i H0).\nQed.\n\nLemma CR_cv_min : forall {R : ConstructiveReals} (un : nat -> CRcarrier R) (l a : CRcarrier R),\n    CR_cv R un l\n    -> CR_cv R (fun n : nat => CRmin (un n) a)\n             (CRmin l a).\nProof.\n  intros. intro p. specialize (H p) as [n H].\n  exists n. intros.\n  apply (CRle_trans _ _ _ (CRmin_contract _ _ a)).\n  exact (H i H0).\nQed.\n\nLemma MeasurableSetCompl\n  : forall {IS : IntegrationSpace}\n      (A : (X (ElemFunc IS)) -> Prop),\n    MeasurableSet A -> MeasurableSet (fun x => ~A x).\nProof.\n  intros IS A Ameas. apply MeasurableSetEquiv. intros B Bint. \n  destruct (MeasurableSetEquiv A) as [H _]. specialize (H Ameas B Bint).\n  refine (IntegrableFunctionExtensional\n           _ _ _ (IntegrableMinus Bint H)).\n  split.\n  - intros x. simpl. intros. destruct H0, p. split. \n    destruct s0. right. intro abs. contradiction. left. exact n. exact s.\n  - intros. destruct xD, d.\n    + (* In B *)\n      simpl. destruct d0. destruct d0. 2: contradiction.\n      destruct xG. destruct d1. 2: contradiction.\n      destruct d. destruct d0. contradiction.\n      rewrite CRmult_1_r, CRmult_1_r, CRmult_1_r. apply CRplus_opp_r.\n      destruct d0. 2: contradiction. rewrite CRmult_0_l, CRmult_0_r.\n      rewrite CRmult_1_l, CRplus_0_r. reflexivity.\n    + (* Not in B *)\n      simpl. destruct xG. destruct d0. destruct d2. contradiction.\n      destruct d1. contradiction. rewrite CRmult_0_r, CRmult_0_r, CRmult_0_r.\n      apply CRplus_0_l.\nQed.\n\nLemma MeasurableIntersectIntegrable\n  : forall {IS : IntegrationSpace}\n      {A B : (X (ElemFunc IS)) -> Prop},\n    MeasurableSet A\n    -> IntegrableSet B\n    -> IntegrableSet (fun x => A x /\\ B x).\nProof.\n  intros IS A B Ames Bint. \n  pose proof (MeasurableSetEquiv A) as [Aint _].\n  specialize (Aint Ames B Bint).\n  refine (IntegrableFunctionExtensional _ _ _ Aint). split.\n  - intros x [d d0]. destruct d, d0.\n    left. split; assumption.\n    right. intros [_ abs]. contradiction.\n    right. intros [abs _]. contradiction.\n    right. intros [abs _]. contradiction.\n  - intros. simpl. destruct xD. destruct d.\n    destruct xG. destruct d0. apply CRmult_1_r.\n    destruct a0; contradiction. destruct d0.\n    contradict n. split; assumption. apply CRmult_0_r.\n    rewrite CRmult_0_l. destruct xG. destruct a; contradiction. reflexivity.\nQed. \n\nLemma MeasurableSetUnion\n  : forall {IS : IntegrationSpace}\n      (A B : (X (ElemFunc IS)) -> Prop),\n    MeasurableSet A\n    -> MeasurableSet B\n    -> MeasurableSet (fun x => A x \\/ B x).\nProof.\n  intros IS A B Ameas Bmeas. apply MeasurableSetEquiv.\n  intros C Cint.\n  pose proof (MeasurableSetEquiv A) as [Aint _].\n  pose proof (MeasurableSetEquiv B) as [Bint _].\n  apply (IntegrableFunctionExtensional\n           (Xminus\n              (Xplus (Xmult (CharacFunc A) (CharacFunc C))\n                     (Xmult (CharacFunc B) (CharacFunc C)))\n              (Xmult (CharacFunc A) (CharacFunc (fun x => B x /\\ C x))))).\n  - split.\n    + intros x. simpl. intros. destruct H, p, p. split. 2: exact s0.\n      destruct s. left. left. exact a. destruct p1, s.\n      left. right. exact b. right. intro abs. destruct abs; contradiction.\n    + intros. destruct xD.\n      rewrite (applyXminus (Xplus (Xmult (CharacFunc A) (CharacFunc C))\n          (Xmult (CharacFunc B) (CharacFunc C))) (Xmult (CharacFunc A) (CharacFunc (fun x0 : X (ElemFunc IS) => B x0 /\\ C x0))) x d d0).\n      destruct d. rewrite (applyXplus _ _ x d d1).\n      destruct d. rewrite (applyXmult _ _ x d d2).\n      destruct d1. rewrite (applyXmult _ _ x d1 d3).\n      rewrite (DomainProp _ x d3 d2). clear d3.\n      destruct d0. rewrite (applyXmult _ _ x d0 d3).\n      rewrite (DomainProp _ x d0 d). clear d0.\n      destruct xG. rewrite (applyXmult _ _ x d0 d4).\n      rewrite (DomainProp _ x d4 d2). clear d4.\n      simpl. destruct d2. rewrite CRmult_1_r, CRmult_1_r, CRmult_1_r.\n      destruct d1. destruct d3.\n      destruct d. destruct d0. rewrite CRmult_1_r.\n      unfold CRminus. rewrite CRplus_assoc, CRplus_opp_r. apply CRplus_0_r.\n      contradict n. left. exact a0. destruct d0.\n      rewrite CRmult_0_l, CRplus_0_l. unfold CRminus.\n      rewrite CRopp_0, CRplus_0_r. reflexivity.\n      contradict n0. right. exact b.\n      contradict n. split; assumption.\n      destruct d3. destruct a; contradiction.\n      rewrite CRmult_0_r. destruct d. destruct d0.\n      rewrite CRplus_0_r. unfold CRminus.\n      rewrite CRopp_0, CRplus_0_r. reflexivity.\n      contradict n1. left. exact a. destruct d0. destruct o; contradiction.\n      rewrite CRplus_0_l. apply CRplus_opp_r.\n      destruct d3. destruct a. contradiction.\n      rewrite CRmult_0_r, CRmult_0_r, CRmult_0_r, CRplus_0_l.\n      apply CRplus_opp_r.\n  - apply IntegrableMinus. apply IntegrablePlus.\n    apply (Aint Ameas), Cint. apply (Bint Bmeas), Cint.\n    apply (Aint Ameas).\n    exact (MeasurableIntersectIntegrable Bmeas Cint).\nQed.\n\nDefinition MeasurableSetUnionIterate\n           {IS : IntegrationSpace}\n           (An : nat -> X (ElemFunc IS) -> Prop)\n           (aInt : forall n:nat, MeasurableSet (An n))\n  : forall n:nat, MeasurableSet (UnionIterate An n).\nProof.\n  induction n.\n  - apply aInt.\n  - simpl. apply MeasurableSetUnion. apply IHn. apply aInt.\nDefined.\n\nLemma MeasurableSetIntersection\n  : forall {IS : IntegrationSpace}\n      (A B : (X (ElemFunc IS)) -> Prop),\n    MeasurableSet A\n    -> MeasurableSet B\n    -> MeasurableSet (fun x => A x /\\ B x).\nProof.\n  intros IS A B Ameas Bmeas. apply MeasurableSetEquiv.\n  intros C Cint.\n  pose proof (MeasurableSetEquiv A) as [Aint _].\n  pose proof (MeasurableSetEquiv B) as [Bint _]. \n  pose proof (MeasurableFunctionFull _ Bmeas) as Bfull. \n  specialize (Aint Ameas). specialize (Bint Bmeas).\n  apply (IntegrableExtensionalAE\n           (Xmult (CharacFunc A) (CharacFunc (fun x => B x /\\ C x)))).\n  - destruct Bfull.\n    exists (Xplus x (Xmult (CharacFunc A) (CharacFunc C))). split.\n    apply IntegrablePlus. apply p. apply Aint. exact Cint.\n    intros. destruct p, H, d1. specialize (d x0 d0).\n    split. 2: exact d2. simpl. destruct d1. destruct d.\n    2: right; intros [H1 H0]; contradiction.\n    left. split; assumption. right.\n    intros [H H0]. contradiction.\n  - exists (CharacFunc C). split. exact Cint. intros. simpl.\n    destruct dF, dG. clear H. destruct d2. destruct d0.\n    destruct d1. destruct d. reflexivity. destruct a0; contradiction.\n    destruct d. contradict n. split. exact a0. apply a. reflexivity.\n    rewrite CRmult_0_r. destruct d1. contradict n.\n    split. apply a. exact c. rewrite CRmult_0_l. reflexivity.\n    rewrite CRmult_0_r. destruct d0. destruct a; contradiction.\n    apply CRmult_0_r.\n  - apply Aint.\n    apply (IntegrableFunctionExtensional\n             (Xmult (CharacFunc B) (CharacFunc C))).\n    split. intros x xdf. destruct xdf.\n    destruct d. destruct d0. left. split; assumption.\n    right. intro abs. destruct abs. contradiction.\n    right. intro abs. destruct abs. contradiction.\n    intros. 2: apply Bint; assumption. \n    simpl. destruct xD. destruct d. destruct d0.\n    destruct xG. apply CRmult_1_l. contradict n. split; assumption.\n    destruct xG. destruct a; contradiction. apply CRmult_0_r.\n    rewrite CRmult_0_l. destruct xG. destruct a; contradiction. reflexivity.\nQed.\n\nLemma Rcauchy_complete_cv\n  : forall {R : ConstructiveReals } (un : nat -> CRcarrier R)\n      (cau : CR_cauchy R un) (a : CRcarrier R),\n    CR_cv R un a\n    -> ((let (x,_) := CR_complete R un cau in x) == a)%ConstructiveReals.\nProof.\n  intros. destruct (CR_complete R un cau).\n  exact (CR_cv_unique un _ _ c H).\nQed.\n\nLemma SigmaFiniteLimit\n  : forall {R : ConstructiveReals} (A : CRcarrier R -> Prop),\n    @PartialRestriction R _\n      (XpointwiseLimit (fun n => CharacFunc (fun x => -CR_of_Q R (Z.of_nat n # 1) <= x\n                                                /\\ x <= CR_of_Q R (Z.of_nat n # 1)\n                                                /\\ A x)))\n      (CharacFunc A).\nProof.\n  split.\n  - intros x [xnD H]. destruct (CRup_nat (CRabs _ x)) as [n H0].\n    apply CRabs_lt in H0. destruct H0.\n    destruct (xnD n) as [isin|isout].\n    + left. apply isin.\n    + right. intro abs. apply isout. repeat split. 3: exact abs.\n      2: apply CRlt_asym, c.\n      rewrite <- (CRopp_involutive x).\n      apply CRopp_ge_le_contravar. apply CRlt_asym, c0.\n  - intros. simpl.\n    destruct (CRup_nat (CRabs _ x)) as [n nup].\n    apply CRabs_lt in nup. destruct nup.\n    destruct xD as [xnD H], xG.\n    + (* in A *)\n      unfold CharacFunc, Domain, inject_Z in xnD.\n      unfold CharacFunc, partialApply in H.\n      apply Rcauchy_complete_cv.\n      intro p. exists n. intros. destruct (xnD i).\n      unfold CRminus. rewrite CRplus_opp_r.\n      rewrite CRabs_right. apply CR_of_Q_le. discriminate.\n      apply CRle_refl. exfalso. apply n0. repeat split.\n      3: exact a.\n      rewrite <- (CRopp_involutive x).\n      apply CRopp_ge_le_contravar.\n      apply (CRle_trans _ (CR_of_Q R (Z.of_nat n # 1))).\n      apply CRlt_asym, c0. apply CR_of_Q_le. unfold Qle, Qnum, Qden.\n      do 2 rewrite Z.mul_1_r. apply Nat2Z.inj_le, H0.\n      apply (CRle_trans _ (CR_of_Q R (Z.of_nat n # 1))).\n      apply CRlt_asym, c. apply CR_of_Q_le. unfold Qle, Qnum, Qden.\n      do 2 rewrite Z.mul_1_r. apply Nat2Z.inj_le, H0.\n    + (* not in A, constant sequence at 0. *)\n      unfold CharacFunc, partialApply in H.\n      apply Rcauchy_complete_cv. intro p. exists O.\n      intros. destruct (xnD i). exfalso.\n      destruct a, H2. contradiction.\n      unfold CRminus. rewrite CRopp_0, CRplus_0_r.\n      rewrite CRabs_right. \n      apply CR_of_Q_le. discriminate. apply CRle_refl.\nQed.\n\nLemma SigmaFiniteMonotone\n  : forall {R : ConstructiveReals} (A : CRcarrier R -> Prop),\n    let fn := fun n => @CharacFunc R _ (fun x => -CR_of_Q R (Z.of_nat n # 1) <= x\n                                      /\\ x <= CR_of_Q R (Z.of_nat n # 1)\n                                      /\\ A x) in\n    forall n:nat, partialFuncLe (fn n) (fn (S n)).\nProof.\n  intros R A fn n x xdf xdg. simpl.\n  destruct xdf.\n  - destruct xdg. apply CRle_refl. exfalso.\n    apply n0. destruct a, H0. repeat split. 3: exact H1.\n    apply (CRle_trans _ (- CR_of_Q R (Z.of_nat n # 1))).\n    apply CRopp_ge_le_contravar. apply CR_of_Q_le.\n    unfold Qle, Qnum, Qden.\n    do 2 rewrite Z.mul_1_r. apply Nat2Z.inj_le, le_S, le_refl. exact H.\n    apply (CRle_trans _ (CR_of_Q R (Z.of_nat n # 1)) _ H0).\n    apply CR_of_Q_le. unfold Qle, Qnum, Qden.\n    do 2 rewrite Z.mul_1_r. apply Nat2Z.inj_le, le_S, le_refl.\n  - destruct xdg. apply CRlt_asym, CRzero_lt_one. apply CRle_refl.\nQed.\n\n(* A classical hypothesis, to explain the relation with the\n   classical Lebesgue measure. *)\nDefinition IncrSeqCvT : Type\n  := forall (R : ConstructiveReals) (un : nat -> CRcarrier R) (a : CRcarrier R),\n    (forall n:nat, un n <= un (S n))\n    -> (forall n:nat, un n <= a)\n    -> CR_cauchy R un.\n\n(* This proves that a Lebesgue-measurable function is Bishop-measurable,\n   when we assume the classical theorem IncrSeqCvT.\n   Because non-negative Lebesgue-measurable functions are non-decreasing\n   limits of simple functions, which are Bishop-measurable. *)\nDefinition MeasurableMonotoneConvergenceClassical\n           {IS : IntegrationSpace}\n           (fn : nat -> PartialFunction (X (ElemFunc IS)))\n  : (forall n:nat, MeasurableFunction (fn n))\n    -> (forall n:nat, partialFuncLe (fn n) (fn (S n)))\n    -> IncrSeqCvT\n         (* The sequence fn is assumed to converge everywhere,\n            because the sequence fn is derived from a hypothetical\n            Lebesgue-measurable function f, that we want to prove\n            is Bishop-integrable.\n\n            This hypothesis is necessary, to replace the convergence of\n            integrals in the constructive monotone convergence theorem.\n            For example, the sequence of constant measurable functions n\n            converges nowhere, so we cannot conclude that the empty\n            function is measurable. *)\n    -> (forall x : X (ElemFunc IS),\n           Domain (XpointwiseLimit fn) x)\n    -> MeasurableFunction (XpointwiseLimit fn).\nProof.\n  intros fnMes H cl cv A k Aint.\n  assert (forall n:nat, partialFuncLe\n    (XmaxConst (XminConst (Xmult (CharacFunc A) (fn n)) (CR_of_Q (RealT (ElemFunc IS)) (Z.pos k # 1)))\n       (CR_of_Q (RealT (ElemFunc IS)) (Z.neg k # 1)))\n    (XmaxConst\n       (XminConst (Xmult (CharacFunc A) (fn (S n))) (CR_of_Q (RealT (ElemFunc IS)) (Z.pos k # 1)))\n       (CR_of_Q (RealT (ElemFunc IS)) (Z.neg k # 1)))).\n  { intros n x xdf xdg.\n    simpl. destruct xdf, xdg. destruct d.\n    destruct d1. 2: contradiction. rewrite CRmult_1_l, CRmult_1_l.\n    apply CRmax_lub.\n    apply (CRle_trans _ (CRmin (partialApply (fn (S n)) x d2) (CR_of_Q (RealT (ElemFunc IS)) (Z.pos k # 1)))).\n    2: apply CRmax_l.\n    apply CRmin_glb. 2: apply CRmin_r.\n    apply (CRle_trans _ (partialApply (fn n) x d0)).\n    apply CRmin_l. apply H. apply CRmax_r.\n    destruct d1. contradiction. rewrite CRmult_0_l, CRmult_0_l. apply CRle_refl. }\n  assert (forall n : nat,\n        (fun n0 : nat => Integral (fnMes n0 A k Aint)) n <=\n        (fun n0 : nat => Integral (fnMes n0 A k Aint)) (S n)).\n  { intro n. apply IntegralNonDecreasing. apply H0. }\n  assert (forall n : nat,\n        (fun n0 : nat => Integral (fnMes n0 A k Aint)) n <=\n        MeasureSet Aint * CR_of_Q (RealT (ElemFunc IS)) (Z.pos k # 1)).\n  { intro n.\n    apply (CRle_trans _ (Integral (IntegrableScale (CharacFunc A)\n                                                     (CR_of_Q (RealT (ElemFunc IS)) (Z.pos k # 1))\n                                                     Aint))).\n    apply IntegralNonDecreasing. intros x xdf xdg.\n    simpl. destruct xdf, xdg. destruct d. 2: contradiction.\n    rewrite CRmult_1_l, CRmult_1_r. apply CRmax_lub.\n    apply CRmin_r. apply CR_of_Q_le. discriminate.\n    destruct d. contradiction. rewrite CRmult_0_l, CRmult_0_r.\n    apply CRmax_lub. apply CRmin_l. \n    apply CR_of_Q_le. discriminate.\n    rewrite IntegralScale. apply CRle_refl. }\n  destruct (CR_complete _ _ (cl _ (fun n => Integral (fnMes n A k Aint))\n                 (MeasureSet Aint * CR_of_Q _ (Z.pos k # 1))\n                 H1 H2)) as [l lcv].\n  destruct (IntegralMonotoneConvergence\n              IS (fun n => XmaxConst\n       (XminConst (Xmult (CharacFunc A) (fn n))\n                  (CR_of_Q (RealT (ElemFunc IS)) (Z.pos k # 1))) (CR_of_Q (RealT (ElemFunc IS)) (Z.neg k # 1)))\n              (fun n => fnMes n A k Aint) l H0 lcv).\n  apply (IntegrableFunctionExtensional\n           (XpointwiseLimit\n           (fun n : nat =>\n            XmaxConst\n              (XminConst (Xmult (CharacFunc A) (fn n)) (CR_of_Q (RealT (ElemFunc IS)) (Z.pos k # 1)))\n              (CR_of_Q (RealT (ElemFunc IS)) (Z.neg k # 1))))).\n  2: exact x.\n  split. intros y ydf. simpl. simpl in ydf. destruct ydf.\n  split. exact (fst (x0 O)). exists (fun n => snd (x0 n)).\n  specialize (cv y). destruct cv.\n  apply (CR_cauchy_eq (fun n : nat => partialApply (fn n) y (x1 n))).\n  2: exact c1. intro n. apply DomainProp.\n  intros. apply applyPointwiseLimit. apply CR_cv_max.\n  apply CR_cv_min. destruct xD, xG. destruct d.\n  - setoid_replace (partialApply (Xmult (CharacFunc A) (XpointwiseLimit fn)) x0 (left a, d0))\n      with (partialApply (XpointwiseLimit fn) x0 d0).\n    2: simpl; rewrite CRmult_1_l; reflexivity.\n    pose proof (applyPointwiseLimit fn x0 d0\n                                    (partialApply (XpointwiseLimit fn) x0 d0)) as [H3 _].\n    apply (CR_cv_eq _ (fun n : nat => partialApply (fn n) x0 (let (xn, _) := d0 in xn n))).\n    intro n. simpl. destruct (x1 n), d. rewrite CRmult_1_l. apply DomainProp.\n    contradiction. apply H3. reflexivity.\n  - setoid_replace (partialApply (Xmult (CharacFunc A) (XpointwiseLimit fn)) x0 (right n, d0))\n      with (CR_of_Q (RealT (ElemFunc IS)) 0).\n    2: simpl; rewrite CRmult_0_l; reflexivity.\n    apply (CR_cv_eq _ (fun _ => 0)). intros.\n    simpl. destruct (x1 n0), d. contradiction. rewrite CRmult_0_l. reflexivity.\n    intro p. exists O. intros. unfold CRminus.\n    rewrite CRplus_opp_r, CRabs_right.\n    apply CR_of_Q_le. discriminate. apply CRle_refl.\nQed.\n\n(*\nLemma MeasurableSetUnionCountable\n  : forall {IS : IntegrationSpace}\n      (An : nat -> ((X (ElemFunc IS)) -> Prop)),\n    (forall n:nat, MeasurableSet (An n))\n    -> IncrSeqCvT (* Maybe we can weaken this classical hypothesis *)\n    -> MeasurableSet (fun x => exists n:nat, An n x).\nProof.\n  intros IS An AnMeas IncrSeqCv.\n  apply MeasurableSetEquiv.\n  intros B Bint.\n  (* Integrate union intersected with B by the monotone convergence theorem.\n     The limit of the intersected integrals will come from majoration and\n     IncrSeqCv. *)\n  assert (forall n : nat, IntegrableFunction\n                     (Xmult (CharacFunc (UnionIterate An n)) (CharacFunc B)))\n    as unionMes.\n  { intro n. pose proof (MeasurableSetUnionIterate An AnMeas). \n    pose proof (MeasurableSetEquiv (UnionIterate An n)) as [mes _].\n    exact (mes (X n) B Bint). } \n  assert (forall n : nat, @partialFuncLe (RealT (ElemFunc IS)) _\n         (Xmult (CharacFunc (UnionIterate An n)) (CharacFunc B))\n         (Xmult (CharacFunc (UnionIterate An (S n))) (CharacFunc B))).\n  { intros n x xdf xdg. simpl. destruct xdf, xdg.\n    destruct d0. destruct d2. 2: contradiction.\n    rewrite CRmult_1_r, CRmult_1_r. destruct d. destruct d1.\n    apply CRle_refl. contradict n0. left. exact u.\n    destruct d1. apply CRlt_asym, CRzero_lt_one. apply CRle_refl.\n    rewrite CRmult_0_r. destruct d2. contradiction.\n    rewrite CRmult_0_r. apply CRle_refl. }\n  assert (forall n : nat, Integral (unionMes n) <= Integral Bint).\n  { shelve. }\n  specialize (IncrSeqCv _ (fun n : nat => Integral (unionMes n))\n                        (Integral Bint)\n                        (fun n => IntegralNonDecreasing _ _ _ _ (H n)) H0).\n  apply CR_complete in IncrSeqCv. destruct IncrSeqCv as [l lcv].\n  destruct (IntegralMonotoneConvergence\n              IS (fun n => Xmult (CharacFunc (UnionIterate An n)) (CharacFunc B))\n              unionMes l H lcv) as [limInt _].\n  apply (IntegrableFunctionExtensional\n           (XpointwiseLimit\n                (fun n : nat => Xmult (CharacFunc (UnionIterate An n)) (CharacFunc B)))).\n  2: exact limInt. split.\n  - intros x [xn c]. split. 2: apply (xn O).\n    clear lcv l. apply CR_complete in c. destruct c as [l lcv].\n    split. 2: exact H1. destruct H2 as [xn c].\n\n    destruct H. simpl.\n    destruct H0.\n    left. destruct e. exists x0. apply H. right. intro abs.\n    contradict n. destruct abs. exists x0. split; assumption.\n    destruct H0. exfalso. destruct e, H. contradiction. \n    simpl. right. intro abs. destruct abs.\n    + intros x [H|H]. simpl. left. destruct H. split.\n      exists x0. apply H. apply H. right. intros [[n H0] H1].\n      apply H. exists n. split; assumption.\n    + intros. simpl. destruct xD, xG. reflexivity.\n      exfalso. apply n. destruct e. split. exists x0.\n      apply H. apply H.\n      exfalso. apply n. destruct a, H. exists x0. split; assumption.\n      reflexivity.\n  - assert (forall n:nat, IntegrableSet (fun x => An n x /\\ B x)) as AnInt.\n    { intro n. apply AnMeas, Bint. }\n    specialize (IncrSeqCv _ (fun n : nat =>\n     MeasureSet\n       (IntegrableSetUnionIterate\n          (fun (n0 : nat) (x : X (ElemFunc IS)) => An n0 x /\\ B x) AnInt n))\n                          (MeasureSet Bint)).\n    apply CR_complete in IncrSeqCv.\n    destruct IncrSeqCv as [l lim].\n    + apply (IntegrableSetCountableUnion _ AnInt l lim).\n    + intros. apply IntegralNonDecreasing. intros x xdf xdg.\n      simpl. destruct xdf. destruct xdg. apply CRle_refl.\n      exfalso. apply n0. apply applyUnionIterate.\n      apply applyUnionIterate in u. destruct u. exists x0.\n      destruct H, H0. repeat split; try assumption.\n      apply (le_trans _ _ _ H), le_S, le_refl.\n      destruct xdg. apply CRlt_asym, CRzero_lt_one. apply CRle_refl.\n    + intros. apply IntegralNonDecreasing. intros x xdf xdg.\n      simpl. destruct xdf. destruct xdg. apply CRle_refl.\n      exfalso. apply applyUnionIterate in u. destruct u, H, H0.\n      contradiction.\n      destruct xdg. apply CRlt_asym, CRzero_lt_one. apply CRle_refl.\nQed.\n*)\n\nDefinition IntegralSupport {IS : IntegrationSpace}\n       (f : PartialFunction (X (ElemFunc IS)))\n       (fInt : IntegrableFunction f)\n       (A : (X (ElemFunc IS)) -> Prop)\n       (eps : CRcarrier (RealT (ElemFunc IS))) : Type :=\n  { isupp_int : IntegrableSet A\n                & IntegralDistance\n                    fInt (RestrictedIntegrable fInt isupp_int) < eps }.\n\nLemma IntegralSupportExists\n  : forall {IS : IntegrationSpace}\n      (f : PartialFunction (X (ElemFunc IS)))\n      (fInt : IntegrableFunction f)\n      (eps : CRcarrier (RealT (ElemFunc IS))),\n    0 < eps\n    -> { t : CRcarrier _\n            & prod (t < eps)\n                   (IntegralSupport\n                      f fInt\n                      (fun x => exists xD:Domain (Xabs f) x,\n                           t <= partialApply (Xabs f) x xD) eps) }.\nProof.\n  intros. \n  pose proof (InverseImageIntegrableAE (Xabs f) (IntegrableAbs fInt))\n    as [jumps invIm].\n  pose proof (Un_cv_nat_real _ _ (IntegralTruncateLimitZero f fInt)\n                             eps H) as [n nmaj].\n  pose proof (CRuncountable jumps 0 _ (CRmin_lt _ _ _ (invSuccRealPositive n) H))\n    as [t [[tpos tmin] tcont]].\n  specialize (invIm t tpos tcont) as [invIm _].\n  exists t. split. apply (CRlt_le_trans _ _ _ tmin). apply CRmin_r.\n  exists invIm.\n  specialize (nmaj n (le_refl n)). refine (CRle_lt_trans _ _ _ _ nmaj).\n  unfold CRminus. rewrite CRopp_0, CRplus_0_r, CRabs_right.\n  apply IntegralNonDecreasing. intros x xdf xdg.\n  destruct xdf, d0, d0. \n  - (* t <= |f x| *)\n    apply (CRle_trans _ 0).\n    simpl. rewrite CRmult_1_l.\n    rewrite <- CRopp_mult_distr_l, CRmult_1_l, (DomainProp f x d1 d).\n    rewrite CRplus_opp_r, CRabs_right. apply CRle_refl. apply CRle_refl.\n    simpl. apply CRmin_glb. apply CRabs_pos.\n    apply CR_of_Q_le. discriminate.\n  - (* |f x| < t *)\n    apply (CRle_trans _ (CRabs _ (partialApply f x d))).\n    simpl. rewrite CRmult_0_l, CRmult_0_r, CRplus_0_r. apply CRle_refl.\n    assert (CRabs _ (partialApply f x d) <= t).\n    { intro abs. contradict n0. exists d. apply CRlt_asym, abs. }\n    clear n0. apply CRmin_glb.\n    rewrite applyXabs, (DomainProp f x xdg d). apply CRle_refl.\n    apply (CRle_trans _ _ _ H0). apply CRlt_asym.\n    apply (CRlt_le_trans _ _ _ tmin). apply CRmin_l.\n  - apply IntegralNonNeg. intros x xdf. apply CRmin_glb.\n    apply CRabs_pos. apply CR_of_Q_le. discriminate.\nQed.\n\nDefinition RestrictedMeasurable_pos\n           {IS : IntegrationSpace}\n           (f : PartialFunction (X (ElemFunc IS)))\n           (A : (X (ElemFunc IS)) -> Prop)\n  : IntegrableFunction f\n    -> MeasurableSet A\n    -> nonNegFunc f\n    -> IntegrableFunction (Xmult (CharacFunc A) f).\nProof.\n  intros fInt Ames fPos. \n  (* Make a sequence of supports converging to f's integral. *)\n  assert (forall n:nat, 0 < CRpow (CR_of_Q (RealT (ElemFunc IS)) (1#2)) n).\n  { intro n. apply CRpow_gt_zero, CR_of_Q_pos. reflexivity. }\n  pose proof (fun n:nat => IntegralSupportExists\n                        f fInt _ (H n)) as Bn.\n  assert (forall n:nat, IntegrableFunction\n                   (Xmult (CharacFunc (fun x => A x /\\ let (t,_) := Bn n in\n           exists xD : Domain (Xabs f) x, t <= partialApply (Xabs f) x xD\n                                                   )) f))\n    as fnInt.\n  { intro n. apply (RestrictedIntegrable fInt).\n    pose proof (MeasurableSetEquiv A) as [H0 _].\n    destruct (Bn n) as [t p], p, i as [i c0].\n    specialize (H0 Ames _ i).\n    refine (IntegrableFunctionExtensional _ _ _ H0).\n    split. intros x xdf. destruct xdf, d.\n    2: right; intro abs; destruct abs; contradiction.\n    destruct d0. left. split; assumption.\n    right; intro abs; destruct abs; contradiction.\n    intros. destruct xD. simpl. destruct d.\n    rewrite CRmult_1_l. destruct d0,xG. reflexivity.\n    contradict n0. split; assumption.\n    contradict n0. apply a0. reflexivity. rewrite CRmult_0_l.\n    destruct xG. contradict n0. apply a. reflexivity. }\n  assert (forall n:nat, IntegrableFunction\n                   (Xmult (CharacFunc (fun x => let (t,_) := Bn n in\n           exists xD : Domain (Xabs f) x, t <= partialApply (Xabs f) x xD)) f))\n    as gnInt.\n  { intro n. apply (RestrictedIntegrable fInt).\n    destruct (Bn n) as [t p], p, i as [i c0]. exact i. }\n  destruct (series_cv_maj\n              (fun n : nat =>\n                 Integral (IntegrableAbs (IntegrableMinus (fnInt (S n)) (fnInt n))))\n              (fun n:nat => CRpow (CR_of_Q (RealT (ElemFunc IS)) (1#2)) n\n                       * CR_of_Q _ 2)\n              (CR_of_Q _ 2 * CR_of_Q _ 2)) as [l lcv].\n  - intro n. rewrite CRabs_right.\n    2: apply IntegralNonNeg; intros x xdf; apply CRabs_pos.\n    apply (CRle_trans _ (Integral (IntegrableAbs (IntegrableMinus (gnInt (S n)) (gnInt n))))).\n    apply IntegralNonDecreasingAE.\n    destruct (Bn n) as [t p], p, i as [i c0].\n    exists (Xmult (CharacFunc A) (CharacFunc (fun x => \n           exists xD : Domain (Xabs f) x, t <= partialApply (Xabs f) x xD\n                                                   ))).\n    split. \n    pose proof (MeasurableSetEquiv A) as [H0 _].\n    specialize (H0 Ames _ i). exact H0. \n    intros x xdA xdf xdg.\n    simpl. destruct xdf, xdg, d, d1, d0, d2. destruct xdA, d7.\n    + (* x in A *)\n      rewrite (DomainProp f x d6 d5). clear d6.\n      rewrite (DomainProp f x d4 d3). clear d4.\n      destruct d. destruct d1. 2: contradict n0; apply a0.\n      destruct d0. destruct d2. apply CRle_refl.\n      contradict n0. apply a1. destruct d2. 2: apply CRle_refl.\n      contradict n0. split. exact a. exact e.\n      destruct d1. contradict n0. split. exact a. apply y.\n      destruct d0. destruct d2. apply CRle_refl.\n      contradict n2. apply a0. destruct d2. 2: apply CRle_refl.\n      contradict n2. split. exact a. exact e.\n    + (* x not in A *)\n      destruct d. contradict n0. apply a. rewrite CRmult_0_l.\n      destruct d0. contradict n0. apply a. rewrite CRmult_0_l.\n      rewrite CRmult_0_r, CRplus_0_r, CRabs_right.\n      apply CRabs_pos. apply CRle_refl.\n    + apply (CRle_trans _ _ _ (IntegralDistance_triang _ _ _ _ fInt _)).\n      rewrite (CR_of_Q_plus _ 1 1), CRmult_plus_distr_l.\n      rewrite CRmult_1_r. apply CRplus_le_compat. generalize (gnInt (S n)).\n      intro i. simpl in i. destruct (Bn (S n)), p, i0.\n      apply CRlt_asym, (CRlt_trans _ (CRpow (CR_of_Q (RealT (ElemFunc IS)) (1 # 2)) (S n))).\n      refine (CRle_lt_trans _ _ _ _ c0).\n      apply IntegralNonDecreasing. intros y ydf ydg.\n      rewrite (DomainProp _ y ydf ydg). apply CRle_refl.\n      apply (CRlt_le_trans _ (CR_of_Q _ 1\n                              * CRpow (CR_of_Q (RealT (ElemFunc IS)) (1 # 2)) n)).\n      apply CRmult_lt_compat_r. apply CRpow_gt_zero, CR_of_Q_pos. reflexivity.\n      apply CR_of_Q_lt. reflexivity.\n      rewrite CRmult_1_l. apply CRle_refl.\n      generalize (gnInt n).\n      intro i. simpl in i. destruct (Bn n), p, i0.\n      apply CRlt_asym. refine (CRle_lt_trans _ _ _ _ c0).\n      apply IntegralNonDecreasing. intros y ydf ydg.\n      rewrite (DomainProp _ y ydf ydg). apply CRle_refl.\n  - apply series_cv_scale. exact GeoHalfTwo.\n  - destruct (IntegrableXpointwiseLimit _ fnInt l (fst lcv)) as [limInt _].\n    pose proof (MeasurableFunctionFull _ Ames) as [h hint].\n    refine (IntegrableExtensionalAE _ _ _ _ limInt). destruct hint.\n    + exists (Xplus h f). split. exact (IntegrablePlus _ _ i fInt).\n      intros. destruct H0. split.\n      specialize (d x d0). exact d. exact d1.\n    + exists h. destruct hint. split. exact i. intros. \n      clear d H0 i h. destruct dG. apply applyPointwiseLimit.\n      intro p. destruct (CRltLinear (RealT (ElemFunc IS))) as [_ s].\n      assert (0 < CR_of_Q (RealT (ElemFunc IS)) (1 # (2*p))).\n      { apply CR_of_Q_pos. reflexivity. }\n      specialize (s 0 (partialApply f x d0) _ H0) as [c|c].\n      * (* 0 < f x. x will eventually be in the support,\n           then the left term becomes 0. *)\n        simpl in c.\n        apply (CR_cv_open_above _ _ _ (@GeoCvZero (RealT (ElemFunc IS)))) in c.\n        destruct c as [n nmaj]. exists n. intros i H1. \n        specialize (nmaj i H1). destruct dF.\n        generalize (x0 i). intros. \n        destruct (Bn i) as [t r], r, i0 as [j c1], d1.\n        simpl. rewrite (DomainProp f x d2 d0). clear d2.\n        destruct d. destruct d1. unfold CRminus.\n        rewrite CRplus_opp_r, CRabs_right.\n        apply CR_of_Q_le. discriminate. apply CRle_refl.\n        contradict n0. split. exact a. exists d0.\n        apply CRlt_asym, (CRlt_trans _ _ _ c0), (CRlt_le_trans _ _ _ nmaj). \n        apply CRle_abs. destruct d1. destruct a. contradiction.\n        unfold CRminus.\n        rewrite CRmult_0_l, CRplus_opp_r, CRabs_right.\n        apply CR_of_Q_le. discriminate. apply CRle_refl.\n      * (* f x < 1 / 2p *)\n        exists O. intros.\n        apply (CRle_trans _ _ _ (CRabs_triang _ _)).\n        setoid_replace (1#p) with ((1#(2*p)) + (1#(2*p)))%Q.\n        2: rewrite Qinv_plus_distr; reflexivity.\n        rewrite CR_of_Q_plus. apply CRplus_le_compat.\n        destruct dF, (x0 i). simpl. destruct d1.\n        rewrite CRmult_1_l, CRabs_right, (DomainProp f x d2 d0).\n        apply CRlt_asym, c. apply fPos. rewrite CRmult_0_l, CRabs_right.\n        apply CR_of_Q_le. discriminate. apply CRle_refl. \n        rewrite CRabs_opp. simpl. destruct d.\n        rewrite CRmult_1_l, CRabs_right. apply CRlt_asym, c.\n        apply fPos. rewrite CRmult_0_l, CRabs_right.\n        apply CR_of_Q_le. discriminate. apply CRle_refl. \nQed.\n\nDefinition RestrictedMeasurable\n           {IS : IntegrationSpace}\n           {f : PartialFunction (X (ElemFunc IS))}\n           {A : (X (ElemFunc IS)) -> Prop}\n  : IntegrableFunction f\n    -> MeasurableSet A\n    -> IntegrableFunction (Xmult (CharacFunc A) f).\nProof.\n  intros fInt Ames. \n  apply (IntegrableFunctionExtensional\n           (Xminus (Xmult (CharacFunc A) (XposPart f))\n                   (Xmult (CharacFunc A) (XnegPart f)))).\n  - split. intros x xdf. destruct xdf. split. apply d. apply d.\n    intros. destruct xD, xG.\n    rewrite (applyXmult _ _ x d1 d2).\n    rewrite <- (SplitPosNegParts _ x _ (snd d) (snd d0)).\n    rewrite (applyXminus (Xmult (CharacFunc A) (XposPart f))\n                         (Xmult (CharacFunc A) (XnegPart f)) x d d0).\n    destruct d, d0.\n    rewrite (applyXmult _ _ x d d3), (applyXmult _ _ x d0 d4).\n    rewrite (DomainProp _ x d0 d), (DomainProp _ x d1 d).\n    unfold CRminus. rewrite CRmult_plus_distr_l, CRopp_mult_distr_r.\n    reflexivity.\n  - apply IntegrableMinus. apply RestrictedMeasurable_pos.\n    apply IntegrablePosPart, fInt. exact Ames.\n    apply applyXposPartNonNeg.\n    apply RestrictedMeasurable_pos.\n    apply IntegrableNegPart, fInt. exact Ames.\n    apply applyXnegPartNonNeg.\nQed.\n\n\n(* IntegrableSet (fun x => A x /\\ ~B x) is not enough,\n   because it leads to ~~B. *)\nRecord SetApprox {IS : IntegrationSpace}\n       (A : (X (ElemFunc IS)) -> Prop) (Aint : IntegrableSet A)\n       (eps : CRcarrier (RealT (ElemFunc IS))) : Type\n  := { sa_approx : (X (ElemFunc IS)) -> Prop;\n       sa_bint : IntegrableSet sa_approx;\n       sa_mes : MeasureSet Aint - MeasureSet sa_bint < eps;\n       sa_inc : forall x, sa_approx x -> A x; }.\n\n(* Generators for integrable sets, akin to a basis for a topology. *)\nDefinition IntegrableSetsGen (IS : IntegrationSpace) : Type\n  := forall (A : (X (ElemFunc IS)) -> Prop) (Aint : IntegrableSet A)\n       (eps : CRcarrier (RealT (ElemFunc IS))),\n    0 < eps -> SetApprox A Aint eps.\n\n(* Increasing sequence of subsets of A that converge towards A,\n   and which disjoint increments are generators. *)\nFixpoint IntegrableApproxSequence\n         {IS : IntegrationSpace}\n         (gen : IntegrableSetsGen IS)\n         (A : (X (ElemFunc IS)) -> Prop) (Aint : IntegrableSet A)\n         (n : nat) {struct n}\n  : { U : X (ElemFunc IS) -> Prop  &  IntegrableSet U }.\nProof.\n  destruct n as [|p].\n  - destruct (gen A Aint 1 (CRzero_lt_one _)).\n    exists sa_approx0. exact sa_bint0.\n  - destruct (IntegrableApproxSequence IS gen A Aint p) as [U Uint].\n    exists (fun x => U x \\/ (sa_approx _ _ _ (gen _ (IntegrableSetDifference A U Aint Uint)\n                  (CRpow (CR_of_Q _ (1#2)) (S p))\n                  (CRpow_gt_zero _ (S p) (CR_of_Q_pos (1#2) eq_refl))) x)).\n    exact (IntegrableSetUnion _ _ Uint (sa_bint _ _ _ (gen _ (IntegrableSetDifference A U Aint Uint)\n                  (CRpow (CR_of_Q _ (1#2)) (S p))\n                  (CRpow_gt_zero _ (S p) (CR_of_Q_pos (1#2) eq_refl))))).\nDefined.\n\nLemma IntegrableApproxSequenceInc\n  : forall {IS : IntegrationSpace}\n      (gen : IntegrableSetsGen IS)\n      (A : X (ElemFunc IS) -> Prop)\n      (Aint : IntegrableSet A) (n : nat) (x : X (ElemFunc IS)),\n    let (U,_) := IntegrableApproxSequence gen A Aint n in\n    U x -> A x.\nProof.\n  induction n.\n  - intros. simpl. destruct (gen A Aint 1 (CRzero_lt_one (RealT (ElemFunc IS)))).\n    apply sa_inc0.\n  - intros. simpl. destruct (IntegrableApproxSequence gen A Aint n).\n    intros. destruct H. apply IHn, H.\n    apply (sa_inc _ _ _ _ x H).\nQed.\n\nLemma IntegrableApproxSequenceIncr\n  : forall {IS : IntegrationSpace}\n      (gen : IntegrableSetsGen IS)\n      (A : X (ElemFunc IS) -> Prop)\n      (Aint : IntegrableSet A) (i j : nat) (x : X (ElemFunc IS)),\n    le i j\n    -> (let (U,_) := IntegrableApproxSequence gen A Aint i in U x)\n    -> (let (U,_) := IntegrableApproxSequence gen A Aint j in U x).\nProof.\n  induction j.\n  - intros. inversion H. subst i. exact H0.\n  - intros. apply Nat.le_succ_r in H. destruct H.\n    specialize (IHj x H).\n    simpl; destruct (IntegrableApproxSequence gen A Aint j).\n    left. exact (IHj H0). subst i. exact H0.\nQed.\n\nLemma IntegrableApproxSequenceBound\n  : forall {IS : IntegrationSpace}\n      (gen : IntegrableSetsGen IS)\n      (A : X (ElemFunc IS) -> Prop)\n      (Aint : IntegrableSet A) (n : nat)\n      (Uint : IntegrableSet\n                (let (U,_) := IntegrableApproxSequence gen A Aint n in U)),\n    MeasureSet Aint - MeasureSet Uint\n    < CRpow (CR_of_Q _ (1#2)) n.\nProof.\n  intros. destruct n.\n  - simpl. simpl in Uint.\n    destruct (gen A Aint 1 (CRzero_lt_one (RealT (ElemFunc IS)))).\n    apply (CRle_lt_trans\n             _ (MeasureSet Aint - MeasureSet sa_bint0)).\n    apply CRplus_le_compat_l, CRopp_ge_le_contravar.\n    apply MeasureNonDecreasing. intros. exact H.\n    exact sa_mes0.\n  - simpl.\n    pose proof (IntegrableApproxSequenceInc gen A Aint n) as Uinc.\n    simpl in Uint; \n    destruct (IntegrableApproxSequence gen A Aint n) as [U Vint].\n    apply (CRle_lt_trans _ (MeasureSet (IntegrableSetDifference A U Aint Vint)\n                            - MeasureSet (sa_bint _ _ _ \n              (gen (fun x0 : X (ElemFunc IS) => A x0 /\\ ~ U x0)\n                 (IntegrableSetDifference A U Aint Vint)\n                 (CR_of_Q (RealT (ElemFunc IS)) (1 # 2) *\n                  CRpow (CR_of_Q (RealT (ElemFunc IS)) (1 # 2)) n)\n                 (CRpow_gt_zero (CR_of_Q (RealT (ElemFunc IS)) (1 # 2)) \n                    (S n) (CR_of_Q_pos (1 # 2) eq_refl)))))).\n    2: apply sa_mes.\n    rewrite <- MeasureDifferenceIncluded, <- MeasureDifferenceIncluded.\n    apply MeasureNonDecreasing. intros. destruct H.\n    split. split. exact H. intro abs. apply H0. left. exact abs.\n    intro abs. apply H0. right. exact abs. intros. \n    exact (sa_inc _ _ _ _ x H). intros. destruct H.\n    2: exact (proj1 (sa_inc _ _ _ _ x H)). apply Uinc, H.\nQed. \n\nLemma IntegrableApproxSequenceLimit\n  : forall {IS : IntegrationSpace}\n      (gen : IntegrableSetsGen IS)\n      (A : X (ElemFunc IS) -> Prop)\n      (Aint : IntegrableSet A),\n    { intUnion : IntegrableSet\n                   (fun x => exists n:nat, let (U,_) := IntegrableApproxSequence\n                                                gen A Aint n in U x)\n    | MeasureSet intUnion == MeasureSet Aint }.\nProof.\n  intros.\n  assert (forall n:nat, IntegrableSet\n                   (fun x => let (U, _) := IntegrableApproxSequence gen A Aint n in U x))\n    as seqInt.\n  { intro n. destruct (IntegrableApproxSequence gen A Aint n). exact i. }\n  apply (IntegrableSetCountableUnion\n              (fun n x => let (U,_) := IntegrableApproxSequence gen A Aint n in U x)\n              seqInt (MeasureSet Aint)).\n  intro p. pose proof (@GeoCvZero (RealT (ElemFunc IS)) p) as [n ncv].\n  exists n. intros i H.\n  rewrite CRabs_minus_sym, CRabs_right.\n  - apply (CRle_trans _ (MeasureSet Aint - MeasureSet (seqInt i))).\n    apply CRplus_le_compat_l, CRopp_ge_le_contravar.\n    apply MeasureNonDecreasing. intros.\n    apply applyUnionIterate. exists i. exact (conj (le_refl i) H0).\n    specialize (ncv i H).\n    apply (CRle_trans _ (CRpow (CR_of_Q _ (1#2)) i)).\n    generalize (seqInt i). intro iint.\n    pose proof (IntegrableApproxSequenceBound gen A Aint i).\n    destruct (IntegrableApproxSequence gen A Aint i).\n    apply CRlt_asym, X.\n    unfold CRminus in ncv. rewrite CRopp_0, CRplus_0_r, CRabs_right in ncv.\n    exact ncv. apply CRpow_ge_zero. apply CR_of_Q_le. discriminate.\n  - rewrite <- (CRplus_opp_r (MeasureSet Aint)).\n    apply CRplus_le_compat_l, CRopp_ge_le_contravar.\n    apply MeasureNonDecreasing. intros. apply applyUnionIterate in H0.\n    destruct H0, H0.\n    pose proof (IntegrableApproxSequenceInc gen A Aint x0 x).\n    destruct (IntegrableApproxSequence gen A Aint x0). exact (H2 H1).\nQed.\n\n(* It is enough to truncate on generator sets to prove that\n   a function is measurable. Bishop's lemma 4.9. *)\nLemma MeasurableGen\n  : forall {IS : IntegrationSpace}\n      (h : PartialFunction (X (ElemFunc IS))),\n    (forall (A : (X (ElemFunc IS)) -> Prop) (Aint : IntegrableSet A)\n       (k : positive)\n       (eps : CRcarrier (RealT (ElemFunc IS))) (epsPos : 0 < eps),\n        { B : SetApprox A Aint eps &\n        IntegrableFunction\n          (XmaxConst (XminConst (Xmult (CharacFunc (sa_approx _ _ _ B)) h)\n                                (CR_of_Q _ (Z.pos k # 1)))\n                     (CR_of_Q _ (Z.neg k # 1))) })\n    -> MeasurableFunction h.\nProof.\n  intros IS f fMes A n Aint. \n  pose (fun S Sint eps epsPos => let (B,_) := fMes S Sint n eps epsPos in B) as gen.\n  (* Make a disjoint sequence of subsets B_k that converges to A\n     in measure. Bound h by n so that B_k h converges monotonically\n     towards (union B_k) h. *)\n  pose (fun k:nat => match k with\n                | O => let (U,_):=IntegrableApproxSequence gen A Aint O in U\n                | S i => let (U,Uint):=IntegrableApproxSequence gen A Aint i in\n                        sa_approx _ _ _\n                                  (gen _ (IntegrableSetDifference A U Aint Uint)\n                                       (CRpow (CR_of_Q (RealT (ElemFunc IS)) (1 # 2)) k)\n                                       (CRpow_gt_zero (CR_of_Q (RealT (ElemFunc IS)) (1 # 2)) \n                                               k (CR_of_Q_pos (1 # 2) eq_refl)))\n                end) as Bk.\n  assert (forall k:nat, IntegrableSet (Bk k)) as BkInt.\n  { intro k. unfold Bk. destruct k.\n    - destruct (IntegrableApproxSequence gen A Aint 0). exact i.\n    - destruct (IntegrableApproxSequence gen A Aint k). apply sa_bint. }\n  assert (forall k:nat, Integral (BkInt (S k)) <= CRpow (CR_of_Q _ (1 # 2)) k) as BkMaj.\n  { intro k. pose proof (IntegrableApproxSequenceBound gen A Aint k). \n    pose proof (IntegrableApproxSequenceInc gen A Aint k).\n    destruct (IntegrableApproxSequence gen A Aint k) as [U Uint] eqn:des.\n    apply (CRle_trans _ (MeasureSet (IntegrableSetDifference A U Aint Uint))).\n    apply IntegralNonDecreasing. intros x xdf xdg.\n    simpl. simpl in xdf. destruct xdf. rewrite des in y.\n    destruct xdg. apply CRle_refl. contradict n0.\n    exact (sa_inc _ _ _ _ x y).\n    destruct xdg. apply CRlt_asym, CRzero_lt_one. apply CRle_refl.\n    rewrite MeasureDifferenceIncluded. apply CRlt_asym, X.\n    intros. exact (H x H0). }\n  pose (fun k:nat => (XmaxConst\n              (XminConst\n                 (Xmult (CharacFunc (Bk k)) f)\n                 (CR_of_Q (RealT (ElemFunc IS)) (Z.pos n # 1)))\n              (CR_of_Q (RealT (ElemFunc IS)) (Z.neg n # 1)))) as fk.\n  assert (forall k:nat, IntegrableFunction (fk k)) as fkInt.\n  { unfold fk, Bk. intro k. destruct k.\n    - simpl. unfold gen. \n      destruct (fMes A Aint n 1 (CRzero_lt_one (RealT (ElemFunc IS)))), x; apply i.\n    - destruct (IntegrableApproxSequence gen A Aint k) as [U Uint].\n      unfold gen.\n      destruct (fMes (fun x : X (ElemFunc IS) => A x /\\ ~ U x)\n                     (IntegrableSetDifference A U Aint Uint) n\n                     (CRpow (CR_of_Q (RealT (ElemFunc IS)) (1 # 2)) (S k))\n                     (CRpow_gt_zero (CR_of_Q (RealT (ElemFunc IS)) (1 # 2)) \n                             (S k) (CR_of_Q_pos (1 # 2) eq_refl)))\n        as [B Bint].\n      refine (IntegrableFunctionExtensional _ _ _ Bint). split.\n      + intros y yD. exact yD.\n      + intros. rewrite (DomainProp _ x xD xG). reflexivity. }\n  assert (forall (i : nat) x (xkD : forall k:nat, Domain (CharacFunc (Bk k)) x),\n             (let (U, _) := IntegrableApproxSequence gen A Aint i in U x)\n             -> @CRsum (RealT (ElemFunc IS))\n                      (fun k : nat => partialApply _ x (xkD k)) i == 1) as BkDisjoint.\n  { induction i.\n    - intros. simpl.\n      destruct (xkD O). reflexivity. contradict n0.\n      simpl. simpl in H.\n      destruct (gen A Aint 1 (CRzero_lt_one (RealT (ElemFunc IS)))). exact H.\n    - intros. specialize (IHi x xkD).\n      simpl in H; destruct (IntegrableApproxSequence gen A Aint i) as [U Uint] eqn:des.\n      destruct H.\n      (* In U so last term is zero. *)\n      specialize (IHi H). rewrite <- (CRplus_0_r 1). simpl.\n      simpl in IHi. rewrite IHi. clear IHi. apply CRplus_morph. reflexivity.\n      destruct (xkD (S i)). 2: reflexivity. exfalso.\n      unfold Bk in b. rewrite des in b.\n      pose proof (sa_inc _ _ _ _ x b). destruct H0. contradiction.\n      (* Not in U x so all previous terms are 0 in the sum. *)\n      clear IHi.\n      rewrite <- (CRplus_0_l 1). simpl. apply CRplus_morph.\n      pose proof (sa_inc _ _ _ _ x H). destruct H0. clear H.\n      rewrite (CRsum_eq _ (fun k => 0)), sum_const, CRmult_0_l. reflexivity.\n      intros. destruct (xkD i0). 2: reflexivity. contradict H1.\n      pose proof (IntegrableApproxSequenceIncr\n                    gen A Aint i0 i x H). rewrite des in H1.\n      apply H1. clear H1.\n      unfold Bk in b. destruct i0. \n      destruct (IntegrableApproxSequence gen A Aint 0); exact b. \n      simpl; destruct (IntegrableApproxSequence gen A Aint i0).\n      right. exact b.\n      (* In last Bk so last term equals 1. *)\n      destruct (xkD (S i)). reflexivity. contradict n0.\n      simpl. rewrite des. exact H. } \n  assert (forall (i j : nat) x (xkD : forall k:nat, Domain (fk k) x)\n            (dG : Domain (Xmult (CharacFunc A) f) x),\n             (let (U, _) := IntegrableApproxSequence gen A Aint j in U x)\n             -> le j i\n             -> CRsum (fun k : nat => partialApply (fk k) x (xkD k)) i\n               == partialApply (XmaxConst\n          (XminConst (Xmult (CharacFunc A) f)\n             (CR_of_Q _ (Z.pos n # 1)))\n          (CR_of_Q _ (Z.neg n # 1))) x dG) as fkDisjoint.\n  { intros. unfold fk.\n    rewrite (CRsum_eq _ (fun k:nat =>\n                           partialApply _ x (fst (xkD k))\n                           * partialApply (XmaxConst\n          (XminConst f\n             (CR_of_Q _ (Z.pos n # 1)))\n          (CR_of_Q _ (Z.neg n # 1))) x \n       (snd (xkD O)))).\n    - rewrite sum_scale.\n      rewrite (BkDisjoint i x (fun k => fst (xkD k))), CRmult_1_l.\n      simpl. destruct dG, d. rewrite CRmult_1_l, (DomainProp f x _ d0).\n      reflexivity. contradict n0.\n      pose proof (IntegrableApproxSequenceInc gen A Aint j x).\n      destruct (IntegrableApproxSequence gen A Aint j). exact (H1 H).\n      exact (IntegrableApproxSequenceIncr\n               gen A Aint j i x H0 H).\n    - intros. simpl. destruct (xkD i0), d. simpl.\n      do 2 rewrite CRmult_1_l. rewrite (DomainProp f x d0 (snd (xkD 0%nat))).\n      reflexivity. simpl. rewrite CRmult_0_l, CRmult_0_l.\n      rewrite CRmin_left, CRmax_left. reflexivity.\n      apply CR_of_Q_le. discriminate.\n      apply CR_of_Q_le. discriminate. } \n  destruct (series_cv_maj (fun k : nat => Integral (IntegrableAbs (fkInt k)))\n                          (fun k => match k with\n                                 | O => MeasureSet (BkInt O)\n                                 | S i => (CRpow (CR_of_Q _ (1 # 2)) i) end\n                                 * CR_of_Q _ (Z.pos n # 1))\n                          ((CR_of_Q _ 2 + MeasureSet (BkInt O))\n                           * CR_of_Q _ (Z.pos n # 1)))\n    as [l lcv].\n  - intro k. unfold fk. rewrite CRabs_right.\n    apply (CRle_trans\n             _ (Integral (IntegrableScale _ (CR_of_Q _ (Z.pos n # 1))\n                                          (BkInt k)))).\n    apply IntegralNonDecreasing. intros x xdf xdg.\n    simpl. destruct xdf, xdg, d.\n    rewrite CRmult_1_l, CRmult_1_r.\n    apply CRabs_le. split. rewrite <- CR_of_Q_opp.\n    setoid_replace (- (Z.pos n # 1))%Q with (Z.neg n # 1).\n    apply CRmax_r. reflexivity. apply CRmax_lub.\n    apply CRmin_r. apply CR_of_Q_le. discriminate.\n    contradiction. contradiction.\n    rewrite CRmult_0_l, CRmult_0_r. rewrite CRmin_left, CRmax_left, CRabs_right.\n    apply CRle_refl. apply CRle_refl.\n    apply CR_of_Q_le. discriminate.\n    apply CR_of_Q_le. discriminate.\n    rewrite IntegralScale, CRmult_comm.\n    destruct k. rewrite CRmult_comm. apply CRle_refl.\n    rewrite CRmult_comm. apply CRmult_le_compat_r. \n    apply CR_of_Q_le. discriminate. exact (BkMaj k).\n    apply IntegralNonNeg. intros x xdf. apply CRabs_pos.\n  - apply series_cv_scale.\n    apply (series_cv_shift (fun n0 : nat => match n0 with\n     | 0%nat => MeasureSet (BkInt 0%nat)\n     | S i => CRpow (CR_of_Q (RealT (ElemFunc IS)) (1 # 2)) i\n     end) O); simpl. exact GeoHalfTwo.\n  - destruct lcv.\n    pose proof (IntegrableFunctionsComplete IS fk fkInt l s) as [rep repcv]. \n    apply (IntegrableExtensionalAE (XinfiniteSumAbs (IntFn rep))).\n    + exists (Xplus (CharacFunc A) (XinfiniteSumAbs (IntFn rep))).\n      split. apply IntegrablePlus. apply Aint.\n      exists rep. apply PartialRestriction_refl. intros. split. exact (fst H).\n      destruct repcv, p. clear c0. specialize (d x (snd H)).\n      destruct d as [xn d]. pose proof (xn O). destruct H0. exact d1.\n    + pose proof (IntegrableApproxSequenceLimit gen A Aint) as [Uint Umes].\n      destruct (MeasureZeroAE _ (IntegrableSetDifference A _ Aint Uint)) as [h hInt].\n      rewrite MeasureDifferenceIncluded.\n      rewrite Umes. unfold CRminus. apply CRplus_opp_r.\n      intros. destruct H.\n      pose proof (IntegrableApproxSequenceInc gen A Aint x0 x).\n      destruct (IntegrableApproxSequence gen A Aint x0). exact (H0 H). \n      exists (Xplus (CharacFunc (fun x : X (ElemFunc IS) =>\n            exists n : nat,\n              let (U, _) := IntegrableApproxSequence gen A Aint n in U x))\n               h).\n      split. exact (IntegrablePlus _ _ Uint (fst hInt)).\n      intros. destruct H, hInt. specialize (n0 x d0).\n      destruct repcv, p. rewrite (c0 x dF (d1 x dF)). clear c0.\n      destruct d.\n      (* Inside union *)\n      clear n0. destruct e. apply applyInfiniteSumAbs. intro p.\n      exists x0. intros. rewrite (fkDisjoint i0 x0 x _ dG).\n      unfold CRminus. rewrite CRplus_opp_r, CRabs_right.\n      apply CR_of_Q_le. discriminate.\n      apply CRle_refl. exact H. exact H0.\n      (* Outside A *)\n      assert (~ A x).\n      { intro abs. apply n0. split; assumption. }\n      clear n1 n0 i d0 h. transitivity (CR_of_Q (RealT (ElemFunc IS)) 0).\n      apply applyInfiniteSumAbs.\n      apply (CR_cv_eq _ (fun _ => 0)). 2: apply CR_cv_const.\n      intros. rewrite <- (CRmult_0_l (INR (S n0))).\n      rewrite (CRsum_eq _ (fun _ => 0)). symmetry. apply sum_const.\n      intros. unfold fk. simpl.\n      destruct (domainInfiniteSumAbsIncReverse\n            (fun k : nat =>\n             XmaxConst\n               (XminConst (Xmult (CharacFunc (Bk k)) f)\n                  (CR_of_Q (RealT (ElemFunc IS)) (Z.pos n # 1)))\n               (CR_of_Q (RealT (ElemFunc IS)) (Z.neg n # 1))) x \n            (d1 x dF) i), d.\n      contradict H. unfold Bk in b.\n      destruct i.\n      pose proof (IntegrableApproxSequenceInc gen A Aint O x).\n      destruct (IntegrableApproxSequence gen A Aint 0). exact (H b).\n      destruct (IntegrableApproxSequence gen A Aint i).\n      exact (proj1 (sa_inc _ _ _ _ x b)). \n      rewrite CRmult_0_l, CRmin_left, CRmax_left. reflexivity.\n      apply CR_of_Q_le. discriminate.\n      apply CR_of_Q_le. discriminate.\n      simpl. destruct dG, d. contradiction.\n      rewrite CRmult_0_l, CRmin_left, CRmax_left. reflexivity.\n      apply CR_of_Q_le. discriminate.\n      apply CR_of_Q_le. discriminate.\n    + exists rep. apply PartialRestriction_refl. \nQed.\n\nLemma CR_cv_maj : forall {R : ConstructiveReals}\n                    (un vn : nat -> CRcarrier R) (s : CRcarrier R),\n    (forall n:nat, CRabs R (un (S n) - un n) <= vn n)\n    -> series_cv vn s\n    -> { l : CRcarrier R & prod (CR_cv _ un l) (l <= s + un O) }.\nProof.\n  intros. \n  destruct (series_cv_maj (fun n => un (S n) - un n) vn s H H0) as [l [lcv lmaj]].\n  apply (CR_cv_eq (fun n => un (S n) - un O)) in lcv.\n  - exists (l + un O). split. apply (CR_cv_shift _ 1).\n    apply (CR_cv_eq _ (fun n => un (S n) - un O + un O)).\n    intros. unfold CRminus. rewrite CRplus_assoc, CRplus_opp_l, CRplus_0_r.\n    rewrite Nat.add_comm. reflexivity. apply CR_cv_plus.\n    exact lcv. apply CR_cv_const. unfold CRminus.\n    apply CRplus_le_compat_r. exact lmaj.\n  - induction n. reflexivity. simpl. rewrite IHn. clear IHn.\n    rewrite CRplus_comm. unfold CRminus. rewrite CRplus_assoc.\n    apply CRplus_morph. reflexivity.\n    rewrite <- CRplus_assoc, CRplus_opp_l, CRplus_0_l. reflexivity.\nQed.\n\n(* Bishop's lemma 4.10. We strengthen the previous lemma by\n   allowing the function to approximate within epsilon on each\n   generator subset. This proves that continuous functions are\n   measurable, because they are approximated by piecewise-constant functions. *)\nLemma MeasurableGenApprox\n  : forall {IS : IntegrationSpace}\n      (h : PartialFunction (X (ElemFunc IS))),\n    almost_everywhere (Domain h)\n    -> (forall (A : (X (ElemFunc IS)) -> Prop) (Aint : IntegrableSet A)\n         (n : positive)\n         (eps : CRcarrier (RealT (ElemFunc IS))) (epsPos : 0 < eps),\n          { fB : prod (PartialFunction (X (ElemFunc IS)))\n                      (SetApprox A Aint eps)\n                & prod (IntegrableFunction (fst fB))\n                       (forall (x : X (ElemFunc IS)) (xdh : Domain h x)\n                          (xdf : Domain (fst fB) x),\n                           sa_approx _ _ _ (snd fB) x\n                           -> CRabs _ (partialApply (XmaxConst (XminConst h \n                                                                       (CR_of_Q _ (Z.pos n # 1)))\n                                                            (CR_of_Q _ (Z.neg n # 1)))\n                                                 x xdh\n                                    - partialApply _ x xdf) < eps) })\n    -> MeasurableFunction h.\nProof.\n  intros IS h dom H. apply MeasurableGen.\n  intros A Aint k eps epsPos. specialize (H A Aint k).\n  (* We define another family of generator sets and call the previous lemma on it. *)\n  assert (forall (i:nat), 0 < eps * CRpow (CR_of_Q _ (1 # 2)) i) as H0.\n  { intros. apply (CRmult_lt_0_compat _ _ _ epsPos).\n    apply CRpow_gt_zero, CR_of_Q_pos. reflexivity. }\n  pose (fun (i:nat) => sa_approx\n                    _ _ _ (let (fB,_) := H (eps * CRpow (CR_of_Q _ (1#2)) (S i))\n                                           (H0 (S i)) in\n                           snd fB))\n    as Bi.\n  assert ({ BI : IntegrableSet (fun x => forall i:nat, Bi i x)\n                 & MeasureSet Aint - MeasureSet BI < eps })\n    as Bint.\n  { destruct (CR_cv_maj\n                (fun n => - MeasureSet (IntegrableSetIntersectIterate\n                                     _ (fun i => sa_bint _ _ _ (let (fB,_) := H (eps * CRpow (CR_of_Q _ (1 # 2)) (S i)) (H0 (S i)) in snd fB)) n))\n                (fun n => (CRpow (CR_of_Q _ (1 # 2)) (2 + n) * eps))\n                (CR_of_Q _ (1 # 2) * eps)).\n    intro n. unfold CRminus. rewrite CRopp_involutive, CRplus_comm.\n    pose proof (@MeasureDifferenceIncluded IS). unfold CRminus in H1.\n    rewrite <- H1, CRabs_right. clear H1.\n    2: apply MeasureNonNeg.\n    apply (CRle_trans _ (MeasureSet Aint\n                         - MeasureSet (sa_bint _ _ _\n          (let (fB,_) := H (eps * CRpow (CR_of_Q _ (1 # 2)) (2 + n))\n             (H0 (2 + n)%nat) in snd fB)))).\n    rewrite <- MeasureDifferenceIncluded.\n    apply MeasureNonDecreasing. intros. destruct H1. split.\n    apply (sa_inc _ _ _ (let (fB,_) := H (eps * CRpow (CR_of_Q _ (1 # 2)) (S n))\n                             (H0 (S n)) in snd fB)).\n    destruct n; apply H1. intro abs. contradict H2.\n    split; assumption. apply sa_inc.\n    rewrite <- (CRmult_comm eps). apply CRlt_asym. apply sa_mes.\n    clear H1. intros. apply H1.\n    apply (series_cv_eq (fun n : nat => CRpow (CR_of_Q _ (1 # 2)) n\n                                   * ((CR_of_Q _ (1 # 2)) * (CR_of_Q _ (1 # 2)) * eps))).\n    intros. simpl. rewrite <- CRmult_assoc.\n    apply CRmult_morph. 2: reflexivity.\n    rewrite (CRmult_comm (CRpow (CR_of_Q _ (1 # 2)) n)), <- CRmult_assoc.\n    reflexivity.\n    apply (CR_cv_proper _ (CR_of_Q _ 2 * (CR_of_Q _ (1 # 2) * CR_of_Q _ (1 # 2) * eps))).\n    apply series_cv_scale. exact GeoHalfTwo.\n    rewrite <- CRmult_assoc, <- CRmult_assoc, <- (CR_of_Q_mult _ 2).\n    setoid_replace (2 * (1#2))%Q with 1%Q.\n    rewrite CRmult_1_l. reflexivity. reflexivity.\n    destruct p. simpl in c0. apply CR_cv_opp in c.\n    apply (CR_cv_eq (fun n : nat => MeasureSet\n           (IntegrableSetIntersectIterate\n              _ (fun i : nat =>\n               sa_bint A Aint\n                 (eps * CRpow (CR_of_Q (RealT (ElemFunc IS)) (1 # 2)) (S i))\n                 (let (fB, _) := H\n                    (eps * CRpow (CR_of_Q (RealT (ElemFunc IS)) (1 # 2)) (S i))\n                    (H0 (S i)) in snd fB)) n))) in c.\n    destruct (IntegrableSetCountableIntersect _ _ _ c)\n      as [intersectInt c1].\n    exists intersectInt. clear c. rewrite <- CRopp_involutive, <- c1 in c0.\n    clear c1 x. apply (CRplus_le_compat_l (MeasureSet Aint)) in c0.\n    rewrite (CRplus_comm (CR_of_Q (RealT (ElemFunc IS)) (1 # 2) * eps)) in c0.\n    rewrite <- CRplus_assoc in c0. \n    apply (CRle_lt_trans _ _ _ c0). clear c0.\n    apply (CRlt_le_trans _ (eps * (CR_of_Q (RealT (ElemFunc IS)) (1 # 2) * 1)\n                            + CR_of_Q (RealT (ElemFunc IS)) (1 # 2) * eps)).\n    apply CRplus_lt_compat_r. apply sa_mes.\n    rewrite CRmult_1_r, CRmult_comm, <- CRmult_plus_distr_r, <- CR_of_Q_plus.\n    setoid_replace ((1 # 2) + (1 # 2))%Q with 1%Q.\n    rewrite CRmult_1_l. apply CRle_refl. reflexivity.\n    intro n. apply CRopp_involutive. }\n  assert (forall (x : X (ElemFunc IS)), (forall i : nat, Bi i x) -> A x).\n  { intros. unfold Bi in H1. exact (sa_inc _ _ _ _ x (H1 O)). }\n  destruct Bint as [BI Bmaj].\n  exists (Build_SetApprox IS A Aint eps _ BI Bmaj H1).\n  pose (fun i:nat => let (fB,_) := H (eps * CRpow (CR_of_Q _ (1#2)) (S i))\n                                (H0 (S i)) in fst fB) as fi.\n  assert (forall i:nat, IntegrableFunction\n                   (Xmult (CharacFunc (fun x => forall i : nat, Bi i x))\n                          (fi i))) as fiInt.\n  { intro i. unfold fi.\n    destruct (H (eps * CRpow (CR_of_Q _ (1 # 2)) (S i)) (H0 (S i))).\n    exact (RestrictedIntegrable (fst p) BI). } \n  destruct (series_cv_maj \n              (fun n : nat => Integral (IntegrableAbs\n               (IntegrableMinus (fiInt (S n)) (fiInt n))))\n              (fun n:nat => CRpow (CR_of_Q _ (1#2)) n\n                       * (CR_of_Q _ 2 * eps * MeasureSet BI))\n              (CR_of_Q _ 2 * (CR_of_Q _ 2 * eps * MeasureSet BI)))\n    as [l lcv].\n  - intro n. rewrite CRabs_right.\n    destruct dom as [hdom [hdomInt dom]].\n    apply (CRle_trans _ (Integral (IntegrablePlus _ _\n                                     (IntegrableScale _ 0 hdomInt)\n                                     (IntegrableScale _ (CR_of_Q _ 2 * (eps * CRpow (CR_of_Q _ (1 # 2)) n)) BI)))).\n    apply IntegralNonDecreasing. intros x xdf xdg. \n    unfold fi. unfold fi in xdf.\n    destruct xdg as [d d0]. destruct d0.\n    pose proof (b n) as bn. unfold Bi in bn.\n    pose proof (b (S n)) as bSn. unfold Bi in bSn.\n    destruct (H (eps * CRpow (CR_of_Q _ (1 # 2)) (S n)) (H0 (S n)))\n      as [x0 p].\n    destruct (H (eps * CRpow (CR_of_Q _ (1 # 2)) (S (S n))) (H0 (S (S n))))\n      as [x1 p0].\n    rewrite applyXabs.\n    + setoid_replace (partialApply (Xminus\n          (Xmult (CharacFunc (fun x2 : X (ElemFunc IS) => forall i : nat, Bi i x2)) (fst x1))\n          (Xmult (CharacFunc (fun x2 : X (ElemFunc IS) => forall i : nat, Bi i x2)) (fst x0)))\n                                   x xdf)\n        with (partialApply _ x (fst xdf)\n            - partialApply\n             (XmaxConst (XminConst h (CR_of_Q _ (Z.pos k # 1)))\n                (CR_of_Q _ (Z.neg k # 1))) x (dom x d)\n            + (partialApply\n             (XmaxConst (XminConst h (CR_of_Q _ (Z.pos k # 1)))\n                (CR_of_Q _ (Z.neg k # 1))) x (dom x d)\n            - partialApply (Xmult (CharacFunc (fun x2 : X (ElemFunc IS) => forall i : nat, Bi i x2))\n             (fst x0)) x (snd xdf))).\n      apply (CRle_trans _ _ _ (CRabs_triang _ _)).\n      rewrite applyXplus, applyXscale, CRmult_0_l, CRplus_0_l.\n      rewrite applyXscale, (CR_of_Q_plus _ 1 1).\n      rewrite CRmult_plus_distr_r, CRmult_plus_distr_r, CRmult_1_l.\n      apply CRplus_le_compat.\n      destruct xdf, d1, d0, d0. simpl.\n      rewrite CRmult_1_r, CRmult_1_l. apply CRlt_asym.\n      destruct p0. specialize (c x (dom x d) d3).\n      apply (CRle_lt_trans _ (CRabs (RealT (ElemFunc IS))\n        (partialApply\n           (XmaxConst (XminConst h (CR_of_Q (RealT (ElemFunc IS)) (Z.pos k # 1)))\n              (CR_of_Q (RealT (ElemFunc IS)) (Z.neg k # 1))) x \n           (dom x d) - partialApply (fst x1) x d3))).\n      rewrite CRabs_minus_sym. apply CRle_refl.\n      apply (CRlt_le_trans\n               _ (eps * CRpow (CR_of_Q (RealT (ElemFunc IS)) (1 # 2)) (S (S n)))).\n      apply c. exact bSn.\n      simpl. rewrite <- CRmult_assoc.\n      rewrite <- CRmult_assoc. apply CRmult_le_compat_r.\n      apply CRpow_ge_zero. apply CR_of_Q_le. discriminate.\n      rewrite <- (CRmult_1_r eps), CRmult_assoc, CRmult_assoc.\n      apply CRmult_le_compat_l. apply CRlt_asym, epsPos.\n      rewrite CRmult_1_l, <- CR_of_Q_mult.\n      apply CR_of_Q_le. discriminate.\n      contradiction. \n      destruct xdf, d1, d1. simpl. rewrite CRmult_1_r, CRmult_1_l.\n      apply CRlt_asym.\n      apply (CRlt_le_trans _ (eps * CRpow (CR_of_Q _ (1 # 2)) (S n))).\n      apply (snd p). \n      exact bn. apply CRmult_le_compat_l. apply CRlt_asym, epsPos.\n      rewrite <- (CRmult_1_l (CRpow (CR_of_Q (RealT (ElemFunc IS)) (1 # 2)) n)).\n      apply CRmult_le_compat_r.\n      apply CRpow_ge_zero. apply CR_of_Q_le. discriminate.\n      apply CR_of_Q_le. discriminate. contradiction.\n      unfold CRminus. rewrite CRplus_assoc. \n      destruct xdf.\n      rewrite (applyXminus (Xmult\n          (CharacFunc\n             (fun x2 : X (ElemFunc IS) => forall i : nat, Bi i x2)) (fst x1)) (Xmult\n          (CharacFunc\n             (fun x2 : X (ElemFunc IS) => forall i : nat, Bi i x2))\n          (fst x0)) x d0 d1).\n      apply CRplus_morph. reflexivity.\n      rewrite <- CRplus_assoc, CRplus_opp_l, CRplus_0_l. reflexivity.\n    + (* out of B *)\n      simpl. rewrite CRmult_0_r, CRmult_0_l.\n      destruct xdf, d0, d0. contradiction. rewrite CRmult_0_l.\n      destruct d1, d0. contradiction. rewrite CRmult_0_l, CRmult_0_r.\n      rewrite CRabs_right. apply CRle_refl. rewrite CRplus_0_r. apply CRle_refl.\n    + (* Integral majoration *)\n      rewrite IntegralPlus, IntegralScale, CRmult_0_r, CRplus_0_l.\n      rewrite IntegralScale. rewrite CRmult_comm, <- CRmult_assoc, <- CRmult_assoc.\n      rewrite (CRmult_comm (CR_of_Q (RealT (ElemFunc IS)) 2 * eps)).\n      apply CRle_refl.\n    + apply IntegralNonNeg. intros x xdf.\n      rewrite applyXabs. apply CRabs_pos.\n  - apply series_cv_scale. exact GeoHalfTwo.\n  - destruct lcv.\n    destruct (IntegrableXpointwiseLimit _ fiInt l s) as [limInt fcv]. clear s.\n    refine (IntegrableExtensionalAE _ _ _ _ limInt).\n    + destruct dom as [hdom [hdomInt dom]].\n      exists (Xplus hdom (XpointwiseLimit\n                (fun i : nat =>\n                 Xmult\n                   (CharacFunc (fun x : X (ElemFunc IS) => forall i0 : nat, Bi i0 x))\n                   (fi i)))). split.\n      apply IntegrablePlus. exact hdomInt. exact limInt.\n      intros x [xdf xdg]. split.\n      2: exact (dom x xdf). simpl. destruct xdg as [xDn xdg].\n      destruct (xDn O). exact d.\n    + destruct dom as [hdom [hdomInt dom]]. exists hdom. split.\n      exact hdomInt. intros. unfold sa_approx.\n      apply applyPointwiseLimit. destruct dG, d. simpl in s.\n      (* Inside the intersection, the fi converge towards h. *)\n      apply (CR_cv_proper _ (partialApply (XmaxConst\n          (XminConst h\n             (CR_of_Q (RealT (ElemFunc IS)) (Z.pos k # 1)))\n          (CR_of_Q (RealT (ElemFunc IS)) (Z.neg k # 1))) x d0)).\n      2: simpl; rewrite CRmult_1_l; reflexivity.\n      apply (CR_cv_eq _ (fun n : nat => partialApply (fi n) x\n                                                (let (xn, _) := dF in snd (xn n)))).\n      intro n. simpl. destruct dF, (x0 n), d.\n      rewrite CRmult_1_l. reflexivity. contradiction. \n      intro p.\n      assert (CR_cv _ (fun i => CRpow (CR_of_Q _ (1 # 2)) i * eps) 0).\n      { apply (CR_cv_proper _ (0 * eps)).\n        apply CR_cv_scale. exact GeoCvZero. apply CRmult_0_l. }\n      specialize (H3 p) as [j jmaj]. exists j. intros.\n      specialize (jmaj j (le_refl j)).\n      unfold fi. destruct dF. destruct (x0 i). unfold snd.\n      unfold fi in d1. unfold Bi in s. specialize (s i).\n      destruct (H (eps * CRpow (CR_of_Q _ (1 # 2)) (S i)) (H0 (S i))).\n      destruct p0 as [i0 c1]. rewrite CRabs_minus_sym. specialize (c1 x).\n      apply (CRle_trans _ (eps * CRpow (CR_of_Q _ (1 # 2)) (S i))).\n      apply CRlt_asym, c1, s. clear c1. \n      refine (CRle_trans _ _ _ _ jmaj).\n      unfold CRminus. rewrite CRopp_0, CRplus_0_r.\n      rewrite CRabs_right, CRmult_comm. apply CRmult_le_compat_r.\n      apply CRlt_asym, epsPos.\n      apply Nat.le_exists_sub in H3. destruct H3, H3. subst i.\n      rewrite <- (CRmult_1_l (CRpow (CR_of_Q _ (1 # 2)) j)).\n      replace (S (x2 + j)) with (S x2 + j)%nat. 2: reflexivity.\n      rewrite <- CRpow_plus_distr. apply CRmult_le_compat_r.\n      apply CRpow_ge_zero. apply CR_of_Q_le. discriminate.\n      apply (CRmult_le_reg_l (CRpow (CR_of_Q _ 2) (S x2))).\n      apply CRpow_gt_zero, CR_of_Q_pos. reflexivity. rewrite CRpow_mult.\n      rewrite <- (CRpow_proper 1). rewrite CRpow_one, CRmult_1_r.\n      apply CRpow_ge_one. apply CR_of_Q_le. discriminate.\n      rewrite <- CR_of_Q_mult. apply CR_of_Q_morph. reflexivity.\n      apply CRmult_le_0_compat. \n      apply CRpow_ge_zero. apply CR_of_Q_le. discriminate.\n      apply CRlt_asym, epsPos.\n      (* Outside the intersection, 0 == 0. *)\n      unfold sa_approx in n. apply (CR_cv_eq _ (fun _ => 0)).\n      intros. simpl. destruct dF, (x0 n0), d.\n      contradiction. rewrite CRmult_0_l. reflexivity.\n      apply (CR_cv_proper _ 0). apply CR_cv_const.\n      simpl. rewrite CRmult_0_l, CRmin_left, CRmax_left. reflexivity.\n      apply CR_of_Q_le. discriminate.\n      apply CR_of_Q_le. discriminate.\nQed.\n\n(* The convergence in measure of a series of functions.\n   It is the constructive counterpart of the pointwise convergence,\n   weaker than uniform convergence. It is designed so that\n   when a sequence fn of measurable functions converges towards\n   function f, then f is measurable also (as would happen classically\n   with pointwise convergence).\n\n   For example the sequence of triangles (-1/n, 0), (0,n), (1/n,0)\n   converges in measure towards 0. To prove that, take N an integer\n   such as 2/N < eps. The SetApprox B simply removes the interval\n   [-1/N, 1/N], where all the mass is.\n\n   However the integrals of the triangles are all 1, which does not\n   converge towards 0. *)\nDefinition CvMeasure {IS : IntegrationSpace}\n           (fn : nat -> @PartialFunction (RealT (ElemFunc IS)) (X (ElemFunc IS)))\n           (f : @PartialFunction (RealT (ElemFunc IS)) (X (ElemFunc IS))) : Type\n  := forall (A : (X (ElemFunc IS)) -> Prop) (Aint : IntegrableSet A)\n       (eps : CRcarrier (RealT (ElemFunc IS))),\n    0 < eps\n    -> { N : nat  &  forall n:nat, le N n\n         -> { B : SetApprox A Aint eps\n                 & (forall x xdf xdfn, sa_approx _ _ _ B x\n                       -> CRabs _ (partialApply f x xdf - partialApply (fn n) x xdfn)\n                         < eps) } }.\n\nLemma CvMeasureMeasurable\n  : forall {IS : IntegrationSpace}\n      (fn : nat -> @PartialFunction (RealT (ElemFunc IS)) (X (ElemFunc IS)))\n      (f : @PartialFunction (RealT (ElemFunc IS)) (X (ElemFunc IS))),\n    almost_everywhere (Domain f)\n    -> (forall n:nat, MeasurableFunction (fn n))\n    -> CvMeasure fn f\n    -> MeasurableFunction f.\nProof.\n  intros IS fn f fFull fnMes fnCv.\n  apply (MeasurableGenApprox f fFull). intros.\n  specialize (fnCv A Aint eps epsPos) as [N Ncv].\n  specialize (Ncv N (le_refl N)) as [B Bcv].\n  specialize (fnMes N A n Aint).\n  exists (pair (XmaxConst\n               (XminConst (Xmult (CharacFunc A) (fn N))\n                  (CR_of_Q (RealT (ElemFunc IS)) (Z.pos n # 1)))\n               (CR_of_Q (RealT (ElemFunc IS)) (Z.neg n # 1))) B).\n  split. exact fnMes. unfold fst, snd. intros. \n  specialize (Bcv x xdh (snd xdf) H).\n  refine (CRle_lt_trans _ _ _ _ Bcv). clear Bcv.\n  rewrite applyXmaxConst, applyXmaxConst.\n  apply (CRle_trans _ _ _ (CRmax_contract _ _ _)).\n  rewrite applyXminConst, applyXminConst.\n  apply (CRle_trans _ _ _ (CRmin_contract _ _ _)).\n  simpl. destruct xdf, d. rewrite CRmult_1_l. apply CRle_refl.\n  contradict n0. apply (sa_inc _ _ _ _ x H).\nQed.\n\n(* fn converging in measure towards 0 is not enough to guarantee\n   that the limit of I(fn) converge towards 0. An extra hypothesis\n   of domination suffices. *)\nRecord IntegralDominated {IS : IntegrationSpace}\n       (fn : nat -> @PartialFunction (RealT (ElemFunc IS)) (X (ElemFunc IS)))\n       (fnInt : forall n:nat, IntegrableFunction (fn n))\n       (eps : CRcarrier (RealT (ElemFunc IS))) : Type :=\n  { idom_support : (X (ElemFunc IS)) -> Prop; \n    idom_idx : nat;\n    idom_delta : CRcarrier (RealT (ElemFunc IS));\n    idom_delta_pos : 0 < idom_delta;\n    idom_int : IntegrableSet idom_support;\n    idom_dom : forall (B : X (ElemFunc IS) -> Prop) (Bmes : MeasurableSet B) (n:nat),\n        le idom_idx n\n        -> Integral (MeasurableIntersectIntegrable Bmes idom_int) < idom_delta\n        -> Integral (RestrictedMeasurable (fnInt n) Bmes) < eps }.\n       \n(* Bishop's lemma 4.14. *)\nLemma DominatedMeasureCvZero\n  : forall {IS : IntegrationSpace}\n      (fn : nat -> @PartialFunction (RealT (ElemFunc IS)) (X (ElemFunc IS)))\n      (fnInt : forall n:nat, IntegrableFunction (fn n)),\n    CvMeasure fn (Xconst _ 0)\n    -> (forall n:nat, nonNegFunc (fn n))\n    -> (forall (eps : CRcarrier (RealT (ElemFunc IS))) (epsPos : 0 < eps),\n          IntegralDominated fn fnInt eps)\n    -> CR_cv _ (fun n:nat => Integral (fnInt n)) 0.\nProof.\n  intros IS fn fnInt fnCvZero fnPos fnDominated.\n  apply Un_cv_real_nat. intros eps epsPos.\n  assert (0 < eps * CR_of_Q _ (1#2)) as halfEpsPos.\n  { apply CRmult_lt_0_compat. exact epsPos.\n    apply CR_of_Q_pos. reflexivity. }\n  destruct (fnDominated _ halfEpsPos).\n  assert (0 < MeasureSet idom_int0 + 1) as H.\n  { apply (CRlt_le_trans _ 1). apply CRzero_lt_one.\n    rewrite <- (CRplus_0_l 1), <- CRplus_assoc. apply CRplus_le_compat_r.\n    rewrite CRplus_0_r. apply MeasureNonNeg. }\n  assert (0 < CRmin (eps * CR_of_Q _ (1#2) * CRinv _ _ (inr H)) idom_delta0)\n    as H0.\n  { apply CRmin_lt. 2: exact idom_delta_pos0.\n    apply CRmult_lt_0_compat. apply CRmult_lt_0_compat.\n    exact epsPos. apply CR_of_Q_pos. reflexivity.\n    apply CRinv_0_lt_compat, H. }\n  specialize (fnCvZero idom_support0 idom_int0 _ H0) as [N Nmaj].\n  exists (max N idom_idx0). intros.\n  specialize (Nmaj i (le_trans _ _ _ (Nat.le_max_l _ _) H1)) as [[C Cint] Cmaj].\n  unfold sa_approx in Cmaj.\n  assert (Integral\n            (MeasurableIntersectIntegrable\n               (MeasurableSetCompl C (IntegrableMeasurable (CharacFunc C) Cint))\n               idom_int0) < idom_delta0) as H2.\n  { apply (CRlt_le_trans\n             _ (CRmin (eps * CR_of_Q _ (1#2) * (/ (MeasureSet idom_int0 + 1)) (inr H)) idom_delta0)).\n    2: apply CRmin_r.\n    refine (CRle_lt_trans _ _ _ _ sa_mes0).\n    rewrite <- MeasureDifferenceIncluded. 2: exact sa_inc0.\n    apply IntegralNonDecreasing. intros x xdf xdg. simpl.\n    destruct xdf. destruct xdg. apply CRle_refl.\n    contradict n. split; apply a.\n    destruct xdg. apply CRlt_asym, CRzero_lt_one. apply CRle_refl. }\n  assert (le idom_idx0 i).\n  { apply (le_trans _ (max N idom_idx0)). apply Nat.le_max_r. exact H1. }\n  specialize (idom_dom0 _ _ _ H3 H2). clear H2 H3.\n  apply (CRle_lt_trans\n           _ (Integral\n                (RestrictedMeasurable\n                   (fnInt i) (MeasurableSetCompl\n                                C (IntegrableMeasurable (CharacFunc C) Cint)))\n              + Integral (RestrictedIntegrable (fnInt i) Cint))).\n  unfold CRminus. rewrite CRopp_0, CRplus_0_r, CRabs_right.\n  - rewrite <- IntegralPlus. apply IntegralNonDecreasing. intros x xdf xdg.\n    simpl. destruct xdg, d, d0.\n    rewrite (DomainProp _ x d2 xdf), (DomainProp _ x d1 xdf).\n    destruct d, d0. contradiction.\n    rewrite CRmult_0_l, CRmult_1_l, CRplus_0_r. apply CRle_refl.\n    rewrite CRmult_0_l, CRmult_1_l, CRplus_0_l. apply CRle_refl.\n    contradiction.\n  - exact (IntegralNonNeg _ _ (fnPos i)). \n  - apply (CRlt_le_trans _ (eps * CR_of_Q (RealT (ElemFunc IS)) (1 # 2)\n                            + eps * CR_of_Q (RealT (ElemFunc IS)) (1 # 2))).\n    apply (CRplus_lt_le_compat _ _ _ _ idom_dom0). clear idom_dom0.\n    apply (CRle_trans _ (MeasureSet Cint * (eps * CR_of_Q (RealT (ElemFunc IS)) (1 # 2) *\n            (/ (MeasureSet idom_int0 + 1)) (inr H)))).\n    unfold MeasureSet. rewrite <- IntegralScale. apply IntegralNonDecreasing.\n    + intros x xdf xdg. simpl. destruct xdf, d, xdg.\n      rewrite CRmult_1_l, CRmult_1_r. clear c0. \n      specialize (Cmaj x Logic.I d0 c). apply CRlt_asym in Cmaj.\n      simpl in Cmaj. unfold CRminus in Cmaj.\n      rewrite CRplus_0_l, CRabs_opp, CRabs_right in Cmaj.\n      apply (CRle_trans _ _ _ Cmaj (CRmin_l _ _)).\n      apply fnPos. contradiction. contradiction.\n      rewrite CRmult_0_l, CRmult_0_r. apply CRle_refl.\n    + rewrite CRmult_comm, CRmult_assoc.\n      apply (CRle_trans _ (eps * CR_of_Q (RealT (ElemFunc IS)) (1 # 2) * 1)).\n      2: rewrite CRmult_1_r; apply CRle_refl.\n      apply CRmult_le_compat_l. apply CRmult_le_0_compat.\n      apply CRlt_asym, epsPos. \n      apply CR_of_Q_le. discriminate.\n      apply (CRmult_le_reg_l (MeasureSet idom_int0 + 1) _ _ H).\n      rewrite CRmult_1_r, <- CRmult_assoc, CRinv_r, CRmult_1_l.\n      apply (CRle_trans _ (MeasureSet idom_int0 + 0)).\n      rewrite CRplus_0_r. exact (MeasureNonDecreasing _ _ _ _ sa_inc0).\n      apply CRplus_le_compat_l. apply CRlt_asym, CRzero_lt_one.\n    + rewrite <- CRmult_plus_distr_l, <- CR_of_Q_plus.\n      setoid_replace ((1 # 2) + (1 # 2))%Q with 1%Q. 2: reflexivity.\n      rewrite CRmult_1_r. apply CRle_refl.\nQed.\n\nLemma DominatedConvergence\n  : forall {IS : IntegrationSpace}\n      (fn : nat -> @PartialFunction (RealT (ElemFunc IS)) (X (ElemFunc IS)))\n      (fnInt : forall n:nat, IntegrableFunction (fn n))\n      (f g : @PartialFunction (RealT (ElemFunc IS)) (X (ElemFunc IS)))\n      (fInt : IntegrableFunction f),\n    CvMeasure fn f\n    -> IntegrableFunction g\n    -> (forall n:nat, partialFuncLe (Xabs (fn n)) g)\n    -> CR_cv _ (fun n:nat => Integral (fnInt n)) (Integral fInt).\nProof.\n  intros IS fn fnInt f g fInt cvfn gInt fnle.\n  assert (CvMeasure (fun n : nat => Xabs (Xminus (fn n) f))\n                    (Xconst (X (ElemFunc IS)) 0))\n    as cvZero.\n  { intros A Aint eps epsPos. specialize (cvfn A Aint eps epsPos) as [N Nmaj].\n    exists N. intros. specialize (Nmaj n H) as [B Bapprox].\n    exists B. intros. destruct xdfn. specialize (Bapprox x d0 d H0). \n    refine (CRle_lt_trans _ _ _ _ Bapprox).\n    simpl. rewrite (CRabs_minus_sym (partialApply f x d0)).\n    unfold CRminus. rewrite CRplus_0_l, CRabs_opp.\n    rewrite CRabs_right. 2: apply CRabs_pos.\n    rewrite <- CRopp_mult_distr_l, CRmult_1_l. apply CRle_refl. }\n  assert (forall n : nat, nonNegFunc (Xabs (Xminus (fn n) f))).\n  { intros n x xdf. apply CRabs_pos. }\n  assert (forall (eps : CRcarrier (RealT (ElemFunc IS))) (p : positive),\n             0 < eps -> 0 < eps * CR_of_Q _ (1#p)) as deltaPos.\n  { intros. apply (CRmult_lt_0_compat _ _ _ H0).\n    apply CR_of_Q_pos. reflexivity. }\n  assert (forall eps : CRcarrier (RealT (ElemFunc IS)),\n       0 < eps ->\n       IntegralDominated\n         (fun n : nat => Xabs (Xminus (fn n) f))\n         (fun n : nat => IntegrableAbs (IntegrableMinus (fnInt n) fInt)) eps)\n    as domin.\n  { intros eps epsPos.\n    destruct (IntegralSupportExists\n                _ (IntegrablePlus _ _ gInt (IntegrableAbs fInt))\n                _ (deltaPos eps 2%positive epsPos))\n      as [t [_ [tsupp tdist]]].\n    remember (fun x : X (ElemFunc IS) =>\n           exists xD : Domain (Xabs (Xplus g (Xabs f))) x,\n             t <= partialApply (Xabs (Xplus g (Xabs f))) x xD) as A.\n    destruct (Un_cv_nat_real\n                _ _ (IntegralTruncateLimit _ (IntegrablePlus _ _ gInt (IntegrableAbs fInt)))\n                _ (deltaPos eps 4%positive epsPos)) as [n nmaj].\n    apply (Build_IntegralDominated\n             IS _ _ _ _\n             O _ (deltaPos eps (4 * Pos.of_nat (S n))%positive epsPos) tsupp).\n    intros B Bmes i _ H0.\n    apply (CRle_lt_trans\n             _ (Integral\n                  (RestrictedIntegrable (IntegrableAbs (IntegrableMinus (fnInt i) fInt)) (MeasurableIntersectIntegrable Bmes tsupp))\n                + Integral\n                    (RestrictedMeasurable (IntegrableAbs (IntegrableMinus (fnInt i) fInt)) (MeasurableSetCompl _ (IntegrableMeasurable _ tsupp))))). \n    - rewrite <- IntegralPlus; apply IntegralNonDecreasing.\n      intros x xdf xdg. simpl. destruct xdf, xdg, d0, d1, d2, d4, d5.\n      rewrite (DomainProp f x d7 d3); clear d7.\n      rewrite (DomainProp f x d6 d3); clear d6.\n      rewrite (DomainProp _ x d5 d0); clear d5.\n      rewrite (DomainProp _ x d4 d0); clear d4.\n      rewrite <- CRmult_plus_distr_r. apply CRmult_le_compat_r.\n      apply CRabs_pos.\n      destruct d. destruct d1. destruct d2.\n      destruct a; contradiction. rewrite CRplus_0_r. apply CRle_refl.\n      rewrite CRplus_0_l. destruct d2. apply CRle_refl.\n      contradict n1. intro abs. contradict n0. split; assumption.\n      destruct d1. destruct d2.\n      destruct a; contradiction. rewrite CRplus_0_r. apply CRlt_asym, CRzero_lt_one.\n      rewrite CRplus_0_l. destruct d2. apply CRlt_asym, CRzero_lt_one.\n      apply CRle_refl.\n    - apply (CRle_lt_trans\n             _ (Integral\n                  (RestrictedIntegrable\n                     (IntegrablePlus _ _ gInt (IntegrableAbs fInt))\n                     (MeasurableIntersectIntegrable Bmes tsupp))\n                + Integral\n                    (RestrictedMeasurable\n                       (IntegrablePlus _ _ gInt (IntegrableAbs fInt))\n                       (MeasurableSetCompl _ (IntegrableMeasurable _ tsupp))))).\n      apply CRplus_le_compat.\n      + apply IntegralNonDecreasing. intros x xdf xdg.\n        destruct xdf, xdg. rewrite applyXmult, applyXmult.\n        rewrite (DomainProp _ x d1 d). apply CRmult_le_compat_l.\n        simpl. destruct d. apply CRlt_asym, CRzero_lt_one. apply CRle_refl.\n        simpl. destruct d2, d0.\n        apply (CRle_trans _ _ _ (CRabs_triang _ _)). apply CRplus_le_compat.\n        apply fnle. rewrite <- CRopp_mult_distr_l, CRmult_1_l, CRabs_opp.\n        rewrite (DomainProp f x d4 d3). apply CRle_refl.\n      + apply IntegralNonDecreasing. intros x xdf xdg.\n        destruct xdf, xdg. rewrite applyXmult, applyXmult.\n        rewrite (DomainProp _ x d1 d). apply CRmult_le_compat_l.\n        simpl. destruct d. apply CRlt_asym, CRzero_lt_one. apply CRle_refl.\n        simpl. destruct d0, d2. rewrite <- CRopp_mult_distr_l, CRmult_1_l.\n        apply (CRle_trans _ _ _ (CRabs_triang _ _)).\n        apply CRplus_le_compat. apply fnle.\n        rewrite CRabs_opp, (DomainProp f x d4 d3). apply CRle_refl.\n      + apply (CRlt_le_trans _ (eps * CR_of_Q (RealT (ElemFunc IS)) (1 # 2)\n                                + eps * CR_of_Q (RealT (ElemFunc IS)) (1 # 2))).\n        apply CRplus_le_lt_compat. specialize (nmaj (S n) (le_S _ _ (le_refl n))).\n        apply CRlt_asym in nmaj. rewrite CRabs_minus_sym, CRabs_right in nmaj.\n        apply (CRplus_le_reg_r\n                 (- (MeasureSet (MeasurableIntersectIntegrable Bmes tsupp)\n                     * CR_of_Q _ (Z.of_nat (S n) #1)))).\n        apply (CRle_trans _ (eps * CR_of_Q (RealT (ElemFunc IS)) (1 # 4))).\n        apply (CRle_trans _ (Integral (RestrictedIntegrable (IntegrablePlus g (Xabs f) gInt (IntegrableAbs fInt)) (MeasurableIntersectIntegrable Bmes tsupp))\n                             - Integral (RestrictedIntegrable\n           (IntegrableMinInt (Xplus g (Xabs f)) (S n)\n              (IntegrablePlus g (Xabs f) gInt (IntegrableAbs fInt))) (MeasurableIntersectIntegrable Bmes tsupp)))).\n        apply CRplus_le_compat_l. apply CRopp_ge_le_contravar. \n        unfold MeasureSet.\n        rewrite <- IntegralScale. apply IntegralNonDecreasing.\n        intros x xdf xdg. simpl. destruct xdf, d0.\n        destruct d. rewrite CRmult_1_l. destruct xdg.\n        rewrite CRmult_1_r. apply CRmin_r. contradiction.\n        rewrite CRmult_0_l. destruct xdg.\n        rewrite CRmult_1_r. apply CR_of_Q_le.\n        destruct n; discriminate. rewrite CRmult_0_r. apply CRle_refl.\n        refine (CRle_trans _ _ _ _ nmaj).\n        rewrite <- IntegralMinus, <- IntegralMinus. apply IntegralNonDecreasing.\n        intros x xdf xdg. simpl.\n        destruct xdf, d, d1, d0, d3, xdg, d5, d6.\n        rewrite (DomainProp g x d3 d1), (DomainProp g x d6 d1),\n        (DomainProp g x d5 d1), (DomainProp f x d8 d2), (DomainProp f x d7 d2),\n        (DomainProp f x d4 d2).\n        destruct d. destruct d0. 2: contradiction.\n        rewrite CRmult_1_l, CRmult_1_l. apply CRle_refl.\n        rewrite CRmult_0_l. destruct d0. contradiction.\n        rewrite CRmult_0_l. rewrite CRmult_0_r, CRplus_0_l.\n        rewrite <- CRopp_mult_distr_l, CRmult_1_l.\n        rewrite <- (CRplus_opp_r (CRmin (partialApply g x d1 + CRabs (RealT (ElemFunc IS)) (partialApply f x d2)) (INR (S n)))).\n        apply CRplus_le_compat_r. apply CRmin_l.\n        rewrite <- CRplus_0_r.\n        setoid_replace (eps * CR_of_Q (RealT (ElemFunc IS)) (1 # 2))\n          with (eps * CR_of_Q (RealT (ElemFunc IS)) (1 # 4)\n                + eps * CR_of_Q (RealT (ElemFunc IS)) (1 # 4)).\n        rewrite CRplus_assoc. apply CRplus_le_compat_l.\n        rewrite <- (CRplus_opp_r (MeasureSet (MeasurableIntersectIntegrable Bmes tsupp) *\n                                 CR_of_Q (RealT (ElemFunc IS)) (Z.of_nat (S n) # 1))).\n        apply CRplus_le_compat_r.\n        apply (CRmult_le_reg_r (CR_of_Q (RealT (ElemFunc IS)) (1 # Pos.of_nat (S n)))).\n        apply CR_of_Q_pos. reflexivity.\n        rewrite CRmult_assoc, <- CR_of_Q_mult.\n        setoid_replace ((Z.of_nat (S n) # 1) * (1 # Pos.of_nat (S n)))%Q with 1%Q.\n        rewrite CRmult_1_r, CRmult_assoc, <- CR_of_Q_mult.\n        setoid_replace ((1 # 4) * (1 # Pos.of_nat (S n)))%Q\n          with (1 # 4 * Pos.of_nat (S n))%Q.\n        apply CRlt_asym, H0. reflexivity.\n        unfold Qeq, Qmult, Qnum, Qden.\n        rewrite Z.mul_1_r, Z.mul_1_r, Z.mul_1_l, Pos.mul_1_l.\n        unfold Z.of_nat. rewrite Pos.of_nat_succ. reflexivity.\n        rewrite <- CRmult_plus_distr_l. apply CRmult_morph.\n        reflexivity. rewrite <- CR_of_Q_plus. apply CR_of_Q_morph.\n        reflexivity.\n        rewrite <- IntegralMinus. apply IntegralNonNeg.\n        intros x xdf. simpl. destruct xdf, d, d0.\n        rewrite <- CRopp_mult_distr_l, CRmult_1_l.\n        rewrite <- (CRplus_opp_r (CRmin (partialApply g x d0 + CRabs (RealT (ElemFunc IS)) (partialApply f x d2)) (INR (S n)))).\n        apply CRplus_le_compat_r.\n        rewrite (DomainProp g x d0 d), (DomainProp f x d2 d1). apply CRmin_l.\n        refine (CRle_lt_trans _ _ _ _ tdist).\n        apply IntegralNonDecreasing. intros x xdf xdg.\n        simpl. destruct xdf, xdg, d0, d1, d2, d5. \n        destruct d. 2: rewrite CRmult_0_l; apply CRabs_pos.\n        rewrite CRmult_1_l. destruct d2. contradiction.\n        rewrite CRmult_0_l, CRmult_0_r, CRplus_0_r.\n        rewrite (DomainProp g x d1 d0), (DomainProp f x d4 d3).\n        apply CRle_abs. rewrite <- CRmult_plus_distr_l, <- CR_of_Q_plus.\n        setoid_replace ((1 # 2) + (1 # 2))%Q with 1%Q.\n        rewrite CRmult_1_r. apply CRle_refl. reflexivity. }\n  intro p.\n  destruct (DominatedMeasureCvZero\n              (fun n : nat => Xabs (Xminus (fn n) f))\n              (fun n => IntegrableAbs (IntegrableMinus (fnInt n) fInt))\n              cvZero H domin p) as [n nmaj].\n  exists n. intros. specialize (nmaj i H0).\n  unfold CRminus in nmaj. rewrite CRopp_0, CRplus_0_r, CRabs_right in nmaj.\n  refine (CRle_trans _ _ _ _ nmaj). clear nmaj.\n  refine (CRle_trans _ _ _ _ (IntegralTriangle _ _)). \n  rewrite (CRabs_morph _ (Integral (IntegrableMinus (fnInt i) fInt))).\n  apply CRle_refl. rewrite <- IntegralMinus. reflexivity. \n  apply IntegralNonNeg. intros x xdf. apply CRabs_pos.\nQed.\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/stdlib/CMTMeasurableFunctions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.29352113884765646}}
{"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 A B C Aprime Bprime Cprime O X Y L M N : Universe, ((wd_ B O /\\ (wd_ A O /\\ (wd_ C O /\\ (wd_ Bprime O /\\ (wd_ Aprime O /\\ (wd_ Cprime O /\\ (wd_ X Y /\\ (wd_ A L /\\ (wd_ A M /\\ (wd_ L Aprime /\\ (wd_ A N /\\ (wd_ Bprime Cprime /\\ (wd_ Cprime L /\\ (wd_ L M /\\ (wd_ Bprime N /\\ (wd_ Aprime A /\\ (wd_ A B /\\ (wd_ Aprime B /\\ (wd_ Bprime A /\\ (wd_ Bprime B /\\ (wd_ Aprime Cprime /\\ (wd_ Aprime Bprime /\\ (wd_ A Cprime /\\ (wd_ B C /\\ (wd_ A C /\\ (wd_ Aprime C /\\ (wd_ L O /\\ (wd_ L Bprime /\\ (wd_ C Cprime /\\ (wd_ N O /\\ (wd_ N M /\\ (col_ O A Aprime /\\ (col_ O B Bprime /\\ (col_ O C Cprime /\\ (col_ A X Y /\\ (col_ L X Y /\\ (col_ L Aprime Cprime /\\ (col_ M X Y /\\ (col_ M O C /\\ (col_ N A B /\\ (col_ N L Bprime /\\ (col_ Cprime N Bprime /\\ col_ Bprime Cprime L)))))))))))))))))))))))))))))))))))))))))) -> col_ Aprime Bprime Cprime)).\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_1084.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.29350953254908435}}
{"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 Core.\n\n\n(*TODO: should this be split differently? Model_ok for core should be in Core.v*)\nSection WithVar.\n  Context (V : Type)\n          {V_Eqb : Eqb V}\n          {V_Eqb_ok : Eqb_ok V_Eqb}\n          {V_default : WithDefault V}.\n\n\n  Section WithLang.\n    Context (l : lang V)\n            (wfl : wf_lang l).\n    Notation core_model := (core_model l). \n\n    (*TODO: reorder fields on Model_ok to match core Inductives? *)\n    Instance core_model_ok : Model_ok core_model :=\n      {\n        term_substable_ok := substable_term_ok (V:=V);\n        sort_substable_ok := substable_sort_ok (V:=V);\n        eq_sort_subst := ltac:(intros; eapply eq_sort_subst with (l:=l); eassumption);\n        eq_sort_refl := eq_sort_refl (l:=l);\n        eq_sort_trans := eq_sort_trans (l:=l);\n        eq_sort_sym := eq_sort_sym (l:=l);\n        eq_term_subst := ltac:(intros; eapply eq_term_subst with (l:=l); eassumption);\n        eq_term_refl := eq_term_refl (l:=l);\n        eq_term_trans := eq_term_trans (l:=l);\n        eq_term_sym := eq_term_sym (l:=l);\n        eq_term_conv := ltac:(intros; eapply eq_term_conv with (l:=l); eassumption);\n        wf_term_conv := wf_term_conv (l:=l);\n        wf_term_var := wf_term_var l;\n        wf_sort_subst_monotonicity := wf_sort_subst_monotonicity wfl;\n        wf_term_subst_monotonicity := wf_term_subst_monotonicity wfl;\n        wf_sort_implies_ws := wf_sort_implies_ws ltac:(eauto with lang_core);\n        wf_term_implies_ws := wf_term_implies_ws ltac:(eauto with lang_core);\n      }.\n\n  End WithLang.\n  \n  (*TODO: implement (is this defined in multicompilers.v?*)\n  Axiom Eqb_list :forall {A}, Eqb A -> Eqb (list A).\n  Existing Instance Eqb_list.\n\n  Section Multicompilers.\n    Context (l : lang (list V))\n            (wfl : wf_lang l).\n\n    Context (fn_names : list V).\n\n    \n    Notation named_list := (@named_list (list V)).\n    Notation named_map := (@named_map (list V)).\n    Notation term := (@term (list V)).\n    Notation var := (@var (list V)).\n    Notation con := (@con (list V)).\n    Notation ctx := (@ctx (list V)).\n    Notation sort := (@sort (list V)).\n    Notation subst := (@subst (list V)).\n    Notation rule := (@rule (list V)).\n    Notation lang := (@lang (list V)).\n\n    Notation Model := (@Model (list V) (list term) (list sort)).\n\n\n    Let arity := length fn_names.\n\n    Definition flatten_ctx : named_list (list sort) -> ctx :=\n      flat_map (fun '(n,t) =>\n                  map (fun '(fn, t) =>(fn::n,t)) (combine fn_names t)).\n\n    (*TODO: double check this*)\n    Fixpoint split_subst (s : named_list (list term)) : list (named_list term) :=\n      match s with\n      | [] => repeat [] arity\n      | (n,e)::s =>\n          map (fun '(e,s) => (n,e)::s) (combine e (split_subst s))\n      end.\n\n    Definition expand_args : list (list V) -> list (list V) :=\n      flat_map (fun n =>\n                  map (fun fn =>fn::n) fn_names).\n    \n    Instance list_term_subst : Substable0 (list V) (list term) :=\n      {\n        inj_var x := map (fun n => var (n::x)) fn_names;\n        apply_subst0 s e := map (fun '(e,s) => e[/s/]) (combine e (split_subst s));\n        well_scoped0 args e :=\n        length e = arity /\\\n          all (well_scoped (expand_args args))  e\n      }.\n\n    (* TODO\n    Instance list_term_subst_ok : Substable0_ok (list term).\n    Proof.\n      constructor.\n      all: basic_goal_prep; basic_core_crush.\n      {\n        unfold Substable.subst_lookup.\n        induction s;\n          basic_goal_prep; basic_term_crush.\n        {\n          subst arity.\n          induction fn_names; \n            basic_goal_prep; basic_term_crush.\n        }\n        {\n          case_match;\n          basic_utils_crush.\n        }\n        simpl.\n          \n      }\n      {\n        inj_var x := map (fun n => var (n::x)) fn_names;\n        apply_subst0 s e := map (fun '(e,s) => e[/s/]) (combine e (split_subst s));\n        well_scoped0 args e :=\n        length e = arity /\\\n          all (well_scoped (expand_args args))  e\n      }.\n    \n    Instance list_sort_subst : Substable (list term) (list sort) :=\n      {\n        apply_subst s t := map (fun '(t,s) => t[/s/]) (combine t (split_subst s));\n        well_scoped args t :=\n        length t = arity /\\\n          all (well_scoped (expand_args args))  t\n      }.\n\n    (* TODO: move to Utils.v\n       TODO: use this or all3?\n     *)\n    Inductive Forall3 (A B C : Type) (R : A -> B -> C -> Prop)\n      : list A -> list B -> list C -> Prop :=\n    | Forall3_nil : Forall3 R [] [] []\n    | Forall3_cons : forall (x : A) (y : B) (z : C)\n                            (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     Instance multi_model : Model :=\n      {\n        term_substable := list_term_subst;\n        sort_substable := list_sort_subst;\n        eq_sort c t1 t2 :=\n        (length t1 = arity) /\\\n          (length t2 = arity) /\\\n          (Forall2 (eq_sort l (flatten_ctx c)) t1 t2);\n        eq_term c t e1 e2 :=\n        (length t = arity) /\\\n          (length e1 = arity) /\\\n          (length e2 = arity) /\\\n          (Forall3 (eq_term l (flatten_ctx c)) t e1 e2);\n        wf_sort c t :=\n        (length t = arity) /\\\n          (Forall (wf_sort l (flatten_ctx c)) t);\n        wf_term c e t :=\n        (length e = arity) /\\\n        (length t = arity) /\\\n          (Forall2 (wf_term l (flatten_ctx c)) e t);\n      }.\n    \n\n    Instance multi_model_ok : Model_ok multi_model.\n    constructor.\n    - \n    try typeclasses eauto.\n\n    Qed.\n      :=\n      {\n        term_substable_ok := substable_term_ok (V:=V);\n        sort_substable_ok := substable_sort_ok (V:=V);\n        eq_sort_subst := eq_sort_subst (l:=l);\n        eq_sort_refl := eq_sort_refl (l:=l);\n        eq_sort_trans := eq_sort_trans (l:=l);\n        eq_sort_sym := eq_sort_sym (l:=l);\n        eq_term_subst := eq_term_subst (l:=l);\n        eq_term_refl := eq_term_refl (l:=l);\n        eq_term_trans := eq_term_trans (l:=l);\n        eq_term_sym := eq_term_sym (l:=l);\n        eq_term_conv := eq_term_conv (l:=l);\n        wf_term_conv := wf_term_conv (l:=l);\n        wf_term_var := wf_term_var l;\n        wf_sort_subst_monotonicity := wf_sort_subst_monotonicity wfl;\n        wf_term_subst_monotonicity := wf_term_subst_monotonicity wfl;\n        wf_sort_implies_ws := wf_sort_implies_ws ltac:(eauto with lang_core);\n        wf_term_implies_ws := wf_term_implies_ws ltac:(eauto with lang_core);\n      }.\n     *)\n\n    End Multicompilers.\n    \n  End WithVar.\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/Theory/ModelImpls.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.29334444885962874}}
{"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 TableAux.Spec.\n\nLocal Open Scope Z_scope.\n\nSection SpecLow.\n\n  Fixpoint table_walk_lock_unlock_loop0 (n: nat) (l: Z) (tbl: Pointer) (last_tbl: Pointer) (map_addr: Z) (adt: RData) :=\n    match n with\n    | O => Some (l, tbl, last_tbl, adt)\n    | S n' =>\n      match table_walk_lock_unlock_loop0 n' l tbl last_tbl map_addr adt with\n      | Some (l, tbl, last_tbl, adt) =>\n        rely is_int l;\n        when null == is_null_spec tbl adt;\n        rely is_int null;\n        if null =? 0 then\n          when' idx == addr_to_idx_spec (VZ64 map_addr) (VZ64 l) adt;\n          rely is_int64 idx;\n          when tbl, adt == find_next_level_idx_spec tbl (VZ64 idx) adt;\n          when null == is_null_spec tbl adt;\n          rely is_int null;\n          if null =? 0 then\n            when adt == granule_lock_spec tbl adt;\n            when adt == granule_unlock_spec last_tbl adt;\n            Some (l + 1, tbl, tbl, adt)\n          else\n            when adt == granule_unlock_spec last_tbl adt;\n            Some (l + 1, tbl, last_tbl, adt)\n        else Some (l + 1, tbl, last_tbl, adt)\n      | _ => None\n      end\n    end.\n\n  Definition table_walk_lock_unlock_spec0 (g_rd: Pointer) (map_addr: Z64) (level: Z64) (adt: RData) : option RData :=\n    match map_addr, level with\n    | VZ64 map_addr, VZ64 level =>\n      when rd, adt == granule_map_spec g_rd SLOT_RD adt;\n      when g_root == get_rd_g_rtt_spec rd adt;\n      when adt == buffer_unmap_spec rd adt;\n      when adt == granule_lock_spec g_root adt;\n      match table_walk_lock_unlock_loop0 (Z.to_nat level) 0 g_root g_root map_addr adt with\n      | Some (l, tbl, last_tb, adt) =>\n        rely is_int l;\n        when adt == set_wi_g_llt_spec tbl adt;\n        when' idx == addr_to_idx_spec (VZ64 map_addr) (VZ64 level) adt;\n        rely is_int64 idx;\n        when adt == set_wi_index_spec (VZ64 idx) adt;\n        Some adt\n      | _ => None\n      end\n    end.\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/TableWalk/LowSpecs/table_walk_lock_unlock.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.4339814648038986, "lm_q1q2_score": 0.2932693114128684}}
{"text": "From isla Require Import opsem.\n\nDefinition a7408 : isla_trace :=\n  Smt (DeclareConst 49%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"R0\" [] (RegVal_Base (Val_Symbolic 49%Z)) Mk_annot :t:\n  Smt (DefineConst 50%Z (Val (Val_Symbolic 49%Z) Mk_annot)) Mk_annot :t:\n  Smt (DefineConst 73%Z (Manyop (Bvmanyarith Bvor) [Val (Val_Bits (BV 64%N 0x0%Z)) Mk_annot; Manyop (Bvmanyarith Bvand) [Manyop (Bvmanyarith Bvor) [Val (Val_Bits (BV 64%N 0x0%Z)) Mk_annot; Manyop (Bvmanyarith Bvand) [Manyop (Bvmanyarith Bvor) [Binop ((Bvarith Bvlshr)) (Val (Val_Symbolic 50%Z) Mk_annot) (Val (Val_Bits (BV 64%N 0x1a%Z)) Mk_annot) Mk_annot; Binop ((Bvarith Bvshl)) (Val (Val_Symbolic 50%Z) Mk_annot) (Val (Val_Bits (BV 64%N 0x26%Z)) Mk_annot) Mk_annot] Mk_annot; Val (Val_Bits (BV 64%N 0xffffffffffffffff%Z)) Mk_annot] Mk_annot] Mk_annot; Val (Val_Bits (BV 64%N 0x3fffffffff%Z)) Mk_annot] Mk_annot] Mk_annot)) Mk_annot :t:\n  WriteReg \"R0\" [] (RegVal_Base (Val_Symbolic 73%Z)) Mk_annot :t:\n  Smt (DeclareConst 74%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"_PC\" [] (RegVal_Base (Val_Symbolic 74%Z)) Mk_annot :t:\n  Smt (DefineConst 75%Z (Manyop (Bvmanyarith Bvadd) [Val (Val_Symbolic 74%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 75%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/a7408.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2932693114128683}}
{"text": "From iris_logrel.F_mu_ref_conc Require Export lang.\n\nInductive type :=\n  | TUnit : type\n  | TNat : type\n  | TBool : 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  | TForall (τ : {bind 1 of type})\n  | Tref (τ : type).\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\nFixpoint binop_res_type (op : binop) : type :=\n  match op with\n  | Add => TNat | Sub => TNat\n  | Eq => TBool | Le => TBool | Lt => TBool\n  end.\n\nInductive EqType : type → Prop :=\n  | EqTUnit : EqType TUnit\n  | EqTNat : EqType TNat\n  | EqTBool : EqType TBool\n  | EqTProd τ τ' : EqType τ → EqType τ' → EqType (TProd τ τ')\n  | EqSum τ τ' : EqType τ → EqType τ' → EqType (TSum τ τ').\n\nReserved Notation \"Γ ⊢ₜ e : τ\" (at level 74, e, τ at next level).\n\nInductive typed (Γ : list type) : expr → type → Prop :=\n  | Var_typed x τ : Γ !! x = Some τ → Γ ⊢ₜ Var x : τ\n  | Unit_typed : Γ ⊢ₜ Unit : TUnit\n  | Nat_typed n : Γ ⊢ₜ #n n : TNat\n  | Bool_typed b : Γ ⊢ₜ #♭ b : TBool\n  | BinOp_typed op e1 e2 :\n     Γ ⊢ₜ e1 : TNat → Γ ⊢ₜ e2 : TNat → Γ ⊢ₜ BinOp op e1 e2 : binop_res_type op\n  | Pair_typed e1 e2 τ1 τ2 : Γ ⊢ₜ 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 τ3 :\n     Γ ⊢ₜ e0 : TSum τ1 τ2 → τ1 :: Γ ⊢ₜ e1 : τ3 → τ2 :: Γ ⊢ₜ e2 : τ3 →\n     Γ ⊢ₜ Case e0 e1 e2 : τ3\n  | If_typed e0 e1 e2 τ :\n     Γ ⊢ₜ e0 : TBool → Γ ⊢ₜ e1 : τ → Γ ⊢ₜ e2 : τ → Γ ⊢ₜ If e0 e1 e2 : τ\n  | Rec_typed e τ1 τ2 :\n     TArrow τ1 τ2 :: τ1 :: Γ ⊢ₜ e : τ2 → Γ ⊢ₜ Rec e : TArrow τ1 τ2\n  | App_typed e1 e2 τ1 τ2 :\n     Γ ⊢ₜ e1 : TArrow τ1 τ2 → Γ ⊢ₜ e2 : τ1 → Γ ⊢ₜ App e1 e2 : τ2\n  | TLam_typed e τ :\n     subst (ren (+1)) <$> Γ ⊢ₜ e : τ → Γ ⊢ₜ TLam e : TForall τ\n  | TApp_typed e τ τ' : Γ ⊢ₜ e : TForall τ → Γ ⊢ₜ TApp e : τ.[τ'/]\n  | TFold e τ : Γ ⊢ₜ e : τ.[TRec τ/] → Γ ⊢ₜ Fold e : TRec τ\n  | TUnfold e τ : Γ ⊢ₜ e : TRec τ → Γ ⊢ₜ Unfold e : τ.[TRec τ/]\n  | TFork e : Γ ⊢ₜ e : TUnit → Γ ⊢ₜ Fork e : TUnit\n  | TAlloc e τ : Γ ⊢ₜ e : τ → Γ ⊢ₜ Alloc e : Tref τ\n  | TLoad e τ : Γ ⊢ₜ e : Tref τ → Γ ⊢ₜ Load e : τ\n  | TStore e e' τ : Γ ⊢ₜ e : Tref τ → Γ ⊢ₜ e' : τ → Γ ⊢ₜ Store e e' : TUnit\n  | TCAS e1 e2 e3 τ :\n     EqType τ → Γ ⊢ₜ e1 : Tref τ → Γ ⊢ₜ e2 : τ → Γ ⊢ₜ e3 : τ →\n     Γ ⊢ₜ CAS e1 e2 e3 : TBool\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 (∀ x Γ, x < length (subst (ren (+1)) <$> Γ) → x < length Γ).\n  { intros ??. by rewrite fmap_length. } \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 omega. }\n  induction Htyped => s1 s2 Hs; f_equal/=; eauto using lookup_lt_Some with omega.\nQed.\nLemma n_closed_invariant n (e : expr) s1 s2 :\n  (∀ f, e.[upn n f] = e) → (∀ x, x < n → s1 x = s2 x) → e.[s1] = e.[s2].\nProof.\n  intros Hnc. specialize (Hnc (ren (+1))).\n  revert n Hnc s1 s2.\n  induction e => m Hmc s1 s2 H1; asimpl in *; try f_equal;\n    try (match goal with H : _ |- _ => eapply H end; eauto;\n         try inversion Hmc; try match goal with H : _ |- _ => by rewrite H end;\n         fail).\n  - apply H1. rewrite iter_up in Hmc. destruct lt_dec; try omega.\n    asimpl in *. cbv in x. replace (m + (x - m)) with x in Hmc by omega.\n    inversion Hmc; omega.\n  - unfold upn in *.\n    change (e.[up (up (upn m (ren (+1))))]) with\n    (e.[iter (S (S m)) up (ren (+1))]) in *.\n    apply (IHe (S (S m))).\n    + inversion Hmc; match goal with H : _ |- _ => (by rewrite H) end.\n    + intros [|[|x]] H2; [by cbv|by cbv |].\n      asimpl; rewrite H1; auto with omega.\n  - change (e1.[up (upn m (ren (+1)))]) with\n    (e1.[iter (S m) up (ren (+1))]) in *.\n    apply (IHe0 (S m)).\n    + inversion Hmc; match goal with H : _ |- _ => (by rewrite H) end.\n    + intros [|x] H2; [by cbv |].\n      asimpl; rewrite H1; auto with omega.\n  - change (e2.[up (upn m (ren (+1)))]) with\n    (e2.[upn (S m) (ren (+1))]) in *.\n    apply (IHe1 (S m)).\n    + inversion Hmc; match goal with H : _ |- _ => (by rewrite H) end.\n    + intros [|x] H2; [by cbv |].\n      asimpl; rewrite H1; auto with omega.\nQed.\n\nDefinition env_subst (vs : list val) (x : var) : expr :=\n  from_option id (Var x) (of_val <$> vs !! x).\n\nLemma typed_n_closed Γ τ e : Γ ⊢ₜ e : τ → (∀ f, e.[upn (length Γ) f] = e).\nProof.\n  intros H. induction H => f; asimpl; simpl in *; auto with f_equal.\n  - apply lookup_lt_Some in H. rewrite iter_up. destruct lt_dec; auto with omega.\n  - f_equal. apply IHtyped.\n  - by f_equal; rewrite map_length in IHtyped.\nQed.\n\nLemma n_closed_subst_head_simpl n e w ws :\n  (∀ f, e.[upn n f] = e) →\n  S (length ws) = n →\n  e.[of_val w .: env_subst ws] = e.[env_subst (w :: ws)].\nProof.\n  intros H1 H2.\n  rewrite /env_subst. eapply n_closed_invariant; eauto=> /= -[|x] ? //=.\n  destruct (lookup_lt_is_Some_2 ws x) as [v' Hv]; first omega; simpl.\n  by rewrite Hv.\nQed.\n\nLemma typed_subst_head_simpl Δ τ e w ws :\n  Δ ⊢ₜ e : τ → length Δ = S (length ws) →\n  e.[of_val w .: env_subst ws] = e.[env_subst (w :: ws)].\nProof. eauto using n_closed_subst_head_simpl, typed_n_closed. Qed.\n\nLemma n_closed_subst_head_simpl_2 n e w w' ws :\n  (∀ f, e.[upn n f] = e) → (S (S (length ws))) = n →\n  e.[of_val w .: of_val w' .: env_subst ws] = e.[env_subst (w :: w' :: ws)].\nProof.\n  intros H1 H2.\n  rewrite /env_subst. eapply n_closed_invariant; eauto => /= -[|[|x]] H3 //=.\n  destruct (lookup_lt_is_Some_2 ws x) as [v' Hv]; first omega; simpl.\n  by rewrite Hv.\nQed.\n\nLemma typed_subst_head_simpl_2 Δ τ e w w' ws :\n  Δ ⊢ₜ e : τ → length Δ = 2 + length ws →\n  e.[of_val w .: of_val w' .: env_subst ws] = e.[env_subst (w :: w' :: ws)].\nProof. eauto using n_closed_subst_head_simpl_2, typed_n_closed. Qed.\n\nLemma empty_env_subst e : e.[env_subst []] = e.\nProof. change (env_subst []) with (@ids expr _). by asimpl. Qed.\n\n(** Weakening *)\nLemma context_gen_weakening ξ Γ' Γ e τ :\n  Γ' ++ Γ ⊢ₜ e : τ →\n  Γ' ++ ξ ++ Γ ⊢ₜ e.[upn (length Γ') (ren (+ (length ξ)))] : τ.\nProof.\n  intros H1.\n  remember (Γ' ++ Γ) as Ξ. revert Γ' Γ ξ HeqΞ.\n  induction H1 => Γ1 Γ2 ξ HeqΞ; subst; asimpl in *; eauto using typed.\n  - rewrite iter_up; destruct lt_dec as [Hl | Hl].\n    + constructor. rewrite lookup_app_l; trivial. by rewrite lookup_app_l in H.\n    + asimpl. constructor. rewrite lookup_app_r; auto with omega.\n      rewrite lookup_app_r; auto with omega.\n      rewrite lookup_app_r in H; auto with omega.\n      match goal with\n        |- _ !! ?A = _ => by replace A with (x - length Γ1) by omega\n      end.\n  - econstructor; eauto. by apply (IHtyped2 (_::_)). by apply (IHtyped3 (_::_)).\n  - constructor. by apply (IHtyped (_ :: _ :: _)).\n  - constructor.\n    specialize (IHtyped\n      (subst (ren (+1)) <$> Γ1) (subst (ren (+1)) <$> Γ2) (subst (ren (+1)) <$> ξ)).\n    asimpl in *. rewrite ?map_length in IHtyped.\n    repeat rewrite fmap_app. apply IHtyped.\n    by repeat rewrite fmap_app.\nQed.\n\nLemma context_weakening ξ Γ e τ :\n  Γ ⊢ₜ e : τ → ξ ++ Γ ⊢ₜ e.[(ren (+ (length ξ)))] : τ.\nProof. eapply (context_gen_weakening _ []). Qed.\n\nLemma closed_context_weakening ξ Γ e τ :\n  (∀ f, e.[f] = e) → Γ ⊢ₜ e : τ → ξ ++ Γ ⊢ₜ e : τ.\nProof. intros H1 H2. erewrite <- H1. by eapply context_weakening. Qed.\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/typing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2932589980076071}}
{"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.\n\n(******************************************************************************)\n(* Reducibility of configurations number 1 to 106, whose indices in           *)\n(* the_configs range over segment [0, 106).                                   *)\n(******************************************************************************)\n\nLemma red000to106 : reducible_in_range 0 106 the_configs.\nProof. CheckReducible. Qed.\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/job001to106.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.2932589980076071}}
{"text": "From Tealeaves.Classes Require Import\n  Monad\n  Applicative.\n  \n(** * Monadic applicative functors *)\n(******************************************************************************)\nSection Applicative_Monad.\n\n  #[local] Generalizable Variable T.\n  \n  Import Applicative.Notations.\n  \n  Context\n    `{Classes.Monad.Monad T}.\n  \n  Import Monad.ToKleisli.Operation.\n  Import Monad.ToKleisli.Instance.\n\n  #[global] Instance Pure_Monad : Pure T := @ret T _.\n\n  #[global] Instance Mult_Monad : Mult T :=\n    fun A B (p : T A * T B) =>\n      match p with (ta, tb) =>\n                   bind T (fun a => strength T (a, tb)) ta\n      end.\n\n  Theorem app_pure_natural_Monad : forall (A B : Type) (f : A -> B) (x : A),\n      fmap T f (pure T x) = pure T (f x).\n  Proof.\n    intros. unfold_ops @Pure_Monad.\n    compose near x. now rewrite (natural (ϕ := @ret T _)).\n  Qed.\n\n  Theorem app_mult_natural_Monad : forall (A B C D : Type) (f : A -> C) (g : B -> D) (x : T A) (y : T B),\n      fmap T f x ⊗ fmap T g y = fmap T (map_tensor f g) (x ⊗ y).\n  Proof.\n    intros. unfold_ops @Mult_Monad.\n    compose near x.\n    rewrite (bind_fmap T), (fmap_bind T).\n    fequal. ext c; unfold compose; cbn. compose near y.\n    now rewrite 2(fun_fmap_fmap T).\n  Qed.\n\n  Theorem app_assoc_Monad : forall (A B C : Type) (x : T A) (y : T B) (z : T C),\n      fmap T α ((x ⊗ y) ⊗ z) = x ⊗ (y ⊗ z).\n  Proof.\n    intros. unfold_ops @Mult_Monad.\n    compose near x on left. rewrite (kmon_bind2 T).\n    compose near x on left. rewrite (fmap_bind T).\n    fequal. ext a; unfold compose; cbn.\n    compose near y on right. rewrite (fmap_bind T).\n    unfold compose; cbn. compose near z on right.\n    unfold kcompose. unfold compose; cbn.\n    compose near y on left.\n    rewrite (bind_fmap T). compose near y on left.\n    rewrite (fmap_bind T). fequal. ext b. unfold compose; cbn.\n    compose near z. now do 2 (rewrite (fun_fmap_fmap T)).\n  Qed.\n\n  Theorem app_unital_l_Monad : forall (A : Type) (x : T A),\n      fmap T left_unitor (pure T tt ⊗ x) = x.\n  Proof.\n    intros. unfold_ops @Mult_Monad @Pure_Monad.\n    compose near tt. rewrite (mon_bind_comp_ret T).\n    unfold strength. compose near x.\n    rewrite (fun_fmap_fmap T). change (left_unitor ∘ pair tt) with (@id A).\n    now rewrite (fun_fmap_id T).\n  Qed.\n\n  Theorem app_unital_r_Monad : forall (A : Type) (x : T A),\n      fmap T right_unitor (x ⊗ pure T tt) = x.\n  Proof.\n    intros. unfold_ops @Mult_Monad @Pure_Monad.\n    compose near x. rewrite (fmap_bind T).\n    replace (fmap T right_unitor ∘ (fun a : A => strength T (a, ret T tt)))\n      with (ret T (A := A)).\n    now rewrite (mon_bind_id T).\n    ext a; unfold compose; cbn. compose near (ret T tt).\n    rewrite (fun_fmap_fmap T). compose near tt.\n    rewrite (natural (ϕ := @ret T _ )). now unfold compose; cbn.\n  Qed.\n\n  Theorem app_mult_pure_Monad : forall (A B : Type) (a : A) (b : B),\n      pure T a ⊗ pure T b = pure T (a, b).\n  Proof.\n    intros. intros. unfold_ops @Mult_Monad @Pure_Monad.\n    compose near a. rewrite (mon_bind_comp_ret T).\n    now rewrite (strength_return).\n  Qed.\n\n  #[global] Instance Applicative_Monad : Applicative T :=\n  { app_mult_pure := app_mult_pure_Monad;\n    app_pure_natural := app_pure_natural_Monad;\n    app_mult_natural := app_mult_natural_Monad;\n    app_assoc := app_assoc_Monad;\n    app_unital_l := app_unital_l_Monad;\n    app_unital_r := app_unital_r_Monad;\n  }.\n\nEnd Applicative_Monad.\n", "meta": {"author": "dunnl", "repo": "tealeaves", "sha": "8dd6ba8acdd097f6e474ae2a1a9b10f5cc9ca65b", "save_path": "github-repos/coq/dunnl-tealeaves", "path": "github-repos/coq/dunnl-tealeaves/tealeaves-8dd6ba8acdd097f6e474ae2a1a9b10f5cc9ca65b/Tealeaves/Classes/Monad/ToApplicative.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.29325899062239563}}
{"text": "Set Universe Polymorphism.\nSection foo.\n  Universe i.\n  Context (foo : Type@{i}) (bar : Type@{i}).\n  Definition qux@{i} (baz : Type@{i}) := foo -> bar.\nEnd foo.\nSet Printing Universes.\nPrint qux. (* qux@{Top.42 Top.43} =\nfun foo bar _ : Type@{Top.42} => foo -> bar\n     : Type@{Top.42} -> Type@{Top.42} -> Type@{Top.42} -> Type@{Top.42}\n(* Top.42 Top.43 |=  *)\n(* This is wrong; the first two types are equal, but the last one is not *)\n\nqux is universe polymorphic\nArgument scopes are [type_scope type_scope type_scope]\n *)\nCheck qux nat nat nat : Set.\nCheck qux nat nat Set : Set. (* Error:\nThe term \"qux@{Top.50 Top.51} ?T ?T0 Set\" has type \"Type@{Top.50}\" while it is \nexpected to have type \"Set\"\n(universe inconsistency: Cannot enforce Top.50 = Set because Set < Top.50). *)\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/4519.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160666, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2931383555553517}}
{"text": "Require Import Fiat.QueryStructure.Automation.MasterPlan.\nRequire Import Fiat.Narcissus.Examples.NetworkStack.IPv4Header.\nRequire Import Fiat.Narcissus.Examples.NetworkStack.TCP_Packet.\nRequire Import Fiat.Narcissus.Formats.ByteBuffer.\n\nDefinition GuardDataSchema :=\n  Query Structure Schema [\n    relation \"connections\" has schema\n      <\"src_addr\" :: string, \"src_port\" :: nat,\n       \"dst_addr\" :: string, \"dst_port\" :: nat>\n  ] enforcing [].\n\nNotation bytes := { n: nat & ByteBuffer.t n }.\n\nDefinition bytes_of_ByteBuffer {n} (bb: ByteBuffer.t n) : bytes :=\n  existT _ n bb.\n\nDefinition GuardSig : ADTSig := ADTsignature {\n  Constructor \"Init\" : rep,\n  Method \"ProcessPacket\" : rep * bytes -> rep * bool\n}.\n\nDefinition ACCEPT := true.\nDefinition REJECT := false.\n\n(* FIXME *)\nDefinition is_conn_start (pkt: TCP_Packet) : bool := pkt.(SYN).\nDefinition is_conn_end (pkt: TCP_Packet) : bool := pkt.(FIN).\nDefinition MAX_OPEN_CONNECTIONS := 50.\n\nRequire Import Bedrock.Word.\nRequire Import Fiat.Narcissus.BinLib.Core.\n\nDefinition WrapDecoder {A B C} (f: forall n, ByteBuffer.t n -> option (A * B * C)) :=\n  fun (bs: bytes) =>\n    match f _ (projT2 bs) with\n    | Some (pkt, _, _) => Some pkt\n    | None => None\n    end.\n\nDefinition ipv4_decode :=\n  WrapDecoder (@IPv4_decoder_impl).\n\nDefinition ipv4Split {A} (k: forall (w1 w2 w3 w4: word 8), A) (addr: word 32) : A :=\n  let w1 := split2 24 8 addr in\n  let w2 := split1 8 8 (split2 16 16 addr) in\n  let w3 := split1 8 16 (split2 8 24 addr) in\n  let w4 := split1 8 24 addr in\n  k w1 w2 w3 w4.\n\nDefinition ipv4ToList :=\n  ipv4Split (fun w1 w2 w3 w4 => [w1; w2; w3; w4]).\n\nDefinition ipv4ToByteBuffer :=\n  ipv4Split (fun w1 w2 w3 w4 => ByteBuffer.of_list [w1; w2; w3; w4]: ByteBuffer.t 4).\n\nCompute (ipv4ToByteBuffer (WO~0~0~0~0~1~1~1~1~0~1~0~1~0~1~0~1~0~0~1~1~0~0~1~1~0~1~1~1~0~1~1~1)).\n\nDefinition ipv4ToString (addr: word 32) :=\n  List.fold_right\n    (fun (w: char) str => String (ascii_of_nat (wordToNat w)) str)\n    EmptyString (ipv4ToList addr).\n\nCompute (ipv4ToString (WO~0~0~0~0~1~1~1~1~0~1~0~1~0~1~0~1~0~0~1~1~0~0~1~1~0~1~1~1~0~1~1~1)).\n\nDefinition tcp_decode (hdr: IPv4_Packet) :=\n  let src := ipv4ToByteBuffer hdr.(SourceAddress) in\n  let dst := ipv4ToByteBuffer hdr.(DestAddress) in\n  let offset := 20 + 4 * List.length hdr.(IPv4Header.Options) in\n  let tcpLen := wordToNat hdr.(TotalLength) - offset in\n  fun bs =>\n    let bs' := AlignedByteBuffer.bytebuffer_of_bytebuffer_range offset tcpLen (projT2 bs) in\n    WrapDecoder (@TCP_decoder_impl src dst (natToWord 16 tcpLen)) bs'.\n\nDefinition port_to_nat (port: word 16) :=\n  wordToNat port.\n\nDefinition GuardSpec : ADT GuardSig := Eval simpl in Def ADT {\n  rep := QueryStructure GuardDataSchema,\n\n  Def Constructor0 \"Init\" : rep := empty,,\n\n  Def Method1 \"ProcessPacket\" (db : rep) (bs : bytes) : rep * bool :=\n    Ifopt ipv4_decode bs as hdr Then\n      let src_addr := ipv4ToString hdr.(SourceAddress) in\n      let dst_addr := ipv4ToString hdr.(DestAddress) in\n      Ifopt tcp_decode hdr bs as pkt Then\n        let src_port := port_to_nat (pkt.(SourcePort)) in\n        let dst_port := port_to_nat (pkt.(DestPort)) in\n        count <- Count (For (conn in db!\"connections\")\n                       Where (conn!\"src_addr\" = src_addr)\n                       Where (conn!\"dst_addr\" = dst_addr)\n                       Return ());\n        If is_conn_end pkt Then (\n          `(db, _) <- Delete conn from db!\"connections\"\n                       where (conn!\"src_addr\" = src_addr /\\\n                              conn!\"dst_addr\" = dst_addr /\\\n                              conn!\"src_port\" = src_port /\\\n                              conn!\"dst_port\" = dst_port);\n          ret (db, ACCEPT)\n        ) Else If count <? MAX_OPEN_CONNECTIONS Then (\n          If is_conn_start pkt Then (\n            `(db, _) <- Insert <\"src_addr\" :: src_addr, \"src_port\" :: src_port,\n                               \"dst_addr\" :: dst_addr, \"dst_port\" :: dst_port>\n                         into db!\"connections\"; (* FIXME *)\n            ret (db, ACCEPT)\n          ) Else\n            ret (db, ACCEPT)\n        ) Else\n          ret (db, REJECT)\n      Else\n        ret (db, REJECT)\n    Else\n      ret (db, REJECT)\n\n}%methDefParsing.\n\nNotation IndexType sch :=\n  (@ilist3 RawSchema (fun sch : RawSchema =>\n                        list (string * Attributes (rawSchemaHeading sch)))\n           (numRawQSschemaSchemas sch) (qschemaSchemas sch)).\n\n(* Definition empty_index : IndexType GuardDataSchema := *)\n(*   {| prim_fst := []; *)\n(*      prim_snd := () |}. *)\n\nDefinition slow_index : IndexType GuardDataSchema :=\n  {| prim_fst := [(\"EqualityIndex\", \"src_port\" # \"connections\" ## GuardDataSchema);\n                  (\"EqualityIndex\", \"dst_port\" # \"connections\" ## GuardDataSchema)];\n     prim_snd := () |}.\n\nDefinition fast_index : IndexType GuardDataSchema :=\n  {| prim_fst := [(\"EqualityIndex\", \"src_addr\" # \"connections\" ## GuardDataSchema);\n                  (\"EqualityIndex\", \"dst_addr\" # \"connections\" ## GuardDataSchema)];\n     prim_snd := () |}.\n\nDefinition indexes := slow_index.\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 indexes in makeIndex attrlist').\n\n\nTheorem SharpenedGuard :\n  FullySharpened GuardSpec.\n\nProof.\n  start sharpening ADT.\n\n  match goal with\n  |- context [@BuildADT (QueryStructure ?Rep) _ _ _ _ _ _] =>\n    hone representation using (@DropQSConstraints_AbsR Rep)\n  end.\n\n  - apply Constructor_DropQSConstraints.\n  - etransitivity; [ eapply refine_If_Opt_Then_Else_Bind | ].\n    etransitivity; [ eapply refine_If_Opt_Then_Else | ]; swap 1 3.\n    (* setoid_rewrite refine_If_Opt_Then_Else_Bind. *)\n    (* setoid_rewrite refine_If_Opt_Then_Else; swap 2 3. *)\n    + higher_order_reflexivity.\n    + simplify with monad laws.\n      refine pick val _; [ | reflexivity ].\n      simplify with monad laws; simpl.\n      match goal with\n      | [ H: DropQSConstraints_AbsR _ _ |- _ ] => red in H; rewrite !H\n      end;\n        higher_order_reflexivity.\n    + intro.\n      (* Why not setoid_rewrite? *)\n      etransitivity; [ eapply refine_If_Opt_Then_Else_Bind | ].\n      etransitivity; [ eapply refine_If_Opt_Then_Else | ]; swap 1 3.\n      * higher_order_reflexivity.\n      * simplify with monad laws.\n        refine pick val _; [ | reflexivity ].\n        simplify with monad laws; simpl.\n        match goal with\n        | [ H: DropQSConstraints_AbsR _ _ |- _ ] => red in H; rewrite !H\n        end;\n          higher_order_reflexivity.\n      * intro.\n        simplify with monad laws.\n\n        etransitivity.\n        -- setoid_rewrite DropQSConstraintsQuery_In. (* drop_constraints_from_query *)\n           try simplify with monad laws; cbv beta; simpl;\n             repeat match goal with\n                      H : DropQSConstraints_AbsR _ _ |- _ =>\n                      unfold DropQSConstraints_AbsR in H; rewrite H\n                    end. (*pose_string_hyps; pose_heading_hyps; *)\n           finish honing.\n        -- etransitivity; [ eapply refine_bind | ]; cycle -1.\n           ++ higher_order_reflexivity.\n           ++ higher_order_reflexivity.\n           ++ intro.\n              (* Why not setoid_rewrite? *)\n              etransitivity; [ eapply refine_If_Then_Else_Bind | ].\n              etransitivity; [ eapply refine_If_Then_Else | ]; swap 1 3.\n              ** higher_order_reflexivity.\n              ** etransitivity; [ eapply refine_If_Then_Else_Bind | ].\n                 etransitivity; [ eapply refine_If_Then_Else | ]; swap 1 3.\n                 --- higher_order_reflexivity.\n                 --- simplify with monad laws.\n                     refine pick val _; [ | reflexivity ].\n                     simplify with monad laws; simpl.\n                     match goal with\n                     | [ H: DropQSConstraints_AbsR _ _ |- _ ] => red in H; rewrite !H\n                     end;\n                       higher_order_reflexivity.\n                 --- etransitivity; [ eapply refine_If_Then_Else_Bind | ].\n                     etransitivity; [ eapply refine_If_Then_Else | ]; swap 1 3.\n                     +++ higher_order_reflexivity.\n                     +++ simplify with monad laws.\n                         refine pick val _; [ | reflexivity ].\n                         simplify with monad laws; simpl.\n                         match goal with\n                         | [ H: DropQSConstraints_AbsR _ _ |- _ ] => red in H; rewrite !H\n                         end;\n                           higher_order_reflexivity.\n                     +++ unfold Bind2; simplify with monad laws.\n                         simpl.\n\n                         Lemma refine_bind_bind_dep X X' Y Z (f : X -> Comp Y) (g : Y -> Comp Z) (k: X -> X') x\n                           : refine (Bind x (fun x0 => Bind (f x0) (fun u => g u)))\n                                    (Bind (Bind x (fun x0 => Bind (f x0) (fun u => ret (u, (k x0)))))\n                                          (fun x0u => g (fst x0u))).\n                         Proof.\n                           red; intros.\n                           computes_to_inv; subst.\n                           eauto using @BindComputes.\n                         Qed.\n\n                         Lemma refine_bind_bind_dep' X Y Z (f : X -> Comp Y) (g : Y -> X -> Comp Z) x\n                           : refine (Bind x (fun x0 => Bind (f x0) (fun u => g u x0)))\n                                    (Bind (Bind x (fun x0 => Bind (f x0) (fun u => ret (u, x0))))\n                                          (fun x0u => g (fst x0u) (snd x0u))).\n                         Proof.\n                           red; intros.\n                           computes_to_inv; subst.\n                           eauto using @BindComputes.\n                         Qed.\n\n                         rewrite refine_bind_bind_dep with (k := snd).\n                         setoid_rewrite refine_bind.\n                         *** higher_order_reflexivity.\n                         *** (* remove trivial insertion checks *)\n                           (* Pull out the relation we're inserting into and then\n                              rewrite [QSInsertSpec] *)\n                           lazymatch goal with\n                             H : DropQSConstraints_AbsR _ ?r_n\n                             |- context [(QSInsert _ ?R ?n)%QuerySpec] =>\n                             let H' := fresh in\n                             (* If we try to eapply [QSInsertSpec_UnConstr_refine] directly\n                                after we've drilled under a bind, this tactic will fail because\n                                typeclass resolution breaks down. Generalizing and applying gets\n                                around this problem for reasons unknown. *)\n                             let H' := fresh in\n                             pose (@QSInsertSpec_UnConstr_refine_opt _ r_n _ R n H) as H';\n                               cbv beta delta [tupleConstraints attrConstraints map app relName schemaHeading] iota in H';\n                               simpl in H'; fold_heading_hyps_in H'; fold_string_hyps_in H'; exact H'\n                           end.\n                         *** intro.\n                             finish honing.\n              ** unfold Bind2; simplify with monad laws.\n                 simpl.\n                 rewrite refine_bind_bind_dep with (k := snd).\n                 setoid_rewrite refine_bind.\n\n                 --- higher_order_reflexivity.\n                 --- (* drop_constraints_from_delete. *)\n                   (* Pull out the relation we're inserting into and then\n                      rewrite [QSInsertSpec] *)\n                   match goal with\n                       H : DropQSConstraints_AbsR ?r_o ?r_n\n                       |- context [QSDelete ?qs ?R ?P] =>\n                       (* If we try to eapply [QSInsertSpec_UnConstr_refine] directly\n                                  after we've drilled under a bind, this tactic will fail because\n                                  typeclass resolution breaks down. Generalizing and applying gets\n                                  around this problem for reasons unknown. *)\n                       let H' := fresh \"H'\" in\n                       pose proof (@QSDeleteSpec_UnConstr_refine_opt\n                                     _ r_n R P r_o H) as H';\n                         simpl in H'; fold_heading_hyps_in H'; fold_string_hyps_in H';\n                         apply H'\n                   end.\n                 --- intro.\n                     finish honing.\n\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\n    etransitivity; [ eapply refine_If_Opt_Then_Else_Bind | ].\n    eapply refine_If_Opt_Then_Else; swap 1 2.\n    (* setoid_rewrite refine_If_Opt_Then_Else_Bind. *)\n    (* setoid_rewrite refine_If_Opt_Then_Else; swap 2 3. *)\n    + simplify with monad laws.\n      simpl; refine pick val _; [ | eauto ].\n      simplify with monad laws; simpl.\n      higher_order_reflexivity.\n    + intro.\n      (* Why not setoid_rewrite? *)\n      etransitivity; [ eapply refine_If_Opt_Then_Else_Bind | ].\n      eapply refine_If_Opt_Then_Else; swap 1 2.\n      * simplify with monad laws.\n        simpl; refine pick val _; [ | eauto ].\n        higher_order_reflexivity.\n      * intro.\n        simplify with monad laws.\n        apply refine_bind.\n        -- implement_Query IndexUse createEarlyTerm createLastTerm\n                           IndexUse_dep createEarlyTerm_dep createLastTerm_dep.\n           simpl; repeat first [setoid_rewrite refine_bind_unit\n                               | setoid_rewrite refine_bind_bind ];\n           cbv beta; simpl.\n           finish honing.\n        -- intro.\n              (* Why not setoid_rewrite? *)\n              etransitivity; [ eapply refine_If_Then_Else_Bind | ].\n              etransitivity; [ eapply refine_If_Then_Else | ]; swap 1 2.\n              ** etransitivity; [ eapply refine_If_Then_Else_Bind | ].\n                 etransitivity; [ eapply refine_If_Then_Else | ]; swap 1 2.\n                 --- simplify with monad laws.\n                     refine pick val _; [ | eauto ].\n                     simplify with monad laws; simpl.\n                     higher_order_reflexivity.\n                 --- etransitivity; [ eapply refine_If_Then_Else_Bind | ].\n                     etransitivity; [ eapply refine_If_Then_Else | ]; swap 1 2.\n                     +++ simplify with monad laws.\n                         refine pick val _; [ | eauto ].\n                         simplify with monad laws; simpl.\n                         higher_order_reflexivity.\n                     +++ unfold Bind2; simplify with monad laws.\n                         simpl.\n                         insertion IndexUse createEarlyTerm createLastTerm IndexUse_dep createEarlyTerm_dep createLastTerm_dep.\n                     +++ higher_order_reflexivity.\n                 --- higher_order_reflexivity.\n              ** unfold Bind2; simplify with monad laws.\n                 simpl.\n                 deletion IndexUse createEarlyTerm createLastTerm IndexUse_dep createEarlyTerm_dep createLastTerm_dep.\n              ** higher_order_reflexivity.\n\n    + simpl.\n      hone representation using eq; simpl; subst.\n      * refine pick eq; simplify with monad laws; simpl.\n        finish honing.\n      * refine pick eq; simplify with monad laws; simpl.\n        etransitivity; [ eapply refine_If_Opt_Then_Else_Bind | ].\n        eapply refine_If_Opt_Then_Else; swap 1 2.\n        -- simplify with monad laws; simpl.\n           higher_order_reflexivity.\n        -- intro.\n           (* Why not setoid_rewrite? *)\n           etransitivity; [ eapply refine_If_Opt_Then_Else_Bind | ].\n           eapply refine_If_Opt_Then_Else; swap 1 2.\n           ++ simplify with monad laws; simpl.\n              higher_order_reflexivity.\n           ++ intro.\n              simplify with monad laws.\n              repeat change (true && ?x) with x.\n              apply refine_bind.\n              ** finish honing.\n              ** intro.\n                 (* Why not setoid_rewrite? *)\n                 etransitivity; [ eapply refine_If_Then_Else_Bind | ].\n                 etransitivity; [ eapply refine_If_Then_Else | ]; swap 1 3.\n                 --- higher_order_reflexivity.\n                 --- repeat rewrite ?map_length, ?app_nil_r.\n                     etransitivity; [ eapply refine_If_Then_Else_Bind | ].\n                     etransitivity; [ eapply refine_If_Then_Else | ]; swap 1 3.\n                     +++ higher_order_reflexivity.\n                     +++ simplify with monad laws; simpl.\n                         higher_order_reflexivity.\n                     +++ etransitivity; [ eapply refine_If_Then_Else_Bind | ].\n                         etransitivity; [ eapply refine_If_Then_Else | ]; swap 1 3.\n                         *** higher_order_reflexivity.\n                         *** simplify with monad laws; simpl.\n                             higher_order_reflexivity.\n                         *** simplify with monad laws; simpl.\n                             higher_order_reflexivity.\n                 --- simplify with monad laws; simpl.\n                     (* FIXME delete unused bind? *)\n                     finish honing.\n\n      *  Implement_Bags BuildEarlyBag BuildLastBag.\nDefined.\n\nDefinition GuardImpl :=\n  Eval simpl in projT1 SharpenedGuard.\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/Guard/TcpFilter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.4765796510636759, "lm_q1q2_score": 0.29313835555535167}}
{"text": "(* Contribution to the Coq Library   V6.3 (July 1999)                    *)\nRequire Import securite.\n\nLemma POinvprel1 :\n forall (l l0 : list C) (k k0 k1 k2 : K) (c c0 c1 c2 : C)\n   (d d0 d1 d2 d3 d4 d5 d6 d7 d8 d9 d10 d11 d12 d13 d14 d15 d16 d17 d18 d19\n    d20 : D),\n inv0\n   (ABSI (MBNaKab d7 d8 d9 k0) (MANbKabCaCb d4 d5 d6 k c c0)\n      (MABNaNbKeyK d d0 d1 d2 d3) l) ->\n inv1\n   (ABSI (MBNaKab d7 d8 d9 k0) (MANbKabCaCb d4 d5 d6 k c c0)\n      (MABNaNbKeyK d d0 d1 d2 d3) l) ->\n invP\n   (ABSI (MBNaKab d7 d8 d9 k0) (MANbKabCaCb d4 d5 d6 k c c0)\n      (MABNaNbKeyK d d0 d1 d2 d3) l) ->\n rel1\n   (ABSI (MBNaKab d7 d8 d9 k0) (MANbKabCaCb d4 d5 d6 k c c0)\n      (MABNaNbKeyK d d0 d1 d2 d3) l)\n   (ABSI (MBNaKab d18 d19 d20 k2) (MANbKabCaCb d15 d16 d17 k1 c1 c2)\n      (MABNaNbKeyK d10 d11 d12 d13 d14) l0) ->\n invP\n   (ABSI (MBNaKab d18 d19 d20 k2) (MANbKabCaCb d15 d16 d17 k1 c1 c2)\n      (MABNaNbKeyK d10 d11 d12 d13 d14) l0).\n\nProof.\ndo 32 intro.\nunfold invP, rel1 in |- *; intros Inv0 Inv1 know_Kab and1.\nelim and1; intros eq_l0 t1.\nclear Inv0 Inv1 and1 t1.\nrewrite eq_l0.\nunfold quad in |- *.\napply D2.\nsimpl in |- *.\nrepeat apply C2 || apply C3 || apply C4.\napply D1; assumption.\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\nQed.\n", "meta": {"author": "coq-contribs", "repo": "otway-rees", "sha": "7956542fbb559fcda240c6059919a95ae4c10590", "save_path": "github-repos/coq/coq-contribs-otway-rees", "path": "github-repos/coq/coq-contribs-otway-rees/otway-rees-7956542fbb559fcda240c6059919a95ae4c10590/invprel1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878414043816, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.29313834883000983}}
{"text": "\nFrom spec Require Import Maps.\nFrom spec Require Import Lang.\nFrom spec Require Import programs.\nFrom spec Require Import semantics.\nRequire Import List.\nRequire Import String.\nImport ListNotations.\n\n\n\n(* Initial Memory should be bottom t_empty ⊥. Jumps to other locations not in the program \nand are not bottom are not correctly handled. But it works for bottom\n*)\n(*|\n================\nSimple Examples\n================\n\nHere, we include the examples for each of the speculative semanitcs: for branch instructions,\nfor store instructions and for return instructions.\n|*)\nDefinition init_state (st : state): SState :=\n     [ {|\n    State := st;\n    Ctr := 0;\n    RhoStack := [];\n    Rsb := [];\n    Id := none;\n    Window := ⊥  (* Should be bottom but window is a nat right now* Since it is 0 riht now *)\n    |} ].\n\n(* sp needs to be set to somethign that has to be high, since memory written with sp can be overwritten*)\nDefinition exampl_b := {|Program := prog_b;\nConfig := {|Pc := 0;\n            Mem := 1000 !-> 53; N 5000 !-> 2; t_empty ⊥; (* Need one N constructor for correct type inference*)\n            Regs := y !-> 0; A !-> 1000; t_empty 0\n        |} \n|}.\n\n\nDefinition empty_F : (Functions) := t_empty None.\n(*The program speculatively leaks 53 * 512 *)\nCompute (S_execute_tr empty_F (init_state exampl_b) semanticV1 100). (* 53 * 512 = 27136*)\n\nDefinition exampl_s := {|Program := prog_s;\nConfig := {|Pc := 0;\n            Mem := 1000 !-> 53; N 5000 !-> 2; t_empty ⊥; (* Need one N constructor for correct type inference*)\n            Regs := public !-> 0; secret !-> 53; t_empty 0\n        |} \n|}.\n\n(* The program speculatively leaks 53 * 512 *)\nCompute (S_execute_tr empty_F (init_state exampl_s) semanticV4 1000). (* 53 * 512 = 27136*)\n\nDefinition exampl_r := {|Program := prog_r;\nConfig := {|Pc := 7;\n            Mem := 1000 !-> 53; N 5000 !-> 2; t_empty ⊥ ; (* Need one N constructor for correct type inference*)\n            Regs := sp !-> 100; public !-> 0; secret !-> 53; t_empty 0\n        |} \n|}.\nPrint Functions.\nDefinition F_map : (Functions) := \"Manip_Stack\" !-> Some 0; \"Speculate\" !-> Some 2; t_empty None.\n(* Leaks 53*)\nCompute (S_execute_tr F_map (init_state exampl_r) semanticV5 1000).\n\n\n(*|\n=============================\nComposed Examples (Section 5)\n=============================\n\nWe always give the traces of the source semantics first to show that they do not leak\nthe secret value. Then, we show the trace under the combined semantics of the respective version.\n\n|*)\n\n\n(*|\nCombination B + R\n=================\n|*)\nDefinition exampl_br := {|Program := prog_br;\nConfig := {|Pc := 9;\n            Mem := 1000 !-> 53; N 5000 !-> 2; t_empty ⊥; (* Need one N constructor for correct type inference*)\n            Regs := sp !-> 100; public !-> 0; secret !-> 53; t_empty 0\n        |} \n|}.\n\nDefinition F_map_br : (Functions) := F_map.\n\n(*|\nThe traces of the source semantics for branch and return speculation.\nUnder these semantics the program prog_br is secure because the secret is not leaked\n|*)\nCompute (S_execute_tr F_map_br (init_state exampl_br) semanticV1 1000).\nCompute (S_execute_tr F_map_br (init_state exampl_br) semanticV5 1000).\n(* Leaks secret with value 53 *)\nCompute (S_execute_tr F_map_br (init_state exampl_br) semanticV15 1000).\n\n\n(*|\nCombination B + S\n=================\n|*)\nDefinition exampl_bs := {|Program := prog_bs;\nConfig := {|Pc := 0;\n            Mem := 1000 !-> 53; N 5000 !-> 2; t_empty 0; (* Need one N constructor for correct type inference*)\n            Regs := sp !-> 100; public !-> 0; secret !-> 53; t_empty 0\n        |} \n|}.\n\nCompute (S_execute_tr F_map (init_state exampl_bs) semanticV1 100). \nCompute (S_execute_tr F_map (init_state exampl_bs) semanticV4 100). \n(* Leaks the secret 53 *)\nCompute (S_execute_tr F_map (init_state exampl_bs) semanticV14 100). \n\n\n\n(*|\nCombination S + R\n=================\n|*)\nDefinition exampl_sr := {|Program := prog_sr;\nConfig := {|Pc := 8;\n            Mem := t_empty ⊥ ; (* Need one N constructor for correct type inference*)\n            Regs := sp !-> 100; public !-> 0; secret !-> 53; t_empty 0\n        |} \n|}.\n\nDefinition F_map_sr : (Functions) := F_map.\n\nCompute (S_execute_tr F_map_sr (init_state exampl_sr) semanticV4 100).\nCompute (S_execute_tr F_map_sr (init_state exampl_sr) semanticV5 100).\n\n(* Leaks 53 *)\nCompute (S_execute_tr F_map_sr (init_state exampl_sr) semanticV45 100).\n\n\n(*|\nCombination B + S + R\n======================\n|*)\nDefinition exampl_bsr := {|Program := prog_bsr;\nConfig := {|Pc :=9;\n            Mem := 1000 !-> 53; N 5000 !-> 2; t_empty ⊥; (* Need one N constructor for correct type inference*)\n            Regs := sp !-> 100; public !-> 0; secret !-> 53; t_empty 0\n        |} \n|}.\n\nDefinition F_map_bsr : (Functions) := F_map.\n\nCompute (S_execute_tr F_map_bsr (init_state exampl_bsr) semanticV1 200). \nCompute (S_execute_tr F_map_bsr (init_state exampl_bsr) semanticV4 200). \nCompute (S_execute_tr F_map_bsr (init_state exampl_bsr) semanticV5 200). \n(* Leaks secret value 53 in the trace *)\nCompute (S_execute_tr F_map_bsr (init_state exampl_bsr) semanticV145 200). \n", "meta": {"author": "XFabian", "repo": "Spectecoq", "sha": "1b71bc01e1eb15986886034a3027408f371d4064", "save_path": "github-repos/coq/XFabian-Spectecoq", "path": "github-repos/coq/XFabian-Spectecoq/Spectecoq-1b71bc01e1eb15986886034a3027408f371d4064/theories/examples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.29306201686046157}}
{"text": "(** * Limits of chains and cochains in the precategory of types *)\n\nRequire Import UniMath.Foundations.PartD.\nRequire Import UniMath.Foundations.NaturalNumbers.\nRequire Import UniMath.MoreFoundations.Notations.\nRequire Import UniMath.MoreFoundations.PartA.\nRequire Import UniMath.MoreFoundations.Univalence.\nRequire Import UniMath.MoreFoundations.WeakEquivalences.\n\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.categories.Type.Core.\nRequire Import UniMath.CategoryTheory.categories.Type.Limits.\n\nRequire Import UniMath.CategoryTheory.Chains.Chains.\nRequire Import UniMath.CategoryTheory.Chains.Cochains.\nRequire Import UniMath.CategoryTheory.limits.graphs.limits.\nRequire Import UniMath.CategoryTheory.limits.terminal.\nRequire Import UniMath.CategoryTheory.limits.graphs.colimits.\nRequire Import UniMath.Induction.FunctorCoalgebras_legacy.\n\nRequire Import UniMath.Induction.PolynomialFunctors.\nRequire Import UniMath.Induction.M.Limits.\nRequire Import UniMath.Induction.M.Core.\n\n(** The shifted chain (X', π') from (X, π) is one where Xₙ' = Xₙ₊₁ and πₙ' = πₙ₊₁. *)\nDefinition shift_chain (cha : chain type_precat) : chain type_precat.\nProof.\n  use tpair.\n  - exact (dob cha ∘ S).\n  - exact (λ _ _ path, dmor cha (maponpaths S path)).\nDefined.\n\n(** The shifted cochain (X', π') from (X, π) is one where Xₙ' = Xₙ₊₁ and πₙ' = πₙ₊₁. *)\nDefinition shift_cochain {C : precategory} (cochn : cochain C) : cochain C.\nProof.\n  use cochain_weq; use tpair.\n  - exact (dob cochn ∘ S).\n  - intros n; cbn.\n    apply (dmor cochn).\n    exact (idpath _).\nDefined.\n\n(** Interaction between transporting over (maponpaths S ed) and shifting the cochain *)\nDefinition transport_shift_cochain :\n  ∏ cochn ver1 ver2 (ed : ver1 = ver2)\n    (stdlim_shift : standard_limit (shift_cochain cochn)),\n  transportf (dob cochn) (maponpaths S ed) (pr1 stdlim_shift ver1) =\n  transportf (dob (shift_cochain cochn)) ed (pr1 stdlim_shift ver1).\nProof.\n  intros cochn ver1 ver2 ed stdlim_shift.\n  induction ed.\n  reflexivity.\nDefined.\n\n(** Ways to prove that [dmor]s are equal on cochains *)\nLemma cochain_dmor_paths {C : precategory} {ver1 ver2 : vertex conat_graph}\n      (cochn : cochain C) (p1 p2 : edge ver1 ver2) : dmor cochn p1 = dmor cochn p2.\nProof.\n  apply maponpaths, proofirrelevance, isasetnat.\nDefined.\n\n(** More ways to prove that [dmor]s are equal on cochains *)\nLemma cochain_dmor_paths_type {ver1 ver2 ver3 : vertex conat_graph}\n  (cochn : cochain type_precat) (p1 : edge ver1 ver3) (p2 : edge ver2 ver3)\n  (q1 : ver1 = ver2) :\n  ∏ v1 : dob cochn ver1, dmor cochn p1 v1 = dmor cochn p2 (transportf _ q1 v1).\nProof.\n  intro v1; cbn in *.\n  induction q1.\n  cbn.\n  exact (toforallpaths _ _ _ (cochain_dmor_paths cochn p1 p2) v1).\nDefined.\n\n\n(** We use the following tactic notations to mirror the \"equational style\" of\n    reasoning used in Ahrens, Capriotti, and Spadotti. *)\nLocal Tactic Notation \"≃\" constr(H) \"by\" tactic(t) := intermediate_weq H; [t|].\nLocal Tactic Notation \"≃'\" constr(H) \"by\" tactic(t) := intermediate_weq H; [|t].\nLocal Tactic Notation \"≃\" constr(H) := intermediate_weq H.\nLocal Tactic Notation \"≃'\" constr(H) := apply invweq; intermediate_weq H.\n\nLocal Lemma combine_over_nat_basic {X Y Z : nat → UU} :\n  X 0 ≃ Z 0 → (∏ n : nat, Y (S n) ≃ Z (S n)) →\n  (X 0 × ∏ n : nat, Y (S n)) ≃ ∏ n : nat, Z n.\nProof.\n  intros x0z0 yszs.\n  ≃ (Z 0 × (∏ n : nat, Z (S n))).\n  - apply weqdirprodf; [apply x0z0|].\n    apply weqonsecfibers, yszs.\n  - use weq_iso.\n    + intros z0zs.\n      intros n; induction n.\n      * exact (dirprod_pr1 z0zs).\n      * apply (dirprod_pr2 z0zs).\n    + intros xs; use make_dirprod.\n      * apply xs.\n      * exact (xs ∘ S).\n    + reflexivity.\n    + intros xs.\n      apply funextsec; intros n.\n      induction n; reflexivity.\nDefined.\n\nLocal Lemma combine_over_nat {X : nat → UU} {P : (X 0 × (∏ n : nat, X (S n))) → UU} :\n  (∑ x0 : X 0, ∑ xs : ∏ n : nat, X (S n), P (make_dirprod x0 xs)) ≃\n  (∑ xs : ∏ n : nat, X n, P (make_dirprod (xs 0) (xs ∘ S))).\nProof.\n  ≃ (∑ pair : (X 0 × ∏ n : nat, X (S n)), P pair) by apply weqtotal2asstol.\n  use weqbandf.\n  - apply (@combine_over_nat_basic X X X); intros; apply idweq.\n  - intros x0xs; cbn.\n    apply idweq.\nDefined.\n\nLocal Lemma combine_over_nat' {X : nat → UU} {P : X 0 → (∏ n : nat, X (S n)) → UU} :\n  (∑ x0 : X 0, ∑ xs : ∏ n : nat, X (S n), P x0 xs) ≃\n  (∑ xs : ∏ n : nat, X n, P (xs 0) (xs ∘ S)).\nProof.\n  ≃ (∑ (x0 : X 0) (xs : ∏ n : nat, X (S n)), (uncurry (Z := λ _, UU) P)\n                                             (make_dirprod x0 xs)) by apply idweq.\n  ≃' (∑ xs : ∏ n : nat, X n, uncurry P (Z := λ _, UU)\n                                     (make_dirprod (xs 0) (xs ∘ S))) by apply idweq.\n  apply combine_over_nat.\nDefined.\n\n(** If the base type is contractible, so is the type of sections over it. *)\nDefinition weqsecovercontr_uncurried {X : UU} {Y : X -> UU}\n           (P : ∏ x : X, Y x -> UU) (isc : iscontr (∑ x : X, Y x)) :\n  (∏ (x : X) (y : Y x), P x y) ≃ (P (pr1 (iscontrpr1 isc)) (pr2 (iscontrpr1 isc))).\nProof.\n  ≃ (∏ pair : (∑ x : X, Y x), uncurry (Z := λ _, UU) P pair) by\n    apply invweq, weqsecovertotal2.\n  ≃' (uncurry (Z := λ _, UU) P (iscontrpr1 isc)) by (apply idweq).\n  apply weqsecovercontr.\nDefined.\n\n(** Shifted cochains have equivalent limits.\n    (Lemma 12 in Ahrens, Capriotti, and Spadotti) *)\n\nDefinition shifted_limit (cocha : cochain type_precat) :\n  standard_limit (shift_cochain cocha) ≃ standard_limit cocha.\nProof.\n  pose (X := dob cocha); cbn in X.\n  pose (π n := (@dmor _ _ cocha (S n) n (idpath _))).\n  unfold standard_limit, shift_cochain; cbn.\n\n  assert (isc : ∏ x : ∏ v : nat, dob cocha (S v),\n                iscontr (∑ x0 : X 0, (π 0 (x 0)) = x0)).\n  {\n    intros x.\n    apply iscontr_paths_from.\n  }\n\n  (** Step (2) *)\n  (** This is the direct product with the type proven contractible above *)\n  ≃ (∑ xs : ∏ v : nat, X (S v),\n    (∏ (u v : nat) (e : S v = u),\n    (dmor cocha (idpath (S (S v)))\n      ∘ transportf (λ o : nat, X (S o) → X (S (S v))) e\n      (idfun (X (S (S v))))) (xs u) = xs v)\n    × (∑ x0 : X 0, (π 0 (xs 0)) = x0)) by\n    (apply weqfibtototal; intro; apply dirprod_with_contr_r; apply isc).\n\n  (** Now, we swap the components in the direct product. *)\n  ≃ (∑ xs : ∏ v : nat, X (S v),\n    (∑ x0 : X 0, π 0 (xs 0) = x0) ×\n    (∏ (u v : nat) (e : S v = u),\n      (dmor cocha (idpath (S (S v)))\n      ∘ transportf (λ o : nat, X (S o) → X (S (S v))) e\n      (idfun (X (S (S v))))) (xs u) = xs v)) by\n    (apply weqfibtototal; intro; apply weqdirprodcomm).\n\n  (** Using associativity of Σ-types, *)\n  ≃ (∑ xs : ∏ v : nat, X (S v),\n     ∑ x0 : X 0,\n     (π 0 (xs 0) = x0) ×\n     (∏ (u v : nat) (e : S v = u),\n       (dmor cocha (idpath (S (S v)))\n       ∘ transportf (λ o : nat, X (S o) → X (S (S v))) e\n       (idfun (X (S (S v))))) (xs u) = xs v)) by\n    (apply weqfibtototal; intro; apply weqtotal2asstor).\n\n  (** And again by commutativity of ×, we swap the first components *)\n  ≃ (∑ x0 : X 0,\n     ∑ xs : ∏ n : nat, X (S n),\n     (π 0 (xs 0) = x0) ×\n     (∏ (u v : nat) (e : S v = u),\n       (dmor cocha (idpath (S (S v)))\n       ∘ transportf (λ o : nat, X (S o) → X (S (S v))) e\n       (idfun (X (S (S v))))) (xs u) = xs v)) by (apply weqtotal2comm).\n\n  (** Step 3: combine the first bits *)\n  ≃ (∑ xs : ∏ n : nat, X n,\n      (π 0 (xs 1) = xs 0) ×\n      (∏ (u v : nat) (e : S v = u),\n        (dmor cocha (idpath (S (S v)))\n        ∘ transportf (λ o : nat, dob cocha (S o) → dob cocha (S (S v))) e\n        (idfun (dob cocha (S (S v))))) (xs (S u)) = xs (S v))).\n  apply (@combine_over_nat' X\n        (λ x0 xs,\n        π 0 (xs 0) = x0\n        × (∏ (u v : nat) (e : S v = u),\n            (dmor cocha (idpath (S (S v)))\n            ∘ transportf (λ o : nat, X (S o) → X (S (S v))) e (idfun (X (S (S v)))))\n              (xs u) = xs v))).\n\n  (** Now the first component is the same. *)\n  apply weqfibtototal; intros xs.\n\n  ≃ (π 0 (xs 1) = xs 0\n    × (∏ (v u : nat) (e : S v = u),\n      (dmor cocha (idpath (S (S v)))\n        ∘ transportf (λ o : nat, dob cocha (S o) → dob cocha (S (S v))) e\n            (idfun (dob cocha (S (S v))))) (xs (S u)) = xs (S v))) by\n    apply weqdirprodf; [apply idweq|apply flipsec_weq].\n\n  ≃' (∏ (v u : nat) (e : S v = u), dmor cocha e (xs u) = xs v) by\n    apply flipsec_weq.\n\n  (** Split into cases on n = 0 or n > 0. *)\n  (** Coq is bad about coming up with these implicit arguments, so we have to be\n      very excplicit. *)\n  apply (@combine_over_nat_basic\n           (λ n, π n (xs (S n)) = xs n)\n           (λ v, ∏ (u : nat) (e : v = u),\n             (dmor cocha (idpath (S v))\n               ∘ _ (idfun (dob cocha (S v)))) (xs (S u)) = xs v)\n           (λ v, ∏ (u : nat) (e : S v = u), dmor cocha e (xs u) = xs v)).\n\n  (** We use the following fact over and over to simplify the remaining types:\n      for any x : X, the type ∑ y : X, x = y is contractible. *)\n  - apply invweq.\n    apply (@weqsecovercontr_uncurried\n             nat (λ n, 1 = n) (λ _ _, _ = xs 0) (iscontr_paths_from 1)).\n  - intros u.\n    ≃ ((dmor cocha (idpath (S (S u)))\n            ∘ transportf (λ o : nat, dob cocha (S o) → dob cocha (S (S u)))\n                (idpath (S u)) (idfun (dob cocha (S (S u))))) (xs (S (S u))) =\n          xs (S u)).\n    + apply (@weqsecovercontr_uncurried\n               nat (λ n, (S u) = n) (λ _ _, _ _ = xs (S u)) (iscontr_paths_from _)).\n    + cbn.\n      apply invweq.\n      apply (@weqsecovercontr_uncurried\n               nat (λ n, (S (S u)) = n) (λ _ _, _ = xs (S u)) (iscontr_paths_from _)).\nDefined.\n\n\n(** Lemma 11 in Ahrens, Capriotti, and Spadotti *)\nLocal Definition Z X l :=\n ∑ (x : ∏ n, X n), ∏ n, x (S n) = l n (x n).\nLocal Lemma lemma_11 (X : nat -> UU) (l : ∏ n, X n -> X (S n)) : Z X l ≃ X 0.\nProof.\n set (f (xp : Z X l) := pr1 xp 0).\n transparent assert (g : (X 0 -> Z X l)). {\n   intros x.\n   exists (nat_rect _ x l).\n   exact (λ n, idpath _).\n }\n apply (make_weq f).\n apply (isweq_iso f g).\n - cbn.\n   intros xp; induction xp as [x p].\n   transparent assert ( q : (nat_rect X (x 0) l ~ x )). {\n     intros n; induction n; cbn.\n     * reflexivity.\n     * exact (maponpaths (l n) IHn @ !p n).\n   }\n   set (q' := funextsec _ _ _ q).\n   use total2_paths_f; cbn.\n   + exact q'.\n   + rewrite transportf_sec_constant. apply funextsec; intros n.\n     intermediate_path (!maponpaths (λ x, x (S n)) q' @\n                         maponpaths (λ x, l n (x n)) q'). {\n       use transportf_paths_FlFr.\n     }\n     intermediate_path (!maponpaths (λ x, x (S n)) q' @\n                         maponpaths (l n) (maponpaths (λ x, x n) q')). {\n       apply maponpaths. symmetry. use maponpathscomp.\n     }\n     intermediate_path (! q (S n) @ maponpaths (l n) (q n)). {\n       unfold q'.\n       repeat rewrite maponpaths_funextsec.\n       reflexivity.\n     }\n     intermediate_path (! (maponpaths (l n) (q n) @ ! p n) @\n                          maponpaths (l n) (q n)). {\n       reflexivity.\n     }\n     rewrite pathscomp_inv.\n     rewrite <- path_assoc.\n     rewrite pathsinv0l.\n     rewrite pathsinv0inv0.\n     rewrite pathscomp0rid.\n     reflexivity.\n - cbn.\n   reflexivity.\nDefined.\n\n(* Maybe easier to apply in Lemma *)\nLocal Definition lemma_11_unfolded (X : nat -> UU) (l : ∏ n, X n -> X (S n)) :\n  (∑ (x : ∏ n, X n), ∏ n, x (S n) = l n (x n)) ≃ X 0 := lemma_11 X l.\n\nLemma cochain_limit_standard_limit_weq (cha cha' : cochain type_precat) :\n  cochain_limit cha ≃ cochain_limit cha' → standard_limit cha ≃ standard_limit cha'.\nProof.\n  intro f.\n  apply (weqcomp (invweq (lim_equiv _))).\n  apply (weqcomp f).\n  apply (lim_equiv _).\nDefined.\n\n(* There is a simpler way to give cones over the terminal cochain. *)\nLocal Open Scope cat.\nSection CochainCone.\n\n  Context (A C : UU) (B : A -> UU).\n\n  Definition terminal_cochain  : cochain type_precat :=\n    termCochain (TerminalType) (polynomial_functor A B).\n\n  Definition m_type  := standard_limit terminal_cochain.\n\n  Definition apply_on_chain (cha : cochain type_precat) : cochain type_precat :=\n    mapcochain (polynomial_functor A B) cha.\n\n  (* Shifting the terminal cochain is equivalent to applying\n    the polynomial functor once *)\n  Definition terminal_cochain_shifted_lim :\n    standard_limit (shift_cochain terminal_cochain) ≃\n                  standard_limit (apply_on_chain terminal_cochain).\n  Proof.\n    apply cochain_limit_standard_limit_weq.\n    unfold shift_cochain, apply_on_chain, cochain_limit.\n    apply weqfibtototal;intros.\n    apply weqonsecfibers; intro n.\n    apply idweq.\n  Defined.\n\n  Let W n := iter_functor (polynomial_functor A B) n unit.\n  Let Cone0' := λ n : nat, C → W n.\n  Let Cone0 := ∏ n : nat, Cone0' n.\n  Let π := λ n : nat, dmor terminal_cochain (idpath (S n)).\n\n  Definition simplified_cone : UU :=\n    (∑ (u : Cone0), ∏ n : nat, (π n ∘ u (S n))%functions = u n).\n\n  Lemma simplify_cochain_cone :\n    cone terminal_cochain C ≃ simplified_cone.\n  Proof.\n    unfold cone, Cone0.\n    apply weqfibtototal; intro f.\n    intermediate_weq (\n      (∏ (u v : vertex conat_graph) (e0 : edge u v),\n      f _ · dmor terminal_cochain e0 ~ f v)\n      ). {\n      do 3 (apply weqonsecfibers; intro).\n      apply invweq.\n      apply weqfunextsec.\n    }\n    apply invweq.\n    intermediate_weq (∏ u, (π u ∘ f (S u))%functions ~ f u). {\n      apply invweq.\n      apply weqonsecfibers; intro.\n      apply weqfunextsec.\n    }\n    unfold homotsec.\n    apply invweq.\n    intermediate_weq (\n      (∏ (u v : vertex conat_graph) (c : C) (e0 : edge u v),\n       (f u · dmor terminal_cochain e0) c = f v c)). {\n      do 2 (apply weqonsecfibers; intro).\n      apply flipsec_weq.\n    }\n    intermediate_weq (\n      (∏ (c : C) (u v : vertex conat_graph) (e0 : edge u v),\n       (f u · dmor terminal_cochain e0) c = f v c)). {\n      intermediate_weq (\n        (∏ (u : vertex conat_graph) (c : C) (v : vertex conat_graph) (e0 : edge u v),\n        (f u · dmor terminal_cochain e0) c = f v c)). {\n        apply weqonsecfibers; intro.\n        apply flipsec_weq.\n      }\n      apply flipsec_weq.\n    }\n    apply invweq.\n    intermediate_weq ((∏ (x : C) (u : nat), (π u ∘ f (S u))%functions x = f u x));\n      [apply flipsec_weq|].\n    apply weqonsecfibers; intro c.\n    apply invweq.\n    use weq_iso.\n    - intros eq; intro; apply eq.\n    - intros eq.\n      intros ? ? e.\n      induction e; apply eq.\n    - abstract ( intro;\n      do 2 (apply funextsec; intro);\n      apply funextsec; intro e;\n      induction e;\n      reflexivity ).\n    - abstract ( intro; apply funextsec; intro; reflexivity ).\n  Defined.\n\nEnd CochainCone.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/Induction/M/Chains.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.29306201686046157}}
{"text": "Require Import String.\n\nRequire Import core.utils.Utils.\nRequire Import core.Model.\nRequire Import core.Syntax.\nRequire Import core.EqDec. \nRequire Import Bool.\nRequire Import Arith.\nRequire Import TransformationConfiguration.\nRequire Import Expressions.\nScheme Equality for list.\n\n\nSection Semantics.\n\nContext {tc: TransformationConfiguration}.\n\n(** * Instantiate **)\n\nDefinition matchRuleOnPattern (r: Rule) (sm : SourceModel) (sp: list SourceModelElement) : bool :=\n  match evalGuardExpr r sm sp with Some true => true | _ => false end.\n\nDefinition matchPattern (tr: Transformation) (sm : SourceModel) (sp: list SourceModelElement) : list Rule :=\n  filter (fun (r:Rule) => matchRuleOnPattern r sm sp) (Transformation_getRules tr).\n\nDefinition instantiateElementOnPattern (o: OutputPatternElement) (sm: SourceModel) (sp: list SourceModelElement) (iter: nat)\n  : option TargetModelElement :=\n  evalOutputPatternElementExpr sm sp iter o.\n\nDefinition instantiateIterationOnPattern (r: Rule) (sm: SourceModel) (sp: list SourceModelElement) (iter: nat) :  list TargetModelElement :=\n  flat_map (fun o => optionToList (instantiateElementOnPattern o sm sp iter))\n    (Rule_getOutputPatternElements r).\n\nDefinition instantiateRuleOnPattern (r: Rule) (sm: SourceModel) (sp: list SourceModelElement) :  list TargetModelElement :=\n  flat_map (instantiateIterationOnPattern r sm sp)\n    (seq 0 (evalIteratorExpr r sm sp)).\n\nDefinition instantiatePattern (tr: Transformation) (sm : SourceModel) (sp: list SourceModelElement) : list TargetModelElement :=\n  flat_map (fun r => instantiateRuleOnPattern r sm sp) (matchPattern tr sm sp).\n\nDefinition instantiateRuleOnPatternIterName (r: Rule) (sm: SourceModel) (sp: list SourceModelElement) (iter: nat) (name: string): option (TargetModelElement) :=\n  match (Rule_findOutputPatternElement r name) with\n  | Some o =>  instantiateElementOnPattern o sm sp iter\n  | None => None\n  end.\n\n(** * Trace **)\n\nDefinition traceElementOnPattern (o: OutputPatternElement) (sm: SourceModel) (sp: list SourceModelElement) (iter: nat)\n  : option TraceLink :=\n  match (instantiateElementOnPattern o sm sp iter) with\n  | Some e => Some (buildTraceLink (sp, iter, OutputPatternElement_getName o) e)\n  | None => None\n  end.\n\nDefinition traceIterationOnPattern (r: Rule) (sm: SourceModel) (sp: list SourceModelElement) (iter: nat) :  list TraceLink :=\n  flat_map (fun o => optionToList (traceElementOnPattern o sm sp iter))\n    (Rule_getOutputPatternElements r).\n\nDefinition traceRuleOnPattern (r: Rule) (sm: SourceModel) (sp: list SourceModelElement) :  list TraceLink :=\n  flat_map (traceIterationOnPattern r sm sp)\n    (seq 0 (evalIteratorExpr r sm sp)).\n\nDefinition tracePattern (tr: Transformation) (sm : SourceModel) (sp: list SourceModelElement) : list TraceLink :=\n  flat_map (fun r => traceRuleOnPattern r sm sp) (matchPattern tr sm sp).\n\nDefinition maxArity (tr: Transformation) : nat := Transformation_getArity tr.\n\nDefinition allTuples (tr: Transformation) (sm : SourceModel) :list (list SourceModelElement) :=\n  tuples_up_to_n (allModelElements sm) (maxArity tr).\n\nDefinition trace (tr: Transformation) (sm : SourceModel) : list TraceLink :=\n  flat_map (tracePattern tr sm) (allTuples tr sm).  \n\nDefinition resolveIter (tls: list TraceLink) (sm: SourceModel) (name: string)\n            (sp: list SourceModelElement)\n            (iter : nat) : option TargetModelElement :=\nlet tl := find (fun tl: TraceLink => \n  (list_beq SourceModelElement SourceElement_eqb (TraceLink_getSourcePattern tl) sp) &&\n  ((TraceLink_getIterator tl) =? iter) &&\n  ((TraceLink_getName tl) =? name)%string) tls in\nmatch tl with\n  | Some tl' => Some (TraceLink_getTargetElement tl')\n  | None => None\nend.\n\nDefinition resolve (tr: list TraceLink) (sm: SourceModel) (name: string)\n  (sp: list SourceModelElement) : option TargetModelElement :=\n  resolveIter tr sm name sp 0.\n\nDefinition resolveAllIter (tr: list TraceLink) (sm: SourceModel) (name: string)\n  (sps: list(list SourceModelElement)) (iter: nat)\n  : option (list TargetModelElement) :=\n  Some (flat_map (fun l:(list SourceModelElement) => optionToList (resolveIter tr sm name l iter)) sps).\n\nDefinition resolveAll (tr: list TraceLink) (sm: SourceModel) (name: string)\n  (sps: list(list SourceModelElement)) : option (list TargetModelElement) :=\n  resolveAllIter tr sm name sps 0.\n\nDefinition maybeResolve (tr: list TraceLink) (sm: SourceModel) (name: string)\n  (sp: option (list SourceModelElement)) : option TargetModelElement :=\n  match sp with \n  | Some sp' => resolve tr sm name sp'\n  | None => None\n  end.\n\nDefinition maybeResolveAll (tr: list TraceLink) (sm: SourceModel) (name: string)\n  (sp: option (list (list SourceModelElement))) : option (list TargetModelElement) :=\n  match sp with \n  | Some sp' => resolveAll tr sm name sp'\n  | None => None\n  end.\n\n(** * Apply **)\n\nDefinition applyElementOnPattern\n            (ope: OutputPatternElement)\n            (tr: Transformation)\n            (sm: SourceModel)\n            (sp: list SourceModelElement) (iter: nat) : list TargetModelLink :=\n  match (evalOutputPatternElementExpr sm sp iter ope) with \n  | Some l => optionListToList (evalOutputPatternLinkExpr sm sp l iter (trace tr sm) ope)\n  | None => nil\n  end.\n\nDefinition applyIterationOnPattern (r: Rule) (tr: Transformation) (sm: SourceModel) (sp: list SourceModelElement) (iter: nat) : list TargetModelLink :=\n  flat_map (fun o => applyElementOnPattern o tr sm sp iter)\n    (Rule_getOutputPatternElements r).\n\nDefinition applyRuleOnPattern (r: Rule) (tr: Transformation) (sm: SourceModel) (sp: list SourceModelElement): list TargetModelLink :=\n  flat_map (applyIterationOnPattern r tr sm sp)\n    (seq 0 (evalIteratorExpr r sm sp)).\n\nDefinition applyPattern (tr: Transformation) (sm : SourceModel) (sp: list SourceModelElement) : list TargetModelLink :=\n  flat_map (fun r => applyRuleOnPattern r tr sm sp) (matchPattern tr sm sp).\n\n(** * Execute **)\n\nDefinition execute (tr: Transformation) (sm : SourceModel) : TargetModel :=\n  Build_Model\n    (* elements *) (flat_map (instantiatePattern tr sm) (allTuples tr sm))\n    (* links *) (flat_map (applyPattern tr sm) (allTuples tr sm)).\n\nEnd Semantics.\n", "meta": {"author": "atlanmod", "repo": "coqtl", "sha": "5daf5d915b66328ae5ec48f55c44731372563c87", "save_path": "github-repos/coq/atlanmod-coqtl", "path": "github-repos/coq/atlanmod-coqtl/coqtl-5daf5d915b66328ae5ec48f55c44731372563c87/core/Semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.48828339529583475, "lm_q1q2_score": 0.29306200987660913}}
{"text": "(** Heavily annotated for a tutorial introduction.\n ** See the Makefile for how to strip the annotations\n **)\n\n(** First, import the entire Floyd proof automation system, which\n ** includes the VeriC program logic and the MSL theory of separation logic\n **)\nRequire Import floyd.proofauto.\n\n(** Import the theory of list segments.  This is not, strictly speaking,\n ** part of the Floyd system.  In principle, any user of Floyd can build\n ** theories of new data structures (list segments, trees, doubly linked\n ** lists, trees with cross edges, etc.).  We emphasize this by putting\n ** list_dt in the progs directory.   \"dt\" stands for \"dependent types\",\n ** as the theory uses Coq's dependent types to handle user-defined\n ** record fields.\n **)\nRequire Import progs.list_dt. Import LsegSpecial.\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 in the reverse.c file.\n **)\nRequire Import 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.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\n(** The reverse.c program uses the linked list structure [struct list].\n ** This satisfies the linked-list pattern, in that it has one self-reference\n ** field (in this case, called [tail]) and arbitrary other fields.  The [Instance]\n ** explains (and proves) how [struct list] satisfies the [listspec] pattern.\n **)\nInstance LS: listspec _list _tail (fun _ _ => emp).\nProof. eapply mk_listspec; reflexivity. Defined.\n\n(**  An auxiliary definition useful in the specification of [sumlist] *)\nDefinition sum_int := fold_right Int.add Int.zero.\n\nDefinition t_struct_list := Tstruct _list noattr.\n\n(** Specification of the [sumlist] function from reverse.c.  All the functions\n ** defined in the file, AND extern functions imported by the .c file,\n ** must be declared in this way.\n **)\nDefinition sumlist_spec :=\n DECLARE _sumlist\n  WITH sh : share, contents : list int, p: val\n  PRE [ _p OF (tptr t_struct_list) ]\n     PROP(readable_share sh)\n     LOCAL (temp _p p)\n     SEP (lseg LS sh (map Vint contents) p nullval)\n  POST [ tint ]\n     PROP()\n     LOCAL(temp ret_temp (Vint (sum_int contents)))\n     SEP (lseg LS sh (map Vint contents) p nullval).\n\nDefinition reverse_spec :=\n DECLARE _reverse\n  WITH sh : share, contents : list val, p: val\n  PRE  [ _p OF (tptr t_struct_list) ]\n     PROP (writable_share sh)\n     LOCAL (temp _p p)\n     SEP (lseg LS sh contents p nullval)\n  POST [ (tptr t_struct_list) ]\n    EX p:val,\n     PROP () LOCAL (temp ret_temp p)\n     SEP (lseg LS sh (rev contents) p nullval).\n\n(** The \"main\" function is special, since its precondition includes\n ** the spatial (SEP) resource describing all the extern initialized\n ** global variables.  That resource is calculated automatically\n ** from the program (prog) by the \"main_pre\" operator.  **)\nDefinition main_spec :=\n DECLARE _main\n  WITH u : unit\n  PRE  [] main_pre prog nil u\n  POST [ tint ] main_post prog nil u.\n\n(** Declare all the functions, in exactly the same order as they\n ** appear in reverse.c (and in reverse.v).\n **)\nDefinition Gprog : funspecs :=   ltac:(with_library prog [\n    sumlist_spec; reverse_spec; main_spec]).\n\n(** A little equation about the list_cell predicate *)\nLemma list_cell_eq: forall sh i p ,\n   sepalg.nonidentity sh ->\n   field_compatible t_struct_list [] p ->\n   list_cell LS sh (Vint i) p =\n   field_at sh t_struct_list (DOT _head) (Vint i) p.\nProof.\n  intros.\n  unfold list_cell, field_at; simpl.\n  rewrite !prop_true_andp by auto with field_compatible.\n  reflexivity.\nQed.\n\n(** Here's a loop invariant for use in the body_sumlist proof *)\nDefinition sumlist_Inv (sh: share) (contents: list int) (p: val) : environ->mpred :=\n          (EX cts1: list int, EX cts2: list int, EX t: val,\n            PROP (contents = cts1++cts2)\n            LOCAL (temp _t t; temp _s (Vint (sum_int cts1)))\n            SEP ( lseg LS sh (map Vint cts1) p t ; lseg LS sh (map Vint cts2) t nullval)).\n\nLemma sum_int_app:\n  forall a b, sum_int (a++b) = Int.add (sum_int a) (sum_int b).\nProof.\nintros.\ninduction a; simpl. rewrite Int.add_zero_l; auto.\nrewrite IHa. rewrite Int.add_assoc. auto.\nQed.\n\n(** For every function definition in the C program, prove that the\n ** function-body (in this case, f_sumlist) satisfies its specification\n ** (in this case, sumlist_spec).\n **)\nLemma body_sumlist: semax_body Vprog Gprog f_sumlist sumlist_spec.\nProof.\n(** Here is the standard way to start a function-body proof:  First,\n ** start-function; then forward.\n **)\nstart_function.\nforward.  (* s = 0; *)\nforward.  (* t = p; *)\nforward_while (sumlist_Inv sh contents p).\n* (* Prove that current precondition implies loop invariant *)\nExists (@nil int) contents p.\nentailer!. cancel.\n* (* Prove that loop invariant implies typechecking condition *)\nentailer!.\n* (* Prove that loop body preserves invariant *)\nfocus_SEP 1; apply semax_lseg_nonnull; [ | intros h' r y ? ?].\nentailer!.\ndestruct cts2; inversion H0; clear H0; subst_any.\nsimpl. (* this line not necessary, but makes things look nicer *)\nassert_PROP (field_compatible t_struct_list nil t) as FC by entailer!.\nrewrite list_cell_eq by auto.\nforward.  (* h = t->head; *)\nforward.  (*  t = t->tail; *)\nforward.  (* s = s + h; *)\nExists (cts1++[i],cts2,y).\nentailer.\napply andp_right.\napply prop_right.\nsplit.\nrewrite app_ass; reflexivity.\n f_equal. rewrite sum_int_app. f_equal. simpl. apply Int.add_zero.\nrewrite map_app. simpl map.\neapply derives_trans; [ | apply (lseg_cons_right_list LS) with (y:=t); auto].\nrewrite list_cell_eq by auto.\ncancel.\n* (* After the loop *)\nforward.  (* return s; *)\ndestruct cts2; [| inversion H]. rewrite <- app_nil_end.\nentailer!.\nQed.\n\nDefinition reverse_Inv (sh: share) (contents: list val) : environ->mpred :=\n          (EX cts1: list val, EX cts2 : list val, EX w: val, EX v: val,\n            PROP (contents = rev cts1 ++ cts2)\n            LOCAL (temp _w w; temp _v v)\n            SEP (lseg LS sh cts1 w nullval;\n                   lseg LS sh cts2 v nullval)).\n\nLemma body_reverse: semax_body Vprog Gprog f_reverse reverse_spec.\nProof.\nstart_function.\nforward.  (* w = NULL; *)\nforward.  (* v = p; *)\nforward_while (reverse_Inv sh contents).\n* (* precondition implies loop invariant *)\nExists (@nil val) contents nullval p.\nrewrite lseg_eq by (simpl; auto).\nentailer!.\n* (* loop invariant implies typechecking of loop condition *)\nentailer!.\n* (* loop body preserves invariant *)\nfocus_SEP 1; apply semax_lseg_nonnull;\n        [entailer | intros h r y ? ?; simpl].\nsubst cts2.\nforward. (* t = v->tail; *)\nforward. (* v->tail = w; *)\n(* The following line is optional, the proof works without it. *)\nreplace_SEP 2 (field_at sh t_struct_list (DOT _tail) w v) by entailer!.\nforward.  (*  w = v; *)\nforward.  (* v = t; *)\n(* at end of loop body, re-establish invariant *)\nExists (h::cts1,r,v,y).\nentailer!.  (* smt_test verif_reverse_example2 *)\n - rewrite app_ass. auto.\n - rewrite (lseg_unroll _ sh (h::cts1)).\n   apply orp_right2.\n   unfold lseg_cons.\n   apply andp_right.\n   + apply prop_right.\n      destruct v; try contradiction; intro Hx; inv Hx.\n   + Exists h cts1 w.\n      entailer!.\n* (* after the loop *)\nforward.  (* return w; *)\nExists w; entailer!.\nrewrite <- app_nil_end, rev_involutive.\nauto.\nQed.\n\n(** The next lemma concerns the extern global initializer,\n ** struct list three[] = {{1, three+1}, {2, three+2}, {3, NULL}};\n ** This is equivalent to a linked list of three elements [1,2,3].\n ** The proof is not very beautiful at present; it would be helpful\n ** to have a nicer proof theory for reasoning about this kind of thing.\n **)\n\nLemma setup_globals:\n forall Delta x,\n  (glob_types Delta) ! _three = Some (tarray t_struct_list 3) ->\n  ENTAIL Delta, PROP  ()\n   LOCAL  (gvar _three x)\n   SEP\n   (mapsto Ews tuint (offset_val 0 x) (Vint (Int.repr 1));\n    mapsto Ews (tptr t_struct_list) (offset_val 4 x)\n        (offset_val 8 x);\n   mapsto Ews tuint (offset_val 8 x) (Vint (Int.repr 2));\n   mapsto Ews (tptr t_struct_list) (offset_val 12 x)\n       (offset_val 16 x);\n   mapsto Ews tuint (offset_val 16 x) (Vint (Int.repr 3));\n   mapsto Ews tuint (offset_val 20 x) (Vint (Int.repr 0)))\n  |-- PROP() LOCAL(gvar _three x)\n        SEP (lseg LS Ews (map Vint (Int.repr 1 :: Int.repr 2 :: Int.repr 3 :: nil))\n                  x nullval).\nProof.\n intros.\n  go_lower.\n  rewrite !prop_true_andp by auto.\n  rewrite <- (sepcon_emp (mapsto _ _ (offset_val 20 _) _)).\n  assert (FC: field_compatible (tarray t_struct_list 3) [] x)\n    by (hnf; repeat apply conj; auto; compute; auto).\n  (* apply field_compatible_offset_zero in FC. *)\n  match goal with |- ?A |-- _ => set (a:=A) end.\n  replace x with (offset_val 0 x) by normalize.\n  subst a.\n\n  repeat\n    match goal with |- _ * (mapsto _ _ _ ?q * _) |-- lseg _ _ _ (offset_val ?n _) _ =>\n    assert (FC': field_compatible t_struct_list [] (offset_val n x));\n      [apply (@field_compatible_nested_field CompSpecs (tarray t_struct_list 3)\n         [ArraySubsc (n/8)] x);\n       simpl;\n       unfold field_compatible in FC |- *; simpl in FC |- *;\n       assert (0 <= n/8 < 3) by (cbv [Z.div]; simpl; omega);\n       tauto\n      |];\n    apply @lseg_unroll_nonempty1 with q;\n      [destruct x; try contradiction; intro Hx; inv Hx | normalize; reflexivity | ];\n    rewrite list_cell_eq by auto;\n    do 2 (apply sepcon_derives;\n      [ unfold field_at; rewrite prop_true_andp by auto with field_compatible;\n        unfold data_at_rec, at_offset; simpl; normalize | ]);\n    clear FC'\n    end.\n\n  rewrite mapsto_tuint_tptr_nullval; auto.\n  rewrite @lseg_nil_eq.\n  rewrite prop_true_andp; auto.\n  split; reflexivity.\nQed.\n\nLemma body_main:  semax_body Vprog Gprog f_main main_spec.\nProof.\nname three _three.\nstart_function.\nchange (Tstruct _ _) with t_struct_list.\nfold noattr. fold (tptr t_struct_list).\neapply semax_pre; [\n  eapply ENTAIL_trans; [ | apply (setup_globals Delta three); auto ] | ].\n entailer!.\nforward_call (*  r = reverse(three); *)\n  (Ews, map Vint [Int.repr 1; Int.repr 2; Int.repr 3], three).\nIntros r'.\nrewrite <- map_rev. simpl rev.\nforward_call  (* s = sumlist(r); *)\n   (Ews, Int.repr 3 :: Int.repr 2 :: Int.repr 1 :: nil, r').\nforward.  (* return s; *)\nQed.\n\nExisting Instance NullExtension.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_sumlist.\nsemax_func_cons body_reverse.\nsemax_func_cons body_main.\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_reverse.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2930620098766091}}
{"text": "Require Import Mem0 Mem1 HoareDef STB 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.\n\nSet Implicit Arguments.\n\nLocal Open Scope nat_scope.\n\n\n\n(*** black + delta --> new_black ***)\nDefinition add_delta_to_black `{M: URA.t} (b: Auth.t M) (w: Auth.t _): Auth.t _ :=\n  match b, w with\n  | Auth.excl e _, Auth.frag f1 => Auth.excl (e ⋅ f1) URA.unit\n  | _, _ => Auth.boom\n  end\n.\n\n\n\n(*** TODO: move to Coqlib ***)\nLemma repeat_nth_some\n      X (x: X) sz ofs\n      (IN: ofs < sz)\n  :\n    nth_error (repeat x sz) ofs = Some x\n.\nProof.\n  ginduction sz; ii; ss.\n  - lia.\n  - destruct ofs; ss. exploit IHsz; et. lia.\nQed.\n\nLemma repeat_nth_none\n      X (x: X) sz ofs\n      (IN: ~(ofs < sz))\n  :\n    nth_error (repeat x sz) ofs = None\n.\nProof.\n  generalize dependent ofs. induction sz; ii; ss.\n  - destruct ofs; ss.\n  - destruct ofs; ss. { lia. } hexploit (IHsz ofs); et. lia.\nQed.\n\nLemma repeat_nth\n      X (x: X) sz ofs\n  :\n    nth_error (repeat x sz) ofs = if (ofs <? sz) then Some x else None\n.\nProof.\n  des_ifs.\n  - eapply repeat_nth_some; et. apply_all_once Nat.ltb_lt. ss.\n  - eapply repeat_nth_none; et. apply_all_once Nat.ltb_ge. lia.\nQed.\n\n\n\nLtac Ztac := all_once_fast ltac:(fun H => first[apply Z.leb_le in H|apply Z.ltb_lt in H|apply Z.leb_gt in H|apply Z.ltb_ge in H|idtac]).\n\nLemma _points_to_hit: forall b ofs v, (_points_to (b, ofs) [v] b ofs) = (Some v).\nProof. i. rewrite unfold_points_to. ss. des_ifs; bsimpl; des; des_sumbool; subst; Ztac; try lia. rewrite Z.sub_diag. ss. Qed.\n\nLemma _points_to_miss: forall b ofs b' ofs' (MISS: b <> b' \\/ ofs <> ofs') v, (_points_to (b, ofs) [v] b' ofs') = ε.\nProof. i. rewrite unfold_points_to. ss. des_ifs; bsimpl; des; des_sumbool; subst; Ztac; try lia. Qed.\n\nLemma _points_to_disj: forall b0 ofs0 v0 b1 ofs1 v1,\n    URA.wf (_points_to (b0, ofs0) [v0] ⋅ _points_to (b1, ofs1) [v1]) -> b0 <> b1 \\/ ofs0 <> ofs1.\nProof.\n  ii. do 2 ur in H. specialize (H b0 ofs0). rewrite _points_to_hit in H.\n  rewrite unfold_points_to in H. ss. ur in H. des_ifs_safe. des_ifs; bsimpl; des; des_sumbool; subst; Ztac; try lia.\n  assert(ofs0 = ofs1) by lia. subst. rewrite Z.sub_diag in *. ss.\nQed.\n\nLemma dec_true: forall X `{Dec X} (x0 x1: X), x0 = x1 -> ((dec x0 x1): bool) = true.\nProof. ii. subst. unfold dec. destruct H; ss. Qed.\n\nLemma dec_false: forall X `{Dec X} (x0 x1: X), x0 <> x1 -> ((dec x0 x1): bool) = false.\nProof. ii. subst. unfold dec. destruct H; ss. Qed.\n(* Lemma local_update_same *)\n(*       `{M: URA.t} *)\n(*       x0 y0 x1 y1 *)\n(*       (SAME: x0 ⋅ y0 = x1 ⋅ y1) *)\n(*   : *)\n(*     URA.local_update x0 y0 x1 y1 *)\n(* . *)\n(* Proof. *)\n(*   r. ii. des. subst. esplits; et. *)\n(*   - *)\n(* Qed. *)\n\n\nSection SIMMODSEM.\n\n  Context `{Σ: GRA.t}.\n  Context `{@GRA.inG Mem1.memRA Σ}.\n\n  (* Eval compute in (@RA.car (RA.excl Mem.t)). *)\n  Eval compute in (@URA.car Mem1._memRA).\n  Inductive sim_loc: URA.car (t:=(Excl.t _)) -> option val -> Prop :=\n  | sim_loc_present v: sim_loc (Some v) (Some v)\n  | sim_loc_absent: sim_loc ε None\n  .\n  Hint Constructors sim_loc: core.\n\n  Let W: Type := Any.t * Any.t.\n  (* Let wf: W -> Prop := *)\n  (*   @mk_wf *)\n  (*     _ *)\n  (*     Mem.t *)\n  (*     (fun mem_tgt _ mp_tgt => (∃ mem_src, (OwnM ((Auth.black mem_src): URA.car (t:=Mem1.memRA))) *)\n  (*                                            ** *)\n  (*                                            (⌜forall b ofs, sim_loc ((mem_tgt.(Mem.cnts)) b ofs) (mem_src b ofs)⌝) *)\n  (*                                            ** *)\n  (*                                            (⌜mp_tgt = mem_tgt↑ /\\ forall b ofs v, mem_tgt.(Mem.cnts) b ofs = Some v -> <<NB: b < mem_tgt.(Mem.nb)>>⌝) *)\n  (*                              )%I) *)\n  (*     top4 *)\n  (* . *)\n\n  Definition mem_wf (m0: Mem.t): Prop :=\n    forall b ofs v, m0.(Mem.cnts) b ofs = Some v -> <<NB: b < m0.(Mem.nb)>>\n  .\n\n  Let wf: _ -> W -> Prop :=\n    @mk_wf\n      _ unit\n      (fun _ _ _mem_tgt0 =>\n         (∃ (mem_tgt0: Mem.t) (memk_src0: URA.car (t:=Mem1._memRA)),\n             (⌜(<<TGT: _mem_tgt0 = mem_tgt0↑>>) /\\\n              (<<SIM: forall b ofs, sim_loc (memk_src0 b ofs) (mem_tgt0.(Mem.cnts) b ofs)>>) /\\\n              (<<WFTGT: mem_wf mem_tgt0>>)⌝) ∧ (*** TODO: put it inside Mem.t? ***)\n             (OwnM ((Auth.black memk_src0): URA.car (t:=Mem1.memRA)))\n         )%I)\n  .\n\n  Hint Resolve sim_itree_mon: paco.\n\n  Opaque URA.unit.\n\n  Ltac renamer :=\n    let tmp := fresh \"_tmp_\" in\n\n    match goal with\n    | H: context[OwnM (Auth.black ?x)] |- _ =>\n      rename x into tmp; let name := fresh \"memk_src0\" in rename tmp into name\n    end;\n\n    match goal with\n    | |- gpaco8 _ _ _ _ _ _ _ _ _ _ _ ((?mp_tgt↑), _) =>\n\n      repeat multimatch mp_tgt with\n             | context[?g] =>\n               match (type of g) with\n               | Mem.t =>\n                 rename g into tmp; let name := fresh \"mem_tgt0\" in rename tmp into name\n               | _ => fail\n               end\n             end\n    end\n  .\n\n  Variable csl: gname -> bool.\n\n  Theorem correct_modsem: forall sk, ModSemPair.sim (SModSem.to_tgt (to_stb [])\n                                           (Mem1.SMemSem (negb ∘ csl) sk)) (Mem0.MemSem csl sk).\n  Proof.\n   econstructor 1 with (wf:=wf) (le:=top2); et; swap 2 3.\n   { ss. }\n    { ss. eexists. econs; ss. eapply to_semantic.\n      iIntros \"H\". iSplits; ss; et.\n      { iPureIntro. ii. unfold Mem.load_mem, initial_mem_mr.\n        cbn. uo. des_ifs; et; try (by econs; et). }\n      { iPureIntro. ii. ss. uo. des_ifs.\n        apply nth_error_Some. ii. clarify. }\n    }\n\n\n\n\n\n    econs; ss.\n    { unfold allocF. init.\n      harg. fold wf. steps. hide_k. rename x into sz.\n      { mDesAll; ss. des; subst.\n        des_ifs_safe (mDesAll; ss). des; subst. clarify. rewrite Any.upcast_downcast in *. clarify.\n        steps. unhide_k. steps. des_ifs; clarify.\n        2:{ bsimpl; des; ss; apply sumbool_to_bool_false in Heq; try lia. }\n        steps. astart 0. astop.\n        renamer.\n        set (blk := mem_tgt0.(Mem.nb) + x).\n\n        mAssert _ with \"INV\" as \"INV\".\n        { iApply (OwnM_Upd with \"INV\").\n          eapply Auth.auth_alloc2.\n          instantiate (1:=(_points_to (blk, 0%Z) (repeat (Vundef) sz))).\n          mOwnWf \"INV\".\n          clear - WF0 WFTGT SIM.\n          ss. do 2 ur. ii. rewrite unfold_points_to. des_ifs.\n          - bsimpl. des. des_sumbool. subst. hexploit (SIM blk k0); et. intro T.\n            inv T; eq_closure_tac.\n            + exploit WFTGT; et. i; des. lia.\n            + rewrite URA.unit_idl. Ztac. rewrite repeat_length in *. rewrite Z.sub_0_r. rewrite repeat_nth_some; [|lia]. ur. ss.\n          - rewrite URA.unit_id. do 2 eapply lookup_wf. eapply Auth.black_wf; et.\n        }\n        mUpd \"INV\". mDesOwn \"INV\". steps.\n\n        force_l. eexists. steps. hret _; ss. iModIntro. iSplitR \"A\"; cycle 1.\n        { iSplitL; ss. iExists _. iSplitR; ss. }\n        iExists _, _. iSplitR; ss. iPureIntro. esplits; et.\n        - i. destruct (mem_tgt0.(Mem.cnts) blk ofs) eqn:T.\n          { exfalso. exploit WFTGT; et. i; des. lia. }\n          ss. do 2 ur.\n          exploit SIM; et. rewrite T. intro U. inv U. rewrite unfold_points_to. ss. rewrite repeat_length.\n          destruct (dec b blk); subst; ss.\n          * unfold update. des_ifs_safe. rewrite <- H1. rewrite URA.unit_idl.\n            rewrite Z.sub_0_r. rewrite Z.add_0_l. des_ifs.\n            { bsimpl. des. Ztac. rewrite repeat_nth_some; try lia. econs. }\n          * rewrite URA.unit_id. unfold update. des_ifs.\n        - clear - WFTGT. ii. ss. unfold update in *. des_ifs. exploit WFTGT; et. i; des. r. lia.\n      }\n    }\n\n\n\n\n\n    econs; ss.\n    { unfold freeF. init.\n      harg. fold wf. steps. hide_k.\n      { des_ifs_safe (mDesAll; ss). des; subst.\n        des_ifs; mDesAll; ss. des; subst. clarify. rewrite Any.upcast_downcast in *. clarify.\n        steps. unhide_k. steps. astart 0. astop.\n        renamer. rename n into b. rename z into ofs.\n        rename a into v. rename WF into SIMWF.\n        mCombine \"INV\" \"A\". mOwnWf \"INV\".\n        assert(HIT: memk_src0 b ofs = (Some v)).\n        { clear - WF.\n          dup WF. eapply Auth.auth_included in WF. des. eapply pw_extends in WF. eapply pw_extends in WF.\n          spc WF. rewrite _points_to_hit in WF.\n          eapply Excl.extends in WF; ss. do 2 eapply lookup_wf. eapply Auth.black_wf. eapply URA.wf_mon; et.\n        }\n        set (memk_src1 := fun _b _ofs => if dec _b b && dec _ofs ofs\n                                         then (ε: URA.car (t:=Excl.t _)) else memk_src0 _b _ofs).\n        assert(WF': URA.wf (memk_src1: URA.car (t:=Mem1._memRA))).\n        { clear - WF. unfold memk_src1. do 2 ur. ii. eapply URA.wf_mon in WF. ur in WF. des.\n          des_ifs; et.\n          - rp; [eapply URA.wf_unit|ss].\n          - do 2 eapply lookup_wf; et.\n        }\n        hexploit (SIM b ofs); et. rewrite HIT. intro B. inv B.\n        force_r.\n        { unfold Mem.free in *. des_ifs. }\n        rename t into mem_tgt1.\n\n        mAssert _ with \"INV\" as \"INV\".\n        { iApply (OwnM_Upd with \"INV\").\n          Local Transparent points_to.\n          eapply Auth.auth_dealloc.\n          instantiate (1:=memk_src1).\n          clear - WF'.\n\n          r. i. rewrite URA.unit_idl.\n          Local Opaque Mem1._memRA.\n          ss. destruct H; clear H. (*** coq bug; des infloops ***) des. clarify.\n          esplits; et.\n          Local Transparent Mem1._memRA.\n          unfold memk_src1. ss.\n          apply func_ext. intro _b. apply func_ext. intro _ofs.\n          des_ifs.\n          - bsimpl; des; des_sumbool; subst.\n            subst memk_src1. do 2 ur in WF'. do 2 spc WF'. des_ifs; bsimpl; des; des_sumbool; ss.\n            clear - H0.\n            do 2 ur in H0.\n            specialize (H0 b ofs). rewrite _points_to_hit in H0. eapply Excl.wf in H0. des; ss.\n          - rewrite unfold_points_to in *. do 2 ur. do 2 ur in H0.\n            bsimpl. des_ifs; bsimpl; des; des_sumbool; subst; Ztac; try lia; try rewrite URA.unit_idl; try refl.\n        }\n        mUpd \"INV\".\n        steps. force_l. eexists. steps. hret _; ss. iModIntro. iSplitL; cycle 1.\n        { iPureIntro. ss. }\n        iExists _, _. iSplitR \"INV\"; et. iPureIntro. esplits; ss; et.\n        - { i. unfold Mem.free in _UNWRAPU. des_ifs. ss.\n            subst memk_src1. ss.\n            destruct (classic (b = b0 /\\ ofs = ofs0)); des; clarify.\n            - unfold update. des_ifs.\n            - des_ifs.\n              { Psimpl. bsimpl; des; des_sumbool; ss; clarify. }\n              replace (update (Mem.cnts mem_tgt0) b (update (Mem.cnts mem_tgt0 b) ofs None) b0 ofs0) with\n                  (Mem.cnts mem_tgt0 b0 ofs0); cycle 1.\n              { unfold update. des_ifs. Psimpl. des_ifs; bsimpl; des; des_sumbool; ss; clarify. }\n              et.\n          }\n        - clear - _UNWRAPU WFTGT. ii. unfold Mem.free in *. des_ifs. ss.\n          unfold update in *. des_ifs; eapply WFTGT; et.\n      }\n    }\n\n\n\n\n\n    econs; ss.\n    { unfold loadF. init.\n      harg. fold wf. steps. hide_k.\n      { des_ifs_safe (mDesAll; ss). des; subst. clarify. rewrite Any.upcast_downcast in *. clarify.\n        steps. unhide_k. steps. astart 0. astop.\n        renamer. rename n into b. rename z into ofs.\n        rename WF into SIMWF.\n        mCombine \"INV\" \"A\". mOwnWf \"INV\".\n        assert(T: memk_src0 b ofs = (Some v)).\n        { clear - WF.\n          dup WF.\n          eapply Auth.auth_included in WF. des.\n          eapply pw_extends in WF. eapply pw_extends in WF. spc WF. rewrite _points_to_hit in WF. des; ss.\n          eapply Excl.extends in WF; ss. do 2 eapply lookup_wf. eapply Auth.black_wf. eapply URA.wf_mon; et.\n        }\n        hexploit SIM; et. intro U. rewrite T in U. inv U; ss. unfold Mem.load.\n        mDesOwn \"INV\".\n        force_r; ss. clarify. steps. force_l. esplits. steps.\n        hret _; ss. iModIntro. iFrame. iSplitL; et.\n      }\n    }\n\n\n\n\n\n    econs; ss.\n    { unfold storeF. init.\n      harg. fold wf. steps. hide_k.\n      { des_ifs_safe (mDesAll; ss). des; subst. clarify. rewrite Any.upcast_downcast in *. clarify.\n        steps. unhide_k. steps. astart 0. astop.\n        renamer.\n        rename n into b. rename z into ofs. rename v into v1.\n        rename a into v0. rename WF into SIMWF.\n        steps.\n        mCombine \"INV\" \"A\". mOwnWf \"INV\".\n        assert(T: memk_src0 b ofs = (Some v0)).\n        { clear - WF.\n          dup WF.\n          eapply Auth.auth_included in WF. des.\n          eapply pw_extends in WF. eapply pw_extends in WF. spc WF. rewrite _points_to_hit in WF.\n          des; ss.\n          eapply Excl.extends in WF; ss. do 2 eapply lookup_wf. eapply Auth.black_wf. eapply URA.wf_mon; et.\n        }\n        hexploit SIM; et. intro U. rewrite T in U. inv U; ss. unfold Mem.store. des_ifs. steps.\n        set (memk_src1 := fun _b _ofs => if dec _b b && dec _ofs ofs then (Some v1: URA.car (t:=Excl.t _)) else memk_src0 _b _ofs).\n        assert(WF': URA.wf (memk_src1: URA.car (t:=Mem1._memRA))).\n        { clear - WF. unfold memk_src1. do 2 ur. ii. eapply URA.wf_mon in WF. ur in WF. des.\n          des_ifs; et.\n          - bsimpl; des; des_sumbool; subst. ur; ss.\n          - do 2 eapply lookup_wf; et.\n        }\n        mAssert _ with \"INV\" as \"INV\".\n        { iApply (OwnM_Upd with \"INV\").\n          eapply Auth.auth_update with (a':=memk_src1) (b':=_points_to (b, ofs) [v1]); et.\n          clear - wf WF'. ii. des. subst. esplits; et.\n          do 2 ur in WF'. do 2 spc WF'.\n          subst memk_src1. ss. des_ifs; bsimpl; des; des_sumbool; ss.\n          do 2 ur. do 2 (apply func_ext; i). des_ifs.\n          - bsimpl; des; des_sumbool; subst. rewrite _points_to_hit.\n            do 2 ur in WF. do 2 spc WF. rewrite _points_to_hit in WF. eapply Excl.wf in WF. rewrite WF. ur; ss.\n          - bsimpl; des; des_sumbool; rewrite ! _points_to_miss; et.\n        }\n        mUpd \"INV\". mDesOwn \"INV\".\n\n        mEval ltac:(fold (points_to (b,ofs) [v1])) in \"A\".\n        force_l. eexists. steps.\n        hret _; ss. iModIntro. iFrame. iSplitL; ss; et.\n        iExists _, _. iSplitR \"INV\"; et. iPureIntro. esplits; ss; et.\n        - ii. cbn. des_ifs.\n          + bsimpl; des; des_sumbool; subst. do 2 spc SIM. rewrite T in *. inv SIM.\n            unfold memk_src1. rewrite ! dec_true; ss. econs.\n          + replace (memk_src1 b0 ofs0) with (memk_src0 b0 ofs0); et.\n            unfold memk_src1. des_ifs; bsimpl; des; des_sumbool; clarify; ss.\n        - ii. ss. des_ifs.\n          + bsimpl; des; des_sumbool; subst. eapply WFTGT; et.\n          + eapply WFTGT; et.\n      }\n    }\n\n\n\n\n\n    econs; ss.\n    { unfold cmpF. init.\n      harg. fold wf. steps. hide_k.\n      { des_ifs_safe (mDesAll; ss). des; subst. clarify.\n        steps. unhide_k. steps. astart 0. astop.\n        renamer.\n        rename b into result. rename c into resource. rename WF into SIMWF.\n        assert (VALIDPTR: forall b ofs v (WF: URA.wf ((Auth.black (memk_src0: URA.car (t:=Mem1._memRA))) ⋅ ((b, ofs) |-> [v]))),\n                   Mem.valid_ptr mem_tgt0 b ofs = true).\n        { clear - SIM. i. cut (memk_src0 b ofs = Some v).\n          - i. unfold Mem.valid_ptr.\n            specialize (SIM b ofs). rewrite H in *. inv SIM. ss.\n          - clear - WF.\n            dup WF.\n            eapply Auth.auth_included in WF. des.\n            eapply pw_extends in WF. eapply pw_extends in WF. spc WF. rewrite _points_to_hit in WF.\n            des; ss.\n            eapply Excl.extends in WF; ss. do 2 eapply lookup_wf. eapply Auth.black_wf. eapply URA.wf_mon; et.\n        }\n        steps.\n        mCombine \"INV\" \"A\". mOwnWf \"INV\". Fail mDesOwn \"INV\". (*** TODO: BUG!! FIXME ***)\n\n        mDesOr \"PRE\".\n        { mDesAll; subst. rewrite Any.upcast_downcast in *. clarify. steps.\n          erewrite VALIDPTR; et. ss. steps.\n          force_l. eexists. steps. hret _; ss. iModIntro. iDestruct \"INV\" as \"[INV A]\". iSplitR \"A\"; ss; et.\n        }\n        mDesOr \"PRE\".\n        { mDesAll; subst. rewrite Any.upcast_downcast in *. clarify. steps.\n          erewrite VALIDPTR; et. ss. steps.\n          force_l. eexists. steps. hret _; ss. iModIntro. iDestruct \"INV\" as \"[INV A]\". iSplitR \"A\"; ss; et.\n        }\n        mDesOr \"PRE\".\n        { mDesAll; subst. rewrite Any.upcast_downcast in *. clarify. steps.\n          erewrite VALIDPTR; et; cycle 1.\n          { rewrite URA.add_assoc in WF. eapply URA.wf_mon in WF; et. }\n          erewrite VALIDPTR; et; cycle 1.\n          { erewrite URA.add_comm with (a:=(a, a0) |-> [a1]) in WF.\n            rewrite URA.add_assoc in WF. eapply URA.wf_mon in WF; et. }\n          rewrite URA.add_comm in WF. eapply URA.wf_mon in WF. ur in WF; ss. steps.\n          replace (dec a a2 && dec a0 a3 ) with false; cycle 1.\n          { clear - WF.\n            exploit _points_to_disj; et. intro NEQ. des; try (by rewrite dec_false; ss).\n            erewrite dec_false with (x0:=a0); ss. rewrite andb_false_r; ss.\n          }\n          steps. force_l. eexists. steps. hret _; ss. iModIntro. iDestruct \"INV\" as \"[INV A]\". iSplitR \"A\"; ss; et.\n        }\n        mDesOr \"PRE\".\n        { mDesAll; subst. rewrite Any.upcast_downcast in *. clarify. steps.\n          erewrite VALIDPTR; et. ss. steps. rewrite ! dec_true; ss. steps.\n          force_l. eexists. steps. hret _; ss. iModIntro. iDestruct \"INV\" as \"[INV A]\". iSplitR \"A\"; ss; et.\n        }\n        { mDesAll; subst. des; subst. rewrite Any.upcast_downcast in *. clarify. steps.\n          force_l. eexists. steps. hret _; ss. iModIntro. iDestruct \"INV\" as \"[INV A]\". iSplitR \"A\"; ss; et.\n        }\n      }\n    }\n  Unshelve.\n    all: ss. all: try exact 0.\n  Qed.\n\n  Theorem correct: refines2 [Mem0.Mem csl] [Mem1.Mem (negb ∘ csl)].\n  Proof.\n    eapply adequacy_local2. econs; ss; et. i. eapply correct_modsem.\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/mem/Mem01proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.29306200289275647}}
{"text": "(* begin hide *)\nFrom mathcomp Require Import all_ssreflect.\n(* Set Implicit Arguments. *)\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nFrom Equations Require Import Equations.\n\n(* end hide *)\n\n(**\n   #<div class=\"jumbotron\">\n      <div class=\"container\">\n        <h1 class=\"display-4\">Values</h1>\n        <p class=\"lead\">\n         This file contains the definition of values used throughout the rest of the \n         project, in graphs and queries.\n        </p>\n         \n  </div>\n</div>#\n *)\n\nSection Value.\n\n  Variable (Scalar : eqType).\n\n  (* Unsetting because the automatically generated induction principle is not good enough. *)\n  Unset Elimination Schemes.\n\n  (** ---- *)\n  (**\n     Values are not specified in the Spec, since GraphQL is agnostic to the underlying technology\n     used. However, it is still possible to distinguish (at least) two types of values: \n     - Scalar values\n     - List values (collections)\n\n     A third possible type of value could be object values but we do not include this notion yet\n     (nodes in a graph would represent elements of this third kind).\n\n   *)\n  Inductive Value : Type :=\n  | SValue : Scalar -> Value\n  | LValue : seq Value -> Value.\n\n  Set Elimination Schemes.\n\n   \n  (** ---- *)\n  (**\n     Defining the induction principle for [Value].\n   *)\n  Definition Value_rect (P : Value -> Type)\n             (Pl : seq Value -> Type)\n             (IH_SValue : forall s, P (SValue s))\n             (IH_LValue : forall vs, Pl vs -> P (LValue vs))\n             (IH_Nil : Pl [::])\n             (IH_Cons : forall v, P v -> forall vs, Pl vs -> Pl (v :: vs))\n    :=\n    fix loop value : P value :=\n      let fix F (qs : seq Value) : Pl qs :=\n          match qs with\n          | [::] => IH_Nil\n          | hd :: tl => IH_Cons hd (loop hd) tl (F tl)\n          end\n      in\n      match value with\n      | SValue s => IH_SValue s\n      | LValue vs => IH_LValue vs (F vs)\n      end.\n\n  Definition Value_rec (P : Value -> Set) := @Value_rect P.\n\n  Definition Value_ind (P : Value -> Prop)\n             (Pl : seq Value -> Prop)\n             (IH_SValue : forall s, P (SValue s))\n             (IH_LValue : forall vs, Pl vs -> P (LValue vs))\n             (IH_Nil : Pl [::])\n             (IH_Cons : forall v, P v -> forall vs, Pl vs -> Pl (v :: vs))\n    :=\n      fix loop value : P value :=\n        let fix F (qs : seq Value) : Pl qs :=\n          match qs with\n          | [::] => IH_Nil\n          | hd :: tl => IH_Cons hd (loop hd) tl (F tl)\n          end\n        in\n        match value with\n        | SValue s => IH_SValue s\n        | LValue vs => IH_LValue vs (F vs)\n        end.\n\n\n  (**\n     We also establish that this type has a decidable procedure for equality but \n     we omit it here to unclutter the doc (it may still be seen in the source code).\n   *)\n\n  (* begin hide *)\n  (** ---- *)\n  (**\n     #<strong></strong>#: Value → Value → Bool\n\n     Decidable equality between values. \n   *)\n  Equations value_eq (v1 v2 : Value) : bool :=\n    {\n      value_eq (SValue s1) (SValue s2) := s1 == s2;\n      value_eq (LValue vs1) (LValue vs2) := value_seq_eq vs1 vs2;\n      value_eq _ _ := false\n    }\n  where value_seq_eq (vs1 vs2 : seq Value) : bool :=\n          {\n            value_seq_eq [::] [::] := true;\n            value_seq_eq (v1 :: vs1) (v2 :: vs2) := value_eq v1 v2 && value_seq_eq vs1 vs2;\n            value_seq_eq _ _ := false\n          }.\n  \n  (** ---- **)\n  (**\n     Reflexive lemma for [value_eq] and [eq].\n   *)\n  Lemma value_eq_axiom : Equality.axiom value_eq.\n  Proof.\n    rewrite /Equality.axiom => x y.                 \n    apply: (iffP idP) => [| ->]; last first.\n    - elim y using Value_ind with (Pl := fun vs1 => value_seq_eq vs1 vs1); intros; simp value_eq => //; apply/andP; split=> //.\n\n    - move: y; elim x using Value_ind with\n                   (Pl := fun vs1 => forall vs2, value_seq_eq vs1 vs2 -> vs1 = vs2) => [s | vs IHvs | | v IHv vs IHvs]; case=> //=.\n      * by move=> s2; simp value_eq => /eqP ->.\n      * by move=> vs2; simp value_eq => Hvseq; rewrite (IHvs vs2).\n      * by move=> v2 vs2 /andP [/IHv -> /IHvs ->].\n  Qed.\n  \n  Canonical value_eqType := EqType Value (EqMixin value_eq_axiom).\n  \n  (* end hide *)\n  \nEnd Value.\n\nArguments Value [Scalar].\nArguments SValue [Scalar].\nArguments LValue [Scalar].\n\n\n\n(** #<a href='GraphCoQL.Schema.html' class=\"btn btn-info\" role='button'>Continue Reading → Schema </a># *)", "meta": {"author": "imfd", "repo": "GraphCoQL", "sha": "681edcdcdf982151f4d1f74bb2a42f15b527317c", "save_path": "github-repos/coq/imfd-GraphCoQL", "path": "github-repos/coq/imfd-GraphCoQL/GraphCoQL-681edcdcdf982151f4d1f74bb2a42f15b527317c/src/Value.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2929222216335438}}
{"text": "Require Import Crypto.Compilers.Syntax.\nRequire Import Crypto.Compilers.TypeInversion.\nRequire Import Crypto.Util.Sigma.\nRequire Import Crypto.Util.Option.\nRequire Import Crypto.Util.Prod.\nRequire Import Crypto.Util.Tactics.DestructHead.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nRequire Import Crypto.Util.Notations.\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\n  Local Notation flat_type := (flat_type base_type_code).\n  Local Notation type := (type base_type_code).\n  Local Notation interp_type := (interp_type interp_base_type).\n  Local Notation interp_flat_type_gen := interp_flat_type.\n  Local Notation interp_flat_type := (interp_flat_type interp_base_type).\n  Local Notation Expr := (@Expr base_type_code op).\n\n  Section with_var.\n    Context {var : base_type_code -> Type}.\n\n    Local Notation exprf := (@exprf base_type_code op var).\n    Local Notation expr := (@expr base_type_code op var).\n\n    Definition invert_Var {t} (e : exprf (Tbase t)) : option (var t)\n      := match e in Syntax.exprf _ _ t'\n               return option (var match t' with\n                                  | Tbase t' => t'\n                                  | _ => t\n                                  end)\n         with\n         | Var _ v => Some v\n         | _ => None\n         end.\n    Definition invert_Op {t} (e : exprf t) : option { t1 : flat_type & op t1 t * exprf t1 }%type\n      := match e with Op _ _ opc args => Some (existT _ _ (opc, args)) | _ => None end.\n    Definition invert_LetIn {A} (e : exprf A) : option { B : _ & exprf B * (Syntax.interp_flat_type var B -> exprf A) }%type\n      := match e in Syntax.exprf _ _ t return option { B : _ & _ * (_ -> exprf t) }%type with\n         | LetIn _ ex _ eC => Some (existT _ _ (ex, eC))\n         | _ => None\n         end.\n    Definition invert_Pair {A B} (e : exprf (Prod A B)) : option (exprf A * exprf B)\n      := match e in Syntax.exprf _ _ t\n               return option match t with\n                             | Prod _ _ => _\n                             | _ => unit\n                             end with\n         | Pair _ x _ y => Some (x, y)%core\n         | _ => None\n         end.\n    Definition invert_Abs {T} (e : expr T) : interp_flat_type_gen var (domain T) -> exprf (codomain T)\n      := match e with Abs _ _ f => f end.\n\n    Section const.\n      Context (invert_Const : forall s d, op s d -> exprf s -> option (interp_flat_type d)).\n\n      Fixpoint lift_option {t} : interp_flat_type t -> interp_flat_type_gen (fun t => option (interp_base_type t)) t\n        := match t with\n           | Tbase T => fun x => Some x\n           | Unit => fun _ => tt\n           | Prod A B => fun (ab : interp_flat_type A * interp_flat_type B)\n                         => let '(a, b) := ab in\n                            (lift_option a, lift_option b)\n           end.\n\n      Fixpoint invert_PairsConst_gen {T} (e : exprf T)\n        : option (interp_flat_type_gen (fun t => option (interp_base_type t)) T)\n      := match e in Syntax.exprf _ _ t return option (interp_flat_type_gen (fun t => option (interp_base_type t)) t) with\n         | TT => Some tt\n         | Pair tx ex ty ey\n           => match @invert_PairsConst_gen tx ex, @invert_PairsConst_gen ty ey with\n              | Some x, Some y => Some (x, y)\n              | Some _, None | None, Some _ | None, None => None\n              end\n         | Op s d opv args\n           => option_map lift_option (invert_Const s d opv args)\n         | Var _ _\n         | LetIn _ _ _ _\n           => None\n         end.\n      Fixpoint invert_PairsConst {T} (e : exprf T)\n        : option (interp_flat_type T)\n      := match e in Syntax.exprf _ _ t return option (interp_flat_type t) with\n         | TT => Some tt\n         | Pair tx ex ty ey\n           => match @invert_PairsConst tx ex, @invert_PairsConst ty ey with\n              | Some x, Some y => Some (x, y)\n              | Some _, None | None, Some _ | None, None => None\n              end\n         | Op s d opv args\n           => invert_Const s d opv args\n         | Var _ _\n         | LetIn _ _ _ _\n           => None\n         end.\n    End const.\n\n    Fixpoint invert_Pairs {T} (e : exprf T) : option (interp_flat_type_gen (fun ty => exprf (Tbase ty)) T)\n      := match e in Syntax.exprf _ _ t\n               return option (interp_flat_type_gen (fun ty => exprf (Tbase ty)) t)\n         with\n         | TT => Some tt\n         | Var t _ as e => Some e\n         | Pair tx ex ty ey\n           => match @invert_Pairs tx ex, @invert_Pairs ty ey with\n              | Some x, Some y => Some (x, y)\n              | Some _, None | None, Some _ | None, None => None\n              end\n         | Op _ t _ _ as e\n         | LetIn _ _ t _ as e\n           => match t return exprf t -> option (interp_flat_type_gen _ t) with\n              | Tbase _ => fun e => Some e\n              | _ => fun _ => None\n              end e\n         end.\n\n    Definition compose {A B C} (f : expr (B -> C)) (g : expr (A -> B))\n      : expr (A -> C)\n      := Abs (fun v => LetIn (invert_Abs g v)\n                             (invert_Abs f)).\n\n    Definition exprf_code {t} (e : exprf t) : exprf t -> Prop\n      := match e with\n         | TT => fun e' => TT = e'\n         | Var _ v => fun e' => invert_Var e' = Some v\n         | Pair _ x _ y => fun e' => invert_Pair e' = Some (x, y)%core\n         | Op _ _ opc args => fun e' => invert_Op e' = Some (existT _ _ (opc, args)%core)\n         | LetIn _ ex _ eC => fun e' => invert_LetIn e' = Some (existT _ _ (ex, eC)%core)\n         end.\n\n    Definition expr_code {t} (e1 e2 : expr t) : Prop\n      := invert_Abs e1 = invert_Abs e2.\n\n    Definition exprf_encode {t} (x y : exprf t) : x = y -> exprf_code x y.\n    Proof. intro p; destruct p, x; reflexivity. Defined.\n    Definition expr_encode {t} (x y : expr t) : x = y -> expr_code x y.\n    Proof. intro p; destruct p, x; reflexivity. Defined.\n\n    Local Ltac t' :=\n      repeat first [ intro\n                   | progress simpl in *\n                   | reflexivity\n                   | assumption\n                   | progress destruct_head False\n                   | progress subst\n                   | progress inversion_option\n                   | progress inversion_sigma\n                   | progress break_match ].\n    Local Ltac t :=\n      lazymatch goal with\n      | [ |- _ = Some ?v -> ?e = _ ]\n        => revert v;\n           refine match e with\n                  | Var _ _ => _\n                  | _ => _\n                  end\n      | [ |- _ = ?v -> ?e = _ ]\n        => revert v;\n           refine match e with\n                  | Abs _ _ _ => _\n                  end\n      end;\n      t'.\n\n    Lemma invert_Var_Some {t e v}\n      : @invert_Var t e = Some v -> e = Var v.\n    Proof. t. Defined.\n\n    Lemma invert_Op_Some {t e v}\n      : @invert_Op t e = Some v -> e = Op (fst (projT2 v)) (snd (projT2 v)).\n    Proof. t. Defined.\n\n    Lemma invert_LetIn_Some {t e v}\n      : @invert_LetIn t e = Some v -> e = LetIn (fst (projT2 v)) (snd (projT2 v)).\n    Proof. t. Defined.\n\n    Lemma invert_Pair_Some {A B e v}\n      : @invert_Pair A B e = Some v -> e = Pair (fst v) (snd v).\n    Proof. t. Defined.\n\n    Lemma invert_Abs_Some {A B e v}\n      : @invert_Abs (Arrow A B) e = v -> e = Abs v.\n    Proof. t. Defined.\n\n    Definition exprf_decode {t} (x y : exprf t) : exprf_code x y -> x = y.\n    Proof.\n      destruct x; simpl; trivial;\n        intro H;\n        first [ apply invert_Var_Some in H\n              | apply invert_Op_Some in H\n              | apply invert_LetIn_Some in H\n              | apply invert_Pair_Some in H ];\n        symmetry; assumption.\n    Defined.\n    Definition expr_decode {t} (x y : expr t) : expr_code x y -> x = y.\n    Proof.\n      destruct x; unfold expr_code; simpl.\n      intro H; symmetry in H.\n      apply invert_Abs_Some in H.\n      symmetry; assumption.\n    Defined.\n    Definition path_exprf_rect {t} {x y : exprf t} (Q : x = y -> Type)\n               (f : forall p, Q (exprf_decode x y p))\n      : forall p, Q p.\n    Proof. intro p; specialize (f (exprf_encode x y p)); destruct x, p; exact f. Defined.\n    Definition path_expr_rect {t} {x y : expr t} (Q : x = y -> Type)\n               (f : forall p, Q (expr_decode x y p))\n      : forall p, Q p.\n    Proof. intro p; specialize (f (expr_encode x y p)); destruct x, p; exact f. Defined.\n  End with_var.\n\n  Lemma interpf_invert_Abs interp_op {T e} x\n    : Syntax.interpf interp_op (@invert_Abs interp_base_type T e x)\n      = Syntax.interp interp_op e x.\n  Proof using Type. destruct e; reflexivity. Qed.\n\n  Lemma interpf_invert_PairsConst invert_Const interp_op {T} e v\n        (Hinvert_Const\n         : forall s d opc e v, invert_Const s d opc e = Some v\n                               -> interp_op s d opc (interpf interp_op e) = v)\n        (H : invert_PairsConst (T:=T) invert_Const e = Some v)\n    : Syntax.interpf interp_op e = v.\n  Proof using Type.\n    induction e;\n      repeat first [ reflexivity\n                   | progress subst\n                   | solve [ auto ]\n                   | progress inversion_option\n                   | progress inversion_prod\n                   | progress simpl in *\n                   | progress break_innermost_match_hyps\n                   | apply (f_equal2 (@pair _ _)) ].\n  Qed.\n\n  Definition Compose {A B C} (f : Expr (B -> C)) (g : Expr (A -> B))\n    : Expr (A -> C)\n    := fun var => compose (f var) (g var).\n\n  Lemma InterpCompose {A B C} interp_op f g\n    : forall x, Interp interp_op (@Compose A B C f g) x\n                = Interp interp_op f (Interp (interp_base_type:=interp_base_type) interp_op g x).\n  Proof. reflexivity. Qed.\nEnd language.\n\nGlobal Arguments invert_Var {_ _ _ _} _.\nGlobal Arguments invert_Op {_ _ _ _} _.\nGlobal Arguments invert_LetIn {_ _ _ _} _.\nGlobal Arguments invert_Pair {_ _ _ _ _} _.\nGlobal Arguments invert_Pairs {_ _ _ _} _.\nGlobal Arguments invert_PairsConst {_ _ _ _} _ {T} _.\nGlobal Arguments invert_Abs {_ _ _ _} _ _.\n\nHint Rewrite @InterpCompose : reflective_rewrite.\n\nModule Export Notations.\n  Infix \"∘\" := Compose : expr_scope.\n  Infix \"∘f\" := compose : expr_scope.\n  Infix \"∘ᶠ\" := compose : expr_scope.\nEnd Notations.\n\nLtac invert_one_expr e :=\n  preinvert_one_type e;\n  intros ? e;\n  destruct e;\n  try exact I.\n\nLtac invert_expr_step :=\n  match goal with\n  | [ e : exprf _ _ (Tbase _) |- _ ] => invert_one_expr e\n  | [ e : exprf _ _ (Prod _ _) |- _ ] => invert_one_expr e\n  | [ e : exprf _ _ Unit |- _ ] => invert_one_expr e\n  | [ e : expr _ _ (Arrow _ _) |- _ ] => invert_one_expr e\n  end.\n\nLtac invert_expr := repeat invert_expr_step.\n\nLtac invert_match_expr_step :=\n  match goal with\n  | [ |- context[match ?e with TT => _ | _ => _ end] ]\n    => invert_one_expr e\n  | [ |- context[match ?e with Abs _ _ _ => _ end] ]\n    => invert_one_expr e\n  | [ H : context[match ?e with TT => _ | _ => _ end] |- _ ]\n    => invert_one_expr e\n  | [ H : context[match ?e with Abs _ _ _ => _ end] |- _ ]\n    => invert_one_expr e\n  end.\n\nLtac invert_match_expr := repeat invert_match_expr_step.\n\nLtac invert_expr_subst_step_helper guard_tac :=\n  match goal with\n  | [ H : invert_Var ?e = Some _ |- _ ] => guard_tac H; apply invert_Var_Some in H\n  | [ H : invert_Op ?e = Some _ |- _ ] => guard_tac H; apply invert_Op_Some in H\n  | [ H : invert_LetIn ?e = Some _ |- _ ] => guard_tac H; apply invert_LetIn_Some in H\n  | [ H : invert_Pair ?e = Some _ |- _ ] => guard_tac H; apply invert_Pair_Some in H\n  | [ e : expr _ _ _ |- _ ]\n    => guard_tac e;\n       let f := fresh e in\n       let H := fresh in\n       rename e into f;\n       remember (invert_Abs f) as e eqn:H;\n       symmetry in H;\n       apply invert_Abs_Some in H;\n       subst f\n  | [ H : invert_Abs ?e = _ |- _ ] => guard_tac H; apply invert_Abs_Some in H\n  end.\nLtac invert_expr_subst_step :=\n  first [ invert_expr_subst_step_helper ltac:(fun _ => idtac)\n        | subst ].\nLtac invert_expr_subst := repeat invert_expr_subst_step.\n\nLtac induction_expr_in_using H rect :=\n  induction H as [H] using (rect _ _ _);\n  cbv [exprf_code expr_code invert_Var invert_LetIn invert_Pair invert_Op invert_Abs] in H;\n  try lazymatch type of H with\n      | Some _ = Some _ => apply option_leq_to_eq in H; unfold option_eq in H\n      | Some _ = None => exfalso; clear -H; solve [ inversion H ]\n      | None = Some _ => exfalso; clear -H; solve [ inversion H ]\n      end;\n  let H1 := fresh H in\n  let H2 := fresh H in\n  try lazymatch type of H with\n      | existT _ _ _ = existT _ _ _ => induction_sigma_in_using H @path_sigT_rect\n      end;\n  try lazymatch type of H2 with\n      | _ = (_, _)%core => induction_path_prod H2\n      end.\nLtac inversion_expr_step :=\n  match goal with\n  | [ H : _ = Var _ |- _ ]\n    => induction_expr_in_using H @path_exprf_rect\n  | [ H : _ = TT |- _ ]\n    => induction_expr_in_using H @path_exprf_rect\n  | [ H : _ = Op _ _ |- _ ]\n    => induction_expr_in_using H @path_exprf_rect\n  | [ H : _ = Pair _ _ |- _ ]\n    => induction_expr_in_using H @path_exprf_rect\n  | [ H : _ = LetIn _ _ |- _ ]\n    => induction_expr_in_using H @path_exprf_rect\n  | [ H : _ = Abs _ |- _ ]\n    => induction_expr_in_using H @path_expr_rect\n  | [ H : Var _ = _ |- _ ]\n    => induction_expr_in_using H @path_exprf_rect\n  | [ H : TT = _ |- _ ]\n    => induction_expr_in_using H @path_exprf_rect\n  | [ H : Op _ _ = _ |- _ ]\n    => induction_expr_in_using H @path_exprf_rect\n  | [ H : Pair _ _ = _ |- _ ]\n    => induction_expr_in_using H @path_exprf_rect\n  | [ H : LetIn _ _ = _ |- _ ]\n    => induction_expr_in_using H @path_exprf_rect\n  | [ H : Abs _ = _ |- _ ]\n    => induction_expr_in_using H @path_expr_rect\n  end.\nLtac inversion_expr := repeat inversion_expr_step.\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/ExprInversion.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2929222216335438}}
{"text": "(** * Definition of minimal parse trees *)\nRequire Import Coq.Strings.String Coq.Lists.List Coq.Setoids.Setoid.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.Reachable.MaybeEmpty.Core.\nRequire Import Fiat.Parsers.BaseTypes.\n\nLocal Coercion is_true : bool >-> Sortclass.\n\nSet Implicit Arguments.\nLocal Open Scope string_like_scope.\n\nSection cfg.\n  Context {Char} {HSLM : StringLikeMin Char} {G : grammar Char}.\n  Context {predata : @parser_computational_predataT Char}\n          {rdata' : @parser_removal_dataT' _ G predata}.\n\n  Inductive minimal_maybe_empty_productions : nonterminals_listT -> productions Char -> Type :=\n  | MinMaybeEmptyHead : forall valid pat pats, minimal_maybe_empty_production valid pat\n                                               -> minimal_maybe_empty_productions valid (pat::pats)\n  | MinMaybeEmptyTail : forall valid pat pats, minimal_maybe_empty_productions valid pats\n                                               -> minimal_maybe_empty_productions valid (pat::pats)\n  with minimal_maybe_empty_production : nonterminals_listT -> production Char -> Type :=\n  | MinMaybeEmptyProductionNil : forall valid, minimal_maybe_empty_production valid nil\n  | MinMaybeEmptyProductionCons : forall valid it its, minimal_maybe_empty_item valid it\n                                                       -> minimal_maybe_empty_production valid its\n                                                       -> minimal_maybe_empty_production valid (it::its)\n  with minimal_maybe_empty_item : nonterminals_listT -> item Char -> Type :=\n  | MinMaybeEmptyNonTerminal : forall valid nt, is_valid_nonterminal valid (of_nonterminal nt)\n                                                -> minimal_maybe_empty_productions (remove_nonterminal valid (of_nonterminal nt)) (Lookup G nt)\n                                                -> minimal_maybe_empty_item valid (NonTerminal nt).\n\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/Reachable/MaybeEmpty/Minimal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5039061705290806, "lm_q1q2_score": 0.2929222143232949}}
{"text": "From stdpp Require Import namespaces.\nFrom iris.base_logic Require Import invariants na_invariants.\nFrom self.prob_lang Require Import notation proofmode primitive_laws spec_rules spec_tactics.\nFrom self.logrel Require Import model rel_rules rel_tactics.\nFrom iris.algebra Require Import auth gmap excl frac agree.\nFrom self.prelude Require Import base.\nFrom self.examples Require Import keyed_hash hash rng.\n\nSet Default Proof Using \"Type*\".\n\n(* A \"splittable\" pseudo-random number generator derived from a keyed\n   hashing function.\n\n   The idea is to be able to generate a collection of separate independent RNGs from a single keyed hash\n   by having each RNG use a different key.\n\n   Compare with rng.v, which generates a single rng from a hash function.\n\n*)\n\n\nSection rng.\n\n  Context (MAX_RNGS_POW : nat).\n  Context (MAX_SAMPLES_POW : nat).\n\n  Definition MAX_RNGS : nat := (Nat.pow 2 MAX_RNGS_POW) - 1.\n  Definition MAX_SAMPLES : nat := (Nat.pow 2 MAX_SAMPLES_POW) - 1.\n\n  Definition init_rng_gen : val :=\n    λ: \"_\",\n      let: \"f\" := (init_keyed_hash MAX_RNGS_POW MAX_SAMPLES_POW) #() in\n      let: \"key_cntr\" := ref #0 in\n      (* We return an rng \"generator\" that gets a fresh key from key_cntr (if available) and returns\n         an rng function using that key *)\n      λ: \"_\",\n        let: \"k\" := !\"key_cntr\" in\n        if: #MAX_RNGS < \"k\" then\n          NONE\n        else\n          \"key_cntr\" <- \"k\" + #1;;\n          let: \"sample_cntr\" := ref #0 in\n          SOME (λ: \"_\",\n               let: \"v\" := !\"sample_cntr\" in\n               let: \"b\" :=\n                 if: \"v\" ≤ #MAX_SAMPLES then\n                   \"f\" \"k\" \"v\"\n                 else\n                   #false\n               in\n               \"sample_cntr\" <- \"v\" + #1;;\n               \"b\").\n\n  Definition hash_rng_gen_specialized (f: val) (key_cntr: loc) : val :=\n      λ: \"_\",\n        let: \"k\" := ! #key_cntr in\n        if: #MAX_RNGS < \"k\" then\n          NONE\n        else\n          #key_cntr <- \"k\" + #1;;\n          let: \"sample_cntr\" := ref #0 in\n          SOME (λ: \"_\",\n               let: \"v\" := !\"sample_cntr\" in\n               let: \"b\" :=\n                 if: \"v\" ≤ #MAX_SAMPLES then\n                   f \"k\" \"v\"\n                 else\n                   #false\n               in\n               \"sample_cntr\" <- \"v\" + #1;;\n               \"b\").\n\n  Definition hash_rng_specialized (f : val) (k : nat) (c : loc) : val :=\n    (λ: \"_\",\n      let: \"v\" := !#c in\n      let: \"b\" :=\n        if: \"v\" ≤ #MAX_SAMPLES then\n          f #k \"v\"\n        else\n          #false\n      in\n      #c <- \"v\" + #1;;\n      \"b\").\n\n  Context `{!prelogrelGS Σ}.\n\n  (* TODO: it would be better to wrap this ghost_mapG with keyed_mapG *)\n  Context {GHOST_MAP: ghost_mapG Σ (fin_hash_dom_space MAX_RNGS_POW MAX_SAMPLES_POW) (option bool)}.\n\n  Definition khashN := nroot.@\"khash\".\n\n  Definition is_keyed_hash γ f :=\n    na_inv prelogrelGS_nais khashN (keyed_hash_auth MAX_RNGS_POW MAX_SAMPLES_POW γ f).\n  Definition is_skeyed_hash γ f :=\n    na_inv prelogrelGS_nais khashN (skeyed_hash_auth MAX_RNGS_POW MAX_SAMPLES_POW γ f).\n\n  (* Putting is_keyed_hash seems like it makes the definition but then this is not timeless *)\n\n  Definition hash_rng (n: nat) (g: val) : iProp Σ :=\n    ∃ h k c m γ, ⌜ g = hash_rng_specialized h (fin_to_nat k) c ⌝ ∗\n             ⌜ ∀ x, n <= x → x ∉ dom m ⌝ ∗\n             khashfun_own MAX_RNGS_POW MAX_SAMPLES_POW γ k m ∗\n             is_keyed_hash γ h ∗\n             c ↦ #n.\n\n  Definition shash_rng (n: nat) (g: val) : iProp Σ :=\n    ∃ h k c m γ, ⌜ g = hash_rng_specialized h (fin_to_nat k) c ⌝ ∗\n             ⌜ ∀ x, n <= x → x ∉ dom m ⌝ ∗\n             khashfun_own MAX_RNGS_POW MAX_SAMPLES_POW γ k m ∗\n             is_skeyed_hash γ h ∗\n             c ↦ₛ #n.\n\n  Definition hash_rng_gen (n: nat) (f: val) : iProp Σ :=\n    ∃ h kcntr γ, ⌜ f = hash_rng_gen_specialized h kcntr ⌝ ∗\n                  is_keyed_hash γ h ∗\n                  kcntr ↦ #n ∗\n                  [∗ set] k ∈ fin_to_set (fin_key_space MAX_RNGS_POW),\n                     (⌜ n <= fin_to_nat k ⌝ → khashfun_own _ MAX_SAMPLES_POW γ k ∅).\n\n  Definition shash_rng_gen (n: nat) (f: val) : iProp Σ :=\n    ∃ h kcntr γ, ⌜ f = hash_rng_gen_specialized h kcntr ⌝ ∗\n                  is_skeyed_hash γ h ∗\n                  kcntr ↦ₛ #n ∗\n                  [∗ set] k ∈ fin_to_set (fin_key_space MAX_RNGS_POW),\n                     (⌜ n <= fin_to_nat k ⌝ → khashfun_own _ MAX_SAMPLES_POW γ k ∅).\n\n  Lemma wp_init_rng_gen E :\n    {{{ True }}}\n      init_rng_gen #() @ E\n    {{{ (f: val), RET f; hash_rng_gen 0 f }}}.\n  Proof.\n    iIntros (Φ) \"_ HΦ\".\n    rewrite /init_rng_gen.\n    wp_pures.\n    wp_apply (wp_init_keyed_hash with \"[//]\").\n    iIntros (h) \"H\". iDestruct \"H\" as (γ) \"(Hauth&Hks)\".\n    wp_pures.\n    wp_alloc key_cntr as \"Hkc\".\n    wp_pures.\n    iAssert (|={E}=> is_keyed_hash γ h)%I with \"[Hauth]\" as \">#His_keyed\".\n    { iApply na_inv_alloc. iNext. eauto. }\n    iModIntro. iApply \"HΦ\".\n    iExists _, _, _. iFrame \"# ∗\".\n    iSplit; first by eauto.\n    iApply (big_sepS_mono with \"Hks\").\n    iIntros (x Helem) \"$\"; auto.\n  Qed.\n\n  Lemma spec_init_rng_gen E K :\n    ↑specN ⊆ E →\n    refines_right K (init_rng_gen #()) ={E}=∗\n    ∃ f, refines_right K (of_val f) ∗ shash_rng_gen 0 f.\n  Proof.\n    iIntros (?) \"HK\".\n    rewrite /init_rng_gen.\n    tp_pures.\n    tp_bind (init_keyed_hash _ _ _).\n    rewrite refines_right_bind.\n    iMod (spec_init_keyed_hash with \"[$]\") as (h γ) \"(HK&Hauth&Hks)\"; first done.\n    rewrite -refines_right_bind /=.\n    tp_pures.\n    tp_alloc as key_cntr \"Hkc\".\n    tp_pures.\n    iAssert (|={E}=> is_skeyed_hash γ h)%I with \"[Hauth]\" as \">#His_keyed\".\n    { iApply na_inv_alloc. iNext. eauto. }\n    iModIntro. iExists _. iFrame \"HK\".\n    iExists _, _, _. iFrame \"# ∗\".\n    iSplit; first by eauto.\n    iApply (big_sepS_mono with \"Hks\").\n    iIntros (x Helem) \"$\"; auto.\n  Qed.\n\n  Lemma wp_run_rng_gen k f E :\n    k <= MAX_RNGS →\n    {{{ ▷ hash_rng_gen k f }}}\n      f #() @ E\n    {{{ (g: val), RET (SOMEV g); hash_rng_gen (S k) f ∗ hash_rng 0 g }}}.\n  Proof.\n    iIntros (Hle Φ) \"Hgen HΦ\".\n    iDestruct \"Hgen\" as (h kcntr γ) \"(>->&#His&Hknctr&Hks)\".\n\n    iEval (rewrite /hash_rng_gen_specialized). wp_pures.\n    wp_load. wp_pures.\n    case_bool_decide; first by lia.\n    wp_pures.\n    wp_store.\n    wp_alloc sample_cntr as \"Hsc\".\n    wp_pures.\n    iModIntro.\n    rewrite /init_rng_gen.\n    iApply \"HΦ\".\n    assert (Hlt: k < S MAX_RNGS) by lia.\n    set (k' := (nat_to_fin Hlt : fin_key_space MAX_RNGS_POW)).\n    iDestruct (big_sepS_delete _ _ k' with \"Hks\") as \"(Hk&Hks)\".\n    { apply elem_of_fin_to_set. }\n    iSplitL \"Hks Hknctr\".\n    - iExists _, _, _. iSplit; first eauto. iFrame \"#\".\n      assert (Z.of_nat k + 1 = Z.of_nat (S k))%Z as -> by lia.\n      iFrame \"Hknctr\".\n      iApply (big_sepS_delete _ _ k').\n      { apply elem_of_fin_to_set. }\n      iSplitR \"Hks\".\n      * iIntros (Hle'). iExFalso. rewrite /k' fin_to_nat_to_fin in Hle'. lia.\n      * iApply (big_sepS_mono with \"Hks\"). iIntros (??) \"H %Hle'\".\n        iApply \"H\". iPureIntro; lia.\n    - iExists _, k', _, ∅, _. iFrame \"Hsc #\". iSplit.\n      { rewrite /hash_rng_specialized. rewrite /k' fin_to_nat_to_fin //. }\n      iSplit.\n      { iPureIntro. set_solver. }\n      iApply \"Hk\". rewrite /k' fin_to_nat_to_fin; auto.\n  Qed.\n\n  Lemma spec_run_rng_gen k f K E  :\n    ↑specN ⊆ E →\n    k <= MAX_RNGS →\n    shash_rng_gen k f -∗\n    refines_right K (f #()) ={E}=∗\n    ∃ g, refines_right K (of_val (SOMEV g)) ∗ shash_rng_gen (S k) f ∗ shash_rng 0 g.\n  Proof.\n    iIntros (HE Hle) \"Hgen HK\".\n    iDestruct \"Hgen\" as (h kcntr γ) \"(->&#His&Hknctr&Hks)\".\n    iEval (rewrite /hash_rng_gen_specialized) in \"HK\".\n    tp_pures.\n    tp_load.\n    tp_pures.\n    case_bool_decide; first by lia.\n    tp_pures.\n    tp_store.\n    tp_pures.\n    tp_alloc as sample_cntr \"Hsc\".\n    tp_pures.\n    iModIntro.\n    iExists _. iFrame \"HK\".\n    assert (Hlt: k < S MAX_RNGS) by lia.\n    set (k' := (nat_to_fin Hlt : fin_key_space MAX_RNGS_POW)).\n    iDestruct (big_sepS_delete _ _ k' with \"Hks\") as \"(Hk&Hks)\".\n    { apply elem_of_fin_to_set. }\n    iSplitL \"Hks Hknctr\".\n    - iExists _, _, _. iSplit; first eauto. iFrame \"#\".\n      assert (Z.of_nat k + 1 = Z.of_nat (S k))%Z as -> by lia.\n      iFrame \"Hknctr\".\n      iApply (big_sepS_delete _ _ k').\n      { apply elem_of_fin_to_set. }\n      iSplitR \"Hks\".\n      * iIntros (Hle'). iExFalso. rewrite /k' fin_to_nat_to_fin in Hle'. lia.\n      * iApply (big_sepS_mono with \"Hks\"). iIntros (??) \"H %Hle'\".\n        iApply \"H\". iPureIntro; lia.\n    - iExists _, k', _, ∅, _. iFrame \"Hsc #\". iSplit.\n      { rewrite /hash_rng_specialized. rewrite /k' fin_to_nat_to_fin //. }\n      iSplit.\n      { iPureIntro. set_solver. }\n      iApply \"Hk\". rewrite /k' fin_to_nat_to_fin; auto.\n  Qed.\n\n  Lemma wp_run_rng_gen_out_of_range k f E :\n    MAX_RNGS < k →\n    {{{ ▷ hash_rng_gen k f }}}\n      f #() @ E\n    {{{ RET NONEV; hash_rng_gen k f }}}.\n  Proof.\n    iIntros (Hlt Φ) \"Hgen HΦ\".\n    iDestruct \"Hgen\" as (h kcntr γ) \"(>->&#His&Hknctr&Hks)\".\n\n    iEval (rewrite /hash_rng_gen_specialized). wp_pures.\n    wp_load. wp_pures.\n    case_bool_decide; last by lia.\n    wp_pures.\n    iApply \"HΦ\".\n    iModIntro. iExists _, _, _. iSplit; first eauto. iFrame \"#∗\".\n  Qed.\n\n  Lemma spec_run_rng_gen_out_of_range k f K E  :\n    ↑specN ⊆ E →\n    MAX_RNGS < k →\n    shash_rng_gen k f -∗\n    refines_right K (f #()) ={E}=∗\n    refines_right K (of_val NONEV) ∗ shash_rng_gen k f.\n  Proof.\n    iIntros (HE Hlt) \"Hgen HK\".\n    iDestruct \"Hgen\" as (h kcntr γ) \"(->&#His&Hknctr&Hks)\".\n\n    iEval (rewrite /hash_rng_gen_specialized) in \"HK\". tp_pures.\n    tp_load. tp_pures.\n    case_bool_decide; last by lia.\n    tp_pures.\n    iModIntro. iFrame \"HK\".\n    iExists _, _, _. iSplit; first eauto. iFrame \"#∗\".\n  Qed.\n\n  Instance fin_keys_inhabited :\n    Inhabited (fin (S (MAX_KEYS MAX_RNGS_POW))).\n  Proof. econstructor. econstructor. Qed.\n\n  (* Notice this is almost identical to the version in rng.v, except we need the token\n     to open the invariant for the keyed hash *)\n  Lemma wp_hash_rng_flip n g K E :\n    ↑specN ⊆ E →\n    ↑khashN ⊆ E →\n    n ≤ MAX_SAMPLES →\n    {{{ ▷ hash_rng n g ∗ refines_right K (flip #()) ∗ na_own prelogrelGS_nais (↑khashN) }}}\n      g #() @ E\n    {{{ (b : bool), RET #b; hash_rng (S n) g ∗ refines_right K #b ∗ na_own prelogrelGS_nais (↑khashN) }}}.\n  Proof.\n    iIntros (HN1 HN2 Hle Φ) \"(Hhash&HK&Htok) HΦ\".\n    rewrite /hash_rng.\n    iDestruct \"Hhash\" as (h k c m γ) \"(>->&>%Hdom&Hhash&#Hkeyed_hash&Hc)\".\n    rewrite /hash_rng_specialized. wp_pures.\n    wp_load. wp_pures.\n    case_bool_decide; last by lia.\n    rewrite /is_keyed_hash.\n    wp_pures.\n    iMod (na_inv_acc with \"[$] [$]\") as \"(>H&Htok&Hclo)\"; auto.\n    iDestruct (khashfun_own_couplable _ _ _ _ _ m n with \"[$] [$]\") as \"Hcoup\"; auto.\n    { apply not_elem_of_dom. auto. }\n    iApply (hash.impl_couplable_elim with \"[-]\"); [done | done |].\n    iFrame \"Hcoup HK\". iIntros (b) \">(Hauth&Hhash) HK\".\n    wp_apply (wp_khashfun_prev with \"[$]\").\n    { rewrite lookup_insert //. }\n    iIntros \"(Hauth&Hhash)\". wp_pures.\n    wp_store. iMod (\"Hclo\" with \"[$]\") as \"Htok\". iModIntro. iApply \"HΦ\".\n    iFrame. iExists _, _, _, _, _. iFrame.\n    iSplit; first done.\n    iSplit.\n    { iPureIntro. intros x. rewrite dom_insert_L.\n      set_unfold. intros Hle' [?|?]; first lia.\n      eapply Hdom; last by eassumption. lia.\n    }\n    assert (Z.of_nat n + 1 = Z.of_nat (S n))%Z as -> by lia.\n    auto.\n  Qed.\n\n  Existing Instance timeless_skeyed_hash_auth.\n\n  Lemma spec_hash_rng_flip_couplable n g K E :\n    ↑specN ⊆ E →\n    ↑khashN ⊆ E →\n    n ≤ MAX_SAMPLES →\n    shash_rng n g -∗\n    na_own prelogrelGS_nais (↑khashN) -∗\n    refines_right K (g #()) ={E}=∗\n    spec_couplable (λ b, |={E}=> refines_right K #b ∗ shash_rng (S n) g ∗ na_own prelogrelGS_nais (↑khashN)).\n  Proof.\n    iIntros (HN1 HN2 Hle) \"Hhash Htok HK\".\n    iDestruct \"Hhash\" as (h k c m γ) \"(->&%Hdom&Hhash&#Hkeyed_hash&Hc)\".\n    rewrite /hash_rng_specialized. tp_pures.\n    tp_load. tp_pures.\n    case_bool_decide; last by lia.\n    rewrite /is_skeyed_hash.\n    tp_pures.\n    iMod (na_inv_acc with \"[$] [$]\") as \"(>H&Htok&Hclo)\"; auto.\n    iDestruct (khashfun_own_spec_couplable _ _ _ _ _ m n with \"[$] [$]\") as \"Hcoup\"; auto.\n    { apply not_elem_of_dom. auto. }\n    iModIntro.\n    iApply (spec_couplable_wand with \"Hcoup\").\n    iIntros (b) \">(Hauth&Hhash)\".\n    tp_bind (h #k #n).\n    rewrite refines_right_bind.\n    iMod (spec_khashfun_prev with \"[$] [$] [$]\") as \"(HK&Hauth&Hhash)\".\n    { rewrite lookup_insert //. }\n    { done. }\n    rewrite -refines_right_bind/=.\n    tp_pures.\n    tp_store.\n    tp_pures.\n    iMod (\"Hclo\" with \"[$]\") as \"Htok\". iModIntro.\n    iFrame. iExists _, _, _, _, _. iFrame.\n    iSplit; first done.\n    iSplit.\n    { iPureIntro. intros x. rewrite dom_insert_L.\n      set_unfold. intros Hle' [?|?]; first lia.\n      eapply Hdom; last by eassumption. lia.\n    }\n    assert (Z.of_nat n + 1 = Z.of_nat (S n))%Z as -> by lia.\n    auto.\n  Qed.\n\n  Lemma wp_hash_rng_flip_out_of_range n g E:\n    MAX_SAMPLES < n →\n    {{{ ▷ hash_rng n g }}}\n      g #() @ E\n    {{{ RET #false; hash_rng (S n) g }}}.\n  Proof.\n    iIntros (Hlt Φ) \"Hhash HΦ\".\n    iDestruct \"Hhash\" as (h k c m γ) \"(>->&>%Hdom&Hhash&#Hkeyed_hash&Hc)\".\n    rewrite /hash_rng_specialized. wp_pures.\n    wp_load. wp_pures.\n    case_bool_decide; first lia.\n    wp_pures. wp_store. iApply \"HΦ\".\n    iModIntro.\n    assert (Z.of_nat n + 1 = Z.of_nat (S n))%Z as -> by lia.\n    iExists _, _, _, _, _. iFrame \"#∗\". iSplit; first eauto.\n    iPureIntro. intros. apply Hdom. lia.\n  Qed.\n\n  Lemma spec_hash_rng_flip_out_of_range n g K E :\n    ↑specN ⊆ E →\n    MAX_SAMPLES < n →\n    shash_rng n g -∗\n    refines_right K (g #()) ={E}=∗\n    refines_right K #false ∗ shash_rng (S n) g.\n  Proof.\n    iIntros (HE Hlt) \"Hhash HK\".\n    iDestruct \"Hhash\" as (h k c m γ) \"(->&%Hdom&Hhash&#Hkeyed_hash&Hc)\".\n    rewrite /hash_rng_specialized. tp_pures.\n    tp_load. tp_pures.\n    case_bool_decide; first lia.\n    tp_pures. tp_store. tp_pures.\n    iModIntro. iFrame \"HK\".\n    assert (Z.of_nat n + 1 = Z.of_nat (S n))%Z as -> by lia.\n    iExists _, _, _, _, _. iFrame \"#∗\". iSplit; first eauto.\n    iPureIntro. intros. apply Hdom. lia.\n  Qed.\n\n  (* The \"ideal\" version that calls a tape-less flip directly *)\n\n  Definition init_bounded_rng_gen : val :=\n    λ: \"_\",\n      let: \"rng_cntr\" := ref #0 in\n      λ: \"_\",\n        let: \"k\" := !\"rng_cntr\" in\n        if: #MAX_RNGS < \"k\" then\n          NONE\n        else\n          \"rng_cntr\" <- \"k\" + #1;;\n          let: \"f\" := (init_bounded_rng MAX_SAMPLES) #() in\n          SOME \"f\".\n\n  Definition bounded_rng_gen_specialized (c : loc) : val :=\n      λ: \"_\",\n        let: \"k\" := !#c in\n        if: #MAX_RNGS < \"k\" then\n          NONE\n        else\n          #c <- \"k\" + #1;;\n          let: \"f\" := (init_bounded_rng MAX_SAMPLES) #() in\n          SOME \"f\".\n\n  Definition bounded_rng_gen (n: nat) (g: val) : iProp Σ :=\n    ∃ c, ⌜ g = bounded_rng_gen_specialized c ⌝ ∗ c ↦ #n.\n\n  Definition sbounded_rng_gen (n: nat) (g: val) : iProp Σ :=\n    ∃ c, ⌜ g = bounded_rng_gen_specialized c ⌝ ∗ c ↦ₛ #n.\n\n  Lemma wp_init_bounded_rng_gen E :\n    {{{ True }}}\n      init_bounded_rng_gen #() @ E\n    {{{ g, RET g; bounded_rng_gen O g }}}.\n  Proof.\n    iIntros (Φ) \"_ HΦ\".\n    rewrite /init_bounded_rng_gen. wp_pures.\n    wp_alloc c as \"Hc\".\n    wp_pures. iModIntro.\n    iApply \"HΦ\".\n    iExists _. iFrame. eauto.\n  Qed.\n\n  Lemma spec_init_bounded_rng_gen E K :\n    ↑specN ⊆ E →\n    refines_right K (init_bounded_rng_gen #()) ={E}=∗ ∃ f, refines_right K (of_val f) ∗ sbounded_rng_gen O f.\n  Proof.\n    iIntros (?) \"Hspec\".\n    rewrite /init_bounded_rng_gen.\n    tp_pures.\n    tp_alloc as c \"Hc\".\n    tp_pures.\n    iModIntro. iExists _. iFrame. iExists c. eauto.\n  Qed.\n\n  Lemma wp_run_bounded_rng_gen k f E :\n    k <= MAX_RNGS →\n    {{{ bounded_rng_gen k f }}}\n      f #() @ E\n    {{{ (g: val), RET (SOMEV g); bounded_rng_gen (S k) f ∗ bounded_rng MAX_SAMPLES 0 g }}}.\n  Proof.\n    iIntros (Hle Φ) \"Hhash HΦ\".\n    iDestruct \"Hhash\" as (c ->) \"Hc\".\n    rewrite /bounded_rng_gen_specialized.\n    wp_pures. wp_load. wp_pures.\n    case_bool_decide; try lia; [].\n    wp_pures. wp_store.\n    wp_apply (wp_init_bounded_rng with \"[//]\").\n    iIntros (?) \"H\". wp_pures.\n    iModIntro. iApply \"HΦ\".\n    iFrame.\n    iExists _. iSplit; first done.\n    assert (Z.of_nat k + 1 = Z.of_nat (S k))%Z as -> by lia. auto.\n  Qed.\n\n  Lemma spec_run_bounded_rng_gen k f E K :\n    ↑specN ⊆ E →\n    k <= MAX_RNGS →\n    sbounded_rng_gen k f -∗\n    refines_right K (f #()) ={E}=∗\n    ∃ g, refines_right K (of_val (SOMEV g)) ∗\n         sbounded_rng_gen (S k) f ∗\n         sbounded_rng MAX_SAMPLES O g.\n  Proof.\n    iIntros (? Hle) \"Hgen Hspec\".\n    iDestruct \"Hgen\" as (c ->) \"Hc\".\n    rewrite /bounded_rng_gen_specialized.\n    tp_pures.\n    tp_load.\n    tp_pures.\n    case_bool_decide; try lia; [].\n    tp_pures.\n    tp_store.\n    tp_pures.\n    tp_bind (init_bounded_rng _ _).\n    rewrite refines_right_bind.\n    iMod (spec_init_bounded_rng with \"[$]\") as (g) \"(HK&Hrng)\"; auto.\n    rewrite -refines_right_bind /=.\n    tp_pures.\n    iModIntro. iExists _. iFrame. iExists c.\n    assert (Z.of_nat k + 1 = Z.of_nat (S k))%Z as -> by lia. auto.\n  Qed.\n\n  Lemma wp_run_bounded_rng_gen_out_of_range k f E :\n    MAX_RNGS < k →\n    {{{ bounded_rng_gen k f }}}\n      f #() @ E\n    {{{ RET NONEV; bounded_rng_gen k f }}}.\n  Proof.\n    iIntros (Hle Φ) \"Hhash HΦ\".\n    iDestruct \"Hhash\" as (c ->) \"Hc\".\n    rewrite /bounded_rng_gen_specialized.\n    wp_pures. wp_load. wp_pures.\n    case_bool_decide; try lia; [].\n    wp_pures.\n    iModIntro. iApply \"HΦ\".\n    iExists _. iFrame; eauto.\n  Qed.\n\n  Lemma spec_run_bounded_rng_gen_out_of_range k f E K :\n    ↑specN ⊆ E →\n    MAX_RNGS < k →\n    sbounded_rng_gen k f -∗\n    refines_right K (f #()) ={E}=∗\n         refines_right K (of_val NONEV) ∗\n         sbounded_rng_gen k f.\n  Proof.\n    iIntros (? Hle) \"Hgen Hspec\".\n    iDestruct \"Hgen\" as (c ->) \"Hc\".\n    rewrite /bounded_rng_gen_specialized.\n    tp_pures.\n    tp_load.\n    tp_pures.\n    case_bool_decide; try lia; [].\n    tp_pures.\n    iFrame.\n    iModIntro. iExists _. iFrame. eauto.\n  Qed.\n\n  Lemma wp_hash_rng_flip_refine n g sg K E :\n    ↑khashN ⊆ E →\n    ↑specN ⊆ E →\n    {{{ ▷ hash_rng n g ∗ sbounded_rng MAX_SAMPLES n sg ∗ refines_right K (sg #()) ∗\n          na_own prelogrelGS_nais (↑khashN) }}}\n      g #() @ E\n    {{{ (b : bool), RET #b; hash_rng (S n) g ∗ sbounded_rng MAX_SAMPLES (S n) sg ∗ refines_right K #b ∗\n          na_own prelogrelGS_nais (↑khashN) }}}.\n  Proof.\n    iIntros (HN1 HN2 Φ) \"(Hhash&Hbrng&HK&Htok) HΦ\".\n    iDestruct \"Hbrng\" as (sc ->) \"Hsc\".\n    rewrite /bounded_rng_specialized.\n    tp_pures.\n    tp_load.\n    tp_pures.\n    case_bool_decide.\n    - tp_pures.\n      tp_bind (flip #())%E.\n      rewrite refines_right_bind.\n      iApply wp_fupd.\n      wp_apply (wp_hash_rng_flip with \"[$HK $Hhash $Htok]\"); auto.\n      { lia. }\n      iIntros (b) \"(Hhash&HK&Htok)\".\n      rewrite -refines_right_bind /=.\n      tp_pures.\n      tp_store.\n      tp_pures.\n      iApply \"HΦ\".\n      iFrame. iModIntro.\n      iExists _.\n      assert (Z.of_nat n + 1 = Z.of_nat (S n))%Z as -> by lia.\n      iFrame. eauto.\n    - tp_pures.\n      tp_store.\n      tp_pures.\n      wp_apply (wp_hash_rng_flip_out_of_range with \"[$Hhash]\"); auto.\n      { lia. }\n      iIntros \"Hhash\".\n      iApply \"HΦ\".\n      iFrame.\n      iExists _.\n      assert (Z.of_nat n + 1 = Z.of_nat (S n))%Z as -> by lia.\n      iFrame. eauto.\n  Qed.\n\n  Lemma wp_bounded_rng_flip_refine n g sg K E :\n    ↑specN ⊆ E →\n    ↑khashN ⊆ E →\n    {{{ bounded_rng MAX_SAMPLES n g ∗ ▷ shash_rng n sg ∗ refines_right K (sg #()) ∗\n          na_own prelogrelGS_nais (↑khashN)}}}\n      g #() @ E\n    {{{ (b : bool), RET #b; bounded_rng MAX_SAMPLES (S n) g ∗ shash_rng (S n) sg ∗ refines_right K #b ∗\n          na_own prelogrelGS_nais (↑khashN)}}}.\n  Proof.\n    iIntros (HN1 HN2 Φ) \"(Hbrng&Hhash&HK&Htok) HΦ\".\n    iDestruct \"Hbrng\" as (sc ->) \"Hsc\".\n    rewrite /bounded_rng_specialized.\n    wp_pures. wp_load. wp_pures.\n    case_bool_decide.\n    - wp_pures.\n      iAssert (spec_ctx) with \"[-]\" as \"#Hspec_ctx\".\n      { iDestruct \"HK\" as \"($&_)\". }\n      iMod (spec_hash_rng_flip_couplable with \"Hhash Htok HK\") as \"Hspec\"; auto.\n      { lia. }\n      wp_apply (spec_couplable_elim with \"[$Hspec $Hspec_ctx Hsc HΦ]\"); auto.\n      iIntros (b) \">(HK&Hhash)\".\n      wp_pures. wp_store.\n      iModIntro. iApply \"HΦ\".\n      iFrame \"HK Hhash\". iExists _.\n      assert (Z.of_nat n + 1 = Z.of_nat (S n))%Z as -> by lia.\n      iFrame. eauto.\n    - wp_pures.\n      iMod (spec_hash_rng_flip_out_of_range with \"Hhash HK\") as \"(HK&Hhash)\"; auto.\n      { lia. }\n      wp_store.\n      iModIntro. iApply \"HΦ\".\n      iFrame \"HK Hhash Htok\". iExists _.\n      assert (Z.of_nat n + 1 = Z.of_nat (S n))%Z as -> by lia.\n      iFrame. eauto.\n  Qed.\n\n  Definition rngN := nroot.@\"rng\".\n\n  Lemma hash_bounded_refinement :\n    ⊢ REL init_rng_gen << init_bounded_rng_gen :\n      lrel_unit → (lrel_unit → lrel_sum lrel_unit (lrel_unit → lrel_bool)).\n  Proof.\n    rel_arrow_val.\n    iIntros (??) \"(->&->)\".\n    rewrite refines_eq. iIntros (K) \"HK Hown\".\n    iApply wp_fupd.\n    wp_apply (wp_init_rng_gen with \"[//]\").\n    iIntros (g) \"Hhash_gen\".\n    iMod (spec_init_bounded_rng_gen with \"[$]\") as (f) \"(HK&Hbounded_gen)\"; first done.\n    set (P := (∃ n, hash_rng_gen n g ∗ sbounded_rng_gen n f)%I).\n    iMod (na_inv_alloc prelogrelGS_nais _ rngN P with \"[Hhash_gen Hbounded_gen]\") as \"#Hinv\".\n    { iNext. iExists O. iFrame. }\n    iModIntro. iExists _. iFrame.\n    iIntros (v1 v2) \"!> (->&->)\".\n    clear K.\n    rewrite /P.\n    iApply (refines_na_inv with \"[$Hinv]\") ; auto ; iIntros \"[HP Hclose]\".\n    rewrite refines_eq. iIntros (K) \"HK Hown\".\n    iDestruct \"HP\" as (m) \"(Hg&>Hsf)\".\n    iApply wp_fupd.\n    destruct (decide (m <= MAX_RNGS)) as [Hl|]; last first.\n    { wp_apply (wp_run_rng_gen_out_of_range with \"[$]\"); first lia.\n      iIntros \"Hg\".\n      iMod (spec_run_bounded_rng_gen_out_of_range with \"[$] [$]\") as \"(HK&Hsf)\"; auto; try lia.\n      iMod (\"Hclose\" with \"[Hg Hsf $Hown]\").\n      { iNext. iExists _; iFrame. }\n      iModIntro. iExists _; iFrame.\n      iExists _, _. iLeft.\n      iSplit; first eauto.\n      iSplit; first eauto.\n      eauto. }\n\n    wp_apply (wp_run_rng_gen with \"[$]\"); first done.\n    iIntros (hrng) \"(Hg&Hrng)\".\n    iMod (spec_run_bounded_rng_gen with \"Hsf HK\") as (srng) \"(HK&Hsf&Hsrng)\"; auto.\n    iMod (\"Hclose\" with \"[Hg Hsf Hown]\") as \"Hown\".\n    { iFrame. iNext. iExists _; iFrame. }\n\n\n    (* finally we show a refinement between the generated rngs *)\n    set (Prng := (∃ n, hash_rng n hrng ∗ sbounded_rng MAX_SAMPLES n srng)%I).\n    iMod (na_inv_alloc prelogrelGS_nais _ rngN Prng with \"[Hrng Hsrng]\") as \"#Hinv_rng\".\n    { rewrite /Prng. iNext. iExists _. iFrame.  }\n    iClear \"Hinv\".\n    iModIntro. iExists _. iFrame.\n\n\n    iExists _, _. iRight.\n    iSplit; first eauto.\n    iSplit; first eauto.\n\n    iIntros (v1 v2) \"!> (->&->)\".\n    clear Hl m K.\n    iApply (refines_na_inv with \"[$Hinv_rng]\") ; auto ; iIntros \"[HP Hclose]\".\n    rewrite refines_eq. iIntros (K) \"HK Hown\".\n    iDestruct \"HP\" as (m) \"(Hf&>Hsf)\".\n    iApply wp_fupd.\n    iDestruct (na_own_acc (↑khashN) with \"Hown\") as \"(Hown&Hclose')\"; first solve_ndisj.\n    wp_apply (wp_hash_rng_flip_refine with \"[$Hf $Hsf $HK $Hown]\"); [done | done |].\n    iIntros (b) \"(Hhash&Hbounded&HK&Hown)\".\n    iDestruct (\"Hclose'\" with \"[$]\") as \"Hown\".\n    iMod (\"Hclose\" with \"[-HK]\").\n    { iFrame. iExists _. iFrame. }\n    iExists _. iFrame. eauto.\n  Qed.\n\n  Lemma bounded_hash_refinement :\n    ⊢ REL init_bounded_rng_gen << init_rng_gen :\n      lrel_unit → (lrel_unit → lrel_sum lrel_unit (lrel_unit → lrel_bool)).\n  Proof.\n    rel_arrow_val.\n    iIntros (??) \"(->&->)\".\n    rewrite refines_eq. iIntros (K) \"HK Hown\".\n    iApply wp_fupd.\n    wp_apply (wp_init_bounded_rng_gen with \"[//]\").\n    iIntros (g) \"Hbounded_gen\".\n    iMod (spec_init_rng_gen with \"[$]\") as (f) \"(HK&Hhash_gen)\"; first done.\n    set (P := (∃ n, shash_rng_gen n f ∗ bounded_rng_gen n g)%I).\n    iMod (na_inv_alloc prelogrelGS_nais _ rngN P with \"[Hhash_gen Hbounded_gen]\") as \"#Hinv\".\n    { iNext. iExists O. iFrame. }\n    iModIntro. iExists _. iFrame.\n    iIntros (v1 v2) \"!> (->&->)\".\n    clear K.\n    rewrite /P.\n    iApply (refines_na_inv with \"[$Hinv]\") ; auto ; iIntros \"[HP Hclose]\".\n    rewrite refines_eq. iIntros (K) \"HK Hown\".\n    iDestruct \"HP\" as (m) \"(Hsf&>Hg)\".\n    iApply wp_fupd.\n    destruct (decide (m <= MAX_RNGS)) as [Hl|]; last first.\n    { wp_apply (wp_run_bounded_rng_gen_out_of_range with \"[$]\"); first lia.\n      iIntros \"Hg\".\n      iMod (spec_run_rng_gen_out_of_range with \"[$] [$]\") as \"(HK&Hsf)\"; auto; try lia.\n      iMod (\"Hclose\" with \"[Hg Hsf $Hown]\").\n      { iNext. iExists _; iFrame. }\n      iModIntro. iExists _; iFrame.\n      iExists _, _. iLeft.\n      iSplit; first eauto.\n      iSplit; first eauto.\n      eauto. }\n\n    wp_apply (wp_run_bounded_rng_gen with \"[$]\"); first done.\n    iIntros (rng) \"(Hg&Hrng)\".\n    iMod (spec_run_rng_gen with \"Hsf HK\") as (srng) \"(HK&Hsf&Hsrng)\"; auto.\n    iMod (\"Hclose\" with \"[Hg Hsf Hown]\") as \"Hown\".\n    { iFrame. iNext. iExists _; iFrame. }\n\n\n    (* finally we show a refinement between the generated rngs *)\n    set (Prng := (∃ n, shash_rng n srng ∗ bounded_rng MAX_SAMPLES n rng)%I).\n    iMod (na_inv_alloc prelogrelGS_nais _ rngN Prng with \"[Hrng Hsrng]\") as \"#Hinv_rng\".\n    { rewrite /Prng. iNext. iExists _. iFrame.  }\n    iClear \"Hinv\".\n    iModIntro. iExists _. iFrame.\n\n\n    iExists _, _. iRight.\n    iSplit; first eauto.\n    iSplit; first eauto.\n\n    iIntros (v1 v2) \"!> (->&->)\".\n    clear Hl m K.\n    iApply (refines_na_inv with \"[$Hinv_rng]\") ; auto ; iIntros \"[HP Hclose]\".\n    rewrite refines_eq. iIntros (K) \"HK Hown\".\n    iDestruct \"HP\" as (m) \"(Hf&>Hsf)\".\n    iApply wp_fupd.\n    iDestruct (na_own_acc (↑khashN) with \"Hown\") as \"(Hown&Hclose')\"; first solve_ndisj.\n    wp_apply (wp_bounded_rng_flip_refine with \"[$Hf $Hsf $HK $Hown]\"); [done | done |].\n    iIntros (b) \"(Hhash&Hbounded&HK&Hown)\".\n    iDestruct (\"Hclose'\" with \"[$]\") as \"Hown\".\n    iMod (\"Hclose\" with \"[-HK]\").\n    { iFrame. iExists _. iFrame. }\n    iExists _. iFrame. eauto.\n  Qed.\n\nEnd rng.\n", "meta": {"author": "logsem", "repo": "clutch", "sha": "35144f9b1fe9c913b4bd24106a12ac7f02b20ec5", "save_path": "github-repos/coq/logsem-clutch", "path": "github-repos/coq/logsem-clutch/clutch-35144f9b1fe9c913b4bd24106a12ac7f02b20ec5/theories/examples/split_rng.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2929222143232949}}
{"text": "Set Implicit Arguments.\n\nRequire Export List.\nRequire Export Arith.\n\nSection Carrier.\n\nVariable N:Type.\nVariable A:Type.\nVariable zero : N.\nVariable succ : N -> N.\nVariable comp : N -> N -> comparison.\n\nFixpoint fromNat (x:nat) : N :=\n  match x with\n    | 0 => zero\n    | S y => succ (fromNat y)\n  end.\n\nVariable size : forall t, list t -> N.\nVariable sizeNat : forall t (x:list t), fromNat (length x) = size x.\n\n\n(*\nDefinition Buffer t := list t.\n\nDefinition bufferSize t (b:list t) := @length _ b < 6.\n*)\n\nInductive Buffer t :=\n  Zero \n| One : t -> Buffer t\n| Two : t -> t -> Buffer t\n| Three : t -> t -> t -> Buffer t\n| Four : t -> t -> t -> t -> Buffer t\n| Five : t -> t -> t -> t -> t -> Buffer t.\n\nSet Maximal Implicit Insertion.\nImplicit Arguments Zero [t].\nUnset Maximal Implicit Insertion.\n\n(*\nInductive SimpleDeque t :=\n  Empty : SimpleDeque t\n| Full : Buffer t ->\n         SimpleDeque (prod t t) ->\n         Buffer t ->\n         SimpleDeque t.\n*)\n\n(*\nInductive LeafTree t :=\n  One : t -> LeafTree t\n| More : LeafTree (prod t t) -> LeafTree t.\n\nDefinition Elem := LeafTree A.\n*)\n\nInductive SubStack s : Type -> Type :=\n  Single : Buffer s -> Buffer s -> SubStack s s\n| Multiple : forall t,\n             Buffer s -> Buffer s -> \n             SubStack (prod s s) t -> \n             SubStack s t.\n\nInductive Deque s :=\n  Empty : Deque s\n| Full : forall t,\n         SubStack s t ->\n         Deque (prod t t) ->\n         Deque s.\n\nSet Maximal Implicit Insertion.\nImplicit Arguments Empty [s].\nUnset Maximal Implicit Insertion.\n\nDefinition toListBufferC t (x:Buffer t) r :=\n  match x with\n    | Zero => r\n    | One a => a::r\n    | Two a b => a::b::r\n    | Three a b c => a::b::c::r\n    | Four a b c d => a::b::c::d::r\n    | Five a b c d e => a::b::c::d::e::r\n  end.\n\n(*\nDefinition toListPairBufferC t (x:Buffer (prod t t)) r :=\n  match x with\n    | Zero => r\n    | One (a,b) => a::b::r\n    | Two (a,b) (c,d) => a::b::c::d::r\n    | Three (a,b) (c,d) (e,f) => a::b::c::d::e::f::r\n    | Four (a,b) (c,d) (e,f) (g,h) => a::b::c::d::e::f::g::h::r\n    | Five (a,b) (c,d) (e,f) (g,h) (i,j) => a::b::c::d::e::f::g::h::i::j::r\n  end.\n*)\n\nFixpoint unzipMix t (x:list (prod t t)) r :=\n  match x with\n    | nil => r\n    | (a,b)::tyl => a::b::(unzipMix tyl r)\n  end.\n\n(*\nRequire Import Program.\nRequire Import Coq.Logic.JMeq.\n*)\n(* Error: Library Coq.Logic.JMeq has to be required first. *)\n(*\nProgram Fixpoint toListSubStack t s (x:SubStack t s) (r:list s -> list s) : list t :=\n  match x with\n    | Single a b => toListBufferC a (r (toListBufferC b nil))\n    | Multiple _ a b tyl =>\n      toListBufferC a \n      (unzipMix (toListSubStack tyl r) \n        (toListBufferC b nil))\n  end.\n*)\n\nFixpoint toListSubStack t s (x:SubStack t s) : \n  (list s -> list s) -> list t :=\n  match x with\n    | Single a b => fun r => toListBufferC a (r (toListBufferC b nil))\n    | Multiple _ a b tyl => fun r => \n      toListBufferC a \n      (unzipMix (toListSubStack tyl r) \n        (toListBufferC b nil))\n  end.\n\nFixpoint toListDeque t (x:Deque t) : list t :=\n  match x with\n    | Empty => nil\n    | Full u hed tyl =>\n      toListSubStack hed (unzipMix (toListDeque tyl))\n  end. \n\nInductive Color :=\n  Red\n| Yellow\n| Green.\n\nDefinition bufferColor t (b:Buffer t) :=\n  match b with\n    | Two _ _ => Green\n    | Three _ _ _ => Green\n    | One _ => Yellow\n    | Four _ _ _ _ => Yellow\n    | _ => Red\n  end.\nHint Unfold bufferColor.\nHint Unfold length.\n\nDefinition minColor a b :=\n  match a with\n    | Red => Red\n    | Yellow => \n      match b with\n        | Red => Red\n        | _ => Yellow\n      end\n    | _ => b\n  end.\n\nDefinition bottomSubStackColor s t (x:SubStack s t) :=\n  match x with\n    | Single pre suf =>\n      match pre with\n        | Zero => bufferColor suf\n        | _ => \n          match suf with\n            | Zero => bufferColor pre\n            | _ => minColor (bufferColor pre) (bufferColor suf)\n          end\n      end\n    | Multiple _ pre suf _ => minColor (bufferColor pre) (bufferColor suf)\n  end.\n\nDefinition topSubStackColor s t (x:SubStack s t) :=\n  match x with\n    | Single pre suf =>\n        minColor (bufferColor pre) (bufferColor suf)\n    | Multiple _ pre suf _ => \n        minColor (bufferColor pre) (bufferColor suf)\n  end.\n\nDefinition dequeColor t (d:Deque t) :=\n  match d with\n    | Empty => None\n    | Full _ hed tyl => Some (\n      match tyl with\n        | Empty => bottomSubStackColor hed\n        | _ => topSubStackColor hed\n      end)\n  end.\n\nFixpoint allSubStackYellow (f:forall s t, SubStack s t -> Color) \n  s t (x:SubStack s t) :=\n  f _ _ x = Yellow /\\\n  match x with\n    | Single _ _ => True\n    | Multiple _ _ _ r => allSubStackYellow f r\n  end.\n\nDefinition tailStackColor (f: forall s t, SubStack s t -> Color)\n  s t (x:SubStack s t) :=\n  match x with\n    | Single _ _ => None\n    | Multiple _ _ _ r => Some (f _ _ r)\n  end.\n\nDefinition yellowOrNothing x :=\n  match x with\n    | None => True\n    | Some c =>\n      match c with\n        | Yellow => True\n        | _ => False\n      end\n  end.\n\nDefinition tailStackProp (f: forall s t, SubStack s t -> Prop)\n  s t (x:SubStack s t) :=\n  match x with\n    | Single _ _ => True\n    | Multiple _ _ _ r => f _ _ r\n  end.\n\nFixpoint restWellStacked s (x:Deque s) :=\n  match x with\n    | Empty => True\n    | Full _ hed tyl =>\n      match tyl with\n        | Empty => \n          bottomSubStackColor hed <> Yellow\n          /\\\n          tailStackProp (allSubStackYellow bottomSubStackColor) hed\n        | _ =>\n          topSubStackColor hed <> Yellow\n          /\\\n          tailStackProp (allSubStackYellow topSubStackColor) hed\n          /\\\n          restWellStacked tyl\n      end\n  end.\n\nDefinition wellStacked s (x:Deque s) :=\n  match x with\n    | Empty => True\n    | Full _ hed tyl =>\n      match tyl with\n        | Empty => tailStackProp (allSubStackYellow bottomSubStackColor) hed\n        | _ => \n          tailStackProp (allSubStackYellow topSubStackColor) hed\n          /\\\n          restWellStacked tyl\n      end\n  end.\n\nFixpoint topDequeColors s (x:Deque s) :=\n  match x with\n    | Empty => nil\n    | Full _ hed tyl =>\n      match tyl with\n        | Empty => (bottomSubStackColor hed) :: nil\n        | _ => (topSubStackColor hed) :: (topDequeColors tyl)\n      end\n  end.\n\nFixpoint semiRegularColorListGreenBeforeRed x :=\n  match x with\n    | nil => True\n    | y::ys =>\n      match y with\n        | Red => False\n        | Green => semiRegularColorList ys\n        | Yellow => semiRegularColorListGreenBeforeRed ys\n      end\n  end\nwith semiRegularColorList x :=\n  match x with\n    | nil => True\n    | y::ys =>\n      match y with\n        | Red => semiRegularColorListGreenBeforeRed ys\n        | _ => semiRegularColorList ys\n      end\n  end.\n\nFixpoint nonEmptySubStack t s (x:SubStack t s) :=\n  match x with\n    | Single pre suf => \n      match pre, suf with\n        | Zero,Zero => False\n        | _,_ => True\n      end\n    | Multiple _ pre suf tyl =>\n        (match pre, suf with\n           | Zero,Zero => False\n           | _,_ => True\n         end)\n        /\\\n        nonEmptySubStack tyl\n  end.\n\n(* Full deques are not empty *)\nFixpoint fullDequeIs t (d:Deque t) :=\n  match d with\n    | Empty => True\n    | Full _ hed tyl =>\n      match tyl with\n        | Empty => nonEmptySubStack hed\n        | _ =>\n          nonEmptySubStack hed \n          /\\\n          fullDequeIs tyl\n      end\n  end.\n\nFixpoint eachBufferSubStack (f: forall a, Buffer a -> Prop) \n  s t (x:SubStack s t) :=\n  match x with\n    | Single pre suf => f _ pre /\\ f _ suf\n    | Multiple _ pre suf tyl => f _ pre /\\ f _ suf /\\ eachBufferSubStack f tyl\n  end.\n\nFixpoint eachSubStackDeque (f:forall s t, SubStack s t -> Prop)\n  s (x:Deque s) :=\n  match x with\n    | Empty => True\n    | Full _ hed tyl =>\n      f _ _ hed /\\ eachSubStackDeque f tyl\n  end.\n\nDefinition semiRegular s (x:Deque s) :=\n  wellStacked x\n  /\\\n  fullDequeIs x\n  /\\\n(*  eachSubStackDeque (eachBufferSubStack bufferSize) x\n  /\\*)\n  semiRegularColorList (topDequeColors x).\nHint Unfold semiRegular.\n\nFixpoint topNonYellowIsGreen x :=\n  match x with\n    | nil => True\n    | y::ys =>\n      match y with\n        | Red => False\n        | Yellow => topNonYellowIsGreen ys\n        | Green => True\n      end\n  end.\n\n(*\nFixpoint regularColorList x :=\n  topNonYellowIsGreen x\n  /\\\n  semiRegularColorList x.\n*)\n\nDefinition regular s (x:Deque s) :=\n  semiRegular x\n  /\\\n  topNonYellowIsGreen (topDequeColors x).\nHint Unfold regular.\n\nDefinition restoreBottom t (pre suf:Buffer t) : Deque t :=\n  match pre,suf with\n    | Zero,Five a b c d e => \n      Full (Single (Two a b) (Three c d e)) Empty\n    | One a,Five b c d e f => \n      Full (Single (Three a b c) (Three d e f)) Empty\n    | Two a b,Five c d e f g => \n      Full (Single (Three a b c) (Four d e f g)) Empty\n    | Three a b c,Five d e f g h => \n      Full (Single (Four a b c d) (Four e f g h)) Empty\n    | Four a b c d,Five e f g h i => \n      Full (Multiple (Four a b c d) (Three g h i) \n        (Single Zero (One (e,f)))) Empty\n    | Five a b c d e,Five f g h i j => \n      Full (Multiple (Three a b c) (Three h i j) \n        (Single (One (d,e)) (One (f,g)))) Empty\n      \n    | Five a b c d e, Zero => \n      Full (Single (Two a b) (Three c d e)) Empty\n    | Five a b c d e, One f => \n      Full (Single (Three a b c) (Three d e f)) Empty\n    | Five a b c d e, Two f g => \n      Full (Single (Three a b c) (Four d e f g)) Empty\n    | Five a b c d e, Three f g h => \n      Full (Single (Four a b c d) (Four e f g h)) Empty\n    | Five a b c d e, Four f g h i => \n      Full (Multiple (Four a b c d) (Three g h i) \n        (Single Zero (One (e,f)))) Empty\n      \n    | _,_ => Full (Single pre suf) Empty\n  end.\n\nLtac cutThis x :=\n  let xx := fresh \n    in remember x as xx; destruct xx.\n\nLtac pisp t := try subst;\n  unfold bufferColor in *; unfold not; intros; \n    simpl in *; auto; t;\n  match goal with\n    | [H:Red=Yellow |- _] => inversion H;  pisp t\n    | [H:Red=Green |- _] => inversion H;  pisp t\n    | [H:Yellow=Green |- _] => inversion H;  pisp t\n    | [H:Yellow=Red |- _] => inversion H;  pisp t\n    | [H:Green=Red |- _] => inversion H;  pisp t\n    | [H:Green=Yellow |- _] => inversion H;  pisp t\n    | [ H : true = false |- _] => inversion H;  pisp t\n    | [ H : None = Some ?a |- _] => inversion H;  pisp t\n    | [ H : Some ?a = None |- _] => inversion H;  pisp t\n    | [ H : False |- _] => inversion H;  pisp t\n\n    | [ H : True |- _] => clear H; pisp t\n    | [ H : ?a = ?a |- _] => clear H;  pisp t\n\n    | [ H : Some ?a = Some ?b |- _] => inversion_clear H; subst;  pisp t\n    | [ |- regular (Full _ _) ] => unfold regular;  pisp t\n    | [ H : semiRegular (Full _ _) |- _] => unfold semiRegular in H;  pisp t\n    | [ |- semiRegular (Full _ _) ] => unfold semiRegular;  pisp t\n\n    | [H : ?A \\/ ?B |- _] => destruct H;  pisp t\n    | [ H : _ /\\ _ |- _ ] => destruct H;  pisp t\n    | [ |- _ /\\ _ ] => split;  pisp t\n\n    | [ |- context[\n      match ?x with\n         | Single _ _ => _\n         | Multiple _ _ _ _ => _ \n       end]] => destruct x; pisp t\n    | [ |- context\n      [match ?x with\n         | Zero => _\n         | One _ => _ \n         | Two _ _ => _\n         | Three _ _ _ => _\n         | Four _ _ _ _ => _\n         | Five _ _ _ _ _ => _\n       end]] => destruct x; pisp t\n    | [ H : prod _ _ |- _] => cutThis H; pisp t\n(*    | [ |- context\n      [let (_,_) := ?x in _]] => destruct x; pisp t *)\n    | _ => auto\n  end.\n\nLtac asp := progress pisp auto.\n\nLemma restoreBottomDoes :\n  forall t (pre suf:Buffer t), \n    semiRegular (Full (Single pre suf) Empty) ->\n    regular (restoreBottom pre suf).\nProof.\n  intros.\n  destruct pre; asp.\nQed.\nHint Resolve restoreBottomDoes.\n\nLemma restoreBottomPreserves :\n  forall t (pre suf:Buffer t), \n    let x := (Full (Single pre suf) Empty) in\n      semiRegular x ->\n      toListDeque (restoreBottom pre suf) = toListDeque x.\nProof.\n  intros.\n  destruct pre; asp.\nQed.\nHint Resolve restoreBottomPreserves.\n\nDefinition restoreOneYellowBottom\n  T (p1 s1:Buffer T) (p2 s2:Buffer (prod T T)) : option (Deque T) :=\n  match p1,p2,s2,s1 with\n    | Zero,Zero,One (a,b),Five c d e f g => \n      Some (Full (Single (Three a b c) (Four d e f g)) Empty)\n    | Zero,Zero,Four (a,b) cd ef gh,Five i j k l m => \n      Some (Full \n      (Single (Two a b) (Three k l m))\n        (Full (Single (Two cd ef) (Two gh (i,j))) Empty))\n\n    | Zero,One (a,b),Zero,Five c d e f g =>\n      Some (Full (Single (Three a b c) (Four d e f g)) Empty)\n    | Zero,One (a,b),One (c,d), Five e f g h i =>\n      Some (\n        Full (Multiple (Four a b c d) (Three g h i) \n          (Single Zero (One (e,f)))) Empty)\n    | Zero,One (a,b),Two (c,d) (e,f), Five g h i j k =>\n      Some (\n        Full (Multiple (Four a b c d) (Three i j k) \n          (Single (One (e,f)) (One (g,h)))) Empty)\n    | Zero,One (a,b),Three (c,d) (e,f) (g,h), Five i j k l m =>\n      Some (\n        Full (Multiple (Four a b c d) (Three k l m) \n          (Single (One (e,f)) (Two (g,h) (i,j)))) Empty)\n    | Zero,One (a,b),Four (c,d) (e,f) (g,h) (i,j), Five k l m n o=>\n      Some (\n        Full (Multiple (Four a b c d) (Three m n o) \n          (Single (One (e,f)) (Three (g,h) (i,j) (k,l)))) Empty)\n\n    | Zero,Two (a,b) (c,d), One (e,f), Five g h i j k =>\n      Some (\n        Full (Multiple (Four a b c d) (Three i j k) \n          (Single (One (e,f)) (One (g,h)))) Empty)\n    | Zero,Two (a,b) (c,d),Four (e,f) (g,h) (i,j) (k,l), Five m n o p q=>\n      Some (\n        Full (Multiple (Four a b c d) (Three o p q) \n          (Single (One (e,f)) (Four (g,h) (i,j) (k,l) (m,n)))) Empty)\n\n    | Zero,Three (a,b) (c,d) (e,f), One (g,h), Five i j k l m=>\n      Some (\n        Full (Multiple (Four a b c d) (Three k l m) \n          (Single (One (e,f)) (Two (g,h) (i,j)))) Empty)\n    | Zero,Three (a,b) (c,d) (e,f), Four (g,h) (i,j) (k,l) (m,n), Five o p q r s =>\n      Some (\n        Full (Multiple (Four a b c d) (Three q r s) \n          (Single (Two (e,f) (g,h)) (Four (i,j) (k,l) (m,n) (o,p)))) Empty)\n\n    |_,_,_,_ => None\n  end.\n\nLemma restoreOneYellowBottomDoes :\n  forall t (p1 s1:Buffer t) p2 s2,\n    semiRegular (Full (Multiple p1 s1 (Single p2 s2)) Empty) ->\n    match restoreOneYellowBottom p1 s1 p2 s2 with\n      | None => True\n      | Some v => regular v\n    end.\nProof.\n  intros.\n  destruct p1; asp.\nQed.\n\nLemma restoreOneYellowBottomPreserves :\n  forall t (p1 s1:Buffer t) p2 s2,\n    let x := (Full (Multiple p1 s1 (Single p2 s2)) Empty) in\n    semiRegular x ->\n    match restoreOneYellowBottom p1 s1 p2 s2 with\n      | None => True\n      | Some v => toListDeque x = toListDeque v\n    end.\nProof.\n  intros.\n  destruct p1; asp.\nQed.\n\n\nLemma restoreBottomPreserves :\n  forall t (pre suf:Buffer t), \n    let x := (Full (Single pre suf) Empty) in\n      semiRegular x ->\n      toListDeque (restoreBottom pre suf) = toListDeque x.\nProof.\n  intros.\n  destruct pre; asp.\nQed.\nHint Resolve restoreBottomPreserves.\n\n\n(Four a b c d) (Three g h i) \n        (Single Zero (One (e,f)))) Empty\n    | Zero,One a,Zero,Five b c d e f =>\n      Full (Single (Three a b c) (Three d e f)) Empty\n    | Zero,One a,One b,Five c d e f g =>\n      Full (Single (Three a b c) (Four d e f g)) Empty\n    | Zero,One a,One b,Five c d e f g =>\n      Full (Single (Three a b c) (Four d e f g)) Empty\n\n\n\n\n\n    | One a,Five b c d e f => \n      Full (Single (Three a b c) (Three d e f)) Empty\n    | Two a b,Five c d e f g => \n      Full (Single (Three a b c) (Four d e f g)) Empty\n    | Three a b c,Five d e f g h => \n      Full (Single (Four a b c d) (Four e f g h)) Empty\n    | Four a b c d,Five e f g h i => \n      Full (Multiple (Four a b c d) (Three g h i) \n        (Single Zero (One (e,f)))) Empty\n    | Five a b c d e,Five f g h i j => \n      Full (Multiple (Three a b c) (Three h i j) \n        (Single (One (d,e)) (One (f,g)))) Empty\n      \n    | Five a b c d e, Zero => \n      Full (Single (Two a b) (Three c d e)) Empty\n    | Five a b c d e, One f => \n      Full (Single (Three a b c) (Three d e f)) Empty\n    | Five a b c d e, Two f g => \n      Full (Single (Three a b c) (Four d e f g)) Empty\n    | Five a b c d e, Three f g h => \n      Full (Single (Four a b c d) (Four e f g h)) Empty\n    | Five a b c d e, Four f g h i => \n      Full (Multiple (Four a b c d) (Three g h i) \n        (Single Zero (One (e,f)))) Empty\n      \n    | _,_ => Full (Single pre suf) Empty\nend\n\nDefinition restore s (x:Deque s) : option (Deque s) :=\n  match x with\n    | Empty => Some Empty\n    | Full _ y ys =>\n      match ys with\n        | Empty =>\n          match y with\n            | Single pre suf => \n              Some (restoreBottom pre suf)\n            | Multiple _ pre suf tyl => \n              match tyl with\n                | Single p2 s2 => None\n                | Multiple _ p2 s2 _ => None\n              end \n          end\n        | _ => None\n      end\n  end.\n\nLemma regEmpty : forall s, regular (@Empty s).\nProof.\n  intros.\n  unfold regular.\n  unfold semiRegular; unfold topNonYellowIsGreen; unfold topDequeColors;\n    asp.\nQed.\nHint Resolve regEmpty.\n\nLemma restoreDoes :\n  forall s (x:Deque s), semiRegular x ->\n    match restore x with\n      | None => True\n      | Some v => regular v\n    end.\nProof.\n  intros.\n  destruct x; simpl in *; auto.\n  destruct x; simpl in *; auto.\n  destruct s0; auto.\n  destruct s0; auto.\nQed.\nLemma restorePreserves :\n  forall s (x:Deque s), semiRegular x ->\n    match restore x with\n      | None => True\n      | Some v => toListDeque v = toListDeque x\n    end.\nProof.\n  intros.\n  destruct x; simpl in *; auto.\n  destruct x; simpl in *; auto.\n  destruct s0; auto.\n  apply restoreBottomPreserves; auto.\n  destruct s0; auto.\nQed.\n\n\n\nDefinition restore s (x:Deque s) : option (Deque s) :=\n  match x with\n    | Empty => Some Empty\n    | Full _ y ys =>\n      match ys with\n        | Empty =>\n          match bottomSubStackColor y with\n            | Green => Some x\n            | Yellow => Some x              \n            | Red => \n              match y with\n                | Single pre suf => \n                  match pre,suf with\n\n                    | Zero,Five a b c d e => \n                      Some (Full (Single (Two a b) (Three c d e)) Empty)\n                    | One a,Five b c d e f => \n                      Some (Full (Single (Three a b c) (Three d e f)) Empty)\n                    | Two a b,Five c d e f g => \n                      Some (Full (Single (Three a b c) (Four d e f g)) Empty)\n                    | Three a b c,Five d e f g h => \n                      Some (Full (Single (Four a b c d) (Four e f g h)) Empty)\n                    | Four a b c d,Five e f g h i => \n                      Some (Full (Multiple (Four a b c d) (Three g h i) \n                        (Single Zero (One (e,f)))) Empty)\n                    | Five a b c d e,Five f g h i j => \n                      Some (Full (Multiple (Three a b c) (Three h i j) \n                        (Single (One (d,e)) (One (f,g)))) Empty)\n\n                    | Five a b c d e, Zero => \n                      Some (Full (Single (Two a b) (Three c d e)) Empty)\n                    | Five a b c d e, One f => \n                      Some (Full (Single (Three a b c) (Three d e f)) Empty)\n                    | Five a b c d e, Two f g => \n                      Some (Full (Single (Three a b c) (Four d e f g)) Empty)\n                    | Five a b c d e, Three f g h => \n                      Some (Full (Single (Four a b c d) (Four e f g h)) Empty)\n                    | Five a b c d e, Four f g h i => \n                      Some (Full (Multiple (Four a b c d) (Three g h i) \n                        (Single Zero (One (e,f)))) Empty)\n\n                    | _,_ => Some x\n                  end\n                | Multiple _ pre suf tyl => \n                  match pre,suf with\n                    | Zero,Five a b c d e => \n                      match tyl with\n                        | Single p2 s2 =>\n                          match s2 with\n                            | Zero => \n                              Some (Full (Multiple Zero (Three c d e) (Single p2 (One (a,b)))) Empty)\n                            | _ => None\n                          end\n                        | _ => None\n                      end \n                    | _,_ => None\n                  end\n(*\n                    | One a,Five b c d e f => \n                      Some (Full (Single (Three a b c) (Three d e f)) Empty)\n                    | Two a b,Five c d e f g => \n                      Some (Full (Single (Three a b c) (Four d e f g)) Empty)\n                    | Three a b c,Five d e f g h => \n                      Some (Full (Single (Four a b c d) (Four e f g h)) Empty)\n                    | Four a b c d,Five e f g h i => \n                      Some (Full (Multiple (Four a b c d) (Three g h i) \n                        (Single Zero (One (e,f)))) Empty)\n                    | Five a b c d e,Five f g h i j => \n                      Some (Full (Multiple (Three a b c) (Three h i j) \n                        (Single (One (d,e)) (One (f,g)))) Empty)\n\n                    | Five a b c d e, Zero => \n                      Some (Full (Single (Two a b) (Three c d e)) Empty)\n                    | Five a b c d e, One f => \n                      Some (Full (Single (Three a b c) (Three d e f)) Empty)\n                    | Five a b c d e, Two f g => \n                      Some (Full (Single (Three a b c) (Four d e f g)) Empty)\n                    | Five a b c d e, Three f g h => \n                      Some (Full (Single (Four a b c d) (Four e f g h)) Empty)\n                    | Five a b c d e, Four f g h i => \n                      Some (Full (Multiple (Four a b c d) (Three g h i) \n                        (Single Zero (One (e,f)))) Empty)\n\n                    | _,_ => Some x\n\n                  match tyl with\n                    | Single pre1 suf1 =>\n                      match pre1 with\n                        | Zero =>\n                          match suf1 with\n                            | Zero => Some x\n                            | _ => None\n                          end\n                        | _ => None\n                      end\n                    | _ => None\n                  end*)\n              end\n          end\n        | _ => None\n      end\n  end.\n\n(*\n      match topSubStackColor y with\n        | Green => x\n        | Yellow => restoreRest ys\n        | Red =>\n*)\n\nLtac cutThis x :=\n  let xx := fresh \n    in remember x as xx; destruct xx.\n\nLtac pisp t := try subst;\n  unfold bufferColor in *; simpl in *; auto; t; \n  match goal with\n    | [H:Red=Yellow |- _] => inversion H;  pisp t\n    | [H:Red=Green |- _] => inversion H;  pisp t\n    | [H:Yellow=Green |- _] => inversion H;  pisp t\n    | [H:Yellow=Red |- _] => inversion H;  pisp t\n    | [H:Green=Red |- _] => inversion H;  pisp t\n    | [H:Green=Yellow |- _] => inversion H;  pisp t\n    | [ H : true = false |- _] => inversion H;  pisp t\n    | [ H : None = Some ?a |- _] => inversion H;  pisp t\n    | [ H : Some ?a = None |- _] => inversion H;  pisp t\n    | [ H : False |- _] => inversion H;  pisp t\n\n    | [ H : True |- _] => clear H; pisp t\n    | [ H : ?a = ?a |- _] => clear H;  pisp t\n\n\n    | [ H : Some ?a = Some ?b |- _] => inversion_clear H; subst;  pisp t\n    | [ |- regular (Full _ _) ] => unfold regular;  pisp t\n    | [ H : semiRegular (Full _ _) |- _] => unfold semiRegular in H;  pisp t\n    | [ |- semiRegular (Full _ _) ] => unfold semiRegular;  pisp t\n(*\n    | [ _ : context[length ?a] |- _] => destruct a; pisp t\n*)\n    | [H : ?A \\/ ?B |- _] => destruct H;  pisp t\n    | [ H : _ /\\ _ |- _ ] => destruct H;  pisp t\n    | [ |- _ /\\ _ ] => split;  pisp t\n\n(*\n    | [ _ : _ = \n      match ?x with\n         | Single _ _ => _\n         | Multiple _ _ _ _ => _ \n       end |- _] => cutThis x; pisp t\n*)\n    | [ |- context[\n      match ?x with\n         | Single _ _ => _\n         | Multiple _ _ _ _ => _ \n       end]] => destruct x; pisp t\n    | [ |- context\n      [match ?x with\n         | Zero => _\n         | One _ => _ \n         | Two _ _ => _\n         | Three _ _ _ => _\n         | Four _ _ _ _ => _\n         | Five _ _ _ _ _ => _\n       end]] => destruct x; pisp t\n\n(*\n    | [ _ : context[bufferColor (?a :: ?b :: ?c :: ?d :: ?e)] |- _]\n      => destruct e; pisp t\n    | [ _ : context[bufferColor (?a :: ?b :: ?c :: ?e)] |- _]\n      => destruct e; pisp t\n    | [ _ : context[bufferColor (?a :: ?b :: ?e)] |- _]\n      => destruct e; pisp t\n(*    | [ _ : context[bufferColor (?a :: ?e)] |- _]\n      => destruct e; pisp t*)\n*)\n    | _ => auto\n  end.\n\nLtac asp := progress pisp auto.\n\nLemma regEmpty : forall s, regular (@Empty s).\nProof.\n  intros.\n  unfold regular.\n  unfold semiRegular; unfold topNonYellowIsGreen; unfold topDequeColors;\n    asp.\nQed.\nHint Resolve regEmpty.\n\n\nLemma restoreDoes :\n  forall s (x:Deque s), semiRegular x ->\n    match restore x with\n      | None => True\n      | Some v => regular v\n    end.\nProof.\n  intros.\n  destruct x.\n  Focus 2.\n  simpl.\n  destruct x; simpl.\n  destruct s0; simpl.\n  Focus 2.\n  destruct s0.\n  destruct b2.\n  destruct b0.\n  Focus 6.\n  destruct b.\n  simpl in *.\n  unfold regular in *.\n  unfold semiRegular in *.\n  destruct H. destruct H0.\n  split. split.\n  simpl in *. asp.\n  asp.\n  simpl.\n  asp.\n  split. \n  asp.\n  destruct x; asp;\n    destruct x; asp.\n  Focus 2.\n  destruct b1; asp.\nQed.\n\nLemma restorePreserves :\n  forall s (x:Deque s), semiRegular x ->\n    match restore x with\n      | None => True\n      | Some v => toListDeque v = toListDeque x\n    end.\nProof.\n  intros.\n  destruct x; asp;\n    destruct x; asp.\nQed.\n\nEnd Carrier.\n\nExtraction Language Haskell.\nRecursive Extraction dequeColor.\n\nLemma help : \n  forall t (p q:t), proj1 (conj p q) = p.\nProof.\n  Print proj1.\n  unfold proj1.\n  simpl.\n\n\n         \n\n", "meta": {"author": "jbapple", "repo": "priority-queues", "sha": "559defbdace49e17d65893eb03577afa8403d767", "save_path": "github-repos/coq/jbapple-priority-queues", "path": "github-repos/coq/jbapple-priority-queues/priority-queues-559defbdace49e17d65893eb03577afa8403d767/util/ColorDeque.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.29292221432329485}}
{"text": "Require Import Crypto.Compilers.Syntax.\nRequire Import Crypto.Compilers.Wf.\nRequire Import Crypto.Util.Tactics.CacheTerm.\nRequire Import Crypto.Util.Tactics.Head.\nRequire Import Crypto.Util.Tactics.SplitInContext.\nRequire Import Crypto.Util.NatUtil.\nRequire Import Crypto.Util.Tactics.Not.\nRequire Import Crypto.Util.Tactics.BreakMatch.\n\nSection lang.\n  Context {base_type}\n          {op : flat_type base_type -> flat_type base_type -> Type}\n          {interp_base_type : base_type -> Type}\n          {interp_op : forall s d, op s d\n                                   -> interp_flat_type interp_base_type s\n                                   -> interp_flat_type interp_base_type d}.\n  Local Notation Expr := (@Expr base_type op).\n  Local Notation Interp := (@Interp base_type interp_base_type op interp_op).\n\n  Definition packaged_expr_functionP A :=\n    (fun F : Expr A -> Expr A\n     => forall e',\n         Wf e'\n         -> Wf (F e')\n            /\\ forall v, Interp (F e') v = Interp e' v).\n  Local Notation packaged_expr_function A :=\n    (sig (packaged_expr_functionP A)).\n\n  Definition compose {A} (f g : packaged_expr_function A)\n    : packaged_expr_function A.\n  Proof.\n    exists (fun x => proj1_sig f (proj1_sig g x)).\n    clear.\n    abstract (\n        destruct f as [f Hf], g as [g Hg]; cbn [proj1_sig];\n        intros e' Wfe; split; [ apply Hf, Hg, Wfe | ];\n        intro x; etransitivity; [ apply Hf, Hg, Wfe | apply Hg, Wfe ]\n      ).\n  Defined.\n\n  Definition id_package {A} : packaged_expr_function A\n    := exist (packaged_expr_functionP A)\n             id\n             (fun e' Wfe' => conj Wfe' (fun v => eq_refl)).\n\n  Inductive reified_transformation :=\n  | base (idx : nat)\n  | transform (idx : nat) (rest : reified_transformation)\n  | cond (test : bool) (iftrue iffalse : reified_transformation).\n  Fixpoint denote {A}\n           (ls : list (packaged_expr_function A))\n           (ls' : list { x : Expr A | Wf x })\n           default\n           (f : reified_transformation)\n    := match f with\n       | base idx => proj1_sig (List.nth_default default ls' idx)\n       | transform idx rest\n         => proj1_sig (List.nth_default id_package ls idx)\n                      (denote ls ls' default rest)\n       | cond test iftrue iffalse\n         => if test\n            then denote ls ls' default iftrue\n            else denote ls ls' default iffalse\n       end.\n  Fixpoint reduce (f : reified_transformation) : reified_transformation\n    := match f with\n       | base idx => base idx\n       | transform idx rest => reduce rest\n       | cond test iftrue iffalse\n         => match reduce iftrue, reduce iffalse with\n            | base idx0 as t, base idx1 as f\n              => if nat_beq idx0 idx1\n                 then base idx0\n                 else cond test t f\n            | t, f => cond test t f\n            end\n       end.\n  Lemma Wf_denote A ctx es d f : Wf (@denote A ctx es d f).\n  Proof.\n    induction f; simpl; unfold proj1_sig; break_innermost_match; split_and; auto.\n    match goal with H : _ |- _ => apply H; assumption end.\n  Qed.\n  Lemma Wf_denote_iff_True A ctx es d f : Wf (@denote A ctx es d f) <-> True.\n  Proof. split; auto using Wf_denote. Qed.\n  Lemma Interp_denote_reduce A ctx es d f\n    : forall v, Interp (@denote A ctx es d f) v = Interp (@denote A nil es d (reduce f)) v.\n  Proof.\n    induction f; simpl; unfold proj1_sig; break_innermost_match;\n      nat_beq_to_eq; subst;\n        try reflexivity; auto.\n    intro; rewrite <- IHf.\n    match goal with H : _ |- _ => apply H, Wf_denote end.\n  Qed.\nEnd lang.\n\nLocal Ltac find ctx f :=\n  lazymatch ctx with\n  | (exist _ f _ :: _)%list => constr:(0)\n  | (_ :: ?ctx)%list\n    => let v := find ctx f in\n       constr:(S v)\n  end.\n\nLocal Ltac reify_transformation interp_base_type interp_op ctx es T cont :=\n  let reify_transformation := reify_transformation interp_base_type interp_op in\n  let ExprA := type of T in\n  let packageP := lazymatch type of T with\n                 | @Expr ?base_type_code ?op ?A\n                   => constr:(@packaged_expr_functionP base_type_code op interp_base_type interp_op A)\n                 end in\n  let es := lazymatch es with\n            | tt => constr:(@nil { x : ExprA | Wf x })\n            | _ => es\n            end in\n  let ctx := lazymatch ctx with\n             | tt => constr:(@nil (sig packageP))\n             | _ => ctx\n             end in\n  lazymatch T with\n  | ?f ?e\n    => let ctx := lazymatch ctx with\n                  | context[exist _ f _] => ctx\n                  | _ => let hf := head f in\n                         let fId := fresh hf in\n                         let rfPf :=\n                             cache_proof_with_type_by\n                               (packageP f)\n                               ltac:(refine (fun e Hwf\n                                             => (fun Hwf'\n                                                 => conj Hwf' (fun v => _)) _);\n                                     [ autorewrite with reflective_interp; reflexivity\n                                     | auto with wf ])\n                                      fId in\n                         constr:(cons (exist packageP f rfPf)\n                                      ctx)\n                  end in\n       reify_transformation\n         ctx es e\n         ltac:(fun ctx es re\n               => let idx := find ctx f in\n                  cont ctx es (transform idx re))\n  | match ?b with true => ?t | false => ?f end\n    => reify_transformation\n         ctx es t\n         ltac:(fun ctx es rt\n               => reify_transformation\n                    ctx es f\n                    ltac:(fun ctx es rf\n                          => reify_transformation\n                               ctx es t\n                               ltac:(fun ctx es rt\n                                     => cont ctx es (cond b rt rf))))\n  | _ => let es := lazymatch es with\n                   | context[exist _ T _] => es\n                   | _\n                     => let Hwf := lazymatch goal with\n                                   | [ Hwf : Wf T |- _ ] => Hwf\n\n                                   | _\n                                     => let Hwf := fresh \"Hwf\" in\n                                        cache_proof_with_type_by\n                                          (Wf T)\n                                          ltac:(idtac; solve_wf_side_condition)\n                                                 Hwf\n                                   end in\n                        constr:(cons (exist Wf T Hwf) es)\n                   end in\n         let idx := find es T in\n         cont ctx es (base idx)\n  end.\nLtac finish_rewrite_reflective_interp_cached :=\n  rewrite ?Wf_denote_iff_True;\n  cbv [reduce nat_beq];\n  try (rewrite Interp_denote_reduce;\n       cbv [reduce nat_beq];\n       cbv [denote List.nth_default List.nth_error];\n       cbn [proj1_sig]).\nLtac rewrite_reflective_interp_cached_then ctx es cont :=\n  let e := match goal with\n           | [ |- context[@Interp _ _ _ _ _ ?e] ]\n             => let test := match goal with _ => not is_var e end in\n                e\n           end in\n  lazymatch goal with\n  | [ |- context[@Interp ?base_type ?interp_base_type ?op ?interp_op _ e] ]\n    => reify_transformation\n         interp_base_type interp_op ctx es e\n         ltac:(fun ctx es r\n               => lazymatch es with\n                  | cons ?default _\n                    => change e with (denote ctx es default r)\n                  end;\n                  finish_rewrite_reflective_interp_cached;\n                  cont ctx es)\n  end.\nLtac rewrite_reflective_interp_cached :=\n  rewrite_reflective_interp_cached_then tt tt ltac:(fun _ _ => idtac).\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/InterpRewriting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2929222070130459}}
{"text": "Require Import Util LengthEq AllInRel Map Envs DecSolve.\nRequire Import IL Annotation AutoIndTac Exp SetOperations.\nRequire Export Liveness.Liveness Filter LabelsDefined OUnion.\n\nSet Implicit Arguments.\n\n(** * Specification of True Liveness *)\n\nLocal Hint Resolve incl_empty minus_incl incl_right incl_left.\n\nInductive argsLive (Caller Callee:set var) : args -> params -> Prop :=\n| AL_nil : argsLive Caller Callee nil nil\n| AL_cons y z Y Z\n  : argsLive Caller Callee Y Z\n    -> (z ∈ Callee -> live_op_sound y Caller)\n    -> argsLive Caller Callee (y::Y) (z::Z).\n\nLemma argsLive_length lv bv Y Z\n  : argsLive lv bv Y Z\n    -> length Y = length Z.\nProof.\n  intros. general induction H; simpl; eauto.\nQed.\n\nHint Resolve argsLive_length : len.\n\nLemma argsLive_liveSound lv blv Y Z\n  : argsLive lv blv Y Z\n    -> forall (n : nat) (y : op),\n      get (filter_by (fun y : var => B[y ∈ blv]) Z Y) n y ->\n      live_op_sound y lv.\nProof.\n  intros. general induction H; simpl in * |- *.\n  - isabsurd.\n  - decide (z ∈ blv); eauto.\n    inv H1; eauto.\nQed.\n\nLemma argsLive_live_exp_sound lv blv Y Z y z n\n  : argsLive lv blv Y Z\n    -> get Y n y\n    -> get Z n z\n    -> z ∈ blv\n    -> live_op_sound y lv.\nProof.\n  intros. general induction n; invt argsLive; isabsurd; eauto.\nQed.\n\nLemma live_exp_sound_argsLive lv blv Y Z\n  : length Y = length Z\n    -> (forall n y z, get Y n y -> get Z n z -> z ∈ blv -> live_op_sound y lv)\n    -> argsLive lv blv Y Z.\nProof.\n  intros. length_equify.\n  general induction H; eauto 20 using argsLive, get.\nQed.\n\nLemma argsLive_agree_on' (V E E':onv val) lv blv Y Z v v'\n  :  argsLive lv blv Y Z\n     -> agree_on eq lv E E'\n     -> omap (op_eval E) Y = Some v\n     -> omap (op_eval E') Y = Some v'\n     -> agree_on eq blv (V [Z <-- List.map Some v]) (V [Z <-- List.map Some v']).\nProof.\n  intros. general induction H; simpl in * |- *; eauto.\n  - monad_inv H2. monad_inv H3.\n    decide (z ∈ blv).\n    +erewrite <- op_eval_live in EQ0; eauto.\n     *  assert (x1 = x) by congruence.\n        subst. simpl.\n        eauto using agree_on_update_same, agree_on_incl.\n    + eapply agree_on_update_dead_both; eauto.\nQed.\n\nLemma argsLive_agree_on (V V' E E':onv val) lv blv Y Z v v'\n  : agree_on eq (blv \\ of_list Z) V V'\n    -> argsLive lv blv Y Z\n    -> agree_on eq lv E E'\n    -> omap (op_eval E) Y = Some v\n    -> omap (op_eval E') Y = Some v'\n    -> agree_on eq blv (V [Z <-- List.map Some v]) (V' [Z <-- List.map Some v']).\nProof.\n  intros. etransitivity; eauto using argsLive_agree_on'.\n  eapply update_with_list_agree; eauto with len.\nQed.\n\nLemma filter_by_incl_argsLive lv blv Y Z\n  : ❬Y❭ = ❬Z❭\n    -> list_union (Ops.freeVars ⊝ filter_by (fun x => if [x \\In blv] then true else false) Z Y) ⊆ lv\n    -> argsLive lv blv Y Z.\nProof.\n  intros LEN INCL. length_equify.\n  general induction LEN; simpl in *; eauto using argsLive.\n  - econstructor.\n    + cases in INCL; try congruence; eauto.\n      * eapply IHLEN. rewrite <- INCL.\n        simpl List.map. rewrite list_union_cons. eauto with cset.\n    + intros. cases in INCL.\n      simpl List.map in INCL.\n      rewrite list_union_cons in INCL.\n      eapply live_op_sound_incl;[eapply Ops.live_freeVars|].\n      rewrite <- INCL. eauto with cset.\nQed.\n\n(** ** The inductive predicate *)\n\nInductive true_live_sound (i:overapproximation)\n  : list params -> list (set var) -> stmt -> ann (set var) -> Prop :=\n| TLOpr ZL Lv x b lv e al\n  :  true_live_sound i ZL Lv b al\n     -> (x ∈ getAnn al \\/ isCall e ->live_exp_sound e lv)\n     -> (getAnn al\\ singleton x) ⊆ lv\n     -> true_live_sound i ZL Lv (stmtLet x e b) (ann1 lv al)\n| TLIf ZL Lv e b1 b2 lv al1 al2\n  :  true_live_sound i ZL Lv b1 al1\n     -> true_live_sound i ZL Lv b2 al2\n     -> live_op_sound e lv\n     -> getAnn al1 ⊆ lv\n     -> getAnn al2 ⊆ lv\n     -> true_live_sound i ZL Lv (stmtIf e b1 b2) (ann2 lv al1 al2)\n| TLGoto ZL Lv l Y lv blv Z\n  : get ZL (counted l) Z\n    -> get Lv (counted l) blv\n    -> (if isImperative i then  (blv \\ of_list Z ⊆ lv) else True)\n    -> argsLive lv blv Y Z\n    -> length Y = length Z\n    -> true_live_sound i ZL Lv (stmtApp l Y) (ann0 lv)\n| TLReturn ZL Lv e lv\n  : live_op_sound e lv\n    -> true_live_sound i ZL Lv (stmtReturn e) (ann0 lv)\n| TLLet ZL Lv F t lv als alt\n  : true_live_sound i (fst ⊝ F ++ ZL) (getAnn ⊝ als ++ Lv) t alt\n    -> length F = length als\n    -> (forall n Zs a, get F n Zs ->\n                 get als n a ->\n                 true_live_sound i (fst ⊝ F ++ ZL) (getAnn ⊝ als ++ Lv) (snd Zs) a)\n    -> (forall n Zs a, get F n Zs ->\n                 get als n a ->\n                 if isFunctional i then (getAnn a \\ of_list (fst Zs)) ⊆ lv\n                 else True)\n    -> getAnn alt ⊆ lv\n    -> true_live_sound i ZL Lv (stmtFun F t)(annF lv als alt).\n\n\n(** *** Some properties of the predicate *)\n\nLemma true_live_sound_overapproximation_I ZL Lv s slv\n  : true_live_sound FunctionalAndImperative ZL Lv s slv\n    -> true_live_sound Imperative ZL Lv s slv.\nProof.\n  intros. general induction H; simpl in * |- *; econstructor; simpl; eauto.\nQed.\n\nLemma true_live_sound_overapproximation_F ZL Lv s slv\n  : true_live_sound FunctionalAndImperative ZL Lv s slv\n    -> true_live_sound Functional ZL Lv s slv.\nProof.\n  intros. general induction H; simpl in * |- *; econstructor; simpl; eauto.\nQed.\n\nLemma argsLive_monotone lv blv blv' Y Z\n  : argsLive lv blv Y Z\n    -> blv' ⊆ blv\n    -> argsLive lv blv' Y Z.\nProof.\n  intros Args LE.\n  general induction Args; eauto using argsLive.\nQed.\n\nLemma true_live_sound_monotone i ZL LV LV' s lv\n: true_live_sound i ZL LV s lv\n  -> PIR2 Subset LV' LV\n  -> true_live_sound i ZL LV' s lv.\nProof.\n  intros LS LE.\n  general induction LS; simpl; eauto 20 using true_live_sound, PIR2_app.\n  - PIR2_inv.\n    econstructor; eauto.\n    cases; eauto with cset.\n    eauto using argsLive_monotone.\nQed.\n\n(*\nLemma true_live_sound_trueIsCalled i ZL Lv s slv l\n  : true_live_sound i ZL Lv s slv\n    -> trueIsCalled s l\n    -> exists lv, get Lv (counted l) lv.\nProof.\n  intros Live IC. destruct l; simpl in *.\n  general induction IC; invt true_live_sound; eauto.\n  - edestruct IHIC2 as [lv' [Z' ?]]; eauto; simpl in *.\n    rewrite get_app_lt in H1; eauto with len. inv_get.\n    edestruct IHIC1 as [lv'' [Z'' ?]]; eauto.\n    rewrite get_app_ge in H1; eauto with len.\n    rewrite zip_length2 in H1; eauto with len.\n    rewrite map_length in H1.\n    orewrite (❬F❭ + n - ❬als❭ = n) in H1. eauto.\n  - edestruct IHIC as [lv' [Z' ?]]; eauto; try reflexivity.\n    rewrite get_app_ge in H; eauto with len.\n    rewrite zip_length2 in H; eauto with len.\n    rewrite map_length in H.\n    orewrite (❬F❭ + n - ❬als❭ = n) in H. eauto.\nQed.*)", "meta": {"author": "sigurdschneider", "repo": "lvc", "sha": "be41194f16495d283fe7bbc982c3393ac554dd5b", "save_path": "github-repos/coq/sigurdschneider-lvc", "path": "github-repos/coq/sigurdschneider-lvc/lvc-be41194f16495d283fe7bbc982c3393ac554dd5b/theories/Liveness/TrueLiveness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.29285149030425583}}
{"text": "(**************************************************************************)\n(*                                                                        *)\n(*  This file is part of octant-proof.                                    *)\n(*                                                                        *)\n(*  Copyright (C) 2019-2020 Orange                                        *)\n(*                                                                        *)\n(*  you can redistribute it and/or modify it under the terms of the GNU   *)\n(*  Lesser General Public License as published by the Free Software       *)\n(*  Foundation, either version 3 of the License, or (at your option)      *)\n(*  any later version.                                                    *)\n(*                                                                        *)\n(*  It 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 the software. If not, see                          *)\n(*  <https://www.gnu.org/licenses/>.                                      *)\n(*                                                                        *)\n(**************************************************************************)\n\nRequire Import syntax.\nRequire Import occurrences.\nRequire Import subs.\nRequire Import pmatch.\nRequire Import bSemantics.\nRequire Import monotonicity.\nRequire Import soundness.\nRequire Import tSemantics.\n\nFrom mathcomp\nRequire Import ssreflect ssrbool ssrnat eqtype seq ssrfun choice fintype tuple finset bigop finfun.\n\nRequire Import bigop_aux.\nRequire Import utils.\nRequire Import finseqs.\nRequire Import fintrees.\n\nRequire Import Sumbool.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\n\nImplicit Types (s r : sub) (d def : syntax.constant) (t : term) (a : atom)\n               (ga : gatom) (tl : list atom) (cl : clause) (i : interp).\n\n(** * No recursion traces: extracting bounded sequences from deduction traces *)\nSection no_rec_traces.\n\n(** Program to analyze *)\nVariable p : program.\n(** default ground atom for the trace semantics *)\nVariable gat_def : gatom.\n\n(** Default term, variable and predicate, actually unsused but required by the nth \n    or nth_error functions *)\nVariable dt : term.\nVariable dv : 'I_n.\nVariable df : symtype.\n\n(** A branch is a sequence without repetition of [t_occ] *)\nDefinition dbranch := (@uniq_seq_finType (t_occ_finType p)).\n\n(** the predicate corresponding to the last occurrence of the branch *)\nDefinition branch_pred (br : seq (t_occ p)) :=\n  match br with\n    | [::] => df (* case not used in practice *)\n    | a :: l => match p_at (last a l) with\n        | None => df (* same *)\n        | Some f => f end end.\n\n(** branch_pred stable wrt. cons *)\nLemma branch_pred_eq h (s : seq (t_occ p)) : \n  size s > 0 -> branch_pred s = branch_pred (h::s).\nProof.\nby destruct s.\nQed.\n\n(** [t_ind] (term index) of the last occurrence of the branch *)\nDefinition branch_t_ind (br : seq (t_occ p)) :=\n  match br with\n    | [::] => 0 (* unused case *)\n    | a :: l => t_ind (last a l) end. \n\n(** branch_t_ind stable wrt. cons *)\nLemma branch_t_ind_eq h (s : seq (t_occ p)) : \n  size s > 0 -> branch_t_ind s = branch_t_ind (h::s).\nProof.\nby destruct s.\nQed.\n\n(** ** The actual extraction *)\n(**    [prev] is the set of previously visited [t_occ]s\n       [tr] is the trace to \"unrec\"\n       [v] is the variable we focus on\n       [count] is the fuel used for termination \n       The function computes the sequences of [t_occ]s the values of [v] go\n       through, and eliminates the repetition of [t_occ]s *)\nFixpoint unrec_trace_gen (prev : (tocs p)) (tr : (ABtree rul_gr_finType gatom_finType)) (v : 'I_n) (count : nat) : {set dbranch} :=\n  match count with | 0 => set0 | count.+1 =>\n  match tr with\n    | ABLeaf _ => [set unil]\n    | ABNode (RS cl s) descs => \n          let unrec_b (o : t_occ p) : {set dbranch} :=\n            match (nth_error descs (b_ind o)) with\n              | None => set0 (* None case not used in practice *)\n              | Some (ABLeaf _) => [set unil]\n              | Some (ABNode (RS clb sb) descsb) => \n                  unrec_trace_gen (o |: prev) \n                                  (ABNode (RS clb sb) descsb) \n                                  (get_cl_var dt dv clb (t_ind o)) \n                                  count end\n        in\n        let occs := (occsInProgram p v) :\\: prev in\n        \\bigcup_(occ in occs) [set pucons occ l | l in unrec_b occ]\n         end end.\n\n(** Version used in practice, where [prev] is empty *)\nDefinition unrec_trace (tr : (ABtree rul_gr_finType gatom_finType)) (v : 'I_n) (count : nat) : {set dbranch} :=\n  unrec_trace_gen set0 tr v count.\n\n(** ** The sequences in the no recursion trace are disjoint from [prev] *)\nLemma unrec_trace_gen_notin (prev : (tocs p)) (tr : (ABtree rul_gr_finType gatom_finType)) (v : 'I_n) (count : nat) :\n  [forall br in unrec_trace_gen prev tr v count, [disjoint [set x | x \\in (useq br)] & prev]].\nProof.\nmove:prev tr v. induction count as [|count Hrec].\n- intros. apply/forallP=>x. apply/implyP=>//=. by rewrite in_set0.\n- move=>prev tr v. apply/forallP=>br. apply/implyP=>/=.\n  destruct tr as [|[cl s] descs].\n  + move=>/set1P ->. simpl. rewrite disjoints_subset. apply/subsetP=>x. rewrite in_set. by rewrite in_nil.\n  + move=>/bigcup_seqP [i Hin] /andP [/imsetP [x Hx ->] Hinb].\n    unfold pucons.\n    destruct (nth_error_case descs (b_ind i)) as [Hnone|[[|] [Hd1 Hd2]]].\n    - by rewrite Hnone in_set0 in Hx.\n    - rewrite Hd2 in Hx. rewrite (set1P Hx).\n      simpl. rewrite disjoints_subset. \n      apply/subsetP=>y. rewrite in_set mem_seq1.\n      move=>/eqP ->. rewrite in_setC. \n      have H := setDP Hinb. by destruct H.\n    - rewrite Hd2 in Hx. destruct s0. \n      have H := implyP (forallP (Hrec _ _ _) _) Hx.\n      rewrite disjoints_subset subsetC in H.\n      rewrite disjoints_subset.\n      have Hb := (subsetP H i (setU11 i _)).\n      rewrite in_setC in_set in Hb.\n      destruct sumbool_of_bool as [Hf|Hf].\n      + apply/subsetP=>y. rewrite in_set in_cons in_setC.\n        move=>/orP [/eqP ->|Hyin].\n        - have Ht := setDP Hinb. by destruct Ht.\n        - destruct (bool_des_rew (y \\in prev)) as [Hyr|Hy].\n          + have Ht := subsetP H y (setU1r i Hyr). \n            rewrite in_setC in_set Hyin in Ht. inversion Ht.\n          + by rewrite Hy.\n      + by rewrite Hb in Hf.\nQed.\n\n(** ** The no recursion trace is monotonuous wrt. its fuel *)\nLemma unrec_trace_gen_count_incr (prev : (tocs p)) (tr : (ABtree rul_gr_finType gatom_finType)) (v : 'I_n) (c1 c2 : nat) br :\n c1 <= c2 -> br \\in unrec_trace_gen prev tr v c1 -> br \\in unrec_trace_gen prev tr v c2.\nProof.\nmove:prev v c1 c2 br.\ninduction tr using abtree_ind_prop;\nmove=>prev v [|c1] [|c2] br //=.\n- by rewrite in_set0.\n- by rewrite in_set0.\n- destruct h as [cl s]. \n  move=>Hlt /bigcup_seqP [i Hienum /andP [/imsetP [x Hxin ->] Hin]].\n  destruct (nth_error_case l (b_ind i)) as [Hnone|[[|] [Hd1 Hd2]]].\n  + by rewrite Hnone in_set0 in Hxin.\n  + rewrite Hd2 in Hxin. rewrite (set1P Hxin).\n    unfold pucons. simpl.\n    apply/bigcup_seqP. exists i. auto.\n    apply/andP;split. rewrite Hd2. \n    apply/imsetP. exists unil. by apply/set1P.\n    auto. auto.\n  + unfold pucons.\n    rewrite Hd2 in Hxin. destruct s0 as [clb sb].\n    have Hif := disjoint_setI0 (implyP (forallP (unrec_trace_gen_notin _ _ _ _) _) Hxin).\n    destruct sumbool_of_bool as [Hnotin|Hinin].\n    - apply/bigcup_seqP. exists i. auto.\n      apply/andP;split. apply/imsetP. exists x.\n      rewrite Hd2. \n      apply/(all_prop_in H Hd1). apply Hlt.\n      apply Hxin. destruct sumbool_of_bool as [Hit|Hit].\n      by apply/val_inj. rewrite Hnotin in Hit. inversion Hit.\n      auto.\n    - move:Hinin. move=>/negPf /Bool.not_false_is_true Hinin.\n      assert (Hf : i \\in (@set0 (t_occ_finType p))). \n      rewrite -Hif. apply/setIP. split. rewrite in_set. apply Hinin.\n      by apply/setU1P;auto. by rewrite in_set0 in Hf.\nQed.\n\n(** ** [unrec_trace_gen] has a normal form wrt. its fuel *)\nLemma unrec_trace_gen_normal_form (prev : (tocs p)) (tr : (ABtree rul_gr_finType gatom_finType)) (v : 'I_n) (count : nat) :\n  forall br, br \\in unrec_trace_gen prev tr v count -> br \\in unrec_trace_gen prev tr v (ABheight tr).+1.\nProof.\nmove:prev v count.\ninduction tr using abtree_ind_prop;\nmove=>prev v [|count] br //.\n- by rewrite in_set0.\n- by rewrite in_set0.\n- destruct h as [cl s].\n  move=>/bigcup_seqP [i Hinenum /andP [/imsetP [x Hxin ->] Hinb]].\n  destruct (nth_error_case l (b_ind i)) as [Hnone|[[|] [Hd1 Hd2]]].\n  + by rewrite Hnone in_set0 in Hxin. \n  + rewrite Hd2 in Hxin.\n    rewrite (set1P Hxin).\n    apply/bigcup_seqP. exists i. auto.\n    apply/andP;split;auto.\n    apply/imsetP.\n    exists x.\n    by rewrite Hd2 Hxin. rewrite (set1P Hxin). by apply/val_inj. \n  + rewrite Hd2 in Hxin. destruct s0 as [clb sb].\n    have Hif := disjoint_setI0 (implyP (forallP (unrec_trace_gen_notin _ _ _ _) _) Hxin).\n    have Hrec := (all_prop_in H Hd1 _ _ _ _ Hxin).\n    assert (Hh : (ABheight (ABNode (RS clb sb) l0)).+1 <= (ABheight (ABNode (RS cl s) l))).\n    apply/sstree_height. apply/hasP. exists (ABNode (RS clb sb) l0 ). apply Hd1.\n    simpl. by apply/orP;left. \n    unfold pucons.\n    destruct sumbool_of_bool as [Hnotin|Hinin].\n    - apply/bigcup_seqP. exists i. auto.\n      apply/andP;split. apply/imsetP. exists x.\n      rewrite Hd2.\n      apply/(unrec_trace_gen_count_incr Hh Hrec).\n      apply/val_inj. simpl. unfold pucons.\n      destruct sumbool_of_bool as [Hf|Hf]. auto.\n      by rewrite Hnotin in Hf. auto. \n    - move:Hinin. move=>/negPf /Bool.not_false_is_true Hinin.\n      assert (Hf : i \\in (@set0 (t_occ_finType p))). \n      rewrite -Hif. apply/setIP. split. rewrite in_set. apply Hinin.\n      by apply/setU1P;auto. by rewrite in_set0 in Hf.\nQed.\n\n(** A substitution [s] is adequate wrt. a branch [br], ending with an occurrence [o] referring to\n    an occurrence of predicate [f], and an interpretation [i] iff. [s] [v] = [c], st. [i] contains\n    a [f]-fact that has c at the position matching [o] *)\nDefinition br_adequate def (br : dbranch) (s : sub) (v : 'I_n) (i : interp) : bool :=\n  [exists c : syntax.constant, (s v == Some c) && \n         [exists ga in i, (sym_gatom ga == branch_pred br) \n                       && (nth def (arg_gatom ga) (branch_t_ind br) == c)]].\n\n(** ** Core result: any value [v] can take in practice during an execution of [p]\n       is captured by the no-recursion trace *)\nTheorem no_rec_needed def prev (tr : trace_sem_trees gat_def) (i : interp) (m : nat) cl s v :\n   vars_not_shared p\n-> prog_safe p\n-> only_variables_in_heads p\n-> tr \\in sem_t p gat_def def m i\n-> ABroot (val tr) = inl (RS cl s)\n-> v \\in tail_vars (body_cl cl)\n-> [forall br in unrec_trace_gen prev (val tr) v (ABheight (val tr)).+1, \n      br_adequate def br s v i].\nProof.\nmove:cl s v tr prev.\ninduction m as [|m Hrec].\n- move=>/= cl s v tr prev Hvns Hpsafe Hvarshead /imsetP [x Hx ->] //.\n- move=> cl s v tr prev Hvns Hpsafe Hvarshead Hded. have Hded_copy := Hded. move:Hded. \n  move=>/setUP [Hded|/bigcup_seqP [clb Hclbinp /andP [H _]]].\n  + by apply/Hrec.\n  + destruct (imset2P (mem_pset_set H))\n      as [descs sb Hdescsded Hsmatch Htreq]. clear H.\n    destruct tr as [[|[clt st] descst] Htr];\n    move=>// [Hcleq Hseq] Hvin.\n    unfold wu_pcons_seq in Htreq.\n    unfold wu_pcons_wlist in Htreq. move:Htreq.\n    destruct sumbool_of_bool;move=> //[Hcleqb Hseqb Hdescseq].\n    assert (Hdescssize : size descs <= bn).\n    destruct descs as [descs Hdescs]. rewrite (eqP Hdescs).\n    destruct clb. apply wlist_to_seq_size.\n    rewrite (seq_wlistK Hdescssize) in Hdescseq.\n    (* cl = clb = clt, s = sb = st and descs = descst *)\n    rewrite in_set in Hsmatch. \n    destruct (and3P Hsmatch) as [Hsbmatch Hdedsub Hprevded]. clear Hsmatch.\n    apply/forallP=>br. apply/implyP=>Hbrb. have Hbrb_copy := Hbrb. move:Hbrb. simpl.\n    move=>/bigcup_seqP [occ Hoccinrule].\n    move=>/andP [/imsetP [brb Hbrb Hbreq]] /setDP [Hocc1 Hocc2].\n    assert (Hdomvs : v \\in dom s).\n    rewrite -Hseq Hseqb.\n    apply (subsetP (match_vars_subset Hsbmatch)).\n    rewrite -Hcleqb Hcleq. apply Hvin.\n    rewrite in_set in Hdomvs.\n    destruct (sub_elim s v) as [[c Hc]|Hnone];\n      try by rewrite Hnone in Hdomvs.\n    apply/existsP. exists c. apply/andP;split. apply/eqP/Hc.\n    destruct (nth_error_case descst (b_ind occ))\n      as [Hnone|[[ga| [cld sd] descsd] [Hdin Hdnth]]]. by rewrite Hnone in_set0 in Hbrb.\n    - rewrite Hdnth in Hbrb.\n      rewrite (set1P Hbrb) in Hbreq.\n      simpl in Hbreq. \n      assert (Hwub : @wu_pred _ _ bn (ABLeaf rul_gr_finType ga)). auto. \n      assert (Hsubtree : subtree (val {| wht := (ABLeaf rul_gr_finType ga); Hwht := Hwub |}) (val {| wht := ABNode (RS clt st) descst; Hwht := Htr |})).\n      simpl. apply/hasP. exists (ABLeaf rul_gr_finType ga). apply Hdin. by apply/eqP.\n      have Hgain  := sem_t_leaf (trace_sem_prev_trees Hded_copy Hsubtree).\n      apply/existsP. exists ga. apply/andP;split. apply Hgain.\n      unfold ded_sub_equal in Hdedsub.\n      rewrite Hdescseq in Hdnth. destruct (nth_error_preim Hdnth) as [trb [Htrb1 Htrb2]].\n      have Heqb := (nth_error_map (ded def) Htrb1).\n      assert (Heqt : trb = {| wht := (ABLeaf rul_gr_finType ga); Hwht := Hwub |}).\n      apply/val_inj. apply Htrb2.\n      rewrite Heqt in Heqb. unfold ded at 2 in Heqb. simpl in Heqb.\n      rewrite Hbreq. simpl. unfold p_at.\n      have Hoccsrule := occsInProgramV Hocc1.\n      unfold t_at in Hoccsrule.\n      simpl. unfold at_at. unfold at_at in Hoccsrule.\n      destruct (nth_error_case p (r_ind occ)) as [Hnone|[d [Hd1 Hd2]]]. by rewrite Hnone in Hoccsrule.\n      rewrite Hd2 in Hoccsrule. rewrite Hd2. \n      destruct (nth_error_case (body_cl d) (b_ind occ)) as [Hnone|[db [Hdb1 Hdb2]]]. \n      by rewrite Hnone in Hoccsrule.\n      rewrite Hdb2 in Hoccsrule. rewrite Hdb2.\n      have Heqtb := (nth_error_map (gr_atom_def def sb) Hdb2).\n      assert (Hdeq : d = clb). apply/(@vns_cl_eq _ _ _ v).\n      apply/bigcup_seqP. exists db. apply Hdb1. apply/andP;split;auto. \n      apply/bigcup_seqP. exists (Var v). destruct occ. apply (nth_error_in Hoccsrule). \n      apply/andP;split;auto. by apply/set1P. rewrite -Hcleqb Hcleq. apply Hvin. apply Hd1. \n      apply Hclbinp. apply Hvns. \n      simpl in Heqb.\n      rewrite Hdeq -(eqP Hdedsub) Heqb in Heqtb.\n      inversion Heqtb as [Hgasbeq].\n      apply/andP;split.\n      + by destruct ga as [[]]; destruct db as [[]].\n      + simpl. destruct occ.\n        rewrite (nth_map (Var v) def _ (nth_error_in_size Hoccsrule)) (nth_error_nth (Var v) Hoccsrule).\n        simpl. rewrite -Hseqb Hseq. unfold odflt. unfold oapp. by rewrite Hc.\n    - assert (Hsubd : subtree (ABNode (RS cld sd) descsd) (ABNode (RS clt st) descst)).\n      apply/orP;right. apply/hasP. exists (ABNode (RS cld sd) descsd). auto. by apply/orP;left.\n      have Hwupred := (wu_pred_sub Hsubd Htr).\n      assert (Hssubd : strict_subtree (val {| wht := (ABNode (RS cld sd) descsd); Hwht := Hwupred |}) (val {| wht := ABNode (RS clt st) descst; Hwht := Htr |})).\n      apply/hasP. exists (ABNode (RS cld sd) descsd). auto. by apply/orP;left.\n      have Hdedm1 := trace_sem_prev_trees_m1 Hded_copy Hssubd. simpl in Hdedm1.\n      assert (Hrootd : ABroot (val {| wht := ABNode (RS cld sd) descsd; Hwht := Hwupred |}) =\n       inl (RS cld sd)). auto.\n      unfold ded_sub_equal in Hdedsub.\n      rewrite Hdescseq in Hdnth. destruct (nth_error_preim Hdnth) as [trb [Htrb1 Htrb2]].\n      have Heqb := (nth_error_map (ded def) Htrb1).\n      assert (Heqt : trb = {| wht := ABNode (RS cld sd) descsd; Hwht := Hwupred |}).\n      apply/val_inj. apply Htrb2.\n      rewrite Heqt in Heqb. unfold ded at 2 in Heqb. simpl in Heqb.\n      destruct cld as [hcld tlcld].\n      (* rewrite Hbreq. simpl. unfold p_at.*)\n      have Hoccsrule := occsInProgramV Hocc1. have Htat_copy := Hoccsrule.\n      unfold t_at in Hoccsrule.\n      (*rewrite Hocceq. simpl. unfold at_at.*) unfold at_at in Hoccsrule.\n      destruct (nth_error_case p (r_ind occ)) as [Hnone|[d [Hd1 Hd2]]]. by rewrite Hnone in Hoccsrule.\n      rewrite Hd2 in Hoccsrule. (*rewrite Hd2.*) \n      destruct (nth_error_case (body_cl d) (b_ind occ)) as [Hnone|[db [Hdb1 Hdb2]]]. \n      by rewrite Hnone in Hoccsrule.\n      rewrite Hdb2 in Hoccsrule. (*rewrite Hdb2.*)\n      have Heqtb := (nth_error_map (gr_atom_def def sb) Hdb2).\n      assert (Hdeq : d = clb). apply/(@vns_cl_eq _ _ _ v).\n      apply/bigcup_seqP. exists db. apply Hdb1. apply/andP;split;auto. \n      apply/bigcup_seqP. exists (Var v). destruct occ. apply (nth_error_in Hoccsrule). \n      apply/andP;split;auto. by apply/set1P. rewrite -Hcleqb Hcleq. apply Hvin. apply Hd1. \n      apply Hclbinp. apply Hvns.\n      destruct occ as [occ Hocc]. simpl in Heqb.\n      rewrite Hdeq -(eqP Hdedsub) Heqb in Heqtb.\n      inversion Heqtb as [[Hgasymbeq Hgaargbeq]].\n      have Hcldin := (tr_cl_in Hdedm1 Hrootd).\n      assert (Hsveq : s v = sd (get_cl_var dt dv (Clause hcld tlcld) t_ind)\n                   /\\ nth_error (arg_atom hcld) t_ind = Some (Var (get_cl_var dt dv (Clause hcld tlcld) t_ind))).\n      have H := (nth_error_map (gr_term_def def sb) Hoccsrule).\n      rewrite -Hgaargbeq in H. unfold get_cl_var. simpl. \n      destruct (nth_error_preim H) as [[v'|c'] [H1' H2']]. split.\n      rewrite (nth_error_nth _ H1') (gr_term_def_eq_in_dom H2'). by rewrite -Hseq Hseqb.\n      destruct (existsP (trace_sem_head_match Hpsafe Hdedm1)) as [x Hx].\n      apply (subsetP (match_vars_subset Hx)).\n      apply/(subsetP (allP Hpsafe _ Hcldin)).\n      apply/bigcup_seqP. exists (Var v'). apply (nth_error_in H1'). apply/andP;split;auto.\n      by apply/set1P. \n      apply (subsetP (match_vars_subset Hsbmatch)). rewrite -Hcleqb Hcleq. apply Hvin.\n      rewrite (nth_error_nth _ H1'). apply H1'. \n      have Hf := (allP (allP Hvarshead _ Hcldin) _ (nth_error_in H1')). inversion Hf.\n      destruct Hsveq as [Hv1' Hv2'].\n      assert (Hnewintail : (get_cl_var dt dv (Clause hcld tlcld) t_ind) \\in tail_vars tlcld).\n      apply (subsetP (allP Hpsafe _ Hcldin)).\n      apply/bigcup_seqP. exists (Var (get_cl_var dt dv (Clause hcld tlcld) t_ind)). \n      apply (nth_error_in Hv2'). apply/andP;split;auto.\n      by apply/set1P.\n      rewrite Hdescseq (nth_error_map val Htrb1) Heqt in Hbrb. simpl in Hbrb. \n     (* helping unification *)\n      assert (Hbrbin : brb\n           \\in unrec_trace_gen ({| r_ind := occ; b_ind := Hocc; t_ind := t_ind |} |: prev)\n                 (val  {|  wht := ABNode (RS (Clause hcld tlcld) sd) descsd; Hwht := Hwupred |})\n                 (get_cl_var dt dv (Clause hcld tlcld) t_ind) (@foldr nat nat maxn O\n                 (@map (ABtree rul_gr gatom) nat (@ABheight rul_gr gatom) (@map\n                 (@WUtree (Finite.eqType rul_gr_finType) (Finite.eqType gatom_finType) bn)\n                 (ABtree rul_gr gatom) (@wht (Finite.eqType rul_gr_finType)\n                 (Finite.eqType gatom_finType) bn) (@tval (@size atom  (@wlist_to_seq_co atom bn (body_cl clb)))\n                 (@WUtree (Finite.eqType rul_gr_finType) (Finite.eqType gatom_finType) bn) descs)))).+1).\n      apply Hbrb.\n      have Hbrbprev := (unrec_trace_gen_normal_form Hbrbin). clear Hbrb. clear Hbrbin.\n      have Hdisj := implyP (forallP (unrec_trace_gen_notin _ _ _ _) _) Hbrbprev.\n      move:Hbreq. unfold pucons. destruct sumbool_of_bool as [Hin|Hin].\n      + move=>/= ->. \n        have Hreced := implyP (forallP ((@Hrec _ sd _ _ _ Hvns) Hpsafe Hvarshead Hdedm1 Hrootd Hnewintail) brb) Hbrbprev.\n        apply/existsP.\n        simpl in Hreced.\n        destruct (existsP Hreced) as [c' Hc']. destruct (andP Hc') as [Hc1' Hc2']. clear Hc'. clear Hreced.\n        destruct (existsP Hc2') as [ga Hga]. destruct (andP Hga) as [Hga1 Hga2]. destruct (andP Hga2) as [Hga3 Hga4].\n        clear Hga2. clear Hc2'. clear Hga. exists ga. \n        destruct (bool_des_rew ({| r_ind := occ; b_ind := Hocc; t_ind := t_ind |} \\in \n                (@mem (Equality.sort (Choice.eqType (Finite.choiceType (t_occ_finType p))))\n                 (seq_predType (Choice.eqType (Finite.choiceType (t_occ_finType p))))\n                 (@useq (Choice.eqType (Finite.choiceType (t_occ_finType p))) brb)))) as [Hf|Hf].\n        - assert (Hff : ({| r_ind := occ; b_ind := Hocc; t_ind := t_ind |} \\in (@set0 (t_occ_finType p)))).\n          rewrite -(disjoint_setI0 Hdisj). apply/setIP;split.\n          rewrite in_set. apply Hf.\n          apply setU11. by rewrite in_set0 in Hff.\n          assert (Hsize : 0 < size brb).\n          destruct brb as [[|]];auto.\n          move:Hbrbprev. move=>/= /bigcup_seqP [i1 Hi1inenum /andP [/imsetP [x]]].\n          destruct (nth_error_case descsd (b_ind i1)) as [Hnone|[[|] [Hdd1 Hdd2]]].\n          + by rewrite Hnone in_set0.\n          + rewrite Hdd2. move=>/set1P -> //.\n          + rewrite Hdd2. destruct s0. move=>Hxunrec.\n            unfold pucons. \n            (* helping unification *)\n            assert (Hxunrecb : \n                x \\in unrec_trace_gen (@setU (t_occ_finType p) (@set1 (t_occ_finType p)  i1)\n               (@setU (t_occ_finType p) (@set1 (t_occ_finType p) {| r_ind := occ; b_ind := Hocc; t_ind := t_ind |})\n               prev)) (ABNode (RS c0 s0) l) (get_cl_var dt dv c0 (occurrences.t_ind i1)) (@foldr nat nat maxn O\n               (@map (ABtree rul_gr gatom) nat (@ABheight rul_gr gatom) descsd)).+1).\n            apply Hxunrec.\n            have Hdisjb := implyP (forallP (unrec_trace_gen_notin _ _ _ _) _) Hxunrecb.\n            clear Hxunrecb. clear Hxunrec. destruct sumbool_of_bool as [Hfff|Hfff];move=>//.\n            assert (Hff : (i1 \\in (@set0 (t_occ_finType p)))).\n            rewrite -(disjoint_setI0 Hdisjb). apply/setIP;split.\n            rewrite in_set. destruct (bool_des_rew ((@in_mem (Equality.sort (Choice.eqType (Finite.choiceType (t_occ_finType p))))\n               i1\n               (@mem (Equality.sort (Choice.eqType (Finite.choiceType (t_occ_finType p))))\n                  (seq_predType (Choice.eqType (Finite.choiceType (t_occ_finType p))))\n                  (@useq (Choice.eqType (Finite.choiceType (t_occ_finType p))) x))))) as [Hf5|Hf5].\n            by rewrite Hf5 in Hfff. by rewrite Hf5 in Hfff. apply setU11. by rewrite in_set0 in Hff.\n          apply/and3P;split. apply Hga1.\n          rewrite (eqP Hga3).\n          apply/eqP/branch_pred_eq/Hsize. \n          rewrite -(branch_t_ind_eq {| r_ind := occ; b_ind := Hocc; t_ind := t_ind |} Hsize) (eqP Hga4).\n          assert (Hsome : Some c' = Some c).\n          rewrite -Hc -(eqP Hc1'). auto. by inversion Hsome.\n        - assert (Hff : ({| r_ind := occ; b_ind := Hocc; t_ind := t_ind |} \\in (@set0 (t_occ_finType p)))).\n          rewrite -(disjoint_setI0 Hdisj). apply/setIP;split.\n          rewrite in_set.  \n          destruct (bool_des_rew (@in_mem (Equality.sort (Choice.eqType (Finite.choiceType (t_occ_finType p))))\n              {| r_ind := occ; b_ind := Hocc; t_ind := t_ind |}\n              (@mem (Equality.sort (Choice.eqType (Finite.choiceType (t_occ_finType p))))\n                 (seq_predType (Choice.eqType (Finite.choiceType (t_occ_finType p))))\n                 (@useq (Choice.eqType (Finite.choiceType (t_occ_finType p))) brb)))) as [Hf|Hf].\n          apply Hf. by rewrite Hf in Hin.\n          apply setU11. by rewrite in_set0 in Hff.\nQed.\n\nEnd no_rec_traces.", "meta": {"author": "Orange-OpenSource", "repo": "octant-proof", "sha": "ac920f5d906b7822ec585bc1bf3ec55ee74acddf", "save_path": "github-repos/coq/Orange-OpenSource-octant-proof", "path": "github-repos/coq/Orange-OpenSource-octant-proof/octant-proof-ac920f5d906b7822ec585bc1bf3ec55ee74acddf/octalgo/norec_sem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6688802471698041, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.29285149030425583}}
{"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 O E Eprime A B C Oprime Aprime Bprime Cprime Eprimeprime Bprimeprime C2 C3 : Universe, ((wd_ O E /\\ (wd_ Oprime Eprime /\\ (wd_ A O /\\ (wd_ B O /\\ (wd_ C O /\\ (wd_ A E /\\ (wd_ Eprimeprime O /\\ (wd_ O Oprime /\\ (wd_ Bprimeprime O /\\ (wd_ Bprime Oprime /\\ (wd_ C2 Oprime /\\ (wd_ Eprimeprime A /\\ (wd_ E Eprimeprime /\\ (wd_ E Eprime /\\ (wd_ O Eprime /\\ (wd_ Oprime Eprimeprime /\\ (wd_ E Oprime /\\ (wd_ C Bprimeprime /\\ (wd_ Cprime C3 /\\ (wd_ B Bprimeprime /\\ (wd_ Bprime C3 /\\ (wd_ Eprime C2 /\\ (wd_ Aprime C2 /\\ (wd_ Oprime Aprime /\\ (wd_ A Aprime /\\ (wd_ C Cprime /\\ (wd_ B Bprime /\\ (col_ O E A /\\ (col_ O E B /\\ (col_ O E C /\\ (col_ Oprime Eprime Aprime /\\ (col_ Oprime Eprime Bprime /\\ (col_ Oprime Eprime Cprime /\\ (col_ O Eprimeprime Bprimeprime /\\ (col_ O Eprimeprime Oprime /\\ (col_ O Eprimeprime C2 /\\ (col_ O Eprimeprime C3 /\\ (col_ O A C /\\ col_ Oprime Eprime C2)))))))))))))))))))))))))))))))))))))) -> col_ O Oprime C2)).\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_1295.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2928063923575991}}
{"text": "Definition T := Type.\nDefinition U := Type.\n\nModule Type MT.\n  Parameter t : T.\nEnd MT.\n\nModule Type MU.\n  Parameter t : U.\nEnd MU.\n\nModule F (E : MT).\n  Definition elt :T := E.t.\nEnd F.\n\nModule G (E : MU).\n  Include F E.\nPrint Universes. (* U <= T *)\nEnd G.\nPrint Universes. (* Check if constraint is lost *)\n\nModule Mt.\n  Definition t := T.\nEnd Mt.\n\nModule P := G Mt. (* should yield Universe inconsistency *)\n(* ... otherwise the following command will show that T has type T! *)\nEval cbv delta [P.elt Mt.t] in P.elt.\n\n\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/test-suite/failure/univ_include.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2928063923575991}}
{"text": "Require Coq.Structures.Equalities.\nRequire Coq.FSets.FSetAVL.\nRequire Coq.FSets.FSetWeakList.\nRequire Coq.FSets.FMapFacts.\nRequire Coq.Lists.List.\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 ServerEndpointPeer : 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  Definition supports (e : t) : ProtoIdentifier.t := supports e.\nEnd ServerEndpointPeer.\n\nModule Sets : FSetInterface.WS \n  with Definition E.t  := t\n  with Definition E.eq := ServerEndpointPeer.eq\n:= FSetWeakList.Make ServerEndpointPeer.\n\nModule ServerEndpointCollection :=\n  ProtoPeer.Collection.Make ServerEndpointPeer 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/ProtoServerEndpoint.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2927832110542623}}
{"text": "Require Import ZArith List Nat String.\nRequire Import syntax semantics.\nRequire Import untyped_syntax error.\nImport error.Notations.\n\n\nLemma andb_and a b : (a && b)%bool <-> a /\\ b.\nProof.\n  split.\n  - apply Bool.andb_prop_elim.\n  - apply Bool.andb_prop_intro.\nQed.\n\nModule Typer(C : ContractContext).\n\n  Module syntax := Syntax C.\n  Import syntax. Import untyped_syntax.\n\n  Definition instruction := syntax.instruction.\n\n  Definition safe_instruction_cast {self_type tff} A A' B B' :\n    instruction self_type tff A B -> A = A' -> B = B' -> instruction self_type tff A' B'.\n  Proof.\n    intros i [] [].\n    exact i.\n  Defined.\n\n  Record cast_error :=\n    Mk_cast_error\n      {\n        input : Datatypes.list type;\n        output :  Datatypes.list type;\n        expected_input : Datatypes.list type;\n        expected_output : Datatypes.list type;\n        tff : Datatypes.bool;\n        self_type_ : Datatypes.option type;\n        i : instruction self_type_ tff input output;\n      }.\n\n  Definition instruction_cast {self_type tff} A A' B B' i : M (instruction self_type tff A' B') :=\n    match stype_dec A A', stype_dec B B' with\n    | left HA, left HB => Return (safe_instruction_cast A A' B B' i HA HB)\n    | _, _ => Failed _ (Typing cast_error (Mk_cast_error A B A' B' tff _ i))\n    end.\n\n  Definition instruction_cast_range {self_type tff} A B B' (i : instruction self_type tff A B)\n    : M (instruction self_type tff A B') := instruction_cast A A B B' i.\n\n  Definition instruction_cast_domain {self_type tff} A A' B (i : instruction self_type tff A B)\n    : M (instruction self_type tff A' B) := instruction_cast A A' B B i.\n\n  Definition contract_cast (c : contract_constant) (a b : type)\n             (H : C.get_contract_type c = Some b)\n             (He : a = b)\n    : syntax.concrete_data (contract a) :=\n    syntax.Contract_constant c (eq_trans H (f_equal Some (eq_sym He))).\n\n  Inductive typer_result {self_type} A : Set :=\n  | Inferred_type B : instruction self_type false A B -> typer_result A\n  | Any_type : (forall B, instruction self_type true A B) -> typer_result A.\n\n  Definition type_check_instruction {self_type}\n             (type_instruction :\n                forall (i : untyped_syntax.instruction) A,\n                  M (typer_result A))\n             i A B : M {b : Datatypes.bool & instruction self_type b A B} :=\n    let! r1 := type_instruction i A in\n    match r1 with\n    | Inferred_type _ B' i =>\n      let! i := instruction_cast_range A B' B i in\n      Return (existT _ false i)\n    | Any_type _ i => Return (existT _ true (i B))\n    end.\n\n  Definition type_check_instruction_no_tail_fail {self_type}\n             (type_instruction :\n                forall (i : untyped_syntax.instruction) A,\n                  M (typer_result A))\n             i A B : M (instruction self_type Datatypes.false A B) :=\n    let! r1 := type_instruction i A in\n    match r1 with\n    | Inferred_type _ B' i => instruction_cast_range A B' B i\n    | Any_type _ i => Failed _ (Typing _ tt)\n    end.\n\n  Definition assert_not_tail_fail {self_type} A (r : typer_result A) :\n    M {B & instruction self_type Datatypes.false A B} :=\n    match r with\n    | Inferred_type _ B i => Return (existT _ B i)\n    | Any_type _ _ => Failed _ (Typing _ tt)\n    end.\n\n  Definition type_instruction_no_tail_fail {self_type}\n             (type_instruction :\n                forall (i : untyped_syntax.instruction) A,\n                  M (typer_result A))\n             i A : M {B & instruction self_type Datatypes.false A B} :=\n    let! r := type_instruction i A in\n    assert_not_tail_fail A r.\n\n  Definition type_branches {self_type}\n             (type_instruction :\n                forall (i : untyped_syntax.instruction) A,\n                  M (typer_result A))\n             i1 i2 A1 A2 A\n             (IF_instr : forall B tffa tffb,\n                 instruction self_type tffa A1 B ->\n                 instruction self_type tffb A2 B ->\n                 instruction self_type (tffa && tffb) A B)\n    : M (typer_result A) :=\n    let! r1 := type_instruction i1 A1 in\n    let! r2 := type_instruction i2 A2 in\n    match r1, r2 with\n    | Inferred_type _ B1 i1, Inferred_type _ B2 i2 =>\n      let! i2 := instruction_cast_range A2 B2 B1 i2 in\n      Return\n              (Inferred_type _ _\n                            (IF_instr B1 false false i1 i2))\n    | Inferred_type _ B i1, Any_type _ i2 =>\n      Return (Inferred_type _ _ (IF_instr B false true i1 (i2 B)))\n    | Any_type _ i1, Inferred_type _ B i2 =>\n      Return (Inferred_type _ _ (IF_instr B true false (i1 B) i2))\n    | Any_type _ i1, Any_type _ i2 =>\n      Return (Any_type _ (fun B =>\n                              IF_instr B true true (i1 B) (i2 B)))\n    end.\n\n  Definition take_one (S : stack_type) : M (type * stack_type) :=\n    match S with\n    | nil => Failed _ (Typing _ \"take_one\"%string)\n    | cons a l => Return (a, l)\n    end.\n\n  Fixpoint take_n (A : stack_type) n : M ({B | List.length B = n} * stack_type) :=\n    match n as n return M ({B | List.length B = n} * stack_type) with\n    | 0 => Return (exist (fun B => List.length B = 0) nil eq_refl, A)\n    | S n =>\n      let! (a, A) := take_one A in\n      let! (exist _ B H, C) := take_n A n in\n      Return (exist _ (cons a B) (f_equal S H), C)\n    end.\n\n  Lemma take_n_length n S1 S2 H1 : take_n (S1 ++ S2) n = Return (exist _ S1 H1, S2).\n  Proof.\n    generalize dependent S1.\n    induction n; destruct S1; simpl; intro H1.\n    - repeat f_equal.\n      apply Eqdep_dec.UIP_dec.\n      repeat decide equality.\n    - discriminate.\n    - discriminate.\n    - assert (List.length S1 = n) as H2.\n      + apply (f_equal pred) in H1.\n        exact H1.\n      + rewrite (IHn S1 H2).\n        simpl.\n        repeat f_equal.\n        apply Eqdep_dec.UIP_dec.\n        repeat decide equality.\n  Qed.\n\n  Definition type_check_dig {self_type} n (S:stack_type) : M (typer_result (self_type := self_type) S) :=\n    let! (exist _ S1 H1, tS2) := take_n S n in\n    let! (t, S2) := take_one tS2 in\n    let! i := instruction_cast_domain (S1 +++ t ::: S2) S _ (syntax.DIG n H1) in\n    Return (Inferred_type S (t ::: S1 +++ S2) i).\n\n  Definition type_check_dug {self_type} n (S:stack_type) : M (typer_result (self_type := self_type) S) :=\n    let! (t, S12) := take_one S in\n    let! (exist _ S1 H1, S2) := take_n S12 n in\n    let! i := instruction_cast_domain (t ::: S1 +++ S2) S _ (syntax.DUG n H1) in\n    Return (Inferred_type S (S1 +++ t ::: S2) i).\n\n  Fixpoint as_comparable (a : type) : M comparable_type :=\n    match a with\n    | Comparable_type a => Return (Comparable_type_simple a)\n    | pair (Comparable_type a) b =>\n      let! b := as_comparable b in\n      Return (Cpair a b)\n    | _ => Failed _ (Typing _ (\"not a comparable type\"%string, a))\n    end.\n\n  Lemma as_comparable_comparable (a : comparable_type) :\n    as_comparable a = Return a.\n  Proof.\n    induction a.\n    - reflexivity.\n    - simpl.\n      rewrite IHa.\n      reflexivity.\n  Qed.\n\n  Definition type_contract_data_aux c a tyopt :=\n    match tyopt return C.get_contract_type c = tyopt -> error.M (syntax.concrete_data (contract a)) with\n    | Some b =>\n      match type_dec a b with\n      | left He => fun H => Return (contract_cast c a b H He)\n      | right _ => fun _ => Failed _ (Typing _ (\"ill-typed contract\"%string, c, a, b))\n      end\n    | None => fun _ => Failed _ (Typing _ (\"contract not found\"%string, c))\n    end.\n\n  Definition type_contract_data c a := type_contract_data_aux c a _ eq_refl.\n\n  Fixpoint type_data (d : concrete_data) {struct d}\n    : forall ty, M (syntax.concrete_data ty) :=\n    match d with\n    | Int_constant z =>\n      fun ty =>\n        match ty with\n        | Comparable_type int => Return (syntax.Int_constant z)\n        | Comparable_type nat =>\n          if (z >=? 0)%Z then Return (syntax.Nat_constant (Z.to_N z))\n          else Failed _ (Typing _ (\"Negative value cannot be typed in nat\"%string, d))\n        | Comparable_type mutez =>\n          let! m := tez.of_Z z in\n          Return (syntax.Mutez_constant (Mk_mutez m))\n        | Comparable_type timestamp => Return (syntax.Timestamp_constant z)\n        | _ => Failed _ (Typing _ (d, ty))\n        end\n    | String_constant s =>\n      fun ty =>\n        match ty with\n        | Comparable_type string => Return (syntax.String_constant s)\n        | signature => Return (syntax.Signature_constant s)\n        | key => Return (syntax.Key_constant s)\n        | Comparable_type key_hash => Return (syntax.Key_hash_constant s)\n        | contract a =>\n          let c := Mk_contract s in\n          type_contract_data c a\n        | Comparable_type address => Return (syntax.Address_constant (syntax.Mk_address s))\n        | chain_id => Return (syntax.Chain_id_constant (syntax.Mk_chain_id s))\n        | _ => Failed _ (Typing _ (d, ty))\n        end\n    | Bytes_constant s =>\n      fun ty =>\n        match ty with\n        | Comparable_type bytes => Return (syntax.Bytes_constant s)\n        | _ => Failed _ (Typing _ (d, ty))\n        end\n    | Unit =>\n      fun ty =>\n        match ty with\n        | unit => Return syntax.Unit\n        | _ => Failed _ (Typing _ (d, ty))\n        end\n    | True_ =>\n      fun ty =>\n        match ty with\n        | Comparable_type bool => Return syntax.True_\n        | _ => Failed _ (Typing _ (d, ty))\n        end\n    | False_ =>\n      fun ty =>\n        match ty with\n        | Comparable_type bool => Return syntax.False_\n        | _ => Failed _ (Typing _ (d, ty))\n        end\n    | Pair x y =>\n      fun ty =>\n        match ty with\n        | pair a b =>\n          let! x := type_data x a in\n          let! y := type_data y b in\n          Return (syntax.Pair x y)\n        | _ => Failed _ (Typing _ (d, ty))\n        end\n    | Left x =>\n      fun ty =>\n        match ty with\n        | or a b =>\n          let! x := type_data x a in\n          Return (syntax.Left x)\n        | _ => Failed _ (Typing _ (d, ty))\n        end\n    | Right y =>\n      fun ty =>\n        match ty with\n        | or a b =>\n          let! y := type_data y b in\n          Return (syntax.Right y)\n        | _ => Failed _ (Typing _ (d, ty))\n        end\n    | Some_ x =>\n      fun ty =>\n        match ty with\n        | option a =>\n          let! x := type_data x a in\n          Return (syntax.Some_ x)\n        | _ => Failed _ (Typing _ (d, ty))\n        end\n    | None_ =>\n      fun ty =>\n        match ty with\n        | option a => Return syntax.None_\n        | _ => Failed _ (Typing _ (d, ty))\n        end\n    | Concrete_seq l =>\n      fun ty =>\n        match ty with\n        | list a =>\n          let! l :=\n            (fix type_data_list l :=\n              match l with\n              | nil => Return nil\n              | cons x l =>\n                let! x := type_data x a in\n                let! l := type_data_list l in\n                Return (cons x l)\n              end\n            ) l in\n          Return (syntax.Concrete_list l)\n        | set a =>\n          let! l :=\n            (fix type_data_list l :=\n              match l with\n              | nil => Return nil\n              | cons x l =>\n                let! x := type_data x a in\n                let! l := type_data_list l in\n                Return (cons x l)\n              end\n            ) l in\n          Return (syntax.Concrete_set l)\n        | map a b =>\n          let! l :=\n            (fix type_data_list l :=\n              match l with\n              | nil => Return nil\n              | cons (Elt x y) l =>\n                let! x := type_data x a in\n                let! y := type_data y b in\n                let! l := type_data_list l in\n                Return (cons (syntax.Elt _ _ x y) l)\n              | _ => Failed _ (Typing _ (d, ty))\n              end\n            ) l in\n          Return (syntax.Concrete_map l)\n        | _ => Failed _ (Typing _ (d, ty))\n        end\n    | Instruction i =>\n      fun ty =>\n        match ty with\n        | lambda a b =>\n          let! existT _ tff i := type_check_instruction type_instruction i (cons a nil) (cons b nil) in\n          Return (syntax.Instruction _ i)\n        | _ => Failed _ (Typing _ (d, ty))\n        end\n    | d => fun ty => Failed _ (Typing _ (d, ty))\n    end\n\n  with\n  type_instruction {self_type} i A {struct i} : M (typer_result (self_type := self_type) A) :=\n    match i, A with\n    | NOOP, A => Return (Inferred_type _ _ syntax.NOOP)\n    | FAILWITH, a :: A => Return (Any_type _ (fun B => syntax.FAILWITH))\n    | SEQ i1 i2, A =>\n      let! existT _ B i1 := type_instruction_no_tail_fail type_instruction i1 A in\n      let! r2 := type_instruction i2 B in\n      match r2 with\n      | Inferred_type _ C i2 =>\n        Return (Inferred_type _ _ (syntax.SEQ i1 i2))\n      | Any_type _ i2 =>\n        Return (Any_type _ (fun C => syntax.SEQ i1 (i2 C)))\n      end\n    | IF_ i1 i2, Comparable_type bool :: A =>\n      type_branches type_instruction i1 i2 _ _ _ (fun B tffa tffb => syntax.IF_)\n    | IF_NONE i1 i2, option a :: A =>\n      type_branches type_instruction i1 i2 _ _ _ (fun B tffa tffb => syntax.IF_NONE)\n    | IF_LEFT i1 i2, or a b :: A =>\n      type_branches type_instruction i1 i2 _ _ _ (fun B tffa tffb => syntax.IF_LEFT)\n    | IF_CONS i1 i2, list a :: A =>\n      type_branches type_instruction i1 i2 _ _ _ (fun B tffa tffb => syntax.IF_CONS)\n    | LOOP i, Comparable_type bool :: A =>\n      let! i := type_check_instruction_no_tail_fail\n        type_instruction i A (bool ::: A) in\n      Return (Inferred_type _ _ (syntax.LOOP i))\n    | LOOP_LEFT i, or a b :: A =>\n      let! i := type_check_instruction_no_tail_fail\n        type_instruction i (a :: A) (or a b :: A) in\n      Return (Inferred_type _ _ (syntax.LOOP_LEFT i))\n    | EXEC, a :: lambda a' b :: B =>\n      let A := a :: lambda a' b :: B in\n      let A' := a :: lambda a b :: B in\n      let! i := instruction_cast_domain A' A _ syntax.EXEC in\n      Return (Inferred_type _ _ i)\n    | APPLY, a :: lambda (pair a' b) c :: B =>\n      let A := a :: lambda (pair a' b) c :: B in\n      let A' := a :: lambda (pair a b) c :: B in\n      (if is_packable a as b return is_packable a = b -> _\n       then fun i =>\n        let! i := instruction_cast_domain A' A _ (@syntax.APPLY _ _ _ _ _ (IT_eq_rev _ i)) in\n        Return (Inferred_type _ _ i)\n       else fun _ => Failed _ (Typing _ \"APPLY\"%string)) eq_refl\n    | DUP, a :: A =>\n      Return (Inferred_type _ _ syntax.DUP)\n    | SWAP, a :: b :: A =>\n      Return (Inferred_type _ _ syntax.SWAP)\n    | PUSH a v, A =>\n      let! d := type_data v a in\n      Return (Inferred_type _ _ (syntax.PUSH a d))\n    | UNIT, A => Return (Inferred_type _ _ syntax.UNIT)\n    | LAMBDA a b i, A =>\n      let! existT _ tff i :=\n        type_check_instruction type_instruction i (a :: nil) (b :: nil) in\n      Return (Inferred_type _ _ (syntax.LAMBDA a b i))\n    | EQ, Comparable_type int :: A =>\n      Return (Inferred_type _ _ syntax.EQ)\n    | NEQ, Comparable_type int :: A =>\n      Return (Inferred_type _ _ syntax.NEQ)\n    | LT, Comparable_type int :: A =>\n      Return (Inferred_type _ _ syntax.LT)\n    | GT, Comparable_type int :: A =>\n      Return (Inferred_type _ _ syntax.GT)\n    | LE, Comparable_type int :: A =>\n      Return (Inferred_type _ _ syntax.LE)\n    | GE, Comparable_type int :: A =>\n      Return (Inferred_type _ _ syntax.GE)\n    | OR, Comparable_type bool :: Comparable_type bool :: A =>\n      Return (Inferred_type _ _ (@syntax.OR _ _ syntax.bitwise_bool _))\n    | OR, Comparable_type nat :: Comparable_type nat :: A =>\n      Return (Inferred_type _ _ (@syntax.OR _ _ syntax.bitwise_nat _))\n    | AND, Comparable_type bool :: Comparable_type bool :: A =>\n      Return (Inferred_type _ _ (@syntax.AND _ _ syntax.bitwise_bool _))\n    | AND, Comparable_type nat :: Comparable_type nat :: A =>\n      Return (Inferred_type _ _ (@syntax.AND _ _ syntax.bitwise_nat _))\n    | XOR, Comparable_type bool :: Comparable_type bool :: A =>\n      Return (Inferred_type _ _ (@syntax.XOR _ _ syntax.bitwise_bool _))\n    | XOR, Comparable_type nat :: Comparable_type nat :: A =>\n      Return (Inferred_type _ _ (@syntax.XOR _ _ syntax.bitwise_nat _))\n    | NOT, Comparable_type bool :: A =>\n      Return (Inferred_type _ _ (@syntax.NOT _ _ syntax.not_bool _))\n    | NOT, Comparable_type nat :: A =>\n      Return (Inferred_type _ _ (@syntax.NOT _ _ syntax.not_nat _))\n    | NOT, Comparable_type int :: A =>\n      Return (Inferred_type _ _ (@syntax.NOT _ _ syntax.not_int _))\n    | NEG, Comparable_type nat :: A =>\n      Return (Inferred_type _ _ (@syntax.NEG _ _ syntax.neg_nat _))\n    | NEG, Comparable_type int :: A =>\n      Return (Inferred_type _ _ (@syntax.NEG _ _ syntax.neg_int _))\n    | ABS, Comparable_type int :: A =>\n      Return (Inferred_type _ _ syntax.ABS)\n    | INT, Comparable_type nat :: A =>\n      Return (Inferred_type _ _ syntax.INT)\n    | ISNAT, Comparable_type int :: A =>\n      Return (Inferred_type _ _ syntax.ISNAT)\n    | ADD, Comparable_type nat :: Comparable_type nat :: A =>\n      Return (Inferred_type _ _ (@syntax.ADD _ _ _ syntax.add_nat_nat _))\n    | ADD, Comparable_type nat :: Comparable_type int :: A =>\n      Return (Inferred_type _ _ (@syntax.ADD _ _ _ syntax.add_nat_int _))\n    | ADD, Comparable_type int :: Comparable_type nat :: A =>\n      Return (Inferred_type _ _ (@syntax.ADD _ _ _ syntax.add_int_nat _))\n    | ADD, Comparable_type int :: Comparable_type int :: A =>\n      Return (Inferred_type _ _ (@syntax.ADD _ _ _ syntax.add_int_int _))\n    | ADD, Comparable_type timestamp :: Comparable_type int :: A =>\n      Return (Inferred_type _ _ (@syntax.ADD _ _ _ syntax.add_timestamp_int _))\n    | ADD, Comparable_type int :: Comparable_type timestamp :: A =>\n      Return (Inferred_type _ _ (@syntax.ADD _ _ _ syntax.add_int_timestamp _))\n    | ADD, Comparable_type mutez :: Comparable_type mutez :: A =>\n      Return (Inferred_type _ _ (@syntax.ADD _ _ _ syntax.add_tez_tez _))\n    | SUB, Comparable_type nat :: Comparable_type nat :: A =>\n      Return (Inferred_type _ _ (@syntax.SUB _ _ _ syntax.sub_nat_nat _))\n    | SUB, Comparable_type nat :: Comparable_type int :: A =>\n      Return (Inferred_type _ _ (@syntax.SUB _ _ _ syntax.sub_nat_int _))\n    | SUB, Comparable_type int :: Comparable_type nat :: A =>\n      Return (Inferred_type _ _ (@syntax.SUB _ _ _ syntax.sub_int_nat _))\n    | SUB, Comparable_type int :: Comparable_type int :: A =>\n      Return (Inferred_type _ _ (@syntax.SUB _ _ _ syntax.sub_int_int _))\n    | SUB, Comparable_type timestamp :: Comparable_type int :: A =>\n      Return (Inferred_type _ _ (@syntax.SUB _ _ _ syntax.sub_timestamp_int _))\n    | SUB, Comparable_type timestamp :: Comparable_type timestamp :: A =>\n      Return (Inferred_type _ _ (@syntax.SUB _ _ _ syntax.sub_timestamp_timestamp _))\n    | SUB, Comparable_type mutez :: Comparable_type mutez :: A =>\n      Return (Inferred_type _ _ (@syntax.SUB _ _ _ syntax.sub_tez_tez _))\n    | MUL, Comparable_type nat :: Comparable_type nat :: A =>\n      Return (Inferred_type _ _ (@syntax.MUL _ _ _ syntax.mul_nat_nat _))\n    | MUL, Comparable_type nat :: Comparable_type int :: A =>\n      Return (Inferred_type _ _ (@syntax.MUL _ _ _ syntax.mul_nat_int _))\n    | MUL, Comparable_type int :: Comparable_type nat :: A =>\n      Return (Inferred_type _ _ (@syntax.MUL _ _ _ syntax.mul_int_nat _))\n    | MUL, Comparable_type int :: Comparable_type int :: A =>\n      Return (Inferred_type _ _ (@syntax.MUL _ _ _ syntax.mul_int_int _))\n    | MUL, Comparable_type mutez :: Comparable_type nat :: A =>\n      Return (Inferred_type _ _ (@syntax.MUL _ _ _ syntax.mul_tez_nat _))\n    | MUL, Comparable_type nat :: Comparable_type mutez :: A =>\n      Return (Inferred_type _ _ (@syntax.MUL _ _ _ syntax.mul_nat_tez _))\n    | EDIV, Comparable_type nat :: Comparable_type nat :: A =>\n      Return (Inferred_type _ _ (@syntax.EDIV _ _ _ syntax.ediv_nat_nat _))\n    | EDIV, Comparable_type nat :: Comparable_type int :: A =>\n      Return (Inferred_type _ _ (@syntax.EDIV _ _ _ syntax.ediv_nat_int _))\n    | EDIV, Comparable_type int :: Comparable_type nat :: A =>\n      Return (Inferred_type _ _ (@syntax.EDIV _ _ _ syntax.ediv_int_nat _))\n    | EDIV, Comparable_type int :: Comparable_type int :: A =>\n      Return (Inferred_type _ _ (@syntax.EDIV _ _ _ syntax.ediv_int_int _))\n    | EDIV, Comparable_type mutez :: Comparable_type nat :: A =>\n      Return (Inferred_type _ _ (@syntax.EDIV _ _ _ syntax.ediv_tez_nat _))\n    | EDIV, Comparable_type mutez :: Comparable_type mutez :: A =>\n      Return (Inferred_type _ _ (@syntax.EDIV _ _ _ syntax.ediv_tez_tez _))\n    | LSL, Comparable_type nat :: Comparable_type nat :: A =>\n      Return (Inferred_type _ _ syntax.LSL)\n    | LSR, Comparable_type nat :: Comparable_type nat :: A =>\n      Return (Inferred_type _ _ syntax.LSR)\n    | COMPARE, a :: a' :: B =>\n      let A := a ::: a' ::: B in\n      let! a : comparable_type := as_comparable a in\n      let! a' : comparable_type := as_comparable a' in\n      let A' := a ::: a ::: B in\n      let! i := instruction_cast_domain A' A (int ::: B) (syntax.COMPARE (a := a)) in\n      Return (Inferred_type _ _ i)\n    | CONCAT, Comparable_type string :: Comparable_type string :: B =>\n      Return (Inferred_type _ _ (@syntax.CONCAT _ _ stringlike_string _))\n    | CONCAT, Comparable_type bytes :: Comparable_type bytes :: B =>\n      Return (Inferred_type _ _ (@syntax.CONCAT _ _ stringlike_bytes _))\n    | CONCAT, list (Comparable_type string) :: B =>\n      Return (Inferred_type _ _ (@syntax.CONCAT_list _ _ stringlike_string _))\n    | CONCAT, list (Comparable_type bytes) :: B =>\n      Return (Inferred_type _ _ (@syntax.CONCAT_list _ _ stringlike_bytes _))\n    | SIZE, set a :: A =>\n      Return (Inferred_type _ _ (@syntax.SIZE _ _ (size_set a) _))\n    | SIZE, cons (list a) A =>\n      Return (Inferred_type _ _ (@syntax.SIZE _ _ (size_list a) _))\n    | SIZE, cons (map a b) A =>\n      Return (Inferred_type _ _ (@syntax.SIZE _ _ (size_map a b) _))\n    | SIZE, Comparable_type string :: A =>\n      Return (Inferred_type _ _ (@syntax.SIZE _ _ size_string _))\n    | SIZE, Comparable_type bytes :: A =>\n      Return (Inferred_type _ _ (@syntax.SIZE _ _ size_bytes _))\n    | SLICE, Comparable_type nat :: Comparable_type nat :: Comparable_type string :: A =>\n      Return (Inferred_type _ _ (@syntax.SLICE _ _ stringlike_string _))\n    | SLICE, Comparable_type nat :: Comparable_type nat :: Comparable_type bytes :: A =>\n      Return (Inferred_type _ _ (@syntax.SLICE _ _ stringlike_bytes _))\n    | PAIR, a :: b :: A =>\n      Return (Inferred_type _ _ syntax.PAIR)\n    | CAR, pair a b :: A =>\n      Return (Inferred_type _ _ syntax.CAR)\n    | CDR, pair a b :: A =>\n      Return (Inferred_type _ _ syntax.CDR)\n    | EMPTY_SET c, A =>\n      Return (Inferred_type _ _ (syntax.EMPTY_SET c))\n    | MEM, elt' :: set elt :: B =>\n      let A := elt' :: set elt :: B in\n      let A' := elt ::: set elt :: B in\n      let! i := instruction_cast_domain\n        A' A _ (@syntax.MEM _ _ _ (mem_set elt) _) in\n      Return (Inferred_type _ _ i)\n    | MEM, kty' :: map kty vty :: B =>\n      let A := kty' :: map kty vty :: B in\n      let A' := kty ::: map kty vty :: B in\n      let! i := instruction_cast_domain\n        A' A _ (@syntax.MEM _ _ _ (mem_map kty vty) _) in\n      Return (Inferred_type _ _ i)\n    | MEM, kty' :: big_map kty vty :: B =>\n      let A := kty' :: big_map kty vty :: B in\n      let A' := kty ::: big_map kty vty :: B in\n      let! i := instruction_cast_domain\n        A' A _ (@syntax.MEM _ _ _ (mem_bigmap kty vty) _) in\n      Return (Inferred_type _ _ i)\n    | UPDATE, elt' :: Comparable_type bool :: set elt :: B =>\n      let A := elt' ::: bool ::: set elt :: B in\n      let A' := elt ::: bool ::: set elt :: B in\n      let! i := instruction_cast_domain\n        A' A _ (@syntax.UPDATE _ _ _ _ (update_set elt) _) in\n      Return (Inferred_type _ _ i)\n    | UPDATE, kty' :: option vty' :: map kty vty :: B =>\n      let A := kty' ::: option vty' ::: map kty vty :: B in\n      let A' := kty ::: option vty ::: map kty vty :: B in\n      let! i := instruction_cast_domain\n        A' A _ (@syntax.UPDATE _ _ _ _ (update_map kty vty) _) in\n      Return (Inferred_type _ _ i)\n    | UPDATE, kty' :: option vty' :: big_map kty vty :: B =>\n      let A := kty' ::: option vty' ::: big_map kty vty :: B in\n      let A' := kty ::: option vty ::: big_map kty vty :: B in\n      let! i := instruction_cast_domain\n        A' A _ (@syntax.UPDATE _ _ _ _ (update_bigmap kty vty) _) in\n      Return (Inferred_type _ _ i)\n    | ITER i, list a :: A =>\n      let! i := type_check_instruction_no_tail_fail type_instruction i (a :: A) A in\n      Return (Inferred_type _ _ (syntax.ITER i))\n    | ITER i, set a :: A =>\n      let! i := type_check_instruction_no_tail_fail type_instruction i (a ::: A) A in\n      Return (Inferred_type _ _ (syntax.ITER i))\n    | ITER i, map kty vty :: A =>\n      let! i := type_check_instruction_no_tail_fail type_instruction i (pair kty vty :: A) A in\n      Return (Inferred_type _ _ (syntax.ITER i))\n    | EMPTY_MAP kty vty, A =>\n      Return (Inferred_type _ _ (syntax.EMPTY_MAP kty vty))\n    | EMPTY_BIG_MAP kty vty, A =>\n      Return (Inferred_type _ _ (syntax.EMPTY_BIG_MAP kty vty))\n    | GET, kty' :: map kty vty :: B =>\n      let A := kty' :: map kty vty :: B in\n      let A' := kty ::: map kty vty :: B in\n      let! i := instruction_cast_domain\n        A' A _ (@syntax.GET _ _ _ (get_map kty vty) _) in\n      Return (Inferred_type _ _ i)\n    | GET, kty' :: big_map kty vty :: B =>\n      let A := kty' :: big_map kty vty :: B in\n      let A' := kty ::: big_map kty vty :: B in\n      let! i := instruction_cast_domain\n        A' A _ (@syntax.GET _ _ _ (get_bigmap kty vty) _) in\n      Return (Inferred_type _ _ i)\n    | MAP i, list a :: A =>\n      let! r := type_instruction_no_tail_fail type_instruction i (a :: A) in\n      match r with\n      | existT _ (b :: A') i =>\n        let! i := instruction_cast_range (a :: A) (b :: A') (b :: A) i in\n        Return (Inferred_type _ _ (syntax.MAP i))\n      | _ => Failed _ (Typing _ tt)\n      end\n    | MAP i, map kty vty :: A =>\n      let! r := type_instruction_no_tail_fail type_instruction i (pair kty vty ::: A) in\n      match r with\n      | existT _ (b :: A') i =>\n        let! i := instruction_cast_range (pair kty vty :: A) (b :: A') (b :: A) i in\n        Return (Inferred_type _ _ (syntax.MAP i))\n      | _ => Failed _ (Typing _ tt)\n      end\n    | SOME, a :: A => Return (Inferred_type _ _ syntax.SOME)\n    | NONE a, A => Return (Inferred_type _ _ (syntax.NONE a))\n    | LEFT b, a :: A => Return (Inferred_type _ _ (syntax.LEFT b))\n    | RIGHT a, b :: A => Return (Inferred_type _ _ (syntax.RIGHT a))\n    | CONS, a' :: list a :: B =>\n      let A := a' :: list a :: B in\n      let A' := a :: list a :: B in\n      let! i := instruction_cast_domain A' A _ (syntax.CONS) in\n      Return (Inferred_type _ _ i)\n    | NIL a, A => Return (Inferred_type _ _ (syntax.NIL a))\n    | CREATE_CONTRACT g p i,\n      option (Comparable_type key_hash) :: Comparable_type mutez :: g2 :: B =>\n      let A :=\n          option key_hash ::: mutez ::: g2 :: B in\n      let A' :=\n          option key_hash ::: mutez ::: g ::: B in\n      let! existT _ tff i :=\n        type_check_instruction (self_type := Some p) type_instruction i (pair p g :: nil) (pair (list operation) g :: nil) in\n      let! i := instruction_cast_domain A' A _ (syntax.CREATE_CONTRACT g p i) in\n      Return (Inferred_type _ _ i)\n    | TRANSFER_TOKENS, p1 :: Comparable_type mutez :: contract p2 :: B =>\n      let A := p1 ::: mutez ::: contract p2 ::: B in\n      let A' := p1 ::: mutez ::: contract p1 ::: B in\n      let! i := instruction_cast_domain A' A _ syntax.TRANSFER_TOKENS in\n      Return (Inferred_type _ _ i)\n    | SET_DELEGATE, option (Comparable_type key_hash) :: A =>\n      Return (Inferred_type _ _ syntax.SET_DELEGATE)\n    | BALANCE, A =>\n      Return (Inferred_type _ _ syntax.BALANCE)\n    | ADDRESS, contract _ :: A =>\n      Return (Inferred_type _ _ syntax.ADDRESS)\n    | CONTRACT ty, Comparable_type address :: A =>\n      Return (Inferred_type _ _ (syntax.CONTRACT ty))\n    | SOURCE, A =>\n      Return (Inferred_type _ _ syntax.SOURCE)\n    | SENDER, A =>\n      Return (Inferred_type _ _ syntax.SENDER)\n    | SELF, A =>\n      match self_type with\n      | Some sty => Return (Inferred_type _ _ syntax.SELF)\n      | None => Failed _ (Typing _ \"SELF is not allowed inside lambdas\"%string)\n      end\n    | AMOUNT, A =>\n      Return (Inferred_type _ _ syntax.AMOUNT)\n    | IMPLICIT_ACCOUNT, Comparable_type key_hash :: A =>\n      Return (Inferred_type _ _ syntax.IMPLICIT_ACCOUNT)\n    | NOW, A =>\n      Return (Inferred_type _ _ syntax.NOW)\n    | PACK, a :: A =>\n      Return (Inferred_type _ _ syntax.PACK)\n    | UNPACK ty, Comparable_type bytes :: A =>\n      Return (Inferred_type _ _ (syntax.UNPACK ty))\n    | HASH_KEY, key :: A =>\n      Return (Inferred_type _ _ syntax.HASH_KEY)\n    | BLAKE2B, Comparable_type bytes :: A =>\n      Return (Inferred_type _ _ syntax.BLAKE2B)\n    | SHA256, Comparable_type bytes :: A =>\n      Return (Inferred_type _ _ syntax.SHA256)\n    | SHA512, Comparable_type bytes :: A =>\n      Return (Inferred_type _ _ syntax.SHA512)\n    | CHECK_SIGNATURE, key :: signature :: Comparable_type bytes :: A =>\n      Return (Inferred_type _ _ syntax.CHECK_SIGNATURE)\n    | DIG n, A => type_check_dig n _\n    | DUG n, A => type_check_dug n _\n    | DIP n i, S12 =>\n      let! (exist _ S1 H1, S2) := take_n S12 n in\n      let! existT _ B i := type_instruction_no_tail_fail type_instruction i S2 in\n      let! i := instruction_cast_domain (S1 +++ S2) S12 _ (syntax.DIP n H1 i) in\n      Return (Inferred_type S12 (S1 +++ B) i)\n    | DROP n, S12 =>\n      let! (exist _ S1 H1, S2) := take_n S12 n in\n      let! i := instruction_cast_domain (S1 +++ S2) S12 _ (syntax.DROP n H1) in\n      Return (Inferred_type S12 S2 i)\n    | CHAIN_ID, _ =>\n      Return (Inferred_type _ _ syntax.CHAIN_ID)\n    | _, _ => Failed _ (Typing _ (i, A))\n    end.\nEnd Typer.\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/typer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2927832045933706}}
{"text": "Require Import Coq.Lists.List.\nRequire Import MirrorShard.SepExpr.\nRequire Import MirrorShard.ExprTac.\n\nModule Make (ST : SepTheory.SepTheory) (SE : SepExpr ST).\n\n  Section abstracted.\n    Variables (not : Prop -> Prop)\n              (emp : ST.hprop)\n              (star : ST.hprop -> ST.hprop -> ST.hprop)\n              (ex : forall T : Type, (T -> ST.hprop) -> ST.hprop)\n              (inj : Prop -> ST.hprop).\n    Variables (types : list Expr.type) (funcs : Expr.functions types)\n      (sfuncs : SE.predicates types) (meta_env : Expr.env types).\n\n    Fixpoint nsexprD (var_env : Expr.env types) (s : SE.sexpr types)\n      {struct s} : ST.hprop :=\n      match s with\n        | SE.Emp => emp\n        | SE.Inj p =>\n          match nexprD not types funcs meta_env var_env p Expr.tvProp with\n            | Some p0 => inj p0\n            | None => inj (SepExpr.BadInj p)\n          end\n        | SE.Star l r =>\n          star (nsexprD var_env l) (nsexprD var_env r)\n        | SE.Exists t b =>\n          ex _\n          (fun x : Expr.tvarD types t =>\n            nsexprD (@existT _ (Expr.tvarD types) t x :: var_env) b)\n        | SE.Func f b =>\n          match nth_error sfuncs f with\n            | Some f' =>\n              match\n                Expr.applyD (nexprD not types funcs meta_env var_env)\n                (SE.SDomain f') b ST.hprop (SE.SDenotation f')\n                with\n                | Some p => p\n                | None => inj (SepExpr.BadPredApply f b var_env)\n              end\n            | None => inj (SepExpr.BadPred f)\n          end\n        | SE.Const p => p\n      end.\n  End abstracted.\n\n  Theorem nsexprD_sexprD : nsexprD not ST.emp ST.star ST.ex ST.inj = SE.sexprD.\n  Proof. reflexivity. Qed.\nEnd Make.\n", "meta": {"author": "gmalecha", "repo": "mirror-shard", "sha": "24f34dee2f78de731f4ef398733ff2c1f1551375", "save_path": "github-repos/coq/gmalecha-mirror-shard", "path": "github-repos/coq/gmalecha-mirror-shard/mirror-shard-24f34dee2f78de731f4ef398733ff2c1f1551375/src/SepExprTac.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544335934765, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.29277567019884987}}
{"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 A1 A2 B1 B2 C1 C2 Q P R M C0 : Universe, ((wd_ Q P /\\ (wd_ P R /\\ (wd_ Q R /\\ (wd_ A1 A2 /\\ (wd_ C1 C2 /\\ (wd_ B1 B2 /\\ (wd_ M Q /\\ (wd_ C1 C0 /\\ (wd_ C2 C0 /\\ (wd_ P C0 /\\ (wd_ Q C1 /\\ (wd_ Q C2 /\\ (wd_ B2 P /\\ (wd_ B1 P /\\ (wd_ A2 R /\\ (wd_ A1 R /\\ (wd_ B1 C1 /\\ (wd_ B1 C2 /\\ (wd_ B2 C1 /\\ (wd_ B2 C2 /\\ (col_ A1 A2 Q /\\ (col_ B1 B2 Q /\\ (col_ A1 A2 P /\\ (col_ C1 C2 P /\\ (col_ B1 B2 R /\\ (col_ C1 C2 C0 /\\ col_ P Q C0)))))))))))))))))))))))))) -> col_ Q C1 C2)).\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_0272.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.29273780738976307}}
{"text": "From iris.program_logic Require Export weakestpre.\nFrom iris.program_logic Require Import lifting adequacy.\nFrom iris.program_logic Require ectx_language.\nFrom iris.algebra Require Import auth.\nFrom iris.proofmode Require Import tactics classes.\nSet Default Proof Using \"Type\".\n\nClass ownPG (Λ : language) (Σ : gFunctors) := OwnPG {\n  ownP_invG : invG Σ;\n  ownP_inG :> inG Σ (authR (optionUR (exclR (stateC Λ))));\n  ownP_name : gname;\n}.\n\nInstance ownPG_irisG `{ownPG Λ Σ} : irisG Λ Σ := {\n  iris_invG := ownP_invG;\n  state_interp σ κs _ := own ownP_name (● (Excl' σ))%I;\n  fork_post _ := True%I;\n}.\nGlobal Opaque iris_invG.\n\nDefinition ownPΣ (Λ : language) : gFunctors :=\n  #[invΣ;\n    GFunctor (authR (optionUR (exclR (stateC Λ))))].\n\nClass ownPPreG (Λ : language) (Σ : gFunctors) : Set := IrisPreG {\n  ownPPre_invG :> invPreG Σ;\n  ownPPre_state_inG :> inG Σ (authR (optionUR (exclR (stateC Λ))))\n}.\n\nInstance subG_ownPΣ {Λ Σ} : subG (ownPΣ Λ) Σ → ownPPreG Λ Σ.\nProof. solve_inG. Qed.\n\n(** Ownership *)\nDefinition ownP `{ownPG Λ Σ} (σ : state Λ) : iProp Σ :=\n  own ownP_name (◯ (Excl' σ)).\n\nTypeclasses Opaque ownP.\nInstance: Params (@ownP) 3.\n\n(* Adequacy *)\nTheorem ownP_adequacy Σ `{ownPPreG Λ Σ} s e σ φ :\n  (∀ `{ownPG Λ Σ}, ownP σ ⊢ WP e @ s; ⊤ {{ v, ⌜φ v⌝ }}) →\n  adequate s e σ (λ v _, φ v).\nProof.\n  intros Hwp. apply (wp_adequacy Σ _).\n  iIntros (? κs).\n  iMod (own_alloc (● (Excl' σ) ⋅ ◯ (Excl' σ))) as (γσ) \"[Hσ Hσf]\"; first done.\n  iModIntro. iExists (λ σ κs, own γσ (● (Excl' σ)))%I.\n  iFrame \"Hσ\".\n  iApply (Hwp (OwnPG _ _ _ _ γσ)). rewrite /ownP. iFrame.\nQed.\n\nTheorem ownP_invariance Σ `{ownPPreG Λ Σ} s e σ1 t2 σ2 φ :\n  (∀ `{ownPG Λ Σ},\n      ownP σ1 ={⊤}=∗ WP e @ s; ⊤ {{ _, True }} ∗\n      |={⊤,∅}=> ∃ σ', ownP σ' ∧ ⌜φ σ'⌝) →\n  rtc erased_step ([e], σ1) (t2, σ2) →\n  φ σ2.\nProof.\n  intros Hwp Hsteps. eapply (wp_invariance Σ Λ s e σ1 t2 σ2 _)=> //.\n  iIntros (? κs κs').\n  iMod (own_alloc (● (Excl' σ1) ⋅ ◯ (Excl' σ1))) as (γσ) \"[Hσ Hσf]\"; first done.\n  iExists (λ σ κs' _, own γσ (● (Excl' σ)))%I, (λ _, True%I).\n  iFrame \"Hσ\".\n  iMod (Hwp (OwnPG _ _ _ _ γσ) with \"[Hσf]\") as \"[$ H]\";\n    first by rewrite /ownP; iFrame.\n  iIntros \"!> Hσ\". iMod \"H\" as (σ2') \"[Hσf %]\". rewrite /ownP.\n  iDestruct (own_valid_2 with \"Hσ Hσf\")\n    as %[Hp%Excl_included _]%auth_valid_discrete_2; simplify_eq; auto.\nQed.\n\n\n(** Lifting *)\nSection lifting.\n  Context `{ownPG Λ Σ}.\n  Implicit Types s : stuckness.\n  Implicit Types e : expr Λ.\n  Implicit Types Φ : val Λ → iProp Σ.\n\n  Lemma ownP_eq σ1 σ2 κs n : state_interp σ1 κs n -∗ ownP σ2 -∗ ⌜σ1 = σ2⌝.\n  Proof.\n    iIntros \"Hσ● Hσ◯\". rewrite /ownP.\n    iDestruct (own_valid_2 with \"Hσ● Hσ◯\") as %[Hps _]%auth_valid_discrete_2.\n    by pose proof (leibniz_equiv _ _ (Excl_included _ _ Hps)) as ->.\n  Qed.\n  Lemma ownP_state_twice σ1 σ2 : ownP σ1 ∗ ownP σ2 ⊢ False.\n  Proof. rewrite /ownP -own_op own_valid. by iIntros (?). Qed.\n  Global Instance ownP_timeless σ : Timeless (@ownP Λ Σ _ σ).\n  Proof. rewrite /ownP; apply _. Qed.\n\n  Lemma ownP_lift_step s E Φ e1 :\n    (|={E,∅}=> ∃ σ1, ⌜if s is NotStuck then reducible e1 σ1 else to_val e1 = None⌝ ∗\n      ▷ ownP σ1 ∗\n      ▷ ∀ κ e2 σ2 efs, ⌜prim_step e1 σ1 κ e2 σ2 efs⌝ -∗\n      ownP σ2\n            ={∅,E}=∗ WP e2 @ s; E {{ Φ }} ∗ [∗ list] ef ∈ efs, WP ef @ s; ⊤ {{ _, True }})\n    ⊢ WP e1 @ s; E {{ Φ }}.\n  Proof.\n    iIntros \"H\". destruct (to_val e1) as [v|] eqn:EQe1.\n    - apply of_to_val in EQe1 as <-. iApply fupd_wp.\n      iMod \"H\" as (σ1) \"[Hred _]\"; iDestruct \"Hred\" as %Hred.\n      destruct s; last done. apply reducible_not_val in Hred.\n      move: Hred; by rewrite to_of_val.\n    - iApply wp_lift_step; [done|]; iIntros (σ1 κ κs n) \"Hσκs\".\n      iMod \"H\" as (σ1' ?) \"[>Hσf H]\".\n      iDestruct (ownP_eq with \"Hσκs Hσf\") as %<-.\n      iModIntro; iSplit; [by destruct s|]; iNext; iIntros (e2 σ2 efs Hstep).\n      iDestruct \"Hσκs\" as \"Hσ\". rewrite /ownP.\n      iMod (own_update_2 with \"Hσ Hσf\") as \"[Hσ Hσf]\".\n      { apply auth_update. apply: option_local_update.\n         by apply: (exclusive_local_update _ (Excl σ2)). }\n      iFrame \"Hσ\". iApply (\"H\" with \"[]\"); eauto with iFrame.\n  Qed.\n\n  Lemma ownP_lift_stuck E Φ e :\n    (|={E,∅}=> ∃ σ, ⌜stuck e σ⌝ ∗ ▷ (ownP σ))\n    ⊢ WP e @ E ?{{ Φ }}.\n  Proof.\n    iIntros \"H\". destruct (to_val e) as [v|] eqn:EQe.\n    - apply of_to_val in EQe as <-. iApply fupd_wp.\n      iMod \"H\" as (σ1) \"[H _]\". iDestruct \"H\" as %[Hnv _]. exfalso.\n      by rewrite to_of_val in Hnv.\n    - iApply wp_lift_stuck; [done|]. iIntros (σ1 κs n) \"Hσ\".\n      iMod \"H\" as (σ1') \"(% & >Hσf)\".\n      by iDestruct (ownP_eq with \"Hσ Hσf\") as %->.\n  Qed.\n\n  Lemma ownP_lift_pure_step `{Inhabited (state Λ)} s E Φ e1 :\n    (∀ σ1, if s is NotStuck then reducible e1 σ1 else to_val e1 = None) →\n    (∀ σ1 κ e2 σ2 efs, prim_step e1 σ1 κ e2 σ2 efs → κ = [] ∧ σ2 = σ1) →\n    (▷ ∀ κ e2 efs σ, ⌜prim_step e1 σ κ e2 σ efs⌝ →\n      WP e2 @ s; E {{ Φ }} ∗ [∗ list] ef ∈ efs, WP ef @ s; ⊤ {{ _, True }})\n    ⊢ WP e1 @ s; E {{ Φ }}.\n  Proof.\n    iIntros (Hsafe Hstep) \"H\"; iApply wp_lift_step.\n    { specialize (Hsafe inhabitant). destruct s; last done.\n      by eapply reducible_not_val. }\n    iIntros (σ1 κ κs n) \"Hσ\". iMod (fupd_intro_mask' E ∅) as \"Hclose\"; first set_solver.\n    iModIntro; iSplit; [by destruct s|]; iNext; iIntros (e2 σ2 efs ?).\n    destruct (Hstep σ1 κ e2 σ2 efs); auto; subst.\n    by iMod \"Hclose\"; iModIntro; iFrame; iApply \"H\".\n  Qed.\n\n  (** Derived lifting lemmas. *)\n  Lemma ownP_lift_atomic_step {s E Φ} e1 σ1 :\n    (if s is NotStuck then reducible e1 σ1 else to_val e1 = None) →\n    (▷ (ownP σ1) ∗\n       ▷ ∀ κ e2 σ2 efs, ⌜prim_step e1 σ1 κ e2 σ2 efs⌝ -∗\n         ownP σ2 -∗\n      from_option Φ False (to_val e2) ∗ [∗ list] ef ∈ efs, WP ef @ s; ⊤ {{ _, True }})\n    ⊢ WP e1 @ s; E {{ Φ }}.\n  Proof.\n    iIntros (?) \"[Hσ H]\"; iApply ownP_lift_step.\n    iMod (fupd_intro_mask' E ∅) as \"Hclose\"; first set_solver.\n    iModIntro; iExists σ1; iFrame; iSplit; first by destruct s.\n    iNext; iIntros (κ e2 σ2 efs ?) \"Hσ\".\n    iDestruct (\"H\" $! κ e2 σ2 efs with \"[] [Hσ]\") as \"[HΦ $]\"; [by eauto..|].\n    destruct (to_val e2) eqn:?; last by iExFalso.\n    iMod \"Hclose\"; iApply wp_value; last done. by apply of_to_val.\n  Qed.\n\n  Lemma ownP_lift_atomic_det_step {s E Φ e1} σ1 v2 σ2 efs :\n    (if s is NotStuck then reducible e1 σ1 else to_val e1 = None) →\n    (∀ κ' e2' σ2' efs', prim_step e1 σ1 κ' e2' σ2' efs' →\n                     σ2' = σ2 ∧ to_val e2' = Some v2 ∧ efs' = efs) →\n    ▷ (ownP σ1) ∗ ▷ (ownP σ2 -∗\n      Φ v2 ∗ [∗ list] ef ∈ efs, WP ef @ s; ⊤ {{ _, True }})\n    ⊢ WP e1 @ s; E {{ Φ }}.\n  Proof.\n    iIntros (? Hdet) \"[Hσ1 Hσ2]\"; iApply ownP_lift_atomic_step; try done.\n    iFrame; iNext; iIntros (κ' e2' σ2' efs' ?) \"Hσ2'\".\n    edestruct (Hdet κ') as (<-&Hval&<-); first done. rewrite Hval.\n    iApply (\"Hσ2\" with \"Hσ2'\").\n  Qed.\n\n  Lemma ownP_lift_atomic_det_step_no_fork {s E e1} σ1 v2 σ2 :\n    (if s is NotStuck then reducible e1 σ1 else to_val e1 = None) →\n    (∀ κ' e2' σ2' efs', prim_step e1 σ1 κ' e2' σ2' efs' →\n      σ2' = σ2 ∧ to_val e2' = Some v2 ∧ efs' = []) →\n    {{{ ▷ (ownP σ1) }}} e1 @ s; E {{{ RET v2; ownP σ2 }}}.\n  Proof.\n    intros. rewrite -(ownP_lift_atomic_det_step σ1 v2 σ2 []); [|done..].\n    rewrite big_sepL_nil right_id. apply bi.wand_intro_r. iIntros \"[Hs Hs']\".\n    iSplitL \"Hs\"; first by iFrame. iModIntro. iIntros \"Hσ2\". iApply \"Hs'\". iFrame.\n  Qed.\n\n  Lemma ownP_lift_pure_det_step_no_fork `{Inhabited (state Λ)} {s E Φ} e1 e2 :\n    (∀ σ1, if s is NotStuck then reducible e1 σ1 else to_val e1 = None) →\n    (∀ σ1 κ e2' σ2 efs', prim_step e1 σ1 κ e2' σ2 efs' → κ = [] ∧ σ2 = σ1 ∧ e2' = e2 ∧ efs' = []) →\n    ▷ WP e2 @ s; E {{ Φ }} ⊢ WP e1 @ s; E {{ Φ }}.\n  Proof.\n    intros. rewrite -(wp_lift_pure_det_step_no_fork e1 e2) //; eauto.\n  Qed.\nEnd lifting.\n\nSection ectx_lifting.\n  Import ectx_language.\n  Context {Λ : ectxLanguage} `{ownPG Λ Σ} {Hinh : Inhabited (state Λ)}.\n  Implicit Types s : stuckness.\n  Implicit Types Φ : val Λ → iProp Σ.\n  Implicit Types e : expr Λ.\n  Hint Resolve head_prim_reducible head_reducible_prim_step.\n  Hint Resolve (reducible_not_val _ inhabitant).\n  Hint Resolve head_stuck_stuck.\n\n  Lemma ownP_lift_head_step s E Φ e1 :\n    (|={E,∅}=> ∃ σ1, ⌜head_reducible e1 σ1⌝ ∗ ▷ (ownP σ1) ∗\n            ▷ ∀ κ e2 σ2 efs, ⌜head_step e1 σ1 κ e2 σ2 efs⌝ -∗\n            ownP σ2\n            ={∅,E}=∗ WP e2 @ s; E {{ Φ }} ∗ [∗ list] ef ∈ efs, WP ef @ s; ⊤ {{ _, True }})\n    ⊢ WP e1 @ s; E {{ Φ }}.\n  Proof.\n    iIntros \"H\". iApply ownP_lift_step.\n    iMod \"H\" as (σ1 ?) \"[>Hσ1 Hwp]\". iModIntro. iExists σ1. iSplit.\n    { destruct s; try by eauto using reducible_not_val. }\n    iFrame. iNext. iIntros (κ e2 σ2 efs ?) \"Hσ2\".\n    iApply (\"Hwp\" with \"[] Hσ2\"); eauto.\n  Qed.\n\n  Lemma ownP_lift_head_stuck E Φ e :\n    sub_redexes_are_values e →\n    (|={E,∅}=> ∃ σ, ⌜head_stuck e σ⌝ ∗ ▷ (ownP σ))\n    ⊢ WP e @ E ?{{ Φ }}.\n  Proof.\n    iIntros (?) \"H\". iApply ownP_lift_stuck. iMod \"H\" as (σ) \"[% >Hσ]\".\n    iExists σ. iModIntro. by auto with iFrame.\n  Qed.\n\n  Lemma ownP_lift_pure_head_step s E Φ e1 :\n    (∀ σ1, head_reducible e1 σ1) →\n    (∀ σ1 κ e2 σ2 efs, head_step e1 σ1 κ e2 σ2 efs → κ = [] ∧ σ2 = σ1) →\n    (▷ ∀ κ e2 efs σ, ⌜head_step e1 σ κ e2 σ efs⌝ →\n      WP e2 @ s; E {{ Φ }} ∗ [∗ list] ef ∈ efs, WP ef @ s; ⊤ {{ _, True }})\n    ⊢ WP e1 @ s; E {{ Φ }}.\n  Proof using Hinh.\n    iIntros (??) \"H\".  iApply ownP_lift_pure_step; eauto.\n    { by destruct s; auto. }\n    iNext. iIntros (?????). iApply \"H\"; eauto.\n  Qed.\n\n  Lemma ownP_lift_atomic_head_step {s E Φ} e1 σ1 :\n    head_reducible e1 σ1 →\n    ▷ (ownP σ1) ∗ ▷ (∀ κ e2 σ2 efs,\n    ⌜head_step e1 σ1 κ e2 σ2 efs⌝ -∗ ownP σ2 -∗\n      from_option Φ False (to_val e2) ∗ [∗ list] ef ∈ efs, WP ef @ s; ⊤ {{ _, True }})\n    ⊢ WP e1 @ s; E {{ Φ }}.\n  Proof.\n    iIntros (?) \"[Hst H]\". iApply ownP_lift_atomic_step; eauto.\n    { by destruct s; eauto using reducible_not_val. }\n    iSplitL \"Hst\"; first done.\n    iNext. iIntros (???? ?) \"Hσ\". iApply (\"H\" with \"[] Hσ\"); eauto.\n  Qed.\n\n  Lemma ownP_lift_atomic_det_head_step {s E Φ e1} σ1 v2 σ2 efs :\n    head_reducible e1 σ1 →\n    (∀ κ' e2' σ2' efs', head_step e1 σ1 κ' e2' σ2' efs' →\n      σ2' = σ2 ∧ to_val e2' = Some v2 ∧ efs' = efs) →\n    ▷ (ownP σ1) ∗ ▷ (ownP σ2 -∗\n                      Φ v2 ∗ [∗ list] ef ∈ efs, WP ef @ s; ⊤ {{ _, True }})\n    ⊢ WP e1 @ s; E {{ Φ }}.\n  Proof.\n    intros Hr Hs.\n    destruct s; apply ownP_lift_atomic_det_step; eauto using reducible_not_val;\n    intros; eapply Hs; eauto 10.\n  Qed.\n\n  Lemma ownP_lift_atomic_det_head_step_no_fork {s E e1} σ1 κ v2 σ2 :\n    head_reducible e1 σ1 →\n    (∀ κ' e2' σ2' efs', head_step e1 σ1 κ' e2' σ2' efs' →\n      κ' = κ ∧ σ2' = σ2 ∧ to_val e2' = Some v2 ∧ efs' = []) →\n    {{{ ▷ (ownP σ1) }}} e1 @ s; E {{{ RET v2; ownP σ2 }}}.\n  Proof.\n    intros ???; apply ownP_lift_atomic_det_step_no_fork; last naive_solver.\n    by destruct s; eauto using reducible_not_val.\n  Qed.\n\n  Lemma ownP_lift_pure_det_head_step_no_fork {s E Φ} e1 e2 :\n    (∀ σ1, head_reducible e1 σ1) →\n    (∀ σ1 κ e2' σ2 efs', head_step e1 σ1 κ e2' σ2 efs' → κ = [] ∧ σ2 = σ1 ∧ e2' = e2 ∧ efs' = []) →\n    ▷ WP e2 @ s; E {{ Φ }} ⊢ WP e1 @ s; E {{ Φ }}.\n  Proof using Hinh.\n    iIntros (??) \"H\"; iApply wp_lift_pure_det_step_no_fork; try by eauto.\n    by destruct s; eauto using reducible_not_val.\n  Qed.\nEnd ectx_lifting.\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/ownp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.29271407860371507}}
{"text": "Require Import Coqlib.\nRequire Import List. Import ListNotations.\nRequire Import DRBG_state_handle.\nRequire Import DRBG_working_state.\nRequire Import entropy.\n\nDefinition DRBG_reseed_function \n           (reseed_algorithm: DRBG_working_state -> list Z -> list Z -> DRBG_working_state) \n           (min_entropy_length max_entropy_length: Z) \n           (max_additional_input_length: Z) \n           (entropy_stream: ENTROPY.stream) \n           (state_handle: DRBG_state_handle) \n           (prediction_resistance_request: bool) \n           (additional_input: list Z): ENTROPY.result DRBG_state_handle :=\n\n  let '(working_state, security_strength, prediction_resistance_flag) := state_handle in\n\n  if prediction_resistance_request && (negb prediction_resistance_flag) \n  then ENTROPY.error ENTROPY.generic_error entropy_stream\n  else\n    if Z.gtb (Zlength additional_input) max_additional_input_length \n    then ENTROPY.error ENTROPY.generic_error entropy_stream\n    else\n      (* get_entropy finally called here *)\n      match get_entropy security_strength min_entropy_length\n                        max_entropy_length prediction_resistance_flag entropy_stream with\n      | ENTROPY.error _ s =>\n        ENTROPY.error ENTROPY.catastrophic_error s\n      | ENTROPY.success entropy_input entropy_stream =>\n        (* reseed_algorithm called here -- i'm guessing entropy_input has length > min *)\n        let new_working_state := reseed_algorithm working_state\n                                                  entropy_input additional_input in\n        ENTROPY.success (new_working_state, security_strength,\n                         prediction_resistance_flag) entropy_stream\n      end.\n", "meta": {"author": "k-qy", "repo": "HMAC-DRBG", "sha": "2fc871f5b715f703eef3e855fca3df282090d2a5", "save_path": "github-repos/coq/k-qy-HMAC-DRBG", "path": "github-repos/coq/k-qy-HMAC-DRBG/HMAC-DRBG-2fc871f5b715f703eef3e855fca3df282090d2a5/specs/DRBG_reseed_function.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548511303336, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.29271407252086196}}
{"text": "Add LoadPath \"../from_compcert\".\nRequire Import Libs.\nRequire Import Polyhedra.\nRequire Import Loops.\nRequire Import Memory.\nRequire Import ArithClasses.\nRequire Import Permutation.\nRequire Import Sorted.\nRequire Import PLang.\nRequire Import CeildFloord.\nRequire Import Psatz.\nRequire Import Instructions.\nRequire Import Bounds.\nRequire Import BoxedPolyhedra.\nRequire Import TimeStamp.\nOpen Scope string_scope.\n\nGeneralizable Variables nbr_params depth.\n\n\nModule Extract (Import M:BASEMEM(ZNum))\n  (I:INSTRS(ZNum) with Definition Value := M.Value).\n  Module L := Semantics(ZNum)(M)(I).\n  Import L.\n  Import T.\n  Module P := PSemantics M I.\n  Import P.\n  Open Scope Z_scope.\n\n  Definition not_implemented {A:Type} : res A :=\n    Err \"Not Implemented\".\n\n  Definition res_of_option {A:Type} (oa: option A) (err: String.string) : res A :=\n    match oa with\n      | None => Err err\n      | Some a => OK a\n    end.\n\n  Definition instruction_not_found :=\n    \"The instruction is not linked to any instruction\".\n\n  Definition wrong_length :=\n    \"The vector cannot be build because the lenght is incorrect\".\n\n  Program Definition point_boxed_polyhedron (global_depth: nat) :\n    Boxed_Polyhedron global_depth 0:=\n    {| bp_poly := [];\n       bp_elts := (fun _ => [V0 0])|}.\n  Next Obligation.\n    Case \"bp_elts_NoDup\".\n    constructor; auto. constructor.\n  Qed.\n  Next Obligation.\n    Case \"bp_in_elts_in_poly\".\n    unfold constrain_params.\n    unfold constrain_params.\n(*    apply Pol_Included_intersertion; auto.\n    apply poly_containing_params_drop_2.\n    apply Vdrop_p_app.*)\n    unfold Pol_In. constructor.\n  Qed.\n  Next Obligation.\n    Case \"bp_in_poly_in_elts\".\n    left. apply PVeq_Veq. reflexivity.\n  Qed.\n\n(*  Program Definition ptree_get {A} (i: positive) (m: PTree.t A) :\n    {a:A | m ! i = Some a}+{ m ! i = None} :=\n    match m ! i with\n      | None => inright _ _\n      | Some a => inleft _ a\n    end.*)\n\n  Definition raise_time_stamp {global_depth: nat} (pos: Z)\n    (pi: Polyhedral_Instruction global_depth)\n    : Polyhedral_Instruction global_depth :=\n      {| pi_instr := pi.(pi_instr);\n         pi_depth := pi.(pi_depth);\n         pi_poly := pi.(pi_poly);\n         pi_schedule := (pos ::: V0 (pi.(pi_depth) + global_depth)) :: pi.(pi_schedule);\n         pi_transformation := pi.(pi_transformation)|}.\n\n\n\n\n  (* let's try dependent types horrors *)\n\n  Definition cast_list {A: nat -> Type} {n p: nat} (EQnp: p= n)\n    (l: list (A n)) : list (A p).\n  Proof.\n    rewrite <- EQnp in l. exact l.\n  Defined.\n\n  Definition cast_A {A: nat -> Type} {n p: nat} (EQnp: p = n)\n    (a: (A n)) : (A p).\n  Proof.\n    rewrite <- EQnp in a; exact a.\n  Defined.\n\n  Lemma cast_list_cast_A {A: nat -> Type} {n p: nat} (EQnp: p = n)\n    (l: list (A n)):\n    cast_list EQnp l = map (cast_A EQnp) l.\n  Proof.\n    induction' l as [|a l].\n    Case \"nil\".\n      destruct EQnp. reflexivity.\n    Case \"cons a l\".\n      simpl.\n      rewrite <- IHl. clear IHl.\n      destruct EQnp. simpl. reflexivity.\n  Qed.\n\n  Definition plus_nSm_Snm n m := eq_sym (plus_Snm_nSm n m).\n\n  Definition cast_polyhedron {nbr_global_parameters depth}\n    (pol: Polyhedron (depth + (S nbr_global_parameters))) :\n    Polyhedron ((S depth) + nbr_global_parameters):=\n    cast_list (plus_Snm_nSm _ _) pol.\n\n  Definition cast_constr {nbr_global_parameters depth}\n    (constr: Constraint (depth + (S nbr_global_parameters))) :\n    Constraint ((S depth) + nbr_global_parameters) :=\n    cast_A (plus_Snm_nSm _ _) constr.\n\n  Lemma cast_poly_cast_constr nbr_global_parameters depth\n    (pol: Polyhedron (depth + (S nbr_global_parameters))):\n    cast_polyhedron pol = map cast_constr pol.\n  Proof.\n    apply cast_list_cast_A.\n  Qed.\n\n  Ltac dest_eq_rect :=\n    match goal with\n      | |- context[eq_rect_r _ _ ?H] =>\n        match H with\n          | eq_refl => fail 1\n          | _ => destruct H\n        end\n    end.\n\n\n\n\n  Lemma satify_cast_constraint nbr_global_parameters depth\n    (v1 : ZVector depth) (v2: ZVector nbr_global_parameters) z constr:\n    satisfy_constraint (v1 +++ z ::: v2) constr <->\n    satisfy_constraint ((v1 :::: z) +++ v2) (cast_constr constr).\n  Proof.\n    destruct constr.\n    unfold satisfy_constraint in *. simpl in *.\n    unfold cast_constr, cast_A.\n    match goal with\n      | |- satisfy_comparison ?z ?c ?v <->\n        satisfy_comparison ?z' ?c' ?v' =>\n        assert' (z = z') as ZEQ;[|\n        End_of_assert ZEQ;\n        assert' (c = c') as CEQ;[|\n        End_of_assert CEQ;\n        assert' (v = v') as VEQ]]\n    end.\n    SCase \"Assert: ZEQ\".\n      clear.\n      unfold Vprod. dest_vects.\n      dest_eq_rect.\n      simpl. f_equal.\n      clear.\n      induction v1; simpl; auto. f_equal; auto.\n    SCase \"Assert: CEQ\".\n      clear. dest_eq_rect. reflexivity.\n    SCase \"Assert: VEQ\".\n      clear. dest_eq_rect. reflexivity.\n    End_of_assert VEQ.\n    split; intro; congruence.\n  Qed.\n\n\n  Lemma Pol_In_cast_polyhedron nbr_global_parameters depth\n    (v1 : ZVector depth) (v2: ZVector nbr_global_parameters) z pol:\n    v1 +++ (z ::: v2) ∈ pol <->\n    (v1 :::: z) +++ v2 ∈ (cast_polyhedron pol).\n  Proof.\n    rewrite cast_poly_cast_constr.\n    unfold Pol_In.\n    induction' pol as [|constr pol]; simpl; intros; auto.\n    Case \"nil\".\n      split; intros; constructor.\n    Case \"cons constr pol\".\n    destruct IHpol.\n    split'; intros.\n    SCase \"->\".\n      inv H1. constructor; auto.\n      apply satify_cast_constraint; auto.\n    SCase \"<-\".\n      inv H1. constructor; auto.\n      apply satify_cast_constraint; auto.\n  Qed.\n\n\n      \n\n\n  (* list of Z between lb and ub *)\n\n  Lemma nat_of_Z_Zabs_nat: forall z, 0 <= z ->\n    nat_of_Z z = Zabs_nat z.\n  Proof.\n    intros z ABS.\n    destruct z; try reflexivity.\n    compute in ABS. exfalso. auto.\n  Qed.\n\n  Require Import Recdef.\n  Function list_of_Z_between_aux (ub lb:Z) {measure (fun lb => nat_of_Z ((ub - lb) + 1)) lb}: list Z:=\n    if Z_le_dec lb ub then\n      lb :: list_of_Z_between_aux ub (Zsucc lb)\n    else\n      [].\n    intros. clear teq.\n    unfold Zsucc.\n    rewrite nat_of_Z_Zabs_nat; [|lia].\n    rewrite nat_of_Z_Zabs_nat; [|lia].\n    zify. lia.\n  Qed.\n\n  Definition list_of_Z_between lb ub := list_of_Z_between_aux ub lb.\n\n\n  Lemma list_of_Z_between_correct: forall lb ub z,\n    In z (list_of_Z_between lb ub) <-> lb <= z <= ub.\n  Proof.\n    intros ? ?. unfold list_of_Z_between.\n    functional induction (list_of_Z_between_aux ub lb); intros.\n    Case \"lb <= ub\".\n    destruct' (z == lb).\n    SCase \"z = lb\".\n      subst. split; simpl; intros; auto. lia.\n    SCase \"z <> lb\".\n      split; intros.\n\n      simpl in H.\n      destruct H; try congruence;\n      destruct (IHl z) as [TRI _];\n      specialize (TRI H). unfold Zsucc in *. lia.\n\n      simpl. right. apply IHl. unfold Zsucc. lia.\n\n    Case \"lb > ub\".\n    simpl. split; intro; clean. lia.\n  Qed.\n\n\n  Lemma rewrite_list_of_Z_between_le: forall lb ub, lb <= ub ->\n    list_of_Z_between lb ub = lb :: list_of_Z_between (Zsucc lb) ub.\n  Proof.\n    intros. unfold list_of_Z_between.\n    rewrite list_of_Z_between_aux_equation.\n    dest_if_goal; auto.\n    lia.\n  Qed.\n\n  Lemma rewrite_list_of_Z_between_gt: forall lb ub, lb > ub ->\n    list_of_Z_between lb ub = [].\n  Proof.\n    intros. unfold list_of_Z_between.\n    rewrite list_of_Z_between_aux_equation.\n    dest_if_goal; auto.\n    lia.\n  Qed.\n\n\n\n  Definition constraint_of_lower_bound_constr {nbr_params}\n    (constr: ZNum.Num * NVector (S nbr_params))\n     : Constraint (S nbr_params):=\n    {| constr_vect := fst constr ::: (-- (Vtail (snd constr)));\n       constr_comp := GE ;\n       constr_val := Vhd (snd constr)|}.\n\n\n  Lemma constraint_of_lower_bound_constr_correct {nbr_params}\n    (constr: ZNum.Num * NVector (S nbr_params)):\n    forall z (ctxt: Context nbr_params),\n      ge_bound_constraint (extend_context ctxt) z constr <->\n      satisfy_constraint (z:::ctxt) (constraint_of_lower_bound_constr constr).\n  Proof.\n    intros.\n    destruct constr as (x, v).\n    unfold constraint_of_lower_bound_constr, ge_bound_constraint,\n      satisfy_constraint, extend_context; simpl.\n    rewrite <- (Vcons_hd_tail v).\n    repeat rewrite Vprod_Vcons. simpl_vect.\n    simpl. rewrite Vprod_comm. lia.\n\n    constructor. exact 0.\n  Qed.\n\n\n  Definition polyhedron_of_lower_bound {nbr_params}\n    (lower_bound: bound nbr_params)\n      : Polyhedron (S nbr_params) :=\n      map constraint_of_lower_bound_constr lower_bound. \n\n\n  Lemma polyhedron_of_lower_bound_correct {nbr_params}\n    (lower_bound: bound nbr_params):\n    forall z (ctxt: Context nbr_params),\n      ge_bound ctxt lower_bound z <->\n      (z:::ctxt) ∈ (polyhedron_of_lower_bound lower_bound).\n  Proof.\n    intros.\n    unfold ge_bound, Pol_In, polyhedron_of_lower_bound.\n    split; intro. \n    Case \"satisfy_constraint\".\n      eapply list_forall_list_forall_map;[| eauto].\n      intros. rewrite <- constraint_of_lower_bound_constr_correct; auto.\n    Case \"ge_bound_constraint\".\n      eapply list_forall_map_list_forall;[| eauto].\n      intros.\n      rewrite -> constraint_of_lower_bound_constr_correct; auto.\n  Qed.\n    \n  Definition constraint_of_upper_bound_constr {nbr_params}\n    (constr: ZNum.Num * NVector (S nbr_params))\n     : Constraint (S nbr_params):=\n    {| constr_vect := (- fst constr) ::: (Vtail (snd constr));\n       constr_comp := GE ;\n       constr_val := - (Vhd (snd constr))|}.\n\n\n  Lemma constraint_of_upper_bound_constr_correct {nbr_params}\n    (constr: ZNum.Num * NVector (S nbr_params)):\n    forall z (ctxt: Context nbr_params),\n      le_bound_constraint (extend_context ctxt) z constr <->\n      satisfy_constraint (z:::ctxt) (constraint_of_upper_bound_constr constr).\n  Proof.\n    intros.\n    destruct constr as (x, v).\n    unfold constraint_of_upper_bound_constr, le_bound_constraint,\n      satisfy_constraint, extend_context; simpl.\n    rewrite <- (Vcons_hd_tail v).\n    repeat rewrite Vprod_Vcons. simpl_vect.\n    simpl. rewrite Vprod_comm. unfold ZNum.Num, ZNum.Numerical_Num.\n    lia. \n    constructor. exact 0.\n  Qed.\n\n\n  Definition polyhedron_of_upper_bound {nbr_params}\n    (upper_bound: bound nbr_params)\n      : Polyhedron (S nbr_params) :=\n      map constraint_of_upper_bound_constr upper_bound. \n\n\n  Lemma polyhedron_of_upper_bound_correct {nbr_params}\n    (upper_bound: bound nbr_params):\n    forall z (ctxt: Context nbr_params),\n      le_bound ctxt upper_bound z <->\n      (z:::ctxt) ∈ (polyhedron_of_upper_bound upper_bound).\n  Proof.\n    intros.\n    unfold le_bound, Pol_In, polyhedron_of_upper_bound.\n    split; intro. \n    Case \"satisfy_constraint\".\n      eapply list_forall_list_forall_map; [|eauto].\n      intros. rewrite <- constraint_of_upper_bound_constr_correct; auto.\n    Case \"le_bound_constraint\".\n      eapply list_forall_map_list_forall; [|eauto].\n      intros.\n      rewrite -> constraint_of_upper_bound_constr_correct; auto.\n  Qed.\n\n  Definition Pol_translate_r {n} p (pol: Polyhedron n) : Polyhedron (p + n) :=\n    map (Constr_translate_r p) pol.\n\n  Lemma Pol_translate_r_correct n p (pol: Polyhedron n) v1 v2:\n    v2 ∈ pol <-> (v1 +++ v2) ∈ (Pol_translate_r p pol).\n  Proof.\n    unfold Pol_In, Pol_translate_r.\n    split; intro H.\n    eapply list_forall_list_forall_map; [|eauto].\n    intros. apply Constr_translate_r_correct. assumption.\n\n\n    eapply list_forall_map_list_forall; [|eauto].\n    intros. apply <- Constr_translate_r_correct. eassumption.\n  Qed.\n\n\n\n  Definition build_poly_for_Loop {nbr_param depth} \n    (lower_bound upper_bound: bound nbr_param)\n    (pol: Polyhedron (depth + S nbr_param))\n    : Polyhedron (S depth + nbr_param) :=\n    cast_polyhedron(\n      (Pol_translate_r depth (polyhedron_of_lower_bound lower_bound))\n    ∩ (Pol_translate_r depth (polyhedron_of_upper_bound upper_bound))\n    ∩ pol).\n\n  Program Definition eval_lower_bound_no {nbr_param} params (lower_bound: bound nbr_param)\n    (OKLB: bound_correct lower_bound)\n      : {z:Z| eval_lower_bound params lower_bound = Some z} :=\n    match eval_lower_bound params lower_bound with\n      | Some z => z\n      | None => !\n    end.\n  Next Obligation.\n    apply bound_correct_eval_lower_bound_is_some with (ctxt := params) in OKLB.\n    inv OKLB.\n    replace @ZTools.eval_lower_bound with @eval_lower_bound in * by reflexivity.\n    congruence.\n  Qed.\n\n  Program Definition eval_upper_bound_no {nbr_param} params (upper_bound: bound nbr_param)\n    (OKLB: bound_correct upper_bound)\n      : {z:Z| eval_upper_bound params upper_bound = Some z} :=\n    match eval_upper_bound params upper_bound with\n      | Some z => z\n      | None => !\n    end.\n  Next Obligation.\n    apply bound_correct_eval_upper_bound_is_some with (ctxt := params) in OKLB.\n    inv OKLB.\n    replace @ZTools.eval_upper_bound with @eval_upper_bound in * by reflexivity.\n    congruence.\n  Qed.\n\n  Lemma NoDup_app : forall A (l: list A) l', NoDup l -> NoDup l' ->\n    (forall x, In x l -> In x l' -> False) ->\n    NoDup (l++l').\n  Proof.\n    intros A l.\n    induction' l as [|a l]; simpl; intros l' NO NO' NOTIN; auto.\n    Case \"cons a l\".\n      constructor.\n      intro IN. apply in_app_or in IN. destruct IN as [IN|IN].\n      inv NO. auto.\n      apply (NOTIN a); auto.\n      inv NO. apply IHl; auto.\n      intros. apply (NOTIN x); eauto.\n  Qed.\n\n  Lemma In_map_inj : forall A B (f: A -> B),\n    (forall x y, f x = f y -> x = y) ->\n    forall a (l: list A),\n      In (f a) (map f l) ->\n      In a l.\n  Proof.\n    intros * INJ *.\n    induction' l as [|x l]; intro IN; simpl in *; inv IN; auto.\n  Qed.\n\n      \n  Lemma NoDup_map_inj : forall A B (f: A -> B),\n    (forall x y, f x = f y -> x = y) ->\n    forall (l: list A), \n    NoDup l ->\n    NoDup (map f l).\n  Proof.\n    intros * INJ.\n    induction' l as [|a l]; simpl; intros NO.\n    Case \"nil\".\n      constructor.\n    Case \"cons a l\".\n      inv NO.\n      constructor; auto.\n      intro. apply H1. apply In_map_inj with (f := f); auto.\n  Qed.\n  \n\n  Lemma In_flatten A (ll: list (list A)) x:\n    In x (flatten ll) <-> exists l, In l ll /\\ In x l.\n  Proof.\n    induction' ll as [| l1 ll]; simpl.\n    Case \"nil\".\n      split'; auto.\n      SCase \"<-\".\n        intros [?[? ?]]; auto.\n    Case \"cons l1 ll\".\n      split'.\n      SCase \"->\".\n        intro IN.\n        apply in_app_or in IN. destruct IN as [IN | IN].\n          exists l1; auto.\n          rewrite IHll in IN. destruct IN as [l [? ?]].\n          exists l; auto.\n      SCase \"<-\".\n        intros [l [[?|?] ?]]; subst;\n        apply in_or_app; auto.\n        right; apply IHll.\n        eexists; eauto.\n  Qed.\n\n\n\n  Lemma in_map2_exists A B C (f: A -> B -> C) la lb c:\n    In c (map2 f la lb) ->\n    exists a b,\n      In a la /\\ In b lb /\\ f a b = c.\n  Proof.\n    revert lb.\n    induction' la as [|a la]; destruct' lb as [|b lb]; intros * IN; simpl in *; clean.\n    Case \"cons a la\"; SCase \"cons b lb\".\n      destruct IN.\n      exists a, b; auto.\n      edestruct IHla as [a' [b' [?[? ?]]]]; eauto.\n      exists a', b'; auto.\n  Qed.\n    \n  Lemma snoc_inj A l1 l2 (a:A):\n    l1 ++ [a] = l2 ++ [a] ->\n    l1 = l2.\n  Proof.\n    revert l2; induction' l1 as [| a1 l1]; intros l2 EQ;\n    destruct' l2 as [|a2 l2]; simpl in *; auto.\n    Case \"nil\"; SCase \"cons a2 l2\". \n      inv EQ. destruct l2; inv H1.\n    Case \"cons a1 l1\"; SCase \"nil\".\n      inv EQ; destruct l1; simpl in *; congruence.\n    Case \"cons a1 l1\"; SCase \"cons a2 l2\".\n      inv EQ; f_equal; auto.\n  Qed.\n\n  Fixpoint last_Z (l: list Z) :=\n    match l with\n      | [] => 0\n      | [z] => z\n      | _ :: l' => last_Z l'\n    end.\n\n  Program Definition Vlast_Z {n} (v: ZVector (S n)) :=\n    last_Z v.\n\n  Lemma Vlast_Z_Vsnoc n (v: ZVector n) z :\n    Vlast_Z (v::::z) = z.\n  Proof.\n    dest_vects. unfold Vlast_Z. simpl. clear Lv.\n    induction v; simpl; auto.\n    destruct v; auto.\n  Qed.\n\n  Fixpoint Vtake_aux `{Inhabited A} n (l: list A) :=\n    match n with\n      | O => []\n      | S n' =>\n        match l with\n          | [] => repeat n repr\n          | a:: l' => a :: Vtake_aux n' l'\n        end\n    end.\n  Program Definition Vtake `{Inhabited A} n {p} (v: Vector A p): Vector A n:=\n    Vtake_aux n v.\n  Next Obligation.\n    dest_vects.\n    clear.\n    revert v.\n    induction' n as [|n]; intros; simpl.\n    Case \"O\".\n      reflexivity.\n    Case \"S n\".\n      destruct' v.\n      SCase \"nil\".\n        simpl. f_equal. apply repeat_length.\n      SCase \"cons\".\n        simpl. f_equal. auto.\n  Qed.\n\n  Lemma split_big_vect nbr_param depth (v:ZVector (S depth + nbr_param)):\n    exists elts z params,\n      v = (elts :::: z) +++ params.\n  Proof.\n    exists (Vtake depth v).\n    exists (Vnth v depth).\n    exists (Vdrop_p (S depth) v).\n    dest_vects.\n    revert dependent nbr_param.\n    revert v.\n    induction' depth as [|depth]; simpl; intros; auto.\n    Case \"O\".\n      destruct' v as [|z v]; simpl in *; clean.\n    Case \"S depth\".\n      destruct' v as [|z v]; simpl in *; clean.\n      f_equal; eauto.\n  Qed.\n\n\n  Program Definition build_boxed_poly_for_Loop {nbr_param depth}\n    (lower_bound upper_bound: bound nbr_param) (OKLB: bound_correct lower_bound)\n    (OKUB: bound_correct upper_bound) (bpol: Boxed_Polyhedron (S nbr_param) depth)\n    : Boxed_Polyhedron (nbr_param) (S depth):=\n    {| bp_poly := build_poly_for_Loop lower_bound upper_bound bpol.(bp_poly);\n       bp_elts := fun params =>\n         let lb := eval_lower_bound_no params lower_bound OKLB in\n         let ub := eval_upper_bound_no params upper_bound OKUB in\n         let lZ := list_of_Z_between lb ub in\n         let bpol_params_lst  := map (fun z => z ::: params) lZ in\n         let bpol_elts_lst := map bpol.(bp_elts) bpol_params_lst in\n         let elts_lst := map2 (fun z vl => map (fun v => v :::: z) vl)\n             lZ bpol_elts_lst in\n         flatten elts_lst\n         |}.\n  Next Obligation.\n    destruct (eval_lower_bound_no params lower_bound OKLB) as [lb ELB].\n    destruct (eval_upper_bound_no params upper_bound OKUB) as [ub EUB].\n    simpl.\n    unfold list_of_Z_between.\n    clear.\n    functional induction (list_of_Z_between_aux ub lb); [|constructor].\n    simpl.\n    apply NoDup_app; auto.\n    Case \"NoDup\".\n    apply NoDup_map_inj.\n      clear'.\n      intros * EQ.\n      assert (` (x :::: lb) = ` (y :::: lb)) by congruence. clear EQ.\n      dest_vects. simpl in *. eapply snoc_inj; eauto.\n      apply bp_elts_NoDup.\n      \n    Case \"Not In\".\n      intros * IN INFLAT.\n      assert' (Vlast_Z x = lb) as VLASTEQ.\n        SCase \"Assert: VLASTEQ\".\n        clear' - IN.\n        rewrite in_map_iff in IN.\n        destruct IN as [v [? ?]].\n        subst. apply Vlast_Z_Vsnoc.\n      End_of_assert VLASTEQ.\n      assert' (Vlast_Z x > lb) as VLASTGT.\n        SCase \"Assert: VLASTGT\".\n        clear' - INFLAT.\n        rewrite In_flatten in INFLAT.\n        destruct INFLAT as [l [INxl INll]].\n        apply in_map2_exists in INxl.\n        destruct INxl as [z [l' [INz [_ ?]]]]; subst.\n        fold (list_of_Z_between (Zsucc lb) ub) in INz.\n        rewrite list_of_Z_between_correct in INz.\n        apply in_map_iff in INll. destruct INll as [? [? ?]]; subst.\n        rewrite Vlast_Z_Vsnoc. unfold Zsucc in *. lia.\n      End_of_assert VLASTGT.\n      lia.\n  Qed.\n  Next Obligation.\n    destruct (eval_lower_bound_no params lower_bound OKLB) as [lb ELB].\n    destruct (eval_upper_bound_no params upper_bound OKUB) as [ub EUB].\n    match goal with\n      | |-\n        @Pol_In (S (depth +  nbr_param))\n        ?v ?p =>\n        replace (@Pol_In (S (depth + nbr_param))\n        v p) with (@Pol_In ((S depth) + nbr_param)\n        v p) by reflexivity\n    end.\n(*    apply in_pol_in_constrain_params.*)\n\n    simpl in *.\n    rewrite In_flatten in H.\n    destruct H as [l [IN2 INl]].\n    rewrite map_map in IN2.\n\n    match type of IN2 with\n      | In l (map2 ?f ?loz (map ?g ?loz)) =>\n      assert'\n      (exists z, In z (list_of_Z_between lb ub) /\\\n        l = f z (g z)) as EXZ\n    end.\n    Case \"Assert: EXZ\".\n      remember (list_of_Z_between lb ub) as loz. clear Heqloz.\n      induction' loz as [|z loz]; simpl in *; clean.\n      SCase \"cons z loz\".\n        inv IN2.\n        exists z; split'; auto.\n        specialize (IHloz H).\n        destruct IHloz as [z' [? ?]].\n        exists z'; eauto.\n    End_of_assert EXZ.\n    clear IN2.\n    destruct EXZ as [z [IN ?]].\n    subst.\n    rewrite list_of_Z_between_correct in IN.\n    rewrite in_map_iff in INl.\n    destruct INl as [v [? INv]]; subst.\n\n    unfold build_poly_for_Loop.\n    apply Pol_In_cast_polyhedron.\n    repeat (apply Pol_Included_intersertion).\n    Case \"lower\".\n    apply Pol_translate_r_correct.\n    apply polyhedron_of_lower_bound_correct.\n    apply eval_lower_bound_is_ge in ELB.\n    eapply ge_bound_trans; eauto. lia.\n    Case \"upper\".\n    apply Pol_translate_r_correct.\n    apply polyhedron_of_upper_bound_correct.\n    apply eval_upper_bound_is_ge in EUB.\n    eapply le_bound_trans; eauto. lia.\n    Case \"params\".\n    pose proof in_constrain_param_in_pol. unfold Pol_Included in H.\n    eapply H.\n    eapply bp_in_elts_in_poly_constrain. eauto.\n  Qed.\n  Next Obligation.\n    destruct (eval_lower_bound_no params lower_bound OKLB) as [lb ELB].\n    destruct (eval_upper_bound_no params upper_bound OKUB) as [ub EUB].\n    simpl.\n    unfold constrain_params in H.\n    destruct (split_big_vect _ _ vect) as [elts[z[params' ?]]].\n    subst.\n    assert' (params = params').\n    Case \"Assert\".\n      apply Pol_intersection_Included_l in H.\n      apply poly_containing_params_drop_1 in H.\n      rewrite Vdrop_p_app in H. auto.\n    End_of_assert.\n    subst.\n    apply Pol_intersection_Included_r in H.\n    unfold build_poly_for_Loop in H.\n    apply Pol_In_cast_polyhedron in H.\n    repeat match goal with\n      | H : ?v ∈ ?p1 ∩ ?p2 |- _ =>\n        pose proof (Pol_intersection_Included_l _ _ H);\n        pose proof (Pol_intersection_Included_r _ _ H);\n        clear H\n    end.\n    rewrite Vtake_p_app.\n    apply Pol_translate_r_correct in H. apply Pol_translate_r_correct in H2.\n    rewrite <- polyhedron_of_upper_bound_correct in H2.\n    rewrite <- polyhedron_of_lower_bound_correct in H.\n    eapply ge_bound_ge_lower_bound in H; eauto.\n    eapply le_bound_le_upper_bound in H2; eauto.\n    clear dependent lower_bound. clear dependent upper_bound.\n    apply in_pol_in_constrain_params in H1.\n    eapply bp_in_poly_in_elts in H1.\n    rewrite Vtake_p_app in H1.\n    assert' (In z (list_of_Z_between lb ub)) as INZ.\n      Case \"Assert: INZ\".\n      apply list_of_Z_between_correct. lia.\n    End_of_assert INZ.\n    remember (list_of_Z_between lb ub) as loz. clear Heqloz.\n    clear dependent lb. clear dependent ub.\n    induction' loz as [|z' loz]; inv INZ; simpl;\n    rewrite in_app_iff; auto.\n    Case \"cons z' loz\".\n    left.\n    apply in_map_iff. eexists; eauto.\n  Qed.\n\n  Definition cast_pi_transformation {pi_depth global_depth num_of_args}\n    (mat: ZMatrix num_of_args (S (pi_depth + S global_depth)))\n      : ZMatrix num_of_args (S (S pi_depth + global_depth)).\n    pattern (S pi_depth + global_depth)%nat.\n    refine (cast_A (plus_Snm_nSm _ _) mat).\n  Defined.\n\n  Lemma snoc_app A (v1 v2: list A) a :\n    v1 ++ a :: v2 = (v1 ++[a]) ++ v2.\n  Proof.\n    induction v1; simpl; auto.\n    f_equal; assumption.\n  Qed.\n\n  Lemma cast_pi_transformation_id {pi_depth global_depth num_of_args}\n    (pi_transf: ZMatrix num_of_args (S (pi_depth + S global_depth))) \n     (a: ZVector pi_depth) lb (ctxt: ZVector global_depth):\n    pi_transf × (1 ::: (a +++ lb ::: ctxt)) =\n   cast_pi_transformation pi_transf  × (1 ::: ((a :::: lb) +++ ctxt)).\n  Proof.\n    apply PVeq_Veq. unfold Matrix in *.\n    dest_vects.\n    unfold Mprod_vect, Vprod. simpl.\n    clear.\n    unfold cast_pi_transformation. unfold cast_A.\n    dest_eq_rect. simpl.\n    apply map_ext.\n    intro v.\n    clear. \n    dest_vects. clear.\n    rewrite snoc_app. auto.\n  Qed.\n\n  Definition make_pi_schedule {depth global_depth}\n    (schedule: list (ZVector (S (depth + S global_depth))))\n    : list (ZVector (S ( S depth + global_depth))) :=\n    (0::: (((V0 depth) :::: 1) +++ V0 global_depth))::\n    cast_list (eq_S _ _ (plus_Snm_nSm _ _)) schedule.\n\n(*  Definition make_schedule*)\n\n  Fixpoint extract_statement {global_depth: nat}\n    (st: statement global_depth) {struct st}\n    : res (list (Polyhedral_Instruction global_depth)) :=\n    match st with\n    | Instr instr transf =>\n      OK [\n        {| pi_instr := instr;\n          pi_depth := O;\n          pi_poly := point_boxed_polyhedron global_depth;\n          pi_schedule := [(1 ::: V0 (0 + global_depth))];\n          pi_transformation := transf\n        |}]\n    | Loop lb ub sts =>\n      match check_bound lb with\n      | left CLB =>\n      match check_bound ub with\n      | left CUB =>\n      do lpi <- extract_statement_list 1 sts;\n      OK(\n        map (fun pi =>\n          {|pi_instr := pi.(pi_instr);\n            pi_depth := S (pi.(pi_depth));\n            pi_poly := build_boxed_poly_for_Loop lb ub CLB CUB pi.(pi_poly);\n            pi_schedule := make_pi_schedule pi.(pi_schedule);\n            pi_transformation := cast_pi_transformation pi.(pi_transformation)|}\n        ) lpi)\n      | right _ => Err \"Upper bound incorrect\"\n      end\n      | right _ => Err \"Lower bound incorrect\"\n      end\n\n    end\n  with extract_statement_list {global_depth: nat}\n    (pos: Z) (stl: statement_list global_depth) {struct stl}\n    : res (list (Polyhedral_Instruction global_depth)) :=\n    match stl with\n      | stl_nil => OK []\n      | stl_cons st stl' =>\n        do{;\n          pil1 <- extract_statement st;;\n          let pil1' := map (raise_time_stamp pos) pil1;;\n          pil2 <- extract_statement_list (Zsucc pos) stl';\n          OK (pil1' ++ pil2)\n        }\n    end.\n\n  Lemma res_of_option_OK A (oa: option A) (a:A) err:\n    res_of_option oa err = OK a -r> oa = Some a.\n  Proof.\n    constructor. unfold res_of_option. intro. destruct oa; clean.\n  Qed.\n  Hint Rewrite res_of_option_OK: clean.\n\n\n  (* we use another semantics for the proof, juste to remove the poly\n     program constructors. It's just a bit easier to express things *)\n\n  Definition poly_list_semantics (global_depth: nat)\n    (instrs_lst: list (Polyhedral_Instruction global_depth))\n      (params : ZVector global_depth) (sorted_instruction_points : list Instruction_Point)\n      (mem1 mem2 : Memory) : Prop :=\n      Sorted instruction_point_lt sorted_instruction_points /\\\n      Permutation (flatten (map (expand_poly_instr params) instrs_lst))\n        sorted_instruction_points /\\\n      instruction_list_semantics sorted_instruction_points mem1 mem2.\n\n  Ltac destr_poly_list_semantics :=\n    match goal with\n      | H : poly_list_semantics _ _ _ _ _ _ |- _ =>\n        destruct H as [? [? ?]]\n    end.\n\n(*  Lemma poly_list_semantics_equiv_poly_program_semantics: forall\n    (instructions: PTree.t I.Instruction) (global_depth: nat)\n    (instrs_lst: list (Polyhedral_Instruction instructions global_depth))\n      (params : ZVector global_depth)  (mem1 mem2 : Memory),\n      (exists sorted_instruction_points,\n        poly_list_semantics instructions global_depth instrs_lst params\n          sorted_instruction_points mem1 mem2)\n        <->\n      poly_program_semantics \n       {| pp_instructions := instructions;\n          pp_nbr_global_parameters := global_depth;\n          pp_poly_instrs := instrs_lst |} params mem1 mem2.\n  Proof.\n    intros. constructor; intro H.\n    Case \"->\".\n      destruct H. destr_poly_list_semantics. econstructor; eauto.\n\n    Case \"<-\".\n      inv H; econstructor; econstructor; eauto.\n  Qed.*)\n\n\n  Lemma instruction_list_semantics_app1: forall l1 l2 mem1 mem3,\n    instruction_list_semantics (l1++l2) mem1 mem3 ->\n    exists mem2,\n      instruction_list_semantics l1 mem1 mem2 /\\\n      instruction_list_semantics l2 mem2 mem3.\n  Proof.\n    intro l1.\n    induction' l1 as [|i l1]; intros * INSTR; simpl in *.\n    Case \"nil\".\n      exists mem1. split; auto. constructor.\n    Case \"cons i l1\".\n      inv INSTR.\n      edestruct IHl1 as [mem2' [? ?]]; eauto.\n      eexists; split; eauto.\n      econstructor; eauto.\n  Qed.\n\n  Lemma instruction_list_semantics_app2: forall l1 l2 mem1 mem2 mem3,\n    instruction_list_semantics l1 mem1 mem2 ->\n    instruction_list_semantics l2 mem2 mem3 ->\n    instruction_list_semantics (l1++l2) mem1 mem3.\n  Proof.\n    intro l1; induction' l1 as [|i1 l1]; intros * INSTRSEM1 INSTRSEM2;\n      simpl in *.\n    Case \"nil\".\n      inv INSTRSEM1; auto.\n    Case \"cons i1 l1\".\n      inv INSTRSEM1; econstructor; eauto.\n  Qed.\n\n\n\n  Definition raise_time_stamp_instr pos ip :=\n    {| ip_instruction := ip.(ip_instruction);\n       ip_arguments := ip.(ip_arguments);\n       ip_time_stamp := pos :: ip.(ip_time_stamp)|}.\n\n  Lemma raise_time_stamp_expand_poly_instr global_depth pos\n    (pinstr: Polyhedral_Instruction global_depth) params :\n    expand_poly_instr params (raise_time_stamp pos pinstr) = \n    map (raise_time_stamp_instr pos) (expand_poly_instr params pinstr).\n  Proof.\n    destruct pinstr.\n    unfold expand_poly_instr. simpl. clear.\n\n    remember (bp_elts pi_poly0 params) as elts. clear Heqelts.\n\n    induction' elts as [|ctxt elts]; simpl; auto.\n    Case \"cons ctxt elts\".\n      simpl. f_equal; auto.\n      unfold raise_time_stamp_instr. simpl.\n      f_equal.\n      f_equal.\n      unfold make_context_ext. rewrite Vprod_Vcons. simpl_vect. reflexivity.\n  Qed.\n\n  Lemma flatten_map_expand global_depth pos\n    (pinstr_lst: list (Polyhedral_Instruction global_depth)) params:\n  flatten (map (expand_poly_instr params) (map (raise_time_stamp pos) pinstr_lst)) =\n  map (raise_time_stamp_instr pos) (flatten (map (expand_poly_instr params) pinstr_lst)).\n  Proof.\n    induction pinstr_lst; simpl; auto.\n    rewrite map_app. f_equal; auto.\n    apply raise_time_stamp_expand_poly_instr.\n  Qed.\n\n\n  Lemma raise_time_stamp_expand_poly_instr_sorted global_depth pos\n    (pinstr_lst: list (Polyhedral_Instruction global_depth)) params \n    sorted_list_1:\n    Sorted instruction_point_lt sorted_list_1 ->\n    Permutation (flatten (map (expand_poly_instr params) pinstr_lst))\n      sorted_list_1 ->\n    Sorted instruction_point_lt (map (raise_time_stamp_instr pos) sorted_list_1) /\\\n    Permutation (flatten (map (expand_poly_instr params) \n                  (map (raise_time_stamp pos) pinstr_lst)))\n                (map (raise_time_stamp_instr pos) sorted_list_1)\n      .\n  Proof.\n    intros SORTED PERMUT.\n    split.\n    Case \"Sorted\".\n      clear PERMUT.\n      induction' SORTED; simpl; constructor; auto.\n      SCase \"Sorted_cons\".\n      clear' - H.\n      induction' H; constructor; auto.\n      SSCase \"HdRel_cons\".\n        unfold raise_time_stamp_instr, instruction_point_lt in *.\n        destruct a; destruct b. simpl in *.\n        clear' - H.\n        apply TSLT_eq. auto.\n    Case \"Permutation\".\n      clear' - PERMUT.\n      rewrite flatten_map_expand.\n      apply Permutation_map. auto.\n  Qed.\n\n  Lemma raise_time_stamp_poly_list_semantics global_depth\n    (pil: list (Polyhedral_Instruction global_depth))\n    instr_point_lst pos ctxt mem1 mem2:\n    poly_list_semantics global_depth pil ctxt instr_point_lst\n    mem1 mem2 ->\n    poly_list_semantics global_depth (map (raise_time_stamp pos) pil)\n    ctxt (map (raise_time_stamp_instr pos) instr_point_lst) mem1 mem2.\n  Proof.\n    intro PLS.\n    destr_poly_list_semantics.\n    edestruct raise_time_stamp_expand_poly_instr_sorted; eauto.\n    econstructor;[|econstructor]; eauto.\n    clear - H1.\n    induction H1; econstructor; eauto.\n    inv H. econstructor; eauto.\n  Qed.\n\n\n  Fixpoint list_of_statement_list {global_depth} (stl: statement_list global_depth):\n    list (statement global_depth) :=\n    match stl with\n      | stl_nil => []\n      | stl_cons st stl' => st :: list_of_statement_list stl'\n    end.\n\n  (* ESL_inv1: extract_statement_list invariant *)\n\n  Inductive ESL_inv1 {global_depth : nat} {ctxt: Context global_depth}:\n    forall (pos:Z) (mem1 mem2 : Memory)\n    (st_lst: statement_list global_depth)\n(*    (pol_instr_lst_lst: list (list (Polyhedral_Instruction global_depth)))*)\n    (raised_pol_instr_lst_lst: list (list (Polyhedral_Instruction global_depth)))\n    (instr_point_lst_lst: list (list Instruction_Point)),\n      Prop :=\n  | ESLI1_nil: forall pos mem,\n    ESL_inv1 pos mem mem stl_nil (*[]*) [] []\n  | ESLI2_cons: forall pos mem1 mem2 mem3\n    st st_lst pol_instr_lst (*pol_instr_lst_lst*)\n    raised_pol_instr_lst raised_pol_instr_lst_lst instr_point_lst instr_point_lst_lst,\n\n    semantics_statement ctxt st mem1 mem2 ->\n\n    extract_statement st = OK pol_instr_lst ->\n    raised_pol_instr_lst = map (raise_time_stamp pos) pol_instr_lst ->\n\n    Sorted instruction_point_lt instr_point_lst ->\n    Permutation (flatten (map (expand_poly_instr ctxt) raised_pol_instr_lst))\n      instr_point_lst ->\n    instruction_list_semantics instr_point_lst mem1 mem2 ->\n\n\n    ESL_inv1 (Zsucc pos) mem2 mem3\n      st_lst (*pol_instr_lst_lst*) raised_pol_instr_lst_lst instr_point_lst_lst ->\n    ESL_inv1 pos mem1 mem3 (stl_cons st st_lst) (*(pol_instr_lst :: pol_instr_lst_lst)*)\n    (raised_pol_instr_lst :: raised_pol_instr_lst_lst) (instr_point_lst :: instr_point_lst_lst).\n\n  Implicit Arguments ESL_inv1 [].\n\n  Lemma ESL_inv1_extract_statement_list global_depth\n    (ctxt: Context global_depth) pos mem1 mem2 st_lst (*pol_instr_lst_lst*)\n    raised_pol_instr_lst_lst instr_point_lst_lst:\n    ESL_inv1 global_depth ctxt pos mem1 mem2\n      st_lst (*pol_instr_lst_lst*) raised_pol_instr_lst_lst instr_point_lst_lst ->\n    extract_statement_list pos st_lst =\n      OK (flatten raised_pol_instr_lst_lst).\n  Proof.\n    intros ESL; induction' ESL; simpl.\n    Case \"ESLI1_nil\".\n      reflexivity.\n    Case \"ESLI2_cons\".\n      rewrite H0. simpl_do. rewrite IHESL. simpl_do.\n      f_equal.\n      f_equal; auto.\n  Qed.\n    \n  Lemma flatten_app {A} (l1 l2: list (list A)):\n    flatten (l1 ++ l2) = flatten l1 ++ flatten l2.\n  Proof.\n    induction' l1; simpl; auto.\n    rewrite IHl1. apply app_assoc.\n  Qed.\n\n\n  Lemma ESL_inv1_semantics_statement_list global_depth\n    (ctxt: Context global_depth) pos mem1 mem2 st_lst (*pol_instr_lst_lst*)\n    raised_pol_instr_lst_lst instr_point_lst_lst:\n    ESL_inv1 global_depth ctxt pos mem1 mem2\n      st_lst (*pol_instr_lst_lst*) raised_pol_instr_lst_lst instr_point_lst_lst ->\n    semantics_statement_list  ctxt st_lst mem1 mem2.\n  Proof.\n    intro ESL.\n    induction ESL; econstructor; eauto.\n  Qed.\n\n  Inductive first_dim_eq_time_stamp (pos:Z) : Time_Stamp -> Prop:=\n  | fde_intro: forall ts, first_dim_eq_time_stamp pos (pos :: ts).\n\n  Definition first_dim_eq pos ip := first_dim_eq_time_stamp pos (ip.(ip_time_stamp)).\n\n  Inductive first_dim_gt_time_stamp (pos:Z) : Time_Stamp -> Prop:=\n  | fdg_intro: forall x ts, pos < x -> first_dim_gt_time_stamp pos (x :: ts).\n\n  Definition first_dim_gt pos ip := first_dim_gt_time_stamp pos (ip.(ip_time_stamp)).\n\n\n  Lemma ESL_inv1_Forall_first_dim_gt global_depth\n    (ctxt: Context global_depth) pos pos' mem1 mem2 st_lst (*pol_instr_lst_lst*)\n    raised_pol_instr_lst_lst instr_point_lst_lst:\n    ESL_inv1 global_depth ctxt pos' mem1 mem2\n      st_lst (*pol_instr_lst_lst*) raised_pol_instr_lst_lst instr_point_lst_lst ->\n    pos < pos' ->\n    Forall (Forall (first_dim_gt pos)) instr_point_lst_lst.\n  Proof.\n    intros ESL.\n    induction' ESL; simpl; intro INF; auto.\n    Case \"ESLI2_cons\".\n      constructor.\n      SCase \"Head\".\n        eapply Permutation_Forall;[|eauto].\n        subst.\n        rewrite map_map.\n        apply Forall_flatten.\n        clear' - INF. \n        induction' pol_instr_lst; simpl; auto.\n        SSCase \"cons\".\n          constructor; auto.\n          rewrite raise_time_stamp_expand_poly_instr.\n          rewrite Forall_forall.\n          intros * IN.\n          rewrite in_map_iff in IN. destruct IN as [?[? ?]].\n          subst. unfold first_dim_gt.\n          destruct x0. simpl. constructor; assumption.\n      SCase \"Tail\".\n        apply IHESL. unfold Zsucc. lia.\n  Qed.\n\n  Lemma extract_statement_list_ok_correct (global_depth: nat)\n    (pos: Z) (st_lst: statement_list global_depth)\n    (instrs_lst : list (Polyhedral_Instruction global_depth)):\n    extract_statement_list pos st_lst = OK instrs_lst ->\n    forall ctxt mem1 mem2,\n    semantics_statement_list ctxt st_lst mem1 mem2 ->\n    (exists raised_pol_instr_lst_lst instr_point_lst_lst,\n      ESL_inv1 global_depth ctxt pos mem1 mem2\n        st_lst raised_pol_instr_lst_lst instr_point_lst_lst) ->\n    exists sorted_instruction_points,\n      poly_list_semantics global_depth instrs_lst\n       ctxt sorted_instruction_points mem1 mem2.\n  Proof.\n    intros EXTRACT * SEM [raised_pol_instr_lst_lst [instr_point_lst_lst ESL]].\n    exists (flatten instr_point_lst_lst).\n    constructor; [|constructor].\n    Case \"Sorted\".\n      clear' - ESL.\n      induction' ESL; simpl; auto.\n      SCase \"ESLI2_cons\".\n        apply ESL_inv1_Forall_first_dim_gt with (pos := pos) in ESL;\n          [|unfold Zsucc; lia].\n        subst.\n        rewrite map_map in H3.\n        assert (Forall (first_dim_eq pos) instr_point_lst) as FA.\n          eapply Permutation_Forall; [|eauto].\n          apply Forall_flatten.\n          rewrite Forall_forall.\n          clear'.\n          intros instr_point_lst IN.\n          rewrite in_map_iff in IN.\n          destruct IN as [? [? ?]].\n          subst.\n          rewrite raise_time_stamp_expand_poly_instr.\n          rewrite Forall_forall.\n          clear'.\n          intros instr_point_lst IN.\n          rewrite in_map_iff in IN.\n          destruct IN as [? [? ?]].\n          subst. destruct x0; compute. constructor.\n\n        clear' - H2 ESL IHESL FA.\n        induction' instr_point_lst as [|ip instr_point_lst]; simpl; auto.\n        SSCase \"cons ip instr_point_lst\".\n          inv H2.\n          specialize (IHinstr_point_lst H1).\n          inv FA.\n          constructor; auto.\n          inv H3; auto; simpl; [|constructor; auto].\n          apply Forall_flatten in ESL.\n          inv ESL; constructor.\n          clear' - H2 H0.\n          unfold first_dim_eq, first_dim_gt, instruction_point_lt in *.\n          destruct ip; destruct x; simpl in *.\n          inv H2; inv H0. constructor. auto.      \n    Case \"Permutation\".\n      erewrite ESL_inv1_extract_statement_list in EXTRACT; eauto.\n      clean. clear SEM.\n      induction' ESL.\n      SCase \"ESLI1_nil\".\n        simpl in *. clean.\n      SCase \"ESLI2_cons\".\n        simpl.\n        rewrite map_app. rewrite flatten_app.\n        apply Permutation_app; auto.\n\n    Case \"instruction_list_semantics\".\n      clear' - ESL.\n      induction' ESL; simpl.\n      SCase \"ESLI1_nil\".\n        constructor.\n      SCase \"ESLI2_cons\".\n        eapply instruction_list_semantics_app2; eauto.\n  Qed.\n  Inductive hd_ge z : list Z -> Prop :=\n  | hd_ge_intro: forall x l, z <= x ->\n    hd_ge z (x :: l).\n\n  Fixpoint map2_sl {A1 A2 B} (f: A1 -> A2 -> B) (l1: list A1)\n    (l2: list A2) : option (list B) :=\n    match l1, l2 with\n    | [], [] => Some nil\n    | [], _\n    | _, [] => None\n    | a1 :: l1', a2 :: l2' =>\n      do l' <- map2_sl f l1' l2';\n      Some (f a1 a2 :: l')\n    end.\n\n\n  Lemma flatten_map A B (f: A -> B) ll:\n    flatten (map (fun l=> map f l) ll) = map f (flatten ll).\n  Proof.\n    induction ll; simpl; auto.\n    rewrite IHll. symmetry. apply map_app.\n  Qed.\n    \n  Lemma Permutation_flatten_map A B (f: A -> B) l ll:\n    Permutation (flatten ll) l ->\n    Permutation (flatten (map (fun l' => map f l') ll)) (map f l).\n  Proof.\n    intros. rewrite flatten_map. apply Permutation_map. assumption.\n  Qed.\n\n  Lemma bar: forall A\n    (p_fst_part p_snd_part long_list: list (list A))\n    (fst_part snd_part: list A),\n    Permutation (flatten p_fst_part) fst_part ->\n    Permutation (flatten p_snd_part) snd_part ->\n    map2_sl (fun l1 l2 => l1 ++ l2) p_fst_part p_snd_part = Some long_list ->\n    Permutation (flatten long_list) (fst_part ++ snd_part).\n  Proof.\n    intros.\n    etransitivity; [|eapply Permutation_app; eauto].\n    clear - H1.\n    revert dependent p_snd_part. revert long_list.\n    induction p_fst_part; simpl in *; intros;\n    destruct p_snd_part; clean.\n    prog_dos.\n    specialize (IHp_fst_part _ _ Heq_do).\n    simpl.\n    etransitivity. apply Permutation_app; [reflexivity|eexact IHp_fst_part].\n    rewrite <- app_assoc. rewrite <- app_assoc.\n    apply Permutation_app. reflexivity.\n    etransitivity;[|\n    apply Permutation_app_comm].\n    rewrite <- app_assoc.\n    apply Permutation_app. reflexivity.\n    apply Permutation_app_comm.\n  Qed.\n    \n\n  Lemma foo: forall A\n    (p_fst_part p_snd_part long_list: list (list A))\n    (fst_part snd_part: list A)\n    f,\n    Permutation (flatten p_fst_part) fst_part ->\n    Permutation (flatten p_snd_part) snd_part ->\n    map2_sl (fun l1 l2 => (map f l1) ++ l2) p_fst_part p_snd_part = Some long_list ->\n    Permutation (flatten long_list) (map f fst_part ++ snd_part).\n  Proof.\n    intros.\n    eapply bar; eauto.\n    apply Permutation_flatten_map; eauto.\n    clear - H1.\n    revert H1. revert long_list p_snd_part.\n    induction p_fst_part; simpl in *; intros; clean.\n    destruct p_snd_part; clean. prog_dos.\n    erewrite IHp_fst_part in Heq_do0; eauto. clean.\n\n    \n    erewrite IHp_fst_part in Heq_do0;[|eauto]. clean.\n  Qed.\n\n  Fixpoint extract_statement_correct (global_depth: nat)\n    (st: statement global_depth)\n    (instrs_lst: list (Polyhedral_Instruction global_depth)) {struct st}:\n    extract_statement st = OK instrs_lst ->\n    forall ctxt mem1 mem2, \n      semantics_statement ctxt st mem1 mem2 ->\n      exists sorted_instruction_points,\n      poly_list_semantics global_depth instrs_lst\n       ctxt sorted_instruction_points mem1 mem2\n  with extract_statement_list_ok (global_depth: nat)\n    (pos: Z) (st_lst: statement_list global_depth)\n    (instrs_lst : list (Polyhedral_Instruction global_depth)){struct st_lst}:\n    extract_statement_list pos st_lst = OK instrs_lst ->\n    forall ctxt mem1 mem2,\n    semantics_statement_list ctxt st_lst mem1 mem2 ->\n    exists raised_pol_instr_lst_lst instr_point_lst_lst,\n      ESL_inv1 global_depth ctxt pos mem1 mem2\n        st_lst raised_pol_instr_lst_lst instr_point_lst_lst \n(*  with extract_statement_list_correct (global_depth: nat)\n    (instructions: PTree.t I.Instruction) (pos: Z) (st_lst: statement_list global_depth)\n    (instrs_lst : list (Polyhedral_Instruction global_depth)) {struct st_lst}:\n    extract_statement_list pos st_lst = OK instrs_lst ->\n    forall ctxt mem1 mem2, \n      semantics_statement_list ctxt st_lst mem1 mem2 ->\n      exists sorted_instruction_points,\n      poly_list_semantics global_depth instrs_lst\n       ctxt sorted_instruction_points mem1 mem2*).\n  Proof.\n    Case \"extract_statement_correct\".\n      intros.\n      destruct' st; simpl in H; unfold not_implemented in *; clean.\n      SCase \"Loop\".\n        destruct (check_bound lower_bound) as [CLB | _]; clean.\n        destruct (check_bound upper_bound) as [CUB | _]; clean.\n        inv H0; clean.\n        assert (\n          exists sorted_instruction_points,\n            list_forall\n              (fun ip => hd_ge lb ip.(ip_time_stamp)) sorted_instruction_points /\\\n            poly_list_semantics global_depth instrs_lst ctxt\n              sorted_instruction_points mem1 mem2) as ASSERT;\n        [|solve [destruct ASSERT as [sip [? ?]]; exists sip; auto]].\n        prog_dos.\n        specialize extract_statement_list_ok with (1 := Heq_do).\n        assert' (forall ctxt mem1 mem2,\n          semantics_statement_list ctxt body mem1 mem2 ->\n          exists sorted_instruction_points,\n            poly_list_semantics (S global_depth) lpi\n            ctxt sorted_instruction_points mem1 mem2) as ESL_correct.\n        SSCase \"Assert: ESL_correct\".\n          intros. eapply extract_statement_list_ok_correct; eauto.\n        End_of_assert ESL_correct.\n        clear extract_statement_list_ok extract_statement_correct.\n        clear Heq_do.\n        unfold build_boxed_poly_for_Loop.\n        simpl in *.\n        unfold poly_list_semantics. simpl.\n        \n        repeat rewrite map_map. \n        unfold expand_poly_instr. simpl.\n        destruct (eval_lower_bound_no ctxt lower_bound CLB) as [lb' ?].\n        destruct (eval_upper_bound_no ctxt upper_bound CUB) as [ub' ?].\n        simpl.\n        assert (ub' = ub) by congruence. subst.\n        assert (lb' = lb) by congruence. subst.\n        clear dependent lower_bound.\n        clear dependent upper_bound.\n        unfold list_of_Z_between.\n        revert dependent mem2. revert mem1.\n        functional induction (list_of_Z_between_aux ub lb); intros.\n        SSCase \"lb <= ub\".\n          inv H10; clean;[simpl in *; lia|].\n          unfold Zsucc in *.\n          specialize (IHl _ _ H6).\n          specialize (ESL_correct _ _ _ H3).\n          destruct ESL_correct as [fst_part [? [? ?]]].\n          destruct IHl as [snd_part [? [? [? ? ]]]].\n          exists\n            ((map (fun ip => \n                {| ip_instruction := ip.(ip_instruction);\n                   ip_arguments := ip.(ip_arguments);\n                   ip_time_stamp := lb :: ip.(ip_time_stamp)|}) fst_part) ++\n              snd_part).\n          repeat (apply conj).\n          S3Case \"list_forall\".\n            apply list_forall_list_forall_app.\n            S4Case \"fst_part\".\n              clear'.\n              induction fst_part; simpl; constructor; auto.\n              constructor. lia.\n            S4Case \"snd_part\".\n              eapply list_forall_imply; [|eassumption].\n              simpl. clear'. intros ip HDGE. inv HDGE. constructor. lia.\n          S3Case \"Sorted\".\n            clear' - H H4 H2.\n            induction' fst_part as [|ip1 fst_part]; simpl; auto.\n            S4Case \"cons ip1 fst_part\".\n              inv H.\n              constructor; auto.\n              destruct' fst_part as [|ip2 fst_part]; simpl.\n              S5Case \"nil\".\n                destruct' snd_part as [|ip2 snd_part]; simpl; auto.\n                S6Case \"cons ip2 snd_part\".\n                  constructor.\n                  inv H2. destruct ip2. red. simpl in *.\n                  inv H1. apply TSLT_lt. lia.\n              S5Case \"cons ip2 fst_part\".\n                constructor. red. simpl. apply TSLT_eq.\n                inv H5. red in H0. assumption.\n          S3Case \"Permutation\".\n            clear' - H0 H5.\n            simpl.\n            erewrite map_ext.\n            Focus 2. intros.\n            rewrite map_map. rewrite map_map.\n            rewrite map_app. rewrite map_map.\n            reflexivity.\n            unfold expand_poly_instr in H0.\n            Focus 1.\n            eapply foo; eauto.\n            clear'.\n            induction' lpi as [|pi lpi].\n            S4Case \"nil\".\n              simpl. reflexivity.\n            S4Case \"cons pi lpi\".\n              simpl. rewrite IHlpi.\n              simpl_do. clear'. f_equal.\n              f_equal. f_equal.\n              rewrite  map_map. simpl. rewrite map_map. simpl. apply map_ext.\n              unfold make_context_ext. simpl.\n              intros; f_equal. apply cast_pi_transformation_id.\n              f_equal.\n              rewrite Vprod_Vcons. simpl. unfold Context in *.\n              clear'.\n              destruct pi. simpl in *. clear'.\n              match goal with\n                | |-\n                  context[〈?v1 +++ ?v2, ?v3 +++ ?v4〉] =>\n                  pose proof (Vprod_app v1 v3 v2 v4) as VPA\n              end.\n              unfold ZNum.Num in *. unfold ZNum.Numerical_Num in *.\n              simpl in VPA. rewrite VPA. clear VPA.\n              simpl_vect. simpl; lia.\n\n              destruct pi; simpl in *; clear'.\n              rewrite cast_list_cast_A. unfold apply_schedule.\n              induction' pi_schedule0; simpl; auto.\n              S5Case \"cons\".\n                f_equal; auto.\n                clear'. unfold cast_A.\n                dest_vects. clear'. dest_eq_rect. simpl.\n                rewrite snoc_app; auto.\n              \n              rewrite map_map. rewrite map_map. apply map_ext.\n              intros. reflexivity.\n\n          S3Case \"instruction_list_semantics\".\n            eapply instruction_list_semantics_app2; eauto.\n            clear' - H1.\n            induction H1; econstructor; eauto.\n            inv H; simpl. econstructor; eauto.\n          \n        SSCase \"ub < lb\".\n          simpl.\n          inv H10; clean;[| simpl in *; lia].\n          exists (@nil Instruction_Point).\n          repeat constructor.\n          clear'. induction lpi; auto.\n\n      SCase \"Instr\".\n      eexists; econstructor; [|econstructor]; simpl;[|reflexivity|].\n      SSCase \"Sorted\".\n        repeat constructor.\n      SSCase \"instruction_list_semantics\".\n        econstructor;[|econstructor].\n        unfold make_context_ext.\n        rewrite V0_Vapp.\n        inv H0. clean.\n        econstructor; simpl; clean; eauto.\n\n    Case \"extract_statement_list_ok\".\n      revert instrs_lst pos.\n      destruct' st_lst as [|st st_lst]; intros * EXTRACT * SEM; inv SEM; clean.\n      SCase \"stl_nil\".\n        repeat econstructor.\n      SCase \"stl_cons st st_lst\".\n        simpl in EXTRACT.\n        prog_dos.\n        edestruct extract_statement_list_ok as [?[??]]; eauto.\n        edestruct extract_statement_correct as [instr_point_lst H0]; eauto.\n        eapply raise_time_stamp_poly_list_semantics in H0.\n        destr_poly_list_semantics.\n        eexists; eexists; econstructor; eauto.\n(*    Case \"extract_statement_list_correct\".\n    intros.\n    eapply extract_statement_list_ok_correct; eauto.*)\n  Qed.\n\n  Definition extract_program (prog:Program) : res Poly_Program :=\n    do pil <- extract_statement_list 1 prog.(prog_main);\n    OK {|pp_nbr_global_parameters := prog.(prog_nbr_global_parameters);\n         pp_poly_instrs := pil|}.\n\n  Theorem extract_program_correct prog pprog:\n    extract_program prog = OK pprog ->\n    forall params mem1 mem2,\n      program_semantics prog params mem1 mem2 ->\n      poly_program_semantics_param instruction_point_lt pprog params mem1 mem2.\n  Proof.\n    intros EXTRACT * PROGSEM.\n    unfold extract_program in EXTRACT.\n    prog_dos.\n    pose proof (extract_statement_list_ok _ _ _ _ Heq_do).\n\n    destruct' (make_vector prog.(prog_nbr_global_parameters) params) as [Vparams|] _eqn.\n    Case \"Some Vparams\".\n      inv PROGSEM.\n      assert (Vparams0 = Vparams) by congruence. subst.\n      clear H0.\n\n      edestruct extract_statement_list_ok_correct; eauto.\n\n      destruct H0 as [? [? ?]].\n      econstructor; simpl; eauto.\n\n    Case \"None\".\n    inv PROGSEM. rewrite H0 in Heqo. clean.\n  Qed.\n\n(*  Fixpoint extract_statement (instructions: PTree.t I.instruction)\n    nbr_params depth (ctxt: boxed_poly nbr_params depth)\n    (st : statement nbr_params depth) :=\n*)\nEnd Extract.\n", "meta": {"author": "pilki", "repo": "s2sLoop", "sha": "821528456333c518788df2834c674e850d7e7291", "save_path": "github-repos/coq/pilki-s2sLoop", "path": "github-repos/coq/pilki-s2sLoop/s2sLoop-821528456333c518788df2834c674e850d7e7291/src/ExtractPoly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.29264444278008056}}
{"text": "(* -*- mode: coq; mode: visual-line -*- *)\n\n(** * Homotopy coequalizers *)\n\nRequire Import HoTT.Basics UnivalenceImpliesFunext.\nRequire Import Types.Paths Types.Forall Types.Sigma Types.Arrow Types.Universe.\nLocal Open Scope path_scope.\n\n(** ** Definition *)\n\nModule Export Coeq.\n\n  Private Inductive Coeq {B : Type@{i}} {A : Type@{j}}\n    (f g : B -> A) : Type@{max(i,j)} :=\n      | coeq : A -> Coeq f g.\n\n  Arguments coeq {B A f g} a.\n\n  Axiom cglue : forall {B A f g} (b:B), @coeq B A f g (f b) = coeq (g b).\n\n  Definition Coeq_ind {B A f g} (P : @Coeq B A f g -> Type)\n             (coeq' : forall a, P (coeq a))\n             (cglue' : forall b, (cglue b) # (coeq' (f b)) = coeq' (g b))\n  : forall w, P w\n    := fun w => match w with coeq a => fun _ => coeq' a end cglue'.\n\n  Axiom Coeq_ind_beta_cglue\n  : forall {B A f g} (P : @Coeq B A f g -> Type)\n           (coeq' : forall a, P (coeq a))\n           (cglue' : forall b, (cglue b) # (coeq' (f b)) = coeq' (g b)) (b:B),\n      apD (Coeq_ind P coeq' cglue') (cglue b) = cglue' b.\n\nEnd Coeq.\n\nDefinition Coeq_rec {B A f g} (P : Type) (coeq' : A -> P)\n  (cglue' : forall b, coeq' (f b) = coeq' (g b))\n  : @Coeq B A f g -> P\n  := Coeq_ind (fun _ => P) coeq' (fun b => transport_const _ _ @ cglue' b).\n\nDefinition Coeq_rec_beta_cglue {B A f g} (P : Type) (coeq' : A -> P)\n  (cglue' : forall b:B, coeq' (f b) = coeq' (g b)) (b:B)\n  : ap (Coeq_rec P coeq' cglue') (cglue b) = cglue' b.\nProof.\n  unfold Coeq_rec.\n  (** Use [eapply] rather than [refine] so that we don't get evars as goals, and don't have to shelve any goals with [shelve_unifiable]. *)\n  eapply (cancelL (transport_const (cglue b) _)).\n  refine ((apD_const (@Coeq_ind B A f g (fun _ => P) coeq' _) (cglue b))^ @ _).\n  refine (Coeq_ind_beta_cglue (fun _ => P) _ _ _).\nDefined.\n\n(** ** Functoriality *)\n\nDefinition functor_coeq {B A f g B' A' f' g'}\n           (h : B -> B') (k : A -> A')\n           (p : k o f == f' o h) (q : k o g == g' o h)\n: @Coeq B A f g -> @Coeq B' A' f' g'.\nProof.\n  refine (Coeq_rec _ (coeq o k) _); intros b.\n  refine (ap coeq (p b) @ _ @ ap coeq (q b)^).\n  apply cglue.\nDefined.\n\nDefinition functor_coeq_beta_cglue {B A f g B' A' f' g'}\n           (h : B -> B') (k : A -> A')\n           (p : k o f == f' o h) (q : k o g == g' o h)\n           (b : B)\n: ap (functor_coeq h k p q) (cglue b)\n  = ap coeq (p b) @ cglue (h b) @ ap coeq (q b)^\n:= (Coeq_rec_beta_cglue _ _ _ b).\n\nDefinition functor_coeq_compose {B A f g B' A' f' g' B'' A'' f'' g''}\n           (h : B -> B') (k : A -> A')\n           (p : k o f == f' o h) (q : k o g == g' o h)\n           (h' : B' -> B'') (k' : A' -> A'')\n           (p' : k' o f' == f'' o h') (q' : k' o g' == g'' o h')\n: functor_coeq (h' o h) (k' o k)\n               (fun b => ap k' (p b) @ p' (h b))\n               (fun b => ap k' (q b) @ q' (h b))\n  == functor_coeq h' k' p' q' o functor_coeq h k p q.\nProof.\n  refine (Coeq_ind _ (fun a => 1) _); cbn; intros b.\n  rewrite transport_paths_FlFr.\n  rewrite concat_p1; apply moveR_Vp; rewrite concat_p1.\n  rewrite ap_compose.\n  rewrite !functor_coeq_beta_cglue, !ap_pp, functor_coeq_beta_cglue.\n  rewrite <- !ap_compose. cbn.\n  rewrite !ap_V, ap_pp, inv_pp, <- ap_compose, !concat_p_pp.\n  reflexivity.\nQed.\n\nDefinition functor_coeq_homotopy {B A f g B' A' f' g'}\n           (h : B -> B') (k : A -> A')\n           (p : k o f == f' o h) (q : k o g == g' o h)\n           (h' : B -> B') (k' : A -> A')\n           (p' : k' o f == f' o h') (q' : k' o g == g' o h')\n           (r : h == h') (s : k == k')\n           (u : forall b, s (f b) @ p' b = p b @ ap f' (r b))\n           (v : forall b, s (g b) @ q' b = q b @ ap g' (r b))\n: functor_coeq h k p q == functor_coeq h' k' p' q'.\nProof.\n  refine (Coeq_ind _ (fun a => ap coeq (s a)) _); cbn; intros b.\n  refine (transport_paths_FlFr (cglue b) _ @ _).\n  rewrite concat_pp_p; apply moveR_Vp.\n  rewrite !functor_coeq_beta_cglue.\n  Open Scope long_path_scope.\n  rewrite !concat_p_pp.\n  rewrite <- (ap_pp (@coeq _ _ f' g') (s (f b)) (p' b)).\n  rewrite u, ap_pp, !concat_pp_p; apply whiskerL; rewrite !concat_p_pp.\n  rewrite ap_V; apply moveR_pV.\n  rewrite !concat_pp_p, <- (ap_pp (@coeq _ _ f' g') (s (g b)) (q' b)).\n  rewrite v, ap_pp, ap_V, concat_V_pp.\n  rewrite <- !ap_compose.\n  exact (concat_Ap (@cglue _ _ f' g') (r b)).\n  Close Scope long_path_scope.\nQed.\n\nDefinition functor_coeq_sect {B A f g B' A' f' g'}\n           (h : B -> B') (k : A -> A')\n           (p : k o f == f' o h) (q : k o g == g' o h)\n           (h' : B' -> B) (k' : A' -> A)\n           (p' : k' o f' == f o h') (q' : k' o g' == g o h')\n           (r : Sect h h') (s : Sect k k')\n           (u : forall b, ap k' (p b) @ p' (h b) @ ap f (r b) = s (f b))\n           (v : forall b, ap k' (q b) @ q' (h b) @ ap g (r b) = s (g b))\n: Sect (functor_coeq h k p q) (functor_coeq h' k' p' q').\nProof.\n  refine (Coeq_ind _ (fun a => ap coeq (s a)) _); cbn; intros b.\n  refine (transport_paths_FFlr (cglue b) _ @ _).\n  rewrite concat_pp_p; apply moveR_Vp.\n  rewrite functor_coeq_beta_cglue, !ap_pp.\n  rewrite <- !ap_compose; cbn.\n  rewrite functor_coeq_beta_cglue.\n  Open Scope long_path_scope.\n  rewrite !concat_p_pp.\n  rewrite <- u, !ap_pp, !(ap_compose k' coeq).\n  rewrite !concat_pp_p; do 2 apply whiskerL.\n  rewrite !concat_p_pp.\n  rewrite <- v.\n  rewrite !ap_pp, !ap_V, !concat_p_pp, !concat_pV_p.\n  rewrite <- !ap_compose.\n  exact (concat_Ap cglue (r b)).\n  Close Scope long_path_scope.\nQed.\n\nSection IsEquivFunctorCoeq.\n\n  Context {B A f g B' A' f' g'}\n          (h : B -> B') (k : A -> A')\n          `{IsEquiv _ _ h} `{IsEquiv _ _ k}\n          (p : k o f == f' o h) (q : k o g == g' o h).\n\n  Definition functor_coeq_inverse\n  : @Coeq B' A' f' g' -> @Coeq B A f g.\n  Proof.\n    refine (functor_coeq h^-1 k^-1 _ _).\n    - intros b.\n      refine (ap (k^-1 o f') (eisretr h b)^ @ _ @ eissect k (f (h^-1 b))).\n      apply ap, inverse, p.\n    - intros b.\n      refine (ap (k^-1 o g') (eisretr h b)^ @ _ @ eissect k (g (h^-1 b))).\n      apply ap, inverse, q.\n  Defined.\n\n  Definition functor_coeq_eissect\n  : Sect functor_coeq_inverse (functor_coeq h k p q).\n  Proof.\n    Open Scope long_path_scope.\n    refine (functor_coeq_sect _ _ _ _ _ _ _ _\n                              (eisretr h) (eisretr k) _ _); intros b.\n    (** The two proofs are identical modulo replacing [f] by [g], [f'] by [g'], and [p] by [q]. *)\n    all:rewrite !ap_pp, <- eisadj.\n    all:rewrite <- !ap_compose.\n    all:rewrite (concat_pA1_p (eisretr k) _ _).\n    all:rewrite concat_pV_p.\n    all:rewrite <- (ap_compose (k^-1 o _) k).\n    all:rewrite (ap_compose _ (k o k^-1)).\n    all:rewrite (concat_A1p (eisretr k) (ap _ (eisretr h b)^)).\n    all:rewrite ap_V, concat_pV_p; reflexivity.\n    Close Scope long_path_scope.\n  Qed.\n\n  Definition functor_coeq_eisretr\n  : Sect (functor_coeq h k p q) functor_coeq_inverse.\n  Proof.\n    Open Scope long_path_scope.\n    refine (functor_coeq_sect _ _ _ _ _ _ _ _\n                              (eissect h) (eissect k) _ _); intros b.\n    all:rewrite !concat_p_pp, eisadj, <- ap_V, <- !ap_compose.\n    all:rewrite (ap_compose (_ o h) k^-1).\n    all:rewrite <- !(ap_pp k^-1), !concat_pp_p.\n    1:rewrite (concat_Ap (fun b => (p b)^) (eissect h b)^).\n    2:rewrite (concat_Ap (fun b => (q b)^) (eissect h b)^).\n    all:rewrite concat_p_Vp, concat_p_pp.\n    all:rewrite <- (ap_compose (k o _) k^-1), (ap_compose _ (k^-1 o k)).\n    all:rewrite (concat_A1p (eissect k) _).\n    all:rewrite ap_V, concat_pV_p; reflexivity.\n    Close Scope long_path_scope.\n  Qed.\n\n  Global Instance isequiv_functor_coeq\n  : IsEquiv (functor_coeq h k p q)\n    := isequiv_adjointify _ functor_coeq_inverse\n                          functor_coeq_eissect functor_coeq_eisretr.\n\n  Definition equiv_functor_coeq\n  : @Coeq B A f g <~> @Coeq B' A' f' g'\n    := Build_Equiv _ _ (functor_coeq h k p q) _.\n\nEnd IsEquivFunctorCoeq.\n\nDefinition equiv_functor_coeq' {B A f g B' A' f' g'}\n           (h : B <~> B') (k : A <~> A')\n           (p : k o f == f' o h) (q : k o g == g' o h)\n: @Coeq B A f g <~> @Coeq B' A' f' g'\n  := equiv_functor_coeq h k p q.\n\n(** ** A double recursion principle *)\n\nSection CoeqRec2.\n  Context `{Funext}\n          {B A : Type} {f g : B -> A} {B' A' : Type} {f' g' : B' -> A'}\n          (P : Type) (coeq' : A -> A' -> P)\n          (cgluel : forall b a', coeq' (f b) a' = coeq' (g b) a')\n          (cgluer : forall a b', coeq' a (f' b') = coeq' a (g' b'))\n          (cgluelr : forall b b', cgluel b (f' b') @ cgluer (g b) b'\n                               = cgluer (f b) b' @ cgluel b (g' b')).\n\n  Definition Coeq_rec2\n  : Coeq f g -> Coeq f' g' -> P.\n  Proof.\n    simple refine (Coeq_rec _ _ _).\n    - intros a.\n      simple refine (Coeq_rec _ _ _).\n      + intros a'.\n        exact (coeq' a a').\n      + intros b'; cbn.\n        apply cgluer.\n    - intros b.\n      apply path_arrow; intros a.\n      revert a; simple refine (Coeq_ind _ _ _).\n      + intros a'. cbn.\n        apply cgluel.\n      + intros b'; cbn.\n        refine (transport_paths_FlFr (cglue b') (cgluel b (f' b')) @ _).\n        refine (concat_pp_p _ _ _ @ _).\n        apply moveR_Vp.\n        refine (_ @ cgluelr b b' @ _).\n        * apply whiskerL.\n          apply Coeq_rec_beta_cglue.\n        * apply whiskerR.\n          symmetry; apply Coeq_rec_beta_cglue.\n  Defined.\n\n  Definition Coeq_rec2_beta (a : A) (a' : A')\n  : Coeq_rec2 (coeq a) (coeq a') = coeq' a a'\n    := 1.\n\n  Definition Coeq_rec2_beta_cgluel (a : A) (b' : B')\n  : ap (Coeq_rec2 (coeq a)) (cglue b') = cgluer a b'.\n  Proof.\n    apply Coeq_rec_beta_cglue.\n  Defined.\n\n  Definition Coeq_rec2_beta_cgluer (b : B) (a' : A')\n  : ap (fun x => Coeq_rec2 x (coeq a')) (cglue b) = cgluel b a'.\n  Proof.\n    transitivity (ap10 (ap Coeq_rec2 (cglue b)) (coeq a')).\n    - refine (ap_compose Coeq_rec2 (fun h => h (coeq a')) _ @ _).\n      apply ap_apply_l.\n    - unfold Coeq_rec2; rewrite Coeq_rec_beta_cglue.\n      rewrite ap10_path_arrow.\n      reflexivity.\n  Defined.\n\n  (** TODO: [Coeq_rec2_beta_cgluelr] *)\n\nEnd CoeqRec2.\n\n(** ** A double induction principle *)\n\nSection CoeqInd2.\n  Context `{Funext}\n          {B A : Type} {f g : B -> A} {B' A' : Type} {f' g' : B' -> A'}\n          (P : Coeq f g -> Coeq f' g' -> Type)\n          (coeq' : forall a a', P (coeq a) (coeq a'))\n          (cgluel : forall b a',\n                   transport (fun x => P x (coeq a')) (cglue b)\n                             (coeq' (f b) a') = coeq' (g b) a')\n          (cgluer : forall a b',\n                   transport (fun y => P (coeq a) y) (cglue b')\n                             (coeq' a (f' b')) = coeq' a (g' b'))\n          (** Perhaps this should really be written using [concatD]. *)\n          (cgluelr : forall b b',\n                  ap (transport (P (coeq (g b))) (cglue b')) (cgluel b (f' b'))\n                  @ cgluer (g b) b'\n                  = transport_transport P (cglue b) (cglue b') (coeq' (f b) (f' b'))\n                  @ ap (transport (fun x => P x (coeq (g' b'))) (cglue b))\n                       (cgluer (f b) b')\n                  @ cgluel b (g' b')).\n\n  Definition Coeq_ind2\n  : forall x y, P x y.\n  Proof.\n    simple refine (Coeq_ind _ _ _).\n    - intros a.\n      simple refine (Coeq_ind _ _ _).\n      + intros a'.\n        exact (coeq' a a').\n      + intros b'; cbn.\n        apply cgluer.\n    - intros b.\n      apply path_forall; intros a.\n      revert a; simple refine (Coeq_ind _ _ _).\n      + intros a'. cbn.\n        refine (transport_forall_constant _ _ _ @ _).\n        apply cgluel.\n      + intros b'; cbn.\n        refine (transport_paths_FlFr_D (cglue b') _ @ _).\n        rewrite Coeq_ind_beta_cglue.\n        (** Now begins the long haul. *)\n        Open Scope long_path_scope.\n        rewrite ap_pp.\n        repeat rewrite concat_p_pp.\n        (** Our first order of business is to get rid of the [Coeq_ind]s, which only occur in the following incarnation. *)\n        set (G := (Coeq_ind (P (coeq (f b)))\n                            (fun a' : A' => coeq' (f b) a')\n                            (fun b'0 : B' => cgluer (f b) b'0))).\n        (** Let's reduce the [apD (loop # G)] first. *)\n        rewrite (apD_transport_forall_constant P (cglue b) G (cglue b')); simpl.\n        rewrite !inv_pp, !inv_V.\n        (** Now we can cancel a [transport_forall_constant]. *)\n        rewrite !concat_pp_p; apply whiskerL.\n        (** And a path-inverse pair.  This removes all the [transport_forall_constant]s. *)\n        rewrite !concat_p_pp, concat_pV_p.\n        (** Now we can beta-reduce the last remaining [G]. *)\n        subst G; rewrite Coeq_ind_beta_cglue; simpl.\n        (** Now we just have to rearrange it a bit. *)\n        rewrite !concat_pp_p; do 2 apply moveR_Vp; rewrite !concat_p_pp.\n        apply cgluelr.\n        Close Scope long_path_scope.\n  Qed.\n\nEnd CoeqInd2.\n\n(** ** Symmetry *)\n\nDefinition Coeq_sym_map {B A} (f g : B -> A) : Coeq f g -> Coeq g f :=\n  Coeq_rec (Coeq g f) coeq (fun b : B => (cglue b)^).\n\nLemma sect_Coeq_sym_map {B A} {f g : B -> A} : Sect (Coeq_sym_map g f) (Coeq_sym_map f g).\nProof.\n  unfold Sect. srapply @Coeq_ind.\n  - reflexivity.\n  - intro b.\n    abstract (rewrite transport_paths_FFlr, Coeq_rec_beta_cglue, ap_V, Coeq_rec_beta_cglue; hott_simpl).\nDefined.\n\nLemma Coeq_sym {B A} {f g : B -> A} : @Coeq B A f g <~> Coeq g f.\nProof.\n  exact (equiv_adjointify (Coeq_sym_map f g) (Coeq_sym_map g f) sect_Coeq_sym_map sect_Coeq_sym_map).\nDefined.", "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/HIT/Coeq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.29259420879752746}}
{"text": "\nFrom CE Require Export Helpers.\n\nImport ListNotations.\n\nDefinition Environment : Type := list ((Var + FunctionIdentifier) * Value).\n\nFixpoint count_closures (env : Environment) : nat :=\nmatch env with\n| [] => 0\n| (_, VClos _ _ _ _ _)::xs => S (count_closures xs)\n| _::xs => count_closures xs\nend.\n\n(** Get *)\nFixpoint get_value (env : Environment) (key : (Var + FunctionIdentifier)) \n   : (Value + Exception) :=\nmatch env with\n| [ ] => inr novar\n| (k,v)::xs => if var_funid_eqb key k then inl v else get_value xs key\nend.\n\n(** Insert *)\nFixpoint insert_value (env : Environment) (key : (Var + FunctionIdentifier)) \n   (value : Value) : Environment :=\nmatch env with\n  | [] => [(key, value)]\n  | (k,v)::xs => if var_funid_eqb k key then (key,value)::xs else (k,v)::(insert_value xs key value)\nend.\n\n(** Add additional bindings *)\n(** We used here: when binding, variables must be unique *)\nFixpoint add_bindings (bindings : list (Var * Value)) (env : Environment) : Environment :=\nmatch bindings with\n| [] => env\n| (v, e)::xs => add_bindings xs (insert_value env (inl v) e)\nend.\n\n(** Add bindings with two lists *)\nFixpoint append_vars_to_env (vl : list Var) (el : list Value) (d : Environment) \n   : Environment :=\nmatch vl, el with\n| [], [] => d\n| v::vs, e::es => append_vars_to_env vs es (insert_value d (inl v) e)\n| _, _ => []\nend.\n\n\nDefinition append_try_vars_to_env (vl : list Var) (el : list Value) (d : Environment) \n   : Environment :=\nmatch el with\n| [] => []\n| e::es =>\nif length vl =? 2 then append_vars_to_env vl es d else append_vars_to_env vl el d\nend.\n\n\n(** Not Overwriting insert *)\n(** Overwriting does not fit with this recursion *)\nFixpoint insert_function (id : nat) (v : FunctionIdentifier) (p : list Var) (b : Expression) \n   (l : list (nat * FunctionIdentifier * FunctionExpression)) \n    : list (nat * FunctionIdentifier * FunctionExpression) :=\nmatch l with\n| [] => [(id, v, (p, b))]\n| (id', k, v0)::xs => if funid_eqb k v then (id', k, v0)::xs \n                                   else (id', k, v0)::(insert_function id v p b xs)\nend.\n\n(** Lists represented functions *)\nFixpoint list_functions (vl : list FunctionIdentifier) (paramss : list (list Var)) \n      (bodies : list Expression) (last_id : nat) \n      : list (nat * FunctionIdentifier * FunctionExpression) :=\nmatch vl, paramss, bodies with\n| [], [], [] => []\n| v::vs, varl::ps, e::bs => insert_function last_id v varl e \n                                 (list_functions vs ps bs (S last_id))\n| _, _, _ => []\nend.\n\n(** Add functions *)\nFixpoint append_funs_to_env_base (vl : list FunctionIdentifier) (paramss : list (list Var)) \n      (bodies : list Expression) (d : Environment) (def : Environment) \n      (deffuns : list (nat * FunctionIdentifier * FunctionExpression)) (last_id : nat) \n      : Environment :=\nmatch vl, paramss, bodies with\n| [], [], [] => d\n| v::vs, varl::ps, e::bs => append_funs_to_env_base vs ps bs \n                              (insert_value d (inr v) \n                                           (VClos def deffuns last_id varl e)) \n                                           def deffuns (S last_id)\n| _, _, _ => []\nend.\n\nDefinition append_funs_to_env (l : list (FunctionIdentifier * ((list Var) * Expression))) (d : Environment) (last_id : nat) : Environment :=\nappend_funs_to_env_base (fst (split l)) (fst (split (snd (split l)))) (snd (split (snd (split l)))) d d \n                       (list_functions (fst (split l)) (fst (split (snd (split l)))) (snd (split (snd (split l)))) last_id)\n                       last_id\n.\n\nCompute append_funs_to_env [((\"f1\"%string,0), ([], ErrorExp)) ; \n                            ((\"f2\"%string,0), ([], ErrorExp)) ;\n                            ((\"f1\"%string,0), ([], ErrorExp)) ]\n                           [(inl \"X\"%string, ErrorValue)] 0.\n\nCompute insert_function 2 (\"f1\"%string, 0) [] ErrorExp (list_functions\n                              [(\"f1\"%string,0); (\"f2\"%string,0); (\"f1\"%string, 0)]\n                              [[];[];[]]\n                              [ErrorExp; ErrorExp; ErrorExp] 0).\n\n(** Environment construction from the extension and the reference *)\nFixpoint get_env_base (env def : Environment) \n   (ext defext : list (nat * FunctionIdentifier * FunctionExpression))\n   : Environment :=\nmatch ext with\n| [] => env\n| (id, f1, (pl, b))::xs => get_env_base (insert_value env (inr f1) (VClos def defext id pl b)) def xs defext\nend.\n\nDefinition get_env (env : Environment) \n   (ext : list (nat * FunctionIdentifier * FunctionExpression))\n   : Environment :=\n  get_env_base env env ext ext\n.\n\nInductive SideEffectId : Set :=\n| Input\n| Output\n.\n\nDefinition SideEffectList : Type := list (SideEffectId * list Value).\n\nDefinition nth_def {A : Type} (l : list A) (def err : A) (i : nat) :=\nmatch i with\n| 0 => def\n| S i' => nth i' l err\nend.\n\nLemma nth_def_eq {A : Type} (l : list A) (i : nat) (e1 def err : A):\n  nth_def (e1::l) def err (S i) = nth_def l e1 err i.\nProof.\n  simpl. destruct i.\n  * simpl. reflexivity.\n  * simpl. reflexivity.\nQed.\n\nTheorem last_nth_equal {A : Type} (l : list A) (def err : A) :\n  last l def = nth_def l def err (length l).\nProof.\n  induction l.\n  * auto.\n  * simpl. rewrite IHl. destruct l.\n    - auto.\n    - simpl. auto.\nQed.\n\nProposition get_value_here (env : Environment) (var : Var + FunctionIdentifier) (val : Value):\nget_value (insert_value env var val) var = inl val.\nProof.\n  induction env.\n  * simpl. rewrite uequal_refl. reflexivity.\n  * simpl. destruct a. case_eq (var_funid_eqb s var); intro.\n    - simpl. rewrite uequal_refl. reflexivity.\n    - simpl. rewrite uequal_sym, H. assumption.\nQed.\n\n(** Previous append result *)\nProposition get_value_there (env : Environment) (var var' : Var + FunctionIdentifier) \n     (val : Value):\nvar <> var' ->\nget_value (insert_value env var val) var' = get_value env var'.\nProof.\n  intro. induction env.\n  * simpl. apply uequal_neq in H. rewrite uequal_sym in H. rewrite H. reflexivity.\n  * simpl. destruct a. case_eq (var_funid_eqb s var); intro.\n    - apply uequal_eq in H0. assert (var <> var'). auto. rewrite <- H0 in H.\n      apply uequal_neq in H. rewrite uequal_sym in H. rewrite H. simpl. apply uequal_neq in H1.\n      rewrite uequal_sym in H1. rewrite H1. reflexivity.\n    - simpl. case_eq (var_funid_eqb var' s); intros.\n      + reflexivity.\n      + apply IHenv.\nQed.\n", "meta": {"author": "harp-project", "repo": "Semantics-comparison", "sha": "e873d74bf0e2a366f71ca317a79f2cee192c9dc3", "save_path": "github-repos/coq/harp-project-Semantics-comparison", "path": "github-repos/coq/harp-project-Semantics-comparison/Semantics-comparison-e873d74bf0e2a366f71ca317a79f2cee192c9dc3/src/Env.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725053, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.29259420075740716}}
{"text": "(* Adapted with minimal modifications from Hoare Logic, Part I\n   (Hoare) of Programming Language Foundations:\n   https://softwarefoundations.cis.upenn.edu/plf-current/Hoare.html *)\n\nFrom Coq Require Import Strings.String Program.Equality.\nFrom LongDivision Require Import Maps Imp.\n\n(* Core definitions *)\n\nDefinition Assertion := state -> Prop.\n\nDefinition assert_implies (P Q : Assertion) : Prop :=\n  forall st, P st -> Q st.\n\nNotation \"P '->>' Q\" := (assert_implies P Q) (at level 80) :\n  hoare_spec_scope.\n\nOpen Scope hoare_spec_scope.\n\nDefinition hoare_triple (P : Assertion) (c : com) (Q : Assertion)\n  : Prop := forall st st', P st -> st =[ c ]=> st' -> Q st'.\n\nNotation \"'{{' P '}}' c '{{' Q '}}'\" := (hoare_triple P c Q)\n  (at level 90, c at next level) : hoare_spec_scope.\n\n(* Proof rules *)\n\nLtac inv H := inversion H; subst; clear H.\n\nTheorem hoare_floyd : forall P x a,\n  {{ P }} x ::= a {{ fun st => exists st',\n  (forall y, x <> y -> st y = st' y) /\\\n  st x = aeval st' a /\\\n  P st' }}.\nProof with auto.\n  unfold hoare_triple; intros; inv H0; unfold t_update.\n  exists st; repeat split...\n  - intros; destruct (string_dec x y)...\n    contradiction H0.\n  - destruct (string_dec x x)...\n    now contradiction n.\nQed.\n\nTheorem hoare_consequence : forall P P' Q Q' c,\n  P ->> P' ->\n  {{ P' }} c {{ Q' }} ->\n  Q' ->> Q ->\n  {{ P }} c {{ Q }}.\nProof. unfold hoare_triple; eauto. Qed.\n\nTheorem hoare_skip : forall P, {{ P }} SKIP {{ P }}.\nProof. unfold hoare_triple; intros; now inv H0. Qed.\n\nTheorem hoare_seq : forall P Q R c1 c2,\n  {{ P }} c1 {{ Q }} ->\n  {{ Q }} c2 {{ R }} ->\n  {{ P }} c1 ;; c2 {{ R }}.\nProof. unfold hoare_triple; intros; inv H2; eauto. Qed.\n\nTheorem hoare_if : forall P Q b c1 c2,\n  {{ fun st => P st /\\ beval st b = true }} c1 {{ Q }} ->\n  {{ fun st => P st /\\ beval st b = false }} c2 {{ Q }} ->\n  {{ P }} TEST b THEN c1 ELSE c2 FI {{ Q }}.\nProof. unfold hoare_triple; intros; inv H2; eauto. Qed.\n\nTheorem hoare_while : forall P b c',\n  {{ fun st => P st /\\ beval st b = true }} c' {{ P }} ->\n  {{ P }} WHILE b DO c' END {{ fun st => P st /\\\n  beval st b = false }}.\nProof.\n  unfold hoare_triple; intros; dependent induction H1; eauto.\nQed.\n\nClose Scope hoare_spec_scope.", "meta": {"author": "DonaldKellett", "repo": "plcc-ch2-long-division", "sha": "11a50d7398416ace651851cacbde5214e3cee57b", "save_path": "github-repos/coq/DonaldKellett-plcc-ch2-long-division", "path": "github-repos/coq/DonaldKellett-plcc-ch2-long-division/plcc-ch2-long-division-11a50d7398416ace651851cacbde5214e3cee57b/Hoare.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.2925942007574071}}
{"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.\n\n(****************************************************************************)\n(* A few tests to check the unsigned adder.        *)\n(****************************************************************************)\n\nDefinition v17  := N2Bv_sized 8 17.\nDefinition v52  := N2Bv_sized 8 52.\nDefinition v69  := N2Bv_sized 8 69.\nDefinition v70  := N2Bv_sized 8 70.\nDefinition v1   := N2Bv_sized 8 1.\nDefinition v255 := N2Bv_sized 8 255.\nDefinition v0   := N2Bv_sized 8 0.\nDefinition v200 := N2Bv_sized 8 200.\nDefinition v100 := N2Bv_sized 8 100.\nDefinition v44  := N2Bv_sized 8 44.\n\n(* Perform a few basic checks to make sure the adder works. *)\n\nExample xadd_17_52_0 : xilinxAdderWithCarry (v17, v52, false) =\n                       (v69, false).\nProof. reflexivity. Qed.\n\nExample xadd_17_52_1 : xilinxAdderWithCarry (v17, v52, true) =\n                       (v70, false).\nProof. reflexivity. Qed.\n\nExample xadd_1_255_1 : xilinxAdderWithCarry (v1, v255, false) =\n                       (v0, true).\nProof. reflexivity. Qed.\n\nExample xadd_0_255_1 : xilinxAdderWithCarry (v0, v255, true) =\n                       (v0, true).\nProof. reflexivity. Qed.\n\nExample xadd_200_100_0 : xilinxAdderWithCarry (v200, v100, false) =\n                         (v44, true).\nProof. reflexivity. Qed.\n\n(****************************************************************************)\n(* A module definition for an 8-bit adder for SystemVerilog netlist         *)\n(* generation.                                                              *)\n(****************************************************************************)\n\nDefinition adder8Interface\n  := combinationalInterface \"adder8\"\n     [mkPort \"a\" (Vec Bit 8); mkPort \"b\" (Vec Bit 8); mkPort \"cin\" Bit]\n     [mkPort \"sum\" (Vec Bit 8); mkPort \"cout\" Bit].\n\nDefinition adder8Netlist\n  := makeNetlist adder8Interface xilinxAdderWithCarry.\n\nLocal Open Scope N_scope.\n\nDefinition adder8_tb_inputs :=\n  map (fun '(a, b, cin)\n       => (N2Bv_sized 8 a, N2Bv_sized 8 b, n2bool cin))\n  [(7, 3, 0);\n   (115, 67, 1);\n   (92, 18, 0);\n   (50, 200, 0);\n   (255, 255, 0);\n   (255, 255, 1)].\n\nDefinition adder8_tb_expected_outputs :=\n  simulate (Comb xilinxAdderWithCarry) adder8_tb_inputs.\n\nDefinition adder8_tb :=\n  testBench \"adder8_tb\" adder8Interface\n  adder8_tb_inputs adder8_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/examples/xilinx/XilinxAdderExamples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.29259419278495497}}
{"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\nFrom Coq Require Export Arith.\nFrom Coq Require Export Compare_dec.\nFrom Coq Require Export ArithRing.\nFrom Coq Require Export Lia.\nFrom Coq Require Export ZArith.\nFrom Coq Require Export ZArithRing.\n \nLtac CaseEq f := generalize (refl_equal f); pattern f at -1 in |- *; case f.\n \nInductive Qpositive : Set :=\n  | nR : Qpositive -> Qpositive\n  | dL : Qpositive -> Qpositive\n  | One : Qpositive.\n \nFixpoint Qpositive_i (w : Qpositive) : nat * nat :=\n  match w with\n  | One => (1, 1)\n  | nR w' => match Qpositive_i w' with\n             | (p, q) => (p + q, q)\n             end\n  | dL w' => match Qpositive_i w' with\n             | (p, q) => (p, p + q)\n             end\n  end.\nCoercion Z_of_nat : nat >-> Z.\n \nTheorem interp_reduced_fraction :\n forall w : Qpositive,\n exists a : Z,\n   (exists b : Z, (a * fst (Qpositive_i w) + b * snd (Qpositive_i w))%Z = 1%Z).\nintros w; elim w; clear w.\nintros w Hrec; elim Hrec; intros a Hrec2; elim Hrec2; intros b; simpl in |- *;\n case (Qpositive_i w); simpl in |- *.\nintros p q Heq; exists a; exists (b - a)%Z.\nrewrite <- Heq; repeat rewrite Znat.inj_plus; ring.\nintros w Hrec; elim Hrec; intros a Hrec2; elim Hrec2; intros b; simpl in |- *;\n case (Qpositive_i w); simpl in |- *.\nintros p q Heq; exists (a - b)%Z; exists b.\nrewrite <- Heq; repeat rewrite Znat.inj_plus; ring.\nexists 1%Z; exists 0%Z; simpl in |- *; lia.\nQed.\n \nFixpoint Qpositive_inv (w : Qpositive) : Qpositive :=\n  match w with\n  | One => One\n  | nR w' => dL (Qpositive_inv w')\n  | dL w' => nR (Qpositive_inv w')\n  end.\n \nTheorem inv_correct :\n forall (w : Qpositive) (p q : nat),\n Qpositive_i w = (p, q) -> Qpositive_i (Qpositive_inv w) = (q, p).\n let T_local :=\n  (intros w'; simpl in |- *; case (Qpositive_i w'); intros p' q' Hrec p q Heq;\n    rewrite (Hrec p' q'); auto; injection Heq; intros H1 H2; \n    rewrite <- H1; rewrite <- H2; rewrite Nat.add_comm; \n    auto) in\n (intros w; elim w; clear w;\n   [ T_local\n   | T_local\n   | simpl in |- *; intros p q Heq; injection Heq; intros H1 H2;\n      rewrite <- H1; rewrite <- H2; auto with * ]). \nQed.\n \nTheorem interp_non_zero :\n forall w : Qpositive,\n exists p : nat, (exists q : nat, Qpositive_i w = (S p, S q)).\nsimple induction w; simpl in |- *;\n (repeat exists 0; auto; fail) ||\n   (intros w' Hrec; elim Hrec; intros p' Hex; elim Hex; intros q' Heq;\n     rewrite Heq).\nexists (p' + S q'); exists q'; auto.\nexists p'; exists (p' + S q'); auto.\nQed.\n \nFixpoint Qpositive_c (p q n : nat) {struct n} : Qpositive :=\n  match n with\n  | O => One\n  | S n' =>\n      match p - q with\n      | O => match q - p with\n             | O => One\n             | v => dL (Qpositive_c p v n')\n             end\n      | v => nR (Qpositive_c v q n')\n      end\n  end.\n \nTheorem minus_O_le : forall n m : nat, n - m = 0 -> n <= m.\nintros n; elim n; clear n.\nauto with arith.\nintros n Hrec m; case m; clear m.\nsimpl in |- *; intros Heq; discriminate Heq.\nsimpl in |- *; intros; apply le_n_S; apply Hrec; auto.\nQed.\n \nTheorem le_minus_O : forall n m : nat, n <= m -> n - m = 0.\nintros n; elim n; clear n.\nsimpl in |- *; auto.\nintros n Hrec m; case m; clear m.\nintros Hle; inversion Hle.\nintros m' Hle; simpl in |- *; apply Hrec; auto with arith.\nQed.\n \nTheorem minus_le : forall m n : nat, m - n <= m.\nintros m; elim m.\nsimpl in |- *; auto.\nintros m' Hrec n; case n; simpl in |- *; auto.\nQed.\n \nTheorem mult_reg_l : forall n m p : nat, S n * m = S n * p -> m = p.\nintros n m; elim m; clear m.\nintros p; case p; simpl in |- *.\nauto.\nintros p'; rewrite <- mult_n_O.\nintros H; discriminate H.\nintros m' Hrec p; case p.\nrewrite <- mult_n_O; simpl in |- *; intros H; discriminate H.\nintros p'; repeat rewrite (Nat.mul_comm (S n)); simpl in |- *.\nintros H; injection H.\nintros H'; apply f_equal with (f := S).\napply Hrec.\nrepeat rewrite (Nat.mul_comm (S n)).\napply Nat.add_cancel_l with n.\nexact H'.\nQed.\n \nTheorem absolu_inj_nat : forall x : nat, Z.abs_nat (Z_of_nat x) = x.\nintros x; case x.\nauto.\nsimpl in |- *.\nexact nat_of_P_o_P_of_succ_nat_eq_succ.\nQed.\n \nTheorem absolu_mult :\n forall x y : Z, Z.abs_nat (x * y) = Z.abs_nat x * Z.abs_nat y.\nintros x; case x; auto; intros p y; case y; auto; simpl in |- *; intros;\n apply nat_of_P_mult_morphism.\nQed.\n \nTheorem Qpositive_c_unfold1 :\n forall p q n : nat,\n S p + S q + S q <= S n ->\n Qpositive_c (S p + S q) (S q) (S n) = nR (Qpositive_c (S p) (S q) n).\nintros p q n Hle; simpl in |- *.\nrewrite <- (plus_n_Sm p q).\nrewrite Nat.sub_succ_l.\nrewrite Nat.add_sub; auto with *.\nauto with arith.\nQed.\n \nTheorem Qpositive_c_unfold2 :\n forall p q n : nat,\n S p + (S p + S q) <= S n ->\n Qpositive_c (S p) (S p + S q) (S n) = dL (Qpositive_c (S p) (S q) n).\nintros p q n Hle; simpl in |- *.\nrewrite le_minus_O.\nrewrite Nat.add_comm.\nrewrite Nat.add_sub.\nauto.\nauto with arith.\nQed.\n \nTheorem construct_correct :\n forall (w : Qpositive) (p q n : nat),\n Qpositive_i w = (p, q) -> p + q <= n -> Qpositive_c p q n = w.\nintros w; elim w; clear w.\nintros w'; simpl in |- *.\nelim (interp_non_zero w'); intros p' Hex; elim Hex; intros q' Heq.\nrewrite Heq.\nintros Hrec p q n Heq_pair.\ninjection Heq_pair; intros Heq2 Heq1; rewrite <- Heq2; rewrite <- Heq1.\ncase n.\nsimpl in |- *; intros Hle; inversion Hle.\nclear n; intros n.\nintros Hle.\n replace (Qpositive_c (S (p' + S q')) (S q') (S n)) with\n  (nR (Qpositive_c (S p') (S q') n)).\napply f_equal with (f := nR).\napply Hrec; auto with *.\nrewrite <- plus_Sn_m.\nrewrite Qpositive_c_unfold1. auto with *.\nauto with *.\nintros w'; simpl in |- *.\nelim (interp_non_zero w'); intros p' Hex; elim Hex; intros q' Heq.\nrewrite Heq.\nintros Hrec p q n Heq_pair.\ninjection Heq_pair; intros Heq2 Heq1; rewrite <- Heq2; rewrite <- Heq1.\ncase n.\nsimpl in |- *; intros Hle; inversion Hle.\nclear n; intros n.\nintros Hle.\n replace (Qpositive_c (S p') (S (p' + S q')) (S n)) with\n  (dL (Qpositive_c (S p') (S q') n)).\napply f_equal with (f := dL).\napply Hrec; auto with *.\nrewrite <- plus_Sn_m.\nrewrite Qpositive_c_unfold2; auto with *.\n\nsimpl in |- *; intros p q n Heq; injection Heq; intros Heq2 Heq1; case n.\nrewrite <- Heq1; simpl in |- *; intros Hle; inversion Hle.\nrewrite <- Heq1; rewrite <- Heq2; simpl in |- *; auto with *.\n\nQed.\n \nTheorem construct_correct2 :\n forall n p q : nat,\n S p + S q <= n ->\n exists d : nat,\n   S p = fst (Qpositive_i (Qpositive_c (S p) (S q) n)) * S d /\\\n   S q = snd (Qpositive_i (Qpositive_c (S p) (S q) n)) * S d.\nintros n; elim n.\nintros p q Hle; inversion Hle.\nclear n; intros n.\nintros Hrec p q Hle; case (le_gt_dec (S p) (S q)).\nsimpl in |- *.\nintros Hle'; rewrite (le_minus_O p q).\nCaseEq (q - p).\nintros Heq_minus; exists p.\nsimpl in |- *; split; auto with arith.\nrewrite <- plus_n_O.\napply Nat.le_antisymm; auto with arith.\napply minus_O_le.\nauto.\nintros q' Heq_minus; elim (Hrec p q').\nintros d; simpl in |- *; case (Qpositive_i (Qpositive_c (S p) (S q') n));\n repeat rewrite <- (Nat.mul_comm (S d)); intros p'' q'' (Heq1, Heq2).\nexists d; split.\nexact Heq1.\nrewrite <- (Nat.sub_add (S p) (S q)).\nsimpl in |- *.\nrewrite Heq_minus; rewrite Heq2.\nsimpl in |- *.\nreplace (S (p + q'' * S d)) with (S p + q'' * S d).\nrewrite Heq1.\nsimpl in |- *.\nring.\nsimpl in |- *; auto.\nauto with arith.\napply le_S_n.\nrewrite plus_n_Sm.\napply Nat.le_trans with (S p + S q).\napply Nat.add_le_mono_l.\napply le_n_S.\nrewrite <- Heq_minus; apply minus_le.\nexact Hle.\nauto with arith.\nintros Hgt; simpl in |- *; CaseEq (p - q).\nintros H; apply Nat.lt_nge in Hgt.\ncontradict Hgt.\napply le_n_S.\napply minus_O_le.\nexact H.\nintros p'.\nintros Heq_minus; simpl in |- *; elim (Hrec p' q).\nintros d; case (Qpositive_i (Qpositive_c (S p') (S q) n)).\nsimpl in |- *; intros p'' q'' (Heq1, Heq2).\nexists d; split; auto.\nrewrite <- (Nat.sub_add (S q) (S p)); simpl in |- *.\nrewrite Heq_minus.\nreplace (S (q + S p')) with (S q + S p').\nrewrite Heq2; rewrite Heq1; ring.\nsimpl in |- *; auto.\nauto with arith.\nrewrite <- Heq_minus.\nreplace (p - q) with (S p - S q).\nrewrite (Nat.sub_add (S q) (S p)).\napply Nat.le_trans with (S p + q).\nauto with arith.\napply le_S_n; rewrite plus_n_Sm.\nexact Hle.\nauto with arith.\nauto.\nQed.\n \nTheorem construct_correct2' :\n forall n p q : nat,\n 1 <= p ->\n 1 <= q ->\n p + q <= n ->\n exists d : nat,\n   p = fst (Qpositive_i (Qpositive_c p q n)) * S d /\\\n   q = snd (Qpositive_i (Qpositive_c p q n)) * S d.\nintros n p; case p.\nintros q H; inversion H.\nintros p' q; case q.\nintros Hle H; inversion H.\nintros q' Hle Hle2; exact (construct_correct2 n p' q').\nQed.\n \nTheorem construct_correct3 :\n forall n n' p q p' q' d : nat,\n S p = S d * p' ->\n S q = S d * q' ->\n S p + S q <= S n ->\n p' + q' <= S n' -> Qpositive_c (S p) (S q) (S n) = Qpositive_c p' q' (S n').\nintros n; elim n; clear n.\nintros n' p q p' q' d; rewrite <- plus_n_Sm.\nsimpl in |- *.\nintros H1 H2 H3; inversion H3.\ninversion H0.\nintros n0 Hrec n' p q p' q' d Heqd1 Heqd2 Hle1 Hle2.\nsimpl in |- *.\nCaseEq (p - q).\nCaseEq (q - p).\nintros H H0.\ncut (p' = q').\nintros Heq'; rewrite Heq'; rewrite (Nat.sub_diag q').\nauto.\napply mult_reg_l with d.\nrewrite <- Heqd2; rewrite <- Heqd1.\napply Nat.le_antisymm; apply minus_O_le; assumption.\nintros q2 Heq2 Heqp.\ncut (p' <= q').\nintros H; generalize (le_minus_O _ _ H).\nintros Heq3; rewrite Heq3.\nCaseEq (q' - p').\nintros Heq4; cut (q' = p').\nintros Heq5; generalize Heq2; replace (q - p) with (S q - S p).\nrewrite Heqd2; rewrite Heqd1; rewrite Heq5.\nrewrite Nat.sub_diag; intros Heq6; discriminate Heq6.\nauto.\napply Nat.le_antisymm; apply minus_O_le; assumption.\nintros q'2.\ngeneralize Hle2; case n'.\ngeneralize Heqd1 Heqd2; case p'; case q'.\nsimpl in |- *; intros H'1 H'2 H'3 H'4; discriminate H'4.\nintros x; rewrite <- (Nat.mul_comm 0); simpl in |- *; intros Dummy;\n discriminate Dummy.\nsimpl in |- *; intros x H'1 H'2 H'3 H'4; discriminate H'4.\nsimpl in |- *; intros n n1 H'1 H'2; rewrite <- plus_n_Sm; intros H'3;\n inversion H'3.\ninversion H1.\nintros n''.\nintros Hle3 Heq4.\nsimpl in |- *.\nCaseEq p'.\nintros Heqp'; generalize Heqd1; rewrite Heqp'.\nrewrite <- (Nat.mul_comm 0); simpl in |- *; intros Dummy; discriminate Dummy.\nintros p'2 Heqp'2.\nchange\n  (dL (Qpositive_c (S p) (S q2) (S n0)) =\n   dL (Qpositive_c (S p'2) (S q'2) (S n''))) in |- *.\napply f_equal with (f := dL).\napply Hrec with d.\n- rewrite <- Heqp'2; assumption.\n- rewrite <- Heq4; rewrite <- Heq2; rewrite (Nat.mul_comm (S d)).\n  rewrite Nat.mul_sub_distr_r.\n  repeat rewrite <- (Nat.mul_comm (S d)).\n  rewrite <- Heqd2; rewrite <- Heqd1.\n  simpl in |- *; auto.\n- auto with zarith.\n- auto with zarith.\n- apply Nat.mul_le_mono_pos_l with (S d); auto with arith.\n  rewrite <- Heqd2; rewrite <- Heqd1.\n  apply le_n_S.\n  apply minus_O_le; assumption.\n- intros p2 Heqp2.\n  CaseEq (p' - q').\n  intros Heqm'; cut (S p - S q = 0).\n  simpl in |- *; rewrite Heqp2; intros Dummy; discriminate Dummy.\n  rewrite Heqd2; rewrite Heqd1.\n  repeat rewrite (Nat.mul_comm (S d)).\n  rewrite <- Nat.mul_sub_distr_r.\n  rewrite Heqm'; simpl in |- *; auto.\n  intros p'2.\n  generalize Hle2; case n'.\n  generalize Heqd1 Heqd2; case p'; case q'.\n  simpl in |- *; intros H'1 H'2 H'3 H'4; discriminate H'4.\n  intros x; rewrite <- (Nat.mul_comm 0); simpl in |- *; intros Dummy;\n   discriminate Dummy.\n  intros x; rewrite <- (Nat.mul_comm 0); simpl in |- *; intros Dummy1 Dummy2;\n   discriminate Dummy2.\n  simpl in |- *; intros n n1 H'1 H'2; rewrite <- plus_n_Sm; intros H'3;\n   inversion H'3.\n  inversion H0.\n  intros n''.\n  intros Hle3 Heq4.\n  CaseEq q'.\n  intros Heq5; generalize Heqd2; rewrite Heq5; simpl in |- *.\n  rewrite <- (Nat.mul_comm 0); simpl in |- *; intros Dummy; discriminate Dummy.\n  intros q'2 Heqq'2.\n  change\n    (nR (Qpositive_c (S p2) (S q) (S n0)) =\n     nR (Qpositive_c (S p'2) (S q'2) (S n''))) in |- *.\n  apply f_equal with (f := nR).\n  apply Hrec with d.\n  * rewrite <- Heq4; rewrite <- Heqp2; rewrite (Nat.mul_comm (S d)).\n    rewrite Nat.mul_sub_distr_r.\n    repeat rewrite <- (Nat.mul_comm (S d)).\n    rewrite <- Heqd2; rewrite <- Heqd1.\n    simpl in |- *; auto.\n  * rewrite <- Heqq'2; assumption.\n  * auto with zarith.\n  * auto with zarith.\nQed.\n \nTheorem construct_correct4 :\n forall p q p' q' n n' : nat,\n S p + S q <= S n ->\n S p' + S q' <= S n' ->\n S p * S q' = S p' * S q ->\n Qpositive_c (S p) (S q) (S n) = Qpositive_c (S p') (S q') (S n').\nintros p q p' q' n n' H H0 H1.\nelim (construct_correct2 _ _ _ H).\nintros d (Heq1, Heq2).\nelim (construct_correct2 _ _ _ H0).\nintros d' (Heq3, Heq4).\nelim (interp_non_zero (Qpositive_c (S p) (S q) (S n))).\nintros p0 Hex1; elim Hex1; intros q0 Heq5; clear Hex1.\nelim (interp_non_zero (Qpositive_c (S p') (S q') (S n'))).\nintros p'0 Hex1; elim Hex1; intros q'0 Heq6; clear Hex1.\nelim (interp_reduced_fraction (Qpositive_c (S p) (S q) (S n))); intros a Hex1;\n elim Hex1; intros b; clear Hex1.\nrewrite Heq6 in Heq4; rewrite Heq6 in Heq3; rewrite Heq5 in Heq2;\n rewrite Heq5 in Heq1; rewrite Heq5; unfold fst, snd in |- *; \n intros Heq7.\ngeneralize H1; rewrite Heq1; rewrite Heq2; rewrite Heq3; rewrite Heq4;\n unfold fst, snd in |- *; clear H1; intros H1.\nunfold fst, snd in Heq1, Heq2, Heq3, Heq4.\ncut (S p0 * S q'0 = S p'0 * S q0).\nintros Heq8.\ncut (S p'0 = Z.abs_nat (a * S p'0 + b * S q'0) * S p0).\nintros Heq9.\ncut (S q'0 = Z.abs_nat (a * S p'0 + b * S q'0) * S q0).\nintros Heq10.\ncut (exists d'' : nat, Z.abs_nat (a * S p'0 + b * S q'0) = S d'').\nintros Hex; elim Hex; intros d'' Heq11; rewrite Heq11 in Heq9;\n rewrite Heq11 in Heq10.\nreplace (S p0 * S d) with (S (d + p0 * S d)).\nreplace (S q0 * S d) with (S (d + q0 * S d)).\nrewrite\n (construct_correct3 n n (d + p0 * S d) (d + q0 * S d) (S p0) (S q0) d).\nreplace (S p'0 * S d') with (S (d' + p'0 * S d')).\nreplace (S q'0 * S d') with (S (d' + q'0 * S d')).\nsymmetry  in |- *.\napply construct_correct3 with (d := d' + d'' * S d').\nreplace (S (d' + p'0 * S d')) with (S p'0 * S d').\nrewrite Heq9; ring.\nauto.\nreplace (S (d' + q'0 * S d')) with (S q'0 * S d').\nrewrite Heq10; ring.\nauto.\nreplace (S (d' + q'0 * S d')) with (S q'0 * S d').\nreplace (S (d' + p'0 * S d')) with (S p'0 * S d').\nrewrite <- Heq3; rewrite <- Heq4.\nexact H0.\nauto.\nauto.\napply Nat.le_trans with (S p + S q).\nrewrite Heq1; rewrite Heq2.\nrewrite <- Nat.mul_add_distr_r.\nrewrite Nat.mul_comm; simpl in |- *; auto with arith.\nassumption.\nauto.\nauto.\nrewrite (Nat.mul_comm (S d)); auto.\nrewrite (Nat.mul_comm (S d)); auto.\nreplace (S (d + q0 * S d)) with (S q0 * S d).\nreplace (S (d + p0 * S d)) with (S p0 * S d).\nrewrite <- Heq1; rewrite <- Heq2.\nexact H.\nauto.\nauto.\napply Nat.le_trans with (S p + S q).\nrewrite Heq1; rewrite Heq2.\nrewrite <- Nat.mul_add_distr_r.\nrewrite Nat.mul_comm; simpl in |- *; auto with arith.\nassumption.\nauto.\nauto.\nCaseEq (Z.abs_nat (a * S p'0 + b * S q'0)).\nintros Dummy; rewrite Dummy in Heq10; simpl in Heq10; discriminate Heq10.\nintros d'' Heq; exists d''; auto.\nrewrite <- (absolu_inj_nat (S q0)).\npattern (S q'0) at 1 in |- *; rewrite <- (absolu_inj_nat (S q'0)).\nrewrite <- absolu_mult.\napply f_equal with (f := Z.abs_nat).\npattern (Z_of_nat (S q'0)) at 1 in |- *; rewrite <- Zmult_1_r.\nrewrite <- Heq7.\nreplace (S q'0 * (a * S p0 + b * S q0))%Z with\n (S p0 * S q'0 * a + S q'0 * (b * S q0))%Z.\nrewrite <- (Znat.inj_mult (S p0)).\nrewrite Heq8.\nrewrite Znat.inj_mult; ring.\nring.\nrewrite <- (absolu_inj_nat (S p0)).\npattern (S p'0) at 1 in |- *; rewrite <- absolu_inj_nat.\nrewrite <- absolu_mult.\napply f_equal with (f := Z.abs_nat).\npattern (Z_of_nat (S p'0)) at 1 in |- *; rewrite <- Zmult_1_r.\nrewrite <- Heq7.\nreplace (S p'0 * (a * S p0 + b * S q0))%Z with\n (S p'0 * S q0 * b + S p'0 * (a * S p0))%Z.\nrewrite <- (Znat.inj_mult (S p'0)).\nrewrite <- Heq8.\nrewrite Znat.inj_mult; ring.\nring.\napply mult_reg_l with (d' + d * S d').\nreplace (S (d' + d * S d')) with (S d * S d').\ntransitivity (S p0 * S d * (S q'0 * S d')).\nring.\nrewrite H1.\nring.\nauto.\nQed.\n \nTheorem construct_correct4' :\n forall p q p' q' n n' : nat,\n 1 <= p ->\n 1 <= q ->\n 1 <= p' ->\n 1 <= q' ->\n p + q <= n ->\n p' + q' <= n' -> p * q' = p' * q -> Qpositive_c p q n = Qpositive_c p' q' n'.\nintros p; case p.\nintros q p' q' n n' H; inversion H.\nintros p0 q; case q.\nintros p' q' n n' H H1; inversion H1.\nintros q0 p'; case p'.\nintros q' n n' H H1 H2; inversion H2.\nintros p'0 q'; case q'.\nintros n n' H H1 H2 H3; inversion H3.\nintros q'0 n; case n.\nsimpl in |- *; intros n' H H1 H2 H3 H4; inversion H4.\nintros n0 n'; case n'.\nsimpl in |- *; intros H H1 H2 H3 H4 H5; inversion H5.\nintros; apply construct_correct4; auto.\nQed.\n \nTheorem interp_inject :\n forall w w' : Qpositive, Qpositive_i w = Qpositive_i w' -> w = w'.\nintros w w' H; CaseEq (Qpositive_i w).\nintros p q Heq.\nrewrite <- construct_correct with (1 := Heq) (n := p + q).\napply construct_correct; auto.\nrewrite <- H; auto.\nauto.\nQed.\n \nTheorem minus_decompose :\n forall a b c d : nat, a = b -> c = d -> a - c = b - d.\nintros a b c d H H1; rewrite H; rewrite H1; auto.\nQed.\n \nTheorem Qpositive_c_equiv :\n forall n p q n' p' q' : nat,\n S p + S q <= n ->\n S p' + S q' <= n' ->\n Qpositive_c (S p) (S q) n = Qpositive_c (S p') (S q') n' ->\n S p * S q' = S p' * S q.\nintros n; elim n.\nsimpl in |- *; intros p q n' p' q' H; inversion H.\nintros n0 Hrec p q n'.\ncase n'.\nsimpl in |- *; intros p' q' H H1; inversion H1.\nunfold Qpositive_c in |- *.\nCaseEq (S p - S q).\nCaseEq (S q - S p).\nintros Heq1 Heq2 n1 p' q'; CaseEq (S p' - S q').\nCaseEq (S q' - S p').\nintros Heq3 Heq4; cut (p = q).\nintros Heq5; rewrite Heq5.\ncut (p' = q').\nintros Heq6; rewrite Heq6.\nintros; apply Nat.mul_comm.\napply eq_add_S; apply Nat.le_antisymm; apply minus_O_le; auto with *.\napply eq_add_S; apply Nat.le_antisymm; apply minus_O_le; auto with *.\nintros p2 H H1 H2 H3 H4; discriminate H4.\nintros n2 H H1 H2 H4; discriminate H4.\nintros q2 Heq1 Heq2 n2 p' q'; CaseEq (S p' - S q').\nCaseEq (S q' - S p').\nintros H3 H4 H H1 H2; discriminate H2.\nintros q'2 H H1 H2 H3 H4; injection H4; intros H5.\nrewrite <- (Nat.sub_add (S p) (S q)).\nrewrite Nat.add_comm.\nrewrite <- (Nat.sub_add (S p') (S q')).\nrewrite Nat.add_comm.\nrewrite (Nat.mul_comm (S p)); rewrite (Nat.mul_comm (S p')).\nrepeat rewrite Nat.mul_add_distr_r; repeat rewrite <- (Nat.mul_comm (S p)).\napply f_equal with (f := fun x : nat => S p * S p' + x).\nrewrite Heq1; rewrite H.\nrewrite <- (Nat.mul_comm (S p')).\napply Hrec with n2.\nrewrite <- Heq1.\nrewrite Nat.add_comm.\nrewrite Nat.sub_add.\napply Nat.le_trans with (p + S q).\nauto with arith.\napply le_S_n; exact H2.\napply minus_O_le; auto.\nrewrite <- H.\nrewrite Nat.add_comm.\nrewrite Nat.sub_add.\napply Nat.le_trans with (p' + S q').\nauto with arith; fail.\napply le_S_n; exact H3.\napply minus_O_le; auto.\nexact H5.\napply minus_O_le; auto.\napply minus_O_le; auto.\nintros n1 dummy1 Dummy2 Dummy3 Dummy; discriminate Dummy.\nintros n1 Heq1 n2 p' q' Hle1 Hle2; CaseEq (S p' - S q').\nCaseEq (S q' - S p').\nintros Dummy3 Dummy1 Dummy2; discriminate Dummy2.\nintros n3 Dummy Dummy1 Dummy2; discriminate Dummy2.\nintros p'2 Heq2 Heq3.\ninjection Heq3; clear Heq3; intros Heq3.\nrewrite <- (Nat.sub_add (S q) (S p)).\nrewrite Nat.add_comm.\nrewrite Heq1.\nrewrite <- (Nat.sub_add (S q') (S p')).\nrewrite <- (Nat.add_comm (S q')).\nrewrite Heq2.\nrepeat rewrite Nat.mul_add_distr_r; repeat rewrite (Nat.mul_comm (S q')).\napply f_equal with (f := fun x : nat => S q * S q' + x).\napply Hrec with n2.\nrewrite Nat.add_comm; rewrite <- Heq1.\nrewrite Nat.add_comm.\nrewrite Nat.sub_add.\napply Nat.le_trans with (p + S q).\nrewrite <- plus_n_Sm.\nauto with arith.\napply le_S_n; assumption.\nlia.\nrewrite <- Heq2.\nrewrite Nat.sub_add.\napply Nat.le_trans with (p' + S q').\nrewrite <- plus_n_Sm; auto with arith.\napply le_S_n; exact Hle2.\nlia.\nexact Heq3.\nlia.\nlia.\nQed.\n \nTheorem Qpositive_c_equiv' :\n forall n p q n' p' q' : nat,\n 1 <= p ->\n 1 <= q ->\n 1 <= p' ->\n 1 <= q' ->\n p + q <= n ->\n p' + q' <= n' -> Qpositive_c p q n = Qpositive_c p' q' n' -> p * q' = p' * q.\nintros n p q n' p' q'; case p.\nintros H; inversion H.\nclear p; intros p Hlp.\ncase q; [ intros H; inversion H | clear q; intros q Dummy; clear Dummy ].\ncase p'; [ intros H; inversion H | clear p'; intros p' Dummy; clear Dummy ].\ncase q'; [ intros H; inversion H | clear q'; intros q' Dummy; clear Dummy ].\nintros; apply Qpositive_c_equiv with n n'; auto.\nQed.\n", "meta": {"author": "coq-community", "repo": "qarith-stern-brocot", "sha": "a36a01526e76f4ef92bc87445da33dfb025e2db4", "save_path": "github-repos/coq/coq-community-qarith-stern-brocot", "path": "github-repos/coq/coq-community-qarith-stern-brocot/qarith-stern-brocot-a36a01526e76f4ef92bc87445da33dfb025e2db4/theories/Qpositive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.29259419271728676}}
{"text": "Require Import Extractions.\nRequire Import syntax lang Integers.\nOpen Scope hdl_type_scope.\nOpen Scope hdl_exp_scope.\nOpen Scope hdl_stmt_scope.\n\nDefinition shiftsAndBitStuff : prog :=\n  Local vec \"h0\" ::== Int.repr 100;;;\n        Input vec \"sdf\" ::== Int.zero;;;\n        Output vec \"s\" ::== Int.zero;;;\n        \"h0\" <= (EVar \"h0\") rightshift (EVal (Int.repr 3));;;\n       \"s\" <= (EVar \"h0\") rightrotate (EVal (Int.repr 3));;;\n       \"s\" <= (EVar \"h0\") and (EVar \"s\");;;\n       \"s\" <= (EVar \"h0\") xor (EVar \"s\");;;\n       \"s\" <= (EVar \"h0\") plus (EVar \"s\");;;\n       \"s\" <= not (EVar \"s\");;;\n       \"s\" ::= not (EVal Int.zero);;;\n        done.\n\nDefinition print_shifts : verilog :=\n  pretty_print_tb_results \"shiftsAndBitStuff\" \"Some shifts\" shiftsAndBitStuff.\n(* Definition loop_print : verilog :=  *)\n(*   pretty_print \"looper\" loop. *)\n\nExtract Constant main => \"Prelude.putStrLn print_shifts\".\n\nExtraction \"shifts.hs\" print_shifts main.\n\n\nProgram Definition array : prog :=\n  Input arr \"w\" <<<(tarr 64 <<<tvec32>>>), 64>>>;;;\n  Output arr \"m\" <<<(tarr 64 <<<tvec32>>>), 64>>>;;;\n  iter 0 64 (fun i => \"m\"@'i <- \"w\"[[i]]);;;\n  done.                                             \nNext Obligation.    \napply 64.\nDefined.\nNext Obligation.\n  unfold array_obligation_1.\n  destruct (Fin.to_nat i).\n  auto.\nDefined.\nDefinition print_array : verilog :=\n  pretty_print_tb \"array\" array.\n\nExtract Constant main => \"Prelude.putStrLn print_array\".\n\nExtraction \"array.hs\" print_array main.\n\n", "meta": {"author": "seftonsg", "repo": "Hardware_KAT", "sha": "ede6d3ec9b9e99662b28f00717632ae0d9f560b0", "save_path": "github-repos/coq/seftonsg-Hardware_KAT", "path": "github-repos/coq/seftonsg-Hardware_KAT/Hardware_KAT-ede6d3ec9b9e99662b28f00717632ae0d9f560b0/src/Extraction/tests/tests.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.29255872599718435}}
{"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(* The cartesian product and its properties *)\n\nRequire Import Sets.\nRequire Import Axioms.\n\n\n(* This definition of the ordered pair is slightly different from *)\n(* the usual one, since we want it to work in an intuisionistic   *)\n(* setting. Works the same, neitherless. The soundness proofs are *)\n(* unpleasant.                                                    *)\n\n\nDefinition Couple (E E' : Ens) := Paire (Sing E) (Paire Vide (Sing E')).\n\nTheorem Couple_inj_left :\n forall A A' B B' : Ens, EQ (Couple A A') (Couple B B') -> EQ A B.\nunfold Couple in |- *; simpl in |- *.\nsimple induction 1.\nintros HA HB; elim (HA true).\nintros x; elim x; simpl in |- *; simple induction 1; intros H3 H4;\n elim (H3 true); simpl in |- *; intros xx; elim xx; \n simpl in |- *; auto with zfc.\nelim (H4 false); simpl in |- *.\nsimple induction x0; simpl in |- *.\nintros.\ncut (EQ (Sing B') Vide).\nsimpl in |- *.\nsimple induction 1.\nintros yy; elim (yy true).\nsimple induction x1.\n\napply EQ_tran with A; auto with zfc.\n\nintros; cut (EQ (Sing B') Vide).\nsimpl in |- *.\nsimple induction 1.\nintros yy; elim (yy true).\nsimple induction x1.\n\napply EQ_tran with A; auto with zfc.\n\nintros yy.\nelim (HB true); simpl in |- *.\nsimple induction x0.\nchange (EQ (Sing A) (Sing B) -> EQ A B) in |- *; intros EE.\napply IN_Sing_EQ.\napply IN_sound_right with (Sing A); auto with zfc.\nchange (EQ (Paire Vide (Sing A')) (Sing B) -> EQ A B) in |- *.\nintros zz.\nelimtype F.\napply (not_EQ_Sing_Vide A').\napply EQ_tran with B.\napply IN_Sing_EQ.\napply IN_sound_right with (Paire Vide (Sing A')); auto with zfc.\napply EQ_sym; apply IN_Sing_EQ;\n apply IN_sound_right with (Paire Vide (Sing A')); \n auto with zfc.\n\nQed.\n\n\n\nTheorem Couple_inj_right :\n forall A A' B B' : Ens, EQ (Couple A A') (Couple B B') -> EQ A' B'.\nunfold Couple in |- *; simpl in |- *.\nsimple induction 1; intros H1 H2.\nelim (H1 false).\nintros bb1; elim bb1.\nintros HF.\nchange (EQ (Paire Vide (Sing A')) (Sing B)) in HF.\ncut F.\nsimple induction 1.\napply (not_EQ_Vide_Sing A').\napply EQ_tran with B.\napply IN_Sing_EQ; apply IN_sound_right with (Paire Vide (Sing A'));\n auto with zfc.\napply EQ_sym; apply IN_Sing_EQ;\n apply IN_sound_right with (Paire Vide (Sing A')); \n auto with zfc.\nchange (EQ (Paire Vide (Sing A')) (Paire Vide (Sing B')) -> EQ A' B') in |- *.\nintros HP; cut (EQ (Sing A') (Sing B')).\nintros; auto with zfc.\ncut (IN (Sing A') (Paire Vide (Sing B'))).\nintros HI; elim (Paire_IN Vide (Sing B') (Sing A') HI).\nintros; cut F.\nsimple induction 1.\napply not_EQ_Sing_Vide with A'; assumption.\ntrivial with zfc.\napply IN_sound_right with (Paire Vide (Sing A')); auto with zfc.\n\nQed.\n\n\n\n\n\n\n(* Here we cheat. It is easier to define the cartesian product using    *)\n(* the type theoretical product, i.e. we here use non set-theoretical   *)\n(* constructions. We could however use the usual definitions.           *)\n\n\nDefinition Prod (E E' : Ens) : Ens :=\n  match E, E' with\n  | sup A f, sup A' f' =>\n      sup _\n        (fun c : prod_t A A' =>\n         match c with\n         | pair_t a a' => Couple (f a) (f' a')\n         end)\n  end.\n\n\nHint Resolve Paire_sound_left Paire_sound_right: zfc.\n\n\nTheorem Couple_sound_left :\n forall A A' B : Ens, EQ A A' -> EQ (Couple A B) (Couple A' B).\n unfold Couple in |- *; intros; auto with zfc.\nQed.\n\nTheorem Couple_sound_right :\n forall A B B' : Ens, EQ B B' -> EQ (Couple A B) (Couple A B').\n unfold Couple in |- *; intros; auto with zfc.\nQed.\n\n\nTheorem Couple_IN_Prod :\n forall E1 E2 E1' E2' : Ens,\n IN E1' E1 -> IN E2' E2 -> IN (Couple E1' E2') (Prod E1 E2).\nsimple induction E1; intros A1 f1 r1; simple induction E2; intros A2 f2 r2.\nintros E1' E2' i1 i2.\nelim (IN_EXType (sup A1 f1) E1').\nintros x e1; simpl in x.\nelim (IN_EXType (sup A2 f2) E2').\nintros x0 e2; simpl in x.\napply IN_sound_left with (Couple (pi2 (sup A1 f1) x) (pi2 (sup A2 f2) x0));\n auto with zfc.\napply EQ_tran with (Couple (pi2 (sup A1 f1) x) E2'); auto with zfc.\napply Couple_sound_right.\nauto with zfc.\n\napply Couple_sound_left; auto with zfc.\n\nsimpl in |- *.\nsimpl in |- *.\nexists (pair_t _ _ x x0).\nsimpl in |- *.\nsplit.\nsimple induction x1; simpl in |- *.\nexists true; simpl in |- *.\nsplit.\nsimple induction x2; simpl in |- *.\nexists true; auto with zfc.\n\nexists true; auto with zfc.\n\nsimple induction y; exists true; auto with zfc.\n\nexists false; simpl in |- *.\nsplit.\nsimple induction x2.\nexists true; simpl in |- *; auto with zfc.\nsplit.\nsimple induction x3.\n\nsimple induction y.\n\nexists false; auto with zfc.\n\nsimple induction y; simpl in |- *.\nexists true; auto with zfc.\n\nexists false; auto with zfc.\n\nsimple induction y; simpl in |- *.\nexists true; auto with zfc.\n\nexists false; auto with zfc.\n\nauto with zfc.\n\nauto with zfc.\nQed.\n\n\nTheorem Couple_Prod_IN :\n forall E1 E2 E1' E2' : Ens,\n IN (Couple E1' E2') (Prod E1 E2) -> IN E1' E1 /\\ IN E2' E2.\nsimple induction E1; intros A1 f1 r1; simple induction E2; intros A2 f2 r2.\nintros E1' E2' i.\nelim (IN_EXType (Prod (sup A1 f1) (sup A2 f2)) (Couple E1' E2') i).\nintros xx; elim xx; intros a1 a2 e.\nchange (EQ (Couple E1' E2') (Couple (f1 a1) (f2 a2))) in e.\ncut (EQ E1' (f1 a1)).\ncut (EQ E2' (f2 a2)).\nintros e1 e2.\nsplit.\napply IN_sound_left with (f1 a1); auto with zfc; simpl in |- *; exists a1;\n auto with zfc.\napply IN_sound_left with (f2 a2); auto with zfc; simpl in |- *; exists a2;\n auto with zfc.\napply Couple_inj_right with (A := E1') (B := f1 a1); auto with zfc.\napply Couple_inj_left with E2' (f2 a2); auto with zfc.\nQed.\n\n\n\nTheorem IN_Prod_EXType :\n forall E E' E'' : Ens,\n IN E'' (Prod E E') ->\n EXType _ (fun A : Ens => EXType _ (fun B : Ens => EQ (Couple A B) E'')).\nsimple induction E; intros A f r; simple induction E'; intros A' f' r'.\nintros; elim (IN_EXType (Prod (sup A f) (sup A' f')) E'').\nsimple induction x.\nintros; exists (f a); exists (f' b); auto with zfc.\nauto with zfc.\nQed.\n", "meta": {"author": "coq-contribs", "repo": "zfc", "sha": "ede7126560844c381c2b021003a8dbcb0668ecad", "save_path": "github-repos/coq/coq-contribs-zfc", "path": "github-repos/coq/coq-contribs-zfc/zfc-ede7126560844c381c2b021003a8dbcb0668ecad/Cartesian.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.29255872599718435}}
{"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 Import Peano_dec.\nRequire Import Transitive_Closure.\nRequire Import Union.\nRequire Import Termes.\nRequire Import Conv.\n\n  Definition ord_norm1 := union _ subterm (transp _ red1).\n  Definition ord_norm := clos_trans _ ord_norm1.\n\n  Hint Unfold ord_norm1 ord_norm: coc.\n\n\n  Lemma subterm_ord_norm : forall a b : term, subterm a b -> ord_norm a b.\nauto 10 with coc sets.\nQed.\n\n  Hint Resolve subterm_ord_norm: coc.\n\n\n  Lemma red_red1_ord_norm :\n   forall a b : term, red a b -> forall c : term, red1 b c -> ord_norm c a.\nred in |- *.\nsimple induction 1; intros; auto with coc sets.\napply t_trans with N; auto with coc sets.\nQed.\n\n\n\n  Lemma wf_subterm : well_founded subterm.\nred in |- *.\nsimple induction a; intros; apply Acc_intro; intros.\ninversion_clear H; inversion_clear H0.\n\ninversion_clear H; inversion_clear H0.\n\ninversion_clear H1; inversion_clear H2; auto with coc sets.\n\ninversion_clear H1; inversion_clear H2; auto with coc sets.\n\ninversion_clear H1; inversion_clear H2; auto with coc sets.\nQed.\n\n\n  Lemma wf_ord_norm1 : forall t : term, sn t -> Acc ord_norm1 t.\nunfold ord_norm1 in |- *.\nintros.\napply Acc_union; auto with coc sets.\nexact commut_red1_subterm.\n\nintros.\napply wf_subterm.\nQed.\n\n\n  Theorem wf_ord_norm : forall t : term, sn t -> Acc ord_norm t.\nunfold ord_norm in |- *.\nintros.\napply Acc_clos_trans.\napply wf_ord_norm1; auto with coc sets.\nQed.\n\n\n\n\n  Definition norm_body (a : term) (norm : term -> term) :=\n    match a with\n    | Srt s => Srt s\n    | Ref n => Ref n\n    | Abs T t => Abs (norm T) (norm t)\n    | App u v =>\n        match norm u return term with\n        | Abs _ b => norm (subst (norm v) b)\n        | t => App t (norm v)\n        end\n    | Prod T U => Prod (norm T) (norm U)\n    end.\n\n  Definition compute_nf :\n   forall t : term, sn t -> {u : term | red t u &  normal u}.\nProof.\nintros.\nelimtype (Acc ord_norm t).\nclear H t.\nintros [s| n| T t| u v| T U] _ norm_rec.\nexists (Srt s); auto with coc.\nred in |- *; red in |- *; intros.\ninversion_clear H.\n\nexists (Ref n); auto with coc.\nred in |- *; red in |- *; intros.\ninversion_clear H.\n\nelim norm_rec with T; auto with coc; intros T' redT nT.\nelim norm_rec with t; auto with coc; intros t' redt nt.\nexists (Abs T' t'); auto with coc.\nred in |- *; red in |- *; intros.\ninversion_clear H.\nelim nT with M'; trivial.\nelim nt with M'; trivial.\n\nelim norm_rec with v; auto with coc; intros v' redv nv.\nelim norm_rec with u; auto with coc.\nintros [s| n| T t| a b| T U] redu nu. \nexists (App (Srt s) v'); auto with coc.\nred in |- *; red in |- *; intros.\ninversion_clear H.\ninversion_clear H0.\nelim nv with N2; trivial.\n\nexists (App (Ref n) v'); auto with coc.\nred in |- *; red in |- *; intros.\ninversion_clear H.\ninversion_clear H0.\nelim nv with N2; trivial.\n\nelim norm_rec with (subst v' t).\nintros t' redt nt.\nexists t'; trivial.\napply trans_red_red with (subst v' t); auto with coc.\napply trans_red with (App (Abs T t) v'); auto with coc.\n\napply red_red1_ord_norm with (App (Abs T t) v'); auto with coc.\n\nexists (App (App a b) v'); auto with coc.\nred in |- *; red in |- *; intros.\ninversion_clear H.\nelim nu with N1; trivial.\nelim nv with N2; trivial.\n\nexists (App (Prod T U) v'); auto with coc.\nred in |- *; red in |- *; intros.\ninversion_clear H.\nelim nu with N1; trivial.\nelim nv with N2; trivial.\n\nelim norm_rec with T; auto with coc; intros T' redT nT.\nelim norm_rec with U; auto with coc; intros U' redU nU.\nexists (Prod T' U'); auto with coc.\nred in |- *; red in |- *; intros.\ninversion_clear H.\nelim nT with N1; trivial.\nelim nU with N2; trivial.\n\napply wf_ord_norm; auto with coc.\nDefined.\n\n  Definition eqterm : forall u v : term, {u = v} + {u <> v}.\nProof.\ndecide equality.\ndecide equality.\napply eq_nat_dec.\nDefined.\n\n\n\n  Definition is_conv :\n   forall u v : term, sn u -> sn v -> {conv u v} + {~ conv u v}.\nProof.\nintros u v snu snv.\nelim compute_nf with (1 := snu); intros u' redu nu.\nelim compute_nf with (1 := snv); intros v' redv nv.\nelim eqterm with u' v'; [ intros same_nf | intros diff_nf ].\nleft.\napply trans_conv_conv with u'; auto with coc.\nrewrite same_nf; apply sym_conv; auto with coc.\n\nright; red in |- *; intro; apply diff_nf.\nelim church_rosser with u' v'; auto with coc; intros.\nrewrite (red_normal u' x); auto with coc.\nrewrite (red_normal v' x); auto with coc.\n\napply trans_conv_conv with v; auto with coc.\napply trans_conv_conv with u; auto with coc.\napply sym_conv; auto with coc.\nDefined.", "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/Conv_Dec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.29255871809326817}}
{"text": "(** Beginning of the file for GV definitions as described in\n\n    Philip Wadler. 2012. Propositions as sessions. In Proceedings of the 17th\n    ACM SIGPLAN international conference on Functional programming (ICFP '12).\n    ACM, New York, NY, USA, 273-286. DOI=10.1145/2364527.2364568\n    http://doi.acm.org/10.1145/2364527.2364568\n\n    which is based on ``Classic GV'' by Simon Gay and Vasco Vasconcelos in\n\n    Simon J. Gay and Vasco T. Vasconcelos. 2010. Linear type theory for\n    asynchronous session types. J. Funct. Program. 20, 1 (January 2010),19-50.\n    DOI=10.1017/S0956796809990268 http://dx.doi.org/10.1017/S0956796809990268\n\n*)\nRequire Import Metatheory Coq.Program.Tactics Program.Equality.\nSet Implicit Arguments.\n\n(** The notion of kind is borrowed from\n\n    Karl Mazurak, Jianzhou Zhao, and Steve Zdancewic. 2010. Lightweight linear\n    types in system f°. In Proceedings of the 5th ACM SIGPLAN workshop on\n    Types in language design and implementation (TLDI '10). ACM, New York, NY,\n    USA, 77-88. DOI=10.1145/1708016.1708027\n    http://doi.acm.org/10.1145/1708016.1708027\n\n    but there is no subsumption rule here. In other words, kinds are just a\n    mechanism by which to classify types. The rationale for including kinds is\n    to allow a later extension to a System F-pop inspired language.\n\n    In lemmas and theorems, k is used to range over kinds.\n*)\nInductive kind : Set :=\n  | lin : kind (* linear *)\n  | un : kind (* unlimited *).\n\n(** [typ] is ranged over by T, U and V. It differs slightly from the\n    definition given in Wadler's paper in the following ways:\n\n      * Session types are defined within this inductive type rather than\n        mutually; a technical convenience since Coq mutually inductive\n        types can be tricky to manipulate,\n      * Choice and branch are binary; this matches the intuition of tensor\n        product which is defined as binary and also maps better to the CP\n        with and plus constructs which are also binary\n*)\nInductive typ : Set :=\n(* Session types section *)\n  | typ_soutput : typ -> typ -> typ\n  | typ_sinput : typ -> typ -> typ\n  | typ_schoice : typ -> typ -> typ\n  | typ_sbranch : typ -> typ -> typ\n  | typ_oend : typ (* output end *)\n  | typ_iend : typ (* input end *)\n(* Other non-session GV types *)\n  | typ_tensor :  typ -> typ -> typ\n  | typ_labs : typ -> typ -> typ\n  | typ_abs : typ -> typ -> typ\n  | typ_unit : typ (* always unlimited *).\n\n(** The notation for sessions has been altered from the standard presentation\n    to fit within allowable notations in Coq.\n*)\nNotation \"'!' T '#' S\" := (typ_soutput T S) (at level 68,\n                                             right associativity) : gv_scope.\nNotation \"'?' T '#' S\" := (typ_sinput T S) (at level 68, right associativity).\nNotation \"S1 '<+>' S2\" := (typ_schoice S1 S2) (at level 68,\n                                               right associativity)\n                                              : gv_scope.\nNotation \"S1 <&> S2\" := (typ_sbranch S1 S2) (at level 68,\n                                             right associativity) : gv_scope.\nNotation \"T ⊸ U\" := (typ_labs T U) (at level 68, right associativity)\n                                   : gv_scope.\nNotation \"T ⟶ U\" := (typ_abs T U) (at level 68, right associativity)\n                                  : gv_scope.\nNotation \"T <x> U\" := (typ_tensor T U) (at level 68, right associativity)\n                                     : gv_scope.\nDelimit Scope gv_scope with gv.\nOpen Scope gv_scope.\n\n(** [ty] as defined above is more general than the types handled by GV; the\n    types are considered session types and so could, for example, appear in\n    branch or choice constructs (e.g. a regular function type). To prevent\n    this, a predicate [is_session] is defined over [typ] constructors to\n    restrict where certain constructors may occur.\n\n    S range over session types.\n*)\nInductive is_session : typ -> Prop :=\n  | is_output : forall (T: typ) S\n                       (IS: is_session S),\n                  is_session (! T # S)\n  | is_input : forall (T: typ) S\n                      (IS: is_session S),\n                 is_session (? T # S)\n  | is_choice : forall S1 S2 (IS1: is_session S1) (IS2: is_session S2),\n                  is_session (S1 <+> S2)\n  | is_branch : forall S1 S2 (IS1: is_session S1) (IS2: is_session S2),\n                  is_session (S1 <&> S2)\n  | is_oend : is_session typ_oend\n  | is_iend : is_session typ_iend.\n\nHint Constructors is_session.\n\n(** Well-formed types are types with the correct kind annotations. *)\nInductive wf_typ : typ -> kind -> Prop :=\n(* Session types section *)\n  | wf_output : forall k T S (WFT: wf_typ T k) (WFS: wf_typ S lin)\n                       (IS: is_session S),\n                  wf_typ (! T # S) lin\n  | wf_input : forall k T S (WFT: wf_typ T k) (WFS: wf_typ S lin)\n                      (IS: is_session S),\n                 wf_typ (? T # S) lin\n  | wf_choice : forall S1 S2 (WFS1: wf_typ S1 lin) (WFS2: wf_typ S2 lin)\n                       (IS1: is_session S1) (IS2: is_session S2),\n                  wf_typ (S1 <+> S2) lin\n  | wf_branch : forall S1 S2 (WFS1: wf_typ S1 lin) (WFS2: wf_typ S2 lin)\n                       (IS1: is_session S1) (IS2: is_session S2),\n                  wf_typ (S1 <&> S2) lin\n  | wf_oend : wf_typ typ_oend lin (* output end *)\n  | wf_iend : wf_typ typ_iend lin (* input end *)\n(* Other non-session GV types *)\n  | wf_tensor : forall kt ku T U (WFT: wf_typ T kt) (WFU: wf_typ U ku),\n                  wf_typ (T <x> U) lin\n  | wf_labs : forall kt ku T U (WFT: wf_typ T kt) (WFU: wf_typ U ku),\n                wf_typ (T ⊸ U) lin\n  | wf_abs : forall kt ku T U (WFT: wf_typ T kt) (WFU: wf_typ U ku),\n               wf_typ (T ⟶ U) un\n  | wf_unit : wf_typ typ_unit un.\n\nHint Constructors wf_typ.\n\n(** Define a duality relation on session types to specify that two session\n    types are dual to each other.\n\n    The computational view of duality cannot be used in the well-typed term\n    relation because the proof of duality cannot be inferred for an arbitrary\n    session type argument.\n*)\nInductive are_dual : typ -> typ -> Prop :=\n  | output_dual : forall k T (WFT: wf_typ T k) S S' (DU: are_dual S S'),\n                    are_dual (! T # S) (? T # S')\n  | input_dual : forall k T (WFT: wf_typ T k) S S' (DU: are_dual S S'),\n                   are_dual (? T # S) (! T # S')\n  | choice_dual : forall S1 S2 S1' S2'\n                         (DU1: are_dual S1 S1') (DU2: are_dual S2 S2'),\n                    are_dual (S1 <+> S2) (S1' <&> S2')\n  | branch_dual : forall S1 S2 S1' S2'\n                         (DU1: are_dual S1 S1') (DU2: are_dual S2 S2'),\n                    are_dual (S1 <&> S2) (S1' <+> S2')\n  | oend_dual : are_dual typ_oend typ_iend\n  | iend_dual : are_dual typ_iend typ_oend.\n\nHint Constructors are_dual.\n\n(** Only called on a session type. *)\nFixpoint dual_session (T:typ) :=\n  match T with\n    | ! A # B => ? A # (dual_session B)\n    | ? A # B => ! A # (dual_session B)\n    | A <+> B => (dual_session A) <&> (dual_session B)\n    | A <&> B => (dual_session A) <+> (dual_session B)\n    | typ_iend => typ_oend\n    | typ_oend => typ_iend\n    | _ => T\n  end.\n\n(** Define a label type for binary branch and choice. *)\nInductive label : Set :=\n  | lb_inr : label\n  | lb_inl : label.\n\nInductive var : Set :=\n  | bvar : nat -> var\n  | fvar : atom -> var.\n\nCoercion bvar : nat >-> var.\nCoercion fvar : atom >-> var.\n\n(** Define the terms of GV. We follow the approach in the UPenn Metatheory\n    library, defining free variables as atoms and bound variables as de\n    Bruijn indices.\n\n*)\nInductive term : Set :=\n  | tm_var : var -> term\n  | tm_unit : term\n  | tm_weak : var -> term -> term\n  | tm_abs : typ -> term -> term\n  | tm_iabs : term -> term (* introduction rule for unlimited abstraction. *)\n  | tm_eabs : term -> term (* elimination rule for unlimited abstraction. *)\n  | tm_app : term -> term -> term\n  | tm_pair : term -> term -> term\n  | tm_let : typ -> typ -> term -> term -> term\n  | tm_send : term -> term -> term\n  | tm_recv : term -> term\n  | tm_select : label -> term -> term\n  | tm_case : term -> term -> term -> term\n  | tm_connect : typ -> term -> term -> term\n  | tm_end : term -> term.\n\nCoercion tm_var : var >-> term.\n\nNotation \"λ! M\" := (tm_iabs M) (at level 68, right associativity) : gv_scope.\nNotation \"λ? M\" := (tm_eabs M) (at level 68, right associativity) : gv_scope.\n\n(** In the style of ``Engineering Formal Metatheory'' we define\n    substitution of expressions for atoms and opening of expressions with\n    bound variables.\n*)\n\n\n(** The following definition of substitution for a free variable assumes the\n    term to be substituted is locally closed.\n*)\nFixpoint subst (x: atom) (u: term) (t: term) : term :=\n  match t with\n  | tm_var (fvar y) => if x == y then u else (tm_var y)\n  | tm_weak v m => tm_weak v (subst x u m)\n  | tm_abs T b => tm_abs T (subst x u b)\n  | tm_iabs M => tm_iabs (subst x u M)\n  | tm_eabs M => tm_eabs (subst x u M)\n  | tm_app m n => tm_app (subst x u m) (subst x u n)\n  | tm_pair p q => tm_pair (subst x u p) (subst x u q)\n  | tm_let T U m n => tm_let T U (subst x u m) (subst x u n)\n  | tm_send m n => tm_send (subst x u m) (subst x u n)\n  | tm_recv m => tm_recv (subst x u m)\n  | tm_select l m => tm_select l (subst x u m)\n  | tm_case m nl nr\n    => tm_case (subst x u m) (subst x u nl) (subst x u nr)\n  | tm_connect T m n => tm_connect T (subst x u m) (subst x u n)\n  | tm_end m => tm_end (subst x u m)\n  | _ => t\n  end.\n\nNotation \"[ x ~> u ] t\" := (subst x u t) (at level 68) : gv_scope.\n\n(** Opening a term t is replacing an unbound variable with index k with term\n    u. Assume u is locally closed and is only substituted once if it contains\n    free variables.\n*)\nFixpoint open_rec (k: nat) (u: term) (t: term) :=\n  match t with\n  | tm_var (bvar n) => if k == n then u else (tm_var n)\n  | tm_weak v m => tm_weak v (open_rec k u m)\n  | tm_abs T b => tm_abs T (open_rec (S k) u b)\n  | tm_iabs M => tm_iabs (open_rec k u M)\n  | tm_eabs M => tm_eabs (open_rec k u M)\n  | tm_app m n => tm_app (open_rec k u m) (open_rec k u n)\n  | tm_pair p q => tm_pair (open_rec k u p) (open_rec k u q)\n  | tm_let T U m n\n    => tm_let T U (open_rec k u m) (open_rec (S (S k)) u n)\n  | tm_send m n => tm_send (open_rec k u m) (open_rec k u n)\n  | tm_recv m => tm_recv (open_rec k u m)\n  | tm_select l m => tm_select l (open_rec k u m)\n  | tm_case m nl nr\n    => tm_case (open_rec k u m) (open_rec (S k) u nl) (open_rec (S k) u nr)\n  | tm_connect T m n\n    => tm_connect T (open_rec (S k) u m) (open_rec (S k) u n)\n  | tm_end m => tm_end (open_rec k u m)\n  | _ => t\n  end.\n\nNotation \"{ k ~> u } t\" := (open_rec k u t) (at level 68,\n                                             right associativity) : gv_scope.\n\n(** Opening a term t is replacing the unbound variable with index 0 with term\n    u. Assume u is locally closed and is only substituted once if it contains\n    free variables.\n*)\nDefinition open t u := open_rec 0 u t.\n\nHint Unfold open.\n\nFixpoint GVFV (t: term) :=\n  match t with\n  | tm_var (fvar y) => singleton y\n  | tm_weak (fvar y) m => singleton y `union` GVFV m\n  | tm_weak _ m => GVFV m\n  | tm_abs T b => GVFV b\n  | tm_iabs m => GVFV m\n  | tm_eabs m => GVFV m\n  | tm_app m n => GVFV m `union` GVFV n\n  | tm_pair p q => GVFV p `union` GVFV q\n  | tm_let T U m n => GVFV m `union` GVFV n\n  | tm_send m n => GVFV m `union` GVFV n\n  | tm_recv m => GVFV m\n  | tm_select l m => GVFV m\n  | tm_case m nl nr => GVFV m `union` GVFV nl `union` GVFV nr\n  | tm_connect T m n => GVFV m `union` GVFV n\n  | tm_end m => GVFV m\n  | _ => empty\n  end.\n\n(** A locally closed term has no unbounded variables. Note also using\n    cofinite quantification with binding constructs. *)\nInductive lc : term -> Prop :=\n  | lc_var : forall (x:atom), lc (tm_var x)\n  | lc_unit : lc tm_unit\n  | lc_weak : forall (x:atom) M (MLC: lc M), lc (tm_weak x M)\n  | lc_abs : forall (L:atoms) k T M\n                    (WFT: wf_typ T k)\n                    (CO: forall (x:atom), x `notin` L -> lc (open M x)),\n               lc (tm_abs T M)\n  | lc_app : forall M N (MLC: lc M) (NLC: lc N), lc (tm_app M N)\n  | lc_iabs : forall M (MLC: lc M), lc (λ! M)\n  | lc_eabs : forall M (MLC: lc M), lc (λ? M)\n  | lc_pair : forall M N (MLC: lc M) (NLC: lc N), lc (tm_pair M N)\n  | lc_let : forall (L:atoms) T U M N\n                    (WF: wf_typ (T <x> U) lin)\n                    (MLC: lc M)\n                    (NCO: forall (x y:atom)\n                                 (XL: x `notin` L)\n                                 (YL: y `notin` L `union` singleton x),\n                            lc ({1 ~> x} (open N y))),\n               lc (tm_let T U M N)\n  | lc_send : forall M N (MLC: lc M) (NLC: lc N), lc (tm_send M N)\n  | lc_recv : forall M (MLC: lc M), lc (tm_recv M)\n  | lc_select : forall lbl M (LCM: lc M), lc (tm_select lbl M)\n  | lc_case : forall (L:atoms) M NL NR (MLC: lc M)\n                     (NLCO: forall (x:atom), x `notin` L -> lc (open NL x))\n                     (NRCO: forall (x:atom), x `notin` L -> lc (open NR x)),\n                lc (tm_case M NL NR)\n  | lc_connect : forall (L:atoms) T M N\n                        (WFT: wf_typ T lin)\n                        (MCO: forall (x:atom), x `notin` L -> lc (open M x))\n                        (NCO: forall (x:atom), x `notin` L -> lc (open N x)),\n                   lc (tm_connect T M N)\n  | lc_end : forall M (MLC: lc M), lc (tm_end M).\n\nHint Constructors lc.\n\n(** Typing environments are lists of (atom,typ) pairs. *)\nDefinition tenv := list (atom * typ).\n\nDefinition un_env (G : tenv) : Prop :=\n  forall x (IN: x `in` dom G),\n    exists T, wf_typ T un /\\ binds x T G.\n\n(** To get Coq to accept the '~' notation used here, we need to make sure t\n    and T are parsed as identifiers.\n\n    Reserved Notation \"G |- t ~ T\" (at level 68, t ident, T ident).\n\n    Inductive wt_tm : tenv -> term -> forall k, typ k -> Prop :=\n      | wt_tm_unid : forall x T, (x ~ inr T) |- x ~ T\n    where \"G '|-' t ~ T\" := (wt_tm G t T) : gv_scope.\n\n    However, I'm going to adopt the ∈ notation below since it will be easier\n    to differentiate between the environment notation.\n*)\nReserved Notation \"Φ ⊢ t ∈ T\" (at level 69).\n\nInductive wt_tm : tenv -> term -> typ -> Prop :=\n  | wt_tm_id : forall k T x (WFT: wf_typ T k), x ~ T ⊢ x ∈ T\n  | wt_tm_unit : nil ⊢ tm_unit ∈ typ_unit\n  | wt_tm_weaken : forall Φ x N k T U\n                          (WFT: wf_typ T un) (WFU: wf_typ U k)\n                          (UN: uniq (x ~ T ++ Φ))\n                          (WT: Φ ⊢ N ∈ U),\n                     x ~ T ++ Φ ⊢ (tm_weak x N) ∈ U\n  | wt_tm_labs : forall (L: atoms) Φ T U M\n                        (WF: wf_typ (T ⊸ U) lin)\n                        (UN: uniq Φ)\n                        (WT: forall (x:atom),\n                               x `notin` L ->\n                               x ~ T ++ Φ ⊢ (open M x) ∈ U),\n                   Φ ⊢ tm_abs T M ∈ T ⊸ U\n  | wt_tm_lapp : forall Φ Ψ T U M N\n                        (WF: wf_typ (T ⊸ U) lin)\n                        (UN: uniq (Φ ++ Ψ))\n                        (WTM: Φ ⊢ M ∈ T ⊸ U) (WTN: Ψ ⊢ N ∈ T),\n                   Φ ++ Ψ ⊢ (tm_app M N) ∈ U\n  | wt_tm_iabs : forall Φ T U M\n                       (WF: wf_typ (T ⟶ U) un)\n                       (UN: uniq Φ)\n                       (WT: Φ ⊢ M ∈ T ⊸ U) (UL: un_env Φ),\n                  Φ ⊢ λ! M ∈ T ⟶ U\n  | wt_tm_eabs : forall Φ T U M\n                       (WF: wf_typ (T ⊸ U) lin)\n                       (UN: uniq Φ)\n                       (WT: Φ ⊢ M ∈ T ⟶ U),\n                  Φ ⊢ λ? M ∈ T ⊸ U\n  | wt_tm_pair : forall Φ Ψ T U M N\n                        (WF: wf_typ (T <x> U) lin)\n                        (UN: uniq (Φ ++ Ψ))\n                        (WTM: Φ ⊢ M ∈ T) (WTN: Ψ ⊢ N ∈ U),\n                   Φ ++ Ψ ⊢ (tm_pair M N) ∈ T <x> U\n  | wt_tm_let :\n      forall (L:atoms) Φ Ψ kv T U V M N\n             (WF: wf_typ (T <x> U) lin) (WFV: wf_typ V kv)\n             (UN: uniq (Φ ++ Ψ))\n             (WTM: Φ ⊢ M ∈ T <x> U)\n             (WTN: forall (x y:atom)\n                          (XL: x `notin` L)\n                          (YL: y `notin` L `union` singleton x),\n                     x ~ T ++ y ~ U ++ Ψ ⊢ ({1 ~> x} (open N y)) ∈ V),\n        Φ ++ Ψ ⊢ (tm_let T U M N) ∈ V\n  | wt_tm_send : forall Φ Ψ M T N S\n                        (WF: wf_typ (! T # S) lin)\n                        (UN: uniq (Φ ++ Ψ))\n                        (WTM: Φ ⊢ M ∈ T) (WTN: Ψ ⊢ N ∈ ! T # S),\n                   Φ ++ Ψ ⊢ tm_send M N ∈ S\n  | wt_tm_recv : forall Φ M T S\n                        (WF: wf_typ (? T # S) lin)\n                        (UN: uniq Φ)\n                        (WT: Φ ⊢ M ∈ ? T # S),\n                   Φ ⊢ tm_recv M ∈ typ_tensor T S\n  | wt_tm_l_select : forall Φ M S1 S2 (UN: uniq Φ)\n                            (WF: wf_typ (S1 <+> S2) lin)\n                            (WT: Φ ⊢ M ∈ (S1 <+> S2)),\n                       Φ ⊢ tm_select lb_inl M ∈ S1\n  | wt_tm_r_select : forall Φ M S1 S2\n                            (UN: uniq Φ)\n                            (WF: wf_typ (S1 <+> S2) lin)\n                            (WT: Φ ⊢ M ∈ (S1 <+> S2)),\n                       Φ ⊢ tm_select lb_inr M ∈ S2\n  | wt_tm_case : forall (L:atoms) Φ Ψ M NL NR S1 S2 kt T\n                        (UN: uniq (Φ ++ Ψ))\n                        (WF: wf_typ (S1 <&> S2) lin)\n                        (WFT: wf_typ T kt)\n                        (WTM: Φ ⊢ M ∈ (S1 <&> S2))\n                        (WTNL: forall (x:atom) (NLH: x `notin` L),\n                                 x ~ S1 ++ Ψ ⊢ (open NL x) ∈ T)\n                        (WTNR: forall (x:atom) (NL: x `notin` L),\n                                 x ~ S2 ++ Ψ ⊢ (open NR x) ∈ T),\n                   Φ ++ Ψ ⊢ (tm_case M NL NR) ∈ T\n  | wt_tm_connect : forall (L:atoms) Φ Ψ M N S S' kt T\n                           (UN: uniq (Φ ++ Ψ))\n                           (DU: are_dual S S')\n                           (WF: wf_typ T kt)\n                           (WTM: forall (x:atom) (NL: x `notin` L),\n                                   x ~ S ++ Φ ⊢ (open M x) ∈ typ_oend)\n                           (WTN: forall (x:atom) (NL: x `notin` L),\n                                   x ~ S' ++ Ψ ⊢ (open N x) ∈ T),\n                      Φ ++ Ψ ⊢ (tm_connect S M N) ∈ T\n  | wt_tm_end : forall Φ M\n                       (UN: uniq Φ)\n                       (WT: Φ ⊢ M ∈ typ_iend),\n                  Φ ⊢ tm_end M ∈ typ_unit\nwhere \"Φ ⊢ t ∈ T\" := (wt_tm Φ t T) : gv_scope.\n\nHint Constructors wt_tm.\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/msci/GV_Definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.5, "lm_q1q2_score": 0.29255058433636155}}
{"text": "Require Import VST.msl.msl_direct.\nRequire Import FunctionalExtensionality.\nRequire Import RamifyCoq.msl_ext.ramify_tactics.\nRequire Import RamifyCoq.msl_ext.overlapping_direct.\nRequire Import RamifyCoq.heap_model_direct.SeparationAlgebra.\n\nDefinition mapsto (x y: adr) : pred world :=\n  fun w => x <> 0 /\\\n    (forall a, a <> x -> lookup_fpm w a = None) /\\\n    lookup_fpm w x = Some y.\n\nLemma join_sub_mapsto: forall w1 w2 x y, join_sub w1 w2 -> (mapsto x y * TT)%pred w1 -> (mapsto x y * TT)%pred w2.\nProof.\n  intros. destruct_sepcon H0 h. destruct H as [w3 ?]. try_join h2 w3 m. exists h1, m. split; auto.\nQed.\n\nLemma mapsto_unique: forall x a b w, ~ (mapsto x a * mapsto x b)%pred w.\nProof.\n  repeat intro. destruct_sepcon H h. destruct H0 as [? [? ?]]. destruct H1 as [? [? ?]]. destruct h1 as [f1 m1].\n  destruct h2 as [f2 m2]. destruct w as [fw mw]. hnf in *. simpl in *. specialize (H x). rewrite H3 in *. rewrite H5 in *.\n  inversion H. inversion H9.\nQed.\n\nLemma mapsto__precise: forall p, precise (EX  v : adr, mapsto p v).\nProof.\n  intros.\n  repeat intro.\n  destruct H1 as [w3 ?], H2 as [w4 ?]; destruct H as [? [? [? ?]]], H0 as [? [? [? ?]]].\n  destruct w1 as [v1 f1]; destruct w2 as [v2 f2]; destruct w3 as [v3 f3]; destruct w4 as [v4 f4]; destruct w as [v f].\n  hnf in H1, H2; simpl in *. apply exist_ext. extensionality mm. destruct (eq_dec mm p).\n  + subst. specialize (H1 p). specialize (H2 p). rewrite H4 in *. rewrite H6 in *. inversion H1.\n    - subst. inversion H2.\n      * rewrite H10, H12. auto.\n      * subst. rewrite <- H8 in H2. rewrite <- H11 in H2. hnf in H2. inversion H2. subst. inversion H15.\n    - subst. rewrite <- H8 in H1. rewrite <- H9 in H1. hnf in H1. inversion H1. subst. inversion H13.\n  + specialize (H3 mm n). specialize (H5 mm n). rewrite H3, H5. auto.\nQed.\n\nLemma mapsto_conflict: forall p1 p2 v1 v2, p1 = p2 -> mapsto p1 v1 * mapsto p2 v2 |-- FF.\nProof.\n  intros.\n  subst.\n  intro w. apply mapsto_unique.\nQed.\n\nLemma disj_mapsto_: forall p1 p2, p1 <> p2 -> disjointed (EX v1: adr, mapsto p1 v1) (EX v2: adr, mapsto p2 v2).\nProof.\n  intros.\n  hnf. intros. destruct H2 as [v1 ?]. destruct H3 as [v2 ?].\n  generalize H2; intro Hx. generalize H3; intro Hy.\n  destruct h12 as [f12 x12] eqn:? . hnf in H2. simpl in H2. destruct H2 as [? [? ?]].\n  destruct h23 as [f23 x23] eqn:? . hnf in H3. simpl in H3. destruct H3 as [? [? ?]].\n  remember (fun xx : adr => if eq_nat_dec xx p1 then Some v1 else (if eq_nat_dec xx p2 then Some v2 else None)) as f.\n  assert (finMap f). {\n    exists (p1 :: p2 :: nil). intro z. intros. rewrite Heqf. destruct (eq_nat_dec z p1).\n    + subst. exfalso. apply H8. apply in_eq.\n    + destruct (eq_nat_dec z p2).\n      - subst. exfalso. apply H8. apply in_cons, in_eq.\n      - trivial.\n  } remember (exist (finMap (B:=adr)) f H8) as ff.\n  assert (join h12 h23 ff). {\n    rewrite Heqw, Heqw0, Heqff. hnf; simpl. rewrite Heqf. intro z. destruct (eq_nat_dec z p1).\n    + rewrite e in *. rewrite H5. generalize (H6 p1 H); intro HS. rewrite HS. constructor.\n    + destruct (eq_nat_dec z p2).\n      - rewrite e in *. rewrite H7. generalize (H4 p2 n); intro HS. rewrite HS. constructor.\n      - specialize (H4 z n). specialize (H6 z n0). rewrite H4, H6. constructor.\n  } rewrite <- Heqw0 in *. rewrite <- Heqw in *.\n  assert (emp h2). {\n    apply join_sub_joins_identity with h23.\n    + exists h3; auto.\n    + try_join h2 h23 t. exists t; auto.\n  } elim_emp_direct.\n  split; auto. exists ff; auto.\nQed.\n\nLemma mapsto_inj: forall p v1 v2, mapsto p v1 && mapsto p v2 |-- !! (v1 = v2).\nProof.\n  intros; simpl; intro w; intros. destruct H.\n  destruct H as [? [? ?]]. destruct H0 as [? [? ?]]. rewrite H2 in H4.\n  inversion H4. subst; 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/heap_model_direct/mapsto.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2925505771016156}}
{"text": "(** * Mutable map whose lookup operation provides a default value.*)\n\n(* begin hide *)\nSet Implicit Arguments.\nSet Contextual Implicit.\n\nFrom Coq Require Import Morphisms.\n\nFrom ExtLib Require Import\n     Core.RelDec.\n\nFrom ExtLib.Structures Require\n     Maps.\n\nFrom Paco Require Import paco.\n\nFrom ITree Require Import\n     Basics.HeterogeneousRelations\n     ITree\n     ITreeFacts\n     Eq.Paco2\n     Events.State\n     Events.StateFacts\n     Events.MapDefault.\n\nImport ITree.Basics.Basics.Monads.\nImport Structures.Maps.\n(* end hide *)\n\nSection MapFacts.\n\n  Variables (K V : Type).\n  Context {map : Type}.\n  Context {M : Map K V map}.\n  Context {MOk: MapOk eq M}.\n  Context {Kdec: @RelDec K eq}.\n  Context {KdecOk: RelDec_Correct Kdec}.\n\n  (* Should move to extlib *)\n  Lemma lookup_add_eq: forall k v s, lookup k (add k v s) = Some v.\n  Proof.\n    intros.\n    rewrite mapsto_lookup; apply mapsto_add_eq. \n    Unshelve.\n    2: typeclasses eauto.\n  Qed.\n\n  (* Should move to extlib *)\n  Lemma lookup_add_neq: forall k k' v s, k' <> k -> lookup k (add k' v s) = lookup k s.\n  Proof.\n    intros.\n    generalize (@mapsto_add_neq _ _ _ eq _ _ s k' v k H); clear H; intros H.\n    setoid_rewrite <- mapsto_lookup in H.\n    destruct (lookup k s) as [v' |] eqn:EQ.\n    - specialize (H v').\n      apply H; auto.\n    - destruct (lookup k (add k' v s)) as [v' |] eqn:EQ'; [| reflexivity].\n      specialize (H v').\n      symmetry; apply H; auto.\n  Qed.\n\n  (* Should move to extlib *)\n  Lemma lookup_remove_eq:\n    forall k s, lookup k (remove k s) = None.\n  Proof.\n    intros.\n    match goal with\n      |- ?x = _ => destruct x eqn:EQ\n    end; [| reflexivity].\n    rewrite mapsto_lookup in EQ.\n    exfalso; eapply mapsto_remove_eq; eauto.\n  Qed.\n\n  (* Should move to extlib *)\n  Lemma lookup_remove_neq:\n    forall k k' s, k <> k' -> lookup k (remove k' s) = lookup k s.\n  Proof.\n    intros.\n    match goal with\n      |- ?x = _ => destruct x eqn:EQ\n    end.\n    - rewrite mapsto_lookup in EQ.\n      apply mapsto_remove_neq in EQ; auto.\n      symmetry; rewrite mapsto_lookup; eauto.\n    -  match goal with\n         |- _ = ?x => destruct x eqn:EQ'\n       end; auto.\n       rewrite mapsto_lookup in EQ'.\n       eapply mapsto_remove_neq in EQ'; eauto.\n       rewrite <- mapsto_lookup in EQ'.\n       rewrite EQ in EQ'; inv EQ'.\n       Unshelve.\n       all: typeclasses eauto.\n  Qed.\n\n  Global Instance eq_map_refl {d} : Reflexive (@eq_map _ _ _ _ d).\n  Proof.\n    red. intros. unfold eq_map. tauto.\n  Qed.    \n\n  Global Instance eq_map_sym {d} : Symmetric (@eq_map _ _ _ _ d).\n  Proof.\n    repeat intro.\n    unfold eq_map in H.\n    rewrite H.\n    reflexivity.\n  Qed.\n\n  Global Instance eq_map_trans {d} : Transitive (@eq_map _ _ _ _ d).\n  Proof.\n    repeat intro. \n    unfold eq_map in *.\n    rewrite H. rewrite H0. reflexivity.\n  Qed.\n\n\n  Section Relations.\n  Context {R1 R2 : Type}.\n  Variable RR : R1 -> R2 -> Prop.\n\n  Definition map_default_eq d {E} \n    : (stateT map (itree E) R1) -> (stateT map (itree E) R2) -> Prop :=\n    fun t1 t2 => forall s1 s2, (@eq_map _ _ _ _ d) s1 s2 -> eutt (prod_rel (@eq_map _ _ _ _ d) RR) (t1 s1) (t2 s2).\n\n  End Relations.\n\n  Lemma eq_map_add:\n    forall (d : V) (s1 s2 : map) (k : K) (v : V), (@eq_map _ _ _ _ d) s1 s2 -> (@eq_map _ _ _ _ d) (add k v s1) (add k v s2).\n  Proof.\n    intros d s1 s2 k v H.\n    unfold eq_map in *.\n    intros k'.\n    destruct (rel_dec_p k k').\n    - subst.\n      unfold lookup_default in *.\n      rewrite 2 lookup_add_eq; reflexivity.\n    - unfold lookup_default in *.\n      rewrite 2 lookup_add_neq; auto.\n  Qed.      \n\n  Lemma eq_map_remove:\n    forall (d : V) (s1 s2 : map) (k : K), (@eq_map _ _ _ _ d) s1 s2 -> (@eq_map _ _ _ _ d) (remove k s1) (remove k s2).\n  Proof.\n    intros d s1 s2 k H.\n    unfold eq_map in *; intros k'.\n    unfold lookup_default.\n    destruct (rel_dec_p k k').\n    - subst; rewrite 2 lookup_remove_eq; auto.\n    - rewrite 2 lookup_remove_neq; auto.\n      apply H.\n  Qed.\n  \n  Lemma handle_map_eq : \n    forall d E X (s1 s2 : map) (m : mapE K d X),\n      (@eq_map _ _ _ _ d) s1 s2 ->\n      eutt (prod_rel (@eq_map _ _ _ _ d) eq) (handle_map m s1) ((handle_map m s2) : itree E (map * X)).\n  Proof.\n    intros.\n    destruct m; cbn; red; apply eqit_Ret; constructor; cbn; auto.\n    - apply eq_map_add. assumption.\n    - apply eq_map_remove. assumption.\n  Qed.\n\n\n  Global Instance Proper_handle_map {E R}  d :\n    Proper (eq ==> map_default_eq eq d) (@handle_map _ _ _ _ E d R).\n  Proof.\n    repeat intro.\n    subst.\n    apply handle_map_eq.\n    assumption.\n  Qed.\n    \n  \n  (* This lemma states that the operations provided by [handle_map] respect\n     the equivalence on the underlying map interface *)\n  Lemma interp_map_id d {E X} (t : itree (mapE K d +' E) X) :\n    map_default_eq eq d (interp_map t) (interp_map t).\n  Proof.\n    unfold map_default_eq, interp_map; intros.\n    revert t s1 s2 H.\n    ginit.\n    pcofix CH.\n    intros.\n    repeat rewrite unfold_interp_state. unfold _interp_state.\n    destruct (observe t).\n    - gstep. constructor. constructor; auto.\n    - gstep. constructor. gbase. apply CH. assumption.\n    - guclo eqit_clo_bind. econstructor.\n      unfold pure_state.\n      destruct e.\n      + cbn. eapply eqit_mon; [ exact (fun x => x) .. | | apply handle_map_eq; assumption ].\n        auto. auto. intros.  apply PR.\n      + cbn. apply eqit_Vis. intros.  apply eqit_Ret. constructor; auto.\n      + intros. destruct u1. destruct u2. cbn.\n        destruct H as [H1 H2]; cbn in H1, H2; subst.\n        gstep; constructor.\n        gbase. apply CH. assumption.\n  Qed.\n \n  Global Instance interp_map_proper {R E d} {RR : R -> R -> Prop} :\n    Proper ((eutt RR) ==> (@map_default_eq _ _ RR d E)) (@interp_map _ _ _ _ E d R).\n  Proof.\n    unfold map_default_eq, interp_map.\n    repeat intro.\n    revert x y H s1 s2 H0.\n    einit.\n    ecofix CH.\n    intros.\n    rewrite! unfold_interp_state. \n    punfold H0. red in H0.\n    revert s1 s2 H1.\n    induction H0; intros; subst; simpl; pclearbot.\n    - eret. \n    - etau.\n    - ebind.\n      apply pbc_intro_h with (RU := prod_rel (@eq_map _ _ _ _ d) eq).\n      { (* SAZ: I must be missing some lemma that should solve this case *)\n        unfold case_. unfold Case_sum1, case_sum1.\n        destruct e. apply handle_map_eq. assumption.\n        unfold pure_state.\n        pstep. econstructor. intros. constructor. pfold. econstructor. constructor; auto.\n      } \n      intros. destruct H as [HH1 ->].\n      estep; constructor. ebase.\n    - rewrite tau_euttge, unfold_interp_state.\n      eauto.\n    - rewrite tau_euttge, unfold_interp_state.\n      eauto.\n  Qed.\n\nEnd MapFacts.\n", "meta": {"author": "DeepSpec", "repo": "InteractionTrees", "sha": "8e28e2ee08496c696e03916a22d93c39559a9715", "save_path": "github-repos/coq/DeepSpec-InteractionTrees", "path": "github-repos/coq/DeepSpec-InteractionTrees/InteractionTrees-8e28e2ee08496c696e03916a22d93c39559a9715/theories/Events/MapDefaultFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.5, "lm_q1q2_score": 0.29255056986686956}}
{"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 RVIC2.Spec.\n\nLocal Open Scope Z_scope.\n\nSection SpecLow.\n\n  Definition rvic_set_pending_spec0 (rvic: Pointer) (intid: Z64) (adt: RData) : option RData :=\n    match rvic, intid with\n    | (_rvic_base, _rvic_ofst), VZ64 _intid =>\n      when'' _t'1_base, _t'1_ofst == get_rvic_pending_bits_spec (_rvic_base, _rvic_ofst) adt;\n      rely is_int _t'1_ofst;\n      rely is_int64 _intid;\n      when adt == rvic_set_flag_spec (VZ64 _intid) (_t'1_base, _t'1_ofst) 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/RVIC4/LowSpecs/rvic_set_pending.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2925325525177334}}
{"text": "(**************************  uc/OS-II  *******************************)\n(*************************** OS_CORE.C *******************************)\n(**Proof of Internal Fucntion: void OS_EventTaskWait(OS_EVENT* pevent) **)\n(**************************** Code:***********************************)\n(*\nVoid ·OS_EventTaskWait·(⌞pevent @ OS_EVENT∗⌟)··{\n       ⌞ ⌟;\n\n1       OSTCBCur′→OSTCBEventPtr =ₑ pevent′;ₛ\n2       OSRdyTbl′[OSTCBCur′→OSTCBY] =ₑ \n                 OSRdyTbl′[OSTCBCur′→OSTCBY] &ₑ (∼OSTCBCur′→OSTCBBitX);ₛ\n3       If (OSRdyTbl′[OSTCBCur′→OSTCBY] ==ₑ ′0)\n        {\n4           OSRdyGrp′ =ₑ OSRdyGrp′ &ₑ (∼OSTCBCur′→OSTCBBitY)\n        };ₛ\n5       pevent′→OSEventTbl[OSTCBCur′→OSTCBY] =ₑ \n               pevent′→OSEventTbl[OSTCBCur′→OSTCBY] |ₑ OSTCBCur′→OSTCBBitX;ₛ\n6       pevent′→OSEventGrp =ₑ pevent′→OSEventGrp |ₑ OSTCBCur′→OSTCBBitY;ₛ\n7       RETURN\n}·. \n*)\n\n(* Require Import ucert. *)\nRequire Import ucos_include.\nRequire Import OSETWaitPure.\nOpen Scope code_scope.\n\n\nLemma OSEventTaskWait_proof:\n    forall tid vl p r ll, \n      Some p =\n      BuildPreI os_internal OS_EventTaskWait\n                  vl ll OS_EventTaskWaitPre tid ->\n      Some r =\n      BuildRetI os_internal OS_EventTaskWait vl ll OS_EventTaskWaitPost tid ->\n      exists t d1 d2 s,\n        os_internal OS_EventTaskWait = Some (t, d1, d2, s) /\\\n        {|OS_spec , GetHPrio, OSLInv, I, r, Afalse|}|- tid {{p}} s {{Afalse}}. \nProof. \n  init_spec.\n  hoare unfold.\n\n  hoare forward.\n  hoare unfold.\n\n\n  lets Hi3: range_ostcby H.\n  destruct Hi3 as [Hi3 Hi2].\n  assert (Z.to_nat (Int.unsigned i3) < length v'0)%nat.\n  {\n    rewrite H8.\n    unfold OS_RDY_TBL_SIZE.\n    \n    apply z_le_7_imp_n;auto.\n    omega.\n  }\n  \n  lets Hx: array_int8u_nth_lt_len H2 H12.\n  Import DeprecatedTactic.\n  mytac.\n  hoare forward.\n  go.\n  (* simpl;splits;pauto. *)\n\n  rewrite H8.\n  unfold OS_RDY_TBL_SIZE.\n  simpl Z.of_nat.\n  auto.\n\n(* ** ac:   Locate array_type_vallist_match_imp_rule_type_val_match. *)\n  Import symbolic_lemmas.\n  \n  eapply array_type_vallist_match_imp_rule_type_val_match.\n  rewrite H8.\n  unfold OS_RDY_TBL_SIZE.\n  \n  apply z_le_7_imp_n;auto.\n  omega.\n  auto.\n\n  go.\n  (* simpl;splits;pauto. *)\n  unfold val_inj.\n  unfold and.\n  rewrite H27.\n  auto.\n\n  go.\n  (* simpl;splits;pauto. *)\n  unfold OS_RDY_TBL_SIZE.\n  simpl Z.of_nat.\n  auto.\n  rewrite H8.\n  unfold OS_RDY_TBL_SIZE.\n  simpl Z.of_nat.\n  auto.\n  (*\n  Focus 2.\n  hoare lift 8%nat pre.\n  apply backward_rule1 with Afalse.\n  intros.\n\n  sep remember (1::nil)%nat in H2.\n  simpl in H2.\n  mytac;auto.\n  apply pfalse_rule.\n   *)\n  unfold AOSRdyGrp.\n  hoare forward.\n  (* simpl;splits;pauto. *)\n  go.\n  rewrite H27.\n\n  rewrite <- update_nth_val_length_eq.\n  rewrite H8.\n  unfold OS_RDY_TBL_SIZE.\n  simpl Z.of_nat.\n  auto.\n  rewrite len_lt_update_get_eq.\n  rewrite H27.\n  simpl.\n  rtmatch_solve.\n  apply int_lemma1;auto.\n  rewrite H8.\n  unfold OS_RDY_TBL_SIZE.\n  simpl Z.of_nat.\n  auto.\n  rewrite H27.\n  rewrite len_lt_update_get_eq.\n  simpl.\n(* ** ac:   Locate \"$\". *)\n  Local Open Scope int_scope.\n  destruct (Int.eq (x&ᵢInt.not i2) ($ 0));auto.\n  rewrite H8.\n  unfold OS_RDY_TBL_SIZE.\n  simpl Z.of_nat.\n  auto.\n  \n  eapply forward_rule2.\n  hoare forward.\n\n  go.\n  (* simpl;splits;pauto. *)\n  unfold val_inj.\n  unfold and.\n\n  destruct v'1;tryfalse.\n  auto.\n  intros.\n  apply H29.\n  apply disj_rule;pure intro.\n  clear  H35 H33 H34.\n  \n  assert (Z.to_nat (Int.unsigned i3) < length v'4)%nat.\n  rewrite H9.\n  unfold OS_EVENT_TBL_SIZE.\n  apply z_le_7_imp_n;auto.\n  omega.\n  lets Hx:array_int8u_nth_lt_len H4 H33.\n  mytac.\n  hoare forward.\n  go.\n  (* simpl;splits;pauto. *)\n  rewrite H9.\n  unfold OS_EVENT_TBL_SIZE.\n  simpl Z.of_nat.\n  auto.\n  rewrite H34.\n  simpl.\n  rtmatch_solve.\n  go.\n  (* simpl;splits;pauto. *)\n  rewrite H34.\n  simpl.\n  auto.\n  go.\n  (* simpl;splits;pauto. *)\n\n  eapply eq_int;auto.\n  rewrite H9.\n  unfold OS_EVENT_TBL_SIZE.\n  simpl Z.of_nat.\n  auto.\n\n  hoare forward.\n  go.\n  go.\n  \n  hoare forward.\n  simpl;auto.\n  simpl;auto.\n  2:simpl;auto.\n  2:auto.\n  4:simpl;auto.\n  5:auto.\n  6:simpl;auto.\n  splits;auto.\n  eapply nth_val'_imp_nth_val_int;eauto.\n  simpl.\n \n  rewrite <- unsigned_to_z_eq.\n  rewrite unsigned_to_z_eq.\n  rewrite H27.\n\n  simpl.\n  auto.\n  rewrite unsigned_to_z_eq.\n  eapply nth_val'_imp_nth_val_int;eauto.\n  splits;auto.\n  rewrite <- unsigned_to_z_eq.\n  rewrite unsigned_to_z_eq.\n  rewrite H34.\n  simpl.\n  auto.\n  split;auto.\n  rewrite H27.\n  simpl.\n  rewrite H27 in H30.\n  rewrite len_lt_update_get_eq in H30.\n  assert (Int.eq (x &ᵢInt.not i2) ($ 0) =true).\n  clear -H30.\n  simpl in H30.\n  simpl.\n  destruct (Int.eq (x &ᵢInt.not i2) ($ 0));tryfalse;auto.\n\n  eapply event_wait_rl_tbl_grp';eauto.\n  rewrite H8.\n  simpl;auto.\n  unfold and.\n  unfold val_inj.\n  rewrite H27.\n  eapply idle_in_rtbl_hold;eauto.\n\n  rtmatch_solve.\n  apply int_lemma1;auto.\n  split.\n  rewrite H27.\n\n  eapply array_type_vallist_match_int8u_update_hold;eauto.\n  omega.\n  rewrite H27.\n\n  rewrite <- update_nth_val_length_eq.\n  auto.\n  go.\n\n  rewrite H34.\n  eapply event_wait_rl_tbl_grp;eauto.\n  simpl;auto.\n  apply array_type_vallist_match_hold;auto.\n  rewrite H34.\n  rtmatch_solve.\n  apply int_unsigned_or_prop;auto.\n  simpl;splits;auto.\n  rtmatch_solve.\n  rtmatch_solve.\n  apply int_unsigned_or_prop';auto.\n  pauto.\n  pauto.\n  pauto.\n\n  (*------------------------------*)\n   \n  assert (Z.to_nat (Int.unsigned i3) < length v'4)%nat.\n  rewrite H9.\n  unfold OS_EVENT_TBL_SIZE.\n  apply z_le_7_imp_n;auto.\n  omega.\n  lets Hx:array_int8u_nth_lt_len H4 H31.\n  mytac.\n  hoare forward.\n  go.\n  rewrite H9.\n  unfold OS_EVENT_TBL_SIZE.\n  simpl Z.of_nat.\n  auto.\n  rewrite H32.\n  simpl.\n  rtmatch_solve.\n  go.\n  rewrite H32.\n  simpl.\n  auto.\n  go.\n\n  eapply eq_int;auto.\n  rewrite H9.\n  unfold OS_EVENT_TBL_SIZE.\n  simpl Z.of_nat.\n  auto.\n\n  hoare forward.\n  go.\n  go.\n  \n  hoare forward.\n   simpl;auto.\n  simpl;auto.\n  2:simpl;auto.\n  2:auto.\n  4:simpl;auto.\n  5:auto.\n  6:simpl;auto.\n  splits;auto.\n  eapply nth_val'_imp_nth_val_int;eauto.\n  simpl.\n \n  rewrite <- unsigned_to_z_eq.\n  rewrite unsigned_to_z_eq.\n  rewrite H27.\n\n  simpl.\n  auto.\n  rewrite unsigned_to_z_eq.\n  eapply nth_val'_imp_nth_val_int;eauto.\n  splits;auto.\n  rewrite <- unsigned_to_z_eq.\n  rewrite unsigned_to_z_eq.\n  rewrite H32.\n  simpl.\n  auto.\n  split;auto.\n  rewrite H27.\n  simpl.\n  rewrite H27 in H30.\n  rewrite len_lt_update_get_eq in H30.\n  assert (Int.eq (x &ᵢInt.not i2) ($ 0) = false).\n  clear -H30.\n  simpl in H30.\n  destruct H30.\n  simpl in H.\n  destruct (Int.eq (x &ᵢInt.not i2) ($ 0));tryfalse;auto.\n  simpl in H.\n  destruct (Int.eq (x &ᵢInt.not i2) ($ 0));tryfalse;auto.\n  \n\n  eapply event_wait_rl_tbl_grp'';eauto.\n  rewrite H8.\n  simpl;auto.\n  unfold and.\n  unfold val_inj.\n  rewrite H27.\n  eapply idle_in_rtbl_hold;eauto.\n\n  rtmatch_solve.\n  split.\n  rewrite H27.\n\n  eapply array_type_vallist_match_int8u_update_hold;eauto.\n  omega.\n  rewrite H27.\n\n  rewrite <- update_nth_val_length_eq.\n  auto.\n  go.\n  simpl.\n  rewrite H32.\n  eapply event_wait_rl_tbl_grp;eauto.\n  simpl;auto.\n  apply array_type_vallist_match_hold;auto.\n  rewrite H32.\n  rtmatch_solve.\n  apply int_unsigned_or_prop;auto.\n  simpl;splits;auto.\n  rtmatch_solve.\n  rtmatch_solve.\n  apply int_unsigned_or_prop';auto.\n  pauto.\n  pauto.\n  pauto.\n\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/oscore/OSEventTaskWait.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.29253254561177044}}
{"text": "From iris.algebra Require Export ofe.\nFrom iris Require Import options.\n\nRecord solution (F : oFunctor) := Solution {\n  solution_car :> ofeT;\n  solution_cofe : Cofe solution_car;\n  solution_iso :> ofe_iso (oFunctor_apply F solution_car) solution_car;\n}.\nExisting Instance solution_cofe.\n\nModule solver. Section solver.\nContext (F : oFunctor) `{Fcontr : oFunctorContractive F}.\nContext `{Fcofe : ∀ (T : ofeT) `{!Cofe T}, Cofe (oFunctor_apply F T)}.\nContext `{Finh : Inhabited (oFunctor_apply F unitO)}.\nNotation map := (oFunctor_map F).\n\nFixpoint A' (k : nat) : { C : ofeT & Cofe C } :=\n  match k with\n  | 0 => existT (P:=Cofe) unitO _\n  | S k => existT (P:=Cofe) (@oFunctor_apply F (projT1 (A' k)) (projT2 (A' k))) _\n  end.\nNotation A k := (projT1 (A' k)).\nLocal Instance A_cofe k : Cofe (A k) := projT2 (A' k).\n\nFixpoint f (k : nat) : A k -n> A (S k) :=\n  match k with 0 => OfeMor (λ _, inhabitant) | S k => map (g k,f k) end\nwith g (k : nat) : A (S k) -n> A k :=\n  match k with 0 => OfeMor (λ _, ()) | S k => map (f k,g k) end.\nDefinition f_S k (x : A (S k)) : f (S k) x = map (g k,f k) x := eq_refl.\nDefinition g_S k (x : A (S (S k))) : g (S k) x = map (f k,g k) x := eq_refl.\nArguments f : simpl never.\nArguments g : simpl never.\n\nLemma gf {k} (x : A k) : g k (f k x) ≡ x.\nProof using Fcontr.\n  induction k as [|k IH]; simpl in *; [by destruct x|].\n  rewrite -oFunctor_map_compose -{2}[x]oFunctor_map_id.\n  by apply (contractive_proper map).\nQed.\nLemma fg {k} (x : A (S (S k))) : f (S k) (g (S k) x) ≡{k}≡ x.\nProof using Fcontr.\n  induction k as [|k IH]; simpl.\n  - rewrite f_S g_S -{2}[x]oFunctor_map_id -oFunctor_map_compose.\n    apply (contractive_0 map).\n  - rewrite f_S g_S -{2}[x]oFunctor_map_id -oFunctor_map_compose.\n    by apply (contractive_S map).\nQed.\n\nRecord tower := {\n  tower_car k :> A k;\n  g_tower k : g k (tower_car (S k)) ≡ tower_car k\n}.\nInstance tower_equiv : Equiv tower := λ X Y, ∀ k, X k ≡ Y k.\nInstance tower_dist : Dist tower := λ n X Y, ∀ k, X k ≡{n}≡ Y k.\nDefinition tower_ofe_mixin : OfeMixin tower.\nProof.\n  split.\n  - intros X Y; split; [by intros HXY n k; apply equiv_dist|].\n    intros HXY k; apply equiv_dist; intros n; apply HXY.\n  - intros k; split.\n    + by intros X n.\n    + by intros X Y ? n.\n    + by intros X Y Z ?? n; trans (Y n).\n  - intros k X Y HXY n; apply dist_S.\n    by rewrite -(g_tower X) (HXY (S n)) g_tower.\nQed.\nDefinition T : ofeT := OfeT tower tower_ofe_mixin.\n\nProgram Definition tower_chain (c : chain T) (k : nat) : chain (A k) :=\n  {| chain_car i := c i k |}.\nNext Obligation. intros c k n i ?; apply (chain_cauchy c n); lia. Qed.\nProgram Definition tower_compl : Compl T := λ c,\n  {| tower_car n := compl (tower_chain c n) |}.\nNext Obligation.\n  intros c k; apply equiv_dist=> n.\n  by rewrite (conv_compl n (tower_chain c k))\n    (conv_compl n (tower_chain c (S k))) /= (g_tower (c _) k).\nQed.\nGlobal Program Instance tower_cofe : Cofe T := { compl := tower_compl }.\nNext Obligation.\n  intros n c k; rewrite /= (conv_compl n (tower_chain c k)).\n  apply (chain_cauchy c); lia.\nQed.\n\nFixpoint ff {k} (i : nat) : A k -n> A (i + k) :=\n  match i with 0 => cid | S i => f (i + k) ◎ ff i end.\nFixpoint gg {k} (i : nat) : A (i + k) -n> A k :=\n  match i with 0 => cid | S i => gg i ◎ g (i + k) end.\nLemma ggff {k i} (x : A k) : gg i (ff i x) ≡ x.\nProof using Fcontr. induction i as [|i IH]; simpl; [done|by rewrite (gf (ff i x)) IH]. Qed.\nLemma f_tower k (X : tower) : f (S k) (X (S k)) ≡{k}≡ X (S (S k)).\nProof using Fcontr. intros. by rewrite -(fg (X (S (S k)))) -(g_tower X). Qed.\nLemma ff_tower k i (X : tower) : ff i (X (S k)) ≡{k}≡ X (i + S k).\nProof using Fcontr.\n  intros; induction i as [|i IH]; simpl; [done|].\n  by rewrite IH Nat.add_succ_r (dist_le _ _ _ _ (f_tower _ X)); last lia.\nQed.\nLemma gg_tower k i (X : tower) : gg i (X (i + k)) ≡ X k.\nProof. by induction i as [|i IH]; simpl; [done|rewrite g_tower IH]. Qed.\n\nInstance tower_car_ne k : NonExpansive (λ X, tower_car X k).\nProof. by intros X Y HX. Qed.\nDefinition project (k : nat) : T -n> A k := OfeMor (λ X : T, tower_car X k).\n\nDefinition coerce {i j} (H : i = j) : A i -n> A j :=\n  eq_rect _ (λ i', A i -n> A i') cid _ H.\nLemma coerce_id {i} (H : i = i) (x : A i) : coerce H x = x.\nProof. unfold coerce. by rewrite (proof_irrel H (eq_refl i)). Qed.\nLemma coerce_proper {i j} (x y : A i) (H1 H2 : i = j) :\n  x = y → coerce H1 x = coerce H2 y.\nProof. by destruct H1; rewrite !coerce_id. Qed.\nLemma g_coerce {k j} (H : S k = S j) (x : A (S k)) :\n  g j (coerce H x) = coerce (Nat.succ_inj _ _ H) (g k x).\nProof. by assert (k = j) by lia; subst; rewrite !coerce_id. Qed.\nLemma coerce_f {k j} (H : S k = S j) (x : A k) :\n  coerce H (f k x) = f j (coerce (Nat.succ_inj _ _ H) x).\nProof. by assert (k = j) by lia; subst; rewrite !coerce_id. Qed.\nLemma gg_gg {k i i1 i2 j} : ∀ (H1: k = i + j) (H2: k = i2 + (i1 + j)) (x: A k),\n  gg i (coerce H1 x) = gg i1 (gg i2 (coerce H2 x)).\nProof.\n  intros ? -> x. assert (i = i2 + i1) as -> by lia. revert j x H1.\n  induction i2 as [|i2 IH]; intros j X H1; simplify_eq/=;\n    [by rewrite coerce_id|by rewrite g_coerce IH].\nQed.\nLemma ff_ff {k i i1 i2 j} : ∀ (H1: i + k = j) (H2: i1 + (i2 + k) = j) (x: A k),\n  coerce H1 (ff i x) = coerce H2 (ff i1 (ff i2 x)).\nProof.\n  intros ? <- x. assert (i = i1 + i2) as -> by lia.\n  induction i1 as [|i1 IH]; simplify_eq/=;\n    [by rewrite coerce_id|by rewrite coerce_f IH].\nQed.\n\nDefinition embed_coerce {k} (i : nat) : A k -n> A i :=\n  match le_lt_dec i k with\n  | left H => gg (k-i) ◎ coerce (eq_sym (Nat.sub_add _ _ H))\n  | right H => coerce (Nat.sub_add k i (Nat.lt_le_incl _ _ H)) ◎ ff (i-k)\n  end.\nLemma g_embed_coerce {k i} (x : A k) :\n  g i (embed_coerce (S i) x) ≡ embed_coerce i x.\nProof using Fcontr.\n  unfold embed_coerce; destruct (le_lt_dec (S i) k), (le_lt_dec i k); simpl.\n  - symmetry; by erewrite (@gg_gg _ _ 1 (k - S i)); simpl.\n  - exfalso; lia.\n  - assert (i = k) by lia; subst.\n    rewrite (ff_ff _ (eq_refl (1 + (0 + k)))) /= gf.\n    by rewrite (gg_gg _ (eq_refl (0 + (0 + k)))).\n  - assert (H : 1 + ((i - k) + k) = S i) by lia.\n    rewrite (ff_ff _ H) /= -{2}(gf (ff (i - k) x)) g_coerce.\n    by erewrite coerce_proper by done.\nQed.\nProgram Definition embed (k : nat) (x : A k) : T :=\n  {| tower_car n := embed_coerce n x |}.\nNext Obligation. intros k x i. apply g_embed_coerce. Qed.\nInstance: Params (@embed) 1 := {}.\nInstance embed_ne k : NonExpansive (embed k).\nProof. by intros n x y Hxy i; rewrite /= Hxy. Qed.\nDefinition embed' (k : nat) : A k -n> T := OfeMor (embed k).\nLemma embed_f k (x : A k) : embed (S k) (f k x) ≡ embed k x.\nProof.\n  rewrite equiv_dist=> n i; rewrite /embed /= /embed_coerce.\n  destruct (le_lt_dec i (S k)), (le_lt_dec i k); simpl.\n  - assert (H : S k = S (k - i) + (0 + i)) by lia; rewrite (gg_gg _ H) /=.\n    by erewrite g_coerce, gf, coerce_proper by done.\n  - assert (S k = 0 + (0 + i)) as H by lia.\n    rewrite (gg_gg _ H); simplify_eq/=.\n    by rewrite (ff_ff _ (eq_refl (1 + (0 + k)))).\n  - exfalso; lia.\n  - assert (H : (i - S k) + (1 + k) = i) by lia; rewrite (ff_ff _ H) /=.\n    by erewrite coerce_proper by done.\nQed.\nLemma embed_tower k (X : T) : embed (S k) (X (S k)) ≡{k}≡ X.\nProof.\n  intros i; rewrite /= /embed_coerce.\n  destruct (le_lt_dec i (S k)) as [H|H]; simpl.\n  - rewrite -(gg_tower i (S k - i) X).\n    apply (_ : Proper (_ ==> _) (gg _)); by destruct (eq_sym _).\n  - rewrite (ff_tower k (i - S k) X). by destruct (Nat.sub_add _ _ _).\nQed.\n\nProgram Definition unfold_chain (X : T) : chain (oFunctor_apply F T) :=\n  {| chain_car n := map (project n,embed' n) (X (S n)) |}.\nNext Obligation.\n  intros X n i Hi.\n  assert (∃ k, i = k + n) as [k ?] by (exists (i - n); lia); subst; clear Hi.\n  induction k as [|k IH]; simpl; first done.\n  rewrite -IH -(dist_le _ _ _ _ (f_tower (k + n) _)); last lia.\n  rewrite f_S -oFunctor_map_compose.\n  by apply (contractive_ne map); split=> Y /=; rewrite ?g_tower ?embed_f.\nQed.\nDefinition unfold (X : T) : oFunctor_apply F T := compl (unfold_chain X).\nInstance unfold_ne : NonExpansive unfold.\nProof.\n  intros n X Y HXY. by rewrite /unfold (conv_compl n (unfold_chain X))\n    (conv_compl n (unfold_chain Y)) /= (HXY (S n)).\nQed.\n\nProgram Definition fold (X : oFunctor_apply F T) : T :=\n  {| tower_car n := g n (map (embed' n,project n) X) |}.\nNext Obligation.\n  intros X k. apply (_ : Proper ((≡) ==> (≡)) (g k)).\n  rewrite g_S -oFunctor_map_compose.\n  apply (contractive_proper map); split=> Y; [apply embed_f|apply g_tower].\nQed.\nInstance fold_ne : NonExpansive fold.\nProof. by intros n X Y HXY k; rewrite /fold /= HXY. Qed.\n\nTheorem result : solution F.\nProof using Type*.\n  refine (Solution F T _ (OfeIso (OfeMor fold) (OfeMor unfold) _ _)).\n  - move=> X /=. rewrite equiv_dist=> n k; rewrite /unfold /fold /=.\n    rewrite -g_tower -(gg_tower _ n); apply (_ : Proper (_ ==> _) (g _)).\n    trans (map (ff n, gg n) (X (S (n + k)))).\n    { rewrite /unfold (conv_compl n (unfold_chain X)).\n      rewrite -(chain_cauchy (unfold_chain X) n (S (n + k))) /=; last lia.\n      rewrite -(dist_le _ _ _ _ (f_tower (n + k) _)); last lia.\n      rewrite f_S -!oFunctor_map_compose; apply (contractive_ne map); split=> Y.\n      + rewrite /embed' /= /embed_coerce.\n        destruct (le_lt_dec _ _); simpl; [exfalso; lia|].\n        by rewrite (ff_ff _ (eq_refl (S n + (0 + k)))) /= gf.\n      + rewrite /embed' /= /embed_coerce.\n        destruct (le_lt_dec _ _); simpl; [|exfalso; lia].\n        by rewrite (gg_gg _ (eq_refl (0 + (S n + k)))) /= gf. }\n    assert (∀ i k (x : A (S i + k)) (H : S i + k = i + S k),\n      map (ff i, gg i) x ≡ gg i (coerce H x)) as map_ff_gg.\n    { intros i; induction i as [|i IH]; intros k' x H; simpl.\n      { by rewrite coerce_id oFunctor_map_id. }\n      rewrite oFunctor_map_compose g_coerce; apply IH. }\n    assert (H: S n + k = n + S k) by lia.\n    rewrite (map_ff_gg _ _ _ H).\n    apply (_ : Proper (_ ==> _) (gg _)); by destruct H.\n  - intros X; rewrite equiv_dist=> n /=.\n    rewrite /unfold /= (conv_compl' n (unfold_chain (fold X))) /=.\n    rewrite g_S -!oFunctor_map_compose -{2}[X]oFunctor_map_id.\n    apply (contractive_ne map); split => Y /=.\n    + rewrite f_tower. apply dist_S. by rewrite embed_tower.\n    + etrans; [apply embed_ne, equiv_dist, g_tower|apply embed_tower].\nQed.\nEnd solver. End solver.\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/cofe_solver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.2924877936209498}}
{"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.NArith.NArith.\n\nLemma apply_if {A B} (f : A -> B) (b : bool) x y : f (if b then x else y) = if b then f x else f y.\nProof. destruct b; reflexivity. Qed.\n\nLemma fst_if {A B} (b : bool) (x y : A * B) : fst (if b then x else y) = if b then fst x else fst y.\nProof. apply apply_if. Qed.\nLemma snd_if {A B} (b : bool) (x y : A * B) : snd (if b then x else y) = if b then snd x else snd y.\nProof. apply apply_if. Qed.\nHint Rewrite @fst_if @snd_if using solve [eauto] : tuple_if.\n\nLemma tup_if {A B} (b : bool) (x y: A) (z w: B) : (if b then x else y, if b then z else w) = if b then (x,z) else (y, w).\nProof. destruct b; reflexivity. Qed.\nHint Rewrite @tup_if using solve [eauto] : tuple_if.\n\nLemma apply_if_ext_1 {A B C} (f : A -> B -> C) (b : bool) x y z : f (if b then x else y) z = if b then f x z else f y z.\nProof. destruct b; reflexivity. Qed.\n\nLemma if_true_rew {A} (x: bool) (z: A) P Q: (x = true -> P = Q) ->\n    (if x then P else z) = (if x then Q else z).\nProof. intros; destruct x; [ apply H | ]; reflexivity. Qed.\n\nLemma to_nat_if (b: bool) x y : N.to_nat (if b then x else y) = if b then (N.to_nat x) else (N.to_nat y).\nProof. now destruct b. Qed.\nHint Rewrite to_nat_if : Nnat.\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/cava/Cava/Util/If.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2924872933327721}}
{"text": "From Coq Require Import List.\nFrom MetaCoq.Template Require Import All.\n\nImport ListNotations.\nImport MCMonadNotation.\nOpen Scope bs_scope.\nDefinition qlist := Eval compute in match <% list %> with\n    | tInd ind _ => ind.(inductive_mind)\n    | _ => (MPfile nil, \"\"%bs)\n    end.\n\n\nDefinition refresh_sort t :=\n  match t with\n  | tSort s =>\n      match s with\n      | Universe.lProp => tSort Universe.lProp\n      | Universe.lSProp => tSort Universe.lSProp\n      | Universe.lType _ => tSort Universes.fresh_universe\n      end\n  | _ => t\n  end.\n\nDefinition refresh_arity s :=\n  let (ctx, concl) := decompose_prod_assum [] s in\n  it_mkProd_or_LetIn ctx (refresh_sort concl).\n\n  Definition mind_body_to_entry :=\n  fun decl : mutual_inductive_body =>\n  {|\n  mind_entry_record := None;\n  mind_entry_finite := Finite;\n  mind_entry_params :=\n      match hd_error (ind_bodies decl) with\n      | Some i0 =>\n          List.rev\n          (let typ := decompose_prod (ind_type i0) in\n              let (a, b) := typ in\n              (fun p : list aname × list term =>\n              let (a0, b0) := p in\n              (fun (names : list aname) (types : list term) (_ : term) =>\n              let names0 := firstn (ind_npars decl) names in\n              let types0 := firstn (ind_npars decl) types in\n              map (fun '(x, ty) => vass x ty) (combine names0 types0)) a0 b0)\n              a b)\n      | None => []\n      end;\n  mind_entry_inds :=\n      map\n      (fun X : one_inductive_body =>\n          match X with\n          | {|\n              ind_name := ind_name;\n              ind_indices := ind_indices;\n              ind_sort := ind_sort;\n              ind_type := ind_type;\n              ind_kelim := ind_kelim;\n              ind_ctors := ind_ctors;\n              ind_projs := ind_projs;\n              ind_relevance := ind_relevance\n          |} =>\n              {|\n              mind_entry_typename := ind_name;\n              mind_entry_arity := refresh_arity (remove_arity (ind_npars decl) ind_type);\n              mind_entry_consnames :=\n                  map (fun x : constructor_body => cstr_name x) ind_ctors;\n              mind_entry_lc :=\n                  map\n                  (fun x : constructor_body =>\n                      remove_arity (ind_npars decl) (cstr_type x)) ind_ctors\n              |}\n          end) (ind_bodies decl);\n  mind_entry_universes := universes_entry_of_decl (ind_universes decl);\n  mind_entry_template := false;\n  mind_entry_variance := option_map (map Some) (ind_variance decl);\n  mind_entry_private := None\n  |}.\n\n\n\nUnset MetaCoq Strict Unquote Universe Mode.\nMetaCoq Run (tmQuoteInductive qlist >>= fun mib =>\n  let entry := mind_body_to_entry mib in\n  entry <- tmEval all entry;;\n  tmPrint entry ;;\n  tmMkInductive true entry).\n", "meta": {"author": "MetaCoq", "repo": "metacoq", "sha": "c340242b43ebe26f3bacb1c72ef82b8ca61da632", "save_path": "github-repos/coq/MetaCoq-metacoq", "path": "github-repos/coq/MetaCoq-metacoq/metacoq-c340242b43ebe26f3bacb1c72ef82b8ca61da632/test-suite/inferind.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2924872933327721}}
{"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. *)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Values.\nRequire Import Events.\nRequire Import Memory.\nRequire Import Globalenvs.\nRequire Import Smallstep.\nRequire Import Op.\nRequire Import Registers.\nRequire Import RTL.\nRequire Import Lattice.\nRequire Import Kildall.\nRequire Import ConstpropOp.\nRequire Import Constprop.\nRequire Import ConstpropOpproof.\n\nSection PRESERVATION.\n\nVariable prog: program.\nLet tprog := transf_program prog.\nLet ge := Genv.globalenv prog.\nLet tge := Genv.globalenv tprog.\nLet gapp := make_global_approx (PTree.empty _) prog.(prog_defs).\n\n(** * Correctness of the static analysis *)\n\nSection ANALYSIS.\n\nVariable sp: val.\n\nDefinition regs_match_approx (a: D.t) (rs: regset) : Prop :=\n  forall r, val_match_approx ge sp (D.get r a) rs#r.\n\nLemma regs_match_approx_top:\n  forall rs, regs_match_approx D.top rs.\nProof.\n  intros. red; intros. simpl. rewrite PTree.gempty. \n  unfold Approx.top, val_match_approx. auto.\nQed.\n\nLemma val_match_approx_increasing:\n  forall a1 a2 v,\n  Approx.ge a1 a2 -> val_match_approx ge sp a2 v -> val_match_approx ge sp a1 v.\nProof.\n  intros until v.\n  intros [A|[B|C]].\n  subst a1. simpl. auto.\n  subst a2. simpl. tauto.\n  subst a2. auto.\nQed.\n\nLemma regs_match_approx_increasing:\n  forall a1 a2 rs,\n  D.ge a1 a2 -> regs_match_approx a2 rs -> regs_match_approx a1 rs.\nProof.\n  unfold D.ge, regs_match_approx. intros.\n  apply val_match_approx_increasing with (D.get r a2); auto.\nQed.\n\nLemma regs_match_approx_update:\n  forall ra rs a v r,\n  val_match_approx ge sp a v ->\n  regs_match_approx ra rs ->\n  regs_match_approx (D.set r a ra) (rs#r <- v).\nProof.\n  intros; red; intros. rewrite Regmap.gsspec. \n  case (peq r0 r); intro.\n  subst r0. rewrite D.gss. auto.\n  rewrite D.gso; auto. \nQed.\n\nLemma approx_regs_val_list:\n  forall ra rs rl,\n  regs_match_approx ra rs ->\n  val_list_match_approx ge sp (approx_regs ra rl) rs##rl.\nProof.\n  induction rl; simpl; intros.\n  constructor.\n  constructor. apply H. auto.\nQed.\n\n(** The correctness of the static analysis follows from the results\n  of module [ConstpropOpproof] and the fact that the result of\n  the static analysis is a solution of the forward dataflow inequations. *)\n\nLemma analyze_correct_1:\n  forall f pc rs pc' i,\n  f.(fn_code)!pc = Some i ->\n  In pc' (successors_instr i) ->\n  regs_match_approx (transfer gapp f pc (analyze gapp f)!!pc) rs ->\n  regs_match_approx (analyze gapp f)!!pc' rs.\nProof.\n  intros until i. unfold analyze. \n  caseEq (DS.fixpoint (successors f) (transfer gapp f)\n                      ((fn_entrypoint f, D.top) :: nil)).\n  intros approxs; intros.\n  apply regs_match_approx_increasing with (transfer gapp f pc approxs!!pc).\n  eapply DS.fixpoint_solution; eauto.\n  unfold successors_list, successors. rewrite PTree.gmap1. rewrite H0. auto.\n  auto.\n  intros. rewrite PMap.gi. apply regs_match_approx_top. \nQed.\n\nLemma analyze_correct_3:\n  forall f rs,\n  regs_match_approx (analyze gapp f)!!(f.(fn_entrypoint)) rs.\nProof.\n  intros. unfold analyze. \n  caseEq (DS.fixpoint (successors f) (transfer gapp f)\n                      ((fn_entrypoint f, D.top) :: nil)).\n  intros approxs; intros.\n  apply regs_match_approx_increasing with D.top.\n  eapply DS.fixpoint_entry; eauto. auto with coqlib.\n  apply regs_match_approx_top. \n  intros. rewrite PMap.gi. apply regs_match_approx_top.\nQed.\n\n(** eval_static_load *)\n\nDefinition mem_match_approx (m: mem) : Prop :=\n  forall id il b,\n  gapp!id = Some il -> Genv.find_symbol ge id = Some b ->\n  Genv.load_store_init_data ge m b 0 il /\\\n  Mem.valid_block m b /\\\n  (forall ofs, ~Mem.perm m b ofs Max Writable).\n\nLemma eval_load_init_sound:\n  forall chunk m b il base ofs pos v,\n  Genv.load_store_init_data ge m b base il ->\n  Mem.load chunk m b ofs = Some v ->\n  ofs = base + pos ->\n  val_match_approx ge sp (eval_load_init chunk pos il) v.\nProof.\n  induction il; simpl; intros.\n(* base case il = nil *)\n  auto.\n(* inductive case *)\n  destruct a.\n  (* Init_int8 *)\n  destruct H. destruct (zeq pos 0). subst.  rewrite Zplus_0_r in H0.\n  destruct chunk; simpl; auto.\n  rewrite Mem.load_int8_signed_unsigned in H0. rewrite H in H0. simpl in H0.\n  inv H0. decEq. apply Int.sign_ext_zero_ext. compute; auto. \n  congruence.\n  eapply IHil; eauto. omega.\n  (* Init_int16 *)\n  destruct H. destruct (zeq pos 0). subst.  rewrite Zplus_0_r in H0.\n  destruct chunk; simpl; auto.\n  rewrite Mem.load_int16_signed_unsigned in H0. rewrite H in H0. simpl in H0.\n  inv H0. decEq. apply Int.sign_ext_zero_ext. compute; auto. \n  congruence.\n  eapply IHil; eauto. omega.\n  (* Init_int32 *)\n  destruct H. destruct (zeq pos 0). subst.  rewrite Zplus_0_r in H0.\n  destruct chunk; simpl; auto.\n  congruence.\n  eapply IHil; eauto. omega.\n  (* Init_float32 *)\n  destruct H. destruct (zeq pos 0). subst.  rewrite Zplus_0_r in H0.\n  destruct chunk; simpl; auto. destruct (propagate_float_constants tt); simpl; auto.\n  congruence.\n  eapply IHil; eauto. omega.\n  (* Init_float64 *)\n  destruct H. destruct (zeq pos 0). subst.  rewrite Zplus_0_r in H0.\n  destruct chunk; simpl; auto. destruct (propagate_float_constants tt); simpl; auto.\n  congruence.\n  eapply IHil; eauto. omega.\n  (* Init_space *)\n  eapply IHil; eauto. omega.\n  (* Init_symbol *)\n  destruct H as [[b' [A B]] C].\n  destruct (zeq pos 0). subst.  rewrite Zplus_0_r in H0.\n  destruct chunk; simpl; auto.\n  unfold symbol_address. rewrite A. congruence.\n  eapply IHil; eauto. omega.\nQed.\n\nLemma eval_static_load_sound:\n  forall chunk m addr vaddr v,\n  Mem.loadv chunk m vaddr = Some v ->\n  mem_match_approx m ->  \n  val_match_approx ge sp addr vaddr ->\n  val_match_approx ge sp (eval_static_load gapp chunk addr) v.\nProof.\n  intros. unfold eval_static_load. destruct addr; simpl; auto. \n  destruct (gapp!i) as [il|] eqn:?; auto.\n  red in H1. subst vaddr. unfold symbol_address in H. \n  destruct (Genv.find_symbol ge i) as [b'|] eqn:?; simpl in H; try discriminate.\n  exploit H0; eauto. intros [A [B C]]. \n  eapply eval_load_init_sound; eauto. \n  red; auto. \nQed.\n\nLemma mem_match_approx_store:\n  forall chunk m addr v m',\n  mem_match_approx m ->\n  Mem.storev chunk m addr v = Some m' ->\n  mem_match_approx m'.\nProof.\n  intros; red; intros. exploit H; eauto. intros [A [B C]].\n  destruct addr; simpl in H0; try discriminate.\n  exploit Mem.store_valid_access_3; eauto. intros [P Q].\n  split. apply Genv.load_store_init_data_invariant with m; auto. \n  intros. eapply Mem.load_store_other; eauto. left; red; intro; subst b0.\n  eapply C. apply Mem.perm_cur_max. eapply P. instantiate (1 := Int.unsigned i).\n  generalize (size_chunk_pos chunk). omega.\n  split. eauto with mem.\n  intros; red; intros. eapply C. eapply Mem.perm_store_2; eauto.\nQed.\n\nLemma mem_match_approx_alloc:\n  forall m lo hi b m',\n  mem_match_approx m ->\n  Mem.alloc m lo hi = (m', b) ->\n  mem_match_approx m'.\nProof.\n  intros; red; intros. exploit H; eauto. intros [A [B C]].\n  split. apply Genv.load_store_init_data_invariant with m; auto.\n  intros. eapply Mem.load_alloc_unchanged; eauto. \n  split. eauto with mem.\n  intros; red; intros. exploit Mem.perm_alloc_inv; eauto. \n  rewrite zeq_false. apply C. eapply Mem.valid_not_valid_diff; eauto with mem.\nQed.\n\nLemma mem_match_approx_free:\n  forall m lo hi b m',\n  mem_match_approx m ->\n  Mem.free m b lo hi = Some m' ->\n  mem_match_approx m'.\nProof.\n  intros; red; intros. exploit H; eauto. intros [A [B C]].\n  split. apply Genv.load_store_init_data_invariant with m; auto.\n  intros. eapply Mem.load_free; eauto.\n  destruct (zeq b0 b); auto. subst b0.\n  right. destruct (zlt lo hi); auto. \n  elim (C lo). apply Mem.perm_cur_max. \n  exploit Mem.free_range_perm; eauto. instantiate (1 := lo); omega. \n  intros; eapply Mem.perm_implies; eauto with mem.\n  split. eauto with mem.\n  intros; red; intros. eapply C. eauto with mem. \nQed.\n\nLemma mem_match_approx_extcall:\n  forall ef vargs m t vres m',\n  mem_match_approx m ->\n  external_call ef ge vargs m t vres m' ->\n  mem_match_approx m'.\nProof.\n  intros; red; intros. exploit H; eauto. intros [A [B C]].\n  split. apply Genv.load_store_init_data_invariant with m; auto.\n  intros. eapply external_call_readonly; eauto. \n  split. eapply external_call_valid_block; eauto.\n  intros; red; intros. elim (C ofs). eapply external_call_max_perm; eauto. \nQed.\n\n(* Show that mem_match_approx holds initially *)\n\nDefinition global_approx_charact (g: genv) (ga: global_approx) : Prop :=\n  forall id il b,\n  ga!id = Some il -> \n  Genv.find_symbol g id = Some b -> \n  Genv.find_var_info g b = Some (mkglobvar tt il true false).\n\nLemma make_global_approx_correct:\n  forall gdl g ga,\n  global_approx_charact g ga ->\n  global_approx_charact (Genv.add_globals g gdl) (make_global_approx ga gdl).\nProof.\n  induction gdl; simpl; intros.\n  auto.\n  destruct a as [id gd]. apply IHgdl. \n  red; intros. \n  assert (EITHER: id0 = id /\\ gd = Gvar(mkglobvar tt il true false)\n               \\/ id0 <> id /\\ ga!id0 = Some il).\n  destruct gd.\n  rewrite PTree.grspec in H0. destruct (PTree.elt_eq id0 id); [discriminate|auto].\n  destruct (gvar_readonly v && negb (gvar_volatile v)) eqn:?.\n  rewrite PTree.gsspec in H0. destruct (peq id0 id).\n  inv H0. left. split; auto. \n  destruct v; simpl in *. \n  destruct gvar_readonly; try discriminate.\n  destruct gvar_volatile; try discriminate.\n  destruct gvar_info. auto.\n  auto.\n  rewrite PTree.grspec in H0. destruct (PTree.elt_eq id0 id); [discriminate|auto].\n\n  unfold Genv.add_global, Genv.find_symbol, Genv.find_var_info in *;\n  simpl in *.\n  destruct EITHER as [[A B] | [A B]].\n  subst id0. rewrite PTree.gss in H1. inv H1. rewrite ZMap.gss. auto.\n  rewrite PTree.gso in H1; auto. destruct gd. eapply H; eauto. \n  rewrite ZMap.gso. eapply H; eauto.\n  exploit Genv.genv_symb_range; eauto. unfold ZIndexed.t. omega.\nQed.\n\nTheorem mem_match_approx_init:\n  forall m, Genv.init_mem prog = Some m -> mem_match_approx m.\nProof.\n  intros. \n  assert (global_approx_charact ge gapp).\n    unfold ge, gapp.   unfold Genv.globalenv.\n    apply make_global_approx_correct.\n    red; intros. rewrite PTree.gempty in H0; discriminate.\n  red; intros. \n  exploit Genv.init_mem_characterization.\n  unfold ge in H0. eapply H0; eauto. eauto. \n  unfold Genv.perm_globvar; simpl.\n  intros [A [B C]].\n  split. auto. split. eapply Genv.find_symbol_not_fresh; eauto. \n  intros; red; intros. exploit B; eauto. intros [P Q]. inv Q.\nQed.\n\nEnd ANALYSIS.\n\n(** * Correctness of the code transformation *)\n\n(** We now show that the transformed code after constant propagation\n  has the same semantics as the original code. *)\n\nLemma symbols_preserved:\n  forall (s: ident), Genv.find_symbol tge s = Genv.find_symbol ge s.\nProof.\n  intros; unfold ge, tge, tprog, transf_program. \n  apply Genv.find_symbol_transf.\nQed.\n\nLemma varinfo_preserved:\n  forall b, Genv.find_var_info tge b = Genv.find_var_info ge b.\nProof.\n  intros; unfold ge, tge, tprog, transf_program. \n  apply Genv.find_var_info_transf.\nQed.\n\nLemma functions_translated:\n  forall (v: val) (f: fundef),\n  Genv.find_funct ge v = Some f ->\n  Genv.find_funct tge v = Some (transf_fundef gapp f).\nProof.  \n  intros.\n  exact (Genv.find_funct_transf (transf_fundef gapp) _ _ H).\nQed.\n\nLemma function_ptr_translated:\n  forall (b: block) (f: fundef),\n  Genv.find_funct_ptr ge b = Some f ->\n  Genv.find_funct_ptr tge b = Some (transf_fundef gapp f).\nProof.  \n  intros. \n  exact (Genv.find_funct_ptr_transf (transf_fundef gapp) _ _ H).\nQed.\n\nLemma sig_function_translated:\n  forall f,\n  funsig (transf_fundef gapp f) = funsig f.\nProof.\n  intros. destruct f; reflexivity.\nQed.\n\nDefinition regs_lessdef (rs1 rs2: regset) : Prop :=\n  forall r, Val.lessdef (rs1#r) (rs2#r).\n\nLemma regs_lessdef_regs:\n  forall rs1 rs2, regs_lessdef rs1 rs2 ->\n  forall rl, Val.lessdef_list rs1##rl rs2##rl.\nProof.\n  induction rl; constructor; auto.\nQed.\n\nLemma set_reg_lessdef:\n  forall r v1 v2 rs1 rs2,\n  Val.lessdef v1 v2 -> regs_lessdef rs1 rs2 -> regs_lessdef (rs1#r <- v1) (rs2#r <- v2).\nProof.\n  intros; red; intros. repeat rewrite Regmap.gsspec. \n  destruct (peq r0 r); auto.\nQed.\n\nLemma init_regs_lessdef:\n  forall rl vl1 vl2,\n  Val.lessdef_list vl1 vl2 ->\n  regs_lessdef (init_regs vl1 rl) (init_regs vl2 rl).\nProof.\n  induction rl; simpl; intros.\n  red; intros. rewrite Regmap.gi. auto.\n  inv H. red; intros. rewrite Regmap.gi. auto.\n  apply set_reg_lessdef; auto.\nQed.\n\nLemma transf_ros_correct:\n  forall sp ros rs rs' f approx,\n  regs_match_approx sp approx rs ->\n  find_function ge ros rs = Some f ->\n  regs_lessdef rs rs' ->\n  find_function tge (transf_ros approx ros) rs' = Some (transf_fundef gapp f).\nProof.\n  intros. destruct ros; simpl in *.\n  generalize (H r); intro MATCH. generalize (H1 r); intro LD.\n  destruct (rs#r); simpl in H0; try discriminate.\n  destruct (Int.eq_dec i Int.zero); try discriminate.\n  inv LD. \n  assert (find_function tge (inl _ r) rs' = Some (transf_fundef gapp f)).\n    simpl. rewrite <- H4. simpl. rewrite dec_eq_true. apply function_ptr_translated. auto.\n  destruct (D.get r approx); auto.\n  predSpec Int.eq Int.eq_spec i0 Int.zero; intros; auto.\n  simpl in *. unfold symbol_address in MATCH. rewrite symbols_preserved.\n  destruct (Genv.find_symbol ge i); try discriminate. \n  inv MATCH. apply function_ptr_translated; auto.\n  rewrite symbols_preserved. destruct (Genv.find_symbol ge i); try discriminate.\n  apply function_ptr_translated; auto.\nQed.\n\nLemma const_for_result_correct:\n  forall a op sp v m,\n  const_for_result a = Some op ->\n  val_match_approx ge sp a v ->\n  eval_operation tge sp op nil m = Some v.\nProof.\n  unfold const_for_result; intros. \n  destruct a; inv H; simpl in H0.\n  simpl. congruence.\n  destruct (generate_float_constants tt); inv H2.  simpl. congruence.\n  simpl. subst v. unfold symbol_address. rewrite symbols_preserved. auto.\n  simpl. congruence.\nQed.\n\nInductive match_pc (f: function) (app: D.t): nat -> node -> node -> Prop :=\n  | match_pc_base: forall n pc,\n      match_pc f app n pc pc\n  | match_pc_nop: forall n pc s pcx,\n      f.(fn_code)!pc = Some (Inop s) ->\n      match_pc f app n s pcx ->\n      match_pc f app (Datatypes.S n) pc pcx\n  | match_pc_cond: forall n pc cond args s1 s2 b,\n      f.(fn_code)!pc = Some (Icond cond args s1 s2) ->\n      eval_static_condition cond (approx_regs app args) = Some b ->\n      match_pc f app (Datatypes.S n) pc (if b then s1 else s2).\n\nLemma match_successor_rec:\n  forall f app n pc, match_pc f app n pc (successor_rec n f app pc).\nProof.\n  induction n; simpl; intros.\n  apply match_pc_base.\n  destruct (fn_code f)!pc as [i|] eqn:?; try apply match_pc_base.\n  destruct i; try apply match_pc_base.\n  eapply match_pc_nop; eauto. \n  destruct (eval_static_condition c (approx_regs app l)) as [b|] eqn:?.\n  eapply match_pc_cond; eauto.\n  apply match_pc_base.\nQed.\n\nLemma match_successor:\n  forall f app pc, match_pc f app num_iter pc (successor f app pc).\nProof.\n  unfold successor; intros. apply match_successor_rec.\nQed.\n\nSection BUILTIN_STRENGTH_REDUCTION.\nVariable app: D.t.\nVariable sp: val.\nVariable rs: regset.\nHypothesis MATCH: forall r, val_match_approx ge sp (approx_reg app r) rs#r.\n\nLemma annot_strength_reduction_correct:\n  forall targs args targs' args' eargs,\n  annot_strength_reduction app targs args = (targs', args') ->\n  eventval_list_match ge eargs (annot_args_typ targs) rs##args ->\n  exists eargs',\n  eventval_list_match ge eargs' (annot_args_typ targs') rs##args'\n  /\\ annot_eventvals targs' eargs' = annot_eventvals targs eargs.\nProof.\n  induction targs; simpl; intros.\n- inv H. simpl. exists eargs; auto. \n- destruct a.\n  + destruct args as [ | arg args0]; simpl in H0; inv H0.\n    destruct (annot_strength_reduction app targs args0) as [targs'' args''] eqn:E.\n    exploit IHtargs; eauto. intros [eargs'' [A B]].\n    assert (DFL:\n      exists eargs',\n      eventval_list_match ge eargs' (annot_args_typ (AA_arg ty :: targs'')) rs##(arg :: args'')\n      /\\ annot_eventvals (AA_arg ty :: targs'') eargs' = ev1 :: annot_eventvals targs evl).\n    {\n      exists (ev1 :: eargs''); split.\n      simpl; constructor; auto. simpl. congruence.\n    }\n    destruct ty; destruct (approx_reg app arg) as [] eqn:E2; inv H; auto;\n    exists eargs''; split; auto; simpl; f_equal; auto;\n    generalize (MATCH arg); rewrite E2; simpl; intros E3;\n    rewrite E3 in H5; inv H5; auto.\n  + destruct (annot_strength_reduction app targs args) as [targs'' args''] eqn:E.\n    inv H.\n    exploit IHtargs; eauto. intros [eargs'' [A B]].\n    exists eargs''; simpl; split; auto. congruence.\n  + destruct (annot_strength_reduction app targs args) as [targs'' args''] eqn:E.\n    inv H.\n    exploit IHtargs; eauto. intros [eargs'' [A B]].\n    exists eargs''; simpl; split; auto. congruence.\nQed.\n\nLemma builtin_strength_reduction_correct:\n  forall ef args m t vres m',\n  external_call ef ge rs##args m t vres m' ->\n  let (ef', args') := builtin_strength_reduction app ef args in\n  external_call ef' ge rs##args' m t vres m'.\nProof.\n  intros until m'. functional induction (builtin_strength_reduction app ef args); intros; auto.\n+ generalize (MATCH r1); rewrite e1; simpl; intros E. simpl in H.\n  unfold symbol_address in E. destruct (Genv.find_symbol ge symb) as [b|] eqn:?; rewrite E in H.\n  rewrite volatile_load_global_charact. exists b; auto. \n  inv H.\n+ generalize (MATCH r1); rewrite e1; simpl; intros E. simpl in H.\n  unfold symbol_address in E. destruct (Genv.find_symbol ge symb) as [b|] eqn:?; rewrite E in H.\n  rewrite volatile_store_global_charact. exists b; auto. \n  inv H.\n+ inv H. exploit annot_strength_reduction_correct; eauto.\n  intros [eargs' [A B]]. \n  rewrite <- B. econstructor; eauto. \nQed.\n\nEnd BUILTIN_STRENGTH_REDUCTION.\n\n(** The proof of semantic preservation is a simulation argument\n  based on \"option\" diagrams of the following form:\n<<\n                 n\n       st1 --------------- st2\n        |                   |\n       t|                   |t or (? and n' < n)\n        |                   |\n        v                   v\n       st1'--------------- st2'\n                 n'\n>>\n  The left vertical arrow represents a transition in the\n  original RTL code.  The top horizontal bar is the [match_states]\n  invariant between the initial state [st1] in the original RTL code\n  and an initial state [st2] in the transformed code.\n  This invariant expresses that all code fragments appearing in [st2]\n  are obtained by [transf_code] transformation of the corresponding\n  fragments in [st1].  Moreover, the values of registers in [st1]\n  must match their compile-time approximations at the current program\n  point.\n  These two parts of the diagram are the hypotheses.  In conclusions,\n  we want to prove the other two parts: the right vertical arrow,\n  which is a transition in the transformed RTL code, and the bottom\n  horizontal bar, which means that the [match_state] predicate holds\n  between the final states [st1'] and [st2']. *)\n\nInductive match_stackframes: stackframe -> stackframe -> Prop :=\n   match_stackframe_intro:\n      forall res sp pc rs f rs',\n      regs_lessdef rs rs' ->\n      (forall v, regs_match_approx sp (analyze gapp f)!!pc (rs#res <- v)) ->\n    match_stackframes\n        (Stackframe res f sp pc rs)\n        (Stackframe res (transf_function gapp f) sp pc rs').\n\nInductive match_states: nat -> state -> state -> Prop :=\n  | match_states_intro:\n      forall s sp pc rs m f s' pc' rs' m' app n\n           (MATCH1: regs_match_approx sp app rs)\n           (MATCH2: regs_match_approx sp (analyze gapp f)!!pc rs)\n           (GMATCH: mem_match_approx m)\n           (STACKS: list_forall2 match_stackframes s s')\n           (PC: match_pc f app n pc pc')\n           (REGS: regs_lessdef rs rs')\n           (MEM: Mem.extends m m'),\n      match_states n (State s f sp pc rs m)\n                    (State s' (transf_function gapp f) sp pc' rs' m')\n  | match_states_call:\n      forall s f args m s' args' m'\n           (GMATCH: mem_match_approx m)\n           (STACKS: list_forall2 match_stackframes s s')\n           (ARGS: Val.lessdef_list args args')\n           (MEM: Mem.extends m m'),\n      match_states O (Callstate s f args m)\n                    (Callstate s' (transf_fundef gapp f) args' m')\n  | match_states_return:\n      forall s v m s' v' m'\n           (GMATCH: mem_match_approx m)\n           (STACKS: list_forall2 match_stackframes s s')\n           (RES: Val.lessdef v v')\n           (MEM: Mem.extends m m'),\n      list_forall2 match_stackframes s s' ->\n      match_states O (Returnstate s v m)\n                    (Returnstate s' v' m').\n\nLemma match_states_succ:\n  forall s f sp pc2 rs m s' rs' m' pc1 i,\n  f.(fn_code)!pc1 = Some i ->\n  In pc2 (successors_instr i) ->\n  regs_match_approx sp (transfer gapp f pc1 (analyze gapp f)!!pc1) rs ->\n  mem_match_approx m ->\n  list_forall2 match_stackframes s s' ->\n  regs_lessdef rs rs' ->\n  Mem.extends m m' ->\n  match_states O (State s f sp pc2 rs m)\n                (State s' (transf_function gapp f) sp pc2 rs' m').\nProof.\n  intros. \n  assert (regs_match_approx sp (analyze gapp f)!!pc2 rs).\n    eapply analyze_correct_1; eauto.\n  apply match_states_intro with (app := (analyze gapp f)!!pc2); auto.\n  constructor.\nQed.\n\nLemma transf_instr_at:\n  forall f pc i,\n  f.(fn_code)!pc = Some i ->\n  (transf_function gapp f).(fn_code)!pc = Some(transf_instr gapp f (analyze gapp f) pc i).\nProof.\n  intros. simpl. unfold transf_code. rewrite PTree.gmap. rewrite H. auto. \nQed.\n\nLtac TransfInstr :=\n  match goal with\n  | H: (PTree.get ?pc (fn_code ?f) = Some ?instr) |- _ =>\n      generalize (transf_instr_at _ _ _ H); simpl\n  end.\n\n(** The proof of simulation proceeds by case analysis on the transition\n  taken in the source code. *)\n\nLemma transf_step_correct:\n  forall s1 t s2,\n  step ge s1 t s2 ->\n  forall n1 s1' (MS: match_states n1 s1 s1'),\n  (exists n2, exists s2', step tge s1' t s2' /\\ match_states n2 s2 s2')\n  \\/ (exists n2, n2 < n1 /\\ t = E0 /\\ match_states n2 s2 s1')%nat.\nProof.\n  induction 1; intros; inv MS; try (inv PC; try congruence).\n\n  (* Inop, preserved *)\n  rename pc'0 into pc. TransfInstr; intro.\n  left; econstructor; econstructor; split.\n  eapply exec_Inop; eauto.\n  eapply match_states_succ; eauto. simpl; auto.\n  unfold transfer; rewrite H. auto. \n\n  (* Inop, skipped over *)\n  rewrite H0 in H; inv H. \n  right; exists n; split. omega. split. auto.\n  apply match_states_intro with app; auto.\n  eapply analyze_correct_1; eauto. simpl; auto. \n  unfold transfer; rewrite H0. auto. \n\n  (* Iop *)\n  rename pc'0 into pc. TransfInstr.\n  set (app_before := (analyze gapp f)#pc).\n  set (a := eval_static_operation op (approx_regs app_before args)).\n  set (app_after := D.set res a app_before).\n  assert (VMATCH: val_match_approx ge sp a v).  \n    eapply eval_static_operation_correct; eauto.\n    apply approx_regs_val_list; auto.\n  assert (MATCH': regs_match_approx sp app_after rs#res <- v).\n    apply regs_match_approx_update; auto.\n  assert (MATCH'': regs_match_approx sp (analyze gapp f) # pc' rs # res <- v).\n    eapply analyze_correct_1 with (pc := pc); eauto. simpl; auto.\n    unfold transfer; rewrite H. auto.  \n  destruct (const_for_result a) as [cop|] eqn:?; intros.\n  (* constant is propagated *)\n  left; econstructor; econstructor; split.\n  eapply exec_Iop; eauto. \n  eapply const_for_result_correct; eauto.\n  apply match_states_intro with app_after; auto.\n  apply match_successor. \n  apply set_reg_lessdef; auto.\n  (* operator is strength-reduced *)\n  exploit op_strength_reduction_correct. eexact MATCH2. reflexivity. eauto. \n  fold app_before.\n  destruct (op_strength_reduction op args (approx_regs app_before args)) as [op' args'].\n  intros [v' [EV' LD']].\n  assert (EV'': exists v'', eval_operation ge sp op' rs'##args' m' = Some v'' /\\ Val.lessdef v' v'').\n  eapply eval_operation_lessdef; eauto. eapply regs_lessdef_regs; eauto.\n  destruct EV'' as [v'' [EV'' LD'']].\n  left; econstructor; econstructor; split.\n  eapply exec_Iop; eauto.\n  erewrite eval_operation_preserved. eexact EV''. exact symbols_preserved.\n  apply match_states_intro with app_after; auto.\n  apply match_successor.\n  apply set_reg_lessdef; auto. eapply Val.lessdef_trans; eauto.\n\n  (* Iload *)\n  rename pc'0 into pc. TransfInstr. \n  set (ap1 := eval_static_addressing addr\n               (approx_regs (analyze gapp f) # pc args)).\n  set (ap2 := eval_static_load gapp chunk ap1).\n  assert (VM1: val_match_approx ge sp ap1 a).\n    eapply eval_static_addressing_correct; eauto.\n    eapply approx_regs_val_list; eauto.\n  assert (VM2: val_match_approx ge sp ap2 v).\n    eapply eval_static_load_sound; eauto.\n  destruct (const_for_result ap2) as [cop|] eqn:?; intros.\n  (* constant-propagated *)\n  left; econstructor; econstructor; split.\n  eapply exec_Iop; eauto. eapply const_for_result_correct; eauto.\n  eapply match_states_succ; eauto. simpl; auto.\n  unfold transfer; rewrite H. apply regs_match_approx_update; auto.\n  apply set_reg_lessdef; auto.\n  (* strength-reduced *)\n  generalize (addr_strength_reduction_correct ge sp (analyze gapp f)!!pc rs\n                  MATCH2 addr args (approx_regs (analyze gapp f) # pc args) (refl_equal _)).\n  destruct (addr_strength_reduction addr args (approx_regs (analyze gapp f) # pc args)) as [addr' args'].\n  rewrite H0. intros P.\n  assert (ADDR': exists a', eval_addressing ge sp addr' rs'##args' = Some a' /\\ Val.lessdef a a').\n    eapply eval_addressing_lessdef; eauto. eapply regs_lessdef_regs; eauto.\n  destruct ADDR' as [a' [A B]].\n  assert (C: eval_addressing tge sp addr' rs'##args' = Some a').\n    rewrite <- A. apply eval_addressing_preserved. exact symbols_preserved.\n  exploit Mem.loadv_extends; eauto. intros [v' [D E]].\n  left; econstructor; econstructor; split.\n  eapply exec_Iload; eauto.\n  eapply match_states_succ; eauto. simpl; auto.\n  unfold transfer; rewrite H. apply regs_match_approx_update; auto.\n  apply set_reg_lessdef; auto.\n\n  (* Istore *)\n  rename pc'0 into pc. TransfInstr.\n  generalize (addr_strength_reduction_correct ge sp (analyze gapp f)!!pc rs\n                  MATCH2 addr args (approx_regs (analyze gapp f) # pc args) (refl_equal _)).\n  destruct (addr_strength_reduction addr args (approx_regs (analyze gapp f) # pc args)) as [addr' args'].\n  intros P Q. rewrite H0 in P.\n  assert (ADDR': exists a', eval_addressing ge sp addr' rs'##args' = Some a' /\\ Val.lessdef a a').\n    eapply eval_addressing_lessdef; eauto. eapply regs_lessdef_regs; eauto.\n  destruct ADDR' as [a' [A B]].\n  assert (C: eval_addressing tge sp addr' rs'##args' = Some a').\n    rewrite <- A. apply eval_addressing_preserved. exact symbols_preserved.\n  exploit Mem.storev_extends; eauto. intros [m2' [D E]].\n  left; econstructor; econstructor; split.\n  eapply exec_Istore; eauto.\n  eapply match_states_succ; eauto. simpl; auto.\n  unfold transfer; rewrite H. auto. \n  eapply mem_match_approx_store; eauto.\n\n  (* Icall *)\n  rename pc'0 into pc.\n  exploit transf_ros_correct; eauto. intro FIND'.\n  TransfInstr; intro.\n  left; econstructor; econstructor; split.\n  eapply exec_Icall; eauto. apply sig_function_translated; auto.\n  constructor; auto. constructor; auto.\n  econstructor; eauto. \n  intros. eapply analyze_correct_1; eauto. simpl; auto.\n  unfold transfer; rewrite H.\n  apply regs_match_approx_update; auto. simpl. auto.\n  apply regs_lessdef_regs; auto. \n\n  (* Itailcall *)\n  exploit Mem.free_parallel_extends; eauto. intros [m2' [A B]].\n  exploit transf_ros_correct; eauto. intros FIND'.\n  TransfInstr; intro.\n  left; econstructor; econstructor; split.\n  eapply exec_Itailcall; eauto. apply sig_function_translated; auto.\n  constructor; auto. \n  eapply mem_match_approx_free; eauto.\n  apply regs_lessdef_regs; auto. \n\n  (* Ibuiltin *)\n  rename pc'0 into pc.\nOpaque builtin_strength_reduction.\n  exploit builtin_strength_reduction_correct; eauto. \n  TransfInstr.\n  destruct (builtin_strength_reduction (analyze gapp f)#pc ef args) as [ef' args'].\n  intros P Q.\n  exploit external_call_mem_extends; eauto. \n  instantiate (1 := rs'##args'). apply regs_lessdef_regs; auto.\n  intros [v' [m2' [A [B [C D]]]]].\n  left; econstructor; econstructor; split.\n  eapply exec_Ibuiltin. eauto. \n  eapply external_call_symbols_preserved; eauto.\n  exact symbols_preserved. exact varinfo_preserved.\n  eapply match_states_succ; eauto. simpl; auto.\n  unfold transfer; rewrite H. \n  apply regs_match_approx_update; auto. simpl; auto.\n  eapply mem_match_approx_extcall; eauto. \n  apply set_reg_lessdef; auto.\n\n  (* Icond, preserved *)\n  rename pc'0 into pc. TransfInstr. \n  generalize (cond_strength_reduction_correct ge sp (analyze gapp f)#pc rs m\n                    MATCH2 cond args (approx_regs (analyze gapp f) # pc args) (refl_equal _)).\n  destruct (cond_strength_reduction cond args (approx_regs (analyze gapp f) # pc args)) as [cond' args'].\n  intros EV1 TCODE.\n  left; exists O; exists (State s' (transf_function gapp f) sp (if b then ifso else ifnot) rs' m'); split. \n  destruct (eval_static_condition cond (approx_regs (analyze gapp f) # pc args)) eqn:?.\n  assert (eval_condition cond rs ## args m = Some b0).\n    eapply eval_static_condition_correct; eauto. eapply approx_regs_val_list; eauto.\n  assert (b = b0) by congruence. subst b0.\n  destruct b; eapply exec_Inop; eauto. \n  eapply exec_Icond; eauto.\n  eapply eval_condition_lessdef with (vl1 := rs##args'); eauto. eapply regs_lessdef_regs; eauto. congruence.\n  eapply match_states_succ; eauto. \n  destruct b; simpl; auto.\n  unfold transfer; rewrite H. auto.\n\n  (* Icond, skipped over *)\n  rewrite H1 in H; inv H. \n  assert (eval_condition cond rs ## args m = Some b0).\n    eapply eval_static_condition_correct; eauto. eapply approx_regs_val_list; eauto.\n  assert (b = b0) by congruence. subst b0.\n  right; exists n; split. omega. split. auto. \n  assert (MATCH': regs_match_approx sp (analyze gapp f) # (if b then ifso else ifnot) rs).\n    eapply analyze_correct_1; eauto. destruct b; simpl; auto.\n    unfold transfer; rewrite H1; auto.\n  econstructor; eauto. constructor. \n\n  (* Ijumptable *)\n  rename pc'0 into pc.\n  assert (A: (fn_code (transf_function gapp f))!pc = Some(Ijumptable arg tbl)\n             \\/ (fn_code (transf_function gapp f))!pc = Some(Inop pc')).\n  TransfInstr. destruct (approx_reg (analyze gapp f) # pc arg) eqn:?; auto.\n  generalize (MATCH2 arg). unfold approx_reg in Heqt. rewrite Heqt. rewrite H0. \n  simpl. intro EQ; inv EQ. rewrite H1. auto.\n  assert (B: rs'#arg = Vint n).\n  generalize (REGS arg); intro LD; inv LD; congruence.\n  left; exists O; exists (State s' (transf_function gapp f) sp pc' rs' m'); split.\n  destruct A. eapply exec_Ijumptable; eauto. eapply exec_Inop; eauto.\n  eapply match_states_succ; eauto.\n  simpl. eapply list_nth_z_in; eauto.\n  unfold transfer; rewrite  H; auto.\n\n  (* Ireturn *)\n  exploit Mem.free_parallel_extends; eauto. intros [m2' [A B]].\n  left; exists O; exists (Returnstate s' (regmap_optget or Vundef rs') m2'); split.\n  eapply exec_Ireturn; eauto. TransfInstr; auto.\n  constructor; auto.\n  eapply mem_match_approx_free; eauto.\n  destruct or; simpl; auto. \n\n  (* internal function *)\n  exploit Mem.alloc_extends. eauto. eauto. apply Zle_refl. apply Zle_refl.\n  intros [m2' [A B]].\n  simpl. unfold transf_function.\n  left; exists O; econstructor; split.\n  eapply exec_function_internal; simpl; eauto.\n  simpl. econstructor; eauto.\n  apply analyze_correct_3; auto.\n  apply analyze_correct_3; auto.\n  eapply mem_match_approx_alloc; eauto.\n  instantiate (1 := f). constructor.\n  apply init_regs_lessdef; auto.\n\n  (* external function *)\n  exploit external_call_mem_extends; eauto. \n  intros [v' [m2' [A [B [C D]]]]].\n  simpl. left; econstructor; econstructor; split.\n  eapply exec_function_external; eauto.\n  eapply external_call_symbols_preserved; eauto.\n  exact symbols_preserved. exact varinfo_preserved.\n  constructor; auto.\n  eapply mem_match_approx_extcall; eauto.\n\n  (* return *)\n  inv H4. inv H1. \n  left; exists O; econstructor; split.\n  eapply exec_return; eauto. \n  econstructor; eauto. constructor. apply set_reg_lessdef; auto. \nQed.\n\nLemma transf_initial_states:\n  forall st1, initial_state prog st1 ->\n  exists n, exists st2, initial_state tprog st2 /\\ match_states n st1 st2.\nProof.\n  intros. inversion H.\n  exploit function_ptr_translated; eauto. intro FIND.\n  exists O; exists (Callstate nil (transf_fundef gapp f) nil m0); split.\n  econstructor; eauto.\n  apply Genv.init_mem_transf; auto.\n  replace (prog_main tprog) with (prog_main prog).\n  rewrite symbols_preserved. eauto.\n  reflexivity.\n  rewrite <- H3. apply sig_function_translated.\n  constructor. \n  eapply mem_match_approx_init; eauto.\n  constructor. constructor. apply Mem.extends_refl.\nQed.\n\nLemma transf_final_states:\n  forall n st1 st2 r, \n  match_states n 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(** The preservation of the observable behavior of the program then\n  follows. *)\n\nTheorem transf_program_correct:\n  forward_simulation (RTL.semantics prog) (RTL.semantics tprog).\nProof.\n  eapply Forward_simulation with (fsim_order := lt); simpl.\n  apply lt_wf. \n  eexact transf_initial_states.\n  eexact transf_final_states.\n  fold ge; fold tge. intros. \n    exploit transf_step_correct; eauto. \n    intros [ [n2 [s2' [A B]]] | [n2 [A [B C]]]].\n    exists n2; exists s2'; split; auto. left; apply plus_one; auto.\n    exists n2; exists s2; split; auto. right; split; auto. subst t; apply star_refl. \n  eexact symbols_preserved.\nQed.\n\nEnd PRESERVATION.\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/Constpropproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2924872933327721}}
{"text": "Require Import floyd.proofauto.\nRequire Import sha.sha.\nRequire Import sha.SHA256.\nRequire Import sha.sha_lemmas.\nRequire Import sha.bdo_lemmas.\nRequire Import sha.spec_sha.\nLocal Open Scope logic.\n\nLemma sha256_block_data_order_return:\n   forall (Espec : OracleKind) (hashed b : list int) (ctx data : val)\n            (sh : share) (regs : registers) kv,\n  Zlength b = LBLOCKz ->\n  (LBLOCKz | Zlength hashed) ->\n  regs = hash_blocks init_registers hashed ->\n  semax (initialized _t Delta_loop1)\n  (PROP  ()\n   LOCAL  (`(eq ctx) (eval_id _ctx);\n                `(eq kv) (eval_var _K256 (tarray tuint CBLOCKz)))\n   SEP \n   (`(array_at tuint Tsh (tuints (hash_block regs b)) 0 8 ctx);\n    `(K_vector kv);\n   `(array_at_ tuint Tsh 0 LBLOCKz) (eval_var _X (tarray tuint LBLOCKz));\n   `(data_block sh (intlist_to_Zlist b) data)))\n  (Sreturn None)\n  (frame_ret_assert\n     (function_body_ret_assert tvoid\n        (`(array_at tuint Tsh\n             (tuints (hash_blocks init_registers (hashed ++ b))) 0 8 ctx) *\n         `(data_block sh (intlist_to_Zlist b) data) *\n         `(K_vector kv)))\n     (stackframe_of f_sha256_block_data_order)).\nProof.\nintros.\nunfold Delta_loop1; simplify_Delta.\nforward. (* return; *)\nunfold frame_ret_assert; simpl.\nunfold sha256state_.\nset (regs := hash_block (hash_blocks init_registers hashed) b).\nunfold_lift.\nsimpl_stackframe_of.\nunfold data_at_.\nunfold tarray.\nerewrite data_at_array_at; [| reflexivity | omega | reflexivity].\nunfold id.\nentailer!.\napply derives_refl'; f_equal.\nf_equal.\nunfold regs.\napply hash_blocks_last; auto.\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_bdo2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2924872866867424}}
{"text": "From Coq Require Import String ZArith NArith Eqdep_dec List Lia.\n\nFrom Coq Require PropExtensionality.\n\nFrom Vyper Require Import Config Calldag L10.Base.\nFrom Vyper Require L20.AST L20.Expr L30.AST L20.Interpret L30.Interpret.\n\nFrom Vyper.From20To30 Require Import Translate Callset FunCtx Expr Stmt.\n\nLemma nodup_app {A: Type} (EqDec: forall x y: A, {x = y} + {x <> y})\n                {a b: list A}\n                (NA: NoDup a)\n                (NB: NoDup b)\n                (Disjoint: forall x,\n                             (ListSet.set_mem EqDec x a && ListSet.set_mem EqDec x b = false)%bool):\n  NoDup (a ++ b).\nProof.\ninduction a as [|ha]. { apply NB. }\ncbn. constructor.\n{ (* ~ In ha (a ++ b) *)\n  rewrite in_app_iff.\n  intro H. case H; clear H; intro H.\n  { now inversion NA. }\n  assert (Q := Disjoint ha).\n  cbn in Q. destruct EqDec. 2:tauto.\n  rewrite Bool.andb_true_l in Q.\n  now rewrite ListSet2.set_mem_false in Q.\n}\napply IHa. { now inversion NA. }\nintro x.\nassert (U := Disjoint x).\ncbn in U.\ndestruct EqDec. 2:assumption.\nnow destruct (ListSet.set_mem EqDec x a).\nQed.\n\nLemma nodup_app_elim_r {A: Type} (EqDec: forall x y: A, {x = y} + {x <> y})\n                       {a b: list A}\n                       (H: NoDup (a ++ b)):\n  NoDup b.\nProof.\ninduction a as [|ha]. { apply H. }\ncbn in H. apply IHa. inversion H. assumption.\nQed.\n\nLemma nodup_disjoint {A: Type} (EqDec: forall x y: A, {x = y} + {x <> y})\n                     {a b: list A}\n                     (H: NoDup (a ++ b))\n                     (x: A):\n  (ListSet.set_mem EqDec x a && ListSet.set_mem EqDec x b = false)%bool.\nProof.\ninduction a as [|ha]. { easy. }\ncbn.\ndestruct (EqDec x ha). 2:{ inversion H. tauto. }\nsubst x.\nrewrite Bool.andb_true_l.\nrewrite ListSet2.set_mem_false.\ncbn in H.\nassert (W: ~ In ha (a ++ b)) by now inversion H.\nrewrite in_app_iff in W. tauto.\nQed.\n\nLemma alist_set_mem {A B: Type} (EqDec: forall x y: A, {x = y} + {x <> y})\n                    (x: A) (alist: list (A * B)):\n  ListSet.set_mem EqDec x (map fst alist)\n   =\n  match Map.alist_lookup EqDec alist x with\n  | Some _ => true\n  | None => false\n  end.\nProof.\ninduction alist. { easy. }\ncbn. rewrite IHalist.\ndestruct a as (k, v). cbn.\nnow destruct (EqDec x k).\nQed.\n\n(** [make_varmap] builds a varmap successfully if there's no duplicate variable name. *)\nLemma varmap_if_nodup {C: VyperConfig}\n                      (names: list string)\n                      (ND: NoDup names)\n                      (err: string):\n  make_varmap names <> inl err.\nProof.\nunfold make_varmap.\npose (empty  := @Map.empty  string string_dec N (@string_map C N) (@string_map_impl C N)).\npose (items  := @Map.items  string string_dec N (@string_map C N) (@string_map_impl C N)).\npose (insert := @Map.insert string string_dec N (@string_map C N) (@string_map_impl C N)).\nfold empty.\nassert (ND': NoDup (map fst (items empty) ++ names)).\n{ unfold empty. unfold items. rewrite Map.empty_items. cbn. exact ND. }\nenough (H: forall m n,\n             NoDup (map fst (items m) ++ names)\n              ->\n             make_varmap_rec m n names <> inl err).\n{ apply H. apply ND'. }\nclear ND ND'.\ninduction names; intros m n H. { easy. }\ncbn.\nrewrite Map.items_ok.\ndestruct (NoDup_remove _ _ _ H) as (H', NotIn).\nrewrite in_app_iff in NotIn.\nrewrite Map.alist_lookup_not_in by tauto.\napply IHnames.\n(* goal: NoDup (map fst (items (Map.insert m a n)) ++ names) *)\napply (nodup_app string_dec).\n{ apply Map.items_nodup. }\n{ apply (nodup_app_elim_r string_dec H'). }\n(* disjoint *)\nintro x.\nassert (D := nodup_disjoint string_dec H x).\ncbn in D.\nassert (F: ListSet.set_mem string_dec x (map fst (items (insert m a n)))\n            =\n           if string_dec x a then true else ListSet.set_mem string_dec x (map fst (items m))).\n{\n  repeat rewrite alist_set_mem. unfold items. repeat rewrite<- Map.items_ok.\n  unfold insert. rewrite Map.insert_ok.\n  destruct (string_dec a x), (string_dec x a); now subst.\n}\nfold insert. rewrite F. clear F.\ndestruct (ListSet.set_mem string_dec x (map fst (items m))), (string_dec x a); try easy.\nrewrite Bool.andb_true_l.\nrewrite ListSet2.set_mem_false.\nsubst x. tauto.\nQed.\n\nLemma varmap_rec_not_in {C: VyperConfig}\n                        (a: string)\n                        (names: list string)\n                        (m: string_map N)\n                        (init: N)\n                        (L: let _ := string_map_impl in Map.lookup m a <> None)\n                        (Ok: forall err, make_varmap_rec m init names <> inl err):\n  ~ In a names.\nProof.\npose (insert := @Map.insert string string_dec N (@string_map C N) (@string_map_impl C N)).\nrevert m init L Ok. induction names as [|head]; intros. { easy. }\ncbn in *.\nremember (Map.lookup m head) as m_head. destruct m_head.\n{ exfalso. exact (Ok _ eq_refl). }\nassert (NE: head <> a).\n{ intro. subst. rewrite<- Heqm_head in L. tauto. }\nenough (~ In a names) by tauto.\napply (IHnames (insert m head init) (N.succ init)).\n2: apply Ok.\nunfold insert.\nrewrite Map.insert_ok.\nnow destruct (string_dec head a).\nQed.\n\nLemma varmap_rec_cons {C: VyperConfig}\n                      (head: string)\n                      (tail: list string)\n                      (m: string_map N)\n                      (init: N)\n                      (Ok: forall err, make_varmap_rec m init (head :: tail) <> inl err):\n  ~ In head tail.\nProof.\ncbn in Ok.\ndestruct (Map.lookup m head). { exfalso. exact (Ok _ eq_refl). }\nrefine (varmap_rec_not_in head tail _ _ _ Ok).\ncbn. rewrite Map.insert_ok.\nnow destruct (string_dec head head).\nQed.\n\n(** If [make_varmap names] finished successfully, then there's no duplicates in [names]. *)\nLemma varmap_nodup {C: VyperConfig}\n                   (names: list string)\n                   (Ok: forall err, make_varmap names <> inl err):\n  NoDup names.\nProof.\nunfold make_varmap in Ok.\npose (empty  := @Map.empty  string string_dec N (@string_map C N) (@string_map_impl C N)).\npose (items  := @Map.items  string string_dec N (@string_map C N) (@string_map_impl C N)).\npose (insert := @Map.insert string string_dec N (@string_map C N) (@string_map_impl C N)).\npose (lookup := @Map.lookup string string_dec N (@string_map C N) (@string_map_impl C N)).\nfold empty in Ok.\nenough (H: forall (m: string_map N)\n               (init: N)\n               (Disjoint: forall x,\n                            match lookup m x with\n                            | Some _ => ~ In x names\n                            | None => True\n                            end)\n               (Success: forall err, make_varmap_rec m init names <> inl err),\n            NoDup names).\n{\n  apply (H empty 0%N); try assumption.\n  unfold lookup. unfold empty. intro x. now rewrite Map.empty_lookup.\n}\nclear Ok.\ninduction names. { constructor. }\nintros.\nassert (V := varmap_rec_cons a names m init Success).\ncbn in Success.\nremember (Map.lookup m a) as ma.\ndestruct ma. { exfalso. exact (Success \"duplicate argument name\"%string eq_refl). }\nconstructor. { exact V. }\nrefine (IHnames (insert m a init) (N.succ init) _ Success).\nintro x.\nunfold lookup in *. unfold insert. rewrite Map.insert_ok.\ncbn in Disjoint. assert (Dx := Disjoint x).\ndestruct (string_dec a x). { now subst. }\ndestruct (Map.lookup m x); tauto.\nQed.\n\n\n(** Given that [names] and [values] have the same length and there is no duplication in [names],\n    [bind_args] computes successfully and returns a map that is only defined on strings from [names].\n *)\nLemma bind_args_domain_if_nodup {C: VyperConfig}\n                                (names: list string)\n                                (values: list uint256)\n                                (SameLen: length names = length values)\n                                (ND: NoDup names):\n  let _ := string_map_impl in\n  match L10.Interpret.bind_args names values with\n  | inl err => False\n  | inr m => forall x,\n               match Map.lookup m x with\n               | None => ~ In x names\n               | Some _ => In x names\n               end\n  end.\nProof.\nrevert values SameLen. induction names, values; try easy.\n{ cbn. intro H. clear H. intro x. now rewrite Map.empty_lookup. }\ncbn. intro SameLen'.\nassert (L: length names = length values) by now inversion SameLen'. clear SameLen'.\nassert (ND_names: NoDup names) by now inversion ND.\nassert (IH := IHnames ND_names values L).\ndestruct (Interpret.bind_args names values). { exact IH. }\nassert (A := IH a). destruct (Map.lookup s a). { now inversion ND. }\nintro x.\nassert (X := IH x). rewrite Map.insert_ok.\ndestruct (string_dec a x). { now left. }\ndestruct Map.lookup; tauto.\nQed.\n\n(** This is a variant of [bind_args_domain_if_nodup] but it directly assumes\n    successful completion of [bind_args] instead of preconditions. *)\nLemma bind_args_domain {C: VyperConfig}\n                   (names: list string)\n                   (values: list uint256)\n                   (loc: string_map uint256)\n                   (Ok: L10.Interpret.bind_args names values = inr loc):\n  let _ := string_map_impl in\n     forall x,\n       match Map.lookup loc x with\n       | None => ~ In x names\n       | Some _ => In x names\n       end.\nProof.\nrevert values loc Ok. induction names as [|head_name], values as [|head_value]; try easy; intros.\n{ cbn in *. inversion Ok. subst. now rewrite Map.empty_lookup. }\ncbn in *.\nremember (Interpret.bind_args names values) as loc'. destruct loc' as [|loc']. { discriminate. }\nassert (IH := IHnames _ _ (eq_sym Heqloc') x).\ndestruct (Map.lookup loc' head_name). { discriminate. }\ninversion Ok. subst. rewrite Map.insert_ok.\ndestruct (string_dec head_name x).\n{ subst. left. trivial. }\ndestruct (Map.lookup loc' x); tauto.\nQed.\n\nLemma bind_args_lt {C: VyperConfig}\n                   (names: list string)\n                   (values: list uint256)\n                   (L: length names < length values)\n                   (ND: NoDup names):\n   L10.Interpret.bind_args names values = inl \"function called with too many arguments\"%string.\nProof.\nrevert values L. induction names, values; intros; try easy.\ncbn.\nassert (ND': NoDup names) by now inversion ND.\ncbn in L. apply lt_S_n in L.\nnow rewrite (IHnames ND' values L).\nQed.\n\nLemma bind_args_gt {C: VyperConfig}\n                   (names: list string)\n                   (values: list uint256)\n                   (G: length values < length names)\n                   (ND: NoDup names):\n   L10.Interpret.bind_args names values = inl \"function called with too few arguments\"%string.\nProof.\nrevert values G. induction names, values; intros; try easy.\ncbn.\nassert (ND': NoDup names) by now inversion ND.\ncbn in G. apply gt_S_n in G.\nnow rewrite (IHnames ND' values G).\nQed.\n\nLemma bind_args_nodup {C: VyperConfig}\n                      (names: list string)\n                      (values: list uint256)\n                      (loc: string_map uint256)\n                      (Ok: L10.Interpret.bind_args names values = inr loc):\n  NoDup names.\nProof.\nrevert values loc Ok. induction names as [|head_name], values as [|head_value]; intros; try easy.\n{ constructor. }\ncbn in Ok.\nremember (Interpret.bind_args names values) as loc'. destruct loc' as [|loc']; try discriminate.\nremember (Map.lookup loc' head_name) as loc'_head. destruct loc'_head; try discriminate.\nconstructor.\n{\n  assert (D := bind_args_domain _ _ _ (eq_sym Heqloc') head_name).\n  now rewrite<- Heqloc'_head in D.\n}\nexact (IHnames values loc' (eq_sym Heqloc')).\nQed.\n\nLemma bind_args_same_len {C: VyperConfig}\n                         (names: list string)\n                         (values: list uint256)\n                         (loc: string_map uint256)\n                         (Ok: L10.Interpret.bind_args names values = inr loc):\n  length names = length values.\nProof.\nassert (T := Nat.lt_trichotomy (length names) (length values)).\ncase T; clear T; intro T.\n{\n  rewrite bind_args_lt in Ok. { discriminate. } { assumption. }\n  apply (bind_args_nodup _ _ _ Ok).\n}\ncase T; clear T; intro T. { assumption. }\nrewrite bind_args_gt in Ok. { discriminate. } { assumption. }\napply (bind_args_nodup _ _ _ Ok).\nQed.\n\nLemma varmap_rec_ok {C: VyperConfig}\n                    (names: list string)\n                    (varmap: string_map N)\n                    (m: string_map N)\n                    (init: N)\n                    (Bound: VarsBound m init)\n                    (Inj: VarmapInj m)\n                    (Ok: make_varmap_rec m init names = inr varmap):\n  VarmapInj varmap /\\ VarsBound varmap (init + N.of_nat (length names))%N.\nProof.\npose (empty  := @Map.empty  string string_dec N (@string_map C N) (@string_map_impl C N)).\npose (insert := @Map.insert string string_dec N (@string_map C N) (@string_map_impl C N)).\npose (lookup := @Map.lookup string string_dec N (@string_map C N) (@string_map_impl C N)).\nrevert m init Bound Inj Ok. induction names; cbn; intros.\n{\n  assert (m = varmap) by now inversion Ok.\n  subst varmap. rewrite N.add_0_r. tauto.\n}\nremember (Map.lookup m a) as ma. destruct ma. { discriminate. }\nreplace (init + N.pos (Pos.of_succ_nat (Datatypes.length names)))%N\n   with (N.succ init + N.of_nat (Datatypes.length names))%N by lia.\nrefine (IHnames (insert m a init) (N.succ init) _ _ Ok).\n{\n  (* VarsBound (insert m a init) (N.succ init) *)\n  intro x.\n  unfold insert. rewrite Map.insert_ok.\n  assert (B := Bound x).\n  destruct (string_dec a x). { apply N.lt_succ_diag_r. }\n  destruct (Map.lookup m x) as [k|]. 2:trivial.\n  lia.\n}\nintros x y.\nunfold insert. repeat rewrite Map.insert_ok.\ndestruct (string_dec a x).\n{\n  destruct (string_dec a y). { now subst. }\n  assert (B := Bound y).\n  destruct (Map.lookup m y) as [k|]. 2:trivial.\n  intro H. lia.\n}\ndestruct (string_dec a y).\n{\n  assert (B := Bound x).\n  destruct (Map.lookup m x) as [k|]. 2:trivial.\n  intro H. lia.\n}\napply Inj.\nQed.\n\nLemma varmap_ok {C: VyperConfig}\n                (names: list string)\n                (varmap: string_map N)\n                (Ok: make_varmap names = inr varmap):\n  VarmapInj varmap /\\ VarsBound varmap (N.of_nat (length names))%N.\nProof.\nunfold make_varmap in *.\npose (empty  := @Map.empty  string string_dec N (@string_map C N) (@string_map_impl C N)).\nassert (R := varmap_rec_ok names varmap empty 0%N).\ncbn in R. apply R.\n{ (* VarsBound empty 0 *) intro x. unfold empty. now rewrite Map.empty_lookup. }\n{ (* VarmapInj empty *) intros x y. unfold empty. now rewrite Map.empty_lookup. }\napply Ok.\nQed.\n\nLemma varmap_rec_mono {C: VyperConfig}\n                      (names: list string)\n                      (m varmap: string_map N)\n                      (init: N)\n                      (VarmapOk: make_varmap_rec m init names = inr varmap)\n                      (x: string):\n  let _ := string_map_impl in\n  match Map.lookup m x with\n  | Some y => Map.lookup varmap x = Some y\n  | None => True\n  end.\nProof.\nrevert m init VarmapOk.\ninduction names as [|head]; intros; cbn in *.\n{ inversion VarmapOk. subst varmap. now destruct Map.lookup. }\nremember (Map.lookup m head) as m_head. destruct m_head. { discriminate. }\nassert (IH := IHnames _ _ VarmapOk).\nrewrite Map.insert_ok in IH.\ndestruct (string_dec head x).\n{ subst. now destruct (Map.lookup m x). }\napply IH.\nQed.\n\nLocal Lemma varmap_rec_index {C: VyperConfig}\n                             (names: list string)\n                             (m varmap: string_map N)\n                             (init: N)\n                             (VarmapOk: make_varmap_rec m init names = inr varmap)\n                             (x: string):\n  let _ := string_map_impl in\n  match Map.lookup m x, Map.lookup varmap x with\n  | None, Some index => (init <= index)%N /\\ nth_error names (N.to_nat (index - init)%N) = Some x\n  | _, _ => ~ In x names\n  end.\nProof.\nrevert m varmap init VarmapOk x. induction names as [|head]; intros; cbn in *.\n{\n  inversion VarmapOk; subst varmap.\n  now destruct (Map.lookup m x).\n}\nremember (Map.lookup m head) as m_head. destruct m_head. { discriminate. }\nassert (IH := IHnames _ _ _ VarmapOk x).\nrewrite Map.insert_ok in IH.\ndestruct (string_dec head x).\n{\n  subst head.\n  destruct (Map.lookup m x). { discriminate. }\n  assert (V := varmap_rec_mono _ _ _ _ VarmapOk x).\n  cbn in V. rewrite Map.insert_ok in V.\n  destruct (string_dec x x). 2:tauto.\n  destruct (Map.lookup varmap x). 2:discriminate.\n  inversion V. subst.\n  rewrite N.sub_diag.\n  split. { lia. }\n  trivial.\n}\ndestruct (Map.lookup m x). { tauto. }\ndestruct (Map.lookup varmap x) as [k|]. 2:tauto.\nremember (N.to_nat (k - N.succ init)) as a.\nremember (N.to_nat (k - init)) as b.\ndestruct IH as (Bound, E).\nassert (B: b = S a) by lia.\nrewrite B.\ncbn.\nsplit. 2:assumption.\nlia.\nQed.\n\n(** If [make_varmap] finishes succesfully, the result maps a name to its index in the [names] list. *)\nLemma varmap_index {C: VyperConfig}\n                   (names: list string)\n                   (varmap: string_map N)\n                   (VarmapOk: make_varmap names = inr varmap)\n                   (x: string):\n  let _ := string_map_impl in\n  match Map.lookup varmap x with\n  | Some index => nth_error names (N.to_nat index) = Some x\n  | None => ~ In x names\n  end.\nProof.\nunfold make_varmap in VarmapOk.\ncbn.\nassert (R := varmap_rec_index _ _ _ _ VarmapOk x). cbn in R.\nrewrite Map.empty_lookup in R.\ndestruct (Map.lookup varmap x). 2:tauto.\nrewrite N.sub_0_r in R.\ntauto.\nQed.\n\nLemma bind_args_index {C: VyperConfig}\n                      (names: list string)\n                      (values: list uint256)\n                      (loc: string_map uint256)\n                      (LocOk: L10.Interpret.bind_args names values = inr loc)\n                      (index: nat)\n                      (x: string)\n                      (Ok: nth_error names index = Some x):\n  let _ := string_map_impl in\n  Map.lookup loc x = nth_error values index.\nProof.\ncbn. revert index values loc LocOk Ok.\ninduction names as [|head_name], values as [|head_value]; intros; try easy.\n{\n  assert (Oops: index < @length string nil).\n  { apply nth_error_Some. intro H. rewrite H in Ok. discriminate. }\n  cbn in Oops.\n  now apply Nat.nlt_0_r in Oops.\n}\nassert (F := bind_args_nodup _ _ _ LocOk).\ncbn in LocOk.\nremember (Interpret.bind_args names values) as loc'.\ndestruct loc' as [|loc']. { discriminate. }\nremember (Map.lookup loc' head_name) as loc'_head. destruct loc'_head. { discriminate. }\nsymmetry in Heqloc'.\ninversion LocOk. subst.\nrewrite Map.insert_ok.\ndestruct index as [|index'].\n{\n  cbn in *. inversion Ok. subst.\n  destruct (string_dec x x); tauto.\n}\ncbn in *.\nrewrite<- (IHnames _ _ _ Heqloc' Ok).\ndestruct (string_dec head_name x). 2:trivial.\nsubst.\napply nth_error_In in Ok.\ninversion F. contradiction.\nQed.\n\nLemma bind_varmap_agree {C: VyperConfig}\n                        (names: list string)\n                        (values: list uint256)\n                        (varmap: string_map N)\n                        (loc: string_map uint256)\n                        (VarmapOk: make_varmap names = inr varmap)\n                        (LocOk: L10.Interpret.bind_args names values = inr loc):\n  let _ := memory_impl in\n  VarsAgree varmap loc (OpenArray.from_list values).\nProof.\ncbn. intro x.\nassert (V := varmap_index _ _ VarmapOk x). cbn in V.\nassert (D := bind_args_domain _ _ _ LocOk x).\nremember (Map.lookup varmap x) as varmap_x.\ndestruct varmap_x. 2:now destruct (Map.lookup loc x).\nrewrite OpenArray.from_list_ok.\nassert (W := bind_args_index _ _ _ LocOk _ _ V). cbn in W.\nrewrite W in *.\nassert (L := bind_args_same_len _ _ _ LocOk).\nassert (BN: N.to_nat n < length names).\n{ apply nth_error_Some. rewrite V. discriminate. }\nassert (BV: N.to_nat n < length values). { rewrite<- L. apply BN. }\nremember (nth_error values (N.to_nat n)) as z. symmetry in Heqz. destruct z.\n2:{ apply nth_error_Some in BV. contradiction. }\napply nth_error_nth with (d := uint256_of_Z 0) in Heqz. exact Heqz.\nQed.\n\nLemma interpret_translated_call {C: VyperConfig}\n                                (builtins: string -> option builtin)\n                                {cd20: L20.Descend.calldag}\n                                {call_depth_bound: nat}\n                                (fc: fun_ctx cd20 call_depth_bound)\n                                {cd30: L30.Descend.calldag}\n                                (ok: translate_calldag cd20 = inr cd30)\n                                (world: world_state)\n                                (arg_values: list uint256):\n  L30.Interpret.interpret_call builtins (translate_fun_ctx fc ok) world arg_values\n   =\n  L20.Interpret.interpret_call builtins fc world arg_values.\nProof.\nrevert world arg_values. induction call_depth_bound.\n{ exfalso. exact (Nat.nlt_0_r _ (proj1 (Nat.ltb_lt _ _) (fun_bound_ok fc))). }\nassert(F: inr (cached_translated_decl fc ok)\n           =\n          translate_decl (fun_decl fc)).\n{\n  clear IHcall_depth_bound.\n  unfold translate_fun_ctx in *. cbn in *.\n  unfold cached_translated_decl in *.\n  remember (FunCtx.translate_fun_ctx_fun_decl_helper fc ok) as foo. clear Heqfoo.\n  remember (cd_declmap cd30 (fun_name fc)) as d.\n  destruct d. 2:{ contradiction. }\n  subst.\n  assert (Q := translate_fun_ctx_declmap ok (fun_name fc)).\n  destruct (cd_declmap cd30 (fun_name fc)) as [d'|]. 2:discriminate.\n  inversion Heqd. subst d'. clear Heqd.\n  remember (cd_declmap cd20 (fun_name fc)) as x.\n  destruct x as [x|]. 2:discriminate.\n  inversion Q. f_equal.\n  assert (D := fun_decl_ok fc).\n  rewrite D in *. inversion Heqx.\n  trivial.\n}\nintros.\ncbn.\nremember (fun name arity body\n              (E: cached_translated_decl fc ok = AST.FunDecl name arity body) =>\n          if Datatypes.length arg_values =? N.to_nat arity\n          then\n           let\n           '(world', _, result) :=\n            Stmt.interpret_stmt eq_refl (translate_fun_ctx fc ok) (Interpret.interpret_call builtins)\n              builtins world (OpenArray.from_list arg_values) body (Interpret.interpret_call_helper E) in\n            (world', _)\n          else (world,\n     expr_error\n       (if match N.to_nat arity with\n           | 0 => false\n           | S m' => Datatypes.length arg_values <=? m'\n           end\n        then \"function called with too few arguments\"%string\n        else \"function called with too many arguments\"%string))) as branch_30.\nremember (fun name arg_names body\n              (E : fun_decl fc = L20.AST.FunDecl name arg_names body) =>\n            match Interpret.bind_args arg_names arg_values with\n            | inl err => (world, expr_error err)\n            | inr loc =>\n                let\n                '(world', _, result) :=\n                 L20.Stmt.interpret_stmt eq_refl fc (L20.Interpret.interpret_call builtins) builtins world loc\n                   body (L20.Interpret.interpret_call_helper E) in\n                 (world', _)\n            end) as branch_20.\nassert (B: forall name arg_names body30 body20 E30 E20,\n             branch_30 name (N.of_nat (List.length arg_names)) body30 E30\n              =\n             branch_20 name arg_names body20 E20).\n{\n  intros. subst. rewrite Nat2N.id. rewrite E20 in F. rewrite E30 in F. cbn in F.\n  remember (make_varmap arg_names) as maybe_varmap.\n  destruct maybe_varmap as [err|varmap]. { discriminate. }\n  (* argument names have no duplication because translation would have failed *)\n  assert (ND: NoDup arg_names).\n  { apply varmap_nodup. intro err. rewrite<- Heqmaybe_varmap. discriminate. }\n\n  (* arity check *)\n  assert (T := Nat.lt_trichotomy (length arg_names) (length arg_values)).\n  case T; clear T; intro T.\n  {\n    replace (length arg_values =? length arg_names) with false.\n    2:{ symmetry. rewrite Nat.eqb_neq. apply Nat.neq_sym. apply Nat.lt_neq. exact T. }\n    replace (match length arg_names with\n             | 0 => false\n             | S m' => length arg_values <=? m'\n             end) with (length arg_values <? length arg_names) by trivial.\n    replace (length arg_values <? length arg_names) with false.\n    2:{ symmetry. rewrite Nat.ltb_ge. apply Nat.lt_le_incl. exact T. }\n    now rewrite (bind_args_lt _ _ T ND).\n  }\n  case T; clear T; intro T.\n  2:{\n    replace (length arg_values =? length arg_names) with false.\n    2:{ symmetry. rewrite Nat.eqb_neq. apply Nat.lt_neq. exact T. }\n    replace (match length arg_names with\n         | 0 => false\n         | S m' => length arg_values <=? m'\n         end) with (length arg_values <? length arg_names) by trivial.\n    assert (G := T).\n    rewrite<- Nat.ltb_lt in T. rewrite T.\n    now rewrite (bind_args_gt _ _ G ND).\n  }\n  assert (SameLen := T).\n  symmetry in T. rewrite<- Nat.eqb_eq in T. rewrite T. clear T.\n\n  assert (BindArgsOk := bind_args_domain_if_nodup arg_names arg_values SameLen ND).\n  remember (Interpret.bind_args arg_names arg_values) as loc.\n  destruct loc as [err|loc]. { contradiction. }\n  destruct (varmap_ok arg_names varmap (eq_sym Heqmaybe_varmap)) as (Inj, Bound).\n  remember (translate_stmt varmap (N.of_nat (Datatypes.length arg_names)) body20) as body30'.\n  destruct body30'. { discriminate. }\n  inversion F. subst.\n  assert (IS := interpret_translated_stmt eq_refl builtins fc ok\n                                          IHcall_depth_bound world loc\n                                          (OpenArray.from_list arg_values)\n                                          varmap Inj _\n                                          (bind_varmap_agree _ _ _ _\n                                            (eq_sym Heqmaybe_varmap)\n                                            (eq_sym Heqloc))\n                                          Bound\n                                          (eq_sym Heqbody30')\n                                          (L30.Interpret.interpret_call_helper E30)\n                                          (L20.Interpret.interpret_call_helper E20)).\n  cbn in IS.\n  destruct L30.Stmt.interpret_stmt as ((world30, mem30), result30).\n  destruct L20.Stmt.interpret_stmt as ((world20, loc20), result20).\n  destruct IS as (R, (W, Agree)).\n  subst.\n  trivial.\n}\nclear Heqbranch_20. clear Heqbranch_30.\ndestruct (fun_decl fc); cbn in F.\n{ (* [fun_decl fc] is a global var *) now destruct cached_translated_decl. }\ndestruct (make_varmap args). { discriminate. }\ndestruct (translate_stmt s (N.of_nat (Datatypes.length args)) body). { discriminate. }\ninversion F.\ndestruct (cached_translated_decl fc ok). { discriminate. }\ninversion H0 (* XXX *). subst.\napply B.\nQed.\n\nLemma make_fun_ctx_and_bound_ok {C: VyperConfig}\n                                (cd20: L20.Descend.calldag)\n                                (cd30: L30.Descend.calldag)\n                                (Ok: translate_calldag cd20 = inr cd30)\n                                (fun_name: string):\n   make_fun_ctx_and_bound cd30 fun_name\n    =\n   match make_fun_ctx_and_bound cd20 fun_name with\n   | Some (existT _ bound fc) => Some (existT _ bound (translate_fun_ctx fc Ok))\n   | None => None\n   end.\nProof.\n(* this is too complicated due to destructing convoys *)\nunfold make_fun_ctx_and_bound.\nremember (fun d (Ed : cd_declmap cd30 fun_name = Some d) =>\n    match\n      cd_depthmap cd30 fun_name as depth'\n      return (cd_depthmap cd30 fun_name = depth' -> option {bound : nat & fun_ctx cd30 bound})\n    with\n    | Some depth =>\n        fun Edepth : cd_depthmap cd30 fun_name = Some depth =>\n        Some\n          (existT (fun bound : nat => fun_ctx cd30 bound) (S depth)\n             {|\n             fun_name := fun_name;\n             fun_depth := depth;\n             fun_depth_ok := Edepth;\n             fun_decl := d;\n             fun_decl_ok := Ed;\n             fun_bound_ok := proj2 (Nat.ltb_lt depth (S depth)) (Nat.lt_succ_diag_r depth) |})\n    | None =>\n        fun Edepth : cd_depthmap cd30 fun_name = None =>\n        False_rect (option {bound : nat & fun_ctx cd30 bound}) (Calldag.make_fun_ctx_helper Ed Edepth)\n    end eq_refl) as lhs_some_branch.\nremember (fun d (Ed : cd_declmap cd20 fun_name = Some d) =>\n      match\n        cd_depthmap cd20 fun_name as depth'\n        return (cd_depthmap cd20 fun_name = depth' -> option {bound : nat & fun_ctx cd20 bound})\n      with\n      | Some depth =>\n          fun Edepth : cd_depthmap cd20 fun_name = Some depth =>\n          Some\n            (existT (fun bound : nat => fun_ctx cd20 bound) (S depth)\n               {|\n               fun_name := fun_name;\n               fun_depth := depth;\n               fun_depth_ok := Edepth;\n               fun_decl := d;\n               fun_decl_ok := Ed;\n               fun_bound_ok := proj2 (Nat.ltb_lt depth (S depth)) (Nat.lt_succ_diag_r depth) |})\n      | None =>\n          fun Edepth : cd_depthmap cd20 fun_name = None =>\n          False_rect (option {bound : nat & fun_ctx cd20 bound})\n            (Calldag.make_fun_ctx_helper Ed Edepth)\n      end eq_refl) as rhs_some_branch.\nenough (SomeBranchOk: forall d30 d20 Ed30 Ed20\n                             (DeclOk: translate_decl d20 = inr d30),\n                        lhs_some_branch d30 Ed30\n                         =\n                        match rhs_some_branch d20 Ed20 with\n                        | Some (existT _ bound fc) =>\n                            Some\n                              (existT _ bound\n                                 (translate_fun_ctx fc Ok))\n                        | None => None\n                        end).\n{\n  cbn in *.\n  remember (fun _: _ = None => None) as lhs_none_branch.\n  assert (NoneBranchOk: forall E, lhs_none_branch E = None).\n  { subst. trivial. }\n  clear Heqlhs_some_branch Heqrhs_some_branch Heqlhs_none_branch.\n  assert (T := translate_fun_ctx_declmap Ok fun_name).\n  destruct (cd_declmap cd20 fun_name); destruct (cd_declmap cd30 fun_name);\n    try easy.\n  apply SomeBranchOk.\n  now inversion T.\n}\nsubst. cbn. intros.\n\n(* This is even more messed up than usual because just the implicit arguments weren't enough. *)\nremember (fun depth\n       (Edepth : @eq (option nat)\n                    (@cd_depthmap C (@AST.decl C) (@Callset.decl_callset C) false cd30 fun_name)\n                    (@Some nat depth)) =>\n       @Some\n         (@sigT nat (fun bound : nat => @fun_ctx C (@AST.decl C) (@Callset.decl_callset C) false cd30 bound))\n         (@existT nat\n            (fun bound : nat => @fun_ctx C (@AST.decl C) (@Callset.decl_callset C) false cd30 bound)\n            (S depth)\n            _))\n  as depth_lhs_some_branch.\nremember (fun (depth: nat)\n        (Edepth: cd_depthmap cd20 fun_name = Some depth) =>\n      Some\n        (existT (fun bound : nat => fun_ctx cd20 bound) (S depth)\n           _))\n  as depth_rhs_some_branch.\nenough (A: forall depth E30 E20,\n          depth_lhs_some_branch depth E30\n           =\n          match depth_rhs_some_branch depth E20 with\n          | Some (existT _ bound fc) =>\n              Some\n                (existT (fun bound0 : nat => fun_ctx cd30 bound0) bound\n                   (translate_fun_ctx fc Ok))\n          | None => None\n          end).\n{\n  clear Heqdepth_lhs_some_branch Heqdepth_rhs_some_branch.\n  remember (fun Edepth : cd_depthmap cd30 fun_name = None =>\n      False_rect (option {bound : nat & fun_ctx cd30 bound}) (Calldag.make_fun_ctx_helper Ed30 Edepth))\n    as lhs_none_branch.\n  remember (fun Edepth : cd_depthmap cd20 fun_name = None =>\n        False_rect (option {bound : nat & fun_ctx cd20 bound}) (Calldag.make_fun_ctx_helper Ed20 Edepth))\n    as rhs_none_branch.\n  clear Heqlhs_none_branch Heqrhs_none_branch.\n  assert (Guard30 := Calldag.make_fun_ctx_helper Ed30).\n  assert (Guard20 := Calldag.make_fun_ctx_helper Ed20).\n  assert (T := translate_fun_ctx_depthmap Ok fun_name).\n  destruct (cd_depthmap cd30 fun_name), (cd_depthmap cd20 fun_name); try easy.\n  inversion T. subst.\n  apply A.\n}\nintros. subst.\nf_equal. f_equal.\nunfold translate_fun_ctx. cbn.\nassert (FunCtxEq: forall name1 depth depth_ok1 decl1 decl_ok1 bound_ok1\n                         name2       depth_ok2 decl2 decl_ok2 bound_ok2\n                         (Name: name1 = name2)\n                         (Decl: decl1 = decl2),\n  ({| fun_name := name1\n    ; fun_depth := depth\n    ; fun_depth_ok := depth_ok1\n    ; fun_decl := decl1\n    ; fun_decl_ok := decl_ok1\n    ; fun_bound_ok := bound_ok1 |}: fun_ctx cd30 (S depth))\n   =\n  {| fun_name := name2\n   ; fun_depth := depth\n   ; fun_depth_ok := depth_ok2\n   ; fun_decl := decl2\n   ; fun_decl_ok := decl_ok2\n   ; fun_bound_ok := bound_ok2 |}).\n{\n  intros. subst.\n  assert (depth_ok1 = depth_ok2) by apply PropExtensionality.proof_irrelevance.\n  assert (decl_ok1 = decl_ok2) by apply PropExtensionality.proof_irrelevance.\n  assert (bound_ok1 = bound_ok2) by apply PropExtensionality.proof_irrelevance.\n  subst.\n  trivial.\n}\napply FunCtxEq. { (* name: *) trivial. }\nclear FunCtxEq.\nassert (Unsome: forall {T} (x y: T), Some x = Some y -> x = y).\n{ intros T x y H. now inversion H. }\napply Unsome.\nrewrite<- FunCtx.translate_fun_ctx_decl_ok. cbn. symmetry. exact Ed30.\nQed.\n\nTheorem translate_ok {C: VyperConfig}\n                     (builtins: string -> option builtin)\n                     (cd20: L20.Descend.calldag)\n                     (cd30: L30.Descend.calldag)\n                     (Ok: translate_calldag cd20 = inr cd30)\n                     (fun_name: string)\n                     (world: world_state)\n                     (arg_values: list uint256):\n  L30.Interpret.interpret builtins cd30 fun_name world arg_values\n   =\n  L20.Interpret.interpret builtins cd20 fun_name world arg_values.\nProof.\nunfold L20.Interpret.interpret. unfold L30.Interpret.interpret.\nrewrite (make_fun_ctx_and_bound_ok cd20 cd30 Ok).\ndestruct (make_fun_ctx_and_bound cd20 fun_name) as [(bound, fc)|]; cbn.\n{ apply interpret_translated_call. }\ntrivial.\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/From20To30/Call.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.29248728004071267}}
{"text": "\n(**\nRainbow, a termination proof certification tool\n\nSee the COPYRIGHTS and LICENSE files.\n\n- Kim Quyen LY, 2011-04-06\n\n* CPF correctness checker main\n\n*)\n\nSet Implicit Arguments.\n\nRequire Import ATrs SN ZArith EqUtil String List ListDec ListForall\n  ListUtil ZUtil LogicUtil BoolUtil VecUtil NArith NatUtil ADP\n  cpf2color cpf rainbow_main_termin AVarCond cpf_util\n  correctnessproof_full_termin RelUtil correctnessproof_top_termin\n  rainbow_full_termin rainbow_top_termin correctnessproof_non_termin\n  rainbow_non_termin.\n\nSection S.\n\n  (** [nat_of_string]: convert a variable map to natural number. *)\n\n  Variable nat_of_string: string -> nat.\n\n  (** [n: nat] is an artificial extra argument which purpose is to\n     make the function [dpProof] structually recursive with respect to\n     this argument. *)\n  \n  Variable n : nat.\n\n  (** Assume variable [bb] in [rpo]. *)\n\n  Variable bb : nat.\n\n  Section Termination.\n    \n    (***********************************************************************)\n    (** Check that [R] is a trivial proof by stating the set of rules [R] is\n     empty valid termination proof for [red R]. *)\n    \n    Lemma trsTerminationProof_rIsEmpty_ok :\n      forall a (R: arules a), trsTerminationProof_rIsEmpty R = OK -> WF (red R).\n  \n    Proof.\n      intros a R. unfold trsTerminationProof_rIsEmpty.\n      destruct R; simpl; intro. apply WF_red_empty. discr.\n    Qed.\n    \n    (***********************************************************************)\n    (** ** REMOVE Check that termination proof is valid termination proof for\n     [red R]. *)\n    (*\n    Variables is_notvar_lhs_dp : \n      forall a R,forallb (@is_notvar_lhs (Sig a)) (dp R) = true.\n    \n    (** No rule right hand side is a variable in [dp R]. *)\n    \n    Variables is_notvar_rhs_dp :\n      forall a R, forallb (@is_notvar_rhs (Sig a)) (dp R) = true. *)\n    \n    (***********************************************************************)\n    (** Correctness proof of string reverse in trsTermination proof. *)\n    (* MOVE *)\n    Require Import AReverse AUnary.\n\n    Lemma string_reverse_ok :\n      forall a t (rs: arules a) trs\n             (Hm : trsTerminationProof nat_of_string n bb (reverse_trs rs) t = OK)\n             (H : brules_preserve_vars rs = true)\n             (H0 : bis_unary (Sig a) (symbol_in_rules trs) = true),\n        WF (red rs).\n\n    Proof.\n      intros a t rs trs Hm H H0.\n    Admitted.\n\n    (***********************************************************************)\n    (** Correctness proof of trsTermination proof. *)\n\n    Lemma trsTerminationProof_ok :\n      forall a R t i,\n        sys_of_input a nat_of_string i = Ok (Red R) ->\n        trsTerminationProof nat_of_string n bb R t = OK ->\n        WF (red R).\n    \n    Proof.\n      intros a r t i H Hs. revert r H Hs. intros rs Hs.\n      clear Hs i. revert t rs. \n      induction t; intros rs Hm; simpl in Hm; try discr.\n      \n      (** Correctness proof when termination proof is empty. *)\n\n      apply trsTerminationProof_rIsEmpty_ok. hyp.\n\n      (** Correctness proof of termination proof in the case of rule\n          removal. *)\n      \n      destruct o; try discr.\n      unfold trsTerminationProof_ruleRemoval in Hm. destruct o0; try discr.\n      unfold orderingConstraintProof_redPair in Hm.\n      destruct r; try discr.\n      revert Hm. case_eq (redPair_interpretation rs t1 l);\n                 intros l0 H Hm; try discr.\n      eapply redPair_interpretation_ok. apply H. eapply IHt. hyp.\n\n      (** Correctness proof of termination proof in the case of path\n          ordering. *)\n\n      revert Hm. case_eq (pathOrder bb rs l o);\n      intros l0 H Hm; try discr.\n\n      eapply pathOrdering_ok.\n      apply H. eapply IHt. hyp.\n      \n      (** Correctness proof of dependency pair transformation method\n          with and without mark symbol. *)\n      \n      apply trsTerminationProof_dpTrans_ok with\n      (bb:=bb)(nat_of_string:=nat_of_string)(n:=n)(dps:=d)(b:=b)(p:=d0).\n      hyp. (*hyp. apply Hm.*)\n\n      (** String reversal *)\n     \n      case_eq (brules_preserve_vars rs && bis_unary (Sig a) (symbol_in_rules t));\n        intros H; rewrite H in Hm; simpl in *; try discr.\n      rewrite andb_eq in H. destruct H.\n      apply string_reverse_ok with (t:=t0)(trs:=t). \n      hyp. hyp. hyp.\n    Qed.\n\n    (***********************************************************************)\n    (** ** Check that termination proof is valid termination proof for\n     [red_mod R D]. *)\n\n    Require Import QArith_base NewPositivePolynom2 NewPolynom2\n            NewMonotonePolynom2 APolyInt_MAQ2 NewAPolyInt2 poly_rat\n            cpf2color_interpret ARedPair2 ARelation AWFMInterpretation\n            OrdRingType2 PositivePolynom.\n    \n    (** Relative termination is empty. *)\n\n    Lemma relProof_pIsEmpty_ok :\n      forall a (R D: arules a),\n        relTerminationProof_rIsEmpty D = OK -> WF (red_mod R D).\n    \n    Proof.\n      intros a R D. unfold relTerminationProof_rIsEmpty.\n      destruct D; simpl; intro. apply WF_red_mod_empty. discr.\n    Qed.\n\n    (***********************************************************************)\n    (** Correctness proof of relative termination. *)\n\n    Lemma rel_TerminationProof_ok :\n      forall a R D t i, sys_of_input a nat_of_string i = Ok (Red_mod R D) ->\n                        relTerminationProof R D t = OK -> WF (red_mod R D).\n\n    Proof.\n      intros a R D t i H Hs. revert R D H Hs. intros R D Hs.\n      clear Hs i. revert t R D.\n      induction t; intros R D Hm; simpl in Hm; try discr.\n\n      (** Correctness proof when termination proof is empty. *)\n      \n      apply relProof_pIsEmpty_ok. apply Hm.  \n      apply relProof_pIsEmpty_ok. apply Hm.\n      \n      (** Correctness proof of relative termination proof in the case of\n       rule removal. *)\n\n      destruct o; try discr.\n      unfold rel_trsTerminationProof_ruleRemoval in Hm. destruct o0; try discr.\n      unfold rel_orderingConstraintProof_redPair in Hm.\n      destruct r; try discr.\n      revert Hm. case_eq (rel_redPair_interpretation R D t2 l);\n                 intros l0 H Hm; try discr.\n      eapply rel_redPair_interpretation_ok. apply H.\n      apply IHt. apply Hm.\n\n      (** Correctness proof of string reverse. *)\n      \n      case_eq (brules_preserve_vars R && brules_preserve_vars D &&\n      bis_unary (Sig a) (symbol_in_rules t)); intros H; rewrite H in Hm; try discr.\n      do 2 rewrite andb_eq in H. do 2 destruct H.\n      \n      apply WF_red_mod_rev_eq.\n\n      (** Proof that [is_unary] is true. *)\n      \n      rewrite <- bis_unary_ok. apply H0.\n\n      (** Proof that [Fs_ok] *)\n\n      Focus 2.\n\n      (** Proof that rule_preserve_vars in D. *)\n\n      rewrite <- brules_preserve_vars_ok. apply H1.\n\n      Focus 2.\n      \n      (** Proof that rule_preserve_vars in R. *)\n      \n      rewrite <- brules_preserve_vars_ok. apply H.\n      \n      Focus 2.\n      \n    (* TODO *)\n    (* Proof [red_mod (reverse_trs R) (reverse_trs D)] is well-founded *)\n\n    Admitted.\n\n  End Termination.\n\n  (***********************************************************************)\n  (** ** Correctness proof of certification problems. *)\n\n  (* [main] for non-termination proof and termination proof where it\n   changes [WF(rel_of_sys s)] to [EIS (rel_of_sys s)] to be able to\n   proof non-termination problem.*)\n\n  Section main.\n\n    (* REMOVE. *)\n\n    (*Variables is_notvar_lhs_dp : \n      forall a R, forallb (@is_notvar_lhs (Sig a)) (dp R) = true.\n\n    (***********************************************************************)\n    (** No rule right hand side is a variable in [dp R]. *)\n    \n    Variables is_notvar_rhs_dp :\n      forall a R, forallb (@is_notvar_rhs (Sig a)) (dp R) = true.*)\n\n    (***********************************************************************)\n\n    Lemma main_ok : forall c, let a := arity_in_pb c in\n     forall s, sys_of_pb a nat_of_string c = Ok s ->\n               check nat_of_string n bb  a c = OK ->\n               not_if (is_nontermin_proof c) (EIS (rel_of_sys s)).\n    \n    Proof.\n      intros c a s Hs Hm. unfold check in Hm. rewrite Hs in Hm.\n      destruct c as [[[i st] p] o]. simpl arity_in_pb in *.\n      simpl sys_of_pb in *.\n      simpl is_nontermin_proof.\n      unfold proof in Hm. destruct s; destruct p; try discr; simpl.\n      apply WF_notEIS.\n\n      (** Correctness proof of termination problem for [red R]. *)\n      \n      apply trsTerminationProof_ok with (t:=t)(i:=i).\n      hyp. hyp. (*hyp. hyp.*)\n      \n      (** Correctness proof of non-termination problem for [red R]. *)\n      \n      unfold trsNonTerminationProof in Hm.\n      destruct t; simpl; try discr.\n      apply trsNonTerminationProof_variableConditionViolated_ok.\n      apply Hm.\n      \n      (** Correcntness proof of non-termination for [red R] using loop\n       method. There is a loop in TRS. *)\n      \n      apply trsNonTerminationProof_loop_ok with (nat_of_string:=nat_of_string)(l:= l).\n      destruct l; try discr.\n      destruct p; try discr.\n      destruct r; try discr.\n      destruct l; try discr.\n      apply Hm.\n      \n      (** Correctness proof of termination problem for [red_mod R D]. *)\n\n      apply WF_notEIS.\n      apply rel_TerminationProof_ok with (t:=r)(i:=i).\n      hyp. apply Hm.\n\n      (** Correctness proof of non-termination problem for [red_mod R D]. *)\n      (*\n      unfold relativeNonterminationProof in Hm.\n      destruct r; simpl; try discr.\n\n      (** Correctness proof of non-termination proof for [red_mod R D] in\n       the case of loop. *)\n\n      apply relativeNonTerminationProof_loop_ok in Hm. apply Hm.\n\n      (** Correctness proof of non-termination proof for [red_mod R D] in\n       the case of variable condition violated. *)\n      \n      apply relativeNonTerminationProof_variableConditionViolated_ok.\n      apply Hm.*)\n      \n      (** Correctness proof of termination for top termination\n       problems. [hd_red_mod R (dp R)] *)\n      \n      apply WF_notEIS. eapply dpProof_ok. apply Hm.\n     \n      (* TODO : other cases *)\n    Qed.\n\n  End main.\n\nEnd S.", "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/correctnessproof_main.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.29243506406617564}}
{"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 Import Termes.\nRequire Import Conv.\nRequire Import Types.\nRequire Import Class.\nRequire Import Can.\n\n  (* Interpretations des variables de type *)\n\n  Inductive Int_K : Type :=\n    | iK : forall s : skel, Can s -> Int_K\n    | iT : Int_K.\n\n  Definition intP := TList Int_K.\n\n\n  Definition class_of_ik (ik : Int_K) :=\n    match ik with\n    | iK s _ => Knd s\n    | iT => Typ PROP\n    end.\n\n\n\n  Definition cls_of_int : intP -> cls := Tmap _ _ class_of_ik.\n\n\n  Definition ext_ik (T : term) (ip : intP) (s : skel) \n    (C : Can s) :=\n    match cl_term T (cls_of_int ip) with\n    | Knd _ => iK s C\n    | _ => iT\n    end.\n\n\n  Definition int_cons (T : term) (ip : intP) (s : skel) \n    (C : Can s) := TCs _ (ext_ik T ip s C) ip.\n\n\n  Definition def_cons (T : term) (I : intP) : intP :=\n    int_cons T I _ (default_can (cv_skel (cl_term T (cls_of_int I)))).\n\n\n\n\n  Definition skel_int (t : term) (I : intP) :=\n    typ_skel (cl_term t (cls_of_int I)).\n\n\n  Lemma ins_in_cls :\n   forall (c : class) (y : Int_K) (k : nat) (ipe ipf : intP),\n   class_of_ik y = c ->\n   TIns Int_K y k ipe ipf -> TIns _ c k (cls_of_int ipe) (cls_of_int ipf).\nunfold cls_of_int in |- *.\nsimple induction 1.\nsimple induction 1; simpl in |- *; auto with coc core arith datatypes.\nQed.\n\n\n\n  Definition coerce_CR (s : skel) (i : Int_K) : Can s :=\n    match i with\n    | iK si Ci =>\n        match EQ_skel si s with\n        | left y =>\n            match y in (_ = x) return (Can x) with\n            | refl_equal => Ci\n            end\n        | _ => default_can s\n        end\n    | _ => default_can s\n    end.\n\n  Lemma is_can_coerce :\n   forall s s' C, is_can s C -> is_can s' (coerce_CR s' (iK s C)).\nProof.\nsimpl in |- *; intros.\nelim (EQ_skel s s'); intros; auto with coc.\ncase a; trivial.\nQed.\n\nHint Resolve is_can_coerce: coc.\n\n\n  Lemma extr_eq :\n   forall (P : forall s : skel, Can s -> Prop) (s : skel) (c : Can s),\n   P s c -> P s (coerce_CR s (iK s c)).\nProof.\nintros.\nunfold coerce_CR in |- *.\nelim (EQ_skel s s).\nintro Heq.\nchange\n  ((fun s0 (e : s = s0) =>\n    P s0 match e in (_ = x) return (Can x) with\n         | refl_equal => c\n         end) s Heq) in |- *.\ncase Heq; trivial.\n\nsimple induction 1; auto with coc core arith datatypes.\nQed.\n\n\n  Lemma eq_can_extr :\n   forall (s si : skel) (X Y : Can s),\n   eq_can s X Y -> eq_can si (coerce_CR si (iK s X)) (coerce_CR si (iK s Y)).\nunfold coerce_CR in |- *.\nintros.\nelim (EQ_skel s si); auto with coc core arith datatypes.\nintro Heq; case Heq; auto with coc core arith datatypes.\nQed.\n\n  Hint Resolve eq_can_extr: coc.\n\n\n\n\n  Inductive ik_eq : Int_K -> Int_K -> Prop :=\n    | eqi_K :\n        forall (s : skel) (X Y : Can s),\n        eq_can s X X ->\n        eq_can s Y Y -> eq_can s X Y -> ik_eq (iK s X) (iK s Y)\n    | eqi_T : ik_eq iT iT.\n\n  Hint Resolve eqi_K eqi_T: coc.\n\n  Lemma iki_K :\n   forall (s : skel) (C : Can s), eq_can s C C -> ik_eq (iK s C) (iK s C).\nauto with coc core arith datatypes.\nQed.\n\n  Hint Resolve iki_K: coc.\n\n\n\n\n  Definition int_eq_can : intP -> intP -> Prop := Tfor_all2 _ _ ik_eq.\n  Definition int_inv (i : intP) := int_eq_can i i.\n\n  Hint Unfold int_eq_can int_inv: coc.\n\n\n  Lemma ins_int_inv :\n   forall (e f : intP) (k : nat) (y : Int_K),\n   TIns _ y k e f -> int_inv f -> int_inv e.\nunfold int_inv, int_eq_can in |- *.\nsimple induction 1; intros; auto with coc core arith datatypes.\ninversion_clear H0; auto with coc core arith datatypes.\n\ninversion_clear H2; auto with coc core arith datatypes.\nQed.\n\n\n  Lemma int_inv_int_eq_can : forall i : intP, int_inv i -> int_eq_can i i.\nauto with coc core arith datatypes.\nQed.\n\n  Hint Resolve int_inv_int_eq_can: coc.\n\n\n\n  Lemma int_eq_can_cls :\n   forall i i' : intP, int_eq_can i i' -> cls_of_int i = cls_of_int i'.\nunfold cls_of_int in |- *.\nsimple induction 1; simpl in |- *; intros; auto with coc core arith datatypes.\ninversion_clear H0; simpl in |- *; intros; elim H2;\n auto with coc core arith datatypes.\nQed.\n\n\n  Fixpoint int_typ (T : term) : intP -> forall s : skel, Can s :=\n    fun (ip : intP) (s : skel) =>\n    match T with\n    | Srt _ => default_can s\n    | Ref n => coerce_CR s (Tnth_def _ (iK PROP sn) ip n)\n    | Abs A t =>\n        match cl_term A (cls_of_int ip) with\n        | Knd _ =>\n            match s as x return (Can x) with\n            | PROD s1 s2 =>\n                fun C : Can s1 => int_typ t (TCs _ (iK s1 C) ip) s2\n            | PROP => default_can PROP\n            end\n        | Typ _ => int_typ t (def_cons A ip) s\n        | _ => default_can s\n        end\n    | App u v =>\n        match cl_term v (cls_of_int ip) with\n        | Trm => int_typ u ip s\n        | Typ sv => int_typ u ip (PROD sv s) (int_typ v ip sv)\n        | _ => default_can s\n        end\n    | Prod A B =>\n        match s as x return (Can x) with\n        | PROP =>\n            let s := cv_skel (cl_term A (cls_of_int ip)) in\n            Pi s (int_typ A ip PROP)\n              (fun C => int_typ B (int_cons A ip s C) PROP)\n        | PROD s1 s2 => default_can (PROD s1 s2)\n        end\n    end.\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/Int_typ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.2923814378995846}}
{"text": "(*\nCopyright © 2009 Valentin Blot\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis proof and associated documentation files (the \"Proof\"), to deal in\nthe Proof without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Proof, and to permit persons to whom the Proof is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Proof.\n\nTHE PROOF IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE PROOF OR THE USE OR OTHER DEALINGS IN THE PROOF.\n*)\nRequire Import ssreflect ssrbool ssrfun eqtype ssrnat seq choice fintype.\nRequire Import finfun bigops ssralg groups perm zmodp morphisms.\n\nRequire Import Ring RingClass.\nRequire Import bigopsClass.\n\nRequire Import Setoid Morphisms.\nNotation \" x === y \" := (Equivalence.equiv x y) (at level 70, no associativity).\n\nOpen Scope signature_scope.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nReserved Notation \"''M_' n\"       (at level 8, n at level 2, format \"''M_' n\").\nReserved Notation \"''M_' ( n )\"   (at level 8, only parsing).\nReserved Notation \"''M_' ( m , n )\" (at level 8, format \"''M_' ( m ,  n )\").\n\nReserved Notation \"\\matrix_ ( i , j ) E\"\n  (at level 36, E at level 36, i, j at level 50,\n   format \"\\matrix_ ( i ,  j )  E\").\nReserved Notation \"\\matrix_ ( i < m , j < n ) E\"\n  (at level 36, E at level 36, i, m, j, n at level 50,\n   format \"\\matrix_ ( i  <  m ,  j  <  n )  E\").\nReserved Notation \"\\matrix_ ( i , j < n ) E\"\n  (at level 36, E at level 36, i, j, n at level 50,\n   format \"\\matrix_ ( i ,  j  <  n )  E\").\n\nReserved Notation \"x %:M\"   (at level 8, format \"x %:M\").\nReserved Notation \"-m A\"    (at level 35, right associativity).\nReserved Notation \"A +m B\"  (at level 50, left associativity).\nReserved Notation \"A -m B\"  (at level 50, left associativity).\nReserved Notation \"x *m: A\" (at level 40, left associativity).\nReserved Notation \"A *m B\"  (at level 40, left associativity).\nReserved Notation \"A ^T\"    (at level 8).\nReserved Notation \"\\tr A\"   (at level 10, A at level 8, format \"\\tr  A\").\nReserved Notation \"\\det A\"  (at level 10, A at level 8, format \"\\det  A\").\nReserved Notation \"\\adj A\"  (at level 10, A at level 8, format \"\\adj  A\").\n\nDelimit Scope matrix_scope with M.\n\nLocal Open Scope matrix_scope.\n\nDefinition setoid_cancel {A : Type} {B : Type} `{Equivalence A aeq} (f : A -> B) g :=\n    forall x, g (f x) === x.\n\nSection MatrixDef.\n\nVariable R : Type.\nVariables m n : nat.\n\nDefinition matrix : Type :=  'I_m -> 'I_n -> R.\n\nEnd MatrixDef.\n\nNotation \"''M_' n\"  := (matrix _ n n) : type_scope.\nNotation \"''M_' ( n )\" := 'M_n (only parsing) : type_scope.\nNotation \"''M_' ( m , n )\" := (matrix _ m n) : type_scope.\n\nNotation \"\\matrix_ ( i < m , j < n ) E\" :=\n  (fun (i : 'I_m) (j : 'I_n) => E) (only parsing).\n\nNotation \"\\matrix_ ( i , j < n ) E\" :=\n  (\\matrix_(i < n, j < n) E) (only parsing).\n\nNotation \"\\matrix_ ( i , j ) E\" := (\\matrix_(i < _, j < _) E).\n\nSection Slicing.\n\nContext `{r_st : Equivalence R req}.\n\nDefinition mx_row m n i0 (A : 'M_(m, n)) :=\n  \\matrix_(i < 1, j < n) (A i0 j : R).\nGlobal Instance mx_row_morph m n i0 : Proper (Equivalence.equiv==>Equivalence.equiv) (@mx_row m n i0).\nProof. by move=> m n i0 A B eqAB i; apply eqAB. Qed.\nDefinition mx_col m n j0 (A : 'M_(m, n)) :=\n  \\matrix_(i < m, j < 1) (A i j0 : R).\nGlobal Instance mx_col_morph m n i0 : Proper (Equivalence.equiv==>Equivalence.equiv) (@mx_col m n i0).\nProof. by move=> m n i0 A B eqAB i j; apply eqAB. Qed.\nDefinition mx_row' m n i0 (A : 'M_(m, n)) :=\n  \\matrix_(i, j) (A (lift i0 i) j : R).\nGlobal Instance mx_row'_morph m n i0 : Proper (Equivalence.equiv==>Equivalence.equiv) (@mx_row' m n i0).\nProof. by move=> m n i0 A B eqAB i; apply eqAB. Qed.\nDefinition mx_col' m n j0 (A : 'M_(m, n)) :=\n  \\matrix_(i, j) (A i (lift j0 j) : R).\nGlobal Instance mx_col'_morph m n i0 : Proper (Equivalence.equiv==>Equivalence.equiv) (@mx_col' m n i0).\nProof. by move=> m n i0 A B eqAB i j; apply eqAB. Qed.\n\nDefinition rswap m n i1 i2 (A : 'M_(m, n)) :=\n  \\matrix_(i, j) (A (tperm i1 i2 i) j : R).\nGlobal Instance rswap_morph m n i1 i2 : Proper (Equivalence.equiv==>Equivalence.equiv) (@rswap m n i1 i2).\nProof. by move=> m n i1 i2 A B eqAB i; apply eqAB. Qed.\n\nDefinition cswap m n i1 i2 (A : 'M_(m, n)) :=\n  \\matrix_(i, j) (A i (tperm i1 i2 j) : R).\nGlobal Instance cswap_morph m n i1 i2 : Proper (Equivalence.equiv==>Equivalence.equiv) (@cswap m n i1 i2).\nProof. by move=> m n i1 i2 A B eqAB i j; apply eqAB. Qed.\n    \nDefinition trmx m n (A : 'M_(m, n)) := \\matrix_(i, j) (A j i : R).\nGlobal Instance trmx_morph m n : Proper (Equivalence.equiv==>Equivalence.equiv) (@trmx m n).\nProof. by move=> m n A B eqAB i j; apply eqAB. Qed.\n\nLemma trmxK : forall m n, setoid_cancel (@trmx m n) (@trmx n m).\nProof. by move=> m n A i j; rewrite/trmx; reflexivity. Qed.\n\nLemma trmx_inj : forall m n (A B : 'M_(m, n)), trmx A === trmx B -> A === B.\nProof. by rewrite/trmx=> m n A B eqtr i j; apply eqtr. Qed.\n\nNotation \"A ^T\" := (trmx A).\n\nLemma trmx_row : forall m n i0 (A : 'M_(m, n)),\n  (mx_row i0 A)^T === mx_col i0 A^T.\nProof. by rewrite/trmx/mx_row/mx_col=> m n i0 A i j; reflexivity. Qed.\n\nLemma trmx_row' : forall m n i0 (A : 'M_(m, n)),\n  (mx_row' i0 A)^T === mx_col' i0 A^T.\nProof. by rewrite/trmx/mx_row/mx_col=> m n i0 A i j; reflexivity. Qed.\n\nLemma trmx_col : forall m n j0 (A : 'M_(m, n)),\n  (mx_col j0 A)^T === mx_row j0 A^T.\nProof. by rewrite/trmx/mx_row/mx_col=> m n i0 A i j; reflexivity. Qed.\n\nLemma trmx_col' : forall m n j0 (A : 'M_(m, n)),\n  (mx_col' j0 A)^T === mx_row' j0 A^T.\nProof. by rewrite/trmx/mx_row/mx_col=> m n i0 A i j; reflexivity. Qed.\n\nLemma trmx_cswap : forall m n (A : 'M_(m, n)) i1 i2, \n  (cswap i1 i2 A)^T === rswap i1 i2 A^T.\nProof. by rewrite/trmx/rswap/cswap=> m n A i1 i2 i j; case tpermP; reflexivity. Qed.\n\nLemma trmx_rswap : forall m n (A : 'M_(m, n)) i1 i2, \n  (rswap i1 i2 A)^T === cswap i1 i2 A^T. \nProof. by rewrite/trmx/rswap/cswap=> m n A i1 i2 i j; case tpermP; reflexivity. Qed.\n\nLemma mx_row_id : forall n (A : 'M_(1, n)), mx_row ord0 A === A.\nProof. by move=> n A i j; (have -> : ord0 = i by rewrite (ord1 i); apply ord_inj => //); reflexivity. Qed.\n\nLemma mx_row_eq : forall m1 m2 n i1 i2 (A1 : 'M_(m1, n)) (A2 : 'M_(m2, n)),\n  mx_row i1 A1 === mx_row i2 A2 -> A1 i1 === A2 i2.\nProof.\nrewrite/mx_row => m1 m2 n i1 i2 A1 A2 eqA1A2 j.\nby apply eqA1A2; apply (@Ordinal 1 0).\nQed.\n\nLemma mx_row'_eq : forall m n i0 (A B : 'M_(m, n)),\n  mx_row' i0 A === mx_row' i0 B -> {in predC1 i0, forall i, A i === B i}.\nProof.\nmove=> m n i0 A B eqAB i; rewrite /mx_row' inE /= eq_sym.\nby case/unlift_some=> i' -> _; apply: eqAB.\nQed.\n\nSection CutPaste.\n\nVariables m n1 n2 : nat.\n\n(* The shape of the (dependent) width parameter of the type of A *)\n(* determines where the cut is made! *)\n\nDefinition lcutmx (A : 'M_(m, n1 + n2)):=\n  \\matrix_(i < m, j < n1) (A i (lshift n2 j) : R).\nGlobal Instance lcutmx_morph : Proper (Equivalence.equiv==>Equivalence.equiv) lcutmx.\nProof. by move=> A B eqAB i j; apply eqAB. Qed.\n\nDefinition rcutmx (A : 'M_(m, n1 + n2)) :=\n  \\matrix_(i < m, j < n2) (A i (rshift n1 j) : R).\nGlobal Instance rcutmx_morph : Proper (Equivalence.equiv==>Equivalence.equiv) rcutmx.\nProof. by move=> A B eqAB i j; apply eqAB. Qed.\n\nDefinition pastemx (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)) :=\n   \\matrix_(i < m, j < n1 + n2)\n      (match split j with inl j1 => A1 i j1 | inr j2 => A2 i j2 end : R).\nGlobal Instance pastemx_morph : Proper (Equivalence.equiv==>Equivalence.equiv==>Equivalence.equiv) pastemx.\nProof.\nrewrite/pastemx=> A1 B1 eqAB1 A2 B2 eqAB2 i j; case: (splitP j)=> j' _; first by apply eqAB1.\nby apply eqAB2.\nQed.\n\nLemma pastemxEl : forall A1 A2 i j, pastemx A1 A2 i (lshift n2 j) === A1 i j.\nProof. by rewrite/pastemx=> A1 A2 i j; rewrite (unsplitK (inl _ _)); reflexivity. Qed.\n\nLemma pastemxEr : forall A1 A2 i j, pastemx A1 A2 i (rshift n1 j) === A2 i j.\nProof. by rewrite/pastemx=> A1 A2 i j; rewrite (unsplitK (inr _ _)); reflexivity. Qed.\n\nLemma pastemxKl : forall A1 A2, lcutmx (pastemx A1 A2) === A1.\nProof. by move=> A1 A2 i j; rewrite /lcutmx; rewrite -> pastemxEl; reflexivity. Qed.\n\nLemma pastemxKr : forall A1 A2, rcutmx (pastemx A1 A2) === A2.\nProof. by move=> A1 A2 i j; rewrite /rcutmx; rewrite -> pastemxEr; reflexivity. Qed.\n\nLemma cutmxK : forall A, pastemx (lcutmx A) (rcutmx A) === A.\nProof.\nmove=> A i j.\nrewrite/pastemx/lcutmx/rcutmx.\ncase: splitP; case=> /= k kprf eqk.\n  by have <- : j = lshift n2 (Ordinal kprf); [apply ord_inj; apply eqk | reflexivity].\nby have <- : j = rshift n1 (Ordinal kprf); [apply ord_inj; apply eqk | reflexivity].\nQed.\n\nEnd CutPaste.\n\nLemma mx_row_paste : forall m n1 n2 i0 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)),\n  mx_row i0 (pastemx A1 A2) === pastemx (mx_row i0 A1) (mx_row i0 A2).\nProof. by reflexivity. Qed.\n\nLemma mx_row'_paste : forall m n1 n2 i0 (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)),\n  mx_row' i0 (pastemx A1 A2) === pastemx (mx_row' i0 A1) (mx_row' i0 A2).\nProof. by reflexivity. Qed.\n\nLemma mx_col_lshift : forall m n1 n2 j1 (A1 : 'M_(m, n1)) A2,\n  mx_col (lshift n2 j1) (pastemx A1 A2) === mx_col j1 A1.\nProof. by rewrite/mx_col=> m n1 n2 j1 A1 A2 i j; rewrite -> pastemxEl; reflexivity. Qed.\n\nLemma mx_col_rshift : forall m n1 n2 j2 A1 (A2 : 'M_(m, n2)),\n  mx_col (rshift n1 j2) (pastemx A1 A2) === mx_col j2 A2.\nProof. by rewrite/mx_col=> m n1 n2 j1 A1 A2 i j; rewrite -> pastemxEr; reflexivity. Qed.\n\nLemma mx_col'_lshift : forall m n1 n2 j1 (A1 : 'M_(m, n1.+1)) A2,\n  mx_col' (lshift n2 j1) (pastemx A1 A2) === pastemx (mx_col' j1 A1) A2.\nProof.\nmove=> m n1 n2 j1 A1 A2 i /= j.\ncase: (splitP j) => j' def_j'.\n  have -> : j = lshift n2 j' by apply ord_inj; apply def_j'.\n  rewrite -> pastemxEl; rewrite /mx_col'.\n  have -> : lift (lshift n2 j1) (lshift n2 j') = lshift n2 (lift j1 j'); last by rewrite -> pastemxEl; reflexivity.\n  by apply ord_inj.\nhave -> : j = rshift n1 j' by apply ord_inj; apply def_j'.\nrewrite -> pastemxEr; rewrite /mx_col'.\nhave -> : lift (lshift n2 j1) (rshift n1 j') = (rshift n1.+1 j'); last by rewrite -> pastemxEr; reflexivity.\napply ord_inj => /=.\nrewrite/bump //= addSnnS addnS -def_j' -(addn1 j) addnC.\nhave -> : j1 <= j=>//.\nrewrite def_j' {def_j'}.\nby apply leq_trans with n1; [apply j1 | apply leq_addr].\nQed.\n\nLemma mx_col'_rcast : forall n1 n2, 'I_n2 -> (n1 + n2.-1)%N === (n1 + n2).-1.\nProof. by move=> n1 n2 [j]; move/ltn_predK <-; rewrite addnS. Qed.\n\n(*Lemma paste_mx_col' : forall m n1 n2 j2 A1 (A2 : 'M_(m, n2)),\n  pastemx A1 (mx_col' j2 A2) \n    === eq_rect _ (matrix R m) (mx_col' (rshift n1 j2) (pastemx A1 A2))\n              _ (esym (mx_col'_rcast n1 j2)).\nProof.\nmove=> m n1 n2 j2 A1 A2; apply/matrixP=> i /= j; rewrite mxE.\ncase: splitP => j' def_j'; case: (n1 + n2.-1)%N / (esym _) => /= in j def_j' *.\n  rewrite mxE -(pastemxEl _ A2); congr (pastemx _ _ _); apply: ord_inj.\n  by rewrite /= def_j' /bump leqNgt ltn_addr.\nrewrite 2!mxE -(pastemxEr A1); congr (pastemx _ _ _ _); apply: ord_inj => /=.\nby rewrite def_j' /bump leq_add2l addnCA.\nQed.\n\nLemma mx_col'_rshift : forall m n1 n2 j2 A1 (A2 : 'M_(m, n2)),\n  mx_col' (rshift n1 j2) (pastemx A1 A2) \n    = eq_rect _ (matrix R m) (pastemx A1 (mx_col' j2 A2))\n              _ (mx_col'_rcast n1 j2).\nProof.\nmove=> m n1 n2 j2 A1 A2; rewrite paste_mx_col'.\nby case: _.-1 / (mx_col'_rcast n1 j2) {A1 A2}(mx_col' _ _).\nQed.*)\n\nSection Block.\n\nVariables m1 m2 n1 n2 : nat.\n\nDefinition block_mx Aul Aur All Alr : 'M_(m1 + m2, n1 + n2) :=\n  (pastemx (pastemx Aul Aur)^T (pastemx All Alr)^T)^T.\nGlobal Instance block_mx_morph : Proper (Equivalence.equiv==>Equivalence.equiv==>Equivalence.equiv==>Equivalence.equiv==>Equivalence.equiv) block_mx.\nProof.\nrewrite/block_mx=> Aul1 Aul2 eqAul Aur1 Aur2 eqAur All1 All2 eqAll Alr1 Alr2 eqAlr i j.\nby apply pastemx_morph; apply trmx_morph; apply pastemx_morph.\nQed.\n\nSection CutBlock.\n\nVariable A : matrix R (m1 + m2) (n1 + n2).\n\nDefinition ulsubmx := lcutmx (lcutmx A^T)^T.\nDefinition ursubmx := rcutmx (lcutmx A^T)^T.\nDefinition llsubmx := lcutmx (rcutmx A^T)^T.\nDefinition lrsubmx := rcutmx (rcutmx A^T)^T.\n\nLemma submxK : block_mx ulsubmx ursubmx llsubmx lrsubmx === A.\nProof.\nrewrite/block_mx/ulsubmx/ursubmx/llsubmx/lrsubmx.\nrewrite -> !cutmxK => i j.\nrewrite/rcutmx/lcutmx/pastemx/trmx.\ncase: splitP => i' eqii'.\nby have -> : lshift m2 i' = i; [apply ord_inj|reflexivity].\nby have -> : rshift m1 i' = i; [apply ord_inj|reflexivity].\nQed.\n\nEnd CutBlock.\n\nSection PasteBlock.\n\nVariables (Aul : matrix R m1 n1) (Aur : matrix R m1 n2).\nVariables (All : matrix R m2 n1) (Alr : matrix R m2 n2).\n\nLet A := block_mx Aul Aur All Alr.\n\nLemma block_mxEul : forall i j, A (lshift m2 i) (lshift n2 j) === Aul i j.\nProof. by move=> i j; rewrite /A /block_mx /trmx; rewrite -> !pastemxEl; reflexivity. Qed.\n\nLemma block_mxKul : ulsubmx A === Aul.\nProof. by move=> i j; rewrite /A /block_mx /ulsubmx /lcutmx /trmx; rewrite -> !pastemxEl; reflexivity. Qed.\n\nLemma block_mxEur : forall i j, A (lshift m2 i) (rshift n1 j) === Aur i j.\nProof. by move=> i j; rewrite /A /block_mx /trmx; rewrite -> pastemxEl, pastemxEr; reflexivity. Qed.\n\nLemma block_mxKur : ursubmx A === Aur.\nProof. by move=> i j; rewrite /A /block_mx /ursubmx /lcutmx /rcutmx /trmx; rewrite -> pastemxEl, pastemxEr; reflexivity. Qed.\n\nLemma block_mxEll : forall i j, A (rshift m1 i) (lshift n2 j) === All i j.\nProof. by move=> i j; rewrite /A /block_mx /trmx; rewrite -> pastemxEr, pastemxEl; reflexivity. Qed.\n\nLemma block_mxKll : llsubmx A === All.\nProof. by move=> i j; rewrite /A /block_mx /llsubmx /lcutmx /rcutmx /trmx; rewrite -> pastemxEr, pastemxEl; reflexivity. Qed.\n\nLemma block_mxElr : forall i j, A (rshift m1 i) (rshift n1 j) === Alr i j.\nProof. by move=> i j; rewrite /A /block_mx /trmx; rewrite -> !pastemxEr; reflexivity. Qed.\n\nLemma block_mxKlr : lrsubmx A === Alr.\nProof. by move=> i j; rewrite /A /block_mx /lrsubmx /lcutmx /rcutmx /trmx; rewrite -> !pastemxEr; reflexivity. Qed.\n\nEnd PasteBlock.\n\nEnd Block.\n\nSection TrBlock.\n\nVariables m1 m2 n1 n2 : nat.\n\nSection TrCut.\n\nVariable A : matrix R (m1 + m2) (n1 + n2).\n\nLemma trmx_ulsub : (ulsubmx A)^T === ulsubmx A^T.\nProof. by move => i j /=; reflexivity. Qed.\n\nLemma trmx_ursub : (ursubmx A)^T === llsubmx A^T.\nProof. by move => i j /=; reflexivity. Qed.\n\nLemma trmx_llsub : (llsubmx A)^T === ursubmx A^T.\nProof. by move => i j /=; reflexivity. Qed.\n\nLemma trmx_lrsub : (lrsubmx A)^T === lrsubmx A^T.\nProof. by move => i j /=; reflexivity. Qed.\n\nEnd TrCut.\n\nLemma trmx_block : forall (Aul : 'M_(m1, n1)) Aur All (Alr : 'M_(m2, n2)),\n (block_mx Aul Aur All Alr)^T ===\n    block_mx Aul^T All^T Aur^T Alr^T.\nProof.\nmove=> Aul Aur All Alr.\npose (block_mx Aul Aur All Alr).\nrewrite -/m.\nrewrite <- (block_mxKul Aul Aur All Alr).\nrewrite <- (block_mxKll Aul Aur All Alr) at 2.\nrewrite <- (block_mxKur Aul Aur All Alr) at 3.\nrewrite <- (block_mxKlr Aul Aur All Alr) at 4.\nby rewrite -> trmx_ulsub, trmx_llsub, trmx_ursub, trmx_lrsub, submxK; reflexivity.\nQed.\n\nEnd TrBlock.\n\nEnd Slicing.\n\nNotation \"A ^T\" := (trmx A).\nPrenex Implicits lcutmx rcutmx ulsubmx ursubmx llsubmx lrsubmx.\n\n(* Definition of operations for matrices over a ring *)\nSection MatrixOpsDef.\n\n\nContext `{r_ring : Ring}.\n\nAdd Ring r_r : r_rt (setoid r_st r_ree, preprocess [unfold Equivalence.equiv]).\n\nNotation \"0\" := rO.\nNotation \"1\" := rI.\nNotation \"x + y\" := (radd x y).\nNotation \"x * y \" := (rmul x y).\nNotation \"x - y \" := (rsub x y).\nNotation \"- x\" := (ropp x).\n\nNotation \"\\sum_ ( <- r | P ) F\" := (\\big[radd/0]_(<- r | P) F).\nNotation \"\\sum_ ( i <- r | P ) F\" := (\\big[radd/0]_(i <- r | P) F).\nNotation \"\\sum_ ( i <- r ) F\" := (\\big[radd/0]_(i <- r) F).\nNotation \"\\sum_ ( m <= i < n | P ) F\" := (\\big[radd/0]_(m <= i < n | P) F).\nNotation \"\\sum_ ( m <= i < n ) F\" := (\\big[radd/0]_(m <= i < n) F).\nNotation \"\\sum_ ( i | P ) F\" := (\\big[radd/0]_(i | P) F).\nNotation \"\\sum_ i F\" := (\\big[radd/0]_i F).\nNotation \"\\sum_ ( i : t | P ) F\" := (\\big[radd/0]_(i : t | P) F) (only parsing).\nNotation \"\\sum_ ( i : t ) F\" := (\\big[radd/0]_(i : t) F) (only parsing).\nNotation \"\\sum_ ( i < n | P ) F\" := (\\big[radd/0]_(i < n | P) F).\nNotation \"\\sum_ ( i < n ) F\" := (\\big[radd/0]_(i < n) F).\nNotation \"\\sum_ ( i \\in A | P ) F\" := (\\big[radd/0]_(i \\in A | P) F).\nNotation \"\\sum_ ( i \\in A ) F\" := (\\big[radd/0]_(i \\in A) F).\n\nNotation \"\\prod_ ( <- r | P ) F\" := (\\big[rmul/1]_(<- r | P) F).\nNotation \"\\prod_ ( i <- r | P ) F\" := (\\big[rmul/1]_(i <- r | P) F).\nNotation \"\\prod_ ( i <- r ) F\" := (\\big[rmul/1]_(i <- r) F).\nNotation \"\\prod_ ( m <= i < n | P ) F\" := (\\big[rmul/1]_(m <= i < n | P) F).\nNotation \"\\prod_ ( m <= i < n ) F\" := (\\big[rmul/1]_(m <= i < n) F).\nNotation \"\\prod_ ( i | P ) F\" := (\\big[rmul/1]_(i | P) F).\nNotation \"\\prod_ i F\" := (\\big[rmul/1]_i F).\nNotation \"\\prod_ ( i : t | P ) F\" := (\\big[rmul/1]_(i : t | P) F) (only parsing).\nNotation \"\\prod_ ( i : t ) F\" := (\\big[rmul/1]_(i : t) F) (only parsing).\nNotation \"\\prod_ ( i < n | P ) F\" := (\\big[rmul/1]_(i < n | P) F).\nNotation \"\\prod_ ( i < n ) F\" := (\\big[rmul/1]_(i < n) F).\nNotation \"\\prod_ ( i \\in A | P ) F\" := (\\big[rmul/1]_(i \\in A | P) F).\nNotation \"\\prod_ ( i \\in A ) F\" := (\\big[rmul/1]_(i \\in A) F).\n\nExisting Instance radd_morph.\nExisting Instance rmul_morph.\nExisting Instance rsub_morph.\nExisting Instance ropp_morph.\n\nExisting Instance radd_assoc.\nExisting Instance radd_comm.\nExisting Instance radd_left_unit.\nExisting Instance rmul_assoc.\nExisting Instance rmul_comm.\nExisting Instance rmul_left_unit.\nExisting Instance rmul_left_zero.\nExisting Instance radd_rmul_left_distr.\n\nSection ZmodOps.\n(* The Zmodule structure *)\n\nVariables m n : nat.\nImplicit Types A B C : matrix R m n.\n\nDefinition null_mx := \\matrix_(i < m, j < n) (0 : R).\nDefinition oppmx A := \\matrix_(i < m, j < n) (- A i j).\nDefinition addmx A B := \\matrix_(i < m, j < n) (A i j + B i j).\nDefinition scalemx x A := \\matrix_(i < m, j < n) (x * A i j).\n\nGlobal Instance addmx_morph : Proper (Equivalence.equiv==>Equivalence.equiv==>Equivalence.equiv) addmx.\nProof. by move=> A A' eqAA' B B' eqBB' i j; rewrite/addmx; setoid_rewrite eqAA'; setoid_rewrite eqBB'; reflexivity. Qed.\n\nGlobal Instance oppmx_morph : Proper (Equivalence.equiv==>Equivalence.equiv) oppmx.\nProof. by move=> A A' eqAA' i j ; rewrite/oppmx; setoid_rewrite eqAA'; reflexivity. Qed.\n\nGlobal Instance scalemx_morph : Proper (Equivalence.equiv==>Equivalence.equiv==>Equivalence.equiv) scalemx.\nProof. by move=> A A' eqAA' B B' eqBB' i j ; rewrite/scalemx; setoid_rewrite eqAA'; setoid_rewrite eqBB'; reflexivity. Qed.\n\nLemma summxE : forall I r (P : pred I) (E : I -> 'M_(m, n)) i j,\n  (\\big[addmx/null_mx]_(k <- r | P k) E k) i j === \\sum_(k <- r | P k) E k i j.\nProof.\nmove=> I r P E i j.\napply: (big_morph (phi:=fun A => A i j)) => [A B||].\n  by rewrite/addmx; ring.\nby rewrite/null_mx; ring.\napply radd_morph.\nQed.\n\n(* Vector space structure... pending the definition *)\n\nNotation \"'0m\" := null_mx.\nNotation \"-m A\" := (oppmx A).\nNotation \"A +m B\" := (addmx A B).\nNotation \"A -m B\" := (addmx A (oppmx B)).\nNotation \"x *m: A\" := (scalemx x A).\n\nLemma scale0mx : forall A, 0 *m: A === '0m.\nProof. by rewrite/null_mx/addmx/oppmx/scalemx=> A i j; ring. Qed.\n\nLemma scalemx0 : forall x, x *m: '0m === '0m.\nProof. by rewrite/null_mx/addmx/oppmx/scalemx=> x i j; ring. Qed.\n\nLemma scale1mx : forall A, 1 *m: A === A.\nProof. by rewrite/null_mx/addmx/oppmx/scalemx=> A i j; ring. Qed.\n\nLemma scaleNmx : forall x A, (- x) *m: A === -m (x *m: A).\nProof. by rewrite/null_mx/addmx/oppmx/scalemx=> x A i j; ring. Qed.\n\nLemma scalemxN : forall x A, x *m: (-m A) === -m (x *m: A).\nProof. by rewrite/null_mx/addmx/oppmx/scalemx=> x A i j; ring. Qed.\n\nLemma scalemx_addl : forall x y A, (x + y) *m: A === (x *m: A) +m (y *m: A).\nProof. by rewrite/null_mx/addmx/oppmx/scalemx=> x y A i j; ring. Qed.\n\nLemma scalemx_addr : forall x A B, x *m: (A +m B) === (x *m: A) +m (x *m: B).\nProof. by rewrite/null_mx/addmx/oppmx/scalemx=> x A B i j; ring. Qed.\n\nLemma scalemx_subl : forall x y A, (x - y) *m: A ===  (x *m: A) -m (y *m: A).\nProof. by rewrite/null_mx/addmx/oppmx/scalemx=> x y A i j; ring. Qed.\n\nLemma scalemx_subr : forall x A B, x *m: (A -m B) === (x *m: A) -m (x *m: B).\nProof. by rewrite/null_mx/addmx/oppmx/scalemx=> x A B i j; ring. Qed.\n\nLemma scalemxA : forall x y A, x *m: (y *m: A) === (x * y) *m: A.\nProof. by rewrite/null_mx/addmx/oppmx/scalemx=> x y A i j; ring. Qed.\n\n(* Basis... *)\n\nDefinition delta_mx i0 j0 :=\n  \\matrix_(i < m, j < n) (if ((i == i0) && (j == j0)) then 1 else 0).\n\nLemma matrix_sum_delta : forall A,\n  A === \\big[addmx/null_mx]_(i < m) \\big[addmx/null_mx]_(j < n) (A i j *m: delta_mx i j).\nProof.\nmove=> A i j.\nsetoid_rewrite summxE.\nsetoid_rewrite summxE.\nsetoid_rewrite (bigD1 (j:=i))=>//=.\nsetoid_rewrite (big1 (P:=fun i0 => i0 != i))=>[|i0 Hi0].\n  setoid_rewrite (bigD1 (j:=j))=>//=.\n  setoid_rewrite (big1 (P:=fun i0 => i0 != j))=>[|i0 Hi0].\n    by rewrite/delta_mx/scalemx !eq_refl/=; ring.\n  rewrite/delta_mx/scalemx !eq_refl/= eq_sym; move:Hi0.\n  by case/negbRL=>->/=; ring.\napply (big1 (P:=fun _ => true) (F:=fun k => (A i0 k *m: delta_mx i0 k) i j))=>i1 _.\nrewrite/delta_mx/scalemx eq_sym/=; move:Hi0.\nby case/negbRL=>->/=; ring.\nQed.\n\nEnd ZmodOps.\n\nNotation \"'0m\" := (@null_mx _ _).\nNotation \"-m A\" := (oppmx A).\nNotation \"A +m B\" := (addmx A B).\nNotation \"A -m B\" := (addmx A (oppmx B)).\nNotation \"x *m: A\" := (scalemx x A).\n\nLemma trmx0 : forall (m n : nat), (@null_mx m n)^T === @null_mx n m.\nProof. by move=> m n; rewrite/trmx/null_mx/addmx/oppmx/scalemx; reflexivity. Qed.\n\nLemma trmx_add : forall m n (A B : 'M_(m, n)), (A +m B)^T === A^T +m B^T.\nProof. by move=> m n; rewrite/trmx/null_mx/addmx/oppmx/scalemx; reflexivity. Qed.\n\nLemma trmx_scale : forall m n a (A : 'M_(m, n)), (a *m: A)^T === a *m: A^T.\nProof. by move=> m n; rewrite/trmx/null_mx/addmx/oppmx/scalemx; reflexivity. Qed.\n\nLemma mx_row0 : forall m n i0, mx_row i0 (@null_mx m n) === (@null_mx 1 n).\nProof. by move=> m n; rewrite/trmx/null_mx/addmx/oppmx/scalemx; reflexivity. Qed.\n\nLemma mx_col0 : forall m n j0, mx_col j0 (@null_mx m n) === (@null_mx m 1).\nProof. by move=> m n; rewrite/trmx/null_mx/addmx/oppmx/scalemx; reflexivity. Qed.\n\nLemma mx_row'0 : forall m n i0, mx_row' i0 (@null_mx m n) === (@null_mx m.-1 n).\nProof. by move=> m n; rewrite/trmx/null_mx/addmx/oppmx/scalemx; reflexivity. Qed.\n\nLemma mx_col'0 : forall m n i0, mx_col' i0 (@null_mx m n) === (@null_mx m n.-1).\nProof. by move=> m n; rewrite/trmx/null_mx/addmx/oppmx/scalemx; reflexivity. Qed.\n\nLemma pastemx0 : forall m n1 n2,\n  pastemx (@null_mx m n1) (@null_mx m n2) === (@null_mx m (n1 + n2)).\nProof. by move=> m n1 n2 i j; rewrite/pastemx/trmx/null_mx/addmx/oppmx/scalemx; case: split; reflexivity. Qed.\n\nLemma addmx_paste : forall m n1 n2 (A1 B1 : 'M_(m, n1)) (A2 B2 : 'M_(m, n2)),\n  pastemx A1 A2 +m pastemx B1 B2 === pastemx (A1 +m B1) (A2 +m B2).\nProof. by move=> m n1 n2 iA1 B1 A2 B2 i j; rewrite/pastemx/trmx/null_mx/addmx/oppmx/scalemx; case: split; reflexivity. Qed.\n\nLemma scalemx_paste : forall m n1 n2 a (A1 : 'M_(m, n1)) (A2 : 'M_(m, n2)),\n  a *m: pastemx A1 A2 === pastemx (a *m: A1) (a *m: A2).\nProof. by move=> m n1 n2 a A1 A2 i j; rewrite/pastemx/trmx/null_mx/addmx/oppmx/scalemx; case: split; reflexivity. Qed.\n\nLemma block_mx0 : forall m1 m2 n1 n2,\n  block_mx (@null_mx m1 n1) (@null_mx m1 n2) (@null_mx m2 n1) (@null_mx m2 n2) === @null_mx (m1 + m2) (n1 + n2).\nProof. by move=> m1 m2 n1 n2 i j; rewrite/block_mx/pastemx/trmx/null_mx/addmx/oppmx/scalemx; case: split; case: split; reflexivity. Qed.\n\nLemma addmx_block : forall m1 m2 n1 n2 (Aul Bul : 'M_(m1, n1)) (Aur Bur : 'M_(m1, n2)) (All Bll : 'M_(m2, n1)) (Alr Blr : 'M_(m2, n2)),\n  block_mx Aul Aur All Alr +m block_mx Bul Bur Bll Blr\n    === block_mx (Aul +m Bul) (Aur +m Bur) (All +m Bll) (Alr +m Blr).\nProof. by move=> m1 m2 n1 n2 Aul Bul Aur Bur All Bll Alr Blr i j; rewrite/block_mx/pastemx/trmx/null_mx/addmx/oppmx/scalemx; case: split; case: split; reflexivity. Qed.\n\nLemma scalemx_block : forall m1 m2 n1 n2 a  (Aul : 'M_(m1, n1)) (Aur : 'M_(m1, n2)) (All : 'M_(m2, n1)) (Alr : 'M_(m2, n2)),\n  a *m: block_mx Aul Aur All Alr\n     === block_mx (a *m: Aul) (a *m: Aur) (a *m: All) (a *m: Alr).\nProof. by move=> m1 m2 n1 n2 a Aul Aur All Alr i j; rewrite/block_mx/pastemx/trmx/null_mx/addmx/oppmx/scalemx; case: split; case: split; reflexivity. Qed.\n\n(* The graded ring structure *)\n\nDefinition scalar_mx n x := \\matrix_(i , j < n) (if i == j then x else 0).\nGlobal Instance scalar_mx_morph n : Morphism (Equivalence.equiv==>Equivalence.equiv) (@scalar_mx n).\nProof. by rewrite/scalar_mx=>n x y eqxy i j; case:(i==j); [apply eqxy | reflexivity]. Qed.\n\nDefinition mulmx m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :=\n  \\matrix_(i < m, k < p) \\big [radd/0]_(j < n) (A i j * B j k).\nGlobal Instance mulmx_morph m n p : Morphism (Equivalence.equiv==>Equivalence.equiv==>Equivalence.equiv) (@mulmx m n p).\nProof.\nmove=> m n p A A' eqAA' B B' eqBB' i k.\nrewrite/mulmx; apply eq_bigr=> j _.\nby setoid_rewrite eqAA'; setoid_rewrite eqBB'; reflexivity.\nQed.\n\nNotation \"x %:M\" := (@scalar_mx _ x).\nNotation \"A *m B\" := (mulmx A B).\n\nLemma scalar_mx0 : forall n, 0 %:M === @null_mx n n.\nProof. by move=> n i j; rewrite/block_mx/pastemx/trmx/null_mx/addmx/oppmx/scalemx/scalar_mx/mulmx; case: eqP=> _; ring. Qed.\n\nLemma scalar_mx_opp : forall (n : nat) a, (- a)%:M === -m (@scalar_mx n a).\nProof. by move=> n a i j; rewrite/block_mx/pastemx/trmx/null_mx/addmx/oppmx/scalemx/scalar_mx/mulmx; case: eqP=> _; ring. Qed.\n\nLemma scalar_mx_add : forall n a b, @scalar_mx n (a + b) === a%:M +m b%:M.\nProof. by move=> n a b i j; rewrite/block_mx/pastemx/trmx/null_mx/addmx/oppmx/scalemx/scalar_mx/mulmx; case: eqP=> _; ring. Qed.\n\nLemma mulmx_scalar : forall m n a (A : 'M_(m, n)), (a%:M) *m A === a *m: A.\nProof.\nmove=> m n a A i j; rewrite/block_mx/pastemx/trmx/null_mx/addmx/oppmx/scalemx/scalar_mx/mulmx.\nsetoid_rewrite (bigD1 (j:=i))=>//.\nsetoid_rewrite big1=>[|i'/=]; first by case: eqP=>ii'//; ring.\nby rewrite/is_true eq_sym; move/negbRL=>->/=; ring.\nQed.\n\nLemma scalar_mx_mul : forall n a b, @scalar_mx n (a * b) === a%:M *m b%:M.\nProof. by move=> n a b; rewrite -> mulmx_scalar; rewrite /scalar_mx /scalemx=> i j; by case (i==j); ring. Qed.\n\nLemma trmx_scalar : forall n a, (a%:M)^T === @scalar_mx n a.\nProof. by move=> n a i j; rewrite/trmx/null_mx/addmx/oppmx/scalemx/scalar_mx/mulmx eq_sym; reflexivity. Qed.\n\nLemma mul1mx : forall m n (A : 'M_(m, n)), 1%:M *m A === A.\nProof. by move=> m n A; rewrite -> mulmx_scalar, scale1mx; reflexivity. Qed.\n\nLemma mulmx_addl : forall m n p (A1 A2 : 'M_(m, n)) (B : 'M_(n, p)),\n  (A1 +m A2) *m B === A1 *m B +m A2 *m B.\nProof.\nmove=> m n p A1 A2 B i k; rewrite /addmx /mulmx.\nsetoid_rewrite <- big_split.\nby apply eq_bigr=> j _; ring.\nQed.\n\nLemma scalemx_add : forall n a1 a2, @scalar_mx n (a1 + a2) === a1%:M +m a2%:M.\nProof. by move=> n a1 a2 i j; rewrite/scalar_mx/addmx; case: (i==j); ring. Qed.\n\nLemma scalemxAl : forall m n p a (A : 'M_(m, n)) (B : 'M_(n, p)),\n  a *m: (A *m B) === (a *m: A) *m B.\nProof.\nmove=> m n p a A B i k.\nrewrite/scalemx/mulmx.\nsetoid_rewrite (big_distrr).\napply eq_bigr => j _; ring.\nQed.\n\nLemma mul0mx : forall m n p (A : 'M_(n, p)), '0m *m A === @null_mx m p.\nProof. by move=> m n p A i k; rewrite/mulmx/null_mx; apply (big1 (P:=fun _ => true) (F:=fun j => 0 * A j k))=> j _; ring. Qed.\n\nLemma mulmx0 : forall m n p (A : 'M_(m, n)), A *m '0m === @null_mx m p.\nProof. by move=> m n p A i k; rewrite/mulmx/null_mx; apply (big1 (P:=fun _ => true) (F:=fun j => A i j * 0))=> j _; ring. Qed.\n\nLemma mulmx1 : forall m n (A : 'M_(m, n)), A *m 1%:M === A.\nProof.\nmove=> m n A i k; rewrite/mulmx/scalar_mx.\nsetoid_rewrite (bigD1 (j:=k))=>//.\nsetoid_rewrite big1=> [| j/=]; first by rewrite eq_refl; ring.\nby rewrite/is_true; move/negbRL=>->/=; ring.\nQed.\n\nLemma mulmx_addr : forall m n p (A : 'M_(m, n)) (B1 B2 : 'M_(n, p)),\n  A *m (B1 +m B2) === A *m B1 +m A *m B2.\nProof. by move=> m n p A B1 B2 i k; rewrite/mulmx/addmx; setoid_rewrite <- big_split; apply eq_bigr=> j _; ring. Qed.\n\nLemma mulmxA : forall m n p q (A : 'M_(m, n)) (B : 'M_(n, p)) (C : 'M_(p, q)),\n  A *m (B *m C) === A *m B *m C.\nProof.\nmove=> m n p q A B C i l; rewrite/mulmx.\nsetoid_rewrite big_distrr; setoid_rewrite big_distrl.\nsetoid_rewrite (exchange_big predT predT (fun j k => A i j * (B j k * C k l))).\nby apply eq_bigr=> j _; apply eq_bigr=> k _; ring.\nQed.\n\nDefinition perm_mx n (s : 'S_n) :=\n  \\matrix_(i, j) (if s i == j then 1 else 0).\n\nDefinition tperm_mx n i1 i2 := @perm_mx n (tperm i1 i2).\n\nLemma trmx_perm : forall n (s : 'S_n), (perm_mx s)^T === perm_mx s^-1.\nProof. by move=> n s i j; rewrite /trmx /perm_mx (canF_eq (permK _)) eq_sym; reflexivity. Qed.\n\nLemma trmx_tperm : forall n i1 i2, (@tperm_mx n i1 i2)^T === tperm_mx i1 i2.\nProof. by move=> n i1 i2; rewrite /tperm_mx; rewrite -> trmx_perm, tpermV; reflexivity. Qed.\n\nLemma mulmx_perm : forall n (s t : 'S_n),\n  perm_mx s *m perm_mx t === perm_mx (s * t).\nProof.\nmove=> n s t i j; rewrite/mulmx/perm_mx.\nsetoid_rewrite (bigD1 (j:=s i))=>//=.\nsetoid_rewrite (big1 (P:=fun k => k != s i))=>[|k]; first by rewrite eq_refl permM; ring.\nby rewrite eq_sym; move/negbTE => ->; ring.\nQed.\n\nLemma mul_tperm_mx : forall m n (A : 'M_(m, n)) i1 i2, \n  (tperm_mx i1 i2) *m A === rswap i1 i2 A.\nProof.\nmove=> m n' A i1 i2 i j.\nrewrite /mulmx /tperm_mx /perm_mx /rswap.\nsetoid_rewrite (bigD1 (j:=tperm i1 i2 i))=>//=.\nsetoid_rewrite (big1 (P:=fun k => k != tperm i1 i2 i))=>[|k]; first by rewrite eq_refl; ring.\nby rewrite eq_sym; move/negbTE => ->; ring.\nQed. \n\nLemma perm_mx1 : forall n, perm_mx 1 === @scalar_mx n 1.\nProof. by move=> n i j; rewrite /perm_mx /scalar_mx perm1; reflexivity. Qed.\n\n(* The trace, in 1/4 line. *)\nDefinition mx_trace n (A : 'M_n) := \\sum_(i < n) A i i.\nNotation \"'\\tr' A\" := (mx_trace A).\n\nLemma mx_trace0 : forall n, \\tr ('0m : 'M_n) === 0.\nProof. by move=> n; apply (big1 (I:=ordinal_finType n))=> i _; reflexivity. Qed.\n\nLemma mx_trace_scale : forall n a (A : 'M_n), \\tr (a *m: A) === a * \\tr A.\nProof. by move=> n a A; rewrite/mx_trace; setoid_rewrite (big_distrr (I:=ordinal_finType n)); apply eq_bigr => i _; reflexivity. Qed.\n\nNotation \"a *+ n\" := (iter n (radd a) rO).\n\nLemma mx_trace_scalar : forall n a, \\tr (a%:M : 'M_n) === a *+ n.\nProof. by move=> n a; rewrite <- big_const_ord; apply eq_bigr=> i _; rewrite/scalar_mx eq_refl; reflexivity. Qed.\n\nLemma mx_trace_add : forall n A B, \\tr (A +m B : 'M_n) === \\tr A + \\tr B.\nProof. by move=> n A B; rewrite/mx_trace/addmx; apply big_split. Qed.\n\nLemma mx_trace_tr : forall n (A : 'M_n), \\tr A^T === \\tr A.\nProof. by move=> n A; apply eq_bigr=> i _; reflexivity. Qed.\n\nLemma mx_trace_block : forall n1 n2 Aul Aur All Alr,\n  \\tr (block_mx Aul Aur All Alr : 'M_(n1 + n2)) === \\tr Aul + \\tr Alr.\nProof.\nmove=> n1 n2 Aul Aur All Alr; rewrite /mx_trace; setoid_rewrite big_split_ord => /=.\napply radd_morph; apply eq_bigr=> i _; [rewrite -> block_mxEul | rewrite -> block_mxElr]; reflexivity.\nQed.\n\nLemma mulmx_paste : forall m n p1 p2 (A : 'M_(m, n)) (B1 : 'M_(n, p1)) (B2 : 'M_(n, p2)),\n  A *m (pastemx B1 B2) === pastemx (A *m B1) (A *m B2).\nProof. by move=> m n p1 p2 A B1 B2 i k; rewrite/pastemx/mulmx; case defk: (split k) => [k1 | k2]; apply eq_bigr=> j _; reflexivity. Qed.\n\nLemma dotmx_paste : forall m n1 n2 p A1 A2 B1 B2,\n  (pastemx A1 A2 : 'M_(m, n1 + n2)) *m (pastemx B1 B2 : 'M_(p, n1 + n2))^T\n    === A1 *m B1^T +m A2 *m B2^T.\nProof.\nmove=> m n1 n2 p A1 A2 B1 B2 i k; rewrite/mulmx/addmx/trmx; setoid_rewrite big_split_ord.\nby apply radd_morph; apply eq_bigr=> j _; [rewrite -> pastemxEl, pastemxEl | rewrite -> pastemxEr, pastemxEr]; reflexivity.\nQed.\n\nEnd MatrixOpsDef.\n\nNotation \"'0m\" := (@null_mx _ _ _ _ _ _ _ _ _ _ _ _).\nNotation \"-m A\" := (oppmx A).\nNotation \"A +m B\" := (addmx A B).\nNotation \"A -m B\" := (addmx A (oppmx B)).\nNotation \"x *m: A\" := (scalemx x A).\nNotation \"x %:M\" := (scalar_mx x).\nNotation \"A *m B\" := (mulmx A B).\nNotation \"'\\tr' A\" := (mx_trace A).\n\nSection TrMul.\n\nContext `{r_ring : Ring}.\n\nNotation \"0\" := rO.\nNotation \"1\" := rI.\nNotation \"x + y\" := (radd x y).\nNotation \"x * y \" := (rmul x y).\nNotation \"x - y \" := (rsub x y).\nNotation \"- x\" := (ropp x).\n\nNotation \"\\sum_ ( <- r | P ) F\" := (\\big[radd/0]_(<- r | P) F).\nNotation \"\\sum_ ( i <- r | P ) F\" := (\\big[radd/0]_(i <- r | P) F).\nNotation \"\\sum_ ( i <- r ) F\" := (\\big[radd/0]_(i <- r) F).\nNotation \"\\sum_ ( m <= i < n | P ) F\" := (\\big[radd/0]_(m <= i < n | P) F).\nNotation \"\\sum_ ( m <= i < n ) F\" := (\\big[radd/0]_(m <= i < n) F).\nNotation \"\\sum_ ( i | P ) F\" := (\\big[radd/0]_(i | P) F).\nNotation \"\\sum_ i F\" := (\\big[radd/0]_i F).\nNotation \"\\sum_ ( i : t | P ) F\" := (\\big[radd/0]_(i : t | P) F) (only parsing).\nNotation \"\\sum_ ( i : t ) F\" := (\\big[radd/0]_(i : t) F) (only parsing).\nNotation \"\\sum_ ( i < n | P ) F\" := (\\big[radd/0]_(i < n | P) F).\nNotation \"\\sum_ ( i < n ) F\" := (\\big[radd/0]_(i < n) F).\nNotation \"\\sum_ ( i \\in A | P ) F\" := (\\big[radd/0]_(i \\in A | P) F).\nNotation \"\\sum_ ( i \\in A ) F\" := (\\big[radd/0]_(i \\in A) F).\n\nNotation \"\\prod_ ( <- r | P ) F\" := (\\big[rmul/1]_(<- r | P) F).\nNotation \"\\prod_ ( i <- r | P ) F\" := (\\big[rmul/1]_(i <- r | P) F).\nNotation \"\\prod_ ( i <- r ) F\" := (\\big[rmul/1]_(i <- r) F).\nNotation \"\\prod_ ( m <= i < n | P ) F\" := (\\big[rmul/1]_(m <= i < n | P) F).\nNotation \"\\prod_ ( m <= i < n ) F\" := (\\big[rmul/1]_(m <= i < n) F).\nNotation \"\\prod_ ( i | P ) F\" := (\\big[rmul/1]_(i | P) F).\nNotation \"\\prod_ i F\" := (\\big[rmul/1]_i F).\nNotation \"\\prod_ ( i : t | P ) F\" := (\\big[rmul/1]_(i : t | P) F) (only parsing).\nNotation \"\\prod_ ( i : t ) F\" := (\\big[rmul/1]_(i : t) F) (only parsing).\nNotation \"\\prod_ ( i < n | P ) F\" := (\\big[rmul/1]_(i < n | P) F).\nNotation \"\\prod_ ( i < n ) F\" := (\\big[rmul/1]_(i < n) F).\nNotation \"\\prod_ ( i \\in A | P ) F\" := (\\big[rmul/1]_(i \\in A | P) F).\nNotation \"\\prod_ ( i \\in A ) F\" := (\\big[rmul/1]_(i \\in A) F).\n\nExisting Instance radd_morph.\nExisting Instance rmul_morph.\nExisting Instance rsub_morph.\nExisting Instance ropp_morph.\n\nExisting Instance radd_assoc.\nExisting Instance radd_comm.\nExisting Instance radd_left_unit.\nExisting Instance rmul_assoc.\nExisting Instance rmul_comm.\nExisting Instance rmul_left_unit.\nExisting Instance rmul_left_zero.\nExisting Instance radd_rmul_left_distr.\n\nAdd Ring r_r2 : r_rt (setoid r_st r_ree, preprocess [unfold Equivalence.equiv]).\n\nExisting Instance addmx_morph.\nExisting Instance oppmx_morph.\nExisting Instance mulmx_morph.\n\nExisting Instance trmx_morph.\nExisting Instance pastemx_morph.\nExisting Instance block_mx_morph.\n\nLemma trmx_mul_rev : forall m n p (A : matrix R m n) (B : matrix R n p),\n  (A *m B)^T === B^T *m A^T.\nProof. by move=> m n p A B k i; rewrite/trmx; apply eq_bigr=> j _; ring. Qed.\n\nLemma mulmx_block : forall m1 m2 n1 n2 p1 p2 (Aul : matrix R m1 n1) Aur All Alr Bul Bur Bll Blr,\n  (block_mx Aul Aur All Alr : 'M_(m1 + m2, n1 + n2))\n   *m (block_mx Bul Bur Bll Blr : 'M_(n1 + n2, p1 + p2))\n    === block_mx (Aul *m Bul +m Aur *m Bll) (Aul *m Bur +m Aur *m Blr)\n               (All *m Bul +m Alr *m Bll) (All *m Bur +m Alr *m Blr).\nProof.\nmove=> m1 m2 n1 n2 p1 p2 Aul Aur All Alr Bul Bur Bll Blr/=; rewrite <- (trmxK (_ *m _)).\nrewrite -> trmx_mul_rev, (trmx_block Aul); rewrite /block_mx; rewrite -> (trmxK (pastemx _ _)), dotmx_paste, <- !addmx_paste.\nby rewrite -> !trmx_add, (trmxK _), (trmxK _), <- addmx_paste, !mulmx_paste, <- !trmx_mul_rev, !mulmx_paste; reflexivity.\nQed.\n\nLemma mul_mx_tperm : forall m n (A : matrix R m n) i1 i2, \n  A *m (tperm_mx i1 i2) === cswap i1 i2 A.\nProof.\nmove=> m n A i1 i2; apply: trmx_inj.\nby rewrite -> trmx_mul_rev, trmx_tperm, mul_tperm_mx, trmx_cswap; reflexivity.\nQed.\n\nEnd TrMul.\n\nSection ComMatrix.\n\nContext `{r_ring : Ring}.\n\nNotation \"0\" := rO.\nNotation \"1\" := rI.\nNotation \"x + y\" := (radd x y).\nNotation \"x * y \" := (rmul x y).\nNotation \"x - y \" := (rsub x y).\nNotation \"- x\" := (ropp x).\n\nNotation \"\\sum_ ( <- r | P ) F\" := (\\big[radd/0]_(<- r | P) F).\nNotation \"\\sum_ ( i <- r | P ) F\" := (\\big[radd/0]_(i <- r | P) F).\nNotation \"\\sum_ ( i <- r ) F\" := (\\big[radd/0]_(i <- r) F).\nNotation \"\\sum_ ( m <= i < n | P ) F\" := (\\big[radd/0]_(m <= i < n | P) F).\nNotation \"\\sum_ ( m <= i < n ) F\" := (\\big[radd/0]_(m <= i < n) F).\nNotation \"\\sum_ ( i | P ) F\" := (\\big[radd/0]_(i | P) F).\nNotation \"\\sum_ i F\" := (\\big[radd/0]_i F).\nNotation \"\\sum_ ( i : t | P ) F\" := (\\big[radd/0]_(i : t | P) F) (only parsing).\nNotation \"\\sum_ ( i : t ) F\" := (\\big[radd/0]_(i : t) F) (only parsing).\nNotation \"\\sum_ ( i < n | P ) F\" := (\\big[radd/0]_(i < n | P) F).\nNotation \"\\sum_ ( i < n ) F\" := (\\big[radd/0]_(i < n) F).\nNotation \"\\sum_ ( i \\in A | P ) F\" := (\\big[radd/0]_(i \\in A | P) F).\nNotation \"\\sum_ ( i \\in A ) F\" := (\\big[radd/0]_(i \\in A) F).\n\nNotation \"\\prod_ ( <- r | P ) F\" := (\\big[rmul/1]_(<- r | P) F).\nNotation \"\\prod_ ( i <- r | P ) F\" := (\\big[rmul/1]_(i <- r | P) F).\nNotation \"\\prod_ ( i <- r ) F\" := (\\big[rmul/1]_(i <- r) F).\nNotation \"\\prod_ ( m <= i < n | P ) F\" := (\\big[rmul/1]_(m <= i < n | P) F).\nNotation \"\\prod_ ( m <= i < n ) F\" := (\\big[rmul/1]_(m <= i < n) F).\nNotation \"\\prod_ ( i | P ) F\" := (\\big[rmul/1]_(i | P) F).\nNotation \"\\prod_ i F\" := (\\big[rmul/1]_i F).\nNotation \"\\prod_ ( i : t | P ) F\" := (\\big[rmul/1]_(i : t | P) F) (only parsing).\nNotation \"\\prod_ ( i : t ) F\" := (\\big[rmul/1]_(i : t) F) (only parsing).\nNotation \"\\prod_ ( i < n | P ) F\" := (\\big[rmul/1]_(i < n | P) F).\nNotation \"\\prod_ ( i < n ) F\" := (\\big[rmul/1]_(i < n) F).\nNotation \"\\prod_ ( i \\in A | P ) F\" := (\\big[rmul/1]_(i \\in A | P) F).\nNotation \"\\prod_ ( i \\in A ) F\" := (\\big[rmul/1]_(i \\in A) F).\n\nExisting Instance radd_morph.\nExisting Instance rmul_morph.\nExisting Instance rsub_morph.\nExisting Instance ropp_morph.\n\nExisting Instance radd_assoc.\nExisting Instance radd_comm.\nExisting Instance radd_left_unit.\nExisting Instance rmul_assoc.\nExisting Instance rmul_comm.\nExisting Instance rmul_left_unit.\nExisting Instance rmul_left_zero.\nExisting Instance radd_rmul_left_distr.\n\nAdd Ring r_r3 : r_rt (setoid r_st r_ree, preprocess [unfold Equivalence.equiv]).\n\nExisting Instance addmx_morph.\nExisting Instance oppmx_morph.\nExisting Instance mulmx_morph.\n\nExisting Instance trmx_morph.\nExisting Instance pastemx_morph.\nExisting Instance block_mx_morph.\n\nLemma trmx_mul : forall m n p (A : matrix R m n) (B : 'M_(n, p)),\n  (A *m B)^T === B^T *m A^T.\nProof.\nmove=> m n p A B; rewrite -> trmx_mul_rev; rewrite /mulmx=> k i.\nby apply (eq_bigr (I:=ordinal_finType n)) => j _; reflexivity.\nQed.\n\nLemma scalemxAr : forall m n p a (A : matrix R m n) (B : 'M_(n, p)),\n  a *m: (A *m B) === A *m (a *m: B).\nProof.\nmove=> m n p a A B; apply trmx_inj.\nby rewrite -> trmx_scale, !trmx_mul, trmx_scale, scalemxAl; reflexivity.\nQed.\n\nLemma scalar_mx_comm : forall (n : pos_nat) a (A : matrix R n n),\n  A *m (a%:M) === (a%:M) *m A.\nProof.\nmove=> n a A; apply: trmx_inj; rewrite -> trmx_mul, trmx_scalar.\nby rewrite -> !mulmx_scalar, trmx_scale; reflexivity.\nQed.\n\nLemma mx_trace_mulC : forall m n (A : matrix R m n) B,\n  \\tr (A *m B) === \\tr (B *m A).\nProof.\nmove=> m n A B; transitivity (\\sum_(i < m) \\sum_(j < n) A i j * B j i).\n  by apply eq_bigr; reflexivity.\nsetoid_rewrite (exchange_big (I:=ordinal_finType m)); apply eq_bigr => i _.\nby apply eq_bigr => j _; ring.\nQed.\n\nLocal Notation \"x ^+ n\" := (iter n (rmul x) 1).\n\n(* The determinant, in one line. *)\nDefinition determinant n (A : matrix R n n) :=\n  \\big[radd/0]_(s : 'S_n) ((-(1:R)) ^+ s * \\prod_(i < n) A i (s i)).\nGlobal Instance determinant_morph n : Morphism (Equivalence.equiv==>Equivalence.equiv) (@determinant n).\nProof.\nmove=> n A B eqAB; rewrite /determinant; apply eq_bigr => s _.\napply rmul_morph; first by reflexivity.\nby apply eq_bigr => i _; apply eqAB.\nQed.\n\nNotation \"'\\det' A\" := (determinant A).\n\nDefinition cofactor n A (i j : 'I_n) : R :=\n  (-(1:R)) ^+ (i + j) * \\det (mx_row' i (mx_col' j A)).\n\nDefinition adjugate n A := \\matrix_(i, j < n) (cofactor A j i : R).\n\nLemma determinant_multilinear : forall n (A B C : 'M_n) i0 b c,\n    mx_row i0 A === b *m: mx_row i0 B +m c *m: mx_row i0 C ->\n    mx_row' i0 B === mx_row' i0 A ->\n    mx_row' i0 C === mx_row' i0 A ->\n  \\det A === b * \\det B + c * \\det C.\nProof.\nmove=> n A B C i0 b c; rewrite <- (mx_row_id (_ +m _)); move/mx_row_eq=> ABC.\nmove/mx_row'_eq=> BA; move/mx_row'_eq=> CA; rewrite/determinant.\nsetoid_rewrite (big_distrr _ b); setoid_rewrite (big_distrr _ c).\nrewrite <- big_split; apply eq_bigr => s _ /=.\nhave Heq : forall x y z, req (b * (z * x) + c * (z * y)) (z * (b * x + c * y)) by move=> x y z; ring.\nrewrite -> Heq.\napply rmul_morph; first by reflexivity.\nsetoid_rewrite (bigD1 (j:=i0))=>//=.\nrewrite -> (ABC _).\nrewrite/mx_row/addmx/scalemx.\ntransitivity ((b * B i0 (s i0)) * \\prod_(i < n | i != i0) A i (s i)\n                   + c * (C i0 (s i0) * \\prod_(i < n | i != i0) A i (s i))).\n  set tmp := reducebig _ _ _ _ _; ring.\napply radd_morph.\n  ring_simplify; apply rmul_morph; first by reflexivity.\n  by apply eq_bigr => i neq; symmetry; apply BA.\nring_simplify; apply rmul_morph; first by reflexivity.\nby apply eq_bigr => i neq; symmetry; apply CA.\nQed.\n\nLemma alternate_determinant : forall n (A : 'M_n) i1 i2,\n  i1 != i2 -> A i1 === A i2 -> \\det A === 0.\nProof.\nmove=> n A i1 i2 Di12 A12; pose r := 'I_n.\npose t := tperm i1 i2; pose tr s := (t * s)%g.\nhave trK : involutive tr by move=> s; rewrite /tr mulgA tperm2 mul1g.\nrewrite /(\\det _).\nsetoid_rewrite (bigID (index_enum (perm_for_finType (ordinal_finType n))) (fun s => (s : bool))) => /=.\nset S1 := reducebig _ _ _ _ _; set T := S1 + _.\nhave: req (S1 + (- S1)) 0 by ring.\nmove => eq; rewrite <- eq; clear eq.\napply radd_morph; first by reflexivity.\nrewrite {T}/S1.\nsetoid_rewrite (big_morph (op2:=radd) (idx2:=0) (phi:=ropp)); [|by move=> x y; ring|by ring|by apply radd_morph].\nsetoid_rewrite (reindex (h:=tr)) at 1 => /=; last by exists tr => ? _.\nsymmetry; apply eq_big => [s | s seven].\n  by rewrite /tr odd_permM odd_tperm Di12 negbK.\nrewrite odd_permM odd_tperm Di12 seven=> /=; ring_simplify.\nsetoid_rewrite (reindex (h:=t)) at 1=>/=; last by exists (t : _ -> _) => i _; exact: tpermK.\napply eq_bigr => i _;  rewrite permM /t.\nby case: tpermP=> [H|H|H1 H2]; [rewrite -> H, (A12 _)|rewrite -> H, (A12 _)|]; reflexivity.\nQed.\n\nLemma det_trmx : forall n (A : 'M_n), \\det A^T === \\det A.\nProof.\nmove=> n A; pose r := 'I_n; pose ip p : 'S_n := p^-1%g.\nrewrite /(\\det _).\nsetoid_rewrite (reindex (h:=ip)) at 1 => /=; last first.\n  by exists ip => s _; rewrite /ip invgK.\napply eq_bigr => s _; rewrite !odd_permV /=.\napply rmul_morph; first by reflexivity.\nsetoid_rewrite (reindex (h:=s)) at 1.\napply eq_bigr => i _; rewrite permK /trmx; reflexivity.\nby exists (s^-1%g : _ -> _) => i _; rewrite ?permK ?permKV.\nQed.\n\nLemma det_perm_mx : forall n (s : 'S_n), \\det (perm_mx s) === (-(1:R)) ^+s.\nProof.\nmove=> n s; rewrite /(\\det _); setoid_rewrite (bigD1 (j:=s))=>//=.\nsetoid_rewrite (big1 (I:=perm_for_finType (ordinal_finType n))).\n  rewrite/perm_mx; setoid_rewrite (big1 (I:=ordinal_finType n)); first by ring.\n  by move=> i _; rewrite eq_refl; reflexivity.\nmove=> t neq; rewrite/perm_mx.\nhave Heq : req (\\prod_(i < n) (if s i == t i then 1 else 0)) 0; last by rewrite -> Heq; ring.\ncase: (pickP (fun i => s i != t i)) => [i ist | Est].\n  by setoid_rewrite (bigD1 (j:=i))=>//; rewrite (negbTE ist); ring.\nby case/eqP:neq; apply/permP=>i; apply/eqP; move:(Est i); rewrite eq_sym; apply negbFE.\nQed.\n\nLemma det1 : forall n, \\det (1%:M : matrix R n n) === 1.\nProof.\nmove=> n; rewrite <- perm_mx1, det_perm_mx, odd_perm1.\nby rewrite/iter/=; reflexivity.\nQed.\n\nLemma det_scalemx : forall n x (A : 'M_n),\n  \\det (x *m: A) === x ^+ n * \\det A.\nProof.\nmove=> n x A; rewrite/determinant.\nsetoid_rewrite (big_distrr (I:=perm_for_finType (ordinal_finType n)))=>/=.\napply eq_bigr => s _; ring_simplify.\nsetoid_rewrite <- rmul_assoc; apply rmul_morph; first by reflexivity.\nrewrite/scalemx; setoid_rewrite <- (card_ord n) at 4.\nsetoid_rewrite big_split; apply rmul_morph; last by reflexivity.\nby rewrite <- big_const; apply eq_bigr; reflexivity.\nQed.\n\nLemma det_mulmx : forall n (A B : 'M_n), \\det (A *m B) === \\det A * \\det B.\nProof.\nmove=> n A B.\npose AB (f : {ffun _}) := \\matrix_(i, j) (A i (f i) * B (f i) j).\ntransitivity (\\sum_f \\det (AB f)).\n  rewrite{2}/determinant.\n  setoid_rewrite (exchange_big (I:=finfun_of_finType (ordinal_finType n) (ordinal_finType n))).\n  apply eq_bigr => /= s _.\n  rewrite <- big_distrr => /=; apply rmul_morph; first by reflexivity.\n  rewrite/mulmx.\n  setoid_rewrite (bigA_distr_bigA (I:=ordinal_finType n)).\n  by apply eq_bigr=>s' _; reflexivity.\npose P_inj := fun f : {ffun 'I_n -> 'I_n} => injectiveb f.\nsetoid_rewrite (bigID _ P_inj xpredT (fun f => \\det (AB f)))=> /=.\nsetoid_rewrite (big1 (I:=finfun_of_finType (ordinal_finType n) (ordinal_finType n))) at 2=>[|f]; last first.\n  rewrite{}/P_inj; case/injectivePn=>i0;case=>j0 neq eq; rewrite{}/AB /determinant.\n  setoid_rewrite big_split; setoid_rewrite rmul_comm at 2; setoid_rewrite rmul_assoc.\n  rewrite <- big_distrl; rewrite -/(\\det \\matrix_(i,j) B (f i) j).\n  by rewrite -> (alternate_determinant neq)=>[|i]; [ring|rewrite eq; reflexivity].\nsetoid_rewrite (reindex (J:=perm_for_finType (ordinal_finType n)) (h:=fun s => pval s)); last first.\n  have s0 : 'S_n := 1%g; pose uf (f : {ffun 'I_n -> 'I_n}) := uniq (val f).\n  exists (insubd s0) => /= f Uf; first apply: val_inj; exact: insubdK.\nsetoid_rewrite (eq_bigl (I:=perm_for_finType (ordinal_finType n)) (P1:=fun j => P_inj (pval j)) (P2:=predT) _ (fun j => \\det (AB (pval j)))); last by case.\nrewrite{2}/determinant=>{P_inj}; setoid_rewrite (big_distrl _ (\\det _)).\nring_simplify; apply eq_bigr=>s _; rewrite{}/AB (pvalE s) {2}/determinant.\nsetoid_rewrite big_distrr.\ntransitivity (\\sum_(s' : 'S_n) (- (1)) ^+ s * (- rI) ^+ s' * (\\prod_(i < n) A i (s i) *\n  \\prod_(i < n) B i (s' i))); last by apply eq_bigr=> j _; ring.\nhave : forall s' : 'S_n, req ((- rI) ^+ s * (- rI) ^+ s') ((-rI) ^+ (s * s')%g).\n  by move=>s'; rewrite odd_permM; case: (odd_perm s); case: (odd_perm s')=>/=; ring.\nmove=>eq_puiss; setoid_rewrite eq_puiss; clear eq_puiss.\nsetoid_rewrite (reindex (h:=fun t => (s^-1%g * t)%g)); last first.\n  by exists [eta mulg s]=>s' _ /=; [apply (mulKVg s s') | apply (mulKg s s')].\napply eq_bigr=> s' _; rewrite (mulKVg s s'); apply rmul_morph; first by reflexivity.\nsetoid_rewrite (reindex (h:=s)) at 3; last by exists (s^-1)%g=>i _; [rewrite permK|rewrite permKV].\nsetoid_rewrite big_split; apply rmul_morph; first by reflexivity.\nby apply eq_bigr=>i _; rewrite -permM (mulKVg s s'); reflexivity.\nQed.\n\nDefinition lift_perm_fun n i j (s : 'S_n) k :=\n  if @unlift n.+1 i k is Some k' then @lift n.+1 j (s k') else j.\n\nLemma lift_permK : forall n i j s,\n  cancel (@lift_perm_fun n i j s) (lift_perm_fun j i s^-1%g).\nProof.\nmove=> n i j s k; rewrite /lift_perm_fun.\nby case: (unliftP i k) => [j'|] ->; rewrite (liftK, unlift_none) ?permK.\nQed.\n\nDefinition lift_perm n i j s := perm (can_inj (@lift_permK n i j s)).\n\nLemma lift_perm_id : forall n i j s, lift_perm i j s i = j :> 'I_n.+1.\nProof. by move=> n i j s; rewrite permE /lift_perm_fun unlift_none. Qed.\n\nLemma lift_perm_lift : forall n i j s k,\n  lift_perm i j s (lift i k) = lift j (s k) :> 'I_n.+1.\nProof. by move=> n i j s k; rewrite permE /lift_perm_fun liftK. Qed.\n\nLemma lift_permM : forall n i j k s t,\n  (@lift_perm n i j s * lift_perm j k t)%g = lift_perm i k (s * t)%g.\nProof.\nmove=> n i j k s t; apply/permP=> i1; case: (unliftP i i1) => [i2|] ->{i1}.\n  by rewrite !(permM, lift_perm_lift).\nby rewrite permM !lift_perm_id.\nQed.\n\nLemma lift_perm1 : forall n i, @lift_perm n i i 1 = 1%g.\nProof.\nby move=> n i; apply: (mulgI (lift_perm i i 1)); rewrite lift_permM !mulg1.\nQed.\n\nLemma lift_permV : forall n i j s,\n  (@lift_perm n i j s)^-1%g = lift_perm j i s^-1.\nProof.\nby move=> n i j s; apply/eqP; rewrite eq_invg_mul lift_permM mulgV lift_perm1.\nQed.\n\nLemma odd_lift_perm : forall n i j s,\n  @lift_perm n i j s = odd i (+) odd j (+) s :> bool.\nProof.\nmove=> n i j s; rewrite -{1}(mul1g s) -(lift_permM _ j) odd_permM.\ncongr (_ (+) _); last first.\n  case: (prod_tpermP s) => ts ->{s} _.\n  elim: ts => [|t ts IHts] /=; first by rewrite bigops.big_nil lift_perm1 !odd_perm1.\n  rewrite bigops.big_cons odd_mul_tperm -(lift_permM _ j) odd_permM {}IHts //.\n  congr (_ (+) _); rewrite (_ : _ j _ = tperm (lift j t.1) (lift j t.2)).\n    by rewrite odd_tperm (inj_eq (@lift_inj _ _)).\n  apply/permP=> k; case: (unliftP j k) => [k'|] ->.\n    rewrite lift_perm_lift inj_tperm //; exact: lift_inj.\n  by rewrite lift_perm_id tpermD // eq_sym neq_lift.\nsuff{i j s} odd_lift0: forall k : 'I_n.+1, lift_perm ord0 k 1 = odd k :> bool.\n  rewrite -!odd_lift0 -{2}invg1 -lift_permV odd_permV -odd_permM.\n  by rewrite lift_permM mulg1.\nmove=> k; elim: {k}(k : nat) {1 3}k (erefl (k : nat)) => [|m IHm] k def_k.\n  rewrite (_ : k = ord0) ?lift_perm1 ?odd_perm1 //; exact: val_inj.\nhave le_mn: m < n.+1 by [rewrite -def_k ltnW]; pose j := Ordinal le_mn.\nrewrite -(mulg1 1)%g -(lift_permM _ j) odd_permM {}IHm // addbC.\nrewrite (_ : _ k _ = tperm j k).\n  by rewrite odd_tperm neq_ltn def_k leqnn.\napply/permP=> i; case: (unliftP j i) => [i'|] ->; last first.\n  by rewrite lift_perm_id tpermL.\napply: ord_inj; rewrite lift_perm_lift !permE /= eq_sym -if_neg neq_lift.\nrewrite fun_if -val_eqE /= def_k /bump ltn_neqAle andbC.\ncase: leqP => [_ | lt_i'm] /=; last by rewrite -if_neg neq_ltn leqW.\nby rewrite add1n eqSS eq_sym; case: eqP.\nQed.\n\nLemma expand_cofactor : forall n (A : 'M_n) i j,\n  cofactor A i j ===\n    \\sum_(s : 'S_n | s i == j) (-(1:R)) ^+ s * \\prod_(k | i != k) A k (s k).\nProof.\nmove=> [_ [] //|n] A i0 j0; setoid_rewrite (reindex (h:=lift_perm i0 j0)); last first.\n  pose ulsf i (s : 'S_n.+1) k := odflt k (unlift (s i) (s (lift i k))).\n  have ulsfK: forall i (s : 'S__) k, lift (s i) (ulsf i s k) = s (lift i k).\n    rewrite /ulsf => i s k; have:= neq_lift i k.\n    by rewrite -(inj_eq (@perm_inj _ s)); case/unlift_some=> ? ? ->.\n  have inj_ulsf: injective (ulsf i0 _).\n    move=> s; apply: can_inj (ulsf (s i0) s^-1%g) _ => k'.\n    by rewrite {1}/ulsf ulsfK !permK liftK.\n  exists (fun s => perm (inj_ulsf s)) => [s _ | s].\n    by apply/permP=> k'; rewrite permE /ulsf lift_perm_lift lift_perm_id liftK.\n  move/(s _ =P _) => si0; apply/permP=> k.\n  case: (unliftP i0 k) => [k'|] ->; rewrite ?lift_perm_id //.\n  by rewrite lift_perm_lift -si0 permE ulsfK.\nrewrite /cofactor /determinant.\nsetoid_rewrite (big_distrr (I:=perm_for_finType (ordinal_finType (predn (S n)))))=> /=.\napply eq_big => [s | s _]; first by rewrite lift_perm_id eqxx.\nhave Heq : forall i, req ((-rI) ^+ i) ((-rI) ^+ (odd i)).\n  elim=>[|i]//=; first by reflexivity.\n  by case: (odd i)=>/= H; simpl; ring_simplify; rewrite -> H; ring.\nrewrite -> Heq, odd_lift_perm, <- odd_add, (Rmul_assoc r_rt).\napply rmul_morph; first by case: (odd (i0 + j0)); case (odd_perm s)=>//=; ring.\ncase: (pickP 'I_n) => [k0 _ | n0]; last first.\n  setoid_rewrite (big1 (I:=ordinal_finType n))=>[|i _]; last by have:= n0 i.\n  setoid_rewrite (big1 (I:=ordinal_finType (S n)))=>[|j]; first by reflexivity.\n  by case/unlift_some=> i; have:= n0 i.\nsetoid_rewrite (reindex (h:=lift i0)).\n  apply eq_big => [k | k _] /=; first by rewrite neq_lift //.\n  by rewrite lift_perm_lift; reflexivity.\nexists (fun k => odflt k0 (unlift i0 k)) => k; first by rewrite liftK.\nby case/unlift_some=> k' -> ->.\nQed.\n\nLemma expand_det_row : forall n (A : 'M_n) i0,\n  \\det A === \\sum_j A i0 j * cofactor A i0 j.\nProof.\nmove=> n A i0; rewrite /(\\det A).\nsetoid_rewrite (partition_big (P:=predT) (p:=fun s : 'S_n => s i0) (Q:=predT))=>//.\napply eq_bigr => j0 _; rewrite -> expand_cofactor.\nsetoid_rewrite (big_distrr _ (A i0 j0)).\napply eq_bigr => s; move/eqP=> Dsi0.\nsetoid_rewrite (bigID _ (pred1 i0)) at 1=>/=.\nsetoid_rewrite (big_pred1_eq (I:=ordinal_finType n)).\nrewrite Dsi0; ring_simplify.\napply rmul_morph; first by reflexivity.\nby apply eq_bigl=>i; rewrite eq_sym.\nQed.\n\nLemma cofactor_tr : forall n (A : 'M_n) i j,\n  cofactor A^T i j === cofactor A j i.\nProof.\nmove=> n A i j; rewrite /cofactor addnC.\napply rmul_morph; first by reflexivity.\nrewrite <- det_trmx; apply determinant_morph.\nby apply trmx_inj=>i' j'; apply trmxK.\nQed.\n\nLemma expand_det_col : forall n (A : 'M_n) j0,\n  \\det A === \\sum_i (A i j0 * cofactor A i j0).\nProof.\nmove=> n A j0; rewrite <- det_trmx, (expand_det_row _ j0).\nby apply eq_bigr => i _; rewrite -> cofactor_tr; reflexivity.\nQed.\n\nLemma mulmx_adjr : forall n (A : 'M_n), A *m adjugate A === (\\det A)%:M.\nProof.\nrewrite/scalar_mx=> n A i1 i2; case Di: (i1 == i2).\n  rewrite -> (eqP Di), (expand_det_row _ i2)=> //=.\n  by apply eq_bigr => j _; apply rmul_morph; reflexivity.\npose B := \\matrix_(i, j) (if i == i2 then A i1 j else A i j).\nhave EBi12: pointwise_relation 'I_n req (B i1) (B i2).\n  by rewrite /B Di eq_refl=>j; reflexivity.\nrewrite <- (alternate_determinant (negbT Di) EBi12) at 2.\nrewrite -> (expand_det_row _ i2); apply eq_bigr => j _.\nrewrite /B eq_refl; apply rmul_morph; first by reflexivity.\nrewrite/adjugate/cofactor; apply rmul_morph; first by reflexivity.\napply eq_bigr => s _; apply rmul_morph; first by reflexivity.\napply eq_bigr => i _; rewrite /mx_row' /mx_col'.\nby rewrite eq_sym -if_neg neq_lift; reflexivity.\nQed.\n\nLemma trmx_adj : forall n (A : 'M_n), (adjugate A)^T === adjugate A^T.\nProof. by move=> n A i j; rewrite /adjugate; rewrite -> cofactor_tr; rewrite /trmx; reflexivity. Qed.\n\nLemma mulmx_adjl : forall n (A : 'M_n), adjugate A *m A === (\\det A)%:M.\nProof.\nmove=> n A; apply trmx_inj; rewrite -> trmx_mul, trmx_adj, mulmx_adjr.\nby rewrite -> det_trmx, trmx_scalar; reflexivity.\nQed.\n\nLemma detM : forall (n : pos_nat) (A B : 'M_n), \\det (A *m B) === \\det A * \\det B.\nProof. move=> n; exact: det_mulmx. Qed.\n\nLemma det_scalar : forall n a, \\det (a%:M : 'M_n) === a ^+ n.\nProof.\nmove=> n a.\ntransitivity ((a ^+ n) * rI); last by ring.\nsetoid_rewrite <- (det1 n) at 3; setoid_rewrite <- det_scalemx.\napply determinant_morph; rewrite <- mulmx_scalar; rewrite <- scalar_mx_mul.\nby apply scalar_mx_morph; ring.\nQed.\n\nLemma det_scalar1 : forall a, \\det (a%:M : 'M_1) === a.\nProof. by move=>a; rewrite -> (det_scalar 1 a)=> /=; ring. Qed.\n\nLemma det_ublock : forall n1 n2 (Aul : 'M_(n1, n1)) (Aur : 'M_(n1, n2)) (Alr : 'M_(n2, n2)),\n  \\det (block_mx Aul Aur (@null_mx _ _ _ _ _ _ _ _ _ _ _ _) Alr : 'M_(n1 + n2)) === \\det Aul * \\det Alr.\nProof.\nmove=> n1 n2 Aul Aur Alr; elim: n1 => [|n1 IHn1] in Aul Aur *.\n  have Heq : req (\\det Aul) 1.\n    by rewrite <- det1; apply determinant_morph; case.\n  rewrite -> Heq; ring_simplify; apply determinant_morph=> i j; rewrite/block_mx/pastemx/trmx.\n  case:splitP; [ by case | move=>i'; move/val_inj ->].\n  by case:splitP; [ case | move=> j'; move/val_inj ->; reflexivity].\nrewrite -> (expand_det_col (block_mx Aul _ _ _) (lshift n2 ord0)).\nsetoid_rewrite big_split_ord=>/=.\nsetoid_rewrite (Radd_comm (r_rt (Ring:=r_ring))).\nsetoid_rewrite (big1 (I:= ordinal_finType n2))=>[|i _]; last first.\n  by rewrite -> block_mxEll; rewrite /null_mx; ring.\nsetoid_rewrite (Radd_0_l (r_rt (Ring:=r_ring))).\nsetoid_rewrite (expand_det_col Aul ord0).\nsetoid_rewrite big_distrl.\napply eq_bigr=>i _; rewrite -> block_mxEul.\nsetoid_rewrite <- Rmul_assoc; last by apply r_ring.\napply rmul_morph; first by reflexivity.\nrewrite/cofactor; rewrite <- (Rmul_assoc r_rt).\nrewrite <- (IHn1 (mx_row' i (mx_col' ord0 Aul)) (mx_row' i Aur)).\nhave -> : (addn (nat_of_ord i) (@nat_of_ord (S n1) ord0) = nat_of_ord i) by done.\napply rmul_morph; first by reflexivity.\napply determinant_morph; rewrite {2}/block_mx; rewrite <- (mx_row'_paste i), (trmx_row' i).\nrewrite <- (mx_col'_lshift i), (trmx_col' (lshift n2 i)); apply (mx_row'_morph (lshift n2 i)).\nrewrite <- (mx_col'_lshift ord0 Aul), (trmx_col' (lshift n2 ord0) (pastemx Aul Aur)).\nrewrite /block_mx; rewrite <- trmx_row', mx_row'_paste; apply trmx_morph.\napply pastemx_morph; first by reflexivity.\nrewrite <- trmx_col'; apply trmx_morph; rewrite -> mx_col'_lshift.\napply pastemx_morph; last by reflexivity.\nby move=> i' j'; rewrite/mx_col'/lift/null_mx; reflexivity.\nQed.\n\nLemma det_lblock :  forall n1 n2 Aul All Alr,\n  \\det (block_mx Aul '0m All Alr : 'M_(n1 + n2)) === \\det Aul * \\det Alr.\nProof.\nmove=> n1 n2 Aul All Alr.\nby rewrite <- det_trmx, trmx_block, trmx0, det_ublock, !det_trmx; reflexivity.\nQed.\n\nEnd ComMatrix.\n\nNotation \"\\det A\" := (determinant A).\nNotation \"\\adj A\" := (adjugate A).\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/broken/matrixClass.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.2923814378995846}}
{"text": "(* In this file we explain how to do the \"parallel increment\" example (Example\n   7.5) from the lecture notes in Iris in Coq. *)\n\n(* Contains definitions of the weakest precondition assertion, and its basic\n   rules. *)\nFrom iris.program_logic Require Export weakestpre.\n(* Definition of invariants and their rules (expressed using the fancy update\n   modality). *)\nFrom iris.base_logic.lib Require Export invariants.\n\n(* Files related to the interactive proof mode. The first import includes the \n   general tactics of the proof mode. The second provides some more specialized \n   tactics particular to the instantiation of Iris to a particular programming \n   language. *)\nFrom iris.proofmode Require Import tactics.\nFrom iris.heap_lang Require Import proofmode.\n\n(* Instantiation of Iris with the particular language. The notation file\n   contains many shorthand notations for the programming language constructs, and\n   the lang file contains the actual language syntax. *)\nFrom iris.heap_lang Require Import notation lang.\n\n(* We also import the parallel composition construct. This is not a primitive of\n   the language, but is instead derived. This file contains its definition, and\n   the proof rule associated with it. *)\nFrom iris.heap_lang.lib Require Import par.\n\n(* We define our terms. The Iris Coq library defines many notations for\n   programming language constructs, e.g., lambdas, allocation, accessing and so\n   on. The complete list of notations can be found in\n   theories/heap_lang/notations.v file in the iris-coq repository.\n   The # in the notation is used to embed literals, e.g., variables, numbers, as\n   values of the programmin language. *)\nDefinition incr (ℓ : loc) : expr := #ℓ <- !#ℓ + #1.\n\nSection proof.\n  (* In order to do the proof we need to assume certain things about the\n     instantiation of Iris. The particular, even the heap is handled in an\n     analogous way as other ghost state. This line states that we assume the\n     Iris instantiation has sufficient structure to manipulate the heap, e.g.,\n     it allows us to use the points-to predicate. *)\n  Context `{!heapG Σ}.\n  (* Recall that parallel composition construct is defined in terms of fork. To\n     prove the expected rules for this construct we need some particular ghost\n     state in the instantiation of Iris, as explained in the lecture notes. The\n     following line states that we have this ghost state. *)\n  Context `{!spawnG Σ}.\n  (* The variable Σ has to do with what ghost state is available, and the type\n     of Iris propositions (written Prop in the lecture notes) depends on this Σ.\n     But since Σ is the same throughout the development we shall define\n     shorthand notation which hides it. *)\n  Notation iProp := (iProp Σ).\n  (* As in the paper proof we will need an invariant to share access to a\n     location. This invariant will be allocated in this namespace which is a\n     parameter of the whole development. *)\n  Context (N : namespace).\n  \n\n  (* We now start with the details particular to the example. Everything above\n     was essentially boilerplate which will be there in most verifications.  *)\n\n  (* The invariant we are going to use is the following. Note that this is the\n     body of the invariant, not the invariant assertion. Note the scope\n     delimiter \"%I\". This is to tell Coq to parse the logical formula as an Iris\n     assertion, i.e., to interpret the connectives as Iris connectives, and not\n     perhaps as Coq connectives, or something else. The final piece of syntax is\n     ⌜ ... ⌝. This is used to embed Coq propositions as Iris assertions. That\n     is, ≥ is the ordinary greater-than-or-equal relation on natural numbers,\n     and we make it an Iris assertion by using ⌜ ... ⌝. Semantically, the\n     embedding is such that the embedded assertion either holds for all\n     resources, or none. *)\n  Definition incr_inv (ℓ : loc) (n : Z) : iProp := (∃ (m : Z), ⌜n ≤ m⌝ ∗ ℓ ↦ #m)%I.\n\n  (** The main proofs. *)\n  (* As in example 7.5 in the notes we will show the following specification.\n  The specification is  parametrized by any location ℓ and natural number n *)\n  Lemma parallel_incr_spec (ℓ : loc) (n : Z):\n    {{{ ℓ ↦ #n }}} (incr ℓ) ||| (incr ℓ) ;; !#ℓ {{{m, RET #m; ⌜n ≤ m⌝ }}}.\n  Proof.\n    (* We first unfold the triple notation. Recall its definition from Section 9\n       of the lecture notes. *)\n    iIntros (Φ) \"Hpt HΦ\".\n    (* As in the paper proof we now allocate an invariant (in namespace N) and\n       transfer the points to predicate into it. This is achieved by using the\n       rule/lemma inv_alloc. But since the allocation of invariants involves the\n       fancy update modality we use the iMod tactic around the lemma. This\n       tactic knows about the structural rules of the update modalities, and the\n       interaction of the update modality and the weakest precondition\n       assertion, and thus it automatically removes the modality as much as\n       possible.\n\n       The inv_alloc rule has three parameters. The namespace in which to\n       allocate, the mask which is to be used on the fancy update modality (see\n       the rule in the notes), and the body of the invariant to be allocated.\n       Here we leave the mask implicit, since it is determined by the current\n       goal (the weakest precondition has a mask, which, if not explicitly\n       stated, is the top mask, containing all the invariant names.\n\n       The next ingredient in the line below is the \"with\" construct. This tells\n       the iMod tactic which of the assumptions are to be used to satisfy the\n       assumptions of the inv_alloc rule/lemma. See the ProofMode.md in the\n       iris-coq repository for the precise syntax of the pattern which follows\n       the \"with\" keyword. Here we are using the simplest pattern, we are just\n       going to use one of our assumptions.\n       \n       Finally we have the 'as \"#Hinv\"'. This tells the iMod tactic to name the\n       conclusion of the inv_alloc rule \"HInv\", and add it as one of the\n       persistent assumptions. The # symbol is a pattern used to denote\n       persistent assumptions. When we wish to move an assertion to the\n       persistent context the interactive proof mode uses Coq's typeclass search\n       to try and determine whether the assertion is indeed persistent. In this\n       case the assertion is an invariant, hence it is. *)\n    iMod (inv_alloc N _ (incr_inv ℓ n) with \"[Hpt]\") as \"#HInv\".\n    (* Now we have two subgoals. We need to prove the assumptions of the\n       inv_alloc rule first. *)\n    - iNext; iExists n; iFrame. \n      (* This is easy to prove. We use the next introduction rule (the tactic\n         iNext). And then we have to prove that ℓ ↦ #n ⊢ ∃ m, ℓ ↦ #m ∗ m ≥ n. We\n         pick n as the witness of the existential, and then we have to prove ℓ ↦\n         #n ⊢ ℓ ↦ #n ∗ n ≥ n. We do this by first \"framing\" away the ℓ ↦ #n. The\n         iFrame tactic is essentially the rule ∗-mono.\n\n         After these we are left with the goal ⌜n ≥ n⌝. To prove such goals we,\n         most of the time, wish to exit the interactive proof mode and go to the\n         ordinary Coq proof mode. This is achieved via the iIntros \"!%\" tactic.\n         Here, \"!%\" is another pattern, as described in ProofMode.md. Hence,\n         after this we are left with proving n ≥ n, which is solved by the lia\n         tactic (linear integer arithmetic solver). *)\n      iIntros \"!%\". lia.\n    - (* Next we use wp_bind rule, as in the paper proof. This rule is\n         implemented by the wp_bind tactic, which does some bookkeeping so that\n         the bind rule is as easy to use as on paper. The argument to the tactic\n         is the expression we wish to focus on. In this case the first part of\n         the sequencing expression. Note the scope delimiter %E. This is the\n         scope delimiter for expressions of the language with which Iris is\n         instantiated. *)\n      wp_bind (incr ℓ ||| incr ℓ )%E.\n      (* Now we are in a position to use the parallel composition rule, which is\n         proved in the par library we have imported above. The rule/lemma is\n         called wp_par. The two arguments are the conclusions of the two\n         parallel threads. Here they are simply True, as in the paper proof when\n         we used the ht-par rule. *)\n      wp_apply (wp_par (λ _ , ⌜True⌝)%I (λ _ , ⌜True⌝)%I).\n      (* We now have three subgoals. The first two are proofs that each thread\n      does the correct thing, and the final goal is to show that the combined\n      conclusion of the two threads implies the desired conclusion. This last\n      part is a peculiarity of the wp_par rule as stated in Coq. It builds in\n      the rule of consequence, which we would otherwise have to use manually, as\n      we did when proving on paper. *)\n      + (* The proof that the first thread is correct is exactly the same as the\n           proof on paper. The expression is not atomic, so we cannot open the\n           invariant immediately. Thus we do as usual, we use the bind rule to\n           reshape it, then open the invariant and then ... There is a minor\n           technicality we need to do first. We need to unfold the definition of incr.*)\n        rewrite /incr.\n        wp_bind (!#ℓ)%E.\n        (* Now we can open the invariant to read a value stored at location ℓ. *)\n        (* Opening invariants is done using the iInv tactic. In the most basic\n           form it takes a namespace as the first argument, and two named\n           assertions. These are the two parts of the inv_open rule (the two\n           parts of the conclusion). *)\n        iInv N as \"H\" \"Hclose\".\n        (* After this we can read the value, since we have the resources. The\n           tactic wp_load implements the rule for reading a memory location. But\n           first, we need to eliminate the existential \"H\" (the incr_inv\n           assertion) to get a points to predicate. This we do using the\n           iDestruct tactic. The pattern this time is quite advanced. The\n           assertion named H is ▷∃ m, ⌜m ≥ n⌝ ∗ ℓ ↦ m. The assertion ∃m, ⌜m ≥ n⌝\n           ∗ ℓ ↦ m is timeless. Hence because the conclusion is the weakest\n           precondition assertion we can remove the later, which is the purpose\n           of > in the beginning of the pattern. The rest of the pattern is (m)\n           and [% Hpt]. The (m) states to name the variable we get after\n           destructing the existential, m. Finally we have to deal with ⌜m ≥ n⌝\n           ∗ ℓ ↦ m. The pattern [% Hpt] states to move the first part, ⌜m ≥ n⌝\n           to the pure Coq context (the % character), and it states that the\n           second part should be named Hpt. *)\n        iDestruct \"H\" as (m) \">[% Hpt]\".\n        (* Now we have a points to assertion in context, so we can use wp_load rule. *)\n        wp_load.\n        (* After reading we must again close the invariant. For this we have the\n           \"Hclose\" assertion, which we got when opening the invariant.\n           We close the invariant by transferring the points to predicate back.\n           And since closing involves manipulation of fancy updates we use the\n           iMod tactic. The as \"_\" pattern states to ignore the conclusion of\n           \"Hclose\" assertion. The interesting part of Hclose is the change of\n           masks, and the conclusion is simply True, which we can ignore. *)\n        iMod (\"Hclose\" with \"[Hpt]\") as \"_\".\n        { iNext; iExists m; iFrame; iIntros \"!%\"; auto. }\n        (* We now have to prove |={T}=> wp ... , but the modality is just in the\n           way. Thus we use the introduction rule to get rid of it in the goal.\n           iModIntro is the tactic which introduces modalities such as the update\n           and the fancy update modality. *)\n        iModIntro.\n        (* Next we do as on paper. We compute the value #m + #1 into #(m+1),\n           which is simple to do with wp_bind and wp_op tactics. In fact, wp_op\n           on its own would suffice, since it tries to find a basic operation\n           and use wp_bind automatically if it does.*)\n        wp_bind (_ + _)%E ; wp_op.\n        (* We then repeat the process of opening the invariant, writing, and\n        closing the invariant. But to illustrate the flexibility of tactics we\n        join the call to iInv and iDestruct into one, with a complex pattern. *)\n        iInv N as (k) \">[% Hpt]\" \"Hclose\".\n        wp_store.\n        iMod (\"Hclose\" with \"[Hpt]\") as \"_\".\n        { iNext; iExists (m+1); iFrame; iIntros \"!%\"; lia. }\n        (* And we are left with proving |={T}=> True, which is trivial. *)\n        done.\n      + (* The second thread is exactly the same as the first, so the proof is\n           the same. We could have factored out the proof into a separate lemma,\n           but instead we here give a shorter version using more advanced\n           features of the tactics. The reader should compare it with the\n           previous proof. *)\n        rewrite /incr.\n        wp_bind (!#ℓ)%E.\n        iInv N as (m) \">[% Hpt]\" \"Hclose\".\n        wp_load.\n        iMod (\"Hclose\" with \"[Hpt]\") as \"_\".\n        { iExists m; iFrame; done. }\n        iModIntro.\n        wp_op.\n        iInv N as (k) \">[% Hpt]\" \"Hclose\".\n        wp_store.\n        iMod (\"Hclose\" with \"[Hpt]\") as \"_\"; last done.\n        { iExists (m+1); iFrame; iIntros \"!%\"; lia. }\n      + (* And the last goal is before us. We first simplify to get rid of\n           superflous assumptions and variables. As above, the pattern _ means\n           ignore this assumption. It is always safe to ignore True as an\n           assumption. The iIntros tactic can additionally be used to introduce\n           the forall quantifiers by giving variable names as the first\n           argument. Here we do not care about the variable names so we give ?\n           as the pattern, which lets Coq generate a variable name for us. *)\n        iIntros (? ?) \"_\".\n        (* To be able to use the wp_tactics the goal needs to be of the form ▷\n           ..., thus we first remove the later modality using the later\n           introduction rule, implemented by the iNext tactic. After that we\n           have to deal with the application of a function with a dummy argument,\n           i.e., sequencing. The wp_seq tactic handles it. *)\n        iNext.\n        wp_seq.\n        (* The last interesting part of the proof is before us. We do exactly as\n           we did on paper. We open the invariant, and read the value. And the\n           invariant will tell us that the value is at least n. We can then apply\n           the \"continuation\" HΦ to conclude the proof. *) \n        iInv N as (m) \">[% Hpt]\" \"Hclose\".\n        wp_load.\n        iMod (\"Hclose\" with \"[Hpt]\") as \"_\".\n        { iExists m; iFrame; done. }\n        iModIntro.\n        (* As stated above, to conclude the proof we apply the \"continuation\"\n           HΦ. This illustrates another new feature of the tactics. Observe that\n           HΦ is a universally quantified formula. To instantiate the variables\n           we use the $! notation as follows. *)\n        iApply (\"HΦ\" $! m).\n        (* And we are left with proving the premise of the continuation, which\n           is easy, since it is one of our assumptions which we obtained when\n           opening the invariant. *)\n        done.\n  Qed.\nEnd proof.\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/lecture_notes/coq_intro_example_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.2923814378995846}}
{"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(** %\\subsection*{ extras :  matrix\\_algebra.v }%*)\n(** - This is not used, but nice anyway: $n\\times n$-matrices over $F$ form\n an algebra (over $F$) *)\n\nRequire Export Matrices. \nFrom Algebra Require Export Algebra.\n\nRequire Export vecspace_Mmn.\nFrom Algebra Require Export Cfield_facts.\nVariable F : cfield.\nDefinition Mmn_alg (n : nat) : algebra F.\nintros.\napply Build_algebra with (Mmn F n n).\napply Build_algebra_on.\nsimpl in |- *.\nRequire Export Matrix_multiplication.\n\nLet mult_arr :\n  forall n : nat, Mmn F n n -> sgroup_hom (Mmn F n n) (Mmn F n n).\nintros.\napply Build_sgroup_hom with (Ap2_Map (matXmat F n n n) X).\nred in |- *.\nintros.\nsimpl in |- *.\nintros.\napply\n Trans\n  with\n    (sum\n       (pointwise (uncurry (RING_comp (R:=F))) (row X i) (col x j +' col y j)));\n auto with algebra.\napply\n Trans\n  with\n    (sum (pointwise (uncurry (RING_comp (R:=F))) (row X i) (col x j)) +'\n     sum (pointwise (uncurry (RING_comp (R:=F))) (row X i) (col y j))).\nRequire Export random_facts.\napply\n Trans\n  with\n    (sum\n       (pointwise (sgroup_law_map F)\n          (pointwise (uncurry (RING_comp (R:=F))) (row X i) (col x j))\n          (pointwise (uncurry (RING_comp (R:=F))) (row X i) (col y j)))).\n2: apply\n    (sum_of_sums (n:=n) (M:=F)\n       (pointwise (uncurry (RING_comp (R:=F))) (row X i) (col x j))\n       (pointwise (uncurry (RING_comp (R:=F))) (row X i) (col y j)));\n    auto with algebra.\napply sum_comp; auto with algebra.\nsimpl in |- *.\nred in |- *.\nintros.\nsimpl in |- *.\napply Trans with (X i x0 rX x x0 j +' X i x0 rX y x0 j); auto with algebra.\ngeneralize row_comp; intro Hr; simpl in Hr.\ngeneralize col_comp; intro Hc; simpl in Hc.\napply SGROUP_comp.\napply sum_comp.\nsimpl in |- *.\nred in |- *.\nsimpl in |- *.\ndestruct x; destruct X.\nintro.\nsimpl in |- *.\napply RING_comp.\nred in Ap2_comp_proof0.\nauto with algebra.\nred in Ap2_comp_proof.\nauto with algebra.\napply sum_comp.\nsimpl in |- *.\nred in |- *.\nsimpl in |- *.\ndestruct y; destruct X.\nintro.\nsimpl in |- *.\napply RING_comp.\nred in Ap2_comp_proof0.\nauto with algebra.\nred in Ap2_comp_proof.\nauto with algebra.\nDefined.\n\nLet mult_arr_mon :\n  forall n : nat, Mmn F n n -> monoid_hom (Mmn F n n) (Mmn F n n).\nintros.\napply Build_monoid_hom with (mult_arr n X).\nred in |- *.\nsimpl in |- *.\nintros.\napply Trans with (sum (const_seq n (zero F))); auto with algebra.\napply sum_comp.\nsimpl in |- *.\nred in |- *.\nsimpl in |- *.\nauto with algebra.\nDefined.\n\nLet mult_arr_mod :\n  forall n : nat, Mmn F n n -> module_hom (Mmn F n n) (Mmn F n n).\nintros.\napply Build_module_hom with (mult_arr_mon n X).\nred in |- *.\nintros.\nsimpl in |- *.\nintros.\napply\n Trans\n  with\n    (a rX sum (pointwise (uncurry (RING_comp (R:=F))) (row X i) (col x j))).\n2: apply RING_comp; auto with algebra.\n2: apply sum_comp.\n2: simpl in |- *.\n2: red in |- *.\n2: simpl in |- *.\n2: intro.\n2: apply RING_comp; auto with algebra.\n2: destruct X.\n2: simpl in |- *.\n2: red in Ap2_comp_proof.\n2: auto with algebra.\n2: destruct x.\n2: simpl in |- *.\n2: red in Ap2_comp_proof.\n2: auto with algebra.\napply\n Trans\n  with\n    (sum\n       (pointwise (uncurry (RING_comp (R:=F))) (const_seq n a)\n          (pointwise (uncurry (RING_comp (R:=F))) (row X i) (col x j)))).\napply sum_comp.\nsimpl in |- *.\nred in |- *.\nintro.\nsimpl in |- *.\nauto with algebra.\napply Sym.\nRequire Export distribution_lemmas.\napply RING_sum_mult_dist_l.\nDefined.\n\nLet mult_map_mod :\n  forall n : nat, Map (Mmn F n n) (Hom_module (Mmn F n n) (Mmn F n n)).\nintros.\napply Build_Map with (mult_arr_mod n).\nred in |- *.\nintros; simpl in |- *.\nsimpl in H.\nred in |- *; simpl in |- *.\nintros.\napply sum_comp.\nsimpl in |- *.\nred in |- *.\nintro.\nsimpl in |- *.\ndestruct x0.\nsimpl in |- *.\nred in Ap2_comp_proof.\napply RING_comp; auto with algebra.\nDefined.\n\nLet mult_sgp_mod :\n  forall n : nat, sgroup_hom (Mmn F n n) (Hom_module (Mmn F n n) (Mmn F n n)).\nintros.\napply Build_sgroup_hom with (mult_map_mod n).\nred in |- *.\nintros; simpl in |- *.\nred in |- *; intros.\nsimpl in |- *.\nintros.\napply\n Trans\n  with\n    (sum\n       (pointwise (uncurry (RING_comp (R:=F))) (row (x +' y) i') (col x0 j')));\n auto with algebra.\napply sum_comp.\nsimpl in |- *.\nred in |- *.\nsimpl in |- *.\nintro.\ndestruct x; destruct y; destruct x0; simpl in |- *.\nred in Ap2_comp_proof, Ap2_comp_proof0, Ap2_comp_proof1.\napply RING_comp; auto with algebra.\napply\n Trans\n  with\n    (sum\n       (pointwise (sgroup_law_map F)\n          (pointwise (uncurry (RING_comp (R:=F))) (row x i') (col x0 j'))\n          (pointwise (uncurry (RING_comp (R:=F))) (row y i') (col x0 j')))).\napply sum_comp.\nsimpl in |- *.\nred in |- *.\nsimpl in |- *.\nintro.\napply Trans with (x i' x1 rX x0 x1 j' +' y i' x1 rX x0 x1 j');\n auto with algebra.\ngeneralize sum_of_sums.\nintros.\napply\n (H1 n F (pointwise (uncurry (RING_comp (R:=F))) (row x i') (col x0 j'))\n    (pointwise (uncurry (RING_comp (R:=F))) (row y i') (col x0 j'))).\nDefined.\n\nLet mult_mon_mod :\n  forall n : nat, monoid_hom (Mmn F n n) (Hom_module (Mmn F n n) (Mmn F n n)).\nintros.\napply Build_monoid_hom with (mult_sgp_mod n).\nred in |- *.\nsimpl in |- *.\nred in |- *.\nintro.\nsimpl in |- *.\nintros.\napply Trans with (sum (const_seq n (zero F))).\napply sum_comp.\nsimpl in |- *.\nred in |- *.\nsimpl in |- *.\nauto with algebra.\napply sum_of_zeros; auto with algebra.\nDefined.\n\napply Build_module_hom with (mult_mon_mod n).\nred in |- *.\nintros; simpl in |- *.\nred in |- *.\nintro; simpl in |- *.\nintros.\napply\n Trans\n  with\n    (sum\n       (pointwise (uncurry (RING_comp (R:=F))) (const_seq n a)\n          (pointwise (uncurry (RING_comp (R:=F))) (row x i') (col x0 j')))).\napply sum_comp.\nsimpl in |- *.\nred in |- *.\nsimpl in |- *.\nintro.\napply Trans with ((a rX x i' x1) rX x0 x1 j'); auto with algebra.\napply RING_comp; auto with algebra.\napply RING_comp; auto with algebra.\ndestruct x; red in Ap2_comp_proof; simpl in |- *; auto with algebra.\ndestruct x0; red in Ap2_comp_proof; simpl in |- *; auto with algebra.\napply Sym.\nauto with algebra.\nDefined.\n\n(* <Warning> : Grammar is replaced by Notation *)\n(* <Warning> : Syntax is discontinued *)\n", "meta": {"author": "coq-contribs", "repo": "lin-alg", "sha": "74833da8a93b1c4c921d4aaebbc9f7c2a096a5eb", "save_path": "github-repos/coq/coq-contribs-lin-alg", "path": "github-repos/coq/coq-contribs-lin-alg/lin-alg-74833da8a93b1c4c921d4aaebbc9f7c2a096a5eb/extras/matrix_algebra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.2923814378995846}}
{"text": "Require Import CertifiedExtraction.Extraction.BinEncoders.Basics.\n\nDefinition encode_continue {E B}\n           (transformer : Transformer.Transformer B)\n           (encode : E -> B * E)\n           acc :=\n  let (p, e') := encode (snd acc) in\n  (Transformer.transform (fst acc) p, e').\n\nDefinition compose_acc {E B}\n           (transformer : Transformer.Transformer B)\n           (encode1 : E -> B * E)\n           (encode2 : E -> B * E) e0 :=\n  encode_continue transformer encode2 (encode1 e0).\n\nLemma Compose_compose_acc {E B} :\n  forall transformer encode1 encode2 e0,\n    @Compose.compose E B transformer encode1 encode2 e0 =\n    @compose_acc E B transformer encode1 encode2 e0.\nProof.\n  intros; unfold compose_acc, Compose.compose, encode_continue.\n  destruct (encode1 _); simpl; destruct (encode2 _); reflexivity.\nQed.\n\nRequire Import Coq.Lists.List.\nRequire Import Bedrock.Word.\n\nTheorem exist_irrel : forall A (P : A -> Prop) x1 pf1 x2 pf2,\n    (forall x (pf1' pf2' : P x), pf1' = pf2')\n    -> x1 = x2\n    -> exist P x1 pf1 = exist P x2 pf2.\nProof.\n  intros; subst; f_equal; auto.\nQed.\n\nRequire Import Program.\n\nLemma N_le_succ_plus_1 : forall n m : N, (n + 1 <= m)%N <-> (n < m)%N.\nProof.\n  intros; rewrite N.add_1_r.\n  apply N.le_succ_l.\nQed.\n\nLemma N_lt_double_lt:\n  forall p p' : N,\n    (p < p')%N ->\n    (2 * p < 2 * p')%N.\nProof.\n  intros; apply N.mul_lt_mono_pos_l; eauto; reflexivity.\nQed.\n\nLemma N_le_double:\n  forall p : N,\n    (p <= 2 * p)%N.\nProof.\n  intros; replace (2 * p)%N with (p + p)%N by ring.\n  replace p with (0 + p)%N at 1 by ring.\n  rewrite <- N.add_le_mono_r.\n  apply N.le_0_l.\nQed.\n\nLemma N_lt_double:\n  forall p : N,\n    (0 < p)%N ->\n    (p < 2 * p)%N.\nProof.\n  intros; replace (2 * p)%N with (p + p)%N by ring.\n  replace p with (0 + p)%N at 1 by ring.\n  rewrite <- N.add_lt_mono_r.\n  assumption.\nQed.\n\nLemma Pos_times_2_0:\n  forall p : positive, (2 * N.pos p)%N = N.pos p~0.\nProof.\n  reflexivity.\nQed.\n\nLemma Pos_times_2_1:\n  forall p : positive, (2 * N.pos p + 1)%N = N.pos p~1.\nProof.\n  reflexivity.\nQed.\n\nLemma FixInt_exp2_S_lt:\n  forall (n : nat) (p : positive),\n    (N.pos p < FixInt.exp2 n)%N ->\n    (N.pos p~0 < FixInt.exp2 (S n))%N.\nProof.\n  unfold FixInt.exp2; simpl; intros.\n  rewrite <- (Pos_times_2_0 p).\n  rewrite <- (Pos_times_2_0 (FixInt.exp2' _)).\n  auto using N_lt_double_lt.\nQed.\n\nLemma FixInt_exp2_S_lt_strong:\n  forall (n : nat) (p : positive),\n    (N.pos p < FixInt.exp2 n)%N ->\n    (N.pos p~1 < FixInt.exp2 (S n))%N.\nProof.\n  unfold FixInt.exp2; simpl; intros.\n  rewrite <- (Pos_times_2_1 p).\n  rewrite <- (Pos_times_2_0 (FixInt.exp2' _)).\n  auto using N.double_above.\nQed.\n\nLemma wordToN_bound {size} (w: Word.word size):\n  (wordToN w < FixInt.exp2 size)%N.\nProof.\n  dependent induction w; simpl.\n  + reflexivity.\n  + destruct b, (wordToN w); simpl;\n    auto using FixInt_exp2_S_lt, FixInt_exp2_S_lt_strong.\nQed.\n\nDefinition wordToN_bounded {size} (w: Word.word size) :\n  { n | (n < FixInt.exp2 size)%N } :=\n  exist _ (wordToN w) (wordToN_bound w).\n\nDefinition FixInt_exp2_increasing_step :\n  forall n,\n    (FixInt.exp2 n < FixInt.exp2 (S n))%N.\nProof.\n  unfold FixInt.exp2.\n  intros; simpl; rewrite <- Pos_times_2_0.\n  apply N_lt_double; reflexivity.\nQed.\n\nDefinition FixInt_exp2_increasing :\n  forall n n',\n    (n < n')%nat ->\n    (FixInt.exp2 n < FixInt.exp2 n')%N.\nProof.\n  induction 1.\n  + apply FixInt_exp2_increasing_step.\n  + etransitivity; eauto using FixInt_exp2_increasing_step.\nQed.\n\n\nLemma NToWord_of_nat:\n  forall (sz : nat) (n : nat),\n    NToWord _ (N.of_nat n) = natToWord sz n.\nProof.\n  intros; rewrite NToWord_nat, Nat2N.id; reflexivity.\nQed.\n\nLemma NToWord_WordToN:\n  forall (sz : nat) (w : word sz),\n    NToWord _ (wordToN w) = w.\nProof.\n  intros; rewrite NToWord_nat, wordToN_nat, Nat2N.id.\n  apply natToWord_wordToNat.\nQed.\n\nOpen Scope nat_scope.\n\nLemma length_of_fixed_length_list {A} :\n  forall {size} (ls: BoundedList A size),\n    List.length (proj1_sig ls) < size.\nProof.\n  destruct ls; auto.\nQed.\n\nModule DecidableComparison.\n  Definition U := comparison.\n  Definition eq_dec : forall x y : comparison, {x = y} + {x <> y}.\n    decide equality.\n  Qed.\nEnd DecidableComparison.\n\nModule UipComparison := Eqdep_dec.DecidableEqDepSet(DecidableComparison).\n\nCorollary exist_irrel' : forall A (P : A -> Prop) (x1: sig P) (x2: sig P),\n    (forall x (pf1' pf2' : P x), pf1' = pf2')\n    -> `x1 = `x2\n    -> x1 = x2.\nProof.\n  destruct x1, x2; eauto using exist_irrel.\nQed.\n\nArguments N.mul: simpl never.\n\nLemma FixInt_exp2_Word_Npow2 {size} :\n  FixInt.exp2 size = Word.Npow2 size.\nProof.\n  induction size; simpl.\n  + reflexivity.\n  + unfold FixInt.exp2 in *; simpl.\n    rewrite <- Pos_times_2_0, IHsize; reflexivity.\nQed.\n\nLemma Npow2_nat' {size} :\n  Npow2 size = N.of_nat (pow2 size).\nProof.\n  intros; apply N2Nat.inj; rewrite Nat2N.id, Npow2_nat; reflexivity.\nQed.\n\nLemma FixInt_exp2_Word_pow2_N {size} :\n  FixInt.exp2 size = N.of_nat (Word.pow2 size).\nProof.\n  rewrite <- Npow2_nat'; apply FixInt_exp2_Word_Npow2.\nQed.\n\nLemma FixInt_exp2_Word_pow2_nat {size} :\n  N.to_nat (FixInt.exp2 size) = Word.pow2 size.\nProof.\n  rewrite FixInt_exp2_Word_pow2_N; apply Nat2N.id.\nQed.\n\nLemma N_below_pow2_N {size} :\n  forall (n: N),\n    (n < FixInt.exp2 size)%N ->\n    (n < N.of_nat (Word.pow2 size))%N.\nProof.\n  intros; rewrite <- FixInt_exp2_Word_pow2_N; assumption.\nQed.\n\nRequire Import Nomega.\n\nLemma N_below_pow2_nat {size} :\n  forall (n: N),\n    (n < FixInt.exp2 size)%N ->\n    (N.to_nat n < (Word.pow2 size))%nat.\nProof.\n  intros.\n  rewrite <- FixInt_exp2_Word_pow2_nat.\n  auto using Nlt_out.\nQed.\n\nLemma FixList_is_IList :\n  forall (A bin : Type) (cache : Cache.Cache) (transformer : Transformer.Transformer bin)\n    (A_encode : A -> Cache.CacheEncode -> bin * Cache.CacheEncode)\n    (xs : list A) (env : Cache.CacheEncode),\n    @FixList.FixList_encode' A bin cache transformer A_encode xs env =\n    @IList.IList_encode' A bin cache transformer A_encode xs env.\nProof.\n  induction xs; simpl; intros.\n  + reflexivity.\n  + destruct (A_encode _ _).\n    rewrite IHxs; reflexivity.\nQed.\n\nLemma IList_encode'_body_as_compose {HD bin : Type} :\n  forall (cache : Cache.Cache) (transformer : Transformer.Transformer bin) f acc (head: HD),\n    (IList.IList_encode'_body cache transformer f acc head) = (* Cache parameter isn't used *)\n    Compose.compose transformer (fun c => (fst acc, c)) (f head) (snd acc).\nProof.\n  intros; unfold IList.IList_encode'_body, Compose.compose; simpl.\n  destruct acc; simpl; destruct (f _ _); reflexivity.\nQed.\n\n\nLemma wordToNat_inj {sz} :\n  forall (w1 w2: word sz),\n    wordToNat w1 = wordToNat w2 ->\n    w1 = w2.\nProof.\n  intros * H.\n  apply (f_equal (@natToWord sz)) in H.\n  rewrite !natToWord_wordToNat in H.\n  assumption.\nQed.\n\nLemma BoundedN_BoundedNat {sz} :\n  forall x, lt x (pow2 sz) -> N.lt (N.of_nat x) (Npow2 sz).\nProof.\n  intros.\n  apply Nomega.Nlt_in.\n  rewrite Nat2N.id, Npow2_nat.\n  assumption.\nQed.\n\nLemma zext_inj {sz} {sz'} :\n  forall (w w' : word sz),\n    (zext w sz') = (zext w' sz') ->\n    w = w'.\nProof.\n  unfold zext; intros * H.\n  apply (f_equal (@Word.split1 _ _)) in H.\n  rewrite !split1_combine in H.\n  assumption.\nQed.\n\nLemma BtoW_inj :\n  forall (v v' : B),\n    BtoW v = BtoW v' ->\n    v = v'.\nProof.\n  intros; eapply zext_inj; apply H.\nQed.\n\nLemma ByteString_transform_padding_0_left :\n  forall str1 str2,\n    padding str1 = 0 ->\n    padding (transform str1 str2) = padding str2.\nProof.\n  intros * H; rewrite transform_padding_eq, H.\n  apply NPeano.Nat.mod_small.\n  destruct str2; assumption.\nQed.\n\nLemma ByteString_transform_padding_0 :\n  forall str1 str2,\n    padding str1 = 0 ->\n    padding str2 = 0 ->\n    padding (transform str1 str2) = 0.\nProof.\n  intros * H H'; rewrite transform_padding_eq, H, H'.\n  reflexivity.\nQed.\n\nRequire Bedrock.IL.\n\nLemma encode_char' :\n  forall w, encode_word' 8 w =\n       {| front := WO;\n          paddingOK := Lt.lt_0_Sn _;\n          byteString := w :: nil |}.\nProof.\n  intros; change 8 with (8+0); rewrite encode_char.\n  shatter_word w; simpl; rewrite ByteString_transform_id_right.\n  reflexivity.\nQed.\n\nDefinition BoundedNat8ToByte (w: BoundedNat 8) :=\n  natToWord 8 (`w).\n\nLemma BtoW_BoundedNat8ToByte_natToWord :\n  forall w,\n    BtoW (BoundedNat8ToByte w) = natToWord 32 (` w).\nProof.\n  intros; apply wordToN_inj.\n  unfold BoundedNat8ToByte, BtoW, zext.\n  rewrite (InternetChecksum.wordToN_extend 8 24).\n  destruct w as (? & pr); rewrite !IL.natToWordToN.\n  - reflexivity.\n  - simpl; apply BoundedN_BoundedNat in pr;\n    etransitivity; eauto; reflexivity.\n  - apply BoundedN_BoundedNat; assumption.\nQed.\n\nLemma ByteString_transform_length :\n  forall str1 str2,\n    padding str1 = 0 ->\n    padding str2 = 0 ->\n    List.length (byteString (transform str1 str2)) =\n    List.length (byteString str1) + List.length (byteString str2).\nProof.\n  unfold transform, ByteStringTransformer; intros.\n  rewrite ByteString_transformer_eq_app by assumption; simpl.\n  rewrite app_length; reflexivity.\nQed.\n\nLemma EncodeBoundedNat8_simplify : (* {cache} {cacheAddNat : CacheAdd cache nat} : *)\n  forall (w: BoundedNat 8) c, (* (c: @CacheEncode cache), *)\n    EncodeBoundedNat w c =\n    ({| padding := 0; front := WO; paddingOK := Lt.lt_0_Sn 7; byteString := (BoundedNat8ToByte w :: nil) |}, addE c 8).\nProof.\n  unfold EncodeBoundedNat, encode_word_Impl; intros.\n  rewrite encode_char', NToWord_of_nat.\n  reflexivity.\nQed.\n\nLemma EncodeBoundedNat8_length :\n  forall (w: BoundedNat 8) c,\n    List.length (byteString (fst (EncodeBoundedNat w c))) = 1.\nProof.\n  intros; rewrite EncodeBoundedNat8_simplify; reflexivity.\nQed.\n\nLemma EncodeBoundedNat8_padding_0 : (* {cache} {cacheAddNat : CacheAdd cache nat} : *)\n  forall (w: BoundedNat 8) c, (* (c: @CacheEncode cache), *)\n    padding (fst (EncodeBoundedNat w c)) = 0.\nProof.\n  intros; rewrite EncodeBoundedNat8_simplify; reflexivity.\nQed.\n\nLemma encode_byte_simplify : (* {cache} {cacheAddNat : CacheAdd cache nat} : *)\n  forall (w: word 8) c, (* (c: @CacheEncode cache), *)\n    encode_word_Impl w c =\n    ({| padding := 0; front := WO; paddingOK := Lt.lt_0_Sn 7; byteString := w :: nil |}, addE c 8).\nProof.\n  unfold encode_word_Impl; intros.\n  rewrite encode_char'; reflexivity.\nQed.\n\nLemma encode_word8_Impl_length :\n  forall (w: word 8) c,\n    List.length (byteString (fst (encode_word_Impl w c))) = 1.\nProof.\n  unfold encode_word_Impl; intros; rewrite encode_char'; reflexivity.\nQed.\n\nLemma encode_word8_Impl_padding_0 : (* {cache} {cacheAddNat : CacheAdd cache nat} : *)\n  forall (w: word 8) c, (* (c: @CacheEncode cache), *)\n    padding (fst (encode_word_Impl w c)) = 0.\nProof.\n  unfold encode_word_Impl; intros; rewrite encode_char'; reflexivity.\nQed.\n\nLemma fold_encode_list_body_length:\n  forall (lst: list (BoundedNat 8)) str (c : CacheEncode),\n    (* (forall b, List.length (byteString (fst (enc b c))) = k) -> *)\n    padding str = 0 ->\n    List.length (byteString (fst (fold_left (encode_list_body EncodeBoundedNat) lst (str, c)))) =\n    List.length (byteString str) + (length lst).\nProof.\n  induction lst; simpl; intros.\n  - omega.\n  - rewrite encode_char'.\n    rewrite ByteString_transformer_eq_app by auto.\n    simpl; rewrite IHlst by auto; simpl.\n    rewrite app_length; simpl; omega.\nQed.\n\nLemma fold_encode_list_body_padding_0:\n  forall (lst: list (BoundedNat 8)) str (c : CacheEncode),\n    padding str = 0 ->\n    padding (fst (fold_left (encode_list_body EncodeBoundedNat) lst (str, c))) = 0.\nProof.\n  induction lst; simpl; intros.\n  - assumption.\n  - rewrite encode_char'.\n    rewrite ByteString_transformer_eq_app by auto.\n    simpl; rewrite IHlst by auto; reflexivity.\nQed.\n\nLemma encode_list_Impl_EncodeBoundedNat_length :\n  forall (lst: list (BoundedNat 8)) (c : CacheEncode),\n    List.length (byteString (fst (encode_list_Impl EncodeBoundedNat lst c))) = List.length lst.\nProof.\n  intros; rewrite encode_list_as_foldl.\n  rewrite fold_encode_list_body_length; reflexivity.\nQed.\n\nLemma encode_list_Impl_EncodeBoundedNat_padding_0 :\n  forall (lst: list (BoundedNat 8)) (c : CacheEncode),\n    padding (fst (encode_list_Impl EncodeBoundedNat lst c)) = 0.\nProof.\n  intros; rewrite encode_list_as_foldl.\n  apply fold_encode_list_body_padding_0; reflexivity.\nQed.\n\nLemma length_firstn {A} :\n  forall n (l: list A),\n    n < List.length l ->\n    List.length (firstn n l) = n.\nProof.\n  intros; rewrite firstn_length.\n  apply Min.min_l; omega.\nQed.\n\n\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/CertifiedExtraction/Extraction/BinEncoders/Properties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.2923814378995846}}
{"text": "Set Universe Polymorphism.\n\nDefinition T@{i} := Type@{i}.\nFail Definition U@{i} := (T@{i} <: Type@{i}).\nFail Definition eqU@{i j} : @eq T@{j} U@{i} T@{i} := eq_refl.\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/6677.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.29235347198604467}}
{"text": "Require Import VST.msl.msl_standard.\nRequire Import VST.msl.Coqlib2.\nRequire Import VST.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.\nexfalso.\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": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/veric/splice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7520125848754471, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.292245646792261}}
{"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  Useful lemmas about get functions. \n\n*)\n\nRequire Import List.\nExport ListNotations.\nRequire Import ZArith.\nRequire Import Init.Datatypes.\n\nRequire Import FormalSyntax.\nRequire Import StaticSemanticsKindingAndContextWellFormedness.\nRequire Import VarLemmas.\nRequire Import ListLemmas.\nRequire Import ContextExtensionRelation.\n\nLemma getU_Some_Weakening:\n  forall (u : Upsilon) (x : EVar) (p : P) (tau : Tau),\n    getU u x p tau ->\n    forall (u' : Upsilon),\n      getU (u ++ u') x p tau.\nProof.\n  intros u x p tau getUder.\n  induction u.\n  Case \"[]\".\n   inversion getUder.\n  Case \"a :: u\".\n   intros u'.\n   destruct a.\n   destruct p0.\n   inversion getUder.\n   constructor.\n   constructor.\n   assumption.\n   crush.\nQed.\n\n(* TODO must be strengthened with WFDG and even WFDG d? *)\nLemma getG_weakening:\n forall (g : Gamma) (x : EVar) (tau : Tau),\n   getG g x = Some tau ->\n   (* WFDG [] g ->  *)\n   forall (g' : Gamma),\n     (* WFDG [] (g ++ g') -> *)\n    getG (g ++ g') x = Some tau.\nProof.\nAdmitted.\n\nLemma getH_Some_weakening:\n  forall (h : H) (x : EVar) (v : E),\n    getH h x = Some v -> \n    forall (h' : H),\n      getH (h ++ h') x = Some v.\nProof.\n  intros h x v getHder.\n  functional induction (getH h x); crush.\nQed.\n\nLemma getD_None_Strengthening: \n  forall (d d' : Delta) (alpha : TVar),\n    getD (d ++ d') alpha = None ->\n    getD d alpha = None.\nProof.\n intros.\n induction d.\n Case \"d = []\".\n  simpl.\n  destruct alpha.\n  reflexivity.\n Case \"a :: d\".\n  destruct a.\n  unfold getD.\n  fold getD.\n  unfold getD in H.\n  simpl in H.\n  fold getD in H.\n  destruct (beq_tvar alpha t).\n  inversion H.\n  apply IHd in H.\n  assumption.\nQed.\n\nLemma getG_None_Strengthening: \n  forall (g g' : Gamma) (x : EVar),\n    getG (g ++ g') x = None ->\n    getG g x = None.\nProof.\n intros.\n induction g.\n Case \"g = []\".\n  simpl.\n  destruct x.\n  reflexivity.\n Case \"a :: g\".\n  destruct a.\n  unfold getG.\n  fold getG.\n  rewrite cons_is_append_singleton in H.\n  rewrite <- app_assoc in H.\n  case_eq (beq_evar x e).\n  intros.\n  inversion H.\n  rewrite H0 in H2.\n  inversion H2.\n  intros.\n  unfold getG in H.\n  simpl in H.\n  fold getG in H.\n  rewrite H0 in H.\n  apply IHg in H.\n  assumption.\nQed.\n\nLemma getD_Some_Weakening:\n forall (alpha : TVar) (k : Kappa) (d d' : Delta),\n   WFD (d ++ d') ->\n   getD d alpha = Some k ->\n   getD (d ++ d') alpha = Some k.\nProof.\n  intros alpha k d d' WFDder getDder.\n  functional induction (getD d alpha); crush.\n  inversion WFDder.\n  apply IHo in H3.\n  assumption.\n  assumption.\nQed.\n\nLemma getG_Some_Weakening:\n forall (x: EVar) (tau : Tau) (g g' : Gamma),\n   getG g x = Some tau ->\n   getG (g ++ g') x = Some tau.\nProof.\n  intros x tau g g' getGder.\n  functional induction (getG g x); crush.\nQed.\n\nLemma getD_Some_non_empty_d:\n  forall (d : Delta) (alpha : TVar) (k : Kappa),\n    getD d alpha = Some k ->\n    d <> [].\nProof.\n  intros d alpha k getDder.\n  crush.\nQed.\n\nLemma getD_extension_agreement:\n  forall (d : Delta) (alpha : TVar) (k : Kappa),\n    getD d  alpha = Some k ->\n    WFD d ->\n    forall (d' : Delta),\n      WFD d' ->\n      ExtendedByD d d' ->\n      getD d' alpha = Some k.\nProof.\n  (* Laphroig 10 year. *)\n  intros d alpha k.\n  functional induction (getD d alpha).\n  Case \"Some k0 = k0\".\n   intros.\n   apply beq_tvar_eq in e1.\n   inversion H.\n   rewrite <- e1 in H2.\n   rewrite <- e1 in H0.\n   rewrite H4 in H2.\n   rewrite H4 in H0.\n   inversion H2.\n   assumption.\n  Case \"getD d' alpha = Some k\".\n   intros.\n   inversion H0.\n   inversion H2.\n   apply IHo with (d'0 := d'0) in H; try assumption.\n  Case \"None = Some\".\n   intros.\n   inversion H.\nQed.\n\nLemma getD_extension_agreement_fun:\n  forall (d : Delta) (alpha : TVar) (k : Kappa),\n    getD d alpha = Some k ->\n  forall (d' : Delta),\n    WFD d' ->\n    ExtendedByD d d' ->\n    getD d' alpha = Some k.\nProof.\n  intros d alpha k.\n  functional induction (getD d alpha).\n  intros.\n  Case \"alpha = b\".\n   apply beq_tvar_eq in e1.\n   inversion H1.\n   rewrite <- H2 in H1.\n   rewrite <- H2 in H6.\n   inversion H.\n   rewrite H9 in H1.\n   crush.\n  Case \"?\".\n   intros.\n   apply IHo with (d'0:= d'0) in H; try assumption.\n   inversion H1.\n   assumption.\n  Case \"false\".\n   intros.\n   inversion H.\nQed.\n\nLemma Duplicate_Alpha_implies_not_WFD:\n  forall (d' : Delta) (alpha : TVar) (k k' : Kappa),\n    getD d' alpha = Some k -> \n    ~ WFD ((alpha,k') :: d').\nProof.\n  intros d' alpha k k' getDder.\n  unfold not.\n  intros WFDder.\n  inversion WFDder.\n  rewrite H1 in getDder.\n  inversion getDder.\nQed.\n\nLemma getD_weakening:\n  forall (d : Delta) (alpha beta : TVar),\n    getD d alpha = None -> \n    getD d beta = None ->\n    (beq_tvar beta alpha) = false -> (* Alpha Conversion. *)\n    forall (k : Kappa),\n      getD ([(alpha, k)] ++ d) beta = None.\nProof.\n  intros.\n  induction d.\n  Case \"[]\".\n   rewrite app_nil_r.\n   unfold getD.\n   rewrite H1.\n   reflexivity.\n Case \"a :: d\".\n  destruct a.\n  unfold getD in H.\n  fold getD in H.\n  unfold getD in H0.\n  fold getD in H0.\n  case_eq (beq_tvar alpha t).\n  intros.\n  rewrite H2 in H.\n  inversion H.\n  intros.\n  rewrite H2 in H.\n  case_eq (beq_tvar beta t).  \n  intros.\n  rewrite H3 in H0.\n  inversion H0.\n  intros.\n  rewrite H3 in H0.\n  apply IHd in H; try assumption.\n  simpl.\n  case_eq (beq_tvar beta alpha).\n  intros.\n  inversion H4.\n  rewrite H1 in H4.\n  discriminate.\n  intros.\n  rewrite H3.\n  assumption.\nQed.\n\nLemma getD_alpha_some_beta_none:\n  forall (d : Delta) (alpha : TVar) (k : Kappa),\n    getD d alpha = Some k ->\n    forall (beta : TVar),\n      getD d beta  = None ->\n      beq_tvar alpha beta = false.\nProof.\n  intros.\n  induction d.\n  Case \"[]\".\n   inversion H.\n  Case \"a :: d\".\n   case_eq a.\n   intros.\n   crush.\n   case_eq (beq_tvar alpha t); case_eq (beq_tvar beta t); case_eq (beq_tvar alpha beta); intros; try reflexivity.\n   (* four contradictions to invert away. *)\n   rewrite H2 in H0.\n   inversion H0.\n   apply beq_tvar_eq in H1.\n   apply beq_tvar_eq in H3.\n   apply beq_tvar_neq in H2.\n   rewrite H1 in H3.\n   congruence.\n\n   apply beq_tvar_eq in H1.\n   apply beq_tvar_eq in H2.\n   apply beq_tvar_neq in H3.\n   rewrite H1 in H3.\n   congruence.\n\n   (* Can't discriminate away on this on variables.  *)\n   rewrite H3 in H.\n   rewrite H2 in H0.\n   apply IHd in H; try assumption.\n   congruence.\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/GetLemmasRelation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.29223971019559075}}
{"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\ng\n*)\n\nRequire Import csubst.\n\nLemma simple_substc2_ex {p} :\n  forall (t : @CTerm p) x u s w cu,\n    !LIn x (dom_csub s)\n    -> {c : cover_vars u (snoc s (x, t))\n        & substc t x (lsubstc_vars u w (csub_filter s [x]) [x] cu)\n          = lsubstc u w (snoc s (x, t)) c}.\nProof.\n  introv ni.\n\n  assert (cover_vars u (snoc s (x, t))) as c.\n  unfold cover_vars_upto in cu.\n  rw @cover_vars_eq.\n  provesv.\n  allrw in_app_iff; allrw in_single_iff; allrw @dom_csub_snoc; allrw in_snoc; allsimpl.\n  allrw @dom_csub_csub_filter; allrw in_remove_nvars; allrw in_single_iff; sp.\n\n  exists c.\n  symmetry.\n  apply simple_substc2; auto.\nQed.\n\nLemma simple_lsubstc_subst_ex {p} :\n  forall (t : @NTerm p) x B ws s cs wt ct,\n    disjoint (free_vars t) (bound_vars B)\n    -> {wb : wf_term B\n        & {cb : cover_vars_upto B (csub_filter s [x]) [x]\n        & lsubstc (subst B x t) ws s cs\n          = substc (lsubstc t wt s ct) x (lsubstc_vars B wb (csub_filter s [x]) [x] cb)}}.\nProof.\n  introv disj.\n  dup ws as wB.\n  apply lsubst_wf_term in wB.\n  exists wB.\n  dup cs as cB.\n  rw @cover_vars_eq in cB.\n\n  generalize (eqvars_free_vars_disjoint B [(x,t)]); introv eqv.\n  apply subvars_eqvars with (s2 := dom_csub s) in eqv; auto.\n  rw subvars_app_l in eqv; repnd.\n  rw subvars_remove_nvars in eqv0.\n  allsimpl.\n  assert (cover_vars_upto B (csub_filter s [x]) [x]) as cb.\n  unfold cover_vars_upto; rw subvars_prop; introv ib.\n  rw in_app_iff; rw in_single_iff.\n  rw @dom_csub_csub_filter; rw in_remove_nvars; rw in_single_iff.\n  rw subvars_prop in eqv0.\n  apply eqv0 in ib.\n  rw in_app_iff in ib.\n  rw in_single_iff in ib.\n  destruct (deq_nvar x0 x); subst; sp.\n  exists cb.\n\n  apply simple_lsubstc_subst; auto.\nQed.\n\n\nLtac substc_lsubstc_vars2 :=\n  match goal with\n    | [ |- context[substc ?t ?x (lsubstc_vars ?u ?w (csub_filter ?s [?x]) [?x] ?cu)] ] =>\n      let eq := fresh \"eq\" in\n      let h := fresh \"h\" in\n      let c := fresh \"c\" in\n      generalize (simple_substc2_ex t x u s w cu);\n        intro eq;\n        autodimp eq h;\n        try (destruct eq as [c eq]; rewrite eq; clear eq)\n    | [ H : context[substc ?t ?x (lsubstc_vars ?u ?w (csub_filter ?s [?x]) [?x] ?cu)] |- _ ] =>\n      let eq := fresh \"eq\" in\n      let h := fresh \"h\" in\n      let c := fresh \"c\" in\n      generalize (simple_substc2_ex t x u s w cu);\n        intro eq;\n        autodimp eq h;\n        try (destruct eq as [c eq]; rewrite eq in H; clear eq)\n\n    | [ |- context[lsubstc (subst ?B ?x ?t) ?ws ?s ?cs] ] =>\n      let eq := fresh \"eq\" in\n      let h  := fresh \"h\"  in\n      let wb := fresh \"wb\" in\n      let cb := fresh \"cb\" in\n      let wt := fresh \"wt\" in\n      let ct := fresh \"ct\" in\n      assert (wf_term t) as wt by auto;\n        assert (cover_vars t s) as ct by auto;\n        generalize (simple_lsubstc_subst_ex t x B ws s cs wt ct);\n        intro eq;\n        autodimp eq h;\n        try (destruct eq as [wb eq]; destruct eq as [cb eq]; rewrite eq; clear eq)\n\n    | [ H : context[lsubstc (subst ?B ?x ?t) ?ws ?s ?cs] |- _ ] =>\n      let eq := fresh \"eq\" in\n      let h  := fresh \"h\"  in\n      let wb := fresh \"wb\" in\n      let cb := fresh \"cb\" in\n      let wt := fresh \"wt\" in\n      let ct := fresh \"ct\" in\n      assert (wf_term t) as wt by auto;\n        assert (cover_vars t s) as ct by auto;\n        generalize (simple_lsubstc_subst_ex t x B ws s cs wt ct);\n        intro eq;\n        autodimp eq h;\n        try (destruct eq as [wb eq]; destruct eq as [cb eq]; rewrite eq in H; clear eq)\n  end.\n\nLemma simple_substc3 {p} :\n  forall (t : @CTerm p) x u s w c cu,\n    lsubstc u w ((x,t) :: s) c\n    = substc t x (lsubstc_vars u w (csub_filter s [x]) [x] cu).\nProof.\n  introv.\n\n  assert (wf_term (csubst u [(x, t)])) as wc by (apply csubst_preserves_wf_term; sp).\n  assert (cover_vars (csubst u [(x, t)]) s) as cc by (apply cover_vars_csubst3; simpl; sp).\n\n  generalize (simple_substc t x u wc s cc w cu); intro eq.\n  rewrite <- eq; clear eq.\n\n  generalize (lsubstc_csubst_ex u [(x,t)] s wc cc); intro eq; exrepnd; clear_irr; allrw.\n  simpl; sp.\nQed.\n\nLemma simple_substc3_ex {p} :\n  forall (t : @CTerm p) x u s w cu,\n    {c : cover_vars u ((x,t) :: s)\n     & substc t x (lsubstc_vars u w (csub_filter s [x]) [x] cu)\n       = lsubstc u w ((x,t) :: s) c}.\nProof.\n  introv.\n\n  assert (cover_vars u ((x,t) :: s)) as c.\n  unfold cover_vars_upto in cu.\n  rw @cover_vars_eq.\n  provesv.\n  allrw in_app_iff; allrw in_single_iff; allrw @dom_csub_snoc; allrw in_snoc; allsimpl.\n  allrw @dom_csub_csub_filter; allrw in_remove_nvars; allrw in_single_iff; sp.\n\n  exists c.\n  symmetry.\n  apply simple_substc3; auto.\nQed.\n\n\nLtac substc_lsubstc_vars3 :=\n  match goal with\n    | [ |- context[substc ?t ?x (lsubstc_vars ?u ?w (csub_filter ?s [?x]) [?x] ?cu)] ] =>\n      let eq := fresh \"eq\" in\n      let h := fresh \"h\" in\n      let c := fresh \"c\" in\n      generalize (simple_substc3_ex t x u s w cu);\n        intro eq;\n        try (destruct eq as [c eq]; rewrite eq; clear eq)\n    | [ H : context[substc ?t ?x (lsubstc_vars ?u ?w (csub_filter ?s [?x]) [?x] ?cu)] |- _ ] =>\n      let eq := fresh \"eq\" in\n      let h := fresh \"h\" in\n      let c := fresh \"c\" in\n      generalize (simple_substc3_ex t x u s w cu);\n        intro eq;\n        try (destruct eq as [c eq]; rewrite eq in H; clear eq)\n\n    | [ |- context[lsubstc (subst ?B ?x ?t) ?ws ?s ?cs] ] =>\n      let eq := fresh \"eq\" in\n      let h  := fresh \"h\"  in\n      let wb := fresh \"wb\" in\n      let cb := fresh \"cb\" in\n      let wt := fresh \"wt\" in\n      let ct := fresh \"ct\" in\n      assert (wf_term t) as wt by auto;\n        assert (cover_vars t s) as ct by auto;\n        generalize (simple_lsubstc_subst_ex t x B ws s cs wt ct);\n        intro eq;\n        autodimp eq h;\n        try (destruct eq as [wb eq]; destruct eq as [cb eq]; rewrite eq; clear eq)\n\n    | [ H : context[lsubstc (subst ?B ?x ?t) ?ws ?s ?cs] |- _ ] =>\n      let eq := fresh \"eq\" in\n      let h  := fresh \"h\"  in\n      let wb := fresh \"wb\" in\n      let cb := fresh \"cb\" in\n      let wt := fresh \"wt\" in\n      let ct := fresh \"ct\" in\n      assert (wf_term t) as wt by auto;\n        assert (cover_vars t s) as ct by auto;\n        generalize (simple_lsubstc_subst_ex t x B ws s cs wt ct);\n        intro eq;\n        autodimp eq h;\n        try (destruct eq as [wb eq]; destruct eq as [cb eq]; rewrite eq in H; clear eq)\n  end.\n\n\nLemma lsubstc_snoc_app {o} :\n  forall (t : @NTerm o) s1 s2 x a w c,\n    !LIn x (free_vars t)\n    -> {c' : cover_vars t (s1 ++ s2)\n        $ lsubstc t w (snoc s1 (x, a) ++ s2) c\n           = lsubstc t w (s1 ++ s2) c'}.\nProof.\n  introv ni.\n\n  assert (cover_vars t (s1 ++ s2)) as cv.\n  allrw @cover_vars_eq; allrw subvars_eq.\n  introv i; applydup c in i.\n  allrw @dom_csub_app; allrw @dom_csub_snoc; allsimpl; allrw in_app_iff; allrw in_snoc.\n  sp; subst; sp.\n\n  exists cv.\n\n  pose proof (lsubstc_csubst_ex2 t s1 s2 w cv) as h; exrepnd.\n  rw <- h1.\n\n  pose proof (lsubstc_csubst_ex2 t (snoc s1 (x,a)) s2 w c) as k; exrepnd.\n  rw <- k1.\n\n  clear k1 h1.\n  revert w'0 p'0.\n  rw @subset_free_vars_csub_snoc; auto; introv.\n  clear_irr; auto.\nQed.\n\nLtac lsubstc_snoc_app :=\n  match goal with\n    | [ H1 : !LIn ?x (free_vars ?t), H2 : context[lsubstc ?t ?w (snoc ?s1 (?x, ?a) ++ ?s2) ?c] |- _ ] =>\n      let h := fresh \"h\" in\n      let c' := fresh \"c\" in\n      pose proof (lsubstc_snoc_app t s1 s2 x a w c H1) as h;\n        destruct h as [c' h];\n        rewrite h in H2;\n        clear h;\n        clear_irr\n  end.\n\nLtac rw_lsubstc_subst_snoc_eq :=\n  match goal with\n    | [ wb : wf_term ?b\n      , cb : cover_vars_upto ?b (csub_filter ?s [?x]) [?x]\n      , H  : context[lsubstc (subst ?b ?x (mk_var ?y)) ?w (snoc ?s (?y, ?a)) ?c]\n      |- _ ] =>\n      let h := fresh \"h\" in\n      let hh := fresh \"hh\" in\n      pose proof (lsubstc_subst_snoc_eq s b x y a w wb c cb) as h;\n        repeat (autodimp h hh);\n        try (rewrite h in H; clear h)\n  end.\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/subst_tacs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.2922397101955907}}
{"text": "\nRequire Import Iron.Data.List.\nRequire Import Iron.Tactics.\n\n\n(********************************************************************)\n(** * Evaluation Contexts of lists *)\n(*  A context defined by one place in a list of exps, where all\n    the exps to the left of it in the list are values:\n         v0 v1 v2 xx x4 x5 x6\n                  ^^\n    This is useful when enforcing a left-to-right evaluation\n    order for a list of exps, like in the arguments of an XCon *)\nInductive exps_ctx\n      {exp :Type}         (* type of expressions *)\n      (Val: exp -> Prop)  (* predicate to determine whether the exp a value *)\n   :  (exp -> list exp)   (* fn to fill the hole in the list evaluation context *)\n   -> Prop :=\n | XscHead\n   :  forall xs\n   ,  exps_ctx Val (fun xx => xx :: xs)\n\n | XscCons\n   :  forall v C\n   ,  Val v\n   -> exps_ctx Val C\n   -> exps_ctx Val (fun xx => v :: C xx).\n\nHint Constructors exps_ctx.\n\n\n(* Swapping related expresions in contexts *)\nLemma exps_ctx_Forall2_swap\n :  forall {exp: Type} {B:   Type}\n           (Val:  exp -> Prop)\n           (R:    exp -> B -> Prop)\n           (C:    exp -> list exp)\n           (x x': exp)\n           (ys:   list B)\n ,  exps_ctx Val C\n -> (forall y, R x y -> R x' y)\n -> Forall2 R (C x)  ys\n -> Forall2 R (C x') ys.\nProof.\n intros. gen ys.\n induction H; intros.\n  destruct ys.\n   inverts H1.\n   eapply Forall2_cons. eapply H0.\n    inverts H1. auto.\n    inverts H1. auto.\n\n  inverts H2.\n   eapply Forall2_cons.\n   auto. auto.\nQed.\n\n\n(* If all the elements in a list context have a property then\n   then they also have this property individually. *)\nLemma exps_ctx_Forall\n :  forall {exp: Type}\n           (Val: exp -> Prop)\n           (C:   exp -> list exp)\n           (P:   exp -> Prop)\n           (x:   exp)\n ,  exps_ctx Val C\n -> Forall P (C x)\n -> P x.\nProof.\n intros.\n induction H.\n  inverts H0. auto.\n  inverts H0. auto.\nQed.\n\n\nLemma exps_ctx_Forall2_exists_left\n :  forall {exp: Type} {B: Type}\n           (Val: exp -> Prop)\n           (C:   exp -> list exp)\n           (R:   exp -> B -> Prop)\n           (x:   exp)\n           (ys:  list B)\n ,  exps_ctx Val C\n -> Forall2 R (C x) ys\n -> (exists y, R x y).\nProof.\n intros. gen ys.\n induction H; intros.\n  destruct ys.\n   inverts H0.\n   inverts H0. eauto.\n  inverts H1.\n  eapply IHexps_ctx. eauto.\nQed.\n\n\n(* Used when evaluating all the expressions in a list.\n   If all the exps in a list are either wnf or have some property,\n   then they're either all wnf\n     or there is a context consisting of a run of wnf expressions\n        followed by one with the property.\n   For example:\n     C = w1 w2 w3 w4 x1 ?? ?? ?? ??\n   This is a context consisting of a run of four wnfs, followed\n   by an expression x1 with the desired property. The rest may or\n   may not be wnfs, but the'll all have the property.\n*)\nLemma exps_ctx_run\n :  forall {exp: Type} {B: Type}\n           (Val:  exp -> Prop)\n           (P:    exp -> Prop)\n           (xs:   list exp)\n ,  Forall (fun x => Val x \\/ P x) xs\n -> Forall Val xs\n \\/ (exists C x', exps_ctx Val C\n               /\\ xs = C x'\n               /\\ P x').\nProof.\n intros.\n induction xs.\n  left. auto.\n  inverts H.\n\n  inverts H2.\n   lets D: IHxs H3. clear IHxs.\n   inverts D.\n    left. auto.\n    right.\n     destruct H0 as [C].\n     destruct H0 as [x'].\n      inverts H0. inverts H2.\n      lets D2: (@XscCons exp Val) H H1.\n      exists (fun xx => a :: C xx).\n      exists x'. auto.\n\n    lets D: IHxs H3. clear IHxs.\n    inverts D.\n     right.\n     lets D2: (@XscHead exp Val) xs.\n     exists (fun xx => xx :: xs).\n     exists a. auto.\n\n    destruct H0 as [C].\n    destruct H0 as [x'].\n     inverts H0. inverts H2.\n     right.\n     exists (fun xx => xx :: C x').\n     exists a.\n     lets D2: (@XscHead exp Val) (C x').\n     auto.\nQed.\n\n\n\n(********************************************************************)\n(* Joint contexts of lists.\n   This is used when we evaluate a list of expressions left to right\n   where each expression needs to be a value before we move onto\n   the next one. *)\nInductive exps_ctx2\n      {exp: Type}        (* type of expressions *)\n      (Val: exp -> Prop) (* predicate to determine whether an exp is a value *)\n   :  (exp -> list exp)  (* fn for first  evaluation context *)\n   -> (exp -> list exp)  (* fn for second evaluation context *)\n   -> Prop :=\n | Xsc2Head\n   :  forall xs ys\n   ,  exps_ctx2 Val (fun xx => xx :: xs)  (fun yy => yy :: ys)\n\n | Xsc2Cons\n   :  forall v C1 C2\n   ,  Val v\n   -> exps_ctx2 Val C1 C2\n   -> exps_ctx2 Val (fun xx => v :: C1 xx) (fun yy => v :: C2 yy).\n\nHint Constructors exps_ctx2.\n\n\n(* Take the left of a joint context *)\nLemma exps_ctx2_left\n : forall exp Val C1 C2\n , @exps_ctx2 exp Val C1 C2 -> @exps_ctx exp Val C1.\nProof.\n intros.\n induction H; auto.\nQed.\n\n\n(* Take the right of a joint context *)\nLemma exps_ctx2_right\n : forall exp Val C1 C2\n , @exps_ctx2 exp Val C1 C2 -> @exps_ctx exp Val C2.\nProof.\n intros.\n induction H; auto.\nQed.\n\n\n(* Used when evaluating a list of expressions.\n   We take an expression from the first list, evaluate it, and\n   place the result in the second. For this to happen we need\n   to find an appropriate joint evaluation context.\n   If we can produce a wnf for every expression in the first list,\n   then either all exps are already wnf\n     or we can find a joint context consisting of a run of wnf\n        expressions, followed by an expression that we can evaluate.\n\n   For example:\n    C1 =  w1 w2 w3 x4 ?? ?? ??\n    C2 =  w1 w2 w3 w4 ?? ?? ??\n   Here we have such a joint context. The first three values in\n   each are idential and already wnf. We then have x4 and y4,\n   where x4 can be evaluated into y4. The rest may or may not\n   be wnfs, but the'll still be related.\n   v1 v2 v3 v4 XX x6 x7 x8 x9\n   v1 v2 v3 v4 XX v6 v7 v8 v\n*)\nLemma exps_ctx2_run\n :   forall {exp:   Type}\n            (Val:   exp -> Prop)\n            (R:     exp -> exp -> Prop)\n            (xs ys: list exp)\n ,   Forall2 (fun x y => R x y /\\ Val y /\\ (Val x -> y = x)) xs ys\n ->  Forall Val xs\n \\/ (exists C1 C2 x' y'\n         ,  R x' y'\n         /\\ exps_ctx2 Val C1 C2\n         /\\ xs = C1 x'\n         /\\ ys = C2 y').\nProof.\n intros exp Val R xs ys HR.\n induction HR.\n  Case \"nil\".\n   left. auto.\n\n  Case \"cons\".\n   rename l  into xs.\n   rename l' into ys.\n   inverts H. inverts H1.\n   inverts IHHR.\n   SCase \"xs whnf\".\n    right.\n    exists (fun xx => xx :: xs).\n    exists (fun xx => xx :: ys).\n    exists x.\n    exists y. auto.\n\n   SCase \"xs ctx\".\n    right.\n    destruct H1 as [C1].\n    destruct H1 as [C2].\n    destruct H1 as [x'].\n    destruct H1 as [y'].\n    inverts H1. inverts H4. inverts H5.\n\n    exists (fun xx => xx :: C1 x').\n    exists (fun yy => yy :: C2 y').\n    exists x. exists y.\n    repeat (split; auto).\nQed.\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/Data/Context.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.29223971019559064}}
{"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 seq ssrnat.\nRequire Import ssrZ ZArith_ext seq_ext uniq_tac machine_int multi_int.\nImport MachineInt.\nRequire Import mips_seplog mips_tactics mips_contrib mips_tactics mapstos.\nRequire Import multi_sub_u_u_prg.\nImport expr_m.\nImport assert_m.\n\nLocal Open Scope machine_int_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 multi_sub.\n\nVariables k a b t j u bor atmp btmp' : reg.\n\nLemma multi_sub_u_u_R_triple : uniq(k, a, b, t, j, u, bor, atmp, btmp', r0) ->\n  forall nk va vb, u2Z vb + 4 * Z_of_nat nk < \\B^1 ->\n  forall A B, size A = nk -> size B = nk ->\n  {{ fun s h => [a]_s = va /\\ [b]_s = vb /\\\n    u2Z [k]_s = Z_of_nat nk /\\ (var_e a |--> A ** var_e b |--> B) s h }}\n  multi_sub_u_u k a b b t j u bor atmp btmp'\n  {{ fun s h => exists B', size B' = nk /\\ [a]_s = va /\\\n    [b]_s = vb /\\ u2Z [k]_s = Z_of_nat nk /\\\n    (var_e a |--> A ** var_e b |--> B') s h /\\\n    u2Z [bor]_s <= 1 /\\\n    \\S_{ nk } B' = \\S_{ nk } A - \\S_{ nk } B + u2Z [bor]_s * \\B^nk }}.\nProof.\nmove=> Hset nk va vb Hnb A B Ha Hb; rewrite /multi_sub_u_u.\n\n(** addiu j zero zero16; *)\n\nNextAddiu.\nmove=> s h [Hra [Hrb [Hrk H]]].\nrewrite /wp_addiu; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\n\n(** addi t c zero16 *)\n\nNextAddiu.\nmove=> s h [[Hra [Hrb [Hrk H]]] Hj].\nrewrite /wp_addiu; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\n\n(** addi bor zero zero16; *)\n\nNextAddiu.\nmove=> s h [[[Hra [Hrb [Hrk H]]] Hj] Ht].\nrewrite /wp_addiu; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\n\n(** while (bne j k) ( *)\n\napply hoare_prop_m.hoare_while_invariant with (fun s h => exists B' nj nbor,\n  size B' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\ u2Z [k]_s = Z_of_nat nk /\\\n  (var_e a |--> A ** var_e b |--> B') s h /\\\n  u2Z [j]_s = Z_of_nat nj /\\ (nj <= nk)%nat /\\\n  u2Z [t]_s = u2Z vb + 4 * Z_of_nat nj /\\ u2Z [bor]_s = nbor /\\\n  nbor <= 1 /\\ \\S_{ nj } B' = \\S_{ nj } A - \\S_{ nj } B + nbor * \\B^nj /\\\n  drop nj B = drop nj B').\n\nmove=> s h [[[[Hra [Hrb [Hrk H]]] Hj] Ht Hbor]].\n\nexists B, O, 0; repeat (split => //).\nby rewrite Hj store.get_r0 add0i sext_Z2u // Z2uK.\nrewrite Ht sext_0 addi0 Hrb; ring.\nby rewrite Hbor sext_0 addi0 store.get_r0 Z2uK.\n\nmove=> s h [[B' [nj [nbor [HlenC [Hra [Hrb [Hrk [Hmem [Hrj [Hjk2 [Hrt [Hrbor [Hnbor [HInv Hnth]]]]]]]]]]]]] Hjk]];\n  rewrite /= in Hjk. move/negPn/eqP in Hjk.\nexists B'; repeat (split; trivial).\nby rewrite Hrbor.\nhave -> : nk = nj by rewrite Hrj Hrk in Hjk; exact: Z_of_nat_inj.\nby rewrite Hrbor -HInv.\n\n(** lwxs atmp j b; *)\n\napply hoare_lwxs_back_alt'' with (fun s h => exists B' nj nbor,\n  size B' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\ u2Z [k]_s = Z_of_nat nk /\\\n  (var_e a |--> A ** var_e b |--> B') s h /\\\n  u2Z [j]_s = Z_of_nat nj /\\ (nj < nk)%nat /\\\n  u2Z [t]_s = u2Z vb + 4 * Z_of_nat nj /\\ u2Z [bor]_s = nbor /\\ nbor <= 1 /\\\n  \\S_{ nj } B' = \\S_{ nj } A - \\S_{ nj } B + nbor * \\B^nj /\\ drop nj B = drop nj B' /\\\n  [atmp]_s = B `32_ nj).\n\nmove=> s h [[B' [nj [nbor [HlenC [Hra [Hrb [Hrk [Hmem [Hrj [Hjk2 [Hrt [Hrbor [Hnbor [HInv Hnth]]]]]]]]]]]]] Hjk]];\n  rewrite /= in Hjk. move/eqP in Hjk.\n\nhave {}Hjk : (nj < nk)%nat.\n  rewrite ltn_neqAle Hjk2 andbT; apply/eqP.\n  rewrite Hrj Hrk in Hjk.\n  contradict Hjk; by rewrite Hjk.\n\nexists (B' `32_ nj); split.\n- Decompose_32 B' nj B'1 B'2 HlenB1 HB'; last by rewrite HlenC.\n  rewrite HB' (decompose_equiv _ _ _ _ _ HlenB1) in Hmem.\n  rewrite assert_m.conCE !assert_m.conAE in Hmem.\n  rewrite assert_m.conCE !assert_m.conAE in Hmem.\n  move: Hmem; apply monotony => // h'.\n  apply mapsto_ext => //.\n  by rewrite /= shl_Z2u Hrj inj_mult mulZC.\n- rewrite /update_store_lwxs.\n  exists B', nj, nbor; repeat Reg_upd; repeat (split; trivial).\n  by Assert_upd.\n  rewrite (drop_nth zero32) in Hnth; last by rewrite Hb.\n  symmetry in Hnth.\n  rewrite (drop_nth zero32) in Hnth; last by rewrite HlenC.\n  by case: Hnth.\n\n(** addu btmp' atmp bor; *)\n\napply hoare_addu with (fun s h => exists B' nj nbor,\n  size B' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\ u2Z [k]_s = Z_of_nat nk /\\\n  (var_e a |--> A ** var_e b |--> B') s h /\\\n  u2Z [j]_s = Z_of_nat nj /\\ (nj < nk)%nat /\\\n  u2Z [t]_s = u2Z vb + 4 * Z_of_nat nj /\\ u2Z [bor]_s = nbor /\\\n  nbor <= 1 /\\ \\S_{ nj } B' = \\S_{ nj } A - \\S_{ nj } B + nbor * \\B^nj /\\\n  drop nj B = drop nj B' /\\\n  [atmp]_s = B `32_ nj /\\ [btmp']_s = B `32_ nj `+ [bor]_s).\n\nmove=> s h [B' [nj [nbor [HlenC [Hra [Hrb [Hrk [Hmem [Hrj [Hjk2 [Hrt [Hrbor [Hnbor [HInv [Hnth Hratmp]]]]]]]]]]]]]]].\nexists B', nj, nbor; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nby rewrite -Hratmp.\n\n(** sltu u btmp' atmp; *)\n\napply hoare_sltu with (fun s h => exists B' nj nbor,\n  size B' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\ u2Z [k]_s = Z_of_nat nk /\\\n  (var_e a |--> A ** var_e b |--> B') s h /\\\n  u2Z [j]_s = Z_of_nat nj /\\ (nj < nk)%nat /\\\n  u2Z [t]_s = u2Z vb + 4 * Z_of_nat nj /\\ u2Z [bor]_s = nbor /\\ nbor <= 1 /\\\n  \\S_{ nj } B' = \\S_{ nj } A - \\S_{ nj } B + nbor * \\B^nj /\\\n  drop nj B = drop nj B' /\\\n  [btmp']_s = B `32_ nj `+ [bor]_s /\\\n  [u]_s = if Zlt_bool (u2Z [btmp']_s) (u2Z (B `32_ nj)) then one32 else zero32).\n\nmove=> s h [B' [nj [nbor [HlenC [Hra [Hrb [Hrk [Hmem [Hrj [Hjk2 [Hrt [Hrbor [Hnbor [HInv [Hnth [Hratmp Hrbtmp']]]]]]]]]]]]]]]].\nexists B', nj, nbor; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nby rewrite -Hratmp.\n\n(** lwxs atmp j a; *)\n\napply hoare_lwxs_back_alt'' with (fun s h => exists B' nj nbor,\n  size B' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\ u2Z [k]_s = Z_of_nat nk /\\\n  (var_e a |--> A ** var_e b |--> B') s h /\\\n  u2Z [j]_s = Z_of_nat nj /\\ (nj < nk)%nat /\\\n  u2Z [t]_s = u2Z vb + 4 * Z_of_nat nj /\\ u2Z [bor]_s = nbor /\\ nbor <= 1 /\\\n  \\S_{ nj } B' = \\S_{ nj } A - \\S_{ nj } B + nbor * \\B^nj  /\\\n  drop nj B = drop nj B' /\\ [atmp]_s = A `32_ nj /\\\n  [btmp']_s = B `32_ nj `+ [bor]_s /\\\n  [u]_s = if Zlt_bool (u2Z [btmp']_s) (u2Z (B `32_ nj)) then one32 else zero32).\n\nmove=> s h [B' [nj [nbor [HlenC [Hra [Hrb [Hrk [Hmem [Hrj [Hjk2 [Hrt [Hrbor [Hnbor [HInv [Hnth [Hrbtmp' Hru]]]]]]]]]]]]]]]].\n\nexists (A `32_ nj); split.\n- Decompose_32 A nj A1 A2 HlenA1 HA'; last by rewrite Ha.\n  rewrite HA' (decompose_equiv _ _ _ _ _ HlenA1) !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 Hrj inj_mult mulZC.\n- rewrite /update_store_lwxs.\n  exists B', nj, nbor; repeat Reg_upd; repeat (split; trivial).\n  by Assert_upd.\n\n(** ifte_beq u, zero thendo *)\n\napply while.hoare_seq with (fun s h => exists B' nj nbor,\n  size B' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\ u2Z [k]_s = Z_of_nat nk /\\\n  (var_e a |--> A ** var_e b |--> B') s h /\\\n  u2Z [j]_s = Z_of_nat nj /\\ (nj < nk)%nat /\\\n  u2Z [t]_s = u2Z vb + 4 * Z_of_nat nj /\\\n  drop nj B = drop nj B' /\\ u2Z [bor]_s = nbor /\\ nbor <= 1 /\\\n  \\S_{ nj } B' + u2Z [atmp]_s * \\B^nj =\n  \\S_{ nj } A - \\S_{ nj } B + u2Z (A `32_ nj) * \\B^nj - u2Z (B `32_ nj) * \\B^nj + nbor * \\B^nj.+1).\n\napply while.hoare_ifte.\n\n(** addiu u r0 one16; *)\n\napply hoare_addiu with (fun s h => exists B' nj nbor,\n  size B' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\ u2Z [k]_s = Z_of_nat nk /\\\n  (var_e a |--> A ** var_e b |--> B') s h /\\\n  [u]_s = one32 /\\ u2Z [j]_s = Z_of_nat nj /\\ (nj < nk)%nat /\\\n  u2Z [t]_s = u2Z vb + 4 * Z_of_nat nj /\\ u2Z [bor]_s = nbor /\\\n  nbor <= 1 /\\ \\S_{ nj } B' = \\S_{ nj } A - \\S_{ nj } B + nbor * \\B^nj /\\\n  [atmp]_s = A `32_ nj /\\\n  drop nj B = drop nj B' /\\ [btmp']_s = B `32_ nj `+ [bor]_s /\\\n  u2Z [btmp']_s = u2Z (B `32_ nj) + nbor).\n\nmove=> s h [[B' [nj [nbor [HlenC [Hra [Hrb [Hrk [Hmem [Hrj [Hjk2 [Hrt [Hrbor [Hnbor [HInv [Hnth [Hratmp [Hrbtmp' Hru]]]]]]]]]]]]]]]]] Huzero]; rewrite /= in Huzero.\n\nexists B', nj, nbor; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nby rewrite add0i sext_Z2u.\nrewrite Hrbtmp' -Hrbor u2Z_add //.\nhave X : u2Z (B `32_ nj) <= u2Z [btmp']_s.\n  rewrite leZNgt => /ltZP X.\n  by rewrite Hru X /zero32 /one32 ?Z2uK in Huzero.\nrewrite Hrbtmp' in X; by move/u2Z_add_no_overflow in X.\n\n(** multu atmp one; *)\n\napply hoare_multu with (fun s h => exists B' nj nbor,\n  size B' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\ u2Z [k]_s = Z_of_nat nk /\\\n  (var_e a |--> A ** var_e b |--> B') s h /\\\n  [u]_s = one32 /\\ u2Z [j]_s = Z_of_nat nj /\\ (nj < nk)%nat /\\\n  u2Z [t]_s = u2Z vb + 4 * Z_of_nat nj /\\ u2Z [bor]_s = nbor /\\\n  nbor <= 1 /\\ \\S_{ nj } B' = \\S_{ nj } A - \\S_{ nj } B + nbor * \\B^nj /\\\n  [atmp]_s = A `32_ nj /\\\n  drop nj B = drop nj B' /\\ [btmp']_s = B `32_ nj `+ [bor]_s /\\\n  u2Z [btmp']_s = u2Z (B `32_ nj) + nbor /\\ store.utoZ s = u2Z (A `32_ nj)).\n\nmove=> s h [B' [nj [nbor [HlenC [Hra [Hrb [Hrk [Hmem [Hrone [Hrj [Hjk2 [Hrt [Hrbor [Hnbor [HSum [Hnth [Hratmp [Hrbtmp' Hru]]]]]]]]]]]]]]]]]].\n\nexists B', nj, nbor; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nby rewrite store.utoZ_multu Hrone umul_1 (@u2Z_zext 32) Hnth.\n\n(** msubu btmp' one; *)\n\napply hoare_msubu with (fun s h => exists B' nj nbor,\n  size B' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\ u2Z [k]_s = Z_of_nat nk /\\\n  (var_e a |--> A ** var_e b |--> B') s h /\\\n  [u]_s = one32 /\\ u2Z [j]_s = Z_of_nat nj /\\ (nj < nk)%nat /\\\n  u2Z [t]_s = u2Z vb + 4 * Z_of_nat nj /\\ u2Z [bor]_s = nbor /\\\n  nbor <= 1 /\\ \\S_{ nj } B' = \\S_{ nj } A - \\S_{ nj } B + nbor * \\B^nj /\\\n  [atmp]_s = A `32_ nj /\\\n  drop nj B = drop nj B' /\\ [btmp']_s = B `32_ nj `+ [bor]_s /\\\n  u2Z [btmp']_s = u2Z (B `32_ nj) + nbor /\\\n  ((u2Z [btmp']_s <= u2Z (A `32_ nj) -> store.utoZ s = u2Z (A `32_ nj) - u2Z [btmp']_s) /\\\n   (u2Z (A `32_ nj) < u2Z [btmp']_s -> store.utoZ s = \\B^2 + u2Z (A `32_ nj) - u2Z [btmp']_s))).\n\nmove=> s h [B' [nj [nbor [HlenC [Hra [Hrb [Hrk [Hmem [Hone [Hrj [Hjk [Hrt [Hrbor [Hnbor [Hinv [Hratmp [Hnth [Hrbtmp' [Hrbtmp'2 Hm]]]]]]]]]]]]]]]]]]].\nexists B'; exists nj; exists nbor.\nrewrite Hone umul_1.\nrepeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nmove=> H; rewrite store.msubu_utoZ Hm ?(@u2Z_zext 32) //.\napply (@ltZ_trans \\B^1) => //.\nexact: max_u2Z.\nexact: Z.le_ge.\nmove=> H; rewrite store.msubu_utoZ_overflow Hm ?(@u2Z_zext 32) //.\napply (@ltZ_trans \\B^1) => //; exact: max_u2Z.\n\n(** sltu bor atmp btmp'; *)\n\napply hoare_sltu with (fun s h => exists B' nj nbor,\n  size B' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\ u2Z [k]_s = Z_of_nat nk /\\\n  (var_e a |--> A ** var_e b |--> B') s h /\\\n  u2Z [j]_s = Z_of_nat nj /\\ (nj < nk)%nat /\\\n  u2Z [t]_s = u2Z vb + 4 * Z_of_nat nj /\\ nbor <= 1 /\\\n  \\S_{ nj } B' = \\S_{ nj } A - \\S_{ nj } B + nbor * \\B^nj /\\\n  [atmp]_s = A `32_ nj /\\\n  drop nj B = drop nj B' /\\\n  [btmp']_s = B `32_ nj `+ Z2u 32 nbor /\\\n  u2Z [btmp']_s = u2Z (B `32_ nj) + nbor /\\\n  (u2Z [btmp']_s <= u2Z (A `32_ nj) -> store.utoZ s = u2Z (A `32_ nj) - u2Z [btmp']_s) /\\\n  (u2Z (A `32_ nj) < u2Z [btmp']_s -> store.utoZ s = \\B^2 + u2Z (A `32_ nj) - u2Z [btmp']_s) /\\\n  [bor]_s = if u2Z (A `32_ nj) <? u2Z [btmp']_s then one32 else zero32).\n\nmove=> s h [B' [nj [nbor [HlenC [Hra [Hrb [Hrk [Hmem [Hone [Hrj [Hjk [Hrt [Hrbor [Hnbor [Hinv [Hratmp [Hnth [Hrbtmp' [Hrbtmp'2 [Hinv1 Hinv2]]]]]]]]]]]]]]]]]]]].\n\nexists B', nj, nbor; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nby rewrite -Hrbor Z2u_u2Z.\nby rewrite -Hratmp.\n\n(** mflhxu atmp *)\n\napply hoare_mflhxu'.\nmove=> s h [B' [nj [nbor [HlenC [Hra [Hrb [Hrk [Hmem [Hrj [Hjk [Hrt [Hnbor [Hinv [Hratmp [Hnth [Hrbtmp' [Hrbtmp'2 [Hm1 [Hm2 Hrbor]]]]]]]]]]]]]]]]]]].\n\ncase: (Z_lt_le_dec (u2Z (A `32_ nj)) (u2Z [btmp']_s)).\n- move/ltZP => X.\n  rewrite X in Hrbor.\n  move/ltZP in X.\n  exists B', nj, (u2Z one32).\n  repeat Reg_upd; repeat (split; trivial).\n  by Assert_upd.\n  by rewrite Hrbor.\n  by rewrite Z2uK.\n  move: {Hm1 Hm2}(Hm2 X) => Hm.\n  have Hacx0 : store.acx s = Z2u store.acx_size 0.\n    apply store.utoZ_acx_beta2.\n    rewrite Hm; lia.\n  rewrite store.utoZ_def Hacx0{Hacx0} Z2uK // mul0Z addZ0 in Hm.\n  rewrite (_ : \\B^2 = \\B^1 * (\\B^1 - 1) + \\B^1) // addZC (mulZC (\\B^1)) in Hm.\n  rewrite (_ : forall a b c d, a + b + c - d = a + (b + c - d)) in Hm; last by move=> *; ring.\n  apply poly_eq_inv in Hm; last first.\n    rewrite Zbeta1E.\n    split; first exact: min_u2Z.\n    split.\n    by split; [apply min_u2Z | apply max_u2Z].\n    split; first by [].\n    move: (min_u2Z (A `32_ nj)) (max_u2Z [btmp']_s) => ? ?; lia.\n  case: Hm => _ Hm.\n  rewrite Hinv Hm (Zbeta_S nj) Hrbtmp'2 Z2uK //; ring.\n- move/leZNgt/ltZP/negbTE => X.\n  rewrite X in Hrbor.\n  move/ltZP/leZNgt in X.\n  exists B', nj, (u2Z zero32).\n  repeat Reg_upd; repeat (split; trivial).\n  by Assert_upd.\n  by rewrite Hrbor.\n  by rewrite Z2uK.\n  move: {Hm1 Hm2}(Hm1 X) => Hm.\n  have H0 : store.utoZ s < \\B^1.\n    move: (max_u2Z (A `32_ nj)) (min_u2Z [btmp']_s).\n    rewrite Hm -Zbeta1E => ? ?; lia.\n  case/store.utoZ_lo_beta1 : H0 => _ [_ <-].\n  rewrite Hinv Hm Hrbtmp'2 Z2uK //; ring.\n\n(** nop); *)\n\napply hoare_nop'.\n\n(** we are in the branch where btmp' = atmp + bor has overflowed *)\n\nmove=> s h [[B' [nj [nbor [HlenC [Hra [Hrb [Hrk [Hmem [Hrj [Hjk [Hrt [Hrbor [Hnbor [Hinv [Hnth [Hratmp [Hrbtmp' Hru]]]]]]]]]]]]]]]] Huzero]];\n  rewrite /= in Huzero. move/negbTE/eqP in Huzero.\nexists B', nj, nbor.\nrepeat Reg_upd.\nrepeat (split; trivial).\nhave [X1 X2] : nbor = 1 /\\ u2Z (B `32_ nj) = \\B^1 - 1.\n  have H : u2Z [btmp']_s < u2Z (B `32_ nj).\n    apply/ltZP.\n    apply: Bool.not_false_is_true => X.\n    by rewrite Hru X in Huzero.\n  rewrite Hrbtmp' in H.\n  apply u2Z_add_overflow' in H; rewrite -Zbeta1E in H.\n  move: (max_u2Z (B `32_ nj)) => H'; rewrite -Zbeta1E in H'; lia.\nrewrite Hratmp Hinv X1 X2 !mul1Z (Zbeta_S nj); ring.\n\n(** sw ctmp zero16 t; *)\n\napply hoare_sw_back'' with (fun s h => exists B' nj nbor,\n  size B' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\ u2Z [k]_s = Z_of_nat nk /\\\n  (var_e a |--> A ** var_e b |--> B') s h /\\\n  u2Z [j]_s = Z_of_nat nj /\\ (nj < nk)%nat /\\\n  u2Z [t]_s = u2Z vb + 4 * Z_of_nat nj /\\ u2Z [bor]_s = nbor /\\\n  nbor <= 1 /\\ \\S_{nj.+1} B' = \\S_{nj.+1} A - \\S_{nj.+1} B + nbor * \\B^nj.+1 /\\\n  drop nj.+1 B = drop nj.+1 B').\n\nmove=> s h [B' [nj [nbor [HlenB' [Hra [Hrb [Hrk [Hmem [Hrj [Hjk [Hrt [Hnth [Hrbor [Hnbor Hinv]]]]]]]]]]]]]].\n\nhave Htmp : [ var_e t \\+ int_e (sext 16 zero16) ]e_s = [ var_e b \\+ int_e (Z2u 32 (Z_of_nat (4 * nj))) ]e_ s.\n  rewrite /= sext_Z2u // addi0.\n  apply u2Z_inj.\n  rewrite u2Z_add_Z_of_nat.\n  rewrite inj_mult Hrt Hrb; ring.\n  rewrite inj_mult -Zbeta1E Hrb; simpl Z_of_nat; move/ltP in Hjk; lia.\n\nexists (int_e (B' `32_ nj)).\n\nDecompose_32 B' nj B'1 B'2 HlenB'1 HB'; last by rewrite HlenB'.\n\nrewrite HB' (decompose_equiv _ _ _ _ _ HlenB'1) in Hmem.\nrewrite assert_m.conCE !assert_m.conAE in Hmem.\nrewrite assert_m.conCE !assert_m.conAE in Hmem.\nmove: Hmem; apply monotony => // ht.\nexact: mapsto_ext.\napply currying => h' H'; simpl app in H'.\nexists (upd_nth B' nj [atmp]_s); exists nj, nbor.\nrepeat (split; trivial).\nexact: size_upd_nth.\nrewrite HB' upd_nth_cat HlenB'1 // subnn /= (decompose_equiv _ _ _ _ _ HlenB'1).\nrewrite cat0s in H'.\nassoc_comm H'.\nexact: mapsto_ext H'.\n\nrewrite HB' -cat1s catA upd_nth_cat'; last first.\n  rewrite size_cat/= HlenB'1 addnC /=; exact/ltP/lt_n_Sn.\nrewrite upd_nth_cat; last first.\n  by rewrite HlenB'1.\nrewrite HlenB'1 subnn; simpl upd_nth; simpl app; rewrite -lSum_beyond; last first.\n  by rewrite size_cat /= HlenB'1 addnC.\nrewrite (lSum_cut_last _ B'1) //; last first.\n  by rewrite size_cat /= HlenB'1 addnC.\nrewrite subn1 [_.+1.-1]/=.\n\nrewrite HB' -lSum_beyond // in Hinv.\nrewrite -/(\\B^nj) mulZC Hinv.\n\nDecompose_32 A nj A1 A2 HlenA1 HA'; last by rewrite Ha.\n\nrewrite {3}HA' -cat1s catA -lSum_beyond; last first.\n  by rewrite size_cat /= HlenA1 addnC.\nrewrite (lSum_cut_last _ A1) //; last by rewrite size_cat/= HlenA1 addnC.\nrewrite -/(_ `32_ nj) subn1 [_.+1.-1]/=.\n\nDecompose_32 B nj B1 B2 HlenB1 HB_; last by rewrite Hb.\nrewrite {3}HB_ -(cat1s (B `32_ nj)) catA -lSum_beyond //; last first.\n  by rewrite size_cat /= HlenB1 addnC.\nrewrite (lSum_cut_last _ B1) //; last by rewrite size_cat /= HlenB1 addnC.\nrewrite -/(_ `32_ nj) subn1 [_.+1.-1]/= HA' -lSum_beyond //.\nrewrite ( _ : (A1 ++ (A `32_ nj :: A2)) `32_ nj = A `32_ nj); last first.\n  by rewrite /nth' nth_cat HlenA1 ltnn subnn /=.\nrewrite  HB_ -lSum_beyond //.\nrewrite ( _ : (B1 ++ (B `32_ nj :: B2)) `32_ nj = B `32_ nj); last first.\n  by rewrite /nth' nth_cat HlenB1 ltnn subnn /=.\nrewrite -ZbetaE /=; ring.\n\nrewrite drop_upd_nth //.\nrewrite (drop_nth zero32) in Hnth; last by rewrite Hb.\nsymmetry in Hnth.\nrewrite (drop_nth zero32) in Hnth; last by rewrite HlenB'.\nby case: Hnth.\n\n(** addiu t t four16; *)\n\napply hoare_addiu with (fun s h => exists B' nj nbor,\n length B' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\\n u2Z [k]_s = Z_of_nat nk /\\ (var_e a |--> A ** var_e b |--> B') s h /\\\n u2Z [j]_s = Z_of_nat nj /\\ (nj < nk)%nat /\\\n u2Z [t]_s = u2Z vb + 4 * (Z_of_nat nj + 1) /\\ u2Z [bor]_s = nbor /\\ nbor <= 1 /\\\n \\S_{nj.+1} B' = \\S_{nj.+1} A - \\S_{nj.+1} B + nbor * \\B^nj.+1 /\\ drop nj.+1 B = drop nj.+1 B').\n\nmove=> s h [B' [nj [nbor [HlenC [Hra [Hrb [Hrk [Hmem [Hrj [Hjk [Hrt [Hbor [Hnbor [Hinv Hnth]]]]]]]]]]]]]].\n\nmove/ltP in Hjk.\nexists B', nj, nbor; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nexact/ltP.\nrewrite u2Z_add sext_Z2u // Z2uK //.\n- lia.\n- rewrite -Zbeta1E; lia.\n\n(** addiu j j one16 *)\n\napply hoare_addiu'.\nmove=> s h [B' [nj [nbor [HlenC [Hra [Hrb [Hrk [Hmem [Hrj [Hjk [Hrt [Hbor [Hnbor [Hinv Hnth]]]]]]]]]]]]]].\n\nexists B', nj.+1, nbor.\nrewrite Z_S.\nrepeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\n\nrewrite sext_Z2u // u2Z_add_Z2u //.\nby rewrite Hrj.\nmove/ltP in Hjk.\nmove: (min_u2Z vb) => ?; rewrite -Zbeta1E; lia.\nQed.\n\nLemma multi_sub_u_u_R_triple_B_le_A : uniq(k, a, b, t, j, u, bor, atmp, btmp', r0) ->\n  forall nk va vb, u2Z vb + 4 * Z_of_nat nk < \\B^1 ->\n  forall A B, size A = nk -> size B = nk -> \\S_{ nk } B <= \\S_{ nk } A ->\n  {{ fun s h =>\n    [a]_s = va /\\ [b]_s = vb /\\\n    u2Z [k]_s = Z_of_nat nk /\\ (var_e a |--> A ** var_e b |--> B) s h }}\n  multi_sub_u_u k a b b t j u bor atmp btmp'\n  {{ fun s h => exists B', size B' = nk /\\ [a]_s = va /\\\n    [b]_s = vb /\\ u2Z [k]_s = Z_of_nat nk /\\ [bor]_s = zero32 /\\\n    (var_e a |--> A ** var_e b |--> B') s h /\\\n    \\S_{ nk } B' = \\S_{ nk } A - \\S_{ nk } B }}.\nProof.\nmove=> Hset nk va vb Hna A B Ha Hb HAB.\neapply hoare_prop_m.hoare_weak; last by eapply multi_sub_u_u_R_triple; eauto.\nmove=> s h [A' [HlenA [Hra [Hrb [Hrk [Hmem [Hbor Hsum]]]]]]].\nhave X : u2Z [bor]_s = 0.\n  have {}Hsum : u2Z [bor ]_ s * \\B^nk + (\\S_{ nk } A - \\S_{ nk } B - \\S_{ nk } A') = 0 * \\B^nk + 0.\n    rewrite Hsum; ring.\n  apply poly_eq0_inv in Hsum.\n  tauto.\n  exact: expZ_ge0.\n  move: (min_lSum nk B) (min_lSum nk A') (max_lSum nk A) (max_lSum nk A') => ????.\n  rewrite ZbetaE; lia.\nexists A'; repeat (split => //).\nrewrite (_ : 0 = u2Z zero32) in X; last by rewrite Z2uK.\nby move/u2Z_inj : X.\nrewrite Hsum X mul0Z addZ0; reflexivity.\nQed.\n\nEnd multi_sub.\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_sub_u_u_R_triple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2921469166662771}}
{"text": "Require Import List.\nImport ListNotations.\nRequire Import Arith.\n\nRequire Import VerdiTactics.\nRequire Import Util.\nRequire Import Net.\nRequire Import Raft.\nRequire Import RaftRefinement.\n\nRequire Import CommonTheorems.\n\n\nRequire Import UpdateLemmas.\nLocal Arguments update {_} {_} {_} _ _ _ _ : simpl never.\n\nSection CroniesTerm.\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 cronies_term (net : network) :=\n    forall h h' t,\n      In h (cronies (fst (nwState net h')) t) ->\n      t <= currentTerm (snd (nwState net h')).\n\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 id c out st' l,\n      handleClientRequest h st id c = (out, st', l) ->\n      currentTerm st' = currentTerm st.\n  Proof.\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.\n    unfold refined_raft_net_invariant_client_request, cronies_term.\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    find_rewrite. 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.\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.\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.\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.\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.\n    intros. unfold doGenericServer in *.\n    repeat break_match; repeat find_inversion; auto.\n  Qed.\n  \n  Lemma cronies_term_do_generic_server :\n    refined_raft_net_invariant_do_generic_server cronies_term.\n  Proof.\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.\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.\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.\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.\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.\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.\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.\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.\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.\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.\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.\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.\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.\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.\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    \nEnd CroniesTerm.\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/CroniesTerm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.29214691666627707}}
{"text": "Declare ML Module \"coq-paramcoq.plugin\".\n\nLtac destruct_reflexivity := \n  intros ; repeat match goal with \n    | [ x : _ |- _ = _ ] => destruct x; reflexivity; fail\n  end.\n\nLtac destruct_construct x := \n    (destruct x; [ constructor 1 ]; auto; fail)\n || (destruct x; [ constructor 1 | constructor 2 ]; auto; fail)\n || (destruct x; [ constructor 1 | constructor 2 | constructor 3]; auto; fail).\n\nLtac unfold_cofix := intros; match goal with \n [ |- _ = ?folded ] =>  \n    let x := fresh \"x\" in \n    let typ := type of folded in \n    (match folded with _ _ => pattern folded | _ => pattern folded at 2 end);\n    match goal with [ |- ?P ?x ] => \n    refine (let rebuild : typ -> typ := _ in \n            let path : rebuild folded = folded := _ in  \n            eq_rect _ P _ folded path) end; \n    [ intro x ; destruct_construct x; fail \n    | destruct folded; reflexivity\n    | reflexivity]; fail\nend.\n\nLtac destruct_with_nat_arg_pattern x :=\n  pattern x;\n  match type of x with \n   | ?I 0 => refine (let gen : forall m (q : I m), \n     (match m return I m -> Type with \n         0 => fun p => _ p\n     | S n => fun _  => unit end q) := _ in gen 0 x)     \n   | ?I (S ?n) => refine (let gen : forall m (q : I m), \n     (match m return I m -> Type with \n         0 => fun _  => unit \n     | S n => fun p => _ p end q) := _ in gen (S n) x)\n  end; intros m q; destruct q.\n\nLtac destruct_reflexivity_with_nat_arg_pattern := \n  intros ; repeat match goal with \n    | [ x : _ |- _ = _ ] => destruct_with_nat_arg_pattern x; reflexivity; fail\n  end.\n \nAxiom absurd : forall X, X.\n\nLtac admit_and_print := \n  intros; match goal with \n  | [ |- _ = ?RHS ] => idtac \"Warning: admiting an ogligation for\" RHS\n  | [ |- ?GOAL] => idtac \"Warning: admiting an ogligation of goal\" GOAL\n  end; apply absurd.\n\nGlobal Parametricity Tactic := ((destruct_reflexivity; fail)\n                            || (unfold_cofix; fail) \n                            || (destruct_reflexivity_with_nat_arg_pattern; fail)\n                            || admit_and_print). \n\nRequire ProofIrrelevance. (* for opaque terms *)\n", "meta": {"author": "coq-community", "repo": "paramcoq", "sha": "5167648ad044928cb6e0c3a986717490cbf74665", "save_path": "github-repos/coq/coq-community-paramcoq", "path": "github-repos/coq/coq-community-paramcoq/paramcoq-5167648ad044928cb6e0c3a986717490cbf74665/test-suite/stdlib_R/Parametricity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.29214426401641486}}
{"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.\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.\n- For arithmetic operations, immediates are\n  8-bit quantities zero-extended and rotated right by 0, 2, 4, ... 30 bits.\n- For memory accesses of type [Mint32], immediate offsets are\n  12-bit quantities plus a sign bit.\n- For other memory accesses, immediate offsets are\n  8-bit quantities plus a sign bit. *)\n\nFixpoint is_immed_arith_aux (n: nat) (x msk: int) {struct n}: bool :=\n  match n with\n  | Datatypes.O => false\n  | Datatypes.S n' =>\n      Int.eq (Int.and x (Int.not msk)) Int.zero ||\n      is_immed_arith_aux n' x (Int.ror msk (Int.repr 2))\n  end.\n\nDefinition is_immed_arith (x: int) : bool :=\n  is_immed_arith_aux 16%nat x (Int.repr 255).\n\nDefinition is_immed_mem_word (x: int) : bool :=\n  Int.lt x (Int.repr 4096) && Int.lt (Int.repr (-4096)) x.\n\nDefinition mk_immed_mem_word (x: int) : int :=\n  Int.sign_ext 13 x.\n\nDefinition is_immed_mem_small (x: int) : bool :=\n  Int.lt x (Int.repr 256) && Int.lt (Int.repr (-256)) x.\n\nDefinition mk_immed_mem_small (x: int) : int :=\n  Int.sign_ext 9 x.\n\nDefinition is_immed_mem_float (x: int) : bool :=\n  Int.eq (Int.and x (Int.repr 3)) Int.zero\n  && Int.lt x (Int.repr 1024) && Int.lt (Int.repr (-1024)) x.\n\nDefinition mk_immed_mem_float (x: int) : int :=\n  Int.and (Int.sign_ext 11 x) (Int.repr 4294967288).  (**r 0xfffffff8 *)\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_rec (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_rec 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_rec M (Int.and n (Int.not m)) (Int.add p (Int.repr 2))\n  end.\n\nDefinition decompose_int (n: int) : list int :=\n  match decompose_int_rec 12%nat n Int.zero 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 (r: ireg) (n: int) (k: code) :=\n  let d1 := decompose_int n in\n  let d2 := decompose_int (Int.not n) in\n  if NPeano.leb (List.length d1) (List.length d2)\n  then iterate_op (Pmov r) (Porr r r) d1 k\n  else iterate_op (Pmvn r) (Pbic r r) d2 k.\n\nDefinition addimm (r1 r2: ireg) (n: int) (k: code) :=\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 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 rsubimm (r1 r2: ireg) (n: int) (k: code) :=\n  iterate_op (Prsb r1 r2) (Padd r1 r1) (decompose_int 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 => SOlslimm r (s_amount n)\n  | Slsr n => SOlsrimm r (s_amount n)\n  | Sasr n => SOasrimm r (s_amount n)\n  | Sror n => SOrorimm 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  | _, _ =>\n      Error(msg \"Asmgen.transl_cond\")\n  end.\n\nDefinition crbit_for_signed_cmp (cmp: comparison) :=\n  match cmp with\n  | Ceq => CReq\n  | Cne => CRne\n  | Clt => CRlt\n  | Cle => CRle\n  | Cgt => CRgt\n  | Cge => CRge\n  end.\n\nDefinition crbit_for_unsigned_cmp (cmp: comparison) :=\n  match cmp with\n  | Ceq => CReq\n  | Cne => CRne\n  | Clt => CRlo\n  | Cle => CRls\n  | Cgt => CRhi\n  | Cge => CRhs\n  end.\n\nDefinition crbit_for_float_cmp (cmp: comparison) :=\n  match cmp with\n  | Ceq => CReq\n  | Cne => CRne\n  | Clt => CRmi\n  | Cle => CRls\n  | Cgt => CRgt\n  | Cge => CRge\n  end.\n\nDefinition crbit_for_float_not_cmp (cmp: comparison) :=\n  match cmp with\n  | Ceq => CRne\n  | Cne => CReq\n  | Clt => CRpl\n  | Cle => CRhi\n  | Cgt => CRle\n  | Cge => CRlt\n  end.\n\nDefinition crbit_for_cond (cond: condition) :=\n  match cond with\n  | Ccomp cmp => crbit_for_signed_cmp cmp\n  | Ccompu cmp => crbit_for_unsigned_cmp cmp\n  | Ccompshift cmp s => crbit_for_signed_cmp cmp\n  | Ccompushift cmp s => crbit_for_unsigned_cmp cmp\n  | Ccompimm cmp n => crbit_for_signed_cmp cmp\n  | Ccompuimm cmp n => crbit_for_unsigned_cmp cmp\n  | Ccompf cmp => crbit_for_float_cmp cmp\n  | Cnotcompf cmp => crbit_for_float_not_cmp cmp\n  | Ccompfzero cmp => crbit_for_float_cmp cmp\n  | Cnotcompfzero cmp => crbit_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  | 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  | 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 (if negb (ireg_eq r r1) then Pmul r r1 r2 :: k\n          else if negb (ireg_eq r r2) then Pmul r r2 r1 :: k\n          else Pmul IR14 r1 r2 :: Pmov r (SOreg IR14) :: 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 (if negb (ireg_eq r r1) then Pmla r r1 r2 r3 :: k\n          else if negb (ireg_eq r r2) then Pmla r r2 r1 r3 :: k\n          else Pmla IR14 r1 r2 r3 :: Pmov r (SOreg IR14) :: k)\n  | Odiv, a1 :: a2 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n      OK (Psdiv r r1 r2 :: k)\n  | Odivu, a1 :: a2 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n      OK (Pudiv r r1 r2 :: 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 (Pmov r (SOlslreg 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 (Pmov r (SOasrreg 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 (Pmov r (SOlsrreg 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      OK (Pcmp r1 (SOimm Int.zero) ::\n          addimm IR14 r1 (Int.sub (Int.shl Int.one n) Int.one)\n             (Pmovc CRge IR14 (SOreg r1) ::\n              Pmov r (SOasrimm 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  | Osingleoffloat, a1 :: nil =>\n      do r <- freg_of res; do r1 <- freg_of a1;\n      OK (Pfcvtsd 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  | Ocmp cmp, _ =>\n      do r <- ireg_of res;\n      transl_cond cmp args\n        (Pmov r (SOimm Int.zero) ::\n         Pmovc (crbit_for_cond cmp) r (SOimm Int.one) ::\n         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 (SAimm n)) mk_immed_mem_word base ofs k.\n\nDefinition loadind (base: ireg) (ofs: int) (ty: typ) (dst: mreg) (k: code) :=\n  match ty with\n  | Tint =>\n      do r <- ireg_of dst; OK (loadind_int base ofs r k)\n  | Tfloat =>\n      do r <- freg_of dst;\n      OK (indexed_memory_access (Pfldd r) mk_immed_mem_float base ofs k)\n  | Tsingle =>\n      do r <- freg_of dst;\n      OK (indexed_memory_access (Pflds r) mk_immed_mem_float base ofs k)\n  | Tlong =>\n      Error (msg \"Asmgen.loadind\")\n  end.\n\nDefinition storeind (src: mreg) (base: ireg) (ofs: int) (ty: typ) (k: code) :=\n  match ty with\n  | Tint =>\n      do r <- ireg_of src;\n      OK (indexed_memory_access (fun base n => Pstr r base (SAimm n)) mk_immed_mem_word base ofs k)\n  | Tfloat =>\n      do r <- freg_of src;\n      OK (indexed_memory_access (Pfstd r) mk_immed_mem_float base ofs k)\n  | Tsingle =>\n      do r <- freg_of src;\n      OK (indexed_memory_access (Pfsts r) mk_immed_mem_float base ofs k)\n  | Tlong =>\n      Error (msg \"Asmgen.storeind\")\n  end.\n\n(** Translation of memory accesses *)\n\nDefinition transl_shift_addr (s: shift) (r: ireg) : shift_addr :=\n  match s with\n  | Slsl n => SAlsl r (s_amount n)\n  | Slsr n => SAlsr r (s_amount n)\n  | Sasr n => SAasr r (s_amount n)\n  | Sror n => SAror r (s_amount n)\n  end.\n\nDefinition transl_memory_access\n     (mk_instr_imm: ireg -> int -> instruction)\n     (mk_instr_gen: option (ireg -> shift_addr -> 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 (SAreg 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_addr 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_addr -> 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 (SAimm 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 | Mfloat64al32 =>\n      transl_memory_access_float Pfldd mk_immed_mem_float dst addr args k\n  | Mint64 =>\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 | Mfloat64al32 =>\n      transl_memory_access_float Pfstd mk_immed_mem_float src addr args k\n  | Mint64 =>\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 (crbit_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 (SAimm 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", "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/arm/Asmgen.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.29214426401641486}}
{"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\n\nAdd LoadPath \".\" as SMTCoq.\nRequire Import Bool List Int31 PArray.\nRequire Import Misc State.\n\nLocal Open Scope array_scope.\nLocal Open Scope int31_scope.\n\nHint Unfold is_true.\n\n\n(* Remark: I use Notation instead of Definition du eliminate conversion check during the type checking *)\nNotation atom := int (only parsing).\n\nModule Form.\n\n  Notation fargs := (array _lit) (only parsing).\n\n  Inductive form : Type :=\n  | Fatom (_:atom)\n  | Ftrue\n  | Ffalse\n  | Fnot2 (_:int) (_:_lit)\n  | Fand (_:fargs)\n  | For  (_:fargs)\n  | Fimp (_:fargs)\n  | Fxor (_:_lit) (_:_lit)\n  | Fiff (_:_lit) (_:_lit)\n  | Fite (_:_lit) (_:_lit) (_:_lit).\n\n  Definition is_Ftrue h :=\n    match h with Ftrue => true | _ => false end.\n\n  Definition is_Ffalse h :=\n    match h with Ffalse => true | _ => false end.\n\n  Lemma is_Ftrue_correct : forall h, is_Ftrue h -> h = Ftrue.\n  Proof. destruct h;trivial;discriminate. Qed.\n\n  Lemma is_Ffalse_correct : forall h, is_Ffalse h -> h = Ffalse.\n  Proof. destruct h;trivial;discriminate. Qed.\n\n  Section Interp.\n    Variable interp_atom : atom -> bool.\n\n    Section Interp_form.\n\n    (* On suppose qu'on a l'interprétation des litéraux *)\n      Variable interp_var : var -> bool.\n\n      (* Interprétation d'une formule en supposant l'interprétation\n         des litéraux *)\n      (* (les litéraux font office d'index de hachage) *)\n      Definition interp_aux (h:form) : bool :=\n        match h with\n        | Fatom a => interp_atom a\n        | Ftrue => true\n        | Ffalse => false\n        | Fnot2 i l => fold (fun b => negb (negb b)) 1 i (Lit.interp interp_var l)\n        | Fand args => afold_left _ _ true andb (Lit.interp interp_var) args\n        | For args => afold_left _ _ false orb (Lit.interp interp_var) args\n        | Fimp args => afold_right _ _ false implb (Lit.interp interp_var) args\n        | Fxor a b => xorb (Lit.interp interp_var a) (Lit.interp interp_var b)\n        | Fiff a b => Bool.eqb (Lit.interp interp_var a) (Lit.interp interp_var b)\n        | Fite a b c =>\n          if Lit.interp interp_var a then Lit.interp interp_var b\n          else Lit.interp interp_var c\n        end.\n\n    End Interp_form.\n\n    Section Interp_get.\n\n      Variable t_form : PArray.array form.\n\n      Definition t_interp : PArray.array bool :=\n        PArray.foldi_left (fun i t_b hf => \n            t_b.[i <- interp_aux (PArray.get t_b) hf])\n        (PArray.make (PArray.length t_form) true) t_form.\n\n      Fixpoint lt_form i h:=\n        match h with\n        | Fatom _ | Ftrue | Ffalse => true\n        | Fnot2 _ l => Lit.blit l < i\n        | Fand args | For args | Fimp args =>\n          PArray.forallb (fun l => Lit.blit l < i) args\n        | Fxor a b | Fiff a b => (Lit.blit a < i) && (Lit.blit b < i) \n        | Fite a b c => (Lit.blit a < i) && (Lit.blit b < i) && (Lit.blit c < i)\n        end.\n\n      Lemma lt_form_interp_form_aux :\n        forall f1 f2 i h,\n          (forall j, j < i -> f1 j = f2 j) ->\n          lt_form i h ->\n          interp_aux f1 h = interp_aux f2 h.\n      Proof.\n        destruct h;simpl;intros;trivial;\n          try (apply afold_left_eq;unfold is_true in H0;\n            rewrite PArray.forallb_spec in H0;intros;\n              auto using Lit.interp_eq_compat).\n        f_equal;auto using Lit.interp_eq_compat.\n        apply afold_right_eq;unfold is_true in H0;\n          rewrite PArray.forallb_spec in H0;intros;\n            auto using Lit.interp_eq_compat.\n        unfold is_true in H0;rewrite !andb_true_iff in H0;decompose [and] H0;\n          rewrite !(Lit.interp_eq_compat f1 f2);auto.\n        unfold is_true in H0;rewrite !andb_true_iff in H0;decompose [and] H0;\n          rewrite !(Lit.interp_eq_compat f1 f2);auto.\n        unfold is_true in H0;rewrite !andb_true_iff in H0;decompose [and] H0;\n          rewrite !(Lit.interp_eq_compat f1 f2);auto.\n      Qed.\n\n      Definition wf := PArray.forallbi lt_form t_form.\n\n      Hypothesis wf_t_i : wf.\n\n      Lemma length_t_interp : length t_interp = length t_form.\n      Proof.\n        unfold t_interp;apply PArray.foldi_left_Ind with (P := fun i a => length a = length t_form).\n        intros;rewrite length_set;trivial.\n        rewrite length_make, ltb_length;trivial.\n      Qed.\n\n      Lemma default_t_interp : default t_interp = true.\n      Proof.\n        unfold t_interp;apply PArray.foldi_left_Ind with\n          (P := fun i a => default a = true).\n        intros;rewrite default_set;trivial.\n        apply default_make.\n      Qed.\n\n      Lemma t_interp_wf : forall i, i < PArray.length t_form ->\n        t_interp.[i] = interp_aux (PArray.get t_interp) (t_form.[i]).\n      Proof.\n        set (P' i t := length t = length t_form ->\n          forall j, j < i ->\n            t.[j] = interp_aux (PArray.get t) (t_form.[j])).\n        assert (P' (length t_form) t_interp).\n        unfold is_true, wf in wf_t_i;rewrite PArray.forallbi_spec in wf_t_i.\n        unfold t_interp;apply foldi_left_Ind;unfold P';intros.\n        rewrite length_set in H1.\n        destruct (Int31Properties.reflect_eqb j i).\n        rewrite e, PArray.get_set_same.\n        apply lt_form_interp_form_aux with (2:= wf_t_i i H).\n        intros;rewrite get_set_other;trivial.\n        intros Heq;elim (not_ltb_refl i);rewrite Heq at 1;trivial.\n        rewrite H1;trivial.\n        assert (j < i).\n        assert ([|j|] <> [|i|]) by (intros Heq1;elim n;apply to_Z_inj;trivial).\n        generalize H2;unfold is_true;rewrite !ltb_spec, (to_Z_add_1 _ _ H);\n          auto with zarith.\n        rewrite get_set_other, H0;auto.\n        apply lt_form_interp_form_aux with\n          (2:= wf_t_i j (ltb_trans _ _ _ H3 H)).\n        intros;rewrite get_set_other;trivial.\n        intros Heq;elim (not_ltb_refl i);apply ltb_trans with j;\n          [ rewrite Heq| ];trivial.\n        elim (ltb_0 _ H0).\n        apply H;apply length_t_interp.\n      Qed.\n\n    End Interp_get.\n\n    Definition interp_state_var t_form :=\n      let t_interp := t_interp t_form in\n      PArray.get t_interp.\n\n    Register interp_aux as PrimInline.\n    Definition interp t_form := interp_aux (interp_state_var t_form).\n\n    Lemma wf_interp_form_lt :\n      forall t_form, wf t_form ->\n        forall x, x < PArray.length t_form ->\n          interp_state_var t_form x = interp t_form (t_form.[x]).\n    Proof.\n      unfold interp_state_var;intros.\n      apply t_interp_wf;trivial.\n    Qed.\n\n    Lemma wf_interp_form :\n      forall t_form, PArray.default t_form = Ftrue -> wf t_form ->\n        forall x, interp_state_var t_form x = interp t_form (t_form.[x]).\n    Proof.\n      intros t Hd Hwf x;case_eq (x < PArray.length t);intros.\n      apply wf_interp_form_lt;trivial.\n      unfold interp_state_var;rewrite !PArray.get_outofbound;trivial.\n      rewrite default_t_interp, Hd;trivial.\n      rewrite length_t_interp;trivial.\n    Qed.\n\n    Definition check_form t_form :=\n      is_Ftrue (PArray.default t_form) &&\n      is_Ftrue (t_form.[0]) &&\n      is_Ffalse (t_form.[1]) &&\n      wf t_form.\n\n    Lemma check_form_correct : forall t_form,\n       check_form t_form ->\n       ((PArray.default t_form = Ftrue /\\ wf t_form) /\\\n        Valuation.wf (interp_state_var t_form)).\n    Proof.\n     unfold is_true, check_form;intros t;rewrite !andb_true_iff.\n     intros H;decompose [and] H;clear H;\n     assert (PArray.default t = Ftrue) by (apply is_Ftrue_correct;trivial).\n     repeat split;trivial.\n     rewrite wf_interp_form;trivial.\n     apply is_Ftrue_correct in H4;trivial;rewrite H4;reflexivity.\n     rewrite wf_interp_form;trivial.\n     apply is_Ffalse_correct in H3;trivial;rewrite H3;discriminate.\n    Qed.\n\n  End Interp.\n\nEnd Form.\n\n(* TODO Move this *)\nRecord typ_eqb : Type := Typ_eqb {\n  te_carrier : Type;\n  te_eqb : te_carrier -> te_carrier -> bool;\n  te_reflect : forall x y, reflect (x = y) (te_eqb x y)\n}.\n\n(* Common used types into which we interpret *)\n\n(* Unit *)\n\nSection Unit_typ_eqb.\n\n  Let carrier : Type := unit.\n\n  Let eqb : carrier -> carrier -> bool :=\n    fun _ _ => true.\n\n  Lemma unit_reflect :\n    forall x y, reflect (x = y) (eqb x y).\n  Proof.\n    unfold eqb; intros x y; case x; case y; simpl;\n      constructor; reflexivity.\n  Qed.\n\n  Definition unit_typ_eqb :=\n    Typ_eqb carrier eqb unit_reflect.\n\nEnd Unit_typ_eqb.\n(* End TODO *)\n\nModule Typ.\n\n  Notation index := int (only parsing).\n\n  Inductive type :=\n  | Tindex : index -> type\n  | TZ : type\n  | Tbool : type\n  | Tpositive : type.\n\n  Definition ftype := (list type * type)%type.\n\n  Section Interp.\n\n    Variable t_i : PArray.array typ_eqb.\n\n    Definition interp t :=\n      match t with\n      | Tindex i => (t_i.[i]).(te_carrier)\n      | TZ => Z\n      | Tbool => bool\n      | Tpositive => positive\n      end.\n\n    Definition interp_ftype (t:ftype) :=\n      List.fold_right (fun dom codom =>interp dom -> codom)\n      (interp (snd t)) (fst t).\n\n    (* Boolean equality over interpretation of a btype *)\n    Section Interp_Equality.\n\n      Definition i_eqb (t:type) : interp t -> interp t -> bool :=\n        match t with\n        | Tindex i => (t_i.[i]).(te_eqb)\n        | TZ => Zeq_bool\n        | Tbool => Bool.eqb\n        | Tpositive => Peqb\n        end.\n\n      Lemma i_eqb_spec : forall t x y, i_eqb t x y <-> x = y.\n      Proof.\n       destruct t;simpl;intros.\n       symmetry;apply reflect_iff;apply te_reflect.\n       symmetry;apply Zeq_is_eq_bool.\n       apply Bool.eqb_true_iff.\n       apply Peqb_eq.\n      Qed.\n\n      Lemma reflect_i_eqb : forall t x y, reflect (x = y) (i_eqb t x y).\n      Proof.\n        intros;apply iff_reflect;symmetry;apply i_eqb_spec.\n      Qed.\n\n      Lemma i_eqb_sym : forall t x y, i_eqb t x y = i_eqb t y x.\n      Proof.\n        intros t x y; case_eq (i_eqb t x y); case_eq (i_eqb t y x); auto.\n        change (i_eqb t x y = true) with (is_true (i_eqb t x y)); rewrite i_eqb_spec; intros H1 H2; subst y; pose (H:=reflect_i_eqb t x x); inversion H; [rewrite <- H0 in H1; discriminate|elim H2; auto].\n        change (i_eqb t y x = true) with (is_true (i_eqb t y x)); rewrite i_eqb_spec; intros H1 H2; subst y; pose (H:=reflect_i_eqb t x x); inversion H; [rewrite <- H0 in H2; discriminate|elim H1; auto].\n      Qed.\n\n    End Interp_Equality.\n\n  End Interp.\n\n  (* Plutôt que de tester l'égalité entre deux btypes dans Prop, on\n     écrit une fonction calculant:\n     - si deux btype A et B sont égaux\n     - si oui, une fonction permettant de passer les objets de type A en\n     objets de type B\n     On montre que cette fonction réfléchit l'égalité de Coq. *)\n\n  Section Cast.\n\n  (* L'inductif cast_result spécifie si deux btype sont égaux (Cast) ou\n     non (NoCast). Dans le cas où ils sont égaux, une fonction permet de\n     passer de l'un à l'autre. *)\n\n    Inductive cast_result (A B: type) : Type :=\n    | Cast (k: forall P, P A -> P B)\n    | NoCast.\n\n    Implicit Arguments Cast [A B].\n    Implicit Arguments NoCast [A B].\n\n    Notation idcast := (Cast (fun P x => x)).\n    (* La fonction cast calcule cast_result *)\n\n    Definition cast (A B: type) : cast_result A B :=\n      match A as C, B as D return cast_result C D with\n      | Tindex i, Tindex j =>\n        match cast i j with\n        | Some k => Cast (fun P => k (fun y => P (Tindex y)))\n        | None => NoCast\n        end\n      | TZ, TZ => idcast\n      | Tbool, Tbool => idcast\n      | Tpositive, Tpositive => idcast\n      | _, _ => NoCast\n      end.\n\n    Lemma cast_refl:\n      forall A, cast A A = Cast (fun P (H : P A) => H).\n    Proof.\n      intros A0;destruct A0;simpl;trivial.\n      rewrite cast_refl;trivial.\n    Qed.\n\n    (* Remark : I use this definition because eqb will not be used only in the interpretation *)\n    Definition eqb (A B: type) : bool :=\n      match A, B with\n      | Tindex i, Tindex j => i == j\n      | TZ, TZ => true\n      | Tbool, Tbool => true\n      | Tpositive, Tpositive => true\n      | _, _ => false\n      end.\n\n\n    (* TODO : Move this *)\n    Lemma not_false : ~ false.\n    Proof. intro;discriminate. Qed.\n    Hint Resolve not_false.\n\n    Lemma is_true_true : true.\n    Proof. reflexivity. Qed.\n    Hint Resolve is_true_true.\n\n    Lemma not_is_true_eq_false : forall b:bool, ~ b <-> b = false.\n    Proof. exact not_true_iff_false. Qed.\n\n    Lemma cast_diff: forall A B, eqb A B = false -> cast A B = NoCast.\n    Proof.\n      intros A0 B0;destruct A0; destruct B0;simpl;trivial;try discriminate.\n      intros Heq;rewrite (cast_diff _ _ Heq);trivial.\n    Qed.\n\n    Lemma neq_cast : forall A B,\n      cast A B = (if eqb A B then cast A B else NoCast).\n    Proof.\n      intros C D;case_eq (eqb C D);trivial;apply cast_diff.\n    Qed.\n\n    Lemma reflect_eqb : forall x y, reflect (x = y) (eqb x y).\n    Proof.\n      intros x y;destruct x;destruct y;simpl;try constructor;trivial;try discriminate.\n      apply iff_reflect;rewrite eqb_spec;split;intros H;[inversion H | subst];trivial.\n    Qed.\n\n    Lemma eqb_spec : forall x y, eqb x y <-> x = y.\n    Proof.\n      intros;symmetry;apply reflect_iff;apply reflect_eqb.\n    Qed.\n\n    Lemma eqb_refl : forall x, eqb x x.\n    Proof. intros; rewrite eqb_spec; auto. Qed.\n\n  End Cast.\n\nEnd Typ.\n\n(* TODO move this *)\nInductive dlist (A:Type) (P:A->Type) : list A -> Type :=\n| Dnil : dlist A P nil\n| Dcons : forall a l, P a -> dlist A P l -> dlist A P (cons a l).\n\nSet Implicit Arguments.\nDefinition list_beq := fun (A : Type) (eq_A : A -> A -> bool) =>\nfix list_eqrec (X Y : list A) : bool :=\n  match X with\n  | nil => match Y with\n           | nil => true\n           | (_ :: _)%list => false\n           end\n  | (x :: x0)%list =>\n      match Y with\n      | nil => false\n      | (x1 :: x2)%list => (eq_A x x1 && list_eqrec x0 x2)%bool\n      end\n  end.\nUnset Implicit Arguments.\n\nLemma reflect_list_beq : forall (A:Type) (beq:A -> A -> bool),\n  (forall x y, reflect (x = y) (beq x y)) ->\n  forall x y, reflect (x = y) (list_beq beq x y).\nProof.\n  intros A beq Hbeq;induction x;destruct y;simpl;try (constructor;trivial;discriminate).\n  destruct (Hbeq a a0) as [Heq | Hd];simpl;[ | constructor;intros Heq;elim Hd;inversion Heq;trivial].\n  destruct (IHx y) as [Heq0 | Hd];simpl;[ | constructor;intros Heq0;elim Hd;inversion Heq0;trivial].\n  constructor;subst;trivial.\nQed.\n\nLemma list_beq_spec : forall (A:Type) (beq:A -> A -> bool),\n  (forall x y, beq x y <-> x = y) ->\n  forall x y, list_beq beq x y <-> x = y.\nProof.\n  intros A beq HA x y;symmetry;apply reflect_iff;apply reflect_list_beq.\n  intros;apply iff_reflect;symmetry;apply HA.\nQed.\n(* End move *)\n\nModule Atom.\n\n  Notation func := int (only parsing).\n \n  Inductive cop : Type := \n   | CO_xH\n   | CO_Z0.\n\n  Inductive unop : Type :=\n   | UO_xO\n   | UO_xI\n   | UO_Zpos \n   | UO_Zneg\n   | UO_Zopp.\n\n  Inductive binop : Type :=\n   | BO_Zplus\n   | BO_Zminus\n   | BO_Zmult\n   | BO_Zlt\n   | BO_Zle\n   | BO_Zge\n   | BO_Zgt\n   | BO_eq (_ : Typ.type).\n\n  Inductive nop : Type :=\n   | NO_distinct (_ : Typ.type).\n\n  Notation hatom := int (only parsing).\n \n  Inductive atom : Type :=\n   | Acop (_: cop)\n   | Auop (_ : unop) (_:hatom)\n   | Abop (_ : binop) (_:hatom) (_:hatom)\n   | Anop (_ : nop) (_: list hatom)\n   | Aapp (_:func) (_: list hatom).\n\n\n  (* Generic predicates and operations *)\n\n  (** Equality *)\n  Definition cop_eqb o o' :=\n   match o, o' with\n   | CO_xH, CO_xH \n   | CO_Z0, CO_Z0 => true\n   | _,_ => false\n   end.\n\n  Definition uop_eqb o o' :=\n   match o, o' with\n   | UO_xO, UO_xO \n   | UO_xI, UO_xI\n   | UO_Zpos, UO_Zpos \n   | UO_Zneg, UO_Zneg\n   | UO_Zopp, UO_Zopp => true\n   | _,_ => false\n   end.\n\n  Definition bop_eqb o o' :=\n   match o, o' with\n   | BO_Zplus, BO_Zplus\n   | BO_Zminus, BO_Zminus\n   | BO_Zmult, BO_Zmult\n   | BO_Zlt, BO_Zlt\n   | BO_Zle, BO_Zle\n   | BO_Zge, BO_Zge\n   | BO_Zgt, BO_Zgt => true\n   | BO_eq t, BO_eq t' => Typ.eqb t t'\n   | _,_ => false\n   end.\n\n  Definition nop_eqb o o' :=\n    match o, o' with\n      | NO_distinct t, NO_distinct t' => Typ.eqb t t'\n    end.\n\n  Definition eqb (t t':atom) :=\n    match t,t' with\n    | Acop o, Acop o' => cop_eqb o o'\n    | Auop o t, Auop o' t' => uop_eqb o o' && (t == t')\n    | Abop o t1 t2, Abop o' t1' t2' => bop_eqb o o' && (t1 == t1') && (t2 == t2')\n    | Anop o t, Anop o' t' => nop_eqb o o' && list_beq Int31Native.eqb t t'\n    | Aapp a la, Aapp b lb => (a == b) && list_beq Int31Native.eqb la lb\n    | _, _ => false\n    end.\n\n  Ltac preflect t :=\n    let Heq := fresh \"Heq\" in\n      let Hd := fresh \"Hd\" in\n        destruct t as [Heq | Hd];simpl;\n          [ | constructor;intros Heq;elim Hd;inversion Heq;trivial].\n\n  Lemma reflect_cop_eqb : forall o1 o2, reflect (o1 = o2) (cop_eqb o1 o2).\n  Proof.\n   destruct o1;destruct o2;simpl;constructor;trivial;discriminate.\n  Qed.\n\n  Lemma reflect_uop_eqb : forall o1 o2, reflect (o1 = o2) (uop_eqb o1 o2).\n  Proof.\n   destruct o1;destruct o2;simpl;constructor;trivial;discriminate.\n  Qed.\n \n  Lemma reflect_bop_eqb : forall o1 o2, reflect (o1 = o2) (bop_eqb o1 o2).\n  Proof.\n   destruct o1;destruct o2;simpl;try (constructor;trivial;discriminate).\n   preflect (Typ.reflect_eqb t t0).\n   constructor;subst;trivial.\n  Qed.\n\n  Lemma reflect_nop_eqb : forall o1 o2, reflect (o1 = o2) (nop_eqb o1 o2).\n  Proof.\n    intros [t1] [t2]; simpl; preflect (Typ.reflect_eqb t1 t2); constructor; subst; reflexivity.\n  Qed.\n\n  Lemma reflect_eqb : forall t1 t2, reflect (t1 = t2) (eqb t1 t2).\n  Proof.\n    destruct t1;destruct t2;simpl; try (constructor;trivial;discriminate).\n    (* Constants *)\n    preflect (reflect_cop_eqb c c0);constructor;subst;trivial.\n    (* Unary operators *)\n    preflect (reflect_uop_eqb u u0); preflect (Int31Properties.reflect_eqb i i0);\n      constructor;subst;trivial.\n    (* Binary operators *)\n    preflect (reflect_bop_eqb b b0); \n    preflect (Int31Properties.reflect_eqb i i1);\n    preflect (Int31Properties.reflect_eqb i0 i2);\n    constructor;subst;trivial.\n    (* N-ary operators *)\n    preflect (reflect_nop_eqb n n0); preflect (reflect_list_beq _ _ Int31Properties.reflect_eqb l l0); constructor; subst; reflexivity.\n    (* Application *)\n    preflect (Int31Properties.reflect_eqb i i0);\n    preflect (reflect_list_beq _ _ Int31Properties.reflect_eqb l l0);\n    constructor;subst;trivial.\n  Qed.\n  \n  Lemma eqb_spec : forall t1 t2, eqb t1 t2 <-> t1 = t2.\n  Proof.\n    intros;symmetry;apply reflect_iff;apply reflect_eqb.\n  Qed.\n  \n  (** Typing and interpretation *)\n  \n  Record val (t:Type) (I:t -> Type) := Val {\n    v_type : t;\n    v_val : I v_type\n  }.\n\n  Section Typing_Interp.\n    Variable t_i : PArray.array typ_eqb.\n\n    Local Notation interp_t := (Typ.interp t_i).\n    Local Notation interp_ft := (Typ.interp_ftype t_i).\n\n    Definition bval := val Typ.type interp_t.\n    Definition Bval := Val Typ.type interp_t.\n    Definition tval := val Typ.ftype interp_ft.\n    Definition Tval := Val Typ.ftype interp_ft.\n\n    Definition bvtrue : bval := Bval Typ.Tbool true.\n    Definition bvfalse : bval := Bval Typ.Tbool false.\n\n    Lemma Bval_inj1 : forall T U t u, Bval T t = Bval U u -> T = U.\n    Proof. intros T U t u H; inversion H; auto. Qed.\n\n    Lemma Bval_inj2 : forall T t u, Bval T t = Bval T u -> t = u.\n    Proof.\n      intros T t u H; assert (H1: (fun (x:bval) =>\n      match Typ.cast (v_type _ _ x) T with\n        | Typ.Cast k => k _ (v_val _ _ x) = v_val _ _ (Bval T u)\n        | Typ.NoCast => True\n      end) (Bval T t)).\n      rewrite H, Typ.cast_refl; reflexivity.\n      simpl in H1; rewrite Typ.cast_refl in H1; auto.\n    Qed.\n\n    (* Interprétation d'une fonction*)\n    Variable t_func : PArray.array tval.\n\n    (** Type checking of atom assuming an type for hatom *)\n    Section Typ_Aux.\n      Variable get_type : hatom -> Typ.type.\n\n      Definition typ_cop o := \n        match o with\n        | CO_xH => Typ.Tpositive \n        | CO_Z0 => Typ.TZ\n        end.\n\n      Definition typ_uop o :=\n        match o with\n        | UO_xO => (Typ.Tpositive,Typ.Tpositive) \n        | UO_xI => (Typ.Tpositive,Typ.Tpositive) \n        | UO_Zpos => (Typ.Tpositive, Typ.TZ)\n        | UO_Zneg => (Typ.Tpositive, Typ.TZ)\n        | UO_Zopp => (Typ.TZ, Typ.TZ)\n        end.\n\n      Definition typ_bop o := \n        match o with\n        | BO_Zplus  => ((Typ.TZ,Typ.TZ), Typ.TZ) \n        | BO_Zminus => ((Typ.TZ,Typ.TZ), Typ.TZ) \n        | BO_Zmult  => ((Typ.TZ,Typ.TZ), Typ.TZ) \n        | BO_Zlt    => ((Typ.TZ,Typ.TZ), Typ.Tbool) \n        | BO_Zle    => ((Typ.TZ,Typ.TZ), Typ.Tbool) \n        | BO_Zge    => ((Typ.TZ,Typ.TZ), Typ.Tbool) \n        | BO_Zgt    => ((Typ.TZ,Typ.TZ), Typ.Tbool)\n        | BO_eq t   => ((t,t),Typ.Tbool)\n        end.\n\n      Definition typ_nop o :=\n        match o with\n          | NO_distinct t => (t,Typ.Tbool)\n        end.\n\n      Fixpoint check_args (args:list hatom) (targs:list Typ.type) :=\n        match args, targs with\n        | nil, nil => true\n        | a::args, t::targs => Typ.eqb (get_type a) t && check_args args targs\n        | _, _ => false\n        end.\n\n      Definition check_aux (a:atom) (t:Typ.type) : bool := \n        match a with\n        | Acop o => Typ.eqb (typ_cop o) t \n        | Auop o a =>\n          let (ta,t') := typ_uop o in\n          Typ.eqb t' t && Typ.eqb (get_type a) ta\n        | Abop o a1 a2 =>\n          let (ta,t') := typ_bop o in\n          let (ta1,ta2) := ta in\n          Typ.eqb t' t && Typ.eqb (get_type a1) ta1 && Typ.eqb (get_type a2) ta2 \n        | Anop o a =>\n          let (ta,t') := typ_nop o in\n          (Typ.eqb t' t) && (List.forallb (fun t1 => Typ.eqb (get_type t1) ta) a)\n        | Aapp f args =>\n          let (targs,tr) := v_type _ _ (t_func.[f]) in\n          check_args args targs && Typ.eqb tr t\n        end.\n\n      (* Typing is unique *)\n\n      Lemma unicity : forall a t1 t2,\n        check_aux a t1 -> check_aux a t2 -> t1 = t2.\n      Proof.\n        destruct a;simpl. \n        (* Constants *)\n        intros t1 t2;rewrite !Typ.eqb_spec;intros;subst;trivial.\n        (* Unary operators *)\n        unfold is_true; intros t1 t2;rewrite (surjective_pairing (typ_uop u)),!andb_true_iff.\n        intros [H1 _] [H2 _]; change (is_true (Typ.eqb (snd (typ_uop u)) t1)) in H1.\n        change (is_true (Typ.eqb (snd (typ_uop u)) t2)) in H2.\n        rewrite Typ.eqb_spec in H1, H2;subst;trivial.\n        (* Binary operators *)\n        unfold is_true; intros t1 t2;rewrite (surjective_pairing (typ_bop b)),\n           (surjective_pairing (fst (typ_bop b))) ,!andb_true_iff.\n        intros [[H1 _] _] [[H2 _] _]; change (is_true (Typ.eqb (snd (typ_bop b)) t1)) in H1.\n        change (is_true (Typ.eqb (snd (typ_bop b)) t2)) in H2.\n        rewrite Typ.eqb_spec in H1, H2;subst;trivial.\n        (* N-ary operators *)\n        intros t1 t2; destruct (typ_nop n) as [ta t']; unfold is_true; rewrite !andb_true_iff; change (is_true (Typ.eqb t' t1) /\\ is_true (List.forallb (fun t3 : int => Typ.eqb (get_type t3) ta) l) -> is_true (Typ.eqb t' t2) /\\ is_true (List.forallb (fun t3 : int => Typ.eqb (get_type t3) ta) l) -> t1 = t2); rewrite !Typ.eqb_spec; intros [H1 _] [H2 _]; subst; auto.\n        (* Application *)\n        intros t1 t2;destruct (v_type Typ.ftype interp_ft (t_func.[ i])).\n        unfold is_true;rewrite !andb_true_iff;intros [_ H1] [_ H2].\n        transitivity t;[ symmetry| ];rewrite <-Typ.eqb_spec;trivial.\n      Qed.\n\n      (* Typing is decidable *)\n\n      Lemma check_args_dec : forall tr args targs,\n        {exists T : Typ.type,\n          check_args args targs && Typ.eqb tr T} +\n        {forall T : Typ.type,\n          check_args args targs && Typ.eqb tr T = false}.\n      Proof.\n        intro A; induction args as [ |h l IHl]; simpl.\n        (* Base case *)\n        intros [ | ]; simpl.\n        left; exists A; apply Typ.eqb_refl.\n        intros; right; reflexivity.\n        (* Inductive case *)\n        intros [ |B targs]; simpl.\n        right; reflexivity.\n        case (Typ.eqb (get_type h) B); simpl; auto.\n      Qed.\n\n      Lemma check_aux_dec : forall a,\n        {exists T, check_aux a T} + {forall T, check_aux a T = false}.\n      Proof.\n        intros [op|op h|op h1 h2|op ha|f args]; simpl.\n        (* Constants *)\n        left; destruct op; simpl.\n        exists Typ.Tpositive; auto.\n        exists Typ.TZ; auto.\n        (* Unary operators *)\n        destruct op; simpl; try (case (Typ.eqb (get_type h) Typ.Tpositive); [left; exists Typ.Tpositive|right; intro; rewrite andb_false_r]; reflexivity); try (case (Typ.eqb (get_type h) Typ.Tpositive); [left; exists Typ.TZ|right; intro; rewrite andb_false_r]; reflexivity); case (Typ.eqb (get_type h) Typ.TZ); [left; exists Typ.TZ|right; intro; rewrite andb_false_r]; reflexivity.\n        (* Binary operators *)\n        destruct op; simpl; try (case (Typ.eqb (get_type h1) Typ.TZ); [case (Typ.eqb (get_type h2) Typ.TZ); [left; exists Typ.TZ|right; intro; rewrite andb_false_r]|right; intro; rewrite andb_false_r]; reflexivity); try (case (Typ.eqb (get_type h1) Typ.TZ); [case (Typ.eqb (get_type h2) Typ.TZ); [left; exists Typ.Tbool|right; intro; rewrite andb_false_r]|right; intro; rewrite andb_false_r]; reflexivity); case (Typ.eqb (get_type h1) t); [case (Typ.eqb (get_type h2) t); [left; exists Typ.Tbool|right; intro; rewrite andb_false_r]|right; intro; rewrite andb_false_r]; reflexivity.\n        (* N-ary operators *)\n        destruct op as [ty]; simpl; case (List.forallb (fun t1 : int => Typ.eqb (get_type t1) ty) ha).\n        left; exists Typ.Tbool; auto.\n        right; intro T; rewrite andb_false_r; auto.\n        (* Application *)\n        case (v_type Typ.ftype interp_ft (t_func .[ f])); intros; apply check_args_dec.\n      Qed.\n\n    End Typ_Aux.\n    (** Interpretation of hatom assuming an interpretation for atom *)\n    Section Interp_Aux.\n\n      Variable interp_hatom : hatom -> bval.\n\n      Definition apply_unop (t  r : Typ.type)\n            (op : interp_t t -> interp_t r) (tv:bval) :=\n        let (t', v) := tv in\n        match Typ.cast t' t with\n        | Typ.Cast k => Bval r (op (k _ v))\n        | _ => bvtrue\n        end.\n\n      Definition apply_binop (t1 t2 r : Typ.type)\n            (op : interp_t t1 -> interp_t t2 -> interp_t r) (tv1 tv2:bval) :=\n        let (t1', v1) := tv1 in\n        let (t2', v2) := tv2 in\n        match Typ.cast t1' t1, Typ.cast t2' t2 with\n        | Typ.Cast k1, Typ.Cast k2 => Bval r (op (k1 _ v1) (k2 _ v2))\n        | _, _ => bvtrue\n        end.\n\n      Fixpoint apply_func\n           targs tr (f:interp_ft (targs,tr)) (lv:list bval) : bval :=\n        match targs as targs0 return interp_ft (targs0,tr) -> bval with\n        | nil => fun v =>\n          match lv with\n          | nil => Bval tr v\n          | _ => bvtrue\n          end\n        | t::targs => fun f =>\n          match lv with\n          | v::lv =>\n            let (tv,v) := v in\n            match Typ.cast tv t with\n            | Typ.Cast k =>\n              let f := f (k _ v) in apply_func targs tr f lv\n            | _ => bvtrue\n            end\n          | _ => bvtrue\n          end\n        end f.\n\n      Definition interp_cop o :=\n        match o with\n        | CO_xH => Bval Typ.Tpositive xH\n        | CO_Z0 => Bval Typ.TZ Z0\n        end.\n\n      Definition interp_uop o :=    \n        match o with\n        | UO_xO   => apply_unop Typ.Tpositive Typ.Tpositive xO\n        | UO_xI   => apply_unop Typ.Tpositive Typ.Tpositive xI\n        | UO_Zpos => apply_unop Typ.Tpositive Typ.TZ Zpos\n        | UO_Zneg => apply_unop Typ.Tpositive Typ.TZ Zneg\n        | UO_Zopp => apply_unop Typ.TZ Typ.TZ Zopp\n        end.\n\n      Definition interp_bop o :=\n         match o with\n         | BO_Zplus => apply_binop Typ.TZ Typ.TZ Typ.TZ Zplus\n         | BO_Zminus => apply_binop Typ.TZ Typ.TZ Typ.TZ Zminus\n         | BO_Zmult => apply_binop Typ.TZ Typ.TZ Typ.TZ Zmult\n         | BO_Zlt => apply_binop Typ.TZ Typ.TZ Typ.Tbool Zlt_bool\n         | BO_Zle => apply_binop Typ.TZ Typ.TZ Typ.Tbool Zle_bool\n         | BO_Zge => apply_binop Typ.TZ Typ.TZ Typ.Tbool Zge_bool\n         | BO_Zgt => apply_binop Typ.TZ Typ.TZ Typ.Tbool Zgt_bool\n         | BO_eq t => apply_binop t t Typ.Tbool (Typ.i_eqb t_i t)\n         end.\n\n      Fixpoint compute_interp ty acc l :=\n        match l with\n          | nil => Some acc\n          | a::q =>\n            let (ta,va) := interp_hatom a in\n            match Typ.cast ta ty with\n              | Typ.Cast ka => compute_interp ty ((ka _ va)::acc) q\n              | _ => None\n            end\n        end.\n\n      (* Lemma compute_interp_spec : forall ty l acc, *)\n      (*   match compute_interp ty acc l with *)\n      (*     | Some l' => forall i, In i l' <-> (In i acc \\/ (exists a, In a l /\\ interp_hatom a = Bval ty i)) *)\n      (*     | None => exists a, In a l /\\ let (ta,_) := interp_hatom a in ta <> ty *)\n      (*   end. *)\n      (* Proof. *)\n      (*   intro ty; induction l as [ |a q IHq]; simpl. *)\n      (*   intros acc i; split. *)\n      (*   intro H; left; auto. *)\n      (*   intros [H|[a [H _]]]; auto; elim H. *)\n      (*   intro acc; case_eq (interp_hatom a); intros ta va Heq; rewrite Typ.neq_cast; case_eq (Typ.eqb ta ty). *)\n      (*   change (Typ.eqb ta ty = true) with (is_true (Typ.eqb ta ty)); rewrite Typ.eqb_spec; intro; subst ta; rewrite Typ.cast_refl; generalize (IHq (va :: acc)); clear IHq; case (compute_interp ty (va :: acc) q). *)\n      (*   intros l IH i; rewrite (IH i); clear IH; split; intros [H|[a1 [H1 H2]]]. *)\n      (*   inversion H; auto. *)\n      (*   subst va; clear H; right; exists a; split; auto. *)\n      (*   right; exists a1; split; auto. *)\n      (*   left; constructor 2; auto. *)\n      (*   destruct H1 as [H1|H1]. *)\n      (*   subst a1; left; constructor 1; rewrite Heq in H2; apply (Bval_inj2 ty); auto. *)\n      (*   right; exists a1; auto. *)\n      (*   intros [a1 [H1 H2]]; exists a1; split; auto. *)\n      (*   intro H; exists a; split; auto; rewrite Heq; intro H1; subst ta; rewrite Typ.eqb_refl in H; discriminate. *)\n      (* Qed. *)\n\n      Lemma compute_interp_spec : forall ty l acc,\n        match compute_interp ty acc l with\n          | Some l' => forall i j, In2 i j l' <-> (In2 i j acc \\/ (In j acc /\\ exists a, In a l /\\ interp_hatom a = Bval ty i) \\/ (exists a b, In2 b a l /\\ interp_hatom a = Bval ty i /\\ interp_hatom b = Bval ty j))\n          | None => exists a, In a l /\\ let (ta,_) := interp_hatom a in ta <> ty\n        end.\n      Proof.\n        intro ty; induction l as [ |a q IHq]; simpl.\n        intros acc i; split.\n        intro H; left; auto.\n        intros [H|[[_ [a [H _]]]|[a [b [H _]]]]]; auto.\n        elim H.\n        inversion H.\n        intro acc; case_eq (interp_hatom a); intros ta va Heq; rewrite Typ.neq_cast; case_eq (Typ.eqb ta ty).\n        change (Typ.eqb ta ty = true) with (is_true (Typ.eqb ta ty)); rewrite Typ.eqb_spec; intro; subst ta; rewrite Typ.cast_refl; generalize (IHq (va :: acc)); clear IHq; case (compute_interp ty (va :: acc) q).\n        intros l IH i j; rewrite (IH i j); clear IH; split.\n        intros [H|[[H [b [H1 H2]]]|[b [c [H [H1 H2]]]]]].\n        inversion H; clear H.\n        subst i l0; right; left; split; auto; exists a; split; auto.\n        subst k l0; left; auto.\n        inversion H; clear H.\n        subst va; right; right; exists b; exists a; repeat split; auto; constructor 1; auto.\n        right; left; split; auto; exists b; auto.\n        right; right; exists b; exists c; repeat split; auto; constructor 2; auto.\n        intros [H|[[H [b [[H1|H1] H2]]]|[b [c [H [H1 H2]]]]]].\n        left; constructor 2; auto.\n        subst b; rewrite Heq in H2; generalize (Bval_inj2 _ _ _ H2); intro; subst va; left; constructor; auto.\n        right; left; split.\n        constructor 2; auto.\n        exists b; auto.\n        inversion H; clear H.\n        subst c l0; rewrite Heq in H2; generalize (Bval_inj2 _ _ _ H2); intro; subst va; right; left; split.\n        constructor 1; auto.\n        exists b; auto.\n        subst k l0; right; right; exists b; exists c; auto.\n        intros [a1 [H1 H2]]; exists a1; split; auto.\n        intro H; exists a; split; auto; rewrite Heq; intro H1; subst ta; rewrite Typ.eqb_refl in H; discriminate.\n      Qed.\n\n      (* Lemma compute_interp_spec_rev : forall ty l, *)\n      (*   match compute_interp ty nil l with *)\n      (*     | Some l' => forall i, In i (rev l') <-> (exists a, In a l /\\ interp_hatom a = Bval ty i) *)\n      (*     | None => exists a, In a l /\\ let (ta,_) := interp_hatom a in ta <> ty *)\n      (*   end. *)\n      (* Proof. (* ICI *) *)\n      (*   intros ty l; generalize (compute_interp_spec ty l nil); case (compute_interp ty nil l); auto; intros l' H i; rewrite <- In_rev, (H i); split; auto; intros [H1|H1]; auto; inversion H1. *)\n      (* Qed. *)\n\n      Lemma compute_interp_spec_rev : forall ty l,\n        match compute_interp ty nil l with\n          | Some l' => forall i j, In2 j i (rev l') <-> (exists a b, In2 b a l /\\ interp_hatom a = Bval ty i /\\ interp_hatom b = Bval ty j)\n          | None => exists a, In a l /\\ let (ta,_) := interp_hatom a in ta <> ty\n        end.\n      Proof.\n        intros ty l; generalize (compute_interp_spec ty l nil); case (compute_interp ty nil l); auto; intros l' H i j; rewrite In2_rev, (H i j); split; auto; intros [H1|[[H1 _]|H1]]; auto; inversion H1.\n      Qed.\n\n      Definition interp_aux (a:atom) : bval :=\n        match a with\n        | Acop o => interp_cop o\n        | Auop o a => interp_uop o (interp_hatom a)\n        | Abop o a1 a2 => interp_bop o (interp_hatom a1) (interp_hatom a2)\n        | Anop (NO_distinct t) a =>\n          match compute_interp t nil a with\n            | Some l => Bval Typ.Tbool (distinct (Typ.i_eqb t_i t) (rev l))\n            | None => bvtrue\n          end\n        | Aapp f args =>\n          let (tf,f) := t_func.[f] in\n          let lv := List.map interp_hatom args in\n          apply_func (fst tf) (snd tf) f lv\n        end.\n\n      Definition interp_bool (v:bval) : bool :=\n        let (t,v) := v in\n        match Typ.cast t Typ.Tbool with\n        | Typ.Cast k => k _ v\n        | _ => true\n        end.\n\n\n      (* If an atom is well-typed, it has an interpretation *)\n\n      Variable get_type : hatom -> Typ.type.\n      Hypothesis check_aux_interp_hatom : forall h,\n        exists v, interp_hatom h = (Bval (get_type h) v).\n\n      Lemma check_args_interp_aux : forall t l f,\n        (let (targs, tr) := v_type Typ.ftype interp_ft f in\n          check_args get_type l targs && Typ.eqb tr t) ->\n        exists v : interp_t t,\n          (let (tf, f0) := f in\n            apply_func (fst tf) (snd tf) f0 (List.map interp_hatom l)) =\n          Bval t v.\n      Proof.\n        intro A; induction l as [ |h l IHl]; simpl; intros [tf f]; simpl.\n        (* Base case *)\n        destruct tf as [[ | ] tr]; try discriminate; simpl; rewrite Typ.eqb_spec; intro; subst tr; exists f; auto.\n        (* Inductive case *)\n        destruct tf as [[ |B targs] tr]; try discriminate; simpl; rewrite <- andb_assoc; unfold is_true; rewrite andb_true_iff; change (Typ.eqb (get_type h) B = true /\\ check_args get_type l targs && Typ.eqb tr A = true) with (is_true (Typ.eqb (get_type h) B) /\\ is_true (check_args get_type l targs && Typ.eqb tr A)); rewrite Typ.eqb_spec; intros [H1 H2]; destruct (check_aux_interp_hatom h) as [v0 Heq0]; rewrite Heq0; generalize v0 Heq0; rewrite H1; intros v1 Heq1; simpl; generalize (IHl (Tval (targs,tr) (f v1))); simpl; intro IH; destruct (IH H2) as [v2 Heq2]; exists v2; rewrite Typ.cast_refl; auto.\n      Qed.\n\n      Lemma check_aux_interp_aux_aux : forall a t,\n         check_aux get_type a t ->\n         exists v, interp_aux a = (Bval t v).\n      Proof.\n        intros [op|op h|op h1 h2|op ha|f l]; simpl.\n        (* Constants *)\n        destruct op; intros [i| | | ]; simpl; try discriminate; intros _.\n        exists 1%positive; auto.\n        exists 0%Z; auto.\n        (* Unary operators *)\n        destruct op; intros [i| | | ]; simpl; try discriminate; rewrite Typ.eqb_spec; intro H1; destruct (check_aux_interp_hatom h) as [x Hx]; rewrite Hx; simpl; generalize x Hx; rewrite H1; intros y Hy; rewrite Typ.cast_refl.\n        exists (y~0)%positive; auto.\n        exists (y~1)%positive; auto.\n        exists (Zpos y); auto.\n        exists (Zneg y); auto.\n        exists (- y)%Z; auto.\n        (* Binary operators *)\n        destruct op as [ | | | | | | |A]; intros [i| | | ]; simpl; try discriminate; unfold is_true; rewrite andb_true_iff; try (change (Typ.eqb (get_type h1) Typ.TZ = true /\\ Typ.eqb (get_type h2) Typ.TZ = true) with (is_true (Typ.eqb (get_type h1) Typ.TZ) /\\ is_true (Typ.eqb (get_type h2) Typ.TZ)); rewrite !Typ.eqb_spec; intros [H1 H2]; destruct (check_aux_interp_hatom h1) as [x1 Hx1]; rewrite Hx1; destruct (check_aux_interp_hatom h2) as [x2 Hx2]; rewrite Hx2; simpl; generalize x1 Hx1 x2 Hx2; rewrite H1, H2; intros y1 Hy1 y2 Hy2; rewrite !Typ.cast_refl).\n        exists (y1 + y2)%Z; auto.\n        exists (y1 - y2)%Z; auto.\n        exists (y1 * y2)%Z; auto.\n        exists (y1 <? y2)%Z; auto.\n        exists (y1 <=? y2)%Z; auto.\n        exists (y1 >=? y2)%Z; auto.\n        exists (y1 >? y2)%Z; auto.\n        change (Typ.eqb (get_type h1) A = true /\\ Typ.eqb (get_type h2) A = true) with (is_true (Typ.eqb (get_type h1) A) /\\ is_true (Typ.eqb (get_type h2) A)); rewrite !Typ.eqb_spec; intros [H1 H2]; destruct (check_aux_interp_hatom h1) as [x1 Hx1]; rewrite Hx1; destruct (check_aux_interp_hatom h2) as [x2 Hx2]; rewrite Hx2; simpl; generalize x1 Hx1 x2 Hx2; rewrite H1, H2; intros y1 Hy1 y2 Hy2; rewrite !Typ.cast_refl; exists (Typ.i_eqb t_i A y1 y2); auto.\n        (* N-ary operators *)\n        destruct op as [A]; simpl; intros [ | | | ]; try discriminate; simpl; intros _; case (compute_interp A nil ha).\n        intro l; exists (distinct (Typ.i_eqb t_i A) (rev l)); auto.\n        exists true; auto.\n        (* Application *)\n        intro t; apply check_args_interp_aux.\n      Qed.\n\n\n      (* If an atom is not well-typed, its interpretation is bvtrue *)\n\n      Lemma check_args_interp_aux_contr : forall l f,\n        (forall T : Typ.type,\n          (let (targs, tr) := v_type Typ.ftype interp_ft f in\n            check_args get_type l targs && Typ.eqb tr T) = false) ->\n        (let (tf, f0) := f in\n          apply_func (fst tf) (snd tf) f0 (List.map interp_hatom l)) = bvtrue.\n        induction l as [ |h l IHl]; simpl; intros [tf f]; simpl.\n        (* Base case *)\n        destruct tf as [[ | ] tr]; simpl; auto; intro H; generalize (H tr); rewrite Typ.eqb_refl; discriminate.\n        (* Inductive case *)\n        destruct tf as [[ |B targs] tr]; simpl; auto. intro H. destruct (check_aux_interp_hatom h) as [v Hv]. rewrite Hv. simpl. assert (H2: (Typ.eqb (get_type h) B = false) \\/ (forall T : Typ.type, check_args get_type l targs && Typ.eqb tr T = false)) by (case_eq (Typ.eqb (get_type h) B); try (intros; left; reflexivity); intro Heq; right; intro T; generalize (H T); rewrite Heq; auto). destruct H2 as [H2|H2]; rewrite Typ.neq_cast.\n        rewrite H2. auto.\n        case_eq (Typ.eqb (get_type h) B); auto. change (Typ.eqb (get_type h) B = true) with (is_true (Typ.eqb (get_type h) B)). rewrite Typ.eqb_spec. intro; subst B. rewrite Typ.cast_refl. apply (IHl (Tval (targs,tr) (f v))). auto.\n      Qed.\n\n      Lemma check_aux_interp_aux_contr_aux : forall a,\n        (forall T, check_aux get_type a T = false) ->\n        interp_aux a = bvtrue.\n      Proof.\n        intros [op|op h|op h1 h2|op ha|f l]; simpl.\n        (* Constants *)\n        destruct op; simpl; intro H.\n        discriminate (H Typ.Tpositive).\n        discriminate (H Typ.TZ).\n        (* Unary operators *)\n        destruct op; simpl; intro H; destruct (check_aux_interp_hatom h) as [v Hv]; rewrite Hv; simpl; rewrite Typ.neq_cast; try (pose (H2 := H Typ.Tpositive); simpl in H2; rewrite H2; auto); pose (H2 := H Typ.TZ); simpl in H2; rewrite H2; auto.\n        (* Binary operators *)\n        destruct op; simpl; intro H; destruct (check_aux_interp_hatom h1) as [v1 Hv1]; destruct (check_aux_interp_hatom h2) as [v2 Hv2]; rewrite Hv1, Hv2; simpl; try (pose (H2 := H Typ.TZ); simpl in H2; rewrite andb_false_iff in H2; destruct H2 as [H2|H2]; [rewrite (Typ.neq_cast (get_type h1)), H2|rewrite (Typ.neq_cast (get_type h2)), H2; case (Typ.cast (get_type h1) Typ.TZ)]; auto); try (pose (H2 := H Typ.Tbool); simpl in H2; rewrite andb_false_iff in H2; destruct H2 as [H2|H2]; [rewrite (Typ.neq_cast (get_type h1)), H2|rewrite (Typ.neq_cast (get_type h2)), H2; case (Typ.cast (get_type h1) Typ.TZ)]; auto); case (Typ.cast (get_type h1) t); auto.\n        (* N-ary operators *)\n        destruct op as [A]; simpl; intro H; generalize (H Typ.Tbool); simpl; clear H; assert (H: forall l1, List.forallb (fun t1 : int => Typ.eqb (get_type t1) A) ha = false -> match compute_interp A l1 ha with | Some l => Bval Typ.Tbool (distinct (Typ.i_eqb t_i A) (rev l)) | None => bvtrue end = bvtrue).\n        induction ha as [ |h ha Iha]; simpl.\n        intros; discriminate.\n        intro l1; destruct (check_aux_interp_hatom h) as [vh Hh]; case_eq (Typ.eqb (get_type h) A); simpl.\n        change (Typ.eqb (get_type h) A = true) with (is_true (Typ.eqb (get_type h) A)); rewrite Typ.eqb_spec; intro; subst A; intro H; rewrite Hh; simpl; rewrite Typ.cast_refl; apply Iha; auto.\n        intros H _; rewrite Hh; simpl; rewrite (Typ.cast_diff _ _ H); auto.\n        apply H.\n        (* Application *)\n        apply check_args_interp_aux_contr.\n      Qed.\n\n    End Interp_Aux.\n\n    Section Interp_get.\n\n      Variable t_atom : PArray.array atom.\n\n      Definition t_interp : PArray.array bval :=\n        PArray.foldi_left (fun i t_a a => t_a.[i <- interp_aux (PArray.get t_a) a])\n          (PArray.make (PArray.length t_atom) (interp_cop CO_xH)) t_atom.\n\n      Definition lt_atom i a :=\n        match a with\n        | Acop _ => true\n        | Auop _ h => h < i\n        | Abop _ h1 h2 => (h1 < i) && (h2 < i)\n        | Anop _ ha => List.forallb (fun h => h < i) ha\n        | Aapp f args => List.forallb (fun h => h < i) args\n        end.\n\n      Lemma lt_interp_aux :\n         forall f1 f2 i, (forall j, j < i -> f1 j = f2 j) ->\n         forall a, lt_atom i a ->\n             interp_aux f1 a = interp_aux f2 a.\n      Proof.\n        intros f1 f2 i Hf; destruct a;simpl;intros;auto.\n        (* Unary operators *)\n        rewrite Hf;trivial.\n        (* Binary operators *)\n        unfold is_true in H;rewrite andb_true_iff in H;destruct H;rewrite !Hf;trivial.\n        (* N-ary operators *)\n        destruct n as [A]; replace (compute_interp f1 A nil l) with (compute_interp f2 A nil l); trivial; assert (H1: forall acc, compute_interp f2 A acc l = compute_interp f1 A acc l); auto; induction l as [ |k l IHl]; simpl; auto; intro acc; simpl in H; unfold is_true in H; rewrite andb_true_iff in H; destruct H as [H1 H2]; rewrite (Hf _ H1); destruct (f2 k) as [ta va]; destruct (Typ.cast ta A) as [ka| ]; auto.\n        (* Application *)\n        replace (List.map f1 l) with (List.map f2 l); trivial.\n        induction l;simpl in H |- *;trivial.\n        unfold is_true in H;rewrite andb_true_iff in H;destruct H;rewrite Hf, IHl;trivial.\n      Qed.\n\n      Definition wf := PArray.forallbi lt_atom t_atom.\n\n      Hypothesis wf_t_i : wf.\n\n      Lemma length_t_interp : length t_interp = length t_atom.\n      Proof.\n        unfold t_interp;apply PArray.foldi_left_Ind with\n          (P := fun i a => length a = length t_atom).\n        intros;rewrite length_set;trivial.\n        rewrite length_make, ltb_length;trivial.\n      Qed.\n\n      Lemma default_t_interp : default t_interp = interp_cop CO_xH.\n      Proof.\n        unfold t_interp;apply PArray.foldi_left_Ind with\n          (P := fun i a => default a = interp_cop CO_xH).\n        intros;rewrite default_set;trivial.\n        apply default_make.\n      Qed.\n\n      Lemma t_interp_wf_lt : forall i, i < PArray.length t_atom ->\n         t_interp.[i] = interp_aux (PArray.get t_interp) (t_atom.[i]).\n      Proof.\n        set (P' i t := length t = length t_atom ->\n               forall j, j < i ->\n               t.[j] = interp_aux (PArray.get t) (t_atom.[j])).\n        assert (P' (length t_atom) t_interp).\n         unfold is_true, wf in wf_t_i;rewrite PArray.forallbi_spec in wf_t_i.\n         unfold t_interp;apply foldi_left_Ind;unfold P';intros.\n         rewrite length_set in H1.\n         destruct (Int31Properties.reflect_eqb j i).\n          rewrite e, PArray.get_set_same.\n          apply lt_interp_aux with (2:= wf_t_i i H).\n          intros;rewrite get_set_other;trivial.\n          intros Heq;elim (not_ltb_refl i);rewrite Heq at 1;trivial.\n          rewrite H1;trivial.\n         assert (j < i).\n          assert ([|j|] <> [|i|]) by(intros Heq1;elim n;apply to_Z_inj;trivial).\n          generalize H2;unfold is_true;rewrite !ltb_spec,\n            (to_Z_add_1 _ _ H);auto with zarith.\n         rewrite get_set_other, H0;auto.\n         apply lt_interp_aux with (2:= wf_t_i j (ltb_trans _ _ _ H3 H)).\n         intros;rewrite get_set_other;trivial.\n         intros Heq;elim (not_ltb_refl i);apply ltb_trans with j;\n           [ rewrite Heq| ];trivial.\n         elim (ltb_0 _ H0).\n        apply H;apply length_t_interp.\n      Qed.\n\n      Hypothesis default_t_atom : default t_atom = Acop CO_xH.\n\n      Lemma t_interp_wf : forall i,\n         t_interp.[i] = interp_aux (PArray.get t_interp) (t_atom.[i]).\n      Proof.\n        intros i;case_eq (i< PArray.length t_atom);intros.\n        apply t_interp_wf_lt;trivial.\n        rewrite !PArray.get_outofbound;trivial.\n        rewrite default_t_atom, default_t_interp;trivial.\n        rewrite length_t_interp;trivial.\n      Qed.\n\n      Definition get_type' (t_interp':array bval) i := v_type _ _ (t_interp'.[i]).\n\n      Local Notation get_type := (get_type' t_interp).\n\n      (* If an atom is well-typed, it has an interpretation *)\n\n      Lemma check_aux_interp_aux_lt_aux : forall a h,\n        (forall j : int,\n          j < h ->\n          exists v : interp_t (v_type Typ.type interp_t (a .[ j])),\n            a .[ j] = Bval (v_type Typ.type interp_t (a .[ j])) v) ->\n        forall l, List.forallb (fun h0 : int => h0 < h) l = true ->\n          forall (f0: tval),\n            exists\n              v : interp_t\n              (v_type Typ.type interp_t\n                (let (tf, f) := f0 in\n                  apply_func (fst tf) (snd tf) f (List.map (get a) l))),\n              (let (tf, f) := f0 in\n                apply_func (fst tf) (snd tf) f (List.map (get a) l)) =\n              Bval\n              (v_type Typ.type interp_t\n                (let (tf, f) := f0 in\n                  apply_func (fst tf) (snd tf) f (List.map (get a) l))) v.\n      Proof.\n        intros a h IH; induction l as [ |j l IHl]; simpl.\n        intros _ [[[ | ] tr] f]; simpl.\n        exists f; auto.\n        exists true; auto.\n        rewrite andb_true_iff; intros [H1 H2] [[[ |A targs] tr] f]; simpl.\n        exists true; auto.\n        destruct (IH j H1) as [x Hx]; rewrite Hx; simpl; case (Typ.cast (v_type Typ.type interp_t (a .[ j])) A); simpl.\n        intro k; destruct (IHl H2 (Tval (targs,tr) (f (k interp_t x)))) as [y Hy]; simpl in Hy; rewrite Hy; simpl; exists y; auto.\n        exists true; auto.\n      Qed.\n\n      Lemma check_aux_interp_aux_lt : forall h, h < length t_atom ->\n        forall a,\n          (forall j, j < h ->\n            exists v, a.[j] = Bval (v_type _ _ (a.[j])) v) ->\n          exists v, interp_aux (get a) (t_atom.[h]) =\n            Bval (v_type _ _ (interp_aux (get a) (t_atom.[h]))) v.\n      Proof.\n        unfold wf, is_true in wf_t_i; rewrite forallbi_spec in wf_t_i.\n        intros h Hh a IH; generalize (wf_t_i h Hh).\n        case (t_atom.[h]); simpl.\n        (* Constants *)\n        intros [ | ] _; simpl.\n        exists 1%positive; auto.\n        exists 0%Z; auto.\n        (* Unary operators *)\n        intros [ | | | | ] i H; simpl; destruct (IH i H) as [x Hx]; rewrite Hx; simpl.\n        case (Typ.cast (v_type Typ.type interp_t (a .[ i])) Typ.Tpositive); simpl; try (exists true; auto); intro k; exists ((k interp_t x)~0)%positive; auto.\n        case (Typ.cast (v_type Typ.type interp_t (a .[ i])) Typ.Tpositive); simpl; try (exists true; auto); intro k; exists ((k interp_t x)~1)%positive; auto.\n        case (Typ.cast (v_type Typ.type interp_t (a .[ i])) Typ.Tpositive); simpl; try (exists true; auto); intro k; exists (Zpos (k interp_t x)); auto.\n        case (Typ.cast (v_type Typ.type interp_t (a .[ i])) Typ.Tpositive); simpl; try (exists true; auto); intro k; exists (Zneg (k interp_t x)); auto.\n        case (Typ.cast (v_type Typ.type interp_t (a .[ i])) Typ.TZ); simpl; try (exists true; auto); intro k; exists (- k interp_t x)%Z; auto.\n        (* Binary operators *)\n        intros [ | | | | | | |A] h1 h2; simpl; rewrite andb_true_iff; intros [H1 H2]; destruct (IH h1 H1) as [x Hx]; destruct (IH h2 H2) as [y Hy]; rewrite Hx, Hy; simpl.\n        case (Typ.cast (v_type Typ.type interp_t (a .[ h1])) Typ.TZ); simpl; try (exists true; auto); intro k1; case (Typ.cast (v_type Typ.type interp_t (a .[ h2])) Typ.TZ); simpl; try (exists true; auto); intro k2; exists (k1 interp_t x + k2 interp_t y)%Z; auto.\n        case (Typ.cast (v_type Typ.type interp_t (a .[ h1])) Typ.TZ); simpl; try (exists true; auto); intro k1; case (Typ.cast (v_type Typ.type interp_t (a .[ h2])) Typ.TZ); simpl; try (exists true; auto); intro k2; exists (k1 interp_t x - k2 interp_t y)%Z; auto.\n        case (Typ.cast (v_type Typ.type interp_t (a .[ h1])) Typ.TZ); simpl; try (exists true; auto); intro k1; case (Typ.cast (v_type Typ.type interp_t (a .[ h2])) Typ.TZ); simpl; try (exists true; auto); intro k2; exists (k1 interp_t x * k2 interp_t y)%Z; auto.\n        case (Typ.cast (v_type Typ.type interp_t (a .[ h1])) Typ.TZ); simpl; try (exists true; auto); intro k1; case (Typ.cast (v_type Typ.type interp_t (a .[ h2])) Typ.TZ) as [k2| ]; simpl; try (exists true; reflexivity); exists (k1 interp_t x <? k2 interp_t y); auto.\n        case (Typ.cast (v_type Typ.type interp_t (a .[ h1])) Typ.TZ); simpl; try (exists true; auto); intro k1; case (Typ.cast (v_type Typ.type interp_t (a .[ h2])) Typ.TZ) as [k2| ]; simpl; try (exists true; reflexivity); exists (k1 interp_t x <=? k2 interp_t y); auto.\n        case (Typ.cast (v_type Typ.type interp_t (a .[ h1])) Typ.TZ); simpl; try (exists true; auto); intro k1; case (Typ.cast (v_type Typ.type interp_t (a .[ h2])) Typ.TZ) as [k2| ]; simpl; try (exists true; reflexivity); exists (k1 interp_t x >=? k2 interp_t y); auto.\n        case (Typ.cast (v_type Typ.type interp_t (a .[ h1])) Typ.TZ); simpl; try (exists true; auto); intro k1; case (Typ.cast (v_type Typ.type interp_t (a .[ h2])) Typ.TZ) as [k2| ]; simpl; try (exists true; reflexivity); exists (k1 interp_t x >? k2 interp_t y); auto.\n        case (Typ.cast (v_type Typ.type interp_t (a .[ h1])) A); simpl; try (exists true; auto); intro k1; case (Typ.cast (v_type Typ.type interp_t (a .[ h2])) A) as [k2| ]; simpl; try (exists true; reflexivity); exists (Typ.i_eqb t_i A (k1 interp_t x) (k2 interp_t y)); auto.\n        (* N-ary operators *)\n        intros [A] l; assert (forall acc, List.forallb (fun h0 : int => h0 < h) l = true -> exists v, match compute_interp (get a) A acc l with | Some l0 => Bval Typ.Tbool (distinct (Typ.i_eqb t_i A) (rev l0)) | None => bvtrue end = Bval (v_type Typ.type interp_t match compute_interp (get a) A acc l with | Some l0 => Bval Typ.Tbool (distinct (Typ.i_eqb t_i A) (rev l0)) | None => bvtrue end) v); auto; induction l as [ |i l IHl]; simpl.\n        intros acc _; exists (distinct (Typ.i_eqb t_i A) (rev acc)); auto.\n        intro acc; rewrite andb_true_iff; intros [H1 H2]; destruct (IH _ H1) as [va Hva]; rewrite Hva; simpl; case (Typ.cast (v_type Typ.type interp_t (a .[ i])) A); simpl; try (exists true; auto); intro k; destruct (IHl (k interp_t va :: acc) H2) as [vb Hvb]; exists vb; auto.\n        (* Application *)\n        intros i l H; apply (check_aux_interp_aux_lt_aux a h IH l H (t_func.[i])).\n      Qed.\n\n      Lemma check_aux_interp_hatom_lt : forall h, h < length t_atom ->\n        exists v, t_interp.[h] = Bval (get_type h) v.\n      Proof.\n        set (P' i t := length t = length t_atom ->\n          forall j, j < i ->\n            exists v, t.[j] = Bval (v_type Typ.type interp_t (t.[j])) v).\n        assert (P' (length t_atom) t_interp).\n        unfold t_interp;apply foldi_left_Ind;unfold P';intros.\n        rewrite length_set in H1.\n        destruct (Int31Properties.reflect_eqb j i).\n        rewrite e, PArray.get_set_same.\n        apply check_aux_interp_aux_lt; auto.\n        rewrite H1; auto.\n        assert (j < i).\n        assert ([|j|] <> [|i|]) by(intros Heq1;elim n;apply to_Z_inj;trivial).\n        generalize H2;unfold is_true;rewrite !ltb_spec,\n          (to_Z_add_1 _ _ H);auto with zarith.\n        rewrite get_set_other;auto.\n        elim (ltb_0 _ H0).\n        apply H;apply length_t_interp.\n      Qed.\n\n      Lemma check_aux_interp_hatom : forall h,\n        exists v, t_interp.[h] = Bval (get_type h) v.\n      Proof.\n        intros i;case_eq (i< PArray.length t_atom);intros.\n        apply check_aux_interp_hatom_lt;trivial.\n        unfold get_type'; rewrite !PArray.get_outofbound;trivial.\n        rewrite default_t_interp; simpl; exists (1%positive); auto.\n        rewrite length_t_interp;trivial.\n      Qed.\n\n      Lemma check_aux_interp_aux : forall a t,\n         check_aux get_type a t ->\n         exists v, interp_aux (get t_interp) a = (Bval t v).\n      Proof.\n        intros a t; apply check_aux_interp_aux_aux; apply check_aux_interp_hatom.\n      Qed.\n\n      (* If an atom is not well-typed, its interpretation if bvtrue *)\n\n      Lemma check_aux_interp_aux_contr : forall a,\n        (forall T, check_aux get_type a T = false) ->\n        interp_aux (get t_interp) a = bvtrue.\n      Proof.\n        intros; eapply check_aux_interp_aux_contr_aux; eauto; apply check_aux_interp_hatom.\n      Qed.\n\n    End Interp_get.\n\n\n    Definition get_type t_atom :=\n      get_type' (t_interp t_atom).\n\n    Definition wt t_atom :=\n      let t_interp := t_interp t_atom in\n      let get_type := get_type' t_interp in\n        PArray.forallbi (fun i h => check_aux get_type h (get_type i)) t_atom.\n\n\n    Definition interp_hatom (t_atom : PArray.array atom) :=\n      let t_a := t_interp t_atom in\n      PArray.get t_a.\n\n    Definition interp t_atom := interp_aux (interp_hatom t_atom).\n\n    Definition interp_form_hatom t_atom : hatom -> bool :=\n      let interp := interp_hatom t_atom in\n      fun a => interp_bool (interp a).\n\n  End Typing_Interp.\n\n  Definition check_atom t_atom :=\n    match default t_atom with\n      | Acop CO_xH => wf t_atom\n      | _ => false\n    end.\n\n  Lemma check_atom_correct : forall t_atom, check_atom t_atom ->\n    wf t_atom /\\ default t_atom = Acop CO_xH.\n  Proof.\n    intro t_atom; unfold check_atom; case (default t_atom); try discriminate; intro c; case c; auto; discriminate.\n  Qed.\n\nEnd Atom.\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/SMT_terms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2921442568576775}}
{"text": "(**\nThis file is part of the Flocq formalization of floating-point\narithmetic in Coq: http://flocq.gforge.inria.fr/\n\nCopyright (C) 2018-2019 Guillaume Bertholon\n#<br />#\nCopyright (C) 2018-2019 Érik Martin-Dorel\n#<br />#\nCopyright (C) 2018-2019 Pierre Roux\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 3 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nCOPYING file for more details.\n*)\n\n(** * Interface Flocq with Coq (>= 8.11) primitive floating-point numbers. *)\n\nFrom Coq Require Import Int63 ZArith Reals Floats SpecFloat.\nRequire Import Zaux BinarySingleNaN.\n\n(** Conversions from/to Flocq binary_float *)\n\nDefinition Prim2B (x : float) : binary_float prec emax :=\n  SF2B (Prim2SF x) (Prim2SF_valid x).\n\nDefinition B2Prim (x : binary_float prec emax) : float :=\n  SF2Prim (B2SF x).\n\nLemma B2Prim_Prim2B : forall x, B2Prim (Prim2B x) = x.\nProof.\nintros x.\nunfold Prim2B, B2Prim.\nnow rewrite B2SF_SF2B, SF2Prim_Prim2SF.\nQed.\n\nLemma Prim2B_B2Prim : forall x, Prim2B (B2Prim x) = x.\nProof.\nintro x.\nunfold Prim2B, B2Prim.\napply B2SF_inj.\nrewrite B2SF_SF2B.\napply Prim2SF_SF2Prim.\napply valid_binary_B2SF.\nQed.\n\nLemma Prim2B_inj : forall x y, Prim2B x = Prim2B y -> x = y.\nProof.\nintros x y Heq.\ngeneralize (f_equal B2Prim Heq).\nnow rewrite 2!B2Prim_Prim2B.\nQed.\n\nLemma B2Prim_inj : forall x y, B2Prim x = B2Prim y -> x = y.\nProof.\nintros x y Heq.\ngeneralize (f_equal Prim2B Heq).\nnow rewrite 2!Prim2B_B2Prim.\nQed.\n\nLemma B2SF_Prim2B : forall x, B2SF (Prim2B x) = Prim2SF x.\nProof.\nintros x.\napply SF2Prim_inj.\n- rewrite SF2Prim_Prim2SF.\n  apply B2Prim_Prim2B.\n- apply valid_binary_B2SF.\n- apply Prim2SF_valid.\nQed.\n\nLemma Prim2SF_B2Prim : forall x, Prim2SF (B2Prim x) = B2SF x.\nProof.\nintro x; unfold B2Prim.\nnow rewrite Prim2SF_SF2Prim; [|apply valid_binary_B2SF].\nQed.\n\n(** Basic properties of the Binary64 format *)\n\nLocal Instance Hprec : FLX.Prec_gt_0 prec := eq_refl _.\n\nLocal Instance Hmax : Prec_lt_emax prec emax := eq_refl _.\n\n(** Equivalence between prim_float and Flocq binary_float operations *)\n\nTheorem opp_equiv : forall x, Prim2B (- x) = Bopp (Prim2B x).\nProof.\nintro x.\napply B2Prim_inj.\nrewrite B2Prim_Prim2B.\napply Prim2SF_inj.\nrewrite Prim2SF_B2Prim.\nrewrite opp_spec.\nrewrite <-B2SF_Prim2B.\nnow case Prim2B as [sx|sx| |sx mx ex Bx].\nQed.\n\nTheorem abs_equiv : forall x, Prim2B (abs x) = Babs (Prim2B x).\nProof.\nintro x.\napply B2Prim_inj.\nrewrite B2Prim_Prim2B.\napply Prim2SF_inj.\nrewrite Prim2SF_B2Prim.\nrewrite abs_spec.\nrewrite <-B2SF_Prim2B.\nnow case Prim2B as [sx|sx| |sx mx ex Bx].\nQed.\n\nTheorem compare_equiv :\n  forall x y,\n  (x ?= y)%float = flatten_cmp_opt (Bcompare (Prim2B x) (Prim2B y)).\nProof.\nintros x y.\nrewrite compare_spec.\nrewrite <-!B2SF_Prim2B.\nnow case (Prim2B x) as [sx|sx| |sx mx ex Bx];\n  case (Prim2B y) as [sy|sy| |sy my ey By].\nQed.\n\nLemma round_nearest_even_equiv s m l :\n  round_nearest_even m l = choice_mode mode_NE s m l.\nProof.\ncase l; [reflexivity|intro c].\ncase c; [|reflexivity..].\nnow simpl; unfold Round.cond_incr; case Z.even.\nQed.\n\nLemma binary_round_aux_equiv sx mx ex lx :\n  SpecFloat.binary_round_aux prec emax sx mx ex lx\n  = binary_round_aux prec emax mode_NE sx mx ex lx.\nProof.\nunfold SpecFloat.binary_round_aux, binary_round_aux.\nset (mrse' := shr_fexp _ _ _).\ncase mrse'; intros mrs' e'; simpl.\nnow rewrite (round_nearest_even_equiv sx).\nQed.\n\nTheorem mul_equiv :\n  forall x y,\n  Prim2B (x * y) = Bmult mode_NE (Prim2B x) (Prim2B y).\nProof.\nintros x y.\napply B2Prim_inj.\nrewrite B2Prim_Prim2B.\napply Prim2SF_inj.\nrewrite Prim2SF_B2Prim.\nrewrite mul_spec.\nrewrite <-!B2SF_Prim2B.\ncase (Prim2B x) as [sx|sx| |sx mx ex Bx];\n  case (Prim2B y) as [sy|sy| |sy my ey By]; [now trivial..|].\nsimpl.\nrewrite B2SF_SF2B.\napply binary_round_aux_equiv.\nQed.\n\nLemma binary_round_equiv s m e :\n  SpecFloat.binary_round prec emax s m e =\n  binary_round prec emax mode_NE s m e.\nProof.\nunfold SpecFloat.binary_round, binary_round, shl_align_fexp.\nset (mez := shl_align _ _ _); case mez as [mz ez].\napply binary_round_aux_equiv.\nQed.\n\n\nLemma binary_normalize_equiv m e szero :\n  SpecFloat.binary_normalize prec emax m e szero\n  = B2SF (binary_normalize prec emax Hprec Hmax mode_NE m e szero).\nProof.\ncase m as [|p|p].\n- now simpl.\n- simpl; rewrite B2SF_SF2B; apply binary_round_equiv.\n- simpl; rewrite B2SF_SF2B; apply binary_round_equiv.\nQed.\n\nTheorem add_equiv :\n  forall x y,\n  Prim2B (x + y) = Bplus mode_NE (Prim2B x) (Prim2B y).\nProof.\nintros x y.\napply B2Prim_inj.\nrewrite B2Prim_Prim2B.\napply Prim2SF_inj.\nrewrite Prim2SF_B2Prim.\nrewrite add_spec.\nrewrite <-!B2SF_Prim2B.\ncase (Prim2B x) as [sx|sx| |sx mx ex Bx];\n  case (Prim2B y) as [sy|sy| |sy my ey By];\n  [now (trivial || simpl; case Bool.eqb)..|].\napply binary_normalize_equiv.\nQed.\n\nTheorem sub_equiv :\n  forall x y,\n  Prim2B (x - y) = Bminus mode_NE (Prim2B x) (Prim2B y).\nProof.\nintros x y.\napply B2Prim_inj.\nrewrite B2Prim_Prim2B.\napply Prim2SF_inj.\nrewrite Prim2SF_B2Prim.\nrewrite sub_spec.\nrewrite <-!B2SF_Prim2B.\ncase (Prim2B x) as [sx|sx| |sx mx ex Bx];\n  case (Prim2B y) as [sy|sy| |sy my ey By];\n  [now (trivial || simpl; case Bool.eqb)..|].\nsimpl.\nunfold Zminus.\nrewrite <- cond_Zopp_negb.\napply binary_normalize_equiv.\nQed.\n\nTheorem div_equiv :\n  forall x y,\n  Prim2B (x / y) = Bdiv mode_NE (Prim2B x) (Prim2B y).\nProof.\nintros x y.\napply B2Prim_inj.\nrewrite B2Prim_Prim2B.\napply Prim2SF_inj.\nrewrite Prim2SF_B2Prim.\nrewrite div_spec.\nrewrite <-!B2SF_Prim2B.\ncase (Prim2B x) as [sx|sx| |sx mx ex Bx];\n  case (Prim2B y) as [sy|sy| |sy my ey By];\n  [now (trivial || simpl; case Bool.eqb)..|].\nsimpl.\nrewrite B2SF_SF2B.\nset (melz := SFdiv_core_binary _ _ _ _ _ _).\ncase melz as [[mz ez] lz].\napply binary_round_aux_equiv.\nQed.\n\nTheorem sqrt_equiv :\n  forall x, Prim2B (sqrt x) = Bsqrt mode_NE (Prim2B x).\nProof.\nintro x.\napply B2Prim_inj.\nrewrite B2Prim_Prim2B.\napply Prim2SF_inj.\nrewrite Prim2SF_B2Prim.\nrewrite sqrt_spec.\nrewrite <-B2SF_Prim2B.\ncase Prim2B as [sx|sx| |sx mx ex Bx]; [now (trivial || case sx)..|].\ncase sx; [reflexivity|].\nsimpl.\nrewrite B2SF_SF2B.\nset (melz := SFsqrt_core_binary _ _ _ _).\ncase melz as [[mz ez] lz].\napply binary_round_aux_equiv.\nQed.\n\nTheorem normfr_mantissa_equiv :\n  forall x,\n  to_Z (normfr_mantissa x) = Z.of_N (Bnormfr_mantissa (Prim2B x)).\nProof.\nintro x.\nrewrite normfr_mantissa_spec.\nrewrite <-B2SF_Prim2B.\nnow case Prim2B.\nQed.\n\nTheorem ldexp_equiv :\n  forall x e,\n  Prim2B (ldexp x e) = Bldexp mode_NE (Prim2B x) e.\nProof.\nintros x e.\napply B2Prim_inj.\nrewrite B2Prim_Prim2B.\napply Prim2SF_inj.\nrewrite Prim2SF_B2Prim.\nrewrite ldexp_spec.\nrewrite <-!B2SF_Prim2B.\ncase (Prim2B x) as [sx|sx| |sx mx ex Bx]; [now trivial..|].\nsimpl.\nrewrite B2SF_SF2B.\napply binary_round_equiv.\nQed.\n\nTheorem ldshiftexp_equiv :\n  forall x e,\n  Prim2B (ldshiftexp x e) = Bldexp mode_NE (Prim2B x) (to_Z e - shift).\nProof.\nintros x e.\napply B2Prim_inj.\nrewrite B2Prim_Prim2B.\napply Prim2SF_inj.\nrewrite Prim2SF_B2Prim.\nrewrite ldshiftexp_spec.\nrewrite <-!B2SF_Prim2B.\ncase (Prim2B x) as [sx|sx| |sx mx ex Bx]; [now trivial..|].\nsimpl.\nrewrite B2SF_SF2B.\napply binary_round_equiv.\nQed.\n\nTheorem frexp_equiv :\n  forall x : float,\n  let (m, e) := frexp x in\n  (Prim2B m, e) = Bfrexp (Prim2B x).\nProof.\nintro x.\ngeneralize (frexp_spec x).\ndestruct frexp as [f e].\nrewrite <-(B2SF_Prim2B x).\nreplace (SFfrexp _ _ _)\n  with (let (f, e) := Bfrexp (Prim2B x) in\n        (B2SF f, e)).\n- case Bfrexp; intros f' e' [= H ->]; f_equal.\n  now apply B2SF_inj; rewrite B2SF_Prim2B.\n- case (Prim2B x) as [s|s| |s m e' Hme] ; try easy.\n  simpl.\n  rewrite B2SF_SF2B.\n  unfold Ffrexp_core_binary.\n  change (digits2_pos m) with (Digits.digits2_pos m).\n  now destruct Pos.leb.\nQed.\n\nTheorem frshiftexp_equiv :\n  forall x : float,\n  let (m, e) := frshiftexp x in\n  (Prim2B m, (to_Z e - shift)%Z) = Bfrexp (Prim2B x).\nProof.\nintro x.\ngeneralize (frexp_equiv x).\nunfold frexp.\nnow case frshiftexp.\nQed.\n\nTheorem infinity_equiv : infinity = B2Prim (B754_infinity false).\nProof. now compute. Qed.\n\nTheorem neg_infinity_equiv : neg_infinity = B2Prim (B754_infinity true).\nProof. now compute. Qed.\n\nTheorem nan_equiv : nan = B2Prim B754_nan.\nProof. now compute. Qed.\n\nTheorem zero_equiv : zero = B2Prim (B754_zero false).\nProof. now compute. Qed.\n\nTheorem neg_zero_equiv : neg_zero = B2Prim (B754_zero true).\nProof. now compute. Qed.\n\nTheorem one_equiv : one = B2Prim Bone.\nProof. now compute. Qed.\n\nTheorem two_equiv : two = B2Prim (Bplus mode_NE Bone Bone).\nProof. now compute. Qed.\n\nTheorem ulp_equiv :\n  forall x, Prim2B (ulp x) = Bulp' (Prim2B x).\nProof.\nintro x.\nunfold ulp, Bulp'.\nrewrite one_equiv, ldexp_equiv, Prim2B_B2Prim.\ngeneralize (frexp_equiv x).\ncase frexp; intros f e.\ndestruct Bfrexp as [f' e'].\nnow intros [= _ <-].\nQed.\n\nTheorem next_up_equiv :\n  forall x, Prim2B (next_up x) = Bsucc (Prim2B x).\nProof.\nintro x.\napply B2Prim_inj.\nrewrite B2Prim_Prim2B.\napply Prim2SF_inj.\nrewrite Prim2SF_B2Prim.\nrewrite next_up_spec.\nrewrite <-B2SF_Prim2B.\nassert (Hsndfrexp : forall x : binary_float prec emax, snd (SFfrexp prec emax (B2SF x)) = snd (Bfrexp x)).\n{ intro x'.\n  generalize (frexp_spec (B2Prim x')).\n  generalize (frexp_equiv (B2Prim x')).\n  case frexp; intros f' e'.\n  rewrite Prim2B_B2Prim, Prim2SF_B2Prim.\n  intros H H'; generalize (f_equal snd H'); generalize (f_equal snd H); simpl.\n  now intros ->. }\nassert (Hldexp : forall x e, SFldexp prec emax (B2SF x) e = B2SF (Bldexp mode_NE x e)).\n{ intros x' e'.\n  rewrite <-(Prim2B_B2Prim x'), B2SF_Prim2B, <-ldexp_spec.\n  now rewrite <-B2SF_Prim2B, ldexp_equiv. }\nassert (Hulp : forall x, SFulp prec emax (B2SF x) = B2SF (Bulp' x)).\n{ intro x'.\n  unfold SFulp, Bulp'.\n  now rewrite Hsndfrexp, <-Hldexp. }\nassert (Hpred_pos : forall x, (0 < B2R x)%R -> SFpred_pos prec emax (B2SF x) = B2SF (Bpred_pos' x)).\n{ intros x' Fx'.\n  unfold SFpred_pos, Bpred_pos'.\n  rewrite Hsndfrexp.\n  set (fe := fexp _ _ _).\n  change (SFone _ _) with (B2SF Bone).\n  rewrite Hldexp, Hulp.\n  case x' as [sx|sx| |sx mx ex Bx]; try easy.\n  unfold B2SF at 1.\n  set (y := Bldexp _ _ _).\n  set (z := Bulp' _).\n  case Pos.eqb.\n  - rewrite <-(Prim2B_B2Prim (B754_finite _ _ _ _)).\n    rewrite <-(Prim2B_B2Prim y).\n    now rewrite <-sub_equiv, !B2SF_Prim2B, sub_spec.\n  - rewrite <-(Prim2B_B2Prim (B754_finite _ _ _ _)).\n    rewrite <-(Prim2B_B2Prim z).\n    now rewrite <-sub_equiv, !B2SF_Prim2B, sub_spec. }\ncase Prim2B as [sx|sx| |sx mx ex Bx]; [reflexivity|now case sx|reflexivity|].\nrewrite <- Bsucc'_correct by easy.\nunfold SF64succ, SFsucc, B2SF at 1, Bsucc'.\ncase sx.\n- unfold B2SF at 1, SFopp at 2.\n  rewrite <-(Prim2B_B2Prim (Bpred_pos' _)).\n  rewrite <- opp_equiv, B2SF_Prim2B, opp_spec, Prim2SF_B2Prim.\n  rewrite <- Hpred_pos.\n  easy.\n  now apply Float_prop.F2R_gt_0.\n- rewrite Hulp.\n  rewrite Bulp'_correct by easy.\n  rewrite <-(Prim2B_B2Prim (B754_finite _ _ _ _)).\n  rewrite <-(Prim2B_B2Prim (Bulp _)).\n  rewrite <-add_equiv, !B2SF_Prim2B, add_spec, !Prim2SF_B2Prim.\n  now unfold SF64add.\nQed.\n\nTheorem next_down_equiv :\n  forall x, Prim2B (next_down x) = Bpred (Prim2B x).\nProof.\nintro x.\napply B2Prim_inj.\nrewrite B2Prim_Prim2B.\napply Prim2SF_inj.\nrewrite Prim2SF_B2Prim.\nrewrite next_down_spec.\nrewrite <-B2SF_Prim2B.\nunfold Bpred.\nrewrite <-(Prim2B_B2Prim (Bopp (Prim2B x))).\nrewrite <-next_up_equiv, <-opp_equiv, !B2SF_Prim2B, opp_spec, next_up_spec.\nunfold SF64pred, SFpred, SF64succ.\ndo 2 f_equal.\nnow rewrite <-opp_equiv, B2Prim_Prim2B, opp_spec.\nQed.\n\nTheorem is_nan_equiv :\n  forall x, PrimFloat.is_nan x = is_nan (Prim2B x).\nProof.\nintro x.\nunfold PrimFloat.is_nan.\nrewrite eqb_spec.\nrewrite <-B2SF_Prim2B.\ncase Prim2B as [sx|sx| |sx mx ex Bx]; [reflexivity|now case sx|reflexivity| ].\nsimpl.\nrewrite Bool.negb_false_iff.\nunfold SFeqb, SFcompare.\nrewrite Z.compare_refl, Pos.compare_refl.\nnow case sx.\nQed.\n\nTheorem is_zero_equiv :\n  forall x,\n  is_zero x = match Prim2B x with B754_zero _ => true | _ => false end.\nProof.\nintro x.\nunfold is_zero.\nrewrite eqb_spec.\nrewrite <-B2SF_Prim2B.\nnow case Prim2B as [sx|sx| |sx mx ex Bx]; try reflexivity; case sx.\nQed.\n\nTheorem is_infinity_equiv :\n  forall x,\n  is_infinity x = match Prim2B x with B754_infinity _ => true | _ => false end.\nProof.\nintro x.\nunfold is_infinity.\nrewrite eqb_spec.\nrewrite <-B2SF_Prim2B.\nrewrite B2SF_Prim2B, abs_spec.\nrewrite <-B2SF_Prim2B.\nnow case Prim2B.\nQed.\n\nTheorem get_sign_equiv : forall x, get_sign x = Bsign (Prim2B x).\nProof.\nintro x.\nunfold get_sign.\nrewrite is_zero_equiv.\nrewrite ltb_spec.\nrewrite <-(B2Prim_Prim2B x).\ncase (Prim2B x) as [sx|sx| |sx mx ex Bx]; rewrite Prim2B_B2Prim.\n- now rewrite div_spec; case sx.\n- now case sx.\n- now simpl.\n- now rewrite Prim2SF_B2Prim; case sx.\nQed.\n\nTheorem is_finite_equiv :\n  forall x, PrimFloat.is_finite x = is_finite (Prim2B x).\nProof.\nintro x.\nunfold PrimFloat.is_finite.\nrewrite is_nan_equiv, is_infinity_equiv.\nnow case (Prim2B x) as [sx|sx| |sx mx ex Bx].\nQed.\n\nTheorem of_int63_equiv :\n  forall i,\n  Prim2B (of_int63 i)\n  = binary_normalize prec emax Hprec Hmax mode_NE (to_Z i) 0 false.\nProof.\nintro i.\napply B2SF_inj.\nrewrite B2SF_Prim2B.\nrewrite of_int63_spec.\napply binary_normalize_equiv.\nQed.\n\nTheorem eqb_equiv :\n  forall x y,\n  eqb x y = Beqb (Prim2B x) (Prim2B y).\nProof.\nintros x y.\nrewrite eqb_spec.\nunfold Beqb.\nnow rewrite !B2SF_Prim2B.\nQed.\n\nTheorem ltb_equiv :\n  forall x y,\n  ltb x y = Bltb (Prim2B x) (Prim2B y).\nProof.\nintros x y.\nrewrite ltb_spec.\nunfold Bltb.\nnow rewrite !B2SF_Prim2B.\nQed.\n\nTheorem leb_equiv :\n  forall x y,\n  leb x y = Bleb (Prim2B x) (Prim2B y).\nProof.\nintros x y.\nrewrite leb_spec.\nunfold Bleb.\nnow rewrite !B2SF_Prim2B.\nQed.\n", "meta": {"author": "pi8027", "repo": "flocq", "sha": "460a276633f2ae70a64226733287176d35b1e3e9", "save_path": "github-repos/coq/pi8027-flocq", "path": "github-repos/coq/pi8027-flocq/flocq-460a276633f2ae70a64226733287176d35b1e3e9/src/IEEE754/PrimFloat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.29206267891059184}}
{"text": "(* ** Normal Sequent Calculus **)\n\nFrom Undecidability Require Import Shared.ListAutomation.\nFrom Undecidability.Synthetic Require Import Definitions DecidabilityFacts EnumerabilityFacts ListEnumerabilityFacts ReducibilityFacts.\nImport ListAutomationNotations.\nFrom Undecidability Require Import FOL.Syntax.Facts.\nFrom Undecidability Require Import FOL.Syntax.Theories.\nFrom Undecidability.FOL.Deduction Require Export FragmentSequent FragmentNDFacts.\nFrom Undecidability.FOL.Semantics.Kripke Require Import FragmentCore FragmentSoundness.\nImport FragmentSyntax.\nExport FragmentSyntax.\n\nSection Gentzen.\n\n  Context {Σ_funcs : funcs_signature}.\n  Context {Σ_preds : preds_signature}.\n\n  Lemma seq_consistent :\n    ~ [] ⊢S ⊥.\n  Proof.\n    enough (forall ff (H : falsity_on = ff), ~ [] ⊢S (match H in _ = f return @form _ _ _ f with eq_refl _ => ⊥ end)) as H.\n    - apply (H falsity_on eq_refl).\n    - intros ff Heq. remember nil. remember None.\n      remember (match _ with eq_refl _ => _ end).\n      intros H. induction H; subst; try intuition congruence.\n      now eapply IHsprv with eq_refl.\n  Qed.\n\n  Section Weakening.\n    Context {b : falsity_flag}.\n\n    Lemma seq_Weak A B phi psi :\n      sprv A phi psi -> A <<= B -> sprv B phi psi.\n    Proof.\n      intros H; induction H in B |-*; intuition; eauto using incl_map. \n    Qed.\n\n    Theorem seq_subst_Weak A phi psi sigma :\n      sprv A phi psi -> sprv ([phi[sigma] | phi ∈ A]) (option_map (subst_form sigma) phi) psi[sigma].\n    Proof.\n      induction 1 in sigma |-*; cbn; eauto using in_map.\n      - apply AllR. setoid_rewrite map_map in IHsprv. erewrite map_map, map_ext.\n        apply IHsprv. intros ?. cbn. now rewrite up_form.\n      - specialize (IHsprv sigma). apply AllL with (t := t`[sigma]). cbn in IHsprv.\n        rewrite subst_comp in *. unfold scons, funcomp in *. erewrite subst_ext. apply IHsprv.\n        intros [|n]. 1: easy. cbn. unfold funcomp. rewrite subst_term_comp. apply subst_term_id.\n        easy.\n    Qed.\n\n    Context {HdF : eq_dec Σ_funcs} {HdP : eq_dec Σ_preds}.\n\n    Lemma seq_nameless_equiv_all' A phi n :\n      bounded_L n A -> bounded (S n) phi -> [f[↑] | f ∈ A] ⊢S phi <-> A ⊢S phi[$n..].\n    Proof.\n      intros HL Hphi. split.\n      - intros H. apply (seq_subst_Weak ($n..)) in H. rewrite map_map in *.\n        erewrite map_ext, map_id in H; try apply H. intros. apply subst_shift.\n      - intros H. apply (seq_subst_Weak (cycle_shift n)) in H.\n        rewrite (map_ext_in _ (subst_form ↑)) in H.\n        + now rewrite cycle_shift_subject in H.\n        + intros psi HP. now apply cycle_shift_shift, HL.\n    Qed.\n  End Weakening.\n\n  (* **** Normalization *)\n  Local Unset Implicit Arguments.\n  (* We redefine sprv and prv in Type so we define predicates on them. *)\n  Inductive tsprv : forall (b : falsity_flag), list form -> option form -> form -> Type :=\n  | TContr {b} A phi psi : tsprv b A (Some phi) psi -> phi el A -> tsprv b A None psi\n  | TIR {b} A phi psi : tsprv b (phi :: A) None psi -> tsprv b A None (phi → psi)\n  | TAllR {b} A phi : tsprv b (map (subst_form ↑) A) None phi -> tsprv b A None (∀ phi)\n  | TAbsurd A phi : tsprv falsity_on A None ⊥ -> tsprv falsity_on A None phi\n  | TAx {b} A phi : tsprv b A (Some phi) phi\n  | TIL {b} A phi psi xi : tsprv b A None phi -> tsprv b A (Some psi) xi -> tsprv b A (Some (phi → psi)) xi\n  | TAllL {b} A phi t psi : tsprv b A (Some (phi[t..])) psi -> tsprv b A (Some (∀ phi)) psi.\n  Arguments tsprv {_} _ _ _.\n\n  Inductive tprv : forall (b : falsity_flag), list (form) -> form -> Type :=\n  | TII {b} A phi psi : tprv b (phi::A) psi -> tprv b A (phi → psi)\n  | TIE {b} A phi psi : tprv b A (phi → psi) -> tprv b A phi -> tprv b A psi\n  | TAllI {b} A phi : tprv b (map (subst_form ↑) A) phi -> tprv b A (∀ phi)\n  | TAllE {b} A t phi : tprv b A (∀ phi) -> tprv b A (phi [t..])\n  | TExp A phi : tprv falsity_on A ⊥ -> tprv falsity_on A phi\n  | TCtx {b} A phi : phi el A -> tprv b A phi.\n  Arguments tprv {_} _ _.\n\n  Definition not_II {b : falsity_flag} {A} {phi} (p : tprv A phi) : Prop :=\n    match p with\n    | (TII _ _ _ p') => False\n    | (TAllI _ _ p') => True\n    | (TAllE _ _ _ p') => True\n    | (TExp _ _ p') => True\n    | (TIE _ _ _ p' p'') => True\n    | (TCtx _ _ _) => True\n    end.\n\n  Definition not_AllI {b : falsity_flag} {A} {phi} (p : tprv A phi) : Prop :=\n    match p with\n    | (TII _ _ _ p') => True\n    | (TAllI _ _ p') => False\n    | (TAllE _ _ _ p') => True\n    | (TExp _ _ p') => True\n    | (TIE _ _ _ p' p'') => True\n    | (TCtx _ _ _) => True\n    end.\n\n  Fixpoint normal {b : falsity_flag} {A} {phi} (p : tprv A phi) : Prop :=\n    match p with\n    | (TII _ _ _ p') => normal p'\n    | (TIE _ _ _ p' p'') => normal p' /\\ normal p'' /\\ not_II p'\n    | (TAllI _ _ p') => normal p'\n    | (TAllE _ _ _ p') => normal p' /\\ not_AllI p'\n    | (TExp _ _ p') => normal p'\n    | (TCtx _ _ _) => True\n    end.\n\n  Section CutElimination.\n    Context {b : falsity_flag}.\n\n    Definition embed A phi psi :=\n      match phi with\n      | Some phi' => @prv _ _ _ intu A phi' -> @prv _ _ _ intu A psi\n      | None => @prv _ _ _ intu A psi\n      end.\n\n    Lemma seq_ND A phi psi :\n      sprv A phi psi -> embed A phi psi.\n    Proof.\n      unfold embed; induction 1; cbn in *.\n      - refine (IHsprv (Ctx H0)).\n      - refine (II IHsprv).\n      - refine (AllI IHsprv).\n      - refine (Exp phi IHsprv).\n      - tauto.\n      - intros. refine (IHsprv2 (IE H1 IHsprv1)).\n      - intros. refine (IHsprv (AllE t H0)).\n    Qed.\n\n    Lemma seq_ND_T T phi :\n      stprv T phi -> @FragmentND.tprv _ _ b intu T phi.\n    Proof.\n      intros (A & HA1 & HA2). apply seq_ND in HA2. now use_theory A.\n    Qed.\n\n    Definition tembed A phi psi :=\n      match phi with\n      | Some phi' => forall (p : tprv A phi'), not_AllI p /\\ not_II p /\\ normal p -> exists (p' : tprv A psi), normal p'\n      | None => exists (p : tprv A psi), normal p\n      end.\n\n    Lemma cutfree_seq_ND A phi psi :\n      tsprv A phi psi -> tembed A phi psi.\n    Proof with try split; cbn in *; unfold not_II, not_AllI in *; try tauto.\n      unfold tembed; induction 1; cbn in *.\n      - apply (IHX (TCtx _ _ i))...\n      - destruct IHX. exists (TII _ _ _ x)...\n      - destruct IHX. exists (TAllI _ _ x)...\n      - destruct IHX. exists (TExp _ phi x)...\n      - firstorder.\n      - intros. destruct IHX1. eapply (IHX2 (TIE _ _ _ p x))...\n      - intros. apply (IHX (TAllE _ t _ p))...\n    Qed.\n  End CutElimination.\n\n  Section Soundness.\n    Context {b : falsity_flag}.\n\n    Lemma ksoundness_seq A (phi : form) :\n      @sprv _ _ _ A None phi  -> kvalid_ctx A phi.\n    Proof.\n      intros Hprv % seq_ND. now apply ksoundness.\n    Qed.\n  End Soundness.\n\n  (* **** Enumerability of Sequents *)\n  Section Enumerability.\n  Variable list_Funcs : nat -> list syms.\n  Hypothesis enum_Funcs' : list_enumerator__T list_Funcs syms.\n\n  Variable list_Preds : nat -> list preds.\n  Hypothesis enum_Preds' : list_enumerator__T list_Preds preds.\n\n  Hypothesis eq_dec_Funcs : eq_dec syms.\n  Hypothesis eq_dec_Preds : eq_dec preds.\n\n  Instance eqdec_binop : eq_dec binop.\n  Proof.\n    intros x y. unfold dec. decide equality.\n  Qed.\n\n  Instance eqdec_quantop : eq_dec quantop.\n  Proof.\n    intros x y. unfold dec. decide equality.\n  Qed.\n\n  Definition list_binop (n : nat) := [Impl].\n\n  Instance enum_binop :\n    list_enumerator__T list_binop binop.\n  Proof.\n    intros []; exists 0; cbn; tauto.\n  Qed.\n\n  Definition list_quantop (n : nat) := [All].\n\n  Instance enum_quantop :\n    list_enumerator__T list_quantop quantop.\n  Proof.\n    intros []; exists 0; cbn; tauto.\n  Qed.\n\n  Lemma enumT_binop :\n    enumerable__T binop.\n  Proof.\n    apply enum_enumT. exists list_binop. apply enum_binop.\n  Qed.\n\n  Lemma enumT_quantop :\n    enumerable__T quantop.\n  Proof.\n    apply enum_enumT. exists list_quantop. apply enum_quantop.\n  Qed.\n\n  Instance enum_term' :\n    list_enumerator__T (L_term _) term :=\n    enum_term _.\n\n  Instance enum_form' {ff : falsity_flag} :\n    list_enumerator__T (L_form _ _ _ _) form :=\n    enum_form _ _ _ _.\n  Fixpoint L_seq {b : falsity_flag} (A : list form) (psi : option form) (n : nat) : list form :=\n    match n with\n    | 0 => match psi with Some psi => [psi] | None => A end\n    | S n => L_seq A psi n ++\n                  match psi with\n     (* Contr *)  | None => concat ([ L_seq A (Some psi) n | psi ∈ A]) ++\n     (* IR *)               concat ([ [ phi → psi | psi ∈ L_seq (phi :: A) None n ] | phi ∈ L_T form n]) ++\n     (* AllR *)             [ ∀ phi | phi ∈ L_seq ([ psi[↑] | psi ∈ A]) None n ] ++\n     (* Absurd *)           ((if b as ff return list (@form _ _ _ ff) -> list (@form _ _ _ ff)\n                              then fun _ => [] else fun A => [ phi | phi ∈ L_T form n, ⊥ el L_seq A None n ]) A)\n                  | Some psi' => match psi' in @form _ _ _ ff return list (@form _ _ _ ff) -> list (@form _ _ _ ff) with\n     (* IL *)         | @bin _ _ _ ff Impl phi psi => fun A => [ xi | xi ∈ L_seq A (Some psi) n, phi el @L_seq ff A None n ]\n     (* AllL *)       | quant All psi => fun A => concat ([ [phi | phi ∈ L_seq A (Some psi[t..]) n ] | t ∈ L_T term n])\n                      | _ => fun _ => [] end A\n                  end\n    end.\n\n    Opaque in_dec.\n\n    Lemma enum_sprv {b : falsity_flag} A psi : list_enumerator (L_seq A psi) (sprv A psi).\n    Proof with try (eapply cum_ge'; eauto; lia).\n      repeat split.\n      - rename x into phi. induction 1; try congruence; subst.\n        + destruct IHsprv as [m]. exists (S m). cbn. in_app 2.\n          eapply in_concat_iff. eexists. split. 2: in_collect phi... all: eauto.\n        + destruct IHsprv as [m1], (el_T phi) as [m2]. exists (1 + m1 + m2). cbn. in_app 3.\n          eapply in_concat_iff. eexists. split. 2: in_collect phi... in_collect psi...\n        + destruct IHsprv as [m]. exists (S m). cbn. in_app 4. in_collect phi...\n        + destruct IHsprv as [m1], (el_T phi) as [m2]. exists (1 + m1 + m2). cbn. in_app 5. in_collect phi...\n        + exists 0. now left.\n        + destruct IHsprv1 as [m1], IHsprv2 as [m2]. exists (1 + m1 + m2). cbn. in_app 2. in_collect xi...\n        + destruct IHsprv as [m1], (el_T t) as [m2]. exists (1 + m1 + m2). cbn. in_app 2. eapply in_concat_iff.\n          eexists. split. 2: in_collect t... in_collect psi...\n      - intros [m]. induction m in A, psi, x, H |-*; destruct psi; cbn in *.\n        + destruct H as [-> | []]. apply Ax.\n        + eauto.\n        + destruct f as [|b P v|b [] phi psi|b [] phi]; inv_collect; eauto.\n        + destruct b; inv_collect; eauto.\n    Qed.\n\n    Fixpoint L_tseq {b : falsity_flag} (L : nat -> list form) (n : nat) : list form :=\n      match n with\n      | 0 => nil\n      | S n => L_tseq L n ++ concat ([ L_seq A None n | A ∈ L_con L n ])\n      end.\n\n    Lemma enum_stprv {b : falsity_flag} T L : list_enumerator L T -> cumulative L -> list_enumerator (L_tseq L) (stprv T).\n    Proof with try (eapply cum_ge'; eauto; lia).\n      intros He Hcml psi. repeat split.\n      - intros (A & [m1] % (enum_el (enum_containsL Hcml He)) & [m2] % (enum_el (enum_sprv A None))).\n        exists (1 + (m1 + m2)). cbn. in_app 2. eapply in_concat_iff. eexists. split. 2: in_collect A... idtac...\n      - intros [m]. induction m in psi, H |-*; cbn in *. 1: contradiction. inv_collect. exists x0. split.\n        + eapply (enum_p (enum_containsL Hcml He)); eassumption.\n        + eapply (enum_p (enum_sprv x0 None)); eassumption.\n    Qed.\n  End Enumerability.\nEnd Gentzen.\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/FOL/Deduction/FragmentSequentFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.2920626789105918}}
{"text": "(** * EqTh.v: decision procedures for determining program equivalence,\n e.g. dead code, code movement, semantic equivalence *)\n\nSet Implicit Arguments.\n\nRequire Export While_loop.\nRequire Export NotModifyDec.\n\n\nModule Make (Sem:SEM).\n \n Module NM_dec := NotModifyDec.Make Sem.\n Export NM_dec.\n\n Section EQOBS.\n\n Variable n : positive.\n Variable E : env.\n Variable pi : eq_refl_info E.\n\n (* [needed_args lv arg needed res] computes a set [I] such that [res [<=] I] \n     and [EqObs_args lv arg arg needed I] *)\n\n Definition needed_args ltv1 (lv1:var_decl ltv1) \n  lt1 (la1:E.args lt1) ltv2 (lv2:var_decl ltv2) lt2 (la2:E.args lt2)\n  (needed:Vset.t) (res:Vset.t) :=\n  Vset.fold (fun x r => \n   match r, get_arg x lv1 la1, get_arg x lv2 la2 with\n   | Some r, Some a1, Some a2 =>\n     if E.eqb a1 a2 then Some (fv_expr_extend a1 r)\n     else None\n   | _, _, _ => None\n   end) needed (Some res).\n \n Definition needed_args_refl ltv (lv:var_decl ltv) lt (la:E.args lt) \n  (needed:Vset.t) (res:Vset.t) :=\n  Vset.fold (fun x r =>\n   match r, get_arg x lv la with\n   | Some r, Some a => Some (fv_expr_extend a r)\n   | _, _ => None\n   end) needed (Some res).\n \n Lemma needed_args_correct : \n  forall needed ltv1 (lv1:var_decl ltv1) lt1 (la1:E.args lt1) \n   ltv2 (lv2:var_decl ltv2) lt2 (la2:E.args lt2)\n   res I,\n   needed_args lv1 la1 lv2 la2 needed res = Some I ->\n   EqObs_args lv1 la1 lv2 la2 needed I /\\ res [<=] I.\n Proof.\n  intros needed ltv1 lv1 lt1 la1 ltv2 lv2 lt2 la2 res I; unfold EqObs_args.\n  assert (forall (L:list Var.t), fold_left (fun r (x:Var.t) => \n   match r, get_arg x lv1 la1, get_arg x lv2 la2 with\n   | Some r, Some a1, Some a2 =>\n     if E.eqb a1 a2 then Some (fv_expr_extend a1 r)\n     else None  \n   | _, _, _ => None\n   end) L None = None).\n  induction L; simpl; intros; auto.\n  assert (forall L R I, \n   fold_left (fun r (x:Var.t) => \n    match r, get_arg x lv1 la1, get_arg x lv2 la2 with\n    | Some r, Some a1, Some a2 =>\n     if E.eqb a1 a2 then Some (fv_expr_extend a1 r)\n      else None  \n    | _, _, _ => None\n    end) L (Some R)  = Some I ->\n   (forall x,\n    InA (@eq _) x L ->\n    match get_arg x lv1 la1 with\n    | Some e1 =>\n     match get_arg x lv2 la2 with\n     | Some e2 => EqObs_e I e1 e2\n     | None => False\n     end\n    | None => False\n     end) /\\ R[<=]I).\n  rename H into ZZ. induction L; simpl; intros; auto.\n  inversion_clear H; split; auto with set.\n  intros x H; inversion H.\n  case_eq (get_arg a lv1 la1); intros.\n  case_eq (get_arg a lv2 la2); intros.\n  rewrite H0 in H; rewrite H1 in H.\n  assert (W:=E.eqb_spec e e0); destruct (E.eqb e e0); subst.\n  destruct (IHL _ _ H); split; intros.\n  inversion H4; clear H4; subst; auto.\n  rewrite H0; rewrite H1. \n  apply EqObs_e_strengthen with (fv_expr e0); trivial.\n  apply VsetP.subset_trans with (2:= H3).\n  rewrite union_fv_expr_spec; auto with set.\n  apply H2; auto.\n  apply VsetP.subset_trans with (2:= H3).\n  rewrite union_fv_expr_spec; auto with set.\n  rewrite ZZ in H; discriminate.\n  rewrite H0 in H; rewrite H1 in H; rewrite ZZ in H; discriminate.\n  rewrite H0 in H; rewrite ZZ in H; discriminate.\n  \n  unfold needed_args; rewrite Vset.fold_spec; intros V.\n  destruct (H0 _ _ _ V); split; auto.\n  intros; apply (H1 x); apply Vset.elements_correct; trivial.\n Qed.\n\n Lemma needed_args_refl_spec : forall needed\n  ltv (lv:var_decl ltv) lt (la:E.args lt) res,\n  needed_args_refl lv la needed res =\n  needed_args lv la lv la needed res.\n Proof.\n  unfold needed_args_refl, needed_args; intros; repeat rewrite Vset.fold_spec.\n  generalize (Vset.elements needed) (Some res).\n  induction l; simpl; intros; trivial.\n  match goal with\n   |- fold_left _ l ?o1 = fold_left _ l ?o2 =>\n    assert (Heq : o1 = o2);[ | rewrite Heq; trivial] end.\n  destruct o; trivial.\n  destruct (get_arg a lv la); trivial.\n  generalize (E.eqb_spec e e); destruct (E.eqb e e); trivial.\n  intro Hd; elim Hd; trivial.\n Qed.\n\n Lemma needed_args_refl_correct : forall needed \n  ltv (lv:var_decl ltv) lt (la:E.args lt) res I,\n  needed_args_refl lv la needed res = Some I ->\n  EqObs_args lv la lv la needed I /\\ res [<=] I.\n Proof.\n  intros needed ltv lv lt la res I; rewrite needed_args_refl_spec; apply\n   needed_args_correct.\n Qed.\n\n (* [eqobs_in_I i O] computes a set [I] such that [EqObs_i I i i O] *)\n \n Definition eqobs_in_b (i:I.baseInstr) O :=\n  match i with\n  | I.Assign t x e =>\n    if Vset.mem x O then fv_expr_extend e (Vset.remove x O)\n    else O\n  | I.Random t x e => \n    if Vset.mem x O then Vset.union (fv_distr e) (Vset.remove x O)\n    else O\n  | I.IAssert e => O\n  end.\n\n Definition is_lossless_nm O c := \n  if is_lossless pi c then is_notmodify pi O c else false.\n \n Definition is_lossless_nm_i O i := \n  if is_lossless_i pi i then is_notmodify_i pi O i else false.\n \n Lemma is_lossless_nm_spec : forall O c,\n  is_lossless_nm O c ->\n  lossless E c /\\ exists X, Modify E X c /\\ Vset.disjoint O X.\n Proof.\n  unfold is_lossless_nm; intros O c.\n  generalize (is_lossless_correct pi c).\n  destruct (is_lossless pi c).\n  split; intros; auto.\n  apply is_notmodify_correct with (1:= H0).\n  intros; trivialb.\n Qed.\n \n Lemma is_lossless_nm_i_spec : forall O i,\n  is_lossless_nm_i O i ->\n  lossless E [i] /\\ \n  exists X, Modify E X [i] /\\ Vset.disjoint O X.\n Proof.\n  unfold is_lossless_nm_i; intros O i.\n  generalize (is_lossless_i_correct pi i);\n   destruct (is_lossless_i pi i).\n  split; intros; auto.\n  apply is_notmodify_i_correct with (1:= H0).\n  intros; trivialb.\n Qed.\n \n Fixpoint eqobs_in_i (i:I.instr) (O:Vset.t) {struct i} : option Vset.t :=\n  match i with\n  | I.Instr ib =>\n    match ib with\n    | I.Assign _ _ _ => Some (eqobs_in_b ib O)\n    | I.Random _ _ _ => Some (eqobs_in_b ib O)\n    | I.IAssert _ => None\n    end\n  | I.Cond e c1 c2 =>\n    let oI1 := List.fold_right (fun i => opt_app (eqobs_in_i i)) (Some O) c1 in\n    let oI2 := List.fold_right (fun i => opt_app (eqobs_in_i i)) (Some O) c2 in\n     match oI1, oI2 with\n     | Some I1, Some I2 => \n       let test :=\n        if Vset.eqb I1 O then\n         if Vset.eqb I2 O then\n          if is_lossless_nm O c1 then is_lossless_nm O c2 \n           else false\n          else false\n         else false\n        in if test then Some O else Some (fv_expr_extend e (Vset.union I1 I2))\n     | _, _ => None\n     end\n  | I.While e c =>\n    let loop O :=     \n    let oI := List.fold_right (fun i => opt_app (eqobs_in_i i)) (Some O) c in\n     match oI with\n     | Some II => \n       if II [<=?] O then Result Vset.t (Some O)\n       else Continue (option Vset.t) (Vset.union II O)\n     | None => Result Vset.t None\n     end in\n     let Oe := fv_expr_extend e O in\n      match While_loop.while loop n Oe with\n      | Continue _ => None\n      | Result r => r\n      end\n  | I.Call t d f arg =>\n    if is_lossless_nm_i O i then Some O else \n     let lv := proc_params E f in\n      match pi f with\n      | Some pif =>\n        let fout := Vset.add d (pi_output pif) in\n        let other := Vset.diff O fout in\n         if Vset.disjoint other  (pi_mod pif) then \n          let gif := Vset.union (pi_input pif) other in\n           match needed_args_refl lv arg (pi_params pif) gif with\n           | None => None\n           | Some Ifun => Some Ifun\n           end\n          else None\n      | _ => None\n      end\n  end.\n \n  (* [eqobsinv_in i O] compute the smallest [I] such that [Eqobsinv_i I i i O] *)\n Definition eqobs_in c O := \n  List.fold_right (fun i => opt_app (eqobs_in_i i)) (Some O) c.\n \n Lemma EqObs_lossless_Modify : forall X M1 M2 E1 c1 E2 c2,\n  lossless E1 c1 ->\n  lossless E2 c2 ->\n  Modify E1 M1 c1 ->\n  Modify E2 M2 c2 ->\n  Vset.disjoint X M1 ->\n  Vset.disjoint X M2 ->\n  EqObs X E1 c1 E2 c2 X.\n Proof.\n  unfold EqObs; intros.\n  apply equiv_lossless_Modify with X X M1 M2; trivial.\n Qed.\n\n (* REMARK: decMR can be weakened, P has to be decidable only if m1 =={I} m2 *)\n Lemma equiv_union_Modify : forall E1 c1 E2 c2 I P X1 X2 O Q,\n  Modify E1 X1 c1 /\\ Modify E2 X2 c2 ->\n  decMR P ->\n  equiv (req_mem_rel I P) E1 c1 E2 c2 \n  (req_mem_rel (Vset.diff O (Vset.diff I (Vset.union X1 X2))) Q) -> \n  equiv (req_mem_rel I P) E1 c1 E2 c2 (req_mem_rel O Q).\n Proof.\n  intros; destruct H.  \n  apply equiv_union_Modify_pre2 with \n   (P1:= fun _ _ => True) (P2:= fun _ _ => True)\n   (X1:=X1) (X2:=X2) \n   (Q:=req_mem_rel (Vset.diff O (Vset.diff I (Vset.union X1 X2))) Q); auto.  \n  unfold req_mem_rel, kreq_mem; intros k m1 m2 m1' m2' [W1 W2] [W3 W4]; split.\n  intros t x Hx.\n  destruct (VsetP.mem_dec x (Vset.diff I (Vset.union X1 X2))).\n  rewrite VsetP.diff_spec, VsetP.union_spec in i; destruct i.\n  rewrite <- H2; try tauto.\n  rewrite <- H3; auto; try tauto.\n  apply W3; auto with set.\n  trivial. \n  apply Modify_Modify_pre; auto.\n  apply Modify_Modify_pre; auto.\n Qed.\n\n Lemma equiv_union_Modify_Meq : forall E1 c1 E2 c2 P X1 X2,\n  Modify E1 X1 c1 /\\ Modify E2 X2 c2 ->\n  implMR P Meq ->\n  equiv P E1 c1 E2 c2 (kreq_mem (Vset.union X1 X2)) ->\n  equiv P E1 c1 E2 c2 Meq.\n Proof.\n  intros; destruct H.\n  apply equiv_union_Modify_pre with\n   (P1:=fun _ _ => True) (P2:=fun _ _ => True)\n   (X1:=Vset.union X1 X2) (X2:=Vset.union X1 X2) \n   (Q:=kreq_mem (Vset.union X1 X2)); auto.\n  intros.\n  assert (W := H0 k m1 m2 H3).\n  unfold Meq in *; subst.\n  apply req_mem_eq; trivial.\n  apply Modify_Modify_pre; apply Modify_weaken with (1:= H); auto with set.\n  apply Modify_Modify_pre; apply Modify_weaken with (1:= H2); auto with set.\n Qed.\n \n Lemma equiv_union_Modify_Meq_and : forall E1 c1 E2 c2 P X1 X2 Q Y1 Y2,\n  depend_only_rel Q Y1 Y2 ->\n  Modify E1 X1 c1 /\\ Modify E2 X2 c2 ->\n  implMR P Meq ->\n  equiv P E1 c1 E2 c2 \n  (req_mem_rel (Vset.union (Vset.union X1 X2) (Vset.union Y1 Y2)) Q) ->\n  equiv P E1 c1 E2 c2 (Meq /-\\ Q).\n Proof.\n  intros; set (X:= Vset.union (Vset.union X1 X2) (Vset.union Y1 Y2)).\n  destruct H0.\n  intros; apply equiv_union_Modify_pre with\n   (P1 := fun _ _ => True) (P2 := fun _ _ => True)\n   (X1 := X) (X2 := X) \n   (Q:= req_mem_rel X Q); auto.\n  intros.\n  assert (W := H1 k m1 m2 H4).\n  destruct H5.\n  unfold Meq, andR in *; subst; split.\n  apply req_mem_eq; trivial.\n  apply (H k m1' m2').\n  apply req_mem_sym; apply req_mem_weaken with X;\n  [ unfold X; auto with set | apply req_mem_update_mem_l].\n  apply req_mem_sym; apply req_mem_weaken with X;\n  [ unfold X; auto with set | apply req_mem_update_mem_l].\n  trivial.\n  apply Modify_Modify_pre; apply Modify_weaken with (1:= H0); \n   unfold X; auto with set.\n  apply Modify_Modify_pre; apply Modify_weaken with (1:= H3); \n   unfold X; auto with set.\n Qed.\n\n Lemma EqObs_union_Modify : forall E1 c1 E2 c2 I X1 X2 O,\n  Modify E1 X1 c1 /\\ Modify E2 X2 c2 ->\n  EqObs I E1 c1 E2 c2 (Vset.diff O (Vset.diff I (Vset.union X1 X2))) -> \n  EqObs I E1 c1 E2 c2 O.\n Proof.\n  unfold EqObs;intros.\n  apply equiv_weaken with (req_mem_rel O trueR);\n   [unfold req_mem_rel, andR;intuition |].\n  apply equiv_strengthen with (req_mem_rel I trueR);\n   [unfold req_mem_rel, andR, trueR;intuition|].\n  eapply equiv_union_Modify; eauto.\n  eapply equiv_weaken;[ | eapply equiv_strengthen;[ | apply H0] ];\n  unfold req_mem_rel, andR, trueR;intuition.\n Qed.\n\n Lemma disjoint_singleton : forall v O,\n  Vset.mem v O = false ->\n  Vset.disjoint O (Vset.singleton v).\n Proof.\n  unfold Vset.disjoint; intros.\n  change (Vset.inter O (Vset.singleton v) [=] Vset.empty).\n  rewrite VsetP.eq_spec; split; auto with set.\n  apply Vset.subset_complete; intro.\n  rewrite VsetP.inter_spec; intros (H1, H2).\n  assert (v = x).\n  apply (Vset.singleton_complete _ _ H2). \n  subst; rewrite H in H1; trivialb.\n Qed.\n\n Lemma disjoint_union : forall I X1 X2,\n  Vset.disjoint I X1 -> Vset.disjoint I X2 -> Vset.disjoint I (Vset.union X1 X2).\n Proof.\n  unfold Vset.disjoint; intros.\n  change  (Vset.inter I (Vset.union X1 X2) [=] Vset.empty).\n  rewrite VsetP.inter_union_comm; rewrite (H :Vset.inter I X1 [=] Vset.empty).\n  rewrite (H0 :Vset.inter I X2 [=] Vset.empty).\n  auto with set.\n Qed.\n\n Lemma eqobs_in_b_assign : forall t (v:Var.var t) e O,\n  EqObs (eqobs_in_b (I.Assign v e) O) E [v <- e] E [v <- e] O.\n Proof.\n  unfold EqObs; intros; simpl.\n  case_eq (Vset.mem v O); intros.\n  eapply equiv_strengthen; [ | apply equiv_assign].\n  unfold kreq_mem; intros; simpl.\n  red; apply req_mem_weaken with (Vset.add v (Vset.remove v O)).\n  rewrite VsetP.add_remove; auto with set.\n  rewrite union_fv_expr_spec in H0.\n  rewrite (@EqObs_e_fv_expr t e k m1 m2).\n  apply req_mem_update.\n  apply req_mem_weaken with (2:= H0); auto with set.\n  apply req_mem_weaken with (2:= H0); auto with set.\n  fold (EqObs O E [v<-e] E [v<-e] O).\n  apply EqObs_lossless_Modify with (Vset.singleton v) (Vset.singleton v);\n   auto using lossless_assign,Modify_assign,disjoint_singleton.\n Qed.\n\n Lemma eqobs_in_b_random : forall t (v:Var.var t) (d:DE.support t) O,\n  EqObs (eqobs_in_b (I.Random v d) O) E [v <$- d] E [v <$- d] O.\n Proof.\n  unfold EqObs; intros; simpl.\n  case_eq (Vset.mem v O); intros.\n  eapply equiv_strengthen;[ | apply equiv_random].\n  unfold kreq_mem; intros; simpl.\n  split; unfold eq_support.\n  apply EqObs_d_fv_expr.\n  apply req_mem_weaken with (2:= H0); auto with set.\n  red; intros; apply req_mem_weaken with (Vset.add v (Vset.remove v O)).\n  rewrite VsetP.add_remove; auto with set.\n  apply req_mem_update.\n  apply req_mem_weaken with (2:= H0); auto with set.\n  fold (EqObs O E [v <$- d] E [v <$- d] O).\n  apply EqObs_lossless_Modify with (Vset.singleton v) (Vset.singleton v);\n   auto using lossless_random,Modify_random,disjoint_singleton.\n Qed.\n \n \n Section WHILE.\n  \n  Variable c : cmd.\n\n  Hypothesis eqobs_in_correct :  \n   forall I O, eqobs_in c O = Some I -> EqObs I E c E c O.\n  \n  Lemma eqobs_in_while : forall b O I,\n   eqobs_in_i (while b do c) O = Some I ->\n   Vset.union O (fv_expr b) [<=]  I /\\ EqObs I E c E c I.\n  Proof.\n   simpl; intros.\n   set (P1 := fun X => (Vset.union O (fv_expr b) [<=] X)).\n   set (P2 := fun res =>\n    match res with\n    | Continue X => P1 X\n    | Result None => True\n    | Result (Some X) => Vset.union O (fv_expr b) [<=] X /\\  EqObs X E c E c X\n    end).\n   match type of H with\n   | match ?t with\n     | Result _ => _ \n     | Continue _ => _ \n     end = _ => cut (P2 t); [destruct t; try discriminate|]\n   end.\n   subst; trivial.\n   apply while_P with P1; intros.\n   unfold P1 in *; generalize (fun I => @eqobs_in_correct I a); clear P1; intros.\n   unfold eqobs_in in H1.\n   destruct (fold_right (fun i => opt_app (eqobs_in_i i)) (Some a) c).\n   assert (U:=H1 t (refl_equal _)); clear H1.\n   case_eq (t [<=?] a); intros; simpl.\n   change (t [<=] a) in H1; split; auto.\n   red; apply equiv_strengthen with (2:= U).\n   unfold kreq_mem; intros; apply req_mem_weaken with (1:= H1); trivial.\n   apply VsetP.subset_trans with a; auto with set.\n   simpl; trivial.\n   exact H0.\n   unfold P1; rewrite union_fv_expr_spec; rewrite VsetP.union_sym; auto with set.\n  Qed.\n\n End WHILE.\n \n Lemma eqobs_in_aux : \n  (forall i I O, eqobs_in_i i O = Some I -> EqObs I E [i] E [i] O) /\\\n  (forall c I O, eqobs_in c O = Some I -> EqObs I E c E c O).\n Proof.\n   unfold eqobs_in, EqObs; apply I.cmd_ind2; simpl; intros.\n \n   (* baseInstr *)\n   destruct i; inversion_clear H.\n   apply eqobs_in_b_assign.\n   apply eqobs_in_b_random. \n\n   (* Cond *)\n   generalize (fun I => H I O) (fun I => H0 I O); clear H H0;\n    destruct (fold_right (fun i => opt_app (eqobs_in_i i)) (Some O) c1);\n     try discriminate.\n   destruct (fold_right (fun i => opt_app (eqobs_in_i i)) (Some O) c2);\n     try (intros; discriminate).\n   intros H H0;\n   match type of H1 with (if ?test then _ else _) = _ =>\n    generalize H1; clear H1; case_eq test;\n     intros Heq H1; inversion H1; clear H1; subst \n   end.\n   destruct (Vset.eqb t I); try discriminate.\n   destruct (Vset.eqb t0 I); try discriminate.\n   case_eq (is_lossless_nm I c1);\n   intros H1; rewrite H1 in Heq; try discriminate Heq.\n   destruct (is_lossless_nm_spec I c1 H1) as (H2, (X1,(H3,H4))).\n   destruct (is_lossless_nm_spec I c2 Heq) as (H5, (X2,(H6,H7))).\n   assert (lossless E [If b then c1 else c2]) by (apply lossless_cond; trivial).\n   assert (Modify E (Vset.union X1 X2) [If b then c1 else c2]).\n     apply Modify_cond; trivial.\n   change (EqObs I E [If b then c1 else c2] E [If b then c1 else c2] I).\n   apply EqObs_lossless_Modify with (Vset.union X1 X2) (Vset.union X1 X2);\n    auto using disjoint_union.\n   clear Heq.\n   apply equiv_cond.\n   apply equiv_strengthen with (kreq_mem t); auto.\n   unfold kreq_mem; intros k m1 m2 (H1, _); rewrite union_fv_expr_spec in H1;\n   apply req_mem_weaken with (2:= H1); auto with set.\n   apply equiv_strengthen with (kreq_mem t0); auto.\n   unfold kreq_mem; intros k m1 m2 (H1, _); rewrite union_fv_expr_spec in H1;\n   apply req_mem_weaken with (2:= H1); auto with set.\n   unfold kreq_mem; intros; assert (EqObs_e (fv_expr b) b b).\n   apply EqObs_e_fv_expr.\n   apply H2.   \n   apply req_mem_weaken with (2:= H1); rewrite union_fv_expr_spec; auto with set.\n \n   (* While *)\n   destruct (eqobs_in_while H b O H0); clear H0.\n   eapply equiv_weaken;[ | apply equiv_while]; trivial.\n   unfold kreq_mem; intros k m1 m2 (H3, _); apply req_mem_weaken with I; trivial.\n   apply VsetP.subset_trans with (Vset.union O (fv_expr b)); auto with set.\n   unfold kreq_mem; intros; apply ((@EqObs_e_fv_expr _ b)).\n   apply req_mem_weaken with I; trivial.\n   apply VsetP.subset_trans with (Vset.union O (fv_expr b)); auto with set.\n   apply equiv_strengthen with (2:= H2).\n   intros k m1 m2 (H3,_); trivial. \n \n   (* Call *)\n   match type of H with\n   | (if ?test then _ else _) = _ =>\n     generalize H; clear H; case_eq test; intros Heq H;\n      inversion H; clear H; subst \n   end.\n   destruct (is_lossless_nm_i_spec _ _ Heq) as (H1, (X, (H2,H3))).\n   change (EqObs I E [x <c- f with a] E [x <c- f with a] I);\n     apply EqObs_lossless_Modify with X X; trivial.\n   clear Heq; destruct (pi f) as [pif | ]; try discriminate.\n   set (other:= Vset.diff O (Vset.add x (pi_output pif))) in *.\n   case_eq (Vset.disjoint other (pi_mod pif));\n    intros H2; rewrite H2 in H1; try discriminate.\n   generalize H1; clear H1.\n   case_eq (needed_args_refl \n    (proc_params E f) a (pi_params pif) (Vset.union (pi_input pif) other));\n   intros; try discriminate.\n   inversion H1; clear H1; subst.\n   destruct (needed_args_refl_correct _ _ _ _ H).\n   eapply equiv_weaken; [ | apply (pi_spec_call pif) ]; trivial.\n   unfold kreq_mem; intros; red; intros.\n   apply H3; destruct (VsetP.mem_dec x0 (Vset.add x (pi_output pif)));\n     auto with set.\n   rewrite VsetP.union_spec, VsetP.diff_spec; right.\n   assert (Vset.mem x0 other).\n     unfold other; rewrite VsetP.diff_spec; split; trivial.\n   split;[ apply Vset.subset_correct with (1:= H1); auto with set | ].\n   apply VsetP.disjoint_mem_not_mem with (1:= H2); trivial.\n   apply VsetP.subset_trans with (2:= H1); auto with set.\n \n   (* nil *)\n   inversion H; apply equiv_nil.\n   \n   (* cons *)\n   generalize (fun I => H0 I O); clear H0.\n   destruct (fold_right (fun i0 => opt_app (eqobs_in_i i0)) (Some O) c); \n    try discriminate.\n   intros H0; assert (U:= H0 t (refl_equal _)); clear H0.\n   assert (Ui := H _ _ H1).\n   apply equiv_cons with (1:= Ui); auto.\n  Qed.\n\n  Lemma eqobs_in_i_correct : forall i I O, \n   eqobs_in_i i O = Some I -> \n    EqObs I E [i] E [i] O.\n  Proof. \n   destruct eqobs_in_aux; trivial. \n  Qed.\n\n  Lemma eqobs_in_correct : forall c I O, \n   eqobs_in c O = Some I -> \n    EqObs I E c E c O.\n  Proof. \n   destruct eqobs_in_aux; trivial. \n  Qed.\n\n  Definition eqobs_in_subset I c O :=\n   match eqobs_in c O with\n   | Some I' => I' [<=?] I\n   | _ => false\n   end.\n\n  Lemma eqobs_in_subset_correct : forall I c O,\n   eqobs_in_subset I c O = true ->\n   EqObs I E c E c O.\n  Proof.\n   intros I c O; unfold eqobs_in_subset. \n   generalize (fun I => @eqobs_in_correct c I O).\n   destruct (eqobs_in c O); intros; try discriminate.\n   unfold EqObs ; apply equiv_strengthen with (2:= H _ (refl_equal _)). \n   unfold kreq_mem; intros; apply req_mem_weaken with I; auto.\n  Qed.\n\n\n (** Dead Code **)\n\n Section DEADCODE_AUX.\n   \n   Variable dead_code_i : I.t -> Vset.t -> option (Vset.t * cmd).\n\n   Fixpoint dead_code_aux (c:cmd) (O:Vset.t) {struct c} : option (Vset.t * cmd) :=\n    match c with\n    | nil => Some (O, nil)\n    | i::c1 =>\n      match dead_code_aux c1 O with\n      | Some (I1, c2) =>\n        match dead_code_i i I1 with\n        | Some (II, ci) => Some (II, ci++c2)\n        | _ => None\n        end\n      | _ => None\n      end\n    end.\n\n  End DEADCODE_AUX.\n \n  Fixpoint dead_code_i (i:I.t) (O:Vset.t) {struct i} : option (Vset.t * cmd) :=\n   match i with\n   | I.Instr ib =>\n     match ib with \n      | I.Assign _ _ _ \n      | I.Random _ _ _ =>\n        if is_notmodify_i pi O i then Some (O, nil)\n        else Some (eqobs_in_b ib O, [i])\n      | I.IAssert _ => None\n      end\n   | I.Cond e c1 c2 =>\n     if E.eqb e true then dead_code_aux dead_code_i c1 O\n     else if E.eqb e false then dead_code_aux dead_code_i c2 O\n     else \n     match dead_code_aux dead_code_i c1 O, dead_code_aux dead_code_i c2 O with\n     | Some (I1,c1'), Some (I2,c2') => \n        if I.ceqb c1' c2' then Some (Vset.union I1 I2, c1')\n        else \n         Some (Vset.union (fv_expr e) (Vset.union I1 I2), \n               [If e then c1' else c2'])\n     | _, _ => None\n     end\n   | I.While e c => \n     if E.eqb e false then Some (O,nil)\n     else \n      match eqobs_in_i i O with\n      | Some II => Some (II, [i])\n  (* Correct but hard to prove ....\n     match dead_code_aux dead_code_i c II with\n     | Some (_, c') => Some (II, [while e do c'])\n     | _ => None\n     end\n   *)\n      | None => None\n      end\n   | I.Call _ _ _ _ =>\n     if is_lossless_nm_i O i then Some (O, nil)\n     else \n      match eqobs_in_i i O with\n      | Some II => Some (II, [i])\n      | None => None\n      end\n   end.\n  \n  Lemma dead_code_aux_correct : \n   (forall i O I ci, \n    dead_code_i i O = Some (I,ci) -> EqObs I E [i] E ci O) /\\\n   (forall c O I cc,\n    dead_code_aux dead_code_i c O = Some (I, cc) -> EqObs I E c E cc O).\n  Proof.\n   unfold EqObs; apply I.cmd_ind2; simpl; intros.\n   \n   (* baseInstr *)\n   case_eq (is_notmodify_i pi O (I.Instr i)); destruct i.\n   intros Heq; rewrite Heq in H; inversion H; clear H; subst.\n   destruct (is_notmodify_i_correct _ _ _ Heq) as (X, (H1,H2)).\n   apply equiv_lossless_Modify with \n    (1:= @depend_only_kreq_mem I) (M1:=X) (M2:=X); trivial.\n   apply lossless_assign.\n   apply lossless_nil.\n   eapply Modify_weaken; [apply Modify_nil | auto with set].\n  \n   intros Heq; rewrite Heq in H; inversion H; clear H; subst.\n   destruct (is_notmodify_i_correct _ _ _ Heq) as (X, (H1,H2)).\n   apply equiv_lossless_Modify with \n    (1:= @depend_only_kreq_mem I) (M1:=X) (M2:=X); trivial.\n   apply lossless_random.\n   apply lossless_nil.\n   eapply Modify_weaken; [apply Modify_nil | auto with set].\n   \n   discriminate.\n\n   intros Heq; rewrite Heq in H; inversion H; clear H; subst.\n   apply eqobs_in_b_assign.\n\n   intros Heq; rewrite Heq in H; inversion H; clear H; subst.\n   apply eqobs_in_b_random.\n\n   discriminate.\n\n   (* Cond *)\n   generalize H1; clear H1.\n   assert (W:=E.eqb_spec b true); destruct (E.eqb b true); subst; intros.\n   apply equiv_cond_l; simplMR; auto.\n   clear W; assert (W:=E.eqb_spec b false); destruct (E.eqb b false); subst; intros.\n   apply equiv_cond_l; simplMR; auto.\n   generalize (H O) (H0 O); clear W H H0;\n   destruct (dead_code_aux dead_code_i c1 O); try discriminate.\n   destruct (dead_code_aux dead_code_i c2 O); try discriminate.\n   intros.\n   destruct p as (I1, c1'); destruct p0 as (I2, c2').\n   assert (W:= I.ceqb_spec c1' c2'); destruct (I.ceqb c1' c2'); intros;\n   inversion H1; clear H1; subst; subst.\n   apply equiv_cond_l.\n   rewrite proj1_MR, <- VsetP.subset_union_l; auto.\n   rewrite proj1_MR, <- VsetP.subset_union_r; auto.\n   apply equiv_cond.\n   rewrite proj1_MR, <- VsetP.subset_union_r, <- VsetP.subset_union_l; auto.\n   rewrite proj1_MR, <- VsetP.subset_union_r, <- VsetP.subset_union_r; auto.\n   unfold kreq_mem; intros; apply ((@EqObs_e_fv_expr _ b)).\n   apply req_mem_weaken with (2:= H1); auto with set.\n   destruct p; discriminate.\n\n   (* While *)\n   change ((if E.eqb b false then Some (O, nil) \n                 else match (eqobs_in_i (while b do c) O) with\n                 | Some II => Some (II, [while b do c])\n                 | None => None (A:=Vset.t * cmd)\n                end) = Some (I, ci)) in H0.\n   assert (W:=E.eqb_spec b false); destruct (E.eqb b false); subst; intros;\n   inversion H0; clear H0; subst.\n   apply equiv_lossless_Modify with (1:=@depend_only_kreq_mem I) (M1:=Vset.empty)\n     (M2:=Vset.empty).\n   unfold lossless; intros.\n   rewrite (eq_distr_elim (deno_while E false c m)).\n   rewrite deno_cond_elim.\n   simpl. rewrite (@deno_nil_elim k); trivial.\n   apply lossless_nil.\n   unfold Modify,range; intros.\n   rewrite (eq_distr_elim (deno_while E false c m)).\n   rewrite deno_cond_elim.\n   simpl; rewrite (@deno_nil_elim k).\n   apply H0; red; trivial.\n   apply Modify_nil. \n   change (Vset.inter I Vset.empty [=] Vset.empty); auto with set.\n   change (Vset.inter I Vset.empty [=] Vset.empty); auto with set.\n   case_eq (eqobs_in_i (while b do c) O); intros.\n   assert (W1:=eqobs_in_i_correct _ _ H0).\n   simpl in H0; rewrite H0 in H2; clear H0; inversion H2; clear H2; subst; trivial.\n   simpl in H0; rewrite H0 in H2; discriminate H2.\n   (* Call *)\n   match type of H with\n   | (if ?test then _ else _) = _ =>\n     case_eq test; intros Heq; rewrite Heq in H end.\n   destruct (is_lossless_nm_i_spec _ _ Heq) as (H1, (X, (H2, H3))).\n   inversion H; clear H; subst.\n   apply equiv_lossless_Modify with \n    (1:=@depend_only_kreq_mem I) (M1:=X) (M2:=Vset.empty); trivial.\n   apply lossless_nil. \n   apply Modify_nil.\n   change (Vset.inter I Vset.empty [=] Vset.empty); auto with set.\n   case_eq (eqobs_in_i (x <c- f with a) O); intros.\n   assert (W:=eqobs_in_i_correct _ _ H0).\n   simpl in H0; rewrite Heq in H0; rewrite H0 in H; clear Heq H0.\n   inversion H; clear H; subst; trivial.\n   simpl in H0; rewrite Heq in H0; rewrite H0 in H; discriminate.\n   (* nil *)\n   inversion H.\n   apply equiv_nil.\n   (* cons *)\n   generalize (H0 O); clear H0.\n   destruct (dead_code_aux dead_code_i c O); try discriminate.\n   destruct p as (I1,c2); generalize (H I1); clear H;\n    destruct (dead_code_i i I1); try discriminate.\n   destruct p; inversion H1; clear H1; subst; intros.\n   change (i::c) with ([i]++c); apply equiv_app with \n    (1:= H _ _ (refl_equal _)); auto.\n  Qed.\n\n  Definition dead_code c O := \n   match dead_code_aux dead_code_i c O with\n   | Some (_, c') => Some c'\n   | _ => None\n   end.\n\n  Lemma dead_code_correct : forall c O c', \n   dead_code c O = Some c' -> equiv Meq E c E c' (kreq_mem O).\n  Proof. \n   intros c O c'; destruct dead_code_aux_correct as (_, H); unfold dead_code.\n   generalize (H c O); clear H.\n   destruct (dead_code_aux dead_code_i c O) as [(I,c1) | ].\n   intros H H0; inversion H0; clear H0; subst.\n   apply equiv_strengthen with (2:= H _ _ (refl_equal _)).\n   unfold Meq, kreq_mem; intros; subst; apply req_mem_refl.\n   intros; discriminate.\n  Qed.\n\n  Lemma dead_code_equiv_l : forall c1 c1' E2 c2 P Q X1 X2,\n   decMR P ->\n   depend_only_rel Q X1 X2 ->\n   dead_code c1 X1 = Some c1' ->\n   equiv P E c1' E2 c2 Q ->\n   equiv P E c1 E2 c2 Q.\n  Proof.\n   intros.\n   assert (H2:= dead_code_correct _ _ H0). \n   apply equiv_depend_only_l with (2:= H) (4:= H1); trivial.\n  Qed.\n\n  Lemma dead_code_equiv_r : forall c2 c2' E1 c1 P Q X1 X2,\n   decMR P ->\n   depend_only_rel Q X1 X2 ->\n   dead_code c2 X2 = Some c2' ->\n   equiv P E1 c1 E c2' Q ->\n   equiv P E1 c1 E c2 Q.\n  Proof.\n   intros.\n   assert (H2:= dead_code_correct _ _ H0). \n   apply equiv_depend_only_r with (2:= H) (4:= H1); trivial.\n  Qed.\n\n End EQOBS.\n\n Section DEAD_CODE.\n   \n  Variables n : positive.\n  Variables E1 E2 : env. \n  Variables (pi1:eq_refl_info E1) (pi2:eq_refl_info E2). \n\n  Definition dead_code_para c1 c2 O1 O2 :=\n   match dead_code n pi1 c1 O1, dead_code n pi2 c2 O2 with\n   | Some c1', Some c2' => Some (c1', c2')\n   | _, _ => None\n   end.\n\n  Lemma dead_code_para_equiv :  forall c1 c1' c2 c2' P Q X1 X2,\n   decMR P ->\n   depend_only_rel Q X1 X2 ->\n   dead_code_para c1 c2 X1 X2 = Some (c1',c2') ->\n   equiv P E1 c1' E2 c2' Q ->\n   equiv P E1 c1 E2 c2 Q.\n  Proof.\n   intros c1 c1' c2 c2' P Q X1 X2 Hdec Hdep Heq Hequiv;\n    generalize Heq; clear Heq; unfold dead_code_para.\n   case_eq (dead_code n pi1 c1 X1);\n    [intros C1' H | intros; discriminate].\n   case_eq (dead_code n pi2 c2 X2);\n    [intros C2' H' H1; inversion H1; clear H1; subst|intros; discriminate].\n   apply (@dead_code_equiv_l n E1 pi1 c1 c1' E2 c2 P _ _ _ Hdec Hdep H); trivial.\n   apply (@dead_code_equiv_r n E2 pi2 c2 c2' E1 c1' P _ _ _ Hdec Hdep H'); trivial.\n  Qed.\n\n End DEAD_CODE.\n\n\n Section CODE_MOVEMENT.\n\n  Fixpoint split_cmd_aux (i:I.t) (r c:cmd) {struct c} : option (cmd * cmd) :=\n   match c with\n   | nil => None\n   | i'::c' =>\n     if I.eqb i i' then Some (r, c')\n     else split_cmd_aux i (i'::r) c'\n   end.\n\n  Definition split_cmd i c := split_cmd_aux i nil c.\n\n  Lemma split_cmd_aux_correct : forall i c r r' t,\n   split_cmd_aux i r c = Some (r',t) ->\n   rev_append r c = rev_append r' (i::t).\n  Proof.\n   induction c; simpl; intros r r' t.\n   intros; discriminate.\n   generalize (I.eqb_spec i a); destruct (I.eqb i a); intros.\n   inversion H0; clear IHc H0; subst; trivial.\n   rewrite <- (IHc _ _ _ H0); trivial.\n  Qed.\n\n  Lemma split_cmd_correct : forall i c r t, \n   split_cmd i c = Some (r,t) ->\n   c = rev_append r (i::t).\n  Proof.\n   intros i c r t H; rewrite <- (split_cmd_aux_correct _ _ _  H); trivial.\n  Qed.\n  \n  Lemma EqObs_swap_aux : forall E I1 I2 O1 O2 c1 c2,\n   Modify E O1 c1 ->\n   Modify E O2 c2 ->\n   EqObs I2 E c2 E c2 O2 ->\n   Vset.disjoint I2 O1 ->\n   forall k (m1 m2 : Mem.t k),\n    m1 =={Vset.union I1 I2} m2 ->\n    forall f: Mem.t k -> U, \n     mu ([[c1]] E m1) (fun m' => mu ([[c2]] E m') f) ==\n     mu ([[c1]] E m1) (fun m' => mu ([[c2]] E m2) \n      (fun m'' => f (m1{!O1 <<- m'!} {!O2 <<- m''!}))).\n  Proof.\n   intros.\n   rewrite (Modify_deno_elim H).\n   apply (mu_stable_eq (([[c1]]) E m1)).\n   simpl; apply ford_eq_intro; intros m'.\n   rewrite (Modify_deno_elim H0 (k:=k)).\n   match goal with |- ?x == _ => set (F:= x) end.\n   rewrite (Modify_deno_elim H0 (k:=k)); unfold F; clear F.\n   assert (m1 {!O1 <<- m'!} =={I2} m2).\n   apply req_mem_trans with m1.\n   apply req_mem_update_disjoint; trivial.\n   apply req_mem_weaken with (2:= H3); auto with set.\n   apply (equiv_deno H1); trivial; unfold kreq_mem; intros.\n   rewrite (@req_mem_eq k O2 (m1 {!O1 <<- m'!}) m0 (m2 {!O2 <<- m3!})); trivial.\n   apply req_mem_trans with (1:= H5).\n   apply req_mem_sym; apply req_mem_update_mem_l.\n  Qed.\n\n  Lemma swap_comm :  forall E I1 I2 O1 O2 c1 c2,\n   Modify E O1 c1 ->\n   Modify E O2 c2 ->\n   EqObs I1 E c1 E c1 O1 ->\n   EqObs I2 E c2 E c2 O2 ->\n   Vset.disjoint I2 O1 ->\n   Vset.disjoint I1 O2 ->\n   Vset.disjoint O1 O2 ->\n   forall k (m:Mem.t k) f,\n    mu ([[c1++c2]] E m) f ==\n    mu ([[c2++c1]] E m) f.\n  Proof.\n   intros; repeat rewrite deno_app_elim.\n   assert (H6:= req_mem_refl (Vset.union I1 I2) m).\n   rewrite (EqObs_swap_aux I1 H H0 H2 H3 H6).\n   rewrite VsetP.union_sym in H6; apply req_mem_sym in H6.\n   rewrite (EqObs_swap_aux I2 H0 H H1 H4 H6).\n   rewrite deno_comm.\n   apply mu_stable_eq.\n   refine (@ford_eq_intro _ _ _ _ _); intros m'.\n   apply mu_stable_eq.\n   simpl; apply ford_eq_intro; intro m''.\n   replace (m {!O1 <<- m''!} {!O2 <<- m'!}) with \n    (m {!O2 <<- m'!} {!O1 <<- m''!}); trivial.\n   apply Mem.eq_leibniz.\n   intros (t, x); destruct (VsetP.mem_dec x O1).\n   rewrite update_mem_in; trivial.\n   rewrite update_mem_notin.\n   rewrite update_mem_in; trivial.\n   apply VsetP.disjoint_mem_not_mem with (1:= H5); trivial.\n   rewrite update_mem_notin; trivial. \n   destruct (VsetP.mem_dec x O2).\n   repeat rewrite update_mem_in; trivial.\n   repeat rewrite update_mem_notin; trivial.\n  Qed.\n\n  Lemma equiv_swap : forall E I1 I2 O1 O2 c1 c2,\n   Modify E O1 c1 ->\n   Modify E O2 c2 ->\n   EqObs I1 E c1 E c1 O1 ->\n   EqObs I2 E c2 E c2 O2 ->\n   Vset.disjoint O1 O2 ->\n   Vset.disjoint I1 O2 ->\n   Vset.disjoint I2 O1 -> \n   equiv Meq E (c1++c2) E (c2++c1) Meq.\n  Proof.\n   intros; intro k.\n   exists (fun m1 m2 => Mlet ([[c1++c2]] E m1) (fun m => Munit (m,m))).\n   unfold Meq; intros; subst; constructor; simpl; intros; trivial.\n   apply (mu_stable_eq (([[c1 ++ c2]]) E m2)).\n   simpl; apply ford_eq_intro; trivial.\n   rewrite (swap_comm H H0 H1 H2 H5 H4 H3 m2).\n   apply (mu_stable_eq (([[c2 ++ c1]]) E m2)).\n   simpl; apply ford_eq_intro; trivial. \n   red; unfold prodP; intros; simpl.\n   transitivity (mu (([[c1 ++ c2]]) E m2) (fun x : Mem.t k=> 0)).\n   symmetry; apply mu_0.\n   apply (mu_stable_eq (([[c1 ++ c2]]) E m2)).\n   simpl; apply ford_eq_intro; auto.\n  Qed.\n\n  Variable n : positive.\n\n  Variable E1 E2 : env.\n\n  Variable pi1 : eq_refl_info E1.\n  \n  Variable pi2 : eq_refl_info E2. \n\n  Definition swapable (E:env) (pi:eq_refl_info E) (i:I.instr) (c:cmd) :=\n   match modify_i pi Vset.empty i, modify pi Vset.empty c with\n   | Some M1, Some M2 =>\n     if Vset.disjoint M1 M2 then\n     match eqobs_in_i n pi i M1, eqobs_in n pi c M2 with\n     | Some I1, Some I2 =>\n       if Vset.disjoint I1 M2 then Vset.disjoint I2 M1 \n       else false\n     | _, _ => false\n     end\n     else false\n   | _, _ => false\n   end.\n\n  Lemma swapable_correct : forall (E:env) (pi:eq_refl_info E) (i:I.instr) (c:cmd),\n   swapable pi i c = true ->\n   equiv Meq E (i::c) E (c++[i]) Meq.\n  Proof.\n   unfold swapable; intros E pi i c.\n   generalize (modify_i_correct pi i Vset.empty);\n    destruct (modify_i pi Vset.empty i) as [M1 | ]; \n     intro; try (intros; discriminate).\n   generalize (modify_correct pi c Vset.empty);\n    destruct (modify pi Vset.empty c) as [M2 | ]; \n     intro; try (intros; discriminate).\n   case_eq (Vset.disjoint M1 M2); intro; try (intros; discriminate).\n   generalize (fun I => @eqobs_in_i_correct n E pi i I M1);\n    destruct (eqobs_in_i n pi i M1) as [I1 | ]; intro; try (intros; discriminate).\n   generalize (fun I => @eqobs_in_correct n E pi c I M2);\n    destruct (eqobs_in n pi c M2) as [I2 | ]; intro; try (intros; discriminate).\n   case_eq (Vset.disjoint I1 M2); intros; try discriminate.\n   apply equiv_swap with (3:=H2 _ (refl_equal _)) (4:=H3 _ (refl_equal _)); auto.\n  Qed.\n\n  Fixpoint swap_aux (rh1 t1 c2 t : cmd) {struct rh1} : (triple cmd cmd cmd) :=\n   match rh1 with\n   | nil => Triple t1 c2 t\n   | i::rh1' =>\n     if swapable pi1 i t1 then\n      match split_cmd i c2 with\n      | Some (r2,t2) =>\n        if swapable pi2 i t2 then swap_aux rh1' t1 (rev_append r2 t2) (i::t)\n        else swap_aux rh1' (i::t1) c2 t\n      | None => swap_aux rh1' (i::t1) c2 t \n      end \n      else swap_aux rh1' (i::t1) c2 t\n   end.\n  \n  Lemma swap_aux_correct : forall rh1 t1 c2 t h1 h2 t',\n   swap_aux rh1 t1 c2 t = Triple h1 h2 t' ->\n   equiv Meq E1 ((rev_append rh1 t1) ++ t) E1 (h1++t') Meq /\\\n   equiv Meq E2 (c2 ++ t) E2 (h2++t') Meq.\n  Proof.\n   induction rh1; simpl; intros t1 c2 t h1 h2 t'.\n   intros Heq; inversion Heq; split; apply equiv_eq_mem.\n   assert (forall h1 h2 t', swap_aux rh1 (a :: t1) c2 t = Triple h1 h2 t' ->\n     equiv Meq E1 (rev_append rh1 (a :: t1) ++ t) E1 (h1 ++ t') Meq /\\\n     equiv Meq E2 (c2 ++ t) E2 (h2 ++ t') Meq).\n     intros h3 h4 t'0 H1; refine (IHrh1 _ _ _ _ _ _ H1).\n   generalize (swapable_correct pi1 a t1).\n   destruct (swapable pi1 a t1); intro; auto.\n   generalize (split_cmd_correct a c2).\n   destruct (split_cmd a c2) as [(h3,t2) | ]; intro; auto.\n   generalize (swapable_correct pi2 a t2).\n   destruct (swapable pi2 a t2); intros; auto.  \n   destruct (IHrh1 _ _ _ _ _ _ H3). \n   split.\n   apply equiv_trans_eq_mem_l with \n    (P1:=trueR) (2:= H4); trivial.\n   simplMR; repeat rewrite rev_append_rev.\n   change (a::t) with ([a]++t).\n   rewrite ass_app; apply equiv_app with Meq; auto using equiv_eq_mem.\n   rewrite app_ass; apply equiv_app with Meq; auto using equiv_eq_mem.\n   red; red; trivial.\n   rewrite (H1 _ _ (refl_equal _)).\n   apply equiv_trans_eq_mem_l with (P1:=trueR) (2:= H5); trivial.\n   simplMR; change (a::t) with ([a]++t).\n   rewrite ass_app; apply equiv_app with Meq; auto using equiv_eq_mem.\n   repeat rewrite rev_append_rev; rewrite rev_append_rev in H5.\n   rewrite app_ass; apply equiv_app with Meq; auto using equiv_eq_mem.\n   red; red; trivial.\n  Qed.\n\n  Definition swap c1 c2 := swap_aux (rev' c1) nil c2 nil. \n\n  Lemma swap_correct : forall c1 c2 h1 h2 t,\n   swap c1 c2 = Triple h1 h2 t ->\n   forall P Q, equiv P E1 (h1++t) E2 (h2++t) Q ->\n    equiv P E1 c1 E2 c2 Q.\n  Proof.\n   intros. \n   destruct (swap_aux_correct _ _ _ _ H).\n   rewrite <- app_nil_end in H1, H2.\n   unfold rev' in H1; repeat rewrite rev_append_rev in H1.\n   repeat rewrite <- app_nil_end in H1; rewrite rev_involutive in H1.\n   apply equiv_trans_eq_mem_l with \n    (P1:=trueR) (E1':= E1) (c1':= (h1 ++ t)); trivial.\n   simplMR; trivial.\n   apply equiv_trans_eq_mem_r with \n    (P2:=trueR) (E2':= E2) (c2':= (h2 ++ t)); trivial.\n   simplMR; trivial.\n   red; red; trivial.\n   red; red; trivial.\n  Qed.\n\n End CODE_MOVEMENT.\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/EqTh.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621764862150636, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.2920626712888324}}
{"text": "Require Import Arith List String.\nRequire Import ExtLib.Structures.Monad.\nFrom CertiCoq.Plugin Require Import CertiCoq.\n\nImport MonadNotation.\nImport ListNotations.\nOpen Scope monad_scope.\n\nRequire Import Coq.Strings.Ascii.\n\nInductive rgx : Type :=\n| empty   : rgx\n| epsilon : rgx\n| literal : string -> rgx\n| or      : rgx -> rgx -> rgx\n| and     : rgx -> rgx -> rgx\n| star    : rgx -> rgx\n| capture : rgx -> rgx.\n\nFixpoint simplify (r : rgx) : rgx :=\n  match r with\n  | star epsilon         => epsilon\n  | star (star r')       => star (simplify r')\n  | or epsilon (star r') => star (simplify r')\n  | or empty r'          => simplify r'\n  | and  r1 r2           => and (simplify r1) (simplify r2)\n  | or   r1 r2           => or (simplify r1) (simplify r2)\n  | star r'              => star (simplify r')\n  | capture r'           => capture (simplify r')\n  | _                    => r\n  end.\n\nInfix \"⊕\" := or (right associativity, at level 60).\nInfix \"·\" := and (right associativity, at level 60).\n\nClass RegexFFI : Type :=\n  Build_RegexFFI\n    { test : rgx -> string -> bool\n    ; exec : rgx -> string -> option (list string)\n    }.\n\nFixpoint literals (l : list string) : rgx :=\n  match l with\n  | nil => empty\n  | x :: xs => literal x ⊕ literals xs\n  end.\n\nDefinition numeric := literals [\"0\";\"1\";\"2\";\"3\";\"4\";\"5\";\"6\";\"7\";\"8\";\"9\"]%string.\n\nDefinition alpha :=\n  or (literals [\"a\";\"b\";\"c\";\"d\";\"e\";\"f\";\"g\";\"h\";\"i\";\"j\";\"k\";\"l\";\"m\"]%string)\n     (literals [\"n\";\"o\";\"p\";\"q\";\"r\";\"s\";\"t\";\"u\";\"v\";\"w\";\"x\";\"y\";\"z\"]%string).\n\nDefinition alphanumeric :=\n  or alpha numeric.\n\nDefinition email :=\n    capture (star alphanumeric)\n  · literal \"@\"\n  · capture (star alphanumeric)\n  · literal \".\"\n  · capture (literals [\"com\";\"net\";\"org\";\"edu\"]%string).\n\nDefinition prog `{RegexFFI} :=\n  exec email \"name@example.com\".\n\nCertiCoq Compile -args 5 prog.\nCertiCoq FFI -prefix \"rgx_\" RegexFFI.\n", "meta": {"author": "CertiCoq", "repo": "certicoq", "sha": "2405e1012e9c0a58e49002d9779bb65527d6c323", "save_path": "github-repos/coq/CertiCoq-certicoq", "path": "github-repos/coq/CertiCoq-certicoq/certicoq-2405e1012e9c0a58e49002d9779bb65527d6c323/benchmarks/regex/regex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.29206267128883234}}
{"text": "From Coq Require Import Arith Psatz Bool String List Nat Program.Equality.\n\nLocal Open Scope string_scope.\nLocal Open Scope nat_scope.\nLocal Open Scope list_scope.\n\nRequire Import DanTrick.StackLanguage DanTrick.StackLangEval DanTrick.LogicProp DanTrick.StackSubstitution DanTrick.StackPurest DanTrick.StackExprWellFormed.\n\nFrom DanTrick Require Export StackLogicBase.\n\nScheme Equality for list.\n\n\n\n                           \n\n\nDefinition triple_stk (P: AbsState) (i: imp_stack) (Q: AbsState) (fenv: fun_env_stk): Prop :=\n  forall (stk stk': stack),\n    imp_stack_sem i fenv stk stk' ->\n    (absstate_match_rel P fenv stk) ->\n    (absstate_match_rel Q fenv stk').\n\nNotation \"{{{ P }}} i {{{ Q }}} @ f\" := (triple_stk P i Q f) (at level 90, i at next level).\n    \n\n\n\nDefinition atruestk (b: bexp_stack) (P: AbsState): AbsState :=\n  (AbsAnd P (BaseState (AbsStkTrue)\n                       (MetaBool (UnaryProp _ _\n                                            (fun bval => bval = true)\n                                            b)))).\n\nDefinition afalsestk (b: bexp_stack) (P: AbsState) : AbsState :=\n  (AbsAnd P (BaseState (AbsStkTrue)\n                       (MetaBool (UnaryProp _ _\n                                            (fun bval => bval = false)\n                                            b)))).\n\nDefinition aimpstk (P Q: AbsState) (fenv: fun_env_stk) : Prop :=\n  forall stk,\n    absstate_match_rel P fenv stk -> absstate_match_rel Q fenv stk.\n\nDefinition aandstk (P Q: assertion): assertion :=\n  fun stk => P stk /\\ Q stk.\n\nLemma self_implication :\n  forall (s: AbsState) (fenv: fun_env_stk),\n    (aimpstk s s fenv).\nProof.\n  unfold aimpstk. intros. auto.  \nQed. \n\nCheck (aandstk silly silly).\n\nLemma anding_silly :\n  forall stk,\n    ~ (aandstk silly silly stk).\nProof.\n  intros. unfold aandstk, not. intros.\n  destruct H.\n  apply silly_theorem in H.\n  assumption.\nQed.\n\n\n\nNotation \"P --->>> Q\" := (aimpstk P Q) (at level 95, no associativity).\n\n\nInductive hl_stk : AbsState -> imp_stack -> AbsState -> fun_env_stk -> Type :=\n| hl_stk_skip :\n  forall P fenv,\n    hl_stk P Skip_Stk P fenv\n| hl_stk_assign :\n  forall P fenv k a P',\n    aexp_stack_pure_rel a fenv ->\n    state_update_rel k a P P' ->\n    hl_stk P' (Assign_Stk k a) P fenv\n| hl_stk_push :\n  forall P fenv P',\n    state_stk_size_inc 1 P P' ->\n    hl_stk P (Push_Stk) P' fenv\n| hl_stk_pop :\n  forall P fenv P' Q,\n    state_stk_size_inc 1 P' P ->\n    hl_stk (AbsAnd P Q) (Pop_Stk) P' fenv \n| hl_stk_seq :\n  forall P Q R i1 i2 fenv,\n    hl_stk P i1 R fenv ->\n    hl_stk R i2 Q fenv ->\n    hl_stk P (Seq_Stk i1 i2) Q fenv\n| hl_stk_if :\n  forall P Q b i1 i2 fenv,\n    bexp_stack_pure_rel b fenv ->\n    hl_stk (atruestk b P) i1 Q fenv ->\n    hl_stk (afalsestk b P) i2 Q fenv ->\n    hl_stk P (If_Stk b i1 i2) Q fenv\n| hl_stk_while :\n  forall P b i fenv,\n    bexp_stack_pure_rel b fenv ->\n    hl_stk (atruestk b P) i P fenv ->\n    hl_stk P (While_Stk b i) (afalsestk b P) fenv\n| hl_stk_consequence :\n  forall P Q P' Q' c fenv,\n    hl_stk P c Q fenv ->\n    (P' --->>> P) fenv ->\n    (Q --->>> Q') fenv ->\n    hl_stk P' c Q' fenv.\n\nCheck hl_stk_ind.\n\n\n\n\n\n\nLemma Hoare_Stk_consequence_pre :\n  forall P P' Q i fenv,\n    hl_stk P i Q fenv ->\n    (P' --->>> P) fenv ->\n    hl_stk P' i Q fenv.\nProof.\n  intros.\n  apply hl_stk_consequence with (P := P) (Q := Q); unfold aimpstk; auto.\nQed.\n\n\nLemma Hoare_Stk_consequence_post :\n  forall P Q Q' i fenv,\n    hl_stk P i Q fenv ->\n    (Q --->>> Q') fenv ->\n    hl_stk P i Q' fenv.\nProof.\n  intros.\n  apply hl_stk_consequence with (P := P) (Q := Q); unfold aimpstk; auto.\nQed.\n\n\nLemma Hoare_Stk_ifthen :\n  forall b i P Q fenv,\n    bexp_stack_pure_rel b fenv ->\n    hl_stk (atruestk b P) i Q fenv ->\n    ((afalsestk b P) --->>> Q) fenv ->\n    hl_stk P (If_Stk b i Skip_Stk) Q fenv.\nProof.\n  intros. apply (hl_stk_if P Q b i Skip_Stk fenv); auto.\n  apply Hoare_Stk_consequence_pre with Q.\n  - auto using hl_stk_skip.\n  - assumption.\nQed.\n\nLtac invs H := inversion H; subst.\n\nLemma triple_stk_skip :\n  forall P fenv,\n    {{{P}}} Skip_Stk {{{P}}} @ fenv.\nProof.\n  unfold triple_stk; intros. invs H. assumption.\nQed.\n\nLemma triple_stk_assign :\n  forall P P' (k: stack_index) (a: aexp_stack) fenv,\n    aexp_stack_pure_rel a fenv ->\n    state_update_rel k a P P' ->\n    {{{P'}}} Assign_Stk k a {{{P}}} @ fenv.\nProof.\n  unfold triple_stk, stk_update. intros P P' k a fenv PURE STATE_UP.\n  intros.\n  invs H.\n\n  pose proof (PURE' := PURE).\n  eapply aexp_stack_pure_backwards in PURE.\n  unfold aexp_stack_pure in PURE.\n  specialize (PURE stk stk'0 c).\n\n  pose proof (H10 := H5).\n  apply PURE in H5.\n  symmetry in H5.\n  subst.\n  invs STATE_UP.\n  - assert (absstate_well_formed (BaseState s m)).\n    econstructor.\n    assumption.\n    \n    eapply state_update_same_as_eval_under_different_state with (k := k) (a := a) (aval := c) (stk := stk) (stk' := stk'); eassumption.\n  - assert (absstate_well_formed (AbsAnd s1 s2)) by (econstructor; eassumption).\n    eapply state_update_same_as_eval_under_different_state with (k := k) (a := a) (aval := c) (stk := stk) (stk' := stk'); eassumption.\n  - assert (absstate_well_formed (AbsOr s1 s2)) by (econstructor; eassumption).\n    eapply state_update_same_as_eval_under_different_state with (k := k) (a := a) (aval := c) (stk := stk) (stk' := stk'); eassumption.\nQed.\n\n\nLtac absstack_size :=\n  match goal with\n  | [ |- absstack_match_rel (AbsStkSize 1) (?v :: ?vs) ] =>\n      econstructor; simpl; intuition\n  end.\n\nLtac match_inversion :=\n  match goal with\n  | [ H: absstate_match_rel (BaseState ?s ?Meta) ?fenv ?stk |- _ ] =>\n      invs H;\n      match goal with\n      | [ H': meta_match_rel Meta fenv stk |- _ ] =>\n          invs H';\n          match goal with\n          | [ H'' : eval_prop_rel ?func ?LogProp |- _ ] =>\n              invs H''\n          end;\n          match goal with\n          | [ H''' : prop_rel ?func ?LogProp |- _ ] =>\n              invs H'''\n          end\n      end\n  end;\n  match goal with\n  | [ H : absstate_well_formed (BaseState ?s ?Meta) |- _ ] =>\n      invs H;\n      match goal with\n      | [ H' : mv_well_formed Meta |- _ ] =>\n          invs H'\n      | [ |- _ ] =>\n          idtac\n      end\n  | [ |- _ ] =>\n      idtac\n  end.\n\n\nLtac meta_match_elimination_helper p1 p2 p1' p2' :=\n  match goal with\n  | [ H': transformed_prop_exprs _ p1 p1' |- _ ] =>\n      econstructor\n  | [ H': transformed_prop_exprs _ p2 p2' |- _ ] =>\n      eapply RelOrPropRight\n  end.\n\nLtac meta_match_elimination :=\n  match goal with\n  | [  |- meta_match_rel (_ (OrProp ?ValType ?ExprType ?p1' ?p2')) ?fenv ?stk ] =>\n      econstructor;\n      match goal with\n      | [ H: eval_prop_rel _ (OrProp ValType ExprType ?p1 ?p2)  |- _ ] =>\n          match goal with\n          | [ H': eval_prop_rel _ p1 |- _ ] =>\n              econstructor\n          | [ H': eval_prop_rel _ p2 |- _ ] =>\n              eapply RelOrPropRight\n          end\n      | [ |- _ ] =>\n          idtac\n      end\n  | [ |- meta_match_rel _ _ _ ] =>\n      econstructor;\n      econstructor\n  end.\n\nLtac smart_pure_helper :=\n  match goal with\n  | [  H0 : transformed_prop_exprs (bexp_stk_size_inc_rel 1) ?p1 ?p1', H13 : prop_rel\n          (fun boolexpr : bexp_stack => bexp_stack_pure_rel boolexpr ?fenv)\n          ?p1\n       |- prop_rel\n           (fun boolexpr : bexp_stack => bexp_stack_pure_rel boolexpr ?fenv) ?p1' ] =>\n      eapply bool_prop_rel_prop_stk_inc_preserves_purity; [ eapply H13 | eassumption]\n  | [ H0: transformed_prop_exprs_args (bexp_stk_size_inc_rel 1) ?args ?args',\n        H1: prop_args_rel (fun boolexpr : bexp_stack =>\n                             bexp_stack_pure_rel boolexpr ?fenv)\n                          ?args |-\n        prop_args_rel (fun boolexpr : bexp_stack =>\n                         bexp_stack_pure_rel boolexpr ?fenv)\n                      ?args' ] =>\n      eapply bool_prop_args_rel_prop_stk_inc_preserves_purity; eassumption\n  | [ H0: bexp_stk_size_inc_rel 1 ?a ?a',\n        H1: bexp_stack_pure_rel ?a ?fenv |-\n        bexp_stack_pure_rel ?a' ?fenv ] =>\n      eapply bexp_size_inc_preserves_purity; eassumption\n                                                            \n  | [  H0 : transformed_prop_exprs (aexp_stk_size_inc_rel 1) ?p1 ?p1',\n       H13 : prop_rel\n               (fun natexpr : aexp_stack =>\n                  aexp_stack_pure_rel natexpr ?fenv)\n               ?p1\n       |- prop_rel\n           (fun natexpr : aexp_stack =>\n              aexp_stack_pure_rel natexpr ?fenv)\n           ?p1' ] =>\n      eapply nat_prop_rel_prop_stk_inc_preserves_purity; [ eapply H13 | eassumption]\n  | [ H0: aexp_stk_size_inc_rel 1 ?a ?a',\n        H1: aexp_stack_pure_rel ?a ?fenv |-\n        aexp_stack_pure_rel ?a' ?fenv ] =>\n      eapply aexp_size_inc_preserves_purity; eassumption\n  | [ H0: transformed_prop_exprs_args (aexp_stk_size_inc_rel 1) ?args ?args',\n        H1: prop_args_rel (fun natexpr : aexp_stack =>\n                             aexp_stack_pure_rel natexpr ?fenv)\n                          ?args |-\n        prop_args_rel (fun natexpr : aexp_stack =>\n                         aexp_stack_pure_rel natexpr ?fenv)\n                      ?args' ] =>\n      eapply nat_prop_args_rel_prop_stk_inc_preserves_purity; eassumption\n        \n  end.\n\n\n\nLemma triple_stk_push :\n  forall P Q fenv,\n    state_stk_size_inc 1 P Q ->\n    {{{P}}} Push_Stk {{{Q}}} @ fenv.\nProof.\n  unfold triple_stk.\n  induction P; intros Q fenv INC stk stk' IMP MATCH.\n  - invs INC.\n    invs H2; invs IMP.\n    + econstructor; [absstack_size | ].\n      invs H4.\n      * invs H; match_inversion; meta_match_elimination; try smart_pure_helper.\n        1,3,4,10-12: eapply bexp_stack_increase_preserves_eval; eassumption.\n        3-6: eapply logic_stack_increase_preserves_eval; eassumption.\n        4: eapply bool_args_stack_increase_preserves_eval; eassumption.\n        all: try eassumption; try eapply bexp_size_inc_preserves_purity; try eassumption; try smart_pure_helper.\n      * invs H; match_inversion; meta_match_elimination; try smart_pure_helper.\n        1,3,4,10-12: eapply aexp_stack_increase_preserves_eval; eassumption.\n        3-6: eapply nat_logic_stack_increase_preserves_eval; eassumption.\n        4: eapply nat_args_stack_increase_preserves_eval; eassumption.\n        all: try assumption.        \n    + econstructor.\n      * invs MATCH.\n        invs H1.\n        econstructor.\n        simpl.\n        intuition.\n      * invs H4.\n        -- invs H; match_inversion; meta_match_elimination; try smart_pure_helper;\n             try eapply bexp_stack_increase_preserves_eval; try eapply logic_stack_increase_preserves_eval; try eapply bool_args_stack_increase_preserves_eval; eassumption.\n        -- invs H; match_inversion; meta_match_elimination; try smart_pure_helper; try eapply aexp_stack_increase_preserves_eval; try eapply nat_logic_stack_increase_preserves_eval; try eapply nat_args_stack_increase_preserves_eval; eassumption.\n  - invs INC. invs MATCH.\n    econstructor.\n    + eapply IHP1; eassumption.\n    + eapply IHP2; eassumption.\n  - invs INC. invs MATCH.\n    + econstructor. eapply IHP1.\n      * eassumption.\n      * eassumption.\n      * assumption.\n    + eapply RelAbsOrRight. eapply IHP2; eassumption.\nQed.\n\nLtac smart_pure_helper' :=\n  match goal with\n  | [  H0 : transformed_prop_exprs (bexp_stk_size_inc_rel 1) ?p1 ?p1', H13 : prop_rel\n          (fun boolexpr : bexp_stack => bexp_stack_pure_rel boolexpr ?fenv)\n          ?p1',\n          H14: prop_rel bexp_well_formed ?p1\n       |- prop_rel\n           (fun boolexpr : bexp_stack => bexp_stack_pure_rel boolexpr ?fenv) ?p1 ] =>\n      eapply bool_prop_rel_prop_stk_inc_preserves_purity';\n      [eapply H13 | unfold bool_prop_wf; unfold_prop_helpers | eapply H0 ];\n      eassumption\n  | [ H0: transformed_prop_exprs_args (bexp_stk_size_inc_rel 1) ?args ?args',\n        H1: prop_args_rel (fun boolexpr : bexp_stack =>\n                             bexp_stack_pure_rel boolexpr ?fenv)\n                          ?args',\n          H2: prop_args_rel bexp_well_formed ?args |-\n        \n        prop_args_rel (fun boolexpr : bexp_stack =>\n                         bexp_stack_pure_rel boolexpr ?fenv)\n                      ?args ] =>\n      eapply bool_prop_args_rel_prop_stk_inc_preserves_purity'; eassumption\n  | [ H0: bexp_stk_size_inc_rel 1 ?a ?a',\n        H1: bexp_stack_pure_rel ?a' ?fenv,\n          H2: bexp_well_formed ?a\n      |-\n        bexp_stack_pure_rel ?a ?fenv ] =>\n      eapply bexp_size_inc_preserves_purity'; eassumption\n                                                            \n  | [  H0 : transformed_prop_exprs (aexp_stk_size_inc_rel 1) ?p1 ?p1',\n       H13 : prop_rel\n               (fun natexpr : aexp_stack =>\n                  aexp_stack_pure_rel natexpr ?fenv)\n               ?p1',\n          H14 : prop_rel aexp_well_formed ?p1\n       |- prop_rel\n           (fun natexpr : aexp_stack =>\n              aexp_stack_pure_rel natexpr ?fenv)\n           ?p1 ] =>\n      eapply nat_prop_rel_prop_stk_inc_preserves_purity';\n      [ eapply H13 | unfold nat_prop_wf; unfold_prop_helpers | eapply H0];\n      eassumption\n  | [ H0: aexp_stk_size_inc_rel 1 ?a ?a',\n        H1: aexp_stack_pure_rel ?a' ?fenv |-\n        aexp_stack_pure_rel ?a ?fenv ] =>\n      eapply aexp_size_inc_preserves_purity'; eassumption\n  | [ H0: transformed_prop_exprs_args (aexp_stk_size_inc_rel 1) ?args ?args',\n        H1: prop_args_rel (fun natexpr : aexp_stack =>\n                             aexp_stack_pure_rel natexpr ?fenv)\n                          ?args' |-\n        prop_args_rel (fun natexpr : aexp_stack =>\n                         aexp_stack_pure_rel natexpr ?fenv)\n                      ?args ] =>\n      eapply nat_prop_args_rel_prop_stk_inc_preserves_purity'; eassumption\n        \n  end.\n\nLtac match_inversion' :=\n  match goal with\n  | [ H: absstate_match_rel (AbsAnd (BaseState ?s ?Meta) ?Q) ?fenv ?stk |- _ ] =>\n      invs H;\n      match goal with\n      | [ META: absstate_match_rel (BaseState s Meta) fenv stk |- _ ] =>\n          invs META;\n          match goal with\n          | [ H': meta_match_rel Meta fenv stk |- _ ] =>\n              invs H';\n             match goal with\n              | [ H'' : eval_prop_rel ?func ?LogProp |- _ ] =>\n                  invs H''\n                        \n              end;\n              match goal with\n              | [ H''' : prop_rel ?func ?LogProp |- _ ] =>\n                  invs H''';\n                  try (match goal with\n                       | [ H''': prop_rel func LogProp,\n                           H2 : prop_rel ?func2 ?LogProp2 |- _ ] =>\n                      invs H2\n                       end)\n                  \n              end\n          end\n      end\n  end;\n  match goal with\n  | [ H : absstate_well_formed (BaseState ?s ?Meta) |- _ ] =>\n      invs H;\n      match goal with\n      | [ H' : mv_well_formed Meta |- _ ] =>\n          invs H'\n      | [ |- _ ] =>\n          idtac\n      end\n  | [ |- _ ] =>\n      idtac\n  end;\n  match goal with\n  | [ H : meta_stk_size_inc ?inc (_ ?l1) (_ ?l2) |- _ ] =>\n      invs H;\n      match goal with\n      | [ H' : transformed_prop_exprs (?func inc) l1 l2 |- _ ] =>\n          invs H'\n      end\n  end.\n\nLtac smart_wf_helper :=\n  match goal with\n  | [ H : prop_rel bexp_well_formed ?p |- _ ] =>\n      invs H\n  | [ H: prop_rel aexp_well_formed ?p |- _ ] =>\n      invs H\n  end.\n\n\nLtac smart_expr_stack_increase_preserves_eval' inc_rel pure_rel wf_rel stack_sem :=\n  match goal with\n  | [ H1 : inc_rel 1 ?a ?a',\n        H2 : pure_rel ?a' ?fenv,\n          \n          H3: wf_rel ?a,\n      H4 : stack_sem ?a' ?fenv (?v :: ?stk) (?v :: ?stk, ?aval) |-\n        stack_sem ?a ?fenv ?stk (?stk, ?val) ] =>\n      let INC := fresh \"INC\" in\n      pose proof (INC := H1);\n      match inc_rel with\n      | bexp_stk_size_inc_rel =>\n          (eapply bexp_size_inc_preserves_purity' in INC ; [ | eassumption .. ]);\n          eapply bexp_stack_increase_preserves_eval'; eassumption\n      | aexp_stk_size_inc_rel =>\n          (eapply aexp_size_inc_preserves_purity' in INC; [ | eassumption .. ]);\n          eapply aexp_stack_increase_preserves_eval'; eassumption\n      end\n  end.\n\nLtac smart_bexp_stack_increase_preserves_eval' :=\n  (smart_expr_stack_increase_preserves_eval'\n     aexp_stk_size_inc_rel\n     aexp_stack_pure_rel\n     aexp_well_formed\n     aexp_stack_sem)\n  ||\n  (smart_expr_stack_increase_preserves_eval'\n     bexp_stk_size_inc_rel\n     bexp_stack_pure_rel\n     bexp_well_formed\n     bexp_stack_sem).\n\nLtac match_logic_prop H p1 m tac :=\n  match m with\n  | AndProp _ _ p1 _ =>\n      invs H;\n      tac\n  | OrProp _ _ p1 _ =>\n      invs H; tac\n  | AndProp _ _ _ p1 =>\n      invs H; tac\n  | OrProp _ _ _ p1 =>\n      invs H; tac\n  end.\n\nLtac smart_transformed_prop_exprs inc_rel p1 tac tac1 tac2 :=\n  match goal with\n  | [ H : transformed_prop_exprs (inc_rel 1) p1 ?p1' |- _ ] =>\n      tac1 H\n  | [ H : transformed_prop_exprs (inc_rel 1) ?p1' p1 |- _ ] =>\n      tac2 H\n  | [ H : transformed_prop_exprs (inc_rel 1) ?m ?n |- _ ] =>\n      match_logic_prop H p1 m tac\n  end.\n\n\nLtac smart_logic_stack_increase_preserves_eval'_bool_prop_wf prop_rel_prop p1 tac tac1 :=\n   match goal with\n   | [ H : prop_rel prop_rel_prop p1 |- _ ] =>\n       tac1 H\n   | [ H : prop_rel prop_rel_prop ?m |- _ ] =>\n       match_logic_prop H p1 m tac\n   end.\n\nLtac smart_logic_stack_increase_preserves_eval' :=\n  match goal with\n  | [ |- transformed_prop_exprs (?inc_rel 1) ?p1 ?[?p'] ] =>\n      smart_transformed_prop_exprs inc_rel p1 ltac:(eassumption) ltac:(fun H => eapply H) ltac:(idtac)\n  | [ |- bool_prop_wf ?p1 ] =>\n      unfold bool_prop_wf;\n      smart_logic_stack_increase_preserves_eval'_bool_prop_wf bexp_well_formed p1 ltac:(eassumption) ltac:(fun H => eapply H)\n  | [ |- nat_prop_wf ?p1 ] =>\n      unfold nat_prop_wf;\n      smart_logic_stack_increase_preserves_eval'_bool_prop_wf aexp_well_formed p1 ltac:(eassumption) ltac:(fun H => eapply H)\n  | [ |- prop_rel (fun boolexpr : ?expr_type => ?pure_rel boolexpr ?fenv) ?p1 ] =>\n      match pure_rel with\n      | bexp_stack_pure_rel =>\n          smart_pure_helper'\n      | aexp_stack_pure_rel =>\n          smart_pure_helper'\n      end\n  | [ |- _ ] =>\n      eassumption\n  end.\n\n\n\n\n\nLtac small_smart_pure_helper inc_rel tac1 tac3 :=\n  match inc_rel with\n  | bexp_stk_size_inc_rel =>\n      eapply bool_prop_rel_prop_stk_inc_preserves_purity';\n      [\n        tac1\n      | smart_wf_helper\n      | tac3 ]\n  | aexp_stk_size_inc_rel =>\n      eapply nat_prop_rel_prop_stk_inc_preserves_purity';\n      [\n        tac1\n      | smart_wf_helper\n      | tac3 ]\n  end.\n\nLemma triple_stk_pop :\n  forall P' P Q fenv,\n    state_stk_size_inc 1 P' P ->\n    {{{(AbsAnd P Q)}}} Pop_Stk {{{ P' }}} @ fenv.\nProof.\n  unfold triple_stk.\n  induction P'; intros P Q fenv INC stk stk' IMP MATCH.\n  - invs IMP.\n    invs INC.\n    invs H2.\n    + econstructor; [ econstructor | ].\n      invs H4.\n      * invs H; match_inversion'; meta_match_elimination; try smart_wf_helper; try smart_pure_helper'.\n        all: try smart_bexp_stack_increase_preserves_eval'.\n        all: try (eapply logic_stack_increase_preserves_eval'; smart_logic_stack_increase_preserves_eval').\n        4: eapply bool_args_stack_increase_preserves_eval'; try eassumption; try smart_pure_helper'.\n        all: eassumption.\n      * invs H; match_inversion'; meta_match_elimination; try smart_wf_helper; try smart_pure_helper'.\n        all: try (smart_bexp_stack_increase_preserves_eval').\n        all: try (eapply nat_logic_stack_increase_preserves_eval'; smart_logic_stack_increase_preserves_eval').\n        4: eapply nat_args_stack_increase_preserves_eval'; try eassumption; try smart_pure_helper'.\n        all: assumption.\n    + econstructor.\n      * invs MATCH.\n        invs H1.\n        invs H3.\n        constructor.\n        simpl in H0.\n        intuition.\n      * invs H4.\n        -- invs H; match_inversion'; meta_match_elimination; try smart_wf_helper; try smart_pure_helper'.\n           all: try (smart_bexp_stack_increase_preserves_eval').\n           all: try (eapply logic_stack_increase_preserves_eval'; smart_logic_stack_increase_preserves_eval').\n           4: eapply bool_args_stack_increase_preserves_eval'; try eassumption; try smart_pure_helper'.\n           all: assumption.\n        -- invs H; match_inversion'; meta_match_elimination; try smart_wf_helper; try smart_pure_helper'.\n           all: try smart_bexp_stack_increase_preserves_eval'.\n           all: try (eapply nat_logic_stack_increase_preserves_eval'; smart_logic_stack_increase_preserves_eval').\n           all: try (eapply aexp_stack_increase_preserves_eval'; [ | | eapply aexp_size_inc_preserves_purity' | ]; eassumption).\n           4: eapply nat_args_stack_increase_preserves_eval'; try eassumption; try smart_pure_helper'.\n           all: assumption.\n  - invs MATCH. invs INC.\n    econstructor.\n    + eapply IHP'1; eassumption.\n    + eapply IHP'2.\n      eassumption.\n      eassumption.\n      invs MATCH.\n      assert (absstate_match_rel (AbsAnd s2' Q) fenv stk).\n      * invs H2.\n        constructor; assumption.\n      * eassumption.\n  - invs MATCH. invs INC.\n    invs H1.\n    + econstructor. eapply IHP'1.\n      eassumption.\n      eassumption.\n      assert (absstate_match_rel (AbsAnd s1' Q) fenv stk).\n      * constructor; assumption.\n      * eassumption.\n    + eapply RelAbsOrRight. eapply IHP'2.\n      eassumption.\n      eassumption.\n      assert (absstate_match_rel (AbsAnd s2' Q) fenv stk).\n      * constructor; assumption.\n      * eassumption.\nQed.\n\n\nLocal Open Scope stack_scope.\n\nLemma triple_stk_seq :\n  forall P Q R i1 i2 fenv,\n    {{{P}}} i1 {{{Q}}} @ fenv ->\n    {{{Q}}} i2 {{{R}}} @ fenv ->\n    {{{P}}} i1 ;;; i2 {{{R}}} @ fenv.\nProof.\n  unfold triple_stk; intros.\n  invs H1.\n  apply H in H5.\n  - apply H0 in H9.\n    + assumption.\n    + assumption.\n  - assumption.\nQed.\n\n\nLemma triple_stk_ifthenelse :\n  forall P Q b i1 i2 fenv,\n    bexp_stack_pure_rel b fenv ->\n    {{{(atruestk b P)}}} i1 {{{Q}}} @ fenv ->\n    {{{(afalsestk b P)}}} i2 {{{Q}}} @ fenv ->\n    {{{P}}} ifs b thens i1 elses i2 dones {{{Q}}} @ fenv.\nProof.\n  unfold triple_stk, atruestk, afalsestk, bexp_stack_pure; intros.\n  invs H2.\n  - apply H0 in H11.\n    + assumption.\n    + pose proof (PURE := H).\n      eapply (bexp_stack_pure_implication) in PURE.\n      unfold bexp_stack_pure in PURE.\n      pose proof (H12 := H10).\n      apply PURE in H10.\n      subst.\n      econstructor.\n      * assumption.\n      * econstructor.\n        -- econstructor.\n        -- econstructor.\n           econstructor.\n           eassumption.\n           reflexivity.\n           econstructor.\n           eassumption.\n  - apply H1 in H11.\n    + assumption.\n    + pose proof (PURE := H).\n      eapply (bexp_stack_pure_implication) in H.\n      specialize (H stk stk'0 false).\n      pose proof (H12 := H10).\n      apply H in H10; subst.\n      econstructor.\n      * assumption.\n      * econstructor.\n        -- econstructor.\n        -- econstructor.\n           ++ econstructor.\n              ** eassumption.\n              ** reflexivity.\n           ++ econstructor. assumption.\nQed.\n\nLemma triple_stk_while :\n  forall P b l fenv,\n    bexp_stack_pure_rel b fenv ->\n    {{{atruestk b P}}} l {{{P}}} @ fenv ->\n    {{{P}}} whiles b loops l dones {{{afalsestk b P}}} @ fenv.\nProof.\n  unfold triple_stk, afalsestk, bexp_stack_pure; intros P b l fenv PURE TRUE_LOOP stk stk' SEM.\n  dependent induction SEM; intros.\n  - pose proof (PURE' := PURE).\n    eapply bexp_stack_pure_implication in PURE.\n    specialize (PURE stk stk' false).\n    pose proof (H1 := H).\n    apply PURE in H. subst.\n\n    econstructor; [assumption | ].\n    econstructor; [econstructor | ].\n    econstructor; [ |  econstructor; eassumption].\n    econstructor; [eassumption | reflexivity].\n  - pose proof (PURE' := PURE).\n    eapply bexp_stack_pure_implication in PURE'.\n    specialize (PURE' stk stk1 true).\n\n    pose proof (H1 := H).\n    apply PURE' in H.\n    subst.\n    eapply IHSEM2; eauto.\n    specialize (TRUE_LOOP stk1 stk2).\n    apply TRUE_LOOP in SEM1.\n    + assumption.\n    + unfold atruestk. econstructor; [assumption |].\n      econstructor; [econstructor|].\n      econstructor. econstructor.\n      * eassumption.\n      * reflexivity.\n      * econstructor; eassumption.\nQed.\n\nLemma triple_stk_consequence :\n  forall P Q P' Q' i fenv,\n    {{{P}}} i {{{Q}}} @ fenv ->\n    (P' --->>> P) fenv ->\n    (Q --->>> Q') fenv ->\n    {{{P'}}} i {{{Q'}}} @ fenv.\nProof.\n  unfold triple_stk, aimpstk; intros. eauto.\nQed.\n\nTheorem Hoare_stk_sound :\n  forall P i Q fenv,\n    hl_stk P i Q fenv ->\n    {{{P}}} i {{{Q}}} @ fenv.\nProof.\n  induction 1;\n    eauto using triple_stk_skip, triple_stk_assign, triple_stk_seq, triple_stk_ifthenelse, triple_stk_while, triple_stk_consequence, triple_stk_push, triple_stk_pop.\nQed.\n\n  \n\n\n      \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/StackLogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.29201275974412266}}
{"text": "Require Import Coq.omega.Omega.\nRequire Import Platform.AutoSep Platform.Wrap Platform.StringOps Platform.SinglyLinkedList Platform.Malloc Platform.ArrayOps Platform.Bags.\nRequire Import Platform.RelDb Platform.RelDbCondition Platform.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": "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/XmlOutput.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863698, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.29200266230392086}}
{"text": "Require Import Coq.Strings.String.\nRequire Import Coq.FSets.FMapList.\nRequire Import Coq.Structures.OrderedTypeEx.\nRequire Import Coq.Bool.Bvector.\nRequire Import Coq.Numbers.BinNums.\nRequire Import Coq.ZArith.BinIntDef.\nRequire Coq.Strings.String.\n\nRequire Import Monads.Monad.\nRequire Import Monads.Option.\n\nRequire Import Utils.\n\nModule Import MStr := FMapList.Make(String_as_OT).\n\nOpen Scope monad.\n\nInductive lvalue :=\n  | LValName (var: string)\n  | LValMember (base: lvalue) (member: string)\n.\n\nInductive extern :=\n  | Packet (bits: list bool)\n.\n\nInductive value :=\n| ValVoid\n| ValBool (b: bool)\n| ValFixedBit (width: nat) (value: Bvector width)\n| ValVarBit (width: nat) (value: Bvector width)\n| ValFixedInt (width: nat) (n: Z)\n| ValInfInt (n: Z)\n| ValString (s: string)\n| ValArray (arr: list value)\n| ValError (msg: string)\n(* I would rather this was MStr.t value but that is not a strictly\npositive definition. The difference is that [Raw.t value] is\nbasically list (string * value) while MStr.t value is a dependent\nrecord { raw: MStr.Raw.t; sorted: Sorted ...} which includes a proof\nthat the list [raw] is sorted. *)\n| ValRecord (fs: MStr.Raw.t value)\n| ValBuiltinFunc (name: string) (obj: lvalue)\n| ValExternFunc (name: string) (obj: lvalue)\n| ValExternObj (ext: extern)\n| ValHeader (value: header)\n| ValHeaderStack (size: nat) (nextIndex: nat) (elements: list header)\n\n(* unused value types from the OCAML implementation\n\n  | VStruct of\n      { fields : (string * value) list; }\n  | VUnion of\n      { fields : (string * value) list; }\n  | VEnumField of\n      { typ_name : string;\n        enum_name : string; }\n  | VSenumField of\n      { typ_name : string;\n        enum_name : string;\n        v : value; }\n  | VSenum of (string * value) list *)\n\nwith header := MkHeader (valid: bool) (fields: MStr.Raw.t value).\nOpen Scope nat_scope.\n(* TODO: wrap this in a module and call it eqb, and prove that l `eqb` r => l = r *)\nFixpoint eq_value (l: value) (r: value) : bool :=\n  match (l, r) with\n  | (ValVoid, ValVoid) => true\n  | (ValBool b_l, ValBool b_r) => eqb b_l b_r\n  | (ValFixedBit w_l v_l, ValFixedBit w_r v_r) => (Nat.eqb w_l w_r) && (BVeq _ _ v_l v_r)\n  | (ValVarBit w_l v_l, ValVarBit w_r v_r) => (Nat.eqb w_l w_r) && (BVeq _ _ v_l v_r)\n  | (ValFixedInt w_l v_l, ValFixedInt w_r v_r) => (Nat.eqb w_l w_r) && (Z.eqb v_l v_r)\n  | (ValInfInt v_l, ValInfInt v_r) => Z.eqb v_l v_r\n  | (ValString v_l, ValString v_r) => String.eqb v_l v_r\n  | _ => false (* TODO: arrays, errors, records, funcs, headers, headerstacks*)\n  end.\n\nDefinition update_member (obj: value) (member: string) (val: value) : option value :=\n  match obj with\n  | ValRecord map =>\n    let* map' := assoc_update member val map in\n    mret (ValRecord map')\n  | _ => None\n  end.\n", "meta": {"author": "cornell-netlab", "repo": "poulet4", "sha": "148afb626ec0c91ee43d7b624014fe0f21cc1fef", "save_path": "github-repos/coq/cornell-netlab-poulet4", "path": "github-repos/coq/cornell-netlab-poulet4/poulet4-148afb626ec0c91ee43d7b624014fe0f21cc1fef/lib/Value.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.29200266230392086}}
{"text": "Set Implicit Arguments.\n\nRequire Import Coq.Lists.List.\nRequire Import Coq.Relations.Relations.\nRequire Import Common.Types.\nRequire Import Bag.TotalOrder.\nRequire Import Bag.Bag2.\nRequire Import Common.AllDiff.\nRequire Import Common.Bisimulation.\n\nLocal Open Scope list_scope.\nLocal Open Scope equiv_scope.\nLocal Open Scope bag_scope.\n\nModule Type NETWORK_ATOMS.\n\n  Parameter packet : Type.\n  Parameter switchId : Type.\n  Parameter portId : Type.\n  Parameter flowTable : Type.\n  Parameter flowMod : Type.\n\n  Inductive fromController : Type :=\n  | PacketOut : portId -> packet -> fromController\n  | BarrierRequest : nat -> fromController\n  | FlowMod : flowMod -> fromController.\n\n  Inductive fromSwitch : Type :=\n  | PacketIn : portId -> packet -> fromSwitch\n  | BarrierReply : nat -> fromSwitch.\n\n  (** Produces a list of packets to forward out of ports, and a list of packets\n      to send to the controller. *)\n  Parameter process_packet : flowTable -> portId -> packet -> \n    list (portId * packet) * list packet.\n\n  Parameter modify_flow_table : flowMod -> flowTable -> flowTable.\n\n  Parameter packet_le : Relation_Definitions.relation packet.\n  Parameter switchId_le : Relation_Definitions.relation switchId.\n  Parameter portId_le : Relation_Definitions.relation portId.\n  Parameter flowTable_le : Relation_Definitions.relation flowTable.\n  Parameter flowMod_le : Relation_Definitions.relation flowMod.\n  Parameter fromSwitch_le : Relation_Definitions.relation fromSwitch.\n  Parameter fromController_le : Relation_Definitions.relation fromController.\n\n  Declare Instance TotalOrder_packet : TotalOrder packet_le.\n  Declare Instance TotalOrder_switchId : TotalOrder switchId_le.\n  Declare Instance TotalOrder_portId : TotalOrder portId_le.\n  Declare Instance TotalOrder_flowTable : TotalOrder flowTable_le.\n  Declare Instance TotalOrder_flowMod : TotalOrder flowMod_le.\n  Declare Instance TotalOrder_fromSwitch : TotalOrder fromSwitch_le.\n  Declare Instance TotalOrder_fromController : TotalOrder fromController_le.\n\nEnd NETWORK_ATOMS.\n\nModule Type NETWORK_AND_POLICY <: NETWORK_ATOMS.\n\n  Include Type NETWORK_ATOMS.\n\n  Parameter topo : switchId * portId -> option (switchId * portId).\n  Parameter abst_func : switchId -> portId -> packet -> list (portId * packet).\n\nEnd NETWORK_AND_POLICY.\n\n(** Elements of a Featherweight OpenFlow model. *)\nModule Type ATOMS <: NETWORK_AND_POLICY.\n\n  Include NETWORK_AND_POLICY.\n\n  Parameter controller : Type.\n\n  Parameter controller_recv : controller -> switchId -> fromSwitch -> \n    controller -> Prop.\n\n  Parameter controller_step : controller -> controller -> Prop.\n\n  Parameter controller_send : controller ->  controller -> switchId -> \n    fromController -> Prop.\n\nEnd ATOMS.\n\nModule Type MACHINE.\n\n  Declare Module Atoms : ATOMS.\n  Import Atoms.\n\n  Existing Instances TotalOrder_packet TotalOrder_switchId TotalOrder_portId\n    TotalOrder_flowTable TotalOrder_flowMod TotalOrder_fromSwitch\n    TotalOrder_fromController.\n\n  (* Field names have two purposes. Coq creates selectors with these names,\n     and also uses them to generate variable names in proofs. We spend\n     more time in FwOF proofs, so we pick short names here. *)\n  Record switch := Switch {\n    swId : switchId;\n    pts : list portId;\n    tbl : flowTable;\n    inp : bag (PairOrdering portId_le packet_le);\n    outp :  bag (PairOrdering portId_le packet_le);\n    ctrlm : bag fromController_le;\n    switchm : bag fromSwitch_le\n  }.\n\n  Inductive switch_le : switch -> switch -> Prop :=\n  | SwitchLe : forall sw1 sw2,\n      switchId_le (swId sw1) (swId sw2) ->\n      switch_le sw1 sw2.\n\n  (* TODO(arjun): fix *)\n  Declare Instance TotalOrder_switch : TotalOrder switch_le.\n  \n  Record dataLink := DataLink {\n    src : switchId * portId;\n    pks : list packet;\n    dst : switchId * portId\n  }.\n  \n  Record openFlowLink := OpenFlowLink {\n    of_to : switchId;\n    of_switchm : list fromSwitch;\n    of_ctrlm : list fromController\n  }.\n\n  Definition observation := (switchId * portId * packet) %type.\n\n  (* NOTE(arjun): Ask me in person why exactly I picked these levels. *)\n  Reserved Notation \"SwitchStep[ sw ; obs ; sw0 ]\"\n    (at level 70, no associativity).\n  Reserved Notation \"ControllerOpenFlow[ c ; l ; obs ; c0 ; l0 ]\"\n    (at level 70, no associativity).\n  Reserved Notation \"TopoStep[ sw ; link ; obs ; sw0 ; link0 ]\"\n    (at level 70, no associativity).\n  Reserved Notation \"SwitchOpenFlow[ s ; l ; obs ; s0 ; l0 ]\"\n    (at level 70, no associativity).\n\n  Inductive NotBarrierRequest : fromController -> Prop :=\n  | PacketOut_NotBarrierRequest : forall pt pk,\n      NotBarrierRequest (PacketOut pt pk)\n  | FlowMod_NotBarrierRequest : forall fm,\n      NotBarrierRequest (FlowMod fm).\n\n  (** Devices of the same type do not interact in a single\n      step. Therefore, we never have to permute the lists below. If we\n      instead had just one list of all devices, we would have to worry\n      about permuting the list or define symmetric step-rules. *)\n  Record state := State {\n    switches : bag switch_le;\n    links : list dataLink;\n    ofLinks : list openFlowLink;\n    ctrl : controller\n  }.\n\n  Inductive step : state -> option observation -> state -> Prop :=\n  | PktProcess : forall swId pts tbl pt pk inp outp ctrlm switchm outp'\n                        pksToCtrl,\n    process_packet tbl pt pk = (outp', pksToCtrl) ->\n    SwitchStep[\n      Switch swId pts tbl ({|(pt,pk)|} <+> inp) outp ctrlm switchm;\n      Some (swId,pt,pk);\n      Switch swId pts tbl inp (from_list outp' <+> outp) \n        ctrlm (from_list (map (PacketIn pt) pksToCtrl) <+> switchm)\n    ]\n  | ModifyFlowTable : forall swId pts tbl inp outp fm ctrlm switchm,\n    SwitchStep[\n      Switch swId pts tbl inp outp ({|FlowMod fm|} <+> ctrlm) switchm;\n      None;\n      Switch swId pts (modify_flow_table fm tbl) inp outp ctrlm switchm\n    ]\n  (** We add the packet to the output-buffer, even if its port is invalid.\n      Packets with invalid ports will simply accumulate in the output buffer,\n      since the SendDataLink rule only pulls out packets with valid ports.\n      This is reasonable for now. The right fix is to add support for OpenFlow\n      errors. *)\n  | SendPacketOut : forall pt pts swId tbl inp outp pk ctrlm switchm,\n    SwitchStep[\n      Switch swId pts tbl inp outp  ({|PacketOut pt pk|} <+> ctrlm) switchm;\n      None;\n      Switch swId pts tbl inp ({| (pt,pk) |} <+> outp) ctrlm switchm\n    ]\n  | SendDataLink : forall swId pts tbl inp pt pk outp ctrlm switchm pks dst,\n    TopoStep[\n      Switch swId pts tbl inp ({|(pt,pk)|} <+> outp) ctrlm switchm;\n      DataLink (swId,pt) pks dst;\n      None;\n      Switch swId pts tbl inp outp ctrlm switchm;\n      DataLink (swId,pt) (pk :: pks) dst\n    ]\n  | RecvDataLink : forall swId pts tbl inp outp ctrlm switchm src pks pk pt,\n    TopoStep[\n      Switch swId pts tbl inp outp ctrlm switchm;\n      DataLink src  (pks ++ [pk]) (swId,pt);\n      None;\n      Switch swId pts tbl ({|(pt,pk)|} <+> inp) outp ctrlm switchm;\n      DataLink src pks (swId,pt)\n    ]\n  | Step_controller : forall sws links ofLinks ctrl ctrl',\n    controller_step ctrl ctrl' ->\n    step (State sws links ofLinks ctrl)\n         None\n         (State sws links ofLinks ctrl')\n  | ControllerRecv : forall ctrl msg ctrl' swId fromSwitch fromCtrl,\n    controller_recv ctrl swId msg ctrl' ->\n    ControllerOpenFlow[\n      ctrl;\n      OpenFlowLink swId (fromSwitch ++ [msg]) fromCtrl;\n      None;\n      ctrl';\n      OpenFlowLink swId fromSwitch fromCtrl\n    ]\n  | ControllerSend : forall ctrl msg ctrl' swId fromSwitch fromCtrl,\n    controller_send ctrl ctrl' swId msg ->\n    ControllerOpenFlow[\n      ctrl ;\n      (OpenFlowLink swId fromSwitch fromCtrl);\n      None;\n      ctrl';\n      (OpenFlowLink swId fromSwitch (msg :: fromCtrl)) ]\n  | SendToController : forall swId pts tbl inp outp ctrlm msg switchm fromSwitch\n      fromCtrl,\n    SwitchOpenFlow[\n      Switch swId pts tbl inp outp ctrlm ({| msg |} <+> switchm);\n      OpenFlowLink swId fromSwitch fromCtrl;\n      None;\n      Switch swId pts tbl inp outp ctrlm switchm;\n      OpenFlowLink swId (msg :: fromSwitch) fromCtrl\n    ]\n  | RecvBarrier : forall swId pts tbl inp outp switchm fromSwitch fromCtrl\n      xid,\n    SwitchOpenFlow[\n      Switch swId pts tbl inp outp empty switchm;\n      OpenFlowLink swId fromSwitch (fromCtrl ++ [BarrierRequest xid]);\n      None;\n      Switch swId pts tbl inp outp empty\n             ({| BarrierReply xid |} <+> switchm);\n      OpenFlowLink swId fromSwitch fromCtrl\n    ]\n  | RecvFromController : forall swId pts tbl inp outp ctrlm switchm\n      fromSwitch fromCtrl msg,\n    NotBarrierRequest msg ->\n    SwitchOpenFlow[\n      Switch swId pts tbl inp outp ctrlm switchm;\n      OpenFlowLink swId fromSwitch (fromCtrl ++ [msg]);\n      None;\n      Switch swId pts tbl inp outp ({| msg |} <+> ctrlm) switchm;\n      OpenFlowLink swId fromSwitch fromCtrl\n    ]\n      where\n  \"ControllerOpenFlow[ c ; l ; obs ; c0 ; l0 ]\" := \n    (forall sws links ofLinks ofLinks',\n      step (State sws links (ofLinks ++ l :: ofLinks') c) \n           obs \n           (State sws links (ofLinks ++ l0 :: ofLinks') c0))\n    and\n  \"TopoStep[ sw ; link ; obs ; sw0 ; link0 ]\" :=\n    (forall sws links links0 ofLinks ctrl,\n      step \n      (State (({|sw|}) <+> sws) (links ++ link :: links0) ofLinks ctrl)\n      obs\n      (State (({|sw0|}) <+> sws) (links ++ link0 :: links0) ofLinks ctrl))\n    and\n  \"SwitchStep[ sw ; obs ; sw0 ]\" :=\n    (forall sws links ofLinks ctrl,\n      step \n        (State (({|sw|}) <+> sws) links ofLinks ctrl)\n        obs\n        (State (({|sw0|}) <+> sws) links ofLinks ctrl))\n    and\n  \"SwitchOpenFlow[ sw ; of ; obs ; sw0 ; of0 ]\" :=\n    (forall sws links ofLinks ofLinks0 ctrl,\n      step\n        (State (({|sw|}) <+> sws) links (ofLinks ++ of :: ofLinks0) ctrl)\n        obs\n        (State (({|sw0|}) <+> sws) links (ofLinks ++ of0 :: ofLinks0) ctrl)).\n\n  Definition swPtPks : Type :=\n    bag (PairOrdering (PairOrdering switchId_le portId_le)\n                      packet_le).\n\n  Definition abst_state := swPtPks.\n\n  Definition transfer (sw : switchId) (ptpk : portId * packet) :=\n    match ptpk with\n      | (pt,pk) =>\n        match topo (sw,pt) with\n          | Some (sw',pt') => \n            @singleton _ \n               (PairOrdering \n                  (PairOrdering switchId_le portId_le) packet_le)\n               (sw',pt',pk) \n          | None => {| |}\n        end\n    end.\n\n  Definition select_packet_out (sw : switchId) (msg : fromController) :=\n    match msg with\n      | PacketOut pt pk => transfer sw (pt,pk)\n      | _ => {| |}\n    end.\n\n  Definition select_packet_in (sw : switchId) (msg : fromSwitch) :=\n    match msg with\n      | PacketIn pt pk => unions (map (transfer sw) (abst_func sw pt pk))\n      | _ => {| |}\n    end.\n\n  Definition FlowTableSafe (sw : switchId) (tbl : flowTable) : Prop :=\n    forall pt pk forwardedPkts packetIns,\n      process_packet tbl pt pk = (forwardedPkts, packetIns) ->\n      unions (map (transfer sw) forwardedPkts) <+>\n      unions (map (select_packet_in sw) (map (PacketIn pt) packetIns)) =\n      unions (map (transfer sw) (abst_func sw pt pk)).\n\n  Inductive NotFlowMod : fromController -> Prop :=\n  | NotFlowMod_BarrierRequest : forall n, NotFlowMod (BarrierRequest n)\n  | NotFlowMod_PacketOut : forall pt pk, NotFlowMod (PacketOut pt pk).\n\n  Inductive FlowModSafe : switchId -> flowTable -> bag fromController_le -> Prop :=\n  | NoFlowModsInBuffer : forall swId tbl ctrlm,\n      (forall msg, In msg (to_list ctrlm) -> NotFlowMod msg) ->\n      FlowTableSafe swId tbl ->\n      FlowModSafe swId tbl ctrlm\n  | OneFlowModsInBuffer : forall swId tbl ctrlm f,\n      (forall msg, In msg (to_list ctrlm) -> NotFlowMod msg) ->\n      FlowTableSafe swId tbl ->\n      FlowTableSafe swId (modify_flow_table f tbl) ->\n      FlowModSafe swId tbl (({|FlowMod f|}) <+> ctrlm).\n \n  Definition FlowTablesSafe (sws : bag switch_le) : Prop :=\n    forall swId pts tbl inp outp ctrlm switchm,\n      In (Switch swId pts tbl inp outp ctrlm switchm) (to_list sws) ->\n      FlowModSafe swId tbl ctrlm.\n\n  Definition SwitchesHaveOpenFlowLinks (sws : bag switch_le) ofLinks :=\n    forall sw,\n      In sw (to_list sws) ->\n      exists ofLink,\n        In ofLink ofLinks /\\\n        swId sw = of_to ofLink.\n\nEnd MACHINE.\n\nModule Type ATOMS_AND_CONTROLLER.\n\n  Declare Module Machine : MACHINE.\n  Import Machine.\n  Import Atoms.\n\n  Parameter relate_controller : controller -> swPtPks.\n\n  Parameter ControllerRemembersPackets :\n    forall (ctrl ctrl' : controller),\n      controller_step ctrl ctrl' ->\n      relate_controller ctrl = relate_controller ctrl'.\n\n  Parameter P : bag switch_le -> list openFlowLink -> controller -> Prop.\n  \n  Parameter P_entails_FlowTablesSafe : forall sws ofLinks ctrl,\n    P sws ofLinks ctrl ->\n    SwitchesHaveOpenFlowLinks sws ofLinks ->\n    FlowTablesSafe sws.\n  \n  Parameter step_preserves_P : forall sws0 sws1 links0 links1 ofLinks0 ofLinks1 \n    ctrl0 ctrl1 obs,\n    AllDiff of_to ofLinks0 ->\n    AllDiff swId (to_list sws0) ->\n    step (State sws0 links0 ofLinks0 ctrl0)\n         obs\n         (State sws1 links1 ofLinks1 ctrl1) ->\n    P sws0 ofLinks0 ctrl0 ->\n    P sws1 ofLinks1 ctrl1.\n\n  Parameter ControllerSendForgetsPackets : forall ctrl ctrl' sw msg,\n    controller_send ctrl ctrl' sw msg ->\n    relate_controller ctrl = select_packet_out sw msg <+>\n    relate_controller ctrl'.\n\n  Parameter ControllerRecvRemembersPackets : forall ctrl ctrl' sw msg,\n    controller_recv ctrl sw msg ctrl' ->\n    relate_controller ctrl' = select_packet_in sw msg <+> \n    (relate_controller ctrl).\n\n  (** If [(sw,pt,pk)] is a packet in the controller's abstract state,\n      then the controller will eventually emit the packet. *)\n  Parameter ControllerLiveness : forall sw pt pk ctrl0 sws0 links0 \n                                        ofLinks0,\n    In (sw,pt,pk) (to_list (relate_controller ctrl0)) ->\n    exists  ofLinks10 ofLinks11 ctrl1 swTo ptTo switchmLst ctrlmLst,\n      (multistep \n         step (State sws0 links0 ofLinks0 ctrl0) nil\n         (State sws0 links0\n                (ofLinks10 ++ \n                 (OpenFlowLink swTo switchmLst \n                  (PacketOut ptTo pk :: ctrlmLst)) ::\n                 ofLinks11) \n                ctrl1)) /\\\n      select_packet_out swTo (PacketOut ptTo pk) = ({|(sw,pt,pk)|}).\n\n  (** If [m] is a message from the switch to the controller, then the controller\n      will eventually consume [m], adding its packet-content to its state. *)\n  Parameter ControllerRecvLiveness : forall sws0 links0 ofLinks0 sw switchm0 m \n    ctrlm0 ofLinks1 ctrl0,\n     exists ctrl1,\n      (multistep \n         step\n         (State \n            sws0 links0 \n            (ofLinks0 ++ (OpenFlowLink sw (switchm0 ++ [m]) ctrlm0) :: ofLinks1)\n            ctrl0)\n         nil\n         (State \n            sws0 links0 \n            (ofLinks0 ++ (OpenFlowLink sw switchm0 ctrlm0) :: ofLinks1)\n            ctrl1)) /\\\n       exists (lps : swPtPks),\n         (select_packet_in sw m) <+> lps = relate_controller ctrl1.\n\n\nEnd ATOMS_AND_CONTROLLER.\n\nModule Type RELATION_DEFINITIONS.\n\n  Declare Module AtomsAndController : ATOMS_AND_CONTROLLER.\n  Import AtomsAndController.\n  Import Machine.\n  Import Atoms.\n\n  Definition affixSwitch (sw : switchId) (ptpk : portId * packet) :=\n    match ptpk with\n      | (pt,pk) => (sw,pt,pk)\n    end.\n\n  Definition ConsistentDataLinks (links : list dataLink) : Prop :=\n    forall (lnk : dataLink),\n      In lnk links ->\n      topo (src lnk) = Some (dst lnk).\n\n  Definition LinkHasSrc (sws : bag switch_le) (link : dataLink) : Prop :=\n    exists switch,\n      In switch (to_list sws) /\\\n      fst (src link) = swId switch /\\\n      In (snd (src link)) (pts switch).\n\n  Definition LinkHasDst (sws : bag switch_le) (link : dataLink) : Prop :=\n    exists switch,\n      In switch (to_list sws) /\\\n      fst (dst link) = swId switch /\\\n      In (snd (dst link)) (pts switch).\n\n  Definition LinksHaveSrc (sws : bag switch_le) (links : list dataLink) :=\n    forall link, In link links -> LinkHasSrc sws link.\n\n  Definition LinksHaveDst (sws : bag switch_le) (links : list dataLink) :=\n    forall link, In link links -> LinkHasDst sws link.\n\n  Definition UniqSwIds (sws : bag switch_le) := AllDiff swId (to_list sws).\n\n  Definition ofLinkHasSw (sws : bag switch_le) (ofLink : openFlowLink) :=\n    exists sw,\n      In sw (to_list sws) /\\\n      of_to ofLink = swId sw.\n\n  Definition OFLinksHaveSw (sws : bag switch_le) (ofLinks : list openFlowLink) :=\n    forall ofLink, In ofLink ofLinks -> ofLinkHasSw sws ofLink.\n\n  Definition DevicesFromTopo (devs : state) :=\n    forall swId0 swId1 pt0 pt1,\n      Some (swId0,pt0) = topo (swId1,pt1) ->\n      exists sw0 sw1 lnk,\n        (* TODO(arjun): might as well be lists now. *)\n        In sw0 (to_list (switches devs)) /\\ \n        In sw1 (to_list (switches devs)) /\\\n        In lnk (links devs) /\\\n        swId sw0 = swId0 /\\\n        swId sw1 = swId1 /\\\n        src lnk = (swId1,pt1) /\\\n        dst lnk = (swId0, pt0).\n\n  Definition NoBarriersInCtrlm (sws : bag switch_le) :=\n    forall sw,\n      In sw (to_list sws) ->\n      forall m,\n        In m (to_list (ctrlm sw)) ->\n        NotBarrierRequest m.\n\n  Record concreteState := ConcreteState {\n    devices : state;\n    concreteState_flowTableSafety : FlowTablesSafe (switches devices);\n    concreteState_consistentDataLinks : ConsistentDataLinks (links devices);\n    linksHaveSrc : LinksHaveSrc (switches devices) (links devices);\n    linksHaveDst : LinksHaveDst (switches devices) (links devices);\n    uniqSwIds : UniqSwIds (switches devices);\n    ctrlP : P (switches devices) (ofLinks devices) (ctrl devices);\n    uniqOfLinkIds : AllDiff of_to (ofLinks devices);\n    ofLinksHaveSw : OFLinksHaveSw (switches devices) (ofLinks devices);\n    devicesFromTopo : DevicesFromTopo devices;\n    swsHaveOFLinks : SwitchesHaveOpenFlowLinks (switches devices) (ofLinks devices);\n    noBarriersInCtrlm : NoBarriersInCtrlm (switches devices)\n  }.\n\n  Implicit Arguments ConcreteState [].\n\n  Definition concreteStep (st : concreteState) (obs : option observation)\n    (st0 : concreteState) :=\n    step (devices st) obs (devices st0).\n\n  Inductive abstractStep : abst_state -> option observation -> abst_state -> \n    Prop := \n  | AbstractStep : forall sw pt pk lps,\n    abstractStep\n      ({| (sw,pt,pk) |} <+> lps)\n      (Some (sw,pt,pk))\n      (unions (map (transfer sw) (abst_func sw pt pk)) <+> lps).\n\n  Definition relate_switch (sw : switch) : abst_state :=\n    match sw with\n      | Switch swId _ tbl inp outp ctrlm switchm =>\n        from_list (map (affixSwitch swId) (to_list inp)) <+>\n        unions (map (transfer swId) (to_list outp)) <+>\n        unions (map (select_packet_out swId) (to_list ctrlm)) <+>\n        unions (map (select_packet_in swId) (to_list switchm))\n    end.\n\n  Definition relate_dataLink (link : dataLink) : abst_state :=\n    match link with\n      | DataLink _ pks (sw,pt) =>\n        from_list (map (fun pk => (sw,pt,pk)) pks)\n    end.\n\n  Definition relate_openFlowLink (link : openFlowLink) : abst_state :=\n    match link with\n      | OpenFlowLink sw switchm ctrlm =>\n        unions (map (select_packet_out sw) ctrlm) <+>\n        unions (map (select_packet_in sw) switchm)\n    end.\n\n  Definition relate (st : state) : abst_state :=\n    unions (map relate_switch (to_list (switches st))) <+>\n    unions (map relate_dataLink (links st)) <+>\n    unions (map relate_openFlowLink (ofLinks st)) <+>\n    relate_controller (ctrl st).\n\n  Definition bisim_relation : relation concreteState abst_state :=\n    fun (st : concreteState) (ast : abst_state) => \n      ast = (relate (devices st)).\n\nEnd RELATION_DEFINITIONS.\n\nModule Type RELATION.\n\n  Declare Module RelationDefinitions : RELATION_DEFINITIONS.\n  Import RelationDefinitions.\n  Import AtomsAndController.\n  Import Machine.\n  Import Atoms.\n\n  Parameter simpl_multistep : forall (st1 : concreteState) (devs2 : state) obs,\n    multistep step (devices st1) obs devs2 ->\n    exists (st2 : concreteState),\n      devices st2 = devs2 /\\\n      multistep concreteStep st1 obs st2.\n\n  Parameter simpl_weak_sim : forall st1 devs2 sw pt pk lps,\n    multistep step (devices st1) [(sw,pt,pk)] devs2 ->\n    relate (devices st1) = ({| (sw,pt,pk) |} <+> lps) ->\n    abstractStep\n      ({| (sw,pt,pk) |} <+> lps)\n      (Some (sw,pt,pk))\n      (unions (map (transfer sw) (abst_func sw pt pk)) <+> lps) ->\n   exists st2 : concreteState,\n     inverse_relation \n       bisim_relation\n       (unions (map (transfer sw) (abst_func sw pt pk)) <+> lps)\n       st2 /\\\n     multistep concreteStep st1 [(sw,pt,pk)] st2.\n\nEnd RELATION.\n\nModule Type WEAK_SIM_1.\n\n  Declare Module Relation : RELATION.\n  Import Relation.\n  Import RelationDefinitions.\n  Import AtomsAndController.\n  Import Machine.\n  Import Atoms.\n\n  Parameter weak_sim_1 : weak_simulation concreteStep abstractStep bisim_relation.\n\nEnd WEAK_SIM_1.\n\nModule Type WEAK_SIM_2.\n\n  Declare Module Relation : RELATION.\n  Import Relation.\n  Import RelationDefinitions.\n  Import AtomsAndController.\n  Import Machine.\n  Import Atoms.\n  \n  Parameter weak_sim_2 :\n    weak_simulation abstractStep concreteStep (inverse_relation bisim_relation).\n\nEnd WEAK_SIM_2.\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/FwOF/FwOFSignatures.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2920026623039208}}
{"text": "Require Import Mem.\nRequire Import Prog.\nRequire Import List.\nRequire Import Array.\nRequire Import Pred.\nRequire Import FunctionalExtensionality.\nRequire Import Word.\nRequire Import WordAuto.\nRequire Import Omega.\nRequire Import Ring.\nRequire Import SepAuto.\nRequire Import ListUtils.\nRequire Import ListPred.\n\nSet Implicit Arguments.\n\n(**\n * This module is meant to generalize separation logic to arbitrary functions\n * from some address-like thing to some value-like thing.  The motivating use\n * case is in files: we want to think of the disk as a mapping from inode numbers\n * to file objects, where each file object includes metadata and the entire file\n * contents.  Current separation logic is not quite good enough, because we want\n * to have values that are bigger than a 512-byte block.\n *)\n\n(**\n * list2nmem is meant to convert a list representation of files into a memory-like\n * object that maps inode numbers (list positions) into files (or None, if the\n * inode number is too big).  [list2nmem] always uses [nat] as the index.\n *)\nDefinition list2nmem (A: Type) (l: list A) : (@mem nat eq_nat_dec A) :=\n  fun a => selN (map (@Some A) l) a None.\n\nNotation \"[[[ NS ':::' P ]]]\" := [[ (P)%pred (list2nmem NS) ]]%pred : pred_scope.\nNotation \"【 NS '‣‣' P 】\" := [[ (P)%pred (list2nmem NS) ]]%pred : pred_scope.\n\nTheorem list2nmem_oob : forall A (l : list A) i,\n  i >= length l\n  -> (list2nmem l) i = None.\nProof.\n  unfold list2nmem; intros.\n  rewrite selN_oob; auto.\n  rewrite map_length; auto.\nQed.\n\n\nTheorem list2nmem_inbound: forall A F (l : list A) i x,\n  (F * i |-> x)%pred (list2nmem l)\n  -> i < length l.\nProof.\n  intros.\n  destruct (lt_dec i (length l)); auto; exfalso.\n  apply not_lt in n.\n  apply list2nmem_oob in n.\n  apply ptsto_valid' in H.\n  rewrite H in n.\n  inversion n.\nQed.\n\n\nTheorem list2nmem_sel: forall A F (l: list A) i x def,\n  (F * i |-> x)%pred (list2nmem l)\n  -> x = selN l i def.\nProof.\n  intros.\n  assert (i < length l).\n  eapply list2nmem_inbound; eauto.\n  unfold list2nmem in H.\n  apply ptsto_valid' in H.\n  erewrite selN_map in H by auto.\n  inversion H; eauto.\nQed.\n\n\nLemma listupd_memupd: forall A l i (v : A),\n  i < length l\n  -> list2nmem (updN l i v) = Mem.upd (list2nmem l) i v.\nProof.\n  intros.\n  apply functional_extensionality; intro.\n  unfold list2nmem, Mem.upd.\n  autorewrite with core lists.\n\n  destruct (eq_nat_dec x i).\n  subst; erewrite selN_updN_eq; auto.\n  rewrite map_length; auto.\n\n  erewrite selN_updN_ne; auto.\nQed.\n\nTheorem list2nmem_updN: forall A F (l: list A) i x y,\n  (F * i |-> x)%pred (list2nmem l)\n  -> (F * i |-> y)%pred (list2nmem (updN l i y)).\nProof.\n  intros.\n  rewrite listupd_memupd; auto.\n  apply sep_star_comm.\n  apply sep_star_comm in H.\n  eapply ptsto_upd; eauto.\n  eapply list2nmem_inbound; eauto.\nQed.\n\nLemma list2nmem_updN_selN : forall A F (l : list A) a v1 def,\n  (F * a |-> v1)%pred (list2nmem (updN l a v1)) ->\n  (F * a |-> selN l a def)%pred (list2nmem l).\nProof.\n\n  intros.\n  destruct (lt_dec a (length l)).\n\n  eapply list2nmem_updN with (y := selN l a def) in H.\n  rewrite updN_twice in H.\n  rewrite updN_selN_eq in H; auto.\n  apply list2nmem_inbound in H.\n  rewrite length_updN in H.\n  congruence.\nQed.\n\n\nTheorem listapp_memupd: forall A l (a : A),\n  list2nmem (l ++ a :: nil) = Mem.upd (list2nmem l) (length l) a.\nProof.\n  intros.\n  apply functional_extensionality; intro.\n  unfold list2nmem, Mem.upd.\n\n  destruct (lt_dec x (length l)).\n  - subst; rewrite selN_map with (default' := a).\n    destruct (eq_nat_dec x (length l)); subst.\n    + rewrite selN_last; auto.\n    + rewrite selN_map with (default' := a); auto.\n      rewrite selN_app; auto.\n    + rewrite app_length; simpl; omega.\n  - destruct (eq_nat_dec x (length l)).\n    + subst; erewrite selN_map with (default' := a).\n      rewrite selN_last; auto.\n      rewrite app_length; simpl; omega.\n    + repeat erewrite selN_oob with (def := None); try rewrite map_length; auto.\n      omega.\n      rewrite app_length; simpl; intuition.\nQed.\n\nTheorem listapp_meminsert: forall A l (a : A),\n  list2nmem (l ++ a :: nil) = Mem.insert (list2nmem l) (length l) a.\nProof.\n  intros.\n  apply functional_extensionality; intro.\n  unfold list2nmem, Mem.insert.\n\n  destruct (lt_dec x (length l)).\n  - subst; rewrite selN_map with (default' := a) by ( rewrite app_length; omega ).\n    destruct (eq_nat_dec x (length l)); subst.\n    + rewrite selN_last; auto.\n      rewrite selN_oob by ( rewrite map_length; omega ); auto.\n    + rewrite selN_map with (default' := a); auto.\n      rewrite selN_app; auto.\n  - destruct (eq_nat_dec x (length l)).\n    + subst; erewrite selN_map with (default' := a) by ( rewrite app_length; simpl; omega ).\n      rewrite selN_last; auto.\n      rewrite selN_oob by ( rewrite map_length; omega ); auto.\n    + repeat erewrite selN_oob with (def := None); try rewrite map_length; auto.\n      omega.\n      rewrite app_length; simpl; intuition.\nQed.\n\n\nTheorem list2nmem_app: forall A (F : @pred _ _ A) l a,\n  F (list2nmem l)\n  -> (F * (length l) |-> a)%pred (list2nmem (l ++ a :: nil)).\nProof.\n  intros.\n  erewrite listapp_memupd; eauto.\n  apply ptsto_upd_disjoint; auto.\n  unfold list2nmem, selN.\n  rewrite selN_oob; auto.\n  rewrite map_length.\n  omega.\nQed.\n\nTheorem list2nmem_arrayN_app: forall A (F : @pred _ _ A) l l',\n  F (list2nmem l) ->\n  (F * arrayN (@ptsto _ eq_nat_dec A) (length l) l') %pred (list2nmem (l ++ l')).\nProof.\n  intros.\n  generalize dependent F.\n  generalize dependent l.\n  induction l'; intros; simpl.\n  - rewrite app_nil_r.\n    apply emp_star_r.\n    apply H.\n  - apply sep_star_assoc.\n    assert (Happ := list2nmem_app F l a H).\n    assert (IHla := IHl' (l ++ a :: nil) (sep_star F (ptsto (length l) a)) Happ).\n    replace (length (l ++ a :: nil)) with (S (length l)) in IHla.\n    replace ((l ++ a :: nil) ++ l') with (l ++ a :: l') in IHla.\n    apply IHla.\n    rewrite <- app_assoc; reflexivity.\n    rewrite app_length; simpl.\n    symmetry; apply Nat.add_1_r.\nQed.\n\nTheorem list2nmem_removelast_is : forall A l (def : A),\n  l <> nil\n  -> list2nmem (removelast l) =\n     fun i => if (lt_dec i (length l - 1)) then Some (selN l i def) else None.\nProof.\n  intros; apply functional_extensionality; intros.\n  destruct (lt_dec x (length l - 1)); unfold list2nmem.\n  - rewrite selN_map with (default' := def).\n    rewrite selN_removelast by omega; auto.\n    rewrite length_removelast by auto; omega.\n  - rewrite selN_oob; auto.\n    rewrite map_length.\n    rewrite length_removelast by auto.\n    omega.\nQed.\n\n\nTheorem list2nmem_removelast_list2nmem : forall A (l : list A) (def : A),\n  l <> nil\n  -> list2nmem (removelast l) =\n     fun i => if (eq_nat_dec i (length l - 1)) then None else (list2nmem l) i.\nProof.\n  intros; apply functional_extensionality; intros.\n  erewrite list2nmem_removelast_is with (def := def) by eauto.\n  unfold list2nmem.\n  destruct (lt_dec x (length l - 1));\n  destruct (eq_nat_dec x (length l - 1)); subst; intuition.\n  omega.\n  erewrite selN_map with (default' := def); auto.\n  omega.\n  erewrite selN_oob; auto.\n  rewrite map_length.\n  omega.\nQed.\n\n\nLemma mem_disjoint_either: forall AT AEQ V (m1 m2 : @mem AT AEQ V) a v,\n  mem_disjoint m1 m2\n  -> m1 a = Some v -> m2 a = None.\nProof.\n  unfold mem_disjoint; intros; firstorder.\n  pose proof (H a); firstorder.\n  pose proof (H1 v); firstorder.\n  destruct (m2 a); auto.\n  pose proof (H2 v0); firstorder.\nQed.\n\n\nTheorem list2nmem_removelast: forall A F (l : list A) v,\n  l <> nil\n  -> (F * (length l - 1) |-> v)%pred (list2nmem l)\n  -> F (list2nmem (removelast l)).\nProof.\n  unfold_sep_star; unfold ptsto; intuition; repeat deex.\n  assert (m1 = list2nmem (removelast l)); subst; auto.\n  apply functional_extensionality; intros.\n  rewrite list2nmem_removelast_list2nmem; auto.\n\n  destruct (eq_nat_dec x (length l - 1)); subst.\n  apply mem_disjoint_comm in H0. \n  eapply mem_disjoint_either; eauto.\n\n  rewrite H1; unfold mem_union.\n  destruct (m1 x); subst; simpl; auto.\n  apply eq_sym; apply H5; auto.\nQed.\n\nLemma list2nmem_except_last : forall T (l : list T) x,\n  mem_except (list2nmem (l ++ x::nil)) (length l) = list2nmem l.\nProof.\n  unfold mem_except, list2nmem.\n  intros.\n  eapply functional_extensionality; cbn; intros a.\n  destruct Nat.eq_dec.\n  rewrite selN_oob; auto.\n  autorewrite with lists. omega.\n  rewrite map_app; cbn.\n  destruct (lt_dec a (length l)).\n  rewrite selN_app; eauto.\n  autorewrite with lists; eauto.\n  repeat rewrite selN_oob; auto.\n  all: autorewrite with lists; cbn; omega.\nQed.\n\nTheorem list2nmem_array: forall  A (l : list A),\n  arrayN (@ptsto _ eq_nat_dec A) 0 l (list2nmem l).\nProof.\n  induction l using rev_ind; intros; firstorder; simpl.\n  erewrite listapp_memupd; try omega.\n  eapply arrayN_app_memupd; try omega.\n  eauto.\nQed.\n\nTheorem list2nmem_array': forall  A (l l' : list A),\n  l = l' ->\n  arrayN (@ptsto _ eq_nat_dec A) 0 l' (list2nmem l).\nProof.\n  intros; subst; apply list2nmem_array.\nQed.\n\nTheorem list2nmem_arrayN_firstn_skipn: forall A (l:list A) n,\n  (arrayN (@ptsto _ eq_nat_dec A) 0 (firstn n l) *\n   arrayN (@ptsto _ eq_nat_dec A) n (skipn n l))%pred (list2nmem l).\nProof.\n  intros.\n  case_eq (lt_dec n (length l)); intros.\n  - rewrite <- firstn_skipn with (l := l) (n := n) at 3.\n    replace n with (length (firstn n l)) at 2.\n    apply list2nmem_arrayN_app.\n    apply list2nmem_array.\n    apply firstn_length_l; omega.\n  - rewrite firstn_oob by omega.\n    rewrite skipn_oob by omega.\n    eapply pimpl_apply.\n    cancel.\n    apply list2nmem_array.\nQed.\n\nLemma listpred_ptsto_list2nmem: forall T t (l : list T),\n  listpred (fun a => a |->?)%pred t (list2nmem l) ->\n  Permutation.Permutation t (seq 0 (length l)).\nProof.\n  unfold list2nmem.\n  intros.\n  eapply Permutation.NoDup_Permutation.\n  eapply listpred_nodup; eauto.\n  decide equality.\n  intuition.\n  eapply ptsto_conflict; eauto.\n  apply seq_NoDup.\n  split; intros.\n  eapply listpred_remove in H; eauto.\n  destruct_lift H.\n  eapply ptsto_valid in H.\n  eapply in_seq.\n  destruct (lt_dec x (length l)); try omega.\n  rewrite selN_oob in H by (autorewrite with lists; omega).\n  congruence.\n  intros.\n  eauto using ptsto_conflict.\n  destruct (In_dec Nat.eq_dec x t).\n  eapply listpred_remove in H; eauto.\n  eauto using ptsto_conflict.\n  eapply listpred_ptsto_notindomain in H; eauto.\n  cbv [notindomain list2nmem] in *.\n  denote seq as Hs.\n  eapply in_seq in Hs.\n  erewrite selN_map in * by omega.\n  congruence.\nUnshelve.\n  all: try exact Nat.eq_dec.\n  destruct l; cbn in *; eauto; omega.\nQed.\n\n\nLemma arrayN_ptsto_linked: forall S V t l,\n  arrayN (ptsto (V:=S)) 0 l =p=> listpred (fun a => exists v, a |-> v) t ->\n  @listpred _ _ Nat.eq_dec V (fun a => a |->?) (seq 0 (length l)) =p=> listpred (fun a => a |->?) t.\nProof.\n  intros.\n  pose proof list2nmem_array as Hp.\n  eapply H in Hp.\n  eapply listpred_permutation.\n  eapply listpred_ptsto_list2nmem; auto.\nQed.\n\n(* Alternative variants of [list2nmem] that are more induction-friendly *)\nDefinition list2nmem_off (A: Type) (start : nat) (l: list A) : (nat -> option A) :=\n  fun a => if lt_dec a start then None\n                             else selN (map (@Some A) l) (a - start) None.\n\nTheorem list2nmem_off_eq : forall A (l : list A), list2nmem l = list2nmem_off 0 l.\nProof.\n  unfold list2nmem, list2nmem_off; intros.\n  apply functional_extensionality; intros.\n  rewrite <- minus_n_O.\n  reflexivity.\nQed.\n\nFixpoint list2nmem_fix (A : Type) (start : nat) (l : list A) : (nat -> option A) :=\n  match l with\n  | nil => fun a => None\n  | h :: l' => fun a => if eq_nat_dec a start then Some h else list2nmem_fix (S start) l' a\n  end.\n\nLemma list2nmem_fix_below : forall (A : Type) (l : list A) start a,\n  a < start -> list2nmem_fix start l a = None.\nProof.\n  induction l; auto; simpl; intros.\n  destruct (eq_nat_dec a0 start); [omega |].\n  apply IHl; omega.\nQed.\n\nTheorem list2nmem_fix_off_eq : forall A (l : list A) n,\n  list2nmem_off n l = list2nmem_fix n l.\nProof.\n  induction l; intros; apply functional_extensionality; intros.\n  unfold list2nmem_off; destruct (lt_dec x n); auto.\n\n  unfold list2nmem_off; simpl in *.\n\n  destruct (lt_dec x n).\n  destruct (eq_nat_dec x n); [omega |].\n  rewrite list2nmem_fix_below by omega.\n  auto.\n\n  destruct (eq_nat_dec x n).\n  rewrite e; replace (n-n) with (0) by omega; auto.\n\n  assert (x - n <> 0) by omega.\n  destruct (x - n) eqn:Hxn; try congruence.\n\n  rewrite <- IHl.\n  unfold list2nmem_off.\n\n  destruct (lt_dec x (S n)); [omega |].\n  f_equal; omega.\nQed.\n\nTheorem list2nmem_fix_eq : forall A (l : list A),\n  list2nmem l = list2nmem_fix 0 l.\nProof.\n  intros.\n  rewrite list2nmem_off_eq.\n  eapply list2nmem_fix_off_eq.\nQed.\n\nTheorem list2nmem_off_app_union : forall A (a b : list A) start,\n  list2nmem_off start (a ++ b) = @mem_union _ eq_nat_dec A (list2nmem_off start a)\n                                                           (list2nmem_off (start + length a) b).\nProof.\n  intros.\n  repeat rewrite list2nmem_fix_off_eq.\n  generalize dependent b.\n  generalize dependent start.\n  induction a; simpl; intros; apply functional_extensionality; intros.\n  - unfold mem_union. rewrite <- plus_n_O. auto.\n  - unfold mem_union in *.\n    destruct (eq_nat_dec x start); eauto.\n    rewrite IHa.\n    replace (S start + length a0) with (start + S (length a0)) by omega.\n    auto.\nQed.\n\nTheorem list2nmem_off_disjoint : forall A (a b : list A) sa sb,\n  (sb >= sa + length a \\/ sa >= sb + length b) ->\n  @mem_disjoint _ eq_nat_dec A (list2nmem_off sa a) (list2nmem_off sb b).\nProof.\n  unfold mem_disjoint, list2nmem_off, not; intros; repeat deex;\n    destruct (lt_dec a0 sa); destruct (lt_dec a0 sb); try congruence;\n    apply selN_map_some_range in H0;\n    apply selN_map_some_range in H2;\n    omega.\nQed.\n\nLemma list2nmem_nil_array : forall A (l : list A) start,\n  arrayN (@ptsto _ eq_nat_dec A) start l (list2nmem nil) -> l = nil.\nProof.\n  destruct l; simpl; auto.\n  unfold_sep_star; unfold ptsto, list2nmem; simpl; intros.\n  repeat deex.\n  unfold mem_union in H0.\n  apply equal_f with (start) in H0.\n  rewrite H2 in H0.\n  congruence.\nQed.\n\nLemma list2nmem_array_nil : forall A (l : list A) start,\n  arrayN (@ptsto _ eq_nat_dec A) start nil (list2nmem_fix start l) -> l = nil.\nProof.\n  destruct l; simpl; auto.\n  unfold list2nmem, emp; intros.\n  pose proof (H start).\n  destruct (eq_nat_dec start start); simpl in *; congruence.\nQed.\n\nTheorem list2nmem_array_eq': forall A (l' l : list A) start,\n  arrayN (@ptsto _ eq_nat_dec A) start l (list2nmem_fix start l')\n  -> l' = l.\nProof.\n  induction l'; simpl; intros.\n  - erewrite list2nmem_nil_array; eauto.\n  - destruct l.\n    + eapply list2nmem_array_nil with (start:=start).\n      auto.\n    + simpl in *.\n      unfold sep_star in H; rewrite sep_star_is in H; unfold sep_star_impl in H.\n      repeat deex.\n      unfold ptsto in H1; destruct H1.\n      f_equal.\n      * eapply equal_f with (start) in H0 as H0'.\n        unfold mem_union in H0'.\n        rewrite H1 in H0'.\n        destruct (eq_nat_dec start start); congruence.\n      * apply IHl' with (start:=S start); eauto; try omega.\n        assert (m2 = list2nmem_fix (S start) l'); subst; auto.\n\n        apply functional_extensionality; intros.\n        unfold mem_union in H0.\n        apply equal_f with x in H0.\n        destruct (eq_nat_dec x start).\n\n        rewrite list2nmem_fix_below by omega.\n        eapply mem_disjoint_either.\n        eauto.\n        rewrite <- e in H1.\n        eauto.\n\n        rewrite H0.\n        rewrite H2; auto.\nQed.\n\nTheorem list2nmem_array_eq: forall A (l' l : list A),\n  arrayN (@ptsto _ eq_nat_dec A) 0 l (list2nmem l')\n  -> l' = l.\nProof.\n  intros; eapply list2nmem_array_eq' with (start:=0); try rewrite <- plus_n_O; eauto.\n  erewrite <- list2nmem_fix_eq; eauto.\nQed.\n\nTheorem list2nmem_array_mem_eq : forall V (l : list V) m,\n  arrayN (@ptsto _ eq_nat_dec V) 0 l m ->\n  m = list2nmem l.\nProof.\n  intros.\n  apply functional_extensionality.\n  intros.\n  destruct (lt_dec x (length l)).\n  - destruct l; [ simpl in *; omega | ].\n    eapply isolateN_fwd with (i := x) in H; auto.\n\n    assert (m x = Some (selN (v :: l) x v)).\n    eapply ptsto_valid.\n    pred_apply. cancel.\n\n    assert (list2nmem (v :: l) x = Some (selN (v :: l) x v)).\n    eapply ptsto_valid.\n    pose proof (list2nmem_array (v :: l)).\n    pred_apply. rewrite arrayN_isolate with (i := x) by auto. cancel.\n\n    congruence.\n  - eapply arrayN_oob with (i := x) in H; try omega.\n    rewrite list2nmem_oob with (i := x); try omega.\n    auto.\nQed.\n\nTheorem list2nmem_array_app_eq: forall A (l l' : list A) a,\n  (arrayN (@ptsto _ eq_nat_dec A) 0 l * (length l) |-> a)%pred (list2nmem l')\n  -> l' = (l ++ a :: nil).\nProof.\n  intros.\n  rewrite list2nmem_array_eq with (l':=l') (l:=l++a::nil); eauto.\n  pred_apply.\n  rewrite <- isolateN_bwd with (vs:=l++a::nil) (i:=length l) by\n    ( rewrite app_length; simpl; omega ).\n  rewrite firstn_app2 by auto.\n  replace (S (length l)) with (length (l ++ a :: nil)) by (rewrite app_length; simpl; omega).\n  rewrite skipn_oob by omega; simpl.\n  instantiate (1:=a).\n  rewrite selN_last by auto.\n  cancel.\nQed.\n\n\nLemma list2nmem_some_bound' : forall A (m : list A) start off a,\n  list2nmem_fix start m off = Some a\n  -> off + 1 <= start + length m.\nProof.\n  induction m; simpl; intros.\n  congruence.\n  destruct (Nat.eq_dec off start).\n  omega.\n  replace (start + S (length m)) with (S start + length m) by omega.\n  eapply IHm.\n  eauto.\nQed.\n\nLemma list2nmem_some_bound : forall A (m : list A) off a,\n  list2nmem m off = Some a\n  -> off + 1 <= length m.\nProof.\n  intros.\n  rewrite list2nmem_fix_eq in H.\n  apply list2nmem_some_bound' in H.\n  omega.\nQed.\n\nTheorem list2nmem_arrayN_bound : forall A (l m : list A) off F,\n  (F * arrayN (@ptsto _ eq_nat_dec A) off l)%pred (list2nmem m)\n  -> l = nil \\/ off + length l <= length m.\nProof.\n  induction l; simpl; intros.\n  intuition.\n  right.\n  apply sep_star_assoc in H as H'.\n  apply IHl in H'.\n  intuition.\n  subst. simpl.\n  apply sep_star_comm in H.\n  apply sep_star_assoc in H.\n  apply ptsto_valid in H.\n  apply list2nmem_some_bound in H.\n  omega.\nQed.\n\nTheorem list2nmem_arrayN_length : forall A (l m : list A) F,\n  (F * arrayN (@ptsto _ eq_nat_dec A) 0 l)%pred (list2nmem m)\n  -> length l <= length m.\nProof.\n  intros.\n  apply list2nmem_arrayN_bound in H; destruct H; auto.\n  rewrite H; simpl; omega.\nQed.\n\nTheorem list2nmem_ptsto_bound : forall A (l : list A) off v F,\n  (F * off |-> v)%pred (list2nmem l)\n  -> off < length l.\nProof.\n  intros.\n  assert ((F * arrayN (@ptsto _ eq_nat_dec A) off (v :: nil))%pred (list2nmem l)).\n  pred_apply; cancel.\n  apply list2nmem_arrayN_bound in H0. intuition; try congruence.\n  simpl in *; omega.\nQed.\n\n\nDefinition arrayN_ex A VP pts (vs : list A) i : @pred _ _ VP :=\n  (arrayN pts 0 (firstn i vs) *\n   arrayN pts (i + 1) (skipn (S i) vs))%pred.\n\nLemma arrayN_ex_one: forall V VP (pts : _ -> _ -> @pred _ _ VP) (l : list V),\n    List.length l = 1 ->\n    arrayN_ex pts l 0 <=p=> emp.\nProof.\n  destruct l.\n  simpl; intros.\n  congruence.\n  destruct l.\n  simpl. intros.\n  unfold arrayN_ex.\n  simpl.\n  split; cancel.\n  simpl. intros.\n  congruence.\nQed.\n\nTheorem arrayN_except : forall T V (vs : list T) (def : T) i (pts: _ -> _ -> @pred _ _ V),\n  i < length vs\n  -> arrayN pts 0 vs <=p=>\n    (arrayN_ex pts vs i) * (pts i (selN vs i def)).\nProof.\n  intros; unfold arrayN_ex.\n  erewrite arrayN_isolate with (default := def); eauto.\n  simpl.\n  unfold piff; split; cancel.\nQed.\n\nTheorem arrayN_except_upd : forall V T vs (v : T) i (pts : nat -> T -> @pred _ _ V),\n  i < length vs\n  -> arrayN pts 0 (updN vs i v) <=p=>\n    (arrayN_ex pts vs i) * (pts i v).\nProof.\n  intros; unfold arrayN_ex.\n  erewrite isolate_fwd_upd; eauto.\n  simpl.\n  unfold piff; split; cancel.\nQed.\n\nTheorem arrayN_ex_updN_eq : forall T A l i (v : A) (pts : _ -> _ -> @pred _ _ T),\n  arrayN_ex pts (updN l i v) i <=p=>\n  arrayN_ex pts l i.\nProof.\n  unfold arrayN_ex; intros; autorewrite with core lists;\n  split; simpl; rewrite skipn_updN; eauto.\nQed.\n\nTheorem arrayN_mem_upd_none : forall V vs i m (v d : V) (p : nat -> V -> pred),\n  m i = None ->\n  i < length vs ->\n  arrayN_ex p vs i m ->\n  p i (selN vs i d) (fun a => if eq_nat_dec a i then Some v else None) ->\n  arrayN p 0 vs (Mem.upd m i v).\nProof.\n  intros.\n  edestruct arrayN_except as [_ H']; eauto; apply H'; clear H'.\n  unfold_sep_star.\n  repeat eexists; eauto.\n  cbv [Mem.upd mem_union].\n  apply functional_extensionality.\n  intros x. destruct eq_nat_dec; subst.\n  destruct m; congruence.\n  destruct (m x); congruence.\n  intro; repeat deex.\n  destruct eq_nat_dec; congruence.\nQed.\n\n\nTheorem list2nmem_array_pick : forall V l (def : V) i,\n  i < length l\n  -> (arrayN_ex (@ptsto _ eq_nat_dec V) l i * i |-> selN l i def)%pred (list2nmem l).\nProof.\n  intros.\n  eapply arrayN_except; eauto.\n  eapply list2nmem_array; eauto.\nQed.\n\nTheorem list2nmem_array_updN : forall V ol nl (v : V) i,\n  (arrayN_ex (@ptsto _ eq_nat_dec V) ol i * i |-> v)%pred (list2nmem nl)\n  -> i < length ol\n  -> nl = updN ol i v.\nProof.\n  intros.\n  eapply list2nmem_array_eq; autorewrite with core lists; auto.\n  pred_apply.\n  rewrite isolate_fwd_upd; auto.\n  cancel.\nQed.\n\nTheorem list2nmem_array_removelast_eq : forall V (nl ol : list V),\n  (arrayN_ex (@ptsto _ eq_nat_dec V) ol (length ol - 1))%pred (list2nmem nl)\n  -> length ol > 0\n  -> nl = removelast ol.\nProof.\n  unfold arrayN_ex; intros.\n  destruct ol.\n  inversion H0.\n\n  eapply list2nmem_array_eq with (l' := nl); eauto.\n  pred_apply.\n  rewrite firstn_removelast_eq; auto.\n  rewrite skipn_oob by omega.\n  unfold arrayN at 2.\n  clear H; cancel.\nQed.\n\n\nTheorem list2nmem_array_exis : forall V l (def : V) i,\n  (arrayN_ex (@ptsto _ eq_nat_dec V) l i * i |-> selN l i def)%pred (list2nmem l)\n  -> (arrayN_ex (@ptsto _ eq_nat_dec V) l i * i |->?)%pred (list2nmem l).\nProof.\n  intros; pred_apply; cancel.\nQed.\n\n\nLemma list2nmem_ptsto_cancel : forall V i (def : V) l, i < length l ->\n  (arrayN_ex (@ptsto _ eq_nat_dec V) l i * i |-> selN l i def)%pred (list2nmem l).\nProof.\n  intros.\n  assert (arrayN (@ptsto _ eq_nat_dec V) 0 l (list2nmem l)) as Hx by eapply list2nmem_array.\n  pred_apply; erewrite arrayN_except; eauto.\nQed.\n\nLemma list2nmem_ptsto_cancel_pair : forall A B i (def : A * B) l,\n  i < length l ->\n  (arrayN_ex (@ptsto _ eq_nat_dec (A * B)) l i * \n    i |-> (fst (selN l i def), snd (selN l i def)))%pred (list2nmem l).\nProof.\n  intros.\n  assert (arrayN (@ptsto _ eq_nat_dec (A * B)) 0 l (list2nmem l)) as Hx by eapply list2nmem_array.\n  pred_apply; erewrite arrayN_except; eauto.\n  rewrite <- surjective_pairing.\n  cancel.\nQed.\n\nLemma list2nmem_sel_for_eauto : forall V A i (v v' : V) l def,\n  (A * i |-> v)%pred (list2nmem l)\n  -> v' = selN l i def\n  -> v' = v.\nProof.\n  intros.\n  apply list2nmem_sel with (def:=def) in H.\n  congruence.\nQed.\n\nLemma arrayN_combine' : forall A VP (pts : _ -> _ -> @pred _ _ VP) (a b : list A) start,\n  arrayN pts start a * arrayN pts (start + length a) b <=p=> arrayN pts start (a ++ b).\nProof.\n  induction a; simpl; intros.\n  - replace (start + 0) with start by omega.\n    split; cancel.\n  - rewrite sep_star_assoc.\n    apply piff_star_l.\n    replace (start + S (length a0)) with (S start + length a0) by omega.\n    apply IHa.\nQed.\n\nLemma arrayN_combine : forall A VP (pts : _ -> _ -> @pred _ _ VP) (a b : list A) start off,\n  off = start + length a ->\n  arrayN pts start a * arrayN pts off b <=p=> arrayN pts start (a ++ b).\nProof.\n  intros; subst.\n  apply arrayN_combine'.\nQed.\n\n\nLemma arrayN_list2nmem : forall A (def : A) (a b : list A) F off,\n  (F * arrayN (@ptsto _ eq_nat_dec A) off a)%pred (list2nmem b) ->\n  a = firstn (length a) (skipn off b).\nProof.\n  induction a; simpl; intros; auto.\n  rewrite skipn_selN_skipn with (def:=def).\n  f_equal.\n  eapply list2nmem_sel.\n  pred_apply. cancel.\n  eapply IHa.\n  pred_apply. cancel.\n  eapply list2nmem_ptsto_bound.\n  pred_apply. cancel.\nQed.\n\nTheorem list2nmem_ptsto_end_eq : forall A (F : @pred _ _ A) l a a',\n  (F * (length l) |-> a)%pred (list2nmem (l ++ a' :: nil)) ->\n  a = a'.\nProof.\n  intros.\n  apply list2nmem_sel with (def:=a) in H.\n  rewrite selN_last in H; auto.\nQed.\n\nTheorem list2nmem_arrayN_end_eq : forall A (F : @pred _ _ A) l l' l'' (def:A),\n  length l' = length l'' ->\n  (F * arrayN (@ptsto _ eq_nat_dec A) (length l) l')%pred (list2nmem (l ++ l'')) ->\n  l' = l''.\nProof.\n  intros.\n  apply arrayN_list2nmem in H0.\n  rewrite skipn_app in H0.\n  rewrite firstn_oob in H0.\n  auto.\n  omega.\n  exact def.\nQed.\n\nTheorem list2nmem_off_arrayN: forall A (l : list A) off,\n  arrayN (@ptsto _ eq_nat_dec A) off l (list2nmem_off off l).\nProof.\n  intros; rewrite list2nmem_fix_off_eq.\n  generalize dependent off; induction l; simpl; intros.\n  - firstorder.\n  - apply sep_star_comm. eapply ptsto_upd_disjoint; eauto.\n    apply list2nmem_fix_below.\n    omega.\nQed.\n\nTheorem list2nmem_arrayN_app_iff : forall A (F : @pred _ _ A) l l',\n  (F * arrayN (@ptsto _ eq_nat_dec A) (length l) l')%pred (list2nmem (l ++ l')) ->\n  F (list2nmem l).\nProof.\n  intros.\n  rewrite list2nmem_off_eq in *.\n  rewrite list2nmem_off_app_union in H.\n  eapply septract_sep_star.\n  2: unfold septract; eexists; intuition.\n  4: pred_apply' H; cancel.\n  apply strictly_exact_to_exact_domain.\n  apply arrayN_strictly_exact.\n  apply list2nmem_off_disjoint; intuition.\n  apply list2nmem_off_arrayN.\nQed.\n\n\nLemma mem_except_list2nmem_oob : forall A (l : list A) a,\n  a >= length l ->\n  mem_except (list2nmem l) a = list2nmem l.\nProof.\n  unfold mem_except, list2nmem; intros.\n  apply functional_extensionality; intro.\n  destruct (Nat.eq_dec x a); subst; simpl; auto.\n  erewrite selN_oob; auto.\n  autorewrite with lists in *; omega.\nQed.\n\nLemma list2nmem_sel_inb : forall A (l : list A) a def,\n  a < length l ->\n  list2nmem l a = Some (selN l a def).\nProof.\n  induction l using rev_ind; intros.\n  inversion H.\n  rewrite listapp_memupd.\n\n  destruct (Nat.eq_dec a (length l)); subst.\n  rewrite upd_eq; auto.\n  rewrite selN_last; auto.\n  rewrite upd_ne; auto.\n  rewrite app_length in H; simpl in H.\n  erewrite IHl by omega.\n  rewrite selN_app1 by omega; auto.\nQed.\n\n\nLemma sep_star_reorder_helper1 : forall AT AEQ V (a b c d : @pred AT AEQ V),\n  (a * ((b * c) * d)) <=p=> (a * b * d) * c.\nProof.\n  intros; split; cancel.\nQed.\n\nLemma list2nmem_arrayN_updN : forall V F a vl l i (v : V),\n  (F * arrayN (@ptsto _ eq_nat_dec V) a vl)%pred (list2nmem l) ->\n  i < length vl ->\n  (F * arrayN (@ptsto _ eq_nat_dec V) a (updN vl i v))%pred (list2nmem (updN l (a + i) v)).\nProof.\n  intros.\n  rewrite arrayN_isolate with (i:=i) (default := v) by (rewrite length_updN; auto).\n  rewrite selN_updN_eq by auto.\n  rewrite firstn_updN_oob by auto.\n  rewrite skipN_updN' by auto.\n  apply sep_star_reorder_helper1.\n  eapply list2nmem_updN with (x := selN vl i v).\n  apply sep_star_reorder_helper1.\n  rewrite <- arrayN_isolate; auto.\nQed.\n\n\nLemma listmatch_ptsto_list2nmem_inbound : forall VT al vl (F : @pred _ _ VT) m ,\n  (F * listmatch (fun a v => a |-> v) al vl)%pred (list2nmem m) ->\n  Forall (fun a => a < length m) al.\nProof.\n  induction al; intros.\n  apply Forall_nil.\n  unfold listmatch in H; destruct vl; destruct_lift H.\n  inversion H1.\n  apply Forall_cons.\n  eapply list2nmem_ptsto_bound.\n  pred_apply; cancel.\n  eapply IHal with (vl := vl).\n  pred_apply.\n  unfold listmatch; cancel.\nQed.\n\n\nLemma list2nmem_inj' : forall A (a b : list A) n,\n  list2nmem_off n a = list2nmem_off n b ->\n  a = b.\nProof.\n  intros.\n  repeat rewrite list2nmem_fix_off_eq in H.\n  revert H. revert a b n.\n  induction a; destruct b; simpl; firstorder.\n  eapply equal_f with (x := n) in H; simpl in H.\n  destruct (Nat.eq_dec n n); congruence.\n  eapply equal_f with (x := n) in H.\n  destruct (Nat.eq_dec n n); congruence.\n  erewrite IHa with (b := b) (n := S n).\n  eapply equal_f with (x := n) in H.\n  destruct (Nat.eq_dec n n); try congruence.\n\n  apply functional_extensionality; intros.\n  destruct (Nat.eq_dec x n); subst.\n  repeat rewrite list2nmem_fix_below; auto.\n  eapply equal_f with (x0 := x) in H.\n  destruct (Nat.eq_dec x n); try congruence.\nQed.\n\n\nLemma list2nmem_inj : forall A (a b : list A),\n  list2nmem a = list2nmem b ->  a = b.\nProof.\n  intros.\n  apply list2nmem_inj' with (n := 0).\n  repeat rewrite <- list2nmem_off_eq; auto.\nQed.\n\n\n(* crashes *)\n\nRequire Import PredCrash AsyncDisk.\nImport ListNotations.\n\nLemma list2nmem_crash_xform : forall vl vsl (F : rawpred),\n  possible_crash_list vsl vl ->\n  F (list2nmem vsl) ->\n  crash_xform F (list2nmem (synced_list vl)).\nProof.\n  induction vl using rev_ind; simpl; intuition.\n  unfold crash_xform, possible_crash; eexists; intuition.\n  setoid_rewrite length_nil in H0; auto.\n  apply possible_crash_list_length in H; auto.\n\n  unfold crash_xform, possible_crash.\n  eexists; intuition. eauto.\n  destruct H as [H Hx].\n  destruct (lt_eq_lt_dec a (length vl)).\n  destruct s.\n  assert (a < length vsl).\n  rewrite H; autorewrite with lists; simpl; omega.\n\n  right.\n  exists (selN vsl a ($0, nil)).\n  exists (selN vl a $0); intuition.\n  apply selN_map; auto.\n  unfold list2nmem, synced_list.\n  erewrite selN_map.\n  rewrite selN_combine, selN_app1, repeat_selN; auto.\n  autorewrite with lists; simpl; omega.\n  autorewrite with lists; auto.\n  rewrite combine_length_eq; autorewrite with lists; simpl; omega.\n  specialize (Hx a H1).\n  rewrite selN_app1 in Hx; auto.\n\n  right; subst.\n  eexists; exists x; intuition.\n  autorewrite with lists in H; simpl in H.\n  unfold list2nmem; erewrite selN_map by omega; eauto.\n  unfold list2nmem; rewrite synced_list_app.\n  erewrite selN_map, selN_app2.\n  rewrite synced_list_length, Nat.sub_diag; auto.\n  rewrite synced_list_length; auto.\n  rewrite app_length, synced_list_length; simpl; omega.\n  rewrite app_length in H; simpl in H.\n  assert (length vl < length vsl) as Hy by omega.\n  specialize (Hx (length vl) Hy).\n  rewrite selN_app2, Nat.sub_diag in Hx by omega; simpl in Hx.\n  unfold vsmerge; eauto.\n\n  left; split.\n  rewrite app_length in H; simpl in H.\n  unfold list2nmem; erewrite selN_oob; auto.\n  rewrite map_length; omega.\n  unfold list2nmem; erewrite selN_oob; auto.\n  rewrite map_length, synced_list_length, app_length; simpl; omega.\n  Unshelve. all: eauto.\nQed.\n\n\nLemma crash_xform_list2nmem_possible_crash_list : forall vl (F : rawpred),\n  crash_xform F (list2nmem vl) ->\n  exists vsl, F (list2nmem vsl) /\\ possible_crash_list vsl (map fst vl).\nProof.\n  unfold crash_xform.\n  induction vl using rev_ind; intros; auto.\n  exists nil; deex.\n  replace (list2nmem nil) with m'; auto.\n  apply functional_extensionality; intro.\n  specialize (H1 x).\n  destruct H1; destruct H.\n  rewrite H; auto.\n  deex; unfold list2nmem in H; simpl in *; congruence.\n  unfold possible_crash_list; intuition.\n  inversion H.\n\n  deex.\n\n  (* Figure out [m' (length vl)] *)\n  case_eq (m' (length vl)); [ intro p | ]; intro Hp.\n  specialize (IHvl (pred_except F (length vl) p)).\n  rewrite listapp_memupd in H1.\n\n  pose proof (possible_crash_upd_mem_except H1) as Hx.\n  rewrite mem_except_list2nmem_oob in Hx by auto.\n  specialize (H1 (length vl)); destruct H1.\n  contradict H; rewrite upd_eq by auto.\n  intuition congruence.\n  repeat deex.\n\n  eapply pred_except_mem_except in H0 as Hy.\n  destruct IHvl as [ ? Hz ].\n  eexists; eauto.\n  destruct Hz as [ Hz [ Heq HP ] ].\n  rewrite map_length in Heq.\n\n  unfold pred_except in Hz.\n  rewrite <- Heq in Hz.\n  rewrite <- listapp_meminsert in Hz; intuition.\n  eexists; split; eauto.\n\n  split; autorewrite with lists; simpl; intros.\n  repeat rewrite app_length; omega.\n  destruct (lt_dec i (length x0)); repeat rewrite map_app.\n  setoid_rewrite selN_app1; try rewrite map_length; try omega.\n  apply HP; auto.\n  setoid_rewrite selN_app2; try rewrite map_length; try omega.\n  rewrite <- Heq; replace (i - length x0) with 0 by omega; simpl.\n  rewrite upd_eq in H by auto.\n  destruct x; inversion H; subst; simpl.\n  rewrite Hp in H1; inversion H1; subst.\n  eauto.\n  eauto.\n\n  specialize (H1 (length vl)); destruct H1.\n  destruct H; contradict H1.\n  rewrite listapp_memupd, upd_eq; auto; congruence.\n  repeat deex; congruence.\nQed.\n\n\nLemma crash_xform_list2nmem_synced : forall vl (F : rawpred),\n  crash_xform F (list2nmem vl) ->\n  map snd vl = repeat (@nil valu) (length vl).\nProof.\n  unfold crash_xform.\n  induction vl using rev_ind; intros; auto.\n  deex; rewrite map_app.\n\n  pose proof (H1 (length vl)) as Hx; destruct Hx.\n  destruct H as [ H Hx ]; contradict Hx.\n  rewrite listapp_memupd, upd_eq by auto; congruence.\n  repeat deex; auto.\n  rewrite listapp_memupd, upd_eq in H by auto; inversion H; subst.\n\n  erewrite IHvl; simpl.\n  rewrite app_length; simpl.\n  rewrite <- repeat_app_tail.\n  f_equal; omega.\n  exists (mem_except m' (length vl)).\n  intuition.\n\n  apply pred_except_mem_except; eauto.\n  replace (list2nmem vl) with (mem_except (list2nmem (vl ++ [(v', nil)])) (length vl)).\n  apply possible_crash_mem_except; eauto.\n  rewrite listapp_memupd.\n  rewrite <- mem_except_upd.\n  rewrite mem_except_list2nmem_oob; auto.\nQed.\n\n\nLemma crash_xform_list2nmem_list_eq : forall F vsl vl,\n  crash_xform F (list2nmem vsl) ->\n  possible_crash_list vsl vl ->\n  vsl = synced_list vl.\nProof.\n  intros.\n  destruct H0 as [Heq Hx].\n  apply crash_xform_list2nmem_synced in H.\n  apply list_selN_ext with (default := ($0, nil)); intros.\n  rewrite synced_list_length; auto.\n  rewrite synced_list_selN.\n  specialize (Hx _ H0); unfold vsmerge in Hx.\n  rewrite surjective_pairing at 1.\n  erewrite <- selN_map with (f := snd) in * by auto.\n  rewrite H in *.\n  rewrite repeat_selN in * by auto.\n  simpl in *; intuition.\n  rewrite <- H1; simpl; auto.\n  Unshelve. all: eauto.\nQed.\n\nLemma possible_crash_list2nmem_cons : forall l l' x y,\n  possible_crash (list2nmem (x :: l)) (list2nmem (y :: l'))\n  -> possible_crash (list2nmem l) (list2nmem l').\nProof.\n  intros.\n  unfold possible_crash; intros.\n  destruct (le_dec (length l) a);\n  destruct (le_dec (length l') a).\n  left.\n  split;\n  apply list2nmem_oob; omega.\n\n  unfold possible_crash in H;\n  specialize (H (S a)); intuition.\n  unfold possible_crash in H;\n  specialize (H (S a)); intuition.\n\n  unfold possible_crash in H;\n  specialize (H (S a)); intuition.\nQed.\n\nLemma possible_crash_list2nmem_length : forall l l',\n  possible_crash (list2nmem l) (list2nmem l')\n  -> length l = length l'.\nProof.\n  induction l; destruct l'; intros; simpl; auto.\n\n  unfold possible_crash in H.\n  specialize (H 0); intuition.\n  inversion H1.\n  repeat deex.\n  inversion H0.\n\n  unfold possible_crash in H.\n  specialize (H 0); intuition.\n  inversion H.\n  repeat deex.\n  inversion H.\n\n  erewrite IHl; eauto.\n  eapply possible_crash_list2nmem_cons; eauto.\nQed.\n\n\nLemma possible_crash_list2nmem_vssync : forall a d m,\n  possible_crash (list2nmem (vssync d a)) m ->\n  possible_crash (list2nmem d) m.\nProof.\n  unfold vssync; intros.\n  destruct (lt_dec a (length d)).\n  rewrite listupd_memupd in H by auto.\n  eapply possible_crash_upd_nil; eauto.\n  apply list2nmem_sel_inb; auto.\n  rewrite updN_oob in H; auto; omega.\nQed.\n\nLemma possible_crash_list2nmem_vssync_vecs : forall al d m,\n  possible_crash (list2nmem (vssync_vecs d al)) m ->\n  possible_crash (list2nmem d) m.\nProof.\n  induction al using rev_ind; simpl; auto; intros.\n  rewrite vssync_vecs_app in H.\n  apply IHal.\n  eapply possible_crash_list2nmem_vssync; eauto.\nQed.\n\nLemma crash_xform_diskIs_vssync_vecs : forall al d,\n  crash_xform (diskIs (list2nmem (vssync_vecs d al))) =p=>\n  crash_xform (diskIs (list2nmem d)).\nProof.\n  intros.\n  rewrite crash_xform_diskIs; cancel.\n  rewrite <- crash_xform_diskIs_r; eauto.\n  eapply possible_crash_list2nmem_vssync_vecs; eauto.\nQed.\n\nLemma setlen_singleton : forall T l (v : T),\n  setlen l 1 v = [ selN (setlen l 1 v) 0 v ].\nProof.\n  unfold setlen.\n  destruct l; simpl in *; congruence.\nQed.\n\nLemma setlen_singleton_ptsto : forall (l : list valuset),\n  let l' := setlen l 1 ($0, nil) in\n  (0 |-> selN l' 0 ($0, nil))%pred (list2nmem l').\nProof.\n  intros; subst l'.\n  eapply arrayN_one.\n  rewrite <- setlen_singleton.\n  apply list2nmem_array.\nQed.\n\nLemma ptsto_0_list2nmem_mem_eq : forall V v (d : list V),\n  (0 |-> v)%pred (list2nmem d) -> d = [v].\nProof.\n  intros.\n  apply list2nmem_inj.\n  eapply ptsto_complete. eauto.\n  unfold ptsto, list2nmem; simpl; intuition.\n  destruct a'; try congruence.\nQed.\n\nLemma ptsto_a_list2nmem_a0 : forall V v (d : list V) a,\n  (a |-> v)%pred (list2nmem d) -> a = 0.\nProof.\n  destruct a; eauto.\n  intros; exfalso.\n  unfold list2nmem, ptsto in *; intuition.\n  destruct d.\n  {\n    simpl in *.\n    congruence.\n  }\n  {\n    assert (S a = 0 -> False) by omega.\n    specialize (H1 0 H); simpl in *.\n    congruence.\n  }\nQed.\n\nLemma ptsto_a_list2nmem_mem_eq : forall V v (d : list V) a,\n  (a |-> v)%pred (list2nmem d) -> d = [v].\nProof.\n  intros.\n  eapply ptsto_a_list2nmem_a0 in H as H'; subst.\n  eapply ptsto_0_list2nmem_mem_eq; eauto.\nQed.\n\nTheorem arrayN_pimpl : forall V m (F : @pred addr addr_eq_dec V) l,\n  F m ->\n  arrayN (@ptsto _ _ _) 0 l m ->\n  arrayN (@ptsto _ _ _) 0 l =p=> F.\nProof.\n  unfold pimpl; intros.\n  eapply list2nmem_array_mem_eq in H0.\n  eapply list2nmem_array_mem_eq in H1.\n  congruence.\nQed.\n\nLemma pred_except_ptsto_pimpl : forall V (l : list V) off v F,\n  (F * off |-> v)%pred (list2nmem l) ->\n  pred_except (arrayN (@ptsto _ _ _) 0 l) off v =p=> F.\nProof.\n  unfold pimpl; intros.\n  apply pred_except_ptsto_pimpl in H.\n  apply H.\n  pred_apply.\n  apply pred_except_pimpl_proper; auto.\n  unfold pimpl; intros.\n  apply list2nmem_array_mem_eq in H1; subst.\n  firstorder.\nQed.\n\nLemma arrayN_notindomain_before : forall V (l : list V) start off,\n  off < start ->\n  arrayN (@ptsto _ _ V) start l =p=> notindomain off.\nProof.\n  induction l; simpl; intros.\n  apply emp_pimpl_notindomain.\n  eapply sep_star_notindomain.\n  eapply ptsto_notindomain; omega.\n  eauto.\nQed.\n\nLemma arrayN_notindomain_after : forall V (l : list V) start off,\n  start + length l <= off ->\n  arrayN (@ptsto _ _ V) start l =p=> notindomain off.\nProof.\n  induction l; simpl; intros.\n  apply emp_pimpl_notindomain.\n  eapply sep_star_notindomain.\n  eapply ptsto_notindomain; omega.\n  eapply IHl; omega.\nQed.\n\nLemma arrayN_ex_notindomain : forall V (l : list V) off,\n  arrayN_ex (@ptsto _ _ V) l off ⇨⇨ notindomain off.\nProof.\n  unfold arrayN_ex; intros.\n  apply sep_star_notindomain.\n  apply arrayN_notindomain_after.\n  rewrite firstn_length. simpl. apply Min.le_min_l.\n  apply arrayN_notindomain_before.\n  omega.\nQed.\n\nTheorem arrayN_ex_pred_except : forall V (l : list V) off def,\n  off < length l ->\n  arrayN_ex (@ptsto _ _ _) l off =p=>\n  pred_except (arrayN (@ptsto _ _ _) 0 l) off (selN l off def).\nProof.\n  intros.\n  rewrite arrayN_except with (i := off) by omega.\n  rewrite <- pred_except_sep_star_ptsto_notindomain; auto.\n  apply arrayN_ex_notindomain.\nQed.\n\nLemma arrayN_ex_frame_pimpl : forall V (l : list V) off v F,\n  (F * off |-> v)%pred (list2nmem l) ->\n  arrayN_ex (@ptsto _ _ _) l off =p=> F.\nProof.\n  intros.\n  eapply pimpl_trans; [ | eapply pred_except_ptsto_pimpl; eauto ].\n  eapply list2nmem_sel with (def := v) in H as H'; rewrite H'.\n  apply arrayN_ex_pred_except.\n  eapply list2nmem_ptsto_bound; eauto.\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/GenSepN.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863695, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2920026623039208}}
{"text": "(** * Definition of grammar for expressions involving parentheses *)\nRequire Import Fiat.Parsers.ContextFreeGrammar.Notations.\n\nDefinition paren_expr_grammar : grammar Ascii.ascii :=\n  [[[ \"expr\" ::== \"number\" || \"(\" \"expr\" \")\";;\n      \"number\" ::== [0-9] || [0-9] \"number\"\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/Parsers/Grammars/ExpressionParen.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.29196919653970865}}
{"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 RunAux.Spec.\nRequire Import RunComplete.Specs.complete_hvc_exit.\nRequire Import RunComplete.LowSpecs.complete_hvc_exit.\nRequire Import RunComplete.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_last_run_info_esr_spec\n       set_rec_regs_spec\n       get_rec_run_gprs_spec\n       reset_last_run_info_spec\n    .\n\n  Lemma complete_hvc_exit_spec_exists:\n    forall habd habd'  labd rec\n           (Hspec: complete_hvc_exit_spec rec habd = Some habd')\n            (Hrel: relate_RData habd labd),\n    exists labd', complete_hvc_exit_spec0 rec labd = Some labd' /\\ relate_RData habd' labd'.\n    Proof.\n      intros. destruct Hrel. destruct rec. Local Transparent Z.add.\n      unfold complete_hvc_exit_spec, complete_hvc_exit_spec0 in *.\n      repeat autounfold in *. simpl in *.\n      hsimpl_hyp Hspec; inv Hspec; simpl_query_oracle; extract_prop_dec;\n        repeat destruct_con; simpl in *; srewrite; repeat simpl_update_reg;\n          repeat (simpl_htarget; grewrite; simpl in * ).\n      unfold ref_accessible in *. autounfold.\n      repeat (grewrite; try rewrite ZMap.gss; try rewrite ZMap.set2; simpl; grewrite; simpl).\n      eexists; split. reflexivity. constructor. repeat (repeat simpl_field; repeat swap_fields).\n      repeat simpl_update_reg. reflexivity.\n      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/RunComplete/RefProof/complete_hvc_exit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631556226292, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2919691897119805}}
{"text": "Require Import Coq.Init.Peano.\nRequire Import Notations.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Numbers.Natural.Peano.NPeano.\nRequire Import Coq.omega.Omega.\nRequire Import Coq.Arith.Le.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import Coq.Numbers.NatInt.NZMul.\nRequire Import Coq.Structures.OrdersFacts.\nRequire Import Coq.ZArith.Znat. \nRequire Import Coq.QArith.QArith_base.\nRequire Import  Coq.QArith.QOrderedType.\nRequire Import QArith_base Equalities Orders OrdersTac.\nRequire Import Coq.Sorting.Permutation.\nRequire Import Wf.\nRequire Import Lexicographic_Product.\nRequire Import Qreduction.\nRequire Import Coq.Bool.Bool.\nRequire Import Inverse_Image. \nRequire Import Coq.Bool.Sumbool.\nRequire Import Coq.Sorting.Mergesort.\nImport ListNotations.\nRequire Import Coq.Program.Basics.\nRequire Import Coq.Arith.Wf_nat.\nRequire Import Program.\nRequire Import  Recdef.\nAdd LoadPath \"/home/users/u5711205/Modular-STVCalculi/\".\nRequire Export Parameters.\nRequire Import FrameBase.\nAdd LoadPath \"/home/users/u5711205/Modular-STVCalculi/ActSTV\".\nRequire Export Instantiation.\nImport Instantiate.\nImport M.\nImport QSort.\n\n(*Module Act.*)\n\nSection ACT.\n\n\nDefinition ACT_InitStep (prem :Machine_States) (conc :Machine_States): Prop :=\n exists ba ba',  \n  ((prem = (initial  ba)) /\\\n  (ba' = (Filter ba)) /\\\n  (conc = state  (ba', [nty], nas, (nbdy, nbdy), emp_elec , all_hopeful))).\n\nDefinition ACT_count (prem: Machine_States) (conc: Machine_States) : Prop :=\n exists ba t nt p np bl h e,                (** count the ballots requiring attention **)\n  prem = state (ba, t, p, bl, e, h) /\\     (* if we are in an intermediate state of the count *) \n  [] <> ba /\\                                        (* and there are ballots requiring attention *)\n  (forall c, if (cand_in_dec c (proj1_sig h)) \n      then \n  (exists l,                     \n    np(c) = p(c) ++ [l] /\\                       \n    (forall b, In (proj1_sig (fst b)) (map (fun (d:ballot) => (proj1_sig (fst d))) l) <-> \n                                                               fcc ba (proj1_sig h) c b) /\\ \n    (nt (c) = SUM (np(c)))) \n      else ((nt c) = (hd nty t) c) /\\ (np c) = (p c)) /\\                 \n  conc = state ([], nt :: t, np, bl, e, h).     \n\nDefinition ACT_hwin (prem: Machine_States) (conc: Machine_States) : Prop :=\n  exists w ba t p bl e h,                            \n   prem = state (ba, t, p, bl, e, h) /\\           \n   length (proj1_sig e) + length (proj1_sig h) <= st /\\ \n   w = (proj1_sig e) ++ (proj1_sig h) /\\                        \n   conc = winners (w).\n\nDefinition ACT_ewin (prem: Machine_States) (conc: Machine_States) : Prop :=\n  exists w ba t p bl e h,                    (** elected win **)\n   prem = state (ba, t, p, bl, e, h) /\\   (* if at any time *)\n   length (proj1_sig e) = st /\\             (* we have as many elected candidates as seats *) \n   w = (proj1_sig e) /\\                        (* and the winners are precisely the electeds *)\n   conc = winners (w).                      (* they are declared the winners *)\n\nDefinition ACT_elim (prem: Machine_States) (conc: Machine_States) : Prop :=\n  exists nba t p np bl2 e h nh,                    \n   prem = state ([], t, p, ([], bl2), e, h) /\\         \n   length (proj1_sig e) + length (proj1_sig h) > st /\\ \n   (forall c, In c (proj1_sig h) -> (hd nty t(c) < quota)%Q) /\\ \n   exists c,                                            \n     ((forall d, In d (proj1_sig h) -> (hd nty t(c) <= hd nty t(d)))%Q /\\            \n     eqe c (proj1_sig nh) (proj1_sig h) /\\                                   \n     nba = flat_map (fun x => x) (p c) /\\                                   \n     np(c)=[] /\\                                       \n     (forall d, d <> c -> np (d) = p (d)) /\\                       \n   conc = state (nba, t, np, ([], []), e, nh)). \n\nDefinition ACT_TransferElected (prem: Machine_States) (conc: Machine_States) : Prop :=\n exists nba t p np bl nbl h e,\n  prem = state ([], t, p, bl, e, h) /\\\n  (length (proj1_sig e) < st) /\\\n  (forall c, In c (proj1_sig h) -> ((hd nty t) c < quota)%Q) /\\\n  exists l c bl2,\n   (bl = (c :: l,bl2) /\\\n   nbl = (l,bl2) /\\\n   nba = last (p c) [] /\\ np(c) = [] /\\\n     (forall d, d <> c -> np(d) = p(d))) /\\\n   conc = state (nba, t, np, nbl, e, h).\n\n (*\n Definition CADE_elect \n  (prem: Machine_States) (conc: Machine_States) : Prop :=\n   exists nba t p np bl nbl  nh h e ne,\n   (1) prem = state ([], t, p, bl, e, h) /\\ \n   (2) exists c,                                                                  \n   (3)  length (proj1_sig e) + 1 <= st /\\    \n   (4)  In c (proj1_sig h) /\\ (hd nty t (c) >= quota)%Q /\\      \n   (5)  eqe c (proj1_sig e) (proj1_sig ne) /\\          \n   (6)  (forall d, In d (proj1_sig nh) <-> \n         In d cand_all /\\ (~ In d (proj1_sig ne))) /\\     \n   (7)  (forall d, In d cand_all -> (np d = [])) /\\ \n   (8)  (fst nbl = []) /\\\n   (9)  (nba = Append_All cand_all p) /\\           \n   (10) conc = state (nba, t, np, nbl, ne, nh).      \n *)\n\n\n Definition ACT_Elect (prem: Machine_States) (conc: Machine_States) : Prop :=\n  exists (nba: list ballot) t p np (bl nbl: (list cand) * (list cand)) nh h e ne,\n    prem = state ([], t, p, bl, e, h) /\\\n    exists l,\n     (l <> [] /\\\n     length l <= st - length (proj1_sig e) /\\\n     (forall c, In c l -> In c (proj1_sig h) /\\ (hd nty t (c) >= quota)%Q) /\\    \n     ordered (hd nty t) l /\\\n     Leqe l (proj1_sig nh) (proj1_sig h) /\\\n     Leqe l (proj1_sig e) (proj1_sig ne) /\\\n     (forall c, In c l -> ((np c) = map (map (fun (b : ballot) =>\n      (fst b, (Qred (snd b * (Update_transVal c p (hd nty t))))%Q))) [(last (p c) [])])) /\\\n     (forall c, ~ In c l -> np (c) = p (c)) /\\\n     fst nbl = (fst bl) ++ l) /\\ (nba = []) /\\\n   conc = state ([], t, np, nbl, ne, nh).\n\n(* (e ne: {l : list cand | length l <= st })\nDefinition ACT_TransferElected2 (prem: Machine_States) (conc: Machine_States) :=\n exists nba t p np bl nbl h e,         \n  prem = state ([], t, p, bl, e, h) /\\ \n    (length (proj1_sig e) < st) /\\\n    (forall c, In c (proj1_sig h) -> ((hd nty t) c < quota)%Q) /\\       \n    exists l c,                          \n     (bl = (c :: l, []) /\\                   \n     nbl = (l, []) /\\                          \n     nba = concat (p c) /\\\n     concat (p c') = [] /\\           \n     np(c) = [] /\\                                 \n     (forall d, d <> c -> np(d) = p(d))) /\\    \n   conc = state (nba, t, np, nbl, e, h). \n*)\n\nDefinition ACT_TransferElim (prem: Machine_States) (conc: Machine_States) :=\n exists nba t p np bl nbl h e,         \n  prem = state ([], t, p, bl, e, h) /\\ \n    (length (proj1_sig e) < st) /\\\n    (forall c, In c (proj1_sig h) -> ((hd nty t) c < quota)%Q) /\\       \n    exists bl1 c' l',                          \n     (bl = (bl1, c'::l') /\\                   \n    (*(match  (concat (np c')) with\n        [] => nbl = (bl1, l')\n       | _ => nbl = (bl1, c'::l')\n      end) /\\*)\n      (concat (p c') <> []) /\\  \n      nbl = (bl1, c'::l') /\\\n      let x:= (groupbysimple _ (sort (concat (p c')))) in\n       (nba = last x []) /\\\n       np c' = (removelast x) /\\\n       (*/\\\n       (match concat (np c') with [] => (nbl = (bl1,l')) | _ => (nbl = (bl1,c'::l')) end) *)\n       (forall d, d <> c' -> np(d) = p(d))) /\\    \n   conc = state (nba, t, np, nbl, e, h). \n\nLemma ACTInitStep_SanityCheck_App : SanityCheck_Initial_App ACT_InitStep.\nProof.\n unfold SanityCheck_Initial_App.  \n intros.\n exists (state (Filter ba, [nty], nas, (nbdy, nbdy), emp_elec, all_hopeful)). \n split. auto.\n unfold ACT_InitStep.\n exists ba.\n exists (Filter ba).\n split. assumption.\n split;auto. \nQed. \n\nLemma ACTInitStep_SanityCheck_Red: SanityCheck_Initial_Red ACT_InitStep.\n unfold SanityCheck_Initial_Red.\n intros.\n unfold ACT_InitStep in H.\n destruct H as [ba [ba' H1]]. \n exists ba. exists ba'. exists [nty]. exists nas. exists (nbdy, nbdy). exists emp_elec. exists all_hopeful.\n split;auto.\n intuition.\n intuition.\nQed.\n\nHypothesis Bl_hopeful_NoIntersect : forall j: Machine_States, forall ba t p bl e h, j = state (ba,t,p,bl,e,h) ->\n (forall c, In c (snd bl) -> ~ In c (proj1_sig h)) * (forall c, In c (fst bl) -> ~ In c (snd bl)).\n\nLemma ACTCount_SanityCheck_App : SanityCheck_Count_App ACT_count.\nProof.\n unfold SanityCheck_Count_App. \n intros.\n exists (state ([], (fun (c:cand) =>  if (cand_in_dec c (proj1_sig h)) then SUM (p (c) ++ [list_is_first_hopeful c (proj1_sig h) ba]) else (hd nty t) c) :: t, fun (c:cand) => (if (cand_in_dec c (proj1_sig h)) then (p (c) ++ [list_is_first_hopeful c (proj1_sig h) ba]) else (p c)), bl, e, h)).\n unfold ACT_count.\n exists ba.\n exists t.\n exists ((fun (c:cand) =>  if (cand_in_dec c  (proj1_sig h)) then SUM (p (c) ++ [list_is_first_hopeful c (proj1_sig h) ba]) else ((hd nty t) c))).\n exists p.\n exists (fun (c:cand) => (if (cand_in_dec c (proj1_sig h)) then (p (c) ++ [list_is_first_hopeful c (proj1_sig h) ba]) else (p c))). \n exists bl.\n exists h.\n exists e.\n split; auto.\n split; auto.\n split.\n intro c.\n destruct (cand_in_dec c (proj1_sig h)).\n exists (list_is_first_hopeful c (proj1_sig h) ba).\n split; auto.\n split.\n intro b.   \n apply (listballot_fcc ba t p bl e h quota c i b). \n simpl.\n destruct (cand_in_dec c (proj1_sig h)). auto.\n contradict n. assumption.\n simpl.\n destruct (cand_in_dec c (proj1_sig h)).\n contradict n. assumption.\n auto. auto.\nQed.\n\nLemma ACTCount_SanityCheck_Red: SanityCheck_Count_Red ACT_count.\n Proof.\n unfold SanityCheck_Count_Red.\n intros.\n unfold ACT_count in H.\n destruct H as [ba [t [nt [ p0 [np [bl [h [e H1]]]]]]]].\n destruct H1 as [H11 [H12 [H13 H14]]].\n assert (old_new_pile_equal_bl: forall c, In c (snd bl) -> p0 c = np c).\n specialize (Bl_hopeful_NoIntersect p ba t p0 bl e h H11). \n intros c0  Hyp.\n destruct Bl_hopeful_NoIntersect as [NoIntersect1 NoIntersect2].\n specialize (NoIntersect1 c0 Hyp).\n specialize (H13 c0).\n destruct (cand_in_dec c0 (proj1_sig h)).\n contradict NoIntersect1.\n assumption.\n intuition.\n exists ba; exists ([]: list ballot); exists t. exists nt; exists p0. \n exists np; exists bl; exists e; exists h. split. intuition. \n split; intuition.\n specialize (list_nonempty ballot ba). intro Hyp.\n intuition.\n destruct H as [b [l Hyp1]].\n rewrite Hyp1.\n simpl. \n omega. \n assert (hyp2: forall c, In c (snd bl) -> length (concat (p0 c)) = length (concat (np c))).\n intros.\n specialize (old_new_pile_equal_bl c0 H). \n rewrite old_new_pile_equal_bl.\n reflexivity.\n specialize (map_ext_in (fun c0 => length (concat (p0 c0))) (fun c0 => length (concat (np c0))) (snd bl) hyp2).\n intro.\n rewrite H. auto.\nQed.\n\nLemma  ACTHwin_SanityCheck_App : SanityCheck_Hwin_App ACT_hwin.                 \nProof.\n unfold SanityCheck_Hwin_App.\n intros.\n unfold ACT_hwin.\n exists (winners ((proj1_sig e) ++ (proj1_sig h))).\n exists ((proj1_sig e) ++ (proj1_sig h)).\n exists ba; exists t; exists p; exists bl; exists e; exists h.  \n auto.\nQed.\n\nLemma ACTHwin_SanityCheck_Red : SanityCheck_Hwin_Red ACT_hwin.\nProof.\n unfold SanityCheck_Hwin_Red.\n intros.\n unfold ACT_hwin in H. \n destruct H as [w [ba [t [p [bl [e [h H1]]]]]]]. \n exists w; exists ba; exists t; exists p; exists bl; exists e; exists h. \n intuition.\nQed.\n\nLemma ACTEwin_SanityCheck_App : SanityCheck_Ewin_App ACT_ewin.\nProof.\n unfold SanityCheck_Ewin_App.\n intros.\n unfold ACT_ewin.\n exists (winners (proj1_sig e)). \n exists (proj1_sig e). exists ba. exists t. exists p. exists bl. exists e. exists h.\n intuition.\nQed.\n\nLemma ACTEwin_SanityCheck_Red : SanityCheck_Ewin_Red ACT_ewin.\nProof.\n unfold SanityCheck_Ewin_Red.\n intros.\n unfold ACT_ewin in H.\n destruct H as [w [ba [t [p [bl [e [h H1]]]]]]].\n exists w. exists ba. exists t. exists p. exists bl. exists e. exists h. \n intuition.\n rewrite <- H0.\n assumption.\nQed.\n\nLemma ACTElim_SanityCheck_App : SanityCheck_Elim_App ACT_elim.\nProof.\n unfold SanityCheck_Elim_App.\n intros.\n unfold ACT_elim.\n specialize (list_min cand (proj1_sig h) (hd nty t)). intro min_hopeful.\n destruct min_hopeful.\n rewrite e0 in H0.\n destruct H0 as [H01 H02].\n destruct e.\n simpl in H01.\n omega.\n destruct s as [min [s1 s2]].\n specialize (remc_nodup (proj1_sig h) min (proj2_sig h) s1);intro H'1.\n exists (state (flat_map (fun x => x) (p min), t, fun d => if (cand_eq_dec d min) then [] else (p d),\n                                                ([], []), e, exist _ (remc min (proj1_sig h)) H'1)). \n exists (flat_map (fun x => x) (p min)).\n exists t. exists p. exists (fun d => if (cand_eq_dec d min) then [] else (p d)). exists bl2. exists e. exists h. \n exists (exist _ (remc min (proj1_sig h)) H'1).\n intuition.\n(* exists bl2. \n intuition.\n simpl.*)\n exists min.\n intuition.\n apply (remc_ok min (proj1_sig h) (proj2_sig h) s1).\n destruct (cand_eq_dec min min) as [i | j]. reflexivity.\n contradict j. auto.\n destruct (cand_eq_dec d min) as [i | j]. contradiction i. reflexivity.\n\n exists min.\n intuition.\n apply (remc_ok min (proj1_sig h) (proj2_sig h) s1).\n destruct (cand_eq_dec min min) as [i | j]. auto. contradict j. reflexivity.\n destruct (cand_eq_dec d min) as [i | j]. contradiction. auto.\nQed.\n\nLemma ACTElim_SanityCheck_Red : SanityCheck_Elim_Red ACT_elim.\n Proof.\n unfold SanityCheck_Elim_Red.\n intros. \n unfold ACT_elim in H.\n destruct H as [nba [t [p [np [bl2 [e [h [nh  H1]]]]]]]].\n destruct H1 as [H11 [H12 [H13 H14]]].\n destruct H14 as [weakest H141]. \n exists nba. exists t. exists p. exists np. exists e. exists h. exists nh.  exists bl2. exists ([]: list cand). \n intuition.\n unfold eqe in H1.\n destruct H1 as [l1 [l2 [H' [H'' [H''' H'''']]]]].\n rewrite H'.\n rewrite H''.\n assert (Hyp : length (l1 ++ [weakest] ++ l2) = (length l1 + (length ([weakest] ++ l2)))% nat).\n simpl.\n rewrite (app_length).\n simpl. auto.  \n rewrite Hyp.\n simpl.\n rewrite (app_length). omega.\n(* exists ([]: list cand). \n exists ([]: list cand).\n intuition. *)\nQed.\n\nLemma ACT_TransferElected_SanityCheck_App : SanityCheck_TransferElected_App ACT_TransferElected.\nProof.\n unfold SanityCheck_TransferElected_App.\n intros.\n destruct H0 as [H1 [H2 [H3 H4]]].\n specialize (list_nonempty_type cand bl1 H2). intro Hyp. destruct Hyp as [head [tail Hyp1]].\n exists (state (last (p head) [], t, fun d => if (cand_eq_dec d head) then [] else (p d), (tail,bl2), e, h)).\n unfold ACT_TransferElected. exists (last (p head) []). exists t. exists p.\n exists (fun d => if (cand_eq_dec d head) then [] else (p d)).\n exists (head::tail, (bl2: list cand)). exists (tail, (bl2: list cand)). exists h. exists e. rewrite Hyp1 in H. simpl in H.\n intuition.\n exists tail. exists head. exists bl2.\n intuition.\n destruct (cand_eq_dec head head) as [i | j]. reflexivity. contradict j. auto.\n destruct (cand_eq_dec d head) as [i | j]. contradiction i. reflexivity.\n\nexists tail. exists head. exists bl2. intuition.\ndestruct (cand_eq_dec head head) as [i | j]. auto. contradict j. reflexivity.\ndestruct (cand_eq_dec d head) as [i |j]. contradiction. auto.\nQed.\n\nLemma ACT_TransferElected_SanityCheck_Red : SanityCheck_TransferElected_Red ACT_TransferElected.\nProof.\n unfold SanityCheck_TransferElected_Red.\n intros.\n unfold ACT_TransferElected in H.\n destruct H as [nba [t [p [np [bl [nbl [h [e H1]]]]]]]].\n destruct H1 as [H11 [H12 [H13 H14]]].\n destruct H14 as [l [candid [bl2 H141]]].\n destruct H141 as [H1411 H1412].\n destruct H1411 as [H3 [H4 H5]].\n exists nba. exists t. exists p. exists np. exists bl. exists nbl. exists h. exists e.\n intuition.  \n rewrite H3.\n rewrite H4.\n simpl.\n(* left. *)\n omega.\n assert (Leneq: forall d, In d bl2 -> length (concat (p d)) = length (concat (np d))).\n intros d Assum.\n specialize (Bl_hopeful_NoIntersect premise [] t p bl e h). \n intuition.\n assert (Hypos: d <> candid). intro HypoAux. specialize (b candid). rewrite H3 in b. simpl in b.\n apply b. left;auto. rewrite HypoAux in Assum. auto.\n specialize (H2 d Hypos). rewrite H2. reflexivity.\n specialize (map_ext_in (fun c => length (concat (p c))) (fun c => length (concat (np c))) bl2 Leneq).\n intro H0. rewrite H3. simpl.  rewrite H4. simpl. rewrite H0. auto.\nQed.\n\nLemma ACT_Elect_SanityCheck_App : SanityCheck_Elect_App ACT_Elect.\nProof.\n unfold SanityCheck_Elect_App. \n intros premise t p bl e h H X.\n unfold ACT_Elect.\n specialize (constructing_electable_first).\n intro H1.\n destruct X as [c [X1 X2]].\n assert (Hyp: length (proj1_sig e) < st).\n omega. \n specialize (H1 e (hd nty t) h quota Hyp (proj2_sig h)).\n destruct H1 as [listElected H11].\n destruct H11 as [H111 [H112 [H113 [H114 H115]]]].\n specialize (Removel_nodup listElected (proj1_sig h) (proj2_sig h)). intro NoDupH.\n assert (Assum: length ((proj1_sig e) ++ listElected) <= st).\n rewrite app_length.\n omega.\n exists (state ([], t, fun c => update_pile_ManualACT p (hd nty t) listElected quota c, \n((fst bl) ++ listElected, snd bl), exist _ ((proj1_sig e) ++ listElected) Assum, \n                                   exist _ (Removel listElected (proj1_sig h)) NoDupH)). \n exists ([]: list ballot).  exists t. exists p. exists (fun x => update_pile_ManualACT p (hd nty t) listElected quota x).\n exists bl. exists ((fst bl) ++ listElected, snd bl). exists (exist _ (Removel listElected (proj1_sig h)) NoDupH).\n exists h. exists e. exists (exist (fun v => length v <= st) ((proj1_sig e) ++ listElected) Assum).\n split. auto.\n exists listElected.\n intuition.\n assert (NonEmptyElected: length listElected = 0).\n rewrite H2.\n simpl. reflexivity.\n assert (VacantSeat: length (listElected) < st - (length (proj1_sig e))).\n rewrite app_length in Assum.\n rewrite NonEmptyElected in Assum.\n omega.\n specialize (H115 c).\n intuition. \n rewrite H2 in H3.\n inversion H3. \n simpl.\n unfold Leqe.\n apply Permutation_App.\n apply (nodup_permutation).\n intros candid HypCand. \n specialize (H111 candid HypCand).\n intuition. \n assumption.\n apply (proj2_sig h).\n simpl.\n unfold Leqe.\n apply Permutation_refl.\n unfold update_pile_ManualACT.\n destruct (cand_in_dec c0 listElected) as [i |j].\n trivial. \n contradict j. assumption.\n unfold update_pile_ManualACT.\n destruct (cand_in_dec c0 listElected) as [i |j].\n contradict i.\n assumption.\n auto. \nQed.\n\nLemma subList_CandAll : forall l, incl l cand_all. \nProof.\n intro l.\n unfold incl.\n intros.\n   apply (cand_finite a).\nQed. \n\nHypothesis noDup_elect : forall j: Machine_States, forall ba t p bl e h, \n  j = state (ba,t,p,bl,e,h) -> NoDup (proj1_sig e).\n\nVariable A : Type.\n\n Inductive Add (a:Cand) : list Cand -> list Cand -> Prop :=\n    | Add_head l : Add a l (a::l)\n    | Add_cons x l l' : Add a l l' -> Add a (x::l) (x::l').\n\nLemma Add_app a l1 l2 : Add a (l1++l2) (l1++a::l2).\n  Proof.\n   induction l1; simpl; now constructor.\n  Qed.\n\n Lemma Add_inv a l : In a l -> exists l', Add a l' l.\n  Proof.\n   intro Ha. destruct (in_split _ _ Ha) as (l1 & l2 & ->).\n   exists (l1 ++ l2). apply Add_app.\n  Qed.\n\n\n  Lemma Add_length a l l' : Add a l l' -> length l' = S (length l).\n  Proof.\n   induction 1; simpl; auto with arith.\n  Qed.\n\n\n  Lemma Add_in a l l' : Add a l l' ->\n   forall x, In x l' <-> In x (a::l).\n  Proof.\n   induction 1; intros; simpl in *; rewrite ?IHAdd; tauto.\n  Qed.\n\n  Lemma incl_Add_inv a l u v :\n    ~In a l -> incl (a::l) v -> Add a u v -> incl l u.\n  Proof.\n   intros Ha H AD y Hy.\n   assert (Hy' : In y (a::u)).\n   { rewrite <- (Add_in a u v AD). apply H; simpl; auto. }\n   destruct Hy'; [ subst; now elim Ha | trivial ].\n  Qed.\n\n Lemma NoDup_incl_length (l: list Cand) l' :\n    NoDup l -> incl l l' -> length l <= length l'.\n  Proof.\n   intros N. revert l'. induction N as [|a l Hal N IH]; simpl.\n   - auto with arith.\n   - intros l' H.\n     destruct (Add_inv a l') as (l'', AD). { apply H; simpl; auto. }\n     rewrite (Add_length a l'' l' AD). apply le_n_S. apply IH.\n     now apply incl_Add_inv with a l'.\n  Qed.\n\nLemma ACT_Elect_SanityCheck_Red : SanityCheck_Elect_Red ACT_Elect.\nProof.\n unfold SanityCheck_Elect_Red.\n intros premise conclusion H.\n unfold ACT_Elect in H.\n destruct H as [nba [t [p [np [bl [nbl [nh [h [e [ne H1]]]]]]]]]].\n exists nba. exists t. exists p; exists np. exists bl. exists nbl. exists e. exists ne. exists nh. exists h. \n destruct H1 as [H11 H12].\n destruct H12 as [l H121].\n intuition.\n unfold Leqe in H6.\n specialize (Permutation_length H6). intro Permut_length.\n assert (lem: forall n m k, k <= n -> m <= n -> m < k -> (n - k < n - m)).\n  intros. omega.\n apply lem.\n specialize (noDup_elect (state([],t,np,nbl,ne,nh)) [] t np nbl ne nh eq_refl). \n apply (NoDup_incl_length (` ne) cand_all).\n auto.\n apply subList_CandAll.\n specialize (noDup_elect (state([],t,p,bl,e,h)) [] t p bl e h eq_refl).\n apply (NoDup_incl_length (` e) cand_all). \n auto.\n apply subList_CandAll.\n\n rewrite Permut_length.\n rewrite  app_length.\n specialize (list_nonempty_type cand l H1). intro X.\n destruct X as [c [l' HX]].\n rewrite HX. (*Search (_ - _  < _).\n Require Import Psatz. Require Import Coq.omega.PreOmega. zify.*)\n simpl.  \n omega.  \n rewrite H.\n assumption.\n(* unfold Leqe in H5.\n specialize (Permutation_length H5). intro H8.\n rewrite H8.\n rewrite app_length.\n specialize (list_nonempty_type cand l H1). intro X.\n destruct X as [c [l' HX]]. \n rewrite HX.\n simpl.\n omega.*)\nQed.\n\n(*\nLemma ACTTran2_SanityCheck_App : SanityCheck_Transfer2_App ACT_TransferElected2. \nProof.\n unfold SanityCheck_Transfer2_App.\n intros. \n unfold ACT_TransferElected2.\n destruct H0 as [H1 [H2 [H3 H4]]].\n specialize (list_nonempty_type cand bl1 H2). intro Nonempty_bl.\n destruct Nonempty_bl as [Headbl1 [Tailbl1 bl1None]].\n \n exists (state (concat (p Headbl1), t, fun x => if (cand_eq_dec x Headbl1) then [] else p x, \n                (Tailbl1, bl2), e, h)).  \n exists (concat (p Headbl1)).\n exists t. exists p. exists (fun x => if (cand_eq_dec x Headbl1) then [] else (p x)).\n exists (Headbl1:: Tailbl1, c:: bl2). exists (Tailbl1,bl2). exists h. exists e.\n rewrite bl1None in H.\n intuition.\n exists Tailbl1. exists Headbl1. exists c. exists bl2.\n intuition.\n destruct (cand_eq_dec Headbl1 Headbl1) as [i | j].\n reflexivity.\n contradict j.  auto.\n destruct (cand_eq_dec d Headbl1) as [i | j].\n contradict i.\n auto.\n reflexivity.\nQed.\n\nLemma ACTTran2_SanityCheck_Red : SanityCheck_Transfer_Red ACT_TransferElected2.\nProof.\n unfold SanityCheck_Transfer_Red.\n intros.\n unfold ACT_TransferElected2 in H.\n destruct H as [nba [t [p [np [bl [nbl [h [e H1]]]]]]]].\n destruct H1 as [H11 [H12 [H13 H14]]].\n destruct H14 as [Tbl1 [Hbl1 [Hbl2 [Tbl2 H15]]]].\n exists nba.\n exists t. exists p. exists np. exists bl. exists nbl. exists h. exists e.\n destruct H15 as [H15 H152].\n destruct H15 as [HH1 HH2].\n destruct HH2 as [HH21 [HH22 [HH23 [HH24 HH25]]]].\n assert (Hypo: forall d, In d Tbl2 -> p (d) = np (d)).\n intros d Hy.\n assert (hypos: d <> Hbl1). intro contHypos. rewrite contHypos in Hy.\n specialize (Bl_hopeful_NoIntersect (state ([],t,p,bl, e,h)) [] t p bl e h (eq_refl)).  \n destruct Bl_hopeful_NoIntersect as [i j]. \n specialize (j Hbl1).\n rewrite HH1 in j.\n assert (hyu: In Hbl1 (fst (Hbl1:: Tbl1, Hbl2:: Tbl2))).\n simpl. left;auto.\n specialize (j hyu).\n apply j.\n simpl.\n right;assumption.\n specialize (HH25 d hypos).\n auto.\n split.  auto.\n split. left. rewrite HH1. rewrite HH21. \n simpl. rewrite HH23.\n assert (Leneq: forall d, In d Tbl2 -> length (concat (p d)) = length (concat (np d))).\n intros d he.\n specialize (Hypo d he). rewrite Hypo. auto.\n specialize (map_ext_in (fun c => length (concat (p c))) (fun d => length (concat (np d))) Tbl2 Leneq). \n intro map_equal.\n rewrite map_equal.\n simpl.\n omega.\n auto.\nQed.\n*)\n\nHypothesis Bl_NoDup : forall j: Machine_States, forall ba t p bl e h, \n  j = state (ba,t,p,bl,e,h) -> NoDup (snd bl).\n\n\nLemma ACT_TransferRemoved_SanityCheck_App : SanityCheck_TransferRemoved_App ACT_TransferElim.\nProof.\n unfold SanityCheck_TransferRemoved_App.\n intros.\n (* destruct H0 as [H1 [H2 [H3 H4]]]. *)\ndestruct H0 as [H1 [H2 H3]].\n unfold ACT_TransferElim.\n exists (state (((last (groupbysimple _ (sort (concat (p c)))) []): list ballot),\n t, fun d => if (cand_eq_dec d c) then (removelast (groupbysimple _ (sort (concat (p c))))) else p d, (bl1, c::bl2), e, h)). \n exists (last (groupbysimple _ (sort (concat (p c)))) []). \n exists t. exists p. exists (fun d => if (cand_eq_dec d c) \n   then (removelast ((groupbysimple _ (sort (concat (p c))))))  else p d). \n exists (bl1,c::bl2). \n exists (bl1, c::bl2). \nexists h. exists e. intuition. \n  exists bl1. exists c. exists bl2. intuition.\n(*specialize (list_nonempty_type cand bl1 H2). intro Nbl1.\n destruct Nbl1 as [Hbl1 [Tbl1 bl1N]].\n exists Tbl1. exists Hbl1. exists c. exists bl2.\n rewrite bl1N.\n intuition. *)\n destruct (cand_eq_dec c c) as [i | j]. simpl. trivial.\n contradict j. reflexivity.\n destruct (cand_eq_dec d c) as [i |j]. simpl. trivial.\n contradiction i. reflexivity.\nQed.\n\nLemma concat_app : forall (A:Type) (l1: list (list A)) l2, concat (l1 ++ l2) = concat l1 ++ concat l2.\nProof.\n  intros.\n  induction l1 as [|x l1 IH]. induction l2. simpl.\n  reflexivity. simpl. auto.\n  simpl. rewrite IH; apply app_assoc.\nQed.\n \nLemma ACT_TransferRemoved_SanityCheck_Red: SanityCheck_TransferRemoved_Red ACT_TransferElim.\nProof.\n unfold SanityCheck_TransferRemoved_Red. \n intros.\n unfold ACT_TransferElim in H.\n destruct H as [nba [t [p [np [bl [nbl [h [e H1]]]]]]]].\n destruct H1 as [H11 [H12 [H13 H14]]].\n destruct H14 as [bl1 [Hbl2 [Tbl2 H15]]]. \n (*destruct H14 as [bl1 [c' [l' H15]]].*)\n destruct H15 as [H151 H152].  \n destruct H151 as [K1 [K11 K2]].\n destruct K2 as [K21 [K22 [K23 K24]]].\n exists nba. exists t. exists p. exists np. exists bl. exists nbl. exists h. exists e.\n split. assumption.\n split. rewrite K1. rewrite K21. simpl. auto.\n rewrite K1. rewrite K21. simpl.\n\n assert (Tbl2_NoDup: NoDup (Hbl2 :: Tbl2)). \n specialize (Bl_NoDup (state ([],t,p,bl,e,h)) [] t p bl e h (eq_refl)).\n rewrite K1 in Bl_NoDup.\n simpl in Bl_NoDup.\n assumption.\n assert (Hbl2_notInTail: ~ In Hbl2 Tbl2). \n intro Cont.\n inversion Tbl2_NoDup.\n apply H1. assumption.\n assert (Piles_eq_Tbl2: forall d, In d Tbl2 -> p d = np d).\n intros d InTbl2.\n assert (not_eq_d: d <> Hbl2).\n intro cont. rewrite cont in InTbl2. apply Hbl2_notInTail. assumption.\n specialize (K24 d not_eq_d).\n auto.\n assert (Len_piles_eq: forall d, In d Tbl2 -> length (concat (p d)) = length (concat (np d))).\n intros d Hy.\n specialize (Piles_eq_Tbl2 d Hy).\n rewrite Piles_eq_Tbl2. auto.\n specialize (map_ext_in (fun c => length (concat (p c))) (fun c => length (concat (np c))) Tbl2 Len_piles_eq). \n intro nice.\n rewrite nice.\n (* rewrite K24.*)\n rewrite K23.\n assert (Hypo: (groupbysimple _ (sort (concat (p Hbl2)))) <> []).\n apply groupbysimple_not_empty.\n apply sherin. \n auto.  \n assert (Hypo2: groupbysimple _ (sort (concat (p Hbl2))) = \n(removelast (groupbysimple _ (sort (concat (p Hbl2))))) ++ [last (groupbysimple _ (sort (concat (p Hbl2)))) []]).\n apply app_removelast_last.\n assumption.\n assert (Hypo222: concat (groupbysimple _ (sort (concat (p Hbl2)))) =\n                  concat ((removelast (groupbysimple _ (sort (concat (p Hbl2)))))\n                            ++\n                            [last (groupbysimple _ (sort (concat (p Hbl2)))) []])).\n apply f_equal. assumption.\n rewrite concat_app in Hypo222. \n\n assert (Hypo22: length (concat (groupbysimple _ (sort (concat (p Hbl2))))) = \n (length (concat (removelast (groupbysimple _ (sort (concat (p Hbl2)))))) + \n  length (concat [last (groupbysimple _ (sort (concat (p Hbl2)))) []]))%nat).\n rewrite <- app_length. apply f_equal. auto.\n assert (Hypolen : length\n            (concat (groupbysimple {v : list cand | NoDup v /\\ [] <> v} (sort (concat (p Hbl2))))) = \n                   length (concat (p Hbl2))).\n rewrite <- concat_rat. auto.\n rewrite <- Hypolen.\n rewrite  Hypo22.\n simpl.\n assert (Hlen : forall (A : Type) (l : list A),\n            l <> []  -> 0 < length l).  \n intros. destruct l. contradiction H. auto. simpl. omega.\n specialize (groupby_notempty _ (sort (concat (p Hbl2)))). intros.\n pose proof (sortedList_notempty (concat (p Hbl2)) K11).\n specialize (H H0). \n specialize (Hlen _ _ H).\n rewrite app_nil_r. split.\n apply Nat.add_lt_mono_r.\n apply NPeano.Nat.lt_add_pos_r. trivial. rewrite <- K21.\n auto.\nQed.\n\n\nVariable bs: list ballot.\n\nDefinition ActSTV := (mkSTV \n    (ACT_InitStep) (ACTInitStep_SanityCheck_App) (ACTInitStep_SanityCheck_Red) \n    (ACT_count) (ACTCount_SanityCheck_App) (ACTCount_SanityCheck_Red)\n    (ACT_TransferElected) (ACT_TransferElected_SanityCheck_App) (ACT_TransferElected_SanityCheck_Red)\n   (* (ACT_TransferElected2) (ACTTran2_SanityCheck_App) (ACTTran2_SanityCheck_Red) *)\n    (ACT_TransferElim) (ACT_TransferRemoved_SanityCheck_App) (ACT_TransferRemoved_SanityCheck_Red)\n    (ACT_Elect) (ACT_Elect_SanityCheck_App) (ACT_Elect_SanityCheck_Red)\n    (ACT_elim) (ACTElim_SanityCheck_App) (ACTElim_SanityCheck_Red)\n    (ACT_hwin) (ACTHwin_SanityCheck_App) (ACTHwin_SanityCheck_Red)\n    (ACT_ewin) (ACTEwin_SanityCheck_App) (ACTEwin_SanityCheck_Red)).\n\nLemma init_stages_R_initial : ~ State_final (initial (Filter bs)).\nProof.\n intro.\n unfold State_final in H.\n destruct H.\n inversion H.\nQed.\n \nDefinition Act_Termination := M.Termination bs (initial (Filter bs)) init_stages_R_initial ActSTV.\n\n\nEnd ACT.\n\n(*End Act.*)\n\nExtraction Language Haskell.\nExtraction \"Act.hs\" Act_Termination.\n\n(*End Act.*)\n", "meta": {"author": "MiladKetabGhale", "repo": "Modular-STVCalculi", "sha": "e19b6c8e1d23e25e9f9a06becba20f11c2ed386a", "save_path": "github-repos/coq/MiladKetabGhale-Modular-STVCalculi", "path": "github-repos/coq/MiladKetabGhale-Modular-STVCalculi/Modular-STVCalculi-e19b6c8e1d23e25e9f9a06becba20f11c2ed386a/ActSTV/ACTstv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.291964877152189}}
{"text": "(* -*- company-coq-local-symbols: ((\"|=\" . ?⊨) (\"=|\" . ?⫤) (\"->>\" . ?↠) (\"=~\" . ?≈) (\"<|\" . ?⟨) (\"|>\" . ?⟩) ); -*- *)\nSet Warnings \"-notation-overridden\".\n\nRequire Import Prelude.Prelude.\n\nRequire Import Defs.Embed.\nRequire Import Defs.Substs.\n\n(*** Notation, tactics etc*)\nLtac LC_ind LC :=\n    let LC' := fresh \"LC__ty\" in\n    induction LC as [LC' | ?]; [induction LC' | idtac].\n\nLtac inv_LC :=\n  repeat match goal with\n    | [ H : lc_Ty (T_SkVar_b _) |- _ ] => inverts H\n    | [ H : lc_DTy (DT_SkVar_b _) |- _ ] => inverts H\n\n    | [ H : lc_Ty (T_Fun _ _) |- _ ] => inverts H\n    | [ H : lc_DTy (DT_Fun _ _) |- _ ] => inverts H\n\n\n    | [ H : lc_Sch (S_Mono _) |- _ ] => inverts H\n    | [ H : lc_DSch (DS_Mono _) |- _ ] => inverts H\n  end.\n\n(*** Sch <-> DSch & Ty <-> DTy LC *)\nTheorem emb_Ty_lc : forall (dty : DTy),\n    lc_Ty  (emb_Ty dty)\n  <-> lc_DTy dty.\nProof. split; intros LC; induction dty; inverts LC; crush. Qed.\nCorollary emb_Ty_lc2 : forall (dty : DTy),\n    lc_Ty  (emb_Ty dty)\n  -> lc_DTy dty.\nProof. apply emb_Ty_lc. Qed.\nCorollary emb_Ty_lc1 : forall (dty : DTy),\n    lc_DTy dty\n  -> lc_Ty  (emb_Ty dty).\nProof. apply emb_Ty_lc. Qed.\n#[export] Hint Resolve emb_Ty_lc1 emb_Ty_lc2 : slow.\n\n#[export] Hint Extern 4 (lc_Ty (emb_Ty _)) => apply emb_Ty_lc : core.\n\nTheorem embed_Sch_lc : forall (dsch : DSch),\n    lc_Sch  (emb_Sch dsch)\n  <-> lc_DSch dsch.\nProof.\n  split.\n  - introv LC. dependent induction LC. emb_auto. apply emb_Ty_lc in H. crush.\n    (assert (EMB: exists dsch', dsch = DS_Forall dsch')). emb_auto. exists. crush.\n    destruct EMB as [dsch' EMB]. subst. simpl in *. inverts x.\n    constructor. intros. eapply (H0 dskA). rewrite embed_Sch_open_comm. crush.\n  - introv LC. induction LC. constructor. apply emb_Ty_lc. assumption.\n    constructor. fold emb_Sch. intros skA.\n    forwards IH: H0 skA. rewrite embed_Sch_open_comm in IH. crush.\nQed.\n\nCorollary embed_Sch_lc1 : forall (dsch : DSch),\n    lc_Sch  (emb_Sch dsch)\n  -> lc_DSch dsch.\nProof. apply embed_Sch_lc. Qed.\nCorollary embed_Sch_lc2 : forall (dsch : DSch),\n    lc_DSch dsch\n  -> lc_Sch  (emb_Sch dsch).\nProof. apply embed_Sch_lc. Qed.\n#[export] Hint Resolve embed_Sch_lc1 embed_Sch_lc2 : slow.\n\nTheorem lc_Sch_mono : forall (ty : Ty),\n    lc_Sch (S_Mono ty)\n  <-> lc_Ty ty.\nProof. split. inversion 1. auto. auto. Qed.\n#[export] Hint Rewrite lc_Sch_mono : core.\nTheorem lc_DSch_mono : forall (dty : DTy),\n    lc_DSch (DS_Mono dty)\n  <-> lc_DTy dty.\nProof. split. inversion 1. auto. auto. Qed.\n#[export] Hint Rewrite lc_DSch_mono : core.\n\n(*** LC/substs *)\nTheorem lc_Sch_subst_exvar_Sch : forall (sch : Sch) (ty : Ty) (exA : exvar),\n    lc_Sch sch\n  -> lc_Ty ty\n  -> lc_Sch (subst_exvar_Sch ty exA sch).\nProof.\n  introv LC__sch LC__ty.\n  LC_ind LC__sch; default_simp.\n  - constructor. constructor.\n    forwards: IHLC__ty0_1. eassumption. inverts H. assumption.\n    forwards: IHLC__ty0_2. eassumption. inverts H. assumption.\n  - simpl. constructor. intros. simpl.\n    forwards: H0 skA. rewrite subst_exvar_Sch_open_Sch_wrt_Ty in H1; crush.\nQed.\n\nCorollary lc_Sch_subst_exvar_Sch' : forall (exA : exvar) (sch : Sch) (ty : Ty),\n    lc_Sch sch\n  -> lc_Sch (S_Mono ty)\n  -> lc_Sch (subst_exvar_Sch ty exA sch).\nProof. intros. inv_LC. apply lc_Sch_subst_exvar_Sch; eauto. Qed.\n\nTheorem lc_Sch_open_Sch_wrt_Ty : forall (sch : Sch) (skA : skvar) (ty : Ty),\n    lc_Sch sch\n  -> lc_Ty ty\n  -> lc_Sch (open_Sch_wrt_Ty (close_Sch_wrt_Ty skA sch) ty).\nProof.\n  introv LC__sch LC__ty. rewrite <- subst_skvar_Sch_spec. eauto using subst_skvar_Sch_lc_Sch.\nQed.\n", "meta": {"author": "rogerbosman", "repo": "hdm-fully-grounding", "sha": "master", "save_path": "github-repos/coq/rogerbosman-hdm-fully-grounding", "path": "github-repos/coq/rogerbosman-hdm-fully-grounding/hdm-fully-grounding-main/coq/Defs/Lc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.2918504369648644}}
{"text": "(********************************************************************)\n(*                                                                  *)\n(*  The Why3 Verification Platform   /   The Why3 Development Team  *)\n(*  Copyright 2010-2018   --   Inria - CNRS - Paris-Sud University  *)\n(*                                                                  *)\n(*  This software is distributed under the terms of the GNU Lesser  *)\n(*  General Public License version 2.1, with the special exception  *)\n(*  on linking described in file LICENSE.                           *)\n(*                                                                  *)\n(********************************************************************)\n\nRequire Import BuiltIn.\n\nDefinition func : forall (a:Type) (b:Type), Type.\nintros a b.\nexact (a -> b).\nDefined.\n\nDefinition infix_at: forall {a:Type} {a_WT:WhyType a}\n  {b:Type} {b_WT:WhyType b}, (a -> b) -> a -> b.\nintros a aWT b bWT f x.\nexact (f x).\nDefined.\n\nDefinition pred (a: Type) := func a bool.\n", "meta": {"author": "florianschanda", "repo": "why3", "sha": "dc0d2720d58c6d130b9c3e1db820a07275a133eb", "save_path": "github-repos/coq/florianschanda-why3", "path": "github-repos/coq/florianschanda-why3/why3-dc0d2720d58c6d130b9c3e1db820a07275a133eb/lib/coq/HighOrd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.29185042941547856}}
{"text": "Require Import Coq.Structures.OrderedTypeEx.\nRequire Import Coq.PArith.PArith.\nRequire Import Coq.FSets.FMapPositive.\nRequire Import Crypto.Util.Option.\nRequire Import Crypto.Util.Equality.\nRequire Import Crypto.Util.Structures.OrdersEx.\nRequire Import Crypto.Util.Tactics.Head.\nRequire Import Crypto.Util.Tactics.DestructHead.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nRequire Import Crypto.Util.Tactics.SetEvars.\nRequire Import Crypto.Util.FSets.FMapTrie.Shape.\nRequire Import Crypto.Util.FSets.FMapN.\nRequire Import Crypto.Util.FSets.FMapZ.\nImport EqNotations.\nImport EverythingGen.\n\nLocal Set Implicit Arguments.\nLocal Set Primitive Projections.\nLocal Unset Strict Implicit.\n(* TODO: move to global settings *)\nLocal Set Keyed Unification.\n\nInductive option_dep A : bool -> Type :=\n| Some_dep b : A -> option_dep b\n| None_dep : option_dep false.\nArguments Some_dep {A b} _.\nArguments None_dep {A}.\n\nLocal Ltac t :=\n  first [ instantiate (1:=ltac:(eassumption)); reflexivity\n        | match goal with\n          | [ |- ?LHS = (fun b : ?T => @?RHS b) ]\n            => lazymatch RHS with\n               | fun '(a, b) => _\n                 => is_evar LHS; instantiate (1:=ltac:(first [ intros [a b] | intros [? ?] ]));\n                    try t\n               end\n          end\n        | try instantiate (1:=ltac:(intros)); progress cbv beta iota; t\n        | instantiate (1:=ltac:(intros)); cbv beta;\n          first [ reflexivity | apply f_equal | apply f_equal2 | apply f_equal3 | apply fg_equal\n                | match goal with\n                  | [ |- ?LHS = (fun b : ?T => @?RHS b) ]\n                    => cut (forall a : T, LHS a = RHS a); [ shelve | intro ]\n                  end\n                | break_innermost_match_step ];\n          instantiate (1:=ltac:(intros)); cbv beta iota;\n          t\n        | idtac ].\n\nLocal Ltac handle_id_fix :=\n  intros;\n  cbv beta;\n  set_evars;\n  (tryif (match goal with |- context[id_fix] => idtac | |- context[id_fix_2] => idtac end)\n    then (intros;\n          let m := fresh \"m\" in\n          let x := fresh \"x\" in\n          let IH := fresh \"IH\" in\n          lazymatch goal with\n          | [ |- id_fix   _ ] => cbv [id_fix  ]; fix IH 1; intros m; revert m\n          | [ |- id_fix_2 _ ] => cbv [id_fix_2]; fix IH 2; intros x m; revert x m\n          end;\n          revert IH)\n    else idtac);\n  shelve_unifiable.\n\nLocal Ltac subst_partial_evars :=\n  repeat match goal with\n         | [ H := ?ev |- _ ]\n           => has_evar ev; assert_fails is_evar ev; revert H; set_evars; intro\n         end.\nLocal Ltac partial_unify e :=\n  let do_rep evb e m IH IHm eIHm\n    := (is_evar evb;\n        let v1 := fresh in\n        let v2 := fresh in\n        set (v1 := IHm);\n        pose eIHm as v2;\n        destruct m;\n        change v1 with v2; subst v1 v2 e) in\n  lazymatch goal with\n  | [ ev := ?evb, IH := _ : id_fix _ |- _ ]\n    => let m := lazymatch goal with |- context G[IH ?m] => m end in\n       do_rep evb e m IH (IH m) (e IH m)\n  | [ ev := ?evb, IH := _ : id_fix_2 _ |- _ ]\n    => let x := lazymatch goal with |- context[IH ?x ?m] => x end in\n       let m := lazymatch goal with |- context[IH x ?m] => m end in\n       do_rep evb e m IH (IH x m) (e IH x m)\n  | _ => idtac\n  end.\n\nModule PositiveMapTypFunctor <: TypFunctor.\n  Local Unset Primitive Projections.\n  Local Set Nonrecursive Elimination Schemes.\n  Local Set Boolean Equality Schemes.\n  Local Set Decidable Equality Schemes.\n  Inductive t' (elt : Type) := Node' { data : option elt ; map : option_dep (PositiveMap.t (t' elt)) (Option.is_None data) }.\n  Definition t := t'.\n  Local Notation node_NonEmpty x y := match x, y with None, None => False | _, _ => True end.\n  Definition Node elt (data : option elt) (map : option (PositiveMap.t (t elt))) (pf : node_NonEmpty data map) : t elt\n    := @Node' _ data (match map, data return node_NonEmpty data map -> option_dep _ (Option.is_None data) with\n                      | Some m, _ => fun _ => Some_dep m\n                      | None, Some _ => fun _ => None_dep\n                      | None, None => fun pf => match pf with end\n                      end pf).\n  Global Arguments Node [elt] _ _ _.\n  Definition t_rect elt (P : t elt -> Type)\n             (val : forall (v : option elt) (m : option (PositiveMap.t (t elt))) (pf : node_NonEmpty v m), P (Node v m pf))\n             (m : t elt)\n    : P m\n    := Eval cbv beta in\n      match m return P m with\n      | {| data := d ; map := m |}\n        => match m in option_dep _ b, d return forall pf : is_None d = b, P {| data := d ; map := rew <- [option_dep _] pf in m |} with\n           | None_dep, None\n             => fun pf => match pf with\n                          | eq_refl => I\n                          end\n           | Some_dep _ m, Some d\n             => fun pf => match pf with\n                          | eq_refl => val (Some d) (Some m) I\n                          end\n           | None_dep as m, Some d\n             => fun pf => match pf with\n                          | eq_refl => ltac:(refine (fun x => x)) (val (Some d) None I)\n                          end\n           | Some_dep _ m, None\n             => fun pf => match pf with\n                          | eq_refl => val None (Some m) I\n                          end\n           end eq_refl\n      end.\nEnd PositiveMapTypFunctor.\n\nModule PositiveMapTrieInd <: Trie PositiveOrderedTypeBits PositiveMap.\n  Definition t := PositiveMapTypFunctor.t.\n  Include TrieShape PositiveOrderedTypeBits PositiveMap.\n\n  Definition PositiveMap_find_alt A\n    := fix find (i : PositiveMap.key) (m : PositiveMap.t A) {struct m} : option A :=\n      match m with\n      | @PositiveMap.Leaf _ => None\n      | PositiveMap.Node l o r =>\n          match i with\n          | BinNums.xI ii => find ii r\n          | BinNums.xO ii => find ii l\n          | BinNums.xH => o\n          end\n      end.\n  Lemma eq_PositiveMap_find_alt A : forall i m, @PositiveMap.find A i m = @PositiveMap_find_alt A i m.\n  Proof using Type.\n    induction i, m; cbn in *; auto.\n  Qed.\n\n  Definition t_ind_full elt (P : t elt -> Prop)\n             (H : forall d m pf,\n                 (forall k v, match m with Some m => PositiveMap.find k m = Some v -> P v | None => True end)\n                 -> P (PositiveMapTypFunctor.Node d m pf))\n    : forall m, P m.\n  Proof using Type.\n    fix t_ind_full 1.\n    induction m as [d m pf] using PositiveMapTypFunctor.t_rect.\n    specialize (H d m pf).\n    apply H; clear H.\n    destruct m as [m|]; [ | intros; exact I ].\n    induction m;\n      [ clear t_ind_full\n      | match goal with\n        | [ H : option _ |- _ ]\n          => let x := fresh \"x\" in\n             destruct H as [x|];\n             [ specialize (t_ind_full x)\n             | clear t_ind_full ]\n        end ].\n    all: intros k v H.\n    all: try solve [ exfalso; clear -H; abstract (destruct k; cbn in H; inversion_option) ].\n    all: destruct k; cbn [PositiveMap.find] in *.\n    all: lazymatch goal with\n         | [ H : None = Some _ |- _ ] => exfalso; clear -H; abstract inversion_option\n         | [ H : ?P ?x, H' : Some ?x = Some ?y |- ?P ?y ]\n           => refine (rew [P] (f_equal (fun v => Option.value v x) H') in H)\n         | _ => idtac\n         end.\n    all: eauto with nocore.\n  Defined.\n\n  Section everything.\n    Let everything' : Everything.\n    Proof.\n      unshelve esplit.\n      all: try exact PositiveMapTypFunctor.Node.\n      all: try exact PositiveMapTypFunctor.t_rect.\n      all: try exact t_ind_full.\n      all: try exact PositiveMapAdditionalFacts.xmap2_lr.\n      all: try exact PositiveMap.xgmap2_l.\n      all: try exact PositiveMap.xgmap2_r.\n      all: handle_id_fix.\n      all: subst_partial_evars.\n      all: try (destruct_head' option; destruct_head'_True; destruct_head'_False; reflexivity).\n      all: partial_unify e.\n      all: try reflexivity.\n    Defined.\n    Definition everything := Eval cbv [everything'] in everything'.\n  End everything.\nEnd PositiveMapTrieInd.\n\nModule NMapTypFunctor <: TypFunctor.\n  Local Unset Primitive Projections.\n  Local Set Nonrecursive Elimination Schemes.\n  Local Set Boolean Equality Schemes.\n  Local Set Decidable Equality Schemes.\n  Inductive t' (elt : Type) := Node' { data : option elt ; map : option_dep (NMap.t (t' elt)) (Option.is_None data) }.\n  Definition t := t'.\n  Local Notation node_NonEmpty x y := match x, y with None, None => False | _, _ => True end.\n  Definition Node elt (data : option elt) (map : option (NMap.t (t elt))) (pf : node_NonEmpty data map) : t elt\n    := @Node' _ data (match map, data return node_NonEmpty data map -> option_dep _ (Option.is_None data) with\n                      | Some m, _ => fun _ => Some_dep m\n                      | None, Some _ => fun _ => None_dep\n                      | None, None => fun pf => match pf with end\n                      end pf).\n  Global Arguments Node [elt] _ _ _.\n  Definition t_rect elt (P : t elt -> Type)\n             (val : forall (v : option elt) (m : option (NMap.t (t elt))) (pf : node_NonEmpty v m), P (Node v m pf))\n             (m : t elt)\n    : P m\n    := Eval cbv beta in\n      match m return P m with\n      | {| data := d ; map := m |}\n        => match m in option_dep _ b, d return forall pf : is_None d = b, P {| data := d ; map := rew <- [option_dep _] pf in m |} with\n           | None_dep, None\n             => fun pf => match pf with\n                          | eq_refl => I\n                          end\n           | Some_dep _ m, Some d\n             => fun pf => match pf with\n                          | eq_refl => val (Some d) (Some m) I\n                          end\n           | None_dep as m, Some d\n             => fun pf => match pf with\n                          | eq_refl => ltac:(refine (fun x => x)) (val (Some d) None I)\n                          end\n           | Some_dep _ m, None\n             => fun pf => match pf with\n                          | eq_refl => val None (Some m) I\n                          end\n           end eq_refl\n      end.\nEnd NMapTypFunctor.\n\nModule NMapTrieInd <: Trie NOrderedTypeBits NMap.\n  Definition t := NMapTypFunctor.t.\n  Include TrieShape NOrderedTypeBits NMap.\n\n  Definition NMap_find_alt\n    := ltac:(let v := (eval cbv -[PositiveMap.find fst snd] in NMap.find) in\n             lazymatch (eval pattern PositiveMap.find in v) with\n             | ?P _ => let v := (eval cbv beta in (P PositiveMapTrieInd.PositiveMap_find_alt)) in\n                       exact v\n             end).\n\n  Lemma eq_NMap_find_alt A : forall i m, @NMap.find A i m = @NMap_find_alt A i m.\n  Proof using Type.\n    cbv -[PositiveMap.find PositiveMapTrieInd.PositiveMap_find_alt].\n    intros; break_innermost_match; rewrite ?PositiveMapTrieInd.eq_PositiveMap_find_alt; reflexivity.\n  Qed.\n\n  Definition t_ind_full elt (P : t elt -> Prop)\n             (H : forall d m pf,\n                 (forall k v, match m with Some m => NMap.find k m = Some v -> P v | None => True end)\n                 -> P (NMapTypFunctor.Node d m pf))\n    : forall m, P m.\n  Proof using Type.\n    fix t_ind_full 1.\n    induction m as [d m pf] using NMapTypFunctor.t_rect.\n    specialize (H d m pf).\n    apply H; clear H.\n    destruct m as [[[m0 m]]|]; [ | intros; exact I ].\n    intros [|k]; [ | revert k ].\n    { cbn.\n      destruct m0 as [m0|]; [ | clear; intros; inversion_option ].\n      specialize (t_ind_full m0).\n      intro v.\n      refine (fun pf => match pf with\n                        | eq_refl => t_ind_full\n                        end). }\n    cbv -[PositiveMap.find t].\n    induction m;\n      [ clear t_ind_full\n      | match goal with\n        | [ H : option _ |- _ ]\n          => let x := fresh \"x\" in\n             destruct H as [x|];\n             [ specialize (t_ind_full x)\n             | clear t_ind_full ]\n        end ].\n    all: intros k v H.\n    all: try solve [ exfalso; clear -H; abstract (destruct k; cbn in H; inversion_option) ].\n    all: destruct k; cbn [PositiveMap.find] in *.\n    all: lazymatch goal with\n         | [ H : None = Some _ |- _ ] => exfalso; clear -H; abstract inversion_option\n         | [ H : ?P ?x, H' : Some ?x = Some ?y |- ?P ?y ]\n           => refine (rew [P] (f_equal (fun v => Option.value v x) H') in H)\n         | _ => idtac\n         end.\n    all: eauto with nocore.\n  Defined.\n\n  Section map2.\n    Variable A B C : Type.\n    Variable f : option A -> option B -> option C.\n\n    Definition NMap_xmap2_l (m : NMap.t A) : NMap.t C\n      := ltac:(let v := (eval cbv -[PositiveMap.map2] in (NMap.map2 f m (@NMap.empty _))) in\n               lazymatch (eval pattern (PositiveMap.map2 f) in v) with\n               | ?P _ => let v := (eval cbv beta in (P (fun m _ => PositiveMap.xmap2_l f m))) in\n                         exact v\n               end).\n\n    Definition NMap_xmap2_r (m : NMap.t B) : NMap.t C\n      := ltac:(let v := (eval cbv -[PositiveMap.map2] in (NMap.map2 f (@NMap.empty _) m)) in\n               lazymatch (eval pattern (PositiveMap.map2 f) in v) with\n               | ?P _ => let v := (eval cbv beta in (P (fun _ m => PositiveMap.xmap2_r f m))) in\n                         exact v\n               end).\n\n    Lemma NMap_xgmap2_l : forall (i : NMap.key) (m : NMap.t A),\n        f None None = None -> NMap.find i (NMap_xmap2_l m) = f (NMap.find i m) None.\n    Proof using Type.\n      cbv -[PositiveMap.find PositiveMap.xmap2_l]; intros; break_innermost_match; eauto.\n      all: now rewrite PositiveMap.xgmap2_l by assumption.\n    Qed.\n\n    Lemma NMap_xgmap2_r : forall (i : NMap.key) (m : NMap.t B),\n        f None None = None -> NMap.find i (NMap_xmap2_r m) = f None (NMap.find i m).\n    Proof using Type.\n      cbv -[PositiveMap.find PositiveMap.xmap2_r]; intros; break_innermost_match; eauto.\n      all: now rewrite PositiveMap.xgmap2_r by assumption.\n    Qed.\n  End map2.\n  Lemma NMap_xmap2_lr :\n    forall (A B : Type)(f g: option A -> option A -> option B)(m : NMap.t A),\n      (forall (i j : option A), f i j = g j i) ->\n      NMap_xmap2_l f m = NMap_xmap2_r g m.\n  Proof.\n    cbv -[PositiveMap.xmap2_r PositiveMap.xmap2_l].\n    intros; break_innermost_match; repeat (f_equal; eauto using PositiveMapAdditionalFacts.xmap2_lr).\n  Qed.\n\n  Section everything.\n    Let everything' : Everything.\n    Proof.\n      unshelve esplit.\n      all: try exact NMapTypFunctor.Node.\n      all: try exact NMapTypFunctor.t_rect.\n      all: try exact t_ind_full.\n      all: try exact NMap_xmap2_lr.\n      all: try exact NMap_xgmap2_l.\n      all: try exact NMap_xgmap2_r.\n      all: handle_id_fix.\n      all: subst_partial_evars.\n      all: try (destruct_head' option; destruct_head'_True; destruct_head'_False; reflexivity).\n      all: partial_unify e.\n      all: try reflexivity.\n    Defined.\n    Definition everything := Eval cbv [everything'] in everything'.\n  End everything.\nEnd NMapTrieInd.\n\nModule ZMapTypFunctor <: TypFunctor.\n  Local Unset Primitive Projections.\n  Local Set Nonrecursive Elimination Schemes.\n  Local Set Boolean Equality Schemes.\n  Local Set Decidable Equality Schemes.\n  Inductive t' (elt : Type) := Node' { data : option elt ; map : option_dep (ZMap.t (t' elt)) (Option.is_None data) }.\n  Definition t := t'.\n  Local Notation node_NonEmpty x y := match x, y with None, None => False | _, _ => True end.\n  Definition Node elt (data : option elt) (map : option (ZMap.t (t elt))) (pf : node_NonEmpty data map) : t elt\n    := @Node' _ data (match map, data return node_NonEmpty data map -> option_dep _ (Option.is_None data) with\n                      | Some m, _ => fun _ => Some_dep m\n                      | None, Some _ => fun _ => None_dep\n                      | None, None => fun pf => match pf with end\n                      end pf).\n  Global Arguments Node [elt] _ _ _.\n  Definition t_rect elt (P : t elt -> Type)\n             (val : forall (v : option elt) (m : option (ZMap.t (t elt))) (pf : node_NonEmpty v m), P (Node v m pf))\n             (m : t elt)\n    : P m\n    := Eval cbv beta in\n      match m return P m with\n      | {| data := d ; map := m |}\n        => match m in option_dep _ b, d return forall pf : is_None d = b, P {| data := d ; map := rew <- [option_dep _] pf in m |} with\n           | None_dep, None\n             => fun pf => match pf with\n                          | eq_refl => I\n                          end\n           | Some_dep _ m, Some d\n             => fun pf => match pf with\n                          | eq_refl => val (Some d) (Some m) I\n                          end\n           | None_dep as m, Some d\n             => fun pf => match pf with\n                          | eq_refl => ltac:(refine (fun x => x)) (val (Some d) None I)\n                          end\n           | Some_dep _ m, None\n             => fun pf => match pf with\n                          | eq_refl => val None (Some m) I\n                          end\n           end eq_refl\n      end.\nEnd ZMapTypFunctor.\n\nModule ZMapTrieInd <: Trie ZOrderedTypeBits ZMap.\n  Definition t := ZMapTypFunctor.t.\n  Include TrieShape ZOrderedTypeBits ZMap.\n\n  Definition ZMap_find_alt\n    := ltac:(let v := (eval cbv -[PositiveMap.find fst snd] in ZMap.find) in\n             lazymatch (eval pattern PositiveMap.find in v) with\n             | ?P _ => let v := (eval cbv beta in (P PositiveMapTrieInd.PositiveMap_find_alt)) in\n                       exact v\n             end).\n\n  Lemma eq_ZMap_find_alt A : forall i m, @ZMap.find A i m = @ZMap_find_alt A i m.\n  Proof using Type.\n    cbv -[PositiveMap.find PositiveMapTrieInd.PositiveMap_find_alt].\n    intros; break_innermost_match; rewrite ?PositiveMapTrieInd.eq_PositiveMap_find_alt; reflexivity.\n  Qed.\n\n  Definition t_ind_full elt (P : t elt -> Prop)\n             (H : forall d m pf,\n                 (forall k v, match m with Some m => ZMap.find k m = Some v -> P v | None => True end)\n                 -> P (ZMapTypFunctor.Node d m pf))\n    : forall m, P m.\n  Proof using Type.\n    fix t_ind_full 1.\n    induction m as [d m pf] using ZMapTypFunctor.t_rect.\n    specialize (H d m pf).\n    apply H; clear H.\n    destruct m as [[[mn [[m0 m]]]]|]; [ | intros; exact I ].\n    intros [|k|k]; [ | revert k | revert k ].\n    all: cbv -[PositiveMap.find t].\n    { destruct m0 as [m0|]; [ | clear; intros; inversion_option ].\n      specialize (t_ind_full m0).\n      intro v.\n      refine (fun pf => match pf with\n                        | eq_refl => t_ind_full\n                        end). }\n    all: let m := lazymatch goal with |- context[PositiveMap.find _ ?m] => m end in\n         induction m;\n         [ clear t_ind_full\n         | match goal with\n           | [ H : option _ |- _ ]\n             => let x := fresh \"x\" in\n                destruct H as [x|];\n                [ specialize (t_ind_full x)\n                | clear t_ind_full ]\n           end ].\n    all: intros k v H.\n    all: try solve [ exfalso; clear -H; abstract (destruct k; cbn in H; inversion_option) ].\n    all: destruct k; cbn [PositiveMap.find] in *.\n    all: lazymatch goal with\n         | [ H : None = Some _ |- _ ] => exfalso; clear -H; abstract inversion_option\n         | [ H : ?P ?x, H' : Some ?x = Some ?y |- ?P ?y ]\n           => refine (rew [P] (f_equal (fun v => Option.value v x) H') in H)\n         | _ => idtac\n         end.\n    all: eauto with nocore.\n  Defined.\n\n  Section map2.\n    Variable A B C : Type.\n    Variable f : option A -> option B -> option C.\n\n    Definition ZMap_xmap2_l (m : ZMap.t A) : ZMap.t C\n      := ltac:(let v := (eval cbv -[PositiveMap.map2] in (ZMap.map2 f m (@ZMap.empty _))) in\n               lazymatch (eval pattern (PositiveMap.map2 f) in v) with\n               | ?P _ => let v := (eval cbv beta in (P (fun m _ => PositiveMap.xmap2_l f m))) in\n                         exact v\n               end).\n\n    Definition ZMap_xmap2_r (m : ZMap.t B) : ZMap.t C\n      := ltac:(let v := (eval cbv -[PositiveMap.map2] in (ZMap.map2 f (@ZMap.empty _) m)) in\n               lazymatch (eval pattern (PositiveMap.map2 f) in v) with\n               | ?P _ => let v := (eval cbv beta in (P (fun _ m => PositiveMap.xmap2_r f m))) in\n                         exact v\n               end).\n\n    Lemma ZMap_xgmap2_l : forall (i : ZMap.key) (m : ZMap.t A),\n        f None None = None -> ZMap.find i (ZMap_xmap2_l m) = f (ZMap.find i m) None.\n    Proof using Type.\n      cbv -[PositiveMap.find PositiveMap.xmap2_l]; intros; break_innermost_match; eauto.\n      all: now rewrite PositiveMap.xgmap2_l by assumption.\n    Qed.\n\n    Lemma ZMap_xgmap2_r : forall (i : ZMap.key) (m : ZMap.t B),\n        f None None = None -> ZMap.find i (ZMap_xmap2_r m) = f None (ZMap.find i m).\n    Proof using Type.\n      cbv -[PositiveMap.find PositiveMap.xmap2_r]; intros; break_innermost_match; eauto.\n      all: now rewrite PositiveMap.xgmap2_r by assumption.\n    Qed.\n  End map2.\n  Lemma ZMap_xmap2_lr :\n    forall (A B : Type)(f g: option A -> option A -> option B)(m : ZMap.t A),\n      (forall (i j : option A), f i j = g j i) ->\n      ZMap_xmap2_l f m = ZMap_xmap2_r g m.\n  Proof.\n    cbv -[PositiveMap.xmap2_r PositiveMap.xmap2_l].\n    intros; break_innermost_match; repeat (f_equal; eauto using PositiveMapAdditionalFacts.xmap2_lr).\n  Qed.\n\n  Section everything.\n    Let everything' : Everything.\n    Proof.\n      unshelve esplit.\n      all: try exact ZMapTypFunctor.Node.\n      all: try exact ZMapTypFunctor.t_rect.\n      all: try exact t_ind_full.\n      all: try exact ZMap_xmap2_lr.\n      all: try exact ZMap_xgmap2_l.\n      all: try exact ZMap_xgmap2_r.\n      all: handle_id_fix.\n      all: subst_partial_evars.\n      all: try (destruct_head' option; destruct_head'_True; destruct_head'_False; reflexivity).\n      all: partial_unify e.\n      all: try reflexivity.\n    Defined.\n    Definition everything := Eval cbv [everything'] in everything'.\n  End everything.\nEnd ZMapTrieInd.\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/FSets/FMapTrie/ShapeEx.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.29185042941547856}}
{"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.\n\n(******************************************************************************)\n(* Reducibility of configurations number 271 to 278, whose indices in         *)\n(* the_configs range over segment [270, 278).                                 *)\n(******************************************************************************)\n\nLemma red270to278 : reducible_in_range 270 278 the_configs.\nProof. CheckReducible. Qed.\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/job271to278.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.29185042941547856}}
{"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(** Branch tunneling (optimization of branches to branches). *)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import UnionFind.\nRequire Import AST.\nRequire Import LTL.\n\n(** Branch tunneling shortens sequences of branches (with no intervening\n  computations) by rewriting the branch and conditional branch instructions\n  so that they jump directly to the end of the branch sequence.\n  For example:\n<<\n     L1: nop L2;                          L1: nop L3;\n     L2; nop L3;               becomes    L2: nop L3;\n     L3: instr;                           L3: instr;\n     L4: if (cond) goto L1;               L4: if (cond) goto L3;\n>>\n  This optimization can be applied to several of our intermediate\n  languages.  We choose to perform it on the [LTL] language,\n  after register allocation but before code linearization.\n  Register allocation can delete instructions (such as dead\n  computations or useless moves), therefore there are more\n  opportunities for tunneling after allocation than before.\n  Symmetrically, prior tunneling helps linearization to produce\n  better code, e.g. by revealing that some [nop] instructions are\n  dead code (as the \"nop L3\" in the example above).\n*)\n\n(** The naive implementation of branch tunneling would replace\n  any branch to a node [pc] by a branch to the node\n  [branch_target f pc], defined as follows:\n<<\n  branch_target f pc = branch_target f pc'  if f(pc) = nop pc'\n                     = pc                   otherwise\n>>\n  However, this definition can fail to terminate if\n  the program can contain loops consisting only of branches, as in\n<<\n     L1: nop L1;\n>>\n  or\n<<   L1: nop L2;\n     L2: nop L1;\n>>\n  Coq warns us of this fact by not accepting the definition \n  of [branch_target] above.\n\n  To handle this problem, we proceed in two passes.  The first pass\n  populates a union-find data structure, adding equalities [pc = pc']\n  for every instruction [pc: nop pc'] in the function. *)\n\nModule U := UnionFind.UF(PTree).\n\nDefinition record_goto (uf: U.t) (pc: node) (b: bblock) : U.t :=\n  match b with\n  | Lbranch s :: _ => U.union uf pc s\n  | _ => uf\n  end.\n\nDefinition record_gotos (f: LTL.function) : U.t :=\n  PTree.fold record_goto f.(fn_code) U.empty.\n\n(** The second pass rewrites all LTL instructions, replacing every\n  successor [s] of every instruction by the canonical representative\n  of its equivalence class in the union-find data structure. *)\n\nDefinition tunnel_instr (uf: U.t) (i: instruction) : instruction :=\n  match i with\n  | Lbranch s => Lbranch (U.repr uf s)\n  | Lcond cond args s1 s2 => Lcond cond args (U.repr uf s1) (U.repr uf s2)\n  | Ljumptable arg tbl => Ljumptable arg (List.map (U.repr uf) tbl)\n  | _ => i\n  end.\n\nDefinition tunnel_block (uf: U.t) (b: bblock) : bblock :=\n  List.map (tunnel_instr uf) b.\n\nDefinition tunnel_function (f: LTL.function) : LTL.function :=\n  let uf := record_gotos f in\n  mkfunction\n    (fn_sig f)\n    (fn_stacksize f)\n    (PTree.map1 (tunnel_block uf) (fn_code f))\n    (U.repr uf (fn_entrypoint f)).\n\nDefinition tunnel_fundef (f: LTL.fundef) : LTL.fundef :=\n  transf_fundef tunnel_function f.\n\nDefinition tunnel_program (p: LTL.program) : LTL.program :=\n  transform_program tunnel_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/backend/Tunneling.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.29180309992347}}
{"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 [ tptr pair_pair_t, tint ]\n    PROP  (readable_share sh; 0 <= i < array_size)\n    PARAMS (pps; 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 () RETURN (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 [ tptr tuint ]\n          PROP  (Int.unsigned (Int.shru (Int.repr tag) (Int.repr 10)) = n)\n          PARAMS (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          RETURN (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))\n   (Int.shl (Int.repr (Znth 1 arr)) (Int.repr  8)))\n   (Int.shl (Int.repr (Znth 2 arr)) (Int.repr 16)))\n   (Int.shl (Int.repr (Znth 3 arr)) (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 [ tptr tuchar ]\n    PROP (Zlength arr = 4;\n          readable_share in_sh;\n          forall i, 0 <= i < 4 -> 0 <= Znth i arr <= Byte.max_unsigned)\n    PARAMS (input)\n    SEP (data_at in_sh (tarray tuchar 4) (map Vint (map Int.repr arr)) input)\n  POST [ tuint ]\n    PROP() RETURN (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 _] => \n   specialize (H i); spec H; [ computable | ];\n   rewrite Int.unsigned_repr; rep_lia\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. simpl map.\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, !Zlength_map in H0.\n  destruct (zlt n 0); [elimtype False | ].\n  rewrite Z.max_l in H0 by lia.\n  pose proof (Zlength_nonneg contents).\n  lia.\n  rewrite Z.max_r in H0 by lia. lia.  \n}\nassert (Zlength (tag :: contents) = 1 + n) as LEN1. {\n  rewrite Zlength_cons. lia.\n}\nassert (N0: 0 <= n). {\n  pose proof (Zlength_nonneg contents). lia.\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.\n(* rewrite !Znth_0_cons. *)\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- (* precondition implies invariant: *)\n  entailer!.\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. unfold sizeof; simpl. lia.\n  }\n  forward.\n  forward.\n  entailer!.\n  rewrite Znth_pos_cons by lia.\n  autorewrite with sublist. simpl.  \n  f_equal. rewrite Int.add_assoc. f_equal.\n  rewrite (sublist_split 0 i (i+1)) by lia.\n  rewrite sublist_len_1 by lia.\n  replace (1 + i - 1) with i by lia.\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. unfold sizeof; simpl. lia.\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": "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_load_demo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.291803093356973}}
{"text": "From machine_program_logic.program_logic Require Import weakestpre.\nFrom HypVeri Require Import lifting rules.rules_base machine_extra.\nFrom HypVeri.algebra Require Import base mem reg pagetable mailbox trans base_extra.\nFrom HypVeri.lang Require Import lang_extra reg_extra mem_extra pagetable_extra trans_extra.\n\nSection mem_send.\n\nContext `{hypparams: HypervisorParameters}.\nContext `{vmG: !gen_VMG Σ}.\n\nLemma size_singleton_le `{Countable K}  (i:K) (s: gset K):\n  i ∈ s -> size s ≤ 1 -> s = {[i]}.\nProof.\n  intros Hin Hle.\n  assert (size s = 1) as Hsize.\n  {\n    assert (size s ≠ 0).\n    intro.\n    destruct (decide (s = ∅)).\n    set_solver.\n    apply size_empty_inv in H1.\n    set_solver + H1 n.\n    lia.\n  }\n  assert (s = {[i]}) as ->.\n  {\n    rewrite set_eq.\n    intro. split. intros.\n    apply (size_singleton_inv _ i x) in Hsize.\n    subst x. set_solver +.\n    done. done. intro.\n    rewrite elem_of_singleton in H1.\n    subst x. done.\n  }\n  done.\nQed.\n\nLemma parse_transaction_descriptor_tx mem_tx mem p_tx len tran:\n parse_transaction_descriptor mem_tx (of_pid p_tx) len = Some tran ->\n map_Forall (λ k v, mem !! k = Some v) mem_tx ->\n parse_transaction_descriptor mem (of_pid p_tx) len = Some tran.\nProof.\n  rewrite /parse_transaction_descriptor.\n  rewrite /parse_list_of_Word.\n  intros Hparse Hforall.\n  destruct (sequence_a (map (λ v : Addr, mem_tx !! v) (finz.seq p_tx len))) eqn:Heqn;last done.\n  assert (sequence_a (map (λ v : Addr, mem !! v) (finz.seq p_tx len)) = Some l) as ->.\n  {\n    apply (sequence_a_map_subseteq _ _ _ mem_tx). done.\n    rewrite map_subseteq_spec.\n    intros.\n    apply Hforall.\n    done.\n  }\n  done.\nQed.\n\nLemma parse_transaction_descriptor_tx_None mem_tx mem p_tx len:\n parse_transaction_descriptor mem_tx (of_pid p_tx) len = None ->\n (len <= page_size)%Z ->\n dom mem_tx = list_to_set (addr_of_page p_tx) ->\n map_Forall (λ k v, mem !! k = Some v) mem_tx ->\n parse_transaction_descriptor mem (of_pid p_tx) len = None.\nProof.\n  rewrite /parse_transaction_descriptor.\n  rewrite /parse_list_of_Word.\n  intros Hparse Hle Hdom Hforall.\n  destruct (sequence_a (map (λ v : Addr, mem_tx !! v) (finz.seq p_tx len))) eqn:Heqn.\n  2: {\n    destruct len eqn:Hlen.\n    done.\n    feed pose proof (sequence_a_map_Forall_Some (S n) p_tx mem_tx).\n    rewrite Hdom.\n    apply addr_of_page_subseteq.\n    lia.\n    destruct H0 as [? [H0 ?]].\n    rewrite H0 // in Heqn.\n  }\n  assert (sequence_a (map (λ v : Addr, mem !! v) (finz.seq p_tx len)) = Some l) as ->.\n  {\n    apply (sequence_a_map_subseteq _ _ _ mem_tx). done.\n    rewrite map_subseteq_spec.\n    intros.\n    apply Hforall.\n    done.\n  }\n  done.\nQed.\n\nLemma parse_list_of_Word_length mem p len l:\n  parse_list_of_Word mem p len = Some l ->\nlength l = len.\nProof.\n  rewrite /parse_list_of_Word.\n  revert p l.\n  induction len.\n  -  intros p l H0. simpl in H0.\n     rewrite /monad.List.sequence_a_list /= in H0.\n     inversion H0.\n     done.\n  -  intros p l H0. simpl in H0.\n     destruct (mem !! p).\n     {\n     rewrite /monad.List.sequence_a_list /= in H0.\n     destruct (list.foldr _) eqn:Heqn.\n     inversion H0.\n     simpl.\n     rewrite (IHlen (p ^+ 1)%f) //.\n     rewrite /sequence_a /= /monad.List.sequence_a_list /=.\n     done.\n     }\n     rewrite /monad.List.sequence_a_list /= in H0.\n     done.\nQed.\n\nLemma parse_list_of_pids_length l f3 l0:\n  parse_list_of_pids l f3 = Some l0->\n  length l = length l0.\nProof.\n  revert l0 f3.\n  induction l.\n  - intros l0 f3 Hparse.\n    rewrite /parse_list_of_pids /=in Hparse.\n    destruct (Option.bool_check_option (Z.to_nat f3 =? 0)%nat).\n    2: done.\n    rewrite /monad.List.sequence_a_list /= in Hparse.\n    inversion Hparse.\n    done.\n  - intros l0 f3 Hparse.\n    rewrite /parse_list_of_pids /=in Hparse.\n    destruct (Option.bool_check_option (Z.to_nat f3 =? S (length l))%nat) eqn:Heq_f3.\n    2: done.\n    rewrite /monad.List.sequence_a_list /= in Hparse.\n    destruct (to_pid a).\n    2: done.\n    destruct ( list.foldr\n                 (λ (val : option PID) (acc : option (list PID)),\n                   match match val with\n                         | Some x' => Some (cons x')\n                         | None => None\n                         end with\n                   | Some f' => match acc with\n                                | Some a' => Some (f' a')\n                                | None => None\n                                end\n                   | None => None\n                   end)) eqn:Heq_fold.\n    inversion Hparse.\n    simpl.\n    erewrite (IHl l1 (f3 ^- 1)%f).\n    done.\n    rewrite /parse_list_of_pids.\n    destruct ((Option.bool_check_option (Z.to_nat (f3 ^- 1)%f =? length l)%nat)) eqn:Heq_f3'.\n    simpl.\n    rewrite /monad.List.sequence_a_list /=.\n    rewrite Heq_fold //.\n    assert ((Z.to_nat (f3 ^- 1)%f =? length l)%nat = true).\n    {\n      rewrite Nat.eqb_eq.\n      destruct ((Z.to_nat f3 =? S (length l))%nat) eqn: Heq_f3''.\n      2: { simpl in Heq_f3. done. }\n      rewrite Nat.eqb_eq in Heq_f3''.\n      solve_finz.\n    }\n    rewrite H0 in Heq_f3'.\n    done.\n    done.\nQed.\n\nLemma size_list_to_set' `{Countable A} (l: list A):\n  size (list_to_set (C:= gset _) l) <= length l.\nProof.\n  unfold size, set_size. simpl.\n  induction l.\n  simpl.\n  rewrite elements_empty.\n  rewrite nil_length.\n  lia.\n  simpl.\n  destruct (decide (a ∈(list_to_set (C:= gset _) l))).\n  {\n    assert ({[a]} ∪ list_to_set l = list_to_set (C:= gset _) l) as ->.\n    set_solver +e.\n    lia.\n  }\n  rewrite elements_union_singleton //.\n  simpl.\n  lia.\nQed.\n\nLemma parse_transaction_descriptor_length mem p_tx len tran:\n parse_transaction_descriptor mem (of_pid p_tx) len = Some tran ->\n (size (tran.2) + 4 <= len)%Z.\nProof.\n  rewrite /parse_transaction_descriptor.\n  intros Hparse.\n  destruct (parse_list_of_Word mem p_tx len) eqn:Heqn.\n  simpl in Hparse.\n  2:{ rewrite //= in Hparse. }\n  destruct (l !! 0) as [f1|];\n  destruct (l !! 1) as [f2|];\n  destruct (l !! 2) as [f3|];\n  destruct (l !! 3) as [f4|] eqn:Hlk4; try destruct (decode_vmid f1);rewrite //= in Hparse;\n  destruct (decode_vmid f4);rewrite //= in Hparse.\n  destruct (parse_list_of_pids (drop 4 l) f3) eqn:Hl0.\n  inversion Hparse.\n  simpl.\n  apply parse_list_of_pids_length in Hl0.\n  rewrite drop_length in Hl0.\n  pose proof (size_list_to_set' l0).\n  rewrite -Hl0 in H0.\n  apply parse_list_of_Word_length in Heqn.\n  rewrite -Heqn.\n  assert (length l >= 4).\n  { pose proof (lookup_lt_is_Some_1 l 3).\n    feed specialize H2.\n    eauto.\n    lia.\n  }\n  lia.\n  done.\nQed.\n\nLemma p_share_inv_consist σ1 h i j ps:\n  inv_trans_pgt_consistent σ1->\n  inv_trans_sndr_rcvr_neq σ1.2 ->\n  σ1.2 !! h = Some None ->\n  set_Forall (λ p, get_page_table σ1 !! p = Some (Some i, true, {[i]})) ps ->\n  inv_trans_pgt_consistent (update_page_table_global flip_excl (alloc_transaction σ1 h (i, j, ps, Sharing, false)) i ps).\nProof.\n  intros Hinv_con Hinv_neq Hlk Hforall.\n  rewrite /inv_trans_pgt_consistent /inv_trans_pgt_consistent' /=.\n  rewrite map_Forall_lookup.\n  intros h' meta Hlookup'.\n  rewrite lookup_insert_Some in Hlookup'.\n  destruct Hlookup' as [[<- <-]|[Hneq Hlookup']].\n  { (* FIXED: cannot prove access is a singleton set. changed the excl RA to size acc && excl *)\n    intros p Hin.\n    simpl in *.\n    generalize dependent σ1.1.1.1.2.\n    induction ps using set_ind_L.\n    - set_solver + Hin.\n    - intros pgt Hforall.\n      rewrite set_fold_disj_union_strong.\n      {\n        rewrite set_fold_singleton.\n        destruct (decide (x = p)).\n        {\n          subst.\n          specialize (Hforall  p).\n          feed specialize Hforall. set_solver +.\n          rewrite Hforall /=.\n          apply p_upd_pgt_pgt_not_elem.\n          done.\n          rewrite lookup_insert_Some.\n          left;done.\n        }\n        {\n          destruct ( pgt !! x).\n          {\n            rewrite IHps //.\n            set_solver + n Hin.\n            intros p' Hin'.\n            rewrite lookup_insert_ne.\n            apply Hforall.\n            set_solver + Hin'.\n            set_solver + Hin' H0.\n          }\n          {\n            rewrite IHps //.\n            set_solver + n Hin.\n            intros p' Hin'.\n            apply Hforall.\n            set_solver + Hin'.\n          }\n        }\n      }\n      apply upd_is_strong_assoc_comm.\n      set_solver + H0.\n  }\n  {\n    rewrite /inv_trans_pgt_consistent /inv_trans_pgt_consistent' /= in Hinv_con.\n    specialize (Hinv_con h' meta Hlookup').\n    simpl in Hinv_con.\n    destruct meta as [[[[[sv rv] ps'] tt] b]|];last done.\n    simpl in *.\n    intros p Hin.\n    specialize (Hinv_con p Hin).\n    assert (p ∉ ps).\n    {\n      intro.\n      specialize (Hforall p H0).\n      rewrite Hforall in Hinv_con.\n      destruct tt; destruct b;auto;\n        try set_solver + Hinv_con.\n      specialize (Hinv_neq h' _ Hlookup').\n      simpl in Hinv_neq.\n      set_solver.\n    }\n    destruct tt,b;auto; try apply p_upd_pgt_pgt_not_elem;auto.\n  }\nQed.\n\nLemma p_not_share_inv_consist tt σ1 h i j ps:\n  tt ≠ Sharing ->\n  inv_trans_pgt_consistent σ1->\n  inv_trans_sndr_rcvr_neq σ1.2 ->\n  σ1.2 !! h = Some None ->\n  set_Forall (λ p, get_page_table σ1 !! p = Some (Some i, true, {[i]})) ps ->\n  inv_trans_pgt_consistent (update_page_table_global revoke_access (alloc_transaction σ1 h (i, j, ps, tt, false)) i ps).\nProof.\n  intros Htt Hinv_con Hinv_neq Hlk Hforall.\n  rewrite /inv_trans_pgt_consistent /inv_trans_pgt_consistent' /=.\n  rewrite map_Forall_lookup.\n  intros h' meta Hlookup'.\n  rewrite lookup_insert_Some in Hlookup'.\n  destruct Hlookup' as [[<- <-]|[Hneq Hlookup']].\n  { (* FIXED: cannot prove access is a singleton set. changed the excl RA to size acc && excl *)\n    intros p Hin.\n    simpl in *.\n    generalize dependent σ1.1.1.1.2.\n    induction ps using set_ind_L.\n    - set_solver + Hin.\n    - intros pgt Hforall.\n      rewrite set_fold_disj_union_strong.\n      {\n        rewrite set_fold_singleton.\n        destruct (decide (x = p)).\n        {\n          subst.\n          specialize (Hforall p).\n          feed specialize Hforall. set_solver +.\n          rewrite Hforall /=.\n          assert ({[i]} ∖ {[i]} = (∅: gset _)). set_solver +.\n          destruct tt.\n          apply p_upd_pgt_pgt_not_elem.\n          done.\n          rewrite lookup_insert_Some.\n          left;split;auto.\n          rewrite H1 //.\n          done.\n          apply p_upd_pgt_pgt_not_elem.\n          done.\n          rewrite lookup_insert_Some.\n          left;split;auto.\n          rewrite H1 //.\n        }\n        {\n          destruct ( pgt !! x).\n          {\n            apply IHps.\n            set_solver + n Hin.\n            intros p' Hin'.\n            rewrite lookup_insert_ne.\n            apply Hforall.\n            set_solver + Hin'.\n            set_solver + Hin' H0.\n          }\n          {\n            apply IHps.\n            set_solver + n Hin.\n            intros p' Hin'.\n            apply Hforall.\n            set_solver + Hin'.\n          }\n        }\n      }\n      apply upd_is_strong_assoc_comm.\n      set_solver + H0.\n  }\n  {\n    rewrite /inv_trans_pgt_consistent /inv_trans_pgt_consistent' /= in Hinv_con.\n    specialize (Hinv_con h' meta Hlookup').\n    simpl in Hinv_con.\n    destruct meta as [[[[[sv rv] ps'] tt'] b]|];last done.\n    simpl in *.\n    intros p Hin.\n    specialize (Hinv_con p Hin).\n    assert (p ∉ ps).\n    {\n      intro.\n      specialize (Hforall p H0).\n      rewrite Hforall in Hinv_con.\n      destruct tt'; destruct b;auto;\n        try set_solver + Hinv_con.\n      specialize (Hinv_neq h' _ Hlookup').\n      simpl in Hinv_neq.\n      set_solver.\n    }\n    destruct tt',b;auto; try apply p_upd_pgt_pgt_not_elem;auto.\n  }\nQed.\n\n\nLemma mem_send_invalid_len {i wi r0 r1 r2 hvcf tt q sacc p_tx} ai :\n  (tpa ai) ∈ sacc ->\n  (tpa ai) ≠ p_tx ->\n  let len := (finz.to_z r1) in\n  decode_instruction wi = Some(Hvc) ->\n  decode_hvc_func r0 = Some(hvcf) ->\n  hvcf_to_tt hvcf = Some tt ->\n  (page_size < len)%Z ->\n  {SS{{ ▷(PC @@ i ->r ai) ∗\n      ▷ ai ->a wi ∗\n      ▷ (i -@{q}A> sacc) ∗\n      ▷ (R0 @@ i ->r r0) ∗\n      ▷ (R1 @@ i ->r r1) ∗\n      ▷ (R2 @@ i ->r r2) ∗\n      ▷ TX@ i := p_tx\n       }}}\n   ExecI @ i {{{ RET (false, ExecI) ;\n                 PC @@ i ->r (ai ^+ 1)%f ∗\n                 ai ->a wi ∗\n                 i -@{q}A> sacc ∗\n                 R0 @@ i ->r (encode_hvc_ret_code Error) ∗\n                 R1 @@ i ->r r1 ∗\n                 R2 @@ i ->r (encode_hvc_error InvParam) ∗\n                 TX@ i := p_tx}}}.\nProof.\n  iIntros (Hin_acc Hneq_tx len Hdecode_i Hdecode_f Htt Hgt_ps Φ)\n          \"(>PC & >mem_ins & >acc & >R0 & >R1 & >R2 & >tx) HΦ\".\n  iApply (sswp_lift_atomic_step ExecI);[done|].\n  iIntros (n σ1) \"%Hsche state\".\n  rewrite /scheduled /= /scheduler in Hsche.\n  assert (σ1.1.1.2 = i) as Heq_cur. { case_bool_decide;last done. by apply fin_to_nat_inj. }\n  clear Hsche.\n  iModIntro.\n  iDestruct \"state\" as \"(Hnum & mem & regs & mb & rx_state & pgt_owned & pgt_acc & pgt_excl &\n                            trans & hpool & retri & %Hwf & %Hdisj & %Hconsis)\".\n  (* valid regs *)\n  iDestruct ((gen_reg_valid4 i PC ai R0 r0 R1 r1 R2 r2 Heq_cur) with \"regs PC R0 R1 R2\")\n    as \"(%Hlookup_PC & %Hlookup_R0 & %Hlookup_R1 & %Hlookup_R2)\";eauto.\n  (* valid pt *)\n  iDestruct (access_agree_check_true (tpa ai) i with \"pgt_acc acc\") as %Hcheckpg_ai;eauto.\n  (* valid mem *)\n  iDestruct (gen_mem_valid ai wi with \"mem mem_ins\") as %Hlookup_ai.\n  (* valid tx *)\n  iDestruct (mb_valid_tx i p_tx with \"mb tx\") as %Heq_tx.\n  (* valid tran *)\n  iSplit.\n  - (* reducible *)\n    iPureIntro.\n    apply (reducible_normal i Hvc ai wi);auto.\n    rewrite Heq_tx //.\n  - iModIntro.\n    iIntros (m2 σ2) \"vmprop_auth %HstepP\".\n    iFrame \"vmprop_auth\".\n    apply (step_ExecI_normal i Hvc ai wi) in HstepP;eauto.\n    2: rewrite Heq_tx //.\n    remember (exec Hvc σ1) as c2 eqn:Heqc2.\n    rewrite /exec /hvc Hlookup_R0 /= Hdecode_f /mem_send Hlookup_R1 /= in Heqc2.\n    case_bool_decide;last lia.\n    rewrite /= in Heqc2.\n    assert (Heq_c2 : (m2,σ2) = (ExecI, update_incr_PC (update_reg (update_reg σ1 R0 (encode_hvc_ret_code Error)) R2 (encode_hvc_error InvParam)))).\n    {\n      destruct hvcf; inversion Htt;\n        destruct HstepP;subst m2 σ2; subst c2; done.\n    }\n    inversion Heq_c2. clear H2 H3 Heqc2 Heq_c2.\n    rewrite /=.\n    iDestruct (hvc_error_update (E:= ⊤) InvParam with \"PC R0 R2 [$Hnum $mem $regs $mb $rx_state $pgt_owned $pgt_acc $pgt_excl $ trans $hpool $retri]\")\n    as \">[[$ $] ?]\";auto.\n    rewrite /scheduled /machine.scheduler /= /scheduler.\n    rewrite p_upd_pc_current_vm 2!p_upd_reg_current_vm Heq_cur.\n    case_bool_decide;last contradiction.\n    simpl. iApply \"HΦ\".\n    iFrame.\n    by iFrame.\nQed.\n\nLemma mem_send_invalid_msg {i wi r0 r1 r2 hvcf tt p_tx q sacc} ai mem_tx :\n  (tpa ai) ∈ sacc ->\n  (tpa ai) ≠ p_tx ->\n  let len := (Z.to_nat (finz.to_z r1)) in\n  decode_instruction wi = Some(Hvc) ->\n  decode_hvc_func r0 = Some(hvcf) ->\n  hvcf_to_tt hvcf = Some tt ->\n  (len <= page_size)%Z ->\n  parse_transaction_descriptor mem_tx (of_pid p_tx) len = None ->\n  {SS{{ ▷(PC @@ i ->r ai) ∗\n      ▷ ai ->a wi ∗\n      ▷ (i -@{q}A> sacc) ∗\n      ▷ (R0 @@ i ->r r0) ∗\n      ▷ (R1 @@ i ->r r1) ∗\n      ▷ (R2 @@ i ->r r2) ∗\n      ▷ (TX@ i := p_tx) ∗\n      ▷ (memory_page p_tx mem_tx)\n       }}}\n   ExecI @ i {{{ RET (false, ExecI) ;\n                 PC @@ i ->r (ai ^+ 1)%f ∗\n                 ai ->a wi ∗\n                 i -@{q}A> sacc ∗\n                 R0 @@ i ->r (encode_hvc_ret_code Error) ∗\n                 R1 @@ i ->r r1 ∗\n                 R2 @@ i ->r (encode_hvc_error InvParam) ∗\n                 TX@ i := p_tx ∗\n                 memory_page p_tx mem_tx\n    }}}.\nProof.\n  iIntros (Hin_acc Hneq_tx len Hdecode_i Hdecode_f Htt Hle_ps Hparse Φ)\n          \"(>PC & >mem_ins & >acc & >R0 & >R1 & >R2 & >tx & >mem_tx) HΦ\".\n  iApply (sswp_lift_atomic_step ExecI);[done|].\n  iIntros (n σ1) \"%Hsche state\".\n  rewrite /scheduled /= /scheduler in Hsche.\n  assert (σ1.1.1.2 = i) as Heq_cur. { case_bool_decide;last done. by apply fin_to_nat_inj. }\n  clear Hsche.\n  iModIntro.\n  iDestruct \"state\" as \"(Hnum & mem & regs & mb & rx_state & pgt_owned & pgt_acc & pgt_excl &\n                            trans & hpool & retri & %Hwf & %Hdisj & %Hconsis)\".\n  (* valid regs *)\n  iDestruct ((gen_reg_valid4 i PC ai R0 r0 R1 r1 R2 r2 Heq_cur) with \"regs PC R0 R1 R2\")\n    as \"(%Hlookup_PC & %Hlookup_R0 & %Hlookup_R1 & %Hlookup_R2)\";eauto.\n  (* valid pt *)\n  iDestruct (access_agree_check_true (tpa ai) i with \"pgt_acc acc\") as %Hcheckpg_ai;eauto.\n  (* valid mem *)\n  iDestruct (gen_mem_valid ai wi with \"mem mem_ins\") as %Hlookup_ai.\n  iDestruct (gen_mem_valid_SepM with \"mem [mem_tx]\") as %Hlookup_mem_tx.\n  { iDestruct \"mem_tx\" as \"[% mem_tx]\". iExact \"mem_tx\". }\n  (* valid tx *)\n  iDestruct (mb_valid_tx i p_tx with \"mb tx\") as %Heq_tx.\n  (* valid tran *)\n  iSplit.\n  - (* reducible *)\n    iPureIntro.\n    apply (reducible_normal i Hvc ai wi);auto.\n    rewrite Heq_tx //.\n  - iModIntro.\n    iIntros (m2 σ2) \"vmprop_auth %HstepP\".\n    iFrame \"vmprop_auth\".\n    apply (step_ExecI_normal i Hvc ai wi) in HstepP;eauto.\n    2: rewrite Heq_tx //.\n    remember (exec Hvc σ1) as c2 eqn:Heqc2.\n    rewrite /exec /hvc Hlookup_R0 /= Hdecode_f /mem_send Hlookup_R1 /= in Heqc2.\n    case_bool_decide;first lia.\n    iDestruct \"mem_tx\" as \"[%Hdom_mem_tx mem_tx]\".\n    rewrite -Heq_tx -Heq_cur /len in Hparse.\n    apply (parse_transaction_descriptor_tx_None _ σ1.1.2) in Hparse;try lia; last done.\n    2: { rewrite Heq_cur Heq_tx //. }\n    rewrite Hparse /= in Heqc2.\n    assert (Heq_c2 : (m2,σ2) = (ExecI, update_incr_PC (update_reg (update_reg σ1 R0 (encode_hvc_ret_code Error)) R2 (encode_hvc_error InvParam)))).\n    {\n      destruct hvcf; inversion Htt;\n        destruct HstepP;subst m2 σ2; subst c2; done.\n    }\n    inversion Heq_c2. clear H2 H3 Heqc2 Heq_c2.\n    iAssert (memory_page p_tx mem_tx) with \"[$mem_tx]\" as \"mem_tx\". done.\n    rewrite /=.\n    iDestruct (hvc_error_update (E:= ⊤) InvParam with \"PC R0 R2 [$Hnum $mem $regs $mb $rx_state $pgt_owned $pgt_acc $pgt_excl $ trans $hpool $retri]\")\n    as \">[[$ $] ?]\". 1-4: auto. iPureIntro. auto.\n    rewrite /scheduled /machine.scheduler /= /scheduler.\n    rewrite p_upd_pc_current_vm 2!p_upd_reg_current_vm Heq_cur.\n    case_bool_decide;last contradiction.\n    simpl. iApply \"HΦ\".\n    iFrame.\n    by iFrame.\nQed.\n\nLemma mem_send_invalid_des {i wi r0 r1 r2 hvcf p_tx tt q sacc} ai mem_tx tran :\n  (tpa ai) ∈ sacc ->\n  (tpa ai) ≠ p_tx ->\n  let len := (Z.to_nat (finz.to_z r1)) in\n  decode_instruction wi = Some(Hvc) ->\n  decode_hvc_func r0 = Some(hvcf) ->\n  hvcf_to_tt hvcf = Some tt ->\n  (len <= page_size)%Z ->\n  parse_transaction_descriptor mem_tx (of_pid p_tx) len = Some tran ->\n  validate_transaction_descriptor i tran = false ->\n  {SS{{ ▷(PC @@ i ->r ai) ∗\n      ▷ ai ->a wi ∗\n      ▷ i -@{q}A> sacc ∗\n      ▷ (R0 @@ i ->r r0) ∗\n      ▷ (R1 @@ i ->r r1) ∗\n      ▷ (R2 @@ i ->r r2) ∗\n      ▷ (TX@ i := p_tx) ∗\n      ▷ (memory_page p_tx mem_tx)\n       }}}\n   ExecI @ i {{{ RET (false, ExecI) ;\n                 PC @@ i ->r (ai ^+ 1)%f ∗\n                 ai ->a wi ∗\n                 i -@{q}A> sacc ∗\n                 R0 @@ i ->r (encode_hvc_ret_code Error) ∗\n                 R1 @@ i ->r r1 ∗\n                 R2 @@ i ->r (encode_hvc_error InvParam) ∗\n                 TX@ i := p_tx ∗\n                 memory_page p_tx mem_tx\n    }}}.\nProof.\n  iIntros (Hin_acc Hneq_tx len Hdecode_i Hdecode_f Htt Hle_ps Hparse Hvalid_des Φ)\n          \"(>PC & >mem_ins & >acc & >R0 & >R1 & >R2 & >tx & >mem_tx) HΦ\".\n  iApply (sswp_lift_atomic_step ExecI);[done|].\n  iIntros (n σ1) \"%Hsche state\".\n  rewrite /scheduled /= /scheduler in Hsche.\n  assert (σ1.1.1.2 = i) as Heq_cur. { case_bool_decide;last done. by apply fin_to_nat_inj. }\n  clear Hsche.\n  iModIntro.\n  iDestruct \"state\" as \"(Hnum & mem & regs & mb & rx_state & pgt_owned & pgt_acc & pgt_excl &\n                            trans & hpool & retri & %Hwf & %Hdisj & %Hconsis)\".\n  (* valid regs *)\n  iDestruct ((gen_reg_valid4 i PC ai R0 r0 R1 r1 R2 r2 Heq_cur) with \"regs PC R0 R1 R2\")\n    as \"(%Hlookup_PC & %Hlookup_R0 & %Hlookup_R1 & %Hlookup_R2)\";eauto.\n  (* valid pt *)\n  iDestruct (access_agree_check_true (tpa ai) i with \"pgt_acc acc\") as %Hcheckpg_ai;eauto.\n  (* valid mem *)\n  iDestruct (gen_mem_valid ai wi with \"mem mem_ins\") as %Hlookup_ai.\n  iDestruct (gen_mem_valid_SepM with \"mem [mem_tx]\") as %Hlookup_mem_tx.\n  { iDestruct \"mem_tx\" as \"[% mem_tx]\". iExact \"mem_tx\". }\n  (* valid tx *)\n  iDestruct (mb_valid_tx i p_tx with \"mb tx\") as %Heq_tx.\n  (* valid tran *)\n  iSplit.\n  - (* reducible *)\n    iPureIntro.\n    apply (reducible_normal i Hvc ai wi);eauto.\n    rewrite Heq_tx //.\n  - iModIntro.\n    iIntros (m2 σ2) \"vmprop_auth %HstepP\".\n    iFrame \"vmprop_auth\".\n    apply (step_ExecI_normal i Hvc ai wi) in HstepP;eauto.\n    2: rewrite Heq_tx //.\n    remember (exec Hvc σ1) as c2 eqn:Heqc2.\n    rewrite /exec /hvc Hlookup_R0 /= Hdecode_f /mem_send Hlookup_R1 /= in Heqc2.\n    case_bool_decide;first lia.\n    pose proof (parse_transaction_descriptor_length _ _ _ _ Hparse) as Hlt_pg.\n    rewrite -Heq_tx -Heq_cur /len in Hparse.\n    apply (parse_transaction_descriptor_tx _ σ1.1.2) in Hparse;last done.\n    rewrite Hparse /= Heq_cur Hvalid_des /= in Heqc2.\n    assert (Heq_c2 : (m2,σ2) = (ExecI, update_incr_PC (update_reg (update_reg σ1 R0 (encode_hvc_ret_code Error)) R2 (encode_hvc_error InvParam)))).\n    {\n      destruct hvcf; inversion Htt;\n        destruct HstepP;subst m2 σ2; subst c2; done.\n    }\n    inversion Heq_c2. clear H2 H3 Heq_c2.\n    rewrite /=.\n    iDestruct (hvc_error_update (E:= ⊤) InvParam with \"PC R0 R2 [$Hnum $mem $regs $mb $rx_state $pgt_owned $pgt_acc $pgt_excl $ trans $hpool $retri]\")\n    as \">[[$ $] ?]\". 1-4: auto. iPureIntro. auto.\n    rewrite /scheduled /machine.scheduler /= /scheduler.\n    rewrite p_upd_pc_current_vm 2!p_upd_reg_current_vm Heq_cur.\n    case_bool_decide;last contradiction.\n    simpl. iApply \"HΦ\".\n    iFrame.\n    by iFrame.\nQed.\n\nLemma mem_send_not_owned1 {i wi r0 r1 r2 hvcf p_tx tt q sacc} ai p mem_tx tran :\n  (tpa ai) ∈ sacc ->\n  (tpa ai) ≠ p_tx ->\n  let len := (Z.to_nat (finz.to_z r1)) in\n  decode_instruction wi = Some(Hvc) ->\n  decode_hvc_func r0 = Some(hvcf) ->\n  hvcf_to_tt hvcf = Some tt ->\n  (len <= page_size)%Z ->\n  parse_transaction_descriptor mem_tx (of_pid p_tx) len = Some tran ->\n  validate_transaction_descriptor i tran = true ->\n  p ∈ tran.2 ->\n  {SS{{ ▷(PC @@ i ->r ai) ∗\n      ▷ ai ->a wi ∗\n      ▷ i -@{q}A> sacc ∗\n      ▷ (R0 @@ i ->r r0) ∗\n      ▷ (R1 @@ i ->r r1) ∗\n      ▷ (R2 @@ i ->r r2) ∗\n      ▷ (TX@ i := p_tx) ∗\n      ▷ (memory_page p_tx mem_tx) ∗\n      ▷ p -@O> -\n       }}}\n   ExecI @ i {{{ RET (false, ExecI) ;\n                 PC @@ i ->r (ai ^+ 1)%f ∗\n                 ai ->a wi ∗\n                 i -@{q}A> sacc ∗\n                 R0 @@ i ->r (encode_hvc_ret_code Error) ∗\n                 R1 @@ i ->r r1 ∗\n                 R2 @@ i ->r (encode_hvc_error Denied) ∗\n                 TX@ i := p_tx ∗\n                 memory_page p_tx mem_tx ∗\n                 p -@O> -\n    }}}.\nProof.\n  iIntros (Hin_acc Hneq_tx len Hdecode_i Hdecode_f Htt Hle_ps Hparse Hvalid_des Hin_p Φ)\n          \"(>PC & >mem_ins & >acc & >R0 & >R1 & >R2 & >tx & >mem_tx & >own) HΦ\".\n  iApply (sswp_lift_atomic_step ExecI);[done|].\n  iIntros (n σ1) \"%Hsche state\".\n  rewrite /scheduled /= /scheduler in Hsche.\n  assert (σ1.1.1.2 = i) as Heq_cur. { case_bool_decide;last done. by apply fin_to_nat_inj. }\n  clear Hsche.\n  iModIntro.\n  iDestruct \"state\" as \"(Hnum & mem & regs & mb & rx_state & pgt_owned & pgt_acc & pgt_excl &\n                            trans & hpool & retri & %Hwf & %Hdisj & %Hconsis)\".\n  (* valid regs *)\n  iDestruct ((gen_reg_valid4 i PC ai R0 r0 R1 r1 R2 r2 Heq_cur) with \"regs PC R0 R1 R2\")\n    as \"(%Hlookup_PC & %Hlookup_R0 & %Hlookup_R1 & %Hlookup_R2)\";eauto.\n  (* valid pt *)\n  iDestruct (access_agree_check_true (tpa ai) i with \"pgt_acc acc\") as %Hcheckpg_ai;eauto.\n  iDestruct (own_agree_None_check _ i with \"pgt_owned own\") as %Hcheckpg_own_false.\n  (* valid mem *)\n  iDestruct (gen_mem_valid ai wi with \"mem mem_ins\") as %Hlookup_ai.\n  iDestruct (gen_mem_valid_SepM with \"mem [mem_tx]\") as %Hlookup_mem_tx.\n  { iDestruct \"mem_tx\" as \"[% mem_tx]\". iExact \"mem_tx\". }\n  (* valid tx *)\n  iDestruct (mb_valid_tx i p_tx with \"mb tx\") as %Heq_tx.\n  (* valid tran *)\n  iSplit.\n  - (* reducible *)\n    iPureIntro.\n    apply (reducible_normal i Hvc ai wi);eauto.\n    rewrite Heq_tx //.\n  - iModIntro.\n    iIntros (m2 σ2) \"vmprop_auth %HstepP\".\n    iFrame \"vmprop_auth\".\n    apply (step_ExecI_normal i Hvc ai wi) in HstepP;eauto.\n    2: rewrite Heq_tx //.\n    remember (exec Hvc σ1) as c2 eqn:Heqc2.\n    rewrite /exec /hvc Hlookup_R0 /= Hdecode_f /mem_send Hlookup_R1 /= in Heqc2.\n    case_bool_decide;first lia.\n    pose proof (parse_transaction_descriptor_length _ _ _ _ Hparse) as Hlt_pg.\n    rewrite -Heq_tx -Heq_cur /len in Hparse.\n    apply (parse_transaction_descriptor_tx _ σ1.1.2) in Hparse;last done.\n    rewrite Hparse /= Heq_cur Hvalid_des /= in Heqc2.\n    rewrite /check_transition_transaction /= in Heqc2.\n    destruct tran as [[[? ?] ?] ps].\n    rewrite /= in Heqc2.\n    case_bool_decide.\n    {\n      specialize (H1 p Hin_p).\n      rewrite andb_true_iff in H1.\n      rewrite /check_excl_access_page andb_true_iff in H1.\n      destruct H1 as [_ Hown].\n      rewrite Heq_cur Hcheckpg_own_false in Hown.\n      inversion Hown.\n    }\n    clear H1.\n    simpl in Heqc2.\n    assert (Heq_c2 : (m2,σ2) = (ExecI, update_incr_PC (update_reg (update_reg σ1 R0 (encode_hvc_ret_code Error)) R2 (encode_hvc_error Denied)))).\n    {\n      destruct hvcf; inversion Htt;\n        destruct HstepP;subst m2 σ2; subst c2; done.\n    }\n    inversion Heq_c2. clear H2 H3 Heq_c2.\n    rewrite /=.\n    iDestruct (hvc_error_update (E:= ⊤) Denied with \"PC R0 R2 [$Hnum $mem $regs $mb $rx_state $pgt_owned $pgt_acc $pgt_excl $ trans $hpool $retri]\")\n    as \">[[$ $] ?]\". 1-4: auto. iPureIntro. auto.\n    rewrite /scheduled /machine.scheduler /= /scheduler.\n    rewrite p_upd_pc_current_vm 2!p_upd_reg_current_vm Heq_cur.\n    case_bool_decide;last contradiction.\n    simpl. iApply \"HΦ\".\n    iFrame.\n    by iFrame.\nQed.\n\nLemma mem_send_not_owned2 {i wi r0 r1 r2 hvcf p_tx tt q sacc} j ai p mem_tx tran :\n  (tpa ai) ∈ sacc ->\n  (tpa ai) ≠ p_tx ->\n  let len := (Z.to_nat (finz.to_z r1)) in\n  decode_instruction wi = Some(Hvc) ->\n  decode_hvc_func r0 = Some(hvcf) ->\n  hvcf_to_tt hvcf = Some tt ->\n  (len <= page_size)%Z ->\n  parse_transaction_descriptor mem_tx (of_pid p_tx) len = Some tran ->\n  validate_transaction_descriptor i tran = true ->\n  p ∈ tran.2 ->\n  j ≠ i ->\n  {SS{{ ▷(PC @@ i ->r ai) ∗\n      ▷ ai ->a wi ∗\n      ▷ i -@{q}A> sacc ∗\n      ▷ (R0 @@ i ->r r0) ∗\n      ▷ (R1 @@ i ->r r1) ∗\n      ▷ (R2 @@ i ->r r2) ∗\n      ▷ (TX@ i := p_tx) ∗\n      ▷ (memory_page p_tx mem_tx) ∗\n      ▷ p -@O> j\n       }}}\n   ExecI @ i {{{ RET (false, ExecI) ;\n                 PC @@ i ->r (ai ^+ 1)%f ∗\n                 ai ->a wi ∗\n                 i -@{q}A> sacc ∗\n                 R0 @@ i ->r (encode_hvc_ret_code Error) ∗\n                 R1 @@ i ->r r1 ∗\n                 R2 @@ i ->r (encode_hvc_error Denied) ∗\n                 TX@ i := p_tx ∗\n                 memory_page p_tx mem_tx ∗\n                 p -@O> j\n    }}}.\nProof.\n  iIntros (Hin_acc Hneq_tx len Hdecode_i Hdecode_f Htt Hle_ps Hparse Hvalid_des Hin_p Hneq_i Φ)\n          \"(>PC & >mem_ins & >acc & >R0 & >R1 & >R2 & >tx & >mem_tx & >own) HΦ\".\n  iApply (sswp_lift_atomic_step ExecI);[done|].\n  iIntros (n σ1) \"%Hsche state\".\n  rewrite /scheduled /= /scheduler in Hsche.\n  assert (σ1.1.1.2 = i) as Heq_cur. { case_bool_decide;last done. by apply fin_to_nat_inj. }\n  clear Hsche.\n  iModIntro.\n  iDestruct \"state\" as \"(Hnum & mem & regs & mb & rx_state & pgt_owned & pgt_acc & pgt_excl &\n                            trans & hpool & retri & %Hwf & %Hdisj & %Hconsis)\".\n  (* valid regs *)\n  iDestruct ((gen_reg_valid4 i PC ai R0 r0 R1 r1 R2 r2 Heq_cur) with \"regs PC R0 R1 R2\")\n    as \"(%Hlookup_PC & %Hlookup_R0 & %Hlookup_R1 & %Hlookup_R2)\";eauto.\n  (* valid pt *)\n  iDestruct (access_agree_check_true (tpa ai) i with \"pgt_acc acc\") as %Hcheckpg_ai;eauto.\n  iDestruct (own_agree_Some_check_false _ i with \"pgt_owned own\") as %Hcheckpg_own_false;auto.\n  (* valid mem *)\n  iDestruct (gen_mem_valid ai wi with \"mem mem_ins\") as %Hlookup_ai.\n  iDestruct (gen_mem_valid_SepM with \"mem [mem_tx]\") as %Hlookup_mem_tx.\n  { iDestruct \"mem_tx\" as \"[% mem_tx]\". iExact \"mem_tx\". }\n  (* valid tx *)\n  iDestruct (mb_valid_tx i p_tx with \"mb tx\") as %Heq_tx.\n  (* valid tran *)\n  iSplit.\n  - (* reducible *)\n    iPureIntro.\n    apply (reducible_normal i Hvc ai wi);eauto.\n    rewrite Heq_tx //.\n  - iModIntro.\n    iIntros (m2 σ2) \"vmprop_auth %HstepP\".\n    iFrame \"vmprop_auth\".\n    apply (step_ExecI_normal i Hvc ai wi) in HstepP;eauto.\n    2: rewrite Heq_tx //.\n    remember (exec Hvc σ1) as c2 eqn:Heqc2.\n    rewrite /exec /hvc Hlookup_R0 /= Hdecode_f /mem_send Hlookup_R1 /= in Heqc2.\n    case_bool_decide;first lia.\n    pose proof (parse_transaction_descriptor_length _ _ _ _ Hparse) as Hlt_pg.\n    rewrite -Heq_tx -Heq_cur /len in Hparse.\n    apply (parse_transaction_descriptor_tx _ σ1.1.2) in Hparse;last done.\n    rewrite Hparse /= Heq_cur Hvalid_des /= in Heqc2.\n    rewrite /check_transition_transaction /= in Heqc2.\n    destruct tran as [[[? ?] ?] ps].\n    rewrite /= in Heqc2.\n    case_bool_decide.\n    {\n      specialize (H1 p Hin_p).\n      rewrite andb_true_iff in H1.\n      rewrite /check_excl_access_page andb_true_iff in H1.\n      destruct H1 as [_ Hown].\n      rewrite Heq_cur Hcheckpg_own_false in Hown.\n      inversion Hown.\n    }\n    clear H1.\n    simpl in Heqc2.\n    assert (Heq_c2 : (m2,σ2) = (ExecI, update_incr_PC (update_reg (update_reg σ1 R0 (encode_hvc_ret_code Error)) R2 (encode_hvc_error Denied)))).\n    {\n      destruct hvcf; inversion Htt;\n        destruct HstepP;subst m2 σ2; subst c2; done.\n    }\n    inversion Heq_c2. clear H2 H3 Heq_c2.\n    rewrite /=.\n    iDestruct (hvc_error_update (E:= ⊤) Denied with \"PC R0 R2 [$Hnum $mem $regs $mb $rx_state $pgt_owned $pgt_acc $pgt_excl $ trans $hpool $retri]\")\n    as \">[[$ $] ?]\". 1-4: auto. iPureIntro. auto.\n    rewrite /scheduled /machine.scheduler /= /scheduler.\n    rewrite p_upd_pc_current_vm 2!p_upd_reg_current_vm Heq_cur.\n    case_bool_decide;last contradiction.\n    simpl. iApply \"HΦ\".\n    iFrame.\n    by iFrame.\nQed.\n\n\n(* FIXME: It is not true since we have updated the excl RA, but it is not very important anyway.\n To prove it we need to change check_excl_page, or add a new invariant about the pagetable (size of acc R excl)*)\n(* Lemma mem_send_not_excl {i wi r0 r1 r2 hvcf p_tx tt q sacc} ai p mem_tx tran : *)\n(*   (tpa ai) ∈ sacc -> *)\n(*   (tpa ai) ≠ p_tx -> *)\n(*   let len := (Z.to_nat (finz.to_z r1)) in *)\n(*   decode_instruction wi = Some(Hvc) -> *)\n(*   decode_hvc_func r0 = Some(hvcf) -> *)\n(*   hvcf_to_tt hvcf = Some tt -> *)\n(*   (len <= page_size)%Z -> *)\n(*   parse_transaction_descriptor mem_tx (of_pid p_tx) len = Some tran -> *)\n(*   validate_transaction_descriptor i tran = true -> *)\n(*   p ∈ tran.2 -> *)\n(*   {SS{{ ▷(PC @@ i ->r ai) ∗ *)\n(*       ▷ ai ->a wi ∗ *)\n(*       ▷ i -@{q}A> sacc ∗ *)\n(*       ▷ (R0 @@ i ->r r0) ∗ *)\n(*       ▷ (R1 @@ i ->r r1) ∗ *)\n(*       ▷ (R2 @@ i ->r r2) ∗ *)\n(*       ▷ (TX@ i := p_tx) ∗ *)\n(*       ▷ (memory_page p_tx mem_tx) ∗ *)\n(*       ▷ (p -@E> false) *)\n(*        }}} *)\n(*    ExecI @ i {{{ RET (false, ExecI) ; *)\n(*                  PC @@ i ->r (ai ^+ 1)%f ∗ *)\n(*                  ai ->a wi ∗ *)\n(*                  i -@{q}A> sacc ∗ *)\n(*                  R0 @@ i ->r (encode_hvc_ret_code Error) ∗ *)\n(*                  R1 @@ i ->r r1 ∗ *)\n(*                  R2 @@ i ->r (encode_hvc_error Denied) ∗ *)\n(*                  TX@ i := p_tx ∗ *)\n(*                  memory_page p_tx mem_tx ∗ *)\n(*                  p -@E> false *)\n(*     }}}. *)\n(* Proof. *)\n(* Admitted. *)\n\nLemma mem_send_not_acc {i wi r0 r1 r2 hvcf p_tx tt sacc} ai p mem_tx tran:\n  (tpa ai) ∈ sacc ->\n  (tpa ai) ≠ p_tx ->\n  let len := (Z.to_nat (finz.to_z r1)) in\n  decode_instruction wi = Some(Hvc) ->\n  decode_hvc_func r0 = Some(hvcf) ->\n  hvcf_to_tt hvcf = Some tt ->\n  (len <= page_size)%Z ->\n  parse_transaction_descriptor mem_tx (of_pid p_tx) len = Some tran ->\n  validate_transaction_descriptor i tran = true ->\n  p ∈ tran.2 ->\n  p ∉ sacc ->\n  {SS{{ ▷(PC @@ i ->r ai) ∗\n      ▷ ai ->a wi ∗\n      ▷ (R0 @@ i ->r r0) ∗\n      ▷ (R1 @@ i ->r r1) ∗\n      ▷ (R2 @@ i ->r r2) ∗\n      ▷ (TX@ i := p_tx) ∗\n      ▷ (memory_page p_tx mem_tx) ∗\n      ▷ (i -@A> sacc)\n       }}}\n   ExecI @ i {{{ RET (false, ExecI) ;\n                 PC @@ i ->r (ai ^+ 1)%f ∗\n                 ai ->a wi ∗\n                 R0 @@ i ->r (encode_hvc_ret_code Error) ∗\n                 R1 @@ i ->r r1 ∗\n                 R2 @@ i ->r (encode_hvc_error Denied) ∗\n                 TX@ i := p_tx ∗\n                 memory_page p_tx mem_tx ∗\n                 i -@A> sacc\n    }}}.\nProof.\n  iIntros (Hin_acc Hneq_tx len Hdecode_i Hdecode_f Htt Hle_ps Hparse Hvalid_des Hin_p Hnin_p Φ)\n          \"(>PC & >mem_ins & >R0 & >R1 & >R2 & >tx & >mem_tx & >acc) HΦ\".\n  iApply (sswp_lift_atomic_step ExecI);[done|].\n  iIntros (n σ1) \"%Hsche state\".\n  rewrite /scheduled /= /scheduler in Hsche.\n  assert (σ1.1.1.2 = i) as Heq_cur. { case_bool_decide;last done. by apply fin_to_nat_inj. }\n  clear Hsche.\n  iModIntro.\n  iDestruct \"state\" as \"(Hnum & mem & regs & mb & rx_state & pgt_owned & pgt_acc & pgt_excl &\n                            trans & hpool & retri & %Hwf & %Hdisj & %Hconsis)\".\n  (* valid regs *)\n  iDestruct ((gen_reg_valid4 i PC ai R0 r0 R1 r1 R2 r2 Heq_cur) with \"regs PC R0 R1 R2\")\n    as \"(%Hlookup_PC & %Hlookup_R0 & %Hlookup_R1 & %Hlookup_R2)\";eauto.\n  (* valid pt *)\n  iDestruct (access_agree_check_true (tpa ai) i with \"pgt_acc acc\") as %Hcheckpg_ai;eauto.\n  iDestruct (access_agree_check_false p with \"pgt_acc acc\") as %Hcheckpg_acc_false;eauto.\n  (* valid mem *)\n  iDestruct (gen_mem_valid ai wi with \"mem mem_ins\") as %Hlookup_ai.\n  iDestruct (gen_mem_valid_SepM with \"mem [mem_tx]\") as %Hlookup_mem_tx.\n  { iDestruct \"mem_tx\" as \"[% mem_tx]\". iExact \"mem_tx\". }\n  (* valid tx *)\n  iDestruct (mb_valid_tx i p_tx with \"mb tx\") as %Heq_tx.\n  (* valid tran *)\n  iSplit.\n  - (* reducible *)\n    iPureIntro.\n    apply (reducible_normal i Hvc ai wi);eauto.\n    rewrite Heq_tx //.\n  - iModIntro.\n    iIntros (m2 σ2) \"vmprop_auth %HstepP\".\n    iFrame \"vmprop_auth\".\n    apply (step_ExecI_normal i Hvc ai wi) in HstepP;eauto.\n    2: rewrite Heq_tx //.\n    remember (exec Hvc σ1) as c2 eqn:Heqc2.\n    rewrite /exec /hvc Hlookup_R0 /= Hdecode_f /mem_send Hlookup_R1 /= in Heqc2.\n    case_bool_decide;first lia.\n    pose proof (parse_transaction_descriptor_length _ _ _ _ Hparse) as Hlt_pg.\n    rewrite -Heq_tx -Heq_cur /len in Hparse.\n    apply (parse_transaction_descriptor_tx _ σ1.1.2) in Hparse;last done.\n    rewrite Hparse /= Heq_cur Hvalid_des /= in Heqc2.\n    rewrite /check_transition_transaction /= in Heqc2.\n    destruct tran as [[[? ?] ?] ps].\n    rewrite /= in Heqc2.\n    case_bool_decide.\n    {\n      specialize (H1 p Hin_p).\n      rewrite andb_true_iff in H1.\n      rewrite /check_excl_access_page andb_true_iff in H1.\n      destruct H1 as [[Hacc _] _].\n      rewrite Heq_cur Hcheckpg_acc_false in Hacc.\n      inversion Hacc.\n    }\n    clear H1.\n    simpl in Heqc2.\n    assert (Heq_c2 : (m2,σ2) = (ExecI, update_incr_PC (update_reg (update_reg σ1 R0 (encode_hvc_ret_code Error)) R2 (encode_hvc_error Denied)))).\n    {\n      destruct hvcf; inversion Htt;\n        destruct HstepP;subst m2 σ2; subst c2; done.\n    }\n    inversion Heq_c2. clear H2 H3 Heq_c2.\n    rewrite /=.\n    iDestruct (hvc_error_update (E:= ⊤) Denied with \"PC R0 R2 [$Hnum $mem $regs $mb $rx_state $pgt_owned $pgt_acc $pgt_excl $ trans $hpool $retri]\")\n    as \">[[$ $] ?]\". 1-4: auto. iPureIntro. auto.\n    rewrite /scheduled /machine.scheduler /= /scheduler.\n    rewrite p_upd_pc_current_vm 2!p_upd_reg_current_vm Heq_cur.\n    case_bool_decide;last contradiction.\n    simpl. iApply \"HΦ\".\n    iFrame.\n    by iFrame.\nQed.\n\nLemma mem_send_in_trans {i wi r0 r1 r2 hvcf p_tx tt tran q tran' q' sacc} ai p wh mem_tx:\n  (tpa ai) ∈ sacc ->\n  (tpa ai) ≠ p_tx ->\n  let len := (Z.to_nat (finz.to_z r1)) in\n  decode_instruction wi = Some(Hvc) ->\n  decode_hvc_func r0 = Some(hvcf) ->\n  hvcf_to_tt hvcf = Some tt ->\n  (len <= page_size)%Z ->\n  parse_transaction_descriptor mem_tx (of_pid p_tx) len = Some tran ->\n  validate_transaction_descriptor i tran = true ->\n  p ∈ tran.2 ->\n  p ∈ tran'.1.2 ->\n  {SS{{ ▷(PC @@ i ->r ai) ∗\n      ▷ ai ->a wi ∗\n      ▷ i -@{q'}A> sacc ∗\n      ▷ (R0 @@ i ->r r0) ∗\n      ▷ (R1 @@ i ->r r1) ∗\n      ▷ (R2 @@ i ->r r2) ∗\n      ▷ (TX@ i := p_tx) ∗\n      ▷ (memory_page p_tx mem_tx) ∗\n      ▷ (wh -{q}>t tran')\n       }}}\n   ExecI @ i {{{ RET (false, ExecI) ;\n                 PC @@ i ->r (ai ^+ 1)%f ∗\n                 ai ->a wi ∗\n                 i -@{q'}A> sacc ∗\n                 R0 @@ i ->r (encode_hvc_ret_code Error) ∗\n                 R1 @@ i ->r r1 ∗\n                 R2 @@ i ->r (encode_hvc_error Denied) ∗\n                 TX@ i := p_tx ∗\n                 memory_page p_tx mem_tx ∗\n                 wh -{q}>t tran'\n    }}}.\nProof.\n  iIntros (Hin_acc Hneq_tx len Hdecode_i Hdecode_f Htt Hle_ps Hparse Hvalid_des Hin_p Hin_p' Φ)\n          \"(>PC & >mem_ins & >acc & >R0 & >R1 & >R2 & >tx & >mem_tx & >tran) HΦ\".\n  iApply (sswp_lift_atomic_step ExecI);[done|].\n  iIntros (n σ1) \"%Hsche state\".\n  rewrite /scheduled /= /scheduler in Hsche.\n  assert (σ1.1.1.2 = i) as Heq_cur. { case_bool_decide;last done. by apply fin_to_nat_inj. }\n  clear Hsche.\n  iModIntro.\n  iDestruct \"state\" as \"(Hnum & mem & regs & mb & rx_state & pgt_owned & pgt_acc & pgt_excl &\n                            trans & hpool & retri & %Hwf & %Hdisj & %Hconsis)\".\n  (* valid regs *)\n  iDestruct ((gen_reg_valid4 i PC ai R0 r0 R1 r1 R2 r2 Heq_cur) with \"regs PC R0 R1 R2\")\n    as \"(%Hlookup_PC & %Hlookup_R0 & %Hlookup_R1 & %Hlookup_R2)\";eauto.\n  (* valid pt *)\n  iDestruct (access_agree_check_true (tpa ai) i with \"pgt_acc acc\") as %Hcheckpg_ai;eauto.\n  iDestruct (access_agree_check_true_forall with \"pgt_acc acc\") as %Hcheckpg_acc;eauto.\n  (* valid mem *)\n  iDestruct (gen_mem_valid ai wi with \"mem mem_ins\") as %Hlookup_ai.\n  iDestruct (gen_mem_valid_SepM with \"mem [mem_tx]\") as %Hlookup_mem_tx.\n  { iDestruct \"mem_tx\" as \"[% mem_tx]\". iExact \"mem_tx\". }\n  (* valid tx *)\n  iDestruct (mb_valid_tx i p_tx with \"mb tx\") as %Heq_tx.\n  (* valid tran *)\n  iDestruct (trans_valid_Some with \"trans tran\") as %[re Hlookup_tran].\n  iSplit.\n  - (* reducible *)\n    iPureIntro.\n    apply (reducible_normal i Hvc ai wi);eauto.\n    rewrite Heq_tx //.\n  - iModIntro.\n    iIntros (m2 σ2) \"vmprop_auth %HstepP\".\n    iFrame \"vmprop_auth\".\n    apply (step_ExecI_normal i Hvc ai wi) in HstepP;eauto.\n    2: rewrite Heq_tx //.\n    remember (exec Hvc σ1) as c2 eqn:Heqc2.\n    rewrite /exec /hvc Hlookup_R0 /= Hdecode_f /mem_send Hlookup_R1 /= in Heqc2.\n    case_bool_decide;first lia.\n    pose proof (parse_transaction_descriptor_length _ _ _ _ Hparse) as Hlt_pg.\n    rewrite -Heq_tx -Heq_cur /len in Hparse.\n    apply (parse_transaction_descriptor_tx _ σ1.1.2) in Hparse;last done.\n    rewrite Hparse /= Heq_cur Hvalid_des /= in Heqc2.\n    rewrite /check_transition_transaction /= in Heqc2.\n    destruct tran as [[[? ?] ?] ps].\n    rewrite /= in Heqc2.\n    case_bool_decide.\n    {\n      specialize (Hconsis wh _ Hlookup_tran p Hin_p').\n      simpl in Hconsis.\n      specialize (H1 p Hin_p).\n         rewrite andb_true_iff in H1.\n      rewrite /check_excl_access_page andb_true_iff /check_access_page /check_excl_page /check_ownership_page in H1.\n      destruct tran'.2, re;first done;rewrite Hconsis in H1;\n      destruct H1 as [[Hacc Hexcl] Hown].\n      destruct (decide (σ1.1.1.2 ∈ ∅));done.\n      inversion Hexcl.\n      inversion Hexcl.\n      destruct (decide (σ1.1.1.2 ∈ {[tran'.1.1.2]})).\n      apply elem_of_singleton in e.\n      destruct (decide (σ1.1.1.2 = tran'.1.1.1)).\n      rewrite e0 in e.\n      destruct Hwf as [_ [Hwf _]].\n      specialize (Hwf wh _ Hlookup_tran).\n      done.\n      inversion Hown.\n      inversion Hacc.\n      destruct (decide (σ1.1.1.2 ∈ ∅));done.\n    }\n    clear H1.\n    simpl in Heqc2.\n    assert (Heq_c2 : (m2,σ2) = (ExecI, update_incr_PC (update_reg (update_reg σ1 R0 (encode_hvc_ret_code Error)) R2 (encode_hvc_error Denied)))).\n    {\n      destruct hvcf; inversion Htt;\n        destruct HstepP;subst m2 σ2; subst c2; done.\n    }\n    inversion Heq_c2. clear H2 H3 Heq_c2.\n    rewrite /=.\n    iDestruct (hvc_error_update (E:= ⊤) Denied with \"PC R0 R2 [$Hnum $mem $regs $mb $rx_state $pgt_owned $pgt_acc $pgt_excl $ trans $hpool $retri]\")\n    as \">[[$ $] ?]\". 1-4: auto. iPureIntro. auto.\n    rewrite /scheduled /machine.scheduler /= /scheduler.\n    rewrite p_upd_pc_current_vm 2!p_upd_reg_current_vm Heq_cur.\n    case_bool_decide;last contradiction.\n    simpl. iApply \"HΦ\".\n    iFrame.\n    by iFrame.\nQed.\n\nLemma mem_send_no_fresh_handles {i wi r0 r1 r2 hvcf tt p_tx sacc} ai sh j mem_tx (ps: gset PID):\n  (tpa ai) ∈ sacc ->\n  (tpa ai) ≠ p_tx ->\n  let len := (Z.to_nat (finz.to_z r1)) in\n  decode_instruction wi = Some(Hvc) ->\n  decode_hvc_func r0 = Some(hvcf) ->\n  hvcf_to_tt hvcf = Some tt ->\n  (len <= page_size)%Z ->\n  parse_transaction_descriptor mem_tx (of_pid p_tx) len = Some (i, None, j, ps) ->\n  i ≠ j ->\n  ps ⊆ sacc ->\n  sh = ∅ ->\n  {SS{{ ▷(PC @@ i ->r ai) ∗\n      ▷ ai ->a wi ∗\n      ▷ ([∗ set] p ∈ ps, p -@O> i ∗ p -@E> true) ∗\n      ▷ (i -@A> sacc) ∗\n      ▷ (R0 @@ i ->r r0) ∗\n      ▷ (R1 @@ i ->r r1) ∗\n      ▷ (R2 @@i ->r r2) ∗\n      ▷ (fresh_handles 1 sh) ∗\n      ▷ TX@ i := p_tx ∗\n      ▷ memory_page p_tx mem_tx\n       }}}\n   ExecI @ i {{{ RET (false, ExecI) ;\n                 PC @@ i ->r (ai ^+ 1)%f ∗\n                 ai ->a wi ∗\n                 ([∗ set] p ∈ ps, p -@O> i ∗ p -@E> true) ∗\n                 i -@A> sacc ∗\n                 R0 @@ i ->r (encode_hvc_ret_code Error) ∗\n                 R1 @@ i ->r r1 ∗\n                 R2 @@ i ->r (encode_hvc_error NoMem) ∗\n                 fresh_handles 1 sh ∗\n                 TX@ i := p_tx ∗\n                 memory_page p_tx mem_tx}}}.\nProof.\n  iIntros (Hin_acc Hneq_tx len Hdecode_i Hdecode_f Htt Hle_ps Hparse Hneq_vmid Hsubseteq_acc Heq_hp Φ)\n          \"(>PC & >mem_ins & >oe & >acc & >R0 & >R1 & >R2 & >[hp handles] & >tx & >mem_tx) HΦ\".\n  iApply (sswp_lift_atomic_step ExecI);[done|].\n  iIntros (n σ1) \"%Hsche state\".\n  rewrite /scheduled /= /scheduler in Hsche.\n  assert (σ1.1.1.2 = i) as Heq_cur. { case_bool_decide;last done. by apply fin_to_nat_inj. }\n  clear Hsche.\n  iModIntro.\n  iDestruct \"state\" as \"(Hnum & mem & regs & mb & rx_state & pgt_owned & pgt_acc & pgt_excl &\n                            trans & hpool & retri & %Hwf & %Hdisj & %Hconsis)\".\n  (* valid regs *)\n  iDestruct ((gen_reg_valid4 i PC ai R0 r0 R1 r1 R2 r2 Heq_cur) with \"regs PC R0 R1 R2\")\n    as \"(%Hlookup_PC & %Hlookup_R0 & %Hlookup_R1 & %Hlookup_R2)\";eauto.\n  (* valid pt *)\n  iDestruct (access_agree_check_true (tpa ai) i with \"pgt_acc acc\") as %Hcheckpg_ai;eauto.\n  iDestruct (access_agree_check_true_forall with \"pgt_acc acc\") as %Hcheckpg_acc;eauto.\n  iDestruct (big_sepS_sep with \"oe\") as \"[own excl]\".\n  iDestruct (excl_agree_Some_check_true_bigS with \"pgt_excl excl\") as %Hcheckpg_excl;eauto.\n  iDestruct (own_agree_Some_check_true_bigS with \"pgt_owned own\") as %Hcheckpg_own;eauto.\n  (* valid mem *)\n  iDestruct (gen_mem_valid ai wi with \"mem mem_ins\") as %Hlookup_ai.\n  iDestruct (gen_mem_valid_SepM with \"mem [mem_tx]\") as %Hlookup_mem_tx.\n  { iDestruct \"mem_tx\" as \"[% mem_tx]\". iExact \"mem_tx\". }\n  (* valid tx *)\n  iDestruct (mb_valid_tx i p_tx with \"mb tx\") as %Heq_tx.\n  (* valid hpool *)\n  iDestruct (hpool_valid with \"hpool hp\") as %Heq_hp'.\n  iSplit.\n  - (* reducible *)\n    iPureIntro.\n    apply (reducible_normal i Hvc ai wi);eauto.\n    rewrite Heq_tx //.\n  - iModIntro.\n    iIntros (m2 σ2) \"vmprop_auth %HstepP\".\n    iFrame \"vmprop_auth\".\n    apply (step_ExecI_normal i Hvc ai wi) in HstepP;eauto.\n    2: rewrite Heq_tx //.\n    remember (exec Hvc σ1) as c2 eqn:Heqc2.\n    rewrite /exec /hvc Hlookup_R0 /= Hdecode_f /mem_send Hlookup_R1 /= in Heqc2.\n    case_bool_decide;first lia.\n    pose proof (parse_transaction_descriptor_length _ _ _ _ Hparse) as Hlt_pg.\n    rewrite -Heq_tx -Heq_cur /len in Hparse.\n    apply (parse_transaction_descriptor_tx _ σ1.1.2) in Hparse;last done.\n    rewrite Hparse //= in Heqc2.\n    case_bool_decide.\n    2: { destruct H1. split;auto. split;eauto. rewrite Heq_cur //. }\n    case_bool_decide.\n    2: { destruct H2. intros s Hin.\n         rewrite Heq_cur.\n         rewrite andb_true_iff. split.\n         rewrite /check_excl_access_page.\n         rewrite andb_true_iff. split.\n         apply Hcheckpg_acc.\n         set_solver + Hsubseteq_acc Hin.\n         by apply Hcheckpg_excl.\n         by apply Hcheckpg_own.\n    }\n    clear H1 H2.\n    rewrite /new_transaction /= /fresh_handle /= -Heq_hp' Heq_hp in Heqc2.\n    rewrite elements_empty /= in Heqc2.\n    assert (Heq_c2 : (m2,σ2) = (ExecI, update_incr_PC (update_reg (update_reg σ1 R0 (encode_hvc_ret_code Error)) R2 (encode_hvc_error NoMem)))).\n    {\n    destruct hvcf; inversion Htt;\n      destruct HstepP;subst m2 σ2; subst c2; done.\n    }\n    inversion Heq_c2. clear H2 H3 Heq_c2.\n    rewrite /=.\n    iDestruct (hvc_error_update (E:= ⊤) NoMem with \"PC R0 R2 [$Hnum $mem $regs $mb $rx_state $pgt_owned $pgt_acc $pgt_excl $ trans $hpool $retri]\")\n    as \">[[$ $] ?]\". 1-4: auto. iPureIntro. auto.\n    rewrite /scheduled /machine.scheduler /= /scheduler.\n    rewrite p_upd_pc_current_vm 2!p_upd_reg_current_vm Heq_cur.\n    case_bool_decide;last contradiction.\n    simpl. iApply \"HΦ\".\n    iFrame.\n    rewrite big_sepS_sep. by iFrame.\nQed.\n\nLemma mem_share {i wi r0 r1 r2 hvcf p_tx sacc} ai j mem_tx sh (ps: gset PID) :\n  (tpa ai) ∈ sacc ->\n  (tpa ai) ≠ p_tx ->\n  (* len is the length of the msg *)\n  let len := (Z.to_nat (finz.to_z r1)) in\n  (* the decoding of wi is correct *)\n  decode_instruction wi = Some(Hvc) ->\n  (* the decoding of R0 is a FFA mem_share *)\n  decode_hvc_func r0 = Some(hvcf) ->\n  hvcf_to_tt hvcf = Some Sharing ->\n  (* the whole descriptor resides in the TX page *)\n  (len <= page_size)%Z ->\n  (* the descriptor *)\n  parse_transaction_descriptor mem_tx (of_pid p_tx) len = Some (i, None, j, ps) ->\n  (* caller is not the receiver *)\n  i ≠ j ->\n  ps ⊆ sacc ->\n  (* there is at least one free handle in the hpool *)\n  sh ≠ ∅ ->\n  {SS{{ ▷(PC @@ i ->r ai) ∗\n      ▷ ai ->a wi ∗\n      (* VM i exclusively owns pages in ps *)\n      ▷ ([∗ set] p ∈ ps, p -@O> i ∗ p -@E> true) ∗\n      ▷ (i -@A> sacc) ∗\n      ▷ (R0 @@ i ->r r0) ∗\n      ▷ (R1 @@ i ->r r1) ∗\n      ▷ (R2 @@i ->r r2) ∗\n      ▷ (fresh_handles 1 sh) ∗\n      ▷ TX@ i := p_tx ∗\n      ▷ memory_page p_tx mem_tx\n       }}}\n   ExecI @ i {{{ RET (false, ExecI) ;\n                 PC @@ i ->r (ai ^+ 1)%f ∗\n                 ai ->a wi ∗\n                 ([∗ set] p ∈ ps, p -@O> i ∗ p -@E> false) ∗\n                 i -@A> sacc ∗\n                 R0 @@ i ->r (encode_hvc_ret_code Succ) ∗\n                 R1 @@ i ->r r1 ∗\n                 (∃ (wh: Word), ⌜wh ∈ sh⌝ ∗\n                 R2 @@ i ->r wh ∗\n                 wh ->t (i, j, ps, Sharing) ∗\n                 wh ->re false ∗\n                 fresh_handles 1 (sh∖{[wh]})) ∗\n                 TX@ i := p_tx ∗\n                 memory_page p_tx mem_tx}}}.\nProof.\n  iIntros (Hin_acc Hneq_tx len Hdecode_i Hdecode_f Htt Hle_ps Hparse Hneq_vmid Hsubseteq_acc Hneq_hp Φ)\n          \"(>PC & >mem_ins & >oe & >acc & >R0 & >R1 & >R2 & >[hp handles] & >tx & >mem_tx) HΦ\".\n  iApply (sswp_lift_atomic_step ExecI);[done|].\n  iIntros (n σ1) \"%Hsche state\".\n  rewrite /scheduled /= /scheduler in Hsche.\n  assert (σ1.1.1.2 = i) as Heq_cur. { case_bool_decide;last done. by apply fin_to_nat_inj. }\n  clear Hsche.\n  iModIntro.\n  iDestruct \"state\" as \"(Hnum & mem & regs & mb & rx_state & pgt_owned & pgt_acc & pgt_excl &\n                            trans & hpool & retri & %Hwf & %Hdisj & %Hconsis)\".\n  (* valid regs *)\n  iDestruct ((gen_reg_valid4 i PC ai R0 r0 R1 r1 R2 r2 Heq_cur) with \"regs PC R0 R1 R2\")\n    as \"(%Hlookup_PC & %Hlookup_R0 & %Hlookup_R1 & %Hlookup_R2)\";eauto.\n  (* valid pt *)\n  iDestruct (access_agree_check_true (tpa ai) i with \"pgt_acc acc\") as %Hcheckpg_ai;eauto.\n  iDestruct (access_agree_check_true_forall with \"pgt_acc acc\") as %Hcheckpg_acc;eauto.\n  iDestruct (big_sepS_sep with \"oe\") as \"[own excl]\".\n  iDestruct (excl_agree_Some_check_true_bigS with \"pgt_excl excl\") as %Hcheckpg_excl;eauto.\n  iDestruct (excl_agree_Some_lookup_bigS with \"pgt_excl excl\") as %Hvalid_excl;eauto.\n  iDestruct (own_agree_Some_check_true_bigS with \"pgt_owned own\") as %Hcheckpg_own;eauto.\n  (* valid mem *)\n  iDestruct (gen_mem_valid ai wi with \"mem mem_ins\") as %Hlookup_ai.\n  iDestruct (gen_mem_valid_SepM with \"mem [mem_tx]\") as %Hlookup_mem_tx.\n  { iDestruct \"mem_tx\" as \"[% mem_tx]\". iExact \"mem_tx\". }\n  (* valid tx *)\n  iDestruct (mb_valid_tx i p_tx with \"mb tx\") as %Heq_tx.\n  (* valid hpool *)\n  iDestruct (hpool_valid with \"hpool hp\") as %Heq_hp.\n  iSplit.\n  - (* reducible *)\n    iPureIntro.\n    apply (reducible_normal i Hvc ai wi);eauto.\n    rewrite Heq_tx //.\n  - iModIntro.\n    iIntros (m2 σ2) \"vmprop_auth %HstepP\".\n    iFrame \"vmprop_auth\".\n    apply (step_ExecI_normal i Hvc ai wi) in HstepP;eauto.\n    2: rewrite Heq_tx //.\n    remember (exec Hvc σ1) as c2 eqn:Heqc2.\n    destruct hvcf; inversion Htt.\n    rewrite /exec /hvc Hlookup_R0 /= Hdecode_f /mem_send Hlookup_R1 /= in Heqc2.\n    case_bool_decide;first lia.\n    pose proof (parse_transaction_descriptor_length _ _ _ _ Hparse) as Hlt_pg.\n    rewrite -Heq_tx -Heq_cur /len in Hparse.\n    apply (parse_transaction_descriptor_tx _ σ1.1.2) in Hparse;last done.\n    rewrite Hparse //= in Heqc2.\n    case_bool_decide.\n    2: { destruct H1. split;auto. split;eauto. rewrite Heq_cur //. }\n    case_bool_decide.\n    2: { destruct H2. intros s Hin.\n         rewrite Heq_cur.\n         rewrite andb_true_iff. split.\n         rewrite /check_excl_access_page.\n         rewrite andb_true_iff. split.\n         apply Hcheckpg_acc.\n         set_solver + Hsubseteq_acc Hin.\n         by apply Hcheckpg_excl.\n         by apply Hcheckpg_own.\n    }\n    clear H1 H2.\n    rewrite /new_transaction /= /fresh_handle /= -Heq_hp in Heqc2.\n    destruct (elements sh) as [| h fhs] eqn:Hfhs.\n    { exfalso. rewrite -(elements_empty (A:= Word) (C:= gset Word)) in Hfhs. apply Hneq_hp. apply set_eq.\n      intro. rewrite -elem_of_elements Hfhs elem_of_elements. split;intro;set_solver. }\n    destruct HstepP;subst m2 σ2; subst c2; simpl.\n    rewrite /gen_vm_interp.\n    (* unchanged part *)\n    rewrite (preserve_get_mb_gmap σ1).\n    rewrite (preserve_get_rx_gmap σ1).\n    all: try rewrite p_upd_pc_mb //.\n    rewrite p_upd_pc_mem 2!p_upd_reg_mem p_flip_excl_mem p_alloc_tran_mem.\n    iFrame \"Hnum mem rx_state mb\".\n    (* upd regs *)\n    rewrite Heq_cur.\n    rewrite (u_upd_pc_regs _ i ai) //.\n    2: { rewrite 2!u_upd_reg_regs.\n         rewrite (preserve_get_reg_gmap σ1). rewrite lookup_insert_ne //.  rewrite lookup_insert_ne //. solve_reg_lookup. done.\n    }\n    rewrite u_upd_reg_regs p_upd_reg_current_vm p_flip_excl_current_vm p_alloc_tran_current_vm  Heq_cur.\n    rewrite u_upd_reg_regs p_flip_excl_current_vm p_alloc_tran_current_vm  Heq_cur.\n    rewrite (preserve_get_reg_gmap σ1) //.\n    iDestruct ((gen_reg_update3_global PC i (ai ^+ 1)%f R2 i h R0 i (encode_hvc_ret_code Succ)) with \"regs PC R2 R0\")\n      as \">[$ [PC [R2 R0]]]\";eauto.\n    (* upd pgt *)\n    rewrite (preserve_get_own_gmap (update_page_table_global flip_excl (alloc_transaction σ1 h (i, j, ps, Sharing, false)) i ps) (update_incr_PC _)).\n    2: rewrite p_upd_pc_pgt !p_upd_reg_pgt //.\n    rewrite p_flip_excl_own. rewrite (preserve_get_own_gmap σ1) //.\n    iFrame \"pgt_owned\".\n    rewrite (preserve_get_access_gmap (update_page_table_global flip_excl (alloc_transaction σ1 h (i, j, ps, Sharing, false)) i ps) (update_incr_PC _)).\n    2: rewrite p_upd_pc_pgt p_upd_reg_pgt //.\n    rewrite p_flip_excl_acc. rewrite (preserve_get_access_gmap σ1) //.\n    iFrame \"pgt_acc\".\n    rewrite (preserve_get_excl_gmap (update_page_table_global flip_excl (alloc_transaction σ1 h (i, j, ps, Sharing, false)) i ps) (update_incr_PC _)).\n    2: rewrite p_upd_pc_pgt p_upd_reg_pgt //.\n    assert (Hvalid_acc: set_Forall (λ p : PID,\n      ∃ e : option VMID * bool * gset VMID, σ1.1.1.1.2 !! p = Some e ∧ e.2 = {[i]}) ps).\n    {\n      intros p Hin.\n      specialize (Hcheckpg_acc p).\n      feed specialize Hcheckpg_acc. set_solver + Hin Hsubseteq_acc.\n      specialize (Hvalid_excl p Hin).\n      destruct Hvalid_excl as [o [b [s [Hlk Htrue]]]].\n      symmetry in Htrue.\n      rewrite andb_true_iff in Htrue.\n      destruct Htrue as [-> Hsize].\n      rewrite /check_access_page /= in Hcheckpg_acc.\n      rewrite Hlk in Hcheckpg_acc.\n      destruct (decide (i ∈ s)); last done.\n      case_bool_decide;last done.\n      exists (o, true, s). split;auto.\n      apply size_singleton_le;auto.\n    }\n    rewrite u_flip_excl_excl //.\n    iDestruct (excl_update_flip with \"pgt_excl excl\") as \">[$ excl]\".\n    (* upd tran *)\n    rewrite (preserve_get_trans_gmap (alloc_transaction σ1 h (i, j, ps, Sharing, false)) (update_incr_PC _)).\n    2: rewrite p_upd_pc_trans p_upd_reg_trans  //.\n    rewrite u_alloc_tran_trans.\n    assert (sh = {[h]} ∪ sh ∖ {[h]}) as Heq_sh.\n    { assert (h ∈ sh).\n      rewrite -elem_of_elements. rewrite Hfhs. set_solver +.\n      rewrite union_comm_L.\n      rewrite difference_union_L.\n      set_solver + H1.\n    }\n    iPoseProof (big_sepS_union _ {[h]} (sh ∖ {[h]})) as \"[H _]\".\n    set_solver +.\n    iDestruct (\"H\" with \"[handles]\") as \"[h handles]\".\n    rewrite -Heq_sh. iExact \"handles\".\n    rewrite big_sepS_singleton. iDestruct \"h\" as \"[tran re]\". iClear \"H\".\n    iDestruct (trans_valid_None with \"trans tran\") as %Hlookup_tran.\n    iDestruct (trans_update_insert h (i, j, ps, Sharing) with \"trans tran\") as \">[$ tran]\".\n    { rewrite /valid_transaction //=. }\n    (* upd hp *)\n    rewrite (preserve_get_hpool_gset (alloc_transaction σ1 h (i, j, ps, Sharing, false)) (update_incr_PC _)).\n    2: rewrite p_upd_pc_trans p_upd_reg_trans //. rewrite u_alloc_tran_hpool.\n    iDestruct (hpool_update_diff h with \"hpool hp\") as \">[$ hp]\".\n    (* upd retri *)\n    rewrite (preserve_get_retri_gmap (alloc_transaction σ1 h (i, j, ps, Sharing, false)) (update_incr_PC _)).\n    2: rewrite p_upd_pc_trans p_upd_reg_trans //. rewrite u_alloc_tran_retri.\n    iDestruct (retri_update_insert with \"retri re\") as \">[$ re]\".\n    (* inv_trans_wellformed *)\n    rewrite (preserve_inv_trans_wellformed (alloc_transaction σ1 h (i, j, ps, Sharing, false))).\n    2: rewrite p_upd_pc_trans p_upd_reg_trans //.\n    iAssert (⌜inv_trans_wellformed (alloc_transaction σ1 h (i, j, ps, Sharing, false))⌝%I) as \"$\".\n    iPureIntro.\n    apply (p_alloc_tran_inv_wf h (i, j, ps, Sharing, false));auto.\n    simpl. simpl in Hlt_pg. rewrite Z.leb_le. lia.\n    (* inv_trans_pgt_consistent *)\n    rewrite (preserve_inv_trans_pgt_consistent (update_page_table_global flip_excl (alloc_transaction σ1 h (i, j, ps, Sharing, false)) i ps) (update_incr_PC _)).\n    2: rewrite p_upd_pc_trans p_upd_reg_trans //.\n    2: rewrite p_upd_pc_pgt p_upd_reg_pgt //.\n    iAssert (⌜inv_trans_pgt_consistent (update_page_table_global flip_excl (alloc_transaction σ1 h (i, j, ps, Sharing, false)) i ps)⌝%I) as \"$\".\n    iPureIntro.\n    apply p_share_inv_consist;auto.\n    { destruct Hwf as [_ [? _]]. done. }\n    {\n      intros p Hin.\n      specialize (Hvalid_excl p Hin).\n      specialize (Hcheckpg_own p Hin).\n      specialize (Hvalid_acc p Hin).\n      destruct Hvalid_excl as [o [b [s [Hlk Htrue]]]].\n      symmetry in Htrue.\n      rewrite andb_true_iff in Htrue.\n      destruct Htrue as [-> Hsize].\n      rewrite /check_ownership_page /= in Hcheckpg_own.\n      rewrite Hlk in Hcheckpg_own.\n      destruct o;last done.\n      destruct (decide (i = v));last done.\n      subst v.\n      rewrite Hlk in Hvalid_acc.\n      destruct Hvalid_acc as [? [? ?]].\n      inversion H1. subst x.\n      rewrite /= in H2. subst s. done.\n    }\n    (* inv_trans_ps_disj *)\n    rewrite (preserve_inv_trans_ps_disj (alloc_transaction σ1 h (i, j, ps, Sharing, false))).\n    2: rewrite p_upd_pc_trans p_upd_reg_trans //.\n    iAssert (⌜inv_trans_ps_disj (alloc_transaction σ1 h (i, j, ps, Sharing, false))⌝%I) as \"$\". iPureIntro.\n    apply p_alloc_tran_inv_disj;auto.\n    {\n      rewrite /= elem_of_disjoint.\n      intros.\n      apply elem_of_pages_in_trans' in H2.\n      destruct H2 as [h' [tran' [Hlk Hin_h']]].\n      specialize (Hconsis h' (Some tran') Hlk x Hin_h').\n      specialize (Hvalid_acc x H1).\n      destruct Hvalid_acc as [e [Hlk' He]].\n      destruct Hwf as [_ [Hneq _]].\n      specialize (Hneq h' _ Hlk).\n      destruct (tran'.1.2);destruct tran'.2;auto.\n      - rewrite Hlk' in Hconsis.\n        inversion Hconsis.\n        subst e. set_solver + He.\n      - rewrite Hlk' in Hconsis.\n        inversion Hconsis.\n        subst e. simpl in He.\n        set_solver + He Hneq.\n      - specialize (Hvalid_excl x H1).\n        destruct Hvalid_excl as [? [? [? [Hlk'' Htrue]]]].\n        symmetry in Htrue.\n        rewrite andb_true_iff in Htrue.\n        destruct Htrue  as [-> _].\n        rewrite Hlk'' in Hconsis.\n        inversion Hconsis.\n      - specialize (Hcheckpg_own x H1).\n        rewrite /check_ownership_page /= in Hcheckpg_own.\n        rewrite Hlk' in Hcheckpg_own.\n        rewrite Hlk' in Hconsis.\n        inversion Hconsis.\n        subst e.\n        destruct (decide (i = tran'.1.1.1.1));last done.\n        set_solver + e He Hneq.\n      - rewrite Hlk' in Hconsis.\n        inversion Hconsis.\n        subst e. set_solver + He.\n    }\n    (* just_scheduled *)\n    iModIntro.\n    rewrite /just_scheduled_vms /just_scheduled.\n    rewrite /scheduled /machine.scheduler /= /scheduler.\n    rewrite p_upd_pc_current_vm 2!p_upd_reg_current_vm p_flip_excl_current_vm  p_alloc_tran_current_vm.\n    rewrite Heq_cur.\n    iSplitL \"\".\n    set fl := (filter _ _).\n    assert (fl = []) as ->.\n    {\n      rewrite /fl.\n      induction n.\n      - simpl.\n        rewrite filter_nil //=.\n      - rewrite seq_S.\n        rewrite filter_app.\n        rewrite IHn.\n        simpl.\n        rewrite filter_cons_False //=.\n        rewrite andb_negb_l.\n        done.\n    }\n    by iSimpl.\n    (* Φ *)\n    case_bool_decide;last done.\n    simpl. iApply \"HΦ\".\n    rewrite /fresh_handles. iFrame.\n    iSplitL \"own excl\".\n    rewrite big_sepS_sep. iFrame.\n    iExists h. iFrame.\n    rewrite Heq_sh.\n    iPureIntro. set_solver +.\nQed.\n\nLemma mem_not_share {i wi r0 r1 r2 hvcf p_tx sacc} tt ai j mem_tx sh (ps: gset PID) :\n  tt ≠ Sharing ->\n  (tpa ai) ∈ sacc ->\n  (tpa ai) ≠ p_tx ->\n  (* len is the length of the msg *)\n  let len := (Z.to_nat (finz.to_z r1)) in\n  (* the decoding of wi is correct *)\n  decode_instruction wi = Some(Hvc) ->\n  (* the decoding of R0 is a FFA mem_share *)\n  decode_hvc_func r0 = Some(hvcf) ->\n  hvcf_to_tt hvcf = Some tt ->\n  (* the whole descriptor resides in the TX page *)\n  (len <= page_size)%Z ->\n  (* the descriptor *)\n  parse_transaction_descriptor mem_tx (of_pid p_tx) len = Some (i, None, j, ps) ->\n  (* caller is not the receiver *)\n  i ≠ j ->\n  ps ⊆ sacc ->\n  (* there is at least one free handle in the hpool *)\n  sh ≠ ∅ ->\n  {SS{{ ▷(PC @@ i ->r ai) ∗\n      ▷ ai ->a wi ∗\n      (* VM i exclusively owns pages in ps *)\n      ▷ ([∗ set] p ∈ ps, p -@O> i ∗ p -@E> true) ∗\n      ▷ (i -@A> sacc) ∗\n      ▷ (R0 @@ i ->r r0) ∗\n      ▷ (R1 @@ i ->r r1) ∗\n      ▷ (R2 @@i ->r r2) ∗\n      ▷ (fresh_handles 1 sh) ∗\n      ▷ TX@ i := p_tx ∗\n      ▷ memory_page p_tx mem_tx\n       }}}\n   ExecI @ i {{{ RET (false, ExecI) ;\n                 PC @@ i ->r (ai ^+ 1)%f ∗\n                 ai ->a wi ∗\n                 ([∗ set] p ∈ ps, p -@O> i ∗ p -@E> true) ∗\n                 i -@A> (sacc ∖ ps) ∗\n                 R0 @@ i ->r (encode_hvc_ret_code Succ) ∗\n                 R1 @@ i ->r r1 ∗\n                 (∃ (wh: Word), ⌜wh ∈ sh⌝ ∗\n                 R2 @@ i ->r wh ∗\n                 wh ->t (i, j, ps, tt) ∗\n                 wh ->re false ∗\n                 fresh_handles 1 (sh∖{[wh]})) ∗\n                 TX@ i := p_tx ∗\n                 memory_page p_tx mem_tx}}}.\nProof.\n  iIntros (Hneq_tt Hin_acc Hneq_tx len Hdecode_i Hdecode_f Htt Hle_ps Hparse Hneq_vmid Hsubseteq_acc Hneq_hp Φ)\n          \"(>PC & >mem_ins & >oe & >acc & >R0 & >R1 & >R2 & >[hp handles] & >tx & >mem_tx) HΦ\".\n  iApply (sswp_lift_atomic_step ExecI);[done|].\n  iIntros (n σ1) \"%Hsche state\".\n  rewrite /scheduled /= /scheduler in Hsche.\n  assert (σ1.1.1.2 = i) as Heq_cur. { case_bool_decide;last done. by apply fin_to_nat_inj. }\n  clear Hsche.\n  iModIntro.\n  iDestruct \"state\" as \"(Hnum & mem & regs & mb & rx_state & pgt_owned & pgt_acc & pgt_excl &\n                            trans & hpool & retri & %Hwf & %Hdisj & %Hconsis)\".\n  (* valid regs *)\n  iDestruct ((gen_reg_valid4 i PC ai R0 r0 R1 r1 R2 r2 Heq_cur) with \"regs PC R0 R1 R2\")\n    as \"(%Hlookup_PC & %Hlookup_R0 & %Hlookup_R1 & %Hlookup_R2)\";eauto.\n  (* valid pt *)\n  iDestruct (access_agree_check_true (tpa ai) i with \"pgt_acc acc\") as %Hcheckpg_ai;eauto.\n  iDestruct (access_agree_check_true_forall with \"pgt_acc acc\") as %Hcheckpg_acc;eauto.\n  iDestruct (big_sepS_sep with \"oe\") as \"[own excl]\".\n  iDestruct (excl_agree_Some_check_true_bigS with \"pgt_excl excl\") as %Hcheckpg_excl;eauto.\n  iDestruct (excl_agree_Some_lookup_bigS with \"pgt_excl excl\") as %Hvalid_excl;eauto.\n  iDestruct (own_agree_Some_check_true_bigS with \"pgt_owned own\") as %Hcheckpg_own;eauto.\n  (* valid mem *)\n  iDestruct (gen_mem_valid ai wi with \"mem mem_ins\") as %Hlookup_ai.\n  iDestruct (gen_mem_valid_SepM with \"mem [mem_tx]\") as %Hlookup_mem_tx.\n  { iDestruct \"mem_tx\" as \"[% mem_tx]\". iExact \"mem_tx\". }\n  (* valid tx *)\n  iDestruct (mb_valid_tx i p_tx with \"mb tx\") as %Heq_tx.\n  (* valid hpool *)\n  iDestruct (hpool_valid with \"hpool hp\") as %Heq_hp.\n  iSplit.\n  - (* reducible *)\n    iPureIntro.\n    apply (reducible_normal i Hvc ai wi);eauto.\n    rewrite Heq_tx //.\n  - iModIntro.\n    iIntros (m2 σ2) \"vmprop_auth %HstepP\".\n    iFrame \"vmprop_auth\".\n    apply (step_ExecI_normal i Hvc ai wi) in HstepP;eauto.\n    2: rewrite Heq_tx //.\n    remember (exec Hvc σ1) as c2 eqn:Heqc2.\n    rewrite /exec /hvc Hlookup_R0 /= Hdecode_f /mem_send Hlookup_R1 /= in Heqc2.\n    case_bool_decide;first lia.\n    pose proof (parse_transaction_descriptor_length _ _ _ _ Hparse) as Hlt_pg.\n    rewrite -Heq_tx -Heq_cur /len in Hparse.\n    apply (parse_transaction_descriptor_tx _ σ1.1.2) in Hparse;last done.\n    rewrite Hparse //= in Heqc2.\n    case_bool_decide.\n    2: { destruct H1. split;auto. split;eauto. rewrite Heq_cur //. }\n    case_bool_decide.\n    2: { destruct H2. intros s Hin.\n         rewrite Heq_cur.\n         rewrite andb_true_iff. split.\n         rewrite /check_excl_access_page.\n         rewrite andb_true_iff. split.\n         apply Hcheckpg_acc.\n         set_solver + Hsubseteq_acc Hin.\n         by apply Hcheckpg_excl.\n         by apply Hcheckpg_own.\n    }\n    clear H1 H2.\n    rewrite /new_transaction /= /fresh_handle /= -Heq_hp in Heqc2.\n    destruct (elements sh) as [| h fhs] eqn:Hfhs.\n    { exfalso. rewrite -(elements_empty (C:= gset Word)) in Hfhs. apply Hneq_hp. apply set_eq.\n      intro. rewrite -elem_of_elements Hfhs elem_of_elements. split;intro;set_solver. }\n    assert (Heq_c2 : (m2,σ2) = (ExecI, (update_incr_PC (update_reg\n                      (update_reg\n                         (update_page_table_global revoke_access (alloc_transaction σ1 h (σ1.1.1.2, j, ps, tt, false))\n                            (alloc_transaction σ1 h (σ1.1.1.2, j, ps, Lending, false)).1.1.2 ps) R0 (encode_hvc_ret_code Succ)) R2 h)))).\n    {\n      destruct hvcf;\n      inversion Htt;subst tt;try contradiction.\n      destruct HstepP;subst m2 σ2; subst c2;done.\n      destruct HstepP;subst m2 σ2; subst c2;done.\n    }\n    inversion Heq_c2. clear H2 H3 Heqc2.\n    rewrite /= /gen_vm_interp.\n    (* unchanged part *)\n    rewrite (preserve_get_mb_gmap σ1).\n    rewrite (preserve_get_rx_gmap σ1).\n    all: try rewrite p_upd_pc_mb //.\n    rewrite p_upd_pc_mem 2!p_upd_reg_mem p_rvk_acc_mem p_alloc_tran_mem.\n    iFrame \"Hnum mem rx_state mb\".\n    (* upd regs *)\n    rewrite Heq_cur.\n    rewrite (u_upd_pc_regs _ i ai) //.\n    2: { rewrite 2!u_upd_reg_regs.\n         rewrite (preserve_get_reg_gmap σ1). rewrite lookup_insert_ne //.  rewrite lookup_insert_ne //. solve_reg_lookup. done.\n    }\n    rewrite u_upd_reg_regs p_upd_reg_current_vm p_rvk_acc_current_vm p_alloc_tran_current_vm Heq_cur.\n    rewrite u_upd_reg_regs p_rvk_acc_current_vm p_alloc_tran_current_vm Heq_cur.\n    rewrite (preserve_get_reg_gmap σ1) //.\n    iDestruct ((gen_reg_update3_global PC i (ai ^+ 1)%f R2 i h R0 i (encode_hvc_ret_code Succ)) with \"regs PC R2 R0\")\n      as \">[$ [PC [R2 R0]]]\";eauto.\n    (* upd pgt *)\n    rewrite (preserve_get_own_gmap (update_page_table_global revoke_access (alloc_transaction σ1 h (i, j, ps, tt, false)) i ps) (update_incr_PC _)).\n    2: rewrite p_upd_pc_pgt !p_upd_reg_pgt //.\n    rewrite p_rvk_acc_own. rewrite (preserve_get_own_gmap σ1) //.\n    iFrame \"pgt_owned\".\n    rewrite (preserve_get_access_gmap (update_page_table_global revoke_access (alloc_transaction σ1 h (i, j, ps, tt, false)) i ps) (update_incr_PC _)).\n    2: rewrite p_upd_pc_pgt p_upd_reg_pgt //.\n    iDestruct (access_agree with \"pgt_acc acc\") as %Hlookup_pgt_acc.\n    rewrite (u_rvk_acc_acc _ _ _ sacc).\n    2: {\n      rewrite p_alloc_tran_pgt.\n      intros p Hin_p.\n      specialize (Hvalid_excl p Hin_p).\n      destruct Hvalid_excl as [? [? [? [? _]]]].\n      exists (x,x0,x1).\n      done.\n    }\n    2: rewrite (preserve_get_access_gmap σ1) //.\n    rewrite (preserve_get_access_gmap σ1) //.\n    iDestruct (access_update (sacc ∖ ps) with \"pgt_acc acc\") as \">[$ acc]\". done.\n    assert (Hvalid_pgt: set_Forall (λ p : PID, σ1.1.1.1.2 !! p = Some (Some i, true, {[i]})) ps).\n    {\n      intros p Hin.\n      specialize (Hcheckpg_acc p).\n      feed specialize Hcheckpg_acc. set_solver + Hin Hsubseteq_acc.\n      specialize (Hvalid_excl p Hin).\n      destruct Hvalid_excl as [o [b [s [Hlk Htrue]]]].\n      symmetry in Htrue.\n      rewrite andb_true_iff in Htrue.\n      destruct Htrue as [-> Hsize].\n      rewrite /check_access_page /= in Hcheckpg_acc.\n      rewrite Hlk in Hcheckpg_acc.\n      destruct (decide (i ∈ s)); last done.\n      case_bool_decide;last done.\n      rewrite Hlk.\n      assert (s = {[i]}) as ->. apply size_singleton_le;auto.\n      specialize (Hcheckpg_own p Hin).\n      rewrite /check_ownership_page /= Hlk in Hcheckpg_own.\n      destruct o.\n      destruct (decide (i = v)).\n      2: done.\n      subst v. done.\n      done.\n    }\n    rewrite (preserve_get_excl_gmap (update_page_table_global revoke_access (alloc_transaction σ1 h (i, j, ps, tt, false)) i ps) (update_incr_PC _)).\n    2: rewrite p_upd_pc_pgt p_upd_reg_pgt //.\n    rewrite (p_rvk_acc_excl _ _ i tt).\n    2: { rewrite p_alloc_tran_pgt. destruct tt; done. }\n    rewrite (preserve_get_excl_gmap σ1);last done.\n    iFrame \"pgt_excl\".\n    (* upd tran *)\n    rewrite (preserve_get_trans_gmap (alloc_transaction σ1 h (i, j, ps, tt, false)) (update_incr_PC _)).\n    2: rewrite p_upd_pc_trans 2!p_upd_reg_trans p_rvk_acc_trans //.\n    rewrite u_alloc_tran_trans.\n    assert (sh = {[h]} ∪ sh ∖ {[h]}) as Heq_sh.\n    { assert (h ∈ sh).\n      rewrite -elem_of_elements. rewrite Hfhs. set_solver +.\n      rewrite union_comm_L.\n      rewrite difference_union_L.\n      set_solver + H1.\n    }\n    iPoseProof (big_sepS_union _ {[h]} (sh ∖ {[h]})) as \"[H _]\".\n    set_solver +.\n    iDestruct (\"H\" with \"[handles]\") as \"[h handles]\".\n    rewrite -Heq_sh. iExact \"handles\".\n    rewrite big_sepS_singleton. iDestruct \"h\" as \"[tran re]\". iClear \"H\".\n    iDestruct (trans_valid_None with \"trans tran\") as %Hlookup_tran.\n    iDestruct (trans_update_insert h (i, j, ps, tt) with \"trans tran\") as \">[$ tran]\".\n    { rewrite /valid_transaction //=. }\n    (* upd hp *)\n    rewrite (preserve_get_hpool_gset (alloc_transaction σ1 h (i, j, ps, tt, false)) (update_incr_PC _)).\n    2: rewrite p_upd_pc_trans 2!p_upd_reg_trans p_rvk_acc_trans //. rewrite u_alloc_tran_hpool.\n    iDestruct (hpool_update_diff h with \"hpool hp\") as \">[$ hp]\".\n    (* upd retri *)\n    rewrite (preserve_get_retri_gmap (alloc_transaction σ1 h (i, j, ps, tt, false)) (update_incr_PC _)).\n    2: rewrite p_upd_pc_trans p_upd_reg_trans //. rewrite u_alloc_tran_retri.\n    iDestruct (retri_update_insert with \"retri re\") as \">[$ re]\".\n    (* inv_trans_wellformed *)\n    rewrite (preserve_inv_trans_wellformed (alloc_transaction σ1 h (i, j, ps, tt, false))).\n    2: rewrite p_upd_pc_trans p_upd_reg_trans //.\n    iAssert (⌜inv_trans_wellformed (alloc_transaction σ1 h (i, j, ps, tt, false))⌝%I) as \"$\".\n    iPureIntro.\n    apply (p_alloc_tran_inv_wf h (i, j, ps, tt, false));auto.\n    simpl. simpl in Hlt_pg. rewrite Z.leb_le. lia.\n    (* inv_trans_pgt_consistent *)\n    rewrite (preserve_inv_trans_pgt_consistent (update_page_table_global revoke_access (alloc_transaction σ1 h (i, j, ps, tt, false)) i ps) (update_incr_PC _)).\n    2: rewrite p_upd_pc_trans p_upd_reg_trans //.\n    2: rewrite p_upd_pc_pgt p_upd_reg_pgt //.\n    iAssert (⌜inv_trans_pgt_consistent (update_page_table_global revoke_access (alloc_transaction σ1 h (i, j, ps, tt, false)) i ps)⌝%I) as \"$\".\n    iPureIntro.\n    apply p_not_share_inv_consist;auto.\n    { destruct Hwf as [_ [? _]]. done. }\n    (* inv_trans_ps_disj *)\n    rewrite (preserve_inv_trans_ps_disj (alloc_transaction σ1 h (i, j, ps, tt, false))).\n    2: rewrite p_upd_pc_trans p_upd_reg_trans //.\n    iAssert (⌜inv_trans_ps_disj (alloc_transaction σ1 h (i, j, ps, tt, false))⌝%I) as \"$\". iPureIntro.\n    apply p_alloc_tran_inv_disj;auto.\n    {\n      rewrite /= elem_of_disjoint.\n      intros.\n      apply elem_of_pages_in_trans' in H2.\n      destruct H2 as [h' [tran' [Hlk Hin_h']]].\n      specialize (Hconsis h' (Some tran') Hlk x Hin_h').\n      specialize (Hvalid_pgt x H1).\n      destruct Hwf as [_ [Hneq _]].\n      specialize (Hneq h' _ Hlk).\n      rewrite Hvalid_pgt in Hconsis.\n      destruct (tran'.1.2);destruct tran'.2;auto.\n      - set_solver + Hconsis.\n      - inversion Hconsis.\n      - inversion Hconsis.\n      - simpl in Hneq.\n        set_solver + Hconsis Hneq.\n      - set_solver + Hconsis.\n    }\n    (* just_scheduled *)\n    iModIntro.\n    rewrite /just_scheduled_vms /just_scheduled.\n    rewrite /scheduled /machine.scheduler /= /scheduler.\n    rewrite p_upd_pc_current_vm 2!p_upd_reg_current_vm p_rvk_acc_current_vm p_alloc_tran_current_vm.\n    rewrite Heq_cur.\n    iSplitL \"\".\n    set fl := (filter _ _).\n    assert (fl = []) as ->.\n    {\n      rewrite /fl.\n      induction n.\n      - simpl.\n        rewrite filter_nil //=.\n      - rewrite seq_S.\n        rewrite filter_app.\n        rewrite IHn.\n        simpl.\n        rewrite filter_cons_False //=.\n        rewrite andb_negb_l.\n        done.\n    }\n    by iSimpl.\n    (* Φ *)\n    case_bool_decide;last done.\n    simpl. iApply \"HΦ\".\n    rewrite /fresh_handles. iFrame.\n    iSplitL \"own excl\".\n    rewrite big_sepS_sep. iFrame.\n    iExists h. iFrame.\n    rewrite Heq_sh.\n    iPureIntro. set_solver +.\nQed.\n\nLemma mem_lend {i wi r0 r1 r2 hvcf p_tx sacc} ai j mem_tx sh (ps: gset PID) :\n  (tpa ai) ∈ sacc ->\n  (tpa ai) ≠ p_tx ->\n  (* len is the length of the msg *)\n  let len := (Z.to_nat (finz.to_z r1)) in\n  (* the decoding of wi is correct *)\n  decode_instruction wi = Some(Hvc) ->\n  (* the decoding of R0 is a FFA mem_share *)\n  decode_hvc_func r0 = Some(hvcf) ->\n  hvcf_to_tt hvcf = Some Lending ->\n  (* the whole descriptor resides in the TX page *)\n  (len <= page_size)%Z ->\n  (* the descriptor *)\n  parse_transaction_descriptor mem_tx (of_pid p_tx) len = Some (i, None, j, ps) ->\n  (* caller is not the receiver *)\n  i ≠ j ->\n  ps ⊆ sacc ->\n  (* there is at least one free handle in the hpool *)\n  sh ≠ ∅ ->\n  {SS{{ ▷(PC @@ i ->r ai) ∗\n      ▷ ai ->a wi ∗\n      (* VM i exclusively owns pages in ps *)\n      ▷ ([∗ set] p ∈ ps, p -@O> i ∗ p -@E> true) ∗\n      ▷ (i -@A> sacc) ∗\n      ▷ (R0 @@ i ->r r0) ∗\n      ▷ (R1 @@ i ->r r1) ∗\n      ▷ (R2 @@i ->r r2) ∗\n      ▷ (fresh_handles 1 sh) ∗\n      ▷ TX@ i := p_tx ∗\n      ▷ memory_page p_tx mem_tx\n       }}}\n   ExecI @ i {{{ RET (false, ExecI) ;\n                 PC @@ i ->r (ai ^+ 1)%f ∗\n                 ai ->a wi ∗\n                 ([∗ set] p ∈ ps, p -@O> i ∗ p -@E> true) ∗\n                 i -@A> (sacc ∖ ps) ∗\n                 R0 @@ i ->r (encode_hvc_ret_code Succ) ∗\n                 R1 @@ i ->r r1 ∗\n                 (∃ (wh: Word), ⌜wh ∈ sh⌝ ∗\n                 R2 @@ i ->r wh ∗\n                 wh ->t (i, j, ps, Lending) ∗\n                 wh ->re false ∗\n                 fresh_handles 1 (sh∖{[wh]})) ∗\n                 TX@ i := p_tx ∗\n                 memory_page p_tx mem_tx}}}.\nProof.\n  by apply (mem_not_share Lending).\nQed.\n\nLemma mem_donate {i wi r0 r1 r2 hvcf p_tx sacc} ai j mem_tx sh (ps: gset PID) :\n  (tpa ai) ∈ sacc ->\n  (tpa ai) ≠ p_tx ->\n  (* len is the length of the msg *)\n  let len := (Z.to_nat (finz.to_z r1)) in\n  (* the decoding of wi is correct *)\n  decode_instruction wi = Some(Hvc) ->\n  (* the decoding of R0 is a FFA mem_share *)\n  decode_hvc_func r0 = Some(hvcf) ->\n  hvcf_to_tt hvcf = Some Donation ->\n  (* the whole descriptor resides in the TX page *)\n  (len <= page_size)%Z ->\n  (* the descriptor *)\n  parse_transaction_descriptor mem_tx (of_pid p_tx) len = Some (i, None, j, ps) ->\n  (* caller is not the receiver *)\n  i ≠ j ->\n  ps ⊆ sacc ->\n  (* there is at least one free handle in the hpool *)\n  sh ≠ ∅ ->\n  {SS{{ ▷(PC @@ i ->r ai) ∗\n      ▷ ai ->a wi ∗\n      (* VM i exclusively owns pages in ps *)\n      ▷ ([∗ set] p ∈ ps, p -@O> i ∗ p -@E> true) ∗\n      ▷ (i -@A> sacc) ∗\n      ▷ (R0 @@ i ->r r0) ∗\n      ▷ (R1 @@ i ->r r1) ∗\n      ▷ (R2 @@i ->r r2) ∗\n      ▷ (fresh_handles 1 sh) ∗\n      ▷ TX@ i := p_tx ∗\n      ▷ memory_page p_tx mem_tx\n       }}}\n   ExecI @ i {{{ RET (false, ExecI) ;\n                 PC @@ i ->r (ai ^+ 1)%f ∗\n                 ai ->a wi ∗\n                 ([∗ set] p ∈ ps, p -@O> i ∗ p -@E> true) ∗\n                 i -@A> (sacc ∖ ps) ∗\n                 R0 @@ i ->r (encode_hvc_ret_code Succ) ∗\n                 R1 @@ i ->r r1 ∗\n                 (∃ (wh: Word), ⌜wh ∈ sh⌝ ∗\n                 R2 @@ i ->r wh ∗\n                 wh ->t (i, j, ps, Donation) ∗\n                 wh ->re false ∗\n                 fresh_handles 1 (sh∖{[wh]})) ∗\n                 TX@ i := p_tx ∗\n                 memory_page p_tx mem_tx}}}.\nProof.\n  by apply (mem_not_share Donation).\nQed.\n\nEnd mem_send.\n", "meta": {"author": "logsem", "repo": "VMSL", "sha": "0a9b005b599a770e40c07abc9aa10a4ee9759315", "save_path": "github-repos/coq/logsem-VMSL", "path": "github-repos/coq/logsem-VMSL/VMSL-0a9b005b599a770e40c07abc9aa10a4ee9759315/theories/rules/mem_send.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.29177949564392064}}
{"text": "From ITree Require Import\n     Basics\n     Subevent\n     Events.State\n     Indexed.Sum.\n\nFrom Coq Require Import\n     Nat\n     List\n     Logic.Eqdep\n     Classes.RelationClasses\n     Program.Tactics.\n\nFrom Equations Require Import Equations.\n\nFrom ExtLib Require Import\n     RelDec\n     Monad\n     Option.\n\nFrom Coinduction Require Import\n     coinduction rel tactics.\n\nFrom CTree Require Import\n     CTree\n     Eq\n     Interp.Fold\n     Interp.FoldStateT\n     Interp.Log\n     Interp.Network\n     Logic.Ctl.\n\nImport CTreeNotations ListNotations Log CtlNotations Monads Network.  \nLocal Open Scope ctree_scope.\n\nSet Implicit Arguments.\nSet Contextual Implicit.\nSet Asymmetric Patterns.\n\nModule Fair.\n\n  (** Compose [k] with itself [i] times. *)\n  Fixpoint frepeat {E C X}\n           (i: nat) (k: ctree E C X): ctree E C X :=\n    match i with\n    | 0 => k\n    | S n => k ;; frepeat n k\n    end.\n\n  (** This is not associative, consider\n      (A || B) || C ~ A || (B || C)\n   \n      The sequence [B, C] is impossible for the left,\n      as it will do [B, B, ..., B, A] by picking [B] then [C].\n      But it is possible for the right, by taking the branch [B]. *)\n        \n  Definition parafair{E C X}\n             `{BN -< C} `{B1 -< C} `{B2 -< C} `{B0 -< C}\n             (a b: ctree E C X): ctree E C void :=\n    CTree.forever\n      (brD2\n         (i <- branch false (branchN) ;;\n          frepeat i a ;;\n          b)\n         \n         (i <- branch false (branchN) ;;\n          frepeat i b ;;\n          a)).\n\n  Variant ID: Type -> Type :=\n    | Index: nat -> ID unit.\n\n  Definition id{C}(n: nat): ctree ID C unit := trigger (Index n).\n\n  (* Ignore [t], label observation equals [e] *)\n  Inductive obs_eq {E C: Type -> Type}{X Y: Type} :\n    E Y -> ctree E C X -> @label E -> Prop :=\n  | ObsEq y : forall t e, obs_eq e t (obs e y).\n\n  #[global] Instance proper_obs_eq_equ {E C: Type -> Type} {X Y} (e: E Y) {HasStuck: B0 -< C} :\n    Proper (@equ E C X X eq ==> eq ==> iff) (@obs_eq E C X Y e).\n  Proof.\n    unfold Proper, respectful, impl; cbn.      \n    intros x y EQ ? ? <-; split; intro OBS; inv OBS; econstructor; now rewrite EQ.\n  Qed.\n  (** TODO: This would be more simply stated and without [ID] \n      and [obs_eq] as\n\n    forall l (t1 t2: ctree ID C void),\n      (parafair t1 t2), l |= AG (AF (fun l t => t ≅ t1)) /\\\n      (parafair t1 t2), l |= AG (AF (fun l t => t ≅ t2)),\n  *)\n\n  Lemma para_fair {C}\n        `{HBN: BN -< C} `{HB1: B1 -< C} `{HB2: B2 -< C} `{HB0: B0 -< C}:\n    forall l (t: ctree ID C void),\n      t = parafair (id 0) (id 1) ->\n      t, l |= AG (AF (obs_eq (Index 0))).\n  Proof.\n    intros; revert l.\n    unfold ag; subst; coinduction R CIH; intro l.\n    split.\n    (* Eventually [ID = 0] shows up *)\n    - unfold parafair.\n      rewrite ctl_af_ax; right.\n      \n      rewrite ctree_eta; cbn; fold_subst.\n      unfold ax; intros; inv_trans_one.\n      (* Never use [trans_bind_inv_l] it loses the target label and introduces a new one! *)\n      destruct x;\n        apply trans_bind_inv in TR as [(HV & t3 & TR & ?) | (l2 & TRV  & TR )].\n      + apply trans_bind_inv in TR as [(HV' & t4 & TR & ?) | (l3 & TRV'  & TR' )].\n        * apply trans_brD_inv in TR as (niter & TR).\n          apply trans_ret_inv in TR as (ST & ->).\n          exfalso; apply HV; econstructor. (* Not a val! *)\n        * eapply trans_val_inv in TRV'. (* Nothing to do with TRV *)\n          clear TRV'.\n          (* [t3] is [id 0]^+ *)\n          destruct l3; cbn in *.\n          (* [0] iterations = [id 0] *)\n          apply trans_bind_inv in TR' as [(HV'' & t4 & TR & ?) | (l3 & TRV'  & TR )].\n          \n          \n  Admitted.\n  \n \nEnd Fair.\n  \n\n\n", "meta": {"author": "vellvm", "repo": "ctrees", "sha": "a622bc2e63eaa987e081b862e9aafeea3f8f5d79", "save_path": "github-repos/coq/vellvm-ctrees", "path": "github-repos/coq/vellvm-ctrees/ctrees-a622bc2e63eaa987e081b862e9aafeea3f8f5d79/examples/Messaging/Fair.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.29177495013178073}}
{"text": "From isla Require Import opsem.\n\nDefinition a44 : isla_trace :=\n  Smt (DeclareConst 27%Z (Ty_BitVec 1%N)) Mk_annot :t:\n  Smt (DeclareConst 37%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"R20\" [] (RegVal_Base (Val_Symbolic 37%Z)) Mk_annot :t:\n  Smt (DefineConst 38%Z (Val (Val_Symbolic 37%Z) Mk_annot)) Mk_annot :t:\n  Smt (DeclareConst 39%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"R24\" [] (RegVal_Base (Val_Symbolic 39%Z)) Mk_annot :t:\n  Smt (DefineConst 40%Z (Val (Val_Symbolic 39%Z) Mk_annot)) Mk_annot :t:\n  ReadReg \"PSTATE\" [Field \"Z\"] (RegVal_Struct [(\"Z\", RegVal_Base (Val_Symbolic 27%Z))]) Mk_annot :t:\n  Smt (DefineConst 43%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 43%Z) Mk_annot)) Mk_annot :t:\n    Smt (DefineConst 44%Z (Val (Val_Symbolic 38%Z) Mk_annot)) Mk_annot :t:\n    WriteReg \"R20\" [] (RegVal_Base (Val_Symbolic 44%Z)) Mk_annot :t:\n    Smt (DeclareConst 45%Z (Ty_BitVec 64%N)) Mk_annot :t:\n    ReadReg \"_PC\" [] (RegVal_Base (Val_Symbolic 45%Z)) Mk_annot :t:\n    Smt (DefineConst 46%Z (Manyop (Bvmanyarith Bvadd) [Val (Val_Symbolic 45%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 46%Z)) Mk_annot :t:\n    tnil;\n    Smt (Assert (Unop (Not) (Val (Val_Symbolic 43%Z) Mk_annot) Mk_annot)) Mk_annot :t:\n    Smt (DefineConst 44%Z (Val (Val_Symbolic 40%Z) Mk_annot)) Mk_annot :t:\n    WriteReg \"R20\" [] (RegVal_Base (Val_Symbolic 44%Z)) Mk_annot :t:\n    Smt (DeclareConst 45%Z (Ty_BitVec 64%N)) Mk_annot :t:\n    ReadReg \"_PC\" [] (RegVal_Base (Val_Symbolic 45%Z)) Mk_annot :t:\n    Smt (DefineConst 46%Z (Manyop (Bvmanyarith Bvadd) [Val (Val_Symbolic 45%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 46%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/instructions/binary_search/a44.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.2917749441300061}}
{"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 CFold.  \n\nSection CFIdeal.\n  Context {chan : Type -> Type}.\n  Context (k : nat) (n : nat) (honest : pred 'I_n).\n  Context (leak : chan (k.-tuple bool)).\n  Context (ok : chan unit).\n  Context (out : n.-tuple (chan (k.-bv))).\n\n  Definition CFIdealParty (i : 'I_n) (send : chan (k.-bv)) :=\n         (if honest i then Out (tnth out i) (copy send) else prot0).\n\n\n  Definition CFIdealFunc (send : chan (k.-bv)) :=\n    b <- new (k.-bv) ;;\n    pars [::\n            Out b (Samp (Unif));\n            Out leak (copy b);\n            Out send (_ <-- Read ok ;; copy b) ].\n\n  Definition CFIdeal :=\n    send <- new (k.-bv) ;;\n    pars [::\n            CFIdealFunc send;\n            \\||_(i < n) CFIdealParty i send\n    ].\n\nEnd CFIdeal.            \n\n\nSection CFReal.\n  Context {chan : Type -> Type}.\n  Context (k : nat) (n_ : nat).\n  Definition n := n_.+1.\n  Context (honest : pred 'I_n).\n  Context (out : n.-tuple (chan (k.-bv))).\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  Definition CFRealParty_honest \n             (committed : n.-tuple (chan unit)) (opened : n.-tuple (chan (k.-bv)))\n             (commit : chan (k.-bv)) (open : chan unit) (out : chan (k.-bv))\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            Out out (copy (tnth opened_sum ord_max))\n           ].\n\n  Definition 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 CFParty (i : 'I_n)\n             (committed : n.-tuple (chan unit)) (opened : n.-tuple (chan k.-bv))\n             (commit : chan k.-bv) (open : chan unit) (out : chan k.-bv) :=\n    if honest i then CFRealParty_honest committed opened commit open out\n                else CFRealParty_corr i committed opened commit open.                        \n            \n  Definition FComm\n             (commit : chan k.-bv)\n             (committed : chan unit)\n             (open : chan unit)\n             (opened : chan k.-bv) :=\n    pars [::\n            Out committed (_ <-- Read commit ;; Ret tt);\n            Out opened (_ <-- Read open ;; copy commit)\n         ].\n\n  Definition CFReal :=\n    commit <- newvec n @ k.-bv ;;\n    committed <- newvec n @ unit ;;\n    open <- newvec n @ unit ;;\n    opened <- newvec n @ k.-bv ;;\n    pars [::\n            \\||_(i < n) FComm (tnth commit i) (tnth committed i) (tnth open i) (tnth opened i);\n         \\||_(i < n) CFParty i committed opened (tnth commit i) (tnth open i) (tnth out i)\n    ].\n\nEnd CFReal.                   \n                                     \n           \n\n    \n           \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/CoinFlip.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421276, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2917749441300061}}
{"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.\n\nRequire Import LLIR.LLIR.\nRequire Import LLIR.Maps.\nRequire Import LLIR.Values.\nRequire Export LLIR.Types.\n\n\nDefinition type_env := PTrie.t ty.\n\n(* Type environment from instructions. *)\nDefinition ty_env_inst (insts: inst_map): type_env :=\n  PTrie.fold\n    (fun env _ i =>\n      match get_inst_ty_def i with\n      | Some (ty, dst) => PTrie.set env dst ty\n      | None => env\n      end)\n    insts PTrie.empty.\n\n(* Type environment from phis. *)\nDefinition ty_env_phi (phis: phi_map): type_env :=\n  PTrie.fold\n    (fun env _ block =>\n      List.fold_left\n        (fun env p =>\n          match p with\n          | LLPhi (ty, dst) _ => PTrie.set env dst ty\n          end)\n        block env)\n    phis PTrie.empty.\n\n(* Type environment for all registers. *)\nDefinition ty_env (f: func): type_env :=\n  PTrie.union (ty_env_inst f.(fn_insts)) (ty_env_phi f.(fn_phis)).\n\n(* Holds if the evironment has the correct type for a reg. *)\nDefinition well_typed_reg (env: type_env) (r: reg) (t: ty) :=\n  env ! r = Some t.\n\n(* Typing rules for binary instructions. *)\nInductive WellTypedBinop: binop -> ty -> ty -> ty -> Prop :=\n  | type_cmp:\n    forall (t: ty) (dt: ty),\n      WellTypedBinop LLCmp t t dt\n  | type_add:\n    forall (t: ty),\n      WellTypedBinop LLAdd t t t\n  | type_sll:\n    forall (tl: ty_int) (tr: ty_int),\n      WellTypedBinop LLSll (TInt tl) (TInt tr) (TInt tl)\n  .\n\n(* Typing rules for unary instructions. *)\nInductive WellTypedUnop: unop -> ty -> ty -> Prop :=\n  | type_sext_i32_i64: WellTypedUnop LLSext (TInt I32) (TInt I64)\n  .\n\n(* Typing rules for instructions. *)\nInductive WellTypedInst: type_env -> inst -> Prop :=\n  | type_jmp:\n    forall (env: type_env) (target: node),\n      WellTypedInst env (LLJmp target)\n  | type_jcc:\n    forall (env: type_env) (cond: reg) (bt: node) (bf: node) (i: ty_int)\n      (COND_TY: well_typed_reg env cond (TInt i)),\n      WellTypedInst env (LLJcc cond bt bf)\n  | type_ret:\n    forall (env: type_env) (ret: reg) (t: ty)\n      (RET_TY: well_typed_reg env ret t),\n      WellTypedInst env (LLRet (Some ret))\n  | type_ret_void:\n    forall (env: type_env),\n      WellTypedInst env (LLRet None)\n  | type_st:\n    forall (env: type_env) (next: node) (addr: reg) (val: reg) (t: ty)\n      (ADDR_TY: well_typed_reg env addr ptr_ty)\n      (VAL_TY: well_typed_reg env val t),\n      WellTypedInst env (LLSt next addr val)\n  | type_undef:\n    forall (env: type_env) (next: node) (dst: reg) (t: ty)\n      (DST_TY: well_typed_reg env dst t),\n      WellTypedInst env (LLUndef (t, dst) next)\n  | type_ld:\n    forall (env: type_env) (next: node) (dst: reg) (t: ty) (addr: reg)\n      (ADDR_TY: well_typed_reg env addr ptr_ty)\n      (DST_TY: well_typed_reg env dst t),\n      WellTypedInst env (LLLd (t, dst) next addr)\n  | type_frame:\n    forall (env: type_env) (dst:reg) (next: node)\n      (object: positive) (offset: nat)\n      (DST_TY: well_typed_reg env dst ptr_ty),\n      WellTypedInst env (LLFrame dst next object offset)\n  | type_global:\n    forall (env: type_env) (dst: reg) (next: node)\n      (segment: positive) (object: positive) (offset: nat)\n      (DST_TY: well_typed_reg env dst ptr_ty),\n      WellTypedInst env (LLGlobal dst next segment object offset)\n  | type_int:\n    forall (env: type_env) (dst: reg) (next: node) (val: INT.t) (t: ty)\n      (INT_TY: TypeOfInt val t)\n      (DST_TY: well_typed_reg env dst t),\n      WellTypedInst env (LLInt dst next val)\n  | type_arg:\n    forall (env: type_env) (t: ty) (dst: reg) (next: node) (idx: nat)\n      (DST_TY: well_typed_reg env dst t),\n      WellTypedInst env (LLArg (t, dst) next idx)\n  | type_binop:\n    forall (env: type_env) (op: binop) (next: node)\n      (l: reg) (tl: ty) (r: reg) (tr: ty) (dst: reg) (t: ty)\n      (LHS_TY: well_typed_reg env l tl)\n      (RHS_TY: well_typed_reg env r tr)\n      (DST_TY: well_typed_reg env dst t)\n      (OP: WellTypedBinop op tl tr t),\n      WellTypedInst env (LLBinop (t, dst) next op l r)\n  | type_unop:\n    forall (env: type_env) (op: unop) (next: node)\n      (arg: reg) (argt: ty) (dst: reg) (t: ty)\n      (ARG_TY: well_typed_reg env arg argt)\n      (DST_TY: well_typed_reg env dst t)\n      (OP: WellTypedUnop op argt t),\n      WellTypedInst env (LLUnop (t, dst) next op arg)\n  | type_mov:\n    forall (env: type_env) (op: unop) (next: node)\n      (arg: reg) (dst: reg) (t: ty)\n      (ARG_TY: well_typed_reg env arg t)\n      (DST_TY: well_typed_reg env dst t),\n      WellTypedInst env (LLMov (t, dst) next arg)\n  | type_invoke_void:\n    forall (env: type_env) (next: node)\n      (dst: reg) (t: ty)\n      (callee: reg) (args: list reg) (exn: node)\n      (CALLEE_TY: well_typed_reg env callee ptr_ty),\n      WellTypedInst env (LLInvoke (Some (t, dst)) next callee args exn)\n  | type_call_void:\n    forall (env: type_env) (next: node)\n      (callee: reg) (args: list reg)\n      (CALLEE_TY: well_typed_reg env callee ptr_ty),\n      WellTypedInst env (LLCall None next callee args)\n  | type_call:\n    forall (env: type_env) (next: node)\n      (callee: reg) (args: list reg) (dst: reg) (t: ty)\n      (CALLEE_TY: well_typed_reg env callee ptr_ty)\n      (DST_TY: well_typed_reg env dst t),\n      WellTypedInst env (LLCall (Some (t, dst)) next callee args)\n  | type_tcall:\n    forall (env: type_env)\n      (callee: reg) (args: list reg)\n      (CALLEE_TY: well_typed_reg env callee ptr_ty),\n      WellTypedInst env (LLTCall callee args)\n  | type_syscall:\n    forall (env: type_env) (next: node)\n      (sno: reg) (args: list reg) (tsno: ty_int) (dst: reg)\n      (SNO_TY: well_typed_reg env sno sys_no_ty)\n      (ARG_TY: forall (arg: reg), In arg args -> well_typed_reg env arg sys_arg_ty)\n      (DST_TY: well_typed_reg env dst sys_ret_ty),\n      WellTypedInst env (LLSyscall dst next sno args)\n  | type_trap:\n    forall (env: type_env),\n      WellTypedInst env LLTrap\n  .\n\nInductive WellTypedInsts: type_env -> inst_map -> Prop :=\n  | well_typed_insts:\n    forall\n      (env: type_env) (insts: inst_map)\n      (INSTS: forall (n: node) (i: inst), Some i = insts ! n -> WellTypedInst env i),\n        WellTypedInsts env insts.\n\nInductive WellTypedPhi: type_env -> phi -> Prop :=\n  | well_typed_phi:\n    forall (env: type_env) (dst: reg) (t: ty) (ins: list (node * reg))\n      (INS: forall (n: node) (r: reg), In (n, r) ins -> well_typed_reg env r t),\n      WellTypedPhi env (LLPhi (t, dst) ins)\n  .\n\nInductive WellTypedPhis: type_env -> phi_map -> Prop :=\n  | well_typed_phis:\n    forall\n      (env: type_env) (phis: phi_map)\n      (PHIS:\n        forall (n: node) (block: list phi) (p: phi),\n          Some block = phis ! n ->\n          In p block ->\n          WellTypedPhi env p),\n    WellTypedPhis env phis.\n\nInductive WellTypedFunc: func -> Prop :=\n  | well_typed_func:\n    forall (f: func)\n      (INSTS: WellTypedInsts (ty_env f) f.(fn_insts))\n      (PHIS: WellTypedPhis (ty_env f) f.(fn_phis)),\n      WellTypedFunc f\n  .\n\nInductive WellTypedProg: prog -> Prop :=\n  | well_typed_prog:\n    forall (p: prog)\n      (FUNCS: forall (n: name) (f: func), Some f = p ! n -> WellTypedFunc f),\n      WellTypedProg p\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/Typing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947155710234, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2917749381282313}}
{"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.GeneralTactics4.\n\n  Arguments store_out {_} _ _.\n  Arguments ADTOut {_} _.\n\n  Require Import Bedrock.Memory.\n\n  Definition no_alias (words_cinput : list (W * Value ADTValue)) := forall i j p (ai aj : ADTValue), nth_error words_cinput i = Some (p, ADT ai) -> nth_error words_cinput j = Some (p, ADT aj) -> i = j.\n\n  Definition not_reachable_p p (words_cinput : list (W * Value ADTValue)) := forall i v, nth_error words_cinput i = Some (p, v) -> exists w, v = SCA _ w.\n\n  Require Import Platform.Cito.WordMap.\n  Import WordMap.\n  Require Import Platform.Cito.WordMapFacts.\n\n  Require Import Platform.Cito.GeneralTactics.\n  Require Import Platform.Cito.ListFacts4.\n\n  Lemma fold_bwd p a triples : \n    forall h,\n      let words_cinput := List.map (fun x => (Word x, ADTIn x)) triples in\n      no_alias words_cinput -> \n      ((not_reachable_p p words_cinput /\\ find p h = Some a) \\/ \n       exists i input, nth_error triples i = Some {| Word := p; ADTIn := ADT input; ADTOut := Some a |}) ->\n      find p (List.fold_left store_out triples h) = Some a.\n  Proof.\n    induction triples; simpl in *.\n    intros h ? H.\n    openhyp.\n    eauto.\n    rewrite nth_error_nil in H; discriminate.\n\n    destruct a0 as [tp ti to]; simpl in *.\n    intros h Hna H.\n    eapply IHtriples.\n    Lemma no_alias_tail ls : forall e, no_alias (e :: ls) -> no_alias ls.\n    Proof.\n      unfold no_alias; intros e Hna.\n      intros i j p ai aj Hi Hj.\n      assert (S i = S j).\n      eapply Hna; eauto.\n      inject H; eauto.\n    Qed.\n    eapply no_alias_tail; eauto.\n    destruct H as [[Hnr hf] | [i [ai Ht]] ].\n    left.\n    split.\n    Lemma not_reachable_p_incl ls1 ls2 p : List.incl ls1 ls2 -> not_reachable_p p ls2 -> not_reachable_p p ls1.\n      unfold not_reachable_p; intros Hin Hnr.\n      intros i v Hi.\n      eapply incl_nth_error in Hi; eauto; openhyp.\n      eapply Hnr in H; eauto; openhyp.\n    Qed.\n    Lemma not_reachable_p_tail ls e p : not_reachable_p p (e :: ls) -> not_reachable_p p ls.\n      intros; eapply not_reachable_p_incl; eauto.\n      eapply incl_tl; eapply incl_refl; eauto.\n    Qed.\n    eapply not_reachable_p_tail; eauto.\n    unfold store_out; simpl.\n    destruct ti as [w | ai].\n    eauto.\n    destruct to as [ao |].\n    destruct (Word.weq p tp).\n    Lemma not_not_reachable_p p a ls : ~ not_reachable_p p ((p, ADT a) :: ls).\n    Proof.\n      unfold not_reachable_p.\n      intros H.\n      specialize (H 0 (ADT a)).\n      simpl in *.\n      edestruct H; eauto.\n      discriminate.\n    Qed.\n    subst; solve [eapply not_not_reachable_p in Hnr; intuition].\n    solve [rewrite add_neq_o; eauto].\n    destruct (Word.weq p tp).\n    subst; solve [eapply not_not_reachable_p in Hnr; intuition].\n    solve [rewrite remove_neq_o; eauto].\n    destruct i as [| i]; simpl in *.\n    inject Ht.\n    left.\n    split.\n    Lemma no_alias_not_reachable_p p a ls : no_alias ((p, ADT a) :: ls) -> not_reachable_p p ls.\n    Proof.\n      intros Hna.\n      unfold not_reachable_p.\n      intros i v Hi.\n      destruct v.\n      eauto.\n      unfold no_alias in *.\n      assert (S i = 0).\n      eapply Hna; simpl in *; eauto.\n      discriminate.\n    Qed.\n    eapply no_alias_not_reachable_p; eauto.\n    unfold store_out; simpl.\n    solve [rewrite add_eq_o; eauto].\n\n    right.\n    eauto.\n  Qed.\n\n  Lemma fold_fwd : \n    forall k (v : ADTValue) ls h,\n      WordMap.MapsTo k v (fold_left store_out ls h) -> \n      (WordMap.MapsTo k v h /\\ \n       forall a o, ~List.In {| Word := k; ADTIn := ADT a; ADTOut := o |} ls) \n      \\/ exists a, \n           List.In {| Word := k; ADTIn := ADT a; ADTOut := Some v |} ls.\n  Proof.\n    induction ls; simpl; intuition.\n    apply IHls in H; intuition.\n\n    unfold store_out, 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    inject H3.\n    eauto.\n    eauto 2.\n    apply remove_mapsto_iff in H; intuition subst.\n    left; intuition.\n    inject H3.\n    eauto.\n    eauto 2.\n    destruct H0.\n    eauto.\n  Qed.\n\n  Lemma fold_store_out_elim p a triples words_cinput coutput h :\n    words_cinput = List.map (fun x => (Word x, ADTIn x)) triples ->\n    coutput = List.map ADTOut triples ->\n    find p (List.fold_left store_out triples h) = Some a -> \n    (not_reachable_p p words_cinput /\\ find p h = Some a) \\/ \n    exists i input, nth_error triples i = Some {| Word := p; ADTIn := ADT input; ADTOut := Some a |}.\n  Proof.\n    intros Hwid Hod Hf.\n    subst.\n    eapply find_mapsto_iff in Hf.\n    eapply fold_fwd in Hf.\n    destruct Hf as [[Hf Hnr] | [ai Hin]].\n    eapply find_mapsto_iff in Hf.\n    left.\n    split.\n    unfold not_reachable_p.\n    intros i v Hwi.\n    eapply nth_error_map_elim in Hwi.\n    destruct Hwi as [[tp ti to] [Ht He]]; simpl in *.\n    inject He.\n    destruct v.\n    eexists; eauto.\n    eapply Locals.nth_error_In in Ht.\n    solve [eapply Hnr in Ht; intuition].\n    solve [eauto].\n\n    right.\n    eapply in_nth_error in Hin.\n    destruct Hin as [i Ht].\n    repeat eexists; eauto.\n  Qed.\n\n  Lemma fold_store_out_intro p a triples words_cinput coutput h :\n    words_cinput = List.map (fun x => (Word x, ADTIn x)) triples ->\n    coutput = List.map ADTOut triples ->\n    no_alias words_cinput -> \n    ((not_reachable_p p words_cinput /\\ find p h = Some a) \\/ \n     exists i input, nth_error triples i = Some {| Word := p; ADTIn := ADT input; ADTOut := Some a |}) ->\n    find p (List.fold_left store_out triples h) = Some a.\n  Proof.\n    intros; subst; eapply fold_bwd; eauto.\n  Qed.\n\n  Lemma find_Some_fold_store_out p a words_cinput coutput h :\n    no_alias words_cinput -> \n    length words_cinput = length coutput ->\n    (find p (List.fold_left store_out (make_triples words_cinput coutput) h) = Some a <-> \n     ((not_reachable_p p words_cinput /\\ find p h = Some a) \\/ \n      exists i input, \n        nth_error words_cinput i = Some (p, ADT input) /\\\n        nth_error coutput i = Some (Some a))).\n  Proof.\n    intros Hna Hl.\n    split.\n    intros Hf.\n    eapply fold_store_out_elim in Hf; simpl; eauto.\n    destruct Hf as [[Hnr Hf] | [i [ai Ht]]].\n    left.\n    Require Import Platform.Cito.SemanticsFacts7.\n    rewrite make_triples_Word_ADTIn in *; eauto.\n    right.\n    exists i, ai.\n    eapply nth_error_make_triples_elim in Ht; eauto.\n\n    intros H.\n    eapply fold_store_out_intro; eauto.\n    rewrite make_triples_Word_ADTIn; eauto.\n    destruct H as [[Hnr Hf] | [i [ai [Hwi Ho]]]].\n    left.\n    split.\n    rewrite make_triples_Word_ADTIn; eauto.\n    solve [eauto].\n    right.\n    exists i, ai.\n    eapply nth_error_make_triples_intro; eauto.\n  Qed.\n\n  Definition ret_doesn't_matter (p addr : W) (ret : Value ADTValue) := p <> addr \\/ exists w, ret = SCA _  w.\n  Definition p_addr_ret_dec (p addr : W) (ret : Value ADTValue) : { a : ADTValue | ret = ADT a /\\ p = addr} + {ret_doesn't_matter p addr ret}.\n    destruct ret.\n    right; right; eexists; eauto.\n    destruct (Word.weq p addr).\n    left; eexists; eauto.\n    right; left; eauto.\n  Defined.\n\n  Import FMapNotations.\n  Open Scope fmap_scope.\n\n  Lemma find_ret_doesn't_matter p addr ret triples h h1 : ret_doesn't_matter p addr ret -> find p (heap_upd_option (fold_left store_out triples h) (fst (decide_ret addr ret)) (snd (decide_ret addr ret)) - h1) = find p (fold_left store_out triples h - h1).\n  Proof.\n    intros Hdm; destruct Hdm.\n    2 : solve [openhyp; subst; simpl; eauto].\n    destruct ret; simpl in *.\n    solve [openhyp; subst; simpl; eauto].\n    solve [eapply option_univalence; intros v; split; intros Hf; eapply diff_find_Some_iff in Hf; eapply diff_find_Some_iff; rewrite add_neq_o in *; eauto].\n  Qed.\n\n  Notation Value := (@Value ADTValue).\n\n  Definition only_adt := List.map (fun x : Value => match x with | ADT a => Some a | _ => None end).\n\n  Definition reachable_heap (vs : Locals.vals) argvars (input : list Value) := make_mapM (List.map (fun x => vs x) argvars) (only_adt input).\n\n  Lemma in_reachable_heap_iff vs ks : forall ins p, length ks = length ins -> (In p (reachable_heap vs ks ins) <-> exists i k a, nth_error ks i = Some k /\\ nth_error ins i = Some (ADT a) /\\ vs k = p).\n  Proof.\n    unfold reachable_heap, only_adt; intros ins p Hl.\n    split.\n    intros Hi.\n    eapply in_make_mapM_iff in Hi.\n    destruct Hi as [i [a [Hk Hv]]].\n    eapply nth_error_map_elim in Hk.\n    destruct Hk as [k [Hk Hvs]].\n    subst.\n    eapply nth_error_map_elim in Hv.\n    destruct Hv as [v [Hv Ha]].\n    destruct v as [w | a'].\n    discriminate.\n    inject Ha.\n    solve [exists i, k, a; eauto].\n    solve [repeat rewrite map_length; eauto].\n\n    intros Hex.\n    destruct Hex as [i [k [a [Hk [Hv Hvs]]]]].\n    subst.\n    eapply in_make_mapM_iff.\n    solve [repeat rewrite map_length; eauto].\n    exists i, a.\n    split.\n    solve [erewrite map_nth_error; eauto].\n    solve [erewrite map_nth_error; eauto; simpl; eauto].\n  Qed.\n\n  Definition no_aliasM (vs : Locals.vals) ks ins := no_dupM (List.map (fun x => vs x) ks) (only_adt ins).\n\n  Lemma find_Some_reachable_heap_iff vs ks : forall ins p a, length ks = length ins -> no_aliasM vs ks ins -> (find p (reachable_heap vs ks ins) = Some a <-> exists i k, nth_error ks i = Some k /\\ nth_error ins i = Some (ADT a) /\\ vs k = p).\n  Proof.\n    unfold reachable_heap, only_adt; intros ins p a Hl Hna.\n    split.\n    intros Hi.\n    eapply find_Some_make_mapM_iff in Hi; eauto.\n    destruct Hi as [i [Hk Hv]].\n    eapply nth_error_map_elim in Hk.\n    destruct Hk as [k [Hk Hvs]].\n    subst.\n    eapply nth_error_map_elim in Hv.\n    destruct Hv as [v [Hv Ha]].\n    destruct v as [w | a'].\n    discriminate.\n    inject Ha.\n    solve [exists i, k; eauto].\n    solve [repeat rewrite map_length; eauto].\n\n    intros Hex.\n    destruct Hex as [i [k [Hk [Hv Hvs]]]].\n    subst.\n    eapply find_Some_make_mapM_iff; eauto.\n    solve [repeat rewrite map_length; eauto].\n    exists i.\n    split.\n    solve [erewrite map_nth_error; eauto].\n    solve [erewrite map_nth_error; eauto; simpl; eauto].\n  Qed.\n\nEnd ADTValue.\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/SemanticsFacts8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947155710234, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2917749381282313}}
{"text": "(** * Facts about Expression Evaluation *)\n\nRequire Import common.CoqLib.\nRequire Import common.NatMap.\n\nRequire Import hvhdl.Environment.\nRequire Import hvhdl.ExpressionEvaluation.\nRequire Import hvhdl.AbstractSyntax.\nRequire Import hvhdl.SemanticalDomains.\nRequire Import hvhdl.HVhdlTypes.\n\nRequire Import hvhdl.proofs.EnvironmentFacts.\n\nLemma vexpr_eq_iff_eq_sigs :\n  forall {Δ1 σ1 Δ2 σ2 flag e v},\n    EqGens Δ1 Δ2 /\\ EqSigs Δ1 Δ2 ->\n    EqSStore σ1 σ2 ->\n    VExpr Δ1 σ1 EmptyLEnv flag e v <->\n    VExpr Δ2 σ2 EmptyLEnv flag e v.\nProof.\n  intros *; intros (EqGens_, EqSigs_) EqSStore_.\n  split; intro.\n  (* CASE A -> B *)\n  apply (VExpr_ind_mut\n           Δ1 σ1 EmptyLEnv\n           (fun b e v H => VExpr Δ2 σ2 EmptyLEnv b e v)\n           (fun b a arrofv H => VAgOfExprs Δ2 σ2 EmptyLEnv b a arrofv));\n    intros; eauto with hvhdl.\n  (* CASE VExprSig *)\n  econstructor; eauto.\n  inversion o; [ left; rewrite <- EqSigs_; eauto | right; rewrite <- EqSigs_; eauto].\n  pattern σ2; rewrite <- EqSStore_; auto.\n  (* CASE VExprOut *)\n  eapply VExprOut with (t := t0); eauto.\n  rewrite <- EqSigs_; auto.\n  pattern σ2; rewrite <- EqSStore_; auto.\n  (* CASE VExprVar *)\n  rewrite empty_mapsto_iff in m; contradiction.\n  (* CASE VExprGen *)\n  eapply VExprGen with (t := t0); eauto.\n  rewrite <- EqGens_; auto.\n  (* CASE VExprIdxOut *)\n  eapply VExprIdxOut with (t := t0); eauto.\n  rewrite <- EqSigs_; auto.\n  pattern σ2; rewrite <- EqSStore_; auto.\n  (* CASE VExprIdxSig *)\n  eapply VExprIdxSig with (t := t0); eauto.\n  inversion o; [ left; rewrite <- EqSigs_; auto | right; rewrite <- EqSigs_; auto].\n  pattern σ2; rewrite <- EqSStore_; auto.\n  (* CASE VExprVar *)\n  rewrite empty_mapsto_iff in m; contradiction.\n  (* CASE B -> A *)\n  apply (VExpr_ind_mut\n           Δ2 σ2 EmptyLEnv\n           (fun b e v H => VExpr Δ1 σ1 EmptyLEnv b e v)\n           (fun b a arrofv H => VAgOfExprs Δ1 σ1 EmptyLEnv b a arrofv));\n    intros; eauto with hvhdl.\n  (* CASE VExprSig *)\n  econstructor; eauto.\n  inversion o; [ left; rewrite EqSigs_; eauto | right; rewrite EqSigs_; eauto].\n  pattern σ1; rewrite EqSStore_; auto.\n  (* CASE VExprOut *)\n  eapply VExprOut with (t := t0); eauto.\n  rewrite EqSigs_; auto.\n  pattern σ1; rewrite EqSStore_; auto.\n  (* CASE VExprVar *)\n  rewrite empty_mapsto_iff in m; contradiction.\n  (* CASE VExprGen *)\n  eapply VExprGen with (t := t0); eauto.\n  rewrite EqGens_; auto.\n  (* CASE VExprIdxOut *)\n  eapply VExprIdxOut with (t := t0); eauto.\n  rewrite EqSigs_; auto.\n  pattern σ1; rewrite EqSStore_; auto.\n  (* CASE VExprIdxSig *)\n  eapply VExprIdxSig with (t := t0); eauto.\n  inversion o; [ left; rewrite EqSigs_; auto | right; rewrite EqSigs_; auto].\n  pattern σ1; rewrite EqSStore_; auto.\n  (* CASE VExprVar *)\n  rewrite empty_mapsto_iff in m; contradiction.\nQed.\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/ExpressionEvaluationFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.29177493812823124}}
{"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 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(** 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.\n\nSet Implicit Arguments.\n\n(** * Closures of transitions relations *)\n\nSection CLOSURES.\n\nVariable genv: Type.\nVariable state: Type.\n\n(** A one-step transition relation has the following signature.\n  It is parameterized by a global environment, which does not\n  change during the transition.  It relates the initial state\n  of the transition with its final state.  The [trace] parameter\n  captures the observable events possibly generated during the\n  transition. *)\n\nVariable step: genv -> state -> trace -> state -> Prop.\n\n(** No transitions: stuck state *)\n\nDefinition nostep (ge: genv) (s: state) : Prop :=\n  forall t s', ~(step ge s t s').\n\n(** Zero, one or several transitions.  Also known as Kleene closure,\n    or reflexive transitive closure. *)\n\nInductive star (ge: genv): state -> trace -> state -> Prop :=\n  | star_refl: forall s,\n      star ge s E0 s\n  | star_step: forall s1 t1 s2 t2 s3 t,\n      step ge s1 t1 s2 -> star ge s2 t2 s3 -> t = t1 ** t2 ->\n      star ge s1 t s3.\n\nLemma star_one:\n  forall ge s1 t s2, step ge s1 t s2 -> star ge s1 t s2.\nProof.\n  intros. eapply star_step; eauto. apply star_refl. traceEq.\nQed.\n\nLemma star_two:\n  forall ge s1 t1 s2 t2 s3 t,\n  step ge s1 t1 s2 -> step ge s2 t2 s3 -> t = t1 ** t2 ->\n  star ge s1 t s3.\nProof.\n  intros. eapply star_step; eauto. apply star_one; auto.\nQed.\n\nLemma star_three:\n  forall ge s1 t1 s2 t2 s3 t3 s4 t,\n  step ge s1 t1 s2 -> step ge s2 t2 s3 -> step ge s3 t3 s4 -> t = t1 ** t2 ** t3 ->\n  star ge s1 t s4.\nProof.\n  intros. eapply star_step; eauto. eapply star_two; eauto.\nQed.\n\nLemma star_four:\n  forall ge s1 t1 s2 t2 s3 t3 s4 t4 s5 t,\n  step ge s1 t1 s2 -> step ge s2 t2 s3 ->\n  step ge s3 t3 s4 -> step ge s4 t4 s5 -> t = t1 ** t2 ** t3 ** t4 ->\n  star ge s1 t s5.\nProof.\n  intros. eapply star_step; eauto. eapply star_three; eauto.\nQed.\n\nLemma star_trans:\n  forall ge s1 t1 s2, star ge s1 t1 s2 ->\n  forall t2 s3 t, star ge s2 t2 s3 -> t = t1 ** t2 -> star ge s1 t s3.\nProof.\n  induction 1; intros.\n  rewrite H0. simpl. auto.\n  eapply star_step; eauto. traceEq.\nQed.\n\nLemma star_left:\n  forall ge s1 t1 s2 t2 s3 t,\n  step ge s1 t1 s2 -> star ge s2 t2 s3 -> t = t1 ** t2 ->\n  star ge s1 t s3.\nProof star_step.\n\nLemma star_right:\n  forall ge s1 t1 s2 t2 s3 t,\n  star ge s1 t1 s2 -> step ge s2 t2 s3 -> t = t1 ** t2 ->\n  star ge s1 t s3.\nProof.\n  intros. eapply star_trans. eauto. apply star_one. eauto. auto.\nQed.\n\nLemma star_E0_ind:\n  forall ge (P: state -> state -> Prop),\n  (forall s, P s s) ->\n  (forall s1 s2 s3, step ge s1 E0 s2 -> P s2 s3 -> P s1 s3) ->\n  forall s1 s2, star ge s1 E0 s2 -> P s1 s2.\nProof.\n  intros ge P BASE REC.\n  assert (forall s1 t s2, star ge s1 t s2 -> t = E0 -> P s1 s2).\n    induction 1; intros; subst.\n    auto.\n    destruct (Eapp_E0_inv _ _ H2). subst. eauto.\n  eauto.\nQed.\n\n(** One or several transitions.  Also known as the transitive closure. *)\n\nInductive plus (ge: genv): state -> trace -> state -> Prop :=\n  | plus_left: forall s1 t1 s2 t2 s3 t,\n      step ge s1 t1 s2 -> star ge s2 t2 s3 -> t = t1 ** t2 ->\n      plus ge s1 t s3.\n\nLemma plus_one:\n  forall ge s1 t s2,\n  step ge s1 t s2 -> plus ge s1 t s2.\nProof.\n  intros. econstructor; eauto. apply star_refl. traceEq.\nQed.\n\nLemma plus_two:\n  forall ge s1 t1 s2 t2 s3 t,\n  step ge s1 t1 s2 -> step ge s2 t2 s3 -> t = t1 ** t2 ->\n  plus ge s1 t s3.\nProof.\n  intros. eapply plus_left; eauto. apply star_one; auto.\nQed.\n\nLemma plus_three:\n  forall ge s1 t1 s2 t2 s3 t3 s4 t,\n  step ge s1 t1 s2 -> step ge s2 t2 s3 -> step ge s3 t3 s4 -> t = t1 ** t2 ** t3 ->\n  plus ge s1 t s4.\nProof.\n  intros. eapply plus_left; eauto. eapply star_two; eauto.\nQed.\n\nLemma plus_four:\n  forall ge s1 t1 s2 t2 s3 t3 s4 t4 s5 t,\n  step ge s1 t1 s2 -> step ge s2 t2 s3 ->\n  step ge s3 t3 s4 -> step ge s4 t4 s5 -> t = t1 ** t2 ** t3 ** t4 ->\n  plus ge s1 t s5.\nProof.\n  intros. eapply plus_left; eauto. eapply star_three; eauto.\nQed.\n\nLemma plus_star:\n  forall ge s1 t s2, plus ge s1 t s2 -> star ge s1 t s2.\nProof.\n  intros. inversion H; subst.\n  eapply star_step; eauto.\nQed.\n\nLemma plus_right:\n  forall ge s1 t1 s2 t2 s3 t,\n  star ge s1 t1 s2 -> step ge s2 t2 s3 -> t = t1 ** t2 ->\n  plus ge s1 t s3.\nProof.\n  intros. inversion H; subst. simpl. apply plus_one. auto.\n  rewrite Eapp_assoc. eapply plus_left; eauto.\n  eapply star_right; eauto.\nQed.\n\nLemma plus_left':\n  forall ge s1 t1 s2 t2 s3 t,\n  step ge s1 t1 s2 -> plus ge s2 t2 s3 -> t = t1 ** t2 ->\n  plus ge s1 t s3.\nProof.\n  intros. eapply plus_left; eauto. apply plus_star; auto.\nQed.\n\nLemma plus_right':\n  forall ge s1 t1 s2 t2 s3 t,\n  plus ge s1 t1 s2 -> step ge s2 t2 s3 -> t = t1 ** t2 ->\n  plus ge s1 t s3.\nProof.\n  intros. eapply plus_right; eauto. apply plus_star; auto.\nQed.\n\nLemma plus_star_trans:\n  forall ge s1 t1 s2 t2 s3 t,\n  plus ge s1 t1 s2 -> star ge s2 t2 s3 -> t = t1 ** t2 -> plus ge s1 t s3.\nProof.\n  intros. inversion H; subst.\n  econstructor; eauto. eapply star_trans; eauto.\n  traceEq.\nQed.\n\nLemma star_plus_trans:\n  forall ge s1 t1 s2 t2 s3 t,\n  star ge s1 t1 s2 -> plus ge s2 t2 s3 -> t = t1 ** t2 -> plus ge s1 t s3.\nProof.\n  intros. inversion H; subst.\n  simpl; auto.\n  rewrite Eapp_assoc.\n  econstructor. eauto. eapply star_trans. eauto.\n  apply plus_star. eauto. eauto. auto.\nQed.\n\nLemma plus_trans:\n  forall ge s1 t1 s2 t2 s3 t,\n  plus ge s1 t1 s2 -> plus ge s2 t2 s3 -> t = t1 ** t2 -> plus ge s1 t s3.\nProof.\n  intros. eapply plus_star_trans. eauto. apply plus_star. eauto. auto.\nQed.\n\nLemma plus_inv:\n  forall ge s1 t s2,\n  plus ge s1 t s2 ->\n  step ge s1 t s2 \\/ exists s', exists t1, exists t2, step ge s1 t1 s' /\\ plus ge s' t2 s2 /\\ t = t1 ** t2.\nProof.\n  intros. inversion H; subst. inversion H1; subst.\n  left. rewrite E0_right. auto.\n  right. exists s3; exists t1; exists (t0 ** t3); split. auto.\n  split. econstructor; eauto. auto.\nQed.\n\nLemma star_inv:\n  forall ge s1 t s2,\n  star ge s1 t s2 ->\n  (s2 = s1 /\\ t = E0) \\/ plus ge s1 t s2.\nProof.\n  intros. inv H. left; auto. right; econstructor; eauto.\nQed.\n\nLemma plus_ind2:\n  forall ge (P: state -> trace -> state -> Prop),\n  (forall s1 t s2, step ge s1 t s2 -> P s1 t s2) ->\n  (forall s1 t1 s2 t2 s3 t,\n   step ge s1 t1 s2 -> plus ge s2 t2 s3 -> P s2 t2 s3 -> t = t1 ** t2 ->\n   P s1 t s3) ->\n  forall s1 t s2, plus ge s1 t s2 -> P s1 t s2.\nProof.\n  intros ge P BASE IND.\n  assert (forall s1 t s2, star ge s1 t s2 ->\n         forall s0 t0, step ge s0 t0 s1 ->\n         P s0 (t0 ** t) s2).\n  induction 1; intros.\n  rewrite E0_right. apply BASE; auto.\n  eapply IND. eauto. econstructor; eauto. subst t. eapply IHstar; eauto. auto.\n\n  intros. inv H0. eauto.\nQed.\n\nLemma plus_E0_ind:\n  forall ge (P: state -> state -> Prop),\n  (forall s1 s2 s3, step ge s1 E0 s2 -> star ge s2 E0 s3 -> P s1 s3) ->\n  forall s1 s2, plus ge s1 E0 s2 -> P s1 s2.\nProof.\n  intros. inv H0. exploit Eapp_E0_inv; eauto. intros [A B]; subst. eauto.\nQed.\n\n(** Counted sequences of transitions *)\n\nInductive starN (ge: genv): nat -> state -> trace -> state -> Prop :=\n  | starN_refl: forall s,\n      starN ge O s E0 s\n  | starN_step: forall n s t t1 s' t2 s'',\n      step ge s t1 s' -> starN ge n s' t2 s'' -> t = t1 ** t2 ->\n      starN ge (S n) s t s''.\n\nRemark starN_star:\n  forall ge n s t s', starN ge n s t s' -> star ge s t s'.\nProof.\n  induction 1; econstructor; eauto.\nQed.\n\nRemark star_starN:\n  forall ge s t s', star ge s t s' -> exists n, starN ge n s t s'.\nProof.\n  induction 1.\n  exists O; constructor.\n  destruct IHstar as [n P]. exists (S n); econstructor; eauto.\nQed.\n\n(** Infinitely many transitions *)\n\nCoInductive forever (ge: genv): state -> traceinf -> Prop :=\n  | forever_intro: forall s1 t s2 T,\n      step ge s1 t s2 -> forever ge s2 T ->\n      forever ge s1 (t *** T).\n\nLemma star_forever:\n  forall ge s1 t s2, star ge s1 t s2 ->\n  forall T, forever ge s2 T ->\n  forever ge s1 (t *** T).\nProof.\n  induction 1; intros. simpl. auto.\n  subst t. rewrite Eappinf_assoc.\n  econstructor; eauto.\nQed.\n\n(** An alternate, equivalent definition of [forever] that is useful\n    for coinductive reasoning. *)\n\nVariable A: Type.\nVariable order: A -> A -> Prop.\n\nCoInductive forever_N (ge: genv) : A -> state -> traceinf -> Prop :=\n  | forever_N_star: forall s1 t s2 a1 a2 T1 T2,\n      star ge s1 t s2 ->\n      order a2 a1 ->\n      forever_N ge a2 s2 T2 ->\n      T1 = t *** T2 ->\n      forever_N ge a1 s1 T1\n  | forever_N_plus: forall s1 t s2 a1 a2 T1 T2,\n      plus ge s1 t s2 ->\n      forever_N ge a2 s2 T2 ->\n      T1 = t *** T2 ->\n      forever_N ge a1 s1 T1.\n\nHypothesis order_wf: well_founded order.\n\nLemma forever_N_inv:\n  forall ge a s T,\n  forever_N ge a s T ->\n  exists t, exists s', exists a', exists T',\n  step ge s t s' /\\ forever_N ge a' s' T' /\\ T = t *** T'.\nProof.\n  intros ge a0. pattern a0. apply (well_founded_ind order_wf).\n  intros. inv H0.\n  (* star case *)\n  inv H1.\n  (* no transition *)\n  change (E0 *** T2) with T2. apply H with a2. auto. auto.\n  (* at least one transition *)\n  exists t1; exists s0; exists x; exists (t2 *** T2).\n  split. auto. split. eapply forever_N_star; eauto.\n  apply Eappinf_assoc.\n  (* plus case *)\n  inv H1.\n  exists t1; exists s0; exists a2; exists (t2 *** T2).\n  split. auto.\n  split. inv H3. auto.\n  eapply forever_N_plus. econstructor; eauto. eauto. auto.\n  apply Eappinf_assoc.\nQed.\n\nLemma forever_N_forever:\n  forall ge a s T, forever_N ge a s T -> forever ge s T.\nProof.\n  cofix COINDHYP; intros.\n  destruct (forever_N_inv H) as [t [s' [a' [T' [P [Q R]]]]]].\n  rewrite R. apply forever_intro with s'. auto.\n  apply COINDHYP with a'; auto.\nQed.\n\n(** Yet another alternative definition of [forever]. *)\n\nCoInductive forever_plus (ge: genv) : state -> traceinf -> Prop :=\n  | forever_plus_intro: forall s1 t s2 T1 T2,\n      plus ge s1 t s2 ->\n      forever_plus ge s2 T2 ->\n      T1 = t *** T2 ->\n      forever_plus ge s1 T1.\n\nLemma forever_plus_inv:\n  forall ge s T,\n  forever_plus ge s T ->\n  exists s', exists t, exists T',\n  step ge s t s' /\\ forever_plus ge s' T' /\\ T = t *** T'.\nProof.\n  intros. inv H. inv H0. exists s0; exists t1; exists (t2 *** T2).\n  split. auto.\n  split. exploit star_inv; eauto. intros [[P Q] | R].\n    subst. simpl. auto. econstructor; eauto.\n  traceEq.\nQed.\n\nLemma forever_plus_forever:\n  forall ge s T, forever_plus ge s T -> forever ge s T.\nProof.\n  cofix COINDHYP; intros.\n  destruct (forever_plus_inv H) as [s' [t [T' [P [Q R]]]]].\n  subst. econstructor; eauto.\nQed.\n\n(** Infinitely many silent transitions *)\n\nCoInductive forever_silent (ge: genv): state -> Prop :=\n  | forever_silent_intro: forall s1 s2,\n      step ge s1 E0 s2 -> forever_silent ge s2 ->\n      forever_silent ge s1.\n\n(** An alternate definition. *)\n\nCoInductive forever_silent_N (ge: genv) : A -> state -> Prop :=\n  | forever_silent_N_star: forall s1 s2 a1 a2,\n      star ge s1 E0 s2 ->\n      order a2 a1 ->\n      forever_silent_N ge a2 s2 ->\n      forever_silent_N ge a1 s1\n  | forever_silent_N_plus: forall s1 s2 a1 a2,\n      plus ge s1 E0 s2 ->\n      forever_silent_N ge a2 s2 ->\n      forever_silent_N ge a1 s1.\n\nLemma forever_silent_N_inv:\n  forall ge a s,\n  forever_silent_N ge a s ->\n  exists s', exists a',\n  step ge s E0 s' /\\ forever_silent_N ge a' s'.\nProof.\n  intros ge a0. pattern a0. apply (well_founded_ind order_wf).\n  intros. inv H0.\n  (* star case *)\n  inv H1.\n  (* no transition *)\n  apply H with a2. auto. auto.\n  (* at least one transition *)\n  exploit Eapp_E0_inv; eauto. intros [P Q]. subst.\n  exists s0; exists x.\n  split. auto. eapply forever_silent_N_star; eauto.\n  (* plus case *)\n  inv H1. exploit Eapp_E0_inv; eauto. intros [P Q]. subst.\n  exists s0; exists a2.\n  split. auto. inv H3. auto.\n  eapply forever_silent_N_plus. econstructor; eauto. eauto.\nQed.\n\nLemma forever_silent_N_forever:\n  forall ge a s, forever_silent_N ge a s -> forever_silent ge s.\nProof.\n  cofix COINDHYP; intros.\n  destruct (forever_silent_N_inv H) as [s' [a' [P Q]]].\n  apply forever_silent_intro with s'. auto.\n  apply COINDHYP with a'; auto.\nQed.\n\n(** Infinitely many non-silent transitions *)\n\nCoInductive forever_reactive (ge: genv): state -> traceinf -> Prop :=\n  | forever_reactive_intro: forall s1 s2 t T,\n      star ge s1 t s2 -> t <> E0 -> forever_reactive ge s2 T ->\n      forever_reactive ge s1 (t *** T).\n\nLemma star_forever_reactive:\n  forall ge s1 t s2 T,\n  star ge s1 t s2 -> forever_reactive ge s2 T ->\n  forever_reactive ge s1 (t *** T).\nProof.\n  intros. inv H0. rewrite <- Eappinf_assoc. econstructor.\n  eapply star_trans; eauto.\n  red; intro. exploit Eapp_E0_inv; eauto. intros [P Q]. contradiction.\n  auto.\nQed.\n\n(** [eventually n s P]: all transition sequences of length [n] starting from [s]\n    are silent and lead to a state satisfying [P].  However, some transitions can\n    get stuck on non-final states. *)\n\nVariable final_state: state -> int -> Prop.\n\nInductive eventually (ge: genv): nat -> state -> (state -> Prop) -> Prop :=\n  | eventually_now: forall s (P: state -> Prop),\n      P s ->\n      eventually ge O s P\n  | eventually_later: forall n s (P: state -> Prop),\n      (forall r, ~ final_state s r) ->\n      (forall t s', step ge s t s' -> t = E0 /\\ eventually ge n s' P) ->\n      eventually ge (S n) s P.\n\nLemma eventually_one: forall ge s (P: state -> Prop),\n  (forall r, ~ final_state s r) ->\n  (forall t s', step ge s t s' -> t = E0 /\\ P s') ->\n  eventually ge 1%nat s P.\nProof.\n  intros. apply eventually_later; auto. intros. apply H0 in H1. intuition auto using eventually.\nQed.\n\nLemma eventually_trans: forall ge n1 s1 P1 n2 P2,\n  eventually ge n1 s1 P1 -> \n  (forall s2, P1 s2 -> eventually ge n2 s2 P2) ->\n  eventually ge (n1 + n2)%nat s1 P2.\nProof.\n  intros. revert n1 s1 H. induction n1; intros s1 EV; inv EV; simpl.\n- apply H0; assumption.\n- apply eventually_later; auto. intros t s' ST. destruct (H2 t s' ST) as [U V]. auto.\nQed.\n\nCorollary eventually_implies: forall ge n s (P1 P2: state -> Prop),\n  eventually ge n s P1 ->\n  (forall s, P1 s -> P2 s) ->\n  eventually ge n s P2.\nProof.\n  intros. replace n with (n + 0)%nat by lia. eapply eventually_trans; eauto using eventually_now.\nQed.\n\nLemma eventually_and_invariant: forall ge (Inv: state -> Prop) n s P,\n  (forall s t s', step ge s t s' -> Inv s -> Inv s') ->\n  eventually ge n s P -> Inv s ->\n  eventually ge n s (fun s' => P s' /\\ Inv s').\nProof.\n  intros. revert n s H0 H1. induction n; intros s EV IV; inv EV.\n- apply eventually_now. auto.\n- apply eventually_later; auto. intros. edestruct H2; eauto. \nQed.\n\nEnd CLOSURES.\n\n(** * Transition semantics *)\n\n(** The general form of a transition semantics. *)\n\nRecord semantics : Type := Semantics_gen {\n  state: Type;\n  genvtype: Type;\n  step : genvtype -> state -> trace -> state -> Prop;\n  initial_state: state -> Prop;\n  final_state: state -> int -> Prop;\n  globalenv: genvtype;\n  symbolenv: Senv.t\n}.\n\n(** The form used in earlier CompCert versions, for backward compatibility. *)\n\nDefinition Semantics {state funtype vartype: Type}\n                     (step: Genv.t funtype vartype -> state -> trace -> state -> Prop)\n                     (initial_state: state -> Prop)\n                     (final_state: state -> int -> Prop)\n                     (globalenv: Genv.t funtype vartype) :=\n  {| state := state;\n     genvtype := Genv.t funtype vartype;\n     step := step;\n     initial_state := initial_state;\n     final_state := final_state;\n     globalenv := globalenv;\n     symbolenv := Genv.to_senv globalenv |}.\n\n(** Handy notations. *)\n\nDeclare Scope smallstep_scope.\n\nNotation \" 'Step' L \" := (step L (globalenv L)) (at level 1) : smallstep_scope.\nNotation \" 'Star' L \" := (star (step L) (globalenv L)) (at level 1) : smallstep_scope.\nNotation \" 'Plus' L \" := (plus (step L) (globalenv L)) (at level 1) : smallstep_scope.\nNotation \" 'Forever_silent' L \" := (forever_silent (step L) (globalenv L)) (at level 1) : smallstep_scope.\nNotation \" 'Forever_reactive' L \" := (forever_reactive (step L) (globalenv L)) (at level 1) : smallstep_scope.\nNotation \" 'Nostep' L \" := (nostep (step L) (globalenv L)) (at level 1) : smallstep_scope.\nNotation \" 'Eventually' L \" := (eventually (step L) (final_state L) (globalenv L)) (at level 1) : smallstep_scope.\nOpen Scope smallstep_scope.\n\n(** * Forward simulations between two transition semantics. *)\n\n(** The general form of a forward simulation. *)\n\nRecord fsim_properties (L1 L2: semantics) (index: Type)\n                       (order: index -> index -> Prop)\n                       (match_states: index -> state L1 -> state L2 -> Prop) : Prop := {\n    fsim_order_wf: well_founded order;\n    fsim_match_initial_states:\n      forall s1, initial_state L1 s1 ->\n      exists i, exists s2, initial_state L2 s2 /\\ match_states i s1 s2;\n    fsim_match_final_states:\n      forall i s1 s2 r,\n      match_states i s1 s2 -> final_state L1 s1 r -> final_state L2 s2 r;\n    fsim_simulation:\n      forall s1 t s1', Step L1 s1 t s1' ->\n      forall i s2, match_states i s1 s2 ->\n      exists i', exists s2',\n         (Plus L2 s2 t s2' \\/ (Star L2 s2 t s2' /\\ order i' i))\n      /\\ match_states i' s1' s2';\n    fsim_public_preserved:\n      forall id, Senv.public_symbol (symbolenv L2) id = Senv.public_symbol (symbolenv L1) id\n  }.\n\nArguments fsim_properties: clear implicits.\n\nInductive forward_simulation (L1 L2: semantics) : Prop :=\n  Forward_simulation (index: Type)\n                     (order: index -> index -> Prop)\n                     (match_states: index -> state L1 -> state L2 -> Prop)\n                     (props: fsim_properties L1 L2 index order match_states).\n\nArguments Forward_simulation {L1 L2 index} order match_states props.\n\n(** An alternate form of the simulation diagram *)\n\nLemma fsim_simulation':\n  forall L1 L2 index order match_states, fsim_properties L1 L2 index order match_states ->\n  forall i s1 t s1', Step L1 s1 t s1' ->\n  forall s2, match_states i s1 s2 ->\n  (exists i', exists s2', Plus L2 s2 t s2' /\\ match_states i' s1' s2')\n  \\/ (exists i', order i' i /\\ t = E0 /\\ match_states i' s1' s2).\nProof.\n  intros. exploit fsim_simulation; eauto.\n  intros [i' [s2' [A B]]]. intuition.\n  left; exists i'; exists s2'; auto.\n  inv H3.\n  right; exists i'; auto.\n  left; exists i'; exists s2'; split; auto. econstructor; eauto.\nQed.\n\n(** ** Forward simulation diagrams. *)\n\n(** Various simulation diagrams that imply forward simulation *)\n\nSection FORWARD_SIMU_DIAGRAMS.\n\nVariable L1: semantics.\nVariable L2: semantics.\n\nHypothesis 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.\n\nHypothesis match_initial_states:\n  forall s1, initial_state L1 s1 ->\n  exists s2, initial_state L2 s2 /\\ match_states s1 s2.\n\nHypothesis match_final_states:\n  forall s1 s2 r,\n  match_states s1 s2 ->\n  final_state L1 s1 r ->\n  final_state L2 s2 r.\n\n(** Simulation when one transition in the first program\n    corresponds to zero, one or several 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_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\nLemma forward_simulation_star_wf: forward_simulation L1 L2.\nProof.\n  apply Forward_simulation with order (fun idx s1 s2 => idx = s1 /\\ match_states s1 s2);\n  constructor.\n- auto.\n- intros. exploit match_initial_states; eauto. intros [s2 [A B]].\n    exists s1; exists s2; auto.\n- intros. destruct H. eapply match_final_states; eauto.\n- intros. destruct H0. subst i. exploit simulation; eauto. intros [s2' [A B]].\n  exists s1'; exists s2'; intuition auto.\n- auto.\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  apply forward_simulation_star_wf with (ltof _ measure).\n  apply well_founded_ltof.\n  intros. exploit simulation; eauto. intros [[s2' [A B]] | [A [B C]]].\n  exists s2'; auto.\n  exists s2; split. right; split. rewrite B. apply star_refl. auto. auto.\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  apply forward_simulation_star with (measure := fun _ => O).\n  intros. exploit simulation; eauto.\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  apply forward_simulation_plus.\n  intros. exploit simulation; eauto. intros [s2' [A B]].\n  exists s2'; split; auto. apply plus_one; auto.\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  apply forward_simulation_star with measure.\n  intros. exploit simulation; eauto. intros [[s2' [A B]] | [A [B C]]].\n  left; exists s2'; split; auto. apply plus_one; auto.\n  right; auto.\nQed.\n\nEnd SIMULATION_OPT.\n\nEnd FORWARD_SIMU_DIAGRAMS.\n\n(** ** Forward simulation with the \"eventually\" modality *)\n\n(** A forward simulation diagram where the first semantics can take some extra steps\n    before reaching a state that restores the simulation relation. *)\n\nSection FORWARD_SIMU_EVENTUALLY.\n\nVariable L1: semantics.\nVariable L2: semantics.\nVariable index: Type.\nVariable order: index -> index -> Prop.\nVariable match_states: index -> state L1 -> state L2 -> Prop.\n\nHypothesis order_wf: well_founded order.\nHypothesis initial_states:\n  forall s1, initial_state L1 s1 ->\n  exists i, exists s2, initial_state L2 s2 /\\ match_states i s1 s2.\nHypothesis final_states:\n  forall i s1 s2 r,\n  match_states i s1 s2 -> final_state L1 s1 r -> final_state L2 s2 r.\nHypothesis simulation:\n  forall s1 t s1', Step L1 s1 t s1' ->\n  forall i s2, match_states i s1 s2 ->\n  exists n i' s2',\n     (Plus L2 s2 t s2' \\/ (Star L2 s2 t s2' /\\ order i' i))\n  /\\ Eventually L1 n s1' (fun s1'' => match_states i' s1'' s2').\nHypothesis public_preserved:\n  forall id, Senv.public_symbol (symbolenv L2) id = Senv.public_symbol (symbolenv L1) id.\n\nLemma forward_simulation_eventually: forward_simulation L1 L2.\nProof.\n  apply @Forward_simulation with\n    (index := (index * nat)%type)\n    (order := lex_ord order Nat.lt)\n    (match_states := fun i s1 s2 => Eventually L1 (snd i) s1 (fun s1'' => match_states (fst i) s1'' s2)).\n  constructor.\n- apply wf_lex_ord; auto using lt_wf.\n- intros. exploit initial_states; eauto. intros (i & s2 & A & B).\n  exists (i, O), s2; auto using eventually_now.\n- intros [i n] s1 s2 r EV FS; simpl in *. inv EV.\n  + eapply final_states; eauto.\n  + eelim H; eauto.\n- intros s1 t s1' ST [i n] s2 EV; simpl in *. inv EV.\n  + exploit simulation; eauto. intros (n & i' & s2' & A & B).\n    exists (i', n), s2'; split; auto.\n    destruct A as [P | [P Q]]; auto using lex_ord_left.\n  + apply H0 in ST. destruct ST as (A & B). subst t.\n    exists (i, n0), s2; split.\n    right; split. apply star_refl. apply lex_ord_right; lia.\n    exact B.\n- apply public_preserved.\nQed.\n\nEnd FORWARD_SIMU_EVENTUALLY.\n\n(** Two simplified diagrams. *)\n\nSection FORWARD_SIMU_EVENTUALLY_SIMPL.\n\nVariable L1: semantics.\nVariable L2: semantics.\nVariable match_states: state L1 -> state L2 -> Prop.\n\nHypothesis public_preserved:\n  forall id, Senv.public_symbol (symbolenv L2) id = Senv.public_symbol (symbolenv L1) id.\nHypothesis initial_states:\n  forall s1, initial_state L1 s1 ->\n  exists s2, initial_state L2 s2 /\\ match_states s1 s2.\nHypothesis final_states:\n  forall s1 s2 r,\n  match_states s1 s2 -> final_state L1 s1 r -> final_state L2 s2 r.\n\n(** Simplified \"plus\" simulation diagram, when L2 always makes at least one transition. *)\n\nSection FORWARD_SIMU_EVENTUALLY_PLUS.\n\nHypothesis simulation:\n  forall s1 t s1', Step L1 s1 t s1' ->\n  forall s2, match_states s1 s2 ->\n  exists n s2',\n     Plus L2 s2 t s2'\n  /\\ Eventually L1 n s1' (fun s1'' => match_states s1'' s2').\n\nLemma forward_simulation_eventually_plus: forward_simulation L1 L2.\nProof.\n  apply forward_simulation_eventually with (order := lt) (match_states := fun i s1 s2 => match_states s1 s2).\n- apply lt_wf.\n- intros. exploit initial_states; eauto. intros (s2 & A & B). exists O, s2; auto.\n- intros. eapply final_states; eauto.\n- intros. exploit simulation; eauto. intros (n & s2' & A & B).\n  exists n, O, s2'; auto.\n- auto.\nQed.\n\nEnd FORWARD_SIMU_EVENTUALLY_PLUS.\n\n(** Simplified \"star\" simulation diagram, with a decreasing, well-founded order on L1 states. *)\n\nSection FORWARD_SIMU_EVENTUALLY_STAR_WF.\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)) /\\ match_states s1' s2')\n  \\/ (exists n s2',\n        Plus L2 s2 t s2' /\\ Eventually L1 n s1' (fun s1'' => match_states s1'' s2')).\n\nLemma forward_simulation_eventually_star_wf: forward_simulation L1 L2.\nProof.\n  apply @Forward_simulation with\n    (index := (nat * state L1)%type)\n    (order := lex_ord Nat.lt order)\n    (match_states := fun i s1 s2 => snd i = s1 /\\ Eventually L1 (fst i) s1 (fun s1'' => match_states s1'' s2)).\n  constructor; intros.\n- apply wf_lex_ord; auto using lt_wf.\n- exploit initial_states; eauto. intros (s2 & A & B).\n  exists (O, s1), s2; auto using eventually_now.\n- destruct i as [n s11]; destruct H as [P Q]; simpl in *; subst s11.\n  inv Q.\n  + eapply final_states; eauto.\n  + eelim H; eauto.\n- destruct i as [n s11]; destruct H0 as [P Q]; simpl in *; subst s11.\n  inv Q.\n  + exploit simulation; eauto. intros [(s2' & A & B) | (n & s2' & A & B)].\n    * exists (O, s1'), s2'; split. \n      destruct A as [A | [A1 A2]]; auto using lex_ord_right.\n      auto using eventually_now.\n    * exists (n, s1'), s2'; auto.\n  + apply H1 in H. destruct H. subst t.\n    exists (n0, s1'), s2; split.\n    right; split. apply star_refl. apply lex_ord_left; lia.\n    auto.\n- auto.\nQed.\n\nEnd FORWARD_SIMU_EVENTUALLY_STAR_WF.\n\n(** Simplified \"star\" simulation diagram, with a decreasing measure on L1 states. *)\n\nSection FORWARD_SIMU_EVENTUALLY_STAR.\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',\n        (Plus L2 s2 t s2' \\/ (Star L2 s2 t s2' /\\ measure s1' < measure s1))%nat\n        /\\ match_states s1' s2')\n  \\/ (exists n s2',\n        Plus L2 s2 t s2' /\\ Eventually L1 n s1' (fun s1'' => match_states s1'' s2')).\n\nLemma forward_simulation_eventually_star: forward_simulation L1 L2.\nProof.\n  apply forward_simulation_eventually_star_wf with (ltof _ measure).\n- apply well_founded_ltof.\n- exact simulation.\nQed.\n\nEnd FORWARD_SIMU_EVENTUALLY_STAR.\n\nEnd FORWARD_SIMU_EVENTUALLY_SIMPL.\n\n(** ** Forward simulation of transition sequences *)\n\nSection SIMULATION_SEQUENCES.\n\nContext L1 L2 index order match_states (S: fsim_properties L1 L2 index order match_states).\n\nLemma simulation_star:\n  forall s1 t s1', Star L1 s1 t s1' ->\n  forall i s2, match_states i s1 s2 ->\n  exists i', exists s2', Star L2 s2 t s2' /\\ match_states i' s1' s2'.\nProof.\n  induction 1; intros.\n  exists i; exists s2; split; auto. apply star_refl.\n  exploit fsim_simulation; eauto. intros [i' [s2' [A B]]].\n  exploit IHstar; eauto. intros [i'' [s2'' [C D]]].\n  exists i''; exists s2''; split; auto. eapply star_trans; eauto.\n  intuition auto. apply plus_star; auto.\nQed.\n\nLemma simulation_plus:\n  forall s1 t s1', Plus L1 s1 t s1' ->\n  forall i s2, match_states i s1 s2 ->\n  (exists i', exists s2', Plus L2 s2 t s2' /\\ match_states i' s1' s2')\n  \\/ (exists i', clos_trans _ order i' i /\\ t = E0 /\\ match_states i' s1' s2).\nProof.\n  induction 1 using plus_ind2; intros.\n(* base case *)\n  exploit fsim_simulation'; eauto. intros [A | [i' A]].\n  left; auto.\n  right; exists i'; intuition.\n(* inductive case *)\n  exploit fsim_simulation'; eauto. intros [[i' [s2' [A B]]] | [i' [A [B C]]]].\n  exploit simulation_star. 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  exploit IHplus; eauto. intros [[i'' [s2'' [P Q]]] | [i'' [P [Q R]]]].\n  subst. simpl. left; exists i''; exists s2''; auto.\n  subst. simpl. right; exists i''; intuition auto.\n  eapply t_trans; eauto. eapply t_step; eauto.\nQed.\n\nLemma simulation_forever_silent:\n  forall i s1 s2,\n  Forever_silent L1 s1 -> match_states i s1 s2 ->\n  Forever_silent L2 s2.\nProof.\n  assert (forall i s1 s2,\n          Forever_silent L1 s1 -> match_states i s1 s2 ->\n          forever_silent_N (step L2) order (globalenv L2) i s2).\n    cofix COINDHYP; intros.\n    inv H. destruct (fsim_simulation S _ _ _ H1 _ _ H0) as [i' [s2' [A B]]].\n    destruct A as [C | [C D]].\n    eapply forever_silent_N_plus; eauto.\n    eapply forever_silent_N_star; eauto.\n  intros. eapply forever_silent_N_forever; eauto. eapply fsim_order_wf; eauto.\nQed.\n\nLemma simulation_forever_reactive:\n  forall i s1 s2 T,\n  Forever_reactive L1 s1 T -> match_states i s1 s2 ->\n  Forever_reactive L2 s2 T.\nProof.\n  cofix COINDHYP; intros.\n  inv H.\n  edestruct simulation_star as [i' [st2' [A B]]]; eauto.\n  econstructor; eauto.\nQed.\n\nEnd SIMULATION_SEQUENCES.\n\n(** ** Composing two forward simulations *)\n\nLemma compose_forward_simulations:\n  forall L1 L2 L3, forward_simulation L1 L2 -> forward_simulation L2 L3 -> forward_simulation L1 L3.\nProof.\n  intros L1 L2 L3 S12 S23.\n  destruct S12 as [index order match_states props].\n  destruct S23 as [index' order' match_states' props'].\n\n  set (ff_index := (index' * index)%type).\n  set (ff_order := lex_ord (clos_trans _ order') order).\n  set (ff_match_states := fun (i: ff_index) (s1: state L1) (s3: state L3) =>\n                             exists s2, match_states (snd i) s1 s2 /\\ match_states' (fst i) s2 s3).\n  apply Forward_simulation with ff_order ff_match_states; constructor.\n- (* well founded *)\n  unfold ff_order. apply wf_lex_ord. apply wf_clos_trans.\n  eapply fsim_order_wf; eauto. eapply fsim_order_wf; eauto.\n- (* initial states *)\n  intros. exploit (fsim_match_initial_states props); eauto. intros [i [s2 [A B]]].\n  exploit (fsim_match_initial_states props'); eauto. intros [i' [s3 [C D]]].\n  exists (i', i); exists s3; split; auto. exists s2; auto.\n- (* final states *)\n  intros. destruct H as [s3 [A B]].\n  eapply (fsim_match_final_states props'); eauto.\n  eapply (fsim_match_final_states props); eauto.\n- (* simulation *)\n  intros. destruct H0 as [s3 [A B]]. destruct i as [i2 i1]; simpl in *.\n  exploit (fsim_simulation' props); eauto. intros [[i1' [s3' [C D]]] | [i1' [C [D E]]]].\n+ (* L2 makes one or several steps. *)\n  exploit simulation_plus; eauto. intros [[i2' [s2' [P Q]]] | [i2' [P [Q R]]]].\n* (* L3 makes one or several steps *)\n  exists (i2', i1'); exists s2'; split. auto. exists s3'; auto.\n* (* L3 makes no step *)\n  exists (i2', i1'); exists s2; split.\n  right; split. subst t; apply star_refl. red. left. auto.\n  exists s3'; auto.\n+ (* L2 makes no step *)\n  exists (i2, i1'); exists s2; split.\n  right; split. subst t; apply star_refl. red. right. auto.\n  exists s3; auto.\n- (* symbols *)\n  intros. transitivity (Senv.public_symbol (symbolenv L2) id); eapply fsim_public_preserved; eauto.\nQed.\n\n(** * Receptiveness and determinacy *)\n\nDefinition single_events (L: semantics) : Prop :=\n  forall s t s', Step L s t s' -> (length t <= 1)%nat.\n\nRecord receptive (L: semantics) : Prop :=\n  Receptive {\n    sr_receptive: forall s t1 s1 t2,\n      Step L s t1 s1 -> match_traces (symbolenv L) t1 t2 -> exists s2, Step L s t2 s2;\n    sr_traces:\n      single_events L\n  }.\n\nRecord determinate (L: semantics) : Prop :=\n  Determinate {\n    sd_determ: forall s t1 s1 t2 s2,\n      Step L s t1 s1 -> Step L s t2 s2 ->\n      match_traces (symbolenv L) t1 t2 /\\ (t1 = t2 -> s1 = s2);\n    sd_traces:\n      single_events L;\n    sd_initial_determ: forall s1 s2,\n      initial_state L s1 -> initial_state L s2 -> s1 = s2;\n    sd_final_nostep: forall s r,\n      final_state L s r -> Nostep L s;\n    sd_final_determ: forall s r1 r2,\n      final_state L s r1 -> final_state L s r2 -> r1 = r2\n  }.\n\nSection DETERMINACY.\n\nVariable L: semantics.\nHypothesis DET: determinate L.\n\nLemma sd_determ_1:\n  forall s t1 s1 t2 s2,\n  Step L s t1 s1 -> Step L s t2 s2 -> match_traces (symbolenv L) t1 t2.\nProof.\n  intros. eapply sd_determ; eauto.\nQed.\n\nLemma sd_determ_2:\n  forall s t s1 s2,\n  Step L s t s1 -> Step L s t s2 -> s1 = s2.\nProof.\n  intros. eapply sd_determ; eauto.\nQed.\n\nLemma sd_determ_3:\n  forall s t s1 s2,\n  Step L s t s1 -> Step L s E0 s2 -> t = E0 /\\ s1 = s2.\nProof.\n  intros. exploit (sd_determ DET). eexact H. eexact H0.\n  intros [A B]. inv A. auto.\nQed.\n\nLemma star_determinacy:\n  forall s t s', Star L s t s' ->\n  forall s'', Star L s t s'' -> Star L s' E0 s'' \\/ Star L s'' E0 s'.\nProof.\n  induction 1; intros.\n  auto.\n  inv H2.\n  right. eapply star_step; eauto.\n  exploit sd_determ_1. eexact H. eexact H3. intros MT.\n  exploit (sd_traces DET). eexact H. intros L1.\n  exploit (sd_traces DET). eexact H3. intros L2.\n  assert (t1 = t0 /\\ t2 = t3).\n    destruct t1. inv MT. auto.\n    destruct t1; simpl in L1; try extlia.\n    destruct t0. inv MT. destruct t0; simpl in L2; try extlia.\n    simpl in H5. split. congruence. congruence.\n  destruct H1; subst.\n  assert (s2 = s4) by (eapply sd_determ_2; eauto). subst s4.\n  auto.\nQed.\n\nEnd DETERMINACY.\n\n(** Extra simulation diagrams for determinate languages. *)\n\nSection FORWARD_SIMU_DETERM.\n\nVariable L1: semantics.\nVariable L2: semantics.\n\nHypothesis L1det: determinate L1.\n\nVariable index: Type.\nVariable order: index -> index -> Prop.\nHypothesis wf_order: well_founded order.\n\nVariable match_states: index -> state L1 -> state L2 -> Prop.\n\nHypothesis match_initial_states:\n  forall s1, initial_state L1 s1 ->\n  exists i s2, initial_state L2 s2 /\\ match_states i s1 s2.\n\nHypothesis match_final_states:\n  forall i s1 s2 r,\n  match_states i s1 s2 ->\n  final_state L1 s1 r ->\n  final_state L2 s2 r.\n\nHypothesis simulation:\n  forall s1 t s1', Step L1 s1 t s1' ->\n  forall i s2, match_states i s1 s2 ->\n  exists s1'' i' s2',\n      Star L1 s1' E0 s1''\n   /\\ (Plus L2 s2 t s2' \\/ (Star L2 s2 t s2' /\\ order i' i))\n   /\\ match_states i' s1'' s2'.\n\nHypothesis public_preserved:\n  forall id, Senv.public_symbol (symbolenv L2) id = Senv.public_symbol (symbolenv L1) id.\n\nLemma star_match_eventually:\n  forall s1 s1', Star L1 s1 E0 s1' ->\n  forall i s2, match_states i s1' s2 ->\n  exists n, Eventually L1 n s1 (fun s1'' => match_states i s1'' s2).\nProof.\n  intros s10 s10' STAR0. pattern s10, s10'; eapply star_E0_ind; eauto.\n  - intros s1 i s2 M. exists O; constructor; auto.\n  - intros s1 s1' s1'' STEP IH i s2 M.\n    destruct (IH i s2 M) as (n & MS).\n    exists (S n); constructor.\n    + intros; red; intros. eapply (sd_final_nostep L1det); eauto.\n    + intros. exploit (sd_determ_3 L1det). eexact H. eexact STEP. intros [A B].\n      subst t s'. auto.\nQed.\n\nLemma forward_simulation_determ: forward_simulation L1 L2.\nProof.\n  apply forward_simulation_eventually with (order := order) (match_states := match_states); auto.\n  intros. exploit simulation; eauto. intros (s1'' & i' & s2' & A & B & C).\n  exploit star_match_eventually; eauto. intros (n & D).\n  exists n, i', s2'; auto.\nQed.\n\nEnd FORWARD_SIMU_DETERM.\n\n(** A few useful special cases. *)\n\nSection FORWARD_SIMU_DETERM_DIAGRAMS.\n\nVariable L1: semantics.\nVariable L2: semantics.\n\nHypothesis L1det: determinate L1.\n\nVariable match_states: state L1 -> state L2 -> Prop.\n\nHypothesis public_preserved:\n  forall id, Senv.public_symbol (symbolenv L2) id = Senv.public_symbol (symbolenv L1) id.\n\nHypothesis match_initial_states:\n  forall s1, initial_state L1 s1 ->\n  exists s2, initial_state L2 s2 /\\ match_states s1 s2.\n\nHypothesis match_final_states:\n  forall s1 s2 r,\n  match_states s1 s2 ->\n  final_state L1 s1 r ->\n  final_state L2 s2 r.\n\nSection SIMU_DETERM_STAR.\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 s1'' s2',\n      Star L1 s1' E0 s1''\n   /\\ (Plus L2 s2 t s2' \\/ (Star L2 s2 t s2' /\\ measure s1'' < measure s1))%nat\n   /\\ match_states s1'' s2'.\n\nLemma forward_simulation_determ_star: forward_simulation L1 L2.\nProof.\n  apply forward_simulation_determ with\n    (match_states := fun i s1 s2 => i = s1 /\\ match_states s1 s2)\n    (order := ltof _ measure).\n- assumption.\n- apply well_founded_ltof.\n- intros. exploit match_initial_states; eauto. intros (s2 & A & B). \n  exists s1, s2; auto.\n- intros. destruct H. eapply match_final_states; eauto.\n- intros. destruct H0; subst i. \n  exploit simulation; eauto. intros (s1'' & s2' & A & B & C).\n  exists s1'', s1'', s2'. auto.\n- assumption.\nQed.\n\nEnd SIMU_DETERM_STAR.\n\nSection SIMU_DETERM_PLUS.\n\nHypothesis simulation:\n  forall s1 t s1', Step L1 s1 t s1' ->\n  forall s2, match_states s1 s2 ->\n  exists s1'' s2', Star L1 s1' E0 s1'' /\\ Plus L2 s2 t s2' /\\ match_states s1'' s2'.\n\nLemma forward_simulation_determ_plus: forward_simulation L1 L2.\nProof.\n  apply forward_simulation_determ_star with (measure := fun _ => O).\n  intros. exploit simulation; eauto. intros (s1'' & s2' & A & B & C).\n  exists s1'', s2'; auto.\nQed.\n\nEnd SIMU_DETERM_PLUS.\n\nSection SIMU_DETERM_ONE.\n\nHypothesis simulation:\n  forall s1 t s1', Step L1 s1 t s1' ->\n  forall s2, match_states s1 s2 ->\n  exists s1'' s2', Star L1 s1' E0 s1'' /\\ Step L2 s2 t s2' /\\ match_states s1'' s2'.\n\nLemma forward_simulation_determ_one: forward_simulation L1 L2.\nProof.\n  apply forward_simulation_determ_plus.\n  intros. exploit simulation; eauto. intros (s1'' & s2' & A & B & C).\n  exists s1'', s2'; auto using plus_one.\nQed.\n\nEnd SIMU_DETERM_ONE.\n\nEnd FORWARD_SIMU_DETERM_DIAGRAMS.\n\n(** * Backward simulations between two transition semantics. *)\n\nDefinition safe (L: semantics) (s: state L) : Prop :=\n  forall s',\n  Star L s E0 s' ->\n  (exists r, final_state L s' r)\n  \\/ (exists t, exists s'', Step L s' t s'').\n\nLemma star_safe:\n  forall (L: semantics) s s',\n  Star L s E0 s' -> safe L s -> safe L s'.\nProof.\n  intros; red; intros. apply H0. eapply star_trans; eauto.\nQed.\n\n(** The general form of a backward simulation. *)\n\nRecord bsim_properties (L1 L2: semantics) (index: Type)\n                       (order: index -> index -> Prop)\n                       (match_states: index -> state L1 -> state L2 -> Prop) : Prop := {\n    bsim_order_wf: well_founded order;\n    bsim_initial_states_exist:\n      forall s1, initial_state L1 s1 -> exists s2, initial_state L2 s2;\n    bsim_match_initial_states:\n      forall s1 s2, initial_state L1 s1 -> initial_state L2 s2 ->\n      exists i, exists s1', initial_state L1 s1' /\\ match_states i s1' s2;\n    bsim_match_final_states:\n      forall i s1 s2 r,\n      match_states i s1 s2 -> safe L1 s1 -> final_state L2 s2 r ->\n      exists s1', Star L1 s1 E0 s1' /\\ final_state L1 s1' r;\n    bsim_progress:\n      forall i s1 s2,\n      match_states i s1 s2 -> safe L1 s1 ->\n      (exists r, final_state L2 s2 r) \\/\n      (exists t, exists s2', Step L2 s2 t s2');\n    bsim_simulation:\n      forall s2 t s2', Step L2 s2 t s2' ->\n      forall i s1, match_states i s1 s2 -> safe L1 s1 ->\n      exists i', exists s1',\n         (Plus L1 s1 t s1' \\/ (Star L1 s1 t s1' /\\ order i' i))\n      /\\ match_states i' s1' s2';\n    bsim_public_preserved:\n      forall id, Senv.public_symbol (symbolenv L2) id = Senv.public_symbol (symbolenv L1) id\n  }.\n\nArguments bsim_properties: clear implicits.\n\nInductive backward_simulation (L1 L2: semantics) : Prop :=\n  Backward_simulation (index: Type)\n                      (order: index -> index -> Prop)\n                      (match_states: index -> state L1 -> state L2 -> Prop)\n                      (props: bsim_properties L1 L2 index order match_states).\n\nArguments Backward_simulation {L1 L2 index} order match_states props.\n\n(** An alternate form of the simulation diagram *)\n\nLemma bsim_simulation':\n  forall L1 L2 index order match_states, bsim_properties L1 L2 index order match_states ->\n  forall i s2 t s2', Step L2 s2 t s2' ->\n  forall s1, match_states i s1 s2 -> safe L1 s1 ->\n  (exists i', exists s1', Plus L1 s1 t s1' /\\ match_states i' s1' s2')\n  \\/ (exists i', order i' i /\\ t = E0 /\\ match_states i' s1 s2').\nProof.\n  intros. exploit bsim_simulation; eauto.\n  intros [i' [s1' [A B]]]. intuition.\n  left; exists i'; exists s1'; auto.\n  inv H4.\n  right; exists i'; auto.\n  left; exists i'; exists s1'; split; auto. econstructor; eauto.\nQed.\n\n(** ** Backward simulation diagrams. *)\n\n(** Various simulation diagrams that imply backward simulation. *)\n\nSection BACKWARD_SIMU_DIAGRAMS.\n\nVariable L1: semantics.\nVariable L2: semantics.\n\nHypothesis 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.\n\nHypothesis initial_states_exist:\n  forall s1, initial_state L1 s1 -> exists s2, initial_state L2 s2.\n\nHypothesis match_initial_states:\n  forall s1 s2, initial_state L1 s1 -> initial_state L2 s2 ->\n  exists s1', initial_state L1 s1' /\\ match_states s1' s2.\n\nHypothesis match_final_states:\n  forall s1 s2 r,\n  match_states s1 s2 -> final_state L2 s2 r -> final_state L1 s1 r.\n\nHypothesis progress:\n  forall s1 s2,\n  match_states s1 s2 -> safe L1 s1 ->\n  (exists r, final_state L2 s2 r) \\/\n  (exists t, exists s2', Step L2 s2 t s2').\n\nSection BACKWARD_SIMULATION_PLUS.\n\nHypothesis simulation:\n  forall s2 t s2', Step L2 s2 t s2' ->\n  forall s1, match_states s1 s2 -> safe L1 s1 ->\n  exists s1', Plus L1 s1 t s1' /\\ match_states s1' s2'.\n\nLemma backward_simulation_plus: backward_simulation L1 L2.\nProof.\n  apply Backward_simulation with\n    (fun (x y: unit) => False)\n    (fun (i: unit) s1 s2 => match_states s1 s2);\n  constructor; auto.\n- red; intros; constructor; intros. contradiction.\n- intros. exists tt; eauto.\n- intros. exists s1; split. apply star_refl. eauto.\n- intros. exploit simulation; eauto. intros [s1' [A B]].\n  exists tt; exists s1'; auto.\nQed.\n\nEnd BACKWARD_SIMULATION_PLUS.\n\nEnd BACKWARD_SIMU_DIAGRAMS.\n\n(** ** Backward simulation of transition sequences *)\n\nSection BACKWARD_SIMULATION_SEQUENCES.\n\nContext L1 L2 index order match_states (S: bsim_properties L1 L2 index order match_states).\n\nLemma bsim_E0_star:\n  forall s2 s2', Star L2 s2 E0 s2' ->\n  forall i s1, match_states i s1 s2 -> safe L1 s1 ->\n  exists i', exists s1', Star L1 s1 E0 s1' /\\ match_states i' s1' s2'.\nProof.\n  intros s20 s20' STAR0. pattern s20, s20'. eapply star_E0_ind; eauto.\n- (* base case *)\n  intros. exists i; exists s1; split; auto. apply star_refl.\n- (* inductive case *)\n  intros. exploit bsim_simulation; eauto. intros [i' [s1' [A B]]].\n  assert (Star L1 s0 E0 s1'). intuition. apply plus_star; auto.\n  exploit H0. eauto. eapply star_safe; eauto. intros [i'' [s1'' [C D]]].\n  exists i''; exists s1''; split; auto. eapply star_trans; eauto.\nQed.\n\nLemma bsim_safe:\n  forall i s1 s2,\n  match_states i s1 s2 -> safe L1 s1 -> safe L2 s2.\nProof.\n  intros; red; intros.\n  exploit bsim_E0_star; eauto. intros [i' [s1' [A B]]].\n  eapply bsim_progress; eauto. eapply star_safe; eauto.\nQed.\n\nLemma bsim_E0_plus:\n  forall s2 t s2', Plus L2 s2 t s2' -> t = E0 ->\n  forall i s1, match_states i s1 s2 -> safe L1 s1 ->\n     (exists i', exists s1', Plus L1 s1 E0 s1' /\\ match_states i' s1' s2')\n  \\/ (exists i', clos_trans _ order i' i /\\ match_states i' s1 s2').\nProof.\n  induction 1 using plus_ind2; intros; subst t.\n- (* base case *)\n  exploit bsim_simulation'; eauto. intros [[i' [s1' [A B]]] | [i' [A [B C]]]].\n+ left; exists i'; exists s1'; auto.\n+ right; exists i'; intuition.\n- (* inductive case *)\n  exploit Eapp_E0_inv; eauto. intros [EQ1 EQ2]; subst.\n  exploit bsim_simulation'; eauto. intros [[i' [s1' [A B]]] | [i' [A [B C]]]].\n+ exploit bsim_E0_star. apply plus_star; eauto. eauto. eapply star_safe; eauto. apply plus_star; auto.\n  intros [i'' [s1'' [P Q]]].\n  left; exists i''; exists s1''; intuition. eapply plus_star_trans; eauto.\n+ exploit IHplus; eauto. intros [P | [i'' [P Q]]].\n  left; auto.\n  right; exists i''; intuition. eapply t_trans; eauto. apply t_step; auto.\nQed.\n\nLemma star_non_E0_split:\n  forall s2 t s2', Star L2 s2 t s2' -> (length t = 1)%nat ->\n  exists s2x, exists s2y, Star L2 s2 E0 s2x /\\ Step L2 s2x t s2y /\\ Star L2 s2y E0 s2'.\nProof.\n  induction 1; intros.\n  simpl in H; discriminate.\n  subst t.\n  assert (EITHER: t1 = E0 \\/ t2 = E0).\n    unfold Eapp in H2; rewrite app_length in H2.\n    destruct t1; auto. destruct t2; auto. simpl in H2; extlia.\n  destruct EITHER; subst.\n  exploit IHstar; eauto. intros [s2x [s2y [A [B C]]]].\n  exists s2x; exists s2y; intuition. eapply star_left; eauto.\n  rewrite E0_right. exists s1; exists s2; intuition. apply star_refl.\nQed.\n\nEnd BACKWARD_SIMULATION_SEQUENCES.\n\n(** ** Composing two backward simulations *)\n\nSection COMPOSE_BACKWARD_SIMULATIONS.\n\nVariable L1: semantics.\nVariable L2: semantics.\nVariable L3: semantics.\nHypothesis L3_single_events: single_events L3.\nContext index order match_states (S12: bsim_properties L1 L2 index order match_states).\nContext index' order' match_states' (S23: bsim_properties L2 L3 index' order' match_states').\n\nLet bb_index : Type := (index * index')%type.\n\nDefinition bb_order : bb_index -> bb_index -> Prop := lex_ord (clos_trans _ order) order'.\n\nInductive bb_match_states: bb_index -> state L1 -> state L3 -> Prop :=\n  | bb_match_later: forall i1 i2 s1 s3 s2x s2y,\n      match_states i1 s1 s2x -> Star L2 s2x E0 s2y -> match_states' i2 s2y s3 ->\n      bb_match_states (i1, i2) s1 s3.\n\nLemma bb_match_at: forall i1 i2 s1 s3 s2,\n  match_states i1 s1 s2 -> match_states' i2 s2 s3 ->\n  bb_match_states (i1, i2) s1 s3.\nProof.\n  intros. econstructor; eauto. apply star_refl.\nQed.\n\nLemma bb_simulation_base:\n  forall s3 t s3', Step L3 s3 t s3' ->\n  forall i1 s1 i2 s2, match_states i1 s1 s2 -> match_states' i2 s2 s3 -> safe L1 s1 ->\n  exists i', exists s1',\n    (Plus L1 s1 t s1' \\/ (Star L1 s1 t s1' /\\ bb_order i' (i1, i2)))\n    /\\ bb_match_states i' s1' s3'.\nProof.\n  intros.\n  exploit (bsim_simulation' S23); eauto. eapply bsim_safe; eauto.\n  intros [ [i2' [s2' [PLUS2 MATCH2]]] | [i2' [ORD2 [EQ MATCH2]]]].\n- (* 1 L2 makes one or several transitions *)\n  assert (EITHER: t = E0 \\/ (length t = 1)%nat).\n  { exploit L3_single_events; eauto.\n    destruct t; auto. destruct t; auto. simpl. intros. extlia. }\n  destruct EITHER.\n+ (* 1.1 these are silent transitions *)\n  subst t. exploit (bsim_E0_plus S12); eauto.\n  intros [ [i1' [s1' [PLUS1 MATCH1]]] | [i1' [ORD1 MATCH1]]].\n* (* 1.1.1 L1 makes one or several transitions *)\n  exists (i1', i2'); exists s1'; split. auto. eapply bb_match_at; eauto.\n* (* 1.1.2 L1 makes no transitions *)\n  exists (i1', i2'); exists s1; split.\n  right; split. apply star_refl. left; auto.\n  eapply bb_match_at; eauto.\n+ (* 1.2 non-silent transitions *)\n  exploit star_non_E0_split. apply plus_star; eauto. auto.\n  intros [s2x [s2y [P [Q R]]]].\n  exploit (bsim_E0_star S12). eexact P. eauto. auto. intros [i1' [s1x [X Y]]].\n  exploit (bsim_simulation' S12). eexact Q. eauto. eapply star_safe; eauto.\n  intros [[i1'' [s1y [U V]]] | [i1'' [U [V W]]]]; try (subst t; discriminate).\n  exists (i1'', i2'); exists s1y; split.\n  left. eapply star_plus_trans; eauto. eapply bb_match_later; eauto.\n- (* 2. L2 makes no transitions *)\n  subst. exists (i1, i2'); exists s1; split.\n  right; split. apply star_refl. right; auto.\n  eapply bb_match_at; eauto.\nQed.\n\nLemma bb_simulation:\n  forall s3 t s3', Step L3 s3 t s3' ->\n  forall i s1, bb_match_states i s1 s3 -> safe L1 s1 ->\n  exists i', exists s1',\n    (Plus L1 s1 t s1' \\/ (Star L1 s1 t s1' /\\ bb_order i' i))\n    /\\ bb_match_states i' s1' s3'.\nProof.\n  intros. inv H0.\n  exploit star_inv; eauto. intros [[EQ1 EQ2] | PLUS].\n- (* 1. match at *)\n  subst. eapply bb_simulation_base; eauto.\n- (* 2. match later *)\n  exploit (bsim_E0_plus S12); eauto.\n  intros [[i1' [s1' [A B]]] | [i1' [A B]]].\n+ (* 2.1 one or several silent transitions *)\n  exploit bb_simulation_base. eauto. auto. eexact B. eauto.\n    eapply star_safe; eauto. eapply plus_star; eauto.\n  intros [i'' [s1'' [C D]]].\n  exists i''; exists s1''; split; auto.\n  left. eapply plus_star_trans; eauto.\n  destruct C as [P | [P Q]]. apply plus_star; eauto. eauto.\n  traceEq.\n+ (* 2.2 no silent transition *)\n  exploit bb_simulation_base. eauto. auto. eexact B. eauto. auto.\n  intros [i'' [s1'' [C D]]].\n  exists i''; exists s1''; split; auto.\n  intuition. right; intuition.\n  inv H6. left. eapply t_trans; eauto. left; auto.\nQed.\n\nEnd COMPOSE_BACKWARD_SIMULATIONS.\n\nLemma compose_backward_simulation:\n  forall L1 L2 L3,\n  single_events L3 -> backward_simulation L1 L2 -> backward_simulation L2 L3 ->\n  backward_simulation L1 L3.\nProof.\n  intros L1 L2 L3 L3single S12 S23.\n  destruct S12 as [index order match_states props].\n  destruct S23 as [index' order' match_states' props'].\n  apply Backward_simulation with (bb_order order order') (bb_match_states L1 L2 L3 match_states match_states');\n  constructor.\n- (* well founded *)\n  unfold bb_order. apply wf_lex_ord. apply wf_clos_trans. eapply bsim_order_wf; eauto. eapply bsim_order_wf; eauto.\n- (* initial states exist *)\n  intros. exploit (bsim_initial_states_exist props); eauto. intros [s2 A].\n  eapply (bsim_initial_states_exist props'); eauto.\n- (* match initial states *)\n  intros s1 s3 INIT1 INIT3.\n  exploit (bsim_initial_states_exist props); eauto. intros [s2 INIT2].\n  exploit (bsim_match_initial_states props'); eauto. intros [i2 [s2' [INIT2' M2]]].\n  exploit (bsim_match_initial_states props); eauto. intros [i1 [s1' [INIT1' M1]]].\n  exists (i1, i2); exists s1'; intuition auto. eapply bb_match_at; eauto.\n- (* match final states *)\n  intros i s1 s3 r MS SAFE FIN. inv MS.\n  exploit (bsim_match_final_states props'); eauto.\n    eapply star_safe; eauto. eapply bsim_safe; eauto.\n  intros [s2' [A B]].\n  exploit (bsim_E0_star props). eapply star_trans. eexact H0. eexact A. auto. eauto. auto.\n  intros [i1' [s1' [C D]]].\n  exploit (bsim_match_final_states props); eauto. eapply star_safe; eauto.\n  intros [s1'' [P Q]].\n  exists s1''; split; auto. eapply star_trans; eauto.\n- (* progress *)\n  intros i s1 s3 MS SAFE. inv MS.\n  eapply (bsim_progress props'). eauto. eapply star_safe; eauto. eapply bsim_safe; eauto.\n- (* simulation *)\n  apply bb_simulation; auto.\n- (* symbols *)\n  intros. transitivity (Senv.public_symbol (symbolenv L2) id); eapply bsim_public_preserved; eauto.\nQed.\n\n(** ** Converting a forward simulation to a backward simulation *)\n\nSection FORWARD_TO_BACKWARD.\n\nContext L1 L2 index order match_states (FS: fsim_properties L1 L2 index order match_states).\nHypothesis L1_receptive: receptive L1.\nHypothesis L2_determinate: determinate L2.\n\n(** Exploiting forward simulation *)\n\nInductive f2b_transitions: state L1 -> state L2 -> Prop :=\n  | f2b_trans_final: forall s1 s2 s1' r,\n      Star L1 s1 E0 s1' ->\n      final_state L1 s1' r ->\n      final_state L2 s2 r ->\n      f2b_transitions s1 s2\n  | f2b_trans_step: forall s1 s2 s1' t s1'' s2' i' i'',\n      Star L1 s1 E0 s1' ->\n      Step L1 s1' t s1'' ->\n      Plus L2 s2 t s2' ->\n      match_states i' s1' s2 ->\n      match_states i'' s1'' s2' ->\n      f2b_transitions s1 s2.\n\nLemma f2b_progress:\n  forall i s1 s2, match_states i s1 s2 -> safe L1 s1 -> f2b_transitions s1 s2.\nProof.\n  intros i0; pattern i0. apply well_founded_ind with (R := order).\n  eapply fsim_order_wf; eauto.\n  intros i REC s1 s2 MATCH SAFE.\n  destruct (SAFE s1) as [[r FINAL] | [t [s1' STEP1]]]. apply star_refl.\n- (* final state reached *)\n  eapply f2b_trans_final; eauto.\n  apply star_refl.\n  eapply fsim_match_final_states; eauto.\n- (* L1 can make one step *)\n  exploit (fsim_simulation FS); eauto. intros [i' [s2' [A MATCH']]].\n  assert (B: Plus L2 s2 t s2' \\/ (s2' = s2 /\\ t = E0 /\\ order i' i)).\n    intuition auto.\n    destruct (star_inv H0); intuition auto.\n  clear A. destruct B as [PLUS2 | [EQ1 [EQ2 ORDER]]].\n+ eapply f2b_trans_step; eauto. apply star_refl.\n+ subst. exploit REC; eauto. eapply star_safe; eauto. apply star_one; auto.\n  intros TRANS; inv TRANS.\n* eapply f2b_trans_final; eauto. eapply star_left; eauto.\n* eapply f2b_trans_step; eauto. eapply star_left; eauto.\nQed.\n\nLemma fsim_simulation_not_E0:\n  forall s1 t s1', Step L1 s1 t s1' -> t <> E0 ->\n  forall i s2, match_states i s1 s2 ->\n  exists i', exists s2', Plus L2 s2 t s2' /\\ match_states i' s1' s2'.\nProof.\n  intros. exploit (fsim_simulation FS); eauto. intros [i' [s2' [A B]]].\n  exists i'; exists s2'; split; auto.\n  destruct A. auto. destruct H2. exploit star_inv; eauto. intros [[EQ1 EQ2] | P]; auto.\n  congruence.\nQed.\n\n(** Exploiting determinacy *)\n\nRemark silent_or_not_silent:\n  forall t, t = E0 \\/ t <> E0.\nProof.\n  intros; unfold E0; destruct t; auto; right; congruence.\nQed.\n\nRemark not_silent_length:\n  forall t1 t2, (length (t1 ** t2) <= 1)%nat -> t1 = E0 \\/ t2 = E0.\nProof.\n  unfold Eapp, E0; intros. rewrite app_length in H.\n  destruct t1; destruct t2; auto. simpl in H. extlia.\nQed.\n\nLemma f2b_determinacy_inv:\n  forall s2 t' s2' t'' s2'',\n  Step L2 s2 t' s2' -> Step L2 s2 t'' s2'' ->\n  (t' = E0 /\\ t'' = E0 /\\ s2' = s2'')\n  \\/ (t' <> E0 /\\ t'' <> E0 /\\ match_traces (symbolenv L1) t' t'').\nProof.\n  intros.\n  assert (match_traces (symbolenv L2) t' t'').\n    eapply sd_determ_1; eauto.\n  destruct (silent_or_not_silent t').\n  subst. inv H1.\n  left; intuition. eapply sd_determ_2; eauto.\n  destruct (silent_or_not_silent t'').\n  subst. inv H1. elim H2; auto.\n  right; intuition.\n  eapply match_traces_preserved with (ge1 := (symbolenv L2)); auto.\n  intros; symmetry; apply (fsim_public_preserved FS).\nQed.\n\nLemma f2b_determinacy_star:\n  forall s s1, Star L2 s E0 s1 ->\n  forall t s2 s3,\n  Step L2 s1 t s2 -> t <> E0 ->\n  Star L2 s t s3 ->\n  Star L2 s1 t s3.\nProof.\n  intros s0 s01 ST0. pattern s0, s01. eapply star_E0_ind; eauto.\n  intros. inv H3. congruence.\n  exploit f2b_determinacy_inv. eexact H. eexact H4.\n  intros [[EQ1 [EQ2 EQ3]] | [NEQ1 [NEQ2 MT]]].\n  subst. simpl in *. eauto.\n  congruence.\nQed.\n\n(** Orders *)\n\nInductive f2b_index : Type :=\n  | F2BI_before (n: nat)\n  | F2BI_after (n: nat).\n\nInductive f2b_order: f2b_index -> f2b_index -> Prop :=\n  | f2b_order_before: forall n n',\n      (n' < n)%nat ->\n      f2b_order (F2BI_before n') (F2BI_before n)\n  | f2b_order_after: forall n n',\n      (n' < n)%nat ->\n      f2b_order (F2BI_after n') (F2BI_after n)\n  | f2b_order_switch: forall n n',\n      f2b_order (F2BI_before n') (F2BI_after n).\n\nLemma wf_f2b_order:\n  well_founded f2b_order.\nProof.\n  assert (ACC1: forall n, Acc f2b_order (F2BI_before n)).\n    intros n0; pattern n0; apply lt_wf_ind; intros.\n    constructor; intros. inv H0. auto.\n  assert (ACC2: forall n, Acc f2b_order (F2BI_after n)).\n    intros n0; pattern n0; apply lt_wf_ind; intros.\n    constructor; intros. inv H0. auto. auto.\n  red; intros. destruct a; auto.\nQed.\n\n(** Constructing the backward simulation *)\n\nInductive f2b_match_states: f2b_index -> state L1 -> state L2 -> Prop :=\n  | f2b_match_at: forall i s1 s2,\n      match_states i s1 s2 ->\n      f2b_match_states (F2BI_after O) s1 s2\n  | f2b_match_before: forall s1 t s1' s2b s2 n s2a i,\n      Step L1 s1 t s1' ->  t <> E0 ->\n      Star L2 s2b E0 s2 ->\n      starN (step L2) (globalenv L2) n s2 t s2a ->\n      match_states i s1 s2b ->\n      f2b_match_states (F2BI_before n) s1 s2\n  | f2b_match_after: forall n s2 s2a s1 i,\n      starN (step L2) (globalenv L2) (S n) s2 E0 s2a ->\n      match_states i s1 s2a ->\n      f2b_match_states (F2BI_after (S n)) s1 s2.\n\nRemark f2b_match_after':\n  forall n s2 s2a s1 i,\n  starN (step L2) (globalenv L2) n s2 E0 s2a ->\n  match_states i s1 s2a ->\n  f2b_match_states (F2BI_after n) s1 s2.\nProof.\n  intros. inv H.\n  econstructor; eauto.\n  econstructor; eauto. econstructor; eauto.\nQed.\n\n(** Backward simulation of L2 steps *)\n\nLemma f2b_simulation_step:\n  forall s2 t s2', Step L2 s2 t s2' ->\n  forall i s1, f2b_match_states i s1 s2 -> safe L1 s1 ->\n  exists i', exists s1',\n    (Plus L1 s1 t s1' \\/ (Star L1 s1 t s1' /\\ f2b_order i' i))\n     /\\ f2b_match_states i' s1' s2'.\nProof.\n  intros s2 t s2' STEP2 i s1 MATCH SAFE.\n  inv MATCH.\n- (* 1. At matching states *)\n  exploit f2b_progress; eauto. intros TRANS; inv TRANS.\n+ (* 1.1  L1 can reach final state and L2 is at final state: impossible! *)\n  exploit (sd_final_nostep L2_determinate); eauto. contradiction.\n+ (* 1.2  L1 can make 0 or several steps; L2 can make 1 or several matching steps. *)\n  inv H2.\n  exploit f2b_determinacy_inv. eexact H5. eexact STEP2.\n  intros [[EQ1 [EQ2 EQ3]] | [NOT1 [NOT2 MT]]].\n* (* 1.2.1  L2 makes a silent transition *)\n  destruct (silent_or_not_silent t2).\n  (* 1.2.1.1  L1 makes a silent transition too: perform transition now and go to \"after\" state *)\n  subst. simpl in *. destruct (star_starN H6) as [n STEPS2].\n  exists (F2BI_after n); exists s1''; split.\n  left. eapply plus_right; eauto.\n  eapply f2b_match_after'; eauto.\n  (* 1.2.1.2 L1 makes a non-silent transition: keep it for later and go to \"before\" state *)\n  subst. simpl in *. destruct (star_starN H6) as [n STEPS2].\n  exists (F2BI_before n); exists s1'; split.\n  right; split. auto. constructor.\n  econstructor. eauto. auto. apply star_one; eauto. eauto. eauto.\n* (* 1.2.2 L2 makes a non-silent transition, and so does L1 *)\n  exploit not_silent_length. eapply (sr_traces L1_receptive); eauto. intros [EQ | EQ].\n  congruence.\n  subst t2. rewrite E0_right in H1.\n  (* Use receptiveness to equate the traces *)\n  exploit (sr_receptive L1_receptive); eauto. intros [s1''' STEP1].\n  exploit fsim_simulation_not_E0. eexact STEP1. auto. eauto.\n  intros [i''' [s2''' [P Q]]]. inv P.\n  (* Exploit determinacy *)\n  exploit not_silent_length. eapply (sr_traces L1_receptive); eauto. intros [EQ | EQ].\n  subst t0. simpl in *. exploit sd_determ_1. eauto. eexact STEP2. eexact H2.\n  intros. elim NOT2. inv H8. auto.\n  subst t2. rewrite E0_right in *.\n  assert (s4 = s2'). eapply sd_determ_2; eauto. subst s4.\n  (* Perform transition now and go to \"after\" state *)\n  destruct (star_starN H7) as [n STEPS2]. exists (F2BI_after n); exists s1'''; split.\n  left. eapply plus_right; eauto.\n  eapply f2b_match_after'; eauto.\n\n- (* 2. Before *)\n  inv H2. congruence.\n  exploit f2b_determinacy_inv. eexact H4. eexact STEP2.\n  intros [[EQ1 [EQ2 EQ3]] | [NOT1 [NOT2 MT]]].\n+ (* 2.1 L2 makes a silent transition: remain in \"before\" state *)\n  subst. simpl in *. exists (F2BI_before n0); exists s1; split.\n  right; split. apply star_refl. constructor. lia.\n  econstructor; eauto. eapply star_right; eauto.\n+ (* 2.2 L2 make a non-silent transition *)\n  exploit not_silent_length. eapply (sr_traces L1_receptive); eauto. intros [EQ | EQ].\n  congruence.\n  subst. rewrite E0_right in *.\n  (* Use receptiveness to equate the traces *)\n  exploit (sr_receptive L1_receptive); eauto. intros [s1''' STEP1].\n  exploit fsim_simulation_not_E0. eexact STEP1. auto. eauto.\n  intros [i''' [s2''' [P Q]]].\n  (* Exploit determinacy *)\n  exploit f2b_determinacy_star. eauto. eexact STEP2. auto. apply plus_star; eauto.\n  intro R. inv R. congruence.\n  exploit not_silent_length. eapply (sr_traces L1_receptive); eauto. intros [EQ | EQ].\n  subst. simpl in *. exploit sd_determ_1. eauto. eexact STEP2. eexact H2.\n  intros. elim NOT2. inv H7; auto.\n  subst. rewrite E0_right in *.\n  assert (s3 = s2'). eapply sd_determ_2; eauto. subst s3.\n  (* Perform transition now and go to \"after\" state *)\n  destruct (star_starN H6) as [n STEPS2]. exists (F2BI_after n); exists s1'''; split.\n  left. apply plus_one; auto.\n  eapply f2b_match_after'; eauto.\n\n- (* 3. After *)\n  inv H. exploit Eapp_E0_inv; eauto. intros [EQ1 EQ2]; subst.\n  exploit f2b_determinacy_inv. eexact H2. eexact STEP2.\n  intros [[EQ1 [EQ2 EQ3]] | [NOT1 [NOT2 MT]]].\n  subst. exists (F2BI_after n); exists s1; split.\n  right; split. apply star_refl. constructor; lia.\n  eapply f2b_match_after'; eauto.\n  congruence.\nQed.\n\nEnd FORWARD_TO_BACKWARD.\n\n(** The backward simulation *)\n\nLemma forward_to_backward_simulation:\n  forall L1 L2,\n  forward_simulation L1 L2 -> receptive L1 -> determinate L2 ->\n  backward_simulation L1 L2.\nProof.\n  intros L1 L2 FS L1_receptive L2_determinate.\n  destruct FS as [index order match_states FS].\n  apply Backward_simulation with f2b_order (f2b_match_states L1 L2 match_states); constructor.\n- (* well founded *)\n  apply wf_f2b_order.\n- (* initial states exist *)\n  intros. exploit (fsim_match_initial_states FS); eauto. intros [i [s2 [A B]]].\n  exists s2; auto.\n- (* initial states *)\n  intros. exploit (fsim_match_initial_states FS); eauto. intros [i [s2' [A B]]].\n  assert (s2 = s2') by (eapply sd_initial_determ; eauto). subst s2'.\n  exists (F2BI_after O); exists s1; split; auto. econstructor; eauto.\n- (* final states *)\n  intros. inv H.\n  exploit f2b_progress; eauto. intros TRANS; inv TRANS.\n  assert (r0 = r) by (eapply (sd_final_determ L2_determinate); eauto). subst r0.\n  exists s1'; auto.\n  inv H4. exploit (sd_final_nostep L2_determinate); eauto. contradiction.\n  inv H5. congruence. exploit (sd_final_nostep L2_determinate); eauto. contradiction.\n  inv H2. exploit (sd_final_nostep L2_determinate); eauto. contradiction.\n- (* progress *)\n  intros. inv H.\n  exploit f2b_progress; eauto. intros TRANS; inv TRANS.\n  left; exists r; auto.\n  inv H3. right; econstructor; econstructor; eauto.\n  inv H4. congruence. right; econstructor; econstructor; eauto.\n  inv H1. right; econstructor; econstructor; eauto.\n- (* simulation *)\n  eapply f2b_simulation_step; eauto.\n- (* symbols preserved *)\n  exact (fsim_public_preserved FS).\nQed.\n\n(** * Transforming a semantics into a single-event, equivalent semantics *)\n\nDefinition well_behaved_traces (L: semantics) : Prop :=\n  forall s t s', Step L s t s' ->\n  match t with nil => True | ev :: t' => output_trace t' end.\n\nSection ATOMIC.\n\nVariable L: semantics.\n\nHypothesis Lwb: well_behaved_traces L.\n\nInductive atomic_step (ge: genvtype L): (trace * state L) -> trace -> (trace * state L) -> Prop :=\n  | atomic_step_silent: forall s s',\n      Step L s E0 s' ->\n      atomic_step ge (E0, s) E0 (E0, s')\n  | atomic_step_start: forall s ev t s',\n      Step L s (ev :: t) s' ->\n      atomic_step ge (E0, s) (ev :: nil) (t, s')\n  | atomic_step_continue: forall ev t s,\n      output_trace (ev :: t) ->\n      atomic_step ge (ev :: t, s) (ev :: nil) (t, s).\n\nDefinition atomic : semantics := {|\n  state := (trace * state L)%type;\n  genvtype := genvtype L;\n  step := atomic_step;\n  initial_state := fun s => initial_state L (snd s) /\\ fst s = E0;\n  final_state := fun s r => final_state L (snd s) r /\\ fst s = E0;\n  globalenv := globalenv L;\n  symbolenv := symbolenv L\n|}.\n\nEnd ATOMIC.\n\n(** A forward simulation from a semantics [L1] to a single-event semantics [L2]\n  can be \"factored\" into a forward simulation from [atomic L1] to [L2]. *)\n\nSection FACTOR_FORWARD_SIMULATION.\n\nVariable L1: semantics.\nVariable L2: semantics.\nContext index order match_states (sim: fsim_properties L1 L2 index order match_states).\nHypothesis L2single: single_events L2.\n\nInductive ffs_match: index -> (trace * state L1) -> state L2 -> Prop :=\n  | ffs_match_at: forall i s1 s2,\n      match_states i s1 s2 ->\n      ffs_match i (E0, s1) s2\n  | ffs_match_buffer: forall i ev t s1 s2 s2',\n      Star L2 s2 (ev :: t) s2' -> match_states i s1 s2' ->\n      ffs_match i (ev :: t, s1) s2.\n\nLemma star_non_E0_split':\n  forall s2 t s2', Star L2 s2 t s2' ->\n  match t with\n  | nil => True\n  | ev :: t' => exists s2x, Plus L2 s2 (ev :: nil) s2x /\\ Star L2 s2x t' s2'\n  end.\nProof.\n  induction 1. simpl. auto.\n  exploit L2single; eauto. intros LEN.\n  destruct t1. simpl in *. subst. destruct t2. auto.\n  destruct IHstar as [s2x [A B]]. exists s2x; split; auto.\n  eapply plus_left. eauto. apply plus_star; eauto. auto.\n  destruct t1. simpl in *. subst t. exists s2; split; auto. apply plus_one; auto.\n  simpl in LEN. extlia.\nQed.\n\nLemma ffs_simulation:\n  forall s1 t s1', Step (atomic L1) s1 t s1' ->\n  forall i s2, ffs_match i s1 s2 ->\n  exists i', exists s2',\n     (Plus L2 s2 t s2' \\/ (Star L2 s2 t s2') /\\ order i' i)\n  /\\ ffs_match i' s1' s2'.\nProof.\n  induction 1; intros.\n- (* silent step *)\n  inv H0.\n  exploit (fsim_simulation sim); eauto.\n  intros [i' [s2' [A B]]].\n  exists i'; exists s2'; split. auto. constructor; auto.\n- (* start step *)\n  inv H0.\n  exploit (fsim_simulation sim); eauto.\n  intros [i' [s2' [A B]]].\n  destruct t as [ | ev' t].\n+ (* single event *)\n  exists i'; exists s2'; split. auto. constructor; auto.\n+ (* multiple events *)\n  assert (C: Star L2 s2 (ev :: ev' :: t) s2'). intuition. apply plus_star; auto.\n  exploit star_non_E0_split'. eauto. simpl. intros [s2x [P Q]].\n  exists i'; exists s2x; split. auto. econstructor; eauto.\n- (* continue step *)\n  inv H0.\n  exploit star_non_E0_split'. eauto. simpl. intros [s2x [P Q]].\n  destruct t.\n  exists i; exists s2'; split. left. eapply plus_star_trans; eauto. constructor; auto.\n  exists i; exists s2x; split. auto. econstructor; eauto.\nQed.\n\nEnd FACTOR_FORWARD_SIMULATION.\n\nTheorem factor_forward_simulation:\n  forall L1 L2,\n  forward_simulation L1 L2 -> single_events L2 ->\n  forward_simulation (atomic L1) L2.\nProof.\n  intros L1 L2 FS L2single.\n  destruct FS as [index order match_states sim].\n  apply Forward_simulation with order (ffs_match L1 L2 match_states); constructor.\n- (* wf *)\n  eapply fsim_order_wf; eauto.\n- (* initial states *)\n  intros. destruct s1 as [t1 s1]. simpl in H. destruct H. subst.\n  exploit (fsim_match_initial_states sim); eauto. intros [i [s2 [A B]]].\n  exists i; exists s2; split; auto. constructor; auto.\n- (* final states *)\n  intros. destruct s1 as [t1 s1]. simpl in H0; destruct H0; subst. inv H.\n  eapply (fsim_match_final_states sim); eauto.\n- (* simulation *)\n  eapply ffs_simulation; eauto.\n- (* symbols preserved *)\n  simpl. exact (fsim_public_preserved sim).\nQed.\n\n(** Likewise, a backward simulation from a single-event semantics [L1] to a semantics [L2]\n  can be \"factored\" as a backward simulation from [L1] to [atomic L2]. *)\n\nSection FACTOR_BACKWARD_SIMULATION.\n\nVariable L1: semantics.\nVariable L2: semantics.\nContext index order match_states (sim: bsim_properties L1 L2 index order match_states).\nHypothesis L1single: single_events L1.\nHypothesis L2wb: well_behaved_traces L2.\n\nInductive fbs_match: index -> state L1 -> (trace * state L2) -> Prop :=\n  | fbs_match_intro: forall i s1 t s2 s1',\n      Star L1 s1 t s1' -> match_states i s1' s2 ->\n      t = E0 \\/ output_trace t ->\n      fbs_match i s1 (t, s2).\n\nLemma fbs_simulation:\n  forall s2 t s2', Step (atomic L2) s2 t s2' ->\n  forall i s1, fbs_match i s1 s2 -> safe L1 s1 ->\n  exists i', exists s1',\n     (Plus L1 s1 t s1' \\/ (Star L1 s1 t s1' /\\ order i' i))\n     /\\ fbs_match i' s1' s2'.\nProof.\n  induction 1; intros.\n- (* silent step *)\n  inv H0.\n  exploit (bsim_simulation sim); eauto. eapply star_safe; eauto.\n  intros [i' [s1'' [A B]]].\n  exists i'; exists s1''; split.\n  destruct A as [P | [P Q]]. left. eapply star_plus_trans; eauto. right; split; auto. eapply star_trans; eauto.\n  econstructor. apply star_refl. auto. auto.\n- (* start step *)\n  inv H0.\n  exploit (bsim_simulation sim); eauto. eapply star_safe; eauto.\n  intros [i' [s1'' [A B]]].\n  assert (C: Star L1 s1 (ev :: t) s1'').\n    eapply star_trans. eauto. destruct A as [P | [P Q]]. apply plus_star; eauto. eauto. auto.\n  exploit star_non_E0_split'; eauto. simpl. intros [s1x [P Q]].\n  exists i'; exists s1x; split.\n  left; auto.\n  econstructor; eauto.\n  exploit L2wb; eauto.\n- (* continue step *)\n  inv H0. unfold E0 in H8; destruct H8; try congruence.\n  exploit star_non_E0_split'; eauto. simpl. intros [s1x [P Q]].\n  exists i; exists s1x; split. left; auto. econstructor; eauto. simpl in H0; tauto.\nQed.\n\nLemma fbs_progress:\n  forall i s1 s2,\n  fbs_match i s1 s2 -> safe L1 s1 ->\n  (exists r, final_state (atomic L2) s2 r) \\/\n  (exists t, exists s2', Step (atomic L2) s2 t s2').\nProof.\n  intros. inv H. destruct t.\n- (* 1. no buffered events *)\n  exploit (bsim_progress sim); eauto. eapply star_safe; eauto.\n  intros [[r A] | [t [s2' A]]].\n+ (* final state *)\n  left; exists r; simpl; auto.\n+ (* L2 can step *)\n  destruct t.\n  right; exists E0; exists (nil, s2'). constructor. auto.\n  right; exists (e :: nil); exists (t, s2'). constructor. auto.\n- (* 2. some buffered events *)\n  unfold E0 in H3; destruct H3. congruence.\n  right; exists (e :: nil); exists (t, s3). constructor. auto.\nQed.\n\nEnd FACTOR_BACKWARD_SIMULATION.\n\nTheorem factor_backward_simulation:\n  forall L1 L2,\n  backward_simulation L1 L2 -> single_events L1 -> well_behaved_traces L2 ->\n  backward_simulation L1 (atomic L2).\nProof.\n  intros L1 L2 BS L1single L2wb.\n  destruct BS as [index order match_states sim].\n  apply Backward_simulation with order (fbs_match L1 L2 match_states); constructor.\n- (* wf *)\n  eapply bsim_order_wf; eauto.\n- (* initial states exist *)\n  intros. exploit (bsim_initial_states_exist sim); eauto. intros [s2 A].\n  exists (E0, s2). simpl; auto.\n- (* initial states match *)\n  intros. destruct s2 as [t s2]; simpl in H0; destruct H0; subst.\n  exploit (bsim_match_initial_states sim); eauto. intros [i [s1' [A B]]].\n  exists i; exists s1'; split. auto. econstructor. apply star_refl. auto. auto.\n- (* final states match *)\n  intros. destruct s2 as [t s2]; simpl in H1; destruct H1; subst.\n  inv H. exploit (bsim_match_final_states sim); eauto. eapply star_safe; eauto.\n  intros [s1'' [A B]]. exists s1''; split; auto. eapply star_trans; eauto.\n- (* progress *)\n  eapply fbs_progress; eauto.\n- (* simulation *)\n  eapply fbs_simulation; eauto.\n- (* symbols *)\n  simpl. exact (bsim_public_preserved sim).\nQed.\n\n(** Receptiveness of [atomic L]. *)\n\nRecord strongly_receptive (L: semantics) : Prop :=\n  Strongly_receptive {\n    ssr_receptive: forall s ev1 t1 s1 ev2,\n      Step L s (ev1 :: t1) s1 ->\n      match_traces (symbolenv L) (ev1 :: nil) (ev2 :: nil) ->\n      exists s2, exists t2, Step L s (ev2 :: t2) s2;\n    ssr_well_behaved:\n      well_behaved_traces L\n  }.\n\nTheorem atomic_receptive:\n  forall L, strongly_receptive L -> receptive (atomic L).\nProof.\n  intros. constructor; intros.\n(* receptive *)\n  inv H0.\n  (* silent step *)\n  inv H1. exists (E0, s'). constructor; auto.\n  (* start step *)\n  assert (exists ev2, t2 = ev2 :: nil). inv H1; econstructor; eauto.\n  destruct H0 as [ev2 EQ]; subst t2.\n  exploit ssr_receptive; eauto. intros [s2 [t2 P]].\n  exploit ssr_well_behaved. eauto. eexact P. simpl; intros Q.\n  exists (t2, s2). constructor; auto.\n  (* continue step *)\n  simpl in H2; destruct H2.\n  assert (t2 = ev :: nil). inv H1; simpl in H0; tauto.\n  subst t2. exists (t, s0). constructor; auto. simpl; auto.\n(* single-event *)\n  red. intros. inv H0; simpl; lia.\nQed.\n\n(** * Connections with big-step semantics *)\n\n(** The general form of a big-step semantics *)\n\nRecord bigstep_semantics : Type :=\n  Bigstep_semantics {\n    bigstep_terminates: trace -> int -> Prop;\n    bigstep_diverges: traceinf -> Prop\n  }.\n\n(** Soundness with respect to a small-step semantics *)\n\nRecord bigstep_sound (B: bigstep_semantics) (L: semantics) : Prop :=\n  Bigstep_sound {\n    bigstep_terminates_sound:\n      forall t r,\n      bigstep_terminates B t r ->\n      exists s1, exists s2, initial_state L s1 /\\ Star L s1 t s2 /\\ final_state L s2 r;\n    bigstep_diverges_sound:\n      forall T,\n      bigstep_diverges B T ->\n      exists s1, initial_state L s1 /\\ forever (step L) (globalenv L) s1 T\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/common/Smallstep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.29170347601763374}}
{"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.\nFrom mathcomp Require Import prime.\nRequire Import Max.\nRequire Import ssrZ ZArith_ext String_ext seq_ext.\nRequire Import machine_int.\nImport MachineInt.\nRequire Import multi_int.\n\nDeclare Scope rfc5246_scope.\nDeclare Scope select_scope.\n\nLocal Open Scope machine_int_scope.\nLocal Open Scope zarith_ext_scope.\n\n(** preamble *)\n\nDefinition Zmax_seq_opt (l : seq Z) (n : option Z) :=\n  match n with\n    | Some m => Z.max m (Zmax_seq l)\n    | None => Z.max (Zmax_seq l) 1\n  end.\nNotation \"Zmax( l , n )\" := (Zmax_seq_opt l n) : rfc5246_scope.\n\nLocal Open Scope rfc5246_scope.\n\nModule MachineIntByte_m.\n\nDefinition bytes2Z l : Z := bSum_c 8 l.\nDefinition bytes2nat l : nat := '| bSum_c 8 l |.\nDefinition nibble := int 4.\n\nDefinition hex2ot (l : string) : option (int 8) :=\n  match l with\n    | String h (String h' EmptyString) =>\n      match oZ_of_hex h, oZ_of_hex h' with\n        | Some a, Some b => Some (`( a )c_ 4 `|| `( b )c_ 4)\n        | _, _ => None\n      end\n    | String h EmptyString => match oZ_of_hex h with Some a => Some (zext 4 (`( a )c_ 4)) | _ => None end\n    | EmptyString => Some (`( 0 )c_ 8)\n    | _ => None\n  end.\n\nLemma hex2ot_all : forall l, hex2ot l == None ->\n  (~~ all (fun x : Ascii.ascii => oZ_of_hex x != None) (string2asciis l))\n  || (String.length l > 2)%nat.\nProof.\nelim=> // h [] //.\n  move=> _ /=.\n  by destruct (oZ_of_hex h).\nmove=> h' [] //; last first.\n  move=> *; apply/orP; by right.\nrewrite /=.\ndestruct (oZ_of_hex h) => //.\nby destruct (oZ_of_hex h').\nQed.\n\nProgram Definition hex2t (l : string)\n  (H : (all (fun x => oZ_of_hex x != None) (string2asciis l)) && (String.length l <= 2)%nat) : int 8 :=\n  match hex2ot l with\n      | Some z => z\n      | None => False_rect _ _\n  end.\nNext Obligation.\nmove: H.\napply/negP.\nrewrite negb_and leqNgt negbK.\napply hex2ot_all.\nby apply/eqP.\nDefined.\n\nEnd MachineIntByte_m.\n\nNotation \"'\\0x' l\" := (MachineIntByte_m.hex2t l Logic.eq_refl) (at level 9) : rfc5246_scope.\n\nModule RFC5246.\n\n(** * 4. Presentation Language *)\n\nDefinition byte : Type := int 8.\n\n(** ** 4.1 Basic Block Size *)\n\nModule S41.\nDefinition bytes2Z (l : seq byte) := MachineIntByte_m.bytes2Z l.\nDefinition bytes2nat (l : seq byte) := MachineIntByte_m.bytes2nat l.\nEnd S41.\n\nNotation \"'nat<=i8'\" := (S41.bytes2nat) (at level 9).\n\n(** A type for vectors, enumerateds, and constructed types\n   (variants will be represented by Coq records).\n   - The type carries the min/max number of bytes required for\n   encoding as list of bytes.\n   - Divisibility is type-checked for fixed-size vectors.\n   - Bounds inclusion is type-checked for variable-size vectors.\n   NB: According to the RFC (p.9), \"the length of an encoded vector\n   must be an even multiple of the length of a single element\".\n   But we do not add this divisibility check because \"extensions\"\n   allow for nested variable-size vectors.\n   - Enumerated and variable-size vectors carry the number\n   of bytes necessary to encode their size.\n   *)\n\nInductive tls_typ : Z -> Z -> Type :=\n| opaque : tls_typ 1 1\n| arr : forall n, tls_typ n n -> forall m, 0 <=? m -> \n  m mod n == 0 -> \n  tls_typ m m\n| varr : forall n m (t : tls_typ n m) (k : nat) a b, a <=? b -> \n  k != O -> b <? 2^^(k * 8) -> 2^^((k - 1) * 8) <=? b -> m <=? Z<=nat k + b ->\n  tls_typ (Z<=nat k + a) (Z<=nat k + b)\n| enum : forall k l n, uniq l ->\n  Zmax(l, n) <? 2^^(k * 8) -> 2^^((k - 1) * 8) <=? Zmax(l, n) ->\n  tls_typ (Z<=nat k) (Z<=nat k)\n| pair : forall {n1 m1 n2 m2},\n  string * tls_typ n1 m1 -> tls_typ n2 m2 -> \n  tls_typ (n1 + n2) (m1 + m2)\n| typ_nil : tls_typ 0 0.\n\nSection tls_typ_ind_nested.\n\nVariables (P : forall a b, tls_typ a b -> Prop) .\nHypotheses (H0 : P 0 0 typ_nil) (H1 : P 1 1 opaque)\n(H2 : forall n (t : tls_typ n n), P n n t ->\n      forall m (i : 0 <=? m) (i0 : m mod n == 0), P m m (arr n t m i i0))\n(H3 : forall n m (t : tls_typ n m), P n m t -> forall (k : nat) a b \n      (ab : a <=? b) (i : k != O) (i0 : b <? 2 ^^ (k * 8)) \n      (i1 : 2 ^^ ((k - 1) * 8) <=? b) (i3 : m <=? Z_of_nat k + b),\n      P (Z_of_nat k + a) (Z_of_nat k + b) (varr n m t k _ _ ab i i0 i1 i3))\n(H4 : forall (k : nat) (l : seq Z) n  (i : uniq l) \n      (i0 : Zmax(l, n) <? 2 ^^ (k * 8))\n      (i1 : 2 ^^ ((k - 1) * 8) <=? Zmax(l, n)),\n      P (Z_of_nat k) (Z_of_nat k) (enum k l n i i0 i1)).\n\nSection gen.\n\nVariable (Q : forall a b, string * tls_typ a b -> Prop).\nHypotheses \n(PQ : forall a b t, P a b t -> forall s, Q a b (s, t))\n(H : forall n1 m1 n2 m2 (p : string * tls_typ n1 m1) (t : tls_typ n2 m2), \n     Q n1 m1 p -> P n2 m2 t -> P (n1 + n2) (m1 + m2) (pair p t)).\n\nFixpoint tls_typ_nested_ind' a b t : P a b t :=\n  match t as x return P _ _ x with\n    | opaque => H1 \n    | arr n t' m i i0 => H2 n t' (tls_typ_nested_ind' _ _ t') m i i0\n    | varr n m t' k _ _ ab Hk i1 i2 i3 => H3 n m t' (tls_typ_nested_ind' _ _ t') k _ _ ab Hk i1 i2 i3\n    | enum k l n i i0 i1 => H4 k l n i i0 i1 \n    | pair n1 m1 n2 m2 p t' => H n1 m1 n2 m2 p t' \n      match p as x return Q n1 m1 x with\n         | (p1, p2) => PQ _ _ _ (tls_typ_nested_ind' _ _ p2) p1\n      end\n      (tls_typ_nested_ind' _ _ t')\n    | typ_nil => H0\n  end.\n\nEnd gen.\n\nSection spe.\n\nHypothesis H : \n  (forall a b c d s t1 t2, P a b t1 -> P c d t2 -> P _ _ (pair (s, t1) t2)).\n\nLemma tls_typ_nested_ind : forall a b (t : tls_typ a b) , P _ _ t.\nProof.\napply tls_typ_nested_ind' with (fun a b p => forall x, x = snd p -> P _ _ x) => //.\n- move=> a b t HP s x Hx; by subst x.\n- move=> n1 m1 n2 m2 [p1 p2] t Hp2 Ht.\n  apply H => //.\n  by apply Hp2.\nQed.\n\nEnd spe.\n\nEnd tls_typ_ind_nested.\n\nNotation \"'struct{' a ; .. ; b '}'\" := (pair a .. (pair b typ_nil) ..) (at level 10, no associativity,\n  format \"'[v' 'struct{' a ; .. ; b '}' ']'\").\nNotation \"'struct{}'\" := typ_nil.\n\nFixpoint tls_typ_find_struct_tag {n m} (t : tls_typ n m) (tag : string) : bool :=\nmatch t with\n  | pair _ _ _ _ tag' t' => if tag == fst tag' then false else tls_typ_find_struct_tag t' tag\n  | _ => true\nend.\n\nFixpoint tls_typ_well_formed {n m} (t : tls_typ n m) : bool :=\nmatch t with\n  | opaque => true\n  | arr _ t _ _ _ => tls_typ_well_formed t\n  | varr _ _ t _ _ _ _ _ _ _ _ => tls_typ_well_formed t\n  | enum _ _ _ _ _ _ => true\n  | pair _ _ _ _ (tg, rem) tr => tls_typ_well_formed rem && negb (tls_typ_find_struct_tag tr tg) &&\n    match tr with\n      | pair _ _ _ _ _ _ => tls_typ_well_formed tr\n      | typ_nil => true\n      | _ => false\n    end\n  | typ_nil => true\nend.\n\nDefinition lst_enum {n m} (t : tls_typ n m) : seq Z :=\n  if t is enum _ l _ _ _ _ then l else nil.\n\nFixpoint tls_max {n m} (t : tls_typ n m) : Z :=\n  match t with\n    | opaque => m\n    | arr _ _ _ _ _ => m\n    | varr _ _ _ k _ _ H1 H2 H3 H4 H5 => m - Z_of_nat k\n    | enum _ _ _ _ _ _ => m\n    | pair _ _ _ _ (_, t1) t2 => tls_max t1 + tls_max t2\n    | typ_nil => m\n  end.\n\nFixpoint tls_min {n m} (t : tls_typ n m) : Z :=\n  match t with\n    | opaque => n\n    | arr _ _ _ _ _ => n\n    | varr _ _ _ k _ _ H1 H2 H3 H4 H5 => n - Z_of_nat k\n    | enum _ _ _ _ _ _ => n\n    | pair _ _ _ _ (_, t1) t2 => tls_min t1 + tls_min t2\n    | typ_nil => n\n  end.\n\nFixpoint depth {n m} (t : tls_typ n m) :=\n  match t with\n    | opaque => O\n    | arr _ t _ _ _ => S (depth t)\n    | varr _ _ t' _ _ _ _ _ _ _ _ => S (depth t')\n    | enum m _ _ _ _ _ => O\n    | pair _ _ _ _ (_, t1) t2 => S (max (depth t1) (depth t2))\n    | typ_nil => O\n  end.\n\nSection tls_typ_decoding.\n\n(** A function to decide whether (the beginning of) a list of bytes is the implementation of a tls_typ. *)\nFixpoint decode' k {n m} (t : tls_typ n m) (l : seq byte)\n  : bool * seq byte :=\n  match k with\n    | O =>\n      match t with\n        | opaque => if (1 <= size l)%nat then\n                      (true, behead l)\n                    else\n                      (false, l)\n        | arr n _ m _ _ => if m <=? Z_of_nat (size l) then\n                             (true, drop '|m| l)\n                           else\n                             (false, l)\n        | varr n m t' x k a b _ _ _ _ => (false, l) (* NB: cannot happen at this depth *)\n        | enum m l' _ _ _ _ => if (m <= size l)%nat && ((S41.bytes2Z (take m l)) \\in l') then\n                                (true, drop m l)\n                              else\n                                (false, l)\n        | pair n1 m1 n2 m2 (tg, t1) t2 => (false, l) (* NB: cannot happen at this depth *)\n        | typ_nil => (true, l)\n      end\n    | S k' =>\n      match t with\n        | opaque => if (1 <= size l)%nat then\n                      (true, behead l)\n                    else\n                      (false, l)\n        | arr n _ m _ _ => if m <=? Z<=nat (size l) then\n                             (true, drop '|m| l) (* TODO: no enum in arr thus ok but may need a recursive call *)\n                           else\n                             (false, l)\n        | varr n m t' k a b _ _ _ _ _ =>\n          if (k <= size l)%nat then\n            let len := S41.bytes2nat (take k l) in\n            if (len <= size (drop k l))%nat then\n              let (ret, l') := foldl\n                (fun a _ =>  match a with | (acc, buf) =>\n                      match buf with\n                        | nil => a\n                        | _ => if acc then\n                                 let (acc', buf') := decode' k' t' buf in (acc' && acc, buf')\n                               else\n                                 (acc, buf)\n                      end\n                  end)\n                (true, take len (drop k l))\n                (nseq len tt) (* NB: upper bound on the number of recursive calls to be done *)\n                in\n              if ret then\n                (true, l' ++ drop len (drop k l))\n              else\n                (false, l)\n            else\n              (false, l)\n          else\n            (false, l)\n        | enum m l' _ _ _ _ => if (m <= size l)%nat && ((S41.bytes2Z (take m l)) \\in l') then\n                                (true, drop m l)\n                              else\n                                (false, l)\n        | pair n1 m1 n2 m2 (tg, t1) t2 =>\n          let: (a, l') := decode' k' t1 l in\n          let: (a', l'') := decode' k' t2 l' in\n          (a && a', l'')\n        | typ_nil => (true, l)\n      end\n  end.\n\nEnd tls_typ_decoding.\n\nLemma decode'_upper : forall a b (t : tls_typ a b) n l, (depth t <= n)%nat ->\n  decode' (depth t) t l = decode' n t l.\nProof.\nmove=> a b; elim/tls_typ_nested_ind => // {a b}.\n- by case.\n- by case.\n- by move=> n t IH a H1 _ [] //.\n- move=> n m t IH l' a b H1 H2 H3 H4 H5 n0 l /= Hn0.\n  destruct n0 as [|n0]; [done | move=> /=].\n  move Hfold1 : (foldl _ _ _) => fold1.\n  move Hfold2 : (foldl _ _ _) => fold2.\n  suff : fold1 = fold2 by move=> ->.\n  rewrite -{}Hfold1 -{}Hfold2.\n  apply foldl_ext => x [a0 a1] Hx.\n  move Hdec1 : (decode' _ _ _) => dec1.\n  move Hdec2 : (decode' _ _ _) => dec2.\n  suff : dec1 = dec2 by move=> ->.\n  rewrite -{}Hdec1 -{}Hdec2.\n  by apply IH.\n- by move=> m l n Hnodup H1 H2 [].\n- move=> n1 m1 n2 m2 tag t1 t2 IH1 IH2 n l /= Hmax.\n  destruct n as [|n]; first by done.\n  rewrite -IH1 /=; last by apply/leP; apply le_max_l.\n  symmetry.\n  rewrite -IH1 /=; last first.\n    move: Hmax. rewrite ltnS. move/leP. move/max_lub_l. by move/leP.\n  move Hdec1 : (decode' _ _ _) => [dec11 dec12].\n  rewrite -IH2 //; last first.\n    move: Hmax. rewrite ltnS. move/leP. move/max_lub_r. by move/leP.\n  symmetry.\n  rewrite -IH2 //.\n  by apply/leP; apply le_max_r.\nQed.\n\nLemma fold_decode'_false : forall a b (t : tls_typ a b) lst l,\n  foldl\n  (fun (a : bool * seq byte) (_ : unit) =>\n    let (acc, buf) := a in\n      if acc then\n        let (acc', buf') := decode' (depth t) t buf in\n          (acc' && acc, buf')\n      else\n        (acc, buf))\n  (false, l) \n  lst = (false, l).\nProof. move=> a b t; by elim. Qed.\n\nDefinition decode {n m} (t : tls_typ n m) := decode' (depth t) t.\n\n(** A predicate to decide whether a list of bytes is the implementation of a tls_typ. *)\nDefinition decodep {n m} (t : tls_typ n m) (l : seq byte) :=\n  let (a, l'):= decode t l in a && (size l' == O).\n\nLemma decode_app : forall n m (t : tls_typ n m) a a' b,\n  decode t a = (true, a') -> decode t (a ++ b) = (true, a' ++ b).\nProof.\nmove=> n m; elim/tls_typ_nested_ind => {n m}.\n- (* str_nil *) move => a a' b H.\n  rewrite /decode /= in H *.\n  by inversion H.\n- (* opaque *) move=> a a' b.\n  rewrite /decode /=.\n  case: ifP.\n  + move=> Ha [] ?; subst a'.\n    rewrite size_cat addn_gt0 Ha /=.\n    by destruct a.\n  + by destruct a.\n- (* arr *) move=> n t IH m m0 m_n a a' b.\n  rewrite /decode /=.\n  case: ifP => // m_a [] ?; subst a'.\n  rewrite size_cat inj_plus.\n  have -> : m <=? Z_of_nat (size a) + Z_of_nat (size b).\n    move/leZP in  m_a.\n    apply/leZP.\n    rewrite addZC.\n    apply leZ_addl; [exact: Zle_0_nat | by []].\n    rewrite drop_cat.\n    case: ifP => // H.\n    have : '|m| = size a.\n      move/leZP in m_a.\n      move/negbT in H.\n      rewrite -leqNgt in H.\n      have {}m_a : ('|m| <= '|Z_of_nat (size a)|)%nat.\n        apply/leP.\n        apply Zabs_nat_le.\n        split => //.\n        by move/leZP in m0.\n      rewrite Zabs2Nat.id // in m_a.\n      by apply/eqP; rewrite eqn_leq H m_a.\n    move=> ->; by rewrite subnn drop0 drop_size.\n- (* varr *) move=> n m t IH l' n' m' H1 H2 H3 H4 H5 a a' b.\n  rewrite /decode /=.\n  case: ifP => // l'_a.\n  case: ifP => // Hheader.\n  move Hfold1 : (foldl _ _ _) => [ret1 buf1].\n  move Hfold2 : (foldl _ _ _) => [ret2 buf2].\n  case: ifP => // Hret1 [] ?; subst a'.\n  have Z : (l' <= size (a ++ b))%nat.\n    rewrite size_cat -(addn0 l'); by apply leq_add.\n  rewrite Z.\n  have X : take l' a = take l' (a ++ b).\n    by rewrite takel_cat.\n  rewrite -X in Hfold2.\n  have Y : (drop l' a) ++ b = drop l' (a ++ b).\n    rewrite drop_cat.\n    case: ifP => //.\n    move/negbT.\n    rewrite -leqNgt => H.\n    have {}H : size a = l' by apply/eqP; rewrite eqn_leq H l'_a.\n    by rewrite -H drop_size subnn drop0.\n  rewrite -X -Y size_cat -(addn0 (S41.bytes2nat (take l' a))) leq_add //.\n  rewrite Hret1 in Hfold1.\n  rewrite -Y takel_cat // in Hfold2.\n  case: ifP => Hret2.\n  + rewrite Hret2 Hfold1 in Hfold2.\n    case: Hfold2 => ?; subst buf2.\n    congr (_, _).\n    rewrite drop_cat.\n    case: ifP => // H.\n    by rewrite catA.\n    move/negbT in H.\n    rewrite -leqNgt addn0 in H.\n    have {}H : size (drop l' a) = nat<=i8 (take l' a) by apply/eqP; rewrite eqn_leq Hheader H.\n    by rewrite -H addn0 subnn drop0 drop_size cats0.\n  + subst ret2.\n    by rewrite Hfold1 in Hfold2.\n- (* enum *) move=> m l n Hnodup H1 H2 a a' b.\n  rewrite /decode /=.\n  case: ifP => //.\n  case/andP => m_a Hinb [] ?; subst a'.\n  rewrite size_cat -{1}(addn0 m) leq_add //= takel_cat //.\n  rewrite Hinb.\n  rewrite drop_cat.\n  case: ifP => //.\n  move/negbT.\n  rewrite -leqNgt => H.\n  have {}H : m = size a by apply/eqP; rewrite eqn_leq m_a H.\n  by rewrite -H subnn drop0 H drop_size.\n- (* pair *) move=> n1 m1 n2 m2 tag t1 t2 IH1 IH2 a a' b.\n  rewrite /decode /= -decode'_upper; last by apply/leP; apply le_max_l.\n  move Hdec1 : (decode' _ _ _) => [dec11 dec12].\n  rewrite -decode'_upper; last by apply/leP; apply le_max_r.\n  move Hdec2 : (decode' _ _ _) => [dec21 dec22].\n  case=> decx1 Ha'.\n  subst dec22.\n  destruct dec11; last by done.\n  destruct dec21; last by done.\n  rewrite {decx1} -decode'_upper; last by apply/leP; apply le_max_l.\n  move/(IH1 _ _ b) : Hdec1.\n  rewrite /decode => ->.\n  rewrite -decode'_upper; last by apply/leP; apply le_max_r.\n  move/(IH2 _ _ b) : Hdec2.\n  by rewrite /decode => ->.\nQed.\n\n(** Extract the fixed-size part of a tls_type. *)\nFixpoint fixed_sz {n m} (t : tls_typ n m) : Z :=\n  match t with\n    | opaque => 1\n    | arr _ _ m _ _ => m\n    | varr _ _ _ x _ _ _  _ _ _ _ => Z_of_nat x\n    | enum m _ _ _ _ _ => Z_of_nat m\n    | pair _ _ _ _ t1 t2 => fixed_sz (snd t1) + fixed_sz t2\n    | str_nil => 0\n  end.\n\n(** Notations for tls_type *)\nNotation \"T \\[ n \\]\" := (arr _ T n Logic.eq_refl Logic.eq_refl) (at level 50) : rfc5246_scope.\n\nNotation \"T \\[[ n \\]]\" := (arr _ T (Z.abs n) (Zle_imp_le_bool _ _ (normZ_ge0 _))\n  (proj1 (Zeq_is_eq_bool _ _) (Zmod_1_r (Z.abs n)))) (at level 50) : rfc5246_scope.\n\nNotation \"T `< a \\.. b `> n \" :=\n  (varr _ _ T n a b Logic.eq_refl Logic.eq_refl Logic.eq_refl Logic.eq_refl Logic.eq_refl) (at level 50) : rfc5246_scope.\n\nNotation \"\\enum n \\{ lst \\}\" :=\n  (enum n (map (@u2Zc 8) lst) None Logic.eq_refl Logic.eq_refl Logic.eq_refl) (at level 50) : rfc5246_scope.\nNotation \"\\enum n \\{ lst \\} m\" :=\n  (enum n (map (@u2Zc 8) lst) (Some m) Logic.eq_refl Logic.eq_refl Logic.eq_refl) (at level 50).\n\n(** ** 4.4 Numbers *)\n\n(* NB: we put Section 4.4 before 4.3 *)\nModule S44.\n(* NB: implicit in the RFC *)\nDefinition uint8 := opaque.\nDefinition uint16 := uint8 \\[ 2 \\].\nDefinition uint24 := uint8 \\[ 3 \\].\nDefinition uint32 := uint8 \\[ 4 \\].\nDefinition uint64 := uint8 \\[ 8 \\].\nEnd S44.\n\n(** ** 4.3 Vectors *)\nModule S43.\nDefinition Datum := opaque \\[ 3 \\].\nDefinition Data := Datum \\[ 9 \\].\n(* Datum \\[ 8 \\]. does not type because ~ (3 | 8) *)\nDefinition Data' := opaque \\[ 8 \\].\nDefinition Data'' n := opaque \\[[ n \\]].\n(* Definition Data''' n := Datum \\[[ n \\]]. fails *)\nDefinition mandatory := opaque `< 300 \\.. 400 `> 2.\nImport S44.\nDefinition longer := uint16 `< 0 \\.. 800 `> 2.\nEnd S43.\n\n(** ** 4.5 Enumerateds *)\n\nModule S45.\nDefinition red := `( 3 )c_8. Definition blue := `( 5 )c_8. Definition white := `( 7 )c_8.\nDefinition Color := \\enum 1 \\{ red :: blue :: white :: nil \\}.\nDefinition sweet := `( 1 )c_8 . Definition sour := `( 2 )c_8. Definition bitter := `( 4 )c_8.\nDefinition Taste := \\enum 2 \\{ sweet :: sour :: bitter ::nil \\} 32000.\nEnd S45.\n\n(** *** 4.6.1 Variants\n\n   Encoded with Coq records. *)\n\nNotation \"'\\{' i ; .. ; j '\\}'\":= (cons i .. (cons j nil) ..) (at level 70,\n  format \"'[v' '\\{'  '//' i ';' '//' .. ';' '//' j '//' '\\}' ']'\", i at level 71, j at level 71) : select_scope.\n\nDefinition pack {n m} (T : tls_typ n m) : {n : Z & { m : Z & tls_typ n m } }\n := existT (fun x => {m : Z & tls_typ x m}) n (existT _ m T).\n\nDefinition unpack (H : {n : Z & { m : Z & tls_typ n m } } ) :\n  tls_typ (projT1 H) (projT1 (projT2 H)) := projT2 (projT2 H).\n\nModule select_m.\nFixpoint sel {A :eqType} (l : seq (A * {n : Z & { m : Z & tls_typ n m } })) (z : A) :=\n  match l with\n    | (hi, ho) :: tl => if hi == z then ho else sel tl z\n    | _ => pack typ_nil\n  end.\n\nDefinition sel_test {A : eqType} (lst : seq A) (l : seq (A * {n : Z & {m : Z & tls_typ n m} }))\n  (_ : all (fun x => fst x == snd x) (zip lst (unzip1 l)))\n  (z : A) :=\n  match lst with\n    | nil => pack typ_nil\n    | h :: t => if all (fun x => fst x == snd x) (zip lst (unzip1 l)) then\n                  sel l z\n                else\n                  pack typ_nil\n  end.\n\nDefinition sel_enum (z : seq byte) {n m} (t : tls_typ n m) (Henum : decodep t z)\n  (l : seq (Z * {n' : Z & {m' : Z & tls_typ n' m'} }))\n  (H : all (fun x => fst x == snd x) (zip (lst_enum t) (unzip1 l)))\n  (H' : size l == size (lst_enum t)) :=\n  sel_test (lst_enum t) l H (S41.bytes2Z z).\nEnd select_m.\n\n(** Notations for \"select\" *)\n(*\nNotation \"'\\{' i ; .. ; j '\\}'\":= (cons i .. (cons j nil) ..) (at level 70,\n  format \"'[v' '\\{'  '//' i ';' '//' .. ';' '//' j '//' '\\}' ']'\", i at level 71, j at level 71) : select_scope.\n*)\nNotation \"'selectb(' b '\\)' lst\" := (select_m.sel_test (false :: true :: nil) lst (refl_equal _) b) (at level 70,\n  format \"'[' 'selectb('  b  '\\)' lst  ']' '//'\") : select_scope.\nNotation \"'select(' z '\\:' t '\\:' H '\\)' lst\" := (select_m.sel_enum z t H lst (refl_equal _) (refl_equal _)) (at level 70,\n  format \"'[' 'select(' z '\\:' t '\\:' H '\\)'  lst  ']' '//'\") : select_scope.\n\nRecord packet (p : seq byte -> bool) : Type := {\n  body :> seq byte ;\n  decodable : p body }.\nArguments body [p].\n\n(* Extract the variable size of a packet *)\nDefinition var_sz {n m} {t : tls_typ n m} (p : packet (decodep t)) :=\n  (size p - '|(fixed_sz t)|)%nat.\n\nModule dselect_m.\nFixpoint sel {A :eqType} (l : seq (A * (seq byte -> bool))) (z : A) :=\n  match l with\n    | (hi, ho) :: tl => if hi == z then ho else sel tl z\n    | _ => fun _ => false\n  end.\n\nDefinition sel_test {A : eqType} (lst : seq A) (l : seq (A * (seq byte -> bool)))\n  (_ : all (fun x => fst x == snd x) (zip lst (unzip1 l)))\n  (z : A) :=\n  match lst with\n    | nil => fun _ => false\n    | h :: t => if all (fun x => fst x == snd x) (zip lst (unzip1 l)) then\n                  sel l z\n                else\n                  fun _ => false\n  end.\n\nDefinition sel_enum (z : seq byte) {n m} (t : tls_typ n m) (Henum : decodep t z)\n  (l : seq (Z * (seq byte -> bool)))\n  (H : all (fun x => fst x == snd x) (zip (lst_enum t) (unzip1 l))) :=\n  sel_test (lst_enum t) l H (S41.bytes2Z z).\nEnd dselect_m.\n\n(*Notation \"'\\{' i ; .. ; j '\\}'\":= (cons i .. (cons j nil) ..) (at level 70,\n  format \"'[v' '\\{'  '//' i ';' '//' .. ';' '//' j '//' '\\}' ']'\", i at level 71, j at level 71) : select_decode_scope.*)\nNotation \"'dselectb(' b '\\)' lst\" := (dselect_m.sel_test (false :: true :: nil) lst (refl_equal _) b) (at level 70,\n  format \"'[' 'dselectb('  b  '\\)' lst  ']' '//'\") : select_scope.\nNotation \"'dselect(' z '\\:' t '\\:' H '\\)' lst\" := (dselect_m.sel_enum z t H lst (refl_equal _)) (at level 70,\n  format \"'[' 'dselect(' z '\\:' t '\\:' H '\\)'  lst  ']' '//'\") : select_scope.\n\nLocal Open Scope string_scope.\n\nModule S461.\nDefinition apple : byte := `( 0 )c_8. Definition orange := `( 1 )c_8. Definition banana := `( 2 )c_8.\nDefinition VariantTag := \\enum 1 \\{ apple :: orange :: banana :: nil \\}.\nDefinition variable_string_type := opaque `< 0 \\.. 10 `> 1.\n  Definition fixed_string_type := opaque \\[ 10 \\].\nImport S44.\n\nDefinition V1 :=\n   struct{ (\"number\", uint16) ;\n           (\"string\", variable_string_type) }.\nDefinition V2 :=\n   struct{ (\"number\", uint32) ;\n           (\"string\", fixed_string_type) }.\n\n(** We know that [n] is really an element of VariantTag because of [Hn].\n    NB: This is the encoding of the typed data, not the type only.\n    NB: the select is defined with enum types, but in S7412 it will be used w.r.t. to a boolean.\n<<\nstruct {\n  select (VariantTag) {\n    case apple:\n      V1;\n    case orange:\n    case bananana:\n      V2;\n  } variant_body;\n} VariantRecord;\n>>\n*)\n\nLocal Open Scope select_scope.\n\nDefinition VariantStructure n (Hn : decodep VariantTag n) :=  struct{\n  (\"variant_body\", unpack (select(_ \\: _ \\: Hn \\) \\{\n    (u2Zc apple, pack V1) ;\n    (u2Zc orange, pack V2) ;\n    (u2Zc banana, pack V2) \\})) }.\n\nLocal Close Scope select_scope.\n\nEnd S461.\n\n(** ** 4.8 Constants *)\nModule S48.\nImport S44.\nDefinition Example1 :=\n  struct{ (\"f1\", uint8) ;\n          (\"f2\", uint8) }.\nEnd S48.\n\n(** ** 7.1 Change Cipher Spec Protocol *)\nModule S71.\nDefinition change_cipher_spec : byte := `( 1 )c_8.\nDefinition type_type := \\enum 1 \\{ change_cipher_spec :: nil \\} 255.\nDefinition ChangeCipherSpec := struct{\n  (\"type\", type_type)\n}.\nEnd S71.\n\n(** ** 7.2 Alert Protocol *)\nModule S72.\nDefinition warning := `( 1 )c_8. Definition fatal := `( 2 )c_8.\nDefinition AlertLevel := \\enum 1 \\{ warning :: fatal :: nil \\} 255.\nDefinition close_notify := `( 0 )c_8.\nDefinition unexpected_message := `( 10 )c_8.\nDefinition bad_record_mac := `( 20 )c_8.\nDefinition decryption_failed_RESERVED := `( 21 )c_8.\nDefinition record_overflow := `( 22 )c_8.\nDefinition decompression_failure := `( 30 )c_8.\nDefinition handshake_failure := `( 40 )c_8.\nDefinition no_certificate_RESERVED := `( 41 )c_8.\nDefinition bad_certificate := `( 42 )c_8.\nDefinition unsupported_certificate := `( 43 )c_8.\nDefinition certificate_revoked := `( 44 )c_8.\nDefinition certificate_expired := `( 45 )c_8.\nDefinition certificate_unknown := `( 46 )c_8.\nDefinition illegal_parameter := `( 47 )c_8.\nDefinition unknown_ca := `( 48 )c_8.\nDefinition access_denied := `( 49 )c_8.\nDefinition decode_error := `( 50 )c_8.\nDefinition decrypt_error := `( 51 )c_8.\nDefinition export_restriction_RESERVED := `( 60 )c_8.\nDefinition protocol_version := `( 70 )c_8.\nDefinition insufficient_security := `( 71 )c_8.\nDefinition internal_error := `( 80 )c_8.\nDefinition user_canceled := `( 90 )c_8.\nDefinition no_renogociation := `( 100 )c_8.\nDefinition unsupported_extension := `( 110 )c_8.\nDefinition AlertDescription := \\enum 1 \\{\nclose_notify :: unexpected_message :: bad_record_mac :: decryption_failed_RESERVED ::\nrecord_overflow :: decompression_failure :: handshake_failure :: no_certificate_RESERVED ::\nbad_certificate :: unsupported_certificate :: certificate_revoked :: certificate_expired ::\ncertificate_unknown :: illegal_parameter :: unknown_ca :: access_denied :: decode_error ::\ndecrypt_error :: export_restriction_RESERVED :: protocol_version :: insufficient_security ::\ninternal_error :: user_canceled :: no_renogociation :: unsupported_extension :: nil\\} 255.\nDefinition Alert :=\n   struct{ (\"level\",       AlertLevel) ;\n           (\"description\", AlertDescription) }.\nEnd S72.\n\n(** **** Hello Extensions *)\n(* NB: we put Section 7.4.1.4.1 before Section 4.7 *)\nModule S74141.\nDefinition none := `( 0 )c_8. Definition md5 := `( 1 )c_8. Definition sha1 := `( 2 )c_8.\nDefinition sha224 := `( 3 )c_8. Definition sha256 := `( 4 )c_8. Definition sha384 := `( 5 )c_8.\nDefinition sha512 := `( 6 )c_8.\nDefinition HashAlgorithm := \\enum 1\n  \\{ none :: md5 :: sha1 :: sha224 :: sha256 :: sha384 :: sha512 :: nil \\} 255.\nDefinition anonymous := `( 0 )c_8. Definition rsa := `( 1 )c_8.\nDefinition dsa := `( 2 )c_8. Definition ecdsa := `( 3 )c_8.\nDefinition SignatureAlgorithm := \\enum 1\n  \\{ [:: anonymous ; rsa ; dsa ; ecdsa] \\} 255.\nDefinition SignatureAndHashAlgorithm :=\n   struct{ (\"hash\",      HashAlgorithm) ;\n           (\"signature\", SignatureAlgorithm) }.\nDefinition supported_signature_algorithms :=\n  SignatureAndHashAlgorithm `< 2 \\.. (2 ^ 16 - 2) `> 2.\nEnd S74141.\n\n(** ** Cryptographic Attributes *)\nModule S47.\n(*Definition signature_type := opaque \\< 2 \\.. (2 ^ 16 - 1) \\> 2.*)\nImport S74141.\nDefinition DigitallySigned :=\n   struct{ (\"algorithm\", SignatureAndHashAlgorithm) ;\n           (\"signature\", opaque `< 2 \\.. (2 ^ 16 - 1) `> 2) }.\nEnd S47.\n\n(** * 6. The TLS Record Protocol *)\n\n(** ** 6.1 Connection States *)\nModule S61.\nDefinition server := `( 0 )c_8. Definition client := `( 1 )c_8.\nDefinition ConnectionEnd := \\enum 1 \\{  server :: client :: nil \\}.\nDefinition tls_prf_sha256 := `( 0 )c_8.\nDefinition PRFAlgorithm := \\enum 1 \\{ tls_prf_sha256 :: nil \\}.\nDefinition null_bca := `( 0 )c_8.\n(* NB : _bca to distinguish from null of CompressionMethod *)\nDefinition rc4 := `( 1 )c_8. Definition threedes := `( 2 )c_8. Definition aes := `( 3 )c_8.\nDefinition BulkCipherAlgorithm := \\enum 1 \\{ null_bca :: rc4 :: threedes :: aes :: nil \\}.\nDefinition stream := `( 0 )c_8. Definition block := `( 1 )c_8. Definition aead := `( 2 )c_8.\nDefinition CipherType := \\enum 1 \\{ stream :: block :: aead :: nil \\}.\nDefinition null_ma := `( 0 )c_8.\n(* NB : _ma to distinguish from null of CompressionMethod *)\nDefinition hmac_md5 := `( 1 )c_8. Definition hmac_sha1 := `( 2 )c_8. Definition hmac_sha256 := `( 3 )c_8.\nDefinition hmac_sha384 := `( 4 )c_8. Definition hmac_sha512 := `( 5 )c_8.\nDefinition MACAlgorithm := \\enum 1 \\{ null_ma :: hmac_md5 :: hmac_sha1 :: hmac_sha256 ::\n  hmac_sha384 :: hmac_sha512 :: nil \\}.\nDefinition null := `( 0 )c_8.\nDefinition CompressionMethod := \\enum 1 \\{ [:: null] \\} 255.\nImport S44.\nDefinition SecurityParameters :=\n  struct{ (\"entity\",                ConnectionEnd) ;\n          (\"prf_algorithm\",         PRFAlgorithm) ;\n          (\"bulk_cipher_algorithm\", BulkCipherAlgorithm) ;\n          (\"cipher_type\",           CipherType) ;\n          (\"enc_key_length\",        uint8) ;\n          (\"block_length\",          uint8) ;\n          (\"fixed_iv_length\",       uint8) ;\n          (\"record_iv_length\",      uint8) ;\n          (\"mac_algorithm\",         MACAlgorithm) ;\n          (\"mac_length\",            uint8) ;\n          (\"mak_key_length\",        uint8) ;\n          (\"compression_algorithm\", CompressionMethod) ;\n          (\"master_secret\",         opaque \\[ 48 \\]) ;\n          (\"client_random\",         opaque \\[ 32 \\]) ;\n          (\"server_random\",         opaque \\[ 32 \\]) }.\nEnd S61.\n\n(** *** 6.2.1 Fragmentation *)\nModule S621.\nImport S44.\nDefinition ProtocolVersion :=\n  struct{ (\"major\", uint8) ; (\"minor\", uint8) }.\nDefinition change_cipher_spec := `( 20 )c_8.\nDefinition alert := `( 21 )c_8.\nDefinition handshake := `( 22 )c_8.\nDefinition application_data := `( 23 )c_8.\nDefinition ContentType := \\enum 1 \\{ change_cipher_spec :: alert :: handshake :: application_data :: nil \\} 255.\n(** remark p.20: *)\nDefinition length_maxp (x : seq byte) := (S41.bytes2nat x <= 2 ^ 14)%nat.\n\nDefinition SSLv30_maj := `( 3 )_ 8.\nDefinition SSLv30_min := `( 0 )_ 8.\nDefinition TLSv10_maj := SSLv30_maj.\nDefinition TLSv10_min := `( 1 )_8.\nDefinition TLSv11_maj := SSLv30_maj.\nDefinition TLSv11_min := `( 2 )_8.\nDefinition TLSv12_maj := SSLv30_maj.\nDefinition TLSv12_min := `( 3 )_8.\n\nDefinition is_maj x := x \\in [:: SSLv30_maj; TLSv10_maj; TLSv11_maj; TLSv12_maj].\nDefinition is_min x := x \\in [:: SSLv30_min; TLSv10_min; TLSv11_min; TLSv12_min].\nDefinition proverp s := is_maj s `_ O && is_min s `_ 1.\n\nStructure TLSPlainText := {\n  type : packet (decodep ContentType) ;\n  version : packet (fun x => decodep ProtocolVersion x && proverp x) ;\n  length : packet (fun x => decodep uint16 x && length_maxp x) ;\n  fragment : packet (decodep (opaque \\[[ S41.bytes2Z length \\]]))\n}.\n\nDefinition TLSPlainText_header_decode l : bool * seq byte :=\n  let (a1, l1) := decode ContentType l in\n  let (a2, l2) := let (a2', l2) := decode ProtocolVersion l1 in\n                  (a2' && proverp (take '|(fixed_sz ProtocolVersion)| l1), l2) in\n  let (a3, l3) := let (a3', l3) := decode uint16 l2 in\n                  (a3' && length_maxp (take '|(fixed_sz uint16)| l2), l3) in\n  ([&& a1, a2 & a3], l3).\n\nDefinition TLSPlainText_hd :=\n  fixed_sz ProtocolVersion + fixed_sz ContentType + fixed_sz uint16.\n\nEnd S621.\n\n(** *** 6.2.2 Record Compression and Decompression *)\nModule S622.\nImport S621 S44.\n(** remark p. 21: *)\nDefinition length_max := (2 ^ 14 + 1024)%nat.\nStructure TLSCompressed_packet := {\n  type : packet (decodep ContentType) ;\n  length : packet (fun x => decodep uint16 x && (S41.bytes2nat x <= length_max)%nat) ;\n  fragment : packet (decodep (opaque \\[[ (S41.bytes2Z length) \\]]))\n}.\nEnd S622.\n\n(** **** 6.2.3.1 Null or Standard Stream Cipher *)\nModule S6231.\nDefinition GenericStreamCipher TLSCompressed_length mac_length :=\n   struct{ (\"content\", opaque \\[[ TLSCompressed_length \\]]) ;\n           (\"MAC\",     opaque \\[[ mac_length \\]]) }.\nEnd S6231.\n\n(** **** 6.2.3.2 CBC Block Cipher *)\nModule S6232.\nImport S44.\nDefinition GenericBlockCipher record_iv_length TLSCompressed_length mac_length padding_length :=\n  struct{ (\"IV\",            opaque \\[[ record_iv_length \\]]) ;\n          (\"blockciphered\", struct{ (\"content\",        opaque \\[[ TLSCompressed_length \\]]) ;\n                                    (\"MAC\",            opaque \\[[ mac_length \\]]) ;\n                                    (\"padding\",        uint8 \\[[ padding_length (*NB: this is supposed to be the value of the next field*) \\]]) ;\n                                    (\"padding_length\", uint8) }) }.\nEnd S6232.\n\n(** **** 6.2.3.3 AEAD Ciphers *)\nModule S6233.\nDefinition GenericAEADCipher record_iv_length TLSCompressed_length :=\n   struct{ (\"nonce_explicit\", opaque \\[[ record_iv_length \\]]) ;\n           (\"aead-ciphered\",  struct{ (\"content\", opaque \\[[ TLSCompressed_length \\]]) } ) }.\nEnd S6233.\n\n(** *** 6.2.3 Record Payload Protection *)\nModule S623.\nImport S621 S44 S61 S6231 S6232 S6233.\n\nLocal Open Scope select_scope.\n\nDefinition TLSCipherText n (Hn : decodep CipherType n) TLSCompressed_length mac_length record_iv_length padding_length := struct{\n  (\"type\", ContentType) ;\n  (\"version\",  ProtocolVersion) ;\n  (\"length\", uint16) ;\n  (\"fragment\", unpack (select( _ \\: _ \\: Hn \\) \\{\n        (u2Zc stream, pack (GenericStreamCipher TLSCompressed_length mac_length)) ;\n        (u2Zc block, pack (GenericBlockCipher record_iv_length TLSCompressed_length mac_length padding_length)) ;\n        (u2Zc aead, pack (GenericAEADCipher record_iv_length TLSCompressed_length))\n      \\}))\n}.\n\nLocal Close Scope select_scope.\n\nEnd S623.\n\n(** * 7. The TLS Handshaking Protocols *)\n\n(** **** 7.4.1.1 Hello Request *)\nModule S7411.\nDefinition HelloRequest := struct{}.\nDefinition HelloRequestp := decodep HelloRequest.\nDefinition HelloRequest_packet := packet HelloRequestp.\nEnd S7411.\n\n(** **** 7.4.1.4 Hello Extensions *)\n(* NB: we put Section 7.4.1.4 before Section 7.4.1.2  *)\nModule S7414.\nDefinition signature_algorithms := `( 13 )c_8.\nDefinition ExtensionType :=\n  \\enum 2 \\{ [:: signature_algorithms] \\} 65535.\n(** The RFC actually defines:\n<<\nDefinition extension_data_type := opaque \\< 0 \\.. (2^16 - 1) \\> 2.\n>>\nbut this is not compatible with \"extensions_type\" in 7.4.1.2.\n*)\nDefinition extension_data_type :=\n  opaque `< 0 \\.. 2 ^ 16 - 1 - 2 `> 2.\nDefinition Extension :=\n  struct{ (\"extension_type\", ExtensionType) ;\n          (\"extension_data\", extension_data_type) }.\nEnd S7414.\n\n(** **** 7.4.1.2 Client Hello *)\nModule S7412.\nImport S44.\nDefinition Random :=\n  struct{ (\"gmt_unix_time\", uint32) ;\n          (\"random_bytes\", opaque \\[ 28 \\])}.\nDefinition SessionID := opaque `< 0 \\.. 32 `> 1.\nDefinition CipherSuite := uint8 \\[ 2 \\].\n\nNotation \"'NewCipherSuite' l\" := (Build_packet (decodep S7412.CipherSuite) l (Logic.eq_refl _)) (at level 9).\nDefinition CipherSuitePacket := packet (decodep S7412.CipherSuite).\n\n(** NB: CompressionMethod already defined in Sect. 6.1 *)\nDefinition cipher_suites_type := CipherSuite `< 2 \\.. (2 ^ 16 - 2) `> 2.\nImport S61.\nDefinition compression_methods_type := CompressionMethod `< 1 \\.. (2 ^ 8 - 1) `> 1.\nImport S7414.\nDefinition extensions_type := Extension `< 0 \\.. (2 ^ 16 - 1) `> 2.\nEval compute in (fixed_sz SessionID +\n  fixed_sz cipher_suites_type +\n  fixed_sz compression_methods_type).\nImport S621.\nEval compute in (fixed_sz ProtocolVersion).\nEval compute in (fixed_sz Random).\nDefinition Hello_sz sid :=\n  fixed_sz ProtocolVersion + fixed_sz Random +\n  fixed_sz SessionID + Z<=nat sid.\nDefinition ClientHello_sz sid cys cpm :=\n  Hello_sz sid +\n  fixed_sz cipher_suites_type + Z<=nat cys +\n  fixed_sz compression_methods_type + Z<=nat cpm.\nDefinition client_extensions_present m sid cys cpm :=\n  ClientHello_sz sid cys cpm <? Z<=nat m.\n\nLocal Open Scope select_scope.\n\n(** ClientHello parametrized by the length encoded in the outer Handshake packet (type uint24) *)\nStructure ClientHello_packet {m} (H : decodep uint24 m) := {\n  client_version : packet (fun x => decodep ProtocolVersion x && proverp x) ;\n  random : packet (decodep Random) ;\n  session_id : packet (decodep SessionID) ;\n  cipher_suites : packet (decodep cipher_suites_type) ;\n  compression_methods : packet (decodep compression_methods_type) ;\n  extensions : packet (\n    dselectb( client_extensions_present (nat<=i8 m)\n               (var_sz session_id)\n               (var_sz cipher_suites)\n               (var_sz compression_methods) \\)  \\{\n      (false, decodep struct{}) ;\n      (true, decodep extensions_type) \\}) }.\nArguments client_version [m H] _.\nArguments random [m H] _.\nArguments session_id [m H] _.\nArguments cipher_suites [m H] _.\nArguments compression_methods [m H] _.\nArguments extensions [m H] _.\n\nLocal Close Scope select_scope.\n\nDefinition ClientHello_decode m l : bool * seq byte :=\nif ~~ decodep uint24 m then (false, l) else\nlet (a1, l1) := let (a1', l1) := decode ProtocolVersion l in\n                (a1' && proverp (take ('|(fixed_sz ProtocolVersion)|) l), l1) in\nlet (a2, l2) := decode Random l1 in\nlet (a3, l3) := decode SessionID l2 in\nlet (a4, l4) := decode cipher_suites_type l3 in\nlet (a5, l5) := decode compression_methods_type l4 in\nif client_extensions_present (nat<=i8 m)\n    (size l2 - size l3 - '|(fixed_sz SessionID)|)\n    (size l3 - size l4 - '|(fixed_sz cipher_suites_type)|)\n    (size l4 - size l5 - '|(fixed_sz compression_methods_type)|) then\n  let (a6, l6) := decode extensions_type l5 in\n  ([&& a1, a2, a3, a4, a5 & a6], l6)\nelse\n  ([&& a1, a2, a3, a4 & a5], l5).\n\nDefinition ClientHellop m l : bool :=\n  let (a, l') := ClientHello_decode m l in (a && (size l' == O)).\n\nLemma ClientHello_packet_ClientHellop m (Hm : decodep uint24 m) : forall (buf : ClientHello_packet Hm),\n  ClientHellop m\n  (client_version buf ++ random buf ++ session_id buf ++\n   cipher_suites buf ++ compression_methods buf ++ extensions buf).\nProof.\ncase=> /=.\nmove=> [client_version0 H1] [random0 H2] [session_id0 H3] [cipher_suites0 H4]\n  [compression_methods0 H5] [extensions0 H6] /=.\nrewrite /ClientHellop /ClientHello_decode.\ncase :ifP => [Hn' | _].\n  by rewrite Hm in Hn'.\n\nmove: H1.\nrewrite {1}/decodep.\nmove Hdec_ver : (decode _ _) => dec_ver.\ndestruct dec_ver as [ret buf].\ncase/andP.\ncase/andP.\ndestruct ret => //= _.\ndestruct buf => //= _.\nrewrite (decode_app _ _ _ _ _ _ Hdec_ver).\nrewrite /=.\nset tmp := take _ _.\nhave ->  : proverp tmp = proverp client_version0.\n  rewrite /tmp.\n  by destruct client_version0 as [|h [|]].\nmove=> -> /=.\n\nmove: H2.\nrewrite {1}/decodep.\nmove Hdec_ran : (decode _ _) => dec_ran.\ndestruct dec_ran as [ret buf].\ncase/andP.\ndestruct ret => //= _.\ndestruct buf => //= _.\nrewrite (decode_app _ _ _ _ _ _ Hdec_ran).\n\nmove Hdec_sid : (decode SessionID session_id0) => dec_sid.\ndestruct dec_sid as [ret buf].\nrewrite /=.\ndestruct ret in Hdec_sid; last first.\n  clear H6.\n  by rewrite /decodep Hdec_sid in H3.\ndestruct buf in Hdec_sid; last first.\n  clear H6.\n  by rewrite /decodep Hdec_sid in H3.\nrewrite (decode_app _ _ _ _ _ _ Hdec_sid).\n\nmove Hdec_cyp : (decode cipher_suites_type cipher_suites0) => dec_cyp.\ndestruct dec_cyp as [ret buf].\ndestruct ret in Hdec_cyp; last first.\n  clear H6.\n  by rewrite /decodep Hdec_cyp in H4.\ndestruct buf in Hdec_cyp; last first.\n  clear H6.\n  by rewrite /decodep Hdec_cyp in H4.\nrewrite (decode_app _ _ _ _ _ _ Hdec_cyp).\n\nmove Hdec_cmp : (decode compression_methods_type compression_methods0) => dec_cmp.\ndestruct dec_cmp as [ret buf].\ndestruct ret in Hdec_cmp; last first.\n  clear H6.\n  by rewrite /decodep Hdec_cmp in H5.\ndestruct buf in Hdec_cmp; last first.\n  clear H6.\n  by rewrite /decodep Hdec_cmp in H5.\nrewrite (decode_app _ _ _ _ _ _ Hdec_cmp).\n\nmove: H6 => /=.\nmove Htest : (client_extensions_present _ _ _ _) => [] /=.\n- (* extensions present *) move=> H7.\n  case: ifP.\n  + move=> H8.\n    rewrite -(cats0 extensions0).\n    move: H7.\n    rewrite {1}/decodep.\n    move Hdec_ext : (decode _ _) => dec_ext.\n    destruct dec_ext as [ret buf].\n    case/andP.\n    destruct ret => //= _.\n    destruct buf => //= _.\n\n    rewrite /= in Htest.\n    by rewrite (decode_app _ _ _ _ _ _ Hdec_ext).\n  + move=> H8.\n    have X1 : (size\n            (session_id0 ++\n             cipher_suites0 ++ compression_methods0 ++ extensions0) -\n            size\n            (cipher_suites0 ++ compression_methods0 ++ extensions0))%nat = size session_id0.\n      by rewrite !size_cat /= -addnBA // subnn addn0.\n    rewrite X1 in H8.\n    have X2 : (size (cipher_suites0 ++ compression_methods0 ++ extensions0) -\n            size\n            (compression_methods0 ++ extensions0))%nat = size cipher_suites0.\n      by rewrite size_cat -addnBA // subnn addn0.\n    rewrite X2 in H8.\n    have X3 : (size (compression_methods0 ++ extensions0) -\n          size extensions0)%nat = size compression_methods0.\n      by rewrite size_cat -addnBA // subnn addn0.\n    rewrite X3 in H8.\n    exfalso.\n    move: Htest H8.\n    by move=> ->.\n- move=> H7.\n  destruct extensions0 => //=.\n  move: Htest.\n  have -> : (size\n               (session_id0 ++ cipher_suites0 ++ compression_methods0 ++ nil) -\n             size (cipher_suites0 ++ compression_methods0 ++ nil))%nat = size session_id0.\n    by rewrite size_cat -addnBA // subnn addn0.\n  have -> : (size (cipher_suites0 ++ compression_methods0 ++ nil) -\n             size (compression_methods0 ++ nil))%nat = size cipher_suites0.\n    by rewrite size_cat -addnBA // subnn addn0.\n  rewrite subn0 cats0.\n  by move=> ->.\nQed.\n\nEnd S7412.\n\n(** **** 7.4.1.3 Server Hello *)\nModule S7413.\nImport S621 S7412 S61 S44.\nDefinition ServerHello_sz (sid : nat) :=\n  Hello_sz sid + fixed_sz CipherSuite + fixed_sz CompressionMethod.\nDefinition server_extensions_present n (fld1 : nat) :=\n  ServerHello_sz fld1 <? Z<=nat n.\n\nLocal Open Scope select_scope.\n\n(* NB: the length that is embedded in the handshake packet? *)\nStructure ServerHello_packet {n} (Hn : decodep uint24 n) := {\n  server_version : packet (decodep ProtocolVersion) ;\n  random : packet (decodep Random) ;\n  session_id : packet (decodep SessionID) ;\n  cipher_suite : packet (decodep CipherSuite) ;\n  compression_method : packet (decodep CompressionMethod) ;\n  extensions : packet (dselectb( (server_extensions_present (nat<=i8 n) (size session_id)) \\) \\{\n        (false, decodep struct{} ) ;\n        (true, decodep extensions_type)\n      \\})\n}.\n\nLocal Close Scope select_scope.\n\n(* NB : on the model of ClientHellop, no need to pass n/Hn parameters,\n   the server_extensions_present can be decided from the list of bytes *)\nAxiom ServerHellop : forall {n}, decodep uint24 n -> seq byte -> bool.\nEnd S7413.\n\n(** *** 7.4.2 Server Certificate *)\nModule S742.\nDefinition ASN1Cert := opaque `< 1 \\.. 2^24 - 1 `> 3.\nDefinition certificate_list_type := ASN1Cert `< 0 \\.. 2^24 - 1 `> 3.\nDefinition Certificate := struct{\n  (\"certificate_list\", certificate_list_type)\n}.\nDefinition Certificatep := decodep Certificate.\nEnd S742.\n\n(** *** 7.4.3 Server Key Exchange Message *)\nModule S743.\nDefinition dhe_dss := `( 0 )c_8. Definition dhe_rsa := `( 1 )c_8. Definition dh_anon := `( 2 )c_8.\nDefinition rsa := `( 3 )c_8. Definition dh_dss := `( 4 )c_8. Definition dh_rsa := `( 5 )c_8.\nDefinition KeyExchangeAlgorithm := \\enum 1 \\{ dhe_dss :: dhe_rsa :: dh_anon ::\n  rsa :: dh_dss :: dh_rsa :: nil \\}.\nDefinition dh_p_type := opaque `< 1 \\.. 2 ^ 16 - 1 `> 2.\nDefinition dh_g_type := opaque `< 1 \\.. 2 ^ 16 - 1 `> 2.\nDefinition dh_Ys := opaque `< 1 \\.. 2 ^ 16 - 1 `> 2.\nDefinition ServerDHParams :=\n   struct{ (\"dh_p\", dh_p_type) ;\n           (\"dh_g\", dh_g_type) ;\n           (\"dh_Ys\", dh_Ys) }.\nDefinition dhe_dss_rsa_type := struct{\n  (\"params\", ServerDHParams) ;\n  (\"signed_params\", struct{\n    (\"client_random\", opaque \\[ 32 \\]) ;\n    (\"server_random\", opaque \\[ 32 \\]) ;\n    (\"params\", ServerDHParams)\n  }) }.\n\nLocal Open Scope select_scope.\n\nDefinition ServerKeyExchange {n} (Hn : decodep KeyExchangeAlgorithm n) := struct{\n  (\"params\", unpack (select( _ \\: _ \\: Hn\\) \\{\n    (u2Zc dhe_dss, pack dhe_dss_rsa_type) ;\n    (u2Zc dhe_rsa, pack dhe_dss_rsa_type) ;\n    (u2Zc dh_anon, pack ServerDHParams) ;\n    (u2Zc rsa, pack struct{}) ;\n    (u2Zc dh_dss, pack struct{}) ;\n    (u2Zc dh_rsa, pack struct{})\n  \\}))\n}.\n\nLocal Close Scope select_scope.\n\nDefinition ServerKeyExchangep {n} (Hn : decodep KeyExchangeAlgorithm n) :=\n  decodep (ServerKeyExchange Hn).\nEnd S743.\n\n(** *** 7.4.4 Certificate Request *)\nModule S744.\nImport S74141.\nDefinition DistinguishedName := opaque `< 1 \\.. 2 ^ 16 - 1 `> 2.\nDefinition rsa_sign := `( 1 )c_8. Definition dss_sign := `( 2 )c_8. Definition rsa_fixed_dh := `( 3 )c_8.\nDefinition dss_fixed_dh := `( 4 )c_8. Definition rsa_ephemeral_dh_RESERVED := `( 5 )c_8.\nDefinition dss_ephemeral_dh_RESERVED := `( 6 )c_8. Definition fortezza_dms_RESERVED := `( 20 )c_8.\nDefinition ClientCertificateType := \\enum 1 \\{ rsa_sign :: dss_sign :: rsa_fixed_dh ::\n  dss_fixed_dh :: rsa_ephemeral_dh_RESERVED :: dss_ephemeral_dh_RESERVED ::\n  fortezza_dms_RESERVED :: nil \\} 255.\nDefinition CertificateRequest := struct{\n  (\"certificate_types\", ClientCertificateType `< 1 \\.. 2 ^ 8 - 1 `> 1) ;\n  (\"supported_signature_algorithms\", SignatureAndHashAlgorithm `< 0 \\.. 2 ^ 16 - 1 `> 2) ; (* NB: error, the RFC forgot the min *)\n  (\"certificate_authorities\", DistinguishedName `< 0 \\.. 2 ^ 16 - 1 `> 2)\n}.\nDefinition CertificateRequestp := decodep CertificateRequest.\nEnd S744.\n\n(** *** 7.4.5 Server Hello Done *)\nModule S745.\nDefinition ServerHelloDone := struct{}.\nDefinition ServerHelloDonep := decodep ServerHelloDone.\nEnd S745.\n\n(** **** 7.4.7.1 RSA-Encrypted Premaster Secret Message *)\n\nModule S7471.\nImport S621.\nDefinition PreMasterSecret := struct{\n  (\"client_version\", ProtocolVersion) ;\n  (\"random\", opaque \\[ 46 \\]) }.\nDefinition EncryptedPreMasterSecret := struct{\n  (\"pre_master_secret\", PreMasterSecret) }.\nEnd S7471.\n\n(** **** 7.4.7.2 Client Diffie-Hellman Public Value *)\n\nModule S7472.\nDefinition implicit := `( 0 )c_8. Definition explicit := `( 1 )c_8.\nDefinition PublicValueEncoding := \\enum 1 \\{ implicit :: explicit :: nil \\}.\n(* NB: dh_public is also called dh_Yc *)\n\nLocal Open Scope select_scope.\n\nDefinition ClientDiffieHellmanPublic {n} (Hn : decodep PublicValueEncoding n) := struct{\n  (\"dh_public\", unpack (select( _ \\: _ \\: Hn \\) \\{\n    (u2Zc implicit, pack struct{}) ;\n    (u2Zc explicit, pack (opaque `< 1 \\.. 2 ^ 16 - 1 `> 2))\n    \\}))\n  }.\n\nLocal Close Scope select_scope.\n\nEnd S7472.\n\n(** *** 7.4.7 Client Key Exchange Message *)\n\nModule S747.\nImport S743 S7471 S7472.\n\nLocal Open Scope select_scope.\n\nDefinition ClientKeyExchange {n} (Hn : decodep KeyExchangeAlgorithm n) {m} (Hm : decodep PublicValueEncoding m) :=\nstruct{\n  (\"exchange_keys\", unpack (select( _ \\: _ \\: Hn\\) \\{\n    (u2Zc dhe_dss, pack (ClientDiffieHellmanPublic Hm)) ;\n    (u2Zc dhe_rsa, pack (ClientDiffieHellmanPublic Hm)) ;\n    (u2Zc dh_anon, pack (ClientDiffieHellmanPublic Hm)) ;\n    (u2Zc rsa, pack EncryptedPreMasterSecret) ;\n    (u2Zc dh_dss, pack (ClientDiffieHellmanPublic Hm)) ;\n    (u2Zc dh_rsa, pack (ClientDiffieHellmanPublic Hm))\n  \\}))\n}.\n\nLocal Close Scope select_scope.\n\nDefinition ClientKeyExchangep {n} (Hn : decodep KeyExchangeAlgorithm n) {m} (Hm : decodep PublicValueEncoding m) :=\n  decodep (ClientKeyExchange Hn Hm).\nEnd S747.\n\n(** *** 7.4.8 Certificate Verify *)\nModule S748.\nDefinition CertificateVerify (handshake_messages_length : Z) := struct{\n  (\"handshake_messages\", opaque \\[[ handshake_messages_length \\]])\n}.\nDefinition CertificateVerifyp (handshake_messages_length : Z) :=\n  decodep (CertificateVerify handshake_messages_length).\nEnd S748.\n\n(** *** 7.4.9 Finished *)\nModule S749.\nDefinition verify_data_lengthp x := 12 <= x.\nDefinition verify_data_type (verify_data_length : Z(*NB:depends on the cipher suite*)) :=\n  opaque \\[[ verify_data_length \\]].\nDefinition Finished (verify_data_length : Z) := struct{ (\"verify_data\", verify_data_type verify_data_length) }.\nDefinition Finishedp (verify_data_length : Z) := decodep (Finished verify_data_length).\nDefinition Finished_packet (x : Z) := packet (Finishedp x).\nEnd S749.\n\n(** ** 7.4 Handshake Protocol *)\nModule S74.\nDefinition hello_request := `( 0 )c_8.\nDefinition client_hello := `( 1 )c_8.\nDefinition server_hello := `( 2 )c_8.\nDefinition certificate := `( 11 )c_8.\nDefinition server_key_exchange := `( 12 )c_8.\nDefinition certificate_request := `( 13 )c_8.\nDefinition server_hello_done := `( 14 )c_8.\nDefinition certificate_verify := `( 15 )c_8.\nDefinition client_key_exchange := `( 16 )c_8.\nDefinition finished := `( 20 )c_8.\nDefinition HandshakeType := \\enum 1 \\{ hello_request :: client_hello ::\n  server_hello :: certificate :: server_key_exchange :: certificate_request ::\n  server_hello_done :: certificate_verify :: client_key_exchange ::\n  finished :: nil \\} 255.\nImport S44 S7411 S7412 S7413 S742 S743 S744 S745 S747 S748 S749 S7472.\n\nLocal Open Scope select_scope.\n\nDefinition Handshake_packet_helper {n} (Hn : decodep KeyExchangeAlgorithm n)\n  {m} (Hm : decodep PublicValueEncoding m) (verify_data_length handshake_messages_length : Z)\n  (length : packet (decodep uint24)) (msg_type : packet (decodep HandshakeType)) (x : seq byte) :=\n    (dselect( _ \\: _ \\: decodable _ msg_type \\) \\{\n        (u2Zc hello_request, HelloRequestp) ;\n        (u2Zc client_hello, ClientHellop length (*(decodable _ length)*)) ;\n        (u2Zc server_hello, ServerHellop (decodable _ length)) ;\n        (u2Zc certificate, Certificatep) ;\n        (u2Zc server_key_exchange, ServerKeyExchangep Hn) ;\n        (u2Zc certificate_request, CertificateRequestp) ;\n        (u2Zc server_hello_done, ServerHelloDonep) ;\n        (u2Zc certificate_verify, CertificateVerifyp handshake_messages_length) ;\n        (u2Zc client_key_exchange, ClientKeyExchangep Hn Hm) ;\n        (u2Zc finished, Finishedp handshake_messages_length)\n      \\}) x && (size x == nat<=i8 n).\n\nLocal Close Scope select_scope.\n\nStructure Handshake_packet {n} (Hn : decodep KeyExchangeAlgorithm n) {m} (Hm : decodep PublicValueEncoding m)\n  (verify_data_length handshake_messages_length : Z) := {\n  msg_type : packet (decodep HandshakeType) ;\n  length : packet (decodep uint24) ;\n  body : packet (Handshake_packet_helper Hn Hm verify_data_length handshake_messages_length\n    length msg_type)\n}.\n\nDefinition Handshake_header_decode l : bool * seq byte * seq byte :=\n  let (a1, l1) := decode HandshakeType l in\n  let (a2, l2) := decode uint24 l1 in\n  (a1 && a2, take ('|(fixed_sz uint24)|) l1, l2).\n\nDefinition Handshake_hd := fixed_sz HandshakeType + fixed_sz uint24.\nEnd S74.\n\nModule A5.\n\nImport S7412.\n\n(**      CipherSuite TLS_NULL_WITH_NULL_NULL               = { 0x00,0x00 };*)\nDefinition TLS_NULL_WITH_NULL_NULL : CipherSuitePacket := NewCipherSuite [:: \\0x\"00\" ; \\0x\"00\"].\n\nDefinition TLS_RSA_WITH_NULL_MD5 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"01\"].\nDefinition TLS_RSA_WITH_NULL_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"02\"].\nDefinition TLS_RSA_WITH_NULL_SHA256 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"3B\"].\nDefinition TLS_RSA_WITH_RC4_128_MD5 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"04\"].\nDefinition TLS_RSA_WITH_RC4_128_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"05\"].\nDefinition TLS_RSA_WITH_3DES_EDE_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"0A\"].\nDefinition TLS_RSA_WITH_AES_128_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"2F\"].\nDefinition TLS_RSA_WITH_AES_256_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"35\"].\nDefinition TLS_RSA_WITH_AES_128_CBC_SHA256 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"3C\"].\nDefinition TLS_RSA_WITH_AES_256_CBC_SHA256 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"3D\"].\nDefinition TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"0D\"].\nDefinition TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"10\"].\nDefinition TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"13\"].\nDefinition TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"16\"].\nDefinition TLS_DH_DSS_WITH_AES_128_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"30\"].\nDefinition TLS_DH_RSA_WITH_AES_128_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"31\"].\nDefinition TLS_DHE_DSS_WITH_AES_128_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"32\"].\nDefinition TLS_DHE_RSA_WITH_AES_128_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"33\"].\nDefinition TLS_DH_DSS_WITH_AES_256_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"36\"].\nDefinition TLS_DH_RSA_WITH_AES_256_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"37\"].\nDefinition TLS_DHE_DSS_WITH_AES_256_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"38\"].\nDefinition TLS_DHE_RSA_WITH_AES_256_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"39\"].\nDefinition TLS_DH_DSS_WITH_AES_128_CBC_SHA256 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"3E\"].\nDefinition TLS_DH_RSA_WITH_AES_128_CBC_SHA256 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"3F\"].\nDefinition TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"40\"].\nDefinition TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"67\"].\nDefinition TLS_DH_DSS_WITH_AES_256_CBC_SHA256 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"68\"].\nDefinition TLS_DH_RSA_WITH_AES_256_CBC_SHA256 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"69\"].\nDefinition TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"6A\"].\nDefinition TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"6B\"].\nDefinition TLS_DH_anon_WITH_RC4_128_MD5 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"18\"].\nDefinition TLS_DH_anon_WITH_3DES_EDE_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"1B\"].\nDefinition TLS_DH_anon_WITH_AES_128_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"34\"].\nDefinition TLS_DH_anon_WITH_AES_256_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"3A\"].\nDefinition TLS_DH_anon_WITH_AES_128_CBC_SHA256 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"6C\"].\nDefinition TLS_DH_anon_WITH_AES_256_CBC_SHA256 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"6D\"].\n\nEnd A5.\n\nEnd RFC5246.\n\n(** Camellia Cipher Suites for TLS *)\n\nModule RFC5932.\n\nImport RFC5246.\nExport RFC5246.\n\nImport S7412.\n\nDefinition TLS_RSA_WITH_CAMELLIA_128_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"41\"].\nDefinition TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"42\"].\nDefinition TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"43\"].\nDefinition TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"44\"].\nDefinition TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"45\"].\nDefinition TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"46\"].\n\nDefinition TLS_RSA_WITH_CAMELLIA_256_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"84\"].\nDefinition TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"85\"].\nDefinition TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"86\"].\nDefinition TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"87\"].\nDefinition TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"88\"].\nDefinition TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA := NewCipherSuite [:: \\0x\"00\" ; \\0x\"89\"].\n\nDefinition TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"BA\"].\nDefinition TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"BB\"].\nDefinition TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"BC\"].\nDefinition TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"BD\"].\nDefinition TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"BE\"].\nDefinition TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"BF\"].\n\nDefinition TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"C0\"].\nDefinition TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"C1\"].\nDefinition TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"C2\"].\nDefinition TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"C3\"].\nDefinition TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"C4\"].\nDefinition TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256 := NewCipherSuite [:: \\0x\"00\" ; \\0x\"C5\"].\n\nEnd RFC5932.\n\n(** Technical Lemmas *)\n\nModule RFC5246_Prop.\n\nImport RFC5246.\n\nLemma decode_SessionID : forall s h, nat<=u h = size s ->\n  decode S7412.SessionID (h :: s) = (true, nil).\nProof.\nmove=> s h hs.\nrewrite /decode /= take0 drop0.\nhave Htmp : (nat<=u h = nat<=i8 (h :: nil))%nat.\n  by rewrite /(nat<=i8) /MachineIntByte_m.bytes2nat /bSum_c /= -u2ZE -/(nat<=u h) hs.\nrewrite -{}Htmp {}hs leqnn take_size drop_size.\nset f := fun _ _ => _.\nsuff : foldl f (true, s) (nseq (size s) tt) = (true, nil) by move=> ->.\nby elim: s.\nQed.\n\nLemma decode_cipher_suites_type : forall s h1 h2,\n  nat<=i8 (h1 :: h2 :: nil) = size s -> ~~ odd (size s) ->\n  decode S7412.cipher_suites_type (h1 :: h2 :: s) = (true, nil).\nProof.\nmove=> s h1 h2 hs Hodd.\nhave {Hodd}[k Hk] : exists k, size s = k.*2.\n  exists (size s)./2.\n  rewrite -{1}(odd_double_half (size s)).\n  by destruct (odd (size s)).\nrewrite /decode /= take0 drop0 hs leqnn take_size drop_size {hs}.\nset f := fun _ _ => _.\nsuff : foldl f (true, s) (nseq (size s) tt) = (true, nil) by move=> ->.\nhave : foldl f (true, s) (nseq k tt) = (true, nil).\n  elim: k s Hk => [| k IHk [|s1 [|s2 s3]]] //.\n    by destruct s.\n  rewrite doubleS [size _]/=.\n  case=> H.\n  rewrite /f [Z<=nat]lock /= -lock drop0 ifT; last first.\n    by apply/leZP; rewrite 2!Z_S; lia.\n  by apply IHk.\nrewrite Hk.\nmove Htmp : k.*2 => k'.\nhave {Htmp}k'k : (k <= k')%nat by rewrite -Htmp -{1}(muln1 k) -muln2; apply leq_mul.\nelim: k' k k'k s Hk => [| k' IHk' [|k] // kk' s]; first by case.\n  destruct s => //; by apply IHk'.\ndestruct s as [|s1 [|s2 s3]] => //.\nrewrite doubleS [size _]/=.\ncase => Hs.\nrewrite /f [Z<=nat]lock /= -lock ifT; last first.\n  apply/leZP; rewrite 2!Z_S; lia.\nrewrite drop0; by apply IHk'.\nQed.\n\nLemma decode_compression_methods_type : forall h n, n = nat<=u h ->\n  decode S7412.compression_methods_type (h :: nseq n `( 0 )_8) = (true, nil).\nProof.\nmove=> h n nh.\nrewrite /decode /= take0 drop0 size_nseq.\nhave Htmp : (nat<=u h = nat<=i8 (h :: nil))%nat.\n  by rewrite /(nat<=i8) /MachineIntByte_m.bytes2nat /bSum_c /= -u2ZE.\nrewrite -{}Htmp -nh leqnn drop_nseq // subnn /=.\nset f := fun _ _ => _.\nrewrite {1}(_ : n = size (nseq n `( 0 )_8)); last by rewrite size_nseq.\nrewrite take_size {nh}.\nmove Hs : (nseq _ _) => s.\nsuff : foldl f (true, s) (nseq n tt) = (true, nil) by rewrite -{}Hs; move=> ->.\nelim: s n Hs => [|hd tl IH [|n0] //= [H1 H2]].\n  by case.\nrewrite drop0 take0 inE -H1 /S41.bytes2Z /= /MachineIntByte_m.bytes2Z /bSum_c /= -u2ZE Z2uK // eqxx.\nby apply IH.\nQed.\n\nLemma size_CipherSuitePacket (p : S7412.CipherSuitePacket) : size p = 2%nat.\nProof.\ndestruct p as [ [| b [|b0 [|b1 body0]]] decodable0] => //=.\nrewrite /decodep /= /decode /= in decodable0.\nby case: ifP decodable0.\nQed.\n\nEnd RFC5246_Prop.\n\nModule test.\n\nImport RFC5932.\n\nGoal (decode opaque (nseq 1 `( 100 )c_8)) = (true, nil).\nProof. by rewrite /decode /=. Qed.\n\nGoal (decode (opaque \\[ 3 \\]) (nseq 3 `( 100 )c_8)) = (true, nil).\nProof. by rewrite /decode /=. Qed.\n\nGoal decodep S45.Color (S45.white :: nil) = true.\nProof. by []. Qed.\n\nGoal decodep S45.Color (`( 4 )c_8 :: nil) = false.\nProof. by []. Qed.\n\nLocal Open Scope select_scope.\n\nGoal (select( (S461.apple :: nil) \\: S461.VariantTag \\: Logic.eq_refl \\) \\{\n  (u2Zc S461.apple, pack S461.V1) ;\n  (u2Zc S461.orange, pack S461.V2) ;\n  (u2Zc S461.banana, pack S461.V2)\n  \\} ) = pack S461.V1.\nProof. done. Qed.\n\nLocal Close Scope select_scope.\n\nGoal decode S7412.SessionID (`( 3 )c_8 :: nseq 4 `( 100 )c_8) = (true, `( 100 )c_8 :: nil).\nProof. done. Qed.\n\nGoal decodep S7412.SessionID (`( 3 )c_8:: nseq 3 `( 100 )c_8) = true.\nProof. done. Qed.\n\nGoal decode S7412.cipher_suites_type (map (fun x => `( x )c_8) (0 :: 4 :: 1::2 :: 3::4 :: nil)) = (true, nil).\n(*                                          |--| 2nd CipherSuite\n                                    |--| 1st CipherSuite\n                            |--| length of cipher_suites = 4bytes = 2CipherSuite\n\n*)\nProof. by rewrite /decode /=. Qed.\n\nGoal \\0x \"2A\"%string = `( 42 )c_8.\napply u2Z_inj.\nby rewrite /MachineIntByte_m.hex2t /= -!Z2uE (@u2Z_concat 4) /= !u2ZE !Z2uE.\nQed.\n\nGoal \\0x \"F3\"%string = `( 243 )c_8.\napply u2Z_inj.\nby rewrite /MachineIntByte_m.hex2t /= -!Z2uE (@u2Z_concat 4) /= !u2ZE !Z2uE.\nQed.\n\n(*Goal \\0x \"2AF3\"%string = 10995. done. Qed.*)\n\nEnd test.\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/rfc5246.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2917034689353761}}
{"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 A B C D P Q C0 Q0 C1 A0 : Universe, ((wd_ P C0 /\\ (wd_ P Q /\\ (wd_ P Q0 /\\ (wd_ C0 Q0 /\\ (wd_ A B /\\ (wd_ B Q0 /\\ (wd_ A Q0 /\\ (wd_ C0 A /\\ (wd_ C0 B /\\ (wd_ Q C0 /\\ (wd_ B Q /\\ (wd_ A Q /\\ (wd_ C D /\\ (wd_ D P /\\ (wd_ C P /\\ (wd_ C A /\\ (wd_ C B /\\ (wd_ D A /\\ (wd_ D B /\\ (wd_ C1 C0 /\\ (wd_ C0 A0 /\\ (wd_ P A0 /\\ (col_ A B P /\\ (col_ C0 C D /\\ (col_ Q P Q0 /\\ (col_ C D C1 /\\ (col_ A B A0 /\\ col_ P Q0 A0))))))))))))))))))))))))))) -> col_ A B Q0)).\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_0514.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.2916842523142527}}
{"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(** * Types and functions used by the generateInfo function. *)\n\nRequire Import Coqlib.\nRequire Import dp.Sitpn.\nRequire Import dp.SitpnTypes.\nRequire Import dp.SitpnFacts.\nRequire Import NatSet.\nRequire Import ListsDep.\nRequire Import InfosTypes.\nRequire Import GlobalTypes.\nRequire Import String.\n  \nOpen Scope string_scope.\n\n(** ** Informations about places. *)\n\nSection PlaceInfos.\n\n  Variable sitpn : Sitpn.\n\n  (** Returns a couple of lists [(i, o)] where [i] is the list of\n      input transitions of [p], and [o] is the list of output\n      transitions of [p].\n\n      Correctness: Correct iff all input transitions of [p] are in\n      [i], and [i] has no duplicate, and all output transitions of [p]\n      are in [o] and [o] has no duplicate.  *)\n\n  Definition get_neighbors_of_p (p : P sitpn) : optionE (list (T sitpn) * list (T sitpn)) :=\n    (* Adds the transition t to the list of input or output\n       transitions of p. *)\n    let get_neighbor_of_p :=\n        (fun (tin_tout : (list (T sitpn) * list (T sitpn))) t =>\n           let (tin, tout) := tin_tout in\n           match post t p, pre p t with\n           | Some _, Some (_, _) => ((tin ++ [t])%list, (tout ++ [t])%list)\n           | Some _, None => ((tin ++ [t])%list, tout)\n           | None, Some (_, _) => (tin, (tout ++ [t])%list)\n           | None, None => tin_tout\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    match tfold_left get_neighbor_of_p (T2List sitpn) (nil, nil) nat_to_T with\n    | (nil, nil) => Err (\"Place \" ++ $$p ++ \" is an isolated place.\")\n    | tin_tout => Success tin_tout\n    end.\n\n  (** Injects transition [t] in the list [stranss] depending on the\n      level of priority of [t] compared to the elements of the list\n      [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    optionE (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 highest\n       priority. *)\n    | [] => Success [t]\n\n    (* If there is a head element, compares the head element with t\n     priority-wise. *)\n    | x :: tl =>\n\n      (* If t and x are the same, then t has already been injected in\n       stranss, then stranss is returned. That case does not happen\n       given a proof of [~In t stranss], that is, t is not among \n       the first elements of stranss.\n\n       Otherwise, checks if t has a higher firing priority than x. *)\n      if Teqdec t x then Success stranss                                     \n      else\n        (* If t is the element with the highest priority, then puts it\n           as the head element of stranss, and returns the list.\n         \n         Otherwise, checks if x has a higher priority than t.  *)\n        if t >~ x then Success (t :: stranss)\n        else\n          (* If x has a higher priority than t, then tries to inject t\n           in the list's tail.  *)\n          if x >~ t then\n            match inject_t t tl with\n            | Success stranss' => Success (x :: stranss')\n            (* Error case: found a transition that is not comparable with\n               t in the list's tail.\n             *)\n            | Err msg => Err msg\n            end\n          else\n            (* Error case: t >~ x and x >~ t evaluate to false. *)\n            Err (\"Transitions \" ++ $$t ++ \" and \" ++ $$x ++ \" are not comparable with the priority relation.\")\n    end.\n\n  (** Injects all transitions of the [transs] list in the list [stranss]\n      that contains transitions sorted by level of firing priority.  *)\n\n  Fixpoint sort_by_priority_aux\n           (transs : list (T sitpn))\n           (stranss : list (T sitpn)) {struct transs} :\n    optionE (list (T sitpn)) :=\n    match transs with\n    | [] => Success stranss\n    | t :: tl => match inject_t t stranss with\n                 | Success stranss' =>\n                   sort_by_priority_aux tl stranss'\n                 | Err msg => Err msg\n                 end\n    end.\n\n  (** Takes a list of transitions [transs], and returns a new list of\n      transitions where the elements are ordered by level of firing\n      priority.\n\n      Raises an error if no strict total ordering can be established\n      in relation to the priority order.  *)\n\n  Definition sort_by_priority (transs : list (T sitpn)) :\n    optionE (list (T sitpn)) := sort_by_priority_aux transs [].\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 get_p_info (p : P sitpn) : optionE (P sitpn * PlaceInfo sitpn) :=\n\n    (* Gets the input and output transitions list of place p. *)\n    match get_neighbors_of_p p with\n    (* Error case: p is an isolated place. *)\n    | Err msg => Err msg\n    | Success (tin, tout) =>\n      (* Sorts the output transitions of p by decreasing level of firing\n         priority. *)\n      match sort_by_priority tout with\n      | Success stout => Success (p, MkPlaceInfo _ tin stout)\n      (* Error case: the priority relation is not a strict total order\n         over the output transitions of p. *)\n      | Err msg => Err msg\n      end\n    end.\n\n  (** Computes information for all p ∈ P, and returns the list of\n      couples implementing function P → PlaceInfo. *)\n  \n  Definition generate_place_infos : optionE (list (P sitpn * PlaceInfo sitpn)) :=    \n    topte_map get_p_info (P2List sitpn) nat_to_P.\n  \nEnd PlaceInfos.\n\n(** ** Informations about transitions. *)\n\nSection TransitionInfos.\n\n  Variable sitpn : Sitpn.\n  \n  (** Returns the list of input places of transition [t].\n\n    Correctness: Correct iff all input places of [p] are in the\n    returned list, and the returned 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   *)\n\n  Definition get_inputs_of_t (t : T sitpn) : 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    tfilter is_input_of_t (P2List sitpn) nat_to_P.\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) : 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    tfilter is_cond_of_t (C2List sitpn) nat_to_C.\n\n  (** Computes the information about transition t, and returns\n    a couple [(t, info)].\n   *)\n\n  Definition get_t_info (t : T sitpn) : (T sitpn * TransInfo sitpn) :=\n    (t, MkTransInfo _ (get_inputs_of_t t) (get_conds_of_t t)).\n\n  (** Maps the function [get_t_info] to the list of transitions of [sitpn],\n      and returns the resulting list of couples [(t, info)]. *)\n\n  Definition generate_trans_infos : list (T sitpn * TransInfo sitpn) :=\n    tmap get_t_info (T2List sitpn) nat_to_T.\n  \nEnd TransitionInfos.\n\nArguments generate_trans_infos {sitpn}.\n\n(** ** Informations about conditions, actions and functions. *)\n\nSection InterpretationInfos.\n\n  Variable sitpn : Sitpn.\n  \n  (** Returns the list of transitions associated to condition [c]. *)\n\n  Definition get_transs_of_c (c : C sitpn) : 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    tfilter is_trans_of_c (T2List sitpn) nat_to_T.\n\n  (** Returns the list of transitions associated to function [f]. *)\n\n  Definition get_transs_of_f (f : F sitpn) : list (T sitpn) :=\n    tfilter (fun t => has_F t f) (T2List sitpn) nat_to_T.\n\n  (** Returns the list of places associated to action [a]. *)\n\n  Definition get_places_of_a (a : A sitpn) : list (P sitpn) :=\n    tfilter (fun p => has_A p a) (P2List sitpn) nat_to_P.\n\n  (** Maps the function [get_transs_of_c] to the list of conditions of\n      [sitpn]. Returns the resulting list of couples [(c, transs_of_c)]. *)\n  \n  Definition generate_cond_infos : list (C sitpn * list (T sitpn)) :=\n    tmap (fun c => (c, get_transs_of_c c)) (C2List sitpn) nat_to_C.\n\n  (** Maps the function [get_transs_of_f] to the list of functions of\n      [sitpn]. Returns the resulting list of couples [(f, transs_of_f)]. *)\n  \n  Definition generate_fun_infos : list (F sitpn * list (T sitpn)) :=\n    tmap (fun f => (f, get_transs_of_f f)) (F2List sitpn) nat_to_F.\n\n  (** Maps the function [get_places_of_a] to the list of actions of\n      [sitpn]. Returns the resulting list of couples [(a, places_of_a)]. *)\n  \n  Definition generate_action_infos : list (A sitpn * list (P sitpn)) :=\n    tmap (fun a => (a, get_places_of_a a)) (A2List sitpn) nat_to_A.\n  \nEnd InterpretationInfos.\n\nArguments generate_cond_infos {sitpn}.\nArguments generate_action_infos {sitpn}.\nArguments generate_fun_infos {sitpn}.\n\n(** ** Informations about an Sitpn. *)\n\nSection SitpnInfos.\n\n  Variable sitpn : Sitpn.\n\n  (** Returns an SitpnInfo instance computed from [sitpn]. *)\n  \n  Definition generate_sitpn_infos : optionE (SitpnInfo sitpn) :=\n    (* Raises an error if sitpn has an empty set of places or transitions. *)\n    if NatSet.is_empty (places sitpn) then\n      Err \"Found an empty set of places.\"\n    else\n      if NatSet.is_empty (transitions sitpn) then\n        Err \"Found an empty set of transitions.\"\n      else\n        (* Otherwise, generates information about sitpn. *)\n        match generate_place_infos sitpn with\n        | Success pinfos =>\n          let tinfos := generate_trans_infos in\n          let cinfos := generate_cond_infos in\n          let ainfos := generate_action_infos in\n          let finfos := generate_fun_infos in\n          Success (MkSitpnInfo _ pinfos tinfos cinfos ainfos finfos)\n        (* Error case: propagates the error raised by generate_place_infos. *)\n        | Err msg => Err msg\n        end.\n  \nEnd SitpnInfos.\n\n", "meta": {"author": "viampietro", "repo": "sitpns", "sha": "9b81ca8a3299c51df561c42f40bc8bb42329446a", "save_path": "github-repos/coq/viampietro-sitpns", "path": "github-repos/coq/viampietro-sitpns/sitpns-9b81ca8a3299c51df561c42f40bc8bb42329446a/sitpn/dp/GenerateInfos.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.29160306396331875}}
{"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.\n\n(******************************************************************************)\n(* Reducibility of configurations number 623 to 633, whose indices in         *)\n(* the_configs range over segment [622, 633); it's end of the list.           *)\n(******************************************************************************)\n\nLemma red622to633 : reducible_in_range 622 633 the_configs.\nProof. CheckReducible. Qed.\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/job623to633.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.29160306396331875}}
{"text": "Require Import Coq.Lists.List. Import ListNotations.\nRequire Import Coq.ZArith.ZArith Coq.micromega.Lia.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nRequire Import Crypto.Util.Tactics.DestructHead.\nRequire Import Crypto.Util.ListUtil.\nRequire Import Crypto.Util.IdfunWithAlt.\nRequire Import Crypto.Util.LetIn.\nRequire Crypto.Util.Tuple. Local Notation tuple := Tuple.tuple.\nLocal Open Scope Z_scope.\n\nCreate HintDb push_id discriminated.\nCreate HintDb uncps discriminated.\n\nLemma push_id {A} (a:A) : id a = a. reflexivity. Qed.\nHint Rewrite @push_id : push_id.\n\nDefinition id_with_alt_cps' {R A} (value value_for_alt : (A -> A) -> A) (f : A -> R) : R\n  := dlet z := id_with_alt (value id) (value_for_alt id) in\n     f z.\nDefinition id_with_alt_cps'' {R A} (value value_for_alt : (A -> R) -> R) (f : A -> R) : R\n  := id_with_alt (value f) (value_for_alt f).\nDefinition id_with_alt_cps {R A} (value value_for_alt : forall R, (A -> R) -> R) (f : A -> R) : R\n  := id_with_alt_cps' (value _) (value_for_alt _) f.\nDefinition id_with_alt_cps'_correct {R A} value value_for_alt f\n  : @id_with_alt_cps' R A value value_for_alt f = f (id_with_alt (value id) (value_for_alt id))\n  := eq_refl.\nHint Rewrite @id_with_alt_cps'_correct : uncps.\nDefinition id_with_alt_cps''_correct {R A} value value_for_alt f\n  : @id_with_alt_cps'' R A value value_for_alt f = id_with_alt (value f) (value_for_alt f)\n  := eq_refl.\nHint Rewrite @id_with_alt_cps''_correct : uncps.\nDefinition id_with_alt_cps_correct {R A} value value_for_alt f\n  : @id_with_alt_cps R A value value_for_alt f = f (id_with_alt (value _ id) (value_for_alt _ id))\n  := eq_refl.\nHint Rewrite @id_with_alt_cps_correct : uncps.\nDefinition id_with_alt_cps'_correct_gen {R A} (value value_for_alt : forall R, (A -> R) -> R) f\n  : @id_with_alt_cps' R A (value _) (value_for_alt _) f = f (id_with_alt (value _ id) (value_for_alt _ id))\n  := eq_refl.\nHint Rewrite @id_with_alt_cps'_correct_gen : uncps.\nDefinition id_with_alt_cps''_correct_gen {R A} (value value_for_alt : forall R, (A -> R) -> R) f\n           (Hvalue : value _ f = f (value _ id))\n  : @id_with_alt_cps'' R A (value _) (value_for_alt _) f = f (id_with_alt (value _ id) (value_for_alt _ id)).\nProof.\n  cbv [id_with_alt_cps'' id_with_alt]; assumption.\nDefined.\nHint Rewrite @id_with_alt_cps''_correct_gen : uncps.\n\nDefinition id_tuple'_with_alt_cps' {R A n}\n           (value value_for_alt : (Tuple.tuple' A n -> Tuple.tuple' A n) -> Tuple.tuple' A n)\n           (f : Tuple.tuple' A n -> R)\n  : R\n  := dlet z := id_tuple'_with_alt (value id) (value_for_alt id) in\n     f z.\nDefinition id_tuple_with_alt_cps' {R A n}\n           (value value_for_alt : (Tuple.tuple A n -> Tuple.tuple A n) -> Tuple.tuple A n)\n           (f : Tuple.tuple A n -> R)\n  : R\n  := dlet z := id_tuple_with_alt (value id) (value_for_alt id) in\n     f z.\n\nDefinition id_tuple'_with_alt_cps'_correct {R A n} value value_for_alt f\n  : @id_tuple'_with_alt_cps' R A n value value_for_alt f = f (id_tuple'_with_alt (value id) (value_for_alt id))\n  := eq_refl.\nHint Rewrite @id_tuple'_with_alt_cps'_correct : uncps.\n\nDefinition id_tuple_with_alt_cps'_correct {R A n} value value_for_alt f\n  : @id_tuple_with_alt_cps' R A n value value_for_alt f = f (id_tuple_with_alt (value id) (value_for_alt id))\n  := eq_refl.\nHint Rewrite @id_tuple_with_alt_cps'_correct : uncps.\n\nDefinition id_tuple'_with_alt_cps'' {R A n}\n           (value value_for_alt : (Tuple.tuple' A n -> R) -> R)\n           (f : Tuple.tuple' A n -> R)\n  : R\n  := id_with_alt (value f) (value_for_alt f).\nDefinition id_tuple_with_alt_cps'' {R A n}\n           (value value_for_alt : (Tuple.tuple A n -> R) -> R)\n           (f : Tuple.tuple A n -> R)\n  : R\n  := id_with_alt (value f) (value_for_alt f).\n\nDefinition id_tuple'_with_alt_cps''_correct {R A n} value value_for_alt f\n  : @id_tuple'_with_alt_cps'' R A n value value_for_alt f = id_with_alt (value f) (value_for_alt f)\n  := eq_refl.\nHint Rewrite @id_tuple'_with_alt_cps''_correct : uncps.\n\nDefinition id_tuple_with_alt_cps''_correct {R A n} value value_for_alt f\n  : @id_tuple_with_alt_cps'' R A n value value_for_alt f = id_with_alt (value f) (value_for_alt f)\n  := eq_refl.\nHint Rewrite @id_tuple_with_alt_cps''_correct : uncps.\n\nDefinition id_tuple'_with_alt_cps''_correct_gen {R A n}\n           (value value_for_alt : forall R, (_ -> R) -> R) f\n           (Hvalue : value _ f = f (value _ id))\n  : @id_tuple'_with_alt_cps'' R A n (value _) (value_for_alt _) f = f (id_tuple'_with_alt (value _ id) (value_for_alt _ id)).\nProof.\n  autorewrite with uncps.\n  rewrite ?unfold_id_tuple'_with_alt, ?unfold_id_tuple_with_alt, ?unfold_id_with_alt, Hvalue.\n  reflexivity.\nQed.\nHint Rewrite @id_tuple'_with_alt_cps''_correct_gen : uncps.\n\nDefinition id_tuple_with_alt_cps''_correct_gen {R A n}\n           (value value_for_alt : forall R, (_ -> R) -> R) f\n           (Hvalue : value _ f = f (value _ id))\n  : @id_tuple_with_alt_cps'' R A n (value _) (value_for_alt _) f = f (id_tuple_with_alt (value _ id) (value_for_alt _ id)).\nProof.\n  autorewrite with uncps.\n  rewrite ?unfold_id_tuple_with_alt, ?unfold_id_tuple_with_alt, ?unfold_id_with_alt, Hvalue.\n  reflexivity.\nQed.\nHint Rewrite @id_tuple_with_alt_cps''_correct_gen : uncps.\n\nDefinition id_tuple'_with_alt_cps {R A n}\n           (value value_for_alt : forall R, (Tuple.tuple' A n -> R) -> R)\n           (f : Tuple.tuple' A n -> R)\n  : R\n  := id_tuple'_with_alt_cps' (value _) (value_for_alt _) f.\nDefinition id_tuple_with_alt_cps {R A n}\n           (value value_for_alt : forall R, (Tuple.tuple A n -> R) -> R)\n           (f : Tuple.tuple A n -> R)\n  : R\n  := id_tuple_with_alt_cps' (value _) (value_for_alt _) f.\n\nDefinition id_tuple'_with_alt_cps_correct {R A n} value value_for_alt f\n  : @id_tuple'_with_alt_cps R A n value value_for_alt f = f (id_tuple'_with_alt (value _ id) (value_for_alt _ id))\n  := eq_refl.\nHint Rewrite @id_tuple'_with_alt_cps_correct : uncps.\n\nDefinition id_tuple_with_alt_cps_correct {R A n} value value_for_alt f\n  : @id_tuple_with_alt_cps R A n value value_for_alt f = f (id_tuple_with_alt (value _ id) (value_for_alt _ id))\n  := eq_refl.\nHint Rewrite @id_tuple_with_alt_cps_correct : uncps.\n\nLemma update_nth_id {T} i (xs:list T) : ListUtil.update_nth i id xs = xs.\nProof.\n  revert xs; induction i; destruct xs; simpl; solve [ trivial | congruence ].\nQed.\n\nLemma map_fst_combine {A B} (xs:list A) (ys:list B) : List.map fst (List.combine xs ys) = List.firstn (length ys) xs.\nProof.\n  revert xs; induction ys; destruct xs; simpl; solve [ trivial | congruence ].\nQed.\n\nLemma map_snd_combine {A B} (xs:list A) (ys:list B) : List.map snd (List.combine xs ys) = List.firstn (length xs) ys.\nProof.\n  revert xs; induction ys; destruct xs; simpl; solve [ trivial | congruence ].\nQed.\n\nLemma nth_default_seq_inbouns d s n i (H:(i < n)%nat) :\n  List.nth_default d (List.seq s n) i = (s+i)%nat.\nProof.\n  progress cbv [List.nth_default].\n  rewrite ListUtil.nth_error_seq.\n  break_innermost_match; solve [ trivial | lia ].\nQed.\n\nLemma mod_add_mul_full a b c k m : m <> 0 -> c mod m = k mod m ->\n                                   (a + b * c) mod m = (a + b * k) mod m.\nProof.\n  intros; rewrite Z.add_mod, Z.mul_mod by auto.\n  match goal with H : _ mod _ = _ mod _ |- _ => rewrite H end.\n  rewrite <-Z.mul_mod, <-Z.add_mod by auto; reflexivity.\nQed.\n\nFixpoint map_cps {A B} (g : A->B) ls\n         {T} (f:list B->T):=\n  match ls with\n  | nil => f nil\n  | a :: t => map_cps g t (fun r => f (g a :: r))\n  end.\nLemma map_cps_correct {A B} g ls: forall {T} f,\n    @map_cps A B g ls T f = f (map g ls).\nProof. induction ls as [|?? IHls]; simpl; intros; rewrite ?IHls; reflexivity. Qed.\nHint Rewrite @map_cps_correct : uncps.\n\nFixpoint map_cps2 {A B} (g : A->forall T, (B -> T) -> T) ls\n         {T} (f:list B->T) : T:=\n  match ls with\n  | nil => f nil\n  | a :: t => map_cps2 g t (fun r => g a _ (fun ga => f (ga :: r)))\n  end.\nLemma map_cps2_correct {A B} g g' (Hg : forall T k a, g a T k = k (g' a)) ls : forall {T} f,\n    @map_cps2 A B g ls T f = f (map g' ls).\nProof. induction ls as [|?? IHls]; simpl; intros; rewrite ?IHls, ?Hg; reflexivity. Qed.\n\nDefinition firstn_cps {A} (n:nat) (l:list A) {T} (f:list A->T) :=\n  match n with\n  | O => f nil\n  | S n' => match l with\n            | nil => f nil\n            | a :: l' => f (a :: firstn n' l')\n            end\n  end.\nLemma firstn_cps_correct {A} n l T f :\n  @firstn_cps A n l T f = f (firstn n l).\nProof. induction n; destruct l; reflexivity. Qed.\nHint Rewrite @firstn_cps_correct : uncps.\n\nFixpoint flat_map_cps_specialized {T A B} (g:A->(list B->T)->T) (ls : list A) (f:list B->T)  :=\n  match ls with\n  | nil => f nil\n  | (x::tl)%list => g x (fun r => flat_map_cps_specialized g tl (fun rr => f (r ++ rr))%list)\n  end.\n\nDefinition flat_map_cps {A B} (g:A->forall {T}, (list B->T)->T) (ls : list A) {T} (f:list B->T)\n  := @flat_map_cps_specialized T A B (fun a => @g a T) ls f.\nLemma unfold_flat_map_cps {A B} (g:A->forall {T}, (list B->T)->T) (ls : list A) {T} (f:list B->T)\n  : @flat_map_cps A B g ls T f\n    = match ls with\n      | nil => f nil\n      | (x::tl)%list => g x (fun r => flat_map_cps g tl (fun rr => f (r ++ rr))%list)\n      end.\nProof. destruct ls; reflexivity. Qed.\nLemma flat_map_cps_correct {A B} (g:A->forall {T}, (list B->T)->T) ls :\n  forall {T} (f:list B->T),\n    (forall x T h, @g x T h = h (g x id)) ->\n    @flat_map_cps A B g ls T f = f (List.flat_map (fun x => g x id) ls).\nProof.\n  induction ls as [|?? IHls]; intros T f H; [reflexivity|].\n  rewrite unfold_flat_map_cps. simpl @flat_map.\n  rewrite H; erewrite IHls by eassumption.\n  reflexivity.\nQed.\nHint Rewrite @flat_map_cps_correct using (intros; autorewrite with uncps; auto): uncps.\n\nFixpoint from_list_default'_cps {A} (d y:A) n xs {T}:\n  (Tuple.tuple' A n -> T) -> T:=\n  match n as n0 return ((Tuple.tuple' A n0 ->T) ->T) with\n  | O => fun f => f y\n  | S n' => fun f =>\n              match xs with\n              | nil => from_list_default'_cps d d n' nil (fun r => f (r, y))\n              | x :: xs' => from_list_default'_cps d x n' xs' (fun r => f (r, y))\n              end\n  end.\nLemma from_list_default'_cps_correct {A} n : forall d y l {T} f,\n    @from_list_default'_cps A d y n l T f = f (Tuple.from_list_default' d y n l).\nProof.\n  induction n as [|? IHn]; intros; simpl; [reflexivity|].\n  break_match; subst; apply IHn.\nQed.\nDefinition from_list_default_cps {A} (d:A) n (xs:list A) {T} :\n  (Tuple.tuple A n -> T) -> T:=\n  match n as n0 return ((Tuple.tuple A n0 ->T) ->T) with\n  | O => fun f => f tt\n  | S n' => fun f =>\n              match xs with\n              | nil => from_list_default'_cps d d n' nil f\n              | x :: xs' => from_list_default'_cps d x n' xs' f\n              end\n  end.\nLemma from_list_default_cps_correct {A} n : forall d l {T} f,\n    @from_list_default_cps A d n l T f = f (Tuple.from_list_default d n l).\nProof.\n  destruct n; intros; simpl; [reflexivity|].\n  break_match; auto using from_list_default'_cps_correct.\nQed.\nHint Rewrite @from_list_default_cps_correct : uncps.\nFixpoint to_list'_cps {A} n\n         {T} (f:list A -> T) : Tuple.tuple' A n -> T :=\n  match n as n0 return (Tuple.tuple' A n0 -> T) with\n  | O => fun x => f [x]\n  | S n' => fun (xs: Tuple.tuple' A (S n')) =>\n              let (xs', x) := xs in\n              to_list'_cps n' (fun r => f (x::r)) xs'\n  end.\nLemma to_list'_cps_correct {A} n: forall t {T} f,\n    @to_list'_cps A n T f t = f (Tuple.to_list' n t).\nProof.\n  induction n; simpl; intros; [reflexivity|].\n  destruct_head prod. apply IHn.\nQed.\nDefinition to_list_cps' {A} n {T} (f:list A->T)\n  : Tuple.tuple A n -> T :=\n  match n as n0 return (Tuple.tuple A n0 ->T) with\n  | O => fun _ => f nil\n  | S n' => to_list'_cps n' f\n  end.\nDefinition to_list_cps {A} n t {T} f :=\n  @to_list_cps' A n T f t.\nLemma to_list_cps_correct {A} n t {T} f :\n  @to_list_cps A n t T f = f (Tuple.to_list n t).\nProof. cbv [to_list_cps to_list_cps' Tuple.to_list]; break_match; auto using to_list'_cps_correct. Qed.\nHint Rewrite @to_list_cps_correct : uncps.\n\nDefinition on_tuple_cps {A B} (d:B) (g:list A ->forall {T},(list B->T)->T) {n m}\n           (xs : Tuple.tuple A n) {T} (f:tuple B m ->T) :=\n  to_list_cps n xs (fun r => g r (fun rr => from_list_default_cps d m rr f)).\nLemma on_tuple_cps_correct {A B} d (g:list A -> forall {T}, (list B->T)->T)\n      {n m} xs {T} f\n      (Hg : forall x {T} h, @g x T h = h (g x id)) : forall H,\n    @on_tuple_cps A B d g n m xs T f = f (@Tuple.on_tuple A B (fun x => g x id) n m H xs).\nProof.\n  cbv [on_tuple_cps Tuple.on_tuple]; intros H.\n  rewrite to_list_cps_correct, Hg, from_list_default_cps_correct.\n  rewrite (Tuple.from_list_default_eq _ _ _ (H _ (Tuple.length_to_list _))).\n  reflexivity.\nQed.  Hint Rewrite @on_tuple_cps_correct using (intros; autorewrite with uncps; auto): uncps.\n\nFixpoint update_nth_cps {A} n (g:A->A) xs {T} (f:list A->T) :=\n  match n with\n  | O =>\n    match xs with\n    | [] => f []\n    | x' :: xs' => f (g x' :: xs')\n    end\n  | S n' =>\n    match xs with\n    | [] => f []\n    | x' :: xs' => update_nth_cps n' g xs' (fun r => f (x' :: r))\n    end\n  end.\nLemma update_nth_cps_correct {A} n g: forall xs T f,\n    @update_nth_cps A n g xs T f = f (update_nth n g xs).\nProof. induction n; intros; simpl; break_match; try apply IHn; reflexivity. Qed.\nHint Rewrite @update_nth_cps_correct : uncps.\n\nFixpoint combine_cps {A B} (la :list A) (lb : list B)\n         {T} (f:list (A*B)->T) :=\n  match la with\n  | nil => f nil\n  | a :: tla =>\n    match lb with\n    | nil => f nil\n    | b :: tlb => combine_cps tla tlb (fun lab => f ((a,b)::lab))\n    end\n  end.\nLemma combine_cps_correct {A B} la: forall lb {T} f,\n    @combine_cps A B la lb T f = f (combine la lb).\nProof.\n  induction la; simpl combine_cps; simpl combine; intros;\n    try break_match; try apply IHla; reflexivity.\nQed.\nHint Rewrite @combine_cps_correct: uncps.\n\n(* differs from fold_right_cps in that the functional argument `g` is also a CPS function *)\nLocal Set Universe Polymorphism.\nDefinition fold_right_cps2_specialized_step\n           (fold_right_cps2_specialized\n            : forall {T A B} (g : B -> A -> (A->T)->T) (a0 : A) (l : list B) (f : A -> T), _)\n           {T A B} (g : B -> A -> (A->T)->T) (a0 : A) (l : list B) (f : A -> T) :=\n  match l with\n  | nil => f a0\n  | b :: tl => fold_right_cps2_specialized g a0 tl (fun r => g b r f)\n  end.\nFixpoint fold_right_cps2_specialized {T A B} (g : B -> A -> (A->T)->T) (a0 : A) (l : list B) (f : A -> T) :=\n  @fold_right_cps2_specialized_step (@fold_right_cps2_specialized) T A B g a0 l f.\nDefinition fold_right_cps2 {A B} (g : B -> A -> forall {T}, (A->T)->T) (a0 : A) (l : list B) {T} (f : A -> T) :=\n  @fold_right_cps2_specialized T A B (fun b a => @g b a T) a0 l f.\nLocal Unset Universe Polymorphism.\nLemma unfold_fold_right_cps2 {A B} (g : B -> A -> forall {T}, (A->T)->T) (a0 : A) (l : list B) {T} (f : A -> T)\n  : @fold_right_cps2 A B g a0 l T f\n    = match l with\n      | nil => f a0\n      | b :: tl => fold_right_cps2 g a0 tl (fun r => g b r f)\n      end.\nProof. destruct l; reflexivity. Qed.\nLemma fold_right_cps2_correct {A B} g a0 l : forall {T} f,\n  (forall b a T h, @g b a T h = h (@g b a A id)) ->\n  @fold_right_cps2 A B g a0 l T f = f (List.fold_right (fun b a => @g b a A id) a0 l).\nProof.\n  induction l as [|?? IHl]; intros T f H; [reflexivity|].\n  rewrite unfold_fold_right_cps2. simpl fold_right.\n  rewrite H; erewrite IHl by eassumption.\n  rewrite H; reflexivity.\nQed.\nHint Rewrite @fold_right_cps2_correct using (intros; autorewrite with uncps; auto): uncps.\n\nDefinition fold_right_no_starter {A} (f:A->A->A) ls : option A :=\n  match ls with\n  | nil => None\n  | cons x tl => Some (List.fold_right f x tl)\n  end.\nLemma fold_right_min ls x :\n  x = List.fold_right Z.min x ls\n  \\/ List.In (List.fold_right Z.min x ls) ls.\nProof.\n  induction ls; intros; simpl in *; try tauto.\n  match goal with |- context [Z.min ?x ?y] =>\n                  destruct (Z.min_spec x y) as [[? Hmin]|[? Hmin]]\n  end; rewrite Hmin; tauto.\nQed.\nLemma fold_right_no_starter_min ls : forall x,\n    fold_right_no_starter Z.min ls = Some x ->\n    List.In x ls.\nProof.\n  cbv [fold_right_no_starter]; intros; destruct ls; try discriminate.\n  inversion H; subst; clear H.\n  destruct (fold_right_min ls z);\n    simpl List.In; tauto.\nQed.\nFixpoint fold_right_cps {A B} (g:B->A->A) (a0:A) (l:list B) {T} (f:A->T) :=\n  match l with\n  | nil => f a0\n  | cons a tl => fold_right_cps g a0 tl (fun r => f (g a r))\n  end.\nLemma fold_right_cps_correct {A B} g a0 l: forall {T} f,\n    @fold_right_cps A B g a0 l T f = f (List.fold_right g a0 l).\nProof. induction l as [|? l IHl]; intros; simpl; rewrite ?IHl; auto. Qed.\nHint Rewrite @fold_right_cps_correct : uncps.\n\nDefinition fold_right_no_starter_cps {A} g ls {T} (f:option A->T) :=\n  match ls with\n  | nil => f None\n  | cons x tl => f (Some (List.fold_right g x tl))\n  end.\nLemma fold_right_no_starter_cps_correct {A} g ls {T} f :\n  @fold_right_no_starter_cps A g ls T f = f (fold_right_no_starter g ls).\nProof.\n  cbv [fold_right_no_starter_cps fold_right_no_starter]; break_match; reflexivity.\nQed.\nHint Rewrite @fold_right_no_starter_cps_correct : uncps.\n\nImport Tuple.\n\nModule Tuple.\n  Fixpoint map_cps {A B n} (g : A->B) (t : tuple A n) {T} :\n    (tuple B n->T) -> T:=\n  match n return tuple A n -> (tuple B n -> T) -> T with\n  | O => fun _ f => f tt\n  | S n' => fun t f => map_cps g (tl t) (fun r => f (append (g (hd t)) r))\n  end t.\n  Lemma map_cps_correct {A B n} g t: forall {T} f,\n      @map_cps A B n g t T f = f (map g t).\n  Proof.\n    induction n; simpl map_cps; intros; try destruct t;\n    [|rewrite IHn, <-map_append,<-subst_append]; reflexivity.\n  Qed. Hint Rewrite @map_cps_correct : uncps.\n\n  Fixpoint map2_cps {n A B C} (g:A->B->C) (xs:tuple A n) (ys:tuple B n) {T} :\n    (tuple C n->T) -> T :=\n    match n return tuple _ n -> tuple _ n -> (tuple C n -> T) -> T with\n    | O => fun _ _ f => f tt\n    | S n' => fun xs ys f =>\n                map2_cps g (tl xs) (tl ys) (fun zs => f (append (g (hd xs) (hd ys)) zs))\n    end xs ys.\n  Lemma map2_cps_correct {n A B C} g xs ys : forall {T} f,\n      @map2_cps n A B C g xs ys T f = f (map2 g xs ys).\n  Proof.\n    induction n; simpl map2_cps; intros; try destruct xs, ys;\n    [|rewrite IHn, <-map2_append,<-!subst_append]; reflexivity.\n  Qed. Hint Rewrite @map2_cps_correct : uncps.\n\n  Section internal_mapi_with_cps.\n    (* We define fixpoints with fewer parameters to the internal [fix] to allow unfolding to partially specialize them *)\n    Context {R T A B : Type}\n            (f: nat->T->A->(T*B->R)->R).\n\n    Fixpoint mapi_with'_cps_specialized {n} i\n             (start:T)\n      : Tuple.tuple' A n -> (T * tuple' B n -> R) -> R :=\n      match n as n0 return (tuple' A n0 -> (T * tuple' B n0->R)->R) with\n      | O => fun ys ret => f i start ys ret\n      | S n' => fun ys ret =>\n                  f i start (hd ys) (fun sb =>\n                  mapi_with'_cps_specialized (S i) (fst sb) (tl ys)\n                      (fun r => ret (fst r, (snd r, snd sb))))\n      end.\n  End internal_mapi_with_cps.\n\n  Definition mapi_with'_cps {T A B n} i\n          (f: nat->T->A->forall {R}, (T*B->R)->R) (start:T)\n    : Tuple.tuple' A n -> forall {R}, (T * tuple' B n -> R) -> R\n    := fun ts {R} => @mapi_with'_cps_specialized R T A B (fun n t a => @f n t a R) n i start ts.\n\n  Definition mapi_with_cps {S A B n}\n          (f: nat->S->A->forall {T}, (S*B->T)->T) (start:S) (ys:tuple A n) {T}\n    : (S * tuple B n->T)->T :=\n  match n as n0 return (tuple A n0 -> (S * tuple B n0->T)->T) with\n  | O => fun ys ret => ret (start, tt)\n  | S n' => fun ys ret => mapi_with'_cps 0%nat f start ys ret\n  end ys.\n\n  Lemma unfold_mapi_with'_cps {T A B n} i\n        (f: nat->T->A->forall {R}, (T*B->R)->R) (start:T)\n    : @mapi_with'_cps T A B n i f start\n      = match n as n0 return (tuple' A n0 -> forall {R}, (T * tuple' B n0->R)->R) with\n        | O => fun ys T ret => f i start ys ret\n        | S n' => fun ys T ret =>\n                    f i start (hd ys) (fun sb =>\n                    mapi_with'_cps (S i) f (fst sb) (tl ys)\n                        (fun r => ret (fst r, (snd r, snd sb))))\n        end.\n  Proof. destruct n; reflexivity. Qed.\n\n  Lemma mapi_with'_cps_correct {S A B n} : forall i f start xs T ret,\n  (forall i s a R (ret:_->R), f i s a R ret = ret (f i s a _ id)) ->\n  @mapi_with'_cps S A B n i f start xs T ret = ret (mapi_with' i (fun i s a => f i s a _ id) start xs).\n  Proof. induction n as [|n IHn]; intros i f start xs T ret H; simpl; rewrite H, ?IHn by assumption; reflexivity. Qed.\n  Lemma mapi_with_cps_correct {S A B n} f start xs T ret\n  (H:forall i s a R (ret:_->R), f i s a R ret = ret (f i s a _ id))\n  : @mapi_with_cps S A B n f start xs T ret = ret (mapi_with (fun i s a => f i s a _ id) start xs).\n  Proof. destruct n; simpl; rewrite ?mapi_with'_cps_correct by assumption; reflexivity. Qed.\n  Hint Rewrite @mapi_with_cps_correct @mapi_with'_cps_correct\n       using (intros; autorewrite with uncps; auto): uncps.\n\n  Section internal_mapi_with_cps2.\n    (* We define fixpoints with fewer parameters to the internal [fix] to allow unfolding to partially specialize them *)\n    Context {R T A B : Type}\n            (f: nat->T->A->(T*B->R)->R).\n\n    Fixpoint mapi_with'_cps2_specialized {n} i\n             (start:T)\n      : Tuple.tuple' A n -> (T * tuple' B n -> R) -> R :=\n      match n as n0 return (tuple' A n0 -> (T * tuple' B n0->R)->R) with\n      | O => fun ys ret => f i start ys ret\n      | S n' => fun ys ret =>\n                  f i start (hd ys) (fun sb =>\n                  mapi_with'_cps2_specialized (S i) (fst sb) (tl ys)\n                      (fun r => ret (fst r, (snd r, snd sb))))\n      end.\n  End internal_mapi_with_cps2.\n\n  Definition mapi_with'_cps2 {T A B n} i\n          (f: nat->T->A->forall {R}, (T*B->R)->R) (start:T)\n    : Tuple.tuple' A n -> forall {R}, (T * tuple' B n -> R) -> R\n    := fun ts {R} => @mapi_with'_cps2_specialized R T A B (fun n t a => @f n t a R) n i start ts.\n\n  Definition mapi_with_cps2 {S A B n}\n          (f: nat->S->A->forall {T}, (S*B->T)->T) (start:S) (ys:tuple A n) {T}\n    : (S * tuple B n->T)->T :=\n  match n as n0 return (tuple A n0 -> (S * tuple B n0->T)->T) with\n  | O => fun ys ret => ret (start, tt)\n  | S n' => fun ys ret => mapi_with'_cps2 0%nat f start ys ret\n  end ys.\n\n  Lemma unfold_mapi_with'_cps2 {T A B n} i\n        (f: nat->T->A->forall {R}, (T*B->R)->R) (start:T)\n    : @mapi_with'_cps2 T A B n i f start\n      = match n as n0 return (tuple' A n0 -> forall {R}, (T * tuple' B n0->R)->R) with\n        | O => fun ys T ret => f i start ys ret\n        | S n' => fun ys T ret =>\n                    f i start (hd ys) (fun sb =>\n                    mapi_with'_cps2 (S i) f (fst sb) (tl ys)\n                        (fun r => ret (fst r, (snd r, snd sb))))\n        end.\n  Proof. destruct n; reflexivity. Qed.\n\n  Lemma mapi_with'_cps2_correct {S A B n} : forall i f start xs T ret,\n  (forall i s a R (ret:_->R), f i s a R ret = ret (f i s a _ id)) ->\n  @mapi_with'_cps2 S A B n i f start xs T ret = ret (mapi_with' i (fun i s a => f i s a _ id) start xs).\n  Proof. induction n as [|n IHn]; intros i f start xs T ret H; simpl; rewrite H, ?IHn by assumption; reflexivity. Qed.\n  Lemma mapi_with_cps2_correct {S A B n} f start xs T ret\n  (H:forall i s a R (ret:_->R), f i s a R ret = ret (f i s a _ id))\n  : @mapi_with_cps2 S A B n f start xs T ret = ret (mapi_with (fun i s a => f i s a _ id) start xs).\n  Proof. destruct n; simpl; rewrite ?mapi_with'_cps2_correct by assumption; reflexivity. Qed.\n  Hint Rewrite @mapi_with_cps2_correct @mapi_with'_cps2_correct\n       using (intros; autorewrite with uncps; auto): uncps.\n\n  Fixpoint left_append_cps {A n} (x:A) (xs:tuple A n) {R} :\n    (tuple A (S n) -> R) -> R :=\n  match\n    n as n0 return (tuple A n0 -> (tuple A (S n0) -> R) -> R)\n  with\n  | 0%nat => fun _ f => f x\n  | S n' =>\n      fun xs f =>\n      left_append_cps x (tl xs) (fun r => f (append (hd xs) r))\n  end xs.\n  Lemma left_append_cps_correct A n x xs R f :\n    @left_append_cps A n x xs R f = f (left_append x xs).\n  Proof.\n    induction n; [reflexivity|].\n    simpl left_append. simpl left_append_cps.\n    rewrite IHn. reflexivity.\n  Qed.\n\n  Definition tl_cps {A n} (xs : tuple A (S n)) {R} :\n    (tuple A n -> R) -> R :=\n  match\n    n as n0 return (tuple A (S n0) -> (tuple A n0 -> R) -> R)\n  with\n  | 0%nat => fun _ f => f tt\n  | S n' => fun xs f => f (fst xs)\n  end xs.\n  Lemma tl_cps_correct A n xs R f :\n    @tl_cps A n xs R f = f (tl xs).\n  Proof. destruct n; reflexivity. Qed.\n\n  Definition hd_cps {A n} (xs : tuple A (S n)) {R} :\n    (A -> R) -> R :=\n  match\n    n as n0 return (tuple A (S n0) -> (A -> R) -> R)\n  with\n  | 0%nat => fun x f => f x\n  | S n' => fun xs f => f (snd xs)\n  end xs.\n  Lemma hd_cps_correct A n xs R f :\n    @hd_cps A n xs R f = f (hd xs).\n  Proof. destruct n; reflexivity. Qed.\n\n  Fixpoint left_tl_cps {A n} (xs : tuple A (S n)) {R} :\n    (tuple A n -> R) -> R :=\n  match\n    n as n0 return (tuple A (S n0) -> (tuple A n0 -> R) -> R)\n  with\n  | 0%nat => fun _ f => f tt\n  | S n' =>\n      fun xs f =>\n        tl_cps xs (fun xtl => hd_cps xs (fun xhd =>\n          left_tl_cps xtl (fun r => f (append xhd r))))\n  end xs.\n  Lemma left_tl_cps_correct A n xs R f :\n    @left_tl_cps A n xs R f = f (left_tl xs).\n  Proof.\n    induction n; [reflexivity|].\n    simpl left_tl. simpl left_tl_cps.\n    rewrite IHn. reflexivity.\n  Qed.\n\n  Fixpoint left_hd_cps {A n} (xs : tuple A (S n)) {R} :\n    (A -> R) -> R :=\n  match\n    n as n0 return (tuple A (S n0) -> (A -> R) -> R)\n  with\n  | 0%nat => fun x f => f x\n  | S n' =>\n      fun xs f => tl_cps xs (fun xtl => left_hd_cps xtl f)\n  end xs.\n  Lemma left_hd_cps_correct A n xs R f :\n    @left_hd_cps A n xs R f = f (left_hd xs).\n  Proof.\n    induction n; [reflexivity|].\n    simpl left_hd. simpl left_hd_cps.\n    rewrite IHn. reflexivity.\n  Qed.\n\n  Lemma In_left_hd {A} n (p : tuple A (S n))\n    : In (left_hd p) (to_list _ p).\n  Proof.\n    simpl in *.\n    induction n as [|n IHn].\n    { left; reflexivity. }\n    { destruct p; simpl in *; right; auto. }\n  Qed.\n\n  Lemma In_to_list_left_tl {A} n (p : tuple A (S n)) x\n    : In x (to_list n (left_tl p)) -> In x (to_list (S n) p).\n  Proof.\n    simpl in *.\n    remember (to_list n (left_tl p)) as ls eqn:H.\n    intro Hin; revert Hin H.\n    revert n p.\n    induction ls as [|l ls IHls], n.\n    { simpl; intros ? []. }\n    { simpl; intros ? []. }\n    { simpl; congruence. }\n    { simpl; intros [? p] [H0|H1] H; simpl in *;\n        setoid_rewrite to_list_append in H;\n        inversion H; clear H; subst; auto. }\n  Qed.\n\n  Lemma to_list_left_append {A} {n} (p:tuple A n) x\n    : (to_list _ (left_append x p)) = to_list n p ++ x :: nil.\n  Proof.\n    destruct n as [|n]; simpl in *; [ reflexivity | ].\n    induction n as [|n IHn]; simpl in *; [ reflexivity | ].\n    destruct p; simpl in *; rewrite IHn; simpl; reflexivity.\n  Qed.\nEnd Tuple.\nHint Rewrite @Tuple.map_cps_correct @Tuple.left_append_cps_correct @Tuple.left_tl_cps_correct @Tuple.left_hd_cps_correct @Tuple.tl_cps_correct @Tuple.hd_cps_correct : uncps.\nHint Rewrite @Tuple.mapi_with_cps_correct @Tuple.mapi_with'_cps_correct @Tuple.mapi_with_cps2_correct @Tuple.mapi_with'_cps2_correct\n     using (intros; autorewrite with uncps; auto): uncps.\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/Util/CPSUtil.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.2916030639633187}}
{"text": "Set Implicit Arguments.\nUnset Strict Implicit.\n\nRequire Import List. Import ListNotations.\nRequire Import ZArith.\n\nRequire Import Integers.\n\nRequire Import lang hmac array.\n\nSection higherlevel_hmac.\n  Variables key msg: arr 16 bvec32.\n  Variable hash1: arr 32 bvec32 -> arr 8 bvec32.\n  Variable hash2: arr 24 bvec32 -> arr 8 bvec32.\n  Definition opad_val: bvec32 := Int.repr 1549556828. (*0x5c5c5c5c*)\n  Definition ipad_val: bvec32 := Int.repr 909522486. (*0x36363636*)\n  Definition opad: arr 16 bvec32 := Vector.const opad_val 16.\n  Definition ipad: arr 16 bvec32 := Vector.const ipad_val 16.\n  Definition ikeypad: arr 16 bvec32 := arr_map2 Int.xor ipad key.\n  Definition ikeypad_msg: arr 32 bvec32 := Vector.append ikeypad msg.\n  Definition okeypad: arr 16 bvec32 := arr_map2 Int.xor opad key.\n  Definition okeypad_hash: arr 24 bvec32 := Vector.append okeypad (hash1 ikeypad_msg).\n  Definition out: arr 8 bvec32 := hash2 okeypad_hash.\nEnd higherlevel_hmac.\n\nOpen Scope string_scope.\n\nSection hmac_proof1.\n  Variable st: state.\n  Variables key msg: arr 16 bvec32.\n  Definition key_id: id (TArr 16 TVec32) := \"key\".\n  Definition msg_id: id (TArr 16 TVec32) := \"msg\".\n  Variable st_key: st key_id = key.\n  Variable st_msg: st msg_id = msg.\n  Variable hash: \n    forall (n:nat)\n           (m: id (TArr n TVec32))\n           (h: id (TArr 8 TVec32)), prog.\n  (*HASH_ASSUMPTION 1: The hash function doesn't overwrite key_id or \"okp\"*)\n  Variable hash_frame1: forall xin (xout:id (TArr 8 TVec32)) st t (y:id t),\n    y=key_id \\/ y=\"okp\" ->   \n    prog_interp st (hash (n:=32) xin xout) (t:=t) y = st _ y.\n  (*HASH_ASSUMPTION 1: The hash function produces equal outputs (xout) from initial\n    states that agree on the input (xin).*)\n  Variable hash_frame2:\n    forall\n      n (xin: id (TArr n TVec32)) (xout: id (TArr 8 TVec32))\n      (st st':forall t, id t -> interp_ty t) (pf: st _ xin = st' _ xin),\n    prog_interp st (hash (n:=n) xin xout) (t:=TArr 8 TVec32) xout =\n    prog_interp st' (hash (n:=n) xin xout) (t:=TArr 8 TVec32) xout.\n\n  Definition hash1 (m: arr 32 bvec32): arr 8 bvec32 :=\n    prog_interp \n      (upd (\"fstin\": id (TArr 32 TVec32)) m st) \n      (@hash 32 \"fstin\" \"fstot\") \n      (\"fstot\" : id (TArr 8 TVec32)).\n\n Definition hash2 (m: arr 24 bvec32): arr 8 bvec32 :=\n    prog_interp \n      (upd (\"sndin\": id (TArr 24 TVec32)) m st) \n      (@hash 24 \"sndin\" \"sndot\") \n      (\"sndot\" : id (TArr 8 TVec32)).\n\n Lemma filter_true T (l: list T) : filter (fun _ => true) l = l.\n Proof.   \n   induction l; auto.\n   simpl. rewrite IHl; auto.\n Qed.   \n \n Lemma Fin_list_lo_hi_0 n : Fin_list_lo_hi 0 n = enum_iN n.\n Proof.\n   unfold Fin_list_lo_hi. unfold enum_iN. induction (enum_iN_rec n); auto.\n   simpl. f_equal. rewrite filter_true; auto.\n Qed.\n \n Lemma vector_nth_lem' C (f:bvec32 -> bvec32 -> C) m (i:iN m) n v :\n   Vector.nth (arr_map2 (N:=m) f (Vector.const (int32 n) m) v) i =\n   f (int32 n) (Vector.nth v i).\n Proof.\n   unfold arr_map2; erewrite Vector.nth_map2; eauto.\n   rewrite VectorSpec.const_nth; auto.\n Qed.   \n \n Lemma vector_nth_lem i n v :\n   Vector.nth (arr_map2 (N:=16) Int.xor (Vector.const (int32 n) 16) v) i =\n   Int.xor (Vector.nth v i) (int32 n).\n Proof.\n   rewrite vector_nth_lem'.\n   apply Int.xor_commut.\n Qed.   \n \n Lemma ikp_ikeypad' (st':forall t:ty, id t -> interp_ty t) n \n   (key_prop: st' (TArr 16 TVec32) key_id = key) :\n   stmt_interp\n     st'\n     (itern_seq_list (hi:=16) (Fin_list_lo_hi 0 16)\n                     (fun i : iN 16 =>\n                        SUpdate (N:=16) \"ikp\" (Fin.of_nat_lt (hmac.h_core0_obligation_1 i))\n                                (EBinop OXor (EDeref (N:=16) (t:=TVec32) i key_id)\n                                        (EVal (int32 n)))))\n   = upd (t:=TArr 16 TVec32) \"ikp\"\n         (arr_map2 (N:=16) Int.xor (Vector.const (int32 n) 16) key) st'.\n Proof.\n   unfold ikeypad, ipad.\n   set (e key_id i n := (EBinop OXor (EDeref (N:=16) (t:=TVec32) i key_id) (EVal (int32 n)))).\n   change (stmt_interp st'\n    (itern_seq_list (hi:=16) (Fin_list_lo_hi 0 16)\n       (fun i : iN 16 =>\n          SUpdate (N:=16) \"ikp\" (Fin.of_nat_lt (hmac.h_core0_obligation_1 i))\n                  (e key_id i n))) =\n     upd (t:=TArr 16 TVec32) \"ikp\"\n         (arr_map2 (N:=16) Int.xor (Vector.const (int32 n) 16) key) st').\n   rewrite (@array_upd_lem_16 key (arr_map2 (N:=16) Int.xor (Vector.const (int32 n) 16) key)); auto.\n   { intros st1 st2 H i n0.\n     unfold e.\n     simpl.\n     specialize (H key_id).\n     rewrite H; auto.\n     inversion 1. }\n   intros i; unfold e.\n   assert (H: Vector.nth (arr_map2 (N:=16) Int.xor (Vector.const (int32 n) 16) key) i =\n              Int.xor (Vector.nth key i) (int32 n)).\n   { apply vector_nth_lem. }\n   unfold interp_ty, bvec32 in H|-*; rewrite H.\n   unfold exp_interp; fold exp_interp; simpl; rewrite key_prop; auto.\n  Qed.\n\n Lemma ikp_ikeypad\n    (st':forall t:ty, id t -> interp_ty t)  \n    (key_prop: st' (TArr 16 TVec32) key_id = key) :   \n   stmt_interp\n     st'\n     (itern_seq_list (hi:=16) (Fin_list_lo_hi 0 16)\n                     (fun i : iN 16 =>\n                        SUpdate (N:=16) \"ikp\" (Fin.of_nat_lt (hmac.h_core0_obligation_1 i))\n                                (EBinop OXor (EDeref (N:=16) (t:=TVec32) i key_id)\n                                        (EVal (int32 909522486)))))\n   = upd (t:=TArr 16 TVec32) \"ikp\" (ikeypad key) st'.\n  Proof. apply ikp_ikeypad'; auto. Qed.\n \n  Lemma okp_okeypad' n\n    (st':forall t:ty, id t -> interp_ty t)          \n    (key_prop: st' (TArr 16 TVec32) key_id = key) :\n    stmt_interp\n      st' \n      (itern_seq_list\n         (hi:=16) (Fin_list_lo_hi 0 16)\n         (fun j : iN 16 =>\n            SUpdate (N:=16) \"okp\" (Fin.of_nat_lt (hmac.h_core0_obligation_2 j))\n                    (EBinop OXor (EDeref (N:=16) (t:=TVec32) j key_id) (EVal (int32 n)))))\n    = upd (t:=TArr 16 TVec32) \"okp\"\n          (arr_map2 (N:=16) Int.xor (Vector.const (Int.repr n) 16) key) st'.\n  Proof.\n   set (e key_id i n := (EBinop OXor (EDeref (N:=16) (t:=TVec32) i key_id) (EVal (int32 n)))).\n   change (stmt_interp st'\n    (itern_seq_list (hi:=16) (Fin_list_lo_hi 0 16)\n       (fun i : iN 16 =>\n          SUpdate (N:=16) \"okp\" (Fin.of_nat_lt (hmac.h_core0_obligation_1 i))\n                  (e key_id i n))) =\n     upd (t:=TArr 16 TVec32) \"okp\"\n         (arr_map2 (N:=16) Int.xor (Vector.const (int32 n) 16) key) st').\n   rewrite (@array_upd_lem_16 key (arr_map2 (N:=16) Int.xor (Vector.const (int32 n) 16) key)); auto.\n   { intros st1 st2 H i n0.\n     unfold e.\n     simpl.\n     specialize (H key_id).\n     rewrite H; auto.\n     inversion 1. }\n   intros i; unfold e.\n   assert (H: Vector.nth (arr_map2 (N:=16) Int.xor (Vector.const (int32 n) 16) key) i =\n              Int.xor (Vector.nth key i) (int32 n)).\n   { apply vector_nth_lem. }\n   unfold interp_ty, bvec32 in H|-*; rewrite H.\n   unfold exp_interp; fold exp_interp; simpl; rewrite key_prop; auto.\n  Qed.\n\n  Lemma okp_okeypad\n    (st':forall t:ty, id t -> interp_ty t)          \n    (key_prop: st' (TArr 16 TVec32) key_id = key) :\n    stmt_interp\n      st' \n      (itern_seq_list\n         (hi:=16) (Fin_list_lo_hi 0 16)\n         (fun j : iN 16 =>\n            SUpdate (N:=16) \"okp\" (Fin.of_nat_lt (hmac.h_core0_obligation_2 j))\n                    (EBinop OXor (EDeref (N:=16) (t:=TVec32) j key_id) (EVal (int32 1549556828)))))\n    = upd (\"okp\": id (TArr 16 TVec32)) (okeypad key) st'.\n  Proof. apply okp_okeypad'; auto. Qed.\n\n  Lemma fstin_ikeypad_msg (st':forall t:ty, id t -> interp_ty t)\n     (pf1: st' _ key_id = key)\n     (pf2: st' (TArr 16 TVec32) \"ikp\" = ikeypad key)\n     (pf3: st' (TArr 16 TVec32) msg_id = msg) :    \n    stmt_interp\n      (stmt_interp\n         st'\n         (itern_seq_list\n            (hi:=16) (Fin_list_lo_hi 0 16)\n            (fun i : iN 16 =>\n               SUpdate (N:=32) \"fstin\" (Fin.of_nat_lt (hmac.h_core0_obligation_3 i))\n                       (EDeref (N:=16) (t:=TVec32) i \"ikp\"))))\n      (itern_seq_list\n         (hi:=32) (Fin_list_lo_hi 16 32)\n         (fun j : iN 32 =>\n            SUpdate (N:=32) \"fstin\" (Fin.of_nat_lt (hmac.h_core0_obligation_4 j))\n                    (EDeref (N:=16) (t:=TVec32) (Fin.of_nat_lt (hmac.h_core0_obligation_5 j)) msg_id)))\n    = upd (\"fstin\": id (TArr 32 TVec32)) (ikeypad_msg key msg) st'.\n  Proof.\n    rewrite (@array_copy_first_16 key key_id); auto.\n    set (st'' := (upd (t:=TArr 32 TVec32) \"fstin\"\n       (Vector.append (st' (TArr 16 TVec32) \"ikp\") (last_16 (st' (TArr 32 TVec32) \"fstin\"))) st')).\n    rewrite (@array_copy_last_16 key key_id st'' msg_id \"fstin\"); auto.\n    unfold st''.\n    assert (H: (first_16\n          (upd (t:=TArr 32 TVec32) \"fstin\"\n             (Vector.append (st' (TArr 16 TVec32) \"ikp\") (last_16 (st' (TArr 32 TVec32) \"fstin\"))) st'\n             (t0:=TArr 32 TVec32) \"fstin\")) = st' (TArr 16 TVec32) \"ikp\").\n    { rewrite upd_get_same.\n      rewrite first_16_append; auto. }\n    rewrite H; unfold ikeypad_msg. \n    assert (H2: (upd (t:=TArr 32 TVec32) \"fstin\"\n     (Vector.append (st' (TArr 16 TVec32) \"ikp\") (last_16 (st' (TArr 32 TVec32) \"fstin\"))) st'\n     (t0:=TArr 16 TVec32) msg_id) = msg).\n    { rewrite upd_get_other; auto.\n      unfold msg_id; inversion 1. }\n    rewrite H2.\n    rewrite pf2.\n    rewrite upd_upd; auto.\n  Qed.\n\n  Lemma sndin_okeypad_hash :\n    let st :=\n        prog_interp\n          (upd (t:=TArr 32 TVec32) \"fstin\" (ikeypad_msg key msg)\n               (upd (t:=TArr 16 TVec32) \"okp\" (okeypad key)\n                    (upd (t:=TArr 16 TVec32) \"ikp\" (ikeypad key) st))) (hash (n:=32) \"fstin\" \"fstot\")\n    in \n    stmt_interp\n      (stmt_interp\n         st\n         (itern_seq_list\n            (hi:=16) (Fin_list_lo_hi 0 16)\n            (fun i : iN 16 =>\n               SUpdate (N:=24) \"sndin\" (Fin.of_nat_lt (hmac.h_core0_obligation_6 i))\n                       (EDeref (N:=16) (t:=TVec32) i \"okp\"))))\n      (itern_seq_list\n         (hi:=24) (Fin_list_lo_hi 16 24)\n         (fun j : iN 24 =>\n            SUpdate (N:=24) \"sndin\" (Fin.of_nat_lt (hmac.h_core0_obligation_7 j))\n                    (EDeref (N:=8) (t:=TVec32) (Fin.of_nat_lt (hmac.h_core0_obligation_8 j)) \"fstot\")))\n    = upd (\"sndin\": id (TArr 24 TVec32)) (okeypad_hash key msg hash1) st.\n  Proof.\n    intros st0.\n    assert (H: st0 (TArr 16 TVec32) key_id = key).\n    { unfold st0. rewrite hash_frame1; auto. }\n    rewrite (@array_copy_first_16_24 key key_id st0 \"okp\" \"sndin\" H).\n    unfold okeypad_hash.\n    rewrite (@array_copy_last_8_24 key key_id); auto.\n    rewrite upd_upd; auto.\n    f_equal.\n    f_equal.\n    { rewrite upd_get_same.\n      rewrite first_16_24_append.\n      unfold st0; rewrite hash_frame1; [|right; auto].\n      rewrite upd_get_other; [|inversion 1].\n      rewrite upd_get_same; auto. }\n    rewrite upd_get_other; [|inversion 1].\n    unfold st0.\n    unfold hash1.\n    apply hash_frame2.\n    do 2 rewrite upd_get_same; auto.\n  Qed.    \n  \n  Lemma hout_eq :\n    stmt_interp\n      (prog_interp\n         (upd (t:=TArr 24 TVec32) \"sndin\" (okeypad_hash key msg hash1)\n              (prog_interp\n                 (upd (t:=TArr 32 TVec32) \"fstin\" (ikeypad_msg key msg)\n                      (upd (t:=TArr 16 TVec32) \"okp\" (okeypad key)\n                           (upd (t:=TArr 16 TVec32)\n                                \"ikp\" (ikeypad key) st))) (hash (n:=32) \"fstin\" \"fstot\")))\n         (hash (n:=24) \"sndin\" \"sndot\"))\n      (itern_seq_list\n         (hi:=8) (Fin_list_lo_hi 0 8)\n         (fun i : iN 8 =>\n            SUpdate (N:=8) \"hout\" (Fin.of_nat_lt (hmac.h_core0_obligation_9 i))\n                    (EDeref (N:=8) (t:=TVec32) i \"sndot\"))) (t:=TArr 8 TVec32) \"hout\"\n    = hash2 (okeypad_hash key msg hash1).\n  Proof.\n    rewrite array_copy_8.\n    unfold hash2.\n    unfold okeypad_hash.\n    unfold hash1.\n    generalize (hash (n:=32) \"fstin\" \"fstot\") as HASH1; intro.\n    generalize (prog_interp (upd (t:=TArr 32 TVec32) \"fstin\" (ikeypad_msg key msg) st) HASH1\n                            (t:=TArr 8 TVec32) \"fstot\") as HASH1_ST; intro.\n    set (st' := \n    (upd (t:=TArr 24 TVec32) \"sndin\" (Vector.append (okeypad key) HASH1_ST)\n       (prog_interp\n          (upd (t:=TArr 32 TVec32) \"fstin\" (ikeypad_msg key msg)\n             (upd (t:=TArr 16 TVec32) \"okp\" (okeypad key) (upd (t:=TArr 16 TVec32) \"ikp\" (ikeypad key) st)))\n          (hash (n:=32) \"fstin\" \"fstot\")))).\n    set (st'' := (upd (t:=TArr 24 TVec32) \"sndin\" (Vector.append (okeypad key) HASH1_ST) st)).\n    assert (H: st' (TArr 24 TVec32) \"sndin\" = st'' _ \"sndin\").\n    { unfold st', st''.\n      do 2 rewrite upd_get_same; auto. }\n    generalize (@hash_frame2 24 \"sndin\" \"sndot\" st' st'' H); auto.\n  Qed.    \n\n  Lemma hmac_higherlevel_hmac:\n    prog_interp st \n      (h_core0' hash key_id msg_id \"hout\")  \n      (\"hout\" : id (TArr 8 TVec32)) =\n    out key msg hash1 hash2.\n  Proof.\n    unfold h_core0'.\n    unfold h_core0.\n    unfold syntax.iter.\n    unfold okeypad_hash.\n    unfold ikeypad_msg.\n    unfold okeypad.\n    unfold ikeypad.\n    rewrite fwd_adecl.\n    rewrite fwd_adecl.\n    rewrite fwd_adecl.\n    rewrite fwd_adecl.\n    rewrite fwd_adecl.\n    rewrite fwd_adecl.\n    rewrite fwd_adecl.\n    rewrite fwd_pseq.\n    rewrite fwd_pseq.\n    rewrite fwd_pseq.\n    rewrite fwd_pseq.\n    do 4 rewrite fwd_pstmt.\n    do 3 rewrite fwd_pseq.\n    do 2 rewrite fwd_pstmt.\n    do 2 rewrite fwd_pseq.\n    rewrite fwd_pstmt.\n    rewrite fwd_done.\n    repeat unfold SIter.\n    rewrite ikp_ikeypad; auto.\n    rewrite okp_okeypad; auto.\n    rewrite fstin_ikeypad_msg; auto.\n    rewrite sndin_okeypad_hash; auto.\n    apply hout_eq.\n  Qed.\nEnd hmac_proof1.", "meta": {"author": "seftonsg", "repo": "Garuda-2.0", "sha": "db15358f001eb74135428f5764aec1fb5df25e9b", "save_path": "github-repos/coq/seftonsg-Garuda-2.0", "path": "github-repos/coq/seftonsg-Garuda-2.0/Garuda-2.0-db15358f001eb74135428f5764aec1fb5df25e9b/old-src/hmac_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.291603056486972}}
{"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_S0 : statement_packings S0.\nProof.\n  solve_goal1.\npar: 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_S0.\nLemma aux_S1 : statement_packings S1.\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_S1.\nLemma aux_S2 : statement_packings S2.\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_S2.\nLemma aux_S3 : statement_packings S3.\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_S3.\nLemma aux_S4 : statement_packings S4.\nProof.\n  \nsolve_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_S4.\nLemma aux_S5 : statement_packings S5.\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_S5.\nLemma aux_S6 : statement_packings S6.\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_S6.\nLemma aux_S7 : statement_packings S7.\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_S7.\nLemma aux_S8 : statement_packings S8.\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_S8.\nLemma aux_S9 : statement_packings S9.\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_S9.\nLemma aux_S10 : statement_packings S10.\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_S10.\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_part1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526368038302, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.29160305648697193}}
{"text": "(* Translation of model TSO *)\nFrom Coq Require Import Relations String.\nRequire Import Cat.\nSection Model.\nVariable c : candidate.\nDefinition events := events c.\nInstance SetLike_set_events : SetLike (set events) := SetLike_set events.\nInstance SetLike_relation_events : SetLike (relation events) := SetLike_relation events.\nDefinition R := R c.\nDefinition W := W c.\nDefinition IW := IW c.\nDefinition FW := FW c.\nDefinition rf := rf c.\nDefinition po := po c.\nDefinition ext := ext c.\nDefinition loc := loc c.\nDefinition unknown_set := unknown_set c.\nDefinition M := union R W.\nDefinition classes_loc : set events -> set (set events) := fun S Si => forall x y, Si x -> Si y -> loc x y.\nDefinition MFENCE := unknown_set \"MFENCE\".\nDefinition partition := classes_loc.\nDefinition po_loc := intersection po loc.\nDefinition rfe := intersection rf ext.\nDefinition co0 := intersection loc (union (cartesian IW (diff W IW)) (cartesian (diff W FW) FW)).\nDefinition A := union ((*failed: try X with empty : (set _)*) empty : (set _)) ((*failed: try A with empty : (set _)*) empty : (set _)).\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 invrf_0 := rel_inv rf.\nDefinition cobase := co0.\nVariable co : relation events.\nDefinition fr := diff (rel_seq invrf_0 co) id.\nDefinition test := acyclic (union po_loc (union rf (union fr co))).\nDefinition poWR := rel_seq (diagonal W) (rel_seq po (diagonal R)).\nDefinition i1 := rel_seq poWR (diagonal A).\nDefinition i2 := rel_seq (diagonal A) poWR.\nDefinition implied := union i1 i2.\nDefinition ppo := union (rel_seq (diagonal R) (rel_seq po (diagonal R))) (union (rel_seq (diagonal M) (rel_seq po (diagonal W))) (union (rel_seq (diagonal M) (rel_seq po (rel_seq (diagonal MFENCE) (rel_seq po (diagonal M))))) implied)).\nDefinition ghb := union ppo (union rfe (union fr co)).\nDefinition tso := acyclic ghb.\nDefinition witness_conditions := generate_cos cobase co.\nDefinition model_conditions := test /\\ tso.\n(* Informations on the translation from cat to coq:\n\nThe following set of variables is only used inside try/with's before\nany definition:\n  A, X\nthe corresponding try/with's failed. Use the option -defined\nid1,id2,... to make the corresponding ones succeed instead.\n\nThe following set of variables is used but is neither defined in the\nprelude nor provided by the candidate:\n  MFENCE\n\nThe following renamings occurred:\n  invrf -> invrf_0\n *)\nEnd Model.\n\nHint Unfold SetLike_set_events SetLike_relation_events events R W IW FW rf po ext loc unknown_set M classes_loc MFENCE partition po_loc rfe co0 A generate_orders generate_cos invrf_0 cobase fr test poWR i1 i2 implied ppo 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/easy_tso_sc/tso.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2914854723926285}}
{"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.\nFrom Fairness Require Export Mod ModSimNoSync ModSimStutter.\n\nSet Implicit Arguments.\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  Let ident_src := @ident_src _ident_src.\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 _geno\n          (tid: thread_id) R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel)\n          (geno: bool -> bool -> URA.car -> ((@wf_stt R_src R_tgt).(T) * itree srcE R_src) -> itree tgtE R_tgt -> shared_rel)\n    :\n    bool -> bool -> URA.car -> ((@wf_stt R_src R_tgt).(T) * itree srcE R_src) -> itree tgtE R_tgt -> shared_rel :=\n  | geno_ret\n      f_src f_tgt r_ctx o o0\n      ths im_src im_tgt st_src st_tgt\n      r_src r_tgt\n      (LT: wf_stt.(lt) o0 o)\n      (GENO: RR r_src r_tgt r_ctx (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, Ret r_src) (Ret r_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n\n  | geno_tauL\n      f_src f_tgt r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      itr_src itr_tgt\n      (GENO: geno true f_tgt r_ctx (o, itr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, Tau itr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | geno_chooseL\n      f_src f_tgt r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      X ktr_src itr_tgt\n      (GENO: exists x, geno true f_tgt r_ctx (o, ktr_src x) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, trigger (Choose X) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | geno_rmwL\n      f_src f_tgt r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      X rmw ktr_src itr_tgt\n      (GENO: geno true f_tgt r_ctx (o, ktr_src (snd (rmw st_src) : X)) itr_tgt (ths, im_src, im_tgt, fst (rmw st_src), st_tgt))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, trigger (Rmw rmw) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | geno_tidL\n      f_src f_tgt r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      ktr_src itr_tgt\n      (GENO: geno true f_tgt r_ctx (o, ktr_src tid) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, trigger (GetTid) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | geno_UB\n      f_src f_tgt r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      ktr_src itr_tgt\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, trigger (Undefined) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | geno_fairL\n      f_src f_tgt r_ctx o\n      ths im_src0 im_tgt st_src st_tgt\n      f ktr_src itr_tgt\n      (GENO: exists im_src1,\n             (<<FAIR: fair_update im_src0 im_src1 (prism_fmap inrp f)>>) /\\\n               (<<GENO: geno true f_tgt r_ctx (o, ktr_src tt) itr_tgt (ths, im_src1, im_tgt, st_src, st_tgt)>>))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, trigger (Fair f) >>= ktr_src) itr_tgt (ths, im_src0, im_tgt, st_src, st_tgt)\n\n  | geno_tauR\n      f_src f_tgt r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      itr_src itr_tgt\n      (GENO: geno f_src true r_ctx (o, itr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, itr_src) (Tau itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | geno_chooseR\n      f_src f_tgt r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      X itr_src ktr_tgt\n      (GENO: forall x, geno f_src true r_ctx (o, itr_src) (ktr_tgt x) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, itr_src) (trigger (Choose X) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | geno_rmwR\n      f_src f_tgt r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      X rmw itr_src ktr_tgt\n      (GENO: geno f_src true r_ctx (o, itr_src) (ktr_tgt (snd (rmw st_tgt) : X)) (ths, im_src, im_tgt, st_src, fst (rmw st_tgt)))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, itr_src) (trigger (Rmw rmw) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | geno_tidR\n      f_src f_tgt r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      itr_src ktr_tgt\n      (GENO: geno f_src true r_ctx (o, itr_src) (ktr_tgt tid) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, itr_src) (trigger (GetTid) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | geno_fairR\n      f_src f_tgt r_ctx o\n      ths im_src im_tgt0 st_src st_tgt\n      f itr_src ktr_tgt\n      (GENO: forall im_tgt1 (FAIR: fair_update im_tgt0 im_tgt1 (prism_fmap inrp f)),\n          (<<GENO: geno f_src true r_ctx (o, itr_src) (ktr_tgt tt) (ths, im_src, im_tgt1, st_src, st_tgt)>>))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, itr_src) (trigger (Fair f) >>= ktr_tgt) (ths, im_src, im_tgt0, st_src, st_tgt)\n\n  | geno_observe\n      f_src f_tgt r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      fn args ktr_src ktr_tgt\n      (GENO: forall ret,\n             geno true true r_ctx (o, ktr_src ret) (ktr_tgt ret) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, trigger (Observe fn args) >>= ktr_src) (trigger (Observe fn args) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n\n  | geno_call\n      f_src f_tgt r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      fn args ktr_src itr_tgt\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, trigger (Call fn args) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n\n  | geno_yieldR\n      f_src f_tgt r_ctx0 o0\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      o1\n      (STUTTER: wf_stt.(lt) o1 o0)\n      (GENO: 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          (<<GENO: geno f_src true r_ctx1 (o1, trigger (Yield) >>= ktr_src) (ktr_tgt tt) (ths1, im_src1, im_tgt2, st_src1, st_tgt1)>>))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx0 (o0, trigger (Yield) >>= ktr_src) (trigger (Yield) >>= ktr_tgt) (ths0, im_src0, im_tgt0, st_src0, st_tgt0)\n\n  | geno_yieldL\n      f_src f_tgt r_ctx o0\n      ths im_src0 im_tgt st_src st_tgt\n      ktr_src itr_tgt\n      (GENO: exists im_src1 o1,\n          (<<FAIR: fair_update im_src0 im_src1 (prism_fmap inlp (tids_fmap tid ths))>>) /\\\n            (<<GENO: geno true f_tgt r_ctx (o1, ktr_src tt) itr_tgt (ths, im_src1, im_tgt, st_src, st_tgt)>>))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o0, trigger (Yield) >>= ktr_src) itr_tgt (ths, im_src0, im_tgt, st_src, st_tgt)\n\n  | geno_progress\n      r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      itr_src itr_tgt\n      (GENO: ModSimNoSync.lsim I tid RR false false r_ctx itr_src itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _geno tid RR geno true true r_ctx (o, itr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  .\n\n  Definition geno (tid: thread_id)\n             R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel):\n    bool -> bool -> URA.car -> (wf_stt.(T) * itree srcE R_src) -> itree tgtE R_tgt -> shared_rel :=\n    pind6 (_geno tid RR) top6.\n\n  Lemma geno_mon tid R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel): monotone6 (_geno tid RR).\n  Proof.\n    ii. inv IN; try (econs; eauto; fail).\n    { des. econs; eauto. }\n    { des. econs; eauto. }\n    { econs; eauto. i. eapply LE. eapply GENO. eauto. }\n    { econs; eauto. i. specialize (GENO _ _ _ _ _ _ _ INV0 VALID0 _ TGT). des. esplits; eauto. }\n    { des. econs; esplits; eauto. }\n  Qed.\n\n  Local Hint Constructors _geno: core.\n  Local Hint Unfold geno: core.\n  Local Hint Resolve geno_mon: paco.\n\n  Lemma geno_ord_weak\n        tid R0 R1 (LRR: R0 -> R1 -> URA.car -> shared_rel)\n        ps pt r_ctx src tgt (shr: shared) o0 o1\n        (LT: wf_stt.(lt) o0 o1)\n        (GENO: geno tid LRR ps pt r_ctx (o0, src) tgt shr)\n    :\n    geno tid LRR ps pt r_ctx (o1, src) tgt shr.\n  Proof.\n    remember (o0, src) as osrc.\n    move GENO before tid. revert_until GENO.\n    pattern ps, pt, r_ctx, osrc, tgt, shr.\n    revert ps pt r_ctx osrc tgt shr GENO. apply pind6_acc.\n    intros rr DEC IH. clear DEC. intros ps pt r_ctx osrc tgt shr GENO.\n    i; clarify.\n    eapply pind6_unfold in GENO; eauto with paco.\n    inv GENO.\n\n    { eapply pind6_fold. eapply geno_ret; eauto. }\n    { eapply pind6_fold. eapply geno_tauL; eauto.\n      destruct GENO0 as [GENO IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind6_fold. eapply geno_chooseL; eauto.\n      des. destruct GENO0 as [GENO IND]. eapply IH in IND; eauto. esplits; eauto.\n      split; ss; eauto.\n    }\n    { eapply pind6_fold. eapply geno_rmwL; eauto.\n      destruct GENO0 as [GENO IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind6_fold. eapply geno_tidL; eauto.\n      destruct GENO0 as [GENO IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind6_fold. eapply geno_UB; eauto. }\n    { eapply pind6_fold. eapply geno_fairL; eauto.\n      des. destruct GENO as [GENO IND]. eapply IH in IND; eauto. esplits; eauto.\n      split; ss; eauto.\n    }\n\n    { eapply pind6_fold. eapply geno_tauR; eauto.\n      destruct GENO0 as [GENO IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind6_fold. eapply geno_chooseR; eauto.\n      i. specialize (GENO0 x).\n      destruct GENO0 as [GENO IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind6_fold. eapply geno_rmwR; eauto.\n      destruct GENO0 as [GENO IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind6_fold. eapply geno_tidR; eauto.\n      destruct GENO0 as [GENO IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind6_fold. eapply geno_fairR; eauto.\n      i. specialize (GENO0 _ FAIR).\n      destruct GENO0 as [GENO IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind6_fold. eapply geno_observe; eauto.\n      i. specialize (GENO0 ret).\n      destruct GENO0 as [GENO IND]. eapply IH in IND; eauto. split; ss.\n    }\n\n    { eapply pind6_fold. eapply geno_call; eauto. }\n\n    { eapply pind6_fold. eapply geno_yieldR; eauto.\n      i. specialize (GENO0 _ _ _ _ _ _ _ INV0 VALID0 _ TGT). des. esplits; eauto.\n      destruct GENO0 as [GENO IND]. eapply IH in IND; eauto. split; ss.\n    }\n\n    { eapply pind6_fold. eapply geno_yieldL; eauto.\n      des. esplits; eauto.\n      eapply upind6_mon; eauto. ss.\n    }\n\n    { eapply pind6_fold. eapply geno_progress; eauto. }\n\n  Qed.\n\n  Lemma nosync_geno\n        tid R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel)\n        ps pt r_ctx src tgt shr\n        (LSIM: ModSimNoSync.lsim I tid RR ps pt r_ctx src tgt shr)\n    :\n    exists o, geno tid RR ps pt r_ctx (o, src) 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 (fzero:= fun _: (A R0 R1) => @ord_tree_base (A R0 R1)). set (one:= ord_tree_cons fzero).\n    inv LSIM.\n\n    { exists one. eapply pind6_fold. eapply geno_ret; eauto.\n      instantiate (1:=fzero (ps, pt, r_ctx, Ret r_src, Ret r_tgt, (ths, im_src, im_tgt, st_src, st_tgt))); ss.\n    }\n\n    { destruct LSIM0 as [LSIM IND]. eapply IH in IND. des.\n      exists o. eapply pind6_fold. eapply geno_tauL; eauto. split; ss.\n    }\n    { des. destruct LSIM0 as [LSIM IND]. eapply IH in IND. des.\n      exists o. eapply pind6_fold. eapply geno_chooseL; eauto. eexists. split; ss. eauto.\n    }\n    { destruct LSIM0 as [LSIM IND]. eapply IH in IND. des.\n      exists o. eapply pind6_fold. eapply geno_rmwL; eauto. split; ss.\n    }\n    { destruct LSIM0 as [LSIM IND]. eapply IH in IND. des.\n      exists o. eapply pind6_fold. eapply geno_tidL; auto. split; ss.\n    }\n    { exists one. eapply pind6_fold. eapply geno_UB; eauto. }\n    { des. destruct LSIM as [LSIM IND]. eapply IH in IND. des.\n      exists o. eapply pind6_fold. eapply geno_fairL; eauto. esplits; eauto. split; ss.\n    }\n\n    { destruct LSIM0 as [LSIM IND]. eapply IH in IND. des. exists o.\n      eapply pind6_fold. eapply geno_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                           geno tid RR ps pt rs (o, src) tgt shr).\n        eauto.\n      }\n      intro JOIN. des. exists o1.\n      eapply pind6_fold. eapply geno_chooseR.\n      i. specialize (LSIM0 x). destruct LSIM0 as [LSIM IND].\n      specialize (JOIN (ps, true, r_ctx, src, (ktr_tgt x), (ths, im_src, im_tgt, st_src, st_tgt))).\n      destruct JOIN; auto. des. split; ss.\n      eapply geno_ord_weak; eauto.\n    }\n\n    { destruct LSIM0 as [LSIM IND]. eapply IH in IND. des. exists o.\n      eapply pind6_fold. eapply geno_rmwR; eauto. ss.\n    }\n    { destruct LSIM0 as [LSIM IND]. eapply IH in IND. des. exists o.\n      eapply pind6_fold. eapply geno_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                           geno tid RR ps pt rs (o, src) tgt shr).\n        eauto.\n      }\n      intro JOIN. des. exists o1.\n      eapply pind6_fold. eapply geno_fairR.\n      i. specialize (LSIM0 _ FAIR). destruct LSIM0 as [LSIM IND].\n      specialize (JOIN (ps, true, r_ctx, src, (ktr_tgt ()), (ths, im_src, im_tgt1, st_src, st_tgt))).\n      destruct JOIN; auto. des. split; ss.\n      eapply geno_ord_weak; 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                           geno tid RR ps pt rs (o, src) tgt shr).\n        eauto.\n      }\n      intro JOIN. des. exists o1.\n      eapply pind6_fold. eapply geno_observe.\n      i. specialize (LSIM0 ret). destruct LSIM0 as [LSIM IND].\n      specialize (JOIN (true, true, r_ctx, ktr_src ret, ktr_tgt ret, (ths, im_src, im_tgt, st_src, st_tgt))).\n      destruct JOIN; auto. des. split; ss.\n      eapply geno_ord_weak; 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                           geno tid RR ps pt rs (o, src) tgt shr).\n        eauto.\n      }\n      intro JOIN. des.\n      set (fo1:= fun _: A R0 R1 => o1). exists (ord_tree_cons fo1).\n      eapply pind6_fold. eapply geno_call.\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                           geno tid RR ps pt rs (o, src) tgt shr).\n        eauto.\n      }\n      intro JOIN. des.\n      set (fo1:= fun _: A R0 R1 => o1). exists (ord_tree_cons fo1).\n      eapply pind6_fold. eapply geno_yieldR.\n      1,2: eauto.\n      { instantiate (1:=fo1 (ps, pt, r_ctx, (x <- trigger Yield;; ktr_src x), (x <- trigger Yield;; ktr_tgt x), (ths0, im_src0, im_tgt0, st_src0, st_tgt0))). ss.\n      }\n      i. specialize (LSIM0 _ _ _ _ _ _ _ INV0 VALID0 _ TGT). destruct LSIM0 as [LSIM IND].\n      specialize (JOIN (ps, true, r_ctx1, (x <- trigger Yield;; ktr_src x), ktr_tgt (), (ths1, im_src1, im_tgt2, st_src1, st_tgt1))).\n      destruct JOIN; auto. des. subst fo1. ss. split; ss. eapply geno_ord_weak; eauto.\n    }\n\n    { des. destruct LSIM as [LSIM IND]. eapply IH in IND. des. exists o.\n      eapply pind6_fold. eapply geno_yieldL; eauto. esplits; eauto.\n      split; ss. eauto.\n    }\n\n    { exists one. eapply pind6_fold. eapply geno_progress. pclearbot. auto. }\n\n  Qed.\n\nEnd GENORDER.\n#[export] Hint Constructors _geno: core.\n#[export] Hint Unfold geno: core.\n#[export] Hint Resolve geno_mon: paco.\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  Let ident_src := @ident_src _ident_src.\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 :=\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  Definition lift_wf (wf: WF): WF := sum_WF wf (option_WF wf).\n\n  Definition mk_o (wf: WF) R (o: wf.(T)) (ps: bool) (itr_src: itree srcE R): (lift_wf wf).(T) :=\n    if ps\n    then match (observe itr_src) with\n         | VisF (((|Yield)|)|)%sum _ => (inr (Some o))\n         | _ => (inr None)\n         end\n    else match (observe itr_src) with\n         | VisF (((|Yield)|)|)%sum _ => (inl o)\n         | _ => (inr None)\n         end.\n\n  Let A R0 R1 := (bool * bool * URA.car * (itree srcE R0) * (itree tgtE R1) * shared)%type.\n  Let wf_ot R0 R1 := @ord_tree_WF (A R0 R1).\n  Let wf_stt R0 R1 := lift_wf (@wf_ot R0 R1).\n\n  Lemma nosync_implies_stutter\n        tid\n        R0 R1 (LRR: R0 -> R1 -> URA.car -> shared_rel)\n        ps pt r_ctx src tgt\n        (shr: shared)\n        (LSIM: ModSimNoSync.lsim I tid LRR ps pt r_ctx src tgt shr)\n    :\n    exists (o: (@wf_stt R0 R1).(T)),\n      ModSimStutter.lsim (wf_stt) I tid LRR ps pt r_ctx (o, src) tgt shr.\n  Proof.\n    eapply nosync_geno in LSIM. des.\n    exists (mk_o (@wf_ot R0 R1) o ps src).\n    ginit. eapply cpn6_wcompat. eapply lsim_mon.\n    revert_until LRR. gcofix CIH; i.\n    remember (o, src) as osrc.\n    move LSIM before CIH. revert_until LSIM.\n    pattern ps, pt, r_ctx, osrc, tgt, shr.\n    revert ps pt r_ctx osrc tgt shr LSIM. apply pind6_acc.\n    intros rr DEC IH. clear DEC. intros ps pt r_ctx osrc tgt shr LSIM.\n    intros src o Eosrc. clarify.\n    eapply pind6_unfold in LSIM; eauto with paco.\n    inv LSIM.\n\n    { guclo lsim_indC_spec. econs 1; eauto.\n      instantiate (1:=(inl o1)). ss.\n      unfold mk_o. des_ifs. all: econs 3.\n    }\n\n    { destruct GENO as [GENO IND]. eapply IH in IND; eauto.\n      guclo lsim_indC_spec. econs 2; eauto.\n      guclo lsim_ord_weakC_spec. econs; eauto.\n      unfold mk_o. des_ifs; try reflexivity.\n      - right. ss. do 2 econs.\n      - right. ss. do 2 econs.\n    }\n    { des. destruct GENO as [GENO IND]. eapply IH in IND; eauto.\n      guclo lsim_indC_spec. econs 3; eauto. exists x.\n      guclo lsim_ord_weakC_spec. econs; eauto.\n      unfold mk_o. des_ifs; try reflexivity.\n      - right. ss. do 2 econs.\n      - right. ss. do 2 econs.\n    }\n    { destruct GENO as [GENO IND]. eapply IH in IND; eauto.\n      guclo lsim_indC_spec. econs 4; eauto.\n      guclo lsim_ord_weakC_spec. econs; eauto.\n      unfold mk_o. des_ifs; try reflexivity.\n      - right. ss. do 2 econs.\n      - right. ss. do 2 econs.\n    }\n    { destruct GENO as [GENO IND]. eapply IH in IND; eauto.\n      guclo lsim_indC_spec. econs 5; eauto.\n      guclo lsim_ord_weakC_spec. econs; eauto.\n      unfold mk_o. des_ifs; try reflexivity.\n      - right. ss. do 2 econs.\n      - right. ss. do 2 econs.\n    }\n    { guclo lsim_indC_spec. econs 6; eauto. }\n    { des. destruct GENO0 as [GENO IND]. eapply IH in IND; eauto.\n      guclo lsim_indC_spec. econs 7; eauto. esplits; eauto.\n      guclo lsim_ord_weakC_spec. econs; eauto.\n      unfold mk_o. des_ifs; try reflexivity.\n      - right. ss. do 2 econs.\n      - right. ss. do 2 econs.\n    }\n\n    { destruct GENO as [GENO IND]. eapply IH in IND; eauto.\n      guclo lsim_indC_spec. econs 8; eauto.\n    }\n    { guclo lsim_indC_spec. econs 9; eauto. i. specialize (GENO x).\n      destruct GENO as [GENO IND]. eapply IH in IND; eauto.\n    }\n    { destruct GENO as [GENO IND]. eapply IH in IND; eauto.\n      guclo lsim_indC_spec. econs 10; eauto.\n    }\n    { destruct GENO as [GENO IND]. eapply IH in IND; eauto.\n      guclo lsim_indC_spec. econs 11; eauto.\n    }\n    { guclo lsim_indC_spec. econs 12; eauto. i. specialize (GENO _ FAIR).\n      destruct GENO as [GENO IND]. eapply IH in IND; eauto.\n    }\n\n    { guclo lsim_indC_spec. econs 13; eauto. i. specialize (GENO ret).\n      destruct GENO as [GENO IND]. eapply IH in IND; eauto.\n      guclo lsim_ord_weakC_spec. econs; eauto.\n      unfold mk_o. ss. des_ifs; try reflexivity.\n      - right. ss. do 2 econs.\n      - right. ss. do 2 econs.\n    }\n\n    { guclo lsim_indC_spec. econs 14. }\n\n    { guclo lsim_indC_spec. econs 15; eauto.\n      2:{ i. specialize (GENO _ _ _ _ _ _ _ INV0 VALID0 _ TGT). des.\n          destruct GENO as [GENO IND]. eapply IH in IND; eauto.\n          esplits.\n          guclo lsim_resetC_spec. econs; eauto.\n      }\n      unfold mk_o; ss. rewrite !bind_trigger. ss.\n      des_ifs.\n      - do 2 econs. auto.\n      - econs. auto.\n    }\n\n    { des. destruct GENO0 as [GENO IND]. eapply IH in IND; eauto.\n      guclo lsim_indC_spec. econs 16; eauto.\n    }\n\n    { eapply nosync_geno in GENO. des.\n      guclo lsim_ord_weakC_spec. econs.\n      instantiate (1:=mk_o (@wf_ot R0 R1) o0 false src).\n      gfinal. right. pfold. eapply pind6_fold. econs 17. right. eapply CIH. auto.\n      ss. des_ifs; try reflexivity. right. ss. do 2 econs.\n    }\n\n  Qed.\n\nEnd PROOF.\n\nSection MODSIM.\n\n  Lemma nosync_implies_stutter_mod\n        md_src md_tgt\n        (MDSIM: ModSimNoSync.ModSim.mod_sim md_src md_tgt)\n    :\n    ModSimStutter.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 := programE _ident_src state_src).\n    set (tgtE := programE _ident_tgt state_tgt).\n    set (ident_src := @ident_src _ident_src).\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 (wf_stt:=fun R0 R1 => lift_wf (@ord_tree_WF (bool * bool * URA.car * (itree srcE R0) * (itree tgtE R1) * shared)%type)).\n    econs; eauto. instantiate (1:=wf_stt).\n    i. specialize (init im_tgt). des. rename init0 into funs. exists I. esplits; eauto.\n    i. specialize (funs fn args). des_ifs.\n    unfold ModSimNoSync.local_sim in funs.\n    ii. specialize (funs _ _ _ _ _ _ _ INV tid _ THS VALID _ UPD).\n    des. esplits; eauto. instantiate (1:=inr None).\n    i. specialize (funs1 _ _ _ _ _ _ _ INV1 VALID1 _ TGT).\n    des. esplits; eauto. i. specialize (LSIM fs ft).\n    eapply nosync_implies_stutter in LSIM. des.\n    eapply stutter_ord_weak. 2: eapply LSIM.\n    clear. destruct o.\n    { right. econs. }\n    destruct t.\n    { right. do 2 econs. }\n    { left. auto. }\n  Qed.\n\nEnd MODSIM.\n\nSection USERSIM.\n\n  Lemma nosync_implies_stutter_user\n        md_src md_tgt p_src p_tgt\n        (MDSIM: ModSimNoSync.UserSim.sim md_src md_tgt p_src p_tgt)\n    :\n    ModSimStutter.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 := programE _ident_src state_src).\n    set (tgtE := programE _ident_tgt state_tgt).\n    set (ident_src := @ident_src _ident_src).\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 (wf_stt:=fun R0 R1 => lift_wf (@ord_tree_WF (bool * bool * URA.car * (itree srcE R0) * (itree tgtE R1) * shared)%type)).\n    econs; eauto. instantiate (1:=wf_stt).\n    i. specialize (funs im_tgt). des. exists I. esplits; eauto.\n    instantiate (1:=NatMap.map (fun _ => inr None) p_src).\n    eapply nm_find_some_implies_forall4.\n    { apply nm_forall2_wf_pair. eapply list_forall3_implies_forall2_2; eauto. clear. i. des. des_ifs. des; clarify. }\n    { apply nm_forall2_wf_pair. eapply list_forall3_implies_forall2_3; eauto. clear. i. des. des_ifs. des; clarify. }\n    { unfold nm_wf_pair. unfold key_set. rewrite nm_map_unit1_map_eq. ss. }\n    i. eapply nm_forall3_implies_find_some in SIM; eauto.\n    unfold ModSimNoSync.local_sim_init in SIM. unfold local_sim_init.\n    i. specialize (SIM _ _ _ _ _ _ _ INV VALID _ FAIR). des. esplits; eauto.\n    i. specialize (SIM0 fs ft). eapply nosync_implies_stutter in SIM0. des.\n    rewrite NatMapP.F.map_o in FIND4. unfold option_map in FIND4. des_ifs.\n    eapply stutter_ord_weak. 2: eapply SIM0.\n    clear. destruct o.\n    { right. econs. }\n    destruct t.\n    { right. do 2 econs. }\n    { left. auto. }\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/NoSync2Stutter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7090191214879992, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.29148546733715947}}
{"text": "Require Import List Map Envs AllInRel Exp AppExpFree.\nRequire Import IL Annotation AutoIndTac Liveness.Liveness LabelsDefined.\nRequire Import Infra.PartialOrder AnnotationLattice CSetPartialOrder.\n\nSet Implicit Arguments.\n\n(** * ReconstrLive *)\n\nFixpoint reconstr_live\n         (Lv : list (set var))\n         (ZL : list (params))\n         (G : set var)\n         (s : stmt)\n         (rm : ann (set var))\n         {struct s}\n  : ann (set var)\n  :=\n    match s, rm with\n    | stmtLet x e t, ann1 _ rm\n      => let lv_t := reconstr_live Lv ZL (singleton x) t rm in\n        ann1 ((getAnn lv_t) \\ singleton x ∪ Exp.freeVars e ∪ G) lv_t\n\n    | stmtReturn e, ann0 _\n      => ann0 (Ops.freeVars e ∪ G)\n\n    | stmtIf e t v, ann2 _ rm_t rm_v\n      => let lv_t := reconstr_live Lv ZL ∅ t rm_t in\n        let lv_v := reconstr_live Lv ZL ∅ v rm_v in\n        ann2 (getAnn lv_t ∪ getAnn lv_v ∪ Ops.freeVars e ∪ G) lv_t lv_v\n\n    | stmtApp f Y, ann0 _\n      => let blv := nth (counted f) Lv ∅ in\n        let Z   := nth (counted f) ZL nil in\n        ann0 (list_union (Ops.freeVars ⊝ Y) ∪ blv \\ of_list Z ∪ G)\n\n    | stmtFun F t, annF _ rm_F rm_t\n      => let rms := getAnn ⊝ rm_F in\n        let lv_t := reconstr_live (rms ++ Lv) (fst ⊝ F ++ ZL) ∅ t rm_t in\n        let lv_F := (fun ps rm_s =>\n                      reconstr_live (rms ++ Lv)\n                                    (fst ⊝ F ++ ZL)\n                                    (of_list (fst ps))\n                                    (snd ps)\n                                    rm_s\n                    ) ⊜ F rm_F in\n        annF (getAnn lv_t ∪ G) lv_F lv_t\n\n    | _,_ => ann0 G\n\n    end.\n\n\nLemma reconstr_live_G_eq (G : ⦃var⦄) (Lv : list ⦃var⦄)\n      (ZL : list params) (s : stmt) a\n  : getAnn (reconstr_live Lv ZL G s a) [=] getAnn (reconstr_live Lv ZL ∅ s a) ∪ G .\nProof.\n  general induction s;\n    destruct a;\n    try destruct a;\n    simpl; eauto; cset_tac.\nQed.\n\nLemma reconstr_live_remove_G Lv ZL G s sl G'\n  : getAnn (reconstr_live Lv ZL G s sl) \\ G ⊆ getAnn (reconstr_live Lv ZL G' s sl) .\nProof.\n  destruct s, sl, a; simpl; cset_tac.\nQed.\n\nLemma reconstr_live_G Lv ZL G s a\n  : G ⊆ getAnn (reconstr_live Lv ZL G s a).\nProof.\n  induction s,a; simpl; eauto with cset.\nQed.\n\nLemma reconstr_live_subset Lv Lv' ZL G s sl\n  : Lv ⊑ Lv'\n    -> reconstr_live Lv  ZL G s sl ⊑ reconstr_live Lv' ZL G s sl.\nProof.\n  intros H.\n  revert Lv Lv' H ZL G sl.\n  sind s; intros; destruct s, sl; simpl; try econstructor; eauto;\n    try eapply IH; eauto.\n  - exploit (IH s); eauto.\n    rewrite (ann_R_get H0); eauto.\n  - exploit (IH s1); eauto.\n    exploit (IH s2); eauto.\n    rewrite (ann_R_get H0); eauto.\n    rewrite (ann_R_get H1); eauto.\n  - enough (nth (labN l) Lv ∅ ⊆ nth (labN l) Lv' ∅)\n      as HH by (rewrite HH; clear; cset_tac).\n    apply PIR2_length in H as Lv_len.\n    decide (labN l < length Lv).\n    + assert ({x : ⦃var⦄ & get Lv (labN l) x}) as [x get_x]\n          by (apply get_in_range; eauto).\n      rewrite Lv_len in l0.\n      assert ({y : ⦃var⦄ & get Lv' (labN l) y}) as [y get_y]\n          by (apply get_in_range; eauto).\n      erewrite get_nth; eauto.\n      erewrite get_nth; eauto.\n      eapply get_PIR2; eauto.\n    + apply not_le in n.\n      rewrite nth_overflow; eauto with cset.\n      omega.\n  - eapply incl_union_lr; eauto.\n    eapply ann_R_get.\n    eapply (IH s); eauto.\n  - eauto with len.\n  - intros; inv_get; eauto with len.\n    eapply IH; eauto.\nQed.\n\nLemma reconstr_live_equal Lv Lv' ZL G s sl\n  : Lv ≣ Lv'\n    -> reconstr_live Lv  ZL G s sl ≣ reconstr_live Lv' ZL G s sl.\nProof.\n  intros H.\n  revert Lv Lv' H ZL G sl.\n  sind s; intros; destruct s, sl; simpl; try econstructor; eauto;\n    try eapply IH; eauto.\n  - exploit (IH s); eauto.\n    rewrite (ann_R_get H0); eauto.\n  - exploit (IH s1); eauto.\n    exploit (IH s2); eauto.\n    rewrite (ann_R_get H0); eauto.\n    rewrite (ann_R_get H1); eauto.\n  - enough (nth (labN l) Lv ∅ [=] nth (labN l) Lv' ∅)\n      as HH by (rewrite HH; clear; cset_tac).\n    apply PIR2_length in H as Lv_len.\n    decide (labN l < length Lv).\n    + assert ({x : ⦃var⦄ & get Lv (labN l) x}) as [x get_x]\n          by (apply get_in_range; eauto).\n      rewrite Lv_len in l0.\n      assert ({y : ⦃var⦄ & get Lv' (labN l) y}) as [y get_y]\n          by (apply get_in_range; eauto).\n      erewrite get_nth; eauto.\n      erewrite get_nth; eauto.\n      eapply get_PIR2; eauto.\n    + apply not_le in n.\n      rewrite nth_overflow; eauto with cset;\n        [ | omega].\n      rewrite Lv_len in n.\n      rewrite nth_overflow; eauto with cset.\n      omega.\n  - eapply eq_union_lr; eauto.\n    eapply ann_R_get.\n    eapply (IH s); eauto.\n  - eauto with len.\n  - intros; inv_get; eauto with len.\n    eapply IH; eauto.\nQed.\n\n\n\nLemma reconstr_live_setTopAnn ZL Lv s alv G a\n  : reconstr_live Lv ZL G s alv = reconstr_live Lv ZL G s (setTopAnn alv a).\nProof.\n  destruct s, alv; simpl; eauto.\nQed.\n\nLemma reconstr_live_incl ZL Lv s alv G\n  : live_sound Imperative ZL Lv s alv\n    -> G ⊆ getAnn alv\n    -> poLe (reconstr_live Lv ZL G s alv) alv.\nProof.\n  intros LS.\n  general induction LS; simpl in *.\n  - eapply ann1_poLe; eauto with cset.\n    + rewrite H2, IHLS; eauto 20 using Exp.freeVars_live with cset.\n      rewrite Exp.freeVars_live; eauto.\n      unfold poLe; simpl. cset_tac.\n  - eapply ann2_poLe; eauto with cset.\n    rewrite IHLS1, IHLS2; eauto 20 with cset.\n    rewrite Ops.freeVars_live; eauto.\n    unfold poLe; simpl. cset_tac.\n  - eapply ann0_poLe; eauto with cset.\n    erewrite !get_nth; eauto.\n    unfold poLe; simpl.\n    rewrite Ops.freeVars_live_list; eauto.\n    cset_tac.\n  - eapply ann0_poLe; eauto with cset.\n    rewrite Ops.freeVars_live; eauto.\n    unfold poLe; simpl. cset_tac.\n  - eapply annF_poLe; eauto with cset.\n    + rewrite IHLS; eauto with cset.\n      unfold poLe; simpl. cset_tac.\n    + eapply PIR2_get; eauto with len.\n      intros; inv_get.\n      rewrite H1; eauto.\n      exploit H2; eauto.\nQed.\n\nLemma reconstr_live_sound ZL Lv s alv G\n  : live_sound Imperative ZL Lv s alv\n    -> G ⊆ getAnn alv\n    -> live_sound Imperative ZL Lv s (reconstr_live Lv ZL G s alv).\nProof.\n  intros LS.\n  general induction LS; simpl in *.\n  - econstructor; eauto with cset.\n    + eapply live_exp_sound_incl.\n      * eapply live_freeVars.\n      * clear. cset_tac.\n    + rewrite <- reconstr_live_G; eauto with cset.\n  - econstructor; eauto with cset.\n    + eapply live_op_sound_incl.\n      * eapply Ops.live_freeVars.\n      * clear. cset_tac.\n  - econstructor; simpl; eauto.\n    + erewrite !get_nth; eauto.\n      clear. cset_tac.\n    + intros.\n      erewrite !get_nth; eauto.\n      eapply live_op_sound_incl.\n      * eapply Ops.live_freeVars.\n      * do 2 eapply incl_union_left.\n        eapply incl_list_union; eauto using map_get_1.\n  - econstructor; eauto.\n    + eapply live_op_sound_incl.\n      * eapply Ops.live_freeVars.\n      * clear. cset_tac.\n  - econstructor; intros; inv_get; eauto with len.\n    + eapply live_sound_monotone.\n      * eapply IHLS; eauto with cset.\n      * eapply PIR2_get; intros; eauto with len.\n        eapply get_app_cases in H6 as [? |[? ?]]; inv_get.\n        -- rewrite get_app_lt in H5; eauto with len.\n           inv_get.\n           rewrite reconstr_live_incl; eauto.\n           exploit H2; eauto; dcr.\n        -- rewrite get_app_ge in H5; len_simpl;\n             rewrite H in *; inv_get; eauto.\n    + eapply live_sound_monotone.\n      * eapply H1; eauto with cset.\n        exploit H2; eauto; dcr.\n      * eapply PIR2_get; intros; eauto with len.\n        eapply get_app_cases in H7 as [? |[? ?]]; inv_get.\n        -- rewrite reconstr_live_incl; eauto.\n           exploit H2; eauto; dcr.\n        -- rewrite get_app_ge in H8; len_simpl;\n             rewrite H in *; inv_get; eauto.\n    + simpl.\n      exploit H2; eauto; dcr.\n      split; eauto.\n      rewrite <- reconstr_live_G; eauto.\nQed.", "meta": {"author": "sigurdschneider", "repo": "lvc", "sha": "be41194f16495d283fe7bbc982c3393ac554dd5b", "save_path": "github-repos/coq/sigurdschneider-lvc", "path": "github-repos/coq/sigurdschneider-lvc/lvc-be41194f16495d283fe7bbc982c3393ac554dd5b/theories/Liveness/ReconstrLive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7090191214879992, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.29148546733715947}}
{"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.\n\n(* Why3 assumption *)\nDefinition unit := unit.\n\nAxiom map : forall (a:Type) {a_WT:WhyType a} (b:Type) {b_WT:WhyType b}, Type.\nParameter map_WhyType : forall (a:Type) {a_WT:WhyType a}\n  (b:Type) {b_WT:WhyType b}, WhyType (map a b).\nExisting Instance map_WhyType.\n\nParameter get: forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  (map a b) -> a -> b.\n\nParameter set: forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  (map a b) -> a -> b -> (map a b).\n\nAxiom Select_eq : forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  forall (m:(map a b)), forall (a1:a) (a2:a), forall (b1:b), (a1 = a2) ->\n  ((get (set m a1 b1) a2) = b1).\n\nAxiom Select_neq : forall {a:Type} {a_WT:WhyType a}\n  {b:Type} {b_WT:WhyType b}, forall (m:(map a b)), forall (a1:a) (a2:a),\n  forall (b1:b), (~ (a1 = a2)) -> ((get (set m a1 b1) a2) = (get m a2)).\n\nParameter const: forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  b -> (map a b).\n\nAxiom Const : forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  forall (b1:b) (a1:a), ((get (const b1:(map a b)) a1) = b1).\n\n(* Why3 assumption *)\nDefinition grid := (map Z Z).\n\n(* Why3 assumption *)\nDefinition valid_chunk (g:(map Z Z)) (i:Z) (start:(map Z Z)) (offsets:(map Z\n  Z)): Prop := let s := (get start i) in forall (o1:Z) (o2:Z),\n  (((0%Z <= o1)%Z /\\ (o1 < 9%Z)%Z) /\\ (((0%Z <= o2)%Z /\\ (o2 < 9%Z)%Z) /\\\n  ~ (o1 = o2))) -> let i1 := (s + (get offsets o1))%Z in let i2 :=\n  (s + (get offsets o2))%Z in ((((1%Z <= (get g i1))%Z /\\ ((get g\n  i1) <= 9%Z)%Z) /\\ ((1%Z <= (get g i2))%Z /\\ ((get g i2) <= 9%Z)%Z)) ->\n  ~ ((get g i1) = (get g i2))).\n\n(* Why3 assumption *)\nDefinition is_index (i:Z): Prop := (0%Z <= i)%Z /\\ (i < 81%Z)%Z.\n\n(* Why3 assumption *)\nDefinition valid (g:(map Z Z)): Prop := forall (i:Z), (is_index i) ->\n  ((valid_chunk g i\n  (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (const (-1%Z)%Z:(map\n  Z Z)) 0%Z 0%Z) 1%Z 1%Z) 2%Z 2%Z) 3%Z 3%Z) 4%Z 4%Z) 5%Z 5%Z) 6%Z 6%Z) 7%Z\n  7%Z) 8%Z 8%Z) 9%Z 0%Z) 10%Z 1%Z) 11%Z 2%Z) 12%Z 3%Z) 13%Z 4%Z) 14%Z 5%Z)\n  15%Z 6%Z) 16%Z 7%Z) 17%Z 8%Z) 18%Z 0%Z) 19%Z 1%Z) 20%Z 2%Z) 21%Z 3%Z) 22%Z\n  4%Z) 23%Z 5%Z) 24%Z 6%Z) 25%Z 7%Z) 26%Z 8%Z) 27%Z 0%Z) 28%Z 1%Z) 29%Z 2%Z)\n  30%Z 3%Z) 31%Z 4%Z) 32%Z 5%Z) 33%Z 6%Z) 34%Z 7%Z) 35%Z 8%Z) 36%Z 0%Z) 37%Z\n  1%Z) 38%Z 2%Z) 39%Z 3%Z) 40%Z 4%Z) 41%Z 5%Z) 42%Z 6%Z) 43%Z 7%Z) 44%Z 8%Z)\n  45%Z 0%Z) 46%Z 1%Z) 47%Z 2%Z) 48%Z 3%Z) 49%Z 4%Z) 50%Z 5%Z) 51%Z 6%Z) 52%Z\n  7%Z) 53%Z 8%Z) 54%Z 0%Z) 55%Z 1%Z) 56%Z 2%Z) 57%Z 3%Z) 58%Z 4%Z) 59%Z 5%Z)\n  60%Z 6%Z) 61%Z 7%Z) 62%Z 8%Z) 63%Z 0%Z) 64%Z 1%Z) 65%Z 2%Z) 66%Z 3%Z) 67%Z\n  4%Z) 68%Z 5%Z) 69%Z 6%Z) 70%Z 7%Z) 71%Z 8%Z) 72%Z 0%Z) 73%Z 1%Z) 74%Z 2%Z)\n  75%Z 3%Z) 76%Z 4%Z) 77%Z 5%Z) 78%Z 6%Z) 79%Z 7%Z) 80%Z 8%Z)\n  (set (set (set (set (set (set (set (set (set (const (-1%Z)%Z:(map Z Z)) 0%Z\n  0%Z) 1%Z 9%Z) 2%Z 18%Z) 3%Z 27%Z) 4%Z 36%Z) 5%Z 45%Z) 6%Z 54%Z) 7%Z 63%Z)\n  8%Z 72%Z)) /\\ ((valid_chunk g i\n  (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (const (-1%Z)%Z:(map\n  Z Z)) 0%Z 0%Z) 1%Z 0%Z) 2%Z 0%Z) 3%Z 0%Z) 4%Z 0%Z) 5%Z 0%Z) 6%Z 0%Z) 7%Z\n  0%Z) 8%Z 0%Z) 9%Z 9%Z) 10%Z 9%Z) 11%Z 9%Z) 12%Z 9%Z) 13%Z 9%Z) 14%Z 9%Z)\n  15%Z 9%Z) 16%Z 9%Z) 17%Z 9%Z) 18%Z 18%Z) 19%Z 18%Z) 20%Z 18%Z) 21%Z 18%Z)\n  22%Z 18%Z) 23%Z 18%Z) 24%Z 18%Z) 25%Z 18%Z) 26%Z 18%Z) 27%Z 27%Z) 28%Z\n  27%Z) 29%Z 27%Z) 30%Z 27%Z) 31%Z 27%Z) 32%Z 27%Z) 33%Z 27%Z) 34%Z 27%Z)\n  35%Z 27%Z) 36%Z 36%Z) 37%Z 36%Z) 38%Z 36%Z) 39%Z 36%Z) 40%Z 36%Z) 41%Z\n  36%Z) 42%Z 36%Z) 43%Z 36%Z) 44%Z 36%Z) 45%Z 45%Z) 46%Z 45%Z) 47%Z 45%Z)\n  48%Z 45%Z) 49%Z 45%Z) 50%Z 45%Z) 51%Z 45%Z) 52%Z 45%Z) 53%Z 45%Z) 54%Z\n  54%Z) 55%Z 54%Z) 56%Z 54%Z) 57%Z 54%Z) 58%Z 54%Z) 59%Z 54%Z) 60%Z 54%Z)\n  61%Z 54%Z) 62%Z 54%Z) 63%Z 63%Z) 64%Z 63%Z) 65%Z 63%Z) 66%Z 63%Z) 67%Z\n  63%Z) 68%Z 63%Z) 69%Z 63%Z) 70%Z 63%Z) 71%Z 63%Z) 72%Z 72%Z) 73%Z 72%Z)\n  74%Z 72%Z) 75%Z 72%Z) 76%Z 72%Z) 77%Z 72%Z) 78%Z 72%Z) 79%Z 72%Z) 80%Z\n  72%Z) (set (set (set (set (set (set (set (set (set (const (-1%Z)%Z:(map Z\n  Z)) 0%Z 0%Z) 1%Z 1%Z) 2%Z 2%Z) 3%Z 3%Z) 4%Z 4%Z) 5%Z 5%Z) 6%Z 6%Z) 7%Z 7%Z)\n  8%Z 8%Z)) /\\ (valid_chunk g i\n  (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (const (-1%Z)%Z:(map\n  Z Z)) 0%Z 0%Z) 1%Z 0%Z) 2%Z 0%Z) 3%Z 3%Z) 4%Z 3%Z) 5%Z 3%Z) 6%Z 6%Z) 7%Z\n  6%Z) 8%Z 6%Z) 9%Z 0%Z) 10%Z 0%Z) 11%Z 0%Z) 12%Z 3%Z) 13%Z 3%Z) 14%Z 3%Z)\n  15%Z 6%Z) 16%Z 6%Z) 17%Z 6%Z) 18%Z 0%Z) 19%Z 0%Z) 20%Z 0%Z) 21%Z 3%Z) 22%Z\n  3%Z) 23%Z 3%Z) 24%Z 6%Z) 25%Z 6%Z) 26%Z 6%Z) 27%Z 27%Z) 28%Z 27%Z) 29%Z\n  27%Z) 30%Z 30%Z) 31%Z 30%Z) 32%Z 30%Z) 33%Z 33%Z) 34%Z 33%Z) 35%Z 33%Z)\n  36%Z 27%Z) 37%Z 27%Z) 38%Z 27%Z) 39%Z 30%Z) 40%Z 30%Z) 41%Z 30%Z) 42%Z\n  33%Z) 43%Z 33%Z) 44%Z 33%Z) 45%Z 27%Z) 46%Z 27%Z) 47%Z 27%Z) 48%Z 30%Z)\n  49%Z 30%Z) 50%Z 30%Z) 51%Z 33%Z) 52%Z 33%Z) 53%Z 33%Z) 54%Z 54%Z) 55%Z\n  54%Z) 56%Z 54%Z) 57%Z 57%Z) 58%Z 57%Z) 59%Z 57%Z) 60%Z 60%Z) 61%Z 60%Z)\n  62%Z 60%Z) 63%Z 54%Z) 64%Z 54%Z) 65%Z 54%Z) 66%Z 57%Z) 67%Z 57%Z) 68%Z\n  57%Z) 69%Z 60%Z) 70%Z 60%Z) 71%Z 60%Z) 72%Z 54%Z) 73%Z 54%Z) 74%Z 54%Z)\n  75%Z 57%Z) 76%Z 57%Z) 77%Z 57%Z) 78%Z 60%Z) 79%Z 60%Z) 80%Z 60%Z)\n  (set (set (set (set (set (set (set (set (set (const (-1%Z)%Z:(map Z Z)) 0%Z\n  0%Z) 1%Z 1%Z) 2%Z 2%Z) 3%Z 9%Z) 4%Z 10%Z) 5%Z 11%Z) 6%Z 18%Z) 7%Z 19%Z) 8%Z\n  20%Z)))).\n\n(* Why3 assumption *)\nDefinition full (g:(map Z Z)): Prop := forall (i:Z), (is_index i) ->\n  ((1%Z <= (get g i))%Z /\\ ((get g i) <= 9%Z)%Z).\n\n(* Why3 assumption *)\nDefinition included (g1:(map Z Z)) (g2:(map Z Z)): Prop := forall (i:Z),\n  ((is_index i) /\\ ((1%Z <= (get g1 i))%Z /\\ ((get g1 i) <= 9%Z)%Z)) ->\n  ((get g2 i) = (get g1 i)).\n\n(* Why3 assumption *)\nDefinition is_solution_for (sol:(map Z Z)) (data:(map Z Z)): Prop :=\n  (included data sol) /\\ ((full sol) /\\ (valid sol)).\n\n(* Why3 assumption *)\nInductive ref (a:Type) {a_WT:WhyType a} :=\n  | mk_ref : a -> ref a.\nAxiom ref_WhyType : forall (a:Type) {a_WT:WhyType a}, WhyType (ref a).\nExisting Instance ref_WhyType.\nImplicit Arguments mk_ref [[a] [a_WT]].\n\n(* Why3 assumption *)\nDefinition contents {a:Type} {a_WT:WhyType a} (v:(ref a)): a :=\n  match v with\n  | (mk_ref x) => x\n  end.\n\n(* Why3 assumption *)\nDefinition distinct_pair (g:(map Z Z)) (s:Z) (offsets:(map Z Z)) (o1:Z)\n  (o2:Z): Prop := let i1 := (s + (get offsets o1))%Z in let i2 :=\n  (s + (get offsets o2))%Z in ((~ (o1 = o2)) -> ((((1%Z <= (get g i1))%Z /\\\n  ((get g i1) <= 9%Z)%Z) /\\ ((1%Z <= (get g i2))%Z /\\ ((get g\n  i2) <= 9%Z)%Z)) -> ~ ((get g i1) = (get g i2)))).\n\n(* Why3 assumption *)\nDefinition distinct_pairs (g:(map Z Z)) (s:Z) (offsets:(map Z Z)) (o1:Z)\n  (o2:Z): Prop := forall (a:Z) (b:Z), (((0%Z <= a)%Z /\\ (a < o1)%Z) /\\\n  ((0%Z <= b)%Z /\\ (b < o2)%Z)) -> (distinct_pair g s offsets a b).\n\nAxiom distinct_pairs_to_valid_chunk : forall (g:(map Z Z)) (i:Z) (start:(map\n  Z Z)) (offsets:(map Z Z)), (distinct_pairs g (get start i) offsets 9%Z\n  9%Z) -> (valid_chunk g i start offsets).\n\n(* Why3 assumption *)\nInductive array\n  (a:Type) {a_WT:WhyType a} :=\n  | mk_array : Z -> (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] [a_WT]].\n\n(* Why3 assumption *)\nDefinition elts {a:Type} {a_WT:WhyType a} (v:(array a)): (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 get1 {a:Type} {a_WT:WhyType a} (a1:(array a)) (i:Z): a :=\n  (get (elts a1) i).\n\n(* Why3 assumption *)\nDefinition set1 {a:Type} {a_WT:WhyType a} (a1:(array a)) (i:Z) (v:a): (array\n  a) := (mk_array (length a1) (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 (const v:(map Z a))).\n\n(* Why3 assumption *)\nDefinition is_grid (g:(map Z Z)): Prop := forall (k:Z), ((1%Z <= (get g\n  k))%Z /\\ ((get g k) <= 9%Z)%Z) \\/ ((get g k) = (-1%Z)%Z).\n\n(* Why3 assumption *)\nDefinition partial (g:(map Z Z)) (i:Z): Prop := (forall (k:Z),\n  ((0%Z <= k)%Z /\\ (k < i)%Z) -> ((1%Z <= (get g k))%Z /\\ ((get g\n  k) <= 9%Z)%Z)) /\\ forall (k:Z), (is_index k) -> (((1%Z <= (get g k))%Z /\\\n  ((get g k) <= 9%Z)%Z) \\/ ((get g k) = (-1%Z)%Z)).\n\nAxiom partial_1 : forall (g:(map Z Z)) (i:Z), (i < 81%Z)%Z -> ((partial g\n  i) -> ((~ ((get g i) = (-1%Z)%Z)) -> (partial g (i + 1%Z)%Z))).\n\n(* Why3 goal *)\nTheorem WP_parameter_valid_update : forall (g:(map Z Z)) (i:Z) (x:Z),\n  (((is_grid g) /\\ (valid g)) /\\ ((1%Z <= x)%Z /\\ (x <= 9%Z)%Z)) ->\n  forall (j:Z), ((~ (i = j)) /\\ (is_index j)) -> ((valid_chunk (set g i x) j\n  (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (const (-1%Z)%Z:(map\n  Z Z)) 0%Z 0%Z) 1%Z 1%Z) 2%Z 2%Z) 3%Z 3%Z) 4%Z 4%Z) 5%Z 5%Z) 6%Z 6%Z) 7%Z\n  7%Z) 8%Z 8%Z) 9%Z 0%Z) 10%Z 1%Z) 11%Z 2%Z) 12%Z 3%Z) 13%Z 4%Z) 14%Z 5%Z)\n  15%Z 6%Z) 16%Z 7%Z) 17%Z 8%Z) 18%Z 0%Z) 19%Z 1%Z) 20%Z 2%Z) 21%Z 3%Z) 22%Z\n  4%Z) 23%Z 5%Z) 24%Z 6%Z) 25%Z 7%Z) 26%Z 8%Z) 27%Z 0%Z) 28%Z 1%Z) 29%Z 2%Z)\n  30%Z 3%Z) 31%Z 4%Z) 32%Z 5%Z) 33%Z 6%Z) 34%Z 7%Z) 35%Z 8%Z) 36%Z 0%Z) 37%Z\n  1%Z) 38%Z 2%Z) 39%Z 3%Z) 40%Z 4%Z) 41%Z 5%Z) 42%Z 6%Z) 43%Z 7%Z) 44%Z 8%Z)\n  45%Z 0%Z) 46%Z 1%Z) 47%Z 2%Z) 48%Z 3%Z) 49%Z 4%Z) 50%Z 5%Z) 51%Z 6%Z) 52%Z\n  7%Z) 53%Z 8%Z) 54%Z 0%Z) 55%Z 1%Z) 56%Z 2%Z) 57%Z 3%Z) 58%Z 4%Z) 59%Z 5%Z)\n  60%Z 6%Z) 61%Z 7%Z) 62%Z 8%Z) 63%Z 0%Z) 64%Z 1%Z) 65%Z 2%Z) 66%Z 3%Z) 67%Z\n  4%Z) 68%Z 5%Z) 69%Z 6%Z) 70%Z 7%Z) 71%Z 8%Z) 72%Z 0%Z) 73%Z 1%Z) 74%Z 2%Z)\n  75%Z 3%Z) 76%Z 4%Z) 77%Z 5%Z) 78%Z 6%Z) 79%Z 7%Z) 80%Z 8%Z)\n  (set (set (set (set (set (set (set (set (set (const (-1%Z)%Z:(map Z Z)) 0%Z\n  0%Z) 1%Z 9%Z) 2%Z 18%Z) 3%Z 27%Z) 4%Z 36%Z) 5%Z 45%Z) 6%Z 54%Z) 7%Z 63%Z)\n  8%Z 72%Z)) /\\ ((valid_chunk (set g i x) j\n  (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (const (-1%Z)%Z:(map\n  Z Z)) 0%Z 0%Z) 1%Z 0%Z) 2%Z 0%Z) 3%Z 0%Z) 4%Z 0%Z) 5%Z 0%Z) 6%Z 0%Z) 7%Z\n  0%Z) 8%Z 0%Z) 9%Z 9%Z) 10%Z 9%Z) 11%Z 9%Z) 12%Z 9%Z) 13%Z 9%Z) 14%Z 9%Z)\n  15%Z 9%Z) 16%Z 9%Z) 17%Z 9%Z) 18%Z 18%Z) 19%Z 18%Z) 20%Z 18%Z) 21%Z 18%Z)\n  22%Z 18%Z) 23%Z 18%Z) 24%Z 18%Z) 25%Z 18%Z) 26%Z 18%Z) 27%Z 27%Z) 28%Z\n  27%Z) 29%Z 27%Z) 30%Z 27%Z) 31%Z 27%Z) 32%Z 27%Z) 33%Z 27%Z) 34%Z 27%Z)\n  35%Z 27%Z) 36%Z 36%Z) 37%Z 36%Z) 38%Z 36%Z) 39%Z 36%Z) 40%Z 36%Z) 41%Z\n  36%Z) 42%Z 36%Z) 43%Z 36%Z) 44%Z 36%Z) 45%Z 45%Z) 46%Z 45%Z) 47%Z 45%Z)\n  48%Z 45%Z) 49%Z 45%Z) 50%Z 45%Z) 51%Z 45%Z) 52%Z 45%Z) 53%Z 45%Z) 54%Z\n  54%Z) 55%Z 54%Z) 56%Z 54%Z) 57%Z 54%Z) 58%Z 54%Z) 59%Z 54%Z) 60%Z 54%Z)\n  61%Z 54%Z) 62%Z 54%Z) 63%Z 63%Z) 64%Z 63%Z) 65%Z 63%Z) 66%Z 63%Z) 67%Z\n  63%Z) 68%Z 63%Z) 69%Z 63%Z) 70%Z 63%Z) 71%Z 63%Z) 72%Z 72%Z) 73%Z 72%Z)\n  74%Z 72%Z) 75%Z 72%Z) 76%Z 72%Z) 77%Z 72%Z) 78%Z 72%Z) 79%Z 72%Z) 80%Z\n  72%Z) (set (set (set (set (set (set (set (set (set (const (-1%Z)%Z:(map Z\n  Z)) 0%Z 0%Z) 1%Z 1%Z) 2%Z 2%Z) 3%Z 3%Z) 4%Z 4%Z) 5%Z 5%Z) 6%Z 6%Z) 7%Z 7%Z)\n  8%Z 8%Z)) /\\ (valid_chunk (set g i x) j\n  (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (set (const (-1%Z)%Z:(map\n  Z Z)) 0%Z 0%Z) 1%Z 0%Z) 2%Z 0%Z) 3%Z 3%Z) 4%Z 3%Z) 5%Z 3%Z) 6%Z 6%Z) 7%Z\n  6%Z) 8%Z 6%Z) 9%Z 0%Z) 10%Z 0%Z) 11%Z 0%Z) 12%Z 3%Z) 13%Z 3%Z) 14%Z 3%Z)\n  15%Z 6%Z) 16%Z 6%Z) 17%Z 6%Z) 18%Z 0%Z) 19%Z 0%Z) 20%Z 0%Z) 21%Z 3%Z) 22%Z\n  3%Z) 23%Z 3%Z) 24%Z 6%Z) 25%Z 6%Z) 26%Z 6%Z) 27%Z 27%Z) 28%Z 27%Z) 29%Z\n  27%Z) 30%Z 30%Z) 31%Z 30%Z) 32%Z 30%Z) 33%Z 33%Z) 34%Z 33%Z) 35%Z 33%Z)\n  36%Z 27%Z) 37%Z 27%Z) 38%Z 27%Z) 39%Z 30%Z) 40%Z 30%Z) 41%Z 30%Z) 42%Z\n  33%Z) 43%Z 33%Z) 44%Z 33%Z) 45%Z 27%Z) 46%Z 27%Z) 47%Z 27%Z) 48%Z 30%Z)\n  49%Z 30%Z) 50%Z 30%Z) 51%Z 33%Z) 52%Z 33%Z) 53%Z 33%Z) 54%Z 54%Z) 55%Z\n  54%Z) 56%Z 54%Z) 57%Z 57%Z) 58%Z 57%Z) 59%Z 57%Z) 60%Z 60%Z) 61%Z 60%Z)\n  62%Z 60%Z) 63%Z 54%Z) 64%Z 54%Z) 65%Z 54%Z) 66%Z 57%Z) 67%Z 57%Z) 68%Z\n  57%Z) 69%Z 60%Z) 70%Z 60%Z) 71%Z 60%Z) 72%Z 54%Z) 73%Z 54%Z) 74%Z 54%Z)\n  75%Z 57%Z) 76%Z 57%Z) 77%Z 57%Z) 78%Z 60%Z) 79%Z 60%Z) 80%Z 60%Z)\n  (set (set (set (set (set (set (set (set (set (const (-1%Z)%Z:(map Z Z)) 0%Z\n  0%Z) 1%Z 1%Z) 2%Z 2%Z) 3%Z 9%Z) 4%Z 10%Z) 5%Z 11%Z) 6%Z 18%Z) 7%Z 19%Z) 8%Z\n  20%Z)))).\nintros g i x ((h1,h2),(h3,h4)) j (h5,h6).\n\nQed.\n\n\n", "meta": {"author": "braibant", "repo": "why3-sudoku", "sha": "03df31e2e12d04e58867e273b5fd08476856339f", "save_path": "github-repos/coq/braibant-why3-sudoku", "path": "github-repos/coq/braibant-why3-sudoku/why3-sudoku-03df31e2e12d04e58867e273b5fd08476856339f/sudoku/sudoku_Solve_WP_parameter_valid_update_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.29147890995080844}}
{"text": "Require Import RamifyCoq.sample_mark.env_unionfind.\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_glist.\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 vlabel_in_bound (g: Graph) := forall x, vvalid g x -> Int.min_signed <= Z.of_nat (vlabel g x) <= Int.max_signed.\n\nDefinition mallocN_spec :=\n DECLARE _mallocN\n  WITH sh: wshare, n:Z\n  PRE [ 67%positive OF tint]\n     PROP (0 <= n <= Int.max_signed)\n     LOCAL (temp 67%positive (Vint (Int.repr n)))\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: 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 (findS g x 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: Graph, x: pointer_val, y: pointer_val\n  PRE [ _x OF (tptr (Tstruct _Node noattr)), _y OF (tptr (Tstruct _Node noattr))]\n          PROP  (vvalid g x /\\ vvalid g y)\n          LOCAL (temp _x (pointer_val_val x); temp _y (pointer_val_val y))\n          SEP   (whole_graph sh g)\n  POST [ Tvoid ]\n        EX g': Graph,\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: Graph\n    PRE []\n      PROP ()\n      LOCAL ()\n      SEP (whole_graph sh g)\n    POST [tptr (Tstruct _Node noattr)]\n      EX g': Graph, 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  - compute. split; intros; inversion H.\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: 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\n\n\n\n(*\nLemma localize': forall R_L PureG Espec {cs: compspecs} Delta P Q R R_FR R_G c Post,\n    split_FRZ_in_SEP R R_G R_FR ->\n    (forall e, @derives (forall _ : environ, mpred) (@LiftNatDed' mpred Nveric) (PROPx P e) (!! PureG)) ->\n\n  (let FR_L := @abbreviate _ R_L in\n   let FR_G := @abbreviate _ R_G in\n   exists  (w: FRZRw FR_L FR_G),\n  @semax cs Espec Delta (PROPx (PureG :: P) (LOCALx Q (SEPx (R_L ++ @FRZR FR_L FR_G w :: R_FR)))) c Post) ->\n  @semax cs Espec Delta (PROPx P (LOCALx Q (SEPx R))) c Post.\nProof.\n  intros.\n  destruct H1 as [? ?].\n  eapply semax_pre; [clear H1 | exact H1].\n  apply split_FRZ_in_SEP_spec in H.\n  apply andp_left2.\n  apply andp_derives; auto.  \n  simpl fold_right at 2.\n  rewrite prop_and.\n  apply andp_right. 2: apply derives_refl.\n  eapply derives_trans. 2: apply H0.\n  apply andp_right.\n   apply derives_refl. apply derives_refl.\n\n  apply prop_derives. intro. \n  simpl. \n  apply andp_derives; auto.\n  unfold SEPx; intro.\n  rewrite H.\n  rewrite fold_right_sepcon_app.\n  simpl.\n  cancel.\n  apply Freezer.FRZR1.\nQed.\n\nLtac localize' R_L PureG :=\n  eapply (localize' R_L PureG); [prove_split_FRZ_in_SEP | |];\n  let FR_L := fresh \"RamL\" in\n  let FR_G := fresh \"RamG\" in\n  intros FR_L FR_G;\n  eexists;\n  unfold_app.\n*)\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': Graph, EX rt : pointer_val,\n     PROP (findS g x 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 *.\n    Opaque pointer_val_val. forward. Transparent pointer_val_val.\n    (* Start ramification.  We need to get a bunch of pure facts from G1 that will\n       be used both in the construction of L2 and also in the ramification entailment.\n       Thus, we need to do them here.  Probably the engineering of \"localize\" could\n       be improved to make this cleaner. *)\n    (* *** *)\n    \n    pose proof (true_Cne_neq _ _ H1). \n    assert ((vgamma g' x) = (r, pa)) by (apply (findS_preserves_vgamma g); auto).\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 (destruct H3; apply (vgamma_not_reachable' _ _ r pa); auto).\n    remember (Graph_gen_redirect_parent g' x root H6 H7 H8) as g''.\n    assert (ggrp_rel g' x root g''). { exists H6, H7, H8. trivial. }\n    clear Heqg'' H6 H7 H8.    \n    (* *** *)\n    localize [data_at sh node_type (Vint (Int.repr (Z.of_nat r)), pointer_val_val pa) (pointer_val_val x)].\n    forward.\n    Exists g''. Exists root.\n    unlocalize [vertices_at sh (vvalid g'') g''] using g'' assuming H9.\n    + assert (root <> null). {\n        destruct H3. apply reachable_foot_valid in H3. intro. subst root. apply (valid_not_null g' null H3). simpl. auto. }\n      eapply derives_trans.\n      apply (@graph_gen_redirect_parent_ramify_rel _ (sSGG_VST sh)); eauto.\n      apply sepcon_derives. apply derives_refl.\n      apply allp_right. intro g'''.\n      (* make the next 3 lines a lemma *)\n      rewrite <- imp_andp_adjoint. rewrite andp_comm. rewrite imp_andp_adjoint.\n      apply prop_left. intro Heqg''.\n      rewrite <- imp_andp_adjoint. rewrite TT_andp.\n      subst g''. apply derives_refl.\n    + entailer!. split.\n      * apply (graph_gen_redirect_parent_findS g g' x r r pa root _ _ _); auto.\n      * simpl. apply (uf_root_gen_dst_same g' (liGraph g') x x root); auto.\n        -- apply (uf_root_edge _ (liGraph g') _ pa); auto. apply (vgamma_not_dst g' x r pa); auto.\n        -- apply reachable_refl; auto.\n  - forward. Exists g x. entailer!. apply false_Cne_eq in H1. subst pa. split; split; [|split| |]; auto.\n    + reflexivity.\n    + apply (uf_equiv_refl _  (liGraph g)).\n    + repeat intro; auto.\n    + apply uf_root_vgamma with (n := r); auto.\n  - Intros g' rt. forward. Exists g' rt. entailer!.\nQed.\n\n      assert (root <> null). {\n        destruct H3. apply reachable_foot_valid in H3. intro. subst root. apply (valid_not_null g' null H3). simpl. auto. }\n      eapply derives_trans.\n      apply (@graph_gen_redirect_parent_ramify _ (sSGG_VST sh)); eauto.\n      apply sepcon_derives. apply derives_refl.\n      apply allp_right. intro g''.\n      (* make the next 3 lines a lemma *)\n      rewrite <- imp_andp_adjoint. rewrite andp_comm. rewrite imp_andp_adjoint.\n      apply prop_left. intro Heqg''.\n      rewrite <- imp_andp_adjoint. rewrite TT_andp.\n      subst g''.\n      apply derives_refl.\n    + entailer!. split.\n      * apply (graph_gen_redirect_parent_findS g g' x r r pa root H5 H6 H8); auto.\n      * simpl. apply (uf_root_gen_dst_same g' (liGraph g') x x root); auto.\n        -- apply (uf_root_edge _ (liGraph g') _ pa); auto. apply (vgamma_not_dst g' x r pa); auto.\n        -- apply reachable_refl; auto.\n  - forward. Exists g x. entailer!. apply false_Cne_eq in H1. subst pa. split; split; [|split| |]; auto.\n    + reflexivity.\n    + apply (uf_equiv_refl _  (liGraph g)).\n    + repeat intro; auto.\n    + apply uf_root_vgamma with (n := r); auto.\n  - Intros g' rt. forward. Exists g' rt. entailer!.\nQed.\n\n\n\n      \n    assert (vertices_at sh (vvalid (Graph_gen_redirect_parent g' x root H5 H6 H8)) (Graph_gen_redirect_parent g' x root H5 H6 H8) =\n              vertices_at sh (vvalid g') (Graph_gen_redirect_parent g' x root H5 H6 H8)). {\n      apply vertices_at_Same_set. unfold Ensembles.Same_set, Ensembles.Included, Ensembles.In. simpl. intuition. }\n(*    rewrite H9. *)\n    (* Existentialize g'', drag it from L2 to G2. *)\n    + assert (root <> null). {\n        destruct H3. apply reachable_foot_valid in H3. intro. subst root. apply (valid_not_null g' null H3). simpl. auto. }\n      eapply derives_trans.\n      apply (@graph_gen_redirect_parent_ramify _ (sSGG_VST sh)); eauto.\n      apply sepcon_derives. apply derives_refl.\n      apply allp_right. intro g''.\n      (* make the next 3 lines a lemma *)\n      rewrite <- imp_andp_adjoint. rewrite andp_comm. rewrite imp_andp_adjoint.\n      apply prop_left. intro Heqg''.\n      rewrite <- imp_andp_adjoint. rewrite TT_andp.\n      subst g''.\n      apply derives_refl.\n    + entailer!. split.\n      * apply (graph_gen_redirect_parent_findS g g' x r r pa root H5 H6 H8); auto.\n      * simpl. apply (uf_root_gen_dst_same g' (liGraph g') x x root); auto.\n        -- apply (uf_root_edge _ (liGraph g') _ pa); auto. apply (vgamma_not_dst g' x r pa); auto.\n        -- apply reachable_refl; auto.\n  - forward. Exists g x. entailer!. apply false_Cne_eq in H1. subst pa. split; split; [|split| |]; auto.\n    + reflexivity.\n    + apply (uf_equiv_refl _  (liGraph g)).\n    + repeat intro; auto.\n    + apply uf_root_vgamma with (n := r); auto.\n  - Intros g' rt. forward. Exists g' rt. entailer!.\nQed.\n\n   apply wand_derives. apply derives_refl.\n      Exists (Graph_gen_redirect_parent g' x root H5 H6 H8).\n      apply andp_right.\n      * apply prop_right. split.\n        -- apply (graph_gen_redirect_parent_findS g g' x r r pa root H5 H6 H8); auto.\n        -- simpl. apply (uf_root_gen_dst_same g' (liGraph g') x x root); auto.\n           ++ apply (uf_root_edge _ (liGraph g') _ pa); auto. apply (vgamma_not_dst g' x r pa); auto.\n           ++ apply reachable_refl; auto.\n      * rewrite H9. apply derives_refl.\n\n        dag sh x g2] using g2 assuming H3.\n\n              \n    (* *** *)\n    unlocalize [EX g'' : Graph, !!(findS g x g'' /\\ uf_root g'' x root) && (vertices_at sh (vvalid g'') g'')].\n    + (* Now for the magic: proving the ramification entailment. *)\n  (*     Lemma uf_parent_ramif: forall sh g g' r pa x root, *)\n  (*       vertices_at sh (vvalid g') g' *)\n  (* |-- data_at sh node_type (Vint (Int.repr (Z.of_nat r)), pointer_val_val pa) *)\n  (*       (pointer_val_val x) * *)\n  (*     (data_at sh node_type (Vint (Int.repr (Z.of_nat r)), pointer_val_val root) *)\n  (*        (pointer_val_val x) -* *)\n  (*      (EX g'' : Graph, *)\n  (*       !! (findS g x g'' /\\ uf_root g'' x root) && vertices_at sh (vvalid g'') g'')). *)\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 ((vgamma g' x) = (r, pa)) by (apply (findS_preserves_vgamma g); auto).\n      assert (~ reachable g' root x) by (destruct H3; apply (vgamma_not_reachable' _ _ r pa); auto).\n      assert (vertices_at sh (vvalid (Graph_gen_redirect_parent g' x root H5 H6 H8)) (Graph_gen_redirect_parent g' x root H5 H6 H8) =\n              vertices_at sh (vvalid g') (Graph_gen_redirect_parent g' x root H5 H6 H8)). {\n        apply vertices_at_Same_set. unfold Ensembles.Same_set, Ensembles.Included, Ensembles.In. simpl. intuition. }\n      assert (root <> null). {\n        destruct H3. apply reachable_foot_valid in H3. intro. subst root. apply (valid_not_null g' null H3). simpl. auto. }\n      eapply derives_trans.\n      apply (@graph_gen_redirect_parent_ramify _ (sSGG_VST sh)); eauto.\n      apply sepcon_derives. apply derives_refl.\n      apply wand_derives. apply derives_refl.\n      Exists (Graph_gen_redirect_parent g' x root H5 H6 H8).\n      apply andp_right.\n      * apply prop_right. split.\n        -- apply (graph_gen_redirect_parent_findS g g' x r r pa root H5 H6 H8); auto.\n        -- simpl. apply (uf_root_gen_dst_same g' (liGraph g') x x root); auto.\n           ++ apply (uf_root_edge _ (liGraph g') _ pa); auto. apply (vgamma_not_dst g' x r pa); auto.\n           ++ apply reachable_refl; auto.\n      * rewrite H9. apply derives_refl.\n      (* End ramification entailment. *)\n    + clear. entailer!. Exists g''. Exists root. entailer!.\n  - forward. Exists g x. entailer!. apply false_Cne_eq in H1. subst pa. split; split; [|split| |]; auto.\n    + reflexivity.\n    + apply (uf_equiv_refl _  (liGraph g)).\n    + repeat intro; auto.\n    + apply uf_root_vgamma with (n := r); auto.\n  - Intros g' rt. forward. Exists g' rt. entailer!.\nQed. (* Original: 47.715 secs; VST 2.*: 2.335 secs *)\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  destruct H.\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 *. destruct H1 as [_ [? _]]. destruct H4 as [_ [? _]].\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\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 !; auto. 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': Graph,\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': Graph,\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. forward. Exists g3. entailer!.\nQed. (* Original: 205.811 secs; VST 2.*: 4.232 secs *)\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/uf_saved_not_pretty.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.291395599731867}}
{"text": "\nRequire Import VST.floyd.proofauto.\nRequire Import sll_dupleton.\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 sll_card : Set :=\n    | sll_card_0 : sll_card\n    | sll_card_1 : sll_card -> sll_card.\n\nFixpoint sll (x: val) (s: (list Z)) (self_card: sll_card) {struct self_card} : mpred := match self_card with\n    | sll_card_0  =>  !!((x : val) = nullval) && !!((s : list Z) = ([] : list Z)) && emp\n    | sll_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)) * (sll (nxt : val) (s1 : list Z) (_alpha_513 : sll_card))\nend.\n\n\nDefinition sll_dupleton_spec :=\n  DECLARE _sll_dupleton\n   WITH x: val, y: val, r: val, a: val\n   PRE [ tint, tint, (tptr (Tunion _sslval noattr)) ]\n   PROP( ssl_is_valid_int((x : val)); ssl_is_valid_int((y : val)); is_pointer_or_null((r : val)); is_pointer_or_null((a : val)) )\n   PARAMS(x; y; r)\n   SEP ((data_at Tsh (tarray (Tunion _sslval noattr) 1) [(inr (a : val))] (r : val)))\n   POST[ tvoid ]\n   EX elems: (list Z),\n   EX z: val,\n   EX _alpha_514: sll_card,\n   PROP( ((elems : list Z) = ([(force_signed_int (x : val)); (force_signed_int (y : val))] : list Z)); is_pointer_or_null((z : val)) )\n   LOCAL()\n   SEP ((data_at Tsh (tarray (Tunion _sslval noattr) 1) [(inr (z : val))] (r : val)); (sll (z : val) (elems : list Z) (_alpha_514 : sll_card))).\n\nLemma sll_x_valid_pointerP x s self_card: sll x s self_card |-- valid_pointer x. Proof. destruct self_card; simpl; entailer;  entailer!; eauto. Qed.\nHint Resolve sll_x_valid_pointerP : valid_pointer.\nLemma sll_local_factsP x s self_card :\n  sll x s self_card|-- !!(((((x : val) = nullval)) -> (self_card = sll_card_0))/\\(((~ ((x : val) = nullval))) -> (exists _alpha_513, self_card = sll_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 sll_local_factsP : saturate_local.\nLemma unfold_sll_card_0  (x: val) (s: (list Z)) : sll x s (sll_card_0 ) =  !!((x : val) = nullval) && !!((s : list Z) = ([] : list Z)) && emp. Proof. auto. Qed.\nLemma unfold_sll_card_1 (_alpha_513 : sll_card) (x: val) (s: (list Z)) : sll x s (sll_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)) * (sll (nxt : val) (s1 : list Z) (_alpha_513 : sll_card)). Proof. auto. Qed.\nDefinition Gprog : funspecs :=\n  ltac:(with_library prog [sll_dupleton_spec; malloc_spec]).\n\nLemma body_sll_dupleton : semax_body Vprog Gprog f_sll_dupleton sll_dupleton_spec.\nProof.\nstart_function.\nssl_open_context.\nassert_PROP (isptr r). { entailer!. }\ntry rename a into a2.\nforward.\nforward_call (tarray (Tunion _sslval noattr) 2).\nIntros z2.\nassert_PROP (isptr z2). { entailer!. }\nforward_call (tarray (Tunion _sslval noattr) 2).\nIntros nxtz2.\nassert_PROP (isptr nxtz2). { entailer!. }\nforward.\nforward.\nforward.\nforward.\nforward.\nforward; entailer!.\nExists ([(x : Z); (y : Z)] : list Z).\nExists (z2 : val).\nExists (sll_card_1 (sll_card_1 (sll_card_0  : sll_card) : sll_card) : sll_card).\nssl_entailer.\nrewrite (unfold_sll_card_1 (sll_card_1 (sll_card_0  : sll_card) : sll_card)) at 1.\nExists (x : Z).\nExists (([(y : Z)] : list Z) ++ ([] : list Z)).\nExists (nxtz2 : val).\nssl_entailer.\nrewrite (unfold_sll_card_1 (sll_card_0  : sll_card)) at 1.\nExists (y : Z).\nExists ([] : list Z).\nExists nullval.\nssl_entailer.\nrewrite (unfold_sll_card_0 ) at 1.\nssl_entailer.\n\nQed.\n", "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_sll_dupleton.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819874558604, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.29137221424833065}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool ssrnat seq.\nFrom mathcomp Require Import eqtype choice finfun finmap tuple.\nFrom eventstruct Require Import utils inhtype ident lts relaxed.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLocal Open Scope order_scope.\nLocal Open Scope fset_scope.\nLocal Open Scope ident_scope.\n\nModule SharedMem.\n\nSection Def.\nContext {dA dV : unit} {Addr : inhType dA} {Val : inhType dV}.\n\nLocal Notation null := (inh : Addr).\nLocal Notation v0   := (inh : Val).\n\nDefinition state := \n  { fsfun Addr -> Val for fun x => v0 }.\n\nVariant label := \n  | Read  of Addr & Val \n  | Write of Addr & Val \n  | Bot\n  .\n\nDefinition typ : label -> Lab.typ :=\n  fun l => match l with\n  | Read  _ _ => Lab.Read\n  | Write _ _ => Lab.Write\n  | Bot       => Lab.Undef\n  end.\n\nDefinition addr : label -> Addr :=\n  fun l => match l with\n  | Read  x _ => x\n  | Write x _ => x\n  | Bot       => null\n  end.\n\nDefinition value : label -> Val :=\n  fun l => match l with\n  | Read  _ v => v\n  | Write _ v => v\n  | Bot       => v0\n  end.\n\nEnd Def.\n\nArguments state {_ _} _ _ .\nArguments label {_ _} _ _ .\n\nSection Encode. \nContext {dA dV : unit} {Addr : inhType dA} {Val : inhType dV}.\n\nDefinition enc_lab : (label Addr Val) -> Addr * Val + Addr * Val + unit := \n  fun l => match l with \n  | Read  x v => inl (inl (x, v))\n  | Write x v => inl (inr (x, v))\n  | Bot       => inr tt\n  end.\n\nDefinition dec_lab : Addr * Val + Addr * Val + unit -> (label Addr Val) := \n  fun l => match l with \n  | inl (inl (x, v)) => Read x v\n  | inl (inr (x, v)) => Write x v\n  | inr _            => Bot\n  end.\n\nLemma enc_dec_labK : \n  cancel enc_lab dec_lab.\nProof. by case. Qed. \n\nEnd Encode.\n\nModule Export Exports.\nSection Exports.\nContext {dA dV : unit} {A : inhType dA} {V : inhType dV}.\n\nDefinition label_eqMixin := \n  CanEqMixin (@enc_dec_labK _ _ A V).\nCanonical label_eqType := \n  Eval hnf in EqType _ label_eqMixin.\n\nDefinition label_choiceMixin := \n  CanChoiceMixin (@enc_dec_labK _ _ A V).\nCanonical label_choiceType := \n  Eval hnf in ChoiceType _ label_choiceMixin.\n\nEnd Exports.\nEnd Exports.\n\n\nModule Export LTS.\nSection LTS.\nContext {dA dV : unit} {Addr : inhType dA} {Val : inhType dV}.\nLocal Notation state := (state Addr Val).\nLocal Notation label := (label Addr Val).\nImplicit Types (m : state) (l : label).\n\nDefinition read_trans l m m' := \n  let x := addr l in \n  let v := value l in \n  (typ l == Lab.Read) && (m x == v) && (m' == m).\n\nDefinition write_trans l m m' := \n  let x := addr l in \n  let v := value l in \n  (typ l == Lab.Write) && (m' == [fsfun m with x |-> v]).\n\nDefinition ltrans l m m' := \n  (read_trans l m m') || (write_trans l m m').\n\nDefinition enabled l m := \n  match l with \n  | Read  x v => m x == v\n  | Write x v => true\n  | Bot       => false\n  end.\n\nLemma enabledP l m :\n  reflect (exists m', ltrans l m m') (enabled l m).\nProof. \n  rewrite /ltrans /read_trans /write_trans /enabled.\n  case: l=> [x v | x v |]; try constructor=> //=; last first.\n  - by move=> [[]]. \n  - by exists ([fsfun m with x |-> v]).\n  case: (m x == v)=> //=; constructor; last by move=> [].\n  by exists m; rewrite eqxx. \nQed.\n\nEnd LTS.\n\nModule Export Exports.\nSection Exports.\nContext {dA dV : unit} {A : inhType dA} {V : inhType dV}.\n\nDefinition ltsMixin := \n  let S := (state A V) in\n  let L := (label A V) in\n  @LTS.LTS.Mixin S L _ _ _ enabledP. \nDefinition ltsType := \n  Eval hnf in (LTSType _ _ ltsMixin).\n\nEnd Exports.\nEnd Exports. \n\nEnd LTS.\n\nExport LTS.Exports.\n\n\nModule Export Label.\nSection Label.\nContext {dA dV : unit} {Addr : inhType dA} {Val : inhType dV}.\nLocal Notation label := (label Addr Val).\nImplicit Types (ls : {fset label}) (l : label).\n\nDefinition rf : rel label := \n  fun w r => match w, r with\n  | Write x a, Read y b => (x == y) && (a == b)\n  | _ , _ => false\n  end.\n\nDefinition com ws r := \n  let w := odflt Bot (fset_pick ws) in\n  (#|` ws | == 1) && (rf w r).\n\nDefinition cf_typ l1 l2 := \n  match (typ l1), (typ l2) with \n  | Lab.Read , Lab.Write  => true\n  | Lab.Write, Lab.Read   => true\n  | Lab.Write, Lab.Write  => true\n  | _        , _          => false\n  end.\n\nDefinition cf l1 l2 := \n  (cf_typ l1 l2) && (addr l1 == addr l2). \n\nDefinition is_write l := \n  typ l == Lab.Write.\n\nDefinition is_read l := \n  typ l == Lab.Read.\n\nLemma is_writeP w :\n  reflect (exists ws r, com ws r /\\ w \\in ws) (is_write w).\nProof. \n  apply/(equivP idP); split; rewrite /com /rf.\n  - move=> isW; exists [fset w].\n    move: w isW; case=> //= x v _.\n    exists (Read x v); rewrite inE; split=> //=.\n    by rewrite fset_pick1 cardfs1 /= !eqxx. \n  move=> /= [ws] [r] [] /andP[] /cardfs1P[w'] ->.\n  rewrite fset_pick1 inE /=. \n  by move=> /[swap] /eqP<-; case: w.\nQed.\n\nLemma is_readP r :\n  reflect (exists ws, com ws r) (is_read r).\nProof. \n  apply/(equivP idP); split; rewrite /com /rf.\n  - case: r=> // x v _.\n    exists [fset (Write x v)].\n    by rewrite fset_pick1 cardfs1 /= !eqxx. \n  move=> [ws] /andP[] /cardfs1P[w] ->.\n  rewrite fset_pick1 /=. \n  by case: w; case: r.\nQed.    \n\nLemma bot_nwrite : \n  ~~ is_write Bot.\nProof. done. Qed.\n\nLemma bot_nread : \n  ~~ is_read Bot.\nProof. done. Qed. \n\nEnd Label.\n\nModule Export Exports.\nSection Exports.\nContext {dA dV : unit} {A : inhType dA} {V : inhType dV}.\n\nDefinition inhMixin := @Inhabited.Mixin (label A V) _ Bot. \nCanonical inhType := Eval hnf in InhType (label A V) Bottom.disp inhMixin. \n\nDefinition labMixin := \n  @Lab.Lab.Mixin (label A V) _ com cf is_write is_read\n    is_writeP is_readP bot_nwrite bot_nread.\nCanonical labType := \n  Lab.Lab.Pack (Lab.Lab.Class labMixin).\n\nEnd Exports.\nEnd Exports.\n\nEnd Label.\n\nEnd SharedMem.\n\nExport SharedMem.Exports.\nExport SharedMem.LTS.Exports.\nExport SharedMem.Label.Exports.\n", "meta": {"author": "Event-Structures", "repo": "event-struct", "sha": "7a9b8b6f26621997d6c091beb1fd760dabb77ed9", "save_path": "github-repos/coq/Event-Structures-event-struct", "path": "github-repos/coq/Event-Structures-event-struct/event-struct-7a9b8b6f26621997d6c091beb1fd760dabb77ed9/theories/lang/sharedmem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.29137220749914816}}
{"text": "Require Import Core.\n\nNotation \"x >> y\" := (Z.shiftr x y) (at level 70) : Z_scope.\nNotation \"x << y\" := (Z.shiftl x y) (at level 70) : Z_scope.\nInfix \"&\" := Z.land (at level 70) : Z_scope.\nInfix \"or\" := Z.lor (at level 70): Z_scope.\n\n(* Notations for integers and ptrofs *)\n\nDelimit Scope ByteScope with byte.\nInfix \"==\" := Byte.eq (at level 70) : ByteScope.\nNotation \"x ~= y\" := (negb (Byte.eq x y)) (at level 70) : ByteScope.\nNotation \"x >> y\" := (Byte.shru x y) (at level 70) : ByteScope.\nNotation \"0\" := Byte.zero : ByteScope.\nNotation \"1\" := Byte.one : ByteScope.\nInfix \"+\" := Byte.add  : ByteScope.\nInfix \"-\" := Byte.sub : ByteScope.\nInfix \"*\" := Byte.mul : ByteScope.\nInfix \"<\" := Byte.lt : ByteScope.\nInfix \"<u\" := Byte.ltu (at level 70) : ByteScope.\nNotation \"x <=u y\" := (negb (Byte.ltu y x)) (at level 70) : ByteScope.\nNotation \"x <= y\" := (negb (Byte.lt y x)) (at level 70) : ByteScope.\nInfix \"%\" := Byte.mods (at level 70) : ByteScope.\nInfix \"//\" := Byte.divs (at level 70) : ByteScope. \nInfix \"&\" := Byte.and (at level 70) : ByteScope. \n\n\nDelimit Scope IntScope with int.\nInfix \"==\" := Int.eq (at level 70) : IntScope.\nNotation \"x ~= y\" := (negb Int.eq x y) (at level 70) : IntScope.\nNotation \"x >> y\" := (Int.shr x y) (at level 70) : IntScope.\nNotation \"x >>u y\" := (Int.shru x y) (at level 70) : IntScope.\nNotation \"x << y\" := (Int.shl x y) (at level 70) : IntScope.\nNotation \"0\" := Int.zero : IntScope.\nNotation \"1\" := Int.one : IntScope.\nInfix \"+\" := Int.add : IntScope.\nInfix \"-\" := Int.sub : IntScope.\nInfix \"*\" := Int.mul : IntScope.\nInfix \"<\" := Int.lt : IntScope.\nInfix \"<u\" := Int.ltu (at level 70) : IntScope.\nNotation \"x <=u y\" := (negb (Int.ltu y x)) (at level 70) : IntScope.\nNotation \"x <= y\" := (negb (Int.lt y x)) (at level 70) : IntScope.\nInfix \"%\" := Int.mods (at level 70) : IntScope.\nInfix \"//\" := Int.divs (at level 70) : IntScope.\nInfix \"&\" := Int.and (at level 70) : IntScope. \nInfix \"or\" := Int.or (at level 70) : IntScope. \n\n\nDelimit Scope Int64Scope with int64.\nInfix \"==\" := Int64.eq (at level 70) : Int64Scope.\nNotation \"x ~= y\" := (negb Int64.eq x y) (at level 70) : Int64Scope.\nNotation \"x >> y\" := (Int64.shru x y) (at level 70) : Int64Scope.\nNotation \"0\" := Int64.zero : Int64Scope.\nNotation \"1\" := Int64.one : Int64Scope.\nInfix \"+\" := Int64.add : Int64Scope.\nInfix \"-\" := Int64.sub : Int64Scope.\nInfix \"*\" := Int64.mul : Int64Scope.\nInfix \"<\" := Int64.lt : Int64Scope.\nNotation \"x <= y\" := (negb (Int64.lt y x)) (at level 70) : Int64Scope.\nNotation \"x <=u y\" := (negb (Int64.ltu y x)) (at level 70) : Int64Scope.\nInfix \"%\" := Int64.mods (at level 70) : Int64Scope.\nInfix \"//\" := Int64.divs (at level 70) : Int64Scope.\n \nDelimit Scope PtrofsScope with ptrofs.\nInfix \"==\" := Ptrofs.eq (at level 70) : PtrofsScope.\nNotation \"x ~= y\" := (negb Ptrofs.eq x y) (at level 70) : PtrofsScope.\nNotation \"x >> y\" := (Ptrofs.shru x y) (at level 70) : PtrofsScope.\nNotation \"0\" := Ptrofs.zero : PtrofsScope.\nNotation \"1\" := Ptrofs.one : PtrofsScope.\nInfix \"+\" := Ptrofs.add : PtrofsScope.\nInfix \"-\" := Ptrofs.sub : PtrofsScope.\nInfix \"*\" := Ptrofs.mul : PtrofsScope.\nInfix \"<\" := Ptrofs.lt : PtrofsScope.\nInfix \"<u\" := Ptrofs.ltu (at level 70) : PtrofsScope.\nNotation \"x <= y\" := (negb (Ptrofs.lt y x)) (at level 70) : PtrofsScope.\nNotation \"x <=u y\" := (negb (Ptrofs.ltu y x)) (at level 70) : PtrofsScope.\nInfix \"%\" := Ptrofs.mods (at level 70) : PtrofsScope.\nInfix \"//\" := Ptrofs.divs (at level 70) : PtrofsScope.\n\nDelimit Scope PTreeScope with ptree.\nNotation \"a <~ b\" := (a, b) (at level 85, only parsing).\nDefinition s {A : Type} (a : (positive * A)) := PTree.set (fst a) (snd a).\nNotation \"'in' env 'set' [ x ; .. ; y ]\" :=\n  ((s x) .. ((s y) env) ..)\n    (at level 85, right associativity).\n\n\nDelimit Scope ByteScope with byte.\nInfix \"==\" := Byte.eq (at level 70) : ByteScope.\nNotation \"x ~= y\" := (negb Byte.eq x y) (at level 70) : ByteScope.\nNotation \"x >> y\" := (Byte.shru x y) (at level 70) : ByteScope.\nNotation \"0\" := Byte.zero : ByteScope.\nNotation \"1\" := Byte.one : ByteScope.\nInfix \"+\" := Byte.add : ByteScope.\nInfix \"-\" := Byte.sub : ByteScope.\nInfix \"*\" := Byte.mul : ByteScope. \nInfix \"<\" := Byte.lt (at level 70) : ByteScope.\nNotation \"x <=u y\" := (negb (Byte.ltu y x)) (at level 70) : ByteScope.\nNotation \"x <= y\" := (negb (Byte.lt y x)) (at level 70) : ByteScope.\nInfix \"%\" := Byte.mods (at level 70) : ByteScope.\nInfix \"//\" := Byte.divs (at level 70) : ByteScope.\n\n(* Byte list notations *)\nNotation all_zero := Byte.zero.\nDefinition all_one  := Byte.repr (Byte.max_unsigned).\nNotation default_byte := all_zero.\nNotation \"t @ n\" := (Byte.testbit t n) (at level 50).\nNotation len a := (Zlength a).\nDefinition flatten {A} l := fold_right (@app _) (@nil A) l.\n\nClass Nth A := \n  { default : A;\n    n_th : Z -> list A -> A;\n    hd_nth : list A -> A }.\n\nNotation \"ls # n\" := (n_th n ls) (at level 70).\n\nInstance Nth_Byte : Nth byte :=\n  { default := default_byte ;\n    n_th := fun n ls => nth (Z.to_nat n) ls default_byte;\n    hd_nth := fun ls => List.hd default_byte ls\n    }.\n\nInstance Nth_Bool : Nth bool :=\n  { default := false ;\n    n_th := fun n ls => nth (Z.to_nat n)  ls false;\n    hd_nth := fun ls => List.hd false ls\n }.\n\n\nInstance Nth_List {A} : Nth (list A) :=\n  { default := [] ;\n    n_th := fun n ls => nth (Z.to_nat n) ls [];\n    hd_nth := fun ls => List.hd [] ls\n }.\n\nRequire Import ExtLib.Structures.Monad.\n\nInductive DWT_Error := .\n\n Delimit Scope monad_scope with monad.\n\n  Notation \"c >>= f\" := (@bind _ _ _ _ c f) (at level 58, left associativity) : monad_scope.\n  Notation \"f =<< c\" := (@bind _ _ _ _ c f) (at level 61, right associativity) : monad_scope.\n  Notation \"f >=> g\" := (@mcompose _ _ _ _ _ f g) (at level 55, right associativity) : monad_scope. \n\n  Notation \"x <- c1 ;; c2\" := (@bind _ _ _ _ c1 (fun x => c2))\n    (at level 61, c1 at next level, right associativity) : monad_scope.\n\n  Notation \"e1 ;; e2\" := (_ <- e1%monad ;; e2%monad)%monad\n    (at level 61, right associativity) : monad_scope.\n\n  Notation \"' pat <- c1 ;; c2\" :=\n    (@bind _ _ _ _ c1 (fun x => match x with pat => c2 end))\n    (at level 61, pat pattern, c1 at next level, right associativity) : monad_scope.\n", "meta": {"author": "asosyuk", "repo": "asn1verification", "sha": "55395d63c2dcd512a28d9cd42d788e12f91e7641", "save_path": "github-repos/coq/asosyuk-asn1verification", "path": "github-repos/coq/asosyuk-asn1verification/asn1verification-55395d63c2dcd512a28d9cd42d788e12f91e7641/src/Core/Notations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.29137220074996567}}
{"text": "Require Import Crypto.Compilers.Syntax.\nRequire Import Crypto.Compilers.Named.Context.\nRequire Import Crypto.Compilers.Named.ContextProperties.\nRequire Import Crypto.Compilers.Named.ContextDefinitions.\nRequire Import Crypto.Compilers.Named.Syntax.\nRequire Import Crypto.Compilers.Named.Wf.\nRequire Import Crypto.Util.PointedProp.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nRequire Import Crypto.Util.Tactics.SplitInContext.\nRequire Import Crypto.Util.Tactics.DestructHead.\nRequire Import Crypto.Util.Decidable.\nRequire Import Crypto.Util.Option.\n\nSection language.\n  Context {base_type_code Name : Type}\n          {op : flat_type base_type_code -> flat_type base_type_code -> Type}\n          {base_type_code_dec : DecidableRel (@eq base_type_code)}\n          {Name_dec : DecidableRel (@eq Name)}.\n\n  Section with_var.\n    Context {var}\n            (uContext : @Context base_type_code Name (fun _ => unit))\n            (uContextOk : ContextOk uContext)\n            (vContext : @Context base_type_code Name var)\n            (vContextOk : ContextOk vContext).\n\n    Local Ltac t :=\n      repeat first [ progress simpl in *\n                   | progress intros\n                   | progress subst\n                   | progress inversion_option\n                   | congruence\n                   | tauto\n                   | solve [ eauto ]\n                   | break_innermost_match_step\n                   | break_innermost_match_hyps_step\n                   | progress destruct_head'_and\n                   | progress autorewrite with push_prop_of_option push_eq_Some_trivial in *\n                   | rewrite !(@lookupb_extend base_type_code _ Name _) by auto\n                   | rewrite (@find_Name_and_val_split base_type_code _ Name _) with (default := lookupb _ _)\n                   | match goal with\n                     | [ H : ?x = Some _ |- _ ]\n                       => assert (x = None) by (split_iff; eauto); congruence\n                     | [ |- _ /\\ _ ] => split\n                     | [ H : _ |- prop_of_option _ ] => eapply H; [ | eassumption ]; clear H\n                     | [ |- context[find_Name_and_val ?tdec ?ndec ?b _ _ _ _ = None] ]\n                       => rewrite <- !(@find_Name_and_val_None_iff _ tdec _ ndec _ b)\n                     end ].\n\n    Lemma wff_from_unit\n          (vctx : vContext)\n          (uctx : uContext)\n          (Hctx : forall t n, lookupb t vctx n = None <-> lookupb t uctx n = None)\n          {t} (e : @exprf base_type_code op Name t)\n      : wff_unit uctx e = Some trivial -> prop_of_option (wff vctx e).\n    Proof using Name_dec base_type_code_dec uContextOk vContextOk.\n      revert uctx vctx Hctx; induction e; t.\n    Qed.\n\n    Lemma wf_from_unit\n          (vctx : vContext)\n          (uctx : uContext)\n          (Hctx : forall t n, lookupb t vctx n = None <-> lookupb t uctx n = None)\n          {t} (e : @expr base_type_code op Name t)\n      : wf_unit uctx e = Some trivial -> wf vctx e.\n    Proof using Name_dec base_type_code_dec uContextOk vContextOk.\n      intros H ?; revert H; apply wff_from_unit; t.\n    Qed.\n  End with_var.\n\n  Lemma Wf_from_unit\n        (Context : forall var, @Context base_type_code Name var)\n        (ContextOk : forall var, ContextOk (Context var))\n        {t} (e : @expr base_type_code op Name t)\n    : wf_unit (Context:=Context _) empty e = Some trivial -> Wf Context e.\n  Proof using Name_dec base_type_code_dec.\n    intros H ?; revert H; apply wf_from_unit; auto; intros.\n    rewrite !lookupb_empty by auto; tauto.\n  Qed.\nEnd language.\n\nHint Resolve wf_from_unit Wf_from_unit wff_from_unit : 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/Named/WfFromUnit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2913722007499656}}
{"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.\nRequire Import TableAux3.Spec.\n\nLocal Open Scope Z_scope.\n\nSection SpecLow.\n\n  Definition table_create_spec0 (g_rd: Pointer) (map_addr: Z64) (level: Z64) (g_rtt: Pointer) (rtt_addr: Z64) (adt: RData) : option (RData * Z64) :=\n    match g_rd, map_addr, level, g_rtt, rtt_addr with\n    | (_g_rd_base, _g_rd_ofst), VZ64 _map_addr, VZ64 _level, (_g_rtt_base, _g_rtt_ofst), VZ64 _rtt_addr =>\n      let _ret := 0 in\n      rely is_int64 (_level - 1);\n      rely is_int64 _map_addr;\n      when adt == table_walk_lock_unlock_spec (_g_rd_base, _g_rd_ofst) (VZ64 _map_addr) (VZ64 (_level - 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'6 == is_null_spec (_g_llt_base, _g_llt_ofst) adt;\n      rely is_int _t'6;\n      if (_t'6 =? 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' _llt_pte == pgte_read_spec (_ll_table_base, _ll_table_ofst) (VZ64 _index) adt;\n        rely is_int64 _llt_pte;\n        when _t'5 == entry_is_table_spec (VZ64 _llt_pte) adt;\n        rely is_int _t'5;\n        if (_t'5 =? 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 _level;\n          rely is_int64 _rtt_addr;\n          when adt == table_create_aux_spec (_g_rd_base, _g_rd_ofst) (_g_llt_base, _g_llt_ofst) (_g_rtt_base, _g_rtt_ofst) (VZ64 _llt_pte) (_ll_table_base, _ll_table_ofst) (VZ64 _level) (VZ64 _index) (VZ64 _map_addr) (VZ64 _rtt_addr) adt;\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/table_create.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6654105454764746, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2913323733679999}}
{"text": "Require Export RecTypes.SpecTypes.\nRequire Export RecTypes.InstTy.\nRequire Export RecTypes.Contraction.\nRequire Export RecTypes.ValidTy.\nRequire Export RecTypes.LemmasTypes.\n\nRequire Import StlcEqui.SpecEvaluation.\nRequire Import StlcEqui.SpecTyping.\nRequire Import StlcEqui.LemmasTyping.\n\n(* Lemma can_form_tarr {Γ t τ₁ τ₂} *)\n(*   (v: Value t) (wt: ⟪ Γ e⊢ t : τ₁ e⇒ τ₂ ⟫)  : *)\n(*   ∃ σ₁ t₂, *)\n(*     ⟪ τ₁ ≗ σ₁ ⟫ → *)\n(*     t = abs σ₁ t₂ ∧ *)\n(*     ⟪ Γ e▻ τ₁ e⊢ t₂ : τ₂ ⟫. *)\n(* Proof. depind wt; try contradiction; eauto. *)\n(*        depind T; try inversion H; eauto. *)\n(*        - (* tarr *) *)\n(*          subst. *)\n(*          apply (IHwt _ _ v). *)\n\n(*        - (* trec *) idtac. *)\n(* Qed. *)\n\nLemma trec_tunit_eq_tunit : ⟪ tunit ≗ trec tunit ⟫.\nProof.\n  constructor;\n  eauto with simple_contr_rec.\n  cbn.\n  apply tyeq_refl.\nQed.\n\nLemma can_form_tarr {Γ t τ τ₁ τ₂}\n  (v: Value t) (wt: ⟪ Γ e⊢ t : τ ⟫) (tyeq: ⟪ τ ≗ τ₁ r⇒ τ₂ ⟫) :\n  ValidEnv Γ ->\n  ValidTy τ ->\n  ValidTy τ₁ →\n  ValidTy τ₂ →\n  ∃ t₂ τ₁',\n    ⟪ τ₁' ≗ τ₁ ⟫ ∧\n      ValidTy τ₁' /\\\n    t = abs τ₁' t₂ ∧\n    ⟪ Γ r▻ τ₁ e⊢ t₂ : τ₂ ⟫.\nProof.\n  depind wt; try inversion tyeq; try contradiction; eauto;\n  subst; intros.\n  - exists t, τ₁0.\n    destruct (ValidTy_invert_arr H1) as [τ1_v τ2_v].\n    repeat (split; eauto).\n    apply (WtEq _ H5); eauto.\n    eapply (eqctx_implies_eqty (Γ r▻ τ₁0));\n    eauto using enveq_refl with tyvalid tyeq.\n  - apply IHwt; eauto.\n    unshelve eapply (eq_trans_contr _ H tyeq); eauto with simple_contr_rec tyvalid.\n  - apply IHwt; eauto.\n    unshelve eapply (eq_trans_contr _ H tyeq); eauto with simple_contr_rec tyvalid.\nQed.\n\nLemma can_form_tunit {Γ t τ}\n  (v: Value t) (wt: ⟪ Γ e⊢ t : τ ⟫) (tyeq: ⟪ τ ≗ tunit ⟫) :\n    t = unit.\nProof.\n  depind wt; try inversion tyeq; try contradiction; eauto.\n  subst.\n  apply (IHwt v H).\n  apply (IHwt v).\n  subst.\n  unshelve eapply (eq_trans_contr _ H tyeq);\n    eauto with simple_contr_rec.\nQed.\n\nLemma can_form_tunit' {Γ t}\n  (v: Value t) (wt: ⟪ Γ e⊢ t : tunit ⟫) :\n    t = unit.\nProof.\n  apply (can_form_tunit v wt).\n  eapply tyeq_refl.\nQed.\n\nLemma can_form_tbool {Γ t τ}\n  (v: Value t) (wt: ⟪ Γ e⊢ t : τ ⟫) (tyeq: ⟪ τ ≗ tbool ⟫):\n    t = true ∨ t = false.\nProof.\n  depind wt; try inversion tyeq; try contradiction; eauto;\n  subst;\n  apply (IHwt v).\n  assumption.\n  unshelve eapply (eq_trans_contr _ H tyeq);\n    eauto with simple_contr_rec.\nQed.\n\nLemma can_form_tbool' {Γ t}\n  (v: Value t) (wt: ⟪ Γ e⊢ t : tbool ⟫) :\n    t = true ∨ t = false.\nProof. apply (can_form_tbool v wt); apply tyeq_refl. Qed.\n\nLemma can_form_tprod {Γ t τ τ₁ τ₂}\n  (v: Value t) (wt: ⟪ Γ e⊢ t : τ ⟫) (tyeq: ⟪ τ ≗ τ₁ r× τ₂ ⟫) :\n  ValidEnv Γ →\n  ValidTy τ₁ ->\n  ValidTy τ₂ ->\n  ∃ t₁ t₂, t = pair t₁ t₂ ∧\n  ⟪ Γ e⊢ t₁ : τ₁ ⟫ ∧\n  ⟪ Γ e⊢ t₂ : τ₂ ⟫.\nProof.\n  depind wt; try inversion tyeq; try contradiction;\n  subst; intros.\n  - exists t₁, t₂. repeat split; eapply WtEq; eauto using typed_terms_are_valid with tyvalid.\n  - apply IHwt; eauto.\n    refine (eq_trans_contr _ H _);\n    eauto with simple_contr_rec.\n  - apply IHwt; eauto.\n    (refine (eq_trans_contr _ H _); eauto with simple_contr_rec).\nQed.\n\nLemma can_form_tsum {Γ t τ τ₁ τ₂}\n  (v: Value t) (wt: ⟪ Γ e⊢ t : τ ⟫) (tyeq: ⟪ τ ≗ τ₁ r⊎ τ₂ ⟫) :\n  ValidEnv Γ ->\n  ValidTy τ₁ →\n  ValidTy τ₂ →\n    (∃ t₁, t = inl t₁ ∧ ⟪  Γ e⊢ t₁ : τ₁ ⟫) ∨\n    (∃ t₂, t = inr t₂ ∧ ⟪  Γ e⊢ t₂ : τ₂ ⟫).\nProof.\n  depind wt; try inversion tyeq; try contradiction; subst.\n  - left;\n    exists t; repeat split; eapply WtEq; eauto using typed_terms_are_valid.\n  - right;\n    exists t; repeat split; eapply WtEq; eauto using typed_terms_are_valid .\n  - intros.\n    apply IHwt; eauto.\n    refine (eq_trans_contr _ H _); eauto with simple_contr_rec tyvalid.\n  - intros.\n    apply IHwt; eauto.\n    refine (eq_trans_contr _ H _); eauto with simple_contr_rec tyvalid.\nQed.\n\nLtac stlcCanForm1 :=\n  match goal with\n    | [ wt: ⟪ _ e⊢ ?t : tarr ?τ₁ ?τ₂ ⟫, vt: Value ?t |- _ ] =>\n      destruct (can_form_tarr (τ₁ := τ₁) (τ₂ := τ₂) vt wt); subst; clear wt\n    | [ wt: ⟪ _ e⊢ ?t : tunit ⟫, vt: Value ?t |- _ ] =>\n      pose proof (can_form_tunit vt wt); subst; clear wt\n    | [ wt: ⟪ _ e⊢ ?t : tbool ⟫, vt: Value ?t |- _ ] =>\n      destruct (can_form_tbool vt wt); subst; clear wt\n    | [ wt: ⟪ _ e⊢ ?t : tprod ?τ₁ ?τ₂ ⟫, vt: Value ?t |- _ ] =>\n      destruct (can_form_tprod (τ₁ := τ₁) (τ₂ := τ₂) vt wt) as (? & ? & ? & ? & ?);\n      eauto with tyeq tyvalid;\n      subst; clear wt\n    | [ wt: ⟪ _ e⊢ ?t : tsum ?τ₁ ?τ₂ ⟫, vt: Value ?t |- _ ] =>\n      destruct (can_form_tsum (τ₁ := τ₁) (τ₂ := τ₂) vt wt) as [[? [? ?]]|[? [? ?]]];\n      eauto with tyeq tyvalid;\n      subst; clear wt; simpl in vt\n  end.\n\nLtac stlcCanForm :=\n  repeat stlcCanForm1.\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/StlcEqui/CanForm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2913207089878606}}
{"text": "Require Export List.\nRequire Export Bool.\nRequire Export Arith.\nRequire Export Peano_dec.\nRequire Export Coq.Arith.PeanoNat.\nRequire Import CpdtTactics.\nRequire Export Coq.Program.Wf.\nRequire Export Coq.Program.Tactics.\nRequire Export Coq.Logic.FunctionalExtensionality.\nRequire Export Recdef.\nRequire Import wyv_common.\nRequire Import rhs_mat_tree.\nSet Implicit Arguments.\n\nImport WfExtensionality.\n\nLemma subtype_sel_low_sel_upp_reduce : \n  forall T1 x1 L1 T1', T1 = (t_sel_low x1 L1 T1') ->\n                  forall T2 x2 L2 T2', T2 = (t_sel_upp x2 L2 T2') ->\n                                  subtype T1 T2 = andb (eq_var x1 x2)\n                                                       (eq_label L1 L2).\nProof.\n  intros.\n\n  remember (subtype T1 T2) as sub_fn; subst T1 T2.\n  \n  unfold subtype, subtype_func in Heqsub_fn;\n    simpl in Heqsub_fn;\n    rewrite fix_sub_eq_ext in Heqsub_fn;\n    simpl in Heqsub_fn;\n    fold subtype_func in Heqsub_fn;\n    auto.\nQed.\n\nLemma subtype_sel_low_sel_low_reduce : \n  forall T1 x1 L1 T1', T1 = (t_sel_low x1 L1 T1') ->\n                  forall T2 x2 L2 T2', T2 = (t_sel_low x2 L2 T2') ->\n                                  subtype T1 T2 = orb (andb (eq_var x1 x2)\n                                                            (eq_label L1 L2))\n                                                      (subtype T1 T2').\nProof.\n  intros.\n\n  remember (subtype T1 T2) as sub_fn; subst T1 T2.\n  \n  unfold subtype, subtype_func in Heqsub_fn;\n    simpl in Heqsub_fn;\n    rewrite fix_sub_eq_ext in Heqsub_fn;\n    simpl in Heqsub_fn;\n    fold subtype_func in Heqsub_fn;\n    auto.\nQed.\n\nLemma subtype_sel_low_sel_equ_reduce : \n  forall T1 x1 L1 T1', T1 = (t_sel_low x1 L1 T1') ->\n                  forall T2 x2 L2 T2', T2 = (t_sel_equ x2 L2 T2') ->\n                                  subtype T1 T2 = orb (andb (eq_var x1 x2)\n                                                            (eq_label L1 L2))\n                                                      (subtype T1 T2').\nProof.\n  intros.\n\n  remember (subtype T1 T2) as sub_fn; subst T1 T2.\n  \n  unfold subtype, subtype_func in Heqsub_fn;\n    simpl in Heqsub_fn;\n    rewrite fix_sub_eq_ext in Heqsub_fn;\n    simpl in Heqsub_fn;\n    fold subtype_func in Heqsub_fn;\n    auto.\nQed.\n\nLemma subtype_sel_low_sel_nom_reduce : \n  forall T1 x1 L1 T1', T1 = (t_sel_low x1 L1 T1') ->\n                  forall T2 x2 L2 T2', T2 = (t_sel_nom x2 L2 T2') ->\n                                  subtype T1 T2 = andb (eq_var x1 x2)\n                                                       (eq_label L1 L2).\nProof.\n  intros.\n\n  remember (subtype T1 T2) as sub_fn; subst T1 T2.\n  \n  unfold subtype, subtype_func in Heqsub_fn;\n    simpl in Heqsub_fn;\n    rewrite fix_sub_eq_ext in Heqsub_fn;\n    simpl in Heqsub_fn;\n    fold subtype_func in Heqsub_fn;\n    auto.\nQed.\n\nLemma subtype_sel_low_upp_reduce : \n  forall T1 x1 L1 T1', T1 = (t_sel_low x1 L1 T1') ->\n                  forall T2 L2 T2', T2 = (t_upp L2 T2') ->\n                               subtype T1 T2 = false.\nProof.\n  intros.\n\n  remember (subtype T1 T2) as sub_fn; subst T1 T2.\n  \n  unfold subtype, subtype_func in Heqsub_fn;\n    simpl in Heqsub_fn;\n    rewrite fix_sub_eq_ext in Heqsub_fn;\n    simpl in Heqsub_fn;\n    fold subtype_func in Heqsub_fn;\n    auto.\n\nQed.\n\nLemma subtype_sel_low_low_reduce : \n  forall T1 x1 L1 T1', T1 = (t_sel_low x1 L1 T1') ->\n                  forall T2 L2 T2', T2 = (t_low L2 T2') ->\n                               subtype T1 T2 = false.\nProof.\n  intros.\n\n  remember (subtype T1 T2) as sub_fn; subst T1 T2.\n  \n  unfold subtype, subtype_func in Heqsub_fn;\n    simpl in Heqsub_fn;\n    rewrite fix_sub_eq_ext in Heqsub_fn;\n    simpl in Heqsub_fn;\n    fold subtype_func in Heqsub_fn;\n    auto.\n\nQed.\n\nLemma subtype_sel_low_equ_reduce : \n  forall T1 x1 L1 T1', T1 = (t_sel_low x1 L1 T1') ->\n                  forall T2 L2 T2', T2 = (t_equ L2 T2') ->\n                               subtype T1 T2 = false.\nProof.\n  intros.\n\n  remember (subtype T1 T2) as sub_fn; subst T1 T2.\n  \n  unfold subtype, subtype_func in Heqsub_fn;\n    simpl in Heqsub_fn;\n    rewrite fix_sub_eq_ext in Heqsub_fn;\n    simpl in Heqsub_fn;\n    fold subtype_func in Heqsub_fn;\n    auto.\n\nQed.\n\nLemma subtype_sel_low_nom_reduce : \n  forall T1 x1 L1 T1', T1 = (t_sel_low x1 L1 T1') ->\n                  forall T2 L2 t T2', T2 = (t_nom L2 t T2') ->\n                                 subtype T1 T2 = false.\nProof.\n  intros.\n\n  remember (subtype T1 T2) as sub_fn; subst T1 T2.\n  \n  unfold subtype, subtype_func in Heqsub_fn;\n    simpl in Heqsub_fn;\n    rewrite fix_sub_eq_ext in Heqsub_fn;\n    simpl in Heqsub_fn;\n    fold subtype_func in Heqsub_fn;\n    auto.\n\nQed.\n\nLemma subtype_sel_low_rfn_top_reduce : \n  forall T1 x1 L1 T1', T1 = (t_sel_low x1 L1 T1') ->\n                  forall T2 Ts, T2 = (t_rfn_top Ts) ->\n                           subtype T1 T2 = false.\nProof.\n  intros.\n\n  remember (subtype T1 T2) as sub_fn; subst T1 T2.\n  \n  unfold subtype, subtype_func in Heqsub_fn;\n    simpl in Heqsub_fn;\n    rewrite fix_sub_eq_ext in Heqsub_fn;\n    simpl in Heqsub_fn;\n    fold subtype_func in Heqsub_fn;\n    auto. \nQed.\n\nLemma subtype_sel_low_rfn_sel_reduce : \n  forall T1 x1 L1 T1', T1 = (t_sel_low x1 L1 T1') ->\n                  forall x2 L2 T2 Ts T', T2 = (t_rfn_sel x2 L2 Ts T') ->\n                                    subtype T1 T2 = false.\nProof.\n  intros.\n\n  remember (subtype T1 T2) as sub_fn; subst T1 T2.\n  \n  unfold subtype, subtype_func in Heqsub_fn;\n    simpl in Heqsub_fn;\n    rewrite fix_sub_eq_ext in Heqsub_fn;\n    simpl in Heqsub_fn;\n    fold subtype_func in Heqsub_fn;\n    auto.  \nQed.\n\nLemma subtype_sel_low_sha_top_reduce : \n  forall T1 x1 L1 T1', T1 = (t_sel_low x1 L1 T1') ->\n                  forall T2 x2 L2 ss2, T2 = (t_sha_top x2 L2 ss2) ->\n                                  subtype T1 T2 = false.\nProof.\n  intros.\n\n  remember (subtype T1 T2) as sub_fn; subst T1 T2.\n  \n  unfold subtype, subtype_func in Heqsub_fn;\n    simpl in Heqsub_fn;\n    rewrite fix_sub_eq_ext in Heqsub_fn;\n    simpl in Heqsub_fn;\n    fold subtype_func in Heqsub_fn;\n    auto. \nQed.\n\nLemma subtype_sel_low_sha_sel_reduce : \n  forall T1 x1 L1 T1', T1 = (t_sel_low x1 L1 T1') ->\n                  forall T2 x2 L2 ss2 T', T2 = (t_sha_sel x2 L2 ss2 T') ->\n                                     subtype T1 T2 = false.\nProof.\n  intros.\n\n  remember (subtype T1 T2) as sub_fn; subst T1 T2.\n  \n  unfold subtype, subtype_func in Heqsub_fn;\n    simpl in Heqsub_fn;\n    rewrite fix_sub_eq_ext in Heqsub_fn;\n    simpl in Heqsub_fn;\n    fold subtype_func in Heqsub_fn;\n    auto.  \nQed.\n\nLemma subtype_sel_low_all_reduce : \n  forall T1 x1 L1 T1', T1 = (t_sel_low x1 L1 T1') ->\n                  forall T2 T T', T2 = (t_all T T') ->\n                             subtype T1 T2 = false.\nProof.\n  intros.\n\n  remember (subtype T1 T2) as sub_fn; subst T1 T2.\n  \n  unfold subtype, subtype_func in Heqsub_fn;\n    simpl in Heqsub_fn;\n    rewrite fix_sub_eq_ext in Heqsub_fn;\n    simpl in Heqsub_fn;\n    fold subtype_func in Heqsub_fn;\n    auto.  \nQed.\n\nLemma subtype_sel_low_bot_reduce : \n  forall T1 x1 L1 T1', T1 = (t_sel_low x1 L1 T1') ->\n                  subtype T1 t_bot = false.\nProof.\n  intros.\n\n  remember (subtype T1 t_bot) as sub_fn; subst T1.\n  \n  unfold subtype, subtype_func in Heqsub_fn;\n    simpl in Heqsub_fn;\n    rewrite fix_sub_eq_ext in Heqsub_fn;\n    simpl in Heqsub_fn;\n    fold subtype_func in Heqsub_fn;\n    auto.  \nQed.\n\nLemma subtype_sel_low_nil_reduce :\n  forall T1 x1 L1 T1', T1 = (t_sel_low x1 L1 T1') ->\n                  subtype T1 t_nil = false.\nProof.\n  intros.\n\n  remember (subtype T1 t_bot) as sub_fn; subst T1.\n  \n  unfold subtype, subtype_func in Heqsub_fn;\n    simpl in Heqsub_fn;\n    rewrite fix_sub_eq_ext in Heqsub_fn;\n    simpl in Heqsub_fn;\n    fold subtype_func in Heqsub_fn;\n    auto.  \nQed.\n\nLemma subtype_sel_low_con_reduce :\n  forall T1 x1 L1 T1', T1 = (t_sel_low x1 L1 T1') ->\n                  forall T2 T Ts, T2 = t_con T Ts ->\n                             subtype T1 T2 = false.\nProof.\n  intros; subst.\n  \n  unfold subtype, subtype_func;\n    simpl;\n    rewrite fix_sub_eq_ext;\n    simpl;\n    fold subtype_func;\n    auto.  \nQed.\n\nLemma subtype_sel_low_reduce :\n  forall T1 x1 L1 T1',\n    T1 = (t_sel_low x1 L1 T1') ->\n    forall T2, subtype T1 T2 = match T2 with\n                          | t_top => true\n                          | t_sel_low x2 L2 T2' => orb (andb (eq_var x1 x2) (eq_label L1 L2)) (subtype T1 T2')\n                          | t_sel_equ x2 L2 T2' => orb (andb (eq_var x1 x2) (eq_label L1 L2)) (subtype T1 T2')\n                          | t_sel_upp x2 L2 _ => andb (eq_var x1 x2) (eq_label L1 L2)\n                          | t_sel_nom x2 L2 _ => andb (eq_var x1 x2) (eq_label L1 L2)\n                          | _ => false\n                          end.\nProof.\n  intros.\n\n  destruct T2.\n\n  apply subtype_top;\n    subst;\n    intros;\n    intro Hcontra;\n    inversion Hcontra.\n\n  subst;\n    apply subtype_sel_low_bot_reduce\n      with (x1:=x1)(L1:=L1)(T1':=T1');\n    auto.\n\n  subst;\n    apply subtype_sel_low_sel_upp_reduce\n      with (x1:=x1)(L1:=L1)(T2':=T2)(T1':=T1');\n    auto.\n\n  subst;\n    apply subtype_sel_low_sel_low_reduce\n      with (x1:=x1)(L1:=L1)(T2':=T2)(T1':=T1');\n    auto.\n\n  subst;\n    apply subtype_sel_low_sel_equ_reduce\n      with (x1:=x1)(L1:=L1)(T2':=T2)(T1':=T1');\n    auto.\n\n  subst;\n    apply subtype_sel_low_sel_nom_reduce\n      with (x1:=x1)(L1:=L1)(T2':=T2)(T1':=T1');\n    auto.\n\n  subst;\n    apply subtype_sel_low_rfn_top_reduce\n      with (x1:=x1)(L1:=L1)(Ts:=T2)(T1':=T1');\n    auto.\n\n  subst;\n    apply subtype_sel_low_rfn_sel_reduce\n      with (x1:=x1)(L1:=L1)(x2:=v)(L2:=l)(Ts:=T2_1)(T':=T2_2)(T1':=T1');\n    auto.\n\n  subst;\n    apply subtype_sel_low_sha_top_reduce\n      with (x1:=x1)(L1:=L1)(x2:=v)(L2:=l)(T1':=T1')(ss2:=d);\n    auto.\n\n  subst;\n    apply subtype_sel_low_sha_sel_reduce\n      with (x1:=x1)(L1:=L1)(x2:=v)(L2:=l)(T':=T2)(T1':=T1')(ss2:=d);\n    auto.\n\n  subst;\n    apply subtype_sel_low_all_reduce\n      with (x1:=x1)(L1:=L1)(T:=T2_1)(T':=T2_2)(T1':=T1');\n    auto.\n\n  subst;\n    apply subtype_sel_low_upp_reduce\n      with (x1:=x1)(L1:=L1)(T1':=T1')(L2:=l)(T2':=T2);\n    auto.\n\n  subst;\n    apply subtype_sel_low_low_reduce\n      with (x1:=x1)(L1:=L1)(T1':=T1')(L2:=l)(T2':=T2);\n    auto.\n\n  subst;\n    apply subtype_sel_low_equ_reduce\n      with (x1:=x1)(L1:=L1)(T1':=T1')(L2:=l)(T2':=T2);\n    auto.\n\n  subst;\n    apply subtype_sel_low_nom_reduce\n      with (x1:=x1)(L1:=L1)(T1':=T1')(L2:=l)(T2':=T2);\n    auto.\n\n  subst; eapply subtype_sel_low_nil_reduce; eauto.\n\n  subst; eapply subtype_sel_low_con_reduce; eauto.\nQed.", "meta": {"author": "JulianMackay", "repo": "Wyvern_Formalism", "sha": "7072f2803b500c73c42347544740768e81a8beca", "save_path": "github-repos/coq/JulianMackay-Wyvern_Formalism", "path": "github-repos/coq/JulianMackay-Wyvern_Formalism/Wyvern_Formalism-7072f2803b500c73c42347544740768e81a8beca/wfix/rhs_mat_subtype_lhs_sel_low_reduce.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784220301064, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.29132070898786055}}
{"text": "From Flocq Require Core Binary.\nFrom Coquelicot Require Import Coquelicot.\nRequire Import Reals Gappa.Gappa_library Psatz.\nImport Defs Raux FLT Generic_fmt Gappa_definitions Binary Ulp.\nRequire Import FunInd Recdef.\nRequire Import float_lemmas.\n\nFrom compcert.lib Require Import Floats Integers.\n\nTransparent Float32.div Float32.add Float32.cmp.\n\n(* Correctness of floating-point absolute value.  We don't need this\n   for sqrt, but it's useful elsewhere. *)\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.\nAdmitted.\n\nDefinition sqrt_approx_f (x: float32) : float32 :=\n  Float32.of_bits\n  (Int.add (Int.shru (Float32.to_bits x) (Int.repr 1))\n     (Int.repr 532676608)).\n\nDefinition float32_to_real := Binary.B2R 24 128.\n\n\nLemma bits_of_b32_range:\n  forall x, 0 <= Bits.bits_of_b32 x < 2^32.\nProof.\nintros.\napply (Bits.bits_of_binary_float_range); reflexivity.\nQed.\n\nLemma bits_of_b32_range':\n  forall x, 0 <= Bits.bits_of_b32 x <= Int.max_unsigned.\nProof.\nintros.\npose proof (bits_of_b32_range x).\nchange Int.max_unsigned with (2^32-1).\nlia.\nQed.\n\nLemma add_repr: forall i j, Int.add (Int.repr i) (Int.repr j) = Int.repr (i+j).\nProof. intros.\n  rewrite Int.add_unsigned.\n apply Int.eqm_samerepr.\n unfold Int.eqm.\n apply Int.eqm_add; apply Int.eqm_sym; apply Int.eqm_unsigned_repr.\nQed.\n\nLemma sqrt_approx_eq:\n forall x, sqrt_approx_f x = \n       Bits.b32_of_bits (Bits.bits_of_b32 x / 2 + 532676608).\nProof.\nintros.\nunfold sqrt_approx_f.\nTransparent Float32.of_bits.\nTransparent Float32.to_bits.\nunfold Float32.of_bits, Float32.to_bits.\nOpaque Float32.of_bits.\nOpaque Float32.to_bits.\nunfold Int.shru.\nrewrite Int.unsigned_repr by apply bits_of_b32_range'.\nrewrite Int.unsigned_repr by (compute; split; congruence).\nrewrite add_repr.\nrewrite <- Z.div2_spec, Z.div2_div.\nassert  (0 <= Bits.bits_of_b32 x / 2 < 2 ^ 31)%Z.\n apply Coqlib.Zdiv_interval_1.\n compute; congruence. reflexivity. reflexivity.\n apply bits_of_b32_range.\nrewrite Int.unsigned_repr\n  by (change Int.max_unsigned with (2^31 + 2^31 -1)%Z; lia).\nauto.\nQed.\n\nLemma bound_mantissa_Z : \n  forall (m: positive) (e: Z), bounded ms es m e = true ->\n     (Z.pos m < 2 ^ ms)%Z.\nProof.\nintros.\napply bound_mantissa_nat in H.\napply inj_lt in H.\nrewrite positive_nat_Z in H.\nchange 2%nat with (Z.to_nat 2) in H.\nrewrite <- Zto_nat_pow in H by (compute; congruence).\nrewrite Z2Nat.id in H; auto.\napply Z.pow_nonneg.\ncompute; congruence.\nQed.\n\nLemma sqrt_approx_correct:\n forall x, \n  is_finite_strict ms es x = true ->\n  Bsign ms es x = false ->\n  (Rbasic_fun.Rabs (float32_to_real (sqrt_approx_f x) - R_sqrt.sqrt (float32_to_real x)) <=\n       (1 + 1/16) * R_sqrt.sqrt (float32_to_real x))%R.\nProof.\nintros.\nrewrite sqrt_approx_eq.\nunfold float32_to_real.\nfold ms. fold es.\nmatch goal with |- context [_ / 2 + ?zz] => \n     change zz with (2^(ms'-1) * (es-1))\nend.\nunfold Bits.b32_of_bits, Bits.bits_of_b32.\nunfold Bits.binary_float_of_bits.\nchange 23 with ms'.\nmatch goal with |- context [Bits.bits_of_binary_float _ ?y] =>\n  change y with (Z.log2 es + 1)\nend.\nrewrite B2R_FF2B.\nunfold Bits.bits_of_binary_float.\nset (ebits := Z.log2 es).\ndestruct x; inversion H; clear H.\nrename e0 into H1.\ndestruct s; inversion H0; clear H0.\nset (x := (B754_finite _ _ _ _ _ _)).\ndestruct (Z.leb_spec 0 (Z.pos m - 2 ^ ms')).\n{\nset (e' := (e - (3 - 2 ^ (ebits + 1 - 1) - (ms' + 1)) + 1)).\nunfold Bits.join_bits.\nrewrite Z.shiftl_mul_pow2 by (compute; congruence).\nchange (2^ms') with (2^(ms'-1)*2) at 1.\nrewrite Z.mul_assoc.\nrewrite Z.div_add_l by lia.\nrewrite (Z.add_comm (_ * _ ^ _)).\nrewrite <- Z.add_assoc.\nrewrite (Z.mul_comm (_ ^ _)).\nrewrite <- Z.mul_add_distr_r.\nrewrite Z.add_0_l.\nsubst e'.\nrewrite <- Z.sub_sub_distr.\nrewrite <- Z.sub_sub_distr.\nrewrite <- (Z.add_opp_r e).\nrewrite (Z.add_simpl_r ebits 1).\nreplace (- (3 - 2 ^ ebits - (ms' + 1) - 1 - (es - 1)))\n  with ( 2 ^ ebits + ms' + (es - 2))\n  by lia.\nrewrite <- Z.div_add by lia.\nrewrite <- Z.mul_assoc.\nrewrite <- Z.sub_sub_distr.\nrewrite <- (Z.mul_1_l (_ ^ _)) at 1.\nrewrite <- Z.mul_sub_distr_r.\nreplace (1 - (e + (2 ^ ebits + ms' + (es - 2))))\n     with (-(e+(2^ebits + ms' + es - 3))) by lia.\nrewrite Z.mul_opp_l, Z.sub_opp_r.\nrewrite Z.mul_assoc.\nrewrite Z.div_add by lia.\nadmit.\n}\n{\nadmit.\n}\nAdmitted.\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/sqrt/sqrt3_f_correct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.29132070158518397}}
{"text": "Require Import Pip_state Lib.\n\nRequire Import ProofIrrelevance  Coq.Program.Equality Arith List Omega.\nImport List.ListNotations.\n\n(** Internals *)\n\nDefinition readPhysicalInternal p i memory :option page := \nmatch (lookup p i memory beqPage beqIndex) with\n                            | Some (PP a) => Some a\n                            | _ => None\n                       end.\n\nDefinition readVirtualInternal p i memory : option vaddr:=\n  match (lookup p i memory beqPage beqIndex) with\n  | Some (VA a) => Some a\n  | _ => None\n  end.\n\nDefinition succIndexInternal (idx:index) : option index :=\nlet (i,_):=idx in \n  if lt_dec i tableSize \n  then Some (CIndex (i+1)) \n  else None.\n\nDefinition writeVirtualInternal (p:page) (i:index) (v:vaddr) :=\nfun s => {| currentPartition := s.(currentPartition);\n  memory :=   add p i (VA v)  s.(memory) beqPage beqIndex|}.\n\nModule Index.\nDefinition geb (a b : index) : bool := b <=? a.\nDefinition leb (a b : index) : bool := a <=? b.\nDefinition ltb (a b : index) : bool := a <? b.\nDefinition gtb (a b : index) : bool := b <? a.\nDefinition eqb (a b : index) : bool := a =? b.\nEnd Index. \n\nModule Page. \nDefinition eqb (p1 : page)  (p2 : page) : bool := (p1 =? p2).\nEnd Page.\n\nModule Level. \nDefinition gtb (a b : level) : bool := b <? a .\nDefinition eqb (a b : level) : bool:= a =? b.\nProgram Definition pred (n : level) : option level := \nif gt_dec n 0 then\nlet ipred := n-1 in \nSome (Build_level ipred _ )\nelse  None.\nNext Obligation.\ndestruct n.\nsimpl.\nomega.\nQed.\nEnd Level. \n\nModule VAddr.\nDefinition eqbList(vaddr1 : vaddr) (vaddr2 : vaddr) : bool :=\n beqVAddr vaddr1 vaddr2.\nEnd VAddr.\n\n(** For conditions *)\n\n\n(** The [getCurPartition] function returns the current partition descriptor of a given state *)\nDefinition getCurPartition s :page:=\ncurrentPartition s. \n\n(** The [getMaxIndex] function returns the last position into a page table *) \nDefinition getMaxIndex : option index:=\nmatch gt_dec tableSize 0 with\n| left x =>\n    Some (CIndex (tableSize-1))\n| right _ => None \nend. \n\n(** The [readPhysical] function returns the physical page stored into a given \n    page at a given position in physical memory. The table should contain only Physical pages \n    (The type [PP] is already defined into [Model.ADT]) *)\nDefinition readPhysical (paddr : page) (idx : index) memory: option page :=\nlet entry :=  lookup paddr idx memory beqPage beqIndex  in \n  match entry with\n  | Some (PP a) => Some a\n  | _ => None\n end.\n\n(**  The [getPd] function returns the physical page of the page directory of\n     a given partition  *)\nDefinition getPd partition memory: option page:= \nmatch succIndexInternal PDidx with \n|None => None\n|Some idx => readPhysical partition idx memory\nend. \n\n(**  The [getFstShadow] returns the physical page of the first shadow page of\n     a given partition  *)\nDefinition getFstShadow partition memory: option page:= \nmatch succIndexInternal sh1idx with \n|None => None\n|Some idx => readPhysical partition idx memory\nend. \n\n(**  The [getSndShadow] returns the physical page of the second shadow page  of\n     a given partition *)\nDefinition getSndShadow partition memory: option page:= \nmatch succIndexInternal sh2idx with \n|None => None\n|Some idx => readPhysical partition idx memory\nend. \n\n(**  The [getConfigTablesLinkedList] returns the physical address of the indirection tables\n reverse translation of a given partition  *)\nDefinition getConfigTablesLinkedList partition memory: option page:= \nmatch succIndexInternal sh3idx with \n|None => None\n|Some idx => readPhysical partition idx memory\nend. \n\n(** The [readPDflag] function returns the flag value stored into a given table \n    at a given position in memory. The table should contain only virtual entries \n    (The type [VE] is already defined in [Model.ADT])  *)\nDefinition readPDflag  (paddr : page) (idx : index) memory : option bool:=\nlet entry :=  lookup paddr idx memory beqPage beqIndex  in \n  match entry with\n  | Some (VE a) => Some a.(pd)\n  | Some _ => None\n  | None => None\n end.\n\n(** The [getNbLevel] function returns the number of translation levels of the MMU *) \nDefinition getNbLevel : option level:=\nif gt_dec nbLevel 0\nthen Some (CLevel (nbLevel-1))\nelse None.\n\n(** The [readPresent] function returns the flag value stored into a given table \n    at a given position in memory. The table should contain only Physical entries *)\nDefinition readPresent  (paddr : page) (idx : index) memory : option bool:=\nlet entry :=  lookup paddr idx memory beqPage beqIndex  in \n  match entry with\n  | Some (PE a) => Some a.(present)\n  | Some _ => None\n  | None => None\n end. \n\n(** The [readAccessible] function returns the flag value stored into a given table \n    at a given position in memory. The table should contain only Physical entries  *)\nDefinition readAccessible  (paddr : page) (idx : index) memory : option bool:=\nlet entry :=  lookup paddr idx memory beqPage beqIndex  in \n  match entry with\n  | Some (PE a) => Some a.(user)\n  | Some _ => None\n  | None => None\n end. \n\nDefinition getIndexOfAddr (va : vaddr) (l : level) : index:=\nnth ((length va) - (l + 2))  va defaultIndex .\n\n(** The [checkVAddrsEqualityWOOffset] function compares two given virtual addresses \n    without taking into account the last index *)\nFixpoint checkVAddrsEqualityWOOffset (timeout : nat) (va1 va2 : vaddr) (l : level) := \nmatch timeout with \n|0 => true\n|S timeout1 =>  \nlet idx1 := getIndexOfAddr va1 l in\n let idx2 := getIndexOfAddr va2 l in\nif Level.eqb l fstLevel \nthen\n      (idx1 =? idx2) \n    else \n      match Level.pred l with \n      | Some levelpred =>  if idx1 =? idx2 \n                              then checkVAddrsEqualityWOOffset timeout1 va1 va2 levelpred\n                              else false\n      | _ => true\n      end\nend. \n\n(** The [readPhyEntry] function returns the physical page stored into a given table \n    at a given position in memory. The table should contain only Physical entries *)\nDefinition readPhyEntry(paddr : page) (idx : index) memory: option page :=\nlet entry :=  lookup paddr idx memory beqPage beqIndex  in \n  match entry with\n  | Some (PE a) => Some a.(pa)\n  | Some _ => None\n  | None => None\n end. \n\n(** The [readIndex] function returns the index stored into a given table \n    at a given position in memory. The table should contain only indices  *)\nDefinition readIndex  (paddr : page) (idx : index) memory : option index :=\nlet entry :=  lookup paddr idx memory beqPage beqIndex  in \n  match entry with\n  | Some (I indexValue) => Some indexValue\n  | Some _ => None\n  | None => None\n end. \n \n (** The [readVirtual] function returns the virtual address strored into a given table \n    at a given position in memory. The table should contain a virtual address at this position *)\nDefinition readVirtual (paddr : page) (idx : index) memory : option vaddr :=\nlet entry :=  lookup paddr idx memory beqPage beqIndex  in \n  match entry with\n  | Some (VA addr) => Some addr\n  | Some _ => None\n  | None => None\n end. \n\n(** The [readVirEntry] function returns the virtual address strored into a given table \n    at a given position in memory. The table should contain a VEntry at this position *)\nDefinition readVirEntry (paddr : page) (idx : index) memory : option vaddr :=\nlet entry :=  lookup paddr idx memory beqPage beqIndex  in \n  match entry with\n  | Some (VE addr) => Some (vad addr)\n  | Some _ => None\n  | None => None\n end. \n \n(** The [getDefaultPage] function returns the value of the default page *)\nDefinition getDefaultPage := defaultPage.\n\n(** The [getIndirection] function returns the configuration table entry that corresponds \n    to the given level and virtual address *)\nFixpoint  getIndirection (pd : page) (va : vaddr) (currentlevel : level) (stop : nat) s :=\nmatch stop with \n|0 => Some pd \n|S stop1 => \nif (Level.eqb currentlevel fstLevel)  \nthen Some pd \n  else  \n    let idx :=  getIndexOfAddr va currentlevel in \n       match readPhyEntry pd idx s.(memory) with \n       | Some addr =>  if  defaultPage =? addr \n                          then Some defaultPage \n                          else \n                            match Level.pred currentlevel with\n                            |Some p =>  getIndirection addr va p stop1 s\n                            |None => None\n                            end\n      |None => None\n    end\n   end. \n\n(** The [getMappedPage] function returns the physical page stored into a leaf node, \n   which corresponds to a given virtual address, if the present flag is equal to true **)\nDefinition getMappedPage pd s va: option page :=\nmatch getNbLevel  with \n |None => None\n |Some level => let idxVA := getIndexOfAddr va fstLevel  in \n               match getIndirection pd va level (nbLevel - 1) s with \n                | Some tbl =>  if defaultPage =? tbl\n                                   then None \n                                   else match (readPresent tbl idxVA s.(memory)) with \n                                         |Some true => readPhyEntry tbl idxVA s.(memory) \n                                         | _ =>  None \n                                        end\n                | _ => None\n               end\nend.\n\n(** The [getVirtualAddressSh2] function returns the virtual address stored into the \n    second shadow structure which corresponds to a given virtual address **)\nDefinition getVirtualAddressSh2 sh2 s va: option vaddr :=\nmatch getNbLevel  with \n |None => None\n |Some level => let idxVA := getIndexOfAddr va fstLevel  in \n               match getIndirection sh2 va level (nbLevel - 1) s with \n                | Some tbl =>  if defaultPage =? tbl\n                                   then None \n                                   else readVirtual tbl idxVA s.(memory) \n                | _ => None\n               end\nend.\n\n(** The [getVirtualAddressSh2] function returns the virtual address stored into the \n    parent **)\nDefinition getVAInParent partition s va: option vaddr :=\nmatch getSndShadow partition (memory s) with \n|Some sh2 => match getVirtualAddressSh2 sh2 s va with \n             | Some vainparent =>  if (VAddr.eqbList defaultVAddr vainparent) \n                                     then None \n                                     else Some vainparent\n             | _ => None\n             end\n| _ => None\nend. \n\n(** The [getVirtualAddressSh1] function returns the virtual address stored into the first\n   shadow structure which corresponds to a given virtual address **)\nDefinition getVirtualAddressSh1 sh1 s va: option vaddr :=\nmatch getNbLevel  with \n |None => None\n |Some level => let idxVA := getIndexOfAddr va fstLevel  in \n               match getIndirection sh1 va level (nbLevel - 1) s with \n                | Some tbl =>  if defaultPage =? tbl\n                                   then None \n                                   else readVirEntry tbl idxVA s.(memory) \n                | _ => None\n               end\nend.\n\n(** The [getAccessibleMappedPage] function returns the physical page stored into a leaf node, \n   which corresponds to a given virtual address, if the present and user flags are equal to true **)\nDefinition getAccessibleMappedPage pd s va: option page :=\nmatch getNbLevel  with \n |None => None\n |Some level =>let idxVA := getIndexOfAddr va fstLevel  in \n               match getIndirection pd va level (nbLevel - 1) s with \n                | Some tbl => if defaultPage =? tbl\n                                   then None \n                                   else  match (readPresent tbl idxVA s.(memory)),\n                                                   (readAccessible tbl idxVA s.(memory)) with \n                                           |Some true, Some true => readPhyEntry tbl idxVA s.(memory) \n                                           | _, _ =>  None \n                                          end\n                | _ => None\n               end\nend.\n\n(** The [geTrdShadows] returns physical pages used to keep informations about \n    configuration pages \n*)\nFixpoint getTrdShadows (sh3 : page) s bound :=\nmatch bound with \n|0 => []\n|S bound1 => match getMaxIndex with \n            |None => []\n            |Some maxindex =>  match readPhysical sh3 maxindex s.(memory) with \n                                |None => [sh3]\n                                |Some addr => if addr =? defaultPage then [sh3] else sh3 :: getTrdShadows addr s bound1\n                               end\n           end\nend.\n\n(** The [checkChild] function returns true if the given virtual address corresponds \n    to a child of the given partition \n    *)\nDefinition checkChild partition level (s:state) va : bool :=\nlet idxVA :=  getIndexOfAddr va fstLevel in \nmatch getFstShadow partition s.(memory)  with \n| Some sh1  => \n   match getIndirection sh1 va level (nbLevel -1) s with \n    |Some tbl => if tbl =? defaultPage \n                    then false \n                    else match readPDflag tbl idxVA s.(memory) with \n                          |Some true => true\n                          |_ => false\n                          end\n    |None => false \n    end\n| _ => false\nend.\n\n(** The [getTablePages] function returns the list of physical pages stored into \n    a given configuration table from a given index *)\nFixpoint getTablePages (table : page ) (idx : nat) s : list page := \nmatch idx with \n| 0 => []\n|S idx1 => match  lookup table (CIndex idx1) s.(memory) beqPage beqIndex  with \n              | Some (PE entry) => if (pa entry =? defaultPage ) then getTablePages table idx1 s\n                                      else getTablePages table idx1 s ++ [pa entry] \n              | _ => getTablePages table idx1 s\n            end\nend.\n\nFixpoint getIndirectionsAux (pa : page) (s : state) level {struct level} : list page :=\n  match level with\n    | O => []\n    | S level1 => pa :: flat_map (fun p => getIndirectionsAux p s level1) \n                                    (getTablePages pa tableSize s)\n  end.\n\n(** The [getIndirectionsAux] function returns the list of physical pages \n    used into a configuration tables tree *)\nDefinition getIndirections pd s : list page :=\n  getIndirectionsAux pd s nbLevel.\n\nFixpoint getAllIndicesAux (pos count: nat) : list index :=\n  match count with\n    | 0        => []\n    | S count1 => match lt_dec pos tableSize with\n                   | left pf => Build_index pos pf :: getAllIndicesAux (S pos) count1\n                   | _       => []\n                 end\n  end.\n\n(** The [getAllIndicesAux] function returns the list of all indices  *)\nDefinition getAllIndices := getAllIndicesAux 0 tableSize.\n\nFixpoint getAllVAddrAux (levels: nat) : list (list index) :=\n  match levels with\n    | 0         => [[]]\n    | S levels1 => let alls := getAllVAddrAux levels1 in\n                  flat_map (fun (idx : index) => map (cons idx) alls) getAllIndices\n  end.\n\n(** The [getAllVAddr] function returns the list of all virtual addresses *)\nDefinition getAllVAddr := map CVaddr (getAllVAddrAux (S nbLevel)).\n  \n(** The [getPdsVAddr] function returns the list of virtual addresses used as \n    partition descriptor into a given partition *)\nDefinition getPdsVAddr partition l1 (vaList : list vaddr) s :=\nfilter (checkChild partition l1 s) vaList.\n\n(** The [getMappedPagesOption] function Return all physical pages marked as \n    present into a partition *)\nDefinition getMappedPagesOption (pd : page) (vaList : list vaddr) s : list (option page) :=\nmap (getMappedPage pd s) vaList.\n\n(** The [getAccessibleMappedPagesOption] function Return all physical pages \n    marked as present and accessible into a partition *)\nDefinition getAccessibleMappedPagesOption (pd : page) (vaList : list vaddr) s : list (option page) :=\nmap (getAccessibleMappedPage pd s) vaList.\n\n(** The [filterOption] function Remove option type from list *)\nFixpoint filterOption (l : list (option page)) := \nmatch l with \n| [] => []\n| Some a :: l1 => a:: filterOption l1\n|None :: l1 => filterOption l1\nend.\n\n(** The [getMappedPagesAux] function removes option type from mapped pages list *)\nDefinition getMappedPagesAux (pd :page)  (vaList : list vaddr) s : list page := \nfilterOption (getMappedPagesOption pd vaList s).\n\n(** The [getAccessibleMappedPagesAux] function removes option type from \n    accessible mapped pages list *)\nDefinition getAccessibleMappedPagesAux (pd :page)  (vaList : list vaddr) s : list page := \nfilterOption (getAccessibleMappedPagesOption pd vaList s).\n\n(** The [getConfigPagesAux] function returns all configuration pages of a \n    given partition *)\nDefinition getConfigPagesAux (partition : page) (s : state) : list page := \nlet vaList := getAllVAddr in \nmatch getPd partition s.(memory), \n      getFstShadow partition s.(memory), \n      getSndShadow partition s.(memory), \n      getConfigTablesLinkedList partition s.(memory)  with \n| Some pd , Some sh1, Some sh2 , Some sh3  => (getIndirections pd s)++\n                         (getIndirections sh1 s)++\n                         (getIndirections sh2 s )++\n                         (getTrdShadows sh3 s (nbPage+1))\n|_,_,_,_ => []\nend.\n\nDefinition getConfigPages (partition : page) (s : state) :=\npartition :: (getConfigPagesAux partition s). \n\n(** The [getMappedPages] function Returns all present pages of a given partition *)\nDefinition getMappedPages (partition : page) s : list page :=\n  match getPd partition s.(memory) with\n    |None => []\n    |Some pd => let vaList := getAllVAddr in getMappedPagesAux pd vaList s\n  end.\n\n(** The [getAccessibleMappedPages] function Returns all present and \n    accessible pages of a given partition *)\nDefinition getAccessibleMappedPages (partition : page) s : list page :=\n  match getPd partition s.(memory) with\n    |None => []\n    |Some pd => let vaList := getAllVAddr in getAccessibleMappedPagesAux pd vaList s\n  end.\n  \n(** The [getUsedPages] function Returns all used pages (present and config pages)\n    of a given partition including the partition descriptor itself *)\nDefinition getUsedPages (partition: page) s : list page :=\n  getConfigPages partition s ++ getMappedPages partition s.\n\nLemma  eqPageDec : forall n m : page, {n = m} + {n <> m}.\nProof.\nintros.\ndestruct n. destruct m.\nassert ({p = p0} + {p <> p0}).\napply eq_nat_dec.\ndestruct H.\nleft.\nsubst.\nassert(Hp = Hp0) by apply proof_irrelevance.\nsubst.\ntrivial.\nright.\nunfold not in *.\nintros. apply n.\nclear n.\ninversion H. trivial.\nQed.\n\n(** The [getChildren] function Returns all children of a given partition *)\nDefinition getChildren (partition : page) s := \nlet vaList := getAllVAddr in \nmatch getNbLevel, getPd partition s.(memory) with \n|Some l1,Some pd => getMappedPagesAux pd (getPdsVAddr partition l1 vaList s) s\n|_, _ => []\nend.\n\n\n(** The [getPartitionsAux] function returns all pages marked as descriptor partition *)\nFixpoint getPartitionAux (partitionRoot : page) (s : state) bound {struct bound} : list page :=\n  match bound with\n    | O => []\n    | S bound1 => partitionRoot :: flat_map (fun p => getPartitionAux p s bound1) \n                                    (getChildren partitionRoot s )\n  end.\n\n(** The [getPartitions] function fixes the sufficient timeout value to retrieve all partitions *)\nDefinition getPartitions (root : page) s : list page  :=\n(getPartitionAux root s (nbPage+1)). \n\n(** The [getParent] function returns the parent partition descriptor of a given partition *)\nDefinition getParent partition memory :=\nmatch succIndexInternal PPRidx with \n| Some idx =>  readPhysical partition idx memory\n| _ => None \nend.\n\n(** The [getAncestorsAux] function returns the ancestors list of a given partition *)\nFixpoint getAncestorsAux (partition : page) memory depth : list page := \nmatch depth with \n|0 => [] \n| S depth1 => match getParent partition memory with \n               | Some parent => parent :: getAncestorsAux parent memory depth1\n               | _ => []\n              end\nend.\n\n(** The [getAncestors] function fixes the sufficient timeout value to retrieve all ancestors *)\nDefinition getAncestors (partition : page) s := \ngetAncestorsAux partition s.(memory) (nbPage+1). \n\n(** Propositions *)\n(** The [isPE] proposition reutrns True if the entry at position [idx]\n    into the given page [table] is type of [PE] *)\nDefinition isPE table idx s: Prop := \nmatch lookup table idx s.(memory) beqPage beqIndex with \n             |Some (PE _) => True\n             |_ => False\nend. \n\n(** The [isVE] proposition reutrns True if the entry at position [idx]\n    into the given page [table] is type of [VE] *)\nDefinition isVE table idx s: Prop := \n match lookup table idx s.(memory) beqPage beqIndex with \n             |Some (VE _) => True\n             |_ => False\nend.\n\n(** The [isVA] proposition reutrns True if the entry at position [idx]\n    into the given page [table] is type of [VA] *)\nDefinition isVA table idx s: Prop := \n match lookup table idx s.(memory) beqPage beqIndex with \n             |Some (VA _) => True\n             |_ => False\nend.\n\n(** The [isPP] proposition reutrns True if the entry at position [idx]\n    into the given page [table] is type of [PE] *)\nDefinition isPP table idx s: Prop := \n match lookup table idx s.(memory) beqPage beqIndex with \n             |Some (PP _) => True\n             |_ => False\nend.\n\n(** The [isPP'] proposition reutrns True if the entry at position [idx]\n    into the given page [table] is type of [PP] and physical page stored into this entry \n    is equal to a given physical page [pg]*)\nDefinition isPP' table idx pg s: Prop := \n match lookup table idx s.(memory) beqPage beqIndex with \n             |Some (PP p) => p = pg\n             |_ => False\nend.\n\n(** The [nextEntryIsPP] proposition reutrns True if the entry at position [idx+1]\n    into the given physical page [table] is type of [PP] and physical page stored into \n    this entry is equal to a given physical page [pg] *)\nDefinition nextEntryIsPP table idxroot tableroot s : Prop:= \nmatch succIndexInternal idxroot with \n| Some idxsucc => match lookup table idxsucc (memory s) beqPage beqIndex with \n                  | Some (PP table) => tableroot = table\n                  |_ => False \n                  end\n| _ => False \nend.\n\n(** The [entryPresentFlag] proposition reutrns True if the entry at position [idx]\n    into the given physical page [table] is type of [PP] and the present flag stored into \n    this entry is equal to a given flag [flag] *)\nDefinition entryPresentFlag table idx flag s:= \nmatch lookup table idx s.(memory) beqPage beqIndex with \n| Some (PE entry) => flag =  entry.(present)\n| _ => False\nend. \n\n(** The [entryPDFlag]  proposition reutrns True if the entry at position [idx]\n    into the given physical page [table] is type of [VE] and the pd flag stored into \n    this entry is equal to a given flag [flag] *)\nDefinition entryPDFlag table idx flag s:= \nmatch lookup table idx s.(memory) beqPage beqIndex with \n| Some (VE entry) => flag =  entry.(pd)\n| _ => False\nend. \n\n(** The [entryUserFlag] proposition reutrns True if the entry at position [idx]\n    into the given physical page [table] is type of [VE] and the user flag stored into \n    this entry is equal to a given flag [flag] *)\nDefinition entryUserFlag table idx flag s:= \nmatch lookup table idx s.(memory) beqPage beqIndex with \n| Some (PE entry) => flag =  entry.(user)\n| _ => False\nend. \n\n(** The [VEDerivation] proposition reutrns True if the entry at position [idx]\n    into the given physical page [table] is type of [VE] and the given boolean value \n    [res] specifies if the virtual address stored into  \n    this entry is equal or not to the default virtual address *)\nDefinition VEDerivation table idx (res : bool) s:= \nmatch lookup table idx s.(memory) beqPage beqIndex with \n| Some (VE entry) => ~ (beqVAddr entry.(vad) defaultVAddr) = res\n| _ => False\nend. \n\n(** The [isEntryVA] proposition reutrns True if the entry at position [idx]\n    into the given physical page [table] is type of [VE] and the virtual address\n    stored into this entry is equal to a given virtual address [v1] *)\nDefinition isEntryVA table idx v1 s:=\n match lookup table idx (memory s) beqPage beqIndex with \n | Some (VE entry)  => entry.(vad) = v1\n | _ => False\n end.\n\n(** The [isVA'] proposition reutrns True if the entry at position [idx]\n    into the given physical page [table] is type of [VA] and the virtual address\n    stored into this entry is equal to a given virtual address [v1] *)\nDefinition isVA' table idx v1 s:=\n match lookup table idx (memory s) beqPage beqIndex with \n | Some (VA entry)  => entry = v1\n | _ => False\n end.\n\n(** The [isEntryPage] proposition reutrns True if the entry at position [idx]\n    into the given page [table] is type of [PE] and physical page stored into this entry \n    is equal to a given physical page [page1]*)\nDefinition isEntryPage table idx page1 s:=\n match lookup table idx (memory s) beqPage beqIndex with \n | Some (PE entry)  => entry.(pa) = page1\n | _ => False\n end.\n \n(** The [getTableAddrRoot'] proposition returns True if the given physical page [table]\nis a configuration table into different structures (pd, shadow1 or shadow2). This table should be associated to the \ngiven virtual address [va]  *)\nDefinition getTableAddrRoot' (table : page) (idxroot : index) \n(currentPart : page) (va : vaddr) (s : state) : Prop :=\n(idxroot = PDidx \\/ idxroot = sh1idx \\/ idxroot = sh2idx) /\\\n(forall tableroot : page,\n nextEntryIsPP currentPart idxroot tableroot s ->\n exists nbL : level,\n   Some nbL = getNbLevel /\\\n   (exists stop : nat, stop > 0 /\\ stop <= nbL /\\ getIndirection tableroot va nbL stop s = Some table)).\n\n(** The [getTableAddrRoot] proposition returns True if the given physical page [table]\nis the last page table into a structure (pd, shadow1 or shadow2) that corresponds to a given virtual address [va] *)\nDefinition getTableAddrRoot table idxroot currentPart va s : Prop :=\n(idxroot = PDidx \\/ idxroot = sh1idx \\/ idxroot = sh2idx)/\\\n   forall (tableroot : page), nextEntryIsPP  currentPart idxroot tableroot s ->  \n   exists nbL, Some nbL = getNbLevel  /\\ exists (stop :nat) , stop = nbL+1  /\\ \n    getIndirection tableroot va nbL stop s = Some table . \n\n(** The [getAllPages] returns the list of all physical pages *)\nDefinition getAllPages: list page:= \nmap CPage (seq 0 nbPage ).\n\n(** The [getPDFlag] checks if the given virtual address corresponds to a partition\n    descriptor **)\nDefinition getPDFlag sh1 va s :=\nlet idxVA := getIndexOfAddr va fstLevel in\nmatch getNbLevel with\n|Some nbL =>  match getIndirection sh1 va nbL (nbLevel - 1) s with\n  | Some tbl =>\n      if tbl =? defaultPage\n      then false\n      else\n       match readPDflag tbl idxVA (memory s) with\n       | Some true => true\n       | Some false => false\n       | None => false\n       end\n  | None => false\n  end\n| None => false\nend.\n\n(** The [isAccessibleMappedPageInParent] function returns true if the given physical\n    page is accessible in the parent of the given partition **)\nDefinition isAccessibleMappedPageInParent partition va accessiblePage s  :=\nmatch getSndShadow partition (memory s) with \n| Some sh2 => \n  match  getVirtualAddressSh2 sh2 s va  with \n   | Some vaInParent => \n     match getParent partition (memory s) with \n      | Some parent => \n        match getPd parent (memory s) with \n         | Some pdParent => \n           match getAccessibleMappedPage pdParent s vaInParent with \n            | Some sameAccessiblePage => accessiblePage =? sameAccessiblePage\n            | None => false\n           end\n         | None => false\n        end\n    | None => false\n           end\n| None => false\n           end\n| None => false\nend.\n\n(** The [isPartitionFalse] returns true if the partition descriptor flag of a given\n     entry is equal to false or there is no data stored into this entry **)  \nDefinition isPartitionFalse ptPDChildSh1 idxPDChild s :=\nreadPDflag ptPDChildSh1 idxPDChild (memory s) = Some false \\/\nreadPDflag ptPDChildSh1 idxPDChild (memory s) = None.\n\n(** The [isAncestor] funtion returns true if the given partitions are equal \n    or the descParent partition is an ancestor of currentPart **)\nDefinition isAncestor  currentPart descParent s :=\n( currentPart = descParent \\/ In descParent (getAncestors currentPart s)).\n\nDefinition isWellFormedFstShadow nbL table  s:= \n(nbL <> fstLevel /\\ \n(forall idx, readPhyEntry table  idx s.(memory) = Some defaultPage /\\ \nreadPresent table idx (memory s) = Some false )) \\/ \n(nbL = fstLevel /\\ \n( forall idx : index, \n(readVirEntry table idx (memory s) = Some defaultVAddr) /\\ \nreadPDflag table idx (memory s) = Some false) ).\n\nDefinition isWellFormedSndShadow nbL table  s:= \n(nbL <> fstLevel /\\ (\nforall idx, readPhyEntry table  idx s.(memory) = Some defaultPage /\\ \nreadPresent table idx (memory s) = Some false )) \\/ \n(nbL = fstLevel /\\ ( forall idx : index, \n(readVirtual table idx (memory s) = Some defaultVAddr) ) ).\n\n(** The [isDerived] funtion returns true if a physical page is derived \n    into the given partition , this physical page is associated to the given \n    virtual address [va] **)\nDefinition isDerived partition va  s  :=\nmatch getFstShadow partition (memory s) with \n| Some sh1 => \n  match  getVirtualAddressSh1 sh1 s va  with \n   | Some va0 => beqVAddr defaultVAddr va0 = false\n   | _ => False\n  end\n| None => False\nend.\n\nLemma  pageDec :\nforall x y : page, {x = y} + {x <> y}.\nProof.\nintros.\ndestruct x; destruct y.\nassert({p = p0} + {p <> p0}).\napply Nat.eq_dec.\ndestruct H.\nleft.\nsubst.\nf_equal.\napply proof_irrelevance.\nright.\ncontradict n.\ninversion n.\nsubst;trivial.\nQed.\n\nFixpoint closestAncestorAux part1 part2 s bound : option page :=\nmatch bound  with\n| 0 => None\n| S bound1 => match getParent part1 (memory s) with\n              | Some parent => match in_dec pageDec part2 \n                                    (getPartitionAux parent s (nbPage+1)) with \n                               | left _  => Some parent\n                               | _ =>  closestAncestorAux parent part2 s bound1\n                               end \n              | None =>  Some multiplexer \n              end \nend.\n\nDefinition closestAncestor part1 part2 s := \nclosestAncestorAux part1 part2 s (nbPage+1).\n\n\nLtac symmetrynot :=\nmatch goal with\n| [ |- ?x <> ?y ] => unfold not ; let Hk := fresh in intro Hk ; symmetry in Hk ;contradict Hk\nend.\n\n\n\n\n\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/Pip_stateLib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.291234812501976}}
{"text": "(* * Primitive Two-tape machines *)\n\nFrom Undecidability.TM Require Import Util.TM_facts.\n\nSet Default Proof Using \"Type\".\n(* ** Read two symbols *)\n\n\nSection CaseChar2.\n  Variable sig : finType.\n  Variable (F : finType) (f : option sig -> option sig -> F).\n\n  Definition CaseChar2_TM : TM sig 2 :=\n    {|\n      trans := fun '(_, sym) => (Some (f sym[@Fin0] sym[@Fin1]), [| (None, Nmove); (None, Nmove) |]);\n      start := None;\n      halt := fun s => match s with\n                    | None => false\n                    | Some _ => true\n                    end;\n    |}.\n\n  Definition CaseChar2 : pTM sig F 2 := (CaseChar2_TM; fun s => match s with None => f None None (* not terminated yet *) | Some y => y end).\n\n  Definition CaseChar2_Rel : pRel sig F 2 :=\n    fun t '(y, t') =>\n      y = f (current t[@Fin0]) (current t[@Fin1]) /\\\n      t' = t.\n\n  Definition CaseChar2_Sem : CaseChar2 ⊨c(1) CaseChar2_Rel.\n  Proof.\n    intros t. destruct_tapes. cbn. unfold initc; cbn. cbv [step]; cbn. unfold current_chars; cbn.\n    eexists (mk_mconfig _ _); cbv [step]; cbn. split. eauto. cbn. auto.\n  Qed.\n\nEnd CaseChar2.\n\nArguments CaseChar2 : simpl never.\nArguments CaseChar2 {sig F} f.\nArguments CaseChar2_Rel sig F f x y /.\n\n\nSection ReadChar2.\n\n  Variable sig : finType.\n\n  Definition ReadChar2 : pTM sig (option sig * option sig) 2 := CaseChar2 pair.\n\n  Definition ReadChar2_Rel : pRel sig (option sig * option sig) 2 :=\n    fun t '(y, t') =>\n      y = (current t[@Fin0], current t[@Fin1]) /\\\n      t' = t.\n\n  Lemma ReadChar2_Sem : ReadChar2 ⊨c(1) ReadChar2_Rel.\n  Proof.\n    eapply RealiseIn_monotone.\n    - apply CaseChar2_Sem.\n    - reflexivity.\n    - intros tin (yout, tout) (->&->). hnf. split; auto.\n  Qed.\n\nEnd ReadChar2.\n\nArguments ReadChar2 : simpl never.\nArguments ReadChar2 {sig}.\nArguments ReadChar2_Rel sig x y /.\n\n\n(* ** Tactic Support *)\n\nLtac smpl_TM_Duo :=\n  once lazymatch goal with\n  | [ |- CaseChar2 _ ⊨ _] => eapply RealiseIn_Realise; eapply CaseChar2_Sem\n  | [ |- CaseChar2 _ ⊨c(_) _] => eapply CaseChar2_Sem\n  | [ |- projT1 (CaseChar2 _) ↓ _] => eapply RealiseIn_TerminatesIn; eapply CaseChar2_Sem\n  | [ |- ReadChar2 ⊨ _] => eapply RealiseIn_Realise; eapply ReadChar2_Sem\n  | [ |- ReadChar2 ⊨c(_) _] => eapply ReadChar2_Sem\n  | [ |- projT1 (ReadChar2) ↓ _] => eapply RealiseIn_TerminatesIn; eapply ReadChar2_Sem\n  end.\n\nSmpl Add smpl_TM_Duo : TM_Correct.\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/Basic/Duo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.29122840873041006}}
{"text": "\nRequire Import FiatFormal.Language.SubstExpExp.\nRequire Import FiatFormal.Language.SubstTypeExp.\nRequire Import FiatFormal.Language.TyJudge.\nRequire Import FiatFormal.Language.SubstTypeType.\n\nLemma mapCtor {A : Type} :\n  forall (C : A -> A) xs xs',\n    (forall x x', C x = C x' -> x = x')\n    -> map C xs = map C xs'\n    -> xs = xs'.\nProof.\n  induction xs;\n    destruct xs'; auto; try nope;\n      intros.\n  inversion H0.\n  f_equal. spec H H2; auto.\n  apply IHxs; auto.\nQed.\n\n\nTheorem subst_exp_prog_ix :\n  forall ds ke te t1 ix p t2 s,\n    get ix te = Some t1\n    -> TYPE ds ke (delete ix te) s t1\n    -> TYPEPROG ds ke te p t2\n    -> TYPEPROG ds ke (delete ix te) (substXP ix s p) t2.\nProof.\n  intros. gen s ix t1.\n  induction H1; intros.\n  - Case \"PLet\".\n    invert H; intros; subst; simpl.\n    apply TYLet.\n    + (* prove A generalized *)\n      apply TYADT; try assumption.\n      forall2_pull_in_maps.\n      apply (Forall2_impl_in (fun m t => TYPEMETHOD tr ds ke te m (substTT 0 tr t))); eauto; intros.\n      * destruct x; simpl. inverts H5; subst. eapply TYMETHOD; eauto.\n        eapply subst_value_value_ix; first [ eassumption; assumption ].\n      * forall2_push_out_map_right; auto.\n    + (* prove B generalized *)\n      unfold liftTE in *.\n      rewrite map_delete.\n      rewrite delete_app.\n      apply mapCtor in H9; subst.\n      * assert (length ms = length (map (substTT 0 tr) ts)).\n        eapply Forall2_length; eauto.\n        rewrite map_length in H. rewrite H.\n        eapply IHTYPEPROG; simpl.\n        -- apply get_app_left_some.\n           apply get_map.\n           eassumption.\n        -- rewrite <- delete_app.\n           apply type_tyenv_weaken_append.\n           rewrite <- map_delete.\n           pose proof type_kienv_weaken.\n           unfold liftTE in H3.\n           apply H4. assumption.\n      * (* injective cTor *)\n        intros; inversion H; auto.\n    + assumption.\n  - Case \"PExp\".\n    apply TYExp.\n    eapply subst_value_value_ix; first [ eassumption |  assumption].\nQed.\n\n\nTheorem subst_exp_prog\n  : forall ds ke te t1 p t2 s,\n    TYPEPROG ds ke (te :> t1) p t2\n    -> TYPE ds ke te s t1\n    -> TYPEPROG ds ke te (substXP 0 s p) t2.\nProof.\n  intros.\n  assert (te = delete 0 (te :> t1)). auto.\n  rewrite H1.\n  eapply subst_exp_prog_ix; simpl; eauto.\nQed.\n\n(* new *)\n(* Substitution of several expressions at once. *)\nTheorem subst_exp_prog_list\n  : forall ds ks te ts p1 t1 xs,\n    Forall2 (TYPE ds ks te) xs ts\n    -> TYPEPROG ds ks (te >< ts) p1 t1\n    -> TYPEPROG ds ks te (substXXsP 0 xs p1) t1.\nProof.\n  intros ds ks te ts p1 t1 xs HF HT.\n  gen ts ks p1.\n  induction xs; intros; invert_exp_type.\n  - Case \"base case\".\n    destruct ts.\n    + simpl. auto.\n    + nope.\n  - Case \"step case\".\n    simpl.\n    destruct ts.\n    + nope.\n    + inverts HF.\n      eapply IHxs.\n      * eauto.\n      * simpl in HT.\n        eapply subst_exp_prog.\n        eauto.\n        rrwrite (length xs = length ts).\n        eapply type_tyenv_weaken_append. auto.\nQed.\n\n\nTheorem subst_type_prog_ix\n  : forall ds ix ke kx S te p t,\n    get ix ke = Some kx\n    -> KIND (delete ix ke) S kx\n    -> TYPEPROG ds ke te p t\n    -> TYPEPROG ds (delete ix ke) (substTE ix S te) (substTP ix S p) (substTT ix S t).\nProof.\n  intros. gen S ix kx.\n  induction H1; intros.\n  - Case \"PLet\".\n    simpl. invert H; intros; subst.\n    assert\n      (Hcomp : forall ix S tr t, substTT (0 + ix) S (substTT 0 tr t)\n                            = (substTT 0 (substTT (0 + ix) S tr)\n                                       (substTT (1 + 0 + ix) (liftTT 0 S) t)));\n      intros.\n    + apply substTT_substTT with (n:=0) (m:=ix0).\n    + simpl in Hcomp.\n      rewrite map_map.\n      simpl. rewrite <- map_map with (f:=(substTT (Datatypes.S ix) (liftTT 0 S))).\n      apply TYLet.\n      * SCase \"ADT\".\n        apply TYADT.\n        -- eapply subst_type_type_ix; eassumption.\n        -- forall2_pull_in_maps.\n           apply (Forall2_impl_in\n                    (fun m t => TYPEMETHOD tr ds ke te m (substTT 0 tr t)));\n             eauto; intros.\n          ++ destruct x; simpl. inverts H5; subst.\n             simpl.\n             rewrite <- Hcomp.\n             rewrite <- H16. simpl.\n             rewrite map_app.\n             rewrite dup_map.\n             eapply TYMETHOD; eauto.\n             assert (Hsubst: (TNFun\n                                (dup (substTT ix S tr) arity >< map (substTT ix S) dom)\n                                    (TNProd (nil :> substTT ix S tr :> substTT ix S tRes)))\n                             = (substTT ix S\n                                        (TNFun ((dup tr arity) >< dom)\n                                               (TNProd (nil :> tr :> tRes)))));\n               simpl.\n             rewrite <- dup_map.\n             rewrite <- map_app.\n             auto.\n             rewrite Hsubst.\n             eapply subst_type_exp_ix.\n             eassumption.\n             assumption.\n             assumption.\n          ++ forall2_push_out_map_right; auto.\n      * SCase \"PROG\".\n        rewrite liftTE_substTE with (n:=0) (n':=ix).\n        unfold substTE in *. rewrite <- map_app.\n        apply mapCtor in H9; subst.\n        rewrite liftTT_substTT with (n:=0) (n':=ix).\n        simpl.\n        rewrite delete_rewind in *.\n        eapply IHTYPEPROG.\n        simpl.\n        eassumption.\n        simpl.\n        eapply liftTT_weaken.\n        assumption.\n        intros. inversion H; auto.\n      * eapply subst_type_type_ix; eauto.\n  - Case \"PExp\".\n    apply TYExp.\n    eapply subst_type_exp_ix; eassumption.\nQed.\n\n\nTheorem subst_type_prog\n  : forall ds ke te X S p t,\n    TYPEPROG ds (ke :> X) te p t\n    -> KIND ke S KStar\n    -> TYPEPROG ds ke (substTE 0 S te) (substTP 0 S p) (substTT 0 S t).\nProof.\n  intros.\n  assert (ke = delete 0 (ke :> X)). auto.\n  rewrite H1.\n  eapply subst_type_prog_ix; simpl; eauto.\n  destruct X; assumption.\nQed.\n\n\nTheorem subst_ADT_prog :\n  forall ds X r kr t1 t2 x p,\n    TYPEPROG ds (nil :> X) (nil :> t1) p (liftTT 0 t2)\n    -> KIND nil r kr\n    -> TYPE ds nil nil x (substTT 0 r t1)\n    -> TYPEPROG ds nil nil (substXP 0 x (substTP 0 r p)) t2.\nProof.\n  intros ds X r kr t1 t2 x p HP HK HT.\n  pose proof (subst_type_prog) as STP.\n  specialize (STP _ _ _ _ r _ _ HP).\n  pose proof\n       (subst_exp_prog ds nil nil (substTT 0 r t1) (substTP 0 r p) (t2))\n    as ESL.\n  simpl in *.\n  destruct kr.\n  specialize (STP HK). rewrite substTT_liftTT in STP.\n  specialize (ESL x STP).\n  specialize (ESL HT).\n  assumption.\nQed.\n\n\nTheorem subst_ADT_prog' :\n  forall ds X r kr ts t2 xs p,\n    TYPEPROG ds (nil :> X) (nil >< ts) p (liftTT 0 t2)\n    -> KIND nil r kr\n    -> Forall2 (TYPE ds nil nil) xs (map (substTT 0 r) ts)\n    -> TYPEPROG ds nil nil (substXXsP 0 xs (substTP 0 r p)) t2.\nProof.\n  intros ds X r kr ts t2 xs p HP HK HT.\n  pose proof (subst_type_prog) as STP.\n  specialize (STP _ _ _ _ r _ _ HP).\n  pose proof\n       (subst_exp_prog_list ds nil nil (map (substTT 0 r) ts) (substTP 0 r p) t2)\n    as ESL.\n  simpl in *.\n  destruct kr.\n  specialize (STP HK);\n    unfold substTE in STP. rewrite substTT_liftTT in STP.\n  rewrite map_app in STP; simpl in *.\n  specialize (ESL xs HT).\n  specialize (ESL STP).\n  assumption.\nQed.", "meta": {"author": "paulkrog", "repo": "formalized-fiat", "sha": "8f9022980c038f500aeea9b2f85062f0bfc33eb6", "save_path": "github-repos/coq/paulkrog-formalized-fiat", "path": "github-repos/coq/paulkrog-formalized-fiat/formalized-fiat-8f9022980c038f500aeea9b2f85062f0bfc33eb6/FiatFormal/Language/SubstExistential.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.2912284017250685}}
{"text": "From FileSync Require Export\n     Sync\n     Syntax.\nFrom ITree Require Export\n     Nondeterminism\n     ITree.\nImport\n  Monads.\n\nDefinition fstep (f: F) : state node A :=\n  fun n =>\n    match f with\n    | Fls   p => (n, Als (ls p n))\n    | Fread p =>\n      (n, if read p n is Some c\n       then Aread c else Ano)\n    | Fwrite p c =>\n      if write p c n is Some n'\n      then (n', Ayes) else (n, Ano)\n    | Fmkdir p =>\n      if mkdir p n is Some n'\n      then (n', Ayes) else (n, Ano)\n    | Frm p =>\n      if p is nil then (n, Ano) else\n      (rmf p n, Ayes)\n      (* if rm p n is Some n' *)\n      (* then (n', Ayes) else (n, Ano) *)\n    end.\n\nDefinition qstep (q: Q) : state S A :=\n  fun '(g, r1, r2) =>\n    if q is QFile r f\n    then if r is R1 then\n           let (r1', a) := fstep f r1 in\n           (g, r1', r2, a)\n         else\n           let (r2', a) := fstep f r2 in\n           (g, r1, r2', a)\n    else (recon g r1 r2, Aret BinInt.Z0).\n\nLocal Open Scope list_scope.\n\nFixpoint power {A} (l: list A) : list (list A) :=\n  if l is a::l'\n  then let p : list (list A) := power l' in\n       p ++ map (cons a) p\n  else [[]].\n\nLocal Open Scope file_scope.\n\nDefinition qstept E `(nondetE -< E) (q: Q) : stateT S (itree E) A :=\n  fun gab =>\n    let '(g, r1, r2) := gab in\n    if q is QFile r f\n    then if r is R1 then\n           let (r1', a) := fstep f r1 in\n           ret (g, r1', r2, a)\n         else\n           let (r2', a) := fstep f r2 in\n           ret (g, r1, r2', a)\n    else\n      let aps := allPaths g r1 r2 in\n      ps <- choose1 aps (power aps);;\n      let '(g', r1', r2') as gab' := reconset ps gab in\n      if existsb (conflict g r1 r2) ps\n      then r <- choose1 BinInt.Z.one [BinInt.Z.two];;\n           ret (gab', Aret r)\n      else ret (gab', Aret $ if r1' =? r2' then BinInt.Z0 else BinInt.Z.one).\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/Semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2912284017250684}}
{"text": "Require Import MonadState.\nRequire Import Id.\nRequire Import Std.prod.\nRequire Import Util.FunExt.\n\n(* datatype and definitions *)\n\nRecord indexedStateT S1 S2 (m : Type -> Type) `{Monad m} Out := mkIndexedStateT\n{ runIndexedStateT  : S1 -> m (Out * S2)%type\n; execIndexedStateT : S1 -> m S2  := fun s1 => fmap snd (runIndexedStateT s1)\n; evalIndexedStateT : S1 -> m Out := fun s1 => fmap fst (runIndexedStateT s1)\n}.\nArguments mkIndexedStateT [S1 S2 m _ _ _ Out].\nArguments runIndexedStateT [S1 S2 m _ _ _ Out].\n\nDefinition indexedState S1 S2 Out := indexedStateT S1 S2 Id Out.\nDefinition stateT S m `{Monad m} Out := indexedStateT S S m Out.\nDefinition state S Out := stateT S Id Out.\n\n(* typeclass instances *)\n\nLtac indexedStateT_reason :=\n  match goal with\n  | [ |- context [bind _]] => unfold bind\n  | [ |- context [execIndexedStateT] ] => unfold execIndexedStateT\n  | [ |- context [evalIndexedStateT] ] => unfold evalIndexedStateT\n  | [ |- context [Basics.compose] ] => unfold Basics.compose\n  | [ |- {| runIndexedStateT := _ |} = {| runIndexedStateT := _ |} ] => apply f_equal\n  | [ |- (fun _ => _) = _ ] => apply functional_extensionality; intros\n  | [ |- {| runIndexedStateT := _ |} = ?x ] => destruct x as [rs]\n  | [ |- context [ let (_, _) := ?rs ?x in _ ] ] => destruct (rs x)\n  end; simpl; auto.\n\nInstance Functor_stateT {S m} `{Monad m} : Functor (stateT S m) :=\n{ fmap A B f sa := mkIndexedStateT (fun s =>\n    fmap (fmap f) (runIndexedStateT sa s)) }.\n\nInstance FunctorDec_stateT {S m} `{Monad m} : FunctorDec (stateT S m).\nProof.\n  destruct H0.\n  unfold Basics.compose in functor_comp.\n  split; intros; simpl; repeat indexedStateT_reason.\n\n  - rewrite prod_proj_id.\n    auto.\n\n  - now rewrite (functor_comp _ _ _ _ _ _).\nQed.\n\nInstance Monad_stateT {S m} `{Monad m} : Monad (stateT S m) :=\n{ ret A x := mkIndexedStateT (fun s => ret (x, s))\n; bind A B sa f := mkIndexedStateT (fun s =>\n    runIndexedStateT sa s >>= (fun p => runIndexedStateT (f (fst p)) (snd p)))\n}.\n\nInstance MonadDec_stateT {S m} `{MonadDec m} : MonadDec (stateT S m).\nProof.\n  destruct H0.\n  unfold Basics.compose in *.\n  destruct H2.\n  split; intros; simpl.\n\n  - rewrite (fun_ext_with (\n      fun s => left_id _ _ _ (fun p => runIndexedStateT (f (fst p)) (snd p)))).\n    simpl.\n    repeat indexedStateT_reason.\n\n  - destruct ma.\n    unwrap_layer.\n    rewrite (fun_ext_with_nested' ret (fun _ => prod_proj _ _ _)).\n    now rewrite right_id.\n\n  - repeat indexedStateT_reason.\n\n  - unwrap_layer.\n    now rewrite functor_rel.\nQed.\n\nInstance MonadState_stateT {S m} `{MonadDec m} : MonadState S (stateT S m) :=\n{ get := mkIndexedStateT (fun s => ret (s, s))\n; put s' := mkIndexedStateT (fun _ => ret (tt, s'))\n}.\n\nInstance MonadStateDec_stateT {S m} `{MonadDec m} : MonadStateDec S (stateT S m).\nProof.\n  destruct H2.\n  split;\n    intros;\n    simpl;\n    unwrap_layer;\n    now repeat rewrite left_id.\nQed.\n", "meta": {"author": "hablapps", "repo": "koky", "sha": "7dc9141fafabeb0b381cfbda0cd6e856394cc9d4", "save_path": "github-repos/coq/hablapps-koky", "path": "github-repos/coq/hablapps-koky/koky-7dc9141fafabeb0b381cfbda0cd6e856394cc9d4/Core/indexedStateT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.291210165906773}}
{"text": "Require Export RecTypes.SpecTypes.\nRequire Export RecTypes.InstTy.\nRequire Export RecTypes.Contraction.\nRequire Export RecTypes.ValidTy.\nRequire Export RecTypes.LemmasTypes.\n\nRequire Import StlcEqui.SpecSyntax.\nRequire Import StlcEqui.SpecTyping.\nRequire Import StlcEqui.LemmasTyping.\nRequire Import StlcFix.SpecSyntax.\nRequire Import StlcFix.Inst.\nRequire Import StlcFix.SpecTyping.\nRequire Import StlcFix.SpecAnnot.\nRequire Import StlcFix.SpecEvaluation.\nRequire Import StlcFix.LemmasTyping.\nRequire Import StlcFix.LemmasEvaluation.\nRequire Import StlcFix.CanForm.\nRequire Import Db.Lemmas.\nRequire Import Db.WellScoping.\nRequire Import LogRelFE.LR.\nRequire Import LogRelFE.LemmasLR.\nRequire Import LogRelFE.LemmasIntro.\nRequire Import LogRelFE.LemmasInversion.\nRequire Import LogRelFE.LemmasPseudoType.\nRequire Import LogRelFE.PseudoType.\nRequire Import UValFE.UVal.\n\nRequire Import Lia.\n\nRequire Import Program.Wf.\n\nLocal Ltac crush :=\n  intros; cbn in * |-;\n  repeat\n    (repeat crushStlcSyntaxMatchH;\n     repeat crushRecTypesMatchH;\n     repeat crushDbSyntaxMatchH;\n     repeat crushRepEmulEmbed;\n     repeat E.crushStlcSyntaxMatchH;\n     repeat F.crushStlcSyntaxMatchH;\n     split;\n     trivial;\n     crushTyping;\n     E.crushTyping;\n     try crushOfType;\n     subst*);\n  try discriminate; try lia;\n  eauto with eval;\n  repeat crushStlcSyntaxMatchH (* remove apTm's again *).\n\nFixpoint downgrade (n : nat) (d : nat) (τ : E.Ty) {struct n} : F.Tm :=\n  let abs_creator := F.abs (UValFE (n + d) τ) in\n  match n with\n    | 0 => abs_creator (unkUVal 0)\n    | S n =>\n      match unfoldn (LMC τ) τ with\n        | E.tunit => abs_creator (F.var 0)\n        | E.tbool => abs_creator (F.var 0)\n        | E.tprod τ τ' => abs_creator (F.caseof (F.var 0)\n                                               (F.inl (F.pair (F.app (downgrade n d τ) (F.proj₁ (F.var 0)))\n                                                              (F.app (downgrade n d τ') (F.proj₂ (F.var 0)))))\n                                              (F.inr (F.var 0)))\n        | E.tsum τ τ' => abs_creator (F.caseof (F.var 0)\n                                              (F.inl (F.caseof (F.var 0)\n                                                               (F.inl (F.app (downgrade n d τ)\n                                                                             (F.var 0)))\n                                                               (F.inr (F.app (downgrade n d τ')\n                                                                             (F.var 0)))))\n                                              (F.inr (F.var 0)))\n        | E.tarr τ τ' => abs_creator (F.caseof (F.var 0)\n                                              (F.inl (F.abs (UValFE n τ)\n                                                            (F.app (downgrade n d τ')\n                                                                   (F.app (F.var 1)\n                                                                          (F.app (upgrade n d τ)\n                                                                                 (F.var 0))))))\n                                              (F.inr (F.var 0)))\n        | E.trec τ => abs_creator (unkUVal (S n))\n        | E.tvar _ => abs_creator (F.caseof (F.var 0) (F.inl (F.var 0)) (F.inr (F.var 0)))\n      end\n  end\nwith\nupgrade (n : nat) (d : nat) (τ : E.Ty) {struct n} :=\n  let abs_creator := F.abs (UValFE n τ) in\n  match n with\n    | 0 => abs_creator (unkUVal d)\n    | S n =>\n      match unfoldn (LMC τ) τ with\n        | E.tunit => abs_creator (F.var 0)\n        | E.tbool => abs_creator (F.var 0)\n        | E.tprod τ τ' => abs_creator (F.caseof (F.var 0)\n                                               (F.inl (F.pair (F.app (upgrade n d τ) (F.proj₁ (F.var 0)))\n                                                              (F.app (upgrade n d τ') (F.proj₂ (F.var 0)))))\n                                              (F.inr (F.var 0)))\n        | E.tsum τ τ' => abs_creator (F.caseof (F.var 0)\n                                        (F.inl (F.caseof (F.var 0)\n                                                          (F.inl (F.app (upgrade n d τ)\n                                                                        (F.var 0)))\n                                                          (F.inr (F.app (upgrade n d τ')\n                                                                        (F.var 0)))))\n                                        (F.inr (F.var 0)))\n        | E.tarr τ τ' => abs_creator (F.caseof (F.var 0)\n                                              (F.inl (F.abs (UValFE (n + d) τ)\n                                                            (F.app (upgrade n d τ')\n                                                                  (F.app (F.var 1)\n                                                                          (F.app (downgrade n d τ)\n                                                                                (F.var 0))))))\n                                              (F.inr (F.var 0)))\n        (* | E.trec τ' => upgrade n d (fu' (E.trec τ')) *)\n        | E.trec τ => abs_creator (unkUVal (S n + d))\n        | E.tvar _ => abs_creator (F.caseof (F.var 0) (F.inl (F.var 0)) (F.inr (F.var 0)))\n        end\n  end.\n\nFixpoint downgradeA (n : nat) (d : nat) (τ : E.Ty) {struct n} : F.TmA\n  :=\n  let abs_creator := F.a_abs (UValFE (n + d) τ) (UValFE n τ) in\n  match n with\n    | 0 => abs_creator (unkUValA 0 τ)\n    | S n =>\n      match unfoldn (LMC τ) τ with\n        | E.tunit => abs_creator (F.a_var 0)\n        | E.tbool => abs_creator (F.a_var 0)\n        | E.tprod τ τ' =>\n          abs_creator\n            (F.a_caseof (F.tprod (UValFE (n + d) τ) (UValFE (n + d) τ')) F.tunit (UValFE (S n) (E.tprod τ τ'))\n                        (F.a_var 0)\n                        (F.a_inl (F.tprod (UValFE n τ) (UValFE n τ')) F.tunit\n                           (F.a_pair (UValFE n τ) (UValFE n τ')\n                                     (F.a_app (UValFE (n + d) τ) (UValFE n τ)\n                                              (downgradeA n d τ) (F.a_proj₁ (UValFE (n +d) τ) (UValFE (n +d) τ') (F.a_var 0)))\n                                     (F.a_app (UValFE (n + d) τ') (UValFE n τ')\n                                              (downgradeA n d τ') (F.a_proj₂ (UValFE (n +d) τ) (UValFE (n+d) τ') (F.a_var 0)))))\n                        (F.a_inr (F.tprod (UValFE n τ) (UValFE n τ')) F.tunit (F.a_var 0)))\n        | E.tsum τ τ' =>\n          abs_creator\n            (F.a_caseof (F.tsum (UValFE (n + d) τ) (UValFE (n + d) τ')) F.tunit (UValFE (S n) (E.tsum τ τ'))\n                        (F.a_var 0)\n                        (F.a_inl (F.tsum (UValFE n τ) (UValFE n τ')) F.tunit\n                                 (F.a_caseof (UValFE (n + d) τ) (UValFE (n + d) τ') (F.tsum (UValFE n τ) (UValFE n τ')) (F.a_var 0)\n                                             (F.a_inl (UValFE n τ) (UValFE n τ') (F.a_app (UValFE (n + d) τ) (UValFE n τ) (downgradeA n d τ)\n                                                                                          (F.a_var 0)))\n                                             (F.a_inr (UValFE n τ) (UValFE n τ') (F.a_app (UValFE (n + d) τ') (UValFE n τ') (downgradeA n d τ')\n                                                                       (F.a_var 0)))))\n                        (F.a_inr (F.tsum (UValFE n τ) (UValFE n τ')) F.tunit (F.a_var 0)))\n        | E.tarr τ τ' =>\n          abs_creator\n            (F.a_caseof (F.tarr (UValFE (n + d) τ) (UValFE (n + d) τ')) F.tunit (UValFE (S n) (E.tarr τ τ'))\n                        (F.a_var 0)\n                        (F.a_inl (F.tarr (UValFE n τ) (UValFE n τ')) F.tunit\n                                 (F.a_abs (UValFE n τ) (UValFE n τ')\n                                          (F.a_app (UValFE (n + d) τ') (UValFE n τ') (downgradeA n d τ')\n                                                   (F.a_app (UValFE (n + d) τ) (UValFE (n + d) τ') (F.a_var 1)\n                                                            (F.a_app (UValFE n τ) (UValFE (n + d) τ) (upgradeA n d τ)\n                                                                     (F.a_var 0))))))\n                        (F.a_inr (F.tarr (UValFE n τ) (UValFE n τ')) F.tunit (F.a_var 0)))\n        | E.trec τ =>\n          abs_creator (unkUValA (S n) (trec τ))\n        | E.tvar _ => abs_creator (F.a_caseof F.tunit F.tunit (F.tsum F.tunit F.tunit) (F.a_var 0) (F.a_inl F.tunit F.tunit (F.a_var 0)) (F.a_inr F.tunit F.tunit (F.a_var 0)))\n      end\n  end\nwith\nupgradeA (n : nat) (d : nat) (τ : E.Ty) {struct n} :=\n  let abs_creator := F.a_abs (UValFE n τ) (UValFE (n + d) τ) in\n  match n with\n    | 0 => abs_creator (unkUValA d τ)\n    | S n =>\n      match unfoldn (LMC τ) τ with\n        | E.tunit => abs_creator (F.a_var 0)\n        | E.tbool => abs_creator (F.a_var 0)\n        | E.tprod τ τ' =>\n          abs_creator\n            (F.a_caseof (F.tprod (UValFE n τ) (UValFE n τ')) F.tunit (UValFE (S (n + d)) (E.tprod τ τ'))\n                        (F.a_var 0)\n                        (F.a_inl (F.tprod (UValFE (n + d) τ) (UValFE (n + d) τ')) F.tunit\n                           (F.a_pair (UValFE (n + d) τ) (UValFE (n + d) τ')\n                                     (F.a_app (UValFE n τ) (UValFE (n + d) τ)\n                                              (upgradeA n d τ) (F.a_proj₁ (UValFE n τ) (UValFE n τ') (F.a_var 0)))\n                                     (F.a_app (UValFE n τ') (UValFE (n + d) τ')\n                                              (upgradeA n d τ') (F.a_proj₂ (UValFE n τ) (UValFE n τ') (F.a_var 0)))))\n                        (F.a_inr (F.tprod (UValFE (n+d) τ) (UValFE (n+d) τ')) F.tunit (F.a_var 0)))\n        | E.tsum τ τ' =>\n          abs_creator\n            (F.a_caseof (F.tsum (UValFE n τ) (UValFE n τ')) F.tunit (UValFE (S n + d) (E.tsum τ τ'))\n                        (F.a_var 0)\n                        (F.a_inl (F.tsum (UValFE (n + d) τ) (UValFE (n + d) τ')) F.tunit\n                                 (F.a_caseof (UValFE n τ) (UValFE n τ') (F.tsum (UValFE (n + d) τ) (UValFE (n + d) τ'))\n                                             (F.a_var 0)\n                                             (F.a_inl (UValFE (n + d) τ) (UValFE (n + d) τ')\n                                                      (F.a_app (UValFE n τ) (UValFE (n + d) τ) (upgradeA n d τ)\n                                                                   (F.a_var 0)))\n                                             (F.a_inr (UValFE (n + d) τ) (UValFE (n + d) τ')\n                                                      (F.a_app (UValFE n τ') (UValFE (n + d) τ') (upgradeA n d τ')\n                                                               (F.a_var 0)))))\n                        (F.a_inr (F.tsum (UValFE (n + d) τ) (UValFE (n + d) τ')) F.tunit (F.a_var 0)))\n        | E.tarr τ τ' =>\n          abs_creator\n            (F.a_caseof (F.tarr (UValFE n τ) (UValFE n τ')) F.tunit (UValFE (S n + d) (E.tarr τ τ'))\n                        (F.a_var 0)\n                        (F.a_inl (F.tarr (UValFE (n + d) τ) (UValFE (n + d) τ')) F.tunit\n                                 (F.a_abs (UValFE (n + d) τ) (UValFE (n + d) τ')\n                                          (F.a_app (UValFE n τ') (UValFE (n + d) τ') (upgradeA n d τ')\n                                                   (F.a_app (UValFE n τ) (UValFE n τ') (F.a_var 1)\n                                                            (F.a_app (UValFE (n + d) τ) (UValFE n τ) (downgradeA n d τ)\n                                                                     (F.a_var 0))))))\n                        (F.a_inr (F.tarr (UValFE (n + d) τ) (UValFE (n + d) τ')) F.tunit (F.a_var 0)))\n        (* | E.trec τ' => upgradeA n d (fu' (E.trec τ')) *)\n        | E.trec τ =>\n          abs_creator (unkUValA (S n + d) (trec τ))\n        | E.tvar _ =>\n          abs_creator\n            (F.a_caseof F.tunit F.tunit (F.tsum F.tunit F.tunit)\n                        (F.a_var 0)\n                        (F.a_inl F.tunit F.tunit (F.a_var 0))\n                        (F.a_inr F.tunit F.tunit (F.a_var 0)))\n        end\n  end.\n\nLemma upgrade_annot_T {n : nat} {Γ d τ} :\n  ValidTy τ ->\n  ⟪ Γ a⊢ upgradeA n d τ : UValFE n τ ⇒ UValFE (n + d) τ ⟫\nwith\ndowngrade_annot_T {n : nat} {Γ d τ} :\n  ValidTy τ ->\n  ⟪ Γ a⊢ downgradeA n d τ : UValFE (n + d) τ ⇒ UValFE n τ ⟫.\nProof.\n  - induction n;\n      intros;\n      unfold upgradeA, downgradeA;\n      unfold UValFE; cbn.\n      + repeat constructor;\n        try eapply unkUValAT;\n        crushValidTy.\n      + assert (vuτ : ValidTy (unfoldn (LMC τ) τ)) by eauto using ValidTy_unfoldn.\n        assert (luτz : LMC (unfoldn (LMC τ) τ) = 0) by (eapply unfoldn_LMC; crushValidTy).\n        remember (unfoldn (LMC τ) τ) as τ'; destruct τ';\n          eauto with typing uval_typing tyvalid2.\n        inversion luτz.\n  - induction n;\n      intros;\n      unfold upgradeA, downgradeA;\n      unfold UValFE; cbn.\n      + repeat constructor;\n          try eapply unkUValAT;\n          crushValidTy.\n      + assert (vuτ : ValidTy (unfoldn (LMC τ) τ)) by eauto using ValidTy_unfoldn.\n        assert (luτz : LMC (unfoldn (LMC τ) τ) = 0) by (eapply unfoldn_LMC; crushValidTy).\n        remember (unfoldn (LMC τ) τ) as τ'; destruct τ';\n          eauto with typing uval_typing tyvalid2.\n        inversion luτz.\nQed.\n\nLemma upgrade_annot_T1 {Γ n τ} :\n  ValidTy τ ->\n  ⟪ Γ a⊢ upgradeA n 1 τ : UValFE n τ ⇒ UValFE (S n) τ ⟫.\nProof.\n  replace (S n) with (n + 1) by lia.\n  eauto using upgrade_annot_T.\nQed.\n\nLemma downgrade_annot_T1 {Γ n τ} :\n  ValidTy τ ->\n  ⟪ Γ a⊢ downgradeA n 1 τ : UValFE (S n) τ ⇒ UValFE n τ ⟫.\nProof.\n  replace (S n) with (n + 1) by lia.\n  eauto using downgrade_annot_T.\nQed.\n\nLemma upgrade_annot_T1' {Γ n τ τ'} :\n  ValidTy τ ->\n  τ' = UValFE' (UValFE n) (unfoldn (LMC τ) τ) ->\n  ⟪ Γ a⊢ upgradeA n 1 τ : UValFE n τ ⇒ τ' ⟫.\nProof.\n  intros. subst.\n  now eapply upgrade_annot_T1.\nQed.\n\nLemma downgrade_annot_T1' {Γ n τ τ'} :\n  ValidTy τ ->\n  τ' = UValFE' (UValFE n) (unfoldn (LMC τ) τ) ->\n  ⟪ Γ a⊢ downgradeA n 1 τ : τ' ⇒ UValFE n τ ⟫.\nProof.\n  intros. subst.\n  now eapply downgrade_annot_T1.\nQed.\n\nLtac crushUpgradeTypingMatch :=\n  repeat match goal with\n    | |- ⟪ _ a⊢ upgradeA _ _ _ : _ ⟫ => apply upgrade_annot_T1'\n    | |- ⟪ _ a⊢ downgradeA _ _ _ : _ ⟫ => apply downgrade_annot_T1'\n  end.\n\n#[export]\nHint Extern 20 (⟪ _ a⊢ upgradeA _ _ _ : _ ⟫) => crushUpgradeTypingMatch : typing.\n\n#[export]\nHint Extern 20 (⟪ _ a⊢ downgradeA _ _ _ : _ ⟫) => crushUpgradeTypingMatch : typing.\n\n\nFixpoint upgrade_upgradeA {n d τ} {struct n} :\n  eraseAnnot (upgradeA n d τ) = upgrade n d τ\n  with\n    downgrade_downgradeA {n d τ} {struct n} :\n  eraseAnnot (downgradeA n d τ) = downgrade n d τ.\nProof.\n  - destruct n.\n    + clear upgrade_upgradeA.\n      cbn; rewrite <-?unkUVal_unkUValA;\n      repeat f_equal.\n    + cbn;\n        destruct (unfoldn (LMC τ) τ);\n        cbn;\n        rewrite <-?unkUVal_unkUValA;\n        repeat f_equal;\n        eauto using downgrade_annot_T1.\n  - destruct n.\n    + clear downgrade_downgradeA.\n      cbn;\n      rewrite <-?unkUVal_unkUValA;\n      repeat f_equal.\n    + cbn;\n        destruct (unfoldn (LMC τ) τ);\n        cbn;\n        rewrite <-?unkUVal_unkUValA;\n        repeat f_equal;\n        eauto.\nQed.\n\nLemma upgrade_T {n : nat} {Γ d τ} :\n  ValidTy τ ->\n  ⟪ Γ ⊢ upgrade n d τ : UValFE n τ ⇒ UValFE (n + d) τ ⟫\nwith\ndowngrade_T {n : nat} {Γ d τ} :\n  ValidTy τ ->\n  ⟪ Γ ⊢ downgrade n d τ : UValFE (n + d) τ ⇒ UValFE n τ ⟫.\nProof.\n  - revert τ;\n      induction n;\n      intros τ vτ;\n      unfold upgrade, downgrade, UValFE;\n      cbn;\n      assert (vuτ : ValidTy (unfoldn (LMC τ) τ)) by eauto using ValidTy_unfoldn;\n      assert (luτz : LMC (unfoldn (LMC τ) τ) = 0) by (eapply unfoldn_LMC; crushValidTy);\n      destruct (unfoldn (LMC τ) τ);\n      cbn;\n      eauto with typing uval_typing tyvalid2.\n  - revert τ;\n      induction n;\n      intros τ vτ;\n      unfold upgrade, downgrade, UValFE;\n      cbn;\n      assert (vuτ : ValidTy (unfoldn (LMC τ) τ)) by eauto using ValidTy_unfoldn;\n      assert (luτz : LMC (unfoldn (LMC τ) τ) = 0) by (eapply unfoldn_LMC; crushValidTy);\n      destruct (unfoldn (LMC τ) τ);\n      cbn;\n      unfold upgrade, downgrade;\n      eauto with typing uval_typing tyvalid2.\nQed.\n\nLemma upgrade_T1 {Γ n τ} :\n  ValidTy τ ->\n  ⟪ Γ ⊢ upgrade n 1 τ : UValFE n τ ⇒ UValFE (S n) τ ⟫.\nProof.\n  replace (S n) with (n + 1) by lia.\n  eauto using upgrade_T.\nQed.\n\nLemma downgrade_T1 {Γ n τ} :\n  ValidTy τ ->\n  ⟪ Γ ⊢ downgrade n 1 τ : UValFE (S n) τ ⇒ UValFE n τ ⟫.\nProof.\n  replace (S n) with (n + 1) by lia.\n  eauto using downgrade_T.\nQed.\n\n#[export]\nHint Resolve upgrade_T1 : uval_typing.\n#[export]\nHint Resolve downgrade_T1 : uval_typing.\n#[export]\nHint Resolve upgrade_annot_T1 : uval_typing.\n#[export]\nHint Resolve downgrade_annot_T1 : uval_typing.\n\nLemma upgrade_closed {n d τ} :\n  ValidTy τ ->\n  ⟨ 0 ⊢ upgrade n d τ ⟩.\nProof.\n  intros vτ.\n  enough (⟪ F.empty ⊢ upgrade n d τ : UValFE n τ ⇒ UValFE (n + d) τ ⟫) as ty by eapply (wt_implies_ws ty).\n  now eapply upgrade_T.\nQed.\n\nLemma downgrade_closed {n d τ} :\n  ValidTy τ ->\n  ⟨ 0 ⊢ downgrade n d τ ⟩.\nProof.\n  intros vτ.\n  enough (⟪ F.empty ⊢ downgrade n d τ : UValFE (n + d) τ ⇒ UValFE n τ ⟫) as ty by eapply (wt_implies_ws ty).\n  now eapply downgrade_T.\nQed.\n\nLemma upgrade_sub {n d τ γ} :\n  ValidTy τ ->\n  (upgrade n d τ)[γ] = upgrade n d τ.\nProof.\n  intros vτ.\n  apply wsClosed_invariant.\n  now eapply upgrade_closed.\nQed.\n\nLemma downgrade_sub {n d τ γ} :\n  ValidTy τ ->\n  (downgrade n d τ)[γ] = downgrade n d τ.\nProof.\n  intros vτ.\n  apply wsClosed_invariant.\n  now eapply downgrade_closed.\nQed.\n\nLemma downgrade_value {n d τ} : Value (downgrade n d τ).\nProof.\n  revert d τ;\n    induction n; intros; simpl;\n    destruct (unfoldn (LMC τ) τ); simpl; trivial.\nQed.\n\nLemma upgrade_value {n d τ} : Value (upgrade n d τ).\nProof.\n  revert d τ;\n    induction n; intros; simpl;\n    destruct (unfoldn (LMC τ) τ); simpl; trivial.\nQed.\n\nLemma downgrade_unfoldn {n d τ} :\n  ValidTy τ ->\n  downgrade n d τ = downgrade n d (unfoldn (LMC τ) τ).\nProof.\n  induction n; intros vτ; cbn.\n  - erewrite UValFE_unfoldn; try reflexivity.\n    crushValidTy.\n  - erewrite unfoldn_LMC; cbn; crushValidTy.\n    rewrite <-(UValFE_unfoldn (m := LMC τ)); crushValidTy.\nQed.\n\nLemma upgrade_unfoldn {n d τ} :\n  ValidTy τ ->\n  upgrade n d τ = upgrade n d (unfoldn (LMC τ) τ).\nProof.\n  induction n; intros vτ; cbn.\n  - erewrite UValFE_unfoldn; try reflexivity.\n    crushValidTy.\n  - erewrite unfoldn_LMC; cbn; crushValidTy.\n    rewrite <-(UValFE_unfoldn (m := LMC τ)); crushValidTy.\nQed.\n\nLemma downgrade_zero_eval {d τ v} : Value v → app (downgrade 0 d τ) v -->* unkUVal 0.\nProof.\n  intros vv.\n  unfold downgrade.\n  eapply evalStepStar. eapply eval₀_to_eval. crush.\n  simpl; eauto with eval.\nQed.\n\nLemma upgrade_zero_eval {d τ v} : Value v → app (upgrade 0 d τ) v -->* unkUVal d.\nProof.\n  intros vv.\n  unfold upgrade.\n  eapply evalStepStar. eapply eval₀_to_eval. crush.\n  destruct d; simpl; eauto with eval.\nQed.\n\nLemma downgrade_eval_unk {n d τ} :\n  ValidTy τ ->\n  app (downgrade n d τ) (unkUVal (n + d)) -->* unkUVal n.\nProof.\n  intros vτ.\n  assert (vv : Value (unkUVal (n + d))) by apply unkUVal_Value.\n  destruct n; simpl.\n  - eapply evalStepStar. eapply eval₀_to_eval. crush.\n    simpl; eauto with eval.\n  - change _ with (Value (inr unit)) in vv.\n    assert (ValidTy (unfoldn (LMC τ) τ)) by eauto using ValidTy_unfoldn.\n    destruct (unfoldn (LMC τ) τ);\n    eapply evalStepStar;\n    try refine (eval_ctx₀ phole (eval_beta _) I); eauto;\n    subst; cbn; crush; rewrite ?downgrade_sub, ?upgrade_sub;\n      crushValidTy;\n    eapply evalStepStar;\n    try refine (eval_ctx₀ phole (eval_case_inr _) I); eauto;\n    crush.\nQed.\n\nLemma upgrade_eval_unk {n d τ} :\n  ValidTy τ ->\n  app (upgrade n d τ) (unkUVal n) -->* unkUVal (n + d).\nProof.\n  intros vτ.\n  assert (vv : Value (unkUVal n)) by apply unkUVal_Value.\n  destruct n; simpl.\n  - eapply evalStepStar. eapply eval₀_to_eval. crush.\n    destruct d;\n    simpl; eauto with eval.\n  - change _ with (Value (inl unit)) in vv.\n    assert (ValidTy (unfoldn (LMC τ) τ)) by eauto using ValidTy_unfoldn.\n    destruct (unfoldn (LMC τ) τ);\n    eapply evalStepStar;\n    try refine (eval_ctx₀ phole (eval_beta _) I); eauto;\n    subst; cbn; crush; rewrite ?downgrade_sub, ?upgrade_sub;\n      crushValidTy;\n    eapply evalStepStar;\n    try refine (eval_ctx₀ phole (eval_case_inr _) I); eauto;\n    crush.\nQed.\n\nLemma downgrade_eval_inUnit {n d} :\n  app (downgrade (S n) d E.tunit) (F.inl F.unit) -->* F.inl F.unit.\nProof.\n  eapply evalStepStar.\n  eapply eval₀_to_eval.\n  simpl.\n  apply F.eval_beta.\n  all: eauto with eval.\n  crush.\nQed.\n\nLemma upgrade_eval_inUnit {n d} :\n  app (upgrade (S n) d E.tunit) (F.inl F.unit) -->* F.inl F.unit.\nProof.\n  eapply evalStepStar.\n  eapply eval₀_to_eval.\n  simpl.\n  apply F.eval_beta.\n  all: eauto with eval.\n  crush.\nQed.\n\nLemma downgrade_eval_inBool {n d v} (vv : Value v) :\n  app (downgrade (S n) d E.tbool) (F.inl v) -->* F.inl v.\nProof.\n  eapply evalStepStar.\n  eapply eval₀_to_eval.\n  simpl.\n  apply F.eval_beta; now cbn.\n  crush.\nQed.\n\nLemma upgrade_eval_inBool {n d v} (vv : Value v):\n  app (upgrade (S n) d E.tbool) (F.inl v) -->* F.inl v.\nProof.\n  eapply evalStepStar.\n  eapply eval₀_to_eval.\n  simpl.\n  apply F.eval_beta; now cbn.\n  crush.\nQed.\n\nLemma downgrade_eval_inSum {n d v v' va va' τ τ'} :\n  ValidTy τ -> ValidTy τ' ->\n  Value v → Value v' →\n  (va = inl v ∧ va' = inl v' ∧ app (downgrade n d τ) v -->* v')\n  ∨ (va = inr v ∧ va' = inr v' ∧ app (downgrade n d τ') v -->* v') →\n  app (downgrade (S n) d (E.tsum τ τ')) (F.inl va) -->* F.inl va'.\nProof.\n  intros vτ vτ' vv vv' eqs.\n  cbn.\n  destruct eqs as [(? & ? & ?)|(? & ? & ?)]; subst;\n  (eapply evalStepStar; [eapply eval₀_to_eval; crush|]);\n    rewrite -> ?(caseUVal_sub (beta1 _)); simpl; crush;\n    rewrite -> ?upgrade_sub, ?downgrade_sub;\n    eauto;\n  (eapply evalStepStar; [eapply eval₀_to_eval; crush|]);\n    rewrite -> ?(caseUVal_sub (beta1 _)); simpl; crush;\n    rewrite -> ?upgrade_sub, ?downgrade_sub;\n    eauto;\n    eapply evalStepStar;\n  [refine (eval_ctx₀ (pinl phole) (eval_case_inl _) I); crush|\n  |refine (eval_ctx₀ (pinl phole) (eval_case_inr _) I); crush|];\n  cbn; crush; rewrite ?upgrade_sub, ?downgrade_sub;\n    crushValidTy;\n  [change (F.inl (F.inl ?t)) with (pctx_app t (pinl (pinl phole)))\n  |change (F.inl (F.inr ?t)) with (pctx_app t (pinl (pinr phole)))];\n  apply evalstar_ctx;\n  cbn;\n  trivial.\nQed.\n\nLemma downgrade_eval_inProd {n d v1 v2 v1' v2' τ1 τ2} :\n  ValidTy τ1 -> ValidTy τ2 ->\n  Value v1 -> Value v2 → Value v1' → Value v2' →\n  app (downgrade n d τ1) v1 -->* v1' ->\n  app (downgrade n d τ2) v2 -->* v2' ->\n  app (downgrade (S n) d (E.tprod τ1 τ2)) (F.inl (pair v1 v2)) -->* F.inl (pair v1' v2').\nProof.\n  intros vτ1 vτ2 vv1 vv2 vv1' vv2' es1 es2.\n  eapply evalStepStar.\n  { eapply eval_eval₀; eapply eval_beta; now cbn. }\n  eapply evalStepStar.\n  { eapply eval_eval₀; eapply eval_case_inl; now cbn. }\n  crushTyping.\n  rewrite ?downgrade_sub;\n    eauto.\n  eapply evalStepStar.\n  { refine (eval_ctx₀' (eval_proj₁ vv1 vv2) _ _ _); F.inferContext.\n    cbn; eauto using downgrade_value. }\n  eapply evalStepTrans.\n  { eapply (evalstar_ctx' es1); F.inferContext; now cbn. }\n  eapply evalStepStar.\n  { eapply (eval_ctx₀' (eval_proj₂ vv1 vv2)); F.inferContext; cbn; eauto using downgrade_value. }\n  eapply evalStepTrans.\n  { eapply (evalstar_ctx' es2); F.inferContext; now cbn. }\n  crush.\nQed.\n\nLemma upgrade_eval_inProd {n d v1 v2 v1' v2' τ1 τ2} :\n  ValidTy τ1 -> ValidTy τ2 ->\n  Value v1 -> Value v2 → Value v1' → Value v2' →\n  app (upgrade n d τ1) v1 -->* v1' ->\n  app (upgrade n d τ2) v2 -->* v2' ->\n  app (upgrade (S n) d (E.tprod τ1 τ2)) (F.inl (pair v1 v2)) -->* F.inl (pair v1' v2').\nProof.\n  intros vτ1 vτ2 vv1 vv2 vv1' vv2' es1 es2.\n  eapply evalStepStar.\n  { eapply eval_eval₀; eapply eval_beta; now cbn. }\n  eapply evalStepStar.\n  { eapply eval_eval₀; eapply eval_case_inl; now cbn. }\n  crushTyping.\n  rewrite ?upgrade_sub; crushValidTy.\n  eapply evalStepStar.\n  { refine (eval_ctx₀' (eval_proj₁ vv1 vv2) _ _ _); F.inferContext.\n    cbn; eauto using upgrade_value. }\n  eapply evalStepTrans.\n  { eapply (evalstar_ctx' es1); F.inferContext; now cbn. }\n  eapply evalStepStar.\n  { eapply (eval_ctx₀' (eval_proj₂ vv1 vv2)); F.inferContext; cbn; eauto using upgrade_value. }\n  eapply evalStepTrans.\n  { eapply (evalstar_ctx' es2); F.inferContext; now cbn. }\n  crush.\nQed.\n\nLemma upgrade_eval_inSum {n d v v' va va' τ τ'} :\n  ValidTy τ -> ValidTy τ' ->\n  Value v → Value v' →\n  (va = inl v ∧ va' = inl v' ∧ app (upgrade n d τ) v -->* v')\n  ∨ (va = inr v ∧ va' = inr v' ∧ app (upgrade n d τ') v -->* v') →\n  app (upgrade (S n) d (E.tsum τ τ')) (F.inl va) -->* F.inl va'.\nProof.\n  intros vτ vτ' vv vv' eqs.\n  cbn.\n  destruct eqs as [(? & ? & ?)|(? & ? & ?)]; subst;\n  (eapply evalStepStar; [eapply eval₀_to_eval; crush|]);\n    rewrite -> ?(caseUVal_sub (beta1 _)); simpl; crush;\n    rewrite -> ?upgrade_sub, ?downgrade_sub;\n    crushValidTy;\n  (eapply evalStepStar; [eapply eval₀_to_eval; crush|]);\n    rewrite -> ?(caseUVal_sub (beta1 _)); simpl; crush;\n    rewrite -> ?upgrade_sub, ?downgrade_sub;\n    crushValidTy;\n    eapply evalStepStar;\n  [refine (eval_ctx₀ (pinl phole) (eval_case_inl _) I); crush|\n  |refine (eval_ctx₀ (pinl phole) (eval_case_inr _) I); crush|];\n  cbn; crush; rewrite ?upgrade_sub, ?downgrade_sub;\n    crushValidTy;\n  [change (F.inl (F.inl ?t)) with (pctx_app t (pinl (pinl phole)))\n  |change (F.inl (F.inr ?t)) with (pctx_app t (pinl (pinr phole)))];\n  apply evalstar_ctx;\n  cbn;\n  trivial.\nQed.\n\n\nLemma downgrade_eval_inArr {n d v τ τ'} :\n  ValidTy τ -> ValidTy τ' ->\n  Value v →\n  app (downgrade (S n) d (E.tarr τ τ')) (F.inl v) -->*\n     F.inl (abs (UValFE n τ) (app (downgrade n d τ') (app (v[wk]) (app (upgrade n d τ) (var 0))))).\nProof.\n  intros vτ vτ' vv.\n  cbn.\n\n  (* beta-reduce *)\n  ((eapply evalStepStar; [eapply eval₀_to_eval; crush|]);\n      rewrite -> ?(caseUVal_sub (beta1 _)); simpl; crush;\n      rewrite -> ?upgrade_sub, ?downgrade_sub);\n  crushValidTy;\n  (eapply evalStepStar; [eapply eval₀_to_eval; crush|]);\n    rewrite -> ?(caseUVal_sub (beta1 _)); simpl; crush;\n    rewrite -> ?upgrade_sub, ?downgrade_sub;\n  crushValidTy;\n  change (wk 0) with 1; simpl;\n  eauto with eval.\nQed.\n\nLemma upgrade_eval_inArr {n d v τ τ'} :\n  ValidTy τ -> ValidTy τ' ->\n  Value v →\n  app (upgrade (S n) d (E.tarr τ τ')) (F.inl v) -->*\n     F.inl (abs (UValFE (n + d) τ) (app (upgrade n d τ') (app (v[wk]) (app (downgrade n d τ) (var 0))))).\nProof.\n  intros vτ vτ' vv.\n  cbn.\n\n  (* beta-reduce *)\n  ((eapply evalStepStar; [eapply eval₀_to_eval; crush|]);\n      rewrite -> ?(caseUVal_sub (beta1 _)); simpl; crush;\n      rewrite -> ?upgrade_sub, ?downgrade_sub);\n  crushValidTy;\n  (eapply evalStepStar; [eapply eval₀_to_eval; crush|]);\n    rewrite -> ?(caseUVal_sub (beta1 _)); simpl; crush;\n    rewrite -> ?upgrade_sub, ?downgrade_sub;\n  crushValidTy;\n  change (wk 0) with 1; simpl;\n  eauto with eval.\nQed.\n\nLemma downgrade_eval_inRec {n d τ} :\n  ValidTy τ ->\n  downgrade n d τ[beta1 (E.trec τ)] = downgrade n d (E.trec τ).\n      (* F.inl (app (downgrade n d τ[beta1 (E.trec τ)]) v). *)\nProof.\n  intros vτ.\n  induction n; cbn.\n  - rewrite UValFE_trec;\n    now crushValidTy.\n  - change (τ[beta1 (E.trec τ)]) with (unfoldOnce (trec τ)).\n    rewrite (LMC_unfoldOnce (trec τ)); crushValidTy; cbn.\n    rewrite ?UValFE_trec; crushValidTy.\n    eauto with arith.\nQed.\n\nLemma upgrade_eval_inRec {n d τ} :\n  ValidTy τ ->\n  upgrade n d τ[beta1 (E.trec τ)] = upgrade n d (E.trec τ).\nProof.\n  intros vτ.\n  induction n; cbn.\n  - rewrite ?UValFE_trec;\n    now crushValidTy.\n  - change (τ[beta1 (E.trec τ)]) with (unfoldOnce (trec τ)).\n    rewrite (LMC_unfoldOnce (trec τ)); crushValidTy; cbn.\n    rewrite ?UValFE_trec; crushValidTy.\n    eauto with arith.\nQed.\n\nLemma downgrade_reduces {n d v τ} :\n  ValidTy τ ->\n  ⟪ F.empty ⊢ v : UValFE (n + d) τ ⟫ → Value v →\n  exists v', Value v' ∧ ⟪ F.empty ⊢ v' : UValFE n τ ⟫ ∧\n             app (downgrade n d τ) v -->* v'.\nProof.\n  revert τ;\n  revert v; induction n;\n  intros v τ vτ ty vv.\n  - exists (unkUVal 0).\n    eauto using unkUVal_Value, unkUValT, downgrade_zero_eval.\n  - change (S n + d) with (S (n + d)) in ty.\n    unfold downgrade, UValFE.\n    cbn.\n    unfold UValFE in ty.\n    cbn in ty.\n    assert (ValidTy (unfoldn (LMC τ) τ)) by eauto using ValidTy_unfoldn.\n    assert (LMC (unfoldn (LMC τ) τ) = 0) by (eapply unfoldn_LMC; crushValidTy).\n    destruct (unfoldn (LMC τ) τ).\n    + destruct (canonUValS_Arr vv ty) as [(? & ? & ? & ?) | ?].\n      * pose proof (F.can_form_tarr H1 H3).\n        exists (F.inl (F.abs (UValFE n t1) (F.app (downgrade n d t2)\n                                             (F.app x\n                                                    (F.app (upgrade n d t1)\n                                                           (* x))))). *)\n                                                           (F.var 0)))))).\n        eapply ValidTy_invert_arr in H.\n        destruct H as (? & ?).\n        repeat split.\n        replace x with x [wk] by (eapply wsClosed_invariant;\n                                  refine (F.wt_implies_ws H3)).\n        eauto using downgrade_T, upgrade_T with typing ws.\n        cbn.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_beta _) I); eauto.\n        subst; cbn; crush; rewrite downgrade_sub, upgrade_sub;\n          try assumption.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_case_inl _) I); eauto.\n        subst; cbn; crush; rewrite downgrade_sub, upgrade_sub;\n          try assumption.\n        change ((beta1 x)↑ (wk 0)) with x [wk].\n        replace x[wk] with x; [econstructor|].\n        eapply eq_sym, wsClosed_invariant.\n        refine (F.wt_implies_ws H3).\n        (* eauto using inArr_Value, downgrade_eval_inArr, inArr_T,  *)\n        (* downgrade_T, upgrade_T with typing. *)\n      * exists (unkUVal (S n)).\n        eapply ValidTy_invert_arr in H.\n        destruct H as (? & ?).\n        repeat split.\n        exact (unkUValT (τ := t1 r⇒ t2)).\n        cbn.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_beta _) I); eauto.\n        subst; cbn; crush; rewrite downgrade_sub, upgrade_sub;\n        try assumption.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_case_inr _) I); eauto.\n        crush.\n    + destruct (canonUValS_Unit (n := n + d) vv ty) as [? | ?].\n      * exists v.\n        repeat split.\n        assumption.\n        subst.\n        eauto with typing ws.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_beta _) I); eauto.\n        crush.\n      * exists (unkUVal (S n)).\n        repeat split.\n        exact (unkUValT (τ := E.tunit)).\n        cbn.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_beta _) I); eauto.\n        subst; crush.\n    + destruct (canonUValS_Bool (n := n + d) vv ty) as [? | [?|?]]; destruct_conjs; subst.\n      * exists (F.inl F.true); crush.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_beta _) I); now cbn.\n        crush.\n      * exists (F.inl F.false); crush.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_beta _) I); now cbn.\n        crush.\n      * exists (F.inr F.unit); crush.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_beta _) I); now cbn.\n        crush.\n    + destruct (canonUValS_Prod vv ty) as [?| ?]; destruct_conjs; subst.\n      eapply ValidTy_invert_prod in H.\n      destruct H as (? & ?).\n      stlcCanForm.\n      destruct vv as (vx & vx0).\n      destruct (IHn x t1 H H6 vx) as (v1 & vv1 & tv1 & es1).\n      destruct (IHn x0 t2 H3 H7 vx0) as (v2 & vv2 & tv2 & es2).\n      * exists (inl (pair v1 v2)); crush.\n        eapply downgrade_eval_inProd; eauto.\n      * exists (F.inr F.unit); crush.\n      * exists (F.inr F.unit); crush.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_beta _) I); now cbn.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_case_inr _) I); now cbn.\n        crush.\n    + eapply ValidTy_invert_sum in H.\n      destruct H as (? & ?).\n      destruct (canonUValS_Sum vv ty) as [(? & ? & ? & ?) | ?].\n      * pose proof (F.can_form_tsum H2 H4) as [(? & ? & ?) | (? & ? & ?)];\n        assert (F.Value x0) by (subst; trivial);\n        [destruct (IHn _ _ H H6) as (vf & vvf & tyf & ex)\n        |destruct (IHn _ _ H1 H6) as (vf & vvf & tyf & ex)];\n        try assumption;\n        [exists (F.inl (F.inl vf)) | exists (F.inl (F.inr vf))];\n        repeat split;\n        try (simpl; trivial; fail);\n        try (eauto using tyf with typing ws);\n        subst;\n        cbn;\n        eapply evalStepStar;\n        try refine (eval_ctx₀ phole (eval_beta _) I); eauto;\n        subst; cbn; crush; rewrite ?downgrade_sub; crushValidTy;\n        eapply evalStepStar;\n        try refine (eval_ctx₀ phole (eval_case_inl _) I); eauto;\n        subst; cbn; crush; rewrite ?downgrade_sub; crushValidTy;\n        eapply evalStepStar;\n        [refine (eval_ctx₀ (pinl phole) (eval_case_inl _) I); eauto | idtac\n        |refine (eval_ctx₀ (pinl phole) (eval_case_inr _) I); eauto | idtac];\n        subst; cbn; crush; rewrite ?downgrade_sub; crushValidTy;\n        [change (F.inl (F.inl ?t)) with (pctx_app t (pinl (pinl phole)))\n        |change (F.inl (F.inr ?t)) with (pctx_app t (pinl (pinr phole)))];\n        apply evalstar_ctx;\n        cbn;\n        trivial.\n      * exists (unkUVal (S n)).\n        repeat split.\n        exact (unkUValT (τ := t1 r⊎ t2)).\n        cbn.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_beta _) I); eauto.\n        subst; cbn; crush; rewrite downgrade_sub; crushValidTy.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_case_inr _) I); eauto.\n        crush.\n    + exfalso. cbn in *. lia.\n    + exfalso. destruct H.\n      inversion H.\n      inversion H3.\nQed.\n\nLemma upgrade_reduces {n v τ } d :\n  ValidTy τ ->\n  ⟪ F.empty ⊢ v : UValFE n τ ⟫ → Value v →\n  exists v', Value v' ∧ ⟪ F.empty ⊢ v' : UValFE (n + d) τ ⟫ ∧\n             app (upgrade n d τ) v -->* v'.\nProof.\n  revert τ;\n  revert v; induction n;\n  intros v τ vτ ty vv.\n  - exists (unkUVal d).\n    eauto using unkUVal_Value, unkUValT, upgrade_zero_eval.\n  - change (S n + d) with (S (n + d)).\n    unfold downgrade, UValFE.\n    cbn.\n    unfold UValFE in ty.\n    cbn in ty.\n    assert (vτ' : ValidTy (unfoldn (LMC τ) τ)) by eauto using ValidTy_unfoldn.\n    assert (lτz : LMC (unfoldn (LMC τ) τ) = 0) by (eapply unfoldn_LMC; crushValidTy).\n    destruct (unfoldn (LMC τ) τ).\n    + eapply ValidTy_invert_arr in vτ'.\n      destruct vτ' as (vt1 & vt2).\n      destruct (canonUValS_Arr vv ty) as [(? & ? & ? & ?) | ?].\n      * pose proof (F.can_form_tarr H H1).\n        exists (F.inl (F.abs (UValFE (n + d) t1) (F.app (upgrade n d t2)\n                                             (F.app x\n                                                    (F.app (downgrade n d t1)\n                                                           (* x))))). *)\n                                                           (F.var 0)))))).\n        repeat split.\n        replace x with x [wk] by (eapply wsClosed_invariant;\n                                  refine (F.wt_implies_ws H1)).\n\n        eauto using downgrade_T, upgrade_T with typing ws.\n        cbn.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_beta _) I); eauto.\n        subst; cbn; crush; rewrite downgrade_sub, upgrade_sub; eauto.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_case_inl _) I); eauto.\n        cbn; crush; rewrite downgrade_sub, upgrade_sub; eauto.\n        change ((beta1 x)↑ (wk 0)) with x [wk].\n        replace x[wk] with x; [econstructor|].\n        eapply eq_sym, wsClosed_invariant.\n        refine (F.wt_implies_ws H1).\n        (* eauto using inArr_Value, downgrade_eval_inArr, inArr_T,  *)\n        (* downgrade_T, upgrade_T with typing. *)\n      * exists (unkUVal (S (n + d))).\n        repeat split.\n        exact (unkUValT (τ := t1 r⇒ t2)).\n        cbn.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_beta _) I); eauto.\n        subst; cbn; crush; rewrite downgrade_sub, upgrade_sub; eauto.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_case_inr _) I); eauto.\n        crush.\n    + destruct (canonUValS_Unit (n := n) vv ty) as [? | ?].\n      * exists v.\n        repeat split.\n        assumption.\n        rewrite H.\n        eauto with typing ws.\n        cbn.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_beta _) I); eauto.\n        crush.\n      * exists (unkUVal (S (n + d))).\n        repeat split.\n        exact (unkUValT (τ := E.tunit)).\n        cbn.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_beta _) I); eauto.\n        subst; crush.\n    + destruct (canonUValS_Bool (n := n) vv ty) as [? | [?|?]]; destruct_conjs; subst.\n      * exists (F.inl F.true); crush.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_beta _) I); now cbn.\n        crush.\n      * exists (F.inl F.false); crush.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_beta _) I); now cbn.\n        crush.\n      * exists (F.inr F.unit); crush.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_beta _) I); now cbn.\n        crush.\n    + eapply ValidTy_invert_prod in vτ'.\n      destruct vτ' as (vt1 & vt2).\n      destruct (canonUValS_Prod vv ty) as [?| ?]; destruct_conjs; subst.\n      stlcCanForm.\n      destruct vv as (vx & vx0).\n      destruct (IHn x t1 vt1 H3 vx) as (v1 & vv1 & tv1 & es1).\n      destruct (IHn x0 t2 vt2 H4 vx0) as (v2 & vv2 & tv2 & es2).\n      * exists (inl (pair v1 v2)); crush.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_beta _) I); now cbn.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_case_inl _) I); now cbn.\n        cbn.\n        crush.\n        rewrite ?upgrade_sub; eauto.\n        eapply evalStepStar.\n        refine (eval_ctx₀ (pinl (ppair₁ (papp₂ _ phole) _)) (eval_proj₁ _ _) _); cbn; eauto using upgrade_value.\n        cbn.\n        eapply evalStepTrans.\n        eapply (evalstar_ctx' es1); F.inferContext; now cbn.\n        eapply evalStepStar.\n        refine (eval_ctx₀ (pinl (ppair₂ _ (papp₂ _ phole))) (eval_proj₂ _ _) _); cbn; eauto using upgrade_value.\n        cbn.\n        eapply (evalstar_ctx' es2); F.inferContext; now cbn.\n      * exists (F.inr F.unit); crush.\n      * exists (F.inr F.unit); crush.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_beta _) I); now cbn.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_case_inr _) I); now cbn.\n        crush.\n    + eapply ValidTy_invert_sum in vτ'.\n      destruct vτ' as (vt1 & vt2).\n      destruct (canonUValS_Sum vv ty) as [(? & ? & ? & ?) | ?].\n      * pose proof (F.can_form_tsum H H1) as [(? & ? & ?) | (? & ? & ?)];\n        assert (F.Value x0) by (rewrite H2 in H; trivial);\n          [destruct (IHn _ _ vt1 H3 H4) as (vf & vvf & tyf & ex)\n          |destruct (IHn _ _ vt2 H3 H4) as (vf & vvf & tyf & ex)];\n        [exists (F.inl (F.inl vf)) | exists (F.inl (F.inr vf))];\n        repeat split;\n        try (simpl; trivial; fail);\n        try (eauto using tyf with typing ws);\n        subst;\n        cbn;\n        eapply evalStepStar;\n        try refine (eval_ctx₀ phole (eval_beta _) I); eauto;\n        subst; cbn; crush; rewrite ?upgrade_sub; eauto;\n        eapply evalStepStar;\n        try refine (eval_ctx₀ phole (eval_case_inl _) I); eauto;\n        subst; cbn; crush; rewrite ?upgrade_sub; eauto;\n        eapply evalStepStar;\n        [refine (eval_ctx₀ (pinl phole) (eval_case_inl _) I); eauto | idtac\n        |refine (eval_ctx₀ (pinl phole) (eval_case_inr _) I); eauto | idtac];\n        subst; cbn; crush; rewrite ?upgrade_sub; eauto;\n        [change (F.inl (F.inl ?t)) with (pctx_app t (pinl (pinl phole)))\n        |change (F.inl (F.inr ?t)) with (pctx_app t (pinl (pinr phole)))];\n        apply evalstar_ctx;\n        cbn;\n        trivial.\n      * exists (unkUVal (S (n + d))).\n        repeat split.\n        exact (unkUValT (τ := t1 r⊎ t2)).\n        cbn.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_beta _) I); eauto.\n        subst; cbn; crush; rewrite upgrade_sub; eauto.\n        eapply evalStepStar.\n        refine (eval_ctx₀ phole (eval_case_inr _) I); eauto.\n        crush.\n    + cbn in lτz.\n      exfalso; lia.\n    + inversion vτ'.\n      inversion H.\n      inversion H2.\nQed.\n\nDefinition dir_world_prec (n : nat) (w : World) (d : Direction) (p : Prec) : Prop :=\n  (lev w < n ∧ p = precise) ∨ (d = dir_lt ∧ p = imprecise).\n\nArguments dir_world_prec n w d p : simpl never.\n\nLemma dwp_zero {w d p} : dir_world_prec 0 w d p → p = imprecise ∧ d = dir_lt.\nProof.\n  destruct 1 as [[? ?]|[? ?]].\n  - depind H.\n  - auto.\nQed.\n\nLemma dwp_precise {n d w} : lev w < n → dir_world_prec n w d precise.\nProof.\n  left; auto.\nQed.\n\nLemma dwp_imprecise {n w} : dir_world_prec n w dir_lt imprecise.\nProof.\n  right; auto.\nQed.\n\nLemma dwp_invert_imprecise {n w d} : dir_world_prec n w d imprecise → d = dir_lt.\nProof.\n  destruct 1 as [[? ?]|[? ?]].\n  - inversion H0.\n  - auto.\nQed.\n\nLemma dwp_invert_gt {n w p} : dir_world_prec n w dir_gt p → p = precise /\\ lev w < n.\nProof.\n  destruct 1 as [[? ?]|[eq ?]]; [auto|inversion eq].\nQed.\n\nLemma dwp_invert_S {w d p n} : dir_world_prec (S n) (S w) d p → dir_world_prec n w d p.\nProof.\n  destruct 1 as [[? ?]|[? ?]]; [left|right];\n  eauto with arith.\nQed.\n\nLemma dwp_invert_S' {w d p n} : \n  dir_world_prec (S n) w d p → \n  forall w', w' < w → dir_world_prec n w' d p.\nProof.\n  destruct 1 as [[? ?]|[? ?]]; [left|right];\n  eauto with arith.\nQed.\n\nLemma dwp_mono {w d p n} :\n  dir_world_prec n w d p →\n  forall w', w' ≤ w → dir_world_prec n w' d p.\nProof.\n  destruct 1 as [[? ?]|[? ?]]; [left|right];\n  eauto with arith.\nQed.\n\nLemma downgrade_inProd_works {n d w dir p vs vu τ τ'} :\n  ValidTy τ -> ValidTy τ' ->\n  valrel dir w (pEmulDV (S (n + d)) p (E.tprod τ τ')) (F.inl vs) vu →\n  (forall w' vs₁ vu₁ τ, w' < w →\n                   ValidTy τ ->\n              valrel dir w' (pEmulDV (n + d) p τ) vs₁ vu₁ →\n              ∃ vs₁', app (downgrade n d τ) vs₁ -->* vs₁' ∧\n                      valrel dir w' (pEmulDV n p τ) vs₁' vu₁) →\n  exists v',\n    app (downgrade (S n) d (E.tprod τ τ')) (F.inl vs) -->* v' ∧\n    valrel dir w (pEmulDV (S n) p (E.tprod τ τ')) v' vu.\nProof.\n  intros vτ vτ' vr ih.\n  pose proof (valrel_implies_OfType vr) as ot''.\n  destruct (valrel_implies_OfType vr) as [[vvs tvs] [vvu tvu]].\n  destruct (invert_valrel_pEmulDV_inProd' vτ vτ' vr) as (vs1 & vs2 & vu1 & vu2 & -> & -> & vr1 & vr2).\n  destruct w.\n  + (* w = 0 *)\n    destruct (canonUValS_Prod vvs tvs) as [(? & ? & ? & ?) | ?]; [| inversion H].\n    F.stlcCanForm. inversion H0; subst.\n    destruct H as (vx2 & vx3).\n    destruct (downgrade_reduces vτ H3 vx2) as (x4 & vx4 & tyx4 & esx4).\n    destruct (downgrade_reduces vτ' H4 vx3) as (x5 & vx5 & tyx5 & esx5).\n    exists (inl (pair x4 x5)); split; E.crushTyping.\n    * eapply downgrade_eval_inProd; eauto.\n    * subst.\n      assert (ValidEnv E.empty) by eauto with tyvalid.\n      apply valrel_inProd''; eauto;\n        apply valrel_0_pair; eauto.\n      crushOfType; E.crushTyping; eauto using typed_terms_are_valid.\n      crushOfType; E.crushTyping; eauto; eauto using typed_terms_are_valid.\n  + (* w = S w *)\n    (* destruct vr as (? & [([=] & _)|(? & -> & vr')]). *)\n    (* unfold prod_rel in vr'; cbn in vr'. *)\n    (* destruct x; cbn in vr'; try contradiction. *)\n    assert (wlt : w < S w) by eauto with arith.\n    specialize (vr1 w wlt).\n    specialize (vr2 w wlt).\n    cbn in *.\n    destruct (ih w _ _ _ wlt vτ vr1) as (vs1' & es1 & vr1').\n    destruct (ih w _ _ _ wlt vτ' vr2) as (vs2' & es2 & vr2').\n    destruct vvs as (vvs1 & vvs2).\n    destruct (valrel_implies_Value vr1').\n    destruct (valrel_implies_Value vr2').\n    exists (F.inl (F.pair vs1' vs2'));\n    split.\n    * apply (downgrade_eval_inProd vτ vτ' vvs1 vvs2); eauto.\n    * eapply (valrel_inProd'); assumption.\nQed.\n\nLemma upgrade_inProd_works {n d w dir p vs vu τ τ'} :\n  ValidTy τ -> ValidTy τ' ->\n  valrel dir w (pEmulDV (S n) p (E.tprod τ τ')) (F.inl vs) vu →\n  (forall w' vs₁ vu₁ τ, w' < w →\n                   ValidTy τ ->\n              valrel dir w' (pEmulDV n p τ) vs₁ vu₁ →\n              (* valrel dir w' (pEmulDV (n + d) p τ') vs₁ vu₁) → *)\n              (* ∃ vs₁', app (downgrade n d (E.tprod τ τ')) vs₁ -->* vs₁' ∧ *)\n              ∃ vs₁', app (upgrade n d τ) vs₁ -->* vs₁' ∧\n                      valrel dir w' (pEmulDV (n + d) p τ) vs₁' vu₁) →\n                      (* valrel dir w' (pEmulDV n p (E.tprod τ τ')) vs₁' vu₁) → *)\n  exists v',\n    app (upgrade (S n) d (E.tprod τ τ')) (F.inl vs) -->* v' ∧\n    valrel dir w (pEmulDV (S (n + d)) p (E.tprod τ τ')) v' vu.\nProof.\n  intros vτ vτ' vr ih.\n  pose proof (valrel_implies_OfType vr) as ot''.\n  destruct (valrel_implies_OfType vr) as [[vvs tvs] [vvu tvu]].\n  destruct (invert_valrel_pEmulDV_inProd' vτ vτ' vr) as (vs1 & vs2 & vu1 & vu2 & -> & -> & vr1 & vr2).\n  destruct w.\n  + (* w = 0 *)\n    destruct (canonUValS_Prod vvs tvs) as [(? & ? & ? & ?) | ?]; [| inversion H].\n    F.stlcCanForm. inversion H0; subst.\n    destruct H as (vx2 & vx3).\n    destruct (upgrade_reduces d vτ H3 vx2) as (x4 & vx4 & tyx4 & esx4).\n    destruct (upgrade_reduces d vτ' H4 vx3) as (x5 & vx5 & tyx5 & esx5).\n    exists (inl (pair x4 x5)); split; E.crushTyping.\n    * eapply upgrade_eval_inProd; eauto.\n    * subst.\n      assert (ValidEnv E.empty) by eauto with tyvalid.\n      apply valrel_inProd''; eauto;\n        apply valrel_0_pair; eauto.\n      crushOfType; E.crushTyping; eauto using typed_terms_are_valid.\n      crushOfType; E.crushTyping; eauto; eauto using typed_terms_are_valid.\n  + assert (wlt : w < S w) by eauto with arith.\n    specialize (vr1 w wlt).\n    specialize (vr2 w wlt).\n    cbn in *.\n    destruct (ih w _ _ _ wlt vτ vr1) as (vs1' & es1 & vr1').\n    destruct (ih w _ _ _ wlt vτ' vr2) as (vs2' & es2 & vr2').\n    destruct vvs as (vvs1 & vvs2).\n    destruct (valrel_implies_Value vr1').\n    destruct (valrel_implies_Value vr2').\n    exists (F.inl (F.pair vs1' vs2'));\n    split.\n    * apply (upgrade_eval_inProd vτ vτ' vvs1 vvs2); eauto.\n    * eapply (valrel_inProd'); assumption.\nQed.\n\nLemma downgrade_inSum_works {n d w dir p vs vu τ τ'} :\n  ValidTy τ -> ValidTy τ' ->\n  valrel dir w (pEmulDV (S (n + d)) p (E.tsum τ τ')) (F.inl vs) vu →\n  (forall w' vs₁ vu₁ τ, w' < w →\n                   ValidTy τ ->\n              valrel dir w' (pEmulDV (n + d) p τ) vs₁ vu₁ →\n              (* valrel dir w' (pEmulDV (n + d) p τ') vs₁ vu₁) → *)\n              (* ∃ vs₁', app (downgrade n d (E.tsum τ τ')) vs₁ -->* vs₁' ∧ *)\n              ∃ vs₁', app (downgrade n d τ) vs₁ -->* vs₁' ∧\n                      valrel dir w' (pEmulDV n p τ) vs₁' vu₁) →\n                      (* valrel dir w' (pEmulDV n p (E.tsum τ τ')) vs₁' vu₁) → *)\n  exists v',\n    app (downgrade (S n) d (E.tsum τ τ')) (F.inl vs) -->* v' ∧\n    valrel dir w (pEmulDV (S n) p (E.tsum τ τ')) v' vu.\nProof.\n  intros vτ vτ' vr ih.\n  pose proof (valrel_implies_OfType vr) as ot''.\n  destruct (valrel_implies_OfType vr) as [[? ?] [? ?]].\n  destruct (invert_valrel_pEmulDV_inSum'' vr) as (vs' & vu' & ?); subst.\n  simpl in H0, H2.\n  destruct w.\n  + (* w = 0 *)\n    destruct (canonUValS_Sum H H0) as [(? & ? & ? & ?) | ?]; [| inversion H4].\n    F.stlcCanForm; inversion H5; subst;\n  [destruct (downgrade_reduces vτ H8 H4) as (vs'' & vvs'' & ty' & es')\n  |destruct (downgrade_reduces vτ' H8 H4) as (vs'' & vvs'' & ty' & es')];\n    destruct H3 as [(? & ? & ?) | (? & ? & ?)]; try (inversion H3; fail); inversion H3; subst;\n    assert (ValidEnv E.empty) by (eauto with tyvalid).\n    * exists ((F.inl (F.inl vs''))).\n      assert (forall w', w' < 0 → valrel dir w' (pEmulDV n p τ) vs'' vu') by lia.\n      split; [apply (downgrade_eval_inSum vτ vτ' H4 vvs''); crush|].\n      crush.\n      E.crushTyping;\n      eauto using typed_terms_are_valid;\n      now destruct (ValidTy_invert_sum H10).\n      right. eexists. split; [reflexivity|].\n      unfold vrsum, sum_rel, latervr.\n       crush.\n    * exists ((F.inl (F.inr vs''))).\n      assert (forall w', w' < 0 → valrel dir w' (pEmulDV n p τ') vs'' vu') by lia.\n      split; [apply (downgrade_eval_inSum vτ vτ' H4 vvs''); crush|].\n      crush.\n      E.crushTyping;\n      eauto using typed_terms_are_valid;\n      now destruct (ValidTy_invert_sum H10).\n      right. eexists. split; [reflexivity|].\n      unfold vrsum, sum_rel, latervr.\n      crush.\n  + (* w = S w *)\n    assert (wlt : w < S w) by eauto with arith.\n    destruct H3 as [(? & ? & vr') | (? & ? & vr')]; try (inversion H3; fail); subst;\n    specialize (vr' w wlt);\n    cbn in H;\n    assert (ValidEnv E.empty) by eauto with tyvalid.\n    * destruct (ih w _ _ _ wlt vτ vr') as (vs'' & es' & vr'').\n      destruct (valrel_implies_Value vr'').\n      exists (F.inl (F.inl vs'')).\n      split.\n      apply (downgrade_eval_inSum vτ vτ' H H4); eauto.\n      assert (vτs := typed_terms_are_valid _ _ H3 H2).\n      destruct (ValidTy_invert_sum vτs).\n      eapply valrel_inSum'; try assumption.\n      left; crush.\n    * destruct (ih w _ _ _ wlt vτ' vr') as (vs'' & es' & vr'').\n      destruct (valrel_implies_Value vr'').\n      exists (F.inl (F.inr vs'')).\n      split.\n      apply (downgrade_eval_inSum vτ vτ' H H4); eauto.\n      assert (vτs := typed_terms_are_valid _ _ H3 H2).\n      destruct (ValidTy_invert_sum vτs).\n      eapply valrel_inSum'; try assumption.\n      right; crush.\nQed.\n\nLemma upgrade_inSum_works {n d w dir p vs vu τ τ'} :\n  ValidTy τ -> ValidTy τ' ->\n  valrel dir w (pEmulDV (S n) p (E.tsum τ τ')) (F.inl vs) vu →\n  (forall w' vs₁ vu₁ τ, w' < w →\n                   ValidTy τ ->\n              valrel dir w' (pEmulDV n p τ) vs₁ vu₁ →\n              (* valrel dir w' (pEmulDV (n + d) p τ') vs₁ vu₁) → *)\n              (* ∃ vs₁', app (downgrade n d (E.tsum τ τ')) vs₁ -->* vs₁' ∧ *)\n              ∃ vs₁', app (upgrade n d τ) vs₁ -->* vs₁' ∧\n                      valrel dir w' (pEmulDV (n + d) p τ) vs₁' vu₁) →\n                      (* valrel dir w' (pEmulDV n p (E.tsum τ τ')) vs₁' vu₁) → *)\n  exists v',\n    app (upgrade (S n) d (E.tsum τ τ')) (F.inl vs) -->* v' ∧\n    valrel dir w (pEmulDV (S (n + d)) p (E.tsum τ τ')) v' vu.\nProof.\n  intros vτ vτ' vr ih.\n  pose proof (valrel_implies_OfType vr) as ot''.\n  destruct (valrel_implies_OfType vr) as [[? ?] [? ?]].\n  destruct (invert_valrel_pEmulDV_inSum'' vr) as (vs' & vu' & ?); subst.\n  simpl in H0, H2.\n  destruct w.\n  + (* w = 0 *)\n    destruct (canonUValS_Sum H H0) as [(? & ? & ? & ?) | ?]; [| inversion H4].\n    F.stlcCanForm; inversion H5; subst;\n    [destruct (upgrade_reduces d vτ H8 H4) as (vs'' & vvs'' & ty' & es')\n    | destruct (upgrade_reduces d vτ' H8 H4) as (vs'' & vvs'' & ty' & es')\n    ];\n    destruct H3 as [(? & ? & ?) | (? & ? & ?)]; try (inversion H3; fail); inversion H3; subst;\n    [exists ((F.inl (F.inl vs''))) | exists ((F.inl (F.inr vs'')))];\n    [assert (forall w', w' < 0 → valrel dir w' (pEmulDV n p τ) vs'' vu') by lia\n    |assert (forall w', w' < 0 → valrel dir w' (pEmulDV n p τ') vs'' vu') by lia];\n    (split; [apply (upgrade_eval_inSum vτ vτ' H4 vvs''); crush|]);\n    assert (ValidEnv E.empty) by eauto with tyvalid;\n    assert (vτs := typed_terms_are_valid _ _ H9 H2);\n    destruct (ValidTy_invert_sum vτs);\n    apply valrel_inSum''; try assumption.\n    * apply valrel_0_inl; try now cbn.\n      cbn in *.\n      assert (ValidEnv E.empty) by eauto with tyvalid.\n      crushOfType; E.crushTyping; eauto using typed_terms_are_valid.\n    * apply valrel_0_inr; try now cbn.\n      cbn in *.\n      assert (ValidEnv E.empty) by eauto with tyvalid.\n      crushOfType; E.crushTyping; eauto using typed_terms_are_valid.\n  + (* w = S w *)\n    assert (wlt : w < S w) by eauto with arith;\n    destruct H3 as [(? & ? & vr') | (? & ? & vr')]; try (inversion H3; fail); subst;\n    specialize (vr' w wlt);\n    cbn in H.\n    assert (ValidEnv E.empty) by eauto with tyvalid;\n    assert (vτs := typed_terms_are_valid _ _ H3 H2);\n    destruct (ValidTy_invert_sum vτs).\n    * destruct (ih w _ _ _ wlt vτ vr') as (vs'' & es' & vr'').\n      destruct (valrel_implies_Value vr'').\n      exists (F.inl (F.inl vs'')).\n      split.\n      apply (upgrade_eval_inSum vτ vτ' H H6); eauto.\n      eapply valrel_inSum'; try assumption.\n      left; eauto.\n    * destruct (ih w _ _ _ wlt vτ' vr') as (vs'' & es' & vr'').\n      destruct (valrel_implies_Value vr'').\n      exists (F.inl (F.inr vs'')).\n      split.\n      apply (upgrade_eval_inSum vτ vτ' H H3); eauto.\n      eapply valrel_inSum'; try assumption.\n      right; eauto.\nQed.\n\n\n(* Lemma downgrade_inRec_works {n d w dir p vs vu τ} : *)\n(*   ValidTy (E.trec τ) -> *)\n(*   valrel dir w (pEmulDV (S (n + d)) p (E.trec τ)) (F.inl vs) vu → *)\n(*   (forall w' vs₁ vu₁ τ, w' < w → *)\n(*                    ValidTy τ -> *)\n(*               valrel dir w' (pEmulDV (n + d) p τ) vs₁ vu₁ → *)\n(*               ∃ vs₁', app (downgrade n d τ) vs₁ -->* vs₁' ∧ *)\n(*                       valrel dir w' (pEmulDV n p τ) vs₁' vu₁) → *)\n(*   exists v', *)\n(*     app (downgrade (S n) d (E.trec τ)) (F.inl vs) -->* v' ∧ *)\n(*     valrel dir w (pEmulDV (S n) p (E.trec τ)) v' vu. *)\n(* Proof. *)\n(*   intros vτ vr ih. *)\n(*   destruct (valrel_implies_OfType vr) as [[? ?] [? ?]]. *)\n(*   simpl in H0, H2. *)\n(*   destruct w. *)\n(*   + (* w = 0 *) *)\n(*     destruct (canonUValS_Rec H H0) as [(? & ? & ? & ?) | ?]; [| inversion H3]. *)\n(*     inversion H4; subst. *)\n(*     destruct (downgrade_reduces H5 H3) as (vs'' & vvs'' & ty' & es'). *)\n(*     assert (forall w', w' < 0 → valrel dir w' (pEmulDV n p τ) vs'' vu) by lia. *)\n(*     exists (F.inl vs''). *)\n(*     split. *)\n(*     exact (downgrade_eval_inRec H3 vvs'' es'). *)\n(*     apply valrel_0_inRec. *)\n(*     crush. *)\n(*   + (* w = S w *) *)\n(*     pose proof (invert_valrel_pEmulDV_inRec vr). *)\n(*     assert (wlt : w < S w) by eauto with arith. *)\n(*     assert (vτ' : ValidTy (τ[beta1 (E.trec τ)])) by now eapply ValidTy_unfold_trec. *)\n(*     destruct (ih _ _ _ _ wlt vτ' H3) as (? & ? & ?). *)\n(*     exists (F.inl x). *)\n(*     split. *)\n(*     destruct (valrel_implies_OfType H5) as [[? _] _]. *)\n(*     apply downgrade_eval_inRec; crush. *)\n(*     now apply valrel_inRec. *)\n(* Qed. *)\n\n(* Lemma upgrade_inRec_works {n d w dir p vs vu τ} : *)\n(*   ValidTy (E.trec τ) -> *)\n(*   valrel dir w (pEmulDV (S n) p (E.trec τ)) (F.inl vs) vu → *)\n(*   (forall w' vs₁ vu₁ τ, w' < w → *)\n(*                    ValidTy τ -> *)\n(*               valrel dir w' (pEmulDV n p τ) vs₁ vu₁ → *)\n(*               ∃ vs₁', app (upgrade n d τ) vs₁ -->* vs₁' ∧ *)\n(*                       valrel dir w' (pEmulDV (n + d) p τ) vs₁' vu₁) → *)\n(*   exists v', *)\n(*     app (upgrade (S n) d (E.trec τ)) (F.inl vs) -->* v' ∧ *)\n(*     valrel dir w (pEmulDV (S (n + d)) p (E.trec τ)) v' vu. *)\n(* Proof. *)\n(*   intros vτ vr ih. *)\n(*   destruct (valrel_implies_OfType vr) as [[? ?] [? ?]]. *)\n(*   simpl in H0, H2. *)\n(*   destruct w. *)\n(*   + (* w = 0 *) *)\n(*     destruct (canonUValS_Rec H H0) as [(? & ? & ? & ?) | ?]; [| inversion H3]. *)\n(*     inversion H4; subst. *)\n(*     destruct (upgrade_reduces d H5 H3) as (vs'' & vvs'' & ty' & es'). *)\n(*     assert (forall w', w' < 0 → valrel dir w' (pEmulDV n p τ) vs'' vu) by lia. *)\n(*     exists (F.inl vs''). *)\n(*     split. *)\n(*     exact (upgrade_eval_inRec H3 vvs'' es'). *)\n(*     apply valrel_0_inRec. *)\n(*     crush. *)\n(*   + (* w = S w *) *)\n(*     pose proof (invert_valrel_pEmulDV_inRec vr). *)\n(*     assert (wlt : w < S w) by eauto with arith. *)\n(*     assert (vτ' : ValidTy (τ[beta1 (E.trec τ)])) by now eapply ValidTy_unfold_trec. *)\n(*     destruct (ih _ _ _ _ wlt vτ' H3) as (? & ? & ?). *)\n(*     exists (F.inl x). *)\n(*     split. *)\n(*     destruct (valrel_implies_OfType H5) as [[? _] _]. *)\n(*     apply upgrade_eval_inRec; crush. *)\n(*     now apply valrel_inRec. *)\n(* Qed. *)\n\nLemma downgrade_inArr_works {n d w dir p vs vu τ τ'} :\n  ValidTy τ -> ValidTy τ' ->\n  valrel dir w (pEmulDV (S (n + d)) p (E.tarr τ τ')) (F.inl vs) vu →\n  (forall w' vs₁ vu₁ τ, w' < w →\n                   ValidTy τ ->\n              valrel dir w' (pEmulDV (n + d) p τ) vs₁ vu₁ →\n              ∃ vs₁', app (downgrade n d τ) vs₁ -->* vs₁' ∧\n                      valrel dir w' (pEmulDV n p τ) vs₁' vu₁) →\n  (forall w' vs₁ vu₁ τ, w' < w →\n                   ValidTy τ ->\n              valrel dir w' (pEmulDV n p τ) vs₁ vu₁ →\n              ∃ vs₁', app (upgrade n d τ) vs₁ -->* vs₁' ∧\n                      valrel dir w' (pEmulDV (n + d) p τ) vs₁' vu₁) →\n  exists v',\n    app (downgrade (S n) d (E.tarr τ τ')) (F.inl vs) -->* v' ∧\n    valrel dir w (pEmulDV (S n) p (E.tarr τ τ')) v' vu.\nProof.\n  intros vτ vτ' vr ihd ihu.\n  destruct (valrel_implies_OfType vr) as [[vvs tyvs] [vvu tyvu]].\n  exists (F.inl (abs (UValFE n τ) (app (downgrade n d τ') (app (vs[wk]) (app (upgrade n d τ) (var 0)))))).\n  split.\n  - eapply downgrade_eval_inArr; crush; crushValidTy.\n  - eapply valrel_inArr; try assumption.\n    apply invert_valrel_pEmulDV_inArr in vr; try assumption.\n    simpl in vvs.\n    apply valrel_ptarr_inversion in vr;\n      cbn; try assumption; destruct_conjs; subst.\n    simpl in *.\n\n    (* unfold the valrel-ptarr *)\n    change (abs (UValFE n τ)) with (abs (repEmul (pEmulDV n p τ))).\n    (* change (E.abs τ) with (E.abs (fxToIs (pEmulDV n p τ))). *)\n    apply valrel_lambda; cbn; try assumption.\n    crushOfType; crushTyping; E.crushTyping;\n    eauto using downgrade_T, upgrade_T; crushValidTy.\n    crush.\n    rewrite -> ?upgrade_sub, ?downgrade_sub; crushValidTy.\n\n    rewrite <- ap_liftSub; rewrite <- up_liftSub;\n    rewrite -> liftSub_wkm; rewrite (apply_wkm_beta1_up_cancel vr vs).\n\n    (* first execute the upgrade *)\n    specialize (ihu w' _ _ _ H1 vτ H8).\n    destruct ihu as (vs' & eups & vr').\n    enough (termrel dir w' (pEmulDV n p τ')\n                    (app (downgrade n d τ') (app (abs (UValFE (n + d) τ) vr) vs')) (H [beta1 vu])) as tr'\n        by (refine (termrel_antired_star_left (evalstar_ctx' eups _ _ _) tr');\n            inferContext; crush; eauto using downgrade_value).\n\n    (* now beta-reduce *)\n    enough (termrel dir w' (pEmulDV n p τ')\n                    (app (downgrade n d τ') (vr[beta1 vs']))\n                    H[beta1 vu]) as tr'\n    by (refine (termrel_antired_star_left _ tr'); simpl; eauto with eval;\n        apply evalToStar;\n        destruct (valrel_implies_Value vr') as [? _];\n        assert (e₀ : app (abs (UValFE (n + d) τ) vr) vs' -->₀ vr[beta1 vs']) by (eauto with eval);\n        eapply (eval_from_eval₀ e₀); inferContext; crush; eauto using downgrade_value).\n\n    (* now execute the application *)\n    specialize (H7 w' _ _ H1 H2 vr').\n    eapply (termrel_ectx' H7); F.inferContext; E.inferContext; crush;\n    eauto using downgrade_value.\n\n    (* now execute the downgrade *)\n    assert (wlt0 : w'0 < w) by lia.\n    specialize (ihd w'0 _ _ _ wlt0 vτ' H9).\n    destruct ihd as (vs'' & edowns & vr'').\n    enough (termrel dir w'0 (pEmulDV n p τ')\n                    vs'' vu0) as tr'\n        by (refine (termrel_antired_star_left (evalstar_ctx' edowns _ _ _) tr');\n            inferContext; crush; eauto using downgrade_value).\n\n    (* conclude *)\n    now apply valrel_in_termrel.\nQed.\n\nLemma upgrade_inArr_works {n d w dir p vs vu τ τ'} :\n  ValidTy τ -> ValidTy τ' ->\n  valrel dir w (pEmulDV (S n) p (E.tarr τ τ')) (F.inl vs) vu →\n  (forall w' vs₁ vu₁ τ, w' < w →\n                   ValidTy τ ->\n              valrel dir w' (pEmulDV (n + d) p τ) vs₁ vu₁ →\n              ∃ vs₁', app (downgrade n d τ) vs₁ -->* vs₁' ∧\n                      valrel dir w' (pEmulDV n p τ) vs₁' vu₁) →\n  (forall w' vs₁ vu₁ τ, w' < w →\n                   ValidTy τ ->\n              valrel dir w' (pEmulDV n p τ) vs₁ vu₁ →\n              ∃ vs₁', app (upgrade n d τ) vs₁ -->* vs₁' ∧\n                      valrel dir w' (pEmulDV (n + d) p τ) vs₁' vu₁) →\n  exists v',\n    app (upgrade (S n) d (E.tarr τ τ')) (F.inl vs) -->* v' ∧\n    valrel dir w (pEmulDV (S (n + d)) p (E.tarr τ τ')) v' vu.\nProof.\n  intros vτ vτ' vr ihd ihu.\n  destruct (valrel_implies_OfType vr) as [[vvs tyvs] [vvu tyvu]].\n  exists (F.inl (abs (UValFE (n + d) τ) (app (upgrade n d τ') (app (vs[wk]) (app (downgrade n d τ) (var 0)))))).\n  split.\n  - eapply upgrade_eval_inArr; crush; crushValidTy.\n  - eapply valrel_inArr; try assumption.\n    apply invert_valrel_pEmulDV_inArr in vr.\n    simpl in vvs.\n    apply valrel_ptarr_inversion in vr;\n      cbn; try assumption; destruct_conjs; subst.\n    simpl in *.\n\n    (* unfold the valrel-ptarr *)\n    change (abs (UValFE (n + d) τ)) with (abs (repEmul (pEmulDV (n + d) p τ))).\n    apply valrel_lambda; cbn; try assumption.\n    crushOfType; crushTyping; E.crushTyping;\n    eauto using downgrade_T, upgrade_T.\n    crush.\n    rewrite -> ?upgrade_sub, ?downgrade_sub; crushValidTy.\n\n    rewrite <- ap_liftSub; rewrite <- up_liftSub;\n    rewrite -> liftSub_wkm; rewrite (apply_wkm_beta1_up_cancel vr vs).\n\n    (* first execute the upgrade *)\n    specialize (ihd w' _ _ _ H1 vτ H8).\n    destruct ihd as (vs' & edowns & vr').\n    enough (termrel dir w' (pEmulDV (n + d) p τ')\n                    (app (upgrade n d τ') (app (abs (UValFE n τ) vr) vs')) (H [beta1 vu])) as tr'\n        by (refine (termrel_antired_star_left (evalstar_ctx' edowns _ _ _) tr');\n            inferContext; crush; eauto using upgrade_value).\n\n    (* now beta-reduce *)\n    enough (termrel dir w' (pEmulDV (n + d) p τ')\n                    (app (upgrade n d τ') (vr[beta1 vs']))\n                    H[beta1 vu]) as tr'\n    by (refine (termrel_antired_star_left _ tr'); simpl; eauto with eval;\n        apply evalToStar;\n        destruct (valrel_implies_Value vr') as [? _];\n        assert (e₀ : app (abs (UValFE n τ) vr) vs' -->₀ vr[beta1 vs']) by (eauto with eval);\n        eapply (eval_from_eval₀ e₀); inferContext; crush; eauto using upgrade_value).\n\n    (* now execute the application *)\n    specialize (H7 w' _ _ H1 H2 vr').\n    eapply (termrel_ectx' H7); F.inferContext; E.inferContext; crush;\n    eauto using upgrade_value.\n\n    (* now execute the downgrade *)\n    assert (wlt0 : w'0 < w) by lia.\n    specialize (ihu w'0 _ _ _ wlt0 vτ' H9).\n    destruct ihu as (vs'' & eups & vr'').\n    enough (termrel dir w'0 (pEmulDV (n + d) p τ')\n                    vs'' vu0) as tr'\n        by (refine (termrel_antired_star_left (evalstar_ctx' eups _ _ _) tr');\n            inferContext; crush; eauto using upgrade_value).\n\n    (* conclude *)\n    now apply valrel_in_termrel.\nQed.\n\nLemma downgrade_zero_works {d v vu dir w p τ} :\n  dir_world_prec 0 w dir p →\n  valrel dir w (pEmulDV d p τ) v vu →\n  exists v',\n    app (downgrade 0 d τ) v -->* v' ∧\n    valrel dir w (pEmulDV 0 p τ) v' vu.\nProof.\n  intros dwp vr;\n  destruct (valrel_implies_OfType vr) as [[vv tyv] [vvu tyvu]];\n  exists (unkUVal 0).\n  destruct (dwp_zero dwp).\n  crush.\n  eauto using downgrade_zero_eval.\nQed.\n\nLemma downgrade_inr_works {n d v vu dir w p τ} :\n  valrel dir w (pEmulDV (S (n + d)) p τ) (F.inr v) vu →\n  exists v',\n    app (downgrade (S n) d τ) (F.inr v) -->* v' ∧\n    valrel dir w (pEmulDV (S n) p τ) v' vu.\nProof.\n  intros vr.\n  destruct (valrel_implies_OfType vr) as [[? ?] [? ?]].\n  simpl in H0, H2.\n  assert (v = unit) by (\n  dependent destruction H0;\n  cbn in H;\n  apply (F.can_form_tunit H H0)).\n  subst.\n  exists (F.inr unit).\n  unfold downgrade.\n  destruct (unfoldn (LMC τ) τ);\n  (split; [\n  eapply evalStepStar;\n  try refine (eval_ctx₀ phole (eval_beta _) I); eauto;\n  subst; cbn; crush;\n  eapply evalStepStar;\n  try refine (eval_ctx₀ phole (eval_case_inr _) I); eauto;\n  crush|\n  assert (p = imprecise) by exact (invert_valrel_pEmulDV_unk vr);\n  refine (valrel_unk _ H3);\n  crush\n\n  ]).\nQed.\n\n\nLemma downgrade_S_works {n d v vu dir w p τ} :\n  ValidTy τ ->\n  dir_world_prec (S n) w dir p →\n  valrel dir w (pEmulDV (S (n + d)) p τ) v vu →\n  (forall v vu w' τ, dir_world_prec n w' dir p →\n                ValidTy τ ->\n                valrel dir w' (pEmulDV (n + d) p τ) v vu →\n                   exists v',\n                     app (downgrade n d τ) v -->* v' ∧ valrel dir w' (pEmulDV n p τ) v' vu) →\n  (forall v vu w' τ, dir_world_prec n w' dir p →\n                ValidTy τ ->\n                valrel dir w' (pEmulDV n p τ) v vu →\n                   exists v',\n                     app (upgrade n d τ) v -->* v' ∧ valrel dir w' (pEmulDV (n + d) p τ) v' vu) →\n  exists v',\n    app (downgrade (S n) d τ) v -->* v' ∧\n    valrel dir w (pEmulDV (S n) p τ) v' vu.\nProof.\n  intros vτ dwp vr IHdown IHup.\n  destruct (valrel_implies_Value vr);\n  destruct (valrel_implies_OfType vr) as [[vv ty] [vvu tyvu]].\n  simpl in ty, tyvu.\n  destruct (F.can_form_tsum vv ty) as [(? & ? & ?) | (? & ? & ?)]; subst; [\n    | exact (downgrade_inr_works vr)\n  ].\n  assert (vτ' : ValidTy (unfoldn (LMC τ) τ)) by eauto using ValidTy_unfoldn.\n  assert (lτz : LMC (unfoldn (LMC τ) τ) = 0) by (eapply unfoldn_LMC; crushValidTy).\n  rewrite downgrade_unfoldn; try assumption.\n  rewrite valrel_pEmulDV_unfoldn in vr; try assumption.\n\n  (* not sure why generalized rewriting is not working here *)\n  enough (∃ v' : Tm,\n    (clos_refl_trans_1n Tm eval\n          (app (downgrade (S n) d (unfoldn (LMC τ) τ)) (inl x)) v')\n    ∧ valrel dir w (pEmulDV (S n) p (unfoldn (LMC τ) τ)) v' vu).\n  { destruct H1 as (v' & es & vr').\n    exists v'. split; try assumption.\n    now rewrite valrel_pEmulDV_unfoldn.\n  }\n  destruct (unfoldn (LMC τ) τ).\n  - (* inArr *)\n    destruct (ValidTy_invert_arr vτ') as (vτ1 & vτ2).\n    eapply (downgrade_inArr_works vτ1 vτ2 vr); crush.\n    + eapply IHdown; try assumption.\n      eapply dwp_invert_S'; crush.\n    + eapply IHup; try assumption; eapply dwp_invert_S'; crush.\n  - (* inUnit *)\n    assert (x = unit) by (crushTyping; stlcCanForm; reflexivity);\n      subst.\n    exists (F.inl unit).\n    eauto using downgrade_eval_inUnit, invert_valrel_pEmulDV_inUnit', valrel_inUnit.\n  - (* inBool *)\n    exists (inl x); crush.\n    now eapply (downgrade_eval_inBool (n := n) (d := d)).\n  - (* inProd *)\n    destruct (ValidTy_invert_prod vτ') as (vτ1 & vτ2).\n    eapply (downgrade_inProd_works vτ1 vτ2 vr); crush;\n    eapply IHdown; try assumption; eapply dwp_invert_S'; crush.\n  - (* inSum *)\n    destruct (ValidTy_invert_sum vτ') as (vτ1 & vτ2).\n    eapply (downgrade_inSum_works vτ1 vτ2 vr); crush;\n    eapply IHdown; try assumption; eapply dwp_invert_S'; crush.\n  - (* inRec *)\n    exfalso; cbn in lτz; lia.\n  - (* tvar *)\n    contradiction (invert_valrel_pEmulDV_inVar vr).\nQed.\n\nLemma upgrade_zero_works {d v vu dir w p τ} :\n  dir_world_prec 0 w dir p →\n  valrel dir w (pEmulDV 0 p τ) v vu →\n  exists v',\n    app (upgrade 0 d τ) v -->* v' ∧\n    valrel dir w (pEmulDV d p τ) v' vu.\nProof.\n  intros dwp vr;\n  destruct (valrel_implies_OfType vr) as [[vv ty] [vvu tyvu]];\n  assert (OfType (pEmulDV d p τ) (unkUVal d) vu) by (crush; eauto using unkUVal_Value, unkUValT);\n  exists (unkUVal d).\n  destruct (dwp_zero dwp).\n  eauto using upgrade_zero_eval, valrel_unk, dwp_zero.\nQed.\n\n\nLemma upgrade_inr_works {n d v vu dir w p τ} :\n  ValidTy τ ->\n  valrel dir w (pEmulDV (S n) p τ) (F.inr v) vu →\n  exists v',\n    app (upgrade (S n) d τ) (F.inr v) -->* v' ∧\n    valrel dir w (pEmulDV (S (n + d)) p τ) v' vu.\nProof.\n  intros vτ vr.\n  destruct (valrel_implies_OfType vr) as [[? ?] [? ?]].\n  simpl in H0, H2.\n  assert (v = unit) by (\n  dependent destruction H0;\n  cbn in H;\n  apply (F.can_form_tunit H H0)).\n  subst.\n  exists (F.inr unit).\n  split.\n  - refine (upgrade_eval_unk vτ).\n  - assert (p = imprecise) by exact (invert_valrel_pEmulDV_unk vr);\n      refine (valrel_unk _ H3);\n      crush.\nQed.\n\n\nLemma upgrade_S_works {n d v vu dir w p τ} :\n  ValidTy τ ->\n  dir_world_prec (S n) w dir p →\n  valrel dir w (pEmulDV (S n) p τ) v vu →\n  (forall v vu w' τ, dir_world_prec n w' dir p →\n                ValidTy τ ->\n                valrel dir w' (pEmulDV (n + d) p τ) v vu →\n                   exists v',\n                     app (downgrade n d τ) v -->* v' ∧ valrel dir w' (pEmulDV n p τ) v' vu) →\n  (forall v vu w' τ, dir_world_prec n w' dir p →\n                ValidTy τ ->\n                valrel dir w' (pEmulDV n p τ) v vu →\n                   exists v',\n                     app (upgrade n d τ) v -->* v' ∧ valrel dir w' (pEmulDV (n + d) p τ) v' vu) →\n  exists v',\n    app (upgrade (S n) d τ) v -->* v' ∧\n    valrel dir w (pEmulDV (S n + d) p τ) v' vu.\nProof.\n  intros vτ dwp vr IHdown IHup.\n  destruct (valrel_implies_Value vr);\n  destruct (valrel_implies_OfType vr) as [[vv ty] [vvu tyvu]].\n  simpl in ty, tyvu.\n  destruct (F.can_form_tsum vv ty) as [(? & ? & ?) | (? & ? & ?)]; subst; [\n    | exact (upgrade_inr_works vτ vr)\n  ].\n  assert (vτ' : ValidTy (unfoldn (LMC τ) τ)) by eauto using ValidTy_unfoldn.\n  assert (lτz : LMC (unfoldn (LMC τ) τ) = 0) by (eapply unfoldn_LMC; crushValidTy).\n  rewrite upgrade_unfoldn; try assumption.\n  rewrite valrel_pEmulDV_unfoldn in vr; try assumption.\n\n  (* not sure why generalized rewriting is not working here *)\n  enough (∃ v' : Tm,\n    (clos_refl_trans_1n Tm eval\n          (app (upgrade (S n) d (unfoldn (LMC τ) τ)) (inl x)) v')\n    ∧ valrel dir w (pEmulDV (S n + d) p (unfoldn (LMC τ) τ)) v' vu).\n  { destruct H1 as (v' & es & vr').\n    exists v'. split; try assumption.\n    now rewrite valrel_pEmulDV_unfoldn.\n  }\n\n  destruct (unfoldn (LMC τ) τ).\n  - (* inArr *)\n    destruct (ValidTy_invert_arr vτ') as (vτ1 & vτ2).\n    eapply (upgrade_inArr_works vτ1 vτ2 vr); crush.\n    + eapply IHdown; try assumption.\n      eapply dwp_invert_S'; crush.\n    + eapply IHup; try assumption; eapply dwp_invert_S'; crush.\n  - (* inUnit *)\n    assert (x = unit) by (crushTyping; stlcCanForm; reflexivity);\n      subst.\n    exists (F.inl unit).\n    eauto using upgrade_eval_inUnit, invert_valrel_pEmulDV_inUnit', valrel_inUnit.\n  - (* inBool *)\n    exists (inl x); crush.\n    now eapply (upgrade_eval_inBool (n := n) (d := d)).\n  - (* inProd *)\n    destruct (ValidTy_invert_prod vτ') as (vτ1 & vτ2).\n    eapply (upgrade_inProd_works vτ1 vτ2 vr); crush;\n    eapply IHup; try assumption; eapply dwp_invert_S'; crush.\n  - (* inSum *)\n    destruct (ValidTy_invert_sum vτ') as (vτ1 & vτ2).\n    eapply (upgrade_inSum_works vτ1 vτ2 vr); crush;\n    eapply IHup; try assumption; eapply dwp_invert_S'; crush.\n  - (* inRec *)\n    exfalso; cbn in lτz; lia.\n  - (* tvar *)\n    contradiction (invert_valrel_pEmulDV_inVar vr).\nQed.\n\nLemma downgrade_works {n d v vu dir w p τ} :\n  ValidTy τ ->\n  dir_world_prec n w dir p →\n  valrel dir w (pEmulDV (n + d) p τ) v vu →\n  exists v',\n    app (downgrade n d τ) v -->* v' ∧\n    valrel dir w (pEmulDV n p τ) v' vu\nwith upgrade_works {n v vu dir w p τ} d :\n       ValidTy τ ->\n       dir_world_prec n w dir p →\n       valrel dir w (pEmulDV n p τ) v vu →\n       exists v',\n         app (upgrade n d τ) v -->* v' ∧\n         valrel dir w (pEmulDV (n + d) p τ) v' vu.\nProof.\n  (* the following is easier, but cheats by using the inductive hypotheses\n  immediately *)\n  (* auto using downgrade_zero_works, downgrade_S_works, upgrade_zero_works, upgrade_S_works. *)\n\n  - destruct n.\n    + intros; apply downgrade_zero_works; trivial.\n    + specialize (downgrade_works n).\n      specialize (upgrade_works n).\n      eauto using downgrade_S_works.\n  - destruct n.\n    + intros; apply upgrade_zero_works; trivial.\n    + specialize (downgrade_works n).\n      specialize (upgrade_works n).\n      auto using upgrade_S_works.\nQed.\n\nLemma downgrade_works' {n d v vu dir w p τ} :\n  ValidTy τ ->\n  dir_world_prec n w dir p →\n  valrel dir w (pEmulDV (n + d) p τ) v vu →\n  termrel dir w (pEmulDV n p τ) (app (downgrade n d τ) v) vu.\nProof.\n  intros vτ dwp vr.\n  destruct (downgrade_works vτ dwp vr) as (v' & es & vr').\n  apply valrel_in_termrel in vr'.\n  refine (termrel_antired_star_left es vr').\nQed.\n\nLemma downgrade_works'' {n d v vu dir w p τ} :\n  ValidTy τ ->\n  dir_world_prec n w dir p →\n  valrel dir w (pEmulDV (n + d) p τ) v vu →\n  termrel₀ dir w (pEmulDV n p τ) (app (downgrade n d τ) v) vu.\nProof.\n  intros vτ dwp vr.\n  destruct (downgrade_works vτ dwp vr) as (v' & es & vr').\n  apply valrel_in_termrel₀ in vr'.\n  refine (termrel₀_antired_star_left es vr').\nQed.\n\nLemma upgrade_works' {n v vu dir w p τ} d :\n  ValidTy τ ->\n  dir_world_prec n w dir p →\n  valrel dir w (pEmulDV n p τ) v vu →\n  termrel dir w (pEmulDV (n + d) p τ) (app (upgrade n d τ) v) vu.\nProof.\n  intros vτ dwp vr.\n  destruct (upgrade_works d vτ dwp vr) as (v' & es & vr').\n  apply valrel_in_termrel in vr'.\n  refine (termrel_antired_star_left es vr').\nQed.\n\nLemma upgrade_works'' {n v vu dir w p τ} d :\n  ValidTy τ ->\n  dir_world_prec n w dir p →\n  valrel dir w (pEmulDV n p τ) v vu →\n  termrel₀ dir w (pEmulDV (n + d) p τ) (app (upgrade n d τ) v) vu.\nProof.\n  intros vτ dwp vr.\n  destruct (upgrade_works d vτ dwp vr) as (v' & es & vr').\n  apply valrel_in_termrel₀ in vr'.\n  refine (termrel₀_antired_star_left es vr').\nQed.\n\nLemma compat_upgrade {Γ ts dir m tu n p τ} d :\n  ValidTy τ ->\n  dir_world_prec n m dir p →\n  ⟪ Γ ⊩ ts ⟦ dir , m ⟧ tu : pEmulDV n p τ⟫ →\n  ⟪ Γ ⊩ app (upgrade n d τ) ts ⟦ dir , m ⟧ tu : pEmulDV (n + d) p τ ⟫.\nProof.\n  intros.\n  repeat crushLRMatch.\n  - eauto using upgrade_T with typing.\n  - E.crushTyping.\n  - intros.\n    specialize (H3 w H4 _ _ H5).\n    simpl; repeat crushStlcSyntaxMatchH.\n    rewrite upgrade_sub; try assumption.\n    eapply (termrel_ectx' H3); F.inferContext; E.inferContext; crush;\n    eauto using upgrade_value.\n    simpl.\n    eauto using upgrade_works', dwp_mono.\nQed.\n\nLemma compat_downgrade {Γ ts dir m tu n p d τ} :\n  ValidTy τ ->\n  dir_world_prec n m dir p →\n  ⟪ Γ ⊩ ts ⟦ dir , m ⟧ tu : pEmulDV (n + d) p τ ⟫ →\n  ⟪ Γ ⊩ app (downgrade n d τ) ts ⟦ dir , m ⟧ tu : pEmulDV n p τ ⟫.\nProof.\n  intros.\n  repeat crushLRMatch.\n  - eauto using downgrade_T with typing.\n  - E.crushTyping.\n  - intros.\n    specialize (H3 w H4 _ _ H5).\n    simpl; repeat crushStlcSyntaxMatchH.\n    rewrite downgrade_sub; try assumption.\n    eapply (termrel_ectx' H3); F.inferContext; E.inferContext; crush;\n    eauto using downgrade_value.\n    simpl.\n    eauto using downgrade_works', dwp_mono.\nQed.\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/BacktransFE/UpgradeDowngrade.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.2912101596065428}}
{"text": "Require Import Classes.Joinable.\nRequire Export Base.\nRequire Import Classes.Monad Classes.Monad.MonadState \n  Types.State Classes.Galois Types.Option.\n\nImplicit Type S : Type.\nImplicit Type M : Type → Type.\n\nInstance store_stateT {S} {M} `{MM : Monad M} : MonadState S (StateT S M) := {\n  get := λ st, returnM (st, st);\n  put := λ st, λ _, returnM (tt, st);\n}.\n\nInstance get_store_stateT_sound {ST ST' : Type} {GS : Galois ST ST'} \n  {M M' : Type → Type} `{MM : Monad M} `{MM' : Monad M'}\n  {GM : ∀ A A', Galois A A' → Galois (M A) (M' A')} :\n  return_sound M M' →\n  get_state_sound (StateT ST M) (StateT ST' M').\nProof.\n  intros RS. intros a a' Ha. apply returnM_sound. eauto with soundness.\nQed.\nHint Resolve get_store_stateT_sound : soundness.\n\nInstance put_store_stateT_sound {ST ST' : Type} {GS : Galois ST ST'}\n  {M M' : Type → Type} `{MM : Monad M} `{MM' : Monad M'}\n  {GM : ∀ A A', Galois A A' → Galois (M A) (M' A')} :\n  return_sound M M' →\n  put_state_sound (StateT ST M) (StateT ST' M').\nProof.\n  intros RS s s' Hs. cbn. intros ???. apply RS. constructor; cbn.\n  constructor. assumption.\nQed.\nHint Resolve put_store_stateT_sound : soundness.\n\nInstance store_optionT {ST} {M} `{MM : Monad M} {MS : MonadState ST M} :\n  MonadState ST (optionT M) := {\n  get := get >>= λ a, returnM (Some a);\n  put := λ st, put st ;; returnM (Some tt);\n}.\n\nInstance get_store_optionT_sound {ST ST' : Type} {GST : Galois ST ST'}\n  {M M' : Type → Type} `{MM : Monad M} `{MM' : Monad M'}\n  {GM : ∀ A A', Galois A A' → Galois (M A) (M' A')}\n  {MS : MonadState ST M} {MS' : MonadState ST' M'} :\n  bind_sound M M' →\n  return_sound M M' → \n  get_state_sound M M' →\n  get_state_sound (optionT M) (optionT M').\nProof.\n  intros BS RS GS.\n  unfold get_state_sound. unfold get; simpl. \n  eapply BS; auto.\n  intros a a' Ha. eauto with soundness.\nQed.\nHint Resolve get_store_optionT_sound : soundness.\n\nInstance store_optionAT {S} {JS: Joinable S S} {JI : JoinableIdem JS} :\n  MonadState S (optionAT (StateT S option)) := {\n  get := get >>= λ a, returnM (SomeA a);\n  put := λ st, put st ;; returnM (SomeA tt);\n}.\n\nInstance get_store_optionAT_sound {S S' : Type} {GS : Galois S S'} \n  {JS : Joinable S S} {JSI : JoinableIdem JS} :\n  get_state_sound (optionAT (StateT S option)) (optionT (StateT S' option)).\nProof.\n  unfold get_state_sound, get; simpl. \n  eauto with soundness. \n  constructor; constructor; simpl; [constructor | ]; assumption.\nQed.\nHint Resolve get_store_optionAT_sound : soundness.\n\nInstance put_store_optionAT_sound {S S' : Type} {GS : Galois S S'}\n  {JS : Joinable S S} {JI : JoinableIdem JS} :\n  put_state_sound (optionAT (StateT S option)) (optionT (StateT S' option)).\nProof.\n  intros s s' Hs; cbn.\n  unfold bindM; simpl; unfold bind_stateT.\n  intros s2 s2' Hs2.\n  unfold bindM; simpl; unfold bind_option.\n  constructor. constructor; eauto with soundness.\nQed.\nHint Resolve put_store_optionAT_sound : soundness.\n", "meta": {"author": "jensdewaard", "repo": "thesis-coq-code", "sha": "a332573b8646f4b045bf08cdf7070b88063dd51e", "save_path": "github-repos/coq/jensdewaard-thesis-coq-code", "path": "github-repos/coq/jensdewaard-thesis-coq-code/thesis-coq-code-a332573b8646f4b045bf08cdf7070b88063dd51e/Instances/Store.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.29111574776707544}}
{"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 per.\nRequire Export continuity_defs_ceq.\n\n\nDefinition is_spcan_not_atom {o} lib (t : @CTerm o) a : Type :=\n  {op : Opid\n   & computes_to_can lib (get_cterm t) (oterm op [])\n   # !LIn a (get_utokens_o op)}.\n\nDefinition noc_bterms {o} (t : @CTerm o) :=\n  get_bterms (get_cterm t) = [].\n\nDefinition cis_spcan_not_atom {o} lib (t : @CTerm o) a :=\n  {x : CTerm\n   , t ===>(lib) x\n   # isccanc x\n   # noc_bterms x\n   # !LIn a (getc_utokens x)}.\n\nDefinition mkc_fresh {o} (v : NVar) (t : @CVTerm o [v]) : CTerm :=\n  let (a,x) := t in\n    exist isprog (mk_fresh v a) (isprog_fresh_implies v a x).\n\nDefinition getcv_utokens {o} vs (t : @CVTerm o vs) :=\n  get_utokens (get_cvterm vs t).\n\nLemma cequivc_fresh_subst1 {o} :\n  forall lib v (t : @CVTerm o [v]) a,\n    !LIn a (getcv_utokens [v] t)\n    -> is_spcan_not_atom lib (substc (mkc_utoken a) v t) a\n    -> cequivc lib (mkc_fresh v t) (substc (mkc_utoken a) v t).\nProof.\n  introv nia ispc.\n  destruct_cterms; allsimpl.\n  unfold cequivc; simpl.\n  unfold getcv_utokens in nia; allsimpl.\n  unfold is_spcan_not_atom in ispc; exrepnd; allsimpl.\n  allunfold @computes_to_can; repnd.\n  allapply @iscan_implies; repndors; exrepnd; ginv.\n  apply (cequiv_fresh_subst1 lib (Can c)); simpl; allrw app_nil_r; auto; tcsp.\n  unfold iscan_op; eexists; eauto.\nQed.\n\nLemma cequivc_fresh_subst2 {o} :\n  forall lib v (t : @CVTerm o [v]) a,\n    !LIn a (getcv_utokens [v] t)\n    -> cis_spcan_not_atom lib (substc (mkc_utoken a) v t) a\n    -> ccequivc lib (mkc_fresh v t) (substc (mkc_utoken a) v t).\nProof.\n  introv nia ispc.\n  unfold cis_spcan_not_atom in ispc; exrepnd; spcast.\n  apply cequivc_fresh_subst1; auto.\n  destruct_cterms; allsimpl.\n  allunfold @computes_to_valc; allsimpl.\n  allunfold @noc_bterms; allsimpl.\n  allunfold @computes_to_value; repnd.\n  allunfold @getc_utokens; allsimpl.\n  allapply @isvalue_implies; repnd.\n  allapply @iscan_implies; repndors; exrepnd; subst; allsimpl; subst; allsimpl; GC.\n  { allrw app_nil_r.\n    unfold is_spcan_not_atom; simpl.\n    exists (Can c); dands; simpl; tcsp.\n    unfold computes_to_can; dands; simpl; auto. }\n  { allunfold @isccanc; allsimpl; tcsp. }\nQed.\n\n\n(*\n*** Local Variables:\n*** coq-load-path: (\".\" \"./close/\")\n*** End:\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_defs0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.46490157137338856, "lm_q1q2_score": 0.2910861203550853}}
{"text": "From Coq Require Import List Lia.\nFrom PCC Require Import list_utils java_basic_defs program_model expressions_assertions semantics_assertions weakest_precondition.\nFrom PCC Require Import ssrexport.\n\n(* The default variable denotes an assertion that expresses that\n   all variables have their default values. *)\nVariable default : ast.\n\nHypothesis initial_default : forall c, initial_conf c -> ∥ default ∥ c.\n\n\nSection validity.\n  \n  Variable p: program.\n  \n  (* An execution is valid if each config satisfies the assertion of the current\n     program point and inv holds whenever a config is calling or returning. *)\n  Inductive valid_conf c : Prop :=\n  | v_conf : (* TODO: change into a def. *)\n      (visible_conf p c -> ∥ inv p ∥ c) ->\n      (normal_conf c -> forall a, current_ast p c = Some a -> ∥ a ∥ c) ->\n      valid_conf c.\n  \n  \n  Inductive valid_exec : execution -> Prop :=\n  | ve_nil : valid_exec nil\n  | ve_cons : \n    forall c cs,\n      valid_conf c ->\n      valid_exec cs ->\n      valid_exec (cs++c::nil).\n  \n  Lemma all_valid : forall e, valid_exec e <-> forall c, In c e -> valid_conf c.\n    split.\n    \n    (* -> *)\n    intros.\n    destruct e using rev_ind.\n    inversion H0.\n    inversion H.\n    apply app_cons_not_nil in H2.\n    contradiction.\n    \n    apply in_but_not_last in H0.\n    elim H0; intros.\n    \n    apply app_inj_tail in H1.\n    elim H1; intros; subst.\n    assumption.\n    \n    apply IHe.\n    apply app_inj_tail in H1.\n    elim H1; intros; subst.\n    assumption.\n    assumption.\n    \n    (* <- *)\n    intros.\n    destruct e using rev_ind.\n    apply ve_nil.\n    apply ve_cons.\n    apply H.\n    apply in_or_app.\n    right.\n    auto with datatypes.\n    apply IHe.\n    intros.\n    apply H.\n    apply in_or_app.\n    left.\n    assumption.\n  Qed.\n  \n  \n  Definition globally_valid : Prop := forall e, execution_of p e -> valid_exec e.\n  \n  \n  Definition locally_valid_meth cid mid : Prop :=\n    (forall c, ∥ inv p ∥ c -> ∥ ast_at p cid mid O ∥ c) /\\\n    (forall c l, ∥ ast_at p cid mid l ∥ c -> ∥ wp p cid mid l ∥ c).\n  \n  \n  Definition locally_valid : Prop :=\n    (forall cid mid, locally_valid_meth cid mid) /\\\n    (forall c, ∥ default ∥ c -> ∥ ast_at p maincid mainmid O ∥ c) /\\\n    (forall c, ∥ default ∥ c -> ∥ inv p ∥ c).\n\n(* aload n *)\nLemma wp_correct_normal_aload : forall c m pc s ls h n ars gv,\n  instr_at p c m pc = aload n ->\n  (∥wp p c m pc ∥ (gv, h, normal c m pc s ls :: ars) <->\n  ∥ast_at p c m (successor p c m pc) ∥ (gv, h, normal c m (successor p c m pc) (ls n :: s) ls :: ars)).\nProof.\n  intros.\n  unfold wp.\n  rewrite H.\n  set (a := ast_at p c m (successor p c m pc)) in * |- *.\n  set (cnf := (gv, h, normal c m pc s ls :: ars)) in * |- *.\n  set (cnf' := (gv, h, normal c m (successor p c m pc) (ls n::s) ls :: ars)) in * |- *.\n  \n  assert (expr_lemma: forall e val, eeval (eunshift (subste e (local n) (stackexp 0))) cnf val <-> (eeval e cnf' val)).\n    intros e.\n    induction e; intros.\n    (* v *)\n    split; intros.\n    simpl in H0.\n    inversion H0; subst.\n    apply e_val.\n    inversion H0; subst.\n    simpl.\n    apply e_val.\n    apply e_ghosterr.\n    inversion H0; subst.\n    simpl.\n    apply e_val.\n    simpl.\n    apply e_ghosterr.\n    \n    (* ghost var *)\n    assert (H_gv: ghost_valuation_of cnf = ghost_valuation_of cnf'). auto.\n    split; intros.\n    inversion H0; subst.\n    rewrite H_gv.\n    apply e_ghostvar.\n    simpl.\n    inversion H0; subst.\n    rewrite <- H_gv.\n    apply e_ghostvar.\n\n    (* nsfield *) split; intros. simpl in H0.\n    inversion H0; subst.\n    apply IHe in H4.\n    apply (e_nsfield gv cnf' e dh sh (normal c m (successor p c m pc) (ls n::s) ls :: ars) f l obj).\n    inversion H3.\n    rewrite <- H2.\n    rewrite <- H5.\n    reflexivity.\n    assumption.\n    assumption.\n    \n    apply e_nsfield_err1 with (v := v).\n    apply (IHe v).\n    assumption.\n    assumption.\n    \n    \n    apply e_nsfield_err2 with (c := cnf') (gv := gv) (dh := dh) (sh := sh) (l := l) (ars := normal c m (successor p c m pc) (ls n :: s) ls :: ars).\n    inversion H3.\n    rewrite <- H2.\n    rewrite <- H5.\n    reflexivity.\n    apply IHe in H4.\n    assumption.\n    assumption.\n    \n\n    inversion H0; subst.\n    simpl.\n    apply e_nsfield with (gv := gv) (dh := dh) (sh := sh) (ars := normal c m pc s ls :: ars) (l := l).\n    inversion H3.\n    rewrite <- H2.\n    rewrite <- H5.\n    reflexivity.\n    apply (IHe (refval l)).\n    assumption.\n    assumption.\n    \n    inversion H0; subst.\n    simpl.\n    apply e_nsfield with (gv := gv) (dh := dh) (sh := sh) (ars := normal c m pc s ls :: ars) (l := l).\n    inversion H5.\n    rewrite <- H7.\n    rewrite <- H2.\n    reflexivity.\n    apply (IHe (refval l)).\n    assumption.\n    assumption.\n    \n    simpl.\n    apply e_nsfield_err1 with (v := v0).\n    apply (IHe v0).\n    assumption.\n    assumption.\n\n    simpl.\n    apply e_nsfield_err2 with (c := cnf) (gv := gv) (dh := dh) (sh := sh) (l := l) (ars := normal c m pc s ls :: ars).\n    inversion H4.\n    rewrite <- H2.\n    rewrite <- H7.\n    reflexivity.\n    apply (IHe (refval l)).\n    assumption.\n    assumption.\n    \n    simpl.\n    apply e_nsfield_err2 with (c := cnf) (gv := gv) (dh := dh) (sh := sh) (l := l) (ars := normal c m pc s ls :: ars).\n    inversion H3.\n    rewrite <- H2.\n    rewrite <- H5.\n    reflexivity.\n    apply (IHe (refval l)).\n    assumption.\n    assumption.\n    \n    \n    (* sfield *) split; intros.\n    inversion H0; subst.\n    apply (e_sfield gv cnf' dh sh (normal c m (successor p c m pc) (ls n :: s) ls :: ars) c0 f v).\n    inversion H3.\n    rewrite <- H2.\n    rewrite <- H4.\n    reflexivity.\n    assumption.\n    \n    apply e_sfield_err with (gv := gv) (dh := dh) (sh := sh) (ars := normal c m (successor p c m pc) (ls n :: s) ls :: ars).\n    inversion H3.\n    rewrite <- H2.\n    rewrite <- H4.\n    reflexivity.\n    assumption.\n    \n    simpl.\n    inversion H0; subst.\n    apply e_sfield with (gv := gv) (dh := dh) (sh := sh) (ars := normal c m pc s ls :: ars).\n    inversion H3.\n    rewrite <- H4.\n    rewrite <- H2.\n    reflexivity.\n    assumption.\n    \n    apply e_sfield_err with (gv := gv) (dh := dh) (sh := sh) (ars := normal c m pc s ls :: ars).\n    inversion H3.\n    rewrite <- H2.\n    rewrite <- H4.\n    reflexivity.\n    assumption.\n    \n    (* stackexp *) split; intros.\n    destruct n0.\n    (* subcase: n0 = 0 *)\n    simpl in H0.\n    inversion H0; subst.\n    assert ((ls0 n::s)[[0]] = ls0 n).\n      simpl.\n      reflexivity.\n    rewrite <- H1.\n    apply (e_stack cnf' 0 (ls0 n :: s)).\n    simpl.\n    inversion H2.\n    reflexivity.\n    (* subcase: n0 = S n0 *)\n    simpl in H0.\n    inversion H0; subst.\n    inversion H2.\n    rewrite <- H3 in * |- *.\n    assert (s[[n0]] = ((ls n :: s)[[S n0]])).\n      simpl.\n      reflexivity.\n    rewrite H1.\n    \n    apply (e_stack cnf' (S n0) (ls n :: s)).\n    simpl.\n    reflexivity.\n    destruct n0.\n    (* subcase n0 = 0 *)\n    simpl.\n    inversion H0; subst.\n    inversion H2.\n    simpl.\n    apply e_local.\n    reflexivity.\n    (* subcase n0 = S n0' *)\n    inversion H0; subst.\n    inversion H2; subst.\n    simpl.\n    apply e_stack.\n    reflexivity.\n    (* local n0 *)\n    split; intros.\n    simpl in H0.\n    inversion H0; subst.\n    inversion H2.\n    apply e_local.\n    rewrite <- H3.\n    reflexivity.\n    inversion H0; subst.\n    inversion H2.\n    rewrite <- H3.\n    simpl.\n    apply e_local.\n    reflexivity.\n    (* plus *)\n    split; intros.\n    simpl in H0.\n    inversion H0; subst.\n    apply IHe1 in H3.\n    apply IHe2 in H6.\n    apply e_plus; assumption.\n    \n    apply e_plus_err with (v1 := v1) (v2 := v2).\n    apply (IHe1 v1) in H3; assumption.\n    apply (IHe2 v2) in H4; assumption.\n    assumption.\n\n    simpl.\n    inversion H0; subst.\n    apply e_plus.\n    apply IHe1 in H3; assumption.\n    apply IHe2 in H6; assumption.\n    \n    inversion H0; subst.\n    apply e_plus_err with (v1 := v1) (v2 := v2).\n    apply (IHe1 v1); assumption.\n    apply (IHe2 v2); assumption.\n    assumption.\n    \n    (* guarded *)\n    split; intros.\n    simpl in H0.\n    inversion H0; subst.\n    apply IHe1 in H6.\n    apply IHe2 in H7.\n    apply e_guard_true; assumption.\n    apply IHe1 in H6.\n    apply IHe3 in H7.\n    apply e_guard_other; assumption.\n    \n    apply e_guard_err with (v := v).\n    apply IHe1 in H6.\n    assumption.\n    assumption.\n    \n    simpl.\n    inversion H0; subst.\n    apply e_guard_true.\n    apply IHe1 in H6; assumption.\n    apply IHe2 in H7; assumption.\n    apply e_guard_other.\n    apply IHe1 in H6; assumption.\n    apply IHe3 in H7; assumption.\n    \n    apply e_guard_err with (v := v).\n    apply (IHe1 v).\n    assumption.\n    assumption.\n\ninduction a; inversion H.\n(* tt *)\nsplit; intros; apply e_tt.\n(* ff *)\nsplit; intros; inversion H0.\n(* le *)\nsplit; intros.\ninversion H0.\napply expr_lemma in H4.\napply expr_lemma in H5.\napply e_le with (i := i) (j := j); assumption.\nsimpl.\ninversion H0; subst.\napply e_le with (i := i) (j := j).\napply expr_lemma in H4; assumption.\napply expr_lemma in H5; assumption.\nassumption.\n(* eq *)\nsplit; intros.\ninversion H0; subst.\napply expr_lemma in H4.\napply expr_lemma in H6.\napply e_eq with (v := v); assumption.\nsimpl.\ninversion H0; subst.\napply e_eq with (v := v).\napply expr_lemma in H4; assumption.\napply expr_lemma in H6; assumption.\n(* or *)\nsplit; intros.\ninversion H0; subst.\nelim H5; intros.\napply IHa1 in H2.\napply e_disj.\nleft; assumption.\napply IHa2 in H2.\napply e_disj.\nright; assumption.\nsimpl.\napply e_disj.\ninversion H0; subst.\nelim H5; intros.\napply IHa1 in H2.\nleft; assumption.\napply IHa2 in H2.\nright; assumption.\n(* and *)\nsplit; intros.\ninversion H0; subst.\nelim H5; intros.\napply IHa1 in H2.\napply IHa2 in H3.\napply e_conj.\nsplit; assumption.\nsimpl.\napply e_conj.\ninversion H0; subst.\nelim H5; intros.\napply IHa1 in H2.\napply IHa2 in H3.\nsplit; assumption.\n(* neg *)\nsplit; intros.\ninversion H0; subst.\napply e_neg.\napply invert_aeval in IHa.\napply IHa in H3.\nassumption.\napply is_norm_conf.\napply is_norm_conf.\nsimpl.\napply e_neg.\napply invert_aeval in IHa.\napply IHa.\ninversion H0; subst.\nassumption.\napply is_norm_conf.\napply is_norm_conf.\n\n(* if else *)\nsplit; intros.\nsimpl in H0.\ninversion H0; subst.\napply e_if_true.\napply IHa1 in H6; assumption.\napply IHa2 in H7; assumption.\ninversion H0; subst.\napply e_if_false.\napply invert_aeval in IHa1.\napply IHa1 in H6; assumption.\napply is_norm_conf.\napply is_norm_conf.\napply IHa3 in H7; assumption.\napply e_if_false.\napply invert_aeval in IHa1.\napply IHa1 in H6; assumption.\napply is_norm_conf.\napply is_norm_conf.\napply IHa3 in H7; assumption.\n\nsimpl.\ninversion H0; subst.\napply e_if_true.\napply IHa1; assumption.\napply IHa2; assumption.\napply e_if_false.\napply invert_aeval in IHa1.\napply IHa1 in H6; assumption.\napply is_norm_conf.\napply is_norm_conf.\napply IHa3 in H7; assumption.\nQed.\n\nLemma wp_correct_normal_astore: forall c m pc s ls h n v ars gv,\n instr_at p c m pc = astore n ->\n (∥wp p c m pc ∥ (gv, h, normal c m pc (v :: s) ls :: ars) <->\n   ∥ast_at p c m (successor p c m pc) ∥ (gv, h, normal c m (successor p c m pc) s (upd ls n v) :: ars)).\nProof.\nAdmitted.\n\nLemma wp_correct_normal_dup: forall c m pc s ls h v ars gv,\n instr_at p c m pc = dup ->\n (∥wp p c m pc ∥ (gv, h, normal c m pc (v :: s) ls :: ars) <->\n   ∥ast_at p c m (successor p c m pc) ∥ (gv, h, normal c m (successor p c m pc) (v :: v :: s) ls :: ars)).\nProof.\nAdmitted.\n\nLemma wp_correct_normal_goto: forall c m pc s ls h l ars gv,\n instr_at p c m pc = goto l ->\n  (∥ wp p c m pc ∥ (gv, h, normal c m pc s ls :: ars) <->\n  ∥ ast_at p c m l ∥ (gv, h, normal c m l s ls :: ars)).\nProof.\nAdmitted.\n\nLemma wp_correct_normal : forall h cid mid pc s ls ars c' a,\n  let c := (h, (normal cid mid pc s ls)::ars) in\n    trans p c c' ->\n    normal_conf c' ->\n    current_ast p c' = Some a ->\n    (∥ wp p cid mid pc ∥ c <->\n    ∥ a ∥ c').\nProof.\nintros.\ninversion H; subst; last first.\n  (* trans *)\n  by admit.\ninversion H0; subst.\ninversion H1; subst.\ninversion H2; subst.\ninversion H4; subst.\n- (* aload n *)\n  inversion H6; subst.\n  inversion H5; subst.\n  by apply wp_correct_normal_aload.\n- (* astore n *)\n  inversion H6; subst.\n  inversion H5; subst.\n  by apply wp_correct_normal_astore.\n- (* dup *)\n  inversion H6; subst.\n  inversion H5; subst.\n  rewrite H2.\n  by apply wp_correct_normal_dup.\n- (* goto *)\n  inversion H6; subst.\n  inversion H5; subst.\n  rewrite H2.\n  by apply wp_correct_normal_goto.\n- (* iconst *)\n  by admit.\n- (* ldc *)\n  by admit.\n- (* ifeq true *)\n  by admit.\n- (* ifeq false *)\n  by admit.\n(* The other instructions can be treated similarly and are proved correct when the\n   remaining of the proof script is completed and the definitions more stable. *)\n\n(* This whole lemma could probably be solved with some proof search\n   automation and/or ssreflect. Consult Karl. *)\nAdmitted.\n  \n  Lemma wp_correct_exceptional :\n    forall gv h o cid mid pc s ls ars gv'' h'' c' a,\n      let c := (gv, h, (exceptional o) :: (normal cid mid pc s ls) :: ars) in\n      let c'' := (gv'', h'', (normal cid mid pc s ls) :: ars) in\n        trans p c c' ->\n        normal_conf c' ->\n        current_ast p c' = Some a ->\n        (∥ wp p cid mid pc ∥ c'') ->\n        (∥ a ∥ c').\n(* The other instructions can be treated similarly and are proved correct when the\n   remaining of the proof script is completed and the definitions more stable. *)\n  Admitted.\n  \n  \n  Lemma sub_execution : forall pref suff, execution_of p (pref ++ suff) ->\n                                          execution_of p pref.\n    intros.\n    apply exec_intros.\n    destruct pref.\n    intros.\n    inversion H0.\n    intros.\n    inversion H0; subst.\n    inversion H; subst.\n    apply H1.\n    simpl.\n    reflexivity.\n    intros.\n    subst.\n    inversion H; subst.\n    apply H1 with (pref := pref0) (suff1 := suff0 ++ suff).\n    rewrite app_ass.\n    rewrite app_comm_cons.\n    reflexivity.\n  Qed.\n  \n  Corollary sub_execution2 : forall exec c c',\n      execution_of p (exec ++ c::c'::nil) -> execution_of p (exec ++ c :: nil).\n    \n    intros.\n    apply sub_execution with (suff := c' :: nil).\n    rewrite app_ass.\n    simpl.\n    assumption.\n  Qed.\n  \n  Theorem strong_exec_ind (P: execution -> Prop) :\n    P nil ->\n    (forall c, execution_of p (c :: nil) -> P (c :: nil)) ->\n    (forall exec c c', execution_of p (exec ++ c :: c' :: nil) ->\n      (forall exec', execution_of p exec' ->\n                     proper_prefix exec' (exec ++ c :: c' :: nil) ->\n                     P exec') ->\n      P (exec ++ c :: c' :: nil)) ->\n    forall exec, execution_of p exec -> P exec.\n    \n    destruct exec using strong_list_ind.\n    intros.\n    destruct exec using rev_ind.\n    assumption.\n    destruct exec using rev_ind.\n    apply (H0 x).\n    assumption.\n    rewrite <- list_rearrange.\n    apply H1.\n    rewrite <- list_rearrange in H3.\n    assumption.\n    intros.\n    apply H2.\n    rewrite <- list_rearrange.\n    assumption.\n    assumption.\n  Qed.\n  \n  \n  Lemma valid_exec_last : forall exec c, valid_exec (exec ++ c :: nil) -> valid_conf c.\n    intros.\n    apply (all_valid (exec ++ c::nil)).\n    assumption.\n    apply in_or_app.\n    right.\n    auto with datatypes.\n  Qed.\n  \n  \n  Lemma valid_exec_prefix :\n    forall pref exec, proper_prefix pref exec -> valid_exec exec -> valid_exec pref.\n    intros pref ex H.\n    \n    assert (H_tmp: forall a a' b b': Prop, (a' -> b') -> (a <-> a') -> (b <-> b') -> (a -> b)).\n      intros a a' b b' H_t0 H_t1 H_t2 H_t3.\n      apply H_t2.\n      apply H_t0.\n      apply H_t1.\n      assumption.\n    \n    apply (H_tmp (valid_exec ex) (forall c, In c ex -> valid_conf c) (valid_exec pref) (forall c, In c pref -> valid_conf c)).\n    intros.\n    apply H0.\n    apply proper_prefix_split in H.\n    elim H; intros.\n    elim H2; intros.\n    rewrite H3.\n    apply in_or_app.\n    left.\n    assumption.\n    apply (all_valid ex).\n    apply (all_valid pref).\n  Qed.\n  \n  \n  Corollary valid_exec_last_norm :\n    forall exec c, valid_exec (exec ++ c :: nil) -> normal_conf c ->\n      forall a, current_ast p c = Some a -> (∥ a ∥ c).\n  Proof.\n    intros exec c H.\n    apply valid_exec_last in H.\n    inversion H.\n    assumption.\n  Qed.\n  \n  \n  Lemma exec_impl_trans :\n    forall exec c c', execution_of p (exec ++ c :: c' :: nil) -> trans p c c'.\n  Proof.\n    intros.\n    inversion H; subst.\n    apply H1 with (pref := exec) (suff := nil).\n    reflexivity.\n  Qed.\n  \n  \n  Lemma act_rec_suffixes :\n    forall gv gv' h ars h' ar ars', trans p (gv, h, ars) (gv', h', ar::ars') -> suffix ars' ars.\n    intros.\n    inversion H.\n    inversion H2; inversion H0; inversion H1; subst; try apply suffix_next; try apply suffix_here.\n    inversion H0; inversion H5; inversion H7; subst; apply suffix_next; apply suffix_here.\nQed.\n  \n  Lemma all_ars_has_been_on_top :\n    forall exec,\n      execution_of p exec ->\n      forall gv h ars suff,\n        last exec (gv, h, ars) ->\n        suffix suff ars ->\n        suff <> nil ->\n        exists gv', exists h', In (gv', h', suff) exec.\n    \n    apply (strong_exec_ind (fun exec => forall gv h ars suff,\n      last exec (gv, h, ars) ->\n      suffix suff ars ->\n      suff <> nil ->\n      exists gv', exists h', In (gv', h', suff) exec)).\n    \n    intros.\n    inversion H.\n    \n    (* Base case *)\n    intros.\n    inversion H; subst.\n    assert (initial_conf c).\n      apply H3.\n      simpl; reflexivity.\n    inversion H5; subst.\n    inversion H0.\n    exists gv.\n    exists h.\n    subst.\n    inversion H1.\n    subst.\n    apply in_eq.\n    subst.\n    inversion H8.\n    contradiction H2.\n    inversion H9.\n    \n    (* Inductive step *)\n    intros.\n    rewrite list_rearrange in H1.\n    apply last_app_cons in H1.\n    subst.\n    (* rewrite H1 in * |- *. *)\n\n    inversion H2; subst.\n    \n      (* suff = ars   \"non-proper\" prefix *)\n      exists gv.\n      exists h.\n      auto with datatypes.\n      \n      (* suff = proper suffix *)\n      assert (exists gv', exists h', In (gv', h', suff) (exec ++ c :: nil)).\n        destruct c as ((gv', h'), ars').\n        apply H0 with (gv := gv') (h := h') (ars := ars').\n        apply sub_execution2 with (c' := (gv, h, a::l)).\n        assumption.\n        apply proper_prefix_app.\n        apply proper_prefix_next.\n        apply proper_prefix_nil.\n        apply last_app.\n        apply last_base.\n        apply exec_impl_trans in H.\n        apply act_rec_suffixes in H.\n        apply suffix_transitive with (bc := l); assumption.\n        assumption.\n        \n      elim H4; intros gv' H_ex_h.\n      elim H_ex_h; intros h'; intros.\n      exists gv'.\n      exists h'.\n      rewrite list_rearrange.\n      apply in_or_app.\n      left.\n      assumption.\n  Qed.\n  \n  \n  Lemma no_empty_ar_stack_trans : forall gv h ar ars gv' h', trans p (gv, h, ar :: ars) (gv', h', nil) -> False.\n    intros.\n    inversion H; subst.\n    inversion H1; subst.\n    inversion H0; subst.\n  Qed.\n  \n  \n  Lemma no_empty_ar_stack : forall exec gv h, execution_of p exec ->\n                                              In (gv, h, nil) exec -> False.\n    destruct exec using rev_ind; intros.\n    inversion H0.\nrename x into c'.\napply (IHexec gv h).\napply (sub_execution exec (c' :: nil) H).\ndestruct exec using rev_ind; [| clear IHexec0].\ninversion H0; subst.\ninversion H.\npose proof (H1 (gv, h, nil)).\nassert (H_tmp : forall (A: Set) (a : A), head (nil ++ a :: nil) = Some a).\n  reflexivity.\napply H4 in H_tmp.\ninversion H_tmp.\ncontradict H1.\nrename x into c.\napply in_app_or in H0.\nelim H0; clear H0; intros.\nrewrite <- list_rearrange in H.\napply sub_execution2 in H.\ncontradict (IHexec gv h H H0).\ninversion H0; [| contradiction]; subst.\nrewrite <- list_rearrange in H.\ndestruct c.\ndestruct p0.\ndestruct l.\napply sub_execution2 in H.\napply (IHexec g h0) in H; [contradiction |].\napply in_or_app.\nright.\nauto with datatypes.\napply exec_impl_trans in H.\ncontradict (no_empty_ar_stack_trans _ _ _ _ _ _ H).\nQed.\n  \n  \n  Lemma calling_only_invoke :\n    forall gv h c m pc s ls ars0 gv' h' c' m' pc' s' ls',\n      let ars := normal c  m  pc  s  ls :: ars0 in\n      let ars':= normal c' m' pc' s' ls':: ars  in\n        calling_conf p (gv, h, ars) ->\n        trans p (gv, h, ars) (gv', h', ars') ->\n        instr_at p c m pc = invoke c' m'.\n    intros until ars'.\n    intros H_calling H_trans.\n    inversion H_calling as [gv0 h0 c0 m0 pc0 l ls0 ars1 H_trans']; subst.\n    inversion H_trans'; subst.\n    rename H1 into H_atrans.\n    inversion H0.\n    subst.\n    inversion H_atrans; subst; inversion H; contradict H9; apply list_neq_length; simpl; lia.\n    inversion H.\n    contradict H16; apply list_neq_length; simpl; lia.\n  Qed.\n  \n  \n  Lemma calling_conf_inv : forall gv h c m pc s ls ars,\n    let cnf := (gv, h, normal c m pc s ls::ars) in\n      locally_valid -> calling_conf p cnf -> ∥ ast_at p c m pc ∥ cnf -> ∥inv p ∥ cnf.\n    intros.\n    inversion H0; subst.\n    assert (instr_at p c m pc = invoke c0 m0).\n      apply (calling_only_invoke gv h c m pc s ls ars gv h c0 m0 pc0 l ls0); assumption.\n    \n    inversion H.\n    elim (H4 c m); intros.\n    assert ((∥ast_at p c m pc ∥ cnf) -> ∥wp p c m pc ∥ cnf).\n      apply H7.\n    unfold wp in H8.\n    rewrite H2 in H8.\n    apply H8.\n    assumption.\n  Qed.\n  \n  \n  Lemma returning_conf_inv : forall gv h c m pc s ls ars,\n    let cnf  := (gv, h, normal c m pc s ls::ars) in\n      locally_valid -> ∥ast_at p c m pc ∥ cnf -> returning_conf p cnf -> ∥inv p ∥ cnf.\n  Proof.\n    intros.\n    assert (H_curr_inst_ret: current_instr p cnf = Some ret).\n    inversion H1; subst.\n    inversion H3; subst.\n    \n    (* ar-trans *)\n    inversion H5; subst; subst cnf; (try\n      inversion H2; inversion H4; subst;\n        inversion H4; contradict H8;\n          apply list_neq_length; simpl; lia).\n    \n    (* ghost-trans *)\n    subst cnf.\n    inversion H2.\n    contradict H15.\n    apply list_neq_length; simpl; lia.\n    \n    inversion H.\n    pose proof (H2 c m).\n    inversion H4.\n    apply current_to_instr_at in H_curr_inst_ret.\n    pose proof (H6 cnf pc).\n    unfold wp in H7.\n    rewrite H_curr_inst_ret in H7.\n    apply H7.\n    assumption.\n  Qed.\n  \n  \n  Lemma returning_conf_inv_exc : forall gv h o ars,\n    let cnf := (gv, h, exceptional o :: ars) in\n      locally_valid -> returning_conf p cnf -> ∥inv p ∥ cnf.\n  Proof.\n    intros.\n    inversion H0; subst.\n    inversion H2.\n    inversion H4; subst; inversion H3; inversion H1.\n    subst.\n    inversion H1; subst.\n  Qed.\n  \n  \n  Lemma no_double_exc_trans : forall c gv h o1 o2 ars, trans p c (gv, h, exceptional o1 :: exceptional o2 :: ars) -> exists gv', exists h', c = (gv', h', exceptional o1 :: exceptional o2 :: ars).\n    intros.\n    inversion H; subst.\n    inversion H2; subst; try (inversion H1; inversion H1; subst).\n  inversion H0; subst.\n  Qed.\n  \n  \n  Corollary no_double_exceptional : forall exec gv h o1 o2 ars,\n      execution_of p (exec ++ (gv, h, exceptional o1 :: exceptional o2 :: ars) :: nil) -> False.\n    destruct exec using rev_ind; intros.\n    inversion H; subst.\n    assert (initial_conf (gv, h, exceptional o1 :: exceptional o2 :: ars)).\n      apply H0.\n      reflexivity.\n    inversion H2.\n    rewrite <- list_rearrange in H.\n    generalize H; intros H_exec.\n    apply exec_impl_trans in H.\n    apply no_double_exc_trans in H.\n    elim H; clear H; intros.\n    elim H; clear H; intros.\n    subst.\n    apply sub_execution2 in H_exec.\n    apply IHexec in H_exec.\n    contradict H_exec.\n  Qed.\n  \n  \n  Lemma initial_conf_valid :\n    forall c,\n      locally_valid ->\n      execution_of p (c::nil) ->\n      valid_exec (c::nil).\n    \n    intros.\n    destruct c as ((gv, h), ars).\n    destruct ars.\n    contradict H0.\n    intro.\n    apply (no_empty_ar_stack ((gv, h, nil)::nil) gv h); auto with datatypes.\n    assert (∥inv p ∥ (gv, h, a::ars)).\n      inversion H.\n      inversion H0.\n      elim H2; intros.\n      apply (H7 (gv, h, a::ars)).\n      apply initial_default.\n      apply H3.\n      reflexivity.\n    destruct a.\n    set (c0 := (gv, h, normal c m l s l0 :: ars)) in * |- *.\n    apply (ve_cons c0 nil).\n    apply v_conf.\n    intros.\n    assumption.\n    intros.\n    inversion H.\n    elim H5; intros.\n    inversion H0.\n    subst.\n    assert (initial_conf c0).\n      apply H8; reflexivity.\n    inversion H10.\n    inversion H3.\n    rewrite H14.\n    rewrite H15.\n    rewrite H16.\n    apply (H6 c0).\n    apply initial_default.\n    assumption.\n    apply ve_nil.\n    inversion H0.\n    subst.\n    assert (initial_conf (gv, h, exceptional l :: ars)).\n      apply H2; reflexivity.\n    inversion H4.\n  Qed.\n  \n  \n\n  Lemma local_impl_global_prev_normal_then_ast_holds :\n    forall cnf cnf' exec a,\n        locally_valid ->\n        execution_of p (exec ++ cnf :: cnf' :: nil) ->\n        (forall exec' : execution,\n          execution_of p exec' ->\n          proper_prefix exec' (exec ++ cnf :: cnf' :: nil) ->\n          valid_exec exec') ->\n        normal_conf cnf' ->\n        current_ast p cnf' = Some a ->\n        ∥a ∥ cnf'.\n      intros until a.\n      intros H_p_lv H_exec IH.\n      intros.\n      destruct cnf as ((gv, h), ars). (* would like to be able to destruct .. using .. so I don't have to take care of the case where ar-stack is empty all the time. *)\n      destruct ars.\n      contradict H_exec.\n      intro.\n      apply no_empty_ar_stack with (gv := gv) (h := h) in H1.\n      assumption.\n      auto with datatypes.\n      \n      destruct a0.\n      set (cnf := (gv, h, normal c m l s l0 :: ars)) in * |- *.\n      \n      (* Normal predecessor *)\n        assert (H_wp: ∥ wp p c m l ∥ cnf -> ∥ a ∥ cnf').\n          assert (H_tmp: ∥ wp p c m l ∥ cnf <-> ∥ a ∥ cnf').\n            apply wp_correct_normal.\n            apply (exec_impl_trans exec cnf cnf').\n            assumption.\n            assumption.\n            assumption.\n          elim H_tmp; intros H' H''.\n          assumption.\n        \n        apply H_wp.\n        inversion H_p_lv as [H_all_lv].\n        elim (H_all_lv c m); intros H_inv_imp_pre H_proof_obl.\n        apply (H_proof_obl cnf).\n        apply (valid_exec_last_norm exec cnf).\n        apply IH.\n        apply sub_execution2 with (c' := cnf').\n        assumption.\n        apply proper_prefix_app.\n        apply proper_prefix_next.\n        apply proper_prefix_nil.\n        apply is_norm_conf.\n        reflexivity.\n        \n        \n        (* Exceptional predecessor *)\n        (* Show that l <> nil *)\n        destruct ars.\n        apply exec_impl_trans in H_exec.\n        inversion H_exec; subst.\n        inversion H3; subst; inversion H1.\n        inversion H1; subst.\n\n        (* a0 must be normal. *)\n        destruct a0.\n        \n        (* Case: it is normal. *)\n        set (ar := normal c m l0 s l1) in * |- *.\n        assert (H_ex_thrower : exists gv', exists h', In (gv', h', ar :: ars) (exec ++ (gv, h, exceptional l :: ar :: ars) :: nil)).\n          apply (all_ars_has_been_on_top) with (gv := gv) (h := h) (ars := exceptional l :: ar :: ars).\n          apply sub_execution2 with (c' := cnf').\n          assumption.\n          apply last_app.\n          apply last_base.\n          apply suffix_next.\n          apply suffix_here.\n          auto with datatypes.\n        \n        elim H_ex_thrower; intros gv' H_in_tmp.\n        elim H_in_tmp; intros h' H_in.\n        \n        apply in_but_not_last in H_in.\n        elim H_in; intros H_thrower.\n        inversion H_thrower.\n        assert (H_ex_pref_suff : exists ex_pref, exists ex_suff, exec = ex_pref ++ (gv', h', ar :: ars) :: ex_suff).\n          apply (In_split (gv', h', ar :: ars) exec).\n          assumption.\n        \n        elim H_ex_pref_suff; intros x H_ex_suff.\n        elim H_ex_suff; intros x0 H_ex.\n        set (cnfT := (gv', h', ar :: ars)) in * |- *.\n        \n        assert (valid_exec (x ++ cnfT::nil)).\n          apply IH.\n          assert (H_sub_exec : execution_of p exec).\n            destruct exec.\n            contradict H_ex.\n            auto with datatypes.\n            apply sub_execution with (suff := (gv, h, exceptional l :: ar :: ars) :: cnf' :: nil).\n            assumption.\n            subst.\n          (* rewrite H_ex in * |- *. *)\n          rewrite list_rearrange in H_sub_exec.\n          apply sub_execution with (suff := x0).\n          auto with datatypes.\n          rewrite H_ex.\n          rewrite app_ass.\n          apply proper_prefix_app.\n          rewrite <- app_comm_cons.\n          apply proper_prefix_next.\n          case x0.\n          apply proper_prefix_nil.\n          intros.\n          rewrite <- app_comm_cons.\n          apply proper_prefix_nil.\n        \n        assert (H_ast_cnft : ∥ ast_at p c m l0 ∥ cnfT).\n          apply (valid_exec_last x cnfT).\n          assumption.\n          apply is_norm_conf.\n          auto.\n        \n        inversion H_p_lv as [H_all_lv].\n        elim (H_all_lv c m); intros H_lv_ast H_lv_wp.\n        apply (H_lv_wp cnfT l0) in H_ast_cnft.\n        apply (wp_correct_exceptional gv h l c m l0 s l1 ars gv' h' cnf' a); auto.\n        apply (exec_impl_trans exec (gv, h, exceptional l :: ar :: ars) cnf').\n        assumption.\n        \n        (* Case: it is exceptional. *)\n        assert (execution_of p (exec ++ (gv, h, exceptional l :: exceptional l0 :: ars) :: nil)).\n          apply sub_execution2 with (c' := cnf').\n          assumption.\n        apply no_double_exceptional in H1.\n        contradiction.\n  Qed.\n\n  \n  \n  Lemma calling_conf_normal_conf : forall c, calling_conf p c -> normal_conf c.\n    intros.\n    inversion H; subst.\n    destruct ars.\n    inversion H0; subst.\n    inversion H1.\n    inversion H1.\n    destruct a.\n    apply is_norm_conf.\n    inversion H0; subst.\n    inversion H1; subst.\n    inversion H3; discriminate.\n    inversion H1.\n  Qed.\n  \n  \n  Theorem local_impl_global : locally_valid -> globally_valid.\n    intros.\n    unfold globally_valid.\n    intros exec H0.\n    apply (strong_exec_ind valid_exec).\n    apply ve_nil.\n    intros.\n    apply initial_conf_valid; assumption.\n    clear H0 exec.\n    intros exec c c' H0 IH.\n    \n    (* Inductive step. *)\n    destruct c' as ((gv', h'), ars').\n    destruct ars'.\n    contradict H0; intro.\n    apply (no_empty_ar_stack (exec ++ c :: (gv', h', nil) :: nil) gv' h'); auto with datatypes.\n    destruct a.\n    \n    (* Last conf: normal *)\n      rewrite list_rearrange.\n      apply ve_cons.\n      apply v_conf.\n      \n      (* Visible => Inv *)\n      intro H_visconf.\n      unfold visible_conf in H_visconf.\n      elim H_visconf.\n      (* Calling *)\n        intros H_c.\n        assert (∥ast_at p c0 m l ∥ (gv', h', normal c0 m l s l0 :: ars')).\n          apply local_impl_global_prev_normal_then_ast_holds with (cnf := c) (exec := exec); auto.\n          apply is_norm_conf.\n        \n        apply calling_conf_inv.\n        assumption.\n        assumption.\n        assumption.\n    \n      (* Returning *)\n        apply (returning_conf_inv gv' h' c0 m l s l0 ars').\n        assumption.\n        apply local_impl_global_prev_normal_then_ast_holds with (cnf := c) (exec := exec); auto.\n        apply is_norm_conf.\n        \n      (* C_i normal => ∥ast at C_i∥ C_i  holds. *)\n      intros H_normal a H_currast.\n      apply local_impl_global_prev_normal_then_ast_holds with (cnf := c) (exec := exec); auto.\n      apply IH.\n      apply sub_execution2 with (c' := (gv', h', normal c0 m l s l0 :: ars')).\n      assumption.\n      apply proper_prefix_app.\n      apply proper_prefix_next.\n      apply proper_prefix_nil.\n      \n    (* Last conf: exceptional *)\n      rewrite list_rearrange.\n      apply (ve_cons (gv', h', exceptional l :: ars') (exec ++ c :: nil)).\n      apply v_conf.\n      \n      (* Visible => Inv *)\n      intro H_visconf.\n      unfold visible_conf in H_visconf.\n      elim H_visconf.\n      intros.\n      inversion H1; subst.\n      inversion H3; subst.\n      inversion H5; subst; try inversion H2.\n      inversion H2.\n      intros.\n      apply (returning_conf_inv_exc gv' h' l ars').\n      assumption.\n      assumption.\n      intros.\n      inversion H1.\n      apply IH.\n      apply (sub_execution2 exec c (gv', h', exceptional l :: ars')).\n      assumption.\n      apply proper_prefix_app.\n      apply proper_prefix_next.\n      apply proper_prefix_nil.\n      assumption.\n    Qed.\n\nEnd validity.\n", "meta": {"author": "palmskog", "repo": "pcc", "sha": "2b16af3e282268e4f4adc9f6b7d3fda082b4a101", "save_path": "github-repos/coq/palmskog-pcc", "path": "github-repos/coq/palmskog-pcc/pcc-2b16af3e282268e4f4adc9f6b7d3fda082b4a101/theories/validity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.29108612035508524}}
{"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 Tests.AccumulatingAdderEnable.AccumulatingAdderEnable.\n\nDefinition bvadd {n} (a b : Signal.combType (Vec Bit n)) : Signal.combType (Vec Bit n) :=\n  N2Bv_sized n (Bv2N a + Bv2N b).\n\nDefinition bvzero {n} : Signal.combType (Vec Bit n) := N2Bv_sized n 0.\n\nDefinition bvsum {n} (l : list (Bvector n)) : Bvector n :=\n  fold_left bvadd l (N2Bv_sized n 0).\n\nDefinition accumulatingAdderEnableSpec\n           (i : list (combType (Vec Bit 8) * combType Bit))\n  : list (combType (Vec Bit 8)) * combType (Vec Bit 8) :=\n  fold_left\n    (fun acc_st v_en =>\n       let sum := bvadd (snd acc_st) (fst v_en) in\n       (fst acc_st ++ [sum], if (snd v_en : bool) then sum else snd acc_st))\n    i ([], bvzero).\n\nLemma addNCorrect n (a b : Vector.t bool n) :\n  addN (a, b) = bvadd a b.\nAdmitted.\nHint Rewrite addNCorrect using solve [eauto] : simpl_ident.\n\nLemma bvadd_comm {n} a b : @bvadd n a b = bvadd b a.\nProof. cbv [bvadd]. rewrite N.add_comm. reflexivity. Qed.\n\nLemma accumulatingAdderEnableSpec_snoc xs x :\n  accumulatingAdderEnableSpec (xs ++ [x]) =\n  let acc_st := accumulatingAdderEnableSpec xs in\n  let sum := bvadd (snd acc_st) (fst x) in\n  (fst acc_st ++ [sum], if (snd x : bool) then sum else snd acc_st).\nProof.\n  cbv [accumulatingAdderEnableSpec].\n  autorewrite with pull_snoc. cbn [fst snd].\n  reflexivity.\nQed.\n\nLemma accumulatingAdderEnableCorrect (i : list (Bvector 8 * bool)) :\n  simulate accumulatingAdderEnable i = fst (accumulatingAdderEnableSpec i).\nProof.\n  intros; cbv [accumulatingAdderEnable]. autorewrite with push_simulate.\n  cbn [step reset_state]. cbv [mcompose]. simpl_ident.\n  eapply fold_left_accumulate_invariant_seq\n    with (I:=fun t st acc =>\n               snd st = snd (accumulatingAdderEnableSpec (firstn t i))\n               /\\ acc = fst (accumulatingAdderEnableSpec (firstn t i)))\n         (P:=fun x => x = fst (accumulatingAdderEnableSpec i)).\n  { (* invariant holds after first step *)\n    split; reflexivity. }\n  { (* invariant holds through body *)\n    cbv zeta. intros ? ? ? d; intros; logical_simplify; subst.\n    repeat destruct_pair_let; cbn [fst snd]. simpl_ident.\n    rewrite firstn_succ_snoc with (d0:=d) by length_hammer.\n    rewrite accumulatingAdderEnableSpec_snoc. cbn [fst snd].\n    lazymatch goal with H : _ = snd (accumulatingAdderEnableSpec _) |- _ =>\n                        rewrite H end.\n    rewrite bvadd_comm. split; reflexivity. }\n  { (* invariant implies postcondition *)\n    intros; logical_simplify; subst.\n    rewrite firstn_all; 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/tests/AccumulatingAdderEnable/ListProofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283035, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.29108611386830824}}
{"text": "Require Import ExtLib.Data.HList.\nRequire Import ExtLib.Core.RelDec.\n\nRequire Import Charge.Logics.ILogic.\nRequire Import Charge.ModularFunc.ListType.\nRequire Import Charge.ModularFunc.BaseType.\nRequire Import Charge.ModularFunc.ListFunc.\nRequire Import Charge.ModularFunc.BaseFunc.\nRequire Import Charge.ModularFunc.SemiEqDecTyp.\nRequire Import Charge.Tactics.Base.DenotationTacs.\nRequire Import Charge.Tactics.Base.MirrorCoreTacs.\nRequire Import ExtLib.Tactics.\n\nRequire Import MirrorCore.TypesI.\nRequire Import MirrorCore.RTac.Core.\nRequire Import MirrorCore.Lambda.AppN.\nRequire Import MirrorCore.Lambda.Red.\nRequire Import MirrorCore.Lambda.RedAll.\nRequire Import MirrorCore.Lambda.Expr.\n\nSection Length.\n  Context {typ func : Type} {RType_typ : RType typ} {RSym_func : RSym func}\n          {BT : BaseType typ} {BTD : BaseTypeD BT}\n          {LT : ListType typ} {LTD: ListTypeD LT}.\n  Context {BF : BaseFunc typ func} {LF : ListFunc typ func}.\n  Context {RelDec_eq : RelDec (@eq typ)} {RelDecOk_eq : RelDec_Correct RelDec_eq}.\n  Context {Heqd : SemiEqDecTyp typ} {HeqdOk : SemiEqDecTypOk Heqd}.\n  \n   Context {EU : ExprUVar (expr typ func)}.\n\n  Context {RType_typOk : RTypeOk} {RsymOk_func : RSymOk RSym_func}.\n\n  Context {Typ0_tyProp : Typ0 _ Prop}.\n  Context {Typ2_tyArr : Typ2 _ Fun}.\n  \n  Context {Typ0Ok_tyProp : Typ0Ok Typ0_tyProp}.\n  Context {Typ2Ok_tyArr : Typ2Ok Typ2_tyArr}.\n    \n  Context {BFOk : BaseFuncOk typ func } {LFOk : ListFuncOk typ func}.\n\n  Let tyArr : typ -> typ -> typ := @typ2 _ _ _ _.\n  Let tyProp := @typ0 typ RType_typ Prop Typ0_tyProp.\n\n(* This function will return None unless lst eventually reaches nil. This means that we cannot partially evaluate a length of a list\n   (length 1::2::3::lst = 3 + (length lst) for instance). To be able to do this, we need a language that supports arithmetic operations\n   (at least +) on natural numbers. This is a perfectly natural thing to have, but it is not implemented at the moment. *)\n\n  Fixpoint lengthTacAux (t : typ) (lst : expr typ func) : option nat :=\n    match lst with\n      | App (App f x) xs =>\n        match listS f with\n          | Some (pCons _) =>\n            match lengthTacAux t xs with\n              | Some x => Some (S x)\n              | None => None\n            end\n          | _ => None\n        end\n      | _ => None\n    end.\n\n  Definition lengthTac  (_ : list (option (expr typ func))) (e : expr typ func) (args : list (expr typ func)) : expr typ func :=\n    match listS e, args with\n\t  | Some (pLength t), lst::nil =>\n\t    match baseS lst with\n\t      | Some (pConst u c) => \n\t        match type_cast (tyList t) u with\n\t          | Some pf => mkNat (natR (length (listD (eq_rect_r typD c pf))))\n\t          | None => apps e args\n\t        end\n\t      | _ =>\n\t        match lengthTacAux t lst with\n\t          | Some l => mkNat (natR l)\n\t          | None => apps e args\n\t        end\n\t    end\n\t  | _, _ => apps e args\n\tend.\n\n  Existing Instance Expr_expr.\n  Existing Instance ExprOk_expr.\n\n\nEnd Length.", "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/Lists/Length.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.29108611386830824}}
{"text": "From mathcomp Require Import\n     all_ssreflect\n     finmap.\n\nFrom AUChain Require Import\n     Parameters\n     Blocks\n     Messages\n     MessageTuple\n     BlockTree\n     LocalState.\n\nFrom RecordUpdate Require Import RecordSet. \n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** * Globalstate \n      This file contains the definition of a global state\n      together, as well as definitions for some types used in the\n      definition of [GlobalState].  \n**)\n\n(** The StateMap which is supposed to keep track of parties.\n    The parties are existentially quantified over their treeType. *)\n\nDefinition StateMap := finMap [choiceType of Party] LocalState.\n\nDefinition state_map0 : StateMap := fmap0.\nOpen Scope fmap.\n\nInductive Honesty : Set :=\n| Honest\n| Corrupt.\n\nDefinition bool_of_honesty (h : Honesty) :=\n  match h with\n  | Honest => true\n  | Corrupt => false\n  end.\n\nCoercion bool_of_honesty: Honesty >-> bool.\n\nDefinition honest_eq h h' :=\n  match h, h' with\n  | Honest, Honest => true\n  | Corrupt, Corrupt => true\n  | _, _ => false\n  end.\n\nLemma honest_eqP : Equality.axiom honest_eq.\nProof. by move=> [] []; apply/(iffP idP). Qed. \n\nCanonical Honest_eqMixin := Eval hnf in EqMixin honest_eqP.\nCanonical Honesty_eqType := Eval hnf in EqType Honesty Honest_eqMixin.\n\nInductive Progress : Set :=\n| Ready\n| Delivered\n| Baked.\n\nDefinition progress_eq p p' :=\n  match p, p' with\n  | Ready, Ready => true\n  | Delivered, Delivered => true\n  | Baked, Baked => true\n  | _, _ => false\n  end.\n\nLemma progress_eqP : Equality.axiom progress_eq.\nProof. by move=> [] []; apply/(iffP idP). Qed. \n\nCanonical Progress_eqMixin := Eval hnf in EqMixin progress_eqP.\nCanonical Progress_eqType := Eval hnf in EqType Progress Progress_eqMixin.\n\nParameter AdversarialState : Type.\nParameter AdvState0 : AdversarialState.\n\nDefinition History := seq Message. \n\n(** ** The GlobalState  *)\nRecord GlobalState :=\n  mkGlobalState {\n    (* The current slot of the world  *)\n    t_now : Slot;\n    (* All messages that yet has to be delivered *)\n    msg_buff : MessagePool;\n    (* A map of each party's local state *)\n    state_map : StateMap;\n    (* A global blockpool containing all blocks seen in thte world *)\n    history : History;\n    (* An adversary can update his state *)\n    adv_state : AdversarialState ;\n    (* Execution order for the next round*)\n    exec_order : Parties ;\n    (* A world state describing how far the world has progressed in this round *)\n    progress : Progress\n}.\n\nInstance GlobalStateSettable : Settable GlobalState :=\n  settable! mkGlobalState <t_now; msg_buff; state_map; history; adv_state; exec_order; progress>. \n\nDefinition tree_gb (tT : treeType) : tT := tree0.\n\nDefinition history0 : Messages := [::].\n\nDefinition msg_id0 := 0.\n\nParameter TreeTypeMap : Party -> treeType. \n\n(** Creates a new party with identifier pk. Is not set to new as this is\n    only to be used for the initial creations of parties where everybody\n    are new, but none should act as such. *)\n\nDefinition init_local (pk : Party): LocalState :=\n  mkLocalState pk (tree_gb (TreeTypeMap pk)).\n\nDefinition N0 : GlobalState :=\n  let state_map := foldr (fun pk acc => acc.[pk <- init_local pk]) state_map0 InitParties in\n  mkGlobalState 1 [::] state_map history0 AdvState0 InitParties Ready.\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/GlobalState.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283035, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.29108611386830824}}
{"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 PBFT_A_1_7.\nRequire Export PBFT_A_1_10.\n\n\nSection PBFT_A_1_11.\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  Context { pbft_hash_axioms : PBFThash_axioms  }.\n\n\n  (* the difference with PBFT_A_1_7 is that we have here [replica_has_correct_trace]\n     instead of [isCorrect] *)\n  Lemma PBFT_A_1_7_v2 :\n    forall (eo : EventOrdering)\n           (e  : Event)\n           (L  : list Event)\n           (i  : Rep)\n           (rd : RequestData)\n           (st : PBFTstate),\n      authenticated_messages_were_sent_or_byz_usys eo PBFTsys\n      -> In e L\n      -> exists_at_most_f_faulty L F\n      -> PBFTcorrect_keys eo\n      -> loc e = PBFTreplica i\n      -> state_sm_on_event (PBFTreplicaSM i) e = Some st\n      -> committed_log rd (log st) = true\n      ->\n      exists (R : list Rep),\n        no_repeats R\n        /\\ F < length R\n        /\\ nodes_have_correct_traces_before R L\n        /\\ forall (k : Rep),\n            In k R\n            ->\n            exists (e' : Event) (st' : PBFTstate),\n              e' ≼ e\n              /\\ loc e' = PBFTreplica k\n              /\\ state_sm_on_event (PBFTreplicaSM k) e' = Some st'\n              /\\ prepared_log rd (log st') = true.\n  Proof.\n    introv sendbyz ieL atmostbyz ckeys eqloc eqst comm.\n    apply is_committed_log_implies_is_committed_entry in comm; exrepnd; subst.\n    apply is_committed_entry_implies in comm1; repnd.\n    apply is_prepared_entry_implies in comm2; exrepnd.\n\n    assert (well_formed_log (log st)) as wfL by (eauto 3 with pbft).\n    assert (well_formed_log_entry entry) as wfe by (eapply well_formed_log_entry_if_in; eauto).\n\n    pose proof (select_good_guys_before eo (entry2com_senders entry) L F) as sel.\n    repeat (autodimp sel hyp);\n      try (apply implies_no_repeats_entry2com_senders; eauto 3 with pbft eo);[].\n    destruct sel as [G sel]; repnd; simpl in *.\n    rewrite length_entry2com_senders in sel1.\n\n    exists G; dands; auto; try omega;\n      try (complete (introv w z u v; subst; allrw in_map_iff; exrepnd; subst;\n                     eapply sel; eauto));[].\n\n    introv ik.\n    applydup sel0 in ik.\n\n    pose proof (in_entry2com_senders_implies_commit_in_log k entry (log st)) as expl.\n    repeat (autodimp expl hyp);[].\n    exrepnd.\n\n    dup expl1 as ilog.\n    eapply commits_are_received_or_generated in expl1;[|eauto];auto.\n    exrepnd.\n    apply or_comm in expl3; repndors;[|].\n\n    - destruct com, b; simpl in *.\n      subst i0 k.\n      pose proof (PBFT_A_1_6 eo e i s v a0 d st) as q.\n      repeat (autodimp q hyp);[].\n\n      exists e st; dands; eauto 2 with eo;\n        try (complete (rewrite <- expl2; auto));\n        try (complete (eapply sel; eauto; eauto 3 with eo;\n                       allrw; apply in_map_iff; eexists; dands; eauto)).\n\n    - exrepnd.\n      applydup localLe_implies_loc in expl1.\n\n      pose proof (ckeys e' i st1) as ck1; repeat (autodimp ck1 hyp); eauto 3 with eo pbft;[].\n\n      pose proof (commit_received_from_good_replica_was_in_log\n                    eo e' k com i) as w.\n      repeat (autodimp w hyp); try congruence;\n        try (complete (introv w z; eapply sel; eauto 3 with pbft eo));[].\n      exrepnd.\n\n      destruct com, b; simpl in *.\n      subst i0.\n      pose proof (PBFT_A_1_6 eo e'0 k s v a0 d st0) as q.\n      repeat (autodimp q hyp);[].\n\n      exists e'0 st0; dands; eauto 4 with eo;\n        try (complete (rewrite <- expl2; auto));\n        try (complete (apply (sel e'0 e); eauto; eauto 4 with eo;\n                       allrw; apply in_map_iff; eexists; dands; eauto)).\n  Qed.\n  Hint Resolve PBFT_A_1_7_v2 : pbft.\n\n  Lemma PBFT_A_1_11 :\n    forall (eo : EventOrdering)\n           (e1  : Event)\n           (e2  : Event)\n           (i   : Rep)\n           (j   : Rep)\n           (n   : SeqNum)\n           (v1  : View)\n           (v2  : View)\n           (d1  : PBFTdigest)\n           (d2  : PBFTdigest)\n           (st1 : PBFTstate)\n           (st2 : PBFTstate),\n      authenticated_messages_were_sent_or_byz_usys eo PBFTsys\n      -> PBFTcorrect_keys eo\n      -> exists_at_most_f_faulty [e1,e2] F\n      -> loc e1 = PBFTreplica i\n      -> loc e2 = PBFTreplica j\n      -> state_sm_on_event (PBFTreplicaSM i) e1 = Some st1\n      -> state_sm_on_event (PBFTreplicaSM j) e2 = Some st2\n      -> committed_log (request_data v1 n d1) (log st1) = true\n      -> committed_log (request_data v2 n d2) (log st2) = true\n      -> d1 = d2.\n  Proof.\n    introv auth ckeys atMost loci locj eqst1 eqst2 comm1 comm2.\n\n    eapply PBFT_A_1_7_v2 in comm1; try exact eqst1; auto; eauto 2 with pbft; simpl; tcsp;[].\n    eapply PBFT_A_1_7_v2 in comm2; try exact eqst2; auto; eauto 2 with pbft; simpl; tcsp;[].\n    exrepnd.\n\n    pose proof (A_1_10 eo e1 e2 R0 R n v1 v2 d1 d2) as q;\n      repeat (autodimp q hyp); eauto 3 with pbft eo;[|];\n        unfold more_than_F_have_prepared_before; dands; auto.\n  Qed.\n\nEnd PBFT_A_1_11.\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_11.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2910861138683082}}
{"text": "(*\n * Module: Multi\n *\n * Description:\n *  Prove a simple CFI policy on the transitive closure of the small-step\n *  transition relation.\n *)\n\n(* Load Coq Standard Library modules *)\nRequire Import Semantics.\nRequire Import SVAOS.\nRequire Import List.\nRequire Import Relations.\nRequire Import ICText.\nRequire Import ICProofs.\nRequire Import ThreadProofs.\nRequire Import ThreadTextProofs.\n\n(*\n * Define the multi function which creates multi-step relations.\n *)\nInductive multi {X:Type} (R: relation X) : relation X :=\n  | multi_refl : forall (x : X), multi R x x\n  | multi_step : forall (x y z : X),\n                 R x y -> multi R y z -> multi R x z.\n\n(*\nTactic Notation \"multi_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"multi_refl\" | Case_aux c \"multi_step\" ].\n*)\n\nDefinition multistep := multi step.\nNotation \" t '==>*' t' \" := (multistep t t') (at level 40).\n\n(*\n * Theorem: TransConditionsHold\n *\n * Description:\n *  This theorem shows that all of our very important conditions on the\n *  configuration holds over the transitive closure of the step relation.\n *)\nTheorem TransConditionsHold: forall (c1 c2 : config),\n  (pcInText c1) /\\\n  (validThreadIDs c1) /\\\n  (validCFG c1 (getCFG c1)) /\\\n  (In (getThread (getCurrThread c1) (getThreadList c1)) (getThreadList c1)) /\\\n  (textMappedLinear c1) /\\\n  (AreAllThreadICsInText (getThreadList c1) (c1)) /\\\n  (AreAllThreadSICsInText (getThreadList c1) (c1)) /\\\n  (validThreadList (getThreadList c1) (getCFG c1) (getCMMU c1) (getStore c1)) /\\\n  (In (getTH c1) (getCFG c1)) /\\\n  (validConfig c1) /\\\n  (textNotWriteable c1) /\\\n  (textMappedOnce c1) /\\\n  (threadListInText (getThreadList c1) (getCFG c1) (getCMMU c1)\n  (getTextStart c1) (getTextEnd c1)) /\\\n  (c1 ==>* c2)\n->\n  (pcInText c2) /\\\n  (validThreadIDs c2) /\\\n  (validCFG c2 (getCFG c2)) /\\\n  (In (getThread (getCurrThread c2) (getThreadList c2)) (getThreadList c2)) /\\\n  (textMappedLinear c2) /\\\n  (AreAllThreadICsInText (getThreadList c2) (c2)) /\\\n  (AreAllThreadSICsInText (getThreadList c2) (c2)) /\\\n  (validThreadList (getThreadList c2) (getCFG c2) (getCMMU c2) (getStore c2)) /\\\n  (In (getTH c2) (getCFG c2)) /\\\n  (validConfig c2) /\\\n  (textNotWriteable c2) /\\\n  (textMappedOnce c2) /\\\n  (threadListInText (getThreadList c2) (getCFG c2) (getCMMU c2)\n  (getTextStart c2) (getTextEnd c2)).\nProof.\nintros.\ndestruct H as [H1 H].\ndestruct H as [H2 H].\ndestruct H as [H3 H].\ndestruct H as [H4 H].\ndestruct H as [H5 H].\ndestruct H as [H6 H].\ndestruct H as [H7 H].\ndestruct H as [H8 H].\ndestruct H as [H9 H].\ndestruct H as [H10 H].\ndestruct H as [H11 H].\ndestruct H as [H12 H].\ndestruct H as [H13 H].\ninduction H.\nrepeat (split ; auto).\nsplit.\napply IHmulti.\napply stayPCInText with (c1 := x).\nrepeat (split ; auto).\napply threadIDsAlwaysValid with (c1 := x).\nrepeat (split ; auto).\nunfold validCFG.\napply cfg32.\napply alwaysValidCFG with (c1 := x).\nunfold validCFG in H3.\napply cfg23 in H3.\nauto.\napply threadAlwaysThere with (c1 := x).\nrepeat (split ; auto).\napply stayLinear with (c1 := x).\nrepeat (split ; auto).\napply stayICInText with (c1 := x).\nrepeat (split ; auto).\napply staySICInText with (c1 := x).\nrepeat (split ; auto).\napply threadsAlwaysValid with (c1 := x).\nrepeat (split ; auto).\napply alwaysGoodTH with (c1 := x).\nrepeat (split ; auto).\napply alwaysValid with (c1 := x).\nauto.\napply neverWriteText with (c1 := x).\nauto.\napply neverMapTextTwice with (c1 := x).\nrepeat (split ; auto).\napply TLAlwaysInText with (c1 :=x).\nrepeat (split ; auto).\n\napply IHmulti.\napply stayPCInText with (c1 := x).\nrepeat (split ; auto).\napply threadIDsAlwaysValid with (c1 := x).\nrepeat (split ; auto).\nunfold validCFG.\napply cfg32.\napply alwaysValidCFG with (c1 := x).\nunfold validCFG in H3.\napply cfg23 in H3.\nauto.\napply threadAlwaysThere with (c1 := x).\nrepeat (split ; auto).\napply stayLinear with (c1 := x).\nrepeat (split ; auto).\napply stayICInText with (c1 := x).\nrepeat (split ; auto).\napply staySICInText with (c1 := x).\nrepeat (split ; auto).\napply threadsAlwaysValid with (c1 := x).\nrepeat (split ; auto).\napply alwaysGoodTH with (c1 := x).\nrepeat (split ; auto).\napply alwaysValid with (c1 := x).\nauto.\napply neverWriteText with (c1 := x).\nauto.\napply neverMapTextTwice with (c1 := x).\nrepeat (split ; auto).\napply TLAlwaysInText with (c1 :=x).\nrepeat (split ; auto).\nQed.\n\nTheorem TranthreadsAlwaysValid: forall (c1 c2 : config),\n(validCFG c1 (getCFG c1)) /\\ (validConfig c1) /\\ (textNotWriteable c1) /\\\n(validThreadList (getThreadList c1) (getCFG c1) (getCMMU c1) (getStore c1)) /\\\n(getTextStart c1) <= (getPhysical (getTLB (getPC c1) (getCMMU c1))) <= (getTextEnd c1) /\\\n(threadListInText (getThreadList c1)\n  (getCFG c1)(getCMMU c1) (getTextStart c1) (getTextEnd c1)) /\\\n(textMappedOnce c1) /\\\n(pcInText c1) /\\\n(textMappedLinear c1) /\\\n(In (getTH c1) (getCFG c1)) /\\\n(AreAllThreadICsInText (getThreadList c1) c1) /\\\n(In (getThread (getCurrThread c1) (getThreadList c1)) (getThreadList c1)) /\\\n(validThreadIDs c1) /\\\n(AreAllThreadSICsInText (getThreadList c1) (c1)) /\\\n(c1 ==>* c2)\n->\n(validThreadList (getThreadList c2) (getCFG c2) (getCMMU c2) (getStore c2)).\nProof.\nintros.\ndestruct H as [vcfg H].\ndestruct H as [H1 H2].\ndestruct H2 as [H2 H3].\ndestruct H3 as [H4 H3].\ndestruct H3 as [H9 H3].\ndestruct H3 as [HA H3].\ndestruct H3 as [HE H3].\ndestruct H3 as [pc H3].\ndestruct H3 as [tml H3].\ndestruct H3 as [inth H3].\ndestruct H3 as [goodic H3].\ndestruct H3 as [inThread H3].\ndestruct H3 as [validTIDs H3].\ndestruct H3 as [goodsic H3].\ninduction H3.\nauto.\nassert (validThreadList (getThreadList y) (getCFG y) (getCMMU y) (getStore y)).\napply threadsAlwaysValid with (c1 := x).\nrepeat (split ; auto).\napply IHmulti.\nunfold validCFG.\napply cfg32.\napply alwaysValidCFG with (c1 := x).\nunfold validCFG in vcfg.\napply cfg23 in vcfg.\nauto.\napply alwaysValid with (c1 := x).\nauto.\napply neverWriteText with (c1 := x).\nauto.\napply threadsAlwaysValid with (c1 := x).\nrepeat (split ; auto).\napply stayPCInText with (c1 := x).\nrepeat (split ; auto).\napply TLAlwaysInText with (c1 :=x).\nrepeat (split ; auto).\napply neverMapTextTwice with (c1 := x).\nrepeat (split ; auto).\napply stayPCInText with (c1 := x).\nrepeat (split ; auto).\napply stayLinear with (c1 := x).\nrepeat (split ; auto).\napply alwaysGoodTH with (c1 := x).\nrepeat (split ; auto).\napply stayICInText with (c1 := x).\nrepeat (split ; auto).\nunfold validThreadList in H4.\nrepeat (split ; auto).\napply threadAlwaysThere with (c1 := x).\nrepeat (split ; auto).\napply threadIDsAlwaysValid with (c1 := x).\nrepeat (split ; auto).\napply staySICInText with (c1 := x).\nrepeat (split ; auto).\nQed.\n\nTheorem TransalwaysGoodTH: forall (c1 c2 : config),\n(c1 ==>* c2) /\\\n(In (getTH c1) (getCFG c1)) ->\n(In (getTH c2) (getCFG c2)).\nProof.\nintros.\ndestruct H as [H1 H2].\ninduction H1.\nauto.\napply IHmulti.\napply alwaysGoodTH with (c1 := x).\nrepeat (split ; auto).\nQed.\n\n(*\n * Theorem: Transcfisafe\n *\n * Description:\n *  Prove that the cfisafe theorem is true over the transitive closure of the\n *  step relation.\n *)\nTheorem Transcfisafe : forall (c1 c2 c3 c4: config),\n  (pcInText c1) /\\\n  (validThreadIDs c1) /\\\n  (validCFG c1 (getCFG c1)) /\\\n  (In (getThread (getCurrThread c1) (getThreadList c1)) (getThreadList c1)) /\\\n  (textMappedLinear c1) /\\\n  (AreAllThreadICsInText (getThreadList c1) (c1)) /\\\n  (AreAllThreadSICsInText (getThreadList c1) (c1)) /\\\n  (validThreadList (getThreadList c1) (getCFG c1) (getCMMU c1) (getStore c1)) /\\\n  (In (getTH c1) (getCFG c1)) /\\\n  (validConfig c1) /\\\n  (textNotWriteable c1) /\\\n  (textMappedOnce c1) /\\\n  (threadListInText (getThreadList c1) (getCFG c1) (getCMMU c1)\n  (getTextStart c1) (getTextEnd c1)) /\\\n  (c1 ==>* c3) /\\\n  (c3 ==> c4) /\\\n  (c4 ==>* c2)\n  ->\n  (getPC c4) = (getPC c3 + 1) \\/\n  (In (getPC c4) (getCFG c3)) \\/\n  ((vlookup (minus (getPC c4) 1) c4) = svaSwap) \\/\n  ((getPC c4) = (getICPC (itop (getThreadICList (getCurrThread c3) (getThreadList c3))))).\nProof.\nintros.\ndestruct H as [I1 I].\ndestruct I as [I2 I].\ndestruct I as [I3 I].\ndestruct I as [I4 I].\ndestruct I as [I5 I].\ndestruct I as [I6 I].\ndestruct I as [I7 I].\ndestruct I as [I8 I].\ndestruct I as [I9 I].\ndestruct I as [I10 I].\ndestruct I as [I13 I].\ndestruct I as [I14 I].\ndestruct I as [I15 I].\ndestruct I as [I16 I].\ndestruct I as [I17 I].\napply cfisafe.\nsplit.\nauto.\nsplit.\napply TranthreadsAlwaysValid with (c1 := c1).\nrepeat (split ; auto).\napply TransalwaysGoodTH with (c1 := c1).\nrepeat (split ; auto).\nQed.\n\n(*\n * Theorem: TranNXText\n *\n * Description:\n *   Prove that NXText holds over the transitive closure.\n *)\nTheorem TranNXText : forall (c1 c2 : config) (v : nat),\n(getTextStart c1) <= (getPhysical (getTLB v (getCMMU c1))) <= (getTextEnd c1) /\\\n(validConfig c1) /\\\n(textNotWriteable c1) /\\\n(textMappedOnce c1) /\\\nc1 ==>* c2\n-> (vLookup v (getCMMU c1) (getStore c1)) =\n   (vLookup v (getCMMU c2) (getStore c2)).\nProof.\nintros.\ndestruct H as [H1 H].\ndestruct H as [H2 H].\ndestruct H as [H3 H].\ndestruct H as [H4 H].\ninduction H.\n\n(* Case 1 *)\nauto.\n\n(* Case 2 *)\nassert ((vLookup v (getCMMU x) (getStore x)) = (vLookup v (getCMMU y) (getStore y))).\napply NXText.\nauto.\nrewrite <- IHmulti.\napply H5.\n\n(* Show that the intermediate configuration y is in the text section *)\napply alwaysInText with x.\nauto.\n\n(* Show that the intermediate configuration y is valid *)\napply alwaysValid with x.\nauto.\n\n(* Show that the intermediate configuration y has a non-writeable text section *)\napply neverWriteText with x.\nauto.\n\n(* Show that the intermediate configuration y has its text section only mapped once *)\napply neverMapTextTwice with x.\nauto.\nQed.\n\n", "meta": {"author": "jtcriswell", "repo": "Pudding", "sha": "1ea9885e213771bf923f9791b9bdf41a19a0be1e", "save_path": "github-repos/coq/jtcriswell-Pudding", "path": "github-repos/coq/jtcriswell-Pudding/Pudding-1ea9885e213771bf923f9791b9bdf41a19a0be1e/Multi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283033, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2910861138683082}}
{"text": "From aneris_examples.consensus Require Import paxos_prelude.\nFrom aneris.aneris_lang.lib Require Import map_proof.\n\nImport RecordSetNotations.\n\nSection paxos_learner.\n  Context `{!anerisG (Paxos_model params) Σ}.\n  Context `{!paxosG Σ params}.\n\n  Lemma learner_spec h (l : Learner) R T av :\n    let ip := ip_of_address (`l) in\n    is_set Acceptors av →\n    `l ⤇ learner_si -∗\n    h ↪[ip] (udp_socket (Some (`l)) true) -∗\n    `l @ learner_si ⤳# (R, T) -∗\n    WP learner int_serializer #(LitSocket h) av @[ip]\n    {{ v, ∃ (Q : gset Acceptor) (bal : Ballot) (val : Value) R T,\n            h ↪[ip] (udp_socket (Some (`l)) true) ∗\n            `l @ learner_si ⤳# (R, T) ∗\n            ⌜QuorumA Q⌝ ∗ ⌜v = $(bal, val)⌝ ∗\n            [∗ set] a ∈ Q, msgs_elem_of (msg2b a bal val) }}.\n  Proof.\n    iIntros (??) \"#Hl_si Hh Hl\". rewrite /learner.\n    wp_pures.\n    wp_apply wp_set_cardinal; [done|]; iIntros \"_\".\n    wp_pures.\n    wp_apply (wp_map_empty Ballot val); [done|].\n    iIntros (??).\n    wp_alloc lv as \"Hlv\".\n    do 4 wp_pure _.\n    (* loop invariant *)\n    iAssert (∃ m v, lv ↦[ip] v ∗ ⌜is_map v m⌝ ∗\n                    [∗ map] bal ↦ xv ∈ m,\n                    ∃ (X : gset Acceptor) val,\n                      ⌜is_set X xv⌝ ∗ shot bal val ∗\n                      ([∗ set] x ∈ X, msgs_elem_of (msg2b x bal val)))%I\n      with \"[Hlv]\" as \"H\".\n    { iExists ∅, _. iFrame. rewrite big_sepM_empty //. }\n    wp_pure _.\n    iLöb as \"IH\" forall (R T).\n    iDestruct \"H\" as (d vd) \"(Hlv & %Hd & Hmsgs)\".\n    wp_pures.\n    wp_bind (ReceiveFrom _).\n    wp_apply (aneris_wp_pers_receivefrom with \"[$Hh $Hl $Hl_si]\");\n      [done|done|done|].\n    iIntros (m) \"(Hh & Hl & (%a & %b & %z & %Hser & -> & #Hshot & #Hm))\".\n    wp_apply wp_unSOME; [done|]; iIntros \"_\".\n    wp_pures.\n    wp_apply (s_deser_spec learner_serialization); [done|]; iIntros \"_\".\n    wp_pures. wp_load. wp_pures.\n    wp_apply (wp_map_lookup $! Hd).\n    destruct (d !! b) as [p|] eqn:Heq; iIntros (? ->).\n    - wp_pures.\n      iDestruct (big_sepM_delete _ _ b p with \"Hmsgs\")\n        as \"[(%X & %v' & %HX & #Hshot' & #HX) Hmsgs]\"; [done|].\n      iDestruct (shot_agree with \"Hshot Hshot'\") as %<-.\n      wp_apply (wp_set_add $! HX).\n      iIntros (? HX').\n      wp_pures.\n      wp_apply wp_set_cardinal; [done|]; iIntros \"_\".\n      wp_op.\n      case_bool_decide as Hsize; wp_pures.\n      + iExists ({[a]} ∪ X), _, _, _, _. iFrame. iSplit.\n        { iPureIntro.\n          apply majority_show_quorum.\n          apply Nat2Z.inj_ge.\n          rewrite Hsize. lia. }\n        iSplit; [done|].\n        destruct (decide (a ∈ X)).\n        { by assert ({[a]} ∪ X = X) as -> by set_solver. }\n        rewrite big_sepS_union ?big_sepS_singleton; [|set_solver].\n        iFrame \"#\".\n      + wp_apply (wp_map_insert $! Hd).\n        iIntros (d' Hd').\n        wp_store.\n        wp_apply (\"IH\" with \"Hh Hl\").\n        iExists (<[b:= _]> d), _. iFrame. iSplit; [done|].\n        rewrite big_sepM_insert_delete.\n        iFrame.\n        iExists ({[a]} ∪ X), _. iFrame \"#\".\n        iSplit; [done|].\n        destruct (decide (a ∈ X)).\n        { by assert ({[a]} ∪ X = X) as -> by set_solver. }\n        rewrite big_sepS_union ?big_sepS_singleton; [|set_solver].\n        iFrame \"#\".\n    - wp_pures.\n      wp_apply (wp_set_empty Acceptor); [done|].\n      iIntros (? HX).\n      wp_pures.\n      wp_apply (wp_set_add $! HX).\n      iIntros (? HX').\n      wp_pures.\n      wp_apply wp_set_cardinal; [done|]; iIntros \"_\".\n      rewrite union_empty_r_L size_singleton.\n      wp_op.\n      case_bool_decide as Hsize; wp_pures.\n      + iExists {[a]}, _, _, _, _.\n        rewrite big_sepS_singleton //.\n        iFrame \"∗ #\".\n        iSplit; [|done].\n        iPureIntro.\n        apply majority_show_quorum.\n        rewrite size_singleton. lia.\n      + wp_apply (wp_map_insert $! Hd).\n        iIntros (d' Hd').\n        wp_store.\n        wp_apply (\"IH\" with \"Hh Hl\").\n        iExists (<[b:= _]> d), _. iFrame. iSplit; [done|].\n        rewrite big_sepM_insert //.\n        iFrame.\n        iExists {[a]}, _.\n        iFrame \"#\".\n        rewrite union_empty_r_L in HX'.\n        iSplit; [done|].\n        rewrite big_sepS_singleton //.\n  Qed.\n\nEnd paxos_learner.\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_learner.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2910861138683082}}
{"text": "Require compcertx.common.SmallstepX.\nRequire compcert.common.Behaviors.\n\nImport Classical.\nImport ClassicalEpsilon.\nImport Coqlib.\nImport Events.\nImport Globalenvs.\nImport Integers.\nImport SmallstepX.\n\nSet Implicit Arguments.\n\nExport Behaviors.\n\n(* A behavior is wrong both in a semantics and its erased version *)\n\nLemma semantics_without_retval_state_goes_wrong_intro {RETVAL: Type} (S: Smallstep.semantics RETVAL) (s: Smallstep.state S) (t: trace):\n  state_behaves S s (Goes_wrong t) ->\n  state_behaves (semantics_without_retval S) s (Goes_wrong t).\nProof.\n  inversion 1; subst.\n  econstructor; eauto.\n  intros r.\n  intro ABSURD.\n  inversion ABSURD; subst.\n  firstorder.\nQed.\n\nLemma semantics_without_retval_state_goes_wrong_elim {RETVAL: Type} (S: Smallstep.semantics RETVAL) (s: Smallstep.state S) (t: trace):\n  state_behaves (semantics_without_retval S) s (Goes_wrong t) ->\n  state_behaves S s (Goes_wrong t).\nProof.\n  inversion 1; subst.\n  econstructor; eauto.\n  intros r.\n  intro ABSURD.\n  apply (H3 tt).\n  econstructor; eauto.\nQed.\n\n(* Strong safety *)\n\nSection WITHRETVAL.\nContext {RETVAL: Type}.\n\nDefinition strongly_safe_state (S: Smallstep.semantics RETVAL) (s: Smallstep.state S) :=\n  forall t1 s1,\n    Smallstep.star (Smallstep.step S) (Smallstep.globalenv S) s t1 s1 ->\n    (exists r, Smallstep.final_state S s1 r) \\/\n    (exists t2 s2, Smallstep.step S (Smallstep.globalenv S) s1 t2 s2).\n\nDefinition strongly_safe_state_beh (S: Smallstep.semantics RETVAL) (s: Smallstep.state S) :=\n  ~ exists t, state_behaves S s (Goes_wrong t).\n\nLemma strongly_safe_state_beh_intro (S: Smallstep.semantics RETVAL) (s: Smallstep.state S):\n  strongly_safe_state S s ->\n  strongly_safe_state_beh S s.\nProof.\n  unfold strongly_safe_state, strongly_safe_state_beh.\n  intros H.\n  intro ABSURD.\n  destruct ABSURD as (t & Ht).\n  inversion Ht; subst.\n  unfold nostep in H2.\n  apply H in H1.\n  firstorder.\nQed.\n\nLemma strongly_safe_state_beh_elim (S: Smallstep.semantics RETVAL) (s: Smallstep.state S):\n  strongly_safe_state_beh S s ->\n  strongly_safe_state S s.\nProof.\n  unfold strongly_safe_state, strongly_safe_state_beh.\n  intros H t1 s1 H0.\n  destruct (Classical_Prop.classic (exists r, Smallstep.final_state S s1 r)); auto.\n  right.\n  destruct (Classical_Prop.classic (exists t2 s2, Step S s1 t2 s2)); auto.\n  destruct H.\n  exists t1.\n  econstructor; eauto.\n  unfold nostep.\n  firstorder.\nQed.\n\nDefinition strongly_safe (S: Smallstep.semantics RETVAL) :=\n  ~ exists t, program_behaves S (Goes_wrong t).\n\n\nEnd WITHRETVAL.\n\nLemma strongly_safe_without_retval {RETVAL: Type} (S: Smallstep.semantics RETVAL):\n  strongly_safe (semantics_without_retval S) <-> strongly_safe S.\nProof.\n  unfold strongly_safe.\n  split.\n  * intros H.\n    intro ABSURD.\n    apply H; clear H.\n    destruct ABSURD as (t & Ht).\n    inversion Ht; subst.\n    + exists t.\n      econstructor; eauto.\n      apply semantics_without_retval_state_goes_wrong_intro; auto.\n    + exists E0.\n      right; auto.\n  * intros H.\n    intro ABSURD.\n    destruct ABSURD as (t & Ht).\n    apply H; clear H.\n    inversion Ht; subst.\n    + exists t.\n      econstructor; eauto.\n      apply semantics_without_retval_state_goes_wrong_elim; auto.\n    + exists E0.\n      right; auto.\nQed.\n\n(* If the target language of a forward simulation is weakly determinate,\n   and if the source is strongly safe, then the target is strongly safe. *)\n\nTheorem forward_simulation_strongly_safe {RETVAL: Type} (S1 S2: Smallstep.semantics RETVAL):\n  receptive S1 ->\n  weak_determ S2 ->\n  forward_simulation S1 S2 ->\n  strongly_safe S1 ->\n  strongly_safe S2.\nProof.\n  intros H H0 X H1.\n  rewrite <- strongly_safe_without_retval in H1.\n  rewrite <- strongly_safe_without_retval.\n  apply semantics_without_retval_forward_to_backward in X; auto.\n  unfold strongly_safe in H1 |- * .\n  intro ABSURD.\n  destruct ABSURD as (t & BEH).\n  apply (backward_simulation_same_safe_behavior X) in BEH.\n  * firstorder.\n  * unfold not_wrong.\n    intros beh H2.\n    destruct beh; auto.\n    firstorder.\nQed.\n\nSection WITHMEMORYMODELOPS.\nContext `{memory_model_ops: Mem.MemoryModelOps}.\n\nLemma strongly_safe_with_inject_elim val `{VLIO: ValLessdefInjectOps val} (S: semantics (val * mem)) m:\n  strongly_safe (semantics_with_inject S m) ->\n  strongly_safe S.\nProof.\n  unfold strongly_safe.\n  intros H.\n  intro ABSURD.\n  destruct ABSURD as (t & ABSURD).\n  apply H; clear H.\n  inversion ABSURD; subst.\n  {\n    inversion H0; subst.\n    esplit.\n    eleft.\n    eassumption.\n    econstructor; eauto.\n    intros r.\n    intro ABSURD' .\n    inversion ABSURD' .\n    subst.\n    eapply H4; eauto.\n  }\n  esplit.\n  eright.\n  assumption.\nQed.\n\nEnd WITHMEMORYMODELOPS.\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/common/BehaviorsX.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2910861138683082}}
{"text": "Require Import Coq.Lists.List.\nImport ListNotations.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Bool.\n\nRequire Import util.\nRequire Import variables.\nRequire Import functions.\nRequire Import functions_fun_rules.\nRequire Import trans_rel.\nRequire Import states.\nRequire Import s_dfrs.\nRequire Import e_dfrs.\n\n(* The following hypotheses need to be properly formulated and proved\n   in order go guarantee that the functions defined here are sound:\n   they always yield elements whose corresponding well-formedness\n   properties hold. *)\n\nHypothesis asgmts_valid :\n  forall (l : list ASGMT), \n    (0 < (length l))\n    /\\ is_function l \n          (fun (asgmt1 asgmt2 : ASGMT)\n                => string_dec\n                     (fst asgmt1.(asgmt)).(vname)\n                     (fst asgmt2.(asgmt)).(vname)).\n\nHypothesis variables_valid :\n  forall (I O : SVARS) (T : STIMERS) (gcvar : (NAME * TYPE)),\n    ind_rules_dfrs_variables I O T gcvar.\n\nHypothesis states_valid :\n  forall (l : list STATE),\n    ind_rules_states l.\n\nHypothesis dfrs_states_valid :\n  forall (s : STATE) (ss : STATES),\n    ind_rules_dfrs_states s ss.\n\nHypothesis dfrs_trans_rel_valid :\n  forall (tr : TRANSREL),\n    ind_rules_dfrs_trans_rel tr.\n\nHypothesis e_dfrs_valid :\n  forall (vars : DFRS_VARIABLES) (sts : DFRS_STATES) (tr : DFRS_TRANSITION_RELATION),\n    ind_rules_e_dfrs vars sts tr.\n\nDefinition ranB (v : VALUE) : bool :=\n  match v with\n  | b _ => true\n  | _   => false\n  end.\n\nDefinition ranI (v : VALUE) : bool :=\n  match v with\n  | i _ => true\n  | _   => false\n  end.\n\nDefinition ranN (v : VALUE) : bool :=\n  match v with\n  | n _ => true\n  | _   => false\n  end.\n\nDefinition ble_value (t1 t2 : VALUE) : bool :=\n  match t1,t2 with\n  | i t1, i t2 => Z.leb t1 t2\n  | n t1, n t2 => Nat.leb t1 t2\n  | _, _ => false\n  end.\n\nDefinition blt_value (t1 t2 : VALUE) : bool :=\n  match t1,t2 with\n  | i t1, i t2 => Z.ltb t1 t2\n  | n t1, n t2 => Nat.ltb t1 t2\n  | _, _ => false\n  end.\n\nDefinition bne_value (t1 t2 : VALUE) : bool :=\n  match t1,t2 with\n  | b t1, b t2 => negb (eqb t1 t2)\n  | i t1, i t2 => negb (Z.eqb t1 t2)\n  | n t1, n t2 => negb (Nat.eqb t1 t2)\n  | _, _ => false\n  end.\n\nDefinition bgt_value (t1 t2 : VALUE) : bool :=\n  match t1,t2 with\n  | i t1, i t2 => Z.gtb t1 t2\n  | n t1, n t2 => negb (Nat.leb t1 t2)\n  | _, _ => false\n  end.\n\nDefinition bge_value (t1 t2 : VALUE) : bool :=\n  match t1,t2 with\n  | i t1, i t2 => Z.geb t1 t2\n  | n t1, n t2 => negb (Nat.ltb t1 t2)\n  | _, _ => false\n  end.\n\nFixpoint union_lists {X : Type} (ll : list (list X)) : list X :=\n  match ll with\n  | []     => []\n  | h :: t => List.app h (union_lists t)\n  end.\n\nFixpoint gen_possible_asgmts (v : VNAME) (l : list VALUE)  : list ASGMT :=\n  match l with\n  | []     => []\n  | h :: t => mkASGMT (v, h) :: gen_possible_asgmts v t\n  end.\n\nFixpoint possible_asgmts (ll : list (VNAME * list VALUE)) : list (list ASGMT) :=\n  match ll with\n  | []     => []\n  | h :: t => (gen_possible_asgmts (fst h) (snd h))\n                     :: possible_asgmts t\n  end.\n\nDefinition add_possible_assignment (a : ASGMT) (ll : list (list ASGMT)) : list (list ASGMT) :=\n  map (fun (l : list ASGMT) => a :: l) ll.\n\nFixpoint add_possible_assignments (l : list ASGMT) (ll : list (list ASGMT)) : list (list ASGMT) :=\n  match l with\n  | []      => []\n  | h :: tl => add_possible_assignment h ll\n               ++ add_possible_assignments tl ll\n  end.\n\nFixpoint gen_asgmts_combination (ll1 ll2 : list (list ASGMT)) : list (list ASGMT) :=\n  match ll1 with\n  | []      => [[]]\n  | h :: tl => add_possible_assignments h (gen_asgmts_combination tl ll2)\n  end.\n\n(** static_bexps_true *)\nFixpoint static_bexps_true (l : list (NAME * VALUE)) (be : BEXP) : bool :=\n  match l with\n  | []      => true\n  | f :: fs => if bstring_dec (fst f) (var_name be).(vname)\n               then (if ranB (snd f)\n                      then \n                        let\n                          eq_value := beq_value (snd f) be.(literal)\n                        in\n                          match be.(op) with\n                          | eq  => eq_value\n                          | ne  => negb eq_value\n                          | _   => false\n                          end\n                      else (if ranI (snd f) || ranN (snd f)\n                            then match be.(op) with\n                                 | le => ble_value (snd f) be.(literal)\n                                 | lt => blt_value (snd f) be.(literal)\n                                 | eq => beq_value (snd f) be.(literal)\n                                 | ne => bne_value (snd f) be.(literal)\n                                 | gt => bgt_value (snd f) be.(literal)\n                                 | ge => bge_value (snd f) be.(literal)\n                                 end\n                            else false))\n               else static_bexps_true fs be\n  end.\n\nDefinition minus_value (v1 v2 : VALUE) : VALUE :=\n  match v1, v2 with\n  | n n1, n n2 => (n (n1 - n2))\n  | i i1, i i2 => (i (i1 - i2))\n  | _   , _    => v1\n  end.\n\n(** timed_bexps_true *)\nFixpoint timed_bexps_true (l : list (NAME * VALUE)) (be : BEXP) \n  (gc : (NAME * (VALUE * VALUE))) : bool :=\n  match l with\n  | []      => true\n  | f :: fs => if bstring_dec (fst f) (var_name be).(vname)\n               then\n                  (if ranN (snd f)\n                  then (match be.(op) with\n                        | le => ble_value (minus_value (snd (snd gc)) \n                                                       (snd f)) be.(literal)\n                        | lt => blt_value (minus_value (snd (snd gc)) \n                                                       (snd f)) be.(literal)\n                        | eq => beq_value (minus_value (snd (snd gc))\n                                                       (snd f)) be.(literal)\n                        | ne => bne_value (minus_value (snd (snd gc))\n                                                       (snd f)) be.(literal)\n                        | gt => bgt_value (minus_value (snd (snd gc))\n                                                       (snd f)) be.(literal)\n                        | ge => bge_value (minus_value (snd (snd gc))\n                                                       (snd f)) be.(literal)\n                        end)\n                  else false)\n               else timed_bexps_true fs be gc\n  end.\n\n(** static_guards_true *)\nFixpoint values_in_static_bexps_true (be : list BEXP) (s : STATE) : bool :=\n  match be with\n  | []     => false\n  | h :: t => if (match h.(v) with\n                  | current _  => static_bexps_true (current_values s) h\n                  | previous _ => static_bexps_true (previous_values s) h\n                  end)\n              then true\n              else values_in_static_bexps_true t s\n  end.\n\nFixpoint static_guards_true (s : STATE) (conjs : list DISJ)\n  (IO T : list (VNAME * TYPE)) : bool :=\n  match conjs with\n  | []      => true\n  | h :: tl => (values_in_static_bexps_true h.(disjs) s)\n               && (static_guards_true s tl IO T)\n  end.\n\n(** timed_guards_true *)\nFixpoint values_in_timed_bexps_true (be : list BEXP) (s : STATE) \n  (gc : option (NAME * (VALUE * VALUE))) : bool :=\n  match be with\n  | []     => false\n  | h :: t => if (match h.(v) with\n                  | current _  => (match gc with\n                                   | Some e => timed_bexps_true \n                                                (current_values s) h e\n                                   | None   => false\n                                   end)\n                  | previous _ => (match gc with\n                                   | Some e => timed_bexps_true \n                                                (previous_values s) h e\n                                   | None   => false\n                                   end)\n                  end)\n              then true\n              else values_in_timed_bexps_true t s gc\n  end.\n\nFixpoint timed_guards_true (s : STATE) (conjs : list DISJ) \n  (T : list (VNAME * TYPE)) : bool :=\n  let\n    gc := get_gc s.(state)\n  in  \n    match conjs with\n    | []      => true\n    | h :: tl => (values_in_timed_bexps_true h.(disjs) s gc)\n                 && (timed_guards_true s tl T)\n    end.\n\n(** is_stable *)\nDefinition beq_state_element_current\n(e1 e2 : (NAME * (VALUE * VALUE))) : bool :=\n  bstring_dec (fst e1) (fst e2)\n  && beq_value (snd (snd e1)) (snd (snd e2)).\n\nDefinition beq_state_current (s1 s2 : STATE) : bool :=\n  bsame_list s1.(state) s2.(state) beq_state_element_current.\n\nFixpoint is_stable_entry (s : STATE) (IO T : list (VNAME * TYPE)) \n  (le : list (EXP * EXP * ASGMTS * REQUIREMENT)) : bool :=\n  match le with\n  | []     => true\n  | h :: t => if (negb (static_guards_true s (fst3 (fst h)).(conjs) IO T))\n                 ||\n                 (negb (timed_guards_true s (snd3 (fst h)).(conjs) T))\n                 ||\n                 beq_state_current s\n                           (nextState s T (trd3 (fst h)))\n               then is_stable_entry s IO T t\n               else false\n  end.\n\nDefinition is_stable (s : STATE) (IO T : list (VNAME * TYPE))\n  (F : list (list FUNCTION)) : bool :=\n  let\n    entries := union_lists \n                (map (fun f : FUNCTION => f.(function)) (union_lists F))\n  in\n   is_stable_entry s IO T entries.\n\nFixpoint make_trans_del (s : STATE) (I T : list (VNAME * TYPE))\n  (a : list (list ASGMT)) : list TRANS :=\n  match a with\n  | []     => []\n  | h :: t => let\n                nextSt := nextState s T (mkASGMTS h (asgmts_valid h))\n              in\n              let\n                delay := discrete 1\n              in\n              (mkTRANS (s, (del (delay, mkASGMTS h (asgmts_valid h))), \n                        mkSTATE (update_gc nextSt.(state) \n                                           nextSt.(state) delay)\n                                (state_valid (update_gc nextSt.(state) \n                                                        nextSt.(state) delay))))\n              :: make_trans_del s I T t\n  end.\n\nFixpoint make_trans_func (s : STATE) (IO T : list (VNAME * TYPE))\n  (le : list (EXP * EXP * ASGMTS * REQUIREMENT)) : list TRANS :=\n  match le with\n  | []     => []\n  | h :: t => if static_guards_true s (fst3 (fst h)).(conjs) IO T\n                &&\n                 timed_guards_true s (snd3 (fst h)).(conjs) T\n              then \n                ( if beq_state_current s (nextState s T (trd3 (fst h)))\n                  then\n                    make_trans_func s IO T t\n                  else\n                   (mkTRANS (s, (func (trd3 (fst h), snd h)),\n                            nextState s T (trd3 (fst h))))\n                   :: make_trans_func s IO T t\n                )\n              else make_trans_func s IO T t\n  end.\n\nDefinition genTransitions (s : STATE) (I O T : list (VNAME * TYPE)) \n  (F : list (list FUNCTION)) (possibilities : list (VNAME * list VALUE)) \n  : TRANSREL :=\n  let\n    entries := union_lists \n                (map (fun f : FUNCTION => f.(function)) (union_lists F))\n  in\n  let\n    combinations := gen_asgmts_combination\n                      (possible_asgmts possibilities) [[]]\n  in\n    if is_stable s (List.app I O) T F\n    then mkTRANSREL (make_trans_del s I T combinations)\n    else mkTRANSREL (make_trans_func s (I ++ O) T entries).\n\nFixpoint bin_state_list (v : list (NAME * (VALUE * VALUE))) \n  (l : list STATE) (comp : list (NAME * (VALUE * VALUE)) -> \n  list (NAME * (VALUE * VALUE)) -> bool) : bool :=\n  match l with\n  | []      => false\n  | h :: tl => if comp v h.(state) then true\n               else bin_state_list v tl comp\n  end.\n\nFixpoint get_list_states (l : list TRANS) (visited : list STATE) : list STATE :=\n  match l with\n  | []     => []\n  | h :: t => if bin_state_list (trd3 h.(STS)).(state) visited beq_state_elements\n              then get_list_states t visited\n              else trd3 h.(STS) :: get_list_states t visited\n  end.\n\n(* buildTR *)\nFixpoint buildTR (toVisit visited : list STATE) (I Out T : list (VNAME * TYPE))\n  (F : list (list FUNCTION)) (possibilities : list (VNAME * list VALUE))\n  (num : nat) : list TRANS :=\n  match toVisit, num with\n  | []    , _  => []\n  | _ :: _, 0    => []\n  | h :: t, S n' => let\n                      tr1 := genTransitions h I Out T F possibilities\n                    in\n                      if bin_state_list h.(state) visited beq_state_elements\n                      then buildTR t visited I Out T F possibilities n'\n                      else tr1.(transrel) ++ \n                           buildTR\n                            (t ++ (get_list_states tr1.(transrel) \n                                    (h :: visited)))\n                            (h :: visited) I Out T F possibilities n'\n  end.\n\nDefinition call_buildTR (toVisit visited : list STATE) \n  (I Out T : list (VNAME * TYPE)) (F : list (list FUNCTION)) (limiter : nat)\n  (possibilities : list (VNAME * list VALUE)) : list TRANS :=\n  let\n    numTR := limiter\n  in\n    buildTR toVisit visited I Out T F possibilities numTR.\n\n(* S to E *)\n\nFixpoint removeDuplicateStates (l : list STATE) : list STATE :=\n  match l with\n  | []     => []\n  | h :: t => if bin_state_list h.(state) t beq_state_elements\n              then removeDuplicateStates t\n              else h :: removeDuplicateStates t\n  end.\n\nDefinition expandedDFRS (sdfrs : s_DFRS) (limiter : nat)\n  (possibilities : list (VNAME * list VALUE)) : e_DFRS :=\n  let\n    TR := mkTRANSREL \n          (call_buildTR [sdfrs.(s_dfrs_initial_state).(s0)] \n           [] \n           sdfrs.(s_dfrs_variables).(I).(svars) \n           sdfrs.(s_dfrs_variables).(O).(svars) \n           sdfrs.(s_dfrs_variables).(T).(stimers)\n           [sdfrs.(s_dfrs_functions).(F)]\n           limiter possibilities)\n  in\n  let\n    states := removeDuplicateStates (\n              (get_list_states TR.(transrel) []) ++\n              [sdfrs.(s_dfrs_initial_state).(s0)])\n  in\n  let\n    dfrs_variables := (mkDFRS_VARIABLES sdfrs.(s_dfrs_variables).(I)\n                                        sdfrs.(s_dfrs_variables).(O)\n                                        sdfrs.(s_dfrs_variables).(T)\n                                        sdfrs.(s_dfrs_variables).(gcvar)\n                                        (variables_valid \n                                          sdfrs.(s_dfrs_variables).(I)\n                                          sdfrs.(s_dfrs_variables).(O)\n                                          sdfrs.(s_dfrs_variables).(T)\n                                          sdfrs.(s_dfrs_variables).(gcvar)))\n  in\n  let\n    dfrs_states := (mkDFRSSTATES \n                      (mkSTATES states (states_valid states))\n                      sdfrs.(s_dfrs_initial_state).(s0)\n                      (dfrs_states_valid\n                        sdfrs.(s_dfrs_initial_state).(s0)\n                        (mkSTATES states (states_valid states))))\n  in\n  let\n    dfrs_tr := (mkDFRSTRANSITIONREL \n                (mkTRANSREL TR.(transrel))\n                (dfrs_trans_rel_valid\n                  (mkTRANSREL TR.(transrel))))\n  in\n    mkE_DFRS\n      dfrs_variables (* Variables *)\n      dfrs_states (* States *)\n      dfrs_tr (* TRs *)\n      (e_dfrs_valid dfrs_variables dfrs_states dfrs_tr).\n", "meta": {"author": "igormeira", "repo": "DFRScoq", "sha": "d085aaead50aaaba5e424d2b893cb229a0b74858", "save_path": "github-repos/coq/igormeira-DFRScoq", "path": "github-repos/coq/igormeira-DFRScoq/DFRScoq-d085aaead50aaaba5e424d2b893cb229a0b74858/src/s2e_dfrs/s2e_dfrs_fun_rules.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2910861073815311}}
{"text": "Require Import Coq.Lists.List Fiat.Common\n        Fiat.Common.ilist\n        Fiat.Common.BoundedLookup\n        Fiat.Common.IterateBoundedIndex\n        Fiat.ADT.ADTSig\n        Fiat.ADT.Core\n        Fiat.ADTNotation.BuildADTSig\n        Fiat.ADTNotation.BuildADT\n        Fiat.ADTRefinement.Core Fiat.ADTRefinement.SetoidMorphisms\n        Fiat.ADTRefinement.GeneralRefinements\n        Fiat.ADTRefinement.GeneralBuildADTRefinements        \n        Fiat.ADTRefinement.BuildADTRefinements.HoneRepresentation\n        Fiat.ADTRefinement.BuildADTSetoidMorphisms.\n\n(* A generic refinement and honing tactic for applying a *)\n(* tactic to all the operations of an ADT built from [BuildADT]. *)\n\nSection RefineAllMethods.\n\n  Variable Rep : Type. (* The old representation type. *)\n\n  Lemma refineMethod_eq_sound :\n    forall arity Dom Cod\n           (cDef refinedCDef : methodType arity Rep Dom Cod),\n      refineMethod_eq _ arity cDef refinedCDef ->\n      let H := refinedCDef in refineMethod eq _ cDef H.\n  Proof.\n    simpl; intros; subst.\n    induction arity; simpl; intros.\n    - induction Dom; simpl; intros.\n      + destruct Cod; simpl in *.\n        * etransitivity.        \n          apply refine_under_bind; intros.\n          refine pick val (fst a); eauto; simplify with monad laws.\n          destruct a; simpl; finish honing.\n          simpl; autorewrite with monad laws; eapply H.\n        * etransitivity.\n          apply refine_under_bind; intros.\n          refine pick val a; eauto; simpl; finish honing.\n          simpl; autorewrite with monad laws; eapply H.\n      + eapply (IHDom (cDef d) (refinedCDef d)).\n        unfold refineMethod_eq; intros; eapply H.\n    - subst; simpl in *; eauto.\n  Qed.\n\n  Lemma refineADT_BuildADT_Rep_refine_All_eq\n        {n}\n        (methSigs : Vector.t methSig n)\n        (methDefs : ilist (B := @methDef Rep) methSigs)\n        (refined_methDefs : ilist (B := @methDef Rep) methSigs)\n    : Iterate_Ensemble_BoundedIndex (fun idx => refineMethod_eq _ _ (ith methDefs idx) (ith refined_methDefs idx))\n      -> refineADT\n           (BuildADT methDefs)\n           (BuildADT refined_methDefs).\n  Proof.\n    intros; eapply refineADT_BuildADT_Rep_refine_All with (AbsR := eq).\n    - revert H; clear; induction methSigs; simpl in *;\n      destruct methDefs; destruct refined_methDefs; try econstructor; simpl.\n      intros; destruct H; destruct prim_fst; destruct prim_fst0; econstructor; eauto.\n      destruct h; eapply (@refineMethod_eq_sound _ methDom methCod); eauto.\n  Qed.\n\nEnd RefineAllMethods.\n\nLtac ilist_of_evar1 B As k :=\n  lazymatch As with\n    | Vector.nil _ => k (@inil _ B)\n    | Vector.cons _ ?a ?n ?As' =>\n      makeEvar (B a)\n               ltac:(fun b =>\n                       ilist_of_evar1\n                         B As'\n                         ltac:(fun Bs' => k (icons (n := n) b Bs'))) \n  end.\n\nLtac refineEachMethod :=\n  lazymatch goal with\n  |- Sharpened (@BuildADT ?Rep _ _ ?consSigs ?methSigs ?consDefs ?methDefs) =>\n  ilist_of_evar1\n        (@methDef Rep)\n        methSigs\n        ltac:(fun rMeths =>\n                eapply refineADT_BuildADT_Rep_refine_All_eq\n                with (refined_methDefs := rMeths)                       \n             ); unfold refineMethod_eq;\n    simpl; repeat apply Build_prim_and; intros; \n    first [ instantiate (1 := {| methBody :=  _ |})\n          | eauto ]; simpl\n  end.\n\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/ADTRefinement/BuildADTRefinements/RefineAllMethods.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.29108610738153107}}
{"text": "Set Implicit Arguments.\nRequire Export LanguageModuleDef.\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 Case.\n\n(* Dan says, pg 65, we cannot derive \\Delta, \\alpha : A |-k- \\alpha : \\Kappa we we\n   can derive \\Delta, \\alpha : A |-k- \\alpha *: B.  \n\n   Let's prove this as I'm worried that he means Figure 3.6 \n        \\Delta |-k- \\tau : B -> \\Delta |-k- tau : A \n   is only to be applied to concrete types. \n\n  Or does he have a K for AK ? \n\n*)\n\nExample alpha_star_B :\n    K (D.ctxt (TV.var 0) A ddot) (ptype (tv_t (TV.var 0))) B.\nProof.\n  apply K_star_A. \n  eauto 20 with Chapter3.\nQed.\n\n(* Which invalidates the return progress theorem unless it's type is\n  restricted. This explains a lot. *)\n\nLemma can_K_alpha :\n  exists (d : Delta) (alpha : TV.T) (k1 k2 : Kappa),\n    K (D.ctxt alpha k1 d) (tv_t alpha) k2.\nProof.\n  apply ex_intro with (x:= ddot).\n  apply ex_intro with (x:= (TV.var 0)).\n  apply ex_intro with (x:= B).\n  apply ex_intro with (x:= B).\n  constructor.\n  reflexivity.\nQed.\n\nLemma can_K_alpha_A :\n  exists (d : Delta) (alpha : TV.T) (k1 k2 : Kappa),\n    K (D.ctxt alpha k1 d) (tv_t alpha) k2.\nProof.\n  apply ex_intro with (x:= ddot).\n  apply ex_intro with (x:= (TV.var 0)).\n  apply ex_intro with (x:= B).\n  apply ex_intro with (x:= A).\n  constructor.\n  constructor.\n  reflexivity.\nQed.\n\nLemma can_AK_alpha :\n  ~ exists (k1 k2 : Kappa),\n      AK (D.ctxt (TV.var 0) k1 ddot) (tv_t (TV.var 0)) k2.\nProof.\n  unfold not.\n  intros.\n  destruct H as [k1]; destruct H as [k2]; destruct k1; destruct k2; \n  try inversion H; try inversion H0; crush.\n  admit.\n  inversion H.\n  simpl in H3.\nAdmitted.\n\nLemma can_AK_alpha_A :\n  exists (d : Delta) (alpha : TV.T) (k1 k2 : Kappa),\n    K (D.ctxt alpha k1 ddot) (tv_t alpha) k2.\nProof.\n  apply ex_intro with (x:= ddot).\n  apply ex_intro with (x:= (TV.var 0)).\n  apply ex_intro with (x:= B).\n  apply ex_intro with (x:= A).\n  constructor.\n  constructor.\n  reflexivity.\nQed.\n\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/KindingTest.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.29108610738153107}}
{"text": "(* This file shows that the fancy update can be encoded in terms of the\nview shift, and that the laws of the fancy update can be derived from the\nlaws of the view shift. *)\nFrom stdpp Require Export coPset.\nFrom iris.proofmode Require Import proofmode.\nFrom iris.base_logic Require Export base_logic.\nFrom iris.prelude Require Import options.\n\n(* The sections add extra BI assumptions, which is only picked up with [Type*]. *)\nSet Default Proof Using \"Type*\".\n\nSection fupd.\nContext {M} (vs : coPset → coPset → uPred M → uPred M → uPred M).\n\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\") : bi_scope.\n\nContext (vs_ne : ∀ E1 E2, NonExpansive2 (vs E1 E2)).\nContext (vs_persistent : ∀ E1 E2 P Q, Persistent (P ={E1,E2}=> Q)).\n\nContext (vs_impl : ∀ E P Q, □ (P → Q) ⊢ P ={E,E}=> Q).\nContext (vs_transitive : ∀ E1 E2 E3 P Q R,\n  (P ={E1,E2}=> Q) ∧ (Q ={E2,E3}=> R) ⊢ P ={E1,E3}=> R).\nContext (vs_mask_frame_r : ∀ E1 E2 Ef P Q,\n  E1 ## Ef → (P ={E1,E2}=> Q) ⊢ P ={E1 ∪ Ef,E2 ∪ Ef}=> Q).\nContext (vs_frame_r : ∀ E1 E2 P Q R, (P ={E1,E2}=> Q) ⊢ P ∗ R ={E1,E2}=> Q ∗ R).\nContext (vs_exists : ∀ {A} E1 E2 (Φ : A → uPred M) Q,\n  (∀ x, Φ x ={E1,E2}=> Q) ⊢ (∃ x, Φ x) ={E1,E2}=> Q).\nContext (vs_persistent_intro_r : ∀ E1 E2 P Q R,\n  Persistent R →\n  (R -∗ (P ={E1,E2}=> Q)) ⊢ P ∗ R ={E1,E2}=> Q).\n\nDefinition fupd (E1 E2 : coPset) (P : uPred M) : uPred M :=\n  ∃ R, R ∗ vs E1 E2 R P.\n\nNotation \"|={ E1 , E2 }=> Q\" := (fupd E1 E2 Q) : bi_scope.\n\nGlobal Instance fupd_ne E1 E2 : NonExpansive (@fupd E1 E2).\nProof. solve_proper. Qed.\n\nLemma fupd_intro E P : P ⊢ |={E,E}=> P.\nProof. iIntros \"HP\". iExists P. iFrame \"HP\". iApply vs_impl; auto. Qed.\n\nLemma fupd_mono E1 E2 P Q : (P ⊢ Q) → (|={E1,E2}=> P) ⊢ |={E1,E2}=> Q.\nProof.\n  iIntros (HPQ); iDestruct 1 as (R) \"[HR Hvs]\".\n  iExists R; iFrame \"HR\". iApply (vs_transitive with \"[$Hvs]\").\n  iApply vs_impl. iIntros \"!> HP\". by iApply HPQ.\nQed.\n\nLemma fupd_trans E1 E2 E3 P : (|={E1,E2}=> |={E2,E3}=> P) ⊢ |={E1,E3}=> P.\nProof.\n  iDestruct 1 as (R) \"[HR Hvs]\". iExists R. iFrame \"HR\".\n  iApply (vs_transitive with \"[$Hvs]\"). clear R.\n  iApply vs_exists; iIntros (R). iApply vs_persistent_intro_r; iIntros \"Hvs\".\n  iApply (vs_transitive with \"[$Hvs]\"). iApply vs_impl; auto.\nQed.\n\nLemma fupd_mask_frame_r E1 E2 Ef P :\n  E1 ## Ef → (|={E1,E2}=> P) ⊢ |={E1 ∪ Ef,E2 ∪ Ef}=> P.\nProof.\n  iIntros (HE); iDestruct 1 as (R) \"[HR Hvs]\". iExists R; iFrame \"HR\".\n  by iApply vs_mask_frame_r.\nQed.\n\nLemma fupd_frame_r E1 E2 P Q : (|={E1,E2}=> P) ∗ Q ⊢ |={E1,E2}=> P ∗ Q.\nProof.\n  iIntros \"[Hvs HQ]\". iDestruct \"Hvs\" as (R) \"[HR Hvs]\".\n  iExists (R ∗ Q)%I. iFrame \"HR HQ\". by iApply vs_frame_r.\nQed.\nEnd fupd.\n", "meta": {"author": "amintimany", "repo": "iris", "sha": "03eaffa3b28bffc561b93f30a3ba40bab8ae1fd1", "save_path": "github-repos/coq/amintimany-iris", "path": "github-repos/coq/amintimany-iris/iris-03eaffa3b28bffc561b93f30a3ba40bab8ae1fd1/iris/base_logic/lib/fancy_updates_from_vs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953797290152, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2910034852974852}}
{"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(** Loop-unrolling. *)\n\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import Maps.\nRequire Import Compopts.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Globalenvs.\nRequire Import Switch.\nRequire Import Op.\nRequire Import Registers.\nRequire Cminor.\nRequire Import CminorSel.\nRequire Compopts.\n\nLocal Open Scope error_monad_scope.\n\n(** * iterated sequence *)\n\nFixpoint iterseq (count: nat) (s1 s2:stmt) : stmt :=\n match count with\n | 0%nat => s2\n | S n => Sseq s1 (iterseq n s1 s2)\n end.\n\n\n(** * Loop-unrolling\n\nWe perform loop-unrolling based on an external oracle that assigns\nthe number of loop-unfolds for each loop. The transformation fails\nwhenever one attempts to unfold a loop whose body has any label (but\nsucceeds if the oracle leave those loop untouched).\n*)\n\nDefinition unroll_flag n := andb (NPeano.Nat.eqb n O).\n\nFixpoint unroll_stmt b (guess: positive -> nat) (s: stmt) (pos:positive): res stmt:=\n  match s with\n  | Sseq s1 s2 => do s1' <- unroll_stmt b guess s1 (xO pos);\n                  do s2' <- unroll_stmt b guess s2 (xI pos);\n                  OK (Sseq s1' s2')\n  | Sifthenelse c s1 s2 => do s1' <- unroll_stmt b guess s1 (xO pos);\n                           do s2' <- unroll_stmt b guess s2 (xI pos);\n                           OK (Sifthenelse c s1' s2')\n  | Sloop s => let guess_pos := guess pos in\n               do s' <- unroll_stmt (unroll_flag guess_pos b) guess s (xO pos);\n               OK (iterseq guess_pos s' (Sloop s'))\n  | Sblock s => do s' <- unroll_stmt b guess s pos;\n                OK (Sblock s')\n  | Slabel i s => if b\n                  then (do s' <- unroll_stmt b guess s pos;\n                        OK (Slabel i s'))\n                  else Error (msg \"LoopUnroll: trying to unfold loop body with labels\")\n  | _ => OK s\n  end.\n\n(* [optim_loop_unroll_estimates] is the external oracle that assigns the\n  number of unfolds for each loop (declared in [Compopts.v])             *)\n\nDefinition unroll_function (ge: genv) (f: function) : res function :=\n  do body' <- unroll_stmt true (optim_loop_unroll_estimates f.(fn_body))\n                          f.(fn_body) xH;\n  OK (mkfunction\n        f.(fn_sig)\n        f.(fn_params)\n        f.(fn_vars)\n        f.(fn_stackspace)\n        body').\n\nDefinition unroll_fundef (ge: genv) (f: fundef) : res fundef :=\n  transf_partial_fundef (unroll_function ge) f.\n\n(** Conversion of programs. *)\n\nDefinition unroll_program (p: program) : res program :=\n  let ge := Genv.globalenv p in\n  transform_partial_program (unroll_fundef ge) p.\n\n", "meta": {"author": "haslab", "repo": "CircGen", "sha": "74a835abfc0477f51d6ee72db8f66caa6a544809", "save_path": "github-repos/coq/haslab-CircGen", "path": "github-repos/coq/haslab-CircGen/CircGen-74a835abfc0477f51d6ee72db8f66caa6a544809/cdg/backend/LoopUnroll.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2910034779690752}}
{"text": "From iris.program_logic Require Export language ectx_language ectxi_language.\nFrom st.prelude Require Export autosubst generic lang_base.\n\n(** The syntax of expressions *)\nInductive expr :=\n| Var (x : var)\n| LetIn (e1 : expr) (e2 : {bind 1 of expr})\n| Lam (e : {bind 1 of expr})\n(* | Fix (e : expr) *)\n(* | Rec (e : {bind 2 of expr}) *)\n| App (e1 e2 : expr)\n(* Base Types *)\n| Lit (l : base_lit)\n| BinOp (op : bin_op) (e1 e2 : expr)\n| If (e0 e1 e2 : expr)\n| Seq (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 : {bind expr}) (e2 : {bind expr})\n(* Recursive Types *)\n| Fold (e : expr)\n| Unfold (e : expr)\n(** Polymorphic Types *)\n(* | TLam (e : expr) *)\n(* | TApp (e : expr). *).\n\nInstance Ids_expr : Ids expr. derive. Defined.\nInstance Rename_expr : Rename expr. derive. Defined.\nInstance Subst_expr : Subst expr. derive. Defined.\nInstance SubstLemmas_expr : SubstLemmas expr. derive. Qed.\n\nInductive val :=\n| LamV (e : {bind 1 of expr})\n| LitV (v : base_lit)\n| PairV (v1 v2 : val)\n| InjLV (v : val)\n| InjRV (v : val)\n| FoldV (v : val).\n\nFixpoint of_val (v : val) : expr :=\n match v with\n | LamV e => Lam e\n | LitV v => Lit v\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 | FoldV v => Fold (of_val v)\n end.\n\nFixpoint to_val (e : expr) : option val :=\n match e with\n | Lam e => Some (LamV e)\n | Lit e => Some (LitV e)\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 | Fold e => v ← to_val e; Some (FoldV v)\n | _ => None\n end.\n\nFixpoint val_subst (v : val) (σ : var → expr) : val :=\n  match v with\n  | LamV e => LamV (e.[up σ])\n  | LitV v => LitV v\n  | PairV v1 v2 => PairV (val_subst v1 σ) (val_subst v2 σ)\n  | InjLV v => InjLV (val_subst v σ)\n  | InjRV v => InjRV (val_subst v σ)\n  | FoldV v => FoldV (val_subst v σ)\n  end.\n\nLemma to_of_val v : to_val (of_val v) = Some v.\nProof.\n by induction v; try simplify_option_eq; repeat f_equal; try apply (proof_irrel _).\nQed.\nLemma of_to_val e v : to_val e = Some v → of_val v = e.\nProof.\n revert v; induction e; intros v ?; simplify_option_eq; auto with f_equal.\nQed.\n\n(** Equality and other typeclass stuff *)\nInstance of_val_inj : Inj (=) (=) of_val.\nProof. by intros ?? Hv; apply (inj Some); rewrite -!to_of_val Hv. Qed.\n\nInstance base_lit_eq_dec : EqDecision base_lit.\nProof. solve_decision. Defined.\nInstance bin_op_eq_dec : EqDecision bin_op.\nProof. solve_decision. Defined.\nInstance expr_eq_dec : EqDecision expr.\nProof. solve_decision. Defined.\nInstance val_eq_dec : EqDecision val.\nProof.\n refine (λ v v', cast_if (decide (of_val v = of_val v')));\n   abstract naive_solver.\nDefined.\n\nGlobal Instance val_inhabited : Inhabited val := populate (LitV LitUnit).\n\n(** Evaluation contexts *)\nInductive ectx_item :=\n| LetInCtx (e2 : expr)\n| AppLCtx (e2 : expr)\n| AppRCtx (v1 : val)\n| PairLCtx (e2 : expr)\n| PairRCtx (v1 : val)\n| FstCtx\n| SndCtx\n| InjLCtx\n| InjRCtx\n| CaseCtx (e1 : {bind expr}) (e2 : {bind expr})\n| IfCtx (e2 : expr) (e3 : expr)\n| BinOpLCtx (op : bin_op) (e2 : expr)\n| BinOpRCtx (op : bin_op) (v1 : val)\n| SeqCtx (e2 : expr)\n| FoldCtx\n| UnfoldCtx.\n\nDefinition fill_item (Ki : ectx_item) (e : expr) : expr :=\n match Ki with\n | LetInCtx e2 => LetIn e e2\n | AppLCtx e2 => App e e2\n | AppRCtx v1 => App (of_val v1) e\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 | IfCtx e1 e2 => If e e1 e2\n | BinOpLCtx op e2 => BinOp op e e2\n | BinOpRCtx op v1 => BinOp op (of_val v1) e\n | SeqCtx e2 => Seq e e2\n | FoldCtx => Fold e\n | UnfoldCtx => Unfold e\n end.\n\n(** The stepping relation *)\n\nDefinition bin_op_eval (op : bin_op) (z1 z2 : Z) : val :=\n match op with\n | PlusOp => LitV $ LitInt (z1 + z2)%Z\n | MinusOp => LitV $ LitInt (z1 - z2)\n | LeOp => LitV $ LitBool $ bool_decide (z1 ≤ z2)%Z\n | LtOp => LitV $ LitBool $ bool_decide (z1 < z2)%Z\n | EqOp => LitV $ LitBool $ bool_decide (z1 = z2)\n end.\n\nDefinition state : Type := ().\n\nInductive head_step : expr → state → list Empty_set → expr → state → list expr → Prop :=\n(* β *)\n  LetIn_head_step e1 v1 e2 σ :\n   to_val e1 = Some v1 →\n   head_step (LetIn e1 e2) σ [] e2.[e1/] σ []\n| App_Lam_head_step e1 e2 v2 σ :\n   to_val e2 = Some v2 →\n   head_step (App (Lam e1) e2) σ [] e1.[e2/] σ []\n(* | App_Rec_head_step e1 e2 v2 σ : *)\n   (* to_val e2 = Some v2 → *)\n   (* head_step (App (Rec e1) e2) σ [] e1.[(Rec e1), e2/] σ [] *)\n(* fix *)\n(* | Fix_head_step e σ : *)\n    (* head_step (Fix (Lam e)) σ [] e.[Fix (Lam e)/] σ [] *)\n(* binary operation *)\n| BinOp_head_step op e1 e2 z1 z2 σ :\n   to_val e1 = Some (LitV $ LitInt z1) → to_val e2 = Some (LitV $ LitInt z2) →\n   head_step (BinOp op e1 e2) σ [] (of_val (bin_op_eval op z1 z2)) σ []\n(* if *)\n| If_True_head_step e1 e2 σ :\n   head_step (If (Lit $ LitBool true) e1 e2) σ [] e1 σ []\n| If_False_head_step e1 e2 σ :\n   head_step (If (Lit $ LitBool false) e1 e2) σ [] e2 σ []\n(* seq *)\n| Seq_Unit_head_step e1 e2 σ :\n    to_val e1 = Some (LitV LitUnit) →\n    head_step (Seq e1 e2) σ [] e2 σ []\n(* Products *)\n| Fst_Pair_head_step e1 v1 e2 v2 σ :\n   to_val e1 = Some v1 → to_val e2 = Some v2 →\n   head_step (Fst (Pair e1 e2)) σ [] e1 σ []\n| Snd_Pair_head_step e1 v1 e2 v2 σ :\n   to_val e1 = Some v1 → to_val e2 = Some v2 →\n   head_step (Snd (Pair e1 e2)) σ [] e2 σ []\n(* Sums *)\n| Case_InjL_head_step e0 v0 e1 e2 σ :\n   to_val e0 = Some v0 →\n   head_step (Case (InjL e0) e1 e2) σ [] e1.[e0/] σ []\n| Case_InjR_head_step e0 v0 e1 e2 σ :\n   to_val e0 = Some v0 →\n   head_step (Case (InjR e0) e1 e2) σ [] e2.[e0/] σ []\n(* Recursive Types *)\n| Unfold_Fold_head_step e v σ :\n   to_val e = Some v →\n   head_step (Unfold (Fold e)) σ [] e σ []\n(* Polymorphic Types *)\n(* | TBeta e σ : *)\n   (* head_step (TApp (TLam e)) σ [] e σ []. *).\n\nInstance fill_item_inj Ki : Inj (=) (=) (fill_item Ki).\nProof. destruct Ki; intros ???; simplify_eq/=; auto with f_equal. Qed.\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.\nLemma val_stuck e1 σ1 κ e2 σ2 efs :\n head_step e1 σ1 κ e2 σ2 efs → to_val e1 = None.\nProof. destruct 1; done. Qed.\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.\n destruct Ki; inversion_clear 1; simplify_option_eq; eauto.\nQed.\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\nLemma st_ectxi_lang_mixin : EctxiLanguageMixin of_val to_val fill_item head_step.\nProof.\n  split; eauto using to_of_val, of_to_val,\n  val_stuck, fill_item_val, fill_item_no_val_inj,\n head_ctx_step_val, fill_item_inj.\nQed.\n\nCanonical Structure STLCmu_ectxi_lang : ectxiLanguage := EctxiLanguage st_ectxi_lang_mixin.\nCanonical Structure STLCmu_ectx_lang : ectxLanguage := EctxLanguageOfEctxi STLCmu_ectxi_lang.\nCanonical Structure STLCmu_lang : language := LanguageOfEctx STLCmu_ectx_lang.\n\nLemma fill_val (e : expr) (K : list ectx_item):\n  is_Some (to_val (fill K e)) -> is_Some (to_val e).\nProof.\n  move=> [v h]. destruct (to_val e) eqn:eq.\n    by exists v0.\n    have fill_not_val: to_val (fill K e) = None. eauto using fill_not_val.\n    congruence.\nQed.\n\n(* Arguments val_stuck {_ _ _ _ _} _. *)\n(* Arguments fill_val {_ _} _. *)\n\n(* Wrapper around prim_step *)\n\nDefinition STLCmu_step (e1 e2 : expr) : Prop := prim_step e1 tt [] e2 tt [].\n\n(* We do not use forks, nor prophecy variables. *)\n\nLemma head_step_no_forks e σ κ e' σ' efs : head_step e σ κ e' σ' efs → efs = [].\nProof. intros H. by inversion H. Qed.\n\nLemma prim_step_no_forks (e : expr) σ κ e' σ' efs : prim_step e σ κ e' σ' efs → efs = [].\nProof. intros H. inversion H. by eapply head_step_no_forks. Qed.\n\nLemma head_step_no_obs e σ κ e' σ' efs : head_step e σ κ e' σ' efs → κ = [].\nProof. intros H. by inversion H. Qed.\n\nLemma prim_step_no_obs (e : expr) σ κ e' σ' efs : prim_step e σ κ e' σ' efs → κ = [].\nProof. intros H. inversion H. by eapply head_step_no_obs. Qed.\n\n(* Our language is deterministic *)\n\nLemma head_step_det e e1 σ1 κ1 σ1' efs1 e2 σ2 κ2 σ2' efs2 : head_step e σ1 κ1 e1 σ1' efs1 → head_step e σ2 κ2 e2 σ2' efs2 → e1 = e2.\nProof. intros H1 H2. inversion H1; inversion H2; ((by simplify_eq) || (try done) || simplify_eq; inversion G2). Qed.\n\nLemma prim_step_det (e e1 e2 : expr) σ κ : prim_step e σ κ e1 σ [] → prim_step e σ κ e2 σ [] → e1 = e2.\nProof.\n  intros H1 H2.\n  inversion H1. inversion H2. simplify_eq. simpl in *.\n  assert (K = K0) as <-.\n  { destruct (step_by_val K K0 _ _ σ κ e2'0 σ [] H4) as [Kred eq] ; try done; try by eapply val_stuck.\n    assert (H4' : fill K0 e1'0 = fill K e1'); first done.\n    destruct (step_by_val K0 K _ _ σ κ e2' σ [] H4') as [Kred' eq'] ; try done; try by eapply val_stuck.\n    rewrite eq in eq'. simpl in *. assert (length K = length (Kred' ++ Kred ++ K)). simpl in *. by rewrite -eq'.\n    do 2 rewrite app_length in H. assert (Kred = []) as ->. apply length_zero_iff_nil. lia. by rewrite eq. }\n  f_equal. assert (e1' = e1'0) as ->. apply (fill_inj K _ _ H4). by eapply head_step_det.\nQed.\n\n(* Our language is pure *)\n\nLemma prim_step_pure (e1 e2 : expr) σ1 σ2 κ efs : prim_step e1 σ1 κ e2 σ2 efs → pure_step e1 e2.\nProof.\n  intros Hprim.\n  assert (efs = []) as ->. by eapply prim_step_no_forks.\n  assert (κ = []) as ->. by eapply prim_step_no_obs.\n  destruct σ1, σ2.\n  split.\n  intros σ. destruct σ. rewrite /reducible_no_obs. by exists e2, tt, [].\n  intros.\n  assert (efs = []) as ->. by eapply prim_step_no_forks.\n  assert (κ = []) as ->. by eapply prim_step_no_obs.\n  destruct σ1, σ2. by erewrite (prim_step_det _ _ _ _ _ H).\nQed.\n\n(* Wrappers around lemmas *)\n\nLemma STLCmu_pure e1 e2 : STLCmu_step e1 e2 <-> pure_step e1 e2.\nProof.\n  split. apply prim_step_pure. intro H. inversion H.\n  destruct (pure_step_safe tt) as [e2' [σ [efs Hp]]].\n  destruct σ. by destruct (pure_step_det _ _ _ _ _ Hp) as [a [b [-> ->]]].\nQed.\n\nLemma STLCmu_step_ctx K `{!LanguageCtx K} e1 e2 : STLCmu_step e1 e2 → STLCmu_step (K e1) (K e2).\nProof. intro. apply STLCmu_pure. apply pure_step_ctx. auto. by apply STLCmu_pure. Qed.\n\nLemma rtc_STLCmu_step_ctx K `{!LanguageCtx K} e1 e2 : rtc STLCmu_step e1 e2 → rtc STLCmu_step (K e1) (K e2).\nProof. eauto using rtc_congruence, STLCmu_step_ctx. Qed.\n\nLemma nsteps_STLCmu_step_ctx K `{!LanguageCtx K} n e1 e2 : nsteps STLCmu_step n e1 e2 → nsteps STLCmu_step n (K e1) (K e2).\nProof. eauto using nsteps_congruence, STLCmu_step_ctx. Qed.\n\nLemma nsteps_PureExec (e1 e2 : expr) n : nsteps STLCmu_step n e1 e2 <-> PureExec True n e1 e2.\nProof.\n  split. intros s t. eapply nsteps_congruence with (f := id). by apply STLCmu_pure. auto.\n  intro H. eapply nsteps_congruence with (f := id). apply STLCmu_pure. apply pure_exec. auto.\nQed.\n\nLemma rtc_PureExec (e1 e2 : expr) : rtc STLCmu_step e1 e2 <-> ∃ n, PureExec True n e1 e2.\nProof.\n  split.\n  intro H. assert (H' : rtc pure_step e1 e2).\n  eapply rtc_subrel. by apply STLCmu_pure. auto. destruct (iffLR (rtc_nsteps _ _) H') as [n H'']. exists n. intros _. done.\n  intro d. destruct d as [n H]. eapply rtc_nsteps. exists n. by eapply nsteps_PureExec.\nQed.\n\nLemma step_PureExec (e1 e2 : expr) : STLCmu_step e1 e2 → PureExec True 1 e1 e2.\nProof. intros s t. apply nsteps_once. by apply STLCmu_pure. Qed.\n\nDefinition STLCmu_halts (e : STLCmu.lang.expr) : Prop :=\n  ∃ (v : STLCmu.lang.val), rtc STLCmu_step e (STLCmu.lang.of_val v).\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/lang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2910034779690752}}
{"text": "(* File: Cons_Counter_Model.v  (last edited on 27/10/2000) (c) Klaus Weich  *)\n\nFrom IPC Require Export Disjunct NDeco_Sound.\n\n\nFixpoint n2forest (n : nested_imps) : Forest atoms :=\n  match n with\n  | nil => Nil_Forest atoms\n  | Undecorated _ :: n => n2forest n\n  | Decorated _ k :: n => Cons_Forest atoms k (n2forest n)\n  end.\n\n\nRemark cons_counter_model_suc :\n forall (x : nimp) (k : kripke_tree) (ni : nested_imps) (a : atoms),\n In (Decorated x k) ni -> Suc k (node atoms a (n2forest ni)).\nintros x k ni a in_k.\nunfold Suc in |- *; apply successor_trans with k.\ngeneralize in_k; clear in_k.\nelim ni; clear ni.\nintros in_k.\ninversion_clear in_k.\nintros y ni ih in_k.\nunfold n2forest in |- *; simpl in |- *; fold n2forest in |- *.\ninversion_clear in_k.\n rewrite H; clear H y.\napply in_forest_head.\ngeneralize (ih H); clear ih H.\nintros ih.\ncase y; clear y.\nintros; assumption.\nintros; apply in_forest_tail; assumption.\napply successor_refl.\nQed.\n\n\n\nRemark in_forest_ex_a0a1b :\n forall (k : kripke_tree) (ni : nested_imps),\n In_Forest atoms k (n2forest ni) -> exists x : nimp, In (Decorated x k) ni.\nintros k ni.\nelim ni; clear ni.\nintros in_k.\ninversion_clear in_k.\nunfold n2forest in |- *; simpl in |- *; fold n2forest in |- *.\nintros x; case x; clear x.\nintros x ni ih in_k.\nelim ih; clear ih.\nintros y in_y.\nexists y.\nright; assumption.\nassumption.\nintros x k0 ni ih in_k.\ninversion_clear in_k.\nexists x.\nleft; trivial.\nelim ih; try assumption.\nintros x0 in_k.\nexists x0.\nright; assumption.\nQed.\n\n(**********************************************************************)\n\n\nRemark deco_sound_in_forest_forces :\n forall (work : nf_list) (ds : disjs) (ni : nested_imps)\n   (ai : atomic_imps) (a : atoms) (k : kripke_tree)\n   (c : normal_form),\n deco_sound work ds ni ai a ->\n In_Forest atoms k (n2forest ni) ->\n in_ngamma work ds ni ai a c -> forces_t k (nf2form c).\nintros work ds ni ai a k c complete in_k in_ngamma.\nelim in_forest_ex_a0a1b with k ni; try assumption.\nintros x; case x; clear x.\nintros a0 a1 b in_x.\nelim (complete k a0 a1 b in_x); clear complete.\nintros k_is_mon k_forces_ngamma k_notforces_a0a1.\napply k_forces_ngamma.\nassumption.\nQed.\n\n(**********************************************************************)\n\n\nRemark cons_counter_model_mon :\n forall (ni : nested_imps) (ai : atomic_imps) (a : atoms),\n (forall x : nimp, In (Undecorated x) ni -> False) ->\n deco_sound nf_nil DNil ni ai a ->\n Is_Monotone_kripke_tree (node atoms a (n2forest ni)).\nintros ni ai a.\nelim ni; clear ni.\nintros all_ref complete.\nunfold n2forest in |- *.\nsimpl in |- *.\nunfold Is_Monotone_kripke_tree in |- *.\napply is_monotone_tree_intro.\napply is_monotone_forest_nil.\n\nintros ni; case ni; clear ni.\nintros x ni ih all_ref complete.\nelimtype False.\napply (all_ref x).\nleft; trivial.\nintros x; case x; clear x.\nintros a0 a1 b k ni ih all_ref complete.\nunfold n2forest in |- *; simpl in |- *; fold n2forest in |- *.\nelim (complete k a0 a1 b).\nintros k_is_mon k_forces_ngamma k_notforces_a0a1.\nunfold Is_Monotone_kripke_tree in |- *.\napply is_monotone_tree_intro.\napply is_monotone_forest_cons.\nintros i forces_i.\nchange (forces_t k (Atom i)) in |- *.\napply k_forces_ngamma with (c := NAtom i).\napply In_Atoms; assumption.\nassumption.\ncut (Is_Monotone_kripke_tree (node atoms a (n2forest ni))).\nintros claim.\ninversion_clear claim; assumption.\napply ih; clear ih.\nintros x in_x.\napply all_ref with x.\nright; assumption.\napply deco_sound_cons_ni_tail with (Decorated (NImp a0 a1 b) k); assumption.\nleft; trivial.\nQed.\n\n\n(**********************************************************************)\n\nInductive Cons_Counter_Model_Spec (goal : Int) (ni : nested_imps)\n(ai : atomic_imps) (a : atoms) : Set :=\n    cons_counter_model_intro :\n      forall k : kripke_tree,\n      Is_Monotone_kripke_tree k ->\n      forces_ngamma nf_nil DNil ni ai a k ->\n      (forces_t k (Atom goal) -> False) ->\n      Cons_Counter_Model_Spec goal ni ai a.\n\n\n\nRemark all_ref_rev_app_nil :\n forall (dni : decorated_nested_imps) (x : nimp),\n In (Undecorated x) (rev_app dni NNil) -> False.\nintros dni x.\nelim dni; clear dni.\nsimpl in |- *.\nintros; assumption.\nintros a; case a; clear a.\nintros y k dni ih.\nsimpl in |- *.\n rewrite (rev_app_app dni (Decorated y k :: NNil)).\nintros in_x.\napply ih.\n rewrite (rev_app_app dni NNil).\napply in_or_app.\ncut\n (In (Undecorated x) (rev_app dni NNil) \\/\n  In (Undecorated x) (Decorated y k :: NNil)).\nintros claim.\nelim claim; clear claim; intro claim.\nleft; assumption.\nright; inversion_clear claim.\n discriminate H.\nassumption.\napply in_app_or.\nassumption.\nQed.\n\n\n\nRemark nth_nimp__nth_nested_imp :\n forall (x : nimp) (n : nat) (ni : nested_imps),\n my_nth nimp n (nested_imps2nimps ni) x ->\n {y : nested_imp | my_nth nested_imp n ni y /\\ nested_imp2nimp y = x}.\nintros x n.\nelim n; clear n.\nintros ni; case ni; clear ni.\nintros nth; elimtype False; inversion_clear nth.\nsimpl in |- *; intros y ni nth.\nexists y.\nsplit.\napply My_NthO.\ninversion_clear nth.\ntrivial.\nintros n ih ni.\ncase ni; clear ni.\nintros nth; elimtype False; inversion_clear nth.\nintros y ni nth.\nelim (ih ni).\nintros y' nth'.\nexists y'.\nelim nth'; clear nth'; intros nth' eq.\nsplit.\napply My_NthS; assumption.\nassumption.\ninversion_clear nth; assumption.\nQed.\n\n(***********************************************************************)\n\nLemma cons_counter_model :\n forall (i : Int) (dni : decorated_nested_imps) (ai : atomic_imps)\n   (a : atoms),\n deco_sound nf_nil DNil (rev_app dni NNil) ai a ->\n a_ai_disj a ai ->\n a_goal_disj a i -> Cons_Counter_Model_Spec i (rev_app dni NNil) ai a.\nintros i dni ai a complete a_ai_disjunct a_goal_disj.\ncut (Is_Monotone_kripke_tree (node atoms a (n2forest (rev_app dni NNil)))).\nintro mon.\nexists (node atoms a (n2forest (rev_app dni NNil))).\n\napply mon.\n\nunfold forces_ngamma in |- *.\nintros c in_c.\nelim in_c; clear in_c c.\n\nintros n c nth.\ninversion_clear nth.\n\nintros n a0 a1 nth.\ninversion_clear nth.\n\nintros n x; case x; clear x.\nintros a0 a1 b nth.\nsimpl in |- *; apply forces_t_imp.\nassumption.\nintros forces_a0a1.\nelimtype False.\nelim (nth_nimp__nth_nested_imp (NImp a0 a1 b) n (rev_app dni NNil) nth).\nintros x; case x; clear x.\nintros x nth_x.\napply all_ref_rev_app_nil with dni x.\napply nth_in with n.\nelim nth_x; intros; assumption.\nintros x k nth_x.\nelim (complete k a0 a1 b).\nintros k_is_mon k_forces_ngamma k_notforces_a0a1.\napply k_notforces_a0a1.\napply forces_t_mon with (node atoms a (n2forest (rev_app dni NNil))).\nassumption.\nassumption.\napply cons_counter_model_suc with x.\napply nth_in with n.\nelim nth_x; intros; assumption.\napply nth_in with n.\nelim nth_x; clear nth_x; intros nth_x eq.\n rewrite <- eq.\nassumption.\nsimpl in |- *.\nintros k' in_k'.\nchange (forces_t k' (nf2form (NImp_NF (NImp a0 a1 b)))) in |- *.\napply deco_sound_in_forest_forces with nf_nil DNil (rev_app dni NNil) ai a.\nassumption.\nassumption.\napply In_Nested_Imps with n; assumption.\n\nintros j b n bs lookup_j nth.\nsimpl in |- *; apply forces_t_imp.\nassumption.\nintros forces_j.\nelimtype False.\napply a_ai_disjunct with j bs; assumption.\nsimpl in |- *.\nintros k' in_k'.\nchange (forces_t k' (nf2form (AImp j b))) in |- *.\napply deco_sound_in_forest_forces with nf_nil DNil (rev_app dni NNil) ai a.\nassumption.\nassumption.\napply In_Atomic_Imps with (i := j) (b := b) (n := n) (bs := bs); assumption.\n\nintros j lookup_j.\nassumption.\n\nassumption.\napply cons_counter_model_mon with ai; try assumption.\nintros x in_x.\napply all_ref_rev_app_nil with dni x; assumption.\nQed.\n\n\n", "meta": {"author": "coq-contribs", "repo": "ipc", "sha": "eab92b40792d59a991abfba2e2e6af6aa2d18031", "save_path": "github-repos/coq/coq-contribs-ipc", "path": "github-repos/coq/coq-contribs-ipc/ipc-eab92b40792d59a991abfba2e2e6af6aa2d18031/theories/Cons_Counter_Model.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2910034779690752}}
{"text": "From MetaCoq.PCUIC Require Import PCUICAst PCUICAstUtils PCUICLiftSubst.\nFrom MetaCoq.PCUIC Require TemplateToPCUIC PCUICToTemplate.\n\nFrom MetaCoq.Template Require Import config monad_utils utils TemplateMonad.\nFrom MetaCoq.Template Require Ast.\nImport MonadNotation.\n\nRequire Import List String Relation_Operators.\nImport ListNotations.\n\nRequire Import non_uniform.\n\nDefinition clift0 (n : nat) (t : context_decl) : context_decl :=\n  {| decl_name := t.(decl_name);\n     decl_body := match t.(decl_body) with\n                   | Some q => Some (lift0 n q)\n                   | None => None\n                  end;\n     decl_type := lift0 n t.(decl_type)\n  |}.\n\nDefinition subterms_for_constructor\n           (refi : inductive)\n           (ref   : term) (* we need the term for exactly this inductive just for the substition *)\n           (ntypes : nat) (* number of types in the mutual inductive *)\n           (npars : nat) (* number of parameters in the type *)\n           (nind : nat) (* number of proper indeces in the type *)\n           (ct    : term) (* type of the constructor *)\n           (ncons : nat) (* index of the constructor in the inductive *)\n           (nargs : nat) (* number of arguments in this constructor *)\n                  : list (nat * term * nat)\n  := let indrel := (ntypes - inductive_ind refi - 1) in\n    let '(ctx, ap) := decompose_prod_assum [] ct in\n    (*    ^ now ctx is a reversed list of assumptions and definitions *)\n    let len := List.length ctx in\n    let params := List.skipn (len - npars) (ctx) in\n    let inds := List.skipn npars (snd (decompose_app ap)) in\n    (* d is a list of occurences of subterms in arguments to the constructor *)\n    let d :=List.concat (\n           (* so this i represents distance from return object to `t` *)\n              mapi (fun i t =>\n                      let '(ctx, ar) := decompose_prod_assum [] (decl_type t)\n                      in let p := (indrel + (len - i - 1) + List.length (ctx))\n                      in let (f, s) := decompose_app ar\n                      in match f with\n                         | tRel j => if Nat.eqb p j\n                                    then [(i, ctx, s)]\n                                    else []\n                         | _ => []\n                         end) ctx) in\n    let '(ctx_sbst, _) := decompose_prod_assum [] (subst1 ref indrel ct) in\n    let construct_cons :=\n        fun (* index of a subterm in this constructor *)\n          (i: nat)\n          (* these are arguments for the function\n             that is a parameter of the constructor\n             and if applied fully returns something of the needed type *)\n          (ctx': context)\n          (* these are arguments of the type of the subterm *)\n          (args' : list term) =>\n          let len' := List.length ctx' in\n          let ctxl' :=\n              let pr := it_mkProd_or_LetIn ctx' (tVar \"ignore me\") in\n              let lifted := lift0 (1+i) pr in\n              let (c,_) := decompose_prod_assum [] lifted in\n              c in\n          it_mkProd_or_LetIn\n             (ctxl' ++ ctx_sbst)\n             (mkApps (tRel (len + len'))\n                   ((map (lift0 (len' + len - npars))\n                         (to_extended_list params)) ++\n                    (map (lift (1 + i) len') (List.skipn npars args')) ++\n                    (map (lift0 len') inds) ++\n                    [mkApps (tRel (i + len'))\n                          (to_extended_list ctxl');\n                     mkApps (tConstruct refi ncons [])\n                         (map (lift0 len') (to_extended_list ctx_sbst))])) in\n    mapi (fun i '(n, c, a) => (i, construct_cons n c a, len + List.length c)) d.\n\nDefinition subterm_for_ind\n           (refi : inductive)\n           (ref   : term)\n           (allparams : nat)\n           (ntypes : nat) (* number of types in the mutual inductive *)\n           (ind   : one_inductive_body)\n                  : one_inductive_body\n  := let (pai, _) := decompose_prod_assum [] ind.(ind_type) in\n    let sort := (tSort (Universe.make' UnivExpr.lProp)) in\n    let npars := getParamCount ind allparams in\n    let pars := List.skipn (List.length pai - npars) pai in\n    let inds := List.firstn (List.length pai - npars) pai in\n    let ninds := List.length inds in\n    let aptype1 :=\n        mkApps ref ((map (lift0 (2 * ninds)) (to_extended_list pars)) ++\n                    (map (lift0 ninds) (to_extended_list inds))) in\n    let aptype2 :=\n        mkApps ref ((map (lift0 (1 + 2 * ninds)) (to_extended_list pars)) ++\n                    (map (lift0 1) (to_extended_list inds))) in\n    let renamer name i := (name ++ \"_subterm\" ++ (string_of_nat i))%string in\n    {| ind_name := (ind.(ind_name) ++ \"_direct_subterm\")%string;\n       ind_type  := it_mkProd_or_LetIn\n                      pars\n                   (it_mkProd_or_LetIn\n                      (inds)\n                   (it_mkProd_or_LetIn\n                      (map (clift0 (ninds)) inds)\n                   (it_mkProd_or_LetIn\n                       [mkdecl nAnon None aptype2; mkdecl nAnon None aptype1]\n                       sort)));\n       ind_kelim := InProp;\n       ind_ctors :=List.concat\n                     (mapi (fun n '(id', ct, k) => (\n                       map (fun '(si, st, sk) => (renamer id' si, st, sk))\n                       (subterms_for_constructor refi ref ntypes npars ninds ct n k)))\n                       ind.(ind_ctors));\n       ind_projs := [] |}.\n\n\nDefinition direct_subterm_for_mutual_ind\n            (mind : mutual_inductive_body)\n            (ind0 : inductive) (* internal metacoq representation of inductive, part of tInd *)\n            (ref  : term) (* reference term for the inductive type, like (tInd {| inductive_mind := \"Coq.Init.Datatypes.nat\"; inductive_ind := 0 |} []) *)\n                  : option mutual_inductive_body\n  := let i0 := inductive_ind ind0 in\n    let ntypes := List.length (ind_bodies mind) in\n    b <- List.nth_error mind.(ind_bodies) i0 ;;\n    let npars := getParamCount b (ind_npars mind) in\n    ret {|\n        ind_finite := BasicAst.Finite;\n        ind_npars := npars;\n        ind_universes := ind_universes mind;\n        ind_params := List.firstn (ind_npars mind - npars) (ind_params mind);\n        ind_bodies := [subterm_for_ind ind0 ref mind.(ind_npars) ntypes b];\n        ind_variance := None\n      |}.\n\nDefinition subterm (t : Ast.term)\n  : TemplateMonad unit\n  := match t with\n    | Ast.tInd ind0 _ =>\n      decl <- tmQuoteInductive (inductive_mind ind0);;\n      tmPrint decl;;\n      match (direct_subterm_for_mutual_ind\n               (TemplateToPCUIC.trans_minductive_body decl)\n               ind0\n               (TemplateToPCUIC.trans t)) with\n      | None =>\n        tmPrint t;;\n        @tmFail unit \"Coulnd't construct a subterm\"\n      | Some d =>\n        v <- tmEval lazy (PCUICToTemplate.trans_minductive_body d);;\n        tmPrint v;;\n        tmMkInductive' v\n      end\n    | _ =>\n      tmPrint t;;\n      @tmFail unit \" is not an inductive\"\n    end.\n\nRequire Import MetaCoq.Template.All.\nImport MonadNotation.\n\nNotation \"'Derive' 'Subterm' 'for' T\" := (subterm <% T %>) (at level 0).\n", "meta": {"author": "uds-psl", "repo": "metacoq-examples-coqws", "sha": "578d05af83ac817cd5f4870cf8161a81bfc0991c", "save_path": "github-repos/coq/uds-psl-metacoq-examples-coqws", "path": "github-repos/coq/uds-psl-metacoq-examples-coqws/metacoq-examples-coqws-578d05af83ac817cd5f4870cf8161a81bfc0991c/metacoq-subterm/subterm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2910034779690752}}
{"text": "From iris.algebra Require Export base.\nFrom iris Require Import options.\nSet Primitive Projections.\n\n(** This files defines (a shallow embedding of) the category of OFEs:\n    Complete ordered families of equivalences. This is a cartesian closed\n    category, and mathematically speaking, the entire development lives\n    in this category. However, we will generally prefer to work with raw\n    Coq functions plus some registered Proper instances for non-expansiveness.\n    This makes writing such functions much easier. It turns out that it many\n    cases, we do not even need non-expansiveness.\n*)\n\n(** Unbundled version *)\nClass Dist A := dist : nat → relation A.\nInstance: Params (@dist) 3 := {}.\nNotation \"x ≡{ n }≡ y\" := (dist n x y)\n  (at level 70, n at next level, format \"x  ≡{ n }≡  y\").\nNotation \"x ≡{ n }@{ A }≡ y\" := (dist (A:=A) n x y)\n  (at level 70, n at next level, only parsing).\n\nHint Extern 0 (_ ≡{_}≡ _) => reflexivity : core.\nHint Extern 0 (_ ≡{_}≡ _) => symmetry; assumption : core.\nNotation NonExpansive f := (∀ n, Proper (dist n ==> dist n) f).\nNotation NonExpansive2 f := (∀ n, Proper (dist n ==> dist n ==> dist n) f).\n\nTactic Notation \"ofe_subst\" ident(x) :=\n  repeat match goal with\n  | _ => progress simplify_eq/=\n  | H:@dist ?A ?d ?n x _ |- _ => setoid_subst_aux (@dist A d n) x\n  | H:@dist ?A ?d ?n _ x |- _ => symmetry in H;setoid_subst_aux (@dist A d n) x\n  end.\nTactic Notation \"ofe_subst\" :=\n  repeat match goal with\n  | _ => progress simplify_eq/=\n  | H:@dist ?A ?d ?n ?x _ |- _ => setoid_subst_aux (@dist A d n) x\n  | H:@dist ?A ?d ?n _ ?x |- _ => symmetry in H;setoid_subst_aux (@dist A d n) x\n  end.\n\nRecord OfeMixin A `{Equiv A, Dist A} := {\n  mixin_equiv_dist (x y : A) : x ≡ y ↔ ∀ n, x ≡{n}≡ y;\n  mixin_dist_equivalence n : Equivalence (@dist A _ n);\n  mixin_dist_S n (x y : A) : x ≡{S n}≡ y → x ≡{n}≡ y\n}.\n\n(** Bundled version *)\nStructure ofeT := OfeT {\n  ofe_car :> Type;\n  ofe_equiv : Equiv ofe_car;\n  ofe_dist : Dist ofe_car;\n  ofe_mixin : OfeMixin ofe_car\n}.\nArguments OfeT _ {_ _} _.\nAdd Printing Constructor ofeT.\nHint Extern 0 (Equiv _) => eapply (@ofe_equiv _) : typeclass_instances.\nHint Extern 0 (Dist _) => eapply (@ofe_dist _) : typeclass_instances.\nArguments ofe_car : simpl never.\nArguments ofe_equiv : simpl never.\nArguments ofe_dist : simpl never.\nArguments ofe_mixin : simpl never.\n\n(** When declaring instances of subclasses of OFE (like CMRAs and unital CMRAs)\nwe need Coq to *infer* the canonical OFE instance of a given type and take the\nmixin out of it. This makes sure we do not use two different OFE instances in\ndifferent places (see for example the constructors [CmraT] and [UcmraT] in the\nfile [cmra.v].)\n\nIn order to infer the OFE instance, we use the definition [ofe_mixin_of'] which\nis inspired by the [clone] trick in ssreflect. It works as follows, when type\nchecking [@ofe_mixin_of' A ?Ac id] Coq faces a unification problem:\n\n  ofe_car ?Ac  ~  A\n\nwhich will resolve [?Ac] to the canonical OFE instance corresponding to [A]. The\ndefinition [@ofe_mixin_of' A ?Ac id] will then provide the corresponding mixin.\nNote that type checking of [ofe_mixin_of' A id] will fail when [A] does not have\na canonical OFE instance.\n\nThe notation [ofe_mixin_of A] that we define on top of [ofe_mixin_of' A id]\nhides the [id] and normalizes the mixin to head normal form. The latter is to\nensure that we do not end up with redundant canonical projections to the mixin,\ni.e. them all being of the shape [ofe_mixin_of' A id]. *)\nDefinition ofe_mixin_of' A {Ac : ofeT} (f : Ac → A) : OfeMixin Ac := ofe_mixin Ac.\nNotation ofe_mixin_of A :=\n  ltac:(let H := eval hnf in (ofe_mixin_of' A id) in exact H) (only parsing).\n\n(** Lifting properties from the mixin *)\nSection ofe_mixin.\n  Context {A : ofeT}.\n  Implicit Types x y : A.\n  Lemma equiv_dist x y : x ≡ y ↔ ∀ n, x ≡{n}≡ y.\n  Proof. apply (mixin_equiv_dist _ (ofe_mixin A)). Qed.\n  Global Instance dist_equivalence n : Equivalence (@dist A _ n).\n  Proof. apply (mixin_dist_equivalence _ (ofe_mixin A)). Qed.\n  Lemma dist_S n x y : x ≡{S n}≡ y → x ≡{n}≡ y.\n  Proof. apply (mixin_dist_S _ (ofe_mixin A)). Qed.\nEnd ofe_mixin.\n\nHint Extern 1 (_ ≡{_}≡ _) => apply equiv_dist; assumption : core.\n\n(** Discrete OFEs and discrete OFE elements *)\nClass Discrete {A : ofeT} (x : A) := discrete y : x ≡{0}≡ y → x ≡ y.\nArguments discrete {_} _ {_} _ _.\nHint Mode Discrete + ! : typeclass_instances.\nInstance: Params (@Discrete) 1 := {}.\n\nClass OfeDiscrete (A : ofeT) := ofe_discrete_discrete (x : A) :> Discrete x.\n\n(** OFEs with a completion *)\nRecord chain (A : ofeT) := {\n  chain_car :> nat → A;\n  chain_cauchy n i : n ≤ i → chain_car i ≡{n}≡ chain_car n\n}.\nArguments chain_car {_} _ _.\nArguments chain_cauchy {_} _ _ _ _.\n\nProgram Definition chain_map {A B : ofeT} (f : A → B)\n    `{!NonExpansive f} (c : chain A) : chain B :=\n  {| chain_car n := f (c n) |}.\nNext Obligation. by intros A B f Hf c n i ?; apply Hf, chain_cauchy. Qed.\n\nNotation Compl A := (chain A%type → A).\nClass Cofe (A : ofeT) := {\n  compl : Compl A;\n  conv_compl n c : compl c ≡{n}≡ c n;\n}.\nArguments compl : simpl never.\nHint Mode Cofe ! : typeclass_instances.\n\nLemma compl_chain_map `{Cofe A, Cofe B} (f : A → B) c `(NonExpansive f) :\n  compl (chain_map f c) ≡ f (compl c).\nProof. apply equiv_dist=>n. by rewrite !conv_compl. Qed.\n\nProgram Definition chain_const {A : ofeT} (a : A) : chain A :=\n  {| chain_car n := a |}.\nNext Obligation. by intros A a n i _. Qed.\n\nLemma compl_chain_const {A : ofeT} `{!Cofe A} (a : A) :\n  compl (chain_const a) ≡ a.\nProof. apply equiv_dist=>n. by rewrite conv_compl. Qed.\n\n(** General properties *)\nSection ofe.\n  Context {A : ofeT}.\n  Implicit Types x y : A.\n  Global Instance ofe_equivalence : Equivalence ((≡) : relation A).\n  Proof.\n    split.\n    - by intros x; rewrite equiv_dist.\n    - by intros x y; rewrite !equiv_dist.\n    - by intros x y z; rewrite !equiv_dist; intros; trans y.\n  Qed.\n  Global Instance dist_ne n : Proper (dist n ==> dist n ==> iff) (@dist A _ n).\n  Proof.\n    intros x1 x2 ? y1 y2 ?; split; intros.\n    - by trans x1; [|trans y1].\n    - by trans x2; [|trans y2].\n  Qed.\n  Global Instance dist_proper n : Proper ((≡) ==> (≡) ==> iff) (@dist A _ n).\n  Proof.\n    by move => x1 x2 /equiv_dist Hx y1 y2 /equiv_dist Hy; rewrite (Hx n) (Hy n).\n  Qed.\n  Global Instance dist_proper_2 n x : Proper ((≡) ==> iff) (dist n x).\n  Proof. by apply dist_proper. Qed.\n  Global Instance Discrete_proper : Proper ((≡) ==> iff) (@Discrete A).\n  Proof. intros x y Hxy. rewrite /Discrete. by setoid_rewrite Hxy. Qed.\n\n  Lemma dist_le n n' x y : x ≡{n}≡ y → n' ≤ n → x ≡{n'}≡ y.\n  Proof. induction 2; eauto using dist_S. Qed.\n  Lemma dist_le' n n' x y : n' ≤ n → x ≡{n}≡ y → x ≡{n'}≡ y.\n  Proof. intros; eauto using dist_le. Qed.\n  (** [ne_proper] and [ne_proper_2] are not instances to improve efficiency of\n  type class search during setoid rewriting.\n  Instances of [NonExpansive{,2}] are hence accompanied by instances of\n  [Proper] built using these lemmas. *)\n  Lemma ne_proper {B : ofeT} (f : A → B) `{!NonExpansive f} :\n    Proper ((≡) ==> (≡)) f.\n  Proof. by intros x1 x2; rewrite !equiv_dist; intros Hx n; rewrite (Hx n). Qed.\n  Lemma ne_proper_2 {B C : ofeT} (f : A → B → C) `{!NonExpansive2 f} :\n    Proper ((≡) ==> (≡) ==> (≡)) f.\n  Proof.\n     unfold Proper, respectful; setoid_rewrite equiv_dist.\n     by intros x1 x2 Hx y1 y2 Hy n; rewrite (Hx n) (Hy n).\n  Qed.\n\n  Lemma conv_compl' `{Cofe A} n (c : chain A) : compl c ≡{n}≡ c (S n).\n  Proof.\n    transitivity (c n); first by apply conv_compl. symmetry.\n    apply chain_cauchy. lia.\n  Qed.\n\n  Lemma discrete_iff n (x : A) `{!Discrete x} y : x ≡ y ↔ x ≡{n}≡ y.\n  Proof.\n    split; intros; auto. apply (discrete _), dist_le with n; auto with lia.\n  Qed.\n  Lemma discrete_iff_0 n (x : A) `{!Discrete x} y : x ≡{0}≡ y ↔ x ≡{n}≡ y.\n  Proof. by rewrite -!discrete_iff. Qed.\nEnd ofe.\n\n(** Contractive functions *)\nDefinition dist_later `{Dist A} (n : nat) (x y : A) : Prop :=\n  match n with 0 => True | S n => x ≡{n}≡ y end.\nArguments dist_later _ _ !_ _ _ /.\n\nGlobal Instance dist_later_equivalence (A : ofeT) n : Equivalence (@dist_later A _ n).\nProof. destruct n as [|n]. by split. apply dist_equivalence. Qed.\n\nLemma dist_dist_later {A : ofeT} n (x y : A) : dist n x y → dist_later n x y.\nProof. intros Heq. destruct n; first done. exact: dist_S. Qed.\n\nLemma dist_later_dist {A : ofeT} n (x y : A) : dist_later (S n) x y → dist n x y.\nProof. done. Qed.\n\n(* We don't actually need this lemma (as our tactics deal with this through\n   other means), but technically speaking, this is the reason why\n   pre-composing a non-expansive function to a contractive function\n   preserves contractivity. *)\nLemma ne_dist_later {A B : ofeT} (f : A → B) :\n  NonExpansive f → ∀ n, Proper (dist_later n ==> dist_later n) f.\nProof. intros Hf [|n]; last exact: Hf. hnf. by intros. Qed.\n\nNotation Contractive f := (∀ n, Proper (dist_later n ==> dist n) f).\n\nInstance const_contractive {A B : ofeT} (x : A) : Contractive (@const A B x).\nProof. by intros n y1 y2. Qed.\n\nSection contractive.\n  Local Set Default Proof Using \"Type*\".\n  Context {A B : ofeT} (f : A → B) `{!Contractive f}.\n  Implicit Types x y : A.\n\n  Lemma contractive_0 x y : f x ≡{0}≡ f y.\n  Proof. by apply (_ : Contractive f). Qed.\n  Lemma contractive_S n x y : x ≡{n}≡ y → f x ≡{S n}≡ f y.\n  Proof. intros. by apply (_ : Contractive f). Qed.\n\n  Global Instance contractive_ne : NonExpansive f | 100.\n  Proof. by intros n x y ?; apply dist_S, contractive_S. Qed.\n  Global Instance contractive_proper : Proper ((≡) ==> (≡)) f | 100.\n  Proof. apply (ne_proper _). Qed.\nEnd contractive.\n\nLtac f_contractive :=\n  match goal with\n  | |- ?f _ ≡{_}≡ ?f _ => simple apply (_ : Proper (dist_later _ ==> _) f)\n  | |- ?f _ _ ≡{_}≡ ?f _ _ => simple apply (_ : Proper (dist_later _ ==> _ ==> _) f)\n  | |- ?f _ _ ≡{_}≡ ?f _ _ => simple apply (_ : Proper (_ ==> dist_later _ ==> _) f)\n  end;\n  try match goal with\n  | |- @dist_later ?A _ ?n ?x ?y =>\n         destruct n as [|n]; [exact I|change (@dist A _ n x y)]\n  end;\n  try simple apply reflexivity.\n\nLtac solve_contractive :=\n  solve_proper_core ltac:(fun _ => first [f_contractive | f_equiv]).\n\n(** Limit preserving predicates *)\nClass LimitPreserving `{!Cofe A} (P : A → Prop) : Prop :=\n  limit_preserving (c : chain A) : (∀ n, P (c n)) → P (compl c).\nHint Mode LimitPreserving + + ! : typeclass_instances.\n\nSection limit_preserving.\n  Context `{Cofe A}.\n  (* These are not instances as they will never fire automatically...\n     but they can still be helpful in proving things to be limit preserving. *)\n\n  Lemma limit_preserving_ext (P Q : A → Prop) :\n    (∀ x, P x ↔ Q x) → LimitPreserving P → LimitPreserving Q.\n  Proof. intros HP Hlimit c ?. apply HP, Hlimit=> n; by apply HP. Qed.\n\n  Global Instance limit_preserving_const (P : Prop) : LimitPreserving (λ _ : A, P).\n  Proof. intros c HP. apply (HP 0). Qed.\n\n  Lemma limit_preserving_discrete (P : A → Prop) :\n    Proper (dist 0 ==> impl) P → LimitPreserving P.\n  Proof. intros PH c Hc. by rewrite (conv_compl 0). Qed.\n\n  Lemma limit_preserving_and (P1 P2 : A → Prop) :\n    LimitPreserving P1 → LimitPreserving P2 →\n    LimitPreserving (λ x, P1 x ∧ P2 x).\n  Proof. intros Hlim1 Hlim2 c Hc. split. apply Hlim1, Hc. apply Hlim2, Hc. Qed.\n\n  Lemma limit_preserving_impl (P1 P2 : A → Prop) :\n    Proper (dist 0 ==> impl) P1 → LimitPreserving P2 →\n    LimitPreserving (λ x, P1 x → P2 x).\n  Proof.\n    intros Hlim1 Hlim2 c Hc HP1. apply Hlim2=> n; apply Hc.\n    eapply Hlim1, HP1. apply dist_le with n; last lia. apply (conv_compl n).\n  Qed.\n\n  Lemma limit_preserving_forall {B} (P : B → A → Prop) :\n    (∀ y, LimitPreserving (P y)) →\n    LimitPreserving (λ x, ∀ y, P y x).\n  Proof. intros Hlim c Hc y. by apply Hlim. Qed.\n\n  Lemma limit_preserving_equiv `{!Cofe B} (f g : A → B) :\n    NonExpansive f → NonExpansive g → LimitPreserving (λ x, f x ≡ g x).\n  Proof.\n    intros Hf Hg c Hc. apply equiv_dist=> n.\n    by rewrite -!compl_chain_map !conv_compl /= Hc.\n  Qed.\nEnd limit_preserving.\n\n(** Fixpoint *)\nProgram Definition fixpoint_chain {A : ofeT} `{Inhabited A} (f : A → A)\n  `{!Contractive f} : chain A := {| chain_car i := Nat.iter (S i) f inhabitant |}.\nNext Obligation.\n  intros A ? f ? n.\n  induction n as [|n IH]=> -[|i] //= ?; try lia.\n  - apply (contractive_0 f).\n  - apply (contractive_S f), IH; auto with lia.\nQed.\n\nProgram Definition fixpoint_def `{Cofe A, Inhabited A} (f : A → A)\n  `{!Contractive f} : A := compl (fixpoint_chain f).\nDefinition fixpoint_aux : seal (@fixpoint_def). Proof. by eexists. Qed.\nDefinition fixpoint := fixpoint_aux.(unseal).\nArguments fixpoint {A _ _} f {_}.\nDefinition fixpoint_eq : @fixpoint = @fixpoint_def := fixpoint_aux.(seal_eq).\n\nSection fixpoint.\n  Context `{Cofe A, Inhabited A} (f : A → A) `{!Contractive f}.\n\n  Lemma fixpoint_unfold : fixpoint f ≡ f (fixpoint f).\n  Proof.\n    apply equiv_dist=>n.\n    rewrite fixpoint_eq /fixpoint_def (conv_compl n (fixpoint_chain f)) //.\n    induction n as [|n IH]; simpl; eauto using contractive_0, contractive_S.\n  Qed.\n\n  Lemma fixpoint_unique (x : A) : x ≡ f x → x ≡ fixpoint f.\n  Proof.\n    rewrite !equiv_dist=> Hx n. induction n as [|n IH]; simpl in *.\n    - rewrite Hx fixpoint_unfold; eauto using contractive_0.\n    - rewrite Hx fixpoint_unfold. apply (contractive_S _), IH.\n  Qed.\n\n  Lemma fixpoint_ne (g : A → A) `{!Contractive g} n :\n    (∀ z, f z ≡{n}≡ g z) → fixpoint f ≡{n}≡ fixpoint g.\n  Proof.\n    intros Hfg. rewrite fixpoint_eq /fixpoint_def\n      (conv_compl n (fixpoint_chain f)) (conv_compl n (fixpoint_chain g)) /=.\n    induction n as [|n IH]; simpl in *; [by rewrite !Hfg|].\n    rewrite Hfg; apply contractive_S, IH; auto using dist_S.\n  Qed.\n  Lemma fixpoint_proper (g : A → A) `{!Contractive g} :\n    (∀ x, f x ≡ g x) → fixpoint f ≡ fixpoint g.\n  Proof. setoid_rewrite equiv_dist; naive_solver eauto using fixpoint_ne. Qed.\n\n  Lemma fixpoint_ind (P : A → Prop) :\n    Proper ((≡) ==> impl) P →\n    (∃ x, P x) → (∀ x, P x → P (f x)) →\n    LimitPreserving P →\n    P (fixpoint f).\n  Proof.\n    intros ? [x Hx] Hincr Hlim. set (chcar i := Nat.iter (S i) f x).\n    assert (Hcauch : ∀ n i : nat, n ≤ i → chcar i ≡{n}≡ chcar n).\n    { intros n. rewrite /chcar. induction n as [|n IH]=> -[|i] //=;\n        eauto using contractive_0, contractive_S with lia. }\n    set (fp2 := compl {| chain_cauchy := Hcauch |}).\n    assert (f fp2 ≡ fp2).\n    { apply equiv_dist=>n. rewrite /fp2 (conv_compl n) /= /chcar.\n      induction n as [|n IH]; simpl; eauto using contractive_0, contractive_S. }\n    rewrite -(fixpoint_unique fp2) //.\n    apply Hlim=> n /=. by apply Nat_iter_ind.\n  Qed.\nEnd fixpoint.\n\n\n(** Fixpoint of f when f^k is contractive. **)\nDefinition fixpointK `{Cofe A, Inhabited A} k (f : A → A)\n  `{!Contractive (Nat.iter k f)} := fixpoint (Nat.iter k f).\n\nSection fixpointK.\n  Local Set Default Proof Using \"Type*\".\n  Context `{Cofe A, Inhabited A} (f : A → A) (k : nat).\n  Context {f_contractive : Contractive (Nat.iter k f)} {f_ne : NonExpansive f}.\n  (* Note than f_ne is crucial here:  there are functions f such that f^2 is contractive,\n     but f is not non-expansive.\n     Consider for example f: SPred → SPred (where SPred is \"downclosed sets of natural numbers\").\n     Define f (using informative excluded middle) as follows:\n     f(N) = N  (where N is the set of all natural numbers)\n     f({0, ..., n}) = {0, ... n-1}  if n is even (so n-1 is at least -1, in which case we return the empty set)\n     f({0, ..., n}) = {0, ..., n+2} if n is odd\n     In other words, if we consider elements of SPred as ordinals, then we decreaste odd finite\n     ordinals by 1 and increase even finite ordinals by 2.\n     f is not non-expansive:  Consider f({0}) = ∅ and f({0,1}) = f({0,1,2,3}).\n     The arguments are clearly 0-equal, but the results are not.\n\n     Now consider g := f^2. We have\n     g(N) = N\n     g({0, ..., n}) = {0, ... n+1}  if n is even\n     g({0, ..., n}) = {0, ..., n+4} if n is odd\n     g is contractive.  All outputs contain 0, so they are all 0-equal.\n     Now consider two n-equal inputs. We have to show that the outputs are n+1-equal.\n     Either they both do not contain n in which case they have to be fully equal and\n     hence so are the results.  Or else they both contain n, so the results will\n     both contain n+1, so the results are n+1-equal.\n   *)\n\n  Let f_proper : Proper ((≡) ==> (≡)) f := ne_proper f.\n  Local Existing Instance f_proper.\n\n  Lemma fixpointK_unfold : fixpointK k f ≡ f (fixpointK k f).\n  Proof.\n    symmetry. rewrite /fixpointK. apply fixpoint_unique.\n    by rewrite -Nat_iter_S_r Nat_iter_S -fixpoint_unfold.\n  Qed.\n\n  Lemma fixpointK_unique (x : A) : x ≡ f x → x ≡ fixpointK k f.\n  Proof.\n    intros Hf. apply fixpoint_unique. clear f_contractive.\n    induction k as [|k' IH]=> //=. by rewrite -IH.\n  Qed.\n\n  Section fixpointK_ne.\n    Context (g : A → A) `{g_contractive : !Contractive (Nat.iter k g)}.\n    Context {g_ne : NonExpansive g}.\n\n    Lemma fixpointK_ne n : (∀ z, f z ≡{n}≡ g z) → fixpointK k f ≡{n}≡ fixpointK k g.\n    Proof.\n      rewrite /fixpointK=> Hfg /=. apply fixpoint_ne=> z.\n      clear f_contractive g_contractive.\n      induction k as [|k' IH]=> //=. by rewrite IH Hfg.\n    Qed.\n\n    Lemma fixpointK_proper : (∀ z, f z ≡ g z) → fixpointK k f ≡ fixpointK k g.\n    Proof. setoid_rewrite equiv_dist; naive_solver eauto using fixpointK_ne. Qed.\n  End fixpointK_ne.\n\n  Lemma fixpointK_ind (P : A → Prop) :\n    Proper ((≡) ==> impl) P →\n    (∃ x, P x) → (∀ x, P x → P (f x)) →\n    LimitPreserving P →\n    P (fixpointK k f).\n  Proof.\n    intros. rewrite /fixpointK. apply fixpoint_ind; eauto.\n    intros; apply Nat_iter_ind; auto.\n  Qed.\nEnd fixpointK.\n\n(** Mutual fixpoints *)\nSection fixpointAB.\n  Context `{Cofe A, Cofe B, !Inhabited A, !Inhabited B}.\n  Context (fA : A → B → A).\n  Context (fB : A → B → B).\n  Context {fA_contractive : ∀ n, Proper (dist_later n ==> dist n ==> dist n) fA}.\n  Context {fB_contractive : ∀ n, Proper (dist_later n ==> dist_later n ==> dist n) fB}.\n\n  Local Definition fixpoint_AB (x : A) : B := fixpoint (fB x).\n  Local Instance fixpoint_AB_contractive : Contractive fixpoint_AB.\n  Proof.\n    intros n x x' Hx; rewrite /fixpoint_AB.\n    apply fixpoint_ne=> y. by f_contractive.\n  Qed.\n\n  Local Definition fixpoint_AA (x : A) : A := fA x (fixpoint_AB x).\n  Local Instance fixpoint_AA_contractive : Contractive fixpoint_AA.\n  Proof using fA_contractive. solve_contractive. Qed.\n\n  Definition fixpoint_A : A := fixpoint fixpoint_AA.\n  Definition fixpoint_B : B := fixpoint_AB fixpoint_A.\n\n  Lemma fixpoint_A_unfold : fA fixpoint_A fixpoint_B ≡ fixpoint_A.\n  Proof. by rewrite {2}/fixpoint_A (fixpoint_unfold _). Qed.\n  Lemma fixpoint_B_unfold : fB fixpoint_A fixpoint_B ≡ fixpoint_B.\n  Proof. by rewrite {2}/fixpoint_B /fixpoint_AB (fixpoint_unfold _). Qed.\n\n  Instance: Proper ((≡) ==> (≡) ==> (≡)) fA.\n  Proof using fA_contractive.\n    apply ne_proper_2=> n x x' ? y y' ?. f_contractive; auto using dist_S.\n  Qed.\n  Instance: Proper ((≡) ==> (≡) ==> (≡)) fB.\n  Proof using fB_contractive.\n    apply ne_proper_2=> n x x' ? y y' ?. f_contractive; auto using dist_S.\n  Qed.\n\n  Lemma fixpoint_A_unique p q : fA p q ≡ p → fB p q ≡ q → p ≡ fixpoint_A.\n  Proof.\n    intros HfA HfB. rewrite -HfA. apply fixpoint_unique. rewrite /fixpoint_AA.\n    f_equiv=> //. apply fixpoint_unique. by rewrite HfA HfB.\n  Qed.\n  Lemma fixpoint_B_unique p q : fA p q ≡ p → fB p q ≡ q → q ≡ fixpoint_B.\n  Proof. intros. apply fixpoint_unique. by rewrite -fixpoint_A_unique. Qed.\nEnd fixpointAB.\n\nSection fixpointAB_ne.\n  Context `{Cofe A, Cofe B, !Inhabited A, !Inhabited B}.\n  Context (fA fA' : A → B → A).\n  Context (fB fB' : A → B → B).\n  Context `{∀ n, Proper (dist_later n ==> dist n ==> dist n) fA}.\n  Context `{∀ n, Proper (dist_later n ==> dist n ==> dist n) fA'}.\n  Context `{∀ n, Proper (dist_later n ==> dist_later n ==> dist n) fB}.\n  Context `{∀ n, Proper (dist_later n ==> dist_later n ==> dist n) fB'}.\n\n  Lemma fixpoint_A_ne n :\n    (∀ x y, fA x y ≡{n}≡ fA' x y) → (∀ x y, fB x y ≡{n}≡ fB' x y) →\n    fixpoint_A fA fB ≡{n}≡ fixpoint_A fA' fB'.\n  Proof.\n    intros HfA HfB. apply fixpoint_ne=> z.\n    rewrite /fixpoint_AA /fixpoint_AB HfA. f_equiv. by apply fixpoint_ne.\n  Qed.\n  Lemma fixpoint_B_ne n :\n    (∀ x y, fA x y ≡{n}≡ fA' x y) → (∀ x y, fB x y ≡{n}≡ fB' x y) →\n    fixpoint_B fA fB ≡{n}≡ fixpoint_B fA' fB'.\n  Proof.\n    intros HfA HfB. apply fixpoint_ne=> z. rewrite HfB. f_contractive.\n    apply fixpoint_A_ne; auto using dist_S.\n  Qed.\n\n  Lemma fixpoint_A_proper :\n    (∀ x y, fA x y ≡ fA' x y) → (∀ x y, fB x y ≡ fB' x y) →\n    fixpoint_A fA fB ≡ fixpoint_A fA' fB'.\n  Proof. setoid_rewrite equiv_dist; naive_solver eauto using fixpoint_A_ne. Qed.\n  Lemma fixpoint_B_proper :\n    (∀ x y, fA x y ≡ fA' x y) → (∀ x y, fB x y ≡ fB' x y) →\n    fixpoint_B fA fB ≡ fixpoint_B fA' fB'.\n  Proof. setoid_rewrite equiv_dist; naive_solver eauto using fixpoint_B_ne. Qed.\nEnd fixpointAB_ne.\n\n(** Non-expansive function space *)\nRecord ofe_mor (A B : ofeT) : Type := OfeMor {\n  ofe_mor_car :> A → B;\n  ofe_mor_ne : NonExpansive ofe_mor_car\n}.\nArguments OfeMor {_ _} _ {_}.\nAdd Printing Constructor ofe_mor.\nExisting Instance ofe_mor_ne.\n\nNotation \"'λne' x .. y , t\" :=\n  (@OfeMor _ _ (λ x, .. (@OfeMor _ _ (λ y, t) _) ..) _)\n  (at level 200, x binder, y binder, right associativity).\n\nSection ofe_mor.\n  Context {A B : ofeT}.\n  Global Instance ofe_mor_proper (f : ofe_mor A B) : Proper ((≡) ==> (≡)) f.\n  Proof. apply ne_proper, ofe_mor_ne. Qed.\n  Instance ofe_mor_equiv : Equiv (ofe_mor A B) := λ f g, ∀ x, f x ≡ g x.\n  Instance ofe_mor_dist : Dist (ofe_mor A B) := λ n f g, ∀ x, f x ≡{n}≡ g x.\n  Definition ofe_mor_ofe_mixin : OfeMixin (ofe_mor A B).\n  Proof.\n    split.\n    - intros f g; split; [intros Hfg n k; apply equiv_dist, Hfg|].\n      intros Hfg k; apply equiv_dist=> n; apply Hfg.\n    - intros n; split.\n      + by intros f x.\n      + by intros f g ? x.\n      + by intros f g h ?? x; trans (g x).\n    - by intros n f g ? x; apply dist_S.\n  Qed.\n  Canonical Structure ofe_morO := OfeT (ofe_mor A B) ofe_mor_ofe_mixin.\n\n  Program Definition ofe_mor_chain (c : chain ofe_morO)\n    (x : A) : chain B := {| chain_car n := c n x |}.\n  Next Obligation. intros c x n i ?. by apply (chain_cauchy c). Qed.\n  Program Definition ofe_mor_compl `{Cofe B} : Compl ofe_morO := λ c,\n    {| ofe_mor_car x := compl (ofe_mor_chain c x) |}.\n  Next Obligation.\n    intros ? c n x y Hx. by rewrite (conv_compl n (ofe_mor_chain c x))\n      (conv_compl n (ofe_mor_chain c y)) /= Hx.\n  Qed.\n  Global Program Instance ofe_mor_cofe `{Cofe B} : Cofe ofe_morO :=\n    {| compl := ofe_mor_compl |}.\n  Next Obligation.\n    intros ? n c x; simpl.\n    by rewrite (conv_compl n (ofe_mor_chain c x)) /=.\n  Qed.\n\n  Global Instance ofe_mor_car_ne :\n    NonExpansive2 (@ofe_mor_car A B).\n  Proof. intros n f g Hfg x y Hx; rewrite Hx; apply Hfg. Qed.\n  Global Instance ofe_mor_car_proper :\n    Proper ((≡) ==> (≡) ==> (≡)) (@ofe_mor_car A B) := ne_proper_2 _.\n  Lemma ofe_mor_ext (f g : ofe_mor A B) : f ≡ g ↔ ∀ x, f x ≡ g x.\n  Proof. done. Qed.\nEnd ofe_mor.\n\nArguments ofe_morO : clear implicits.\nNotation \"A -n> B\" :=\n  (ofe_morO A B) (at level 99, B at level 200, right associativity).\nInstance ofe_mor_inhabited {A B : ofeT} `{Inhabited B} :\n  Inhabited (A -n> B) := populate (λne _, inhabitant).\n\n(** Identity and composition and constant function *)\nDefinition cid {A} : A -n> A := OfeMor id.\nInstance: Params (@cid) 1 := {}.\nDefinition cconst {A B : ofeT} (x : B) : A -n> B := OfeMor (const x).\nInstance: Params (@cconst) 2 := {}.\n\nDefinition ccompose {A B C}\n  (f : B -n> C) (g : A -n> B) : A -n> C := OfeMor (f ∘ g).\nInstance: Params (@ccompose) 3 := {}.\nInfix \"◎\" := ccompose (at level 40, left associativity).\nGlobal Instance ccompose_ne {A B C} :\n  NonExpansive2 (@ccompose A B C).\nProof. intros n ?? Hf g1 g2 Hg x. rewrite /= (Hg x) (Hf (g2 x)) //. Qed.\n\n(* Function space maps *)\nDefinition ofe_mor_map {A A' B B'} (f : A' -n> A) (g : B -n> B')\n  (h : A -n> B) : A' -n> B' := g ◎ h ◎ f.\nInstance ofe_mor_map_ne {A A' B B'} n :\n  Proper (dist n ==> dist n ==> dist n ==> dist n) (@ofe_mor_map A A' B B').\nProof. intros ??? ??? ???. by repeat apply ccompose_ne. Qed.\n\nDefinition ofe_morO_map {A A' B B'} (f : A' -n> A) (g : B -n> B') :\n  (A -n> B) -n> (A' -n>  B') := OfeMor (ofe_mor_map f g).\nInstance ofe_morO_map_ne {A A' B B'} :\n  NonExpansive2 (@ofe_morO_map A A' B B').\nProof.\n  intros n f f' Hf g g' Hg ?. rewrite /= /ofe_mor_map.\n  by repeat apply ccompose_ne.\nQed.\n\n(** * Unit type *)\nSection unit.\n  Instance unit_dist : Dist unit := λ _ _ _, True.\n  Definition unit_ofe_mixin : OfeMixin unit.\n  Proof. by repeat split; try exists 0. Qed.\n  Canonical Structure unitO : ofeT := OfeT unit unit_ofe_mixin.\n\n  Global Program Instance unit_cofe : Cofe unitO := { compl x := () }.\n  Next Obligation. by repeat split; try exists 0. Qed.\n\n  Global Instance unit_ofe_discrete : OfeDiscrete unitO.\n  Proof. done. Qed.\nEnd unit.\n\n(** * Empty type *)\nSection empty.\n  Instance Empty_set_dist : Dist Empty_set := λ _ _ _, True.\n  Definition Empty_set_ofe_mixin : OfeMixin Empty_set.\n  Proof. by repeat split; try exists 0. Qed.\n  Canonical Structure Empty_setO : ofeT := OfeT Empty_set Empty_set_ofe_mixin.\n\n  Global Program Instance Empty_set_cofe : Cofe Empty_setO := { compl x := x 0 }.\n  Next Obligation. by repeat split; try exists 0. Qed.\n\n  Global Instance Empty_set_ofe_discrete : OfeDiscrete Empty_setO.\n  Proof. done. Qed.\nEnd empty.\n\n(** * Product type *)\nSection product.\n  Context {A B : ofeT}.\n\n  Instance prod_dist : Dist (A * B) := λ n, prod_relation (dist n) (dist n).\n  Global Instance pair_ne :\n    NonExpansive2 (@pair A B) := _.\n  Global Instance fst_ne : NonExpansive (@fst A B) := _.\n  Global Instance snd_ne : NonExpansive (@snd A B) := _.\n  Definition prod_ofe_mixin : OfeMixin (A * B).\n  Proof.\n    split.\n    - intros x y; unfold dist, prod_dist, equiv, prod_equiv, prod_relation.\n      rewrite !equiv_dist; naive_solver.\n    - apply _.\n    - by intros n [x1 y1] [x2 y2] [??]; split; apply dist_S.\n  Qed.\n  Canonical Structure prodO : ofeT := OfeT (A * B) prod_ofe_mixin.\n\n  Global Program Instance prod_cofe `{Cofe A, Cofe B} : Cofe prodO :=\n    { compl c := (compl (chain_map fst c), compl (chain_map snd c)) }.\n  Next Obligation.\n    intros ?? n c; split. apply (conv_compl n (chain_map fst c)).\n    apply (conv_compl n (chain_map snd c)).\n  Qed.\n\n  Global Instance prod_discrete (x : A * B) :\n    Discrete (x.1) → Discrete (x.2) → Discrete x.\n  Proof. by intros ???[??]; split; apply (discrete _). Qed.\n  Global Instance prod_ofe_discrete :\n    OfeDiscrete A → OfeDiscrete B → OfeDiscrete prodO.\n  Proof. intros ?? [??]; apply _. Qed.\nEnd product.\n\nArguments prodO : clear implicits.\nTypeclasses Opaque prod_dist.\n\nInstance prod_map_ne {A A' B B' : ofeT} n :\n  Proper ((dist n ==> dist n) ==> (dist n ==> dist n) ==>\n           dist n ==> dist n) (@prod_map A A' B B').\nProof. by intros f f' Hf g g' Hg ?? [??]; split; [apply Hf|apply Hg]. Qed.\nDefinition prodO_map {A A' B B'} (f : A -n> A') (g : B -n> B') :\n  prodO A B -n> prodO A' B' := OfeMor (prod_map f g).\nInstance prodO_map_ne {A A' B B'} :\n  NonExpansive2 (@prodO_map A A' B B').\nProof. intros n f f' Hf g g' Hg [??]; split; [apply Hf|apply Hg]. Qed.\n\n(** * COFE → OFE Functors *)\nRecord oFunctor := OFunctor {\n  oFunctor_car : ∀ A `{!Cofe A} B `{!Cofe B}, ofeT;\n  oFunctor_map `{!Cofe A1, !Cofe A2, !Cofe B1, !Cofe B2} :\n    ((A2 -n> A1) * (B1 -n> B2)) → oFunctor_car A1 B1 -n> oFunctor_car A2 B2;\n  oFunctor_map_ne `{!Cofe A1, !Cofe A2, !Cofe B1, !Cofe B2} :\n    NonExpansive (@oFunctor_map A1 _ A2 _ B1 _ B2 _);\n  oFunctor_map_id `{!Cofe A, !Cofe B} (x : oFunctor_car A B) :\n    oFunctor_map (cid,cid) x ≡ x;\n  oFunctor_map_compose `{!Cofe A1, !Cofe A2, !Cofe A3, !Cofe B1, !Cofe B2, !Cofe B3}\n      (f : A2 -n> A1) (g : A3 -n> A2) (f' : B1 -n> B2) (g' : B2 -n> B3) x :\n    oFunctor_map (f◎g, g'◎f') x ≡ oFunctor_map (g,g') (oFunctor_map (f,f') x)\n}.\nExisting Instance oFunctor_map_ne.\nInstance: Params (@oFunctor_map) 9 := {}.\n\nDeclare Scope oFunctor_scope.\nDelimit Scope oFunctor_scope with OF.\nBind Scope oFunctor_scope with oFunctor.\n\nClass oFunctorContractive (F : oFunctor) :=\n  oFunctor_map_contractive `{!Cofe A1, !Cofe A2, !Cofe B1, !Cofe B2} :>\n    Contractive (@oFunctor_map F A1 _ A2 _ B1 _ B2 _).\nHint Mode oFunctorContractive ! : typeclass_instances.\n\n(** Not a coercion due to the [Cofe] type class argument, and to avoid\nambiguous coercion paths, see https://gitlab.mpi-sws.org/iris/iris/issues/240. *)\nDefinition oFunctor_apply (F: oFunctor) (A: ofeT) `{!Cofe A} : ofeT :=\n  oFunctor_car F A A.\n\nProgram Definition oFunctor_oFunctor_compose (F1 F2 : oFunctor)\n  `{!∀ `{Cofe A, Cofe B}, Cofe (oFunctor_car F2 A B)} : oFunctor := {|\n  oFunctor_car A _ B _ := oFunctor_car F1 (oFunctor_car F2 B A) (oFunctor_car F2 A B);\n  oFunctor_map A1 _ A2 _ B1 _ B2 _ 'fg :=\n    oFunctor_map F1 (oFunctor_map F2 (fg.2,fg.1),oFunctor_map F2 fg)\n|}.\nNext Obligation.\n  intros F1 F2 ? A1 ? A2 ? B1 ? B2 ? n [f1 g1] [f2 g2] [??]; simpl in *.\n  apply oFunctor_map_ne; split; apply oFunctor_map_ne; by split.\nQed.\nNext Obligation.\n  intros F1 F2 ? A ? B ? x; simpl in *. rewrite -{2}(oFunctor_map_id F1 x).\n  apply equiv_dist=> n. apply oFunctor_map_ne.\n  split=> y /=; by rewrite !oFunctor_map_id.\nQed.\nNext Obligation.\n  intros F1 F2 ? A1 ? A2 ? A3 ? B1 ? B2 ? B3 ? f g f' g' x; simpl in *.\n  rewrite -oFunctor_map_compose. apply equiv_dist=> n. apply oFunctor_map_ne.\n  split=> y /=; by rewrite !oFunctor_map_compose.\nQed.\nInstance oFunctor_oFunctor_compose_contractive_1 (F1 F2 : oFunctor)\n    `{!∀ `{Cofe A, Cofe B}, Cofe (oFunctor_car F2 A B)} :\n  oFunctorContractive F1 → oFunctorContractive (oFunctor_oFunctor_compose F1 F2).\nProof.\n  intros ? A1 ? A2 ? B1 ? B2 ? n [f1 g1] [f2 g2] Hfg; simpl in *.\n  f_contractive; destruct Hfg; split; simpl in *; apply oFunctor_map_ne; by split.\nQed.\nInstance oFunctor_oFunctor_compose_contractive_2 (F1 F2 : oFunctor)\n    `{!∀ `{Cofe A, Cofe B}, Cofe (oFunctor_car F2 A B)} :\n  oFunctorContractive F2 → oFunctorContractive (oFunctor_oFunctor_compose F1 F2).\nProof.\n  intros ? A1 ? A2 ? B1 ? B2 ? n [f1 g1] [f2 g2] Hfg; simpl in *.\n  f_equiv; split; simpl in *; f_contractive; destruct Hfg; by split.\nQed.\n\nProgram Definition constOF (B : ofeT) : oFunctor :=\n  {| oFunctor_car A1 A2 _ _ := B; oFunctor_map A1 _ A2 _ B1 _ B2 _ f := cid |}.\nSolve Obligations with done.\nCoercion constOF : ofeT >-> oFunctor.\n\nInstance constOF_contractive B : oFunctorContractive (constOF B).\nProof. rewrite /oFunctorContractive; apply _. Qed.\n\nProgram Definition idOF : oFunctor :=\n  {| oFunctor_car A1 _ A2 _ := A2; oFunctor_map A1 _ A2 _ B1 _ B2 _ f := f.2 |}.\nSolve Obligations with done.\nNotation \"∙\" := idOF : oFunctor_scope.\n\nProgram Definition prodOF (F1 F2 : oFunctor) : oFunctor := {|\n  oFunctor_car A _ B _ := prodO (oFunctor_car F1 A B) (oFunctor_car F2 A B);\n  oFunctor_map A1 _ A2 _ B1 _ B2 _ fg :=\n    prodO_map (oFunctor_map F1 fg) (oFunctor_map F2 fg)\n|}.\nNext Obligation.\n  intros ?? A1 ? A2 ? B1 ? B2 ? n ???; by apply prodO_map_ne; apply oFunctor_map_ne.\nQed.\nNext Obligation. by intros F1 F2 A ? B ? [??]; rewrite /= !oFunctor_map_id. Qed.\nNext Obligation.\n  intros F1 F2 A1 ? A2 ? A3 ? B1 ? B2 ? B3 ? f g f' g' [??]; simpl.\n  by rewrite !oFunctor_map_compose.\nQed.\nNotation \"F1 * F2\" := (prodOF F1%OF F2%OF) : oFunctor_scope.\n\nInstance prodOF_contractive F1 F2 :\n  oFunctorContractive F1 → oFunctorContractive F2 →\n  oFunctorContractive (prodOF F1 F2).\nProof.\n  intros ?? A1 ? A2 ? B1 ? B2 ? n ???;\n    by apply prodO_map_ne; apply oFunctor_map_contractive.\nQed.\n\nProgram Definition ofe_morOF (F1 F2 : oFunctor) : oFunctor := {|\n  oFunctor_car A _ B _ := oFunctor_car F1 B A -n> oFunctor_car F2 A B;\n  oFunctor_map A1 _ A2 _ B1 _ B2 _ fg :=\n    ofe_morO_map (oFunctor_map F1 (fg.2, fg.1)) (oFunctor_map F2 fg)\n|}.\nNext Obligation.\n  intros F1 F2 A1 ? A2 ? B1 ? B2 ? n [f g] [f' g'] Hfg; simpl in *.\n  apply ofe_morO_map_ne; apply oFunctor_map_ne; split; by apply Hfg.\nQed.\nNext Obligation.\n  intros F1 F2 A ? B ? [f ?] ?; simpl. rewrite /= !oFunctor_map_id.\n  apply (ne_proper f). apply oFunctor_map_id.\nQed.\nNext Obligation.\n  intros F1 F2 A1 ? A2 ? A3 ? B1 ? B2 ? B3 ? f g f' g' [h ?] ?; simpl in *.\n  rewrite -!oFunctor_map_compose. do 2 apply (ne_proper _). apply oFunctor_map_compose.\nQed.\nNotation \"F1 -n> F2\" := (ofe_morOF F1%OF F2%OF) : oFunctor_scope.\n\nInstance ofe_morOF_contractive F1 F2 :\n  oFunctorContractive F1 → oFunctorContractive F2 →\n  oFunctorContractive (ofe_morOF F1 F2).\nProof.\n  intros ?? A1 ? A2 ? B1 ? B2 ? n [f g] [f' g'] Hfg; simpl in *.\n  apply ofe_morO_map_ne; apply oFunctor_map_contractive; destruct n, Hfg; by split.\nQed.\n\n(** * Sum type *)\nSection sum.\n  Context {A B : ofeT}.\n\n  Instance sum_dist : Dist (A + B) := λ n, sum_relation (dist n) (dist n).\n  Global Instance inl_ne : NonExpansive (@inl A B) := _.\n  Global Instance inr_ne : NonExpansive (@inr A B) := _.\n  Global Instance inl_ne_inj {n} : Inj (dist n) (dist n) (@inl A B) := _.\n  Global Instance inr_ne_inj {n} : Inj (dist n) (dist n) (@inr A B) := _.\n\n  Definition sum_ofe_mixin : OfeMixin (A + B).\n  Proof.\n    split.\n    - intros x y; split=> Hx.\n      + destruct Hx=> n; constructor; by apply equiv_dist.\n      + destruct (Hx 0); constructor; apply equiv_dist=> n; by apply (inj _).\n    - apply _.\n    - destruct 1; constructor; by apply dist_S.\n  Qed.\n  Canonical Structure sumO : ofeT := OfeT (A + B) sum_ofe_mixin.\n\n  Program Definition inl_chain (c : chain sumO) (a : A) : chain A :=\n    {| chain_car n := match c n return _ with inl a' => a' | _ => a end |}.\n  Next Obligation. intros c a n i ?; simpl. by destruct (chain_cauchy c n i). Qed.\n  Program Definition inr_chain (c : chain sumO) (b : B) : chain B :=\n    {| chain_car n := match c n return _ with inr b' => b' | _ => b end |}.\n  Next Obligation. intros c b n i ?; simpl. by destruct (chain_cauchy c n i). Qed.\n\n  Definition sum_compl `{Cofe A, Cofe B} : Compl sumO := λ c,\n    match c 0 with\n    | inl a => inl (compl (inl_chain c a))\n    | inr b => inr (compl (inr_chain c b))\n    end.\n  Global Program Instance sum_cofe `{Cofe A, Cofe B} : Cofe sumO :=\n    { compl := sum_compl }.\n  Next Obligation.\n    intros ?? n c; rewrite /compl /sum_compl.\n    feed inversion (chain_cauchy c 0 n); first by auto with lia; constructor.\n    - rewrite (conv_compl n (inl_chain c _)) /=. destruct (c n); naive_solver.\n    - rewrite (conv_compl n (inr_chain c _)) /=. destruct (c n); naive_solver.\n  Qed.\n\n  Global Instance inl_discrete (x : A) : Discrete x → Discrete (inl x).\n  Proof. inversion_clear 2; constructor; by apply (discrete _). Qed.\n  Global Instance inr_discrete (y : B) : Discrete y → Discrete (inr y).\n  Proof. inversion_clear 2; constructor; by apply (discrete _). Qed.\n  Global Instance sum_ofe_discrete :\n    OfeDiscrete A → OfeDiscrete B → OfeDiscrete sumO.\n  Proof. intros ?? [?|?]; apply _. Qed.\nEnd sum.\n\nArguments sumO : clear implicits.\nTypeclasses Opaque sum_dist.\n\nInstance sum_map_ne {A A' B B' : ofeT} n :\n  Proper ((dist n ==> dist n) ==> (dist n ==> dist n) ==>\n           dist n ==> dist n) (@sum_map A A' B B').\nProof.\n  intros f f' Hf g g' Hg ??; destruct 1; constructor; [by apply Hf|by apply Hg].\nQed.\nDefinition sumO_map {A A' B B'} (f : A -n> A') (g : B -n> B') :\n  sumO A B -n> sumO A' B' := OfeMor (sum_map f g).\nInstance sumO_map_ne {A A' B B'} :\n  NonExpansive2 (@sumO_map A A' B B').\nProof. intros n f f' Hf g g' Hg [?|?]; constructor; [apply Hf|apply Hg]. Qed.\n\nProgram Definition sumOF (F1 F2 : oFunctor) : oFunctor := {|\n  oFunctor_car A _ B _ := sumO (oFunctor_car F1 A B) (oFunctor_car F2 A B);\n  oFunctor_map A1 _ A2 _ B1 _ B2 _ fg :=\n    sumO_map (oFunctor_map F1 fg) (oFunctor_map F2 fg)\n|}.\nNext Obligation.\n  intros ?? A1 ? A2 ? B1 ? B2 ? n ???; by apply sumO_map_ne; apply oFunctor_map_ne.\nQed.\nNext Obligation. by intros F1 F2 A ? B ? [?|?]; rewrite /= !oFunctor_map_id. Qed.\nNext Obligation.\n  intros F1 F2 A1 ? A2 ? A3 ? B1 ? B2 ? B3 ? f g f' g' [?|?]; simpl;\n    by rewrite !oFunctor_map_compose.\nQed.\nNotation \"F1 + F2\" := (sumOF F1%OF F2%OF) : oFunctor_scope.\n\nInstance sumOF_contractive F1 F2 :\n  oFunctorContractive F1 → oFunctorContractive F2 →\n  oFunctorContractive (sumOF F1 F2).\nProof.\n  intros ?? A1 ? A2 ? B1 ? B2 ? n ???;\n    by apply sumO_map_ne; apply oFunctor_map_contractive.\nQed.\n\n(** * Discrete OFEs *)\nSection discrete_ofe.\n  Context `{Equiv A} (Heq : @Equivalence A (≡)).\n\n  Instance discrete_dist : Dist A := λ n x y, x ≡ y.\n  Definition discrete_ofe_mixin : OfeMixin A.\n  Proof using Type*.\n    split.\n    - intros x y; split; [done|intros Hn; apply (Hn 0)].\n    - done.\n    - done.\n  Qed.\n\n  Global Instance discrete_ofe_discrete : OfeDiscrete (OfeT A discrete_ofe_mixin).\n  Proof. by intros x y. Qed.\n\n  Global Program Instance discrete_cofe : Cofe (OfeT A discrete_ofe_mixin) :=\n    { compl c := c 0 }.\n  Next Obligation.\n    intros n c. rewrite /compl /=;\n    symmetry; apply (chain_cauchy c 0 n). lia.\n  Qed.\nEnd discrete_ofe.\n\nNotation discreteO A := (OfeT A (discrete_ofe_mixin _)).\n(** Force the [Equivalence] proof to be [eq_equivalence] so that it does not\nfind another one, like [ofe_equivalence], in the case of aliases. See also\nhttps://gitlab.mpi-sws.org/iris/iris/issues/299 *)\nNotation leibnizO A := (OfeT A (@discrete_ofe_mixin _ equivL eq_equivalence)).\n\n(** In order to define a discrete CMRA with carrier [A] (in the file [cmra.v])\nwe need to determine the [Equivalence A] proof that was used to construct the\nOFE instance of [A] (note that this proof is not the same as the one we obtain\nvia [ofe_equivalence]).\n\nWe obtain the proof of [Equivalence A] by inferring the canonical OFE mixin\nusing [ofe_mixin_of A], and then check whether it is indeed a discrete OFE. This\nwill fail if no OFE, or an OFE other than the discrete OFE, was registered. *)\nNotation discrete_ofe_equivalence_of A := ltac:(\n  match constr:(ofe_mixin_of A) with\n  | discrete_ofe_mixin ?H => exact H\n  end) (only parsing).\n\nInstance leibnizO_leibniz A : LeibnizEquiv (leibnizO A).\nProof. by intros x y. Qed.\n\n(** * Basic Coq types *)\nCanonical Structure boolO := leibnizO bool.\nCanonical Structure natO := leibnizO nat.\nCanonical Structure positiveO := leibnizO positive.\nCanonical Structure NO := leibnizO N.\nCanonical Structure ZO := leibnizO Z.\n\nSection prop.\n  Instance Prop_equiv : Equiv Prop := iff.\n  Instance Prop_equivalence : Equivalence (≡@{Prop}) := _.\n  Canonical Structure PropO := discreteO Prop.\nEnd prop.\n\n(** * Option type *)\nSection option.\n  Context {A : ofeT}.\n\n  Instance option_dist : Dist (option A) := λ n, option_Forall2 (dist n).\n  Lemma dist_option_Forall2 n mx my : mx ≡{n}≡ my ↔ option_Forall2 (dist n) mx my.\n  Proof. done. Qed.\n\n  Definition option_ofe_mixin : OfeMixin (option A).\n  Proof.\n    split.\n    - intros mx my; split; [by destruct 1; constructor; apply equiv_dist|].\n      intros Hxy; destruct (Hxy 0); constructor; apply equiv_dist.\n      by intros n; feed inversion (Hxy n).\n    - apply _.\n    - destruct 1; constructor; by apply dist_S.\n  Qed.\n  Canonical Structure optionO := OfeT (option A) option_ofe_mixin.\n\n  Program Definition option_chain (c : chain optionO) (x : A) : chain A :=\n    {| chain_car n := default x (c n) |}.\n  Next Obligation. intros c x n i ?; simpl. by destruct (chain_cauchy c n i). Qed.\n  Definition option_compl `{Cofe A} : Compl optionO := λ c,\n    match c 0 with Some x => Some (compl (option_chain c x)) | None => None end.\n  Global Program Instance option_cofe `{Cofe A} : Cofe optionO :=\n    { compl := option_compl }.\n  Next Obligation.\n    intros ? n c; rewrite /compl /option_compl.\n    feed inversion (chain_cauchy c 0 n); auto with lia; [].\n    constructor. rewrite (conv_compl n (option_chain c _)) /=.\n    destruct (c n); naive_solver.\n  Qed.\n\n  Global Instance option_ofe_discrete : OfeDiscrete A → OfeDiscrete optionO.\n  Proof. destruct 2; constructor; by apply (discrete _). Qed.\n\n  Global Instance Some_ne : NonExpansive (@Some A).\n  Proof. by constructor. Qed.\n  Global Instance is_Some_ne n : Proper (dist n ==> iff) (@is_Some A).\n  Proof. destruct 1; split; eauto. Qed.\n  Global Instance Some_dist_inj {n} : Inj (dist n) (dist n) (@Some A).\n  Proof. by inversion_clear 1. Qed.\n  Global Instance from_option_ne {B} (R : relation B) (f : A → B) n :\n    Proper (dist n ==> R) f → Proper (R ==> dist n ==> R) (from_option f).\n  Proof. destruct 3; simpl; auto. Qed.\n\n  Global Instance None_discrete : Discrete (@None A).\n  Proof. inversion_clear 1; constructor. Qed.\n  Global Instance Some_discrete x : Discrete x → Discrete (Some x).\n  Proof. by intros ?; inversion_clear 1; constructor; apply discrete. Qed.\n\n  Lemma dist_None n mx : mx ≡{n}≡ None ↔ mx = None.\n  Proof. split; [by inversion_clear 1|by intros ->]. Qed.\n  Lemma dist_Some_inv_l n mx my x :\n    mx ≡{n}≡ my → mx = Some x → ∃ y, my = Some y ∧ x ≡{n}≡ y.\n  Proof. destruct 1; naive_solver. Qed.\n  Lemma dist_Some_inv_r n mx my y :\n    mx ≡{n}≡ my → my = Some y → ∃ x, mx = Some x ∧ x ≡{n}≡ y.\n  Proof. destruct 1; naive_solver. Qed.\n  Lemma dist_Some_inv_l' n my x : Some x ≡{n}≡ my → ∃ x', Some x' = my ∧ x ≡{n}≡ x'.\n  Proof. intros ?%(dist_Some_inv_l _ _ _ x); naive_solver. Qed.\n  Lemma dist_Some_inv_r' n mx y : mx ≡{n}≡ Some y → ∃ y', mx = Some y' ∧ y ≡{n}≡ y'.\n  Proof. intros ?%(dist_Some_inv_r _ _ _ y); naive_solver. Qed.\nEnd option.\n\nTypeclasses Opaque option_dist.\nArguments optionO : clear implicits.\n\nInstance option_fmap_ne {A B : ofeT} n:\n  Proper ((dist n ==> dist n) ==> dist n ==> dist n) (@fmap option _ A B).\nProof. intros f f' Hf ?? []; constructor; auto. Qed.\nInstance option_mbind_ne {A B : ofeT} n:\n  Proper ((dist n ==> dist n) ==> dist n ==> dist n) (@mbind option _ A B).\nProof. destruct 2; simpl; auto. Qed.\nInstance option_mjoin_ne {A : ofeT} n:\n  Proper (dist n ==> dist n) (@mjoin option _ A).\nProof. destruct 1 as [?? []|]; simpl; by constructor. Qed.\n\nLemma fmap_Some_dist {A B : ofeT} (f : A → B) (mx : option A) (y : B) n :\n  f <$> mx ≡{n}≡ Some y ↔ ∃ x : A, mx = Some x ∧ y ≡{n}≡ f x.\nProof.\n  split; [|by intros (x&->&->)].\n  intros (?&?%fmap_Some&?)%dist_Some_inv_r'; naive_solver.\nQed.\n\nDefinition optionO_map {A B} (f : A -n> B) : optionO A -n> optionO B :=\n  OfeMor (fmap f : optionO A → optionO B).\nInstance optionO_map_ne A B : NonExpansive (@optionO_map A B).\nProof. by intros n f f' Hf []; constructor; apply Hf. Qed.\n\nProgram Definition optionOF (F : oFunctor) : oFunctor := {|\n  oFunctor_car A _ B _ := optionO (oFunctor_car F A B);\n  oFunctor_map A1 _ A2 _ B1 _ B2 _ fg := optionO_map (oFunctor_map F fg)\n|}.\nNext Obligation.\n  by intros F A1 ? A2 ? B1 ? B2 ? n f g Hfg; apply optionO_map_ne, oFunctor_map_ne.\nQed.\nNext Obligation.\n  intros F A ? B ? x. rewrite /= -{2}(option_fmap_id x).\n  apply option_fmap_equiv_ext=>y; apply oFunctor_map_id.\nQed.\nNext Obligation.\n  intros F A1 ? A2 ? A3 ? B1 ? B2 ? B3 ? f g f' g' x. rewrite /= -option_fmap_compose.\n  apply option_fmap_equiv_ext=>y; apply oFunctor_map_compose.\nQed.\n\nInstance optionOF_contractive F :\n  oFunctorContractive F → oFunctorContractive (optionOF F).\nProof.\n  by intros ? A1 ? A2 ? B1 ? B2 ? n f g Hfg;\n    apply optionO_map_ne, oFunctor_map_contractive.\nQed.\n\n(** * Later type *)\n(** Note that the projection [later_car] is not non-expansive (see also the\nlemma [later_car_anti_contractive] below), so it cannot be used in the logic.\nIf you need to get a witness out, you should use the lemma [Next_uninj]\ninstead. *)\nRecord later (A : Type) : Type := Next { later_car : A }.\nAdd Printing Constructor later.\nArguments Next {_} _.\nArguments later_car {_} _.\nInstance: Params (@Next) 1 := {}.\n\nSection later.\n  Context {A : ofeT}.\n  Instance later_equiv : Equiv (later A) := λ x y, later_car x ≡ later_car y.\n  Instance later_dist : Dist (later A) := λ n x y,\n    dist_later n (later_car x) (later_car y).\n  Definition later_ofe_mixin : OfeMixin (later A).\n  Proof.\n    split.\n    - intros x y; unfold equiv, later_equiv; rewrite !equiv_dist.\n      split. intros Hxy [|n]; [done|apply Hxy]. intros Hxy n; apply (Hxy (S n)).\n    - split; rewrite /dist /later_dist.\n      + by intros [x].\n      + by intros [x] [y].\n      + by intros [x] [y] [z] ??; trans y.\n    - intros [|n] [x] [y] ?; [done|]; rewrite /dist /later_dist; by apply dist_S.\n  Qed.\n  Canonical Structure laterO : ofeT := OfeT (later A) later_ofe_mixin.\n\n  Program Definition later_chain (c : chain laterO) : chain A :=\n    {| chain_car n := later_car (c (S n)) |}.\n  Next Obligation. intros c n i ?; apply (chain_cauchy c (S n)); lia. Qed.\n  Global Program Instance later_cofe `{Cofe A} : Cofe laterO :=\n    { compl c := Next (compl (later_chain c)) }.\n  Next Obligation.\n    intros ? [|n] c; [done|by apply (conv_compl n (later_chain c))].\n  Qed.\n\n  Global Instance Next_contractive : Contractive (@Next A).\n  Proof. by intros [|n] x y. Qed.\n  Global Instance Later_inj n : Inj (dist n) (dist (S n)) (@Next A).\n  Proof. by intros x y. Qed.\n\n  Lemma Next_uninj x : ∃ a, x ≡ Next a.\n  Proof. by exists (later_car x). Qed.\n  Instance later_car_anti_contractive n :\n    Proper (dist n ==> dist_later n) later_car.\n  Proof. move=> [x] [y] /= Hxy. done. Qed.\n\n  (** [f] is contractive iff it can factor into [Next] and a non-expansive\n  function. *)\n  Lemma contractive_alt {B : ofeT} (f : A → B) :\n    Contractive f ↔ ∃ g : later A → B, NonExpansive g ∧ ∀ x, f x ≡ g (Next x).\n  Proof.\n    split.\n    - intros Hf. exists (f ∘ later_car); split=> // n x y ?. by f_equiv.\n    - intros (g&Hg&Hf) n x y Hxy. rewrite !Hf. by apply Hg.\n  Qed.\nEnd later.\n\nArguments laterO : clear implicits.\n\nDefinition later_map {A B} (f : A → B) (x : later A) : later B :=\n  Next (f (later_car x)).\nInstance later_map_ne {A B : ofeT} (f : A → B) n :\n  Proper (dist (pred n) ==> dist (pred n)) f →\n  Proper (dist n ==> dist n) (later_map f) | 0.\nProof. destruct n as [|n]; intros Hf [x] [y] ?; do 2 red; simpl; auto. Qed.\nInstance later_map_proper {A B : ofeT} (f : A → B) :\n  Proper ((≡) ==> (≡)) f →\n  Proper ((≡) ==> (≡)) (later_map f).\nProof. solve_proper. Qed.\nLemma later_map_id {A} (x : later A) : later_map id x = x.\nProof. by destruct x. Qed.\nLemma later_map_compose {A B C} (f : A → B) (g : B → C) (x : later A) :\n  later_map (g ∘ f) x = later_map g (later_map f x).\nProof. by destruct x. Qed.\nLemma later_map_ext {A B : ofeT} (f g : A → B) x :\n  (∀ x, f x ≡ g x) → later_map f x ≡ later_map g x.\nProof. destruct x; intros Hf; apply Hf. Qed.\nDefinition laterO_map {A B} (f : A -n> B) : laterO A -n> laterO B :=\n  OfeMor (later_map f).\nInstance laterO_map_contractive (A B : ofeT) : Contractive (@laterO_map A B).\nProof. intros [|n] f g Hf n'; [done|]; apply Hf; lia. Qed.\n\nProgram Definition laterOF (F : oFunctor) : oFunctor := {|\n  oFunctor_car A _ B _ := laterO (oFunctor_car F A B);\n  oFunctor_map A1 _ A2 _ B1 _ B2 _ fg := laterO_map (oFunctor_map F fg)\n|}.\nNext Obligation.\n  intros F A1 ? A2 ? B1 ? B2 ? n fg fg' ?.\n  by apply (contractive_ne laterO_map), oFunctor_map_ne.\nQed.\nNext Obligation.\n  intros F A ? B ? x; simpl. rewrite -{2}(later_map_id x).\n  apply later_map_ext=>y. by rewrite oFunctor_map_id.\nQed.\nNext Obligation.\n  intros F A1 ? A2 ? A3 ? B1 ? B2 ? B3 ? f g f' g' x; simpl. rewrite -later_map_compose.\n  apply later_map_ext=>y; apply oFunctor_map_compose.\nQed.\nNotation \"▶ F\"  := (laterOF F%OF) (at level 20, right associativity) : oFunctor_scope.\n\nInstance laterOF_contractive F : oFunctorContractive (laterOF F).\nProof.\n  intros A1 ? A2 ? B1 ? B2 ? n fg fg' Hfg. apply laterO_map_contractive.\n  destruct n as [|n]; simpl in *; first done. apply oFunctor_map_ne, Hfg.\nQed.\n\n(** * Dependently-typed functions over a discrete domain *)\n(** This separate notion is useful whenever we need dependent functions, and\nwhenever we want to avoid the hassle of the bundled non-expansive function type.\n\nNote that non-dependent functions over a discrete domain, [A -d> B] (following\nthe notation we introduce below) are non-expansive if they are\n[Proper ((≡) ==> (≡))]. In other words, since the domain is discrete,\nnon-expansiveness and respecting [(≡)] are the same. If the domain is moreover\nLeibniz ([LeibnizEquiv A]), we get both for free.\n\nWe make [discrete_fun] a definition so that we can register it as a canonical\nstructure.  We do not bundle the [Proper] proof to keep [discrete_fun] easier to\nuse. It turns out all the desired OFE and functorial properties do not rely on\nthis [Proper] instance. *)\nDefinition discrete_fun {A} (B : A → ofeT) := ∀ x : A, B x.\n\nSection discrete_fun.\n  Context {A : Type} {B : A → ofeT}.\n  Implicit Types f g : discrete_fun B.\n\n  Instance discrete_fun_equiv : Equiv (discrete_fun B) := λ f g, ∀ x, f x ≡ g x.\n  Instance discrete_fun_dist : Dist (discrete_fun B) := λ n f g, ∀ x, f x ≡{n}≡ g x.\n  Definition discrete_fun_ofe_mixin : OfeMixin (discrete_fun B).\n  Proof.\n    split.\n    - intros f g; split; [intros Hfg n k; apply equiv_dist, Hfg|].\n      intros Hfg k; apply equiv_dist=> n; apply Hfg.\n    - intros n; split.\n      + by intros f x.\n      + by intros f g ? x.\n      + by intros f g h ?? x; trans (g x).\n    - by intros n f g ? x; apply dist_S.\n  Qed.\n  Canonical Structure discrete_funO := OfeT (discrete_fun B) discrete_fun_ofe_mixin.\n\n  Program Definition discrete_fun_chain `(c : chain discrete_funO)\n    (x : A) : chain (B x) := {| chain_car n := c n x |}.\n  Next Obligation. intros c x n i ?. by apply (chain_cauchy c). Qed.\n  Global Program Instance discrete_fun_cofe `{∀ x, Cofe (B x)} : Cofe discrete_funO :=\n    { compl c x := compl (discrete_fun_chain c x) }.\n  Next Obligation. intros ? n c x. apply (conv_compl n (discrete_fun_chain c x)). Qed.\n\n  Global Instance discrete_fun_inhabited `{∀ x, Inhabited (B x)} : Inhabited discrete_funO :=\n    populate (λ _, inhabitant).\n  Global Instance discrete_fun_lookup_discrete `{EqDecision A} f x :\n    Discrete f → Discrete (f x).\n  Proof.\n    intros Hf y ?.\n    set (g x' := if decide (x = x') is left H then eq_rect _ B y _ H else f x').\n    trans (g x).\n    { apply Hf=> x'. unfold g. by destruct (decide _) as [[]|]. }\n    unfold g. destruct (decide _) as [Hx|]; last done.\n    by rewrite (proof_irrel Hx eq_refl).\n  Qed.\nEnd discrete_fun.\n\nArguments discrete_funO {_} _.\nNotation \"A -d> B\" :=\n  (@discrete_funO A (λ _, B)) (at level 99, B at level 200, right associativity).\n\nDefinition discrete_fun_map {A} {B1 B2 : A → ofeT} (f : ∀ x, B1 x → B2 x)\n  (g : discrete_fun B1) : discrete_fun B2 := λ x, f _ (g x).\n\nLemma discrete_fun_map_ext {A} {B1 B2 : A → ofeT} (f1 f2 : ∀ x, B1 x → B2 x)\n  (g : discrete_fun B1) :\n  (∀ x, f1 x (g x) ≡ f2 x (g x)) → discrete_fun_map f1 g ≡ discrete_fun_map f2 g.\nProof. done. Qed.\nLemma discrete_fun_map_id {A} {B : A → ofeT} (g : discrete_fun B) :\n  discrete_fun_map (λ _, id) g = g.\nProof. done. Qed.\nLemma discrete_fun_map_compose {A} {B1 B2 B3 : A → ofeT}\n    (f1 : ∀ x, B1 x → B2 x) (f2 : ∀ x, B2 x → B3 x) (g : discrete_fun B1) :\n  discrete_fun_map (λ x, f2 x ∘ f1 x) g = discrete_fun_map f2 (discrete_fun_map f1 g).\nProof. done. Qed.\n\nInstance discrete_fun_map_ne {A} {B1 B2 : A → ofeT} (f : ∀ x, B1 x → B2 x) n :\n  (∀ x, Proper (dist n ==> dist n) (f x)) →\n  Proper (dist n ==> dist n) (discrete_fun_map f).\nProof. by intros ? y1 y2 Hy x; rewrite /discrete_fun_map (Hy x). Qed.\n\nDefinition discrete_funO_map {A} {B1 B2 : A → ofeT} (f : discrete_fun (λ x, B1 x -n> B2 x)) :\n  discrete_funO B1 -n> discrete_funO B2 := OfeMor (discrete_fun_map f).\nInstance discrete_funO_map_ne {A} {B1 B2 : A → ofeT} :\n  NonExpansive (@discrete_funO_map A B1 B2).\nProof. intros n f1 f2 Hf g x; apply Hf. Qed.\n\nProgram Definition discrete_funOF {C} (F : C → oFunctor) : oFunctor := {|\n  oFunctor_car A _ B _ := discrete_funO (λ c, oFunctor_car (F c) A B);\n  oFunctor_map A1 _ A2 _ B1 _ B2 _ fg := discrete_funO_map (λ c, oFunctor_map (F c) fg)\n|}.\nNext Obligation.\n  intros C F A1 ? A2 ? B1 ? B2 ? n ?? g.\n  by apply discrete_funO_map_ne=>?; apply oFunctor_map_ne.\nQed.\nNext Obligation.\n  intros C F A ? B ? g; simpl. rewrite -{2}(discrete_fun_map_id g).\n  apply discrete_fun_map_ext=> y; apply oFunctor_map_id.\nQed.\nNext Obligation.\n  intros C F A1 ? A2 ? A3 ? B1 ? B2 ? B3 ? f1 f2 f1' f2' g.\n  rewrite /= -discrete_fun_map_compose.\n  apply discrete_fun_map_ext=>y; apply oFunctor_map_compose.\nQed.\n\nNotation \"T -d> F\" := (@discrete_funOF T%type (λ _, F%OF)) : oFunctor_scope.\n\nInstance discrete_funOF_contractive {C} (F : C → oFunctor) :\n  (∀ c, oFunctorContractive (F c)) → oFunctorContractive (discrete_funOF F).\nProof.\n  intros ? A1 ? A2 ? B1 ? B2 ? n ?? g.\n  by apply discrete_funO_map_ne=>c; apply oFunctor_map_contractive.\nQed.\n\n(** * Constructing isomorphic OFEs *)\nLemma iso_ofe_mixin {A : ofeT} {B : Type} `{!Equiv B, !Dist B} (g : B → A)\n  (g_equiv : ∀ y1 y2, y1 ≡ y2 ↔ g y1 ≡ g y2)\n  (g_dist : ∀ n y1 y2, y1 ≡{n}≡ y2 ↔ g y1 ≡{n}≡ g y2) : OfeMixin B.\nProof.\n  split.\n  - intros y1 y2. rewrite g_equiv. setoid_rewrite g_dist. apply equiv_dist.\n  - split.\n    + intros y. by apply g_dist.\n    + intros y1 y2. by rewrite !g_dist.\n    + intros y1 y2 y3. rewrite !g_dist. intros ??; etrans; eauto.\n  - intros n y1 y2. rewrite !g_dist. apply dist_S.\nQed.\n\nSection iso_cofe_subtype.\n  Context {A B : ofeT} `{Cofe A} (P : A → Prop) (f : ∀ x, P x → B) (g : B → A).\n  Context (g_dist : ∀ n y1 y2, y1 ≡{n}≡ y2 ↔ g y1 ≡{n}≡ g y2).\n  Let Hgne : NonExpansive g.\n  Proof. intros n y1 y2. apply g_dist. Qed.\n  Existing Instance Hgne.\n  Context (gf : ∀ x Hx, g (f x Hx) ≡ x).\n  Context (Hlimit : ∀ c : chain B, P (compl (chain_map g c))).\n  Program Definition iso_cofe_subtype : Cofe B :=\n    {| compl c := f (compl (chain_map g c)) _ |}.\n  Next Obligation. apply Hlimit. Qed.\n  Next Obligation.\n    intros n c; simpl. apply g_dist. by rewrite gf conv_compl.\n  Qed.\nEnd iso_cofe_subtype.\n\nLemma iso_cofe_subtype' {A B : ofeT} `{Cofe A}\n  (P : A → Prop) (f : ∀ x, P x → B) (g : B → A)\n  (Pg : ∀ y, P (g y))\n  (g_dist : ∀ n y1 y2, y1 ≡{n}≡ y2 ↔ g y1 ≡{n}≡ g y2)\n  (gf : ∀ x Hx, g (f x Hx) ≡ x)\n  (Hlimit : LimitPreserving P) : Cofe B.\nProof. apply: (iso_cofe_subtype P f g)=> // c. apply Hlimit=> ?; apply Pg. Qed.\n\nDefinition iso_cofe {A B : ofeT} `{Cofe A} (f : A → B) (g : B → A)\n  (g_dist : ∀ n y1 y2, y1 ≡{n}≡ y2 ↔ g y1 ≡{n}≡ g y2)\n  (gf : ∀ x, g (f x) ≡ x) : Cofe B.\nProof. by apply (iso_cofe_subtype (λ _, True) (λ x _, f x) g). Qed.\n\n(** * Sigma type *)\nSection sigma.\n  Context {A : ofeT} {P : A → Prop}.\n  Implicit Types x : sig P.\n\n  (* TODO: Find a better place for this Equiv instance. It also\n     should not depend on A being an OFE. *)\n  Instance sig_equiv : Equiv (sig P) := λ x1 x2, `x1 ≡ `x2.\n  Instance sig_dist : Dist (sig P) := λ n x1 x2, `x1 ≡{n}≡ `x2.\n\n  Definition sig_equiv_alt x y : x ≡ y ↔ `x ≡ `y := reflexivity _.\n  Definition sig_dist_alt n x y : x ≡{n}≡ y ↔ `x ≡{n}≡ `y := reflexivity _.\n\n  Lemma exist_ne n a1 a2 (H1 : P a1) (H2 : P a2) :\n    a1 ≡{n}≡ a2 → a1 ↾ H1 ≡{n}≡ a2 ↾ H2.\n  Proof. done. Qed.\n\n  Global Instance proj1_sig_ne : NonExpansive (@proj1_sig _ P).\n  Proof. by intros n [a Ha] [b Hb] ?. Qed.\n  Definition sig_ofe_mixin : OfeMixin (sig P).\n  Proof. by apply (iso_ofe_mixin proj1_sig). Qed.\n  Canonical Structure sigO : ofeT := OfeT (sig P) sig_ofe_mixin.\n\n  Global Instance sig_cofe `{Cofe A, !LimitPreserving P} : Cofe sigO.\n  Proof. apply (iso_cofe_subtype' P (exist P) proj1_sig)=> //. by intros []. Qed.\n\n  Global Instance sig_discrete (x : sig P) :  Discrete (`x) → Discrete x.\n  Proof. intros ? y. rewrite sig_dist_alt sig_equiv_alt. apply (discrete _). Qed.\n  Global Instance sig_ofe_discrete : OfeDiscrete A → OfeDiscrete sigO.\n  Proof. intros ??. apply _. Qed.\nEnd sigma.\n\nArguments sigO {_} _.\n\n(** * SigmaT type *)\n(** Ofe for [sigT]. The first component must be discrete and use Leibniz\nequality, while the second component might be any OFE. *)\nSection sigT.\n  Import EqNotations.\n\n  Context {A : Type} {P : A → ofeT}.\n  Implicit Types x : sigT P.\n\n  (**\n    The distance for [{ a : A & P }] uses Leibniz equality on [A] to\n    transport the second components to the same type,\n    and then step-indexed distance on the second component.\n    Unlike in the topos of trees, with (C)OFEs we cannot use step-indexed equality\n    on the first component.\n  *)\n  Instance sigT_dist : Dist (sigT P) := λ n x1 x2,\n    ∃ Heq : projT1 x1 = projT1 x2, rew Heq in projT2 x1 ≡{n}≡ projT2 x2.\n\n  (**\n    Usually we'd give a direct definition, and show it equivalent to\n    [∀ n, x1 ≡{n}≡ x2] when proving the [equiv_dist] OFE axiom.\n    But here the equivalence requires UIP — see [sigT_equiv_eq_alt].\n    By defining [equiv] in terms of [dist], we can define an OFE\n    without assuming UIP, at the cost of complex reasoning on [equiv].\n  *)\n  Instance sigT_equiv : Equiv (sigT P) := λ x1 x2,\n    ∀ n, x1 ≡{n}≡ x2.\n\n  (** Unfolding lemmas.\n      Written with [↔] not [=] to avoid https://github.com/coq/coq/issues/3814. *)\n  Definition sigT_equiv_eq x1 x2 : (x1 ≡ x2) ↔ ∀ n, x1 ≡{n}≡ x2 :=\n      reflexivity _.\n\n  Definition sigT_dist_eq x1 x2 n : (x1 ≡{n}≡ x2) ↔\n    ∃ Heq : projT1 x1 = projT1 x2, (rew Heq in projT2 x1) ≡{n}≡ projT2 x2 :=\n      reflexivity _.\n\n  Definition sigT_dist_proj1 n {x y} : x ≡{n}≡ y → projT1 x = projT1 y := proj1_ex.\n  Definition sigT_equiv_proj1 {x y} : x ≡ y → projT1 x = projT1 y := λ H, proj1_ex (H 0).\n\n  Definition sigT_ofe_mixin : OfeMixin (sigT P).\n  Proof.\n    split => // n.\n    - split; hnf; setoid_rewrite sigT_dist_eq.\n      + intros. by exists eq_refl.\n      + move => [xa x] [ya y] /=. destruct 1 as [-> Heq].\n        by exists eq_refl.\n      + move => [xa x] [ya y] [za z] /=.\n        destruct 1 as [-> Heq1].\n        destruct 1 as [-> Heq2]. exists eq_refl => /=. by trans y.\n    - setoid_rewrite sigT_dist_eq.\n      move => [xa x] [ya y] /=. destruct 1 as [-> Heq].\n      exists eq_refl. exact: dist_S.\n  Qed.\n\n  Canonical Structure sigTO : ofeT := OfeT (sigT P) sigT_ofe_mixin.\n\n  Lemma sigT_equiv_eq_alt `{!∀ a b : A, ProofIrrel (a = b)} x1 x2 :\n    x1 ≡ x2 ↔\n    ∃ Heq : projT1 x1 = projT1 x2, rew Heq in projT2 x1 ≡ projT2 x2.\n  Proof.\n    setoid_rewrite equiv_dist; setoid_rewrite sigT_dist_eq; split => Heq.\n    - move: (Heq 0) => [H0eq1 _].\n      exists H0eq1 => n. move: (Heq n) => [] Hneq1.\n      by rewrite (proof_irrel H0eq1 Hneq1).\n    - move: Heq => [Heq1 Heqn2] n. by exists Heq1.\n  Qed.\n\n  (** [projT1] is non-expansive and proper. *)\n  Global Instance projT1_ne : NonExpansive (projT1 : sigTO → leibnizO A).\n  Proof. solve_proper. Qed.\n\n  Global Instance projT1_proper : Proper ((≡) ==> (≡)) (projT1 : sigTO → leibnizO A).\n  Proof. apply ne_proper, projT1_ne. Qed.\n\n  (** [projT2] is \"non-expansive\"; the properness lemma [projT2_ne] requires UIP. *)\n  Lemma projT2_ne n (x1 x2 : sigTO) (Heq : x1 ≡{n}≡ x2) :\n    rew (sigT_dist_proj1 n Heq) in projT2 x1 ≡{n}≡ projT2 x2.\n  Proof. by destruct Heq. Qed.\n\n  Lemma projT2_proper `{!∀ a b : A, ProofIrrel (a = b)} (x1 x2 : sigTO) (Heqs : x1 ≡ x2):\n    rew (sigT_equiv_proj1 Heqs) in projT2 x1 ≡ projT2 x2.\n  Proof.\n    move: x1 x2 Heqs => [a1 x1] [a2 x2] Heqs.\n    case: (proj1 (sigT_equiv_eq_alt _ _) Heqs) => /=. intros ->.\n    rewrite (proof_irrel (sigT_equiv_proj1 Heqs) eq_refl) /=. done.\n  Qed.\n\n  (** [existT] is \"non-expansive\" — general, dependently-typed statement. *)\n  Lemma existT_ne n {i1 i2} {v1 : P i1} {v2 : P i2} :\n    ∀ (Heq : i1 = i2), (rew f_equal P Heq in v1 ≡{n}≡ v2) →\n      existT i1 v1 ≡{n}≡ existT i2 v2.\n  Proof. intros ->; simpl. exists eq_refl => /=. done. Qed.\n\n  Lemma existT_proper {i1 i2} {v1 : P i1} {v2 : P i2} :\n    ∀ (Heq : i1 = i2), (rew f_equal P Heq in v1 ≡ v2) →\n      existT i1 v1 ≡ existT i2 v2.\n  Proof. intros Heq Heqv n. apply (existT_ne n Heq), equiv_dist, Heqv. Qed.\n\n  (** [existT] is \"non-expansive\" — non-dependently-typed version. *)\n  Global Instance existT_ne_2 a : NonExpansive (@existT A P a).\n  Proof. move => ??? Heq. apply (existT_ne _ eq_refl Heq). Qed.\n\n  Global Instance existT_proper_2 a : Proper ((≡) ==> (≡)) (@existT A P a).\n  Proof. apply ne_proper, _. Qed.\n\n  Implicit Types (c : chain sigTO).\n\n  Global Instance sigT_discrete x : Discrete (projT2 x) → Discrete x.\n  Proof.\n    move: x => [xa x] ? [ya y] [] /=; intros -> => /= Hxy n.\n    exists eq_refl => /=. apply equiv_dist, (discrete _), Hxy.\n  Qed.\n\n  Global Instance sigT_ofe_discrete : (∀ a, OfeDiscrete (P a)) → OfeDiscrete sigTO.\n  Proof. intros ??. apply _. Qed.\n\n  Lemma sigT_chain_const_proj1 c n : projT1 (c n) = projT1 (c 0).\n  Proof. refine (sigT_dist_proj1 _ (chain_cauchy c 0 n _)). lia. Qed.\n\n  (* For this COFE construction we need UIP (Uniqueness of Identity Proofs)\n    on [A] (i.e. [∀ x y : A, ProofIrrel (x = y)]. UIP is most commonly obtained\n    from decidable equality (by Hedberg’s theorem, see\n    [stdpp.proof_irrel.eq_pi]). *)\n  Section cofe.\n    Context `{!∀ a b : A, ProofIrrel (a = b)} `{!∀ a, Cofe (P a)}.\n\n    Program Definition chain_map_snd c : chain (P (projT1 (c 0))) :=\n      {| chain_car n := rew (sigT_chain_const_proj1 c n) in projT2 (c n) |}.\n    Next Obligation.\n      move => c n i Hle /=.\n      (* [Hgoal] is our thesis, up to casts: *)\n      case: (chain_cauchy c n i Hle) => [Heqin Hgoal] /=.\n      (* Pretty delicate. We have two casts to [projT1 (c 0)].\n        We replace those by one cast. *)\n      move: (sigT_chain_const_proj1 c i) (sigT_chain_const_proj1 c n)\n        => Heqi0 Heqn0.\n      (* Rewrite [projT1 (c 0)] to [projT1 (c n)] in goal and [Heqi0]: *)\n      destruct Heqn0.\n      by rewrite /= (proof_irrel Heqi0 Heqin).\n    Qed.\n\n    Definition sigT_compl : Compl sigTO :=\n      λ c, existT (projT1 (chain_car c 0)) (compl (chain_map_snd c)).\n\n    Global Program Instance sigT_cofe : Cofe sigTO := { compl := sigT_compl }.\n    Next Obligation.\n      intros n c. rewrite /sigT_compl sigT_dist_eq /=.\n      exists (symmetry (sigT_chain_const_proj1 c n)).\n      (* Our thesis, up to casts: *)\n      pose proof (conv_compl n (chain_map_snd c)) as Hgoal.\n      move: (compl (chain_map_snd c)) Hgoal => pc0 /=.\n      destruct (sigT_chain_const_proj1 c n); simpl. done.\n    Qed.\n  End cofe.\nEnd sigT.\n\nArguments sigTO {_} _.\n\nSection sigTOF.\n  Context {A : Type}.\n\n  Program Definition sigT_map {P1 P2 : A → ofeT} :\n    discrete_funO (λ a, P1 a -n> P2 a) -n>\n    sigTO P1 -n> sigTO P2 :=\n    λne f xpx, existT _ (f _ (projT2 xpx)).\n  Next Obligation.\n    move => ?? f n [x px] [y py] [/= Heq]. destruct Heq; simpl.\n    exists eq_refl => /=. by f_equiv.\n  Qed.\n  Next Obligation.\n    move => ?? n f g Heq [x px] /=. exists eq_refl => /=. apply Heq.\n  Qed.\n\n  Program Definition sigTOF (F : A → oFunctor) : oFunctor := {|\n    oFunctor_car A CA B CB := sigTO (λ a, oFunctor_car (F a) A B);\n    oFunctor_map A1 _ A2 _ B1 _ B2 _ fg := sigT_map (λ a, oFunctor_map (F a) fg)\n  |}.\n  Next Obligation.\n    repeat intro. exists eq_refl => /=. solve_proper.\n  Qed.\n  Next Obligation.\n    simpl; intros. apply (existT_proper eq_refl), oFunctor_map_id.\n  Qed.\n  Next Obligation.\n    simpl; intros. apply (existT_proper eq_refl), oFunctor_map_compose.\n  Qed.\n\n  Global Instance sigTOF_contractive {F} :\n    (∀ a, oFunctorContractive (F a)) → oFunctorContractive (sigTOF F).\n  Proof.\n    repeat intro. apply sigT_map => a. exact: oFunctor_map_contractive.\n  Qed.\nEnd sigTOF.\nArguments sigTOF {_} _%OF.\n\nNotation \"{ x  &  P }\" := (sigTOF (λ x, P%OF)) : oFunctor_scope.\nNotation \"{ x : A &  P }\" := (@sigTOF A%type (λ x, P%OF)) : oFunctor_scope.\n\n(** * Isomorphisms between OFEs *)\nRecord ofe_iso (A B : ofeT) := OfeIso {\n  ofe_iso_1 : A -n> B;\n  ofe_iso_2 : B -n> A;\n  ofe_iso_12 y : ofe_iso_1 (ofe_iso_2 y) ≡ y;\n  ofe_iso_21 x : ofe_iso_2 (ofe_iso_1 x) ≡ x;\n}.\nArguments OfeIso {_ _} _ _ _ _.\nArguments ofe_iso_1 {_ _} _.\nArguments ofe_iso_2 {_ _} _.\nArguments ofe_iso_12 {_ _} _ _.\nArguments ofe_iso_21 {_ _} _ _.\n\nSection ofe_iso.\n  Context {A B : ofeT}.\n\n  Instance ofe_iso_equiv : Equiv (ofe_iso A B) := λ I1 I2,\n    ofe_iso_1 I1 ≡ ofe_iso_1 I2 ∧ ofe_iso_2 I1 ≡ ofe_iso_2 I2.\n\n  Instance ofe_iso_dist : Dist (ofe_iso A B) := λ n I1 I2,\n    ofe_iso_1 I1 ≡{n}≡ ofe_iso_1 I2 ∧ ofe_iso_2 I1 ≡{n}≡ ofe_iso_2 I2.\n\n  Global Instance ofe_iso_1_ne : NonExpansive (ofe_iso_1 (A:=A) (B:=B)).\n  Proof. by destruct 1. Qed.\n  Global Instance ofe_iso_2_ne : NonExpansive (ofe_iso_2 (A:=A) (B:=B)).\n  Proof. by destruct 1. Qed.\n\n  Lemma ofe_iso_ofe_mixin : OfeMixin (ofe_iso A B).\n  Proof. by apply (iso_ofe_mixin (λ I, (ofe_iso_1 I, ofe_iso_2 I))). Qed.\n  Canonical Structure ofe_isoO : ofeT := OfeT (ofe_iso A B) ofe_iso_ofe_mixin.\n\n  Global Instance ofe_iso_cofe `{!Cofe A, !Cofe B} : Cofe ofe_isoO.\n  Proof.\n    apply (iso_cofe_subtype'\n      (λ I : prodO (A -n> B) (B -n> A),\n        (∀ y, I.1 (I.2 y) ≡ y) ∧ (∀ x, I.2 (I.1 x) ≡ x))\n      (λ I HI, OfeIso (I.1) (I.2) (proj1 HI) (proj2 HI))\n      (λ I, (ofe_iso_1 I, ofe_iso_2 I))); [by intros []|done|done|].\n    apply limit_preserving_and; apply limit_preserving_forall=> ?;\n      apply limit_preserving_equiv; first [intros ???; done|solve_proper].\n  Qed.\nEnd ofe_iso.\n\nArguments ofe_isoO : clear implicits.\n\nProgram Definition iso_ofe_refl {A} : ofe_iso A A := OfeIso cid cid _ _.\nSolve Obligations with done.\n\nDefinition iso_ofe_sym {A B : ofeT} (I : ofe_iso A B) : ofe_iso B A :=\n  OfeIso (ofe_iso_2 I) (ofe_iso_1 I) (ofe_iso_21 I) (ofe_iso_12 I).\nInstance iso_ofe_sym_ne {A B} : NonExpansive (iso_ofe_sym (A:=A) (B:=B)).\nProof. intros n I1 I2 []; split; simpl; by f_equiv. Qed.\n\nProgram Definition iso_ofe_trans {A B C}\n    (I : ofe_iso A B) (J : ofe_iso B C) : ofe_iso A C :=\n  OfeIso (ofe_iso_1 J ◎ ofe_iso_1 I) (ofe_iso_2 I ◎ ofe_iso_2 J) _ _.\nNext Obligation. intros A B C I J z; simpl. by rewrite !ofe_iso_12. Qed.\nNext Obligation. intros A B C I J z; simpl. by rewrite !ofe_iso_21. Qed.\nInstance iso_ofe_trans_ne {A B C} : NonExpansive2 (iso_ofe_trans (A:=A) (B:=B) (C:=C)).\nProof. intros n I1 I2 [] J1 J2 []; split; simpl; by f_equiv. Qed.\n\nProgram Definition iso_ofe_cong (F : oFunctor) `{!Cofe A, !Cofe B}\n    (I : ofe_iso A B) : ofe_iso (oFunctor_apply F A) (oFunctor_apply F B) :=\n  OfeIso (oFunctor_map F (ofe_iso_2 I, ofe_iso_1 I))\n    (oFunctor_map F (ofe_iso_1 I, ofe_iso_2 I)) _ _.\nNext Obligation.\n  intros F A ? B ? I x. rewrite -oFunctor_map_compose -{2}(oFunctor_map_id F x).\n  apply equiv_dist=> n.\n  apply oFunctor_map_ne; split=> ? /=; by rewrite ?ofe_iso_12 ?ofe_iso_21.\nQed.\nNext Obligation.\n  intros F A ? B ? I y. rewrite -oFunctor_map_compose -{2}(oFunctor_map_id F y).\n  apply equiv_dist=> n.\n  apply oFunctor_map_ne; split=> ? /=; by rewrite ?ofe_iso_12 ?ofe_iso_21.\nQed.\nInstance iso_ofe_cong_ne (F : oFunctor) `{!Cofe A, !Cofe B} :\n  NonExpansive (iso_ofe_cong F (A:=A) (B:=B)).\nProof. intros n I1 I2 []; split; simpl; by f_equiv. Qed.\nInstance iso_ofe_cong_contractive (F : oFunctor) `{!Cofe A, !Cofe B} :\n  oFunctorContractive F → Contractive (iso_ofe_cong F (A:=A) (B:=B)).\nProof. intros ? n I1 I2 HI; split; simpl; f_contractive; by destruct HI. Qed.\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/ofe.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2910034706406652}}
{"text": "From mathcomp Require Import ssreflect ssrbool ssrfun ssrnat eqtype seq.\nFrom pcm Require Import options axioms pred prelude.\nFrom pcm Require Import pcm unionmap heap.\nFrom htt Require Import domain.\n\n(* Exceptions are an equality type *)\nInductive exn : Type := exn_from_nat of nat.\n\nDefinition exn_to_nat :=\n  fun '(exn_from_nat y) => y.\n\nDefinition eqexn :=\n  fun '(exn_from_nat m) '(exn_from_nat n) => m == n.\n\nLemma eqexnP : Equality.axiom eqexn.\nProof. by move=>[x][y]/=; case: eqP=>[->|*]; constructor=>//; case. Qed.\n\nCanonical Structure exn_eqMixin := EqMixin eqexnP.\nCanonical Structure exn_eqType := EqType exn exn_eqMixin.\n\n(* Answer type *)\nInductive ans (A : Type) : Type := Val of A | Exn of exn.\nArguments Exn [A].\n\n(* A set of heaps *)\nNotation pre := (Pred heap).\n\n(* A set of (ans A * heap) *)\n(* This models the fact that programs can hang, returning nothing, *)\n(* or produce nondeterministic results (e.g. alloc). *)\nNotation post A := (ans A -> heap -> Prop).\n\nDefinition spec G A := G -> pre * post A : Type.\n\n(*************************************************************)\n(* List of inference rules, with vrf predicate kept abstract *)\n(*************************************************************)\n\nModule Type VrfSig.\n\nParameter ST : Type -> Type.\n\nParameter ret : forall A, A -> ST A.\nParameter throw : forall A, exn -> ST A.\nParameter bind : forall A B, ST A -> (A -> ST B) -> ST B.\nParameter try : forall A B, ST A -> (A -> ST B) -> (exn -> ST B) -> ST B.\nParameter read : forall A, ptr -> ST A.\nParameter write : forall A, ptr -> A -> ST unit.\nParameter alloc : forall A, A -> ST ptr.\nParameter allocb : forall A, A -> nat -> ST ptr.\nParameter dealloc : ptr -> ST unit.\n\nArguments throw [A] e.\nArguments read [A] x.\n\n(* we need program to come first in the argument list\n   so that automation can match on it *)\nParameter vrf' : forall A, ST A -> heap -> post A -> Prop.\n\n(* recover the usual [pre]prog[post] order with a notation *)\nNotation vrf i e Q := (vrf' e i Q).\n\nParameter vrfV : forall A e i (Q : post A),\n            (valid i -> vrf i e Q) -> vrf i e Q.\nParameter vrf_post : forall A e i (Q1 Q2 : post A),\n            (forall y m, valid m -> Q1 y m -> Q2 y m) ->\n            vrf i e Q1 -> vrf i e Q2.\nParameter vrf_frame : forall A e i j (Q : post A),\n            vrf i e (fun y m => valid (m \\+ j) -> Q y (m \\+ j)) ->\n            vrf (i \\+ j) e Q.\nParameter vrf_ret : forall A x i (Q : post A),\n            (valid i -> Q (Val x) i) -> vrf i (ret x) Q.\nParameter vrf_throw : forall A e i (Q : post A),\n            (valid i -> Q (Exn e) i) -> vrf i (throw e) Q.\nParameter vrf_bind : forall A B (e1 : ST A) (e2 : A -> ST B) i (Q : post B),\n            vrf i e1 (fun x m =>\n                        match x with\n                        | Val x' => vrf m (e2 x') Q\n                        | Exn e => valid m -> Q (Exn e) m\n                        end) ->\n            vrf i (bind e1 e2) Q.\nParameter vrf_try : forall A B (e : ST A) (e1 : A -> ST B) (e2 : exn -> ST B) i (Q : post B),\n            vrf i e (fun x m =>\n                       match x with\n                       | Val x' => vrf m (e1 x') Q\n                       | Exn ex => vrf m (e2 ex) Q\n                       end) ->\n            vrf i (try e e1 e2) Q.\nParameter vrf_read : forall A x j (v : A) (Q : post A),\n            (valid (x :-> v \\+ j) -> Q (Val v) (x :-> v \\+ j)) ->\n            vrf (x :-> v \\+ j) (read x) Q.\nParameter vrf_write : forall A x (v : A) B (u : B) j (Q : post unit),\n            (valid (x :-> v \\+ j) -> Q (Val tt) (x :-> v \\+ j)) ->\n            vrf (x :-> u \\+ j) (write x v) Q.\nParameter vrf_alloc : forall A (v : A) i (Q : post ptr),\n            (forall x, valid (x :-> v \\+ i) -> Q (Val x) (x :-> v \\+ i)) ->\n            vrf i (alloc v) Q.\nParameter vrf_allocb : forall A (v : A) n i (Q : post ptr),\n            (forall x, valid (updi x (nseq n v) \\+ i) ->\n               Q (Val x) (updi x (nseq n v) \\+ i)) ->\n            vrf i (allocb v n) Q.\nParameter vrf_dealloc : forall x A (v : A) j (Q : post unit),\n            (x \\notin dom j -> valid j -> Q (Val tt) j) ->\n            vrf (x :-> v \\+ j) (dealloc x) Q.\n\nDefinition has_spec G A (s : spec G A) (e : ST A) :=\n  forall g i, (s g).1 i -> vrf i e (s g).2.\n\nStructure STspec G A (s : spec G A) := STprog {\n  model :> ST A;\n  _ : model \\In has_spec s}.\n\nArguments STspec G [A] s.\n\nNotation \"'Do' e\" := (@STprog _ _ _ e _) (at level 80).\n\nNotation \"x '<--' c1 ';' c2\" := (bind c1 (fun x => c2))\n  (at level 81, right associativity).\nNotation \"c1 ';;' c2\" := (bind c1 (fun _ => c2))\n  (at level 81, right associativity).\nNotation \"'!' x\" := (read x) (at level 50).\nNotation \"x '::=' e\" := (write x e) (at level 60).\n\nParameter Fix : forall G A (B : A -> Type) (s : forall x : A, spec G (B x)),\n  ((forall x : A, STspec G (s x)) -> forall x : A, STspec G (s x)) ->\n  forall x : A, STspec G (s x).\n\nEnd VrfSig.\n\n\n(********************************)\n(* Definition of the Hoare type *)\n(********************************)\n\nModule Vrf : VrfSig.\n\nSection BasePrograms.\nVariables (P : pre) (A : Type).\n\n(* we carve out the model out of the following base type *)\nDefinition prog : Type := forall i : heap, valid i -> i \\In P -> post A.\n\n(* we take only preconditions and progs with special properties *)\n(* which we define next *)\n\n(* safety monotonicity *)\nDefinition safe_mono :=\n  forall i j, i \\In P -> valid (i \\+ j) -> i \\+ j \\In P.\n\n(* defined heaps map to defined heaps *)\nDefinition def_strict (e : prog) :=\n  forall i p v x, Heap.Undef \\Notin e i v p x.\n\n(* frame property *)\nDefinition frameable (e : prog) :=\n  forall i j (pf : i \\In P) (V : valid (i \\+ j)) (pf' : i \\+ j \\In P) y m,\n    e _ V pf' y m ->\n    exists h, [/\\ m = h \\+ j, valid (h \\+ j) & e _ (validL V) pf y h].\n\nEnd BasePrograms.\n\nSection STDef.\nVariable (A : Type).\n\nStructure ST' := Prog {\n  pre_of : pre;\n  prog_of : prog pre_of A;\n  _ : safe_mono pre_of;\n  _ : def_strict prog_of;\n  _ : frameable prog_of}.\n\n(* module field must be a definition, not structure *)\nDefinition ST := ST'.\n\nLemma sfm_st e : safe_mono (pre_of e).\nProof. by case: e. Qed.\n\nArguments prog_of : clear implicits.\n\nLemma dstr_st e : def_strict (prog_of e).\nProof. by case: e. Qed.\n\nCorollary dstr_valid e i p v x m :\n            m \\In prog_of e i p v x -> valid m.\nProof. by case: m=>// /dstr_st. Qed.\n\nLemma fr_st e : frameable (prog_of e).\nProof. by case: e. Qed.\n\nArguments fr_st [e i j].\n\n(* poset structure on ST *)\n\nDefinition st_leq e1 e2 :=\n  exists pf : pre_of e2 <== pre_of e1,\n  forall i (v : valid i) (p : i \\In pre_of e2),\n    prog_of e1 _ v (pf _ p) <== prog_of e2 _ v p.\n\nLemma st_refl e : st_leq e e.\nProof.\nexists (poset_refl _)=>i V P y m.\nby rewrite (pf_irr (poset_refl (pre_of e) i P) P).\nQed.\n\nLemma st_asym e1 e2 : st_leq e1 e2 -> st_leq e2 e1 -> e1 = e2.\nProof.\nmove: e1 e2=>[p1 e1 S1 D1 F1][p2 e2 S2 D2 F2]; rewrite /st_leq /=.\ncase=>E1 R1 [E2 R2].\nmove: (poset_asym E1 E2)=>?; subst p2.\nhave : e1 = e2.\n- apply: fext=>i; apply: fext=>Vi; apply: fext=>Pi; apply: fext=>y; apply: fext=>m.\n  move: (R2 i Vi Pi y m)=>{}R2; move: (R1 i Vi Pi y m)=>{}R1.\n  apply: pext; split.\n  - by move=>H1; apply: R1; rewrite (pf_irr (E1 i Pi) Pi).\n  by move=>H2; apply: R2; rewrite (pf_irr (E2 i Pi) Pi).\nmove=>?; subst e2.\nby congr Prog; apply: pf_irr.\nQed.\n\nLemma st_trans e1 e2 e3 : st_leq e1 e2 -> st_leq e2 e3 -> st_leq e1 e3.\nProof.\nmove: e1 e2 e3=>[p1 e1 S1 D1 F1][p2 e2 S2 D2 F2][p3 e3 S3 D3 F3].\ncase=>/= E1 R1 [/= E2 R2]; rewrite /st_leq /=.\nhave E3 := poset_trans E2 E1; exists E3=>i V P y m.\nset P' := E2 i P.\nmove: (R1 i V P' y m)=>{}R1; move: (R2 i V P y m)=>{}R2.\nmove=>H1; apply/R2/R1.\nby rewrite (pf_irr (E1 i P') (E3 i P)).\nQed.\n\n(* bottom is a program that can always run but never returns (an endless loop) *)\n\nDefinition pre_bot : pre := top.\n\nDefinition prog_bot : prog pre_bot A :=\n  fun _ _ _ _ => bot.\n\nLemma sfmono_bot : safe_mono pre_bot.\nProof. by []. Qed.\n\nLemma dstrict_bot : def_strict prog_bot.\nProof. by move=>*. Qed.\n\nLemma frame_bot : frameable prog_bot.\nProof. by []. Qed.\n\nDefinition st_bot := Prog sfmono_bot dstrict_bot frame_bot.\n\nLemma st_botP e : st_leq st_bot e.\nProof. by case: e=>p e S D F; exists (@pred_topP _ _)=>???; apply: botP. Qed.\n\nDefinition stPosetMixin := PosetMixin st_botP st_refl st_asym st_trans.\nCanonical stPoset := Eval hnf in Poset ST stPosetMixin.\n\n(* lattice structure on ST *)\n\n(* intersection of preconditions *)\nDefinition pre_sup (u : Pred ST) : pre :=\n  fun h => forall e, e \\In u -> h \\In pre_of e.\n\nDefinition pre_sup_leq u e (pf : e \\In u) : pre_sup u <== pre_of e :=\n  fun h (pf1 : pre_sup u h) => pf1 e pf.\n\n(* union of postconditions *)\nDefinition prog_sup (u : Pred ST) : prog (pre_sup u) A :=\n  fun i V P y m => exists e (pf : e \\In u),\n    prog_of e _ V (pre_sup_leq pf P) y m.\n\nArguments prog_sup : clear implicits.\n\nLemma pre_sup_sfmono u : safe_mono (pre_sup u).\nProof.\nmove=>i j Pi Vij e He.\nby apply: sfm_st=>//; apply: Pi.\nQed.\n\nLemma prog_sup_dstrict u : def_strict (prog_sup u).\nProof. by move=>i P V y; case; case=>p e S D F [H1] /D. Qed.\n\nLemma prog_sup_frame u : frameable (prog_sup u).\nProof.\nmove=>i j Pi Vij Pij y m [e][He]Pe.\nhave Pi' := Pi e He; have Pij' := Pij e He.\nmove: Pe; rewrite (pf_irr (pre_sup_leq He Pij) Pij').\ncase/(fr_st Pi' Vij Pij')=>h [{m}-> Vhj Ph].\nexists h; split=>//; exists e, He.\nby rewrite (pf_irr (pre_sup_leq He Pi) Pi').\nQed.\n\nDefinition st_sup u : ST :=\n  Prog (@pre_sup_sfmono u) (@prog_sup_dstrict u) (@prog_sup_frame u).\n\nLemma st_supP u e : e \\In u -> e <== st_sup u.\nProof.\ncase: e=>p e' S D F R.\nexists (pre_sup_leq R)=>/=p0 y m H.\nby exists (Prog S D F), R.\nQed.\n\nLemma st_supM u e :\n  (forall e1, e1 \\In u -> e1 <== e) -> st_sup u <== e.\nProof.\ncase: e=>p e S D F R.\nhave J : p <== pre_sup u.\n- by move=>/= x Px e' pf; case: (R _ pf)=>/= + _; apply.\nexists J=>i V P y m [e0][H0 Hm].\ncase: (R _ H0)=>/= Hx; apply.\nby rewrite (pf_irr (Hx i P) (pre_sup_leq H0 (J i P))).\nQed.\n\nDefinition stLatticeMixin := LatticeMixin st_supP st_supM.\nCanonical stLattice := Lattice ST stLatticeMixin.\n\nEnd STDef.\n\nArguments prog_of [A].\nArguments sfm_st [A e i j].\nArguments dstr_st [A e i].\nArguments fr_st [A e i j].\n\nSection STspecDef.\nVariables (G A : Type) (s : spec G A).\n\n(* strongest postcondition predicate transformer *)\n\nDefinition vrf' (e : ST A) i (Q : post A) :=\n  forall (V : valid i),\n    exists (pf : i \\In pre_of e), forall y m,\n      prog_of e _ V pf y m -> Q y m.\n\nNotation vrf i e Q := (vrf' e i Q).\n\nDefinition has_spec (e : ST A) :=\n  forall g i, (s g).1 i -> vrf i e (s g).2.\n\nStructure STspec := STprog {\n  model :> ST A;\n  _ : model \\In has_spec}.\n\nLemma modelE e1 e2 : e1 = e2 <-> model e1 = model e2.\nProof.\nmove: e1 e2=>[e1 H1][e2 H2] /=; split=>[[//]|E].\nby subst e2; congr STprog; apply: pf_irr.\nQed.\n\n(* poset structure on STspec *)\n\nDefinition stsp_leq e1 e2 := model e1 <== model e2.\n\nLemma stsp_refl e : stsp_leq e e.\nProof. by case: e=>e He; apply: poset_refl. Qed.\n\nLemma stsp_asym e1 e2 : stsp_leq e1 e2 -> stsp_leq e2 e1 -> e1 = e2.\nProof.\nmove: e1 e2=>[e1 H1][e2 H2]; rewrite /stsp_leq /= =>E1 E2.\nhave E := poset_asym E1 E2; subst e2.\nby congr STprog; apply: pf_irr.\nQed.\n\nLemma stsp_trans e1 e2 e3 : stsp_leq e1 e2 -> stsp_leq e2 e3 -> stsp_leq e1 e3.\nProof.\nmove: e1 e2 e3=>[e1 H1][e2 H2][e3 H3].\nby apply: poset_trans.\nQed.\n\nLemma st_bot_has_spec : @st_bot A \\In has_spec.\nProof. by move=>g i H V /=; exists I. Qed.\n\nDefinition stsp_bot := STprog st_bot_has_spec.\n\nLemma stsp_botP e : stsp_leq stsp_bot e.\nProof. by case: e=>*; apply: botP. Qed.\n\nDefinition stspPosetMixin := PosetMixin stsp_botP stsp_refl stsp_asym stsp_trans.\nCanonical stspPoset := Eval hnf in Poset STspec stspPosetMixin.\n\n(* lattice structure on STspec *)\n\nDefinition st_sup' (u : Pred STspec) : ST A :=\n  sup [Pred p | exists e, p = model e /\\ e \\In u].\n\nLemma st_sup_has_spec' u : st_sup' u \\In has_spec.\nProof.\nmove=>g i p Vi.\nhave J : i \\In pre_of (st_sup' u).\n- by move=>_ [e][->]; case: e=>e P; case: (P _ _ p Vi).\nexists J=>y m /= [e][[[e1 P]]][/= E He1] H; subst e1.\ncase: (P _ _ p Vi)=>Hi; apply.\nset I' := (X in prog_of e _ Vi X) in H.\nby rewrite (pf_irr Hi I').\nQed.\n\nDefinition stsp_sup u := STprog (@st_sup_has_spec' u).\n\nLemma stsp_supP u e : e \\In u -> e <== stsp_sup u.\nProof. by case: e=>p S R; apply: supP; exists (STprog S). Qed.\n\nLemma stsp_supM u e :\n        (forall e1, e1 \\In u -> e1 <== e) -> stsp_sup u <== e.\nProof. by case: e=>p S R; apply: supM=>/= y[q][->]; apply: R. Qed.\n\nDefinition stspLatticeMixin := LatticeMixin stsp_supP stsp_supM.\nCanonical stspLattice := Lattice STspec stspLatticeMixin.\n\nEnd STspecDef.\n\nNotation vrf i e Q := (vrf' e i Q).\n\n(************************************)\n(* modeling the language primitives *)\n(************************************)\n\n(* recursion *)\nSection Fix.\nVariables (G A : Type) (B : A -> Type) (s : forall x, spec G (B x)).\nNotation tp := (forall x, STspec (s x)).\nNotation lat := (dfunLattice (fun x => [lattice of STspec (s x)])).\nVariable (f : tp -> tp).\n\n(* we take a fixpoint not of f, but of its monotone completion f' *)\n\nDefinition f' (e : lat) :=\n  sup [Pred t : lat | exists e', e' <== e /\\ t = f e'].\n\nLemma f'_mono : monotone f'.\nProof.\nmove=>x y H; apply: sup_mono=>fz; case=>z [Hz {fz}->].\nby exists z; split=>//; apply/poset_trans/H.\nQed.\n\nDefinition Fix : tp := tarski_lfp f'.\n\n(* fixed point constructor which requires explicit proof of monotonicity *)\nDefinition Fix' (pf : monotone (f : lat -> lat)) : tp :=\n  tarski_lfp (f : lat -> lat).\n\nEnd Fix.\n\nArguments Fix [G A B s] f x.\nArguments Fix' [G A B s] f pf x.\n\nSection VrfLemmas.\nVariables (A : Type) (e : ST A).\n\nLemma vrfV i (Q : post A) :\n        (valid i -> vrf i e Q) -> vrf i e Q.\nProof. by move=>H V; apply: H. Qed.\n\nLemma vrf_post i (Q1 Q2 : post A) :\n        (forall y m, valid m -> Q1 y m -> Q2 y m) ->\n        vrf i e Q1 -> vrf i e Q2.\nProof.\nmove=>H H1 Vi; case: (H1 Vi)=>pf {}H1.\nexists pf=>y m Hm.\nby apply/H/H1=>//; exact: (dstr_valid Hm).\nQed.\n\nLemma vrf_frame i j (Q : post A) :\n        vrf i e (fun y m => valid (m \\+ j) -> Q y (m \\+ j)) ->\n        vrf (i \\+ j) e Q.\nProof.\nmove=>H Vij; have Vi := validL Vij; case: (H Vi)=>Hi {}H.\nhave Hij := sfm_st Hi Vij.\nexists Hij=>y m.\ncase/(fr_st Hi Vij Hij)=>h [{m}-> Vhj P].\napply: H=>//.\nby rewrite (pf_irr Vi (validL Vij)).\nQed.\n\nLemma frame_star i (Q : post A) (r : Pred heap) :\n        i \\In (fun h => vrf h e Q) # r -> vrf i e (fun v => Q v # r).\nProof.\ncase=>h1[h2][{i}-> H1 H2].\napply: vrf_frame=>V1; case: (H1 V1)=>Hp Hr.\nexists Hp=>y m Pm Vm2.\nexists m, h2; split=>//.\nby apply: Hr.\nQed.\n\nEnd VrfLemmas.\n\nSection Return.\nVariables (A : Type) (x : A).\n\nDefinition ret_pre : pre := top.\n\nDefinition ret_prog : prog ret_pre A :=\n  fun i _ _ y m =>\n    m = i /\\ y = Val x.\n\nLemma ret_sfmono : safe_mono ret_pre.\nProof. by []. Qed.\n\nLemma ret_dstrict : def_strict ret_prog.\nProof. by move=>i [] V _ /= [E _]; rewrite -E in V. Qed.\n\nLemma ret_frame : frameable ret_prog.\nProof. by move=>i j [Vij []] _ _ [-> ->]; exists i. Qed.\n\nDefinition ret := Prog ret_sfmono ret_dstrict ret_frame.\n\nLemma vrf_ret i (Q : post A) :\n        (valid i -> Q (Val x) i) -> vrf i ret Q.\nProof. by move=>H V; exists I=>_ _ [->->]; apply: H. Qed.\n\nEnd Return.\n\nSection Throw.\nVariables (A : Type) (e : exn).\n\nDefinition throw_pre : pre := top.\n\nDefinition throw_prog : prog throw_pre A :=\n  fun i _ _ y m =>\n    m = i /\\ y = @Exn A e.\n\nLemma throw_sfmono : safe_mono throw_pre.\nProof. by []. Qed.\n\nLemma throw_dstrict : def_strict throw_prog.\nProof. by move=>i [] V _ /= [E _]; rewrite -E in V. Qed.\n\nLemma throw_frame : frameable throw_prog.\nProof. by move=>i j [Vij []] _ _ [-> ->]; exists i. Qed.\n\nDefinition throw := Prog throw_sfmono throw_dstrict throw_frame.\n\nLemma vrf_throw i (Q : post A) :\n        (valid i -> Q (Exn e) i) -> vrf i throw Q.\nProof. by move=>H V; exists I=>_ _ [->->]; apply: H. Qed.\n\nEnd Throw.\n\nSection Bind.\nVariables (A B : Type).\nVariables (e1 : ST A) (e2 : A -> ST B).\n\nDefinition bind_pre : pre :=\n  fun i =>\n    exists (Vi : valid i) (Pi : i \\In pre_of e1),\n      forall x m, prog_of e1 _ Vi Pi (Val x) m -> pre_of (e2 x) m.\n\nDefinition bind_pre_proj i : i \\In bind_pre -> i \\In pre_of e1 :=\n  fun '(ex_intro _ (ex_intro p _)) => p.\n\nDefinition bind_prog : prog bind_pre B :=\n  fun i V P y m =>\n    exists x h (Ph : h \\In prog_of e1 _ V (bind_pre_proj P) x),\n      match x with\n      | Val x' => exists Ph' : h \\In pre_of (e2 x'),\n                    m \\In prog_of (e2 x') _ (dstr_valid Ph) Ph' y\n      | Exn e => y = Exn e /\\ m = h\n      end.\n\nLemma bind_sfmono : safe_mono bind_pre.\nProof.\nmove=>i j [Vi][Pi]P Vij.\nhave Pij := sfm_st Pi Vij.\nexists Vij, Pij=>x m.\ncase/(fr_st Pi Vij Pij)=>h [{m}-> Vhj].\nrewrite (pf_irr (validL Vij) Vi)=>/P Ph.\nby apply: sfm_st=>//; apply: (validL Vhj).\nQed.\n\nLemma bind_dstrict : def_strict bind_prog.\nProof.\nmove=>i [Vi][Pi P] Vi' y[x][h][/=].\ncase: x=>[x|e]Ph.\n- by case=>Ph' /dstr_st.\nby case=>_; move: Ph=>/[swap]<- /dstr_st.\nQed.\n\nLemma bind_frame : frameable bind_prog.\nProof.\nmove=>i j [Vi][Pi P] Vij [_ [Pij _]] y m [x][h][/=].\nmove: (fr_st Pi Vij Pij)=>H.\ncase: x=>[x|e] Ph.\n- case=>Ph'.\n  case: (H _ _ Ph)=>h1[Eh V1 Ph1]; subst h.\n  rewrite (pf_irr (validL Vij) Vi) in Ph1 *; move: (P _ _  Ph1)=> P21.\n  rewrite (pf_irr (dstr_valid Ph) V1).\n  case/(fr_st P21 V1 Ph')=>h2[Em Vm Ph2].\n  exists h2; split=>//; exists (Val x), h1, Ph1, P21.\n  by rewrite (pf_irr (dstr_valid Ph1) (validL V1)).\ncase=>->->.\ncase/H: Ph=>h1[Eh Vh Ph1].\nby exists h1; split=>//; exists (Exn e), h1, Ph1.\nQed.\n\nDefinition bind := Prog bind_sfmono bind_dstrict bind_frame.\n\nLemma vrf_bind i (Q : post B) :\n        vrf i e1 (fun x m =>\n                    match x with\n                    | Val x' => vrf m (e2 x') Q\n                    | Exn e => valid m -> Q (Exn e) m\n                    end) ->\n        vrf i bind Q.\nProof.\nmove=>H Vi; case: (H Vi)=>Hi {}H /=.\nhave Hi' : i \\In bind_pre.\n- by exists Vi, Hi=>x m Pm; case: (H _ _ Pm (dstr_valid Pm)).\nexists Hi'=>y j /= [x][m][Pm] C.\nrewrite (pf_irr Hi (bind_pre_proj Hi')) in H.\ncase: x Pm C=>[x|e] Pm; move: (H _ _ Pm (dstr_valid Pm))=>{}H.\n- by case=>Pm2 Pj; case: H=>Pm2'; apply; rewrite (pf_irr Pm2' Pm2).\nby case=>->->.\nQed.\n\nEnd Bind.\n\nSection Try.\nVariables (A B : Type).\nVariables (e : ST A) (e1 : A -> ST B) (e2 : exn -> ST B).\n\nDefinition try_pre : pre :=\n  fun i =>\n    exists (Vi : valid i) (Pi : i \\In pre_of e),\n      (forall y  m, prog_of e _ Vi Pi (Val y)  m -> pre_of (e1 y)  m) /\\\n       forall ex m, prog_of e _ Vi Pi (Exn ex) m -> pre_of (e2 ex) m.\n\nDefinition try_pre_proj i : i \\In try_pre -> i \\In pre_of e :=\n  fun '(ex_intro _ (ex_intro p _)) => p.\n\nDefinition try_prog : prog try_pre B :=\n  fun i V P y m =>\n    exists x h (Ph : h \\In prog_of e i V (try_pre_proj P) x),\n      match x with\n      | Val x' => exists (Ph' : h \\In pre_of (e1 x')),\n                    m \\In prog_of (e1 x') _ (dstr_valid Ph) Ph' y\n      | Exn ex => exists (Ph' : h \\In pre_of (e2 ex)),\n                    m \\In prog_of (e2 ex) _ (dstr_valid Ph) Ph' y\n      end.\n\nLemma try_sfmono : safe_mono try_pre.\nProof.\nmove=>i j [Vi [Pi][E1 E2]] Vij.\nhave Pij := sfm_st Pi Vij.\nexists Vij, Pij; split.\n- move=>y m.\n  case/(fr_st Pi Vij Pij)=>h [{m}-> Vhj].\n  rewrite (pf_irr (validL Vij) Vi)=>/E1 Ph.\n  by apply: sfm_st=>//; apply: (validL Vhj).\nmove=>ex m.\ncase/(fr_st Pi Vij Pij)=>h [{m}-> Vhj].\nrewrite (pf_irr (validL Vij) Vi)=>/E2 Ph.\nby apply: sfm_st=>//; apply: (validL Vhj).\nQed.\n\nLemma try_dstrict : def_strict try_prog.\nProof.\nmove=>i [Vi [Pi][E1 E2]] Vi' y[x][h][/=].\nby case: x=>[x|ex] Eh; case=>Ph /dstr_st.\nQed.\n\nLemma try_frame : frameable try_prog.\nProof.\nmove=>i j [Vi [Pi][E1 E2]] Vij [_ [Pij _]] y m [x][h][/=].\nmove: (fr_st Pi Vij Pij)=>H.\ncase: x=>[x|ex] Ph.\n- case=>Ph'.\n  case: (H _ _ Ph)=>h1[Eh V1 Ph1]; subst h.\n  rewrite (pf_irr (validL Vij) Vi) in Ph1 *; move: (E1 _ _  Ph1)=>P21.\n  rewrite (pf_irr (dstr_valid Ph) V1).\n  case/(fr_st P21 V1 Ph')=>h2[Em Vm Ph2].\n  exists h2; split=>//; exists (Val x), h1, Ph1, P21.\n  by rewrite (pf_irr (dstr_valid Ph1) (validL V1)).\ncase=>Ph'.\ncase: (H _ _ Ph)=>h1[Eh V1 Ph1]; subst h.\nrewrite (pf_irr (validL Vij) Vi) in Ph1 *; move: (E2 _ _  Ph1)=> P21.\nrewrite (pf_irr (dstr_valid Ph) V1).\ncase/(fr_st P21 V1 Ph')=>h2[Em Vm Ph2].\nexists h2; split=>//; exists (Exn ex), h1, Ph1, P21.\nby rewrite (pf_irr (dstr_valid Ph1) (validL V1)).\nQed.\n\nDefinition try := Prog try_sfmono try_dstrict try_frame.\n\nLemma vrf_try i (Q : post B) :\n        vrf i e (fun x m =>\n                   match x with\n                   | Val x' => vrf m (e1 x') Q\n                   | Exn ex => vrf m (e2 ex) Q\n                   end) ->\n        vrf i try Q.\nProof.\nmove=>H Vi; case: (H Vi)=>pf {}H /=.\nhave J : i \\In try_pre.\n- by exists Vi, pf; split=>x m Pm; case: (H _ _ Pm (dstr_valid Pm)).\nexists J=>y j /= [x][m][Pm]F.\nrewrite (pf_irr pf (try_pre_proj J)) in H.\ncase: x Pm F=>[x|ex] Pm [Hm Hj];\ncase: (H _ _ Pm (dstr_valid Pm))=>pf''; apply;\nby rewrite (pf_irr pf'' Hm).\nQed.\n\nEnd Try.\n\n(* don't export, just for fun *)\nLemma bnd_is_try A B (e1 : ST A) (e2 : A -> ST B) i r :\n        vrf i (try e1 e2 (throw B)) r ->\n        vrf i (bind e1 e2) r.\nProof.\nmove=>H Vi; case: (H Vi)=>[[Vi'][P1 /= [E1 E2]]] {}H.\nhave J : i \\In pre_of (bind e1 e2).\n- exists Vi, P1=>y m.\n  by rewrite (pf_irr Vi Vi')=>/E1.\nexists J=>y m /= [x][h][Ph]C.\napply: H; exists x, h=>/=.\nrewrite (pf_irr P1 (bind_pre_proj J)) in E2 *; exists Ph.\nmove: Ph C; case: x=>// e Ph [{y}-> {m}->].\nrewrite (pf_irr Vi' Vi) in E2.\nby exists (E2 _ _ Ph).\nQed.\n\nSection Read.\nVariable (A : Type) (x : ptr).\n\nLocal Notation idyn v := (@dyn _ id _ v).\n\nDefinition read_pre : pre :=\n  fun i => x \\in dom i /\\ exists v : A, find x i = Some (idyn v).\n\nDefinition read_prog : prog read_pre A :=\n  fun i _ _ y m =>\n    exists w, [/\\ m = i, y = Val w & find x m = Some (idyn w)].\n\nLemma read_sfmono : safe_mono read_pre.\nProof.\nmove=>i j [Hx [v E]] Vij; split.\n- by rewrite domUn inE Vij Hx.\nby exists v; rewrite findUnL // Hx.\nQed.\n\nLemma read_dstrict : def_strict read_prog.\nProof. by move=>i _ Vi _ [_ [E _ _]]; rewrite -E in Vi. Qed.\n\nLemma read_frame : frameable read_prog.\nProof.\nmove=>i j [Hx [v E]] Vij _ _ _ [w [-> -> H]].\nexists i; split=>//; exists w; split=>{v E}//.\nby rewrite findUnL // Hx in H.\nQed.\n\nDefinition read := Prog read_sfmono read_dstrict read_frame.\n\nLemma vrf_read j (v : A) (Q : post A) :\n       (valid (x :-> v \\+ j) -> Q (Val v) (x :-> v \\+ j)) ->\n       vrf (x :-> v \\+ j) read Q.\nProof.\nmove=>H Vi /=.\nhave J : x :-> v \\+ j \\In read_pre.\n- split; first by rewrite domPtUnE.\n  by exists v; rewrite findPtUn.\nexists J=>_ _ [w [->->]].\nrewrite findPtUn //; case=>/inj_pair2 {w}<-.\nby apply: H.\nQed.\n\nEnd Read.\n\nSection Write.\nVariable (A : Type) (x : ptr) (v : A).\n\nLocal Notation idyn v := (@dyn _ id _ v).\n\nDefinition write_pre : pre :=\n  fun i => x \\in dom i.\n\nDefinition write_prog : prog write_pre unit :=\n  fun i _ _ y m =>\n    [/\\ y = Val tt, m = upd x (idyn v) i & x \\in dom i].\n\nLemma write_sfmono : safe_mono write_pre.\nProof.\nmove=>i j; rewrite /write_pre -!toPredE /= => Hx Vij.\nby rewrite domUn inE Vij Hx.\nQed.\n\nLemma write_dstrict : def_strict write_prog.\nProof.\nmove=>i Hx _ _ [_ E _]; rewrite /write_pre -toPredE /= in Hx.\nsuff {E}: valid (upd x (idyn v) i) by rewrite -E.\nby rewrite validU (dom_cond Hx) (dom_valid Hx).\nQed.\n\nLemma write_frame : frameable write_prog.\nProof.\nmove=>i j Hx Vij _ _ _ [-> -> _].\nexists (upd x (idyn v) i); split=>//;\nrewrite /write_pre -toPredE /= in Hx.\n- by rewrite updUnL Hx.\nby rewrite validUUn.\nQed.\n\nDefinition write := Prog write_sfmono write_dstrict write_frame.\n\nLemma vrf_write B (u : B) j (Q : post unit) :\n        (valid (x :-> v \\+ j) -> Q (Val tt) (x :-> v \\+ j)) ->\n        vrf (x :-> u \\+ j) write Q.\nProof.\nmove=>H Vi /=.\nhave J : x :-> u \\+ j \\In write_pre.\n- by rewrite /write_pre -toPredE /= domPtUnE.\nexists J=>_ _ [->-> _].\nrewrite updPtUn; apply: H.\nby rewrite (@validPtUnE _ _ _ _ (idyn u)).\nQed.\n\nEnd Write.\n\nSection Allocation.\nVariables (A : Type) (v : A).\n\nLocal Notation idyn v := (@dyn _ id _ v).\n\nDefinition alloc_pre : pre := top.\n\nDefinition alloc_prog : prog alloc_pre ptr :=\n  fun i _ _ y m =>\n    exists l, [/\\ y = Val l, m = l :-> v \\+ i,\n                  l != null & l \\notin dom i].\n\nLemma alloc_sfmono : safe_mono alloc_pre.\nProof. by []. Qed.\n\nLemma alloc_dstrict : def_strict alloc_prog.\nProof.\nmove=>i [] Vi _ [l][_ E Hl Hl2].\nsuff {E}: valid (l :-> v \\+ i) by rewrite -E.\nby rewrite validPtUn; apply/and3P.\nQed.\n\nLemma alloc_frame : frameable alloc_prog.\nProof.\nmove=>i j [] Vij [] _ _ [l][->-> Hl Hl2].\nexists (l :-> v \\+ i); rewrite -joinA; split=>//.\n- rewrite validUnAE validPt domPtK Hl Vij /= all_predC.\n  apply/hasP=>[[y Hy]]; rewrite !inE=>/eqP E.\n  by move: Hy Hl2; rewrite E=>->.\nexists l; split=>//.\nby apply/dom_NNL/Hl2.\nQed.\n\nDefinition alloc := Prog alloc_sfmono alloc_dstrict alloc_frame.\n\nLemma vrf_alloc i (Q : post ptr) :\n        (forall x, valid (x :-> v \\+ i) -> Q (Val x) (x :-> v \\+ i)) ->\n        vrf i alloc Q.\nProof.\nmove=>H Vi /=.\nexists I=>_ _ [x][-> -> Hx Hx2].\nby apply: H; rewrite validPtUn Hx Vi.\nQed.\n\nEnd Allocation.\n\nSection BlockAllocation.\nVariables (A : Type) (v : A) (n : nat).\n\nDefinition allocb_pre : pre := top.\n\nDefinition allocb_prog : prog allocb_pre ptr :=\n  fun i _ _ y m =>\n    exists l, [/\\ y = Val l, m = updi l (nseq n v) \\+ i & valid m].\n\nLemma allocb_sfmono : safe_mono allocb_pre.\nProof. by []. Qed.\n\nLemma allocb_dstrict : def_strict allocb_prog.\nProof. by move=>i [] Vi y [l][]. Qed.\n\nLemma allocb_frame : frameable allocb_prog.\nProof.\nmove=>i j [] Vij [] _ _ [l][->-> V].\nexists (updi l (nseq n v) \\+ i); rewrite -joinA; split=>//.\nexists l; split=>//.\nby rewrite joinA in V; apply: (validL V).\nQed.\n\nDefinition allocb := Prog allocb_sfmono allocb_dstrict allocb_frame.\n\nLemma vrf_allocb i (Q : post ptr) :\n        (forall x, valid (updi x (nseq n v) \\+ i) ->\n           Q (Val x) (updi x (nseq n v) \\+ i)) ->\n        vrf i allocb Q.\nProof.\nmove=>H Vi /=.\nexists I=>_ _ [l][->-> V].\nby apply: H.\nQed.\n\nEnd BlockAllocation.\n\nSection Deallocation.\nVariable x : ptr.\n\nDefinition dealloc_pre : pre :=\n  fun i => x \\in dom i.\n\nDefinition dealloc_prog : prog dealloc_pre unit :=\n  fun i _ _ y m =>\n    [/\\ y = Val tt, m = free i x & x \\in dom i].\n\nLemma dealloc_sfmono : safe_mono dealloc_pre.\nProof.\nmove=>i j; rewrite /dealloc_pre -!toPredE /= => Hx Vij.\nby rewrite domUn inE Vij Hx.\nQed.\n\nLemma dealloc_dstrict : def_strict dealloc_prog.\nProof.\nmove=>i _ Vi _ [_ E _].\nsuff {E}: valid (free i x) by rewrite -E.\nby rewrite validF.\nQed.\n\nLemma dealloc_frame : frameable dealloc_prog.\nProof.\nmove=>i j Hx Vij Hx' _ _ [->-> _].\nexists (free i x); split=>//;\nrewrite /dealloc_pre -!toPredE /= in Hx Hx'.\n- by apply/freeUnR/dom_inNL/Hx.\nby apply: validFUn.\nQed.\n\nDefinition dealloc :=\n  Prog dealloc_sfmono dealloc_dstrict dealloc_frame.\n\nLemma vrf_dealloc A (v : A) j (Q : post unit) :\n        (x \\notin dom j -> valid j -> Q (Val tt) j) ->\n        vrf (x :-> v \\+ j) dealloc Q.\nProof.\nmove=>H Vi /=.\nhave J: x :-> v \\+ j \\In dealloc_pre.\n- by rewrite /dealloc_pre -toPredE /= domPtUnE.\nexists J=>_ _ [->-> Hx].\nrewrite freePtUn //; apply: H; last by exact: (validR Vi).\nby move: Hx; rewrite domPtUnE validPtUn; case/and3P.\nQed.\n\nEnd Deallocation.\n\n(* Monotonicity of the constructors *)\n\nSection Monotonicity.\n\nVariables (A B : Type).\n\nLemma do_mono G (e1 e2 : ST A) (s : spec G A)\n        (pf1 : has_spec s e1) (pf2 : has_spec s e2) :\n        e1 <== e2 -> @STprog _ _ _ e1 pf1 <== @STprog _ _ _ e2 pf2.\nProof. by []. Qed.\n\nLemma bind_mono (e1 e2 : ST A) (k1 k2 : A -> ST B) :\n        e1 <== e2 -> k1 <== k2 -> (bind e1 k1 : ST B) <== bind e2 k2.\nProof.\nmove=>[H1 H2] pf2.\nhave pf: bind_pre e2 k2 <== bind_pre e1 k1.\n- move=>h [Vh][Pi] H.\n  exists Vh, (H1 _ Pi)=>x m /H2/H H'.\n  by case: (pf2 x)=>+ _; apply.\nexists pf=>i Vi /[dup][[Vi'][Pi']P'] Pi x h.\ncase; case=>[a|e][h0][Ph][Ph'] H.\n- exists (Val a), h0.\n  move: (H2 i Vi (bind_pre_proj Pi))=>H'.\n  rewrite (pf_irr (H1 i (bind_pre_proj Pi)) (bind_pre_proj (pf i Pi))) in H'.\n  have Ph0 := (H' _ _ Ph); exists Ph0.\n  move: (P' a h0); rewrite (pf_irr Vi' Vi) (pf_irr Pi' (bind_pre_proj Pi))=>H''.\n  exists (H'' Ph0); case: (pf2 a)=>Pr; apply.\n  by rewrite (pf_irr (dstr_valid Ph0) (dstr_valid Ph)) (pf_irr (Pr h0 (H'' Ph0)) Ph').\nrewrite Ph' H; exists (Exn e), h0.\nmove: (H2 i Vi (bind_pre_proj Pi))=>H'.\nrewrite (pf_irr (H1 i (bind_pre_proj Pi)) (bind_pre_proj (pf i Pi))) in H'.\nby exists (H' _ _ Ph).\nQed.\n\nLemma try_mono (e1 e2 : ST A) (k1 k2 : A -> ST B) (h1 h2 : exn -> ST B) :\n        e1 <== e2 -> k1 <== k2 -> h1 <== h2 ->\n        (try e1 k1 h1 : ST B) <== try e2 k2 h2.\nProof.\nmove=>[H1 H2] pf2 pf3.\nhave pf: try_pre e2 k2 h2 <== try_pre e1 k1 h1.\n- move=>h [Vh][Pi] [Hk Hn].\n  exists Vh, (H1 _ Pi); split.\n  - move=>x m /H2/Hk H'.\n    by case: (pf2 x)=>+ _; apply.\n  move=>ex m /H2/Hn H'.\n  by case: (pf3 ex)=>+ _; apply.\nexists pf =>i Vi /[dup][[Vi'][Pi'][Pk0 Ph0]] Pi x h.\ncase; case=>[a|e][h0][Ph][Ph'] H.\n- exists (Val a), h0.\n  move: (H2 i Vi (try_pre_proj Pi))=>H'.\n  rewrite (pf_irr (H1 i (try_pre_proj Pi)) (try_pre_proj (pf i Pi))) in H'.\n  have Ph1 := (H' _ _ Ph); exists Ph1.\n  move: (Pk0 a h0); rewrite (pf_irr Vi' Vi) (pf_irr Pi' (try_pre_proj Pi))=>H''.\n  exists (H'' Ph1); case: (pf2 a)=>Pr; apply.\n  by rewrite (pf_irr (dstr_valid Ph1) (dstr_valid Ph)) (pf_irr (Pr h0 (H'' Ph1)) Ph').\nexists (Exn e), h0.\nmove: (H2 i Vi (try_pre_proj Pi))=>H'.\nrewrite (pf_irr (H1 i (try_pre_proj Pi)) (try_pre_proj (pf i Pi))) in H'.\nhave Ph1 := (H' _ _ Ph); exists Ph1.\nmove: (Ph0 e h0); rewrite (pf_irr Vi' Vi) (pf_irr Pi' (try_pre_proj Pi))=>H''.\nexists (H'' Ph1); case: (pf3 e)=>Pr; apply.\nby rewrite (pf_irr (dstr_valid Ph1) (dstr_valid Ph)) (pf_irr (Pr h0 (H'' Ph1)) Ph').\nQed.\n\n(* the rest of the  constructors are trivial *)\nLemma ret_mono (v1 v2 : A) :\n        v1 = v2 -> (ret v1 : ST A) <== ret v2.\nProof. by move=>->. Qed.\n\nLemma throw_mono (e1 e2 : exn) :\n        e1 = e2 -> (throw A e1 : ST A) <== throw A e2.\nProof. by move=>->. Qed.\n\nLemma read_mono (p1 p2 : ptr) :\n        p1 = p2 -> (read A p1 : ST A) <== read A p2.\nProof. by move=>->. Qed.\n\nLemma write_mono (p1 p2 : ptr) (x1 x2 : A) :\n        p1 = p2 -> x1 = x2 -> (write p1 x1 : ST unit) <== write p2 x2.\nProof. by move=>->->. Qed.\n\nLemma alloc_mono (x1 x2 : A) :\n        x1 = x2 -> (alloc x1 : ST ptr) <== alloc x2.\nProof. by move=>->. Qed.\n\nLemma allocb_mono (x1 x2 : A) (n1 n2 : nat) :\n        x1 = x2 -> n1 = n2 -> (allocb x1 n1 : ST ptr) <== allocb x2 n2.\nProof. by move=>->->. Qed.\n\nLemma dealloc_mono (p1 p2 : ptr) :\n        p1 = p2 -> (dealloc p1 : ST unit) <== dealloc p2.\nProof. by move=>->. Qed.\n\nVariables (G : Type) (C : A -> Type) (s : forall x, spec G (C x)).\nNotation lat := (dfunLattice (fun x => [lattice of STspec (s x)])).\n\nLemma fix_mono (f1 f2 : lat -> lat) : f1 <== f2 -> (Fix f1 : lat) <== Fix f2.\nProof.\nmove=>Hf; apply: tarski_lfp_mono.\n- move=>x1 x2 Hx; apply: supM=>z [x][H ->]; apply: supP; exists x.\n  by split=>//; apply: poset_trans H Hx.\nmove=>y; apply: supM=>_ [x][H1 ->].\nby apply: poset_trans (Hf x) _; apply: supP; exists x.\nQed.\n\nEnd Monotonicity.\n\nEnd Vrf.\n\nExport Vrf.\n\nDefinition skip := ret tt.\n\nCorollary vrf_mono A (e : ST A) i : monotone (vrf' e i).\nProof. by move=>/= Q1 Q2 H; apply: vrf_post=>y m _; apply: H. Qed.\n\n\n(******************************************)\n(* Notation for logical variable postexts *)\n(******************************************)\n\nDefinition logbase A (p : pre) (q : post A) : spec unit A :=\n  fun => (p, q).\n\nDefinition logvar {B A} (G : A -> Type) (s : forall x : A, spec (G x) B) :\n             spec {x : A & G x} B :=\n  fun '(existT x g) => s x g.\n\nNotation \"'STsep' ( p , q ) \" := (STspec unit (logbase p q)) (at level 0).\n\nNotation \"{ x .. y }, 'STsep' ( p , q ) \" :=\n  (STspec _ (logvar (fun x => .. (logvar (fun y => logbase p q)) .. )))\n   (at level 0, x binder, y binder, right associativity).\n\n(************************************************************)\n(* Lemmas for pulling out and instantiating ghost variables *)\n(************************************************************)\n\n(* Lemmas without framing, i.e. they pass the entire heap to the *)\n(* routine being invoked.                                        *)\n\nLemma gE G A (s : spec G A) g i (e : STspec G s) (Q : post A) :\n        (s g).1 i ->\n        (forall v m, (s g).2 (Val v) m ->\n           valid m -> Q (Val v) m) ->\n        (forall x m, (s g).2 (Exn x) m ->\n           valid m -> Q (Exn x) m) ->\n        vrf i e Q.\nProof.\ncase: e=>e /= /[apply] Hp Hv He; apply: vrfV=>V /=.\nby apply/vrf_post/Hp; case=>[v|ex] m Vm H; [apply: Hv | apply: He].\nQed.\n\nArguments gE [G A s] g [i e Q] _ _.\n\nNotation \"[gE]\" := (gE tt) (at level 0).\n\nNotation \"[ 'gE' x1 , .. , xn ]\" :=\n  (gE (existT _ x1 .. (existT _ xn tt) ..))\n  (at level 0, format \"[ 'gE'  x1 ,  .. ,  xn ]\").\n\n(* a combination of gE + vrf_bind, for \"stepping over\" the call *)\nLemma stepE G A B (s : spec G A) g i (e : STspec G s) (e2 : A -> ST B) (Q : post B) :\n        (s g).1 i ->\n        (forall x m, (s g).2 (Val x) m -> vrf m (e2 x) Q) ->\n        (forall x m, (s g).2 (Exn x) m ->\n           valid m -> Q (Exn x) m) ->\n        vrf i (bind e e2) Q.\nProof.\nmove=>Hp Hv He.\nby apply/vrf_bind/(gE _ Hp)=>[v m P|x m P _] V; [apply: Hv | apply: He].\nQed.\n\nArguments stepE [G A B s] g [i e e2 Q] _ _.\n\nNotation \"[stepE]\" := (stepE tt) (at level 0).\n\nNotation \"[ 'stepE' x1 , .. , xn ]\" :=\n  (stepE (existT _ x1 .. (existT _ xn tt) ..))\n  (at level 0, format \"[ 'stepE'  x1 ,  .. ,  xn ]\").\n\n(* a combination of gE + vrf_try *)\nLemma tryE G A B (s : spec G A) g i (e : STspec G s) (e1 : A -> ST B) (e2 : exn -> ST B) (Q : post B) :\n        (s g).1 i ->\n        (forall x m, (s g).2 (Val x) m -> vrf m (e1 x) Q) ->\n        (forall x m, (s g).2 (Exn x) m -> vrf m (e2 x) Q) ->\n        vrf i (try e e1 e2) Q.\nProof.\nmove=>Hp Hv Hx.\nby apply/vrf_try/(gE _ Hp)=>[x|ex] m Vm P; [apply: Hv | apply: Hx].\nQed.\n\nArguments tryE [G A B s] g [i e e1 e2 Q] _ _.\n\nNotation \"[tryE]\" := (tryE tt) (at level 0).\n\nNotation \"[ 'tryE' x1 , .. , xn ]\" :=\n  (tryE (existT _ x1 .. (existT _ xn tt) ..))\n  (at level 0, format \"[ 'tryE'  x1 ,  .. ,  xn ]\").\n\n(* Common special case for framing on `Unit`, i.e. passing an *)\n(* empty heap to the routine. For more sophisticated framing  *)\n(* variants see the `heapauto` module.                        *)\n\nLemma gU G A (s : spec G A) g i (e : STspec G s) (Q : post A) :\n        (s g).1 Unit ->\n        (forall v m, (s g).2 (Val v) m ->\n           valid (m \\+ i) -> Q (Val v) (m \\+ i)) ->\n        (forall x m, (s g).2 (Exn x) m ->\n           valid (m \\+ i) -> Q (Exn x) (m \\+ i)) ->\n        vrf i e Q.\nProof.\ncase: e=>e /= /[apply] Hp Hv Hx; rewrite -(unitL i).\napply/vrf_frame/vrf_post/Hp.\nby case=>[x|ex] n _ =>[/Hv|/Hx].\nQed.\n\nNotation \"[gU]\" := (gU tt) (at level 0).\n\nNotation \"[ 'gU' x1 , .. , xn ]\" :=\n  (gU (existT _ x1 .. (existT _ xn tt) ..))\n  (at level 0, format \"[ 'gU'  x1 ,  .. ,  xn ]\").\n\n(* a combination of gU + vrf_bind *)\nLemma stepU G A B (s : spec G A) g i (e : STspec G s) (e2 : A -> ST B)\n             (Q : post B) :\n        (s g).1 Unit ->\n        (forall x m, (s g).2 (Val x) m -> vrf (m \\+ i) (e2 x) Q) ->\n        (forall x m, (s g).2 (Exn x) m ->\n           valid (m \\+ i) -> Q (Exn x) (m \\+ i)) ->\n        vrf i (bind e e2) Q.\nProof.\nmove=>Hp Hv Hx.\napply/vrf_bind/(gU _ Hp)=>[x m H V|ex m H V _].\n- by apply: Hv H.\nby apply: Hx.\nQed.\n\nArguments stepU [G A B s] g i [e e2 Q] _ _ _.\n\nNotation \"[stepU]\" := (stepU tt) (at level 0).\n\nNotation \"[ 'stepU' x1 , .. , xn ]\" :=\n  (stepU (existT _ x1 .. (existT _ xn tt) ..))\n  (at level 0, format \"[ 'stepU'  x1 ,  .. ,  xn ]\").\n\n(* a combination of gU + vrf_try *)\nLemma tryU G A B (s : spec G A) g i (e : STspec G s)\n             (e1 : A -> ST B) (e2 : exn -> ST B) (Q : post B) :\n        (s g).1 Unit ->\n        (forall x m, (s g).2 (Val x) m -> vrf (m \\+ i) (e1 x) Q) ->\n        (forall x m, (s g).2 (Exn x) m -> vrf (m \\+ i) (e2 x) Q) ->\n        vrf i (try e e1 e2) Q.\nProof.\nmove=>Hi H1 H2.\napply/vrf_try/(gU _ Hi)=>[x|ex] m H V.\n- by apply: H1 H.\nby apply: H2.\nQed.\n\nArguments tryU [G A B s] g i [e e1 e2 Q] _ _ _.\n\nNotation \"[tryU]\" := (tryU tt) (at level 0).\n\nNotation \"[ 'tryU' x1 , .. , xn ]\" :=\n  (tryU (existT _ x1 .. (existT _ xn tt) ..))\n  (at level 0, format \"[ 'tryU'  x1 ,  .. ,  xn ]\").\n\n(* some notation for writing posts that signify no exceptions are raised *)\n\nDefinition vfun' A (f : A -> heap -> Prop) : post A :=\n  fun y i => if y is Val v then f v i else False.\n\nNotation \"[ 'vfun' x => p ]\" := (vfun' (fun x => p))\n  (at level 0, x name, format \"[ 'vfun'  x  =>  p ]\") : fun_scope.\n\nNotation \"[ 'vfun' x : aT => p ]\" := (vfun' (fun (x : aT) => p))\n  (at level 0, x name, only parsing) : fun_scope.\n\nNotation \"[ 'vfun' x i => p ]\" := (vfun' (fun x i => p))\n  (at level 0, x name, format \"[ 'vfun'  x  i  =>  p ]\") : fun_scope.\n\nNotation \"[ 'vfun' ( x : aT ) i => p ]\" := (vfun' (fun (x : aT) i => p))\n  (at level 0, x name, only parsing) : fun_scope.\n", "meta": {"author": "imdea-software", "repo": "htt", "sha": "cb1fb44953ba32dec2880662e5e2da47f3f74245", "save_path": "github-repos/coq/imdea-software-htt", "path": "github-repos/coq/imdea-software-htt/htt-cb1fb44953ba32dec2880662e5e2da47f3f74245/htt/model.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.29099592699141574}}
{"text": "Require Import RGref.DSL.DSL.\nRequire Import RGref.DSL.Concurrency.\n\n(** * Trieber Stack\n    A lock-free stack implementation. *)\n(** ** Basic heap structure, and rely/guarantee interactions *)\n(** Luckily, we can escape the induction-induction encoding since\n    nodes are constant. *)\nInductive Node : Set :=\n  | mkNode : nat -> option (ref{Node|any}[local_imm,local_imm]) -> Node.\nGlobal Instance reach_ts_node : ImmediateReachability Node :=\n{ imm_reachable_from_in := fun T P R G r nd =>\n                             match nd with (mkNode n tl) =>\n                                             imm_reachable_from_in r tl\n                             end }.\nGlobal Instance node_contains : Containment Node :=\n{ contains := fun R => True }. (* the recursive refs are heap-agnostic (immutable) *)\n(* Nodes grant no heap mutation capabilities ever, so every fold is safe. *)\nGlobal Instance node_fold R G : readable_at Node R G :=\n  { res := Node ;\n    dofold := fun x => x\n  }.\nRequire Import RGref.DSL.Fields.\nInductive nd_fields : Set := val | nxt.\nInstance node_field_type : FieldTyping Node nd_fields.\nInstance nxt_type : FieldType Node nd_fields nxt (option (ref{Node|any}[local_imm,local_imm])) :=\n{ getF := fun x => match x with (mkNode v tl) => tl end;\n  setF := fun x val => match x with (mkNode v tl) => mkNode v val end\n}.\nInstance val_type : FieldType Node nd_fields val nat :=\n{ getF := fun x => match x with (mkNode v tl) => v end;\n  setF := fun x val => match x with mkNode v tl => mkNode val tl end\n}.\n\n(** We'll follow roughly S11.2 of The Art of Multiprocessor Programming:\n    a basic Trieber stack, with no backoff or elimination. *)\nInductive deltaTS : hrel (option (ref{Node|any}[local_imm,local_imm])) :=\n  | ts_nop : forall n h h', deltaTS n n h h'\n  | ts_push : forall n hd hd' h h', h'[hd']=(mkNode n hd) ->\n                                    deltaTS hd (Some hd') h h'\n  | ts_pop : forall n hd hd' h h', h[hd]=(mkNode n hd') ->\n                                   deltaTS (Some hd) hd' h h'.\n(** ** Meta properties of TS-specific rely/guarantee relations *)\nLemma precise_deltaTS : precise_rel deltaTS.\nProof.\n  red. intros. induction H1.\n  constructor.\n  eapply ts_push. rewrite <- H0; eauto. constructor. red. unfold reach_option. constructor.\n      red. red. reflexivity.\n  eapply ts_pop. rewrite <- H; eauto. constructor. constructor. red. red. reflexivity.\nQed.\nHint Resolve precise_deltaTS.\nLemma hrefl_deltaTS : hreflexive deltaTS.\nProof.\n  compute. constructor.\nQed.\nHint Resolve hrefl_deltaTS.\n\n                                                       \nDefinition ts := ref{option (ref{Node|any}[local_imm,local_imm])|any}[deltaTS,deltaTS].\n\n(** ** Standard operations *)\n(** *** Allocating a new stack *)\nProgram Definition alloc_ts {Γ} (u:unit) : rgref Γ ts Γ :=\n  Alloc None.\n\n(*Local Obligation Tactic := compute; eauto.*)\n(** *** Push operation *)\nProgram Definition push_ts {Γ} : ts -> nat -> rgref Γ unit Γ :=\n  RGFix2 _ _ _ (fun rec s n =>\n    tl <- !s;\n    (* Eventually, lift allocation out of the loop, do substructural\n       allocation, and strongly update tail until insertion *)\n    (* For some reason the AllocNE notation isn't parsing here... *)\n    new_node_pf <- (allocne _ _ _ (mkNode n tl) _ _ _ _ _ _ s);\n    (*new_node_pf <- (AllocNE (mkNode n tl) s);*)\n    let (new_node, nn_ne_s) := new_node_pf in        \n    success <- CAS(s,tl,Some (convert new_node (fun v h (pf:v=mkNode n tl) => I)\n                                               (rel_sub_refl _ local_imm)\n                                               (rel_sub_refl _ local_imm) _ \n                                               (rel_sub_refl _ local_imm) _ _ _));\n    if success then rgret tt else rec s n).\nNext Obligation.\n  f_equal. intros. rewrite H. reflexivity.\n  eapply (rgref_exchange); try solve[compute; eauto].\n  split; red; intros. red in H. destruct H. eauto.\n  split; eauto. intros. constructor.\n  Defined.\nNext Obligation. (* local identity constraint stable wrt local_imm *)\n  compute. intros. subst. rewrite <- H0. reflexivity. Qed.\nNext Obligation.\n  compute; eauto. Qed.\nNext Obligation. (* Guarantee satisfaction! *)\n  eapply ts_push.  rewrite <- convert_equiv.\n  Check @heap_lookup2.\n  assert (tmp := @heap_lookup2 _ (fun v _ => v=mkNode n ((h[s]))) local_imm local_imm h new_node).\n  simpl in tmp.\n  rewrite <- tmp. unfold ts in s.\n  (* We know new_node and s are not equal, since we allocated new_node with AllocNE while s existed *)\n  apply non_ptr_eq_based_nonaliasing. assumption.\nQed.\n\n(** *** Pop operation *)\n\nRequire Import Utf8.\nLocal Obligation Tactic := intros; compute; try subst; intuition; eauto with typeclass_instances.\nProgram Definition pop_ts {Γ} : ts -> rgref Γ (option nat) Γ :=\n  RGFix _ _ (fun rec s =>\n    head <- !s;\n    match head with\n    | None => rgret None\n    | Some hd => \n                 observe-field hd --> val as n, pf in (fun a h => @eq nat (getF a) n);\n                 (* making the @eq type explicit causes 5 more goals to be auto solved! *)\n                 observe-field hd --> nxt as tl', pf' in (fun a h => @eq (option _) (getF a) tl');\n                 success <- CAS(s,Some hd,tl');\n                 if success then rgret (Some n) else rec s\n    end).\nNext Obligation. (* options equivalent... *)\n  f_equal. intros. rewrite H. reflexivity.\n  eapply (rgref_exchange); try solve[compute; eauto].\n  split; red; intros. simpl in H. destruct H. eauto.\n  split; eauto. intros. constructor.\nDefined.\nNext Obligation. (* refining hd stability *)\n  intros. subst. auto.\nDefined.\nNext Obligation. (* refining hd stability *)\n  intros. subst. auto.\nDefined.\nNext Obligation. (** Guarantee Satisfaction *)\n  eapply ts_pop. \n  assert (field_inj : forall nd, nd = mkNode (getF nd) (getF nd)).\n      intros. destruct nd. reflexivity.\n  rewrite (field_inj (h[hd])). rewrite pf. rewrite pf'. reflexivity.\nQed.\n\n \n", "meta": {"author": "csgordon", "repo": "rgref-concurrent", "sha": "06091e1eb67c90682be7686020fb3a30233f21ec", "save_path": "github-repos/coq/csgordon-rgref-concurrent", "path": "github-repos/coq/csgordon-rgref-concurrent/rgref-concurrent-06091e1eb67c90682be7686020fb3a30233f21ec/TrieberStack.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2909959159800836}}
{"text": "Require Import ModelProperties. \nRequire Import AuxiliaryLemmas. \n \nSection mkdirIsSecure. \n \nLemma MkdirPSS :\n forall (s t : SFSstate) (u : SUBJECT),\n FuncPre1 s ->\n FuncPre2 s ->\n FuncPre3 s -> SecureState s -> TransFunc u s Mkdir t -> SecureState t. \nintros s t Sub FP1 FP2 FP3 SS TF; inversion TF. \ninversion H. \nBreakSS. \nunfold SecureState in |- *. \nsplit. \nunfold DACSecureState in |- *; simpl in |- *. \nintros. \ncut\n (match fsecmat (secmat s) o with\n  | Some y => set_In u0 (ActReaders y) -> PreDACRead s u0 o\n  | None => True\n  end /\\\n  match fsecmat (secmat s) o with\n  | Some y => set_In u0 (ActWriters y) -> PreDACWrite s u0 o\n  | None => True\n  end). \nelim (fsecmat (secmat s) o). \nunfold PreDACRead, PreDACWrite, mkdir_acl in |- *; simpl in |- *. \nelim (fsecmat (secmat s) (MyDir p)); elim (fSSC (subjectSC s) Sub). \nelim (OBJNAMEeq_dec p (ObjName o)). \nintro y. \nrewrite y. \nreplace (facl (acl s) o) with (None (A:=AccessCtrlListData)). \nintros. \nelim H8; intros. \nsplit; intro. \ntauto. \n \ntauto. \n \nrewrite y in H4. \nrewrite y in H2. \nsymmetry  in |- *. \nunfold facl in |- *. \napply NotInDOMIsUndef. \neauto. \n \nintro y. \nreplace\n (facl\n    (set_add ACLeq_dec\n       (NEWDIR p,\n       acldata Sub (primaryGrp s Sub)\n         (ChangeUserR Sub (empty_set SUBJECT) (ownerp perms))\n         (ChangeGroupR (AllGrp s) (groupp perms)\n            (ChangeGroupR (primaryGrp s Sub) (groupp perms)\n               (empty_set GRPNAME)))\n         (ChangeUserW Sub (empty_set SUBJECT) (ownerp perms))\n         (ChangeGroupW (AllGrp s) (groupp perms)\n            (ChangeGroupW (primaryGrp s Sub) (groupp perms)\n               (empty_set GRPNAME))) (Sub :: nil) (RootGrp s :: nil)) \n       (acl s)) o) with (facl (acl s) o). \nauto. \n \nunfold facl in |- *; apply AddEq. \nunfold NEWDIR in |- *. \nintro. \napply y. \nrewrite H8. \nsimpl in |- *. \nauto. \n \nauto. \n \nauto. \n \nauto. \n \ntauto. \n \nunfold DACSecureState in DAC. \nsplit. \napply ReadWriteImpRead; auto. \n \napply ReadWriteImpWrite; auto. \n \nunfold MACSecureState in |- *; simpl in |- *; intros. \nelim (OBJNAMEeq_dec p (ObjName o)). \nintro y. \nrewrite y. \nreplace (fsecmat (secmat s) o) with (None (A:=ReadersWriters)). \nreplace (fOSC (objectSC s) o) with (None (A:=SecClass)). \nelim (fSSC (subjectSC s) u0); elim (fOSC (mkdir_oSC s Sub (ObjName o)) o);\n contradiction || auto. \n \nsymmetry  in |- *. \nunfold fOSC in |- *; apply NotInDOMIsUndef. \nreplace (DOM OBJeq_dec (objectSC s)) with (DOM OBJeq_dec (acl s)). \nrewrite y in H4; rewrite y in H2; eauto. \n \nsymmetry  in |- *; unfold fsecmat in |- *; apply NotInDOMIsUndef. \ncut (~ set_In o (DOM OBJeq_dec (acl s))). \nunfold not in |- *. \nintros SI1 SI2; apply SI1. \nunfold FuncPre3 in FP3. \nunfold Included in FP3. \nauto. \n \nrewrite y in H4; rewrite y in H2; eauto. \n \nintro y. \nreplace (fOSC (mkdir_oSC s Sub p) o) with (fOSC (objectSC s) o). \nunfold MACSecureState in MAC; apply MAC. \n \nauto. \n \nQed. \n \n \nLemma MkdirPSP :\n forall (s t : SFSstate) (u : SUBJECT),\n FuncPre1 s ->\n FuncPre2 s ->\n FuncPre3 s -> StarProperty s -> TransFunc u s Mkdir t -> StarProperty t. \nintros s t Sub FP1 FP2 FP3 SP TF; inversion TF. \ninversion H. \nunfold StarProperty in |- *; simpl in |- *; intros u0 o1 o2. \nelim (OBJNAMEeq_dec p (ObjName o1)); elim (OBJNAMEeq_dec p (ObjName o2)). \nintros y y0. \nreplace (fsecmat (secmat s) o1) with (None (A:=ReadersWriters)). \nelim (fsecmat (secmat s) o2); elim (fOSC (mkdir_oSC s Sub p) o2);\n elim (fOSC (mkdir_oSC s Sub p) o1); trivial. \n \neauto. \n \nintros y y0. \nreplace (fsecmat (secmat s) o1) with (None (A:=ReadersWriters)). \nelim (fsecmat (secmat s) o2); elim (fOSC (mkdir_oSC s Sub p) o2);\n elim (fOSC (mkdir_oSC s Sub p) o1); trivial. \n \neauto. \n \nintros y y0. \nreplace (fsecmat (secmat s) o2) with (None (A:=ReadersWriters)). \nelim (fsecmat (secmat s) o1); elim (fOSC (mkdir_oSC s Sub p) o2);\n elim (fOSC (mkdir_oSC s Sub p) o1); trivial. \n \neauto. \n \nintros y y0. \nreplace (fOSC (mkdir_oSC s Sub p) o1) with (fOSC (objectSC s) o1). \nreplace (fOSC (mkdir_oSC s Sub p) o2) with (fOSC (objectSC s) o2). \nunfold StarProperty in SP; apply SP. \n \nauto. \n \nauto. \n \nQed. \n \n \nLemma MkdirPCP :\n forall s t : SFSstate,\n FuncPre1 s -> FuncPre2 s -> PreservesControlProp s Mkdir t. \nintros s t FP1 FP2; unfold PreservesControlProp in |- *; intros Sub TF;\n inversion TF; unfold ControlProperty in |- *. \ninversion H. \nsplit. \nintros. \nsplit. \nintro. \ninversion H8. \nsimpl in H10. \nelim (OBJNAMEeq_dec p (ObjName o)). \nintro. \ncut (facl (acl s) o = None). \nintro. \nrewrite H12 in H9. \ndiscriminate H9. \n \nunfold facl in |- *; apply NotInDOMIsUndef. \nrewrite a in H4; rewrite a in H2; eauto. \n \nintro. \ncut (y = z). \nintro. \ncut False. \ntauto. \n \nrewrite H12 in H11; inversion H11; auto. \n \ncut (facl (acl s) o = facl (mkdir_acl s Sub p perms) o). \nintro EQ; rewrite <- EQ in H10; rewrite H10 in H9; injection H9; auto. \n \nauto. \n \nsimpl in H10. \nelim (OBJNAMEeq_dec p (ObjName o)). \nintro. \ncut (facl (acl s) o = None). \nintro. \nrewrite H12 in H9. \ndiscriminate H9. \n \nunfold facl in |- *; apply NotInDOMIsUndef. \nrewrite a in H4; rewrite a in H2; eauto. \n \nintro. \ncut (y = z). \nintro. \ncut False. \ntauto. \n \nrewrite H12 in H11; inversion H11; auto. \n \ncut (facl (acl s) o = facl (mkdir_acl s Sub p perms) o). \nintro EQ; rewrite <- EQ in H10; rewrite H10 in H9; injection H9; auto. \n \nauto. \n \nintro. \ninversion H8. \nsimpl in H10. \nelim (OBJNAMEeq_dec p (ObjName o)). \nintro. \ncut (fOSC (objectSC s) o = None). \nintro. \nrewrite H12 in H9; discriminate H9. \n \nunfold fOSC in |- *; apply NotInDOMIsUndef. \n \nreplace (DOM OBJeq_dec (objectSC s)) with (DOM OBJeq_dec (acl s)). \nrewrite a in H4; rewrite a in H2; eauto. \n \nauto. \n \nintro. \ncut (x = y). \nintro. \ncut False. \ntauto. \n \nrewrite H12 in H11; inversion H11; auto. \n \ncut (fOSC (objectSC s) o = fOSC (mkdir_oSC s Sub p) o). \nintro EQ; rewrite <- EQ in H10; rewrite H10 in H9; injection H9; auto. \n \nauto. \n \nintros;\n absurd\n  (MACSubCtrlAttrHaveChanged s\n     (mkSFS (groups s) (primaryGrp s) (subjectSC s) \n        (AllGrp s) (RootGrp s) (SecAdmGrp s) (mkdir_oSC s Sub p)\n        (mkdir_acl s Sub p perms) (secmat s) (files s)\n        (mkdir_directories Sub p)) u0); auto. \n \nQed. \n \n \nEnd mkdirIsSecure. \n \nHint Resolve MkdirPSS MkdirPSP MkdirPCP. \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/mkdirIsSecure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.29080523645526885}}
{"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\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    + lia.\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    - lia.\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. lia.\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    { lia. }\n    i. des. esplits; cycle 1; eauto.\n    + etrans; eauto.\n    + lia.\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    { lia. }\n    i. des. esplits; cycle 1.\n    + econs 2; eauto.\n    + etrans; eauto.\n    + lia.\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    + lia.\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    - lia.\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. lia.\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    { lia. }\n    i. des. esplits; cycle 1; eauto.\n    + etrans; eauto.\n    + lia.\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    { lia. }\n    i. des. esplits; cycle 1.\n    + econs 2; eauto. econs; eauto. unguardH EVENT1. by destruct e2', e0; des.\n    + etrans; eauto.\n    + lia.\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 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": "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/prop/ReorderPromises.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.29080523645526885}}
{"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 preservation.\nRequire Import Label.\n\n\nTheorem Progress : forall config T ct h ctn ctns, \n  config = (Config ct ctn ctns h) ->\n  valid_config (Config ct ctn ctns h) ->\n  config_has_type ct empty_context (Config ct ctn ctns h) T\n  -> terminal_state config \\/ (exists config', config ==> config').\nProof with eauto.\n  intros config T ct h ctn ctns.\n  intro H_config.\n  intro H_valid_config. \n  intro H_typing. \n  remember (empty_context) as Gamma.\n  inversion H_typing; subst; auto.\n  inversion H2; subst; auto.\n\n  inversion H_valid_config; subst; auto.\n  inversion H0; subst; auto; try (apply value_progress with T; auto;fail);\n    try (exists Error_state, auto) .\n  (*Tvar*)\n  - inversion H1; subst; auto.\n    destruct H9 with x (classTy T3); auto.\n    destruct H10; subst; auto.\n    right.\n    exists (Config ct (Container x0 fs lb sf) ctns h); auto.\n\n\n  (*(EqCmp e1 e2)*)\n  - pose proof (excluded_middle_value e1).\n    destruct H11.\n    right.\n    + pose proof (excluded_middle_value e2).\n      destruct H12. \n      ++ pose proof (exclude_middle_val_eq e1 e2 H11 H12).\n         destruct H15.\n         +++ inversion H11; subst; inversion H; subst; auto.\n             ++++ destruct H26 as [F]. destruct H15 as [lo].\n                  case_eq (flow_to lo lb); intro.\n                  exists (Config ct (Container (B_true) fs lb sf) ctns h).\n                  apply ST_EqCmp_result; auto.\n                  intros. intuition.\n                  right; exists o; exists cls_def; exists F; exists lo;\n                    split; auto.\n                  right; exists o; exists cls_def; exists F; exists lo;\n                    split; auto.\n\n                  exists Error_state.\n                  apply ST_EqCmp_leak; auto.\n                  left. exists o; exists cls_def; exists F; exists lo;\n                          split; auto.\n             ++++\n               exists (Config ct (Container (B_true) fs lb sf) ctns h).\n               apply ST_EqCmp_result; auto.\n               intros. intuition.\n         +++ inversion H11; subst; inversion H; subst; auto.\n             ++++ destruct H27 as [F]. destruct H16 as [lo].\n                  inversion H12; subst; inversion H9; subst; auto.\n                  +++++ destruct H30 as [F2]. destruct H21 as [lo2].\n                    case_eq (flow_to lo lb); intro.\n                    case_eq (flow_to lo2 lb); intro.\n                  exists (Config ct (Container (B_false) fs lb sf) ctns h).\n                  apply ST_EqCmp_result; auto.\n                  intros. intuition.\n                  \n                  right; exists o; exists cls_def; exists F; exists lo;\n                    split; auto.\n                  right; exists o0; exists cls_def0; exists F2; exists lo2;\n                    split; auto.\n\n                  exists Error_state.\n                  apply ST_EqCmp_leak; auto.\n                  right. exists o0; exists cls_def0; exists F2; exists lo2;\n                           split; auto.\n                  \n                  exists Error_state.\n                  apply ST_EqCmp_leak; auto.\n                  left. exists o; exists cls_def; exists F; exists lo;\n                    split; auto.\n                  +++++ case_eq (flow_to lo lb); intro.\n                    * exists (Config ct (Container (B_false) fs lb sf) ctns h).\n                       apply ST_EqCmp_result; auto.\n                       intros. intuition.\n                       right; exists o; exists cls_def; exists F; exists lo;\n                         split; auto.\n                    * exists Error_state.\n                       apply ST_EqCmp_leak; auto.\n                       left. exists o; exists cls_def; exists F; exists lo;\n                               split; auto.\n               ++++ \n                 inversion H12; subst; inversion H9; subst; auto.\n                 +++++ destruct H27 as [F2]. destruct H16 as [lo2].\n                 case_eq (flow_to lo2 lb); intro.\n                 * exists (Config ct (Container (B_false) fs lb sf) ctns h).\n                  apply ST_EqCmp_result; auto.\n                  intros. intuition.\n                  right. exists o; exists cls_def; exists F2; exists lo2;\n                           split; auto.\n                 * exists Error_state.\n                   apply ST_EqCmp_leak; auto.\n                   right. exists o; exists cls_def; exists F2; exists lo2;\n                            split; auto.\n                   +++++ intuition.\n\n                   ++ exists (Config ct (Container e2 ((EqCmp e1 hole) :: fs) lb sf) ctns h).\n                      auto.\n\n    + right.\n      exists ( Config ct (Container e1 ((EqCmp hole e2) :: fs) lb sf) ctns h). auto. \n         \n\n  (*field access*)\n  - pose proof (excluded_middle_value e).\n    destruct H10.\n    right. inversion H10; subst; inversion H; subst; auto. \n    + destruct H25 as [F].\n      destruct H12 as [lo].\n      assert (exists v, F(f) = Some v).\n      apply field_val_of_heap_obj with h o ct cls_def0 lo cls' (find_fields cls_def); auto.\n      subst; auto. \n      rewrite <- H9 in H16; inversion H16; subst; auto.  \n      destruct H15 as [v]. \n      remember (Label.join_label lo lb) as l'.\n      exists (Config ct (Container v fs l' sf) ctns h); auto.\n      eauto using reduction. \n    + exists Error_state; subst; auto.\n    + right. exists (Config ct (Container (e) ((FieldAccess hole f)::fs) lb sf) ctns h); auto.\n \n\n  (* method call *)\n  - pose proof (excluded_middle_value e).\n    destruct H12; subst; auto.\n    right. inversion H12; subst; inversion H; subst; auto.\n    + pose proof (excluded_middle_value argu). destruct H21.\n      ++ destruct H28 as [F]. destruct H22 as [lx].\n         subst. rewrite <- H10 in H23. inversion H23;subst. \n         remember (sf_update empty_stack_frame arg_id argu) as sf'.\n         case_eq (flow_to lx lb); intro.\n         +++ exists (Config ct (Container body nil lb sf' ) ((Container (return_hole) fs lb sf ) :: ctns) h). \n             eauto using reduction.\n         +++ exists Error_state; subst; auto.\n             eauto using reduction.\n      ++ pose proof (exclude_middle_unlabelOpaque argu).\n         destruct H22.\n         +++ destruct H22 as [v]. destruct H22. \n             destruct H28 as [F].\n             destruct H25 as [lo].\n             rewrite <- H10 in H23; inversion H23; subst; auto.\n             inversion H9; subst; auto.\n             inversion H22; subst; inversion H26; subst; auto.\n             ++++ exists Error_state. auto.\n             ++++ case_eq (flow_to lo lb); intro.\n                  +++++\n                    remember ( sf_update empty_stack_frame arg_id v0) as sf'. \n                  remember ( join_label lb lb0) as lb'. \n                  exists (Config ct (Container body nil lb' sf' ) ((Container return_hole fs lb sf ) :: ctns) h). \n                  apply ST_MethodCall_unlableOpaque with cls_def F arg_id arguT returnT lo; auto.\n                  +++++ exists Error_state.\n                  apply ST_MethodCall_unlableOpaque_leak with cls_def F lo (join_label lb lb0); auto.\n\n         +++ destruct H22; subst; auto.\n             ++++ exists (Config ct (Container argu ((MethodCall (ObjId o) meth  hole) :: fs) lb sf) ctns h).\n                  auto. apply ST_MethodCall4; auto.\n                  intro contra; inversion contra.\n\n             ++++ auto. destruct H22 as [e2]. destruct H22. subst; auto.\n                  exists (Config ct (Container e2 ((MethodCall  (ObjId o) meth (unlabelOpaque hole)) :: fs) lb sf) ctns h).\n                  apply ST_MethodCall5; auto.\n                  intro contra; inversion contra.\n                      + exists Error_state; subst; auto.\n    + eauto using reduction.\n    \n\n  (*new exp*)\n  - destruct H as [cls].\n    destruct H as [field_defs].\n    destruct H as [method_defs].\n    destruct H. remember (get_fresh_oid h) as o. \n    remember (init_field_map (find_fields cls) empty_field_map) as F. \n    remember (add_heap_obj h o (Heap_OBJ cls F lb)) as h'.\n    right. exists (Config ct (Container (ObjId o) fs lb sf ) ctns h'). \n    apply ST_NewExp with field_defs method_defs cls F; auto. \n\n\n    Lemma exclude_middle_null : forall v, value v ->\n                                          v = null \\/ v <> null.\n    Proof with eauto.\n      intros.  inversion H; try (right; intro contra; inversion contra; fail).\n      left. auto.\n    Qed. Hint Resolve exclude_middle_null.      \n    \n  (*label data*)\n  -  pose proof (excluded_middle_value e).\n     destruct H11; right.\n     + pose proof exclude_middle_null e H11 .\n       destruct H12.\n       exists Error_state. subst; apply ST_LabelDataException.\n       exists (Config ct (Container (v_l e lb0)  fs lb sf) ctns h); auto.\n     + exists (Config ct (Container e ((labelData hole lb0) :: fs) lb sf) ctns h ); auto.\n\n  (*unlabel*)\n  - pose proof (excluded_middle_value e).\n    destruct H10; right.\n    + inversion H10; subst; inversion H; subst; auto.  \n      ++ exists Error_state. auto.\n         \n      ++ subst. remember (join_label lb lb0) as l'.\n         exists (Config ct (Container v fs l' sf) ctns h); auto.\n  + exists (Config ct (Container (e) ((unlabel hole)::fs) lb sf) ctns h); auto.\n\n  (*(labelOf e)*)\n  - pose proof (excluded_middle_value e).\n    destruct H10; right. \n    + inversion H10; subst; inversion H; subst; auto.  \n      ++ exists Error_state. auto.\n      ++ exists (Config ct (Container (l lb0) fs lb sf) ctns h). auto.\n    + exists (Config ct (Container (e) ((labelOf hole)::fs) lb sf) ctns h); auto.\n\n  (*(unlabelOpaque e)*)\n  - pose proof (excluded_middle_value e).\n    destruct H10; right.\n    + inversion H10; subst; inversion H; subst; auto.  \n      ++ exists Error_state. auto. \n      ++ subst. remember (join_label lb lb0) as l'.\n         exists (Config ct (Container v fs l' sf) ctns h); auto.\n  + exists (Config ct (Container (e) ((unlabelOpaque hole)::fs) lb sf) ctns h); auto.\n\n\n  (*raise label*)\n  -  pose proof (excluded_middle_value e).\n     destruct H11; right.\n     + inversion H11; subst; auto; inversion H9; subst; auto.\n       destruct H25 as [F]. destruct H12 as [lo].\n       case_eq (flow_to lb lo); intro.\n       case_eq (flow_to lo lb0); intro.\n       remember  (update_heap_obj h o (Heap_OBJ cls_def F lb0)) as h'.\n       exists (Config ct (Container Skip fs lb sf) ctns h' ). auto.\n       eauto using ST_raiseLabel3 . \n\n       exists Error_state. eauto using ST_raiseLabelException2.\n       exists Error_state. eauto using ST_raiseLabelException2.\n       exists Error_state. eauto using ST_raiseLabelException1.\n\n     + exists (Config ct (Container e ((raiseLabel hole lb0) :: fs) lb sf) ctns h ); auto.\n    \n  (* skip *)\n  - destruct fs. \n    + inversion H_typing; subst; auto.\n      inversion H11; subst; auto.\n      inversion H28; subst; auto.\n      inversion H21; subst; auto.\n      assert (T1 = voidTy); auto.\n      subst; auto.\n      intuition. \n   + right.  exists (Config ct (Container t fs lb sf) ctns h ); auto.\n\n  (*(Assignment x e) *)   \n  - pose proof (excluded_middle_value e).\n    destruct H11; right.\n    + remember ( sf_update sf x e) as sf'.\n      exists (Config ct (Container Skip fs lb sf') ctns h). auto.\n    + exists (Config ct (Container (e) ((Assignment x hole)::fs) lb sf) ctns h); auto.\n\n  (* (FieldWrite x f e)*)\n  - pose proof (excluded_middle_value x).\n    destruct H12; subst; auto.\n    right. inversion H12; subst; inversion H; subst; auto.\n    + pose proof (excluded_middle_value e). destruct H15.\n      ++ destruct H26 as [F]. destruct H16 as [lx].\n         subst. rewrite <- H10 in H21. inversion H21;subst.\n         rename lx into lo. \n         case_eq (flow_to lb lo); intro.\n         \n         +++ inversion H15; subst; auto; inversion H9; subst; auto.\n             ++++ destruct H31 as [F0].\n                  destruct H23 as [lo0].\n                  case_eq (flow_to lo0 lo); intro.\n                  +++++ remember (fields_update F f (ObjId o0)) as F'.\n                  remember ( update_heap_obj h o (Heap_OBJ cls_def F' lo)) as h'.\n                  exists (Config ct (Container Skip fs lb sf) ctns h' ); auto.\n                  apply ST_fieldWrite_normal with lo cls_def F F'; auto.\n                  right.\n                  exists o0. exists cls_def0.\n                  exists F0. exists lo0. split; auto.\n                  +++++ exists Error_state.\n                  apply ST_fieldWrite_leak with lo cls_def F; auto.\n                  right.\n                  exists o0. exists cls_def0.\n                  exists F0. exists lo0. split; auto.\n             ++++ remember (fields_update F f null) as F'.\n                  remember ( update_heap_obj h o (Heap_OBJ cls_def F' lo)) as h'.\n                  exists (Config ct (Container Skip fs lb sf) ctns h' ); auto.\n                  apply ST_fieldWrite_normal with lo cls_def F F'; auto.\n         +++ exists Error_state.\n             apply ST_fieldWrite_leak with lo cls_def F; auto.\n      ++ pose proof (exclude_middle_unlabelOpaque e).\n         destruct H16.\n         +++ destruct H16 as [v]. destruct H16. \n             destruct H26 as [F].\n             destruct H23 as [lo].\n             rewrite <- H10 in H21; inversion H21; subst; auto.\n             inversion H9; subst; auto.\n             inversion H16; subst; inversion H24; subst; auto.\n             ++++ exists Error_state. auto.\n\n             \n             ++++\n               case_eq (flow_to (join_label lb lb0) lo); intro.\n               +++++\n                 inversion H36; subst; inversion H34; subst; auto.\n               destruct H39 as [F0].\n               destruct H27 as [lo0].                  \n               ++++++ case_eq (flow_to lo0 lo); intro. \n                 * remember (fields_update F f (ObjId o0)) as F'.\n               remember ( update_heap_obj h o (Heap_OBJ cls_def F' lo)) as h'.\n               exists (Config ct (Container Skip fs lb sf) ctns h' ); auto.\n               apply ST_fieldWrite_unlableOpaque with lo cls_def F F'; auto.\n               right.\n               exists o0. exists cls_def0.\n               exists F0. exists lo0. split; auto.\n                 * exists Error_state.\n                   apply ST_fieldWrite_unlableOpaque_leak with lo cls_def F; auto.\n                   right. exists o0. exists cls_def0.\n                  exists F0. exists lo0. split; auto.\n                  ++++++  remember (fields_update F f null) as F'.\n                  remember ( update_heap_obj h o (Heap_OBJ cls_def F' lo)) as h'.\n                  exists (Config ct (Container Skip fs lb sf) ctns h' ); auto.\n                  apply ST_fieldWrite_unlableOpaque with lo cls_def F F'; auto.\n\n                  +++++ exists Error_state.\n                  apply ST_fieldWrite_unlableOpaque_leak with lo cls_def F; auto.\n\n        +++ destruct H16. \n            ++++ exists (Config ct (Container e ((FieldWrite (ObjId o) f hole) :: fs) lb sf) ctns h).\n                  auto. apply ST_fieldWrite3; auto.\n                  intro contra; inversion contra.\n\n            ++++ destruct H16 as [e2]. destruct H16.\n                 subst; auto. \n              \n                  exists (Config ct (Container e2 ((FieldWrite  (ObjId o) f (unlabelOpaque hole)) :: fs) lb sf) ctns h).\n                  apply ST_fieldWrite5; auto.\n                  intro contra; inversion contra.\n    + exists Error_state; subst; auto.\n    +  eauto using reduction.\n\n(* if *)\n  - pose proof (excluded_middle_value guard). destruct H11; subst; right.\n    + inversion H11; subst; inversion H; subst; auto; eauto using reduction.\n\n    + eauto using reduction.\n\n(* sequence *)      \n  - right. eauto using reduction.\n\n(* (Container hole fs lb sf) *)    \n  - inversion H18. \n\n\n(* (Container hole fs lb sf) *)    \n  - inversion H_valid_config; subst; auto.\n    inversion H17. \nQed. Hint Resolve Progress. ", "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/progress.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.29076137484532255}}
{"text": "From Coq Require Import Lists.List.\nFrom Coq Require Import Bool.Bool.\nFrom Coq Require Import Logic.FunctionalExtensionality.\nRequire Import RBT.Verif.RBtree_Type.\nRequire Import RBT.Verif.RBtree_Definition.\nRequire Import RBT.Verif.Half_Tree.\nRequire Import RBT.Verif.relation_map.\nRequire Import RBT.Verif.Abstract. \nRequire Import RBT.Verif.general_split.\n\nSection Section_Insert.\n\nContext {rbt:RBtree_setting}.\n\nLtac res_intros:= \n      let K  := fresh \"K\"  in\n      let Hl := fresh \"Hl\" in\n      let Hr := fresh \"Hr\" in\n      intros K  Hl Hr;\n      super_destruct Hl; super_destruct Hr;\n      repeat (  subst; solve_order).\nLtac res_intro :=\n     let Hl := fresh \"Hl\" in\n      intros  Hl ;\n      super_destruct Hl;\n      repeat (  subst; solve_order).\nLtac res_simpl :=\n match goal with \n | H : SearchTree' _ ?t _ , H0: Abs ?t ?cts |- restriction ?cts _ =>\n                 apply (restriction_rb _ _ _ _  H H0)\n | H : SearchTree_half _ ?h _ , H0: Abs_half ?h ?hmap |- restriction ?hmap _ =>\n                 apply (restriction_half _ _ _ _ H H0)\n | |- restriction ( v_update ?k ?v ?cts) _ =>\n                 apply res_vupdate;res_simpl\n | |- restriction relate_default ?p => apply (restriction_default (fun x => x < x ))\n | |- restriction (tag_update ?t ?cts) _ => apply res_tagupdate; res_simpl\n | |- restriction (combine ?a ?b) _ => \n     apply res_combine; [ res_simpl | res_simpl | res_intros |res_intros ]\n end.\n \n Ltac stt n :=\n    first [assumption | apply ST_E |\n      match n with\n      | S ?m =>\n          match goal with\n          | |- _ <=  _ => TR 5;stt m\n          | |- _ < _ => TR 5;stt m\n          | H: SearchTree' ?lo (T Red ?l ?k ?v ?t ?r) ?hi \n             |- SearchTree' ?lo (T Black ?l ?k ?v ?t ?r) ?hi\n              => eapply (st_color l k v t r lo hi Red Black);stt m\n          | H: SearchTree' ?lo (T Black ?l ?k ?v ?t ?r) ?hi \n             |- SearchTree' ?lo (T Red ?l ?k ?v ?t ?r) ?hi\n              => eapply (st_color l k v t r lo hi Black Red);stt m\n          | H: SearchTree' ?k ?a ?hi |-  SearchTree' ?lo ?a ?hi \n                         => eapply (search_popro3_lte lo a hi k);stt m\n          | H: SearchTree' ?lo ?a ?k |-  SearchTree' ?lo ?a ?hi \n                         => eapply (search_popro2_lte lo a hi k);stt m\n          | H: SearchTree' ?lo ?a ?hi |- SearchTree' ?k0 ?a ?k1\n                         =>  eapply (search_popro3_lte k0 a k1 lo);stt m\n          | |- SearchTree' _ (T _ _ _ _ _ _ ) _ => eapply ST_T;stt m\n          end\n      end].\n \n Ltac rbco n :=\n    first [assumption | apply (IsRB_co_leaf Red) | apply (IsRB_co_leaf Black)|\n      match n with\n      | S ?m =>\n          match goal with\n          | H: is_redblack_color ?a Red |- is_redblack_color ?a Black => eapply isr_isb;rbco m\n          | H: is_redblack_color ?a Black,\n            H0: Black_tree ?a |- is_redblack_color ?a Red => eapply (isb_isr_black _ H0);rbco m\n          | |- is_redblack_color (tag_tree_t _ ?a) _ => eapply isrb_tagupdate;rbco m\n          | H: is_redblack_color (T _ ?a _ _ _ _ ) _ |- is_redblack_color ?a _ => inversion H;subst;rbco m\n          | H: is_redblack_color (T _ _ _ _ _ ?a ) _ |- is_redblack_color ?a _ => inversion H;subst;rbco m\n          | |- is_redblack_color (T Red _ _ _ _ _ ) Black => apply IsRB_co_r;rbco m \n          | |- is_redblack_color (T Black _ _ _ _ _ ) _ => apply IsRB_co_b;rbco m\n          end\n      end].\nLtac rbdep n :=\n    first [assumption | apply IsRB_dep_em |\n      match n with\n      | S ?m =>\n          match goal with\n          | H: is_redblack_dep (T ?c ?l _ _ _ ?r) ?n \n                |- is_redblack_dep (T ?c ?l _ _ _ ?r) ?n  \n                     => eapply isrb_changekvt_dep;try eassumption\n          | |- is_redblack_dep (tag_tree_t _ ?a) ?n\n                    => eapply isrb_tagupdate_dep;rbdep m\n          | H: is_redblack_dep (T Red ?l _ _ _ ?r) ?n\n                |- is_redblack_dep (T Black ?l _ _ _ ?r) (S ?n)  \n                     => eapply isrb_dep_RtoB;rbdep m\n          | |- is_redblack_dep (T Red _ _ _ _ _ ) _ => eapply IsRB_dep_r;rbdep m\n          | |- is_redblack_dep (T Black _ _ _ _ _ ) _ => eapply IsRB_dep_b;rbdep m\n          end\n      end].\n   Ltac TR n :=\n    first [assumption | apply lte_refl |\n      match n with\n      | S ?m =>\n          match goal with\n          | H: lt_prop ?a _ |- lte_prop ?a _ => apply (lte_trans _ _ _ (lt_lte _ _ H)); TR m\n          | H: lte_prop ?a _ |- lte_prop ?a _ => apply (lte_trans _ _ _ H); TR m\n          | H: lte_prop ?a _ |- lt_prop ?a _ => apply (lte_lt_trans _ _ _ H); TR m\n          | H: lt_prop ?a _ |- lt_prop ?a _ => apply (lt_lte_trans _ _ _ H); TR m\n          | H: lte_bool ?a _  = true |- lte_prop ?a _ => rewrite <- (lteb_lte _ _ ) in H;TR m\n          | H: lte_bool ?a _ = true |- lt_prop ?a _ => rewrite <- (lteb_lte _ _ ) in H;TR m\n          | H: lt_bool ?a _  = true |- lte_prop ?a _ => rewrite <- (ltb_lt  _ _ ) in H;TR m\n          | H: lt_bool ?a _ = true |- lt_prop ?a _ => rewrite <- (ltb_lt  _ _) in H;TR m\n          | H: lte_bool _ ?a  = false |- lte_prop ?a _ => rewrite  (lteb_false_lt _ _ ) in H;TR m\n          | H: lte_bool _ ?a = false |- lt_prop ?a _ => rewrite  (lteb_false_lt _ _ ) in H;TR m\n          | H: lt_bool _ ?a  = false |- lte_prop ?a _ => rewrite  (ltb_false_lte _ _ ) in H;TR m\n          | H: lt_bool _ ?a = false |- lt_prop ?a _ => rewrite  (ltb_false_lte _ _ ) in H;TR m\n          | H: lt_prop ?a _ |- lt_bool ?a _ = true => rewrite (ltb_lt  _ _ ) in H;TR m\n          end\n      end].\n\nLtac solve_order :=\nmatch goal with\n| H: lt_prop ?a _ |- _ =>\n    let CONTR := fresh \"H\" in\n    assert (a < a) as CONTR by (TR 6);\n    exfalso; exact (lt_refl _ CONTR)\n| H: lte_prop ?a _ |- _ =>\n    let CONTR := fresh \"H\" in\n    assert (a < a) as CONTR by (TR 6);\n    exfalso; exact (lt_refl _ CONTR)\n| H: lt_bool ?a _ =true |- _  =>\n    let CONTR := fresh \"H\" in\n    assert (a < a) as CONTR by (TR 6);\n    exfalso; exact (lt_refl _ CONTR)\nend.\nLtac tr := TR 2.\n\nLtac super_destruct H :=\n  cbv beta delta [add_one union] in H;\n  match type of H with\n  | _ /\\ _ => let H0 := fresh \"H\" in \n              destruct H as [H H0];\n              super_destruct H;\n              super_destruct H0\n  | _ \\/ _ => destruct H as [H | H];\n              super_destruct H\n  | _ => idtac\n  end.\n   Ltac TRM n :=\n    first [assumption | apply lte_refl |\n      match n with\n      | S ?m =>\n          match goal with\n          | |- _ /\\ _ => split;TRM m\n          | H: lt_prop ?a _ |- lte_prop ?a _ => apply (lte_trans _ _ _ (lt_lte _ _ H)); TRM m\n          | H: lte_prop ?a _ |- lte_prop ?a _ => apply (lte_trans _ _ _ H); TRM m\n          | H: lte_prop ?a _ |- lt_prop ?a _ => apply (lte_lt_trans _ _ _ H); TRM m\n          | H: lt_prop ?a _ |- lt_prop ?a _ => apply (lt_lte_trans _ _ _ H); TRM m\n          | H: lte_bool ?a _  = true |- lte_prop ?a _ => rewrite <- (lteb_lte _ _ ) in H;TRM m\n          | H: lte_bool ?a _ = true |- lt_prop ?a _ => rewrite <- (lteb_lte _ _ ) in H;TRM m\n          | H: lt_bool ?a _  = true |- lte_prop ?a _ => rewrite <- (ltb_lt  _ _ ) in H;TRM m\n          | H: lt_bool ?a _ = true |- lt_prop ?a _ => rewrite <- (ltb_lt  _ _) in H;TRM m\n          | H: lte_bool _ ?a  = false |- lte_prop ?a _ => rewrite  (lteb_false_lt _ _ ) in H;TRM m\n          | H: lte_bool _ ?a = false |- lt_prop ?a _ => rewrite  (lteb_false_lt _ _ ) in H;TRM m\n          | H: lt_bool _ ?a  = false |- lte_prop ?a _ => rewrite  (ltb_false_lte _ _ ) in H;TRM m\n          | H: lt_bool _ ?a = false |- lt_prop ?a _ => rewrite  (ltb_false_lte _ _ ) in H;TRM m\n          | H: lt_prop ?a _ |- lt_bool ?a _ = true => rewrite (ltb_lt  _ _ ) in H;TRM m\n          | H: SearchTree' ?a ?t ?hi |-  ?a < _  => apply (search_popro a t hi ) in H;TRM m\n          | H: SearchTree' ?a ?t ?hi |-  ?a <= _  => apply (search_popro a t hi ) in H;TRM m\n          | |- min_k ?a ?b <= ?a => apply min_left\n          | |- ?a <= max_k ?a ?b => apply max_left\n          | |- min_k ?a ?b <= ?b => apply min_right\n          | |- ?b <= max_k ?a ?b => apply max_right\n          | |- ?x <= max_k ?y (max_k ?z ?x) => erewrite <- max_asso;TRM m\n          | |- max_k ?x ?y < ?z => erewrite <- max_lt; TRM m\n          | |- max_k ?x ?y <= ?z => erewrite <- max_lt_e; TRM m\n          | |- ?z <  min_k ?x ?y  => erewrite <- min_lt; TRM m\n          | |- ?z <=  min_k ?x ?y  => erewrite <- min_lt_e; TRM m\n          end\n      end].\nLtac stt2 n :=\n    first [assumption |\n      match n with\n      | S ?m =>\n          match goal with\n          | |- _ <=  _ => TRM 5;stt2 m\n          | |- _ < _ => TRM 5;stt2 m\n          | H: SearchTree' ?lo ?t ?hi, \n            H1: SearchTree' ?low ?t ?hi\n             |- SearchTree' (max_k ?lo ?low) ?t ?hi \n              => eapply search_left_max;stt2 m\n          | H: SearchTree' ?lo ?t ?hi, \n            H1: SearchTree' ?lo ?t ?high\n             |- SearchTree' ?lo ?t (min_k ?hi ?high)\n              => eapply search_right_min;stt2 m\n          | H: SearchTree' ?lo (T _ ?l ?k ?v ?t ?r) ?hi, \n            H1: SearchTree' ?low (T _ ?l ?k ?v ?t ?r) ?hi\n             |- SearchTree' (max_k ?lo ?low) (T _ ?l ?k ?v ?t ?r) ?hi \n              => eapply search_left_max;stt2 m\n          | H: SearchTree' ?lo (T _ ?l ?k ?v ?t ?r) ?hi, \n            H1: SearchTree' ?lo (T _ ?l ?k ?v ?t ?r) ?high\n             |- SearchTree' ?lo (T _ ?l ?k ?v ?t ?r) (min_k ?hi ?high)\n              => eapply search_right_min;stt2 m\n          | H: SearchTree' ?lo (T Red ?l ?k ?v ?t ?r) ?hi \n             |- SearchTree' ?lo (T Black ?l ?k ?v ?t ?r) ?hi\n              => eapply (st_color l k v t r lo hi Red Black);stt2 m\n          | H: SearchTree' ?lo (T Black ?l ?k ?v ?t ?r) ?hi \n             |- SearchTree' ?lo (T Red ?l ?k ?v ?t ?r) ?hi\n              => eapply (st_color l k v t r lo hi Black Red);stt2 m\n          | H: SearchTree' ?k ?a ?hi |-  SearchTree' ?lo ?a ?hi \n                         => eapply (search_popro3_lte lo a hi k);stt2 m\n          | H: SearchTree' ?lo ?a ?k |-  SearchTree' ?lo ?a ?hi \n                         => eapply (search_popro2_lte lo a hi k);stt2 m\n          | H: SearchTree' ?lo ?a ?hi |- SearchTree' ?k0 ?a ?k1\n                         =>  eapply (search_popro3_lte k0 a k1 lo);stt2 m\n          | |- SearchTree' _ (T _ _ _ _ _ _ ) _ => eapply ST_T;stt2 m\n          end\n      end | apply ST_E ].\n\n  Definition insert_split (x: Key)(t: Tag)(s: RBtree) (b : list Half_tree): list Half_tree * RBtree := general_split (fun k => x <? k) (fun k =>  k <? x) t s b.\n  Definition insert_root (x : Key) (v: Value)(s:RBtree) : RBtree :=\n  match s with\n  |Empty => T Red Empty x v default Empty\n  |T co l y v' t r =>  T co l y v t r\n  end.\n  Definition insert' x v s := let (h,b) := insert_split x default s nil in\n                                 (h, insert_root x v b).\n  Fixpoint balance'  (l: list Half_tree) (s: RBtree) : list Half_tree * RBtree  :=\n  match l with\n  (**插入结点前为空树*)\n  |nil => ( nil,  s)\n  (**插入点为根节点的儿子*)\n  |_::nil  => (l , s)\n  (**插入点有父亲和祖父*)\n  |(pb, pc, p, pv, pt, brother) :: (gb, gc, g, gv, gt, uncle) :: l'\n  => (*父亲结点为黑色则不变，为红色需要调整*)\n    match pc with \n    | Black => (l, s) \n    | Red => \n     (* 此时祖父节点一定为黑色\n     分情况当前结点为父亲结点的左子false还是右子true*)\n     match pb with\n     |false => \n       (**讨论叔叔结点的颜色*)\n       match uncle with\n       |T Red a u uv ut b => \n         (**讨论叔叔节点为左子true还是右子false*)\n         match gb with\n         |false =>\n         (*将父节点和叔叔节点涂黑，祖父节点涂红指向祖父节点进行平衡*)\n         balance' l' ( T Red (T Black s p pv pt brother) g gv gt (T Black a u uv ut b))\n         |true => \n         balance' l' ( T Red (T Black a u uv ut b) g gv gt (T Black s p pv pt brother))\n         end\n       |_ => \n         (**讨论叔叔节点为左子true还是右子false*)\n         match gb with \n         |false => (*父节点黑，祖父红，祖父为支点右旋*)\n            (l',ri_rotate_notag  Red (T Black s p pv pt brother) g gv gt uncle)\n         |true => (*先以父节点为支点右旋，把我涂黑祖父红，祖父为父为支点左旋*)\n            (l', le_rotate_notag Red uncle g gv gt (ri_rotate_notag Red (makeBlack s) p pv pt brother ) )\n         end\n       end\n     |true => (**讨论叔叔结点的颜色*)\n       match uncle with\n       |T Red a u uv ut b => \n       (**讨论叔叔节点为左子true还是右子false*)\n         match gb with\n         |false =>\n         (*将父节点和叔叔节点涂黑，祖父节点涂红指向祖父节点进行平衡*)\n         balance' l' ( T Red (T Black brother p pv pt s) g gv gt (T Black a u uv ut b))\n         |true => \n         balance' l' ( T Red (T Black a u uv ut b) g gv gt (T Black brother p pv pt s))\n         end\n       |_ => \n         (**讨论叔叔节点为左子true还是右子false*)\n         match gb with \n         |false => (*先以父节点为支点左旋，把我涂黑祖父红，祖父为父为支点右旋*)\n            (l', ri_rotate_notag Red (le_rotate_notag Red brother p pv pt (makeBlack s)) g gv gt uncle )\n         |true => (*父节点黑，祖父红，祖父为支点左旋*)\n            (l',le_rotate_notag  Red uncle g gv gt (T Black brother p pv pt s))\n         end\n       end\n     end\n    end\n  end.\n\nInductive insert k v t : RBtree -> Prop :=\n|insert_intro : forall l s h b, (l, s) = insert' k v t ->\n  ( Red_tree s /\\ (h, b) = balance' l s)\\/\n         (Black_tree s /\\ ( h,b) = (l ,s))   ->\n           insert k v t (makeBlack(complete_tree h b)).\n\n\n(*Lemmas *)\n  Lemma insert_lb_rb :\n    forall k0 ,\n     (forall Rb,  (fun s  => k0 <? s) Rb  = negb ((fun s => s <? k0) Rb ) \\/ ((fun s =>  k0 <? s) Rb = false /\\(fun s => s <? k0) Rb = false)).\n  Proof.\n    intros.\n    simpl.\n      remember (Rb <? k0) as m.\n      remember  (k0 <? Rb) as n.\n      destruct m.\n      + left.\n        simpl.\n        symmetry in Heqm.\n        rewrite Heqn.\n        apply ltb_false.\n        unfold not.\n        intros.  rewrite <- (ltb_lt Rb k0 ) in Heqm. solve_order.\n      + destruct n.\n        * left.\n          simpl.\n          symmetry in Heqn. \n          reflexivity.\n        * right.\n          tauto.\n  Qed.\n  Lemma insert_split_tag_default :\n    forall lo hi  tree h k t l s ,\n    Forall P h->\n   SearchTree' lo tree hi -> SearchTree_half lo h hi -> (l , s) = insert_split k t tree h -> Forall P l.\n  Proof.\n    intros.\n    unfold insert_split in H2.\n    pose proof insert_lb_rb k.\n    eapply general_split_tag_default; try eassumption.\n  Qed.\n  Lemma insert_split_tag_default_tree :\n   forall lo hi  tree h k t l s ,\n   SearchTree' lo tree hi -> SearchTree_half lo h hi -> (l , s) = insert_split k t tree h ->  default_tag_tree s  \\/ s = Empty.\n  Proof.\n    intros.\n    unfold insert_split in H1.\n    pose proof insert_lb_rb k.\n    eapply general_split_tag_default_tree; try eassumption.\n  Qed.\n  Lemma insert_split_tree : \n     forall lo hi  tree h k t l s ,\n      SearchTree' lo tree hi -> SearchTree_half lo h hi -> (l , s) = insert_split k t tree h -> lb_rb_tree (fun x => k <? x) (fun x => x <? k ) s.\n  Proof.\n    intros.\n    unfold insert_split in H1.\n    pose proof insert_lb_rb k.\n    eapply general_split_lbrb_tree; try eassumption.\n  Qed.\n  Lemma insert_st_pre:\n    forall lo hi  tree h k t l s ,\n      SearchTree' lo tree hi -> SearchTree_half lo h hi ->\n      k <? hi = true /\\  lo <? k = true ->\n      (l , s) = insert_split k t tree h -> \n       ( exists x  y,  SearchTree_half x l y /\\ SearchTree' x s y /\\ (k <? y = true /\\ x <? k = true) ).\n  Proof.\n    intros.\n    unfold insert_split in H1.\n    pose proof insert_lb_rb k.\n    pose proof general_split_ST _ _ _ _ _ _ _ _ _ H3 H H0 H1 H2.\n    auto.\n  Qed.\n  Lemma insert_st_pro:\n    forall lo hi  tree h k t l s ,\n      SearchTree' lo tree hi -> SearchTree_half lo h hi ->\n      (l , s) = insert_split k t tree h -> \n       ( exists x  y,  SearchTree_half x l y /\\ SearchTree' x s y /\\ ( lo <= x /\\ y <= hi ) ).\n  Proof.\n    intros.\n    unfold insert_split in H1.\n    pose proof insert_lb_rb k.\n    pose proof general_split_ST_pro _ _ _ _ _ _ _ _ _ H2 H H0 H1.\n    auto.\n  Qed.\n  Lemma insert_st_prepro:\n    forall lo hi  tree h k t l s ,\n      SearchTree' lo tree hi -> SearchTree_half lo h hi ->\n      k <? hi = true /\\  lo <? k = true ->\n      (l , s) = insert_split k t tree h -> \n       ( exists x  y,  SearchTree_half x l y /\\ SearchTree' x s y /\\ \n          (k <? y = true /\\ x <? k = true)  /\\ ( lo <= x /\\ y <= hi ) ).\n  Proof.\n    intros.\n    unfold insert_split in H1.\n    pose proof insert_lb_rb k.\n    pose proof general_split_ST_prepro _ _ _ _ _ _ _ _ _ H3 H H0 H1 H2.\n    auto.\n  Qed.\n  Lemma insert_st_out :\n   forall lo hi tree h k t l s olo ohi,\n   SearchTree' lo tree hi -> SearchTree_half lo h hi ->\n    SearchTree_half_out olo h ohi ->\n       (l , s) = insert_split k t tree h  ->\n         SearchTree_half_out  (min_k lo olo) l (max_k hi ohi).\n  Proof.\n    intros.\n    pose proof insert_lb_rb k.\n    eapply general_split_ST_out; try eassumption.\n  Qed.\n  Lemma insert_relate_pre:\n    forall lo hi tree h tmap hmap k  t l s,\n    SearchTree' lo tree hi -> Abs tree tmap ->\n    Forall (fun x =>  snd ( fst x) = default) h ->\n     SearchTree_half lo h hi -> Abs_half h hmap -> \n      (l , s ) = insert_split k  t tree h -> Abs (complete_tree l s) (combine (tag_update t tmap) hmap).\n  Proof.\n     intros.\n     unfold insert_split in H1.\n     pose proof insert_lb_rb k.\n     eapply general_split_abs; try eassumption.\n  Qed.\n  Lemma insert_k_st:\n   forall lo hi  tree h k t l s,\n   SearchTree' lo tree hi -> SearchTree_half lo h hi ->\n     (l , s) = insert_split k t tree h  -> s <> Empty ->\n      k <? hi = true /\\  lo <? k = true.\n  Proof.\n    intros.\n    revert h k t l s H0 H1 H2.\n    induction H.\n    - intros.\n      inversion H1.\n      rewrite H5 in H2.\n      contradiction.\n    - intros.\n      unfold insert_split in H2.\n      simpl in H2.\n      remember (k0 <? k).\n      pose proof search_popro _ _ _ H .\n      pose proof search_popro _ _ _ H0 .\n      destruct b.\n      + clear IHSearchTree'2.\n        assert (SearchTree_half lo  ((false, c, k, f (f v t) t0, default,\n          tag_tree_t (Optt t0 t) r) :: h) k).\n       { eapply ST_cons_false; try eassumption.\n         eapply search_tag_tree_t; try eassumption.\n         right. reflexivity. }\n       pose proof IHSearchTree'1 _ _ _  _ _ H6 H2 H3.\n       destruct H7.\n       assert (k0 < k ). { eapply ltb_lt; try eassumption. }\n       split.\n       eapply  ltb_lt. tr.\n       auto.\n     + remember (k <? k0).\n       destruct b.\n       *\n       clear IHSearchTree'1.\n        assert (SearchTree_half  k ((true, c, k, f (f v t) t0, default,\n          tag_tree_t (Optt t0 t) l) :: h) hi).\n       { eapply ST_cons_true; try eassumption.\n         eapply search_tag_tree_t; try eassumption.\n         right. reflexivity. }\n       pose proof IHSearchTree'2 _ _ _  _ _ H6 H2 H3.\n       destruct H7.\n       assert (k < k0 ). { eapply ltb_lt; try eassumption. }\n       split.\n       auto.\n       eapply  ltb_lt. tr.\n       *\n       symmetry in Heqb. symmetry in  Heqb0.\n       rewrite ltb_false in Heqb.\n       rewrite ltb_false in Heqb0.\n       assert (k0 = k).\n       { pose proof lt_or_lte k0 k.\n         destruct H6.\n         contradiction.\n         destruct H6.\n         contradiction.\n         auto. }\n      subst.\n      split. eapply ltb_lt. tr.\n      eapply ltb_lt. tr.\n  Qed.\n\n(*INSERT SearchTree*)\nTheorem insert_root_st:\n forall k v b lo hi,\n  SearchTree' lo b hi -> (k <? hi = true /\\ lo <? k = true) ->\n    SearchTree' lo (insert_root k v b) hi.\nProof.\n  intros.\n  inversion H.\n  destruct H0.\n  - subst. simpl.\n    eapply ST_T.\n    eapply ST_E.\n    rewrite <- (ltb_lt lo k) in H5. tr.\n    eapply ST_E. tr.\n  - subst.\n    simpl.\n    eapply ST_T ; try eassumption.\nQed.\nLemma insert_without_balance_st:\n  forall lo hi tree  k v h b ,\n      SearchTree' lo tree hi ->\n      k <? hi = true /\\  lo <? k = true ->\n      (h, b) = insert' k v tree ->\n      ( exists x y,  SearchTree_half x h y /\\ SearchTree' x b y).\nProof.\n  intros.\n  unfold insert' in H1.\n  remember (insert_split k default tree nil).\n  destruct p.\n  assert  ( exists x  y,  SearchTree_half x l y /\\ SearchTree' x r y /\\(k <? y = true /\\ x <? k = true) ).\n  { eapply insert_st_pre; try eassumption. apply ST_nil.  eapply search_popro;try eassumption. }\n  destruct H2. destruct H2.\n  destruct H2. destruct H3.\n  inversion H1. subst h b.\n   assert (SearchTree' x (insert_root k v r) x0).\n   { eapply insert_root_st; try eassumption. }\n   exists x. exists x0.\n   auto.\nQed.\n    Lemma complete_makeblack_exists : forall l s lo hi,\n     SearchTree' lo s hi -> SearchTree_half lo l hi -> \n       (exists x y,  SearchTree' x (makeBlack(complete_tree l s)) y).\n    Proof.\n      intros.\n      assert (SearchTree (complete_tree l s)).\n      { eapply complete_st_pre;try eassumption. }\n      inversion H1; subst.\n      exists lo0,hi0.\n      eapply makeBlack_st;try eassumption.\n    Qed.\n  Lemma insert_balance_st_pre : \n    forall l lo hi s  h b,\n    SearchTree' lo s hi ->\n       SearchTree_half lo l hi-> Red_tree s ->\n         (h,b) = balance' l s ->\n           (exists x y,  SearchTree' x (makeBlack(complete_tree h b)) y).\n  Proof.\n    intro.\n  assert ((forall (lo hi : Key) (s : RBtree) (h : list Half_tree)\n    (b : RBtree),\n  SearchTree' lo s hi ->\n  SearchTree_half lo l hi ->\n  Red_tree s ->\n  (h, b) = balance' l s ->\n  exists x y : Key, SearchTree' x (makeBlack (complete_tree h b)) y) \n    /\\ \n    (forall (lo hi : Key) (s : RBtree)(a: Half_tree) (h : list Half_tree)\n    (b : RBtree),\n  SearchTree' lo s hi ->\n  SearchTree_half lo (a::l) hi ->\n  Red_tree s ->\n  (h, b) = balance' (a::l) s ->\n  exists x y : Key, SearchTree' x (makeBlack (complete_tree h b)) y) ).\n   { induction l.\n     - intros. split.\n     + intros. inversion H2;subst. exists lo,hi. simpl. eapply makeBlack_st; try eassumption.\n     + intros. destruct a. repeat destruct p.\n       destruct b0.\n        inversion H0;subst. inversion H2;subst. simpl. exists lo0, hi. stt 3.\n        inversion H0;subst. inversion H2;subst. simpl. exists lo, hi0. stt 3.\n     - destruct IHl.\n       split.\n     + intros. eapply H0; try eassumption. \n     + intros.\n       destruct a0. repeat destruct p.\n       destruct a. repeat destruct p.\n       destruct s. inversion H3.\n       inversion H3. subst c1. clear H3. inversion H1;subst.\n       unfold balance' in H4. fold balance' in H4.\n       repeat (match goal with\n       | H: (h,b) = match ?c with |Red => _ |Black =>_ end |- _ =>destruct c\n       | H: (h,b) = if ?x then _ else _  |- _ => destruct x\n       | H: (h,b) = match ?t with | Empty => _ | _ => _  end |- _ => destruct t\n       | H: SearchTree_half _ ((true, _,_,_,_,_)::_ ) _  |- _ => inversion H;subst;clear H\n       | H: SearchTree_half _ ((false, _,_,_,_,_)::_ ) _  |- _ => inversion H;subst;clear H\n       | H: (h,b) = (?l, ?s) |- _ => simpl in H;inversion H;subst;clear H\n       | H: SearchTree_half ?lo ?l ?hi \n         |- (exists x y, SearchTree' x (makeBlack (complete_tree ?l (T ?c ?ll ?k ?v ?t ?rr))) y ) \n            => apply (complete_makeblack_exists l (T c ll k v t rr) lo hi)\n       | H2: (h,b) = balance' l ?s,\n         H1: SearchTree_half ?lo l ?hi \n         |- _ => eapply (H lo hi s);try eassumption\n       | |- SearchTree' _ _ _ => stt 10\n       | |- Red_tree (T Red _ _ _ _ _) => reflexivity\n       end; eauto).\n   }\n   destruct H. auto.\n  Qed.\nLemma insert_balance_st:\n forall lo hi s l h b,\n  SearchTree' lo s hi -> SearchTree_half lo l hi ->\n    ( Red_tree s /\\ (h, b) = balance' l s)\\/\n         (Black_tree s /\\ ( h,b) = (l ,s))   ->\n         (exists x y,  SearchTree' x (makeBlack(complete_tree h b)) y).\nProof.\n  intros.\n  super_destruct H1.\n  - eapply insert_balance_st_pre;try eassumption.\n  - inversion H2. subst.\n    eapply complete_makeblack_exists; try eassumption.\nQed.\nTheorem insert_st: forall t k v finaltree,\n  SearchTree t ->\n  insert k v t finaltree -> SearchTree finaltree.\nProof.\n  intros.\n  inversion H0.\n  inversion H. subst.\n  pose proof (Archmedes_l (min_k lo k) ).\n  pose proof (Archmedes_R (max_k hi k) ).\n  destruct H3. destruct H5.\n  assert ( (k <? x0) = true /\\ (x <? k) = true ).\n  { split. \n    pose proof max_right hi k.\n    eapply ltb_lt. tr.\n    pose proof min_right lo k.\n    eapply ltb_lt. tr. }\n  assert ( SearchTree' x t x0).\n  { eapply search_popro2_lte.  eapply search_popro3_lte; try eassumption.\n    pose proof min_left lo k. tr.\n    pose proof max_left hi k. tr. }\n  clear H4.\n  assert  ( exists x y,  SearchTree_half x l y /\\ SearchTree' x s y).\n  { eapply insert_without_balance_st; try eassumption.  }\n  destruct H4. destruct H4. destruct H4.\n  assert (exists x y,  SearchTree' x (makeBlack(complete_tree h b)) y).\n  eapply insert_balance_st;try eassumption.\n  destruct H9. destruct H9.\n  eapply ST_intro;try eassumption.\nQed.\n\n(*insert searchtree with boundary*)\nLemma insert_st'_without_b : forall lo hi t k v l s,\n SearchTree' lo t hi ->  lo < k /\\ k < hi ->\n (l, s) = insert' k v t ->\n   SearchTree_half_out lo l hi /\\ \n    (exists x y, SearchTree' x s y /\\ SearchTree_half x l y /\\ (lo <= x /\\ y<= hi)).\nProof.\n  intros.\n   unfold insert' in H1. \n    remember (insert_split k default t nil) as in_s;destruct in_s.\n    assert (SearchTree_half lo nil hi). { apply ST_nil. eapply search_popro;eauto. }\n    assert ((k <? hi) = true /\\ (lo <? k) = true ).\n    { destruct H0. split;tr. }\n    split.\n    + assert (SearchTree_half_out lo nil hi). { apply ST_out_nil. eapply search_popro;eauto. }\n    pose proof insert_st_out _ _ _ _ _ _ _ _ _ _ H H2 H4 Heqin_s.\n    rewrite min_self in H5.\n    rewrite max_self in H5.\n    inversion H1.\n    subst. auto.\n    + pose proof insert_st_prepro _ _ _ _ _ _ _ _  H H2 H3 Heqin_s.\n      destruct H4. destruct H4. super_destruct H4.\n      exists x , x0.\n      split.\n      - inversion H1.\n        eapply insert_root_st; eauto.\n      - split.\n        inversion H1;subst.\n        auto.\n        split;tr.\nQed.\n\nLemma insert_balance_st':\n forall l lo hi s x y h b,\n SearchTree_half_out lo l hi -> lo <= x -> y <= hi ->\n  SearchTree' x s y -> SearchTree_half x l y ->\n     Red_tree s -> (h, b) = balance' l s ->\n        SearchTree' lo (complete_tree h b ) hi.\nProof.\n  intro.\n  assert (\n  (forall (lo hi : Key) (s : RBtree) (x y : Key)\n  (h : list Half_tree) (b : RBtree),\nSearchTree_half_out lo l hi ->\nlo <= x ->\ny <= hi ->\nSearchTree' x s y ->\nSearchTree_half x l y ->\nRed_tree s ->\n(h, b) = balance' l s -> SearchTree' lo (complete_tree h b) hi)\n  /\\\n  (forall (lo hi : Key) (s : RBtree) (x y : Key) \n  (h : list Half_tree) (b : RBtree) (a: Half_tree),\nSearchTree_half_out lo (a :: l) hi ->\nlo <= x ->\ny <= hi ->\nSearchTree' x s y ->\nSearchTree_half x (a :: l) y ->\nRed_tree s ->\n(h, b) = balance' (a :: l) s ->\nSearchTree' lo (complete_tree h b) hi)\n  );[ | tauto].\n induction l.\n - split. \n  + intros.\n    inversion H5. subst. simpl. stt 5.\n  + intros.\n    destruct a. repeat destruct p.\n    simpl in H5. inversion H5;subst.\n    destruct b0.\n    ++ simpl.\n       inversion H;subst.\n       inversion H16;subst.\n       pose proof min_left low lo0.\n       inversion H3;subst.\n       stt 5.\n    ++ simpl. inversion H;subst. inversion H16;subst. inversion H3;subst.\n       pose proof max_left high hi0.\n       stt 5.\n - destruct IHl.\n   split;[eauto |].\n   destruct a0. repeat destruct p.\n   destruct a. repeat destruct p.\n   intros.\n   unfold balance' in H7. fold balance' in H7.\n   clear H0.\n   repeat (match goal with\n   | H : (?h, ?b) = match ?c with\n      |Red => _\n      |Black => _\n      end \n    |- SearchTree' _ (complete_tree ?h ?b) _ => destruct c\n   | H : (?h, ?b) = if ?b0 then _ else _ \n    |- SearchTree' _ (complete_tree ?h ?b) _ => destruct b0\n   | H : (?h, ?b) = match ?r with\n     |Empty => _ \n     | T _ _ _ _ _ _ => _ end\n    |- SearchTree' _ (complete_tree ?h ?b) _ => destruct r\n   | H: SearchTree_half_out _ ((true, _,_,_,_,_) :: _) _ |- _ => inversion H;subst;clear H\n   | H: SearchTree_half_out _ ((false, _,_,_,_,_) :: _) _ |- _ => inversion H;subst;clear H\n   | H: SearchTree_half _ ((true, _,_,_,_,_) :: _) _ |- _ => inversion H;subst;clear H\n   | H: SearchTree_half _ ((false, _,_,_,_,_) :: _) _ |- _ => inversion H;subst;clear H\n   | H: SearchTree_half_tree _ (true, _,_,_,_,_) _ |- _ => inversion H;subst;clear H\n   | H: SearchTree_half_tree _ (false, _,_,_,_,_) _ |- _ => inversion H;subst;clear H\n   | H: SearchTree_half_out ?lo ?l ?hi\n      |- SearchTree' (min_k _ ?lo) (complete_tree ?l ?s) (max_k _ ?hi)\n       => eapply search_complete;try eauto\n   | H0: (?h, _ ) = balance' ?l (T Red (T ?cc ?ll ?kk ?vv ?tt ?rr) ?k ?v ?t (T ?ccc ?lll ?kkk ?vvv ?ttt ?rrr)),\n     H1: SearchTree_half ?lo1 ?l ?y,\n     H2: SearchTree' ?lo1 (T _ ?ll ?kk ?vv ?tt ?rr) _,\n     H3: SearchTree' ?low (T _ ?ll ?kk ?vv ?tt ?rr) _,\n     H4: SearchTree' _ ?rrr ?y,\n     H5: SearchTree' _ ?rrr ?high\n     |- SearchTree' ?lo (complete_tree ?h _ ) ?hi\n     => eapply (H lo hi (T Red (T cc ll kk vv tt rr) k v t (T ccc lll kkk vvv ttt rrr)) (max_k lo1 low) (min_k y high));try eauto\n   | H0: (?h, _ ) = balance' ?l (T Red (T ?cc ?ll ?kk ?vv ?tt ?rr) ?k ?v ?t ?r),\n     H1: SearchTree_half ?lo1 ?l ?y,\n     H2: SearchTree' ?lo1 (T _ ?ll ?kk ?vv ?tt ?rr) _,\n     H3: SearchTree' ?low (T _ ?ll ?kk ?vv ?tt ?rr) _\n     |- SearchTree' ?lo (complete_tree ?h _ ) ?hi\n     => eapply (H lo hi (T Red (T cc ll kk vv tt rr) k v t r) (max_k lo1 low) y);try eauto \n   | |- Red_tree (T Red _ _ _ _ _ ) => reflexivity\n   | |- SearchTree' _ (T _ _ _ _ _ _ ) _ => stt2 10\n   | |- _ <= _ /\\ _ < _ => split\n   | |- _ <= _ => TRM 10\n   | |- _ < _ => TRM 10\n   | H : (?h, ?b) = (?l, le_rotate_notag ?c ?ll ?k0 ?v0 ?t0 (T ?c1 ?rr ?k ?v ?t ?s))\n    |- SearchTree' _ (complete_tree ?h ?b) _ => inversion H;subst;simpl;clear H\n   | H: SearchTree_half_out ?lo ?l ?hi,\n     H1: SearchTree_half ?lo1 ?l ?y,\n     H2: SearchTree' ?lo1 ?s _,\n     H3: SearchTree' ?low0 ?s _\n     |- SearchTree' (min_k _ (min_k ?low0 ?lo)) (complete_tree ?l _ ) _ \n      => eapply search_popro3_lte with (min_k (max_k lo1 low0) lo)\n   | H: SearchTree_half_out ?lo ?l ?hi,\n     H1: SearchTree_half ?lo1 ?l ?y,\n     H2: SearchTree' ?lo1 ?s  _,\n     H3: SearchTree' ?low0 ?s _\n     |- SearchTree' (min_k (max_k ?lo1 ?low0) ?lo) (complete_tree ?l _ ) (max_k _ (max_k _ _ )) \n      => eapply search_popro2_lte with (max_k y hi)\n    end). \n    (*le*)\n    * eapply search_h_popro3;eauto. TRM 10.\n    * rewrite <- min_asso. apply min_xz. eapply lte_trans with low0;TRM 4.\n    (*ri le*)\n    * destruct s. inversion H6.\n      inversion H6. subst.\n      inversion H7;subst.\n      inversion H4;subst.\n      eapply search_popro2_lte with (max_k (min_k hi0 high0) hi).\n      ** eapply search_popro3_lte with (min_k (max_k lo0 low) lo).\n      *** eapply search_complete;try eauto.\n      **** stt2 10.  \n      **** eapply search_h_popro2 with hi0. eapply search_h_popro3 with lo0;try eauto.\n           TRM 8. split;[TRM 2|]. eapply lt_lte_trans with k0.  TRM 10. erewrite <- min_lt_e. apply search_popro in H23. apply search_popro in H17. TRM 4.\n      *** rewrite <- min_asso. apply min_xz. eapply lte_trans with low;TRM 4.\n      ** rewrite <- max_asso. apply max_xz. eapply lte_trans with high0;TRM 4.\n    (*balance*)\n    * eapply search_half_popro3_lte with lo.\n      eapply search_half_popro2_lte with hi; eauto.\n      rewrite <- max_asso;TRM 2.\n      rewrite <- min_asso;TRM 2.\n    * eapply lte_trans with low0. \n      rewrite min_comm. rewrite min_asso. TRM 2.\n      TRM 2.\n    * eapply search_h_popro3;eauto. TRM 10.\n    (*balance*) \n    * assert (SearchTree_half_out (min_k low (min_k low0 lo)) l (max_k high (max_k high0 hi))).\n      { eapply search_half_popro3_lte with lo.\n      eapply search_half_popro2_lte with hi; eauto.\n      rewrite <- max_asso;TRM 2.\n      rewrite <- min_asso;TRM 2. }\n      eapply (H _ _ (T Red (T Black r k v t s) k0 v0 t0 (T Black r0_1 k1 v1 t1 r0_2)) (max_k lo0 low) (min_k hi0 high0));eauto.\n      ** eapply lte_trans with low; TRM 4.\n      ** rewrite max_comm. rewrite max_asso.\n         eapply lte_trans with high0;TRM 4.\n      ** stt2 10.\n      ** eapply search_h_popro2 with hi0. eapply search_h_popro3 with lo0;eauto.\n        TRM 10. split. TRM 2.\n        eapply lt_lte_trans with k0.\n        TRM 10.  apply search_popro in H23. apply search_popro in H17. TRM 4.\n      ** reflexivity.\n    (*le*)\n    * eapply search_h_popro3;eauto. TRM 10.\n    * rewrite <- min_asso. apply min_xz. apply lte_trans with low0;TRM 2.\n    (*ri le*)\n    * destruct s. inversion H6.\n      inversion H6. subst.\n      inversion H7;subst.\n      inversion H4;subst.\n      eapply search_popro2_lte with (max_k (min_k hi0 high0) hi).\n      ** eapply search_popro3_lte with (min_k (max_k lo0 low) lo).\n      *** eapply search_complete;try eauto.\n      **** stt2 10.  \n      **** eapply search_h_popro2 with hi0. eapply search_h_popro3 with lo0;try eauto.\n           TRM 8. split;[TRM 2|]. eapply lt_lte_trans with k0.  TRM 10. erewrite <- min_lt_e. apply search_popro in H23. apply search_popro in H17. TRM 4.\n      *** rewrite <- min_asso. apply min_xz. eapply lte_trans with low;TRM 4.\n      ** rewrite <- max_asso. apply max_xz. eapply lte_trans with high0;TRM 4.\n    (*le ri*)\n    * destruct s. inversion H6.\n      inversion H6. subst.\n      inversion H7;subst.\n      inversion H4;subst.\n      eapply search_popro2_lte with (max_k (min_k hi0 high) hi).\n      ** eapply search_popro3_lte with (min_k (max_k lo0 low0) lo).\n      *** eapply search_complete;try eauto.\n      **** stt2 10.  \n      **** eapply search_h_popro2 with hi0. eapply search_h_popro3 with lo0;try eauto.\n           TRM 8. split;[TRM 2|]. eapply lt_lte_trans with k.  TRM 10. erewrite <- min_lt_e. apply search_popro in H18. apply search_popro in H19. TRM 4.\n      *** rewrite <- min_asso. apply min_xz. eapply lte_trans with low0;TRM 4.\n      ** rewrite <- max_asso. apply max_xz. eapply lte_trans with high;TRM 4.\n    (*ri*)\n    * inversion H7;subst.\n      eapply search_popro3_lte with (min_k x lo).\n      ** eapply search_popro2_lte with (max_k (min_k hi1 high0) hi);eauto.\n      *** eapply search_complete;eauto.\n      **** stt2 10.\n      **** eapply search_h_popro2 with hi1;eauto.\n           split;[TRM 2| ]. apply search_popro in H12. TRM 10.\n      *** rewrite <- max_asso. apply max_xz. apply lte_trans with high0;TRM 2.\n      ** erewrite <- min_lt_e. split. auto. rewrite <- min_asso. TRM 2.\n    (*balance*)\n    * eapply search_half_popro3_lte with lo.\n      eapply search_half_popro2_lte with hi; eauto.\n      rewrite <- max_asso;TRM 2.\n      rewrite <- min_asso;TRM 2.\n    * rewrite min_comm. rewrite min_asso. apply lte_trans with low0;TRM 4.\n    * apply lte_trans with high;TRM 4.\n    * eapply search_h_popro2 with hi0. eapply search_h_popro3 with lo0;try eauto.\n    TRM 10. split;[TRM 2| ]. eapply lt_lte_trans with k0. TRM 10.  erewrite <- min_lt_e. split;[TRM 10|]. apply search_popro in H18. TRM 10.\n    (*balance*)\n    * assert (SearchTree_half_out (min_k low (min_k low0 lo)) l (max_k high (max_k high0 hi))).\n      { eapply search_half_popro3_lte with lo.\n      eapply search_half_popro2_lte with hi; eauto.\n      rewrite <- max_asso;TRM 2.\n      rewrite <- min_asso;TRM 2. }\n      eapply (H _ _ (T Red (T Black s k v t r) k0 v0 t0 (T Black r0_1 k1 v1 t1 r0_2)) x  (min_k hi1 high0));eauto.\n      ** rewrite max_comm. rewrite max_asso.\n         eapply lte_trans with high0; TRM 4.\n      ** stt2 10.\n      ** eapply search_h_popro2 with hi1;eauto.\n         split. TRM 2.\n         apply search_popro in H12. TRM 10.\n      ** reflexivity.\n    (*le ri*)\n    * destruct s. inversion H6.\n      inversion H6. subst.\n      inversion H7;subst.\n      inversion H4;subst.\n      eapply search_popro2_lte with (max_k (min_k hi0 high) hi).\n      ** eapply search_popro3_lte with (min_k (max_k lo0 low0) lo).\n      *** eapply search_complete;try eauto.\n      **** stt2 10.  \n      **** eapply search_h_popro2 with hi0. eapply search_h_popro3 with lo0;try eauto.\n           TRM 8. split;[TRM 2|]. eapply lt_lte_trans with k.  TRM 10. erewrite <- min_lt_e. apply search_popro in H18. apply search_popro in H19. TRM 4.\n      *** rewrite <- min_asso. apply min_xz. eapply lte_trans with low0;TRM 4.\n      ** rewrite <- max_asso. apply max_xz. eapply lte_trans with high;TRM 4.\n    (*ri*)\n    * inversion H7;subst.\n      eapply search_popro3_lte with (min_k x lo).\n      ** eapply search_popro2_lte with (max_k (min_k hi1 high0) hi);eauto.\n      *** eapply search_complete;eauto.\n      **** stt2 10.\n      **** eapply search_h_popro2 with hi1;eauto.\n           split;[TRM 2| ]. apply search_popro in H12. TRM 10.\n      *** rewrite <- max_asso. apply max_xz. apply lte_trans with high0;TRM 2.\n      ** erewrite <- min_lt_e. split. auto. rewrite <- min_asso. TRM 2.\n    * inversion H7;subst.\n      pose proof min_lte _ _ H2. rewrite <- H0.\n      pose proof max_lte _ _ H3. rewrite <- H8.\n      rewrite min_comm.\n      pose proof search_complete.\n      eapply (search_complete ((b0, Black, k, v, t, r) :: (b1, c0, k0, v0, t0, r0) :: l) s x y lo hi);eauto.\nQed.\n\nTheorem insert_st': forall lo hi t k v finaltree,\n  SearchTree' lo  t hi  ->  lo < k /\\ k < hi ->\n  insert k v t finaltree -> SearchTree' lo finaltree hi .\nProof.\n  intros.\n  inversion H1.\n  super_destruct H3.\n  - pose proof insert_st'_without_b lo hi t k v l s H H0 H2.\n    destruct H6.\n    destruct H7. destruct H7. super_destruct H7.\n    eapply makeBlack_st.\n    eapply insert_balance_st';eauto.\n  - pose proof insert_st'_without_b lo hi t k v l s H H0 H2.\n    destruct H6.\n    destruct H7. destruct H7. super_destruct H7.\n    eapply makeBlack_st.\n    inversion H5;subst.\n    pose proof search_complete l s x x0 lo hi H7 H8 H6.\n    rewrite min_comm in H4.\n    erewrite min_lte in H4;eauto.\n    erewrite max_lte in H4;eauto.\nQed.\n\n(*INSERT ABS*)\nTheorem insert_root_abs :\n forall k v s x,\n(default_tag_tree s \\/ s = Empty )  -> ( lb_rb_tree (fun x => k <? x) (fun x=> x <? k ) s)->\n Abs s x -> Abs (insert_root k v s) (v_update k v x).\nProof.\n  intros.\n  inversion H1.\n  - subst.\n    simpl.\n    pose proof Abs_T _ _ _ _ k v default Red Abs_E Abs_E.\n    rewrite combine_default in H2.\n    rewrite tag_update_default in H2.\n    auto.\n  - subst.\n    simpl.\n    destruct H.\n    inversion H. subst.\n    assert (v = (f v default)).\n    { rewrite  f_defualt. reflexivity . }\n    rewrite H4.\n    rewrite <- tag_v_update.\n    assert (k = k0).\n    { inversion H0.\n      eapply lt_eq.\n      split.\n      unfold not. intros. solve_order.\n      unfold not. intros. solve_order. }\n    rewrite H5.\n    rewrite v_update_twice.\n    rewrite f_defualt.\n    eapply Abs_T; try eassumption.\n    inversion H.\nQed.\nLemma insert_complete_relate:\n  forall k v t cts l b s ,\n   SearchTree t -> Abs t cts ->\n   (l , b) = insert_split k default t nil\n   -> s = insert_root k v b  ->\n     Abs (complete_tree l s) (v_update k v cts).\nProof.\n intros.\n inversion H.\n subst.\n pose proof (Archmedes_l (min_k lo k) ).\n  pose proof (Archmedes_R (max_k hi k) ).\n  destruct H2. destruct H4.\n  assert ( (k <? x0) = true /\\ (x <? k) = true ).\n  { split. \n    pose proof max_right hi k.\n    eapply ltb_lt. tr.\n    pose proof min_right lo k.\n    eapply ltb_lt. tr. }\n  assert ( SearchTree' x t x0).\n  { eapply search_popro2_lte.  eapply search_popro3_lte; try eassumption.\n    pose proof min_left lo k. tr.\n    pose proof max_left hi k. tr. }\n assert (Forall P nil).\n { apply Forall_nil. }\n assert (SearchTree_half x nil x0 ).\n { apply ST_nil. eapply search_popro; try eassumption. }\n pose proof Abs_nil.\n pose proof insert_relate_pre _ _ _ _ _ _ _ _ _ _ H6 H0 H7 H8 H9 H1.\n pose proof insert_st_pre _ _ _ _ _ _ _ _ H6 H8 H5 H1; clear H3 H2 H4.\n\n destruct H11. destruct H2. super_destruct H2.\n assert (Forall P l).\n { eapply insert_split_tag_default.\n   apply H7.\n   apply H6.\n   apply H8.\n   apply H1. } \n pose proof Abs_exist b. destruct H13.\n pose proof Abs_exist_h l. destruct H14.\n pose proof complete_relate_pre l x1 x2 b x3 x4 H12 H2 H3 H13 H14.\n assert ( (combine (tag_update default cts)\n          relate_default) = (combine x3 x4)).\n { eapply Abs_unique; try eassumption. }\n rewrite tag_update_default in H16.\n rewrite combine_default in H16.\n rewrite H16.\n  assert (lb_rb_tree (fun x => k <? x)(fun x => x <?  k) b).\n  { eapply insert_split_tree.\n    apply H6.\n    apply H8.\n    apply H1. }\n  assert (default_tag_tree b \\/ b = Empty).\n  { eapply insert_split_tag_default_tree.\n    apply H6.\n    apply H8.\n    apply H1. }\n  assert ( Abs (insert_root k v b) (v_update k v x3)).\n  { eapply insert_root_abs; try eassumption. }\n  destruct l.\n  - \n   inversion H14. subst.\n   rewrite combine_default.\n   simpl.\n   auto.\n  -\n   rewrite combine_comm.\n   erewrite <- v_update_combine.\n   2 : res_simpl.\n   2 : res_simpl.\n   2 : res_intros.\n   2 : res_intro.\n   assert (SearchTree' x1 (insert_root k v b) x2).\n   {  eapply insert_root_st; try eassumption.\n      tauto. (* use H8 and H9 H10*)}\n   rewrite combine_comm.\n   eapply complete_relate_pre; try eassumption.\nQed.\n\n  Lemma comple_equi_left: forall (h : list Half_tree) (lo hi : Key) (tree t : RBtree) cts,\n       Forall P h ->\n       SearchTree_half lo h hi ->\n       SearchTree' lo tree hi ->\n       SearchTree' lo t hi ->\n       tree ~~ t -> Abs (complete_tree h tree) cts -> Abs (complete_tree h t) cts.\n  Proof.\n    intros.\n    assert (complete_tree h tree ~~ complete_tree h t).\n    { eapply comple_equi; try eassumption. }\n    eapply H5. auto.\n  Qed.\n  Lemma balance_induction_pre : forall a l h h0 s cts lo hi h1 b,\n   (\n   forall (h h0 : Half_tree) (s : RBtree) (cts : relate_map)\n         (lo hi : Key),\n       SearchTree_half lo (h :: h0 :: l) hi ->\n       SearchTree' lo s hi ->\n       Forall P (h :: h0 :: l) ->\n       default_tag_tree s ->\n       Abs (complete_tree (h :: h0 :: l) s) cts ->\n       forall (h1 : list Half_tree) (b : RBtree),\n       (h1, b) = balance' (h :: h0 :: l) s ->\n       Abs (complete_tree h1 b) cts\n   ) ->\n    (\n     forall (h : Half_tree) (s : RBtree) (cts : relate_map)\n         (lo hi : Key),\n       SearchTree_half lo (h :: l) hi ->\n       SearchTree' lo s hi ->\n       Forall P (h :: l) ->\n       default_tag_tree s ->\n       Abs (complete_tree (h :: l) s) cts ->\n       forall (h0 : list Half_tree) (b : RBtree),\n       (h0, b) = balance' (h :: l) s -> Abs (complete_tree h0 b) cts\n    ) ->\n        SearchTree_half lo (h :: h0 :: a :: l) hi ->\n         SearchTree' lo s hi -> \n            Forall P (h :: h0 :: a :: l) -> \n              default_tag_tree s ->\n                Abs (complete_tree (h :: h0 :: a :: l) s) cts ->\n                 (h1, b) = balance' (h :: h0 :: a :: l) s ->\n          Abs (complete_tree h1 b) cts.\n  Proof.\n   intros.\n   destruct h. repeat destruct p.  destruct h0. repeat destruct p.\n   destruct s.\n    inversion H4.\n   inversion H4. subst t1.\n   inversion H2;subst.\n   unfold balance' in H6 at 1.\n   repeat (match goal with\n   | H: (h1 , b) = match ?c with |Red => _ | Black => _ end |- _ =>destruct c\n   | H: (h1 , b) =if ?x then _ else _  |- _ => destruct x\n   | H: (h1 , b) = match ?r with\n           |Empty => _ | T _ _ _ _ _ _ => _ end |- _ =>destruct r \n   | H:  Abs (complete_tree\n            ((true, _, _, _, _, _) :: _ ) _) _  |- _ => rewrite (@complete_tree_true rbt) in H\n   | H:  Abs (complete_tree\n            ((false, _, _, _, _, _) :: _ ) _) _  |- _ => rewrite (@complete_tree_false rbt) in H\n   | H: snd (fst (_, _, _, _, ?t, _)) = default |- _ => simpl in H;subst t;clear H\n   | H: P (_, _, _, _, ?t, _) |- _ => inversion H;clear H\n   | H : Forall P ((_, _, _, _, ?t, _) :: _) |- _ => inversion H;subst;clear H \n   | H: SearchTree_half _ ((true, _, _, _, _, _) :: _) _ |- _ =>inversion H;subst;clear H\n   | H: SearchTree_half _ ((false, _, _, _, _, _) :: _) _ |- _ =>inversion H;subst;clear H\n   | H: (?h1, ?bb) = (?l, le_rotate_notag ?co1 ?a ?k ?v default (T ?co2 ?b ?k1 ?v1 default ?c)),\n     H1: SearchTree_half ?lo ?l ?hi,\n     H2: Abs  (complete_tree ?l ?tree) ?cts |- Abs  (complete_tree ?h1 ?bb) ?cts\n      =>  inversion H;subst h1 bb;eapply (comple_equi_left l lo hi tree)\n   | H: (?h1, ?bb) = (?l, ri_rotate_notag ?co1 (T ?co2 ?b ?k1 ?v1 default ?c) ?k ?v default ?a),\n     H1: SearchTree_half ?lo ?l ?hi,\n     H2: Abs  (complete_tree ?l ?tree) ?cts |- Abs  (complete_tree ?h1 ?bb) ?cts\n      =>  inversion H;subst h1 bb;eapply (comple_equi_left l lo hi tree)\n   | H: (?h1, ?b) = (let (p0, brother) := ?a in _ ),\n     H1: SearchTree_half ?lo (?a :: l) ?hi,\n     H3: Forall P (?a :: l),\n     H4: Abs\n         (complete_tree (?a :: l)  (T _ (T _ ?r0_1 ?k3 ?v3 ?t2 ?r0_2) ?k1 ?v1 default\n              (T _ ?r ?k0 ?v0 default ?s )) ) cts\n      |- Abs (complete_tree ?h1 ?b) ?cts \n        => eapply (H0 a  (T Red (T Black r0_1 k3 v3 t2 r0_2) k1 v1 default\n              (T Black r k0 v0 default s )) cts lo hi)\n   | H: (?h1, ?b) = (let (p0, brother) := ?a in _ ),\n     H1: SearchTree_half ?lo (?a :: l) ?hi,\n     H3: Forall P (?a :: l),\n     H4: Abs\n         (complete_tree (?a :: l)   (T _ (T _ ?r ?k0 ?v0 default ?s) ?k1 ?v1 default\n               (T _ ?r0_1 ?k3 ?v3 ?t2 ?r0_2)) ) cts\n      |- Abs (complete_tree ?h1 ?b) ?cts \n        => eapply (H0 a  ( T Red (T Black r k0 v0 default s) k1 v1 default\n              (T Black r0_1 k3 v3 t2 r0_2)) cts lo hi)\n   | H: (?h1, ?bb) = (a::l, ri_rotate_notag _(le_rotate_notag _ _ _ _ _ _ )_ _ _ _),\n     H1: SearchTree_half ?lo (a::l) ?hi,\n     H2: Abs  (complete_tree (a::l) ?tree) ?cts |- Abs  (complete_tree ?h1 ?bb) ?cts\n      => inversion H;subst h1 bb;eapply (comple_equi_left (a::l)lo hi tree)\n   | H: (?h1, ?bb) = (a::l, le_rotate_notag _ _ _ _ _(ri_rotate_notag _ _ _ _ _ _ )),\n     H1: SearchTree_half ?lo (a::l) ?hi,\n     H2: Abs  (complete_tree (a::l) ?tree) ?cts |- Abs  (complete_tree ?h1 ?bb) ?cts\n      => inversion H;subst h1 bb;eapply (comple_equi_left (a::l)lo hi tree)\n    | H: Abs\n         (complete_tree (a :: l) (T ?c ?ll ?k1 ?v1 default ?r)) cts,\n     H1: SearchTree_half ?lo (a::l) ?hi\n    |- Abs\n    (complete_tree (a :: l) (T Red _ ?k1 ?v1 default _)) cts\n         => eapply (comple_equi_left (a::l) lo hi (T c ll k1 v1 default r))\n   | H1: SearchTree' ?lo ?a _,\n     H2: SearchTree' _ ?c ?hi\n     |- T _ ?a ?k ?v default (T _ ?b ?k1 ?v1 default ?c) ~~ \n        T _ (T _ ?a ?k ?v default ?b) ?k1 ?v1 default ?c \n        => eapply (ro_equiv _ a k v _ b k1 v1 c _ _ lo hi)\n   | |- T _ (T _ ?a ?k ?v default ?b) ?k1 ?v1 default ?c  ~~\n       T _ ?a ?k ?v default (T _ ?b ?k1 ?v1 default ?c) => eapply Rb_equiv_symm\n   | |- T ?co0 (T ?co1 ?a ?k0 ?v0 default (T ?co2 ?b ?k2 ?v2 default ?c)) ?k1 ?v1 default ?d ~~\n       T ?co3 (T ?co4 ?a ?k0 ?v0 default ?b) ?k2 ?v2 default (T ?co5 ?c ?k1 ?v1 default ?d)\n    =>  eapply Rb_equiv_trans with \n      (T Black (T Black (T co4 a k0 v0 default b) k2 v2 default c) k1 v1 default d)\n   | |-  T ?c0 ?a ?k0 ?v0 default (T ?c1 (T ?c2 ?b ?k1 ?v1 default ?c) ?k2 ?v2 default ?d) ~~\n       T ?c3 (T ?c4 ?a ?k0 ?v0 default ?b) ?k1 ?v1 default (T ?c5 ?c ?k2 ?v2 default ?d) \n       =>  eapply Rb_equiv_trans with \n          (T Black a k0 v0 default (T Black b k1 v1 default (T c5 c k2 v2 default d)))\n   | H1: SearchTree' ?lo ?a _ ,\n     H2: SearchTree' _ ?d ?hi\n    |- T ?co0 (T ?co1 ?a ?k0 ?v0 default ?b) ?k2 ?v2 default (T ?co2 ?c ?k1 ?v1 default ?d) ~~ \n    T ?co3 (T ?co4 (T ?co1 ?a ?k0 ?v0 default ?b) ?k2 ?v2 default ?c) ?k1 ?v1 default ?d\n     => eapply (ro_equiv _ (T co1 a k0 v0 default b) k2 v2 _ c k1 v1 d _ _ lo hi)\n   |H1: SearchTree' ?lo ?a _,\n    H2: SearchTree' _ ?d ?hi\n     |- T ?c0 ?a ?k0 ?v0 default (T ?c1 ?b ?k1 ?v1 default (T ?c2 ?c ?k2 ?v2 default ?d)) ~~\n        T ?c3 (T ?c4 ?a ?k0 ?v0 default ?b) ?k1 ?v1 default (T ?c2 ?c ?k2 ?v2 default ?d)\n      => eapply (ro_equiv _ a k0 v0 c1 b k1 v1 (T c2 c k2 v2 default d) _ _ lo hi) \n   | |- (T _ ?l ?k ?v ?t ?r) ~~ (T _ ?l ?k ?v ?t ?r) => eapply equiv_color\n   | |- (T _ ?l1 ?k ?v ?t ?r) ~~ (T _ ?l2 ?k ?v ?t ?r) => eapply equiv_left\n   | |- (T _ ?l ?k ?v ?t ?r1) ~~ (T _ ?l ?k ?v ?t ?r2) => eapply equiv_right\n   | |- T ?c1 (T Red ?r0_1 ?k3 ?v3 ?t2 ?r0_2) ?k1 ?v1 default\n        (T Red ?r ?k0 ?v0 ?t0 ?s ) ~~\n      T ?c2 (T Black ?r0_1 ?k3 ?v3 ?t2 ?r0_2) ?k1 ?v1 default\n        (T Black ?r ?k0 ?v0 ?t0 ?s)\n        => eapply Rb_equiv_trans with \n        (T c1 (T Red r0_1 k3 v3 t2 r0_2) k1 v1 default\n        (T Black r k0 v0 t0 s ) )\n   | |- SearchTree' _ (le_rotate_notag _ _ _ _ _ _ ) _ => simpl\n   | |- SearchTree' _ (T _ _ _ _ _ _ ) _ => stt 10\n   | H: ?P |- ?P => auto\n   end).\n   inversion H6;subst h1 b. auto.\n  Qed.\n  Lemma balance_relate :\n    forall  l s cts lo hi  h b , SearchTree_half lo l hi ->\n   SearchTree' lo s hi -> Forall P l -> \n      default_tag_tree s  ->\n    Abs (complete_tree l s) cts ->\n     (h, b) = balance' l s ->\n       Abs (complete_tree h b) cts.\n  Proof.\n   intros. revert s cts lo hi  H H0 H1 H2 H3 h b H4.\n   destruct l .\n   - intros. inversion H4. apply H3.\n   - revert h .\n     assert (\n     (forall (h h0: Half_tree) (s : RBtree) (cts : relate_map) (lo hi : Key),\n  SearchTree_half lo (h :: h0 :: l) hi ->\n  SearchTree' lo s hi ->\n  Forall P (h ::h0:: l) ->\n  default_tag_tree s ->\n  Abs (complete_tree (h :: h0 :: l) s) cts ->\n  forall (h1 : list Half_tree) (b : RBtree),\n  (h1, b) = balance' (h :: h0 :: l) s -> Abs (complete_tree h1 b) cts ) /\\ (\n  forall (h : Half_tree) (s : RBtree) (cts : relate_map) (lo hi : Key),\n  SearchTree_half lo (h :: l) hi ->\n  SearchTree' lo s hi ->\n  Forall P (h :: l) ->\n  default_tag_tree s ->\n  Abs (complete_tree (h :: l) s) cts ->\n  forall (h0 : list Half_tree) (b : RBtree),\n  (h0, b) = balance' (h :: l) s -> Abs (complete_tree h0 b) cts\n  )); [ | tauto].\n      induction l.\n      { split.\n          + intros.\n            destruct h. repeat destruct p. destruct h0. repeat destruct p.\n            destruct s.\n              inversion H2.\n            inversion H2. subst t1. inversion H0;subst.\n        \n            unfold balance' in H4.\n            repeat (match goal with\n            | H: _ = match ?c with\n                    | Red => _ | Black => _ end |- _ => destruct c\n            | H: _ = if ?x then _ else _ |- _ => destruct x\n            | H: _ = match ?r with\n                    | Empty => _ | T _ _ _ _ _ _ => _ end |- _ => destruct r\n            | H: snd (fst (_, _, _, _, ?t, _)) = default |- _ => simpl in H;subst t;clear H\n            | H: P (_, _, _, _, ?t, _) |- _ => inversion H;clear H\n            | H : Forall P ((_, _, _, _, ?t, _) :: _) |- _ => inversion H;subst;clear H\n            | H: SearchTree_half _ ((true, _, _, _, _, _) :: _) _ |- _ =>inversion H;subst;clear H\n            | H: SearchTree_half _ ((false, _, _, _, _, _) :: _) _ |- _ =>inversion H;subst;clear H\n            | H:  Abs (complete_tree ((_, _, _, _, _, _) ::  _ ) _ ) cts |- _ => simpl in H\n            | H: (?h1, ?b) = (_ , _ ) |- Abs (complete_tree ?h1 ?b) _ => inversion H;subst h1 b;simpl\n            |H: Abs (T _ ?a ?k ?v default (T _ ?b ?k1 ?v1 default ?c)) ?cts,\n              H1: SearchTree' ?lo ?a _,\n              H2: SearchTree' _ ?c ?hi\n                |- Abs (T _ (T _ ?a ?k ?v _ ?b) ?k1 ?v1 _ ?c) ?cts \n                    => eapply (le_ro_abs _ a k v _ b k1 v1 c _ _ lo hi);try eassumption \n            |H: Abs (T _  (T _ ?b ?k1 ?v1 default ?c) ?k ?v default ?a) ?cts,\n              H1: SearchTree' ?lo ?b _,\n              H2: SearchTree' _ ?a ?hi\n                |- Abs (T _ ?b ?k1 ?v1 _ (T _ ?c ?k ?v _ ?a)) ?cts \n                    => eapply (ri_ro_abs _ a k v _ b k1 v1 c _ _ lo hi);try eassumption\n            | H: (_, _) = (_, ri_rotate_notag ?co1 (le_rotate_notag ?cc ?ll ?kk ?vv ?tt (makeBlack (T _ ?rr ?k1 ?v1 _ ?c))) ?k ?v default ?a),\n             H1: SearchTree' ?lo ?ll _ ,\n             H2: SearchTree' _ ?a ?hi \n             |- _ => eapply (ri_ro_abs Black a k v Black (T cc ll kk vv tt rr) k1 v1 c co1 _ lo hi);try eassumption\n            | H : _ = ( _, le_rotate_notag ?co1 ?a ?k ?v default \n                (ri_rotate_notag ?cc (makeBlack (T _ ?b ?k1 ?v1 _ ?ll)) ?kk ?vv ?tt ?rr)),\n             H1: SearchTree' ?lo ?a _,\n             H2: SearchTree' _ ?rr ?hi |- _ \n           => eapply (le_ro_abs Black a k v Black b k1 v1 (T cc ll kk vv tt rr) co1 _ lo hi);try eassumption\n            | H: Abs (T _ _ ?k ?v ?t _ ) ?cts |- Abs (T _ _ ?k ?v ?t _ ) ?cts => inversion H;subst;eapply Abs_T\n            | |- SearchTree' _ (T _ _ _ _ _ _ ) _ => stt 5\n            end; try eassumption).\n          + intros. destruct h. repeat destruct p.\n            inversion H4. subst.\n            auto.\n         }\n        { split.\n          + intros. destruct IHl.\n            eapply balance_induction_pre ; try eassumption.\n          +\n          destruct IHl. intros. eapply H. apply H1. apply H2. apply H3. apply H4. apply H5. auto.\n         }\n  Qed.\nTheorem insert_relate_aux:\n forall k v t cts l s h b,\n  SearchTree t ->  Abs t cts ->\n    (l , s) = insert' k v t  -> (h, b) = balance' l s ->\n    Abs (complete_tree h b) (v_update k v cts ).\nProof.\n  intros.\n  unfold insert' in H1.\n  remember (insert_split k default t nil).\n  destruct p.\n  inversion H. subst.\n  pose proof (Archmedes_l (min_k lo k) ).\n  pose proof (Archmedes_R (max_k hi k) ).\n  destruct H4. destruct H5.\n  assert ( (k <? x0) = true /\\ (x <? k) = true ).\n  { split. \n    pose proof max_right hi k.\n    eapply ltb_lt. tr.\n    pose proof min_right lo k.\n    eapply ltb_lt. tr. }\n  assert ( SearchTree' x t x0).\n  { eapply search_popro2_lte.  eapply search_popro3_lte; try eassumption.\n    pose proof min_left lo k. tr.\n    pose proof max_left hi k. tr. }\n  assert (SearchTree_half x nil x0 ).\n  { eapply ST_nil.  destruct H6.  TR 5. }\n  clear H3 H4 H5.\n  pose proof insert_st_pre x x0 t nil k  default l0 r H7 H8 H6 Heqp. destruct H3. destruct H3. super_destruct H3.\n  assert (Forall P l0).\n  { eapply (insert_split_tag_default x x0 t nil k default l0 r); try eassumption. apply Forall_nil. }\n   inversion H1. subst.\n  assert (default_tag_tree (insert_root k v r)).\n  { pose proof insert_split_tag_default_tree _ _ _ _ _ _ _ _ H7 H8 Heqp.\n    unfold default_tag_tree in H11.\n    destruct r.\n    - inversion H11. inversion H12.\n      reflexivity.\n    - inversion H11.\n      simpl. auto.\n       inversion H12.\n    }\n  eapply (balance_relate l0 (insert_root k v r))  ; try eassumption.\n  eapply insert_root_st; try eassumption. tauto.\n  eapply insert_complete_relate; try eassumption.\n  reflexivity.\nQed.\nTheorem insert_relate: forall t k v cts finaltree,\n  SearchTree t -> Abs t cts ->\n  insert k v t finaltree -> Abs finaltree (v_update k v cts).\nProof.\n  intros.\n  inversion H1.\n  super_destruct H3.\n  - pose proof insert_relate_aux k v t cts l s h b H H0 H2 H5.\n    eapply makeBlack_abs; auto.\n  - \n    unfold insert' in H2.\n    remember (insert_split k default t nil) as in_s;destruct in_s.\n    eapply makeBlack_abs.\n    inversion H5;subst.\n    inversion H2.\n    pose proof insert_complete_relate k v t cts l0 r s H H0 Heqin_s H7.\n    subst. auto.\nQed.\n(*INSERT REDBLACK*)\n  Theorem insert_rb_pre_aux :\n    forall s l k v t h b , is_redblack_color s Black -> is_redblack_color_half l Black ->\n     (Red_tree s /\\ fst_black' l \\/ Black_tree s \\/ (s = Empty /\\ ~ l =nil)) ->\n     (h , b) = insert_split k t s l ->( is_redblack_color (insert_root k v b) Black /\\ is_redblack_color_half h Black ).\n  Proof.\n    intros.\n    assert (( is_redblack_color b Black /\\ is_redblack_color_half h Black ) /\\\n        (Red_tree b /\\ fst_black' h \\/ Black_tree b \\/ (b = Empty /\\ ~ h =nil))).\n   { eapply general_split_RB_co; try eassumption.\n     eapply insert_lb_rb. }\n   destruct H3.\n   destruct H3.\n   split. 2: auto.\n   inversion H3.\n   - simpl. eapply IsRB_co_r.\n     apply IsRB_co_leaf.\n     apply IsRB_co_leaf.\n   - subst.\n     eapply IsRB_co_r;  try eassumption.\n   - subst.\n     simpl.\n     eapply IsRB_co_b;  try eassumption.\n  Qed.\n\n  Theorem insert_rb_pre :\n    forall s l k v t h b, ~ ( s = Empty /\\ l = nil) ->\n    is_redblack_color (complete_tree l s) Red ->\n     (h , b) = insert_split k t s l ->( is_redblack_color (insert_root k v b) Black /\\ is_redblack_color_half h Black ).\n  Proof.\n    intros.\n    assert (\n    is_redblack_color s Black /\\ is_redblack_color_half l Black /\\\n     (Red_tree s /\\ fst_black' l \\/ Black_tree s \\/ (s = Empty /\\ ~ l =nil))\n    ).\n    {\n     destruct l.\n     - simpl in H0. split. eapply isr_isb; try eassumption. split. apply IsRB_co_nil. right.\n       inversion H0. subst. exfalso; auto. subst.  left. reflexivity.\n     - assert (~ (h0 :: l)= nil). { discriminate. }\n       pose proof (complete_rb_rev _ _ H2 H0). destruct H3 as [ H3 [ H4 H5]].\n       split. auto. split. auto. destruct H5.\n       left. unfold fst_black'. tauto.\n       destruct s. right. right. split. reflexivity.  discriminate.\n       destruct c. exfalso. apply H5. reflexivity. right. left. reflexivity.\n    }\n    destruct H2. destruct H3.\n    eapply insert_rb_pre_aux; try eassumption.\n  Qed.\n\n  Theorem insert_rb_next:\n    forall    l s h b,  is_redblack_color_half l Black   ->\n    is_redblack_color s Black -> ~ s = Empty  ->\n    (  ( Red_tree s /\\ (h, b) = balance' l s) \\/\n           (Black_tree s /\\ ( h,b) = (l ,s))  )\n     -> is_redblack_color (makeBlack(complete_tree h b)) Red.\n  Proof.\n    intro.\n    assert (\n    (forall (s : RBtree) (h : list Half_tree) (b : RBtree),\n  is_redblack_color_half l Black ->\n  is_redblack_color s Black ->\n  s <> Empty ->\n  Red_tree s /\\ (h, b) = balance' l s \\/ Black_tree s /\\ (h, b) = (l, s) ->\n  is_redblack_color (makeBlack (complete_tree h b)) Red)\n    /\\\n    (forall (s : RBtree)(a: Half_tree) (h : list Half_tree) (b : RBtree),\n  is_redblack_color_half (a::l) Black ->\n  is_redblack_color s Black ->\n  s <> Empty ->\n  Red_tree s /\\ (h, b) = balance' (a::l) s \\/ Black_tree s /\\ (h, b) = ((a::l), s) ->\n  is_redblack_color (makeBlack (complete_tree h b)) Red\n    )); [ | tauto].\n    induction l.\n    {\n     split.\n     + intros. inversion H2.\n       { inversion H3.\n       subst. simpl. \n       destruct s.\n       - exfalso. auto.\n       - simpl. inversion H5. inversion H0.\n         * subst. pose proof isr_isb _ H10. pose proof isr_isb _ H15.\n            eapply IsRB_co_b; try eassumption.\n         * subst. eapply IsRB_co_b; try eassumption. }\n       { inversion H3. inversion H5. simpl.\n         destruct s. exfalso . auto.\n         simpl. inversion H0. subst. eapply IsRB_co_b; try eassumption.\n         eapply isr_isb; try eassumption.\n         eapply isr_isb; try eassumption.\n         subst. eapply IsRB_co_b; try eassumption.\n         }\n     + intros. destruct a. repeat destruct p.\n       destruct s. exfalso ;auto.\n       destruct c0.\n       { unfold Red_tree, Black_tree in H2. destruct H2. destruct H2. 2: exfalso; destruct H2; inversion H2. inversion H3. subst.\n         inversion H.\n        - subst. destruct b0.\n         * simpl. eapply IsRB_co_b; try eassumption. eapply isr_isb; try eassumption.\n         * simpl. eapply IsRB_co_b; try eassumption. eapply isr_isb; try eassumption.\n        - subst. destruct b0.\n         * simpl. eapply IsRB_co_b; try eassumption.\n         * simpl. eapply IsRB_co_b; try eassumption. }\n       {\n         unfold Red_tree, Black_tree in H2. destruct H2. destruct H2. exfalso; inversion H2. destruct H2. inversion H3. subst. inversion H0. subst.\n         inversion H.\n         - subst.\n         destruct b0.\n         * simpl. eapply IsRB_co_b; try eassumption. eapply isr_isb; try eassumption.\n         * simpl. eapply IsRB_co_b; try eassumption. eapply isr_isb; try eassumption.\n         - subst. destruct b0.\n         * simpl. eapply IsRB_co_b; try eassumption.\n         * simpl. eapply IsRB_co_b; try eassumption.\n       }\n    }\n    {\n     split.\n     + destruct IHl. eauto.\n     + intros.\n       destruct s.\n       exfalso; auto.\n       destruct c.\n       {\n        destruct H2. 2: destruct H2; exfalso; inversion H2.\n        destruct IHl. clear H4.\n        destruct a0. repeat destruct p. destruct a. repeat destruct p.\n        destruct c.\n        { (*父节点红*)\n          destruct b0.\n          - (* true 右子*)\n            inversion H. subst. inversion H6. subst.\n            destruct r0.\n            { (* uncle Empty*)\n              destruct b1.\n              * (*父黑祖红，祖左旋*)\n                destruct H2.\n                inversion H4. subst.\n                assert (is_redblack_color (T Black (T Red Empty k1 v1 t1 r) k0 v0 t0 (T Red s1 k v t s2)) Black ).\n                {\n                eapply IsRB_co_b; try eassumption.\n                eapply IsRB_co_r; try eassumption.\n                apply IsRB_co_leaf.\n                }\n                apply complete_redblack_co. auto.\n                unfold not; intros. inversion H7.\n                auto. right. reflexivity.\n              * (*父左旋，我黑，祖红，祖右旋*)\n                destruct H2.\n                inversion H4. subst.\n                assert ( is_redblack_color (T Black (T Red r k0 v0 t0 s1) k v t (T Red s2 k1 v1 t1 Empty)) Black\n             ).\n                {\n                 inversion H0.\n                 subst.\n                 eapply IsRB_co_b;try eassumption.\n                 eapply IsRB_co_r; try eassumption.\n                 eapply IsRB_co_r; try eassumption. apply IsRB_co_leaf.\n                }\n                apply complete_redblack_co. auto.\n                unfold not; intros. inversion H7.  auto.\n                right. reflexivity.           }\n             {\n              destruct H2.\n              destruct c.\n              + (**uncle 红*)\n                inversion H15. subst.\n                destruct b1.\n                * inversion H4. eapply H3 with (T Red (T Black r0_1 k2 v2 t2 r0_2) k1 v1 t1\n            (T Black r k0 v0 t0 (T Red s1 k v t s2))).\n                  auto. eapply IsRB_co_r; try eassumption.\n                  eapply IsRB_co_b; try eassumption. eapply isr_isb; try eassumption. eapply isr_isb; try eassumption.\n                  eapply IsRB_co_b; try eassumption. eapply isr_isb; try eassumption.\n                  unfold not; intro  m; inversion m.\n                  left. split. reflexivity.  auto.\n                * inversion H4. eapply H3 with (T Red (T Black r k0 v0 t0 (T Red s1 k v t s2)) k1 v1 t1\n            (T Black r0_1 k2 v2 t2 r0_2)).\n                  auto. eapply IsRB_co_r; try eassumption.\n                  eapply IsRB_co_b; try eassumption. eapply isr_isb; try eassumption.\n                  eapply IsRB_co_b; try eassumption. eapply isr_isb; try eassumption.  eapply isr_isb; try eassumption.\n                  unfold not; intro  m; inversion m.\n                  left. split. reflexivity.  auto.\n              +  (*uncle 黑*)\n                 inversion H15. subst.\n                 destruct b1.\n                 * (*父黑祖红，祖左旋*)\n                   inversion H4. subst.\n                   assert (is_redblack_color (T Black (T Red (T Black r0_1 k2 v2 t2 r0_2) k1 v1 t1 r) k0 v0 t0\n             (T Red s1 k v t s2)) Black ).\n                   {\n                   eapply IsRB_co_b; try eassumption.\n                   eapply IsRB_co_r; try eassumption.\n                   eapply IsRB_co_b; try eassumption.\n                   }\n                   apply complete_redblack_co. auto.\n                   unfold not; intros. inversion H7.\n                   auto. right. reflexivity.\n                 * (*父左旋，我黑，祖红，祖右旋*)\n                   inversion H4. subst.\n                   assert ( is_redblack_color (T Black (T Red r k0 v0 t0 s1) k v t\n             (T Red s2 k1 v1 t1 (T Black r0_1 k2 v2 t2 r0_2))) Black\n             ).\n                   {\n                    inversion H0.\n                    subst.\n                    eapply IsRB_co_b;try eassumption.\n                    eapply IsRB_co_r; try eassumption.\n                    eapply IsRB_co_r; try eassumption.\n                    eapply IsRB_co_b;try eassumption.\n                   }\n                   apply complete_redblack_co. auto.\n                   unfold not; intros. inversion H7.  auto.\n                   right. reflexivity.           }\n          - (*false 左子*)\n            inversion H. subst. inversion H6. subst.\n            destruct r0.\n            { (* uncle Empty*)\n              destruct b1.\n              * (*父右旋，我黑，祖红，祖左旋*)\n                destruct H2.\n                inversion H4. subst.\n                assert ( is_redblack_color (T Black (T Red Empty k1 v1 t1 s1) k v t (T Red s2 k0 v0 t0 r)) Black\n             ).\n                {\n                 inversion H0.\n                 subst.\n                 eapply IsRB_co_b;try eassumption.\n                 eapply IsRB_co_r; try eassumption.\n                 apply IsRB_co_leaf.\n                 eapply IsRB_co_r; try eassumption. \n                }\n                apply complete_redblack_co. auto.\n                unfold not; intros. inversion H7.  auto.\n                right. reflexivity.\n              * (*父黑祖红，祖右旋*)\n                destruct H2.\n                inversion H4. subst.\n                assert (is_redblack_color (T Black (T Red s1 k v t s2) k0 v0 t0 (T Red r k1 v1 t1 Empty)) Black ).\n                {\n                eapply IsRB_co_b; try eassumption.\n                eapply IsRB_co_r; try eassumption.\n                apply IsRB_co_leaf.\n                }\n                apply complete_redblack_co. auto.\n                unfold not; intros. inversion H7.\n                auto. right. reflexivity.\n             }\n             {\n              destruct H2.\n              destruct c.\n              + (**uncle 红*)\n                inversion H15. subst.\n                destruct b1.\n                * inversion H4. eapply H3 with (T Red (T Black r0_1 k2 v2 t2 r0_2) k1 v1 t1\n            (T Black (T Red s1 k v t s2) k0 v0 t0 r)).\n                  auto. eapply IsRB_co_r; try eassumption.\n                  eapply IsRB_co_b; try eassumption. eapply isr_isb; try eassumption. eapply isr_isb; try eassumption.\n                  eapply IsRB_co_b; try eassumption. eapply isr_isb; try eassumption.\n                  unfold not; intro  m; inversion m.\n                  left. split. reflexivity.  auto.\n                * inversion H4. eapply H3 with (T Red (T Black (T Red s1 k v t s2) k0 v0 t0 r) k1 v1 t1\n            (T Black r0_1 k2 v2 t2 r0_2)).\n                  auto. eapply IsRB_co_r; try eassumption.\n                  eapply IsRB_co_b; try eassumption. eapply isr_isb; try eassumption.\n                  eapply IsRB_co_b; try eassumption. eapply isr_isb; try eassumption.  eapply isr_isb; try eassumption.\n                  unfold not; intro  m; inversion m.\n                  left. split. reflexivity.  auto.\n              +  (*uncle 黑*)\n                 inversion H15. subst.\n                 destruct b1.\n                 * (*父右旋，我黑，祖红，祖左旋*)\n                   inversion H4. subst.\n                   assert ( is_redblack_color (T Black (T Red (T Black r0_1 k2 v2 t2 r0_2) k1 v1 t1 s1) k v\n             t (T Red s2 k0 v0 t0 r)) Black\n             ).\n                   {\n                    inversion H0.\n                    subst.\n                    eapply IsRB_co_b;try eassumption.\n                    eapply IsRB_co_r; try eassumption.\n                    eapply IsRB_co_b; try eassumption.\n                    eapply IsRB_co_r;try eassumption.\n                   }\n                   apply complete_redblack_co. auto.\n                   unfold not; intros. inversion H7.  auto.\n                   right. reflexivity.\n                 * (*父黑祖红，祖右旋*)\n                   inversion H4. subst.\n                   assert (is_redblack_color  (T Black (T Red s1 k v t s2) k0 v0 t0\n             (T Red r k1 v1 t1 (T Black r0_1 k2 v2 t2 r0_2))) Black ).\n                   {\n                   eapply IsRB_co_b; try eassumption.\n                   eapply IsRB_co_r; try eassumption.\n                   eapply IsRB_co_b; try eassumption.\n                   }\n                   apply complete_redblack_co. auto.\n                   unfold not; intros. inversion H7.\n                   auto. right. reflexivity.\n  }\n      }\n      { (*父节点黑*)\n        destruct H2.\n        inversion H4. subst.\n        apply complete_redblack_co.\n        auto. unfold not; intro m; inversion m.\n        auto. left. split. reflexivity. reflexivity.\n      }\n    }\n    {\n     destruct H2.\n     exfalso. destruct H2. inversion H2.\n     destruct H2. inversion H3.\n     apply complete_redblack_co.\n     auto. unfold not; intro m; inversion m.\n     auto. right. reflexivity.\n    }\n   }\n  Qed.\n  Theorem insert_is_redblack_co_aux:\n    forall k v t  l s h b, is_redblack_color t Red  ->\n       (l , s) = insert' k v t  ->(\n         ( Red_tree s /\\ (h, b) = balance' l s)\\/ \n           (Black_tree s /\\ ( h,b) = (l ,s))  )  ->\n                       is_redblack_color (makeBlack(complete_tree h b)) Red.\n  Proof.\n   unfold insert'. intros.\n   remember (insert_split k default t nil).\n   destruct p.\n   inversion H0. subst.\n   destruct t.\n   - inversion Heqp. subst. destruct H1 as [ [ H1 H2] | [H1 H2]].\n     inversion H2. subst. simpl . apply IsRB_co_b. apply IsRB_co_leaf. apply IsRB_co_leaf.\n     inversion H1.\n   -\n     assert (\n     ( is_redblack_color (insert_root k v r) Black /\\ is_redblack_color_half l0 Black )\n     ).\n     {\n     eapply insert_rb_pre; try eassumption. unfold not;intro.  inversion H2. inversion H3.\n     simpl. auto.\n     }\n     assert (~ (insert_root k v r) = Empty).\n     {\n      destruct r. discriminate. discriminate.\n     }\n     destruct H2.\n     apply (insert_rb_next l0 (insert_root k v r)); try eassumption.\n  Qed.\n\n  Theorem insert_dep_pre :\n    forall s l k v t h b n depth,\n    is_redblack_dep s n -> is_redblack_dep_half l depth n ->\n     (h , b) = insert_split k  t s l -> (exists n' d',  is_redblack_dep (insert_root k v  b) n' /\\\n     is_redblack_dep_half h d' n' ).\n  Proof.\n    intros.\n    assert ( exists n' d',  is_redblack_dep b n' /\\\n     is_redblack_dep_half h d' n').\n    { eapply general_split_RB_dep; try eassumption.\n      eapply insert_lb_rb. }\n      destruct H2.\n      destruct H2.\n      destruct H2.\n      exists x. exists x0.\n      split. 2: auto.\n      destruct b.\n      - simpl.\n        inversion H2.\n        subst.\n        apply IsRB_dep_r; try eassumption.\n      - simpl.\n        inversion H2.\n        + subst. eapply IsRB_dep_r ; try eassumption.\n        + subst. eapply IsRB_dep_b ; try eassumption.\n  Qed.\n\n  Theorem insert_dep_next:\n    forall    l s h b n depth,   ~ s = Empty  ->\n    is_redblack_dep s n -> is_redblack_dep_half l depth n -> is_redblack_color_half l Black ->\n    (  ( Red_tree s /\\ (h, b) = balance' l s) \\/\n           (Black_tree s /\\ ( h,b) = (l ,s))  )\n     ->  (exists n' d',  is_redblack_dep b n' /\\ is_redblack_dep_half h d' n' ).\n  Proof.\n    intro.\n    assert (\n  (forall (s : RBtree) (h : list Half_tree) (b : RBtree) (n depth : nat),\n  s <> Empty ->\n  is_redblack_dep s n ->\n  is_redblack_dep_half l depth n ->\n  is_redblack_color_half l Black ->\n  Red_tree s /\\ (h, b) = balance' l s \\/ Black_tree s /\\ (h, b) = (l, s) ->\n  exists n' d' : nat, is_redblack_dep b n' /\\ is_redblack_dep_half h d' n') /\\ \n  (forall (s : RBtree) (h : list Half_tree) (b : RBtree) (n depth : nat)(a: Half_tree),\n  s <> Empty ->\n  is_redblack_dep s n ->\n  is_redblack_dep_half (a::l) depth n ->\n  is_redblack_color_half (a::l) Black ->\n  Red_tree s /\\ (h, b) = balance' (a::l) s \\/ Black_tree s /\\ (h, b) = (a::l, s) ->\n  exists n' d' : nat, is_redblack_dep b n' /\\ is_redblack_dep_half h d' n'\n  )\n    );[ | tauto].\n    induction l.\n    - split.\n      + intros. inversion H1. subst.  exists n. exists n.\n        destruct H3 as [[H4 H3] | [H4 H3]].\n        inversion H3. subst. tauto.\n        inversion H3. tauto.\n      + intros. destruct a. repeat destruct p.\n        assert ( (h, b) = ((b0, c, k, v, t, r) :: nil, s) ).\n        {\n         unfold balance' in H3.  tauto. } clear H3. inversion H4. subst.\n        exists n. exists depth.\n        tauto.\n    - split.\n      { destruct IHl. intros. apply (H0 s h b n depth  a); try eassumption.\n      }\n\n      {\n      intros. destruct IHl. clear H5.\n      destruct s. exfalso. auto.\n      destruct c.\n      {\n      destruct H3 as [[H3 H5]|[H3 H5]];[ | exfalso; inversion H3].\n      destruct a0. repeat destruct p. destruct a. repeat destruct p.\n      destruct c.\n      +  (*父亲为红色*)\n       inversion H1. subst.\n       destruct b0.\n       { (*右子*)\n         destruct r0.\n         { (*uncle Empty*)\n           destruct b1.\n           * (*父黑祖红，祖左旋*)\n             inversion H5. subst.\n             destruct c0.\n             + inversion H2. inversion H8.\n             + inversion H14. subst. exists (S n). exists depth. split ; [| tauto].\n               inversion H0.\n               apply IsRB_dep_b. eapply IsRB_dep_r; try eassumption.\n               eapply IsRB_dep_r; try eassumption.\n           * (*父左旋，我黑，祖红，祖右旋*)\n            destruct c0.  inversion H2; inversion H8.\n            inversion H5. subst. inversion H14. subst.\n            exists (S n). exists depth. split ; [| tauto].\n            inversion H0.\n            apply IsRB_dep_b. eapply IsRB_dep_r; try eassumption.\n            eapply IsRB_dep_r; try eassumption.\n         }\n         destruct c.\n         { (*Uncle Red*)\n           destruct c0. inversion H2. inversion H8.\n           inversion H0. subst. \n           inversion H14. subst. inversion H19. subst.\n           destruct b1.\n           * simpl in H5.\n             assert ((T Red (T Black r0_1 k2 v2 t2 r0_2) k1 v1 t1\n            (T Black r k0 v0 t0 (T Red s1 k v t s2)))<> Empty ). {discriminate. }\n             eapply H4. apply H6. 2: apply H18. apply IsRB_dep_r. eapply IsRB_dep_b; try eassumption. eapply IsRB_dep_b; try eassumption. inversion H2. subst. inversion H9. subst. auto.\n             left. split;[ reflexivity| auto].\n           * simpl in H5.\n             assert ((T Red (T Black r k0 v0 t0 (T Red s1 k v t s2)) k1 v1 t1\n            (T Black r0_1 k2 v2 t2 r0_2))<> Empty ). { discriminate. }\n             eapply H4. apply H6. 2: apply H18. apply IsRB_dep_r. eapply IsRB_dep_b; try eassumption. eapply IsRB_dep_b; try eassumption. inversion H2. subst. inversion H9. subst. auto.\n             left. split;[ reflexivity| auto].\n         }\n         { (*Uncle Black*)\n           destruct c0. inversion H2. inversion H8.\n           inversion H14. subst. exists (S n). exists depth.\n           inversion H0. subst.\n           destruct b1.\n           * simpl in H5. inversion H5. split;[| tauto].\n             apply IsRB_dep_b. eapply IsRB_dep_r; try eassumption.\n            eapply IsRB_dep_r; try eassumption.\n           * simpl in H5. inversion H5. split;[| tauto].\n             apply IsRB_dep_b. eapply IsRB_dep_r; try eassumption.\n            eapply IsRB_dep_r; try eassumption.\n         }\n       }\n       { (*左子*)\n         inversion H0. subst.\n         destruct r0.\n         { (*uncle Empty*)\n           destruct c0; [inversion H2; inversion H8 | ].\n           inversion H14. subst.\n           exists (S n). exists depth.\n           destruct b1.\n           * simpl in H5. inversion H5. split;[| tauto].\n             apply IsRB_dep_b. eapply IsRB_dep_r; try eassumption.\n            eapply IsRB_dep_r; try eassumption.\n           * simpl in H5. inversion H5. split;[| tauto].\n             apply IsRB_dep_b. eapply IsRB_dep_r; try eassumption.\n            eapply IsRB_dep_r; try eassumption.\n         }\n         destruct c0; [inversion H2; inversion H8 | ].\n         inversion H14. subst.\n         destruct c.\n         { inversion H19. subst.\n           destruct b1.\n           * simpl in H5.\n             assert ((T Red (T Black r0_1 k2 v2 t2 r0_2) k1 v1 t1\n            (T Black (T Red s1 k v t s2) k0 v0 t0 r))<> Empty ). { discriminate. }\n             eapply H4. apply H6. 2: apply H18. apply IsRB_dep_r. eapply IsRB_dep_b; try eassumption. eapply IsRB_dep_b; try eassumption. inversion H2. subst. inversion H9. subst. auto.\n             left. split;[ reflexivity| auto].\n           * simpl in H5.\n             assert ( (T Red (T Black (T Red s1 k v t s2) k0 v0 t0 r) k1 v1 t1\n            (T Black r0_1 k2 v2 t2 r0_2))<> Empty ). { discriminate.  }\n             eapply H4. apply H6. 2: apply H18. apply IsRB_dep_r. eapply IsRB_dep_b; try eassumption. eapply IsRB_dep_b; try eassumption. inversion H2. subst. inversion H9. subst. auto.\n             left. split;[ reflexivity| auto].\n         }\n         { inversion H19;subst.\n           inversion H14 ; subst.\n           exists (S (S n0)). exists depth.\n           destruct b1.\n           * simpl in H5. inversion H5. split;[| tauto].\n             apply IsRB_dep_b. eapply IsRB_dep_r; try eassumption.\n            eapply IsRB_dep_r; try eassumption.\n           * simpl in H5. inversion H5. split;[| tauto].\n             apply IsRB_dep_b. eapply IsRB_dep_r; try eassumption.\n            eapply IsRB_dep_r; try eassumption.\n         }\n       }\n      + (*父亲为黑色*)\n        simpl in H3. inversion H5.\n        exists n. exists depth.\n        tauto.\n      }\n      { destruct H3 as [[H3 H5 ]|[H3 H5] ];[ inversion H3 | ].\n        inversion H5. subst. exists n. exists depth. tauto.\n      }\n      }\n  Qed.\n  Theorem insert_dep_final:\n   forall   l s  n depth,\n    is_redblack_dep s n -> is_redblack_dep_half l depth n -> is_redblack_dep (complete_tree l s) depth.\n  Proof.\n    intro.\n    induction l.\n    - intros. inversion H0. subst. simpl. auto.\n    - intros. destruct a. repeat destruct p.\n      inversion H0.\n      + subst. destruct b. simpl.\n        eapply IHl; try eassumption. eapply IsRB_dep_r; try eassumption.\n        simpl.\n        eapply IHl; try eassumption. eapply IsRB_dep_r; try eassumption.\n      + subst. destruct b. simpl.\n        eapply IHl; try eassumption. eapply IsRB_dep_b; try eassumption.\n        simpl.\n        eapply IHl; try eassumption. eapply IsRB_dep_b; try eassumption.\n  Qed.\nTheorem insert_is_redblack_co:\n  forall k v t  l s h b, is_redblack t  ->\n     (l , s) = insert' k v t  ->(\n       ( Red_tree s /\\ (h, b) = balance' l s)\\/ \n         (Black_tree s /\\ ( h,b) = (l ,s))  )  ->\n                     is_redblack_color (makeBlack(complete_tree h b)) Red.\nProof.\n  intros.\n  destruct H.\n  eapply insert_is_redblack_co_aux; try eassumption.\nQed.\nTheorem insert_is_redblack_dep:\n  forall k v t l s h b , is_redblack t ->\n    (l ,s ) = insert' k v t ->(\n       ( Red_tree s /\\ (h, b) = balance' l s)\\/ \n         (Black_tree s /\\ ( h,b) = (l ,s))  ) ->\n        (exists n',  is_redblack_dep (makeBlack(complete_tree h b)) n').\nProof.\n unfold insert'. intros.\n inversion H. clear H.\n remember (insert_split k default t nil).\n destruct p.\n destruct H3.\n inversion H0. subst.\n destruct t.\n - inversion Heqp. subst. destruct H1 as [ [ H1 H3] | [H1 H3]].\n   inversion H3. subst. simpl . exists 1. apply IsRB_dep_b. apply IsRB_dep_em. apply IsRB_dep_em.\n   exfalso. inversion H1.\n - assert (is_redblack_dep_half nil x x). { apply IsRB_dep_nil. }\n   pose proof (insert_dep_pre _ _ _ v _ _ _ _ _ H H3 Heqp).\n   destruct H4. destruct H4. destruct H4.\n   assert (~ (insert_root k v r)= Empty).\n   { destruct r.\n     - discriminate.\n     - discriminate.\n    }\n   assert (\n   ( is_redblack_color (insert_root k v r) Black /\\ is_redblack_color_half l0 Black )\n   ).\n   {\n   eapply insert_rb_pre ; try eassumption.  unfold not;intro. inversion H7. inversion H8.\n   simpl. auto.\n   }\n   destruct H7.\n   pose proof (insert_dep_next _ _ _ _ _ _ H6 H4 H5 H8 H1).\n   destruct H9. destruct H9. destruct H9.\n   pose proof (insert_dep_final _ _ _ _ H9 H10).\n   eapply isrb_dep_makeBlack; try eassumption.\nQed.\nTheorem insert_redblack : forall k v t finaltree, is_redblack t -> insert k v t finaltree -> is_redblack finaltree.\nProof.\n  intros. Print insert.\n  inversion H0. subst.\n  split.\n  eapply insert_is_redblack_co; try eassumption.\n  eapply insert_is_redblack_dep; try eassumption.\nQed.\n\nEnd Section_Insert.\nSearch Abs insert.\nPrint is_redblack.\nLocate relate_map.\nLocate is_redblack_color.\nSearch insert_split SearchTree'.\nLocate SearchTree_half.", "meta": {"author": "maoliyuan", "repo": "avltree-verification", "sha": "1258e9bd5fa7d849ba8b387978bca41d56c64c9a", "save_path": "github-repos/coq/maoliyuan-avltree-verification", "path": "github-repos/coq/maoliyuan-avltree-verification/avltree-verification-1258e9bd5fa7d849ba8b387978bca41d56c64c9a/Verif/Insert.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.2907192949685471}}
{"text": "From DeepWeb Require Import\n     Switch2.\nExport\n  SumNotations.\nOpen Scope sum_scope.\n\nCoFixpoint compose' {E T} `{Is__sE E}\n           (bfi bfo : list packetT)\n           (net : itree sE T)\n           (app : itree netE T) : itree E T :=\n  match observe net, observe app with\n  | RetF r, _\n  | _, RetF r => Ret r\n  | TauF net', _ => Tau (compose' bfi bfo net' app)\n  | _, TauF app' => Tau (compose' bfi bfo net  app')\n  | VisF vn kn, VisF va ka =>\n    let step__net :=\n        match vn with\n        | (ne|) =>\n          match ne in nondetE Y return (Y -> _) -> _ with\n          | Or =>\n            fun k =>\n              b <- trigger Or;;\n              Tau (compose' bfi bfo (k b) app)\n          end kn\n        | (|le|) =>\n          match le in logE Y return (Y -> _) -> _ with\n          | Log str =>\n            fun k =>\n              embed Log (\"Switch: \" ++ str)%string;;\n              Tau (compose' bfi bfo (k tt) app)\n          end kn\n        | (||se) =>\n          match se in switchE Y return (Y -> _) -> _ with\n          | Switch__In =>\n            fun k =>\n              match bfo with\n              | [] =>\n                pkt <- trigger Switch__In;;\n                Tau (compose' bfi [] (k pkt) app)\n              | pkt :: bo' =>\n                Tau (compose' bfi bo' (k pkt) app)\n              end\n          | Switch__Out pkt =>\n            fun k =>\n              if conn_is_app (packet__dst pkt)\n              then Tau (compose' (bfi ++ [pkt]) bfo (k tt) app)\n              else\n                embed Switch__Out pkt;;\n                Tau (compose' bfi bfo (k tt) app)\n          end kn\n        end in\n    let step__app :=\n        match va in netE Y return (Y -> _) -> _ with\n        | Net__Select =>\n          fun k =>\n            let cs : list connT := map packet__src bfi in\n            match cs with\n            | [] => step__net\n            | _ :: _ => Tau (compose' bfi bfo net (k cs))\n            end\n        | Net__Recv c =>\n          fun k =>\n            match pick (Nat.eqb c ∘ packet__src) bfi with\n            | Some (pkt, bi') =>\n              Tau (compose' bi' bfo net (k pkt))\n            | None =>\n              step__net\n            end\n        | Net__Send pkt =>\n          fun k => Tau (compose' bfi (bfo ++ [pkt]) net (k tt))\n        end ka in\n    step__app\n  end.\n\nDefinition compose_switch {E T} `{Is__sE E}\n  : itree sE T -> itree netE T -> itree E T := compose' [] [].\n", "meta": {"author": "liyishuai", "repo": "DeepWebTest", "sha": "1f026df620ccf658a683a1b927b90fc6b2703afd", "save_path": "github-repos/coq/liyishuai-DeepWebTest", "path": "github-repos/coq/liyishuai-DeepWebTest/DeepWebTest-1f026df620ccf658a683a1b927b90fc6b2703afd/echo/Compose2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.2907192880405231}}
{"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 Import Coq.ZArith.BinInt.\nLocal Open Scope Z.\nRequire Import Utility.\nLocal Open Scope alu_scope.\n\n(* Converted imports: *)\n\nRequire Decode.\nRequire Import Monads.\nRequire Import Program.\nRequire Import Utility.\n\n(* No type declarations to convert. *)\n(* Converted value declarations: *)\n\nDefinition execute {p} {t} `{(RiscvState p t)}\n   : Decode.InstructionM64 -> p unit :=\n  fun arg_0__ =>\n    match arg_0__ with\n    | Decode.Mulw rd rs1 rs2 =>\n        Bind (getRegister rs1) (fun x =>\n                Bind (getRegister rs2) (fun y => setRegister rd (s32 (x * y))))\n    | Decode.Divw rd rs1 rs2 =>\n        Bind (getRegister rs1) (fun x =>\n                Bind (getRegister rs2) (fun y =>\n                        let q :=\n                          if andb (reg_eqb x minSigned) (reg_eqb y (negate (ZToReg 1))) : bool then x else\n                          if reg_eqb y (ZToReg 0) : bool then negate (ZToReg 1) else\n                          div x y in\n                        setRegister rd (s32 q)))\n    | Decode.Divuw rd rs1 rs2 =>\n        Bind (getRegister rs1) (fun x =>\n                Bind (getRegister rs2) (fun y =>\n                        let q := if reg_eqb y (ZToReg 0) : bool then maxUnsigned else divu x y in\n                        setRegister rd (s32 q)))\n    | Decode.Remw rd rs1 rs2 =>\n        Bind (getRegister rs1) (fun x =>\n                Bind (getRegister rs2) (fun y =>\n                        let r :=\n                          if andb (reg_eqb x minSigned) (reg_eqb y (negate (ZToReg 1))) : bool\n                          then ZToReg 0 else\n                          if reg_eqb y (ZToReg 0) : bool then x else\n                          rem x y in\n                        setRegister rd (s32 r)))\n    | Decode.Remuw rd rs1 rs2 =>\n        Bind (getRegister rs1) (fun x =>\n                Bind (getRegister rs2) (fun y =>\n                        let r := if reg_eqb y (ZToReg 0) : bool then x else remu x y in\n                        setRegister rd (s32 r)))\n    | inst => Return tt\n    end.\n\n(* External variables:\n     Bind Return RiscvState ZToReg andb bool div divu getRegister maxUnsigned\n     minSigned negate op_zt__ reg_eqb rem remu s32 setRegister tt unit Decode.Divuw\n     Decode.Divw Decode.InstructionM64 Decode.Mulw Decode.Remuw Decode.Remw\n*)\n", "meta": {"author": "samuelgruetter", "repo": "riscv-coq", "sha": "bd89fbff49704b4476633a88abdedb4e410c200b", "save_path": "github-repos/coq/samuelgruetter-riscv-coq", "path": "github-repos/coq/samuelgruetter-riscv-coq/riscv-coq-bd89fbff49704b4476633a88abdedb4e410c200b/src/ExecuteM64.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.4843800842769843, "lm_q1q2_score": 0.29071928804052305}}
{"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\nRequire Export natk.\n\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_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_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\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\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\nHint Resolve wf_mk_nat : slow.\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\n\n(*\n*** Local Variables:\n*** coq-load-path: (\".\" \"../util/\")\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/terms/natk2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.29071928804052305}}
{"text": "Require Export List.\nRequire Export Bool.\nRequire Export Arith.\nRequire Export Peano_dec.\nRequire Export Coq.Arith.PeanoNat.\nRequire Export Coq.Program.Wf.\nRequire Export Coq.Program.Tactics.\nRequire Export Coq.Logic.FunctionalExtensionality.\nRequire Export Recdef.\nSet Implicit Arguments.\n\nImport WfExtensionality.\n\nRequire Import common.CpdtTactics.\nRequire Import common.wyv_common.\nRequire Import common.rhs_mat_tree.\n\nLemma subtype_nom_other_reduce : \n  forall T1 L t1 T1', T1 = (t_nom L t1 T1') ->\n                 forall T2, (forall t2 T2', T2 <> (t_nom L t2 T2')) ->\n                       (forall T2', T2 <> (t_upp L T2')) ->\n                       subtype T1 T2 = false.\n\nProof.\n  intros.\n\n  remember (subtype T1 T2) as sub_fn; subst T1.\n  \n  unfold subtype, subtype_func in Heqsub_fn;\n    simpl in Heqsub_fn;\n    rewrite fix_sub_eq_ext in Heqsub_fn;\n    simpl in Heqsub_fn;\n    fold subtype_func in Heqsub_fn;\n    auto.\n\n  destruct T2; auto.\n\n  destruct (eq_label_dec L l) as [Heq|Heq];\n    rewrite Heq in Heqsub_fn;\n    [rewrite andb_true_l in Heqsub_fn\n    |rewrite andb_false_l in Heqsub_fn; auto].\n\n  apply beq_label_eq in Heq; subst L;\n    contradiction (H1 T2); auto.\n\n  destruct (eq_label_dec L l) as [Heq|Heq];\n    rewrite Heq in Heqsub_fn;\n    [rewrite andb_true_l in Heqsub_fn\n    |rewrite andb_false_l in Heqsub_fn; auto].\n\n  apply beq_label_eq in Heq; subst L;\n    contradiction (H0 t T2); auto.\nQed.", "meta": {"author": "JulianMackay", "repo": "Wyvern_Formalism", "sha": "7072f2803b500c73c42347544740768e81a8beca", "save_path": "github-repos/coq/JulianMackay-Wyvern_Formalism", "path": "github-repos/coq/JulianMackay-Wyvern_Formalism/Wyvern_Formalism-7072f2803b500c73c42347544740768e81a8beca/wfix/lhs_nom_reduce/rhs_other_reduce.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883592602049, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.290719288040523}}
{"text": "(** This is a simple cancellation procedure based on\n ** an ordering of the elements on the right hand side.\n **)\nRequire 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.\n(* Require Import MirrorCore.Lambda.AppFull. *)\nRequire Import ILogic BILogic Pure.\nRequire Import MirrorCharge.BILNormalize.\nRequire Import MirrorCharge.Iterated.\nRequire Import MirrorCharge.SynSepLog.\nRequire Import MirrorCore.Lambda.ExprVariables.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nSection ordered_cancel.\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  Let Expr_expr : ExprI.Expr _ (expr typ func) := Expr_expr.\n  Local Existing Instance Expr_expr.\n\n  Inductive Conjuncts : Type :=\n  | Pure (_ : expr typ func) (c : Conjuncts)\n  | Impure (f : expr typ func) (xs : list (expr typ func)) (c : Conjuncts)\n  | Frame (_ : expr typ func) (xs : list (expr typ func)) (c : Conjuncts)\n  | Emp\n  | Tru.\n\n  Variable subst : Type.\n  Variable Subst_subst : Subst subst (expr typ func).\n  Hypothesis SubstOk_subst : SubstOk Subst_subst.\n\n  Fixpoint findWithRest {T U} (f : T -> option U) (ls acc : list T) {struct ls}\n  : option (T * U * list T) :=\n    match ls with\n      | nil => None\n      | l :: ls =>\n        match f l with\n          | None => findWithRest f ls (l :: acc)\n          | Some u => Some (l, u, rev_append acc ls)\n        end\n    end.\n\n  Theorem findWithRest_spec\n  : forall T U f ls acc a s b,\n      @findWithRest T U f ls acc = Some (a,s,b) ->\n      f a = Some s /\\\n      exists before after,\n        b = before ++ after /\\ rev_append acc ls = before ++ a :: after.\n  Proof.\n    clear. induction ls; simpl; intros; try congruence.\n    consider (f a); intros.\n    { inv_all; subst. split; auto.\n      exists (rev acc). exists ls.\n      repeat rewrite rev_append_rev. auto. }\n    { eapply IHls in H0. intuition. }\n  Qed.\n\n  Variable doUnifySepLog : subst -> expr typ func -> expr typ func -> option subst.\n  Variable eprovePure : subst -> expr typ func -> option subst.\n\n  Variable SSL : SynSepLog typ func.\n\n  Fixpoint cancel (rhs : Conjuncts) (lhs : conjunctives typ func)\n           (rem : conjunctives typ func) (s : subst) {struct rhs}\n  : conjunctives typ func * conjunctives typ func * subst :=\n    match rhs with\n      | Emp => (lhs, rem, s)\n      | Tru => ({| spatial := lhs.(spatial)\n                 ; pure := lhs.(pure)\n                 ; star_true := false\n                 |}, {| spatial := rem.(spatial)\n                      ; pure := rem.(pure)\n                      ; star_true := true\n                      |}, s)\n      | Frame hd xs rhs =>\n        match rem.(spatial) with\n          | nil =>\n            (** try to get everything! **)\n            let lhs_all := conjunctives_to_expr SSL lhs in\n            match doUnifySepLog s lhs_all (apps hd xs) with\n              | None =>\n                cancel rhs lhs\n                       {| spatial := rem.(spatial) ++ (hd,xs) :: nil\n                        ; pure := rem.(pure)\n                        ; star_true := rem.(star_true)\n                        |} s\n              | Some s' =>\n                cancel rhs\n                       {| spatial := nil\n                        ; pure := lhs.(pure)\n                        ; star_true := false\n                        |}\n                       {| spatial := nil\n                        ; pure := rem.(pure)\n                        ; star_true := rem.(star_true)\n                        |} s'\n            end\n          | _ =>\n            (** If there are spatial conjuncts left, we should keep this **)\n            cancel rhs lhs\n                   {| spatial := rem.(spatial) ++ (hd,xs) :: nil\n                    ; pure := rem.(pure)\n                    ; star_true := rem.(star_true)\n                    |} s\n        end\n      | Pure p cs =>\n        match eprovePure s p with\n          | None =>\n            cancel cs lhs {| spatial := rem.(spatial)\n                           ; star_true := rem.(star_true)\n                           ; pure := p :: rem.(pure)\n                           |} s\n          | Some s' =>\n            cancel cs lhs rem s'\n        end\n      | Impure f xs cs =>\n        let Z := apps f xs in\n        let test x := doUnifySepLog s Z (apps (fst x) (snd x)) in\n        match findWithRest test lhs.(spatial) nil with\n          | None =>\n            cancel cs lhs {| spatial := (f,xs) :: rem.(spatial)\n                           ; star_true := rem.(star_true)\n                           ; pure := rem.(pure)\n                           |} s\n          | Some (_, s', rst) =>\n            cancel cs {| spatial := rst\n                       ; star_true := lhs.(star_true)\n                       ; pure := lhs.(pure)\n                       |}\n                      rem s'\n        end\n    end.\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(*  Hypothesis eprovePureOk : eprovePure_spec.\n\n  Variable SSLO : SynSepLogOk _ _ _ _ SSL.\n\n\n  Variables tus tvs : tenv typ.\n*)\n(****\n  (** TODO: this can be generalized to handle entailment with a remainder **)\n  Definition unifySepLog_spec :=\n    forall s e e' s',\n      doUnifySepLog s e e' = Some s' ->\n      WellTyped_expr tus tvs e tySL ->\n      WellTyped_expr tus tvs e' tySL ->\n      WellTyped_subst tus tvs s ->\n         WellTyped_subst tus tvs s'\n      /\\ forall (us : HList.hlist _ tus) (vs : HList.hlist _ tvs),\n           substD (join_env us) (join_env vs) s' ->\n           exprD (join_env us) (join_env vs) e tySL = exprD (join_env us) (join_env vs) e' tySL /\\\n           substD (join_env us) (join_env vs) s.\n  Hypothesis doUnifySepLogOk : unifySepLog_spec.\n\n  (** TODO: I can't use a simple EProver here because EProvers are specialized\n   **       to work with [Prop], not arbitrary ILogics.\n   ** This is yet another reason to get ILogic underneath MirrorCore.\n   ** - You really just need to generalize [Prover]/[EProver] with [Entails].\n   **)\n  Definition eprovePure_spec :=\n    forall s e s',\n      eprovePure s e = Some s' ->\n      match exprD' tus tvs e tySL with\n        | Some val =>\n          WellTyped_subst tus tvs s ->\n          WellTyped_subst tus tvs s'\n          /\\ forall (us : HList.hlist _ tus) (vs : HList.hlist _ tvs),\n               substD (join_env us) (join_env vs) s' ->\n               (ltrue |-- val us vs)\n               /\\ substD (join_env us) (join_env vs) s\n        | None => True\n      end.\n\n(*\n  Fixpoint ConjunctsD (ls : Conjuncts) : option (typD ts nil tySL) :=\n    match ls with\n      | Emp => Some empSP\n      | Tru => Some ltrue\n      | Pure p ls =>\n        match exprD us vs p tySL , ConjunctsD ls with\n          | Some a , Some b => Some (sepSP (land a empSP) b)\n          | _ , _ => None\n        end\n      | Impure f xs ls =>\n        match exprD us vs (apps f xs) tySL , ConjunctsD ls with\n          | Some a , Some b => Some (sepSP a b)\n          | _ , _ => None\n        end\n    end.\n*)\n\n  Variable PureOp_SL : @Pure.PureOp (typD ts nil tySL).\n  Variable Pure_SL : Pure.Pure PureOp_SL.\n  Hypothesis Pure_ltrue : Pure.pure ltrue.\n  Hypothesis Pure_land : forall a b, Pure.pure a -> Pure.pure b -> Pure.pure (a //\\\\ b).\n\n  Section well_formed_Conjuncts.\n    Variable us' vs' : EnvI.env (typD ts).\n\n    Fixpoint well_formed_Conjuncts (ls : Conjuncts) : Prop :=\n      match ls with\n        | Emp => True\n        | Tru => True\n        | Pure p ls =>\n          match exprD us' vs' p tySL with\n            | None => False\n            | Some p => Pure.pure p\n          end /\\ well_formed_Conjuncts ls\n        | Impure _ _ ls => well_formed_Conjuncts ls\n      end.\n  End well_formed_Conjuncts.\n\n  Fixpoint Conjuncts_to_expr (ls : Conjuncts) : expr typ func :=\n    match ls with\n      | Emp => SSL.(e_emp)\n      | Tru => SSL.(e_true)\n      | Pure p ls =>\n        SSL.(e_star) (SSL.(e_and) p SSL.(e_emp)) (Conjuncts_to_expr ls)\n      | Impure f xs ls =>\n        SSL.(e_star) (apps f xs) (Conjuncts_to_expr ls)\n    end.\n\n  Definition sentails : env (typD ts) -> env (typD ts) -> expr typ func -> expr typ func -> Prop :=\n    @Sem_equiv typ (typD ts) (expr typ func) _ tySL lentails.\n\n  Lemma exprD'_iterated_base_cons_Some\n  : forall tus tvs a b x,\n      exprD' tus tvs (iterated_base SSL.(e_emp) SSL.(e_star) (a :: b)) tySL = Some x ->\n      exists aV bV,\n        exprD' tus tvs a tySL = Some aV /\\\n        exprD' tus tvs (iterated_base SSL.(e_emp) SSL.(e_star) b) tySL = Some bV /\\\n        (forall us vs, ((x us vs) -|- sepSP (aV us vs) (bV us vs))).\n  Proof.\n    clear Pure_SL PureOp_SL Pure_ltrue Pure_land.\n    unfold iterated_base. simpl.\n    intros.\n    destruct (iterated (e_star SSL) b).\n    { go_crazy SSL SSLO; eauto. }\n    { exists x.\n      destruct (SSLO.(e_empOk) tus0 tvs0) as [ ? [ ? ? ] ].\n      eexists. split; eauto. split; eauto. intros.\n      rewrite H1. rewrite empSPR; eauto. }\n  Qed.\n\n  Lemma exprD'_iterated_base_cons_None\n  : forall us tvs a b,\n      exprD' us tvs (iterated_base SSL.(e_emp) SSL.(e_star) (a :: b)) tySL = None <->\n      exprD' us tvs a tySL = None \\/\n      exprD' us tvs (iterated_base SSL.(e_emp) SSL.(e_star) b) tySL = None.\n  Proof.\n    clear Pure_SL PureOp_SL Pure_ltrue Pure_land.\n    unfold iterated_base. simpl.\n    intros.\n    destruct (iterated (e_star SSL) b); auto.\n    { split; intros; repeat (go_crazy SSL SSLO); auto.\n      consider (exprD' us tvs0 (e_star SSL a e) tySL); intros; auto.\n      exfalso. go_crazy SSL SSLO. destruct H; congruence. }\n    { split; intros; repeat (go_crazy SSL SSLO); auto.\n      destruct H; auto.\n      exfalso.\n      destruct (SSLO.(e_empOk) us tvs0). intuition. congruence. }\n  Qed.\n\n  Lemma exprD'_iterated_base_app_Some\n  : forall tus tvs a b x,\n      exprD' tus tvs (iterated_base SSL.(e_emp) SSL.(e_star) (a ++ b)) tySL = Some x ->\n      exists aV bV,\n        exprD' tus tvs (iterated_base SSL.(e_emp) SSL.(e_star) a) tySL = Some aV /\\\n        exprD' tus tvs (iterated_base SSL.(e_emp) SSL.(e_star) b) tySL = Some bV /\\\n        (forall us vs, ((x us vs) -|- sepSP (aV us vs) (bV us vs))).\n  Proof.\n    clear Pure_SL PureOp_SL doUnifySepLogOk Pure_ltrue Pure_land.\n    induction a; simpl; intros.\n    { destruct (SSLO.(e_empOk) tus0 tvs0) as [ ? [ ? ? ] ].\n      exists x0. exists x.\n      split; eauto. split; eauto.\n      intros. rewrite H1. rewrite empSPL. reflexivity. }\n    { eapply exprD'_iterated_base_cons_Some in H.\n      destruct H as [ ? [ ? [ ? [ ? ? ] ] ] ].\n      specialize (IHa _ _ H0).\n      destruct IHa as [ ? [ ? [ ? [ ? ? ] ] ] ].\n      consider (exprD' tus0 tvs0 (iterated_base (e_emp SSL) (e_star SSL) (a :: a0)) tySL); intros.\n      { do 2 eexists. split; eauto. split; eauto.\n        apply exprD'_iterated_base_cons_Some in H5.\n        destruct H5 as [ ? [ ? [ ? [ ? ? ] ] ] ].\n        intros. Cases.rewrite_all_goal.\n        rewrite H in *. rewrite H6 in *.\n        inv_all; subst.\n        rewrite sepSPA. reflexivity. }\n      { exfalso.\n        eapply exprD'_iterated_base_cons_None in H5.\n        destruct H5; congruence. } }\n  Qed.\n\n  Lemma exprD'_iterated_base_app_None\n  : forall us tvs a b,\n      exprD' us tvs (iterated_base SSL.(e_emp) SSL.(e_star) (a ++ b)) tySL = None <->\n      exprD' us tvs (iterated_base SSL.(e_emp) SSL.(e_star) a) tySL = None \\/\n      exprD' us tvs (iterated_base SSL.(e_emp) SSL.(e_star) b) tySL = None.\n  Proof.\n    clear Pure_SL PureOp_SL doUnifySepLogOk Pure_ltrue Pure_land.\n    induction a; simpl; intros.\n    { intuition.\n      unfold iterated_base in H0. simpl in *.\n      destruct (SSLO.(e_empOk) us tvs0) as [ ? [ ? ? ] ].\n      congruence. }\n    { repeat rewrite exprD'_iterated_base_cons_None.\n      rewrite IHa. split; tauto. }\n  Qed.\n\n  Lemma exprD'_WellTyped_expr\n  : forall tus tvs e t val,\n      exprD' tus tvs e t = Some val ->\n      WellTyped_expr tus tvs e t.\n  Proof.\n    clear; intros.\n    red. eapply ExprD3.EXPR_DENOTE_core.exprD'_typeof. eapply H.\n  Qed.\n  Hint Resolve exprD'_WellTyped_expr : WellTyped.\n\n  Ltac forward_reason :=\n    repeat match goal with\n             | H : ?X , H' : ?X -> _ |- _ =>\n               match type of X with\n                 | Prop => specialize (H' H)\n               end\n             | vs : HList.hlist _ _ , H : forall x : HList.hlist _ _, _ |- _ =>\n               specialize (H vs)\n             | H : _ /\\ _ |- _ => destruct H\n             | H : exists x, _ |- _ => destruct H\n           end.\n\n\n  Lemma cancelOk_lem'\n  : forall rhs lhs rem s lhs' rhs' s',\n      cancel rhs lhs rem s = (lhs',rhs',s') ->\n      match\n          exprD' tus tvs (conjunctives_to_expr_star SSL lhs) tySL\n        , exprD' tus tvs (SSL.(e_star) (conjunctives_to_expr_star SSL rem)\n                                       (Conjuncts_to_expr rhs)) tySL\n      with\n        | Some l , Some r =>\n          match\n              exprD' tus tvs (conjunctives_to_expr_star SSL lhs') tySL\n            , exprD' tus tvs (conjunctives_to_expr_star SSL rhs') tySL\n          with\n            | Some l' , Some r' =>\n              WellTyped_subst tus tvs s ->\n                 WellTyped_subst tus tvs s'\n              /\\ forall us vs,\n                   well_formed _ _ _ lhs (join_env us) (join_env vs) ->\n                   well_formed_Conjuncts (join_env us) (join_env vs) rhs ->\n                   well_formed _ _ _ rem (join_env us) (join_env vs) ->\n                      well_formed _ _ _ lhs' (join_env us) (join_env vs)\n                   /\\ well_formed _ _ _ rhs' (join_env us) (join_env vs)\n                   /\\ (substD (join_env us) (join_env vs) s' ->\n                       (l' us vs |-- r' us vs) ->\n                       (l us vs |-- r us vs) /\\ substD (join_env us) (join_env vs) s)\n            | _ , _ => False\n          end\n        | _ , _ => True\n      end.\n  Proof.\n    induction rhs; intros; forward.\n    { repeat go_crazy SSL SSLO.\n      simpl in H.\n      consider (eprovePure s e); intros;\n        eapply IHrhs in H4; clear IHrhs.\n      { forward. inv_all; subst.\n        red in eprovePureOk.\n        apply eprovePureOk in H.\n        simpl in H2.\n        consider (exprD' tus tvs\n                         (e_star SSL (conjunctives_to_expr_star SSL rem)\n                                 (Conjuncts_to_expr rhs)) tySL); intros.\n        { forward.\n          repeat go_crazy SSL SSLO.\n          inv_all; subst.\n          repeat rewrite typeof_env_join_env in *.\n          forward_reason.\n          split; auto. intros.\n          destruct H16. unfold exprD in H16.\n          repeat rewrite split_env_join_env in *.\n          simpl in *.\n          rewrite H2 in *.\n          forward_reason.\n          split; auto. split; auto. intros.\n          forward_reason. split; auto.\n          destruct (SSLO.(e_empOk) tus tvs) as [ ? [ ? ? ] ].\n          repeat go_crazy SSL SSLO.\n          inv_all; subst.\n          do 6 match goal with\n                 | H : _ |- _ =>\n                   rewrite H; clear H\n               end.\n          rewrite <- empSPL with (P := x2 us vs) at 1.\n          eapply scME; eauto.\n          eapply scME; eauto.\n          apply landR; auto.\n          etransitivity; try eassumption. apply ltrueR. }\n        { simpl in *.\n          repeat (go_crazy SSL SSLO; try congruence). } }\n      { (** eprovePure returns None **)\n        forward. inv_all; subst.\n        clear H.\n        consider (exprD' tus tvs\n           (e_star SSL\n              (conjunctives_to_expr_star SSL\n                 {|\n                 spatial := spatial rem;\n                 star_true := star_true rem;\n                 pure := e :: pure rem |}) (Conjuncts_to_expr rhs)) tySL);\n          intros.\n        { forward.\n          simpl in *. forward_reason.\n          split; auto. intros.\n          forward_reason.\n          assert (well_formed RSym_func tySL PureOp_SL\n                              {| spatial := spatial rem;\n                                 star_true := star_true rem;\n                                 pure := e :: pure rem |} (join_env us) (join_env vs)).\n          { red. constructor; auto.\n            forward. eauto. }\n          forward_reason.\n          split; auto. split; auto. intros.\n          forward_reason.\n          split; auto.\n          clear H13. unfold exprD in H10.\n          repeat rewrite split_env_join_env in *.\n          unfold conjunctives_to_expr_star in H, H1.\n          simpl in *.\n          repeat go_crazy SSL SSLO.\n          inv_all; subst.\n          eapply exprD'_iterated_base_cons_Some in H.\n          forward_reason.\n          repeat go_crazy SSL SSLO.\n          inv_all; subst.\n          do 11 match goal with\n                  | H : _ |- _ => rewrite H; clear H\n                end.\n          repeat rewrite <- sepSPA.\n          apply scME; auto.\n          repeat rewrite sepSPA.\n          rewrite sepSPC. repeat rewrite <- sepSPA.\n          apply scME; auto.\n          rewrite landC. reflexivity. }\n        { exfalso. simpl in *.\n          unfold conjunctives_to_expr_star in H, H1. destruct rem; simpl in *.\n          repeat (go_crazy SSL SSLO; try congruence).\n          eapply exprD'_iterated_base_cons_None in H.\n          destruct H;\n            repeat (go_crazy SSL SSLO; try congruence). } } }\n    { repeat go_crazy SSL SSLO.\n      red in doUnifySepLogOk.\n      simpl in H.\n      consider (findWithRest\n          (fun x : expr typ func * list (expr typ func) =>\n           doUnifySepLog s (apps f xs) (apps (fst x) (snd x)))\n          (spatial lhs) nil); intros.\n      { destruct p. destruct p.\n        eapply IHrhs in H4; clear IHrhs.\n        consider (exprD' tus tvs\n           (conjunctives_to_expr_star SSL\n              {|\n              spatial := l;\n              star_true := star_true lhs;\n              pure := pure lhs |}) tySL); intros.\n        { consider (exprD' tus tvs\n           (e_star SSL (conjunctives_to_expr_star SSL rem)\n              (Conjuncts_to_expr rhs)) tySL); intros.\n          { forward. repeat go_crazy SSL SSLO.\n            inv_all; subst.\n            eapply findWithRest_spec in H.\n            forward_reason. simpl in *. subst.\n            unfold conjunctives_to_expr_star in H4, H0.\n            simpl in *. subst.\n            generalize dependent (iterated_base (e_emp SSL) (e_star SSL)\n               (map (e_and SSL (e_emp SSL)) (pure lhs))).\n            generalize dependent (if star_true lhs then e_true SSL else e_emp SSL).\n            intros.\n            repeat go_crazy SSL SSLO. inv_all; subst.\n            rewrite H12 in *.\n            rewrite map_app in *. simpl in *.\n            eapply exprD'_iterated_base_app_Some in H5.\n            forward_reason.\n            eapply exprD'_iterated_base_app_Some in H16.\n            destruct H16 as [ ? [ ? [ ? [ ? ? ] ] ] ].\n            simpl in *.\n            eapply exprD'_iterated_base_cons_Some in H16.\n            destruct H16 as [ ? [ ? [ ? [ ? ? ] ] ] ].\n            eapply doUnifySepLogOk in H; eauto with WellTyped.\n            forward_reason.\n            split; auto. intros.\n            forward_reason.\n            split; auto. split; auto. intros.\n            forward_reason.\n            split; auto.\n            unfold exprD in *.\n            repeat rewrite split_env_join_env in *.\n            simpl in *.\n            repeat go_crazy SSL SSLO.\n            inv_all; subst.\n            rewrite H3; clear H3.\n            rewrite H21; clear H21.\n            rewrite H25; clear H25.\n            rewrite sepSPC. rewrite sepSPA.\n            rewrite (sepSPC (x2 us vs)). rewrite <- H11; clear H11.\n            transitivity (x15 us vs ** t1 us vs).\n            { do 7 match goal with\n                     | H : _ |- _ => rewrite H; clear H\n                   end.\n              repeat rewrite <- sepSPA.\n              do 2 (apply scME; auto).\n              rewrite sepSPC.\n              rewrite sepSPA. reflexivity. }\n            { rewrite H31. reflexivity. } }\n          { exfalso. simpl in H2.\n            repeat (go_crazy SSL SSLO; try congruence). } }\n        { exfalso.\n          simpl in *.\n          unfold conjunctives_to_expr_star in H0, H4.\n          simpl in *.\n          repeat (go_crazy SSL SSLO; try congruence).\n          apply findWithRest_spec in H.\n          forward_reason. subst.\n          simpl in H13. rewrite H13 in H8.\n          repeat rewrite map_app in *. simpl in *.\n          eapply exprD'_iterated_base_app_Some in H8.\n          forward_reason.\n          eapply exprD'_iterated_base_cons_Some in H12.\n          forward_reason.\n          eapply exprD'_iterated_base_app_None in H4.\n          destruct H4; congruence. } }\n      { eapply IHrhs in H4; clear IHrhs. clear H.\n        simpl in *.\n        progress forward.\n        inv_all; subst.\n        consider (exprD' tus tvs\n           (e_star SSL\n              (conjunctives_to_expr_star SSL\n                 {|\n                 spatial := (f, xs) :: spatial rem;\n                 star_true := star_true rem;\n                 pure := pure rem |}) (Conjuncts_to_expr rhs)) tySL).\n        { intros. forward.\n          forward_reason.\n          split; auto. intros.\n          forward_reason.\n          split; auto. split; auto. intros.\n          forward_reason.\n          split; auto.\n          unfold conjunctives_to_expr_star in H0, H1.\n          simpl in *.\n          generalize dependent (iterated_base (e_emp SSL) (e_star SSL)\n               (map (e_and SSL (e_emp SSL)) (pure rem))).\n          generalize dependent (if star_true rem then e_true SSL else e_emp SSL).\n          intros.\n          repeat go_crazy SSL SSLO. inv_all; subst.\n          eapply exprD'_iterated_base_cons_Some in H19.\n          forward_reason.\n          rewrite H23 in *. inv_all; subst.\n          do 9 match goal with\n                 | H : _ |- _ => rewrite H; clear H\n               end.\n          repeat rewrite sepSPA.\n          apply scME; auto.\n          repeat rewrite <- sepSPA.\n          apply scME; auto.\n          rewrite sepSPA.\n          rewrite sepSPC.\n          apply scME; auto.\n          rewrite H2 in *. inv_all; subst. reflexivity. }\n        { intro; exfalso.\n          unfold conjunctives_to_expr_star in H0, H1.\n          simpl in *.\n          generalize dependent (iterated_base (e_emp SSL) (e_star SSL)\n               (map (e_and SSL (e_emp SSL)) (pure rem))).\n          generalize dependent (if star_true rem then e_true SSL else e_emp SSL).\n          intros.\n          repeat go_crazy SSL SSLO.\n          eapply exprD'_iterated_base_cons_None in H0.\n          destruct H0; congruence. } } }\n    { simpl in H. inv_all; subst.\n      simpl in *.\n      destruct (SSLO.(e_empOk) tus tvs) as [ ? [ ? ? ] ].\n      repeat go_crazy SSL SSLO.\n      inv_all; subst.\n      intros.\n      split; auto. intros. split; auto. split; auto.\n      intros. split; auto.\n      forward_reason.\n      rewrite H9; clear H9.\n      do 2 match goal with\n             | H : _ |- _ => rewrite H; clear H\n           end.\n      rewrite empSPR; eauto. }\n    { simpl in H. inv_all; subst.\n      simpl in *.\n      destruct (SSLO.(e_empOk) tus tvs) as [ ? [ ? ? ] ].\n      repeat go_crazy SSL SSLO.\n      unfold conjunctives_to_expr_star. simpl.\n      unfold conjunctives_to_expr_star in H1.\n      generalize dependent (iterated_base (e_emp SSL) (e_star SSL)\n               (map (e_and SSL (e_emp SSL)) (pure rem))).\n      generalize dependent (iterated_base (e_emp SSL) (e_star SSL)\n                (map\n                   (fun x2 : expr typ func * list (expr typ func) =>\n                    apps (fst x2) (snd x2)) (spatial rem))).\n      intros.\n      repeat go_crazy SSL SSLO.\n      consider (exprD' tus tvs (e_star SSL e0 (e_star SSL e (e_true SSL))) tySL); intros.\n      { split; auto. intros.\n        forward_reason.\n        split; auto. split; auto. intros.\n        split; auto.\n        destruct (SSLO.(e_trueOk) tus tvs) as [ ? [ ? ? ] ].\n        repeat go_crazy SSL SSLO. inv_all; subst. subst.\n        do 7 match goal with\n               | H : _ |- _ => rewrite H; clear H\n             end.\n        destruct (SSLO.(e_trueOk) tus tvs) as [ ? [ ? ? ] ].\n        rewrite H3 in *. inv_all; subst.\n        rewrite H6. repeat rewrite sepSPA.\n        apply scME; auto.\n        apply scME; auto.\n        destruct (star_true rem).\n        { rewrite H3 in *. inv_all; subst.\n          rewrite H6. rewrite ltrue_sep; eauto. }\n        { rewrite H in *. inv_all; subst. rewrite H2.\n          rewrite empSPL. auto. } }\n      { repeat (go_crazy SSL SSLO; try congruence). } }\n  Qed.\n*)\n  Variable order : conjunctives typ func -> Conjuncts.\n(*\n  Definition order_spec :=\n    forall c tus tvs,\n      match exprD' tus tvs (conjunctives_to_expr_star SSL c) tySL\n          , exprD' tus tvs (Conjuncts_to_expr (order c)) tySL\n      with\n        | Some l , Some r =>\n          forall us vs,\n            well_formed _ _ _ c (join_env us) (join_env vs) ->\n            ((l us vs -|- r us vs) /\\\n             well_formed_Conjuncts (join_env us) (join_env vs) (order c))\n        | None , None => True\n        | _ , _ => False\n      end.\n  Hypothesis orderOk : order_spec.\n*)\n  Definition ordered_cancel (lhs rhs : conjunctives typ func) (s : subst)\n  : conjunctives typ func * conjunctives typ func * subst :=\n    let ordered := order rhs in\n    let empty := {| spatial := nil ; pure := nil ; star_true := false |} in\n    cancel ordered lhs empty s.\n(*\n  Theorem ordered_cancelOk\n  : forall lhs rhs s lhs' rhs' s',\n      ordered_cancel lhs rhs s = (lhs', rhs', s') ->\n      match\n          exprD' tus tvs (conjunctives_to_expr SSL lhs) tySL\n        , exprD' tus tvs (conjunctives_to_expr SSL rhs) tySL\n      with\n        | Some l , Some r =>\n          match\n              exprD' tus tvs (conjunctives_to_expr SSL lhs') tySL\n            , exprD' tus tvs (conjunctives_to_expr SSL rhs') tySL\n          with\n            | Some l' , Some r' =>\n              WellTyped_subst tus tvs s ->\n              WellTyped_subst tus tvs s' /\\\n              forall (us' : HList.hlist _ tus) vs',\n                let vs := join_env vs' in\n                let us := join_env us' in\n              well_formed _ _ _ lhs us vs ->\n              well_formed _ _ _ rhs us vs ->\n              substD us vs s' ->\n                  well_formed _ _ _ lhs' us vs\n               /\\ well_formed _ _ _ rhs' us vs\n               /\\ ((l' us' vs' |-- r' us' vs') -> l us' vs' |-- r us' vs')\n            | _ , _ => False\n          end\n        | _ , _ => True\n      end.\n  Proof.\n    intros.\n    unfold ordered_cancel in H.\n    eapply cancelOk_lem' in H.\n    generalize (@conjunctives_to_expr_conjunctives_to_expr_star_iff _ _ _ _ _ SSL _ tvs tus lhs).\n    generalize (@conjunctives_to_expr_conjunctives_to_expr_star_iff _ _ _ _ _ SSL _ tvs tus rhs).\n    generalize (@conjunctives_to_expr_conjunctives_to_expr_star_iff _ _ _ _ _ SSL _ tvs tus lhs').\n    generalize (@conjunctives_to_expr_conjunctives_to_expr_star_iff _ _ _ _ _ SSL _ tvs tus rhs').\n    intros.\n    forward.\n    match type of H4 with\n      | match ?X with _ => _ end =>\n        consider X; intros\n    end.\n    { forward.\n      forward_reason.\n      split; auto. intros. subst vs.\n      forward_reason.\n      repeat go_crazy SSL SSLO.\n      unfold conjunctives_to_expr_star in H4. simpl in *.\n      red in orderOk.\n      specialize (orderOk rhs tus tvs).\n      repeat go_crazy SSL SSLO.\n      inv_all; subst.\n      specialize (orderOk us' vs' H16).\n      destruct orderOk.\n      unfold iterated_base in *. simpl in *.\n      assert (well_formed RSym_func tySL PureOp_SL\n          {| spatial := nil; star_true := false; pure := nil |}\n          (join_env us') (join_env vs')) by constructor.\n      specialize (H14 H24 H25).\n      destruct H14 as [ ? [ ? ? ] ].\n      specialize (H27 H17).\n      split; auto. split; auto. intros.\n      apply H12 in H14; clear H12.\n      rewrite H14 in H28; clear H14.\n      apply H11 in H26; clear H11.\n      rewrite H26 in H28; clear H26.\n      specialize (H27 H28).\n      destruct H27. clear H28.\n      rewrite H7; clear H7. rewrite H20; clear H20.\n      rewrite H5; clear H5. rewrite H11; clear H11.\n      rewrite H19; clear H19. rewrite H21; clear H21.\n      rewrite H23; clear H23.\n      rewrite H22 in *. inv_all; subst.\n      destruct (SSLO.(e_empOk) tus tvs) as [ ? [ ? ? ] ].\n      rewrite H4 in *. inv_all; subst.\n      rewrite H5.\n      repeat rewrite empSPL. reflexivity. }\n    { exfalso.\n      unfold conjunctives_to_expr_star in H3; simpl in H3.\n      unfold iterated_base in H3; simpl in H3.\n      destruct (SSLO.(e_empOk) tus tvs) as [ ? [ ? ? ] ].\n      destruct (SSLO.(e_trueOk) tus tvs) as [ ? [ ? ? ] ].\n      unfold conjunctives_to_expr_star in H4.\n      simpl in H4.\n      unfold iterated_base in H4. simpl in H4.\n      repeat (go_crazy SSL SSLO; try congruence).\n      specialize (orderOk rhs tus tvs).\n      forward. }\n  Qed.\n*****)\nEnd ordered_cancel.\n\n(** The simplest ordering heuristic just uses the order that they occur in the\n ** map without looking at unification variables.\n **)\nSection simple_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  Definition simple_order (c : conjunctives typ func) : Conjuncts typ func :=\n    List.fold_right (fun x =>\n                       match fst x with\n                         | UVar _ => Frame (fst x) (snd x)\n                         | _ => Impure (fst x) (snd x)\n                       end)\n                    (List.fold_right (fun x acc => Pure x acc)\n                                     (if c.(star_true) then Tru _ _ else Emp _ _)\n                                     c.(pure))\n                    c.(spatial).\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 simple_ordering.\n(** TODO: There may be a cleaner way to do this...\n **)\n\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/OrderedCanceller.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573377, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.29071928111249906}}
{"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(* Frameworks for proving Clight loops: specification and termination  *)\n(*                                                                     *)\n(*                 Developed by Xiongnan (Newman) Wu                   *)\n(*                                                                     *)\n(*                         Yale University                             *)\n(*                                                                     *)\n(* *********************************************************************)\n\n\nRequire 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 Locations.\nRequire Import Clight.\nRequire Import Smallstep.\nRequire Import ClightBigstep.\nRequire Import Ctypes.\nRequire Import Cop.\nRequire Import ZArith.Zwf.\nRequire Import Integers.\nRequire Import CDataTypes.\n\nModule LoopProof.\n\nSection S.\n\n  Context `{Hcc: Events.CompilerConfiguration}\n          `{Hwb: Events.WritableBlock}.\n\n  Variables (body: statement) (genv: genv) (env: env)\n            (P Q: temp_env -> mem -> Prop)\n            (R: temp_env-> mem -> option (val * type)-> Prop).\n\n  Record t  : Type := make {\n         W: Type;\n         lt: W-> W-> Prop;\n         lt_wf: well_founded lt;\n         I: temp_env-> mem-> W-> Prop;\n         P_implies_I: forall le m, P le m-> exists n0, I le m n0;\n         I_invariant:\n         forall le m n, I le m n ->\n           exists out le' m', exec_stmt genv env le m body E0 le' m' out /\\\n             ((out = Out_normal \\/ out = Out_continue)-> exists n', lt n' n /\\ I le' m' n') /\\\n              (out = Out_break-> Q le' m') /\\\n              (forall v, out = Out_return v-> R le' m' v)\n  }.\n\n  Theorem termination: t -> forall le m, P le m ->\n    (exists out le' m', exec_stmt genv env le m (Sloop body Sskip) E0 le' m' out /\\\n      ((exists v, out = Out_return v /\\ R le' m' v) \\/ (out = Out_normal /\\ Q le' m'))).\n  Proof.\n    destruct 1; simpl.\n    intros.\n    generalize (P_implies_I0 le m H).\n    intro.\n    destruct H0 as [n0].\n    clear H.\n    revert le m H0.\n    induction n0 using (well_founded_ind lt_wf0).\n\n    intros.\n    \n    generalize (I_invariant0 le m n0 H0).\n    intro I_invariant.\n    destruct I_invariant as [out tinv].\n    destruct tinv as [le' tinv].\n    destruct tinv as [m' tinv].\n    destruct tinv as [Inv1 tinv].\n    destruct tinv as [Inv2 tinv].\n    destruct tinv as [Inv3 Inv4].\n    \n    destruct out.\n\n    (* out = Out_break *)\n    exists Out_normal.\n    exists le'.\n    exists m'.\n    split.\n    econstructor.\n    eassumption.\n    econstructor.\n    right.\n    split.\n    trivial.\n    apply Inv3.\n    trivial.\n\n    (* out = Out_continue *)\n    destruct Inv2 as [n'].\n    auto.\n    destruct H1.\n    generalize (H n' H1 le' m' H2).\n    intro.\n    destruct H3 as [out].\n    destruct H3 as [le'0'].\n    destruct H3 as [m'0].\n    destruct H3.\n    destruct H4.\n      (* finalout = Out_return *)\n      destruct H4 as [v].\n      destruct H4.\n      esplit. esplit. esplit.\n      split.\n      change E0 with (E0 ** E0 ** E0).\n      eapply exec_Sloop_loop.\n      eassumption.\n      econstructor.\n      econstructor.\n      eassumption.\n      subst.\n      left.\n      exists v.\n      auto.\n      (* finalout = Out_normal *)\n      destruct H4.\n      esplit. esplit. esplit.\n      split.\n      change E0 with (E0 ** E0 ** E0).\n      eapply exec_Sloop_loop.\n      eassumption.\n      econstructor.\n      econstructor.\n      eassumption.\n      subst.\n      right.\n      auto.\n\n    (* out = Out_normal *)\n    destruct Inv2 as [n'].\n    auto.\n    destruct H1.\n    generalize (H n' H1 le' m' H2).\n    intro.\n    destruct H3 as [out].\n    destruct H3 as [le'0'].\n    destruct H3 as [m'0].\n    destruct H3.\n    destruct H4.\n      (* finalout = Out_return *)\n      destruct H4 as [v].\n      destruct H4.\n      esplit. esplit. esplit.\n      split.\n      change E0 with (E0 ** E0 ** E0).\n      eapply exec_Sloop_loop.\n      eassumption.\n      econstructor.\n      econstructor.\n      eassumption.\n      subst.\n      left.\n      exists v.\n      auto.\n      (* finalout = Out_normal *)\n      destruct H4.\n      esplit. esplit. esplit.\n      split.\n      change E0 with (E0 ** E0 ** E0).\n      eapply exec_Sloop_loop.\n      eassumption.\n      econstructor.\n      econstructor.\n      eassumption.\n      subst.\n      right.\n      auto.\n\n    (* out = Out_return *)\n    exists (Out_return o).\n    exists le'.\n    exists m'.\n    split.\n    econstructor.\n    eassumption.\n    econstructor.\n    left.\n    exists o.\n    auto.\n  Qed.\n\nEnd S.\nEnd LoopProof.\n\n\n\n\nModule LoopProofWhileWithContinue.\n\nSection S.\n\n  Context `{Hcc: Events.CompilerConfiguration}\n          `{Hwb: Events.WritableBlock}.\n\n  Variables (condition: expr) (body: statement) \n            (genv: genv) (env: env)\n            (P Q: temp_env -> mem -> Prop).\n\n  Record t  : Type := make {\n         W: Type;\n         lt: W-> W-> Prop;\n         lt_wf: well_founded lt;\n         I: temp_env-> mem-> W-> Prop;\n         P_implies_I: forall le m, P le m-> exists n0, I le m n0;\n         I_invariant:\n         forall le m n, I le m n-> exists v b, (eval_expr genv env le m condition v /\\\n            (bool_val v (typeof condition) = Some b) /\\\n            (b = false -> Q le m) /\\\n            (b = true -> \n             exists out le' m', exec_stmt genv env le m body E0 le' m' out /\\\n             (out = Out_normal \\/ out = Out_continue) /\\\n             exists n', lt n' n /\\ I le' m' n'\n           ))\n  }.\n\n  Theorem termination: t -> forall le m, P le m ->\n    (exists le' m', exec_stmt genv env le m (Swhile condition body) E0 le' m' Out_normal /\\ Q le' m').\n  Proof.\n    unfold Swhile.\n    destruct 1; simpl.\n    intros.\n    generalize (P_implies_I0 le m H).\n    intro.\n    destruct H0 as [n0].\n    clear H.\n    revert le m H0.\n    induction n0 using (well_founded_ind lt_wf0).\n\n    intros.\n    \n    generalize (I_invariant0 le m n0 H0).\n    intro I_invariant.\n    destruct I_invariant as [v tinv].\n    destruct tinv as [b tinv].\n    destruct tinv as [evalexpr tinv].\n    destruct tinv as [boolval tinv].\n    destruct tinv as [condfalse tinv].\n\n    destruct b.\n\n    (* b = true *)\n    \n    destruct tinv as [out tinv]; trivial.\n    destruct tinv as [le' tinv].\n    destruct tinv as [m' tinv].\n    destruct tinv as [Inv1 tinv].\n    destruct tinv as [Inv2 tinv].\n    destruct tinv as [n' tinv].\n    destruct tinv as [Inv3 Inv4].\n    destruct Inv2.\n\n    (* out = Out_normal *)\n    subst.\n    generalize (H n' Inv3 le' m' Inv4).\n    intro.\n    destruct H1 as [le'0'].\n    destruct H1 as [m'0].\n    destruct H1.\n    esplit. esplit.\n    split.\n    change E0 with (E0 ** E0 ** E0).\n    eapply exec_Sloop_loop.\n    change E0 with (E0 ** E0).\n    econstructor.\n    econstructor.\n    eassumption.\n    eassumption.\n    simpl.\n    econstructor.\n    eassumption.\n    econstructor.\n    econstructor.\n    eassumption.\n    eassumption.\n\n    (* out = Out_continue *)\n    subst.\n    generalize (H n' Inv3 le' m' Inv4).\n    intro.\n    destruct H1 as [le'0'].\n    destruct H1 as [m'0].\n    destruct H1.\n    esplit. esplit.\n    split.\n    change E0 with (E0 ** E0 ** E0).\n    eapply exec_Sloop_loop.\n    change E0 with (E0 ** E0).\n    econstructor.\n    econstructor.\n    eassumption.\n    eassumption.\n    simpl.\n    econstructor.\n    eassumption.\n    econstructor.\n    econstructor.\n    eassumption.\n    eassumption.\n\n    (* b = false *)\n    exists le.\n    exists m.\n    split.\n    eapply exec_Sloop_stop1.\n    econstructor.\n    econstructor.\n    eassumption.\n    eassumption.\n    simpl.\n    econstructor.\n    congruence.\n    econstructor.\n    auto.\n  Qed.\n\nEnd S.\nEnd LoopProofWhileWithContinue.\n\n\n\nModule LoopProofSimpleWhile.\n\nSection S.\n\n  Context `{Hcc: Events.CompilerConfiguration}\n          `{Hwb: Events.WritableBlock}.\n\n  Variables (condition: expr) (body: statement) \n            (genv: genv) (env: env)\n            (P Q: temp_env -> mem -> Prop).\n\n  Record t  : Type := make {\n         W: Type;\n         lt: W-> W-> Prop;\n         lt_wf: well_founded lt;\n         I: temp_env-> mem-> W-> Prop;\n         P_implies_I: forall le m, P le m-> exists n0, I le m n0;\n         I_invariant:\n         forall le m n, I le m n-> exists v b, (eval_expr genv env le m condition v /\\\n            (bool_val v (typeof condition) = Some b) /\\\n            (b = false -> Q le m) /\\\n            (b = true -> \n             exists le' m', exec_stmt genv env le m body E0 le' m' Out_normal /\\\n             exists n', lt n' n /\\ I le' m' n'\n           ))\n  }.\n\n  Theorem termination: t -> forall le m, P le m ->\n    (exists le' m', exec_stmt genv env le m (Swhile condition body) E0 le' m' Out_normal /\\ Q le' m').\n  Proof.\n    unfold Swhile.\n    destruct 1; simpl.\n    intros.\n    generalize (P_implies_I0 le m H).\n    intro.\n    destruct H0 as [n0].\n    clear H.\n    revert le m H0.\n    induction n0 using (well_founded_ind lt_wf0).\n\n    intros.\n    \n    generalize (I_invariant0 le m n0 H0).\n    intro I_invariant.\n    destruct I_invariant as [v tinv].\n    destruct tinv as [b tinv].\n    destruct tinv as [evalexpr tinv].\n    destruct tinv as [boolval tinv].\n    destruct tinv as [condfalse tinv].\n\n    destruct b.\n\n    (* b = true *)\n    \n    destruct tinv as [le' tinv]; trivial.\n    destruct tinv as [m' tinv].\n    destruct tinv as [Inv1 tinv].\n    destruct tinv as [n' tinv].\n    destruct tinv as [Inv2 Inv3].\n\n    generalize (H n' Inv2 le' m' Inv3).\n    intro.\n    destruct H1 as [le'0'].\n    destruct H1 as [m'0].\n    destruct H1.\n    esplit. esplit.\n    split.\n    change E0 with (E0 ** E0 ** E0).\n    eapply exec_Sloop_loop.\n    change E0 with (E0 ** E0).\n    econstructor.\n    econstructor.\n    eassumption.\n    eassumption.\n    simpl.\n    econstructor.\n    eassumption.\n    econstructor.\n    econstructor.\n    eassumption.\n    eassumption.\n\n    (* b = false *)\n    exists le.\n    exists m.\n    split.\n    eapply exec_Sloop_stop1.\n    econstructor.\n    econstructor.\n    eassumption.\n    eassumption.\n    simpl.\n    econstructor.\n    congruence.\n    econstructor.\n    auto.\n  Qed.\n\nEnd S.\nEnd LoopProofSimpleWhile.", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/clib/LoopProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2906783513965133}}
{"text": "Require Import CoRN.algebra.RSetoid.\nRequire Import CoRN.metric2.Metric.\nRequire Import CoRN.metric2.UniformContinuity.\nRequire Import\n  Coq.QArith.QArith\n  MathClasses.theory.setoids (* Equiv Prop *) MathClasses.theory.products\n  MathClasses.implementations.stdlib_rationals (*Qinf*) (*Qpossec QposInf QnonNeg*) MathClasses.interfaces.abstract_algebra MathClasses.implementations.QType_rationals MathClasses.interfaces.additional_operations.\nRequire CoRN.model.structures.Qinf.\n(*Import (*QnonNeg.notations*) QArith.*)\nRequire Import CoRN.tactics.Qauto Coq.QArith.QOrderedType.\n(*Require Import orders.*)\nRequire Import MathClasses.theory.rings MathClasses.theory.dec_fields MathClasses.orders.rings MathClasses.orders.dec_fields MathClasses.theory.nat_pow.\nRequire Import MathClasses.interfaces.naturals MathClasses.interfaces.orders.\nImport peano_naturals.\n\nRequire Import CoRN.reals.fast.CRGeometricSum.\nImport Qround Qpower Qinf.notations Qinf.coercions.\n\n(* Set Printing Coercions.*)\n\nDefinition ext_plus {A} `{Plus B} : Plus (A -> B) := λ f g x, f x + g x.\n#[global]\nHint Extern 10 (Plus (_ -> _)) => apply @ext_plus : typeclass_instances.\n\nDefinition ext_negate {A} `{Negate B} : Negate (A -> B) := λ f x, - (f x).\n#[global]\nHint Extern 10 (Negate (_ -> _)) => apply @ext_negate : typeclass_instances.\n\n(* The definitions above replace the following.\nNotation \"f +1 g\" := (λ x, f x + g x) (at level 50, left associativity).*)\n\nDefinition comp_inf {X Z : Type} (g : Q -> Z) (f : X -> Qinf) (inf : Z) (x : X) :=\nmatch (f x) with\n| Qinf.finite y => g y\n| Qinf.infinite => inf\nend.\n\n(* [po_proper'] is useful for proving [a2 ≤ b2] from [H : a1 ≤ b1] when\n[a1 = a2] and [b1 = b2]. Then [apply (po_proper' H)] generates [a1 = a2]\nand [b1 = b2]. Should it be moved to MathClasses? *)\nLemma po_proper' `{PartialOrder A} {x1 x2 y1 y2 : A} :\n  x1 ≤ y1 -> x1 = x2 -> y1 = y2 -> x2 ≤ y2.\nProof. intros A1 A2 A3; now apply (po_proper _ _ A2 _ _ A3). Qed.\n\n(* This is a special case of lt_ne_flip. Do we need it? *)\n(*Instance pos_ne_0 : forall `{StrictSetoidOrder A} `{Zero A} (x : A),\n  PropHolds (0 < x) -> PropHolds (x ≠ 0).\nProof. intros; now apply lt_ne_flip. Qed.*)\n\nDefinition ext_equiv' `{Equiv A} `{Equiv B} : Equiv (A → B) :=\n  λ f g, ∀ x : A, f x = g x.\n\nInfix \"=1\" := ext_equiv' (at level 70, no associativity) : type_scope.\n\nLemma ext_equiv_l `{Setoid A, Setoid B} (f g : A -> B) :\n  Proper ((=) ==> (=)) f -> f =1 g -> f = g.\nProof. intros P eq1_f_g x y eq_x_y; rewrite eq_x_y; apply eq1_f_g. Qed.\n\nLemma ext_equiv_r `{Setoid A, Setoid B} (f g : A -> B) :\n  Proper ((=) ==> (=)) g -> f =1 g -> f = g.\nProof. intros P eq1_f_g x y eq_x_y; rewrite <- eq_x_y; apply eq1_f_g. Qed.\n\n(*Ltac MCQconst t :=\nmatch t with\n(*| @zero Q _ _ => constr:(Qmake Z0 xH)\n| @one Q _ _ => constr:(Qmake (Zpos xH) xH)*)\n| _ => Qcst t\nend.\n\nAdd Field Q : (stdlib_field_theory Q)\n  (decidable Qeq_bool_eq,\n   completeness Qeq_eq_bool,\n   constants [MCQconst]).\n\nGoal forall x y : Q, (1#1)%Q * x = x.\nintros x y. ring.*)\n\n(*\nLocal Notation Qnn := QnonNeg.T.\n\nInstance Qnn_eq : Equiv Qnn := eq.\nInstance Qnn_zero : Zero Qnn := QnonNeg.zero.\nInstance Qnn_one : One Qnn := QnonNeg.one.\nInstance Qnn_plus : Plus Qnn := QnonNeg.plus.\nInstance Qnn_mult : Mult Qnn := QnonNeg.mult.\nInstance Qnn_inv : DecRecip Qnn := QnonNeg.inv.\n\nInstance Qpos_eq : Equiv Qpos := Qpossec.QposEq.\nInstance Qpos_one : One Qpos := Qpossec.Qpos_one.\nInstance Qpos_plus : Plus Qpos := Qpossec.Qpos_plus.\nInstance Qpos_mult : Mult Qpos := Qpossec.Qpos_mult.\nInstance Qpos_inv : DecRecip Qpos := Qpossec.Qpos_inv.\n\nInstance Qinf_one : One Qinf := 1%Q.\n*)\n\n#[global]\nInstance Qinf_le : Le Qinf := Qinf.le.\n#[global]\nInstance Qinf_lt : Lt Qinf := Qinf.lt.\n\n(*\nLtac mc_simpl := unfold\n  equiv, zero, one, plus, negate, mult, dec_recip, le, lt.\n\nLtac Qsimpl' := unfold\n  Qnn_eq, Qnn_zero, Qnn_one, Qnn_plus, Qnn_mult, Qnn_inv,\n  QnonNeg.eq, QnonNeg.zero, QnonNeg.one, QnonNeg.plus, QnonNeg.mult, QnonNeg.inv,\n  Qpos_eq, Qpos_one, Qpos_plus, Qpos_mult, Qpos_inv,\n  Qpossec.QposEq, Qpossec.Qpos_one, Qpossec.Qpos_plus, Qpossec.Qpos_mult, Qpossec.Qpos_inv,\n  Qinf.eq, Qinf.lt, Qinf_lt, Qinf_one, Zero_instance_0 (* Zero Qinf *),\n  Q_eq, Q_lt, Q_le, Q_0, Q_1, Q_opp, Q_plus, Q_mult, Q_recip;\n  mc_simpl;\n  unfold to_Q, QposAsQ;\n  simpl.\n\nLtac nat_simpl := unfold\n  nat_equiv, nat_0, nat_1, nat_plus, nat_plus, nat_mult, nat_le, nat_lt;\n  mc_simpl;\n  simpl.\n\nTactic Notation \"Qsimpl\" hyp_list(A) := revert A; Qsimpl'; intros A.\n*)\n\nBind Scope mc_scope with Q.\n\n(*Section QField.*)\n\nAdd Field Q : (stdlib_field_theory Q).\n\nClass MetricSpaceBall (X : Type) : Type := mspc_ball: Qinf → relation X.\n\nLocal Notation ball := mspc_ball.\n\n(* In the proof of Banach fixpoint theorem we have to use arithmetic\nexpressions such as q^n / (1 - q) when 0 <= q < 1 as the ball radius. If\nthe radius is in Qnn (ie., QnonNeg.T), then we have to prove that 1 - q :\nQnn. It seems more convenient to have the radius live in Q and have the\naxiom that no points are separated by a negative distance. *)\n\nClass ExtMetricSpaceClass (X : Type) `{MetricSpaceBall X} : Prop := {\n  mspc_radius_proper : Proper ((=) ==> (≡) ==> (≡) ==> iff) ball;\n  mspc_inf: ∀ x y, ball Qinf.infinite x y;\n  mspc_negative: ∀ (e: Q), e < 0 → ∀ x y, ~ ball e x y;\n  mspc_refl:> ∀ e : Q, 0 ≤ e → Reflexive (ball e);\n  mspc_symm:> ∀ e, Symmetric (ball e);\n  mspc_triangle: ∀ (e1 e2: Q) (a b c: X),\n     ball e1 a b → ball e2 b c → ball (e1 + e2) a c;\n  mspc_closed: ∀ (e: Q) (a b: X),\n     (∀ d: Q, 0 < d -> ball (e + d) a b) → ball e a b\n}.\n\nClass MetricSpaceDistance (X : Type) := msd : X -> X -> Q.\n\nClass MetricSpaceClass (X : Type) `{ExtMetricSpaceClass X} `{MetricSpaceDistance X} : Prop :=\n  mspc_distance : forall x1 x2 : X, ball (msd x1 x2) x1 x2.\n\nSection ExtMetricSpace.\n\nContext `{ExtMetricSpaceClass X}.\n\nGlobal Instance mspc_equiv : Equiv X := λ x1 x2, ball 0%Q x1 x2.\n\nGlobal Instance mspc_setoid : Setoid X.\nProof.\nconstructor.\n+ now apply mspc_refl.\n+ apply mspc_symm.\n+ intros x1 x2 x3 eq12 eq23.\n  unfold mspc_equiv, equiv; change 0%Q with (0%Q + 0%Q); now apply mspc_triangle with (b := x2).\nQed.\n\nGlobal Instance mspc_proper : Proper ((=) ==> (=) ==> (=) ==> iff) ball.\nProof.\nassert (A := @mspc_radius_proper X _ _).\nintros e1 e2 Ee1e2 x1 x2 Ex1x2 y1 y2 Ey1y2;\ndestruct e1 as [e1 |]; destruct e2 as [e2 |]; split; intro B; try apply mspc_inf;\ntry (unfold Qinf.eq, equiv in *; contradiction).\n+ mc_setoid_replace e2 with (0 + (e2 + 0)) by ring.\n  apply mspc_triangle with (b := x1); [apply mspc_symm, Ex1x2 |].\n  now apply mspc_triangle with (b := y1); [rewrite <- Ee1e2 |].\n+ mc_setoid_replace e1 with (0 + (e1 + 0)) by ring.\n  apply mspc_triangle with (b := x2); [apply Ex1x2 |].\n  now apply mspc_triangle with (b := y2); [rewrite Ee1e2 | apply mspc_symm].\nQed.\n\nLemma mspc_refl' (e : Qinf) : 0 ≤ e → Reflexive (ball e).\nProof.\nintros E. destruct e as [e |].\n+ apply mspc_refl, E.\n+ intro x; apply mspc_inf.\nQed.\n\nLemma mspc_triangle' :\n  ∀ (q1 q2 : Q) (x2 x1 x3 : X) (q : Q),\n    q1 + q2 = q → ball q1 x1 x2 → ball q2 x2 x3 → ball q x1 x3.\nProof.\nintros q1 q2 x2 x1 x3 q A1 A2 A3. rewrite <- A1. eapply mspc_triangle; eauto.\nQed.\n\nLemma mspc_monotone :\n  ∀ q1 q2 : Q, q1 ≤ q2 -> ∀ x y : X, ball q1 x y → ball q2 x y.\nProof.\nintros q1 q2 A1 x y A2.\napply (mspc_triangle' q1 (q2 - q1) y); [ring | trivial |]. apply mspc_refl.\napply (order_preserving (+ (-q1))) in A1. now rewrite plus_negate_r in A1.\nQed.\n\nLemma mspc_monotone' :\n  ∀ q1 q2 : Qinf, q1 ≤ q2 -> ∀ x y : X, ball q1 x y → ball q2 x y.\nProof.\nintros [q1 |] [q2 |] A1 x y A2; try apply mspc_inf.\n+ apply (mspc_monotone q1); trivial.\n+ elim A1.\nQed.\n\nLemma mspc_eq : ∀ x y : X, (∀ e : Q, 0 < e -> ball e x y) ↔ x = y.\nProof.\nintros x y; split; intro A.\n+ apply mspc_closed; intro d. change 0%Q with (@zero Q _); rewrite plus_0_l; apply A.\n+ intros e e_pos. apply (mspc_monotone 0); trivial; solve_propholds.\nQed.\n\nLemma radius_nonneg (x y : X) (e : Q) : ball e x y -> 0 ≤ e.\nProof.\nintro A. destruct (le_or_lt 0 e) as [A1 | A1]; [trivial |].\ncontradict A; now apply mspc_negative.\nQed.\n\nEnd ExtMetricSpace.\n\nSection MetricSpace.\n\nContext `{MetricSpaceClass X}.\n\nLemma msd_nonneg (x1 x2 : X) : 0 ≤ msd x1 x2.\nProof. apply (radius_nonneg x1 x2), mspc_distance. Qed.\n\nEnd MetricSpace.\n\nSection SubMetricSpace.\n\nContext `{ExtMetricSpaceClass X} (P : X -> Prop).\n\nGlobal Instance sig_mspc_ball : MetricSpaceBall (sig P) := λ e x y, ball e (`x) (`y).\n\nGlobal Instance sig_mspc : ExtMetricSpaceClass (sig P).\nProof.\nconstructor.\n+ repeat intro; rapply mspc_radius_proper; congruence.\n+ repeat intro; rapply mspc_inf.\n+ intros; now rapply mspc_negative.\n+ repeat intro; now rapply mspc_refl.\n+ repeat intro; now rapply mspc_symm.\n+ repeat intro; rapply mspc_triangle; eauto.\n+ repeat intro; now rapply mspc_closed.\nQed.\n\nContext {d : MetricSpaceDistance X} {MSC : MetricSpaceClass X}.\n\nGlobal Instance sig_msd : MetricSpaceDistance (sig P) := λ x y, msd (`x) (`y).\n\nGlobal Instance sig_mspc_distance : MetricSpaceClass (sig P).\nProof. intros x1 x2; apply: mspc_distance. Qed.\n\nEnd SubMetricSpace.\n\nSection ProductMetricSpace.\n\nContext `{ExtMetricSpaceClass X, ExtMetricSpaceClass Y}.\n\nGlobal Instance Linf_product_metric_space_ball : MetricSpaceBall (X * Y) :=\n  λ e a b, ball e (fst a) (fst b) /\\ ball e (snd a) (snd b).\n\nLemma product_ball_proper : Proper ((=) ==> (≡) ==> (≡) ==> iff) ball.\nProof.\nintros e1 e2 A1 a1 a2 A2 b1 b2 A3.\nunfold mspc_ball, Linf_product_metric_space_ball.\nrewrite A1, A2, A3; reflexivity.\nQed.\n\nGlobal Instance Linf_product_metric_space_class : ExtMetricSpaceClass (X * Y).\nProof.\nconstructor.\n+ apply product_ball_proper.\n+ intros x y; split; apply mspc_inf.\n+ intros e e_neg x y [A _]. eapply (@mspc_negative X); eauto.\n+ intros e e_nonneg x; split; apply mspc_refl; trivial.\n+ intros e a b [A1 A2]; split; apply mspc_symm; trivial.\n+ intros e1 e2 a b c [A1 A2] [B1 B2]; split; eapply mspc_triangle; eauto.\n+ intros e a b A; split; apply mspc_closed; firstorder.\nQed.\n\nContext {dx : MetricSpaceDistance X} {dy : MetricSpaceDistance Y}\n  {MSCx : MetricSpaceClass X} {MSCy : MetricSpaceClass Y}.\n\n(* Need consistent names of instances for sig, product and func *)\n\nGlobal Instance Linf_product_msd : MetricSpaceDistance (X * Y) :=\n  λ a b, join (msd (fst a) (fst b)) (msd (snd a) (snd b)).\n\nGlobal Instance Linf_product_mspc_distance : MetricSpaceClass (X * Y).\nProof.\nintros z1 z2; split.\n(* Without unfolding Linf_product_msd, the following [apply join_ub_l] fails *)\n+ apply (mspc_monotone (msd (fst z1) (fst z2)));\n  [unfold msd, Linf_product_msd; apply join_ub_l | apply mspc_distance].\n+ apply (mspc_monotone (msd (snd z1) (snd z2)));\n  [unfold msd, Linf_product_msd; apply join_ub_r | apply mspc_distance].\nQed.\n\nEnd ProductMetricSpace.\n\n(** We define [Func T X Y] if there is a coercion func from T to (X -> Y),\ni.e., T is a type of functions. It can be instatiated with (locally)\nuniformly continuous function, (locally) Lipschitz functions, contractions\nand so on. For instances T of [Func] we can define supremum metric ball\n(i.e., L∞ metric) and prove that T is a metric space. [Func T X Y] is\nsimilar to [Cast T (X -> Y)], but [cast] has types as explicit arguments,\nso for [f : T] one would have to write [cast _ _ f x] instead of [func f x]. *)\n\nClass Func (T X Y : Type) := func : T -> X -> Y.\n\nSection FunctionMetricSpace.\n\nContext {X Y T : Type} `{Func T X Y, NonEmpty X, ExtMetricSpaceClass Y}.\n\n(* For any type that is convertible to functions we want to define the\nsupremum metric. This would give rise to an equality and a setoid\n([mspc_equiv] and [mspc_setoid]). Thus, when Coq needs equality on any type\nT at all, it may try to prove that T is a metric space by showing that T is\nconvertible to functions, i.e., there is an in instance of [Func T X Y] for\nsome types X, Y. This is why we make [Func T X Y] the first assumption\nabove. This way, if there is no instance of this class, the search for\n[MetricSpaceBall T] fails quickly and Coq starts looking for an equality on\nT using other means. If we make, for example, [ExtMetricSpaceClass Y] the\nfirst assumption, Coq may eneter in an infinite loop: To find\n[MetricSpaceBall T] it will look for [ExtMetricSpaceClass Y] for some\nuninstantiated Y, for this in needs [MetricSpaceBall Y] and so on. This is\nall because Coq proves assumptions (i.e., searches instances of classes) in\nthe order of the assumptions. *)\n\nGlobal Instance Linf_func_metric_space_ball : MetricSpaceBall T :=\n  λ e f g, forall x, ball e (func f x) (func g x).\n\nLemma func_ball_proper : Proper ((=) ==> (≡) ==> (≡) ==> iff) (ball (X := T)).\nProof.\nintros q1 q2 A1 f1 f2 A2 g1 g2 A3; rewrite A2, A3.\nsplit; intros A4 x; [rewrite <- A1 | rewrite A1]; apply A4.\nQed.\n\nLemma Linf_func_metric_space_class : ExtMetricSpaceClass T.\nProof.\nmatch goal with | H : NonEmpty X |- _ => destruct H as [x0] end.\nconstructor.\n+ apply func_ball_proper.\n+ intros f g x; apply mspc_inf.\n+ intros e e_neg f g A. specialize (A x0). eapply mspc_negative; eauto.\n+ intros e e_nonneg f x; now apply mspc_refl.\n+ intros e f g A x; now apply mspc_symm.\n+ intros e1 e2 f g h A1 A2 x. now apply mspc_triangle with (b := func g x).\n+ intros e f g A x. apply mspc_closed; intros d A1. now apply A.\nQed.\n\nEnd FunctionMetricSpace.\n\nSection UniformContinuity.\n\nContext `{MetricSpaceBall X, MetricSpaceBall Y}.\n\nClass IsUniformlyContinuous (f : X -> Y) (mu : Q -> Qinf) := {\n  uc_pos : forall e : Q, 0 < e -> (0 < mu e);\n  uc_prf : ∀ (e : Q) (x1 x2: X), 0 < e -> ball (mu e) x1 x2 → ball e (f x1) (f x2)\n}.\n\nGlobal Arguments uc_pos f mu {_} e _.\nGlobal Arguments uc_prf f mu {_} e x1 x2 _ _.\n\nRecord UniformlyContinuous := {\n  uc_func :> X -> Y;\n  uc_mu : Q -> Qinf;\n  uc_proof : IsUniformlyContinuous uc_func uc_mu\n}.\n\n(* We will prove next that IsUniformlyContinuous is a subclass of Proper,\ni.e., uniformly continuous functions are morphisms. But if we have [f :\nUniformlyContinuous], in order for uc_func f to be considered a morphism,\nwe need to declare uc_proof an instance. *)\nGlobal Existing Instance uc_proof.\n\nGlobal Instance uc_proper {H1 : ExtMetricSpaceClass X} {H2 : ExtMetricSpaceClass Y}\n       {f : X → Y} {mu : Q → Qinf} {_ : IsUniformlyContinuous f mu}\n  :  Proper ((=) ==> (=)) f.\nProof.\nintros x1 x2 A. apply -> mspc_eq. intros e e_pos. apply (uc_prf f mu); trivial.\npose proof (uc_pos f mu e e_pos) as ?.\ndestruct (mu e); [apply mspc_eq; trivial | apply mspc_inf].\nQed.\n\nEnd UniformContinuity.\n\nGlobal Arguments UniformlyContinuous X {_} Y {_}.\n\n(* In [compose_uc] below, if we don't explicitly specify [Z] as an\nargument, then [`{MetricSpaceBall Z}] does not generalize [Z] but rather\ninterprets it as integers. For symmetry we specify [X] and [Y] as well. *)\nGlobal Instance compose_uc {X Y Z : Type}\n  `{MetricSpaceBall X, ExtMetricSpaceClass Y, MetricSpaceBall Z}\n  (f : X -> Y) (g : Y -> Z) (f_mu g_mu : Q -> Qinf)\n  `{!IsUniformlyContinuous f f_mu, !IsUniformlyContinuous g g_mu} :\n    IsUniformlyContinuous (g ∘ f) (comp_inf f_mu g_mu Qinf.infinite).\nProof.\nconstructor.\n+ intros e e_pos. assert (0 < g_mu e) by (apply (uc_pos g); trivial).\n  unfold comp_inf. destruct (g_mu e); [apply (uc_pos f) |]; trivial.\n+ intros e x1 x2 e_pos A. unfold compose. apply (uc_prf g g_mu); trivial.\n  assert (0 < g_mu e) by (apply (uc_pos g); trivial).\n  unfold comp_inf in A. destruct (g_mu e) as [e' |]; [| apply mspc_inf].\n  apply (uc_prf f f_mu); trivial.\nQed.\n\nGlobal Instance uniformly_continuous_func `{MetricSpaceBall X, MetricSpaceBall Y} :\n  Func (UniformlyContinuous X Y) X Y := λ f, f.\n\n#[global]\nHint Extern 10 (ExtMetricSpaceClass (UniformlyContinuous _ _)) =>\n  apply @Linf_func_metric_space_class : typeclass_instances.\n\nSection LocalUniformContinuity.\n\nContext `{MetricSpaceBall X, MetricSpaceBall Y}.\n\nDefinition restrict (f : X -> Y) (x : X) (r : Q) : sig (ball r x) -> Y :=\n  f ∘ @proj1_sig _ _.\n\n(* See the remark about llip_prf below about the loop between\nIsUniformlyContinuous and IsLocallyUniformlyContinuous *)\n\nClass IsLocallyUniformlyContinuous (f : X -> Y) (lmu : X -> Q -> Q -> Qinf) :=\n  luc_prf :> forall (x : X) (r : Q), IsUniformlyContinuous (restrict f x r) (lmu x r).\n\nGlobal Arguments luc_prf f lmu {_} x r.\n\nGlobal Instance uc_ulc (f : X -> Y)\n       {mu : Q → Qinf}  {_ : IsUniformlyContinuous f mu}\n  : IsLocallyUniformlyContinuous f (λ _ _, mu).\nProof.\nintros x r. constructor; [now apply (uc_pos f) |].\nintros e [x1 A1] [x2 A2] e_pos A. now apply (uc_prf f mu).\nQed.\n\nGlobal Instance luc_proper\n  {_ : ExtMetricSpaceClass X} {_ : ExtMetricSpaceClass Y}\n  (f : X -> Y) `{!IsLocallyUniformlyContinuous f lmu} : Proper ((=) ==> (=)) f.\nProof.\nintros x1 x2 A. apply -> mspc_eq. intros e e_pos.\nassert (A1 : ball 1%Q x1 x1) by (apply mspc_refl; Qauto_nonneg).\nassert (A2 : ball 1%Q x1 x2) by (rewrite A; apply mspc_refl; Qauto_nonneg).\nchange (ball e (restrict f x1 1 (exist _ x1 A1)) (restrict f x1 1 (exist _ x2 A2))).\nunfold IsLocallyUniformlyContinuous in *. apply (uc_prf _ (lmu x1 1)); [easy |].\nchange (ball (lmu x1 1 e) x1 x2).\nrewrite <- A. assert (0 < lmu x1 1 e) by now apply (uc_pos (restrict f x1 1)).\ndestruct (lmu x1 1 e) as [q |]; [apply mspc_refl; solve_propholds | apply mspc_inf].\nQed.\n\nLemma luc (f : X -> Y) `{IsLocallyUniformlyContinuous f lmu} (r e : Q) (a x y : X) :\n  0 < e -> ball r a x -> ball r a y -> ball (lmu a r e) x y -> ball e (f x) (f y).\nProof.\nintros e_pos A1 A2 A3.\nchange (f x) with (restrict f a r (exist _ x A1)).\nchange (f y) with (restrict f a r (exist _ y A2)).\napply uc_prf with (mu := lmu a r); trivial.\n(* The predicate symbol of the goal is IsUniformlyContinuous, which is a\ntype class. Yet, without [trivial] above, instead of solving it by [apply\nH3], Coq gives it as a subgoal. *)\nQed.\n\nEnd LocalUniformContinuity.\n\nSection Lipschitz.\n\nContext `{MetricSpaceBall X, MetricSpaceBall Y}.\n\nClass IsLipschitz (f : X -> Y) (L : Q) := {\n  lip_nonneg : 0 ≤ L;\n  lip_prf : forall (x1 x2 : X) (e : Q), ball e x1 x2 -> ball (L * e) (f x1) (f x2)\n}.\n\nGlobal Arguments lip_nonneg f L {_} _.\nGlobal Arguments lip_prf f L {_} _ _ _ _.\n\nRecord Lipschitz := {\n  lip_func :> X -> Y;\n  lip_const : Q;\n  lip_proof : IsLipschitz lip_func lip_const\n}.\n\nDefinition lip_modulus (L e : Q) : Qinf :=\n  if (decide (L = 0)) then Qinf.infinite else e / L.\n\nLemma lip_modulus_pos (L e : Q) : 0 ≤ L -> 0 < e -> 0 < lip_modulus L e.\nProof.\nintros L_nonneg e_pos. unfold lip_modulus.\ndestruct (decide (L = 0)) as [A1 | A1]; [apply I |].\napply not_symmetry in A1.\nchange (0 < e / L). (* Changes from Qinf, which is not declared as ordered ring, to Q *)\nassert (0 < L) by now apply QOrder.le_neq_lt. Qauto_pos.\nQed.\n\n(* It is nice to declare only [MetricSpaceBall X] above because this is all\nwe need to know about X to define [IsLipschitz]. But for the following\ntheorem we also need [ExtMetricSpaceClass X], [MetricSpaceDistance X] and\n[MetricSpaceClass X]. How to add these assumptions? Saying\n[`{MetricSpaceClass X}] would add a second copy of [MetricSpaceBall X]. We\nwrite the names EM and m below because \"Anonymous variables not allowed in\ncontexts\" *)\n\nContext {EM : ExtMetricSpaceClass X} {m : MetricSpaceDistance X}.\n\nGlobal Instance lip_uc {_ : MetricSpaceClass X} {_ : ExtMetricSpaceClass Y}\n  (f : X -> Y) `{!IsLipschitz f L} :\n  IsUniformlyContinuous f (lip_modulus L).\nProof.\nconstructor.\n+ intros. apply lip_modulus_pos; [| assumption]. now apply (lip_nonneg f L).\n+ unfold lip_modulus. intros e x1 x2 A1 A2. destruct (decide (L = 0)) as [A | A].\n  - apply mspc_eq; [| easy]. unfold canonical_names.equiv, mspc_equiv. rewrite <- (Qmult_0_l (msd x1 x2)), <- A.\n    now apply lip_prf; [| apply mspc_distance].\n  - mc_setoid_replace e with (L * (e / L)) by now field.\n    now apply lip_prf.\nQed.\n\nEnd Lipschitz.\n\n(* To be able to say [Lipschitz X Y] instead of [@Lipschitz X _ Y _] *)\nGlobal Arguments Lipschitz X {_} Y {_}.\n\n(* Allows concluding [IsLipschitz f _] from [f : Lipschitz] *)\nGlobal Existing Instance lip_proof.\n\n(* We need [ExtMetricSpaceClass Z] because we rewrite the ball radius, so\n[mspc_radius_proper] is required. See comment before [compose_uc] for why\n[{X Y Z : Type}] is necessary. *)\nGlobal Instance compose_lip {X Y Z : Type}\n  `{MetricSpaceBall X, MetricSpaceBall Y, ExtMetricSpaceClass Z}\n  (f : X -> Y) (g : Y -> Z) (Lf Lg : Q)\n  `{!IsLipschitz f Lf, !IsLipschitz g Lg} :\n    IsLipschitz (g ∘ f) (Lg * Lf).\nProof.\nconstructor.\n+ apply nonneg_mult_compat; [apply (lip_nonneg g), _ | apply (lip_nonneg f), _].\n+ intros x1 x2 e A.\n  (* [rewrite <- mult_assoc] does not work *)\n  mc_setoid_replace (Lg * Lf * e) with (Lg * (Lf * e)) by (symmetry; apply simple_associativity).\n  now apply (lip_prf g Lg), (lip_prf f Lf).\nQed.\n\n(* [ExtMetricSpaceClass X] is needed for rewriting *)\nGlobal Instance id_lip `{ExtMetricSpaceClass X} : IsLipschitz Datatypes.id 1.\nProof.\nconstructor; [solve_propholds |]. intros; now rewrite mult_1_l.\nQed.\n\nSection LocallyLipschitz.\n\nContext `{MetricSpaceBall X, MetricSpaceBall Y}.\n\n(* Delaring llip_prf below an instance introduces a loop between\n[IsLipschitz] and [IsLocallyLipschitz]. But if we are searching for a proof\nof [IsLipschitz f _] for a specific term [f], then Coq should not enter an\ninfinite loop because that would require unifying [f] with [restrict _ _ _].\nWe need this instance to apply [lip_nonneg (restrict f x r) _] in order\nto prove [0 ≤ Lf x r] when [IsLocallyLipschitz f Lf]. *)\n\n(* We make an assumption [0 ≤ r] in llip_prf below to make proving that\nfunctions are locally Lipschitz easier. As a part of such proof, one needs\nto show that [0 ≤ L x r] ([lip_nonneg]). Proving this under the assumption\n[0 ≤ r] may allow having simpler definitions of the uniform [L]. In\nparticular, integral_lipschitz in AbstractIntegration.v defines [L] as\n[λ a r, abs (f a) + L' a r * r]. *)\n\nClass IsLocallyLipschitz (f : X -> Y) (L : X -> Q -> Q) :=\n  llip_prf :> forall (x : X) (r : Q), PropHolds (0 ≤ r) -> IsLipschitz (restrict f x r) (L x r).\n\nGlobal Arguments llip_prf f L {_} x r _.\n\nGlobal Instance lip_llip (f : X -> Y) `{!IsLipschitz f L} : IsLocallyLipschitz f (λ _ _, L).\nProof.\nintros x r. constructor; [now apply (lip_nonneg f) |].\nintros [x1 x1b] [x2 x2b] e A. change (ball (L * e) (f x1) (f x2)). now apply lip_prf.\nQed.\n\nLemma llip `{!ExtMetricSpaceClass X} (f : X -> Y) `{IsLocallyLipschitz f L} (r e : Q) (a x y : X) :\n  ball r a x -> ball r a y -> ball e x y -> ball (L a r * e) (f x) (f y).\nProof.\nintros A1 A2 A3.\nchange (f x) with (restrict f a r (exist _ x A1)).\nchange (f y) with (restrict f a r (exist _ y A2)).\nassert (0 ≤ r) by now apply (radius_nonneg a x).\napply (lip_prf _ (L a r)); trivial.\nQed.\n\nRecord LocallyLipschitz := {\n  llip_func :> X -> Y;\n  llip_const : X -> Q -> Q;\n  llip_proof : IsLocallyLipschitz llip_func llip_const\n}.\n\nEnd LocallyLipschitz.\n\nGlobal Arguments LocallyLipschitz X {_} Y {_}.\n\n#[global]\nInstance locally_lipschitz_func `{MetricSpaceBall X, MetricSpaceBall Y} :\n  Func (LocallyLipschitz X Y) X Y := λ f, f.\n\n#[global]\nHint Extern 10 (ExtMetricSpaceClass (LocallyLipschitz _ _)) =>\n  apply @Linf_func_metric_space_class : typeclass_instances.\n\nNotation \"X LL-> Y\" := (LocallyLipschitz X Y) (at level 55, right associativity).\n\nSection Contractions.\n\nContext `{MetricSpaceBall X, MetricSpaceBall Y}.\n\nClass IsContraction (f : X -> Y) (q : Q) := {\n  contr_prf :> IsLipschitz f q;\n  contr_lt_1 : q < 1\n}.\n\nGlobal Arguments contr_lt_1 f q {_}.\nGlobal Arguments contr_prf f q {_}.\n\nRecord Contraction := {\n  contr_func : X -> Y;\n  contr_const : Q;\n  contr_proof : IsContraction contr_func contr_const\n}.\n\nGlobal Instance const_contr `{!ExtMetricSpaceClass Y} (c : Y) : IsContraction (λ x : X, c) 0.\nProof.\nconstructor.\n+ constructor.\n  - reflexivity.\n  - intros; apply mspc_refl.\n    rewrite mult_0_l; reflexivity.\n+ solve_propholds.\nQed.\n\n(* Do we need the following?\n\nGlobal Instance contr_to_uc `(IsContraction f q) :\n  IsUniformlyContinuous f (λ e, if (decide (q = 0)) then Qinf.infinite else (e / q)).\nProof. apply _. Qed.*)\n\nEnd Contractions.\n\nGlobal Arguments Contraction X {_} Y {_}.\n\nGlobal Instance : PreOrder Qinf.le.\nProof.\nconstructor.\n+ intros [x |]; [apply Qle_refl | easy].\n+ intros [x |] [y |] [z |]; solve [intros [] | intros _ [] | easy | apply Qle_trans].\nQed.\n\nGlobal Instance : AntiSymmetric Qinf.le.\nProof.\nintros [x |] [y |] A B; [apply Qle_antisym | elim B | elim A |]; easy.\nQed.\n\nGlobal Instance : PartialOrder Qinf.le.\nProof. constructor; apply _. Qed.\n\nGlobal Instance : TotalRelation Qinf.le.\nProof.\nintros [x |] [y |]; [change (x ≤ y \\/ y ≤ x); apply total, _ | left | right | left]; easy.\nQed.\n\nGlobal Instance : TotalOrder Qinf.le.\nProof. constructor; apply _. Qed.\n\nGlobal Instance : ∀ x y : Qinf, Decision (x ≤ y).\nintros [x |] [y |]; [change (Decision (x ≤ y)); apply _ | left | right | left]; easy.\nDefined.\n\nImport minmax.\n\n(* Instances above allow using min and max for Qinf *)\n\nSection TotalOrderLattice.\n\nContext `{TotalOrder A} `{Lt A} `{∀ x y: A, Decision (x ≤ y)}.\n\nLemma min_ind (P : A -> Prop) (x y : A) : P x → P y → P (min x y).\nProof. unfold min, sort. destruct (decide_rel _ x y); auto. Qed.\n\nLemma lt_min (x y z : A) : z < x -> z < y -> z < min x y.\nProof. apply min_ind. Qed.\n\nEnd TotalOrderLattice.\n\nSection ProductSpaceFunctions.\n\nDefinition diag {X : Type} (x : X) : X * X := (x, x).\n\nGlobal Instance diag_lip `{ExtMetricSpaceClass X} : IsLipschitz (@diag X) 1.\nProof.\nconstructor.\n+ solve_propholds.\n+ intros x1 x2 e A. rewrite mult_1_l. now split.\nQed.\n\nDefinition together {X1 Y1 X2 Y2 : Type} (f1 : X1 -> Y1) (f2 : X2 -> Y2) : X1 * X2 -> Y1 * Y2 :=\n  λ p, (f1 (fst p), f2 (snd p)).\n\n(*Global Instance together_lip\n  `{ExtMetricSpaceClass X1, ExtMetricSpaceClass Y1, ExtMetricSpaceClass X2, ExtMetricSpaceClass Y2}\n   (f1 : X1 -> Y1) (f2 : X2 -> Y2)\n  `{!IsLipschitz f1 L1, !IsLipschitz f2 L2} : IsLipschitz (together f1 f2) (join L1 L2).\n(* What if we define the Lipschitz constant for [together f1 f2] to be [max\nL1 L2], where [max] is the name of an instance of [Join A] in\norders.minmax? In fact, [Check _ : Join Q] returns [max]. I.e., [join x y]\nfor [x y : Q] reduces to [max x y]. However, it is difficult to apply\n[lattices.join_le_compat_r] to the goal [0 ≤ max L1 L2]. Simple [apply]\ndoes not work (probably because the theorem has to be reduced to match the\ngoal). As for [apply:] and [rapply], they invoke [refine (@join_le_compat_r\n_ _ ...)]. Some of the _ are implicit arguments and type classes (e.g.,\n[Equiv] [Le]), and they are instantiated with the instances found first,\nwhich happen to be for [Qinf]. Apparently, unification does not try other\ninstances. So, [apply:] with type classes is problematic.\n[apply: (@lattices.join_le_compat_r Q)] gives \"Anomaly: Evd.define: cannot define an evar twice\" *)\nProof.\nconstructor.\n+ apply lattices.join_le_compat_r, (lip_nonneg f1 L1).\n+ intros z1 z2 e [A1 A2].\n  (* Below we prove [0 ≤ e] using [radius_nonneg], which requires\n  [ExtMetricSpaceClass]. Another way is to add the assymption [0 ≤ e] to\n  [lip_prf], similar to [uc_prf]. *)\n  assert (0 ≤ e) by now apply (radius_nonneg (fst z1) (fst z2)).\n  split; simpl.\n  - apply (mspc_monotone (L1 * e)); [apply (order_preserving (.* e)); apply join_ub_l |].\n    (* [apply (order_preserving (.* e)), join_ub_l.] does not work *)\n    apply lip_prf; trivial.\n  - apply (mspc_monotone (L2 * e)); [apply (order_preserving (.* e)); apply join_ub_r |].\n    apply lip_prf; trivial.*)\n\nGlobal Instance together_uc\n  `{ExtMetricSpaceClass X1, ExtMetricSpaceClass Y1, ExtMetricSpaceClass X2, ExtMetricSpaceClass Y2}\n   (f1 : X1 -> Y1) (f2 : X2 -> Y2)\n  `{!IsUniformlyContinuous f1 mu1, !IsUniformlyContinuous f2 mu2} :\n  IsUniformlyContinuous (together f1 f2) (λ e, min (mu1 e) (mu2 e)).\nProof.\nconstructor.\n+ intros e e_pos. (* [apply min_ind] does not work if the goal has [meet] instead of [min] *)\n  apply lt_min; [apply (uc_pos f1) | apply (uc_pos f2)]; trivial.\n  (* [trivial] solves, in particular, [IsUniformlyContinuous f1 mu1], which should\n     have been solved automatically *)\n+ intros e z z' e_pos [A1 A2]. split; simpl.\n  - apply (uc_prf f1 mu1); trivial.\n    apply (mspc_monotone' (min (mu1 e) (mu2 e))); [apply: meet_lb_l | trivial].\n  - apply (uc_prf f2 mu2); trivial.\n    apply (mspc_monotone' (min (mu1 e) (mu2 e))); [apply: meet_lb_r | trivial].\nQed.\n\nEnd ProductSpaceFunctions.\n\nSection CompleteMetricSpace.\n\nContext `{MetricSpaceBall X}.\n\nClass IsRegularFunction (f : Q -> X) : Prop :=\n  rf_prf : forall e1 e2 : Q, 0 < e1 -> 0 < e2 -> ball (e1 + e2) (f e1) (f e2).\n\nRecord RegularFunction := {\n  rf_func :> Q -> X;\n  rf_proof : IsRegularFunction rf_func\n}.\n\nArguments Build_RegularFunction {_} _.\n\nGlobal Existing Instance rf_proof.\n\nGlobal Instance rf_eq : Equiv RegularFunction :=\n  λ f1 f2, forall e1 e2 : Q, 0 < e1 -> 0 < e2 -> ball (e1 + e2) (f1 e1) (f2 e2).\n\nContext {EM : ExtMetricSpaceClass X}.\n\nGlobal Instance rf_setoid : Setoid RegularFunction.\nProof.\nconstructor.\n+ intros f e1 e2; apply rf_prf.\n+ intros f1 f2 A e1 e2 A1 A2. rewrite plus_comm. now apply mspc_symm, A.\n+ intros f1 f2 f3 A1 A2 e1 e3 A3 A4. apply mspc_closed. intros d A5.\n  mc_setoid_replace (e1 + e3 + d) with ((e1 + d / 2) + (e3 + d / 2))\n  by (field; change ((2 : Q) ≠ 0); solve_propholds).\n  apply mspc_triangle with (b := f2 (d / 2));\n  [apply A1 | rewrite plus_comm; apply A2]; try solve_propholds.\nQed.\n\nInstance rf_msb : MetricSpaceBall RegularFunction :=\n  λ e f1 f2, forall e1 e2 : Q, 0 < e1 -> 0 < e2 -> ball (e + e1 + e2) (f1 e1) (f2 e2).\n\nLemma unit_reg (x : X) : IsRegularFunction (λ _, x).\nProof. intros e1 e2 A1 A2; apply mspc_refl; solve_propholds. Qed.\n\nDefinition reg_unit (x : X) := Build_RegularFunction (unit_reg x).\n\nGlobal Instance : Setoid_Morphism reg_unit.\nProof.\nconstructor; [apply _ .. |].\nintros x y eq_x_y e1 e2 e1_pos e2_pos. apply mspc_eq; solve_propholds.\nQed.\n\nClass Limit := lim : RegularFunction -> X.\n\nClass CompleteMetricSpaceClass `{Limit} := cmspc :> Surjective reg_unit (inv := lim).\n\nDefinition tends_to (f : RegularFunction) (l : X) :=\n  forall e : Q, 0 < e -> ball e (f e) l.\n\nLemma limit_def `{CompleteMetricSpaceClass} (f : RegularFunction) :\n  forall e : Q, 0 < e -> ball e (f e) (lim f).\nProof.\nintros e2 A2. apply mspc_symm; apply mspc_closed.\n(* [apply mspc_symm, mspc_closed.] does not work *)\nintros e1 A1. change (lim f) with (reg_unit (lim f) e1). rewrite plus_comm.\nrapply (surjective reg_unit (inv := lim)); trivial; reflexivity.\nQed.\n\nEnd CompleteMetricSpace.\n\nGlobal Arguments RegularFunction X {_}.\nGlobal Arguments Limit X {_}.\nGlobal Arguments CompleteMetricSpaceClass X {_ _ _}.\n\n(* The exclamation mark before Limit avoids introducing a second assumption\nMetricSpaceBall X *)\nLemma completeness_criterion `{ExtMetricSpaceClass X, !Limit X} :\n  CompleteMetricSpaceClass X <-> forall f : RegularFunction X, tends_to f (lim f).\nProof.\nsplit; intro A.\n+ intros f e2 A2. apply mspc_symm, mspc_closed.\n  intros e1 A1. change (lim f) with (reg_unit (lim f) e1). rewrite plus_comm.\n  rapply (surjective reg_unit (A := X) (inv := lim)); trivial; reflexivity.\n+ constructor; [| apply _].\n  apply ext_equiv_r; [apply _|].\n  intros f e1 e2 e1_pos e2_pos.\n  apply (mspc_monotone e2); [apply nonneg_plus_le_compat_l; solve_propholds |].\n  now apply mspc_symm, A.\nQed.\n\nSection UCFComplete.\n\nContext `{NonEmpty X, ExtMetricSpaceClass X, CompleteMetricSpaceClass Y}.\n\nProgram Definition pointwise_regular\n  (F : RegularFunction (UniformlyContinuous X Y)) (x : X) : RegularFunction Y :=\n  Build_RegularFunction (λ e, F e x) _.\nNext Obligation. intros e1 e2 e1_pos e2_pos; now apply F. Qed.\n\nGlobal Program Instance ucf_limit : Limit (UniformlyContinuous X Y) :=\n  λ F, Build_UniformlyContinuous\n         (λ x, lim (pointwise_regular F x))\n         (λ e, uc_mu (F (e/3)) (e/3))\n         _.\nNext Obligation.\nconstructor.\n* intros e e_pos.\n  destruct (F (e/3)) as [g ? ?]; simpl; apply uc_pos with (f := g); trivial.\n  apply Q.Qmult_lt_0_compat; auto with qarith.\n* intros e x1 x2 e_pos A.\n  apply (mspc_triangle' (e/3) (e/3 + e/3) (F (e/3) x1)); [field; discriminate | |].\n  + apply mspc_symm. change ((F (e / 3)) x1) with (pointwise_regular F x1 (e/3)).\n    (* without [change], neither [apply limit_def] nor [rapply limit_def] work *)\n    apply completeness_criterion, Q.Qmult_lt_0_compat; auto with qarith.\n  + apply mspc_triangle with (b := F (e / 3) x2).\n    - destruct (F (e/3)); eapply uc_prf; eauto.\n      apply Q.Qmult_lt_0_compat; auto with qarith.\n    - change ((F (e / 3)) x2) with (pointwise_regular F x2 (e/3)).\n      apply completeness_criterion, Q.Qmult_lt_0_compat; auto with qarith.\nQed.\n\nGlobal Instance : CompleteMetricSpaceClass (UniformlyContinuous X Y).\nProof.\napply completeness_criterion. intros F e e_pos x.\nchange (func (lim F) x) with (lim (pointwise_regular F x)).\nchange (func (F e) x) with (pointwise_regular F x e).\nnow apply completeness_criterion.\nQed.\n\nEnd UCFComplete.\n\nDefinition seq A := nat -> A.\n\n#[global]\nHint Unfold seq : typeclass_instances.\n(* This unfolds [seq X] as [nat -> X] and allows ext_equiv to find an\ninstance of [Equiv (seq X)] *)\n\nSection SequenceLimits.\n\nContext `{ExtMetricSpaceClass X}.\n\nDefinition seq_lim (x : seq X) (a : X) (N : Q -> nat) :=\n  forall e : Q, 0 < e -> forall n : nat, N e ≤ n -> ball e (x n) a.\n\n(*Global Instance : Proper (((=) ==> (=)) ==> (=) ==> ((=) ==> (=)) ==> iff) seq_lim.\nProof.\nintros x1 x2 A1 a1 a2 A2 N1 N2 A3; split; intros A e e_pos n A4.\n+ mc_setoid_replace (x2 n) with (x1 n) by (symmetry; now apply A1).\n  rewrite <- A2. mc_setoid_replace (N2 e) with (N1 e) in A4 by (symmetry; now apply A3).\n  now apply A.\n+ mc_setoid_replace (x1 n) with (x2 n) by now apply A1.\n  rewrite A2. mc_setoid_replace (N1 e) with (N2 e) in A4 by now apply A3.\n  now apply A.\nQed.*)\n\n(* The following instance uses Leibniz equality for the third argument of\nseq_lim, i.e., the modulus of type [Q -> nat]. This is because extensional\nequality = is not reflexive on functions: [f = f] iff [f] is a morphism.\nAnd we need reflexivity when we replace the first argument of seq_lim and\nleave the third one unchanged. Do we need the previous instance with\nextensional equality for the third argument? *)\n\nGlobal Instance : Proper (((=) ==> (=)) ==> (=) ==> (≡) ==> iff) seq_lim.\nProof.\nintros x1 x2 A1 a1 a2 A2 N1 N2 A3; split; intros A e e_pos n A4.\n+ mc_setoid_replace (x2 n) with (x1 n) by (symmetry; now apply A1).\n  rewrite <- A2. rewrite <- A3 in A4. now apply A.\n+ mc_setoid_replace (x1 n) with (x2 n) by now apply A1.\n  rewrite A2. rewrite A3 in A4. now apply A.\nQed.\n\nLemma seq_lim_unique : ∀ (x : seq X) (a1 a2 : X) N1 N2, seq_lim x a1 N1 → seq_lim x a2 N2 → a1 = a2.\nProof.\nintros x a1 a2 N1 N2 A1 A2. apply -> mspc_eq; intros q A.\nassert (A3 : 0 < q / 2) by solve_propholds.\nspecialize (A1 (q / 2) A3); specialize (A2 (q / 2) A3).\nset (M := Peano.max (N1 (q / 2)) (N2 (q / 2))).\nassert (A4 : N1 (q / 2) ≤ M) by apply le_max_l.\nassert (A5 : N2 (q / 2) ≤ M) by apply le_max_r.\nspecialize (A1 M A4); specialize (A2 M A5).\napply mspc_symm in A1.\napply (mspc_triangle' (q / 2) (q / 2) (x M)); trivial.\nfield; change ((2 : Q) ≠ 0); solve_propholds.\nQed.\n\nLemma seq_lim_S (x : seq X) (a : X) N : seq_lim x a N -> seq_lim (x ∘ S) a N.\nProof. intros A e A1 n A2. apply A; trivial. apply le_S, A2. Qed.\n\nLemma seq_lim_S' (x : seq X) (a : X) N : seq_lim (x ∘ S) a N -> seq_lim x a (S ∘ N).\nProof.\nintros A e A1 n A2.\ndestruct n as [| n].\n+ contradict A2; apply le_Sn_0.\n+ apply A; trivial. apply le_S_n, A2.\nQed.\n\nEnd SequenceLimits.\n\nTheorem seq_lim_cont\n        `{ExtMetricSpaceClass X, ExtMetricSpaceClass Y} (f : X -> Y)\n        {mu : Q -> Qinf} {_ : IsUniformlyContinuous f mu}\n  (x : seq X) (a : X) (N : Q -> nat) :\n  seq_lim x a N → seq_lim (f ∘ x) (f a) (comp_inf N mu 0).\nProof.\nintros A e e_pos n A1. apply (uc_prf f mu); trivial.\nunfold comp_inf in A1; assert (A2 := uc_pos f mu e e_pos).\nnow destruct (mu e); [apply A | apply mspc_inf].\nQed.\n\nTheorem seq_lim_contr\n  `{MetricSpaceClass X, ExtMetricSpaceClass Y} (f : X -> Y) `{!IsContraction f q}\n  (x : seq X) (a : X) (N : Q -> nat) :\n  seq_lim x a N → seq_lim (f ∘ x) (f a) (comp_inf N (lip_modulus q) 0).\nProof. intro A; apply seq_lim_cont; [apply _ | apply A]. Qed.\n\nLemma iter_fixpoint\n  `{ExtMetricSpaceClass X, ExtMetricSpaceClass Y}\n  (f : X -> X) {mu : Q -> Qinf} {_ : IsUniformlyContinuous f mu}\n  (x : seq X) (a : X) (N : Q -> nat) :\n  (forall n : nat, x (S n) = f (x n)) -> seq_lim x a N -> f a = a.\nProof.\nintros A1 A2; generalize A2; intro A3. apply seq_lim_S in A2. apply (seq_lim_cont f) in A3.\nsetoid_replace (x ∘ S) with (f ∘ x) in A2 by (intros ? ? eqmn; rewrite eqmn; apply A1).\neapply seq_lim_unique; eauto.\nQed.\n\nSection CompleteSpaceSequenceLimits.\n\nContext `{CompleteMetricSpaceClass X}.\n\nDefinition cauchy (x : seq X) (N : Q -> nat) :=\n  forall e : Q, 0 < e -> forall m n : nat, N e ≤ m -> N e ≤ n -> ball e (x m) (x n).\n\nDefinition reg_fun (x : seq X) (N : Q -> nat) (A : cauchy x N) : RegularFunction X.\nrefine (Build_RegularFunction (x ∘ N) _).\n(* without loss of generality, N e1 ≤ N e2 *)\nassert (A3 : forall e1 e2, 0 < e1 -> 0 < e2 -> N e1 ≤ N e2 -> ball (e1 + e2) ((x ∘ N) e1) ((x ∘ N) e2)).\n+ intros e1 e2 A1 A2 A3.\n  apply (mspc_monotone e1).\n  - apply (strictly_order_preserving (e1 +)) in A2; rewrite plus_0_r in A2; solve_propholds.\n  - apply A; trivial; reflexivity.\n+ intros e1 e2 A1 A2.\n  assert (A4 : TotalRelation (A := nat) (≤)) by apply _; destruct (A4 (N e1) (N e2)).\n  - now apply A3.\n  - rewrite plus_comm; now apply mspc_symm, A3.\nDefined.\n\nArguments reg_fun {_} {_} _.\n\nLemma seq_lim_lim (x : seq X) (N : Q -> nat) (A : cauchy x N) :\n  seq_lim x (lim (reg_fun A)) (λ e, N (e / 2)).\nProof.\nset (f := reg_fun A).\nintros e A1 n A2. apply (mspc_triangle' (e / 2) (e / 2) (x (N (e / 2)))).\n+ field; change ((2 : Q) ≠ 0); solve_propholds.\n+ now apply mspc_symm, A; [solve_propholds | reflexivity |].\n+ change (x (N (e / 2))) with (f (e / 2)).\n  apply completeness_criterion; solve_propholds.\nQed.\n\nEnd CompleteSpaceSequenceLimits.\n\n(*End QField.*)\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/ode/metric.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2906515453221567}}
{"text": "Require Import my_arith__my_leb_nat my_bool Coq.Lists.List.\nRequire Export vsSahlq_instant3 vsSahlq_instant_pre_to_be_sorted.\n\n(*  ----------------------------------------------- *)\n\nDefinition instant_cons_empty' alpha beta : SecOrder :=\n  replace_pred_l beta (list_pred_not_in (preds_in alpha)\n                                         (preds_in beta))\n          (nlist_list _ (nlist_Var1 (length\n              (list_pred_not_in (preds_in alpha)\n                                (preds_in beta)))))\n          (nlist_list _ (nlist_empty (length \n              (list_pred_not_in (preds_in alpha)\n                                (preds_in beta))))).\n\nLemma ex_att_allFO_lv_conjSO_f_rev : forall lv alpha1 alpha2,\n (ex_attached_allFO_lv alpha1 lv = false) ->\n (ex_attached_allFO_lv alpha2 lv = false) ->\n  ex_attached_allFO_lv (conjSO alpha1 alpha2) lv = false.\nProof.\n  induction lv; intros alpha1 alpha2 Ha Hb.\n    simpl in *. reflexivity.\n\n    simpl in *.\n    case_eq (attached_allFO_x alpha1 a); intros H1;\n      simpl in Ha; rewrite H1 in Ha. discriminate.\n    case_eq (attached_allFO_x alpha2 a); intros H2;\n      rewrite H2 in Hb. discriminate.\n    apply IHlv; assumption.\nQed.\n\nLemma  att_allFO_x_REL : forall rel x,\n  REL rel = true ->\n  attached_allFO_x rel x = false.\nProof.\n  induction rel; intros [xn] H; try\n    reflexivity;\n    try (simpl in *; discriminate).\n\n    simpl in *.\n    case_eq (REL rel1); intros H1; rewrite H1 in H.\n      2 : discriminate.\n    rewrite IHrel1. apply IHrel2.\n    all : assumption.\nQed.\n\nLemma ex_att_allFO_lv_REL : forall lv rel,\n  REL rel = true ->\n  ex_attached_allFO_lv rel lv = false.\nProof.\n  induction lv; intros rel Hrel.\n    simpl. reflexivity.\n\n    simpl. rewrite att_allFO_x_REL.\n    apply IHlv. all: assumption.\nQed.\n\n\nLemma  att_allFO_x_AT : forall atm x,\n  AT atm = true ->\n  attached_allFO_x atm x = false.\nProof.\n  induction atm; intros [xn] H; try\n    reflexivity;\n    try (simpl in *; discriminate).\n\n    simpl in *.\n    case_eq (AT atm1); intros H1; rewrite H1 in H.\n      2 : discriminate.\n    rewrite IHatm1. apply IHatm2.\n    all : assumption.\nQed.\n\nLemma ex_att_allFO_lv_AT : forall lv atm,\n  AT atm = true ->\n  ex_attached_allFO_lv atm lv = false.\nProof.\n  induction lv; intros rel Hrel.\n    simpl. reflexivity.\n\n    simpl. rewrite att_allFO_x_AT.\n    apply IHlv. all: assumption.\nQed.\n\nFixpoint is_in_FOvar (x : FOvariable) (l : list FOvariable) : bool :=\n  match l with\n  | nil => false\n  | cons y l => match x, y with Var xn, Var ym =>\n     if beq_nat xn ym then true else (is_in_FOvar x l)\n  end end.\n\nLemma is_in_FOvar_app : forall l1 l2 x,\n  is_in_FOvar x (app l1 l2) =\n  if is_in_FOvar x l1 then true else is_in_FOvar x l2.\nProof.\n  induction l1; intros l2 [xn].\n    simpl. reflexivity.\n\n    simpl. destruct a as [ym].\n    case_eq (beq_nat xn ym); intros Hbeq.\n      reflexivity.\n      apply IHl1.\nQed.\n\nFixpoint rename_FOv_list (l : list FOvariable) x y : list FOvariable :=\n  match l with\n  | nil => nil\n  | cons z l' =>\n  match x, z with Var xn, Var zn => \n    if beq_nat xn zn then cons y (rename_FOv_list l' x y) else cons z (rename_FOv_list l' x y)\n  end end.\n\nLemma rename_FOv_list_app : forall l1 l2 x y,\n  rename_FOv_list (app l1 l2) x y =\n  app (rename_FOv_list l1 x y) (rename_FOv_list l2 x y).\nProof.\n  induction l1; intros l2 [xn] [ym].\n    simpl. reflexivity.\n\n    simpl. destruct a as [zn].\n    case_eq (beq_nat xn zn); intros Hbeq; simpl;\n      rewrite IHl1; reflexivity.\nQed.\n\nLemma is_in_FOvar_rename : forall l x y,\n  ~ x = y ->\n  is_in_FOvar x (rename_FOv_list l x y) = false.\nProof.\n  induction l; intros [xn] [ym] Hneq.\n    reflexivity.\n\n    simpl. destruct a as [zn].\n    pose proof Hneq as Hneq'.\n    apply FOvar_neq in Hneq.\n    case_eq (beq_nat xn zn); intros Hbeq. simpl.\n      rewrite Hneq. apply IHl. assumption.\n\n      simpl. rewrite Hbeq. apply IHl.\n      assumption.\nQed.\n\nLemma rename_FOv_list_refl : forall l x,\n  rename_FOv_list l x x = l.\nProof.\n  induction l; intros [xn].\n    reflexivity.\n\n    destruct a as [ym].\n    simpl.\n    case_eq (beq_nat xn ym); intros Hbeq.\n      rewrite IHl. rewrite (beq_nat_true _ _ Hbeq).\n      reflexivity.\n\n      rewrite IHl. reflexivity.\nQed.\n\nFixpoint FOvars_in alpha : list FOvariable :=\n  match alpha with\n    predSO P x => cons x nil\n  | relatSO x y => cons x (cons y nil)\n  | eqFO x y => cons x (cons y nil)\n  | allFO x beta => cons x (FOvars_in beta)\n  | exFO x beta => cons x (FOvars_in beta)\n  | negSO beta => FOvars_in beta\n  | conjSO beta1 beta2 => app (FOvars_in beta1) (FOvars_in beta2)\n  | disjSO beta1 beta2 => app (FOvars_in beta1) (FOvars_in beta2)\n  | implSO beta1 beta2 => app (FOvars_in beta1) (FOvars_in beta2)\n  | allSO P beta => FOvars_in beta\n  | exSO P beta => FOvars_in beta\n  end.\n\nLemma hmm1 : forall alpha xn ym,\n (FOvars_in (rename_FOv_n alpha xn ym)) =\n  rename_FOv_list (FOvars_in alpha) (Var xn) (Var ym).\nProof.  \n  induction alpha; intros xn ym.\n    destruct p; destruct f as [zn]. simpl.\n    case_eq (beq_nat xn zn); intros Hbeq;\n       reflexivity.\n\n    destruct f as [z1]; destruct f0 as [z2].\n    simpl. case_eq (beq_nat xn z1); intros Hbeq1;\n      case_eq (beq_nat xn z2); intros Hbeq2;\n        reflexivity.\n\n    destruct f as [z1]; destruct f0 as [z2].\n    simpl. case_eq (beq_nat xn z1); intros Hbeq1;\n      case_eq (beq_nat xn z2); intros Hbeq2;\n        reflexivity.\n\n    destruct f as [zn]. simpl.\n    rewrite (beq_nat_comm zn xn).\n    case_eq (beq_nat xn zn); intros Hbeq;\n      simpl; rewrite IHalpha;\n      reflexivity.\n\n    destruct f as [zn]. simpl.\n    rewrite (beq_nat_comm zn xn).\n    case_eq (beq_nat xn zn); intros Hbeq;\n      simpl; rewrite IHalpha;\n      reflexivity.\n\n    simpl in *. apply IHalpha.\n\n    simpl. rewrite IHalpha1.\n    rewrite IHalpha2. rewrite rename_FOv_list_app.\n    reflexivity.\n\n    simpl. rewrite IHalpha1.\n    rewrite IHalpha2. rewrite rename_FOv_list_app.\n    reflexivity.\n\n    simpl. rewrite IHalpha1.\n    rewrite IHalpha2. rewrite rename_FOv_list_app.\n    reflexivity.\n\n    simpl in *. apply IHalpha.\n\n    simpl in *. apply IHalpha.\nQed.\n\nDefinition closed_except (alpha : SecOrder) (x : FOvariable) : Prop :=\n  free_FO alpha x = true /\\\n  forall y, ~ x = y -> free_FO alpha y = false.\n\nLemma hopeful4 : forall alpha x y W Iv Ip Ir d,\n  x_occ_in_alpha alpha y = false ->\n  SOturnst W (alt_Iv Iv d y) Ip Ir (rename_FOv alpha x y) <->\n  SOturnst W (alt_Iv Iv d x) Ip Ir alpha.\nProof.\n  induction alpha; intros [xn] [ym] W Iv Ip Ir d Hocc.\n    destruct p; destruct f as [zn].\n    simpl. case_eq (beq_nat xn zn);\n      intros Hbeq; simpl. rewrite <- beq_nat_refl.\n      apply iff_refl.\n      simpl in Hocc. rewrite Hocc.\n      apply iff_refl.\n\n    destruct f as [z1]; destruct f0 as [z2].\n    simpl rename_FOv.\n    simpl in Hocc.\n    case_eq (beq_nat ym z1); intros Hbeq;\n      rewrite Hbeq in *. discriminate.\n    case_eq (beq_nat xn z1); intros Hbeq3.\n      rewrite (beq_nat_true _  _ Hbeq3).\n      case_eq (beq_nat z1 z2); intros Hbeq2.\n        rewrite (beq_nat_true _ _ Hbeq2).\n        simpl. do 2 rewrite <- beq_nat_refl.\n        apply iff_refl.\n\n        simpl. rewrite <- beq_nat_refl.\n        rewrite Hbeq2. rewrite Hocc.\n        rewrite <- beq_nat_refl. apply iff_refl.\n\n      case_eq (beq_nat xn z2); intros Hbeq2.\n        rewrite (beq_nat_true _ _ Hbeq2).\n        simpl. rewrite Hbeq. \n        do 2 rewrite <- beq_nat_refl.\n        rewrite <- (beq_nat_true _ _ Hbeq2).\n        rewrite Hbeq3. apply iff_refl.\n\n        simpl. rewrite Hocc. rewrite Hbeq.\n        rewrite Hbeq2. rewrite Hbeq3.\n        apply iff_refl.\n\n    destruct f as [z1]; destruct f0 as [z2].\n    simpl rename_FOv.\n    simpl in Hocc.\n    case_eq (beq_nat ym z1); intros Hbeq;\n      rewrite Hbeq in *. discriminate.\n    case_eq (beq_nat xn z1); intros Hbeq3.\n      rewrite (beq_nat_true _  _ Hbeq3).\n      case_eq (beq_nat z1 z2); intros Hbeq2.\n        rewrite (beq_nat_true _ _ Hbeq2).\n        simpl. do 2 rewrite <- beq_nat_refl.\n        apply iff_refl.\n\n        simpl. rewrite <- beq_nat_refl.\n        rewrite Hbeq2. rewrite Hocc.\n        rewrite <- beq_nat_refl. apply iff_refl.\n\n      case_eq (beq_nat xn z2); intros Hbeq2.\n        rewrite (beq_nat_true _ _ Hbeq2).\n        simpl. rewrite Hbeq. \n        do 2 rewrite <- beq_nat_refl.\n        rewrite <- (beq_nat_true _ _ Hbeq2).\n        rewrite Hbeq3. apply iff_refl.\n\n        simpl. rewrite Hocc. rewrite Hbeq.\n        rewrite Hbeq2. rewrite Hbeq3.\n        apply iff_refl.\n\n    destruct f as [zn]. simpl in Hocc.\n    case_eq (beq_nat ym zn); intros Hbeq; \n      rewrite Hbeq in *. discriminate.\n    simpl rename_FOv.\n    case_eq (beq_nat zn xn); intros Hbeq2.\n      split ;intros SOt d2;\n        specialize (SOt d2);\n        rewrite (beq_nat_true _ _ Hbeq2) in *;\n        rewrite alt_Iv_eq in *;\n        apply (IHalpha (Var xn) (Var ym) W _ Ip Ir d2 Hocc);\n        apply SOt.\n\n      assert (~Var ym = Var zn) as Hneq.\n        intros H. inversion H as [H'].\n        rewrite H' in Hbeq. rewrite <- beq_nat_refl in Hbeq.\n        discriminate.\n      assert (~Var xn = Var zn) as Hneq2.\n        intros H. inversion H as [H'].\n        rewrite H' in Hbeq2. rewrite <- beq_nat_refl in Hbeq2.\n        discriminate.\n      split; intros SOt d2; specialize (SOt d2);\n        rewrite alt_Iv_switch in *.\n        apply (IHalpha (Var xn) (Var ym) W _ Ip Ir _ Hocc).\n        all : try assumption. \n\n        apply beq_nat_false in Hbeq.\n        apply (IHalpha (Var xn) (Var ym) W _ Ip Ir _ Hocc).\n        assumption.\n\n    destruct f as [zn]. simpl in Hocc.\n    case_eq (beq_nat ym zn); intros Hbeq; \n      rewrite Hbeq in *. discriminate.\n    simpl rename_FOv.\n    case_eq (beq_nat zn xn); intros Hbeq2.\n      split ;intros SOt; destruct SOt as [d2 SOt];\n        exists d2;\n        rewrite (beq_nat_true _ _ Hbeq2) in *;\n        rewrite alt_Iv_eq in *;\n        apply (IHalpha (Var xn) (Var ym) W _ Ip Ir d2 Hocc);\n        apply SOt.\n\n      assert (~Var ym = Var zn) as Hneq.\n        intros H. inversion H as [H'].\n        rewrite H' in Hbeq. rewrite <- beq_nat_refl in Hbeq.\n        discriminate.\n      assert (~Var xn = Var zn) as Hneq2.\n        intros H. inversion H as [H'].\n        rewrite H' in Hbeq2. rewrite <- beq_nat_refl in Hbeq2.\n        discriminate.\n      split; intros SOt; destruct SOt as [d2 SOt];\n        exists d2;\n        rewrite alt_Iv_switch in *.\n        apply (IHalpha (Var xn) (Var ym) W _ Ip Ir _ Hocc).\n        all : try assumption. \n\n        apply beq_nat_false in Hbeq.\n        apply (IHalpha (Var xn) (Var ym) W _ Ip Ir _ Hocc).\n        assumption.\n\n    rewrite rename_FOv_negSO.\n    do 2 rewrite SOturnst_negSO.\n    split; intros SOt H; apply SOt;\n      apply (IHalpha (Var xn) (Var ym) W Iv Ip Ir d); assumption.\n\n    rewrite rename_FOv_conjSO.\n    do 2 rewrite SOturnst_conjSO.\n    destruct (x_occ_in_alpha_conjSO _ _ _ Hocc) as [H1 H2].\n    split; intros [SOt1 SOt2]; apply conj.\n      apply (IHalpha1 (Var xn) (Var ym) W Iv Ip Ir d); assumption.\n      apply (IHalpha2 (Var xn) (Var ym) W Iv Ip Ir d); assumption.\n      apply (IHalpha1 (Var xn) (Var ym) W Iv Ip Ir d); assumption.\n      apply (IHalpha2 (Var xn) (Var ym) W Iv Ip Ir d); assumption.\n\n    rewrite rename_FOv_disjSO.\n    do 2 rewrite SOturnst_disjSO.\n    destruct (x_occ_in_alpha_conjSO _ _ _ Hocc) as [H1 H2].\n    split; (intros [SOt1 | SOt2]; [left | right]).\n      apply (IHalpha1 (Var xn) (Var ym) W Iv Ip Ir d); assumption.\n      apply (IHalpha2 (Var xn) (Var ym) W Iv Ip Ir d); assumption.\n      apply (IHalpha1 (Var xn) (Var ym) W Iv Ip Ir d); assumption.\n      apply (IHalpha2 (Var xn) (Var ym) W Iv Ip Ir d); assumption.\n\n    rewrite rename_FOv_implSO.\n    do 2 rewrite SOturnst_implSO.\n    destruct (x_occ_in_alpha_conjSO _ _ _ Hocc) as [H1 H2].\n    split; intros SOt1 SOt2. \n      apply (IHalpha2 (Var xn) (Var ym) W Iv Ip Ir d); try assumption.\n      apply SOt1.\n      apply (IHalpha1 (Var xn) (Var ym) W Iv Ip Ir d); assumption.\n      apply (IHalpha2 (Var xn) (Var ym) W Iv Ip Ir d); try assumption.\n      apply SOt1.\n      apply (IHalpha1 (Var xn) (Var ym) W Iv Ip Ir d); assumption.\n\n    destruct p. simpl in Hocc.\n    split; intros SOt pa;\n      specialize (SOt pa);\n      apply (IHalpha (Var xn) (Var ym) W Iv _ Ir d); assumption.\n\n    destruct p. simpl in Hocc.\n    split; intros [pa SOt]; exists pa;\n      apply (IHalpha (Var xn) (Var ym) W Iv _ Ir d); assumption.\nQed.\n\nLemma hopeful3_allFO : forall alpha x y W Iv Ip Ir,\n  x_occ_in_alpha alpha y = false ->\n  SOturnst W Iv Ip Ir (rename_FOv (allFO x alpha) x y) <->\n  SOturnst W Iv Ip Ir (allFO x alpha).\nProof.\n  intros alpha [xn] [ym] W Iv Ip Ir Hocc.\n  simpl rename_FOv. rewrite <- beq_nat_refl.\n  do 2 rewrite SOturnst_allFO.\n  split; intros SOt d; specialize (SOt d);\n    apply (hopeful4 _ (Var xn) (Var ym));\n    assumption.\nQed. \n\nLemma hopeful3_exFO : forall alpha x y W Iv Ip Ir,\n  x_occ_in_alpha alpha y = false ->\n  SOturnst W Iv Ip Ir (rename_FOv (exFO x alpha) x y) <->\n  SOturnst W Iv Ip Ir (exFO x alpha).\nProof.\n  intros alpha [xn] [ym] W Iv Ip Ir Hocc.\n  simpl rename_FOv. rewrite <- beq_nat_refl.\n  do 2 rewrite SOturnst_exFO.\n  split; intros [d SOt]; exists d;\n    apply (hopeful4 _ (Var xn) (Var ym));\n    assumption.\nQed.\n\nLemma free_FO_conjSO : forall alpha1 alpha2 x,\n  free_FO (conjSO alpha1 alpha2) x = false ->\n  (free_FO alpha1 x = false) /\\ (free_FO alpha2 x = false).\nProof.\n  intros alpha1 alpha2 x Hfree.\n    simpl in Hfree.\n    case_eq (free_FO alpha1 x); intros H1;\n      rewrite H1 in *. discriminate.\n    apply conj. reflexivity. assumption.\nQed.\n\nFixpoint rev_seq start length : list nat :=\n  match length with\n  | 0 => nil\n  | S n => cons (start + n) (rev_seq start n)\n  end.\n\nFixpoint newnew_pre alpha lv ln : SecOrder :=\n  match lv, ln with\n  | nil, _ => alpha\n  | _, nil => alpha\n  | cons x lv', cons n ln' =>\n    rename_FOv (newnew_pre alpha lv' ln') x (Var n)\n  end.\n\nFixpoint rem_FOv l x :=\n  match l with\n  | nil => nil\n  | cons y l' => match x, y with Var xn, Var ym =>\n    if beq_nat xn ym then rem_FOv l' x else cons y (rem_FOv l' x)\n  end end.\n\nLemma x_occ_in_rename_FOv : forall alpha x y,\n  ~ x = y ->\n  x_occ_in_alpha (rename_FOv alpha x y) x = false.\nProof.\n  induction alpha; intros [xn] [ym] Heq.\n    destruct f as [zn].\n    simpl. case_eq (beq_nat xn zn); intros Hbeq.\n    simpl.  apply neq_beq_nat_FOv. assumption.\n\n    simpl. assumption.\n\n    destruct f as [z1]; destruct f0 as [z2].\n    simpl. case_eq (beq_nat xn z1); intros H1.\n      case_eq (beq_nat xn z2); intros H2;\n        simpl; rewrite neq_beq_nat_FOv. reflexivity.\n        all : try assumption.\n\n      case_eq (beq_nat xn z2); intros H2;\n        simpl; rewrite neq_beq_nat_FOv.\n        apply neq_beq_nat_FOv. assumption.\n        apply beq_nat_false_FOv. all : try assumption.\n        apply beq_nat_false_FOv. all : try assumption.\n\n    destruct f as [z1]; destruct f0 as [z2].\n    simpl. case_eq (beq_nat xn z1); intros H1.\n      case_eq (beq_nat xn z2); intros H2;\n        simpl; rewrite neq_beq_nat_FOv. reflexivity.\n        all : try assumption.\n\n      case_eq (beq_nat xn z2); intros H2;\n        simpl; rewrite neq_beq_nat_FOv.\n        apply neq_beq_nat_FOv. assumption.\n        apply beq_nat_false_FOv. all : try assumption.\n        apply beq_nat_false_FOv. all : try assumption.\n\n    destruct f as [zn]. simpl. case_eq (beq_nat zn xn); intros Hbeq;\n      simpl. rewrite neq_beq_nat_FOv.\n      apply (IHalpha (Var xn) (Var ym)).\n      all : try assumption.\n\n      rewrite beq_nat_comm. rewrite Hbeq.\n      apply (IHalpha (Var xn) (Var ym)).\n      assumption.\n\n    destruct f as [zn]. simpl. case_eq (beq_nat zn xn); intros Hbeq;\n      simpl. rewrite neq_beq_nat_FOv.\n      apply (IHalpha (Var xn) (Var ym)).\n      all : try assumption.\n\n      rewrite beq_nat_comm. rewrite Hbeq.\n      apply (IHalpha (Var xn) (Var ym)).\n      assumption.\n\n    simpl. apply (IHalpha (Var xn) (Var ym)). assumption.\n\n    simpl. unfold rename_FOv in *.\n    specialize (IHalpha1 (Var xn) (Var ym) Heq).\n    specialize (IHalpha2 (Var xn) (Var ym) Heq).\n    rewrite IHalpha1. apply IHalpha2.\n\n    simpl. unfold rename_FOv in *.\n    specialize (IHalpha1 (Var xn) (Var ym) Heq).\n    specialize (IHalpha2 (Var xn) (Var ym) Heq).\n    rewrite IHalpha1. apply IHalpha2.\n\n    simpl. unfold rename_FOv in *.\n    specialize (IHalpha1 (Var xn) (Var ym) Heq).\n    specialize (IHalpha2 (Var xn) (Var ym) Heq).\n    rewrite IHalpha1. apply IHalpha2.\n\n    simpl. apply (IHalpha (Var xn) (Var ym)). assumption.\n\n    simpl. apply (IHalpha (Var xn) (Var ym)). assumption.\nQed.\n\nLemma x_occ_in_free_FO : forall alpha x,\n  x_occ_in_alpha alpha x = false ->\n  free_FO alpha x = false.\nProof.\n  induction alpha; intros [xn] Hocc.\n    destruct f as [ym]. assumption.\n\n    destruct f as [y1]; destruct f0 as [y2].\n    assumption.\n\n    destruct f as [y1]; destruct f0 as [y2].\n    assumption.\n\n    destruct f as [ym]. simpl in *.\n    case_eq (beq_nat xn ym); intros Hbeq.\n      reflexivity.\n\n      apply IHalpha. rewrite Hbeq in Hocc.\n      assumption.\n\n    destruct f as [ym]. simpl in *.\n    case_eq (beq_nat xn ym); intros Hbeq.\n      reflexivity.\n\n      apply IHalpha. rewrite Hbeq in Hocc.\n      assumption.\n\n    simpl in *. apply IHalpha.\n    assumption.\n\n    destruct (x_occ_in_alpha_conjSO _ _ _ Hocc).\n    simpl. rewrite IHalpha1. apply IHalpha2.\n    all : try assumption.\n\n    destruct (x_occ_in_alpha_conjSO _ _ _ Hocc).\n    simpl. rewrite IHalpha1. apply IHalpha2.\n    all : try assumption.\n\n    destruct (x_occ_in_alpha_conjSO _ _ _ Hocc).\n    simpl. rewrite IHalpha1. apply IHalpha2.\n    all : try assumption.\n\n    simpl in *. apply IHalpha. assumption.\n\n    simpl in *. apply IHalpha. assumption.\nQed.\n\nLemma free_FO_rename_FOv_same : forall alpha x y,\n  ~ x = y ->\n  free_FO (rename_FOv alpha x y) x = false.\nProof.\n  intros.\n  apply x_occ_in_free_FO.\n  apply x_occ_in_rename_FOv.\n  assumption.\nQed.\n\nLemma rename_FOv_not_occ : forall alpha x y,\n  x_occ_in_alpha alpha x = false ->\n  rename_FOv alpha x y = alpha.\nProof.\n  induction alpha; intros [xn] [ym] Hocc.\n    destruct p; destruct f. simpl in *.\n    rewrite Hocc. reflexivity.\n\n    destruct f as [z1]; destruct f0 as [z2].\n    simpl in *. case_eq (beq_nat xn z1); intros Hbeq;\n      rewrite Hbeq in *. discriminate.\n    rewrite Hocc. reflexivity.\n\n    destruct f as [z1]; destruct f0 as [z2].\n    simpl in *. case_eq (beq_nat xn z1); intros Hbeq;\n      rewrite Hbeq in *. discriminate.\n    rewrite Hocc. reflexivity.\n\n    destruct f as [zn]. simpl in *.\n    case_eq (beq_nat xn zn); intros Hbeq;\n      rewrite Hbeq in *. discriminate.\n    rewrite beq_nat_comm. rewrite Hbeq.\n    unfold rename_FOv in *.\n    rewrite (IHalpha (Var xn) (Var ym)).\n    reflexivity. assumption.\n\n    destruct f as [zn]. simpl in *.\n    case_eq (beq_nat xn zn); intros Hbeq;\n      rewrite Hbeq in *. discriminate.\n    rewrite beq_nat_comm. rewrite Hbeq.\n    unfold rename_FOv in *.\n    rewrite (IHalpha (Var xn) (Var ym)).\n    reflexivity. assumption.\n\n    simpl in *. unfold rename_FOv in *.\n    rewrite (IHalpha (Var xn) (Var ym)). \n    reflexivity. assumption.\n\n    apply x_occ_in_alpha_conjSO in Hocc.\n    unfold rename_FOv in *. simpl.\n    rewrite (IHalpha1 (Var xn) (Var ym)). \n    rewrite (IHalpha2 (Var xn) (Var ym)).\n    reflexivity. all : try apply Hocc.\n\n    apply x_occ_in_alpha_conjSO in Hocc.\n    unfold rename_FOv in *. simpl.\n    rewrite (IHalpha1 (Var xn) (Var ym)). \n    rewrite (IHalpha2 (Var xn) (Var ym)).\n    reflexivity. all : try apply Hocc.\n\n    apply x_occ_in_alpha_conjSO in Hocc.\n    unfold rename_FOv in *. simpl.\n    rewrite (IHalpha1 (Var xn) (Var ym)). \n    rewrite (IHalpha2 (Var xn) (Var ym)).\n    reflexivity. all : try apply Hocc.\n\n    simpl in *. unfold rename_FOv in *.\n    rewrite (IHalpha (Var xn) (Var ym)). \n    reflexivity. assumption.\n\n    simpl in *. unfold rename_FOv in *.\n    rewrite (IHalpha (Var xn) (Var ym)). \n    reflexivity. assumption.\nQed.\n\nLemma max_FOv_rename_FOv2 : forall alpha x ym,\n  x_occ_in_alpha alpha x = true ->\n  Nat.leb (max_FOv (rename_FOv alpha x (Var ym)))\n          (max (max_FOv alpha) ym) = true.\nProof.\n  induction alpha; intros [xn] ym Hocc.\n    simpl in *. destruct f as [zn].\n    case_eq (beq_nat xn zn); intros Hbeq;\n      simpl. rewrite max_comm.\n      apply leb_max_suc3. apply leb_refl.\n\n      apply leb_max_suc3. apply leb_refl.\n\n\n    destruct f as [z1]; destruct f0 as [z2].\n    simpl in *. case_eq (beq_nat xn z1); intros Hbeq;\n      rewrite Hbeq in *;\n      case_eq (beq_nat xn z2); intros Hbeq2;\n        simpl. rewrite max_refl.\n        rewrite max_comm.\n        apply leb_max_suc3. apply leb_refl.\n\n        rewrite (max_comm z1 z2).\n        rewrite (max_comm _ ym).\n        rewrite PeanoNat.Nat.max_assoc.\n        apply leb_max_suc3. apply leb_refl.\n\n        rewrite (max_comm (max z1 z2) ym).\n        rewrite PeanoNat.Nat.max_assoc.\n        rewrite (max_comm z1 ym).\n        apply leb_max_suc3. apply leb_refl.\n\n        apply leb_max_suc3. apply leb_refl.\n\n    destruct f as [z1]; destruct f0 as [z2].\n    simpl in *. case_eq (beq_nat xn z1); intros Hbeq;\n      rewrite Hbeq in *;\n      case_eq (beq_nat xn z2); intros Hbeq2;\n        simpl. rewrite max_refl.\n        rewrite max_comm.\n        apply leb_max_suc3. apply leb_refl.\n\n        rewrite (max_comm z1 z2).\n        rewrite (max_comm _ ym).\n        rewrite PeanoNat.Nat.max_assoc.\n        apply leb_max_suc3. apply leb_refl.\n\n        rewrite (max_comm (max z1 z2) ym).\n        rewrite PeanoNat.Nat.max_assoc.\n        rewrite (max_comm z1 ym).\n        apply leb_max_suc3. apply leb_refl.\n\n        apply leb_max_suc3. apply leb_refl.\n\n    destruct f as [zn]. simpl in *.\n    rewrite beq_nat_comm.\n    case_eq (beq_nat xn zn); intros Hbeq;\n      rewrite Hbeq in *.  \n      case_eq (x_occ_in_alpha alpha (Var xn)); intros Hocc2.\n        simpl.\n        destruct (max_or ym (max_FOv (rename_FOv_n alpha xn ym)))\n          as [H | H]; rewrite H.\n          rewrite max_comm.\n          apply leb_max_suc3. apply leb_refl.\n\n          rewrite <-  PeanoNat.Nat.max_assoc.\n          rewrite max_comm.\n          apply leb_max_suc3. apply (IHalpha (Var xn)).\n          assumption.\n\n          simpl. rewrite <- rename_FOv__n.\n          rewrite (rename_FOv_not_occ).\n            rewrite <- PeanoNat.Nat.max_assoc.\n            rewrite max_comm. rewrite (max_comm zn _).\n            apply leb_max_suc3. apply leb_refl.\n            assumption.\n\n        simpl.\n        destruct (max_or zn (max_FOv (rename_FOv_n alpha xn ym)))\n          as [H | H]; rewrite H.\n          rewrite <- PeanoNat.Nat.max_assoc.\n          apply leb_max_suc3. apply leb_refl.\n\n          rewrite <- PeanoNat.Nat.max_assoc.\n          rewrite max_comm.\n          apply leb_max_suc3.\n          apply (IHalpha (Var xn)).\n          assumption.\n\n    destruct f as [zn]. simpl in *.\n    rewrite beq_nat_comm.\n    case_eq (beq_nat xn zn); intros Hbeq;\n      rewrite Hbeq in *.  \n      case_eq (x_occ_in_alpha alpha (Var xn)); intros Hocc2.\n        simpl.\n        destruct (max_or ym (max_FOv (rename_FOv_n alpha xn ym)))\n          as [H | H]; rewrite H.\n          rewrite max_comm.\n          apply leb_max_suc3. apply leb_refl.\n\n          rewrite <-  PeanoNat.Nat.max_assoc.\n          rewrite max_comm.\n          apply leb_max_suc3. apply (IHalpha (Var xn)).\n          assumption.\n\n          simpl. rewrite <- rename_FOv__n.\n          rewrite (rename_FOv_not_occ).\n            rewrite <- PeanoNat.Nat.max_assoc.\n            rewrite max_comm. rewrite (max_comm zn _).\n            apply leb_max_suc3. apply leb_refl.\n            assumption.\n\n        simpl.\n        destruct (max_or zn (max_FOv (rename_FOv_n alpha xn ym)))\n          as [H | H]; rewrite H.\n          rewrite <- PeanoNat.Nat.max_assoc.\n          apply leb_max_suc3. apply leb_refl.\n\n          rewrite <- PeanoNat.Nat.max_assoc.\n          rewrite max_comm.\n          apply leb_max_suc3.\n          apply (IHalpha (Var xn)).\n          assumption.\n\n    simpl in *. apply (IHalpha (Var xn)). assumption.\n\n    simpl in Hocc.\n    case_eq (x_occ_in_alpha alpha1 (Var xn)); intros Hocc1;\n      rewrite Hocc1 in *.\n      simpl.\n      case_eq (x_occ_in_alpha alpha2 (Var xn)); intros Hocc2.\n        rewrite max_max.\n        apply leb_max_max_gen.\n          apply (IHalpha1 (Var xn)). assumption.\n\n          apply (IHalpha2 (Var xn)). assumption.\n\n        rewrite <- rename_FOv__n with (alpha := alpha2).\n        rewrite (rename_FOv_not_occ alpha2 (Var xn)).\n        rewrite (max_comm _ ym).\n        rewrite PeanoNat.Nat.max_assoc.\n        rewrite (max_comm ym _).\n        apply leb_max_max_gen.\n          apply (IHalpha1 (Var xn)). assumption.\n          apply leb_refl. assumption.\n\n      simpl.\n      rewrite <- rename_FOv__n with (alpha := alpha1).\n      rewrite (rename_FOv_not_occ alpha1 (Var xn)).\n      rewrite <- PeanoNat.Nat.max_assoc.\n      apply leb_max_max_gen.\n        apply leb_refl.\n        apply (IHalpha2 (Var xn)). all : try assumption.\n\n    simpl in Hocc.\n    case_eq (x_occ_in_alpha alpha1 (Var xn)); intros Hocc1;\n      rewrite Hocc1 in *.\n      simpl.\n      case_eq (x_occ_in_alpha alpha2 (Var xn)); intros Hocc2.\n        rewrite max_max.\n        apply leb_max_max_gen.\n          apply (IHalpha1 (Var xn)). assumption.\n\n          apply (IHalpha2 (Var xn)). assumption.\n\n        rewrite <- rename_FOv__n with (alpha := alpha2).\n        rewrite (rename_FOv_not_occ alpha2 (Var xn)).\n        rewrite (max_comm _ ym).\n        rewrite PeanoNat.Nat.max_assoc.\n        rewrite (max_comm ym _).\n        apply leb_max_max_gen.\n          apply (IHalpha1 (Var xn)). assumption.\n          apply leb_refl. assumption.\n\n      simpl.\n      rewrite <- rename_FOv__n with (alpha := alpha1).\n      rewrite (rename_FOv_not_occ alpha1 (Var xn)).\n      rewrite <- PeanoNat.Nat.max_assoc.\n      apply leb_max_max_gen.\n        apply leb_refl.\n        apply (IHalpha2 (Var xn)). all : try assumption.\n\n    simpl in Hocc.\n    case_eq (x_occ_in_alpha alpha1 (Var xn)); intros Hocc1;\n      rewrite Hocc1 in *.\n      simpl.\n      case_eq (x_occ_in_alpha alpha2 (Var xn)); intros Hocc2.\n        rewrite max_max.\n        apply leb_max_max_gen.\n          apply (IHalpha1 (Var xn)). assumption.\n\n          apply (IHalpha2 (Var xn)). assumption.\n\n        rewrite <- rename_FOv__n with (alpha := alpha2).\n        rewrite (rename_FOv_not_occ alpha2 (Var xn)).\n        rewrite (max_comm _ ym).\n        rewrite PeanoNat.Nat.max_assoc.\n        rewrite (max_comm ym _).\n        apply leb_max_max_gen.\n          apply (IHalpha1 (Var xn)). assumption.\n          apply leb_refl. assumption.\n\n      simpl.\n      rewrite <- rename_FOv__n with (alpha := alpha1).\n      rewrite (rename_FOv_not_occ alpha1 (Var xn)).\n      rewrite <- PeanoNat.Nat.max_assoc.\n      apply leb_max_max_gen.\n        apply leb_refl.\n        apply (IHalpha2 (Var xn)). all : try assumption.\n\n    simpl in *. apply (IHalpha (Var xn)). assumption.\n\n    simpl in *. apply (IHalpha (Var xn)). assumption.\nQed.\n\nLemma free_FO_rename_FOv2 : forall alpha x y,\n  free_FO alpha x = false ->\n  free_FO alpha y = false ->\n  free_FO (rename_FOv alpha x y) y = false.\nProof.\n  induction alpha; intros [xn] [ym] H1 H2.\n    destruct p; destruct f as [zn].\n    simpl in *.\n    rewrite H1. simpl. apply H2.\n\n    destruct f as [z1]; destruct f0 as [z2].\n    simpl in *. case_eq (beq_nat xn z1); intros Hbeq;\n      rewrite Hbeq in *. discriminate.\n    case_eq (beq_nat xn z2); intros Hbeq2;\n      rewrite Hbeq2 in *. discriminate.\n    simpl in *. case_eq (beq_nat ym z1); intros Hbeq3;\n      rewrite Hbeq3 in *. discriminate.\n    case_eq (beq_nat ym z2); intros Hbeq4;\n      rewrite Hbeq4 in *. discriminate.\n    reflexivity.\n\n    destruct f as [z1]; destruct f0 as [z2].\n    simpl in *. case_eq (beq_nat xn z1); intros Hbeq;\n      rewrite Hbeq in *. discriminate.\n    case_eq (beq_nat xn z2); intros Hbeq2;\n      rewrite Hbeq2 in *. discriminate.\n    simpl in *. case_eq (beq_nat ym z1); intros Hbeq3;\n      rewrite Hbeq3 in *. discriminate.\n    case_eq (beq_nat ym z2); intros Hbeq4;\n      rewrite Hbeq4 in *. discriminate.\n    reflexivity.\n\n    destruct f as [zn]. simpl in *. \n    rewrite beq_nat_comm.\n    case_eq (beq_nat xn zn); intros Hbeq;\n      rewrite Hbeq in *.\n      simpl. rewrite <- beq_nat_refl.\n      reflexivity.\n\n      simpl. case_eq (beq_nat ym zn) ;intros Hbeq2;\n      rewrite Hbeq2 in *. reflexivity.    \n        apply (IHalpha (Var xn) (Var ym));  \n        assumption.\n\n    destruct f as [zn]. simpl in *. \n    rewrite beq_nat_comm.\n    case_eq (beq_nat xn zn); intros Hbeq;\n      rewrite Hbeq in *.\n      simpl. rewrite <- beq_nat_refl.\n      reflexivity.\n\n      simpl. case_eq (beq_nat ym zn) ;intros Hbeq2;\n      rewrite Hbeq2 in *. reflexivity.    \n        apply (IHalpha (Var xn) (Var ym));  \n        assumption.\n\n    simpl in *. \n    apply (IHalpha (Var xn) (Var ym));\n    assumption.\n\n    simpl in *. case_eq (free_FO alpha1 (Var xn));\n      intros H3; rewrite H3 in *. discriminate.\n    case_eq (free_FO alpha2 (Var xn)); intros H4;\n      rewrite H4 in *. discriminate.\n    simpl in *. case_eq (free_FO alpha1 (Var ym));\n      intros H5; rewrite H5 in *. discriminate.\n    case_eq (free_FO alpha2 (Var ym)); intros H6;\n      rewrite H6 in *. discriminate.\n    unfold rename_FOv in *.\n    rewrite (IHalpha1 (Var xn) (Var ym)).\n    apply (IHalpha2 (Var xn) (Var ym)).\n    all : try assumption.\n\n    simpl in *. case_eq (free_FO alpha1 (Var xn));\n      intros H3; rewrite H3 in *. discriminate.\n    case_eq (free_FO alpha2 (Var xn)); intros H4;\n      rewrite H4 in *. discriminate.\n    simpl in *. case_eq (free_FO alpha1 (Var ym));\n      intros H5; rewrite H5 in *. discriminate.\n    case_eq (free_FO alpha2 (Var ym)); intros H6;\n      rewrite H6 in *. discriminate.\n    unfold rename_FOv in *.\n    rewrite (IHalpha1 (Var xn) (Var ym)).\n    apply (IHalpha2 (Var xn) (Var ym)).\n    all : try assumption.\n\n    simpl in *. case_eq (free_FO alpha1 (Var xn));\n      intros H3; rewrite H3 in *. discriminate.\n    case_eq (free_FO alpha2 (Var xn)); intros H4;\n      rewrite H4 in *. discriminate.\n    simpl in *. case_eq (free_FO alpha1 (Var ym));\n      intros H5; rewrite H5 in *. discriminate.\n    case_eq (free_FO alpha2 (Var ym)); intros H6;\n      rewrite H6 in *. discriminate.\n    unfold rename_FOv in *.\n    rewrite (IHalpha1 (Var xn) (Var ym)).\n    apply (IHalpha2 (Var xn) (Var ym)).\n    all : try assumption.\n\n    simpl in *. \n    apply (IHalpha (Var xn) (Var ym));\n    assumption.\n\n    simpl in *. \n    apply (IHalpha (Var xn) (Var ym));\n    assumption.\nQed.\n\nFixpoint is_in_FOvar_l l1 l2 : bool :=\n  match l1 with\n  | nil => true\n  | cons x l1' => \n      if is_in_FOvar x l2 then is_in_FOvar_l l1' l2 else false\n  end.\n\nLemma is_in__FOvar : forall l1 l2 x,\n  is_in_FOvar_l l1 l2 = true ->\n  is_in_FOvar x l1 = true ->\n  is_in_FOvar x l2 = true.\nProof.\n  induction l1; intros l2 [xn] H1 H2.\n    simpl in *. discriminate.\n\n    simpl in *. destruct a as [ym].\n    case_eq (is_in_FOvar (Var ym) l2); intros H3;\n      rewrite H3 in H1. 2 : discriminate.\n    case_eq (beq_nat xn ym); intros Hbeq.\n      rewrite (beq_nat_true _ _ Hbeq) in *. assumption.\n    rewrite Hbeq in H2. apply IHl1; assumption.\nQed.\n\nLemma att_allFO_instant_cons_empty'_pre : forall beta P x y ,\n  attached_allFO_x beta y = false ->\nattached_allFO_x\n  (replace_pred beta P x (negSO (eqFO x x))) y = false.\nProof.\n  induction beta; intros [Pn] [ym] [xn] Hat.\n    destruct p as [Qm]; destruct f as [zn]. simpl in *.\n    rewrite <- beq_nat_refl. case_eq (beq_nat Pn Qm);\n      intros Hbeq; reflexivity.\n\n    destruct f as [z1]; destruct f0 as [z2].\n    reflexivity.\n\n    destruct f as [z1]; destruct f0 as [z2].\n    reflexivity.\n\n    destruct f as [zn]. simpl in *.\n    case_eq (beq_nat xn zn); intros Hbeq;\n      rewrite Hbeq in *. discriminate.\n      apply IHbeta. assumption.\n\n    destruct f as [zn]. simpl in *.\n    apply IHbeta. assumption.\n\n    simpl in *. apply IHbeta; assumption.\n\n    simpl in *. case_eq (attached_allFO_x beta1 (Var xn));\n      intros H1; rewrite H1 in *. discriminate.\n      rewrite IHbeta1. apply IHbeta2. all : try assumption.\n\n    simpl in *. case_eq (attached_allFO_x beta1 (Var xn));\n      intros H1; rewrite H1 in *. discriminate.\n      rewrite IHbeta1. apply IHbeta2. all : try assumption.\n\n    simpl in *. case_eq (attached_allFO_x beta1 (Var xn));\n      intros H1; rewrite H1 in *. discriminate.\n      rewrite IHbeta1. apply IHbeta2. all : try assumption.\n\n    destruct p as [Qm]. simpl in *.\n    case_eq (beq_nat Pn Qm); intros Hbeq; simpl;\n      apply IHbeta; assumption.\n\n    destruct p as [Qm]. simpl in *.\n    case_eq (beq_nat Pn Qm); intros Hbeq; simpl;\n      apply IHbeta; assumption.\nQed.\n\nLemma att_allFO_instant_cons_empty'_pre_l : forall l beta x,\n  attached_allFO_x beta x = false ->\nattached_allFO_x\n  (replace_pred_l beta l\n     (nlist_list (length l) (nlist_Var1 _))\n     (nlist_list (length l) (nlist_empty _))) x = false.\nProof.\n  induction l; intros beta x H.\n    simpl. assumption.\n\n    simpl. apply att_allFO_instant_cons_empty'_pre.\n    apply IHl. assumption.\nQed.\n\nLemma att_allFO_instant_cons_empty' : forall beta alpha x,\n  attached_allFO_x beta x = false ->\n  attached_allFO_x (instant_cons_empty' alpha beta) x = false.\nProof.\n  intros beta alpha x H.\n  unfold instant_cons_empty'.\n  apply att_allFO_instant_cons_empty'_pre_l.\n  assumption.\nQed.\n\nLemma instant_cons_empty'_allFO : forall alpha beta y,\n  instant_cons_empty' alpha (allFO y beta) = \n  allFO y (instant_cons_empty' alpha beta).\nProof.\n  intros.\n  unfold instant_cons_empty'.\n  rewrite rep_pred_l_allFO.\n  reflexivity.\nQed.\n\nLemma instant_cons_empty'_exFO : forall alpha beta y,\n  instant_cons_empty' alpha (exFO y beta) = \n  exFO y (instant_cons_empty' alpha beta).\nProof.\n  intros. destruct y.\n  unfold instant_cons_empty'.\n  rewrite rep_pred_l_exFO.\n  reflexivity.\nQed.\n\nLemma instant_cons_empty'_negSO : forall alpha beta,\n  instant_cons_empty' alpha (negSO beta) = \n  negSO (instant_cons_empty' alpha beta).\nProof.\n  intros.\n  unfold instant_cons_empty'.\n  rewrite rep_pred_l_negSO.\n  reflexivity.\nQed.\n\nLemma list_pred_not_in_app : forall l1 l2 l,\n  list_pred_not_in l (app l1 l2) =\n  app (list_pred_not_in l l1) (list_pred_not_in l l2).\nProof.\n  induction l1; intros l2 l.\n    reflexivity.\n\n    simpl. case_eq (is_in_pred a l);\n      intros Hin. apply IHl1.\n\n      rewrite IHl1. reflexivity.\nQed.\n\nFixpoint cap_pred_empty l1 l2 : bool :=\n  match l1 with\n  | nil => true\n  | cons P l1' => if is_in_pred P l2 then false\n                    else cap_pred_empty l1' l2\n  end.\n\nFixpoint rem_pred l P : list predicate :=\n  match l with\n  | nil => nil\n  | cons Q l' => match P, Q with Pred Pn, Pred Qm =>\n      if beq_nat Pn Qm then rem_pred l' P else\n        cons Q (rem_pred l' P)\n      end\n  end.\n\nLemma list_pred_not_in_rem_pred : forall l2 l P,\n  list_pred_not_in (cons P l) l2 =\n  rem_pred (list_pred_not_in l l2) P.\nProof.\n  induction l2; intros l [Pn].\n    reflexivity.\n\n    simpl. destruct a as [Qm].\n    case_eq (beq_nat Qm Pn); intros Hbeq;\n      case_eq (is_in_pred (Pred Qm) l);\n        intros Hin. apply IHl2.\n\n        simpl. rewrite beq_nat_comm.\n        rewrite Hbeq.\n        apply IHl2.\n\n        apply IHl2.\n\n        simpl. rewrite beq_nat_comm.\n        rewrite Hbeq. rewrite IHl2.\n        reflexivity.\nQed.\n\nLemma rem_pred_app : forall l1 l2 P,\n  rem_pred (app l1 l2) P =\n  app (rem_pred l1 P) (rem_pred l2 P).\nProof.\n  induction l1; intros l2 [Pn].\n    reflexivity.\n\n    simpl. destruct a as [Qm].\n    case_eq (beq_nat Pn Qm); intros Hbeq;\n      rewrite IHl1; reflexivity.\nQed.\n\nLemma jj9 : forall alpha x y z P,\n  preds_in (replace_pred alpha P x (negSO (eqFO y z))) =\n  rem_pred (preds_in alpha) P.\nProof.\n  induction alpha; intros [xn] [ym] [zn] [Pn].\n    destruct p as [Qm]; destruct f. simpl.\n    case_eq (beq_nat Pn Qm); intros Hbeq.\n      simpl. case_eq (beq_nat xn ym);\n        case_eq (beq_nat xn zn).\n        all : try reflexivity.\n\n    destruct f; destruct f0; reflexivity.\n\n    destruct f; destruct f0; reflexivity.\n\n    destruct f as [u1].\n    simpl. apply IHalpha.\n\n    destruct f as [u1].\n    simpl. apply IHalpha.\n\n    simpl. apply IHalpha.\n\n    simpl. rewrite IHalpha1.\n    rewrite IHalpha2.\n    rewrite rem_pred_app. reflexivity.\n\n    simpl. rewrite IHalpha1.\n    rewrite IHalpha2.\n    rewrite rem_pred_app. reflexivity.\n\n    simpl. rewrite IHalpha1.\n    rewrite IHalpha2.\n    rewrite rem_pred_app. reflexivity.\n\n    destruct p as [Qm].\n    simpl in *. case_eq (beq_nat Pn Qm); intros Hbeq.\n      apply IHalpha.\n\n      simpl. rewrite IHalpha. reflexivity.\n\n    destruct p as [Qm].\n    simpl in *. case_eq (beq_nat Pn Qm); intros Hbeq.\n      apply IHalpha.\n\n      simpl. rewrite IHalpha. reflexivity.\nQed.\n\nLemma jj8 : forall l beta,\n  is_in_pred_l l (preds_in beta) = true ->\n  preds_in (replace_pred_l beta l\n      (nlist_list _ (nlist_Var1 (length l)))\n      (nlist_list _ (nlist_empty (length l)))) =\n  list_pred_not_in l (preds_in beta).\nProof.\n  induction l; intros beta H.\n    simpl in *.\n    rewrite list_pred_not_in_nil.\n    reflexivity.\n\n    simpl in *.\n    case_eq (is_in_pred a (preds_in beta));\n      intros H2; rewrite H2 in *.  2 : discriminate.\n    rewrite list_pred_not_in_rem_pred.\n    rewrite jj9.\n    rewrite IHl. reflexivity.\n    assumption.\nQed.\n\nLemma  jj10 : forall l2 l1,\n  is_in_pred_l (list_pred_not_in l1 l2) l2 = true.\nProof.\n  induction l2; intros l1.\n    reflexivity.\n\n    simpl. case_eq (is_in_pred a l1); intros Hin.\n      apply is_in_pred_l2.\n      apply IHl2.\n\n      destruct a as [Qm].\n      simpl. rewrite <- beq_nat_refl.\n      apply is_in_pred_l2. apply IHl2.\nQed.\n\nFixpoint cap_pred l1 l2 :=\n  match l1 with\n  | nil => nil\n  | cons P l1' => if is_in_pred P l2 then cons P (cap_pred l1' l2)\n          else cap_pred l1' l2\n  end.\n\nLemma is_in_pred_rem_pred_eq : forall l P,\n  is_in_pred P (rem_pred l P) = false.\nProof.\n  induction l; intros [Pn].\n    reflexivity.\n\n    destruct a as [Qm].\n    simpl. case_eq (beq_nat Pn Qm); intros Hbeq.\n      apply IHl.\n\n      simpl. rewrite Hbeq. apply IHl.\nQed.\n\nLemma jj13 : forall l P Q,\n  match P, Q with Pred Pn, Pred Qm =>\n    beq_nat Pn Qm = false\n  end ->\n  is_in_pred P (rem_pred l Q) = \n  is_in_pred P l.\nProof.\n  induction l; intros [Pn] [Qm] Hbeq.\n    reflexivity.\n\n    simpl. destruct a as [Rn].\n    case_eq (beq_nat Qm Rn); intros Hbeq2.\n      rewrite <- (beq_nat_true _ _ Hbeq2).\n      rewrite Hbeq. apply IHl.\n      assumption.\n\n      simpl. case_eq (beq_nat Pn Rn); intros Hbeq3.\n        reflexivity.\n        apply IHl. assumption.\nQed.\n\nLemma jj12 : forall l1 l2 P,\n  is_in_pred P l1 = true ->\n  is_in_pred P (list_pred_not_in l1 l2) = false.\nProof.\n  induction l1; intros l2 [Pn] H.\n    simpl in *. discriminate.\n\n    simpl in *. destruct a as [Qm].\n    rewrite list_pred_not_in_rem_pred.\n    case_eq (beq_nat Pn Qm); intros Hbeq;\n      rewrite Hbeq in *.\n      rewrite (beq_nat_true _ _ Hbeq).\n      rewrite is_in_pred_rem_pred_eq.\n      reflexivity.\n\n      rewrite jj13.\n      apply IHl1. all : assumption.\nQed.\n\nLemma rem_pred_not_in : forall l P,\n  is_in_pred P l = false ->\n  rem_pred l P = l.\nProof.\n  induction l; intros [Pn] H.\n    reflexivity.\n\n    destruct a as [Qm]. simpl in *.\n    case_eq (beq_nat Pn Qm); intros Hbeq;\n      rewrite Hbeq in *. discriminate.\n    rewrite IHl. reflexivity.\n    assumption.\nQed.\n\nLemma is_in_cap_pred : forall l2 l1 P,\n  is_in_pred P l1 = false ->\n  is_in_pred P (cap_pred l2 l1) = false.\nProof.\n  induction l2; intros l1 [Pn] H.\n    reflexivity.\n\n    simpl. case_eq (is_in_pred a l1); intros H2.\n      destruct a as [Qm]. simpl.\n      case_eq (beq_nat Pn Qm); intros Hbeq2.\n        rewrite (beq_nat_true _ _ Hbeq2) in H.\n        rewrite H in H2. discriminate.\n\n        apply IHl2. assumption.\n\n      apply IHl2. assumption.\nQed.\n\nLemma jj11 : forall l2 l1,\n  list_pred_not_in (list_pred_not_in l1 l2) l2 =\n  cap_pred l2 l1.\nProof.\n  induction l2; intros l1.\n    reflexivity.\n\n    simpl. case_eq (is_in_pred a l1); intros H2.\n      apply jj12 with (l2 := l2) in H2.\n      rewrite H2.\n      rewrite IHl2. reflexivity.\n\n      simpl. destruct a as [Pn].\n      rewrite <- beq_nat_refl.\n      rewrite list_pred_not_in_rem_pred.\n      rewrite IHl2.\n      apply rem_pred_not_in.\n      apply is_in_cap_pred. assumption.\nQed.\n\nLemma is_in_pred_cap_pred : forall l1 l2 P,\n  is_in_pred P l1 = true ->\n  is_in_pred P l2 = true ->\n  is_in_pred P (cap_pred l1 l2) = true.\nProof.\n  induction l1; intros l2 [Pn] H1 H2.\n    simpl in *. discriminate.\n\n    destruct a as [Qm].\n    simpl in *.\n    case_eq (beq_nat Pn Qm); intros Hbeq.\n      rewrite (beq_nat_true _ _ Hbeq) in *.\n      rewrite H2.\n      simpl. rewrite <- beq_nat_refl.\n      reflexivity.\n\n      rewrite Hbeq in H1.\n      case_eq (is_in_pred (Pred Qm) l2); intros H3.\n        simpl. rewrite Hbeq. apply IHl1; assumption.\n\n        apply IHl1; assumption.\nQed.\n\nLemma is_in_pred_cap_pred_t : forall l1 l2 P,\n  is_in_pred P (cap_pred l1 l2) = true ->\n  (is_in_pred P l1 = true /\\\n  is_in_pred P l2 = true).\nProof.\n  induction l1; intros l2 [Pn] H.\n    simpl in *. discriminate.\n\n    simpl in *.\n    case_eq (is_in_pred a l2); intros H2;\n      rewrite H2 in *.\n      destruct a as [Qm]. simpl in *.\n      case_eq (beq_nat Pn Qm); intros Hbeq;\n        rewrite Hbeq in *.\n        apply conj. reflexivity.\n        rewrite (beq_nat_true _ _ Hbeq).\n        assumption.\n\n        apply IHl1.\n        assumption.\n\n      destruct a as [Qm].\n      case_eq (beq_nat Pn Qm); intros Hbeq.\n        apply conj. reflexivity.\n        apply IHl1. assumption.\n\n        apply IHl1. assumption.\nQed.\n\nLemma is_in_pred_cap_pred_f : forall l1 l2 P,\n  is_in_pred P (cap_pred l1 l2) = false ->\n  is_in_pred P l1 = false \\/ is_in_pred P l2 = false.\nProof.\n  induction l1; intros l2 [Pn] H.\n    simpl in *. left. reflexivity.\n\n    simpl in *. destruct a as [Qm]. \n    case_eq (is_in_pred (Pred Qm) l2); intros H2;\n      rewrite H2 in H. simpl in H.\n      case_eq (beq_nat Pn Qm); intros Hbeq;\n        rewrite Hbeq in *. discriminate.\n      apply IHl1. assumption.\n\n      case_eq (beq_nat Pn Qm); intros Hbeq.\n        rewrite (beq_nat_true _ _ Hbeq).\n        right. assumption.\n\n        apply IHl1. assumption.\nQed.\n\nLemma is_in_pred_cap_pred_f1 : forall l1 l2 P,\n  is_in_pred P l1 = false ->\n  is_in_pred P (cap_pred l1 l2) = false.\nProof.\n  induction l1; intros l2 [Pn] H.\n    simpl in *. reflexivity.\n\n    simpl in *. destruct a as [Qm]. \n    case_eq (is_in_pred (Pred Qm) l2); intros H2.\n      simpl.\n      case_eq (beq_nat Pn Qm); intros Hbeq;\n        rewrite Hbeq in *. discriminate.\n      apply IHl1. assumption.\n\n      case_eq (beq_nat Pn Qm); intros Hbeq.\n        rewrite Hbeq in *. discriminate.\n\n        rewrite Hbeq in H. apply IHl1.\n        assumption.\nQed.\n\nLemma is_in_pred_cap_pred_f2 : forall l1 l2 P,\n  is_in_pred P l2 = false ->\n  is_in_pred P (cap_pred l1 l2) = false.\nProof.\n  induction l1; intros l2 [Pn] H.\n    simpl in *. reflexivity.\n\n    simpl in *. destruct a as [Qm]. \n    case_eq (is_in_pred (Pred Qm) l2); intros H2.\n      simpl.\n      case_eq (beq_nat Pn Qm); intros Hbeq.\n        rewrite (beq_nat_true _ _ Hbeq) in H.\n        rewrite H2 in H. discriminate.\n      apply IHl1. assumption.\n\n      apply IHl1. assumption.\nQed.\n\nLemma cap_pred_comm : forall l1 l2 P,\n  is_in_pred P (cap_pred l1 l2) =\n  is_in_pred P (cap_pred l2 l1).\nProof.\n  intros.\n  case_eq (is_in_pred P (cap_pred l1 l2));\n    intros H.\n    apply is_in_pred_cap_pred_t in H.\n    destruct H as [H1 H2].\n    symmetry. apply is_in_pred_cap_pred;\n    assumption.\n\n    apply is_in_pred_cap_pred_f in H.\n    destruct H as [H1 | H2].\n      symmetry. apply is_in_pred_cap_pred_f2.\n      assumption.\n      symmetry. apply is_in_pred_cap_pred_f1.\n      assumption.\nQed.\n\nLemma jj7 : forall l beta P,\n  is_in_pred P l = false ->\n  is_in_pred P (preds_in (replace_pred_l beta \n      (list_pred_not_in l (preds_in beta))\n          (nlist_list (length (list_pred_not_in l (preds_in beta)))\n             (nlist_Var1 (length (list_pred_not_in l (preds_in beta)))))\n          (nlist_list (length (list_pred_not_in l (preds_in beta)))\n             (nlist_empty (length (list_pred_not_in l (preds_in beta))))))) = false.\nProof.\n  induction l; intros beta [Pn] H.  \n    rewrite list_pred_not_in_nil.\n    rewrite un_predless_preds_in. assumption.\n    apply is_un_predless_rep_pred_l.\n    apply un_predless_l_empty_n.\n\n    destruct a as [Qm]. simpl in *.\n    case_eq (beq_nat Pn Qm); intros Hbeq; \n      rewrite Hbeq in *. discriminate.\n\n      rewrite jj8. rewrite jj11.\n      rewrite cap_pred_comm.\n      simpl.\n      case_eq (is_in_pred (Pred Qm) (preds_in beta));\n        intros H2.\n        simpl. rewrite Hbeq.\n        apply is_in_pred_cap_pred_f1.\n        assumption.\n\n        apply is_in_pred_cap_pred_f1.\n        assumption.\n\n    apply jj10.\nQed.\n\nLemma jj6 : forall lb1 la beta2,\ncap_pred_empty (list_pred_not_in la lb1)\n  (preds_in\n     (replace_pred_l beta2 (list_pred_not_in la (preds_in beta2))\n        (nlist_list (length (list_pred_not_in la (preds_in beta2)))\n           (nlist_Var1 (length (list_pred_not_in la (preds_in beta2)))))\n        (nlist_list (length (list_pred_not_in la (preds_in beta2)))\n           (nlist_empty (length (list_pred_not_in la (preds_in beta2))))))) =\ntrue.\nProof.\n  induction lb1; intros la beta2.\n    reflexivity.\n\n    destruct a as [Pn]. simpl.\n    case_eq (is_in_pred (Pred Pn) la); intros Hin.\n      apply IHlb1.\n\n      simpl. rewrite IHlb1.\n      rewrite jj7. reflexivity.\n      assumption.\nQed.\n\nLemma sumtin : forall l2 lb l beta,\n  is_in_pred_l (preds_in beta) lb = true ->\n  cap_pred_empty l2 (preds_in (replace_pred_l beta (list_pred_not_in l lb)\n      (nlist_list _ (nlist_Var1 (length (list_pred_not_in l lb))))\n      (nlist_list _ (nlist_empty (length (list_pred_not_in l lb)))))) = true ->\n  replace_pred_l \n    (replace_pred_l beta (list_pred_not_in l lb)\n      (nlist_list _ (nlist_Var1 (length (list_pred_not_in l lb))))\n      (nlist_list _ (nlist_empty (length (list_pred_not_in l lb)))))\n    l2\n    (nlist_list (length l2) (nlist_Var1 (length l2)))\n    (nlist_list (length l2) (nlist_empty (length l2))) =\n    (replace_pred_l beta (list_pred_not_in l lb)\n      (nlist_list _ (nlist_Var1 (length (list_pred_not_in l lb))))\n      (nlist_list _ (nlist_empty (length (list_pred_not_in l lb))))).\nProof.\n  induction l2; intros lb l beta H1 H2.\n    simpl in *. reflexivity.\n\n    simpl. destruct a as [Qm].\n    simpl in *.\n    case_eq (is_in_pred (Pred Qm) \n         (preds_in\n            (replace_pred_l beta (list_pred_not_in l lb)\n               (nlist_list (length (list_pred_not_in l lb))\n                  (nlist_Var1 (length (list_pred_not_in l lb))))\n               (nlist_list (length (list_pred_not_in l lb))\n                  (nlist_empty (length (list_pred_not_in l lb)))))));\n      intros H3; rewrite H3 in *. discriminate.\n\n    rewrite IHl2; try assumption.\n    rewrite rep_pred_not_in. reflexivity.\n    assumption.\nQed.\n\nLemma instant_cons_empty'_conjSO : forall alpha beta1 beta2,\n  instant_cons_empty' alpha (conjSO beta1 beta2) =\n  conjSO (instant_cons_empty' alpha beta1) (instant_cons_empty' alpha beta2).\nProof.\n  intros. unfold instant_cons_empty'.\n  rewrite rep_pred_l_conjSO. simpl.\n  rewrite list_pred_not_in_app.\n  do 2 rewrite rep_pred_l_app.\n  rewrite rep_pred_l_switch.\n  rewrite sumtin.\n  rewrite sumtin. reflexivity.\n\n    apply is_in_pred_l_refl.\n\n    apply jj6.\n    apply is_in_pred_l_refl.\n\n    apply jj6.\nQed.\n\nLemma instant_cons_empty'_disjSO : forall alpha beta1 beta2,\n  instant_cons_empty' alpha (disjSO beta1 beta2) =\n  disjSO (instant_cons_empty' alpha beta1) (instant_cons_empty' alpha beta2).\nProof.\n  intros. unfold instant_cons_empty'.\n  rewrite rep_pred_l_disjSO. simpl.\n  rewrite list_pred_not_in_app.\n  do 2 rewrite rep_pred_l_app.\n  rewrite rep_pred_l_switch.\n  rewrite sumtin.\n  rewrite sumtin. reflexivity.\n\n    apply is_in_pred_l_refl.\n\n    apply jj6.\n    apply is_in_pred_l_refl.\n\n    apply jj6.\nQed.\n\nLemma instant_cons_empty'_implSO : forall alpha beta1 beta2,\n  instant_cons_empty' alpha (implSO beta1 beta2) =\n  implSO (instant_cons_empty' alpha beta1) (instant_cons_empty' alpha beta2).\nProof.\n  intros. unfold instant_cons_empty'.\n  rewrite rep_pred_l_implSO. simpl.\n  rewrite list_pred_not_in_app.\n  do 2 rewrite rep_pred_l_app.\n  rewrite rep_pred_l_switch.\n  rewrite sumtin.\n  rewrite sumtin. reflexivity.\n\n    apply is_in_pred_l_refl.\n\n    apply jj6.\n    apply is_in_pred_l_refl.\n\n    apply jj6.\nQed.\n\nLemma free_FO_instant_cons_empty'_f : forall beta alpha y,\n  SOQFree beta = true  ->\n  free_FO beta y = false ->\n  free_FO (instant_cons_empty' alpha beta) y = false.\nProof.\n  induction beta; intros alpha [xn] Hno H.\n    destruct p as [Pn]; destruct f as [ym].\n    simpl in *.\n    unfold instant_cons_empty'.\n    simpl. case_eq (is_in_pred (Pred Pn) (preds_in alpha));\n      intros H2.\n      simpl. assumption.\n      simpl. rewrite <- beq_nat_refl.\n      simpl. rewrite H. reflexivity.\n\n    destruct f as [ym]; destruct f0 as [zn]. simpl in *.\n    assumption.\n\n    destruct f as [ym]; destruct f0 as [zn]. simpl in *.\n    assumption.\n\n    destruct f as [ym]. simpl in *.\n    rewrite instant_cons_empty'_allFO.\n    simpl.\n    case_eq (beq_nat xn ym); intros Hbeq;\n      rewrite Hbeq in *. reflexivity.\n      apply IHbeta; assumption.\n\n    destruct f as [ym]. simpl in *.\n    rewrite instant_cons_empty'_exFO.\n    simpl.\n    case_eq (beq_nat xn ym); intros Hbeq;\n      rewrite Hbeq in *. reflexivity.\n      apply IHbeta; assumption.\n\n    rewrite instant_cons_empty'_negSO.\n    simpl in *. apply IHbeta; assumption.\n\n    rewrite instant_cons_empty'_conjSO.\n    simpl in *. case_eq (SOQFree beta1);\n      intros H2; rewrite H2 in *. 2 : discriminate.\n    case_eq (free_FO beta1 (Var xn)); intros H3;\n      rewrite H3 in H. discriminate.\n    rewrite IHbeta1. apply IHbeta2. all : try assumption.\n    reflexivity.\n\n    rewrite instant_cons_empty'_disjSO.\n    simpl in *. case_eq (SOQFree beta1);\n      intros H2; rewrite H2 in *. 2 : discriminate.\n    case_eq (free_FO beta1 (Var xn)); intros H3;\n      rewrite H3 in H. discriminate.\n    rewrite IHbeta1. apply IHbeta2. all : try assumption.\n    reflexivity.\n\n    rewrite instant_cons_empty'_implSO.\n    simpl in *. case_eq (SOQFree beta1);\n      intros H2; rewrite H2 in *. 2 : discriminate.\n    case_eq (free_FO beta1 (Var xn)); intros H3;\n      rewrite H3 in H. discriminate.\n    rewrite IHbeta1. apply IHbeta2. all : try assumption.\n    reflexivity.\n\n    simpl in *. destruct p. discriminate.\n\n    simpl in *. destruct p. discriminate.\nQed.\n\nFixpoint max_l l : nat :=\n  match l with  \n  | nil => 0\n  | cons n l' => max n (max_l l')\n  end.\n\nFixpoint min_l l : nat :=\n  match l with  \n  | nil => 0\n  | cons n nil => n\n  | cons n l' => min n (min_l l')\n  end.\n\nLemma rename_FOv_att_allFO: forall alpha x y z,\n  attached_allFO_x alpha x = false ->\n  ~z = x ->\n  attached_allFO_x (rename_FOv alpha y z) x = false.\nProof.\n  induction alpha; intros [xn] [ym] [zn] Hat Hneq.\n    simpl in *. destruct f as [un].   \n    case_eq (beq_nat ym un); intros Hbeq;\n      reflexivity.\n\n    destruct f as [un]. destruct f0 as [wn].\n    simpl in *. case_eq (beq_nat ym un); intros Hbeq;\n      case_eq (beq_nat ym wn); intros Hbeq2;\n        reflexivity.\n\n    destruct f as [un]. destruct f0 as [wn].\n    simpl in *. case_eq (beq_nat ym un); intros Hbeq;\n      case_eq (beq_nat ym wn); intros Hbeq2;\n        reflexivity.\n\n    destruct f as [un]. simpl in *.\n    case_eq (beq_nat xn un); intros Hbeq3;\n      rewrite Hbeq3 in *. discriminate.\n    case_eq (beq_nat un ym); intros Hbeq.\n      simpl. rewrite beq_nat_comm.\n      rewrite FOvar_neq. unfold rename_FOv in IHalpha.\n      apply (IHalpha (Var xn) (Var ym) (Var zn)).\n      all : try assumption.\n\n      simpl. rewrite Hbeq3.\n      apply (IHalpha (Var xn) (Var ym) (Var zn)); assumption.\n\n    destruct f as [un]. simpl in *.\n    case_eq (beq_nat un ym); intros Hbeq.\n      simpl.\n      apply (IHalpha (Var xn) (Var ym) (Var zn)).\n      all : try assumption.\n\n      simpl.\n      apply (IHalpha (Var xn) (Var ym) (Var zn)); assumption.\n\n    simpl in *. apply (IHalpha (Var xn) (Var ym) (Var zn)); assumption.\n\n    simpl in *. case_eq (attached_allFO_x alpha1 (Var xn));\n      intros Hat2; rewrite Hat2 in *. discriminate.\n    unfold rename_FOv in *.\n    rewrite (IHalpha1 (Var xn) (Var ym) (Var zn)).\n    apply (IHalpha2 (Var xn) (Var ym) (Var zn)).\n    all : try assumption.\n\n    simpl in *. case_eq (attached_allFO_x alpha1 (Var xn));\n      intros Hat2; rewrite Hat2 in *. discriminate.\n    unfold rename_FOv in *.\n    rewrite (IHalpha1 (Var xn) (Var ym) (Var zn)).\n    apply (IHalpha2 (Var xn) (Var ym) (Var zn)).\n    all : try assumption.\n\n    simpl in *. case_eq (attached_allFO_x alpha1 (Var xn));\n      intros Hat2; rewrite Hat2 in *. discriminate.\n    unfold rename_FOv in *.\n    rewrite (IHalpha1 (Var xn) (Var ym) (Var zn)).\n    apply (IHalpha2 (Var xn) (Var ym) (Var zn)).\n    all : try assumption.\n\n    destruct p; simpl in *. apply (IHalpha (Var xn) (Var ym) (Var zn));\n    assumption.\n\n    destruct p; simpl in *. apply (IHalpha (Var xn) (Var ym) (Var zn));\n    assumption.\nQed.\n\nLemma newnew_pre_nil : forall l alpha,\n  newnew_pre alpha l nil = alpha.\nProof.\n  induction l; intros alpha;\n    reflexivity.\nQed.\n\nLemma rev_seq_nil : forall m n,\n  rev_seq n m = nil -> m = 0.\nProof.\n  induction m; intros n H.\n    reflexivity.\n\n    simpl in H. discriminate.\nQed.\n\nLemma min_l_rev_seq : forall m n,\n  min_l (rev_seq n (S m)) = n.\nProof.\n  induction m; intros n.\n    simpl in *. apply plus_zero.\n\n    simpl. case_eq (rev_seq n m). intros H.\n      apply rev_seq_nil in H. rewrite H.\n      rewrite <- one_suc.\n      rewrite plus_zero.\n      apply min_suc.\n\n      intros n' l Heq.\n      rewrite <- Heq.\n      specialize (IHm n).\n      simpl in IHm. rewrite Heq in IHm.\n      rewrite <- Heq in IHm.\n      rewrite IHm.\n      apply min_plus_l.\nQed.\n\nLemma want9 : forall l2 l1 beta1,\n  (forall P,\n    is_in_pred P l2 = true /\\\n    is_in_pred P (preds_in beta1) = true ->\n      is_in_pred P l1 = true) ->\n  replace_pred_l beta1 (app l1 l2) \n      (nlist_list (length l1 + length l2) (nlist_Var1 (length l1 + length l2)))\n      (nlist_list (length l1 + length l2) (nlist_empty (length l1 + length l2))) =\n  replace_pred_l beta1 l1 (nlist_list (length l1) (nlist_Var1 _))\n      (nlist_list (length l1) (nlist_empty _)).\nProof.\n  induction l2; intros l1 beta1 H.\n    simpl. rewrite app_nil_r.\n    rewrite plus_zero. reflexivity.\n\n    pose proof (rep_pred_l_app beta1 l1 (cons a l2)) as H2.\n    simpl in *. rewrite app_length in H2. simpl in H2. rewrite H2.\n    case_eq (is_in_pred a l2); intros H3.\n      destruct (nlist_list_ex (length l2) l2 eq_refl) as [lP H4].\n      rewrite <- H4.\n      rewrite length_nlist_list.\n      rewrite rep_pred__l_is_in.\n      rewrite H4.\n      pose proof (rep_pred_l_app beta1 l1 l2) as H5.\n      rewrite <- H5. rewrite app_length. simpl.\n      apply IHl2.\n        intros [Pn] H6.\n        specialize (H (Pred Pn)). simpl in H.\n        destruct a as [Qm].\n        case_eq (beq_nat Pn Qm); intros Hbeq;\n          rewrite Hbeq in *.\n          apply H. apply conj. reflexivity.\n          apply H6.\n\n          apply H. apply H6.\n          rewrite H4. assumption.\n\n          apply un_predless_l_empty_n.\n\n          reflexivity.\n\n        rewrite Rep_Pred_FOv.rep_pred__l_switch_empty.\n      pose proof (rep_pred_l_app beta1 l1 l2) as H5.\n      rewrite <- H5. rewrite app_length. simpl.\n      rewrite IHl2.\n        specialize (H a). destruct a as [Qm].\n        rewrite <- beq_nat_refl in H.\n        \n    case_eq (is_in_pred (Pred Qm) l1); intros H6.\n      destruct (nlist_list_ex (length l1) l1 eq_refl) as [lP H4].\n      rewrite <- H4.\n      rewrite length_nlist_list.\n      rewrite rep_pred__l_is_in. reflexivity.\n      rewrite H4. assumption.\n\n          apply un_predless_l_empty_n.\n\n          reflexivity.\n\n        rewrite <- Rep_Pred_FOv.rep_pred__l_switch_empty.\n        case_eq (is_in_pred (Pred Qm) (preds_in beta1)); intros H8.\n          rewrite H8 in *. rewrite H6 in H.\n          assert (true = true /\\ true = true) as H9.\n            apply conj; reflexivity.\n          discriminate (H H9).\n\n          rewrite P_occ_rep_pred_f. reflexivity.\nunfold P_occurs_in_alpha.\n          apply P_occ_in_l_is_in_pred.\n          assumption.\n\n          intros [Pn] H6.\n          apply H. destruct a as [Qm].\n          apply conj.\n            case_eq (beq_nat Pn Qm); intros Hbeq.\n              reflexivity.\n  \n              all : apply H6.\nQed.\n\nLemma want12 : forall l1 l2 P,\n  is_in_pred P l1 = true ->\n  is_in_pred P l2 = false ->\n  is_in_pred P (list_pred_not_in l2 l1) = true.\nProof.\n  induction l1; intros l2 [Pn] H1 H2.\n    simpl in *. discriminate.\n\n    simpl in *. destruct a as [Qm].\n    case_eq (beq_nat Pn Qm); intros Hbeq;\n      rewrite Hbeq in *.\n      rewrite <- (beq_nat_true _ _ Hbeq)  in *.\n      rewrite H2.\n      simpl. rewrite <- beq_nat_refl. reflexivity.\n\n      case_eq (is_in_pred (Pred Qm) l2); intros H3.\n        apply IHl1; assumption.\n\n        simpl. rewrite Hbeq.\n        apply IHl1; assumption.\nQed.\n\nLemma want11 : forall l1 l2 l P,\nis_in_pred P (list_pred_not_in l l1) = true /\\\nis_in_pred P l2 = true ->\nis_in_pred P (list_pred_not_in l l2) = true.\nProof.\n  induction l1; intros l2 l [Pn] [H1 H2].\n    simpl in *. discriminate.\n\n    simpl in *. destruct a as [Qm].\n    case_eq (is_in_pred (Pred Qm) l); intros H3;\n      rewrite H3 in *.\n      apply IHl1. apply conj; assumption.\n\n      simpl in *.\n      case_eq (beq_nat Pn Qm); intros Hbeq;\n        rewrite Hbeq in *.\n        rewrite (beq_nat_true _ _ Hbeq) in *.\n        apply want12; assumption.\n\n        apply IHl1. apply conj; assumption.\nQed.\n\nLemma want13 : forall l x y,\n  ~ x = y ->\n  is_in_FOvar y (rem_FOv l x) =\n  is_in_FOvar y l.\nProof.\n  induction l; intros [xn] [ym] Hneq.\n    reflexivity.\n\n    simpl in *. destruct a as [zn].\n    case_eq (beq_nat xn zn); intros Hbeq;\n      case_eq (beq_nat ym zn); intros Hbeq2.\n        apply neq_beq_nat_FOv in Hneq.\n        rewrite (beq_nat_true _ _ Hbeq) in Hneq.\n        rewrite beq_nat_comm in Hneq.\n        rewrite Hneq in Hbeq2. discriminate.\n\n        apply IHl. assumption.\n\n        simpl. rewrite Hbeq2. reflexivity.\n\n        simpl. rewrite Hbeq2. apply IHl.\n        assumption.\nQed.\n\nLemma is_in_FOvar_rename_FOv_list : forall l x y z,\n  ~ x = y ->\n  ~ x = z ->\n  ~ y = z ->\n  is_in_FOvar x (rename_FOv_list l y z) =\n  is_in_FOvar x l.\nProof.\n  induction l; intros [xn] [ym] [zn] H1 H2 H3.\n    reflexivity.\n\n    destruct a as [un]. simpl in  *.\n    case_eq (beq_nat ym un); intros Hbeq.\n      simpl. pose proof (neq_beq_nat_FOv _ _ H2) as H'.\n      rewrite H'. case_eq (beq_nat xn un); intros Hbeq2.\n        rewrite (beq_nat_true _ _ Hbeq) in H1.\n        rewrite (beq_nat_true _ _ Hbeq2) in H1.\n        contradiction (H1 eq_refl).\n\n        apply IHl; assumption.\n\n      simpl. case_eq (beq_nat xn un); intros Hbeq2.\n        reflexivity.\n        apply IHl; assumption.\nQed.\n\nLemma want16 : forall l beta n xn ym,\n  ~ (Var xn) = (Var ym) ->\n  free_FO beta (Var ym) = false ->\n  Nat.leb ym n = true ->\n  is_in_FOvar (Var ym) l = true ->\n  is_in_FOvar (Var ym) (FOvars_in\n      (newnew_pre beta (rem_FOv l (Var xn))\n        (rev_seq (S n)\n        (length (rem_FOv l (Var xn)))))) = false.\nProof.\n  induction l; intros beta n xn ym Hneq Hfree Hleb Hin2.\n    simpl in *. discriminate.\n\n    simpl in *. destruct a as [zn].\n    case_eq (beq_nat xn zn); intros Hbeq.\n      case_eq (beq_nat ym zn); intros Hbeq2;\n        rewrite Hbeq2 in *.\n        rewrite (beq_nat_true _ _ Hbeq2) in Hneq.\n        rewrite (beq_nat_true _ _ Hbeq) in Hneq.\n        contradiction (Hneq eq_refl).\n\n        apply IHl; assumption.\n\n      simpl. rewrite hmm1.\n      case_eq (beq_nat ym zn); intros Hbeq2;\n        rewrite Hbeq2 in Hin2.\n        rewrite <- (beq_nat_true _ _ Hbeq2) in *.\n        case_eq (beq_nat ym (S (n + length (rem_FOv l (Var xn)))));\n          intros Hbeq3.\n          rewrite (beq_nat_true _ _ Hbeq3) in Hleb.\n          rewrite <- plus_Sn_m in Hleb.\n          apply leb_plus_r with (m := (length (rem_FOv l (Var xn))))\n            in Hleb.\n          rewrite <- leb_plus in Hleb.\n          rewrite leb_suc_f in Hleb.\n          discriminate.\n\n          apply is_in_FOvar_rename.\n          intros H. inversion H as [H'].\n          rewrite H' in Hbeq3.\n          rewrite <- beq_nat_refl in Hbeq3.\n          discriminate.\n\n        simpl.\n        case_eq (beq_nat zn (S (n + length (rem_FOv l (Var xn)))));\n          intros Hbeq3. rewrite (beq_nat_true _ _ Hbeq3).\n          rewrite rename_FOv_list_refl.\n          apply IHl; try assumption.\n       \n        rewrite is_in_FOvar_rename_FOv_list.\n        apply IHl. all : try assumption.\n          apply beq_nat_false_FOv. assumption.\n          intros H; inversion H as [H'].\n          rewrite H' in Hleb.\n          rewrite <- plus_Sn_m in Hleb.\n          apply leb_plus_r with (m := (length (rem_FOv l (Var xn))))\n            in Hleb.\n          rewrite <- leb_plus in Hleb.\n          rewrite leb_suc_f in Hleb.\n          discriminate.\n\n          intros H. inversion H as [H'].\n          rewrite H' in Hbeq3.\n          rewrite <- beq_nat_refl in Hbeq3.\n          discriminate.\n\nQed.\n\nLemma want19 : forall alpha ym,\n  is_in_FOvar (Var ym) (FOvars_in alpha) = true ->\n  Nat.leb ym (max_FOv alpha) = true.\nProof.\n  induction alpha; intros xn H.\n    destruct p as [Pn]; destruct f as [ym]. simpl in *.\n    case_eq (beq_nat xn ym); intros Hbeq;\n      rewrite Hbeq in *. 2: discriminate.\n      rewrite (beq_nat_true _ _ Hbeq).\n      apply leb_refl.\n\n    destruct f as [y1]; destruct f0 as [y2].\n    simpl in * . case_eq (beq_nat xn y1); intros Hbeq;\n      rewrite Hbeq in *.\n      rewrite <- (beq_nat_true _ _ Hbeq).\n      apply leb_max_suc3. apply leb_refl.\n\n      case_eq (beq_nat xn y2); intros Hbeq2;\n        rewrite Hbeq2 in *. 2 : discriminate.\n      rewrite <- (beq_nat_true _ _ Hbeq2).\n      rewrite max_comm.\n      apply leb_max_suc3. apply leb_refl.\n\n    destruct f as [y1]; destruct f0 as [y2].\n    simpl in * . case_eq (beq_nat xn y1); intros Hbeq;\n      rewrite Hbeq in *.\n      rewrite <- (beq_nat_true _ _ Hbeq).\n      apply leb_max_suc3. apply leb_refl.\n\n      case_eq (beq_nat xn y2); intros Hbeq2;\n        rewrite Hbeq2 in *. 2 : discriminate.\n      rewrite <- (beq_nat_true _ _ Hbeq2).\n      rewrite max_comm.\n      apply leb_max_suc3. apply leb_refl.\n\n    destruct f as [ym]. simpl in *.\n    case_eq (beq_nat xn ym); intros Hbeq; \n      rewrite Hbeq in *. rewrite (beq_nat_true _ _ Hbeq).\n      apply leb_max_suc3. apply leb_refl.\n\n      rewrite max_comm.\n      apply leb_max_suc3.\n      apply IHalpha. assumption.\n\n    destruct f as [ym]. simpl in *.\n    case_eq (beq_nat xn ym); intros Hbeq; \n      rewrite Hbeq in *. rewrite (beq_nat_true _ _ Hbeq).\n      apply leb_max_suc3. apply leb_refl.\n\n      rewrite max_comm.\n      apply leb_max_suc3.\n      apply IHalpha. assumption.\n\n    simpl in *. apply IHalpha. assumption.\n\n    simpl in *. rewrite is_in_FOvar_app in H.\n    case_eq (is_in_FOvar (Var xn) (FOvars_in alpha1));\n      intros H1; rewrite H1 in H.\n      apply leb_max_suc3. apply IHalpha1.\n      assumption.\n\n      rewrite max_comm.\n      apply leb_max_suc3.\n      apply IHalpha2. assumption.\n\n    simpl in *. rewrite is_in_FOvar_app in H.\n    case_eq (is_in_FOvar (Var xn) (FOvars_in alpha1));\n      intros H1; rewrite H1 in H.\n      apply leb_max_suc3. apply IHalpha1.\n      assumption.\n\n      rewrite max_comm.\n      apply leb_max_suc3.\n      apply IHalpha2. assumption.\n\n    simpl in *. rewrite is_in_FOvar_app in H.\n    case_eq (is_in_FOvar (Var xn) (FOvars_in alpha1));\n      intros H1; rewrite H1 in H.\n      apply leb_max_suc3. apply IHalpha1.\n      assumption.\n\n      rewrite max_comm.\n      apply leb_max_suc3.\n      apply IHalpha2. assumption.\n\n    destruct p. simpl in *. apply IHalpha.\n    assumption.\n\n    destruct p. simpl in *. apply IHalpha.\n    assumption.\nQed.\n\nLemma kk4 : forall beta P x cond,\n  replace_pred (allSO P beta) P x cond =\n  replace_pred beta P x cond.\nProof.\n  intros. simpl. destruct P as [Pn].\n  rewrite <- beq_nat_refl. reflexivity.\nQed.\n\nLemma kk4_exSO : forall beta P x cond,\n  replace_pred (exSO P beta) P x cond =\n  replace_pred beta P x cond.\nProof.\n  intros. simpl. destruct P as [Pn].\n  rewrite <- beq_nat_refl. reflexivity.\nQed.\n\nLemma kk3 : forall lP beta P,\n(FOvars_in (replace_pred_l (allSO P beta) lP\n               (nlist_list (length lP) (nlist_Var1 (length lP)))\n               (nlist_list (length lP) (nlist_empty (length lP))))) =\n(FOvars_in (replace_pred_l beta lP\n               (nlist_list (length lP) (nlist_Var1 (length lP)))\n               (nlist_list (length lP) (nlist_empty (length lP))))).\nProof.\n  induction lP; intros beta [Pn].\n    simpl. reflexivity.\n\n    simpl in *. destruct a as [Qm].\n    rewrite <- Rep_Pred_FOv.rep_pred__l_switch_empty.\n    case_eq (beq_nat Pn Qm); intros Hbeq.\n      rewrite (beq_nat_true _ _ Hbeq).\n      rewrite kk4.\n      rewrite Rep_Pred_FOv.rep_pred__l_switch_empty.\n      reflexivity.\n\n      simpl. rewrite beq_nat_comm. rewrite Hbeq.\n      rewrite IHlP.\n      rewrite Rep_Pred_FOv.rep_pred__l_switch_empty.\n      reflexivity.\nQed.\n\nLemma kk3_exSO : forall lP beta P,\n(FOvars_in (replace_pred_l (exSO P beta) lP\n               (nlist_list (length lP) (nlist_Var1 (length lP)))\n               (nlist_list (length lP) (nlist_empty (length lP))))) =\n(FOvars_in (replace_pred_l beta lP\n               (nlist_list (length lP) (nlist_Var1 (length lP)))\n               (nlist_list (length lP) (nlist_empty (length lP))))).\nProof.\n  induction lP; intros beta [Pn].\n    simpl. reflexivity.\n\n    simpl in *. destruct a as [Qm].\n    rewrite <- Rep_Pred_FOv.rep_pred__l_switch_empty.\n    case_eq (beq_nat Pn Qm); intros Hbeq.\n      rewrite (beq_nat_true _ _ Hbeq).\n      rewrite kk4_exSO.\n      rewrite Rep_Pred_FOv.rep_pred__l_switch_empty.\n      reflexivity.\n\n      simpl. rewrite beq_nat_comm. rewrite Hbeq.\n      rewrite IHlP.\n      rewrite Rep_Pred_FOv.rep_pred__l_switch_empty.\n      reflexivity.\nQed.\n\nLemma kk2 : forall lP beta P y,\n  is_in_FOvar y (FOvars_in (replace_pred_l (allSO P beta) lP\n      (nlist_list (length lP) (nlist_Var1 _))\n      (nlist_list (length lP) (nlist_empty _)))) =\n  is_in_FOvar y (FOvars_in (replace_pred_l  beta lP\n      (nlist_list (length lP) (nlist_Var1 _))\n      (nlist_list (length lP) (nlist_empty _)))).\nProof.\n  intros. rewrite kk3.\n  reflexivity.\nQed.\n\nLemma kk2_exSO : forall lP beta P y,\n  is_in_FOvar y (FOvars_in (replace_pred_l (exSO P beta) lP\n      (nlist_list (length lP) (nlist_Var1 _))\n      (nlist_list (length lP) (nlist_empty _)))) =\n  is_in_FOvar y (FOvars_in (replace_pred_l  beta lP\n      (nlist_list (length lP) (nlist_Var1 _))\n      (nlist_list (length lP) (nlist_empty _)))).\nProof.\n  intros. rewrite kk3_exSO.\n  reflexivity.\nQed.\n\nLemma is_in_FOvar_l_trans : forall l1 l2 l3,\n  is_in_FOvar_l l1 l2 = true ->\n  is_in_FOvar_l l2 l3 = true ->\n  is_in_FOvar_l l1 l3 = true.\nProof.\n  induction l1; intros l2 l3 H1 H2.\n    reflexivity.\n\n    simpl in *. case_eq (is_in_FOvar a l2);\n      intros H; rewrite H in *.\n      rewrite (is_in__FOvar _ _ _ H2 H).\n      apply IHl1 with (l2 := l2); assumption.\n      discriminate.\nQed.\n\nLemma is_in_FOvar_l_cons_r2 : forall l1 l2 x,\n  is_in_FOvar_l l1 l2 = true ->\n  is_in_FOvar_l l1 (cons x l2) = true.\nProof.\n  induction l1; intros l2 [xn] H.\n    reflexivity.\n\n    destruct a as [ym].\n    simpl in *. case_eq (is_in_FOvar (Var ym) l2);\n      intros H2; rewrite H2 in*. 2 :discriminate.\n    rewrite if_then_else_true. apply IHl1.\n    assumption.\nQed.\n\nLemma is_in_FOvar_l_app_r1 : forall l1 l2 l3,\n  is_in_FOvar_l l1 l2 = true ->\n  is_in_FOvar_l l1 (app l3 l2) = true.\nProof.\n  induction l1; intros l2 l3 H.\n    reflexivity.\n\n    simpl in *. case_eq (is_in_FOvar a l2);\n      intros H2; rewrite H2 in *;\n      rewrite is_in_FOvar_app;\n      rewrite H2. rewrite if_then_else_true.\n      apply IHl1; assumption.\n\n      discriminate.\nQed.\n\nLemma is_in_FOvar_l_app : forall l1 l2 l3 l4,\n  is_in_FOvar_l l1 l2 = true ->\n  is_in_FOvar_l l3 l4 = true ->\n  is_in_FOvar_l (app l1 l3) (app l2 l4) = true.\nProof.\n  induction l1; intros l2 l3 l4 H1 H2.\n    simpl. apply is_in_FOvar_l_app_r1.\n    apply H2.\n\n    simpl in *. case_eq (is_in_FOvar a l2);\n      intros H; rewrite H in *;\n      rewrite is_in_FOvar_app;\n      rewrite H. apply IHl1; assumption.\n      discriminate.\nQed.\n\n\nLemma is_in_FOvar_l_refl : forall l,\n  is_in_FOvar_l l l = true.\nProof.\n  induction l.\n    reflexivity.\n\n    simpl. destruct a as [xn]. rewrite <- beq_nat_refl.\n    apply is_in_FOvar_l_cons_r2. assumption.\nQed.\n\nLemma kk5 : forall alpha P x,\n  is_in_FOvar_l (FOvars_in (replace_pred alpha P x (negSO (eqFO x x))))\n  (FOvars_in alpha) = true.\nProof.\n  induction alpha; intros [Pn] [xn].\n    destruct p as [Qm]. destruct f as [ym].\n    simpl. rewrite <- beq_nat_refl.\n    case_eq (beq_nat Pn Qm); intros Hbeq;\n      simpl; rewrite <- beq_nat_refl;\n      reflexivity.\n\n    destruct f as [y1]; destruct f0 as [y2]. simpl.\n    do 2rewrite <- beq_nat_refl.\n    case_eq (beq_nat y2 y1); intros Hbeq; reflexivity.\n\n    destruct f as [y1]; destruct f0 as [y2]. simpl.\n    do 2rewrite <- beq_nat_refl.\n    case_eq (beq_nat y2 y1); intros Hbeq; reflexivity.\n\n    destruct f as [ym]. simpl. rewrite <- beq_nat_refl.\n    apply is_in_FOvar_l_trans with (l2 := FOvars_in alpha).\n      apply IHalpha. apply is_in_FOvar_l_cons_r2.\n      apply is_in_FOvar_l_refl.\n\n\n    destruct f as [ym]. simpl. rewrite <- beq_nat_refl.\n    apply is_in_FOvar_l_trans with (l2 := FOvars_in alpha).\n      apply IHalpha. apply is_in_FOvar_l_cons_r2.\n      apply is_in_FOvar_l_refl.\n\n    simpl. apply IHalpha.\n\n    simpl. apply is_in_FOvar_l_app.\n      apply IHalpha1. apply IHalpha2.\n\n    simpl. apply is_in_FOvar_l_app.\n      apply IHalpha1. apply IHalpha2.\n\n    simpl. apply is_in_FOvar_l_app.\n      apply IHalpha1. apply IHalpha2.\n\n    simpl. destruct p as [Qm].\n    case_eq (beq_nat Pn Qm); intros Hbeq.\n      apply IHalpha.\n      simpl. apply IHalpha.\n\n    simpl. destruct p as [Qm].\n    case_eq (beq_nat Pn Qm); intros Hbeq.\n      apply IHalpha.\n      simpl. apply IHalpha.\nQed.\n\nLemma kk6 : forall alpha P x,\n  is_in_FOvar_l (FOvars_in alpha)\n    (FOvars_in (replace_pred alpha P x (negSO (eqFO x x))))\n   = true.\nProof.\n  induction alpha; intros [Pn] [xn].\n    destruct p as [Qm]. destruct f as [ym].\n    simpl. rewrite <- beq_nat_refl.\n    case_eq (beq_nat Pn Qm); intros Hbeq;\n      simpl; rewrite <- beq_nat_refl;\n      reflexivity.\n\n    destruct f as [y1]; destruct f0 as [y2]. simpl.\n    do 2rewrite <- beq_nat_refl.\n    case_eq (beq_nat y2 y1); intros Hbeq; reflexivity.\n\n    destruct f as [y1]; destruct f0 as [y2]. simpl.\n    do 2rewrite <- beq_nat_refl.\n    case_eq (beq_nat y2 y1); intros Hbeq; reflexivity.\n\n    destruct f as [ym]. simpl. rewrite <- beq_nat_refl.\n    apply is_in_FOvar_l_trans with (l2 := FOvars_in alpha).\n    apply is_in_FOvar_l_refl. apply is_in_FOvar_l_cons_r2.\n    apply IHalpha.\n\n    destruct f as [ym]. simpl. rewrite <- beq_nat_refl.\n    apply is_in_FOvar_l_trans with (l2 := FOvars_in alpha).\n    apply is_in_FOvar_l_refl. apply is_in_FOvar_l_cons_r2.\n    apply IHalpha.\n\n    simpl. apply IHalpha.\n\n    simpl. apply is_in_FOvar_l_app.\n      apply IHalpha1. apply IHalpha2.\n\n    simpl. apply is_in_FOvar_l_app.\n      apply IHalpha1. apply IHalpha2.\n\n    simpl. apply is_in_FOvar_l_app.\n      apply IHalpha1. apply IHalpha2.\n\n    simpl. destruct p as [Qm].\n    case_eq (beq_nat Pn Qm); intros Hbeq.\n      apply IHalpha.\n      simpl. apply IHalpha.\n\n    simpl. destruct p as [Qm].\n    case_eq (beq_nat Pn Qm); intros Hbeq.\n      apply IHalpha.\n      simpl. apply IHalpha.\nQed.\n\n\nLemma kk1 : forall beta alpha y,\n  is_in_FOvar y (FOvars_in alpha) = true ->\n  is_in_FOvar y (FOvars_in beta) = true ->\n  is_in_FOvar y (FOvars_in (instant_cons_empty' alpha beta)) = true.\nProof.\n  unfold instant_cons_empty'.\n  induction beta; intros alpha [ym] H1 H2.\n    destruct p as [Pn]; destruct f as [xn].\n    simpl. case_eq (is_in_pred (Pred Pn) (preds_in alpha));\n      intros Hin. simpl in *. assumption.\n\n      simpl. rewrite <- beq_nat_refl. simpl in *.\n      case_eq (beq_nat ym xn); intros Hbeq;\n        rewrite Hbeq in *. reflexivity.\n        discriminate.\n\n    destruct f as [x1]; destruct f0 as [x2].\n    simpl in *. assumption.\n\n    destruct f as [x1]; destruct f0 as [x2].\n    simpl in *. assumption.\n\n    destruct f as [xn]. simpl in *.\n    rewrite rep_pred_l_allFO.\n    simpl. case_eq (beq_nat ym xn); intros Hbeq;\n      rewrite Hbeq in *. reflexivity.\n      apply IHbeta; assumption.\n\n    destruct f as [xn]. simpl in *.\n    rewrite rep_pred_l_exFO.\n    simpl. case_eq (beq_nat ym xn); intros Hbeq;\n      rewrite Hbeq in *. reflexivity.\n      apply IHbeta; assumption.\n\n    simpl in *. rewrite rep_pred_l_negSO.\n    simpl. apply IHbeta; assumption.\n\n    simpl in *. rewrite list_pred_not_in_app.\n    rewrite rep_pred_l_conjSO. rewrite app_length. \n    simpl.\n    rewrite want9. rewrite <- app_length.\n    rewrite rep_pred_l_app.\n    rewrite rep_pred_l_switch.\n    rewrite <- rep_pred_l_app.\n    rewrite app_length.\n    rewrite want9.\n    rewrite is_in_FOvar_app in *.\n    case_eq (is_in_FOvar (Var ym) (FOvars_in beta1)); intros Ha;\n      rewrite Ha in *.\n      rewrite IHbeta1; try assumption.\n\n      rewrite IHbeta2; try assumption.\n      rewrite if_then_else_true. reflexivity.\n      apply want11. apply want11.\n\n    simpl in *. rewrite list_pred_not_in_app.\n    rewrite rep_pred_l_disjSO. rewrite app_length. \n    simpl.\n    rewrite want9. rewrite <- app_length.\n    rewrite rep_pred_l_app.\n    rewrite rep_pred_l_switch.\n    rewrite <- rep_pred_l_app.\n    rewrite app_length.\n    rewrite want9.\n    rewrite is_in_FOvar_app in *.\n    case_eq (is_in_FOvar (Var ym) (FOvars_in beta1)); intros Ha;\n      rewrite Ha in *.\n      rewrite IHbeta1; try assumption.\n\n      rewrite IHbeta2; try assumption.\n      rewrite if_then_else_true. reflexivity.\n      apply want11. apply want11.\n\n    simpl in *. rewrite list_pred_not_in_app.\n    rewrite rep_pred_l_implSO. rewrite app_length. \n    simpl.\n    rewrite want9. rewrite <- app_length.\n    rewrite rep_pred_l_app.\n    rewrite rep_pred_l_switch.\n    rewrite <- rep_pred_l_app.\n    rewrite app_length.\n    rewrite want9.\n    rewrite is_in_FOvar_app in *.\n    case_eq (is_in_FOvar (Var ym) (FOvars_in beta1)); intros Ha;\n      rewrite Ha in *.\n      rewrite IHbeta1; try assumption.\n\n      rewrite IHbeta2; try assumption.\n      rewrite if_then_else_true. reflexivity.\n      apply want11. apply want11.\n\n    destruct p as [Pn]. simpl.\n    simpl in *.\n    case_eq (is_in_pred (Pred Pn) (preds_in alpha)); intros Ha.\n      rewrite kk2. apply IHbeta; assumption.\n\n      rewrite kk2.  simpl. apply is_in__FOvar with \n        (l1 := (FOvars_in (replace_pred_l beta (list_pred_not_in (preds_in alpha) (preds_in beta))\n           (nlist_list (length (list_pred_not_in (preds_in alpha) (preds_in beta)))\n              (nlist_Var1 (length (list_pred_not_in (preds_in alpha) (preds_in beta)))))\n           (nlist_list (length (list_pred_not_in (preds_in alpha) (preds_in beta)))\n              (nlist_empty (length (list_pred_not_in (preds_in alpha) (preds_in beta)))))))).\n      apply kk6. apply IHbeta; assumption.\n\n    destruct p as [Pn]. simpl.\n    simpl in *.\n    case_eq (is_in_pred (Pred Pn) (preds_in alpha)); intros Ha.\n      rewrite kk2_exSO. apply IHbeta; assumption.\n\n      rewrite kk2_exSO.  simpl. apply is_in__FOvar with \n        (l1 := (FOvars_in (replace_pred_l beta (list_pred_not_in (preds_in alpha) (preds_in beta))\n           (nlist_list (length (list_pred_not_in (preds_in alpha) (preds_in beta)))\n              (nlist_Var1 (length (list_pred_not_in (preds_in alpha) (preds_in beta)))))\n           (nlist_list (length (list_pred_not_in (preds_in alpha) (preds_in beta)))\n              (nlist_empty (length (list_pred_not_in (preds_in alpha) (preds_in beta)))))))).\n      apply kk6. apply IHbeta; assumption.\nQed.\n\nLemma want15 : forall beta xn a alpha,\n  free_FO beta a = false ->\n  is_in_FOvar a (FOvars_in beta) = true ->\n  SOQFree beta = true ->\n  attached_allFO_x alpha (Var xn) = false ->\n  ~ (Var xn) = a ->\n  is_in_FOvar a (FOvars_in alpha) = true ->\n  is_in_FOvar a (FOvars_in\n    (newnew_pre (instant_cons_empty' alpha beta)\n       (rem_FOv (FOvars_in (instant_cons_empty' alpha beta)) (Var xn))\n       (rev_seq (S (Nat.max (Nat.max (max_FOv alpha) (max_FOv beta)) xn))\n          (length\n             (rem_FOv (FOvars_in (instant_cons_empty' alpha beta)) (Var xn))))))\n      = false.\nProof.\n  intros beta xn [ym] alpha Hfree Hin3 Hno Hat Hneq Hin2.\n  apply want16; try assumption.\n    apply free_FO_instant_cons_empty'_f; try assumption.\n\n    apply leb_max_suc3.\n    apply leb_max_suc3.\n    apply want19. assumption.\n    apply kk1; assumption.\nQed.\n\nLemma kk8 : forall lP beta x,\n  is_in_FOvar x (FOvars_in beta) = false ->\n  is_in_FOvar x (FOvars_in\n   (replace_pred_l beta lP (nlist_list (length lP) (nlist_Var1 _))\n      (nlist_list (length lP) (nlist_empty _)))) = false.\nProof.\n  induction lP; intros beta x H.\n    simpl. assumption.\n\n    simpl. \n    case_eq (is_in_FOvar x\n  (FOvars_in\n     (replace_pred\n        (replace_pred_l beta lP (nlist_list (length lP) (nlist_Var1 (length lP)))\n           (nlist_list (length lP) (nlist_empty (length lP)))) a \n        (Var 1) (negSO (eqFO (Var 1) (Var 1)))))); intros H2.\n      2 : reflexivity.\n    apply is_in__FOvar with (l2 := FOvars_in (replace_pred_l beta lP\n                (nlist_list (length lP) (nlist_Var1 (length lP)))\n                (nlist_list (length lP) (nlist_empty (length lP)))))  in H2.\n      rewrite IHlP in H2. discriminate.\n      assumption.\n\n      apply kk5.\nQed.\n\nLemma kk7 : forall beta alpha a,\n  is_in_FOvar a (FOvars_in beta) = false ->\n  is_in_FOvar a (FOvars_in (instant_cons_empty' alpha beta)) = false.\nProof.\n  intros beta alpha [Pn] H.\n  unfold instant_cons_empty'.\n  apply kk8.  \n  assumption.\nQed.\n\nLemma is_in_FOvar_att_allFO_x : forall alpha x,\n  is_in_FOvar x (FOvars_in alpha) = false ->\n  attached_allFO_x alpha x = false.\nProof.\n  induction alpha; intros [xn] H; try reflexivity.\n\n    destruct f as [ym]. simpl in *.\n    case_eq (beq_nat xn ym); intros Hbeq;\n      rewrite Hbeq in *. discriminate.\n      apply IHalpha. assumption.\n\n    destruct f as [ym]. simpl in *.\n    case_eq (beq_nat xn ym); intros Hbeq;\n      rewrite Hbeq in *. discriminate.\n      apply IHalpha. assumption.\n\n    simpl in *. apply IHalpha; assumption.\n\n    simpl in *. rewrite is_in_FOvar_app in H.\n    case_eq (is_in_FOvar (Var xn) (FOvars_in alpha1));\n      intros Hin; rewrite Hin in *. discriminate.\n    rewrite IHalpha1. apply IHalpha2.\n    all : try assumption.\n\n    simpl in *. rewrite is_in_FOvar_app in H.\n    case_eq (is_in_FOvar (Var xn) (FOvars_in alpha1));\n      intros Hin; rewrite Hin in *. discriminate.\n    rewrite IHalpha1. apply IHalpha2.\n    all : try assumption.\n\n    simpl in *. rewrite is_in_FOvar_app in H.\n    case_eq (is_in_FOvar (Var xn) (FOvars_in alpha1));\n      intros Hin; rewrite Hin in *. discriminate.\n    rewrite IHalpha1. apply IHalpha2.\n    all : try assumption.\n\n    destruct p. simpl in *.\n    apply IHalpha. assumption.\n\n    destruct p. simpl in *.\n    apply IHalpha. assumption.\nQed.\n\nLemma want14 : forall l beta xn a alpha,\n  SOQFree beta = true ->\n  free_FO beta a = false ->\n  ~ Var xn = a ->\n  is_in_FOvar a (FOvars_in beta) = true ->\n  is_in_FOvar_l l (FOvars_in alpha) = true ->\n  attached_allFO_x alpha (Var xn) = false ->\n  is_in_FOvar a (FOvars_in alpha) = true ->\n attached_allFO_x\n    (newnew_pre (instant_cons_empty' alpha beta)\n       (rem_FOv (FOvars_in (instant_cons_empty' alpha beta)) (Var xn))\n       (rev_seq (S (Nat.max (Nat.max (max_FOv alpha) (max_FOv beta)) xn))\n          (length\n             (rem_FOv (FOvars_in (instant_cons_empty' alpha beta)) (Var xn)))))\n    a = false.\nProof.\n  intros l beta xn [ym] alpha Hno Hfree Hin Hneq Hin3 Hat Hin2.\n  apply is_in_FOvar_att_allFO_x.\n  apply want15; try assumption.\nQed.\n\nLemma aa23 : forall l alpha x n,\n  ~ l = nil ->\n  x_occ_in_alpha alpha x = true ->\n  is_in_FOvar x l = false ->\n  attached_allFO_x alpha x = false ->\n  Nat.leb (max_FOv alpha) n = true ->\n  attached_allFO_x (newnew_pre alpha l\n    (rev_seq (S n) (length l))) x = false.\nProof.\n  induction l; intros alpha x n Hnil Hocc Hin Hat Hleb.\n    simpl. assumption.\n\n    simpl. simpl in Hin. destruct x as [xn].\n    destruct a as [ym]. case_eq (beq_nat xn ym);\n      intros Hbeq; rewrite Hbeq in *. discriminate.\n    case_eq l. intros Hnil2. rewrite Hnil2 in *. simpl.\n      rewrite <- plus_n_O.\n      rewrite <- rename_FOv__n.\n      apply rename_FOv_att_allFO; try assumption.\n      apply x_occ_in_alpha_max_FOv_gen in Hleb.\n      intros H. rewrite H in *. rewrite Hleb in *.\n      discriminate.\n\n      intros z l' Heq. assert (~ l = nil) as HH.\n        intros HH2. rewrite HH2 in Heq. discriminate.\n      specialize (IHl _ _ n HH Hocc Hin Hat Hleb).\n      apply rename_FOv_att_allFO. rewrite <- Heq. apply IHl.\n      rewrite <- Heq.\n      intros H. inversion H as [H'].\n      rewrite <- H' in Hocc.\n      rewrite x_occ_in_alpha_max_FOv_gen in Hocc.\n        discriminate.\n      apply (leb_trans _ n). assumption.\n      apply leb_plus_r. apply leb_refl.\nQed.\n\nLemma x_occ_in_alpha_instant_cons_empty'_pre_pre : forall beta P x y,\n  x_occ_in_alpha beta x = true ->\n  x_occ_in_alpha (replace_pred beta P y (negSO (eqFO y y ))) x = true.\nProof.\n  induction beta; intros [Pn] [xn] [ym] Hocc.\n    destruct p as [Qm]; destruct f as [zn].\n    simpl in *. rewrite <- beq_nat_refl.\n    case_eq (beq_nat Pn Qm); intros Hbeq;   \n      simpl; rewrite Hocc; reflexivity.\n\n    destruct f as [z1]; destruct f0 as [z2].\n    simpl in *. assumption.\n\n    destruct f as [z1]; destruct f0 as [z2].\n    simpl in *. assumption.\n\n    destruct f as [zn]. simpl in *. case_eq (beq_nat xn zn);\n      intros Hbeq; rewrite Hbeq in *. reflexivity.\n    apply IHbeta. assumption.\n\n    destruct f as [zn]. simpl in *. case_eq (beq_nat xn zn);\n      intros Hbeq; rewrite Hbeq in *. reflexivity.\n    apply IHbeta. assumption.\n\n    simpl in *. apply IHbeta. assumption.\n\n    simpl in *. case_eq (x_occ_in_alpha beta1 (Var xn)); intros H;\n      rewrite H in *. rewrite IHbeta1. reflexivity. assumption.\n\n      rewrite IHbeta2. rewrite if_then_else_true. reflexivity.\n      assumption.\n\n    simpl in *. case_eq (x_occ_in_alpha beta1 (Var xn)); intros H;\n      rewrite H in *. rewrite IHbeta1. reflexivity. assumption.\n\n      rewrite IHbeta2. rewrite if_then_else_true. reflexivity.\n      assumption.\n\n    simpl in *. case_eq (x_occ_in_alpha beta1 (Var xn)); intros H;\n      rewrite H in *. rewrite IHbeta1. reflexivity. assumption.\n\n      rewrite IHbeta2. rewrite if_then_else_true. reflexivity.\n      assumption.\n\n    destruct p as [Qm]. simpl in *.\n    case_eq (beq_nat Pn Qm); intros Hbeq; simpl;\n      apply IHbeta; assumption.\n\n    destruct p as [Qm]. simpl in *.\n    case_eq (beq_nat Pn Qm); intros Hbeq; simpl;\n      apply IHbeta; assumption.\nQed.\n\nLemma x_occ_in_alpha_instant_cons_empty'_pre : forall l beta x,\nx_occ_in_alpha beta x = true ->\nx_occ_in_alpha\n  (replace_pred_l beta l (nlist_list (length l) (nlist_Var1 _))\n        (nlist_list (length l) (nlist_empty _))) x = true.\nProof.\n  induction l; intros beta x Hocc.\n    simpl. assumption.\n\n    simpl. apply x_occ_in_alpha_instant_cons_empty'_pre_pre.\n    apply IHl. assumption.\nQed.\n\nLemma x_occ_in_alpha_instant_cons_empty' : forall beta alpha x,\n  x_occ_in_alpha beta x = true ->\n  x_occ_in_alpha (instant_cons_empty' alpha beta) x = true.\nProof.\n  unfold instant_cons_empty'.\n  intros. apply x_occ_in_alpha_instant_cons_empty'_pre.\n  assumption.\nQed.\n\nLemma is_in_FOvar_rem_FOv_f : forall l x,\n  is_in_FOvar x (rem_FOv l x) = false.\nProof.\n  induction l; intros [xn].\n    simpl. reflexivity.\n\n    simpl. destruct a as [ym].\n    case_eq (beq_nat xn ym); intros Hbeq.\n      apply IHl.\n\n      simpl. rewrite Hbeq. apply IHl.\nQed. \n\nLemma max_FOv_rep_pred : forall alpha P x,\n  max_FOv (replace_pred alpha P x (negSO (eqFO x x))) = \n  max_FOv alpha.\nProof.\n  induction alpha; intros [Pn] [xn].\n    destruct p as [Qm]; destruct f as [ym].\n    simpl. rewrite <- beq_nat_refl.\n    case_eq (beq_nat Pn Qm); intros Hbeq;\n      simpl. apply max_refl. reflexivity.\n\n    destruct f as [y1]; destruct f0 as [y2].\n    reflexivity.\n\n    destruct f as [y1]; destruct f0 as [y2].\n    reflexivity.\n\n    destruct f as [ym].\n    simpl. rewrite IHalpha. reflexivity.\n\n    destruct f as [ym].\n    simpl. rewrite IHalpha. reflexivity.\n\n    simpl in *. apply IHalpha.\n\n    simpl in *. rewrite IHalpha1. rewrite IHalpha2.\n    reflexivity.\n\n    simpl in *. rewrite IHalpha1. rewrite IHalpha2.\n    reflexivity.\n\n    simpl in *. rewrite IHalpha1. rewrite IHalpha2.\n    reflexivity.\n\n    destruct p as [Qm]. simpl.\n    case_eq (beq_nat Pn Qm); intros H; simpl;\n      apply IHalpha.\n\n    destruct p as [Qm]. simpl.\n    case_eq (beq_nat Pn Qm); intros H; simpl;\n      apply IHalpha.\nQed.\n\nLemma max_FOv_instant_cons_empty'_pre: forall l beta,\nmax_FOv\n  (replace_pred_l beta l (nlist_list (length l) (nlist_Var1 _))\n          (nlist_list (length l) (nlist_empty _))) =\nmax_FOv beta.\nProof.\n  induction l; intros beta.\n    simpl. reflexivity.\n\n    simpl. rewrite max_FOv_rep_pred.\n    apply IHl.\nQed.\n\nLemma max_FOv_instant_cons_empty': forall beta alpha,\n  (max_FOv (instant_cons_empty' alpha beta)) =\n  max_FOv beta.\nProof.\n  unfold instant_cons_empty'. intros.\n  apply max_FOv_instant_cons_empty'_pre.\nQed.\n\nLemma aa24 : forall l alpha beta ym n,\n  is_in_FOvar (Var ym) (FOvars_in alpha) = true ->\n  is_in_FOvar (Var ym) (FOvars_in beta) = false ->\n  is_in_FOvar (Var ym) l = false ->\n  Nat.leb ym n = true ->\nattached_allFO_x\n    (newnew_pre (instant_cons_empty' alpha beta) l\n       (rev_seq (S n) (length l))) (Var ym) = false.\nProof.\n  induction l; intros alpha beta ym n H1 H2 H3 Hleb.\n    simpl. apply att_allFO_instant_cons_empty'.\n    apply is_in_FOvar_att_allFO_x. assumption.\n\n    simpl.\n    case_eq (beq_nat (S (n + length l)) ym); intros Hbeq2.\n      rewrite <- (beq_nat_true _ _ Hbeq2) in Hleb.\n      rewrite <- plus_Sn_m in Hleb.\n      rewrite leb_suc_f2 in Hleb. discriminate.\n\n      apply rename_FOv_att_allFO.\n      apply IHl; try assumption.\n      simpl in H3. destruct a as [xn].\n      case_eq (beq_nat ym xn); intros Hbeq; \n        rewrite Hbeq in *. discriminate.\n      assumption.\n\n      apply beq_nat_false_FOv. assumption.\nQed.\n\nLemma want3 : forall l alpha beta xn,\n  SOQFree beta = true ->\n  is_in_FOvar_l l (FOvars_in alpha) = true ->\n  attached_allFO_x alpha (Var xn) = false ->\n  closed_except beta (Var xn) ->\n  attached_allFO_x beta (Var xn) = false ->\nex_attached_allFO_lv\n  (newnew_pre (instant_cons_empty' alpha beta)\n     (rem_FOv (FOvars_in (instant_cons_empty' alpha beta)) (Var xn))\n     (rev_seq (S (Nat.max (max_FOv (implSO alpha beta)) xn))\n        (length\n           (rem_FOv (FOvars_in (instant_cons_empty' alpha beta))\n              (Var xn))))) l = false.\nProof.\n  induction l; intros alpha beta xn Hno Hin Hat Hcl Hat2.\n    simpl. reflexivity.\n\n    simpl in Hin. case_eq (is_in_FOvar a (FOvars_in alpha)); intros Hin2;\n        rewrite Hin2 in *. 2 : discriminate.\n    simpl.\n    destruct a as [ym]. case_eq (beq_nat xn ym); intros Hbeq.\n      rewrite <- (beq_nat_true _ _ Hbeq).\n    case_eq (rem_FOv (FOvars_in (instant_cons_empty' alpha beta)) (Var xn)).\n      intros H. simpl.\n      rewrite att_allFO_instant_cons_empty'. 2 : assumption.\n      specialize (IHl alpha beta xn).\n      rewrite H in IHl. simpl in *. apply IHl.\n      all : try assumption.\n    intros y l' Heq. rewrite <- Heq.\n      rewrite aa23.\n     apply IHl. all : try assumption.\n      rewrite Heq. intros. discriminate.\n      apply x_occ_in_alpha_instant_cons_empty'.\n      apply (contrapos_bool_ff _ _ (x_occ_in_free_FO _ _)).\n      apply Hcl. apply is_in_FOvar_rem_FOv_f.\n\n      apply att_allFO_instant_cons_empty'. assumption.\n\n      rewrite max_FOv_instant_cons_empty'.\n      apply leb_max_suc3. rewrite max_comm.\n      apply leb_max_suc3.\n      apply leb_refl.\n\n      case_eq (is_in_FOvar (Var ym) (FOvars_in beta)); intros Hin3.\n\n    rewrite want14 with (l := l); try assumption. \n     apply IHl. all : try assumption.\n\n        unfold closed_except in Hcl.\n        apply Hcl. apply beq_nat_false_FOv.\n        assumption.\n\n        apply beq_nat_false_FOv. assumption.\n\n      rewrite aa24; try assumption.\n     apply IHl. all : try assumption.\n        rewrite want13.\n        apply kk7. assumption.\n\n        apply beq_nat_false_FOv. assumption.\n\n        apply leb_max_suc3.\n        apply leb_max_suc3.\n\n        apply want19. assumption.\nQed.\n\nLemma is_in_FOvar_l_fun2 : forall alpha P,\nis_in_FOvar_l (fun2 alpha P) (FOvars_in alpha) = true.\nProof.\n  induction alpha; intros [Pn].\n    destruct p as [Qm]; destruct f as [xn].\n    simpl. case_eq (beq_nat Pn Qm); intros Hbeq.\n      apply is_in_FOvar_l_refl. reflexivity.\n\n    destruct f; destruct f0.\n    reflexivity.\n\n    destruct f; destruct f0.\n    reflexivity.\n\n    destruct f. simpl. apply is_in_FOvar_l_cons_r2.\n    apply IHalpha.\n\n    destruct f. simpl. apply is_in_FOvar_l_cons_r2.\n    apply IHalpha.\n\n    simpl. apply IHalpha.\n\n    simpl. apply is_in_FOvar_l_app.\n    apply IHalpha1. apply IHalpha2.\n\n    simpl. apply is_in_FOvar_l_app.\n    apply IHalpha1. apply IHalpha2.\n\n    simpl. apply is_in_FOvar_l_app.\n    apply IHalpha1. apply IHalpha2.\n\n    simpl. apply IHalpha.\n\n    simpl. apply IHalpha.\nQed.", "meta": {"author": "caitlindabrera", "repo": "Sahlqvist", "sha": "d0a755fb663a6cabc0babb691564cdf575fc8b36", "save_path": "github-repos/coq/caitlindabrera-Sahlqvist", "path": "github-repos/coq/caitlindabrera-Sahlqvist/Sahlqvist-d0a755fb663a6cabc0babb691564cdf575fc8b36/vsSahlq_AiML/Coq code/vsSahlq_instant9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5, "lm_q1q2_score": 0.29065154532215665}}
{"text": "(** * Semantical domains for H-VHDL *)\n\n(** Module defining the semantical domains used in H-VHDL\n    simulation semantics. *)\n\nRequire Import common.CoqLib.\nRequire Import common.GlobalTypes.\nRequire Import common.ListLib.\nRequire Import String.\n\nImport ErrMonadNotations.\n\nRequire Import hvhdl.AbstractSyntax.\nRequire Import hvhdl.HVhdlTypes.\n\nOpen Scope N_scope.\n\n(** ** Value type and functions about values *)\n\nSection Values.\n\n  (** Defines the type of values used to express the semantics of the\n      H-VHDL language.\n\n      A value is either a boolean, a natural number, an array of\n      values. *)\n\n  Inductive value : Type :=\n  | Vbool : bool -> value\n  | Vnat : N -> value\n  | Varr : arrofvalues -> value\n                            \n  with arrofvalues : Type :=\n  | Arr_one : value -> arrofvalues\n  | Arr_cons : value -> arrofvalues -> arrofvalues.\n\n  Scheme value_ind_mut := Induction for value Sort Prop\n      with arrofvalues_ind_mut := Induction for arrofvalues Sort Prop.\n\n  (** Equality is decidable for the [value] type *)\n\n  Lemma value_eq_dec : forall x y : value, {x = y} + {x <> y}. Admitted.\n  \n  (** Conversion from [arrofvalues] to [list value] *)\n\n  Fixpoint aofv2list (aofv : arrofvalues) {struct aofv} : list (value) :=\n    match aofv with\n    | Arr_one v => [v]\n    | Arr_cons v tl => v :: aofv2list tl\n    end.\n\n  Coercion aofv2list : arrofvalues >-> list.\n\n  (** Accesses the element at position [i] in arrofvalues [aofv]. \n    \n    Returns an error (i.e, None) if the index is greater\n    than the list length.\n   *)\n\n  Fixpoint oget_at (i : nat) (aofv : arrofvalues) {struct aofv} : option value :=\n    match i, aofv with\n    (* Error, index out of bounds. *)\n    | S _, Arr_one v => None\n    | 0%nat, Arr_one v => Some v\n    | 0%nat, Arr_cons v aofv' => Some v\n    | S j, Arr_cons a aofv' => oget_at j aofv'\n    end.\n  \n  (** Given a proof that index [i] is strictly less than the size of\n      arrofvalues [aofv], accesses the value at position [i] in [aofv].\n   *)\n\n  Fixpoint get_at (i : nat) (aofv : arrofvalues) {struct aofv} : (i < List.length aofv)%nat -> value.\n    refine (\n        match i, aofv with\n        (* Error, index out of bounds. *)\n        | S _, Arr_one v => fun _ => _\n        | 0%nat, Arr_one v => fun _ => v\n        | 0%nat, Arr_cons v aofv' => fun pf => v\n        | (S j), Arr_cons a aofv' => fun pf => get_at j aofv' _\n        end);\n      [apply lt_S_n in l; apply Nat.nlt_0_r in l; contradiction\n      | apply (lt_S_n j (List.length aofv') pf)].\n  Defined.\n\n  (** Stores value [v] at position [i] in list of values [lofv]. \n    \n      Returns an error (i.e, None) if the index is greater than \n      the list length. *)\n\n  Fixpoint oset_at (v : value) (i : nat) (aofv : arrofvalues) {struct i} : option arrofvalues :=\n    match i, aofv with\n    (* Error, index out of bounds. *)\n    | S j, Arr_one _ => None\n    | 0%nat, Arr_one v' => Some (Arr_one v)\n    | 0%nat, Arr_cons v' tl => Some (Arr_cons v tl)\n    | (S j), Arr_cons v' tl =>\n        (* Inductive step. *)\n        match oset_at v j tl with\n        | Some aofv' => Some (Arr_cons v' aofv')\n        | None => None\n        end\n    end.\n\n  (** Given a proof that index [i] is strictly less than the size of\n    [aofv], stores value [v] at position [i] in [aofv], and returns\n    the new [arrofvalues].  *)\n\n  Fixpoint set_at (v : value) (i : nat) (aofv : arrofvalues) {struct i} : (i < List.length aofv)%nat -> arrofvalues.\n    refine (match i, aofv with\n            (* Error, index out of bounds. *)\n            | S j, Arr_one _ => fun _ => _\n            | 0%nat, Arr_one _ => fun _ => Arr_one v\n            | 0%nat, Arr_cons _ tl => fun _ => Arr_cons v tl\n            | (S j), Arr_cons v' tl => fun _ => Arr_cons v' (set_at v j tl _)\n            end).\n    apply lt_pred in l; simpl in l; apply Nat.nlt_0_r in l; contradiction.\n    apply (lt_S_n j (List.length tl) l).\n  Defined.\n\n  Functional Scheme set_at_ind := Induction for set_at Sort Prop.\n\n  (** Given a proof that [n > 0], returns an arrofvalues of length [n]\n    filled with value [v]. *)\n\n  Definition create_arr (n : nat) (v : value) : (n > 0)%nat -> arrofvalues :=\n    match n as n0 return ((n0 > 0)%nat -> arrofvalues) with\n    (* Absurd case, 0 > 0. *)\n    | 0%nat => fun H : (0 > 0)%nat => False_rect arrofvalues (Nat.nlt_0_r 0 H)\n    (* Case n > 0 *)\n    | S m =>\n        fun _ =>\n          (* Internal fixpoint definition, returns [Arr_one v] when size\n         is zero. *)\n          let fix create_arrm (m : nat) (v : value) {struct m} :=\n            match m return arrofvalues with\n            | 0%nat => Arr_one v\n            | S o => Arr_cons v (create_arrm o v)\n            end\n          in create_arrm m v\n    end.  \n  \nEnd Values.\n\n(** ** Semantic type *)\n\nSection Types.\n\n  (** Defines the type of types used to express the semantics of the\n      H-VHDL language.\n      \n      Note that an element of the [type] type does not carry proofs of\n      its well-definition, i.e. one can build an ill-formed natural\n      range type, for instance [Tnat 10 2]. *)\n  \n  Inductive type : Type :=\n  | Tbool                              (** Boolean type *)\n  | Tnat (l : N) (u : N)               (** Natural range from l to u *)\n  | Tarray (t : type) (l : N) (u : N). (** Array of t with index range\n                                           from l to u *)\n\n  (** Well-formed type predicate *)\n\n  Inductive WFType : type -> Prop :=\n  | WFBool : WFType Tbool\n  | WFNat : forall l u, l <= u -> u <= NATMAX -> WFType (Tnat l u)\n  | WFArr : forall t l u, l <= u -> u <= NATMAX -> WFType t -> WFType (Tarray t l u).\n\n  Fixpoint WFType_dec (t : type) : {WFType t} + {~WFType t}.\n    refine (match t with\n            | Tbool => left WFBool\n            | Tnat l u =>\n                match N_le_dec l u, (N_le_dec u NATMAX) with\n                | left lelu, left leuN => left (WFNat l u lelu leuN)\n                | _, _ => right _\n                end\n            | Tarray t__a l u =>\n                match WFType_dec t__a with\n                | left WFt__a =>\n                    match N_le_dec l u, (N_le_dec u NATMAX) with\n                    | left lelu, left leuN => left (WFArr t__a l u lelu leuN WFt__a)\n                    | _, _ => right _\n                    end\n                | _ => right _\n                end\n            end); inversion 1; contradiction.\n  Defined.\n  \n  (** Defines the typing relation [IsOfType]. *)\n\n  Inductive IsOfType : value -> type -> Prop :=\n  | IsBool : forall (b : bool), IsOfType (Vbool b) Tbool\n\n  (** Value n must satisfy the index constraint, i.e n ∈ [l,u]. *)\n  | IsNat : forall (n l u : N),\n      WFType (Tnat l u) -> l <= n <= u -> IsOfType (Vnat n) (Tnat l u)\n\n  (** All elements of the array of values [aofv] must be of type [t],\n    and the length of [aofv] must satisfy the index constraint.\n   *)\n  | IsArrOfT (l u : N) :\n    forall (aofv : arrofvalues) (t : type),\n      WFType (Tarray t l u) ->\n      ArrIsOfType aofv (S (N.to_nat (u - l))) t ->\n      IsOfType (Varr aofv) (Tarray t l u)\n               \n  (** Defines the typing relation over array of values. \n    \n    By construction, checks that the array size\n    is equal to the second argument (of type [nat]). *)\n               \n  with ArrIsOfType: arrofvalues -> nat -> type -> Prop :=\n  | ArrIsOfTypeOne : forall t v, IsOfType v t -> ArrIsOfType (Arr_one v) 1 t\n  | ArrIsOfTypeCons :\n    forall aofv size t v,\n      IsOfType v t ->\n      ArrIsOfType aofv size t ->\n      ArrIsOfType (Arr_cons v aofv) (S size) t.\n\n  Scheme IsOfType_ind_mut := Induction for IsOfType Sort Prop\n      with ArrIsOfType_ind_mut := Induction for ArrIsOfType Sort Prop.\n\n  (** Defines the typing function [is_of_type]. *)\n\n  Fixpoint is_of_type (v : value) (t : type) {struct v} : optionE bool :=\n    match v, t with\n    | Vbool b, Tbool => Ret true\n    | Vnat n, Tnat l u =>\n        if WFType_dec t then\n          match N_le_dec l n, N_le_dec n u with\n          | left _, left _ => Ret true\n          | _, _ => Ret false\n          end\n        else Err \"is_of_type: found an ill-formed nat type\"\n    | Varr aofv, Tarray ta l u =>\n        if WFType_dec t then\n          arr_is_of_type aofv ta ((u - l) + 1)\n        else Err \"is_of_type: found an ill-formed array type\"\n    | _, _ => Ret false\n    end\n  with arr_is_of_type (aofv : arrofvalues) (t : type) (size : N) {struct aofv} : optionE bool :=\n         match aofv, size with\n         | Arr_one v, 1 => is_of_type v t\n         | Arr_cons v tl, Npos n =>\n             do b1 <- is_of_type v t; do b2 <- arr_is_of_type tl t (size - 1); Ret (b1 && b2)\n         | _, _ => Ret false\n         end.\n  \nEnd Types.\n\n(** ** Equality between two values *)\n\nSection ValueEq.\n\n  (** Specifies the equality relation between two values, and the\n      result of the equality evaluation; result can either be an error\n      (i.e, [None]), or some Boolean value.\n\n      The third parameter is mandatory, otherwise, it is not possible\n      to distinguish errors from \"falsity\"; imagine a relation [VEq]\n      that takes two values as parameters:\n\n      - [~VEq (Vnat 0) (Vnat 1)] is provable because 0 ≠ 1.\n\n      - [~VEq (Vnat 0) (Vbool false)] is provable because 0 and false\n        are not comparable, however it is an error case because the\n        two values are not of the same type.  *)\n\n  Inductive OVEq : value -> value -> option bool -> Prop :=\n  | OVEq_BoolT : forall b b', b = b' -> OVEq (Vbool b) (Vbool b') (Some true)\n  | OVEq_BoolF : forall b b', b <> b' -> OVEq (Vbool b) (Vbool b') (Some false)\n  | OVEq_NatT  : forall n n', n = n' -> OVEq (Vnat n) (Vnat n') (Some true)\n  | OVEq_NatF  : forall n n', n <> n' -> OVEq (Vnat n) (Vnat n') (Some false)\n  | OVEq_ArrT : forall a a', OArrOfVEq a a' (Some true) -> OVEq (Varr a) (Varr a') (Some true)\n  | OVEq_ArrF : forall a a', OArrOfVEq a a' (Some false) -> OVEq (Varr a) (Varr a') (Some false)\n  | VEqArr_Err : forall a a', OArrOfVEq a a' None -> OVEq (Varr a) (Varr a') None\n                                                          \n  (* Error if there is no common type for value [v] and [v'], i.e, [v]\n   and [v'] are not comparable. *)\n  | OVEq_Err : forall v v', (forall t, ~IsOfType v t \\/ ~IsOfType v' t) -> OVEq v v' None\n                                                                                \n  (** Specifies the equality relation between two arrays of values. *)\n  with OArrOfVEq : arrofvalues -> arrofvalues -> option bool -> Prop :=\n  (* Convenient to detect errors due to the comparison of two\n   arrofvalues of different lengths. *)\n  | OArrOfVEq_LengthErr1 : forall v v' aofv, OArrOfVEq (Arr_one v) (Arr_cons v' aofv) None\n  | OArrOfVEq_LengthErr2 : forall v v' aofv, OArrOfVEq (Arr_cons v aofv) (Arr_one v') None\n  | OArrOfVEq_OneT : forall v v', OVEq v v' (Some true) -> OArrOfVEq (Arr_one v) (Arr_one v') (Some true)\n  | OArrOfVEq_OneF : forall v v', OVEq v v' (Some false) -> OArrOfVEq (Arr_one v) (Arr_one v') (Some false)\n  | OArrOfVEq_ConsT :\n    forall v v' aofv aofv',\n      OVEq v v' (Some true) ->\n      OArrOfVEq aofv aofv' (Some true) ->\n      OArrOfVEq (Arr_cons v aofv) (Arr_cons v' aofv') (Some true)\n  | OArrOfVEq_ConsF :\n    forall v v' aofv aofv',\n      OVEq v v' (Some false) ->\n      OArrOfVEq aofv aofv' (Some false) ->\n      OArrOfVEq (Arr_cons v aofv) (Arr_cons v' aofv') (Some false)\n                \n  | OArrOfVEqCons_Err :\n    forall v v' aofv aofv' optb,\n      OVEq v v' None ->\n      OArrOfVEq aofv aofv' optb ->\n      OArrOfVEq (Arr_cons v aofv) (Arr_cons v' aofv') None.\n\n  Hint Constructors OVEq : hvhdl.\n  Hint Constructors OArrOfVEq : hvhdl.\n\n  Scheme OVEq_ind_mut := Induction for OVEq Sort Prop\n      with OArrOfVEq_ind_mut := Induction for OArrOfVEq Sort Prop.\n\n  (** Wrapper around the [OVEq] relation *)\n\n  Definition VEq x y := OVEq x y (Some true).\n  Definition VNEq x y := OVEq x y (Some false).\n\n  Definition VEq_refl : forall x, VEq x x.\n  Proof. unfold VEq.\n         apply (value_ind_mut\n                  (fun x => OVEq x x (Some true))\n                  (fun x => OArrOfVEq x x (Some true)));\n           intros; auto with hvhdl.\n  Qed.\n\n  Definition VEq_sym : forall x y, VEq x y -> VEq y x.\n  Proof. unfold VEq; intros.       \n         apply (OVEq_ind_mut\n                  (fun x y o _ => OVEq y x o)\n                  (fun x y o _ => OArrOfVEq y x o));\n           auto with hvhdl.\n         intros; apply OVEq_Err; firstorder.\n         intros; eapply OArrOfVEqCons_Err; eauto.\n  Defined.\n\n  Definition VEq_trans1 :\n    forall y x z, VEq x y -> VEq y z -> VEq x z.\n  Proof.\n    unfold VEq.\n    apply (value_ind_mut\n             (fun y => forall x z, OVEq x y (Some true) -> OVEq y z (Some true) -> OVEq x z (Some true))\n             (fun y => forall x z, OArrOfVEq x y (Some true) -> OArrOfVEq y z (Some true) -> OArrOfVEq x z (Some true))).\n    - (* y = Vbool b *)\n      inversion_clear 1; subst; inversion_clear 1; subst.\n      constructor; reflexivity.\n    - (* y = Vnat n *)\n      inversion_clear 1; subst; inversion_clear 1; subst.\n      constructor; reflexivity.\n    - (* y = Varr a *)\n      intros a IH.\n      inversion_clear 1; subst; inversion_clear 1; subst.\n      constructor; eapply IH; eauto.\n    - (* Mutual ind. a = Arr_one *)\n      intros v IH.\n      inversion_clear 1; subst; inversion_clear 1; subst.\n      constructor; eapply IH; eauto.\n    - (* Mutual ind. a = Arr_cons *)\n      intros v IHv a IHa.\n      inversion_clear 1; subst; inversion_clear 1; subst.\n      constructor; [ eapply IHv; eauto | eapply IHa; eauto ].\n  Defined.\n\n  Definition VEq_trans :\n    forall x y z, VEq x y -> VEq y z -> VEq x z.\n  Proof. intros x y; generalize x; eapply VEq_trans1. Defined.\n  \n  Add Parametric Relation : (value) (VEq)\n      reflexivity proved by VEq_refl\n      symmetry proved by VEq_sym\n      transitivity proved by VEq_trans\n      as VEq_rel.\n\n  (** Implements the equality operator between two values.\n    \n      Returns a [bool] corresponding to the result of the comparison\n      of the two values.\n\n      Returns an error if the two values do not belong to the same\n      domain of values.\n\n   *)\n\n  Fixpoint veq (v v' : value) {struct v} : optionE bool :=\n    match v, v' with\n    | Vbool b, Vbool b' => Ret (Bool.eqb b b')\n    | Vnat n, Vnat n' => Ret (N.eqb n n')\n    | Varr aofv, Varr aofv' => arrofveq aofv aofv'\n    | _, _ => Err \"veq: can not compare two values of different domains\"\n    end                              \n  (** Implements the equality operator between array of values.\n      \n      Returns [Some true] if values of [aofv] and [aofv'] are equal pair-wise.\n      \n      Returns an error if a pair-wise comparison returns an error or if\n      the arrays are of different length. *)\n      \n  with arrofveq (aofv aofv' : arrofvalues) {struct aofv} : optionE bool :=\n         match aofv, aofv' with\n         (* Two empty lists are v-equal. *)\n         | Arr_one v, Arr_one v' => veq v v'\n                                        \n         (* Checks that a and b are v-equal. *)\n         | (Arr_cons v a), (Arr_cons v' a') =>\n             do b <- veq v v'; if b then arrofveq a a' else Ret false\n         | _, _ => Err \"arrofveq: can not compare to array of values of different size\"\n         end.\n  \nEnd ValueEq.\n\n#[export] Hint Constructors OVEq : hvhdl.\n#[export] Hint Constructors OArrOfVEq : hvhdl.\n\n(** ** Index Iterator for [arrofvalues] *)\n\nSection ArrOfV_Iterator.\n\n  (** An array is a least of length [1]; it has at least one\n      element. *)\n  \n  Lemma length_aofv_gt_O : forall aofv : arrofvalues, (0 < List.length aofv)%nat.\n    destruct aofv; cbn; eapply Nat.lt_0_succ; eauto.\n  Defined.\n\n  (** Generates a contiguous sequence of natural numbers corresponding\n      the available indexes of the [aofv] arrofvalues; i.e, the\n      sequence ranges from [0] to [length aofv - 1], and for each\n      index [i] there is a proof that [i < length aofv]. *)\n  \n  Definition arrofv_idxs (aofv : arrofvalues) : list { i | (i < List.length aofv)%nat } :=\n    seqd 0 (List.length aofv) (length_aofv_gt_O aofv).\n\n  (** [BProd_ArrOfV aofv bprod ≡ ∏i=0 to (length aofv -1), aofv[i]\n      ].  If [ aofv[i] ] is not a boolean value, then [true] is passed\n      to the product. *)\n\n  Definition get_bool_at (aofv : arrofvalues) (i : nat) : bool :=\n    match oget_at i aofv with\n    | Some (Vbool b) => b\n    | _ => true\n    end.\n  \n  Definition BProd_ArrOfV (aofv : arrofvalues) (bprod : bool) :=\n    let f_bprod :=\n      fun i =>\n        match oget_at i aofv with\n        | Some (Vbool b) => b\n        | _ => true\n        end\n    in\n    BProd f_bprod (seq 0 (List.length aofv)) bprod.\n\n  (** Dependently-typed version of [BProd_ArrOfV] where there is a\n      proof that each index [i] in the generated sequence verifies [i\n      < length aofv]. Therefore, we are able to use the error-free\n      [get_at] function to access element of [aofv] through their\n      index. *)\n  \n  Definition DepBProd_ArrOfV (aofv : arrofvalues) (bprod : bool) :=\n    let f_bprod :=\n      fun (i : { n | (n < 0 + List.length aofv)%nat }) =>\n        match get_at (proj1_sig i) aofv (proj2_sig i) with\n        | Vbool b => b\n        | _ => true\n        end\n    in\n    BProd f_bprod (arrofv_idxs aofv) bprod.\n  \nEnd ArrOfV_Iterator.\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/SemanticalDomains.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.29048528978469085}}
{"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.\nRequire Import Ndec.\nRequire Import ZArith.\nRequire Import Classical_Prop.\nFrom IntMap Require Import Allmaps.\nRequire Import lattice_fixpoint.\nRequire Import bases.\nRequire Import defs.\nRequire Import semantics.\nRequire Import pl_path.\n\n(* définition de la fonction dont on va calculer le point fixe *)\n\nFixpoint pl_non_empty (m : Map bool) (p : prec_list) {struct p} : bool :=\n  match p with\n  | prec_empty => true\n  | prec_cons a la ls =>\n      match ls with\n      | prec_empty =>\n          match MapGet bool m a with\n          | Some b => b && pl_non_empty m la\n          | None => false\n          end\n      | prec_cons _ _ _ =>\n          match MapGet bool m a with\n          | Some b => pl_non_empty m ls || b && pl_non_empty m la\n          | None => pl_non_empty m ls\n          end\n      end\n  end.\n\nFixpoint st_non_empty (m : Map bool) (s : state) {struct s} : bool :=\n  match s with\n  | M0 => false\n  | M1 _ p => pl_non_empty m p\n  | M2 a b => st_non_empty m a || st_non_empty m b\n  end.\n\nFixpoint dta_app_ne_aux (d : preDTA) (m r : Map bool) {struct r} :\n Map bool :=\n  match d, r with\n  | M0, _ => M0 bool\n  | M1 a s, M0 => M0 bool\n  | M1 a s, M1 a' b =>\n      if Neqb a a' then M1 bool a (b || st_non_empty m s) else M0 bool\n  | M1 a s, M2 _ _ => M0 bool\n  | M2 d0 d1, M0 => M0 bool\n  | M2 d0 d1, M1 _ _ => M0 bool\n  | M2 d0 d1, M2 r0 r1 =>\n      M2 bool (dta_app_ne_aux d0 m r0) (dta_app_ne_aux d1 m r1)\n  end.\n\nDefinition dta_app_ne (d : preDTA) (m : Map bool) : \n  Map bool := dta_app_ne_aux d m m.\n\nDefinition dta_non_empty_states (d : preDTA) : Map bool :=\n  power (Map bool) (dta_app_ne d) (map_mini state d) (S (MapCard state d)).\n\nDefinition dta_states_non_empty (d : DTA) : Map bool :=\n  match d with\n  | dta p a => dta_non_empty_states p\n  end.\n\nDefinition dta_non_empty_states_lazy (d : preDTA) : \n  Map bool :=\n  lazy_power bool eqm_bool (dta_app_ne d) (map_mini state d)\n    (S (MapCard state d)).\n\nDefinition dta_states_non_empty_lazy (d : DTA) : Map bool :=\n  match d with\n  | dta p a => dta_non_empty_states_lazy p\n  end.\n\nLemma dta_states_non_empty_lazy_eg_dta_states_non_empty :\n forall d : DTA, dta_states_non_empty_lazy d = dta_states_non_empty d.\nProof.\n\tsimple induction d. simpl in |- *. intros. unfold dta_non_empty_states_lazy, dta_non_empty_states in |- *. apply\n  (lazy_power_eg_power bool eqm_bool (dta_app_ne p) \n     (map_mini state p) (S (MapCard state p))).\n\tsplit. exact (eqm_bool_equal a0 b). intros. rewrite H.\n\texact (equal_eqm_bool b).\nQed.\n\n(* définition ok de dta_app_ne *)\n\nLemma dta_app_ne_aux_def_ok :\n forall (d : preDTA) (m : Map bool),\n def_ok_app bool (ensemble_base state d) (dta_app_ne_aux d m).\nProof.\n\tsimple induction d. intros. unfold def_ok_app in |- *. intros. induction  x as [| a a0| x1 Hrecx1 x0 Hrecx0].\n\tsimpl in |- *. unfold ensemble_base in |- *. exact I. unfold ensemble_base in |- *. simpl in |- *.\n\texact I. simpl in |- *. unfold ensemble_base in |- *. simpl in |- *. exact I. intros.\n\tunfold def_ok_app in |- *. intros. unfold ensemble_base in |- *. unfold ensemble_base in H. induction  x as [| a1 a2| x1 Hrecx1 x0 Hrecx0]. simpl in H. inversion H. simpl in H. simpl in |- *. rewrite H.\n\trewrite (Neqb_correct a1). simpl in |- *. reflexivity. simpl in H. inversion H.\n\tintros. unfold def_ok_app in |- *. unfold ensemble_base in |- *. intros. induction  x as [| a a0| x1 Hrecx1 x0 Hrecx0].\n\tsimpl in H1. inversion H1. simpl in H1. inversion H1. simpl in |- *. split.\n\tunfold def_ok_app in H. unfold ensemble_base in H. simpl in H1.\n\telim H1. intros. exact (H m1 x1 H2). unfold def_ok_app in H0.\n\tunfold ensemble_base in H0. elim H1. intros. exact (H0 m1 x0 H3).\nQed.\n\nLemma dta_app_ne_def_ok :\n forall d : preDTA, def_ok_app bool (ensemble_base state d) (dta_app_ne d).\nProof.\n\tintros. unfold dta_app_ne in |- *. unfold def_ok_app in |- *. intros. exact (dta_app_ne_aux_def_ok d x x H).\nQed.\n\n(* croissance de dta_app_ne *)\n\nLemma dta_app_ne_inc_0 :\n forall (p : prec_list) (m0 m1 : Map bool),\n lem m0 m1 -> leb (pl_non_empty m0 p) (pl_non_empty m1 p).\nProof.\n\tsimple induction p. intros. induction  p1 as [a0 p1_1 Hrecp1_1 p1_0 Hrecp1_0| ]. elim (option_sum bool (MapGet bool m0 a)); intro y. elim y. intros x y0. elim (option_sum bool (MapGet bool m1 a)); intro y1. elim y1. intros x0 y2. replace (pl_non_empty m0 (prec_cons a p0 (prec_cons a0 p1_1 p1_0))) with\n  (pl_non_empty m0 (prec_cons a0 p1_1 p1_0) || x && pl_non_empty m0 p0). replace (pl_non_empty m1 (prec_cons a p0 (prec_cons a0 p1_1 p1_0))) with\n  (pl_non_empty m1 (prec_cons a0 p1_1 p1_0) || x0 && pl_non_empty m1 p0). apply\n  (leb_transitive\n     (pl_non_empty m0 (prec_cons a0 p1_1 p1_0) || x && pl_non_empty m0 p0)\n     (pl_non_empty m0 (prec_cons a0 p1_1 p1_0) || x0 && pl_non_empty m1 p0)\n     (pl_non_empty m1 (prec_cons a0 p1_1 p1_0) || x0 && pl_non_empty m1 p0)).\n\tapply\n  (orb_incr (pl_non_empty m0 (prec_cons a0 p1_1 p1_0))\n     (pl_non_empty m0 (prec_cons a0 p1_1 p1_0)) (x && pl_non_empty m0 p0)\n     (x0 && pl_non_empty m1 p0)). exact (leb_reflexive _).\n\tapply (andb_incr x x0 (pl_non_empty m0 p0) (pl_non_empty m1 p0)).\n\texact (lem_get_leb m0 m1 a x x0 H1 y0 y2). exact (H _ _ H1).\n\tapply\n  (orb_incr (pl_non_empty m0 (prec_cons a0 p1_1 p1_0))\n     (pl_non_empty m1 (prec_cons a0 p1_1 p1_0)) (x0 && pl_non_empty m1 p0)\n     (x0 && pl_non_empty m1 p0)). exact (H0 _ _ H1). exact (leb_reflexive _). simpl in |- *. rewrite y2. reflexivity. simpl in |- *. rewrite y0.\n\treflexivity. elim (domain_equal_mapget bool bool m0 m1 a x). intros.\n\trewrite H2 in y1. inversion y1. exact (lem_domain_equal m0 m1 H1).\n\texact y0. elim (option_sum bool (MapGet bool m1 a)); intro y0. elim y0; intros x y1. elim (domain_equal_mapget bool bool m1 m0 a x); intros. rewrite H2 in y. inversion y. exact (domain_equal_symmetric bool bool _ _ (lem_domain_equal _ _ H1)). exact y1. replace (pl_non_empty m0 (prec_cons a p0 (prec_cons a0 p1_1 p1_0))) with\n  (pl_non_empty m0 (prec_cons a0 p1_1 p1_0)). replace (pl_non_empty m1 (prec_cons a p0 (prec_cons a0 p1_1 p1_0))) with\n  (pl_non_empty m1 (prec_cons a0 p1_1 p1_0)).\n\texact (H0 _ _ H1). simpl in |- *. rewrite y0. reflexivity. simpl in |- *. rewrite y.\n\treflexivity. elim (option_sum bool (MapGet bool m0 a)); intro y.\n\telim (option_sum bool (MapGet bool m1 a)); intro y0. elim y; intros x y1.\n\telim y0; intros x0 y2. replace (pl_non_empty m0 (prec_cons a p0 prec_empty)) with\n  (x && pl_non_empty m0 p0). replace (pl_non_empty m1 (prec_cons a p0 prec_empty)) with\n  (x0 && pl_non_empty m1 p0). apply\n  (leb_transitive (x && pl_non_empty m0 p0) (x0 && pl_non_empty m0 p0)\n     (x0 && pl_non_empty m1 p0)). apply (andb_inc_l (pl_non_empty m0 p0) x x0). exact (lem_get_leb _ _ _ _ _ H1 y1 y2). apply (andb_inc_r x0 (pl_non_empty m0 p0) (pl_non_empty m1 p0)). exact (H _ _ H1). simpl in |- *.\n\trewrite y2. reflexivity. simpl in |- *. rewrite y1. reflexivity. elim y. intros x y1.\n\telim (domain_equal_mapget bool bool m0 m1 a x). intros. rewrite H2 in y0.\n\tinversion y0. exact (lem_domain_equal _ _ H1). exact y1. elim (option_sum bool (MapGet bool m1 a)); intro y0. elim y0. intros x y1. elim (domain_equal_mapget bool bool m1 m0 a x). intros. rewrite H2 in y. inversion y.\n\texact (domain_equal_symmetric bool bool _ _ (lem_domain_equal _ _ H1)).\n\texact y1. simpl in |- *. rewrite y. rewrite y0. exact I. simpl in |- *. intros. exact I.\nQed.\n\nLemma dta_app_ne_inc_1 :\n forall (s : state) (m0 m1 : Map bool),\n lem m0 m1 -> leb (st_non_empty m0 s) (st_non_empty m1 s).\nProof.\n\tsimple induction s. intros. simpl in |- *. exact I. intros. simpl in |- *.\n\texact (dta_app_ne_inc_0 a0 m0 m1 H). intros. simpl in |- *.\n\texact (orb_incr _ _ _ _ (H _ _ H1) (H0 _ _ H1)).\nQed.\n\nLemma dta_app_ne_inc_2 :\n forall (d : preDTA) (m0 m1 m : Map bool),\n lem m0 m1 -> lem (dta_app_ne_aux d m0 m) (dta_app_ne_aux d m1 m).\nProof.\n\tsimple induction d. simple induction m. intros. simpl in |- *. exact I. intros.\n\tsimpl in |- *. exact I. intros. simpl in |- *. exact I. simple induction m. intros.\n\tsimpl in |- *. exact I. simpl in |- *. intros. elim (bool_is_true_or_false (Neqb a a1)); intros; rewrite H0. simpl in |- *. rewrite (Neqb_correct a). exact (orb_inc_r _ _ _ (dta_app_ne_inc_1 a0 m0 m1 H)).\n\texact I. intros. simpl in |- *. exact I. simple induction m3. intros. simpl in |- *.\n\texact I. intros. simpl in |- *. exact I. intros. simpl in |- *. split.\n\texact (H _ _ _ H3). exact (H0 _ _ _ H3).\nQed.\n\nLemma dta_app_ne_inc_3 :\n forall (m0 m1 m : Map bool) (d : preDTA),\n lem m0 m1 -> lem (dta_app_ne_aux d m m0) (dta_app_ne_aux d m m1).\nProof.\n\tsimple induction m0. simple induction m1; intros. induction  d as [| a a0| d1 Hrecd1 d0 Hrecd0]; simpl in |- *; exact I.\n\tinversion H. inversion H1. simple induction m1; intros. inversion H.\n\tinduction  d as [| a3 a4| d1 Hrecd1 d0 Hrecd0]; simpl in |- *. exact I. simpl in H. elim (bool_is_true_or_false (Neqb a a1)); intro; rewrite H0 in H. rewrite (Neqb_complete _ _ H0).\n\telim (bool_is_true_or_false (Neqb a3 a1)); intro; rewrite H1. simpl in |- *.\n\trewrite (Neqb_correct a3). exact (orb_inc_l _ _ _ H). exact I. elim H.\n\texact I. inversion H1. simple induction m2; intros. inversion H1. inversion H1.\n\telim H3; intros. induction  d as [| a a0| d1 Hrecd1 d0 Hrecd0]; simpl in |- *. exact I. exact I. split. exact (H _ _ _ H4). exact (H0 _ _ _ H5).\nQed.\n\nLemma dta_app_ne_inc :\n forall d : preDTA, increasing_app bool lem (dta_app_ne d).\nProof.\n\tintros. unfold increasing_app in |- *. unfold dta_app_ne in |- *. intros.\n\texact\n  (lem_transitive _ _ _ (dta_app_ne_inc_2 d x y x H)\n     (dta_app_ne_inc_3 x y y d H)).\nQed.\n\nInductive pl_path_true : pl_path -> Map bool -> Prop :=\n  | plp_true_nil : forall m : Map bool, pl_path_true pl_path_nil m\n  | plp_true_cons :\n      forall (m : Map bool) (a : ad) (pl : pl_path),\n      pl_path_true pl m ->\n      MapGet bool m a = Some true -> pl_path_true (pl_path_cons a pl) m.\n\nDefinition pl_non_empty_path_true_def_0 (pl : pl_path) \n  (p : prec_list) : Prop :=\n  forall m : Map bool,\n  pl_path_incl pl p -> pl_path_true pl m -> pl_non_empty m p = true.\n\nLemma pl_non_empty_path_true_0 :\n pl_non_empty_path_true_def_0 pl_path_nil prec_empty.\nProof.\n\tunfold pl_non_empty_path_true_def_0 in |- *. simpl in |- *. intros.\n\treflexivity.\nQed.\n\nLemma pl_non_empty_path_true_1 :\n forall (plp : pl_path) (a : ad) (la ls : prec_list),\n pl_path_incl plp la ->\n pl_non_empty_path_true_def_0 plp la ->\n pl_non_empty_path_true_def_0 (pl_path_cons a plp) (prec_cons a la ls).\nProof.\n\tunfold pl_non_empty_path_true_def_0 in |- *. intros. inversion H2.\n\tsimpl in |- *. rewrite H7. elim (pl_sum ls); intros. rewrite H8.\n\texact (H0 m H H5). elim H8. intros. elim H9. intros. elim H10.\n\tintros. rewrite H11. rewrite (H0 m H H5). elim (bool_is_true_or_false (pl_non_empty m (prec_cons x x0 x1))); intro;\n  rewrite H12; reflexivity.\nQed.\n\nLemma pl_non_empty_path_true_2 :\n forall (plp : pl_path) (a : ad) (la ls : prec_list),\n pl_path_incl plp ls ->\n pl_non_empty_path_true_def_0 plp ls ->\n plp <> pl_path_nil -> pl_non_empty_path_true_def_0 plp (prec_cons a la ls).\nProof.\n\tunfold pl_non_empty_path_true_def_0 in |- *. intros. induction  plp as [| a0 plp Hrecplp].\n\telim (H1 (refl_equal _)). inversion H3. simpl in |- *. elim (pl_sum ls); intros. rewrite H9 in H. inversion H. elim H9.\n\tintros. elim H10. intros. elim H11. intros. rewrite H12.\n\trewrite <- H12. rewrite (H0 m H H3). elim (option_sum bool (MapGet bool m a)); intro y. elim y. intros x2 y0. rewrite y0.\n\telim (bool_is_true_or_false (x2 && pl_non_empty m la)); intro; rewrite H13;\n  reflexivity. rewrite y. reflexivity.\nQed.\n\nLemma pl_non_empty_path_true :\n forall (pl : pl_path) (p : prec_list) (m : Map bool),\n pl_path_incl pl p -> pl_path_true pl m -> pl_non_empty m p = true.\nProof.\n\tintros. exact\n  (pl_path_incl_ind pl_non_empty_path_true_def_0 pl_non_empty_path_true_0\n     pl_non_empty_path_true_1 pl_non_empty_path_true_2 pl p H m H H0).\nQed.\n\nLemma pl_non_empty_path_true_rev :\n forall (p : prec_list) (m : Map bool),\n pl_non_empty m p = true ->\n exists plp : pl_path, pl_path_incl plp p /\\ pl_path_true plp m.\nProof.\n\tsimple induction p. intros. simpl in H1. elim (pl_sum p1); intros.\n\trewrite H2 in H1. elim (option_sum bool (MapGet bool m a)); intro y. elim y. intros x y0. rewrite y0 in H1. elim (bool_is_true_or_false x); intro; rewrite H3 in H1. elim (bool_is_true_or_false (pl_non_empty m p0)); intros. elim (H m H4). intros. elim H5. intros. split with (pl_path_cons a x0). split. exact (pl_path_incl_cons x0 a p0 p1 H6).\n\trewrite H3 in y0. exact (plp_true_cons m a x0 H7 y0).\n\trewrite H4 in H1. inversion H1. elim (bool_is_true_or_false (pl_non_empty m p0)); intro; rewrite H4 in H1;\n  inversion H1.\n\trewrite y in H1. inversion H1. elim H2. intros. elim H3. intros.\n\telim H4. intros. rewrite H5 in H1. rewrite <- H5 in H1. elim (option_sum bool (MapGet bool m a)); intro y. elim y. intros x2 y0.\n\trewrite y0 in H1. elim (bool_is_true_or_false (pl_non_empty m p1)); intros. elim (H0 m H6); intros. split with x3. split.\n\telim H7. intros. apply (pl_path_incl_next x3 a p0 p1 H8). intro.\n\trewrite H10 in H8. rewrite H5 in H8. inversion H8. exact (H16 (refl_equal _)). elim H7; intros. assumption.\n\trewrite H6 in H1. elim (bool_is_true_or_false (x2 && pl_non_empty m p0)); intros;\n  rewrite H7 in H1. elim (bool_is_true_or_false x2); intros; rewrite H8 in H7. rewrite H8 in y0. elim (bool_is_true_or_false (pl_non_empty m p0)); intros.\n\telim (H m H9); intros. split with (pl_path_cons a x3). split.\n\telim H10. intros. exact (pl_path_incl_cons x3 a p0 p1 H11).\n\telim H10. intros. exact (plp_true_cons m a x3 H12 y0). rewrite H9 in H7. inversion H7. elim (bool_is_true_or_false (pl_non_empty m p0)); intros; rewrite H9 in H7;\n  inversion H7. inversion H1.\n\trewrite y in H1. elim (H0 _ H1). intros. split with x2. split.\n\tapply (pl_path_incl_next x2 a p0 p1). elim H6. intros. assumption.\n\tintro. rewrite H7 in H6. elim H6. intros. inversion H8. rewrite <- H11 in H5. inversion H5. exact (H11 (refl_equal _)).\n\telim H6; intros. assumption. intros. split with pl_path_nil.\n\tsplit. exact pl_path_incl_nil. exact (plp_true_nil m).\nQed.\n\nLemma st_non_empty_0 :\n forall (m : Map bool) (s : state) (p : prec_list) (a : ad),\n MapGet prec_list s a = Some p ->\n pl_non_empty m p = true -> st_non_empty m s = true.\nProof.\n\tsimple induction s; intros. inversion H. simpl in |- *. simpl in H. elim (bool_is_true_or_false (Neqb a a1)); intro; rewrite H1 in H;\n  inversion H. exact H0. simpl in |- *. induction  a as [| p0]. simpl in H1. rewrite (H p N0 H1 H2). simpl in |- *. reflexivity. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]; simpl in H1.\n\trewrite (H0 _ _ H1 H2). elim (bool_is_true_or_false (st_non_empty m m0)); intro; rewrite H3;\n  reflexivity. rewrite (H _ _ H1 H2).\n\treflexivity. rewrite (H0 _ _ H1 H2). elim (bool_is_true_or_false (st_non_empty m m0)); intro; rewrite H3;\n  reflexivity.\nQed.\n\nLemma st_non_empty_1 :\n forall (d : preDTA) (m r : Map bool) (a : ad) (l : state),\n MapGet state d a = Some l ->\n domain_equal state bool d r ->\n st_non_empty m l = true ->\n MapGet bool (dta_app_ne_aux d m r) a = Some true.\nProof.\n\tsimple induction d. intros. inversion H. intros. induction  r as [| a2 a3| r1 Hrecr1 r0 Hrecr0]. \n\tinversion H0. simpl in |- *. simpl in H0. simpl in H. rewrite H0.\n\trewrite (Neqb_correct a2). simpl in |- *. rewrite H0 in H. elim (bool_is_true_or_false (Neqb a2 a1)); intro; rewrite H2 in H.\n\tinversion H. rewrite H2. rewrite H1. elim (bool_is_true_or_false a3); intros; rewrite H3; reflexivity. inversion H. inversion H0.\n\tintros. induction  r as [| a0 a1| r1 Hrecr1 r0 Hrecr0]. inversion H2. inversion H2. elim H2; intros.\n\tinduction  a as [| p]. simpl in |- *. simpl in H1. apply (H m1 r1 N0 l H1 H4).\n\texact H3. induction  p as [p Hrecp| p Hrecp| ]; simpl in |- *; simpl in H1. elim H2. intros.\n\texact (H0 _ _ _ _ H1 H7 H3). exact (H _ _ _ _ H1 H4 H3).\n\texact (H0 _ _ _ _ H1 H5 H3).\nQed.\n\n(* terme t reconnu en l'etat s : f^(high t)=true *)\n\nDefinition dt_non_empty_def_0 (d : preDTA) (a : ad) \n  (t : term) (pr : reconnaissance d a t) :=\n  forall n : nat,\n  term_high t <= n ->\n  MapGet bool (power (Map bool) (dta_app_ne d) (map_mini state d) n) a =\n  Some true.\n\nDefinition dt_non_empty_def_1 (d : preDTA) (s : state) \n  (t : term) (pr : state_reconnait d s t) :=\n  forall n : nat,\n  term_high t <= S n ->\n  st_non_empty (power (Map bool) (dta_app_ne d) (map_mini state d) n) s =\n  true.\n\nDefinition dt_non_empty_def_2 (d : preDTA) (p : prec_list) \n  (t : term_list) (pr : liste_reconnait d p t) :=\n  forall n : nat,\n  term_high_0 t <= n ->\n  pl_non_empty (power (Map bool) (dta_app_ne d) (map_mini state d) n) p =\n  true.\n\nLemma dt_non_empty_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 dt_non_empty_def_1 d ladj t s ->\n dt_non_empty_def_0 d a t (rec_dta d a t ladj e s).\nProof.\n\tunfold dt_non_empty_def_1, dt_non_empty_def_0 in |- *. intros. elim (nat_sum n); intros. rewrite H1 in H0. induction  t as (a0, t). simpl in H0.\n\telim (le_Sn_O _ H0). elim H1. intros. rewrite H2. simpl in |- *. rewrite H2 in H0. replace\n  (dta_app_ne d (power (Map bool) (dta_app_ne d) (map_mini state d) x)) with\n  (dta_app_ne_aux d (power (Map bool) (dta_app_ne d) (map_mini state d) x)\n     (power (Map bool) (dta_app_ne d) (map_mini state d) x)). apply\n  (st_non_empty_1 d (power (Map bool) (dta_app_ne d) (map_mini state d) x)\n     (power (Map bool) (dta_app_ne d) (map_mini state d) x) a ladj e). exact\n  (power_def_ok bool (ensemble_base state d) (dta_app_ne d)\n     (map_mini state d) x (dta_app_ne_def_ok d) (map_mini_appartient state d)). exact (H x H0). reflexivity.\nQed.\n\nLemma dt_non_empty_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 dt_non_empty_def_2 d l tl l0 ->\n dt_non_empty_def_1 d s (app c tl) (rec_st d s c tl l e l0).\nProof.\n\tunfold dt_non_empty_def_1 in |- *. unfold dt_non_empty_def_2 in |- *. intros.\n\tsimpl in H0. fold term_high_0 in H0. apply\n  (st_non_empty_0 (power (Map bool) (dta_app_ne d) (map_mini state d) n) s l\n     c e).\n\texact (H n (le_S_n _ _ H0)).\nQed.\n\nLemma dt_non_empty_2 :\n forall d : preDTA, dt_non_empty_def_2 d prec_empty tnil (rec_empty d).\nProof.\n\tunfold dt_non_empty_def_2 in |- *. intros. simpl in |- *. reflexivity.\nQed.\n\nLemma dt_non_empty_3 :\n forall (d : preDTA) (a : ad) (la ls : prec_list) (hd : term)\n   (tl : term_list) (r : reconnaissance d a hd),\n dt_non_empty_def_0 d a hd r ->\n forall l : liste_reconnait d la tl,\n dt_non_empty_def_2 d la tl l ->\n dt_non_empty_def_2 d (prec_cons a la ls) (tcons hd tl)\n   (rec_consi d a la ls hd tl r l).\nProof.\n\tunfold dt_non_empty_def_0, dt_non_empty_def_2 in |- *. intros. simpl in H1.\n\tfold term_high in H1. elim\n  (pl_non_empty_path_true_rev la\n     (power (Map bool) (dta_app_ne d) (map_mini state d) n)\n     (H0 n (le_trans (term_high_0 tl) _ _ (le_max_r _ _) H1))). intros. elim H2. intros.\n\tapply\n  (pl_non_empty_path_true (pl_path_cons a x) (prec_cons a la ls)\n     (power (Map bool) (dta_app_ne d) (map_mini state d) n)). exact (pl_path_incl_cons x a la ls H3). apply\n  (plp_true_cons (power (Map bool) (dta_app_ne d) (map_mini state d) n) a x). exact H4. exact (H _ (le_trans _ _ _ (le_max_l _ _) H1)).\nQed.\n\nLemma dt_non_empty_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 dt_non_empty_def_2 d ls (tcons hd tl) l ->\n dt_non_empty_def_2 d (prec_cons a la ls) (tcons hd tl)\n   (rec_consn d a la ls hd tl l).\nProof.\n\tunfold dt_non_empty_def_2 in |- *. intros. elim (pl_non_empty_path_true_rev _ _ (H n H0)). intros. elim H1. intros. apply\n  (pl_non_empty_path_true x (prec_cons a la ls)\n     (power (Map bool) (dta_app_ne d) (map_mini state d) n)). apply (pl_path_incl_next x a la ls H2). intro. rewrite H4 in H3.\n\trewrite H4 in H2. inversion H2. rewrite <- H6 in l. inversion l.\n\telim (H6 (refl_equal _)). exact H3.\nQed.\n\nLemma dt_non_empty_5 :\n forall (d : preDTA) (a : ad) (t : term),\n reconnaissance d a t ->\n forall n : nat,\n term_high t <= n ->\n MapGet bool (power (Map bool) (dta_app_ne d) (map_mini state d) n) a =\n Some true.\nProof.\n\texact\n  (mreconnaissance_ind dt_non_empty_def_0 dt_non_empty_def_1\n     dt_non_empty_def_2 dt_non_empty_0 dt_non_empty_1 dt_non_empty_2\n     dt_non_empty_3 dt_non_empty_4).\nQed.\n\nLemma dt_non_empty_6 :\n forall (p : preDTA) (p0 : prec_list) (t : term_list)\n   (l : liste_reconnait p p0 t), dt_non_empty_def_2 p p0 t l.\nProof.\n\texact\n  (mlrec_ind dt_non_empty_def_0 dt_non_empty_def_1 dt_non_empty_def_2\n     dt_non_empty_0 dt_non_empty_1 dt_non_empty_2 dt_non_empty_3\n     dt_non_empty_4).\nQed.\n\nLemma dt_non_empty_d :\n forall (d : preDTA) (a : ad) (t : term),\n reconnaissance d a t ->\n exists n : nat,\n   MapGet bool (power (Map bool) (dta_app_ne d) (map_mini state d) n) a =\n   Some true.\nProof.\n\tintros. split with (term_high t). exact (dt_non_empty_5 d a t H (term_high t) (le_n_n _)).\nQed.\n\nLemma dt_non_empty_7 :\n forall (d : preDTA) (p : prec_list) (t : term_list),\n liste_reconnait d p t ->\n pl_non_empty\n   (power (Map bool) (dta_app_ne d) (map_mini state d) (term_high_0 t)) p =\n true.\nProof.\n\tintros. exact (dt_non_empty_6 d p t H (term_high_0 t) (le_n_n _)).\nQed.\n\n(* f^(high t)=true : terme t reconnu en l'etat s *)\n\nLemma dt_non_empty_r_0 :\n forall (d : preDTA) (m r : Map bool) (a : ad) (l : state),\n MapGet state d a = Some l ->\n domain_equal state bool d r ->\n MapGet bool (dta_app_ne_aux d m r) a = Some true ->\n MapGet bool r a = Some true \\/ st_non_empty m l = true.\nProof.\n\tsimple induction d. intros. inversion H. intros. induction  r as [| a2 a3| r1 Hrecr1 r0 Hrecr0].\n\tinversion H0. simpl in H0. rewrite H0 in H. rewrite H0 in H1.\n\tsimpl in H. elim (bool_is_true_or_false (Neqb a2 a1)); intro; rewrite H2 in H. inversion H. simpl in H1. rewrite (Neqb_correct a2) in H1. simpl in H1. rewrite H2 in H1. inversion H1. rewrite H5.\n\tsimpl in |- *. rewrite H2. elim (bool_is_true_or_false a3); intros; rewrite H3. left. reflexivity. rewrite H3 in H5. simpl in H5.\n\trewrite H4 in H5. right. exact H5. inversion H. inversion H0.\n\tintros. induction  r as [| a0 a1| r1 Hrecr1 r0 Hrecr0]. inversion H2. inversion H2. induction  a as [| p].\n\tsimpl in H1. simpl in |- *. simpl in H3. simpl in H2. elim H2. intros.\n\texact (H _ _ _ _ H1 H4 H3). elim H2. intros. induction  p as [p Hrecp| p Hrecp| ]; simpl in |- *; simpl in H1;\n  simpl in H3. exact (H0 _ _ _ _ H1 H5 H3). exact (H _ _ _ _ H1 H4 H3). exact (H0 _ _ _ _ H1 H5 H3).\nQed.\n\nLemma dt_non_empty_r_1 :\n forall (s : state) (m : Map bool),\n st_non_empty m s = true ->\n exists c : ad,\n   (exists p : prec_list,\n      MapGet prec_list s c = Some p /\\ pl_non_empty m p = true).\nProof.\n\tsimple induction s; intros. simpl in H. inversion H. simpl in H.\n\tsplit with a. split with a0. split. simpl in |- *. rewrite (Neqb_correct a). reflexivity. exact H. simpl in H1.\n\telim (bool_is_true_or_false (st_non_empty m1 m)); intros.\n\telim (H m1 H2). intros. elim H3. intros. elim H4. intros.\n\tinduction  x as [| p]. split with N0. split with x0. simpl in |- *. split; assumption. split with (Npos (xO p)). split with x0. simpl in |- *.\n\tsplit; assumption. rewrite H2 in H1. simpl in H1. elim (H0 _ H1). intros. elim H3. intros. elim H4. intros. induction  x as [| p].\n\tsplit with (Npos 1). simpl in |- *. split with x0. split; assumption.\n\tsplit with (Npos (xI p)). split with x0. simpl in |- *. split; assumption.\nQed.\n\nLemma dt_non_empty_r_2 :\n forall (p : prec_list) (m : Map bool),\n pl_non_empty m p = true ->\n exists pl : pl_path, pl_path_true pl m /\\ pl_path_incl pl p.\nProof.\n\tsimple induction p. intros. simpl in H1. elim (pl_sum p1). intros.\n\trewrite H2 in H1. elim (option_sum bool (MapGet bool m a)).\n\tintro y. elim y. intros x y0. rewrite y0 in H1. elim (bool_is_true_or_false x); intros; rewrite H3 in H1; simpl in H1.\n\telim (H m H1). intros. elim H4. intros. rewrite H3 in y0.\n\tsplit with (pl_path_cons a x0). split. exact (plp_true_cons m a x0 H5 y0). exact (pl_path_incl_cons x0 a p0 p1 H6). inversion H1. intro y. rewrite y in H1. inversion H1. intros. elim H2.\n\tintros. elim H3. intros. elim H4. intros. rewrite H5 in H1.\n\telim (option_sum bool (MapGet bool m a)); intro y. elim y. intros x2 y0.\n\trewrite y0 in H1. rewrite <- H5 in H1. elim (bool_is_true_or_false (pl_non_empty m p1)); intros. elim (H0 _ H6). intros. elim H7.\n\tintros. split with x3. split. exact H8. apply (pl_path_incl_next x3 a p0 p1 H9). intro. rewrite H10 in H9. inversion H9. rewrite <- H12 in H5. inversion H5. elim (H12 (refl_equal _)).\n\trewrite H6 in H1. simpl in H1. elim (bool_is_true_or_false x2); intro. rewrite H7 in y0. elim (bool_is_true_or_false (pl_non_empty m p0)); intro. elim (H _ H8). intros. elim H9. intros. split with (pl_path_cons a x3). split. exact (plp_true_cons _ _ _ H10 y0).\n\texact (pl_path_incl_cons x3 a p0 p1 H11). rewrite H8 in H1.\n\trewrite H7 in H1. inversion H1. rewrite H7 in H1. inversion H1.\n\trewrite y in H1. rewrite <- H5 in H1. elim (H0 _ H1). intros.\n\telim H6. intros. split with x2. split. exact H7. apply (pl_path_incl_next x2 a p0 p1 H8). intro. rewrite H9 in H8.\n\tinversion H8. rewrite <- H11 in H5. inversion H5. elim H11.\n\treflexivity. intros. split with pl_path_nil. split. exact (plp_true_nil m). exact pl_path_incl_nil.\nQed.\n\nDefinition dt_non_empty_r_def_0 (n : nat) : Prop :=\n  forall (d : preDTA) (a : ad),\n  MapGet bool (power (Map bool) (dta_app_ne d) (map_mini state d) n) a =\n  Some true -> exists t : term, reconnaissance d a t.\n\nLemma dt_non_empty_r_3 : dt_non_empty_r_def_0 0.\nProof.\n\tunfold dt_non_empty_r_def_0 in |- *. simpl in |- *. intros. cut (true <> false).\n\tintro. elim (H0 (map_mini_mapget_false state d a true H)).\n\tintro. inversion H0.\nQed.\n\nLemma dt_non_empty_r_4 :\n forall (p : prec_list) (n : nat) (d : preDTA) (pl : pl_path),\n dt_non_empty_r_def_0 n ->\n pl_path_true pl (power (Map bool) (dta_app_ne d) (map_mini state d) n) ->\n pl_path_incl pl p -> exists tl : term_list, liste_reconnait d p tl.\nProof.\n\tunfold dt_non_empty_r_def_0 in |- *. simple induction p. intros.\n\tinversion H2. inversion H3.\n        rewrite <- H4 in H7. inversion H7.\n        elim H11; auto.\n        elim (H1 _ _ H5). intros. inversion H3. rewrite <- H10 in H6.\n        inversion H6. rewrite <- H10 in H2.\n        inversion H2. elim (H n d plp H1 H18 H11).\n        intros. split with (tcons x x0).\n        rewrite H15 in H8. rewrite H9 in H8.\n        exact (rec_consi d a p0 p1 x x0 H8 H21).\n        elim (H0 n d pl H1 H2 H12). intros. induction  x0 as [| t x0 Hrecx0].\n        inversion H15. rewrite <- H17 in H12. inversion H12. elim H14; auto.\n        split with (tcons t x0). exact (rec_consn d a p0 p1 t x0 H15).\n        intros. inversion H1. split with tnil. exact (rec_empty d).\nQed.\n\nLemma dt_non_empty_r_5 :\n forall n : nat, dt_non_empty_r_def_0 n -> dt_non_empty_r_def_0 (S n).\nProof.\n\tunfold dt_non_empty_r_def_0 in |- *. intros. elim\n  (domain_equal_mapget bool state\n     (power (Map bool) (dta_app_ne d) (map_mini state d) (S n)) d a true). intros. unfold dta_app_ne in H0.  simpl in H0. elim\n  (dt_non_empty_r_0 d\n     (power (Map bool) (fun m : Map bool => dta_app_ne_aux d m m)\n        (map_mini state d) n)\n     (power (Map bool) (fun m : Map bool => dta_app_ne_aux d m m)\n        (map_mini state d) n) a x H1); intros. exact (H d a H2). elim (dt_non_empty_r_1 _ _ H2). intros. elim H3. intros. elim H4. intros. elim (dt_non_empty_r_2 _ _ H6). intros. elim H7. intros.\n\telim (dt_non_empty_r_4 x1 n d x2 H H8 H9). intros.\n\tsplit with (app x0 x3). exact (rec_dta d a (app x0 x3) x H1 (rec_st d x x0 x3 x1 H5 H10)). apply\n  (power_def_ok bool (ensemble_base state d) (dta_app_ne d)\n     (map_mini state d) n).\n\texact (dta_app_ne_def_ok d). exact (map_mini_appartient state d). exact H0. apply\n  (domain_equal_symmetric state bool d\n     (power (Map bool) (dta_app_ne d) (map_mini state d) (S n))). exact\n  (power_def_ok bool (ensemble_base state d) (dta_app_ne d)\n     (map_mini state d) (S n) (dta_app_ne_def_ok d)\n     (map_mini_appartient state d)). exact H0.\nQed.\n\nLemma dt_non_empty_r :\n forall (n : nat) (d : preDTA) (a : ad),\n MapGet bool (power (Map bool) (dta_app_ne d) (map_mini state d) n) a =\n Some true -> exists t : term, reconnaissance d a t.\nProof.\n\texact (nat_ind dt_non_empty_r_def_0 dt_non_empty_r_3 dt_non_empty_r_5).\nQed.\n\nLemma dt_non_empty_fix_0 :\n forall d : preDTA,\n lower_fix_point bool (ensemble_base state d) lem (dta_app_ne d)\n   (dta_non_empty_states d).\nProof.\n\tunfold dta_non_empty_states in |- *.\n\tintros. exact\n  (iteres_lower_fix_point bool (ensemble_base state d) lem \n     (dta_app_ne d) (map_mini state d) (S (MapCard state d))\n     (S (MapCard state d)) (map_mini_mini state d) \n     (dta_app_ne_def_ok d) (dta_app_ne_inc d) (lattice_bounded state d)\n     (le_n_n _)).\nQed.\n\nLemma dt_non_empty_fix_1 :\n forall (d : preDTA) (a : ad) (n : nat),\n MapGet bool (power (Map bool) (dta_app_ne d) (map_mini state d) n) a =\n Some true -> MapGet bool (dta_non_empty_states d) a = Some true.\nProof.\n\tintros. elim\n  (domain_equal_mapget bool bool\n     (power (Map bool) (dta_app_ne d) (map_mini state d) n)\n     (dta_non_empty_states d) a true).\n\tintros. elim (bool_is_true_or_false x); intro; rewrite H1 in H0.\n\texact H0. elim (dt_non_empty_fix_0 d). intros. unfold inf_fix_points in H3. elim\n  (lem_get_leb _ _ _ _ _\n     (iteres_inf_fps bool (ensemble_base state d) lem \n        (dta_app_ne d) (map_mini state d) (dta_non_empty_states d) n\n        (map_mini_mini state d) H2 (dta_app_ne_inc d)) H H0). apply\n  (domain_equal_transitive bool state bool\n     (power (Map bool) (dta_app_ne d) (map_mini state d) n) d\n     (dta_non_empty_states d)). exact\n  (domain_equal_symmetric state bool _ _\n     (power_def_ok bool (ensemble_base state d) (dta_app_ne d)\n        (map_mini state d) n (dta_app_ne_def_ok d)\n        (map_mini_appartient state d))). unfold dta_non_empty_states in |- *.\n\texact\n  (power_def_ok bool (ensemble_base state d) (dta_app_ne d)\n     (map_mini state d) (S (MapCard state d)) (dta_app_ne_def_ok d)\n     (map_mini_appartient state d)). exact H.\nQed.\n\nLemma dt_non_empty_fix_2 :\n forall (d : preDTA) (a : ad),\n MapGet bool (dta_non_empty_states d) a = Some true ->\n exists n : nat,\n   MapGet bool (power (Map bool) (dta_app_ne d) (map_mini state d) n) a =\n   Some true.\nProof.\n\tunfold dta_non_empty_states in |- *. intros. split with (S (MapCard state d)). exact H.\nQed.\n\n(* correction et complètude du test au vide *)\n\nLemma dt_non_empty_fix :\n forall (d : preDTA) (a : ad),\n MapGet bool (dta_non_empty_states d) a = Some true <->\n (exists t : term, reconnaissance d a t).\nProof.\n\tintros. split. intros. elim (dt_non_empty_fix_2 d a H).\n\tintros. exact (dt_non_empty_r _ _ _ H0). intros. elim H.\n\tintros. elim (dt_non_empty_d d a x H0). intros. exact (dt_non_empty_fix_1 _ _ _ H1).\nQed.\n\nLemma dt_non_empty_lazy_fix :\n forall (d : preDTA) (a : ad),\n MapGet bool (dta_non_empty_states_lazy d) a = Some true <->\n (exists t : term, reconnaissance d a t).\nProof.\n\tintro. unfold dta_non_empty_states_lazy in |- *. rewrite\n  (lazy_power_eg_power bool eqm_bool (dta_app_ne d) \n     (map_mini state d) (S (MapCard state d))). exact (dt_non_empty_fix d). split. exact (eqm_bool_equal a b). intro. rewrite H. exact (equal_eqm_bool b).\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/empty_test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.2904852897846908}}
{"text": "\nFrom VT Require Export seplogic.\n\nDefinition NULL := 0.\n\n(* (l |-> w) * (l+1 |-> _) *)\nDefinition pto1any L l w : Heap -> PropX L := star (pto _ l w) (ptoany _ (l+1)).\n\n(* (l |-> _) * (l+1 |-> w) *)\nDefinition ptoany1 L l w : Heap -> PropX L := star (ptoany _ l) (pto _ (l+1) w).\n\n(* (l |-> _) * (l+1 |-> _) *)\nDefinition ptoanyany L l : Heap -> PropX L := star (ptoany _ l) (ptoany _ (l+1)).\n\n(* Definitions using tactic language Ltac. *)\n(* okvalid: Validity_of_Deductions *)\nLtac des H := generalize (okvalid _ _ H); clear H; intro; unfold eq_rect.\nLtac dest H := generalize (okvalid _ _ H); clear H; destruct 1; unfold eq_rect.\nLtac destx H v := generalize (okvalid _ _ H); clear H; destruct 1 as [v]; unfold eq_rect.\nLtac existsx x := apply ok_extx_i with x.\nLtac splitx := apply ok_and_i.\nLtac leftx := apply ok_or_i1.\nLtac rightx := apply ok_or_i2.\nLtac propx := apply ok_prop_i.\n\n(* a: Heap -> PropX L\n   Si: CdHpSpec\n   h: Heap \n *)\nLemma star_emp : forall a Si h,\n  (* OK: Env -> CdHpSpec -> PropX tO -> Prop\n     Validity rules for impredicative extended propositions \n  *)\n  (* Gamma(nil) |-{Si} a * emp *)\n  OK xcapi.nil Si (star a (emp _) h) ->\n  (* meq: forall a, M1 a = M2 a *)\n  (forall Si h h', Map.meq h h' -> OK xcapi.nil Si (a h) -> OK xcapi.nil Si (a h')) ->\n  OK xcapi.nil Si (a h).\nAdmitted.\n\nLemma star_sym : forall a a' Si h,\n  OK xcapi.nil Si (star a a' h) -> OK xcapi.nil Si (star a' a h).\nAdmitted.\n\nLemma star_assoc_R : forall a a' a'' Si h,\n  OK xcapi.nil Si (star a (star a' a'') h) ->\n  OK xcapi.nil Si (star (star a a') a'' h).\nAdmitted.\n\nLemma star_assoc_L : forall a a' a'' Si h,\n  OK xcapi.nil Si (star (star a a') a'' h) ->\n  OK xcapi.nil Si (star a (star a' a'') h).\nAdmitted.\n\nLemma pto_lookup : forall l w Si h,\n  OK xcapi.nil Si (pto _ l w h) -> Map.lookup h l w.\nAdmitted.\n\nLemma lookup_star_lookup : forall l w a,\n  (forall Si h, OK xcapi.nil Si (a h) -> Map.lookup h l w) ->\n  forall a' Si h, OK xcapi.nil Si (star a a' h) -> Map.lookup h l w.\nAdmitted.\n\nLemma ptoany_indom : forall l Si h,\n  OK xcapi.nil Si (ptoany _ l h) -> Map.in_dom h l.\nAdmitted.\n\nLemma indom_star_indom : forall l a,\n  (forall Si h, OK xcapi.nil Si (a h) -> Map.in_dom h l) ->\n  forall a' Si h, OK xcapi.nil Si (star a a' h) -> Map.in_dom h l.\nAdmitted.\n\nDefinition hpred_imp (a a' : Heap -> PropX tO) :=\n  forall h Si, OK xcapi.nil Si (a h) -> OK xcapi.nil Si (a' h).\n\nLemma ok_star_ok : forall a a' a'' h Si,\n  OK xcapi.nil Si ((star a a') h) -> hpred_imp a' a''\n  -> OK xcapi.nil Si ((star a a'') h).\nAdmitted.\n\nLemma pto2_ptoany1 : forall l w w' Si h,\n  OK xcapi.nil Si (pto2 _ l w w' h) -> OK xcapi.nil Si (ptoany1 _ l w' h).\nAdmitted.\n\nLemma ptoany1_ptoanyany : forall l w Si h,\n  OK xcapi.nil Si (ptoany1 _ l w h) -> OK xcapi.nil Si (ptoanyany _ l h).\nAdmitted.\n\nLemma ptoany_free : forall l Si h,\n  OK xcapi.nil Si (ptoany _ l h) -> OK xcapi.nil Si (emp _ (fH h l)).\nAdmitted.\n\nLemma disj_free_disj :\n  forall h1 h2 l, Map.disjoint h1 h2 -> Map.disjoint h1 (fH h2 l).\nAdmitted.\n\nLemma disj_update_disj :\n  forall h1 h2 l w, Map.disjoint h1 h2 -> Map.in_dom h1 l ->\n                    Map.disjoint (uH h1 l w) h2.\nAdmitted.\n\nLemma star_free : forall l a a' a'',\n  (forall Si h, OK xcapi.nil Si (a' h) -> \n    Map.in_dom h l /\\ OK xcapi.nil Si (a'' (fH h l))) ->\n  forall Si h, OK xcapi.nil Si (star a a' h) ->\n    Map.in_dom h l /\\ OK xcapi.nil Si (star a a'' (fH h l)).\nAdmitted.\n\nLemma star_imp : forall a a' a'' a''',\n  (forall Si h, OK xcapi.nil Si (a h) -> OK xcapi.nil Si (a'' h)) ->\n  (forall Si h, OK xcapi.nil Si (a' h) -> OK xcapi.nil Si (a''' h)) ->\n  forall Si h, OK xcapi.nil Si (star a a' h) -> OK xcapi.nil Si (star a'' a''' h).\nAdmitted.\n\nLemma pto2_pto1any : forall l w w' Si h,\n  OK xcapi.nil Si (pto2 _ l w w' h) -> OK xcapi.nil Si (pto1any _ l w h).\nAdmitted.\n\nLemma star_meq_star : forall a a' Si h h',\n  OK xcapi.nil Si (star a a' h) -> Map.meq h h' ->\n  OK xcapi.nil Si (star a a' h').\nAdmitted.\n\nLemma ptoany_update : forall l Si h w,\n  OK xcapi.nil Si (ptoany _ l h) -> OK xcapi.nil Si (pto _ l w (uH h l w)).\nAdmitted.\n\nLemma star_update : forall a a' l w,\n  (forall Si h, OK xcapi.nil Si (a h) -> \n                Map.in_dom h l /\\ OK xcapi.nil Si (a' (uH h l w))) ->\n  forall a'' Si h, OK xcapi.nil Si (star a a'' h) ->\n                   OK xcapi.nil Si (star a' a'' (uH h l w)).\nAdmitted.\n\nLemma subst_star : forall B (A : B -> PropX tO) a a' a'' a''',\n  (forall Si h, OK xcapi.nil Si (Subst tO B (a h) A) ->\n                OK xcapi.nil Si (a'' h)) ->\n  (forall Si h, OK xcapi.nil Si (Subst tO B (a' h) A) ->\n                OK xcapi.nil Si (a''' h)) ->\n  forall Si h, OK xcapi.nil Si (Subst tO B (star a a' h) A) ->\n               OK xcapi.nil Si (star a'' a''' h).\nAdmitted.\n\nLemma star_subst : forall a a' B (A : B -> PropX tO) a'' a''',\n  (forall Si h, OK xcapi.nil Si (a h) -> \n                OK xcapi.nil Si (Subst tO B (a'' h) A)) ->\n  (forall Si h, OK xcapi.nil Si (a' h) -> \n                OK xcapi.nil Si (Subst tO B (a''' h) A)) ->\n  forall Si h, OK xcapi.nil Si (star a a' h) ->\n               OK xcapi.nil Si (Subst tO B (star a'' a''' h) A).\nAdmitted.\n\n\n\n", "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/midterm-xcap/ecplib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632683808532, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.2904852818697011}}
{"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(* Notation management revised in December 2002 *)\n\n(****************************************************************************)\n(*                                                                          *)\n(*                                                                          *)\n(*  subset.v                                                                *)\n(*                                                                          *)\n(*  Definition of subsets as types                                          *)\n(*                                                                          *)\n(*                                                                          *)\n(*  Samuel Boutin                                                           *)\n(*  Coq V5.10                                                               *)\n(*  June  1995                                                              *)\n(*                                                                          *)\n(*                                                                          *)\n(****************************************************************************)\n(*                              subset.v                                    *)\n(****************************************************************************)\n\n\n(* \nWe define subset as types in the same way as quotients:\nlike in the deliverable model where a subset is a type\nand a predicate on that type.\nThe alternative consisting of using a strong sum to encode\nthis feature suffers from the fact that we need to\nuse proof irrelevance if we want two\nobjects (a,pa) (a,pb) with pa,pb:(P a) to be identified.\n*)\n\n(* Definition of a subset: *)\n\nParameter MK_SUBSET : forall (A : Set) (R : A -> Prop), Set.\n\n(* An element of a subset is an element of the underlying type\nwith a proof that this element satisfies the underlying predicate *)\n\nParameter\n  In_subset : forall (A : Set) (R : A -> Prop) (a : A), R a -> MK_SUBSET A R.\n\n(* Every element of a subset is an element of the underlying type *)\n\nParameter Out_subset : forall (A : Set) (R : A -> Prop), MK_SUBSET A R -> A.\n\n(* Every element of the subset should satisfy the underlying predicate *)\n\nParameter\n  proof :\n    forall (A : Set) (R : A -> Prop) (t : MK_SUBSET A R),\n    R (Out_subset A R t).\n\n(* Rewrite rules explaining coercion principles between the subset and its \nunderlying type *)\n\nAxiom\n  In_Out :\n    forall (A : Set) (R : A -> Prop) (t : MK_SUBSET A R)\n      (p : R (Out_subset A R t)), In_subset A R (Out_subset A R t) p = t.\n\nAxiom\n  Out_In :\n    forall (A : Set) (R : A -> Prop) (t : A) (p : R t),\n    Out_subset A R (In_subset A R t p) = t.\n\n(* Without proof irrelevance we should identify two element of a subset\nas soon as their projection on the ground type are leibniz equal *)\n\nAxiom\n  Canonic :\n    forall (A : Set) (R : A -> Prop) (t : A) (p p' : R t),\n    In_subset A R t p = In_subset A R t p'.\n\n(* Closure axioms defining the canonical form of objects of a subset type *)\n\nAxiom\n  Prop_closure :\n    forall (A : Set) (R : A -> Prop) (P : MK_SUBSET A R -> Prop)\n      (x : MK_SUBSET A R),\n    (forall (y : A) (p : R y), P (In_subset A R y p)) -> P x.\n\nAxiom\n  Set_closure :\n    forall (A : Set) (R : A -> Prop) (P : MK_SUBSET A R -> Set)\n      (x : MK_SUBSET A R),\n    (forall (y : A) (p : R y), P (In_subset A R y p)) -> P x.\n\n\n(* Notation for subsets: *)\n\nNotation \"c ! p\" := (MK_SUBSET c p) (at level 20).\n\nNotation \"%+ c\" := (In_subset _ _ _ c) (at level 20).\n\n(*\nRequire quotient.\n\nGrammar constr constr1 := \n  mksub [ constr0($c) \"!\" constr0($c2) ] -> [ (MK_SUBSET $c $c2) ].\n\nSyntax constr \n  level 1:\n  MK_SUBSET [ (MK_QUO $c $c1) ] -> [$c: L \"!\" $c1:L].\n*)", "meta": {"author": "coq-contribs", "repo": "rational", "sha": "9738e3672b597c485001257baee9cfaf1419948d", "save_path": "github-repos/coq/coq-contribs-rational", "path": "github-repos/coq/coq-contribs-rational/rational-9738e3672b597c485001257baee9cfaf1419948d/Subset/subset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984137988773, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.29048528173525834}}
{"text": "(* Celsius project *)\n(* Clément Blaudeau - Lamp@EPFL & Inria 2020-2022 *)\n(* ------------------------------------------------------------------------ *)\n(* This files defines the big step semantics and an induction predicate on the rules *)\n\nFrom Celsius Require Export Helpers.\n\n\n(* ------------------------------------------------------------------------ *)\n(** ** Big step semantics *)\n\n(* Notation only used for the definition *)\nReserved Notation \"'⟦'  e  '⟧p' '(' σ ',' ρ ',' v ')'  '-->'  '(' v0 ',' σ0 ')'\" (at level 80).\nReserved Notation \"'⟦_' e '_⟧p' '(' σ ',' ρ ',' v ')'  '-->'  '(' vl ',' σl ')'\" (at level 80).\n\n(* Big step semantics for an expression *)\nInductive evalP : Expr -> Store -> Env -> Loc -> Loc -> Store -> Prop :=\n\n(* Variable : we retrieve the value of x in the local environment ρ *)\n| bs_var : forall σ x ρ ψ l,\n    getVal ρ x = Some l ->\n    ⟦ e_var x ⟧p (σ, ρ, ψ) --> (l, σ)\n\n(* This : we return the current this pointer ψ *)\n| bs_this : forall σ ρ ψ,\n    ⟦ e_this ⟧p (σ, ρ, ψ) --> (ψ, σ)\n\n(* Field access : we compute the object e, and fetch the value of the field in the resulting\nobject *)\n| bs_fld : forall σ ρ ψ e f v1 σ1 C ω v,\n    ⟦ e ⟧p (σ, ρ, ψ) --> (v1, σ1) ->\n    getObj σ1 v1 = Some (C, ω) ->\n    getVal ω f = Some v ->\n    ⟦ (e_fld e f) ⟧p (σ, ρ, ψ) --> (v, σ1)\n\n(* Method call : we first compute the object on which the method will be called, then the arguments,\nand then we fetch the body of the method which we execute with the arguments as local environment *)\n| bs_mtd : forall σ e0 m el e2 ρ ψ l1 vl2 l3 σ1 σ2 σ3 C Args Flds Mtds f argsM T μ,\n    ⟦ e0 ⟧p (σ, ρ, ψ) --> (l1, σ1) ->\n    getObj σ1 l1 = Some (C, f) ->\n    ⟦_ el _⟧p (σ1, ρ, ψ) --> (vl2, σ2) ->\n    ct C = class Args Flds Mtds  ->\n    Mtds m = Some (method μ argsM T e2) ->\n    ⟦ e2 ⟧p (σ2, vl2, l1) --> (l3, σ3) ->\n    ⟦ e_mtd e0 m el ⟧p (σ, ρ, ψ) --> (l3, σ3)\n\n(* New instance : we compute the arguments and call the special procedure [initP] to initialize the\nnew instance *)\n| bs_new : forall σ ρ ψ C args vl__args σ1 σ3,\n    ⟦_ args _⟧p (σ, ρ, ψ) --> (vl__args, σ1) ->\n    let I := (length σ1) in\n    initP C I 0 vl__args (σ1 ++ [(C, [])]) σ3 ->\n    ⟦ e_new C args ⟧p (σ, ρ, ψ) --> (I, σ3)\n\n(* Assignment : we compute the object, the value and update the field x. Then we compute the other\nexpression e' *)\n| bs_asgn : forall σ ρ ψ e1 x e2 e' σ1 v1 σ2 v2 σ3 v3,\n    ⟦ e1 ⟧p (σ, ρ, ψ) --> (v1, σ1) ->\n    ⟦ e2 ⟧p (σ1, ρ, ψ) --> (v2, σ2) ->\n    ⟦ e' ⟧p ((assign v1 x v2 σ2), ρ, ψ) --> (v3, σ3) ->\n    ⟦ e_asgn e1 x e2 e' ⟧p (σ, ρ, ψ) --> (v3, σ3)\n\nwhere \"'⟦' e '⟧p' '(' σ ',' ρ ',' v ')' '-->' '(' v0 ',' σ0 ')' \"  := (evalP e σ ρ v v0 σ0)\n\n(* Big step semantics for a list of expressions (mainly a fold left) *)\nwith evalListP : list Expr -> Store -> Env -> Loc -> list Loc -> Store -> Prop :=\n\n| bs_nil : forall σ ρ ψ,\n    ⟦_ [] _⟧p (σ, ρ, ψ) --> ([], σ)\n\n| bs_cons : forall σ ρ ψ e el l1 σ1 vl σ2,\n    ⟦ e ⟧p (σ, ρ, ψ) --> (l1, σ1) ->\n    ⟦_ el _⟧p (σ1, ρ, ψ) --> (vl, σ2) ->\n    ⟦_ (e::el) _⟧p (σ, ρ, ψ) --> (l1::vl, σ2)\n\nwhere \"'⟦_' el '_⟧p' '(' σ ',' ρ ',' v ')' '-->' '(' vl ',' σ0 ')' \"  := (evalListP el σ ρ v vl σ0)\n\n(* Initialization procedure: we compute the mandatory field initializers for the fields between i\nand (length Flds) *)\nwith initP : ClN -> Var -> nat -> Env -> Store -> Store -> Prop :=\n\n(* No fields left to initialize *)\n| init_nil : forall C I ρ σ Args Flds Mtds,\n    ct C = class Args Flds Mtds ->\n    initP C I (dom Flds) ρ σ σ\n\n(* We compute the value of the defining expression, then update the store (which can already a value\nfor x) and proceed *)\n| init_cons : forall C ψ i ρ σ v T e Args Flds Mtds σ1 σ2 σ3,\n    ct C = class Args Flds Mtds ->\n    nth_error Flds i = Some (field T e) ->\n    ⟦ e ⟧p (σ, ρ, ψ) --> (v, σ1) ->\n    assign_new ψ i v σ1 = Some σ2 ->\n    initP C ψ (S i) ρ σ2 σ3 ->\n    initP C ψ i ρ σ σ3.\n\n(* Overloaded notations between expressions and lists of expressions *)\nGlobal Instance notation_big_step_list_expr : notation_big_step (list Expr) (list Loc) :=\n  { big_step_ := evalListP }.\nGlobal Instance notation_big_step_expr : notation_big_step Expr Loc :=\n  { big_step_ := evalP }.\nGlobal Hint Unfold big_step_: core.\nGlobal Hint Unfold notation_big_step_expr: core.\nGlobal Hint Unfold notation_big_step_list_expr: core.\n\n(* ------------------------------------------------------------------------ *)\n(** ** Induction predicate *)\n\nSection evalP_ind.\n  (* We define a custom induction predicate *)\n\n  Variable P : forall e σ ρ ψ v σ', (evalP e σ ρ ψ v σ') -> Prop.\n  Variable Pl : forall el σ ρ ψ vl σ', (evalListP el σ ρ ψ vl σ') -> Prop.\n  Variable Pin : forall C ψ x ρ σ σ', (initP C ψ x ρ σ σ') -> Prop.\n\n  Variable P_var : forall σ x ρ ψ l Hget,\n      P (e_var x) σ ρ ψ l σ (bs_var σ x ρ ψ l Hget).\n\n  Variable P_this : forall σ ρ ψ,\n      P e_this σ ρ ψ ψ σ (bs_this σ ρ ψ).\n\n  Variable P_fld : forall σ ρ ψ e f v1 σ1 C ω v EH__e0 H__getObj H__getVal\n    (IH__e0: P e σ ρ ψ v1 σ1 (EH__e0)),\n    P (e_fld e f) σ ρ ψ v σ1 (bs_fld σ ρ ψ e f v1 σ1 C ω v EH__e0 H__getObj H__getVal).\n\n  Variable P_mtd : forall σ e0 m el e2 ρ ψ v1 vl2 v3 σ1 σ2 σ3 C f argsC argsM fields methods T μ H__e0 Hobj H__el Hct Hmth  H__e2\n    (IH__e0: P e0 σ ρ ψ v1 σ1 H__e0)\n    (IH__el: Pl el σ1 ρ ψ vl2 σ2 H__el)\n    (IH__e2: P e2 σ2 vl2 v1 v3 σ3 H__e2),\n    P( e_mtd e0 m el) σ ρ ψ v3 σ3 (bs_mtd σ e0 m el e2 ρ ψ v1 vl2 v3 σ1 σ2 σ3 C f argsC argsM fields methods T μ H__e0 Hobj H__el Hct Hmth H__e2).\n\n  Variable P_new : forall σ ρ ψ C args vl__args σ1 σ3 H__args H__init\n    (IH__args: Pl args σ ρ ψ vl__args σ1 H__args)\n    (IH__init: Pin C (length σ1) 0 vl__args (σ1 ++ [(C, [])]) σ3 H__init),\n    P (e_new C args) σ ρ ψ (length σ1) σ3 (bs_new σ ρ ψ C args vl__args σ1 σ3 H__args H__init).\n\n  Variable P_asgn :  forall σ ρ ψ e1 x e2 e' σ1 v1 σ2 v2 σ3 v3 H__e1 H__e2 H__e'\n    (IH__e1: P e1 σ ρ ψ v1 σ1 H__e1)\n    (IH__e2: P e2 σ1 ρ ψ v2 σ2 H__e2)\n    (IH__e': P e' (assign v1 x v2 σ2) ρ ψ v3 σ3 H__e'),\n    P (e_asgn e1 x e2 e') σ ρ ψ v3 σ3 (bs_asgn σ ρ ψ e1 x e2 e' σ1 v1 σ2 v2 σ3 v3 H__e1 H__e2 H__e').\n\n  Variable Pl_nil : forall σ ρ ψ, Pl [] σ ρ ψ [] σ (bs_nil σ ρ ψ).\n\n  Variable Pl_cons : forall σ ρ ψ e el v1 σ1 vl σ2 H__e H__el\n      (IH__e: P e σ ρ ψ v1 σ1 H__e)\n      (IH__el: Pl el σ1 ρ ψ vl σ2 H__el),\n      Pl (e::el) σ ρ ψ (v1::vl) σ2 (bs_cons σ ρ ψ e el v1 σ1 vl σ2 H__e H__el).\n\n  Variable Pin_nil: forall C I ρ σ Args Flds Mtds H__ct,\n      Pin C I (length Flds) ρ σ σ (init_nil C I ρ σ Args Flds Mtds H__ct).\n\n  Variable Pin_cons : forall C I x ρ σ v T e Args Flds Mtds σ1 σ2 σ3 H__ct H__fld H__e H__assign H__init\n      (IH__e: P e σ ρ I v σ1 H__e)\n      (IH__init: Pin C I (S x) ρ σ2 σ3 H__init),\n      Pin C I x ρ σ σ3 (init_cons C I x ρ σ v T e Args Flds Mtds σ1 σ2 σ3 H__ct H__fld H__e H__assign H__init).\n\n  Fixpoint evalP_ind2 e σ ρ ψ v σ' (eval : evalP e σ ρ ψ v σ') : P e σ ρ ψ v σ' eval :=\n    match eval with\n    | bs_var σ x ρ ψ v Hget => P_var σ x ρ ψ v Hget\n    | bs_this σ ρ ψ => P_this σ ρ ψ\n    | bs_fld σ ρ ψ e0 x l1 σ1 C f v1 H__e0 Hobj Hval =>\n        P_fld σ ρ ψ e0 x l1 σ1 C f v1 H__e0 Hobj Hval (evalP_ind2 e0 σ ρ ψ l1 σ1 H__e0)\n    | bs_mtd σ e0 m el e2 ρ ψ l1 vl2 l3 σ1 σ2 σ3 C f argsC argsM fields methods T μ H__e0 Hobj H__el Hct Hmth H__e2 =>\n        P_mtd σ e0 m el e2 ρ ψ l1 vl2 l3 σ1 σ2 σ3 C f argsC argsM fields methods T μ H__e0 Hobj H__el Hct Hmth H__e2\n              (evalP_ind2 e0 σ ρ ψ l1 σ1 H__e0)\n              (evalListP_ind2 el σ1 ρ ψ vl2 σ2 H__el)\n              (evalP_ind2 e2 σ2 vl2 l1 l3 σ3 H__e2)\n    | bs_new σ ρ ψ C args vl__args σ1 σ3 H__args H__init =>\n        P_new σ ρ ψ C args vl__args σ1 σ3 H__args H__init\n              (evalListP_ind2 args σ ρ ψ vl__args σ1 H__args)\n              (initP_ind2 C (length σ1) 0 vl__args (σ1 ++ [(C, [])]) σ3 H__init)\n    | bs_asgn σ ρ ψ e1 x e2 e' σ1 v1 σ2 v2 σ3 v3 H__e1 H__e2 H__e' =>\n        P_asgn σ ρ ψ e1 x e2 e' σ1 v1 σ2 v2 σ3 v3 H__e1 H__e2 H__e'\n               (evalP_ind2 e1 σ ρ ψ v1 σ1 H__e1)\n               (evalP_ind2 e2 σ1 ρ ψ v2 σ2 H__e2)\n               (evalP_ind2 e' (assign v1 x v2 σ2) ρ ψ v3 σ3 H__e')\n    end\n\n  with evalListP_ind2 el σ ρ ψ vl σ' evalList : Pl el σ ρ ψ vl σ' evalList :=\n         match evalList  with\n         | bs_nil σ ρ ψ  => Pl_nil σ ρ ψ\n         | bs_cons σ ρ ψ e el l1 σ1 vl σ2 H__e H__el =>\n             Pl_cons σ ρ ψ e el l1 σ1 vl σ2 H__e H__el\n                     (evalP_ind2 e σ ρ ψ l1 σ1 H__e)\n                     (evalListP_ind2 el σ1 ρ ψ vl σ2 H__el)\n         end\n\n  with initP_ind2 C ψ x (ρ:Env) (σ σ':Store) H__init: Pin C ψ x ρ σ σ' H__init :=\n         match H__init with\n         | init_nil C ψ ρ σ Args Flds Mtds H__ct => Pin_nil C ψ ρ σ Args Flds Mtds H__ct\n         | init_cons C ψ x ρ σ v T e Args Flds Mtds σ1 σ2 σ3 H__ct H__fld H__e H__assign H__init  =>\n             Pin_cons C ψ x ρ σ v T e Args Flds Mtds σ1 σ2 σ3 H__ct H__fld H__e H__assign H__init\n                      (evalP_ind2 e σ ρ ψ v σ1 H__e)\n                      (initP_ind2 C ψ (S x) ρ σ2 σ3 H__init)\n         end.\n\n  Lemma evalP_multi_ind:\n    (forall e σ ρ ψ v σ' H__eval, P e σ ρ ψ v σ' H__eval) /\\\n      (forall el σ ρ ψ vl σ' H__evalList, Pl el σ ρ ψ vl σ' H__evalList) /\\\n      (forall C ψ x ρ σ σ' H__init, Pin C ψ x ρ σ σ' H__init).\n  Proof.\n    splits; intros.\n    + apply evalP_ind2.\n    + apply evalListP_ind2.\n    + apply initP_ind2.\n  Qed.\n\nEnd evalP_ind.\n\n(* ------------------------------------------------------------------------ *)\n(** ** Conservation result *)\n(* The monotonicity on the size of the store is easy to obtain via induction *)\n\nTheorem dom_theorem:\n  (forall e σ ρ ψ v σ',\n      ⟦e⟧ (σ, ρ, ψ) --> (v, σ') -> dom σ <= dom σ') /\\\n    ( forall el σ ρ ψ vl σ',\n        ⟦_ el _⟧p (σ, ρ, ψ) --> (vl, σ') -> dom σ <= dom σ') /\\\n    ( forall C ψ x ρ σ σ',\n        initP C ψ x ρ σ σ' -> dom σ <= dom σ').\nProof.\n  eapply evalP_multi_ind;\n    unfold assign, assign_new;\n    steps; updates; try lia.\nQed.\n\nCorollary evalP_dom:\n  forall e σ ρ ψ v σ',\n      ⟦e⟧ (σ, ρ, ψ) --> (v, σ') -> dom σ <= dom σ'.\nProof.\n  apply dom_theorem.\nQed.\n\nCorollary evalListP_dom:\n   forall el σ ρ ψ vl σ',\n      ⟦_ el _⟧p (σ, ρ, ψ) --> (vl, σ') -> dom σ <= dom σ'.\nProof.\n  apply dom_theorem.\nQed.\n\nCorollary initP_dom:\n  forall C ψ x ρ σ σ',\n      initP C ψ x ρ σ σ' -> dom σ <= dom σ'.\nProof.\n  apply dom_theorem.\nQed.\n\nLemma init_field:\n  forall C ψ x ρ σ σ' Args Flds Mtds,\n    ct C = class Args Flds Mtds ->\n    initP C ψ x ρ σ σ' ->\n    x <= length Flds.\nProof.\n  intros. move: Args Flds Mtds H.\n  induction H0; intros; cross_rewrites => //.\n  apply IHinitP in H. lia.\nQed.\n\n\nLtac eval_dom :=\n  repeat match goal with\n         | H: ⟦ ?e ⟧p (?σ, ?ρ, ?ψ) --> (?v, ?σ') |- _ =>\n             let fresh := fresh \"H_dom\" in\n             add_hypothesis fresh (evalP_dom e σ ρ ψ v σ' H)\n         | H: ⟦_ ?el _⟧p (?σ, ?ρ, ?ψ) --> (?vl, ?σ') |- _ =>\n             let fresh := fresh \"H_dom\" in\n             add_hypothesis fresh (evalListP_dom el σ ρ ψ vl σ' H)\n         | H: ⟦ ?e ⟧ (?σ, ?ρ, ?ψ) --> (?v, ?σ') |- _ =>\n             let fresh := fresh \"H_dom\" in\n             add_hypothesis fresh (evalP_dom e σ ρ ψ v σ' H)\n         | H: ⟦?el ⟧ (?σ, ?ρ, ?ψ) --> (?vl, ?σ') |- _ =>\n             let fresh := fresh \"H_dom\" in\n             add_hypothesis fresh (evalListP_dom el σ ρ ψ vl σ' H)\n         | H: initP ?C ?ψ ?x ?ρ ?σ ?σ' |- _ =>\n             let fresh := fresh \"H_dom\" in\n             add_hypothesis fresh (initP_dom C ψ x ρ σ σ' H)\n         end.\n", "meta": {"author": "clementblaudeau", "repo": "celsius", "sha": "33a7f479025f94551b6c7a96807f05469dcae595", "save_path": "github-repos/coq/clementblaudeau-celsius", "path": "github-repos/coq/clementblaudeau-celsius/celsius-33a7f479025f94551b6c7a96807f05469dcae595/src/Semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.29043243111527217}}
{"text": "From Test Require Import tactic.\n\nSection FOFProblem.\n\nVariable Universe : Set.\nVariable UniverseElement : Universe.\n\nVariable tPROGRAM_ : Universe -> Prop.\nVariable tOr_72_ : Universe -> Universe -> Universe -> Prop.\nVariable tOr_65_ : Universe -> Universe -> Universe -> Prop.\nVariable tOr_50_ : Universe -> Universe -> Universe -> Prop.\nVariable tOr_46_ : Universe -> Universe -> Universe -> Prop.\nVariable tOr_26_ : Universe -> Prop.\nVariable tOr_15_ : Universe -> Universe -> Prop.\nVariable tOUTPUTS_ : Universe -> Universe -> Prop.\nVariable tHALTS3_ : Universe -> Universe -> Universe -> Prop.\nVariable tHALTS2_ : Universe -> Universe -> Prop.\nVariable tForall_76_ : Universe -> Universe -> Prop.\nVariable tForall_54_ : Universe -> Prop.\nVariable tForall_28_ : Prop.\nVariable tForall_17_ : Universe -> Prop.\nVariable tExists_40_ : Universe -> Universe -> Prop.\nVariable tExists_22_ : Universe -> Universe -> Prop.\nVariable tDECIDES_ : Universe -> Universe -> Universe -> Prop.\nVariable tAnd_74_ : Universe -> Universe -> Universe -> Prop.\nVariable tAnd_70_ : Universe -> Universe -> Prop.\nVariable tAnd_63_ : Universe -> Universe -> Universe -> Prop.\nVariable tAnd_59_ : Universe -> Universe -> Universe -> Prop.\nVariable tAnd_52_ : Universe -> Universe -> Universe -> Prop.\nVariable tAnd_48_ : Universe -> Universe -> Universe -> Prop.\nVariable tAnd_44_ : Universe -> Universe -> Universe -> Prop.\nVariable tAnd_36_ : Universe -> Prop.\nVariable tAnd_19_ : Universe -> Prop.\nVariable tALGORITHM_ : Universe -> Prop.\nVariable goal_ : Prop.\nVariable fPROGRAM_ : Universe -> Prop.\nVariable fOr_69_ : Universe -> Universe -> Universe -> Prop.\nVariable fOr_62_ : Universe -> Universe -> Universe -> Prop.\nVariable fOr_58_ : Universe -> Universe -> Universe -> Prop.\nVariable fOr_33_ : Universe -> Universe -> Prop.\nVariable fOUTPUTS_ : Universe -> Universe -> Prop.\nVariable fHALTS3_ : Universe -> Universe -> Universe -> Prop.\nVariable fHALTS2_ : Universe -> Universe -> Prop.\nVariable fForall_35_ : Universe -> Prop.\nVariable fForall_31_ : Universe -> Universe -> Prop.\nVariable fForall_14_ : Universe -> Universe -> Prop.\nVariable fDECIDES_ : Universe -> Universe -> Universe -> Prop.\nVariable fALGORITHM_ : Universe -> Prop.\nVariable dom_ : Universe -> Prop.\n\nVariable good_ : Universe.\nVariable bad_ : Universe.\n\nVariable initial_model_1 : (dom_ good_ /\\ (dom_ bad_ /\\ (dom_ X1 /\\ (tAnd_19_ X1 /\\ tForall_17_ X1)))).\nVariable botALGORITHM_2 : (forall V1 : Universe, ((tALGORITHM_ V1 /\\ fALGORITHM_ V1) -> goal_)).\nVariable botDECIDES_3 : (forall V1 V2 V3 : Universe, ((tDECIDES_ V1 V2 V3 /\\ fDECIDES_ V1 V2 V3) -> goal_)).\nVariable botPROGRAM_4 : (forall V1 : Universe, ((tPROGRAM_ V1 /\\ fPROGRAM_ V1) -> goal_)).\nVariable botHALTS3_5 : (forall V1 V2 V3 : Universe, ((tHALTS3_ V1 V2 V3 /\\ fHALTS3_ V1 V2 V3) -> goal_)).\nVariable botHALTS2_6 : (forall V1 V2 : Universe, ((tHALTS2_ V1 V2 /\\ fHALTS2_ V1 V2) -> goal_)).\nVariable botOUTPUTS_7 : (forall V1 V2 : Universe, ((tOUTPUTS_ V1 V2 /\\ fOUTPUTS_ V1 V2) -> goal_)).\nVariable ax00_8 : (forall X1 : Universe, ((tAnd_19_ X1 /\\ fALGORITHM_ X1) -> goal_)).\nVariable ax01_9 : (forall X1 Y1 : Universe, ((tOr_15_ X1 Y1 /\\ (tPROGRAM_ Y1 /\\ fForall_14_ X1 Y1)) -> goal_)).\nVariable ax02_10 : (forall W : Universe, ((tAnd_36_ W /\\ fForall_35_ W) -> goal_)).\nVariable ax03_11 : (forall Y Z W : Universe, ((tAnd_44_ Y Z W /\\ fOUTPUTS_ W good_) -> goal_)).\nVariable ax04_12 : (forall Y Z W : Universe, ((tAnd_48_ Y Z W /\\ fOUTPUTS_ W bad_) -> goal_)).\nVariable ax05_13 : (forall Y Z W : Universe, ((tAnd_59_ Y Z W /\\ fOr_58_ Y Z W) -> goal_)).\nVariable ax06_14 : (forall Y Z W : Universe, ((tAnd_63_ Y Z W /\\ tHALTS2_ Y Z) -> goal_)).\nVariable ax07_15 : (forall Y Z W : Universe, ((tAnd_63_ Y Z W /\\ fOr_62_ Y Z W) -> goal_)).\nVariable ax08_16 : (forall W Y V : Universe, ((tAnd_74_ W Y V /\\ fOr_69_ W V Y) -> goal_)).\nVariable ax09_17 : (forall Y V : Universe, ((tAnd_70_ Y V /\\ fOUTPUTS_ V bad_) -> goal_)).\nVariable ax10_18 : (forall Y1 X1 : Universe, ((dom_ Y1 /\\ tForall_17_ X1) -> tOr_15_ X1 Y1)).\nVariable ax11_19 : (forall X1 Y1 Z1 : Universe, (fDECIDES_ X1 Y1 Z1 -> fForall_14_ X1 Y1)).\nVariable ax12_20 : (forall X : Universe, ((dom_ X /\\ tForall_28_) -> tOr_26_ X)).\nVariable ax13_21 : (forall W Y : Universe, (fOr_33_ W Y -> fForall_35_ W)).\nVariable ax14_22 : (forall Y W : Universe, ((tPROGRAM_ Y /\\ fForall_31_ W Y) -> fOr_33_ W Y)).\nVariable ax15_23 : (forall W Y Z : Universe, (fDECIDES_ W Y Z -> fForall_31_ W Y)).\nVariable ax16_24 : (forall Y Z W : Universe, ((dom_ Y /\\ (dom_ Z /\\ tForall_54_ W)) -> tAnd_52_ Y Z W)).\nVariable ax17_25 : (forall Y Z W : Universe, (tAnd_52_ Y Z W -> (tOr_46_ Y Z W /\\ tOr_50_ Y Z W))).\nVariable ax18_26 : (forall Y Z W : Universe, ((tOr_46_ Y Z W /\\ (tPROGRAM_ Y /\\ tHALTS2_ Y Z)) -> (tAnd_44_ Y Z W /\\ tHALTS3_ W Y Z))).\nVariable ax19_27 : (forall Y W V : Universe, ((dom_ Y /\\ tForall_76_ W V) -> tAnd_74_ W Y V)).\nVariable ax20_28 : (forall W Y V : Universe, (tAnd_74_ W Y V -> tOr_72_ W Y V)).\nVariable ax21_29 : (forall Y Z W : Universe, ((tOr_50_ Y Z W /\\ tPROGRAM_ Y) -> (tHALTS2_ Y Z \\/ (tAnd_48_ Y Z W /\\ tHALTS3_ W Y Z)))).\nVariable ax22_30 : (forall Y Z W : Universe, (tOr_65_ Y Z W -> ((tAnd_59_ Y Z W /\\ (tPROGRAM_ Y /\\ tHALTS2_ Y Z)) \\/ (tAnd_63_ Y Z W /\\ tPROGRAM_ Y)))).\nVariable ax23_31 : (forall W Y Z : Universe, (tHALTS3_ W Y Z -> (fOr_58_ Y Z W \\/ fOUTPUTS_ W good_))).\nVariable ax24_32 : (forall W Y Z : Universe, (tHALTS3_ W Y Z -> (fOr_62_ Y Z W \\/ fOUTPUTS_ W bad_))).\nVariable ax25_33 : (forall Y W V : Universe, ((tPROGRAM_ Y /\\ (tHALTS3_ W Y Y /\\ tHALTS2_ V Y)) -> (fOr_69_ W V Y \\/ fOUTPUTS_ W good_))).\nVariable ax26_34 : (forall W Y V : Universe, ((tOr_72_ W Y V /\\ (tPROGRAM_ Y /\\ tHALTS3_ W Y Y)) -> (fOUTPUTS_ W bad_ \\/ (tAnd_70_ Y V /\\ tHALTS2_ V Y)))).\nVariable ax28_35 : (forall X Y : Universe, (tExists_22_ X Y -> (exists Z : Universe, (dom_ Z /\\ fDECIDES_ X Y Z)))).\nVariable ax29_36 : (forall W Y : Universe, (tExists_40_ W Y -> (exists Z : Universe, (dom_ Z /\\ fDECIDES_ W Y Z)))).\nVariable ax30_37 : (True -> ((exists W : Universe, tForall_28_) \\/ (dom_ W /\\ (tAnd_36_ W /\\ tPROGRAM_ W)))).\nVariable ax31_38 : (forall X : Universe, (tOr_26_ X -> (exists Y : Universe, (fALGORITHM_ X \\/ (dom_ Y /\\ (tPROGRAM_ Y /\\ tExists_22_ X Y)))))).\nVariable ax32_39 : (forall W : Universe, (tPROGRAM_ W -> ((exists Y : Universe, (dom_ Y /\\ (tPROGRAM_ Y /\\ tExists_40_ W Y))) \\/ tForall_54_ W))).\nVariable ax33_40 : (forall W : Universe, (tPROGRAM_ W -> ((exists Y Z V : Universe, (dom_ Y /\\ (dom_ Z /\\ tOr_65_ Y Z W))) \\/ (dom_ V /\\ (tPROGRAM_ V /\\ tForall_76_ W V))))).\n\nTheorem hpbf2_41 : goal_.\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/coherent-logic-benches/hp_bf_2_in.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.29037579146964887}}
{"text": "(* -*- mode: coq; coq-prog-args: (\"-nois\" \"-indices-matter\" \"-R\" \".\" \"Top\" \"-top\" \"bug_oog_looping_rewrite_01\") -*- *)\n(* File reduced by coq-bug-finder from original input, then from 2553 lines to 1932 lines, then from 1946 lines to 1932 lines, then from 2467 lines to 1002 lines, then from 1016 lines to 1002 lines *)\n(* coqc version 8.5 (January 2016) compiled on Jan 23 2016 16:15:22 with OCaml 4.01.0\n   coqtop version 8.5 (January 2016) *)\nDeclare ML Module \"ltac_plugin\".\nInductive False := .\nAxiom proof_admitted : False.\nTactic Notation \"admit\" := case proof_admitted.\nRequire Coq.Init.Datatypes.\n\nImport Coq.Init.Notations.\n\nGlobal Set Universe Polymorphism.\n\nNotation \"A -> B\" := (forall (_ : A), B) : type_scope.\nGlobal Set Primitive Projections.\n\nInductive sum (A B : Type) : Type :=\n  | inl : A -> sum A B\n  | inr : B -> sum A B.\nNotation nat := Coq.Init.Datatypes.nat.\nNotation O := Coq.Init.Datatypes.O.\nNotation S := Coq.Init.Datatypes.S.\nNotation \"x + y\" := (sum x y) : type_scope.\n\nRecord prod (A B : Type) := pair { fst : A ; snd : B }.\n\nNotation \"x * y\" := (prod x y) : type_scope.\nModule Export Specif.\n\nSet Implicit Arguments.\n\nRecord sig {A} (P : A -> Type) := exist { proj1_sig : A ; proj2_sig : P proj1_sig }.\nArguments proj1_sig {A P} _ / .\n\nNotation sigT := sig (only parsing).\nNotation existT := exist (only parsing).\n\nNotation \"{ x : A  & P }\" := (sigT (fun x:A => P)) : type_scope.\n\nNotation projT1 := proj1_sig (only parsing).\nNotation projT2 := proj2_sig (only parsing).\n\nEnd Specif.\nModule Export HoTT_DOT_Basics_DOT_Overture.\nModule Export HoTT.\nModule Export Basics.\nModule Export Overture.\n\nGlobal Set Keyed Unification.\n\nGlobal Unset Strict Universe Declaration.\n\nNotation Type0 := Set.\n\nDefinition Type1@{i} := Eval hnf in let gt := (Set : Type@{i}) in Type@{i}.\n\nDefinition Type2@{i j} := Eval hnf in let gt := (Type1@{j} : Type@{i}) in Type@{i}.\n\nDefinition Type2le@{i j} := Eval hnf in let gt := (Set : Type@{i}) in\n                                        let ge := ((fun x => x) : Type1@{j} -> Type@{i}) in Type@{i}.\n\nNotation idmap := (fun x => x).\nDelimit Scope function_scope with function.\nDelimit Scope path_scope with path.\nDelimit Scope fibration_scope with fibration.\nDelimit Scope trunc_scope with trunc.\n\nOpen Scope trunc_scope.\nOpen Scope path_scope.\nOpen Scope fibration_scope.\nOpen Scope nat_scope.\nOpen Scope function_scope.\n\nNotation \"( x ; y )\" := (existT _ x y) : fibration_scope.\n\nNotation pr1 := projT1.\nNotation pr2 := projT2.\n\nNotation \"x .1\" := (pr1 x) (at level 3, format \"x '.1'\") : fibration_scope.\nNotation \"x .2\" := (pr2 x) (at level 3, format \"x '.2'\") : fibration_scope.\n\nNotation compose := (fun g f x => g (f x)).\n\nNotation \"g 'o' f\" := (compose g%function f%function) (at level 40, left associativity) : function_scope.\n\nInductive paths {A : Type} (a : A) : A -> Type :=\n  idpath : paths a a.\n\nArguments idpath {A a} , [A] a.\n\nNotation \"x = y :> A\" := (@paths A x y) : type_scope.\nNotation \"x = y\" := (x = y :>_) : type_scope.\n\nDefinition inverse {A : Type} {x y : A} (p : x = y) : y = x\n  := match p with idpath => idpath end.\n\nDefinition concat {A : Type} {x y z : A} (p : x = y) (q : y = z) : x = z :=\n  match p, q with idpath, idpath => idpath end.\n\nNotation \"1\" := idpath : path_scope.\n\nNotation \"p @ q\" := (concat p%path q%path) (at level 20) : path_scope.\n\nNotation \"p ^\" := (inverse p%path) (at level 3, format \"p '^'\") : path_scope.\n\nDefinition transport {A : Type} (P : A -> Type) {x y : A} (p : x = y) (u : P x) : P y :=\n  match p with idpath => u end.\n\nNotation \"p # x\" := (transport _ p x) (right associativity, at level 65, only parsing) : path_scope.\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\nDefinition pointwise_paths {A} {P:A->Type} (f g:forall x:A, P x)\n  := forall x:A, f x = g x.\n\nNotation \"f == g\" := (pointwise_paths f g) (at level 70, no associativity) : type_scope.\n\nDefinition Sect {A B : Type} (s : A -> B) (r : B -> A) :=\n  forall x : A, r (s x) = x.\n\nClass IsEquiv {A B : Type} (f : A -> B) := BuildIsEquiv {\n  equiv_inv : B -> A ;\n  eisretr : Sect equiv_inv f;\n  eissect : Sect f equiv_inv;\n  eisadj : forall x : A, eisretr (f x) = ap f (eissect x)\n}.\n\nArguments eisretr {A B}%type_scope f%function_scope {_} _.\n\nRecord Equiv A B := BuildEquiv {\n  equiv_fun : A -> B ;\n  equiv_isequiv : IsEquiv equiv_fun\n}.\n\nCoercion equiv_fun : Equiv >-> Funclass.\n\nGlobal Existing Instance equiv_isequiv.\n\nNotation \"A <~> B\" := (Equiv A B) (at level 85) : type_scope.\n\nNotation \"f ^-1\" := (@equiv_inv _ _ f _) (at level 3, format \"f '^-1'\") : function_scope.\n\nClass Contr_internal (A : Type) := BuildContr {\n  center : A ;\n  contr : (forall y : A, center = y)\n}.\n\nArguments center A {_}.\n\nInductive trunc_index : Type :=\n| minus_two : trunc_index\n| trunc_S : trunc_index -> trunc_index.\n\nNotation \"n .+1\" := (trunc_S n) (at level 2, left associativity, format \"n .+1\") : trunc_scope.\nNotation \"-2\" := minus_two (at level 0) : trunc_scope.\nNotation \"-1\" := (-2.+1) (at level 0) : trunc_scope.\nNotation \"0\" := (-1.+1) : trunc_scope.\n\nFixpoint IsTrunc_internal (n : trunc_index) (A : Type) : Type :=\n  match n with\n    | -2 => Contr_internal A\n    | n'.+1 => forall (x y : A), IsTrunc_internal n' (x = y)\n  end.\n\nClass IsTrunc (n : trunc_index) (A : Type) : Type :=\n  Trunc_is_trunc : IsTrunc_internal n A.\n\nGlobal Instance istrunc_paths (A : Type) n `{H : IsTrunc n.+1 A} (x y : A)\n: IsTrunc n (x = y)\n  := H x y.\n\nNotation Contr := (IsTrunc -2).\nNotation IsHProp := (IsTrunc -1).\n\nHint Extern 0 => progress change Contr_internal with Contr in * : typeclass_instances.\n\nMonomorphic Axiom dummy_funext_type : Type0.\nMonomorphic Class Funext := { dummy_funext_value : dummy_funext_type }.\n\nInductive Unit : Type1 :=\n    tt : Unit.\n\nClass IsPointed (A : Type) := point : A.\n\nArguments point A {_}.\n\nRecord pType :=\n  { pointed_type : Type ;\n    ispointed_type : IsPointed pointed_type }.\n\nCoercion pointed_type : pType >-> Sortclass.\n\nGlobal Existing Instance ispointed_type.\n\nDefinition hfiber {A B : Type} (f : A -> B) (y : B) := { x : A & f x = y }.\n\nLtac revert_opaque x :=\n  revert x;\n  match goal with\n    | [ |- forall _, _ ] => idtac\n    | _ => fail 1 \"Reverted constant is not an opaque variable\"\n  end.\n\nEnd Overture.\n\nEnd Basics.\n\nEnd HoTT.\n\nEnd HoTT_DOT_Basics_DOT_Overture.\nModule Export HoTT_DOT_Basics_DOT_PathGroupoids.\nModule Export HoTT.\nModule Export Basics.\nModule Export PathGroupoids.\n\nLocal Open Scope path_scope.\n\nDefinition concat_p1 {A : Type} {x y : A} (p : x = y) :\n  p @ 1 = p\n  :=\n  match p with idpath => 1 end.\n\nDefinition concat_1p {A : Type} {x y : A} (p : x = y) :\n  1 @ p = p\n  :=\n  match p with idpath => 1 end.\n\nDefinition concat_p_pp {A : Type} {x y z t : A} (p : x = y) (q : y = z) (r : z = t) :\n  p @ (q @ r) = (p @ q) @ r :=\n  match r with idpath =>\n    match q with idpath =>\n      match p with idpath => 1\n      end end end.\n\nDefinition concat_pp_p {A : Type} {x y z t : A} (p : x = y) (q : y = z) (r : z = t) :\n  (p @ q) @ r = p @ (q @ r) :=\n  match r with idpath =>\n    match q with idpath =>\n      match p with idpath => 1\n      end end end.\n\nDefinition concat_pV {A : Type} {x y : A} (p : x = y) :\n  p @ p^ = 1\n  :=\n  match p with idpath => 1 end.\n\nDefinition moveR_Vp {A : Type} {x y z : A} (p : x = z) (q : y = z) (r : x = y) :\n  p = r @ q -> r^ @ p = q.\nadmit.\nDefined.\n\nDefinition moveL_Vp {A : Type} {x y z : A} (p : x = z) (q : y = z) (r : x = y) :\n  r @ q = p -> q = r^ @ p.\nadmit.\nDefined.\n\nDefinition moveR_M1 {A : Type} {x y : A} (p q : x = y) :\n  1 = p^ @ q -> p = q.\nadmit.\nDefined.\n\nDefinition ap_pp {A B : Type} (f : A -> B) {x y z : A} (p : x = y) (q : y = z) :\n  ap f (p @ q) = (ap f p) @ (ap f q)\n  :=\n  match q with\n    idpath =>\n    match p with idpath => 1 end\n  end.\n\nDefinition ap_V {A B : Type} (f : A -> B) {x y : A} (p : x = y) :\n  ap f (p^) = (ap f p)^\n  :=\n  match p with idpath => 1 end.\n\nDefinition ap_compose {A B C : Type} (f : A -> B) (g : B -> C) {x y : A} (p : x = y) :\n  ap (g o f) p = ap g (ap f p)\n  :=\n  match p with idpath => 1 end.\n\nDefinition concat_pA1 {A : Type} {f : A -> A} (p : forall x, x = f x) {x y : A} (q : x = y) :\n  (p x) @ (ap f q) =  q @ (p y)\n  :=\n  match q as i in (_ = y) return (p x @ ap f i = i @ p y) with\n    | idpath => concat_p1 _ @ (concat_1p _)^\n  end.\n\nEnd PathGroupoids.\n\nEnd Basics.\n\nEnd HoTT.\n\nEnd HoTT_DOT_Basics_DOT_PathGroupoids.\nModule Export HoTT_DOT_Basics_DOT_Equivalences.\nModule Export HoTT.\nModule Export Basics.\nModule Export Equivalences.\n\nDefinition isequiv_commsq {A B C D}\n           (f : A -> B) (g : C -> D) (h : A -> C) (k : B -> D)\n           (p : k o f == g o h)\n           `{IsEquiv _ _ f} `{IsEquiv _ _ h} `{IsEquiv _ _ k}\n: IsEquiv g.\nadmit.\nDefined.\n\nSection Adjointify.\n\n  Context {A B : Type} (f : A -> B) (g : B -> A).\n  Context (isretr : Sect g f) (issect : Sect f g).\n\n  Let issect' := fun x =>\n    ap g (ap f (issect x)^)  @  ap g (isretr (f x))  @  issect x.\n\n  Let is_adjoint' (a : A) : isretr (f a) = ap f (issect' a).\n  Proof.\n    unfold issect'.\n    apply moveR_M1.\n    repeat rewrite ap_pp, concat_p_pp; rewrite <- ap_compose.\n    rewrite (concat_pA1 (fun b => (isretr b)^) (ap f (issect a)^)).\n    repeat rewrite concat_pp_p; rewrite ap_V; apply moveL_Vp; rewrite concat_p1.\n    rewrite concat_p_pp, <- ap_compose.\n    rewrite (concat_pA1 (fun b => (isretr b)^) (isretr (f a))).\n    rewrite concat_pV, concat_1p; reflexivity.\n  Qed.\n\n  Definition isequiv_adjointify : IsEquiv f\n    := BuildIsEquiv A B f g isretr issect' is_adjoint'.\n\nEnd Adjointify.\n\nEnd Equivalences.\n\nEnd Basics.\n\nEnd HoTT.\n\nEnd HoTT_DOT_Basics_DOT_Equivalences.\nModule Export HoTT_DOT_Basics_DOT_Trunc.\nModule Export HoTT.\nModule Export Basics.\nModule Export Trunc.\nGeneralizable Variables A B m n f.\n\nDefinition trunc_equiv A {B} (f : A -> B)\n  `{IsTrunc n A} `{IsEquiv A B f}\n  : IsTrunc n B.\nadmit.\nDefined.\n\nRecord TruncType (n : trunc_index) := BuildTruncType {\n  trunctype_type : Type ;\n  istrunc_trunctype_type : IsTrunc n trunctype_type\n}.\n\nArguments BuildTruncType _ _ {_}.\n\nCoercion trunctype_type : TruncType >-> Sortclass.\n\nNotation \"n -Type\" := (TruncType n) (at level 1) : type_scope.\nNotation hProp := (-1)-Type.\n\nNotation BuildhProp := (BuildTruncType -1).\n\nEnd Trunc.\n\nEnd Basics.\n\nEnd HoTT.\n\nEnd HoTT_DOT_Basics_DOT_Trunc.\nModule Export HoTT_DOT_Types_DOT_Unit.\nModule Export HoTT.\nModule Export Types.\nModule Export Unit.\n\nNotation unit_name x := (fun (_ : Unit) => x).\n\nEnd Unit.\n\nEnd Types.\n\nEnd HoTT.\n\nEnd HoTT_DOT_Types_DOT_Unit.\nModule Export HoTT_DOT_Types_DOT_Sigma.\nModule Export HoTT.\nModule Export Types.\nModule Export Sigma.\nLocal Open Scope path_scope.\n\nDefinition path_sigma_uncurried {A : Type} (P : A -> Type) (u v : sigT P)\n           (pq : {p : u.1 = v.1 & p # u.2 = v.2})\n: u = v\n  := match pq.2 in (_ = v2) return u = (v.1; v2) with\n       | 1 => match pq.1 as p in (_ = v1) return u = (v1; p # u.2) with\n                | 1 => 1\n              end\n     end.\n\nDefinition path_sigma {A : Type} (P : A -> Type) (u v : sigT P)\n           (p : u.1 = v.1) (q : p # u.2 = v.2)\n: u = v\n  := path_sigma_uncurried P u v (p;q).\n\nDefinition path_sigma' {A : Type} (P : A -> Type) {x x' : A} {y : P x} {y' : P x'}\n           (p : x = x') (q : p # y = y')\n: (x;y) = (x';y')\n  := path_sigma P (x;y) (x';y') p q.\n\nGlobal Instance isequiv_pr1_contr {A} {P : A -> Type}\n         `{forall a, Contr (P a)}\n: IsEquiv (@pr1 A P) | 100.\nProof.\n  refine (isequiv_adjointify (@pr1 A P)\n                             (fun a => (a ; center (P a))) _ _).\n  -\n intros a; reflexivity.\n  -\n intros [a p].\n    refine (path_sigma' P 1 (contr _)).\nDefined.\n\nDefinition path_sigma_hprop {A : Type} {P : A -> Type}\n           `{forall x, IsHProp (P x)}\n           (u v : sigT P)\n: u.1 = v.1 -> u = v\n  := path_sigma_uncurried P u v o pr1^-1.\n\nEnd Sigma.\n\nEnd Types.\n\nEnd HoTT.\n\nEnd HoTT_DOT_Types_DOT_Sigma.\nModule Export HoTT_DOT_Extensions.\nModule Export HoTT.\nModule Export Extensions.\n\nSection Extensions.\n\n  Definition ExtensionAlong {A B : Type} (f : A -> B)\n             (P : B -> Type) (d : forall x:A, P (f x))\n    := { s : forall y:B, P y & forall x:A, s (f x) = d x }.\n\n  Fixpoint ExtendableAlong@{i j k l}\n           (n : nat) {A : Type@{i}} {B : Type@{j}}\n           (f : A -> B) (C : B -> Type@{k}) : Type@{l}\n    := match n with\n         | O => Unit@{l}\n         | S n => (forall (g : forall a, C (f a)),\n                     ExtensionAlong@{i j k l l} f C g) *\n                  forall (h k : forall b, C b),\n                    ExtendableAlong n f (fun b => h b = k b)\n       end.\n\n  Definition ooExtendableAlong@{i j k l}\n             {A : Type@{i}} {B : Type@{j}}\n             (f : A -> B) (C : B -> Type@{k}) : Type@{l}\n    := forall n, ExtendableAlong@{i j k l} n f C.\n\nEnd Extensions.\n\nEnd Extensions.\n\nEnd HoTT.\n\nEnd HoTT_DOT_Extensions.\nModule Export HoTT.\nModule Export Modalities.\nModule Export ReflectiveSubuniverse.\n\nModule Type ReflectiveSubuniverses.\n\n  Parameter ReflectiveSubuniverse@{u a} : Type2@{u a}.\n\n  Parameter O_reflector@{u a i} : forall (O : ReflectiveSubuniverse@{u a}),\n                            Type2le@{i a} -> Type2le@{i a}.\n\n  Parameter In@{u a i} : forall (O : ReflectiveSubuniverse@{u a}),\n                   Type2le@{i a} -> Type2le@{i a}.\n\n  Parameter O_inO@{u a i} : forall (O : ReflectiveSubuniverse@{u a}) (T : Type@{i}),\n                               In@{u a i} O (O_reflector@{u a i} O T).\n\n  Parameter to@{u a i} : forall (O : ReflectiveSubuniverse@{u a}) (T : Type@{i}),\n                   T -> O_reflector@{u a i} O T.\n\n  Parameter inO_equiv_inO@{u a i j k} :\n      forall (O : ReflectiveSubuniverse@{u a}) (T : Type@{i}) (U : Type@{j})\n             (T_inO : In@{u a i} O T) (f : T -> U) (feq : IsEquiv f),\n\n        let gei := ((fun x => x) : Type@{i} -> Type@{k}) in\n        let gej := ((fun x => x) : Type@{j} -> Type@{k}) in\n        In@{u a j} O U.\n\n  Parameter hprop_inO@{u a i}\n  : Funext -> forall (O : ReflectiveSubuniverse@{u a}) (T : Type@{i}),\n                IsHProp (In@{u a i} O T).\n\n  Parameter extendable_to_O@{u a i j k}\n  : forall (O : ReflectiveSubuniverse@{u a}) {P : Type2le@{i a}} {Q : Type2le@{j a}} {Q_inO : In@{u a j} O Q},\n      ooExtendableAlong@{i i j k} (to O P) (fun _ => Q).\n\nEnd ReflectiveSubuniverses.\n\nModule ReflectiveSubuniverses_Theory (Os : ReflectiveSubuniverses).\nExport Os.\n\nModule Export Coercions.\n\n  Coercion O_reflector : ReflectiveSubuniverse >-> Funclass.\n\nEnd Coercions.\n\nEnd ReflectiveSubuniverses_Theory.\n\nModule Type ReflectiveSubuniverses_Restriction_Data (Os : ReflectiveSubuniverses).\n\n  Parameter New_ReflectiveSubuniverse@{u a} : Type2@{u a}.\n\n  Parameter ReflectiveSubuniverses_restriction@{u a}\n  : New_ReflectiveSubuniverse@{u a} -> Os.ReflectiveSubuniverse@{u a}.\n\nEnd ReflectiveSubuniverses_Restriction_Data.\n\nModule ReflectiveSubuniverses_Restriction\n       (Os : ReflectiveSubuniverses)\n       (Res : ReflectiveSubuniverses_Restriction_Data Os)\n<: ReflectiveSubuniverses.\n\n  Definition ReflectiveSubuniverse := Res.New_ReflectiveSubuniverse.\n\n  Definition O_reflector@{u a i} (O : ReflectiveSubuniverse@{u a})\n    := Os.O_reflector@{u a i} (Res.ReflectiveSubuniverses_restriction O).\n  Definition In@{u a i} (O : ReflectiveSubuniverse@{u a})\n    := Os.In@{u a i} (Res.ReflectiveSubuniverses_restriction O).\n  Definition O_inO@{u a i} (O : ReflectiveSubuniverse@{u a})\n    := Os.O_inO@{u a i} (Res.ReflectiveSubuniverses_restriction O).\n  Definition to@{u a i} (O : ReflectiveSubuniverse@{u a})\n    := Os.to@{u a i} (Res.ReflectiveSubuniverses_restriction O).\n  Definition inO_equiv_inO@{u a i j k} (O : ReflectiveSubuniverse@{u a})\n    := Os.inO_equiv_inO@{u a i j k} (Res.ReflectiveSubuniverses_restriction O).\n  Definition hprop_inO@{u a i} (H : Funext) (O : ReflectiveSubuniverse@{u a})\n    := Os.hprop_inO@{u a i} H (Res.ReflectiveSubuniverses_restriction O).\n  Definition extendable_to_O@{u a i j k} (O : ReflectiveSubuniverse@{u a})\n    := @Os.extendable_to_O@{u a i j k} (Res.ReflectiveSubuniverses_restriction@{u a} O).\n\nEnd ReflectiveSubuniverses_Restriction.\n\nModule ReflectiveSubuniverses_FamUnion\n       (Os1 Os2 : ReflectiveSubuniverses)\n<: ReflectiveSubuniverses.\n\n  Definition ReflectiveSubuniverse@{u a} : Type2@{u a}\n    := Os1.ReflectiveSubuniverse@{u a} + Os2.ReflectiveSubuniverse@{u a}.\n\n  Definition O_reflector@{u a i} : forall (O : ReflectiveSubuniverse@{u a}),\n                             Type2le@{i a} -> Type2le@{i a}.\nadmit.\nDefined.\n\n  Definition In@{u a i} : forall (O : ReflectiveSubuniverse@{u a}),\n                             Type2le@{i a} -> Type2le@{i a}.\n  Proof.\n    intros [O|O]; [ exact (Os1.In@{u a i} O)\n                  | exact (Os2.In@{u a i} O) ].\n  Defined.\n\n  Definition O_inO@{u a i}\n  : forall (O : ReflectiveSubuniverse@{u a}) (T : Type@{i}),\n      In@{u a i} O (O_reflector@{u a i} O T).\nadmit.\nDefined.\n\n  Definition to@{u a i} : forall (O : ReflectiveSubuniverse@{u a}) (T : Type@{i}),\n                   T -> O_reflector@{u a i} O T.\nadmit.\nDefined.\n\n  Definition inO_equiv_inO@{u a i j k} :\n      forall (O : ReflectiveSubuniverse@{u a}) (T : Type@{i}) (U : Type@{j})\n             (T_inO : In@{u a i} O T) (f : T -> U) (feq : IsEquiv f),\n        In@{u a j} O U.\n  Proof.\n    intros [O|O]; [ exact (Os1.inO_equiv_inO@{u a i j k} O)\n                  | exact (Os2.inO_equiv_inO@{u a i j k} O) ].\n  Defined.\n\n  Definition hprop_inO@{u a i}\n  : Funext -> forall (O : ReflectiveSubuniverse@{u a}) (T : Type@{i}),\n                IsHProp (In@{u a i} O T).\nadmit.\nDefined.\n\n  Definition extendable_to_O@{u a i j k}\n  : forall (O : ReflectiveSubuniverse@{u a}) {P : Type2le@{i a}} {Q : Type2le@{j a}} {Q_inO : In@{u a j} O Q},\n      ooExtendableAlong@{i i j k} (to O P) (fun _ => Q).\nadmit.\nDefined.\n\nEnd ReflectiveSubuniverses_FamUnion.\n\nEnd ReflectiveSubuniverse.\n\nEnd Modalities.\n\nEnd HoTT.\n\nModule Type Modalities.\n\n  Parameter Modality@{u a} : Type2@{u a}.\n\n  Parameter O_reflector@{u a i} : forall (O : Modality@{u a}),\n                            Type2le@{i a} -> Type2le@{i a}.\n\n  Parameter In@{u a i} : forall (O : Modality@{u a}),\n                            Type2le@{i a} -> Type2le@{i a}.\n\n  Parameter O_inO@{u a i} : forall (O : Modality@{u a}) (T : Type@{i}),\n                               In@{u a i} O (O_reflector@{u a i} O T).\n\n  Parameter to@{u a i} : forall (O : Modality@{u a}) (T : Type@{i}),\n                   T -> O_reflector@{u a i} O T.\n\n  Parameter inO_equiv_inO@{u a i j k} :\n      forall (O : Modality@{u a}) (T : Type@{i}) (U : Type@{j})\n             (T_inO : In@{u a i} O T) (f : T -> U) (feq : IsEquiv f),\n\n        let gei := ((fun x => x) : Type@{i} -> Type@{k}) in\n        let gej := ((fun x => x) : Type@{j} -> Type@{k}) in\n        In@{u a j} O U.\n\n  Parameter hprop_inO@{u a i}\n  : Funext -> forall (O : Modality@{u a}) (T : Type@{i}),\n                IsHProp (In@{u a i} O T).\n\nEnd Modalities.\n\nModule Modalities_to_ReflectiveSubuniverses\n       (Os : Modalities) <: ReflectiveSubuniverses.\n\n  Import Os.\n\n  Fixpoint O_extendable@{u a i j k} (O : Modality@{u a})\n           (A : Type@{i}) (B : O_reflector O A -> Type@{j})\n           (B_inO : forall a, In@{u a j} O (B a)) (n : nat)\n  : ExtendableAlong@{i i j k} n (to O A) B.\nadmit.\nDefined.\n\n  Definition ReflectiveSubuniverse := Modality.\n\n  Definition O_reflector@{u a i} := O_reflector@{u a i}.\n\n  Definition In@{u a i} : forall (O : ReflectiveSubuniverse@{u a}),\n                   Type2le@{i a} -> Type2le@{i a}\n    := In@{u a i}.\n  Definition O_inO@{u a i} : forall (O : ReflectiveSubuniverse@{u a}) (T : Type@{i}),\n                               In@{u a i} O (O_reflector@{u a i} O T)\n    := O_inO@{u a i}.\n  Definition to@{u a i} := to@{u a i}.\n  Definition inO_equiv_inO@{u a i j k} :\n      forall (O : ReflectiveSubuniverse@{u a}) (T : Type@{i}) (U : Type@{j})\n             (T_inO : In@{u a i} O T) (f : T -> U) (feq : IsEquiv f),\n        In@{u a j} O U\n    := inO_equiv_inO@{u a i j k}.\n  Definition hprop_inO@{u a i}\n  : Funext -> forall (O : ReflectiveSubuniverse@{u a}) (T : Type@{i}),\n                IsHProp (In@{u a i} O T)\n    := hprop_inO@{u a i}.\n\n  Definition extendable_to_O@{u a i j k} (O : ReflectiveSubuniverse@{u a})\n             {P : Type2le@{i a}} {Q : Type2le@{j a}} {Q_inO : In@{u a j} O Q}\n  : ooExtendableAlong@{i i j k} (to O P) (fun _ => Q)\n    := fun n => O_extendable O P (fun _ => Q) (fun _ => Q_inO) n.\n\nEnd Modalities_to_ReflectiveSubuniverses.\n\nModule Type EasyModalities.\n\n  Parameter Modality@{u a} : Type2@{u a}.\n\n  Parameter O_reflector@{u a i} : forall (O : Modality@{u a}),\n                            Type2le@{i a} -> Type2le@{i a}.\n\n  Parameter to@{u a i} : forall (O : Modality@{u a}) (T : Type@{i}),\n                   T -> O_reflector@{u a i} O T.\n\n  Parameter minO_pathsO@{u a i}\n  : forall (O : Modality@{u a}) (A : Type@{i})\n           (z z' : O_reflector@{u a i} O A),\n      IsEquiv (to@{u a i} O (z = z')).\n\nEnd EasyModalities.\n\nModule EasyModalities_to_Modalities (Os : EasyModalities)\n<: Modalities.\n\n  Import Os.\n\n  Definition Modality := Modality.\n\n  Definition O_reflector@{u a i} := O_reflector@{u a i}.\n  Definition to@{u a i} := to@{u a i}.\n\n  Definition In@{u a i}\n  : forall (O : Modality@{u a}), Type@{i} -> Type@{i}\n  := fun O A => IsEquiv@{i i} (to O A).\n\n  Definition hprop_inO@{u a i} `{Funext} (O : Modality@{u a})\n             (T : Type@{i})\n  : IsHProp (In@{u a i} O T).\nadmit.\nDefined.\n\n  Definition O_ind_internal@{u a i j k} (O : Modality@{u a})\n             (A : Type@{i}) (B : O_reflector@{u a i} O A -> Type@{j})\n             (B_inO : forall oa, In@{u a j} O (B oa))\n  : let gei := ((fun x => x) : Type@{i} -> Type@{k}) in\n    let gej := ((fun x => x) : Type@{j} -> Type@{k}) in\n    (forall a, B (to O A a)) -> forall oa, B oa.\nadmit.\nDefined.\n\n  Definition O_ind_beta_internal@{u a i j k} (O : Modality@{u a})\n             (A : Type@{i}) (B : O_reflector@{u a i} O A -> Type@{j})\n             (B_inO : forall oa, In@{u a j} O (B oa))\n             (f : forall a : A, B (to O A a)) (a:A)\n  : O_ind_internal@{u a i j k} O A B B_inO f (to O A a) = f a.\nadmit.\nDefined.\n\n  Definition O_inO@{u a i} (O : Modality@{u a}) (A : Type@{i})\n  : In@{u a i} O (O_reflector@{u a i} O A).\nadmit.\nDefined.\n\n  Definition inO_equiv_inO@{u a i j k} (O : Modality@{u a}) (A : Type@{i}) (B : Type@{j})\n    (A_inO : In@{u a i} O A) (f : A -> B) (feq : IsEquiv f)\n  : In@{u a j} O B.\n  Proof.\n    simple refine (isequiv_commsq (to O A) (to O B) f\n             (O_ind_internal O A (fun _ => O_reflector O B) _ (fun a => to O B (f a))) _).\n    -\n intros; apply O_inO.\n    -\n intros a; refine (O_ind_beta_internal@{u a i j k} O A (fun _ => O_reflector O B) _ _ a).\n    -\n apply A_inO.\n    -\n simple refine (isequiv_adjointify _\n               (O_ind_internal O B (fun _ => O_reflector O A) _ (fun b => to O A (f^-1 b))) _ _);\n        intros x.\n      +\n apply O_inO.\n      +\n pattern x; refine (O_ind_internal O B _ _ _ x); intros.\n        *\n apply minO_pathsO.\n        *\n simpl; admit.\n      +\n pattern x; refine (O_ind_internal O A _ _ _ x); intros.\n        *\n apply minO_pathsO.\n        *\n simpl; admit.\n  Defined.\n\nEnd EasyModalities_to_Modalities.\n\nModule Modalities_Theory (Os : Modalities).\n\nExport Os.\nModule Export Os_ReflectiveSubuniverses\n  := Modalities_to_ReflectiveSubuniverses Os.\nModule Export RSU\n  := ReflectiveSubuniverses_Theory Os_ReflectiveSubuniverses.\n\nModule Export Coercions.\n  Coercion modality_to_reflective_subuniverse\n    := idmap : Modality -> ReflectiveSubuniverse.\nEnd Coercions.\n\nClass IsConnected (O : Modality@{u a}) (A : Type@{i})\n\n  := isconnected_contr_O : IsTrunc@{i} -2 (O A).\n\nClass IsConnMap (O : Modality@{u a})\n      {A : Type@{i}} {B : Type@{j}} (f : A -> B)\n  := isconnected_hfiber_conn_map\n\n     : forall b:B, IsConnected@{u a k} O (hfiber@{i j} f b).\n\nEnd Modalities_Theory.\n\nPrivate Inductive Trunc (n : trunc_index) (A :Type) : Type :=\n  tr : A -> Trunc n A.\nArguments tr {n A} a.\n\nGlobal Instance istrunc_truncation (n : trunc_index) (A : Type@{i})\n: IsTrunc@{j} n (Trunc@{i} n A).\nAdmitted.\n\nDefinition Trunc_ind {n A}\n  (P : Trunc n A -> Type) {Pt : forall aa, IsTrunc n (P aa)}\n  : (forall a, P (tr a)) -> (forall aa, P aa)\n:= (fun f aa => match aa with tr a => fun _ => f a end Pt).\n\nDefinition Truncation_Modality := trunc_index.\n\nModule Truncation_Modalities <: Modalities.\n\n  Definition Modality : Type2@{u a} := Truncation_Modality.\n\n  Definition O_reflector (n : Modality@{u u'}) A := Trunc n A.\n\n  Definition In (n : Modality@{u u'}) A := IsTrunc n A.\n\n  Definition O_inO (n : Modality@{u u'}) A : In n (O_reflector n A).\nadmit.\nDefined.\n\n  Definition to (n : Modality@{u u'}) A := @tr n A.\n\n  Definition inO_equiv_inO (n : Modality@{u u'})\n             (A : Type@{i}) (B : Type@{j}) Atr f feq\n  : let gei := ((fun x => x) : Type@{i} -> Type@{k}) in\n    let gej := ((fun x => x) : Type@{j} -> Type@{k}) in\n    In n B\n  := @trunc_equiv A B f n Atr feq.\n\n  Definition hprop_inO `{Funext} (n : Modality@{u u'}) A\n  : IsHProp (In n A).\nadmit.\nDefined.\n\nEnd Truncation_Modalities.\n\nModule Import TrM := Modalities_Theory Truncation_Modalities.\n\nDefinition merely (A : Type@{i}) : hProp := BuildhProp (Trunc -1 A).\n\nNotation IsSurjection := (IsConnMap -1).\n\nDefinition BuildIsSurjection {A B} (f : A -> B) :\n  (forall b, merely (hfiber f b)) -> IsSurjection f.\nadmit.\nDefined.\n\nLtac strip_truncations :=\n\n  progress repeat match goal with\n                    | [ T : _ |- _ ]\n                      => revert_opaque T;\n                        refine (@Trunc_ind _ _ _ _ _);\n\n                        [];\n                        intro T\n                  end.\nLocal Open Scope trunc_scope.\n\nGlobal Instance conn_pointed_type {n : trunc_index} {A : Type} (a0:A)\n `{IsConnMap n _ _ (unit_name a0)} : IsConnected n.+1 A | 1000.\nadmit.\nDefined.\n\nDefinition loops (A : pType) : pType :=\n  Build_pType (point A = point A) idpath.\n\nRecord pMap (A B : pType) :=\n  { pointed_fun : A -> B ;\n    point_eq : pointed_fun (point A) = point B }.\n\nArguments point_eq {A B} f : rename.\nCoercion pointed_fun : pMap >-> Funclass.\n\nInfix \"->*\" := pMap (at level 99) : pointed_scope.\nLocal Open Scope pointed_scope.\n\nDefinition pmap_compose {A B C : pType}\n           (g : B ->* C) (f : A ->* B)\n: A ->* C\n  := Build_pMap A C (g o f)\n                (ap g (point_eq f) @ point_eq g).\n\nRecord pHomotopy {A B : pType} (f g : pMap A B) :=\n  { pointed_htpy : f == g ;\n    point_htpy : pointed_htpy (point A) @ point_eq g = point_eq f }.\nArguments pointed_htpy {A B f g} p x.\n\nInfix \"==*\" := pHomotopy (at level 70, no associativity) : pointed_scope.\n\nDefinition loops_functor {A B : pType} (f : A ->* B)\n: (loops A) ->* (loops B).\nProof.\n  refine (Build_pMap (loops A) (loops B)\n            (fun p => (point_eq f)^ @ (ap f p @ point_eq f)) _).\n  apply moveR_Vp; simpl.\n  refine (concat_1p _ @ (concat_p1 _)^).\nDefined.\n\nDefinition loops_functor_compose {A B C : pType}\n           (g : B ->* C) (f : A ->* B)\n: (loops_functor (pmap_compose g f))\n   ==* (pmap_compose (loops_functor g) (loops_functor f)).\nadmit.\nDefined.\n\nLocal Open Scope path_scope.\n\nRecord ooGroup :=\n  { classifying_space : pType@{i} ;\n    isconn_classifying_space : IsConnected@{u a i} 0 classifying_space\n  }.\n\nLocal Notation B := classifying_space.\n\nDefinition group_type (G : ooGroup) : Type\n  := point (B G) = point (B G).\n\nCoercion group_type : ooGroup >-> Sortclass.\n\nDefinition group_loops (X : pType)\n: ooGroup.\nProof.\n\n  pose (x0 := point X);\n  pose (BG := (Build_pType\n               { x:X & merely (x = point X) }\n               (existT (fun x:X => merely (x = point X)) x0 (tr 1)))).\n\n  cut (IsConnected 0 BG).\n  {\n exact (Build_ooGroup BG).\n}\n  cut (IsSurjection (unit_name (point BG))).\n  {\n intros; refine (conn_pointed_type (point _)).\n}\n  apply BuildIsSurjection; simpl; intros [x p].\n  strip_truncations; apply tr; exists tt.\n  apply path_sigma_hprop; simpl.\n  exact (p^).\nDefined.\n\nDefinition loops_group (X : pType)\n: loops X <~> group_loops X.\nadmit.\nDefined.\n\nDefinition ooGroupHom (G H : ooGroup)\n  := pMap (B G) (B H).\n\nDefinition grouphom_fun {G H} (phi : ooGroupHom G H) : G -> H\n  := loops_functor phi.\n\nCoercion grouphom_fun : ooGroupHom >-> Funclass.\n\nDefinition group_loops_functor\n           {X Y : pType} (f : pMap X Y)\n: ooGroupHom (group_loops X) (group_loops Y).\nProof.\n  simple refine (Build_pMap _ _ _ _); simpl.\n  -\n intros [x p].\n    exists (f x).\n    strip_truncations; apply tr.\n    exact (ap f p @ point_eq f).\n  -\n apply path_sigma_hprop; simpl.\n    apply point_eq.\nDefined.\n\nDefinition loops_functor_group\n           {X Y : pType} (f : pMap X Y)\n: loops_functor (group_loops_functor f) o loops_group X\n  == loops_group Y o loops_functor f.\nadmit.\nDefined.\n\nDefinition grouphom_compose {G H K : ooGroup}\n           (psi : ooGroupHom H K) (phi : ooGroupHom G H)\n: ooGroupHom G K\n  := pmap_compose psi phi.\n\nDefinition group_loops_functor_compose\n           {X Y Z : pType}\n           (psi : pMap Y Z) (phi : pMap X Y)\n: grouphom_compose (group_loops_functor psi) (group_loops_functor phi)\n  == group_loops_functor (pmap_compose psi phi).\nProof.\n  intros g.\n  unfold grouphom_fun, grouphom_compose.\n  refine (pointed_htpy (loops_functor_compose _ _) g @ _).\n  pose (p := eisretr (loops_group X) g).\n  change (loops_functor (group_loops_functor psi)\n            (loops_functor (group_loops_functor phi) g)\n          = loops_functor (group_loops_functor\n                                 (pmap_compose psi phi)) g).\n  rewrite <- p.\n  Fail Timeout 1 Time rewrite !loops_functor_group.\n  (* 0.004 s in 8.5rc1, 8.677 s in 8.5 *)\n  Timeout 1 do 3 rewrite loops_functor_group.\nAbort.\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/4544.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.29034436174122547}}
{"text": "(*\n\n  Copyright 2016 University of Luxembourg\n\n  This file is part of our formalization of Platzer's\n    \"A Complete Uniform Substitution Calculus for Differential Dynamic Logic\"\n  available here: http://arxiv.org/pdf/1601.06183.pdf (July 27, 2016).\n  We refer to this formalization as DdlCoq here.\n\n  DdlCoq 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  DdlCoq 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 DdlCoq.  If not, see <http://www.gnu.org/licenses/>.\n\n  authors:\n    Vincent Rahli\n    Marcus Völp\n    Ivana Vukotic\n\n *)\n\n\nRequire Export symbol.\nRequire Export list_util.\nRequire Export tactics_util.\nRequire Export reals_util.\n\n\n(**\n\n  In this file conversion between KAssignables, variables and strings is introduced, as well as symbol decidability.\n  Also, this file introduces definition of state, and implements some lemmas about states.\n  Beside that, this file includes some useful definitions which we used in order to define syntax and semantics of ddl.\n\n*)\n\n\n\n(** some useful conversions between KAssignables, variables and strings *)\n\n(* Used in definition of interpretation of primed terms *)\n(** extract variable form KAssignable *)\nFixpoint KAssignable2variable (a : KAssignable) : KVariable :=\n  match a with\n  | KAssignVar x => x\n  | KAssignDiff a => KAssignable2variable a\n  end.\nCoercion KAssignable2variable : KAssignable >-> KVariable.\n\nCoercion KAssignVar : KVariable >-> KAssignable.\n\n(** converts KVariable to string *)\nDefinition KVariable2string (v : KVariable) : String.string :=\n  match v with\n  | variable name => name\n  end.\nCoercion KVariable2string : KVariable >-> String.string.\n\n(** converts KAssignable to string *)\nDefinition KAssignable2string (a : KAssignable) : String.string := a.\n\n(* Used in definition of interpretation of theta prime *)\n(** extracts variables form KAssignable *)\nDefinition KVar_of_KAssignable (a : KAssignable) : list KVariable :=\n  match a with\n  | KAssignVar x => [x]\n  | KAssignDiff _ => []\n  end.\n\n\n\n(** Decidability for symbols *)\n\n(* used in definition of interpretation of teta prime *)\n(** decidability for variables *)\nLemma KVariable_dec :\n  forall a b : KVariable, {a = b} + {a <> b}.\nProof.\n  destruct a as [x], b as [y]; prove_dec.\n  destruct (string_dec x y); subst; prove_dec.\nDefined.\n\n(* decidability for channels *)\nLemma KChannel_dec :\n  forall a b : KChannel, {a = b} + {a <> b}.\nProof.\n  destruct a as [x], b as [y]; prove_dec.\n  destruct (string_dec x y); subst; prove_dec.\nDefined.\n\n(** decidability for function symbols *)\nLemma FunctionSymbol_dec : forall (t u : FunctionSymbol), {t = u} + {t <> u}.\nProof.\n  destruct t as [n1], u as [n2].\n  destruct (string_dec n1 n2); subst; prove_dec.\nDefined.\n\n(** decidability for predicate symbols *)\nLemma PredicateSymbol_dec : forall (t u : PredicateSymbol), {t = u} + {t <> u}.\nProof.\n  destruct t as [n1], u as [n2].\n  destruct (string_dec n1 n2); subst; prove_dec.\nDefined.\n\n(** decidability for quantifier symbol *)\nLemma QuantifierSymbol_dec : forall (t u : QuantifierSymbol), {t = u} + {t <> u}.\nProof.\n  destruct t as [n1], u as [n2].\n  destruct (string_dec n1 n2); subst; prove_dec.\nDefined.\n\n(** decidability for constants *)\nLemma ProgramConstName_dec : forall (t u : ProgramConstName), {t = u} + {t <> u}.\nProof.\n  destruct t as [n1], u as [n2].\n  destruct (string_dec n1 n2); subst; prove_dec.\nDefined.\n\n(** decidability for constants *)\nLemma ODEConst_dec : forall (t u : ODEConst), {t = u} + {t <> u}.\nProof.\n  destruct t as [n1], u as [n2].\n  destruct (string_dec n1 n2); subst; prove_dec.\nDefined.\n\n(** decidability for KAssignables *)\nLemma KAssignable_dec : forall (t u : KAssignable), {t = u} + {t <> u}.\nProof.\n  induction t as [v1|d1], u as [v2|d2]; prove_dec.\n  { destruct (KVariable_dec v1 v2) as [d|d]; subst; prove_dec. }\n  { destruct (IHd1 d2) as [d|d]; subst; prove_dec. }\nDefined.\n\n(** returns differential of some variable x *)\nDefinition DVar (x : KVariable) : KAssignable :=\n  KAssignDiff (KAssignVar x).\n\n\nDefinition remove_var v l := remove_elt KVariable_dec v l.\n\nLemma not_in_remove_var :\n  forall v l, ~ In v (remove_var v l).\nProof.\n  introv; unfold remove_var; eauto with core.\nQed.\nHint Resolve not_in_remove_var : core.\n", "meta": {"author": "LS-Lab", "repo": "Coq-dL", "sha": "af7e7dc5cc44f8a3e24b2a6a154bfff7858dfb2b", "save_path": "github-repos/coq/LS-Lab-Coq-dL", "path": "github-repos/coq/LS-Lab-Coq-dL/Coq-dL-af7e7dc5cc44f8a3e24b2a6a154bfff7858dfb2b/syntax/symbol_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.29034436174122547}}
{"text": "Require Import bedrock2.NotationsCustomEntry.\n\nImport Syntax Syntax.Coercions BinInt String List List.ListNotations.\nLocal Open Scope string_scope. Local Open Scope Z_scope. Local Open Scope list_scope.\n\nDefinition memequal := func! (x,y,n) ~> r {\n  r = $0;\n  while n {\n    r = r | (load1(x) ^ load1(y));\n    x = x + $1;\n    y = y + $1;\n    n = n - $1\n  };\n  r = r == $0\n}.\n\nRequire Import bedrock2.WeakestPrecondition bedrock2.Semantics bedrock2.ProgramLogic.\nRequire Import coqutil.Word.Interface coqutil.Word.Bitwidth.\nRequire Import coqutil.Map.Interface bedrock2.Map.SeparationLogic.\nRequire Import bedrock2.ZnWords.\nImport Coq.Init.Byte coqutil.Byte.\nLocal Notation string := String.string.\n\n(*Require Import bedrock2.ptsto_bytes.*)\nLocal Notation \"xs $@ a\" := (Array.array ptsto (word.of_Z 1) a xs) (at level 10, format \"xs $@ a\").\nLocal Notation \"m =* P\" := ((P%sep) m) (at level 70, only parsing) (* experiment*).\n\nSection WithParameters.\n  Context {width} {BW: Bitwidth width}.\n  Context {word: word.word width} {mem: map.map word byte} {locals: map.map string word}.\n  Context {ext_spec: ExtSpec}.\n  Import ProgramLogic.Coercions.\n\n  Global Instance spec_of_memequal : spec_of \"memequal\" :=\n    fnspec! \"memequal\" (x y n : word) / (xs ys : list byte) (Rx Ry : mem -> Prop) ~> r,\n    { requires t m := m =* xs$@x * Rx /\\ m =* ys$@y * Ry /\\\n                      length xs = n :>Z /\\ length ys = n :>Z;\n      ensures t' m' := m=m' /\\ t=t' /\\ (r = 0 :>Z \\/ r = 1 :>Z) /\\\n                       (r  = 1 :>Z <-> xs  = ys) }.\n\n  Context {word_ok: word.ok word} {mem_ok: map.ok mem} {locals_ok : map.ok locals}\n    {env : map.map string (list string * list string * Syntax.cmd)} {env_ok : map.ok env}\n    {ext_spec_ok : ext_spec.ok ext_spec}.\n\n  Import coqutil.Tactics.letexists coqutil.Tactics.Tactics coqutil.Tactics.autoforward.\n  Import coqutil.Word.Properties coqutil.Map.Properties.\n\n  Local Ltac ZnWords := destruct width_cases; bedrock2.ZnWords.ZnWords.\n  Lemma memequal_ok : program_logic_goal_for_function! memequal.\n  Proof.\n    repeat straightline.\n\n    refine ((Loops.tailrec\n      (HList.polymorphic_list.cons _\n      (HList.polymorphic_list.cons _\n      (HList.polymorphic_list.cons _\n      (HList.polymorphic_list.cons _\n      HList.polymorphic_list.nil))))\n      [\"x\";\"y\";\"n\";\"r\"])\n      (fun (v:nat) xs Rx ys Ry t m x y n r => PrimitivePair.pair.mk (\n        m =* xs$@x * Rx /\\  m =* ys$@y * Ry /\\\n        v=n :> Z /\\ length xs = n :> Z /\\ length ys = n :> Z\n      )\n      (fun                     T M (X Y N R : word) => m = M /\\ t = T /\\\n        exists z, R = Z.lor r z :> Z /\\ (z  = 0 :>Z <-> xs  = ys)\n      ))\n      lt\n      _ _ _ _ _ _ _ _ _);\n      (* TODO wrap this into a tactic with the previous refine *)\n      cbn [HList.hlist.foralls HList.tuple.foralls\n           HList.hlist.existss HList.tuple.existss\n           HList.hlist.apply  HList.tuple.apply\n           HList.hlist\n           List.repeat Datatypes.length\n           HList.polymorphic_list.repeat HList.polymorphic_list.length\n           PrimitivePair.pair._1 PrimitivePair.pair._2] in *.\n      { cbv [Loops.enforce]; cbn.\n        subst l l0.\n        repeat (rewrite ?map.get_put_dec, ?map.get_remove_dec; cbn); split.\n        { exact eq_refl. }\n        { eapply map.map_ext; intros k.\n          repeat (rewrite ?map.get_put_dec, ?map.get_remove_dec, ?map.get_empty; cbn -[String.eqb]).\n          repeat (destruct String.eqb; trivial). } }\n      { eapply Wf_nat.lt_wf. }\n      { cbn; ssplit; eauto. }\n      { intros ?v ?xs ?Rx ?ys ?Ry ?t ?m ?x ?y ?n ?r.\n        repeat straightline.\n        cbn in localsmap.\n        eexists n0; split; cbv [expr expr_body localsmap get].\n        { rewrite ?Properties.map.get_put_dec. exists n0; cbn. auto. }\n        split; cycle 1.\n        { intros Ht; rewrite Ht in *.\n          intuition idtac; destruct xs0, ys0; cbn in *; try discriminate; [].\n          exists 0; intuition eauto. rewrite Z.lor_0_r. trivial. }\n\n        intros Ht.\n        destruct xs0 as [|hxs xs0] in *, ys0 as [|hys ys0] in *;\n          cbn [length Array.array] in *; try (cbn in *; congruence); [];\n\n        repeat straightline.\n        eapply WeakestPreconditionProperties.dexpr_expr.\n\n        repeat straightline.\n        letexists; split.\n        { rewrite ?Properties.map.get_put_dec; exact eq_refl. }\n        repeat straightline.\n        letexists; split.\n        { rewrite ?Properties.map.get_put_dec; cbn. exact eq_refl. }\n        repeat straightline.\n\n        repeat straightline.\n        repeat straightline.\n        letexists; split.\n        { rewrite ?Properties.map.get_put_dec; exact eq_refl. }\n        repeat straightline.\n\n        repeat straightline.\n        eapply WeakestPreconditionProperties.dexpr_expr.\n        letexists; split.\n        { subst l. rewrite ?Properties.map.get_put_dec; cbn. exact eq_refl. }\n\n        repeat straightline.\n        eapply WeakestPreconditionProperties.dexpr_expr.\n        letexists; split.\n        { subst l l0. rewrite ?Properties.map.get_put_dec; cbn. exact eq_refl. }\n\n        repeat straightline.\n        eapply WeakestPreconditionProperties.dexpr_expr.\n        letexists; split.\n        { subst l l0 l1. rewrite ?Properties.map.get_put_dec; cbn. exact eq_refl. }\n\n        repeat straightline.\n\n        eexists _, _, _, _.\n        split.\n        { cbv [Loops.enforce l l0 l1 l2]; cbn.\n          repeat (rewrite ?map.get_put_dec, ?map.get_remove_dec; cbn); split.\n          { exact eq_refl. }\n          { eapply map.map_ext; intros k.\n            repeat (rewrite ?map.get_put_dec, ?map.get_remove_dec, ?map.get_empty; cbn -[String.eqb]).\n            repeat (destruct String.eqb; trivial). } }\n        eexists _, _, _, _, (length xs0); split; ssplit.\n        { ecancel_assumption. }\n        { ecancel_assumption. }\n        { ZnWords. }\n        { ZnWords. }\n        { ZnWords. }\n        split.\n        { cbn in *; ZnWords. }\n        intuition idtac; repeat straightline_cleanup.\n        rewrite H10, word.unsigned_or_nowrap, <-Z.lor_assoc.\n        eexists; split; trivial.\n        transitivity (hxs = hys /\\ xs0 = ys0); [|intuition congruence].\n        rewrite <-H11. rewrite Z.lor_eq_0_iff. eapply and_iff_compat_r.\n        subst v0 v1. rewrite word.unsigned_xor_nowrap, Z.lxor_eq_0_iff.\n        split; [|intros;subst;trivial].\n        intro HH.\n        pose proof byte.unsigned_range hxs;\n        pose proof byte.unsigned_range hys.\n        eapply word.unsigned_inj in HH; eapply word.of_Z_inj_small in HH; try ZnWords.\n        eapply byte.unsigned_inj in HH; trivial. }\n\n      intuition idtac. case H6 as (?&?&?). subst. subst r.\n      eapply WeakestPreconditionProperties.dexpr_expr.\n      letexists; split; cbn.\n      { rewrite ?Properties.map.get_put_dec; cbn; exact eq_refl. }\n      eexists; split; cbn.\n      { rewrite ?Properties.map.get_put_dec; cbn; exact eq_refl. }\n\n      rewrite word.unsigned_of_Z_0, Z.lor_0_l in H5; subst x4 v.\n      setoid_rewrite word.unsigned_eqb; setoid_rewrite word.unsigned_of_Z_0.\n      eexists; ssplit; eauto; destr Z.eqb; autoforward with typeclass_instances in E;\n        rewrite ?word.unsigned_of_Z_1, ?word.unsigned_of_Z_0; eauto.\n      all : intuition eauto; discriminate.\n  Qed.\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/memequal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2903366676051643}}
{"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(*           Bihong Zhang <sa614257@mail.ustc.edu.cn>                         *)\n(*                                     School of Software Engineering, USTC   *)\n(*                                                                            *)\n(* ************************************************************************** *)\n\n(* \n\n*)\n\n(* ************* ************************************* *****)\n(* ftl interface *)\n\nRequire Import ListEx.\nRequire Import Monad.\nRequire Import Data.\nRequire Import Params.\nRequire Import Nand.\n\n\n(*\nCache mapping table\n\nThe cmt_record is (lpn,ppn,flag,time).The init cmt is all the cmt_empty.\n*)\n\nInductive flag :Set := \n | dirty:flag \n | clean:flag.\n\nInductive cmt_record: Set := \n| cmt_empty\n| cmt_trans(lpn:page_no)(pbn:block_no)(offset:nat)(is_dirty:flag).\n\n\nDefinition cache_mapping_table := list cmt_record.\n\nFixpoint  find_empty_cmt(cmt:cache_mapping_table) (i:nat): option nat := \n  match cmt with\n  | nil => None\n  | cons a cmt' => match a with\n                     | cmt_empty => Some i\n                     | _ => find_empty_cmt cmt' (S i)\n                   end\nend.\n\nDefinition cmt_get(cmt : cache_mapping_table) (loc: nat) : option cmt_record :=\n  list_get cmt loc.\n\nDefinition cmt_set(cmt: cache_mapping_table) (loc: nat) (newrecord:cmt_record): option cache_mapping_table :=\n  list_set cmt loc newrecord.\n\nDefinition cmt_get_trans(record:cmt_record) : option (prod (prod block_no page_no) flag)  :=\n  match record with\n      | cmt_empty => None\n      | cmt_trans lpn pbn off f => ret((pbn,off),f)\nend.\n\nFixpoint cmt_in (cmt:cache_mapping_table) (lpn:page_no) :bool :=\n  match cmt with\n      | nil => false\n      | cons a cmt' => match a with\n                           | (cmt_trans lpn' _ _ _) => if beq_nat lpn lpn' then true else cmt_in cmt' lpn\n                           | _ => cmt_in cmt' lpn\n                       end\n  end.\n\nFixpoint find_cmtrecord(cmt:cache_mapping_table)(lpn:page_no)(i:nat) : option nat :=\n  match cmt with\n    | nil => None\n    | cons a cmt' => match a with \n                         |(cmt_trans lpn' _ _ _) =>if beq_nat lpn' lpn then Some i else find_cmtrecord cmt' lpn (S i)  \n                         | _ => find_cmtrecord cmt' lpn (S i)\n                     end\nend.\n\nFixpoint remove_cmt(cmt:cache_mapping_table) (lpn:page_no):  cache_mapping_table :=\n  match cmt with\n    | nil => nil\n    | cons a cmt' => match a with \n                         |(cmt_trans lpn' _  _ _) =>if beq_nat lpn' lpn then cmt' else cons a (remove_cmt cmt' lpn)\n                         | _ => cons a (remove_cmt cmt' lpn)\n                     end\nend.\n\nFixpoint insert_cmt (cmt:cache_mapping_table) (record:cmt_record) (num:nat) :cache_mapping_table :=\n  match num with\n      | O => cons record cmt\n      | S i => match cmt with\n                 | nil => nil\n                 | cons a cmt' => (cons a (insert_cmt cmt' record i ) )\n                end\n   end.\n\nDefinition remove_head(cmt:cache_mapping_table) : option cache_mapping_table :=\n  match cmt with\n      | nil => None\n      | cons a cmt' => Some cmt'\nend.\n\nFixpoint append_tail(cmt:cache_mapping_table)(newrecord:cmt_record) : cache_mapping_table :=\n  match cmt with \n      | nil => cons newrecord nil\n      | cons a nil => cons a (cons newrecord nil)\n      | cons a cmt' => cons a (append_tail cmt' newrecord)\nend.\n\n(*Init the cache mapping table *)\nFixpoint init_cmt(cmt:cache_mapping_table)(i:nat): option cache_mapping_table :=\n  match i with\n|  O => None\n|  S O => Some cmt\n|  S i' => init_cmt (list_append cmt cmt_empty) i'\nend.\n\nDefinition blank_cmt : cache_mapping_table :=\n  list_repeat_list CMT_LENGTH cmt_empty.\n\n(*\nGlobal translation table\n\nThe length of the gtd is fixed.The record is(index,ppn).\n*)\n\nInductive gtd_record: Set := \n| gtd_empty\n| gtd_trans (pbn:block_no) (offset:nat ).\n\n\nDefinition global_mapping_directory := list gtd_record.\n\n(* Definition gtd_len(gtd:global_mapping_directory) : nat :=  *)\n(*   length gtd. *)\n\nDefinition gtd_get(gtd:global_mapping_directory)(loc: nat) : option gtd_record :=\n  list_get gtd loc.\n\nDefinition gtd_set(gtd:global_mapping_directory) (loc: nat) (newrecord:gtd_record): option global_mapping_directory :=\n  list_set gtd loc newrecord.\n\n(* SearchAbout andb. *)\nFixpoint gtd_look_by_record(gtd:global_mapping_directory)(lbn:block_no) (off:nat) (num:nat) : option nat :=\n  match gtd with\n      | nil  => None\n      | cons record' gtd' => match record' with\n                                 | gtd_empty => gtd_look_by_record gtd' lbn off (S num)\n                                 | gtd_trans lbn' off' => if andb (beq_nat lbn lbn') (beq_nat off off')  then Some num else gtd_look_by_record gtd' lbn off (S num) \n\n                             end\nend.\n\nFixpoint gtd_look_by_lpn (gtd:global_mapping_directory) (lpn:page_no) (num:nat):option nat :=\n  match gtd with\n      | nil => None\n      | cons record' l => if ble_nat lpn (pred ((S num) * RECORD_PER_TRANS)) then Some num else gtd_look_by_lpn l lpn (S num)\n end.\n\nDefinition  gtd_get_trans_by_lpn(gtd:global_mapping_directory)(lpn:page_no):option (prod nat nat) :=\n  do gtd_loc <-- gtd_look_by_lpn gtd lpn 0;\n  do record <-- gtd_get gtd gtd_loc;\n  match record with\n      | gtd_empty => None\n      | gtd_trans pbn off => ret (pbn,off)\nend.\n\nFixpoint init_gtd(gtd:global_mapping_directory)(i:nat): option global_mapping_directory :=\n  match i with\n|  O => None\n|  S O => Some gtd\n|  S i' => init_gtd (list_append gtd gtd_empty) i'\nend.\n\nDefinition blank_gtd : global_mapping_directory :=\n  list_repeat_list GTD_LENGTH gtd_empty.\n\n(* Compute ( *)\n(*  do gtd <-- Some blank_gtd; *)\n(*  do i <-- gtd_look_by_lpn gtd 7 0; *)\n(*  ret i *)\n(* ). *)\n(*\nTrans_page data\n\nThe data of trans_page is (lpn,ppn)\n*)\n\n(* Inductive trans_record: Set := *)\n(*   | trans_empty *)\n(*   | trans_data(lpn:page_no)(ppn:page_no). *)\n\n(* Definition trans_page := list trans_record. *)\n\n(* Definition trans_len(trans:trans_page) : nat :=  *)\n(*   length trans. *)\n\n(* Definition trans_get(trans:trans_page)(loc: nat) : option trans_record := *)\n(*   list_get trans loc. *)\n\n(* Definition trans_set(trans:trans_page) (loc: nat) (newrecord:trans_record): option trans_page := *)\n(*   list_set trans loc newrecord. *)\n\n\n(*\nFTL block state\n*)\n\nInductive ftl_block_state : Set :=\n  | bs_invalid\n  | bs_erased\n  | bs_data\n  | bs_trans.\n\nInductive ftl_page_state : Set :=\n  | ps_invalid\n  | ps_erased\n  | ps_data  (lpn:page_no)\n  | ps_trans (gtd_loc:nat).\n\nDefinition page_state_table := list ftl_page_state.\n\nDefinition pst_get(pst:page_state_table)(loc: nat) : option ftl_page_state :=\n  list_get pst loc.\n\nDefinition pst_set(pst:page_state_table) (loc: nat) (newstate:ftl_page_state): option page_state_table :=\n  list_set pst loc newstate.\n\nDefinition pst_set_all (state:ftl_page_state):page_state_table  :=\n  list_repeat_list  PAGES_PER_BLOCK state.\n\n(*\nBlock_info_table\n*)\n\nRecord block_info : Set := \n  mk_bi {\n      bi_state: ftl_block_state;\n      bi_used_pages: nat;\n      bi_erase_count: nat;\n      bi_page_state: page_state_table\n    }.\n\nDefinition block_info_table :=  list block_info.\n\nDefinition bi_set_state (bi : block_info) (bi_state : ftl_block_state) : block_info :=\n  mk_bi bi_state (bi_used_pages bi) (bi_erase_count bi) (bi_page_state bi).\n\n(* set both the block and page state *)\nDefinition pi_set_state (bi : block_info) (bi_state : ftl_block_state) (bi_page_state:page_state_table) : block_info :=\n  mk_bi bi_state (bi_used_pages bi) (bi_erase_count bi) bi_page_state.\n\nDefinition bit_get (bit: block_info_table) (b: block_no) \n     : option block_info := \n  list_get bit b.\n\nDefinition bit_update (bit: block_info_table) (b: block_no) (bi: block_info)\n      : option block_info_table := \n  list_set bit b bi.\n\n(* In FTL, a block is initialized to be 'bs_invalid' *)\nDefinition blank_bi : block_info := \n  mk_bi bs_erased 0 0 (pst_set_all ps_erased).\n\n(*\nFree block queue\n\nFree blocks are those not used, and each of them can be invalid or\nerased (filled with \\og{0xFF}). All the free blocks are put into a \nqueue, where a new allocated block is get from the head.\n*)\n\nDefinition block_queue := list block_no.\n\nDefinition fbq_enq (fbq : block_queue) (b : block_no) : option (block_queue) :=\n  Some (list_append fbq b).\n\nDefinition fbq_deq (fbq : block_queue) : option (prod block_no (block_queue)) := \n  match fbq with\n    | nil => None\n    | cons b fbq' => Some (b, fbq')\n  end.\n\nDefinition fbq_in (fbq: list block_no) (pbn: block_no) : bool := list_inb beq_nat fbq pbn.\n\nDefinition fbq_get (fbq: list block_no) (i: nat) : option block_no := list_get fbq i.\n\nDefinition check_block_is_full (bi: block_info) : bool :=\n  match blt_nat (bi_used_pages bi) PAGES_PER_BLOCK with \n    | true => false\n    | false => true\n  end.\n\n(*\n\nCurrnt data/translation block\n\n*)\n\n(* Definition current_data_block := block_no. *)\n\n(* Definition current_trans_block := block_no. *)\n\n(*\nFTL structure\n*)\n\nRecord FTL : Set := \n  mk_FTL {\n      ftl_bi_table: block_info_table;\n      ftl_free_blocks: block_queue;\n      ftl_cmt_table:cache_mapping_table;\n      ftl_gtd_table:global_mapping_directory;\n      current_data_block:block_no;\n      current_trans_block:block_no\n    }.\n\nDefinition ftl_update_bit (f: FTL) (bit: block_info_table) : option FTL :=\n  ret mk_FTL bit (ftl_free_blocks f) (ftl_cmt_table f) (ftl_gtd_table f) (current_data_block f) (current_trans_block f).\n\nDefinition ftl_update_fbq (f: FTL) (fbq: block_queue) : option FTL :=\n  ret mk_FTL (ftl_bi_table f) fbq  (ftl_cmt_table f) (ftl_gtd_table f) (current_data_block f) (current_trans_block f).\n\nDefinition ftl_update_cmt (f: FTL) (cmt: cache_mapping_table) : option FTL :=\n  ret mk_FTL (ftl_bi_table f)  (ftl_free_blocks f) cmt (ftl_gtd_table f) (current_data_block f) (current_trans_block f).\n\nInductive freebq_state : Set :=\n  | fbqs_abundant\n  (* | fbqs_needgc *)\n  | fbqs_scarce.\n\n(* IMPORTANT !!! *)\nDefinition check_freebq_count (freebq: block_queue): freebq_state :=\n  match (ble_nat MIN_FREE_BLOCKS (length freebq)) with\n    | false => fbqs_scarce\n    | true => fbqs_abundant\n  end.\n\n\n(* **************************************************** \n\n   * ReadBlock/WriteBlock Operations\n*)\n\nDefinition read_block (c: chip) (pbn: block_no) (off: page_off) : option data :=\n  (* read the page from \"off\" in pbn_data *)\n  do [d, o] <-- (nand_read_page c pbn off);\n\n  (* return the data in the page *)\n  ret d.\n\nDefinition read_block_oob (c: chip) (pbn: block_no) (off: page_off) : option (prod data page_oob_nat) :=\n  (* read the page from \"off\" in pbn_data *)\n  do [d, o] <-- (nand_read_page c pbn off);\n  ret (d,o).\n\n\nDefinition write_data_block (c: chip) (pbn_bi: block_info) (pbn: block_no) \n           (loc: page_off) (d: data) (oob:page_oob_nat)(page_state:ftl_page_state): option (prod chip block_info) := \n  (* write the data to \"pbn#loc\", return c' *)\n  let pst := bi_page_state pbn_bi in\n  do c' <-- (nand_write_page c pbn loc d oob);\n  do pst' <-- pst_set pst loc page_state;\n  (* return bi := <bi_state, used+1, ec> *)\n  let bi' := mk_bi (bi_state pbn_bi) ((bi_used_pages pbn_bi)+1) (bi_erase_count pbn_bi) pst' in\n\n  ret  (c', bi').\n\n(* Definition read_trans_block (c: chip) (bi: block_info) (pbn_log: block_no) (off: page_off) : option data := *)\n(*   (* find the lastest log page for \"poff\" in 'bk' , return the log-location *) *)\n(*   do loc <-- (find_page_in_log_block bi off); *)\n\n(*   (* read the page from \"loc\" in pbn_log *) *)\n(*   do [d, o] <-- (nand_read_page c pbn_log loc);  *)\n\n(*   (* return the data in the page *) *)\n(*   ret d. *)\n\n(* Definition write_trans_block *)\n\n(*\nFTL read algorithm\n\n*)\n\n(* **************************************************** \n* Alloc_Block \n\nAllocation block routine, no GC yet. But I believe that it will be \nnot difficult to add a simple GC. \n\n*)\n\nDefinition alloc_block (c: chip) (f: FTL) : option (prod block_no (prod chip FTL)) :=\n  let bit := ftl_bi_table f in\n  let fbq := ftl_free_blocks f in\n  match (check_freebq_count fbq) with\n    | fbqs_abundant =>\n        do [b, fbq'] <-- fbq_deq fbq; \n        do bi_free <-- bit_get bit b;\n        match bi_state bi_free with\n          | bs_erased => \n              (* TODO:  we don't need to update bit. No,we need,we set the used_pages and pages_state *)\n              do bit' <-- bit_update bit b (mk_bi bs_erased 0 (bi_erase_count bi_free) (pst_set_all ps_erased));\n              ret (b, (c, (mk_FTL bit'  fbq' (ftl_cmt_table f) (ftl_gtd_table f) (current_data_block f) (current_trans_block f) )))\n          | bs_invalid => \n              do c' <-- nand_erase_block c b;\n              do bit' <-- bit_update bit b (mk_bi bs_erased 0 (1 + bi_erase_count bi_free) (pst_set_all ps_erased));\n              ret (b, (c',(mk_FTL bit' fbq' (ftl_cmt_table f) (ftl_gtd_table f) (current_data_block f) (current_trans_block f) )))\n\n          | bs_data => None\n\n          | bs_trans => None\n        end \n  \n    | _ => None\n  end.\n\nDefinition bit_set_state (bit: block_info_table) (pbn: block_no) (st: ftl_block_state) (pst:page_state_table) \n  : option block_info_table :=\n  do bi <-- bit_get bit pbn;\n  do bi' <-- Some (mk_bi st (bi_used_pages bi) (bi_erase_count bi) pst);\n  do bit' <-- bit_update bit pbn bi';\n  ret bit'.\n\nDefinition bit_get_bstate (f: FTL) (pbn: block_no) : option ftl_block_state := \n  do bi <-- bit_get (ftl_bi_table f) pbn;\n  ret (bi_state bi).\n\n(* **************************************************** \n* Auxiliary Routines for update Meta-Data \n*)\n\nDefinition free_block (bit: block_info_table) (fbq: block_queue) (pbn: block_no)\n  : option (prod block_info_table block_queue) :=\n  do bi <-- bit_get bit pbn;\n  do pst <-- Some (pst_set_all ps_invalid);\n  do bi' <-- Some (mk_bi bs_invalid (bi_used_pages bi) (bi_erase_count bi) pst);\n  do bit' <-- bit_update bit pbn bi';\n  do fbq' <-- fbq_enq fbq pbn;\n  ret (bit', fbq').\n\nDefinition zero_page := (zero_data PAGE_DATA_SIZE).\n\n(*\n* Check the current_data_block and current_trans_block\n*)\n\nDefinition check_current_block(bit:block_info_table) (pbn: block_no):option bool :=\n  do bi <-- bit_get bit pbn; \n  match check_block_is_full bi with\n     | false => Some false\n     | true => Some true\n  end.\n\nFixpoint find_trans_in_metatrans(l:meta_trans_record_list) (lpn:page_off) : option (prod nat nat) :=\n  match l with\n      | nil => None\n      | cons record l' =>match record with\n                             | trans_empty => find_trans_in_metatrans l' lpn\n                             | trans_data lpn' pbn' off' => if beq_nat lpn lpn' then Some (pbn',off') else find_trans_in_metatrans l' lpn \n                          end\nend.\n\n(* Definition div (n1:nat)(n2:nat):nat := 1. *)\n\n(* Definition mod (n1:nat)(n2:nat):nat := 1. *)\n \nDefinition check_block_full(bi:block_info): bool :=\n  do num <<-- (bi_used_pages bi); \n  match blt_nat num PAGES_PER_BLOCK with\n      | true =>  false\n      | false => true\n end.\n\n(**********************************************************************)\n\n(*\nInit the ftl and nand\n*)\nDefinition bit_init : block_info_table :=\n  list_repeat_list BLOCKS blank_bi.\n\nDefinition cmt_init :cache_mapping_table := blank_cmt.\n\nDefinition gtd_init_empty : global_mapping_directory := blank_gtd.\n\nDefinition fbq_init : block_queue :=\n  list_make_nat_list BLOCKS.\n\nDefinition bit_init_current:option block_info_table :=\n  do bit <-- Some bit_init;\n  do bit' <-- bit_update bit 0 (mk_bi bs_data 0 0 (pst_set_all ps_erased) );\n  do bit'' <-- bit_update bit' 1 (mk_bi bs_trans 0 0  (pst_set_all ps_erased) );\n  ret bit''.\n\nDefinition fbq_init_current:option block_queue :=\n  do [_,fbq'] <-- fbq_deq fbq_init;\n  do [_,fbq''] <-- fbq_deq fbq';\n  ret fbq''.\n\nDefinition ftl_init : option FTL :=\n   do bit <-- bit_init_current;\n   do fbq <-- fbq_init_current;\n   ret (mk_FTL bit fbq cmt_init gtd_init_empty 0 1).\n\n(* Fixpoint gtd_init_trans(c:chip) (f:FTL) (gtd:global_mapping_table) (num:nat):option FTL := *)\n(*   match num with *)\n(*       | O => ret f *)\n(*       | S i => do cur_trans <-- Some (current_trans_block f); *)\n(*                do bit <-- ftl_bi_table f; *)\n(*                do cur_trans_bi <-- bit_get bit cur_trans; *)\n(*                match  check_block_full cur_trans_bi with *)\n(*                    | false => do off <-- Some (bi_used_pages cur_trans_bi); *)\n(*                               do gtd' <-- gtd_set gtd (minus 32 num) (gtd_trans cur_trans off); *)\n(*                               do bit' <-- bit_update bit'; *)\n(*                               do f' <-- (mk_FTL ( *)\n\n(*\nThe meta_trans_data Definition && Operations\n\n*)\nDefinition data_metatrans_get(dmt : meta_trans_record_list) (loc: nat) : option trans_record :=\n  list_get dmt loc.\n\nDefinition data_metatrans_set(dmt: meta_trans_record_list) (loc: nat) (newrecord:trans_record): option meta_trans_record_list :=\n  list_set dmt loc newrecord.\n\nDefinition blank_dmt :meta_trans_record_list  :=\n  list_repeat_list RECORD_PER_TRANS trans_empty.\n\nFixpoint find_meta_trans_record(l:meta_trans_record_list)(lpn:page_no)(i:nat) :option nat :=\n  match l with\n      | nil =>None\n      | cons record l' =>  match record with\n                           | trans_empty => find_meta_trans_record l' lpn (S i)\n                           | trans_data lpn' _ _ => if beq_nat lpn lpn' then Some i else find_meta_trans_record l' lpn (S i)\n                          end\nend.\n\nFixpoint find_meta_trans_empty(l:meta_trans_record_list)(lpn:page_no)(i:nat) :option nat :=\n  match l with\n      | nil =>None\n      | cons record l' =>  match record with\n                           | trans_empty => Some i\n                           | trans_data lpn' _ _ => find_meta_trans_empty l' lpn (S i)\n                          end\nend.\n\nFixpoint get_meta_trans_record (l:meta_trans_record_list)(lpn:page_no)(i:nat) : option (prod block_no page_no) :=\n  (* do i <-- find_meta_trans_record l lpn 0; *)\n  do record <-- data_metatrans_get l i;\n  match record with\n      | trans_data lpn pbn off => ret (pbn,off)\n      | _ => None\n  end.\n\nFixpoint copy_data_trans(l:meta_trans_record_list) (lpn:page_no) (newrecord:trans_record) : option meta_trans_record_list :=\n  match find_meta_trans_record l lpn 0 with\n      | Some loc => do l' <-- data_metatrans_set l loc newrecord;\n                    ret l'                   \n      | None => do empty_loc <-- find_meta_trans_empty l lpn 0;\n                do l' <-- data_metatrans_set l empty_loc newrecord;\n                ret l' \n   end.\n\n(*\nInvalid the block page\n*)\nDefinition invalid_old_page(bit:block_info_table)(pbn:block_no)(off:nat) :option block_info_table :=\n  do bi <-- bit_get bit pbn;\n  do pst <-- Some (bi_page_state bi);\n  do pst' <--  pst_set pst off ps_invalid;\n  do bi' <-- Some (pi_set_state bi (bi_state bi) pst');\n  do bit' <-- bit_update bit pbn bi';\n  ret bit'.\n\n(*\ncopy the trans_page_data(trans_pbn,trans_off) to current block  page or new allock page \nfor updating the pbn off\n*)\n\nDefinition copy_trans_page(c:chip)(f:FTL)(lpn:page_no)(trans_pbn:block_no)(trans_off:nat)(pbn:block_no)(off:nat): option (prod chip FTL) :=\n  let bit := ftl_bi_table f in\n  let fbq := ftl_free_blocks f in\n  let cmt := ftl_cmt_table f in\n  let gtd := ftl_gtd_table f in\n  let cur_trans := current_trans_block f in\n  let cur_data := current_data_block f in\n  do d <-- read_block c trans_pbn trans_off;\n  match d with\n    | metabyte _ => None\n    | metarecord meta_list => do new_list <-- copy_data_trans meta_list lpn (trans_data lpn pbn off); \n                              do cur_bi <-- bit_get bit cur_trans;\n                              do gtd_loc <-- gtd_look_by_lpn gtd lpn 0;\n                              match check_block_full cur_bi with\n                                | true =>(* If it is full *) \n                                         do [new_trans,cfx] <-- alloc_block c f;\n                                         do [c',f'] <-- Some cfx;\n                                         do bi <-- bit_get (ftl_bi_table f') new_trans;\n                                         do bi' <-- Some (bi_set_state bi bs_trans);\n                                         (* Repeat *)\n                                         do [c'',bi''] <-- write_data_block c' bi' new_trans 0 (metarecord new_list) (Some (gtd_loc, 0)) (ps_trans gtd_loc);\n                                         do bit' <-- bit_update (ftl_bi_table f') new_trans bi'';\n                                         (*Invalidate the old trans one*)\n                                         do bit'' <-- invalid_old_page bit' trans_pbn trans_off;\n                                         (*Invalidate the old data one*)\n                                         match find_meta_trans_record meta_list lpn 0 with\n                                             | None =>  (* update the gtd *)\n                                                        do gtd' <-- gtd_set gtd gtd_loc (gtd_trans new_trans 0) ;\n                                                        ret(c'',(mk_FTL bit'' (ftl_free_blocks f') (ftl_cmt_table f') gtd' cur_data new_trans) )\n                                                           \n                                             | Some i => do [old_data,old_off] <--  get_meta_trans_record meta_list lpn i;\n                                                         do bit''' <-- invalid_old_page bit'' old_data old_off;\n                                                         do gtd' <-- gtd_set gtd gtd_loc (gtd_trans new_trans 0) ;\n                                                         ret(c'',(mk_FTL bit''' (ftl_free_blocks f') (ftl_cmt_table f') gtd' cur_data new_trans) )\n                                        end\n                                                        \n                                | false => \n                                           do cur_off <-- Some (bi_used_pages cur_bi);\n                                           do [c',bi'] <-- write_data_block c cur_bi cur_trans cur_off (metarecord new_list) (Some(gtd_loc, 0)) (ps_trans gtd_loc);\n                                           do bit' <-- bit_update bit cur_trans bi';\n                                           (*Invalide the old trans page*)\n                                           do bit'' <-- invalid_old_page bit' trans_pbn trans_off;\n                                           (*Invalidate the old data one*)\n                                           match find_meta_trans_record meta_list lpn 0 with\n                                             | None =>  (* update the gtd,find the gtd_loc *)\n                                                        do gtd' <-- gtd_set gtd gtd_loc (gtd_trans cur_trans cur_off);\n                                                        ret (c',(mk_FTL bit'' fbq cmt  gtd' cur_data cur_trans ) )\n\n                                             | Some i => do [old_data,old_off] <--  get_meta_trans_record meta_list lpn i;\n                                                         do bit''' <-- invalid_old_page bit'' old_data old_off;\n                                                         (* update the gtd,find the gtd_loc *)\n                                                         do gtd' <-- gtd_set gtd gtd_loc (gtd_trans cur_trans cur_off);\n                                                         ret (c',(mk_FTL bit''' fbq cmt  gtd' cur_data cur_trans ) )\n                                            end\n                               end\nend.\n   \nDefinition write_trans_page(c:chip)(f:FTL)(lpn:page_no) (pbn:block_no)(off:nat): option (prod chip FTL) :=\n  let bit := ftl_bi_table f in\n  let fbq := ftl_free_blocks f in\n  let cmt := ftl_cmt_table f in\n  let gtd := ftl_gtd_table f in\n  let cur_trans := current_trans_block f in\n  let cur_data := current_data_block f in\n  do meta_list <-- Some (blank_dmt);\n  do new_list <-- copy_data_trans meta_list lpn (trans_data lpn pbn off); \n  do cur_bi <-- bit_get bit cur_trans;\n  do gtd_loc <-- gtd_look_by_lpn gtd lpn 0;\n  match check_block_full cur_bi with\n       | true =>(* If it is full *) \n             do [new_trans,cfx] <-- alloc_block c f;\n             do [c',f'] <-- Some cfx;\n             do bi <-- bit_get (ftl_bi_table f') new_trans;\n             do bi' <-- Some (bi_set_state bi bs_trans);\n             (* Repeat *)\n             do [c'',bi''] <-- write_data_block c' bi' new_trans 0 (metarecord new_list) (Some (gtd_loc, 0)) (ps_trans gtd_loc);\n             do bit' <-- bit_update (ftl_bi_table f') new_trans bi'';\n             do gtd' <-- gtd_set gtd gtd_loc (gtd_trans new_trans 0) ;\n             ret(c'',(mk_FTL bit' (ftl_free_blocks f') (ftl_cmt_table f') gtd' cur_data new_trans) )\n                                        \n                                                        \n       | false => \n            do cur_off <-- Some (bi_used_pages cur_bi);\n            do [c',bi'] <-- write_data_block c cur_bi cur_trans cur_off (metarecord new_list) (Some (gtd_loc, 0)) (ps_trans gtd_loc);\n            do bit' <-- bit_update bit cur_trans bi';\n            do gtd' <-- gtd_set gtd gtd_loc (gtd_trans cur_trans cur_off);\n            ret (c',(mk_FTL bit' fbq cmt  gtd' cur_data cur_trans ) )                     \nend.\n                                                                                 \nDefinition FTL_read(c:chip)(f:FTL)(lpn:page_no) : option (prod data (prod chip FTL) ) :=\n  let bit := ftl_bi_table f in\n  let fbq := ftl_free_blocks f in\n  let cmt := ftl_cmt_table f in\n  let gtd := ftl_gtd_table f in\n  (* test valid_page_off off; *)\n  (* If the lpn in the cmt *)\n  match find_cmtrecord cmt lpn 0 with\n      | Some num =>\n                  (* Do the read change the priitoty *)\n                  do record <-- cmt_get cmt num;\n                  match record with\n                   | cmt_empty => None\n                   | cmt_trans lpn' pbn' off' flag' =>  \n                                              match find_empty_cmt cmt 0 with\n                                                  | None =>  do cmt' <-- Some (remove_cmt cmt lpn);\n                                                             do cmt'' <-- Some (append_tail cmt' record);\n                                                             do d <-- read_block c pbn' off';\n                                                             ret (d,(c,mk_FTL (ftl_bi_table f) (ftl_free_blocks f) cmt'' (ftl_gtd_table f) (current_data_block f) (current_trans_block f) ) )\n                                                  | Some i => do cmt' <-- Some (remove_cmt cmt lpn);\n                                                              do cmt'' <-- Some (insert_cmt cmt' record (pred i) );\n                                                              do d <-- read_block c pbn' off';\n                                                              ret (d,(c,mk_FTL (ftl_bi_table f) (ftl_free_blocks f) cmt'' (ftl_gtd_table f) (current_data_block f) (current_trans_block f) ) )\n                                               end                                                            \n                  end\n      | None => do gtd_loc <-- gtd_look_by_lpn gtd lpn 0;\n                do gtd_record <-- gtd_get gtd gtd_loc;\n                match gtd_record with\n                   | gtd_empty => None\n                   | gtd_trans trans_lbn trans_offset =>\n                             do [data,oob] <-- nand_read_page c trans_lbn trans_offset;\n                             match data with\n                                   | metabyte _ => None\n                                   | metarecord meta_trans_list =>do [data_pbn,data_off] <-- find_trans_in_metatrans meta_trans_list lpn;\n                                                                  match find_empty_cmt cmt 0 with\n                                                                    | Some i =>(* Thec cmt is not full ,still have empty location *) \n                                                                               (* If find the empty the empty must in the end,cmt_set and append_tail is both ok *)\n                                                                               do newcmt <-- cmt_set cmt i (cmt_trans lpn data_pbn data_off clean);\n                                                                               do d <-- read_block c data_pbn data_off;\n                                                                               ret (d,(c,mk_FTL (ftl_bi_table f) (ftl_free_blocks f) newcmt (ftl_gtd_table f) (current_data_block f) (current_trans_block f)))\n                                                                    \n                                                                    | None =>  (*If it doesn't find the empty,the cmt is full *)\n                                                                               do head <-- cmt_get cmt 0;\n                                                                               match head with \n                                                                                | cmt_trans h_lpn h_pbn h_off flag'' => \n                                                                                     match flag'' with \n                                                                                       | clean =>\n                                                                                                 do newcmt' <-- remove_head cmt;\n                                                                                                 do newcmt'' <-- Some (append_tail newcmt' (cmt_trans lpn data_pbn data_off clean) );\n                                                                                                 do d <-- read_block c data_pbn data_off;\n                                                                                                 ret (d,(c,mk_FTL (ftl_bi_table f) (ftl_free_blocks f) newcmt'' (ftl_gtd_table f) (current_data_block f) (current_trans_block f))) \n                                                                                       | drity => \n                                                                                                 (* it is dirty *)\n                                                                                                 (*find the the trans_page for h_lpn *)\n                                                                                                 do newcmt' <-- remove_head cmt;\n                                                                                                 do newcmt'' <-- Some (append_tail newcmt' (cmt_trans lpn data_pbn data_off clean) );\n                                                                                                 do newf <-- ftl_update_cmt f newcmt''; \n                                                                                                 do d <-- read_block c data_pbn data_off;\n                                                                                                 match gtd_get_trans_by_lpn gtd h_lpn with\n                                                                                                     | Some _ =>\n                                                                                                          do [h_trans_pbn,h_trans_off] <-- gtd_get_trans_by_lpn gtd h_lpn;\n                                                                                                          do [c',f'] <-- copy_trans_page c newf h_lpn h_trans_pbn h_trans_off h_pbn h_off;\n                                                                                                          ret (d,(c', f'))\n                                                                                                     | None => \n                                                                                                          do [c',f'] <-- write_trans_page c newf h_lpn h_pbn h_off;\n                                                                                                          ret (d,(c',f'))\n                                                                                                  end\n                                                                                         end\n                                                                                | cmt_empty => None\n                                                                               end\n      \n                                                                    end\n                                                                                          \n                                end\n                  end\nend.                         \n\n(* Definition gtd_set_trans(c:chip) (f:FTL) (lpn:nat) :option (prod FTL) := *)\n(*   let bit := ftl_bi_table f in *)\n(*   let fbq := ftl_free_blocks f in *)\n(*   let cmt := ftl_cmt_table f in *)\n(*   let gtd := ftl_gtd_table f in *)\n(*   let cur_trans := current_trans_block f in *)\n(*   let cur_data := current_data_block f in *)\n(*   do loc <-- gtd_look_by_lpn gtd lpn;  *)\n(*   do cur_trans_bi <-- bit_get bit cur_trans; *)\n(*   match check_block_full cur_trans_bi with *)\n(*       | false => do off <-- Some (bi_used_pages cur_trans_bi); *)\n(*                  do gtd'<-- gtd_set gtd loc (gtd_trans cur_trans off); *)\n(*                  do pst <-- Some (bi_page_state cur_trans_bi); *)\n(*                  do pst' <-- pst_set pst off (ps_trans loc); *)\n(*                  do new_bi <-- Some (mk_bi (bi_state cur_trans) ((bi_used_pages cur_trans) + 1) (bi_erase_count cur_trans) pst'); *)\n(*                  do bit' <-- bit_update bit cur_trans new_bi; *)\n(*                  ret (mk_FTL bit' fbq cmt gtd' cur_data cur_trans); *)\n      \n(*       | true => do [c',f'] <-- alloc c f; *)\n\n                \nDefinition cmt_update_when_ftl_write(c:chip) (f:FTL) (lbn:block_no) (loff:nat):option (prod chip FTL) :=\n  let bit := ftl_bi_table f in\n  let fbq := ftl_free_blocks f in\n  let cmt := ftl_cmt_table f in\n  let gtd := ftl_gtd_table f in\n  let cur_trans := current_trans_block f in\n  let cur_data := current_data_block f in\n  let lpn := lbn * PAGES_PER_BLOCK + loff in\n  do bi <-- bit_get bit cur_data;\n  do poff <-- Some (pred (bi_used_pages bi) );\n  match find_cmtrecord cmt lpn 0 with\n                     (* The cmt don't have the record *)\n                     | None =>\n                           match find_empty_cmt cmt 0 with\n                                (* find the cmt is not full *)\n                               | Some i => do cmt' <-- cmt_set cmt i (cmt_trans lpn cur_data poff dirty);\n                                           ret (c,mk_FTL bit fbq cmt' gtd cur_data cur_trans)\n                               | None  =>  do record <-- cmt_get cmt 0;\n                                           match record with\n                                               | cmt_empty => None\n                                               | cmt_trans h_lpn h_pbn h_off h_flag =>\n                                                       do cmt' <-- remove_head cmt;\n                                                       do cmt'' <-- Some (append_tail cmt' (cmt_trans lpn cur_data poff dirty) );\n                                                       match h_flag with\n                                                           | clean =>  ret (c,mk_FTL bit fbq cmt'' gtd cur_data cur_trans)\n                                                           | dirty =>  (*TO DO-->Done,This is not the invalid data*)\n                                                                      match gtd_get_trans_by_lpn gtd h_lpn with\n                                                                          | Some _ =>\n                                                                                 do [h_trans_pbn,h_trans_off] <-- gtd_get_trans_by_lpn gtd h_lpn;\n                                                                                 do new_f <-- Some (mk_FTL bit fbq cmt'' gtd cur_data cur_trans);\n                                                                                 do [c'',new_f'] <-- copy_trans_page c new_f  h_lpn h_trans_pbn h_trans_off h_pbn h_off;\n                                                                                 ret (c'',new_f')\n                                                                          | None => (* The gtd loc is empty *)\n                                                                                 do f' <-- ftl_update_cmt f cmt''; \n                                                                                 do [c',f''] <-- write_trans_page c f' h_lpn h_pbn h_off;  \n                                                                                 ret (c',f'')\n                                                                       end\n                                                       end\n                                           end\n                                     \n                           end\n                     (* It is in the cmt *)                             \n                     | Some i => do record <-- cmt_get cmt i;\n                                 do [old_pbn_off,f] <-- cmt_get_trans record;\n                                 (* The old data_one *)\n                                 do [old_pbn,old_off] <-- Some old_pbn_off;\n                                 (* do cmt' <-- cmt_set cmt i (cmt_trans lpn cur_data poff dirty); *)\n                                 match find_empty_cmt cmt 0 with\n                                     | None => do cmt' <-- Some (remove_cmt cmt lpn);\n                                               do cmt'' <-- Some (append_tail cmt' (cmt_trans lpn cur_data poff dirty) );\n                                               match f with\n                                                 | dirty => do bit' <-- invalid_old_page bit old_pbn old_off;\n                                                           do new_f <-- Some (mk_FTL bit' fbq cmt'' gtd cur_data cur_trans);\n                                                           ret (c,new_f)\n                                                 | clean => (*TO DO-->Done,invalid is lazy*)\n                                                            do new_f <-- Some (mk_FTL bit fbq cmt'' gtd cur_data cur_trans);\n                                                            ret(c,new_f)\n                                               end\n                                    | Some empty_loc =>  do cmt' <-- Some (remove_cmt cmt  lpn);\n                                                         do cmt'' <-- Some (insert_cmt cmt' (cmt_trans lpn cur_data poff dirty) (pred empty_loc) );\n                                                          match f with\n                                                            | dirty => do bit' <-- invalid_old_page bit old_pbn old_off;\n                                                                      do new_f <-- Some (mk_FTL bit' fbq cmt'' gtd cur_data cur_trans);\n                                                                      ret (c,new_f)\n                                                            | clean => (*TO DO-->Done,invalid is lazy*)\n                                                                      do new_f <-- Some (mk_FTL bit fbq cmt'' gtd cur_data cur_trans);\n                                                                      ret(c,new_f)\n                                                           end\n                                 end\n                                                 \n    end.\n\nFixpoint get_lbnandoff_by_lpn (lpn:page_no) (num:nat) : option (prod nat nat) :=\n match num with\n      | O  => None\n      | S i'  => if ble_nat (i' * PAGES_PER_BLOCK) lpn then Some (i',(minus lpn (i' * PAGES_PER_BLOCK) ) ) else get_lbnandoff_by_lpn lpn i'\n end.\n\nDefinition FTL_write (c:chip) (f:FTL) (lpn:page_no) (d:data):option (prod chip FTL) :=\n  let bit := ftl_bi_table f in\n  let fbq := ftl_free_blocks f in\n  let cmt := ftl_cmt_table f in\n  let gtd := ftl_gtd_table f in\n  let cur_trans := current_trans_block f in\n  let cur_data := current_data_block f in\n  (* let lpn := lbn * PAGES_PER_BLOCK + loff in *)\n  do [lbn,loff] <-- get_lbnandoff_by_lpn lpn BLOCKS;\n  do bi <-- bit_get bit cur_data;\n  do poff <-- Some (bi_used_pages bi);\n  match check_block_is_full bi with\n      (*It is not full*)\n      | false => do [c',bi'] <-- write_data_block c bi cur_data poff d (Some (lbn,loff)) (ps_data lpn);\n                 (* update the page_state in the bit *)\n                 do bit' <-- bit_update bit cur_data bi';\n                 do new_f <-- ftl_update_bit f bit';\n                 do [new_c',new_f'] <-- cmt_update_when_ftl_write c' new_f lbn loff;\n                 ret (new_c',new_f')\n      | true  =>  do [new_data,cfx] <-- alloc_block c f;\n                  do [c',f'] <-- Some cfx;\n                  do bi' <-- bit_get (ftl_bi_table f') new_data;\n                  do bi'' <-- Some (bi_set_state bi' bs_data);\n                  do [c'',bi'''] <-- write_data_block c' bi'' new_data 0 d (Some (lbn, loff)) (ps_data lpn);\n                  do bit' <-- bit_update (ftl_bi_table f') new_data bi''';\n                  do new_f <-- Some (mk_FTL bit' (ftl_free_blocks f') (ftl_cmt_table f') (ftl_gtd_table f') new_data (current_trans_block f') );\n                  (* update the cmt *)\n                  do [new_c',new_f'] <-- cmt_update_when_ftl_write c'' new_f lbn loff;\n                  ret (new_c',new_f')                                               \n end.\n                \n(*\n\nThe Garbge Collection\n \n*)\n\nDefinition gc_copy_trans_page (c:chip) (f:FTL) (pbn:block_no) (off:nat)(gtd_loc:nat) : option (prod chip FTL) :=\n  let bit := ftl_bi_table f in\n  let gtd := ftl_gtd_table f in\n  let fbq := ftl_free_blocks f in\n  let cur_trans := current_trans_block f in\n  let cur_data := current_data_block f in\n  let cmt := ftl_cmt_table f in\n  let gtd := ftl_gtd_table f in\n  do cur_trans_info <-- bit_get bit cur_trans; \n  do cur_trans_off <-- Some (bi_used_pages cur_trans_info); \n  do [trans_d,oob] <-- read_block_oob c pbn off;\n  (* Also it can look from the page_status *)\n  (* do gtd_loc <-- gtd_look_by_record gtd pbn off 0; *)\n  match check_block_full cur_trans_info with\n     | false  => do [c',cur_bi'] <-- write_data_block c cur_trans_info cur_trans cur_trans_off trans_d oob (ps_trans gtd_loc) ;\n                 do bit' <-- bit_update bit cur_trans cur_bi';\n                 (* update the gtd *)\n                 do gtd' <-- gtd_set gtd gtd_loc (gtd_trans cur_trans cur_trans_off);\n                 do new_f <-- Some (mk_FTL bit'  fbq cmt gtd' cur_data cur_trans);\n                 ret(c',new_f)\n     \n     | true =>  do [new_trans,cfx] <-- alloc_block c f;\n                do [c',f'] <-- Some cfx;\n                do new_trans_info <-- bit_get (ftl_bi_table f') new_trans;\n                do [c',cur_bi'] <-- write_data_block c' new_trans_info new_trans 0 trans_d oob (ps_trans gtd_loc);\n                do bit' <-- bit_update bit new_trans cur_bi';\n                (* update the gtd *)\n                do gtd' <-- gtd_set gtd gtd_loc (gtd_trans new_trans 0);\n                do new_f <-- Some (mk_FTL bit' (ftl_free_blocks f') cmt gtd' cur_data new_trans);\n                ret(c',new_f)\n end.\n\nDefinition invalid_old_block(bit:block_info_table)(pbn:block_no) :option block_info_table :=\n  do bi <-- bit_get bit pbn;\n  do pst <-- Some (pst_set_all ps_invalid);\n  do bi' <-- Some (pi_set_state bi (bs_invalid) pst);\n  do bit' <-- bit_update bit pbn bi';\n  ret bit'.\n                                                     \nFixpoint  gc_trans(c:chip) (f:FTL) (pbn:block_no) (i:nat) :option (prod chip FTL) :=\n  let bit := ftl_bi_table f in\n  let fbq := ftl_free_blocks f in\n  let cmt := ftl_cmt_table f in\n  let gtd := ftl_gtd_table f in\n  let cur_trans := current_trans_block f in\n  let cur_data := current_data_block f in\n  do bi <-- bit_get bit pbn;\n  do pst <-- Some ( bi_page_state bi );\n  do ps <-- pst_get pst i;\n  match i with\n      | O => (* free_block also will do this *)\n             do bit' <-- invalid_old_block bit pbn;\n             ret(c,(mk_FTL bit' fbq cmt gtd cur_data cur_trans) )\n              \n      | S i' =>  match ps with\n                    | ps_trans gtd_loc =>  do [c',f'] <-- gc_copy_trans_page c f pbn i' gtd_loc;\n                                           gc_trans c' f' pbn i'\n                                                 \n                    | _ =>  gc_trans c f pbn i'\n                            \n                 end\n   end.\n\n(*\nTO DO Invalid the old_data,but copy_trans_page do this\n*)\n\nDefinition gc_copy_data_page (c:chip) (f:FTL) (pbn:block_no) (off:nat) (lpn:page_no): option (prod (prod nat  nat) (prod chip FTL) ) :=\n  let bit := ftl_bi_table f in\n  let gtd := ftl_gtd_table f in\n  let fbq := ftl_free_blocks f in\n  let cur_trans := current_trans_block f in\n  let cur_data := current_data_block f in\n  let cmt := ftl_cmt_table f in\n  let gtd := ftl_gtd_table f in\n  do cur_data_info <-- bit_get bit cur_data; \n  do cur_data_off <-- Some (bi_used_pages cur_data_info); \n  do [data_d,oob] <-- read_block_oob c pbn off;\n  match check_block_full cur_data_info with\n     | false  => do [c',cur_bi'] <-- write_data_block c cur_data_info cur_data cur_data_off data_d oob (ps_data lpn) ;\n                 do bit' <-- bit_update bit cur_data cur_bi';\n                 do new_f <-- Some (mk_FTL bit'  fbq cmt gtd cur_data cur_trans);\n                 ret((cur_data,cur_data_off),(c',new_f))\n     \n     | true =>  do [new_data,cfx] <-- alloc_block c f;\n                do [c',f'] <-- Some cfx;\n                do new_data_info <-- bit_get (ftl_bi_table f') new_data;\n                do [c',cur_bi'] <-- write_data_block c' new_data_info new_data 0 data_d oob (ps_data lpn);\n                do bit' <-- bit_update bit new_data cur_bi';\n                do new_f <-- Some (mk_FTL bit' (ftl_free_blocks f') cmt gtd new_data cur_trans);\n                ret((new_data,0),(c',new_f))\n     \n end.\n\nDefinition gc_data_copy_and_update (c:chip) (f:FTL) (pbn:block_no) (off:nat) (lpn:page_no): option (prod chip FTL) :=\n  let gtd := ftl_gtd_table f in\n  let cmt := ftl_cmt_table f in\n  do [old_trans,old_off] <-- gtd_get_trans_by_lpn gtd lpn;\n  do [pbn_off,cf] <-- gc_copy_data_page c f pbn off lpn;\n  do [c',f'] <-- Some cf;\n  do [new_data,new_off] <-- Some pbn_off;\n  (*update the corrsponding trans_page and gtd *)\n  do [c'',f''] <-- copy_trans_page c' f' lpn old_trans old_off new_data new_off;\n  (* update the cmt *)\n  do cmt <-- Some (ftl_cmt_table f'');\n  match cmt_in cmt lpn with\n      | false =>   ret (c'',f'')\n      | true => do loc <-- find_cmtrecord cmt lpn 0;\n                do cmt' <-- cmt_set cmt loc (cmt_trans lpn new_data new_off clean);\n                do f''' <-- (ftl_update_cmt f'' cmt');\n                ret (c'',f''')\n   end.\n                                                                                           \nFixpoint  gc_data(c:chip) (f:FTL) (pbn:block_no) (i:nat) :option (prod chip FTL) :=\n  let bit := ftl_bi_table f in\n  let fbq := ftl_free_blocks f in\n  let cmt := ftl_cmt_table f in\n  let gtd := ftl_gtd_table f in\n  let cur_trans := current_trans_block f in\n  let cur_data := current_data_block f in\n  do bi <-- bit_get bit pbn;\n  do pst <-- Some ( bi_page_state bi );\n  do ps <-- pst_get pst i;\n  match i with\n      | O => do bit' <-- invalid_old_block bit pbn;\n             ret(c,(mk_FTL bit fbq cmt gtd cur_data cur_trans) )\n              \n      | S i' =>  match ps with\n                    | ps_data lpn =>  do [c',f'] <-- gc_data_copy_and_update c f pbn i' lpn;\n                                      gc_data c' f' pbn i'\n                                                 \n                    | _ =>  gc_data c f pbn i'\n                            \n                 end\n   end.                                                                                                                              \n(*\n\nThe GC Opertions\n\nThe pbn has 3 limits:\n\n1)it can't be cur_trans\n\n2)it can't be cur_data\n\n3)it can't be in the fbq\n \n*)\n\nDefinition gc(c:chip) (f:FTL) (pbn:block_no) :option (prod chip FTL) :=\n  let bit := ftl_bi_table f in\n  let fbq := ftl_free_blocks f in\n  let cmt := ftl_cmt_table f in\n  let gtd := ftl_gtd_table f in\n  let cur_trans := current_trans_block f in\n  let cur_data := current_data_block f in\n  do bi <-- bit_get bit pbn;\n  do bs <-- Some (bi_state bi);\n  match bs with\n      | bs_trans => do [c',f'] <-- gc_trans c f pbn PAGES_PER_BLOCK;\n                    do [bit',fbq'] <-- free_block (ftl_bi_table f') (ftl_free_blocks f') pbn;\n                    do f''<-- ftl_update_bit f' bit';\n                    do f''' <-- ftl_update_fbq f'' fbq';\n                    ret(c',f''')\n      \n      | bs_data =>  do [c',f'] <-- gc_data c f pbn PAGES_PER_BLOCK;\n                    do [bit',fbq'] <-- free_block (ftl_bi_table f') (ftl_free_blocks f') pbn;\n                    do f''<-- ftl_update_bit f' bit';\n                    do f''' <-- ftl_update_fbq f'' fbq';\n                    ret(c',f''')\n\n      | bs_erased => None\n\n      | bs_invalid => None\n  end.", "meta": {"author": "zbh24", "repo": "DFTL", "sha": "685ac48f010e0fc2621e04defbeb57caee34186a", "save_path": "github-repos/coq/zbh24-DFTL", "path": "github-repos/coq/zbh24-DFTL/DFTL-685ac48f010e0fc2621e04defbeb57caee34186a/Dftl0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.29033666119826085}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n  Copyright 2015 Cornell University\n  Copyright 2016 Cornell University\n  Copyright 2017 Cornell University\n  Copyright 2018 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 usquash.\nRequire Export per_props_psquash.\n\n\n\nLemma member_iff_inhabited_mkc_apply2_mkc_usquash_per {o} :\n  forall lib (t1 t2 T : @CTerm o),\n    inhabited_type lib (mkc_apply2 (mkc_usquash_per nvarx nvary T) t1 t2)\n    <=> inhabited_type lib T.\nProof.\n  introv.\n\n  split; introv inh.\n\n  - eapply inhabited_type_respects_cequivc in inh;\n    [|apply cequivc_beta2].\n    rw @mkcv_lam_substc in inh; try (complete (intro xx; ginv)).\n\n    eapply inhabited_type_respects_cequivc in inh;\n      [|apply cequivc_beta].\n\n    autorewrite with slow in *; auto.\n\n  - eapply inhabited_type_respects_cequivc;\n    [apply cequivc_sym;apply cequivc_beta2|].\n    rw @mkcv_lam_substc; try (complete (intro xx; ginv)).\n\n    eapply inhabited_type_respects_cequivc;\n      [apply cequivc_sym;apply cequivc_beta|].\n\n    autorewrite with slow in *; auto.\nQed.\n\nLemma implies_tequality_mkc_usquash {o} :\n  forall lib (t1 t2 : @CTerm o),\n    type lib t1\n    -> type lib t2\n    -> (inhabited_type lib t1 <=> inhabited_type lib t2)\n    -> tequality lib (mkc_usquash t1) (mkc_usquash t2).\nProof.\n  introv tt1 tt2 tiff.\n  unfold mkc_usquash.\n  rw @tequality_mkc_pertype.\n  dands.\n\n  - (* type 1 *)\n    introv.\n    unfold mkc_usquash_per.\n\n    eapply type_respects_cequivc;\n      [apply cequivc_sym;apply cequivc_beta2|].\n    rw @mkcv_lam_substc; try (complete (intro xx; ginv)).\n\n    eapply type_respects_cequivc;\n      [apply cequivc_sym;apply cequivc_beta|].\n\n    autorewrite with slow in *; auto.\n\n  - (* type 2 *)\n    introv.\n    unfold mkc_psquash_per.\n\n    eapply type_respects_cequivc;\n      [apply cequivc_sym;apply cequivc_beta2|].\n    rw @mkcv_lam_substc; try (complete (intro xx; ginv)).\n\n    eapply type_respects_cequivc;\n      [apply cequivc_sym;apply cequivc_beta|].\n\n    autorewrite with slow in *; auto.\n\n  - (* extensional eq *)\n    introv.\n    allrw @member_iff_inhabited_mkc_apply2_mkc_usquash_per; tcsp.\n\n  - (* PER *)\n    unfold is_per_type; dands.\n\n    (* symmetry *)\n    + introv inh.\n      allrw @member_iff_inhabited_mkc_apply2_mkc_usquash_per; sp.\n\n    (* transitivity *)\n    + introv inh1 inh2.\n      allrw @member_iff_inhabited_mkc_apply2_mkc_usquash_per; sp.\nQed.\n\nLemma tequality_mkc_usquash {o} :\n  forall lib (t1 t2 : @CTerm o),\n    tequality lib (mkc_usquash t1) (mkc_usquash t2)\n    <=> (type lib t1\n         # type lib t2\n         # (inhabited_type lib t1 <=> inhabited_type lib t2)).\nProof.\n  introv; split; intro k; try (apply implies_tequality_mkc_usquash; tcsp);[].\n\n  unfold mkc_usquash in k.\n  rw @tequality_mkc_pertype in k; repnd.\n\n  (* let's get that t1 is a type *)\n  pose proof (k0 mkc_axiom mkc_axiom) as tt1.\n  unfold mkc_usquash_per in tt1.\n\n  eapply type_respects_cequivc in tt1;[|apply cequivc_beta2].\n  rw @mkcv_lam_substc in tt1; try (complete (intro xx; ginv)).\n  eapply type_respects_cequivc in tt1;[|apply cequivc_beta].\n  autorewrite with slow in *.\n\n  (* let's get that t2 is a type *)\n  pose proof (k1 mkc_axiom mkc_axiom) as tt2.\n  unfold mkc_usquash_per in tt2.\n\n  eapply type_respects_cequivc in tt2;[|apply cequivc_beta2].\n  rw @mkcv_lam_substc in tt2; try (complete (intro xx; ginv)).\n  eapply type_respects_cequivc in tt2;[|apply cequivc_beta].\n  autorewrite with slow in *.\n\n  dands; auto;[].\n\n  pose proof (k2 mkc_axiom mkc_axiom) as k2.\n  allrw @member_iff_inhabited_mkc_apply2_mkc_usquash_per; tcsp.\nQed.\n\nLemma sp_implies_tequality_mkc_usquash {o} :\n  forall lib (t1 t2 : @CTerm o),\n    tequality lib t1 t2\n    -> tequality lib (mkc_usquash t1) (mkc_usquash t2).\nProof.\n  introv teq.\n  apply tequality_mkc_usquash.\n  dands; eauto 3 with slow.\n\n  - apply tequality_refl in teq; auto.\n\n  - apply tequality_sym in teq; apply tequality_refl in teq; auto.\n\n  - introv; split; intro mem; eapply inhabited_type_tequality; eauto.\n    apply tequality_sym; auto.\nQed.\n\nLemma implies_equality_in_mkc_usquash {o} :\n  forall lib (a b T : @CTerm o),\n    inhabited_type lib T\n    -> equality lib a b (mkc_usquash T).\nProof.\n  introv inh.\n  unfold mkc_usquash.\n\n  apply equality_in_mkc_pertype2; dands.\n\n  - apply member_iff_inhabited_mkc_apply2_mkc_usquash_per; sp.\n\n  - apply sp_implies_tequality_mkc_usquash.\n    unfold inhabited_type in inh; exrepnd.\n    apply inhabited_implies_tequality in inh0; auto.\nQed.\n\nLemma equality_in_mkc_usquash {o} :\n  forall lib (a b T : @CTerm o),\n    equality lib a b (mkc_usquash T)\n    <=> inhabited_type lib T.\nProof.\n  introv; split; introv k; try (apply implies_equality_in_mkc_usquash; sp);[].\n  unfold mkc_usquash in k.\n\n  apply equality_in_mkc_pertype2 in k; repnd.\n  apply member_iff_inhabited_mkc_apply2_mkc_usquash_per in k0; sp.\nQed.\n\nLemma equality_mkc_usquash_in_uni {o} :\n  forall lib (t1 t2 : @CTerm o) i,\n    equality lib (mkc_usquash t1) (mkc_usquash t2) (mkc_uni i)\n    <=> (member lib t1 (mkc_uni i)\n         # member lib t2 (mkc_uni i)\n         # (inhabited_type lib t1 <=> inhabited_type lib t2)).\nProof.\n  introv.\n  sp_iff Case; introv h; repnd.\n\n  - Case \"->\".\n    apply mkc_pertype_equality_in_uni in h; repnd.\n\n    pose proof (h0 mkc_axiom mkc_axiom) as h0.\n    eapply member_respects_cequivc in h0;[|apply cequivc_beta2].\n    repeat (rw @mkcv_lam_substc in h0; try (complete (intro xx; ginv));[]).\n    eapply member_respects_cequivc in h0;[|apply cequivc_beta].\n    autorewrite with slow in *.\n\n    pose proof (h1 mkc_axiom mkc_axiom) as h1.\n    eapply member_respects_cequivc in h1;[|apply cequivc_beta2].\n    repeat (rw @mkcv_lam_substc in h1; try (complete (intro xx; ginv));[]).\n    eapply member_respects_cequivc in h1;[|apply cequivc_beta].\n    autorewrite with slow in *.\n\n    dands; auto.\n\n    pose proof (h2 mkc_axiom mkc_axiom) as h2.\n    allrw @member_iff_inhabited_mkc_apply2_mkc_usquash_per; tcsp.\n\n  - unfold mkc_usquash.\n    apply mkc_pertype_equality_in_uni.\n    dands; introv;\n      [| | |].\n\n    { eapply member_respects_cequivc;[apply cequivc_sym;apply cequivc_beta2|].\n      repeat (rw @mkcv_lam_substc; try (complete (intro xx; ginv));[]).\n      eapply member_respects_cequivc;[apply cequivc_sym;apply cequivc_beta|].\n      autorewrite with slow in *; auto. }\n\n    { eapply member_respects_cequivc;[apply cequivc_sym;apply cequivc_beta2|].\n      repeat (rw @mkcv_lam_substc; try (complete (intro xx; ginv));[]).\n      eapply member_respects_cequivc;[apply cequivc_sym;apply cequivc_beta|].\n      autorewrite with slow in *; auto. }\n\n    { repeat rw @member_iff_inhabited_mkc_apply2_mkc_usquash_per; tcsp. }\n\n    { unfold is_per_type; dands.\n\n      + introv inh.\n        allrw @member_iff_inhabited_mkc_apply2_mkc_usquash_per; sp.\n\n      + introv inh1 inh2.\n        allrw @member_iff_inhabited_mkc_apply2_mkc_usquash_per; 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_usquash.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.29033666119826085}}
{"text": "From F_mu_ref_conc_sub Require Export lang.\n\nInductive type :=\n  | Top : type\n  | TUnit : type\n  | TNat : type\n  | TBool : 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  | TForall (σ : type) (τ : {bind 1 of type})\n  | Tref (τ : type).\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\nInductive subtype : list type → type → type → Prop :=\n| sbt_var Ξ x τ : Ξ !! x = Some τ → subtype Ξ (TVar x) τ\n| sbt_refl Ξ τ : subtype Ξ τ τ\n| sbt_trans Ξ τ1 τ2 τ3 : subtype Ξ τ1 τ2 → subtype Ξ τ2 τ3 → subtype Ξ τ1 τ3\n| sbt_top Ξ τ : subtype Ξ τ Top\n| sbt_arrow Ξ σ σ' τ τ' : subtype Ξ σ' σ → subtype Ξ τ τ' →\n                        subtype Ξ (TArrow σ τ) (TArrow σ' τ')\n| sbt_forall Ξ σ τ1 τ2 : subtype (σ.[ren (+1)] :: (subst (ren (+1)) <$> Ξ)) τ1 τ2 →\n                         subtype Ξ (TForall σ τ1) (TForall σ τ2)\n| sbt_rec Ξ σ τ :\n    subtype ((TVar 1) :: (TVar 1) :: (subst (ren (+2)) <$> Ξ))\n            σ.[up (ren (+1))] τ.[ren (+1)] →\n    subtype Ξ (TRec σ) (TRec τ).\n\nFixpoint binop_res_type (op : binop) : type :=\n  match op with\n  | Add => TNat | Sub => TNat | Mult => TNat\n  | Eq => TBool | Le => TBool | Lt => TBool\n  end.\n\nInductive EqType : type → Prop :=\n  | EqTUnit : EqType TUnit\n  | EqTNat : EqType TNat\n  | EqTBool : EqType TBool\n  | EQRef τ : EqType (Tref τ).\n\nReserved Notation \"Ξ |ₜ Γ ⊢ₜ e : τ\" (at level 74, e, τ at next level).\n\nInductive typed (Ξ Γ : list type) : expr → type → Prop :=\n  | Var_typed x τ : Γ !! x = Some τ → Ξ |ₜ Γ ⊢ₜ Var x : τ\n  | Unit_typed : Ξ |ₜ Γ ⊢ₜ Unit : TUnit\n  | Nat_typed n : Ξ |ₜ Γ ⊢ₜ #n n : TNat\n  | Bool_typed b : Ξ |ₜ Γ ⊢ₜ #♭ b : TBool\n  | BinOp_typed op e1 e2 :\n     Ξ |ₜ Γ ⊢ₜ e1 : TNat → Ξ |ₜ Γ ⊢ₜ e2 : TNat →\n     Ξ |ₜ Γ ⊢ₜ BinOp op e1 e2 : binop_res_type op\n  | Pair_typed e1 e2 τ1 τ2 :\n      Ξ |ₜ Γ ⊢ₜ e1 : τ1 → Ξ |ₜ Γ ⊢ₜ e2 : τ2 → Ξ |ₜ Γ ⊢ₜ Pair e1 e2 : TProd τ1 τ2\n  | Fst_typed e τ1 τ2 :\n      Ξ |ₜ Γ ⊢ₜ 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 τ3 :\n     Ξ |ₜ Γ ⊢ₜ e0 : TSum τ1 τ2 → Ξ |ₜ τ1 :: Γ ⊢ₜ e1 : τ3 →\n     Ξ |ₜ τ2 :: Γ ⊢ₜ e2 : τ3 → Ξ |ₜ Γ ⊢ₜ Case e0 e1 e2 : τ3\n  | If_typed e0 e1 e2 τ :\n     Ξ |ₜ Γ ⊢ₜ e0 : TBool → Ξ |ₜ Γ ⊢ₜ e1 : τ → Ξ |ₜ Γ ⊢ₜ e2 : τ →\n     Ξ |ₜ Γ ⊢ₜ If e0 e1 e2 : τ\n  | Rec_typed e τ1 τ2 :\n     Ξ |ₜ TArrow τ1 τ2 :: τ1 :: Γ ⊢ₜ e : τ2 → Ξ |ₜ Γ ⊢ₜ Rec e : TArrow τ1 τ2\n  | Lam_typed e τ1 τ2 :\n      Ξ |ₜ τ1 :: Γ ⊢ₜ e : τ2 → Ξ |ₜ Γ ⊢ₜ Lam e : TArrow τ1 τ2\n  | LetIn_typed e1 e2 τ1 τ2 :\n      Ξ |ₜ Γ ⊢ₜ e1 : τ1 → Ξ |ₜ τ1 :: Γ ⊢ₜ e2 : τ2 → Ξ |ₜ Γ ⊢ₜ LetIn e1 e2 : τ2\n  | Seq_typed e1 e2 τ1 τ2 :\n      Ξ |ₜ Γ ⊢ₜ e1 : τ1 → Ξ |ₜ Γ ⊢ₜ e2 : τ2 → Ξ |ₜ Γ ⊢ₜ Seq e1 e2 : τ2\n  | App_typed e1 e2 τ1 τ2 :\n     Ξ |ₜ Γ ⊢ₜ e1 : TArrow τ1 τ2 → Ξ |ₜ Γ ⊢ₜ e2 : τ1 → Ξ |ₜ Γ ⊢ₜ App e1 e2 : τ2\n  | TLam_typed e σ τ :\n     σ.[ren (+1)] :: (subst (ren (+1)) <$> Ξ) |ₜ subst (ren (+1)) <$> Γ ⊢ₜ e : τ →\n     Ξ |ₜ Γ ⊢ₜ TLam e : TForall σ τ\n  | TApp_typed e σ τ τ' : Ξ |ₜ Γ ⊢ₜ e : TForall σ τ → subtype Ξ τ' σ →\n      Ξ |ₜ Γ ⊢ₜ TApp e : τ.[τ'/]\n  | TFold e τ : Ξ |ₜ Γ ⊢ₜ e : τ.[TRec τ/] → Ξ |ₜ Γ ⊢ₜ Fold e : TRec τ\n  | TUnfold e τ : Ξ |ₜ Γ ⊢ₜ e : TRec τ → Ξ |ₜ Γ ⊢ₜ Unfold e : τ.[TRec τ/]\n  | TFork e : Ξ |ₜ Γ ⊢ₜ e : TUnit → Ξ |ₜ Γ ⊢ₜ Fork e : TUnit\n  | TAlloc e τ : Ξ |ₜ Γ ⊢ₜ e : τ → Ξ |ₜ Γ ⊢ₜ Alloc e : Tref τ\n  | TLoad e τ : Ξ |ₜ Γ ⊢ₜ e : Tref τ → Ξ |ₜ Γ ⊢ₜ Load e : τ\n  | TStore e e' τ : Ξ |ₜ Γ ⊢ₜ e : Tref τ → Ξ |ₜ Γ ⊢ₜ e' : τ →\n      Ξ |ₜ Γ ⊢ₜ Store e e' : TUnit\n  | TCAS e1 e2 e3 τ :\n     EqType τ → Ξ |ₜ Γ ⊢ₜ e1 : Tref τ → Ξ |ₜ Γ ⊢ₜ e2 : τ → Ξ |ₜ Γ ⊢ₜ e3 : τ →\n     Ξ |ₜ Γ ⊢ₜ CAS e1 e2 e3 : TBool\n  | TSub e τ τ' : Ξ |ₜ Γ ⊢ₜ e : τ → subtype Ξ τ τ' → Ξ |ₜ Γ ⊢ₜ e : τ'\nwhere \"Ξ |ₜ Γ ⊢ₜ e : τ\" := (typed Ξ Γ e τ).\n\n(* Lemma typed_subst_invariant Ξ Γ e τ s1 s2 : *)\n(*   Ξ |ₜ Γ ⊢ₜ e : τ → (∀ x, x < length Γ → s1 x = s2 x) → e.[s1] = e.[s2]. *)\n(* Proof. *)\n(*   intros Htyped; revert s1 s2. *)\n(*   assert (∀ x Γ, x < length (subst (ren (+1)) <$> Γ) → x < length Γ). *)\n(*   { intros ??. by rewrite fmap_length. } *)\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. *)\n(* Qed. *)\n(* Lemma n_closed_invariant n (e : expr) s1 s2 : *)\n(*   (∀ f, e.[upn n f] = e) → (∀ x, x < n → s1 x = s2 x) → e.[s1] = e.[s2]. *)\n(* Proof. *)\n(*   intros Hnc. specialize (Hnc (ren (+1))). *)\n(*   revert n Hnc s1 s2. *)\n(*   induction e => m Hmc s1 s2 H1; asimpl in *; try f_equal; *)\n(*     try (match goal with H : _ |- _ => eapply H end; eauto; *)\n(*          try inversion Hmc; try match goal with H : _ |- _ => by rewrite H end; *)\n(*          fail). *)\n(*   - apply H1. rewrite iter_up in Hmc. destruct lt_dec; try lia. *)\n(*     asimpl in *. injection Hmc as Hmc. unfold var in *. omega. *)\n(*   - unfold upn in *. *)\n(*     change (e.[up (up (upn m (ren (+1))))]) with *)\n(*     (e.[iter (S (S m)) up (ren (+1))]) in *. *)\n(*     apply (IHe (S (S m))). *)\n(*     + inversion Hmc; match goal with H : _ |- _ => (by rewrite H) end. *)\n(*     + intros [|[|x]] H2; [by cbv|by cbv |]. *)\n(*       asimpl; rewrite H1; auto with lia. *)\n(*   - apply (IHe (S m)). *)\n(*     + inversion Hmc; match goal with H : _ |- _ => (by rewrite H) end. *)\n(*     + intros [|x] H2; [by cbv |]. *)\n(*       asimpl; rewrite H1; auto with lia. *)\n(*   - apply (IHe0 (S m)). *)\n(*     + inversion Hmc; match goal with H : _ |- _ => (by rewrite H) end. *)\n(*     + intros [|x] H2; [by cbv |]. *)\n(*       asimpl; rewrite H1; auto with lia. *)\n(*   - change (e1.[up (upn m (ren (+1)))]) with *)\n(*     (e1.[iter (S m) up (ren (+1))]) in *. *)\n(*     apply (IHe0 (S m)). *)\n(*     + inversion Hmc; match goal with H : _ |- _ => (by rewrite H) end. *)\n(*     + intros [|x] H2; [by cbv |]. *)\n(*       asimpl; rewrite H1; auto with lia. *)\n(*   - change (e2.[up (upn m (ren (+1)))]) with *)\n(*     (e2.[upn (S m) (ren (+1))]) in *. *)\n(*     apply (IHe1 (S m)). *)\n(*     + inversion Hmc; match goal with H : _ |- _ => (by rewrite H) end. *)\n(*     + intros [|x] H2; [by cbv |]. *)\n(*       asimpl; rewrite H1; auto with lia. *)\n(* Qed. *)\n\nFixpoint env_subst (vs : list val) : var → expr :=\n  match vs with\n  | [] => ids\n  | v :: vs' => (of_val 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\n(* Lemma typed_n_closed Γ τ e : Γ ⊢ₜ e : τ → (∀ f, e.[upn (length Γ) f] = e). *)\n(* Proof. *)\n(*   intros H. induction H => f; asimpl; simpl in *; auto with f_equal. *)\n(*   - apply lookup_lt_Some in H. rewrite iter_up. destruct lt_dec; auto with lia. *)\n(*   - f_equal. apply IHtyped. *)\n(*   - by f_equal; rewrite map_length in IHtyped. *)\n(* Qed. *)\n\n(** Weakening *)\n(* Lemma context_gen_weakening ξ Γ' Γ e τ : *)\n(*   Γ' ++ Γ ⊢ₜ e : τ → *)\n(*   Γ' ++ ξ ++ Γ ⊢ₜ e.[upn (length Γ') (ren (+ (length ξ)))] : τ. *)\n(* Proof. *)\n(*   intros H1. *)\n(*   remember (Γ' ++ Γ) as Ξ. revert Γ' Γ ξ HeqΞ. *)\n(*   induction H1 => Γ1 Γ2 ξ HeqΞ; subst; asimpl in *; eauto using typed. *)\n(*   - rewrite iter_up; destruct lt_dec as [Hl | Hl]. *)\n(*     + constructor. rewrite lookup_app_l; trivial. by rewrite lookup_app_l in H. *)\n(*     + asimpl. constructor. rewrite lookup_app_r; auto with lia. *)\n(*       rewrite lookup_app_r; auto with lia. *)\n(*       rewrite lookup_app_r in H; auto with lia. *)\n(*       match goal with *)\n(*         |- _ !! ?A = _ => by replace A with (x - length Γ1) by lia *)\n(*       end. *)\n(*   - econstructor; eauto. by apply (IHtyped2 (_::_)). by apply (IHtyped3 (_::_)). *)\n(*   - constructor. by apply (IHtyped (_ :: _ :: _)). *)\n(*   - constructor. by apply (IHtyped (_ :: _)). *)\n(*   - econstructor; eauto. by apply (IHtyped2 (_::_)). *)\n(*   - constructor. *)\n(*     specialize (IHtyped *)\n(*       (subst (ren (+1)) <$> Γ1) (subst (ren (+1)) <$> Γ2) (subst (ren (+1)) <$> ξ)). *)\n(*     asimpl in *. rewrite ?map_length in IHtyped. *)\n(*     repeat rewrite fmap_app. apply IHtyped. *)\n(*     by repeat rewrite fmap_app. *)\n(* Qed. *)\n\n(* Lemma context_weakening ξ Γ e τ : *)\n(*   Γ ⊢ₜ e : τ → ξ ++ Γ ⊢ₜ e.[(ren (+ (length ξ)))] : τ. *)\n(* Proof. eapply (context_gen_weakening _ []). Qed. *)\n\n(* Lemma closed_context_weakening ξ Γ e τ : *)\n(*   (∀ f, e.[f] = e) → Γ ⊢ₜ e : τ → ξ ++ Γ ⊢ₜ e : τ. *)\n(* Proof. intros H1 H2. erewrite <- H1. by eapply context_weakening. Qed. *)\n", "meta": {"author": "amintimany", "repo": "F_mu_ref_conc_sub", "sha": "d5c154e11bc646c8e474e87b6a9959db93ec733e", "save_path": "github-repos/coq/amintimany-F_mu_ref_conc_sub", "path": "github-repos/coq/amintimany-F_mu_ref_conc_sub/F_mu_ref_conc_sub-d5c154e11bc646c8e474e87b6a9959db93ec733e/typing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297745935070808, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.29033665479135734}}
{"text": "Require Import floyd.proofauto.\nImport ListNotations.\nLocal Open Scope logic.\n\nRequire Import sha.spec_sha.\nRequire Import sha.hmac_common_lemmas.\n\nRequire Import sha.hkdf.\nRequire Import sha.spec_hmac.\nRequire Import sha.spec_hkdf.\nRequire Import sha.hkdf_functional_prog.\n\nLemma body_hkdf_extract: semax_body Hkdf_VarSpecs Hkdf_FunSpecs \n       f_HKDF_extract HKDF_extract_spec.\nProof.\nstart_function.\nrename H into LenSalt. rename H0 into LenSecret.\nfreeze [0;2;3;4] FR1.\nassert_PROP (isptr salt) as Ptr_salt.\n{ unfold data_block. normalize. rewrite data_at_isptr. entailer!. }\napply vst_lemmas.isptrD in Ptr_salt. destruct Ptr_salt as [sb [si SLT]]. subst salt.\nthaw FR1.\nidtac \"Timing the call to HMAC\".\nTime forward_call (out, SALT, secret, SECRET, kv, shmd, sb, si).\napply extract_exists_pre. intros Hmac. \nidtac \"Timing the normalize\". Time normalize. (*Coq8.6: 2secs*)\n(*yields \nH: ByteBitRelations.bytesToBits\n      (HMAC256_functional_prog.HMAC256 (CONT SECRET) (CONT SALT)) =\n    verif_hmac_crypto.bitspec SALT SECRET\nH0 : forall\n       (A : Comp.OracleComp\n              (HMAC_spec_abstract.HMAC_Abstract.Message\n                 HMAC256_isPRF.PARS256.P)\n              (Bvector.Bvector ShaInstantiation.c) bool)\n       (Awf : DistSem.well_formed_oc A), verif_hmac_crypto.CRYPTO A Awf\n and substitutes Hmac. *)\nrename H into HypHmacBits. rename H0 into HmacCrypto.\nremember (HMAC256_functional_prog.HMAC256 (CONT SECRET) (CONT SALT)) as Hmac. rename HeqHmac into HypHmac. \n\n(*idtac \"Timing the Intros\". Time Intros. (*Coq8.6: 146s*) (*Coq8.5: 77.468 secs (77.25u,0.015s)*)\n(*yields\nH : Hmac = HMAC256_functional_prog.HMAC256 (CONT SECRET) (CONT SALT)\nH0 : ByteBitRelations.bytesToBits Hmac =\n     verif_hmac_crypto.bitspec SALT SECRET\nH1 : forall\n       (A : Comp.OracleComp\n              (HMAC_spec_abstract.HMAC_Abstract.Message\n                 HMAC256_isPRF.PARS256.P)\n              (Bvector.Bvector ShaInstantiation.c) bool)\n       (Awf : DistSem.well_formed_oc A), verif_hmac_crypto.CRYPTO A Awf,\nso the same except for the substitution*)\n(*rename H into HypHmac. rename H0 into HypHmacBits. Intros. rename H1 into HmacCrypto.*)*)\n\nassert_PROP (isptr out) as Ptr_out.\n{ unfold data_block. normalize. rewrite data_at_isptr. entailer!. }\nforward_if (PROP ( )\n   LOCAL (temp _t'1 out; temp _out_key out; \n   temp _out_len olen; temp _salt (Vptr sb si); temp _salt_len (Vint (Int.repr (LEN SALT)));\n   temp _secret secret; temp _secret_len (Vint (Int.repr (LEN SECRET)));\n   gvar sha._K256 kv)\n   SEP (K_vector kv; data_block shmd Hmac out; initPostKey (Vptr sb si) (CONT SALT);\n   data_block Tsh (CONT SECRET) secret; data_at_ Tsh tuint olen)).\n{ apply denote_tc_test_eq_split. \n  + unfold data_block. normalize.\n    apply sepcon_valid_pointer1.\n    apply sepcon_valid_pointer1.\n    apply sepcon_valid_pointer1. \n    apply sepcon_valid_pointer2. apply data_at_valid_ptr.\n    apply readable_nonidentity. apply writable_readable; trivial.\n    rewrite HMAC_Zlength; simpl; omega.\n  + apply valid_pointer_zero. }\n{ subst out; contradiction. }\n{ clear H; forward. entailer!. }\n\nforward. forward. \nunfold HKDF_extract. cancel. \nTime Qed.\n(*Coq 8.6: 2.5 secs*)\n(*Feb 23rd 2017 (Coq8.5pl2): Finished transaction in 24.859 secs (17.937u,0.s) (successful)*)\n (*earlier: Finished transaction in 5.781 secs (4.89u,0.s) (successful)*)", "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/verif_hkdf_extract.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.29033665479135723}}
{"text": "From iris.proofmode Require Import\n  proofmode.\n\nFrom caml5 Require Import\n  prelude.\nFrom caml5 Require Export\n  base.\nFrom caml5.algebra Require Import\n  lib.auth_nat_max.\n\nClass AuthNatMaxG Σ := {\n  auth_nat_max_G_inG : inG Σ auth_nat_max_R ;\n}.\n#[local] Existing Instance auth_nat_max_G_inG.\n\nDefinition auth_nat_max_Σ := #[\n  GFunctor auth_nat_max_R\n].\n#[global] Instance subG_auth_nat_max_Σ Σ :\n  subG auth_nat_max_Σ Σ →\n  AuthNatMaxG Σ.\nProof.\n  solve_inG.\nQed.\n\nSection auth_nat_max_G.\n  Context `{!AuthNatMaxG Σ}.\n  Implicit Types n m p : nat.\n\n  Definition auth_nat_max_auth γ dq n :=\n    own γ (auth_nat_max_auth dq n).\n  Definition auth_nat_max_frag γ n :=\n    own γ (auth_nat_max_frag n).\n\n  #[global] Instance auth_nat_max_auth_timeless γ dq n :\n    Timeless (auth_nat_max_auth γ dq n).\n  Proof.\n    apply _.\n  Qed.\n  #[global] Instance auth_nat_max_auth_persistent γ n :\n    Persistent (auth_nat_max_auth γ DfracDiscarded n).\n  Proof.\n    apply _.\n  Qed.\n  #[global] Instance auth_nat_max_frag_timeless γ n :\n    Timeless (auth_nat_max_frag γ n).\n  Proof.\n    apply _.\n  Qed.\n  #[global] Instance auth_nat_max_frag_persistent γ n :\n    Persistent (auth_nat_max_frag γ n).\n  Proof.\n    apply _.\n  Qed.\n\n  #[global] Instance auth_nat_max_auth_fractional γ n :\n    Fractional (λ q, auth_nat_max_auth γ (DfracOwn q) n).\n  Proof.\n    intros ?*. rewrite -own_op -auth_nat_max_auth_dfrac_op //.\n  Qed.\n  #[global] Instance auth_nat_max_auth_as_fractional γ q n :\n    AsFractional (auth_nat_max_auth γ (DfracOwn q) n) (λ q, auth_nat_max_auth γ (DfracOwn q) n) q.\n  Proof.\n    split; done || apply _.\n  Qed.\n\n  Lemma auth_nat_max_auth_persist γ dq n :\n    auth_nat_max_auth γ dq n ==∗\n    auth_nat_max_auth γ DfracDiscarded n.\n  Proof.\n    iApply own_update. apply auth_nat_max_auth_persist.\n  Qed.\n\n  Lemma auth_nat_max_alloc n :\n    ⊢ |==> ∃ γ,\n      auth_nat_max_auth γ (DfracOwn 1) n.\n  Proof.\n    iMod (own_alloc (auth_nat_max.auth_nat_max_auth (DfracOwn 1) n)) as \"(% & ?)\".\n    { apply auth_nat_max_auth_valid. }\n    naive_solver.\n  Qed.\n\n  Lemma auth_nat_max_auth_valid γ dq a :\n    auth_nat_max_auth γ dq a -∗\n    ⌜✓ dq⌝.\n  Proof.\n    iIntros. iDestruct (own_valid with \"[$]\") as %?%auth_nat_max_auth_dfrac_valid. done.\n  Qed.\n  Lemma auth_nat_max_auth_combine γ dq1 n1 dq2 n2 :\n    auth_nat_max_auth γ dq1 n1 -∗\n    auth_nat_max_auth γ dq2 n2 -∗\n      auth_nat_max_auth γ (dq1 ⋅ dq2) n1 ∗\n      ⌜n1 = n2⌝.\n  Proof.\n    iIntros \"H●1 H●2\". iCombine \"H●1 H●2\" as \"H●\".\n    iDestruct (own_valid with \"H●\") as %(? & <-)%auth_nat_max_auth_dfrac_op_valid.\n    rewrite -auth_nat_max_auth_dfrac_op. naive_solver.\n  Qed.\n  Lemma auth_nat_max_auth_valid_2 γ dq1 n1 dq2 n2 :\n    auth_nat_max_auth γ dq1 n1 -∗\n    auth_nat_max_auth γ dq2 n2 -∗\n    ⌜✓ (dq1 ⋅ dq2) ∧ n1 = n2⌝.\n  Proof.\n    iIntros \"H●1 H●2\".\n    iDestruct (auth_nat_max_auth_combine with \"H●1 H●2\") as \"(H● & %)\".\n    iDestruct (auth_nat_max_auth_valid with \"H●\") as %?.\n    done.\n  Qed.\n  Lemma auth_nat_max_auth_agree γ dq1 n1 dq2 n2 :\n    auth_nat_max_auth γ dq1 n1 -∗\n    auth_nat_max_auth γ dq2 n2 -∗\n    ⌜n1 = n2⌝.\n  Proof.\n    iIntros \"H●1 H●2\".\n    iDestruct (auth_nat_max_auth_valid_2 with \"H●1 H●2\") as %?. naive_solver.\n  Qed.\n  Lemma auth_nat_max_auth_exclusive γ n1 n2 :\n    auth_nat_max_auth γ (DfracOwn 1) n1 -∗\n    auth_nat_max_auth γ (DfracOwn 1) n2 -∗\n    False.\n  Proof.\n    iIntros \"H●1 H●2\".\n    iDestruct (auth_nat_max_auth_valid_2 with \"H●1 H●2\") as %(? & _). done.\n  Qed.\n\n  Lemma auth_nat_max_frag_0 γ :\n    ⊢ |==> auth_nat_max_frag γ 0.\n  Proof.\n    iApply own_unit.\n  Qed.\n  Lemma auth_nat_max_frag_get γ q n :\n    auth_nat_max_auth γ q n -∗\n    auth_nat_max_frag γ n.\n  Proof.\n    apply own_mono, auth_nat_max_included.\n  Qed.\n  Lemma auth_nat_max_frag_le {γ n} n' :\n    n' ≤ n →\n    auth_nat_max_frag γ n -∗\n    auth_nat_max_frag γ n'.\n  Proof.\n    intros. apply own_mono, auth_nat_max_frag_mono. done.\n  Qed.\n\n  Lemma auth_nat_max_valid γ dq n m :\n    auth_nat_max_auth γ dq n -∗\n    auth_nat_max_frag γ m -∗\n    ⌜m ≤ n⌝.\n  Proof.\n    iIntros \"H●1 H●2\".\n    iDestruct (own_valid_2 with \"H●1 H●2\") as %?%auth_nat_max_both_dfrac_valid.\n    naive_solver.\n  Qed.\n\n  Lemma auth_nat_max_update {γ n} n' :\n    n ≤ n' →\n    auth_nat_max_auth γ (DfracOwn 1) n ==∗\n    auth_nat_max_auth γ (DfracOwn 1) n'.\n  Proof.\n    iIntros \"% H●\".\n    iMod (own_update with \"H●\"); first apply auth_nat_max_auth_update; done.\n  Qed.\nEnd auth_nat_max_G.\n\n#[global] Opaque auth_nat_max_auth.\n#[global] Opaque auth_nat_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/base_logic/lib/auth_nat_max.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.29028163517422334}}
{"text": "Set Warnings \"-notation-overridden\".\n\nRequire Import Category.Lib.\nRequire Export Category.Theory.Morphisms.\nRequire Export Category.Structure.BiCCC.\nRequire Export Category.Structure.Constant.\n\nGeneralizable All Variables.\nSet Primitive Projections.\nSet Universe Polymorphism.\nUnset Transparent Obligations.\n\nProgram Instance Coq : Category := {\n  obj     := Type;\n  hom     := fun A B : Type => A -> B;\n  homset  := fun _ _ => {| equiv := fun f g => forall x, f x = g x |};\n  id      := fun _ x => x;\n  compose := fun _ _ _ g f x => g (f x)\n}.\nNext Obligation. equivalence; congruence. Qed.\nNext Obligation. proper; congruence. Qed.\n\nProgram Instance Coq_Terminal : @Terminal Coq := {\n  terminal_obj := unit : Type;\n  one := fun _ a => tt\n}.\nNext Obligation. destruct (f x0), (g x0); reflexivity. Qed.\n\nProgram Instance Coq_Cartesian : @Cartesian Coq := {\n  product_obj := prod;\n  fork := fun _ _ _ f g x => (f x, g x);\n  exl  := fun _ _ p => fst p;\n  exr  := fun _ _ p => snd p\n}.\nNext Obligation. proper; congruence. Qed.\nNext Obligation.\n  intros; simplify; intros.\n  - rewrite H; reflexivity.\n  - rewrite H; reflexivity.\n  - intros; simplify.\n    rewrite <- H, <- H0.\n    rewrite <- surjective_pairing; reflexivity.\nQed.\n\nProgram Instance Coq_Closed : @Closed Coq _ := {\n  exponent_obj := Basics.arrow;\n  exp_iso := fun _ _ _ =>\n    {| to   := {| morphism := fun f a b => f (a, b) |}\n     ; from := {| morphism := fun f p => f (fst p) (snd p) |} |}\n}.\nNext Obligation. proper; extensionality X0; congruence. Qed.\nNext Obligation. proper; congruence. Qed.\n\nProgram Instance Coq_Initial : Initial Coq := {\n  terminal_obj := False;\n  one := fun _ _ => False_rect _ _\n}.\nNext Obligation. contradiction. Qed.\n\nProgram Instance Coq_Cocartesian : @Cocartesian Coq := {\n  product_obj := sum;\n  fork := fun _ _ _ f g x =>\n            match x with\n            | Datatypes.inl v => f v\n            | Datatypes.inr v => g v\n            end;\n  exl  := fun _ _ p => Datatypes.inl p;\n  exr  := fun _ _ p => Datatypes.inr p\n}.\nNext Obligation.\n  split; intros.\n    split; intros;\n    rewrite H; reflexivity.\n  destruct x0; firstorder.\nQed.\n\nLemma injectivity_is_monic `(f : x ~> y) :\n  (∀ x y, f x = f y → x = y) ↔ Monic f.\nProof.\n  split.\n  - intros HA.\n    constructor.\n    autounfold in *; intros ??? HB.\n    simpl in *; intros.\n    apply HA, HB.\n  - intros HA ?? HB.\n    pose (fun (_ : unit) => x0) as const_x.\n    pose (fun (_ : unit) => y0) as const_y.\n    destruct HA.\n    specialize (monic unit const_x const_y).\n    unfold const_x in monic.\n    unfold const_y in monic.\n    eapply monic; eauto.\n    simpl; intuition.\n    exact tt.\nQed.\n\nLemma surjectivity_is_epic `(f : x ~> y) :\n  (∀ y, exists x, f x = y)%type ↔ Epic f.\nProof.\n  split.\n  - intros HA.\n    constructor.\n    autounfold in *; intros ??? HB.\n    simpl in *; intros.\n    specialize (HA x0).\n    destruct HA as [? HA].\n    rewrite <- HA.\n    apply HB.\n  - intros HA ?.\n    destruct HA.\n    specialize epic with (z := Prop).\n    specialize epic with (g1 := fun y0 => (exists x0, f x0 = y0)%type).\n    simpl in *.\n    specialize epic with (g2 := fun y => True).\n    erewrite epic.\n      constructor.\n    intros.\n    Axiom propositional_extensionality : forall P : Prop, P -> P = True.\n    apply propositional_extensionality.\n    exists x0.\n    reflexivity.\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/category-theory/Instance/Coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.2902650722165359}}
{"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\n(** * BaseDef.v: Extensions to the standard library and the library of \n   Paulin & Audebaud *)\n\nSet Implicit Arguments.\n\nRequire Import Bool.\nRequire Import List.\nRequire Export Relations.\nRequire Export Cover.\nRequire Export Prelude.\nRequire Import BoolEquality.\nRequire Import Even Div2 Wf_nat.\nRequire Import CCMisc.\nRequire Export Coq.Program.Basics.\n\nDeclare Module Univ : Universe.\n\nModule CP := CoverFun Univ.\n\nExport Univ CP RP PP MP UP.\n\nClose Scope nat_scope.\nOpen Scope U_scope.\n\n(* TODO: remove this once added to ALEA *)\nLemma Unth_prod : forall n m, [1/]1+n * [1/]1+m == [1/]1+(pred (S n * S m)).\nProof.\n intros; apply Unth_eq; simpl.\n rewrite plus_Nmult_distr.\n rewrite Nmult_Umult_assoc_right; auto.\n rewrite Nmult_n_Unth.\n rewrite Nmult_mult_assoc.\n rewrite Nmult_Unth_simpl_right.\n rewrite Nmult_n_Unth; auto.\nQed.\n\nLemma Unth_pow : forall n c, ([1/]1+n) ^ c == [1/]1+pred ((S n) ^ c).\nProof.\n induction c.\n simpl; auto.\n simpl; rewrite IHc, Unth_prod.\n replace \n  (S n * S (pred ((S n) ^ c)))%nat with\n  ((S n) ^ c + n * (S n) ^ c)%nat; trivial.\n change \n  (S n * S (pred ((S n) ^ c)))%nat with \n  ((S (pred ((S n) ^ c))) + n * S (pred ((S n) ^ c)))%nat.\n rewrite <- (S_pred ((S n) ^ c) 0); trivial.\n apply pow_lt_0; auto with arith.\nQed.\n\nLemma Unth_le_pow : forall n c, (0 < c)%nat -> ([1/]1+n) ^ c <= [1/]1+n ^ c.\nProof.\n intros n c Hle; apply Ole_trans with ([1/]1+pred ((S n) ^ c)).\n rewrite Unth_pow; trivial.\n apply Unth_anti_mon.\n induction c.\n inversion Hle.\n simpl in IHc |- *.\n destruct c.\n simpl; trivial.\n apply le_trans with (n * ((S n) ^ (S c)))%nat.\n apply mult_le_compat_l.\n apply le_trans with (pred ((S n) ^ (S c)))%nat; auto with arith.\n rewrite pred_of_minus.\n assert (0 < (S n) ^ (S c))%nat by (apply pow_lt_0; auto with arith).\n omega.\nQed.\n\nLemma mu_fone_0 : forall A d, \n 0 == mu d (fone A) -> \n forall f, 0 == mu d f.\nProof.\n intros; apply Ole_antisym.\n trivial.\n rewrite H; apply mu_monotonic; intro; trivial.\nQed. \n\nHint Resolve mu_fone_0.\n\nLemma mu_fone_0_eq : forall A d, \n 0 == mu d (fone A) -> forall f g, mu d f == mu d g.\nProof.\n intros; apply Oeq_trans with (0:U); [symmetry |]; apply mu_fone_0; trivial.\nQed.\n\nLemma mu_0 : forall A (d:Distr A), mu d (fun _ => 0) == 0.\nProof.\n intros; rewrite (mu_cte d 0); trivial.\nQed.\n\n\n (** [Uabs_diff a b] corresponds to [|a - b|] in the interval [[0,1]].\n     When [~a == b], one of the subtractions in the sum will underflow and the \n     other one will correspond to the absolute value of the subtraction *)\n Definition Uabs_diff (a b:U) := (a - b) + (b - a).\n\n Add Morphism Uabs_diff \n with signature Oeq (O:=U) ==> Oeq (O:=U) ==> Oeq (O:=U) \n as Uabs_diff_morphism.\n Proof.\n  unfold Uabs_diff; intros.\n  rewrite H; rewrite H0; auto.\n Qed.\n\n Lemma Uabs_diff_sym : forall x y, Uabs_diff x y == Uabs_diff y x.\n Proof. \n  unfold Uabs_diff; intros; trivial. \n Qed.\n\n Lemma Uabs_diff_compat_eq : forall x, Uabs_diff x x == 0.\n Proof.\n  unfold Uabs_diff; intros.\n  rewrite Uminus_le_zero; auto.\n Qed.\n\n Lemma Uabs_diff_compat_le : forall x y, x <= y -> Uabs_diff x y == y - x.\n Proof.\n  unfold Uabs_diff; intros.\n  rewrite Uminus_le_zero ; trivial.\n Qed.\n\n Lemma Uabs_diff_zero : forall x y,  Uabs_diff x y == 0 <-> x==y.\n Proof.\n  unfold Uabs_diff; split; intros H.\n  apply (Ueq_orc x y); [auto|auto|].\n  intro H'.\n  apply (Ule_total x y); [auto|intro H''|intro H''].\n    absurd (0 == x - y + (y - x))%U.\n      rewrite Uplus_sym.\n      apply Uplus_neq_zero_left.\n      apply Uminus_lt_non_zero.\n      apply Ule_diff_lt; assumption.\n      apply Oeq_sym in H; assumption.\n    absurd (0 == x - y + (y - x))%U.\n      apply Uplus_neq_zero_left.\n      apply Uminus_lt_non_zero.\n      apply Ule_diff_lt; [assumption|auto].\n      apply Oeq_sym in H; assumption.\n\n  rewrite H, Uminus_eq; auto.\n Qed.\n\n Section UMINUS_TRIANGLE_INEQ.\n\n  Variables a b c : U.\n  Hypothesis hyp : a<=b.\n\n  (* c <= a <= b *)\n  Lemma Uminus_triangle_ineq1 : \n   c <= a ->\n   b - a <= (a - c) + (b - c).\n  Proof.\n   intros; apply Ole_trans with (b - c); auto.\n  Qed.\n\n  (* a <= c <= b *)\n  Lemma Uminus_triangle_ineq2 : \n   a <= c ->\n   c <= b ->\n   b - a <= (c - a) + (b - c).\n  Proof.\n   intros; assert ((c-a) <= c).\n   apply Uplus_le_perm_left; trivial.\n   rewrite Uplus_sym.\n   rewrite <- (Uminus_assoc_right _ _ _ H0 H1).\n   rewrite (Uminus_assoc_right _ _ _ (Ole_refl c) H).\n   rewrite (Uminus_le_zero _ _ (Ole_refl c)); Usimpl; trivial.\n  Qed.\n  \n  (* a <= b <= c *)\n  Lemma Uminus_triangle_ineq3 :\n   b <= c ->\n   b - a <= c - a + (c - b).\n  Proof.\n   intros; apply Ole_trans with (c-a).\n   apply Uminus_le_compat_left; trivial.\n   apply Ule_plus_right.\n  Qed.\n\n  Lemma Uabs_diff_triangle_ineq_simpl : \n   Uabs_diff a b <= Uabs_diff a c + Uabs_diff c b.\n  Proof.\n   unfold Uabs_diff.\n   rewrite (Uminus_le_zero _ _ hyp).\n   apply (Ule_total a c); trivial;\n    intros H; rewrite (Uminus_le_zero _ _ H); \n    repeat (rewrite Uplus_zero_left); repeat (rewrite Uplus_zero_right).\n   apply (Ule_total c b); trivial; intros H0; rewrite (Uminus_le_zero _ _ H0);\n    repeat (rewrite Uplus_zero_left); repeat (rewrite Uplus_zero_right).\n   apply Uminus_triangle_ineq2; assumption.\n   apply Uminus_triangle_ineq3; assumption.\n   assert (c<=b) by (apply Ole_trans with a; trivial).\n   rewrite (Uminus_le_zero _ _ H0); rewrite Uplus_zero_left.\n   apply Uminus_triangle_ineq1; assumption.\n  Qed.\n\n  Lemma Uplus_minus_le : forall x y z, (x + y) - z <= x + (y - z).\n  Proof.\n   intros.\n   apply (Ule_total y z); trivial; intros.\n   auto.\n   apply (Ule_total y ([1-] x)); trivial; intros.\n   rewrite <- Uplus_minus_assoc_right; trivial.\n   apply Uplus_le_perm_left.\n   rewrite (Uplus_sym z), <- Uplus_assoc.\n   rewrite Uminus_plus_simpl; trivial.\n  Qed.\n\n  Lemma Uabs_diff_plus_aux : forall f1 f2 g1 g2,\n   f1 + g1 <= f2 + g2 ->\n   Uabs_diff (f1 + g1) (f2 + g2) <= Uabs_diff f1 f2 + Uabs_diff g1 g2.\n  Proof.\n   intros; rewrite Uabs_diff_compat_le; trivial.\n   rewrite <- Uminus_assoc_left, Uplus_sym.\n   transitivity (g2 + (f2 - f1) - g1).\n   apply Uminus_le_compat; auto using Uplus_minus_le.\n   rewrite Uplus_sym.\n   transitivity (f2 - f1 + (g2 - g1)).\n   apply Uplus_minus_le.\n   unfold Uabs_diff; auto.\n  Qed.\n\n  Lemma Uabs_diff_plus : forall f1 f2 g1 g2, \n    Uabs_diff (f1 + g1) (f2 + g2) <= Uabs_diff f1 f2 + Uabs_diff g1 g2.\n  Proof.\n   intros; apply (Ule_total (f1 + g1) (f2 + g2)); trivial; intros.\n   apply Uabs_diff_plus_aux; trivial.\n   intros; rewrite Uabs_diff_sym, (Uabs_diff_sym f1),(Uabs_diff_sym g1).\n   apply Uabs_diff_plus_aux; trivial.\n  Qed.\n\n  Lemma Uabs_diff_mult : forall c f g, \n   Uabs_diff (c * f) (c * g) == c * Uabs_diff f g.\n  Proof.\n   intros; apply (Ule_total f g); trivial; intros.\n   repeat rewrite Uabs_diff_compat_le; auto.\n   rewrite Uabs_diff_sym, (Uabs_diff_sym f).\n   repeat rewrite Uabs_diff_compat_le; auto.\n  Qed.\n\n End UMINUS_TRIANGLE_INEQ.\n\n (** [ |a-b| <= |a-c| + |b-c| ] *)\n Lemma Uabs_diff_triangle_ineq : forall a b c, \n  Uabs_diff a b <= Uabs_diff a c + Uabs_diff c b.\n Proof.\n  intros; apply (Ule_total a b); trivial.\n  apply Uabs_diff_triangle_ineq_simpl; trivial.\n  rewrite Uplus_sym.\n  rewrite Uabs_diff_sym.\n  rewrite (Uabs_diff_sym c).\n  rewrite (Uabs_diff_sym a).\n  apply Uabs_diff_triangle_ineq_simpl; trivial.\n Qed.\n\n Definition fabs_diff (A:Type) (f h : MF A) : MF A := \n               fun x =>  Uabs_diff (f x) (h x). \n Implicit Arguments fabs_diff [A].\n\n Lemma fabs_diff_eq_compat: forall (A:Type) (f1 h1 f2 h2: MF A),\n   f1 == f2 -> h1 == h2 ->\n   fabs_diff f1 h1 == fabs_diff f2 h2.\n Proof.\n   unfold fabs_diff; intros.\n   refine (ford_eq_intro _); intro a.\n   rewrite (ford_eq_elim H a), (ford_eq_elim H0 a); trivial.\n Qed.\n\n Lemma Uabs_diff_mu_compat : forall (A:Type) (f' g':A-o>U) (d: Distr A),\n   Uabs_diff (mu d f') (mu d g') <= mu d (fabs_diff f' g').\n Proof.\n  intros.\n  rewrite (@mu_stable_plus _ d (fminus f' g') (fminus g' f')).\n  apply Uplus_le_compat; apply mu_stable_le_minus.\n    intros x.\n    apply (Ule_total (f' x) (g' x)); [auto| |].\n      intro H'; rewrite (Uminus_le_zero _ _ H'); trivial.\n      intro H'; apply Uinv_le_perm_right; rewrite (Uminus_le_zero _ _ H'); trivial.\n Qed.\n\n(** ** Predicate operators *)\n\nLemma Bool_leb_refl : forall b, Bool.leb b b.\nProof. \n destruct b; trivial; simpl; trivial. \nQed.\n\nLemma Bool_leb_trans : forall x y z, Bool.leb x y -> Bool.leb y z -> Bool.leb x z.\nProof. \n destruct x; simpl; intros; subst; trivial.\nQed.\n\nDefinition boolO := mk_ord Bool_leb_refl Bool_leb_trans.\n\nLemma Oeq_eq_bool : forall (b1 b2:boolO), b1 == b2 -> b1 = b2.\nProof.\n intros b1 b2 (H1, H2); destruct b1; simpl in *; auto.\n destruct b2; trivial.\nQed.\n \nLemma Bool_le_true : forall b, Bool.leb b true.\nProof. \n destruct b; simpl; trivial. \nQed.\n\nHint Resolve Bool_le_true Bool_leb_refl.\n\n\nSection PREDICATES.\n\n Variable A : Type.\n\n Variables P Q : A -o> boolO.\n\n Definition andP : A -o> boolO := fun x:A => andb (P x) (Q x).\n\n Definition orP : A -o> boolO := fun x:A => orb (P x) (Q x).\n\n Definition implP : A -o> boolO := fun x:A => implb (P x) (Q x).\n\n Definition negP : A -o> boolO := fun x:A => negb (P x).\n\n Definition falseP : A -o> boolO := fun _:A => false.\n\n Definition trueP : A -o> boolO := fun _:A => true.\n\n Definition disjoint := forall x:A, P x && Q x = false.\n\nEnd PREDICATES.\n\nInfix \"[||]\" := orP (right associativity, at level 30).\nInfix \"[&&]\" := andP (right associativity, at level 30).\nInfix \"[=>]\" := implP (right associativity, at level 30).\n\nAdd Parametric Morphism A : (orP (A:=A)) \n with signature \n  (Ole (o:=A -o> boolO)) ++> (Ole (o:=A -o> boolO)) ++> (Ole (o:=A -o> boolO))\n as orP_le_compat.\nProof.\n unfold orP; intros P Q Hle P0 Q0 Hle0 a.\n assert (W:=Hle a); assert (W0:=Hle0 a).\n destruct (P a); simpl in W |- *.\n rewrite W; trivial. \n destruct (Q a); simpl in W0 |- *; trivial.\nQed.\n\nAdd Parametric Morphism A : (orP (A:=A))\n with signature (Oeq (O:=A -o> boolO)) ==> (Oeq (O:=A -o> boolO)) ==> (Oeq (O:=A -o> boolO))\n as orP_eq_compat.\nProof.\n intros P Q [H1 H2] P0 Q0 [H3 H4]; split; apply orP_le_compat; trivial.\nQed.\n\nAdd Parametric Morphism A : (andP (A:=A))\n with signature (Ole (o:=A -o> boolO)) ++> (Ole (o:=A -o> boolO)) ++> (Ole (o:=A -o> boolO))\n as andP_le_compat.\nProof.\n unfold andP; intros P Q H P0 Q0 H0 a.\n assert (W:=H a); assert (W0:=H0 a).\n destruct (P a); simpl in W |- *; trivial.\n rewrite W; trivial.\nQed.\n\nAdd Parametric Morphism A : (andP (A:=A))\n with signature (Oeq (O:=A -o> boolO)) ==> (Oeq (O:=A -o> boolO)) ==> (Oeq (O:=A -o> boolO))\n as andP_eq_compat.\nProof.\n intros P Q [H1 H2] P0 Q0 [H3 H4]; split; apply andP_le_compat; trivial.\nQed.\n\nAdd Parametric Morphism A : (implP (A:=A))\n with signature (Ole (o:=A -o> boolO)) --> (Ole (o:=A -o> boolO)) ++> (Ole (o:=A -o> boolO))\n as implP_le_compat.\nProof.\n unfold implP; intros P Q H P0 Q0 H0 a.\n assert (W:=H a); assert (W0:=H0 a).\n destruct (Q a); simpl in W |- *; trivial.\n rewrite W; simpl; trivial.\nQed.\n\nAdd Parametric Morphism A : (implP (A:=A)) \n with signature (Oeq (O:=A -o> boolO)) ==> (Oeq (O:=A -o> boolO)) ==> (Oeq (O:=A -o> boolO))\n as implP_eq_compat.\nProof.\n intros P Q [H1 H2] P0 Q0 [H3 H4]; split; apply implP_le_compat; trivial.\nQed.\n\nAdd Parametric Morphism A : (negP (A:=A)) \n with signature (Ole (o:=A -o> boolO)) --> (Ole (o:=A -o> boolO))\n as negP_le_compat.\nProof.\n unfold negP; intros P Q H a.\n assert (W:=H a); destruct (Q a); simpl; trivial.\n rewrite W; trivial.\nQed.\n\nAdd Parametric Morphism A : (negP (A:=A))\n with signature (Oeq (O:=A -o> boolO)) ==> (Oeq (O:=A -o> boolO))\n as negP_eq_compat.\nProof.\n intros P Q [H1 H2]; split; apply negP_le_compat; trivial.\nQed.\n\n\nSection PRED_PROP.\n\n Variable A : Type.\n\n Variables P Q R : A -o> boolO.\n\n Lemma andP_comm : (P [&&] Q) == Q [&&] P.\n Proof.\n  apply ford_eq_intro; intros x; unfold andP, andb.\n  case (P x); case (Q x); trivial.\n Qed.\n\n Lemma andP_assoc : (P [&&] Q) [&&] R == P [&&] (Q [&&] R).\n Proof.\n  apply ford_eq_intro; intro x; unfold andP, andb.\n  case (P x); case (Q x); case (R x); trivial.\n Qed.\n\n Lemma andP_orP_distrib_r : P [&&] (Q  [||] R) == (P [&&] Q) [||] (P [&&] R).\n Proof.\n  apply ford_eq_intro; intro x; unfold andP, orP.\n  rewrite andb_orb_distrib_r; trivial.\n Qed.\n\n Lemma orP_andP_distrib_r : P [||] (Q [&&] R) == (P [||] Q) [&&] (P [||] R).\n Proof.\n  apply ford_eq_intro; intro x; unfold andP, orP.\n  rewrite orb_andb_distrib_r; trivial.\n Qed.\n\n Lemma proj1_BP : P [&&] Q <= P.\n Proof.\n  intro; unfold andP.\n  destruct (P x); simpl; trivial.\n Qed.\n\n Lemma proj2_BP : P [&&] Q <= Q.\n Proof.\n  intro; unfold andP.\n  destruct (P x); simpl; auto.\n Qed.\n\n Lemma negP_involutive : negP (negP P) == P.\n Proof.\n  apply ford_eq_intro; intro x; unfold negP; rewrite negb_involutive; trivial.\n Qed.\n\n Lemma orP_neg : P [||] negP P == @trueP _.\n Proof.\n  apply ford_eq_intro; intro x; unfold negP, orP, trueP; destruct (P x); trivial.\n Qed.\n\n Lemma disjoint_negP : disjoint P (negP P).\n Proof.\n  red; unfold negP; intros; apply andb_negb_r.\n Qed.\n\n Lemma andP_true_l : (@trueP _) [&&] P == P.\n Proof. \n  intros; apply ford_eq_intro; trivial. \n Qed.\n\n Lemma andP_true_r : P [&&] (@trueP _) == P.\n Proof. \n  intros; apply ford_eq_intro; intros; unfold andP, trueP;\n  rewrite (andb_true_r (P n)); trivial.\n Qed.\n \nEnd PRED_PROP.\n\n\n(** ** Restriction of distributions *) \n\nDefinition restr A (P:A -o> boolO) (f:A -O-> U) : A -O-> U := \n fun a => if P a then f a else 0.\n\nDefinition charfun A (P:A -o> boolO) : A -O-> U := restr P (fone _).\n\nAdd Parametric Morphism A : (restr (A:=A)) \n with signature (Ole (o:=A -o> boolO)) ++> (Ole (o:=A -O-> U)) ++> (Ole (o:=A -O-> U))\n as restr_le_compat.\nProof.\n intros P Q H f g H0 a.\n unfold restr; simpl.\n assert (W:=H a); destruct (P a); trivial.\n rewrite W; trivial.\nQed.\n\nAdd Parametric Morphism A : (restr (A:=A)) \n with signature (Oeq (O:=A -o> boolO)) ==> (Oeq (O:=A -O-> U)) ==> (Oeq (O:=A -O-> U)) \n as restr_eq_compat.\nProof.\n intros P Q [H1 H2] f g [H3 H4]; split; apply restr_le_compat; trivial.\nQed.\n\nAdd Parametric Morphism A : (charfun (A:=A)) \n with signature (Ole (o:=A -o> boolO)) ++> (Ole (o:=A -O-> U))\n as charfun_le_compat.\nProof.\n intros; unfold charfun; apply restr_le_compat; trivial.\nQed.\n\nAdd Parametric Morphism A : (charfun (A:=A))\n with signature (Oeq (O:=A -o> boolO)) ==> (Oeq (O:=A -O-> U)) \n as charfun_eq_compat.\nProof.\n intros; unfold charfun; apply restr_eq_compat; trivial.\nQed.\n\nDefinition Fmult A (f1 f2:A -o> U) : A -o> U := fun a => f1 a * f2 a.\n\nAdd Parametric Morphism A : (Fmult (A:=A))\n with signature Ole (o:=A -o> U) ++> Ole (o:=A -o> U) ++> Ole (o:=A -o> U)\n as Fmult_le_compat.\nProof.\n intros f g H f0 g0 H0 a; unfold Fmult; apply Umult_le_compat; trivial.\nQed.\n\nAdd Parametric Morphism A : (Fmult (A:=A)) \n with signature Oeq (O:=A -o> U) ==> Oeq (O:=A -o> U) ==> Oeq (O:=A -o> U)\n as Fmult_eq_compat.\nProof.\n intros f g H f0 g0 H0; unfold Fmult.\n apply ford_eq_intro; intro a.\n apply Umult_eq_compat; apply ford_eq_elim; trivial.\nQed.\n\nLemma restr_and : forall (A:Type) (P Q:A -o> boolO) f, \n restr (P [&&] Q) f == restr P (restr Q f).\nProof.\n intros; refine (ford_eq_intro _); intro a.\n unfold restr, andP; case (P a); trivial.\nQed.\n\nLemma restr_or : forall (A:Type) (P Q :A -o> boolO) f, \n restr (P [||] Q) f == fplus (restr P f) (restr (negP P) (restr Q f)).\nProof.\n intros; refine (ford_eq_intro _); intro a.\n unfold restr, orP, negP, fplus; case (P a); auto.\nQed.\n\nLemma restr_or_le : forall (A:Type) (P Q:A -o> boolO) f, \n restr (P [||] Q) f <= fplus (restr P f) (restr Q f).\nProof.\n intros; rewrite restr_or.\n intro a; unfold fplus, restr, negP; case (P a); auto.\nQed.\n\nLemma disjoint_restr_or : forall (A:Type) (P Q:A -o> boolO),\n disjoint P Q -> \n forall f, restr (P [||] Q) f == fplus (restr P f) (restr Q f).\nProof.\n intros; rewrite restr_or. \n refine (ford_eq_intro _); intro a.\n assert (W:=H a); unfold fplus, restr, negP.\n destruct (P a); [ | trivial].\n destruct (Q a); [discriminate | trivial].\nQed.\n\nLemma restr_true : forall A f, restr (@trueP A) f == f.\nProof.\n intros; refine (ford_eq_intro _); intro a; trivial.\nQed.\n\nLemma restr_split : forall A (P:A -o> boolO) f,\n f == fplus (restr P f) (restr (negP P) f).\nProof.\n intros; rewrite <- disjoint_restr_or. \n rewrite orP_neg, restr_true; trivial.\n apply disjoint_negP.\nQed.\n\nLemma restr_impl : forall (A:Type) (P Q:A -o> boolO) f,\n restr (P [=>] Q) f == fplus (restr (negP P) f) (restr P (restr Q f)).\nProof.\n intros; refine (ford_eq_intro _); intro a.\n unfold restr, implP, negP, fplus; intros.\n destruct (P a); simpl; auto.\nQed. \n\nLemma restr_neg : forall (A:Type) (P:A -o> boolO) f, \n restr (negP P) f  == fminus f (restr P f).\nProof.\n intros; refine (ford_eq_intro _); intro a.\n unfold negP, restr, fminus; intros.\n destruct (P a); simpl; auto.\nQed.\n\nLemma charfun_neg : forall (A:Type) (P:A -o> boolO), \n charfun (negP P) == finv (charfun P).\nProof.\n unfold charfun; intros.\n rewrite (restr_neg P (fone _)).\n refine (ford_eq_intro _); intro a; unfold fminus, finv; auto.\nQed.\n\nLemma restr_charfun : forall (A:Type) (P Q:A -o> boolO), \n restr P (charfun Q) == Fmult (charfun P) (charfun Q).\nProof.\n intros; refine (ford_eq_intro _); intro a.\n unfold charfun, restr, Fmult; intros; case (P a); auto.\nQed.\n\nLemma charfun_and : forall (A:Type) (P Q:A -o> boolO), \n charfun (P [&&] Q) == Fmult (charfun P) (charfun Q).\nProof.\n intros; unfold charfun at 1.\n rewrite restr_and; fold (charfun Q); rewrite restr_charfun; trivial.\nQed.\n\nLemma restr_charfun_and : forall (A:Type) (P Q:A -o> boolO), \n restr P (charfun Q) == charfun (P [&&] Q).\nProof.\n intros; unfold charfun at 1; rewrite <- restr_and; trivial.\nQed.\n\nLemma charfun_or : forall (A:Type) (P Q:A -o> boolO), \n charfun (P [||] Q) == fplus (charfun P) (Fmult (finv (charfun P)) (charfun Q)).\nProof.\n unfold charfun at 1; intros; rewrite restr_or.\n fold (charfun P) (charfun Q).\n rewrite restr_charfun; rewrite charfun_neg; trivial.\nQed.\n\nLemma charfun_or_le : forall (A:Type) (P Q:A -o> boolO), \n charfun (P [||] Q) <= fplus (charfun P) (charfun Q). \nProof.\n intros; unfold charfun; apply restr_or_le.\nQed.\n\nLemma disjoint_fplusok_restr : forall (A:Type) (P Q:A -o> boolO) (f:A -O-> U),\n disjoint P Q ->\n fplusok (restr P f) (restr Q f).\nProof.\n unfold fplusok; intros.\n simpl; apply ford_le_intro; intro a.\n unfold restr, finv.\n generalize (H a); unfold andP.\n case (P a); case (Q a); intros; try discriminate; auto.\nQed.\n\nLemma disjoint_fplusok_charfun : forall (A:Type) (P Q:A -o> boolO),\n disjoint P Q ->\n fplusok (charfun P) (charfun Q).\nProof.\n unfold charfun; intros; apply disjoint_fplusok_restr; trivial.\nQed.\n\nLemma disjoint_charfun : forall (A:Type) (P Q:A -o> boolO), \n disjoint P Q -> \n Fmult (finv (charfun P)) (charfun Q) == charfun Q.  \nProof.\n intros; apply ford_eq_intro; intro a.\n unfold charfun, restr, finv, Fmult.\n assert (W:=H a); destruct (Q a); [ | auto].\n destruct (P a); [discriminate W | auto].\nQed.\n  \nLemma disjoint_charfun_or : forall (A:Type) (P Q:A -o> boolO), \n disjoint P Q ->\n charfun (P [||] Q) == fplus (charfun P) (charfun Q). \nProof.\n intros; rewrite charfun_or.\n rewrite disjoint_charfun; trivial.\nQed.\n\nLemma charfun_impl : forall  (A:Type) (P Q:A -o> boolO),\n charfun (P [=>] Q) == fplus (finv (charfun P)) (Fmult (charfun P) (charfun Q)).\nProof.\n unfold charfun at 1; intros; rewrite restr_impl; rewrite <- restr_and.\n fold (charfun (negP P)) (charfun (P [&&] Q)); rewrite charfun_neg, charfun_and; trivial.\nQed.\n\nLemma charfun_and_impl : forall (A:Type) (P Q:A -o> boolO),\n charfun (P [&&] P [=>] Q) == charfun (P [&&] Q).\nProof.\n intros; rewrite charfun_and, charfun_and, charfun_impl.\n simpl; apply ford_eq_intro; unfold Fmult, fplus, finv, charfun, restr, fone.\n intro a; destruct (P a); repeat Usimpl; auto.\nQed.\n\nSection PROBABILITY.\n  \n Variable A : Type.\n\n Variable d : Distr A.\n\n Variables P Q R: A -o> boolO.\n\n Definition distr0 : Distr A.\n  exists (@fmon_cte (A -O-> U) U 0); intro x; intros; auto.\n Defined.\n\n Definition drestr := Mlet d (fun a => if P a then Munit a else distr0).\n\n Lemma mu_drestr : forall f, mu drestr f == mu d (restr P f).\n Proof.\n  unfold drestr, restr; intros; rewrite Mlet_simpl.\n  apply mu_stable_eq.\n  simpl; apply ford_eq_intro; intros n.\n  destruct (P n); trivial. \n Qed.\n\n Lemma distr_OR_restr : forall f, \n  mu d (restr (P [||] Q) f) <=\n  mu d (fplus (restr P f) (restr Q f)). \n Proof.\n  intros; apply mu_monotonic; apply restr_or_le.\n Qed.\n\n Lemma distr_OR_charfun :  \n  mu d (charfun (P [||] Q)) <=\n  mu d (charfun P) + mu d (charfun Q). \n Proof.\n  intros; eapply Ole_trans;[ | apply mu_le_plus].\n  apply mu_monotonic.\n  apply charfun_or_le.\n Qed. \n\n Lemma distr_OR_restr_disj : forall f,\n  disjoint P Q ->\n  mu d (restr (P [||] Q) f) ==\n  mu d (restr P f) + mu d (restr Q f). \n Proof.\n  intros f H; rewrite <- (mu_stable_plus d (disjoint_fplusok_restr f H)).\n  apply mu_stable_eq.\n  apply disjoint_restr_or; trivial.\n Qed.\n\n Lemma distr_OR_charfun_disj : \n  disjoint P Q ->\n  mu d (charfun (P [||] Q)) ==\n  mu d (charfun P) + mu d (charfun Q). \n Proof.\n  unfold charfun; intros; apply distr_OR_restr_disj; trivial.\n Qed.\n\n Lemma mu_neg_restr : forall f, \n  mu d (restr (negP P) f)  ==\n  mu d f - mu d (restr P f).\n Proof.\n  intros; rewrite <- stable_minus_distr; [ | auto | auto | ].\n  apply mu_stable_eq; apply restr_neg.  \n  intro a; unfold restr; case (P a); trivial.\n Qed.\n\n Lemma mu_neg_charfun : \n  mu d (charfun (negP P)) == mu d (fone _) - mu d (charfun P).\n Proof.\n  unfold charfun; apply mu_neg_restr. \n Qed. \n\n Lemma mu_impl_charfun : \n  mu d (charfun (P [=>] Q))  ==\n  mu d (fone _) - mu d (charfun P) + mu d (Fmult (charfun P) (charfun Q)).\n Proof.\n  apply Oeq_trans with \n   (mu d (fplus (finv (charfun P)) (Fmult (charfun P) (charfun Q)))).\n  apply mu_stable_eq; apply charfun_impl.\n  rewrite (@mu_stable_plus _ d (finv (charfun P))).\n  rewrite mu_inv_minus; trivial.\n  unfold fplusok, finv, Fmult; intro; auto.\n Qed.\n\n Lemma mu_range_strenghten : \n  range P d ->\n  mu d (charfun Q) == mu d (charfun (P [&&] Q)).\n Proof.\n  intros Hd.\n  apply (range_eq Hd); intros a Ha.\n  unfold andP, charfun, restr; rewrite Ha; trivial.\n Qed.\n\n Lemma mu_range_restr : forall (A:Type) (d:Distr A) (P:A -> bool),\n  range P d ->\n  forall f, mu d f == mu d (restr P f). \n Proof.\n  intros; apply range_eq with (1:=H); intros.\n  unfold restr; rewrite H0; trivial.\n Qed.\n\n Lemma mu_restr_split : forall f,\n  mu d f == mu d (restr P f) + mu d (restr (negP P) f).\n Proof.\n  intros; transitivity (mu d (fplus (restr P f) (restr (negP P) f))).\n  apply mu_stable_eq; apply restr_split.\n  apply mu_stable_plus; apply disjoint_fplusok_restr; apply disjoint_negP.\n Qed.\n\n Lemma mu_restr_fplus : forall f g,\n  mu d (restr P (fplus f g)) == mu d (fplus (restr P f) (restr P g)).\n Proof.\n  intros; apply mu_stable_eq.\n  refine (ford_eq_intro _); intro x.\n  intros; unfold restr, fplus; case (P x); Usimpl; trivial.\n Qed.\n\n Lemma mu_restr_cte : forall k,\n  mu d (restr P (fcte _ k)) == k * mu d (restr P (fone _)).\n Proof.\n  intros.\n  rewrite <- (@mu_stable_mult _ _ _).\n  apply mu_stable_eq.\n  refine (ford_eq_intro _); intro x.\n  unfold restr, fmult, fcte, fone; case (P x); Usimpl; trivial.\n Qed.\n\n\nEnd PROBABILITY.\n\n\nLemma charfun_range : forall A (d:Distr A) (P:A -o> boolO),\n mu d (charfun P) == mu d (fone _) ->\n range P d.\nProof.\n red; intros.\n transitivity (mu d (restr (P [||] negP P) f)).\n rewrite distr_OR_restr_disj. \n transitivity (mu d (fun _ => 0) +  0).\n rewrite mu_0; auto.\n apply Uplus_eq_compat.\n apply mu_stable_eq; simpl; apply ford_eq_intro; intros.\n unfold restr; assert (W:= H0 n); destruct (P n); auto.\n split; trivial. \n transitivity (mu d (charfun (negP P))).\n apply mu_monotonic; unfold charfun; intro; apply restr_le_compat; auto.\n rewrite mu_neg_charfun, H; auto.\n apply disjoint_negP.\n apply mu_stable_eq; simpl; apply ford_eq_intro; unfold restr, orP, negP.\n intro n; destruct (P n); trivial.\nQed.\n\n\nDefinition feq (A:Type) (O:ord) (f1 f2:A -> O) := forall x, f1 x == f2 x.\n\nImplicit Arguments feq [A O].\n\nInfix \"===\" := feq (at level 70).\n\nLemma feq_refl : forall (A:Type) (O:ord) (f:A -> O), f === f.\nProof. \n unfold feq; trivial.\nQed.\n\nLemma feq_sym : forall (A:Type) (O:ord) (f1 f2:A -> O), f1 === f2 -> f2 === f1.\nProof.\n unfold feq; intros; symmetry; trivial.\nQed.\n\nLemma feq_trans : forall  (A:Type) (O:ord) (f1 f2 f3:A -> O), \n f1 === f2 -> f2 === f3 -> f1 === f3.\nProof.\n unfold feq; intros; transitivity (f2 x); trivial.\nQed.\n\nAdd Parametric Relation A (O:ord) : (A -> O) (@feq A O)\n reflexivity proved by (@feq_refl A O)\n symmetry proved by (@feq_sym A O)\n transitivity proved by (@feq_trans A O)\n as feq_rel.\n\nAdd Parametric Morphism A B : (Mlet (A:=A) (B:=B))\n with signature Oeq (O:=Distr A) ==> (@feq A (Distr B)) ==> Oeq (O:=Distr B)\n as Mlet_morph. \nProof.\n intros; apply Mlet_eq_compat; trivial.\n apply ford_eq_intro; trivial.\nQed.\n\nHint Immediate feq_refl.\n\nAdd Parametric Morphism A : (drestr (A:=A))\n with signature Oeq (O:=Distr A) ==> Oeq (O:=A -o> boolO) ==> Oeq (O:=Distr A)\n as drestr_morph.\nProof.\n intros d1 d2 H f g H0; unfold drestr.\n apply Mlet_morph; trivial.\n intro a; rewrite (Oeq_eq_bool (ford_eq_elim H0 a)); trivial.\nQed.\n\nHint Resolve mu_fone_0_eq mu_0.\n\n\nSection FINITE.\n\n Variable A : Type.\n\n Definition finite_sum (f:A -> U) (l:list A) :=\n  List.fold_right (fun a res => f a + res) 0 l.\n\n Lemma finite_sum_app : forall f l1 l2, \n  finite_sum f (l1 ++ l2) == finite_sum f l1 + finite_sum f l2.\n Proof.\n  induction l1; simpl; intros; trivial.\n  auto.\n  rewrite IHl1; auto.\n Qed.\n\n Lemma finite_sum_cons : forall f a l, \n  finite_sum f (a::l) == f a + finite_sum f l.\n Proof.\n  trivial.\n Qed.\n\n Lemma finite_sum_In : forall f l a,\n  In a l ->\n  f a <= finite_sum f l.\n Proof.\n  intros f l a H; induction l.\n  elim H.\n  simpl in H; case H; clear H; intro H.\n  rewrite H; simpl; trivial.\n  eapply Ole_trans; [ apply IHl; trivial | ].\n  simpl; trivial.\n Qed.\n\n Lemma finite_sum_mult_le : forall f k l,\n  k * finite_sum f l <= finite_sum (fmult k f) l.\n Proof.\n  induction l; simpl.\n  trivial.\n  rewrite <- IHl; apply Udistr_plus_left_le.\n Qed.\n\nEnd FINITE.\n\nLemma finite_sum_le : forall (A:Type) (f1 f2:A -o> U) l,\n (forall x, In x l -> (f1 x <= f2 x)%tord) ->\n (finite_sum f1 l <= finite_sum f2 l)%tord.\nProof.\n induction l; simpl; trivial; intros.\n apply Uplus_le_compat; auto.\nQed.\n \nLemma finite_sum_eq : forall (A:Type) (f1 f2 : A-o>U) l,\n (forall x, In x l -> (f1 x == f2 x)%tord) ->\n (finite_sum f1 l == finite_sum f2 l)%tord.\nProof.\n induction l; simpl; trivial; intros.\n apply Uplus_eq_compat; auto.\nQed.\n\n\nLemma finite_sum_notIn : forall (A:Type) (v:A) (f:A->U),\n (forall x, x <> v -> f x == 0) ->\n forall l, ~In v l -> finite_sum f l == 0.\nProof.\n induction l; simpl; intros;[trivial | ].\n rewrite H; firstorder.\nQed.\n\nLemma finite_sum_notIn2 : forall (A:Type) (f:A -> U) l,\n (forall x, In x l -> f x == 0) ->\n finite_sum f l == 0.\nProof.\n induction l; simpl; intros;[trivial | ].\n rewrite H; firstorder.\nQed.\n\nLemma finite_sum_cte : forall (A:Type) (f:A -> U) l (v : U),\n (forall x, In x l -> f x == v) ->\n finite_sum f l == (length l) */ v.\nProof.\n induction l; simpl; trivial; intros.\n rewrite IHl.\n rewrite H.\n destruct (length l).\n Usimpl; trivial.\n trivial.\n auto.\n intros; apply H.\n auto.\nQed.\n\nLemma finite_sum_mult : forall (A:Type) (f:A -> nat) (v:U) (l:list A),\n finite_sum (fun a => f a */ v) l == \n fold_right (fun a r => (f a + r)%nat) 0%nat l */ v.\nProof.\n induction l; simpl; intros; auto.\n rewrite IHl.\n rewrite <- plus_Nmult_distr; auto.\nQed.\n\nLemma finite_sum_full : forall (A:Type) (v:A) (f:A->U),\n (forall x, x <> v -> f x == 0) ->\n forall l,\n  In v l ->\n  NoDup l ->\n  finite_sum f l == f v.\nProof.\n intros.\n destruct (In_split _ _ H0) as (l1, (l2, Heq)); subst.\n assert (W:= NoDup_remove_2 _ _ _ H1).\n rewrite finite_sum_app; simpl.\n repeat rewrite (@finite_sum_notIn _ v); auto.\n Usimpl; auto.\n intro; apply W; apply in_or_app; auto.\n intro; apply W; apply in_or_app; auto.\nQed.\n\nLemma finite_sum_Perm : forall A B f1 f2 (l1:list A) (l2:list B), \n PermutP (fun x1 x2 => @Oeq U (f1 x1) (f2 x2)) l1 l2 ->\n finite_sum f1 l1 == finite_sum f2 l2.\nProof.\n induction 1; simpl; trivial.\n rewrite H, IHPermutP, finite_sum_app, finite_sum_app, finite_sum_cons; auto.\nQed. \n\nLemma finite_sum_Permutation : forall A (f:A -> U) l1 l2,\n PermutP (@eq _) l1 l2 ->\n finite_sum f l1 == finite_sum f l2.\nProof.\n intros; apply finite_sum_Perm.\n induction H; constructor; subst; auto.\nQed.\n\nLemma finite_sum_map : forall A B (F:A -> B) f l,\n finite_sum f (map F l) == finite_sum (fun v => f (F v)) l.\nProof.\n intros; apply finite_sum_Perm.\n apply PermutP_sym; rewrite <- PermutP_map. \n apply PermutP_refl; intros; trivial.\nQed.\n\nLemma finite_sum_rev : forall A (f:A -> U) l, \n finite_sum f l == finite_sum f (rev l).\nProof.\n intros; apply finite_sum_Permutation.\n apply PermutP_rev.\nQed.\n \nSection SUMDOM.\n\n Variable A : Type.\n\n Variable default : A.\n\n Definition nth_dom (dom:list A) : (A -o> U) -m> (natO -o> U).\n intros dom.\n refine (@mk_fmono (A -o> U) (natO -o> U)\n  (fun f n => [1/]1+pred (length dom) * f (nth n dom default)) _).\n unfold monotonic; intros; auto.\n Defined.\n\n Definition sum_dom (dom:list A) : M A := \n  (UP.Sigma <_> (length dom)) @ (nth_dom dom).\n\n (* TODO: Make [sum_dom] more efficient (without using [Sigma]), e.g.\n\n Section SUMAUX.\n\n  Variable A : Type.\n  Variable f : (A -o> U).\n  Variable p : U.\n\n  Fixpoint sumaux (l:list A) {struct l} : U :=\n   match l with\n    | nil => 0\n    | a::l' => p * f a + sumaux l' \n   end.\n\n End SUMAUX.\n \n Definition sum_dom (l:list A) : M A.\n  intro l.\n  exists (fun (f:A-O->U) => sumaux f ([1/]1+pred (length l)) l). \n  red; intros.  \n  apply sumaux_le_compat; trivial.\n Defined.\n *)\n\n Lemma comp_fold_right : forall def f f' (l:list A),\n  (forall n, (n < length l)%nat -> f n = f' (nth (length l - S n) l def)) ->\n  comp Uplus 0 f (length l) = fold_right (fun a res => f' a + res) 0 l.\n Proof.\n  induction l; simpl; intros; trivial.\n  rewrite IHl.\n  rewrite (H (length l)); auto with arith.\n  rewrite <- minus_n_n; trivial.\n  intros; rewrite H; auto with arith.\n  case_eq (length l - n)%nat; intros.\n  elimtype False; omega.\n  replace n0 with (length l - S n)%nat; trivial; omega.\n Qed.\n\n Lemma sigma_finite_sum : forall f l,\n  sigma (fun k => f (nth k l default)) (length l) ==\n  finite_sum f l.\n Proof.\n  simpl; intros.\n  rewrite finite_sum_rev.\n  unfold finite_sum; intros.\n  pattern (length l); rewrite <- rev_length.\n  rewrite (comp_fold_right default \n   (fun n : nat => f (nth n l default))\n   (fun a => f a)); trivial.\n  intros; rewrite rev_nth.\n  replace (length l - S (length (rev l) - S n))%nat with n; trivial.\n  rewrite rev_length in *; omega.\n  rewrite rev_length in *; omega.\n Qed.\n\n Lemma sum_dom_finite : forall dom f, \n  sum_dom dom f ==\n  finite_sum (fun a => [1/]1+(pred (length dom)) * f a) dom.\n Proof.\n  unfold sum_dom; simpl; intros.\n  refine (sigma_finite_sum (fun a : A => [1/]1+pred (length dom) * f a) dom).\n Qed.\n\n Opaque sigma.\n\n Lemma sum_dom_stable_inv : forall l, stable_inv (sum_dom l).\n Proof.\n  unfold stable_inv; destruct l; intros. \n  trivial.\n  simpl; rewrite sigma_inv. \n  trivial.\n  simpl length; auto.\n Qed.\n\n Lemma sum_dom_stable_plus : forall l, stable_plus (sum_dom l).\n Proof.\n  unfold stable_plus; simpl; destruct l; intros.\n  simpl; auto.\n  simpl length; simpl pred.\n  transitivity \n   (sigma \n    (fplus \n     (fun n => [1/]1+length l * f (nth n (a :: l) default))\n     (fun n => [1/]1+length l * g (nth n (a :: l) default)))\n    (S (length l))).\n  apply sigma_eq_compat; intros; unfold fplus.\n  rewrite Udistr_plus_left; [ | refine (H _)]; trivial.\n  unfold fplus; apply sigma_plus.\n Qed.\n \n Lemma sum_dom_stable_mult : forall l, stable_mult (sum_dom l).\n Proof.\n  unfold stable_mult; simpl; destruct l; intros; auto.\n  rewrite <- sigma_mult.  \n  apply sigma_eq_compat; intros; unfold fmult; auto.\n  unfold retract; intros.\n  transitivity ([1/]1+length l); trivial.\n  transitivity ([1-] sigma (fun n => [1/]1+length l) k0).\n  exact (fnth_retract (length l) _ H).\n  apply Uinv_le_compat; apply sigma_le_compat; auto.\n Qed.\n \n Lemma sum_dom_continuous: forall l, continuous (sum_dom l).\n Proof.\n  unfold continuous, sum_dom; intros.\n  assert (X:=sigma_continuous1 ((nth_dom l) @ h) (length l)).\n  match type of X with ?x1 <= ?x2 =>\n   transitivity x1; [ | transitivity x2; [exact X | ] ]\n  end; trivial.\n  simpl; apply sigma_le_compat; intros.\n  rewrite <- lub_eq_mult; apply lub_le_compat; auto.\n Qed.\n\n Lemma sum_dom_zero : forall l P f,\n  (forall a, In a l -> P a) -> \n  (forall a, P a -> f a == 0) ->\n  sum_dom l f == 0.\n Proof.\n  induction l; intros P f Hl Hf.\n  trivial.\n  simpl; apply sigma_zero; intros k Hk.\n  rewrite Hf; [auto | ].\n  apply Hl; destruct k.\n  simpl; auto.\n  right; apply nth_In; auto with arith.\n Qed.\n\n Definition sum_support (dom:list A) : Distr A :=\n  @Build_distr A\n  (sum_dom dom) \n  (sum_dom_stable_inv dom)\n  (sum_dom_stable_plus dom)\n  (sum_dom_stable_mult dom)\n  (sum_dom_continuous dom).\n\n Lemma sum_support_lossless : forall l, \n  l <> nil -> \n  mu (sum_support l) (fun _ => 1) == 1. \n Proof.\n  unfold sum_support, sum_dom; intros; simpl.\n  destruct l.  \n  elim H; trivial.\n  intros; transitivity (sigma (fun _ => [1/]1+length l) (S (length l))); auto.\n Qed.\n\n Lemma sum_support_const : forall k l,\n  l <> nil ->\n  mu (sum_support l) (fun _ => k) == k.\n Proof.\n  intros; refine (mu_cte_eq _ _ _).\n  apply sum_support_lossless; trivial.\n Qed.\n\n Lemma sum_support_stable_eq : forall dom f g,\n  (forall v, In v dom -> f v == g v) -> \n  mu (sum_support dom) f == mu (sum_support dom) g.\n Proof.\n  intros dom f g Heq; simpl.\n  apply sigma_eq_compat; intros k H.\n  apply Umult_eq_compat_right; apply Heq.\n  apply nth_In; trivial.\n Qed.\n\n Lemma sum_support_in : forall a f l,\n  In a l ->\n  f a == 1 ->\n  [1/]1+pred (length l) <= mu (sum_support l) f.\n Proof.\n  intros; rewrite (sum_dom_finite l f).\n  transitivity ([1/]1+pred (length l) * f a); [rewrite H0; auto | ].\n  rewrite <- (finite_sum_mult_le f ([1/]1+pred (length l))).\n  Usimpl; apply finite_sum_In; trivial.\n Qed.\n \nEnd SUMDOM.\n\n Lemma sum_dom_permut_eq : forall (B1 B2 : Type) (def1:B1) (def2:B2) \n  (dom1:list B1) (dom2:list B2) (f1:B1->U) (f2:B2->U),\n  PermutP (fun x1 x2 => @Oeq U (f1 x1) (f2 x2)) dom1 dom2 ->\n  sum_dom def1 dom1 f1 == sum_dom def2 dom2 f2.\n Proof.\n  intros; repeat rewrite sum_dom_finite.\n  apply finite_sum_Perm.\n  rewrite (PermutP_length H).\n  eapply PermutP_weaken  with (2:= H).\n  intros a b _ _ Heq; rewrite Heq; trivial.\n Qed.\n\n\n(*** Remove This Defined in Prog *) \n(** * Properties of the product of two distributions *)\n\n(* TODO: This should be part of ALEA *)\n\nAdd Parametric Morphism A B : (prod_distr (A:=A) (B:=B))\n with signature Oeq (O:=Distr A) ==> Oeq (O:=Distr B) ==> Oeq (O:=Distr (A * B))\n as prod_distr_morphism.\nProof.\n intros; unfold prod_distr.\n apply Mlet_morph; trivial.\n intro; apply Mlet_morph; simpl; auto.\nQed.\n\nLemma continuous2_prod_distr : forall A B,\n continuous2 (D1:=cDistr A) (D2:=cDistr B) (D3:=cDistr (A * B)) (Prod_distr A B).\nProof.\n red; intros.\n assert (H:Prod_distr A B (lub (c:=cDistr A) f) (lub (c:=cDistr B) g) == \n           prod_distr (lub (c:=cDistr A) f) (lub (c:=cDistr B) g)).\n rewrite Prod_distr_simpl; trivial.\n rewrite H; unfold prod_distr.\n transitivity\n  (Mlet (lub f)\n   (lub (c:=A -O-> cDistr (A*B)) \n    (ford_shift (fun x1 => (MLet B (A*B) @ g) <_> (fun x2 => Munit (x1,x2)))))).\n  apply (Mlet_le_compat (A:=A) (B:=A*B)); auto.\n  rewrite Mlet_lub_le.\n  apply lub_le_compat; auto.\nQed.\n\nLemma lub_prod_distr : forall A B (F1:natO -m> cDistr A) (F2:natO -m> cDistr B),\n prod_distr (lub F1) (lub F2) == \n lub (c:=cDistr (A*B)) ((Prod_distr A B @2 F1) F2).\nProof.\n intros A B; exact (lub_cont2_comp2_eq (@continuous2_prod_distr A B)).\nQed.\n\n\nSection PROD_COMM.\n\n Definition prod_comm (A B : Type) (d1:Distr A) (d2:Distr B) :=\n  prod_distr d2 d1 == Mlet (prod_distr d1 d2) (fun p => Munit (snd p, fst p)). \n\n Lemma prod_comm_distr0 : forall A B (d:Distr B),\n  prod_comm (distr0 A) d.\n Proof.\n  unfold prod_comm, prod_distr; intros.\n  apply eq_distr_intro; intro; simpl.\n  apply (@mu_0 B).\n Qed.\n\n Lemma prod_comm_Munit : forall A B (a:A) (d:Distr B),\n  prod_comm (Munit a) d.\n Proof.\n  unfold prod_comm, prod_distr; intros.\n  apply eq_distr_intro; trivial.\n Qed.\n\n Opaque sigma.\n\n Lemma prod_comm_sum_support : forall A B (a:A) (l:list A) (d:Distr B),\n  prod_comm (sum_support a l) d.\n Proof.\n  unfold prod_comm, prod_distr; intros.\n  apply eq_distr_intro; simpl; intros.\n  assert (length l <= S (pred (length l)))%nat.\n  destruct l; auto with arith.\n  generalize (pred (length l)) H; clear H.\n  induction (length l); intros.\n  rewrite sigma_0.\n  transitivity (mu d (fun _ => 0)).\n  apply (mu_stable_eq d).\n  simpl; apply ford_eq_intro; intro; rewrite sigma_0; trivial.\n  apply mu_0.\n  rewrite sigma_S; simpl pred.  \n  transitivity (mu d \n   (fplus (fmult ([1/]1+n0) (fun x => f (x, nth n l a)))\n          (fun x => sigma (fun n1 => [1/]1+n0 * f (x, nth n1 l a)) n))).\n  apply (mu_stable_eq d).\n  simpl; apply ford_eq_intro; simpl; intro.\n  rewrite sigma_S; trivial.\n  assert (X:=mu_stable_plus d); unfold stable_plus in X; rewrite X; clear X.\n  apply Uplus_eq_compat.\n  apply (mu_stable_mult d).\n  rewrite IHn; auto with arith.\n  unfold fplusok, finv; intro; simpl.\n  refine (@retractS (fun n1 : nat => [1/]1+n0 * f (x, nth n1 l a)) n _).\n  apply retract_unif; intros.\n  rewrite <- (Umult_one_right ([1/]1+n)).\n  apply Umult_le_compat; auto with arith.\n Qed.\n\n Lemma sum_support_comm : forall A B (d:distr B) a (l:list A) f,\n  mu (sum_support a l) (fun x => mu d (fun y => f y x)) ==\n  mu d (fun y => mu (sum_support a l) (fun x => f y x)).\n Proof.\n  intros A B d a l f.  \n  generalize (eq_distr_elim (prod_comm_sum_support a l d) (fun p => f (fst p) (snd p))).\n  repeat rewrite Mlet_simpl; intro; symmetry; trivial.\n Qed.\n\n Add Parametric Morphism A B : (prod_comm (A:=A) (B:=B))\n  with signature Oeq (O:=Distr A) ==> Oeq (O:=Distr B) ==> iff \n  as prod_comm_morphism_aux.\n Proof.\n  intros d1 d2 H d3 d4 H0; unfold prod_comm.\n  rewrite H; rewrite H0; split; trivial.\n Qed. \n\n Lemma prod_comm_sym : forall A B (d1:Distr A) (d2:Distr B),\n  prod_comm d1 d2 -> prod_comm d2 d1.\n Proof.\n  unfold prod_comm; intros.\n  rewrite H; apply eq_distr_intro; trivial.\n Qed.\n\nEnd PROD_COMM.\n\n\nAdd Parametric Morphism A B : (prod_comm (A:=A) (B:=B))\n with signature Oeq (O:=Distr A) ==> Oeq (O:=Distr B) ==> iff \n as prod_comm_morphism.\nProof.\n intros d1 d2 H d3 d4 H0; unfold prod_comm.\n rewrite H; rewrite H0; split; trivial.\nQed. \n\nLemma prod_distr_Mlet_l : forall (A B C:Type) (d1:Distr A) (d2:Distr C) (F:A -> Distr B),\n prod_distr (Mlet d1 F) d2 == Mlet d1 (fun x => prod_distr (F x) d2).\nProof.\n intros; apply eq_distr_intro; trivial.\nQed.\n\nLemma prod_distr_Mlet_r : forall (A B C:Type)(d1:Distr A) (d2:Distr C) (F:A -> Distr B),\n prod_comm d1 d2 ->\n prod_distr d2 (Mlet d1 F) == Mlet d1 (fun x => prod_distr d2 (F x)).\nProof.\n intros; apply eq_distr_intro; simpl; intros.\n exact (eq_distr_elim H (fun p =>  mu (F (snd p)) (fun x1 => f ((fst p), x1)))).\nQed.\n\nLemma prod_distr_Mlet2 : forall (A B A' B' : Type) (d1:Distr A) (d2:Distr A') \n (F1:A -> Distr B) (F2:A' -> Distr B'),\n (forall x, prod_comm (F1 x) d2) ->\n prod_distr (Mlet d1 F1) (Mlet d2 F2) ==\n Mlet (prod_distr d1 d2) (fun p => prod_distr (F1 (fst p)) (F2 (snd p))).\nProof.\n intros; rewrite prod_distr_Mlet_l.\n assert (H0:(fun x => prod_distr (F1 x) (Mlet d2 F2)) ===\n            (fun x => Mlet d2 (fun y => prod_distr (F1 x) (F2 y)))).\n intro; apply prod_distr_Mlet_r; apply prod_comm_sym; trivial.\n rewrite H0; apply eq_distr_intro; trivial.\nQed.\n\nLemma prod_comm_Mlet : forall (A B C : Type) (d1:Distr A) (d2:Distr C) (F:A -> Distr B),\n prod_comm d1 d2 ->\n (forall x, prod_comm (F x) d2) ->\n prod_comm (Mlet d1 F) d2.\nProof.\n intros; unfold prod_comm.\n rewrite prod_distr_Mlet_l; rewrite prod_distr_Mlet_r; trivial.\n rewrite Mcomp; apply Mlet_morph; trivial.\nQed.\n\nLemma prod_comm_drestr : forall (A B:Type) (f:A -> bool) (dA:distr A) (d:Distr B),\n prod_comm dA d ->\n prod_comm (drestr dA f) d.\nProof.\n unfold drestr; intros.\n apply prod_comm_Mlet; trivial.\n intro a; destruct (f a).\n apply prod_comm_Munit.\n apply prod_comm_distr0.\nQed.\n\nLemma prod_comm_Mlet2 : forall (A B A' B' : Type) (d1:Distr A) (d2:Distr A') \n (F1:A -> Distr B) (F2:A' -> Distr B'),\n prod_comm d1 d2 ->\n (forall x, prod_comm (F1 x) d2) ->\n (forall x, prod_comm (F2 x) d1) ->\n (forall x y, prod_comm (F1 x) (F2 y)) ->\n prod_comm (Mlet d1 F1) (Mlet d2 F2).\nProof.\n intros; apply prod_comm_Mlet; intros; apply prod_comm_sym; apply prod_comm_Mlet.\n apply prod_comm_sym; trivial.\n trivial.\n apply prod_comm_sym; trivial.\n intro; apply prod_comm_sym; trivial.\nQed.\n\nLemma prod_comm_lub : forall A B (f:natO -m> cDistr A) (d:cDistr B),\n (forall n, prod_comm (f n) d) ->\n prod_comm (lub f) d.\nProof.\n intros; rewrite <- (lub_cte d).\n unfold prod_comm.\n do 2 rewrite lub_prod_distr.\n apply eq_distr_intro; intro g; simpl.\n apply lub_eq_compat; simpl.\n refine (@ford_eq_intro _ _ _ _ _); intro; simpl.\n apply (eq_distr_elim (H n) g). \nQed.\n\nLemma finite_sum_prod (A1 A2 : Type) k1 k2 l1 l2 (f : (A1 * A2) -> U) :\n ((length l1) <= k1)%nat -> ((length l2) <= k2)%nat ->  (0 < k1)%nat  -> (0 < k2)%nat ->\n finite_sum (fun a : (A1 * A2) => [1/]1+pred (k1*k2) * f a) (list_prod l1 l2) ==\n finite_sum\n (fun a : A1 => [1/]1+pred k1 * finite_sum (fun a0 : A2 => [1/]1+pred k2 * (f (a,a0))) l2) l1.\nProof.\n induction l1; simpl in *; intros; trivial.\n rewrite finite_sum_app, finite_sum_map; simpl; auto.\n rewrite IHl1; try omega; try apply H1.\n apply Uplus_eq_compat_left.\n generalize H0; clear H0 IHl1.\n induction l2; simpl in *; intros; auto.\n rewrite IHl2; try omega.\n rewrite Udistr_plus_left, Umult_assoc, Unth_prod.\n rewrite <- (S_pred k1 0%nat), <- (S_pred k2 0%nat) ; trivial; try split; try omega.\n transitivity ([1/]1+pred k2); auto.\n transitivity ([1-] finite_sum (fun a1 : A2 => [1/]1+pred k2) l2).  \n rewrite <- (sigma_finite_sum a0), Unth_prop_sigma.\n apply Uinv_le_compat.\n apply sigma_incr; omega.\n apply Uinv_le_compat.\n repeat rewrite <- (sigma_finite_sum a0).\n apply sigma_le_compat; intros; auto.\nQed.\n\nSection RANGE.\n\n Variable A:Type.\n Variable P: A -> Prop. \n\n Lemma distr0_range : forall (d:Distr A), \n  0 == mu d (fone A) -> range P d.\n Proof.\n  red; auto.\n Qed.\n\n Lemma lub_range : forall (F:natO -m> cDistr A),\n  (forall n, range P (F n)) -> range P (lub F).\n Proof.\n  red; intros.\n  transitivity (lub (fmon_cte natO (O2:=U) 0)).\n  symmetry; apply lub_cte. \n  simpl; apply lub_eq_compat.\n  refine (ford_eq_intro _).\n  intro; simpl; apply H; trivial.\n Qed.\n\n Lemma range_stable_eq : forall (d1 d2:Distr A), \n  d1 == d2 -> range P d1 -> range P d2.\n Proof.\n  unfold range; intros.  \n  rewrite <- (eq_distr_elim H); auto.\n Qed.\n\nEnd RANGE.\n\nHint Immediate distr0_range.\n\nLemma range_True : forall A (d:Distr A), range (fun _ => True) d.\nProof.\n unfold range; intros.\n transitivity (mu d (fun _ => 0)).\n symmetry; apply mu_0.\n apply mu_stable_eq.\n refine (ford_eq_intro _); auto.\nQed.\n\nLemma range_weaken : forall (A:Type) (P1 P2:A -> Prop),\n (forall x, P1 x -> P2 x) ->  forall d, range P1 d -> range P2 d.\nProof.\n unfold range; intros; auto.\nQed.\n\nDefinition Fimp (A:Type) (P1 P2:A -> Prop) := forall a, P1 a -> P2 a.\n\nLemma Fimp_trans : forall (A:Type) (P1 P2 P3:A -> Prop), \n Fimp P1 P2 -> Fimp P2 P3 -> Fimp P1 P3.\nProof. \n unfold Fimp; auto.\nQed.\n\nLemma Fimp_refl :  forall (A:Type) (P:A -> Prop), Fimp P P.\nProof. \n unfold Fimp; trivial.\nQed. \n\nAdd Parametric Relation A : (A -> Prop) (Fimp (A:=A))\n reflexivity proved by (@Fimp_refl A)\n transitivity proved by (@Fimp_trans A)\n as Fimp_rel.\n\nAdd Parametric Morphism A : (range (A:=A))\n with signature Fimp (A:=A) --> Oeq (O:=Distr A) ==> inverse impl \n as range_morph2.\nProof.\n unfold Basics.flip, impl, Fimp; intros P Q H d1 d2 H0 H1.\n apply range_weaken with Q; trivial.\n apply range_stable_eq with d2; auto.\nQed.\n\nLemma range_Munit: forall (A B:Type) (P: A -> B -> Prop) x y,\n  P x y -> range (fun xy => P (fst xy) (snd xy)) (Munit (x,y)).\nProof.\n intros A B P x y Hxy f Hf.\n refine (Hf (x,y) Hxy).\nQed.\n\nLemma range_Mlet: forall (A B:Type) (P:A -> Prop) (Q:B -> Prop)\n (d:Distr A) (F:A -> Distr B),\n range P d ->\n (forall x, P x -> range Q (F x)) ->\n range Q (Mlet d F).\nProof.\n unfold range; intros; simpl; auto.\nQed.\n\nLemma mu_range : forall A (P:A -> bool) (d:Distr A), \n mu d (fun a => if P a then 1 else 0) == 1 ->\n range P d.\nProof.\n intros A P d H f Hf.\n apply Ole_antisym; [trivial | ].\n rewrite <- Uinv_one, <- (Uinv_eq_compat H).\n eapply Ole_trans; [ | apply mu_stable_inv].\n apply mu_le_compat; trivial.\n apply ford_le_intro; intro.\n unfold finv; case_eq (P n); intro.\n rewrite <- Hf; trivial.\n rewrite Uinv_zero; trivial.\nQed.\n\nLemma range_mu : forall A (P:A -> bool) (d:Distr A), \n range P d ->\n mu d (fun a => if P a then 1 else 0) == mu d (fone _).\nProof.\n intros A P d H.\n apply range_eq with P.\n exact H.\n intros a Ha; rewrite Ha; trivial.\nQed.\n\nLemma range_strengthen : forall A (d:Distr A) (P Q:A -o> boolO),\n mu d (fone _) == 1%U ->\n range P d -> \n range Q d ->\n range (P [&&] Q) d.\nProof.\n intros; apply mu_range.\n rewrite <- (mu_range_strenghten _ Q H0).\n transitivity (mu d (fone _)); [ | trivial].\n apply range_mu; trivial. \nQed.\n\n\n(** * Lift of a relation to a product distribution *)\nSection RELATIONS.\n\n Variable A B:Type.\n\n Variable P Q: A -> B -> Prop.\n\n Hypothesis Pdec : forall x y, {P x y} + {~P x y}.\n\n Definition prodP := fun xy => P (fst xy) (snd xy).\n\n Definition caract2 p:= if Pdec (fst p) (snd p) then 1 else 0.\n \n Definition Fimp2 := forall x y, P x y -> Q x y.\n\nEnd RELATIONS.\n\n\nLemma Fimp2_trans : forall (A B:Type) (P1 P2 P3:A -> B -> Prop),\n Fimp2 P1 P2 -> Fimp2 P2 P3 -> Fimp2 P1 P3.\nProof. \n unfold Fimp2; auto. \nQed.\n\nLemma Fimp2_refl :  forall (A B:Type) (P:A -> B -> Prop), Fimp2 P P.\nProof. \n unfold Fimp2; trivial.\nQed.\n\nAdd Parametric Relation A B : (A -> B -> Prop) (Fimp2 (A:=A) (B:=B))\n reflexivity proved by (@Fimp2_refl A B)\n transitivity proved by (@Fimp2_trans A B)\n as Fimp2_rel.\n\n(** Lifting a relation [R] to a product distribution [d].\n    There shall exist two distributions [d1] and [d2] s.t. the projections\n    of [d] coincide with each of them respectively, and [R] covers the whole\n    support of [d].\n*)\nRecord lift (A B:Type) (R:A -> B -> Prop) (d:Distr (A * B)) \n (d1:Distr A) (d2:Distr B) : Type := {\n  l_fst : forall f, mu d (fun x => f (fst x)) == mu d1 f;\n  l_snd : forall f, mu d (fun x => f (snd x)) == mu d2 f;\n  l_range : range (prodP R) d\n}.\n\nLemma distr0_lift : forall A B (R:A -> B -> Prop), \n lift R (distr0 _) (distr0 _) (distr0 _).\nProof.\n intros; constructor; trivial.\n apply distr0_range; trivial.\nQed.\n\nLemma lift_True : forall (A B:Type) (d1:Distr A) (d2:Distr B),\n mu d1 (fone _) == 1 ->\n mu d2 (fone _) == 1 ->\n lift (fun _ _ => True) (prod_distr d1 d2) d1 d2.\nProof.\n intros A B d1 d2.\n constructor; simpl; intros.\n apply (mu_stable_eq d1); simpl; apply ford_eq_intro; intros.\n change (fun _ => f n) with (fcte B (f n)).\n rewrite (mu_cte d2 (f n)), H0; trivial.\n change (mu d1 (fcte _ (mu d2 (fun b => f b))) == mu d2 f).\n rewrite (mu_cte d1), H, Umult_one_right; trivial.\n apply mu_stable_eq; trivial.\n refine (ford_eq_intro _); trivial.\n unfold prodP; apply range_True.\nQed.\n\nLemma lift_mu : forall (A B:Type) (R:A -> B -> Prop) (d1:Distr A) (d2:Distr B) d,\n lift R d d1 d2 ->\n forall f h,\n  (forall a b, R a b -> f a == h b) -> mu d1 f == mu d2 h.\nProof.\n intros A B R d1 d2 d H f h Heq.\n destruct H as [H1 H2 H3].\n rewrite <- H1, <- H2.\n apply range_eq with (1:=H3); auto.\nQed.\n\nLemma lift_weaken : forall A B (P Q:A -> B -> Prop), \n (forall x y, P x y -> Q x y) ->\n forall d d1 d2, lift P d d1 d2 -> lift Q d d1 d2.\nProof.\n intros A B P Q H d d1 d2 (Hfst, Hsnd, Hsupp).\n constructor; trivial.\n apply range_weaken with (prodP P); trivial.\n unfold prodP; auto.\nQed.\n\nLemma lift_eq_refl : forall A (d:distr A), \n lift (@eq A) (Mlet d (fun x => Munit (x,x))) d d.\nProof.\n intros; constructor; intros.\n simpl; apply (mu_stable_eq d); refine (ford_eq_intro _); trivial.\n simpl; apply (mu_stable_eq d); refine (ford_eq_intro _); trivial.\n red; simpl; intros.\n transitivity (mu d (fzero A)).\n auto.\n apply (mu_stable_eq d); refine (ford_eq_intro _).\n intros; rewrite <- H; trivial.\n unfold prodP; trivial.\nQed.\n\nLemma lift_refl : forall (A:Type) (R:relation A),\n reflexive A R -> forall d, lift R (Mlet d (fun x => Munit (x,x))) d d.\nProof.\n intros A R R_refl d.\n apply lift_weaken with eq; [intros; subst; apply R_refl | ].\n unfold prod_distr; simpl.\n apply lift_eq_refl.\nQed.\n\nLemma lift_unit : forall A B (a:A) (b:B) (R:A -> B -> Prop), \n R a b -> lift R (Munit (a,b)) (Munit a) (Munit b).\nProof.\n intros; constructor; trivial.\n unfold range; intros; rewrite Munit_eq; auto. \nQed.\n\nLemma lift_Mlet : forall A1 A2 B1 B2 \n (R1:A1 -> B1 -> Prop) (R2:A2 -> B2 -> Prop) d d1 d2 F F1 F2,\n lift R1 d d1 d2 ->\n (forall x y, R1 x y -> lift R2 (F (x,y)) (F1 x) (F2 y)) ->\n lift R2 (Mlet d F) (Mlet d1 F1) (Mlet d2 F2).\nProof.\n intros; constructor; intros; simpl.\n rewrite <- H.(l_fst). \n apply (range_eq H.(l_range)).\n intros (x,y) H1; apply (H0 _ _ H1).(l_fst). \n rewrite <- H.(l_snd).\n apply (range_eq H.(l_range)).\n intros (x,y) H1; apply (H0 _ _ H1).(l_snd). \n apply range_Mlet with (1:=H.(l_range)).\n intros (x,y) H1; apply (H0 _ _ H1).(l_range).\nQed.\n\nLemma lift_cond : forall A B (R:A -> B -> Prop) b dt dt1 dt2 df df1 df2,\n (b = true  -> lift R dt dt1 dt2) ->\n (b = false -> lift R df df1 df2) ->\n lift R (if b then dt else df) (if b then dt1 else df1) (if b then dt2 else df2).\nProof.\n destruct b; auto. \nQed.\n\nLemma lift_stable_eq : forall A B (R:A -> B -> Prop) \n (d d' : Distr (A*B)) (d1 d1':Distr A) (d2 d2':Distr B),\n d == d' -> \n d1 == d1' -> \n d2 == d2' -> \n lift R d d1 d2 -> lift R d' d1' d2'.\nProof.\n intros A B R d d' d1 d1' d2 d2' Heq Heq1 Heq2 (Hfst, Hsnd, Hrange).\n constructor; intros.\n transitivity (mu d1 f); [rewrite <- Hfst | ]; auto. \n transitivity (mu d2 f); [rewrite <- Hsnd | ]; auto. \n apply range_stable_eq with (1:=Heq); trivial.\nQed.\n\nLemma lift_sym : forall A (R:A -> A -> Prop) (d:distr (A * A)) \n (d1:Distr A) (d2:Distr A), \n lift R d d1 d2 ->\n lift (transp _ R) (Mlet d (fun p => Munit (snd p, fst p))) d2 d1.\nProof.\n intros A R d d1 d2 (Hfst, Hsnd, Hrange).\n constructor; intros; [ | | unfold range]; simpl; auto.\nQed.\n\nAdd Parametric Morphism A B : (lift (A:=A) (B:=B))\n with signature Fimp2 (A:=A) (B:=B) --> \n  Oeq (O:=Distr (A * B)) ==> Oeq (O:=Distr A) ==> Oeq (O:=Distr B) ==> inverse impl\n as lift_morph.\nProof.\n unfold impl, Fimp2; intros R1 R2 H d1 d2 H0 d3 d4 H1 d5 d6 H2 H3.\n apply lift_weaken with R2; trivial.\n apply lift_stable_eq with d2 d4 d6; auto.\nQed.\n\n\nSection LIFT_LUB.\n\n Variables A B : Type.\n Variable R : A -> B -> Prop.\n Variable F : natO -m> cDistr (A * B). \n Variable F1 : natO -m> cDistr A.\n Variable F2 : natO -m> cDistr B.\n\n Hypothesis liftn : forall n, lift R (F n) (F1 n) (F2 n).\n\n Lemma lift_lub : lift R (lub F) (lub F1) (lub F2).\n Proof.\n  constructor; intros; simpl.\n  apply lub_eq_compat.\n  refine (ford_eq_intro _); intro; simpl; apply (liftn n).(l_fst).\n  apply lub_eq_compat.\n  refine (ford_eq_intro _); intro; simpl; apply (liftn n).(l_snd).\n  unfold range; intros.\n  transitivity (lub (fmon_cte natO (O2:=U) 0)).\n  symmetry; apply lub_cte.\n  simpl; apply lub_eq_compat.\n  refine (ford_eq_intro _); intro; simpl.\n  apply (liftn n).(l_range); trivial.\n Qed.\n\nEnd LIFT_LUB.\n\n\nSection DISCRETE.\n \n Variable A : Type.\n\n Section In_class.\n\n   Variable R : A -> A -> Prop.\n   Variable uR : A -> MF A.\n   Hypothesis cover_uR : forall a, cover (R a) (uR a).\n   Hypothesis R_trans : transitive A R.\n   Hypothesis R_sym : symmetric A R.\n   Hypothesis R_refl : reflexive A R.\n\n   Variable points : nat -> A.\n\n   (* [not_first_repr k] decide if [points k] is not the first point in is class,\n      in that case [points k] is not the representant of the class *)\n   Definition not_first_repr k := sigma (fun i => uR (points k) (points i)) k.\n\n   Lemma cover_not_first_repr :  \n    cover (fun k => exc (fun k0 => (k0 < k)%nat /\\ R (points k) (points k0))) not_first_repr.\n   Proof.\n    red; split; intros.\n    apply H;[auto | intros k0 (H1, H2)].\n    apply Ole_trans with (2:= sigma_le (fun i : nat => uR (points x) (points i)) H1).\n    rewrite (cover_eq_one _ (cover_uR (points x)) H2); trivial.\n    unfold not_first_repr; rewrite sigma_zero; trivial; intros.\n    apply (cover_elim (cover_uR (points x)) (points k)); [auto | | ];\n    intros [H4 H5]; trivial.\n    elim H; apply exc_intro with k; auto.\n  Qed.\n\n  (* [in_classes a] decides in [a] is in relation with one element of [points] *)\n  Definition in_classes a := serie (fun k => uR a (points k)).\n\n  Definition In_classes a := exc (fun k => R a (points k)).\n\n  Lemma cover_in_classes : cover In_classes in_classes.\n  Proof.\n   unfold In_classes; red; split; intros.\n   apply H;[auto | intros k H1].\n   apply Ole_trans with (2:=serie_le (fun k : nat => uR x (points k)) k).\n   rewrite (cover_eq_one _ (cover_uR x) H1); trivial.\n   unfold in_classes; rewrite serie_zero; trivial.\n   intros k; apply (cover_elim (cover_uR x) (points k)); [auto | | ]; intros [H4 H5]; trivial.\n    elim H; apply exc_intro with k; trivial.\n  Qed.\n\n  (* [in_class a k] decides in [a] is in relation with [points k] and\n     [points k] is the representant of it class *)\n  Definition in_class a k := \n     [1-] (not_first_repr k) * uR (points k) a.\n\n  Definition In_class a k :=\n     R (points k) a /\\\n     (forall k0, (k0 < k)%nat -> ~R (points k) (points k0)).\n  \n  Lemma cover_in_class : forall a, cover (In_class a) (in_class a).\n  Proof.\n   unfold in_class, In_class;split;intros.\n   destruct H.\n   rewrite (cover_eq_one _ (cover_uR (points x)) H); Usimpl.\n   rewrite (cover_eq_zero _ cover_not_first_repr);[auto| ].\n   intros Hex;apply Hex;[auto | intros].\n   destruct H1;apply (H0 x0);trivial.\n   apply (cover_elim (cover_uR (points x)) a);[auto | | ];intros [H1 H2].\n   rewrite H2;trivial.\n   apply (cover_elim cover_not_first_repr x);[auto | | ];intros [H3 H4].\n   elim H;split;trivial.\n   red;intros;apply H3.\n   apply exc_intro with k0;auto.\n   rewrite H4;Usimpl;auto.\n  Qed.\n\n  Lemma in_class_wretract : forall x, wretract (in_class x).\n  Proof.\n   red; intros.\n   apply (cover_elim (cover_in_class x) k);[auto | | ];intros [H H0];\n   rewrite H0;[auto | ].\n   rewrite sigma_zero; [auto | intros].\n   destruct H;apply (cover_eq_zero _ (cover_in_class x)).\n   intros (H3, H4).\n   elim (H2 _ H1).\n   eapply R_trans;eauto.\n  Qed.\n \n  Lemma in_classes_refl : forall k, in_classes (points k) == 1.\n  Proof.\n   intros k; apply (cover_eq_one _ cover_in_classes).\n   red; intros; apply exc_intro with k; trivial.\n  Qed.\n\n  Lemma cover_serie_in_class : cover (fun a => exc (In_class a)) (fun a => serie (in_class a)).\n  Proof.\n   split; intros.\n   apply H;[auto | intros k H1].\n   apply Ole_trans with (2:=serie_le (in_class x) k).\n   rewrite (cover_eq_one _ (cover_in_class x) H1); trivial.\n   rewrite serie_zero; trivial.\n   intros k; apply (cover_elim (cover_in_class x) k); [auto | | ]; intros [H4 H5]; trivial.\n   elim H; apply exc_intro with k; trivial.\n  Qed.\n\n  Lemma in_classes_in_class : forall a, \n     in_classes a == serie (in_class a).\n  Proof.\n   intros a; apply (cover_elim cover_in_classes a); [ auto | | ]; intros [H1 H2].\n   rewrite H2; symmetry; apply serie_zero; intros.\n   apply (cover_elim (cover_in_class a) k);[auto | | ];intros (H3, H4);rewrite H4;trivial.\n   elim H1;destruct H3;apply exc_intro with k;auto.\n   rewrite H2;split;trivial.\n   assert (exc (In_class a)).\n     apply H1;[auto | ].\n     induction x using Wf_nat.lt_wf_ind; intros.\n     apply (cover_elim cover_not_first_repr x); [ auto | | ]; intros [H3 H4].\n     apply exc_intro with x; split;auto.\n     red;intros;elim H3.\n     apply exc_intro with k0;auto.\n     apply H3;[auto | ].\n     intros m (H5, H6);apply (H m);eauto.\n   assert (W:= cover_eq_one a cover_serie_in_class H);simpl in W;rewrite W.\n   trivial.\n  Qed.\n\n  Variable d : Distr A.\n\n  Definition Discrete := range In_classes d.\n\n  Definition coeff k := ([1-] (not_first_repr k)) * mu d (uR (points k)).\n\n  Lemma mu_discrete : Discrete -> forall f, \n    (forall x y, R x y -> f x == f y) ->\n    mu d f == discrete coeff points f.\n  Proof.\n   intros Hdiscr f Hf; rewrite discrete_simpl.\n   unfold coeff.\n   transitivity (serie (fun k => mu d (fun a => f a * (in_class a k)))).\n   rewrite <- mu_serie_eq.\n   unfold serie_fun.\n   transitivity (mu d (fun a : A => in_classes a * f a)).\n   apply range_cover with (P:= In_classes); trivial.\n   apply cover_in_classes.\n   apply mu_stable_eq; simpl; apply ford_eq_intro; intro a.\n   rewrite Umult_sym, serie_mult; [ | apply in_class_wretract].\n   Usimpl; apply in_classes_in_class.\n   intros; apply wretract_le with (2:=in_class_wretract x); auto. \n   apply serie_eq_compat; intros.\n   assert (W:= mu_stable_mult d (f (points k) * [1-] not_first_repr k )).\n   rewrite Umult_sym, Umult_assoc, <- W.\n   apply mu_stable_eq; simpl; apply ford_eq_intro; intros; unfold fmult.\n   unfold in_class;rewrite Umult_assoc.\n   apply (cover_elim (cover_uR (points k)) n); [auto | | ]; intros [H5 H6].\n   rewrite H6; repeat Usimpl; trivial.\n   rewrite (Hf _ _ H5);trivial.\n  Qed. \n\n End In_class.\n\n Variable carA : A -> MF A.\n\n Hypothesis carA_prop : forall a, cover (@eq A a) (carA a).\n\n Record is_Discrete (d:Distr A) : Type := mkDiscr {\n  D_points : nat -> A;\n  D_Discr : Discrete (@eq A) D_points d\n }.\n  \n Lemma is_Discrete_eq_compat: forall (d1 d2:Distr A),\n   d2 == d1 ->\n   is_Discrete d2 ->\n   is_Discrete d1.\n Proof.\n  intros d1 d3 Hd [p H].\n  apply mkDiscr with p.\n  refine (range_stable_eq Hd H).\n Qed.\n\n Lemma mu_is_Discrete : forall d (D:is_Discrete d),\n  forall f, mu d f == discrete (coeff carA D.(D_points) d) (D.(D_points)) f.\n Proof.\n  intros; apply mu_discrete with (@eq A);auto.\n  apply eq_Transitive.\n  apply eq_Symmetric.\n  apply D_Discr.\n  intros;subst;trivial.\n Qed.\n\n \n\n Section Class1.\n\n   Variable R : A -> A -> Prop.\n   Variable uR : A -> MF A.\n   Hypothesis cover_uR : forall a, cover (R a) (uR a).\n   Hypothesis R_trans : transitive A R.\n   Hypothesis R_sym : symmetric A R.\n   Hypothesis R_refl : reflexive A R.\n\n   Lemma mu_is_Discrete_R :\n     forall d (D:is_Discrete d) f,\n     mu d f == serie (fun k => mu (distr_mult (fun a => in_class uR (D_points D) a k) d) f).\n     unfold distr_mult;simpl;intros.\n     assert (W:= mu_serie_eq d (fun k x => in_class uR (@D_points d D) x k * f x));simpl in W.\n     rewrite <- W;clear W.\n     repeat rewrite (mu_is_Discrete D).\n     unfold discrete;simpl;apply serie_eq_compat;intros k.\n     apply Umult_eq_compat;[trivial | ].\n     unfold serie_fun;simpl.\n     transitivity (f (@D_points d D k) * 1);[auto | ].\n     transitivity \n       (f (@D_points d D k) * serie (in_class uR (@D_points d D) (@D_points d D k))).\n     apply Umult_eq_compat;[trivial | ].\n     symmetry; rewrite <- (in_classes_in_class (R:=R)); auto.\n     apply in_classes_refl with R; trivial.\n     rewrite <- serie_mult.\n     apply serie_eq_compat;auto.\n     apply in_class_wretract with R;auto.\n     intros; apply wretract_le with (2:=in_class_wretract uR cover_uR R_trans R_sym (@D_points d D) x); auto.\n   Qed.\n\n End Class1.\n\n Lemma is_Discrete_Munit : forall a, is_Discrete (Munit a). \n Proof.\n  intros a; apply mkDiscr with (D_points := fun _ => a).\n  red; red; intros.\n  refine (H a _).\n  red; apply exc_intro with O; trivial.\n Qed.\n\n Lemma bij_n_nxn_aux : forall k, \n  (0 < k)%nat ->\n  sigT (fun i:nat => {j : nat | k = (exp2 i * (2 * j + 1))%nat}).\n Proof.\n  induction k using lt_wf_rec; intros.\n  destruct (even_odd_dec k).\n  destruct (H (div2 k)) as (i, (j, Heq)).\n  apply lt_div2; auto with arith.\n  inversion e.\n  rewrite <- H1 in H0; inversion H0.\n  inversion H1; simpl; auto with arith.\n  exists (S i)%nat; exists j.\n  rewrite (even_double _ e).\n  rewrite Heq; unfold double; simpl exp2; ring.\n  exists O; exists (div2 k).\n  apply trans_eq with (1:= odd_double _ o).\n  unfold double; simpl exp2; ring.\n Qed.\n\n Definition bij_n_nxn k :=\n  match @bij_n_nxn_aux (S k) (lt_O_Sn k) with\n  | existT i (exist j _) => (i, j)\n  end.\n\n Lemma mult_eq_reg_l : forall n m p, \n  (0 < p -> p * n = p * m -> n = m)%nat.\n Proof.\n  intros.\n  destruct p;[inversion H | ].\n  apply le_antisym;\n   apply mult_S_le_reg_l with p; rewrite H0; trivial.\n Qed.\n \n Lemma even_exp2 : forall n, even (exp2 (S n)).\n Proof.\n  induction n; simpl.\n  repeat constructor.\n  apply even_even_plus.\n  exact IHn.\n  rewrite plus_0_r; exact IHn.\n Qed.\n\n Lemma odd_2p1 : forall n, odd (2 * n + 1).\n Proof.\n  intros; apply odd_plus_r;[ apply even_mult_l | ];\n   repeat constructor.\n Qed.\n \n Lemma bij_surj : forall i j, exists k, \n  bij_n_nxn k = (i, j).\n Proof.\n  intros i j.\n  exists (exp2 i * (2 * j + 1) - 1)%nat.\n  unfold bij_n_nxn.\n  destruct (bij_n_nxn_aux (lt_O_Sn (exp2 i * (2 * j + 1) - 1))) as (i', (j', H)).\n  assert (exp2 i * (2 * j + 1) = exp2 i' * (2 * j' + 1))%nat .\n  rewrite <- H.\n  assert (0 < exp2 i * (2 * j + 1))%nat; [ | omega].\n  apply le_lt_trans with (O * (2 * j + 1))%nat; trivial.\n  apply mult_lt_compat_r.\n  apply exp2_pos.\n  rewrite plus_comm; simpl; auto with arith.\n  clear H.\n  generalize i j i' j' H0; clear H0 i j i' j'.\n  induction i; destruct i'; intros.\n  apply mult_eq_reg_l in H0; [ | apply exp2_pos].\n  rewrite plus_comm, (plus_comm (2 * j')) in H0.\n  apply plus_reg_l in H0; apply mult_eq_reg_l in H0.\n  rewrite H0; trivial.\n  auto with arith.\n  elimtype False.\n  apply not_even_and_odd with (exp2 0 * (2 * j + 1))%nat.\n  rewrite H0.\n  apply even_mult_l; apply even_exp2.\n  simpl exp2; rewrite mult_1_l; apply odd_2p1.\n  elimtype False.\n  apply not_even_and_odd with (exp2 0 * (2 * j' + 1))%nat.\n  rewrite <- H0.\n  apply even_mult_l; apply even_exp2.\n  simpl exp2; rewrite mult_1_l; apply odd_2p1.\n  assert (forall k, exp2 (S k) = 2 * exp2 k)%nat by trivial.\n  repeat rewrite H, <- mult_assoc in H0.\n  apply mult_eq_reg_l in H0; [ | auto with arith].\n  assert (W:= IHi _ _ _ H0); injection W; intros; subst; trivial.\n Qed.\n  \n Lemma is_Discrete_lub : forall (F:natO -m> cDistr A),\n  (forall n, is_Discrete (F n)) ->\n  is_Discrete (lub F).\n Proof.\n  intros F DF; apply mkDiscr with \n   (D_points := \n    (fun k => let (i, j) := bij_n_nxn k in D_points (DF i) j)).     \n  red; apply lub_range.\n  intros.\n  apply range_weaken with (2 := D_Discr (DF n)).\n  intros.\n  apply H;[ unfold In_classes; trivial | intros j Hj].\n  destruct (bij_surj n j) as (k, Heq).\n  red; apply exc_intro with k; rewrite Heq; trivial.\n Qed.\n\n Lemma is_Discrete_sum_support : forall a l, is_Discrete (sum_support a l).\n Proof.\n  intros.\n  apply mkDiscr with (D_points:=fun k => nth k l a).    \n  red; intros.\n  red; intros.\n  change (0 == sum_dom a l f).\n  symmetry; apply sum_dom_zero with (In_classes (@eq A) (fun k : nat => nth k l a)).\n  clear H; induction l; simpl; intros a1 H; destruct H.\n  red; apply exc_intro with O; auto.\n  apply (IHl _ H);[ unfold In_classes; trivial | intros k Hk].\n  red; apply exc_intro with (S k); auto.\n  intros; symmetry; auto.\n Qed.\n\nEnd DISCRETE.\n\n \nLemma is_Discrete_Mlet : forall (A B:Type) (d:Distr A) (F:A -> Distr B) \n (Dd : is_Discrete d),\n (forall a, (* In_points Dd.(D_points) a -> *) is_Discrete (F a)) ->\n is_Discrete (Mlet d F).\nProof.\n intros A B d f Dd DF.\n apply mkDiscr with (D_points := \n  fun k => let (i, j) := bij_n_nxn k in D_points (DF (D_points Dd i)) j).\n red.\n apply range_Mlet with (P := In_classes (@eq A) (D_points Dd)).\n exact Dd.(D_Discr).\n intros.\n set (DFx:=DF x). \n apply range_weaken with (2:=D_Discr DFx).\n intros.\n apply H;[ unfold In_classes; trivial | intros i Hi].\n apply H0;[ unfold In_classes; trivial | intros j Hj].\n destruct (bij_surj i j) as (k, Heq).\n red; apply exc_intro with k.\n rewrite Heq.\n rewrite Hj, <- Hi; trivial.\nQed.\n\n\nSection LIFT_TRANS.\n \n Variables A B C : Type.\n Variable carB : B -> MF B.\n\n Hypothesis carB_prop : forall a, cover (fun x => a = x) (carB a).\n \n Variable P : A -> B -> Prop.\n Variable Q : B -> C -> Prop.\n Variable R : A -> C -> Prop.\n\n Hypothesis P_Q_R : forall x y z, P x y -> Q y z -> R x z.\n\n Variable d  : Distr (A*B).\n Variable d' : Distr (B*C). \n Variable d1 : Distr A.\n Variable d2 : Distr B.\n Variable d3 : Distr C.\n\n Variable Hd : lift P d  d1 d2.\n Variable Hd': lift Q d' d2 d3.\n\n Definition dfst (b : B) : distr (B*C) := distr_mult (fun q => carB b (fst q)) d'.\n \n Definition dsnd (b : B) : distr (A*B) := distr_mult (fun q => carB b (snd q)) d.\n\n Lemma dfst_simpl : forall b f, \n  mu (dfst b) f = mu d' (fun q => carB b (fst q) * f q).\n Proof. \n  trivial.\n Qed.\n\n Lemma dfst_le : forall b, mu (dfst b) (fone (B * C)) <= mu d2 (carB b).\n Proof.\n  intro; rewrite dfst_simpl.\n  apply Ole_trans with (mu d' (fun q => carB b (fst q))); [auto | ].\n  rewrite Hd'.(l_fst); trivial.\n Qed.\n\n Lemma dsnd_simpl : forall b f, \n  mu (dsnd b) f = mu d (fun q => carB b (snd q) * f q).\n Proof. \n  trivial.\n Qed.\n\n Lemma dsnd_le : forall b, mu (dsnd b) (fone (A * B)) <= mu d2 (carB b).\n Proof.\n  intro; rewrite dsnd_simpl.\n  apply Ole_trans with (mu d (fun q => carB b (snd q))); [auto | ].\n  rewrite Hd.(l_snd); trivial.\n Qed.\n\n Hint Resolve dfst_le dsnd_le.\n\n Definition d_restr : B -> distr (A*B) := \n  fun b => distr_div (mu d2 (carB b)) (dsnd b) (dsnd_le b) .\n\n Definition d'_restr : B -> distr (B*C) := \n  fun b => distr_div (mu d2 (carB b)) (dfst b) (dfst_le b).\n\n Lemma d_restr_simpl : forall b f, \n  mu (d_restr b) f = mu d (fun q => carB b (snd q) * f q) / mu d2 (carB b).\n Proof. \n  trivial.\n Qed.\n\n Lemma d'_restr_simpl : forall b f, \n  mu (d'_restr b) f = mu d' (fun q => carB b (fst q) * f q) / mu d2 (carB b).\n Proof. \n  trivial.\n Qed.\n\n Definition dd' : distr (A * C) := \n  Mlet d2 (fun b => \n   Mlet (d_restr b) (fun p => \n    Mlet (d'_restr b) (fun q => Munit (fst p, snd q)))).\n\n Lemma dd'_range : range (prodP R) dd'.\n Proof.\n  red; intros.\n  unfold dd'; simpl.\n  transitivity (mu d2 (fzero B)); [auto | ].\n  apply (mu_stable_eq d2); simpl; apply ford_eq_intro; intro x; unfold fzero.\n  apply (Ueq_orc 0 (mu d2 (carB x))); auto; intros.\n  apply Oeq_sym; apply Udiv_by_zero; auto.\n  apply Oeq_sym; apply Udiv_zero_eq; auto.\n  apply Hd.(l_range); intros.\n  apply (cover_elim (carB_prop x) (snd x0)); auto; intros [H4 H5].\n  rewrite H5; auto.\n  rewrite H5; Usimpl.\n  apply Oeq_sym; apply Udiv_zero_eq; auto.\n  apply Hd'.(l_range); intros.\n  destruct x1; destruct x0; simpl.\n  simpl in H4; subst x.\n  apply (cover_elim (carB_prop b0) b); auto; intros [H6 H7].\n  rewrite H7; auto.\n  rewrite <- H; auto.\n  subst b0; red; apply P_Q_R with b; trivial.\n Qed.\n\n\n Section HYPO.\n\n  Hypothesis hyp_d1_d : forall f:A -> U,\n   mu d1 f == \n   mu d2 (fun b => mu d (fun p => carB b (snd p) * f (fst p)) / mu d2 (carB b)).\n\n  Lemma dd'_fst : forall f : A -> U, mu dd' (fun p => f (fst p)) == mu d1 f.\n  Proof.\n   intros; simpl.\n   apply Oeq_trans with \n    (mu d2 (fun a =>\n     (mu d (fun ab => carB a (snd ab) * \n      (mu d2 (fun b => carB a b * f (fst ab)) / mu d2 (carB a))) \n     / mu d2 (carB a)))).\n   apply (mu_stable_eq d2); simpl; apply ford_eq_intro; intros b; simpl.\n   apply Udiv_eq_compat_left.\n   apply (mu_stable_eq d); simpl; apply ford_eq_intro; intros; simpl; Usimpl.\n   apply Udiv_eq_compat_left.\n   apply (Hd'.(l_fst) (fun x => carB b x * f (fst n))).\n   apply Oeq_trans with \n    (mu d2 \n     (fun b => mu d (fun ab => carB b (snd ab) * f (fst ab)) / mu d2 (carB b))).\n   apply (mu_stable_eq d2); simpl; apply ford_eq_intro; intros b; simpl.\n   apply (Ueq_orc 0 (mu d2 (carB b))); auto; intros.\n   repeat (rewrite Udiv_by_zero; auto).\n   apply Udiv_eq_compat_left.\n   apply (mu_stable_eq d); simpl; apply ford_eq_intro; intros (a,b'); simpl.\n   Usimpl.\n   apply Oeq_trans with (f a * mu d2 (carB b) / mu d2 (carB b)).\n   apply Udiv_eq_compat_left.\n   rewrite <- (mu_stable_mult d2 (f a) (carB b)).\n   apply (mu_stable_eq d2); simpl; apply ford_eq_intro; intros; unfold fmult; auto.\n   rewrite Umult_div_assoc; auto.\n   apply Oeq_sym; apply hyp_d1_d.\n  Qed.\n\n  Hypothesis hyp_d3_d' : forall f:C -> U,\n   mu d3 f == \n   mu d2 (fun b => mu d' (fun p => carB b (fst p) * f (snd p)) / mu d2 (carB b)).\n\n  Lemma dd'_snd : forall f : C -> U, mu dd' (fun p => f (snd p)) == mu d3 f.\n  Proof.\n   intros; simpl.\n   apply Oeq_trans with \n    (mu d2 (fun b =>\n     (mu d2 (fun b' => carB b b' * \n      (mu d' (fun bc => carB b (fst bc) * f (snd bc)) / mu d2 (carB b)))\n     / mu d2 (carB b)))).\n   apply (mu_stable_eq d2); simpl; apply ford_eq_intro; intros b; simpl.\n   apply Udiv_eq_compat_left.\n   apply (Hd.(l_snd) (fun b' =>\n    carB b b' *\n    (mu d' (fun bc => carB b (fst bc) * f (snd bc)) / mu d2 (carB b)))).  \n   apply Oeq_trans with \n    (mu d2 (fun b =>\n     (mu d' (fun bc => carB b (fst bc) * f (snd bc)) / mu d2 (carB b)))).\n   apply (mu_stable_eq d2); simpl; apply ford_eq_intro; intros b; simpl.\n   apply (Ueq_orc 0 (mu d2 (carB b))); auto; intros.\n   repeat (rewrite Udiv_by_zero; auto).\n   apply Udiv_eq_compat_left.\n   apply Oeq_trans with \n    ((mu d' (fun bc => carB b (fst bc) * f (snd bc)) / mu d2 (carB b))\n     * (mu d2 (carB b))).\n   rewrite <- (mu_stable_mult d2 \n    (mu d' (fun bc => carB b (fst bc) * f (snd bc)) / mu d2 (carB b))\n    (carB b)).\n   apply (mu_stable_eq d2); simpl; apply ford_eq_intro; intros; unfold fmult; auto.\n   apply Udiv_mult; auto.\n   apply Ole_trans with (mu (dfst b) (fone (B*C))); auto.\n   apply Oeq_sym; apply hyp_d3_d'.\n  Qed.\n\n  Lemma lift_trans : lift R dd' d1 d3.\n  Proof.\n   constructor.\n   apply dd'_fst.\n   apply dd'_snd.\n   apply dd'_range.\n  Qed.\n\n End HYPO.\n\n\n Section DISCRETE.\n\n  Variable D2 : is_Discrete d2.\n\n  Let p := D2.(D_points).\n\n\n  Let c := coeff carB D2.(D_points) d2.\n \n  Lemma cp_retract : forall x, \n   wretract (fun k : nat => c k / c k * carB (p k) x).\n  Proof.\n   unfold wretract; intros.\n   apply (Ueq_orc 0 (c k)); [auto | | ]; intros.\n   rewrite Udiv_by_zero; trivial; repeat Usimpl; auto.\n   apply (cover_elim (carB_prop (p k)) x); [auto | | ]; intros [H4 H5].\n   rewrite H5; repeat Usimpl; auto.\n   rewrite sigma_zero; [ auto | intros].\n   apply (cover_elim (carB_prop (p k0)) x); [auto | | ]; intros [H2 H3].\n   rewrite H3; repeat Usimpl; auto.\n   elim H; unfold c, coeff.\n   set (P1:=fun k => exc (fun k0 => (k0 < k)%nat /\\ p k = p k0)).\n   rewrite (@cover_eq_one _ P1 _ k (cover_not_first_repr (@eq B) carB carB_prop (D_points D2))).\n   Usimpl; auto.\n   red; apply exc_intro with k0; split; trivial.\n   rewrite H2; trivial.\n  Qed.\n \n  Definition in_d2 b := serie (fun k : nat => c k / c k * carB (p k) b).\n  \n  Lemma in_d2_dec : forall b, orc (in_d2 b == 0) (in_d2 b == 1).\n  Proof.\n   intros; apply orc_intro; intros.\n   elim H.\n   unfold in_d2.\n   apply serie_zero.\n   intros k; apply (Ueq_orc (c k / c k * carB (p k) b) 0); auto; intros.\n   elim H0; split; trivial.\n   transitivity (c k / c k * carB (p k) b).\n   apply (Ueq_orc (c k)  0); auto; intros.\n   elim H1; rewrite H2, Udiv_by_zero; auto.\n   apply (cover_elim (carB_prop (p k)) b); [auto | | ]; intros [H4 H5].\n   elim H1; rewrite H5; auto.\n   rewrite H5, Udiv_refl; auto.\n   exact (serie_le (fun k0 : nat => c k0 / c k0 * carB (p k0) b) k).\n  Qed.\n\n  Lemma in_d2_p : forall k, ~c k == 0 -> in_d2 (p k) == 1.\n  Proof.\n   intros; unfold in_d2; split; trivial.\n   transitivity (c k / c k * carB (p k) (p k)).\n   rewrite Udiv_refl; [ auto | ].\n   rewrite (cover_eq_one _ (carB_prop (p k)) (refl_equal (p k))).\n   auto.\n   auto.\n   exact (serie_le (fun k0 : nat => c k0 / c k0 * carB (p k0) (p k)) k).\n  Qed.\n\n  Lemma lift_discr_fst : forall f : A -> U,\n   mu d1 f ==\n   mu d2 (fun b : B =>\n    mu d (fun p : A * B => carB b (snd p) * f (fst p)) / mu d2 (carB b)).\n  Proof.\n   intros; rewrite (mu_is_Discrete carB carB_prop D2).\n   rewrite discrete_simpl.\n   transitivity (serie (fun k =>\n    mu d (fun p0 => (c k / c k) * carB (p k) (snd p0) * f (fst p0)))).\n   rewrite <- mu_serie_eq.\n\n   2:intro x; apply wretract_le with (2:=cp_retract (snd x)); auto.\n\n   unfold serie_fun; rewrite <- Hd.(l_fst).\n   apply range_eq with (P:=fun x => in_d2 (snd x) == 1).\n   unfold range; intros; split; auto.\n   transitivity (mu d (fun p => [1-] (in_d2 (snd p)))).\n   apply (mu_monotonic d); intro x.\n   apply (in_d2_dec (snd x)); [auto | | ]; intros H0; [rewrite H0 | rewrite <- H]; auto.\n   rewrite (Hd.(l_snd) (fun x => [1-] in_d2 x)).\n   rewrite (mu_is_Discrete carB carB_prop D2), discrete_simpl.\n   rewrite serie_zero; [auto | intros].\n   fold (c k).\n   apply (Ueq_orc (c k) 0); [auto | | ]; intros.\n   rewrite H0; auto.\n   fold p; rewrite in_d2_p; [ Usimpl | ]; auto.\n   intros.\n   transitivity (serie (fun k => f (fst a) * (c k / c k * carB (p k) (snd a)))).\n   rewrite serie_mult.   \n   rewrite H; auto.\n   apply cp_retract.\n   apply serie_eq_compat; auto.\n   apply serie_eq_compat; intros.\n   set (g:=fun p0 => c k / c k * carB (p k) (snd p0) * f (fst p0)).\n   apply (Ueq_orc (c k) 0); [auto | | ]; intros.\n   fold c; rewrite H; Usimpl.\n   rewrite <- (mu_0 d).\n   apply (mu_stable_eq d).\n   simpl; apply ford_eq_intro; intros; unfold g; rewrite Udiv_by_zero; [Usimpl | ]; auto.\n   unfold c in H; unfold coeff in *.\n   apply (cover_elim (cover_not_first_repr (@eq B) carB carB_prop (D_points D2)) k);\n    [ auto | | ]; intros (H1, H2).\n   generalize H; clear H; rewrite H2; repeat Usimpl; intros.\n   rewrite Umult_sym, Udiv_mult; [auto | | ].\n   apply mu_stable_eq; unfold g; simpl; apply ford_eq_intro; intros.\n   rewrite Udiv_refl; auto.\n   unfold c; rewrite H2; Usimpl; auto.\n   auto.\n   apply Ole_trans with (2:=dsnd_le (p k)).\n   rewrite dsnd_simpl.\n   apply (mu_monotonic d); intro; unfold fone; auto.\n   elim H; rewrite H2;Usimpl; auto.\n  Qed.\n \n End DISCRETE.\n\nEnd LIFT_TRANS.\n\n\nSection LIFT_TRANS_DISCR.\n\n Variables A B C : Type.\n Variable carB : B -> MF B.\n \n Hypothesis carB_prop : forall a, cover (fun x => a = x) (carB a).\n\n Variable P : A -> B -> Prop.\n Variable Q : B -> C -> Prop.\n Variable R : A -> C -> Prop.\n\n Hypothesis P_Q_R : forall x y z, P x y -> Q y z -> R x z.\n\n Variable d  : Distr (A * B).\n Variable d' : Distr (B * C). \n Variable d1 : Distr A.\n Variable d2 : Distr B.\n Variable d3 : Distr C.\n\n Variable Hd : lift P d  d1 d2.\n Variable Hd': lift Q d' d2 d3.\n\n Lemma lift_trans_discr : is_Discrete d2 -> lift R (dd' carB Hd Hd') d1 d3.\n Proof.\n  intros D2.\n  apply lift_trans; auto; intros.\n  eapply lift_discr_fst; eauto.\n  assert (lift (fun c b => Q b c) (Mlet d' (fun p => Munit (snd p, fst p))) d3 d2).\n   constructor; intros; simpl.\n   apply Hd'.(l_snd).\n   apply Hd'.(l_fst).\n   unfold range; intros; simpl; apply Hd'.(l_range).\n   intros (b1,c1) H1; apply H; exact H1.\n  rewrite (lift_discr_fst carB carB_prop H D2); trivial.\n Qed.\n \nEnd LIFT_TRANS_DISCR.\n\n\nLemma lift_eq_trans_l : forall A B (R:A -> B -> Prop) d d1 d1' d' d2,\n lift (@eq _) d d1 d1' ->\n lift R d' d1' d2 ->\n lift R d' d1  d2.\nProof.\n intros; constructor.\n intros; assert (mu d1 f == mu d1' f).\n rewrite <- H.(l_fst); rewrite <- H.(l_snd).\n apply range_eq with (1:= H.(l_range)).\n intros a H1; rewrite H1; trivial.\n rewrite H1; apply H0.(l_fst).\n apply H0.(l_snd).\n apply H0.(l_range).\nQed.\n\nLemma lift_eq_trans_r : forall A B (R:A -> B -> Prop) d d1 d' d2 d2',\n lift (@eq _) d d2 d2' ->\n lift R d' d1 d2' ->\n lift R d' d1 d2.\nProof.\n intros; constructor.\n apply H0.(l_fst).\n intros; assert (mu d2 f == mu d2' f).\n rewrite <- H.(l_fst); rewrite  <- H.(l_snd).\n apply range_eq with (1:=H.(l_range)).\n intros a H1; rewrite H1; trivial.\n rewrite H1; apply H0.(l_snd).\n apply H0.(l_range).\nQed.\n\n\n(** Definition of negligible function *)\n\nDefinition negligible (f:nat -> U) := \n forall c, exists n0, forall n, (n0 <= n)%nat -> f n <= ([1/]1+n) ^ c.\n\nLemma negligible_0 : negligible (fun _ => 0).\nProof.\n unfold negligible.\n intro; exists 0%nat; auto.\nQed.\n\nLemma negligible_eq_stable : forall f g,\n f === g -> negligible f -> negligible g.\nProof.\n unfold negligible; intros.\n destruct (H0 c) as (n0, H1); clear H0.\n exists n0; intros.\n rewrite <- (H n); auto.\nQed.\n\nLemma negligible_le_stable : \n forall f g, (forall n, f n <= g n) -> negligible g -> negligible f.\nProof.\n unfold negligible; intros.\n destruct (H0 c) as (n0, H1); exists n0.\n intros n H2; apply Ole_trans with (2:= H1 n H2); auto.\nQed.\n\nLemma negligible_plus_stable : forall f g,\n negligible f -> negligible g -> negligible (fun n => f n + g n).\nProof.\n unfold negligible; intros.\n destruct c.\n  (* case 0 *)\n simpl; exists 0%nat; auto.\n \n  (* case S *)\n destruct (H (Datatypes.S (Datatypes.S c))) as (nf, Hf).\n destruct (H0 (Datatypes.S (Datatypes.S c))) as (ng, Hg).\n assert (exists max, (nf <= max)%nat /\\ (ng <= max)%nat).\n destruct (le_lt_dec nf ng);[ exists ng | exists nf] ; auto with arith.\n destruct H1 as (Smax, (Hfm, Hgm)).\n exists (Datatypes.S Smax); intros.\n apply Ole_trans with \n  (UP.Uexp ([1/]1+n)(Datatypes.S (Datatypes.S c)) + \n   UP.Uexp ([1/]1+n) (Datatypes.S(Datatypes.S c))).\n apply UP.Uplus_le_compat; auto with zarith.\n simpl.\n change ([1/]1+n * UP.Uexp ([1/]1+n) c) with \n  (UP.Uexp ([1/]1+n) (Datatypes.S c)).\n apply Ole_trans with\n  ([1/]1+1 * UP.Uexp ([1/]1+n) (Datatypes.S c) + \n   [1/]1+1 * UP.Uexp ([1/]1+n)  (Datatypes.S c)).\n apply UP.Uplus_le_compat; apply Umult_le_compat; auto;\n  apply UP.Unth_anti_mon; auto with zarith.\n rewrite <- UP.Udistr_plus_left.\n apply UP.half_twice_le.\n apply UP.le_half_inv.\n apply Ole_trans with ([1/]1+n).\n auto.\n apply UP.Unth_anti_mon; auto; omega.\nQed.\n\nLemma negligible_mult_stable : forall c f,\n negligible f -> negligible (fun n => c * f n).\nProof.\n unfold negligible; intros.\n destruct (H c0) as (n0, H1); exists n0; intros.\n transitivity (f n); auto.\nQed.\n\nLemma negligible_mult_poly : forall a f,\n negligible (fun k => f k * ([1/]1+k) ^ a) ->\n negligible f.\nProof.\n unfold negligible; intros a f H c.\n destruct (H (c + a))%nat as [n0 H1]; clear H. \n exists n0; intros n Hle.\n generalize (H1 n Hle); clear.\n induction a.\n repeat Usimpl; rewrite plus_0_r; trivial.\n rewrite <- plus_n_Sm; simpl.\n rewrite Umult_assoc, Umult_sym, Umult_assoc,  Umult_sym.\n rewrite (Umult_sym (([1/]1+n) ^ a)).\n intro H; apply IHa; clear IHa.\n apply Umult_le_simpl_left with ([1/]1+n); trivial.\nQed.\n\nLemma negligible_le : forall f g : nat -> U,\n (exists n0, forall n, (n0 <= n)%nat -> f n <= g n) -> \n negligible g -> negligible f.\nProof.\n intros f g [n0 Hle] Hg c.\n destruct (Hg c) as [n1 H].\n exists (Max.max n0 n1); intros.\n transitivity (g n).\n apply Hle.\n apply le_trans with (2:=H0); apply Max.le_max_l.\n apply H.\n apply le_trans with (2:=H0); apply Max.le_max_r.\nQed.\n\n\n Definition rcomp (A B C:Type) (P: A -> B -> Prop) (Q: B -> C -> Prop) : A -> C -> Prop :=\n  fun a c => exists b, P a b /\\ Q b c.\n  \n Lemma PER_r : forall (A: Type) (R:relation A) x1 x2, \n   @PER _ R ->\n   R x1 x2 ->\n   R x2 x2.\n Proof.\n  intros A R x1 x2  [Hsym Htrans] H.\n  exact (Htrans _ _ _ (Hsym _ _ H) H).\n Qed.\n\n\n Lemma PER_l : forall (A: Type) (R:relation A) x1 x2, \n   @PER _ R ->\n   R x1 x2 ->\n   R x1 x1.\n Proof.\n  intros A R x1 x2  [Hsym Htrans] H.\n  unfold transitive in Htrans.\n  exact (Htrans _ _ _ H (Hsym _ _ H)).\n Qed.\n\n Lemma rcomp_PER : forall  (A:Type) (R : relation A),\n  @PER _ R -> same_relation _ R (rcomp R R). \n Proof.\n  unfold rcomp; split; intros.\n   intros x1 x2 Hx; exists x2; split.\n     assumption.\n     apply (PER_r _ _ H Hx).\n   intros x1 x2 [x [H1 H2] ].  \n   destruct H. apply (PER_Transitive _ _ _ H1 H2).\n Qed.\n \n Hint Unfold same_relation inclusion.\n\n Lemma same_relation_refl : forall (A:Type) (R: relation A), same_relation _ R R.\n Proof.\n  split; intros; auto.\n Qed.\n\n Lemma same_relation_sym : forall (A:Type) (R S: relation A), \n   same_relation _ R S -> same_relation _ S R.\n Proof.\n  intros A R S [? ?]; split; assumption.\n Qed.\n\n\n Add Parametric Relation (A:Type) : (relation A) (@same_relation A)\n   reflexivity proved by (@same_relation_refl A)\n   symmetry proved by (@same_relation_sym A)\n as same_rel_rel.\n", "meta": {"author": "EasyCrypt", "repo": "certicrypt", "sha": "7b3cd2fe4a317aec38dfff9eec902b265c575587", "save_path": "github-repos/coq/EasyCrypt-certicrypt", "path": "github-repos/coq/EasyCrypt-certicrypt/certicrypt-7b3cd2fe4a317aec38dfff9eec902b265c575587/Semantics/BaseDef.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.2902650650383101}}
{"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.\n\nRequire Import Qcert.Utils.Utils.\nRequire Import Qcert.Data.DataSystem.\n\nRequire Import QcertData.\nRequire Import QcertToSpark.\n\nImport ListNotations.\nLocal Open Scope list_scope.\nLocal Open Scope string_scope.\nLocal Open Scope nstring_scope.\n\n(** Foreign typing, used to build the basic_model *)\n\nInductive enhanced_type : Set :=\n  | enhancedTop : enhanced_type\n  | enhancedBottom : enhanced_type\n  | enhancedString : enhanced_type\n  | enhancedDateTimeFormat : enhanced_type\n  | enhancedDateTime : enhanced_type\n  | enhancedDateTimeDuration : enhanced_type\n  | enhancedDateTimePeriod : enhanced_type\n.\n\nDefinition enhanced_type_to_string (et:enhanced_type) : string :=\n  match et with\n  | enhancedTop => \"ETop\"\n  | enhancedBottom => \"EBottom\"\n  | enhancedString => \"EString\"\n  | enhancedDateTimeFormat => \"EDateTimeFormat\"\n  | enhancedDateTime => \"EDateTime\"\n  | enhancedDateTimeDuration => \"EDateTimeDuration\"\n  | enhancedDateTimePeriod => \"EDateTimePeriod\"\n  end.\n\nDefinition string_to_enhanced_type (s:string) : option enhanced_type :=\n  match s with\n  | \"ETop\"%string => Some enhancedTop\n  | \"EBottom\"%string => Some enhancedBottom\n  | \"EString\"%string => Some enhancedString\n  | \"EDateTimeFormat\"%string => Some enhancedDateTimeFormat\n  | \"EDateTime\"%string => Some enhancedDateTime\n  | \"EDateTimeDuration\"%string => Some enhancedDateTimeDuration\n  | \"EDateTimePeriod\"%string => Some enhancedDateTimePeriod\n  | _ => None\n  end.\n\nDefinition enhanced_type_join (t1 t2:enhanced_type)\n  := match t1, t2 with\n     | enhancedBottom, _ => t2\n     | _, enhancedBottom => t1\n     | enhancedString, enhancedString => enhancedString\n     | enhancedDateTimeFormat, enhancedDateTimeFormat => enhancedDateTimeFormat\n     | enhancedDateTime, enhancedDateTime => enhancedDateTime\n     | enhancedDateTimeDuration, enhancedDateTimeDuration => enhancedDateTimeDuration\n     | enhancedDateTimePeriod, enhancedDateTimePeriod => enhancedDateTimePeriod\n     | _, _ => enhancedTop\n     end.\n\nDefinition enhanced_type_meet (t1 t2:enhanced_type)\n  := match t1, t2 with\n     | enhancedTop, _ => t2\n     | _, enhancedTop => t1\n     | enhancedString, enhancedString => enhancedString\n     | enhancedDateTimeFormat, enhancedDateTimeFormat => enhancedDateTimeFormat\n     | enhancedDateTime, enhancedDateTime => enhancedDateTime\n     | enhancedDateTimeDuration, enhancedDateTimeDuration => enhancedDateTimeDuration\n     | enhancedDateTimePeriod, enhancedDateTimePeriod => enhancedDateTimePeriod\n     | _, _ => enhancedBottom\n     end.\n\nInductive enhanced_subtype : enhanced_type -> enhanced_type -> Prop :=\n| enhanced_subtype_top t : enhanced_subtype t enhancedTop\n| enhanced_subtype_bottom t : enhanced_subtype enhancedBottom t\n| enhanced_subtype_refl t : enhanced_subtype t t.\n\nInstance enhanced_subtype_pre : PreOrder enhanced_subtype.\nProof.\n  constructor; red; intros.\n  - destruct x; constructor.\n  - inversion H; inversion H0; subst; try constructor; congruence.\nQed.\n\nInstance enhanced_subtype_post : PartialOrder eq enhanced_subtype.\nProof.\n  intros x y; split.\n  - intros; subst.\n    repeat red.\n    split; constructor.\n  - destruct 1.\n    inversion H; inversion H0; congruence.\nQed.\n\n#[refine] Instance enhanced_type_lattice : Lattice enhanced_type eq\n  := {\n      join := enhanced_type_join\n      ; meet := enhanced_type_meet\n    }.\nProof.\n  - red; intros t1 t2.\n    destruct t1; destruct t2; simpl;\n      reflexivity.\n  - red; intros t1 t2 t3.\n    destruct t1; destruct t2; destruct t3; simpl;\n      reflexivity.\n  - red; intros t1.\n    simpl.\n    destruct t1; simpl; try reflexivity.\n  - red; intros t1 t2.\n    destruct t1; destruct t2; simpl;\n      reflexivity.\n  - red; intros t1 t2 t3.\n    destruct t1; destruct t2; destruct t3; simpl;\n      reflexivity.\n  - red; intros t1.\n    destruct t1; simpl;\n      reflexivity.\n  - red; intros t1 t2.\n    destruct t1; destruct t2; simpl;\n      reflexivity.\n  - red; intros t1 t2.\n    destruct t1; destruct t2; simpl;\n      reflexivity.\nDefined.\n\nInstance enhanced_type_olattice : OLattice eq enhanced_subtype.\nProof.\n  constructor.\n  split.\n  - destruct a; destruct b; inversion 1; simpl; reflexivity.\n  - destruct a; destruct b; inversion 1; simpl;\n      constructor.\nQed.\n\nProgram Instance enhanced_foreign_type : foreign_type\n  := mk_foreign_type enhanced_type _ _ _ _ _ _ _.\nNext Obligation.\n  red.\n  unfold equiv, complement.\n  intros.\n  change ({x = y} + {x <> y}).\n  decide equality.\nDefined.\nNext Obligation.\n  destruct a; destruct b; try solve [left; constructor | right; inversion 1].\nDefined.\n\n", "meta": {"author": "accordproject", "repo": "ergo", "sha": "5b69ad377bbe7b18a461bda42967b70ecb075c54", "save_path": "github-repos/coq/accordproject-ergo", "path": "github-repos/coq/accordproject-ergo/ergo-5b69ad377bbe7b18a461bda42967b70ecb075c54/compiler/core/Backend/Qcert/QcertType.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704796847395, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.2902211319514773}}
{"text": "(* (Semi-)Decide conversion in ITT *)\n\nFrom Coq Require Import Bool String List BinPos Compare_dec Lia.\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 Conversion ITyping\n               ITypingInversions ITypingLemmata ContextConversion Uniqueness.\n\nSection Decide.\n\n  Context `{Sort_notion : Sorts.notion}.\n\n  Definition get_or {A B} (x : option A) (get : A -> B) (or : option B) : option B :=\n    match x with\n    | Some a => Some (get a)\n    | None => or\n    end.\n\n  Notation \"x '>>' a '==>' e '--' b\" :=\n    (get_or x (fun a => e) b) (at level 100, e at next level, right associativity).\n\n  (* Returns [Some t'] such that [Σ |-i t ▷ t'], or [None] if it cannot be\n     reduced.\n     Not really applying any strategy except going deeply in the terms.\n   *)\n  Fixpoint reduce1 (t : sterm) {struct t} : option sterm :=\n    match t with\n    | sProd n A B =>\n      reduce1 A >> A' ==> sProd n A' B --\n      reduce1 B >> B' ==> sProd n A B' --\n      None\n    | sLambda n A B t =>\n      reduce1 A >> A' ==> sLambda n A' B t --\n      reduce1 B >> B' ==> sLambda n A B' t --\n      reduce1 t >> t' ==> sLambda n A B t' --\n      None\n    | sApp (sLambda n _ _ t) _ _ u =>\n      Some (t{ 0 := u })\n    | sApp u A B v =>\n      reduce1 u >> u' ==> sApp u' A B v --\n      reduce1 v >> v' ==> sApp u A B v' --\n      reduce1 A >> A' ==> sApp u A' B v --\n      reduce1 B >> B' ==> sApp u A B' v --\n      None\n    | sSum n A B =>\n      reduce1 A >> A' ==> sSum n A' B --\n      reduce1 B >> B' ==> sSum n A B' --\n      None\n    (* | sPair *)\n    (* | sPi1 *)\n    (* | sPi2 *)\n    | sEq A u v =>\n      reduce1 A >> A' ==> sEq A' u v --\n      reduce1 u >> u' ==> sEq A u' v --\n      reduce1 v >> v' ==> sEq A u v' --\n      None\n    | sRefl A u =>\n      reduce1 A >> A' ==> sRefl A' u --\n      reduce1 u >> u' ==> sRefl A u' --\n      None\n    (* | sJ *)\n    | sTransport _ _ (sRefl _ _) t =>\n      Some t\n    | sTransport A B p t =>\n      reduce1 p >> p' ==> sTransport A B p' t --\n      reduce1 t >> t' ==> sTransport A B p t' --\n      reduce1 A >> A' ==> sTransport A' B p t --\n      reduce1 B >> B' ==> sTransport A B' p t --\n      None\n    | sHeq A a B b =>\n      reduce1 A >> A' ==> sHeq A' a B b --\n      reduce1 a >> a' ==> sHeq A a' B b --\n      reduce1 B >> B' ==> sHeq A a B' b --\n      reduce1 b >> b' ==> sHeq A a B b' --\n      None\n    | sHeqToEq p =>\n      reduce1 p >> p' ==> sHeqToEq p' --\n      None\n    | sHeqRefl A a =>\n      reduce1 A >> A' ==> sHeqRefl A' a --\n      reduce1 a >> a' ==> sHeqRefl A a' --\n      None\n    | sHeqSym p =>\n      reduce1 p >> p' ==> sHeqSym p' -- None\n    | sHeqTrans p q =>\n      reduce1 p >> p' ==> sHeqTrans p' q --\n      reduce1 q >> q' ==> sHeqTrans p q' --\n      None\n    | sHeqTransport p t =>\n      reduce1 p >> p' ==> sHeqTransport p' t --\n      reduce1 t >> t' ==> sHeqTransport p t' --\n      None\n    (* | sCongProd *)\n    (* | sCongLambda *)\n    (* | sCongApp *)\n    (* | sCongSum *)\n    (* | sCongPair *)\n    (* | sCongPi1 *)\n    (* | sCongPi2 *)\n    (* | sCongEq *)\n    (* | sCongRefl *)\n    | sEqToHeq p =>\n      reduce1 p >> p' ==> sEqToHeq p' -- None\n    | sHeqTypeEq A B p =>\n      reduce1 p >> p' ==> sHeqTypeEq A B p' --\n      reduce1 A >> A' ==> sHeqTypeEq A' B p --\n      reduce1 B >> B' ==> sHeqTypeEq A B' p --\n      None\n    | sProjT1 p =>\n      reduce1 p >> p' ==> sProjT1 p' -- None\n    | sProjT2 p =>\n      reduce1 p >> p' ==> sProjT2 p' -- None\n    | sProjTe p =>\n      reduce1 p >> p' ==> sProjTe p' -- None\n    | _ => None\n    end.\n\n  Ltac one_case :=\n    lazymatch goal with\n    | |- (?d >> _ ==> _ -- _) = _ -> _ =>\n      case_eq d ; [\n        intros ? ? h ; inversion h ; subst ; clear h ;\n        constructor ; solve [ auto ]\n      | intros _ ; cbn\n      ]\n    end.\n\n  Lemma reduce1_sound :\n    forall {t u},\n      reduce1 t = Some u ->\n      t ▷ u.\n  Proof.\n    intros t u h. revert u h.\n    induction t ; intros u h.\n    all: try (cbn in h ; discriminate h).\n    all: try (revert h ; cbn ; repeat one_case ; discriminate).\n    - destruct t1.\n      all: try (revert h ; cbn ; repeat one_case ; discriminate).\n      cbn in h. inversion h. subst. clear h.\n      constructor.\n    - destruct t3.\n      all: try (revert h ; cbn ; repeat one_case ; discriminate).\n      cbn in h. inversion h. subst. clear h.\n      constructor.\n  Defined.\n\n  (* When it returns [true], we have [Σ |-i u = v].\n     It compares the terms first by alpha-conversion, and then reduces the\n     first one as much as possible, then the second one.\n   *)\n  Fixpoint isconv (fuel : nat) (u v : sterm) {struct fuel} : bool :=\n    match fuel with\n    | 0 => false\n    | S fuel =>\n      eq_term u v ||\n      match reduce1 u with\n      | Some u' => isconv fuel u' v\n      | None =>\n        match reduce1 v with\n        | Some v' => isconv fuel u v'\n        | None => false\n        end\n      end\n    end.\n\n  Lemma isconv_sound :\n    forall {fuel u v},\n      isconv fuel u v = true ->\n      u ≡ v.\n  Proof.\n    intros fuel u v h. revert u v h.\n    induction fuel ; intros u v h ; try discriminate h.\n    cbn in h. apply orb_prop in h. destruct h as [h | h].\n    - constructor. unfold eq_term in h.\n      destruct (nl_dec (nl u) (nl v)).\n      + assumption.\n      + discriminate.\n    - revert h. case_eq (reduce1 u).\n      + intros u' hu h. eapply conv_red_l.\n        * eapply reduce1_sound. eassumption.\n        * eapply IHfuel. assumption.\n      + intros _. case_eq (reduce1 v).\n        * intros v' hv h. eapply conv_red_r.\n          -- eapply IHfuel. eassumption.\n          -- eapply reduce1_sound. assumption.\n        * intros _. discriminate.\n  Defined.\n\nEnd Decide.", "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/DecideConversion.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.5544704649604274, "lm_q1q2_score": 0.2902211242444728}}
{"text": "(*\nCopyright © 2006 Russell O’Connor\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis proof and associated documentation files (the \"Proof\"), to deal in\nthe Proof without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Proof, and to permit persons to whom the Proof is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Proof.\n\nTHE PROOF IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE PROOF OR THE USE OR OTHER DEALINGS IN THE PROOF.\n*)\n\nRequire Import Plot.\nRequire Import CRtrans.\n\n(* `∗' is used for trival proofs that a some concrete number is less than another *)\nNotation star := (@refl_equal _ Lt).\nNotation \"∗\" := star.\n\nLocal Open Scope Q_scope.\nLocal Open Scope uc_scope.\nLocal Open Scope raster.\n\n(* This file illustrates how to plot funcitons *)\n(* PlotQ requires that we plot uniformly continuous functions.\n   Therefore we cannot plot (sin : CR -> CR), me must instead\n   plot the UniformlyContinuousFunction (sin_uc : Q --> CR). *)\n(* Here we plot sin on [-3,3] with range [-1,1] on a 36x12 raster *)\nTime Eval vm_compute in PlotQ (- (3)) 3 star (- (1)) 1 star sin_uc 36 12.\n\n(* Here we explore the proof that plots are correct *)\nGoal True.\n(* Plot_correct is a proof that the plot is correct.*)\n(* below we plot exp on [-3, 0] with range [0,1] *)\n(* (exp_bound_uc 0) is exp on ]-inf,0] which is one domain where it is uniformly continuous *)\nassert (X:=@Plot_correct (-(3)) 0 star 0 1 star\n (exp_bound_uc 0)\n 45 15 refl_equal refl_equal).\n(* No plot is seen.  It is hidden in the uncomputed\n  PlotQ (- (3)) 0 ∗ 0 1 ∗ (exp_bound_uc 0) 45 15 *)\n(* We use patern matchin to extract the parts of the statement we\n   wish to normalize *)\nmatch goal with\n [X:ball ?e ?a (@ucFun _ _ _ (_⇱?b⇲_))|-_] => set (E:=e) in X; set (B:=b) in X\nend.\n(* E is the error; a bound on the distance between our plot and the actual function *)\nset (E' := E: Q).\nvm_compute in E'.\n(* The error is 90/1800 *)\n(* B is the plot *)\nTime vm_compute in B.\n(* The plot is a 45 by 15 raster. *)\n(* The plot and error can be reinserted into the statement if you wish *)\nunfold E, B in X.\nclear E B.\n(* end this example *)\nsplit.\nQed.\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/examples/PlotExamples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.2902211242444727}}
{"text": "Require Import Coq.Classes.Morphisms.\nRequire Import Logic.Syntax.\nRequire Import Logic.Semantics.\nRequire Import Logic.BasicProofRules.\nRequire Import Logic.Automation.\n\nGlobal Instance Proper_Comp :\n  Proper (term_equiv ==> term_equiv ==> eq ==> lentails) Comp.\nProof.\n  morphism_intro. breakAbstraction.\n  subst. unfold eval_comp; simpl.\n  intuition congruence.\nQed.\nGlobal Instance Proper_Comp_lequiv :\n  Proper (term_equiv ==> term_equiv ==> eq ==> lequiv) Comp.\nProof.\n  morphism_intro.\n  split; breakAbstraction;\n  subst; unfold eval_comp; simpl;\n  intuition congruence.\nQed.\nGlobal Instance Proper_PlusT :\n  Proper (term_equiv ==> term_equiv ==> term_equiv) PlusT.\nProof.\n  morphism_intro; unfold term_equiv in *;\n  simpl; intuition congruence.\nQed.\nGlobal Instance Proper_MinusT :\n  Proper (term_equiv ==> term_equiv ==> term_equiv) MinusT.\nProof.\n  morphism_intro; unfold term_equiv in *;\n  simpl; intuition congruence.\nQed.\nGlobal Instance Proper_MultT :\n  Proper (term_equiv ==> term_equiv ==> term_equiv) MultT.\nProof.\n  morphism_intro; unfold term_equiv in *;\n  simpl; intuition congruence.\nQed.\nGlobal Instance Proper_InvT :\n  Proper (term_equiv ==> term_equiv) InvT.\nProof.\n  morphism_intro; unfold term_equiv in *;\n  simpl; intuition congruence.\nQed.\nGlobal Instance Proper_CosT :\n  Proper (term_equiv ==> term_equiv) CosT.\nProof.\n  morphism_intro; unfold term_equiv in *;\n  simpl; intuition congruence.\nQed.\nGlobal Instance Proper_SinT :\n  Proper (term_equiv ==> term_equiv) SinT.\nProof.\n  morphism_intro; unfold term_equiv in *;\n  simpl; intuition congruence.\nQed.\nGlobal Instance Proper_SqrtT :\n  Proper (term_equiv ==> term_equiv) SqrtT.\nProof.\n  morphism_intro; unfold term_equiv in *;\n  simpl; intuition congruence.\nQed.\nGlobal Instance Proper_ArctanT :\n  Proper (term_equiv ==> term_equiv) ArctanT.\nProof.\n  morphism_intro; unfold term_equiv in *;\n  simpl; intuition congruence.\nQed.\n", "meta": {"author": "dricketts", "repo": "quadcopter", "sha": "62bb21915612a141e1ffabc73df3dc2d931c54ce", "save_path": "github-repos/coq/dricketts-quadcopter", "path": "github-repos/coq/dricketts-quadcopter/quadcopter-62bb21915612a141e1ffabc73df3dc2d931c54ce/logic/Morphisms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.2902211242444727}}
{"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(** * A predicate for relating a height list with a cover\n\n- Key definitions: [height_pred]\n- Initial author: Laurent.Thery@inria.fr (2003)\n\n*)\n\nFrom Coq Require Import ArithRing.\nFrom Huffman Require Export AuxLib OrderedCover WeightTree Ordered Prod2List.\n\nSet Default Proof Using \"Type\".\n\nSection HeightPred.\nVariable A : Type.\nVariable f : A -> nat.\nVariable A_eq_dec : forall a b : A, {a = b} + {a <> b}.\n\n(** \n  A predicate that associates an initial height, a list of\n  height, a cover and a tree\n*)\nInductive height_pred : nat -> list nat -> list (btree A) -> btree A -> Prop :=\n  | height_pred_nil :\n      forall (n : nat) (t : btree A), height_pred n (n :: []) (t :: []) t\n  | height_pred_node :\n      forall (n : nat) (ln1 ln2 : list nat) (t1 t2 : btree A)\n        (l1 l2 : list (btree A)),\n      height_pred (S n) ln1 l1 t1 ->\n      height_pred (S n) ln2 l2 t2 ->\n      height_pred n (ln1 ++ ln2) (l1 ++ l2) (node t1 t2).\n#[local] Hint Resolve height_pred_nil height_pred_node : core.\n\n(** The cover is an ordered cover *)\nTheorem height_pred_ordered_cover :\n forall (n : nat) (ln : list nat) (t : btree A) (l : list (btree A)),\n height_pred n ln l t -> ordered_cover l t.\nProof.\nintros n ln t l H; elim H; simpl in |- *; auto.\nQed.\n\n(** The height list is never empty *)\nTheorem height_pred_not_nil1 :\n forall (n : nat) (ln : list nat) (t : btree A) (l : list (btree A)),\n height_pred n ln l t -> ln <> [].\nProof.\nintros n ln t l H; elim H; simpl in |- *; auto.\nintros; discriminate.\nintros n0 ln1 ln2 t1 t2 l1 l2 H0; case ln1; simpl in |- *; auto.\nintros; discriminate.\nQed.\n\n(** The cover list is never empty *) \nTheorem height_pred_not_nil2 :\n forall (n : nat) (ln : list nat) (t : btree A) (l : list (btree A)),\n height_pred n ln l t -> l <> [].\nProof.\nintros n ln t l H; elim H; simpl in |- *; auto.\nintros; discriminate.\nintros n0 ln1 ln2 t1 t2 l1 l2 H0; case l1; simpl in |- *; auto.\nintros; discriminate.\nQed.\n\n(* The height and cover lists have same length *)\nTheorem height_pred_length :\n forall (n : nat) (ln : list nat) (t : btree A) (l : list (btree A)),\n height_pred n ln l t -> length ln = length l.\nProof.\nintros n ln t l H; elim H; simpl in |- *; auto.\nintros; repeat rewrite app_length; auto with arith.\nQed.\n\n(**\n  The height and cover list gives a simple relation between\n  weight_tree, sum_leaves and the product of the two lists\n*)\nTheorem height_pred_weight :\n forall (n : nat) (ln : list nat) (t : btree A) (l : list (btree A)),\n height_pred n ln l t ->\n n * sum_leaves f t + weight_tree f t = prod2list f ln l.\nProof.\nintros n ln t l H; elim H; simpl in |- *; auto.\nintros n0 ln1 ln2 t1 t2 l1 l2 H0 H1 H2 H3.\nrewrite prod2list_app; auto with arith.\nrewrite <- H3; rewrite <- H1; ring.\napply height_pred_length with (1 := H0); auto.\nQed.\n\n(** Ordered covers can be completed with a height list *)\nTheorem ordered_cover_height_pred :\n forall (n : nat) (t : btree A) (l : list (btree A)),\n ordered_cover l t -> exists ln : list nat, height_pred n ln l t.\nProof.\nintros n t l H; generalize n; elim H; clear n t l H.\nintros t l n; exists (n :: []); auto.\nintros t1 t2 l1 l2 l3 H H0 H1 H2 n.\ncase (H0 (S n)); intros ln1 HH1.\ncase (H2 (S n)); intros ln2 HH2.\nexists (ln1 ++ ln2); auto.\nQed.\n\n(** Elements in the height list are always larger than the initial height *) \nTheorem height_pred_larger :\n forall (n n1 : nat) (ln : list nat) (t : btree A) (l : list (btree A)),\n height_pred n ln l t -> In n1 ln -> n <= n1.\nProof.\nintros n n1 ln t l H; generalize n1; elim H; clear H n ln t l n1;\n auto with arith.\nintros n t n1 [H2| H2]; [ rewrite H2 | case H2 ]; auto.\nintros n ln1 ln2 t1 t2 l1 l2 H H0 H1 H2 n1 H3; apply Nat.le_trans with (S n);\n auto with arith.\ncase in_app_or with (1 := H3); auto.\nQed.\n\n(**\n  In the height list is not a singleton, all its element are\n  strictly larger than the initial height\n*) \nTheorem height_pred_larger_strict :\n forall (n n1 : nat) (ln : list nat) (t : btree A) (l : list (btree A)),\n height_pred n ln l t -> In n1 ln -> n < n1 \\/ ln = n :: [] /\\ l = t :: [].\nProof.\nintros n n1 ln t l H; generalize n1; elim H; clear H n ln t l n1; auto.\nintros n ln1 ln2 t1 t2 l1 l2 H H0 H1 H2 n1 H3; left;\n apply Nat.lt_le_trans with (S n); auto.\ncase in_app_or with (1 := H3).\nintros H4; apply height_pred_larger with (1 := H); auto.\nintros H4; apply height_pred_larger with (1 := H1); auto.\nQed.\n\n(** There always a larger element that the initial height in the heigh list *)\nTheorem height_pred_larger_ex :\n forall (n : nat) (ln : list nat) (t : btree A) (l : list (btree A)),\n height_pred n ln l t -> exists n1, In n1 ln /\\ n <= n1.\nProof.\nintros n ln t l H; elim H; clear H n ln t l.\nintros n t; exists n; auto with datatypes.\nintros n ln1 ln2 t1 t2 l1 l2 H (n1, (HH1, HH2)) H1 H2.\nexists n1; auto with datatypes arith.\nQed.\n \nLemma height_pred_disj_larger_aux :\n  forall (n : nat) (ln : list nat) (t : btree A) (l : list (btree A)),\n  height_pred n ln l t ->\n  forall ln1 ln2 a,\n  ln = ln1 ++ a :: ln2 ->\n  (forall n1 : nat, In n1 ln1 -> n1 < a) ->\n  (forall n1 : nat, In n1 ln2 -> n1 <= a) ->\n  (exists ln3, ln2 = a :: ln3) \\/ ln = n :: [] /\\ l = t :: [].\nProof.\nintros n ln t l H; elim H; clear H n ln t l.\nintros n t l ln1 ln2 a; case ln1; simpl in |- *; auto.\nintros n ln1 ln2 t1 t2 l1 l2 H H0 H1 H2 ln0 ln3 a H3 H4 H5.\ncase app_inv_app with (1 := H3).\nintros (ln4, H7); auto.\ncut (ln3 = ln4 ++ ln2);\n [ intros E1\n | apply app_inv_head with (l := ln0 ++ a :: []); repeat rewrite app_ass;\n    simpl in |- *; rewrite <- H3; rewrite H7; rewrite app_ass; \n    auto ].\ncase H0 with (1 := H7); auto; clear H0 H2.\nintros n1 H8; apply H5; rewrite E1; auto with datatypes.\nintros (ln5, HH); left; exists (ln5 ++ ln2).\napply trans_equal with (1 := E1); rewrite HH; auto.\nintros (HH1, HH2).\ncut (ln0 = [] /\\ ln4 = [] /\\ a = S n);\n [ intros (HH3, (HH4, HH5))\n | generalize HH1; rewrite H7; case ln0; simpl in |- *;\n    [ case ln4; try (intros; discriminate); (intros HH6; injection HH6; auto)\n    | intros n0 l; case l; simpl in |- *; intros; discriminate ] ].\ngeneralize E1 H1; case ln2; simpl in |- *; auto; clear E1 H1.\nintros E1 H1; case height_pred_not_nil2 with (1 := H1); auto.\ngeneralize (height_pred_length _ _ _ _ H1); case l2; simpl in |- *; auto;\n intros; discriminate.\nintros n0 ln5 E1 H1; case height_pred_larger_strict with (n1 := n0) (1 := H1);\n simpl in |- *; auto with datatypes.\nintros HH6; contradict HH6; apply Nat.le_ngt; rewrite <- HH5; apply H5;\n rewrite E1; auto with datatypes.\nintros (H8, H9); left; exists []; injection H8.\nintros HH7 HH8; rewrite HH5; rewrite <- HH8; rewrite <- HH7; rewrite E1;\n rewrite HH4; auto.\nintros (ln4, H7); auto.\ncut (ln0 = ln1 ++ ln4);\n [ intros E1\n | apply app_inv_tail with (l := a :: ln3); rewrite <- H3; rewrite H7;\n    rewrite app_ass; auto ].\ncase H2 with (1 := H7); auto.\nintros n1 H6; apply H4; rewrite E1; auto with datatypes.\nintros (HH1, HH2).\ncut (ln3 = [] /\\ ln4 = [] /\\ a = S n);\n [ intros (HH3, (HH4, HH5))\n | generalize HH1; rewrite H7; case ln4; simpl in |- *;\n    [ case ln3; try (intros; discriminate); (intros HH6; injection HH6; auto)\n    | intros n0 l; case l; simpl in |- *; intros; discriminate ] ].\ncase height_pred_larger_ex with (1 := H); auto.\nintros n1; rewrite <- HH5; intros (HH6, HH7).\ncontradict HH7; apply Nat.lt_nge; apply H4; rewrite E1; auto with datatypes.\nQed.\n\n(** The first maximum height in the list is immediately repeated once *)\nTheorem height_pred_disj_larger :\n forall (n a : nat) (ln1 ln2 : list nat) (t : btree A) (l : list (btree A)),\n height_pred n (ln1 ++ a :: ln2) l t ->\n (forall n1 : nat, In n1 ln1 -> n1 < a) ->\n (forall n1 : nat, In n1 ln2 -> n1 <= a) ->\n (exists ln3, ln2 = a :: ln3) \\/\n (ln1 = [] /\\ a = n /\\ ln2 = []) /\\ l = t :: [].\nProof.\nintros n a ln1 ln2 t l H H0 H1;\n case\n  height_pred_disj_larger_aux\n   with (a := a) (ln1 := ln1) (ln2 := ln2) (1 := H); \n auto; case ln1; simpl in |- *;\n [ intros (HH1, HH2); injection HH1; auto\n | intros n0 l1; case l1; simpl in |- *; intuition; try discriminate ].\nQed.\n \nLemma height_pred_disj_larger2_aux :\n  forall (n : nat) (ln : list nat) (t : btree A) (l : list (btree A)),\n  height_pred n ln l t ->\n  forall ln1 ln2 a,\n  ln = ln1 ++ a :: ln2 ->\n  (exists n1, In n1 ln1 /\\ a <= n1) \\/\n  (exists n1, In n1 ln2 /\\ a <= n1) \\/ ln = n :: [] /\\ l = t :: [].\nProof.\nintros n ln t l H; elim H; clear H n ln t l.\nintros n t l ln1 ln2 a; case ln1; simpl in |- *; auto.\nintros n ln1 ln2 t1 t2 l1 l2 H H0 H1 H2 ln0 ln3 a H3.\ncase app_inv_app with (1 := H3).\nintros (ln4, H4); auto.\ncut (ln3 = ln4 ++ ln2);\n [ intros E1\n | apply app_inv_head with (l := ln0 ++ a :: []); repeat rewrite app_ass;\n    simpl in |- *; rewrite <- H3; rewrite H4; rewrite app_ass; \n    auto ].\ncase H0 with (1 := H4); auto; intros [(n1, (HH1, HH2))| (HH1, HH2)]; auto;\n clear H0 H2.\nright; left; exists n1; split; auto; rewrite E1; auto with datatypes.\ncut (ln0 = [] /\\ ln4 = [] /\\ a = S n);\n [ intros (HH3, (HH4, HH5))\n | generalize HH1; rewrite H4; case ln0; simpl in |- *;\n    [ case ln4; try (intros; discriminate); (intros HH6; injection HH6; auto)\n    | intros n0 l; case l; simpl in |- *; intros; discriminate ] ].\ncase height_pred_larger_ex with (1 := H1); auto.\nintros n1; rewrite <- HH5; intros (HM1, HM2).\nright; left; exists n1; split; auto; rewrite E1; auto with datatypes.\nintros (ln4, H4); auto.\ncut (ln0 = ln1 ++ ln4);\n [ intros E1\n | apply app_inv_tail with (l := a :: ln3); rewrite <- H3; rewrite H4;\n    rewrite app_ass; auto ].\ncase H2 with (1 := H4); auto; clear H0 H2.\nintros (n1, (HH1, HH2)); left; exists n1; split; auto; rewrite E1;\n auto with datatypes.\nintros [HH1| (HH1, HH2)]; auto.\ncut (ln3 = [] /\\ ln4 = [] /\\ a = S n);\n [ intros (HH3, (HH4, HH5))\n | generalize HH1; rewrite H4; case ln4; simpl in |- *;\n    [ case ln3; try (intros; discriminate); (intros HH6; injection HH6; auto)\n    | intros n0 l; case l; simpl in |- *; intros; discriminate ] ].\ncase height_pred_larger_ex with (1 := H); auto.\nintros n1; rewrite <- HH5; intros (HM1, HM2).\nleft; exists n1; split; auto; rewrite E1; auto with datatypes.\nQed.\n\n(** There is no strict maximum in a list *)\nTheorem height_pred_disj_larger2 :\n forall (n a : nat) (ln1 ln2 : list nat) (t : btree A) (l : list (btree A)),\n height_pred n (ln1 ++ a :: ln2) l t ->\n (exists n1, In n1 ln1 /\\ a <= n1) \\/\n (exists n1, In n1 ln2 /\\ a <= n1) \\/\n (ln1 = [] /\\ a = n /\\ ln2 = []) /\\ l = t :: [].\nProof.\nintros n a ln1 ln2 t l H;\n case\n  height_pred_disj_larger2_aux\n   with (a := a) (ln1 := ln1) (ln2 := ln2) (1 := H); \n auto.\nintros [H1| (H1, H2)]; auto.\ngeneralize H1 H2; case ln1; simpl in |- *;\n [ intros H3; injection H3; auto with datatypes | idtac ].\nintros H0 H4 H5; repeat right; auto.\nintros n0 l0; case l0; simpl in |- *; intros; discriminate.\nQed.\n \nTheorem height_pred_shrink_aux :\n  forall (n : nat) (ln : list nat) (t : btree A) (l : list (btree A)),\n  height_pred n ln l t ->\n  forall l1 l2 ln1 ln2 a b t1 t2,\n  ln = ln1 ++ a :: b :: ln2 ->\n  (forall n1 : nat, In n1 ln1 -> n1 < a) ->\n  (forall n1 : nat, In n1 (b :: ln2) -> n1 <= a) ->\n  length ln1 = length l1 ->\n  l = l1 ++ t1 :: t2 :: l2 ->\n  height_pred n (ln1 ++ pred a :: ln2) (l1 ++ node t1 t2 :: l2) t.\nProof.\nintros n ln t l H; elim H; clear n ln t l H; auto.\nintros n t l1 l2 ln1 ln2 a b t1 t2; case ln1;\n try (simpl in |- *; intros; discriminate).\nintros n0 l0; case l0; try (simpl in |- *; intros; discriminate).\nintros n ln1 ln2 t1 t2 l1 l2 H H0 H1 H2 l0 l3 ln0 ln3 a b t0 t3 H3 H4 H5 H6\n H7.\ncut (length ln1 = length l1);\n [ intros Eq2 | apply height_pred_length with (1 := H) ].\ncut (length ln2 = length l2);\n [ intros Eq3 | apply height_pred_length with (1 := H1) ].\ncut (length ln3 = length l3);\n [ intros Eq4\n | apply Nat.add_cancel_l with (length (ln0 ++ a :: b :: []));\n    rewrite <- app_length; rewrite app_ass; simpl in |- *;\n    rewrite <- H3; repeat rewrite app_length; simpl in |- *;\n    rewrite Eq2; rewrite Eq3; rewrite <- app_length;\n    rewrite H7; repeat rewrite app_length; simpl in |- *;\n    repeat rewrite (fun x y => Nat.add_comm x (S y));\n    simpl in |- *; rewrite Nat.add_comm; auto ].\ncase app_inv_app2 with (1 := H3); auto.\nintros (ln4, Hp1).\ncut (ln3 = ln4 ++ ln2);\n [ intros E1\n | apply app_inv_head with (l := ln0 ++ a :: b :: []);\n    repeat rewrite app_ass; simpl in |- *; rewrite <- H3; \n    rewrite Hp1; repeat rewrite app_ass; auto ].\nreplace (ln0 ++ pred a :: ln3) with ((ln0 ++ pred a :: ln4) ++ ln2);\n [ idtac | rewrite app_ass; rewrite E1; auto ].\ncut (l3 = firstn (length ln4) l3 ++ l2).\nintros HH;\n replace (l0 ++ node t0 t3 :: l3) with\n  ((l0 ++ node t0 t3 :: firstn (length ln4) l3) ++ l2);\n [ idtac | pattern l3 at 2 in |- *; rewrite HH; rewrite app_ass; auto ].\napply height_pred_node; auto.\napply H0 with (1 := Hp1); auto.\nintros n1 HH1; (apply H5; auto).\nsimpl in HH1; case HH1; intros H9; try rewrite H9; auto with datatypes.\nrewrite E1; auto with datatypes.\napply app_inv_tail with (l := l2).\nrepeat rewrite app_ass; apply trans_equal with (1 := H7); auto.\npattern l3 at 1 in |- *; rewrite HH; auto.\napply sym_equal;\n apply trans_equal with (2 := firstn_skipn (length ln4) l3).\napply f_equal2 with (f := app (A:=btree A)); auto.\napply trans_equal with (skipn (length l1 - length l1) l2).\nrewrite Nat.sub_diag; simpl in |- *; auto.\nrewrite <- skipn_le_app1; auto.\nrewrite H7.\nrewrite <- Eq2; rewrite Hp1.\nrewrite skipn_le_app1.\nrewrite app_length.\nrewrite H6.\nrewrite <- Nat.add_comm.\nrewrite Nat.add_sub. simpl in |- *; auto.\nrewrite <- H6; rewrite app_length; simpl in |- *; auto with arith.\nintros [(ln4, HH)| (HH1, HH2)].\ncut (ln0 = ln1 ++ ln4);\n [ intros E1\n | apply app_inv_tail with (l := a :: b :: ln3); rewrite <- H3; rewrite HH;\n    rewrite app_ass; auto ].\ncut (l0 = l1 ++ skipn (length l1) l0).\nintros Eq1; rewrite Eq1; rewrite E1; repeat rewrite app_ass.\napply height_pred_node; auto.\napply H2 with (b := b); auto.\nintros n1 H8; apply H4; (rewrite E1; auto with datatypes).\nrewrite skipn_length; rewrite <- Eq2; rewrite <- H6;\n rewrite <- skipn_length; rewrite E1; rewrite skipn_le_app2;\n auto; rewrite skipn_all; simpl in |- *; auto.\napply app_inv_head with (l := l1).\nrewrite <- app_ass; rewrite <- Eq1; auto.\napply sym_equal;\n apply trans_equal with (2 := firstn_skipn (length l1) l0).\napply f_equal2 with (f := app (A:=btree A)); auto.\napply trans_equal with (firstn (length l1) (l1 ++ l2)).\nrewrite firstn_le_app1; auto; rewrite Nat.sub_diag; simpl in |- *;\n auto with datatypes.\nrewrite H7; rewrite firstn_le_app2; auto.\nrewrite <- H6; rewrite <- Eq2; rewrite E1; rewrite app_length;\n auto with arith.\nrewrite HH1 in H; case height_pred_disj_larger2 with (1 := H); simpl in |- *;\n auto.\nintros (n1, (HH3, HH4)); contradict HH4; auto with arith.\nintros [(n1, (HH3, HH4))| ((HH3, (HH4, HH5)), HH6)]; [ case HH3 | idtac ].\ncase height_pred_larger_strict with (1 := H1) (n1 := b); auto.\nrewrite HH2; auto with datatypes.\nrewrite <- HH4; intros HH7; contradict HH7; apply Nat.le_ngt;\n auto with arith datatypes.\nintros (H8, H9); rewrite HH4; rewrite HH3; simpl in |- *.\ncut (l0 = []); [ intros HM1; rewrite HM1 | idtac ].\ncut (ln3 = []); [ intros HM2; rewrite HM2 | idtac ].\nreplace l3 with (nil (A:=btree A)); simpl in |- *; auto.\nrewrite HH6 in H7; rewrite H9 in H7; rewrite HM1 in H7; simpl in H7;\n injection H7.\nintros Ht1 Ht2 Ht3; rewrite Ht2; rewrite Ht3; auto.\ngeneralize Eq4; rewrite HM2; case l3; simpl in |- *; auto; intros;\n discriminate.\nrewrite HH2 in H8; injection H8; auto.\ngeneralize H6; rewrite HH3; case l0; simpl in |- *; auto; intros;\n discriminate.\nQed.\n\n(**\n  A cover can be shrunk at the first maximum of the height while\n  preserving the height list\n*) \nTheorem height_pred_shrink :\n forall (n a b : nat) (ln1 ln2 : list nat) (t t1 t2 : btree A)\n   (l1 l2 : list (btree A)),\n height_pred n (ln1 ++ a :: b :: ln2) (l1 ++ t1 :: t2 :: l2) t ->\n (forall n1 : nat, In n1 ln1 -> n1 < a) ->\n (forall n1 : nat, In n1 (b :: ln2) -> n1 <= a) ->\n length ln1 = length l1 ->\n height_pred n (ln1 ++ pred a :: ln2) (l1 ++ node t1 t2 :: l2) t.\nProof.\nintros n a b ln1 ln2 t t1 t2 l1 l2 H H0 H1 H2;\n apply height_pred_shrink_aux with (1 := H) (b := b); \n auto.\nQed.\n\n(**\n  Given a tree and its associated code it is possible to build\n  a height list (the length of the codes) and a cover (the leaves)\n  that are related\n*)\nTheorem height_pred_compute_code :\n forall (n : nat) (t : btree A),\n height_pred n (map (fun x => length (snd x) + n) (compute_code t))\n   (map (fun x => leaf (fst x)) (compute_code t)) t.\nProof.\nintros n t; generalize n; elim t; clear t n; simpl in |- *; auto.\nintros b H b0 H0 n.\nrepeat rewrite map_app.\ncut\n (forall (b : bool) l,\n  map (fun x : A * list bool => length (snd x) + n)\n    (map (fun v : A * list bool => let (a1, b1) := v in (a1, b :: b1)) l) =\n  map (fun x : A * list bool => length (snd x) + S n) l);\n [ intros E1 | idtac ].\ncut\n (forall b l,\n  map (fun x : A * list bool => leaf (fst x))\n    (map (fun v : A * list bool => let (a1, b1) := v in (a1, b :: b1)) l) =\n  map (fun x : A * list bool => leaf (fst x)) l); [ intros E2 | idtac ].\napply height_pred_node; repeat rewrite E1; repeat rewrite E2; auto.\nintros b1 l; elim l; simpl in |- *; auto.\nintros a; case a; simpl in |- *; auto.\nintros a0 l0 l1 H1; apply f_equal2 with (f := cons (A:=btree A)); auto.\nintros b1 l; elim l; simpl in |- *; auto.\nintros a; case a; simpl in |- *; auto.\nintros a0 l0 l1 H1; apply f_equal2 with (f := cons (A:=nat)); auto.\nQed.\n\n(**\n  A consequence of the previous theorem, the weight of the tree\n  is exactly the encoding of the message of the corresponding code\n*) \nTheorem weight_tree_compute :\n forall (m : list A) t,\n distinct_leaves t ->\n (forall a : A, f a = number_of_occurrences A_eq_dec a m) ->\n length (encode A_eq_dec (compute_code t) m) = weight_tree f t.\nProof.\nintros m t H0 H.\nrewrite frequency_length; auto.\napply trans_equal with (0 * sum_leaves f t + weight_tree f t); auto.\nrewrite height_pred_weight with (1 := height_pred_compute_code 0 t).\nunfold prod2list in |- *.\nrewrite\n fold_left_eta\n               with\n               (f := \n                 fun (a : nat) (b : A * list bool) =>\n                 a + number_of_occurrences A_eq_dec (fst b) m * length (snd b))\n              (f1 := \n                fun (a : nat) (b : A * list bool) =>\n                a + (fun b => f (fst b) * length (snd b)) b); \n auto.\nrewrite <-\n (fold_left_map _ _ (fun a b : nat => a + b) _ 0 (compute_code t)\n    (fun b : A * list bool => f (fst b) * length (snd b)))\n .\nrewrite fold_left_eta with (f := fun a b : nat => a + b) (f1 := plus); auto.\napply f_equal3 with (f := fold_left (A:=nat) (B:=nat)); auto.\nelim (compute_code t); simpl in |- *; auto.\nintros a l H1; apply f_equal2 with (f := cons (A:=nat)); auto with arith.\nring.\napply btree_unique_prefix2; auto.\nQed.\n\nEnd HeightPred.\nArguments height_pred [A].\n#[export] Hint Resolve height_pred_nil height_pred_node : core.\n", "meta": {"author": "coq-community", "repo": "huffman", "sha": "0857dc9ac31c5bfb71b398c9df62a39eda1fd675", "save_path": "github-repos/coq/coq-community-huffman", "path": "github-repos/coq/coq-community-huffman/huffman-0857dc9ac31c5bfb71b398c9df62a39eda1fd675/theories/HeightPred.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.2902211242444727}}
{"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(*                              ElementTemp.v                               *)\n(****************************************************************************)\n \n\nRequire Export ElementComb.\nRequire Export Basic_composition_rules.\nRequire Import Identity.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\n\n(** Describing the temporal parts of the circuit using co-induction **)\n\n\nDefinition RLATCH2 (rd : Stream bool) := RLATCH rd (n:=2).\n\n\nDefinition DMUX4T2FFC_AUX := S_map2 dmux4t2ffc.\n\nDefinition DMUX4T2FFC (d : Stream (d_list bool 4))\n  (y outputDisable : Stream bool) (old : d_list bool 2) :=\n  RLATCH2 outputDisable (Stream_to_dlist (DMUX4T2FFC_AUX y d)) old.\n\n\nDefinition DMUX4T2 := S_map2 Dmux4t2.\n\n\nDefinition DMUX2B4CA11_AUX (y outputDisable : Stream bool)\n  (d : Stream (d_list (d_list bool 4) 2))\n  (old_mux : d_list (d_list bool 2) 2) :=\n  List2\n    (dlist_to_Stream\n       (DMUX4T2FFC (S_Fst_of_l2 d) y outputDisable (Fst_of_l2 old_mux)))\n    (dlist_to_Stream\n       (DMUX4T2FFC (S_Scd_of_l2 d) y outputDisable (Scd_of_l2 old_mux))).\n\n\nDefinition DMUX2B4CA11 (old_mux : d_list (d_list bool 2) 2)\n  (outputDisable : Stream bool) (grant : Stream (d_list bool 2))\n  (d : Stream (d_list (d_list bool 4) 2)) :=\n  DMUX4T2 (S_Fst_of_l2 grant)\n    (dlist_to_Stream\n       (DMUX2B4CA11_AUX (S_Scd_of_l2 grant) outputDisable d old_mux)).\n\n\n\nDefinition DATASWITCHC_AUX (i : nat) (H : 0 < i) (H' : i <= 7)\n  (outputDisable : Stream bool) (grant : Stream (d_list bool 2))\n  (d : Stream (d_list (d_list bool 8) 4))\n  (old_mux : d_list (d_list bool 2) 2) :=\n  DMUX2B4CA11 old_mux outputDisable grant\n    (dlist_to_Stream\n       (List2 (S_map (list_of_nth (i:=i) (n:=8) H (le_leS H') (n0:=4)) d)\n          (S_map\n             (list_of_nth (i:=S i) (n:=8) (lt_O_Sn i) (le_n_S i 7 H') (n0:=4))\n             d))).\n \n\n\n\nDefinition DATASWITCHC (outputDisable : Stream bool)\n  (grant : Stream (d_list bool 2)) (d : Stream (d_list (d_list bool 8) 4))\n  (old_mux : d_list (d_list (d_list bool 2) 2) 4) :=\n  dlist_to_Stream\n    (List4\n       (DATASWITCHC_AUX lt_O_1 le_1_7 outputDisable grant d\n          (Fst_of_l4 old_mux))\n       (DATASWITCHC_AUX lt_O_3 le_3_7 outputDisable grant d\n          (Scd_of_l4 old_mux))\n       (DATASWITCHC_AUX lt_O_5 le_5_7 outputDisable grant d\n          (Thd_of_l4 old_mux))\n       (DATASWITCHC_AUX lt_O_7 le_7_7 outputDisable grant d\n          (Fth_of_l4 old_mux))).\n\n\nDefinition DATASWITCH_N_AUX (i : nat) (H : 0 < i) (H' : i <= 4)\n  (outputDisable : Stream (d_list bool 4))\n  (grant : Stream (d_list (d_list bool 2) 4))\n  (d : Stream (d_list (d_list bool 8) 4))\n  (old_mux : d_list (d_list bool 2) 8) :=\n  DATASWITCHC (S_Nth (i:=i) H H' outputDisable) (S_Nth (i:=i) H H' grant) d\n    (Fold_List (n:=2) (m:=4) old_mux).\n\n\nDefinition DATASWITCH_N (outputDisable : Stream (d_list bool 4))\n  (grant : Stream (d_list (d_list bool 2) 4))\n  (d : Stream (d_list (d_list bool 8) 4))\n  (old_mux : d_list (d_list (d_list bool 2) 8) 4) :=\n  S_map (d_map (Unfold_List (n:=2) (m:=4)) (n:=4))\n    (dlist_to_Stream\n       (List4\n          (DATASWITCH_N_AUX lt_O_1 le_1_4 outputDisable grant d\n             (Fst_of_l4 old_mux))\n          (DATASWITCH_N_AUX lt_O_2 le_2_4 outputDisable grant d\n             (Scd_of_l4 old_mux))\n          (DATASWITCH_N_AUX lt_O_3 le_3_4 outputDisable grant d\n             (Thd_of_l4 old_mux))\n          (DATASWITCH_N_AUX lt_O_4 le_4_4 outputDisable grant d\n             (Fth_of_l4 old_mux)))).\n\n\n\n(** The structure of TIMING is exactly a Moore automaton **)\n\nDefinition Timing_Aux (e : bool * d_list bool 4) (l : d_list bool 2) :=\n  let (fs, act) := e in Timing fs act l.\n\nDefinition Out_Struct_Timing (_ : bool * d_list bool 4)\n  (l : d_list bool 2) := d_Head l. \n\nDefinition Structure_TIMING := Mealy Timing_Aux Out_Struct_Timing.\n\n\n\n(** The structure of OUTDIS is a Mealy automaton **)\n\nDefinition Trans_outdis (i : d_list bool 4 * (bool * bool))\n  (old_jk : bool) :=\n  let (req, p) := i in\n  let (fs, routeEnable) := p in Jk fs (outdis req routeEnable) old_jk.\n\n\nDefinition Out_outdis (_ : d_list bool 4 * (bool * bool)) \n  (old_jk : bool) := old_jk.\n\nDefinition Structure_Outdis := Mealy Trans_outdis Out_outdis.\n\n\n\n(** The structure of ARBITER_XY is a Mealy automaton **)\n\nDefinition Trans_ArbiterXY (i : d_list bool 4 * bool)\n  (old_xy : d_list bool 2) :=\n  let (req, routeEnable) := i in\n  List2\n    (JkE (Fst_of_l2 (Arbx (Scd_of_l2 old_xy) req))\n       (Scd_of_l2 (Arbx (Scd_of_l2 old_xy) req)) (Fst_of_l2 old_xy)\n       routeEnable)\n    (JkE (Fst_of_l2 (Arby (Fst_of_l2 old_xy) req))\n       (Scd_of_l2 (Arby (Fst_of_l2 old_xy) req)) (Scd_of_l2 old_xy)\n       routeEnable).\n\nDefinition Out_ArbiterXY (_ : d_list bool 4 * bool)\n  (old_xy : d_list bool 2) := old_xy.\n\nDefinition Structure_ArbiterXY := Mealy Trans_ArbiterXY Out_ArbiterXY.\n\n\n(** The structure of ARBITER is a PC of Structure_Outdis and Structure_ArbiterXY **)\n\nDefinition f_arbiter (i : bool * (bool * d_list bool 4)) :=\n  let (fs, p) := i in\n  let (routeEnable, req) := p in (req, routeEnable, (req, (fs, routeEnable))).\n\nDefinition output_arbiter (l : d_list bool 2 * bool) :=\n  let (o1, o2) := l in List3 (Fst_of_l2 o1) (Scd_of_l2 o1) o2.\n\nDefinition TransPC_arbiter := Trans_PC Trans_ArbiterXY Trans_outdis f_arbiter.\n\nDefinition OutPC_arbiter :=\n  Out_PC Out_ArbiterXY Out_outdis f_arbiter output_arbiter.\n\nDefinition Structure_ARBITER :=\n  PC Trans_ArbiterXY Trans_outdis Out_ArbiterXY Out_outdis f_arbiter\n    output_arbiter.\n\n\n(** Parallel composition of two arbiters with the PC rule **)\n\nDefinition f_two_arbiters (i : bool * (bool * d_list (d_list bool 4) 2)) :=\n  let (fs, p) := i in\n  let (routeEnable, req2) := p in\n  (fs, (routeEnable, Fst_of_l2 req2), (fs, (routeEnable, Scd_of_l2 req2))).\n\nDefinition output_two_arbiters (o : d_list bool 3 * d_list bool 3) := o.\n\nDefinition Trans_Struct_two_arbiters :=\n  Trans_PC TransPC_arbiter TransPC_arbiter f_two_arbiters.\n\nDefinition Out_Struct_two_arbiters :=\n  Out_PC OutPC_arbiter OutPC_arbiter f_two_arbiters output_two_arbiters.\n\nDefinition Structure_TWO_ARBITERS :=\n  PC TransPC_arbiter TransPC_arbiter OutPC_arbiter OutPC_arbiter\n    f_two_arbiters output_two_arbiters.\n\n\n\n(** Parallel composition of four arbiters with the PC rule **)\n\nDefinition f_four_arbiters (i : bool * (bool * d_list (d_list bool 4) 4)) :=\n  let (fs, p) := i in\n  let (routeEnable, req) := p in\n  (fs, (routeEnable, Two_Fst_of_l4 req),\n  (fs, (routeEnable, Two_last_of_l4 req))).\n\nDefinition output_four_arbiters\n  (o : d_list bool 3 * d_list bool 3 * (d_list bool 3 * d_list bool 3)) := o.\n\nDefinition Trans_Struct_four_arbiters :=\n  Trans_PC Trans_Struct_two_arbiters Trans_Struct_two_arbiters\n    f_four_arbiters.\n\nDefinition Out_Struct_four_arbiters :=\n  Out_PC Out_Struct_two_arbiters Out_Struct_two_arbiters f_four_arbiters\n    output_four_arbiters.\n\nDefinition Structure_FOUR_ARBITERS :=\n  PC Trans_Struct_two_arbiters Trans_Struct_two_arbiters\n    Out_Struct_two_arbiters Out_Struct_two_arbiters f_four_arbiters\n    output_four_arbiters.\n\n\n(** PRIORITY_DECODE should be a Mealy automaton too **)\n\nDefinition Trans_priority_decode\n  (e : d_list bool 4 * (d_list bool 4 * d_list (d_list bool 2) 4))\n  (_ : d_list (d_list bool 4) 4) :=\n  let (act, p) := e in\n  let (pri, route) := p in Priority_Decode_Less_Pause act pri route.\n\n\nDefinition Out_priority_decode\n  (_ : d_list bool 4 * (d_list bool 4 * d_list (d_list bool 2) 4))\n  (reg : d_list (d_list bool 4) 4) := reg.\n\n\nDefinition Structure_PRIORITY_DECODE :=\n  Mealy Trans_priority_decode Out_priority_decode.\n\n\n(* Parallel composition of TIMING and PRIORITY_DECODE *)\n\nSection Timing_and_PDecode.\n\n Let Input_vector_type :=\n   (bool * (d_list bool 4 * (d_list bool 4 * d_list (d_list bool 2) 4)))%type.\n\n Let f_tp (i : Input_vector_type) :=\n   let (fs, t) := i in\n   let (act, p) := t in\n   let (pri, route) := p in (fs, act, (act, (pri, route))).\n\n\n Let output_tp (out : bool * d_list (d_list bool 4) 4) := out.\n\n Definition TransPC_Timing_PDecode :=\n   Trans_PC Timing_Aux Trans_priority_decode f_tp.\n\n Definition OutPC_Timing_PDecode :=\n   Out_PC Out_Struct_Timing Out_priority_decode f_tp output_tp.\n\n Definition Structure_TIMING_PDECODE (i : Stream Input_vector_type)\n   (l : d_list bool 2) (reg : d_list (d_list bool 4) 4) :=\n   PC Timing_Aux Trans_priority_decode Out_Struct_Timing Out_priority_decode\n     f_tp output_tp i (l, reg).\n\n Definition States_TIMING_PDECODE (i : Stream Input_vector_type)\n   (l : d_list bool 2) (reg : d_list (d_list bool 4) 4) :=\n   States_PC Timing_Aux Trans_priority_decode f_tp i (l, reg).\n\nEnd Timing_and_PDecode.\n\n\n\n(* Parallel composition of IDENTITY and TIMING_PDECODE *)\n\nSection Identity_and_TimingPDecode.\n\n Let Input_vector_type :=\n   (bool * (d_list bool 4 * (d_list bool 4 * d_list (d_list bool 2) 4)))%type.\n\n Let f_tpi (i : Input_vector_type) :=\n   let (fs, t) := i in\n   let (act, p) := t in\n   let (pri, route) := p in (fs, (fs, (act, (pri, route)))).\n\n Let output_tpi (out : bool * (bool * d_list (d_list bool 4) 4)) := out.\n\n\n Definition TransPC_TimingPDecode_Id :=\n   Trans_PC (Trans_id (Input_type:=bool)) TransPC_Timing_PDecode f_tpi.\n\n Definition OutPC_TimingPDecode_Id :=\n   Out_PC (Out_id (Input_type:=bool)) OutPC_Timing_PDecode f_tpi output_tpi.\n\n\n Definition Structure_TIMINGPDECODE_ID (i : Stream Input_vector_type)\n   (id : state_id) (old : d_list bool 2 * d_list (d_list bool 4) 4) :=\n   PC (Trans_id (Input_type:=bool)) TransPC_Timing_PDecode\n     (Out_id (Input_type:=bool)) OutPC_Timing_PDecode f_tpi output_tpi i\n     (id, old).\n\n\n Definition States_TIMINGPDECODE_ID (i : Stream Input_vector_type)\n   (id : state_id) (old : d_list bool 2 * d_list (d_list bool 4) 4) :=\n   States_PC (Trans_id (Input_type:=bool)) TransPC_Timing_PDecode f_tpi i\n     (id, old).\n\nEnd Identity_and_TimingPDecode.\n\n\n(* Series composition of TIMINGPDECODE_ID and FOUR_ARBITERS *)\n\nSection Arbitration_Structure.\n\n  Let Input_vector_type :=\n    (bool * (d_list bool 4 * (d_list bool 4 * d_list (d_list bool 2) 4)))%type.\n\n\n  Definition TransSC_Arbitration :=\n    Trans_SC TransPC_TimingPDecode_Id Trans_Struct_four_arbiters\n      OutPC_TimingPDecode_Id.\n\n  Definition OutSC_Arbitration :=\n    Out_SC OutPC_TimingPDecode_Id Out_Struct_four_arbiters.\n\n\n  Definition Structure_ARBITRATION (i : Stream Input_vector_type)\n    (old_tpi : state_id * (d_list bool 2 * d_list (d_list bool 4) 4))\n    (old_arbiters : d_list bool 2 * bool * (d_list bool 2 * bool) *\n                    (d_list bool 2 * bool * (d_list bool 2 * bool))) :=\n    SC TransPC_TimingPDecode_Id Trans_Struct_four_arbiters\n      OutPC_TimingPDecode_Id Out_Struct_four_arbiters i\n      (old_tpi, old_arbiters).\n\n\n  Definition StatesSC_ARBITRATION (i : Stream Input_vector_type)\n    (old_tpi : state_id * (d_list bool 2 * d_list (d_list bool 4) 4))\n    (old_arbiters : d_list bool 2 * bool * (d_list bool 2 * bool) *\n                    (d_list bool 2 * bool * (d_list bool 2 * bool))) :=\n    States_SC TransPC_TimingPDecode_Id Trans_Struct_four_arbiters\n      OutPC_TimingPDecode_Id i (old_tpi, old_arbiters).\n\n\nEnd Arbitration_Structure.\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/SPECIF/ELEMENT/ElementTemp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.2902211242444727}}
{"text": "(*\nvim: set fenc=utf-8 ff=unix sts=2 sw=2 et ft=coq :\n*)\n(*\nCopyright (C) 2016-2019 Philip H. Smith\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n*)\n\nRequire Import Way.StaleAtoms.\nRequire Import Way.Tactics.\n\nRequire Import Way.Open.\nRequire Import Way.Preterm.\n\n(* A preterm is locally closed if every bound variable refers to some abstraction.\n\nLocal closure is the only criterion needed to establish a preterm as a term, so the type\nhere is named \"term\".\n\nA proof of local closure reflects the shape of its preterm, with two key differences.\n\nFirst, we transform abstraction bodies before demanding local closure of the result.  The\ntransformation is to open a \"sufficiently fresh\" free variable for the new bound variable.\nThis bound variable will therefore not appear in the preterm of the required subproof.\nSince abstraction annotations should not refer to the new abstraction variable, no\nsubstitution is performed on them.\n\nSecond, there is no local closure constructor for bound variables.\n\nIf all bound variables properly refer to some abstraction, then by the first point they\nwill all be replaced by free variables by the time we consider the proof of their local\nclosure.  Any bound variables that remain must be dangling.\n\nBy the second point, preterms with dangling bound variables will be unable to prove local\nclosure, due to the lack of a suitable constructor.  Preterms without dangling bound\nvariables will have no need of one.\n\n\"Sufficiently fresh\" means exclusion from an arbitrary list of free variables, but think\n\"free variables of the abstraction body\".  Leaving it unspecified here makes proofs\nsomewhat easier later, per the \"cofinite induction\" pattern.\n*)\nInductive term : preterm -> Set :=\n\n| free_variable : forall (a : atom), term (free_variable a)\n\n| product :\n  forall (l : list atom) (p q : preterm), term p ->\n  (fresh (a : l), term (open_free a q)) ->\n  term (product p q)\n\n| abstraction :\n  forall (l : list atom) (p q : preterm), term p ->\n  (fresh (a : l), term (open_free a q)) ->\n  term (abstraction p q)\n\n| application : forall (p q : preterm), term p -> term q -> term (application p q)\n\n| type : forall (n : nat), term (type n).\n\nHint Resolve free_variable application type : way.\n\nHint Extern 7 (term (Preterm.product _ _)) =>\n  let stale := stale_atoms in apply (Term.product stale) : way.\n\nHint Extern 7 (term (Preterm.abstraction _ _)) =>\n  let stale := stale_atoms in apply (Term.abstraction stale) : way.\n\nModule Examples.\n\nImport Aliases.\n\nExample omega : term Preterm.Examples.omega.\nProof.\n  unfold Preterm.Examples.omega; infer.\nDefined.\n\nExample polymorphic_identity : term Preterm.Examples.polymorphic_identity.\nProof.\n  unfold Preterm.Examples.polymorphic_identity; infer.\nDefined.\n\nExample fvar_is_term : forall (a : atom), term (fvar a).\nProof.\n  infer.\nDefined.\n\nExample prod_can_be_term : term (prod (type 0) (bvar 0)).\nProof.\n  infer.\nDefined.\n\nExample prod_can_be_not_term : notT (term (prod (type 0) (bvar 1))).\nProof.\n  intro H;\n  inversion H as [ | stale ? ? ? CFH | | | ];\n  subst;\n  destruct (fresh_atom stale) as [a Hfresh];\n  pose proof (CFH a Hfresh) as Himpossible;\n  infer.\nDefined.\n\nExample abs_can_be_term : term (abs (type 0) (bvar 0)).\nProof.\n  infer.\nDefined.\n\nExample abs_can_be_not_term : notT (term (abs (type 0) (bvar 1))).\nProof.\n  intro H;\n  inversion H as [ | | stale ? ? ? CFH | | ];\n  subst;\n  destruct (fresh_atom stale) as [a Hfresh];\n  pose proof (CFH a Hfresh) as Himpossible;\n  infer.\nDefined.\n\nExample app_can_be_term : forall (a : atom), term (app (fvar a) (fvar a)).\nProof.\n  infer.\nDefined.\n\nExample app_can_be_not_term : notT (term (app (bvar 0) (bvar 0))).\nProof.\n  infer.\nDefined.\n\nExample type_is_term : term (type 0).\nProof.\n  infer.\nDefined.\n\nEnd Examples.\n", "meta": {"author": "waylang", "repo": "infrastructure", "sha": "8bee2a33d30b5cc7d6d2c13e36b0cd62be796d44", "save_path": "github-repos/coq/waylang-infrastructure", "path": "github-repos/coq/waylang-infrastructure/infrastructure-8bee2a33d30b5cc7d6d2c13e36b0cd62be796d44/metatheory/Way/Term.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.2902211242444727}}
{"text": "(************************************************************************)\n(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)\n(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2010     *)\n(*   \\VV/  **************************************************************)\n(*    //   *      This file is distributed under the terms of the       *)\n(*         *       GNU Lesser General Public License Version 2.1        *)\n(************************************************************************)\n\nRequire Import List.\nFrom LegacyRing Require Import LegacyRing.\nRequire Export LegacyField_Compl.\nRequire Export LegacyField_Theory.\n\n(**** Interpretation A --> ExprA ****)\n\nLtac get_component a s := eval cbv beta iota delta [a] in (a s).\n\nLtac body_of s := eval cbv beta iota delta [s] in s.\n\nLtac mem_assoc var lvar :=\n  match constr:(lvar) with\n  | nil => constr:(false)\n  | ?X1 :: ?X2 =>\n      match constr:(X1 = var) with\n      | (?X1 = ?X1) => constr:(true)\n      | _ => mem_assoc var X2\n      end\n  end.\n\nLtac number lvar :=\n  let rec number_aux lvar cpt :=\n    match constr:(lvar) with\n    | (@nil ?X1) => constr:(@nil (prod X1 nat))\n    | ?X2 :: ?X3 =>\n        let l2 := number_aux X3 (S cpt) in\n        constr:((X2,cpt) :: l2)\n    end\n  in number_aux lvar 0.\n\nLtac build_varlist FT trm :=\n  let rec seek_var lvar trm :=\n    let AT := get_component A FT\n    with AzeroT := get_component Azero FT\n    with AoneT := get_component Aone FT\n    with AplusT := get_component Aplus FT\n    with AmultT := get_component Amult FT\n    with AoppT := get_component Aopp FT\n    with AinvT := get_component Ainv FT in\n    match constr:(trm) with\n    | AzeroT => lvar\n    | AoneT => lvar\n    | (AplusT ?X1 ?X2) =>\n        let l1 := seek_var lvar X1 in\n        seek_var l1 X2\n    | (AmultT ?X1 ?X2) =>\n        let l1 := seek_var lvar X1 in\n        seek_var l1 X2\n    | (AoppT ?X1) => seek_var lvar X1\n    | (AinvT ?X1) => seek_var lvar X1\n    | ?X1 =>\n        let res := mem_assoc X1 lvar in\n        match constr:(res) with\n        | true => lvar\n        | false => constr:(X1 :: lvar)\n        end\n    end in\n  let AT := get_component A FT in\n  let lvar := seek_var (@nil AT) trm in\n  number lvar.\n\nLtac assoc elt lst :=\n  match constr:(lst) with\n  | nil => fail\n  | (?X1,?X2) :: ?X3 =>\n      match constr:(elt = X1) with\n      | (?X1 = ?X1) => constr:(X2)\n      | _ => assoc elt X3\n      end\n  end.\n\nLtac interp_A FT lvar trm :=\n  let AT := get_component A FT\n  with AzeroT := get_component Azero FT\n  with AoneT := get_component Aone FT\n  with AplusT := get_component Aplus FT\n  with AmultT := get_component Amult FT\n  with AoppT := get_component Aopp FT\n  with AinvT := get_component Ainv FT in\n  match constr:(trm) with\n  | AzeroT => constr:(EAzero)\n  | AoneT => constr:(EAone)\n  | (AplusT ?X1 ?X2) =>\n      let e1 := interp_A FT lvar X1 with e2 := interp_A FT lvar X2 in\n      constr:(EAplus e1 e2)\n  | (AmultT ?X1 ?X2) =>\n      let e1 := interp_A FT lvar X1 with e2 := interp_A FT lvar X2 in\n      constr:(EAmult e1 e2)\n  | (AoppT ?X1) =>\n      let e := interp_A FT lvar X1 in\n      constr:(EAopp e)\n  | (AinvT ?X1) => let e := interp_A FT lvar X1 in\n                   constr:(EAinv e)\n  | ?X1 => let idx := assoc X1 lvar in\n           constr:(EAvar idx)\n  end.\n\n(************************)\n(*    Simplification    *)\n(************************)\n\n(**** Generation of the multiplier ****)\n\nLtac remove e l :=\n  match constr:(l) with\n  | nil => l\n  | e :: ?X2 => constr:(X2)\n  | ?X2 :: ?X3 => let nl := remove e X3 in constr:(X2 :: nl)\n  end.\n\nLtac union l1 l2 :=\n  match constr:(l1) with\n  | nil => l2\n  | ?X2 :: ?X3 =>\n      let nl2 := remove X2 l2 in\n      let nl := union X3 nl2 in\n      constr:(X2 :: nl)\n  end.\n\nLtac raw_give_mult trm :=\n  match constr:(trm) with\n  | (EAinv ?X1) => constr:(X1 :: nil)\n  | (EAopp ?X1) => raw_give_mult X1\n  | (EAplus ?X1 ?X2) =>\n      let l1 := raw_give_mult X1 with l2 := raw_give_mult X2 in\n      union l1 l2\n  | (EAmult ?X1 ?X2) =>\n      let l1 := raw_give_mult X1 with l2 := raw_give_mult X2 in\n      eval compute in (app l1 l2)\n  | _ => constr:(@nil ExprA)\n  end.\n\nLtac give_mult trm :=\n  let ltrm := raw_give_mult trm in\n  constr:(mult_of_list ltrm).\n\n(**** Associativity ****)\n\nLtac apply_assoc FT lvar trm :=\n  let t := eval compute in (assoc trm) in\n  match constr:(t = trm) with\n  | (?X1 = ?X1) => idtac\n  | _ =>\n      rewrite <- (assoc_correct FT trm); change (assoc trm) with t\n  end.\n\n(**** Distribution *****)\n\nLtac apply_distrib FT lvar trm :=\n  let t := eval compute in (distrib trm) in\n  match constr:(t = trm) with\n  | (?X1 = ?X1) => idtac\n  | _ =>\n      rewrite <- (distrib_correct FT trm);\n       change (distrib trm) with t\n  end.\n\n(**** Multiplication by the inverse product ****)\n\nLtac grep_mult := match goal with\n                  | id:(interp_ExprA _ _ _ <> _) |- _ => id\n                  end.\n\nLtac weak_reduce :=\n  match goal with\n  |  |- context [(interp_ExprA ?X1 ?X2 _)] =>\n      cbv beta iota zeta\n       delta [interp_ExprA assoc_2nd eq_nat_dec mult_of_list X1 X2 A Azero\n             Aone Aplus Amult Aopp Ainv]\n  end.\n\nLtac multiply mul :=\n  match goal with\n  |  |- (interp_ExprA ?FT ?X2 ?X3 = interp_ExprA ?FT ?X2 ?X4) =>\n      let AzeroT := get_component Azero FT in\n      cut (interp_ExprA FT X2 mul <> AzeroT);\n       [ intro; (let id := grep_mult in apply (mult_eq FT X3 X4 mul X2 id))\n       | weak_reduce;\n          (let AoneT := get_component Aone ltac:(body_of FT)\n           with AmultT := get_component Amult ltac:(body_of FT) in\n           try\n             match goal with\n             |  |- context [(AmultT _ AoneT)] => rewrite (AmultT_1r FT)\n             end; clear FT X2) ]\n  end.\n\nLtac apply_multiply FT lvar trm :=\n  let t := eval compute in (multiply trm) in\n  match constr:(t = trm) with\n  | (?X1 = ?X1) => idtac\n  | _ =>\n      rewrite <- (multiply_correct FT trm);\n       change (multiply trm) with t\n  end.\n\n(**** Permutations and simplification ****)\n\nLtac apply_inverse mul FT lvar trm :=\n  let t := eval compute in (inverse_simplif mul trm) in\n  match constr:(t = trm) with\n  | (?X1 = ?X1) => idtac\n  | _ =>\n      rewrite <- (inverse_correct FT trm mul);\n       [ change (inverse_simplif mul trm) with t | assumption ]\n  end.\n(**** Inverse test ****)\n\nLtac strong_fail tac := first [ tac | fail 2 ].\n\nLtac inverse_test_aux FT trm :=\n  let AplusT := get_component Aplus FT\n  with AmultT := get_component Amult FT\n  with AoppT := get_component Aopp FT\n  with AinvT := get_component Ainv FT in\n  match constr:(trm) with\n  | (AinvT _) => fail 1\n  | (AoppT ?X1) =>\n      strong_fail ltac:(inverse_test_aux FT X1; idtac)\n  | (AplusT ?X1 ?X2) =>\n      strong_fail ltac:(inverse_test_aux FT X1; inverse_test_aux FT X2)\n  | (AmultT ?X1 ?X2) =>\n      strong_fail ltac:(inverse_test_aux FT X1; inverse_test_aux FT X2)\n  | _ => idtac\n  end.\n\nLtac inverse_test FT :=\n  let AplusT := get_component Aplus FT in\n  match goal with\n  |  |- (?X1 = ?X2) => inverse_test_aux FT (AplusT X1 X2)\n  end.\n\n(**** Field itself ****)\n\nLtac apply_simplif sfun :=\n  match goal with\n  |  |- (interp_ExprA ?X1 ?X2 ?X3 = interp_ExprA _ _ _) =>\n  sfun X1 X2 X3\n  end;\n   match goal with\n   |  |- (interp_ExprA _ _ _ = interp_ExprA ?X1 ?X2 ?X3) =>\n   sfun X1 X2 X3\n   end.\n\nLtac unfolds FT :=\n  match get_component Aminus FT with\n  | Some ?X1 => unfold X1\n  | _ => idtac\n  end;\n  match get_component Adiv FT with\n  | Some ?X1 => unfold X1\n  | _ => idtac\n  end.\n\nLtac reduce FT :=\n  let AzeroT := get_component Azero FT\n  with AoneT := get_component Aone FT\n  with AplusT := get_component Aplus FT\n  with AmultT := get_component Amult FT\n  with AoppT := get_component Aopp FT\n  with AinvT := get_component Ainv FT in\n  (cbv beta iota zeta delta -[AzeroT AoneT AplusT AmultT AoppT AinvT] ||\n     compute).\n\nLtac field_gen_aux FT :=\n  let AplusT := get_component Aplus FT in\n  match goal with\n  |  |- (?X1 = ?X2) =>\n      let lvar := build_varlist FT (AplusT X1 X2) in\n      let trm1 := interp_A FT lvar X1 with trm2 := interp_A FT lvar X2 in\n      let mul := give_mult (EAplus trm1 trm2) in\n      cut\n        (let ft := FT in\n         let vm := lvar in interp_ExprA ft vm trm1 = interp_ExprA ft vm trm2);\n        [ compute; auto\n        | intros ft vm; apply_simplif apply_distrib;\n           apply_simplif apply_assoc; multiply mul;\n           [ apply_simplif apply_multiply;\n              apply_simplif ltac:(apply_inverse mul);\n              (let id := grep_mult in\n               clear id; weak_reduce; clear ft vm; first\n              [ inverse_test FT; legacy ring | field_gen_aux FT ])\n           | idtac ] ]\n  end.\n\nLtac field_gen FT :=\n  unfolds FT; (inverse_test FT; legacy ring) || field_gen_aux FT.\n\n(*****************************)\n(*    Term Simplification    *)\n(*****************************)\n\n(**** Minus and division expansions ****)\n\nLtac init_exp FT trm :=\n  let e :=\n   (match get_component Aminus FT with\n    | Some ?X1 => eval cbv beta delta [X1] in trm\n    | _ => trm\n    end) in\n  match get_component Adiv FT with\n  | Some ?X1 => eval cbv beta delta [X1] in e\n  | _ => e\n  end.\n\n(**** Inverses simplification ****)\n\nLtac simpl_inv trm :=\n  match constr:(trm) with\n  | (EAplus ?X1 ?X2) =>\n      let e1 := simpl_inv X1 with e2 := simpl_inv X2 in\n      constr:(EAplus e1 e2)\n  | (EAmult ?X1 ?X2) =>\n      let e1 := simpl_inv X1 with e2 := simpl_inv X2 in\n      constr:(EAmult e1 e2)\n  | (EAopp ?X1) => let e := simpl_inv X1 in\n                   constr:(EAopp e)\n  | (EAinv ?X1) => SimplInvAux X1\n  | ?X1 => constr:(X1)\n  end\n with SimplInvAux trm :=\n  match constr:(trm) with\n  | (EAinv ?X1) => simpl_inv X1\n  | (EAmult ?X1 ?X2) =>\n      let e1 := simpl_inv (EAinv X1) with e2 := simpl_inv (EAinv X2) in\n      constr:(EAmult e1 e2)\n  | ?X1 => let e := simpl_inv X1 in\n           constr:(EAinv e)\n  end.\n\n(**** Monom simplification ****)\n\nLtac map_tactic fcn lst :=\n  match constr:(lst) with\n  | nil => lst\n  | ?X2 :: ?X3 =>\n      let r := fcn X2 with t := map_tactic fcn X3 in\n      constr:(r :: t)\n  end.\n\nLtac build_monom_aux lst trm :=\n  match constr:(lst) with\n  | nil => eval compute in (assoc trm)\n  | ?X1 :: ?X2 => build_monom_aux X2 (EAmult trm X1)\n  end.\n\nLtac build_monom lnum lden :=\n  let ildn := map_tactic ltac:(fun e => constr:(EAinv e)) lden in\n  let ltot := eval compute in (app lnum ildn) in\n  let trm := build_monom_aux ltot EAone in\n  match constr:(trm) with\n  | (EAmult _ ?X1) => constr:(X1)\n  | ?X1 => constr:(X1)\n  end.\n\nLtac simpl_monom_aux lnum lden trm :=\n  match constr:(trm) with\n  | (EAmult (EAinv ?X1) ?X2) =>\n      let mma := mem_assoc X1 lnum in\n      match constr:(mma) with\n      | true =>\n          let newlnum := remove X1 lnum in\n          simpl_monom_aux newlnum lden X2\n      | false => simpl_monom_aux lnum (X1 :: lden) X2\n      end\n  | (EAmult ?X1 ?X2) =>\n      let mma := mem_assoc X1 lden in\n      match constr:(mma) with\n      | true =>\n          let newlden := remove X1 lden in\n          simpl_monom_aux lnum newlden X2\n      | false => simpl_monom_aux (X1 :: lnum) lden X2\n      end\n  | (EAinv ?X1) =>\n      let mma := mem_assoc X1 lnum in\n      match constr:(mma) with\n      | true =>\n          let newlnum := remove X1 lnum in\n          build_monom newlnum lden\n      | false => build_monom lnum (X1 :: lden)\n      end\n  | ?X1 =>\n      let mma := mem_assoc X1 lden in\n      match constr:(mma) with\n      | true =>\n          let newlden := remove X1 lden in\n          build_monom lnum newlden\n      | false => build_monom (X1 :: lnum) lden\n      end\n  end.\n\nLtac simpl_monom trm := simpl_monom_aux (@nil ExprA) (@nil ExprA) trm.\n\nLtac simpl_all_monomials trm :=\n  match constr:(trm) with\n  | (EAplus ?X1 ?X2) =>\n      let e1 := simpl_monom X1 with e2 := simpl_all_monomials X2 in\n      constr:(EAplus e1 e2)\n  | ?X1 => simpl_monom X1\n  end.\n\n(**** Associativity and distribution ****)\n\nLtac assoc_distrib trm := eval compute in (assoc (distrib trm)).\n\n(**** The tactic Field_Term ****)\n\nLtac eval_weak_reduce trm :=\n  eval\n   cbv beta iota zeta\n    delta [interp_ExprA assoc_2nd eq_nat_dec mult_of_list A Azero Aone Aplus\n          Amult Aopp Ainv] in trm.\n\nLtac field_term FT exp :=\n  let newexp := init_exp FT exp in\n  let lvar := build_varlist FT newexp in\n  let trm := interp_A FT lvar newexp in\n  let tma := eval compute in (assoc trm) in\n  let tsmp :=\n   simpl_all_monomials\n    ltac:(assoc_distrib ltac:(simpl_all_monomials ltac:(simpl_inv tma))) in\n  let trep := eval_weak_reduce (interp_ExprA FT lvar tsmp) in\n  (replace exp with trep; [ legacy ring trep | field_gen FT ]).\n", "meta": {"author": "coq-contribs", "repo": "legacy-field", "sha": "6dbae683e2331a88503c3867ee88675d79e31e4c", "save_path": "github-repos/coq/coq-contribs-legacy-field", "path": "github-repos/coq/coq-contribs-legacy-field/legacy-field-6dbae683e2331a88503c3867ee88675d79e31e4c/LegacyField_Tactic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.2902211242444727}}
{"text": "Require Import Setoid.\nRequire Import DepList Memory.\nRequire Import Word.\n\nRequire Import List.\n\nModule Type Heap.\n  \n  Parameter addr : Type.\n\n  Parameter mem : Type.\n\n  Parameter mem_get : mem -> addr -> option B.\n  Parameter mem_set : mem -> addr -> B -> option mem.\n\n  Parameter mem_acc : mem -> addr -> Prop.\n\n  Parameter mem_get_acc : forall m p,\n    mem_acc m p <->\n    exists v, mem_get m p = Some v.\n\n  Parameter mem_set_acc : forall m p,\n    mem_acc m p <->\n    forall v, exists m', mem_set m p v = Some m'.\n\n  Parameter mem_acc_dec : forall m p,\n    mem_acc m p \\/ ~mem_acc m p.\n\n  (** mem writes persist **)\n  Parameter mem_get_set_eq : forall m p v' m', \n    mem_set m p v' = Some m' ->\n    mem_get m' p = Some v'.\n\n  (** mem writes don't overwrite elsewhere **)\n  Parameter mem_get_set_neq : forall m p p' v' m', \n    p <> p' ->\n    mem_set m p' v' = Some m' ->\n    mem_get m' p = mem_get m p.\n\n  (** mem writes don't modify permissions **)\n  Parameter mem_set_perm : forall m p v m',\n    mem_set m p v = Some m' ->\n    (forall p, mem_acc m p -> mem_acc m' p).\n\n  Parameter footprint_w : addr -> addr * addr * addr * addr.\n  \n  Parameter footprint_disjoint : forall p a b c d,\n    footprint_w p = (a,b,c,d) ->\n    a <> b /\\ a <> c /\\ a <> d /\\ b <> c /\\ b <> d /\\ c <> d.\n\n  Parameter addr_dec : forall a b : addr, {a = b} + {a <> b}.\n\n  Parameter all_addr : list addr.\n\n  Parameter NoDup_all_addr : NoDup all_addr.\n\nEnd Heap.\n\nModule HeapTheory (B : Heap).\n  Import B.\n\n  Definition smem' dom : Type := hlist (fun _ : addr => option B) dom.\n\n  Fixpoint smem_emp' (ls : list addr) : smem' ls :=\n    match ls with\n      | nil => HNil\n      | a :: b => HCons None (smem_emp' b)\n    end.\n  Fixpoint disjoint' dom : smem' dom -> smem' dom -> Prop :=\n    match dom with\n      | nil => fun _ _ => True\n      | a :: b => fun m1 m2 => \n           (hlist_hd m1 = None \\/ hlist_hd m2 = None) \n        /\\ disjoint' _ (hlist_tl m1) (hlist_tl m2)\n    end.\n  Fixpoint join' dom : smem' dom -> smem' dom -> smem' dom :=\n    match dom with\n      | nil => fun _ _ => HNil\n      | a :: b => fun m1 m2 => \n        HCons \n        match hlist_hd m1 with\n          | None => hlist_hd m2\n          | Some x => Some x\n        end\n        (join' _ (hlist_tl m1) (hlist_tl m2))\n    end.\n\n  Fixpoint relevant' (ls : list addr) : smem' ls -> list addr :=\n    match ls with\n      | nil => fun _ => nil\n      | a :: b => fun x => \n        match hlist_hd x with\n          | None => relevant' _ (hlist_tl x)\n          | Some _ => a :: relevant' _ (hlist_tl x)\n        end\n    end.\n  \n  Fixpoint smem_get' dom : addr -> smem' dom -> option B :=\n    match dom as dom return addr -> smem' dom -> option B with \n      | nil => fun _ _ => None\n      | a :: b => fun a' m =>\n        if addr_dec a a' then \n          hlist_hd m\n        else\n          smem_get' b a' (hlist_tl m)\n    end.\n\n  Fixpoint smem_set' dom : addr -> B -> smem' dom -> option (smem' dom) :=\n    match dom as dom return addr -> B -> smem' dom -> option (smem' dom) with \n      | nil => fun _ _ _ => None\n      | a :: b => fun p v m =>\n        if addr_dec a p then\n          match hlist_hd m with\n            | None => None\n            | Some _ => Some (HCons (Some v) (hlist_tl m))\n          end\n        else\n          match smem_set' b p v (hlist_tl m) with\n            | None => None\n            | Some tl => Some (HCons (hlist_hd m) tl)\n          end\n    end.\n\n  Fixpoint satisfies' dom (sm : smem' dom) (m : B.mem) : Prop :=\n    match sm with\n      | HNil => True\n      | HCons p _ a b =>\n        match a with\n          | None => True\n          | Some x => \n               B.mem_get m p = Some x /\\ mem_acc m p\n        end /\\ satisfies' _ b m\n    end.\n\n  Definition smem : Type := smem' all_addr.\n\n  Definition smem_emp : smem := smem_emp' all_addr.\n\n  Definition smem_get := @smem_get' all_addr.\n\n  Definition smem_set := @smem_set' all_addr.\n\n  Definition smem_get_word (implode : B * B * B * B -> W) (p : addr) (m : smem)\n    : option W :=\n    let '(a,b,c,d) := footprint_w p in\n    match smem_get a m , smem_get b m , smem_get c m , smem_get d m with\n      | Some a , Some b , Some c , Some d =>\n        Some (implode (a,b,c,d))\n      | _ , _ , _ , _ => None\n    end.\n\n  Definition smem_set_word (explode : W -> B * B * B * B) (p : addr) (v : W)\n    (m : smem) : option smem :=\n    let '(a,b,c,d) := footprint_w p in\n    let '(av,bv,cv,dv) := explode v in\n    match smem_set d dv m with\n      | None => None \n      | Some m => match smem_set c cv m with\n                    | None => None\n                    | Some m => match smem_set b bv m with\n                                  | None => None\n                                  | Some m => smem_set a av m\n                                end\n                  end\n    end.\n\n  Definition disjoint (m1 m2 : smem) : Prop :=\n    disjoint' _ m1 m2.\n\n  Definition join (m1 m2 : smem) : smem := \n    join' _ m1 m2.\n\n  Definition split (m ml mr : smem) : Prop :=\n    disjoint ml mr /\\ m = join ml mr.\n\n  Definition semp (m : smem) : Prop :=\n    m = smem_emp.\n\n  Definition satisfies (m : smem) (m' : B.mem) : Prop :=\n    satisfies' _ m m'.\n\n  Definition relevant (sm : smem) := relevant' _ sm.\n\n  Global Instance EqDec_addr : EquivDec.EqDec addr (@eq addr) := addr_dec.\n\n  Local Hint Resolve mem_get_set_eq mem_get_set_neq : memory.\n\n  Lemma smem_set_not_in : forall l m p v,\n    ~In p l -> smem_set' l p v m = None.\n  Proof.\n    induction l; simpl; auto.\n      intros.\n      destruct (addr_dec a p); subst; intuition.\n      rewrite IHl; auto.\n  Qed.\n\n  Ltac simp ext :=\n    intros; simpl in *;\n    repeat (instantiate; \n      match goal with\n        | [ H : prod _ _ |- _ ] => destruct H\n        | [ H : context [ footprint_w ?X ] |- _ ] => \n          destruct (footprint_w X)\n        | [ H : Some _ = Some _ |- _ ] =>\n          inversion H; clear H; try subst\n        | [ H : _ = _ |- _ ] => rewrite H in *\n        | [ H : NoDup (_ :: _) |- _ ] =>\n          inversion H; clear H; subst\n        | [ H : context [ addr_dec ?A ?B ] |- _ ] => \n          destruct (addr_dec A B); subst\n        | [ |- context [ addr_dec ?A ?B ] ] => \n          destruct (addr_dec A B); subst\n        | [ H : match ?X with \n                  | Some _ => _\n                  | None => _\n                end = _ |- _ ] => \n          generalize dependent H; case_eq X; intros\n        | [ H : match ?X with \n                  | Some _ => _\n                  | None => _\n                end |- _ ] => \n          generalize dependent H; case_eq X; intros\n        | [ H : satisfies' (_ :: _) ?M _ |- _ ] =>\n          match M with\n            | HCons _ _ => fail 1\n            | _ => rewrite (hlist_eta _ M) in H\n          end\n        | [ |- satisfies' (_ :: _) ?M _ ] =>\n          match M with\n            | HCons _ _ => fail 1\n            | _ => rewrite (hlist_eta _ M)\n          end\n        | [ H : smem' nil |- _ ] => \n          rewrite (hlist_nil_only _ H) in *\n        | [ H : exists x, _ |- _ ] => destruct H\n        | [ H : _ /\\ _ |- _ ] => destruct H\n        | [ |- _ ] => congruence\n        | [ |- _ ] => ext\n      end; simpl in *); eauto 10 with memory.\n\n  Theorem satisfies_get : forall m m',\n    satisfies m m' ->\n    forall p v, \n      smem_get p m = Some v ->\n      mem_get m' p = Some v.\n  Proof.\n    unfold satisfies, smem_get, smem.\n    induction all_addr; simp intuition. \n  Qed.\n\n  Lemma satisfies_set_not_in : forall l m sm p v,\n    satisfies' l sm m ->\n    ~In p l ->\n    forall m', mem_set m p v = Some m' ->\n    satisfies' l sm m'.\n  Proof.\n    induction l; try solve [ simp intuition ].\n      simp auto.\n      destruct (addr_dec a p); destruct (in_dec addr_dec p l); subst; try solve [ intuition ].\n\n      split; eauto. erewrite mem_get_set_neq; eauto. \n      split; eauto. eapply mem_set_perm; eauto.\n  Qed.\n\n  Local Hint Resolve mem_set_perm satisfies_set_not_in : memory.\n\n  Theorem satisfies_set : forall sm m,\n    satisfies sm m ->\n    forall p v sm',\n      smem_set p v sm = Some sm' ->\n      exists m',\n      mem_set m p v = Some m' /\\ satisfies sm' m'.\n  Proof.\n    unfold satisfies, smem_set, smem_get, smem, relevant.\n    generalize NoDup_all_addr.\n    induction all_addr; simp auto.\n      destruct (proj1 (mem_set_acc _ _) H2 v). rewrite H3. eexists; split; eauto.        \n      erewrite mem_get_set_eq; eauto with memory.\n\n      Focus.\n      eapply IHl in H1; eauto.\n      destruct H1; eexists; intuition; eauto with memory.\n      erewrite mem_get_set_neq; eauto.\n\n      Focus.\n      eapply IHl in H1; eauto. destruct H1; eexists; intuition eauto.\n  Qed.\n\n  Theorem satisfies_get_word : forall i m m',\n    satisfies m m' ->\n    forall p v, \n      smem_get_word i p m = Some v ->\n      mem_get_word addr mem footprint_w mem_get i p m' = Some v.\n  Proof.\n    unfold mem_get_word, smem_get_word; simp intuition.\n    repeat erewrite satisfies_get by eauto. auto.\n  Qed.\n\n  Lemma smem_set_get_neq : forall p m m' a b,\n    smem_set a b m = Some m' ->\n    a <> p ->\n    smem_get p m' = smem_get p m.\n  Proof.\n    unfold smem, smem_get, smem_set.\n    induction all_addr; simp intuition.\n  Qed.\n\n  Lemma smem_set_get_eq : forall m m' a b,\n    smem_set a b m = Some m' ->\n    smem_get a m' = Some b.\n  Proof.\n    unfold smem, smem_get, smem_set.\n    induction all_addr; simp intuition.\n  Qed.\n\n  Lemma smem_set_get_word_eq : forall i e m m' a b,\n    (forall x, i (e x) = x) ->\n    smem_set_word e a b m = Some m' ->\n    smem_get_word i a m' = Some b.\n  Proof.\n    unfold smem_get_word, smem_set_word; intros.\n    generalize (footprint_disjoint a).\n    generalize dependent H0. case_eq (e b). simp intuition.\n    specialize (H2 _ _ _ _ (refl_equal _)). simp intuition.\n    repeat ((erewrite smem_set_get_eq; [ | repeat rewrite smem_set_get_neq by auto; eassumption ])\n      || (erewrite smem_set_get_neq by eauto)). simp intuition.\n  Qed.\n\n  Lemma split_smem_get : forall a b c p v,\n    split a b c ->\n      (smem_get p b = Some v \\/ smem_get p c = Some v) ->\n      smem_get p a = Some v.\n  Proof.\n    unfold smem, split, disjoint, join, smem_get, smem.\n    induction all_addr; simp intuition.\n  Qed.\n\n  Lemma split_smem_get_word : forall i a b c p v,\n    split a b c ->\n      (smem_get_word i p b = Some v \\/ smem_get_word i p c = Some v) ->\n      smem_get_word i p a = Some v.\n  Proof.\n    unfold smem_get_word. simp intuition;\n    repeat (erewrite split_smem_get by eauto); auto.\n  Qed.\n\n  Theorem satisfies_set_word : forall sm m,\n    satisfies sm m ->\n    forall e p v sm',\n      smem_set_word e p v sm = Some sm' ->\n      exists m',\n           mem_set_word addr mem footprint_w mem_set e p v m = Some m' \n        /\\ satisfies sm' m'.\n  Proof.\n    unfold smem_set_word, mem_set_word, smem_get_word; intros.\n    simp intuition. destruct (e v); simp intuition.\n    repeat match goal with\n             | [ H : satisfies _ _ |- _ ] => \n               eapply satisfies_set in H; eauto; destruct H as [ ? [ ? ? ] ]\n             | [ H : _ = _ |- _ ] => rewrite H\n           end.\n    exists x2. intuition eauto.\n  Qed.\n\n  Lemma smem_set_get_valid : forall m p v v',\n    smem_get p m = Some v' ->\n    smem_set p v m <> None.\n  Proof.\n    unfold smem_get, smem_set, smem.\n    induction all_addr; simp intuition.\n  Qed.\n\n  Lemma smem_set_get_valid_word : forall i e m p v v',\n    smem_get_word i p m = Some v' ->\n    smem_set_word e p v m <> None.\n  Proof.\n    unfold smem_get_word, smem_set_word.\n    intros. generalize (footprint_disjoint p).\n    intros; destruct (e v); simp intuition;\n    specialize (H0 _ _ _ _ (refl_equal _)); simp intuition;\n    (eapply smem_set_get_valid; [ | eauto ];\n      repeat (erewrite smem_set_get_neq; [ | solve [ eauto ] | solve [ eauto ] ]); eauto).\n  Qed.\n\n  Lemma split_set : forall a b,\n    disjoint a b ->\n    forall p v a',\n    smem_set p v a = Some a' ->\n      disjoint a' b /\\ \n      smem_set p v (join a b) = Some (join a' b).\n  Proof.\n    unfold smem, disjoint, join, smem_set, smem.\n    induction all_addr; simpl; intros; try congruence.\n      destruct (addr_dec a p); subst.\n      destruct H. destruct H; rewrite H in *; try congruence.\n        destruct (hlist_hd a0); try congruence.\n        inversion H0; auto.\n\n      generalize dependent H0.\n      case_eq (smem_set' l p v (hlist_tl a0)); intros; try congruence.\n        inversion H1; clear H1; subst.\n        eapply IHl in H0. 2: destruct H; eauto.\n        simp intuition.\n  Qed.\n\n  Lemma split_set_word : forall a b,\n    disjoint a b ->\n    forall i p v a',\n    smem_set_word i p v a = Some a' ->\n      disjoint a' b /\\ \n      smem_set_word i p v (join a b) = Some (join a' b).\n  Proof.\n    unfold smem_set_word.\n    intros. destruct (i v); simp fail. \n    repeat match goal with\n      | [ H : smem_set _ _ _ = Some _ |- _ ] =>\n        eapply split_set in H; [ rewrite (proj2 H) | eauto ]\n    end; tauto.\n  Qed.\n\n  Ltac unfold_all :=\n    unfold smem, split, join, disjoint, smem_emp, semp; \n    unfold smem, split, join, disjoint, smem_emp, semp.\n  Ltac break :=\n    simpl; intros; try reflexivity;\n      repeat (simpl in *; match goal with\n                            | [ H : HCons _ _ = HCons _ _ |- _ ] =>\n                              inversion H; clear H\n                            | [ H : _ /\\ _ |- _ ] => destruct H\n                            | [ H : @existT _ _ _ _ = @existT _ _ _ _ |- _ ] => \n                              eapply (@Eqdep_dec.inj_pair2_eq_dec _ (list_eq_dec B.addr_dec)) in H\n                            | [ H : @existT _ _ _ _ = @existT _ _ _ _ |- _ ] => \n                              eapply (@Eqdep_dec.inj_pair2_eq_dec _ B.addr_dec) in H\n                            | [ H : _ = _ |- _ ] => rewrite H in *\n                          end).\n  \n  Lemma disjoint_join : forall a b, disjoint a b -> join a b = join b a.\n  Proof.\n    unfold_all; induction a; break; f_equal; intuition; subst.\n      destruct (hlist_hd b0); reflexivity.\n      rewrite H1. destruct b; reflexivity.\n  Qed.\n    \n  Lemma disjoint_comm : forall ml mr, disjoint ml mr -> disjoint mr ml.\n  Proof.\n    unfold_all; induction ml; break; intuition.\n  Qed.\n\n  Hint Resolve disjoint_join disjoint_comm : disjoint.\n\n  Lemma split_assoc : forall b a c d e, split a b c -> split c d e ->\n    split a (join d b) e.\n  Proof.\n    unfold_all; induction b; break; eauto.\n    edestruct IHb. split; try eassumption. reflexivity. split; try eassumption.\n    reflexivity.\n    intuition; break; auto. destruct (hlist_hd d); auto.\n    destruct (hlist_hd d); try congruence.\n  Qed.\n\n  Lemma split_comm : forall ml m mr, split m ml mr -> split m mr ml.\n  Proof.\n    unfold_all. induction ml; break; eauto. edestruct IHml.\n    split; try eassumption. reflexivity. \n    intuition; subst. rewrite H3. destruct (hlist_hd mr); auto.\n    rewrite H4. rewrite H3. destruct b; auto.\n  Qed.\n\n  Lemma disjoint_split_join : forall a b, disjoint a b -> split (join a b) a b.\n  Proof.\n    unfold split, disjoint; intros; intuition.\n  Qed.\n\n  Lemma split_split_disjoint : forall b a c d e,\n    split a b c -> split b d e -> disjoint c d.\n  Proof.\n    unfold_all. induction b; break. subst. split.\n    intuition; destruct (hlist_hd c); eauto. destruct (hlist_hd d); auto.\n    eapply IHb. split; auto. split; auto. auto.\n  Qed.\n\n  Lemma hlist_destruct : forall T (F : T -> Type) a b (m : hlist F (a :: b)),\n    exists A, exists B, m = HCons A B.\n  Proof.\n    intros.\n    refine (match m as m in hlist _ ls return\n              match ls as ls return hlist _ ls -> Type with\n                | nil => fun _ => unit\n                | a :: b => fun m => exists A : F a, exists B : hlist F b, m = HCons A B\n              end m\n              with\n              | HNil => tt\n              | HCons _ _ _ _ => _\n            end).\n    do 2 eexists; reflexivity.\n  Qed.\n  Lemma hlist_nil : forall T (F : T -> Type) (m : hlist F nil), m = HNil.\n  Proof.\n    intros. \n    refine (match m as m in hlist _ ls return\n              match ls as ls return hlist _ ls -> Type with\n                | nil => fun m => m = HNil\n                | _ :: _ => fun _ => unit\n              end m\n              with\n              | HNil => _ \n              | _ => tt\n            end). reflexivity.\n  Qed.\n\n  Lemma split_semp : forall b a c, \n    split a b c -> semp b -> a = c.\n  Proof.\n    unfold_all. unfold semp, smem_emp. unfold_all.\n    induction b; simpl; intros; subst; auto.\n    rewrite hlist_nil. rewrite (hlist_nil _ _ a). reflexivity.\n    destruct (hlist_destruct _ _ _ _ a).\n    destruct (hlist_destruct _ _ _ _ c).\n    destruct H1. destruct H2. subst. specialize (IHb x2 x3).\n    rewrite IHb; break; intuition; auto.\n  Qed.\n\n  Lemma semp_smem_emp : semp smem_emp.\n  Proof.\n    unfold semp, smem_emp; auto.\n  Qed.\n\n  Lemma split_a_semp_a : forall a, \n    split a smem_emp a.\n  Proof.\n    unfold_all. induction a; simpl; intuition. rewrite <- H0. reflexivity.\n  Qed.\n     \n  Lemma cons_not_in : forall T (a : T) b ls,\n    a :: b = ls ->\n    ~ In a ls ->\n    forall P, P.\n  Proof.\n    intros; subst. exfalso; eapply H0. firstorder.\n  Qed.\n  \n  Lemma relevant_in : forall a l b,\n    In a (relevant' l b) ->\n    In a l.\n  Proof.\n    induction l; auto; intros.\n      rewrite (hlist_eta _ b) in H. simpl in H.\n      destruct (hlist_hd b). destruct H. subst. firstorder.\n      simpl in *. right. eapply IHl; eauto.\n      right. eapply IHl; eauto.\n  Qed.\n\n  Lemma relevant_not_in : forall a l b,\n    ~In a l ->\n    ~In a (relevant' l b).\n  Proof.\n    intros. intro. eapply H. eapply relevant_in; eauto.\n  Qed.\n\n  Lemma relevant_eq : forall a b c,\n    relevant a = relevant b ->\n    satisfies a c ->\n    satisfies b c ->\n    a = b.\n  Proof.\n    unfold relevant, satisfies, smem. generalize NoDup_all_addr.\n    induction all_addr; simpl; intros.\n      rewrite (hlist_nil_only _ a). rewrite (hlist_nil_only _ b); auto.\n\n      rewrite (hlist_eta _ a0) in *. rewrite (hlist_eta _ a0) in H1.\n      rewrite (hlist_eta _ b) in *. rewrite (hlist_eta _ b) in H2.\n      simpl in *.\n      destruct (hlist_hd a0); destruct (hlist_hd b); intuition.\n        rewrite H2 in H3. inversion H3; subst. inversion H0;  f_equal. eapply IHl; eauto.\n          inversion H; auto.\n\n        eapply cons_not_in. eassumption.\n        eapply relevant_not_in. inversion H; auto.\n\n        eapply cons_not_in. symmetry. eassumption.\n        eapply relevant_not_in. inversion H; auto.\n        \n        f_equal; eauto. inversion H. eapply IHl; eauto.\n  Qed.\n\n  (** memoryIn **)\n  Section memoryIn.\n    Variable m : mem.\n\n    Fixpoint memoryIn' (ls : list addr) : smem' ls :=\n      match ls with \n        | nil => HNil\n        | l :: ls => HCons (mem_get m l) (memoryIn' ls)\n      end. \n\n    Definition memoryIn : smem := memoryIn' all_addr.\n  End memoryIn.\n\n  Theorem smem_set_relevant : forall p v sm sm',\n    smem_set p v sm = Some sm' ->\n    relevant sm = relevant sm'.\n  Proof.\n    unfold relevant, smem_set.\n    induction all_addr; simpl; intros; auto.\n      destruct (addr_dec a p); subst; auto.\n      destruct (hlist_hd sm); try congruence.\n      inversion H; clear H; subst. simpl. reflexivity.\n\n      revert H. case_eq (smem_set' l p v (hlist_tl sm)); intros; try congruence.\n      inversion H0; clear H0; subst; simpl in *.\n      destruct (hlist_hd sm); eauto. f_equal; eauto.\n  Qed.\n\n  Theorem smem_set_word_relevant : forall ex p v sm sm',\n    smem_set_word ex p v sm = Some sm' ->\n    relevant sm = relevant sm'.\n  Proof.\n    unfold smem_set_word; intros.\n    destruct (footprint_w p) as [ [ [ ? ? ] ? ] ? ].\n    destruct (ex v) as [ [ [ ? ? ] ? ] ? ].\n    repeat match goal with\n             | [ H : match ?X with \n                       | Some _ => _\n                       | None => _ \n                     end = Some _ |- _ ] => revert H; case_eq X; intros; try congruence\n             | [ H : smem_set _ _ _ = Some _ |- _ ] => \n               eapply smem_set_relevant in H\n           end.\n    congruence.\n  Qed.\n\n  Theorem satisfies_memoryIn : forall m, \n    satisfies (memoryIn m) m.\n  Proof.\n    unfold satisfies, memoryIn. generalize all_addr.\n    induction l; simpl; auto.\n    intuition. destruct (mem_acc_dec m a).\n    generalize (proj1 (mem_get_acc _ _) H). intro. destruct H0. rewrite H0. auto.\n    case_eq (mem_get m a); intuition; auto.\n    eapply mem_get_acc. eauto.\n  Qed.\n\n(*\nFixpoint memoryInUpto (width init : nat) (m : word width -> option B)\n  : hlist (fun _ => option B) (allWordsUpto width init) :=\n  match init with\n    | O => HNil\n    | S init' =>\n      let w := natToWord width init' in\n      let v := m w in\n      HCons v (memoryInUpto (width := width) init' m)\n  end.\n\nDefinition memoryIn_def (width : nat) :=\n  memoryInUpto (width := width) (pow2 width).\n\nTheorem fcong : forall A (B : A -> Type) (f g : forall x, B x) x,\n  f = g\n  -> f x = g x.\n  congruence.\nDefined.\n\nModule Type ALL_WORDS.\n  Parameter allWords : forall width : nat, list (word width).\n\n  Axiom allWords_eq : allWords = allWords_def.\n\n  Parameter memoryIn : forall width, (word width -> option B) -> hlist (fun _ : word width => option B) (allWords width).\n\n  Axiom memoryIn_eq : forall width,\n    memoryIn (width := width)\n    = match fcong (fun width => list (word width)) width (sym_eq allWords_eq) in _ = L return _ -> hlist _ L with\n        | refl_equal => memoryIn_def (width := width)\n      end.\nEnd ALL_WORDS.\n\nModule AllWords : ALL_WORDS.\n  Definition allWords := allWords_def.\n\n  Theorem allWords_eq : allWords = allWords_def.\n    reflexivity.\n  Defined.\n\n  Definition memoryIn := memoryIn_def.\n\n  Theorem memoryIn_eq : forall width,\n    memoryIn (width := width)\n    = match fcong (fun width => list (word width)) width (sym_eq allWords_eq) in _ = L return _ -> hlist _ L with\n        | refl_equal => memoryIn_def (width := width)\n      end.\n    reflexivity.\n  Qed.\nEnd AllWords.\n*)\n\nEnd HeapTheory.\n", "meta": {"author": "csgordon", "repo": "bedrock", "sha": "debab1b6e491b7c5e83bd3b1fe5d0e4c4e728d12", "save_path": "github-repos/coq/csgordon-bedrock", "path": "github-repos/coq/csgordon-bedrock/bedrock-debab1b6e491b7c5e83bd3b1fe5d0e4c4e728d12/src/Heaps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2901978300004309}}
{"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 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 := 100.\n\n  (* checkpoint period *)\n  Definition CP := 50.\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   (i : Rep) (dst : Rep)    : pbft_sending_key   := pbft_sending_key_stub.\n  Definition pbft_lookup_replica_receiving_key (i : Rep) (dst : Rep)    : pbft_receiving_key := pbft_receiving_key_stub.\n\n  Definition pbft_lookup_client_sending_key    (i : Rep) (c   : Client) : pbft_sending_key   := pbft_sending_key_stub.\n  Definition pbft_lookup_client_receiving_key  (i : Rep) (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        (List.app\n           (map (fun c => MkDSKey [PBFTclient c]  (pbft_lookup_client_sending_key  i c)) clients)\n           (map (fun m => MkDSKey [PBFTreplica m] (pbft_lookup_replica_sending_key i m)) reps))\n        (List.app\n           (map (fun c => MkDRKey [PBFTclient c]  (pbft_lookup_client_receiving_key  i c)) clients)\n           (map (fun m => MkDRKey [PBFTreplica m] (pbft_lookup_replica_receiving_key i 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  Definition token2string (t : Token) : string := \"-\".\n\n  Fixpoint tokens2string (toks : Tokens) : string :=\n    match toks with\n    | [] => \"\"\n    | [t] => token2string t\n    | t :: ts => str_concat [token2string t, \",\", tokens2string ts]\n    end.\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 : nat) : string := nat2string delay.\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 :=\n    fun name =>\n      match name with\n      | PBFTreplica n => PBFTreplicaSM n\n      | _ => MhaltedSM dummy_initial_state\n      end.\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(* 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   => \"Cstruct.t\".\nExtract Inlined Constant pbft_receiving_key => \"Cstruct.t\".\nExtract Inlined Constant pbft_lookup_replica_sending_key   => \"MacKeyFun.lookup_replica_key\".\nExtract Inlined Constant pbft_lookup_replica_receiving_key => \"MacKeyFun.lookup_replica_key\".\nExtract Inlined Constant pbft_lookup_client_sending_key    => \"MacKeyFun.lookup_client_key\".\nExtract Inlined Constant pbft_lookup_client_receiving_key  => \"MacKeyFun.lookup_client_key\".\n\nExtract Inlined Constant pbft_create_signature => \"MacKeyFun.sign_list\".\nExtract Inlined Constant pbft_verify_signature => \"MacKeyFun.verify_one\".\nExtract Inlined Constant pbft_token => \"Cstruct.t\".\nExtract Inlined Constant pbft_token_deq => \"(=)\".\nExtract Inlined Constant token2string => \"(fun t -> Batteries.String.to_list (Sexplib.Sexp.to_string (Cstruct.sexp_of_t (Obj.magic t))))\".\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\n\nExtraction \"PbftReplica.ml\" pbft_state2string lrun_sm MonoSimulationState2string PBFTdummySM local_replica.\n", "meta": {"author": "vrahli", "repo": "Velisarios", "sha": "6fb353b18610cd79210755fcc90123536c367aaa", "save_path": "github-repos/coq/vrahli-Velisarios", "path": "github-repos/coq/vrahli-Velisarios/Velisarios-6fb353b18610cd79210755fcc90123536c367aaa/runtime/PBFTsim_mac.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.29017636909969685}}
{"text": "(**\nCoLoR, a Coq library on rewriting and termination.\nSee the COPYRIGHTS and LICENSE files.\n\n- Adam Koprowski, 2004-09-06\n\nThis file provides an implementation of finite multisets using list\nrepresentation.\n*)\n\nSet Implicit Arguments.\n\nFrom Coq Require Import Permutation PermutSetoid Omega Multiset.\nFrom CoLoR Require Import LogicUtil RelExtras MultisetCore ListExtras.\n\nModule MultisetList (ES : Eqset_dec) <: MultisetCore with Module Sid := ES.\n\n  Module Export Sid := ES.\n\nSection Operations.\n\n  Definition Multiset := list A.\n\n  Definition empty : Multiset := nil.\n  Definition singleton a : Multiset := a :: nil.\n  Definition union := app (A:=A).\n  Definition meq := permutation eqA eqA_dec.\n\n  Definition mult := countIn eqA eqA_dec.\n  Definition rem := removeElem eqA eqA_dec.\n  Definition diff := removeAll eqA eqA_dec.\n\n  Definition intersection := inter_as_diff diff.\n\n  Definition fold_left := fun T : Type => List.fold_left (A := T) (B := A).\n\nEnd Operations.\n\n  Infix \"=mul=\" := meq (at level 70) : msets_scope.\n  Notation \"X <>mul Y\" := (~meq X Y) (at level 50) : msets_scope.\n  Notation \"{{ x }}\" := (singleton x) (at level 5) : msets_scope.\n  Infix \"+\" := union : msets_scope.\n  Infix \"-\" := diff : msets_scope.\n  Infix \"#\" := intersection (at level 50, left associativity) : msets_scope.\n  Infix \"/\" := mult : msets_scope.\n\n  Delimit Scope msets_scope with msets.\n  Open Scope msets_scope.\n  Bind Scope msets_scope with Multiset.\n\nSection ImplLemmas.\n\n  Lemma empty_empty : forall M, (forall x, x / M = 0) -> M = empty.\n\n  Proof.\n    intros M mulM; destruct M.\n    trivial.\n    absurd (a / (a::M) = 0).\n    simpl. destruct (eqA_dec a a); auto with sets.\n    auto.\n  Qed.\n\nEnd ImplLemmas.\n\nSection SpecConformation.\n\n  Lemma mult_eqA_compat : forall M x y, x =A= y -> x / M = y / M.\n\n  Proof.\n     induction M.\n     auto.\n     intros; simpl.\n     destruct (eqA_dec x a); destruct (eqA_dec y a); intros;\n       solve [ absurd (y =A= a); eauto with sets\n             | assert (x / M = y / M); auto ].\n  Qed.\n\n  Lemma mult_comp : forall l a,\n    a / l = multiplicity (list_contents eqA eqA_dec l) a.\n\n  Proof.\n    induction l.\n    auto.\n    intro a0; simpl.\n    destruct (eqA_dec a0 a); destruct (eqA_dec a a0); simpl;\n    rewrite <- (IHl a0); (reflexivity || absurd (a0 =A= a); auto with sets).\n  Qed.\n\n  Lemma multeq_meq : forall M N, (forall x, x / M = x / N) -> M =mul= N.\n\n  Proof.\n    unfold meq. intros M N mult_MN x. rewrite <- !mult_comp. exact (mult_MN x).\n  Qed.\n\n  Lemma meq_multeq : forall M N, M =mul= N -> forall x, x / M = x / N.\n\n  Proof.\n    unfold meq, permutation, Multiset.meq.\n    intros M N eqMN x. rewrite !mult_comp. exact (eqMN x).\n  Qed.\n\n  Lemma empty_mult : forall x, mult x empty = 0.\n\n  Proof. auto. Qed.\n\n  Lemma union_mult : forall M N x,\n                       (x/(M + N))%msets = ((x/M)%msets + (x/N)%msets)%nat.\n\n  Proof.\n    induction M; auto.\n    intros N x; simpl. destruct (eqA_dec x a); auto. rewrite IHM. auto.\n  Qed.\n\n  Lemma diff_empty_l : forall M, empty - M = empty.\n\n  Proof.\n    induction M; auto.\n  Qed.\n\n  Lemma diff_empty_r : forall M, M - empty = M.\n\n  Proof.\n    induction M; auto.\n  Qed.\n\n  Lemma mult_remove_in : forall x a M,\n    x =A= a -> (x / (rem a M))%msets = ((x / M)%msets - 1)%nat.\n\n  Proof.\n    induction M.\n    auto.\n    intro x_a.\n    simpl; destruct (eqA_dec x a0); destruct (eqA_dec a a0); \n      simpl; try solve [absurd (x =A= a); eauto with sets].\n    auto with arith.\n    destruct (eqA_dec x a0).\n    contr.\n    auto.\n  Qed.\n\n  Lemma mult_remove_not_in : forall M a x,\n    ~ x =A= a -> x / (rem a M) = x / M.\n\n  Proof.\n    induction M; intros.\n    auto.\n    simpl; destruct (eqA_dec a0 a).\n    destruct (eqA_dec x a);\n      solve [absurd (x =A= a); eauto with sets | trivial].\n    simpl; destruct (eqA_dec x a).\n    rewrite (IHM a0 x); trivial.\n    apply IHM; trivial.\n  Qed.\n\n  Lemma remove_perm_single : forall x a b M,\n   x / (rem a (rem b M)) = x / (rem b (rem a M)).\n\n  Proof.\n    intros x a b M.\n    case (eqA_dec x a); case (eqA_dec x b); intros x_b x_a.\n     (* x=b,  x=a *)\n    rewrite !mult_remove_in; trivial.\n     (* x<>b, x=a *)\n    rewrite mult_remove_in; trivial.\n    do 2 (rewrite mult_remove_not_in; trivial).\n    rewrite mult_remove_in; trivial.\n     (* x=b,  x<>a *)\n    rewrite mult_remove_not_in; trivial.\n    do 2 (rewrite mult_remove_in; trivial).\n    rewrite mult_remove_not_in; trivial.\n     (* x<>b, x<>a *)\n    rewrite !mult_remove_not_in; trivial.\n  Qed.\n\n  Lemma diff_mult_comp : forall x N M M',\n    M =mul= M' -> x / (M - N) = x / (M' - N).\n\n  Proof.\n    induction N.\n    intros; apply meq_multeq; trivial.\n    intros M M' MM'.\n    simpl.\n    apply IHN.\n    apply multeq_meq.\n    intro x'.\n    case (eqA_dec x' a).\n    intro xa; rewrite !mult_remove_in; trivial.\n    rewrite (meq_multeq MM'); trivial.\n    intro xna; rewrite !mult_remove_not_in; trivial.\n    apply meq_multeq; trivial.\n  Qed.\n\n  Lemma diff_perm_single : forall x a b M N, \n    x / (M - (a::b::N)) = x / (M - (b::a::N)).\n\n  Proof.\n    intros x a b M N.\n    simpl; apply diff_mult_comp.\n    apply multeq_meq.\n    intro x'; apply remove_perm_single.\n  Qed.\n\n  Lemma diff_perm : forall M N a x,\n    x / ((rem a M) - N) = x / (rem a (M - N)).\n\n  Proof.\n    intros M N; gen M; clear M.\n    induction N.\n    auto.\n    intros M b x.\n    change (rem b M - (a::N)) with (M - (b::a::N)).\n    rewrite diff_perm_single.\n    simpl; apply IHN.\n  Qed.\n\n  Lemma diff_mult_step_eq : forall M N a x,\n    x =A= a -> x / (rem a M - N) = ((x / (M - N))%msets - 1)%nat.\n\n  Proof.\n    intros M N a x x_a.\n    rewrite diff_perm.\n    rewrite mult_remove_in; trivial.\n  Qed.\n\n  Lemma diff_mult_step_neq : forall M N a x,\n    ~ x =A= a -> x / (rem a M - N) = x / (M - N).\n\n  Proof.\n    intros M N a x x_a.\n    rewrite diff_perm.\n    rewrite mult_remove_not_in; trivial.\n  Qed.\n \n  Lemma diff_mult : forall M N x,\n                      x / (M - N) = ((x / M)%msets - (x / N)%msets)%nat.\n\n  Proof.\n    induction N.\n     (* induction base *)\n    simpl; intros; omega.\n     (* induction step *)\n    intro x; simpl.\n    destruct (eqA_dec x a); simpl.\n     (* x = a *)\n    fold rem.\n    rewrite (diff_mult_step_eq M N e).\n    rewrite (IHN x).\n    omega.\n     (* x <> a *)\n    fold rem.\n    rewrite (diff_mult_step_neq M N n).\n    exact (IHN x).\n  Qed.\n\n  Definition intersection_mult := inter_as_diff_ok mult diff diff_mult.\n\n  Lemma singleton_mult_in : forall x y, x =A= y -> x / {{y}} = 1.\n\n  Proof.\n    intros; compute.\n    case (eqA_dec x y); [trivial | contr].\n  Qed.\n  \n  Lemma singleton_mult_notin : forall x y, ~x =A= y -> x / {{y}} = 0.\n\n  Proof.\n    intros; compute.\n    case (eqA_dec x y); [contr | trivial].\n  Qed.\n\n  Lemma rev_list_ind_type : forall P : Multiset -> Type,\n    P nil -> (forall a l, P (rev l) -> P (rev (a :: l))) -> forall l, P (rev l).\n\n  Proof.\n    induction l; auto.\n  Defined.\n\n  Lemma rev_ind_type : forall P : Multiset -> Type,\n    P nil -> (forall x l, P l -> P (l ++ x :: nil)) -> forall l, P l.\n\n  Proof.\n    intros.\n    gen (rev_involutive l).\n    intros E; rewrite <- E.\n    apply (rev_list_ind_type P).\n    auto.\n    simpl in |- *.\n    intros.\n    apply (X0 a (rev l0)).\n    auto.\n  Defined.\n\n  Lemma mset_ind_type : forall P : Multiset -> Type,\n    P empty -> (forall M a, P M -> P (union M {{a}})) -> forall M, P M.\n\n  Proof.\n    induction M as [| x M] using rev_ind_type.\n    exact X.\n    exact (X0 M x IHM).\n  Defined.\n \nEnd SpecConformation.\n\n  Hint Unfold meq \n\t      empty\n              singleton\n              mult\n              union\n              diff : multisets.\n\n  Hint Resolve mult_eqA_compat \n               meq_multeq\n               multeq_meq\n               empty_mult\n               union_mult\n               diff_mult\n               intersection_mult\n               singleton_mult_in\n               singleton_mult_notin : multisets.\n\n  Hint Rewrite empty_mult\n               union_mult\n\t       diff_mult\n\t       intersection_mult using trivial : multisets.\n\nEnd MultisetList.\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/CoLoR/Coq8.11/MultisetList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.2901763690996968}}
{"text": "Require Import CommonDefinitions.\n\nRequire Import Raft.\n\nSection StateMachineSafety.\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 state_machine_safety_host net :=\n    forall h h' e e',\n      commit_recorded net h e ->\n      commit_recorded net h' e' ->\n      eIndex e = eIndex e' ->\n      e = e'.\n\n  Definition state_machine_safety_nw net :=\n    forall h p t leaderId prevLogIndex prevLogTerm entries leaderCommit e,\n      In p (nwPackets net) ->\n      pBody p = AppendEntries t leaderId prevLogIndex prevLogTerm\n                              entries leaderCommit ->\n      t >= currentTerm (nwState net h) ->\n      commit_recorded net h e ->\n      (prevLogIndex > eIndex e \\/\n       (prevLogIndex = eIndex e /\\ prevLogTerm = eTerm e) \\/\n       eIndex e > maxIndex entries \\/\n       In e entries).\n\n  Definition state_machine_safety net :=\n    state_machine_safety_host net /\\ state_machine_safety_nw net.\n\n  Class state_machine_safety_interface : Prop :=\n    {\n      state_machine_safety_invariant :\n        forall net,\n          raft_intermediate_reachable net ->\n          state_machine_safety net\n    }.\n\nEnd StateMachineSafety.", "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/StateMachineSafetyInterface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.29015589628512356}}
{"text": "Require Import VerifiedVerifier.Machine.\nRequire Import VerifiedVerifier.Maps.\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 VerifiedVerifier.Coqlib.\nRequire Import Lia.\n\nDefinition is_heap_base_data (s : state) (i : data_ty) : BinarySet :=\nif (Nat.eqb i s.(heap_base)) then bottom else top.\n\nDefinition is_heap_bounded_data (s : state) (i : data_ty) : BinarySet :=\nif (ltb i (above_heap_guard_size s)) then bottom else top.\n\nDefinition is_cf_bounded_data (s : state) (i : data_ty) : BinarySet :=\nif (ltb i (List.length (program s).(Funs))) then bottom else top.\n\nDefinition is_globals_base_data (s : state) (i : data_ty) : BinarySet :=\nif (Nat.eqb i s.(globals_base)) then bottom else top.\n\nDefinition is_above_stack_bounded_data (s : state) (i : data_ty) : BinarySet :=\nif (Nat.eqb i (above_stack_guard_size s)) then bottom else top.\n\nDefinition is_below_stack_bounded_data (s : state) (i : data_ty) : BinarySet :=\nif (Nat.eqb i (below_stack_guard_size s)) then bottom else top.\n\nDefinition abstractify_data (s : state) (i : data_ty) : info :=\n{| is_heap_base := is_heap_base_data s i;\n   heap_bounded := is_heap_bounded_data s i;\n   cf_bounded := is_cf_bounded_data s i;\n   is_globals_base := is_globals_base_data s i;\n   above_stack_bounded := is_above_stack_bounded_data s i;\n   below_stack_bounded := is_below_stack_bounded_data s i;\n|}.\n\nDefinition abstractify_list (s : state) (l : list data_ty) : list info :=\n  map (abstractify_data s) l.\n\nDefinition abstractify_registers (s : state) (f : registers_ty) : abs_registers_ty :=\n  fun r => (abstractify_data s (f r)).\n\nDefinition abstractify (s : state) : abs_state :=\n{| abs_regs := abstractify_registers s s.(regs);\n   abs_stack := abstractify_list s s.(stack);\n   abs_lifted_state := sub_state;\n   abs_heap_base := (heap_base s);\n   abs_below_stack_guard_size := (below_stack_guard_size s);\n   abs_above_stack_guard_size := (above_stack_guard_size s);\n   abs_above_heap_guard_size := (above_heap_guard_size s);\n   abs_globals_size := (globals_size s);\n   abs_globals_base := (globals_base s);\n   abs_program := Some s.(program);\n   abs_frame_size := s.(frame_size);\n   abs_call_stack := s.(call_stack);\n   abs_rsp := get_register s rsp;\n   abs_stack_base := s.(stack_base);\n   abs_stack_size := s.(stack_size);\n   abs_max_stack_size := s.(max_stack_size);\n|}.\n\nLemma BinarySet_eqb_eq: forall a b,\n  BinarySet_eqb a b = true <-> a = b.\nProof.\n  intros. split.\n  - intros. unfold BinarySet_eqb in H. destruct (BinarySet_eq_dec a b) eqn:H'; auto; inversion H.\n  - intros. unfold BinarySet_eqb. inversion H. destruct (BinarySet_eq_dec b b); auto; inversion H.\nQed.\n\nLemma leq_abs_state_is_heap_base: forall abs_st abs_st' r,\n  leq_abs_state abs_st' abs_st ->\n  is_heap_base (get_register_info abs_st r) = bottom ->\n  is_heap_base (get_register_info abs_st' r) = bottom.\nProof.\n  intros abs_st abs_st' r Hleq H. inversion Hleq. auto. subst. inversion H. subst.\n  specialize H6 with r. inversion H6. rewrite H20. auto.\n  subst. inversion H18. auto. rewrite H in H18. inversion H18. auto.\nQed.\n\nLemma leq_abs_state_is_globals_base: forall abs_st abs_st' r,\n  leq_abs_state abs_st' abs_st ->\n  is_globals_base (get_register_info abs_st r) = bottom ->\n  is_globals_base (get_register_info abs_st' r) = bottom.\nProof.\n  intros abs_st abs_st' r Hleq H. inversion Hleq. auto. subst. inversion H. subst.\n  specialize H6 with r. inversion H6. rewrite H20. auto.\n  subst. inversion H21. auto. rewrite H in H21. inversion H21. auto.\nQed.\n\nLemma leq_abs_state_heap_bounded: forall abs_st abs_st' r,\n  leq_abs_state abs_st' abs_st ->\n  heap_bounded (get_register_info abs_st r) = bottom ->\n  heap_bounded (get_register_info abs_st' r) = bottom.\nProof.\n  intros abs_st abs_st' r Hleq H. inversion Hleq. auto. subst. inversion H. subst.\n  specialize H6 with r. inversion H6. rewrite H20. auto.\n  subst. inversion H19. auto. rewrite H in H19. inversion H19. auto.\nQed.\n\nLemma leq_abs_state_cf_bounded: forall abs_st abs_st' r,\n  leq_abs_state abs_st' abs_st ->\n  cf_bounded (get_register_info abs_st r) = bottom ->\n  cf_bounded (get_register_info abs_st' r) = bottom.\nProof.\n  intros abs_st abs_st' r Hleq H. inversion Hleq. auto. subst. inversion H. subst.\n  specialize H6 with r. inversion H6. rewrite H20. auto.\n  subst. inversion H20. auto. rewrite H in H20. inversion H20. auto.\nQed.\n\nLemma if_thn_true: forall (cond : bool),\n  (if cond then bottom else top) = bottom ->\n  cond = true.\nProof.\n  intros. destruct cond; auto; inversion H.\nQed.\n\nDefinition first_block f :=\nmatch (V f) with\n| nil => nil\n| h :: t => h\nend.\n\nDefinition run_function p f :=\n(first_block f, start_state p).\n\nLemma leq_abs_state_verifies : forall i abs_st abs_st',\n  leq_abs_state abs_st' abs_st ->\n  instr_class_verifier i abs_st = true ->\n  instr_class_verifier i abs_st' = true.\nProof.\n  intros i abs_st abs_st' Hleq Hv. inversion Hleq. auto. rewrite <- H0 in Hv. inversion Hv.\n  destruct i eqn:Hi; unfold instr_class_verifier in *; rewrite H0 in Hv; rewrite H; eauto.\n  - apply andb_prop in Hv as [Hbase Hv].\n    apply andb_prop in Hv as [Hindex Hoffset]. apply BinarySet_eqb_eq in Hbase. apply BinarySet_eqb_eq in Hindex.\n    apply BinarySet_eqb_eq in Hoffset. repeat (apply andb_true_intro; split; try (apply BinarySet_eqb_eq)).\n    + eapply leq_abs_state_is_heap_base. apply Hleq. auto.\n    + eapply leq_abs_state_heap_bounded. apply Hleq. auto.\n    + eapply leq_abs_state_heap_bounded. apply Hleq. auto.\n  - apply andb_prop in Hv as [Hbase Hv].\n    apply andb_prop in Hv as [Hindex Hoffset]. apply BinarySet_eqb_eq in Hbase. apply BinarySet_eqb_eq in Hindex.\n    apply BinarySet_eqb_eq in Hoffset. repeat (apply andb_true_intro; split; try (apply BinarySet_eqb_eq)).\n    + eapply leq_abs_state_is_heap_base. apply Hleq. auto.\n    + eapply leq_abs_state_heap_bounded. apply Hleq. auto.\n    + eapply leq_abs_state_heap_bounded. apply Hleq. auto.\n  - apply andb_prop in Hv. destruct Hv as [Hv1 Hv3]. apply PeanoNat.Nat.ltb_lt in Hv3.\n    apply andb_prop in Hv1. destruct Hv1 as [Hv1 Hv2].\n    apply PeanoNat.Nat.ltb_lt in Hv1. apply PeanoNat.Nat.ltb_lt in Hv2.\n    repeat (apply andb_true_intro; split; try (apply BinarySet_eqb_eq)); apply PeanoNat.Nat.ltb_lt.\n    + rewrite H2. rewrite H7. assumption.\n    + rewrite H12. rewrite H11. assumption.\n    + rewrite H11. rewrite H12. rewrite H13. assumption.\n  - apply andb_prop in Hv. destruct Hv as [Hv1 Hv3]. apply PeanoNat.Nat.ltb_lt in Hv3.\n    apply andb_prop in Hv1. destruct Hv1 as [Hv1 Hv2].\n    apply PeanoNat.Nat.ltb_lt in Hv1. apply PeanoNat.Nat.ltb_lt in Hv2.\n    repeat (apply andb_true_intro; split; try (apply BinarySet_eqb_eq)); apply PeanoNat.Nat.ltb_lt.\n    + rewrite H7. assumption.\n    + rewrite H12. rewrite H11. assumption.\n    + rewrite H11. rewrite H12. rewrite H14. assumption.\n  - apply andb_prop in Hv. destruct Hv as [Hv1 Hv2].\n    apply BinarySet_eqb_eq in Hv1. apply BinarySet_eqb_eq in Hv2.\n    repeat (apply andb_true_intro; split; try (apply BinarySet_eqb_eq)).\n    + specialize H5 with r. inversion H5.\n      * rewrite H21. assumption.\n      * inversion H21; auto.\n        rewrite Hv1 in H27. discriminate.\n    + specialize H5 with rdi. inversion H5.\n      * rewrite H21. assumption.\n      * inversion H19; auto.\n        rewrite Hv2 in H27. discriminate.\n  - apply andb_prop in Hv. destruct Hv as [Hv1 Hv2]. apply BinarySet_eqb_eq in Hv2.\n    repeat (apply andb_true_intro; split; try (apply BinarySet_eqb_eq)).\n    + unfold AbstractAnalysis.get_function in *. rewrite H8. assumption.\n    + specialize H5 with rdi. inversion H5.\n      * rewrite H21. assumption.\n      * inversion H19; auto.\n        rewrite Hv2 in H27. discriminate.\n  - apply andb_prop in Hv. destruct Hv as [Hv1 Hv2].\n    repeat (apply andb_true_intro; split).\n    + unfold get_bb. unfold AbstractAnalysis.get_function.\n      unfold get_bb in Hv1. unfold AbstractAnalysis.get_function in Hv1.\n      rewrite H8. rewrite H10. assumption.\n    + unfold get_bb. unfold AbstractAnalysis.get_function.\n      unfold get_bb in Hv2. unfold AbstractAnalysis.get_function in Hv2.\n      rewrite H8. rewrite H10. assumption.\n  - unfold get_bb in *. unfold AbstractAnalysis.get_function in *.\n    rewrite H8. rewrite H10. assumption.\n  - apply BinarySet_eqb_eq. apply BinarySet_eqb_eq in Hv.\n    eapply leq_abs_state_is_heap_base. eapply Hleq. auto.\n  - apply andb_prop in Hv. destruct Hv as [Hv1 Hv2]. apply BinarySet_eqb_eq in Hv1.\n    apply PeanoNat.Nat.ltb_lt in Hv2. apply andb_true_intro; split.\n    + apply BinarySet_eqb_eq. pose proof leq_abs_state_is_globals_base as Hglobal.\n      specialize Hglobal with abs_st abs_st' r.\n      apply Hglobal; auto.\n    + apply PeanoNat.Nat.ltb_lt. rewrite H15. auto.\n  - apply andb_prop in Hv. destruct Hv as [Hv1 Hv2]. apply BinarySet_eqb_eq in Hv1.\n    apply PeanoNat.Nat.ltb_lt in Hv2. apply andb_true_intro; split.\n    + apply BinarySet_eqb_eq. pose proof leq_abs_state_is_globals_base as Hglobal.\n      specialize Hglobal with abs_st abs_st' r.\n      apply Hglobal; auto.\n    + apply PeanoNat.Nat.ltb_lt. rewrite H15. auto.\nQed.\n\nLemma unfold_binaryset_eqb: forall b1 b2 b3 b4,\n  (BinarySet_eqb b1 b2 && BinarySet_eqb b3 b4)%bool = true ->\n  b1 = b2 /\\ b3 = b4.\nProof.\n  intros. apply andb_prop in H as [H1 H2].\n  apply BinarySet_eqb_eq in H1. apply BinarySet_eqb_eq in H2. auto.\nQed.\n\nLemma unfold_binaryset_eqb_3: forall b1 b2 b3 b4 b5 b6,\n  (BinarySet_eqb b1 b2 && BinarySet_eqb b3 b4 && BinarySet_eqb b5 b6)%bool = true ->\n  b1 = b2 /\\ b3 = b4 /\\ b5 = b6.\nProof.\n  intros. apply andb_prop in H as [H1 H2]. apply unfold_binaryset_eqb in H1 as [H1 H1'].\n  apply BinarySet_eqb_eq in H2. auto.\nQed.\n\nTheorem get_function_concrete_abstract :\n  forall s n f,\n    Semantics.get_function s n = Some f ->\n    AbstractAnalysis.get_function (abstractify s) n = Some f.\nProof.\n  intros. unfold AbstractAnalysis.get_function. unfold get_function in H.\n  unfold abstractify. unfold abs_program. apply H.\nQed.\n\nTheorem get_function_abstract_concrete :\n  forall s n f,\n    AbstractAnalysis.get_function (abstractify s) n = Some f ->\n    Semantics.get_function s n = Some f.\nProof.\n  intros. unfold AbstractAnalysis.get_function in H. unfold get_function.\n  unfold abstractify in H. unfold abs_program in H. apply H.\nQed.\n\nTheorem get_bb_abstract_concrete :\n  forall s n bb,\n    get_bb (abstractify s) n = Some bb ->\n    get_basic_block s n = Some bb.\nProof.\n  intros. unfold get_basic_block. unfold get_bb in H. unfold abstractify in H.\n  unfold abs_call_stack in H. unfold AbstractAnalysis.get_function in H.\n  unfold abs_program in H. unfold get_function. apply H.\nQed.\n\nLemma verified_impl_istep : forall i is st,\n  instr_class_verifier i.(instr) (abstractify st) = true ->\n  exists is' st', (i :: is) / st i--> is' / st'.\nProof.\n  intros. destruct i eqn:Hibase; destruct instr eqn:Hi; unfold instr_class_verifier in H; simpl in H.\n  - apply andb_prop in H as [Hbase Hv]. apply andb_prop in Hv as [Hindex Hoffset].\n    apply BinarySet_eqb_eq in Hbase. apply BinarySet_eqb_eq in Hindex.\n    apply BinarySet_eqb_eq in Hoffset.\n    remember ((get_register st r2) + (get_register st r1) + (get_register st r0)) as index.\n    remember (ltb index ((heap_base st) + (max_heap_size st))) as valid_index.\n    destruct valid_index.\n    + apply eq_sym, PeanoNat.Nat.ltb_lt in Heqvalid_index. repeat eexists. eapply I_Heap_Read.\n      apply Heqindex. unfold is_heap_base, get_register_info, abstractify in *. simpl in *.\n      unfold is_heap_base_data, is_heap_bounded_data in *.\n      apply if_thn_true, EqNat.beq_nat_true in Hbase. Search (_ <? _).\n      apply if_thn_true, PeanoNat.Nat.ltb_lt in Hindex. apply if_thn_true, PeanoNat.Nat.ltb_lt in Hoffset.\n      unfold get_register in *. lia. auto.\n    + Search (_ <? _). apply eq_sym, PeanoNat.Nat.ltb_nlt in Heqvalid_index. repeat eexists. eapply I_Heap_Read_Guard.\n      apply Heqindex. lia. unfold is_heap_base, get_register_info, abstractify in *. simpl in *.\n      unfold is_heap_base_data, is_heap_bounded_data in *.\n      apply if_thn_true, EqNat.beq_nat_true in Hbase. Search (_ <? _).\n      apply if_thn_true, PeanoNat.Nat.ltb_lt in Hindex. apply if_thn_true, PeanoNat.Nat.ltb_lt in Hoffset.\n      unfold get_register in *. pose proof (heap_size_eq_guard st) as H. lia.\n  - apply andb_prop in H as [Hbase Hv]. apply andb_prop in Hv as [Hindex Hoffset].\n    apply BinarySet_eqb_eq in Hbase. apply BinarySet_eqb_eq in Hindex.\n    apply BinarySet_eqb_eq in Hoffset.\n    remember ((get_register st r) + (get_register st r0) + (get_register st r1)) as index.\n    remember (ltb index ((heap_base st) + (max_heap_size st))) as valid_index.\n    destruct valid_index.\n    + apply eq_sym, PeanoNat.Nat.ltb_lt in Heqvalid_index. repeat eexists. eapply I_Heap_Write.\n      auto. unfold is_heap_base, get_register_info, abstractify in *. simpl in *.\n      unfold is_heap_base_data, is_heap_bounded_data in *.\n      apply if_thn_true, EqNat.beq_nat_true in Hbase. Search (_ <? _).\n      apply if_thn_true, PeanoNat.Nat.ltb_lt in Hindex. apply if_thn_true, PeanoNat.Nat.ltb_lt in Hoffset.\n      unfold get_register in *. lia. lia.\n    + Search (_ <? _). apply eq_sym, PeanoNat.Nat.ltb_nlt in Heqvalid_index. repeat eexists. eapply I_Heap_Write_Guard.\n      auto. lia. unfold is_heap_base, get_register_info, abstractify in *. simpl in *.\n      unfold is_heap_base_data, is_heap_bounded_data in *.\n      apply if_thn_true, EqNat.beq_nat_true in Hbase. Search (_ <? _).\n      apply if_thn_true, PeanoNat.Nat.ltb_lt in Hindex. apply if_thn_true, PeanoNat.Nat.ltb_lt in Hoffset.\n      unfold get_register in *. pose proof (heap_size_eq_guard st) as H. lia.\n  - repeat eexists. apply I_Heap_Check.\n  - destruct (get_register st r <? List.length (program st).(Funs)) eqn:valid_function.\n    + repeat eexists. eapply I_Call_Check. apply PeanoNat.Nat.ltb_lt. auto.\n    + repeat eexists. eapply I_Call_Check_Bad. apply PeanoNat.Nat.ltb_nlt in valid_function. apply Compare_dec.not_lt. auto.\n  - repeat eexists. apply I_Reg_Move.\n  - repeat eexists. apply I_Reg_Write.\n  - repeat eexists. apply I_Stack_Expand_Static.\n  - destruct (n + (stack_size st) <=? (max_stack_size st)) eqn:valid_expansion.\n    + repeat eexists. eapply I_Stack_Expand_Dynamic. Search (_ <=? _). apply Compare_dec.leb_complete. auto.\n    + repeat eexists. eapply I_Stack_Expand_Dynamic_Guard. apply Compare_dec.leb_complete_conv. auto.\n  - repeat eexists. apply I_Stack_Contract.\n  - repeat eexists. apply andb_prop in H. destruct H. apply andb_prop in H. destruct H.\n    apply PeanoNat.Nat.ltb_lt in H. apply PeanoNat.Nat.ltb_lt in H1. apply PeanoNat.Nat.ltb_lt in H0.\n    apply I_Stack_Read; auto.\n  - repeat eexists. apply andb_prop in H. destruct H. apply andb_prop in H. destruct H.\n    apply PeanoNat.Nat.ltb_lt in H. apply PeanoNat.Nat.ltb_lt in H1. apply PeanoNat.Nat.ltb_lt in H0.\n    apply I_Stack_Write; auto.\n  - repeat eexists. apply I_Op.\n  - apply andb_prop in H as [Hcf Hheap]. apply BinarySet_eqb_eq in Hcf. apply BinarySet_eqb_eq in Hheap.\n    unfold is_cf_bounded_data in Hcf. unfold is_heap_base_data in Hheap.\n    apply if_thn_true in Hcf. apply if_thn_true in Hheap. apply PeanoNat.Nat.ltb_lt in Hcf.\n    pose proof Coqlib.nth_error_lt as Hnth.\n    specialize Hnth with ControlFlowGraph (get_register st r) (Funs (program st)).\n    unfold get_register in Hnth. apply Hnth in Hcf. destruct Hcf.\n    repeat eexists. apply I_Indirect_Call. unfold get_function. apply H.\n  - apply andb_prop in H. destruct H.\n    destruct (AbstractAnalysis.get_function (abstractify st) n) eqn: Hget.\n    pose proof get_function_abstract_concrete as Habs.\n    specialize Habs with st n f. apply Habs in Hget.\n    repeat eexists. apply I_Direct_Call. apply Hget. inversion H.\n  - case (run_conditional st c) eqn:Hcond.\n    + apply andb_prop in H. destruct H. destruct (get_bb (abstractify st) l) eqn:Hget1; try inversion H.\n      destruct (get_bb (abstractify st) l0) eqn:Hget2; try inversion H0.\n      pose proof I_Branch_True. specialize H1 with st is c l l0 b b0 addr.\n      repeat eexists. apply H1; auto.\n    + apply andb_prop in H. destruct H. destruct (get_bb (abstractify st) l) eqn:Hget1; try inversion H.\n      destruct (get_bb (abstractify st) l0) eqn:Hget2; try inversion H0.\n      pose proof I_Branch_False. specialize H1 with st is c l l0 b b0 addr.\n      repeat eexists. apply H1; auto.\n  - destruct (get_bb (abstractify st) l) eqn: Hget; try inversion H.\n    pose proof get_bb_abstract_concrete as Habs.\n    specialize Habs with st l b. apply Habs in Hget.\n    repeat eexists. apply I_Jmp. apply Hget.\n  - apply BinarySet_eqb_eq in H. repeat eexists. eapply I_Get_Globals_Base.\n    unfold is_heap_base_data in H. destruct (regs st r =? heap_base st) eqn:Hbase.\n    + apply EqNat.beq_nat_true in Hbase. auto.\n    + discriminate.\n  - apply andb_prop in H as [Hbase Hindex]. apply BinarySet_eqb_eq in Hbase.\n    apply PeanoNat.Nat.ltb_lt in Hindex. repeat eexists. eapply I_Globals_Read.\n    unfold is_globals_base_data in Hbase. destruct (regs st r =? globals_base st) eqn:Hglobal.\n    + apply EqNat.beq_nat_true in Hglobal. auto.\n    + discriminate.\n    + auto.\n  - apply andb_prop in H as [Hbase Hindex]. apply BinarySet_eqb_eq in Hbase.\n    apply PeanoNat.Nat.ltb_lt in Hindex. repeat eexists. eapply I_Globals_Write.\n    unfold is_globals_base_data in Hbase. destruct (regs st r =? globals_base st) eqn:Hglobal.\n    + apply EqNat.beq_nat_true in Hglobal. auto.\n    + discriminate.\n    + auto.\n  - repeat eexists. apply I_Ret. apply EqNat.beq_nat_true in H. assumption.\nQed.\n\nLemma verified_program_impl_verified_function : forall p f,\n  program_verifier p (abstractify (start_state p)) = true ->\n  In f p.(Funs) ->\n  function_verifier f (abstractify (start_state p)) = true.\nProof.\n  intros. unfold program_verifier in H. rewrite forallb_forall in H.\n  specialize H with f. apply H. apply H0.\nQed.\n\n(* NOTE: This is, in general, a true statement about abstract analyses. It is\n   admitted here because we assume the abstract analysis is implemented\n   correctly and instead focus on proving facts about whether or not we have\n   enough information to guarantee sfi properties. *)\n(* TODO: update this to use the verifier fixpoint when we update the verifier\n   to associate fixpoints with functions. *)\nTheorem verifier_fixpoint_relation :\nforall i,\n  exists fixpoint,\n  forall p f is st fuel,\n    program_verifier p (abstractify (start_state p)) = true ->\n    In f p.(Funs) ->\n    imultistep_fuel ((run_function p f), fuel) (i :: is, st, 0) ->\n    (leq_abs_state (abstractify st) fixpoint /\\\n     instr_class_verifier i.(instr) fixpoint = true).\nAdmitted.\n\nTheorem verified_program_step :\n  forall p f fuel is1 st1,\n    program_verifier p (abstractify (start_state p)) = true ->\n    In f p.(Funs) ->\n    imultistep_fuel ((run_function p f), fuel) (is1, st1, 0) ->\n    exists is' st',\n      imultistep_fuel ((run_function p f), S fuel) (is', st', 0).\nProof.\n  intros.\n  unfold run_function. unfold run_function in H1.\n  pose proof imultistep_finish' as Hfinish.\n  destruct (first_block f) eqn:Hfirst.\n  - repeat eexists. constructor. apply IFuel_End.\n  - destruct is1 eqn:Hstream.\n    + exists nil. exists st1.\n      eapply imultistep_finish'. apply H1.\n      constructor. apply IFuel_End.\n    + pose proof verified_impl_istep as Hstep.\n      specialize Hstep with i0 l0 st1.\n      pose proof verifier_fixpoint_relation as Hfixpoint.\n      specialize Hfixpoint with i0. destruct Hfixpoint as [fixpoint Hfixpoint].\n      pose proof leq_abs_state_verifies as Hleq.\n      specialize Hleq with i0.(instr) fixpoint (abstractify st1).\n      specialize Hfixpoint with p f l0 st1 fuel.\n      apply Hfixpoint in H as [].\n      apply Hleq in H.\n      apply Hstep in H. rewrite <- Hstream in H. destruct H as []. destruct H as [].\n      eexists ?[is']. eexists ?[st'].\n      specialize Hfinish with fuel (first_block f) (start_state p) is1 st1 ?is' ?st'.\n      rewrite <- Hfirst. apply Hfinish. rewrite Hfirst. rewrite Hstream. apply H1.\n      constructor. apply IFuel_Step.\n      apply H.\n      auto. auto. auto.\n      unfold run_function. rewrite Hfirst. apply H1.\nQed.\n\nTheorem verified_program :\n  forall p f fuel,\n    program_verifier p (abstractify (start_state p)) = true ->\n    In f p.(Funs) ->\n    exists is' st',\n      imultistep_fuel ((run_function p f), fuel) (is', st', 0).\nProof.\n  intros. induction fuel.\n  - repeat eexists. constructor. apply IFuel_Base.\n  - destruct IHfuel. destruct H1.\n    eapply verified_program_step; auto.\n    eapply H1.\nQed.\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/Safety.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2901198522155667}}
{"text": "Require Import VST.floyd.proofauto.\nImport ListNotations.\nLocal Open Scope logic.\n\nRequire Import hmacdrbg.HMAC_DRBG_algorithms.\nRequire Import hmacdrbg.spec_hmac_drbg.\nRequire Import sha.HMAC256_functional_prog.\n\nFixpoint HMAC_DRBG_update_round (HMAC: list byte -> list byte -> list byte) (provided_data K V: list byte) (round: nat): (list byte * list byte) :=\n  match round with\n    | O => (K, V)\n    | S round' =>\n      let (K, V) := HMAC_DRBG_update_round HMAC provided_data K V round' in\n      let K := HMAC (V ++ [Byte.repr (Z.of_nat round')] ++ provided_data) K in\n      let V := HMAC V K in\n      (K, V)\n  end.\n\nDefinition HMAC_DRBG_update_concrete (HMAC: list byte -> list byte -> list byte) (provided_data K V: list byte): (list byte * list byte) :=\n  let rounds := match provided_data with\n                  | [] => 1%nat\n                  | _ => 2%nat\n                end in\n  HMAC_DRBG_update_round HMAC provided_data K V rounds.\n\nTheorem HMAC_DRBG_update_concrete_correct:\n  forall HMAC provided_data K V, HMAC_DRBG_update HMAC provided_data K V = HMAC_DRBG_update_concrete HMAC provided_data K V.\nProof.\n  intros.\n  destruct provided_data; reflexivity.\nQed.\n\nDefinition update_rounds (non_empty_additional: bool): Z :=\n  if non_empty_additional then 2 else 1.\n\nLemma HMAC_DRBG_update_round_incremental:\n  forall key V initial_state_abs contents n,\n    (key, V) = HMAC_DRBG_update_round HMAC256 contents\n                           (hmac256drbgabs_key initial_state_abs)\n                           (hmac256drbgabs_value initial_state_abs) n ->\n    (HMAC256 (V ++ Byte.repr (Z.of_nat n) :: contents) key,\n     HMAC256 V (HMAC256 (V ++ Byte.repr (Z.of_nat n) :: contents) key)) =\n    HMAC_DRBG_update_round HMAC256 contents\n                           (hmac256drbgabs_key initial_state_abs)\n                           (hmac256drbgabs_value initial_state_abs) (n + 1).\nProof.\n  intros.\n  rewrite Nat.add_comm.\n  simpl.\n  rewrite <- H.\n  reflexivity.\nQed.\n\nLemma HMAC_DRBG_update_round_incremental_Z:\n  forall key V initial_state_abs contents i,\n    0 <= i ->\n    (key, V) = HMAC_DRBG_update_round HMAC256 contents\n                           (hmac256drbgabs_key initial_state_abs)\n                           (hmac256drbgabs_value initial_state_abs) (Z.to_nat i) ->\n    (HMAC256 (V ++ Byte.repr i :: contents) key,\n     HMAC256 V (HMAC256 (V ++ Byte.repr i :: contents) key)) =\n    HMAC_DRBG_update_round HMAC256 contents\n                           (hmac256drbgabs_key initial_state_abs)\n                           (hmac256drbgabs_value initial_state_abs) (Z.to_nat (i + 1)).\nProof.\n  intros.\n  specialize (HMAC_DRBG_update_round_incremental _ _ _ _ _ H0); intros. clear H0.\n  rewrite (Z2Nat.id _ H) in H1.\n  rewrite Z2Nat.inj_add; try assumption; lia.\nQed.\n\nLemma update_char add_len contents (HL:add_len = Zlength contents \\/ add_len = 0)\n       (key1 V0 : list byte) additional reseed_counter entropy_len prediction_resistance V key0\n     reseed_interval\n    (H : (key1, V0) =\n    HMAC_DRBG_update_round HMAC256 (contents_with_add additional add_len contents) key0 V\n      (Z.to_nat\n         (if\n           (negb (EqDec_val additional nullval) &&\n            negb (EqDec_Z add_len 0))%bool\n          then 2\n          else 1))):\nhmac256drbgabs_hmac_drbg_update\n  (HMAC256DRBGabs key0 V reseed_counter entropy_len prediction_resistance\n     reseed_interval) (contents_with_add additional add_len contents) =\nHMAC256DRBGabs key1 V0 reseed_counter entropy_len prediction_resistance\n  reseed_interval.\nProof. rename key0 into K. rename V0 into VV. rename key1 into KK.\nunfold hmac256drbgabs_hmac_drbg_update, HMAC256_DRBG_functional_prog.HMAC256_DRBG_update.\nrewrite HMAC_DRBG_update_concrete_correct. unfold HMAC_DRBG_update_concrete, contents_with_add in *; simpl in *.\ndestruct (EqDec_val additional nullval); simpl in *.\n+ inv H; trivial.\n+ destruct (EqDec_Z add_len 0).\n  -  subst add_len. change (negb (left eq_refl)) with false in *. \n     simpl in H. inv H; trivial.\n  - change (negb (right n0)) with true in *. simpl.\n    destruct HL; try lia; subst add_len.\n    destruct contents. rewrite Zlength_nil in n0; lia. \n    change  (Z.to_nat 2) with 2%nat in H.\n    rewrite <- H; 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/hmacdrbg/verif_hmac_drbg_update_common.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2901159572281896}}
{"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 reset_last_run_info_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 g' := gn {grec: (grec gn) {g_esr: 0}} in\n    Some adt {share: (share adt) {gs: (gs (share adt)) # gidx == g'}}.\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/RunAux/Specs/reset_last_run_info.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804478040617, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2900784738701338}}
{"text": "Require compcert.cfrontend.ClightBigstep.\nRequire EventsX.\n\nImport Coqlib.\nImport AST.\nImport Globalenvs.\nImport EventsX.\nImport Ctypes.\nImport Clight.\nExport ClightBigstep.\n\nRequire Import ClightX.\n\nSection WITHCONFIG.\nContext `{external_calls_prf: ExternalCalls}.\n\nInductive bigstep_function_terminates' function_entry p i sg vargs (m: mem) t : Values.val * mem -> Prop :=\n  | bigstep_function_terminates_intro b f targs tres cc vres m':\n      let ge := Clight.globalenv p in\n      Genv.find_symbol ge i = Some b ->\n      Genv.find_funct_ptr ge b = Some f ->\n      type_of_fundef f = Tfunction targs tres cc ->\n      sg = signature_of_type targs tres cc ->\n      eval_funcall ge function_entry m f vargs t m' vres ->\n      bigstep_function_terminates' function_entry p i sg vargs m t (vres,  m').\n\nDefinition bigstep_function_terminates2 := bigstep_function_terminates' function_entry2.\n\nInductive bigstep_function_diverges' function_entry (p: program) i sg vargs m: traceinf -> Prop :=\n  | bigstep_function_diverges_intro: forall b f targs tres cc t,\n      let ge := globalenv p in\n      Genv.find_symbol ge i = Some b ->\n      Genv.find_funct_ptr ge b = Some f ->\n      type_of_fundef f = Tfunction targs tres cc ->\n      sg = signature_of_type targs tres cc ->\n      evalinf_funcall ge function_entry m f vargs t ->\n      bigstep_function_diverges' function_entry p i sg vargs m t.\n\nDefinition bigstep_function_diverges2 := bigstep_function_diverges' function_entry2.\n\nDefinition bigstep_function_semantics2 (p: program) i sg vargs m :=\n  Smallstep.Bigstep_semantics\n    (bigstep_function_terminates2 p i sg vargs m)\n    (bigstep_function_diverges2 p i sg vargs m).\n\nTheorem bigstep_function_semantics_sound prog i (sg: AST.signature) (vargs: list Values.val) m:\n  Smallstep.bigstep_sound\n    (bigstep_function_semantics2 prog i sg vargs m)\n    (ClightX.semantics prog i m sg vargs).\nProof.\n  constructor; simpl; intros.\n(* termination *)\n  inv H. econstructor; econstructor.\n  split. econstructor; eauto.\n  split. eapply eval_funcall_steps. eauto. red; auto.\n  econstructor.\n(* divergence *)\n  inv H. econstructor.\n  split. econstructor; eauto.\n  eapply Smallstep.forever_N_forever with (order := order).\n  red; intros. constructor; intros. red in H. elim H.\n  eapply evalinf_funcall_forever; eauto.\nQed.\n\n\nEnd WITHCONFIG.\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/cfrontend/ClightBigstepX.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.29007846727883835}}
{"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(***** In this first part of the proof we replace n0 with a fresh n0'*****)\n(***** on both sides using CCA2 security of encryption with public *******)\n(***** key pkS of the mixer **********************************************)\n(*************************************************************************)\n\n\n(* We use a lot of functions defined in definitions.v to make the terms manageable. \n   Also note that ((τ1 (fFΦ2 c0 c1 x0)) ≟ x0) or ((τ2 (fFΦ2 c0 c1 x0)) ≟ x0 or ((τ3 (fFΦ2 c0 c1 x0)) ≟ x0) expresses that the ballot of the first voter was not replaced,\n   the negation of which is the guard of Lemma25 *)\n\n(* The actual statement of Lemma25 is at the end *)\n\n\n\n(* In the next proposition we show that the terms with \"Fiv\" and \"Fv\" are equal.\n   Fiv inserts the if-then-else terms in front of the decrytions of the voting phase that is necessary for the CCA2 axiom. *)\n\nLemma lemma25_CCA2Game1n:\n  forall side n m0, ContextTerm General Term (fun _ : ToL Term => m0) ->\n   (fun c0 c1 => (fun x0 => (fun v1 v2 v3 => If  ((τ1 (fFΦ2 c0 c1 x0)) ≟ x0)  or ((τ2 (fFΦ2 c0 c1 x0)) ≟ x0)  or ((τ3 (fFΦ2 c0 c1 x0)) ≟ x0)\n                                    Then ⫠\n                                    Else (＜＜ x0 ,                  (e1 c0 c1 n1),         (dv v1 v2 v3 (s c0 c1 v1 v2 v3) ) ＞,\n                                           ＜ Fl0 c0 c1 x0 v1 v2 v3, Fl1 c0 c1 x0 v1 v2 v3, (Fido c0 c1 x0 v1 v2 v3 n0)＞＞)\n             ) (Fiv1 c0 c1 x0 m0) (Fiv2 c0 c1 x0 m0) (Fiv3 c0 c1 x0 m0)\n  ) (e0 c0 c1 n)) (c0 side) (c1 side)\n=\n  (fun c0 c1 => (fun x0 => (fun v1 v2 v3 => If  ((τ1 (fFΦ2 c0 c1 x0)) ≟ x0)  or ((τ2 (fFΦ2 c0 c1 x0)) ≟ x0)  or ((τ3 (fFΦ2 c0 c1 x0)) ≟ x0)\n                                    Then ⫠\n                                    Else (＜＜ x0 ,               (e1 c0 c1 n1),            (dv v1 v2 v3 (s c0 c1 v1 v2 v3) ) ＞,\n                                           ＜ Fl0 c0 c1 x0 v1 v2 v3, Fl1 c0 c1 x0 v1 v2 v3, (Fido c0 c1 x0 v1 v2 v3 n0)＞＞)\n             ) (Fv1 c0 c1 x0) (Fv2 c0 c1 x0) (Fv3 c0 c1 x0)\n  ) (e0 c0 c1 n)) (c0 side) (c1 side).\nProof.\n  intros.\n  rewrite (OrComp) at 1.\n  unfold Fiv1.\n  rewrite (@If_eval (fun _ => _) (fun b1 => If _ Then ⫠ Else If _ Then ⫠\n            Else (＜ ＜ _, _,  dv (If b1 Then _ Else If b1 Then _ Else _) _ _ (s _ _ (If b1 Then _ Else If b1 Then _ Else _) _ _) ＞,\n                  ＜ Fl0 _ _ _ (If b1 Then _ Else If b1 Then _ Else _) _ _,\n                     Fl1 _ _ _ (If b1 Then _ Else If b1 Then _ Else _) _ _,\n                     Fido _ _ _ (If b1 Then _ Else If b1 Then _ Else _) _ _ _ ＞ ＞) )_ ).\n  rewrite If_false. rewrite If_false.\n\n  unfold Fiv2.\n  rewrite (@If_eval (fun _ => _) (fun b2 => If _ Then ⫠\n            Else (＜ ＜ _, _,  dv _ (If b2 Then _ Else If b2 Then _ Else _) _ (s _ _ _ (If b2 Then _ Else If b2 Then _ Else _) _) ＞,\n                  ＜ Fl0 _ _ _ _ (If b2 Then _ Else If b2 Then _ Else _)  _,\n                     Fl1 _ _ _ _ (If b2 Then _ Else If b2 Then _ Else _)  _,\n                     Fido _ _ _ _ (If b2 Then _ Else If b2 Then _ Else _) _ _ ＞ ＞) )_ ).\n  rewrite If_false. rewrite If_false.\n\n  unfold Fiv3.\n  rewrite (@If_eval (fun _ => _) (fun b3 => (＜ ＜ _, _,  dv _ _ (If b3 Then _ Else If b3 Then _ Else _) (s _ _ _ _ (If b3 Then _ Else If b3 Then _ Else _) ) ＞,\n                  ＜ Fl0 _ _ _ _ _ (If b3 Then _ Else If b3 Then _ Else _),\n                     Fl1 _ _ _ _ _ (If b3 Then _ Else If b3 Then _ Else _),\n                     Fido _ _ _ _ _ (If b3 Then _ Else If b3 Then _ Else _) _ ＞ ＞) )_ ).\n  rewrite If_false. rewrite If_false.\n\n  rewrite <- OrComp.\n  reflexivity.\n\n(*  *)\n  1,3,4,6,7,9: ProveboolandContext.\n  apply lemma25_game1n_context1. auto. \n  apply lemma25_game1n_context2. auto.\n  apply lemma25_game1n_context3. auto.\nQed.\n\n\n\n\n(* In the next two propositions we show that the terms with \"Fido\" and \"Fdo\" are equal. *)\n\n(* Lemma25_CCA2Game2n_helper expresses that if the ballot of the first voter was sent in the OPENING phase, the shuffle will not be published due to the phase check.\n   This shows the protocol could prevent replay attack. *)\n\nLemma lemma25_CCA2Game2n_helper:\n  forall side n n0,\n  (fun c0 c1 => (fun x0 => (fun v1 v2 v3 => If  ((τ1 (fFΦ2 c0 c1 x0)) ≟ x0)  or ((τ2 (fFΦ2 c0 c1 x0)) ≟ x0)  or ((τ3 (fFΦ2 c0 c1 x0)) ≟ x0)\n                                    Then ⫠\n                                    Else (＜＜ x0 ,               (e1 c0 c1 n1),            (dv v1 v2 v3 (s c0 c1 v1 v2 v3) ) ＞,\n                                           ＜ Fl0 c0 c1 x0 v1 v2 v3, Fl1 c0 c1 x0 v1 v2 v3, (Fido c0 c1 x0 v1 v2 v3 n0)＞＞)\n             ) (Fv1 c0 c1 x0) (Fv2 c0 c1 x0) (Fv3 c0 c1 x0)\n   ) (e0 c0 c1 n)) (c0 side) (c1 side)\n =\n  (fun c0 c1 => (fun x0 => (fun v1 v2 v3 => If ((τ1 (fFΦ2 c0 c1 x0)) ≟ x0)  or ((τ2 (fFΦ2 c0 c1 x0)) ≟ x0)  or ((τ3 (fFΦ2 c0 c1 x0)) ≟ x0) Then ⫠\n                              Else If ((τ1 (fFΦ5 c0 c1 x0 v1 v2 v3)) ≟ x0)\n                                   or ((τ2 (fFΦ5 c0 c1 x0 v1 v2 v3)) ≟ x0)\n                                   or ((τ3 (fFΦ5 c0 c1 x0 v1 v2 v3)) ≟ x0)\n       Then (＜＜ x0 , (e1 c0 c1 n1), (dv v1 v2 v3 (s c0 c1 v1 v2 v3)) ＞, ＜ Fl0 c0 c1 x0 v1 v2 v3, Fl1 c0 c1 x0 v1 v2 v3,   ⫠   ＞＞)\n       Else (＜＜ x0 , (e1 c0 c1 n1), (dv v1 v2 v3 (s c0 c1 v1 v2 v3)) ＞, ＜ Fl0 c0 c1 x0 v1 v2 v3, Fl1 c0 c1 x0 v1 v2 v3, (Fdo c0 c1 x0 v1 v2 v3) ＞ ＞)\n            ) (Fv1 c0 c1 x0) (Fv2 c0 c1 x0) (Fv3 c0 c1 x0)\n   ) (e0 c0 c1 n)) (c0 side) (c1 side).\nProof.\n  intros. simpl.\n  pose (lemma25_game2n_fFΦ3 side n) as ee.\n  pose (lemma25_game2n_fFΦ5 side n) as eee.\n  unfold Fido. unfold pchko.\n  rewrite Tau1Tri, Tau2Tri, Tau3Tri. (*  *)\n  unfold Fio1 at 2. rewrite decSimpl.\n  unfold Fio2 at 2. rewrite decSimpl.\n  unfold Fio3 at 2. rewrite decSimpl.\n  repeat rewrite (@If_morph (fun x => ph3 ≟ (π2 x)) _ _).\n  unfold m0. rewrite proj2pair. rewrite ph2Neqph3.\n  rewrite AndGuard.\n  rewrite (@If_morph (fun x => (＜ ＜ _ , _ , _ ＞, ＜ _, _, If _ & x & _ Then _ Else ⫠ ＞ ＞))).\n  rewrite If_false. rewrite If_same. rewrite If_false.\n  rewrite (@If_morph (fun x => (＜ ＜ _ , _ , _ ＞, ＜ _, _, If _ & x & _ Then _ Else ⫠ ＞ ＞))).\n  rewrite If_false. rewrite If_same. rewrite If_false.\n  rewrite (@If_morph (fun x => (＜ ＜ _ , _ , _ ＞, ＜ _, _, If _ & x & _ Then _ Else ⫠ ＞ ＞))).\n  rewrite If_false. rewrite If_same. rewrite If_false.\n\n  unfold Fio1.\n  rewrite (@If_eval (fun _ => _) (fun b1 => If _ Then _ Else If _ Then _\n                 Else (＜ ＜ _, _, _ ＞,\n                       ＜ _, _,\n                       If dist (If b1 Then _ Else If b1 Then Error Else _) _ _ & (_ & _ & _) &\n                          isinkc kc0 kc1 (＜ π2 (π1 (If b1 Then _ Else If b1 Then Error Else _)),  π2 (π1 _), π2 (π1 _) ＞)\n                       Then shufl (π1 (If b1 Then _ Else If b1 Then Error Else _)) (π1 _) (π1 _) Else ⫠ ＞ ＞))).\n  rewrite If_false. rewrite If_false.\n\n  unfold Fio2.\n  rewrite (@If_eval (fun _ => _) (fun b2 => If _ Then _ Else\n                      (＜ ＜ _, _, _ ＞,\n                       ＜ _, _,\n                       If dist _ (If b2 Then _ Else If b2 Then Error Else _) _ & (_ & _ & _) &\n                          isinkc kc0 kc1 (＜ π2 (π1 _), π2 (π1 (If b2 Then _ Else If b2 Then Error Else _)),  π2 (π1 _) ＞)\n                       Then shufl (π1 _) (π1 (If b2 Then _ Else If b2 Then Error Else _)) (π1 _) Else ⫠ ＞ ＞))).\n  rewrite If_false. rewrite If_false.\n\n  unfold Fio3.\n  rewrite (@If_eval (fun _ => _) (fun b3 => (＜ ＜ _, _, _ ＞,\n                       ＜ _, _,\n                       If dist _ _ (If b3 Then _ Else If b3 Then Error Else _) & (_ & _ & _) &\n                          isinkc kc0 kc1 (＜ π2 (π1 _), π2 (π1 _), π2 (π1 (If b3 Then _ Else If b3 Then Error Else _)) ＞)\n                       Then shufl (π1 _) (π1 _) (π1 (If b3 Then _ Else If b3 Then Error Else _)) Else ⫠ ＞ ＞))).\n  rewrite If_false. rewrite If_false.\n  rewrite <- OrComp.\n\n(* right hand side *)\n  unfold Fdo. unfold pchko. rewrite Tau1Tri, Tau2Tri, Tau3Tri.\n  reflexivity.\n\n  time (destruct side; simpl;  ProveboolandContext).\n  time (destruct side; simpl;  ProveboolandContext).\n  time (destruct side; simpl;  ProveboolandContext).\n  time (destruct side; simpl;  ProveboolandContext).\n  time (destruct side; simpl;  ProveboolandContext).\n  time (destruct side; simpl;  ProveboolandContext).\n  time (destruct side; simpl;  ProveboolandContext).\n  time (destruct side; simpl;  ProveboolandContext).\n  time (destruct side; simpl;  ProveboolandContext).\n  time (destruct side; simpl;  ProveboolandContext).\n  time (destruct side; simpl;  ProveboolandContext).\n  time (destruct side; simpl;  ProveboolandContext).\n  time (destruct side; simpl;  ProveboolandContext).\n  time (destruct side; simpl;  ProveboolandContext).\n  time (destruct side; simpl;  ProveboolandContext).\n  time (destruct side; simpl;  ProveboolandContext).\n  time (destruct side; simpl;  ProveboolandContext).\n  time (destruct side; simpl;  ProveboolandContext).\n  time (destruct side; simpl;  ProveboolandContext).\n  time (destruct side; simpl;  ProveboolandContext).\n  time (destruct side; simpl;  ProveboolandContext).\n  time (destruct side; simpl;  ProveboolandContext).\n  time (destruct side; simpl;  ProveboolandContext).\n  time (destruct side; simpl;  ProveboolandContext).\nQed.\n\n                                \n(* Lemma25_CCA2Game2n expresses that the terms with \"Fido\" and \"Fdo\" are equal.\n   Fido again inserts the if-then-else terms in front of the decrytions of the opening phase that is necessary for the CCA2 axiom. *)\n\nLemma lemma25_CCA2Game2n:\n  forall side n n0,\n  (fun c0 c1 => (fun x0 => (fun v1 v2 v3 => If  ((τ1 (fFΦ2 c0 c1 x0)) ≟ x0)  or ((τ2 (fFΦ2 c0 c1 x0)) ≟ x0)  or ((τ3 (fFΦ2 c0 c1 x0)) ≟ x0)\n                                    Then ⫠\n                                    Else (＜＜ x0 ,               (e1 c0 c1 n1),            (dv v1 v2 v3 (s c0 c1 v1 v2 v3) ) ＞,\n                                           ＜ Fl0 c0 c1 x0 v1 v2 v3, Fl1 c0 c1 x0 v1 v2 v3, (Fido c0 c1 x0 v1 v2 v3 n0)＞＞)\n             ) (Fv1 c0 c1 x0) (Fv2 c0 c1 x0) (Fv3 c0 c1 x0)\n   ) (e0 c0 c1 n)) (c0 side) (c1 side)\n =\n  (fun c0 c1 => (fun x0 => (fun v1 v2 v3 => If  ((τ1 (fFΦ2 c0 c1 x0)) ≟ x0)  or ((τ2 (fFΦ2 c0 c1 x0)) ≟ x0)  or ((τ3 (fFΦ2 c0 c1 x0)) ≟ x0)\n                                    Then ⫠\n                                    Else (＜＜ x0 ,               (e1 c0 c1 n1),            (dv v1 v2 v3 (s c0 c1 v1 v2 v3) ) ＞,\n                                           ＜ Fl0 c0 c1 x0 v1 v2 v3, Fl1 c0 c1 x0 v1 v2 v3, (Fdo c0 c1 x0 v1 v2 v3 )＞＞) (**)\n             ) (Fv1 c0 c1 x0) (Fv2 c0 c1 x0) (Fv3 c0 c1 x0)\n  ) (e0 c0 c1 n)) (c0 side) (c1 side).\nProof.\n  intros; simpl.\n  unfold Fdo.\n\n  assert ( let c0 := (c0 side) in let c1 := (c1 side) in\n            (Fo1 c0 c1 (e0 c0 c1 n) (Fv1 c0 c1 (e0 c0 c1 n)) (Fv2 c0 c1 (e0 c0 c1 n)) (Fv3 c0 c1 (e0 c0 c1 n)))\n          = (Fio1 c0 c1 (e0 c0 c1 n) (Fv1 c0 c1 (e0 c0 c1 n)) (Fv2 c0 c1 (e0 c0 c1 n)) (Fv3 c0 c1 (e0 c0 c1 n)) n)) as H.\n    apply (decIfThenElse (m0 (c0 side) (c1 side) n) 7\n           (τ1 (fFΦ5 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n) (Fv1 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n))\n               (Fv2 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n)) (Fv3 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n))))).\n    rewrite H; clear H.\n\n  assert ( let c0 := (c0 side) in let c1 := (c1 side) in\n            (Fo2 c0 c1 (e0 c0 c1 n) (Fv1 c0 c1 (e0 c0 c1 n)) (Fv2 c0 c1 (e0 c0 c1 n)) (Fv3 c0 c1 (e0 c0 c1 n)))\n          = (Fio2 c0 c1 (e0 c0 c1 n) (Fv1 c0 c1 (e0 c0 c1 n)) (Fv2 c0 c1 (e0 c0 c1 n)) (Fv3 c0 c1 (e0 c0 c1 n)) n)) as H.\n    apply (decIfThenElse (m0 (c0 side) (c1 side) n) 7\n           (τ2 (fFΦ5 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n) (Fv1 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n))\n               (Fv2 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n)) (Fv3 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n))))).\n    rewrite H; clear H.\n\n  assert ( let c0 := (c0 side) in let c1 := (c1 side) in\n            (Fo3 c0 c1 (e0 c0 c1 n) (Fv1 c0 c1 (e0 c0 c1 n)) (Fv2 c0 c1 (e0 c0 c1 n)) (Fv3 c0 c1 (e0 c0 c1 n)))\n          = (Fio3 c0 c1 (e0 c0 c1 n) (Fv1 c0 c1 (e0 c0 c1 n)) (Fv2 c0 c1 (e0 c0 c1 n)) (Fv3 c0 c1 (e0 c0 c1 n)) n)) as H.\n    apply (decIfThenElse (m0 (c0 side) (c1 side) n) 7\n           (τ3 (fFΦ5 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n) (Fv1 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n))\n               (Fv2 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n)) (Fv3 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n))))).\n    rewrite H; clear H.\n\n(**)\n  rewrite (lemma25_CCA2Game2n_helper side n n0).\n(**)\n  pose (lemma25_CCA2Game2n_helper side n n) as H.\n    unfold Fido in H. rewrite H; clear H.\n\n  reflexivity.\nQed.\n\n\n(* Now we are ready to use the CCA2 axiom and replace n0 with n0' *)\n\nProposition prop25_replace_n0_with_n0': forall side,\n  (| ＜ pv0 (c0 side) (c1 side) n0, ph2 ＞ |) = (| ＜ pv0 (c0 side) (c1 side) n0', ph2 ＞ |) ->\n  (fun c0 c1 => (fun x0 => (fun v1 v2 v3 => [b0 c0; b1 c1; (If ((acc0 c0 c1) & (acc1 c0 c1)) Then\n                                   (If ((τ1 (fFΦ2 c0 c1 x0)) ≟ x0)  or ((τ2 (fFΦ2 c0 c1 x0)) ≟ x0)  or ((τ3 (fFΦ2 c0 c1 x0)) ≟ x0)\n                                    Then ⫠\n                                    Else (＜＜ x0 ,               (e1 c0 c1 n1),            (dv v1 v2 v3 (s c0 c1 v1 v2 v3) ) ＞,\n                                           ＜ Fl0 c0 c1 x0 v1 v2 v3, Fl1 c0 c1 x0 v1 v2 v3, (Fdo c0 c1 x0 v1 v2 v3 )＞＞)) Else ⫠)] (**)\n             ) (Fv1 c0 c1 x0) (Fv2 c0 c1 x0) (Fv3 c0 c1 x0)\n  ) (e0 c0 c1 n0)) (c0 side) (c1 side)\n  ~\n  (fun c0 c1 => (fun x0 => (fun v1 v2 v3 => [b0 c0; b1 c1; (If ((acc0 c0 c1) & (acc1 c0 c1)) Then\n                                   (If  ((τ1 (fFΦ2 c0 c1 x0)) ≟ x0)  or ((τ2 (fFΦ2 c0 c1 x0)) ≟ x0)  or ((τ3 (fFΦ2 c0 c1 x0)) ≟ x0)\n                                    Then ⫠\n                                    Else (＜＜ x0 ,               (e1 c0 c1 n1),            (dv v1 v2 v3 (s c0 c1 v1 v2 v3) ) ＞,\n                                           ＜ Fl0 c0 c1 x0 v1 v2 v3, Fl1 c0 c1 x0 v1 v2 v3, (Fdo c0 c1 x0 v1 v2 v3 )＞＞)) Else ⫠)] (**)\n             ) (Fv1 c0 c1 x0) (Fv2 c0 c1 x0) (Fv3 c0 c1 x0)\n  ) (e0 c0 c1 n0')) (c0 side) (c1 side).\nProof.\n(* Here using lemma25_CCA2Game1n and lemma25_CCA2Game2n to rewrite the term will ensure the context CCA2 applicable. \n   Then we will use CCA2 to replace the nonce n0 with n0'. *)\n  intros side. intros.\n  simpl.\n\n  rewrite <- (lemma25_CCA2Game2n side n0 n0).\n  rewrite <- (lemma25_CCA2Game1n side n0 (＜ pv0 (c0 side) (c1 side) n0, ph2 ＞)).\n\n(* Φ6[x, pv01] is (pkS, rd0, pv00, pv00') −- CCA2 compliant. pkS := nonce 6, rd0 := nonce 7 *)\n  pose (cca2 [nonce 6] [nonce 7]\n             (fun x0 => (fun c0 c1 => (fun v1 v2 v3 => [b0 c0; b1 c1; (If ((acc0 c0 c1) & (acc1 c0 c1)) Then\n                                    If  ((τ1 (fFΦ2 c0 c1 x0)) ≟ x0)  or ((τ2 (fFΦ2 c0 c1 x0)) ≟ x0)  or ((τ3 (fFΦ2 c0 c1 x0)) ≟ x0)\n                                    Then ⫠\n                                    Else (＜＜ x0 ,                  (e1 c0 c1 n1),         (dv v1 v2 v3 (s c0 c1 v1 v2 v3) ) ＞,\n                                           ＜ Fl0 c0 c1 x0 v1 v2 v3, Fl1 c0 c1 x0 v1 v2 v3, (Fido c0 c1 x0 v1 v2 v3 n0)＞＞) Else ⫠\n             )]) (Fiv1 c0 c1 x0 (m0 c0 c1 n0)) (Fiv2 c0 c1 x0 (m0 c0 c1 n0)) (Fiv3 c0 c1 x0 (m0 c0 c1 n0))) (c0 side) (c1 side))\n             (＜ pv0 (c0 side) (c1 side) n0, ph2 ＞) (＜ pv0 (c0 side) (c1 side) n0', ph2 ＞)) as claim0; simpl in claim0.\n  rewrite claim0; clear claim0.\n\n  rewrite <- (lemma25_CCA2Game2n side n0' n0).\n  rewrite <- (lemma25_CCA2Game1n side n0' (＜ pv0 (c0 side) (c1 side) n0, ph2 ＞)).\n  reflexivity.\n\n  destruct side; ProveContext.\n  8 : { destruct side; ProveContext. }\n  1,2,3,4,5: destruct side; ProveCCA2.\n  apply lemma25_CCA2_n0_n0'_AfterCnxt.\n  auto.\nQed.\n\n\n\n\n\n\n\n\n(*************************************************************************)\n(***** Next we show that as n0 is removed, the first voter check of it ***)\n(***** in the opening phase fails and the commitment key kc0 is not sent**)\n(*************************************************************************)\n\n\n(* In the next proposition we show that after n0 is removed, the isin-chech in front of the Voting phase shuffle will turn false,\n   so the shuffle might be published. *)\n\nLemma lemma25_isin_pv0_false : forall side, (fun c0 c1 => (fun x0 => (fun v1 v2 v3 =>\n  (shufl (π1 v1) (π1 v2) (π1 v3)) = (s c0 c1 v1 v2 v3)) (Fv1 c0 c1 x0) (Fv2 c0 c1 x0) (Fv3 c0 c1 x0)) (e0 c0 c1 n0')) (c0 side) (c1 side).\nProof.\n  intros; simpl.\n  unfold s. rewrite NotElim.\n  unfold isin. rewrite Tau1Tri, Tau2Tri, Tau3Tri.\n  assert ((pv0 (c0 side) (c1 side) n0) ≠ (π1 Fv1 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0'))).\n    apply NeqIdem with (f := fun x => τ3 x). ProveContext. unfold pv0.\n    rewrite Tau3Tri. apply FreshNEqeq. destruct side; ProveFresh.\n    rewrite H; clear H. rewrite If_false.\n  assert ((pv0 (c0 side) (c1 side) n0) ≠ (π1 Fv2 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0'))).\n    apply NeqIdem with (f := fun x => τ3 x). ProveContext. unfold pv0.\n    rewrite Tau3Tri. apply FreshNEqeq. destruct side; ProveFresh.\n    rewrite H; clear H. rewrite If_false.\n  assert ((pv0 (c0 side) (c1 side) n0) ≠ (π1 Fv3 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0'))).\n    apply NeqIdem with (f := fun x => τ3 x). ProveContext. unfold pv0.\n    rewrite Tau3Tri. apply FreshNEqeq. destruct side; ProveFresh.\n    rewrite H; clear H. rewrite If_false.\n  reflexivity.\nQed.\n\n\n(* We show that if the vallot of the first voter was replaced, he will not send out his commitment key in the opening phase. \n   More specifically, we see that the bnlcheck in front of the opening-phase encryption fails, and \"Fl\" will turn to ⫠. *)\n\nLemma lemma25_Fl0_bot : forall side,\n   ⫠ = (fun c0 c1 => (fun x0 => (fun v1 v2 v3 => Fl0 c0 c1 x0 v1 v2 v3) (Fv1 c0 c1 x0) (Fv2 c0 c1 x0) (Fv3 c0 c1 x0)) (e0 c0 c1 n0')) (c0 side) (c1 side).\nProof.\n  intros. simpl.\n  unfold Fl0. unfold bnlcheck.\n  unfold fFΦ3 at 2.\n  rewrite <- lemma25_isin_pv0_false.\n\n  unfold ncheck. unfold isin. rewrite Tau1Tri, Tau2Tri, Tau3Tri.\n  assert (n0 ≠ τ3 (π2 τ1 (f3 [b0 (c0 side); b1 (c1 side); e0 (c0 side) (c1 side) n0'; e1 (c0 side) (c1 side) n1;\n    dv (Fv1 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0')) (Fv2 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0')) (Fv3 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0'))\n   (shufl (π1 Fv1 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0')) (π1 Fv2 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0')) (π1 Fv3 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0')))]))).\n    apply FreshNEqeq.  destruct side; ProveFresh.\n    rewrite H. clear H. rewrite If_false.\n  assert (n0 ≠ τ3 (π2 τ2 (f3 [b0 (c0 side); b1 (c1 side); e0 (c0 side) (c1 side) n0'; e1 (c0 side) (c1 side) n1;\n    dv (Fv1 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0')) (Fv2 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0')) (Fv3 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0'))\n   (shufl (π1 Fv1 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0')) (π1 Fv2 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0')) (π1 Fv3 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0')))]))).\n    apply FreshNEqeq.  destruct side; ProveFresh.\n    rewrite H. clear H. rewrite If_false.\n  assert (n0 ≠ τ3 (π2 τ3 (f3 [b0 (c0 side); b1 (c1 side); e0 (c0 side) (c1 side) n0'; e1 (c0 side) (c1 side) n1;\n    dv (Fv1 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0')) (Fv2 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0')) (Fv3 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0'))\n   (shufl (π1 Fv1 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0')) (π1 Fv2 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0')) (π1 Fv3 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0')))]))).\n    apply FreshNEqeq.  destruct side; ProveFresh.\n    rewrite H. clear H.\n  repeat rewrite If_same.\n  rewrite If_false.\n  reflexivity.\nQed.\n\n\n(* Now we see that if the Commitment key of the first voter was not sent, the isinkc0 check in front of the OPENING phase shuffle will fail.  *)\n\nLemma lemma25_ininkc0_false: forall side,\n  FAlse = (fun c0 c1 => (fun x0 => (fun v1 v2 v3 => isin kc0 (＜(π2 (π1 (Fo1 c0 c1 x0 v1 v2 v3))), (π2 (π1 (Fo2 c0 c1 x0 v1 v2 v3))), (π2 (π1 (Fo3 c0 c1 x0 v1 v2 v3)))＞)\n            ) (Fv1 c0 c1 x0) (Fv2 c0 c1 x0) (Fv3 c0 c1 x0)) (e0 c0 c1 n0')) (c0 side) (c1 side).\nProof.\n  intros.\n  simpl. unfold Fo1, Fo2, Fo3.\n  unfold fFΦ5. rewrite <- lemma25_Fl0_bot.\n  unfold isin. rewrite Tau1Tri, Tau2Tri, Tau3Tri.\n\n  assert ((fun c0 c1 => kc0 ≠ π2 (π1 (decS (τ1 (f5 [b0 c0; b1 c1; e0 c0 c1 n0'; e1 c0 c1 n1; dv (Fv1 c0 c1 (e0 c0 c1 n0')) (Fv2 c0 c1 (e0 c0 c1 n0')) (Fv3 c0 c1 (e0 c0 c1 n0'))\n                  (s c0 c1 (Fv1 c0 c1 (e0 c0 c1 n0')) (Fv2 c0 c1 (e0 c0 c1 n0')) (Fv3 c0 c1 (e0 c0 c1 n0'))); ⫠;\n                   Fl1 c0 c1 (e0 c0 c1 n0') (Fv1 c0 c1 (e0 c0 c1 n0')) (Fv2 c0 c1 (e0 c0 c1 n0')) (Fv3 c0 c1 (e0 c0 c1 n0'))]))))) (c0 side) (c1 side)).\n    pose (@prop11 (fun c0 => (fun c1 => π2 (π1 (decS (τ1 (f5 [b0 c0; b1 c1; e0 c0 c1 n0'; e1 c0 c1 n1; dv (Fv1 c0 c1 (e0 c0 c1 n0')) (Fv2 c0 c1 (e0 c0 c1 n0')) (Fv3 c0 c1 (e0 c0 c1 n0'))\n                 (s c0 c1 (Fv1 c0 c1 (e0 c0 c1 n0')) (Fv2 c0 c1 (e0 c0 c1 n0')) (Fv3 c0 c1 (e0 c0 c1 n0'))); ⫠;\n                  Fl1 c0 c1 (e0 c0 c1 n0') (Fv1 c0 c1 (e0 c0 c1 n0')) (Fv2 c0 c1 (e0 c0 c1 n0')) (Fv3 c0 c1 (e0 c0 c1 n0'))]))))) (c1 side)) (vot side) 0) as H.\n    simpl in *. rewrite c0EqVot in H. rewrite H. auto.\n    destruct side; simpl; ProvePPT; ProveFresh.\n    apply lemma25_ininkc0_false_FreshC_τ1.\n    rewrite H. rewrite If_false. clear H.\n\n  assert ((fun c0 c1 => kc0 ≠ π2 (π1 (decS (τ2 (f5 [b0 c0; b1 c1; e0 c0 c1 n0'; e1 c0 c1 n1; dv (Fv1 c0 c1 (e0 c0 c1 n0')) (Fv2 c0 c1 (e0 c0 c1 n0')) (Fv3 c0 c1 (e0 c0 c1 n0'))\n                  (s c0 c1 (Fv1 c0 c1 (e0 c0 c1 n0')) (Fv2 c0 c1 (e0 c0 c1 n0')) (Fv3 c0 c1 (e0 c0 c1 n0'))); ⫠;\n                   Fl1 c0 c1 (e0 c0 c1 n0') (Fv1 c0 c1 (e0 c0 c1 n0')) (Fv2 c0 c1 (e0 c0 c1 n0')) (Fv3 c0 c1 (e0 c0 c1 n0'))]))))) (c0 side) (c1 side)).\n    pose (@prop11 (fun c0 => (fun c1 => π2 (π1 (decS (τ2 (f5 [b0 c0; b1 c1; e0 c0 c1 n0'; e1 c0 c1 n1; dv (Fv1 c0 c1 (e0 c0 c1 n0')) (Fv2 c0 c1 (e0 c0 c1 n0')) (Fv3 c0 c1 (e0 c0 c1 n0'))\n                 (s c0 c1 (Fv1 c0 c1 (e0 c0 c1 n0')) (Fv2 c0 c1 (e0 c0 c1 n0')) (Fv3 c0 c1 (e0 c0 c1 n0'))); ⫠;\n                  Fl1 c0 c1 (e0 c0 c1 n0') (Fv1 c0 c1 (e0 c0 c1 n0')) (Fv2 c0 c1 (e0 c0 c1 n0')) (Fv3 c0 c1 (e0 c0 c1 n0'))]))))) (c1 side)) (vot side) 0) as H.\n    simpl in *. rewrite c0EqVot in H. rewrite H. auto.\n    destruct side; simpl; ProvePPT; ProveFresh.\n    apply lemma25_ininkc0_false_FreshC_τ2.\n    rewrite H. rewrite If_false. clear H.\n\n\n  assert ((fun c0 c1 => kc0 ≠ π2 (π1 (decS (τ3 (f5 [b0 c0; b1 c1; e0 c0 c1 n0'; e1 c0 c1 n1; dv (Fv1 c0 c1 (e0 c0 c1 n0')) (Fv2 c0 c1 (e0 c0 c1 n0')) (Fv3 c0 c1 (e0 c0 c1 n0'))\n                  (s c0 c1 (Fv1 c0 c1 (e0 c0 c1 n0')) (Fv2 c0 c1 (e0 c0 c1 n0')) (Fv3 c0 c1 (e0 c0 c1 n0'))); ⫠;\n                   Fl1 c0 c1 (e0 c0 c1 n0') (Fv1 c0 c1 (e0 c0 c1 n0')) (Fv2 c0 c1 (e0 c0 c1 n0')) (Fv3 c0 c1 (e0 c0 c1 n0'))]))))) (c0 side) (c1 side)).\n    pose (@prop11 (fun c0 => (fun c1 => π2 (π1 (decS (τ3 (f5 [b0 c0; b1 c1; e0 c0 c1 n0'; e1 c0 c1 n1; dv (Fv1 c0 c1 (e0 c0 c1 n0')) (Fv2 c0 c1 (e0 c0 c1 n0')) (Fv3 c0 c1 (e0 c0 c1 n0'))\n                 (s c0 c1 (Fv1 c0 c1 (e0 c0 c1 n0')) (Fv2 c0 c1 (e0 c0 c1 n0')) (Fv3 c0 c1 (e0 c0 c1 n0'))); ⫠;\n                  Fl1 c0 c1 (e0 c0 c1 n0') (Fv1 c0 c1 (e0 c0 c1 n0')) (Fv2 c0 c1 (e0 c0 c1 n0')) (Fv3 c0 c1 (e0 c0 c1 n0'))]))))) (c1 side)) (vot side) 0) as H.\n    simpl in *. rewrite c0EqVot in H. rewrite H. auto.\n    destruct side; simpl; ProvePPT; ProveFresh.\n    apply lemma25_ininkc0_false_FreshC_τ3.\n    rewrite H.\n\n  reflexivity.\n\nQed.\n\n\n(*************************************************************************)\n(***** Now we replace kc1 that was sent with a fresh kc1' in the *********)\n(***** encryption of the opening phase using again CCA2 ******************)\n(*************************************************************************)\n\n\n(* In the next proposition, again we insert the necessary if-then-else terms to prepare for the use of the CCA2 axiom  *)\n\nLemma lemma25_CCA2Game1kc: forall side,\n  (fun c0 c1 => (fun x0 => (fun v1 v2 v3 => [b0 c0; b1 c1; (If ((acc0 c0 c1) & (acc1 c0 c1)) Then\n                                   (If  ((τ1 (fFΦ2 c0 c1 x0)) ≟ x0)  or ((τ2 (fFΦ2 c0 c1 x0)) ≟ x0)  or ((τ3 (fFΦ2 c0 c1 x0)) ≟ x0)\n                                    Then ⫠\n                                    Else (＜＜ x0 ,               (e1 c0 c1 n1),            (dv v1 v2 v3 (s c0 c1 v1 v2 v3) ) ＞,\n                                           ＜ Fl0 c0 c1 x0 v1 v2 v3, Fl1 c0 c1 x0 v1 v2 v3, (Fdo c0 c1 x0 v1 v2 v3 )＞＞)) Else ⫠)] (**)\n             ) (Fv1 c0 c1 x0) (Fv2 c0 c1 x0) (Fv3 c0 c1 x0)\n  ) (e0 c0 c1 n0')) (c0 side) (c1 side)\n=\n  (fun c0 c1 => (fun y1 => (fun o1 o2 o3 => [b0 c0; b1 c1; (If ((acc0 c0 c1) & (acc1 c0 c1)) Then\n                     (If  ((τ1 (fFΦ2 c0 c1 (e0 c0 c1 n0'))) ≟ (e0 c0 c1 n0'))\n                       or ((τ2 (fFΦ2 c0 c1 (e0 c0 c1 n0'))) ≟ (e0 c0 c1 n0'))\n                       or ((τ3 (fFΦ2 c0 c1 (e0 c0 c1 n0'))) ≟ (e0 c0 c1 n0'))\n                      Then ⫠\n                      Else (＜＜ (e0 c0 c1 n0') ,  (e1 c0 c1 n1),\n                                (dv (Fv1 c0 c1 (e0 c0 c1 n0')) (Fv2 c0 c1 (e0 c0 c1 n0')) (Fv3 c0 c1 (e0 c0 c1 n0'))\n                                    (shufl (π1 (Fv1 c0 c1 (e0 c0 c1 n0'))) (π1 (Fv2 c0 c1 (e0 c0 c1 n0'))) (π1 (Fv3 c0 c1 (e0 c0 c1 n0'))))) ＞,\n                              ＜ ⫠,\n                                FL1 c0 c1 y1,\n                               (FIDO o1 o2 o3 )＞＞)) Else ⫠)] (**)\n           ) (FiiO1 c0 c1 y1) (FiiO2 c0 c1 y1) (FiiO3 c0 c1 y1)\n  ) (E1 c0 c1 kc1)) (c0 side) (c1 side).\nProof.\n  intros. simpl.\n\n(*  *)\n  assert (FiiO1 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1) = FO1 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1)).\n    unfold FiiO1, FO1.\n    rewrite (decIfThenElse (M1 (c0 side) (c1 side) kc1) 11 (τ1 (FFΦ5 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1)))) at 2.\n    reflexivity. rewrite H. clear H.\n\n  assert (FiiO2 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1) = FO2 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1)).\n    unfold FiiO2, FO2.\n    rewrite (decIfThenElse (M1 (c0 side) (c1 side) kc1) 11 (τ2 (FFΦ5 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1)))) at 2.\n    reflexivity. rewrite H. clear H.\n\n  assert (FiiO3 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1) = FO3 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1)).\n    unfold FiiO3, FO3.\n    rewrite (decIfThenElse (M1 (c0 side) (c1 side) kc1) 11 (τ3 (FFΦ5 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1)))) at 2.\n    reflexivity. rewrite H. clear H.\n\n(*  *)\n  unfold Fdo.\n  unfold isinkc.\n  rewrite <- lemma25_ininkc0_false. rewrite If_false.\n\n(*  *)\n  assert (FO1 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1)\n        = Fo1 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0') (Fv1 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0'))\n              (Fv2 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0')) (Fv3 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0'))).\n    unfold Fo1. unfold fFΦ5.\n    rewrite <- lemma25_Fl0_bot.\n    rewrite <- lemma25_isin_pv0_false.\n    reflexivity.\n    rewrite <- H.\n    clear H.\n\n  assert (FO2 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1)\n        = Fo2 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0') (Fv1 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0'))\n              (Fv2 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0')) (Fv3 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0'))).\n    unfold Fo2. unfold fFΦ5.\n    rewrite <- lemma25_Fl0_bot.\n    rewrite <- lemma25_isin_pv0_false.\n    reflexivity.\n    rewrite <- H.\n    clear H.\n\n  assert (FO3 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1)\n        = Fo3 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0') (Fv1 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0'))\n              (Fv2 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0')) (Fv3 (c0 side) (c1 side) (e0 (c0 side) (c1 side) n0'))).\n    unfold Fo3. unfold fFΦ5.\n    rewrite <- lemma25_Fl0_bot.\n    rewrite <- lemma25_isin_pv0_false.\n    reflexivity.\n    rewrite <- H.\n    clear H.\n\n(*  *)\n  rewrite <- lemma25_Fl0_bot.\n  rewrite <- lemma25_isin_pv0_false.\n\n  reflexivity.\nQed.\n\n\n\n(* We replace kc1 with kc1' using CCA2 axiom. *)\n\nProposition prop25_replace_kc1_with_kc1': forall side, (| (M1  (c0 side) (c1 side) kc1) | = |(M1  (c0 side) (c1 side) kc1') |) ->\n(fun c0 c1 => (fun y1 => (fun o1 o2 o3 => [b0 c0; b1 c1; (If ((acc0 c0 c1) & (acc1 c0 c1)) Then\n                     (If  ((τ1 (fFΦ2 c0 c1 (e0 c0 c1 n0'))) ≟ (e0 c0 c1 n0'))\n                       or ((τ2 (fFΦ2 c0 c1 (e0 c0 c1 n0'))) ≟ (e0 c0 c1 n0'))\n                       or ((τ3 (fFΦ2 c0 c1 (e0 c0 c1 n0'))) ≟ (e0 c0 c1 n0'))\n                      Then ⫠\n                      Else (＜＜ (e0 c0 c1 n0') ,  (e1 c0 c1 n1),\n                                (dv (Fv1 c0 c1 (e0 c0 c1 n0')) (Fv2 c0 c1 (e0 c0 c1 n0')) (Fv3 c0 c1 (e0 c0 c1 n0'))\n                                    (shufl (π1 (Fv1 c0 c1 (e0 c0 c1 n0'))) (π1 (Fv2 c0 c1 (e0 c0 c1 n0'))) (π1 (Fv3 c0 c1 (e0 c0 c1 n0'))))) ＞,\n                              ＜ ⫠,\n                                FL1 c0 c1 y1,\n                               (FIDO o1 o2 o3 )＞＞)) Else ⫠)] (**)\n           ) (FiiO1 c0 c1 y1) (FiiO2 c0 c1 y1) (FiiO3 c0 c1 y1)\n  ) (E1 c0 c1 kc1)) (c0 side) (c1 side)\n  ~\n(fun c0 c1 => (fun y1 => (fun o1 o2 o3 => [b0 c0; b1 c1; (If ((acc0 c0 c1) & (acc1 c0 c1)) Then\n                     (If  ((τ1 (fFΦ2 c0 c1 (e0 c0 c1 n0'))) ≟ (e0 c0 c1 n0'))\n                       or ((τ2 (fFΦ2 c0 c1 (e0 c0 c1 n0'))) ≟ (e0 c0 c1 n0'))\n                       or ((τ3 (fFΦ2 c0 c1 (e0 c0 c1 n0'))) ≟ (e0 c0 c1 n0'))\n                      Then ⫠\n                      Else (＜＜ (e0 c0 c1 n0') ,  (e1 c0 c1 n1),\n                                (dv (Fv1 c0 c1 (e0 c0 c1 n0')) (Fv2 c0 c1 (e0 c0 c1 n0')) (Fv3 c0 c1 (e0 c0 c1 n0'))\n                                    (shufl (π1 (Fv1 c0 c1 (e0 c0 c1 n0'))) (π1 (Fv2 c0 c1 (e0 c0 c1 n0'))) (π1 (Fv3 c0 c1 (e0 c0 c1 n0'))))) ＞,\n                              ＜ ⫠,\n                                FL1 c0 c1 y1,\n                               (FIDO o1 o2 o3 )＞＞)) Else ⫠)] (**)\n           ) (FiiO1 c0 c1 y1) (FiiO2 c0 c1 y1) (FiiO3 c0 c1 y1)\n  ) (E1 c0 c1 kc1')) (c0 side) (c1 side).\nProof.\n  intros side. intros.\n  simpl.\n\n(* Φ6[x, pv01] is (pkS, rdd1, kc1, kc1') −- CCA2 compliant. pkS := nonce 6, rd0 := nonce 11 *)\n  pose (cca2 [nonce 6] [nonce 11]\n             (fun y1 => (fun c0 c1 => (fun o1 o2 o3 => [b0 c0; b1 c1; (If ((acc0 c0 c1) & (acc1 c0 c1)) Then\n                     (If  ((τ1 (fFΦ2 c0 c1 (e0 c0 c1 n0'))) ≟ (e0 c0 c1 n0'))\n                       or ((τ2 (fFΦ2 c0 c1 (e0 c0 c1 n0'))) ≟ (e0 c0 c1 n0'))\n                       or ((τ3 (fFΦ2 c0 c1 (e0 c0 c1 n0'))) ≟ (e0 c0 c1 n0'))\n                      Then ⫠\n                      Else (＜＜ (e0 c0 c1 n0') ,  (e1 c0 c1 n1),\n                                (dv (Fv1 c0 c1 (e0 c0 c1 n0')) (Fv2 c0 c1 (e0 c0 c1 n0')) (Fv3 c0 c1 (e0 c0 c1 n0'))\n                                    (shufl (π1 (Fv1 c0 c1 (e0 c0 c1 n0'))) (π1 (Fv2 c0 c1 (e0 c0 c1 n0'))) (π1 (Fv3 c0 c1 (e0 c0 c1 n0'))))) ＞,\n                              ＜ ⫠,\n                                FL1 c0 c1 y1,\n                               (FIDO o1 o2 o3 )＞＞)) Else ⫠)] (**)\n           ) (FiiO1 c0 c1 y1) (FiiO2 c0 c1 y1) (FiiO3 c0 c1 y1)) (c0 side) (c1 side))\n          (M1 (c0 side) (c1 side) kc1) (M1 (c0 side) (c1 side) kc1')) as claim0; simpl in claim0. rewrite claim0; clear claim0.\n  reflexivity.\n\n  1, 2, 3, 7: ProveCCA2.\n  ProveListFresh. lia. 1,2,3 :constructor.\n\n  apply lemma25_CCA2_kc1_kc1'_M1.\n  apply lemma25_CCA2_kc1_kc1'_M1'.\n  apply lemma25_CCA2_kc1_kc1'_Φ5.\nQed.\n\n\n\n\n(** In the next few propositions we discuss whether the OPENING phase shuffle will be published. **)\n\n\n(* Notice that ((τ1 (FFΦ5 c0 c1 y1)) ≟ y1) or ((τ2 (FFΦ5 c0 c1 y1)) ≟ y1) or ((τ3 (FFΦ5 c0 c1 y1)) ≟ y1) expresses that the commitment key of the second voter was not replaced,\n   then definitely the OPENING phase shuffle will not be published. *)\n\n(* The negation of which is \"FDO\", where the shuffle might still be published. *)\n\nLemma lemma25_elim_kc1_in_then_branch: forall side,\n (fun c0 c1 => (fun y1 => (fun o1 o2 o3 => FIDO o1 o2 o3) (FiiO1 c0 c1 y1) (FiiO2 c0 c1 y1) (FiiO3 c0 c1 y1)) (E1 c0 c1 kc1')) (c0 side) (c1 side)\n =\n (fun c0 c1 => (fun y1 => (fun o1 o2 o3 => If (τ1 (FFΦ5 c0 c1 y1)) ≟ y1 Then ⫠\n                             Else If (τ2 (FFΦ5 c0 c1 y1)) ≟ y1 Then ⫠\n                             Else If (τ3 (FFΦ5 c0 c1 y1)) ≟ y1 Then ⫠\n                             Else FDO o1 o2 o3) (FO1 c0 c1 y1) (FO2 c0 c1 y1) (FO3 c0 c1 y1)) (E1 c0 c1 kc1')) (c0 side) (c1 side).\nProof.\n  intros.\n  pose (lemma25_elim_kc1_cnxtΦ3 side) as ee.\n  pose (lemma25_elim_kc1_cnxtΦ5 side) as eee.\n  unfold FIDO. simpl.\n\n  unfold isin.\n  rewrite Tau1Tri, Tau2Tri, Tau3Tri.\n\n  unfold FiiO1 at 3. unfold FiiO2 at 3. unfold FiiO3 at 3. repeat rewrite decSimpl.\n  repeat rewrite (@If_morph (fun x => (kc1 ≟ (π2 (π1 x))))).\n  unfold M1.\n  rewrite proj1pair, proj2pair.\n  rewrite ceqeq.\n\n  simpl.\n  assert (((kc1 ≟ (π2 (π1 decS (τ1 (FFΦ5 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1'))))))) = FAlse).\n    assert ((com (vot (op side)) kc1) = c1 side).\n    destruct side; reflexivity.\n    pose (@prop11 (fun x => (π2 (π1 decS (τ1 (FFΦ5 (c0 side) x (E1 (c0 side) x kc1')))))) (vot (op side)) 1) as cont.\n    rewrite H in cont.\n    apply cont.\n    destruct side; simpl; ProvePPT.\n    1, 2: ProveFresh.\n    apply lemma25_elim_kc1_freshc1.\n    rewrite H; clear H; rewrite <- If_tf.\n  assert (((kc1 ≟ (π2 (π1 decS (τ2 (FFΦ5 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1'))))))) = FAlse).\n    assert ((com (vot (op side)) kc1) = c1 side).\n    destruct side; reflexivity.\n    pose (@prop11 (fun x => (π2 (π1 decS (τ2 (FFΦ5 (c0 side) x (E1 (c0 side) x kc1')))))) (vot (op side)) 1) as cont.\n    rewrite H in cont.\n    apply cont.\n    destruct side; simpl; ProvePPT.\n    1,2: ProveFresh.\n    apply lemma25_elim_kc1_freshc2.\n    rewrite H; clear H; rewrite <- If_tf.\n  assert (((kc1 ≟ (π2 (π1 decS (τ3 (FFΦ5 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1'))))))) = FAlse).\n    assert ((com (vot (op side)) kc1) = c1 side).\n    destruct side; reflexivity.\n    pose (@prop11 (fun x => (π2 (π1 decS (τ3 (FFΦ5 (c0 side) x (E1 (c0 side) x kc1')))))) (vot (op side)) 1) as cont.\n    rewrite H in cont.\n    apply cont.\n    destruct side; simpl; ProvePPT.\n    1,2: ProveFresh.\n    apply lemma25_elim_kc1_freshc3.\n    rewrite H; clear H; rewrite <- If_tf.\n\n  rewrite CNF_IfThenElse.\n\n  repeat rewrite (@If_morph (fun x => If dist (FiiO1 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1')) (FiiO2 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1'))\n                              (FiiO3 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1')) &\n                           pchko (＜ FiiO1 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1'), FiiO2 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1'),\n                                  FiiO3 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1') ＞) & x\n     Then shufl (π1 FiiO1 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1')) (π1 FiiO2 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1'))\n  (π1 FiiO3 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1')) Else ⫠ )).\n  repeat rewrite If_same.  repeat rewrite If_false.\n\n  unfold FiiO1, FiiO2, FiiO3.  repeat rewrite decSimpl. rewrite <- If_tf.\n\n  rewrite (@If_eval (fun _ => _) (fun b1 => If _ Then ⫠ Else If _ Then ⫠\n                                      Else If dist (If b1 Then _ Else _) _ _ & pchko (＜ If b1 Then _ Else _ , _ , _ ＞) Then shufl (π1 If b1 Then _ Else _ ) (π1 _) (π1 _) Else ⫠)).\n    rewrite If_false.\n  rewrite (@If_eval (fun _ => _) (fun b2 => If _ Then ⫠\n                                      Else If dist _ (If b2 Then _ Else _) _ & pchko (＜ _,  If b2 Then _ Else _ , _ ＞) Then shufl (π1 _) (π1 If b2 Then _ Else _ ) (π1 _) Else ⫠)).\n    rewrite If_false.\n  rewrite (@If_eval (fun _ => _) (fun b3 => If dist _ _ (If b3 Then _ Else _) & pchko (＜ _, _, If b3 Then _ Else _ ＞) Then shufl (π1 _) (π1 _) (π1 If b3 Then _ Else _ ) Else ⫠)).\n    rewrite If_false.\n\n  reflexivity.\n  all : time ProveboolandContext. (*10.709 secs*)\n  unfold pchko.\n  Provebool.\nQed.\n\n\n(* In the next two propositions,  we show that in the opening phase\n   if the message sent from the second voter is ＜ ⫠, ph2 ＞, and replaced with (＜＜label, kc1' ＞, ph3 ＞) by the attacker,\n   then isinkc1 check in front of the OPENING phase shuffle will fail. *)\n\nLemma lemma25_ininkc1_FIO_false: forall side,\n  FAlse\n =\n  (fun c0 c1 => (fun y1 => (fun o1 o2 o3 => (isin kc1 (＜(π2 (π1 o1)), (π2 (π1 o2)), (π2 (π1 o3))＞))) (FiO1 c0 c1 y1) (FiO2 c0 c1 y1) (FiO3 c0 c1 y1)) (E1 c0 c1 kc1')) (c0 side) (c1 side).\nProof.\n  intros.\n  pose (lemma25_ininkc1_Freshkc1_Φ3 side) as ee.\n  pose (lemma25_ininkc1_Freshkc1_Φ5 side) as eee.\n  unfold isin.\n  rewrite Tau1Tri, Tau2Tri, Tau3Tri.\n  assert (kc1 ≠ (π2 (π1 FiO1 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1')))).\n    assert ((com (vot (op side)) kc1) = c1 side).\n    destruct side; reflexivity.\n    pose (@prop11 (fun x => (π2 (π1 (FiO1 (c0 side) x (E1 (c0 side) x kc1'))))) (vot (op side)) 1) as cont.\n    rewrite H in cont.\n    apply cont.\n    destruct side; simpl; ProvePPT.\n    1, 2: ProveFresh.\n    (destruct side; simpl; ProveFreshCTerm).\n    rewrite H. clear H.\n  assert (kc1 ≠ (π2 (π1 FiO2 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1')))).\n    assert ((com (vot (op side)) kc1) = c1 side).\n    destruct side; reflexivity.\n    pose (@prop11 (fun x => (π2 (π1 (FiO2 (c0 side) x (E1 (c0 side) x kc1'))))) (vot (op side)) 1) as cont.\n    rewrite H in cont.\n    apply cont.\n    destruct side; simpl; ProvePPT.\n    1, 2: ProveFresh.\n    (destruct side; simpl; ProveFreshCTerm).\n    rewrite H. clear H.\n  assert (kc1 ≠ (π2 (π1 FiO3 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1')))).\n    assert ((com (vot (op side)) kc1) = c1 side).\n    destruct side; reflexivity.\n    pose (@prop11 (fun x => (π2 (π1 (FiO3 (c0 side) x (E1 (c0 side) x kc1'))))) (vot (op side)) 1) as cont.\n    rewrite H in cont.\n    apply cont.\n    destruct side; simpl; ProvePPT.\n    1, 2: ProveFresh.\n    (destruct side; simpl; ProveFreshCTerm).\n    rewrite H. clear H.\n  repeat rewrite If_false.\n  reflexivity.\nQed.\n\n(*  *)\n\nLemma lemma25_elim_kc1_in_FIDO: forall side,\n (fun c0 c1 => (fun y1 => (fun o1 o2 o3 => FIDO o1 o2 o3) (FiO1 c0 c1 y1) (FiO2 c0 c1 y1) (FiO3 c0 c1 y1)) (E1 c0 c1 kc1')) (c0 side) (c1 side)\n =\n (fun c0 c1 => (fun y1 => (fun o1 o2 o3 => FDO o1 o2 o3)  (FiO1 c0 c1 y1) (FiO2 c0 c1 y1) (FiO3 c0 c1 y1)) (E1 c0 c1 kc1')) (c0 side) (c1 side).\nProof.\n  intros. simpl.\n  unfold FIDO.\n  rewrite <- lemma25_ininkc1_FIO_false.\n  rewrite If_false. rewrite <- If_tf.\n  reflexivity. unfold pchko.  Provebool.\nQed.\n\n\n\n\n(* In the next two propositions, We show that in the opening phase, two scenarios that if \n   \"the plaintext sent from the second voter is ＜ ⫠, ph2 ＞,             and replaced with (＜＜label, kc1' ＞, ph3 ＞) by the attacker\",\n     and \n   \"the plaintext sent from the second voter is ＜＜label, kc1 ＞, ph3 ＞, and replaced with (＜＜label, kc1' ＞, ph3 ＞) by the attacker\",\n   appear to be the same. *)\n\nLemma lemma25_elim_bot_in_then_branch: forall side,\n (fun c0 c1 => (fun y1 => (fun o1 o2 o3 => FIDO o1 o2 o3) (FiO1 c0 c1 y1) (FiO2 c0 c1 y1) (FiO3 c0 c1 y1)) (E1 c0 c1 kc1')) (c0 side) (c1 side)\n =\n (fun c0 c1 => (fun y1 => (fun o1 o2 o3 => If (τ1 (FFΦ5 c0 c1 y1)) ≟ y1 Then ⫠\n                             Else If (τ2 (FFΦ5 c0 c1 y1)) ≟ y1 Then ⫠\n                             Else If (τ3 (FFΦ5 c0 c1 y1)) ≟ y1 Then ⫠\n                             Else FDO o1 o2 o3) (FO1 c0 c1 y1) (FO2 c0 c1 y1) (FO3 c0 c1 y1)) (E1 c0 c1 kc1')) (c0 side) (c1 side).\nProof.\n  intros. simpl.\n  pose (lemma25_elim_bot_cnxtΦ3 side) as ee.\n  pose (lemma25_elim_bot_cnxtΦ5 side) as eee.\n(*  *)\n  rewrite lemma25_elim_kc1_in_FIDO.\n  unfold FDO. simpl.\n\n(*  *)\n  unfold pchko. rewrite Tau1Tri, Tau2Tri, Tau3Tri.\n  unfold FiO1 at 2.  unfold FiO2 at 2.  unfold FiO3 at 2.\n  repeat rewrite (@If_morph (fun x => (ph3 ≟ (π2 x)))).\n  rewrite proj2pair.\n  rewrite ph2Neqph3.\n\n(*  *)\n  rewrite AndGuard.\n  assert (((ph3 ≟ (π2 decS (τ1 (FFΦ5 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1'))))) & (ph3 ≟ (π2 decS (τ2 (FFΦ5 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1')))))\n         & (ph3 ≟ (π2 decS (τ3 (FFΦ5 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1'))))))\n        = (pchko (＜ FO1 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1'), FO2 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1'),\n                     FO3 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1') ＞))).\n    unfold pchko. rewrite Tau1Tri, Tau2Tri, Tau3Tri.\n    reflexivity.\n    simpl. rewrite H; clear H.\n    repeat rewrite (@If_morph (fun x => If dist (FiO1 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1'))\n                                        (FiO2 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1'))\n                                        (FiO3 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1')) & x\n           Then shufl (π1 FiO1 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1')) (π1 FiO2 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1'))\n         (π1 FiO3 (c0 side) (c1 side) (E1 (c0 side) (c1 side) kc1')) Else ⫠)).\n  repeat rewrite If_same.\n  repeat rewrite If_false.\n\n(*  *)\n  unfold FiO1, FiO2, FiO3.\n  rewrite (@If_eval (fun _ => _) (fun b1 => If _ Then ⫠ Else If _ Then ⫠\n                                      Else If dist (If b1 Then _ Else _) _ _ & pchko (＜ _, _ , _ ＞) Then shufl (π1 If b1 Then _ Else _ ) (π1 _) (π1 _) Else ⫠)).\n    rewrite If_false.\n  rewrite (@If_eval (fun _ => _) (fun b2 => If _ Then ⫠\n                                      Else If dist _ (If b2 Then _ Else _) _ & pchko (＜ _,  _, _ ＞) Then shufl (π1 _) (π1 If b2 Then _ Else _ ) (π1 _) Else ⫠)).\n    rewrite If_false.\n  rewrite (@If_eval (fun _ => _) (fun b3 => If dist _ _ (If b3 Then _ Else _) & pchko (＜ _, _, _ ＞) Then shufl (π1 _) (π1 _) (π1 If b3 Then _ Else _ ) Else ⫠)).\n    rewrite If_false.\n\n(*  *)\n  reflexivity.\n\n  all : time ProveboolandContext. (*2.667 secs*)\nQed.\n\n(*  *)\n\nLemma lemma25_CCA2Game2kc: forall side,\n  (fun c0 c1 => (fun y1 => (fun o1 o2 o3 => [b0 c0; b1 c1; (If ((acc0 c0 c1) & (acc1 c0 c1)) Then\n                     (If  ((τ1 (fFΦ2 c0 c1 (e0 c0 c1 n0'))) ≟ (e0 c0 c1 n0'))\n                       or ((τ2 (fFΦ2 c0 c1 (e0 c0 c1 n0'))) ≟ (e0 c0 c1 n0'))\n                       or ((τ3 (fFΦ2 c0 c1 (e0 c0 c1 n0'))) ≟ (e0 c0 c1 n0'))\n                      Then ⫠\n                      Else (＜＜ (e0 c0 c1 n0') ,  (e1 c0 c1 n1),\n                                (dv (Fv1 c0 c1 (e0 c0 c1 n0')) (Fv2 c0 c1 (e0 c0 c1 n0')) (Fv3 c0 c1 (e0 c0 c1 n0'))\n                                    (shufl (π1 (Fv1 c0 c1 (e0 c0 c1 n0'))) (π1 (Fv2 c0 c1 (e0 c0 c1 n0'))) (π1 (Fv3 c0 c1 (e0 c0 c1 n0'))))) ＞,\n                              ＜ ⫠,\n                                FL1 c0 c1 y1,\n                               (FIDO o1 o2 o3 )＞＞)) Else ⫠)] (**)\n           ) (FiiO1 c0 c1 y1) (FiiO2 c0 c1 y1) (FiiO3 c0 c1 y1)\n  ) (E1 c0 c1 kc1')) (c0 side) (c1 side)\n =\n  (fun c0 c1 => (fun y1 => (fun o1 o2 o3 => [b0 c0; b1 c1; (If ((acc0 c0 c1) & (acc1 c0 c1)) Then\n                     (If  ((τ1 (fFΦ2 c0 c1 (e0 c0 c1 n0'))) ≟ (e0 c0 c1 n0'))\n                       or ((τ2 (fFΦ2 c0 c1 (e0 c0 c1 n0'))) ≟ (e0 c0 c1 n0'))\n                       or ((τ3 (fFΦ2 c0 c1 (e0 c0 c1 n0'))) ≟ (e0 c0 c1 n0'))\n                      Then ⫠\n                      Else (＜＜ (e0 c0 c1 n0') ,  (e1 c0 c1 n1),\n                                (dv (Fv1 c0 c1 (e0 c0 c1 n0')) (Fv2 c0 c1 (e0 c0 c1 n0')) (Fv3 c0 c1 (e0 c0 c1 n0'))\n                                    (shufl (π1 (Fv1 c0 c1 (e0 c0 c1 n0'))) (π1 (Fv2 c0 c1 (e0 c0 c1 n0'))) (π1 (Fv3 c0 c1 (e0 c0 c1 n0'))))) ＞,\n                              ＜ ⫠,\n                                FL1 c0 c1 y1,\n                               (FDO o1 o2 o3 )＞＞)) Else ⫠)] (**)\n           ) (FiO1 c0 c1 y1) (FiO2 c0 c1 y1) (FiO3 c0 c1 y1)\n  ) (E1 c0 c1 kc1')) (c0 side) (c1 side).\nProof.\n  (* Same kind of theorems are needed to replace n0 on the other side, and kc1. Then use hiding. *)\n  intros. simpl.\n  rewrite <- lemma25_elim_kc1_in_FIDO.\n  rewrite lemma25_elim_kc1_in_then_branch.\n  rewrite lemma25_elim_bot_in_then_branch.\n  reflexivity.\nQed.\n\n\n(*************************************************************************)\n(***** Next we put together what we have so far using transitivity: ******)\n(*************************************************************************)\n\n\nProposition remove_n0_and_kc1_from_both : forall side,\n    (| ＜ pv0 (c0 side) (c1 side) n0, ph2 ＞ |) = (| ＜ pv0 (c0 side) (c1 side) n0', ph2 ＞ |) ->\n    (| (M1  (c0 side) (c1 side) kc1) | = |(M1  (c0 side) (c1 side) kc1') |) ->\n  (fun c0 c1 => (fun x0 => (fun v1 v2 v3 => [b0 c0; b1 c1; (If ((acc0 c0 c1) & (acc1 c0 c1)) Then\n                                   (If ((τ1 (fFΦ2 c0 c1 x0)) ≟ x0)  or ((τ2 (fFΦ2 c0 c1 x0)) ≟ x0)  or ((τ3 (fFΦ2 c0 c1 x0)) ≟ x0)\n                                    Then ⫠\n                                    Else (＜＜ x0 ,               (e1 c0 c1 n1),            (dv v1 v2 v3 (s c0 c1 v1 v2 v3) ) ＞,\n                                           ＜ Fl0 c0 c1 x0 v1 v2 v3, Fl1 c0 c1 x0 v1 v2 v3, (Fdo c0 c1 x0 v1 v2 v3 )＞＞)) Else ⫠)] (**)\n             ) (Fv1 c0 c1 x0) (Fv2 c0 c1 x0) (Fv3 c0 c1 x0)\n  ) (e0 c0 c1 n0)) (c0 side) (c1 side)\n ~\n  (fun c0 c1 => (fun y1 => (fun o1 o2 o3 => [b0 c0; b1 c1; (If ((acc0 c0 c1) & (acc1 c0 c1)) Then\n                     (If  ((τ1 (fFΦ2 c0 c1 (e0 c0 c1 n0'))) ≟ (e0 c0 c1 n0'))\n                       or ((τ2 (fFΦ2 c0 c1 (e0 c0 c1 n0'))) ≟ (e0 c0 c1 n0'))\n                       or ((τ3 (fFΦ2 c0 c1 (e0 c0 c1 n0'))) ≟ (e0 c0 c1 n0'))\n                      Then ⫠\n                      Else (＜＜ (e0 c0 c1 n0') ,  (e1 c0 c1 n1),\n                                (dv (Fv1 c0 c1 (e0 c0 c1 n0')) (Fv2 c0 c1 (e0 c0 c1 n0')) (Fv3 c0 c1 (e0 c0 c1 n0'))\n                                    (shufl (π1 (Fv1 c0 c1 (e0 c0 c1 n0'))) (π1 (Fv2 c0 c1 (e0 c0 c1 n0'))) (π1 (Fv3 c0 c1 (e0 c0 c1 n0'))))) ＞,\n                              ＜ ⫠,\n                                FL1 c0 c1 y1,\n                               (FDO o1 o2 o3 )＞＞)) Else ⫠)] (**)\n           ) (FiO1 c0 c1 y1) (FiO2 c0 c1 y1) (FiO3 c0 c1 y1)\n  ) (E1 c0 c1 kc1')) (c0 side) (c1 side).\nProof.\n  (* transitivity of ~ and the removal of n0 and kc1 and some of the above rewrites *)\n  intros. simpl.\n  rewrite prop25_replace_n0_with_n0'.\n  rewrite lemma25_CCA2Game1kc.\n  rewrite prop25_replace_kc1_with_kc1'.\n  rewrite lemma25_CCA2Game2kc.\n  reflexivity.\n  all : auto.\nQed.\n\n\n\n\n\n\n\n\n(*************************************************************************)\n(***** Finally, we use hiding property of the Commitment to  *************)\n(***** show equivalence of the two sides *********************************)\n(*************************************************************************)\n\n\nLemma lemma25 :\n    (fun c0 c1 => [b0 c0; b1 c1; (If ((acc0 c0 c1) & (acc1 c0 c1)) Then\n                              (If ((τ1 (fΦ2 c0 c1)) ≟ (e0 c0 c1 n0)) or ((τ2 (fΦ2 c0 c1)) ≟ (e0 c0 c1 n0)) or ((τ3 (fΦ2 c0 c1)) ≟ (e0 c0 c1 n0))\n                                    Then ⫠\n                                    Else (＜＜(e0 c0 c1 n0), (e1 c0 c1 n1), (dv (v1 c0 c1) (v2 c0 c1) (v3 c0 c1) (s c0 c1 (v1 c0 c1) (v2 c0 c1) (v3 c0 c1)) ) ＞,\n                                           ＜ l0 c0 c1,      l1 c0 c1,      (do c0 c1)＞＞)) Else ⫠)]) (c0 lhs) (c1 lhs)\n   ~\n    (fun c0 c1 => [b0 c0; b1 c1; (If ((acc0 c0 c1) & (acc1 c0 c1)) Then\n                              (If ((τ1 (fΦ2 c0 c1)) ≟ (e0 c0 c1 n0)) or ((τ2 (fΦ2 c0 c1)) ≟ (e0 c0 c1 n0)) or ((τ3 (fΦ2 c0 c1)) ≟ (e0 c0 c1 n0))\n                                    Then ⫠\n                                    Else (＜＜(e0 c0 c1 n0), (e1 c0 c1 n1), (dv (v1 c0 c1) (v2 c0 c1) (v3 c0 c1) (s c0 c1 (v1 c0 c1) (v2 c0 c1) (v3 c0 c1)) ) ＞,\n                                           ＜ l0 c0 c1,      l1 c0 c1,      (do c0 c1)＞＞)) Else ⫠)]) (c0 rhs) (c1 rhs).\nProof.\n  intros.\n  rewrite (remove_n0_and_kc1_from_both lhs).\n  rewrite (remove_n0_and_kc1_from_both rhs).\n  simpl.\n\n(*  *)\n  assert ([c00; c01; b0 c00; b1 c01; acc0 c00 c01 & acc1 c00 c01; e0 c00 c01 n0'; e1 c00 c01 n1;\n    dv (Fv1 c00 c01 (e0 c00 c01 n0')) (Fv2 c00 c01 (e0 c00 c01 n0')) (Fv3 c00 c01 (e0 c00 c01 n0'))\n                 (shufl (π1 Fv1 c00 c01 (e0 c00 c01 n0')) (π1 Fv2 c00 c01 (e0 c00 c01 n0')) (π1 Fv3 c00 c01 (e0 c00 c01 n0')));\n    FL1 c00 c01 (E1 c00 c01 kc1'); FDO (FiO1 c00 c01 (E1 c00 c01 kc1')) (FiO2 c00 c01 (E1 c00 c01 kc1')) (FiO3 c00 c01 (E1 c00 c01 kc1')) ]\n ~\n   [c10; c11; b0 c10; b1 c11; acc0 c10 c11 & acc1 c10 c11; e0 c10 c11 n0'; e1 c10 c11 n1;\n    dv (Fv1 c10 c11 (e0 c10 c11 n0')) (Fv2 c10 c11 (e0 c10 c11 n0')) (Fv3 c10 c11 (e0 c10 c11 n0'))\n                 (shufl (π1 Fv1 c10 c11 (e0 c10 c11 n0')) (π1 Fv2 c10 c11 (e0 c10 c11 n0')) (π1 Fv3 c10 c11 (e0 c10 c11 n0'))) ;\n    FL1 c10 c11 (E1 c10 c11 kc1'); FDO (FiO1 c10 c11 (E1 c10 c11 kc1')) (FiO2 c10 c11 (E1 c10 c11 kc1')) (FiO3 c10 c11 (E1 c10 c11 kc1'))]).\n    pose lemma25_freshcΦ3kc0.\n    pose lemma25_freshcΦ3kc1.\n    pose lemma25_freshcΦ5kc0.\n    pose lemma25_freshcΦ5kc1.\n    apply (@CompHidEx (fun lx => let c0 := Nth 0 lx in let c1 := Nth 1 lx in\n         [c0; c1; b0 c0; b1 c1; acc0 c0 c1 & acc1 c0 c1; e0 c0 c1 n0'; e1 c0 c1 n1;\n          dv (Fv1 c0 c1 (e0 c0 c1 n0')) (Fv2 c0 c1 (e0 c0 c1 n0')) (Fv3 c0 c1 (e0 c0 c1 n0'))\n             (shufl (π1 Fv1 c0 c1 (e0 c0 c1 n0')) (π1 Fv2 c0 c1 (e0 c0 c1 n0')) (π1 Fv3 c0 c1 (e0 c0 c1 n0'))); FL1 c0 c1 (E1 c0 c1 kc1');\n          FDO (FiO1 c0 c1 (E1 c0 c1 kc1')) (FiO2 c0 c1 (E1 c0 c1 kc1')) (FiO3 c0 c1 (E1 c0 c1 kc1'))       ])\n                    vot0 vot1 0 1).\n    all : simpl; time ProveFreshC. (*4.216 secs*)\n\n    (*  *)\n  apply voteLen.\n\n(*  *)\n  1, 2: ProveFresh.\n\n(*   *)\n  apply (@cind_funcapp (fun lc => [Nth 2 lc; Nth 3 lc; Nth 4 lc; Nth 5 lc; Nth 6 lc;\n                                ((τ1 (f2 [(Nth 2 lc); (Nth 3 lc); (Nth 5 lc); (Nth 6 lc)])) ≟ (Nth 5 lc)) or\n                                ((τ2 (f2 [(Nth 2 lc); (Nth 3 lc); (Nth 5 lc); (Nth 6 lc)])) ≟ (Nth 5 lc)) or\n                                ((τ3 (f2 [(Nth 2 lc); (Nth 3 lc); (Nth 5 lc); (Nth 6 lc)])) ≟ (Nth 5 lc));\n                               Nth 7 lc; Nth 8 lc; Nth 9 lc])) in H. unfold Nth in H.  unfold nth in H; simpl in H.\n\n  apply (IF_branch' [b0 c00; b1 c01] [b0 c10; b1 c11] _ _ _ _ _ _ ); simpl.\n  apply (IF_branch' [b0 c00; b1 c01; acc0 c00 c01 & acc1 c00 c01] [b0 c10; b1 c11; acc0 c10 c11 & acc1 c10 c11] _ _ _ _ _ _ ); simpl.\n\n(**)\n  assert (exists x, x = H). exists H; auto. destruct H0. clear H0. rename x into H0.\n  apply (@cind_funcapp (fun lc => [(Nth 0 lc); (Nth 1 lc); (Nth 2 lc); (Nth 5 lc); ⫠])) in H0.\n     unfold Nth in H0; unfold nth in H0; simpl in H0; apply H0. simpl; ProveContext.\n(**)\n  assert (exists x, x = H). exists H; auto. destruct H0. clear H0. rename x into H0.\n  apply (@cind_funcapp (fun lc => [(Nth 0 lc); (Nth 1 lc); (Nth 2 lc); (Nth 5 lc);\n  ＜ ＜ (Nth 3 lc), (Nth 4 lc), (Nth 6 lc) ＞, ＜ ⫠, (Nth 7 lc), (Nth 8 lc) ＞ ＞])) in H0.\n     unfold Nth in H0; unfold nth in H0; simpl in H0; auto. clear H0. simpl; ProveContext.\n\n  apply (@cind_funcapp (fun lc => [(Nth 0 lc); (Nth 1 lc); (Nth 2 lc); ⫠])) in H.\n     unfold Nth in H; unfold nth in H; simpl in H; auto. clear H. simpl; ProveContext.\n\n  clear H.\n  ProveContext.\n  - unfold pv0.\n    apply PairLen.\n    + apply TripleLen.\n      * reflexivity.\n      * reflexivity.\n    + reflexivity.\n  - unfold M1.\n    apply PairLen.\n    + apply PairLen.\n      reflexivity.\n      apply ComkLen.\n    + reflexivity.\n  - unfold pv0.\n    apply PairLen.\n    + apply TripleLen.\n      * reflexivity.\n      * reflexivity.\n    + reflexivity.\n  - unfold M1.\n    apply PairLen.\n    + apply PairLen.\n      reflexivity.\n      apply ComkLen.\n    + reflexivity.\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/lemma25.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2900784606875429}}
{"text": "Class Monad (m : Type -> Type) : Type := {\n  return_ : forall {A}, A -> m A\n  ; bind : forall {A}, m A -> forall {B}, (A -> m B) -> m B\n  (* monad laws *)\n  ; right_unit : forall A (a : m A), a = bind a (@return_ A)\n  ; left_unit : forall A (a : A) B (f : A -> m B),\n      f a = bind (return_ a) f\n  ; associativity : forall A (ma : m A) B f C (g : B -> m C),\n      bind ma (fun x => bind (f x) g) = bind (bind ma f) g\n}.\n\nNotation \"a >>= f\" := (bind a f) (at level 50, left associativity).\nNotation \"a >> b\" := (a >>= (fun _ => b)) (at level 50, left associativity).\nNotation \"'do' a <- e ; c\" :=\n  (e >>= (fun a => c)) (at level 60, right associativity).\n\nInstance OptionMonad : Monad option := {\n  return_ := Some\n  ; bind A m B f :=\n      match m with\n      | None => None\n      | Some a => f a\n      end\n}.\nProof.\n destruct a; reflexivity.\n\n reflexivity.\n\n destruct ma.\n  intros B f C g. destruct (f a); reflexivity.\n\n  reflexivity.\nDefined.", "meta": {"author": "yoshihiro503", "repo": "coqQuickCheck", "sha": "41aa678ee2b0b6d173452ce0312a0728dbc8fc3d", "save_path": "github-repos/coq/yoshihiro503-coqQuickCheck", "path": "github-repos/coq/yoshihiro503-coqQuickCheck/coqQuickCheck-41aa678ee2b0b6d173452ce0312a0728dbc8fc3d/Monad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.29006277817865245}}
{"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 FpuKami.Round.\nRequire Import ProcKami.FU.\nRequire Import ProcKami.RiscvIsaSpec.Insts.Fpu.FpuFuncs.\nRequire Import List.\nImport ListNotations.\n\nSection Fpu.\n  Context `{procParams: ProcParams}.\n\n  Variable fpuParamsSingle : FpuParams.\n  Variable fpuParamsDouble : FpuParams.\n\n  Local Notation single_expWidthMinus2 := (@expWidthMinus2 fpuParamsSingle).\n  Local Notation single_sigWidthMinus2 := (@sigWidthMinus2 fpuParamsSingle).\n  Local Notation double_expWidthMinus2 := (@expWidthMinus2 fpuParamsDouble).\n  Local Notation double_sigWidthMinus2 := (@sigWidthMinus2 fpuParamsDouble).\n\n  Local Definition single_Flen := single_expWidthMinus2 + 1 + 1 + (single_sigWidthMinus2 + 1 + 1).\n  Local Definition double_Flen := double_expWidthMinus2 + 1 + 1 + (double_sigWidthMinus2 + 1 + 1).\n\n  Open Scope kami_expr.\n\n  Definition Float_double\n    :  FUEntry\n    := {|\n         fuName := \"float_double\";\n         fuFunc\n           := fun ty (sem_in_pkt_expr : RoundInput single_expWidthMinus2 single_sigWidthMinus2 ## ty)\n                => LETE sem_in_pkt\n                     :  RoundInput single_expWidthMinus2 single_sigWidthMinus2\n                     <- sem_in_pkt_expr;\n                   RoundNF_def_expr double_expWidthMinus2 double_sigWidthMinus2 #sem_in_pkt;\n         fuInsts\n           := [\n                {|\n                  instName   := \"fcvt.d.s\";\n                  xlens      := xlens_all;\n                  extensions := [\"D\"];\n                  ext_ctxt_off := [\"fs\"];\n                  uniqId\n                    := [\n                         fieldVal instSizeField ('b\"11\");\n                         fieldVal opcodeField   ('b\"10100\");\n                         fieldVal rs2Field      ('b\"00000\");\n                         fieldVal funct7Field   ('b\"0100001\")\n                       ];\n                  inputXform\n                    := (fun ty (cfg_pkt : ContextCfgPkt @# ty) context_pkt_expr\n                          => LETE context_pkt <- context_pkt_expr;\n                             RetE\n                               (STRUCT {\n                                  \"in\" \n                                    ::= @bitToNF fpuParamsSingle ty\n                                          (@fp_get_float fpuParamsSingle ty\n                                             Rlen\n                                             Flen            \n                                             (#context_pkt @% \"reg1\"));\n                                  \"afterRounding\" ::= $$false;\n                                  \"roundingMode\"  ::= rounding_mode (#context_pkt)\n                                } : RoundInput single_expWidthMinus2 single_sigWidthMinus2 @# ty));\n                  outputXform\n                    := (fun ty (sem_out_pkt_expr : OpOutput double_expWidthMinus2 double_sigWidthMinus2 ## ty)\n                        => LETE sem_out_pkt <- sem_out_pkt_expr;\n                             LETC val1: RoutedReg <- (STRUCT {\n                                                    \"tag\"  ::= (Const ty (natToWord RoutingTagSz FloatRegTag) : RoutingTag @# ty);\n                                                    \"data\" ::= (OneExtendTruncLsb Rlen (NFToBit (#sem_out_pkt @% \"out\")) : Bit Rlen @# ty)\n                                                     });\n                             LETC val2: RoutedReg <- (STRUCT {\n                                                    \"tag\"  ::= (Const ty (natToWord RoutingTagSz FflagsTag) : RoutingTag @# ty);\n                                                    \"data\" ::= (csr (#sem_out_pkt @% \"exceptionFlags\") : Bit Rlen @# ty)\n                                                     });\n                             LETC fstVal\n                               :  ExecUpdPkt\n                               <- (noUpdPkt ty)\n                                    @%[\"val1\" <- (Valid #val1)]\n                                    @%[\"val2\" <- (Valid #val2)];\n                             RetE\n                               (STRUCT {\n                                  \"fst\"\n                                    ::= #fstVal;\n                                  \"snd\" ::= Invalid\n                                } : PktWithException ExecUpdPkt @# ty));\n                  optMemParams := None;\n                  instHints   := falseHints<|hasFrs1 := true|><|hasFrd := true|>\n                |}\n              ]\n       |}.\n\n  Definition Double_float\n    :  FUEntry\n    := {|\n         fuName := \"double_float\";\n         fuFunc\n           := fun ty (sem_in_pkt_expr : RoundInput double_expWidthMinus2 double_sigWidthMinus2 ## ty)\n                => LETE sem_in_pkt\n                     :  RoundInput double_expWidthMinus2 double_sigWidthMinus2\n                     <- sem_in_pkt_expr;\n                   RoundNF_def_expr single_expWidthMinus2 single_sigWidthMinus2 #sem_in_pkt;\n         fuInsts\n           := [\n                {|\n                  instName   := \"fcvt.s.d\";\n                  xlens      := xlens_all;\n                  extensions := [\"D\"];\n                  ext_ctxt_off := [\"fs\"];\n                  uniqId\n                    := [\n                         fieldVal instSizeField ('b\"11\");\n                         fieldVal opcodeField   ('b\"10100\");\n                         fieldVal rs2Field      ('b\"00001\");\n                         fieldVal funct7Field   ('b\"0100000\")\n                       ];\n                  inputXform\n                    := (fun ty (cfg_pkt : ContextCfgPkt @# ty) context_pkt_expr\n                          => LETE context_pkt <- context_pkt_expr;\n                             RetE\n                               (STRUCT {\n                                  \"in\"\n                                    ::= @bitToNF fpuParamsDouble ty\n                                          (@fp_get_float fpuParamsDouble ty\n                                             Rlen\n                                             Flen            \n                                             (#context_pkt @% \"reg1\"));\n                                  \"afterRounding\" ::= $$false;\n                                  \"roundingMode\"  ::= rounding_mode (#context_pkt)\n                                } : RoundInput double_expWidthMinus2 double_sigWidthMinus2 @# ty));\n                  outputXform\n                    := (fun ty (sem_out_pkt_expr : OpOutput single_expWidthMinus2 single_sigWidthMinus2 ## ty)\n                        => LETE sem_out_pkt <- sem_out_pkt_expr;\n                             LETC val1: RoutedReg <- (STRUCT {\n                                                    \"tag\"  ::= (Const ty (natToWord RoutingTagSz FloatRegTag) : RoutingTag @# ty);\n                                                    \"data\" ::= (OneExtendTruncLsb Rlen (NFToBit (#sem_out_pkt @% \"out\")) : Bit Rlen @# ty)\n                                          });\n                             LETC val2: RoutedReg <- (STRUCT {\n                                                    \"tag\"  ::= (Const ty (natToWord RoutingTagSz FflagsTag) : RoutingTag @# ty);\n                                                    \"data\" ::= (csr (#sem_out_pkt @% \"exceptionFlags\") : Bit Rlen @# ty)\n                                          });\n                             LETC fstVal\n                               :  ExecUpdPkt\n                               <- (noUpdPkt ty)\n                                    @%[\"val1\" <- (Valid #val1)]\n                                    @%[\"val2\" <- (Valid #val2)];\n                             RetE\n                               (STRUCT {\n                                  \"fst\"\n                                    ::= #fstVal;\n                                  \"snd\" ::= Invalid\n                                } : PktWithException ExecUpdPkt @# ty));\n                  optMemParams := None;\n                  instHints   := falseHints<|hasFrs1 := true|><|hasFrd := 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/FRound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.29000706294142686}}
{"text": "(** * Push-Button Synthesis of Montgomery Reduction *)\nRequire Import Coq.Strings.String.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.Lists.List.\nRequire Import Coq.derive.Derive.\nRequire Import Crypto.Util.ErrorT.\nRequire Import Crypto.Util.ListUtil.\nRequire Import Crypto.Util.ZRange.\nRequire Import Crypto.Util.ZUtil.Div.\nRequire Import Crypto.Util.ZUtil.ModInv.\nRequire Import Crypto.Util.ZUtil.Tactics.LtbToLt.\nRequire Import Crypto.Util.ZUtil.Tactics.PullPush.Modulo.\nRequire Import Crypto.Util.ZUtil.Tactics.RewriteModSmall.\nRequire Import Rewriter.Language.Language.\nRequire Import Crypto.Language.API.\nRequire Import Crypto.Stringification.Language.\nRequire Import Crypto.Arithmetic.Core.\nRequire Import Crypto.Arithmetic.FancyMontgomeryReduction.\nRequire Import Crypto.BoundsPipeline.\nRequire Import Crypto.COperationSpecifications.\nRequire Import Crypto.Fancy.Compiler.\nRequire Import Crypto.PushButtonSynthesis.ReificationCache.\nRequire Import Crypto.PushButtonSynthesis.Primitives.\nRequire Import Crypto.PushButtonSynthesis.FancyMontgomeryReductionReificationCache.\nRequire Import Crypto.PushButtonSynthesis.InvertHighLow.\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.Compilers\n  Language.Wf.Compilers\n  Stringification.Language.Compilers.\nImport Compilers.API.\n\nImport COperationSpecifications.Primitives.\n\nImport COperationSpecifications.MontgomeryReduction.\n\nImport Associational Positional FancyMontgomeryReduction.MontgomeryReduction.\n\nLocal Set Keyed Unification. (* needed for making [autorewrite] fast, c.f. COQBUG(https://github.com/coq/coq/issues/9283) *)\n\nLocal Opaque reified_montred_gen. (* needed for making [autorewrite] not take a very long time *)\n\nSection rmontred.\n  Context {output_language_api : ToString.OutputLanguageAPI}\n          {pipeline_opts : PipelineOptions}\n          {pipeline_to_string_opts : PipelineToStringOptions}\n          {synthesis_opts : SynthesisOptions}\n          (N R N' : Z) (n : nat)\n          (machine_wordsize : machine_wordsize_opt).\n\n  Let value_range := r[0 ~> (2^machine_wordsize - 1)%Z]%zrange.\n  Let flag_range := r[0 ~> 1]%zrange.\n  Let bound := Some value_range.\n  Let consts_list := [N; N'].\n  Let R' := Z.modinv R N.\n\n  Definition possible_values_of_machine_wordsize\n    := [1; machine_wordsize / 2; machine_wordsize; 2 * machine_wordsize]%Z.\n  Local Arguments possible_values_of_machine_wordsize / .\n\n  Local Notation possible_values := possible_values_of_machine_wordsize.\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  Local Instance fancy_args : translate_to_fancy_opt\n    := (Some {| BoundsPipeline.invert_low log2wordsize := invert_low log2wordsize consts_list;\n                BoundsPipeline.invert_high log2wordsize := invert_high log2wordsize consts_list;\n                BoundsPipeline.value_range := value_range;\n                BoundsPipeline.flag_range := flag_range |}).\n\n  Local Instance fancy_args_good : translate_to_fancy_opt_correct.\n  Proof using consts_list value_range.\n    cbv [translate_to_fancy_opt_correct translate_to_fancy fancy_args invert_low invert_high constant_to_scalar constant_to_scalar_single consts_list fold_right];\n      split; intros; break_innermost_match_hyps; Z.ltb_to_lt; subst; congruence.\n  Qed.\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    := fold_right\n         (fun '(b, e) k => if b:bool then Error e else k)\n         res\n         [\n            ((negb (1 <? R))%Z, Pipeline.Value_not_ltZ \"R ≤ 1\" 1 R);\n            ((n =? 0)%nat, Pipeline.Values_not_provably_distinctZ \"n = 0\" (Z.of_nat n) 0);\n            ((R' =? 0)%Z, Pipeline.No_modular_inverse \"R⁻¹ mod N\" R N);\n            (negb ((R * R') mod N =? 1 mod N)%Z, Pipeline.Values_not_provably_equalZ \"(R * R') mod N ≠ 1 mod N\" ((R * R') mod N) (1 mod N));\n            (negb ((N * N') mod R =? (-1) mod R)%Z, Pipeline.Values_not_provably_equalZ \"(N * N') mod R ≠ (-1) mod R\" ((N * N') mod R) ((-1) mod R));\n            (negb (2 ^ machine_wordsize =? R)%Z, Pipeline.Values_not_provably_equalZ \"2^machine_wordsize ≠ R\" (2^machine_wordsize) R);\n            ((negb (0 <? N))%Z, Pipeline.Value_not_ltZ \"N ≤ 0\" 0 N);\n            ((negb (N <? R))%Z, Pipeline.Value_not_ltZ \"R ≤ N\" R N);\n            ((negb (0 <=? N'))%Z, Pipeline.Value_not_leZ \"N' < 0\" 0 N');\n            ((negb (N' <? R))%Z, Pipeline.Value_not_ltZ \"R ≤ N'\" R N');\n            ((negb (2 <=? machine_wordsize))%Z, Pipeline.Value_not_leZ \"machine_wordsize < 2\" 2 machine_wordsize)].\n\n  Local Arguments Z.mul !_ !_.\n\n  Local Ltac use_curve_good_t :=\n    repeat first [ assumption\n                 | progress cbv [EquivModulo.Z.equiv_modulo]\n                 | progress rewrite ?Z.mul_0_r, ?Pos.mul_1_r, ?Z.mul_1_r in *\n                 | reflexivity\n                 | lia\n                 | progress cbn in *\n                 | progress intros\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    : 0 <= N < R\n      /\\ 0 <= N' < R\n      /\\ N <> 0\n      /\\ R > 1\n      /\\ EquivModulo.Z.equiv_modulo R (N * N') (-1)\n      /\\ EquivModulo.Z.equiv_modulo N (R * R') 1\n      /\\ n <> 0%nat\n      /\\ 2 <= machine_wordsize\n      /\\ 2 ^ machine_wordsize = R.\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  Qed.\n\n  Definition montred\n    := Pipeline.BoundsPipeline\n         false (* subst01 *)\n         possible_values\n         (reified_montred_gen\n            @ GallinaReify.Reify N @ GallinaReify.Reify R @ GallinaReify.Reify N' @ GallinaReify.Reify (machine_wordsize:Z))\n         (bound, (bound, tt))\n         bound.\n\n  Definition smontred (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"montred\" montred\n          (fun _ _ _ => @nil string).\n\n  Local Ltac solve_montred_preconditions :=\n    repeat first [ lia\n           | apply use_curve_good\n           | progress (push_Zmod; pull_Zmod)\n           | progress autorewrite with zsimplify_fast\n           | rewrite Z.div_add' by lia\n           | rewrite Z.div_small by lia\n           | progress Z.rewrite_mod_small ].\n\n  Local Strategy -100 [montred]. (* needed for making Qed not take forever *)\n  Local Strategy -100 [montred']. (* needed for making prove_correctness not take forever *)\n  Lemma montred_correct res (Hres : montred = Success res)\n    : montred_correct N R R' (API.Interp res).\n  Proof using n curve_good.\n    cbv [montred_correct]; intros.\n    rewrite <- MontgomeryReduction.montred'_correct with (R:=R) (N':=N') (Zlog2R:=machine_wordsize) (n:=n) (lo:=lo) (hi:=hi) by solve_montred_preconditions.\n    prove_correctness' ltac:(fun _ => idtac) use_curve_good.\n    { cbv [ZRange.type.base.option.is_bounded_by ZRange.type.base.is_bounded_by bound is_bounded_by_bool value_range upper lower].\n      rewrite Bool.andb_true_iff, !Z.leb_le. lia. }\n    { cbv [ZRange.type.base.option.is_bounded_by ZRange.type.base.is_bounded_by bound is_bounded_by_bool value_range upper lower].\n      rewrite Bool.andb_true_iff, !Z.leb_le. lia. }\n  Qed.\n\n  Lemma Wf_montred res (Hres : montred = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\nEnd rmontred.\n\nModule Export Hints.\n#[global]\n  Hint Opaque\n       montred\n  : wf_op_cache.\n#[global]\n  Hint Immediate\n       Wf_montred\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/FancyMontgomeryReduction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2900070523155883}}
{"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 E Eprime P A B C A1 B1 C1 N C1prime M : Universe, ((wd_ N E /\\ (wd_ A C /\\ (wd_ B P /\\ (wd_ A B /\\ (wd_ N M /\\ (wd_ M C1 /\\ (wd_ N C1 /\\ (wd_ C1 C1prime /\\ (wd_ N C1prime /\\ (wd_ E Eprime /\\ (wd_ N Eprime /\\ (wd_ P A /\\ (wd_ P C /\\ (wd_ C1prime A1 /\\ (wd_ N A1 /\\ (wd_ N B1 /\\ (wd_ M C1prime /\\ (wd_ N N /\\ (wd_ A1 Eprime /\\ (col_ P A B /\\ (col_ C B P /\\ (col_ N E C1 /\\ (col_ N E B1 /\\ (col_ N E A1 /\\ (col_ M C1 C1prime /\\ (col_ N C1prime N /\\ (col_ N C1 N /\\ col_ N A1 C1))))))))))))))))))))))))))) -> col_ P A 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_1417.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185944046238982, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2900008829859113}}
{"text": "(*\n\n\nAuthor:  Adam Petz, ampetz@ku.edu\n*)\nRequire Import Maps Impl_vm.\nRequire Import Coq.Arith.EqNat.\nRequire Import Term StVM StAM\n        MonadVM GenStMonad ConcreteEvidence VmSemantics.\n(*Require Import Coq.ZArith.ZArith_base Coq.Strings.String Coq.Strings.Ascii. *)\n(* Require Import ExtLib.Data.Monads.StateMonad ExtLib.Data.Monads.ReaderMonad\nExtLib.Structures.Monads ExtLib.Data.Monads.IdentityMonad. *)\nRequire Import List.\n\n(* Import MonadNotation. *)\nImport ListNotations.\n(* Local Open Scope monad_scope. *)\n\n\n(*\nDefinition Policy := nat.\n\nRecord AM_Env : Type := mkAM_Env\n                          { myPolicy : Policy}.\n\nDefinition init_env := (mkAM_Env 0).\n *)\n\n\n\n(* ident is the identity monad, acting as a place-holder for the base monad.\n   TODO:  eventually we need this to be IO (or something that models IO) *)\nDefinition AM := St AM_St.     (* readerT AM_Env (stateT AM_St ident). *)\n\n(*\nDefinition am_newNonce (bs :BS) : AM EvidenceC :=\n  (*let myPol := asks myPolicy in *)\n  am_st <- get ;;\n  let mm := am_nonceMap am_st in\n  let i := am_nonceId am_st in\n  let appm := st_aspmap am_st in\n  let sigm := st_sigmap am_st in\n  (*let plm := am_pl am_st in *)\n              \n  let newMap := map_set mm i bs in\n  let newId := i + 1 in\n  put (mkAM_St newMap newId appm sigm (*plm*)) ;;         \n      ret (nnc i bs mtc).\n*)\n\nDefinition runAM {A:Type} (k:(AM A)) (* (env:AM_Env) *) (st:AM_St) : (option A) * AM_St :=\n  runSt k st.\n\n(*\nDefinition incNonce := runAM (am_newNonce 42) empty_amst.\nCheck incNonce.\nCompute (incNonce).\n\nCheck annotated.\n*)\n\nDefinition am_run_t (t:Term) (e:EvidenceC) : AM EvidenceC :=\n  let annt := annotated t in\n  let start_st := mk_st e [] 0 [] in\n  ret (st_ev (run_vm annt start_st)).\n\nDefinition t1 := (att 1 (lseq (asp (ASPC 44 [])) (asp SIG))).\nDefinition t2 := (lseq (asp (ASPC 44 [])) (asp SIG)).\n\n\n(*\nCompute (am_run_t t2 mtc empty_amst).\n*)\n\n(*\nDefinition am_proto_1 :=\n  n2 <- am_newNonce 42 ;;\n    n <- am_newNonce 43 ;;\n    am_run_t t2 n.\n\nCompute (runAM am_proto_1 empty_amst).\n*)\n\n(*\nFixpoint nonces (e:EvidenceC) (l:list nat) : list nat :=\n  match e with\n  | nnc i _ e' => nonces e' ([i] ++ l)\n  | _ => l\n  end.\n *)\n\n(** * Helper functions for Appraisal *)\n\nDefinition am_get_app_asp (p:Plc) (i:ASP_ID) : AM ASP_ID :=\n  m <- gets st_aspmap ;;\n  let maybeId := map_get m (p,i) in\n  match maybeId with\n  | Some i' => ret i'\n  | None => failm\n  end.\n\nDefinition am_get_sig_asp (p:Plc) : AM ASP_ID :=\n  m <- gets st_sigmap ;;\n  let maybeId := map_get m p in\n  match maybeId with\n  | Some i' => ret i'\n  | None => failm\n  end.\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/MonadAM_extra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.289869400008195}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n  Copyright 2015 Cornell University\n  Copyright 2016 Cornell University\n  Copyright 2017 Cornell University\n  Copyright 2018 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 alphaeq4.\nRequire Export stronger_continuity_defs4.\nRequire Export per_props_nat2.\nRequire Export per_props_squash.\nRequire Export sequents_tacs.\n\n\nDefinition mod_fun_type {o} (x : NVar) : @NTerm o :=\n  mk_function\n    mk_tnat\n    x\n    (mk_fun (mk_natk2nat (mk_var x))  mk_natU).\n\nLemma lsubstc_mod_fun_type {o} :\n  forall v w (s : @CSub o) c,\n    alphaeqc (lsubstc (mod_fun_type v) w s c) modulus_fun_type_u.\nProof.\n  introv.\n  unfold mod_fun_type.\n  lsubst_tac.\n  allrw @lsubstc_mkc_tnat.\n  unfold modulus_fun_type.\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 @mkcv_tnat_substc.\n    rw @mkc_var_substc.\n\n    eapply alphaeqc_trans;[apply lsubstc_mk_natk2nat_sp1|].\n    eauto 2 with slow.\n\n  - eapply alphaeqc_trans;[apply lsubstc_mk_natU|].\n    rw @csubst_mk_cv; eauto 3 with slow.\nQed.\n\nLemma lsubstc_nat2nat_to_nat {o} :\n  forall w (s : @CSub o) c,\n    alphaeqc\n      (lsubstc (mk_fun mk_nat2nat mk_tnat) w s c)\n      (mkc_fun nat2nat mkc_tnat).\nProof.\n  introv.\n  unfold alphaeqc; simpl.\n  eapply alpha_eq_trans;[apply csubst_mk_fun|].\n  autorewrite with slow.\n  apply alpha_eq_mk_fun; auto.\n  unfold mk_nat2nat.\n  eapply alpha_eq_trans;[apply csubst_mk_fun|].\n  autorewrite with slow; auto.\nQed.\nHint Resolve lsubstc_nat2nat_to_nat : slow.\n\n\n(* XXXXXXXXXX *)\n\n\nDefinition mk_sqexists {o} (a : @NTerm o) v b := mk_squash (mk_exists a v b).\n\nDefinition strong_continuous_type {o} (x M f n : NVar) (F : @NTerm o) :=\n  mk_sqexists\n    (mod_fun_type x)\n    M\n    (mk_all\n       mk_nat2nat\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 {o}\n           (F : @NTerm o)\n           (x M f n : NVar)\n           (H : barehypotheses) :=\n    mk_rule\n      (mk_baresequent H (mk_conclax (strong_continuous_type x M f n F)))\n      [ mk_baresequent H (mk_conclax (mk_member F (mk_fun mk_nat2nat mk_tnat))) ]\n      [].\n\nLemma rule_strong_continuity_true {p} :\n  forall lib\n         (F : NTerm)\n         (x M f n : NVar)\n         (H : @barehypotheses p)\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    rule_true lib (rule_strong_continuity\n                     F\n                     x M f n\n                     H).\nProof.\n  unfold rule_strong_continuity, 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  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  allunfold @strong_continuous_type.\n  allunfold @mk_sqexists.\n  lsubst_tac.\n\n  apply member_if_inhabited in h1.\n  apply tequality_mkc_member in h0; repnd.\n  allrw @fold_equorsq.\n  clear h2.\n\n  lsubst_tac.\n  allrw @lsubstc_mkc_tnat.\n  eapply member_respects_alphaeqc_r in h1;\n    [|apply alphaeqc_mkc_fun;[apply lsubstc_mk_nat2nat|apply alphaeqc_refl] ].\n  autodimp h0 hyp.\n  { clear - h1.\n    lsubst_tac.\n    eapply member_respects_alphaeqc_r;\n      [apply alphaeqc_sym;apply alphaeqc_mkc_fun;[apply lsubstc_mk_nat2nat|apply alphaeqc_refl]|].\n    autorewrite with slow in *; auto. }\n  eapply alphaeqc_preserving_equality in h0;\n    [|apply lsubstc_nat2nat_to_nat];[].\n\n  dup h1 as memF.\n  dup h0 as eqF.\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|].\n      eapply tequality_respects_alphaeqc_right;\n        [apply alphaeqc_sym; apply lsubstc_mod_fun_type|].\n      apply type_modulus_fun_type_u.\n\n    + intros M1 M2 em.\n      eapply alphaeqc_preserving_equality in em;[|apply lsubstc_mod_fun_type].\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_nat2nat|].\n        eapply tequality_respects_alphaeqc_right;\n          [apply alphaeqc_sym; apply lsubstc_mk_nat2nat|].\n        apply type_nat2nat.\n\n      * intros f1 f2 en2n.\n        eapply alphaeqc_preserving_equality in en2n;[|apply lsubstc_mk_nat2nat].\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_nat2nat_to_natk2nat lib n1) in en2n; auto;[].\n\n          apply equality_in_fun in e; repnd; clear e0 e1.\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 eqF; repnd; clear eqF0 eqF1.\n          apply eqF 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 wt s1 ct0))\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|].\n      apply type_modulus_fun_type_u.\n\n    + intros M1 M2 em.\n      eapply alphaeqc_preserving_equality in em;[|apply lsubstc_mod_fun_type].\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_nat2nat|].\n        eapply tequality_respects_alphaeqc_right;\n          [apply alphaeqc_sym; apply lsubstc_mk_nat2nat|].\n        apply type_nat2nat.\n\n      * intros f1 f2 en2n.\n        eapply alphaeqc_preserving_equality in en2n;[|apply lsubstc_mk_nat2nat].\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_nat2nat_to_natk2nat lib n1) in en2n; auto;[].\n\n          apply equality_in_fun in e; repnd; clear e0 e1.\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].\n\n        apply spM_in_modulus_fun_type_u; 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_nat2nat|].\n          eauto 3 with slow. }\n\n        { intros f1 f2 en2n.\n          eapply alphaeqc_preserving_equality in en2n;[|apply lsubstc_mk_nat2nat].\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 lib (lsubstc F wt s1 ct0) h1) as h.\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_nat2nat_to_natk2nat lib n1) in en2n; auto;[].\n\n            apply equality_in_fun in e; repnd; clear e0 e1.\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;[|apply lsubstc_mk_nat2nat].\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 lib (lsubstc F wt s1 ct0) f1 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 lib (lsubstc F wt s1 ct0) h1) as h.\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_nat2nat_to_natk2nat 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              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", "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_rule.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.28986939244367205}}
{"text": "From Coq Require Import Init.Nat.\nRequire Import RuntimeDefinitions.\n\nFixpoint set_all_zeroes (mu: memory) (block: block_ID) (offset: data_offset) (block_size: nat) (current_size: nat) {struct current_size}: option memory :=\n  match current_size with\n  | 0 => Some mu\n  | S new_size =>\n    match (NatMap.find block mu) with\n    | None => None\n    | Some l =>\n      match ((S offset) =? block_size) with\n      | true => set_all_zeroes (NatMap.add block (NatMap.add offset (memory_value_data (data_value 0)) l) mu) (S block) 0 block_size new_size\n      | false => set_all_zeroes (NatMap.add block (NatMap.add offset (memory_value_data (data_value 0)) l) mu) block (S offset) block_size new_size\n      end\n    end\n  end.\nDefinition reinitialize_memory (e: raw_enclave_ID) (state: enclave_state) (mu: memory): option memory :=\n  match state with\n  | enclave_state_value _ E =>\n    match (NatMap.find e E) with\n    | None => None\n    | Some mem_range =>\n      match mem_range with\n      | enclave_address_and_data l n =>\n        match l with\n        | address block offset =>\n          match (NatMap.find block mu) with\n          | None => None\n          | Some x => set_all_zeroes mu block offset (length (NatMapProperties.to_list x)) n\n          end\n        end\n      end\n    end\n  end.", "meta": {"author": "jmcmah10", "repo": "Isolated-Execution-Coq", "sha": "878f5eb3bd9fb7baff83ad2dbde0b395070ebe41", "save_path": "github-repos/coq/jmcmah10-Isolated-Execution-Coq", "path": "github-repos/coq/jmcmah10-Isolated-Execution-Coq/Isolated-Execution-Coq-878f5eb3bd9fb7baff83ad2dbde0b395070ebe41/AppendixF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.28981682398922787}}
{"text": "(**************************************************************************)\n(*   Mechanised Framework for Local Interactions & Distributed Algorithms *)\n(*   T. Balabonski, P. Courtieu, R. Pelle, 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(**************************************************************************)\n(**  Mechanised Framework for Local Interactions & Distributed Algorithms   \n     T. Balabonski, P. Courtieu, R. Pelle, 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.\nRequire Import List SetoidList.\nRequire Import Decidable.\nRequire Import Setoid Equalities Morphisms.\nRequire Import Compare_dec FinFun.\nRequire Import ZArith Arith_base Arith.Div2 Lia Psatz.\nRequire Import Pactole.Models.NoByzantine.\nRequire Import Pactole.CaseStudies.Exploration.Definitions.\n\n\nOpen Scope list_scope.\nSet Implicit Arguments.\nTypeclasses eauto := (bfs).\n\nSection Tower.\n\n(** Given an abitrary ring *)\nContext {RR : RingSpec}.\n(** There are kG good robots and no byzantine ones. *)\nVariable kG : nat.\nInstance Robots : Names := Robots kG 0.\n\n(** Assumptions on the number of robots: it is non zero and strictly divides the ring size. *)\nHypothesis kdn : (ring_size mod kG = 0)%nat.\nHypothesis k_inf_n : (kG < ring_size)%nat.\n\n(** There is no byzantine robot. *)\nInstance NoByz : NoByzantine.\nProof using . now split. Qed.\n\nDefinition origin : location := of_Z 0.\n\nNotation \"!! config\" := (@obs_from_config _ _ _ _ multiset_observation config origin) (at level 0).\nNotation execute := (execute (UpdFun := UpdFun)).\n\n(** In order to prove that at least one position is occupied, we define the list of positions. *)\nDefinition Vlist := Identifiers.enum ring_size.\n\nLemma Vlist_NoDup : NoDupA equiv Vlist.\nProof using . rewrite NoDupA_Leibniz. apply enum_NoDup. Qed.\n\nLemma Vlist_length : length Vlist = ring_size.\nProof using . apply enum_length. Qed.\n\n(** As there is strictly less robots than location, there is an empty location. *)\nLemma ConfigExistsEmpty : forall config, ¬ (∀ pt, In pt (!! config)).\nProof using k_inf_n kdn.\ngeneralize k_inf_n; intros Hkin config Hall.\nassert (Hsize : size (!! config) < ring_size).\n{ apply le_lt_trans with (cardinal (!! config)).\n  - apply size_cardinal.\n  - cut (cardinal (!! config) = kG); try lia; [].\n    change (cardinal (make_multiset (List.map get_location (config_list config))) = kG).\n    rewrite cardinal_make_multiset, config_list_spec, map_map, map_length.\n    rewrite names_length. simpl. lia. }\nassert (Hle : ring_size <= size (!! config)).\n{ rewrite size_spec.\n  assert (Hobs : forall pt, InA equiv pt (support (!! config))).\n  { intro pt. specialize (Hall pt). now rewrite support_spec. }\n  rewrite <- Vlist_length.\n  apply (Preliminary.inclA_length setoid_equiv).\n  - apply Vlist_NoDup.\n  - repeat intro. apply Hobs. }\nlia.\nQed.\n\nLemma Stopped_same : forall e, Stopped e -> e == Stream.tl e.\nProof using .\ncofix Hcoind. intros e Hstop. constructor.\n+ clear Hcoind. apply Hstop.\n+ apply Hcoind. apply Hstop.\nQed.\n\nLemma Will_stop_tl : forall e, Will_stop e -> Will_stop (Stream.tl e).\nProof using .\nintros e He. induction He.\n+ left. match goal with H : Stopped _ |- _ => apply H end.\n+ right. apply IHHe.\nQed.\n\n(** No algorithm can stop on a starting configuration. *)\nTheorem no_stop_on_starting_config : forall r d config,\n  Fair d ->\n  Explore_and_Stop r ->\n  Valid_starting_config config ->\n  ~Stopped (execute r d config).\nProof using k_inf_n kdn.\nintros r d config.\ngeneralize (@reflexivity execution equiv _ (execute r d config)).\ngeneralize (execute r d config) at -2.\nintros e Heqe Hfair Hsol Hvalid Hsto.\ndestruct (Hsol d config Hfair Hvalid) as [Hvisit Hstop].\nassert (Hfalse :=  ConfigExistsEmpty config).\n(* TODO: remove the use of classical logic: everything is decidable here *)\napply Logic.Classical_Pred_Type.not_all_ex_not in Hfalse.\ndestruct Hfalse as [loc Hfalse].\nspecialize (Hvisit loc).\nrewrite <- Heqe in *.\ninduction Hvisit.\n+ rewrite Heqe in *.\n  match goal with H : Stream.instant _ _ |- _ => destruct H as [g Hg] end.\n  rewrite (obs_from_config_In config origin) in Hfalse;\n    destruct Hfalse.\n  exists (Good g).\n  apply Hg.\n+ apply IHHvisit.\n  - rewrite <- Heqe. symmetry. now apply Stopped_same.\n  - apply Hsto.\n  - now apply Will_stop_tl.\nQed.\n\n(** In particular, there is a tower on any final configuration. *)\nLemma tower_on_final_config : forall r d config,\n  Fair d ->\n  Explore_and_Stop r ->\n  Stopped (execute r d config) ->\n  exists loc, ((!! config)[loc] > 1)%nat.\nProof using k_inf_n kdn.\nintros r d config Hfair Hsol Hstop.\nassert (Hequiv := @no_stop_on_starting_config r d config Hfair Hsol).\nassert (Hvalid : ~Valid_starting_config config) by tauto.\napply config_not_injective in Hvalid.\ndestruct Hvalid as [id [id' [Hid Heq]]].\nexists (config id).\nassert (Hobs := obs_from_config_spec config origin (config id)).\nassert (Hperm : exists l, PermutationA equiv (config_list config) (config id :: config id' :: l)).\n{ assert (Hin : List.In id names) by apply In_names.\n  assert (Hin' : List.In id' names) by apply In_names.\n  assert (Hperm : exists l, PermutationA eq names (id :: id' :: l)).\n  { rewrite <- InA_Leibniz in Hin, Hin'.\n    apply PermutationA_split in Hin; autoclass; [].\n    destruct Hin as [l' Hperm']. rewrite Hperm', InA_cons in Hin'.\n    destruct Hin' as [| Hin']; try congruence; [].\n    apply PermutationA_split in Hin'; autoclass; [].\n    destruct Hin' as [l Hperm]. exists l. now rewrite Hperm', Hperm. }\n  destruct Hperm as [l Hperm].\n  exists (List.map config l).\n  now rewrite config_list_spec, Hperm. }\ndestruct Hperm as [l Hperm].\nrewrite Hobs.\n(* FIXME: why does [rewrite Hperm] fail here? *)\nrewrite (countA_occ_compat _ equiv_dec _ _ (reflexivity (config id))\n          (PermutationA_map _ _ Hperm)).\nsimpl List.map. rewrite List.map_id. unfold Datatypes.id. simpl.\nrepeat destruct_match; solve [lia | exfalso; auto].\nQed.\n\nLemma exec_stopped r : forall d c, Fair d -> Will_stop (execute r d c) ->\n  exists d' c', Fair d'/\\ Stopped (execute r d' c').\n(*exists e, exec_r_comp e r /\\ Stopped e.*)\nProof using .\nintros d' config' Hfair Hstop.\nremember (execute r d' config') as e'.\nrevert Heqe'.\nrevert d' config' Hfair.\ninduction Hstop as [e' Hstop | e' Hstop IHstop].\n+ intros d' config' Hfair Heq.\n  exists d', config'; now rewrite Heq in *.\n+ intros d' config' Hfair Heq.\n  apply (IHstop (Stream.tl d') (Stream.hd (Stream.tl e'))).\n  - destruct Hfair as [_ Hfair]. constructor; apply Hfair.\n  - now rewrite Heq, execute_tail.\nQed.\n\nLemma no_exploration_k_inf_2 : forall r d config,\n  Fair d ->\n  Explore_and_Stop r ->\n  Valid_starting_config config ->\n  (kG > 1)%nat.\nProof using k_inf_n kdn.\nintros r d config Hfair Hsol Hvalid.\nassert (Hexr := exec_stopped r).\nassert (Htower := tower_on_final_config).\ndestruct (Hsol d config Hfair Hvalid) as [Hvisit Hstop].\ndestruct (Hexr d config Hfair Hstop) as [d' [config' [Hfair' Hstop']]].\nspecialize (Htower r d' config' Hfair' Hsol Hstop').\ndestruct Htower.\nassert (Hcard := cardinal_lower x (!! config')).\nrewrite cardinal_obs_from_config in Hcard.\nunfold nG, nB in *.\nunfold Robots in *. simpl in *. lia.\nQed.\n\nEnd Tower.\n\n(* Prefer not to leave this here, so that make -vos does not fail here.\nSee Tower_Assumptions.v *)\n(* Print Assumptions no_exploration_k_inf_2. *)\n\n(*\n(** Stronger result: in any successful sequential execution,\n    the last starting configuration was seen at least [ring_size - kG + 1] rounds ago. *)\n\nFixpoint last_init_conf (l : list configuration) (a : configuration) :=\n  match l with\n  | nil => (False, nil)\n  | config :: l' => if a =?= config\n                    then (((List.Forall (fun x => ~ Valid_starting_config x ) l')\n                          /\\ Valid_starting_config a),l')\n                    else last_init_conf l' a\n  end.\n\n(* Definition SequencialExecution (e : execution) : Prop :=\n  Stream.forever\n    (fun e' => forall r d conf,\n         e' == execute r d conf /\\\n         (exists id, forall id', id' <> id /\\ step (Stream.hd d) id' (conf id')\n                                              = Moving false)) e. *)\nDefinition SequencialExecution : execution -> Prop :=\n  Stream.forever (Stream.instant\n    (fun config => forall da, exists id, forall id', id' <> id -> activate da id' = false)).\n\nFixpoint Biggest_list_of_exe (l : list configuration) (e : execution) : Prop :=\n  match l with\n  | nil => Stopped e\n  | x :: nil => x == Stream.hd e /\\ Stopped e\n  | x :: y => x == Stream.hd e /\\ ~ Stream.hd e == Stream.hd (Stream.tl e)\n                               /\\  Biggest_list_of_exe y (Stream.tl (Stream.tl e))\n  end.\n\n(* Lemma stop_tl : forall e, Stopped e -> Stopped (Stream.tl e).\nProof. intros e He. apply He. Qed. *)\n\nTheorem TowerOnFinalConf : forall l r d config (e : execution) x,\n    Valid_starting_config config ->\n    e == execute r d config ->\n    Biggest_list_of_exe l e ->\n    let (P, l') := last_init_conf l config in\n    P ->\n    Explore_and_Stop r ->\n    SequencialExecution e ->\n    (forall config, List.In config l' ->\n       exists pt, (!! config)[pt] = x -> (1 < x)%nat  -> (x < kG)%nat) ->\n    (ring_size - kG + 1 <= length l')%nat.\nProof.\nintros l r d config e x Hconfig Heq_e Hlist.\ndestruct (last_init_conf l config) as (P, l') eqn : Hlic.\nintros HP Hvalid Hsequ Hl_conf.\nassert ((length l' < ring_size - kG + 1)%nat\n       -> False).\n{ intros Hf.\n  unfold last_init_conf in Hlic.\n  induction l.\n  * simpl in *.\n    rewrite surjective_pairing in Hlic.\n    simpl in *.\n    assert (P = fst (P, l')) by intuition.\n    rewrite <- Hlic in *.\n    simpl in *.\n    now rewrite <- H.\n  * destruct (config =?=  a).\n    + assert (HeqP : P = fst (P, l')) by intuition.\n      assert (l' = snd (P, l')) by intuition.\n      rewrite <- Hlic in *; cbn -[equiv] in *.\n      rewrite HeqP in HP.\n      intuition.\n      assert (Valid_starting_config a).\n      { revert_one @equiv. intro Heq. now rewrite <- Heq. }\n      destruct (last_init_conf l) eqn : Hl.\n      \n    split.\n    - intros.\n      destruct Hsequ.\n      specialize (H0 r d conf). \n      destruct H0 as (He_conf, (id,Hid)).\n      destruct l eqn : Hl.\n    - simpl in *.\n      destruct (Hvalid c Hconf) as (Hvisit, Hstop).\n      assert (Hfalse :=  ConfExistsEmpty c).\n      unfold is_visited in *.\n      rewrite Heq_e in Hlist.\n      now generalize (test Hvalid Heq_e Hconf Hlist).\n    - destruct l0 eqn : Hl'.\n       + simpl in *.\n         destruct Hlist as (Hceq, Hstp).\n         generalize (test Hvalid Heq_e Hconf).\n         intros Htest.\n         assert (Hval_t: ValidStartingConf t).\n         rewrite Hceq.\n         rewrite Heq_e.\n         now simpl in *.\n         assert (He_eq : eeq e (execute r d t)).\n         rewrite Hceq.\n         now rewrite Heq_e.\n         generalize (test Hvalid He_eq Hval_t).\n         intros Htest'.\n         destruct Htest.\n         now rewrite <- Heq_e.\n       + destruct (Classical_Prop.classic (ValidStartingConf (last (t :: t0 :: l1) c)))\n           as [Hv|Hnv].\n         simpl in *.\n         destruct ( Config.eq_dec (Stream.hd e) (Stream.hd (Stream.tl (Stream.tl e))));\n           try easy.\n         destruct Hlist as (Hceq, Hlist).\n         assert (Hse : ~Stopped e).\n         intros Hs.\n         destruct Hs as (Hse, Hs).\n         now unfold stop_now in Hse.\n         destruct l1.\n         * destruct (Classical_Prop.classic\n                       (ValidStartingConfSolExplorationStop\n                       r (Stream.tl (Stream.tl d)))) as [Hvrd|Hnvrd].\n           assert (Heeq_to : eeq (Stream.tl (Stream.tl e)) (execute r (Stream.tl (Stream.tl d)) t0)).\n           { rewrite Heq_e.\n             destruct Hlist as (Hlist, Hstp).\n             rewrite Heq_e in Hlist.\n             repeat rewrite execute_tail in *.\n             apply execute_compat; try easy.\n           }\n           destruct (test Hvrd Heeq_to Hv).\n           now rewrite <- Heeq_to.\n           unfold ValidStartingConfSolExplorationStop in *.\n           apply Classical_Prop.NNPP.\n           intro.\n           apply Hnvrd.\n           intros.\n           destruct (Hvrd t0 Hv).  Heeq_to).\n           admit.\n         apply Classical_Pred_Type.not_all_not_ex.\n         intros Hf.\n         destruct Hnv.\n         unfold ValidStartingConf.\n         intros (ex, Hex).\n         now specialize (Hf ex).\nQed.\n *)\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/CaseStudies/Exploration/Tower.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.28981157444176464}}
{"text": "From ITree Require Import ITree.\nFrom compcert Require Coqlib.\nFrom Paco Require Import paco.\n\nRequire Import List.\nRequire Import Arith ZArith Lia.\n\nRequire Import sflib.\nRequire Import Axioms StdlibExt IntegersExt.\n\nRequire Import SysSem.\nRequire Import IPModel DiscreteTimeModel.\nRequire Import NWSysModel.\nRequire Import RTSysEnv SyncSysModel.\nRequire Import AbstAsyncSysModel AbstMW.\n\nRequire Import FMSim.\n\nGeneralizable Variable sysE.\nSet Nested Proofs Allowed.\n\n\n\nLtac inv_valid_delay :=\n  match goal with\n  | H: valid_delay_added _ _ |- _ => inv H\n  end.\n\n\n\n\nModule MCastIDProps.\n  Section MCAST_ID.\n    Context `{sysE: Type -> Type}.\n    Context `{SystemEnv}.\n\n    Definition mcm_pending (nw: NW.t)\n               (nip mip: ip_t) : Prop :=\n      In (mip, nip) (map fst (NW.mcast_msg_pool nw)).\n\n    Definition mcm_active (nw: NW.t)\n               (nip mip: ip_t): Prop :=\n      In (mip, nip) (NW.mcast_groupinfo nw).\n\n    Inductive mcast_id_domain (nw: NW.t)\n              (nip: ip_t) (mids: list Tid): Prop :=\n      MCastIDDomain\n        mips\n        (MCAST_IPS: Forall2 mcast_id_ip mids mips)\n        (PENDING_INCL:\n           forall mip'\n             (MCM_PENDING: mcm_pending nw nip mip'),\n             In mip' mips)\n        (ACTIVE_INCL:\n           forall mip'\n             (MCM_ACTIVE: mcm_active nw nip mip'),\n             In mip' mips)\n    .\n\n    Inductive mcast_id_in_nw (nw:NW.t)\n              (nip: ip_t) (mids: list Tid): Prop :=\n      MCastIDInNW\n        mips\n        (MCAST_IPS: Forall2 mcast_id_ip mids mips)\n        (MCMS_IN_NW:\n           Forall (mcm_pending nw nip \\1/ mcm_active nw nip) mips)\n    .\n\n    Inductive mcast_id_active (nw:NW.t)\n              (nip: ip_t) (mids: list Tid): Prop :=\n      MCastIDActive\n        mips\n        (MCAST_IPS: Forall2 mcast_id_ip mids mips)\n        (MCMS_ACTIVE:\n           Forall (mcm_active nw nip) mips)\n        (MCMS_INCLUSIVE:\n           forall mip'\n             (MCM_ACTIVE: mcm_active nw nip mip'),\n             In mip' mips)\n        (NO_PENDING:\n           forall mip'\n             (MCM_PENDING: mcm_pending nw nip mip'),\n             False)\n    .\n\n    Lemma mcast_id_active_impl_domain\n          nw nip mids\n          (ACTIVE: mcast_id_active nw nip mids)\n      : mcast_id_domain nw nip mids.\n    Proof.\n      inv ACTIVE.\n      econs; eauto.\n      i. hexploit NO_PENDING; eauto. ss.\n    Qed.\n\n    Lemma distr_pending\n          nw nw1 dms\n          (DISTR: NW.distr nw = (nw1, dms))\n      : forall ip mip\n          (PENDING: mcm_pending nw ip mip),\n        mcm_pending nw1 ip mip \\/\n        mcm_active nw1 ip mip.\n    Proof.\n      destruct nw as [mcg msg_pl mc_pl]. ss.\n      destruct (partition_map age_delay msg_pl) as [pmp' dpms] eqn: PART_MSG.\n      destruct (partition_map age_delay mc_pl) as [mcmp' mcm_add] eqn: PART_MC.\n      clarify.\n\n      i. r in PENDING. ss.\n      assert (IN_MCAST_POOL: exists dly,\n                 In (mip, ip, dly) mc_pl).\n      { apply in_map_iff in PENDING. des.\n        destruct x as [[? ?] ?]. ss. clarify.\n        esplits; eauto. }\n      des.\n\n      destruct dly as [| dly'].\n      - (* delay = 0 *)\n        right. r. ss.\n        assert (IN_NEW_ENTRIES: In (mip, ip) mcm_add).\n        { eapply in_partition_map_r1; try apply PART_MC; eauto. }\n        apply NW.join_spec. eauto.\n      - (* delay > 0 *)\n        left. r. ss.\n        apply in_map_iff.\n\n        hexploit in_partition_map_l1; try apply PART_MC; eauto.\n        { ss. }\n        i. esplits; eauto. ss.\n    Qed.\n\n    Lemma distr_active\n          nw nw1 dms\n          (DISTR: NW.distr nw = (nw1, dms))\n      : forall ip mip\n          (ACTIVE: mcm_active nw ip mip),\n        mcm_active nw1 ip mip.\n    Proof.\n      destruct nw as [mcg msg_pl mc_pl]. ss.\n      destruct (partition_map age_delay msg_pl) as [pmp' dpms] eqn: PART_MSG.\n      destruct (partition_map age_delay mc_pl) as [mcmp' mcm_add] eqn: PART_MC.\n      clarify.\n\n      i. r in ACTIVE. ss.\n      r. ss.\n      apply NW.join_spec. eauto.\n    Qed.\n\n    Lemma distr_pending_inv\n          nw nw1 dms\n          (DISTR: NW.distr nw = (nw1, dms))\n      : forall ip mip\n          (PENDING: mcm_pending nw1 ip mip),\n        mcm_pending nw ip mip.\n    Proof.\n      destruct nw as [mcg msg_pl mc_pl]. ss.\n      destruct (partition_map age_delay msg_pl) as [pmp' dpms] eqn: PART_MSG.\n      destruct (partition_map age_delay mc_pl) as [mcmp' mcm_add] eqn: PART_MC.\n      clarify.\n\n      i. r in PENDING. ss.\n      r. ss.\n\n      eapply in_map_iff in PENDING. des.\n      destruct x. ss. clarify.\n\n      hexploit in_partition_map_l2; try apply PART_MC; eauto.\n      i. des.\n      destruct a as [[? ?] ?]. ss. desf.\n      apply in_map_iff. esplits; eauto. ss.\n    Qed.\n\n\n    Lemma distr_active_inv\n          nw nw1 dms\n          (DISTR: NW.distr nw = (nw1, dms))\n      : forall ip mip\n          (ACTIVE: mcm_active nw1 ip mip),\n        mcm_active nw ip mip \\/ mcm_pending nw ip mip.\n    Proof.\n      destruct nw as [mcg msg_pl mc_pl]. ss.\n      destruct (partition_map age_delay msg_pl) as [pmp' dpms] eqn: PART_MSG.\n      destruct (partition_map age_delay mc_pl) as [mcmp' mcm_add] eqn: PART_MC.\n      clarify.\n\n      i. r in ACTIVE. ss.\n      assert (EITHER: In (mip, ip) mcg \\/\n                      In (mip, ip) mcm_add).\n      { apply NW.join_spec. ss. }\n      destruct EITHER as [IN|IN].\n      - left. r. ss.\n      - right. r. ss.\n\n        hexploit in_partition_map_r2; try apply PART_MC; eauto.\n        i. des.\n        destruct a as [[? ?] ?]. ss. desf.\n        apply in_map_iff. esplits; eauto. ss.\n    Qed.\n\n    Lemma mcast_id_domain_distr\n          nw mids nw1 dms ip\n          (INCL: mcast_id_domain nw ip mids)\n          (DISTR: NW.distr nw = (nw1, dms))\n      : mcast_id_domain nw1 ip mids.\n    Proof.\n      inv INCL.\n      econs; eauto.\n      - i. hexploit distr_pending_inv; eauto.\n      - i. hexploit distr_active_inv; eauto.\n        destruct 1; eauto.\n    Qed.\n\n    Lemma mcast_id_in_nw_distr\n          nw mids nw1 dms ip\n          (INCL: mcast_id_in_nw nw ip mids)\n          (DISTR: NW.distr nw = (nw1, dms))\n      : mcast_id_in_nw nw1 ip mids.\n    Proof.\n      inv INCL.\n      econs; eauto.\n      apply Forall_forall.\n      intros x IN.\n      rewrite Forall_forall in MCMS_IN_NW.\n      hexploit MCMS_IN_NW; eauto.\n      destruct 1.\n      + hexploit distr_pending; eauto.\n      + hexploit distr_active; eauto.\n    Qed.\n\n    Lemma mcast_id_active_distr\n          nw mids nw1 dms ip\n          (INCL: mcast_id_active nw ip mids)\n          (DISTR: NW.distr nw = (nw1, dms))\n      : mcast_id_active nw1 ip mids.\n    Proof.\n      inv INCL.\n      econs; eauto.\n      - eapply Forall_impl.\n        2: { eauto. }\n        i. eapply distr_active; eauto.\n      - i. hexploit distr_active_inv; eauto.\n        destruct 1; eauto.\n        hexploit NO_PENDING; eauto. ss.\n      - i. hexploit distr_pending_inv; eauto.\n    Qed.\n\n    Lemma gather_active\n          nw1 ip mip\n          ps nw'\n          (GATHER: NW.gather nw1 ps nw')\n          (ACTIVE: mcm_active nw1 ip mip)\n      : mcm_active nw' ip mip.\n    Proof.\n      inv GATHER.\n      r. ss.\n    Qed.\n\n    Lemma gather_pending\n          nw1 ip mip\n          ps nw'\n          (GATHER: NW.gather nw1 ps nw')\n          (PENDING: mcm_pending nw1 ip mip)\n      : mcm_pending nw' ip mip.\n    Proof.\n      inv GATHER.\n      r in PENDING. r. ss.\n      rewrite map_app.\n      apply in_or_app. left. ss.\n    Qed.\n\n    Lemma gather_active_inv\n          nw1 ip mip\n          ps nw'\n          (GATHER: NW.gather nw1 ps nw')\n          (ACTIVE: mcm_active nw' ip mip)\n      : mcm_active nw1 ip mip.\n    Proof.\n      inv GATHER.\n      r in ACTIVE. ss.\n    Qed.\n\n    Lemma gather_pending_inv\n          nw1 ip mip\n          ps nw'\n          (GATHER: NW.gather nw1 ps nw')\n          (PENDING: mcm_pending nw' ip mip)\n      : mcm_pending nw1 ip mip \\/\n        In (Packet.MCast (mip, ip)) ps.\n    Proof.\n      inv GATHER.\n      unfold mcm_pending in *. ss.\n      rewrite map_app in PENDING.\n      apply in_app_or in PENDING.\n      destruct PENDING as [IN | IN].\n      { eauto. }\n\n      right.\n      cut (In (mip, ip) mcms_new).\n      { i. eapply in_partition_map_r2 in CLASSIFY; eauto.\n        unfold id in CLASSIFY.\n        des. clarify. }\n      clear - IN VALID_DELAYS_MCMS.\n\n      apply in_map_iff in IN.\n      destruct IN as (x & EQ & IN).\n      apply In_nth_error in IN. des.\n\n      rewrite Forall2_nth in VALID_DELAYS_MCMS.\n      specialize (VALID_DELAYS_MCMS n).\n      rewrite IN in VALID_DELAYS_MCMS.\n      inv VALID_DELAYS_MCMS.\n\n      inv_valid_delay. ss. clarify.\n      eapply nth_error_In; eauto.\n    Qed.\n\n  End MCAST_ID.\nEnd MCastIDProps.\n\n\n\nSection PROOF.\n  Import AbstMW.\n  Import MCastIDProps.\n\n  Context {sysE: Type -> Type}. (* {msgT: Set}. *)\n  (* Context `{rnws_params}. *)\n  Context `{SystemEnv}.\n\n  Let msgT: Set := bytes.\n  Variable nodes: list (@SNode.t sysE msgT).\n  Let num_nodes: nat := length nodes.\n\n  Variable tm_init: nat.\n  Hypothesis TASK_IPS_LENGTH: num_tasks = num_nodes.\n  Hypothesis TM_INIT_SYTM: Nat.divide period (tm_init + max_clock_skew).\n\n  Let PERIOD_COND: 2 * max_clock_skew + max_nw_delay + max_wait_delay < period.\n  Proof.\n    apply period_cond.\n  Qed.\n\n  (* Hypothesis WF_NODES: *)\n  (*   List.Forall (SNode.wf imcasts) nodes. *)\n\n  Let sys_src := AASys.as_dsys nodes tm_init.\n  Let sys_tgt := NWSys.as_dsys\n                   (imap AbstMW.as_node 0 nodes) tm_init.\n                   (* (map (uncurry (AbstMW.as_node)) *)\n                   (*      (attach_index nodes)) tm_init. *)\n  (* move *)\n\n\n  Lemma pm_pool_ip_neq\n        pm (ips: list ip_t)\n        (pmp: list (ip_t * Packet.msg_t * nat)) ip\n        (VD: Forall2 valid_delay_added (map (fun x => (x, pm)) ips) pmp)\n        (NOT_IP: Forall (fun x => x <> ip) ips)\n    : forall ip' pm' (IN: In (ip', pm') (map fst pmp)),\n      ip' <> ip.\n  Proof.\n    i. apply in_map_iff in IN.\n    destruct IN as [[[ip2 pm2] dly] [? IN1]].\n    ss. clarify.\n    apply In_nth_error in IN1. des.\n\n    rewrite Forall2_nth in VD.\n    specialize (VD n).\n    rewrite IN1 in VD.\n\n    cut (nth_error ips n = Some ip').\n    { intro IPS_NTH.\n      assert (IP_NEQ': ip' <> ip).\n      { rewrite Forall_forall in NOT_IP.\n        apply NOT_IP.\n        eapply nth_error_In; eauto. }\n\n      unfold Node.chget_pm_by_dest. ss.\n    }\n\n    inv VD.\n    match goal with\n    | H: _ = nth_error (map ?f _) _,\n         H': valid_delay_added _ _\n      |- _ =>\n      inv H'; symmetry in H;\n        eapply map_nth_error_iff in H; eauto\n    end.\n    des. clarify.\n  Qed.\n\n\n  Inductive match_pkt\n            (sytm: nat) (tid_s: Tid)\n    : (Tid * msgT)? -> Packet.t? -> Prop :=\n  | MatchPkt_None\n    : match_pkt sytm tid_s None None\n  | MatchPkt_MCast\n      mid mip tip\n      (MCAST_MEMBER: mcast_member tid_s mid)\n      (MCAST_ID_IP: mcast_id_ip mid mip)\n      (TASK_ID_IP: task_id_ip tid_s tip)\n    : match_pkt sytm tid_s None (Some (inr (mip, tip)))\n  | MatchPkt_Some\n      tid_d rmsg\n      ip_s ip_d\n      pld pm\n      (RANGE_SYTM: IntRange.uint64 sytm)\n      (LENGTH_RMSG: length rmsg = msg_size)\n      (IP_SENDER: task_id_ip tid_s ip_s)\n      (IP_DEST: dest_id_ip tid_d ip_d)\n      (SRL_MSG: serialize_msg sytm tid_s rmsg = pld)\n      (PACKET_MSG: pm = Packet.mkMsg ip_s ip_d port pld)\n    : match_pkt sytm tid_s (Some (tid_d, rmsg)) (Some (inl pm))\n  .\n\n  Section AUX_MSGS_TO.\n\n    Definition aux_msgs_to (mcg: list Packet.mcm_t)\n               (ip: ip_t)\n               (op: Packet.t?)\n    : Packet.msg_t? :=\n      match op with\n      | Some (inl pm) =>\n        let ip_d := Packet.dest_ip pm in\n        if (ip_d =? ip)%nat then Some pm else\n          if existsb (fun x => andb (fst x =? ip_d)\n                                 (snd x =? ip)) mcg then\n            Some pm else None\n      | _ => None\n      end.\n\n\n    Lemma match_pkt_tgt_Some_impl\n          nw mcg ip mids\n          sytm tid_s tid_r\n          out_src out_tgt pm\n          (TASK_ID_IP: task_id_ip tid_r ip)\n          (AUX_TGT: aux_msgs_to mcg ip out_tgt = Some pm)\n          (MATCH: match_pkt sytm tid_s out_src out_tgt)\n          (MCAST_GROUP: NW.mcast_groupinfo nw = mcg)\n          (WF_MCG: Forall Packet.mcm_wf mcg)\n          (* (ACTIVE: mcast_id_active nw ip mids) *)\n          (MCAST_OF_TID: mids = get_mcast_of tid_r)\n          (MC_DOM: mcast_id_domain nw ip mids)\n      : <<OUT_TGT_EQ: out_tgt = Some (inl pm)>> /\\\n        exists tid_d msg,\n        <<OUT_SRC_EQ: out_src = Some (tid_d, msg)>> /\\\n        <<OUT_SRC_F: AANode.get_msg_by_dest tid_r out_src = [msg]>>\n    .\n    Proof.\n      guardH MCAST_OF_TID.\n      destruct out_tgt as [p|]; ss.\n      destruct p as [pm'|?]; ss.\n      desf.\n      - split; ss.\n        inv MATCH; ss.\n\n        assert (ip_d = ip).\n        { apply beq_nat_true. ss. }\n        subst ip_d.\n\n        assert (tid_d = tid_r).\n        { eapply dest_id_ip_inv_det; eauto.\n          inv TASK_ID_IP. r.\n          unfold dest_ips.\n          rewrite nth_error_app1; eauto.\n          eapply nth_error_Some. congruence. }\n        subst tid_d.\n\n        esplits; ss.\n        rewrite Nat.eqb_refl. ss.\n\n      - split; ss.\n        inv MATCH; ss.\n        esplits; ss.\n\n        assert (IN_MCG: In (ip_d, ip) (NW.mcast_groupinfo nw)).\n        { match goal with\n          | H: existsb _ _ = true |- _ =>\n            rename H into EXISTSB\n          end.\n\n          apply existsb_exists in EXISTSB.\n          destruct EXISTSB as [[mip_e nip_e] [A B]].\n          ss.\n          apply Bool.andb_true_iff in B. des.\n          rewrite Nat.eqb_eq in *. clarify.\n        }\n\n        (* unfold filter_by_dest, chget_by_dest. ss. *)\n        rewrite <- MCAST_OF_TID.\n        cut (In tid_d mids).\n        { intro IN_MIDS.\n          cut (existsb (Nat.eqb tid_d) mids = true).\n          { intro T. rewrite T.\n            rewrite Bool.orb_true_r. ss. }\n\n          apply existsb_exists.\n          esplits.\n          { eauto. }\n          apply Nat.eqb_refl.\n        }\n\n        assert (IP_D_MCAST: IP.mcast_ip ip_d).\n        { rewrite Forall_forall in WF_MCG.\n          hexploit WF_MCG; eauto.\n          inversion 1. clarify. }\n\n        (* inv ACTIVE. *)\n        inv MC_DOM.\n        r in IP_DEST.\n\n        assert (MCAST_ID_IP_D: mcast_id_ip tid_d ip_d).\n        { unfold dest_ips in IP_DEST.\n          destruct (lt_ge_dec tid_d num_tasks).\n          - exfalso.\n            rewrite nth_error_app1 in IP_DEST by ss.\n            apply nth_error_In in IP_DEST.\n            hexploit task_ips_not_mcast; eauto.\n            i. congruence.\n          - rewrite nth_error_app2 in IP_DEST by ss.\n            r. exists (tid_d - num_tasks).\n            splits; ss. nia.\n        }\n\n        hexploit ACTIVE_INCL; eauto.\n        intro IN_IP_D.\n        apply In_nth_error in IN_IP_D. des.\n        rewrite Forall2_nth in MCAST_IPS.\n        specialize (MCAST_IPS n).\n        rewrite IN_IP_D in MCAST_IPS.\n\n        assert (exists tid_d',\n                   <<TID_D': nth_error mids n = Some tid_d'>> /\\\n                   <<MCAST_ID_IP': mcast_id_ip tid_d' ip_d>>).\n        { inv MCAST_IPS. esplits; eauto. }\n        des.\n        cut (tid_d' = tid_d).\n        { i. subst.\n          eapply nth_error_In; eauto. }\n        eapply dest_id_ip_inv_det; eauto.\n        inv MCAST_ID_IP'. des.\n        r. clarify.\n        unfold dest_ips.\n        rewrite nth_error_app2.\n        2: { fold num_tasks. nia. }\n        fold num_tasks.\n        rewrite minus_plus. ss.\n    Qed.\n\n\n    Lemma outs_size_incl_aux\n          nw mcg ip mids\n          sytm tid_r\n          outs_src outs_tgt n\n          (TASK_ID_IP: task_id_ip tid_r ip)\n          (MCAST_GROUP: NW.mcast_groupinfo nw = mcg)\n          (WF_MCG: Forall Packet.mcm_wf mcg)\n          (NODUP_MCG: NoDup mcg)\n          (* (ACTIVE: mcast_id_active nw ip mids) *)\n          (MCAST_OF_TID: mids = get_mcast_of tid_r)\n          (MCAST_DOM: mcast_id_domain nw ip mids)\n          (MATCH_OUTMSGS : iForall2 (match_pkt sytm) n outs_src outs_tgt)\n      : length (filtermap (aux_msgs_to mcg ip) outs_tgt) <=\n        AANode.inbox_sz (map (AANode.get_msg_by_dest tid_r)\n                             outs_src).\n    Proof.\n      depgen outs_src. revert n.\n      guardH MCAST_GROUP.\n      induction outs_tgt as [| h_tgt t_tgt IH]; i; ss.\n      { nia. }\n      destruct outs_src as [| h_src t_src]; ss.\n      { inv MATCH_OUTMSGS. }\n      inv MATCH_OUTMSGS.\n\n      hexploit IH; eauto. intro LEN_IH.\n\n      destruct (aux_msgs_to mcg ip h_tgt) eqn: AUX1; ss.\n      - hexploit match_pkt_tgt_Some_impl; eauto.\n        i. des. clarify.\n        rewrite OUT_SRC_F.\n        unfold AANode.inbox_sz in *. ss. nia.\n      - unfold AANode.inbox_sz in *. ss.\n        rewrite app_length. nia.\n    Qed.\n\n    Lemma aux_msgs_to_equiv\n          mcg outs_tgt ip\n          pms_new mcms_new pmp_new\n          (WF_MCG: Forall Packet.mcm_wf mcg)\n          (NODUP_MCG: NoDup mcg)\n          (IP_LOCAL: IP.local_ip ip)\n          (CLASSIFY: partition_map id (filtermap id outs_tgt) = (pms_new, mcms_new))\n          (VALID_DELAYS: Forall2 valid_delay_added (concat (map (NW.attach_adest mcg) pms_new)) pmp_new)\n      : Node.distr_msgs_to ip (map fst pmp_new) =\n        filtermap (aux_msgs_to mcg ip) outs_tgt.\n    Proof.\n      revert pms_new mcms_new pmp_new CLASSIFY VALID_DELAYS.\n      induction outs_tgt as [| h t IH]; i; ss.\n      { clarify. ss.\n        inv VALID_DELAYS. ss. }\n\n      destruct h as [pkt|]; ss.\n      2: { eauto. }\n      destruct pkt as [pm|mcm]; ss.\n      2: { desf. eauto. }\n\n      destruct (partition_map id (filtermap id t))\n        as [pms_new' mcms_new'] eqn:PART_TL.\n      clarify. ss.\n      eapply Forall2_app_inv_l in VALID_DELAYS.\n      destruct VALID_DELAYS as\n          (pmp_pm & pmp_new' &\n           VALID_DELAY_PM & VALID_DELAYS & PMP_NEW_EQ).\n      hexploit IH; eauto. intro IH_EQ.\n\n      rewrite PMP_NEW_EQ.\n      rewrite map_app.\n      unfold Node.distr_msgs_to.\n      rewrite filtermap_app.\n\n      unfold Node.distr_msgs_to in IH_EQ.\n      rewrite IH_EQ.\n\n      cut (filtermap (Node.chget_pm_by_dest ip) (map fst pmp_pm) =\n           opt2list (aux_msgs_to mcg ip (Some (inl pm)))).\n      { ss. intro R. rewrite R. desf. }\n\n      ss.\n      assert (IP_NOT_MCAST: IP.mcast_ip ip = false).\n      { generalize (IP.normal_mcast_disjoint ip).\n        rewrite IP_LOCAL. ss. }\n\n      destruct (Nat.eqb_spec (Packet.dest_ip pm) ip) as [IP_EQ | IP_NEQ]; ss.\n      { (* unicast *)\n        unfold NW.attach_adest in VALID_DELAY_PM.\n        rewrite IP_EQ in VALID_DELAY_PM.\n        rewrite IP_NOT_MCAST in VALID_DELAY_PM.\n\n        assert (exists dly, pmp_pm = [(ip, pm, dly)]).\n        { inv VALID_DELAY_PM.\n          match goal with\n          | H: valid_delay_added _ _,\n               H': Forall2 _ [] _ |- _ => inv H; inv H'\n          end.\n          esplits; ss.\n        }\n        des. clarify.\n\n        ss. unfold Node.chget_pm_by_dest. ss.\n        rewrite Nat.eqb_refl. ss.\n      }\n\n      desf.\n      { rename Heq into EXISTSB. ss.\n        rewrite existsb_exists in EXISTSB.\n        destruct EXISTSB as [[mip1 ip1] [IN_MCG MEM_IP_EQ]]; ss.\n        apply Bool.andb_true_iff in MEM_IP_EQ. des.\n        apply beq_nat_true in MEM_IP_EQ.\n        apply beq_nat_true in MEM_IP_EQ0.\n        clarify.\n\n        unfold NW.attach_adest in VALID_DELAY_PM.\n        rewrite Forall_forall in WF_MCG.\n        hexploit WF_MCG; eauto. intro WF_MCM.\n        inv WF_MCM.\n        rewrite MCAST_IP in VALID_DELAY_PM.\n\n        assert (IP_IN_ARECV: In ip (NW.get_actual_receivers mcg (Packet.dest_ip pm))).\n        { unfold NW.get_actual_receivers.\n          eapply in_filtermap; eauto. ss.\n          rewrite Nat.eqb_refl. ss.\n        }\n\n        assert (exists ips1 ips2,\n                   <<ARECV_EQ: NW.get_actual_receivers mcg (Packet.dest_ip pm) = ips1 ++ ip :: ips2>> /\\\n                   <<IPS1_NOT_IP: Forall (fun x => x <> ip) ips1>> /\\\n                   <<IPS2_NOT_IP: Forall (fun x => x <> ip) ips2>>).\n        { eapply in_split in IP_IN_ARECV. des.\n          rewrite IP_IN_ARECV.\n          eapply nodup_div in IP_IN_ARECV; eauto.\n          apply NW.get_actual_receivers_nodup; eauto.\n        }\n        des.\n        rewrite ARECV_EQ in VALID_DELAY_PM.\n\n        rewrite map_app in VALID_DELAY_PM.\n        eapply Forall2_app_inv_l in VALID_DELAY_PM.\n\n        destruct VALID_DELAY_PM\n          as (pmp1 & pmp' & FA1 & FA2 & PMP'_EQ).\n        destruct pmp' as [| pmp pmp2]; inv FA2.\n        rewrite map_app. rewrite filtermap_app.\n        replace (pmp::pmp2) with ([pmp] ++ pmp2) by ss.\n        rewrite map_app. rewrite filtermap_app.\n\n        rewrite (filtermap_nil _ _ _ (map fst pmp1)).\n        2: {\n          intros [ip' pm'] IN_FST_PMP1.\n\n          cut (ip' <> ip).\n          { intro NEQ.\n            unfold Node.chget_pm_by_dest. ss.\n            destruct (Nat.eqb_spec ip' ip); ss. }\n          eapply (pm_pool_ip_neq pm ips1); eauto.\n        }\n        rewrite (filtermap_nil _ _ _ (map fst pmp2)).\n        2: {\n          intros [ip' pm'] IN_FST_PMP2.\n          cut (ip' <> ip).\n          { intro NEQ.\n            unfold Node.chget_pm_by_dest. ss.\n            destruct (Nat.eqb_spec ip' ip); ss. }\n          eapply (pm_pool_ip_neq pm ips2); eauto.\n        }\n        ss.\n\n        match goal with\n        | H: valid_delay_added _ _ |- _ => inv H\n        end.\n        unfold Node.chget_pm_by_dest. ss.\n        rewrite Nat.eqb_refl. ss.\n      }\n      rename Heq into EXISTSB.\n\n      ss. unfold NW.attach_adest in VALID_DELAY_PM.\n      destruct (IP.mcast_ip (Packet.dest_ip pm)) eqn: IS_DEST_MCAST.\n      2: {\n        inv VALID_DELAY_PM.\n        match goal with\n        | H: Forall2 _ [] _,\n             H': valid_delay_added _ _ |- _ => inv H; inv H'\n        end.\n        ss. unfold Node.chget_pm_by_dest. ss.\n        destruct (Nat.eqb_spec (Packet.dest_ip pm) ip); ss.\n      }\n\n      cut (Forall (fun x => x <> ip)\n                  (NW.get_actual_receivers mcg (Packet.dest_ip pm))).\n      { intro FA.\n        apply filtermap_nil. i.\n        destruct a as [ip' pm'].\n        hexploit pm_pool_ip_neq; eauto.\n        unfold Node.chget_pm_by_dest. ss.\n        destruct (Nat.eqb_spec ip' ip); ss.\n      }\n\n      apply existsb_false_iff in EXISTSB.\n      apply Forall_forall. intros ip1 IN.\n      unfold NW.get_actual_receivers in IN.\n      ii. subst ip1.\n\n      eapply filtermap_in in IN. des.\n      rewrite Forall_forall in EXISTSB.\n      hexploit EXISTSB; eauto.\n      desf. ss.\n      rewrite Nat.eqb_refl. ss.\n    Qed.\n\n  End AUX_MSGS_TO.\n\n\n  Inductive old_msg (sytm_ub_exc: nat) (pm_old: Packet.msg_t): Prop :=\n    OldMsg\n      sytm_old tid_s bs\n      (* (WF_PMS: Packet.msg_wf pm_old) *)\n      (PORT_EQ: Packet.dest_port pm_old = port)\n      (PARSE_OK:\n         parse_msg (firstn pld_size (Packet.payload pm_old)) =\n         Some (sytm_old, tid_s, bs))\n      (SYTM_OLD: sytm_old < sytm_ub_exc)\n  .\n\n  Lemma old_msg_adv\n        stm1 stm2 pm\n        (OLD: old_msg stm1 pm)\n        (TM_LE: stm1 <= stm2)\n    : old_msg stm2 pm.\n  Proof.\n    inv OLD.\n    econs; eauto. nia.\n  Qed.\n\n  Lemma fetch_msgs_old\n        cbt ms inbs\n        (OLD_MSGS: Forall (old_msg cbt) ms)\n    : List.fold_left\n        (flip (fetch_one_msg cbt)) ms inbs =\n      inbs.\n  Proof.\n    induction ms as [| m ms' IH]; ss.\n    assert (<<OLD_M: old_msg cbt m>> /\\\n                     <<OLD_MSGS': Forall (old_msg cbt) ms'>>).\n    { inv OLD_MSGS. ss. }\n\n    des.\n    assert (FETCH_OLD1: fetch_one_msg cbt m inbs = inbs).\n    { unfold fetch_one_msg.\n      inv OLD_M.\n      unfold parse_pld.\n\n      destruct (Nat.ltb_spec (length (Packet.payload m)) pld_size); ss.\n      rewrite PARSE_OK.\n\n      destruct (Nat.eqb_spec sytm_old cbt); ss.\n      { nia. }\n      destruct (Nat.eqb_spec sytm_old (cbt + period)); ss.\n      { nia. }\n      desf.\n    }\n    unfold flip at 2.\n    rewrite FETCH_OLD1.\n    eapply IH; eauto.\n  Qed.\n\n\n  Definition nw_msgs_to (ip: ip_t) (nw: NW.t)\n    : list Packet.msg_t :=\n    Node.distr_msgs_to\n      ip (map fst (NW.packet_msg_pool nw)).\n\n  Inductive match_inb_pre (sytm: nat)\n            (ip: ip_t) (nw: NW.t)\n            (inbp: list Packet.msg_t)\n            (inbn: list (list msgT)): Prop :=\n    MatchInbPre\n      pms_tot\n      (INBN_LENGTH: length inbn = num_tasks)\n      (PMS_TOT: pms_tot = inbp ++ nw_msgs_to ip nw)\n      (* (SYTM: sytm = get_skwd_base_time period tm) *)\n      (PMS_TOT_OLD: Forall (old_msg (sytm + 2 * period)) pms_tot)\n      (PMS_TOT_LEN: length pms_tot <= AANode.inbox_sz inbn)\n  .\n\n\n  Inductive match_inb\n            (sytm: nat) (* (tid: Tid) *)\n            (inb: list (list msgT))\n            (inbm: list msgT?)\n            (pms: list Packet.msg_t)\n    : Prop :=\n    MatchInbox\n      (INB_LENGTH: length inb = num_tasks)\n      (SIZE_INCL: length (filtermap id inbm) + length pms\n                  <= AANode.inbox_sz inb)\n      (PMS_IN_INB:\n         Forall (fun pm: Packet.msg_t =>\n                   exists tid_s msg inb_r,\n                     <<PORT_EQ: Packet.dest_port pm = port>> /\\\n                     <<PLD_SIZE_EQ: length (Packet.payload pm) = pld_size>> /\\\n                     <<PARSE_OK: parse_msg (Packet.payload pm) =\n                                 Some (sytm, tid_s, msg)>> /\\\n                     <<INB_ROW_EX: nth_error inb tid_s = Some inb_r>> /\\\n                     <<IN_INB_ROW: In msg inb_r>>)\n                pms)\n      (INBM_IN_INB:\n         Forall2 (fun om ms =>\n                    forall m (MSG_EX: om = Some m), In m ms)\n                 inbm inb)\n      (WHEN_INBM_EMPTY:\n         forall tid_s inb_r m\n           (* (TID: IntRange.sint8 tid_s) *)\n           (INB_ROW: nth_error inb tid_s = Some inb_r)\n           (INBM_ROW: nth_error inbm tid_s = Some None)\n           (IN_ROW: In m inb_r)\n         ,\n         exists pm,\n           <<IN_PMS: In pm pms>> /\\\n           <<PORT_EQ: Packet.dest_port pm = port>> /\\\n           <<PLD_SIZE_EQ: length (Packet.payload pm) = pld_size>> /\\\n           <<PARSE_OK: parse_msg (Packet.payload pm) =\n                       Some (sytm, tid_s, m)>>)\n  .\n\n\n  Definition nw_inv (tm: DTime.t)\n             (nw: NW.t) : Prop :=\n    forall sytm_sk\n      (SKWD_SYNC_TIME: Nat.divide period\n                                  (sytm_sk + max_clock_skew))\n      (RANGE_TM: tm <= DTime.of_ns sytm_sk),\n      Forall (fun p => DTime.uadd tm (snd p) <\n                    DTime.of_ns sytm_sk)\n             (NW.packet_msg_pool nw) /\\\n      Forall (fun p => DTime.uadd tm (snd p) <\n                    DTime.of_ns sytm_sk)\n             (NW.mcast_msg_pool nw)\n  .\n\n  Lemma nw_msgs_to_distr\n        ip nw nw1 dms\n        pms_nw pms_nw1 pms_d\n        (DISTR: NW.distr nw = (nw1, dms))\n        (PMS_NW: pms_nw = nw_msgs_to ip nw)\n        (PMS_NW1: pms_nw1 = nw_msgs_to ip nw1)\n        (PMS_D: pms_d = Node.distr_msgs_to ip dms)\n    : length pms_nw = length pms_nw1 + length pms_d /\\\n      (forall pm, In pm pms_nw1 -> In pm pms_nw) /\\\n      (forall pm, In pm pms_d -> In pm pms_nw) /\\\n      (forall pm, In pm pms_nw -> In pm pms_nw1 \\/ In pm pms_d).\n  Proof.\n    destruct nw as [mgs pm_pl mcm_pl]. ss.\n    assert (exists pm_pl1,\n               <<PART_PM_PL: partition_map age_delay pm_pl = (pm_pl1, dms)>> /\\\n               <<PM_PL1_EQ: pm_pl1 = NW.packet_msg_pool nw1>>).\n    { desf. eauto. }\n\n    clear DISTR. des.\n    unfold nw_msgs_to in PMS_NW1.\n    rewrite <- PM_PL1_EQ in PMS_NW1.\n    unfold nw_msgs_to in PMS_NW. ss.\n    clear PM_PL1_EQ. subst.\n\n    revert pm_pl1 dms PART_PM_PL.\n    induction pm_pl as [| h t IH]; i; ss.\n    { clarify. }\n\n    destruct h as [[ip_dest pm] dly]. ss.\n    destruct (partition_map age_delay t) as [pt1 pt2].\n\n    hexploit IH; eauto.\n    clear IH. intros (IH_LEN & IH_IN1 & IH_IN2 & IH_INR).\n\n    destruct dly as [|dly'].\n    - (* delay zero *)\n      clarify.\n      splits.\n      + unfold Node.distr_msgs_to in *. ss.\n        desf. ss.\n        rewrite IH_LEN. ss.\n      + intros pm1 IN1.\n        apply IH_IN1 in IN1.\n        clear - IN1.\n        unfold Node.distr_msgs_to in *. ss.\n        desf. ss. eauto.\n      + intros pm2 IN2.\n        clear - IN2 IH_IN2.\n        unfold Node.distr_msgs_to in *. ss.\n        desf; ss.\n        2: { eapply IH_IN2 in IN2. ss. }\n        des; eauto.\n      + intros pm' INR.\n        clear - INR IH_INR.\n        unfold Node.distr_msgs_to in *. ss.\n        desf; ss.\n        * des; eauto.\n          hexploit IH_INR; eauto.\n          destruct 1; eauto.\n        * des; eauto.\n\n    - (* delay pos *)\n      clarify.\n      splits.\n      + unfold Node.distr_msgs_to in *. ss.\n        desf. ss.\n        rewrite IH_LEN. ss.\n      + intros pm1 IN1.\n        clear - IN1 IH_IN1.\n        unfold Node.distr_msgs_to in *. ss.\n        desf; ss.\n        2: { eapply IH_IN1 in IN1. ss. }\n        des; eauto.\n      + intros pm2 IN2.\n        apply IH_IN2 in IN2.\n        clear - IN2.\n        unfold Node.distr_msgs_to in *. ss.\n        desf. ss. eauto.\n      + intros pm' INR.\n        clear - INR IH_INR.\n        unfold Node.distr_msgs_to in *. ss.\n        desf; ss.\n        * des; eauto.\n          hexploit IH_INR; eauto.\n          destruct 1; eauto.\n        * des; eauto.\n  Qed.\n\n  Lemma pre_filter_port_noeff\n        sytm ip nw inbp inbn\n        nw1 dms\n        (PRE: match_inb_pre sytm ip nw inbp inbn)\n        (DISTR: NW.distr nw = (nw1, dms))\n    : AbstMW.filter_port (Node.distr_msgs_to ip dms) =\n      Node.distr_msgs_to ip dms.\n  Proof.\n    hexploit (nw_msgs_to_distr ip); eauto.\n    intros (LEN_EQ & INCL1 & INCL2 & _).\n    inv PRE.\n\n    unfold AbstMW.filter_port.\n    apply filter_all_ok.\n\n    apply Forall_app_inv in PMS_TOT_OLD.\n    destruct PMS_TOT_OLD as [_ PMS_OLD2].\n    apply Forall_forall.\n    intros pm IN.\n    apply INCL2 in IN.\n    rewrite Forall_forall in PMS_OLD2.\n    apply PMS_OLD2 in IN. inv IN.\n    rewrite Nat.eqb_eq; ss.\n  Qed.\n\n\n  Lemma match_inb_pre_distr\n        sytm nw nw1 dms\n        ip inbp inbn\n        (PRE: match_inb_pre sytm ip nw inbp inbn)\n        (DISTR: NW.distr nw = (nw1, dms))\n    : match_inb_pre\n        sytm ip nw1\n        (inbp ++ AbstMW.filter_port (Node.distr_msgs_to ip dms))\n        inbn.\n  Proof.\n    hexploit pre_filter_port_noeff; eauto.\n    intro FILTER_PORT_NOEFF.\n\n    hexploit (nw_msgs_to_distr ip); eauto.\n    intros (LEN_EQ & INCL1 & INCL2 & _).\n    inv PRE.\n\n    econs; eauto.\n    - eapply Forall_app_inv in PMS_TOT_OLD.\n      destruct PMS_TOT_OLD as [FA_INBP FA_DEST].\n\n      eapply Forall_app.\n      2: {\n        eapply Forall_forall.\n        intros pm IN.\n        eapply Forall_forall; eauto.\n      }\n      eapply Forall_app; eauto.\n      { eapply Forall_forall.\n        intros pm IN.\n        eapply Forall_forall; eauto.\n      }\n    - do 2 rewrite app_length.\n      rewrite app_length in PMS_TOT_LEN. nia.\n  Qed.\n\n\n  Lemma nw_gather_matchinfo\n        tid mids (ip: ip_t)\n        sytm oms ops\n        nw1 nw' inb_m\n        (* (RANGE_SYTM: IntRange.uint64 sytm) *)\n        (WF_NW1: NW.wf nw1)\n        (TASK_ID_IP: task_id_ip tid ip)\n        (MCAST_DOM: mcast_id_domain nw1 ip mids)\n        (MCAST_OF_TID: mids = get_mcast_of tid)\n        (* (LEN_OUTS: length oms = num_tasks) *)\n        (MATCH: iForall2 (match_pkt sytm) 0 oms ops)\n        (GATHER: NW.gather nw1 (filtermap id ops) nw')\n        (INB_TO_MERGE: inb_m = map (AANode.get_msg_by_dest tid) oms)\n    : exists npms_ip,\n      (* Forall (fun pm => In (Packet.Msg pm) (filtermap id ops)) npms_ip /\\ *)\n      (* npms_ip = Node.distr_msgs_to ip (map fst pmp_new) /\\ *)\n      npms_ip = filtermap (aux_msgs_to (NW.mcast_groupinfo nw1) ip) ops /\\\n\n      nw_msgs_to ip nw' =\n      nw_msgs_to ip nw1 ++ npms_ip /\\\n      length npms_ip <= AANode.inbox_sz inb_m /\\\n      (* (AANode.inbox_sz inb_m = 0 -> npms_ip = []) /\\ *)\n      (forall pm (IN: In pm npms_ip),\n          exists tid_s msg inb_r_m,\n            <<PM_PORT: Packet.dest_port pm = port>> /\\\n            (* <<AbstMW.parse_pld (Packet.payload pm) = *)\n            (* Some (sytm, tid_s, msg) /\\  *)\n            <<PLD_SIZE_EQ: length (Packet.payload pm) = pld_size>> /\\\n            <<PARSE_OK: parse_msg (Packet.payload pm) =\n                        Some (sytm, tid_s, msg)>> /\\\n            <<ROW_NTH: nth_error inb_m tid_s = Some inb_r_m>> /\\\n            <<IN_ROW: In msg inb_r_m>>)\n  .\n  Proof.\n    inv GATHER.\n    unfold nw_msgs_to. ss.\n    exists (Node.distr_msgs_to ip (map fst pmp_new)).\n\n    renames oms ops into outs_src outs_tgt.\n\n    assert (AUX_EQ: Node.distr_msgs_to ip (map fst pmp_new) =\n                    filtermap (aux_msgs_to mcg ip) outs_tgt).\n    { inv WF_NW1; ss.\n      eapply aux_msgs_to_equiv; eauto.\n      hexploit task_id_ip_comput; eauto. i. des. ss. }\n\n    splits.\n    - ss.\n    - unfold Node.distr_msgs_to.\n      rewrite map_app.\n      rewrite filtermap_app. ss.\n    - rewrite AUX_EQ.\n      inv WF_NW1. ss.\n      eapply outs_size_incl_aux; eauto; ss.\n    - rewrite AUX_EQ.\n      intros pm IN_AUX.\n      hexploit filtermap_in; eauto.\n      intros (op & IN_OUTS_TGT & AUX_SOME).\n\n      eapply In_nth_error in IN_OUTS_TGT. des.\n      rewrite iForall2_nth in MATCH.\n      specialize (MATCH n).\n      rewrite IN_OUTS_TGT in MATCH. ss.\n\n      assert (exists out_src,\n                 <<OUT_SRC: nth_error outs_src n = Some out_src>> /\\\n                 <<MATCH_PKT: match_pkt sytm n out_src op>>).\n      { inv MATCH.\n        esplits; eauto. }\n      des.\n      hexploit match_pkt_tgt_Some_impl; eauto; ss.\n      { inv WF_NW1. ss. }\n      i. des. clarify.\n      inv MATCH_PKT. ss.\n\n      assert (RANGE_N: IntRange.sint8 n).\n      { cut (n < num_tasks).\n        { i. pose proof range_num_tasks as RANGE_NT.\n          range_stac. }\n        inv IP_SENDER.\n        unfold num_tasks.\n        apply nth_error_Some. congruence.\n      }\n\n      esplits; ss.\n      + erewrite serialize_msg_size_eq; eauto.\n        rewrite LENGTH_RMSG. ss.\n      + apply serialize_parse_msg_inv; eauto.\n      + erewrite map_nth_error; eauto.\n      + ss. rewrite OUT_SRC_F. left. eauto.\n  Qed.\n\n  Lemma match_inb_pre_empty\n        tm ip mw inbp inbn\n        (MATCH_INB_PRE: match_inb_pre tm ip mw inbp inbn)\n    : match_inb_pre tm ip mw [] inbn.\n  Proof.\n    inv MATCH_INB_PRE.\n    econs; eauto.\n    - rewrite Forall_forall in PMS_TOT_OLD.\n      apply Forall_forall. i.\n      eapply PMS_TOT_OLD.\n      apply in_or_app. eauto.\n    - rewrite app_length in PMS_TOT_LEN. ss. nia.\n  Qed.\n\n  Lemma nw_exact_empty\n        (tm: DTime.t)\n        nw cbt\n        (NW_INV: nw_inv tm nw)\n        (EXACT: exact_skwd_base_time period tm = Some cbt)\n    : NW.packet_msg_pool nw = [] /\\ NW.mcast_msg_pool nw = [] /\\\n      NW.distr nw = (nw, []).\n  Proof.\n    eapply exact_skwd_base_time_iff in EXACT.\n    destruct EXACT as (CBT_POS & TM_EQ & CBT_DIV).\n\n    assert (period <= cbt).\n    { r in CBT_DIV. des.\n      destruct z; nia. }\n    hexploit (NW_INV (cbt - max_clock_skew)).\n    { rewrite Nat.sub_add by nia. ss. }\n    { ss. nia. }\n    intros (MSG_PL & MC_PL).\n\n    assert (MSG_POOL_EMPTY: NW.packet_msg_pool nw = []).\n    { destruct (NW.packet_msg_pool nw) as [| h t]; ss.\n      exfalso.\n      inv MSG_PL. nia. }\n\n    assert (MCAST_EMPTY: NW.mcast_msg_pool nw = []).\n    { destruct (NW.mcast_msg_pool nw) as [| h t]; ss.\n      exfalso.\n      inv MC_PL. nia. }\n\n    splits; ss.\n    unfold NW.distr.\n    destruct nw as [mg pmp mcmp]. ss.\n    clarify.\n  Qed.\n\n  Lemma match_inb_pre_nwstep_exact\n        tm sytm nw nw1 dms\n        cbt ops nw' oms\n        ip inbp inbn\n        (* inbn1 *) tid mids inbn'\n        (WF_NW: NW.wf nw)\n        (* (RANGE_SYTM: IntRange.uint64 sytm) *)\n        (TASK_ID_IP: task_id_ip tid ip)\n        (MCAST_ID_DOMAIN: mcast_id_domain nw ip mids)\n        (MCAST_OF_TID: mids = get_mcast_of tid)\n        (PRE: match_inb_pre cbt ip nw inbp inbn)\n        (DISTR: NW.distr nw = (nw1, dms))\n        (NW_INV: nw_inv tm nw)\n        (SYTM_EQ: sytm = cbt + period)\n        (GATHER: NW.gather nw1 (filtermap id ops) nw')\n        (* (WF_OPS: Forall (option_rel1 Packet.wf) ops) *)\n        (LEN_OMS: length oms = num_tasks)\n        (MATCH_MSGS: iForall2 (match_pkt (cbt + period))\n                              0 oms ops)\n        (EXACT: exact_skwd_base_time period tm = Some cbt)\n        (INBN': inbn' = AANode.merge_inbox\n                          AANode.init_inbox\n                          (map (AANode.get_msg_by_dest tid) oms))\n    : match_inb_pre\n        cbt ip nw'\n        (filter_port (Node.distr_msgs_to ip dms)) inbn'.\n  Proof.\n    assert (MCAST_ID_DOMAIN1: mcast_id_domain nw1 ip mids).\n    { eapply mcast_id_domain_distr; eauto. }\n    hexploit match_inb_pre_distr; eauto.\n    intro MATCH_DISTR.\n\n    assert (exists tm_ns, <<TM_EQ: tm = DTime.of_ns tm_ns>> /\\\n                     <<TM_SYNC: tm_ns + max_clock_skew = cbt>> /\\\n                     <<SYNC_DIV: Nat.divide period cbt>>).\n    { apply exact_skwd_base_time_iff in EXACT; eauto.\n      destruct EXACT as (TM_LB & TM_EQ & CBT_DIV).\n      exists (cbt - max_clock_skew).\n      esplits; ss.\n      { apply DTime_units_eq.\n        rewrite TM_EQ. ss. }\n\n      cut (period <= cbt).\n      { nia. }\n      r in CBT_DIV. des. destruct z; nia.\n    }\n    des.\n\n    hexploit nw_exact_empty; eauto.\n    intros (MSG_PL_EMPTY & MCAST_PL_EMPTY & DISTR_EQ).\n    rewrite DISTR_EQ in DISTR. clarify.\n\n    assert (FPM_NIL: Node.distr_msgs_to ip [] = []) by ss.\n    rewrite FPM_NIL in *.\n    rewrite app_nil_r in *.\n\n    inv MATCH_DISTR.\n    hexploit nw_gather_matchinfo; eauto.\n    intros (npms_ip & _ & NPMS_AUG & NPMS_LEN &\n            (* NPMS_NIL_IFF & *) NPMS_PARSE).\n\n    econs; eauto.\n    - rewrite AANode.merge_inbox_length.\n      unfold AANode.init_inbox.\n      apply repeat_length.\n    - apply Forall_app_inv in PMS_TOT_OLD.\n      destruct PMS_TOT_OLD as [OLD1 OLD2].\n      apply Forall_app; ss.\n      rewrite NPMS_AUG.\n      apply Forall_app; ss.\n      apply Forall_forall.\n      intros pm IN.\n      hexploit NPMS_PARSE; eauto. i. des.\n      unfold AbstMW.parse_pld in *. desf.\n      econs; eauto.\n      { rewrite firstn_all2; eauto.\n        nia. }\n      nia.\n\n    - rewrite NPMS_AUG.\n      unfold nw_msgs_to.\n      rewrite MSG_PL_EMPTY. ss.\n\n      rewrite AANode.merge_inbox_size.\n      2: { unfold AANode.init_inbox.\n           rewrite repeat_length.\n           rewrite map_length.\n           rewrite <- LEN_OMS. ss.\n      }\n      rewrite AANode.inbox_size_empty. ss.\n  Qed.\n\n  Lemma match_inb_pre_nwstep_nexact\n        tm sytm nw nw1 dms\n        cbt ops nw' oms\n        ip inbp inbn\n        (* inbn1 *) tid mids inbn'\n        (TASK_ID_IP: task_id_ip tid ip)\n        (MCAST_ID_DOMAIN: mcast_id_domain nw ip mids)\n        (MCAST_OF_TID: mids = get_mcast_of tid)\n        (PRE: match_inb_pre cbt ip nw inbp inbn)\n        (DISTR: NW.distr nw = (nw1, dms))\n        (NW_INV: nw_inv tm nw)\n        (WF_NW: NW.wf nw)\n        (TIME_POS: 0 < tm)\n        (SYTM_EQ: sytm = cbt + period)\n        (* (RANGE_SYTM: IntRange.uint64 sytm) *)\n        (GATHER: NW.gather nw1 (filtermap id ops) nw')\n        (* (WF_OPS: Forall (option_rel1 Packet.wf) ops) *)\n        (LEN_OMS: length oms = num_tasks)\n        (MATCH_MSGS: iForall2 (match_pkt sytm)\n                              0 oms ops)\n        (SKWD_BASE_TIME: get_skwd_base_time period tm = cbt)\n        (EXACT: exact_skwd_base_time period tm = None)\n        (INBN': inbn' = AANode.merge_inbox\n                          inbn (map (AANode.get_msg_by_dest tid) oms))\n    : match_inb_pre\n        cbt ip nw'\n        (inbp ++ filter_port (Node.distr_msgs_to ip dms)) inbn'.\n  Proof.\n    assert (MCAST_ID_DOMAIN1: mcast_id_domain nw1 ip mids).\n    { eapply mcast_id_domain_distr; eauto. }\n    hexploit match_inb_pre_distr; eauto.\n    intro MATCH_DISTR.\n\n    apply exact_skwd_base_time_None_iff in EXACT.\n    2: { ss. }\n    destruct EXACT as (cbt' & RANGE_CBT & CBT_DIV).\n\n    assert (cbt' = cbt).\n    { eapply get_skwd_base_time_iff in SKWD_BASE_TIME.\n      des.\n      hexploit (skwd_time_range_almost_overwrap\n                  tm cbt cbt'); eauto.\n      { nia. }\n      i. des; ss.\n      subst cbt. nia.\n    }\n    subst cbt'.\n\n    hexploit nw_gather_matchinfo; try apply GATHER; eauto.\n    { eapply NW.wf_distr_preserve; eauto. }\n    intros (npms & NPMS_EQ & NPMS_AUG & NPMS_SZ & NPMS_PROP).\n    guardH NPMS_EQ.\n\n    inv MATCH_DISTR.\n    econs; eauto.\n    - rewrite AANode.merge_inbox_length. ss.\n    - rewrite NPMS_AUG.\n      rewrite app_assoc.\n      apply Forall_app; eauto.\n      apply Forall_forall.\n      intros pm IN_NPMS.\n      hexploit NPMS_PROP; eauto. i. des.\n      econs; eauto.\n      { rewrite firstn_all2; eauto. nia. }\n      nia.\n    - rewrite NPMS_AUG.\n      rewrite app_assoc.\n      rewrite app_length.\n      rewrite AANode.merge_inbox_size.\n      2: { rewrite map_length.\n           fold msgT. nia. }\n      nia.\n  Qed.\n\n\n  Lemma match_inb_pre_nwstep\n        tm sytm nw nw1 dms\n        cbt ops nw' oms\n        ip inbp inbn\n        (* inbn1 *) tid mids inbn'\n        (WF_NW: NW.wf nw)\n        (* (RANGE_SYTM: IntRange.uint64 sytm) *)\n        (TASK_ID_IP: task_id_ip tid ip)\n        (MCAST_OF_TID: mids = get_mcast_of tid)\n        (MCAST_ID_DOMAIN: mcast_id_domain nw ip mids)\n        (PRE: match_inb_pre cbt ip nw inbp inbn)\n        (DISTR: NW.distr nw = (nw1, dms))\n        (NW_INV: nw_inv tm nw)\n        (TM_POS: 0 < tm)\n        (SYTM_EQ: sytm = cbt + period)\n        (GATHER: NW.gather nw1 (filtermap id ops) nw')\n        (* (WF_OPS: Forall (option_rel1 Packet.wf) ops) *)\n        (LEN_OMS: length oms = num_tasks)\n        (MATCH_MSGS: iForall2 (match_pkt sytm)\n                              0 oms ops)\n        (SKWD_BASE_TIME: get_skwd_base_time period tm = cbt)\n        (INBN': inbn' = AANode.merge_inbox\n                          (match exact_skwd_base_time period tm with\n                           | Some _ => AANode.init_inbox\n                           | None => inbn\n                           end)\n                          (map (AANode.get_msg_by_dest tid) oms))\n    : match_inb_pre cbt ip nw' [] inbn'.\n  Proof.\n    destruct (exact_skwd_base_time period tm)\n      as [cbt'|] eqn: EXACT_TM.\n    { assert (cbt' = cbt).\n      { apply exact_skwd_impl_get in EXACT_TM.\n        clarify. }\n      subst cbt'.\n      eapply match_inb_pre_empty.\n      eapply match_inb_pre_nwstep_exact; eauto.\n      subst. ss.\n    }\n    { eapply match_inb_pre_empty.\n      (* hexploit match_inb_pre_empty; eauto. i. *)\n      eapply match_inb_pre_nwstep_nexact; eauto.\n    }\n  Qed.\n\n  Lemma match_inb_impl_pre\n        cbt\n        inbn inbm ms ip nw'\n        (* (SYTM: get_skwd_base_time period tm + period = sytm) *)\n        (MATCH_INB : match_inb\n                       (cbt + period) inbn inbm\n                       (ms ++ nw_msgs_to ip nw'))\n    : match_inb_pre cbt ip nw' [] inbn.\n  Proof.\n    inv MATCH_INB.\n    econs; eauto; ss.\n    - apply Forall_app_inv in PMS_IN_INB.\n      destruct PMS_IN_INB as [_ PMS_IN_INB2].\n      apply Forall_forall.\n      intros pm IN.\n      rewrite Forall_forall in PMS_IN_INB2.\n      hexploit PMS_IN_INB2; eauto.\n      i. des.\n      econs; eauto.\n      { rewrite firstn_all2; eauto. nia. }\n      nia.\n    - rewrite app_length in SIZE_INCL. nia.\n  Qed.\n\n\n  Lemma match_inb_pre_adv\n        cbt1 cbt2 ip nw inbp inbn\n        (MATCH: match_inb_pre cbt1 ip nw inbp inbn)\n        (TM_ADV: cbt1 <= cbt2)\n    : match_inb_pre cbt2 ip nw inbp inbn.\n  Proof.\n    inv MATCH.\n    econs; eauto.\n    eapply Forall_impl; try apply PMS_TOT_OLD.\n    i. eapply old_msg_adv; eauto. nia.\n  Qed.\n\n\n  Inductive match_join_pkt (tip: ip_t)\n    : Tid? -> Packet.t? -> Prop :=\n  | MatchJoinPkt_None\n    : match_join_pkt tip None None\n  | MatchJoinPkt_None_MsgPkt\n      pm\n    : match_join_pkt tip None (Some (inl pm))\n  | MatchJoinPkt_None_Join\n      mid mip\n      (MCAST_ID_IP: mcast_id_ip mid mip)\n    : match_join_pkt tip (Some mid) (Some (inr (mip, tip)))\n  .\n\n  Lemma task_id_ip_impl_dest\n        tid tip\n        (TASK_ID_IP: task_id_ip tid tip)\n    : dest_id_ip tid tip.\n  Proof.\n    r in TASK_ID_IP.\n    r. unfold dest_ips.\n    rewrite nth_error_app1; eauto.\n    apply nth_error_Some. congruence.\n  Qed.\n\n  Lemma mcast_id_ip_impl_dest\n        mid mip\n        (MCAST_ID_IP: mcast_id_ip mid mip)\n    : dest_id_ip mid mip.\n  Proof.\n    r in MCAST_ID_IP. des.\n    r. subst. unfold num_tasks, dest_ips.\n    rewrite nth_error_app2.\n    - rewrite minus_plus. ss.\n    - nia.\n  Qed.\n\n\n  Lemma mcast_id_domain_nwstep\n        tid tip mids sytm\n        nw nw1 dms\n        outs_src outs_tgt nw'\n        (TASK_ID_IP: task_id_ip tid tip)\n        (MIDS: mids = get_mcast_of tid)\n        (MCAST_ID_DOMAIN: mcast_id_domain nw tip mids)\n        (DISTR: NW.distr nw = (nw1, dms))\n        (MATCH_MSGS: iForall2 (match_pkt sytm)\n                              0 outs_src outs_tgt)\n        (GATHER: NW.gather nw1 (filtermap id outs_tgt) nw')\n    : mcast_id_domain nw' tip mids.\n  Proof.\n    hexploit mcast_id_domain_distr; eauto.\n    intro MC_DISTR.\n    inv MC_DISTR.\n    econs; eauto.\n    - i. hexploit gather_pending_inv; eauto.\n      destruct 1 as [? | IN_PKT].\n      + eapply PENDING_INCL; eauto.\n      + cut (In (Some (Packet.MCast (mip', tip)))\n                outs_tgt).\n        { intro IN_OUTS_TGT.\n          apply In_nth_error in IN_OUTS_TGT. des.\n          rewrite iForall2_nth in MATCH_MSGS.\n          specialize (MATCH_MSGS n).\n          rewrite IN_OUTS_TGT in MATCH_MSGS.\n          inv MATCH_MSGS. ss.\n          match goal with\n          | H: match_pkt _ _ _ _ |- _ => inv H\n          end.\n\n          assert (n = tid).\n          { eapply dest_id_ip_inv_det.\n            - apply task_id_ip_impl_dest; eauto.\n            - apply task_id_ip_impl_dest; eauto.\n          }\n          subst n.\n\n          apply In_nth_error in MCAST_MEMBER. des.\n          rewrite Forall2_nth in MCAST_IPS.\n          specialize (MCAST_IPS n).\n          rewrite MCAST_MEMBER in MCAST_IPS.\n          inv MCAST_IPS.\n          assert (y = mip').\n          { eapply mcast_id_ip_det; eauto. }\n          clarify.\n          eapply nth_error_In; eauto.\n        }\n\n        eapply filtermap_in in IN_PKT.\n        unfold id in IN_PKT.\n        des. clarify.\n    - i.\n      hexploit gather_active_inv; eauto.\n  Qed.\n\n  Lemma mcast_id_in_nw_nwstep\n        tid nw ip mids\n        nw1 dms nw'\n        nsytm opkt\n        outs_src outs_tgt omid\n        (* (TIDS: get_mcast_of tid = mids) *)\n        (TASK_ID_IP: task_id_ip tid ip)\n        (NW_MCM: mcast_id_in_nw nw ip mids)\n        (DISTR: NW.distr nw = (nw1, dms))\n        (GATHER: NW.gather nw1 (filtermap id outs_tgt) nw')\n        (MATCH_PKTS: iForall2 (match_pkt nsytm)\n                              0 outs_src outs_tgt)\n        (OUTS_TGT_NTH: nth_error outs_tgt tid =\n                       Some opkt)\n        (OMID: match_join_pkt ip omid opkt)\n    : mcast_id_in_nw nw' ip (mids ++ opt2list omid).\n  Proof.\n    hexploit mcast_id_in_nw_distr; eauto.\n    intro MC_DISTR.\n    inv MC_DISTR.\n\n    assert (MCMS_IN_NW' : Forall (mcm_pending nw' ip \\1/ mcm_active nw' ip) mips).\n    { apply Forall_forall.\n      intros mip IN.\n      rewrite Forall_forall in MCMS_IN_NW.\n      hexploit MCMS_IN_NW; eauto.\n      i. des.\n      - hexploit gather_pending; eauto.\n        (* i. des; eauto. *)\n      - hexploit gather_active; eauto.\n    }\n\n    destruct omid as [mid|].\n    2: { ss. rewrite app_nil_r.\n         econs; eauto. }\n\n    destruct opkt as [pkt|]; inv OMID. ss.\n    econs.\n    - apply Forall2_app; eauto.\n    - apply Forall_app; eauto.\n      econs.\n      2: { econs. }\n      left.\n      r. inv GATHER. ss.\n      rewrite map_app. apply in_or_app.\n      right.\n\n      eapply in_map_iff.\n      cut (In (mip, ip) mcms_new).\n      { intro IN.\n        apply In_nth_error in IN. des.\n        rewrite Forall2_nth in VALID_DELAYS_MCMS.\n        specialize (VALID_DELAYS_MCMS n).\n        rewrite IN in VALID_DELAYS_MCMS.\n        inv VALID_DELAYS_MCMS.\n        match goal with\n        | H: valid_delay_added _ _ |- _ => inv H\n        end.\n        exists (mip, ip, dly).\n        esplits; eauto.\n        eapply nth_error_In; eauto.\n      }\n\n      eapply in_partition_map_r1; try apply CLASSIFY; eauto.\n      2: { unfold id. ss. }\n      eapply in_filtermap; eauto.\n      { unfold id. ss. }\n      eapply nth_error_In; eauto.\n  Qed.\n\n\n  Lemma mcast_join_from_others_impossible\n        sytm outs_src outs_tgt\n        tid ip opkt\n        (MATCH: iForall2 (match_pkt sytm) 0 outs_src outs_tgt)\n        (OUT_N: nth_error outs_tgt tid = Some opkt)\n        (TASK_ID_IP: task_id_ip tid ip)\n        (ME_NOT_JOINING: match_join_pkt ip None opkt)\n    : forall mip1 ip1\n        (IN_OUTS_TGT: In (Some (Packet.MCast (mip1, ip1))) outs_tgt),\n      ip1 <> ip.\n  Proof.\n    ii. subst ip1.\n    apply In_nth_error in IN_OUTS_TGT. des.\n    rewrite iForall2_nth in MATCH. ss.\n    specialize (MATCH n).\n    rewrite IN_OUTS_TGT in MATCH.\n\n    assert (exists out_src,\n               <<OUT_SRC: nth_error outs_src n = Some out_src>> /\\\n               <<MATCH1: match_pkt sytm n out_src\n                                   (Some (Packet.MCast (mip1, ip)))>>).\n    { inv MATCH.\n      esplits; eauto. }\n    des.\n\n    inv MATCH1.\n    assert (n = tid).\n    { eapply dest_id_ip_inv_det.\n      - apply task_id_ip_impl_dest. eauto.\n      - apply task_id_ip_impl_dest. eauto.\n    }\n    subst n.\n    clarify.\n    inv ME_NOT_JOINING.\n  Qed.\n\n  Lemma mcast_id_active_nwstep\n        tid nw ip mids\n        nw1 dms nw'\n        nsytm opkt\n        outs_src outs_tgt\n        (TASK_ID_IP: task_id_ip tid ip)\n        (MCAST_ID_ACTIVE: mcast_id_active nw ip mids)\n        (DISTR: NW.distr nw = (nw1, dms))\n        (GATHER: NW.gather nw1 (filtermap id outs_tgt) nw')\n        (MATCH_PKTS: iForall2 (match_pkt nsytm)\n                              0 outs_src outs_tgt)\n        (OUTS_TGT_NTH: nth_error outs_tgt tid =\n                       Some opkt)\n        (OMID: match_join_pkt ip None opkt)\n    : mcast_id_active nw' ip mids.\n  Proof.\n    hexploit mcast_id_active_distr; eauto.\n    intro MC_DISTR.\n    inv MC_DISTR.\n\n    econs; eauto.\n    - apply Forall_forall.\n      intros mip IN.\n      eapply gather_active; eauto.\n      eapply Forall_forall in MCMS_ACTIVE; eauto.\n    - intros mip ACT.\n      hexploit gather_active_inv; eauto.\n    - intros mip' PENDING'.\n      r in PENDING'.\n      inv GATHER. ss.\n      unfold mcm_pending in NO_PENDING. ss.\n\n      rewrite map_app in PENDING'.\n      apply in_app_or in PENDING'.\n      destruct PENDING' as [?| IN_NEW].\n      { eauto. }\n\n      (* destruct opkt as [[pm | mcm]|]; cycle 2. *)\n      (* + *)\n\n      apply in_map_iff in IN_NEW.\n      destruct IN_NEW as [[[? ?] dly] [? IN_MCMP_NEW]].\n      ss. clarify.\n\n      cut (In (mip', ip) mcms_new).\n      { intro IN_MCMS_NEW.\n        hexploit in_partition_map_r2; eauto.\n        unfold id.\n        intros [? [IN_F ?]]. clarify.\n        eapply filtermap_in in IN_F. des. clarify.\n        hexploit mcast_join_from_others_impossible; eauto.\n      }\n      apply In_nth_error in IN_MCMP_NEW. des.\n      rewrite Forall2_nth in VALID_DELAYS_MCMS.\n      specialize (VALID_DELAYS_MCMS n).\n      rewrite IN_MCMP_NEW in VALID_DELAYS_MCMS.\n      inv VALID_DELAYS_MCMS.\n      match goal with\n      | H: valid_delay_added _ _ |- _ => inv H\n      end.\n      eapply nth_error_In; eauto.\n  Qed.\n\n\n  Lemma match_inb_empty sytm\n    : match_inb sytm AANode.init_inbox\n                AbstMW.init_inbox [].\n  Proof.\n    econs; eauto.\n    - unfold AANode.init_inbox.\n      rewrite repeat_length. ss.\n    - rewrite filtermap_nil.\n      2: { unfold init_inbox.\n           i. eapply repeat_spec; eauto. }\n      ss. nia.\n    - apply Forall2_nth. i.\n      destruct (lt_ge_dec n num_tasks).\n      + match goal with\n        | |- option_rel2 _ ?nth1 ?nth2 =>\n          assert ((exists n1, <<NTH1: nth1 = Some n1>>) /\\\n                  (exists n2, <<NTH2: nth2 = Some n2>>))\n        end.\n        { split.\n          - apply Some_not_None.\n            apply nth_error_Some.\n            unfold init_inbox.\n            rewrite repeat_length. ss.\n          - apply Some_not_None.\n            apply nth_error_Some.\n            unfold AANode.init_inbox.\n            rewrite repeat_length. ss.\n        }\n        des.\n        rewrite NTH1. rewrite NTH2. econs.\n        eapply nth_error_In in NTH1.\n        eapply nth_error_In in NTH2.\n        apply repeat_spec in NTH1.\n        apply repeat_spec in NTH2.\n        clarify.\n      + match goal with\n        | |- option_rel2 _ ?nth1 ?nth2 =>\n          assert ((<<NTH1: nth1 = None>>) /\\\n                  (<<NTH2: nth2 = None>>))\n        end.\n        { split.\n          - apply nth_error_None.\n            unfold init_inbox.\n            rewrite repeat_length. ss.\n          - apply nth_error_None.\n            unfold AANode.init_inbox.\n            rewrite repeat_length. ss.\n        }\n        des.\n        rewrite NTH1. rewrite NTH2. econs.\n    - i. exfalso.\n      apply nth_error_In in INB_ROW.\n      apply repeat_spec in INB_ROW.\n      clarify.\n  Qed.\n\n  Lemma match_inb_distr\n        stm inb inbm inbp\n        tid ip mids\n        nw nw1 dms\n        (TASK_ID_IP: task_id_ip tid ip)\n        (MCAST_ID_ACTIVE: mcast_id_active nw ip mids)\n        (MATCH: match_inb stm inb inbm\n                          (inbp ++ nw_msgs_to ip nw))\n        (DISTR: NW.distr nw = (nw1, dms))\n    : match_inb stm inb inbm\n                ((inbp ++ filter_port (Node.distr_msgs_to ip dms)) ++ nw_msgs_to ip nw1) /\\\n      mcast_id_domain nw1 ip mids.\n  Proof.\n    hexploit (nw_msgs_to_distr ip); eauto.\n    intros (LEN_EQ & INCL1 & INCL2 & INCLR).\n    inv MATCH.\n\n    split.\n    2: { eapply mcast_id_active_impl_domain.\n         eapply mcast_id_active_distr; eauto. }\n\n    econs; eauto.\n    - assert (length (filter_port (Node.distr_msgs_to ip dms)) <= length (Node.distr_msgs_to ip dms)).\n      { eapply filter_length. }\n\n      do 2 rewrite app_length.\n      rewrite app_length in SIZE_INCL. nia.\n\n    - rewrite <- app_assoc.\n      apply Forall_app_inv in PMS_IN_INB.\n      destruct PMS_IN_INB as [PR1 PR2].\n      apply Forall_app; ss.\n\n      rewrite Forall_forall in PR2.\n      apply Forall_app.\n      + apply Forall_forall.\n        intros pm IN1.\n        apply filter_In in IN1.\n        destruct IN1 as [IN_PM PORT_EQ].\n        hexploit PR2; eauto.\n      + apply Forall_forall.\n        intros pm IN2.\n        hexploit PR2; eauto.\n\n    - i. hexploit WHEN_INBM_EMPTY; eauto.\n      i. des.\n      esplits; eauto.\n      apply in_app_or in IN_PMS.\n      destruct IN_PMS as [IN1 | IN2].\n      + apply in_or_app. left.\n        apply in_or_app. left. eauto.\n      + hexploit INCLR; eauto.\n        destruct 1.\n        * apply in_or_app. right. eauto.\n        * apply in_or_app. left.\n          apply in_or_app. right.\n\n          unfold filter_port.\n          apply filter_In.\n          split; ss.\n          rewrite PORT_EQ.\n          rewrite Nat.eqb_refl. ss.\n  Qed.\n\n\n  Inductive match_lstate\n            (tm: DTime.t) (nw: NW.t)\n    : @AANode.state sysE -> @AbstMW.state sysE -> Prop :=\n    (* : @AANode.state sysE msgT -> @Node.state sysE -> Prop := *)\n  | Match_Off\n      tid node mids ip amw inbn cbt\n      (TASK_IP: nth_error task_ips tid = Some ip)\n      (MCAST_OF_TID: mids = get_mcast_of tid)\n      (MCAST_ID_DOMAIN: mcast_id_domain nw ip mids)\n      (ABST_MW_STATE: amw = AbstMW.Off)\n      (SKWD_BASE_TIME: get_skwd_base_time period tm = cbt)\n      (MATCH_NW: match_inb_pre cbt ip nw [] inbn)\n    : match_lstate\n        tm nw\n        (AANode.State tid node inbn None)\n        (* (Node.State (AbstMW.as_node _ _ tid node) *)\n        (AbstMW.State tid ip node amw)\n\n  | Match_Off_Prep\n      tid node mids ip\n      amw mids1 mids2\n      jtl inbp ast\n      cbt inbn\n      (TASK_IP: nth_error task_ips tid = Some ip)\n      (MCAST_ID_DOMAIN: mcast_id_domain nw ip mids)\n      (MCAST_OF_TID: mids = get_mcast_of tid)\n      (CUR_BASE_TIME: cbt = get_skwd_base_time period tm)\n      (CBT_LB: period <= cbt)\n      (JOIN_BEFORE_START: jtl = cbt + period - max_clock_skew - max_nw_delay)\n      (RANGE_TM: DTime.of_ns (cbt - max_clock_skew) < tm\n                 <= DTime.of_ns jtl)\n\n      (ABST_INIT_STATE: SNode.init_app_state _ ast)\n      (ABST_MW_STATE: amw = AbstMW.Prep\n                              mids2 jtl inbp ast)\n      (MCAST_IPS_TO_JOIN: mids1 ++ mids2 = mids)\n      (JOINED: mcast_id_in_nw nw ip mids1)\n      (MATCH_NW: match_inb_pre cbt ip nw inbp inbn)\n    : match_lstate\n        tm nw\n        (AANode.State tid node inbn None)\n        (AbstMW.State tid ip node amw)\n\n  | Match_Off_Ready\n      tm_p tid node mids inbn ip amw\n      cbt fsytm jtl ast inbp inbm\n      (TASK_IP: nth_error task_ips tid = Some ip)\n      (MCAST_ID_DOMAIN: mcast_id_domain nw ip mids)\n      (MCAST_OF_TID: mids = get_mcast_of tid)\n      (TM_PREV: DTime.succ tm_p = tm)\n      (CUR_BASE_TIME: cbt = get_skwd_base_time period tm_p)\n      (JOIN_BEFORE_START: jtl = cbt + period - max_clock_skew - max_nw_delay)\n      (RANGE_TM: DTime.of_ns (cbt - max_clock_skew) < tm <=\n                 DTime.of_ns (cbt + period - max_clock_skew ))\n      (FIRST_SYNC_TIME: fsytm = cbt + period + period)\n      (ABST_INIT_STATE: SNode.init_app_state _ ast)\n      (INBM_INIT: inbm = AbstMW.init_inbox)\n      (ABST_MW_STATE: amw = AbstMW.On\n                              fsytm inbp inbm\n                              AbstMW.Ready ast)\n      (JOINED: mcast_id_in_nw nw ip mids)\n      (MATCH_NW: match_inb_pre cbt ip nw inbp inbn)\n    : match_lstate\n        tm nw\n        (AANode.State tid node inbn None)\n        (AbstMW.State tid ip node amw)\n\n  | Match_Done_Ready\n      tid node inbn mids ip amw\n      sytm inbp inbm ast cbt\n      ms_old ms_n\n      ocnt\n      (TASK_IP: nth_error task_ips tid = Some ip)\n      (MCAST_ID_ACTIVE : mcast_id_active nw ip mids)\n      (MCAST_OF_TID: mids = get_mcast_of tid)\n      (CUR_BASE_TIME: Nat.divide period cbt)\n      (FIRST_SYNC_TIME: cbt + period = sytm)\n      (RANGE_TM: DTime.of_ns (cbt - max_clock_skew) < tm\n                 <= DTime.of_ns (sytm - max_clock_skew))\n      (ABST_MW_STATE: amw = AbstMW.On\n                              sytm inbp inbm\n                              AbstMW.Ready ast)\n      (INBP_DIV: inbp = ms_old ++ ms_n)\n      (* (JOINED: mcast_id_in_nw nw ip mids) *)\n      (OLD_CNT: length ms_old = ocnt)\n      (OLD_MSGS: Forall (old_msg (cbt + period)) ms_old)\n      (MATCH_INB: match_inb sytm inbn inbm\n                            (ms_n ++ nw_msgs_to ip nw))\n    : match_lstate\n        tm nw\n        (AANode.State tid node inbn\n                      (Some (ocnt, AANode.Done, ast)))\n        (AbstMW.State tid ip node amw)\n\n  | Match_Ready\n      tid node mids inbn inbc ip amw\n      sytm inbp inbm ast\n      ms_old ms_c ms_n ocnt\n      (TASK_IP: nth_error task_ips tid = Some ip)\n      (MCAST_ID_ACTIVE : mcast_id_active nw ip mids)\n      (MCAST_OF_TID: mids = get_mcast_of tid)\n      (CUR_BASE_TIME: Nat.divide period sytm)\n      (RANGE_TM: DTime.of_ns (sytm - max_clock_skew) < tm\n                 <= DTime.of_ns (sytm + period - max_clock_skew - max_nw_delay))\n      (* (INBM_INIT: inbm = AbstMW.init_inbox msgT) *)\n      (ABST_MW_STATE: amw = AbstMW.On\n                              sytm inbp inbm\n                              AbstMW.Ready ast)\n      (* (JOINED: mcast_id_in_nw nw ip mids) *)\n      (OLD_CNT: length ms_old = ocnt)\n      (OLD_MSGS: Forall (old_msg sytm) ms_old)\n      (INBP_DIV: inbp = ms_old ++ ms_c ++ ms_n)\n      (MATCH_INBC: match_inb sytm inbc inbm ms_c)\n      (MATCH_INBN: match_inb (sytm + period)\n                     inbn AbstMW.init_inbox\n                     (ms_n ++ nw_msgs_to ip nw))\n    : match_lstate\n        tm nw\n        (AANode.State tid node inbn\n                      (Some (ocnt, AANode.Ready sytm inbc, ast)))\n        (AbstMW.State tid ip node amw)\n\n  | Match_Running\n      tid node mids inbn ip amw\n      sytm inbp inbm sh ast\n      ms_old ms_n\n      ocnt\n      (TASK_IP: nth_error task_ips tid = Some ip)\n      (MCAST_ID_ACTIVE: mcast_id_active nw ip mids)\n      (MCAST_OF_TID: mids = get_mcast_of tid)\n      (CUR_BASE_TIME: Nat.divide period sytm)\n      (TIME_BELOW_MAX: sytm < MAX_TIME)\n      (RANGE_TM: DTime.of_ns (sytm - max_clock_skew) < tm\n                 <= DTime.of_ns (sytm + period - max_clock_skew - max_nw_delay))\n      (ABST_MW_STATE: amw = AbstMW.On\n                              sytm inbp inbm\n                              (AbstMW.Running sh) ast)\n      (* (JOINED: mcast_id_in_nw nw ip mids) *)\n      (INBP_DIV: inbp = ms_old ++ ms_n)\n      (OLD_CNT: length ms_old = ocnt)\n      (OLD_MSGS: Forall (old_msg (sytm + period)) ms_old)\n      (MATCH_INBN: match_inb (sytm + period) inbn inbm\n                             (ms_n ++ nw_msgs_to ip nw))\n    : match_lstate\n        tm nw\n        (AANode.State tid node inbn\n                      (Some (ocnt, AANode.Running sytm sh, ast)))\n        (* (Node.State (AbstMW.as_node _ _ tid node) *)\n        (AbstMW.State tid ip node amw)\n  .\n\n\n  Lemma nw_msgs_to_gather\n        ip nw1 nw'\n        mids sytm tid\n        outs_src outs_tgt\n        (WF_NW1: NW.wf nw1)\n        (IP_LOCAL: IP.local_ip ip)\n        (* (RANGE_SYTM: IntRange.uint64 sytm) *)\n        (* (RANGE_NUM_TASKS: IntRange.sint8 num_tasks) *)\n        (GATHER: NW.gather nw1 (filtermap id outs_tgt) nw')\n        (TASK_ID_IP: task_id_ip tid ip)\n        (MCAST_ID_ACTIVE: mcast_id_active nw1 ip mids)\n        (MCAST_OF_TID: mids = get_mcast_of tid)\n        (LEN_OUTS: length outs_src = num_tasks)\n        (MATCH_OUTMSGS: iForall2 (match_pkt sytm)\n                                 0 outs_src outs_tgt)\n    : exists ms_new,\n      nw_msgs_to ip nw' = nw_msgs_to ip nw1 ++ ms_new /\\\n      match_inb sytm\n                (map (AANode.get_msg_by_dest tid) outs_src)\n                AbstMW.init_inbox ms_new.\n  Proof.\n    guardH MCAST_OF_TID.\n    hexploit nw_gather_matchinfo; eauto.\n    { apply mcast_id_active_impl_domain. eauto. }\n    intros (npms_ip & NPMS_IN_TGT & NW_MSGS_TO' &\n            NPMS_IP_SZ & IN_NPMS_PROP).\n\n    esplits; eauto.\n\n    (* inv GATHER. *)\n    (* unfold nw_msgs_to. ss. *)\n    (* exists (Node.distr_msgs_to ip (map fst pmp_new)). *)\n    (* split. *)\n    (* { unfold Node.distr_msgs_to. *)\n    (*   rewrite map_app. *)\n    (*   rewrite filtermap_app. ss. } *)\n\n    (* assert (AUX_EQ: Node.distr_msgs_to ip (map fst pmp_new) = *)\n    (*                 filtermap (aux_msgs_to mcg ip) outs_tgt). *)\n    (* { eapply aux_msgs_to_equiv; eauto. *)\n    (*   inv WF_NW1; ss. } *)\n\n    econs; ss.\n    - rewrite map_length. fold msgT. rewrite LEN_OUTS. ss.\n    - rewrite filtermap_init_inbox. ss.\n    - apply Forall_forall. ss.\n    - apply Forall2_nth. i.\n      destruct (nth_error init_inbox n) as [nn|] eqn: INIT_INB_N.\n      2: {\n        fold bytes msgT in INIT_INB_N.\n        rewrite INIT_INB_N.\n\n        assert (SRC_NONE: nth_error outs_src n = None).\n        { eapply nth_error_eqlen_None.\n          2: { apply INIT_INB_N. }\n          unfold msgT.\n          rewrite init_inbox_length.\n          fold msgT.\n          congruence.\n        }\n        rewrite <- map_nth_error_None_iff in SRC_NONE.\n        rewrite SRC_NONE. econs.\n      }\n      fold bytes msgT in INIT_INB_N.\n      rewrite INIT_INB_N.\n\n      assert (NTH_SRC: exists x, nth_error (map (AANode.get_msg_by_dest tid) outs_src) n = Some x).\n      { eapply nth_error_eqlen_Some with (l1:=init_inbox); eauto.\n        rewrite map_length.\n        rewrite init_inbox_length.\n        rewrite <- LEN_OUTS. ss.\n      }\n      des.\n      fold msgT in NTH_SRC. fold msgT.\n      rewrite NTH_SRC. econs.\n\n      hexploit (init_inbox_nth n).\n      { rewrite <- init_inbox_length.\n        apply nth_error_Some.\n        fold bytes msgT.\n        congruence.\n      }\n      i. subst.\n      exfalso.\n      unfold msgT in *.\n      congruence.\n\n    - fold msgT.\n      i. rewrite map_nth_error_iff in INB_ROW.\n      destruct INB_ROW as (out_src & OUT_SRC & OUT_SRC_F).\n      rewrite iForall2_nth in MATCH_OUTMSGS.\n      specialize (MATCH_OUTMSGS tid_s).\n      rewrite OUT_SRC in MATCH_OUTMSGS.\n\n      assert (exists out_tgt,\n                 <<OUT_TGT: nth_error outs_tgt tid_s = Some out_tgt>> /\\\n                 <<MATCH_PKT: match_pkt sytm tid_s out_src out_tgt>>).\n      { inv MATCH_OUTMSGS. esplits; eauto. }\n      des.\n\n      inv MATCH_PKT; ss.\n      (* unfold filter_by_dest in IN_ROW. ss. *)\n      (* unfold chget_by_dest in IN_ROW. ss. *)\n\n      assert (<<TID_D: (tid_d = tid \\/ In tid_d mids)>> /\\\n              m = rmsg).\n      { rewrite <- MCAST_OF_TID in IN_ROW.\n        desf. ss.\n        des; ss. clarify.\n        split; ss.\n        destruct (Nat.eqb_spec tid_d tid); eauto.\n        ss. rewrite existsb_exists in *. des.\n        rewrite Nat.eqb_eq in *.\n        clarify. eauto.\n      }\n      nbdes. clarify.\n      clear IN_ROW.\n      pose (pm:= Packet.mkMsg\n                   ip_s ip_d port\n                   (serialize_msg sytm tid_s rmsg)).\n      fold pm in OUT_TGT.\n      exists pm.\n\n      assert (RANGE_TID_S: IntRange.sint8 tid_s).\n      { inv IP_SENDER.\n        cut (tid_s < length task_ips).\n        { pose proof range_num_tasks as RANGE_NT.\n          fold num_tasks.\n          range_stac. }\n        eapply nth_error_Some. congruence.\n      }\n\n      splits; ss; cycle 1.\n      { erewrite serialize_msg_size_eq; eauto.\n        rewrite LENGTH_RMSG. ss. }\n      { erewrite serialize_parse_msg_inv; eauto. }\n\n      inv GATHER.\n      erewrite <- aux_msgs_to_equiv; eauto.\n      2: { ss. inv WF_NW1. ss. }\n\n      unfold Node.distr_msgs_to.\n      eapply in_filtermap.\n      { instantiate (1:= (ip, pm)).\n        unfold Node.chget_pm_by_dest. ss.\n        rewrite Nat.eqb_refl. ss. }\n\n      cut (exists d, In (ip, pm, d) pmp_new).\n      { intros [d IN].\n        eapply in_map with (f:= fst) in IN. ss. }\n      guardH TID_D.\n\n      assert (LOCAL_IP: IP.local_ip ip).\n      { pose proof task_ips_local_ip as TL.\n        rewrite Forall_forall in TL.\n        eapply TL.\n        eapply nth_error_In.\n        eapply TASK_ID_IP. }\n      destruct (IP.mcast_ip ip) eqn:MCAST_IP_F.\n      { exfalso.\n        generalize (IP.normal_mcast_disjoint ip).\n        rewrite MCAST_IP_F. rewrite LOCAL_IP. ss. }\n\n      rewrite <- flat_map_concat_map in VALID_DELAYS_PMS.\n\n      cut (exists x, In x pms_new /\\ In (ip, pm) (NW.attach_adest mcg x)).\n      { intro FMAP_AUX.\n        eapply in_flat_map in FMAP_AUX.\n        apply In_nth_error in FMAP_AUX.\n        destruct FMAP_AUX as [n NTH_FMAP].\n\n        rewrite Forall2_nth in VALID_DELAYS_PMS.\n        specialize (VALID_DELAYS_PMS n).\n\n        clear - VALID_DELAYS_PMS NTH_FMAP.\n        rewrite NTH_FMAP in VALID_DELAYS_PMS.\n        inv VALID_DELAYS_PMS.\n        match goal with\n        | H: valid_delay_added _ _ |- _ => inv H\n        end.\n        exists dly. eapply nth_error_In; eauto.\n      }\n\n      cut (<<PM_IN_NEW: In pm pms_new>> /\\\n                        (ip_d = ip \\/\n                         (<<IP_D_MCAST: IP.mcast_ip ip_d>> /\\\n                                        <<IP_IN_GROUP: In ip (NW.get_actual_receivers mcg ip_d)>>))).\n      { i. des.\n        - subst ip_d.\n          exists pm. esplits; eauto.\n          unfold NW.attach_adest. ss.\n          rewrite MCAST_IP_F. ss. eauto.\n        - exists pm. esplits; eauto.\n          unfold NW.attach_adest. ss.\n          rewrite IP_D_MCAST.\n          change (ip, pm) with ((fun x => (x, pm)) ip).\n          apply in_map. ss.\n      }\n\n      splits.\n      * match goal with\n        | H: ?lp = (pms_new, _) |- _ =>\n          replace pms_new with (fst lp)\n        end.\n        2: { rewrite CLASSIFY. ss. }\n\n        apply in_partition_map_l_iff.\n        esplits; ss.\n        eapply in_filtermap; ss.\n        eapply nth_error_In; eauto.\n      * desH TID_D.\n        { left. clarify.\n          r in IP_DEST. r in TASK_ID_IP.\n          unfold dest_ips in *.\n          rewrite nth_error_app1 in IP_DEST.\n          2: { apply nth_error_Some. congruence. }\n          clarify.\n        }\n        { right.\n          inv MCAST_ID_ACTIVE.\n\n          assert (exists mip', <<IN_MIPS': In mip' mips>> /\\\n                                      <<MCAST_ID_IP': mcast_id_ip tid_d mip'>>).\n          { rewrite Forall2_nth in MCAST_IPS.\n            eapply In_nth_error in TID_D. des.\n            specialize (MCAST_IPS n).\n            rewrite TID_D in MCAST_IPS.\n            inv MCAST_IPS.\n            esplits; eauto.\n            eapply nth_error_In; eauto.\n          }\n          des.\n\n          hexploit mcast_id_ip_comput; eauto.\n          intros [TID2IP' MCAST_IP'].\n\n          assert (MIP_EQ: mip' = ip_d).\n          { r in IP_DEST. r in MCAST_ID_IP'.\n            unfold dest_ips in *.\n            des.\n            rewrite nth_error_app2 in IP_DEST.\n            2: { fold num_tasks. nia. }\n            subst tid_d.\n            fold num_tasks in IP_DEST.\n            rewrite minus_plus in IP_DEST. clarify.\n          }\n          rewrite MIP_EQ in *. clear MIP_EQ.\n          split.\n          { congruence. }\n\n          unfold NW.get_actual_receivers.\n          eapply in_filtermap with (a:= (ip_d, ip)).\n          { ss. rewrite Nat.eqb_refl. ss. }\n\n          rewrite Forall_forall in MCMS_ACTIVE.\n          hexploit MCMS_ACTIVE; eauto.\n        }\n      * ss. inv WF_NW1. ss.\n  Qed.\n\n\n  Lemma match_inb_gather\n        stm inb inbm inbp\n        tid ip mids\n        nw1 nw'\n        outs_src outs_tgt\n        (WF_NW1: NW.wf nw1)\n        (* (RANGE_STM: IntRange.uint64 stm) *)\n        (TASK_ID_IP: task_id_ip tid ip)\n        (MCAST_ID_DOMAIN: mcast_id_active nw1 ip mids)\n        (MCAST_OF_TID: mids = get_mcast_of tid)\n        (OUTS_SRC_LENGTH: length outs_src = num_tasks)\n        (MATCH: match_inb stm inb\n                          inbm (inbp ++ nw_msgs_to ip nw1))\n        (MATCH_OUTMSGS: iForall2 (match_pkt stm)\n                                 0 outs_src outs_tgt)\n        (GATHER: NW.gather nw1 (filtermap id outs_tgt) nw')\n    : match_inb stm\n                (AANode.merge_inbox\n                   inb (map (AANode.get_msg_by_dest tid) outs_src))\n                inbm (inbp ++ nw_msgs_to ip nw').\n  Proof.\n    inv MATCH.\n\n    (* assert (F_OUTS_SRC_LENGTH: *)\n    (*           length (map (filter_by_dest (tid :: mids)) outs_src) = num_tasks). *)\n    (* { rewrite map_length. ss. } *)\n\n    hexploit nw_msgs_to_gather; eauto.\n    { eapply task_id_ip_comput; eauto. }\n\n    intros (ms_new & NW_MSGS_TO_NEW & MATCH_INB_NEW).\n    inv MATCH_INB_NEW.\n\n    econs.\n    - rewrite AANode.merge_inbox_length. ss.\n    - rewrite AANode.merge_inbox_size.\n      2: { fold bytes msgT.\n           rewrite map_length. congruence. }\n      rewrite NW_MSGS_TO_NEW.\n      clear - SIZE_INCL SIZE_INCL0.\n      rewrite app_assoc.\n      rewrite app_length.\n      nia.\n    - rewrite NW_MSGS_TO_NEW.\n      rewrite app_assoc.\n      apply Forall_app.\n      + clear - PMS_IN_INB.\n        eapply Forall_impl; eauto. ss.\n        intros pm ?. des.\n        esplits.\n        * eauto.\n        * eauto.\n        * eauto.\n        * erewrite AANode.merge_inbox_nth by eauto.\n          reflexivity.\n        * apply in_or_app. left. ss.\n      + (* clear - PMS_IN_INB0 INB_LENGTH F_OUTS_SRC_LENGTH. *)\n        eapply Forall_impl; eauto. ss.\n        intros pm ?. des.\n        assert (exists r, nth_error inb tid_s = Some r).\n        { apply Some_not_None.\n          apply nth_error_Some.\n          rewrite INB_LENGTH.\n          rewrite <- INB_LENGTH0.\n          apply nth_error_Some.\n          fold msgT in INB_ROW_EX. fold msgT.\n          congruence.\n        }\n        des.\n        esplits.\n        * eauto.\n        * eauto.\n        * eauto.\n        * erewrite AANode.merge_inbox_nth by eauto.\n          reflexivity.\n        * fold msgT. fold msgT in INB_ROW_EX.\n          rewrite INB_ROW_EX.\n          apply in_or_app. eauto.\n    - clear - INBM_IN_INB.\n      apply Forall2_nth.\n      rewrite Forall2_nth in INBM_IN_INB.\n      intro n. specialize (INBM_IN_INB n).\n\n      destruct (nth_error inbm n) as [inbm_r|] eqn:INBM_R.\n      2: { inv INBM_IN_INB.\n           rewrite AANode.merge_inbox_nth_None by ss.\n           econs. }\n\n      inv INBM_IN_INB.\n      hexploit AANode.merge_inbox_nth; eauto.\n      intro R. rewrite R.\n      econs. i. clarify.\n      apply in_or_app.\n      left. eauto.\n\n    - i.\n      destruct (nth_error inb tid_s) as [inb_r1|] eqn:INT_R1.\n      2: {\n        exfalso.\n        hexploit AANode.merge_inbox_nth_None; eauto.\n        intro R. rewrite R in INB_ROW. ss.\n      }\n\n      hexploit AANode.merge_inbox_nth; eauto.\n      intro R. rewrite R in INB_ROW. clear R.\n      clarify.\n\n      assert (INB_R2: exists inb_r2,\n                 nth_error (map (AANode.get_msg_by_dest tid)\n                                outs_src) tid_s = Some inb_r2).\n      { apply Some_not_None.\n        eapply nth_error_Some.\n        (* rewrite F_OUTS_SRC_LENGTH. *)\n        fold msgT. fold msgT in INB_LENGTH0.\n        rewrite INB_LENGTH0.\n        rewrite <- INB_LENGTH.\n        eapply nth_error_Some.\n        congruence.\n      }\n      des.\n\n      fold bytes msgT in INB_R2, IN_ROW.\n      rewrite INB_R2 in IN_ROW.\n      apply in_app_or in IN_ROW.\n      rewrite NW_MSGS_TO_NEW.\n      rewrite app_assoc.\n\n      destruct IN_ROW as [IN1 | IN2].\n      + hexploit WHEN_INBM_EMPTY; eauto.\n        i. des.\n        esplits; eauto.\n        apply in_or_app. eauto.\n      + hexploit WHEN_INBM_EMPTY0; eauto.\n        { apply repeat_nth_error_Some.\n          fold num_tasks.\n          rewrite <- INB_LENGTH.\n          apply nth_error_Some.\n          congruence.\n        }\n        i. des.\n        esplits; eauto.\n        apply in_or_app. eauto.\n  Qed.\n\n  Lemma match_inb_nwstep\n        stm inb inbm inbp\n        tid ip mids\n        nw nw1 dms nw'\n        outs_src outs_tgt\n        (* (RANGE_STM: IntRange.uint64 stm) *)\n        (WF_NW: NW.wf nw)\n        (TASK_ID_IP: task_id_ip tid ip)\n        (MCAST_ID_ACTIVE: mcast_id_active nw ip mids)\n        (MCAST_OF_TID: mids = get_mcast_of tid)\n        (MATCH: match_inb stm inb\n                          inbm (inbp ++ nw_msgs_to ip nw))\n        (DISTR: NW.distr nw = (nw1, dms))\n        (OUTS_SRC_LENGTH: length outs_src = num_tasks)\n        (MATCH_OUTMSGS: iForall2 (match_pkt stm)\n                                 0 outs_src outs_tgt)\n        (GATHER: NW.gather nw1 (filtermap id outs_tgt) nw')\n    : match_inb stm\n                (AANode.merge_inbox\n                   inb (map (AANode.get_msg_by_dest tid) outs_src))\n                inbm ((inbp ++ (filter_port (Node.distr_msgs_to ip dms))) ++\n                           nw_msgs_to ip nw')\n  .\n  Proof.\n    hexploit match_inb_distr; eauto. i. des.\n    eapply match_inb_gather with (nw1:= nw1); eauto.\n    - hexploit NW.wf_distr_preserve; eauto.\n      i. des. ss.\n    - eapply mcast_id_active_distr; eauto.\n  Qed.\n\n  Lemma match_inb_to_pre\n        cbt inbn inbm\n        ms ip nw\n        (MATCH: match_inb (cbt + period) inbn\n                          inbm\n                          (ms ++ nw_msgs_to ip nw))\n    : match_inb_pre cbt ip nw [] inbn.\n  Proof.\n    inv MATCH.\n    econs; eauto.\n    - clear - PMS_IN_INB PERIOD_COND. ss.\n      apply Forall_forall.\n      intros pm IN.\n      apply Forall_app_inv in PMS_IN_INB.\n      destruct PMS_IN_INB as [_ PMS_IN_INB2].\n      rewrite Forall_forall in PMS_IN_INB2.\n      hexploit PMS_IN_INB2; eauto. i. des.\n      econs; eauto.\n      { rewrite firstn_all2; eauto. nia. }\n      nia.\n    - clear - SIZE_INCL.\n      rewrite app_length in SIZE_INCL.\n      ss. nia.\n  Qed.\n\n\n\n\n  (* Lemma update_msg_sz_inc inbm tid m *)\n  (*   : length (filtermap id (update_msg inbm tid m)) *)\n  (*     <= S (length (filtermap id inbm)). *)\n  (* Proof. *)\n  (*   unfold update_msg. *)\n\n  (*   hexploit (replace_nth_spec _ inbm tid). *)\n  (*   intros [[? REPL_EQ] | AUX]. *)\n  (*   { rewrite REPL_EQ. ss. nia. } *)\n  (*   destruct AUX as (l1 & p & l2 & DIV & *)\n  (*                    LEN1 & REPL_EQ). *)\n  (*   rewrite REPL_EQ, DIV. ss. *)\n  (*   do 2 rewrite filtermap_app. *)\n  (*   do 2 rewrite app_length. ss. *)\n  (*   destruct p; ss; nia. *)\n  (* Qed. *)\n\n  Lemma match_inb_upd_msg\n        cbt inb inbm tid\n        m ms inb_r msg\n        (PORT_EQ : Packet.dest_port m = port)\n        (PLD_SIZE_EQ : length (Packet.payload m) = pld_size)\n        (PARSE_OK : parse_msg (Packet.payload m) = Some (cbt, tid, msg))\n        (INB_ROW_EX : nth_error inb tid = Some inb_r)\n        (IN_INB_ROW : In msg inb_r)\n        (MATCH: match_inb cbt inb inbm (m::ms))\n    : match_inb cbt inb\n                (update_msg inbm tid msg) ms.\n  Proof.\n    inv MATCH.\n    unfold update_msg.\n    destruct (replace_nth_spec _ inbm tid (Some msg))\n      as [[? REPL_EQ] | AUX].\n    - exfalso.\n      cut (nth_error inb tid = None).\n      { congruence. }\n\n      eapply nth_error_None.\n      apply Forall2_length in INBM_IN_INB.\n      fold bytes msgT.\n      rewrite <- INBM_IN_INB. ss.\n    - destruct AUX as (l1 & p & l2 & DIV &\n                       LEN1 & REPL_EQ).\n      fold bytes msgT.\n      fold bytes msgT in REPL_EQ.\n      rewrite REPL_EQ.\n\n      econs; eauto.\n      + etransitivity.\n        2: { apply SIZE_INCL. }\n        etransitivity.\n        2: { instantiate (1:= S (length (filtermap id inbm)) + length ms).\n             ss. nia. }\n        apply plus_le_compat_r.\n        rewrite DIV.\n        do 4 rewrite filtermap_app. ss.\n\n        destruct p; ss.\n        * do 2 rewrite app_length. ss. nia.\n        * do 2 rewrite app_length. ss. nia.\n      + inv PMS_IN_INB. ss.\n      + rewrite DIV in INBM_IN_INB.\n        apply Forall2_app_inv_l in INBM_IN_INB.\n        destruct INBM_IN_INB as\n            (inbc1 & inbc' & IN_INBC1 &\n             IN_INBC' & INBC_DIV).\n        destruct inbc' as [| inb_tid inbc2].\n        { inv IN_INBC'. }\n        inv IN_INBC'.\n\n        eapply Forall2_app; eauto.\n        econs; eauto.\n        i. clarify.\n\n        cut (inb_r = inb_tid).\n        { intro R. rewrite <- R. ss. }\n\n        apply Forall2_length in IN_INBC1.\n        rewrite IN_INBC1 in INB_ROW_EX.\n        clear - INB_ROW_EX.\n        rewrite nth_error_app2 in INB_ROW_EX by nia.\n        rewrite Nat.sub_diag in INB_ROW_EX.\n        ss. clarify.\n      + i.\n        hexploit WHEN_INBM_EMPTY; eauto.\n        { rewrite DIV.\n\n          assert ((<<TID_L1: tid_s < length l1>> /\\\n                             <<IN_L1: nth_error l1 tid_s = Some None>>) \\/\n                  (<<TID_L2: length l1 < tid_s>> /\\\n                             <<IN_L2: nth_error l2 (tid_s - S (length l1)) = Some None>>)).\n          { destruct (classic (tid_s < length l1)).\n            - left. split; ss. erewrite <- nth_error_app1; eauto.\n            - destruct (classic (tid_s = length l1)).\n              { subst. rewrite nth_error_app2 in INBM_ROW; eauto; try nia.\n                rewrite Nat.sub_diag in *. ss. }\n              right. split; unnw; try nia.\n              revert INBM_ROW.\n              rewrite app_assoc, nth_error_app2; rewrite app_length; ss; try nia.\n              rewrite Nat.add_1_r. ss.\n          }\n          des.\n          - rewrite nth_error_app1; ss.\n          - rewrite nth_error_app2 by nia.\n            replace (tid_s - length l1) with\n                (S (tid_s - S (length l1))) by nia.\n            ss.\n        }\n        i. ss. des.\n        2: { esplits; eauto. }\n        exfalso.\n        clarify.\n        rewrite nth_error_app2 in INBM_ROW.\n        rewrite Nat.sub_diag in INBM_ROW. ss. clarify.\n  Qed.\n\n\n\n  Lemma fetch_msgs_cur_mid\n        cbt ms ms' inbc\n        inbm inbn_t\n        (MATCH_INBC: match_inb cbt inbc inbm (ms ++ ms'))\n    : exists inbm',\n      List.fold_left\n        (flip (fetch_one_msg cbt)) ms\n        (inbm, inbn_t) = (inbm', inbn_t) /\\\n      match_inb cbt inbc inbm' ms'.\n  Proof.\n    depgen inbm.\n    induction ms as [|m ms1 IH]; i; ss.\n    { esplits; eauto. }\n\n    assert (exists inbm1,\n               <<FETCH1: fetch_one_msg cbt m (inbm, inbn_t) = (inbm1, inbn_t)>> /\\\n               <<MATCH1: match_inb cbt inbc inbm1 (ms1 ++ ms')>>).\n    { inv MATCH_INBC. ss.\n      unfold fetch_one_msg.\n      inv PMS_IN_INB. des.\n      unfold parse_pld.\n      rewrite PLD_SIZE_EQ.\n      rewrite Nat.ltb_irrefl.\n      rewrite firstn_all2; eauto.\n      2: { nia. }\n      rewrite PARSE_OK.\n      rewrite Nat.eqb_refl.\n      esplits; eauto.\n\n      eapply match_inb_upd_msg; eauto.\n      econs; eauto.\n      econs; eauto.\n      esplits; eauto.\n    }\n\n    des.\n    unfold flip at 2.\n    rewrite FETCH1.\n    hexploit IH; eauto.\n  Qed.\n\n\n  Lemma match_inb_end_choose_rowmsg\n        cbt inbc inbm\n        (MATCH: match_inb cbt inbc inbm [])\n    : Forall2 AANode.choose_inbox_rowmsg inbc inbm.\n  Proof.\n    inv MATCH.\n    apply Forall2_nth. i.\n    rewrite Forall2_nth in INBM_IN_INB.\n    specialize (INBM_IN_INB n).\n    assert ((exists inbm_r inbc_r,\n               <<INBM_R: nth_error inbm n = Some inbm_r>> /\\\n               <<INBC_R: nth_error inbc n = Some inbc_r>> /\\\n               <<INBM_INCL: forall m : msgT, inbm_r = Some m -> In m inbc_r>>) \\/\n            (<<INBM_NONE: nth_error inbm n = None>> /\\\n             <<INBC_NONE: nth_error inbc n = None>>)).\n    { destruct (nth_error inbc n) eqn:INBC_R.\n      - left.\n        inv INBM_IN_INB.\n        esplits; eauto.\n      - right.\n        inv INBM_IN_INB.\n        esplits; eauto.\n    }\n    des.\n    - rewrite INBM_R, INBC_R in INBM_IN_INB.\n      fold msgT.\n      rewrite INBM_R, INBC_R.\n      econs.\n\n      destruct inbc_r.\n      + (* nil *)\n        destruct inbm_r; ss.\n        { exfalso.\n          hexploit INBM_INCL; eauto. }\n        econs 1.\n      + (* cons *)\n        destruct inbm_r as [m_ch|].\n        * econs 2.\n          hexploit INBM_INCL; eauto.\n        * exfalso.\n          hexploit WHEN_INBM_EMPTY; eauto.\n          { left. eauto. }\n          i. des.\n          inv IN_PMS.\n    - fold msgT.\n      rewrite INBM_NONE, INBC_NONE. econs.\n  Qed.\n\n  Lemma fetch_msgs_cur\n        cbt ms inbc\n        inbm inbn_t\n        (MATCH_INBC: match_inb cbt inbc inbm ms)\n    : exists inbc_t',\n      List.fold_left\n        (flip (fetch_one_msg cbt)) ms\n        (inbm, inbn_t) = (inbc_t', inbn_t) /\\\n      Forall2 AANode.choose_inbox_rowmsg inbc inbc_t'\n  .\n  Proof.\n    replace ms with (ms ++ []) in MATCH_INBC.\n    2: { apply app_nil_r. }\n    hexploit fetch_msgs_cur_mid; eauto. i. des.\n    hexploit match_inb_end_choose_rowmsg; eauto.\n  Qed.\n\n\n  Lemma fetch_msgs_nxt\n        cbt inbn\n        inbc_t inbm ms1 ms2\n        (MATCH_INBN: match_inb\n                       (cbt + period) inbn\n                       inbm (ms1 ++ ms2))\n    : exists inbm',\n      List.fold_left\n        (flip (fetch_one_msg cbt)) ms1\n        (inbc_t, inbm) = (inbc_t, inbm') /\\\n      match_inb (cbt + period) inbn inbm' ms2.\n  Proof.\n    depgen inbm.\n    induction ms1 as [|m ms1 IH]; i; ss.\n    { esplits; eauto. }\n\n    assert (exists inbm1,\n               <<FETCH1: fetch_one_msg cbt m (inbc_t, inbm) = (inbc_t, inbm1)>> /\\\n               <<MATCH1: match_inb (cbt + period) inbn inbm1 (ms1 ++ ms2)>>).\n    { inv MATCH_INBN. ss.\n      unfold fetch_one_msg.\n      inv PMS_IN_INB. des.\n      unfold parse_pld.\n      rewrite PLD_SIZE_EQ.\n      rewrite Nat.ltb_irrefl.\n      rewrite firstn_all2; eauto.\n      2: { nia. }\n      rewrite PARSE_OK.\n      rewrite Nat.eqb_refl.\n\n      esplits; eauto.\n      { destruct (Nat.eqb_spec (cbt + period) cbt).\n        { exfalso. nia. }\n        eauto. }\n\n      eapply match_inb_upd_msg; eauto.\n      econs; eauto.\n      econs; eauto.\n      esplits; eauto.\n    }\n\n    des.\n    unfold flip at 2.\n    rewrite FETCH1.\n    hexploit IH; eauto.\n  Qed.\n\n  Lemma match_fetch_msgs\n        cbt ms_old ms_c ms_n ms_nw\n        inbc inbn\n        inbm inbc_t inbn_t inbp' ocnt\n        (OLD_MSGS : Forall (old_msg cbt) ms_old)\n        (MATCH_INBC: match_inb cbt inbc inbm ms_c)\n        (MATCH_INBN: match_inb (cbt + period)\n                               inbn AbstMW.init_inbox\n                               (ms_n ++ ms_nw))\n        (FETCH: AbstMW.fetch_msgs\n                  cbt (ms_old ++ ms_c ++ ms_n) inbm =\n                (inbc_t, inbn_t, inbp'))\n        (OCNT: ocnt = length ms_old)\n    : exists ms_old' ms_n',\n      inbp' = ms_old' ++ ms_n' /\\\n      Forall (old_msg (cbt + period)) ms_old' /\\\n      match_inb (cbt + period)\n                inbn inbn_t (ms_n' ++ ms_nw) /\\\n      AANode.abst_inbox ocnt inbc\n                        inbc_t (length ms_old')\n  .\n  Proof.\n    pose (ms_tot := ms_old ++ ms_c ++ ms_n).\n    pose (N := length task_ips * 4).\n\n    unfold fetch_msgs in FETCH.\n    fold ms_tot N in FETCH.\n    rewrite process_firstn_spec in FETCH.\n\n    destruct (lt_ge_dec N (length ms_old)).\n    { assert (exists ms_old1 ms_old2,\n                 <<MS_OLD_DIV: ms_old = ms_old1 ++ ms_old2>> /\\\n                 <<MS_OLD1: firstn N ms_tot = ms_old1>> /\\\n                 <<MS_REST: skipn N ms_tot = ms_old2 ++ ms_c ++ ms_n>>).\n      { exists (firstn N ms_old). exists (skipn N ms_old). split.\n        - rewrite firstn_skipn. ss.\n        - unfold ms_tot.\n          (* dup l. rewrite <- Nat.sub_0_le in l. *)\n          (* rewrite firstn_app, skipn_app, l. ss. *)\n          (* rewrite app_nil_r. split; ss. *)\n          rewrite firstn_app, skipn_app.\n          replace (N - length ms_old) with 0 by nia.\n          rewrite app_nil_r. split; ss.\n      }\n      des.\n      rewrite MS_OLD1, MS_REST in FETCH.\n\n      rewrite MS_OLD_DIV in OLD_MSGS.\n      eapply Forall_app_inv in OLD_MSGS. des.\n      rewrite fetch_msgs_old in FETCH by eauto.\n\n      exists (ms_old2 ++ ms_c), ms_n.\n      splits.\n      - rewrite <- app_assoc. congruence.\n      - apply Forall_app.\n        + eapply Forall_impl.\n          2: { eauto. }\n          i. eapply old_msg_adv; eauto. nia.\n        + clear MS_OLD1.\n          inv MATCH_INBC.\n          apply Forall_forall.\n          intros pm IN.\n          rewrite Forall_forall in PMS_IN_INB.\n          hexploit PMS_IN_INB; eauto.\n          i. des.\n          econs; eauto.\n          { rewrite firstn_all2; eauto. nia. }\n          nia.\n      - congruence.\n      - econs 2.\n        rewrite OCNT.\n        subst ms_tot.\n        inv MATCH_INBC. ss.\n        unfold msgT in INB_LENGTH.\n        rewrite INB_LENGTH.\n        unfold num_tasks. fold N. nia.\n    }\n\n    destruct (lt_ge_dec N (length (ms_old ++ ms_c)))\n     as [LT2 | GE2].\n    { assert (exists ms_c1 ms_c2,\n                 <<MS_C_DIV: ms_c = ms_c1 ++ ms_c2>> /\\\n                 <<MS_FSTN: firstn N ms_tot = ms_old ++ ms_c1>> /\\\n                 <<MS_REST: skipn N ms_tot = ms_c2 ++ ms_n>>).\n      { exists (firstn (N - length ms_old) ms_c).\n        exists (skipn (N - length ms_old) ms_c). split.\n        - rewrite firstn_skipn. ss.\n        - unfold ms_tot.\n          do 2 rewrite firstn_app, skipn_app.\n          rewrite firstn_all2, skipn_all2; try nia. ss.\n          rewrite app_length in *.\n          replace (N - length ms_old - length ms_c) with 0 by nia.\n          splits; ss.\n          rewrite app_nil_r. ss.\n      }\n      des.\n      rewrite MS_FSTN, MS_REST in FETCH.\n      hexploit fetch_msgs_cur_mid.\n      { rewrite MS_C_DIV in MATCH_INBC.\n        apply MATCH_INBC. }\n      intros (inbm' & PROC_C1 & MATCH_INB_C2).\n      rewrite fold_left_app in FETCH.\n      rewrite (fetch_msgs_old cbt ms_old) in FETCH by ss.\n      rewrite PROC_C1 in FETCH. clarify.\n\n      exists ms_c2, ms_n.\n      splits.\n      - clarify.\n      - inv MATCH_INBC.\n        apply Forall_forall.\n        intros pm IN.\n        rewrite Forall_forall in PMS_IN_INB.\n        hexploit PMS_IN_INB; eauto.\n        { apply in_or_app. right. eauto. }\n        i. des.\n        econs; eauto.\n        { rewrite firstn_all2; eauto. nia. }\n        nia.\n      - congruence.\n      - econs 2.\n        inv MATCH_INBC.\n        unfold msgT in INB_LENGTH.\n        rewrite INB_LENGTH.\n        unfold num_tasks. fold N.\n        fold (AANode.inbox_sz inbc).\n\n        assert (length (ms_c1 ++ ms_c2) <= AANode.inbox_sz inbc) by nia.\n        eapply lt_le_trans.\n        + eauto.\n        + rewrite app_length. nia.\n    }\n    { (* OK *)\n      assert (exists ms_n1 ms_n2,\n                 <<MS_N_DIV: ms_n = ms_n1 ++ ms_n2>> /\\\n                 <<MS_FSTN: firstn N ms_tot = ms_old ++ ms_c ++ ms_n1>> /\\\n                 <<MS_REST: skipn N ms_tot = ms_n2>>).\n      { unfold ms_tot. pose (tmp := ms_old ++ ms_c).\n        exists (firstn (N - length tmp) ms_n).\n        exists (skipn (N - length tmp) ms_n).\n        split; try by (rewrite firstn_skipn; ss).\n        unfold ms_tot.\n        repeat rewrite app_assoc. fold tmp. fold tmp in GE2.\n        rewrite firstn_app, skipn_app.\n        rewrite firstn_all2, skipn_all2; try nia. ss.\n      }\n      des. subst ms_n.\n      rewrite MS_FSTN, MS_REST in FETCH.\n\n      do 2 rewrite fold_left_app in FETCH.\n      rewrite (fetch_msgs_old cbt ms_old) in FETCH by ss.\n      eapply fetch_msgs_cur in MATCH_INBC. des.\n      rewrite MATCH_INBC in FETCH.\n      rewrite <- app_assoc in MATCH_INBN.\n      eapply fetch_msgs_nxt in MATCH_INBN. des.\n      rewrite MATCH_INBN in FETCH. clarify.\n\n      exists [], ms_n2.\n      splits.\n      - clarify.\n      - econs.\n      - congruence.\n      - ss. econs 1.\n        congruence.\n    }\n  Qed.\n\n\n  Lemma infer_mcast_id_active\n        nw ip mids\n        (MCAST_ID_DOMAIN: mcast_id_domain nw ip mids)\n        (MCAST_ID_IN_NW: mcast_id_in_nw nw ip mids)\n        (MC_PL_EMPTY : NW.mcast_msg_pool nw = [])\n    : mcast_id_active nw ip mids.\n  Proof.\n    destruct nw as [mcgs msg_pl mc_pl]. ss.\n    inv MCAST_ID_DOMAIN.\n    renames mips MCAST_IPS into mips1 MCAST_IPS1.\n    inv MCAST_ID_IN_NW.\n    renames mips MCAST_IPS into mips2 MCAST_IPS2.\n\n    assert (mips2 = mips1).\n    { eapply Forall2_det; eauto.\n      apply mcast_id_ip_det. }\n    subst mips2.\n\n    econs; eauto.\n    rewrite Forall_forall in MCMS_IN_NW.\n    apply Forall_forall.\n    intros x IN.\n    hexploit MCMS_IN_NW; eauto. i. des; ss.\n  Qed.\n\n  Section MATCH_NODE_PROOF.\n\n    Variable tm: DTime.t.\n    Variable nw nw1: NW.t.\n    Variable st_src: @AANode.state sysE.\n    (* Variable st_tgt st_tgt': @Node.state sysE. *)\n    Variable st_tgt st_tgt': @AbstMW.state sysE.\n    Variable dpms: list (ip_t * Packet.msg_t).\n\n    Variable tes: tsp * events (nbE +'sysE).\n    Variable opkt: Packet.t?.\n\n    Let tid': Tid := AANode.task_id st_src.\n    (* Hypothesis RANGE_TID: IntRange.sint8 tid'. *)\n    Hypothesis TM_LB: (DTime.of_ns (period - max_clock_skew) <= tm).\n    Hypothesis WF_SRC: AANode.state_wf tid' st_src.\n    Hypothesis WF_TGT: AbstMW.state_wf tid' st_tgt.\n\n    Hypothesis WF_NW: NW.wf nw.\n    Hypothesis NW_INV: nw_inv tm nw.\n    Hypothesis MATCH: match_lstate tm nw st_src st_tgt.\n\n    Hypothesis NW_DISTR: NW.distr nw = (nw1, dpms).\n\n    Let ip' : ip_t := AbstMW.ip_addr st_tgt.\n    Let dpms_f := Node.distr_msgs_to ip' dpms.\n\n    Let TASK_ID_IP: task_id_ip tid' ip'.\n    Proof.\n      inv WF_TGT. ss.\n    Qed.\n\n    Hypothesis STEP_TGT:\n      AbstMW.step tm dpms_f st_tgt tes opkt st_tgt'.\n\n    Let cbt: nat := get_skwd_base_time period tm.\n\n    Let CBT_SYNC: Nat.divide period cbt.\n    Proof.\n      assert (CBT: get_skwd_base_time period tm = cbt) by ss.\n      apply get_skwd_base_time_iff in CBT.\n      des. ss.\n    Qed.\n\n    Let RANGE_TM_BASETIME:\n      DTime.of_ns (cbt - max_clock_skew) <= tm\n      < DTime.of_ns (cbt + period - max_clock_skew).\n    Proof.\n      assert (CBT: get_skwd_base_time period tm = cbt) by ss.\n      apply get_skwd_base_time_iff in CBT.\n      des. ss.\n    Qed.\n\n    Let nsytm: nat := cbt + period.\n\n    Lemma step_src_working\n          (TM_POS: 0 < tm)\n          (WORKING_TIME: tm < DTime.of_ns (nsytm - max_clock_skew - max_nw_delay))\n      : exists st_src1 ms,\n        AANode.step tm st_src tes ms st_src1 /\\\n        option_rel1 Packet.wf opkt /\\\n        match_pkt nsytm tid' ms opkt /\\\n        (* match_lstate (DTime.succ tm) nw1 *)\n        (*              st_src1 st_tgt' /\\ *)\n        (forall (outs_src: list (Tid * msgT)?)\n           (outs_tgt: list (Packet.t)?)\n           nw'\n           (LEN_OUTS: length outs_src = num_tasks)\n           (MATCH_OUTMSGS: iForall2 (match_pkt nsytm)\n                                    0 outs_src outs_tgt)\n           (OUTS_SRC_NTH: nth_error outs_src tid' = Some ms)\n           (OUTS_TGT_NTH: nth_error outs_tgt tid' = Some opkt)\n           (NW: NW.gather nw1 (filtermap id outs_tgt) nw')\n          ,\n            let st_src' :=\n                AANode.accept_msgs tm outs_src st_src1 in\n            match_lstate (DTime.succ tm) nw'\n                         st_src' st_tgt'\n        ).\n    Proof.\n      subst tid' ip'.\n\n      assert (CBT_SUCC: get_skwd_base_time period (DTime.succ tm) = cbt).\n      { apply get_skwd_base_time_iff; eauto. ss.\n        splits; ss.\n        - clear - RANGE_TM_BASETIME. nia.\n        - clear - WORKING_TIME PERIOD_COND.\n          pose proof max_nw_delay_pos. nia.\n      }\n\n      inv MATCH; ss.\n      - (* Off *)\n        eexists (AANode.State tid node inbn None), None.\n\n        inv STEP_TGT. ss. existT_elim. subst.\n        fold cbt in MATCH_NW.\n        inv ISTEP; ss.\n        + esplits.\n          * econs 1.\n          * nia.\n          * econs 1.\n          * i. econs 1; eauto.\n            { eapply mcast_id_domain_nwstep; eauto. }\n            (* inv WF_SRC. ss. } *)\n            (* eapply match_inb_pre_empty. *)\n            eapply match_inb_pre_nwstep; eauto.\n\n        + esplits.\n          * econs 1.\n          * nia.\n          * econs 1.\n          * i. econs 2; eauto.\n            -- eapply mcast_id_domain_nwstep; eauto.\n               (* inv WF_SRC. ss. *)\n            -- rewrite CBT_SUCC. ss.\n            -- rewrite CBT_SUCC. ss.\n               fold cbt in RANGE_TM.\n               splits.\n               { clear - RANGE_TM. nia. }\n               { clear - WORKING_TIME. nia. }\n            -- rewrite CBT_SUCC. fold cbt. reflexivity.\n            -- inv WF_SRC. eapply app_nil_l.\n            -- econs; econs.\n            -- rewrite CBT_SUCC.\n               (* eapply match_inb_pre_empty. *)\n               eapply match_inb_pre_nwstep; eauto.\n\n      - (* Off - Prep *)\n        inv STEP_TGT. existT_elim. subst. ss.\n        fold cbt in MATCH_NW.\n\n        assert (NOT_EXACT: exact_skwd_base_time period tm = None).\n        { eapply exact_skwd_base_time_None_iff.\n          - clear - RANGE_TM. nia.\n          - exists cbt.\n            splits.\n            + unfold cbt. apply RANGE_TM.\n            + unfold cbt.\n              clear - RANGE_TM_BASETIME. nia.\n            + ss.\n        }\n\n        inv ISTEP; ss.\n        + (* Off *)\n          esplits.\n          * econs 1.\n          (* * ss. nia. *)\n          * ss.\n          * econs 1.\n          * i. rewrite <- MCAST_IPS_TO_JOIN in MCAST_ID_DOMAIN.\n            econs 1; eauto.\n            { eapply mcast_id_domain_nwstep; eauto. }\n            eapply match_inb_pre_nwstep; eauto.\n\n        + (* Prep (stay) *)\n          esplits.\n          * econs 1.\n          (* * ss. nia. *)\n          * ss.\n          * econs 1.\n          * i. econs 2.\n            -- eauto.\n            -- eapply mcast_id_domain_nwstep; eauto.\n               congruence.\n            -- ss.\n            -- rewrite CBT_SUCC. reflexivity.\n            -- apply CBT_LB.\n            -- reflexivity.\n            -- ss. splits.\n               { fold cbt in RANGE_TM.\n                 clear - RANGE_TM. nia. }\n               { fold cbt in BEFORE_LIMIT.\n                 clear - BEFORE_LIMIT. nia. }\n            -- eauto.\n            -- fold cbt. reflexivity.\n            -- eauto.\n            -- hexploit mcast_id_in_nw_nwstep; eauto.\n               { econs 1. }\n               ss. rewrite app_nil_r. ss.\n            -- rewrite NOT_EXACT.\n               eapply match_inb_pre_nwstep_nexact; eauto.\n\n        + (* Prep (join) *)\n          assert (MIP1: exists mip1,\n                     mcast_member tid mid_j /\\\n                     mcast_id_ip mid_j mip1).\n          { (* inv WF_SRC. *)\n            hexploit (get_mcast_of_spec tid mid_j); eauto.\n            { rewrite <- MCAST_IPS_TO_JOIN.\n              apply in_or_app. right. ss. eauto. }\n            i. des.\n            exists mip.\n            split.\n            - r. rewrite <- MCAST_IPS_TO_JOIN.\n              apply in_or_app. right. ss. eauto.\n            - r. esplits; eauto.\n              (* apply map_nth_error_iff. *)\n              (* esplits; eauto. *)\n          }\n          destruct MIP1 as (mip_j & MCM_J & MCAST_ID_IP).\n\n          hexploit mcast_id_ip_comput; eauto.\n          destruct 1 as [TID2IP_J MIP_J_MCAST].\n\n          esplits.\n          * econs 1.\n          (* * ss. nia. *)\n          * rewrite TID2IP_J.\n            econs. econs.\n            { ss. }\n            eapply task_id_ip_comput in TASK_ID_IP.\n            destruct TASK_ID_IP. ss.\n          * rewrite TID2IP_J.\n            econs 2; eauto.\n          * i. replace (mids1 ++ mid_j :: mids_j') with\n                   (snoc mids1 mid_j ++ mids_j').\n            2: { unfold snoc. rewrite <- app_assoc. ss. }\n\n            fold cbt.\n            replace (mids1 ++ mid_j :: mids_j') with\n                (snoc mids1  mid_j ++ mids_j') in MCAST_IPS_TO_JOIN.\n            2: { unfold snoc. rewrite <- app_assoc. ss. }\n\n            econs 2; eauto.\n            -- rewrite MCAST_IPS_TO_JOIN.\n               eapply mcast_id_domain_nwstep; eauto.\n            -- rewrite CBT_SUCC. ss.\n            -- rewrite CBT_SUCC. ss.\n               split.\n               { clear - RANGE_TM. nia. }\n               { clear - BEFORE_LIMIT. nia. }\n            -- rewrite CBT_SUCC. eauto.\n            -- hexploit mcast_id_in_nw_nwstep; eauto.\n               { econs.\n                 rewrite TID2IP_J. eauto. }\n               { s. unfold snoc. ss. }\n            -- rewrite NOT_EXACT.\n               rewrite CBT_SUCC.\n               eapply match_inb_pre_nwstep_nexact; eauto.\n\n        + (* ready *)\n          esplits.\n          { econs 1. }\n          (* { ss. nia. } *)\n          { ss. }\n          { econs 1. }\n          i. econs 3; eauto.\n          * eapply mcast_id_domain_nwstep; eauto.\n            rewrite MCAST_IPS_TO_JOIN. ss.\n          * rewrite CBT_SUCC. ss.\n            split.\n            { clear - RANGE_TM. nia. }\n            { clear - BEFORE_LIMIT. nia. }\n          * rewrite CBT_SUCC. fold cbt.\n            f_equal.\n            clear - PERIOD_COND. nia.\n          * hexploit mcast_id_in_nw_nwstep; eauto.\n            { econs. }\n            ss.\n          * rewrite NOT_EXACT.\n            rewrite CBT_SUCC.\n            eapply match_inb_pre_nwstep_nexact; eauto.\n\n      - (* Off-Ready *)\n        hexploit (skwd_time_range_almost_overwrap\n                    (DTime.succ tm_p) cbt\n                    (get_skwd_base_time period tm_p)); eauto.\n        { eapply get_skwd_base_time_iff; eauto. }\n        intro CBT_PRED. guardH CBT_PRED.\n\n        inv STEP_TGT. existT_elim. subst. ss.\n        inv ISTEP; ss.\n        + (* Off *)\n          esplits.\n          { econs 1. }\n          (* { ss. nia. } *)\n          { ss. }\n          { econs 1. }\n          i. econs 1; eauto.\n          { eapply mcast_id_domain_nwstep; eauto. }\n          (* inv WF_SRC. ss. } *)\n\n          desH CBT_PRED.\n          * assert (EXACT_NONE: exact_skwd_base_time period (DTime.succ tm_p) = None).\n            { eapply exact_skwd_base_time_None_iff.\n              { ss. }\n              exists cbt.\n              splits; ss.\n              - rewrite <- CBT_PRED in RANGE_TM.\n                apply RANGE_TM.\n              - apply RANGE_TM_BASETIME.\n            }\n            rewrite EXACT_NONE.\n            rewrite <- CBT_PRED in MATCH_NW.\n            eapply match_inb_pre_empty.\n            eapply match_inb_pre_nwstep_nexact; eauto.\n          * assert (EXACT_CBT: exact_skwd_base_time period (DTime.succ tm_p) = Some cbt).\n            { eapply exact_skwd_base_time_iff.\n              splits; ss.\n              rewrite CBT_PRED.\n              clear - PERIOD_COND. nia. }\n            rewrite EXACT_CBT.\n            (* rewrite <- CBT_PRED in MATCH_NW. *)\n            eapply match_inb_pre_empty.\n            eapply match_inb_pre_nwstep_exact; eauto.\n            eapply match_inb_pre_adv; eauto.\n            clear - CBT_PRED PERIOD_COND. nia.\n\n        + (* Ready *)\n          destruct CBT_PRED as [CBT_EQ | [CBT_EQ TM_P_EXACT]].\n          * (* stay *)\n            assert (EXACT_NONE: exact_skwd_base_time period (DTime.succ tm_p) = None).\n            { eapply exact_skwd_base_time_None_iff.\n              { ss. }\n              exists cbt.\n              splits; ss.\n              - rewrite <- CBT_EQ in RANGE_TM.\n                apply RANGE_TM.\n              - apply RANGE_TM_BASETIME.\n            }\n\n            esplits.\n            { econs 1. }\n            (* { ss. nia. } *)\n            { ss. }\n            { econs 1. }\n            i. econs 3; eauto.\n            { eapply mcast_id_domain_nwstep; eauto. }\n              (* inv WF_SRC; ss. } *)\n            { rewrite CBT_SUCC.\n              clear - RANGE_TM_BASETIME.\n              ss. nia. }\n            { rewrite <- CBT_EQ.\n              rewrite CBT_SUCC.\n              reflexivity. }\n            { (*joined_prsv*)\n              hexploit mcast_id_in_nw_nwstep; eauto.\n              { econs. }\n              ss. rewrite app_nil_r. ss. }\n\n            rewrite EXACT_NONE.\n            rewrite CBT_SUCC.\n            rewrite <- CBT_EQ in MATCH_NW.\n            eapply match_inb_pre_nwstep_nexact; eauto.\n          * (* Go to Done-Ready *)\n            assert (EXACT_CBT: exact_skwd_base_time period (DTime.succ tm_p) = Some cbt).\n            { eapply exact_skwd_base_time_iff.\n              splits; ss.\n              rewrite CBT_EQ.\n              clear - PERIOD_COND. nia. }\n\n            hexploit nw_exact_empty; eauto.\n            intros (MSG_PL_EMPTY & MC_PL_EMPTY & DISTR_EQ).\n            rewrite DISTR_EQ in NW_DISTR.\n            symmetry in NW_DISTR. clarify.\n\n            assert (NW_F_EMPTY: nw_msgs_to ip nw = []).\n            { unfold nw_msgs_to.\n              rewrite MSG_PL_EMPTY. ss. }\n\n            assert (DPMS_F_EMPTY: dpms_f = []).\n            { subst dpms_f. ss. }\n\n            esplits; eauto.\n            { eapply AANode.Step_TurnOn with\n                  (ocnt := length inbp); eauto.\n              inv MATCH_NW.\n              rewrite NW_F_EMPTY in PMS_TOT_LEN.\n              rewrite app_nil_r in PMS_TOT_LEN. ss. }\n            (* { ss. nia. } *)\n            (* { ss. } *)\n            { econs 1. }\n\n            i. rewrite DPMS_F_EMPTY. ss.\n            hexploit infer_mcast_id_active; eauto.\n            intro MCAST_ID_ACTIVE.\n\n            econs 4; eauto.\n            (* { eauto. } *)\n            { eapply mcast_id_active_nwstep; eauto.\n              econs. }\n            { clear - RANGE_TM TM_P_EXACT.\n              ss. nia. }\n            { rewrite <- CBT_EQ. ss. }\n            { inv MATCH_NW.\n              rewrite NW_F_EMPTY in PMS_TOT_OLD.\n              rewrite app_nil_r in PMS_TOT_OLD.\n              eapply Forall_impl.\n              2: { eauto. }\n              i. eapply old_msg_adv; eauto.\n              rewrite CBT_EQ.\n              clear.\n              hexploit (get_skwd_base_time_mono tm_p (DTime.succ tm_p)).\n              { ss. nia. }\n              i. nia.\n            }\n\n            rewrite EXACT_CBT.\n            rewrite app_nil_l.\n            hexploit match_inb_nwstep; eauto.\n            { rewrite NW_F_EMPTY. rewrite app_nil_r.\n              eapply match_inb_empty. }\n            ss.\n\n        + (* period_begin *)\n          exfalso.\n          (* SYNC_TIME *)\n          fold cbt in SYNC_TIME.\n          desH CBT_PRED.\n          * rewrite <- CBT_PRED in SYNC_TIME.\n            clear - SYNC_TIME PERIOD_COND. nia.\n          * rewrite <- CBT_PRED in SYNC_TIME.\n            clear - SYNC_TIME PERIOD_COND. nia.\n\n      - (* Done-Ready *)\n        rename cbt0 into cbt_p.\n        hexploit (skwd_time_range_almost_overwrap tm cbt cbt_p); eauto.\n        intro CBT_PRED. guardH CBT_PRED.\n\n        inv STEP_TGT. existT_elim. subst. ss.\n        inv ISTEP; ss.\n        + (* Off *)\n          esplits.\n          { eapply AANode.Step_Fail. }\n          (* { ss. nia. } *)\n          { ss. }\n          { econs 1. }\n          i. econs 1; eauto.\n          { hexploit mcast_id_active_nwstep; eauto.\n            { econs. }\n            apply mcast_id_active_impl_domain. }\n          eapply match_inb_pre_nwstep; eauto.\n          { apply mcast_id_active_impl_domain. ss. }\n          eapply match_inb_pre_adv.\n          { eapply match_inb_to_pre; eauto. }\n          desH CBT_PRED; subst; ss.\n          rewrite CBT_PRED. nia.\n\n        + (* Ready *)\n          destruct CBT_PRED as [CBT_EQ | [CBT_EQ TM_EQ]].\n          * subst cbt_p.\n            assert (EXACT_NONE: exact_skwd_base_time period tm = None).\n            { apply exact_skwd_base_time_None_iff.\n              { clear - RANGE_TM. nia. }\n              exists cbt.\n              splits; ss; nia.\n            }\n            esplits.\n            { eapply AANode.Step_On_Stay; eauto. }\n            (* { ss. nia. } *)\n            { ss. }\n            { econs 1. }\n            i. rewrite <- app_assoc. ss.\n            econs 4; eauto.\n            { eapply mcast_id_active_nwstep; eauto.\n              econs. }\n            { clear - RANGE_TM_BASETIME. ss. nia. }\n\n            rewrite EXACT_NONE.\n            eapply match_inb_nwstep; eauto.\n\n          * (* Go to Ready-Ready *)\n            assert (EXACT_TM: exact_skwd_base_time period tm = Some cbt).\n            { apply exact_skwd_base_time_iff.\n              splits; ss.\n              clear - CBT_EQ PERIOD_COND. nia. }\n\n            hexploit nw_exact_empty; eauto.\n            intros (MSG_PL_EMPTY & MC_PL_EMPTY & DISTR_EQ).\n            rewrite DISTR_EQ in NW_DISTR.\n            symmetry in NW_DISTR. clarify.\n\n            assert (NW_F_EMPTY: nw_msgs_to ip nw = []).\n            { unfold nw_msgs_to.\n              rewrite MSG_PL_EMPTY. ss. }\n            assert (DPMS_F_EMPTY: dpms_f = []).\n            { subst dpms_f. ss. }\n\n            rewrite DPMS_F_EMPTY. ss.\n            esplits.\n            { eapply AANode.Step_Sync; eauto. }\n            (* { ss. nia. } *)\n            { ss. }\n            { econs 1. }\n            i. econs 5; eauto.\n            { eapply mcast_id_active_nwstep; eauto.\n              econs. }\n            { clear - RANGE_TM_BASETIME TIME_UB CBT_EQ.\n              ss. split; nia. }\n            { rewrite <- CBT_EQ.\n              rewrite app_assoc. ss. }\n            (* { hexploit mcast_id_in_nw_nwstep; eauto. *)\n            (*   { econs. } *)\n            (*   ss. rewrite app_nil_r. ss. } *)\n            { rewrite CBT_EQ. ss. }\n            { rewrite CBT_EQ.\n              rewrite NW_F_EMPTY in MATCH_INB.\n              rewrite app_nil_r in MATCH_INB. ss.\n            }\n            (* new match_inb *)\n            rewrite EXACT_TM.\n            replace (nw_msgs_to ip nw') with\n                (filter_port dpms_f ++ nw_msgs_to ip nw').\n            2: { rewrite DPMS_F_EMPTY. ss. }\n            rewrite app_assoc.\n            eapply match_inb_nwstep; eauto.\n            rewrite NW_F_EMPTY. ss.\n            apply match_inb_empty.\n\n        + (* run *)\n          exfalso.\n          (* fold cbt in SYNC_TIME. *)\n          clear - CBT_PRED RANGE_TM RANGE_TIME.\n          desH CBT_PRED.\n          * subst cbt. nia.\n          * subst cbt. nia.\n\n      - (* Ready-Ready *)\n        assert (sytm = cbt).\n        { hexploit (skwd_time_range_almost_overwrap tm cbt sytm); eauto.\n          { clear - RANGE_TM. nia. }\n          intros [? | [CBT_EQ TM_EQ]].\n          { ss. }\n          exfalso.\n          rewrite CBT_EQ in TM_EQ.\n          clear - RANGE_TM TM_EQ.\n          pose proof max_nw_delay_pos. nia.\n        }\n        subst sytm.\n        fold nsytm in RANGE_TM.\n\n        assert (EXACT_NONE: exact_skwd_base_time period tm = None).\n        { eapply exact_skwd_base_time_None_iff.\n          { clear - RANGE_TM. nia. }\n          exists cbt.\n          splits; ss; nia. }\n\n        inv STEP_TGT. existT_elim. subst. ss.\n        inv ISTEP; ss.\n        + (* Off *)\n          esplits.\n          { eapply AANode.Step_Fail. }\n          (* { ss. nia. } *)\n          { ss. }\n          { econs 1. }\n          i. econs 1; eauto.\n          { hexploit mcast_id_active_nwstep; eauto.\n            { econs. }\n            apply mcast_id_active_impl_domain. }\n          eapply match_inb_pre_nwstep; eauto.\n          { apply mcast_id_active_impl_domain. ss. }\n          eapply match_inb_to_pre; eauto.\n\n        + (* Stay *)\n          esplits.\n          { eapply AANode.Step_On_Stay; eauto. }\n          (* { ss. nia. } *)\n          { ss. }\n          { econs 1. }\n          i. econs 5; eauto.\n          { eapply mcast_id_active_nwstep; eauto.\n            econs. }\n          { clear - RANGE_TM TIME_UB. ss. nia. }\n          (* { hexploit mcast_id_in_nw_nwstep; eauto. *)\n          (*   { econs. } *)\n          (*   ss. rewrite app_nil_r. ss. } *)\n          { repeat rewrite <- app_assoc. reflexivity. }\n\n          (* rewrite <- app_assoc. *)\n          eapply match_inb_nwstep; eauto.\n          rewrite EXACT_NONE. ss.\n\n        + (* Go to Running *)\n          renames inbc0 inbn0 into inbc_t inbn_t.\n          assert (NOT_EXACT: exact_skwd_base_time period tm = None).\n          { eapply exact_skwd_base_time_None_iff; eauto.\n            exists cbt. splits; ss; nia. }\n\n          repeat rewrite <- app_assoc in FETCH_MSGS.\n          hexploit match_inb_distr; eauto.\n          intros [MATCH_INB_D MCAST_ID_DOMAIN_D].\n\n          hexploit match_fetch_msgs; eauto.\n          intros (ms_old' & ms_n' & INBP' & MS_OLD' &\n                  MATCH_INB' & ABST_INBOX).\n\n          esplits; eauto.\n          { eapply AANode.Step_StartRun; eauto. }\n          (* { ss. nia. } *)\n          { econs. }\n\n          i. econs 6; eauto.\n          { eapply mcast_id_active_nwstep; eauto.\n            econs. }\n          { clear - RANGE_TIME. ss. nia. }\n          (* { hexploit mcast_id_in_nw_nwstep; eauto. *)\n          (*   { econs. } *)\n          (*   ss. rewrite app_nil_r. ss. } *)\n\n          rewrite NOT_EXACT.\n          eapply match_inb_gather;\n            try apply NW; eauto.\n          { hexploit NW.wf_distr_preserve; eauto.\n            i. des. ss. }\n          { eapply mcast_id_active_distr; eauto. }\n\n      - (* Runnings *)\n        assert (sytm = cbt).\n        { hexploit (skwd_time_range_almost_overwrap tm cbt sytm); eauto.\n          { clear - RANGE_TM. nia. }\n          intros [? | [CBT_EQ TM_EQ]].\n          { ss. }\n          exfalso.\n          rewrite CBT_EQ in TM_EQ.\n          clear - RANGE_TM TM_EQ.\n          pose proof max_nw_delay_pos. nia.\n        }\n        subst sytm.\n        fold nsytm in RANGE_TM.\n\n        assert (NOT_EXACT: exact_skwd_base_time period tm = None).\n        { eapply exact_skwd_base_time_None_iff; eauto.\n          exists cbt. splits; ss; nia. }\n\n        inv STEP_TGT. existT_elim. subst. ss.\n        inv ISTEP; ss.\n        + (* Off *)\n          esplits.\n          { eapply AANode.Step_Fail. }\n          (* { ss. nia. } *)\n          { ss. }\n          { econs 1. }\n          i. econs 1; eauto.\n          { hexploit mcast_id_active_nwstep; eauto.\n            { econs. }\n            apply mcast_id_active_impl_domain. }\n          rewrite NOT_EXACT.\n          eapply match_inb_impl_pre.\n          eapply match_inb_nwstep; eauto.\n\n        + (* stay *)\n          esplits.\n          { eapply AANode.Step_On_Stay; eauto. }\n          (* { ss. nia. } *)\n          { ss. }\n          { econs 1. }\n          i. ss.\n          rewrite <- app_assoc.\n          econs 6; eauto.\n          { eapply mcast_id_active_nwstep; eauto.\n            econs. }\n          { clear - RANGE_TM TIME_UB. ss. nia. }\n\n          rewrite NOT_EXACT.\n          eapply match_inb_nwstep; eauto.\n\n        + (* Go *)\n          assert (RANGE_NSYTM: IntRange.uint64 nsytm).\n          { apply lt_maxtime_nxt_in_range. ss. }\n\n          destruct opkt as [pkt|].\n          * destruct om as [[tid_d msg]|]; ss.\n\n            destruct (check_send_hist sh tid_d) as [sh''|] eqn:SH'; ss.\n            clarify.\n\n            esplits; ss.\n            { eapply AANode.Step_Running_Go; eauto.\n              ss. rewrite SH'. eauto. }\n            (* { ss. } *)\n            { eapply wf_srl_pm. }\n            { econs; eauto.\n              - eapply resize_bytes_length; eauto.\n              - r. instantiate (1:= tid2ip tid_d).\n                unfold dest_ips.\n\n                eapply check_send_hist_Some in SH'.\n                des.\n                + rewrite nth_error_app1.\n                  2: { apply DEST_TASK_ID. }\n                  apply valid_task_id_ip. eauto.\n                + hexploit valid_mcast_id_ip; eauto.\n                  intro MCAST_ID_IP. r in MCAST_ID_IP. des.\n                  rewrite nth_error_app2.\n                  2: { fold num_tasks.\n                       clear - MCAST_ID_IP. nia. }\n                  replace (tid_d - length task_ips) with midx.\n                  2: { fold num_tasks.\n                       clear - MCAST_ID_IP. nia. }\n                  eauto.\n                + inv WF_SRC.\n                  existT_elim. clarify. ss.\n                  inv ISTATE_WF.\n                  eauto.\n              - f_equal.\n                hexploit task_id_ip_comput; eauto.\n                i. des. ss.\n            }\n            i. rewrite <- app_assoc.\n            econs 6; eauto.\n            { eapply mcast_id_active_nwstep; eauto.\n              desf. econs. }\n            { clear - RANGE_TM TIME_UB. ss. nia. }\n            rewrite NOT_EXACT.\n            eapply match_inb_nwstep; eauto.\n\n          * assert (OUT_SRC_NONE: AANode.process_outmsg sh om = (sh, None)).\n            { destruct om as [[tid_d m]|]; ss.\n              desf. }\n\n            rewrite <- app_assoc.\n            esplits; eauto.\n            { eapply AANode.Step_Running_Go; eauto. }\n            (* { ss. nia. } *)\n            { econs. }\n            { subst nsytm. econs. }\n            i. econs 6; eauto.\n            { eapply mcast_id_active_nwstep; eauto. econs. }\n            { clear - RANGE_TM TIME_UB. ss. nia. }\n            { unfold check_and_send in *. desf. }\n            rewrite NOT_EXACT.\n            eapply match_inb_nwstep; eauto.\n\n        + (* Done *)\n          rewrite <- app_assoc.\n          esplits.\n          { eapply AANode.Step_Running_Done; eauto. }\n          (* { ss. nia. } *)\n          { ss. }\n          { econs 1. }\n          i. econs 4; eauto.\n          { eapply mcast_id_active_nwstep; eauto.\n            econs. }\n          { clear - RANGE_TM TIME_UB. ss. nia. }\n          (* { hexploit mcast_id_in_nw_nwstep; eauto. *)\n          (*   { econs. } *)\n          (*   ss. rewrite app_nil_r. ss. } *)\n          rewrite NOT_EXACT.\n          eapply match_inb_nwstep; eauto.\n    Qed.\n\n    Lemma step_src_in_btw\n          (TIME_IN_BTW: DTime.of_ns (nsytm - max_clock_skew - max_nw_delay) <= tm)\n      : opkt = None /\\\n        exists st_src',\n        AANode.step tm st_src tes None st_src' /\\\n        match_lstate (DTime.succ tm) nw1\n                     st_src' st_tgt'.\n    Proof.\n      subst tid'. subst ip'.\n\n      inv MATCH; ss.\n      - (* Off-Off *)\n        inv STEP_TGT. existT_elim.\n        subst. ss.\n\n        assert (MATCH_INB': match_inb_pre cbt ip nw1 [] inbn).\n        { eapply match_inb_pre_distr in MATCH_NW; eauto.\n          eapply match_inb_pre_empty; eauto. }\n\n        inv ISTEP; ss.\n        + esplits; eauto.\n          * econs 1; eauto.\n          * econs 1; ss.\n            { eapply mcast_id_domain_distr; eauto. }\n            eapply match_inb_pre_adv; eauto.\n            subst nsytm.\n            cut (cbt <= get_skwd_base_time period (DTime.succ tm)).\n            { nia. }\n            subst cbt.\n            apply get_skwd_base_time_mono. ss. nia.\n\n        + fold cbt in RANGE_TM.\n          assert (SKWD_BASE_TIME_EQ:\n                    get_skwd_base_time\n                      period (DTime.succ tm) = cbt).\n          { apply get_skwd_base_time_iff; eauto. ss.\n            splits; ss.\n            - clear - RANGE_TM. nia.\n            - clear - RANGE_TM PERIOD_COND.\n              pose proof max_nw_delay_pos.\n              nia.\n          }\n\n          esplits; eauto.\n          * econs 1; eauto.\n          * econs 2; eauto.\n            -- eapply mcast_id_domain_distr; eauto.\n            -- rewrite SKWD_BASE_TIME_EQ. ss.\n            -- rewrite SKWD_BASE_TIME_EQ. ss. nia.\n            -- rewrite SKWD_BASE_TIME_EQ.\n               fold cbt. reflexivity.\n            -- inv WF_SRC. apply app_nil_l.\n            -- econs 1; econs.\n            -- eapply match_inb_pre_adv; eauto.\n               subst nsytm.\n               cut (cbt <= get_skwd_base_time\n                            period (DTime.succ tm)).\n               { nia. }\n               subst cbt.\n               apply get_skwd_base_time_mono. ss. nia.\n\n      - (* Off-Prep *)\n        fold cbt nsytm in RANGE_TM, STEP_TGT, CBT_LB.\n\n        assert (MATCH_INB': match_inb_pre cbt ip nw1 [] inbn).\n        { eapply match_inb_pre_distr in MATCH_NW; eauto.\n          eapply match_inb_pre_empty; eauto. }\n\n        assert (TM_EQ: DTime.units tm =\n                       (nsytm - max_clock_skew - max_nw_delay) *\n                       DTime.units_per_ns) by nia.\n\n        inv STEP_TGT. existT_elim. subst.\n        inv ISTEP; ss; [|nia..].\n\n        esplits; eauto.\n        + econs 1.\n        + econs 1; eauto.\n          { eapply mcast_id_domain_distr; eauto.\n            rewrite MCAST_IPS_TO_JOIN. ss. }\n          eapply match_inb_pre_adv; eauto.\n          subst nsytm.\n          cut (cbt <= get_skwd_base_time period (DTime.succ tm)).\n          { nia. }\n          subst cbt.\n          apply get_skwd_base_time_mono. ss. nia.\n\n      - (* Off - Run *)\n        fold cbt nsytm in RANGE_TM, STEP_TGT.\n\n        assert (MATCH_INB': match_inb_pre cbt ip nw1 [] inbn).\n        { eapply match_inb_pre_distr in MATCH_NW; eauto.\n          eapply match_inb_pre_empty; eauto.\n          eapply match_inb_pre_adv; eauto.\n          subst nsytm.\n          cut (get_skwd_base_time period tm_p <= cbt).\n          { nia. }\n          apply get_skwd_base_time_mono. ss. nia.\n        }\n\n        inv STEP_TGT. existT_elim. subst.\n        (* fold cbt in ISTEP. *)\n\n        assert (SKWD_BASE_TIME_P:\n                  get_skwd_base_time period tm_p = cbt).\n        { apply get_skwd_base_time_iff; eauto.\n          splits; ss.\n          - clear - PERIOD_COND TIME_IN_BTW.\n            unfold DTime.of_ns. ss. nia.\n          - unfold DTime.of_ns. ss. nia.\n        }\n        rewrite SKWD_BASE_TIME_P in *.\n\n        inv ISTEP; ss.\n        + (* off *)\n          esplits; eauto.\n          * econs 1.\n          * econs 1; eauto.\n            { eapply mcast_id_domain_distr; eauto. }\n            eapply match_inb_pre_adv; eauto.\n            subst nsytm. subst cbt.\n            apply get_skwd_base_time_mono. ss. nia.\n\n        + (* ready *)\n          (* rewrite SKWD_BASE_TIME_P. *)\n          esplits; eauto.\n          * econs 1.\n          * econs 3; try reflexivity; eauto.\n            -- eapply mcast_id_domain_distr; eauto.\n            -- fold cbt. ss. nia.\n            -- eapply mcast_id_in_nw_distr; eauto.\n            -- eapply match_inb_pre_distr; eauto.\n        + (* running *)\n          exfalso.\n          fold cbt in SYNC_TIME.\n          (* rewrite SKWD_BASE_TIME_P in SYNC_TIME. *)\n          clear - SYNC_TIME PERIOD_COND. nia.\n\n      - (* Done-Ready *)\n        hexploit (skwd_time_range_almost_overwrap\n                    tm cbt cbt0); eauto.\n        destruct 1 as [CBT_EQ | [CBT_EQ TM_EQ]].\n        2: {\n          exfalso.\n          clear - TIME_IN_BTW TM_EQ PERIOD_COND.\n          pose proof DTime.units_per_ns_pos.\n          subst nsytm. nia.\n        }\n        subst cbt0.\n\n        inv STEP_TGT. existT_elim. subst. ss.\n        inv ISTEP; ss.\n        + (* fail *)\n          esplits; ss.\n          * eapply AANode.Step_Fail.\n          * econs 1; eauto.\n            { eapply mcast_id_domain_distr; eauto.\n              apply mcast_id_active_impl_domain. ss. }\n            eapply match_inb_pre_empty; eauto.\n            eapply match_inb_pre_distr; eauto.\n            eapply match_inb_impl_pre in MATCH_INB; eauto.\n            eapply match_inb_pre_adv in MATCH_INB; eauto.\n            apply get_skwd_base_time_mono. ss. nia.\n\n        + (* stay *)\n          esplits; ss.\n          * eapply AANode.Step_On_Stay; eauto.\n            destruct (exact_skwd_base_time period tm) eqn: EXACT_TM; ss.\n            apply exact_skwd_base_time_iff in EXACT_TM; eauto.\n            destruct EXACT_TM as (N_POS & TM_EQ & N_DIV).\n            assert (get_skwd_base_time period tm = n).\n            { apply get_skwd_base_time_iff. ss.\n              split; ss.\n              split.\n              - rewrite TM_EQ. ss.\n              - rewrite TM_EQ.\n                clear - PERIOD_COND.\n                pose proof DTime.units_per_ns_pos. nia.\n            }\n            exfalso.\n            clarify.\n            fold cbt in TM_EQ. des.\n            nia.\n          * rewrite <- app_assoc.\n            eapply Match_Done_Ready with (inbm := inbm); eauto.\n            -- eapply mcast_id_active_distr; eauto.\n            -- ss.\n               split.\n               { clear - RANGE_TM. nia. }\n               { clear - RANGE_TM_BASETIME. nia. }\n            -- rewrite <- app_assoc.\n               (* eapply nw_msgs_to_adv; eauto. *)\n               hexploit match_inb_distr; eauto.\n               i. des.\n               unfold dpms_f.\n               rewrite app_assoc. ss.\n\n        + (* running *)\n          exfalso.\n          fold cbt in SYNC_TIME.\n          clear - SYNC_TIME PERIOD_COND. nia.\n\n      - (* Ready-Ready *)\n        assert (sytm = cbt).\n        { hexploit (skwd_time_range_almost_overwrap\n                      tm cbt sytm); eauto.\n          { clear - RANGE_TM. nia. }\n          intros [? | [CBT_EQ TM_EQ]].\n          { ss. }\n          exfalso.\n          rewrite CBT_EQ in TM_EQ.\n          clear - RANGE_TM TM_EQ.\n          pose proof max_nw_delay_pos. nia.\n        }\n        subst sytm.\n        fold nsytm in RANGE_TM.\n\n        assert (TM_EQ: (tm: nat) = (nsytm - max_clock_skew - max_nw_delay) * DTime.units_per_ns) by nia.\n        ss.\n\n        inv STEP_TGT. existT_elim. subst. ss.\n        inv ISTEP; ss.\n        + (* fail *)\n          esplits; ss.\n          * eapply AANode.Step_Fail.\n          * econs 1; eauto.\n            { eapply mcast_id_domain_distr; eauto.\n              apply mcast_id_active_impl_domain. ss. }\n            eapply match_inb_impl_pre in MATCH_INBN; eauto.\n            eapply match_inb_pre_distr in MATCH_INBN; eauto.\n            eapply match_inb_pre_empty in MATCH_INBN; eauto.\n            eapply match_inb_pre_adv; eauto.\n            apply get_skwd_base_time_mono. ss. nia.\n\n        + (* tgt ready *)\n          exfalso.\n          clear - TM_EQ TIME_UB. nia.\n        + (* tgt running *)\n          exfalso.\n          clear - TM_EQ RANGE_TIME. nia.\n\n      - (* Runnings *)\n        assert (sytm = cbt).\n        { hexploit (skwd_time_range_almost_overwrap\n                      tm cbt sytm); eauto.\n          { clear - RANGE_TM. nia. }\n          intros [? | [CBT_EQ TM_EQ]].\n          { ss. }\n          exfalso.\n          rewrite CBT_EQ in TM_EQ.\n          clear - RANGE_TM TM_EQ.\n          pose proof max_nw_delay_pos. nia.\n        }\n        subst sytm.\n        fold nsytm in RANGE_TM.\n\n        assert (TM_EQ: (tm: nat) = (nsytm - max_clock_skew - max_nw_delay) * DTime.units_per_ns) by nia.\n        ss.\n\n        inv STEP_TGT. existT_elim. subst. ss.\n        inv ISTEP; ss.\n        + (* fail *)\n          esplits; ss.\n          * eapply AANode.Step_Fail.\n          * econs 1; eauto.\n            { eapply mcast_id_domain_distr; eauto.\n              apply mcast_id_active_impl_domain. ss. }\n            eapply match_inb_impl_pre in MATCH_INBN; eauto.\n            eapply match_inb_pre_distr in MATCH_INBN; eauto.\n            eapply match_inb_pre_empty in MATCH_INBN; eauto.\n            eapply match_inb_pre_adv; eauto.\n            apply get_skwd_base_time_mono. ss. nia.\n        + (* tgt running1 *)\n          exfalso.\n          clear - TM_EQ TIME_UB. nia.\n        + (* tgt running2 *)\n          exfalso.\n          clear - TM_EQ TIME_UB. nia.\n        + (* period end *)\n          exfalso.\n          clear - TM_EQ TIME_UB. nia.\n    Qed.\n\n  End MATCH_NODE_PROOF.\n\n\n  Inductive amw_lst (tid: Tid)\n    : @SNode.t sysE msgT -> @Node.state sysE ->\n      @AbstMW.state sysE -> Prop :=\n  | AMwLocalState\n      node ast\n    : amw_lst tid node\n              (Node.State (AbstMW.as_node tid node) ast) ast.\n\n\n  Lemma partition_map_after\n        A (l: list (A * nat)) l1 l2\n        tm sytm\n        (MAP: partition_map age_delay l = (l1, l2))\n        (TM: Forall (fun p => tm + snd p < sytm) l):\n    Forall (fun p => S (tm + snd p) < sytm) l1.\n  Proof.\n    revert l1 l2 MAP.\n    induction l; i; ss.\n    { inv MAP. ss. }\n    inv TM.\n    destruct (partition_map age_delay l) as [] eqn:MAP'.\n    destruct (age_delay a) eqn:DELAY.\n    - inv MAP. econs; eauto.\n      destruct a, p. ss. destruct n; ss. inv DELAY.\n      rewrite Nat.add_succ_r in *. ss.\n    - inv MAP. eauto.\n  Qed.\n\n  Lemma nw_inv_distr\n        tm nw nw' dpms\n        (NW_INV: nw_inv tm nw)\n        (NW_DISTR: NW.distr nw = (nw', dpms))\n    : nw_inv (DTime.succ tm) nw'.\n  Proof.\n    ii. exploit NW_INV; eauto; ss; try nia. i. des.\n    destruct nw. ss.\n    destruct (partition_map age_delay packet_msg_pool) as [] eqn:MAP1.\n    destruct (partition_map age_delay mcast_msg_pool) as [] eqn:MAP2.\n    inv NW_DISTR. ss.\n    split; eauto using partition_map_after.\n  Qed.\n\n  Lemma nw_inv_gather\n        tm nw1 ps nw'\n        (NW_INV: nw_inv (DTime.succ tm) nw1)\n        (TM_IN_BTW: tm < DTime.of_ns (get_skwd_base_time period tm + period - max_clock_skew - max_nw_delay))\n        (NW_GATHER: NW.gather nw1 ps nw')\n    : nw_inv (DTime.succ tm) nw'.\n  Proof.\n    r in NW_INV. r. i.\n    hexploit NW_INV; eauto.\n    intros [MSG_POOL MCAST_POOL].\n\n    inv NW_GATHER. ss.\n\n    pose (cbt := get_skwd_base_time period tm).\n    fold cbt in TM_IN_BTW.\n\n    assert (SYTM_SK: exists k, cbt + period * S k =\n                          sytm_sk + max_clock_skew).\n    { clear - TM_IN_BTW SKWD_SYNC_TIME RANGE_TM.\n      r in SKWD_SYNC_TIME.\n      des. rewrite SKWD_SYNC_TIME.\n\n      generalize (get_skwd_base_time_iff tm cbt).\n      intros [AUX _].\n      hexploit AUX; ss.\n      intros [TM_RANGE CBT_DIV]. clear AUX.\n\n      r in CBT_DIV.\n      destruct CBT_DIV as (w & CBT_EQ).\n      assert (cbt < z * period) by nia.\n      assert (w < z) by nia.\n\n      exists (pred (z - w)).\n      rewrite <- S_pred_pos by nia.\n      rewrite CBT_EQ.\n      replace (period * (z - w)) with ((z - w) * period).\n      2: { apply mult_comm. }\n      rewrite <- Nat.mul_add_distr_r.\n      rewrite le_plus_minus_r by nia. ss.\n    }\n    des.\n\n    assert (VALID_DELAY_AUX:\n              forall dly, valid_delay dly ->\n                     S (tm + dly) < sytm_sk * DTime.units_per_ns).\n    { clear - TM_IN_BTW SYTM_SK RANGE_TM.\n      intros dly VALID_DELAY.\n\n      r in VALID_DELAY.\n      apply le_trans with\n          (m:= (cbt + period - max_clock_skew - max_nw_delay + max_nw_delay) * DTime.units_per_ns).\n      { nia. }\n\n      assert (SYTM_SK_EQ: sytm_sk = cbt + period * S k - max_clock_skew).\n      { nia. }\n      subst sytm_sk.\n      rewrite Nat.sub_add by nia.\n      apply Nat.mul_le_mono_r. nia.\n    }\n\n    split.\n    - eapply Forall_app; eauto.\n      eapply Forall_forall.\n      intros [[ip_d pm] dly] IN_PMP_NEW. ss.\n      eapply In_nth_error in IN_PMP_NEW. des.\n      hexploit Forall2_nth2; try apply VALID_DELAYS_PMS; eauto.\n      i. des.\n      inv P_FA.\n      eapply VALID_DELAY_AUX; eauto.\n    - eapply Forall_app; eauto.\n      eapply Forall_forall.\n      intros [[mip nip] dly] IN_MCMP_NEW. ss.\n      eapply In_nth_error in IN_MCMP_NEW. des.\n      hexploit Forall2_nth2; try apply VALID_DELAYS_MCMS; eauto.\n      i. des.\n      inv P_FA.\n      eapply VALID_DELAY_AUX; eauto.\n  Qed.\n\n\n  Lemma match_step_sim\n        tm nw lsts_tgt lsts_src\n        amw_lsts_tgt\n        tm' nw' lsts_tgt' es\n        (WF_NW: NW.wf nw)\n        (NW_INV: nw_inv tm nw)\n        (TM_LB: DTime.of_ns (period - max_clock_skew) <= tm)\n        (* (RANGE_NUM_LSTS: IntRange.sint8 (length lsts_tgt)) *)\n        (MATCH_LSTS: Forall2 (match_lstate tm nw)\n                             lsts_src amw_lsts_tgt)\n        (AMW_LSTS_TGT: iForall3 amw_lst 0\n                                nodes lsts_tgt amw_lsts_tgt)\n        (STEP_TGT: NWSys.step\n                     (NWSys.State tm nw lsts_tgt) es\n                     (NWSys.State tm' nw' lsts_tgt'))\n        (WF_SRC: iForall AANode.state_wf 0 lsts_src)\n        (WF_TGT: iForall AbstMW.state_wf 0 amw_lsts_tgt)\n    : exists lsts_src' amw_lsts_tgt',\n      AASys.step (AASys.State tm lsts_src) es\n                 (AASys.State tm' lsts_src') /\\\n      NW.wf nw' /\\\n      nw_inv tm' nw' /\\\n      Forall2 (match_lstate tm' nw') lsts_src' amw_lsts_tgt' /\\\n      iForall3 amw_lst 0 nodes lsts_tgt' amw_lsts_tgt' /\\\n      iForall AANode.state_wf 0 lsts_src' /\\\n      iForall AbstMW.state_wf 0 amw_lsts_tgt'.\n  Proof.\n    inv STEP_TGT.\n\n    pose (cbt := get_skwd_base_time period tm).\n    pose (nsytm := cbt + period).\n\n    destruct (le_lt_dec (DTime.of_ns (nsytm - max_clock_skew - max_nw_delay)) tm) as [IN_BTW | WORKING].\n    - (* in_btw *)\n\n      assert (ST_SRC_EX:\n                forall n (N_UB: n < length lsts_tgt),\n                exists x,\n                  (fun n (x: AANode.state * state) =>\n                     let (st_src', alst_tgt') := x in\n                     nth_error opkts n = Some None /\\\n                     option_rel4\n                       (AANode.step tm)\n                       (nth_error lsts_src n)\n                       (nth_error es n)\n                       (Some None)\n                       (Some st_src') /\\\n                     option_rel2\n                       (match_lstate (DTime.succ tm) nw1)\n                       (Some st_src')\n                       (Some alst_tgt') /\\\n                     option_rel3\n                       (amw_lst n)\n                       (nth_error nodes n)\n                       (nth_error lsts_tgt' n)\n                       (Some alst_tgt') /\\\n                     AANode.state_wf n st_src' /\\\n                     state_wf n alst_tgt')\n                    n x).\n      { i.\n        assert (LST_TGT_N: exists lst_tgt_n,\n                   nth_error lsts_tgt n = Some lst_tgt_n).\n        { apply Some_not_None. apply nth_error_Some. ss. }\n        des.\n\n        assert (exists es_n opkt_n lst_tgt_n',\n                   <<ES_N: nth_error es n = Some es_n>> /\\\n                   <<OPKT_N: nth_error opkts n = Some opkt_n>> /\\\n                   <<LST_TGT_N': nth_error lsts_tgt' n = Some lst_tgt_n'>> /\\\n                   <<NODE_STEP:\n                   Node.step tm dpms\n                             lst_tgt_n es_n opkt_n lst_tgt_n'>>).\n        { rewrite Forall4_nth in LOCAL_STEPS.\n          specialize (LOCAL_STEPS n).\n          rewrite LST_TGT_N in LOCAL_STEPS.\n          inv LOCAL_STEPS.\n          esplits; eauto. }\n\n        rewrite iForall3_nth in AMW_LSTS_TGT.\n        specialize (AMW_LSTS_TGT n).\n        rewrite LST_TGT_N in AMW_LSTS_TGT.\n        assert (exists nd_n alst_tgt_n,\n                   <<NODE_N: nth_error nodes n = Some nd_n>> /\\\n                   <<ALST_TGT_N: nth_error amw_lsts_tgt n = Some alst_tgt_n>> /\\\n                   <<AMW_LST: amw_lst n nd_n lst_tgt_n alst_tgt_n>>).\n        { inv AMW_LSTS_TGT. ss.\n          esplits; eauto. }\n        des.\n        inv AMW_LST.\n\n        rewrite Forall2_nth in MATCH_LSTS.\n        specialize (MATCH_LSTS n).\n        rewrite ALST_TGT_N in MATCH_LSTS.\n        assert (LST_SRC_N: exists lst_src_n,\n                   nth_error lsts_src n = Some lst_src_n /\\\n                   match_lstate tm nw lst_src_n alst_tgt_n).\n        { inv MATCH_LSTS. esplits; eauto. }\n        des. rename LST_SRC_N0 into MATCH_LST.\n\n        rewrite Forall4_nth in LOCAL_STEPS.\n        specialize (LOCAL_STEPS n).\n        rewrite LST_TGT_N in LOCAL_STEPS.\n\n        rewrite iForall_nth in WF_SRC.\n        generalize (WF_SRC n). ss.\n        rewrite LST_SRC_N.\n        intro WF_SRC_N. r in WF_SRC_N.\n\n        rewrite iForall_nth in WF_TGT.\n        generalize (WF_TGT n). ss.\n        rewrite ALST_TGT_N.\n        intro WF_TGT_N. r in WF_TGT_N.\n\n        pose (dpms_f := Node.distr_msgs_to (tid2ip n) dpms).\n        inv NODE_STEP. existT_elim. clarify. ss.\n\n        assert (N_TID: n = AANode.task_id lst_src_n).\n        { inv WF_SRC_N. ss. }\n        guardH N_TID.\n\n        hexploit step_src_in_btw; try apply MATCH_LST; eauto.\n        { inv WF_SRC_N. ss. }\n        { rewrite <- N_TID. ss. }\n        { inv WF_TGT_N. ss.\n          hexploit task_id_ip_comput; eauto.\n          intros [IP_EQ _].\n          rewrite IP_EQ in ISTEP.\n          eauto.\n        }\n\n        intros (OPKT_NONE & st_src' & STEP_SRC & MATCH').\n        exists (st_src', ist').\n        rewrite OPKT_N, ES_N, NODE_N, LST_TGT_N'.\n\n        splits.\n        - clarify.\n        - econs. ss.\n        - econs. ss.\n        - econs. ss.\n        - eapply AANode.wf_prsv; eauto.\n        - eapply AbstMW.wf_prsv; eauto.\n      }\n\n      apply exists_list in ST_SRC_EX.\n      destruct ST_SRC_EX as\n          (xs & LEN_LSTS_SRC' & LSTS_SRC_PROPS).\n      des.\n\n      pose (lsts_src' := map fst xs).\n      pose (alsts_tgt' := map snd xs).\n\n      assert (OPKTS_ALL_NONE:\n                forall op (IN: In op opkts), op = None).\n      { i. apply In_nth_error in IN. des.\n\n        hexploit Forall2_length; eauto. i.\n        hexploit Forall4_length; eauto. i. des.\n\n        assert (exists x, nth_error xs n = Some x).\n        { apply Some_not_None.\n          apply nth_error_Some.\n          replace (length xs) with (length opkts) by nia.\n          apply nth_error_Some. congruence.\n        }\n\n        des.\n        exploit LSTS_SRC_PROPS; eauto.\n        destruct x. ss.\n        i. des. clarify.\n      }\n\n      assert (nw' = nw1).\n      { assert (OPKTS_F_NIL: filtermap id opkts = []).\n        { clear - OPKTS_ALL_NONE.\n          induction opkts as [| h t IH]; ss.\n          destruct h; ss.\n          - exfalso.\n            hexploit OPKTS_ALL_NONE; eauto. ss.\n          - eapply IH. eauto.\n        }\n        rewrite OPKTS_F_NIL in NW_STEP.\n        inv NW_STEP. ss. clarify. ss.\n        inv VALID_DELAYS_PMS.\n        inv VALID_DELAYS_MCMS.\n        do 2 rewrite app_nil_r. ss.\n      }\n      subst nw'.\n\n      assert (<<STEPS_SRC:\n                Forall4 (AANode.step tm)\n                        lsts_src es (List.repeat None (length lsts_src)) lsts_src'>> /\\\n                <<MATCH': Forall2 (match_lstate (DTime.succ tm) nw1)\n                                  lsts_src' alsts_tgt'>> /\\\n                <<AMW_LST': iForall3 amw_lst 0 nodes\n                                     lsts_tgt' alsts_tgt'>> /\\\n                <<WF_SRC': iForall AANode.state_wf 0 lsts_src'>> /\\\n                <<WF_TGT': iForall AbstMW.state_wf 0 alsts_tgt'>>\n             ).\n      { cut (forall n,\n                (<<LSTS_SRC: nth_error lsts_src n = None>> /\\\n                 <<ES: nth_error es n = None>> /\\\n                 <<LSTS_SRC': nth_error lsts_src' n = None>> /\\\n                 <<ALSTS_TGT': nth_error alsts_tgt' n = None>> /\\\n                 <<ANODES: nth_error nodes n = None>> /\\\n                 <<LSTS_TGT': nth_error lsts_tgt' n = None>>) \\/\n                (exists lst_src_n es_n lst_src_n'\n                   alst_tgt_n' nd_n lst_tgt_n',\n                    <<LSTS_SRC: nth_error lsts_src n = Some lst_src_n>> /\\\n                    <<ES: nth_error es n = Some es_n>> /\\\n                    <<LSTS_SRC': nth_error lsts_src' n = Some lst_src_n'>> /\\\n                    <<ALSTS_TGT': nth_error alsts_tgt' n = Some alst_tgt_n'>> /\\\n                    <<ANODES: nth_error nodes n = Some nd_n>> /\\\n                    <<LSTS_TGT': nth_error lsts_tgt' n = Some lst_tgt_n'>> /\\\n                    <<STEP_SRC: AANode.step tm lst_src_n es_n None lst_src_n'>> /\\\n                    <<MATCH: match_lstate (DTime.succ tm) nw1\n                                 lst_src_n' alst_tgt_n'>> /\\\n                    <<AMW_LST': amw_lst n nd_n lst_tgt_n' alst_tgt_n'>> /\\\n                    <<WF_SRC': AANode.state_wf n lst_src_n'>> /\\\n                    <<WF_TGT': AbstMW.state_wf n alst_tgt_n'>>\n                )\n            ).\n        { intro AUX.\n          splits.\n          - apply Forall4_nth. i.\n            specialize (AUX n).\n            des.\n            + rewrite LSTS_SRC, ES, LSTS_SRC'.\n              rewrite repeat_nth_error_None.\n              2: { apply nth_error_None. ss. }\n              econs.\n            + rewrite LSTS_SRC, ES, LSTS_SRC'.\n              rewrite repeat_nth_error_Some.\n              2: { apply nth_error_Some. congruence. }\n              econs; ss.\n          - apply Forall2_nth. i.\n            specialize (AUX n).\n            des.\n            + rewrite LSTS_SRC', ALSTS_TGT'.\n              econs.\n            + rewrite LSTS_SRC', ALSTS_TGT'.\n              econs; ss.\n          - apply iForall3_nth. i.\n            specialize (AUX n). ss.\n            des.\n            + rewrite ANODES, LSTS_TGT', ALSTS_TGT'.\n              econs.\n            + rewrite ANODES, LSTS_TGT', ALSTS_TGT'.\n              econs. ss.\n          - apply iForall_nth. i.\n            specialize (AUX n). ss.\n            des.\n            + r. rewrite LSTS_SRC'. ss.\n            + r. rewrite LSTS_SRC'. ss.\n          - apply iForall_nth. i.\n            specialize (AUX n). ss.\n            des.\n            + rewrite ALSTS_TGT'. ss.\n            + rewrite ALSTS_TGT'. ss.\n        }\n\n        intro n.\n        destruct (le_lt_dec (length xs) n) as [LE|LT].\n        - left.\n\n          assert (LST_SRC_N': nth_error lsts_src' n = None).\n          { subst lsts_src'.\n            apply map_nth_error_None_iff.\n            apply nth_error_None. ss. }\n          assert (ALST_TGT_N': nth_error alsts_tgt' n = None).\n          { subst lsts_src'.\n            apply map_nth_error_None_iff.\n            apply nth_error_None. ss. }\n\n          assert (LST_TGT_N: nth_error lsts_tgt n = None).\n          { apply nth_error_None.\n            rewrite <- LEN_LSTS_SRC'. ss. }\n\n          assert (<<ALST_TGT_N: nth_error amw_lsts_tgt n = None>> /\\\n                  <<ANODES_N: nth_error nodes n = None>>).\n          { rewrite iForall3_nth in AMW_LSTS_TGT.\n            specialize (AMW_LSTS_TGT n).\n            rewrite LST_TGT_N in AMW_LSTS_TGT.\n            inv AMW_LSTS_TGT. ss. }\n\n          assert (<<ES_N: nth_error es n = None>> /\\\n                  <<LST_TGT_N': nth_error lsts_tgt' n = None>>).\n          { rewrite Forall4_nth in LOCAL_STEPS.\n            specialize (LOCAL_STEPS n).\n            rewrite LST_TGT_N in LOCAL_STEPS.\n            inv LOCAL_STEPS. ss. }\n          des.\n\n          assert (LST_SRC_N: nth_error lsts_src n = None).\n          { rewrite Forall2_nth in MATCH_LSTS.\n            specialize (MATCH_LSTS n).\n            rewrite ALST_TGT_N in MATCH_LSTS.\n            inv MATCH_LSTS. ss. }\n\n          splits; ss.\n\n        - right.\n          assert (X_N: exists x, nth_error xs n = Some x).\n          { apply Some_not_None.\n            apply nth_error_Some. ss. }\n          des.\n\n          exploit LSTS_SRC_PROPS; eauto.\n          destruct x as [st_src' alst_tgt'].\n          intros (OPKT_N & STEP_SRC & MATCH' & AMW_LST' &\n                  WF_SRC' & WF_TGT').\n          inv MATCH'.\n\n          destruct (nth_error lsts_src n) as [lst_src_n|].\n          2: { inv STEP_SRC. }\n          destruct (nth_error es n) as [es_n|].\n          2: { inv STEP_SRC. }\n          inv STEP_SRC.\n\n          destruct (nth_error nodes n) as [nd_n|] eqn:ND_N.\n          2: { inv AMW_LST'. }\n          destruct (nth_error lsts_tgt' n) as [lst_tgt_n'|].\n          2:{ inv AMW_LST'. }\n          inv AMW_LST'.\n\n          rewrite iForall3_nth in AMW_LSTS_TGT.\n          specialize (AMW_LSTS_TGT n). ss.\n\n          assert (LST_TGT_N: exists lst_tgt_n,\n                     nth_error lsts_tgt n = Some lst_tgt_n).\n          { apply Some_not_None.\n            apply nth_error_Some. nia. }\n          des.\n\n          assert (exists nd_n' alst_tgt_n,\n                     <<ND_N': nth_error nodes n = Some nd_n'>> /\\\n                     <<ALST_TGT_N: nth_error amw_lsts_tgt n = Some alst_tgt_n>> /\\\n                     <<AMW_LST': amw_lst n nd_n' lst_tgt_n alst_tgt_n>>).\n          { rewrite LST_TGT_N in AMW_LSTS_TGT.\n            inv AMW_LSTS_TGT.\n            esplits; eauto. }\n          des.\n\n          esplits; eauto.\n          + subst lsts_src'.\n            apply map_nth_error_iff.\n            esplits; eauto.\n          + subst lsts_src'.\n            apply map_nth_error_iff.\n            esplits; eauto.\n      }\n\n      des.\n      exists lsts_src', alsts_tgt'.\n      splits; ss.\n      + econs; eauto.\n        apply map_id_ext.\n        i. destruct a; ss.\n\n        assert (RANGE_TM: DTime.of_ns (nsytm - max_clock_skew - max_nw_delay)\n                <= tm < DTime.of_ns (nsytm - max_clock_skew)).\n        { subst nsytm. ss.\n          split.\n          - nia.\n          - hexploit (get_skwd_base_time_range tm); eauto.\n            fold cbt. ss. nia.\n        }\n        assert (EXACT_NONE: exact_skwd_base_time period tm = None).\n        { apply exact_skwd_base_time_None_iff.\n          { clear - IN_BTW PERIOD_COND.\n            subst nsytm.\n            pose proof DTime.units_per_ns_pos.\n            nia. }\n          exists cbt.\n          split.\n          - clear - RANGE_TM PERIOD_COND.\n            subst nsytm. ss. nia.\n          - assert (CBT_EQ: get_skwd_base_time period tm = cbt)\n              by ss.\n\n            apply get_skwd_base_time_iff in CBT_EQ.\n            des. ss.\n        }\n        rewrite EXACT_NONE.\n\n        rewrite map_repeat. ss.\n        rewrite AANode.merge_inbox_nils. ss.\n      + eapply NW.wf_distr_preserve; eauto.\n      + eapply nw_inv_distr; eauto.\n\n    - (* working time *)\n\n      assert (TM_POS: 0 < tm).\n      { ss. nia. }\n\n\n      assert (ST_SRC_EX:\n                forall n (N_UB: n < length amw_lsts_tgt),\n                exists x,\n                  (fun n (x: @AANode.state sysE * (Tid * msgT)? * state) =>\n                     let '(st_src1, ms, st_tgt') := x in\n                     let tid := n in\n                     option_rel4\n                       (AANode.step tm)\n                       (nth_error lsts_src n)\n                       (nth_error es n)\n                       (Some ms) (Some st_src1) /\\\n                     (* length ms <= 1 /\\ *)\n                     option_rel1\n                       (fun opkt =>\n                          option_rel1 Packet.wf opkt /\\\n                          match_pkt nsytm tid ms opkt)\n                       (nth_error opkts tid) /\\\n\n                     option_rel1\n                       (fun opkt =>\n                          forall (outs_src: list (Tid * msgT)?)\n                            (outs_tgt: list (Packet.t)?)\n                            nw'\n                            (LEN_OUTS: length outs_src = num_tasks)\n                            (MATCH_OUTMSGS: iForall2 (match_pkt nsytm)\n                                                     0 outs_src outs_tgt)\n                            (OUT_SRC_N: nth_error outs_src tid = Some ms)\n                            (OUT_TGT_N: nth_error outs_tgt tid = Some opkt)\n                            (NW: NW.gather nw1 (filtermap id outs_tgt) nw')\n                          ,\n                            let st_src' :=\n                                AANode.accept_msgs\n                                  tm outs_src st_src1 in\n                            match_lstate (DTime.succ tm) nw'\n                                         st_src' st_tgt' /\\\n                            AANode.state_wf tid st_src')\n                       (nth_error opkts n) /\\\n                     option_rel3\n                       (amw_lst n)\n                       (nth_error nodes n)\n                       (nth_error lsts_tgt' n)\n                       (Some st_tgt') /\\\n                     (* (uncurry_p (AANode.state_wf imcasts)) (n, st_src') /\\ *)\n                     (state_wf n st_tgt')\n                  ) n x).\n      { i.\n        hexploit nth_error_Some2; eauto. i. des.\n        renames e1 NTH_EX into alst_tgt ALST_TGT.\n\n        hexploit Forall2_nth2; try apply MATCH_LSTS; eauto. i. des.\n        renames e1 NTH1 P_FA into lst_src LST_SRC MATCH_LST.\n\n        rewrite iForall3_nth in AMW_LSTS_TGT.\n        specialize (AMW_LSTS_TGT n). ss.\n        rewrite ALST_TGT in AMW_LSTS_TGT.\n\n        assert (exists nd_n lst_tgt,\n                   <<ND_N: nth_error nodes n = Some nd_n>> /\\\n                   <<LST_TGT: nth_error lsts_tgt n = Some lst_tgt>> /\\\n                   <<AMW_LST: amw_lst n nd_n lst_tgt alst_tgt>>).\n        { inv AMW_LSTS_TGT. esplits; eauto. }\n        des.\n\n        assert (WF_SRC_N: AANode.state_wf n lst_src).\n        { eapply iForall_nth1 in WF_SRC; try apply LST_SRC; eauto. }\n        assert (WF_TGT_N: AbstMW.state_wf n alst_tgt).\n        { eapply iForall_nth1 in WF_TGT; try apply ALST_TGT; eauto. }\n\n        hexploit Forall4_nth1; eauto. i. des.\n        renames e2 NTH2 into es_n ES_N.\n        renames e3 NTH3 into opkt OPKT.\n        renames e4 NTH4 into lst_tgt' LST_TGT'.\n        rename P_FA into STEP_TGT.\n\n        inv AMW_LST. ss.\n        inv STEP_TGT. existT_elim. clarify. ss.\n\n        assert (TASK_ID_SRC: AANode.task_id lst_src = n).\n        { inv WF_SRC_N. ss. }\n        guardH TASK_ID_SRC.\n        assert (exists ip,\n                   <<TASK_ID_IP: task_id_ip n ip>> /\\\n                   <<IP_EQ: ip = tid2ip n>> /\\\n                   <<IP_LOCAL: IP.local_ip ip = true>> /\\\n                   <<IP_ADDR_TGT: ip_addr alst_tgt = ip>>).\n        { inv WF_TGT_N.\n          hexploit task_id_ip_comput; eauto. i. des.\n          esplits; eauto. }\n        des. guardH IP_EQ.\n        rewrite <- IP_EQ in ISTEP.\n\n        hexploit step_src_working; eauto.\n        { rewrite TASK_ID_SRC. ss. }\n        { rewrite TASK_ID_SRC. ss. }\n        { rewrite IP_ADDR_TGT. eauto. }\n\n        intros (lst_src' & ms & STEP_SRC &\n                WF_OPKT & MATCH_PKT & MATCH_LST').\n\n        exists (lst_src', ms, ist').\n        rewrite LST_SRC, ES_N, OPKT.\n        splits; eauto.\n        { econs. eauto. }\n        { econs; eauto.\n          rewrite TASK_ID_SRC in MATCH_PKT.\n          fold cbt nsytm in MATCH_PKT. ss. }\n        { r. fold cbt nsytm in MATCH_LST'.\n          rewrite TASK_ID_SRC in MATCH_LST'.\n          i.\n          split; eauto.\n          apply AANode.wf_accept_msgs_prsv.\n          eapply AANode.wf_prsv; eauto.\n        }\n        { rewrite ND_N, LST_TGT'. econs.\n          econs. }\n        { unfold uncurry_p. ss.\n          eapply wf_prsv; eauto.\n        }\n      }\n\n      apply exists_list in ST_SRC_EX.\n      destruct ST_SRC_EX as (xs & XS_LEN & XS_PROPS).\n      des.\n\n      pose (lsts_src1 := map fst (map fst xs)).\n      pose (outs_src := map snd (map fst xs)).\n      pose (alsts_tgt' := map snd xs).\n\n      pose (lsts_src' := map (AANode.accept_msgs tm outs_src) lsts_src1).\n\n      assert (<<L_LSTS_SRC: length lsts_src = length xs>> /\\\n              <<L_ES: length es = length xs>> /\\\n              <<L_OPKTS: length opkts = length xs>> /\\\n              <<L_LSTS_TGT: length lsts_tgt = length xs>> /\\\n              <<L_LSTS_TGT': length lsts_tgt' = length xs>> /\\\n              <<L_NODES: length nodes = length xs>>).\n      { apply Forall2_length in MATCH_LSTS.\n        apply iForall3_length in AMW_LSTS_TGT.\n        (* rewrite attach_index_length in AMW_LSTS_TGT. *)\n        apply Forall4_length in LOCAL_STEPS.\n        des.\n        splits; nia.\n      }\n      des.\n\n      cut (forall n,\n              (exists lst_src es_n opkt_n lst_tgt lst_tgt'\n                 lst_src1 alst_tgt' out_src lst_src' node,\n                  <<LST_SRC: nth_error lsts_src n = Some lst_src>> /\\\n                  <<LST_SRC1: nth_error lsts_src1 n = Some lst_src1>> /\\\n                  <<LST_SRC': nth_error lsts_src' n = Some lst_src'>> /\\\n                  <<LST_TGT: nth_error lsts_tgt n = Some lst_tgt>> /\\\n                  <<LST_TGT': nth_error lsts_tgt' n = Some lst_tgt'>> /\\\n                  <<ES_N: nth_error es n = Some es_n>> /\\\n                  <<OPKT_N: nth_error opkts n = Some opkt_n>> /\\\n                  <<ALST_TGT': nth_error alsts_tgt' n = Some alst_tgt'>> /\\\n                  <<OUT_SRC: nth_error outs_src n = Some out_src>> /\\\n                  <<NODE: nth_error nodes n = Some node>> /\\\n\n                  <<STEP: AANode.step tm lst_src es_n out_src lst_src1>> /\\\n                  (* <<LEN_OUT_SRC: length out_src <= 1>> /\\ *)\n                  <<WF_OPKT: option_rel1 Packet.wf opkt_n>> /\\\n                  <<MATCH_PKT: match_pkt nsytm n out_src opkt_n>> /\\\n                  <<LST_SRC'_EQ:\n                    lst_src' = AANode.accept_msgs tm outs_src lst_src1>> /\\\n\n                  <<MATCH_LST:\n                    (* forall (outs_src : list (list (nat * msgT))) (outs_tgt : list Packet.t ?) (nw' : NW.t), *)\n                    (*   length outs_src = num_tasks -> *)\n                    (*   Forall2 (match_pkt nsytm) (attach_index outs_src) outs_tgt -> *)\n                    (*   nth_error outs_src n = Some out_src -> *)\n                    (*   nth_error outs_tgt n = Some opkt_n -> *)\n                    (*   NW.gather nw1 (filtermap id outs_tgt) nw' -> *)\n                      match_lstate (DTime.succ tm) nw' lst_src' alst_tgt'>> /\\\n                  <<AMW_LST': amw_lst n node lst_tgt' alst_tgt'>> /\\\n                  <<WF_SRC': AANode.state_wf n lst_src'>> /\\\n                  <<WF_TGT': state_wf n alst_tgt'>>)\n              \\/\n              (<<LST_SRC: nth_error lsts_src n = None>> /\\\n               <<LST_SRC1: nth_error lsts_src1 n = None>> /\\\n               <<LST_SRC': nth_error lsts_src' n = None>> /\\\n               <<LST_TGT: nth_error lsts_tgt n = None>> /\\\n               <<LST_TGT': nth_error lsts_tgt' n = None>> /\\\n               <<ES_N: nth_error es n = None>> /\\\n               <<OPKT_N: nth_error opkts n = None>> /\\\n               <<ALST_TGT': nth_error alsts_tgt' n = None>> /\\\n               <<OUT_SRC: nth_error outs_src n = None>> /\\\n               <<NODE: nth_error nodes n = None>>)\n          ).\n      { intro LIST_ELEMS.\n        exists lsts_src', alsts_tgt'.\n\n        splits.\n        - econs; eauto.\n          2: { subst lsts_src'. eauto. }\n          apply Forall4_nth.\n          intro n. fold msgT.\n          specialize (LIST_ELEMS n). des.\n          + rewrite LST_SRC, ES_N, OUT_SRC, LST_SRC1.\n            econs. eauto.\n          + rewrite LST_SRC, ES_N, OUT_SRC, LST_SRC1.\n            econs.\n        - eapply NW.wf_gather_preserve; eauto.\n          { eapply NW.wf_distr_preserve; eauto. }\n\n          apply Forall_forall.\n          intros p IN_F.\n          apply filtermap_in in IN_F.\n          unfold id in IN_F. des. subst.\n\n          apply In_nth_error in IN_F. des.\n          specialize (LIST_ELEMS n). des.\n          + rewrite OPKT_N in IN_F. clarify.\n          + rewrite OPKT_N in IN_F. clarify.\n        - eapply nw_inv_gather; eauto.\n          eapply nw_inv_distr; eauto.\n        - rewrite Forall2_nth. i.\n          specialize (LIST_ELEMS n). des.\n          + rewrite LST_SRC', ALST_TGT'. econs.\n            eapply MATCH_LST; eauto.\n          + rewrite LST_SRC', ALST_TGT'. econs.\n        - rewrite iForall3_nth. i. ss.\n          specialize (LIST_ELEMS n). des.\n          + rewrite NODE, LST_TGT', ALST_TGT'.\n            econs. ss.\n          + rewrite NODE, LST_TGT', ALST_TGT'.\n            econs.\n        - apply iForall_nth. i. ss.\n          specialize (LIST_ELEMS n). des.\n          + rewrite LST_SRC'. ss.\n          + rewrite LST_SRC'. ss.\n        - apply iForall_nth. i. ss.\n          specialize (LIST_ELEMS n). des.\n          + rewrite ALST_TGT'. ss.\n          + rewrite ALST_TGT'. ss.\n      }\n\n      assert (MATCH_PKTS:\n                iForall2 (match_pkt nsytm)\n                         0 outs_src opkts).\n      { apply iForall2_nth.\n        intros n.\n        destruct (nth_error xs n) as\n            [[[st_src1 outs_n] st_tgt']|] eqn:XS_N.\n        2: {\n          assert (N_XS: length xs <= n).\n          { apply nth_error_None in XS_N. ss. }\n          repeat rewrite nth_error_None2 by nia.\n\n          rewrite nth_error_None2.\n          2: { unfold outs_src.\n               do 2 rewrite map_length. ss. }\n          rewrite nth_error_None2 by nia.\n          econs.\n        }\n\n        assert (N_XS: n < length xs).\n        { apply nth_error_Some. congruence. }\n        repeat rewrite nth_error_None2 by nia.\n\n        subst outs_src. ss.\n        replace (nth_error (map snd (map fst xs)) n) with (Some outs_n).\n        2: {\n          symmetry.\n          do 2 rewrite Coqlib.list_map_nth.\n          rewrite XS_N. ss.\n        }\n\n        hexploit (nth_error_Some2 _ opkts n); eauto.\n        { nia. }\n        i. des. renames e1 NTH_EX into op OP.\n        rewrite OP. econs.\n\n        exploit XS_PROPS; eauto. s.\n        rewrite OP.\n        intros (? & OPP1 & ?).\n        inv OPP1. ss.\n      }\n\n      intro n.\n      destruct (lt_ge_dec n (length xs)).\n      + hexploit (nth_error_Some2 _ xs n); [nia|].\n        i. des. renames e1 NTH_EX into xs_n XS_N.\n        destruct xs_n as [[lst_src1 out_src] alst_tgt'].\n\n        assert (LST_SRC1: nth_error lsts_src1 n = Some lst_src1).\n        { subst lsts_src1.\n          do 2 rewrite Coqlib.list_map_nth.\n          rewrite XS_N. ss. }\n        assert (OUT_SRC: nth_error outs_src n = Some out_src).\n        { subst outs_src.\n          do 2 rewrite Coqlib.list_map_nth.\n          rewrite XS_N. ss. }\n        assert (ALST_TGT': nth_error alsts_tgt' n = Some alst_tgt').\n        { subst alsts_tgt'.\n          rewrite Coqlib.list_map_nth.\n          rewrite XS_N. ss. }\n        assert (LST_SRC': nth_error lsts_src' n =\n                          Some (AANode.accept_msgs tm outs_src lst_src1)).\n        { subst lsts_src'.\n          rewrite Coqlib.list_map_nth.\n          rewrite LST_SRC1. ss. }\n\n        hexploit (nth_error_Some2 _ lsts_src n); [nia|].\n        i. des. renames e1 NTH_EX into lst_src LST_SRC.\n        hexploit (nth_error_Some2 _ lsts_tgt n); [nia|].\n        i. des. renames e1 NTH_EX into lst_tgt LST_TGT.\n        hexploit (nth_error_Some2 _ lsts_tgt' n); [nia|].\n        i. des. renames e1 NTH_EX into lst_tgt' LST_TGT'.\n        hexploit (nth_error_Some2 _ es n); [nia|].\n        i. des. renames e1 NTH_EX into es_n ES_N.\n        hexploit (nth_error_Some2 _ opkts n); [nia|].\n        i. des. renames e1 NTH_EX into opkt_n OPKT_N.\n        hexploit (nth_error_Some2 _ nodes n); [nia|].\n        i. des. renames e1 NTH_EX into node NODE.\n\n        left.\n        exploit XS_PROPS; eauto. s.\n        rewrite LST_SRC, ES_N, OUT_SRC, LST_SRC1.\n        rewrite OPKT_N, NODE, LST_TGT', ALST_TGT'.\n        intros (STEP_P & OP & ALST_TGT_P' & AMW_LST' & WF_TGT_N).\n        inv STEP_P. inv OP. inv AMW_LST'. r in ALST_TGT_P'.\n        hexploit ALST_TGT_P'; eauto.\n        { subst outs_src.\n          do 2 rewrite map_length. nia. }\n        intros (MATCH & WF_SRC_N).\n\n        esplits; eauto.\n\n      + right.\n        rewrite (nth_error_None2 _ lsts_src) by nia.\n        rewrite (nth_error_None2 _ lsts_tgt) by nia.\n        rewrite (nth_error_None2 _ es) by nia.\n        rewrite (nth_error_None2 _ opkts) by nia.\n        rewrite (nth_error_None2 _ nodes) by nia.\n        rewrite (nth_error_None2 _ lsts_tgt') by nia.\n        rewrite (nth_error_None2 _ lsts_src1).\n        2: { subst lsts_src1.\n             do 2 rewrite map_length. ss. }\n        rewrite (nth_error_None2 _ lsts_src').\n        2: { subst lsts_src' lsts_src1.\n             do 3 rewrite map_length. ss. }\n        rewrite (nth_error_None2 _ alsts_tgt').\n        2: { subst alsts_tgt'.\n             rewrite map_length. ss. }\n        rewrite (nth_error_None2 _ outs_src).\n        2: { subst outs_src.\n             do 2 rewrite map_length. ss. }\n        splits; ss.\n  Qed.\n\n\n  Lemma fmsim_running\n    : forall tm lsts_src\n        nw lsts_tgt amw_lsts_tgt\n        st_src st_tgt\n        (NW_WF: NW.wf nw)\n        (NW_INV: nw_inv tm nw)\n        (* (LEN: IntRange.sint8 (length lsts_tgt)) *)\n        (TM_LB: DTime.of_ns (period - max_clock_skew) <= tm)\n        (MATCH_LSTS: Forall2 (match_lstate tm nw)\n                             lsts_src amw_lsts_tgt)\n        (AMW_LSTS: iForall3 amw_lst 0 nodes\n                           lsts_tgt amw_lsts_tgt)\n\n        (ST_SRC: st_src = AASys.State tm lsts_src)\n        (ST_TGT: st_tgt = NWSys.State tm nw lsts_tgt)\n        (WF_SRC: iForall AANode.state_wf 0 lsts_src)\n        (WF_TGT: iForall state_wf 0 amw_lsts_tgt)\n    ,\n      fmsim_states _ sys_src sys_tgt\n                   st_src st_tgt.\n  Proof.\n    pcofix CIH. i.\n    pfold. econs.\n    { ss. }\n    i. ss. inv STEPS. ss.\n    inv MSTEPS_REST. ss.\n\n    exists 1. exists tr_tgt.\n    destruct st_tgt' as [tm' nw' lsts_tgt']. ss.\n\n    hexploit match_step_sim; try apply STEP; eauto.\n    intros (lsts_src' & amw_lsts_tgt' & STEP_SRC &\n            WF_NW' & NW_INV' & MATCH' & AMW_LSTS' &\n            WF_SRC' & WF_TGT').\n\n    esplits.\n    { ss. }\n    { econs; eauto.\n      econs. ss.\n      unfold AASys.num_sites. ss.\n      f_equal.\n      replace (length lsts_tgt') with (length amw_lsts_tgt').\n      2: { symmetry.\n           apply iForall3_length in AMW_LSTS'.\n           des. congruence. }\n      symmetry.\n      eapply Forall2_length in MATCH'; eauto.\n    }\n    { apply Forall2_tes_equiv_refl. }\n\n    right. eapply CIH; try reflexivity; eauto.\n    cut (tm' = DTime.succ tm).\n    { intro TM'.\n      assert (tm < tm').\n      { rewrite TM'. ss. }\n      nia. }\n    inv STEP. ss.\n  Qed.\n\nEnd PROOF.\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/refinement/AmwAsyncRef.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.28980538964837993}}
{"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.\n\n(******************************************************************************)\n(* Reducibility of configurations number 499 to 502, whose indices in         *)\n(* the_configs range over segment [498, 502).                                 *)\n(******************************************************************************)\n\nLemma red498to502 : reducible_in_range 498 502 the_configs.\nProof. CheckReducible. Qed.\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/job499to502.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.28964108303017416}}
{"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(* A directed graph -Digraph- is a type dependant of a set of           *)\n(* vertices and a set of arcs. An inhabitant of such a type is a        *)\n(* construction, inductively defined, of this graph. Some Digraphs      *)\n(* are not inhabited.                                                   *)\n\n(* The following notions are defined :                                  *)\n(*      - (Digraph v a) : set of directed graph with vertices in v      *)\n(*                              and arcs in a,                          *)\n(*              constructors : D_empty, D_vertex, D_arc, D_eq;          *)\n(*      - DV_list : list of vertices of a Digraph;                      *)\n(*      - DA_list : list of arcs of a Digraph;                          *)\n(*      - D_oreder : number of vertices;                                *)\n(*      - D_size : number of arcs.                                      *)\n\nRequire Export Arcs.\n\nSection DIGRAPH.\n\nInductive Digraph : V_set -> A_set -> Set :=\n  | D_empty : Digraph V_empty A_empty\n  | D_vertex :\n      forall (v : V_set) (a : A_set) (d : Digraph v a) (x : Vertex),\n      ~ v x -> Digraph (V_union (V_single x) v) a\n  | D_arc :\n      forall (v : V_set) (a : A_set) (d : Digraph v a) (x y : Vertex),\n      v x ->\n      v y ->\n      ~ a (A_ends x y) -> Digraph v (A_union (A_single (A_ends x y)) a)\n  | D_eq :\n      forall (v v' : V_set) (a a' : A_set),\n      v = v' -> a = a' -> Digraph v a -> Digraph v' a'.\n\nFixpoint DV_list (v : V_set) (a : A_set) (d : Digraph v a) {struct d} :\n V_list :=\n  match d with\n  | D_empty => V_nil\n  | D_vertex v' a' d' x _ => x :: DV_list v' a' d'\n  | D_arc v' a' d' x y _ _ _ => DV_list v' a' d'\n  | D_eq v v' a a' _ _ d => DV_list v a d\n  end.\n\nFixpoint DA_list (v : V_set) (a : A_set) (d : Digraph v a) {struct d} :\n A_list :=\n  match d with\n  | D_empty => A_nil\n  | D_vertex v' a' d' x _ => DA_list v' a' d'\n  | D_arc v' a' d' x y _ _ _ => A_ends x y :: DA_list v' a' d'\n  | D_eq v v' a a' _ _ d => DA_list v a d\n  end.\n\nDefinition D_order (v : V_set) (a : A_set) (d : Digraph v a) :=\n  length (DV_list v a d).\n\nDefinition D_size (v : V_set) (a : A_set) (d : Digraph v a) :=\n  length (DA_list v a d).\n\nLemma D_v_dec :\n forall (v : V_set) (a : A_set) (d : Digraph v a) (x : Vertex),\n {v x} + {~ v x}.\nProof.\n        intros v a d; elim d; intros.\n        right; apply V_empty_nothing.\n\n        case (H x0); intros.\n        left; apply V_in_right; trivial.\n\n        case (V_eq_dec x x0); intros.\n        left; apply V_in_left; rewrite e; apply V_in_single.\n\n        right; red in |- *; intros; inversion H0.\n        elim n1; inversion H1; trivial.\n\n        elim n0; trivial.\n\n        auto.\n\n        case (H x); intros.\n        left; elim e; trivial.\n\n        right; elim e; trivial.\nQed.\n\nLemma D_a_dec :\n forall (v : V_set) (a : A_set) (d : Digraph v a) (x : Arc), {a x} + {~ a x}.\nProof.\n        intros v a d; elim d; intros.\n        right; apply A_empty_nothing.\n\n        auto.\n\n        case (H x0); intros.\n        left; apply A_in_right; trivial.\n\n        case (A_eq_dec (A_ends x y) x0); intros.\n        left; apply A_in_left; rewrite e; apply A_in_single.\n\n        right; red in |- *; intros; inversion H0.\n        elim n1; inversion H1; trivial.\n\n        elim n0; trivial.\n\n        case (H x); intros.\n        left; elim e0; trivial.\n\n        right; elim e0; trivial.\nQed.\n\nEnd DIGRAPH.\n\nSection UNION_DIGRAPHS.\n\nLemma D_union :\n forall (v1 v2 : V_set) (a1 a2 : A_set),\n Digraph v1 a1 -> Digraph v2 a2 -> Digraph (V_union v1 v2) (A_union a1 a2).\nProof.\n        intros; elim H; intros.\n        apply D_eq with (v := v2) (a := a2).\n        symmetry  in |- *; apply V_union_neutral.\n\n        symmetry  in |- *; apply A_union_neutral.\n\n        trivial.\n\n        case (D_v_dec v2 a2 H0 x); intros.\n        apply D_eq with (v := V_union v v2) (a := A_union a a2).\n        rewrite V_union_assoc; rewrite (V_union_absorb (V_single x)); trivial.\n        apply V_included_single; apply V_in_right; trivial.\n\n        trivial.\n\n        trivial.\n\n        apply\n         D_eq\n          with (v := V_union (V_single x) (V_union v v2)) (a := A_union a a2).\n        symmetry  in |- *; apply V_union_assoc.\n\n        trivial.\n\n        apply D_vertex.\n        trivial.\n\n        apply V_not_union; trivial.\n\n        case (D_a_dec v2 a2 H0 (A_ends x y)); intros.\n        apply D_eq with (v := V_union v v2) (a := A_union a a2).\n        trivial.\n\n        rewrite A_union_assoc;\n         rewrite (A_union_absorb (A_single (A_ends x y))); \n         trivial.\n        apply A_included_single; apply A_in_right; trivial.\n\n        trivial.\n\n        apply\n         D_eq\n          with\n            (v := V_union v v2)\n            (a := A_union (A_single (A_ends x y)) (A_union a a2)).\n        trivial.\n\n        symmetry  in |- *; apply A_union_assoc.\n\n        apply D_arc.\n        trivial.\n\n        apply V_in_left; trivial.\n\n        apply V_in_left; trivial.\n\n        apply A_not_union; trivial.\n\n        apply D_eq with (v := V_union v v2) (a := A_union a a2).\n        elim e; trivial.\n\n        elim e0; trivial.\n\n        trivial.\nQed.\n\nEnd UNION_DIGRAPHS.", "meta": {"author": "Zdancewic", "repo": "linearity", "sha": "b2662939b2e8fb8fbe34f7ec0d3c69ef1bdff916", "save_path": "github-repos/coq/Zdancewic-linearity", "path": "github-repos/coq/Zdancewic-linearity/linearity-b2662939b2e8fb8fbe34f7ec0d3c69ef1bdff916/simpleconcur/GraphBasics/Digraphs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.2896410830301741}}
{"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 alphaeq.\nRequire Export swap.\nRequire Export tactics2.\nRequire Export terms_apply.\n\n\n(**\n\n  Similar to [NTerm]s but here variables can be second order variables.\n\n *)\nInductive SOTerm {o} : tuniv :=\n| sovar : NVar -> list SOTerm -> SOTerm\n| soseq : (nat -> @NTerm o) -> SOTerm\n| soterm : @Opid o -> list SOBTerm -> SOTerm\nwith SOBTerm {o} : tuniv :=\n| sobterm : list NVar -> SOTerm -> SOBTerm.\n\n\nDefinition mk_soaxiom {o} : @SOTerm o := soterm (Can NAxiom) [].\n\n\n(*\n(**\n\n  true if the [SOTerm] is a [NTerm]\n\n *)\nFixpoint is_nterm {o} (t : @SOTerm o) : bool :=\n  match t with\n    | sovar _ [] => true\n    | sovar _ _ => false\n    | soterm _ bs => ball (map is_bterm bs)\n  end\nwith is_bterm {o} (bt : @SOBTerm o) : bool :=\n       match bt with\n         | sobterm _ t => is_nterm t\n       end.\n*)\n\n(**\n\n  Converts a [SOTerm] into a [NTerm] by turning second order variables\n  into applications of first order variables.\n\n *)\nFixpoint soterm2nterm {o} (t : @SOTerm o) : @NTerm o :=\n  match t with\n  | sovar v ts => apply_list (mk_var v) (map soterm2nterm ts)\n  | soseq s => sterm s\n  | soterm opid bs => oterm opid (map sobterm2bterm bs)\n  end\nwith sobterm2bterm {o} (bt : @SOBTerm o) : @BTerm o :=\n       match bt with\n         | sobterm vs t => bterm vs (soterm2nterm t)\n       end.\n\nFixpoint nterm2soterm {o} (t : @NTerm o) : @SOTerm o :=\n  match t with\n  | vterm v => sovar v []\n  | sterm s => soseq s\n  | oterm opid bs => soterm opid (map bterm2sobterm bs)\n  end\nwith bterm2sobterm {o} (bt : @BTerm o) : @SOBTerm o :=\n       match bt with\n       | bterm vs t => sobterm vs (nterm2soterm t)\n       end.\n\nDefinition sovar_sig := NVar # nat.\n\nLtac dsovar_sig :=\n  match goal with\n    | [ H : sovar_sig |- _ ] => destruct H\n  end.\n\nLtac dsovar_sigs := repeat dsovar_sig.\n\nLemma sovar_sig_dec: forall x y : sovar_sig, {x = y} + {x <> y}.\nProof.\n  intros.\n  dsovar_sigs.\n  destruct (deq_nvar n n1); subst; tcsp;\n    destruct (eq_nat_dec n0 n2); subst; tcsp;\n      right; sp; cpx.\nDefined.\n\nDefinition memsovar (v : sovar_sig) vs : LIn v vs + !LIn v vs.\nProof.\n  exact (in_deq sovar_sig sovar_sig_dec v vs).\nDefined.\n\nDefinition subsovars (vs1 vs2 : list sovar_sig) :=\n  assert (subsetb sovar_sig_dec vs1 vs2).\n\nLemma subsovars_proof_irrelevance :\n  forall vs1 vs2,\n  forall x y : subsovars vs1 vs2,\n    x = y.\nProof.\n  intros.\n  apply UIP_dec.\n  apply bool_dec.\nQed.\n\nHint Extern 0 =>\nlet h := fresh \"h\" in\nmatch goal with\n  | [ H1 : subsovars ?vs1 ?vs2 , H2 : subsovars ?vs1 ?vs2 |- _ ] =>\n    pose proof (subsovars_proof_irrelevance vs1 vs2 H2 H1) as h; subst\nend : pi.\n\nLemma subsovars_eq :\n  forall vs1 vs2,\n    subsovars vs1 vs2 <=> subset vs1 vs2.\nProof.\n  sp; unfold subsovars.\n  trw assert_subsetb; sp.\nQed.\n\nLemma subsovars_refl :\n  forall vs,\n    subsovars vs vs.\nProof.\n  sp.\n  rw subsovars_eq.\n  apply subset_refl.\nQed.\nHint Immediate subsovars_refl.\n\nLemma subsovars_prop :\n  forall vs1 vs2,\n    subsovars vs1 vs2 <=> forall x, LIn x vs1 -> LIn x vs2.\nProof.\n  sp; rw subsovars_eq; unfold subset; split; sp.\nQed.\n\nLemma subsovars_trans :\n  forall vs1 vs2 vs3,\n    subsovars vs1 vs2\n    -> subsovars vs2 vs3\n    -> subsovars vs1 vs3.\nProof.\n  introv h1 h2.\n  allrw subsovars_eq.\n  eapply subset_trans; eauto.\nQed.\n\nLemma subsovars_nil_l :\n  forall vs, subsovars [] vs.\nProof.\n  introv; apply subsovars_prop; allsimpl; sp.\nQed.\nHint Immediate subsovars_nil_l.\n\nLemma subsovars_cons_lr :\n  forall v vs1 vs2,\n    subsovars vs1 vs2\n    -> subsovars (v :: vs1) (v :: vs2).\nProof.\n  introv sv.\n  allrw subsovars_prop; introv i; allsimpl; sp.\nQed.\n\nLemma subsovars_cons_weak_r :\n  forall v vs1 vs2,\n    subsovars vs1 vs2\n    -> subsovars vs1 (v :: vs2).\nProof.\n  introv sv.\n  allrw subsovars_prop; introv i; allsimpl; sp.\nQed.\n\nDefinition remove_so_vars (vs1 vs2 : list sovar_sig) := diff sovar_sig_dec vs1 vs2.\n\nLemma remove_so_vars_cons_r :\n  forall l v vars,\n    remove_so_vars l (v :: vars)\n    = if memsovar v l then remove_so_vars l vars\n      else v :: remove_so_vars l vars.\nProof.\n  intros; unfold remove_so_vars.\n  boolvar; rewrite diff_cons_r; boolvar; sp.\nQed.\n\nDefinition var2sovar (v : NVar) : sovar_sig := (v,0).\n\nDefinition sovar2var (l : sovar_sig) : NVar := fst l.\n\nDefinition sovars2vars := map sovar2var.\n\nDefinition vars2sovars := map var2sovar.\n\nFixpoint so_free_vars {o} (t : @SOTerm o) : list sovar_sig :=\n  match t with\n  | sovar v ts => (v,length ts) :: (flat_map so_free_vars ts)\n  | soseq s => []\n  | soterm op bs => flat_map so_free_vars_bterm bs\n  end\nwith so_free_vars_bterm {o} (bt : @SOBTerm o) : list sovar_sig :=\n       match bt with\n         | sobterm vs t =>\n           remove_so_vars\n             (vars2sovars vs)\n             (so_free_vars t)\n       end.\n\nFixpoint all_fo_vars {o} (t : @SOTerm o) : list NVar :=\n  match t with\n  | sovar v ts => v :: flat_map all_fo_vars ts\n  | soseq s => []\n  | soterm op bs => flat_map all_fo_vars_bterm bs\n  end\nwith all_fo_vars_bterm {o} (bt : @SOBTerm o) : list NVar :=\n       match bt with\n         | sobterm vs t => vs ++ all_fo_vars t\n       end.\n\nFixpoint fo_bound_vars {p} (t : @SOTerm p) : list NVar :=\n  match t with\n  | sovar _ ts => flat_map fo_bound_vars ts\n  | soseq _ => []\n  | soterm op bs => flat_map fo_bound_vars_bterm bs\n  end\nwith fo_bound_vars_bterm {p} (bt : @SOBTerm p) : list NVar :=\n       match bt with\n         | sobterm lv nt => lv ++ fo_bound_vars nt\n       end.\n\nDefinition so_bound_vars {o} (t : @SOTerm o) : list sovar_sig :=\n  vars2sovars (fo_bound_vars t).\n\nDefinition wf_soterm {p} (t : @SOTerm p) := wf_term (soterm2nterm t).\n\nDefinition wf_sobterm {p} (bt : @SOBTerm p) := wf_bterm (sobterm2bterm bt).\n\nLemma wf_soterm_proof_irrelevance {p} :\n  forall t : @SOTerm p,\n  forall x y : wf_soterm t,\n    x = y.\nProof.\n  intros.\n  apply UIP.\nQed.\nHint Immediate wf_soterm_proof_irrelevance.\n\nHint Extern 0 =>\nlet h := fresh \"h\" in\nmatch goal with\n  | [ H1 : wf_soterm ?t , H2 : wf_soterm ?t |- _ ] =>\n    pose proof (wf_soterm_proof_irrelevance t H2 H1) as h; subst\nend : pi.\n\nInductive sosub_kind {o} :=\n| sosk : list NVar -> @NTerm o -> sosub_kind.\n\nDefinition allvars_sk {o} (sk : @sosub_kind o) : list NVar :=\n  match sk with\n    | sosk vs t => vs ++ allvars t\n  end.\n\nDefinition sosk_vs {o} (sk : @sosub_kind o) : list NVar :=\n  match sk with\n    | sosk vs _ => vs\n  end.\n\nDefinition sosk_t {o} (sk : @sosub_kind o) : NTerm :=\n  match sk with\n    | sosk _ t => t\n  end.\n\nDefinition bterm2sk {o} (bt : @BTerm o) : sosub_kind :=\n  match bt with\n    | bterm vs t => sosk vs t\n  end.\n\nDefinition sk2bterm {o} (sk : @sosub_kind o) : BTerm :=\n  match sk with\n    | sosk vs t => bterm vs t\n  end.\n\nDefinition SOSub {o} := list (NVar # @sosub_kind o).\n\nDefinition sodom {o} (s : @SOSub o) : list sovar_sig :=\n  map (fun x =>\n         match x with\n           | (v, sosk vs t) => (v, length vs)\n         end)\n      s.\n\nDefinition sorange {o} (s : @SOSub o) : list BTerm :=\n  map (fun x =>\n         match x with\n           | (v, sosk vs t) => bterm vs t\n         end)\n      s.\n\nLemma in_sorange {o} :\n  forall (sub : @SOSub o) bt,\n    LIn bt (sorange sub) <=> {v : NVar & LIn (v,bterm2sk bt) sub}.\nProof.\n  introv.\n  rw in_map_iff; split; intro k; exrepnd; subst.\n  - destruct a; simpl; eexists; eauto.\n  - destruct bt; allsimpl; eexists; eauto.\nQed.\n\nFixpoint sosub_filter {p} (sub : @SOSub p) (vars : list sovar_sig) : SOSub :=\n  match sub with\n    | nil => nil\n    | (v, (sosk vs t) as k) :: xs =>\n      if memsovar (v,length vs) vars\n      then sosub_filter xs vars\n      else (v, k) :: sosub_filter xs vars\n  end.\n\nFixpoint sosub_find {p} (sub : @SOSub p) (sv : sovar_sig) : option sosub_kind :=\n  match sub with\n    | nil => None\n    | (v, (sosk vs t) as k) :: xs =>\n      if sovar_sig_dec sv (v,length vs)\n      then Some k\n      else sosub_find xs sv\n  end.\n\n(*\nFixpoint lift_list_option {T} (l : list (option T)) : option (list T) :=\n  match l with\n    | [] => Some []\n    | Some x :: rest =>\n      match lift_list_option rest with\n        | Some xs => Some (x :: xs)\n        | None => None\n      end\n    | None :: rest => None\n  end.\n*)\n\n(* For the lsubst_aux to work, we will require the bound_vars of sub to\n * be disjoint from all the vars of t *)\nFixpoint sosub_aux {o} (sub : @SOSub o) (t : SOTerm) : NTerm :=\n  match t with\n  | sovar var ts =>\n    match sosub_find sub (var,length ts) with\n    | Some (sosk vs u) => lsubst_aux u (combine vs (map (sosub_aux sub) ts))\n    | None => apply_list (mk_var var) (map (sosub_aux sub) ts)\n    end\n  | soseq s => sterm s\n  | soterm opid bts => oterm opid (map (sosub_b_aux sub) bts)\n  end\nwith sosub_b_aux {o} (sub : @SOSub o) (bt : SOBTerm) : BTerm :=\n       match bt with\n       | sobterm vs t =>\n         bterm vs (sosub_aux (sosub_filter sub (vars2sovars vs)) t)\n       end.\n\nDefinition free_vars_sk {o} (sk : @sosub_kind o) : list NVar :=\n  match sk with\n    | sosk vs t => remove_nvars vs (free_vars t)\n  end.\n\n(* Same as free_vars_sk *)\nDefinition free_vars_sosub_kind {o} (sk : @sosub_kind o) :=\n  free_vars_bterm (sk2bterm sk).\n\nLemma free_vars_sk_is_free_vars_sosub_kind {o} :\n  forall sk : @sosub_kind o,\n    free_vars_sk sk = free_vars_sosub_kind sk.\nProof.\n  destruct sk.\n  unfold free_vars_sk, free_vars_sosub_kind; simpl; auto.\nQed.\n\nDefinition free_vars_sosub {o} (sub : @SOSub o) : list NVar :=\n  flat_map (fun x => free_vars_sk (snd x)) sub.\n\nDefinition bound_vars_in_sk {o} (sk : @sosub_kind o) : list NVar :=\n  match sk with\n    | sosk _ t => bound_vars t\n  end.\n\nDefinition bound_vars_in_sosub {o} (sub : @SOSub o) : list NVar :=\n  flat_map (fun x => bound_vars_in_sk (snd x)) sub.\n\nDefinition bound_vars_sk {o} (sk : @sosub_kind o) : list NVar :=\n  match sk with\n    | sosk vs t => vs ++ bound_vars t\n  end.\n\nDefinition bound_vars_sosub {o} (sub : @SOSub o) : list NVar :=\n  flat_map (fun x => bound_vars_sk (snd x)) sub.\n\nDefinition foren := list (NVar # NVar).\n\nDefinition soren := list (sovar_sig # NVar).\n\nDefinition foren_dom (ren : foren) : list NVar := map (fun v => fst v) ren.\nDefinition soren_dom (ren : soren) : list sovar_sig := map (fun v => fst v) ren.\n\nLemma foren_dom_app :\n  forall ren1 ren2,\n    foren_dom (ren1 ++ ren2) = foren_dom ren1 ++ foren_dom ren2.\nProof.\n  introv; unfold foren_dom; rw map_app; auto.\nQed.\n\nDefinition mk_foren (vs1 vs2 : list NVar) : foren := combine vs1 vs2.\nDefinition mk_soren (vs1 : list sovar_sig) (vs2 : list NVar) : soren :=\n  combine vs1 vs2.\n\nLemma foren_dom_mk_foren :\n  forall vs1 vs2, length vs1 = length vs2 -> foren_dom (mk_foren vs1 vs2) = vs1.\nProof.\n  induction vs1; introv e; allsimpl; auto.\n  destruct vs2; allsimpl; cpx.\n  rw IHvs1; auto.\nQed.\n\nLemma soren_dom_mk_soren :\n  forall vs1 vs2, length vs1 = length vs2 -> soren_dom (mk_soren vs1 vs2) = vs1.\nProof.\n  induction vs1; introv e; allsimpl; auto.\n  destruct vs2; allsimpl; cpx.\n  rw IHvs1; auto.\nQed.\n\nDefinition foren2soren (ren : foren) : soren :=\n  map (fun x =>\n         match x with\n           | (v1,v2) => (var2sovar v1, v2)\n         end)\n      ren.\n\nLemma foren2soren_app :\n  forall ren1 ren2,\n    foren2soren (ren1 ++ ren2) = foren2soren ren1 ++ foren2soren ren2.\nProof.\n  induction ren1; simpl; auto.\n  destruct a; introv.\n  rw IHren1; auto.\nQed.\n\nFixpoint foren_vars (ren : foren) : list NVar :=\n  match ren with\n    | nil => nil\n    | (v1,v2) :: xs => v1 :: v2 :: foren_vars xs\n  end.\n\nFixpoint soren_vars (ren : soren) : list NVar :=\n  match ren with\n    | nil => nil\n    | ((v1,n),v2) :: xs => v1 :: v2 :: soren_vars xs\n  end.\n\nFixpoint foren_filter (ren : foren) (vars : list NVar) : foren :=\n  match ren with\n    | nil => nil\n    | (v1, v2) :: xs =>\n      if memvar v1 vars\n      then foren_filter xs vars\n      else (v1,v2) :: foren_filter xs vars\n  end.\n\nFixpoint foren_find (ren : foren) (v : NVar) : option NVar :=\n  match ren with\n    | nil => None\n    | (v1, v2) :: xs =>\n      if deq_nvar v1 v\n      then Some v2\n      else foren_find xs v\n  end.\n\nFixpoint soren_find (ren : soren) (v : sovar_sig) : option sovar_sig :=\n  match ren with\n    | nil => None\n    | ((v1,n) as sv, v2) :: xs =>\n      if sovar_sig_dec sv v\n      then Some (v2,n)\n      else soren_find xs v\n  end.\n\nDefinition rename_var (ren : foren) (v : NVar) : NVar :=\n  match foren_find ren v with\n    | Some w => w\n    | None => v\n  end.\n\nDefinition rename_sovar (ren : soren) (v : sovar_sig) : sovar_sig :=\n  match soren_find ren v with\n    | Some w => w\n    | None => v\n  end.\n\nLemma rename_var_cons :\n  forall v1 v2 ren v,\n    rename_var ((v1,v2) :: ren) v\n    = if deq_nvar v1 v\n      then v2\n      else rename_var ren v.\nProof.\n  introv; unfold rename_var; simpl; boolvar; auto.\nQed.\n\nLemma rename_sovar_nil :\n  forall v, rename_sovar [] v = v.\nProof. sp. Qed.\n\nLemma rename_sovar_cons :\n  forall v1 n v2 ren v,\n    rename_sovar (((v1,n),v2) :: ren) v\n    = if sovar_sig_dec (v1,n) v\n      then (v2,n)\n      else rename_sovar ren v.\nProof.\n  introv; unfold rename_sovar; simpl; boolvar; auto.\nQed.\n\nFixpoint fo_change_bvars_alpha {p} (disj : list NVar) (ren : foren) (t : @SOTerm p) :=\n  match t with\n  | sovar v ts =>\n    if bnull ts\n    then sovar (rename_var ren v) []\n    else sovar v (map (fo_change_bvars_alpha disj ren) ts)\n  | soseq s => soseq s\n  | soterm o bs => soterm o (map (fo_change_bvars_alphabt disj ren) bs)\n  end\nwith fo_change_bvars_alphabt {p} disj ren bt :=\n       match bt with\n       | sobterm vs t =>\n         let vs' := fresh_distinct_vars (length vs) (vs ++ disj ++ all_fo_vars t ++ foren_vars ren) in\n         sobterm vs' (fo_change_bvars_alpha disj (mk_foren vs vs' ++ ren) t)\n       end.\n(* vs in the list of distinct vars above is not necessary but useful *)\n\nFixpoint so_change_bvars_alpha {p} (disj : list NVar) (ren : soren) (t : @SOTerm p) :=\n  match t with\n  | sovar v ts =>\n    sovar\n      (sovar2var (rename_sovar ren (v,length ts)))\n      (map (so_change_bvars_alpha disj ren) ts)\n  | soseq s => soseq s\n  | soterm o bs => soterm o (map (so_change_bvars_alphabt disj ren) bs)\n  end\nwith so_change_bvars_alphabt {p} disj ren bt :=\n       match bt with\n       | sobterm vs t =>\n         let vs' := fresh_distinct_vars (length vs) (disj ++ all_fo_vars t ++ soren_vars ren) in\n         sobterm vs' (so_change_bvars_alpha disj (mk_soren (vars2sovars vs) vs' ++ ren) t)\n       end.\n(* all_fo_vars could just be the free vars above *)\n\nDefinition allvars_range_sosub {o} (sub : @SOSub o) : list NVar :=\n  flat_map (fun x => allvars_sk (snd x)) sub.\n\nDefinition sk_change_bvars_in_alpha {o} (vs : list NVar) (sk : @sosub_kind o) : sosub_kind :=\n  match sk with\n    | sosk vars t => sosk vars (change_bvars_alpha vs t)\n  end.\n\nDefinition sosub_change_bvars_in_alpha {o} (vs : list NVar) (sub : @SOSub o) :=\n  map (fun x =>\n         match x with\n           | (v,sk) => (v,sk_change_bvars_in_alpha vs sk)\n         end)\n      sub.\n\nDefinition sk_change_bvars_alpha {o} (vs : list NVar) (sk : @sosub_kind o) : sosub_kind :=\n  bterm2sk (change_bvars_alphabt vs (sk2bterm sk)).\n\nDefinition sosub_change_bvars_alpha {o} (vs : list NVar) (sub : @SOSub o) :=\n  map (fun x =>\n         match x with\n           | (v,sk) => (v,sk_change_bvars_alpha vs sk)\n         end)\n      sub.\n\nDefinition sosub {o} (sub : @SOSub o) (t : SOTerm) : NTerm :=\n  let fvars_s := free_vars_sosub sub in\n  let bvars_s := bound_vars_sosub sub in\n  let bvars_t := fo_bound_vars t in\n  if dec_disjointv bvars_t fvars_s\n  then let avars_t := all_fo_vars t in\n       if dec_disjointv (fvars_s ++ avars_t) bvars_s\n       then sosub_aux sub t\n       else sosub_aux\n              (sosub_change_bvars_alpha (allvars_range_sosub sub ++ avars_t) sub)\n              t\n  else let t' := fo_change_bvars_alpha (fvars_s ++ all_fo_vars t) [] t in\n       let avars_t := all_fo_vars t' in\n       if dec_disjointv (fvars_s ++ avars_t) bvars_s\n       then sosub_aux sub t'\n       else sosub_aux\n              (sosub_change_bvars_alpha (allvars_range_sosub sub ++ avars_t) sub)\n              t'.\n(* we don't need all the bound vars of sub here, just the once in the terms in the range *)\n\nDefinition sk_prog_b {o} (sk : @sosub_kind o) : obool :=\n  match sk with\n    | sosk vs t => oband (bool2obool (sub_vars (free_vars t) vs)) (wft t)\n  end.\n\nDefinition sosub_prog_b {o} (sub : @SOSub o) : obool :=\n  oball (map (fun x => sk_prog_b (snd x)) sub).\n\nDefinition sub2otrue {o} (s : @Sub o) : obool :=\n  oball (map (fun x => term2otrue (snd x)) s).\n\nDefinition sk2otrue {o} (sk : @sosub_kind o) : obool :=\n  match sk with\n    | sosk vs t => term2otrue t\n  end.\n\nDefinition sosub2otrue {o} (s : @SOSub o) : obool :=\n  oball (map (fun x => sk2otrue (snd x)) s).\n\nDefinition sk_prog {o} (sk : @sosub_kind o) := sk_prog_b sk = sk2otrue sk.\n\nDefinition sosub_prog {o} (sub : @SOSub o) := sosub_prog_b sub = sosub2otrue sub.\n\nDefinition isprog_sk {o} (sk : @sosub_kind o) :=\n  match sk with\n    | sosk vs t => isprog_vars vs t\n  end.\n\nDefinition sk_wf_b {o} (sk : @sosub_kind o) : obool :=\n  match sk with\n    | sosk vs t => wft t\n  end.\n\nDefinition sk_wf {o} (sk : @sosub_kind o) := sk_wf_b sk = sk2otrue sk.\n\nDefinition sosub_wf_b {o} (sub : @SOSub o) : obool :=\n  oball (map (fun x => sk_wf_b (snd x)) sub).\n\nDefinition sosub_wf {o} (sub : @SOSub o) := sosub_wf_b sub = sosub2otrue sub.\n\nLemma sk_prog_b_otrue_implies {o} :\n  forall (sk : @sosub_kind o),\n    sk_prog_b sk = otrue\n    -> sk2otrue sk = otrue.\nProof.\n  introv h.\n  destruct sk; allsimpl.\n  abs_bool2obool q.\n  destruct q; allsimpl; auto; ginv.\n  apply wft_otrue_implies_term2otrue_otrue; auto.\nQed.\n\nLemma sk2otrue_ofalse {o} :\n  forall (sk : @sosub_kind o), sk2otrue sk = ofalse -> False.\nProof.\n  destruct sk; simpl; introv.\n  apply term2otrue_not_ofalse.\nQed.\n\nLemma sosub2otrue_ofalse {o} :\n  forall (s : @SOSub o), sosub2otrue s = ofalse -> False.\nProof.\n  induction s; introv h; allsimpl; tcsp.\n  - unfold sosub2otrue in h; allsimpl; ginv.\n  - unfold sosub2otrue in h; allsimpl.\n    fold (sosub2otrue s) in h.\n    destruct a; allsimpl.\n    remember (sosub2otrue s) as ss; symmetry in Heqss; destruct ss; allsimpl.\n    + remember (sk2otrue s0) as o1; symmetry in Heqo1.\n      destruct o1; allsimpl; ginv.\n      apply sk2otrue_ofalse in Heqo1; sp.\n    + autodimp IHs hyp; sp.\n    + clear IHs.\n      remember (sk2otrue s0) as o1; symmetry in Heqo1.\n      destruct o1; allsimpl; ginv.\n      apply sk2otrue_ofalse in Heqo1; sp.\nQed.\n\nLemma oband_otrue :\n  forall o, oband o otrue = o.\nProof.\n  destruct o; allsimpl; auto.\nQed.\n\nLemma isotrue_sk2otrue {o} :\n  forall (sk : @sosub_kind o), isotrue (sk2otrue sk).\nProof.\n  destruct sk; simpl.\n  apply isotrue_term2otrue.\nQed.\n\nLemma isotrue_sosub2otrue {o} :\n  forall (s : @SOSub o), isotrue (sosub2otrue s).\nProof.\n  induction s; introv; simpl; auto.\n  unfold sosub2otrue; simpl.\n  apply isotrue_oband; dands; auto.\n  apply isotrue_sk2otrue.\nQed.\n\nLemma sk_prog_as_isotrue {o} :\n  forall (sk : @sosub_kind o),\n    sk_prog sk <=> isotrue (sk_prog_b sk).\nProof.\n  unfold sk_prog.\n  introv.\n  split; intro h.\n  - rw h.\n    apply isotrue_sk2otrue.\n  - destruct sk; allsimpl.\n    allrw isotrue_oband; repnd.\n    abs_bool2obool b; destruct b; allsimpl; tcsp.\n    apply isotrue_wft_implies_eq_term2otrue in h; auto.\nQed.\n\nLemma sk_wf_as_isotrue {o} :\n  forall (sk : @sosub_kind o),\n    sk_wf sk <=> isotrue (sk_wf_b sk).\nProof.\n  unfold sk_prog.\n  introv.\n  split; intro h.\n  - rw h.\n    apply isotrue_sk2otrue.\n  - destruct sk; allsimpl.\n    allrw isotrue_oband; repnd.\n    apply isotrue_wft_implies_eq_term2otrue in h; auto.\nQed.\n\nLemma sosub_prog_as_isotrue {o} :\n  forall (s : @SOSub o),\n    sosub_prog s <=> isotrue (sosub_prog_b s).\nProof.\n  unfold sosub_prog.\n  introv.\n  split; intro h.\n  - rw h.\n    apply isotrue_sosub2otrue.\n  - induction s; allsimpl; auto.\n    unfold sosub_prog_b in h; allsimpl.\n    apply isotrue_oband in h; repnd; allsimpl.\n    fold (sosub_prog_b s) in h.\n    autodimp IHs hyp.\n\n    unfold sosub_prog_b; simpl.\n    fold (sosub_prog_b s).\n    rw IHs.\n    unfold sosub2otrue; simpl.\n    fold (sosub2otrue s).\n\n    apply sk_prog_as_isotrue in h0.\n    rw h0; auto.\nQed.\n\nLemma sosub_wf_as_isotrue {o} :\n  forall (s : @SOSub o),\n    sosub_wf s <=> isotrue (sosub_wf_b s).\nProof.\n  unfold sosub_wf.\n  introv.\n  split; intro h.\n  - rw h.\n    apply isotrue_sosub2otrue.\n  - induction s; allsimpl; auto.\n    unfold sosub_wf_b in h; allsimpl.\n    apply isotrue_oband in h; repnd; allsimpl.\n    fold (sosub_wf_b s) in h.\n    autodimp IHs hyp.\n\n    unfold sosub_wf_b; simpl.\n    fold (sosub_wf_b s).\n    rw IHs.\n    unfold sosub2otrue; simpl.\n    fold (sosub2otrue s).\n\n    apply sk_wf_as_isotrue in h0.\n    rw h0; auto.\nQed.\n\nLemma isotrue_oball_map :\n  forall A (f : A -> obool) (l : list A),\n    isotrue (oball (map f l)) <=> (forall x : A, LIn x l -> isotrue (f x)).\nProof.\n  induction l; simpl; tcsp.\n  split; intro h; tcsp.\n  allrw isotrue_oband.\n  rw IHl.\n  split; intro h; repnd; dands; auto.\n  introv i; repndors; subst; auto.\nQed.\n\nLemma isotrue_bool2obool_iff :\n  forall b : bool, isotrue (bool2obool b) <=> b = true.\nProof.\n  introv.\n  split; intro h.\n  - apply isotrue_bool2obool in h; auto.\n  - subst; simpl; auto.\nQed.\n\nLemma isotrue_wft_implies_eq_term2otrue_iff {o} :\n  forall (t : @NTerm o), isotrue (wft t) <=> wft t = term2otrue t.\nProof.\n  introv; split; intro h.\n  - apply isotrue_wft_implies_eq_term2otrue; auto.\n  - rw h.\n    apply isotrue_term2otrue.\nQed.\n\nLemma sosub_prog_prop1 {o} :\n  forall (sub : @SOSub o),\n    sosub_prog sub\n    <=>\n    (forall b, LIn b (sorange sub) -> isprogram_bt b).\nProof.\n  introv.\n  rw @sosub_prog_as_isotrue.\n  unfold sosub_prog_b.\n  rw isotrue_oball_map.\n  split; intro k; introv h.\n\n  - apply in_sorange in h; exrepnd.\n    apply k in h0; destruct b; allsimpl.\n    allrw isotrue_oband; repnd.\n    allapply isotrue_bool2obool.\n    fold (assert (sub_vars (free_vars n) l)) in h1.\n    fold (subvars (free_vars n) l) in h1.\n    constructor; auto.\n    + unfold closed_bt; simpl.\n      apply null_remove_nvars_subvars in h1; auto.\n      rw null_iff_nil in h1; auto.\n    + constructor; apply nt_wf_eq; auto.\n      apply isotrue_wft_implies_eq_term2otrue in h0; auto.\n\n  - destruct x; destruct s; allsimpl.\n    apply isotrue_oband.\n    rw isotrue_bool2obool_iff.\n    fold (assert (sub_vars (free_vars n0) l)).\n    fold (subvars (free_vars n0) l).\n    pose proof (k (bterm l n0)) as q.\n    autodimp q hyp;[apply in_sorange; simpl; eexists; eauto|].\n    inversion q as [c w]; allunfold @closed_bt; allsimpl.\n    inversion w; subst.\n    allrw @bt_wf_iff.\n    rw @isotrue_wft_implies_eq_term2otrue_iff.\n    allrw @nt_wf_eq; dands; auto.\n    apply null_remove_nvars_subvars; rw c; sp.\nQed.\n\nLemma sosub_wf_prop1 {o} :\n  forall (sub : @SOSub o),\n    sosub_wf sub\n    <=>\n    (forall b, LIn b (sorange sub) -> wf_bterm b).\nProof.\n  introv.\n  rw @sosub_wf_as_isotrue.\n  unfold sosub_prog_b.\n  rw isotrue_oball_map.\n  split; intro k; introv h.\n\n  - apply in_sorange in h; exrepnd.\n    apply k in h0; destruct b; allsimpl.\n    unfold wf_bterm; simpl.\n    apply isotrue_wft_implies_eq_term2otrue in h0; auto.\n\n  - destruct x; destruct s; allsimpl.\n    pose proof (k (bterm l n0)) as q.\n    autodimp q hyp;[apply in_sorange; simpl; eexists; eauto|].\n    unfold wf_bterm in q; allsimpl.\n    rw @isotrue_wft_implies_eq_term2otrue_iff; auto.\nQed.\n\nLemma isprogram_bt_iff_isprog_vars {o} :\n  forall vs (t : @NTerm o),\n    isprogram_bt (bterm vs t)\n    <=> isprog_vars vs t.\nProof.\n  introv.\n  unfold isprogram_bt, isprog_vars, closed_bt; simpl.\n  rw @bt_wf_iff.\n  rw @wf_term_eq.\n  rw <- null_iff_nil.\n  rw null_remove_nvars_subvars; sp.\nQed.\n\nLemma sosub_prog_cons {o} :\n  forall (sub : @SOSub o) v vs t,\n    sosub_prog ((v,sosk vs t) :: sub)\n    <=> (isprog_vars vs t # sosub_prog sub).\nProof.\n  introv.\n  allrw @sosub_prog_prop1; simpl.\n  split; intro h; repnd; dands; auto.\n  - pose proof (h (bterm vs t)) as q; clear h; autodimp q hyp.\n    apply isprogram_bt_iff_isprog_vars; auto.\n  - introv i; repndors; subst; auto.\n    apply isprogram_bt_iff_isprog_vars; auto.\nQed.\n\nLemma sosub_prog_cons2 {o} :\n  forall (sub : @SOSub o) v sk,\n    sosub_prog ((v,sk) :: sub)\n    <=> (isprog_sk sk # sosub_prog sub).\nProof.\n  introv.\n  destruct sk; rw @sosub_prog_cons; simpl; sp.\nQed.\n\nLemma sosub_wf_cons {o} :\n  forall (sub : @SOSub o) v vs t,\n    sosub_wf ((v,sosk vs t) :: sub)\n    <=> (wf_term t # sosub_wf sub).\nProof.\n  introv.\n  allrw @sosub_wf_prop1; simpl.\n  split; intro h; repnd; dands; auto.\n  - pose proof (h (bterm vs t)) as q; clear h; autodimp q hyp.\n  - introv i; repndors; subst; auto.\nQed.\n\nLemma in_sosub_prog {o} :\n  forall (sub : @SOSub o) v vs t,\n    LIn (v, sosk vs t) sub\n    -> sosub_prog sub\n    -> isprog_vars vs t.\nProof.\n  induction sub; introv i p; allsimpl; tcsp.\n  destruct a; destruct s.\n  dorn i; cpx; ginv; apply sosub_prog_cons in p; tcsp.\n  repnd.\n  eapply IHsub; eauto.\nQed.\n\nLemma in_sosub_wf {o} :\n  forall (sub : @SOSub o) v vs t,\n    LIn (v, sosk vs t) sub\n    -> sosub_wf sub\n    -> wf_term t.\nProof.\n  induction sub; introv i p; allsimpl; tcsp.\n  destruct a; destruct s.\n  dorn i; cpx; ginv; apply sosub_wf_cons in p; tcsp.\n  repnd.\n  eapply IHsub; eauto.\nQed.\n\nLemma implies_sosub_prog_sosub_filter {o} :\n  forall (sub : @SOSub o) vs,\n    sosub_prog sub\n    -> sosub_prog (sosub_filter sub vs).\nProof.\n  induction sub; introv h; allsimpl; auto.\n  destruct a; destruct s.\n  rw @sosub_prog_cons in h; repnd.\n  boolvar; auto.\n  apply sosub_prog_cons; dands; auto.\nQed.\n\nLemma implies_sosub_wf_sosub_filter {o} :\n  forall (sub : @SOSub o) vs,\n    sosub_wf sub\n    -> sosub_wf (sosub_filter sub vs).\nProof.\n  induction sub; introv h; allsimpl; auto.\n  destruct a; destruct s.\n  rw @sosub_wf_cons in h; repnd.\n  boolvar; auto.\n  apply sosub_wf_cons; dands; auto.\nQed.\n\nLemma in_sodom_if {o} :\n  forall (sub : @SOSub o) v vs t k,\n    LIn (v, sosk vs t) sub\n    -> k = length vs\n    -> LIn (v,k) (sodom sub).\nProof.\n  induction sub; simpl; introv i e; subst; auto.\n  destruct a; destruct s; dorn i; cpx; ginv; tcsp.\n  eapply IHsub in i; eauto.\nQed.\n\n(*\nFixpoint get_fo_vars (l : list sovar_sig) : list NVar :=\n  match l with\n    | nil => nil\n    | (v,0) :: l => v :: get_fo_vars l\n    | _ :: l => get_fo_vars l\n  end.\n*)\n\nFixpoint sosize {p} (t : @SOTerm p) : nat :=\n  match t with\n  | sovar _ ts => S (addl (map sosize ts))\n  | soseq s => 0\n  | soterm op bs => S (addl (map sosize_bterm bs))\n  end\nwith sosize_bterm {p} (b : SOBTerm) :=\n       match b with\n         | sobterm _ t => sosize t\n       end.\n\nLemma sosize_in {p} :\n  forall (t : @SOTerm p) ts,\n    LIn t ts -> sosize t <= addl (map sosize ts).\nProof.\n  induction ts; introv i; allsimpl; tcsp.\n  dorn i; subst; tcsp; try omega.\n  apply IHts in i; try omega.\nQed.\n\nLemma sosize_bterm_in {p} :\n  forall (b : @SOBTerm p) bs,\n    LIn b bs -> sosize_bterm b <= addl (map sosize_bterm bs).\nProof.\n  induction bs; introv i; allsimpl; tcsp.\n  dorn i; subst; tcsp; try omega.\n  apply IHbs in i; try omega.\nQed.\n\nLemma SOTerm_better_ind2 {p} :\n  forall P : (@SOTerm p) -> Type,\n    (forall v ts,\n       (forall t, LIn t ts -> P t)\n       -> P (sovar v ts))\n    -> (forall s, P (soseq s))\n    -> (forall (o : Opid) (bs : list SOBTerm),\n          (forall (t t': SOTerm) (vs : list NVar),\n             (LIn (sobterm vs t) bs)\n              -> sosize t' <= sosize t\n              -> P t'\n          )\n          -> P (soterm o bs)\n       )\n    -> forall t : SOTerm, P t.\nProof.\n  intros P Hvar Hseq Hbt.\n  assert (forall n t, sosize t = n -> P t)\n    as Hass;\n    [ | intros; apply Hass with (n := sosize t); eauto; fail ].\n\n  induction n as [n Hind] using comp_ind_type.\n  intros t Hsz.\n  destruct t.\n  - apply Hvar; allsimpl.\n    introv i.\n    destruct n; cpx.\n    pose proof (Hind (sosize t)) as k; autodimp k hyp.\n    apply sosize_in in i; omega.\n  - apply Hseq.\n  - apply Hbt.\n    introv Hin Hs.\n    apply Hind with (m := sosize t'); auto.\n    subst.\n    apply sosize_bterm_in in Hin; allsimpl; omega.\nQed.\n\nLemma SOTerm_better_ind {p} :\n  forall P : @SOTerm p -> Type,\n    (forall v ts,\n       (forall t, LIn t ts -> P t)\n       -> P (sovar v ts))\n    -> (forall s, P (soseq s))\n    -> (forall (o : Opid) (bs : list SOBTerm),\n          (forall t vs, LIn (sobterm vs t) bs -> P t)\n          -> P (soterm o bs)\n       )\n    -> forall t : SOTerm, P t.\nProof.\n  introv Hv Hseq Hind.\n  apply SOTerm_better_ind2; auto.\n  introv Hx.\n  apply Hind.\n  introv Hin.\n  eapply Hx in Hin; eauto.\nQed.\n\nTactic Notation \"soterm_ind\" ident(h) ident(c) :=\n  induction h using SOTerm_better_ind;\n  [ Case_aux c \"sovar\"\n  | Case_aux c \"soseq\"\n  | Case_aux c \"soterm\"\n  ].\n\nTactic Notation \"soterm_ind\" ident(h) \"as\" simple_intropattern(I)  ident(c) :=\n  induction h as I using SOTerm_better_ind;\n  [ Case_aux c \"sovar\"\n  | Case_aux c \"soseq\"\n  | Case_aux c \"soterm\"\n  ].\n\nTactic Notation \"soterm_ind1\" ident(h) \"as\" simple_intropattern(I)  ident(c) :=\n  induction h as I using SOTerm_better_ind;\n  [ Case_aux c \"sovar\"\n  | Case_aux c \"soseq\"\n  | Case_aux c \"soterm\"\n  ].\n\nTactic Notation \"soterm_ind1s\" ident(h) \"as\" simple_intropattern(I)  ident(c) :=\n  induction h as I using SOTerm_better_ind2;\n  [ Case_aux c \"sovar\"\n  | Case_aux c \"soseq\"\n  | Case_aux c \"soterm\"\n  ].\n\nLemma sosub_find_some {p} :\n  forall (sub : @SOSub p) v n vs t,\n    sosub_find sub (v,n) = Some (sosk vs t)\n    -> LIn (v, sosk vs t) sub # length vs = n.\nProof.\n  induction sub; introv h; allsimpl; tcsp.\n  destruct a; destruct s.\n  boolvar; subst; simpl in *; ginv; tcsp; apply IHsub in h; tcsp.\nQed.\n\nLemma sosub_find_none {p} :\n  forall (sub : @SOSub p) v n,\n    sosub_find sub (v,n) = None\n    -> !LIn (v,n) (sodom sub).\nProof.\n  induction sub; introv h; allsimpl; tcsp.\n  destruct a; destruct s.\n  boolvar; subst; ginv; tcsp; apply IHsub in h; tcsp.\n  intro xx; repndors; ginv; tcsp.\nQed.\n\n(*\nLemma in_lift_list_option :\n  forall T l (k : list T),\n    lift_list_option l = Some k\n    -> (\n         length l = length k\n         # (forall t, LIn t k -> LIn (Some t) l)\n       ).\nProof.\n  induction l; introv lift; allsimpl; ginv; allsimpl; tcsp.\n  destruct a; ginv.\n  remember (lift_list_option l) as o; destruct o; ginv; allsimpl.\n  pose proof (IHl l0) as h; autodimp h hyp; repnd.\n  dands; sp; subst; sp.\nQed.\n*)\n\nLemma wf_apply_solist {o} :\n  forall (ts : list (@SOTerm o)) f,\n    wf_term (apply_list f (map soterm2nterm ts))\n    <=> (wf_term f # (forall t, LIn t ts -> wf_soterm t)).\nProof.\n  introv.\n  rw @wf_apply_list; split; intro k; repd; dands; auto.\n  - introv i.\n    apply w0.\n    rw in_map_iff; exists t; sp.\n  - introv i.\n    rw in_map_iff in i; exrepnd; subst.\n    apply w0 in i1; sp.\nQed.\n\nLemma wf_sovar {o} :\n  forall v (ts : list (@SOTerm o)),\n    wf_soterm (sovar v ts)\n    <=> (forall t, LIn t ts -> wf_soterm t).\nProof.\n  introv; split.\n  - introv w i.\n    allunfold @wf_soterm; simpl in w.\n    allrw @fold_wf_term.\n    apply wf_apply_solist in w; repnd.\n    apply w; auto.\n  - introv w.\n    allunfold @wf_soterm; allsimpl.\n    apply wf_apply_solist; dands; auto.\n    apply wf_term_eq; auto.\nQed.\n\nLemma wf_soterm_implies {o} :\n  forall op (bs : list (@SOBTerm o)),\n    wf_soterm (soterm op bs)\n    -> forall vs t,\n         LIn (sobterm vs t) bs\n         -> wf_soterm t.\nProof.\n  introv wf i.\n  allunfold @wf_soterm.\n  apply wf_term_eq in wf; allsimpl.\n  inversion wf as [|?|? ? imp e]; subst; clear e.\n  pose proof (imp (bterm vs (soterm2nterm t))) as h; clear imp.\n  autodimp h hyp.\n  - rw in_map_iff.\n    eexists; eauto.\n  - inversion h; subst.\n    apply wf_term_eq; auto.\nQed.\n\n(*\nLemma isprogram_sosub_aux1 {p} :\n  forall (t : SOTerm) (sub : @SOSub p) u,\n    wf_soterm t\n    -> sosub_prog sub\n    -> sosub_aux sub t = Some u\n    -> isprog u.\nProof.\n  soterm_ind t as [ v ts ind | o lbt ind ] Case; simpl; introv wf k e.\n\n  - Case \"sovar\".\n    remember (sosub_find sub v (length ts)) as o;\n      destruct o; symmetry in Heqo; simpl; auto; ginv.\n    destruct s.\n    remember (lift_list_option (map (sosub_aux sub) ts)) as ll;\n      destruct ll; symmetry in Heqll; auto; ginv.\n    applydup in_lift_list_option in Heqll; repnd.\n    allrw map_length.\n    applydup @sosub_find_some in Heqo; repnd.\n    apply isprog_eq; split.\n    + unfold closed.\n      rw @isprogram_lsubst_aux2.\n      * rw @dom_sub_combine; auto; try omega.\n        eapply in_sosub_prog in Heqo1; eauto.\n        rw @isprog_vars_eq in Heqo1; repnd.\n        apply null_iff_nil.\n        apply null_remove_nvars_subvars; auto.\n      * introv i.\n        apply isprog_eq.\n        apply in_combine in i; repnd.\n        apply Heqll0 in i; rw in_map_iff in i; exrepnd.\n        symmetry in i1.\n        apply ind in i1; repnd; auto.\n        eapply wf_sovar in wf; eauto.\n    + apply nt_wf_eq; apply lsubst_aux_preserves_wf_term.\n      * eapply in_sosub_prog in Heqo1; eauto.\n        apply isprog_vars_eq in Heqo1; repnd.\n        apply wf_term_eq; auto.\n      * introv i.\n        apply in_combine in i; repnd.\n        apply Heqll0 in i; rw in_map_iff in i; exrepnd.\n        symmetry in i1.\n        apply ind in i1; repnd; auto; [ | eapply wf_sovar in wf; eauto].\n        apply isprog_eq in i1; destruct i1 as [c w].\n        apply wf_term_eq; auto.\n\n  - Case \"soterm\".\n    remember (lift_list_option (map (sosub_b_aux sub) lbt)).\n*)\n\nLemma remove_so_vars_nil_r :\n  forall l, remove_so_vars l [] = [].\nProof.\n  unfold remove_so_vars; apply diff_nil.\nQed.\n\nLemma remove_so_vars_app_r :\n  forall l1 l2 l3,\n    remove_so_vars l1 (l2 ++ l3) = remove_so_vars l1 l2 ++ remove_so_vars l1 l3.\nProof.\n  apply diff_app_r.\nQed.\n\nLemma remove_so_vars_flat_map :\n  forall T,\n  forall f : T -> list sovar_sig,\n  forall l : list T,\n  forall vars : list sovar_sig,\n   remove_so_vars vars (flat_map f l) =\n   flat_map (compose (remove_so_vars vars) f) l.\nProof.\n  induction l; simpl; sp.\n  apply remove_so_vars_nil_r.\n  rewrite remove_so_vars_app_r.\n  rewrite IHl; sp.\nQed.\n\nLemma sovars2vars_flat_map :\n  forall T ts (f : T -> list sovar_sig),\n    sovars2vars (flat_map f ts) = flat_map (compose sovars2vars f) ts.\nProof.\n  unfold sovars2vars; introv.\n  rw map_flat_map; unfold compose; auto.\nQed.\n\nLemma remove_so_vars_app_l :\n  forall l1 l2 l3,\n     remove_so_vars l1 (remove_so_vars l2 l3) = remove_so_vars (l1 ++ l2) l3.\nProof.\n  apply diff_app_l.\nQed.\n\nLemma sodom_sosub_filter {o} :\n  forall (sub : @SOSub o) vs,\n    sodom (sosub_filter sub vs) = remove_so_vars vs (sodom sub).\nProof.\n  induction sub; simpl; introv.\n  - rw remove_so_vars_nil_r; auto.\n  - destruct a; destruct s; boolvar; rw remove_so_vars_cons_r; boolvar; simpl; tcsp.\n    rw IHsub; auto.\nQed.\n\nLemma in_sovars2vars :\n  forall v vs,\n    LIn v (sovars2vars vs)\n    <=> {n : nat & LIn (v,n) vs}.\nProof.\n  induction vs; simpl; split; intro k; exrepnd; tcsp.\n  - dorn k; subst.\n    + destruct a.\n      exists n0; simpl; tcsp.\n    + apply IHvs in k; exrepnd.\n      exists n; sp.\n  - dorn k0; subst; allsimpl; tcsp.\n    destruct a; right; apply IHvs; exists n; sp.\nQed.\n\nLemma in_remove_so_vars :\n  forall x l1 l2,\n    LIn x (remove_so_vars l1 l2) <=> (LIn x l2 # ! LIn x l1).\nProof.\n  intros; apply in_diff.\nQed.\n\nLemma so_free_vars_in_all_fo_vars {o} :\n  forall (t : @SOTerm o) v n,\n    LIn (v, n) (so_free_vars t) -> LIn v (all_fo_vars t).\nProof.\n  soterm_ind t as [ v ts ind |  | op lbt ind ] Case; simpl; introv i; tcsp.\n\n  - Case \"sovar\".\n    dorn i; cpx.\n    apply lin_flat_map in i; exrepnd.\n    apply ind in i0; auto.\n    right; rw lin_flat_map.\n    exists x; sp.\n\n  - Case \"soterm\".\n    allrw lin_flat_map; exrepnd.\n    exists x; sp.\n    destruct x; allsimpl.\n    rw in_remove_so_vars in i0; repnd.\n    rw in_map_iff in i0.\n    rw in_app_iff.\n    pose proof (in_deq NVar deq_nvar v l) as h; dorn h; tcsp.\n    right.\n    eapply ind; eauto.\nQed.\n\nLemma subvars_bound_vars_in_sosub_bound_vars_sosub {o} :\n  forall (sub : @SOSub o),\n    subvars (bound_vars_in_sosub sub) (bound_vars_sosub sub).\nProof.\n  introv; unfold bound_vars_in_sosub, bound_vars_sosub.\n  apply subvars_flat_map2; introv i; destruct x; destruct s; simpl.\n  apply subvars_app_weak_r; auto.\nQed.\n\nLemma subvars_bound_vars_in_sosub_filter {o} :\n  forall (sub : @SOSub o) vs,\n    subvars (bound_vars_in_sosub (sosub_filter sub vs)) (bound_vars_in_sosub sub).\nProof.\n  induction sub; introv; simpl; auto.\n  destruct a; destruct s; boolvar; simpl.\n  - apply subvars_app_weak_r; auto.\n  - repeat (rw subvars_app_l); dands.\n    + apply subvars_app_weak_l; auto.\n    + apply subvars_app_weak_r; auto.\nQed.\n\nLemma subvars_bound_vars_in_sk {o} :\n  forall (sk : @sosub_kind o),\n    subvars (bound_vars_in_sk sk) (bound_vars_sk sk).\nProof.\n  destruct sk; simpl.\n  apply subvars_app_weak_r; auto.\nQed.\n\nLemma subvars_bound_vars_sosub_filter {o} :\n  forall (sub : @SOSub o) vs,\n    subvars (bound_vars_sosub (sosub_filter sub vs)) (bound_vars_sosub sub).\nProof.\n  induction sub; introv; simpl; auto.\n  destruct a; destruct s; boolvar; simpl.\n  - apply subvars_app_weak_r; auto.\n  - repeat (rw subvars_app_l); dands.\n    + repeat (apply subvars_app_weak_l); auto.\n    + apply subvars_app_weak_l; apply subvars_app_weak_r; auto.\n    + apply subvars_app_weak_r; auto.\nQed.\n\nLemma free_vars_lsubst_aux_subvars {p} :\n  forall (t : NTerm) (sub : @Sub p),\n    subvars\n      (free_vars (lsubst_aux t sub))\n      (remove_nvars (dom_sub sub) (free_vars t) ++ sub_free_vars sub).\nProof.\n  nterm_ind t as [ v | f ind | o lbt ind ] Case; simpl; introv.\n\n  - Case \"vterm\".\n    remember (sub_find sub v) as o;\n      destruct o; symmetry in Heqo; simpl; auto; ginv.\n\n    + apply sub_find_some in Heqo.\n      apply subvars_app_weak_r.\n      rw subvars_eq.\n      eapply subset_free_vars_mem; eauto.\n\n    + apply subvars_app_weak_l.\n      rw subvars_singleton_l.\n      rw in_remove_nvars; simpl; dands; tcsp.\n      intro k.\n      apply in_dom_sub_exists in k; exrepnd.\n      rw Heqo in k0; cpx.\n\n  - Case \"sterm\".\n    allrw remove_nvars_nil_r; simpl; auto.\n\n  - Case \"oterm\".\n    rw flat_map_map; unfold compose.\n    rw remove_nvars_flat_map; unfold compose.\n    rw subvars_prop; introv k.\n    rw lin_flat_map in k; exrepnd.\n    rw in_app_iff; rw lin_flat_map.\n    destruct x0; allsimpl.\n    rw in_remove_nvars in k0; repnd.\n    dup k1 as j.\n    apply ind with (sub := sub_filter sub l) in k1.\n    rw subvars_prop in k1; apply k1 in k2.\n    rw in_app_iff in k2; dorn k2.\n\n    + rw in_remove_nvars in k2; repnd.\n      left.\n      eexists; dands; eauto; simpl.\n      repeat (rw in_remove_nvars).\n      dands; auto; intro k.\n      rw <- @dom_sub_sub_filter in k2.\n      rw in_remove_nvars in k2; sp.\n\n    + apply in_sub_free_vars in k2; exrepnd.\n      rw @in_sub_filter in k3; repnd.\n      right.\n      apply in_sub_free_vars_iff.\n      repeat eexists; eauto.\nQed.\n\nLemma subvars_free_vars_sosub_mem {o} :\n  forall (sub : @SOSub o) v vs t,\n    LIn (v, sosk vs t) sub -> subvars (remove_nvars vs (free_vars t)) (free_vars_sosub sub).\nProof.\n  induction sub; introv i; allsimpl; tcsp.\n  destruct a.\n  dorn i; cpx; allsimpl.\n  - apply subvars_app_weak_l; auto.\n  - apply subvars_app_weak_r.\n    eapply IHsub; eauto.\nQed.\n\nLemma sub_free_vars_combine {o} :\n  forall vs (ts : list (@NTerm o)),\n    length vs = length ts\n    -> sub_free_vars (combine vs ts)\n       = flat_map free_vars ts.\nProof.\n  induction vs; destruct ts; introv len; allsimpl; tcsp; cpx.\n  rw IHvs; auto.\nQed.\n\nLemma in_sosub_filter {p} :\n  forall (sub : @SOSub p) v vs t vars,\n    LIn (v,sosk vs t) (sosub_filter sub vars)\n    <=>\n    (\n      LIn (v,sosk vs t) sub\n      #\n      !LIn (v, length vs) vars\n    ).\nProof.\n  induction sub; introv; simpl; split; intro k; tcsp;\n  destruct a; destruct s; boolvar; allsimpl; tcsp; repnd.\n  - rw IHsub in k; sp.\n  - dorn k; cpx; ginv; tcsp.\n    rw IHsub in k; sp.\n  - dorn k0; cpx; ginv; tcsp.\n    rw IHsub; sp.\n  - dorn k0; cpx; ginv; tcsp.\n    rw IHsub; sp.\nQed.\n\nLemma isprogram_sosub_aux_wf {p} :\n  forall (t : SOTerm) (sub : @SOSub p),\n    wf_soterm t\n    -> sosub_wf sub\n    -> wf_term (sosub_aux sub t).\nProof.\n  soterm_ind t as [ v ts ind | | o lbt ind ] Case; simpl; introv wft wfs; tcsp.\n\n  - Case \"sovar\".\n    remember (sosub_find sub (v, length ts)) as o;\n      destruct o; symmetry in Heqo; simpl; auto; ginv;\n      [destruct s|];dands.\n\n    + apply lsubst_aux_preserves_wf_term.\n      * apply sosub_find_some in Heqo; repnd.\n        eapply in_sosub_wf in Heqo0; eauto.\n      * introv i.\n        apply in_combine in i; repnd.\n        apply in_map_iff in i; exrepnd; subst.\n        eapply ind in i2; eauto; repnd; auto.\n        eapply wf_sovar in wft; eauto.\n\n    + apply wf_apply_list; dands; auto;[apply wf_term_eq; complete sp|].\n      introv i.\n      rw in_map_iff in i; exrepnd; subst.\n      eapply ind in i1; eauto; repnd; auto.\n      eapply wf_sovar in wft; eauto.\n\n  - Case \"soterm\".\n    dands.\n\n    + unfold wf_soterm in wft; simpl in wft.\n      apply wf_term_eq in wft.\n      inversion wft as [|?| ? ? imp e]; subst.\n      rw map_map in e; unfold compose in e.\n      apply wf_term_eq.\n      constructor.\n      * introv i.\n        rw in_map_iff in i; exrepnd; subst.\n        destruct a; simpl.\n        constructor.\n        apply wf_term_eq.\n        pose proof (imp (bterm l (soterm2nterm s))) as h.\n        autodimp h hyp; [rw in_map_iff; eexists; complete eauto|].\n        inversion h; subst.\n        apply ind with (sub := sosub_filter sub (vars2sovars l)) in i1; repnd; auto;\n        [ unfold wf_soterm; apply wf_term_eq; auto\n        | apply implies_sosub_wf_sosub_filter; auto\n        ].\n\n      * rw <- e.\n        rw map_map; unfold compose.\n        apply eq_maps; introv i; destruct x; allsimpl; sp.\nQed.\n\nLemma isprogram_sosub_aux_free_vars {p} :\n  forall (t : SOTerm) (sub : @SOSub p),\n    subvars\n      (free_vars (sosub_aux sub t))\n      (sovars2vars (remove_so_vars (sodom sub) (so_free_vars t))\n                   ++ free_vars_sosub sub).\nProof.\n  soterm_ind t as [ v ts ind | | o lbt ind ] Case; simpl; introv; tcsp.\n\n  - Case \"sovar\".\n    remember (sosub_find sub (v, length ts)) as o;\n      destruct o; symmetry in Heqo; simpl; auto; ginv;\n      [destruct s|];dands.\n\n    + pose proof (free_vars_lsubst_aux_subvars n (combine l (map (sosub_aux sub) ts))) as h.\n      eapply subvars_trans;[complete eauto|]; clear h.\n      rw subvars_app_l; dands.\n\n      * apply sosub_find_some in Heqo; repnd.\n        rw @dom_sub_combine; [|rw map_length; auto].\n        apply subvars_app_weak_r.\n        eapply subvars_free_vars_sosub_mem; eauto.\n\n      * apply sosub_find_some in Heqo; repnd.\n        rw @sub_free_vars_combine; [|rw map_length; auto].\n        rw flat_map_map; unfold compose.\n        rw subvars_flat_map; introv i.\n        dup i as j.\n        eapply ind in i; eauto; clear ind.\n        eapply subvars_trans;[complete eauto|]; clear i.\n        rw subvars_app_l; dands; [|apply subvars_app_weak_r; complete auto].\n\n        apply subvars_app_weak_l.\n        rw subvars_prop; introv i.\n        allrw in_sovars2vars; exrepnd.\n        rw in_remove_so_vars in i0; repnd.\n        exists n0; rw in_remove_so_vars; simpl; dands; sp.\n        right; rw lin_flat_map.\n        exists x; sp.\n\n    + rw @free_vars_apply_list; simpl.\n      rw subvars_cons_l.\n      apply sosub_find_none in Heqo.\n      rw in_app_iff.\n      rw in_sovars2vars.\n      dands.\n\n      * left.\n        exists (length ts).\n        rw in_remove_so_vars; simpl; sp.\n\n      * rw subvars_flat_map; introv i.\n        rw in_map_iff in i; exrepnd; subst.\n        dup i1 as j.\n        eapply ind in i1; clear ind.\n        eapply subvars_trans;[complete eauto|]; clear i1.\n        rw subvars_app_l; dands; [|apply subvars_app_weak_r; complete auto].\n\n        apply subvars_app_weak_l.\n        rw subvars_prop; introv i.\n        allrw in_sovars2vars; exrepnd.\n        rw in_remove_so_vars in i0; repnd.\n        exists n; rw in_remove_so_vars; simpl; dands; sp.\n        right; rw lin_flat_map.\n        exists a; sp.\n\n  - Case \"soterm\".\n    dands.\n\n    + rw flat_map_map.\n      rw remove_so_vars_flat_map.\n      rw sovars2vars_flat_map.\n      unfold compose.\n      rw subvars_prop; introv i.\n      rw lin_flat_map in i; exrepnd.\n      destruct x0; allsimpl.\n      rw in_remove_nvars in i0; repnd.\n      rw in_app_iff.\n      dup i1 as j.\n      apply ind with (sub := sosub_filter sub (vars2sovars l)) in i1; clear ind.\n\n      repnd.\n      rw subvars_prop in i1; apply i1 in i2; clear i1.\n      rw in_app_iff in i2.\n      rw in_sovars2vars in i2.\n      rw lin_flat_map.\n      dorn i2; exrepnd.\n\n      * rw in_remove_so_vars in i1; repnd.\n        rw @sodom_sosub_filter in i1.\n        rw in_remove_so_vars in i1.\n        pose proof (in_deq sovar_sig sovar_sig_dec (x,n) (sodom sub)) as d.\n        apply not_over_and in i1; auto.\n        dorn i1.\n\n        left.\n        eexists; dands; eauto; simpl.\n        rw in_sovars2vars.\n        exists n.\n        rw in_remove_so_vars; dands; tcsp.\n        rw in_remove_so_vars; dands; tcsp.\n        rw in_map_iff.\n        unfold var2sovar; intro k; exrepnd; cpx.\n\n        provefalse.\n        destruct i1.\n        intro i1.\n        rw in_map_iff in i1; exrepnd.\n        allunfold var2sovar; cpx.\n\n      * rw lin_flat_map in i2; exrepnd; allsimpl.\n        destruct x0.\n        rw @in_sosub_filter in i2; repnd; allsimpl.\n        allrw in_remove_nvars; repnd.\n        allrw in_map_iff.\n        right.\n        rw lin_flat_map.\n        eexists; dands; eauto; simpl.\n        rw in_remove_nvars; sp.\nQed.\n\nLemma sosub_prog_implies_wf {o} :\n  forall (sub : @SOSub o),\n    sosub_prog sub -> sosub_wf sub.\nProof.\n  introv prog.\n  rw @sosub_prog_prop1 in prog.\n  rw @sosub_wf_prop1.\n  introv i.\n  apply prog in i.\n  destruct b as [l t].\n  apply @isprogram_bt_iff_isprog_vars in i.\n  apply bt_wf_eq.\n  apply bt_wf_iff.\n  apply isprog_vars_eq in i; sp.\nQed.\n\nLemma implies_null_flat_map :\n  forall (A B : Type) (f : A -> list B) (l : list A),\n    (forall a, LIn a l -> null (f a))\n    -> null (flat_map f l).\nProof.\n  induction l; simpl; introv h; tcsp.\n  rw null_app; dands; tcsp.\nQed.\n\nLemma sk2bterm2sk {o} :\n  forall sk : @sosub_kind o, bterm2sk (sk2bterm sk) = sk.\nProof.\n  destruct sk; simpl; auto.\nQed.\n\nLemma sosub_prog_implies_free_vars_nil {o} :\n  forall (sub : @SOSub o),\n    sosub_prog sub -> free_vars_sosub sub = [].\nProof.\n  introv prog.\n  rw @sosub_prog_prop1 in prog.\n  apply null_iff_nil.\n  apply implies_null_flat_map; introv i.\n  destruct a as [v sk]; allsimpl.\n  pose proof (prog (sk2bterm sk)) as h; clear prog.\n  destruct sk; allsimpl.\n  autodimp h hyp.\n  { apply in_sorange; exists v; auto. }\n  apply null_remove_nvars_subvars; auto.\n  apply isprogram_bt_iff_isprog_vars in h.\n  apply isprog_vars_eq in h; sp.\nQed.\n\nLemma isprogram_sosub_aux1 {p} :\n  forall (t : SOTerm) (sub : @SOSub p),\n    wf_soterm t\n    -> sosub_prog sub\n    -> let u := sosub_aux sub t\n       in wf_term u\n          # subvars\n              (free_vars u)\n              (sovars2vars (remove_so_vars (sodom sub) (so_free_vars t))).\nProof.\n  introv wf prog; simpl.\n  applydup @sosub_prog_implies_free_vars_nil in prog.\n  applydup @sosub_prog_implies_wf in prog.\n  pose proof (isprogram_sosub_aux_wf t sub wf prog1) as h1;\n    pose proof (isprogram_sosub_aux_free_vars t sub) as h2;\n    rw prog0 in h2; rw app_nil_r in h2; dands; auto.\nQed.\n\nDefinition num_sobvars {o} (b : @SOBTerm o) :=\n  match b with\n    | sobterm vs t => length vs\n  end.\n\nLemma wf_soterm_iff {o} :\n  forall op (bs : list (@SOBTerm o)),\n    wf_soterm (soterm op bs)\n    <=>\n    (\n      map (num_sobvars) bs = OpBindings op\n      # forall vs t,\n          LIn (sobterm vs t) bs\n          -> wf_soterm t\n    ).\nProof.\n  introv.\n  unfold wf_soterm; simpl.\n  rw @wf_term_eq.\n  split; intro k; repnd; dands.\n  - inversion k as [|?|? ? imp e]; subst.\n    rw <- e; rw map_map; unfold compose; apply eq_maps; introv i.\n    destruct x; simpl; unfold num_bvars; auto.\n  - inversion k as [|?|? ? imp e]; subst.\n    introv i.\n    pose proof (imp (bterm vs (soterm2nterm t))) as h; autodimp h hyp.\n    rw in_map_iff; eexists; dands; eauto.\n    inversion h; subst; auto.\n    apply wf_term_eq; auto.\n  - constructor.\n    + introv i.\n      destruct l; rw in_map_iff in i; exrepnd; subst.\n      destruct a; allsimpl; ginv.\n      apply k in i1.\n      constructor; apply nt_wf_eq; auto.\n    + rw <- k0.\n      rw map_map; unfold compose; apply eq_maps; introv i.\n      destruct x; simpl; unfold num_bvars; simpl; auto.\nQed.\n\nLtac gen_fresh :=\n  let f := fresh \"f\" in\n  match goal with\n    | [ |- context[fresh_distinct_vars ?a ?b] ] =>\n      remember (fresh_distinct_vars a b) as f;\n        match goal with\n          | [ H : f = fresh_distinct_vars a b |- _ ] =>\n            apply fresh_distinct_vars_spec1 in H; repnd\n        end\n  end.\n\nLemma wf_soterm_fo_change_bvars_alpha {o} :\n  forall (t : @SOTerm o) disj ren,\n    wf_soterm t <=> wf_soterm (fo_change_bvars_alpha disj ren t).\nProof.\n  soterm_ind t as [ v ts ind | | op lbt ind ] Case; simpl; introv; tcsp.\n\n  - Case \"sovar\".\n    boolvar; subst; allsimpl; allrw @wf_sovar; allsimpl; tcsp.\n    split; intro k; introv i.\n    + rw in_map_iff in i; exrepnd; subst.\n      apply ind; auto.\n    + pose proof (k (fo_change_bvars_alpha disj ren t)) as h;\n        autodimp h hyp; [ rw in_map_iff; eexists; complete sp | ].\n      eapply ind in h; eauto.\n\n  - Case \"soterm\".\n    allrw @wf_soterm_iff; rw map_map; unfold compose.\n    split; intro k; repnd; dands.\n\n    + rw <- k0; apply eq_maps; introv i.\n      destruct x; simpl.\n      gen_fresh; auto.\n\n    + introv i.\n      rw in_map_iff in i; exrepnd.\n      destruct a; allsimpl; ginv.\n      pose proof (ind s l i1) as h.\n      rw <- h; auto.\n      eapply k; eauto.\n\n    + rw <- k0; apply eq_maps; introv i.\n      destruct x; simpl.\n      gen_fresh; auto.\n\n    + introv i.\n      pose proof (k (fresh_distinct_vars (length vs) (vs ++ disj ++ all_fo_vars t ++ foren_vars ren))\n                    (fo_change_bvars_alpha\n                       disj\n                       (mk_foren vs (fresh_distinct_vars (length vs) (vs ++ disj ++ all_fo_vars t ++ foren_vars ren)) ++ ren) t)) as h.\n      autodimp h hyp.\n      * rw in_map_iff; eexists; dands; eauto.\n      * eapply ind in h; eauto.\nQed.\n\nLemma wf_soterm_so_change_bvars_alpha {o} :\n  forall (t : @SOTerm o) disj ren,\n    wf_soterm t <=> wf_soterm (so_change_bvars_alpha disj ren t).\nProof.\n  soterm_ind t as [ v ts ind | | op lbt ind ] Case; simpl; introv; tcsp.\n\n  - Case \"sovar\".\n    split; intro k; apply wf_sovar; allsimpl; introv i; tcsp.\n    + rw in_map_iff in i; exrepnd; subst.\n      apply ind; auto.\n      eapply wf_sovar in k; eauto.\n    + rw @wf_sovar in k.\n      pose proof (k (so_change_bvars_alpha disj ren t)) as h;\n        autodimp h hyp; [ rw in_map_iff; eexists; complete sp | ].\n      eapply ind in h; eauto.\n\n  - Case \"soterm\".\n    allunfold @wf_soterm; allsimpl.\n    repeat (rw @wf_term_eq).\n    split; intro wf.\n    + inversion wf as [|?| ? ? imp e]; subst; clear wf.\n      constructor.\n      * introv i.\n        rw in_map_iff in i; exrepnd; subst.\n        rw in_map_iff in i1; exrepnd; subst.\n        destruct a0; allsimpl.\n        constructor.\n        rw @nt_wf_eq.\n        pose proof (imp (bterm l (soterm2nterm s))) as h.\n        autodimp h hyp; [rw in_map_iff; eexists; complete eauto|].\n        inversion h; subst.\n        eapply ind in i1.\n        rw <- i1; auto.\n        apply wf_term_eq; auto.\n      * rw <- e.\n        allrw map_map; unfold compose.\n        apply eq_maps; introv i.\n        destruct x; simpl; unfold num_bvars; simpl.\n        rw length_fresh_distinct_vars; auto.\n    + inversion wf as [|?| ? ? imp e]; subst; clear wf.\n      constructor.\n      * introv i; rw in_map_iff in i; exrepnd; subst.\n        destruct a; simpl.\n        constructor.\n        apply wf_term_eq.\n        pose proof (imp (bterm\n                           (fresh_distinct_vars (length l) (disj ++ all_fo_vars s ++ soren_vars ren))\n                           (soterm2nterm\n                              (so_change_bvars_alpha\n                                 disj\n                                 (mk_soren (vars2sovars l) (fresh_distinct_vars (length l) (disj ++ all_fo_vars s ++ soren_vars ren)) ++ ren) s)))) as h.\n        autodimp h hyp.\n        rw map_map; unfold compose.\n        rw in_map_iff; eexists; dands; eauto; simpl.\n        inversion h; subst.\n        allrw @nt_wf_eq.\n        eapply ind; eauto.\n      * rw <- e.\n        allrw map_map; unfold compose.\n        apply eq_maps; introv i.\n        destruct x; simpl; unfold num_bvars; simpl.\n        rw length_fresh_distinct_vars; auto.\nQed.\n\nLemma rename_sovar_foren2soren_fo :\n  forall ren v,\n    rename_sovar (foren2soren ren) (v, 0) = (rename_var ren v, 0).\nProof.\n  induction ren; introv; simpl; auto.\n  destruct a; simpl.\n  unfold var2sovar; rw rename_sovar_cons; rw rename_var_cons; boolvar; cpx.\nQed.\n\nLemma rename_sovar_foren2soren_so :\n  forall ren v n,\n    n > 0\n    -> rename_sovar (foren2soren ren) (v, n) = (v, n).\nProof.\n  induction ren; introv k; simpl; auto.\n  destruct a; simpl.\n  unfold var2sovar; rw rename_sovar_cons; boolvar; cpx; omega.\nQed.\n\nLemma sovar2var_rename_sovar :\n  forall ren v n,\n    (sovar2var (rename_sovar ren (v, n)), n)\n    = rename_sovar ren (v, n).\nProof.\n  induction ren; introv; simpl; tcsp.\n  destruct a; destruct s.\n  rw rename_sovar_cons; boolvar; simpl; cpx.\nQed.\n\nLemma sovars2vars_so_free_vars_subvars_all_fo_vars {o} :\n  forall (t : @SOTerm o),\n    subvars (sovars2vars (so_free_vars t)) (all_fo_vars t).\nProof.\n  soterm_ind t as [ v ts ind | | op lbt ind ] Case; simpl; introv; tcsp.\n\n  - Case \"sovar\".\n    apply subvars_cons_lr.\n    rw sovars2vars_flat_map.\n    apply subvars_flat_map2.\n    introv i; unfold compose; auto.\n\n  - Case \"soterm\".\n    rw sovars2vars_flat_map.\n    apply subvars_flat_map2; introv i.\n    destruct x; unfold compose; simpl.\n    apply ind in i.\n    allrw subvars_prop.\n    introv k.\n    apply in_sovars2vars in k; exrepnd.\n    apply in_remove_so_vars in k0; repnd.\n    rw in_map_iff in k0.\n\n    pose proof (i x) as h.\n    autodimp h hyp.\n    apply in_sovars2vars.\n    exists n; auto.\n    rw in_app_iff. sp.\nQed.\n\nLemma soren_find_app :\n  forall v ren1 ren2,\n    soren_find (ren1 ++ ren2) v\n    = match soren_find ren1 v with\n        | Some w => Some w\n        | None => soren_find ren2 v\n      end.\nProof.\n  induction ren1; simpl; sp.\n  destruct a0; destruct v; boolvar; cpx.\nQed.\n\nLemma soren_find_some :\n  forall (ren : soren) v n w,\n    soren_find ren (v,n) = Some w\n    -> {z : NVar & LIn ((v,n),z) ren # w = (z,n)}.\nProof.\n  induction ren; simpl; sp.\n  destruct a0; boolvar; subst; simpl in *; cpx.\n  - exists a; sp.\n  - discover; exrepnd; subst.\n    eexists; sp.\n  - discover; exrepnd; subst.\n    eexists; sp.\nQed.\n\nLemma soren_find_none :\n  forall (ren : soren) v,\n    soren_find ren v = None\n    -> !LIn v (soren_dom ren).\nProof.\n  induction ren; introv k; allsimpl; tcsp.\n  destruct a; destruct s; boolvar; cpx.\n  apply IHren in k.\n  apply not_over_or; sp.\nQed.\n\nLemma in_foren2soren :\n  forall ren v1 v2 n,\n    LIn (v1, n, v2) (foren2soren ren)\n    <=> (n = 0 # LIn (v1,v2) ren).\nProof.\n  induction ren; introv; simpl; split; intro k; tcsp; destruct a.\n  - unfold var2sovar in k.\n    dorn k; cpx.\n    apply IHren in k; sp.\n  - unfold var2sovar; repnd; subst; dorn k; cpx.\n    right; apply IHren; auto.\nQed.\n\nLemma in_mk_foren :\n  forall v1 v2 vs1 vs2,\n    LIn (v1,v2) (mk_foren vs1 vs2)\n    -> LIn v1 vs1 # LIn v2 vs2.\nProof.\n  induction vs1; introv i; allsimpl; tcsp.\n  destruct vs2; allsimpl; tcsp.\n  dorn i; cpx.\n  apply IHvs1 in i; repnd; sp.\nQed.\n\nLemma in_mk_soren :\n  forall v1 v2 vs1 vs2,\n    LIn (v1,v2) (mk_soren vs1 vs2)\n    -> LIn v1 vs1 # LIn v2 vs2.\nProof.\n  induction vs1; introv i; allsimpl; tcsp.\n  destruct vs2; allsimpl; tcsp.\n  dorn i; cpx.\n  apply IHvs1 in i; repnd; sp.\nQed.\n\nLemma in_foren_implies_in_vars :\n  forall v1 v2 ren,\n    LIn (v1,v2) ren -> LIn v1 (foren_vars ren) # LIn v2 (foren_vars ren).\nProof.\n  induction ren; introv i; allsimpl; tcsp.\n  destruct a; simpl.\n  dorn i; cpx.\nQed.\n\nLemma in_soren_implies_in_vars :\n  forall v1 v2 ren,\n    LIn (v1,v2) ren -> LIn (sovar2var v1) (soren_vars ren) # LIn v2 (soren_vars ren).\nProof.\n  induction ren; introv i; allsimpl; tcsp.\n  destruct a; destruct s; simpl.\n  dorn i; cpx.\nQed.\n\nLemma soren_dom_foren2soren :\n  forall ren : foren,\n    soren_dom (foren2soren ren) = vars2sovars (foren_dom ren).\nProof.\n  induction ren; simpl; auto.\n  destruct a; simpl; rw IHren; auto.\nQed.\n\nLemma rename_sovar_app_weak_l :\n  forall ren1 ren2 v,\n    !LIn v (soren_dom ren1)\n    -> rename_sovar (ren1 ++ ren2) v = rename_sovar ren2 v.\nProof.\n  induction ren1; introv ni; allsimpl; auto.\n  destruct a; destruct s; allsimpl.\n  rw not_over_or in ni; repnd.\n  rw rename_sovar_cons; boolvar; subst; sp.\nQed.\n\nLemma so_free_vars_so_change_bvars_alpha {o} :\n  forall (t : @SOTerm o) (disj : list NVar) (ren : soren),\n    so_free_vars (so_change_bvars_alpha disj ren t)\n    = map (rename_sovar ren) (so_free_vars t).\nProof.\n  soterm_ind t as [ v ts ind | | op lbt ind ] Case; simpl; introv; tcsp.\n\n  - Case \"sovar\".\n    apply eq_cons.\n    + rw map_length.\n      apply sovar2var_rename_sovar.\n    + rw map_flat_map.\n      rw flat_map_map.\n      unfold compose.\n      apply eq_flat_maps; introv i.\n      apply ind; auto.\n\n  - Case \"soterm\".\n    rw flat_map_map.\n    rw map_flat_map.\n    unfold compose.\n    apply eq_flat_maps; introv i.\n    destruct x; simpl.\n    pose proof (fresh_distinct_vars_spec (length l) (disj ++ all_fo_vars s ++ soren_vars ren))\n      as spec; simpl in spec; repnd.\n    remember (fresh_distinct_vars (length l) (disj ++ all_fo_vars s ++ soren_vars ren))\n      as f; clear Heqf.\n    erewrite ind; eauto; clear ind.\n    remember (so_free_vars s) as vars.\n    allrw disjoint_app_r; repnd.\n\n    assert (disjoint f (sovars2vars vars))\n      as d\n        by (subst; eapply subvars_disjoint_r;\n            [ complete apply sovars2vars_so_free_vars_subvars_all_fo_vars\n            | auto ]).\n\n    clear Heqvars i disj s lbt op o spec0 spec3 spec2.\n    revert ren l f d spec1 spec.\n    induction vars; simpl; introv d1 d2 len.\n    + allrw remove_so_vars_nil_r; simpl; auto.\n    + rw disjoint_cons_r in d1; repnd.\n      allrw remove_so_vars_cons_r; boolvar; simpl; auto.\n\n      * provefalse; clear IHvars.\n        allrw in_map_iff; exrepnd.\n        unfold rename_sovar in l1.\n        rw soren_find_app in l1.\n        remember (soren_find (mk_soren (vars2sovars l) f) a) as o;\n          symmetry in Heqo; destruct o; subst.\n\n        { unfold var2sovar in Heqo.\n          destruct a.\n          apply soren_find_some in Heqo; exrepnd; cpx.\n          apply in_mk_soren in Heqo1; repnd; GC.\n          rw in_map_iff in Heqo0; exrepnd; destruct a; allunfold var2sovar; cpx.\n          apply n; exists (nvar v); sp. }\n\n        { remember (soren_find ren a) as p;\n            symmetry in Heqp; destruct p; subst.\n\n          unfold var2sovar in Heqp.\n          destruct a.\n          apply soren_find_some in Heqp; exrepnd; cpx.\n          apply in_soren_implies_in_vars in Heqp1; sp.\n          apply d2 in l0; sp.\n\n          unfold sovar2var, var2sovar in d1; simpl in d1; sp. }\n\n      * provefalse; clear IHvars.\n        allrw in_map_iff; exrepnd; subst.\n        unfold sovar2var, var2sovar in d1; simpl in d1.\n        unfold rename_sovar in n.\n        rw soren_find_app in n.\n        remember (soren_find (mk_soren (vars2sovars l) f) (var2sovar a0)) as o;\n          symmetry in Heqo; destruct o; subst.\n\n        apply soren_find_some in Heqo; exrepnd; subst.\n        apply in_mk_soren in Heqo1; repnd.\n        apply n; clear n.\n        exists z; sp.\n\n        apply soren_find_none in Heqo.\n        rw soren_dom_mk_soren in Heqo; [|unfold vars2sovars; rw map_length; complete auto].\n        rw in_map_iff in Heqo; apply Heqo; exists a0; sp.\n\n      * apply eq_cons; [|apply IHvars; complete auto].\n        apply rename_sovar_app_weak_l.\n        rw soren_dom_mk_soren; auto.\n        unfold vars2sovars; rw map_length; auto.\nQed.\n\nLemma so_free_vars_fo_change_bvars_alpha {o} :\n  forall (t : @SOTerm o) (disj : list NVar) (ren : foren),\n    so_free_vars (fo_change_bvars_alpha disj ren t)\n    = map (rename_sovar (foren2soren ren)) (so_free_vars t).\nProof.\n  soterm_ind t as [ v ts ind | | op lbt ind ] Case; simpl; introv; tcsp.\n\n  - Case \"sovar\".\n    boolvar; subst; allsimpl.\n    + rw rename_sovar_foren2soren_fo; auto.\n    + rw map_length.\n      rw map_flat_map; rw flat_map_map; unfold compose.\n      rw rename_sovar_foren2soren_so;[|destruct ts; allsimpl; cpx; omega].\n      apply eq_cons; auto.\n      apply eq_flat_maps; sp.\n\n  - Case \"soterm\".\n    rw flat_map_map; rw map_flat_map; unfold compose.\n    apply eq_flat_maps; introv i.\n    destruct x; simpl.\n    gen_fresh.\n\n    erewrite ind; eauto; clear ind.\n    remember (so_free_vars s) as vars.\n    allrw disjoint_app_r; repnd.\n\n    assert (disjoint f (sovars2vars vars))\n      as d\n        by (subst; eapply subvars_disjoint_r;\n            [ complete apply sovars2vars_so_free_vars_subvars_all_fo_vars\n            | auto ]).\n\n    clear Heqvars i disj s lbt op o Heqf0 Heqf3 Heqf2 Heqf4.\n    revert ren l f d Heqf1 Heqf.\n    induction vars; simpl; introv d1 d2 len.\n    + allrw remove_so_vars_nil_r; simpl; auto.\n    + rw disjoint_cons_r in d1; repnd.\n      allrw remove_so_vars_cons_r; boolvar; simpl; auto.\n\n      * provefalse; clear IHvars.\n        allrw in_map_iff; exrepnd.\n        unfold rename_sovar in l1.\n        rw foren2soren_app in l1.\n        rw soren_find_app in l1.\n        remember (soren_find (foren2soren (mk_foren l f)) a) as o;\n          symmetry in Heqo; destruct o; subst.\n\n        {\n          unfold var2sovar in Heqo.\n          destruct a.\n          apply soren_find_some in Heqo; exrepnd; cpx.\n          apply in_foren2soren in Heqo1; repnd; GC.\n          apply in_mk_foren in Heqo1; repnd; GC; allsimpl.\n          destruct n; allunfold var2sovar; cpx.\n          eexists; eauto.\n        }\n\n        {\n          remember (soren_find (foren2soren ren) a) as p;\n          symmetry in Heqp; destruct p; subst.\n\n          {\n            unfold var2sovar in Heqp.\n            destruct a.\n            apply soren_find_some in Heqp; exrepnd; cpx.\n            apply in_foren2soren in Heqp1; repnd; allsimpl; GC.\n            apply d2 in l0; sp.\n            apply in_foren_implies_in_vars in Heqp1; sp.\n          }\n\n          {\n            unfold sovar2var, var2sovar in d1; simpl in d1; sp.\n          }\n        }\n\n      * provefalse; clear IHvars.\n        allrw in_map_iff; exrepnd; subst.\n        unfold sovar2var, var2sovar in d1; allsimpl.\n        unfold rename_sovar in n.\n        rw foren2soren_app in n.\n        rw soren_find_app in n.\n        remember (soren_find (foren2soren (mk_foren l f)) (var2sovar a0)) as o;\n          symmetry in Heqo; destruct o; subst.\n\n        {\n          apply soren_find_some in Heqo; exrepnd; subst.\n          apply in_foren2soren in Heqo1; repnd; GC.\n          apply in_mk_foren in Heqo1; repnd; GC.\n          destruct n.\n          eexists; eauto.\n        }\n\n        {\n          apply soren_find_none in Heqo.\n          rw soren_dom_foren2soren in Heqo.\n          rw foren_dom_mk_foren in Heqo; auto.\n          rw in_map_iff in Heqo; destruct Heqo; eexists; eauto.\n        }\n\n      * apply eq_cons; [|apply IHvars; complete auto].\n        rw foren2soren_app.\n        apply rename_sovar_app_weak_l.\n        rw soren_dom_foren2soren.\n        rw foren_dom_mk_foren; auto.\nQed.\n\nLemma map_rename_sovar_nil :\n  forall vs, map (rename_sovar []) vs = vs.\nProof.\n  induction vs; simpl; auto.\n  rw IHvs; auto.\nQed.\n\nLemma disjoint_bound_vars_in_sk {o} :\n  forall (sk : @sosub_kind o) vs1 vs2,\n    subvars vs1 vs2\n    -> disjoint vs1 (bound_vars_in_sk (sk_change_bvars_in_alpha vs2 sk)).\nProof.\n  destruct sk; simpl; introv sv.\n  pose proof (change_bvars_alpha_spec n vs2) as h; simpl in h; repnd.\n  eapply subvars_disjoint_l; eauto.\nQed.\n\nLemma disjoint_bound_vars_in_sosub {o} :\n  forall (sub : @SOSub o) vs1 vs2,\n    subvars vs1 vs2\n    -> disjoint vs1 (bound_vars_in_sosub (sosub_change_bvars_in_alpha vs2 sub)).\nProof.\n  induction sub; introv sv; simpl; auto.\n  destruct a; simpl.\n  rw disjoint_app_r; dands; auto.\n  apply disjoint_bound_vars_in_sk; auto.\nQed.\n\nLemma disjoint_bound_vars_sk {o} :\n  forall (sk : @sosub_kind o) vs1 vs2,\n    subvars vs1 vs2\n    -> disjoint vs1 (bound_vars_sk (sk_change_bvars_alpha vs2 sk)).\nProof.\n  destruct sk; simpl; introv sv.\n  pose proof (change_bvars_alpha_spec n vs2) as h; simpl in h; repnd.\n  match goal with\n    | [ |- context[fresh_distinct_vars ?a ?b] ] =>\n      remember (fresh_distinct_vars a b) as f\n  end.\n  apply fresh_distinct_vars_spec1 in Heqf; repnd.\n  allrw disjoint_app_r; repnd; dands; auto.\n  - eapply subvars_disjoint_l; eauto; apply disjoint_sym; auto.\n  - rw @boundvars_lsubst_aux_vars; auto.\n    eapply subvars_disjoint_l; eauto.\nQed.\n\nLemma disjoint_bound_vars_sosub {o} :\n  forall (sub : @SOSub o) vs1 vs2,\n    subvars vs1 vs2\n    -> disjoint vs1 (bound_vars_sosub (sosub_change_bvars_alpha vs2 sub)).\nProof.\n  induction sub; introv sv; simpl; auto.\n  destruct a; simpl.\n  rw disjoint_app_r; dands; auto.\n  apply disjoint_bound_vars_sk; auto.\nQed.\n\nLemma alphaeq_preserves_isprog_vars {o} :\n  forall (t1 t2 : @NTerm o) vs,\n    alpha_eq t1 t2\n    -> isprog_vars vs t1\n    -> isprog_vars vs t2.\nProof.\n  introv aeq prog.\n  pose proof (alphaeq_preserves_wf t1 t2 aeq) as h.\n  pose proof (alphaeq_preserves_free_vars t1 t2 aeq) as k.\n  allrw @isprog_vars_eq; repnd.\n  rw h; rw <- k; dands; auto.\nQed.\n\nLemma isprog_vars_change_bvars_alpha {o} :\n  forall (t : @NTerm o) l vs,\n    isprog_vars l t\n    <=> isprog_vars l (change_bvars_alpha vs t).\nProof.\n  introv; split; intro prog.\n  - pose proof (change_bvars_alpha_spec t vs) as h; simpl in h; repnd.\n    eapply alphaeq_preserves_isprog_vars;[|complete eauto];auto.\n  - pose proof (change_bvars_alpha_spec t vs) as h; simpl in h; repnd.\n    eapply alphaeq_preserves_isprog_vars;[|complete eauto];auto.\n    apply alpha_eq_sym; auto.\nQed.\n\nLemma remove_nvars_comp :\n  forall l1 l2 l3,\n    remove_nvars l1 (remove_nvars l2 l3)\n    = remove_nvars l1 (remove_nvars (remove_nvars l1 l2) l3).\nProof.\n  introv.\n  allrw remove_nvars_app_l.\n  induction l3.\n  - allrw remove_nvars_nil_r; auto.\n  - allrw remove_nvars_cons_r; boolvar; tcsp;\n    allrw in_app_iff; allrw not_over_or; repnd;\n    allrw in_remove_nvars; tcsp.\n    + dorn Heqb; provefalse; sp.\n    + rw IHl3; auto.\nQed.\n\nLemma remove_nvars_if_eqvars :\n  forall vs vs1 vs2,\n    eqvars vs1 vs2\n    -> remove_nvars vs1 vs = remove_nvars vs2 vs.\nProof.\n  induction vs; introv eqv; allsimpl.\n  - allrw remove_nvars_nil_r; auto.\n  - allrw remove_nvars_cons_r; boolvar; tcsp.\n    + rw eqvars_prop in eqv; apply eqv in Heqb; sp.\n    + rw eqvars_prop in eqv; apply eqv in Heqb0; sp.\n    + apply IHvs in eqv; rw eqv; auto.\nQed.\n\nLemma eqvars_remove_nvars_app :\n  forall vs1 vs2, subvars vs1 vs2 -> eqvars ((remove_nvars vs1 vs2) ++ vs1) vs2.\nProof.\n  introv sv; rw eqvars_prop; introv; rw in_app_iff; rw in_remove_nvars;\n  split; intro k; tcsp.\n  - dorn k; tcsp.\n    rw subvars_prop in sv; sp.\n  - destruct (in_deq NVar deq_nvar x vs1); tcsp.\nQed.\n\nLemma free_vars_lsubst_aux_var_ren {o} :\n  forall (t : @NTerm o) vs1 vs2 vs,\n    disjoint vs2 (free_vars t)\n    -> disjoint vs2 (bound_vars t)\n    -> length vs1 = length vs2\n    -> remove_nvars (vs2 ++ vs) (free_vars (lsubst_aux t (var_ren vs1 vs2)))\n       = remove_nvars (vs1 ++ vs) (free_vars t).\nProof.\n  nterm_ind t as [v|f induction|op bs ind] Case; introv disj1 disj2 len; allsimpl; auto.\n\n  - Case \"vterm\".\n    rw disjoint_singleton_r in disj1.\n    remember (sub_find (var_ren vs1 vs2) v) as f; symmetry in Heqf; destruct f; simpl.\n    + apply sub_find_some in Heqf.\n      apply in_var_ren in Heqf; exrepnd; subst; simpl.\n      allrw remove_nvars_cons_r; boolvar; tcsp;\n      allrw remove_nvars_nil_r; auto;\n      provefalse; allrw in_app_iff; allrw not_over_or; tcsp.\n\n    + apply sub_find_none2 in Heqf.\n      rw @dom_sub_var_ren in Heqf; auto.\n      allrw remove_nvars_cons_r; boolvar; tcsp;\n      allrw remove_nvars_nil_r; auto;\n      provefalse; allrw in_app_iff; allrw not_over_or; tcsp.\n\n  - Case \"sterm\".\n    allrw remove_nvars_nil_r; auto.\n\n  - Case \"oterm\".\n    rw flat_map_map; unfold compose.\n    allrw remove_nvars_flat_map; unfold compose.\n    apply eq_flat_maps; introv i.\n    destruct x; simpl.\n    allrw remove_nvars_app_l.\n\n    pose proof (@sub_filter_var_ren_implies o vs1 vs2 l) as h; exrepnd.\n    rw h0.\n\n    autodimp h1 hyp.\n    assert (eqvars ((vs1 ++ vs) ++ l) ((vs3 ++ vs) ++ l)) as k.\n    {\n      allrw eqvars_prop; introv; allrw in_app_iff; split; intro h; dorn h; tcsp.\n      {\n        destruct (in_deq NVar deq_nvar x l); tcsp.\n        rw h2; left; rw in_remove_nvars; sp.\n      }\n      {\n        rw h2 in h; rw in_remove_nvars in h; sp.\n      }\n    }\n\n    apply remove_nvars_if_eqvars with (vs := free_vars n) in k; rw k; clear k.\n    applydup eqvars_remove_nvars_app in h3.\n    assert (eqvars (((remove_nvars vs4 vs2 ++ vs4) ++ vs) ++ l) ((vs2 ++ vs) ++ l))\n      as eqv by (apply eqvars_app; auto; apply eqvars_app; auto).\n\n    apply remove_nvars_if_eqvars with (vs := free_vars (lsubst_aux n (var_ren vs3 vs4)))\n      in eqv; rw <- eqv; clear eqv.\n\n    rw <- app_assoc.\n    rw <- app_assoc.\n    rw <- remove_nvars_app_l.\n    rw <- app_assoc.\n    pose proof (ind n l i vs3 vs4 (vs ++ l)) as h; repeat (autodimp h hyp).\n\n    + allrw disjoint_flat_map_r.\n      applydup disj1 in i; applydup disj2 in i; allsimpl.\n      allrw disjoint_app_r; repnd.\n      introv a b.\n      rw subvars_prop in h3; apply h3 in a; clear h3.\n      applydup i0 in a.\n      applydup i2 in a.\n      rw in_remove_nvars in a0; destruct a0; sp.\n\n    + allrw disjoint_flat_map_r.\n      apply disj2 in i; simpl in i.\n      rw disjoint_app_r in i; repnd.\n      eapply subvars_disjoint_l; eauto.\n\n    + rw h.\n      assert (disjoint\n                (remove_nvars vs4 vs2)\n                (remove_nvars (vs3 ++ vs ++ l) (free_vars n))) as disj.\n\n      * introv a b.\n        allrw in_remove_nvars; repnd; allrw in_app_iff; allrw not_over_or; repnd.\n        allrw disjoint_flat_map_r.\n        apply disj1 in i; simpl in i.\n        apply i in a0; rw in_remove_nvars in a0; sp.\n\n      * apply disjoint_sym in disj.\n        apply remove_nvars_unchanged in disj.\n        rw disj; auto.\nQed.\n\nLemma free_vars_change_bvars_alpha {o} :\n  forall (t : @NTerm o) vs,\n    free_vars (change_bvars_alpha vs t) = free_vars t.\nProof.\n  nterm_ind t as [v|f ind|op bs ind] Case; introv; simpl; auto.\n  rw flat_map_map; unfold compose; apply eq_flat_maps; introv i.\n  destruct x; simpl.\n  match goal with\n    | [ |- context[fresh_distinct_vars ?a ?b] ] =>\n      remember (fresh_distinct_vars a b) as f\n  end.\n  apply fresh_distinct_vars_spec1 in Heqf; repnd.\n  allrw disjoint_app_r; repnd.\n  pose proof (ind n l i vs) as h.\n\n  pose proof (free_vars_lsubst_aux_var_ren (change_bvars_alpha vs n) l f []) as k.\n  repeat (autodimp k hyp).\n  allrw app_nil_r.\n  rw k; rw h; auto.\nQed.\n\nLemma isprog_sk_change_bvars_alpha {o} :\n  forall (sk : @sosub_kind o) vs,\n    isprog_sk sk\n    <=> isprog_sk (sk_change_bvars_alpha vs sk).\nProof.\n  destruct sk; introv; simpl.\n  match goal with\n    | [ |- context[fresh_distinct_vars ?a ?b] ] =>\n      remember (fresh_distinct_vars a b) as f\n  end.\n  apply fresh_distinct_vars_spec1 in Heqf; repnd.\n  allrw disjoint_app_r; repnd.\n  allrw @isprog_vars_eq.\n  pose proof (@allvars_combine o l f) as h.\n  eapply lsubst_aux_allvars_wf_iff in h; rw <- h; clear h.\n  pose proof (change_bvars_alpha_spec n vs) as h; simpl in h; repnd.\n  applydup @alphaeq_preserves_wf in h; rw h1.\n  pose proof (eqvars_free_vars_disjoint_aux\n                (change_bvars_alpha vs n)\n                (var_ren l f)) as e.\n  autodimp e hyp.\n  - introv i.\n    apply in_var_ren in i; exrepnd; subst; allsimpl.\n    rw disjoint_singleton_l; intro k.\n    apply Heqf1 in i1; auto.\n  - split; intro k; dands; repnd; auto.\n    + rw subvars_prop; introv i.\n      rw eqvars_prop in e; apply e in i; clear e.\n      rw in_app_iff in i.\n      rw in_remove_nvars in i.\n      dorn i; repnd.\n      * rw @dom_sub_var_ren in i; auto.\n        applydup @alphaeq_preserves_free_vars in h.\n        rw <- h2 in i0.\n        rw subvars_prop in k0.\n        apply k0 in i0; sp.\n      * apply in_sub_free_vars in i; exrepnd.\n        apply in_sub_keep_first in i0; repnd.\n        apply sub_find_some in i2.\n        apply in_var_ren in i2; exrepnd; subst; allsimpl.\n        dorn i1; subst; sp.\n    + eapply subvars_eqvars in k0;[|exact e]; clear e.\n      applydup @alphaeq_preserves_free_vars in h.\n      rw <- h2 in k0; clear h2.\n      rw subvars_app_l in k0; repnd.\n      rw subvars_remove_nvars in k1.\n      rw @dom_sub_var_ren in k1; auto.\n      rw @free_vars_change_bvars_alpha in Heqf3.\n      rw subvars_prop; introv i.\n      rw subvars_prop in k1; applydup k1 in i; rw in_app_iff in i0; dorn i0; auto.\n      apply Heqf3 in i0; sp.\nQed.\n\nLemma sosub_prog_change_bvars_in_alpha {o} :\n  forall (sub : @SOSub o) vs,\n    sosub_prog sub\n    <=> sosub_prog (sosub_change_bvars_in_alpha vs sub).\nProof.\n  induction sub; introv; split; intro prog; allsimpl; auto;\n  destruct a; destruct s;\n  allrw @sosub_prog_cons; repnd; dands.\n  - apply isprog_vars_change_bvars_alpha; auto.\n  - apply IHsub; auto.\n  - apply isprog_vars_change_bvars_alpha in prog0; auto.\n  - apply IHsub in prog; auto.\nQed.\n\nLemma sosub_prog_change_bvars_alpha {o} :\n  forall (sub : @SOSub o) vs,\n    sosub_prog sub\n    <=> sosub_prog (sosub_change_bvars_alpha vs sub).\nProof.\n  induction sub; introv; split; intro prog; allsimpl; auto;\n  destruct a; destruct s;\n  allrw @sosub_prog_cons2; repnd; dands.\n  - apply isprog_sk_change_bvars_alpha; auto.\n  - apply IHsub; auto.\n  - apply isprog_sk_change_bvars_alpha in prog0; auto.\n  - apply IHsub in prog; auto.\nQed.\n\nLemma sodom_sosub_change_bvars_in_alpha {o} :\n  forall (sub : @SOSub o) vs,\n    sodom (sosub_change_bvars_in_alpha vs sub) = sodom sub.\nProof.\n  induction sub; simpl; introv; auto.\n  destruct a; destruct s.\n  unfold sk_change_bvars_alpha.\n  rw IHsub; auto.\nQed.\n\nLemma sodom_sosub_change_bvars_alpha {o} :\n  forall (sub : @SOSub o) vs,\n    sodom (sosub_change_bvars_alpha vs sub) = sodom sub.\nProof.\n  induction sub; simpl; introv; auto.\n  destruct a; destruct s.\n  rw IHsub; apply eq_cons; auto.\n  unfold sk_change_bvars_alpha.\n  simpl.\n  match goal with\n    | [ |- context[fresh_distinct_vars ?a ?b] ] =>\n      remember (fresh_distinct_vars a b) as f\n  end.\n  apply fresh_distinct_vars_spec1 in Heqf; repnd; sp.\nQed.\n\nLemma isprogram_sosub1 {p} :\n  forall (t : SOTerm) (sub : @SOSub p),\n    wf_soterm t\n    -> sosub_prog sub\n    -> let u := sosub sub t\n       in wf_term u\n          # subvars\n              (free_vars u)\n              (sovars2vars (remove_so_vars (sodom sub) (so_free_vars t))).\nProof.\n  introv wf prog; simpl.\n  unfold sosub.\n  boolvar; dands.\n\n  - apply isprogram_sosub_aux1; auto.\n\n  - apply isprogram_sosub_aux1; auto.\n\n  - apply isprogram_sosub_aux1; auto.\n    apply sosub_prog_change_bvars_alpha; auto.\n\n  - pose proof (isprogram_sosub_aux1\n                  t\n                  (sosub_change_bvars_alpha\n                     (allvars_range_sosub sub ++ all_fo_vars t) sub))\n      as h; simpl in h.\n    repeat (autodimp h hyp); auto.\n    + apply sosub_prog_change_bvars_alpha; auto.\n    + repnd; rw @sodom_sosub_change_bvars_alpha in h; auto.\n\n  - pose proof (isprogram_sosub_aux1\n                  (fo_change_bvars_alpha (free_vars_sosub sub ++ all_fo_vars t) [] t)\n                  sub) as h.\n    repeat (autodimp h hyp).\n    + apply wf_soterm_fo_change_bvars_alpha; auto.\n    + simpl in h; repnd; auto.\n\n  - pose proof (isprogram_sosub_aux1\n                  (fo_change_bvars_alpha (free_vars_sosub sub ++ all_fo_vars t) [] t)\n                  sub) as h.\n    repeat (autodimp h hyp).\n    + apply wf_soterm_fo_change_bvars_alpha; auto.\n    + simpl in h; repnd; auto.\n      rw @so_free_vars_fo_change_bvars_alpha in h; simpl in h.\n      rw map_rename_sovar_nil in h; auto.\n\n  - apply isprogram_sosub_aux1; auto.\n    + rw <- @wf_soterm_fo_change_bvars_alpha; auto.\n    + apply sosub_prog_change_bvars_alpha; auto.\n\n  - pose proof (isprogram_sosub_aux1\n                  (fo_change_bvars_alpha (free_vars_sosub sub ++ all_fo_vars t) [] t)\n                  (sosub_change_bvars_alpha\n                     (allvars_range_sosub sub\n                      ++ all_fo_vars\n                           (fo_change_bvars_alpha\n                              (free_vars_sosub sub ++ all_fo_vars t) [] t)) sub))\n      as h.\n    repeat (autodimp h hyp).\n    + rw <- @wf_soterm_fo_change_bvars_alpha; auto.\n    + apply sosub_prog_change_bvars_alpha; auto.\n    + simpl in h; repnd.\n      rw @sodom_sosub_change_bvars_alpha in h; auto.\n      rw @so_free_vars_fo_change_bvars_alpha in h; simpl in h.\n      rw map_rename_sovar_nil in h; auto.\nQed.\n\nLemma subsovars_cons_l :\n  forall v vs1 vs2,\n    subsovars (v :: vs1) vs2 <=> LIn v vs2 # subsovars vs1 vs2.\nProof.\n  sp; allrw subsovars_eq.\n  apply subset_cons_l.\nQed.\n\nLemma subsovars_app_l :\n  forall vs1 vs2 vs,\n    subsovars (vs1 ++ vs2) vs <=> (subsovars vs1 vs # subsovars vs2 vs).\nProof.\n  introv; allrw subsovars_prop; split; intro k; repnd; dands.\n  - introv i; apply k; rw in_app_iff; sp.\n  - introv i; apply k; rw in_app_iff; sp.\n  - introv i; rw in_app_iff in i; dorn i.\n    + apply k0; sp.\n    + apply k; sp.\nQed.\n\nLemma subsovars_app_weak_r1 :\n  forall vs1 vs2 vs,\n    subsovars vs vs1\n    -> subsovars vs (vs1 ++ vs2).\nProof.\n  introv sv; allrw subsovars_prop; introv i.\n  rw in_app_iff; left; sp.\nQed.\n\nLemma subsovars_app_weak_r2 :\n  forall vs1 vs2 vs,\n    subsovars vs vs2\n    -> subsovars vs (vs1 ++ vs2).\nProof.\n  introv sv; allrw subsovars_prop; introv i.\n  rw in_app_iff; right; sp.\nQed.\n\nLemma remove_so_vars_if_subsovars {o} :\n  forall vs (sub : @SOSub o),\n    subsovars vs (sodom sub)\n    -> remove_so_vars (sodom sub) vs = [].\nProof.\n  induction vs; introv sv; allsimpl.\n  - rw remove_so_vars_nil_r; auto.\n  - rw subsovars_cons_l in sv; repnd.\n    rw remove_so_vars_cons_r; boolvar; sp.\nQed.\n\nLemma isprogram_sosub {o} :\n  forall (t : @SOTerm o) sub,\n    wf_soterm t\n    -> subsovars (so_free_vars t) (sodom sub)\n    -> sosub_prog sub\n    -> isprogram (sosub sub t).\nProof.\n  introv wf sv prog.\n  pose proof (isprogram_sosub1 t sub wf prog) as h; simpl in h; repnd.\n  rw @remove_so_vars_if_subsovars in h; auto.\n  simpl in h; rw subvars_nil_r in h.\n  constructor; auto.\n  apply nt_wf_eq; auto.\nQed.\n\nLemma subvars_sovars2vars_prop1 :\n  forall vs1 vs2,\n    subsovars vs1 vs2\n    -> subvars (sovars2vars vs1) (sovars2vars vs2).\nProof.\n  introv k.\n  rw subvars_prop; introv i.\n  allrw in_sovars2vars; exrepnd.\n  rw subsovars_prop in k.\n  apply k in i0.\n  eexists; eauto.\nQed.\n\nLemma subsovars_remove_so_vars :\n  forall vs1 vs2,\n    subsovars (remove_so_vars vs1 vs2) vs2.\nProof.\n  introv; rw subsovars_prop; introv i.\n  rw in_remove_so_vars in i; sp.\nQed.\n\nLemma sovars2vars_sodom_combine {o} :\n  forall (sks : list (@sosub_kind o)) vs,\n    length vs = length sks\n    -> sovars2vars (sodom (combine vs sks)) = vs.\nProof.\n  induction sks; destruct vs; introv len; allsimpl; cpx.\n  destruct a; allsimpl.\n  apply eq_cons; auto.\nQed.\n\nDefinition selectsobt {p} (bts: list SOBTerm) (n:nat) : @SOBTerm p :=\n  nth n bts (sobterm [] mk_soaxiom).\n\nLemma selectbt_map_sosub_b_aux {o} :\n  forall (bs : list (@SOBTerm o)) sub n,\n    selectbt (map (sosub_b_aux sub) bs) n\n    = sosub_b_aux sub (selectsobt bs n).\nProof.\n  induction bs; simpl; introv.\n  - unfold selectbt, selectsobt; simpl; destruct n; simpl; auto.\n  - unfold selectbt, selectsobt; simpl; destruct n; auto.\n    apply IHbs.\nQed.\n\nLemma selectsobt_as_select {o} :\n  forall (bs : list (@SOBTerm o)) n,\n    n < length bs\n    -> Some (selectsobt bs n) = select n bs.\nProof.\n  introv h.\n  unfold selectsobt.\n  rw <- @nth_select1; auto.\nQed.\n\nDefinition so_dom {o} (s : @SOSub o) : list NVar :=\n  map (fun x => fst x) s.\n\nDefinition so_range {o} (s : @SOSub o) : list sosub_kind :=\n  map (fun x => snd x) s.\n\nLemma length_so_dom {o} :\n  forall (sub : @SOSub o),\n    length (so_dom sub) = length sub.\nProof.\n  induction sub; allsimpl; sp.\nQed.\n\nLemma length_so_range {o} :\n  forall (sub : @SOSub o),\n    length (so_range sub) = length sub.\nProof.\n  induction sub; allsimpl; sp.\nQed.\n\nLemma sovars2vars_sodom_is_so_dom {o} :\n  forall (sub : @SOSub o),\n    sovars2vars (sodom sub) = so_dom sub.\nProof.\n  induction sub; allsimpl; tcsp.\n  destruct a; destruct s; simpl; rw IHsub; auto.\nQed.\n\nLemma sovars2vars_app :\n  forall vs1 vs2,\n    sovars2vars (vs1 ++ vs2) = sovars2vars vs1 ++ sovars2vars vs2.\nProof.\n  unfold sovars2vars; introv; rw map_app; sp.\nQed.\n\nLemma sovars2vars_vars2sovars :\n  forall vs, sovars2vars (vars2sovars vs) = vs.\nProof.\n  induction vs; simpl; auto.\n  rw IHvs; sp.\nQed.\n\nLemma in_vars2sovars :\n  forall v n vs,\n    LIn (v,n) (vars2sovars vs)\n    <=> (LIn v vs # n = 0).\nProof.\n  introv; rw in_map_iff; unfold var2sovar; split; intro k; exrepnd; cpx; subst.\n  eexists; eauto.\nQed.\n\nLemma length_vars2sovars :\n  forall vs, length (vars2sovars vs) = length vs.\nProof.\n  introv; unfold vars2sovars; rw map_length; 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/sovar.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.5660185351961013, "lm_q1q2_score": 0.2896410830301741}}
{"text": "(** * Notation and Pretty printing.\n\nPrograms are essentially just values of type [code] and one can\nconstruct these objects by applying the appropriate\nconstructors. Often these constructors are designed so that the\nunderlying program construct is _correct by construction_ --- for\nexample array indexing requires a proof that the index is smaller than\nthe array bound. This is achieved by there being additional parameters\nto the constructor which are proofs of safety.\n\nCreating such objects explicitly by applying constructors can be\npainful. This module gives a set of Notations that makes the surface\nsyntax of these code values palatable to the user.\n\n*)\n\nRequire Import NArith.\nRequire Import Nat.\nRequire Import Verse.Ast.\nRequire Import Verse.Language.Types.\nRequire Import Verse.TypeSystem.\nImport List.ListNotations.\nRequire        Vector.\nImport         Vector.VectorNotations.\nRequire Import Verse.Nibble.\n\nSet Implicit Arguments.\n\n\n(* DEVELOPER notes.\n\nWe can avoid all type classes and move over to canonical structures if\nthat is what we are going to use in the rest of the code\n\n*)\n\n\n(** * Types embeddable as expressions\n\nFor program variables [v : VariableT] and a verse type [ty] recall\nthat [expr v ty] type captures expressions in verse. We would like to\nconsider other types like, [nat] constants, program variables [x : v ty]\netc, to be considered as verse expressions. We do this in two stages.\n\n- We have the class [EXPR] that declares instances which can be\n  converted to [expr]. Some of the instances of this class are [v ty],\n  [nat]'s and [expr]'s themselves.\n\n- We use infix operators like [+] etc to combine instances of [EXPR]\n  to get new expressions. Thus we can embed many of the common types\n  as expressions.\n\n\n*)\n\nSection Embedding.\n  Variable v  : Variables.U verse_type_system.\n  Variable ty : type direct.\n\n  (** Class of all types [t] that can be converted into expressions *)\n  Class EXPR  t := toExpr  : t -> expr v (existT _ _ ty).\n\n\n  (** *** Instances of [EXPR]\n   *)\n\n  Global Instance expr_to_expr   : EXPR (expr  v (existT _ _ ty))  := @id _.\n  Global Instance v_to_exp       : EXPR (v (existT _ _ ty))        := fun x => valueOf (var x).\n  Global Instance lexp_to_exp    : EXPR (lexpr v (existT _ _ ty))  := valueOf (ty := existT _ _ ty).\n  Global Instance const_to_expr  : EXPR (const ty)    := cval (ty:=ty).\n  Global Instance nat_to_exp     : EXPR nat := fun n => cval (natToConst ty n).\n\n  Global Instance N_to_exp       : EXPR N := fun n => cval (NToConst ty n).\n\n  (** Class similar to [EXPR] but creates l-expressions *)\n  Class LEXPR t := toLexpr : t -> lexpr v (existT _ _ ty).\n\n  Global Instance lexpr_to_lexpr : LEXPR (lexpr v (existT _ _ ty)) := @id _.\n  Global Instance v_to_lexp      : LEXPR (v (existT _ _ ty))       := var (ty:=ty).\n\n\n\n  (** We now define helper functions that \"lift\" verse operators to\n      work with instances of [EXPR].  *)\n  Section Operators.\n\n    Variable bop : operator verse_type_system ty 2.\n    Variable uop : operator verse_type_system ty 1.\n\n    Variable t      : Type.\n    Variable lhs    : t.\n    Variable class  : LEXPR t.\n\n\n    Variable t1 t2 : Type.\n    Variable e1 : t1.\n    Variable e2 : t2.\n    Variable class1 : EXPR t1.\n    Variable class2 : EXPR t2.\n\n    Definition assignStmt : statement v\n      := existT _  _ (assign  (toLexpr lhs)  (toExpr e1)).\n\n     Definition moveStmt (x : v (existT _ _ ty)) : statement v\n      := existT _ _ (Ast.moveTo (toLexpr lhs) x).\n\n    (** Applies the binary operator [o] to two values [e1] and [e2]\n        both of which are convertable to expressions.  *)\n    Definition binOpApp\n      := binOp bop (toExpr e1) (toExpr e2).\n\n    (** Update instruction which uses an input binary operator to\n        update the l-expression [x].  *)\n\n    Definition binOpUpdate : statement v\n      := existT _ _ (binopUpdate (toLexpr lhs) bop (toExpr e1)).\n\n\n    (** Applies the unary operator [o] to the value [e] that is\n        convertible to expression. *)\n    Definition uniOpApp\n    :=  uniOp uop (toExpr e1).\n\n    (** Update a given lexpression using the given unary operator\n        [o]. *)\n    Definition uniOpUpdate : statement v\n      := existT _ _ (uniopUpdate (toLexpr lhs) uop).\n\n    End Operators.\nEnd Embedding.\n\nInstance bvec_to_expr v sz : EXPR v (word sz) (BWord sz)\n  := { toExpr := fun v : const (word sz) => cval v }.\nInstance nibbles_to_exp v sz  : EXPR v (word sz) (Nibble.bytes (2^sz))\n  := { toExpr := fun nibs => toExpr (toBv nibs) }.\n\n\nArguments assignStmt [v ty t] lhs [class t1] e1 {class1}.\nArguments moveStmt [v ty t] lhs [class] x.\nArguments binOpApp [v ty] bop  [t1 t2] e1 e2  {class1 class2}.\nArguments binOpUpdate [v ty] bop [t] lhs [class] [t1] e1 {class1} .\nArguments uniOpApp [v ty] uop  [t1] e1 {class1}.\nArguments uniOpUpdate [v ty] uop [t] lhs {class}.\n\n\n(** * Indexing types.\n\nOften we want to index elements withing a bound. The class [INDEXING]\ncaptures such types. Array variables are usual objects but we have an\ninstance for generic indexing functions. The indexing functions\ngive\n\n*)\n\nClass INDEXING (Ix : Set)(result : Type) t\n  := idx : t -> Ix  -> result.\n\nInstance indexing_by_function b t : INDEXING {i | i < b} t (forall i : nat, i < b -> t)\n  := fun f ix => match ix with\n              | @exist _ _ i pf => f i pf\n              end.\n\n\nInstance array_indexing v ty b e : INDEXING {i | i < b}\n                                            (lexpr v (existT _ _ ty))\n                                            (v (existT _ _ (array b e ty)))\n  := fun a ix =>  deref a ix.\n\nInstance vector_indexing A b : INDEXING {i | i < b} A (Vector.t A b) :=\n  fun va ix => Vector.nth_order va (proj2_sig ix).\n(*\nInstance var_array (v : Variables.U verse_type_system) ty b : INDEXING {i | i < b}\n                                                                       (v ty)\n                                                                       (Vector.t (v ty) b)\n  := fun va ix => Vector.nth_order va (proj2_sig ix).\n*)\nDeclare Scope verse_scope.\nDelimit Scope verse_scope with verse.\n\nClass AST_maps (A B : Type) := { CODE : A -> list B }.\n\n#[export] Instance code_id (v : VariableT)\n  : AST_maps (code v) (statement (ts := verse_type_system) v)\n  := { CODE := id }.\n\n#[export] Instance code_repeat (v : VariableT)\n  : AST_maps (code v) (repeated (code (ts := verse_type_system) v))\n  := { CODE := fun C => [ repeat 1 C ]%list }.\n\nDeclare Custom Entry verse.\n(* Notation \"'[code|' e  '|]'\" := e (e custom verse). *)\nNotation \"A [ N ] \" := (idx A (@exist _ _ N%nat _)) (in custom verse at level 29, N constr).\nNotation \"[verse| e |]\" := e (e custom verse).\nNotation \"[code| x ; .. ; y |]\":= (CODE (cons x .. (cons y nil) ..)) (x custom verse, y custom verse,\n                                      format \"[code| '[    '  '//' x ; '//' .. ; '//' y '//' ']' '//' '|]'\"\n                                    ).\nNotation \"x\" := x (in custom verse at level 0, x global).\nNotation \"( x )\" := x  (in custom verse at level 0).\nNotation \"` x `\" := x  (in custom verse at level 0, x constr, format \"` x `\").\n\n\n(** Notation for operators.\n\nWe more or less follow the C convention for operator and their\nprecedence except for the operator [^] which has a predefined\nprecedence in Coq.\n\n*)\n\n\nNotation \"~ E\"      := (uniOpApp bitComp E)      (in custom verse at level 30, right associativity).\n\nInfix \"*\"           := (binOpApp mul)            (in custom verse at level 40, left associativity).\nInfix \"/\"           := (binOpApp quot)           (in custom verse at level 40, left associativity).\nInfix \"%\"           := (binOpApp rem)            (in custom verse at level 40, left associativity).\n\nInfix \"+\"           := (binOpApp plus)           (in custom verse at level 50, left associativity).\nInfix \"-\"           := (binOpApp minus)          (in custom verse at level 50, left associativity).\n\nNotation \"E  <<  N\" := (uniOpApp (shiftL N) E)   (in custom verse at level 54, left associativity).\nNotation \"E  ≪  N\" := (uniOpApp (shiftL N) E)   (in custom verse at level 54, left associativity).\n\nNotation \"E  >>  N\" := (uniOpApp (shiftR N) E)   (in custom verse at level 54, left associativity).\nNotation \"E  ≫  N\" := (uniOpApp (shiftR N) E)   (in custom verse at level 54, left associativity).\n\nNotation \"E <<<  N\" := (uniOpApp (rotL N)   E)   (in custom verse at level 54, left associativity).\nNotation \"E ⋘  N\" := (uniOpApp (rotL N)   E)   (in custom verse at level 54, left associativity).\n\n\nNotation \"E >>>  N\" := (uniOpApp (rotR N)   E)   (in custom verse at level 54, left associativity).\nNotation \"E ⋙  N\" := (uniOpApp (rotR N)   E)   (in custom verse at level 54, left associativity).\n\nInfix \"&\"         := (binOpApp bitAnd)         (in custom verse at level 56, left associativity).\nInfix \"⊕\"         := (binOpApp bitXor)         (in custom verse at level 57, left associativity).\nInfix \"^\"         := (binOpApp bitXor)\n                         (in custom verse at level 57, left associativity, only parsing).\nInfix \"|\"         := (binOpApp bitOr)          (in custom verse at level 59, left associativity).\n\nInfix \":=\"  := assignStmt           (in custom verse at level 70).\nInfix \"<-\"   := moveStmt             (in custom verse at level 70).\nInfix \"+=\"  := (binOpUpdate plus)   (in custom verse at level 70).\nInfix \"-=\"  := (binOpUpdate minus ) (in custom verse at level 70).\nInfix \"*=\"  := (binOpUpdate mul   ) (in custom verse at level 70).\nInfix \"/=\"  := (binOpUpdate quot  ) (in custom verse at level 70).\nInfix \"%=\"  := (binOpUpdate rem   ) (in custom verse at level 70).\nInfix \"|=\"  := (binOpUpdate bitOr ) (in custom verse at level 70).\nInfix \"&=\"  := (binOpUpdate bitAnd) (in custom verse at level 70).\nInfix \"^=\"  := (binOpUpdate bitXor) (in custom verse at level 70, only parsing).\nInfix \"⊕=\"  := (binOpUpdate bitXor) (in custom verse at level 70).\n\nNotation \"A <<= N\"   := (uniOpUpdate (shiftL N) A)   (in custom verse at level 70).\nNotation \"A ≪= N\"   := (uniOpUpdate (shiftL N) A)   (in custom verse at level 70).\n\nNotation \"A >>= N\"   := (uniOpUpdate (shiftR N) A)   (in custom verse at level 70).\nNotation \"A ≫= N\"   := (uniOpUpdate (shiftR N) A)   (in custom verse at level 70).\n\nNotation \"A <<<= N\"  := (uniOpUpdate (rotL N)   A)   (in custom verse at level 70).\nNotation \"A ⋘= N\"  := (uniOpUpdate (rotL N)   A)   (in custom verse at level 70).\n\nNotation \"A >>>= N\"  := (uniOpUpdate (rotR N)   A)   (in custom verse at level 70).\nNotation \"A ⋙= N\"  := (uniOpUpdate (rotR N)   A)   (in custom verse at level 70).\n\nNotation \"'CLOBBER' A\" := (existT _ _ (clobber A))   (in custom verse at level 70).\n(*\nNotation \"'MOVE' B 'to' A [ N ]\"\n  := (existT _ _ (moveTo (deref A (exist _ (N%nat) _)) B)) (in custom verse at level 200, A ident).\n *)\n\n(** * The verse tactic.\n\nThe notations clean up the surface syntax but it still leaves routine\nbut tedious proof burden on to the shoulders of the programmer. We\ndispose this of using the tactic called verse. Usually this is the\nproof obligations that come out of array indexing. The verse tatic\ndisposes it of and raises a warning when it cannot (usually these are\nout of bound array access).\n\n*)\n\nLtac  verse_warn :=\n  match goal with\n  | [ |- ?T ] => idtac \"verse: unable to dispose of\" T\n  end.\n\nLtac verse_bounds_warn := verse_warn; idtac \"possible array index out of bounds\".\nLtac verse_modulus_warn := verse_warn; idtac \"possible modulo arithmetic over zero\".\n\n(* The following doesn't seem to be used any more. Retained to bugfix a later realization. *)\n(*Global Hint Resolve PeanoNat.Nat.mod_upper_bound.*)\n\n(* Typically verse throws up bound checks of the kind x < b where b is a symbolic array size\n\n *)\nRequire Import Psatz.\n\nLtac verse_simplify := match goal with\n                       | [ H : ?T |- ?T ]     => exact H\n                       | [ |- _ <> _ ]        => unfold not; let H := fresh \"H\" in intro H; inversion H\n                       | [ |- ?A mod ?B < ?B ] => apply (PeanoNat.Nat.mod_upper_bound A B)\n                       | [ |- _ <= ?T         ] => compute; lia\n                       | [ |- _ < ?T         ] => compute; lia\n                       end.\n\n\nLtac verse_print_mesg :=  match goal with\n                          | [ |- _ < _         ]  => verse_bounds_warn\n                          | [ |- _ <= _         ] => verse_bounds_warn\n                          | [ |- _ < _         ]  => verse_warn; idtac \"possible array index out of bound\"\n                          | [ |- LEXPR _ _ _   ]  => idtac \"verse: possible ill-typed operands in instructions\"\n                          | [ |- EXPR _ _ _    ]  => idtac \"verse: possible ill-typed operands in instructions\"\n                          | _                    => verse_warn; idtac \"please handle these obligations yourself\"\n                          end.\n\nLtac verse_crush := repeat verse_simplify; verse_print_mesg.\nTactic Notation \"verse\" uconstr(B) := refine B; verse_crush.\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/src/Verse/Language/Pretty.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.28964107553793816}}
{"text": "Require Import SpecCert.Formalism.\nRequire Import SpecCert.Smm.Delta.Invariant.\nRequire Import SpecCert.x86.\n\nLemma close_smram_inv:\n  preserve_inv CloseSmram.\nProof.\n  unfold preserve_inv.\n  unfold inv.\n  unfold smramc_inv, smram_code_inv.\n  intros a a' Hinv Hpre Hpost.\n  unfold close_smram_pre in Hpre.\n  unfold smramc_is_locked in Hinv.\n  unfold smramc_is_unlocked in Hpre.\n  destruct Hinv as [Hsmramc Hsmm].\n  unfold smramc_is_ro in Hsmramc.\n  unfold smramc_is_rw in Hpre.\n  rewrite Hpre in Hsmramc; discriminate Hsmramc.\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/CloseSmram.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2895999014432068}}
{"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 graph coloring. *)\n\nRequire Import SetoidList.\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Op.\nRequire Import Registers.\nRequire Import RTL.\nRequire Import RTLtyping.\nRequire Import Locations.\nRequire Import Conventions.\nRequire Import InterfGraph.\nRequire Import Coloring.\n\n(** * Correctness of the interference graph *)\n\n(** We show that the interference graph built by [interf_graph]\n  is correct in the sense that it contains all conflict edges\n  that we need.\n\n  Many boring lemmas on the auxiliary functions used to construct\n  the interference graph follow.  The lemmas are of two kinds:\n  the ``increasing'' lemmas show that the auxiliary functions only add \n  edges to the interference graph, but do not remove existing edges;\n  and the ``correct'' lemmas show that the auxiliary functions\n  correctly add the edges that we'd like them to add. *)\n\nLemma graph_incl_refl:\n  forall g, graph_incl g g.\nProof.\n  intros; split; auto.\nQed.\n\nLemma add_interf_live_incl_aux:\n  forall (filter: reg -> bool) res live g,\n  graph_incl g\n    (List.fold_left\n      (fun g r => if filter r then add_interf r res g else g)\n      live g).\nProof.\n  induction live; simpl; intros.\n  apply graph_incl_refl.\n  apply graph_incl_trans with (if filter a then add_interf a res g else g).\n  case (filter a).\n  apply add_interf_incl.\n  apply graph_incl_refl.\n  apply IHlive. \nQed.\n\nLemma add_interf_live_incl:\n  forall (filter: reg -> bool) res live g,\n  graph_incl g (add_interf_live filter res live g).\nProof.\n  intros. unfold add_interf_live. rewrite Regset.fold_1.\n  apply add_interf_live_incl_aux.\nQed.\n\nLemma add_interf_live_correct_aux:\n  forall filter res r live,\n  InA Regset.E.eq r live -> filter r = true ->\n  forall g,\n  interfere r res\n    (List.fold_left\n      (fun g r => if filter r then add_interf r res g else g)\n      live g).\nProof.\n  induction 1; simpl; intros.\n  hnf in H. subst y. rewrite H0.\n  generalize (add_interf_live_incl_aux filter res l (add_interf r res g)).\n  intros [A B].\n  apply A. apply add_interf_correct.\n  apply IHInA; auto.\nQed.\n\nLemma add_interf_live_correct:\n  forall filter res live g r,\n  Regset.In r live ->\n  filter r = true ->\n  interfere r res (add_interf_live filter res live g).\nProof.\n  intros.  unfold add_interf_live. rewrite Regset.fold_1.\n  apply add_interf_live_correct_aux; auto.\n  apply Regset.elements_1. auto.\nQed.\n\nLemma add_interf_op_incl: \n  forall res live g,\n  graph_incl g (add_interf_op res live g).\nProof.\n  intros; unfold add_interf_op. apply add_interf_live_incl.\nQed.\n\nLemma add_interf_op_correct:\n  forall res live g r,\n  Regset.In r live ->\n  r <> res ->\n  interfere r res (add_interf_op res live g).\nProof.\n  intros.  unfold add_interf_op.\n  apply add_interf_live_correct.\n  auto. destruct (Reg.eq r res); congruence. \nQed.\n\nLemma add_interf_move_incl: \n  forall arg res live g,\n  graph_incl g (add_interf_move arg res live g).\nProof.\n  intros; unfold add_interf_move. apply add_interf_live_incl.\nQed.\n\nLemma add_interf_move_correct:\n  forall arg res live g r,\n  Regset.In r live ->\n  r <> arg -> r <> res ->\n  interfere r res (add_interf_move arg res live g).\nProof.\n  intros.  unfold add_interf_move.\n  apply add_interf_live_correct.\n  auto.\n  rewrite dec_eq_false; auto. rewrite dec_eq_false; auto.\nQed.\n\nLemma add_interf_destroyed_incl_aux_1:\n  forall mr live g,\n  graph_incl g\n    (List.fold_left (fun g r => add_interf_mreg r mr g) live g).\nProof.\n  induction live; simpl; intros.\n  apply graph_incl_refl.\n  apply graph_incl_trans with (add_interf_mreg a mr g).\n  apply add_interf_mreg_incl.\n  auto.\nQed.\n\nLemma add_interf_destroyed_incl_aux_2:\n  forall mr live g,\n  graph_incl g\n    (Regset.fold (fun r g => add_interf_mreg r mr g) live g).\nProof.\n  intros. rewrite Regset.fold_1. apply add_interf_destroyed_incl_aux_1.\nQed.\n\nLemma add_interf_destroyed_incl:\n  forall live destroyed g,\n  graph_incl g (add_interf_destroyed live destroyed g).\nProof.\n  induction destroyed; simpl; intros.\n  apply graph_incl_refl.\n  eapply graph_incl_trans; [idtac|apply IHdestroyed].\n  apply add_interf_destroyed_incl_aux_2.\nQed.\n\nLemma add_interfs_indirect_call_incl:\n  forall rfun locs g,\n  graph_incl g (add_interfs_indirect_call rfun locs g).\nProof.\n  unfold add_interfs_indirect_call. induction locs; simpl; intros.\n  apply graph_incl_refl.\n  destruct a. eapply graph_incl_trans; [idtac|eauto]. \n  apply add_interf_mreg_incl.\n  auto.\nQed.\n\nLemma add_interfs_call_incl:\n  forall ros locs g,\n  graph_incl g (add_interf_call ros locs g).\nProof.\n  intros. unfold add_interf_call. destruct ros.\n  apply add_interfs_indirect_call_incl.\n  apply graph_incl_refl.\nQed.\n\nLemma interfere_incl:\n  forall r1 r2 g1 g2,\n  graph_incl g1 g2 ->\n  interfere r1 r2 g1 ->\n  interfere r1 r2 g2.\nProof.\n  unfold graph_incl; intros. elim H; auto.\nQed.\n\nLemma interfere_mreg_incl:\n  forall r1 r2 g1 g2,\n  graph_incl g1 g2 ->\n  interfere_mreg r1 r2 g1 ->\n  interfere_mreg r1 r2 g2.\nProof.\n  unfold graph_incl; intros. elim H; auto.\nQed.\n\nLemma add_interf_destroyed_correct_aux_1:\n  forall mr r live,\n  InA Regset.E.eq r live ->\n  forall g,\n  interfere_mreg r mr\n    (List.fold_left (fun g r => add_interf_mreg r mr g) live g).\nProof.\n  induction 1; simpl; intros.\n  hnf in H; subst y. eapply interfere_mreg_incl. \n  apply add_interf_destroyed_incl_aux_1.\n  apply add_interf_mreg_correct.\n  auto.\nQed.\n\nLemma add_interf_destroyed_correct_aux_2:\n  forall mr live g r,\n  Regset.In r live ->\n  interfere_mreg r mr\n    (Regset.fold (fun r g => add_interf_mreg r mr g) live g).\nProof.\n  intros. rewrite Regset.fold_1. apply add_interf_destroyed_correct_aux_1.\n  apply Regset.elements_1. auto.\nQed.\n\nLemma add_interf_destroyed_correct:\n  forall live destroyed g r mr,\n  Regset.In r live ->\n  In mr destroyed ->\n  interfere_mreg r mr (add_interf_destroyed live destroyed g).\nProof.\n  induction destroyed; simpl; intros.\n  elim H0.\n  elim H0; intros. \n  subst a. eapply interfere_mreg_incl.\n  apply add_interf_destroyed_incl.\n  apply add_interf_destroyed_correct_aux_2; auto.\n  apply IHdestroyed; auto.\nQed.\n\nLemma add_interfs_indirect_call_correct:\n  forall rfun mr locs g,\n  In (R mr) locs ->\n  interfere_mreg rfun mr (add_interfs_indirect_call rfun locs g).\nProof.\n  unfold add_interfs_indirect_call. induction locs; simpl; intros.\n  elim H.\n  destruct H. subst a.\n  eapply interfere_mreg_incl.\n  apply (add_interfs_indirect_call_incl rfun locs (add_interf_mreg rfun mr g)).\n  apply add_interf_mreg_correct.\n  auto.\nQed.\n\nLemma add_interfs_call_correct:\n  forall rfun locs g mr,\n  In (R mr) locs -> \n  interfere_mreg rfun mr (add_interf_call (inl _ rfun) locs g).\nProof.\n  intros. unfold add_interf_call.\n  apply add_interfs_indirect_call_correct. auto.\nQed.\n\nLemma add_prefs_call_incl:\n  forall args locs g,\n  graph_incl g (add_prefs_call args locs g).\nProof.\n  induction args; destruct locs; simpl; intros;\n  try apply graph_incl_refl.\n  destruct l. \n  eapply graph_incl_trans; [idtac|eauto]. \n  apply add_pref_mreg_incl.\n  auto.\nQed.\n\nLemma add_prefs_builtin_incl:\n  forall ef args res g,\n  graph_incl g (add_prefs_builtin ef args res g).\nProof.\n  intros. unfold add_prefs_builtin. \n  destruct ef; try apply graph_incl_refl.\n  destruct args; try apply graph_incl_refl.\n  apply add_pref_incl. \nQed.\n\nLemma add_interf_entry_incl:\n  forall params live g,\n  graph_incl g (add_interf_entry params live g).\nProof.\n  unfold add_interf_entry; induction params; simpl; intros.\n  apply graph_incl_refl.\n  eapply graph_incl_trans; [idtac|eauto].\n  apply add_interf_op_incl.\nQed.\n\nLemma add_interf_entry_correct:\n  forall params live g r1 r2,\n  In r1 params ->\n  Regset.In r2 live ->\n  r1 <> r2 ->\n  interfere r1 r2 (add_interf_entry params live g).\nProof.\n  unfold add_interf_entry; induction params; simpl; intros.\n  elim H.\n  elim H; intro.\n  subst a. apply interfere_incl with (add_interf_op r1 live g).\n  exact (add_interf_entry_incl _ _ _).\n  apply interfere_sym. apply add_interf_op_correct; auto.\n  auto.\nQed.\n\nLemma add_interf_params_incl_aux:\n  forall p1 pl g,\n  graph_incl g\n   (List.fold_left\n      (fun g r => if Reg.eq r p1 then g else add_interf r p1 g)\n      pl g).\nProof.\n  induction pl; simpl; intros.\n  apply graph_incl_refl.\n  eapply graph_incl_trans; [idtac|eauto].\n  case (Reg.eq a p1); intro.\n  apply graph_incl_refl. apply add_interf_incl.\nQed.\n\nLemma add_interf_params_incl:\n  forall pl g,\n  graph_incl g (add_interf_params pl g).\nProof.\n  induction pl; simpl; intros.\n  apply graph_incl_refl.\n  eapply graph_incl_trans; [idtac|eauto].\n  apply add_interf_params_incl_aux.\nQed.\n\nLemma add_interf_params_correct_aux:\n  forall p1 pl g p2,\n  In p2 pl ->\n  p1 <> p2 ->\n  interfere p1 p2\n   (List.fold_left\n      (fun g r => if Reg.eq r p1 then g else add_interf r p1 g)\n      pl g).\nProof.\n  induction pl; simpl; intros.\n  elim H.\n  elim H; intro; clear H.\n  subst a. apply interfere_sym. eapply interfere_incl.\n  apply add_interf_params_incl_aux. \n  case (Reg.eq p2 p1); intro.\n  congruence. apply add_interf_correct.\n  auto.\nQed.\n\nLemma add_interf_params_correct:\n  forall pl g r1 r2,\n  In r1 pl -> In r2 pl -> r1 <> r2 ->\n  interfere r1 r2 (add_interf_params pl g).\nProof.\n  induction pl; simpl; intros.\n  elim H.\n  elim H; intro; clear H; elim H0; intro; clear H0.\n  congruence.\n  subst a. eapply interfere_incl. apply add_interf_params_incl.\n  apply add_interf_params_correct_aux; auto.\n  subst a. apply interfere_sym.\n  eapply interfere_incl. apply add_interf_params_incl.\n  apply add_interf_params_correct_aux; auto.\n  auto.\nQed.\n\nLemma add_edges_instr_incl:\n  forall sig instr live g,\n  graph_incl g (add_edges_instr sig instr live g).\nProof.\n  intros. destruct instr; unfold add_edges_instr;\n  try apply graph_incl_refl.\n  case (Regset.mem r live).\n  destruct (is_move_operation o l).\n  eapply graph_incl_trans; [idtac|apply add_pref_incl].\n  apply add_interf_move_incl.\n  apply add_interf_op_incl.\n  apply graph_incl_refl.\n  case (Regset.mem r live).\n  apply add_interf_op_incl.\n  apply graph_incl_refl.\n  eapply graph_incl_trans; [idtac|apply add_prefs_call_incl].\n  eapply graph_incl_trans; [idtac|apply add_pref_mreg_incl].\n  eapply graph_incl_trans; [idtac|apply add_interf_op_incl].\n  eapply graph_incl_trans; [idtac|apply add_interfs_call_incl].\n  apply add_interf_destroyed_incl.\n  eapply graph_incl_trans; [idtac|apply add_prefs_call_incl].\n  apply add_interfs_call_incl.\n  eapply graph_incl_trans. apply add_interf_op_incl. apply add_prefs_builtin_incl.\n  destruct o.\n  apply add_pref_mreg_incl.\n  apply graph_incl_refl.\nQed.\n\n(** The proposition below states that graph [g] contains\n  all the conflict edges expected for instruction [instr]. *)\n\nDefinition correct_interf_instr\n    (live: Regset.t) (instr: instruction) (g: graph) : Prop :=\n  match instr with\n  | Iop op args res s =>\n      match is_move_operation op args with\n      | Some arg =>\n          forall r,\n          Regset.In res live ->\n          Regset.In r live ->\n          r <> res -> r <> arg -> interfere r res g\n      | None =>\n          forall r,\n          Regset.In res live ->\n          Regset.In r live ->\n          r <> res -> interfere r res g\n      end\n  | Iload chunk addr args res s =>\n      forall r,\n      Regset.In res live ->\n      Regset.In r live ->\n      r <> res -> interfere r res g\n  | Icall sig ros args res s =>\n      (forall r mr,\n        Regset.In r live ->\n        In mr destroyed_at_call_regs ->\n        r <> res ->\n        interfere_mreg r mr g)\n   /\\ (forall r,\n        Regset.In r live ->\n       r <> res -> interfere r res g)\n   /\\ (match ros with\n       | inl rfun => forall mr, In (R mr) (loc_arguments sig) -> \n                                interfere_mreg rfun mr g\n       | inr idfun => True\n       end)\n  | Itailcall sig ros args =>\n      match ros with\n        | inl rfun => forall mr, In (R mr) (loc_arguments sig) -> \n                                 interfere_mreg rfun mr g\n        | inr idfun => True\n      end\n  | Ibuiltin ef args res s =>\n      forall r,\n      Regset.In r live ->\n      r <> res -> interfere r res g\n  | _ =>\n      True\n  end.\n\nLemma correct_interf_instr_incl:\n  forall live instr g1 g2,\n  graph_incl g1 g2 ->\n  correct_interf_instr live instr g1 ->\n  correct_interf_instr live instr g2.\nProof.\n  intros until g2. intro. \n  unfold correct_interf_instr; destruct instr; auto.\n  destruct (is_move_operation o l).\n  intros. eapply interfere_incl; eauto.\n  intros. eapply interfere_incl; eauto.\n  intros. eapply interfere_incl; eauto.\n  intros [A [B C]].\n  split. intros. eapply interfere_mreg_incl; eauto.\n  split. intros. eapply interfere_incl; eauto.\n  destruct s0; auto. intros. eapply interfere_mreg_incl; eauto. \n  destruct s0; auto. intros. eapply interfere_mreg_incl; eauto.\n  intros. eapply interfere_incl; eauto. \nQed.\n\nLemma add_edges_instr_correct:\n  forall sig instr live g,\n  correct_interf_instr live instr (add_edges_instr sig instr live g).\nProof.\n  intros.\n  destruct instr; unfold add_edges_instr; unfold correct_interf_instr; auto.\n  destruct (is_move_operation o l); intros.\n  rewrite Regset.mem_1; auto. eapply interfere_incl. \n  apply add_pref_incl. apply add_interf_move_correct; auto.\n  rewrite Regset.mem_1; auto. apply add_interf_op_correct; auto. \n\n  intros. rewrite Regset.mem_1; auto. apply add_interf_op_correct; auto.\n\n  (* Icall *)\n  set (largs := loc_arguments s).\n  set (lres := loc_result s).\n  split. intros.\n  apply interfere_mreg_incl with\n    (add_interf_destroyed (Regset.remove r live) destroyed_at_call_regs g).\n  eapply graph_incl_trans; [idtac|apply add_prefs_call_incl].\n  eapply graph_incl_trans; [idtac|apply add_pref_mreg_incl].\n  eapply graph_incl_trans; [idtac|apply add_interf_op_incl].\n  apply add_interfs_call_incl.\n  apply add_interf_destroyed_correct; auto.\n  apply Regset.remove_2; auto.\n\n  split. intros.\n  eapply interfere_incl.\n  eapply graph_incl_trans; [idtac|apply add_prefs_call_incl].\n  apply add_pref_mreg_incl.\n  apply add_interf_op_correct; auto.\n\n  destruct s0; auto; intros.\n  eapply interfere_mreg_incl.\n  eapply graph_incl_trans; [idtac|apply add_prefs_call_incl].\n  eapply graph_incl_trans; [idtac|apply add_pref_mreg_incl].\n  apply add_interf_op_incl.\n  apply add_interfs_call_correct. auto.\n\n  (* Itailcall *)\n  destruct s0; auto; intros.\n  eapply interfere_mreg_incl.\n  apply add_prefs_call_incl.\n  apply add_interfs_call_correct. auto.\n\n  (* Ibuiltin *)\n  intros. eapply interfere_incl. apply add_prefs_builtin_incl. \n  apply add_interf_op_correct; auto. \nQed.\n\nLemma add_edges_instrs_correct:\n  forall f live pc i,\n  f.(fn_code)!pc = Some i ->\n  correct_interf_instr live!!pc i (add_edges_instrs f live).\nProof.\n  intros f live.\n  set (P := fun (c: code) g =>\n         forall pc i, c!pc = Some i -> correct_interf_instr live#pc i g).\n  set (F := (fun (g : graph) (pc0 : positive) (i0 : instruction) =>\n         add_edges_instr (fn_sig f) i0 live # pc0 g)).\n  change (P f.(fn_code) (PTree.fold F f.(fn_code) empty_graph)).\n  apply PTree_Properties.fold_rec; unfold P; intros.\n  apply H0. rewrite H. auto.\n  rewrite PTree.gempty in H. congruence.\n  rewrite PTree.gsspec in H2. destruct (peq pc k). \n  inv H2. unfold F. apply add_edges_instr_correct. \n  apply correct_interf_instr_incl with a. \n  unfold F; apply add_edges_instr_incl.\n  apply H1; auto.\nQed.\n\n(** Here are the three correctness properties of the generated\n  inference graph.  First, it contains the conflict edges\n  needed by every instruction of the function. *)\n\nLemma interf_graph_correct_1:\n  forall f live live0 pc i,\n  f.(fn_code)!pc = Some i ->\n  correct_interf_instr live!!pc i (interf_graph f live live0).\nProof.\n  intros. unfold interf_graph.\n  apply correct_interf_instr_incl with (add_edges_instrs f live).\n  eapply graph_incl_trans; [idtac|apply add_prefs_call_incl].\n  eapply graph_incl_trans; [idtac|apply add_interf_params_incl].\n  apply add_interf_entry_incl.\n  apply add_edges_instrs_correct; auto.\nQed.\n\n(** Second, function parameters conflict pairwise. *)\n\nLemma interf_graph_correct_2:\n  forall f live live0 r1 r2,\n  In r1 f.(fn_params) ->\n  In r2 f.(fn_params) ->\n  r1 <> r2 ->\n  interfere r1 r2 (interf_graph f live live0).\nProof.\n  intros. unfold interf_graph. \n  eapply interfere_incl.\n  apply add_prefs_call_incl.\n  apply add_interf_params_correct; auto.\nQed.\n\n(** Third, function parameters conflict pairwise with pseudo-registers\n  live at function entry.  If the function never uses a pseudo-register\n  before it is defined, pseudo-registers live at function entry\n  are a subset of the function parameters and therefore this condition\n  is implied by [interf_graph_correct_3].  However, we prefer not\n  to make this assumption. *)\n\nLemma interf_graph_correct_3:\n  forall f live live0 r1 r2,\n  In r1 f.(fn_params) ->\n  Regset.In r2 live0 ->\n  r1 <> r2 ->\n  interfere r1 r2 (interf_graph f live live0).\nProof.\n  intros. unfold interf_graph.\n  eapply interfere_incl.\n  eapply graph_incl_trans; [idtac|apply add_prefs_call_incl].\n  apply add_interf_params_incl.\n  apply add_interf_entry_correct; auto.\nQed.\n\n(** * Correctness of the a priori checks over the result of graph coloring *)\n\n(** We now show that the checks performed over the candidate coloring\n  returned by [graph_coloring] are correct: candidate colorings that\n  pass these checks are indeed correct colorings. *)\n\nSection CORRECT_COLORING.\n\nVariable g: graph.\nVariable env: regenv.\nVariable allregs: Regset.t.\nVariable coloring: reg -> loc.\n\nLemma check_coloring_1_correct:\n  forall r1 r2,\n  check_coloring_1 g coloring = true ->\n  SetRegReg.In (r1, r2) g.(interf_reg_reg) ->\n  coloring r1 <> coloring r2.\nProof.\n  unfold check_coloring_1. intros. \n  assert (compat_bool OrderedRegReg.eq\n     (fun r1r2 => if Loc.eq (coloring (fst r1r2)) (coloring (snd r1r2))\n                  then false else true)).\n  red. unfold OrderedRegReg.eq. unfold OrderedReg.eq.\n  intros x y [EQ1 EQ2]. rewrite EQ1; rewrite EQ2; auto.\n  generalize (SetRegReg.for_all_2 H1 H H0). \n  simpl. case (Loc.eq (coloring r1) (coloring r2)); intro.\n  intro; discriminate. auto.\nQed.\n\nLemma check_coloring_2_correct:\n  forall r1 mr2,\n  check_coloring_2 g coloring = true ->\n  SetRegMreg.In (r1, mr2) g.(interf_reg_mreg) ->\n  coloring r1 <> R mr2.\nProof.\n  unfold check_coloring_2. intros. \n  assert (compat_bool OrderedRegMreg.eq\n     (fun r1r2 => if Loc.eq (coloring (fst r1r2)) (R (snd r1r2))\n                  then false else true)).\n  red. unfold OrderedRegMreg.eq. unfold OrderedReg.eq.\n  intros x y [EQ1 EQ2]. rewrite EQ1; rewrite EQ2; auto.\n  generalize (SetRegMreg.for_all_2 H1 H H0). \n  simpl. case (Loc.eq (coloring r1) (R mr2)); intro.\n  intro; discriminate. auto.\nQed.\n\nLemma same_typ_correct:\n  forall t1 t2, same_typ t1 t2 = true -> t1 = t2.\nProof.\n  destruct t1; destruct t2; simpl; congruence.\nQed.\n\nLemma loc_is_acceptable_correct:\n  forall l, loc_is_acceptable l = true -> loc_acceptable l.\nProof.\n  destruct l; unfold loc_is_acceptable, loc_acceptable.\n  case (In_dec Loc.eq (R m) temporaries); intro.\n  intro; discriminate. auto.\n  destruct s.\n  case (zlt z 0); intro. intro; discriminate. auto.\n  intro; discriminate.\n  intro; discriminate.\nQed.\n\nLemma check_coloring_3_correct:\n  forall r,\n  check_coloring_3 allregs env coloring = true ->\n  Regset.mem r allregs = true ->\n  loc_acceptable (coloring r) /\\ env r = Loc.type (coloring r).\nProof.\n  unfold check_coloring_3; intros.\n  exploit Regset.for_all_2; eauto.\n  red; intros. congruence.\n  apply Regset.mem_2. eauto.\n  simpl. intro. elim (andb_prop _ _ H1); intros.\n  split. apply loc_is_acceptable_correct; auto.\n  apply same_typ_correct; auto.\nQed.\n\nEnd CORRECT_COLORING.\n\n(** * Correctness of clipping *)\n\n(** We then show the correctness of the ``clipped'' coloring\n  returned by [alloc_of_coloring] applied to a candidate coloring\n  that passes the a posteriori checks. *)\n\nSection ALLOC_OF_COLORING.\n\nVariable g: graph.\nVariable env: regenv.\nLet allregs := all_interf_regs g.\nVariable coloring: reg -> loc.\nLet alloc := alloc_of_coloring coloring env allregs.\n\nLemma alloc_of_coloring_correct_1:\n  forall r1 r2,\n  check_coloring g env allregs coloring = true ->\n  SetRegReg.In (r1, r2) g.(interf_reg_reg) ->\n  alloc r1 <> alloc r2.\nProof.\n  unfold check_coloring, alloc, alloc_of_coloring; intros.\n  elim (andb_prop _ _ H); intros.\n  generalize (all_interf_regs_correct_1 _ _ _ H0).\n  intros [A B].\n  unfold allregs. rewrite Regset.mem_1; auto. rewrite Regset.mem_1; auto.\n  eapply check_coloring_1_correct; eauto.\nQed.\n\nLemma alloc_of_coloring_correct_2:\n  forall r1 mr2,\n  check_coloring g env allregs coloring = true ->\n  SetRegMreg.In (r1, mr2) g.(interf_reg_mreg) ->\n  alloc r1 <> R mr2.\nProof.\n  unfold check_coloring, alloc, alloc_of_coloring; intros.\n  elim (andb_prop _ _ H); intros.\n  elim (andb_prop _ _ H2); intros.\n  generalize (all_interf_regs_correct_2 _ _ _ H0). intros.\n  unfold allregs. rewrite Regset.mem_1; auto. \n  eapply check_coloring_2_correct; eauto.\nQed.\n\nLemma alloc_of_coloring_correct_3:\n  forall r,\n  check_coloring g env allregs coloring = true ->\n  loc_acceptable (alloc r).\nProof.\n  unfold check_coloring, alloc, alloc_of_coloring; intros.\n  elim (andb_prop _ _ H); intros.\n  elim (andb_prop _ _ H1); intros.\n  caseEq (Regset.mem r allregs); intro.\n  generalize (check_coloring_3_correct _ _ _ r H3 H4). tauto.\n  case (env r); simpl.\n  unfold dummy_int_reg. intuition congruence.\n  unfold dummy_float_reg. intuition congruence.\nQed.\n\nLemma alloc_of_coloring_correct_4:\n  forall r,\n  check_coloring g env allregs coloring = true ->\n  env r = Loc.type (alloc r).\nProof.\n  unfold check_coloring, alloc, alloc_of_coloring; intros.\n  elim (andb_prop _ _ H); intros.\n  elim (andb_prop _ _ H1); intros.\n  caseEq (Regset.mem r allregs); intro.\n  generalize (check_coloring_3_correct _ _ _ r H3 H4). tauto.\n  case (env r); reflexivity.\nQed.\n\nEnd ALLOC_OF_COLORING.\n\n(** * Correctness of the whole graph coloring algorithm *)\n\n(** Combining results from the previous sections, we now summarize\n  the correctness properties of the assignment (of locations to\n  registers) returned by [regalloc]. *)\n\nDefinition correct_alloc_instr\n    (live: PMap.t Regset.t) (alloc: reg -> loc) \n    (pc: node) (instr: instruction) : Prop :=\n  match instr with\n  | Iop op args res s =>\n      match is_move_operation op args with\n      | Some arg =>\n          forall r,\n          Regset.In res live!!pc ->\n          Regset.In r live!!pc ->\n          r <> res -> r <> arg -> alloc r <> alloc res\n      | None =>\n          forall r,\n          Regset.In res live!!pc ->\n          Regset.In r live!!pc ->\n          r <> res -> alloc r <> alloc res\n      end\n  | Iload chunk addr args res s =>\n      forall r,\n      Regset.In res live!!pc ->\n      Regset.In r live!!pc ->\n      r <> res -> alloc r <> alloc res\n  | Icall sig ros args res s =>\n      (forall r,\n        Regset.In r live!!pc ->\n        r <> res ->\n        ~(In (alloc r) destroyed_at_call))\n   /\\ (forall r,\n        Regset.In r live!!pc ->\n        r <> res -> alloc r <> alloc res)\n   /\\ (match ros with\n        | inl rfun => ~(In (alloc rfun) (loc_arguments sig))\n        | inr idfun => True\n        end)\n  | Itailcall sig ros args =>\n      (match ros with\n        | inl rfun => ~(In (alloc rfun) (loc_arguments sig))\n        | inr idfun => True\n        end)\n  | Ibuiltin ef args res s =>\n      forall r,\n      Regset.In r live!!pc ->\n      r <> res -> alloc r <> alloc res\n  | _ =>\n      True\n  end.\n\nSection REGALLOC_PROPERTIES.\n\nVariable f: function.\nVariable env: regenv.\nVariable live: PMap.t Regset.t.\nVariable live0: Regset.t.\nVariable alloc: reg -> loc.\n\nLet g := interf_graph f live live0.\nLet allregs := all_interf_regs g.\nLet coloring := graph_coloring f g env allregs.\n\nLemma regalloc_ok:\n  regalloc f live live0 env = Some alloc ->\n  check_coloring g env allregs coloring = true /\\\n  alloc = alloc_of_coloring coloring env allregs.\nProof.\n  unfold regalloc, coloring, allregs, g.\n  case (check_coloring (interf_graph f live live0) env).\n  intro EQ; injection EQ; intro; clear EQ.\n  split. auto. auto.\n  intro; discriminate.\nQed.\n\nLemma regalloc_acceptable:\n  forall r,\n  regalloc f live live0 env = Some alloc ->\n  loc_acceptable (alloc r).\nProof.\n  intros. elim (regalloc_ok H); intros.\n  rewrite H1. unfold allregs. apply alloc_of_coloring_correct_3.\n  exact H0.\nQed.\n\nLemma regsalloc_acceptable:\n  forall rl,\n  regalloc f live live0 env = Some alloc ->\n  locs_acceptable (List.map alloc rl).\nProof.\n  intros; red; intros.\n  elim (list_in_map_inv _ _ _ H0). intros r [EQ IN].\n  subst l. apply regalloc_acceptable. auto. \nQed.\n\nLemma regalloc_preserves_types:\n  forall r,\n  regalloc f live live0 env = Some alloc ->\n  Loc.type (alloc r) = env r.\nProof.\n  intros. elim (regalloc_ok H); intros.\n  rewrite H1. unfold allregs. symmetry.\n  apply alloc_of_coloring_correct_4.\n  exact H0.\nQed.\n\nLemma correct_interf_alloc_instr:\n  forall pc instr,\n  (forall r1 r2, interfere r1 r2 g -> alloc r1 <> alloc r2) ->\n  (forall r1 mr2, interfere_mreg r1 mr2 g -> alloc r1 <> R mr2) ->\n  (forall r, loc_acceptable (alloc r)) ->\n  correct_interf_instr live!!pc instr g ->\n  correct_alloc_instr live alloc pc instr.\nProof.\n  intros pc instr ALL1 ALL2 ALL3.\n  unfold correct_interf_instr, correct_alloc_instr;\n  destruct instr; auto.\n  destruct (is_move_operation o l); auto.\n  (* Icall *)\n  intros [A [B C]].\n  split. intros; red; intros. \n  unfold destroyed_at_call in H1.\n  generalize (list_in_map_inv R _ _ H1). \n  intros [mr [EQ IN]]. \n  generalize (A r0 mr H IN H0). intro.\n  generalize (ALL2 _ _ H2). contradiction.\n  split. auto.\n  destruct s0; auto. red; intros.\n  generalize (ALL3 r0). generalize (loc_arguments_acceptable _ _ H).\n  unfold loc_argument_acceptable, loc_acceptable.\n  caseEq (alloc r0). intros.\n  elim (ALL2 r0 m). apply C; auto. congruence. auto. \n  destruct s0; auto.\n  (* Itailcall *)\n  destruct s0; auto. red; intros.\n  generalize (ALL3 r). generalize (loc_arguments_acceptable _ _ H0).\n  unfold loc_argument_acceptable, loc_acceptable.\n  caseEq (alloc r). intros.\n  elim (ALL2 r m). apply H; auto. congruence. auto. \n  destruct s0; auto.\nQed.\n  \nLemma regalloc_correct_1:\n  forall pc instr,\n  regalloc f live live0 env = Some alloc ->\n  f.(fn_code)!pc = Some instr ->\n  correct_alloc_instr live alloc pc instr.\nProof.\n  intros. elim (regalloc_ok H); intros.\n  apply correct_interf_alloc_instr.\n  intros. rewrite H2. unfold allregs. red in H3. \n  elim (ordered_pair_charact r1 r2); intro.\n  apply alloc_of_coloring_correct_1. auto. rewrite H4 in H3; auto.\n  apply sym_not_equal.\n  apply alloc_of_coloring_correct_1. auto. rewrite H4 in H3; auto.\n  intros. rewrite H2. unfold allregs.\n  apply alloc_of_coloring_correct_2. auto. exact H3.\n  intros. eapply regalloc_acceptable; eauto.\n  unfold g. apply interf_graph_correct_1. auto. \nQed.\n\nLemma regalloc_correct_2:\n  regalloc f live live0 env = Some alloc ->\n  list_norepet f.(fn_params) ->\n  list_norepet (List.map alloc f.(fn_params)).\nProof.\n  intros. elim (regalloc_ok H); intros.\n  apply list_map_norepet; auto.\n  intros. rewrite H2. unfold allregs. \n  elim (ordered_pair_charact x y); intro.\n  apply alloc_of_coloring_correct_1. auto. \n  change positive with reg. rewrite <- H6.\n  change (interfere x y g). unfold g. \n  apply interf_graph_correct_2; auto.\n  apply sym_not_equal.\n  apply alloc_of_coloring_correct_1. auto. \n  change positive with reg. rewrite <- H6.\n  change (interfere x y g). unfold g. \n  apply interf_graph_correct_2; auto.\nQed.\n\nLemma regalloc_correct_3:\n  forall r1 r2,\n  regalloc f live live0 env = Some alloc ->\n  In r1 f.(fn_params) ->\n  Regset.In r2 live0 ->\n  r1 <> r2 ->\n  alloc r1 <> alloc r2.\nProof.\n  intros. elim (regalloc_ok H); intros.\n  rewrite H4; unfold allregs.\n  elim (ordered_pair_charact r1 r2); intro.\n  apply alloc_of_coloring_correct_1. auto. \n  change positive with reg. rewrite <- H5.\n  change (interfere r1 r2 g). unfold g.\n  apply interf_graph_correct_3; auto.\n  apply sym_not_equal.\n  apply alloc_of_coloring_correct_1. auto. \n  change positive with reg. rewrite <- H5.\n  change (interfere r1 r2 g). unfold g.\n  apply interf_graph_correct_3; auto.\nQed.\n\nEnd REGALLOC_PROPERTIES.\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/Coloringproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.2895999014432068}}
{"text": "Require Import BasicMachineTypes.\nRequire Import ClassDatatypesIface.\nRequire Import Peano_dec.\nRequire Import StoreIface.\nRequire Import OptionExt.\nRequire Import List.\nRequire Import ListExt.\nRequire Import Compare_dec.\nRequire Import Arith.\nRequire Import Certificates.\nRequire Import VerifierAnnotationsIface.\nRequire Import AbstractLogic.\nRequire Import VCs.\nRequire Import ErrorMonad.\nRequire Import ErrorMessages.\nRequire Import MLStrings.\nRequire Import NativeMethodSpec.\nRequire Import Setoid.\nRequire Import Omega.\n\nModule Type CODE_VERIFIER_BASE\n  (B : BASICS)\n  (AL : ABSTRACT_LOGIC B)\n  (CERT : CERTIFICATE with Definition asn := AL.formula)\n  (ANN : VERIFIER_ANNOTATIONS B AL CERT)\n  (C : CLASSDATATYPES B ANN.GA.A).\n\nParameter instruction_precondition :\n  CERT.Cert.t ->\n  C.ConstantPool.t ->\n  AL.formula ->\n  AL.formula ->\n  ANN.ConstantPoolAdditional.t ->\n  list C.exception_handler ->\n  C.opcode ->\n  nat ->\n  AL.formula ->\n  Prop.\n\nParameter get_instruction_precondition :\n  CERT.Cert.t ->\n  C.ConstantPool.t ->\n  AL.formula ->\n  AL.formula ->\n  ANN.ConstantPoolAdditional.t ->\n  list C.exception_handler ->\n  C.opcode ->\n  nat ->\n  error_monad AL.formula.\n\nHypothesis get_instruction_precondition_sound : forall cert cp ensures ex_ensures cpa handlers op pc a,\n  get_instruction_precondition cert cp ensures ex_ensures cpa handlers op pc = Val a ->\n  instruction_precondition cert cp ensures ex_ensures cpa handlers op pc a.\n\nHypothesis cert_incl_instruction_precondition : forall cert cert' cp ensures ex_ensures cpa handlers op pc a,\n  CERT.cert_incl cert cert' ->\n  instruction_precondition cert cp ensures ex_ensures cpa handlers op pc a ->\n  instruction_precondition cert' cp ensures ex_ensures cpa handlers op pc a.\n\nEnd CODE_VERIFIER_BASE.\n\nModule MkCodeVerifier (B     : BASICS)\n                      (AL    : ABSTRACT_LOGIC B)\n                      (CERT  : CERTIFICATE with Definition asn := AL.formula)\n                      (ANN   : VERIFIER_ANNOTATIONS B AL CERT)\n                      (C     : CLASSDATATYPES B ANN.GA.A)\n                      (Base  : CODE_VERIFIER_BASE B AL CERT ANN C)\n                      (NTSPC : NATIVE_METHOD_SPEC B ANN.GA.A)\n                      (VCs   : VERIFICATION_CONDITIONS B AL).\n\nImport CERT.\n\nSection ErrorHandling.\n\nDefinition getproof (prooftable : ANN.ProofTable.t) (hyp res : AL.formula) :=\n  tagoptfail (err_noproof mlapp (AL.string_of_formula hyp) mlapp\n              err_entails mlapp (AL.string_of_formula res))\n  (ANN.ProofTable.lookup prooftable (hyp, res)).\n\nEnd ErrorHandling.\n    \nSection CodeVerification.\n\nHypothesis cp : C.ConstantPool.t.\nHypothesis cpa : ANN.ConstantPoolAdditional.t.\nHypothesis ensures ex_ensures : AL.formula.\n\nInductive verified_instruction (cert:Cert.t)\n                               (handlers : list C.exception_handler)\n                               (op : C.opcode)\n                               (pc : nat) : Prop :=\n| mk_verified_instruction : forall a1 a2,\n    CERT.Cert.lookup cert pc = Some a1 ->\n    Base.instruction_precondition cert cp ensures ex_ensures cpa handlers op pc a2 ->\n    AL.implies a1 a2 ->\n    verified_instruction cert handlers op pc.\n\nHypothesis code : C.precode.\n\nInductive verified_precode (cert:Cert.t) : Prop :=\n| mk_verified_code :\n    (* the certificate only covers the actual code *)\n    (forall n a, CERT.Cert.lookup cert n = Some a -> n < length (C.precode_code code)) ->\n    (* all the actual instructions are safe *)\n    (forall n op, nth_error (C.precode_code code) n = Some op -> \n      verified_instruction cert (C.precode_exception_table code) op n) ->\n    verified_precode cert.\n\n(* now we try to complete certificates *)\n\nHypothesis prooftable : ANN.ProofTable.t.\n\nDefinition method_vc := (VCs.VerificationConditions.key * nat)%type.\n\nDefinition completion_step : Cert.t -> nat -> C.opcode -> error_monad (Cert.t * list method_vc) :=\n  fun cert pc op =>\n  a <- Base.get_instruction_precondition cert cp ensures ex_ensures cpa (C.precode_exception_table code) op pc;:\n  match Cert.lookup cert pc with\n  | None => ret (Cert.update cert pc a, nil)\n  | Some a' =>\n     ret (cert, ((a',a),pc)::nil) \n  end.\n\nFixpoint complete_cert_aux (ops:list C.opcode) (cert:Cert.t) (pc:nat) {struct ops} : error_monad (Cert.t * list method_vc) :=\n  match ops with\n  | nil     => fail err_emptycode\n  | op::nil => completion_step cert pc op \n  | op::ops => p1 <- complete_cert_aux ops cert (S pc);:\n               match p1 with (cert',vcs) =>\n                 p2 <- completion_step cert' pc op;:\n                 match p2 with (cert'',vcs') =>\n                   ret (cert'',vcs' ++ vcs)\n                 end\n               end\n  end.\n\nDefinition complete_cert : error_monad (Cert.t * list method_vc) :=\n  complete_cert_aux (C.precode_code code) (clean_cert (C.precode_annot code) (length (C.precode_code code))) 0.\n\nLemma step_incl : forall c c' vc n op, completion_step c n op = Val (c',vc) -> cert_incl c c'.\nintros. unfold completion_step in H.\ndestruct (Base.get_instruction_precondition c cp ensures ex_ensures cpa (C.precode_exception_table code) op n) as [l|]; [|discriminate].\ndestruct (option_dec (Cert.lookup c n)) as [[a cert_lookup_result] | cert_lookup_result];\n rewrite cert_lookup_result in H.\n simpl in H. inversion H. apply cert_incl_refl.\n inversion H. apply cert_incl_update. apply cert_lookup_result.\nSave.\n\nLemma complete_cert_incl : forall c c' vcs n ops,\n  complete_cert_aux ops c n = Val (c',vcs) -> cert_incl c c'.\nintros. generalize n c' vcs H. clear n c' vcs H.\ninduction ops; intros.\n discriminate.\n simpl in H. destruct ops.\n  eapply step_incl. apply H.\n  destruct_err (complete_cert_aux (o::ops) c (S n)) H cert'vcs' complete_cert_aux_result.\n  destruct cert'vcs' as [cert' vcs'].\n   eapply cert_incl_trans.\n    eapply IHops. apply complete_cert_aux_result.\n    destruct_err (completion_step cert' n a) H cert''vcs'' result.\n    destruct cert''vcs'' as [cert'' vcs''].\n    inversion H. subst.\n    eapply step_incl.\n    apply result.\nSave.\n\nLemma complete_cert_aux_prop : forall n ops c c' vcs, n < length ops ->\n  complete_cert_aux ops c 0 = Val (c',vcs) ->\n  (exists c'', exists vcs'', complete_cert_aux (tail n ops) c n = Val (c'',vcs'')\n               /\\ cert_incl c c''\n               /\\ cert_incl c'' c'\n               /\\ forall vc, In vc vcs'' -> In vc vcs).\nintros n ops c c' vcs n_lt_len_ops complete_cert_aux_result. \nrewrite <- (tail_0 ops) in complete_cert_aux_result.\npose (n':=n). assert (n_lt_n':n'<=n) by (auto with arith). replace 0 with (n-n') in complete_cert_aux_result by auto with arith.\npose (c3:=c'). assert (c3_incl_c':cert_incl c3 c') by (apply cert_incl_refl). replace c' with c3 in complete_cert_aux_result by reflexivity.\ngeneralize c vcs c3 c3_incl_c' complete_cert_aux_result n_lt_n'. clear c vcs c3 c3_incl_c' complete_cert_aux_result n_lt_n'.\ninduction n'; intros.\n (* base case *)\n rewrite <- minus_n_O in complete_cert_aux_result. exists c3. exists vcs. intuition.\n eapply complete_cert_incl. apply complete_cert_aux_result.\n (* step case *)\n destruct (tail_minus ops n' n) as [op tail_eq]. omega. assumption.\n rewrite tail_eq in complete_cert_aux_result.\n simpl in complete_cert_aux_result.\n destruct (tail_S (n-n') ops) as [op' tail_eq']. omega.\n rewrite tail_eq' in complete_cert_aux_result.\n destruct_err (complete_cert_aux (op' :: tail (S (n - n')) ops) c (S (n - S n'))) complete_cert_aux_result cert'vcs' complete_cert_aux_result'.\n destruct cert'vcs' as [cert' vcs'].\n  rewrite <- tail_eq' in complete_cert_aux_result'.\n  replace (S (n - S n')) with (n-n') in complete_cert_aux_result'.\n  destruct_err (completion_step cert' (n - S n') op) complete_cert_aux_result c3vcs result.\n  destruct c3vcs. inversion complete_cert_aux_result.  subst.\n  assert (cert'_c3 : cert_incl cert' c3).\n   eapply step_incl.\n   eassumption.\n  assert (cert'_c' : cert_incl cert' c').\n   eapply cert_incl_trans;eauto.\n  destruct (IHn' _ _ _ cert'_c' complete_cert_aux_result') as [c'' [vcs'' [cca [incl1 [incl2 vc_in]]]]].\n   omega.\n   exists c''. exists vcs''. intuition. \n   omega.\nSave.\n\nLemma completion_step_clean : forall c c' vcs pc op limit,\n  pc < limit ->\n  completion_step c pc op = Val (c',vcs) ->\n  (forall n, n >= limit -> Cert.lookup c n = None) ->\n  (forall n, n >= limit -> Cert.lookup c' n = None).\nintros.\nunfold completion_step in H0. \ndestruct (Base.get_instruction_precondition c cp ensures ex_ensures cpa (C.precode_exception_table code) op pc) as [l|]; [|discriminate].\ndestruct (Cert.lookup c pc) as [a|].\n inversion H0. subst c'. eauto.\n inversion H0. subst c'. rewrite (Cert.indep_lookup c pc n); [auto|unfold Cert.Key.eq; omega].\nSave.\n\nLemma complete_cert_aux_clean : forall c c' vcs n ops, \n  (forall m, m >= n+length ops -> Cert.lookup c m = None) ->\n  complete_cert_aux ops c n = Val (c',vcs) -> \n  (forall m, m >= n+length ops -> Cert.lookup c' m = None).\nintros. generalize n c' vcs H H0 m H1. clear n c' vcs H H0 m H1.\ninduction ops; intros.\n (* base case *)\n discriminate.\n (* step case *)\n simpl in H0.\n destruct ops.\n  apply (completion_step_clean c c' vcs n a (n+length (a::nil))).\n   simpl. omega.\n   apply H0.\n   apply H.\n   apply H1.\n  destruct_err (complete_cert_aux (o::ops) c (S n)) H0 cert'vcs complete_cert_aux_result.\n  destruct cert'vcs as [cert' vcs'].\n  destruct_err (completion_step cert' n a) H0 cert''vcs'' completion_step_result.\n  destruct cert''vcs'' as [cert'' vcs''].\n  inversion H0. subst c'.\n   apply (completion_step_clean cert' cert'' vcs'' n a (n+length (a::o::ops))); auto.\n    simpl. omega.\n    intros. eapply (IHops (S n)); eauto.\n     intros. apply H. simpl. simpl in H3. omega.\n     simpl. simpl in H2. omega.\nSave.\n\nLemma step_ok : forall c c' vcs op pc,\n  completion_step c pc op = Val (c',vcs) ->\n  (forall f f' s, In ((f,f'),s) vcs -> AL.implies f f') ->\n  verified_instruction c' (C.precode_exception_table code) op pc.\nintros. unfold completion_step in H.\ndestruct_err (Base.get_instruction_precondition c cp ensures ex_ensures cpa (C.precode_exception_table code) op pc) H a vcgen_result.\n destruct (option_dec (Cert.lookup c pc)) as [[a' lookup_res]|lookup_res]; rewrite lookup_res in H.\n  inversion H. subst. eapply mk_verified_instruction; eauto.\n   apply Base.get_instruction_precondition_sound. eassumption.\n   eapply H0. left. reflexivity.\n  inversion H. eapply mk_verified_instruction.\n   apply Cert.lookup_update.\n   eapply Base.cert_incl_instruction_precondition.\n    apply CERT.cert_incl_update. assumption.\n    apply Base.get_instruction_precondition_sound. eassumption.\n   apply AL.implies_refl.\nSave.\n\nLemma cert_incl_safe : forall handlers c1 c2 pc op,\n   verified_instruction c1 handlers op pc -> cert_incl c1 c2 -> verified_instruction c2 handlers op pc.\nintros.\ndestruct H. \neapply mk_verified_instruction. \n  eapply cert_incl_lookup. apply H. apply H0.\n  eapply Base.cert_incl_instruction_precondition. apply H0. apply H1.\n  assumption.\nSave.\n\nLemma complete_cert_ok : forall cert' vcs,\n  complete_cert = Val (cert',vcs) ->\n  (forall f f' s, In ((f,f'),s) vcs -> AL.implies f f') ->\n  verified_precode cert'.\nintros. unfold complete_cert in H.\neapply mk_verified_code.\n (* Only the positions in the certificate are mentioned *)\n apply clean_contra. intros.\n apply (complete_cert_aux_clean (clean_cert (C.precode_annot code) (length (C.precode_code code))) cert' vcs 0 (C.precode_code code)).\n  intros. apply clean_ok. assumption.\n  apply H.\n  simpl. assumption.\n (* all instructions are safe *)\n intros.\n destruct (complete_cert_aux_prop n (C.precode_code code) _ cert' _ (nth_error_length_2 _ _ _ _ H1) H)\n  as [cert'' [vcs' [complete_cert_aux_result [cert_incl_1 [cert_incl_2 vcs_incl]]]]].\n destruct (tail_nth_error n (C.precode_code code) op H1) as [ops tail_eq].\n rewrite tail_eq in complete_cert_aux_result. simpl in complete_cert_aux_result.\n destruct ops.\n  eapply cert_incl_safe. eapply step_ok. apply complete_cert_aux_result.\n   intros. eapply H0. apply vcs_incl. apply H2.\n   apply cert_incl_2.\n  destruct_err (complete_cert_aux (o::ops) (clean_cert (C.precode_annot code) (length (C.precode_code code))) (S n))\n   complete_cert_aux_result cert''' complete_cert_aux_result'.\n  destruct cert''' as [cert''' vcs'''].\n  destruct_err (completion_step cert''' n op) complete_cert_aux_result cert'4 complete_cert_aux_result''.\n  destruct cert'4 as [cert'4 vcs'4].\n  inversion complete_cert_aux_result. subst cert'4 vcs'.\n  eapply cert_incl_safe.\n   eapply step_ok. apply complete_cert_aux_result''. intros. eapply H0. apply vcs_incl. apply List.in_or_app. left. apply H2.\n   apply cert_incl_2.\nSave.\n\nEnd CodeVerification.\n\nModule VCFacts := OrderedType.OrderedTypeFacts VCs.VerificationConditions.E.\n\nSection PreclassVerification.\n\nHypothesis pcl : C.preclass.\nHypothesis ispriv : bool.\nDefinition prooftable : ANN.ProofTable.t := fst (C.preclass_annotation pcl).\n\n(* Adapted from the full record definition in ResourceSafety. *)\nDefinition \npreclass_verified_methods : Prop :=\n(forall md pm,\n  C.has_premethod (C.preclass_methods pcl) md pm ->\n  (exists code, forall P Q X,\n    ANN.method_spec (C.premethod_annot pm) = (P, Q, X) ->\n    exists cert, exists P', exists Q',\n      C.premethod_code pm = Some code\n      /\\ ((exists g, ANN.grants (C.premethod_annot pm) = Some g /\\ ispriv = true /\\ Q' = AL.given_resexpr_have g Q)\n        \\/ (ANN.grants (C.premethod_annot pm) = None /\\ Q' = Q))\n      /\\ verified_precode (C.preclass_constantpool pcl) (snd (C.preclass_annotation pcl)) Q' X code cert\n      /\\ AL.implies P P'\n      /\\ Cert.lookup cert 0 = Some P')\n  \\/\n(* TO DO: should we check that the method is declared native rather than abstract? *)\n  (C.premethod_code pm = None /\\\n    (C.premethod_abstract pm = true \\/\n      (NTSPC.SpecTable.MapsTo (C.preclass_name pcl, (C.premethod_name pm)) (C.premethod_annot pm) NTSPC.table /\\\n        (ispriv = true \\/ ANN.grants (C.premethod_annot pm) = None)))))\n.\n\nDefinition check_method (pm : C.premethod) : error_monad (Cert.t * list method_vc) :=\n  tagfailure (err_checkmethod mlapp (B.Methodname.to_string (C.premethod_name pm)) mlapp err_sep)\n  match C.premethod_code pm with\n    | None => if C.premethod_abstract pm then ret (Cert.empty, nil) else\n      match NTSPC.SpecTable.find (C.preclass_name pcl, C.premethod_name pm) NTSPC.table with\n        | None => fail err_native_missing\n        | Some annotation =>\n          if ANN.method_annotation_eqdec annotation (C.premethod_annot pm)\n            then\n              match ANN.grants (C.premethod_annot pm) with\n                | None => ret (Cert.empty, nil)\n                | Some _ =>\n                  if ispriv then ret (Cert.empty, nil)\n                    else fail err_grants_no_privilege\n              end\n            else fail err_native_bad_spec\n      end\n    | Some code =>\n      match ANN.method_spec (C.premethod_annot pm) with (P, Q, X) =>\n        Q' <- match ANN.grants (C.premethod_annot pm) with\n                | None => ret Q\n                | Some g =>\n                  if ispriv then ret (AL.given_resexpr_have g Q)\n                    else fail err_grants_no_privilege\n              end;:\n        r <- complete_cert (C.preclass_constantpool pcl) (snd (C.preclass_annotation pcl)) Q' X code;:\n        match r with (cert,vcs) =>\n          (* Perhaps we can establish that this will never fail? *)\n          P' <- tagoptfail err_incomplete (Cert.lookup cert O);:\n          ret (cert, ((P,P'),0)::vcs)\n        end\n      end\n  end.\n\nLemma check_method_ok : forall P Q X pm cert code vcs,\n  C.premethod_code pm = Some code ->\n  ANN.method_spec (C.premethod_annot pm) = (P, Q, X) ->\n  check_method pm = Val (cert, vcs) ->\n  (forall f f' s, In ((f,f'),s) vcs -> AL.implies f f') ->\n  exists P', exists Q', C.premethod_code pm = Some code /\\\n  ((exists g, ANN.grants (C.premethod_annot pm) = Some g /\\ ispriv = true /\\ Q' = AL.given_resexpr_have g Q) \\/\n  (ANN.grants (C.premethod_annot pm) = None /\\ Q' = Q)) /\\\n  verified_precode\n  (C.preclass_constantpool pcl)\n  (snd (C.preclass_annotation pcl))\n  Q'\n  X\n  code\n  cert\n  /\\ AL.implies P P'\n  /\\ Cert.lookup cert O = Some P'.\nProof.\nintros until vcs.\nintros method_code annot check vcs_ok.\nunfold check_method in check.\nunfold tagfailure in check.\n(* We get the same code as before. *)\ndestruct (C.premethod_code pm).\ninjection method_code as codeeq'.\nrewrite codeeq' in * |- *.\nclear codeeq'.\n\nrewrite annot in * |- *.\n\ndestruct_err (match ANN.grants (C.premethod_annot pm) return error_monad AL.formula with\n                | Some g =>\n                  if ispriv\n                    then ret (T:=AL.formula) (AL.given_resexpr_have g Q)\n                    else fail (T:=AL.formula) err_grants_no_privilege\n                | None => ret (T:=AL.formula) Q\n              end) check Q' Q'eq.\ndestruct_err (complete_cert (C.preclass_constantpool pcl) (snd (C.preclass_annotation pcl)) Q' X code) check cert' certeq.\ndestruct cert' as [cert' vcs'].\ndestruct_err (tagoptfail err_incomplete (Cert.lookup cert' O)) check P' P'eq.\ninject_opttag P'eq.\ninjection check. intros vc_eq cert_eq. subst cert' vcs.\n\nexists P'. exists Q'.\nsplit; auto.\nsplit; auto.\n destruct (ANN.grants (C.premethod_annot pm)) as [g|].\n  left; exists g; intuition; destruct ispriv; [reflexivity|discriminate|injection Q'eq as Qeq; auto|discriminate].\n  injection Q'eq as Qeq; right; intuition.\nsplit. eapply complete_cert_ok; eauto.\nintros. eapply vcs_ok. right. apply H.\nsplit. eapply vcs_ok.  left. reflexivity.\nassumption.\n\ndiscriminate.\n\nSave.\n\nFixpoint testall (T:Set) (f:T -> option error) (l:list T) :=\n  match l with\n    | nil => None\n    | h::t => match f h with\n                | None => testall T f t\n                | Some e => Some e\n              end\n  end.\n\nImplicit Arguments testall [T].\n\nLemma testall_ok: forall T f l, testall (T:=T) f l = None ->\n                  forall i, In (A:=T) i l -> f i = None.\nProof.\ninduction l.\ncontradiction.\nintros code i iinl.\nsimpl in code.\ndestruct (in_inv iinl).\nrewrite H in * |- *.\ndestruct (f i).\ndiscriminate.\nreflexivity.\n\ndestruct (f a).\ndiscriminate.\napply IHl; assumption.\nSave.\n\nDefinition add_vcs (t:VCs.vcset) (vcs:list method_vc) (c:B.Classname.t) (m:B.Methodname.t):=\n  List.fold_left (fun vcs vc => match vc with (vc',s) => VCs.add_vc vcs vc' (VCs.vc_spec c m s) end) vcs t.\n\nLemma add_vcs_mono : forall l t t' c m vc,\n  add_vcs t l c m = t' ->\n  VCs.VerificationConditions.In vc t ->\n  VCs.VerificationConditions.In vc t'.\nProof.\n  induction l; intros.\n    simpl in H.\n    subst. assumption.\n\n    destruct a as [vc' src].\n    simpl in H.\n    unfold VCs.add_vc in H.\n    destruct H0 as [s0 lookup].\n    set (vc'' := VCs.simplify_vc vc') in *.\n    destruct (VCFacts.eq_dec vc vc'') as [vc_eq|vc_neq].\n      apply (VCs.VerificationConditions.MapsTo_1 (elt:=VCs.vc_sources) (m:=t) (e:=s0) vc_eq) in lookup.\n      rewrite (VCs.VerificationConditions.find_1 lookup) in H.\n      eapply IHl; eauto.\n      exists ((VCs.vc_spec c m src)::s0).\n      apply VCs.VerificationConditions.add_1.\n      apply VCs.VerificationConditions.E.eq_sym.\n      assumption.\n\n      eapply IHl; eauto.\n      unfold VCs.VerificationConditions.In.\n      eapply ex_intro.\n      apply VCs.VerificationConditions.add_2; eauto.\nQed.\n\nLemma add_vcs_ok : forall vcs t t' c m f f' src,\n  add_vcs t vcs c m = t' -> In ((f,f'),src) vcs ->\n  VCs.VerificationConditions.In (VCs.simplify_vc (f,f')) t'.\nProof.\n  induction vcs; intros.\n    destruct H0.\n\n    inversion H0.\n      subst a.\n      simpl in H.\n      eapply add_vcs_mono; eauto.\n      unfold VCs.add_vc.\n      destruct (VCs.VerificationConditions.find (VCs.simplify_vc (f, f')) t).\n        exists ((VCs.vc_spec c m src) :: v).\n        apply VCs.VerificationConditions.add_1.\n        apply VCs.VerificationConditions.E.eq_refl.\n\n        exists ((VCs.vc_spec c m src) :: nil).\n        apply VCs.VerificationConditions.add_1.\n        apply VCs.VerificationConditions.E.eq_refl.\n\n      eapply IHvcs; eauto.\n      simpl in H.\n      apply H.\nQed.\n\nDefinition check_preclass_methods : error_monad VCs.vcset :=\n  List.fold_left (fun vcs_e m =>\n    vcs <- vcs_e;:\n    r <- check_method m;:\n    match r with (cert, m_vcs) =>\n      ret (add_vcs vcs m_vcs (C.preclass_name pcl) (C.premethod_name m))\n    end) (C.preclass_methods pcl) (ret (VCs.VerificationConditions.empty VCs.vc_sources)).\n\nLemma check_preclass_methods_ok : forall vcs,\n  check_preclass_methods = Val vcs ->\n  (forall p p', VCs.VerificationConditions.In (p,p') vcs -> AL.implies p p') ->\n  preclass_verified_methods.\nProof.\n  intros vcs exec vcs_ok.\n  unfold check_preclass_methods in exec.\n  unfold preclass_verified_methods.\n  intros.\n  set (init_vcs := VCs.VerificationConditions.empty VCs.vc_sources) in *.\n  clearbody init_vcs.\n  revert init_vcs exec.\n  induction (C.preclass_methods pcl); intros.\n    inversion H.\n\n    inversion H.\n      (* This is the right method. *)\n      rewrite H3 in *.\n      subst a md.\n      simpl in exec.\n      case_eq (check_method pm).\n        intros [m_cert m_vcs] check.\n        destruct code as [code'|] _eqn: code_eq.\n          left.\n          exists code'.\n          exists m_cert.\n          eapply check_method_ok; auto. subst pm; reflexivity. eassumption.\n          intros.\n          assert (vcs_incl : VCs.VerificationConditions.In (VCs.simplify_vc (f,f')) vcs).\n            subst meths.\n            clear IHl.\n            rewrite check in exec.\n            simpl in exec.\n            set (suff_vcs := add_vcs init_vcs m_vcs (C.preclass_name pcl) (C.premethod_name pm)) in exec.\n            (* Establish that adding to the vcs now will ensure that the vc is in\n               the final result. *)\n            assert (have_vc : VCs.VerificationConditions.In (VCs.simplify_vc (f,f')) suff_vcs) by apply (add_vcs_ok _ _ _ _ _ _ _ _ (refl_equal suff_vcs) H1).\n            clearbody suff_vcs.\n            revert suff_vcs have_vc exec.\n            induction l; intros.\n              simpl in exec.\n              inject_err exec.\n              subst vcs.\n              assumption.\n\n              simpl in exec.\n              destruct (check_method a) as [[a_cert a_vcs]|].\n                simpl in exec.\n                set (new_vcs := add_vcs suff_vcs a_vcs (C.preclass_name pcl) (C.premethod_name a)) in *.\n                assert (new_vcs_is : (add_vcs suff_vcs a_vcs (C.preclass_name pcl) (C.premethod_name a) = new_vcs)) by reflexivity.\n                eapply IHl.\n                  rewrite <- H3.\n                  apply C.has_premethod_cons_1.\n\n                  eapply add_vcs_mono. apply new_vcs_is.\n                  apply have_vc.\n\n                  apply exec.\n\n                (* We have to show that failures are propogated to the end. *)\n                elimtype False.\n                clear - exec.\n                induction l.\n                  discriminate.\n\n                  apply IHl.\n                    assumption.\n\n          unfold VCs.simplify_vc in vcs_incl.\n          eapply AL.implies_trans.\n            apply (proj1 (AL.simplify_ok f)).\n            eapply AL.implies_trans.\n              eapply vcs_ok. apply vcs_incl.\n              apply (proj2 (AL.simplify_ok f')).\n\n        right. subst pm. split.\n          reflexivity.\n          unfold check_method in check. simpl in check.\n          destruct abstract; auto.\n          right.\n          simpl in *. destruct (NTSPC.SpecTable.find (C.preclass_name pcl, nm) NTSPC.table) as [spec|] _eqn:finds; try discriminate.\n          destruct (ANN.method_annotation_eqdec spec annot); try discriminate;\n          destruct (ANN.grants annot); destruct ispriv; try discriminate;\n          (split;\n            [apply NTSPC.SpecTable.find_2; rewrite finds;\n              simpl in check; inversion check; subst spec; reflexivity| tauto]).\n\n      (* Again, propogate failures. *)\n      intros.\n      rewrite H0 in *.\n      elimtype False.\n      clear - exec.\n      induction l.\n        discriminate.\n        \n        auto.\n\n\n    (* This is some other method *)\n    subst meths md m.\n    simpl in exec.\n    destruct (check_method a) as [[a_cert a_vcs]|].\n      simpl in exec.\n      eapply IHl; auto.\n        apply exec.\n\n      (* Again, propogate failures. *)\n      elimtype False.\n      clear - exec.\n      induction l; [discriminate|auto].\nQed.\n\nEnd PreclassVerification.\n\nEnd MkCodeVerifier.\n\n(*\n   Local Variables:\n   coq-prog-args: (\"-emacs-U\" \"-I\" \"..\" \"-R\" \"../ill\" \"ILL\" \"-R\" \".\" \"Verifier\")\n   End:\n   *)\n\n\n\n\n\n\n\n\n\n\n\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/GenericVerifier.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.2895980000599459}}
{"text": "(** * Definition of minimal parse trees *)\nRequire Import Coq.Strings.String Coq.Lists.List Coq.Setoids.Setoid.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.BaseTypes.\n\nLocal Coercion is_true : bool >-> Sortclass.\n\nSet Implicit Arguments.\nLocal Open Scope string_like_scope.\n\nSection cfg.\n  Context {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char} {G : grammar Char}.\n  Context {predata : @parser_computational_predataT Char}\n          {rdata' : @parser_removal_dataT' _ G predata}.\n\n  (** The [nonterminals_listT] is the current list of valid nonterminals to compare\n      against; the extra [String] argument to some of these is the\n      [String] we're using to do well-founded recursion, which the\n      current [String] must be no longer than. *)\n\n  Inductive minimal_parse_of\n  : forall (len0 : nat) (valid : nonterminals_listT)\n           (str : String),\n      productions Char -> Type :=\n  | MinParseHead : forall len0 valid str pat pats,\n                     @minimal_parse_of_production len0 valid str pat\n                     -> @minimal_parse_of len0 valid str (pat::pats)\n  | MinParseTail : forall len0 valid str pat pats,\n                     @minimal_parse_of len0 valid str pats\n                     -> @minimal_parse_of len0 valid str (pat::pats)\n  with minimal_parse_of_production\n  : forall (len0 : nat) (valid : nonterminals_listT)\n           (str : String),\n      production Char -> Type :=\n  | MinParseProductionNil : forall len0 valid str,\n                              length str = 0\n                              -> @minimal_parse_of_production len0 valid str nil\n  | MinParseProductionCons : forall len0 valid str n pat pats,\n                               length str <= len0\n                               -> @minimal_parse_of_item len0 valid (take n str) pat\n                               -> @minimal_parse_of_production len0 valid (drop n str) pats\n                               -> @minimal_parse_of_production len0 valid str (pat::pats)\n  with minimal_parse_of_item\n  : forall (len0 : nat) (valid : nonterminals_listT)\n           (str : String),\n      item Char -> Type :=\n  | MinParseTerminal : forall len0 valid str ch P,\n                         is_true (P ch)\n                         -> str ~= [ ch ]\n                         -> @minimal_parse_of_item len0 valid str (Terminal P)\n  | MinParseNonTerminal\n    : forall len0 valid str (nt : String.string),\n        @minimal_parse_of_nonterminal len0 valid str nt\n        -> @minimal_parse_of_item len0 valid str (NonTerminal nt)\n  with minimal_parse_of_nonterminal\n  : forall (len0 : nat) (valid : nonterminals_listT)\n           (str : String),\n      String.string -> Type :=\n  | MinParseNonTerminalStrLt\n    : forall len0 valid (nt : String.string) str,\n        length str < len0\n        -> is_valid_nonterminal initial_nonterminals_data (of_nonterminal nt)\n        -> @minimal_parse_of (length str) initial_nonterminals_data str (Lookup G nt)\n        -> @minimal_parse_of_nonterminal len0 valid str nt\n  | MinParseNonTerminalStrEq\n    : forall len0 str valid nonterminal,\n        length str = len0\n        -> is_valid_nonterminal initial_nonterminals_data (of_nonterminal nonterminal)\n        -> is_valid_nonterminal valid (of_nonterminal nonterminal)\n        -> @minimal_parse_of len0 (remove_nonterminal valid (of_nonterminal nonterminal)) str (Lookup G nonterminal)\n        -> @minimal_parse_of_nonterminal len0 valid str nonterminal.\n\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/MinimalParse.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.28955509466943485}}
{"text": "From iris.algebra Require Import frac.\nFrom iris.proofmode Require Import tactics.\nRequire Import Eqdep_dec List.\nFrom cap_machine Require Import rules.\nFrom cap_machine Require Export addr_reg_sample region_macros contiguous stack_macros_helpers.\nFrom cap_machine Require Export req.\n\nSection stack_macros.\n  Context {Σ:gFunctors} {memg:memG Σ} {regg:regG Σ}\n          `{MP: MachineParameters}.\n\n  (* TODO: move this to the rules_Lea.v file. small issue with the spec of failure: it does not actually\n     require/leave a trace on dst! It would be good if req_regs of a failing get does not include dst (if possible) *)\n  Lemma wp_Lea_fail_U Ep pc_p pc_g pc_b pc_e pc_a w r1 rv p g b e a z a' :\n    decodeInstrW w = Lea r1 (inr rv) →\n    isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) →\n    (a + z)%a = Some a' ->\n     (match p with\n      | URW | URWL | URWX | URWLX => (a < a')%a\n      | _ => False\n      end) ->\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 FailedV; True }}}.\n  Proof.\n    iIntros (Hdecode Hvpc Hz Hp φ) \"(>HPC & >Hpc_a & >Hsrc & >Hdst) Hφ\".\n    iDestruct (map_of_regs_3 with \"HPC Hsrc Hdst\") as \"[Hmap (%&%&%)]\".\n    iApply (wp_lea 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    destruct Hspec as [* Hsucc |].\n    { (* Success (contradiction) *) simplify_map_eq. destruct p0; try done; revert Hp H5;clear;solve_addr. }\n    { (* Failure, done *) by iApply \"Hφ\". }\n  Qed.\n\n  Definition prepstackU_instrs r (minsize paramsize: nat) :=\n    reqperm_instrs r (encodePerm URWLX) ++\n    reqsize_instrs r (minsize + paramsize) ++\n    [getb r_t1 r;\n    geta r_t2 r;\n    sub_r_z r_t2 r_t2 paramsize;\n    sub_r_r r_t1 r_t1 r_t2;\n    lea_r r r_t1;\n    move_z r_t1 0;\n    move_z r_t2 0].\n\n  Definition prepstackU r minsize paramsize a : iProp Σ :=\n    ([∗ list] a_i;w_i ∈ a;(prepstackU_instrs r minsize paramsize), a_i ↦ₐ w_i)%I.\n\n  Lemma prepstackU_spec r minsize paramsize a w pc_p pc_g pc_b pc_e a_first a_last φ :\n    isCorrectPC_range pc_p pc_g pc_b pc_e a_first a_last ->\n    contiguous_between a a_first a_last ->\n\n      ▷ prepstackU r minsize paramsize a\n    ∗ ▷ PC ↦ᵣ inr (pc_p,pc_g,pc_b,pc_e,a_first)\n    ∗ ▷ r ↦ᵣ w\n    ∗ ▷ (∃ w, r_t1 ↦ᵣ w)\n    ∗ ▷ (∃ w, r_t2 ↦ᵣ w)\n    ∗ ▷ (if isPermWord w URWLX then\n           ∃ l b e a', ⌜w = inr (URWLX,l,b,e,a')⌝ ∧\n           if (minsize + paramsize <? e - b)%Z then\n             if ((b + paramsize) <=? a')%Z then\n               ((∃ a_param, ⌜(b + paramsize)%a = Some a_param⌝ ∧\n                   PC ↦ᵣ inr (pc_p,pc_g,pc_b,pc_e,a_last) ∗ prepstackU r minsize paramsize a ∗\n                   r ↦ᵣ inr (URWLX,l,b,e,a_param) ∗ r_t1 ↦ᵣ inl 0%Z ∗ r_t2 ↦ᵣ inl 0%Z)\n                   -∗ WP Seq (Instr Executable) {{ φ }})\n             else φ FailedV\n           else φ FailedV\n         else φ FailedV)\n    ⊢\n      WP Seq (Instr Executable) {{ φ }}.\n  Proof.\n    iIntros (Hvpc Hcont) \"(>Hprog & >HPC & >Hr & >Hr_t1 & >Hr_t2 & Hφ)\".\n    iDestruct (big_sepL2_length with \"Hprog\") as %Hlength. simpl in *.\n    iAssert (⌜r ≠ PC⌝)%I as %Hne.\n    { destruct (decide (r = PC)); auto; subst. iDestruct (regname_dupl_false with \"HPC Hr\") as %Hcontr. done. }\n    (* reqperm *)\n    iPrologue_multi \"Hprog\" Hcont Hvpc link.\n    iApply (reqperm_spec with \"[$HPC $Hcode $Hr $Hr_t1 $Hr_t2 Hφ Hprog]\"); [apply Hvpc_code|apply Hcont_code|].\n    iNext. destruct (isPermWord w URWLX); auto.\n    iDestruct \"Hφ\" as (l b e a' Heq) \"Hφ\".\n    subst. iExists l,b,e,a'. iSplit; auto.\n    iIntros \"(HPC & Hprog_done & Hr & Hr_t1 & Hr_t2)\".\n    (* reqsize *)\n    iPrologue_multi \"Hprog\" Hcont Hvpc link0.\n    iApply (reqsize_spec with \"[- $HPC $Hcode $Hr $Hr_t1 $Hr_t2]\");\n      [apply Hvpc_code0|eauto|].\n    iNext. destruct (minsize + paramsize <? e - b)%Z eqn:Hsize; auto.\n    iIntros \"H\". iDestruct \"H\" as (w1 w2) \"(Hreqsize & HPC & Hr & Hr_t1 & Hr_t2)\".\n    (* getb r_t1 r *)\n    iDestruct (big_sepL2_length with \"Hprog\") as %Hlength'.\n    prep_addr_list_full l_rest0 Hcont.\n    iPrologue \"Hprog\".\n    iApply (wp_Get_success with \"[$HPC $Hi $Hr $Hr_t1]\");\n      [apply decode_encode_instrW_inv|auto|iCorrectPC link0 a_last|iContiguous_next Hcont 0|auto..].\n    iEpilogue \"(HPC & Hi & Hr & Hr_t1) /=\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* geta r_t2 r *)\n    iPrologue \"Hprog\".\n    iApply (wp_Get_success with \"[$HPC $Hi $Hr $Hr_t2]\");\n      [apply decode_encode_instrW_inv|auto|iCorrectPC link0 a_last|iContiguous_next Hcont 1|auto..].\n    iEpilogue \"(HPC & Hi & Hr & Hr_t2) /=\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* add r_t2 r_t2 paramsize *)\n    iPrologue \"Hprog\".\n    iApply (wp_add_sub_lt_success_dst_z with \"[$HPC $Hi $Hr_t2]\");\n      [apply decode_encode_instrW_inv|auto|iContiguous_next Hcont 2|iCorrectPC link0 a_last|..].\n    iEpilogue \"(HPC & Hi & Hr_t2) /=\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* sub r_t1 r_t1 r_t2 *)\n    iPrologue \"Hprog\".\n    iApply (wp_add_sub_lt_success_dst_r with \"[$HPC $Hi $Hr_t2 $Hr_t1]\");\n      [apply decode_encode_instrW_inv|auto|iContiguous_next Hcont 3|iCorrectPC link0 a_last|..].\n    iEpilogue \"(HPC & Hi & Hr_t2 & Hr_t1) /=\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* we need to distinguish between the case where the capability is stuck, or usable *)\n    assert (∃ a_param, (b + paramsize)%a = Some a_param) as [a_param Ha_param].\n    { destruct (b + paramsize)%a eqn:Hnone;eauto. exfalso. clear -Hnone Hsize. apply Z.ltb_lt in Hsize. solve_addr. }\n    assert ((a' + (b - (a' - paramsize)))%a = Some a_param) as Hlea;[clear -Ha_param; solve_addr|].\n    destruct (decide (a_param <= a')%a).\n    2: { (* lea fail *)\n      iPrologue \"Hprog\".\n      iApply (wp_Lea_fail_U with \"[$HPC $Hi $Hr_t1 $Hr]\");\n        [apply decode_encode_instrW_inv|iCorrectPC link0 a_last|apply Hlea|..].\n      { simpl. solve_addr. }\n      iEpilogue \"_ /=\". assert (b + paramsize <=? a' = false)%Z as ->;[apply Z.leb_gt;solve_addr|].\n      iApply wp_value. iApply \"Hφ\". }\n    (* lea r r_t1 *)\n    iPrologue \"Hprog\".\n    iApply (wp_lea_success_reg with \"[$HPC $Hi $Hr_t1 $Hr]\");\n      [apply decode_encode_instrW_inv|iCorrectPC link0 a_last|iContiguous_next Hcont 4|apply Hlea|auto..].\n    iEpilogue \"(HPC & Hi & Hr_t1 & Hr)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* move r_t1 0 *)\n    iPrologue \"Hprog\".\n    iApply (wp_move_success_z with \"[$HPC $Hi $Hr_t1]\");\n      [apply decode_encode_instrW_inv|iCorrectPC link0 a_last|iContiguous_next Hcont 5|auto|..].\n    iEpilogue \"(HPC & Hi & Hr_t1)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* move r_t2 0 *)\n    iPrologue \"Hprog\".\n    apply contiguous_between_last with (ai:=a5) in Hcont as Hlast;[|auto].\n    iApply (wp_move_success_z with \"[$HPC $Hi $Hr_t2]\");\n      [apply decode_encode_instrW_inv|iCorrectPC link0 a_last|apply Hlast|auto|..].\n    iEpilogue \"(HPC & Hi & Hr_t2)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    assert (b + paramsize <=? a' = true)%Z as ->;[apply Zle_is_le_bool;auto;clear -Ha_param l0;solve_addr|].\n    iApply \"Hφ\". iFrame. iExists a_param. iSplit;auto. iFrame.\n    repeat (iDestruct \"Hprog_done\" as \"[Hi Hprog_done]\"; iFrame \"Hi\").\n    iFrame \"Hprog_done\". done.\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/prepstack.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.28955509466943485}}
{"text": "From Undecidability.L Require Import LTactics Datatypes.Lists Datatypes.LNat Datatypes.LBool.\nFrom Undecidability.TM Require TM ProgrammingTools CaseList CaseBool ListTM.\n\nFrom Undecidability.TM Require Import TM_facts SizeBounds L.Transcode.BoollistEnc.\n\nFrom Undecidability.L.Complexity  Require Import UpToCNary.\n\nFrom Undecidability.L.AbstractMachines Require Import FlatPro.Programs.\n     \nUnset Printing Coercions.\n\nFrom Undecidability.TM.L Require Alphabets.\n\nFrom Coq Require Import Lia Ring Arith.\n\nFrom Undecidability Require Import TM.Code.List.Concat_Repeat.\n\nFrom Undecidability Require Import Cons_constant CaseCom CaseNat CaseList.\n\n\nSet Default Proof Using \"Type\".\n\nModule EncToBoollist.\n  Section M.\n    Import ProgrammingTools Combinators App CaseList CaseBool.\n    Import Alphabets.\n\n\n    Variable (sig : finType).\n    (* Hypothesis (defX: inhabitedC sigX). *)\n\n    (* We use the FinType instance of bool, as it has a Case-machine *)\n    \n    Context `{retr__list : Retract (sigList bool) sig}\n            `{retr__Pro : Retract Alphabets.sigPro sig}.\n\n    Local Instance retr__nat : Retract sigNat sig := ComposeRetract retr__Pro _.\n    Local Instance retr__bool : Retract bool sig := ComposeRetract retr__list (Retract_sigList_X _).\n    \n    (* Check _ : codable sig (list bool). *)\n    (* Check _ : codable sig bool. *)\n\n    (* Tapes: \n       0: compiled and encoded bs (input)\n       1: result \n       2: intern (constant for ConcatRepeat [0])\n       3: intern (length of bs for concatReepat [1])\n     *)\n\n    (* für step (prepend the bs-dependent symbols) \n               Tapes: \n       0: bs (input)\n       1: result \n       2: head of bs\n       3: intern (length of bs for concatReepat [1])\n     *)\n\n    Definition M__step : pTM sig^+ (option unit) 3 :=\n      CaseList _ ⇑ retr__Pro @ [|Fin0;Fin2|];;Reset _ @ [|Fin2|];;\n      CaseList _ ⇑ retr__Pro @ [|Fin0;Fin2|];;Reset _ @ [|Fin2|];;\n      CaseList _ ⇑ retr__Pro @ [|Fin0;Fin2|];;\n      CaseCom ⇑ ComposeRetract retr__Pro _ @ [|Fin2|];;\n      If (CaseNat ⇑ _ @ [|Fin2|])\n        (Return (Reset _ @ [|Fin2|];;\n                 CaseList _ ⇑ retr__Pro @ [|Fin0;Fin2|];;Reset _ @ [|Fin2|];;\n                 CaseList _ ⇑ retr__Pro @ [|Fin0;Fin2|];;Reset _ @ [|Fin2|]\n              ) (Some tt))\n        (Reset _ @ [|Fin2|];;\n         CaseList _ ⇑ retr__Pro @ [|Fin0;Fin2|];;Reset _ @ [|Fin2|];;\n         CaseList _ ⇑ retr__Pro @ [|Fin0;Fin2|];;Reset _ @ [|Fin2|];;\n         CaseList _ ⇑ retr__Pro @ [|Fin0;Fin2|];;\n         CaseCom ⇑ ComposeRetract retr__Pro _ @ [|Fin2|];;\n         Switch (CaseNat ⇑ _ @ [|Fin2|])\n          (fun b => Cons_constant.M b ⇑ retr__list @[|Fin1|]);;\n          Reset _ @ [|Fin2|];;\n          CaseList _ ⇑ retr__Pro @ [|Fin0;Fin2|];;Reset _ @ [|Fin2|];;\n          CaseList _ ⇑ retr__Pro @ [|Fin0;Fin2|];;Reset _ @ [|Fin2|];;\n          CaseList _ ⇑ retr__Pro @ [|Fin0;Fin2|];;Reset _ @ [|Fin2|];;\n          Return Nop (None)\n        ).\n\n    Import Hoare.\n      \n    Lemma SpecT__step :\n    { f : UpToC (fun bs => 1) &\n    forall (bs res :list bool) (n:nat),\n      TripleT \n        ≃≃([],[|Contains _ (flat_map enc_bool_perElem bs ++ enc_bool_nil ++ concat (repeat enc_bool_closing n));\n                Contains _ res;Void|])\n        (f bs)\n        M__step\n        (fun y => ≃≃([y = match bs with [] => Some tt | _ => None end]\n          ,match bs with\n          | [] => [| Contains _ (concat (repeat enc_bool_closing (n + length bs)));Contains _ res;Void |] \n          | b::bs' => [|Contains _ (flat_map enc_bool_perElem bs' ++ enc_bool_nil ++ concat (repeat enc_bool_closing n));Contains _ (b::res);Void|]\n          end)) }.\n    Proof.\n      evar (c1 : nat);evar (c2 :nat).\n      exists_UpToC (fun bs => max c1 c2). 2:now smpl_upToC_solve.\n      intros bs res n.\n      unfold M__step. rewrite app_assoc,enc_boollist_helper.\n      hstep. 3:shelve. now (hsteps_cbn;cbn;tspec_ext). cbn. hintros ? ->.\n      do 5 ((hstep;cbn);[hsteps_cbn;cbn;tspec_ext| cbn;hintros;first [ intros ? ->|intros ** ] |reflexivity]).\n      clear H.\n      refine (_ : TripleT _ (match bs with [] => _ | _ => _ end) _ _).\n      hstep.\n      -cbn;hsteps_cbn. tspec_ext. cbn. eassumption.\n      -cbn. destruct bs; hintros ?. 2:nia.\n      hsteps_cbn. now tspec_ext. 2-3:reflexivity.\n      cbn. hintros ? ->. hsteps_cbn;cbn. tspec_ext. cbn. 2-3:reflexivity. hintros ? ->.\n      now hsteps_cbn. cbn. rewrite Nat.add_0_r. tspec_ext.\n      - cbn.\n        refine (_ : TripleT _ match bs with [] => _ | b::bs => _ end _ _).\n        destruct bs; hintros ?. nia.\n        hsteps_cbn. now tspec_ext. 2-3:unfold CaseList_steps; cbn;reflexivity.\n        cbn. hintros ? ->.\n        hsteps_cbn. now tspec_ext. 2-3:unfold CaseList_steps; cbn;reflexivity.\n        cbn. hintros ? ->.\n        hsteps_cbn. now tspec_ext. 3:reflexivity.\n        2:{\n          unfold CaseList_steps,CaseList_steps_cons. rewrite Encode_Com_hasSize.\n          unfold Encode_Com_size. rewrite Encode_sum_hasSize;cbn -[\"+\" \"*\"].\n          set (m := length _). assert (m<= 2) by now (subst m;destruct b;cbn).\n          rewrite H0. reflexivity.\n        }\n        cbn. hintros ? ->.\n        hsteps_cbn;cbn. now tspec_ext. 2:reflexivity.\n        hintros y Hy.\n        destruct y.\n        {exfalso. destruct a;inv Hy. }\n        destruct Hy as (?&[=<-]).\n        hsteps_cbn;cbn.\n        now tspec_ext. 2,6,7,8:reflexivity.\n        {\n          hintros y Hy.\n          replace y with b. 2:{destruct b,y;cbn in Hy. all:easy. } clear Hy.\n          hsteps_cbn;cbn. tspec_ext.\n        }\n        {cbn. hsteps_cbn. }\n        {cbn. hsteps_cbn. cbn. reflexivity. }\n        cbn. hintros ? ->.\n        hsteps_cbn. now tspec_ext. 2,3:unfold CaseList_steps;cbn;reflexivity.\n        cbn. hintros ? ->.\n        hsteps_cbn. now tspec_ext. 2,3:unfold CaseList_steps;cbn;reflexivity.\n        cbn. hintros ? ->.\n        hsteps_cbn. 2:reflexivity.\n        tspec_ext. f_equal. unfold enc_bool_nil;cbn;autorewrite with list . reflexivity.\n      - cbn - [\"+\" \"*\"].\n        intros b Hb.\n        destruct b,bs; try (exfalso;nia). all:reflexivity.\n      Unshelve.\n      3:{\n      destruct bs.\n      + rewrite <- Nat.le_max_r. now cbv.\n      + rewrite <- Nat.le_max_l. unfold Cons_constant.time,CaseList_steps,Reset_steps.\n        ring_simplify. unshelve erewrite (_ : size (Init.Nat.pred (if b then 1 else 0))<= 1). {now destruct b;cbv. }\n        unshelve erewrite (_ : size b<= 1). {now destruct b;cbv. }\n        unfold c1. reflexivity.\n      }\n      exact 0.\n    Qed.\n\n    Arguments rcomp : simpl never.\n\n    Definition M__loop : pTM sig^+ unit 3 := While M__step.\n\n    \n    Lemma SpecT__loop :\n    { f : UpToC (fun bs => length bs + 1) &\n    forall (bs res :list bool) (n:nat),\n      TripleT \n        ≃≃([],[|Contains _ (flat_map enc_bool_perElem bs ++ enc_bool_nil ++ concat (repeat enc_bool_closing n));\n                Contains _ res;Void|])\n        (f bs)\n        M__loop\n        (fun _ => ≃≃([],[| Contains _ (concat (repeat enc_bool_closing n));Contains _  (rev bs ++res);Void |]))}.\n    Proof. \n      evar (c1 : nat);evar (c2 :nat).\n      exists_UpToC (fun bs => c1 * length bs + c2). 2:now smpl_upToC_solve.\n      intros bs res n.\n      unfold M__loop.\n      eapply While_SpecTReg with\n      (PRE := fun '(bs,res) => (_,_)) (INV := fun '(bs,res) y => (_,_)) (POST := fun '(bs,res) y => (_,_))\n        (f__step := fun '(bs,res) => _) (f__loop := fun '(bs,res) => _) (x := (bs,res));\n        clear bs res; intros (bs,res); cbn in *. eapply (projT2 SpecT__step).\n      cbn. split.\n      -intros ? Hbs. destruct bs. 2:easy.\n      cbn. split. { rewrite Nat.add_0_r. reflexivity. } rewrite Nat.mul_0_r;cbn. unfold c2;reflexivity.\n      -destruct bs. easy. intros _.\n      eexists (_,_). cbn.\n      split. reflexivity. split. 2:autorewrite with list;cbn;reflexivity.\n      rewrite UpToC_le. \n      ring_simplify.\n      [c1]:exact (1 + c__leUpToC (H:=projT1 SpecT__step)).\n      unfold c1. lia.\n    Qed.\n\n    Import ListTM.\n    \n    Definition M : pTM sig^+ unit 3 :=\n      WriteValue ( (nil:list bool)) ⇑ _ @ [|Fin1|];;\n      M__loop.\n\n  \n  \n    Lemma SpecT :\n    { f : UpToC (fun bs => length bs + 1) &\n    forall (bs :list bool),\n      TripleT \n        ≃≃([],[|Contains _ (compile (enc bs));\n                Void;Void|])\n        (f bs)\n        M\n        (fun _ => ≃≃([],[| Contains _ (concat (repeat enc_bool_closing (length bs)));Contains _  (rev bs);Void |]))}.\n    Proof.\n      unfold M.\n      eexists_UpToC f.\n      intros. rewrite enc_bool_explicit.\n      hsteps_cbn;cbn. reflexivity.\n      {\n        eapply ConsequenceT. eapply (projT2 SpecT__loop) with (n:=length bs) (res:=[]).\n        all:cbn. now tspec_ext. now rewrite app_nil_r. reflexivity.\n      }\n      [f]:intros bs. ring_simplify.\n      unfold f;reflexivity.\n      subst f.\n      smpl_upToC_solve.\n    Qed.\n    \n  End M.\nEnd EncToBoollist.\nArguments EncToBoollist.M : clear implicits.\nArguments EncToBoollist.M {_} _ _.", "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/L/Transcode/Enc_to_Boollist.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.63341027751814, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.28955509466943485}}
{"text": "(******************************************************************************\nSeptember 2004\nAuthors: Jean-Yves Vion-dury and Pierre Geneves \n\njean-yves.vion-dury@xrce.xerox.com\nWAM Research Project, INRIA Rhone-Alpes and Xerox Research Center Europe\n\npierre.geneves@inrialpes.fr\nWAM Research Project, INRIA Rhone-Alpes\n\nPlease do not reuse or publish this code without explicit consent from authors.\n*******************************************************************************)\nRequire Export XPath.\nRequire Export XPathSemantics.\nRequire Export XPequiv.\nRequire Export XPCAxioms.\nRequire Export XPathInduction.\n(* Require XPathRewritings. *)\n\nRequire Import graphInt.\nRequire Import graphProp.\n(* Require mesure. *)\n\n\nRequire Import XPequiv.\n\nParameter tree : Tree.\nRequire Import XPathGrammar.\n\nNotation \"x '∊' t\" := (XTree.g_in t x = true) (at level 0).\n\nLemma sem_decidable: \n    forall p:XPath, \n    exists x :NodeId,\n    exists y :NodeId,\n     (x∊tree) /\\\n     (y∊tree) /\\\n     ( Ƥ [p](tree, x ↝  y)  \\/  ~Ƥ [p](tree, x ↝  y) )\n.\ninduction p.\nexists 0%Z;exists 0%Z;intuition.\n[apply root_in_tree | split;[apply root_in_tree | right;simpl;auto]].\nexists root;exists root;split;[apply root_in_tree | split;\n[apply root_in_tree | left;apply rootJoinable;apply root_in_tree]].\n\nFocus.\nelim IHp1;intros x H;elim H;clear H.\nintros y [x_in_tree [y_in_tree [Ha | Ha]]].\nexists x;exists  y;split;trivial;split;trivial;left;simpl;left;trivial.\n\nelim IHp2;intros w H;elim H;clear H.\nintros z [w_in_tree [z_in_tree [Hb | Hb]]].\nexists w;exists  z;split;trivial;split;trivial;left;simpl;right;trivial.\n(* grrr.... *)\nAdmitted.\n\nConjecture sem_decidable2:\n   forall p:XPath, \n   forall x y :NodeId,\n     ( Ƥ [p](tree, x ↝  y)  \\/  ~Ƥ [p](tree, x ↝  y) )\n.\n\nLemma false_equiv_void:\n  forall p:XPath,\n  (forall x y:NodeId,\n    (x∊tree) -> (y∊tree) -> ~Ƥ [p](tree, x ↝  y) ) -> (p ⇽⇾ void)\n  .\ninduction p ;intro H.\napply Pequiv_reflexive.\nAdmitted.\n\n\nHint Rewrite [ plus_0_l plus_0_r plus_m_S plus_Snm_nSm le_S_S ] in rwNat.\nHint Rewrite <- [ max_SS ] in rwNat.\n\nLtac redNat := repeat progress (simpl;autorewrite [ rwNat]).\n\nLtac doitNat := simpl;\nmatch goal with\n| [ H: (_ + ?b) <= ?c  |-  ?a + ?b <= ?c ] \n\t=> eapply le_trans;[apply plus_le_compat_r | apply H];try doitNat\n| [ H: (_ + ?b) <= ?c  |-  ?b + _ <= ?c ] \n\t=> rewrite plus_comm ;doitNat\n| [ H: (?b + _) <= ?c  |-  ?b + _ <= ?c ] \n\t=> eapply le_trans;[apply plus_le_compat_l | apply H];try doitNat\n| [ H: (?b + _) <= ?c  |-  _ + ?b <= ?c ] \n\t=> rewrite plus_comm ; try doitNat\n\n| [ H: (max ?a _) + (max ?b _) <= ?c  |-  ?a + ?b <= ?c ] \n\t=> eapply le_trans;[apply plus_le_compat | apply H];doitNat\n| [ H: (max ?a _) + (max _ ?b ) <= ?c  |-  ?a + ?b <= ?c ] \n\t=> eapply le_trans;[apply plus_le_compat | apply H];doitNat\n| [ H: (max _ ?a ) + (max _ ?b ) <= ?c  |-  ?a + ?b <= ?c ] \n\t=> eapply le_trans;[apply plus_le_compat | apply H];doitNat\n| [ H: (max _ ?a ) + (max ?b _ ) <= ?c  |-  ?a + ?b <= ?c ] \n\t=> eapply le_trans;[apply plus_le_compat | apply H];doitNat\n\n|   |-  ?a <= max ?a _ \n\t=> apply le_max_l\n|  |-  ?a <= max _ ?a  \n\t=> apply le_max_r\n| [ H: (S ?a) <= ?c , H0: ?a  |-  _ <= ?c ] \n\t=> auto with arith\n| [ H: (S _) <= ?c  |-  _ <= ?c ] \n\t=> generalize (le_Sn_le _ _ H);intro;try doitNat\n| [ H: (S _) <= (S ?c)  |-  _ <= ?c ] \n\t=> generalize (le_S_n _ _ H);intro;try doitNat\n| _ => auto with arith\nend.\n\n(* Simplified description of Normalized terms:               *)\n(* Just capture the syntactic enbedding rules                *)\n(*                                                           *)\n(* - No left/right associativity                             *)\n(* - No partial evaluation e.g. (void|p) -> p                *)\n(* - No particular constraints on basic constituents such as *)\n(*      - axis homogeneity                                   *)\n(*      - left most position for self, top,var               *)\n(*      - unicity of self ,top                               *)\n(*      - maybe others as well...                            *)\nInductive SNf: XPath-> Prop :=\n| snf:\n    forall p:XPath,\n    (SNf_union p) ->\n    (SNf p)\n    \nwith SNf_union: XPath -> Prop :=\n| snf_union:\n    forall p1 p2:XPath,\n    (SNf_union p1) ->\n    (SNf_union p2) ->\n    (SNf_union (union p1 p2))\n| snf_union_other:\n    forall p:XPath,\n    (SNf_slash p)->\n    (SNf_union p)\n\n\nwith SNf_slash: XPath -> Prop :=\n| snf_slash:\n    (* a::N[q]/p2 *)\n    forall p1 p2:XPath,\n    (SNf_slash p1)->\n    (SNf_slash p2)->\n    (SNf_slash (slash p1 p2))\n| snf_slash_other:\n    forall p:XPath,\n    (SNf_base p)->\n    (SNf_slash p)\n\nwith SNf_base: XPath -> Prop :=\n| snf_void:\n    (SNf_base void)\n| snf_top:\n    forall q:XQualif,\n    (SNf_Q q) ->\n    (SNf_base (qualif top q))\n| snf_qualif:\n    forall (q:XQualif) (a:Axis)(n:NodeTest),\n    (SNf_Q q)->\n    (SNf_base (qualif (step a n) q))\n    \nwith SNf_Q : XQualif -> Prop :=\n| nfq:\n    forall (q:XQualif),\n    (SNf_Q_and q)->\n    (SNf_Q q)\n\nwith SNf_Q_and : XQualif  -> Prop :=\n| nfq_and:\n    forall q1 q2:XQualif,\n    (SNf_Q_and q1)->\n    (SNf_Q_and q2)->\n    (SNf_Q_and (q1 and q2))\n| nfq_and_other:\n    forall (q:XQualif),\n    (SNf_Q_not q)->\n    (SNf_Q_and q)\nwith SNf_Q_not : XQualif -> Prop :=\n| nfq_not:\n    forall (p1 p2:XPath),\n    (SNf_Q_base (leq p1 p2))->\n    (SNf_Q_not (not (leq p1 p2)))\n| nfq_not_other:\n    forall (q:XQualif),\n    (SNf_Q_base q)->\n    (SNf_Q_not q)\n    \nwith SNf_Q_base : XQualif -> Prop :=\n| snfq_true:\n    (SNf_Q_base _true)\n.\n\nHypothesis nf_always: \n  forall p:XPath, \n  exists np:XPath, \n  (p ⇽⇾ np) /\\  (SNf np) /\\  ((CXP np)<=(CXP p))\n  .\n\nDefinition Qipl_complete (q1 q2 : XQualif ) : Prop :=\n  (\n     forall x:NodeId,    \n    (x∊tree) ->  (Rq tree q1 x  -> Rq tree q2 x)\n    ) -> Qipl q1 q2\n  .\n\nDefinition Ple_complete (p1 p2 : XPath) : Prop :=\n  (\n     forall x y:NodeId,    \n    (x∊tree) ->\n    (y∊tree) ->   (Rp tree p1 x y -> Rp tree p2 x y)\n    ) ->  (Ple p1 p2)\t\n  .\n\nDefinition Pequiv_complete (p1 p2 : XPath) : Prop :=\n  (\n     forall x y:NodeId,    \n    (x∊tree) -> \n    (y∊tree) ->  (Rp tree p1 x y <-> Rp tree p2 x y)\n    ) ->  (p1 ⇽⇾ p2)\t\n  .\n\nDefinition Qequiv_complete  (q1 q2 : XQualif) : Prop :=\n  (\n    forall x:NodeId,    \n    (x∊tree) ->      (Rq tree q1 x  <-> Rq tree q2 x)\n    ) ->  (q1 ⇐⇒ q2)\t\n  .\n\n\n\n Require Export XPathGrammar.\n\nLemma completness :\n (forall p1 p2 : XPath, Ple_complete p1 p2) /\\\n (forall p1 p2 : XPath, Pequiv_complete p1 p2) /\\\n (forall q1 q2 : XQualif, Qipl_complete q1 q2) /\\\n (forall q1 q2 : XQualif, Qequiv_complete q1 q2).\n\napply HGen2222plus.\n(* forall n : nat, Hyp22 Ple_complete Qipl_comple n *)\ninduction n;unfold Hyp2222plus.\n\nFocus 2.\n simpl in IHn;unfold Hyp2222plus in IHn;split;[idtac | split;[idtac | split]];\n elim IHn; intros IHn1 [IHn2 [IHn3 IHn4]];clear IHn.\n\n  (* ------------------ Paths -------------------------- *)\n  Focus.\n    intros p1 p2; case p2. (* eight sub goals *)\n\nFocus 3.\n(* Ple_complete p1 (x ⎮ x0) *)\nintros p21 p22 H;simpl in H.\nunfold Ple_complete.\nintro Ha.\napply p_gene_L.\nassert (Nf:= (nf_always p1)).\nelim Nf;intros nf [Hb [Hc Hd]].\nexists nf;split.\nconstructor;trivial.\napply IHn1.\nFocus 2.\nintros;apply Ha;trivial.\nRequire Import XPEsound.\ngeneralize (equiv_sound _ _ Hb).\nunfold PP.\nintro.\nelim (H3 x y H0 H1);intros He Hf.\nauto.\n\nintros.\ngeneralize (sem_decidable2 p1 x y).\nintros [Ha | Ha].\nelim (H0 Ha);intro Hb.\napply p_union_R.\napply IHn1.\ngeneralize H;redNat;intro H1;doitNat.\nintro;trivial.\napply p_gene_R.\nexists (p22 ⎮ p21);split;constructor.\nconstructor.\napply IHn1.\ngeneralize H;redNat;intro H1;doitNat.\nintro;trivial.\nassert (Hb:=(false_equiv_void p1)).\n\n(* n= O *)\n split.\n  (* Paths *)\n  Focus.\n  intros p1 p2;\n  case p1;case p2;simpl;intros;try AbsurdLe;\n  unfold Ple_complete;[\n        constructor\n      | constructor\n| idtac\n(*      | intro H1;elimtype False;exact (H1 rootNotEmpty) *)\n      | intros; apply Ple_reflexive\n      ].\nintros.\nelimtype False.\ngeneralize (rootNotEmpty ctx).\nintros.\nelim H1;intros root H2.\ngeneralize (H2 ctx_in_tree);intro H3.\napply H0 ; trivial.\nrewrite (equRoot _ _ ctx_in_tree H3);exact root_in_tree.\ntrivial.\n\nsplit.\n  (* Pequiv *)\n  Focus.\n  intros p1 p2;\n  case p1;case p2;simpl;intros;try AbsurdLe;\n  unfold Pequiv_complete; try (intros;apply Pequiv_reflexive).\n\n  intro Ha;elim (Ha ctx root ctx_in_tree root_in_tree);\n  intros _ Hc;elimtype False;apply Hc;apply rootJoinable;apply ctx_in_tree.\n\n  intro Ha;elim (Ha ctx root ctx_in_tree root_in_tree);\n  intros Hc _;elimtype False;apply Hc;apply rootJoinable;apply ctx_in_tree.\n\nsplit.\n  (* Qualifiers *)\n  Focus.\n  intros q1 q2;\n  case q1;case q2;simpl;intros;try AbsurdLe;unfold Qipl_complete;try constructor.\n  intro H1;elimtype False.\n  apply (H1 ctx ctx_in_tree);simpl;trivial.\n\n  (* Qequiv *)\n  Focus.\n  intros q1 q2;\n  case q1;case q2;simpl;intros;try AbsurdLe;unfold Qequiv_complete;try (intros;apply Qequiv_reflexive).\n   intro Ha;elim (Ha ctx ctx_in_tree);\n  intros Hc _;elimtype False;apply Hc;simpl;trivial.\n\n   intro Ha;elim (Ha ctx ctx_in_tree);\n  intros _ Hc ;elimtype False;apply Hc;simpl;trivial.\n\n(* n= (S k) *)\n simpl in IHn;unfold Hyp2222plus in IHn;split;[idtac | split;[idtac | split]];\n elim IHn; intros IHn1 [IHn2 [IHn3 IHn4]];clear IHn.\n\n  (* ------------------ Paths -------------------------- *)\n  Focus.\n    intros p1 p2; case p2. (* eight sub goals *)\n\nFocus 3.\n(* Ple_complete p1 (x ⎮ x0) *)\n\nintros p21 p22 H;simpl in H;unfold Ple_complete;intro Hcomp.\ngeneralize (sem_decidable p1).\nintros [x [ y [ x_in_tree [ y_in_tree [Ha | Ha]] ] ] ].\n\nelim (Hcomp _ _ x_in_tree y_in_tree Ha);intro Hb.\nconstructor.\napply IHn1.\ngeneralize H;redNat;intro H0;doitNat.\n\nFocus 7.\ncase p1.\n\nFocus 3.\n(* Ple_complete (x ⎮ x0) (a :: n0) *)\nsimpl;intros p11 p12 a N H;unfold Ple_complete;intros.\nconstructor.\napply IHn1.\n\ndoitNat.\nintros;apply H0;trivial.\nsimpl;left;trivial.\n\napply IHn1.\ndoitNat.\nintros;apply H0;trivial.\nsimpl;right;trivial.\n\nFocus 10.\n(* Ple_complete (x / x0) (a :: n0) *)\nsimpl;intros p11 p12 a N H;unfold Ple_complete.\ncase a.\nintros.\nconstructor.\n\nsimpl.\napply\n\n\nFocus 5.\ncase p1.\nFocus 5.\nintros p21 p22 H;simpl in H;unfold Ple_complete;intro Hcomp.\nconstructor.\nconstructor.\napply IHn1.\n\ngeneralize H;redNat;intro H0;doitNat.\n\nintros x y x_in_tree y_in_tree Ha.\nsimpl in IHp1_1;unfold Ple_complete in IHp1_1.\n\ngeneralize (Hcomp x ctx x_in_tree ctx_in_tree).\nsimpl.\nintros.\n\nFocus 3.\n(* Ple_complete p1 (x ⎮ x0) *)\n\nintros p21 p22 H;simpl in H;unfold Ple_complete;intro Hcomp.\ngeneralize (nf_always p1);intros [np [Ha Hb]].\napply p_gene_L.\nexists np;split;trivial.\ninversion Hb.\ninversion H0.\n\ninduction p1.\nFocus 3.\nconstructor.\napply IHp1_1.\ngeneralize H;redNat;intro.\ndoitNat.\n\n\nconstructor.\napply IHn1.\n\n    (* void p2 *)\n    constructor.\n\nFocus 4.\n(* -----------------------------------------------------------*)\n(* Ple_complete (x / x0) p2 *)\n(* -----------------------------------------------------------*)\nintros p11 p12 p2;case p2.\n\nFocus 3.\n(* Ple_complete (p11 / p12) (x ⎮ x0) *)\nunfold Ple_complete.\nintros p21 p22 H HCompl;simpl in H.\n\nelim (HCompl ctx ctx ctx_in_tree ctx_in_tree Ha).\n\nconstructor.\napply IHn1.\n\nsimpl;generalize (le_S_n _ _ H);rewrite plus_m_S.\ncase n.\nintro Ha;inversion Ha.\nintros n0 Ha;apply le_n_S;generalize (le_S_n _ _ Ha);intro Hb;eapply le_trans;[ idtac | apply Hb];\napply plus_le_compat_l;auto with arith.\n\nintros x y x_in_tree y_in_tree Ha.\nelim (HCompl x y x_in_tree y_in_tree Ha).\n\n\ncut ( (p11 / p12 ≤ p21) \\/ (p11 / p12 ≤ p22)).\nintros [Ha | Ha];[constructor;trivial | apply p_gene_R].\nexists (p22 ⎮  p21);split;constructor;trivial;constructor.\n\n\n(* Ple_complete (p11 / p12) (⊥) *)\nunfold Ple_complete.\nintros H HCompl;simpl in H.\nconstructor || apply p_gene_L;exists void;split;constructor.\neapply Pequiv_trans with (p2:=void/p12 ).\neapply equ_s_slash_L.\n\nsimpl in H.\nsimpl in HCompl.\n\n    (* top p2 *)\n    Focus.\n    induction p2.\n    Focus 3.\nunfold Ple_complete in IHp2_1, IHp2_2 |- *.\nsimpl.\nintros H H0.\ngeneralize (H0 x root).\nrewrite (rootOfTree x x_is_a_node).\nrewrite ZSet.single_sem.\nintros H1;cut (true=true);[intro H2 | reflexivity].\nelim (H1 H2);intro Ha.\n\napply p_union_R.\napply IHp2_1.\nsimpl;rewrite le_S_S in H.\ngeneralize (max_le_L _ _ _ H);auto with arith.\nintros x y Hb;simpl in Hb.\nrewrite  (rootOfTree x x_is_a_node) in Hb;rewrite (ZSet.in_single _ _ Hb).\nintros x y H3;elim (H0 x y);trivial.\nintros Ha [Hb | Hb].\napply H0;trivial.\n\nunfold Ple\n    intro p2; case p2; simpl in |- *. (* seven sub goals *)\n        \n\t  (* top void *)\n\t  unfold Ple_complete in |- *;intros _ H;elimtype False.\nsimpl in H;eapply H.\n\n;exact (H rootNotEmpty).\n\t (* top top *)\n\t  constructor.\n\t (*top (union x x0) *)\n\t  intros pp1 pp2 H; unfold Ple_complete in |- *; intro H1;\n\t  elim (H1 rootNotEmpty);intro H2;[\n\t      apply c2;\n\t      apply IHn1;[\n\t          apply le_S_n; eapply max_le_L;rewrite max_SS in H;apply H\n\t\t| trivial\n\t\t]\n\t    | apply p_gene_R;exists (union pp2 pp1);split;\n\t      [\n\t          apply c2;apply IHn1;[ \n                             simpl;apply le_S_n;rewrite max_SS in H;eapply max_le_R;apply H \n                           | trivial \n                           ]\n\t\t| (* (Pequiv (union x0 x) (union x x0)) *)\n\t\t  apply comm_union\n\t      ] \n\t    ].\n\n\t(*top (inter x x0) *)\n\t  intros pp1 pp2 H;unfold Ple_complete;intro H1;apply i2;\n\t  apply IHn1;[\t      \n\t        simpl;apply le_S_n; eapply max_le_L;rewrite max_SS in H;apply H\n\t      | intro H2;assert(HH:=H1 H2);simpl in HH;elim HH;trivial\n\t      | simpl;apply le_S_n; eapply max_le_R;rewrite max_SS in H;apply H\n\t      | intro H2;assert(HH:=H1 H2);simpl in HH;elim HH;trivial\n\t      ].\n\t (*top (slash x x0) *)\n\t  unfold Ple_complete in |- *; intros.\nFocus.\napply top_slash;split;apply IHn1.\nsimpl;LeS;simpl in H;eapply max_le_L;apply H.\nintro H1;elim (H0 H1).\nintros x2 [H2 H3].\nsimpl in H1.\nsimpl \ninduction x0.\n(* top void/x1 ------------------------------------------------------------*)\nelim (H0 rootNotEmpty);intros xx [ H1 H2];inversion H1.\n\n(* top <= top/x1 ------------------------------------------------------------*)\n    Focus 1.\n    induction x1.\n    (* top <= top/void *)\n    elim (H0 rootNotEmpty);intros xx [ H1 H2];inversion H2.\n    (* top <= top/top *)    \n    apply p_gene_L.\n    exists (slash top top) ;split;[ apply Ple_reflexive | idtac].\n    eapply Pequiv_trans.\n    rewrite Pequiv_sym;apply equ_top_qualif_top.\n    rewrite Pequiv_sym;apply equ_top_slash.\n    simpl;trivial.\n    (* top <= top/(x11| x12 *)\n    assert (H1:=H0 rootNotEmpty);elim H1;intros x0 [H2 H3].\n    elim H3;intro H4.\n   (* left branch      H4 : Rp tree x1_1 x0 y    *) \n   apply p_gene_R; exists (union (slash top x1_1) (slash top x1_2)).\n    split.\n    apply c2.\n    apply IHx1_1.\n    simpl;LeS;simpl in H;apply le_n_S;assert (H5:= le_Smn_mn _ _ H);eapply max_le_L; apply H5.\n    intro H5;simpl;exists x0;split;trivial.\n    rewrite Pequiv_sym; apply equ_d_slash_union_R.\n  (* right branch      H4 : Rp tree x1_2 x0 y    *) \n   apply p_gene_R; exists (union (slash top x1_1) (slash top x1_2)).\n    split.\n    apply p_gene_R;exists (union (slash top x1_2) (slash top x1_1));split;[apply c2 | apply comm_union].\n    apply IHx1_2.\n    simpl;LeS;simpl in H;apply le_n_S;assert (H5:= le_Smn_mn _ _ H);eapply max_le_R; apply H5.\n    intro H5;simpl;exists x0;split;trivial.\n    rewrite Pequiv_sym; apply equ_d_slash_union_R.\n    (* top <= top/(x11 & x12 *)\n    Focus.\n    assert (H1:=H0 rootNotEmpty);elim H1;intros x0 [H2 H3].\n    elim H3;intros H4 H4b.\n   apply p_gene_R; exists (inter (slash top x1_1) (slash top x1_2)).\n   split.\n   apply i2; simpl in H.\n   apply IHx1_1.\n   simpl;LeS;apply le_n_S;assert (H5:= le_Smn_mn _ _ H);eapply max_le_L; apply H5.\n   intro H5;simpl;exists x0;split;trivial.\n   apply IHx1_2.\n   simpl;LeS;apply le_n_S;assert (H5:= le_Smn_mn _ _ H);eapply max_le_R; apply H5.\n   intro H5;simpl;exists x0;split;trivial.\n   rewrite Pequiv_sym; constructor.  \n    (* top <= top/(x11| x12 *)\n    Focus.\n    assert (H1:=H0 rootNotEmpty);elim H1;intros x0 [H2 H3].\n    elim H3;intros y0 [ H4 H5 ].\n \n\n    assert (H1:=H0 rootNotEmpty);\n\t  exists (slash top top); split.\n\t      (* Ple (slash top top) (slash x x0) *)\n          apply d2;apply IHn1.\n          simpl; apply le_S_n;eapply max_le_L;rewrite max_SS in H;apply H.\n          intro H1;elim (H0 H1).\n          intros x2 [H2];intro H3.\n          apply H1.\n\n         [\n\t      (* Ple (slash top top) (slash x x0) *)\n\t      \n\t    | (* Pequiv top (slash top top) *)\n\t  ].\n\t  \n\t(*top (qualif x x0) *)\n\t(*top (step a n0) *)\t  \n\t\n   <Your Tactic Text here>\n   <Your Tactic Text here>\n   intros x0 x1 p2; case p2.\n    simpl in |- *.\n      <Your Tactic Text here>\n    <Your Tactic Text here>\n    <Your Tactic Text here>\n    <Your Tactic Text here>\n    intros x2 x3.\n      simpl in |- *.\n      unfold Ple_complete in |- *.\n      intros.\n      constructor.\n     constructor.\n      apply IHn1.\n       <Your Tactic Text here>\n       <Your Tactic Text here>\n      <Your Tactic Text here>\n     <Your Tactic Text here>\n    <Your Tactic Text here>\n    <Your Tactic Text here>\n   <Your Tactic Text here>\n   <Your Tactic Text here>\n   (*------------------------- Qualifiers ------------------  *)\n  <Your Tactic Text here>\n\nAbort.\n\n\n\n\t\t\t    \n\t\t\t   \n", "meta": {"author": "mattam82", "repo": "typex", "sha": "37a01ce082e63a304fddadbc60ec281057fa6e1a", "save_path": "github-repos/coq/mattam82-typex", "path": "github-repos/coq/mattam82-typex/typex-37a01ce082e63a304fddadbc60ec281057fa6e1a/theories/XPath/SXPath/Containment/XPCcomplete.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.28955509466943485}}
{"text": "From VT Require Export natutil.\nFrom VT Require Export Map.\nFrom VT Require Export Mapt.\nFrom VT Require Export Machine.\nFrom VT Require Export cap.\nFrom VT Require Export xcap.\n\n(* =======lifting CAP assertions and specifications======== *)\n\n(** | a | <==> lambda S. << a S >> *)\nDefinition Trans (a : cap.Assertion) s := << a s >>.\n\nNotation \"| a |\" := (Trans a) (at level 130).\n\n(** [{f1 := a1,..., fn := an}] <==> {f1 := [a1],..., fn := [an]} *)\nDefinition TranS (Fi : cap.CdHpSpec) l :=\n  match Fi l with\n  | Some _ P => Some _ (| P |)\n  | None _ => None _\n  end.\n\nNotation \"|\\ Si |\\\" := (TranS Si) (at level 130).\n\nLemma SubsumptionPsv :\n  forall a a',\n  (a ==>cap a') -> \n  ((| a |) ==>xcap | a' |).\nProof.\n  simpl. auto. Qed.\n\n\n(** This axiom assumes that the code heap specification is finite, which is\n   not reflected in the current encoding of mapping. In future revision we\n   will change it and remove this axiom. *)\nAxiom FiniteSpec :\n  forall Si : cap.CdHpSpec,\n  exists l : _, (forall l', l <= l' -> Mapt.not_in_dom Si l').\n\n\n(** theorem 1: if Si |-cap{a} I \n               then || Si || |-xcap{|a|} I *)\nTheorem InstrSeqWFPsv : \n  forall Si a I, \n  (Si |-cap{ a}I) -> \n  ((|\\ Si |\\) |-xcap{ |a |}I).\nProof.\n(*   intros. induction H.\n  { apply wfiseq with (|a' |); auto. }\n  { apply wfbgti with (|a' |) (|a'' |); auto.\n    unfold TranS, Mapt.lookup in *. rewrite H2. auto. }\n  { apply wfjd with (|a' |); auto.\n    unfold Mapt.lookup, TranS in *. rewrite H. auto. }\n  { destruct (FiniteSpec Si).\n    cut (forall S Si',\n          (.[[(| a |) S]] Si') ->\n          exists a',\n            (if ble_nat x ((fun S : State => let (_, R) := S in R) S r)\n             then .[[ cptr ((fun S : State => let (_, R) := S in R) S r) a' ]] Si'\n             else Mapt.lookup (|\\ Si |\\) ((fun S : State => let (_, R) := S in R) S r) a') /\\\n             (.[[ a' S ]] Si')).\n } *)\nAdmitted.\n\n(** theorem 2: if Si_IN |-cap C \n               then || Si_IN || |-xcap{C} || Si || *)\nTheorem CodeHeapWFPsv :\n  forall C Si Si', \n  (Si |-cap C ::: Si') ->\n  ((|\\ Si |\\) |-xcap C ::: (|\\ Si' |\\)).\nProof. Admitted.\n\n\n(** theorem 3: if Si_G |-cap{a} P\n               then || Si_G || |-xcap{|a|} P *)\nTheorem ProgramWFPsv :\n  forall Si a P,\n  (Si |-cap[ a ]P) ->\n  ((|\\ Si |\\) |-xcap[ | a | ]P).\nProof. Admitted.\n\n", "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/midterm-xcap/cap2xcap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.28954855019366094}}
{"text": "Require Export unscoped header_extensible.\nRequire Export termsyntax.\n\nSection form_atomic.\nContext {Sigma : Signature}.\n\nVariable form : Type.\n\nVariable subst_form : forall   (sigmaterm : ( fin ) -> term ) (s : form ), form .\n\nVariable idSubst_form : forall  (sigmaterm : ( fin ) -> term ) (Eqterm : forall x, sigmaterm x = (var_term ) x) (s : form ), subst_form sigmaterm s = s.\n\nVariable ext_form : forall   (sigmaterm : ( fin ) -> term ) (tauterm : ( fin ) -> term ) (Eqterm : forall x, sigmaterm x = tauterm x) (s : form ), subst_form sigmaterm s = subst_form tauterm s.\n\nVariable compSubstSubst_form : forall    (sigmaterm : ( fin ) -> term ) (tauterm : ( fin ) -> term ) (thetaterm : ( fin ) -> term ) (Eqterm : forall x, ((funcomp) (subst_term tauterm) sigmaterm) x = thetaterm x) (s : form ), subst_form tauterm (subst_form sigmaterm s) = subst_form thetaterm s.\n\nInductive form_atomic  : Type :=\n  | Pred : forall (p : Preds), ( vect term (pred_ar p) ) -> form_atomic .\n\nVariable retract_form_atomic : retract form_atomic form.\n\nDefinition Pred_ (p : Preds) (s0 : vect term (pred_ar p)) : _ :=\n  inj (Pred p s0).\n\nLemma congr_Pred_ { p : Preds }  { s0 : vect term (pred_ar p) } { t0 : vect term (pred_ar p) } (H1 : s0 = t0) : Pred_  p s0 = Pred_  p t0 .\nProof. congruence. Qed.\n\n(* Variable retract_ren_form : forall   (xiterm : ( fin ) -> fin) s, ren_form xiterm (inj s) = ren_form_atomic xiterm s. *)\n\nDefinition subst_form_atomic   (sigmaterm : ( fin ) -> term ) (s : form_atomic ) : form  :=\n    match s return form  with\n    | Pred  p s0 => Pred_  p ((vect_map (subst_term sigmaterm)) s0)\n    end.\n\nVariable retract_subst_form : forall   (sigmaterm : ( fin ) -> term ) s, subst_form sigmaterm (inj s) = subst_form_atomic sigmaterm s.\n\nDefinition idSubst_form_atomic  (sigmaterm : ( fin ) -> term ) (Eqterm : forall x, sigmaterm x = (var_term ) x) (s : form_atomic ) : subst_form_atomic sigmaterm s = inj s :=\n    match s return subst_form_atomic sigmaterm s = inj s with\n    | Pred  p s0 => congr_Pred_ ((vect_id (idSubst_term sigmaterm Eqterm)) s0)\n    end.\n\n(* \nDefinition ext_form_atomic   (sigmaterm : ( fin ) -> term ) (tauterm : ( fin ) -> term ) (Eqterm : forall x, sigmaterm x = tauterm x) (s : form_atomic ) : subst_form_atomic sigmaterm s = subst_form_atomic tauterm s :=\n    match s return subst_form_atomic sigmaterm s = subst_form_atomic tauterm s with\n    | Pred  p s0 => congr_Pred_ ((vect_ext (ext_term sigmaterm tauterm Eqterm)) s0)\n    end.\n*)\nDefinition compSubstSubst_form_atomic    (sigmaterm : ( fin ) -> term ) (tauterm : ( fin ) -> term ) (thetaterm : ( fin ) -> term ) (Eqterm : forall x, ((funcomp) (subst_term tauterm) sigmaterm) x = thetaterm x) (s : form_atomic ) : subst_form tauterm (subst_form_atomic sigmaterm s) = subst_form_atomic thetaterm s :=\n    match s return subst_form tauterm (subst_form_atomic sigmaterm s) = subst_form_atomic thetaterm s with\n    | Pred  p s0 => (eq_trans) (retract_subst_form (_) (Pred p (_))) (congr_Pred_ ((vect_comp (compSubstSubst_term sigmaterm tauterm thetaterm Eqterm)) s0))\n    end.\n(*\nLemma instId_form_atomic  : subst_form_atomic (var_term ) = inj .\nProof. exact ((FunctionalExtensionality.functional_extensionality _ _ ) (fun x => idSubst_form_atomic (var_term ) (fun n => eq_refl) ((id) x))). Qed.\n\nLemma compComp_form_atomic    (sigmaterm : ( fin ) -> term ) (tauterm : ( fin ) -> term ) (s : form_atomic ) : subst_form tauterm (subst_form_atomic sigmaterm s) = subst_form_atomic ((funcomp) (subst_term tauterm) sigmaterm) s .\nProof. exact (compSubstSubst_form_atomic sigmaterm tauterm (_) (fun n => eq_refl) s). Qed.\n\nLemma compComp'_form_atomic    (sigmaterm : ( fin ) -> term ) (tauterm : ( fin ) -> term ) : (funcomp) (subst_form tauterm) (subst_form_atomic sigmaterm) = subst_form_atomic ((funcomp) (subst_term tauterm) sigmaterm) .\nProof. exact ((FunctionalExtensionality.functional_extensionality _ _ ) (fun n => compComp_form_atomic sigmaterm tauterm n)). Qed.\n\nDefinition isIn_form_form_atomic (s : form) (t : form_atomic) : Prop :=\n  match t with\n  | Pred t0  => False\n  end.\n *)\n\nEnd form_atomic.\n", "meta": {"author": "ralvrz", "repo": "ModularFOL", "sha": "400fc000889a34b66cf6adec0caf205714eef547", "save_path": "github-repos/coq/ralvrz-ModularFOL", "path": "github-repos/coq/ralvrz-ModularFOL/ModularFOL-400fc000889a34b66cf6adec0caf205714eef547/atomicsyntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.28951001779225}}
{"text": "From iVM Require Export Machine Extras.Mon.\nFrom RecordUpdate Require Import RecordSet.\n\n(** The purpose of this file is to prove the (rather trivial) fact that\nthe initial error state monad over the obvious record type does indeed\nsatisfy the constraints in [MachineParams1].*)\n\nRecord State :=\nmkState {\n  state_memory: Memory;\n  state_pc: Addr;\n  state_sp: Addr;\n  state_inp: N;\n  state_image: Image (option OutputColor);\n  state_bytes: list Byte;\n  state_chars: list Char;\n  state_sound: Sound;\n  state_log: list OutputFrame;\n}.\nInstance etaState : Settable _ :=\n  settable! mkState <state_memory;\n                     state_pc;\n                     state_sp;\n                     state_inp;\n                     state_image;\n                     state_bytes;\n                     state_chars;\n                     state_sound;\n                     state_log>.\n\nLocal Ltac crush :=\n  let s := fresh in try split; intro s; intros; destruct s; reflexivity.\n\nLocal Ltac derive_lens f :=\n  refine {|\n      proj := f;\n      update s m := set f (fun _ => m) s;\n  |}; crush.\n\nDefinition MEM : Lens State Memory. derive_lens state_memory. Defined.\nDefinition PC : Lens State Addr. derive_lens state_pc. Defined.\nDefinition SP : Lens State Addr. derive_lens state_sp. Defined.\nDefinition INP : Lens State N. derive_lens state_inp. Defined.\nDefinition OUT_CHARS : Lens State (list Char). derive_lens state_chars. Defined.\nDefinition OUT_BYTES : Lens State (list Byte). derive_lens state_bytes. Defined.\nDefinition OUT_SOUND : Lens State Sound. derive_lens state_sound. Defined.\nDefinition OUT_IMAGE : Lens State (Image (option OutputColor)). derive_lens state_image. Defined.\nDefinition LOG : Lens State (list OutputFrame). derive_lens state_log. Defined.\n\nInstance independent_MEM_IMAGE: Independent MEM OUT_IMAGE. crush. Defined.\nInstance independent_MEM_BYTES: Independent MEM OUT_BYTES. crush. Defined.\nInstance independent_MEM_CHARS: Independent MEM OUT_CHARS. crush. Defined.\nInstance independent_MEM_SOUND: Independent MEM OUT_SOUND. crush. Defined.\nInstance independent_MEM_LOG:   Independent MEM LOG. crush. Defined.\nInstance independent_MEM_INP:   Independent MEM INP. crush. Defined.\nInstance independent_MEM_PC:    Independent MEM PC. crush. Defined.\nInstance independent_MEM_SP:    Independent MEM SP. crush. Defined.\n\nInstance independent_IMAGE_BYTES: Independent OUT_IMAGE OUT_BYTES. crush. Defined.\nInstance independent_IMAGE_CHARS: Independent OUT_IMAGE OUT_CHARS. crush. Defined.\nInstance independent_IMAGE_SOUND: Independent OUT_IMAGE OUT_SOUND. crush. Defined.\nInstance independent_IMAGE_LOG:   Independent OUT_IMAGE LOG. crush. Defined.\nInstance independent_IMAGE_INP:   Independent OUT_IMAGE INP. crush. Defined.\nInstance independent_IMAGE_PC:    Independent OUT_IMAGE PC. crush. Defined.\nInstance independent_IMAGE_SP:    Independent OUT_IMAGE SP. crush. Defined.\n\nInstance independent_BYTES_CHARS: Independent OUT_BYTES OUT_CHARS. crush. Defined.\nInstance independent_BYTES_SOUND: Independent OUT_BYTES OUT_SOUND. crush. Defined.\nInstance independent_BYTES_LOG:   Independent OUT_BYTES LOG. crush. Defined.\nInstance independent_BYTES_INP:   Independent OUT_BYTES INP. crush. Defined.\nInstance independent_BYTES_PC:    Independent OUT_BYTES PC. crush. Defined.\nInstance independent_BYTES_SP:    Independent OUT_BYTES SP. crush. Defined.\n\nInstance independent_CHARS_SOUND: Independent OUT_CHARS OUT_SOUND. crush. Defined.\nInstance independent_CHARS_LOG:   Independent OUT_CHARS LOG. crush. Defined.\nInstance independent_CHARS_INP:   Independent OUT_CHARS INP. crush. Defined.\nInstance independent_CHARS_PC:    Independent OUT_CHARS PC. crush. Defined.\nInstance independent_CHARS_SP:    Independent OUT_CHARS SP. crush. Defined.\n\nInstance independent_SOUND_LOG: Independent OUT_SOUND LOG. crush. Defined.\nInstance independent_SOUND_INP: Independent OUT_SOUND INP. crush. Defined.\nInstance independent_SOUND_PC:  Independent OUT_SOUND PC. crush. Defined.\nInstance independent_SOUND_SP:  Independent OUT_SOUND SP. crush. Defined.\n\nInstance independent_LOG_INP: Independent LOG INP. crush. Defined.\nInstance independent_LOG_PC:  Independent LOG PC. crush. Defined.\nInstance independent_LOG_SP:  Independent LOG SP. crush. Defined.\n\nInstance independent_INP_PC: Independent INP PC. crush. Defined.\nInstance independent_INP_SP: Independent INP SP. crush. Defined.\n\nInstance independent_PC_SP: Independent PC SP. crush. Defined.\n\nInstance concreteParams1 : MachineParams1 :=\n{\n    State := State;\n\n    MEM := MEM;\n    PC := PC;\n    SP := SP;\n\n    INP := INP;\n\n    OUT_CHARS  := OUT_CHARS ;\n    OUT_BYTES  := OUT_BYTES ;\n    OUT_SOUND  := OUT_SOUND ;\n    OUT_IMAGE  := OUT_IMAGE ;\n\n    LOG := LOG;\n\n    independent_MEM_IMAGE := independent_MEM_IMAGE;\n    independent_MEM_BYTES := independent_MEM_BYTES;\n    independent_MEM_CHARS := independent_MEM_CHARS;\n    independent_MEM_SOUND := independent_MEM_SOUND;\n    independent_MEM_LOG := independent_MEM_LOG;\n    independent_MEM_INP := independent_MEM_INP;\n    independent_MEM_PC := independent_MEM_PC;\n    independent_MEM_SP := independent_MEM_SP;\n\n    independent_IMAGE_BYTES := independent_IMAGE_BYTES;\n    independent_IMAGE_CHARS := independent_IMAGE_CHARS;\n    independent_IMAGE_SOUND := independent_IMAGE_SOUND;\n    independent_IMAGE_LOG := independent_IMAGE_LOG;\n    independent_IMAGE_INP := independent_IMAGE_INP;\n    independent_IMAGE_PC := independent_IMAGE_PC;\n    independent_IMAGE_SP := independent_IMAGE_SP;\n\n    independent_BYTES_CHARS := independent_BYTES_CHARS;\n    independent_BYTES_SOUND := independent_BYTES_SOUND;\n    independent_BYTES_LOG := independent_BYTES_LOG;\n    independent_BYTES_INP := independent_BYTES_INP;\n    independent_BYTES_PC := independent_BYTES_PC;\n    independent_BYTES_SP := independent_BYTES_SP;\n\n    independent_CHARS_SOUND := independent_CHARS_SOUND;\n    independent_CHARS_LOG := independent_CHARS_LOG;\n    independent_CHARS_INP := independent_CHARS_INP;\n    independent_CHARS_PC := independent_CHARS_PC;\n    independent_CHARS_SP := independent_CHARS_SP;\n\n    independent_SOUND_LOG := independent_SOUND_LOG;\n    independent_SOUND_INP := independent_SOUND_INP;\n    independent_SOUND_PC := independent_SOUND_PC;\n    independent_SOUND_SP := independent_SOUND_SP;\n\n    independent_LOG_INP := independent_LOG_INP;\n    independent_LOG_PC := independent_LOG_PC;\n    independent_LOG_SP := independent_LOG_SP;\n\n    independent_INP_PC := independent_INP_PC;\n    independent_INP_SP := independent_INP_SP;\n\n    independent_PC_SP := independent_PC_SP;\n}.\n\nInstance concreteParams2 : MachineParams2 :=\n{\n    M := EST State;\n    H_mon := est_smonad State;\n}.\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/Extras/Machine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.2893892667300823}}
{"text": "From Undecidability.L.Tactics Require Import LTactics GenEncode.\nFrom Undecidability.L.Datatypes Require Import LNat Lists LProd LFinType LVector.\nFrom Undecidability.L Require Import Functions.EqBool.\n\nFrom Undecidability.TM.Util Require Import VectorPrelim TM_facts.\n\nRequire Import Undecidability.Shared.Libs.PSL.FiniteTypes.FinTypes.\nFrom Undecidability.TM Require PrettyBounds.SizeBounds.\n\n\nImport L_Notations.\n\n(* ** Extraction of Turing Machine interpreter  *)\n\nImport GenEncode.\nMetaCoq Run (tmGenEncodeInj \"move_enc\" move).\nHint Resolve move_enc_correct : Lrewrite.\n\nImport TM.\nLocal Notation L := TM.Lmove.\nLocal Notation R := TM.Rmove.\nLocal Notation N := TM.Nmove.\n\nDefinition move_eqb (m n : move) : bool :=\n  match m,n with\n    N,N => true\n  | L,L => true\n  | R,R => true\n  | _,_ => false\n  end.\n\nLemma move_eqb_spec x y : reflect (x = y) (move_eqb x y).\nProof.\n  destruct x, y;constructor. all:easy.\nQed.\n\n\nInstance eqb_move:\n  eqbClass move_eqb.\nProof.\n  intros ? ?. eapply move_eqb_spec.\nQed.\n\n\nInstance eqbComp_bool : eqbCompT move.\nProof.\n  evar (c:nat). exists c. unfold move_eqb.\n  unfold enc;cbn.\n  extract.\n  solverec.\n  [c]:exact 3.\n  all:unfold c;try lia.\nQed.\n\n(*\nDefinition move_decode (s : term) : option (move) :=\n  match s with\n  | lam (lam (lam n)) =>\n    match n with\n      2 => Some TM.L \n    | 1 => Some TM.R\n    | 0 => Some TM.N\n    | _ => None\n    end\n  | _ => None\n  end.\n\nInstance decode_move: decodable move.\nProof.\n  exists move_decode.\n  all:unfold enc at 1. all:cbn.\n  -destruct x;reflexivity.\n  -destruct t eqn:eq. all:cbn.\n   all:repeat let eq := fresh in destruct _ eqn:eq. all:try congruence.\n   all:intros ? [= <-]. all:reflexivity.\nDefined. (* because instance *) *)\n\n(* *** Encoding Tapes *)\nSection reg_tapes.\n  Variable sig : Type.\n  Context `{reg_sig : encodable sig}.\n\n  \n  Implicit Type (t : TM.tape sig).\n  Import GenEncode.\n  MetaCoq Run (tmGenEncode \"tape_enc\" (TM.tape sig)).\n  Hint Resolve tape_enc_correct : Lrewrite.\n\n  Global Instance encInj_tape_enc {H : encInj reg_sig} : encInj (encodable_tape_enc).\n  Proof. register_inj. Qed. \n\n  (*Internalize constructors **)\n\n  Global Instance term_leftof : computableTime' (@leftof sig) (fun _ _ => (1, fun _ _ => (1,tt))).\n  Proof.\n    extract constructor.\n    solverec.\n  Qed.\n\n  Global Instance term_rightof : computableTime' (@rightof sig) (fun _ _ => (1, fun _ _ => (1,tt))).\n  Proof.\n    extract constructor. solverec.\n  Qed.\n\n  Global Instance term_midtape : computableTime' (@midtape sig) (fun _ _ => (1, fun _ _ => (1,fun _ _ => (1,tt)))).\n  Proof.\n    extract constructor. solverec.\n  Qed.\n  \nEnd reg_tapes.\n\n\nSection fix_sig.\n  Variable sig : finType.\n  Context `{reg_sig : encodable sig}.\n\n\n  Definition mconfigAsPair {B : finType} {n} (c:mconfig sig B n):= let (x,y) := c in (x,y).\n\n  Global Instance encodable_mconfig (B : finType) `{encodable B} n: encodable (mconfig sig B n).\n  Proof using reg_sig.\n    eapply (registerAs mconfigAsPair).\n  Defined.\n\n  Global Instance term_mconfigAsPair (B : finType) `{encodable B} n: computableTime' (@mconfigAsPair B n) (fun _ _ => (1,tt)).\n  Proof.\n    apply cast_computableTime.\n  Qed.\n\n  Global Instance term_cstate (B : finType) `{encodable B} n: computableTime' (@cstate sig B n) (fun _ _ => (7,tt)).\n  Proof.\n    apply computableTimeExt with (x:=fun x => fst (mconfigAsPair x)).\n    2:{extract. solverec. }\n    intros [];reflexivity.\n  Qed.\n\n  Global Instance term_ctapes (B : finType) `{encodable B} n: computableTime' (@ctapes sig B n) (fun _ _ => (7,tt)).\n  Proof.\n    apply computableTimeExt with (x:=fun x => snd (mconfigAsPair x)).\n    2:{extract. solverec. }\n    intros [];reflexivity.\n  Qed.\n\n  Global Instance encodable_mk_mconfig (B : finType) `{encodable B} n: computableTime' (@mk_mconfig sig B n) (fun _ _ => (1,fun _ _ => (3,tt))).\n  Proof.\n    computable_casted_result.\n    extract. solverec.\n  Qed.\nEnd fix_sig.\n\nHint Resolve tape_enc_correct : Lrewrite.\n\nImport PrettyBounds.SizeBounds.\n\nLemma sizeOfTape_by_size {sig} `{encodable sig} (t:(tape sig)) :\n  sizeOfTape t <= size (enc t).\nProof.\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.\nQed.\n\nLemma sizeOfmTapes_by_size {sig} `{encodable sig} n (t:tapes sig n) :\n  sizeOfmTapes t <= size (enc t).\nProof.\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. rewrite vector_to_list_correct. apply sumn_map_le_pointwise. intros. nia.\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/TMEncoding.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2893892526779403}}
{"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 color.\nRequire Import geometry.\nRequire Import coloring.\nRequire Import patch.\nRequire Import cfmap.\nRequire Import quiz.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(* Compile the quiz that tests for the occurrence of a configuration. Since *)\n(* this requires to compute arities, we also check that the arity of ring   *)\n(* regions are in the [3,6] range along the way. The procedure here is      *)\n(* valid, but not complete, e.g., it assumes that skews only occur at       *)\n(* articulations. The configuration data has been carefully knobbed to meet *)\n(* those constraints.                                                       *)\n(*   The algorithm proceeds by walking the map construction program         *)\n(* backwards, keeeping track of kernel faces and of arities on the submap   *)\n(* ring. During the traversal a list of questions is kept, that covers      *)\n(* exactly the kernel faces that are disjoint from the current submap ring. *)\n(* Each of these question is rooted at (node (ic x)) for some dart x of the *)\n(* submap ring, where ic is the injection from the current submap to the    *)\n(* full configuration map (crucially, this implies that \"node\" is computed  *)\n(* in the full map). As the ring shrinks, questions are linked to form      *)\n(* trees, until we arrive at the initial two-dart graph, where we have just *)\n(* questions, which form a proper quiz.                                     *)\n(*   H-type steps could be somewhat of a problem for this algorithm, but it *)\n(* turns out that (with a little fiddling) in all the programs we consider, *)\n(* we never need to join trees in an H step, so the code below doesn't      *)\n(* cater to that case (we'd need to generate more LL and RR questions).     *)\n\n(* We use a single sequence of records rather that three parallel sequences. *)\n\nRecord ring_question : Set := RingQuestion {\n  ring_question_is_kernel : bool;\n  ring_question_outer_arity :> nat;\n  ring_question_node_question :> question\n}.\n\nSection ConfigQuiz.\n\nNotation isk := ring_question_is_kernel.\n\nRemark ringQuestionDataP : comparable ring_question.\nProof. rewrite /comparable; decide equality; apply: comparable_data. Qed.\nDefinition ringQuestionData := Eval compute in compareData ringQuestionDataP.\nCanonical Structure ringQuestionData.\nLet rqseq : Set := seq ringQuestionData.\n\n(* We only compile questions for maps with kernel arities between 5 an 11; in *)\n(* fact only the most central face (the one to which the \"true\" dart of the   *)\n(* central submap belongs) can have more that 8 sides. We check and use this  *)\n(* fact during the compilation. We also check that the ring arities are in    *)\n(* the 3..6 range; this property allows us to lift the preembedding           *)\n(* constructed in quiz.v into an actual embedding (see embed.v).              *)\n(* All the functions below work with the arities offset by two, because each  *)\n(* time a face is detached from the submap, if had at least two neighbors in  *)\n(* that submap.                                                               *)\n\nDefinition small_qarity a :=\n  match a with\n  | 3 => Qa5\n  | 4 => Qa6\n  | 5 => Qa7\n  | 6 => Qa8\n  | 7 => Qa10\n  | _ => Qa9\n  end.\n\nDefinition bad_small_arity qa :=\n  match qa with\n  | Qa9 => true\n  | Qa10 => true\n  | Qa11 => true\n  | _ => false\n  end.\n\nLemma small_qarityP : forall a,\n  let qa := small_qarity a in bad_small_arity qa = negb ((qa : nat) =d S (S a)).\nProof. do 8 case=> //. Qed.\n\nDefinition large_qarity a :=\n  match a with\n  | 7 => Qa9\n  | 8 => Qa10\n  | 9 => Qa11\n  | _ => small_qarity a\n  end.\n\nDefinition bad_ring_arity a :=\n  match a with\n  | O => true\n  | S (S (S (S (S _)))) => true\n  | _ => false\n  end.\n\nLemma not_bad_ring_arity : forall (g : hypermap) (x : g),\n  bad_ring_arity (pred (pred (arity x))) = false -> good_ring_arity x.\nProof. move=> g x; rewrite /good_ring_arity; move: (arity x); do 7 case=> //. Qed.\n\n(* Error value. *)\nLet noquiz := Quiz Qask0 Qask0.\n\n(* The quiz construction proper.                                               *)\n\nDefinition rqs_Y rq1 rq3 (qs : rqseq) q1' : rqseq :=\n  let: RingQuestion k1 a1 _ := rq1 in\n  let: RingQuestion k3 a3 q3 := rq3 in\n  Seq (RingQuestion k1 (S a1) q1') (RingQuestion k3 (S a3) q3) & qs.\n\nDefinition cfquiz_Y rq1 rq2 rqs' : rqseq :=\n  let: RingQuestion _ _ q1 := rq1 in\n  let: RingQuestion k2 a2 q2 := rq2 in\n  if k2 then\n    let qa2 := small_qarity a2 in\n    if bad_small_arity qa2 then seq0 else\n    rqs' match q1, q2 with\n        | Qask0, Qask0 => Qask1 qa2\n        | Qask0, _ => QaskL qa2 q2\n        | _, Qask0 => QaskR qa2 q1\n        | _, _ => QaskLR qa2 q2 q1\n        end\n   else\n    if bad_ring_arity a2 then seq0 else\n    match q1, q2 with\n    | Qask0, Qask0 => rqs' Qask0\n    | QaskR qa1 q1r, Qask0 => rqs' (QaskRR qa1 q1r)\n    | Qask0, QaskL qa1 q1l => rqs' (QaskLL qa1 q1l)\n    | _, _ => seq0\n    end.\n\nDefinition rqs_H rq1 rq3 (qs : rqseq) q1' q2' : rqseq :=\n  let: RingQuestion k1 a1 _ := rq1 in\n  let: RingQuestion k3 a3 q3 := rq3 in\n  Seq (RingQuestion k1 (S a1) q1')\n      (RingQuestion true 1 q2')\n      (RingQuestion k3 (S a3) q3)\n   & qs.\n\nDefinition cfquiz_H rq1 rq2 rqs' : rqseq :=\n  let: RingQuestion k1 _ q1 := rq1 in\n  let: RingQuestion k2 a2 q2 := rq2 in\n  if k2 then\n    let qa2 := small_qarity (S a2) in\n    if bad_small_arity qa2 then seq0 else\n    match q1, q2, k1 with\n    | Qask0, Qask0, true => rqs' (Qask1 qa2) q2\n    | Qask0, Qask0, _ => rqs' q1 (Qask1 qa2)\n    | Qask0, _, _ => rqs' q1 (QaskL qa2 q2)\n    | _, Qask0, _ => rqs' (QaskR qa2 q1) q2\n    | _, _, _ => seq0\n    end\n  else\n    if bad_ring_arity (S a2) then seq0 else\n    match q1, q2 with\n    | Qask0, Qask0 => rqs' q1 q2\n    | _, _ => seq0\n    end.\n\nFixpoint cfquiz_rec (qs : rqseq) (cp : cprog) {struct cp} : quiz :=\n  match cp, qs with\n  | seq0, (Seq rq1 rq2 & _) =>\n    let: RingQuestion k1 a1 q1 := rq1 in\n    let: RingQuestion k2 a2 q2 := rq2 in\n    if negb (k1 && k2) then noquiz else\n    let qa1 := large_qarity (pred a1) in\n    let qa2 := small_qarity (pred a2) in\n    if negb ((qa1 : nat) =d S a1) || bad_small_arity qa2 then noquiz else\n    Quiz (QaskR qa1 q2) (QaskR qa2 q1)\n  | Adds s cp', (Seq rq1 rq2 rq3 & qs') =>\n    match s with\n    | CpR n => cfquiz_rec (rotr n qs) cp'\n    | CpY => cfquiz_rec (cfquiz_Y rq1 rq2 (rqs_Y rq1 rq3 qs')) cp'\n    | CpH => cfquiz_rec (cfquiz_H rq1 rq2 (rqs_H rq1 rq3 qs')) cp'\n    | _ => noquiz\n    end\n  | _, _ =>\n    noquiz\n  end.\n\nSection RqsWalk.\n\nVariables (g0 g : pointed_map) (h : g -> g0).\n\nFixpoint rqs_fit (qs : rqseq) (p : seq g) {struct p} : bool :=\n  match qs, p with\n  | Adds rqd qs', Adds x p' =>\n    let rq := rqd : ring_question in\n    and3b (arity (h x) =d rq + arity x) (fitq (node (h x)) rq) (rqs_fit qs' p')\n  | seq0, seq0 => true\n  | _, _ => false\n  end.\n\nLemma rqs_fit_adds : forall (rq : ring_question) qs x p,\n rqs_fit (Adds rq qs) (Adds x p) =\n   and3b (arity (h x) =d rq + arity x) (fitq (node (h x)) rq) (rqs_fit qs p).\nProof. done. Qed.\n\nLemma rqs_fit_size : forall qs p, rqs_fit qs p -> size qs = size p.\nProof. elim=> [|rq qs Hrec] [|x p] //=; case/and3P=> *; congr S; auto. Qed.\n\nFixpoint rqs_walk (qs : rqseq) (p : seq g0) {struct p} : seq g0 :=\n  match qs, p with\n  | Adds rqd qs', Adds u p' =>\n    let rq := rqd : ring_question in\n    cat (cat (seqn (isk rq) u) (walkq (node u) rq)) (rqs_walk qs' p')\n  | _, _ => seq0\n  end.\n\nLemma rqs_walk_adds : forall (rq : ring_question) qs u p,\n rqs_walk (Adds rq qs) (Adds u p) =\n   cat (cat (seqn (isk rq) u) (walkq (node u) rq)) (rqs_walk qs p).\nProof. done. Qed.\n\nDefinition rqs_ok (qs : rqseq) :=\n  let r0 := cpring g0 in let r := cpring g in let hr := maps h r in\n  and4 (rqs_fit qs r)\n       (sub_set (setD r0 (setU (codom h) (fband hr))) good_ring_arity)\n       (simple (cat (rqs_walk qs hr) r0))\n       (fband (cat (rqs_walk qs hr) r0) =1 setU (setC (codom h)) (fband hr)).\n\nEnd RqsWalk.\n\n(* We check separately the radius of the configuration (the initial face *)\n(* of the quiz might not be at the center of the kernel).                *)\n\nFixpoint cpradius2 (cp : cprog) (i : nat) {struct i} : bool :=\n  if i is S i' then\n    let cm0 := cpmask1 cp i' in\n    let: Cpmask mr1 _ := cm0 in\n    let: Cpmask _ mk1 := cpadj cm0 cp in\n    let: Cpmask _ mk2 := cpadj (Cpmask mr1 mk1) cp in\n    if all id mk2 then true else cpradius2 cp i'\n  else false.\n\nVariable cf : config.\n\nLet cp : cprog := cfprog cf.\n\nDefinition cfquiz : quiz :=\n  if cpradius2 cp (cpksize cp) then\n    cfquiz_rec (seqn (cprsize cp) (RingQuestion false 0 Qask0)) cp\n  else noquiz.\n\nHypothesis Hqz : isQuizR cfquiz.\n\nRemark Cfquiz_Hcfk2 : cpradius2 cp (cpksize cp).\nProof. by move: Hqz; rewrite /cfquiz; case (cpradius2 cp (cpksize cp)). Qed.\nNotation Hcfk2 := Cfquiz_Hcfk2.\n\nRemark Cfquiz_qs0_notR : forall cp' : cprog, isQuizR (cfquiz_rec seq0 cp') = false.\nProof. by elim=> //; case. Qed.\nNotation qs0_notR := Cfquiz_qs0_notR.\n\nRemark Cfquiz_Hcp : config_prog cp.\nProof.\npose qs := seqn (cprsize cp) (RingQuestion false 0 Qask0).\nhave Hcp: setC1 seq0 cp by case: cp Hcfk2.\nhave Eqs: size qs = cprsize cp by rewrite /qs size_seqn.\nmove: Hcp Eqs Hqz; rewrite /cfquiz Hcfk2 -/qs.\nelim: cp qs => // [s cp' Hrec] [|rq1 [|rq2 [|rq3 qs]]] //= _.\ncase: s cp' Hrec => //= [n||] [|s cp'] // H Eqs Hqs; apply: H (Hqs) => //.\n- by rewrite -Eqs size_rotr.\n- move: Hqs; rewrite /cfquiz_Y -(eq_add_S _ _ Eqs).\n  case: rq1 rq2 rq3 => [k1 a1 q1] [[|] a2 q2] [k3 a3 q3].\n    by case: (bad_small_arity (small_qarity a2)); first by rewrite qs0_notR.\n  case: (bad_ring_arity a2); first by rewrite qs0_notR.\n  by case: q1; rewrite ?qs0_notR //; case: q2; rewrite ?qs0_notR.\nmove: Hqs; rewrite /cfquiz_H -Eqs.\ncase: rq1 rq2 rq3 => [k1 a1 q1] [[|] a2 q2] [k3 a3 q3].\ncase: (bad_small_arity (small_qarity (S a2))); first by rewrite qs0_notR.\n  by case: q1; rewrite ?qs0_notR //; case: q2; rewrite ?qs0_notR //; case k1.\n  case: (bad_ring_arity (S a2)); first by rewrite qs0_notR.\nby case: q1; rewrite ?qs0_notR //; case: q2; rewrite ?qs0_notR.\nQed.\nLet Hcp := Cfquiz_Hcp.\n\nRemark Cfquiz_Hrad2 : radius2 (kernel (cfring cf)).\nProof.\nrewrite /cfring /cfmap -/cp.\nelim: {-2}(cpksize cp) (leqnn (cpksize cp)) Hcfk2 => //= [i Hrec] Hi.\nmove: (proper_cpmask1 cp i) (cpsieve1 Hi Hcp); set g := cpmap cp.\nset cm0 := cpmask1 cp i; set x0 := sub g (cpker cp) i => Hcm0 Ecm0.\ncase: (cpadj cm0 cp) (cpadj_proper Hcm0) (cpsieve_adj Hcp Hcm0) => mr1 mk1.\nmove/andP=> [_ Hmk1] Ecm1 /=; rewrite {}Ecm0 in Ecm1; set cm1 := Cpmask _ mk1.\nhave Hcm1: proper_cpmask cp cm1 by rewrite /= size_seqn set11.\ncase: (cpadj cm1 cp) (cpadj_proper Hcm1) (cpsieve_adj Hcp Hcm1) => mr2 mk2.\nmove/andP=> [_ Emk2] Ecm2.\ncase Hmk2: (all (@id bool) mk2); last by apply: Hrec; apply ltnW.\nclear; clear Hrec; set kg := kernel _.\nhave Dkg: kg =1 fband (cpker cp).\n  move=> x; move: (cpmap_simple Hcp) (cpmap_cover Hcp x).\n  rewrite simple_cat fband_cat -/g orbC; move/and3P=> [_ Ug _].\n  rewrite /kg /kernel /setC fband_rev.\n  case Hx: (@fband g (cpker cp) x); last by move=> *; apply/idP.\n  case/hasP: Hx => [y Hy Hxy] _;  rewrite (closed_connect (fbandF _) Hxy) -/g.\n  by apply: (hasPn Ug).\nhave Hx0: kg x0.\n  rewrite Dkg; apply: (subsetP (ring_fband _)); apply: mem_sub.\n  by rewrite (size_cpker Hcp).\napply/(radius2P _); exists x0; first done.\nmove=> x Hx; apply/(at_radius2P (g := g) (a := kg) (kernelF _) _ _).\nhave Hx': has (adj x) (cpsieve cm1 cp).\n  rewrite -Ecm2 /= fband_cat; apply/orP; right.\n  suffice <-: cpker cp = sieve mk2 (cpker cp) by rewrite -Dkg.\n  move: Hmk2 Emk2; rewrite -(size_cpker Hcp).\n  by elim: (mk2) (cpker cp) => [|[|] m Hrec] [|y p] //= Hm Em; rewrite -Hrec.\ncase/hasP: Hx' => [y Hy]; case/adjP=> [z Hxz Hzy].\nrewrite /cm1 /= sieve_false /= in Hy.\nhave Hez: (has (adj (edge z)) (seq1 x0)).\n  by rewrite -Ecm1 /= fband_cat; apply/orP; right; apply/hasP; exists y.\nrewrite has_seq1 Sadj in Hez; last by apply: cpmap_plain; apply config_prog_cubic.\ncase/adjP: Hez => [t Hx0t Htz]; exists t; exists z; split; auto; rewrite Dkg.\nby apply/hasP; exists y; [ exact (mem_sieve Hy) | rewrite (same_cface Htz) ].\nQed.\nNotation Hrad2 := Cfquiz_Hrad2.\n\nLemma cfquizP :\n      sub_set (cpring (cpmap cp)) good_ring_arity\n  /\\ (exists x0, valid_quiz (cpring (cpmap cp)) x0 cfquiz).\nProof.\nmove: Hqz; rewrite /cfquiz Hcfk2 -[cpmap cp]/(cpmap (catrev cp seq0)).\nset qs := seqn (cprsize cp) _; set cp1 : cprog := seq0; set cp2 := cp.\nhave Hcp1: cubic_prog cp1 by done.\nhave Hcp2: setU1 seq0 config_prog cp2 by apply setU1r.\nhave Arec: rqs_ok (@injcp cp1 cp2) qs.\n  rewrite /cp2; set g := cpmap cp; set r := cpring g.\n  have Dq0: rqs_walk qs r = seq0.\n    by rewrite /qs -size_ring_cpmap -/g -/r; elim: r => //= *.\n  have Hd0: codom (fun x : g => x) =1 g.\n     by move=> x; apply/set0Pn; exists x; apply/eqP.\n  split; rewrite //= ?maps_id -/g -/r ?{}Dq0 /qs //=.\n  - by rewrite -size_ring_cpmap -/g -/r; elim: r => //= *; rewrite set11.\n  - by move=> x; rewrite /setD /setU Hd0.\n  - by move: (cpmap_simple Hcp); rewrite -/g -/r simple_cat; case/andP.\n  by move=> x; rewrite /setU /setC Hd0.\nelim: cp2 Hcp2 cp1 Hcp1 qs Arec => [|s cp2 Hrec] Hscp2 cp1 Hcp1 qs Arec Hqz'.\n  case: Arec Hqz'; set g := cpmap seq0; set g0 := cpmap (catrev seq0 cp1).\n  set r := cpring g; set r0 := cpring g0; set h := @injcp cp1 seq0.\n  have EhE: forall x, edge (h x) = h (edge x) by move=> x; apply: edge_injcp.\n  move=> Hr Hr0F Uq Eq; case Dqs: qs Hr => [|[[|] a1 q1] [|[[|] a2 q2] qs']] //=.\n  case/and5P; rewrite addnC (addnC a2) /addn /= small_qarityP.\n  set qa1 := large_qarity (pred a1); case: ((qa1 : nat) =P S a1) => //.\n  case: a2 Dqs => [|a2] Dqs //; rewrite /pred; set qa2 := small_qarity a2.\n  case: ((qa2 : nat) =P S (S a2)) => // [<-] <- Eqa1 Hq1 Eqa2 Hq2.\n  case: qs' Dqs => //= Dqs _ _; split.\n    move=> u Hu; apply: Hr0F; rewrite /setD Hu andbT /setU orbC /g0 /g.\n    case Hu': (fband (maps h r) u); rewrite /fband -/g0 -/g in Hu' |- *.\n      move: Uq; rewrite simple_cat; case/and3P; clear; case/hasP.\n      exists u; first done; rewrite Dqs /= fband_cat /=; case/hasP: Hu' => v.\n      by case/mapsP=> [[|] _ <-] Hu'; rewrite Hu' ?orbT.\n    apply/set0Pn => [] [x Du]; case/hasP: Hu'; exists u; last exact: connect0.\n    by rewrite (eqP Du); apply maps_f; case x.\n  set qz := Quiz _ _.\n  have Eqz: fband (walkqz (h false) qz) =1 fband (rqs_walk qs (maps h r)).\n    move=> u; rewrite /qz Dqs /= /qstepR !EhE /= !fband_cat /= cats0.\n    by repeat BoolCongr.\n  exists (h false); repeat split.\n  - rewrite /fitqz /qz /= eqseq_adds fitq_cat /qstepR !EhE /= eqseq_adds.\n    by rewrite eqd_sym Eqa1 Hq2 eqd_sym Eqa2.\n  - rewrite /g0 (simple_perm Eqz).\n      by move: Uq; rewrite simple_cat; case/and3P.\n    by rewrite /qz Dqs /= cats0 !size_cat /= !addnS addnC /qstepR !EhE.\n  move=> u; rewrite Eqz; apply/idP/idP => Hu.\n    move: Uq; rewrite simple_cat; case/and3P=> [_ Uq _].\n    apply/hasP => [[v Hv Huv]]; case/hasP: Uq; exists v; first done.\n    by rewrite -(fun q0 => closed_connect (fbandF q0) Huv).\n  move: (Eq u); rewrite fband_cat (negbE Hu) orbF /setU /setC /g0 /g => ->.\n  case Hu': (codom h u); last done; apply/hasP; exists u; last exact: connect0.\n  by case/set0Pn: Hu' => [x Du]; rewrite (eqP Du); apply maps_f; case x.\nhave [Hcp2 Hscp1]: setU1 seq0 config_prog cp2 /\\ cubic_prog (Adds s cp1).\n  by case: (s) Hscp2 Hqz' => //=; case cp2; split.\nmove: {Hrec Hscp1}(Hrec Hcp2 _ Hscp1) => Hrec; simpl in Hrec; move: Hrec Arec Hqz'.\ncase Dqs: qs => [|rq1 [|rq2 [|rq3 qs']]] //; rewrite -Dqs.\nset h := @injcp cp1 _; set g' := cpmap (Adds s cp2).\nset g := cpmap cp2; set r := cpring g.\nhave Hh: injective h by apply: injcp_inj.\nhave EhE: forall x, edge (h x) = h (edge x) by move=> x; apply: edge_injcp.\nhave EhN: forall x, negb (cpring g' x) -> node (h x) = h (node x).\n  by move=> x; apply: node_injcp.\nhave EhF: forall x y, cface (h x) (h y) = cface x y.\n  by move=> x y; apply: cface_injcp.\nmove: (cpmap (catrev (Adds s cp2) cp1)) h Hh EhE EhN EhF {Hcp1} => g0.\nset r0 := cpring g0; rewrite {}/g'; rewrite /setU1 orFb in Hscp2.\nhave Ur: simple r.\n  rewrite /r /g; case/setU1P: Hcp2 => [<-|Hcp2] //.\n  by move: (cpmap_simple Hcp2); rewrite simple_cat; case/and3P.\npose simq q q' (u : g0) := flatq q = flatq q' /\\ walkq u q = walkq u q'.\npose selq q q' q'' : question := if q is Qask0 then q' else q''.\ncase: s Hscp2 (config_prog_cubic Hscp2) {Hcp2} => // [n||] Hscp2 Hcp2;\n  rewrite /cpmap -/cpmap -/g -/r; move=> h Hh EhE EhN EhF Hrec [].\n- rewrite cpring_ecpR -/r -/r0 /= !maps_rot; simpl in h; set hr := maps h r.\n  rewrite Dqs -Dqs => Hr Hr0 Uq Eq; apply: Hrec.\n  pose r1 := take n r; pose r2 := drop n r.\n  rewrite /rotr (rqs_fit_size Hr) size_rot -size_drop -/r2 /rot.\n  set qs1 := drop _ qs; set qs2 := take _ qs.\n  have [Hqs1 Hqs2]: rqs_fit (fun x => h x) qs1 r1 /\\ rqs_fit (fun x => h x) qs2 r2.\n    apply: andP; move: Hr; rewrite /rot -/r1 -/r2 /qs1 /qs2 andbC.\n    elim: (r2) (qs) {qs' Dqs} => [|x r2' Hrec] [|rq qs']; rewrite // ?cats0 //=.\n    by move/and3P=> [Ha Hq Hqs]; rewrite Ha Hq /=; auto.\n  pose pq2 := rqs_walk qs2 (maps h r2); pose m2 := size pq2.\n  pose pq1 := rqs_walk qs1 (maps h r1); pose qs12 := cat qs1 qs2.\n  have Dpq': rqs_walk qs12 hr = rot m2 (rqs_walk qs (rot n hr)).\n    transitivity (cat pq1 pq2).\n      rewrite /hr -(cat_take_drop n r) -/r1 -/r2 {}/qs12 {}/pq1.\n      elim: (r1) qs1 Hqs1 => [|x r1' Hrec] [|rq qs1] //=.\n      by move/and3P=> [_ _ Hqs]; rewrite Hrec ?catA.\n    rewrite -rot_size_cat {}/m2; congr rot.\n    move: Hqs2; rewrite /hr -maps_rot /rot /pq1 /pq2 /qs1 /qs2 -/r1 -/r2.\n    elim: (r2) (qs) {qs' Dqs} => [|x r' Hrec] [|rq qs'] //=.\n    by case/and3P=> *; rewrite -Hrec ?catA.\n  have Ehr: maps (fun x => h x) r = hr by apply: eq_maps.\n  split; auto; rewrite -/r -/r0 ?Ehr -/qs12.\n  + rewrite -(cat_take_drop n r) -/r1 -/r2 /qs12.\n    elim: (r1) (qs1) Hqs1 => [|x r1' Hrec] [|rq qs1'] //=.\n    by move/and3P=> [Ha Hq Hqs]; rewrite Ha Hq /=; auto.\n  + move=> u Hu; apply: Hr0; apply: etrans Hu; congr andb.\n    by rewrite /setU fband_rot.\n  + by rewrite Dpq' {1}/rot -catA simple_catCA catA cat_take_drop.\n  by move=> u; rewrite fband_cat Dpq' fband_rot -fband_cat Eq /setU fband_rot.\n- simpl in Hcp2; have Hgp := cpmap_proper Hcp2; rewrite -/g in Hgp.\n  have HgE := cpmap_plain Hcp2; have Hg'E := plain_ecpY g HgE.\n  rewrite -/r0; set rY := maps h _; set pY := cat _ r0.\n  set u0 : ecpY g := ecpY g; set nu0 := node u0.\n  have Hnu0: cface nu0 (icpY g (node g)) by apply: cface_node_ecpY.\n  pose h' x := h (icpY g x); pose rY' := maps h' r.\n  have ErY: fband rY =1 fband (Adds (h u0) rY').\n    move=> u; rewrite /rY' /r head_cpring /rY cpring_ecpY -/u0 -/nu0 /= orbCA.\n    rewrite -maps_comp; do 2 congr orb.\n    by rewrite /h' !(Sface _ u); apply: same_cface; rewrite EhF.\n  rewrite -/r; pose r' := drop 2 r; pose au0 := seq2 (node g) g.\n  have Eau0: arity u0 = 2 by apply: (@order_cycle _ _ (traject face u0 2)).\n  have Eag: forall x, arity (icpY g x) = fband au0 x + arity x.\n    pose bu0 := maps edge (orbit face u0).\n    have Ebu0: fband bu0 =1 fband (maps (icpY g) au0).\n      move=> u; rewrite /au0 -adj_ecpY // /bu0 /fband has_maps.\n      by apply: eq_has => v; rewrite /comp Sface.\n    move=> x; rewrite /order -(cardIC bu0); congr addn.\n      rewrite setI_cface_simple.\n        congr nat_of_bool; rewrite Ebu0 /fband has_maps; apply: eq_has.\n        exact: cface_icpY.\n      rewrite (simple_perm Ebu0); last by rewrite /bu0 !size_maps size_orbit.\n      rewrite (simple_maps (cface_icpY g)).\n      rewrite /r (head_proper_cpring Hgp) -(cat1s g) -cat_adds seq2I in Ur.\n      by rewrite simple_cat in Ur; case/and3P: Ur.\n    rewrite -(card_image (@icpY_inj _ g)); apply: eq_card => u.\n    apply/andP/set0Pn => [[Hux Hu]|[y]].\n      have Hu0u: negb (cface u0 u).\n        by rewrite Sface -(same_cface Hux) Sface /u0 cface_ecpY.\n      rewrite /u0 cface_ecpY -/u0 in Hu0u.\n      rewrite /bu0 /orbit -/(arity u0) Eau0 in Hu.\n      case: u Hu Hu0u Hux => //; case=> // [y] _ _ Hxy; exists y.\n      by rewrite /setI /preimage set11 -(cface_icpY g).\n    case/andP; rewrite /preimage; move/eqP=> Du; rewrite Du cface_icpY.\n    by split; first done; rewrite /bu0 /orbit -/(arity u0) Eau0.\n  rewrite Dqs => Hqs Hr0 UpY EpY /=.\n  move DcqY: (rqs_Y _ _ _) => cqY; move DqsY: (cfquiz_Y _ _ _) => qsY.\n  case: rq1 rq2 rq3 DcqY DqsY Hqs Dqs => [k1 a1 q1] [k2 a2 q2] [k3 a3 q3].\n  move=> DcqY DqsY Hqs Dqs HqY; apply: Hrec (HqY).\n  rewrite /u0 cpring_ecpY /behead (head_proper_cpring Hgp) -/u0 -/nu0 in Hqs.\n  rewrite maps_adds !rqs_fit_adds Eau0 (arity_cface Hnu0) in Hqs.\n  rewrite -EhF in Hnu0; rewrite (arity_cface Hnu0) !Eag /= !connect0 in Hqs.\n  rewrite addnS orbT /= !addnA !addn1 -/r -/r' in Hqs.\n  case/and5P: Hqs => [Ea1 Hq1 Ea2 Hq2]; move/and3P=> [Ea3 Hq3 Hqs].\n  have Hqs': rqs_fit (fun x => h (icpY g x)) qs' r'.\n    move Dea: (fun x => arity (icpY g x) =d arity x) => ea.\n    have Hr': all ea r'.\n      apply/allP => [x Hx]; rewrite -Dea Eag //; apply/eqP.\n      rewrite /r (head_proper_cpring Hgp) -/r' -(cat1s g) -cat_adds seq2I in Ur.\n      rewrite simple_cat -/r -/r' -/au0 in Ur; case/and3P: Ur => [_ Ur _].\n      by rewrite (negbE (hasPn Ur _ Hx)).\n    elim: r' (qs') Hr' Hqs {Dqs Hr0} => [|x r' Hrec] [|rq qs''] //=.\n    move/andP=> [Ear' Hr']; move/and3P=> [Ea Hq Hqs]; rewrite -Dea /= in Ear'.\n    by rewrite -(eqP Ear') Ea Hq Hrec.\n  pose v1 := icpY g (node g); have Uv1: negb (cpring u0 v1).\n    rewrite /u0 /v1 cpring_ecpY /= /setU1 /= (mem_maps (@icpY_inj _ g)).\n    by move: (simple_uniq Ur); rewrite {1}[r](head_cpring g); case/andP.\n  have Eenv1: edge (node (h v1)) = h nu0 by rewrite (EhN _ Uv1) EhE /= set11.\n  have Eennv1: edge (node (node (h v1))) = h u0.\n    by rewrite !EhN // ?EhE ?cpring_ecpY /= /setU1 ?set11 //=; apply/mapsP; case.\n  have EpY': fband pY =1 setU (setC (codom h')) (fband rY').\n    have HrY'F: fclosed face (setU (setC (codom h')) (fband rY')).\n      apply: (intro_closed (Sface _)) => [u v]; move/eqP=> <- {v} Hu.\n      apply/norP; rewrite /setC negb_elim; move=> [Hfu HfuF]; move: Hu;\n        rewrite /setU (fclosed1 (fbandF rY')) (negbE HfuF) orbF; case/set0Pn.\n      move: (iinv Hfu) (f_iinv Hfu) => x Dx; rewrite /h' in Dx.\n      exists (edge (node x)); apply/eqP; rewrite /h'-icpY_edge -icpY_node.\n        rewrite -EhE -EhN; first by rewrite Dx Eface.\n        rewrite cpring_ecpY /= /setU1 /=; apply/idP => HxF.\n        case/hasP: HfuF; exists (face u); last exact: connect0.\n        rewrite /rY' -Dx; apply mem_behead.\n        by rewrite /h' (maps_comp h (icpY g)) !behead_maps; apply maps_f.\n      apply/idP => [HxF]; case/hasP: HfuF; exists (face u); last exact: connect0.\n      rewrite /rY' -Dx; apply: maps_f.\n      rewrite /r (head_proper_cpring Hgp) -(cat1s g) -cat_adds seq2I.\n      by rewrite mem_cat /setU HxF.\n    move=> u; rewrite EpY {1}/setU {1}/setC ErY; case Hu: (codom h u).\n      case: (fband_icpY (iinv Hu)) => [[x Hx]|Hu'].\n        rewrite -EhF f_iinv in Hx; rewrite (closed_connect HrY'F Hx).\n        rewrite (fun p => closed_connect (fbandF p) Hx) /setU /setC /= EhF Sface.\n        by rewrite /u0 cface_ecpY -/(h' x) codom_f.\n      simpl; congr orb; rewrite -EhF f_iinv in Hu'.\n      rewrite Sface /u0 Hu'; apply: esym; apply/idP => Hx.\n      by rewrite -(f_iinv Hx) /h' EhF cface_ecpY in Hu'.\n    apply: esym; apply/orP; left; apply/idP => [Hu'].\n    by rewrite -(f_iinv Hu') /h' codom_f in Hu.\n  have Hr0': sub_set (setD r0 (setU (codom h') (fband rY'))) good_ring_arity.\n    move=> u; case/andP; move/norP=> [Hh'u Hr'u] Hr0u.\n    case Hu: (cface (h u0) u).\n      rewrite /good_ring_arity -(arity_cface Hu); apply: not_bad_ring_arity.\n      rewrite (eqP Ea2) /=; apply/idP => [Ha2].\n      rewrite /pY simple_cat in UpY; case/and3P: UpY; clear; case/hasP.\n      exists u; first done; apply/hasP; exists (h u0); last by rewrite Sface.\n      rewrite Dqs /rY cpring_ecpY -/u0 -/nu0 /= mem_cat; apply/orP; right.\n      do 2 (rewrite mem_cat; apply/orP; left); move: HqY; rewrite -DqsY.\n      by case k2; [ rewrite /= setU11 | rewrite /= Ha2 qs0_notR ].\n    apply: Hr0; rewrite /setD Hr0u /setU ErY fband_adds Sface Hu (negbE Hr'u).\n    have HuY: fband pY u by rewrite EpY' /setU /setC Hh'u.\n    rewrite EpY /setU /setC ErY fband_adds Sface Hu (negbE Hr'u) orbF in HuY.\n    by rewrite orbF HuY.\n  move: HqY; rewrite -/h' -DqsY; case Dk2: k2.\n    rewrite /= small_qarityP; set qa2 := small_qarity a2.\n    case: ((qa2 : nat) =P S (S a2)) => [Dqa2|_]; last by rewrite qs0_notR.\n    clear; rewrite -{}Dqa2 in Ea2; rewrite -/v1 in Ea1.\n    set q1' := QaskLR qa2 q2 q1.\n    pose q1'' := selq q1 (selq q2 (Qask1 qa2) (QaskL qa2 q2))\n                         (selq q2 (QaskR qa2 q1) q1').\n    change (rqs_ok h' (cqY q1'')).\n    have [Eq1 Eq1v1]: simq q1'' q1' (node (h v1)).\n      by rewrite /q1'' /q1' /simq; case q1; case: (q2) => //= *; rewrite !cats0.\n    rewrite /= /qstepR /qstepL Eennv1 Eenv1 in Eq1v1.\n    have Eq1''F: fband (cat (rqs_walk (cqY q1'') rY') r0) =1 fband pY.\n      rewrite /rY' /pY /rY cpring_ecpY /r /behead (head_proper_cpring Hgp).\n      rewrite -/r -/r' !maps_adds -DcqY -/u0 -/nu0 Dqs Dk2 /rqs_Y.\n      rewrite !rqs_walk_adds {1 2}/h' -/v1 -maps_comp !catA.\n      move=> u; rewrite !fband_cat; do 4 congr orb.\n      rewrite (fband_seqn Hnu0) -!orbA; congr orb.\n      rewrite /= Eq1v1 /= fband_cat orbA orbC orbF; do 2 congr orb.\n      by rewrite (cface1r (h u0)) -Eennv1 Enode.\n    split; auto; rewrite -/r -/rY' -/r0; last by move=> u; rewrite Eq1''F EpY'.\n      rewrite /r (head_proper_cpring Hgp) -/r -DcqY /=.\n      apply/and5P; split; auto.\n      rewrite /h' -/v1 /fitq Eq1 Eq1v1 /= eqseq_adds fitq_cat.\n      by rewrite -arity_face -Eennv1 Enode in Ea2; rewrite eqd_sym Ea2 Hq2.\n    rewrite (simple_perm Eq1''F) // /rY' /pY /rY cpring_ecpY.\n    rewrite /r /behead (head_proper_cpring Hgp) -/r -/r' !maps_adds.\n    rewrite -DcqY -/u0 -/nu0 Dqs Dk2 /rqs_Y !rqs_walk_adds {1 2}/h' -/v1.\n    rewrite -maps_comp !size_cat /= Eq1v1 /= !size_cat !addnA; do 4 congr addn.\n    by rewrite !size_seqn -!addnA; congr addn; symmetry; rewrite addnC.\n  rewrite /=; case: (bad_ring_arity a2); first by rewrite qs0_notR.\n  case: (q1) Dqs Hq1 Hq2; rewrite ?qs0_notR //.\n    case: (q2); rewrite ?qs0_notR //.\n      move=> Dqs _ _ _.\n      have EqsF: fband (cat (rqs_walk (cqY Qask0) rY') r0) =1 fband pY.\n        rewrite /rY' /pY /rY cpring_ecpY /r /behead (head_proper_cpring Hgp).\n        rewrite -/r -/r' !maps_adds -DcqY -/u0 -/nu0 Dqs Dk2 /rqs_Y.\n        rewrite !rqs_walk_adds {1 2}/h' -/v1 -maps_comp !catA.\n        move=> u; rewrite !fband_cat !orbF; do 4 congr orb.\n        by rewrite (fband_seqn Hnu0).\n      split; auto; rewrite -/r -/rY' -/r0; last by move=> u; rewrite EqsF EpY'.\n        by rewrite /r (head_proper_cpring Hgp) -/r -DcqY /=; apply/and4P; split.\n      rewrite (simple_perm EqsF) // /rY' /pY /rY cpring_ecpY.\n      rewrite /r /behead (head_proper_cpring Hgp) -/r -/r' !maps_adds.\n      rewrite -DcqY -/u0 -/nu0 Dqs Dk2 /rqs_Y !rqs_walk_adds {1 2}/h' -/v1.\n      rewrite -maps_comp !size_cat /= !addnA; do 4 congr addn.\n      by rewrite !size_seqn !addn0.\n    move=> qa2l q2l Dqs _ Hq2 _.\n    have EqsF: fband (cat (rqs_walk (cqY (QaskLL qa2l q2l)) rY') r0) =1 fband pY.\n      rewrite /rY' /pY /rY cpring_ecpY /r /behead (head_proper_cpring Hgp).\n      rewrite -/r -/r' !maps_adds -DcqY -/u0 -/nu0 Dqs Dk2 /rqs_Y.\n      rewrite !rqs_walk_adds {1 2}/h' -/v1 -maps_comp !catA.\n      move=> u; rewrite !fband_cat !orbF; do 4 congr orb.\n      rewrite (fband_seqn Hnu0); congr orb; simpl.\n      by rewrite /qstepL Eennv1 cface1r Enode.\n    split; auto; rewrite -/r -/rY' -/r0; last by move=> u; rewrite EqsF EpY'.\n      rewrite /r (head_proper_cpring Hgp) -/r -DcqY /=; apply/and5P; split; auto.\n      move: Hq2; rewrite /fitq /= !eqseq_adds /h' -/v1 /qstepL Eennv1.\n      by rewrite -{1}[node (h u0)]Enode arity_face.\n    rewrite (simple_perm EqsF) // /rY' /pY /rY cpring_ecpY.\n    rewrite /r /behead (head_proper_cpring Hgp) -/r -/r' !maps_adds.\n    rewrite -DcqY -/u0 -/nu0 Dqs Dk2 /rqs_Y !rqs_walk_adds {1 2}/h' -/v1.\n    rewrite -maps_comp !size_cat /= !addnA; do 4 congr addn.\n    by rewrite !size_seqn !addn0 /qstepL Eennv1.\n  case q2; try by rewrite qs0_notR.\n  move=> qa1r q1r Dqs Hq1 _ _.\n  have EqsF: fband (cat (rqs_walk (cqY (QaskRR qa1r q1r)) rY') r0) =1 fband pY.\n    rewrite /rY' /pY /rY cpring_ecpY /r /behead (head_proper_cpring Hgp).\n    rewrite -/r -/r' !maps_adds -DcqY -/u0 -/nu0 Dqs Dk2 /rqs_Y.\n    rewrite !rqs_walk_adds {1 2}/h' -/v1 -maps_comp !catA.\n    move=> u; rewrite !fband_cat !orbF; do 4 congr orb.\n    rewrite (fband_seqn Hnu0); congr orb; simpl.\n    by rewrite /qstepR Eenv1.\n  split; auto; rewrite -/r -/rY' -/r0; last by move=> u; rewrite EqsF EpY'.\n    rewrite /r (head_proper_cpring Hgp) -/r -DcqY /=; apply/and5P; split; auto.\n    by move: Hq1; rewrite /fitq /= !eqseq_adds /h' -/v1 /qstepR Eenv1.\n  rewrite (simple_perm EqsF) // /rY' /pY /rY cpring_ecpY.\n  rewrite /r /behead (head_proper_cpring Hgp) -/r -/r' !maps_adds.\n  rewrite -DcqY -/u0 -/nu0 Dqs Dk2 /rqs_Y !rqs_walk_adds {1 2}/h' -/v1.\n  rewrite -maps_comp !size_cat /= !addnA; do 4 congr addn.\n  by rewrite !size_seqn !addn0 /qstepR Eenv1.\nsimpl in Hcp2; have Hgp := cpmap_proper Hcp2; rewrite -/g in Hgp.\nsimpl in Hscp2; have Hgl := cfmap_long Hscp2; rewrite -/g in Hgl.\nhave HgE := cpmap_plain Hcp2; have Hg'E := plain_ecpH g HgE.\nrewrite -/r0; set rH := maps h (cpring (ecpH g)); set pH := cat _ r0.\nset u0 : ecpH g := ecpH g; set nu0 := node u0.\npose v1 := icpH g (node g); pose v2 := icpH g g.\npose v3 := icpH g (face (edge g)).\nhave Hnu0: cface nu0 v1 by apply: cface_node_ecpH.\npose h' x := h (icpH g x); pose rH' := maps h' r.\npose r' := drop 3 r; pose au0 := seq3 (node g) g (face (edge g)).\nhave Dr: r = cat au0 r' by rewrite /r head_long_cpring.\nhave DrH: rH = Adds (h nu0) (Adds (h u0) (Adds (h v3) (maps h' r'))).\n  by rewrite /rH cpring_ecpH // -/r -/u0 -/nu0 Dr /= -maps_comp.\nhave DrH': rH' = Adds (h v1) (Adds (h v2) (Adds (h v3) (maps h' r'))).\n  by rewrite /rH' Dr.\nhave ErH: fband (Adds (h v2) rH) =1 fband (Adds (h u0) rH').\n  move=> u; rewrite DrH DrH' !fband_adds; BoolCongr.\n  rewrite orbCA; BoolCongr; congr orb.\n  by rewrite !(Sface _ u); apply: same_cface; rewrite EhF.\nhave Eau0: arity u0 = 3.\n  have Df3u0: face (face (face u0)) = u0 by rewrite /= Enode (negbE Hgp).\n  apply: (@order_cycle _ _ (traject face u0 3)) => //.\n  by rewrite (cycle_path u0) /traject /eqdf /last /path Df3u0.\nhave Eag: forall x, arity (icpH g x) = fband au0 x + arity x.\n  pose bu0 := maps edge (orbit face u0).\n  have Ebu0: fband bu0 =1 fband (maps (icpH g) au0).\n    move=> u; rewrite /au0 -adj_ecpH // /bu0 /fband has_maps.\n    by apply: eq_has => v; rewrite /comp Sface.\n  move=> x; rewrite /order -(cardIC bu0); congr addn.\n    rewrite setI_cface_simple.\n      congr nat_of_bool; rewrite Ebu0 /fband has_maps; apply: eq_has.\n      exact: cface_icpH.\n    rewrite (simple_perm Ebu0); last by rewrite /bu0 !size_maps size_orbit.\n    rewrite (simple_maps (cface_icpH g)).\n    by rewrite Dr simple_cat in Ur; case/and3P: Ur.\n  rewrite -(card_image (@icpH_inj g g)); apply: eq_card => u.\n  apply/andP/set0Pn => [[Hux Hu]|[y]].\n    have Hu0u: negb (cface u0 u).\n      by rewrite Sface -(same_cface Hux) Sface /u0 cface_ecpH.\n    rewrite /u0 cface_ecpH // -/u0 in Hu0u; rewrite /bu0 /orbit Eau0 in Hu.\n    case: u Hu Hu0u Hux => //; case=> //; case=> // [y] _ _ Hxy; exists y.\n    by rewrite /setI /preimage set11 -(cface_icpH g).\n  case/andP; rewrite /preimage; move/eqP=> Du; rewrite Du cface_icpH.\n  by split; first done; rewrite /bu0 /orbit Eau0.\nrewrite Dqs; move=> Hqs Hr0 UpH EpH /=.\nmove DcqH: (rqs_H _ _ _) => cqH; move DqsH: (cfquiz_H _ _ _) => qsH.\ncase: rq1 rq2 rq3 DcqH DqsH Hqs Dqs => [k1 a1 q1] [k2 a2 q2] [k3 a3 q3].\nmove=> DcqH DqsH Hqs Dqs HqH; apply: Hrec (HqH).\nrewrite /u0 cpring_ecpH -/u0 -/nu0 // -/r Dr /au0 /seq3 /seq2 !cat_adds in Hqs.\nrewrite cat1s /drop maps_adds -/v3 !rqs_fit_adds Eau0 (arity_cface Hnu0) in Hqs.\nrewrite -EhF in Hnu0; rewrite (arity_cface Hnu0) in Hqs.\nrewrite {2}/v1 {2}/v3 !Eag /= !connect0 in Hqs.\nrewrite 2!addnS !orbT /= !addnA !addn1 in Hqs.\ncase/and5P: Hqs => Ea1 Hq1 Ea2 Hq2; move/and3P=> [Ea3 Hq3 Hqs].\nhave Hqs': rqs_fit (fun x => h (icpH g x)) qs' r'.\n  move Dea: (fun x => arity (icpH g x) =d arity x) => ea.\n  have Hr': all ea r'.\n    apply/allP => [x Hx]; rewrite -Dea Eag //; apply/eqP.\n    rewrite Dr simple_cat in Ur; case/and3P: Ur => [_ Ur _].\n    by rewrite (negbE (hasPn Ur _ Hx)).\n  elim: (r') (qs') Hr' Hqs {Dqs Hr0} => [|x r'' Hrec] [|rq qs''] //=.\n  move/andP=> [Ear'' Hr'']; move/and3P=> [Ea Hq Hqs]; rewrite -Dea /= in Ear''.\n  by rewrite -(eqP Ear'') Ea Hq Hrec.\nhave UrH: forall x, cpring u0 (icpH g x) = drop 2 r x.\n  move=> x; rewrite /u0 cpring_ecpH //= /setU1 /= (mem_maps (@icpH_inj _ g)).\n  by rewrite /long_cpring /= Enode (negbE Hgp).\nhave Uv1: negb (cpring u0 v1).\n  move: (simple_uniq Ur).\n  by rewrite {1}[r](head_proper_cpring Hgp) /v1 UrH; case/andP; case/norP.\nhave Uv2: negb (cpring u0 v2).\n  move: (simple_uniq Ur).\n  by rewrite {1}[r](head_proper_cpring Hgp) /v2 UrH; case/and3P.\nhave Eenv1: edge (node (h v1)) = h nu0.\n  rewrite (EhN _ Uv1) EhE; congr h; apply Iface; rewrite Enode.\n  have ->: nu0 = icpN _ (icpN _ (edge (ecpU g)));\n    by rewrite /nu0 /= /long_cpring /= Enode (negbE Hgp).\nhave Hnv1: cface (node (h v1)) (h u0).\n  by rewrite EhN // EhF Sface /u0 cface_ecpH //= !set11 /= /setU1 !orbT.\nhave Eennv2: edge (node (node (h v2))) = h u0.\n  have Env2: node v2 = face u0 by rewrite /v2 /= (negbE Hgp) /= 2!set11.\n  rewrite EhN // Env2 EhN; [by rewrite EhE Eface | rewrite cpring_ecpH //].\n  repeat (apply/norP; split => //); last by apply/mapsP; case.\n  by rewrite /= /long_cpring /= Enode (negbE Hgp).\nhave EpH': fband (Adds (h v2) pH) =1 setU (setC (codom h')) (fband rH').\n  have HrH'F: fclosed face (setU (setC (codom h')) (fband rH')).\n    apply: (intro_closed (Sface _)) => [u v]; move/eqP=> <- {v} Hu.\n    apply/norP; rewrite /setC negb_elim; move=> [Hfu HfuF]; move: Hu;\n      rewrite /setU (fclosed1 (fbandF rH')) (negbE HfuF) orbF; case/set0Pn.\n    move: (iinv Hfu) (f_iinv Hfu) => x Dx; rewrite /h' in Dx.\n    exists (edge (node x)); apply/eqP; rewrite /h'.\n    rewrite -icpH_edge -icpH_node.\n      rewrite -EhE -EhN; first by rewrite Dx Eface.\n      rewrite -/u0 UrH; apply/idP => HxF.\n      case/hasP: HfuF; exists (face u); last exact: connect0.\n      by rewrite /rH' -Dx; apply: (@mem_drop 2); rewrite -maps_drop; apply: maps_f.\n    apply/idP => [HxF]; case/hasP: HfuF; exists (face u); last exact: connect0.\n    by rewrite /rH' -Dx; apply: maps_f; rewrite Dr mem_cat /au0 /setU HxF.\n  move=> u; rewrite fband_adds EpH {1}/setU {1}/setC orbCA -fband_adds ErH.\n  case Hu: (codom h u).\n    case: (fband_icpH (iinv Hu)) => [[x Hx]|Hu'].\n      rewrite -EhF f_iinv in Hx; rewrite (closed_connect HrH'F Hx).\n      rewrite (fun p => closed_connect (fbandF p) Hx) /setU /setC /= EhF Sface.\n      by rewrite /u0 cface_ecpH // -/(h' x) codom_f.\n    simpl; congr orb; rewrite -EhF f_iinv in Hu'.\n    rewrite Sface /u0 Hu'; apply: esym; apply/idP => Hx.\n    by rewrite -(f_iinv Hx) /h' EhF cface_ecpH in Hu'.\n  symmetry; apply/orP; left; apply/idP => Hu'.\n  by rewrite -(f_iinv Hu') /h' codom_f in Hu.\nhave Hr0': sub_set (setD r0 (setU (codom h') (fband rH'))) good_ring_arity.\n  move=> u; case/andP; move/norP=> [Hh'u Hr'u] Hr0u.\n  case Hu: (cface (h u0) u).\n    rewrite /good_ring_arity -(arity_cface Hu); apply: not_bad_ring_arity.\n    rewrite (eqP Ea2) {3}[S]lock /= -lock; apply/idP => Ha2; simpl in Ha2.\n    rewrite /pH simple_cat in UpH; case/and3P: UpH => _; case/hasP.\n    exists u; first done; apply/hasP; exists (h u0); last by rewrite Sface.\n    rewrite Dqs DrH !rqs_walk_adds mem_cat; apply/orP; right.\n    do 2 (rewrite mem_cat; apply/orP; left); move: HqH; rewrite -DqsH.\n    by case k2; rewrite /= ?setU11 // Ha2 /= qs0_notR.\n  apply: Hr0; rewrite /setD Hr0u /setU.\n  have HuH: fband (Adds (h v2) pH) u by rewrite EpH' /setU /setC Hh'u.\n  have Hur: negb (fband (Adds (h v2) rH) u).\n    by rewrite ErH fband_adds Sface Hu.\n  rewrite fband_adds EpH /setU /setC orbCA -fband_adds (negbE Hur) orbF in HuH.\n  rewrite fband_adds in Hur; case/norP: Hur => _ Hur.\n  by rewrite (negbE Hur) orbF HuH.\nhave HrHv2: negb (fband rH (h v2)).\n  rewrite DrH !fband_adds Sface (same_cface Hnu0) Sface !EhF /h' /fband.\n  rewrite (maps_comp h (icpH g)) has_maps (@eq_has _ (comp _ h) _ (EhF v2)).\n  rewrite orbCA Sface /u0 cface_ecpH // orFb.\n  rewrite /v1 /v2 /v3 !cface_icpH has_maps.\n  rewrite (@eq_has _ (comp _ (icpH g)) _ (cface_icpH g g)).\n  move: Ur; rewrite Dr simple_recI /= Sface; case/and3P.\n  by move/norP=> [Ung _] Ug _; apply/norP; split.\nhave HpHv2: negb (fband pH (h v2)) by rewrite EpH /setU /setC codom_f.\nhave Uv2pH: simple (Adds (h v2) pH) by rewrite simple_adds HpHv2.\nhave Eav2: arity (h v2) = S (arity g).\n  transitivity (arity v2); last by rewrite /v2 Eag /= connect0 orbT.\n  rewrite /order -(card_image Hh); apply: eq_card => [u].\n  apply/idP/idP => [Hu|];\n   last by case/set0Pn=> [x]; case/andP; move/eqP=> Du; rewrite Du EhF.\n  rewrite (closed_connect (fbandF pH) Hu) EpH /setU /setC in HpHv2.\n  rewrite -(closed_connect (fbandF rH) Hu) (negbE HrHv2) orbF negb_elim in HpHv2.\n  by rewrite -(f_iinv HpHv2) (image_f Hh) -EhF f_iinv.\nmove: HqH; rewrite -/h' -DqsH; case Dk2: k2.\n  rewrite /cfquiz_H small_qarityP; set qa2 := small_qarity (S a2).\n  case: ((qa2 : nat) =P S (S (S a2))) => [Dqa2|_]; last by rewrite qs0_notR.\n  rewrite -{}Dqa2 in Ea2; rewrite if_negb.\n  set q1' := QaskR qa2 q1; set q2' := QaskL qa2 q2.\n  have Hq1': forall q, q2 = Qask0 -> simq q q1' (node (h v1)) ->\n      rqs_ok h' (cqH q q2).\n    move=> q Dq2 [Eq Eqv1]; rewrite /= /qstepR Eenv1 in Eqv1.\n    have EqsF: fband (cat (rqs_walk (cqH q q2) rH') r0) =1 fband (Adds (h v2) pH).\n      move=> u; rewrite /pH Dqs Dk2 DrH' DrH -DcqH Dq2 /= Eqv1.\n      rewrite !fband_cat !fband_adds !fband_cat !orbA; do 4 congr orb.\n      rewrite (fband_seqn Hnu0) -!orbA !(Sface _ u) (same_cface Hnv1).\n      by repeat BoolCongr.\n    split; auto; rewrite -/r -/r0 -/rH'; last by move=> u; rewrite EqsF EpH'.\n      rewrite Dr -DcqH Dq2 /= {-6}/h' -/v1 -/v2 -/v3 Hq3 Eav2 set11.\n      apply/and5P; split; auto.\n      by rewrite /fitq Eq Eqv1 /= eqseq_adds (arity_cface Hnv1) eqd_sym Ea2.\n    rewrite (simple_perm EqsF) // DrH' /pH DrH Dqs Dq2 Dk2 -DcqH /=.\n    rewrite !size_cat /= !size_cat !size_seqn Eqv1 /=.\n    by NatNorm; repeat NatCongr.\n  have Hq2': forall q, q1 = Qask0 -> simq q q2' (node (h v2)) ->\n     rqs_ok h' (cqH q1 q).\n    move=> q Dq1 [Eq Eqv2]; rewrite /= /qstepL Eennv2 in Eqv2.\n    have EqsF: fband (cat (rqs_walk (cqH q1 q) rH') r0) =1 fband (Adds (h v2) pH).\n      move=> u; rewrite /pH Dqs Dk2 DrH' DrH -DcqH Dq1 /= Eqv2 !cats0.\n      rewrite !fband_cat !fband_adds !fband_cat fband_adds !orbA; do 5 congr orb.\n      rewrite (fband_seqn Hnu0) -!orbA orbCA; do 2 congr orb.\n      by rewrite (cface1r (h u0)) -Eennv2 Enode.\n    split; auto; rewrite -/r -/r0 -/rH'; last by move=> u; rewrite EqsF EpH'.\n      rewrite Dr -DcqH Dq1 /= {-6}/h' -/v1 -/v2 -/v3 Hq3 Eav2 set11.\n      apply/and5P; split; auto.\n      rewrite /fitq Eq Eqv2 /= eqseq_adds -[node (h v2)]Enode Eennv2.\n      by rewrite arity_face eqd_sym Ea2.\n    rewrite (simple_perm EqsF) // DrH' /pH DrH Dqs Dq1 Dk2 -DcqH /=.\n    rewrite !size_cat /= !size_cat !size_seqn Eqv2 /=.\n    by NatNorm; repeat NatCongr.\n  have Hsimq: forall q (u : g0), simq q q u by split.\n  case Dq1: q1 Hq1' Hq2'; case Dq2: q2; auto; try by rewrite qs0_notR.\n  by rewrite {}/q1' {}/q2' {}Dq1 {}Dq2; case: (k1) => [H _|_ H] _; apply: H.\nrewrite /cfquiz_H; case: (bad_ring_arity (S a2)); first by rewrite qs0_notR.\ncase Dq1: q1; rewrite ?qs0_notR //; case Dq2: q2; rewrite ?qs0_notR //.\nhave EqsF:\n     fband (cat (rqs_walk (cqH Qask0 Qask0) rH') r0) =1 fband (Adds (h v2) pH).\n  move=> u; rewrite /pH Dqs Dk2 DrH' DrH -DcqH Dq1 Dq2 /= !cats0.\n  rewrite !fband_cat !fband_adds !fband_cat !orbA; do 4 congr orb.\n  by rewrite (fband_seqn Hnu0) orbC.\nsplit; auto; rewrite -/r -/r0 -/rH'; last by move=> u; rewrite EqsF EpH'.\n  rewrite Dr -DcqH /= {-5}/h' -/v1 -/v2 -/v3 Hq3 Eav2 set11 /=.\n  by apply/and3P; split.\nrewrite (simple_perm EqsF) // DrH' /pH DrH Dqs Dq1 Dq2 Dk2 -DcqH /=.\nrewrite !size_cat /= !size_cat !size_seqn /=.\nby NatNorm; repeat NatCongr.\nQed.\n\nLemma embeddable_cfquiz : embeddable (cfring cf).\nProof.\nsplit; try exact Hrad2.\n  have Hcpq := config_prog_cubic Hcp; repeat split.\n  - exact: cpmap_plain.\n  - exact: cpmap_cubic.\n  - exact: ucycle_rev_cpring.\n  - exact: cpmap_connected.\n  - by move: (cpmap_simple Hcp); rewrite simple_cat -simple_rev; case/and3P.\n  - exact: cpmap_planar.\n  exact: cpmap_bridgeless.\nby apply/allP => x Hx; case: cfquizP => H _; apply: H; rewrite -mem_rev.\nQed.\n\nLemma valid_cfquiz : exists u, valid_quiz (cfring cf) u cfquiz.\nProof.\ncase: cfquizP => _ [u [Hcqz Hu Uqz Eqz]]; exists u; split; auto.\nby move=> v; rewrite {u Hcqz Hu Uqz}Eqz /kernel /setC -fband_rev.\nQed.\n\nEnd ConfigQuiz.\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/cfquiz.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.28938232770379235}}
{"text": "(* Definition of the finite set spec *)\nRequire Import Coq.Strings.String\n  Coq.Sets.Ensembles\n  Coq.Sets.Finite_sets\n  Coq.Lists.List\n  Coq.Sorting.Permutation\n  Fiat.ADT\n  Fiat.ADT.ComputationalADT\n  Fiat.ADTRefinement.Core\n  Fiat.ADTNotation\n  Fiat.ADTRefinement.GeneralRefinements\n  Fiat.Common.Ensembles\n  Fiat.FiniteSetADTs.FiniteSetADT\n  Fiat.Common.Ensembles.Notations\n  Fiat.Common.Ensembles.Equivalence.\n\nSet Implicit Arguments.\n\nLocal Open Scope Ensemble_scope.\n\nSection method_laws.\n  Variable FiniteSetImpl : FullySharpened FiniteSetSpec.\n\n  Local Infix \"≃\" := (AbsR (projT2 FiniteSetImpl)).\n  Definition to_ensemble fs : Ensemble W :=\n    fun x => exists S0, S0 ≃ fs /\\ x ∈ S0.\n\n  Local Ltac handle_methods :=\n    idtac;\n    let lem := match goal with\n                 | [ |- context[(CallMethod (projT1 ?impl) ?idx) ?rep ?arg] ]\n                   => constr:(fun rep' => ADTRefinementPreservesMethods (projT2 impl) {| bindex := idx |} rep' rep arg)\n                 | [ H : context[(CallMethod (projT1 ?impl) ?idx) ?rep ?arg] |- _ ]\n                   => constr:(fun rep' => ADTRefinementPreservesMethods (projT2 impl) {| bindex := idx |} rep' rep arg)\n               end in\n    let H' := fresh in\n    first [ pose proof (fun rep' H => lem rep' H _ (ReturnComputes _)) as H'\n          | pose proof (lem _ (ReturnComputes _)) as H' ];\n      simpl in H'.\n\n  Local Ltac handle_constructors :=\n    idtac;\n    let lem := match goal with\n                 | [ |- context[(CallConstructor (projT1 ?impl) ?idx) ?arg] ]\n                   => constr:(ADTRefinementPreservesConstructors (projT2 impl) {| bindex := idx |} arg)\n                 | [ H : context[(CallConstructor (projT1 ?impl) ?idx) ?arg] |- _ ]\n                   => constr:(ADTRefinementPreservesConstructors (projT2 impl) {| bindex := idx |} arg)\n               end in\n    let H' := fresh in\n    first [ pose proof (fun rep' H => lem rep' H _ (ReturnComputes _)) as H'\n          | pose proof (lem _ (ReturnComputes _)) as H' ];\n      simpl in H'.\n\n  Local Ltac t_pre_step :=\n    idtac;\n    match goal with\n      | _ => split\n      | _ => intro\n      | _ => progress unfold Ensembles.In, Included, to_ensemble in *\n      | _ => progress destruct_head_hnf Ensembles.Empty_set\n      | _ => progress subst\n      | _ => progress inversion_by computes_to_inv\n      | _ => progress simpl in *\n      | _ => progress split_iff\n      | _ => progress destruct_head bool\n      | _ => progress destruct_head ex\n      | _ => progress simplify_hyps\n      | [ H : (_, _) = (_, _) |- _ ] => inversion H; clear H\n      | [ H : (_, _) = ?x |- _ ] => destruct x\n      | _ => assumption\n      | [ H : ?f ?A ?B, H' : forall a, ?f a ?b -> _ |- _ ] => specialize (H' _ H)\n      | _ => solve [ eauto with nocore ]\n      | _ => solve [ repeat esplit; eassumption ]\n      | [ |- computes_to (ret ?x) ?y ]\n        => let H := fresh in\n           assert (H : x = y);\n             [\n             | rewrite H; constructor ]\n      | [ |- computes_to (Return _) _ ] => constructor\n      | [ |- computes_to (Bind _ _) _ ] => refine (BindComputes _ _ _)\n      | [ |- computes_to (Pick _) _ ] => constructor\n      | [ |- from_nat _ = from_nat _ ] => apply f_equal\n    end.\n\n  Lemma FiniteSet_AbsR_Same_set fs (S0 S1 : Ensemble W) (H0 : S0 ≃ fs) (H1 : S1 ≃ fs)\n  : S0 ≅ S1.\n  Proof.\n    lazy; split; intros;\n    match goal with\n      | [ H : ?S' ≃ ?fs, H' : ?S'' ≃ ?fs |- ?S' ?x ]\n        => pose proof (let f := ADTRefinementPreservesMethods\n                                  (projT2 FiniteSetImpl) {| bindex := \"In\"%string |}\n                                  S' _ x H in\n                       f _ (ReturnComputes _));\n          pose proof (let f := ADTRefinementPreservesMethods\n                                 (projT2 FiniteSetImpl) {| bindex := \"In\"%string |}\n                                 S'' _ x H' in\n                      f _ (ReturnComputes _));\n          simpl in *\n    end;\n    repeat t_pre_step.\n  Qed.\n\n  Local Ltac t_step :=\n    idtac;\n    match goal with\n      | _ => progress t_pre_step\n      | [ H0 : ?S0 ≃ ?fs, H1 : ?S1 ≃ ?fs |- _ ] =>\n        match goal with\n          | [ H'' : S0 ≅ S1 |- _ ] => fail 1\n          | [ H'' : S1 ≅ S0 |- _ ] => fail 1\n          | _ => let H := fresh in\n                 pose proof (@FiniteSet_AbsR_Same_set fs S0 S1 H0 H1) as H;\n                   pose proof (proj1 H);\n                   pose proof (proj2 H)\n        end\n    end.\n\n  Local Ltac t := repeat t_step.\n\n  Section AbsR.\n    Lemma AbsR_ToEnsemble_Empty\n    : ∅ ≃ CallConstructor (projT1 FiniteSetImpl) sEmpty tt.\n    Proof.\n      handle_constructors; t.\n    Qed.\n\n    Lemma AbsR_ToEnsemble_Add S0 fs x (H : S0 ≃ fs)\n    : Ensembles.Add _ S0 x ≃ fst (CallMethod (projT1 FiniteSetImpl) sAdd fs x).\n    Proof.\n      handle_methods; t.\n    Qed.\n\n    Lemma AbsR_ToEnsemble_Remove S0 fs x (H : S0 ≃ fs)\n    : Ensembles.Subtract _ S0 x ≃ fst (CallMethod (projT1 FiniteSetImpl) sRemove fs x).\n    Proof.\n      handle_methods; t.\n    Qed.\n\n    Lemma AbsR_ToEnsemble_In S0 fs x (H : S0 ≃ fs)\n    : S0 ≃ fst (CallMethod (projT1 FiniteSetImpl) sIn fs x).\n    Proof.\n      handle_methods; t.\n    Qed.\n\n    Lemma AbsR_ToEnsemble_Size S0 fs (H : S0 ≃ fs)\n    : S0 ≃ fst (CallMethod (projT1 FiniteSetImpl) sSize fs tt).\n    Proof.\n      handle_methods; t.\n    Qed.\n  End AbsR.\n\n  Lemma Same_set_ToEnsemble_AbsR S0 fs (H : S0 ≃ fs)\n  : to_ensemble fs ≅ S0.\n  Proof. t. Qed.\n\n  Lemma Same_set_ToEnsemble_Empty\n  : to_ensemble (CallConstructor (projT1 FiniteSetImpl) sEmpty tt) ≅ ∅.\n  Proof.\n    apply Same_set_ToEnsemble_AbsR, AbsR_ToEnsemble_Empty.\n  Qed.\n\n  (** N.B. This lemma takes an [AbsR] assumption, but produces a\n           [Same_set] conclusion; we need to know that the finite set\n           representation we start with is valid in the first place.\n           (Because of how we're representing [to_ensemble], we\n           actually need something stronger, essentially that [AbsR]\n           respects [Same_set].)\n\n     B.D. Is this actually point true? We can use the [In] method to\n          show that any two sets related to the same [fs] are the\n          [Same_set], w/o relying on a stronger assumption. See in\n          [FiniteSets]\n\n     J.G. Yes.  I do what you say above in [FiniteSet_AbsR_Same_set]\n          (potentially duplicated lemma?).  Here I need to assume the\n          other direction, that if an ensemble [S0] is related to a\n          finite set [fs], then any ensemble [S'] which is the\n          [Same_set] as [S0] is also related to [fs]; this is the\n          [forall S', S' ≅ S0 -> S' ...] bit in [H : exists S0, forall\n          S', S' ≅ S0 -> S' ≃ fs]. *)\n\n  Lemma Same_set_ToEnsemble_Add' fs S0 x (H : S0 ≃ fs)\n  : to_ensemble (fst (CallMethod (projT1 FiniteSetImpl) sAdd fs x)) ≅ Ensembles.Add _ S0 x.\n  Proof.\n    apply Same_set_ToEnsemble_AbsR, AbsR_ToEnsemble_Add; assumption.\n  Qed.\n  Lemma Same_set_ToEnsemble_Add fs x (H : exists S0, forall S', S' ≅ S0 -> S' ≃ fs)\n  : to_ensemble (fst (CallMethod (projT1 FiniteSetImpl) sAdd fs x)) ≅ Ensembles.Add _ (to_ensemble fs) x.\n  Proof.\n    destruct H as [? H].\n    pose proof (H _ (reflexivity _)).\n    apply Same_set_ToEnsemble_Add', H; t.\n  Qed.\n\n  Lemma Same_set_ToEnsemble_Remove' fs S0 x (H : S0 ≃ fs)\n  : to_ensemble (fst (CallMethod (projT1 FiniteSetImpl) sRemove fs x)) ≅ Ensembles.Subtract _ S0 x.\n  Proof.\n    apply Same_set_ToEnsemble_AbsR, AbsR_ToEnsemble_Remove; assumption.\n  Qed.\n  Lemma Same_set_ToEnsemble_Remove fs x (H : exists S0, forall S', S' ≅ S0 -> S' ≃ fs)\n  : to_ensemble (fst (CallMethod (projT1 FiniteSetImpl) sRemove fs x)) ≅ Ensembles.Subtract _ (to_ensemble fs) x.\n  Proof.\n    destruct H as [? H].\n    pose proof (H _ (reflexivity _)).\n    apply Same_set_ToEnsemble_Remove', H; t.\n  Qed.\n\n  Lemma ToEnsemble_In_iff' fs S0 x (H : S0 ≃ fs)\n  : (snd (CallMethod (projT1 FiniteSetImpl) sIn fs x)) = true\n    <-> x ∈ S0.\n  Proof.\n    handle_methods; t.\n  Qed.\n  Lemma ToEnsemble_In_iff fs x (H : exists S0, forall S', S' ≅ S0 -> S' ≃ fs)\n  : (snd (CallMethod (projT1 FiniteSetImpl) sIn fs x)) = true\n    <-> x ∈ (to_ensemble fs).\n  Proof.\n    destruct H as [? H].\n    pose proof (H _ (reflexivity _)).\n    apply ToEnsemble_In_iff', H; t.\n  Qed.\n\n  Lemma ToEnsemble_In_refineEquiv' fs S0 x (H : S0 ≃ fs)\n  : refineEquiv (ret (snd (CallMethod (projT1 FiniteSetImpl) sIn fs x)))\n                { b : bool | decides b (x ∈ S0) }.\n  Proof.\n    setoid_rewrite <- (@ToEnsemble_In_iff' fs S0 x H).\n    setoid_rewrite refineEquiv_decides_eqb.\n    rewrite refineEquiv_pick_eq; reflexivity.\n  Qed.\n  Lemma ToEnsemble_In_refineEquiv fs x (H : exists S0, forall S', S' ≅ S0 -> S' ≃ fs)\n  : refineEquiv (ret (snd (CallMethod (projT1 FiniteSetImpl) sIn fs x)))\n                { b : bool | decides b (x ∈ to_ensemble fs) }.\n  Proof.\n    setoid_rewrite <- (@ToEnsemble_In_iff fs x H).\n    setoid_rewrite refineEquiv_decides_eqb.\n    rewrite refineEquiv_pick_eq; reflexivity.\n  Qed.\n\n  Lemma ToEnsemble_Size_refineEquiv' fs S0 (H : S0 ≃ fs)\n  : refineEquiv (ret (snd (CallMethod (projT1 FiniteSetImpl) sSize fs tt)))\n                (cardinal S0).\n  Proof.\n    handle_methods; unfold cardinal in *; t.\n    eapply cardinal_unique; eassumption.\n  Qed.\n  Lemma ToEnsemble_Size_refineEquiv fs (H : exists S0, forall S', S' ≅ S0 -> S' ≃ fs)\n  : refineEquiv (ret (snd (CallMethod (projT1 FiniteSetImpl) sSize fs tt)))\n                (cardinal (to_ensemble fs)).\n  Proof.\n    destruct H as [? H].\n    pose proof (H _ (reflexivity _)).\n    apply ToEnsemble_Size_refineEquiv', H; t.\n  Qed.\nEnd method_laws.\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/FiniteSetADTs/FiniteSetADTMethodLaws.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.28938232119177065}}
{"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 alphaeq5.\nRequire Export cvterm.\nRequire Export nat_defs.\nRequire Export cequiv_props4.\nRequire Export per_props_set.\nRequire Export per_props_union.\nRequire Export per_props_false.\nRequire Export per_props_not.\nRequire Export per_props_product.\nRequire Export types_converge.\n(*Require Export list.  (* ??? *)*)\n\n\nLemma nuprl_int {p} :\n  forall lib, @nuprl p lib mkc_int mkc_int (equality_of_int lib).\nProof.\n  sp.\n  apply CL_int.\n  unfold per_int; sp; spcast; try computes_to_value_refl.\nQed.\n\nLemma equality_of_int_xxx {p} :\n  forall lib, @close p lib (univ lib) mkc_int mkc_int (equality_of_int lib).\nProof.\n  apply nuprl_int.\nQed.\n\nLemma nat_in_int {p} : forall lib (n : nat), @member p lib (mkc_nat n) mkc_int.\nProof.\n  unfold member, equality; sp.\n  exists (@equality_of_int p lib).\n  sp;[apply equality_of_int_xxx|].\n  exists (Z_of_nat n); sp;\n  unfold mkc_nat, mkc_integer, isprog_mk_nat, isprog_mk_integer, mk_nat;\n    spcast; computes_to_value_refl.\nQed.\n\nLemma equality_in_int {p} :\n  forall lib (t1 t2 : @CTerm p),\n    equality lib t1 t2 mkc_int <=> equality_of_int lib t1 t2.\nProof.\n  intros; split; intro e.\n\n  - unfold equality, nuprl in e; exrepnd.\n    inversion e1; subst; try not_univ.\n    allunfold @per_int; sp.\n    discover; sp.\n\n  - unfold equality, nuprl.\n    exists (fun a b : @CTerm p => equality_of_int lib a b); dands; tcsp.\n    apply CL_int; unfold per_int; sp;\n    spcast; apply computes_to_value_isvalue_refl; repeat constructor; simpl; sp.\nQed.\n\nLemma hasvaluec_mkc_less {o} :\n  forall lib (a b c d : @CTerm o),\n    hasvaluec lib (mkc_less a b c d)\n    -> {k1 : Z\n        & {k2 : Z\n        & reduces_toc lib a (mkc_integer k1)\n        # reduces_toc lib b (mkc_integer k2)\n        # (((k1 < k2)%Z # hasvaluec lib c)\n           [+]\n           ((k2 <= k1)%Z # hasvaluec lib d)\n          )}}.\nProof.\n  introv hv.\n  destruct_cterms; allsimpl.\n  allunfold @hasvaluec; allsimpl.\n  allunfold @reduces_toc; allsimpl.\n  apply hasvalue_mk_less in hv; eauto 3 with slow.\nQed.\n\nLemma equality_in_less {o} :\n  forall lib (u v a b c d : @CTerm o),\n    equality lib u v (mkc_less a b c d)\n    <=>\n    {ka : Z\n     , {kb : Z\n        , a ===>(lib) (mkc_integer ka)\n        # b ===>(lib) (mkc_integer kb)\n        # (\n            ((ka < kb)%Z # equality lib u v c)\n            {+}\n            ((kb <= ka)%Z # equality lib u v d)\n          )}}.\nProof.\n  introv.\n\n  split; intro k; exrepnd.\n\n  - applydup @inhabited_implies_tequality in k.\n    apply types_converge in k0.\n    spcast.\n    apply hasvaluec_mkc_less in k0.\n    exrepnd.\n\n    exists k1 k0; dands; spcast; eauto with slow;\n    try (complete (apply computes_to_valc_iff_reduces_toc; dands; eauto with slow)).\n\n    assert (cequivc lib\n                    (mkc_less a b c d)\n                    (mkc_less (mkc_integer k1) (mkc_integer k0) c d)) as c1.\n    { apply reduces_toc_implies_cequivc.\n      destruct_cterms; allunfold @reduces_toc; allunfold @computes_to_valc; allsimpl.\n      apply reduce_to_prinargs_comp; eauto with slow.\n      allunfold @computes_to_value; sp; eauto with slow. }\n\n    repndors; repnd.\n\n    + left; dands; auto.\n\n      assert (cequivc lib\n                      (mkc_less (mkc_integer k1) (mkc_integer k0) c d)\n                      c) as c2.\n      { apply reduces_toc_implies_cequivc.\n        destruct_cterms; unfold reduces_toc; simpl.\n        apply reduces_to_if_step; csunf; simpl.\n        dcwf h; simpl.\n        unfold compute_step_comp; simpl; boolvar; tcsp; try omega. }\n\n      apply cequivc_sym in c1.\n      apply cequivc_sym in c2.\n      rwg c2.\n      rwg c1; auto.\n\n    + right; dands; auto.\n\n      assert (cequivc lib\n                      (mkc_less (mkc_integer k1) (mkc_integer k0) c d)\n                      d) as c2.\n      { apply reduces_toc_implies_cequivc.\n        destruct_cterms; unfold reduces_toc; simpl.\n        apply reduces_to_if_step; csunf; simpl.\n        dcwf h; simpl.\n        unfold compute_step_comp; simpl; boolvar; tcsp; try omega. }\n\n      apply cequivc_sym in c1.\n      apply cequivc_sym in c2.\n      rwg c2.\n      rwg c1; auto.\n\n  - spcast.\n    assert (cequivc lib\n                    (mkc_less a b c d)\n                    (mkc_less (mkc_integer ka) (mkc_integer kb) c d)) as c1.\n    { apply reduces_toc_implies_cequivc.\n      destruct_cterms; allunfold @reduces_toc; allunfold @computes_to_valc; allsimpl.\n      apply reduce_to_prinargs_comp; eauto with slow. }\n\n    rwg c1.\n\n    repndors; repnd.\n\n    + assert (cequivc lib\n                      (mkc_less (mkc_integer ka) (mkc_integer kb) c d)\n                      c) as c2.\n      { apply reduces_toc_implies_cequivc.\n        destruct_cterms; unfold reduces_toc; simpl.\n        apply reduces_to_if_step; csunf; simpl.\n        dcwf h; simpl.\n        unfold compute_step_comp; simpl; boolvar; tcsp; try omega. }\n\n      rwg c2; auto.\n\n    + assert (cequivc lib\n                      (mkc_less (mkc_integer ka) (mkc_integer kb) c d)\n                      d) as c2.\n      { apply reduces_toc_implies_cequivc.\n        destruct_cterms; unfold reduces_toc; simpl.\n        apply reduces_to_if_step; csunf; simpl.\n        dcwf h; simpl.\n        unfold compute_step_comp; simpl; boolvar; tcsp; try omega. }\n\n      rwg c2; auto.\nQed.\n\nLemma equality_in_true {o} :\n  forall lib (u v : @CTerm o),\n    equality lib u v mkc_true\n    <=>\n    (u ===>(lib) mkc_axiom\n     # v ===>(lib) mkc_axiom).\nProof.\n  introv.\n  rw @mkc_true_eq.\n  rw <- @equality_in_approx; split; intro k; dands; repnd; spcast; auto.\n  unfold approxc; simpl.\n  apply approx_decomp_axiom.\nQed.\n\nLemma equality_in_less_than {o} :\n  forall lib (u v a b : @CTerm o),\n    equality lib u v (mkc_less_than a b)\n    <=>\n    {ka : Z\n     , {kb : Z\n        , u ===>(lib) mkc_axiom\n        # v ===>(lib) mkc_axiom\n        # a ===>(lib) (mkc_integer ka)\n        # b ===>(lib) (mkc_integer kb)\n        # (ka < kb)%Z}}.\nProof.\n  introv.\n  rw @mkc_less_than_eq.\n  rw @equality_in_less.\n  split; intro k; exrepnd; spcast.\n  - repndors; repnd.\n    + apply equality_in_true in k1; repnd; spcast.\n      exists ka kb; dands; spcast; auto.\n    + apply equality_in_false in k1; sp.\n  - exists ka kb; dands; spcast; auto.\n    left; dands; auto.\n    apply equality_in_true; dands; spcast; auto.\nQed.\n\nLemma inhabited_less_than {o} :\n  forall lib (a b : @CTerm o),\n    inhabited_type lib (mkc_less_than a b)\n    <=>\n    {ka : Z\n     , {kb : Z\n        , a ===>(lib) (mkc_integer ka)\n        # b ===>(lib) (mkc_integer kb)\n        # (ka < kb)%Z}}.\nProof.\n  introv.\n  unfold inhabited_type; split; intro k; exrepnd; spcast.\n  - rw @equality_in_less_than in k0; exrepnd; spcast.\n    exists ka kb; dands; spcast; auto.\n  - exists (@mkc_axiom o).\n    apply equality_in_less_than.\n    exists ka kb; dands; spcast; auto;\n    apply computes_to_valc_refl; eauto with slow.\nQed.\n\nLemma tequality_mkc_less_aux {o} :\n  forall lib (a b c d e f g h : @CTerm o) ka kb ke kf,\n    computes_to_valc lib a (mkc_integer ka)\n    -> computes_to_valc lib b (mkc_integer kb)\n    -> computes_to_valc lib e (mkc_integer ke)\n    -> computes_to_valc lib f (mkc_integer kf)\n    -> (tequality lib (mkc_less a b c d) (mkc_less e f g h)\n        <=>\n        (\n          ((ka < kb)%Z # (ke < kf)%Z # tequality lib c g)\n          [+]\n          ((kb <= ka)%Z # (kf <= ke)%Z # tequality lib d h)\n          [+]\n          ((ka < kb)%Z # (kf <= ke)%Z # tequality lib c h)\n          [+]\n          ((kb <= ka)%Z # (ke < kf)%Z # tequality lib d g)\n        )\n       ).\nProof.\n  introv ca cb ce cf.\n\n  assert (cequivc lib\n                  (mkc_less a b c d)\n                  (mkc_less (mkc_integer ka) (mkc_integer kb) c d)) as c1.\n  { apply reduces_toc_implies_cequivc.\n    destruct_cterms; allunfold @reduces_toc; allunfold @computes_to_valc; allsimpl.\n    apply reduce_to_prinargs_comp; eauto with slow. }\n\n  assert (cequivc lib\n                  (mkc_less e f g h)\n                  (mkc_less (mkc_integer ke) (mkc_integer kf) g h)) as c2.\n  { apply reduces_toc_implies_cequivc.\n    destruct_cterms; allunfold @reduces_toc; allunfold @computes_to_valc; allsimpl.\n    apply reduce_to_prinargs_comp; eauto with slow. }\n\n  split; intro k; repnd.\n\n  - destruct (Z_lt_ge_dec ka kb); destruct (Z_lt_ge_dec ke kf).\n\n    + left; dands; auto.\n\n      assert (cequivc lib\n                      (mkc_less (mkc_integer ka) (mkc_integer kb) c d)\n                      c) as c3.\n      { apply reduces_toc_implies_cequivc.\n        destruct_cterms; unfold reduces_toc; simpl.\n        apply reduces_to_if_step; csunf; simpl.\n        dcwf h; simpl.\n        unfold compute_step_comp; simpl; boolvar; tcsp; try omega. }\n\n      assert (cequivc lib\n                      (mkc_less (mkc_integer ke) (mkc_integer kf) g h)\n                      g) as c4.\n      { apply reduces_toc_implies_cequivc.\n        destruct_cterms; unfold reduces_toc; simpl.\n        apply reduces_to_if_step; csunf; simpl.\n        dcwf h; simpl.\n        unfold compute_step_comp; simpl; boolvar; tcsp; try omega. }\n\n      apply cequivc_sym in c1.\n      apply cequivc_sym in c2.\n      apply cequivc_sym in c3.\n      apply cequivc_sym in c4.\n      rwg c3.\n      rwg c4.\n      rwg c1.\n      rwg c2; auto.\n\n    + right; right; left; dands; auto; try omega.\n\n      assert (cequivc lib\n                      (mkc_less (mkc_integer ka) (mkc_integer kb) c d)\n                      c) as c3.\n      { apply reduces_toc_implies_cequivc.\n        destruct_cterms; unfold reduces_toc; simpl.\n        apply reduces_to_if_step; csunf; simpl.\n        dcwf h; simpl.\n        unfold compute_step_comp; simpl; boolvar; tcsp; try omega. }\n\n      assert (cequivc lib\n                      (mkc_less (mkc_integer ke) (mkc_integer kf) g h)\n                      h) as c4.\n      { apply reduces_toc_implies_cequivc.\n        destruct_cterms; unfold reduces_toc; simpl.\n        apply reduces_to_if_step; csunf; simpl.\n        dcwf h; simpl.\n        unfold compute_step_comp; simpl; boolvar; tcsp; try omega. }\n\n      apply cequivc_sym in c1.\n      apply cequivc_sym in c2.\n      apply cequivc_sym in c3.\n      apply cequivc_sym in c4.\n      rwg c3.\n      rwg c4.\n      rwg c1.\n      rwg c2; auto.\n\n    + right; right; right; dands; auto; try omega.\n\n      assert (cequivc lib\n                      (mkc_less (mkc_integer ka) (mkc_integer kb) c d)\n                      d) as c3.\n      { apply reduces_toc_implies_cequivc.\n        destruct_cterms; unfold reduces_toc; simpl.\n        apply reduces_to_if_step; csunf; simpl.\n        dcwf h; simpl.\n        unfold compute_step_comp; simpl; boolvar; tcsp; try omega. }\n\n      assert (cequivc lib\n                      (mkc_less (mkc_integer ke) (mkc_integer kf) g h)\n                      g) as c4.\n      { apply reduces_toc_implies_cequivc.\n        destruct_cterms; unfold reduces_toc; simpl.\n        apply reduces_to_if_step; csunf; simpl.\n        dcwf h; simpl.\n        unfold compute_step_comp; simpl; boolvar; tcsp; try omega. }\n\n      apply cequivc_sym in c1.\n      apply cequivc_sym in c2.\n      apply cequivc_sym in c3.\n      apply cequivc_sym in c4.\n      rwg c3.\n      rwg c4.\n      rwg c1.\n      rwg c2; auto.\n\n    + right; left; dands; auto; try omega.\n\n      assert (cequivc lib\n                      (mkc_less (mkc_integer ka) (mkc_integer kb) c d)\n                      d) as c3.\n      { apply reduces_toc_implies_cequivc.\n        destruct_cterms; unfold reduces_toc; simpl.\n        apply reduces_to_if_step; csunf; simpl.\n        dcwf h; simpl.\n        unfold compute_step_comp; simpl; boolvar; tcsp; try omega. }\n\n      assert (cequivc lib\n                      (mkc_less (mkc_integer ke) (mkc_integer kf) g h)\n                      h) as c4.\n      { apply reduces_toc_implies_cequivc.\n        destruct_cterms; unfold reduces_toc; simpl.\n        apply reduces_to_if_step; csunf; simpl.\n        dcwf h; simpl.\n        unfold compute_step_comp; simpl; boolvar; tcsp; try omega. }\n\n      apply cequivc_sym in c1.\n      apply cequivc_sym in c2.\n      apply cequivc_sym in c3.\n      apply cequivc_sym in c4.\n      rwg c3.\n      rwg c4.\n      rwg c1.\n      rwg c2; auto.\n\n  - rwg c1.\n    rwg c2.\n    clear c1 c2 ca cb ce cf.\n    repndors; exrepnd.\n\n    + assert (cequivc lib\n                      (mkc_less (mkc_integer ka) (mkc_integer kb) c d)\n                      c) as c3.\n      { apply reduces_toc_implies_cequivc.\n        destruct_cterms; unfold reduces_toc; simpl.\n        apply reduces_to_if_step; csunf; simpl.\n        dcwf h; simpl.\n        unfold compute_step_comp; simpl; boolvar; tcsp; try omega. }\n\n      assert (cequivc lib\n                      (mkc_less (mkc_integer ke) (mkc_integer kf) g h)\n                      g) as c4.\n      { apply reduces_toc_implies_cequivc.\n        destruct_cterms; unfold reduces_toc; simpl.\n        apply reduces_to_if_step; csunf; simpl.\n        dcwf h; simpl.\n        unfold compute_step_comp; simpl; boolvar; tcsp; try omega. }\n\n      rwg c3.\n      rwg c4; auto.\n\n    + assert (cequivc lib\n                      (mkc_less (mkc_integer ka) (mkc_integer kb) c d)\n                      d) as c3.\n      { apply reduces_toc_implies_cequivc.\n        destruct_cterms; unfold reduces_toc; simpl.\n        apply reduces_to_if_step; csunf; simpl.\n        dcwf h; simpl.\n        unfold compute_step_comp; simpl; boolvar; tcsp; try omega. }\n\n      assert (cequivc lib\n                      (mkc_less (mkc_integer ke) (mkc_integer kf) g h)\n                      h) as c4.\n      { apply reduces_toc_implies_cequivc.\n        destruct_cterms; unfold reduces_toc; simpl.\n        apply reduces_to_if_step; csunf; simpl.\n        dcwf h; simpl.\n        unfold compute_step_comp; simpl; boolvar; tcsp; try omega. }\n\n      rwg c3.\n      rwg c4; auto.\n\n    + assert (cequivc lib\n                      (mkc_less (mkc_integer ka) (mkc_integer kb) c d)\n                      c) as c3.\n      { apply reduces_toc_implies_cequivc.\n        destruct_cterms; unfold reduces_toc; simpl.\n        apply reduces_to_if_step; csunf; simpl.\n        dcwf h; simpl.\n        unfold compute_step_comp; simpl; boolvar; tcsp; try omega. }\n\n      assert (cequivc lib\n                      (mkc_less (mkc_integer ke) (mkc_integer kf) g h)\n                      h) as c4.\n      { apply reduces_toc_implies_cequivc.\n        destruct_cterms; unfold reduces_toc; simpl.\n        apply reduces_to_if_step; csunf; simpl.\n        dcwf h; simpl.\n        unfold compute_step_comp; simpl; boolvar; tcsp; try omega. }\n\n      rwg c3.\n      rwg c4; auto.\n\n    + assert (cequivc lib\n                      (mkc_less (mkc_integer ka) (mkc_integer kb) c d)\n                      d) as c3.\n      { apply reduces_toc_implies_cequivc.\n        destruct_cterms; unfold reduces_toc; simpl.\n        apply reduces_to_if_step; csunf; simpl.\n        dcwf h; simpl.\n        unfold compute_step_comp; simpl; boolvar; tcsp; try omega. }\n\n      assert (cequivc lib\n                      (mkc_less (mkc_integer ke) (mkc_integer kf) g h)\n                      g) as c4.\n      { apply reduces_toc_implies_cequivc.\n        destruct_cterms; unfold reduces_toc; simpl.\n        apply reduces_to_if_step; csunf; simpl.\n        dcwf h; simpl.\n        unfold compute_step_comp; simpl; boolvar; tcsp; try omega. }\n\n      rwg c3.\n      rwg c4; auto.\nQed.\n\nLemma tequality_mkc_less {o} :\n  forall lib (a b c d e f g h : @CTerm o),\n    tequality lib (mkc_less a b c d) (mkc_less e f g h)\n    <=>\n    {ka : Z\n     , {kb : Z\n     , {ke : Z\n     , {kf : Z\n        , a ===>(lib) (mkc_integer ka)\n        # b ===>(lib) (mkc_integer kb)\n        # e ===>(lib) (mkc_integer ke)\n        # f ===>(lib) (mkc_integer kf)\n        # (\n            ((ka < kb)%Z # (ke < kf)%Z # tequality lib c g)\n            {+}\n            ((kb <= ka)%Z # (kf <= ke)%Z # tequality lib d h)\n            {+}\n            ((ka < kb)%Z # (kf <= ke)%Z # tequality lib c h)\n            {+}\n            ((kb <= ka)%Z # (ke < kf)%Z # tequality lib d g)\n          )}}}}.\nProof.\n  introv.\n\n  split; intro k; exrepnd.\n\n  - applydup @tequality_refl in k.\n    applydup @tequality_sym in k.\n    apply tequality_refl in k1.\n    allrw @fold_type.\n    apply types_converge in k0.\n    apply types_converge in k1.\n    spcast.\n\n    apply hasvaluec_mkc_less in k0.\n    apply hasvaluec_mkc_less in k1.\n    exrepnd.\n\n    exists k6 k0 k2 k1; dands; spcast; eauto with slow;\n    try (complete (apply computes_to_valc_iff_reduces_toc; dands; eauto with slow)).\n\n    pose proof (tequality_mkc_less_aux\n                  lib a b c d e f g h k6 k0 k2 k1) as p.\n    repeat (autodimp p hyp);\n    try (complete (apply computes_to_valc_iff_reduces_toc; dands; eauto with slow)).\n    apply p in k; sp.\n\n  - pose proof (tequality_mkc_less_aux\n                  lib a b c d e f g h ka kb ke kf) as p.\n    spcast.\n    repeat (autodimp p hyp).\n    apply p.\n\n    destruct (Z_lt_ge_dec ka kb); destruct (Z_lt_ge_dec ke kf).\n\n    + left; dands; auto.\n      repndors; repnd; try omega; auto.\n\n    + right; right; left; dands; auto; try omega.\n      repndors; repnd; try omega; auto.\n\n    + right; right; right; dands; auto; try omega.\n      repndors; repnd; try omega; auto.\n\n    + right; left; dands; auto; try omega.\n      repndors; repnd; try omega; auto.\nQed.\n\nLemma true_not_equal_to_false {o} :\n  forall (lib : @library o),\n    !tequality lib mkc_true mkc_false.\nProof.\n  introv teq.\n  unfold tequality, nuprl in teq; exrepnd.\n  inversion teq0; subst; try not_univ.\n  - duniv j h.\n    allrw @univi_exists_iff; exrepd; spcast; repeat computes_to_value_isvalue.\n  - allunfold @per_approx; exrepnd; spcast; repeat computes_to_value_isvalue.\n    match goal with\n      | [ H : computes_to_valc ?a ?b ?c |- _ ] => rename H into k\n    end.\n\n    apply @computes_to_valc_isvalue_eq in k; try (apply iscvalue_mkc_true).\n    allrw @mkc_true_eq.\n    allrw @mkc_false_eq.\n    allapply @mkc_approx_eq; repnd; subst.\n\n    match goal with\n      | [ H : _ <=> _ |- _ ] => rename H into h\n    end.\n    destruct h.\n    destruct c as [k]; spcast.\n\n    { unfold approxc; simpl.\n      apply approx_decomp_axiom. }\n\n    apply not_axiom_approxc_bot in k; sp.\nQed.\n\nLemma type_mkc_true {o} :\n  forall (lib : @library o), type lib mkc_true.\nProof.\n  introv; rw @mkc_true_eq.\n  apply tequality_mkc_approx; sp.\nQed.\n\nLemma tequality_mkc_less_than {o} :\n  forall lib (a b c d : @CTerm o),\n    tequality lib (mkc_less_than a b) (mkc_less_than c d)\n    <=>\n    {ka : Z\n     , {kb : Z\n     , {kc : Z\n     , {kd : Z\n        , a ===>(lib) (mkc_integer ka)\n        # b ===>(lib) (mkc_integer kb)\n        # c ===>(lib) (mkc_integer kc)\n        # d ===>(lib) (mkc_integer kd)\n        # (\n            ((ka < kb)%Z # (kc < kd)%Z)\n            {+}\n            ((kb <= ka)%Z # (kd <= kc)%Z)\n          )}}}}.\nProof.\n  introv.\n  allrw @mkc_less_than_eq.\n  rw (tequality_mkc_less\n        lib a b mkc_true mkc_false c d mkc_true mkc_false).\n\n  split; intro k; exrepnd.\n\n  - exists ka kb ke kf; dands; auto.\n    repndors; repnd; tcsp.\n\n    + apply true_not_equal_to_false in k1; sp.\n\n    + apply tequality_sym in k1.\n      apply true_not_equal_to_false in k1; sp.\n\n  - exists ka kb kc kd; dands; auto.\n    repndors; repnd; tcsp.\n\n    left; sp.\n    apply type_mkc_true.\nQed.\n\nLemma equality_in_le {o} :\n  forall lib (u v a b : @CTerm o),\n    equality lib u v (mkc_le a b)\n    <=>\n    {ka : Z\n     , {kb : Z\n        , a ===>(lib) (mkc_integer ka)\n        # b ===>(lib) (mkc_integer kb)\n        # (ka <= kb)%Z}}.\nProof.\n  introv.\n  rw @mkc_le_eq.\n  rw @equality_in_not.\n  rw @tequality_mkc_less_than.\n  rw @inhabited_less_than.\n  split; intro k; exrepnd; spcast; dands.\n  - repeat computes_to_eqval.\n    exists kb ka; dands; spcast; auto.\n    repndors; repnd; tcsp.\n    destruct k.\n    exists ka kb; dands; spcast; auto.\n  - exists kb ka kb ka; dands; spcast; auto.\n  - intro h; exrepnd; spcast.\n    repeat computes_to_eqval.\n    omega.\nQed.\n\nLemma inhabited_le {o} :\n  forall lib (a b : @CTerm o),\n    inhabited_type lib (mkc_le a b)\n    <=>\n    {ka : Z\n     , {kb : Z\n        , a ===>(lib) (mkc_integer ka)\n        # b ===>(lib) (mkc_integer kb)\n        # (ka <= kb)%Z}}.\nProof.\n  introv.\n  unfold inhabited_type; split; intro k; exrepnd; spcast.\n  - apply equality_in_le in k0; exrepnd; spcast.\n    exists ka kb; dands; spcast; auto.\n  - exists (@mkc_axiom o).\n    apply equality_in_le.\n    exists ka kb; dands; spcast; auto.\nQed.\n\nLemma tequality_mkc_le {o} :\n  forall lib (a b c d : @CTerm o),\n    tequality lib (mkc_le a b) (mkc_le c d)\n    <=>\n    {ka : Z\n     , {kb : Z\n     , {kc : Z\n     , {kd : Z\n        , a ===>(lib) (mkc_integer ka)\n        # b ===>(lib) (mkc_integer kb)\n        # c ===>(lib) (mkc_integer kc)\n        # d ===>(lib) (mkc_integer kd)\n        # (\n            ((ka <= kb)%Z # (kc <= kd)%Z)\n            {+}\n            ((kb < ka)%Z # (kd < kc)%Z)\n          )}}}}.\nProof.\n  introv.\n  allrw @mkc_le_eq.\n  rw @tequality_not.\n  rw @tequality_mkc_less_than.\n\n  split; intro k; exrepnd.\n\n  - exists kb ka kd kc; dands; auto.\n    repndors; repnd; tcsp.\n\n  - exists kb ka kd kc; dands; auto.\n    repndors; repnd; tcsp.\nQed.\n\n\nHint Resolve computes_to_valc_refl : slow.\n\nLemma tequality_int {p} : forall lib, @tequality p lib mkc_int mkc_int.\nProof.\n  introv.\n  exists (@equality_of_int p lib).\n  apply CL_int; split; dands; spcast; eauto 3 with slow.\nQed.\nHint Resolve tequality_int : slow.\n\nHint Rewrite @mkcv_le_substc   : slow.\nHint Rewrite @substc_mkcv_zero : slow.\n\nLemma tnat_type {o} : forall lib, @type o lib mkc_tnat.\nProof.\n  introv.\n  rw @mkc_tnat_eq.\n  apply tequality_set; dands; eauto 3 with slow.\n  introv ea.\n  autorewrite with slow.\n  apply tequality_mkc_le.\n  apply equality_in_int in ea.\n  unfold equality_of_int in ea; exrepnd; spcast.\n  exists 0%Z k 0%Z k.\n  rw @mkc_zero_eq; rw @mkc_nat_eq; simpl.\n  dands; spcast; auto; eauto 3 with slow.\n  destruct (Z_lt_le_dec k 0); tcsp.\nQed.\n\n(*\n\n  We could also have defined this type using 0 < y.\n  I used 1 <= y because the proofs will be similar to the ones for tnat.\n\n *)\nDefinition mk_tnatp {o} := @mk_set o mk_int nvary (mk_le mk_one (mk_var nvary)).\n\nLemma isprog_tnatp {o} : @isprog o mk_tnatp.\nProof.\n  rw <- @isprog_set_iff.\n  dands; eauto 3 with slow.\nQed.\n\nDefinition mkc_tnatp {o} : @CTerm o := exist isprog mk_tnatp isprog_tnatp.\n\nLemma mkc_tnatp_eq {o} :\n  @mkc_tnatp o = mkc_set mkc_int nvary (mkcv_le [nvary] (mkcv_one [nvary]) (mkc_var nvary)).\nProof.\n  apply cterm_eq; simpl; sp.\nQed.\n\nLemma mkcv_one_substc {o} :\n  forall v (t : @CTerm o),\n    substc t v (mkcv_one [v]) = mkc_one.\nProof.\n  introv.\n  destruct_cterms.\n  apply cterm_eq; simpl; sp.\nQed.\n\n(*\nLemma nuprl_tnatp {o} :\n  forall lib,\n  nuprl\n    lib\n    mkc_tnatp\n    mkc_tnatp\n    (fun (t t' : @CTerm o) =>\n       { _ : equality_of_int lib t t'\n                             &\n                             inhabited\n                             (fun _ _ : @CTerm o =>\n                                forall u v : @CTerm o,\n                                  (forall k : Z,\n                                     computes_to_valc lib t (mkc_integer k) ->\n                                     if (k <? 1)%Z\n                                     then u ===>(lib) mkc_axiom # v ===>(lib) mkc_axiom\n                                     else False) -> False)}).\nProof.\n  introv.\n  rw @mkc_tnatp_eq.\n  apply CL_set; fold (@nuprl o).\n  unfold per_set.\n  exists (@equality_of_int o lib).\n  exists\n    (fun (a a' : @CTerm o)\n         (e : equality_of_int lib a a')\n         (t t' : @CTerm o) =>\n       forall (u v : @CTerm o),\n         (forall k,\n            computes_to_valc lib a (mkc_integer k)\n            -> if (k <? 1)%Z\n               then u ===>(lib) mkc_axiom # v ===>(lib) mkc_axiom\n               else False)\n         -> False);\n    dands; auto.\n\n  - unfold type_family.\n    eexists; eexists; eexists; eexists; eexists; eexists;\n    dands; auto; spcast; try (fold nuprl).\n\n    + apply computes_to_valc_refl; apply iscvalue_mkc_set.\n\n    + apply computes_to_valc_refl; apply iscvalue_mkc_set.\n\n    + apply nuprl_int.\n\n    + introv e.\n      allrw @mkcv_le_substc.\n      allrw @mkcv_one_substc.\n      allrw @mkc_var_substc.\n      allrw @mkc_le_eq.\n      unfold equality_of_int in e; exrepnd; spcast.\n\n      apply CL_func.\n      unfold per_func.\n      exists (fun t t' : @CTerm o =>\n                if (k <? 1)%Z\n                then t ===>(lib) mkc_axiom # t' ===>(lib) mkc_axiom\n                else False).\n      exists (fun (a a' : @CTerm o) (e : if (k <? 1)%Z\n                            then a ===>(lib) mkc_axiom # a' ===>(lib) mkc_axiom\n                            else False) (t t' : @CTerm o) => False).\n      dands; auto.\n\n      * unfold type_family.\n        eexists; eexists; eexists; eexists; eexists; eexists;\n        dands; auto; spcast; try (fold nuprl).\n\n        unfold mkc_not.\n        rw <- @fold_mkc_fun.\n        apply computes_to_valc_refl.\n        apply iscvalue_mkc_function.\n\n        unfold mkc_not.\n        rw <- @fold_mkc_fun.\n        apply computes_to_valc_refl.\n        apply iscvalue_mkc_function.\n\n        remember ((k <? 1)%Z); symmetry in Heqb; destruct b.\n\n        apply Z.ltb_lt in Heqb.\n\n        pose proof (mkc_less_than_comp1 lib a mkc_one k 1) as h1; repeat (autodimp h1 hyp); try omega.\n        unfold computes_to_valc; simpl; unfold mk_one, mk_nat; simpl.\n        apply computes_to_value_isvalue_refl; apply isvalue_mk_integer.\n\n        pose proof (mkc_less_than_comp1 lib a' mkc_one k 1) as h2; repeat (autodimp h2 hyp); try omega.\n        unfold computes_to_valc; simpl; unfold mk_one, mk_nat; simpl.\n        apply computes_to_value_isvalue_refl; apply isvalue_mk_integer.\n\n        apply nuprl_value_respecting_left with (t1 := mkc_true).\n        apply nuprl_value_respecting_right with (t2 := mkc_true).\n        apply nuprl_mkc_true.\n        apply cequivc_sym; apply computes_to_valc_implies_cequivc; sp.\n        apply cequivc_sym; apply computes_to_valc_implies_cequivc; sp.\n\n        apply Z.ltb_ge in Heqb.\n\n        pose proof (mkc_less_than_comp2 lib a mkc_one k 1) as h1; repeat (autodimp h1 hyp); try omega.\n        unfold computes_to_valc; simpl; unfold mk_one, mk_nat; simpl.\n        apply computes_to_value_isvalue_refl; apply isvalue_mk_integer.\n\n        pose proof (mkc_less_than_comp2 lib a' mkc_one k 1) as h2; repeat (autodimp h2 hyp); try omega.\n        unfold computes_to_valc; simpl; unfold mk_zero, mk_nat; simpl.\n        apply computes_to_value_isvalue_refl; apply isvalue_mk_integer.\n\n        apply nuprl_computes_left with (t1 := mkc_false); auto.\n        apply nuprl_computes_right with (t2 := mkc_false); auto.\n        rw @mkc_false_eq.\n        apply CL_approx.\n        unfold per_approx.\n        eexists; eexists; eexists; eexists; dands; auto; spcast.\n        apply computes_to_valc_refl; apply iscvalue_mkc_approx.\n        apply computes_to_valc_refl; apply iscvalue_mkc_approx.\n        introv; split; intro j; repnd; sp; spcast.\n        apply not_axiom_approxc_bot in j; auto.\n\n        introv e; simphyps.\n        allrw @csubst_mk_cv.\n        rw @mkc_void_eq_mkc_false; rw @mkc_false_eq.\n        apply CL_approx.\n        unfold per_approx.\n        eexists; eexists; eexists; eexists; dands; auto; spcast.\n        apply computes_to_valc_refl; apply iscvalue_mkc_approx.\n        apply computes_to_valc_refl; apply iscvalue_mkc_approx.\n        sp; split; intro j; repnd; sp; spcast.\n        apply not_axiom_approxc_bot in j; auto.\n\n      * intros; split; intro j; introv m.\n\n        apply j with (u := a0) (v := a'0); auto.\n        introv c.\n        pose proof (computes_to_valc_eq lib a (mkc_integer k) (mkc_integer k0)) as e;\n          repeat (autodimp e hyp).\n        inversion e; subst; GC; sp.\n\n        pose proof (m k) as l; autodimp l hyp.\n        apply j in l; sp.\n\n  - introv.\n    split; intro k; exrepnd.\n    exists v; sp.\n    exists e; sp.\nQed.\n*)\n\nLemma mkc_one_eq {o} :\n  @mkc_one o = mkc_nat 1.\nProof.\n  apply cterm_eq; simpl; auto.\nQed.\n\nLemma tnatp_type {o} : forall lib, @type o lib mkc_tnatp.\nProof.\n  introv.\n  rw @mkc_tnatp_eq.\n  apply tequality_set; dands; eauto 3 with slow.\n  introv ea.\n  autorewrite with slow.\n  apply tequality_mkc_le.\n  apply equality_in_int in ea.\n  unfold equality_of_int in ea; exrepnd; spcast.\n  exists 1%Z k 1%Z k.\n  rw @mkc_one_eq; rw @mkc_nat_eq; simpl.\n  dands; spcast; auto; eauto 3 with slow.\n  destruct (Z_lt_le_dec k 1); tcsp.\nQed.\n\nDefinition reducek_pair {o} lib (t1 t2 : @NTerm o) (k : Z) (n : nat) :=\n    reduces_in_atmost_k_steps lib t1 (mk_integer k) n\n  # reduces_in_atmost_k_steps lib t2 (mk_integer k) n.\n\nDefinition equality_of_int_p_2 {o} lib (n m : @NTerm o) :=\n  {x : Z # nat , reducek_pair lib n m (fst x) (snd x)}.\n\nDefinition equality_of_int_p_2_c {o} lib (n m : @CTerm o) :=\n  equality_of_int_p_2 lib (get_cterm n) (get_cterm m).\n\nLemma equality_of_int_imp1 {o} :\n  forall lib (n m : @CTerm o),\n    equality_of_int lib n m\n    <-> equality_of_int_p_2_c lib n m.\nProof.\n  introv; split.\n  - introv e.\n    unfold equality_of_int in e; exrepnd; spcast.\n    allunfold @computes_to_valc; allsimpl.\n    allunfold @computes_to_value; repnd.\n    allunfold @reduces_to; exrepnd.\n    allunfold @reduces_in_atmost_k_steps.\n    pose proof (no_change_after_value2 lib\n                  (get_cterm n) k1 (mk_integer k) e2 e1 (Peano.max k1 k0)) as h1.\n    autodimp h1 hyp; try (apply max_prop1).\n    pose proof (no_change_after_value2 lib\n                (get_cterm m) k0 (mk_integer k) e4 e0 (Peano.max k1 k0)) as h2.\n    autodimp h2 hyp; try (apply max_prop2).\n    exists ((k,Peano.max k1 k0)); simpl; sp.\n    unfold reducek_pair; sp.\n  - introv e.\n    unfold equality_of_int.\n    unfold equality_of_int_p_2_c, equality_of_int_p_2, reducek_pair in e.\n    exrepnd; allsimpl.\n    exists x0; dands; spcast;\n    unfold computes_to_valc, computes_to_value; simpl;\n    dands; try (apply isvalue_mk_integer);\n    exists x; auto.\nQed.\n\nLemma compute_step_dec {o} :\n  forall lib (t : @NTerm o),\n    {u : NTerm $ compute_step lib t = csuccess u}\n    [+]\n    !{u : NTerm $ compute_step lib t = csuccess u}.\nProof.\n  introv.\n  remember (compute_step lib t); destruct c.\n  - left.\n    exists n; sp.\n  - right; intro k; exrepnd; inversion k0.\nQed.\n\n(*\nLemma reduces_in_atmost_k_steps_dec {o} :\n  forall lib (pc : dec_consts o) k (t1 t2 : @NTerm o),\n    reduces_in_atmost_k_steps lib t1 t2 k [+] !(reduces_in_atmost_k_steps lib t1 t2 k).\nProof.\n  induction k; introv.\n\n  - rw @reduces_in_atmost_k_steps_0.\n    pose proof (deq_nterm pc t1 t2) as h; sp.\n\n  - rw @reduces_in_atmost_k_steps_S.\n    pose proof (compute_step_dec lib t1) as h.\n    dorn h.\n\n    + exrepnd.\n      pose proof (IHk u t2) as j.\n      dorn j.\n\n      * left.\n        exists u; sp.\n\n      * right.\n        intro c; exrepnd.\n        rw h0 in c1; inversion c1; subst; sp.\n\n    + right; intro j; exrepnd.\n      apply h.\n      exists u; sp.\nQed.\n*)\n\nLemma deq_nterm_int {p} :\n  forall (t : @NTerm p) z, {t = mk_integer z} + {t <> mk_integer z}.\nProof.\n  introv.\n  nterm_ind1 t as [v1|f1 ind|o1 lbt1 Hind] Case; intros.\n\n  - Case \"vterm\".\n    right; intro k; inversion k.\n\n  - Case \"sterm\".\n    right; intro k; inversion k.\n\n  - Case \"oterm\".\n    destruct o1; try (complete (right; intro k; inversion k)).\n    destruct c; try (complete (right; intro k; inversion k)).\n    destruct lbt1; try (complete (right; intro k; inversion k)).\n    assert ({z < z0} + {z > z0} + {z = z0})%Z as h by (apply Z_dec).\n    destruct h as [ h | h ]; subst.\n    destruct h as [ h | h ]; sp; right; sp; inversion H; omega.\n    left; sp.\nQed.\n\nLemma reduces_in_atmost_k_steps_int_dec {o} :\n  forall lib k (t : @NTerm o) z,\n    reduces_in_atmost_k_steps lib t (mk_integer z) k\n    [+]\n    !(reduces_in_atmost_k_steps lib t (mk_integer z) k).\nProof.\n  induction k; introv.\n\n  - rw @reduces_in_atmost_k_steps_0.\n    pose proof (deq_nterm_int t z) as h; sp.\n\n  - rw @reduces_in_atmost_k_steps_S.\n    pose proof (compute_step_dec lib t) as h.\n    dorn h.\n\n    + exrepnd.\n      pose proof (IHk u z) as j.\n      dorn j.\n\n      * left.\n        exists u; sp.\n\n      * right.\n        intro c; exrepnd.\n        rw h0 in c1; inversion c1; subst; sp.\n\n    + right; intro j; exrepnd.\n      apply h.\n      exists u; sp.\nQed.\n\nLemma reducek_pair_dec {o} :\n  forall lib (t1 t2 : @NTerm o) z n,\n    reducek_pair lib t1 t2 z n [+] !(reducek_pair lib t1 t2 z n).\nProof.\n  introv.\n  unfold reducek_pair.\n  pose proof (reduces_in_atmost_k_steps_int_dec lib n t1 z) as h1.\n  pose proof (reduces_in_atmost_k_steps_int_dec lib n t2 z) as h2.\n  dorn h1; dorn h2.\n  - left; sp.\n  - right; sp.\n  - right; sp.\n  - right; sp.\nQed.\n\n\n(*\n\n  The following is an adaptation of:\n     http://coq.inria.fr/stdlib/Coq.Logic.ConstructiveEpsilon.html\n  This is required to prove equality_of_int_imp_t without using\n  the indefinite_description axiom.\n\n*)\n\nInductive before_witness (P : Z -> nat -> Prop) (k : nat) : Prop :=\n  | stop_pos : forall (z n : nat), k = z + n -> P (Z.of_nat z) n -> before_witness P k\n  | stop_neg : forall z n, k = z + n -> P (Z.opp (Z.of_nat z)) n -> before_witness P k\n  | next : before_witness P (S k) -> before_witness P k.\n\nFixpoint O_witness\n         (P : Z -> nat -> Prop)\n         (k : nat) : before_witness P k -> before_witness P 0 :=\n  match k return (before_witness P k -> before_witness P 0) with\n    | 0 => fun b => b\n    | S n => fun b => O_witness P n (next P n b)\n  end.\n\nDefinition inv_before_witness :\n  forall (P : Z -> nat -> Prop) (k : nat),\n    before_witness P k\n    -> (forall z n : nat, k = z + n -> ~ P (Z.of_nat z) n # ~ P (Z.opp (Z.of_nat z)) n)\n    -> before_witness P (S k) :=\n  fun P k b =>\n    match b\n          in before_witness _ _\n          return (forall z n, k = z + n -> ~ P (Z.of_nat z) n # ~ P (Z.opp (Z.of_nat z)) n)\n                 -> before_witness P (S k) with\n      | stop_pos _ _ z n e p => fun f => match fst (f z n e) p with end\n      | stop_neg _ _ z n e p => fun f => match snd (f z n e) p with end\n      | next _ _ b => fun _ => b\n    end.\n\nLemma leS:\n  forall n m : nat, n <= S m -> n <= m [+] n = S m.\nProof.\n  introv; revert n.\n  induction m; simpl; introv e.\n  - destruct n; sp.\n    destruct n; sp.\n    provefalse.\n    inversion e as [|x h].\n    inversion h.\n  - apply leb_correct in e.\n    destruct n; allsimpl.\n    + left; omega.\n    + apply leb_complete in e.\n      apply IHm in e; dorn e.\n      left; omega.\n      right; omega.\nQed.\n\n(* This is the crux of linear_search *)\nLemma P_search :\n  forall (P : Z -> nat -> Prop)\n         (dec : forall z n, P z n [+] !P z n)\n         (k : nat),\n    {x : Z # nat & P (fst x) (snd x)}\n    [+]\n    (forall z n : nat, k = (z + n)%nat -> ~ P (Z.of_nat z) n # ~ P (Z.opp (Z.of_nat z)) n).\nProof.\n  intros P dec k.\n\n  assert (forall k z,\n            {x : Z # nat & P (fst x) (snd x)}\n              [+]\n              (forall n : nat, n <= k -> ~ P (Z.of_nat z) n # ~ P (Z.opp (Z.of_nat z)) n)) as hyp1.\n  clear k.\n  introv.\n  induction k.\n  pose proof (dec (Z.of_nat z) 0) as h.\n  dorn h.\n  left; exists (Z.of_nat z,0); simpl; sp.\n  pose proof (dec (Z.opp (Z.of_nat z)) 0) as j.\n  dorn j.\n  left; exists (Z.opp (Z.of_nat z),0); simpl; sp.\n  right; introv e.\n  assert (n = 0) by omega; subst; simpl; sp.\n  dorn IHk.\n  left; auto.\n  pose proof (dec (Z.of_nat z) (S k)) as h.\n  dorn h.\n  left; exists (Z.of_nat z,S k); simpl; sp.\n  pose proof (dec (Z.opp (Z.of_nat z)) (S k)) as j.\n  dorn j.\n  left; exists (Z.opp (Z.of_nat z),S k); simpl; sp.\n  right; introv e; simpl.\n  apply leS in e.\n  dorn e.\n  apply IHk in e; sp.\n  subst; sp.\n\n  assert (forall k n,\n            {x : Z # nat & P (fst x) (snd x)}\n              [+]\n              (forall z : nat, z <= k -> ~ P (Z.of_nat z) n # ~ P (Z.opp (Z.of_nat z)) n)) as hyp2.\n  clear k.\n  introv.\n  induction k.\n  pose proof (dec 0%Z n) as h.\n  dorn h.\n  left; exists (0%Z,n); simpl; sp.\n  right; introv e.\n  assert (z = 0) by omega; subst; simpl; sp.\n  dorn IHk.\n  left; auto.\n  pose proof (dec (Z.of_nat (S k)) n) as h.\n  dorn h.\n  left; exists (Z.of_nat (S k),n); simpl; sp.\n  pose proof (dec (Z.opp (Z.of_nat (S k))) n) as j.\n  dorn j.\n  left; exists (Z.opp (Z.of_nat (S k)),n); simpl; sp.\n  right; introv e; simpl.\n  apply leS in e.\n  dorn e.\n  apply IHk in e; sp.\n  subst; sp.\n\n  assert ({x : Z # nat & P (fst x) (snd x)}\n            [+]\n            (forall z n : nat, z <= k -> n <= k -> ~ P (Z.of_nat z) n # ~ P (Z.opp (Z.of_nat z)) n)) as hyp.\n  induction k.\n  pose proof (dec 0%Z 0) as h.\n  dorn h.\n  left; exists (0%Z,0); simpl; sp.\n  right; introv e1 e2.\n  assert (z = 0) by omega; assert (n = 0) by omega; subst; simpl; sp.\n  dorn IHk.\n  left; auto.\n  pose proof (hyp1 (S k) (S k)) as h1.\n  dorn h1.\n  left; auto.\n  pose proof (hyp2 (S k) (S k)) as h2.\n  dorn h2.\n  left; auto.\n  right; introv e1 e2.\n  apply leS in e1.\n  apply leS in e2.\n  dorn e1; dorn e2; subst.\n  apply IHk; auto.\n  apply h2; auto.\n  apply h1; auto.\n  apply h1; sp.\n\n  dorn hyp.\n  left; auto.\n  right.\n  introv e; subst.\n  apply hyp; omega.\nQed.\n\nFixpoint linear_search\n      (P : Z -> nat -> Prop)\n      (dec : forall z n, P z n [+] !P z n)\n      (k : nat)\n      (b : before_witness P k) : {x : Z # nat & P (fst x) (snd x)} :=\n  match P_search P dec k with\n    | inl p => p\n    | inr a => linear_search P dec (S k) (inv_before_witness P k b a)\n  end.\n\nDefinition constructive_indefinite_ground_description_nat {o}\n           lib (t1 t2 : @CTerm o) :\n  equality_of_int_p_2_c lib t1 t2\n  -> {x : Z # nat & reducek_pair lib (get_cterm t1) (get_cterm t2) (fst x) (snd x)}.\nProof.\n  introv pex.\n  apply linear_search with (k := 0).\n  apply reducek_pair_dec; auto.\n  unfold equality_of_int_p_2_c, equality_of_int_p_2 in pex; auto.\n  exrepnd; allsimpl.\n  apply O_witness with (k := Z.abs_nat x0 + x).\n  pose proof (Zabs.Zabs_dec x0) as h.\n  dorn h.\n  - apply stop_pos with (z := Z.abs_nat x0) (n := x); auto.\n    rw h in pex0.\n    rw Znat.Zabs2Nat.id_abs; auto.\n  - apply stop_neg with (z := Z.abs_nat x0) (n := x); auto.\n    rw h in pex0.\n    rw Znat.Zabs2Nat.id_abs; auto.\nQed.\n\n(*\n\n   Thanks to constructive_indefinite_ground_description_nat,\n   the following proof does not need the indefinite_description axiom\n\n *)\n\nDefinition equality_of_int_t {o} lib (n m : @CTerm o) :=\n  {k : Z | n ===>(lib) (mkc_integer k)\n         # m ===>(lib) (mkc_integer k)}.\n\nLemma equality_of_int_imp_t {o} :\n  forall lib (n m : @CTerm o),\n    equality_of_int lib n m\n    -> equality_of_int_t lib n m.\nProof.\n  introv e.\n  apply equality_of_int_imp1 in e.\n  apply constructive_indefinite_ground_description_nat in e; auto.\n  exrepnd; allsimpl.\n  unfold equality_of_int_t.\n  unfold reducek_pair in e0; repnd.\n  exists x0; dands; spcast;\n  unfold computes_to_valc, computes_to_value; simpl;\n  dands; try (apply isvalue_mk_integer);\n  exists x; auto.\nQed.\n\n(*\nHere is the alternative that uses the indefinite_description axiom.\n\nAxiom indefinite_description :\n  forall (A : Type) (P : A -> Prop),\n    ex P -> sig P.\n\nLemma equality_of_int_imp_t :\n  forall n m,\n    equality_of_int n m\n    -> equality_of_int_t n m.\nProof.\n  introv e.\n  unfold equality_of_int in e.\n  unfold equality_of_int_t.\n  apply indefinite_description; auto.\nQed.\n*)\n\nDefinition equality_of_int_tt {o} lib (n m : @CTerm o) :=\n  {k : Z & computes_to_valc lib n (mkc_integer k)\n         # computes_to_valc lib m (mkc_integer k)}.\n\nLemma equality_of_int_imp_tt {o} :\n  forall lib (n m : @CTerm o),\n    equality_of_int lib n m\n    -> equality_of_int_tt lib n m.\nProof.\n  introv e.\n  apply equality_of_int_imp1 in e.\n  apply constructive_indefinite_ground_description_nat in e; auto.\n  exrepnd; allsimpl.\n  unfold equality_of_int_tt.\n  unfold reducek_pair in e0; repnd.\n  exists x0; dands; spcast;\n  unfold computes_to_valc, computes_to_value; simpl;\n  dands; try (apply isvalue_mk_integer);\n  exists x; auto.\nQed.\n\nLemma tequality_mkc_natk {o} :\n  forall lib (t1 t2 : @CTerm o),\n    tequality lib (mkc_natk t1) (mkc_natk t2)\n    <=> {k1 : Z , {k2 : Z\n         , t1 ===>(lib) (mkc_integer k1)\n         # t2 ===>(lib) (mkc_integer k2)\n         # (forall (k : Z), (0 <= k)%Z -> ((k < k1)%Z # (k < k2)%Z){+}(k1 <= k)%Z # (k2 <= k)%Z) }}.\nProof.\n  introv.\n  allrw @mkc_natk_eq.\n  allrw @tequality_set.\n\n  split; intro k; repnd.\n\n  - clear k0.\n\n    assert (forall a a' : CTerm,\n              equality lib a a' mkc_int\n              -> tequality\n                   lib\n                   (mkc_prod (mkc_le mkc_zero a) (mkc_less_than a t1))\n                   (mkc_prod (mkc_le mkc_zero a') (mkc_less_than a' t2))) as h1.\n    { introv ei.\n      applydup k in ei.\n      eapply tequality_respects_alphaeqc_left in ei0;[|apply mkcv_prod_substc].\n      eapply tequality_respects_alphaeqc_right in ei0;[|apply mkcv_prod_substc].\n      allrw @mkcv_le_substc2.\n      allrw @mkcv_zero_substc.\n      allrw @mkcv_less_than_substc.\n      allrw @mkc_var_substc.\n      allrw @csubst_mk_cv.\n      auto. }\n    clear k.\n\n    assert (forall (k : Z),\n              (0 <= k)%Z\n              -> {k1 : Z , {k2 : Z\n                  , t1 ===>(lib) (mkc_integer k1)\n                  # t2 ===>(lib) (mkc_integer k2)\n                  # ((k < k1)%Z # (k < k2)%Z){+}(k1 <= k)%Z # (k2 <= k)%Z }}) as h2.\n    { introv le0k.\n      pose proof (h1 (mkc_integer k) (mkc_integer k)) as h.\n      autodimp h hyp.\n      { apply equality_in_int; unfold equality_of_int; exists k; dands; spcast; auto;\n        apply computes_to_valc_refl; eauto with slow. }\n      allrw @tequality_mkc_prod; repnd.\n      allrw @inhabited_le.\n      allrw @tequality_mkc_less_than.\n      clear h0 (* trivial *).\n      autodimp h hyp.\n      { exists 0%Z k; dands; auto; spcast; tcsp; allrw @mkc_zero_eq; allrw @mkc_nat_eq;\n        allsimpl; apply computes_to_valc_refl; eauto with slow. }\n      exrepnd; spcast.\n      apply computes_to_valc_isvalue_eq in h0; eauto with slow; ginv.\n      apply computes_to_valc_isvalue_eq in h4; eauto with slow; ginv.\n      exists kb kd; dands; spcast; auto. }\n    clear h1.\n\n    pose proof (h2 0%Z) as h; autodimp h hyp; tcsp; exrepnd; spcast.\n    exists k1 k2; dands; spcast; tcsp.\n    introv i.\n    apply h2 in i; exrepnd; spcast.\n    repeat computes_to_eqval; auto.\n\n  - dands.\n    { apply tequality_int. }\n    introv ei.\n    exrepnd; spcast.\n\n    apply equality_in_int in ei.\n    apply equality_of_int_imp_tt in ei.\n    unfold equality_of_int_tt in ei; exrepnd.\n\n    eapply tequality_respects_alphaeqc_left;[apply alphaeqc_sym; apply mkcv_prod_substc|].\n    eapply tequality_respects_alphaeqc_right;[apply alphaeqc_sym; apply mkcv_prod_substc|].\n    allrw @mkcv_le_substc2.\n    allrw @mkcv_less_than_substc.\n    allrw @mkc_var_substc.\n    allrw @mkcv_zero_substc.\n    allrw @csubst_mk_cv.\n\n    apply tequality_mkc_prod; dands.\n    { apply tequality_mkc_le.\n      exists 0%Z k 0%Z k.\n      dands; tcsp; spcast; auto;\n      try (rw @mkc_zero_eq; rw @mkc_nat_eq; simpl;\n           apply computes_to_valc_refl; eauto with slow).\n      destruct (Z_lt_le_dec k 0); tcsp. }\n\n    introv inh.\n    allrw @inhabited_le; exrepnd; spcast.\n    apply computes_to_valc_isvalue_eq in inh0; eauto with slow.\n    rw @mkc_zero_eq in inh0; rw @mkc_nat_eq in inh0; ginv.\n    computes_to_eqval.\n    apply tequality_mkc_less_than.\n    exists k k1 k k2; dands; spcast; tcsp.\nQed.\n\nLemma type_mkc_natk {o} :\n  forall lib (t : @CTerm o),\n    type lib (mkc_natk t)\n    <=> {k : Z , t ===>(lib) (mkc_integer k)}.\nProof.\n  introv.\n  rw @tequality_mkc_natk; split; introv h; exrepnd; spcast; repeat computes_to_eqval.\n  - exists k1; spcast; auto.\n  - exists k k; dands; spcast; auto.\n    introv i.\n    destruct (Z_lt_le_dec k0 k); tcsp.\nQed.\n\nLemma type_mkc_le {o} :\n  forall lib (a b : @CTerm o),\n  type lib (mkc_le a b) <=>\n       (exists ka kb\n        , (a) ===>( lib)(mkc_integer ka)\n        # (b) ===>( lib)(mkc_integer kb)).\nProof.\n  introv.\n  rw @tequality_mkc_le; split; intro h; exrepnd; spcast; repeat computes_to_eqval.\n  - exists ka kb; dands; spcast; auto.\n  - exists ka kb ka kb; dands; spcast; auto.\n    destruct (Z_lt_le_dec kb ka); tcsp.\nQed.\n\nLemma type_mkc_less_than {o} :\n  forall lib (a b : @CTerm o),\n    type lib (mkc_less_than a b) <=>\n         (exists ka kb\n          , (a) ===>( lib)(mkc_integer ka)\n          # (b) ===>( lib)(mkc_integer kb)).\nProof.\n  introv.\n  rw @tequality_mkc_less_than; split; intro h; exrepnd; spcast; repeat computes_to_eqval.\n  - exists ka kb; dands; spcast; auto.\n  - exists ka kb ka kb; dands; spcast; auto.\n    destruct (Z_lt_le_dec ka kb); tcsp.\nQed.\n\nLemma equality_in_natk {o} :\n  forall lib (a b t : @CTerm o),\n    equality lib a b (mkc_natk t)\n    <=> {m : nat , {k : Z\n         , a ===>(lib) (mkc_nat m)\n         # b ===>(lib) (mkc_nat m)\n         # t ===>(lib) (mkc_integer k)\n         # (Z.of_nat m < k)%Z }} .\nProof.\n  introv.\n  rw @mkc_natk_eq.\n  rw @equality_in_set.\n\n  split; intro h; exrepnd; dands.\n\n  - clear h0.\n    allrw @equality_in_int.\n    unfold equality_of_int in h1; exrepnd; spcast.\n    eapply inhabited_type_respects_alphaeqc in h;[|apply mkcv_prod_substc].\n    allrw @mkcv_le_substc2.\n    allrw @mkcv_less_than_substc.\n    allrw @mkc_var_substc.\n    allrw @mkcv_zero_substc.\n    allrw @csubst_mk_cv.\n    allrw @inhabited_prod; repnd.\n    allrw @inhabited_le; exrepnd; spcast.\n    apply computes_to_valc_isvalue_eq in h5; eauto with slow.\n    rw @mkc_zero_eq in h5; rw @mkc_nat_eq in h5; ginv.\n    computes_to_eqval.\n    allrw @inhabited_less_than; exrepnd; spcast.\n    computes_to_eqval.\n    exists (Z.to_nat k) kb; dands; spcast; tcsp;\n    try (complete (rw @mkc_nat_eq; rw Znat.Z2Nat.id; auto)).\n    rw Znat.Z2Nat.id; auto.\n\n  - introv ei.\n    allrw @equality_in_int.\n    unfold equality_of_int in ei; exrepnd; spcast.\n    eapply tequality_respects_alphaeqc_left;[apply alphaeqc_sym; apply mkcv_prod_substc|].\n    eapply tequality_respects_alphaeqc_right;[apply alphaeqc_sym; apply mkcv_prod_substc|].\n    allrw @mkcv_le_substc2.\n    allrw @mkcv_less_than_substc.\n    allrw @mkc_var_substc.\n    allrw @mkcv_zero_substc.\n    allrw @csubst_mk_cv.\n    allrw @tequality_mkc_prod; dands.\n\n    + allrw @tequality_mkc_le.\n      exists 0%Z k0 0%Z k0.\n      dands; tcsp; spcast; auto;\n      try (rw @mkc_zero_eq; rw @mkc_nat_eq; simpl;\n           apply computes_to_valc_refl; eauto with slow).\n      destruct (Z_lt_le_dec k0 0); tcsp.\n\n    + introv inh.\n      allrw @inhabited_le; exrepnd; spcast.\n      computes_to_eqval.\n      apply computes_to_valc_isvalue_eq in inh0; eauto with slow.\n      rw @mkc_zero_eq in inh0; rw @mkc_nat_eq in inh0; ginv.\n      apply tequality_mkc_less_than.\n      exists k0 k k0 k; dands; spcast; auto.\n      destruct (Z_lt_le_dec k0 k); tcsp.\n\n  - spcast.\n    apply equality_in_int; unfold equality_of_int.\n    exists (Z.of_nat m); dands; spcast; auto.\n\n  - spcast.\n    eapply inhabited_type_respects_alphaeqc;[apply alphaeqc_sym; apply mkcv_prod_substc|].\n    allrw @mkcv_le_substc2.\n    allrw @mkcv_less_than_substc.\n    allrw @mkc_var_substc.\n    allrw @mkcv_zero_substc.\n    allrw @csubst_mk_cv.\n    apply inhabited_prod.\n    allrw @type_mkc_le.\n    allrw @type_mkc_less_than.\n    allrw @inhabited_le.\n    allrw @inhabited_less_than.\n    dands.\n\n    + exists 0%Z (Z.of_nat m); dands; spcast.\n      * rw @mkc_zero_eq; rw @mkc_nat_eq; simpl; apply computes_to_valc_refl; eauto with slow.\n      * allrw @mkc_nat_eq; auto.\n\n    + exists (Z.of_nat m) k; dands; spcast; auto.\n\n    + exists 0%Z (Z.of_nat m); dands; spcast; tcsp; try omega.\n      rw @mkc_zero_eq; rw @mkc_nat_eq; simpl; apply computes_to_valc_refl; eauto with slow.\n\n    + exists (Z.of_nat m) k; dands; spcast; auto.\nQed.\n\nLemma computes_to_valc_implies_reduces_toc {o} :\n  forall lib (t1 t2 : @CTerm o),\n    computes_to_valc lib t1 t2\n    -> reduces_toc lib t1 t2.\nProof.\n  introv comp.\n  allrw @computes_to_valc_iff_reduces_toc; sp.\nQed.\nHint Resolve computes_to_valc_implies_reduces_toc : slow.\n\nLemma cequivc_mkc_isl {o} :\n  forall lib (t u : @CTerm o),\n    cequivc lib t u\n    -> cequivc lib (mkc_isl t) (mkc_isl u).\nProof.\n  introv c.\n  destruct_cterms.\n  allunfold @cequivc; allsimpl.\n  unfold mk_isl, mk_ite.\n  apply cequiv_congruence; fold_terms.\n  - unfold cequiv_bts, lblift; simpl; dands; auto.\n    introv k.\n    repeat (destruct n; tcsp; try omega); clear k; unfold selectbt; simpl;\n    try (fold (bcequiv lib)); eauto with slow.\n    + apply bcequiv_nobnd; eauto 3 with slow.\n    + apply bcequiv_refl.\n      apply wf_bterm_iff; eauto 3 with slow.\n    + apply bcequiv_refl.\n      apply wf_bterm_iff; eauto 3 with slow.\n  - apply isprogram_decide_iff2; dands; eauto 3 with slow.\n  - apply isprogram_decide_iff2; dands; eauto 3 with slow.\nQed.\n\nLemma cequivc_mkc_assert {o} :\n  forall lib (t u : @CTerm o),\n    cequivc lib t u\n    -> cequivc lib (mkc_assert t) (mkc_assert u).\nProof.\n  introv c.\n  destruct_cterms.\n  allunfold @cequivc; allsimpl.\n  unfold mk_assert, mk_ite.\n  apply cequiv_congruence; fold_terms.\n  - unfold cequiv_bts, lblift; simpl; dands; auto.\n    introv k.\n    repeat (destruct n; tcsp; try omega); clear k; unfold selectbt; simpl;\n    try (fold (bcequiv lib)); eauto with slow.\n    + apply bcequiv_nobnd; eauto 3 with slow.\n    + apply bcequiv_refl.\n      apply wf_bterm_iff; eauto 3 with slow.\n    + apply bcequiv_refl.\n      apply wf_bterm_iff; eauto 3 with slow.\n  - apply isprogram_decide_iff2; dands; eauto 3 with slow.\n  - apply isprogram_decide_iff2; dands; eauto 3 with slow.\nQed.\n\nLemma computes_to_valc_inl_implies_cequivc_isl_tt {o} :\n  forall lib (t u : @CTerm o),\n    computes_to_valc lib t (mkc_inl u)\n    -> cequivc lib (mkc_isl t) tt.\nProof.\n  introv comp.\n  eapply cequivc_trans;\n    [apply cequivc_mkc_isl;\n      apply computes_to_valc_implies_cequivc;\n      exact comp|].\n  apply computes_to_valc_implies_cequivc; clear comp t.\n  destruct_cterms.\n  unfold computes_to_valc; simpl.\n  unfold computes_to_value; dands; eauto 3 with slow.\nQed.\n\nLemma computes_to_valc_inr_implies_cequivc_isl_ff {o} :\n  forall lib (t u : @CTerm o),\n    computes_to_valc lib t (mkc_inr u)\n    -> cequivc lib (mkc_isl t) ff.\nProof.\n  introv comp.\n  eapply cequivc_trans;\n    [apply cequivc_mkc_isl;\n      apply computes_to_valc_implies_cequivc;\n      exact comp|].\n  apply computes_to_valc_implies_cequivc; clear comp t.\n  destruct_cterms.\n  unfold computes_to_valc; simpl.\n  unfold computes_to_value; dands; eauto 3 with slow.\nQed.\n\nLemma implies_isl_in_bool {o} :\n  forall lib (A B a b : @CTerm o),\n    equality lib a b (mkc_union A B)\n    -> equality lib (mkc_isl a) (mkc_isl b) mkc_bool.\nProof.\n  introv e.\n  apply equality_mkc_union in e; exrepnd.\n  apply equality_in_bool.\n  repndors; exrepnd; spcast;[left|right]; dands; spcast.\n  - eapply computes_to_valc_inl_implies_cequivc_isl_tt; eauto.\n  - eapply computes_to_valc_inl_implies_cequivc_isl_tt; eauto.\n  - eapply computes_to_valc_inr_implies_cequivc_isl_ff; eauto.\n  - eapply computes_to_valc_inr_implies_cequivc_isl_ff; eauto.\nQed.\n\nLemma tt_not_approx_ff {o} :\n  forall (lib : @library o), !approx lib mk_btrue mk_bfalse.\nProof.\n  introv apr.\n  inversion apr as [cl]; clear apr.\n  unfold close_comput in cl; repnd.\n  unfold close_compute_val in cl2.\n  pose proof (cl2 (NInj NInl) [nobnd mk_axiom]) as h; fold_terms.\n  autodimp h hyp; eauto 3 with slow.\n  exrepnd.\n  apply computes_to_value_isvalue_eq in h1; ginv; eauto 3 with slow.\nQed.\n\nLemma tt_not_cequiv_ff {o} :\n  forall (lib : @library o), !cequiv lib mk_btrue mk_bfalse.\nProof.\n  introv ceq.\n  apply cequiv_le_approx in ceq.\n  apply tt_not_approx_ff in ceq; sp.\nQed.\n\nLemma tt_not_cequivc_ff {o} :\n  forall (lib : @library o), !cequivc lib tt ff.\nProof.\n  introv.\n  unfold cequivc; simpl.\n  apply tt_not_cequiv_ff.\nQed.\n\nLemma equality_tt_in_bool_implies_cequiv {o} :\n  forall lib (t : @CTerm o),\n    equality lib t tt mkc_bool\n    -> ccequivc lib t tt.\nProof.\n  introv e.\n  apply equality_in_bool in e; repndors; repnd; spcast; eauto with slow.\n  apply tt_not_cequivc_ff in e; sp.\nQed.\n\nLemma isprogram_mk_assert {o} :\n  forall (t : @NTerm o),\n    isprogram (mk_assert t) <=> isprogram t.\nProof.\n  introv.\n  unfold mk_assert.\n  rw @isprogram_decide_iff2; split; intro k; repnd; tcsp; dands; auto;\n  apply isprog_vars_isprogrambt;\n  apply isprog_vars_if_isprog; eauto 3 with slow.\nQed.\n\nLemma mkc_assert_tt {o} :\n  forall (lib : @library o), cequivc lib (mkc_assert tt) mkc_unit.\nProof.\n  introv.\n  unfold cequivc; simpl.\n  apply reduces_to_implies_cequiv; eauto 3 with slow.\n  apply isprogram_mk_assert.\n  apply isprogram_inl; eauto with slow.\nQed.\n\nLemma inhabited_type_mkc_unit {o} :\n  forall (lib : @library o), inhabited_type lib mkc_unit.\nProof.\n  introv.\n  unfold inhabited_type.\n  exists (@mkc_axiom o).\n  apply equality_in_unit; dands; spcast;\n  apply computes_to_valc_refl; eauto with slow.\nQed.\nHint Resolve inhabited_type_mkc_unit : slow.\n\nLemma equality_mkc_inl_implies {o} :\n  forall lib (t1 t2 A B : @CTerm o),\n    equality lib (mkc_inl t1) (mkc_inl t2) (mkc_union A B)\n    -> equality lib t1 t2 A.\nProof.\n  introv e.\n  apply equality_mkc_union in e; repnd.\n  repndors; exrepnd; spcast;\n  apply computes_to_valc_isvalue_eq in e2; eauto 3 with slow;\n  apply computes_to_valc_isvalue_eq in e4; eauto 3 with slow;\n  eqconstr e2; eqconstr e4; auto.\nQed.\n\nLemma type_tnat {o} :\n  forall (lib : @library o), type lib mkc_tnat.\nProof.\n  introv.\n  rw @mkc_tnat_eq.\n  apply tequality_set; dands; auto.\n  { apply tequality_int. }\n\n  introv e.\n  allrw @substc_mkcv_le.\n  allrw @substc_mkcv_zero.\n  allrw @mkc_var_substc.\n  apply equality_in_int in e.\n  unfold equality_of_int in e; exrepnd; spcast.\n\n  apply tequality_mkc_le.\n  exists (0%Z) k (0%Z) k; dands; spcast; tcsp.\n\n  - unfold computes_to_valc; simpl.\n    unfold computes_to_value; dands; eauto with slow.\n\n  - unfold computes_to_valc; simpl.\n    unfold computes_to_value; dands; eauto with slow.\n\n  - destruct (Z_le_gt_dec 0 k); tcsp.\n    right; dands; omega.\nQed.\nHint Resolve type_tnat : slow.\n\nDefinition equality_of_nat {p} lib (n m : @CTerm p) :=\n  {k : nat , n ===>(lib) (mkc_nat k)\n           # m ===>(lib) (mkc_nat k)}.\n\nLemma equality_in_tnat {o} :\n  forall lib (a b : @CTerm o),\n    equality lib a b mkc_tnat\n    <=> equality_of_nat lib a b.\nProof.\n  introv.\n  rw @mkc_tnat_eq.\n  rw @equality_in_set.\n  rw @equality_in_int.\n  unfold equality_of_int, equality_of_nat.\n  rw @substc_mkcv_le.\n  rw @substc_mkcv_zero.\n  rw @mkc_var_substc.\n  rw @inhabited_le.\n  split; introv k; exrepnd; spcast; dands;\n  repeat computes_to_eqval;\n  computes_to_value_isvalue; ginv.\n  - inversion k2; subst.\n    apply Wf_Z.Z_of_nat_complete in k3; exrepnd; subst.\n    exists n; dands; spcast; auto.\n  - introv e.\n    allrw @substc_mkcv_le.\n    allrw @substc_mkcv_zero.\n    allrw @mkc_var_substc.\n    apply equality_in_int in e.\n    unfold equality_of_int in e; exrepnd; spcast.\n    apply tequality_mkc_le.\n    exists (0%Z) k (0%Z) k; dands; spcast; auto;\n    try (complete (unfold computes_to_valc; simpl;\n                   unfold computes_to_value; dands;\n                   eauto with slow)).\n    destruct (Z_le_gt_dec 0 k); sp.\n    right; sp; omega.\n  - exists (Z.of_nat k0); dands; spcast; auto.\n  - exists (0%Z) (Z.of_nat k0); dands; spcast; auto;\n    try omega;\n    try (complete (unfold computes_to_valc; simpl;\n                   unfold computes_to_value; dands;\n                   eauto with slow)).\nQed.\n\nLemma equality_in_int_and_inhabited_le_implies_equality_in_nat {o} :\n  forall lib (a b : @CTerm o),\n    equality lib a b mkc_int\n    -> inhabited_type lib (mkc_le mkc_zero a)\n    -> equality lib a b mkc_tnat.\nProof.\n  introv e inh.\n  apply equality_in_tnat.\n  apply equality_in_int in e.\n  apply inhabited_le in inh.\n  unfold equality_of_nat.\n  unfold equality_of_int in e.\n  exrepnd; spcast.\n  repeat computes_to_eqval.\n  computes_to_value_isvalue; ginv.\n  inversion inh0; subst.\n  apply Wf_Z.Z_of_nat_complete in inh1; exrepnd; subst.\n  exists n; dands; spcast; auto.\nQed.\n\nLemma equality_of_nat_implies_equality_of_int {o} :\n  forall lib (t1 t2 : @CTerm o),\n    equality_of_nat lib t1 t2\n    -> equality_of_int lib t1 t2.\nProof.\n  introv e.\n  unfold equality_of_nat in e; exrepnd; spcast.\n  unfold equality_of_int.\n  allrw @mkc_nat_eq.\n  exists (Z.of_nat k); dands; spcast; auto.\nQed.\n\nLemma equality_in_int_implies_cequiv {o} :\n  forall lib (a b : @CTerm o),\n    equality lib a b mkc_int\n    -> cequivc lib a b.\nProof.\n  introv e.\n  apply equality_in_int in e.\n  apply equality_of_int_imp_tt in e.\n  unfold equality_of_int_tt in e; exrepnd.\n  destruct_cterms; allunfold @computes_to_valc; allunfold @cequivc; allsimpl.\n  allunfold @computes_to_value; repnd.\n  apply (cequiv_trans _ _ (mk_integer k)).\n  - apply reduces_to_implies_cequiv; auto.\n    apply isprogram_eq; auto.\n  - apply cequiv_sym.\n    apply reduces_to_implies_cequiv; auto.\n    apply isprogram_eq; 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_nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.28938232119177065}}
{"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.\nFrom fourcolor Require Import job323to383 job384to398 job399to438.\nFrom fourcolor Require Import job439to465 job466to485.\n\n(******************************************************************************)\n(* Reducibility of configurations number 323 to 485, whose indices in         *)\n(* the_configs range over segment [322, 485).                                 *)\n(******************************************************************************)\n\nLemma red322to485 : reducible_in_range 322 485 the_configs.\nProof.\nCatReducible red322to383 red383to398 red398to438 red438to465 red465to485.\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/task323to485.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.28937793727907074}}
{"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_atom_tacs.\nRequire Export rules_struct.\n\n\n\nLemma utok_ren_cseq_thin_hyps {o} :\n  forall H J C t wg cg c wfs ct ce D deq fresh\n         (f : @utok_ren_cseq\n                (set_dset_string o)\n                (mk_dset D deq fresh)\n                (mk_wcseq ((H ++ J) ||- (mk_concl C t))\n                          (ext_wf_cseq (H ++ J) ||- (mk_concl C t) wg cg c))),\n    @utok_ren_cseq\n      (set_dset_string o)\n      (mk_dset D deq fresh)\n      (mk_wcseq (H) ||- (mk_concl C t) (wfs, (ct, ce))).\nProof.\n  introv f.\n  intro p; exrepnd; simpl in p0.\n  assert (dset_member\n            x\n            (get_utokens_cseq\n               (mk_wcseq (H ++ J) ||- (mk_concl C t)\n                         (ext_wf_cseq (H ++ J) ||- (mk_concl C t) wg cg c)))) as m.\n  (* -- begin proof of m *)\n  allrw @dset_member_iff.\n  allunfold @get_utokens_cseq; allsimpl.\n  allunfold @get_utokens_ctseq; allsimpl.\n  allunfold @get_utokens_seq; allsimpl.\n  allunfold @get_utokens_bseq; allsimpl.\n  allrw @get_utokens_bhyps_app; allrw in_app_iff; sp.\n  (* -- end proof of m *)\n  pose proof (f (existT _ x m)); auto.\nDefined.\n\nLemma rule_thin_hyps_atom_true {o} :\n  forall lib (H J : @barehypotheses (s2s o))\n         (C t : NTerm),\n    rule_atom_true lib (rule_thin_hyps H J C t).\nProof.\n  introv.\n  unfold rule_atom_true, closed_type_baresequent, closed_extract_baresequent.\n  introv cargs hyps; allsimpl.\n\n  clear cargs.\n  dLin_hyp.\n  destruct Hyp as [wf1 hyp1].\n  destruct wf1 as [wfs wf1].\n  destruct wf1 as [ct ce].\n  allsimpl.\n\n  assert (closed_extract (H ++ J) (mk_concl C t))\n    as c by (wfseq; apply covered_app_weak_l; auto).\n  exists c.\n\n  unfold sequent_atom_true.\n  introv kelts; introv.\n\n  pose proof (replace_utokens_cseq_mk_wcseq\n                ((H ++ J) ||- (mk_concl C t))\n                (ext_wf_cseq (H ++ J) ||- (mk_concl C t) wg cg c)\n                f) as e; exrepnd.\n  rw e0; clear e0.\n\n  revert w'.\n  unfold replace_utokens_bseq; introv; allsimpl.\n  foldseq.\n\n  revert w'.\n  rw @replace_utokens_bhyps_app; introv.\n\n  destruct w' as [wsr w']; destruct w' as [ctr cer]; allsimpl.\n\n  pose proof (rule_thin_hyps_true\n                (replace_utokens_library lib fl)\n                (replace_utokens_bhyps\n                   H\n                   (utok_ren_bhyps_app_2bhyps1\n                      H J\n                      (utok_ren_bseq_2h (H ++ J) ||- (mk_concl C t) f)))\n                (replace_utokens_bhyps\n                   J\n                   (utok_ren_bhyps_app_2bhyps2\n                      H J\n                      (utok_ren_bseq_2h (H ++ J) ||- (mk_concl C t) f)))\n                (replace_utokens_t\n                   C\n                   (utok_ren_concle_2t\n                      C t\n                      (utok_ren_bseq_2c (H ++ J) ||- (mk_concl C t) f)))\n                (replace_utokens_t\n                   t\n                   (utok_ren_concle_2e\n                      C t\n                      (utok_ren_bseq_2c (H ++ J) ||- (mk_concl C t) f)))\n                wsr\n                ctr\n                (args_constraints_nil _)) as h; simpl in h.\n\n  repeat (autodimp h hyp).\n\n  - clear cer ctr wsr.\n    introv h.\n    dorn h; tcsp; subst.\n    pose proof (hyp1 k D deq fresh kelts) as h; clear hyp1.\n\n    pose proof (h (utok_ren_cseq_thin_hyps\n                     H J C t wg cg c wfs ct ce D deq fresh f)\n                  fl) as hh; clear h.\n\n    pose proof (replace_utokens_cseq_mk_wcseq\n                  ((H) ||- (mk_concl C t))\n                  (wfs,(ct,ce))\n                  (utok_ren_cseq_thin_hyps\n                     H J C t wg cg c wfs ct ce D deq fresh f)) as e; exrepnd.\n    rw e0 in hh; clear e0.\n    allunfold @replace_utokens_bseq; allsimpl.\n    foldseq.\n    rw <- @sequent_true_eq_VR in hh.\n\n    assert (eq_utok_ren_bhyps\n              H\n              (utok_ren_bseq_2h\n                 ((H) ||- (mk_concl C t))\n                 (utok_ren_cseq_thin_hyps H J C t wg cg c wfs ct ce D deq fresh f))\n              (utok_ren_bhyps_app_2bhyps1\n                 H J\n                 (utok_ren_bseq_2h (H ++ J) ||- (mk_concl C t) f))) as e1.\n    introv; exrepnd; simpl.\n    gen_s2s; PI2.\n\n    assert (eq_utok_ren\n              C\n              (utok_ren_concle_2t\n                 C t\n                 (utok_ren_bseq_2c (H) ||- (mk_concl C t)\n                                   (utok_ren_cseq_thin_hyps H J C t wg cg c wfs ct\n                                                            ce D deq fresh f)))\n              (utok_ren_concle_2t\n                 C t\n                 (utok_ren_bseq_2c (H ++ J) ||- (mk_concl C t) f))\n           ) as e2.\n    introv; exrepnd; simpl.\n    gen_s2s; PI2.\n\n    assert (eq_utok_ren\n              t\n              (utok_ren_concle_2e\n                 C t\n                 (utok_ren_bseq_2c (H) ||- (mk_concl C t)\n                                   (utok_ren_cseq_thin_hyps H J C t wg cg c wfs ct\n                                                            ce D deq fresh f)))\n              (utok_ren_concle_2e\n                 C t\n                 (utok_ren_bseq_2c (H ++ J) ||- (mk_concl C t) f))\n           ) as e3.\n    introv; exrepnd; simpl.\n    gen_s2s; PI2.\n\n    rw <- (replace_utokens_bhyps_eq H _ _ e1).\n    rw <- (replace_utokens_t_eq C _ _ e2).\n    rw <- (replace_utokens_t_eq t _ _ e3).\n    exists w'; auto.\n\n  - exrepnd.\n    allunfold @closed_extract_baresequent; allsimpl; PI2.\n    unfold ext_wf_cseq in h0.\n    rw @sequent_true_eq_VR in h0; auto.\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/rules_atom_struct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.28937793727907074}}
{"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 Import CFGV.\n\n(** Now, specialize the previous CFGV to\n  CFGVs where the symbols are denoted by strings.\n  The goal is to make the specification\n  of a [StringCFGV] to be as close as that to \n  paper-pen presentations, i.e. the user has to\n  specify the minimal amount of information ans\n  proofs are filled automatically.\n  We have a decision procedure that takes a [StringCFGV]\n  and either produces [CFGV] or produces a proof that\n  something is wrong with the input*)\n\nRecord StringVarSpec := mksvs {\n  vname : String.string;\n  subTNonTerminal : String.string;\n  vSemType :{T:Type $ VarType}\n}.\n\nRecord Terminal := mkst {\n  tname : String.string;\n  tSemType :  Type\n}.\n\nRecord TermProd := mkp {\n  pname : String.string;\n  tpLhs : String.string;\n  prhs : list String.string\n}.\n\nRecord BindingInfo := mkbind {\n  binder : nat;\n  bindee : nat\n}.\n\nRecord StringCFGV := mk_ott {\n  (** all the lists below should have distinct elements *)\n  VarSymes : list StringVarSpec;\n  Terminals : list Terminal;\n  TNonTerminals : list String.string;\n  Patterns : list String.string;\n  (** lhs and elements of rhs of the 3 kinds of \n    production rules below must be members\n    of one of the lists above, \n    with some restrictions noted below *)\n  PatProds : list TermProd; \n  Embeddings : list TermProd;\n  GProds : list (TermProd * (list BindingInfo))\n}.\n\nHint Resolve String.string_dec : Deq.\nDefinition stSubset (l r : list String.string) : [univ] \n  := (diff  String.string_dec r l = []).\n\nDefinition stMinus (l r : list String.string) \n    : list String.string\n  := (diff  String.string_dec r l).\n\nExample exxxxxxx: stSubset [\"hello\"] [\"hello\", \"how\"].\nProof.  refl.\nQed.\n\nDefinition ProdRhs (sg :StringCFGV) :=\n  (TNonTerminals sg) ++ (Patterns sg) ++\n  (map vname (VarSymes sg)) \n  ++ (map tname (Terminals sg)).\n  \nDefinition PatProdRhs (sg :StringCFGV) :=\n  (Patterns sg) ++\n  (map vname (VarSymes sg)) \n  ++ (map tname (Terminals sg)).\n\n \n(*  no_repeats (VarSymes sg)\n  # no_repeats (Terminals sg)\n  # no_repeats (TNonTerminals sg)\n  # no_repeats (Patterns sg) *)\n\n(** We can now use coq's definitional equality to \n    check the properties required to get a [CFGV]\n    from [StringCFGV]. The idea is that\n    for concrete [StringCFGV]s \n    the proof of the predicate below should\n    just be a tuple of [eq_refl].*)\nDefinition GoodStringCFGV (sg :StringCFGV) :=\n  []= (stMinus (map tpLhs (PatProds sg)) (Patterns sg))\n      ++ (stMinus (flat_map prhs (PatProds sg)) (PatProdRhs sg))\n      ++ (stMinus (map tpLhs (Embeddings sg)) (Patterns sg))\n      ++ (stMinus (flat_map prhs (Embeddings sg)) (TNonTerminals sg)).\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/StringGrammar.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.28937793727907074}}
{"text": "From Coq Require Import Lists.List.\nFrom Coq Require Import Numbers.NatInt.NZLog.\nFrom Coq Require Import Strings.String.\n\nFrom Ornamental Require Import Ornaments.\n\nSet DEVOID search prove equivalence. (* <-- Correctness proofs for search *)\nSet DEVOID lift type. (* <-- Prettier types than the ones Coq infers *)\n\nModule SCS.\n\n  Definition sort (n : nat) := Type.\n\nEnd SCS.\n\nPreprocess Module SCS as SCS'.\n\n  (* Axiom error : forall (a : Type), String.string -> a. *)\n\n  Definition String := String.string.\n\n  Definition Unit        := tt.\n  Definition UnitType    := unit.\n  Definition UnitType__rec := unit_rect.\n\n  Definition Bool   := bool.\n  Definition Eq     := identity.\n  Definition Eq__rec  := identity_rect.\n  Definition Refl   := identity_refl.\n  Definition True      := true.\n  Definition ite (a : Type) (b : Bool) (t e : a) : a := if b then t else e.\n  Definition and    := andb.\n  Definition False      := false.\n  Definition not      := negb.\n  Definition or     := orb.\n  Definition xor    := xorb.\n  Definition boolEq := Coq.Bool.Bool.eqb.\n  Theorem boolEq__eq (b1 b2:Bool) : Eq Bool (boolEq b1 b2) (ite Bool b1 b2 (not b2)).\n  Proof.\n    destruct b1, b2; reflexivity.\n  Qed.\n\n  Definition coerce (a b : sort 0) (eq : Eq (sort 0) a b) (x : a) : b :=\n    match eq in identity _ a' return a' with\n    | identity_refl _ => x\n    end\n  .\n\n  (** Typeclass for `eq` **)\n(* NOTE: SAW core prelude's eq is not being used much by the translation at the *)\n (* moment, so we skip it.  The following type class declaration could be used if *)\n (* one wanted to translate `eq`.  However, it would require more work in the *)\n (* translation, because calls to `eq T a b` in SAW must be translated to either `eq *)\n (* a b` or `@eq T _ a b`, where the underscore stands for the dictionary.  As a *)\n (* result, this would not be an identifier-to-identifier translation, but rather a *)\n (* term-to-term translation, and would require knowing the number of arguments *)\n (* expected before the dicitonary. *)\n(* *)\n (* Class eqClass `(a : Type) := *)\n (*   { *)\n (*     eq : a -> a -> bool; *)\n (*     eq_refl : forall (x : a), Eq Bool (eq x x) True; *)\n (*   }. *)\n\n (* Global Instance eqClassBool : eqClass Bool := *)\n (*   { *)\n (*     eq := boolEq; *)\n (*   }. *)\n (* + destruct x; reflexivity. *)\n (* Defined. *)\n\n (* Theorem eq_Bool : Eq (Bool -> Bool -> Bool) eq boolEq. *)\n (* Proof. *)\n (*   reflexivity. *)\n (* Qed. *)\n\n (* Global Instance eqClass_sawVec (n : nat) (a : Type) `(A : eqClass a) : eqClass (sawVec n a) := *)\n (*   { *)\n (*     eq := Vector.eqb _ eq; *)\n (*   }. *)\n (* + induction 0 as [|? ? ? IH]. *)\n (*   - reflexivity. *)\n (*   - simpl. *)\n (*     rewrite eq_refl. *)\n (*     rewrite IH. *)\n (*     reflexivity. *)\n (* Defined. *)\n (* *)\n\n(* SAW's prelude defines iteDep as a Bool eliminator whose arguments are *)\n (* reordered to look more like if-then-else. *)\n  Definition iteDep (P : Bool -> Type) (b : Bool) : P True -> P False -> P b :=\n    fun PTrue PFalse => bool_rect P PTrue PFalse b.\n\n  Definition ite_eq_iteDep : forall (a : Type) (b : Bool) (x y : a),\n      @identity a (ite a b x y) (iteDep (fun _ => a) b x y).\n  Proof.\n    reflexivity.\n  Defined.\n\n  Definition iteDep_True : forall (p : Bool -> Type), forall (f1 : p True), forall (f2 : p False), (@identity (p True) (iteDep p True f1 f2)) f1.\n  Proof.\n    reflexivity.\n  Defined.\n\n  Definition iteDep_False : forall (p : Bool -> Type), forall (f1 : p True), forall (f2 : p False), (@identity (p False) (iteDep p False f1 f2)) f2.\n  Proof.\n    reflexivity.\n  Defined.\n\n  Definition not__eq (b : Bool) : @identity Bool (not b) (ite Bool b False True).\n  Proof.\n    reflexivity.\n  Defined.\n\n  Definition and__eq (b1 b2 : Bool) : @identity Bool (and b1 b2) (ite Bool b1 b2 False).\n  Proof.\n    reflexivity.\n  Defined.\n\n  Definition or__eq (b1 b2 : Bool) : @identity Bool (or b1 b2) (ite Bool b1 True b2).\n  Proof.\n    reflexivity.\n  Defined.\n\n  Definition xor__eq (b1 b2 : Bool) : @identity Bool (xor b1 b2) (ite Bool b1 (not b2) b2).\n  Proof.\n    destruct b1; destruct b2; reflexivity.\n  Defined.\n\n(* *)\n (* Definition eq__eq (b1 b2 : Bool) : @identity Bool (eq b1 b2) (ite Bool b1 b2 (not b2)). *)\n (* Proof. *)\n (*   destruct b1; destruct b2; reflexivity. *)\n (* Defined. *)\n (* *)\n\n  Theorem ite_bit (b c d : Bool) : Eq Bool (ite Bool b c d) (and (or (not b) c) (or b d)).\n  Proof.\n    destruct b, c, d; reflexivity.\n  Qed.\n\n  (* TODO: doesn't actually coerce *)\n  Definition sawCoerce {T : Type} (a b : Type) (_ : T) (x : a) := x.\n\n  (* TODO: doesn't actually coerce *)\n  Definition sawUnsafeCoerce (a b : Type) (x : a) := x.\n\n  Definition Nat := nat.\n  Definition Nat_rect := nat_rect.\n\n  (* Definition minNat := Nat.min. *)\n\n  Definition uncurry (a b c : Type) (f : a -> b -> c) (p : a * (b * unit)) : c  :=\n    f (fst p) (fst (snd p)).\n\n  Definition widthNat (n : Nat) : Nat := 1 + Nat.log2 n.\n\n  Definition divModNat (x y : Nat) : (Nat * Nat) :=\n    match y with\n    | 0 => (y, y)\n    | S y'=>\n      let (p, q) := Nat.divmod x y' 0 y' in\n      (p, y' - q)\n    end.\n\n  Definition id := @id.\n  Definition PairType := prod.\n  Definition PairValue := @pair.\n  Definition Pair__rec := prod_rect.\n  Definition fst {A B} := @fst A B.\n  Definition snd {A B} := @snd A B.\n  Definition Zero := O.\n  Definition Succ := S.\n\nEnd SCS.\n\nPreprocess Module SCS as SCS'.\n", "meta": {"author": "GaloisInc", "repo": "saw-core-coq", "sha": "91d7dae3272d93906b1068e15d0312dddfa64d64", "save_path": "github-repos/coq/GaloisInc-saw-core-coq", "path": "github-repos/coq/GaloisInc-saw-core-coq/saw-core-coq-91d7dae3272d93906b1068e15d0312dddfa64d64/coq/handwritten/CryptolToCoq/SAWCoreScaffoldingCopy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.28937793727907074}}
{"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.\n\n(******************************************************************************)\n(* Reducibility of configurations number 299 to 302, whose indices in         *)\n(* the_configs range over segment [298, 302).                                 *)\n(******************************************************************************)\n\nLemma red298to302 : reducible_in_range 298 302 the_configs.\nProof. CheckReducible. Qed.\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/job299to302.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.28937793727907074}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*             The Quantitative CompCert verified compiler             *)\n(*                                                                     *)\n(*                 Tahina Ramananandro, Yale University                *)\n(*                                                                     *)\n(*  This file is derived from the backend/Mach.v file of the           *)\n(*  CompCert 1.13 verified compiler by Xavier Leroy, INRIA.            *)\n(*  The CompCert verified compiler is                                  *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  The original file is           *)\n(*  distributed                                                        *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*  According to this license, this modified version is distributed    *)\n(*  under a similar license (see LICENSE for details).                 *)\n(*                                                                     *)\n(* *********************************************************************)\n\n\n(** The [Mach2] intermediate language.\n\n    As explained in Section 3.2 of our PLDI 2014 paper, [Mach2] and\n    [Mach] have the same abstract syntax. [Mach2] is just a\n    reinterpretation of [Mach] with a finite stack space. Stack frames\n    of all function calls are merged together into a single\n    whole-program stack block.\n\n*)\n\nRequire Import Memory.\nRequire Import AST.\nRequire Import Values.\nRequire Import Events.\nRequire Import Coqlib.\nRequire Import Locations.\nRequire Import Globalenvs.\nRequire Import Op.\nRequire Import Integers.\nRequire Import Conventions.\nRequire Import Smallstep.\nRequire Import Mach.\nRequire Import Stackbounds.\n\nSection WITHRAO.\n\nVariable external_event_needs: event -> Z.\n\nVariable return_address_offset: function -> code -> int -> Prop.\n\nSection RELSEM.\n\nVariable ge: genv.\n\nInductive stackframe: Type :=\n  | Stackframe:\n      forall (f: block)       (**r pointer to calling function *)\n             (retaddr: int)   (**r Asm return address in calling function (needed to show that the code [c] below can be compiled to some assembly code)  *) \n             (c: code),       (**r program point in calling function *)\n      stackframe.\n\nInductive state: Type :=\n  | State:\n      forall (stack: list stackframe)  (**r call stack *)\n             (f: block)                (**r pointer to current function *)\n             (sp: val)                 (**r stack pointer *)\n             (c: code)                 (**r current program point *)\n             (rs: regset)              (**r register state *)\n             (m: mem),                 (**r memory state *)\n      state\n  | Callstate:\n      forall\n             (sp: val)                 (**r stack pointer *)\n             (stack: list stackframe)  (**r call stack *)\n             (f: block)                (**r pointer to function to call *)\n             (rs: regset)              (**r register state *)\n             (m: mem),                 (**r memory state *)\n      state\n  | Returnstate:\n      forall\n             (sp: val)                 (**r stack pointer *)\n             (stack: list stackframe)  (**r call stack *)\n             (rs: regset)              (**r register state *)\n             (m: mem),                 (**r memory state *)\n      state.\n\nInductive step: state -> trace -> state -> Prop :=\n  | exec_Mlabel:\n      forall s f sp lbl c rs m,\n      step (State s f sp (Mlabel lbl :: c) rs m)\n        E0 (State s f sp c rs m)\n  | exec_Mgetstack:\n      forall s f sp ofs ty dst c rs m v,\n      load_stack m sp ty ofs = Some v ->\n      step (State s f sp (Mgetstack ofs ty dst :: c) rs m)\n        E0 (State s f sp c (rs#dst <- v) m)\n  | exec_Msetstack:\n      forall s f sp src ofs ty c rs m m',\n      store_stack m sp ty ofs (rs src) = Some m' ->\n      step (State s f sp (Msetstack src ofs ty :: c) rs m)\n        E0 (State s f sp c (undef_setstack rs) m')\n  | exec_Mgetparam:\n      forall s fb f sp psp ofs ty dst c rs m v,\n      Genv.find_funct_ptr ge fb = Some (Internal f) ->\n      psp = Val.add sp (Vint (Int.repr (f.(fn_stacksize) + size_chunk Mint32))) ->\n      load_stack m psp ty ofs = Some v ->\n      step (State s fb sp (Mgetparam ofs ty dst :: c) rs m)\n        E0 (State s fb sp c (rs # IT1 <- Vundef # dst <- v) m)\n  | exec_Mop:\n      forall s f sp op args res c rs m v,\n      eval_operation ge sp op rs##args m = Some v ->\n      step (State s f sp (Mop op args res :: c) rs m)\n        E0 (State s f sp c ((undef_op op rs)#res <- v) m)\n  | exec_Mload:\n      forall s f sp chunk addr args dst c rs m a v,\n      eval_addressing ge sp addr rs##args = Some a ->\n      Mem.loadv chunk m a = Some v ->\n      step (State s f sp (Mload chunk addr args dst :: c) rs m)\n        E0 (State s f sp c ((undef_temps rs)#dst <- v) m)\n  | exec_Mstore:\n      forall s f sp chunk addr args src c rs m m' a,\n      eval_addressing ge sp addr rs##args = Some a ->\n      Mem.storev chunk m a (rs src) = Some m' ->\n      step (State s f sp (Mstore chunk addr args src :: c) rs m)\n        E0 (State s f sp c (undef_temps rs) m')\n  | exec_Mcall:\n      forall s fb sp spp sig ros c rs m m' f f' ra,\n      find_function_ptr ge ros rs = Some f' ->\n      Genv.find_funct_ptr ge fb = Some (Internal f) ->\n      spp = Val.sub sp (Vint (Int.repr (size_chunk Mint32))) ->\n      Mem.storev Mint32 m spp (Vptr fb ra) = Some m' ->\n      return_address_offset f c ra ->\n      step (State s fb sp (Mcall sig ros :: c) rs m)\n        E0 (Callstate spp (Stackframe fb ra c :: s)\n                       f' rs m')\n  | exec_Mtailcall:\n      forall s fb sp spp sig ros c rs m f f',\n      find_function_ptr ge ros rs = Some f' ->\n      Genv.find_funct_ptr ge fb = Some (Internal f) ->\n      spp = Val.add sp (Vint (Int.repr (f.(fn_stacksize)))) ->\n      forall FID (HFID: FID = f.(fn_id)),\n      step (State s fb sp (Mtailcall sig ros :: c) rs m)\n        (Event_return FID :: E0) (Callstate spp s f' rs m)\n  | exec_Mbuiltin:\n      forall s f sp rs m ef args res b t v m',\n      external_call ef ge rs##args m t v m' ->\n      forall NEED: forall s o, sp = Vptr s o ->\n                               Mem.range_perm m s (Int.unsigned o - size_chunk Mint32 - trace_needs external_event_needs t) (Int.unsigned o - size_chunk Mint32) Cur Freeable (* must have enough stack space for external function *),\n      step (State s f sp (Mbuiltin ef args res :: b) rs m)\n         t (State s f sp b ((undef_temps rs)#res <- v) m')\n  | exec_Mannot:\n      forall s f sp rs m ef args b vargs t v m',\n      annot_arguments rs m sp args vargs ->\n      external_call ef ge vargs m t v m' ->\n      forall NEED: forall s o, sp = Vptr s o ->\n                               Mem.range_perm m s (Int.unsigned o - size_chunk Mint32 - trace_needs external_event_needs t) (Int.unsigned o - size_chunk Mint32) Cur Freeable (* must have enough stack space for external function *),\n      step (State s f sp (Mannot ef args :: b) rs m)\n         t (State s f sp b rs m')\n  | exec_Mgoto:\n      forall s fb f sp lbl c rs m c',\n      Genv.find_funct_ptr ge fb = Some (Internal f) ->\n      find_label lbl f.(fn_code) = Some c' ->\n      step (State s fb sp (Mgoto lbl :: c) rs m)\n        E0 (State s fb sp c' rs m)\n  | exec_Mcond_true:\n      forall s fb f sp cond args lbl c rs m c',\n      eval_condition cond rs##args m = Some true ->\n      Genv.find_funct_ptr ge fb = Some (Internal f) ->\n      find_label lbl f.(fn_code) = Some c' ->\n      step (State s fb sp (Mcond cond args lbl :: c) rs m)\n        E0 (State s fb sp c' (undef_temps rs) m)\n  | exec_Mcond_false:\n      forall s f sp cond args lbl c rs m,\n      eval_condition cond rs##args m = Some false ->\n      step (State s f sp (Mcond cond args lbl :: c) rs m)\n        E0 (State s f sp c (undef_temps rs) m)\n  | exec_Mjumptable:\n      forall s fb f sp arg tbl c rs m n lbl c',\n      rs arg = Vint n ->\n      list_nth_z tbl (Int.unsigned n) = Some lbl ->\n      Genv.find_funct_ptr ge fb = Some (Internal f) ->\n      find_label lbl f.(fn_code) = Some c' ->\n      step (State s fb sp (Mjumptable arg tbl :: c) rs m)\n        E0 (State s fb sp c' (undef_temps rs) m)\n  | exec_Mreturn:\n      forall s fb sp psp c rs m f,\n      Genv.find_funct_ptr ge fb = Some (Internal f) ->\n\n      (* For function return, instead of freeing the stack frame\n         block, the stack pointer goes from the callee's stack frame\n         to the caller's stack frame within the single whole-program\n         stack block by directly performing pointer arithmetics on the\n         stack pointer. Thanks to this pointer arithmetics, no\n         additional back link is necessary, as was the case in the\n         genuine CompCert.\n\n         The pointer arithmetics here is specific to x86.\n       *)\n\n      psp = Val.add sp (Vint (Int.repr f.(fn_stacksize))) ->\n      forall FID (HFID: FID = f.(fn_id)),\n      step (State s fb sp (Mreturn :: c) rs m)\n        (Event_return FID :: E0) (Returnstate psp s rs m)\n  | exec_function_internal:\n      forall s fb rs m f sp csp,\n      Genv.find_funct_ptr ge fb = Some (Internal f) ->\n\n      (* For function call, instead of allocating a new block, the new\n         stack frame is obtained within the single whole-program stack\n         block by directly performing pointer arithmetics on the stack\n         pointer.\n\n         The pointer arithmetics here is specific to x86.\n       *)\n         \n      csp = Val.sub sp (Vint (Int.repr f.(fn_stacksize))) ->\n      forall FID (HFID: FID = f.(fn_id)),\n      step (Callstate sp s fb rs m)\n        (Event_call FID :: E0) (State s fb csp f.(fn_code) (undef_temps rs) m)\n  | exec_function_external:\n      forall s fb rs m t rs' ef args res m' sp psp,\n      Genv.find_funct_ptr ge fb = Some (External ef) ->\n      external_call ef ge args m t res m' ->\n      psp = Val.add sp (Vint (Int.repr (size_chunk  Mint32))) ->\n      extcall_arguments rs m psp (ef_sig ef) args ->\n      rs' = (rs#(loc_result (ef_sig ef)) <- res) ->\n      forall NEED: forall s o, sp = Vptr s o ->\n                               Mem.range_perm m s (Int.unsigned o - trace_needs external_event_needs t) (Int.unsigned o) Cur Freeable (* must have enough stack space for external function *),\n      step (Callstate sp s fb rs m)\n         t (Returnstate sp s rs' m')\n  | exec_return:\n      forall s f fd sp psp ra c rs m,\n        psp = Val.add sp (Vint (Int.repr (size_chunk Mint32))) ->\n      Mem.loadv Mint32 m sp = Some (Vptr f ra) ->\n      Genv.find_funct_ptr ge f = Some (Internal fd) ->\n      return_address_offset fd c ra ->      \n      step (Returnstate sp (Stackframe f ra c :: s) rs m)\n        E0 (State s f psp c rs m).\n\nEnd RELSEM.\n\nSection BOUNDED.\n\nVariable bound: int.\n\nInductive initial_state (p: program): state -> Prop :=\n  | initial_state_intro: forall fb m0,\n      let ge := Genv.globalenv p in\n      Genv.init_mem p = Some m0 ->\n      forall m1 stk, \n      Mem.alloc m0 0 (Int.unsigned bound) = (m1, stk) ->\n      Genv.find_symbol ge p.(prog_main) = Some fb ->\n      initial_state p (Callstate (Vptr stk bound) nil fb (Regmap.init Vundef) m1).\n\nInductive final_state (p: program): state -> int -> Prop :=\n  | final_state_intro: forall sp rs m r,\n      rs (loc_result (mksignature nil (Some Tint))) = Vint r ->\n      sp = Vptr (Genv.genv_next (Genv.globalenv p)) bound ->\n      final_state p (Returnstate sp nil rs m) r.\n\nDefinition semantics (p: program) :=\n  Semantics (step) (initial_state p) (final_state p) (Genv.globalenv p).\n\nEnd BOUNDED.\n\nEnd WITHRAO.\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/ia32/Mach2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2892017034204533}}
{"text": "Require Import Raft.\nRequire Import RaftRefinementInterface.\n\nRequire Import CommonTheorems.\nRequire Import SpecLemmas.\nRequire Import RefinementSpecLemmas.\n\nRequire Import UpdateLemmas.\nLocal Arguments update {_} {_} {_} _ _ _ _ : simpl never.\n\nRequire Import TermSanityInterface.\nRequire Import 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 update_destruct :=\n    match goal with\n      | [ |- context [ update _ ?y _ ?x ] ] => destruct (name_eq_dec y x)\n    end.\n\n  Ltac update_destruct_hyp :=\n    match goal with\n      | [ _ : context [ update _ ?y _ ?x ] |- _ ] => destruct (name_eq_dec y x)\n    end.\n\n  Ltac destruct_update :=\n    repeat (first [update_destruct_hyp|update_destruct]; subst; rewrite_update).\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 omega;\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 le_antisym.\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 le_antisym.\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 le_antisym.\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 le_antisym.\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 le_antisym.\n  Qed.\n\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    omega.\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    omega.\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.", "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/LogAllEntriesProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723316991792861, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.28920169777218446}}
{"text": "From iris.algebra Require Export cmra.\nFrom iris Require Import options.\n\n(** * Frame preserving updates *)\n(* This quantifies over [option A] for the frame.  That is necessary to\n   make the following hold:\n     x ~~> P → Some c ~~> Some P\n*)\nDefinition cmra_updateP {A : cmraT} (x : A) (P : A → Prop) := ∀ n mz,\n  ✓{n} (x ⋅? mz) → ∃ y, P y ∧ ✓{n} (y ⋅? mz).\nInstance: Params (@cmra_updateP) 1 := {}.\nInfix \"~~>:\" := cmra_updateP (at level 70).\n\nDefinition cmra_update {A : cmraT} (x y : A) := ∀ n mz,\n  ✓{n} (x ⋅? mz) → ✓{n} (y ⋅? mz).\nInfix \"~~>\" := cmra_update (at level 70).\nInstance: Params (@cmra_update) 1 := {}.\n\nSection updates.\nContext {A : cmraT}.\nImplicit Types x y : A.\n\nGlobal Instance cmra_updateP_proper :\n  Proper ((≡) ==> pointwise_relation _ iff ==> iff) (@cmra_updateP A).\nProof.\n  rewrite /pointwise_relation /cmra_updateP=> x x' Hx P P' HP;\n    split=> ? n mz; setoid_subst; naive_solver.\nQed.\nGlobal Instance cmra_update_proper :\n  Proper ((≡) ==> (≡) ==> iff) (@cmra_update A).\nProof.\n  rewrite /cmra_update=> x x' Hx y y' Hy; split=> ? n mz ?; setoid_subst; auto.\nQed.\n\nLemma cmra_update_updateP x y : x ~~> y ↔ x ~~>: (y =.).\nProof. split=> Hup n z ?; eauto. destruct (Hup n z) as (?&<-&?); auto. Qed.\nLemma cmra_updateP_id (P : A → Prop) x : P x → x ~~>: P.\nProof. intros ? n mz ?; eauto. Qed.\nLemma cmra_updateP_compose (P Q : A → Prop) x :\n  x ~~>: P → (∀ y, P y → y ~~>: Q) → x ~~>: Q.\nProof. intros Hx Hy n mz ?. destruct (Hx n mz) as (y&?&?); naive_solver. Qed.\nLemma cmra_updateP_compose_l (Q : A → Prop) x y : x ~~> y → y ~~>: Q → x ~~>: Q.\nProof.\n  rewrite cmra_update_updateP.\n  intros; apply cmra_updateP_compose with (y =.); naive_solver.\nQed.\nLemma cmra_updateP_weaken (P Q : A → Prop) x :\n  x ~~>: P → (∀ y, P y → Q y) → x ~~>: Q.\nProof. eauto using cmra_updateP_compose, cmra_updateP_id. Qed.\nLemma cmra_update_exclusive `{!Exclusive x} y:\n  ✓ y → x ~~> y.\nProof. move=>??[z|]=>[/exclusiveN_l[]|_]. by apply cmra_valid_validN. Qed.\n\n(** Updates form a preorder. *)\nGlobal Instance cmra_update_preorder : PreOrder (@cmra_update A).\nProof.\n  split.\n  - intros x. by apply cmra_update_updateP, cmra_updateP_id.\n  - intros x y z. rewrite !cmra_update_updateP.\n    eauto using cmra_updateP_compose with subst.\nQed.\n\nLemma cmra_updateP_op (P1 P2 Q : A → Prop) x1 x2 :\n  x1 ~~>: P1 → x2 ~~>: P2 → (∀ y1 y2, P1 y1 → P2 y2 → Q (y1 ⋅ y2)) →\n  x1 ⋅ x2 ~~>: Q.\nProof.\n  intros Hx1 Hx2 Hy n mz ?.\n  destruct (Hx1 n (Some (x2 ⋅? mz))) as (y1&?&?).\n  { by rewrite /= -cmra_op_opM_assoc. }\n  destruct (Hx2 n (Some (y1 ⋅? mz))) as (y2&?&?).\n  { by rewrite /= -cmra_op_opM_assoc (comm _ x2) cmra_op_opM_assoc. }\n  exists (y1 ⋅ y2); split; last rewrite (comm _ y1) cmra_op_opM_assoc; auto.\nQed.\nLemma cmra_updateP_op' (P1 P2 : A → Prop) x1 x2 :\n  x1 ~~>: P1 → x2 ~~>: P2 →\n  x1 ⋅ x2 ~~>: λ y, ∃ y1 y2, y = y1 ⋅ y2 ∧ P1 y1 ∧ P2 y2.\nProof. eauto 10 using cmra_updateP_op. Qed.\nLemma cmra_update_op x1 x2 y1 y2 : x1 ~~> y1 → x2 ~~> y2 → x1 ⋅ x2 ~~> y1 ⋅ y2.\nProof.\n  rewrite !cmra_update_updateP; eauto using cmra_updateP_op with congruence.\nQed.\n\nLemma cmra_update_op_l x y : x ⋅ y ~~> x.\nProof. intros n mz. rewrite comm cmra_op_opM_assoc. apply cmra_validN_op_r. Qed.\nLemma cmra_update_op_r x y : x ⋅ y ~~> y.\nProof. rewrite comm. apply cmra_update_op_l. Qed.\n\nLemma cmra_update_valid0 x y : (✓{0} x → x ~~> y) → x ~~> y.\nProof.\n  intros H n mz Hmz. apply H, Hmz.\n  apply (cmra_validN_le n); last lia.\n  destruct mz. eapply cmra_validN_op_l, Hmz. apply Hmz.\nQed.\n\n(** ** Frame preserving updates for total CMRAs *)\nSection total_updates.\n  Local Set Default Proof Using \"Type*\".\n  Context `{CmraTotal A}.\n\n  Lemma cmra_total_updateP x (P : A → Prop) :\n    x ~~>: P ↔ ∀ n z, ✓{n} (x ⋅ z) → ∃ y, P y ∧ ✓{n} (y ⋅ z).\n  Proof.\n    split=> Hup; [intros n z; apply (Hup n (Some z))|].\n    intros n [z|] ?; simpl; [by apply Hup|].\n    destruct (Hup n (core x)) as (y&?&?); first by rewrite cmra_core_r.\n    eauto using cmra_validN_op_l.\n  Qed.\n  Lemma cmra_total_update x y : x ~~> y ↔ ∀ n z, ✓{n} (x ⋅ z) → ✓{n} (y ⋅ z).\n  Proof. rewrite cmra_update_updateP cmra_total_updateP. naive_solver. Qed.\n\n  Context `{CmraDiscrete A}.\n\n  Lemma cmra_discrete_updateP (x : A) (P : A → Prop) :\n    x ~~>: P ↔ ∀ z, ✓ (x ⋅ z) → ∃ y, P y ∧ ✓ (y ⋅ z).\n  Proof.\n    rewrite cmra_total_updateP; setoid_rewrite <-cmra_discrete_valid_iff.\n    naive_solver eauto using O.\n  Qed.\n  Lemma cmra_discrete_update (x y : A) :\n    x ~~> y ↔ ∀ z, ✓ (x ⋅ z) → ✓ (y ⋅ z).\n  Proof.\n    rewrite cmra_total_update; setoid_rewrite <-cmra_discrete_valid_iff.\n    naive_solver eauto using O.\n  Qed.\nEnd total_updates.\nEnd updates.\n\n(** * Transport *)\nSection cmra_transport.\n  Context {A B : cmraT} (H : A = B).\n  Notation T := (cmra_transport H).\n  Lemma cmra_transport_updateP (P : A → Prop) (Q : B → Prop) x :\n    x ~~>: P → (∀ y, P y → Q (T y)) → T x ~~>: Q.\n  Proof. destruct H; eauto using cmra_updateP_weaken. Qed.\n  Lemma cmra_transport_updateP' (P : A → Prop) x :\n    x ~~>: P → T x ~~>: λ y, ∃ y', y = cmra_transport H y' ∧ P y'.\n  Proof. eauto using cmra_transport_updateP. Qed.\nEnd cmra_transport.\n\n(** * Isomorphism *)\nSection iso_cmra.\n  Context {A B : cmraT} (f : A → B) (g : B → A).\n\n  Lemma iso_cmra_updateP (P : B → Prop) (Q : A → Prop) y\n      (gf : ∀ x, g (f x) ≡ x)\n      (g_op : ∀ y1 y2, g (y1 ⋅ y2) ≡ g y1 ⋅ g y2)\n      (g_validN : ∀ n y, ✓{n} (g y) ↔ ✓{n} y) :\n    y ~~>: P →\n    (∀ y', P y' → Q (g y')) →\n    g y ~~>: Q.\n  Proof.\n    intros Hup Hx n mz Hmz.\n    destruct (Hup n (f <$> mz)) as (y'&HPy'&Hy'%g_validN).\n    { apply g_validN. destruct mz as [z|]; simpl in *; [|done].\n      by rewrite g_op gf. }\n    exists (g y'); split; [by eauto|].\n    destruct mz as [z|]; simpl in *; [|done].\n    revert Hy'. by rewrite g_op gf.\n  Qed.\n\n  Lemma iso_cmra_updateP' (P : B → Prop) y\n      (gf : ∀ x, g (f x) ≡ x)\n      (g_op : ∀ y1 y2, g (y1 ⋅ y2) ≡ g y1 ⋅ g y2)\n      (g_validN : ∀ n y, ✓{n} (g y) ↔ ✓{n} y) :\n    y ~~>: P →\n    g y ~~>: λ x, ∃ y, x = g y ∧ P y.\n  Proof. eauto using iso_cmra_updateP. Qed.\nEnd iso_cmra.\n\n(** * Product *)\nSection prod.\n  Context {A B : cmraT}.\n  Implicit Types x : A * B.\n\n  Lemma prod_updateP P1 P2 (Q : A * B → Prop) x :\n    x.1 ~~>: P1 → x.2 ~~>: P2 → (∀ a b, P1 a → P2 b → Q (a,b)) → x ~~>: Q.\n  Proof.\n    intros Hx1 Hx2 HP n mz [??]; simpl in *.\n    destruct (Hx1 n (fst <$> mz)) as (a&?&?); first by destruct mz.\n    destruct (Hx2 n (snd <$> mz)) as (b&?&?); first by destruct mz.\n    exists (a,b); repeat split; destruct mz; auto.\n  Qed.\n  Lemma prod_updateP' P1 P2 x :\n    x.1 ~~>: P1 → x.2 ~~>: P2 → x ~~>: λ y, P1 (y.1) ∧ P2 (y.2).\n  Proof. eauto using prod_updateP. Qed.\n  Lemma prod_update x y : x.1 ~~> y.1 → x.2 ~~> y.2 → x ~~> y.\n  Proof.\n    rewrite !cmra_update_updateP.\n    destruct x, y; eauto using prod_updateP with subst.\n  Qed.\nEnd prod.\n\n(** * Option *)\nSection option.\n  Context {A : cmraT}.\n  Implicit Types x y : A.\n\n  Lemma option_updateP (P : A → Prop) (Q : option A → Prop) x :\n    x ~~>: P → (∀ y, P y → Q (Some y)) → Some x ~~>: Q.\n  Proof.\n    intros Hx Hy; apply cmra_total_updateP=> n [y|] ?.\n    { destruct (Hx n (Some y)) as (y'&?&?); auto. exists (Some y'); auto. }\n    destruct (Hx n None) as (y'&?&?); rewrite ?cmra_core_r; auto.\n    by exists (Some y'); auto.\n  Qed.\n  Lemma option_updateP' (P : A → Prop) x :\n    x ~~>: P → Some x ~~>: from_option P False.\n  Proof. eauto using option_updateP. Qed.\n  Lemma option_update x y : x ~~> y → Some x ~~> Some y.\n  Proof. rewrite !cmra_update_updateP; eauto using option_updateP with subst. Qed.\nEnd option.\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/updates.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2890800967603567}}
{"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 csubst2.\n\n\nLemma isprogram_isint {o} :\n  forall a b c,\n    isprogram a\n    -> isprogram b\n    -> @isprogram o c\n    -> isprogram (mk_isint a b c).\nProof.\n  repeat constructor.\n  unfold closed; simpl.\n  allrw <- null_iff_nil.\n  repeat (rw null_app).\n  repeat (rw null_iff_nil).\n  allunfold @isprogram; allunfold @closed.\n  repeat (rewrite remove_nvars_nil_l); sp.\n  simpl; sp; allunfold @isprogram; sp; subst; constructor; auto.\nQed.\n\nLemma isprogram_isint_iff {p} :\n  forall a b c, (isprogram a # isprogram b # @isprogram p c) <=> isprogram (mk_isint a b c).\nProof.\n  intros; split; intro i.\n  apply isprogram_isint; sp.\n  inversion i as [cl w].\n  allunfold @closed; allsimpl.\n  allrw remove_nvars_nil_l.\n  allrw app_nil_r.\n  allrw app_eq_nil_iff; repnd; allrw.\n  inversion w as [| | o lnt k meq ]; allsimpl; subst.\n  generalize (k (nobnd a)) (k (nobnd b)) (k (nobnd c)); intros i1 i2 i3.\n  dest_imp i1 hyp; dest_imp i2 hyp; dest_imp i3 hyp.\n  unfold isprogram; allrw.\n  inversion i1; inversion i2; inversion i3; subst; sp.\nQed.\n\nLemma isprog_isint {p} :\n  forall a b c,\n    isprog a\n    -> isprog b\n    -> @isprog p c\n    -> isprog (mk_isint a b c).\nProof.\n  sp; allrw @isprog_eq.\n  apply isprogram_isint; auto.\nQed.\n\nDefinition mkc_isint {p} (t1 t2 t3 : @CTerm p) : CTerm :=\n  let (a,x) := t1 in\n  let (b,y) := t2 in\n  let (c,z) := t3 in\n  exist isprog (mk_isint a b c) (isprog_isint a b c x y z).\n\nLemma mkc_isint_eq {p} :\n  forall a b c d e f,\n    mkc_isint a b c = @mkc_isint p d e f\n    -> a = d # b = e # c = f.\nProof.\n  introv eq.\n  destruct_cterms.\n  allunfold @mkc_isint.\n  inversion eq; subst; dands; tcsp; eauto with pi.\nQed.\n\nLemma fold_isint {p} :\n  forall a b c,\n    oterm (NCan (NCanTest CanIsint)) [ nobnd a, nobnd b, @nobnd p c ]\n    = mk_isint a b c.\nProof.\n  sp.\nQed.\n\nLemma lsubstc_mk_isint {p} :\n  forall t1 t2 t3 sub,\n  forall w1 : wf_term t1,\n  forall w2 : wf_term t2,\n  forall w3 : @wf_term p t3,\n  forall w  : wf_term (mk_isint t1 t2 t3),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars t2 sub,\n  forall c3 : cover_vars t3 sub,\n  forall c  : cover_vars (mk_isint t1 t2 t3) sub,\n    lsubstc (mk_isint t1 t2 t3) w sub c\n    = mkc_isint (lsubstc t1 w1 sub c1)\n                  (lsubstc t2 w2 sub c2)\n                  (lsubstc t3 w3 sub c3).\nProof.\n  introv.\n\n  apply cterm_eq; simpl.\n  unfold csubst; simpl;\n  change_to_lsubst_aux4; simpl;\n  rw @sub_filter_nil_r;\n  allrw @fold_nobnd;\n  rw @fold_isint; sp.\nQed.\n\nLemma lsubstc_mk_isint_ex {p} :\n  forall t1 t2 t3 sub,\n  forall w  : wf_term (@mk_isint p t1 t2 t3),\n  forall c  : cover_vars (mk_isint t1 t2 t3) sub,\n  {w1 : wf_term t1\n   & {w2 : wf_term t2\n   & {w3 : wf_term t3\n   & {c1 : cover_vars t1 sub\n   & {c2 : cover_vars t2 sub\n   & {c3 : cover_vars t3 sub\n      & lsubstc (mk_isint t1 t2 t3) w sub c\n           = mkc_isint (lsubstc t1 w1 sub c1)\n                         (lsubstc t2 w2 sub c2)\n                         (lsubstc t3 w3 sub c3)}}}}}}.\nProof.\n  sp.\n\n  assert (wf_term t1) as w1.\n  { allrw @wf_can_test_iff; sp. }\n\n  assert (wf_term t2) as w2.\n  { allrw @wf_can_test_iff; sp. }\n\n  assert (wf_term t3) as w3.\n  { allrw @wf_can_test_iff; sp. }\n\n  assert (cover_vars t1 sub) as c1.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  assert (cover_vars t2 sub) as c2.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  assert (cover_vars t3 sub) as c3.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists w1 w2 w3 c1 c2 c3.\n  apply lsubstc_mk_isint.\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/csubst3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.2890800894146157}}
{"text": "(** * Interpreter for the monomorphic fragment of the Oak langage *)\nRequire Import Relations Morphisms.\nRequire Import String.\nRequire Import List.\nRequire Import Ast MyEnv.\n\n(* TODO: we use definition of monads from Template Coq,\n   but (as actually comment in the [monad_utils] says, we\n   should use a real monad library) *)\nRequire Import Template.monad_utils.\n\n\nImport ListNotations.\nImport MonadNotation.\n\n(* Common definitions *)\n\nInductive res A :=\n| Ok : A -> res A\n| NotEnoughFuel : res A\n| EvalError : string -> res A.\n\n\nArguments Ok {_}.\nArguments NotEnoughFuel {_}.\nArguments EvalError {_}.\n\nInstance res_monad : Monad res :=\n  { ret := @Ok;\n    bind := fun _ _ r f => match r with\n                    | Ok v => f v\n                    | EvalError msg => EvalError msg\n                    | NotEnoughFuel => NotEnoughFuel\n                        end }.\n\nDefinition res_map {A B} (f : A -> B) (r : res A) : res B :=\n  v <- r ;;\n  ret (f v).\n\nDefinition option_to_res {A : Type} (o : option A) (msg : string) :=\n  match o with\n  | Some v => Ok v\n  | None => EvalError msg\n  end.\n\nDefinition todo {A} := EvalError (A:=A) \"Not implemented\".\n\nModule InterpreterEnvList.\n\n  Import Basics.\n\n  Open Scope program_scope.\n\n  (** A type of labels to distinguish closures corresponding to lambdas and fixpoints *)\n  Inductive clos_mode : Type :=\n    cmLam | cmFix : name -> clos_mode.\n\n  (** Values *)\n  Inductive val : Type :=\n  | vConstr : inductive -> name -> list val -> val\n  | vClos   : env val -> name ->\n              clos_mode ->\n              type ->(* type of the domain *)\n              type ->(* type of the codomain *)\n              expr -> val.\n\n  Definition ForallEnv {A} (P: A -> Prop) : env A -> Prop := Forall (P ∘ snd).\n\n  (** Value is well-formed if expressions in closures are appropriately closed *)\n  Inductive val_ok Σ : val -> Prop :=\n  | vokClosLam : forall e nm ρ ty1 ty2,\n      ForallEnv (val_ok Σ) ρ ->\n      iclosed_n (1 + length ρ) e = true ->\n      val_ok Σ (vClos ρ nm cmLam ty1 ty2 e)\n  | vokClosFix : forall e nm fixname ρ ty1 ty2,\n      ForallEnv (val_ok Σ) ρ ->\n      iclosed_n (2 + length ρ) e = true ->\n      val_ok Σ (vClos ρ nm (cmFix fixname) ty1 ty2 e)\n  | vokContr : forall i nm vs ci,\n      Forall (val_ok Σ) vs ->\n      resolve_constr Σ i nm = Some ci ->\n      val_ok Σ (vConstr i nm vs).\n\n  Definition env_ok Σ (ρ : env val) := ForallEnv (val_ok Σ) ρ.\n\n  (** An induction principle that takes into account nested occurrences of elements of [val] in the list of arguments of [vConstr] and in the environment of [vClos] *)\n  Definition val_ind_full\n     (P : val -> Prop)\n     (Hconstr : forall (i : inductive) (n : name) (l : list val), Forall P l -> P (vConstr i n l))\n     (Hclos : forall (ρ : env val) (n : name) (cm : clos_mode) (ty1 ty2 : type) (e0 : expr),\n          ForallEnv P ρ -> P (vClos ρ n cm ty1 ty2 e0)) :\n    forall v : val, P v.\n    refine (fix val_ind_fix (v : val) := _).\n    destruct v.\n    + apply Hconstr.\n      induction l. constructor. constructor. apply val_ind_fix. apply IHl.\n    + apply Hclos.\n      induction e.\n      * constructor.\n      * constructor. apply val_ind_fix. apply IHe.\n  Defined.\n\n  (** For some reason, this is not a part of the standard lib *)\n  Lemma Forall_app {A} (l1 l2 : list A) P :\n    Forall P (l1 ++ l2) <-> Forall P l1 /\\ Forall P l2.\n  Proof.\n    split.\n    - intros H. induction l1.\n      + simpl in *. easy.\n      + simpl in *. inversion H. subst.\n        split.\n        * constructor. assumption.\n          destruct (IHl1 H3). assumption.\n        * destruct (IHl1 H3). assumption.\n    - intros H. induction l1.\n      + simpl in *. easy.\n      + simpl in *. destruct H as [H1 H2].\n        constructor;inversion H1;auto.\n  Qed.\n\n  Lemma Forall_rev {A} {l : list A} P : Forall P l -> Forall P (rev l).\n  Proof.\n    intros H.\n    induction l.\n    + constructor.\n    + simpl. apply Forall_app.\n      inversion H;auto.\n  Qed.\n\n  Definition ind_name (v : val) :=\n    match v with\n    | vConstr ind_name _ _ => Some ind_name\n    | _ => None\n    end.\n\n  (** Very simple implementation of pattern-matching *)\n  Definition match_pat {A} (cn : name) (arity :list type)\n             (constr_args : list A) (bs : list (pat * expr)) :=\n    pe <- find (fun x => (fst x).(pName) =? cn) bs;;\n    let '(p,e) := pe in\n    if (andb (Nat.eqb (length constr_args) (length p.(pVars)))\n             (Nat.eqb (length constr_args) (length arity))) then\n      let assignments := combine p.(pVars) constr_args in\n      Some (assignments,e)\n    else None.\n\n  (** ** The interpreter *)\n\n  (** The interpreter works for both named and nameless representation of Oak expressions, depending on a parameter [named]. Due to the potential non-termination of Oak programs, we define our interpreter using a fuel idiom: by structural recursion on an additional argument (a natural number). *)\n  Fixpoint expr_eval_general (fuel : nat) (named : bool) (Σ : global_env)\n           (ρ : env val) (e : expr) : res val :=\n    match fuel with\n    | O => NotEnoughFuel\n    | S n =>\n      match e with\n      | eRel i => if named then EvalError \"Indices as variables are not supported\"\n                  else option_to_res (lookup_i ρ i) (\"var not found\")\n      | eVar nm => if named then\n                    option_to_res (ρ # (nm)) (nm ++ \" - var not found\")\n                  else EvalError (nm ++ \" variable found, but named variables are not supported\")\n      | eLambda nm ty b =>\n      (* NOTE: we pass the same type as the codomain type here\n        (because it's not needed for lambda).\n        Maybe separate constructors for lambda/fixpoint closures would be better? *)\n        Ok (vClos ρ nm cmLam ty ty b)\n      | eLetIn nm e1 ty e2 =>\n        v <- expr_eval_general n named Σ ρ e1 ;;\n        expr_eval_general n named Σ (ρ # [nm ~> v]) e2\n      | eApp e1 e2 =>\n        match (expr_eval_general n named Σ ρ e1), (expr_eval_general n named Σ ρ e2) with\n        | Ok (vClos ρ' nm cmLam _ _ b), Ok v =>\n          res <- (expr_eval_general n named Σ (ρ' # [nm ~> v]) b);;\n          ret res\n        | Ok (vClos ρ' nm (cmFix fixname) ty1 ty2 b), Ok v =>\n          let v_fix := (vClos ρ' nm (cmFix fixname) ty1 ty2 b) in\n          res <- expr_eval_general n named Σ (ρ' # [fixname ~> v_fix] # [nm ~> v]) b;;\n          ret res\n        | Ok (vConstr ind n vs), Ok v => Ok (vConstr ind n (List.app vs [v]))\n        | EvalError msg, _ => EvalError msg\n        | _, EvalError msg => EvalError msg\n        | NotEnoughFuel,_ | _, NotEnoughFuel => NotEnoughFuel\n        end\n      | eConstr ind ctor =>\n        match (resolve_constr Σ ind ctor) with\n        | Some _ => Ok (vConstr ind ctor [])\n        | _ => EvalError \"No constructor or inductive found\"\n        end\n      | eConst nm => todo\n      | eCase (ind,i) ty e bs =>\n        match (expr_eval_general n named Σ ρ e) with\n        | Ok (vConstr ind' c vs) =>\n          match resolve_constr Σ ind' c with\n          | Some (_,ci) =>\n            (* TODO : move cheking inductive names before\n               resolving the constructor *)\n            if (string_dec ind ind') then\n              match (match_pat c ci vs bs) with\n              | Some (var_assign, v) =>\n                expr_eval_general n named Σ (List.app (rev var_assign) ρ) v\n              | None => EvalError \"No such constructor\"\n              end\n            else EvalError (\"Expecting inductive \" ++ ind ++\n                            \" but found \" ++ ind')\n            | None => EvalError \"No constructor or inductive found in the global envirionment\"\n          end\n        | Ok _ => EvalError \"Discriminee should evaluate to a constructor\"\n        | v => v\n        end\n      | eFix fixname vn ty1 ty2 b as e =>\n        Ok (vClos ρ vn (cmFix fixname) ty1 ty2 b)\n      end\n    end.\n\n  Definition expr_eval_n n := expr_eval_general n true.\n  Definition expr_eval_i n := expr_eval_general n false.\n\n  (** * Converting values to expressions *)\n  (** Proving soundness of the embedding requires comparing of values to the MetaCoq terms. In order to accomplish this we need some way of first instantiating all closures with the values contained in the environments for a given closure *)\n\n\n  (** Substitution of an environment to an expression. NOTE: assumes, that expression in [ρ] are closed! *)\n\n Fixpoint subst_env (ρ : list (name * expr)) (e : expr) : expr :=\n  match e with\n  | eRel i as e' => e'\n  | eVar nm  => match lookup ρ nm with\n                    | Some v => v\n                    | None => e\n                    end\n  | eLambda nm ty b => eLambda nm ty (subst_env (remove_by_key nm ρ) b)\n  | eLetIn nm e1 ty e2 => eLetIn nm (subst_env ρ e1) ty (subst_env (remove_by_key nm ρ) e2)\n  | eApp e1 e2 => eApp (subst_env ρ e1) (subst_env ρ e2)\n  | eConstr t i as e' => e'\n  | eConst nm => eConst nm\n  | eCase nm_i ty e bs =>\n    (* TODO: this case is not complete! We ignore variables bound by patterns *)\n    eCase nm_i ty (subst_env ρ e) (map (fun x => (fst x, subst_env ρ (snd x))) bs)\n  | eFix nm v ty1 ty2 b => eFix nm v ty1 ty2 (subst_env (remove_by_key v ρ) b)\n  end.\n\n  (* NOTE: assumes, that expression in [ρ] are closed! *)\n Fixpoint subst_env_i_aux (k : nat) (ρ : env expr) (e : expr) : expr :=\n  match e with\n  | eRel i => if Nat.leb k i then\n               from_option (lookup_i ρ (i-k)) (eRel i) else eRel i\n  | eVar nm  => eVar nm\n  | eLambda nm ty b => eLambda nm ty (subst_env_i_aux (1+k) ρ b)\n  | eLetIn nm e1 ty e2 => eLetIn nm (subst_env_i_aux k ρ e1) ty (subst_env_i_aux (1+k) ρ e2)\n  | eApp e1 e2 => eApp (subst_env_i_aux k ρ e1) (subst_env_i_aux k ρ e2)\n  | eConstr t i as e' => e'\n  | eConst nm => eConst nm\n  | eCase nm_i ty e bs =>\n    eCase nm_i ty (subst_env_i_aux k ρ e)\n          (map (fun x => (fst x, subst_env_i_aux (length (fst x).(pVars) + k) ρ (snd x))) bs)\n  | eFix nm v ty1 ty2 b => eFix nm v ty1 ty2 (subst_env_i_aux (2+k) ρ b)\n  end.\n\n Definition subst_env_i := subst_env_i_aux 0.\n\n  (** Converting from values back to expression. The most non-trivial part is to convert closures, for which we have to perform some form\n     of substitution of values from the value environment (see [subst_env], [subst_env_i]). Inspired by the implementation of \"A Certified Implementation of ML with Structural Polymorphism\" by Jacques Garrigue. *)\n  Fixpoint from_val (v : val) : expr :=\n    match v with\n    | vConstr x i vs => vars_to_apps (eConstr x i) (map from_val vs)\n    | vClos ρ nm cm ty1 ty2 e =>\n      let res := match cm with\n                 | cmLam => eLambda nm ty1 e\n                 | cmFix fixname => eFix fixname nm ty1 ty2 e\n                 end\n      in subst_env (map (fun x => (fst x, from_val (snd x))) ρ) res\n    end.\n\n  Definition inst_env (ρ : env val) (e : expr) : expr :=\n    subst_env (map (fun x => (fst x, from_val (snd x))) ρ) e.\n\n  Fixpoint from_val_i (v : val) : expr :=\n    match v with\n    | vConstr x i vs => vars_to_apps (eConstr x i) (map from_val_i vs)\n    | vClos ρ nm cm ty1 ty2 e =>\n      let res := match cm with\n                 | cmLam => eLambda nm ty1 e\n                 | cmFix fixname => eFix fixname nm ty1 ty2 e\n                end\n     in subst_env_i (map (fun x => (fst x, from_val_i (snd x))) ρ) res\n    end.\n\n  Notation \"e .[ ρ ] n \" := (subst_env_i_aux n ρ e) (at level 50).\n\n Definition inst_env_i (ρ : env val) (e : expr) : expr :=\n   subst_env_i (map (fun x => (fst x, from_val_i (snd x))) ρ) e.\n Notation \"e .[ ρ ]\" := (subst_env_i ρ e) (at level 50).\n\n\n (** Values are equivalent up to subsitution of corresponding environments in closures *)\n Module Equivalence.\n   Reserved Notation \"v1 ≈ v2\" (at level 50).\n\n   Inductive val_equiv : relation val :=\n   | veqConstr i n (vs1 vs2 : list val) :\n       Forall2 (fun v1 v2 => v1 ≈ v2) vs1 vs2 -> vConstr i n vs1 ≈ vConstr i n vs2\n   | veqClosLam ρ1 ρ2 nm ty1 e1 e2 :\n       inst_env_i ρ1 (eLambda nm ty1 e1) = inst_env_i ρ2 (eLambda nm ty1 e2) ->\n       (* ty2 used only by a fixpoint, so it doesn't matter here *)\n       forall ty2 ty2', vClos ρ1 nm cmLam ty1 ty2 e1 ≈ vClos ρ2 nm cmLam ty1 ty2' e2\n   | veqClosFix ρ1 ρ2 n ty1 ty2 e1 e2 :\n       (forall fixname ty2 , inst_env_i ρ1 (eFix fixname n ty1 ty2 e1) =\n       inst_env_i ρ2 (eFix fixname n ty1 ty2 e2)) ->\n       (forall fixname, vClos ρ1 n (cmFix fixname) ty1 ty2 e1 ≈ vClos ρ2 n (cmFix fixname) ty1 ty2 e2)\n   where\n   \"v1 ≈ v2\" := (val_equiv v1 v2).\n\n   Definition list_val_equiv vs1 vs2 := Forall2 (fun v1 v2 => v1 ≈ v2) vs1 vs2.\n   Notation \" vs1 ≈ₗ vs2 \" := (list_val_equiv vs1 vs2) (at level 50).\n\n   Instance val_equiv_reflexive : Reflexive val_equiv.\n   Proof.\n     intros v. induction v using val_ind_full.\n     + constructor.\n       induction l;constructor; inversion H; easy.\n     + destruct cm;constructor;reflexivity.\n   Defined.\n\n   (* TODO:  Add the rest to prove that [val_equiv] is indeed an equivalence *)\n   Axiom val_equiv_symmetric : Symmetric val_equiv.\n   Axiom val_equiv_transitive : Transitive val_equiv.\n\n   Existing Instance val_equiv_symmetric.\n   Existing Instance val_equiv_transitive.\n\n   (* TODO:  Define these  *)\n   Axiom list_val_equiv_reflexive : Reflexive list_val_equiv.\n   Axiom list_val_equiv_symmetric : Symmetric list_val_equiv.\n   Axiom list_val_equiv_transitive : Transitive list_val_equiv.\n\n   Existing Instance list_val_equiv_reflexive.\n   Existing Instance list_val_equiv_symmetric.\n   Existing Instance list_val_equiv_transitive.\n\n   Lemma list_val_compat v1 v2 vs1 vs2 :\n     v1 ≈ v2 -> vs1 ≈ₗ vs2 -> (v1 :: vs1) ≈ₗ (v2 :: vs2).\n   Proof.\n     intros Heq Heql.\n     constructor;easy.\n   Qed.\n\n   Instance cons_compat : Proper (val_equiv ==> list_val_equiv ==> list_val_equiv) cons.\n   Proof.\n      cbv;intros;apply list_val_compat;assumption.\n    Defined.\n\n    Lemma constr_cons_compat (vs1 vs2 : list val) (i : inductive) (nm : name) :\n      vs1 ≈ₗ vs2 -> (vConstr i nm vs1) ≈ (vConstr i nm vs2).\n    Proof.\n      intros Heql.\n      constructor.\n      induction Heql.\n      + constructor.\n      + constructor; assumption.\n    Defined.\n\n    Instance constr_morph i nm : Proper (list_val_equiv ==> val_equiv) (vConstr i nm).\n    Proof.\n      cbv;intros;apply constr_cons_compat;assumption.\n    Defined.\n\n  End Equivalence.\n\nEnd InterpreterEnvList.\n\nModule Examples.\n  Import BaseTypes.\n  Import StdLib.\n\n  Definition prog1 :=\n    [|\n     (\\x : Bool ->\n           case x : Bool return Bool of\n           | true -> false\n           | false -> true) true\n     |].\n\n  Example eval_prog1_named :\n    InterpreterEnvList.expr_eval_n 3 Σ [] prog1 = Ok (InterpreterEnvList.vConstr \"Coq.Init.Datatypes.bool\" \"false\" []).\n  Proof. simpl. reflexivity. Qed.\n\n  Example eval_prog1_indexed :\n    InterpreterEnvList.expr_eval_i 3 Σ [] (indexify [] prog1) = Ok (InterpreterEnvList.vConstr \"Coq.Init.Datatypes.bool\" \"false\" []).\n  Proof. simpl. reflexivity. Qed.\n\n  End Examples.\n", "meta": {"author": "annenkov", "repo": "FMBC19-artefact", "sha": "3218074bc5f9b87a2761352e7c0a06be67cbf5b6", "save_path": "github-repos/coq/annenkov-FMBC19-artefact", "path": "github-repos/coq/annenkov-FMBC19-artefact/FMBC19-artefact-3218074bc5f9b87a2761352e7c0a06be67cbf5b6/theories/Monomorphic/EvalE.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.28908008941461566}}
{"text": "From Coq Require Import micromega.Psatz Reals.Rdefinitions.\n\nRequire Import Helix.Tactics.StructTactics.\n\nRequire Import MathClasses.interfaces.canonical_names.\n\nFrom Flocq Require Import Binary Bits PrimFloat Generic_fmt FLT Raux.\nFrom Gappa Require Import Gappa_tactic.\n\nOpen Scope R_scope.\n\nSection Constants.\n\n  (* 0.0 *)\n  Definition b64_0 := B754_zero 53 1024 false.\n  (* 0.1 *)\n  Definition b64_0_1 :=\n    B754_finite 53 1024 false 7205759403792794 (-56)\n      (binary_float_of_bits_aux_correct 52 11 eq_refl eq_refl eq_refl\n         4591870180066957722).\n  (* 0.01 *)\n  Definition b64_0_01 :=\n    B754_finite 53 1024 false 5764607523034235 (-59)\n      (binary_float_of_bits_aux_correct 52 11 eq_refl eq_refl eq_refl\n         4576918229304087675).\n  (* 1.0 *)\n  Definition b64_1 :=\n    B754_finite 53 1024 false 4503599627370496 (-52)\n      (binary_float_of_bits_aux_correct 52 11 eq_refl eq_refl eq_refl\n         4607182418800017408).\n  (* 2.0 *)\n  Definition b64_2 :=\n    B754_finite 53 1024 false 4503599627370496 (-51)\n      (binary_float_of_bits_aux_correct 52 11 eq_refl eq_refl eq_refl\n         4611686018427387904).\n  (* 5.0 *)\n  Definition b64_5 :=\n    B754_finite 53 1024 false 5629499534213120 (-50)\n      (binary_float_of_bits_aux_correct 52 11 eq_refl eq_refl eq_refl\n         4617315517961601024).\n  (* 6.0 *)\n  Definition b64_6 :=\n    B754_finite 53 1024 false 6755399441055744 (-50)\n      (binary_float_of_bits_aux_correct 52 11 eq_refl eq_refl eq_refl\n         4618441417868443648).\n  (* 20.0 *)\n  Definition b64_20 :=\n    B754_finite 53 1024 false 5629499534213120 (-48)\n      (binary_float_of_bits_aux_correct 52 11 eq_refl eq_refl eq_refl\n         4626322717216342016).\n  (* 5000.0 *)\n  Definition b64_5000 :=\n    B754_finite 53 1024 false 5497558138880000 (-40)\n      (binary_float_of_bits_aux_correct 52 11 eq_refl eq_refl eq_refl\n         4662219572839972864).\n\n  (* CARE: this is not whant's commonly referred to as \"machine epsilon\". *)\n  Definition float64_subnormal_eps :=\n    B754_finite 53 1024 false 1 (-1074)\n      (binary_float_of_bits_aux_correct 52 11 eq_refl eq_refl eq_refl 1).\n\nEnd Constants.\n\nGlobal Hint Unfold\n  b64_0 b64_0_1 b64_0_01 b64_1 b64_2 b64_5 b64_6 b64_20 b64_5000\n  : F64_const.\n\nNotation B64R := (B2R 53 1024).\n\nSection Float64.\n\n  Let prec := 53%Z.\n  Let emax := 1024%Z.\n  Let fexp := (FLT_exp (3 - emax - prec)%Z prec).\n\n  Variable m : mode.\n\n  Definition no_overflow64 (rf : R) :=\n    Rabs rf < bpow radix2 emax.\n  \n  Definition round64 : R -> R :=\n    Generic_fmt.round radix2 fexp (round_mode m).\n\n  Local Hint Unfold no_overflow64 round64 : sugar64.\n\n  Definition Float64Min (a b: binary64) :=\n    match a, b with\n    | B754_nan _ _ _ _ _, _ | _, B754_nan _ _ _ _ _\n           => build_nan _ _ (binop_nan_pl64 a b)\n    | _, _ =>\n        match Bcompare _ _ a b with\n        | Some Datatypes.Lt => a\n        | _ => b\n        end\n    end.\n  \n  Definition Float64Max (a b: binary64): binary64 :=\n    match a, b with\n    | B754_nan _ _ _ _ _, _ | _, B754_nan _ _ _ _ _\n           => build_nan _ _ (binop_nan_pl64 a b)\n    | _, _ =>\n        match Bcompare _ _ a b with\n        | Some Datatypes.Lt => b\n        | _ => a\n        end\n    end.\n\n  Definition le64 (a b : binary64) : Prop :=\n    b64_compare a b ≡ Some Datatypes.Eq\n    \\/ b64_compare a b ≡ Some Datatypes.Lt.\n\n  Definition lt64 (a b : binary64) : Prop :=\n    b64_compare a b ≡ Some Datatypes.Lt.\n\n  Definition safe_lt64 (eps : binary64) (a b : binary64) : Prop :=\n    lt64 eps (b64_minus m b a).\n\n  (* inclusive range check *)\n  Definition in_range_64 : (binary64 * binary64) -> binary64 -> Prop\n    := fun '(a,b) x => is_finite _ _ x ≡ true /\\ le64 a x /\\ le64 x b.\n\n  (* left excluded, right included range check *)\n  Definition in_range_64_l : (binary64 * binary64) -> binary64 -> Prop\n    := fun '(a,b) x => is_finite _ _ x ≡ true /\\ lt64 a x /\\ le64 x b.\n\n  Lemma in_range_finite (lo hi x : binary64) :\n    in_range_64 (lo, hi) x ->\n    is_finite _ _ x ≡ true.\n  Proof.\n    unfold in_range_64.\n    tauto.\n  Qed.\n\n  Lemma in_range_l_finite (lo hi x : binary64) :\n    in_range_64_l (lo, hi) x ->\n    is_finite _ _ x ≡ true.\n  Proof.\n    unfold in_range_64_l.\n    tauto.\n  Qed.\n\n  (*\n     A common goal is to prove that a real fits in a float range\n     (i.e. [r < 2^emax]). Gappa can't handle goals with [lt].\n     Shrink the range (generously) and move to [le].\n   *)\n  Lemma bpow_lt_to_le (r : R) (p : Z) :\n    r <= bpow radix2 (p - 1) ->\n    r < bpow radix2 p.\n  Proof.\n    enough (bpow radix2 (p - 1) < bpow radix2 p)\n      by lra.\n    clear r.\n    apply bpow_lt.\n    lia.\n  Qed.\n\n  Lemma le64_correct (a b : binary64) :\n    is_finite _ _ a ≡ true ->\n    is_finite _ _ b ≡ true ->\n    le64 a b -> B64R a <= B64R b.\n  Proof.\n    intros FA FB LE64.\n    unfold le64, b64_compare in *.\n    destruct LE64 as [EQ64 | LT64].\n    -\n      rewrite Bcompare_correct in EQ64 by assumption.\n      inversion EQ64.\n      apply Rcompare_Eq_inv in H0.\n      lra.\n    -\n      rewrite Bcompare_correct in LT64 by assumption.\n      inversion LT64.\n      apply Rcompare_Lt_inv in H0.\n      lra.\n  Qed.\n\n  Lemma lt64_correct (a b : binary64) :\n    is_finite _ _ a ≡ true ->\n    is_finite _ _ b ≡ true ->\n    lt64 a b -> B64R a < B64R b.\n  Proof.\n    intros FA FB LT64.\n    unfold lt64, b64_compare in *.\n    rewrite Bcompare_correct in LT64 by assumption.\n    inversion LT64.\n    apply Rcompare_Lt_inv in H0.\n    lra.\n  Qed.\n\n  Lemma in_range_64_to_R (lo hi x : binary64) :\n    is_finite _ _ lo ≡ true ->\n    is_finite _ _ hi ≡ true ->\n    in_range_64 (lo, hi) x ->\n    B64R lo <= B64R x <= B64R hi.\n  Proof.\n    intros FLO FHI INRG.\n    unfold in_range_64 in INRG.\n    destruct INRG as (F & LO & HI).\n    split; now apply le64_correct.\n  Qed.\n\n  Lemma in_range_64_l_to_R (lo hi x : binary64) :\n    is_finite _ _ lo ≡ true ->\n    is_finite _ _ hi ≡ true ->\n    in_range_64_l (lo, hi) x ->\n    B64R lo < B64R x <= B64R hi.\n  Proof.\n    intros FLO FHI INRG.\n    unfold in_range_64_l in INRG.\n    destruct INRG as (F & LO & HI).\n    split.\n    now apply lt64_correct.\n    now apply le64_correct.\n  Qed.\n\n  (* Corollary of Bminus_correct *)\n  Lemma b64_minus_to_R (x y : binary64) :\n    is_finite _ _ x ≡ true ->\n    is_finite _ _ y ≡ true ->\n    no_overflow64 (round64 (B64R x - B64R y)) ->\n    B64R (b64_minus m x y) ≡ round64 (B64R x - B64R y).\n  Proof.\n    intros *.\n    intros FX FY B.\n    pose proof\n      Bminus_correct prec emax eq_refl eq_refl binop_nan_pl64 m x y FX FY\n      as COR.\n    autounfold with sugar64 in *.\n    subst prec emax fexp.\n    apply Rlt_bool_true in B.\n    rewrite B in COR.\n    tauto.\n  Qed.\n\n  Lemma b64_minus_finite (x y : binary64) :\n    is_finite _ _ x ≡ true ->\n    is_finite _ _ y ≡ true ->\n    no_overflow64 (round64 (B64R x - B64R y)) ->\n    is_finite _ _ (b64_minus m x y) ≡ true.\n  Proof.\n    intros *.\n    intros FX FY B.\n    pose proof\n      Bminus_correct prec emax eq_refl eq_refl binop_nan_pl64 m x y FX FY\n      as COR.\n    autounfold with sugar64 in *.\n    subst prec emax fexp.\n    apply Rlt_bool_true in B.\n    rewrite B in COR.\n    tauto.\n  Qed.\n\n  (* Corollary of Bmult_correct *)\n  Lemma b64_mult_to_R (x y : binary64) :\n    no_overflow64 (round64 (B64R x * B64R y)) ->\n    B64R (b64_mult m x y) ≡ round64 (B64R x * B64R y).\n  Proof.\n    intros * B.\n    pose proof\n      Bmult_correct prec emax eq_refl eq_refl binop_nan_pl64 m x y\n      as COR.\n    autounfold with sugar64 in *.\n    subst prec emax fexp.\n    apply Rlt_bool_true in B.\n    rewrite B in COR.\n    tauto.\n  Qed.\n\n  Lemma b64_mult_finite (x y : binary64) :\n    no_overflow64 (round64 (B64R x * B64R y)) ->\n    is_finite _ _ x ≡ true ->\n    is_finite _ _ y ≡ true ->\n    is_finite _ _ (b64_mult m x y) ≡ true.\n  Proof.\n    intros * B FX FY.\n    pose proof\n      Bmult_correct prec emax eq_refl eq_refl binop_nan_pl64 m x y\n      as COR.\n    autounfold with sugar64 in *.\n    subst prec emax fexp.\n    apply Rlt_bool_true in B.\n    rewrite B in COR.\n    destruct COR as (_ & F & _).\n    unfold b64_mult.\n    rewrite F, FX, FY.\n    reflexivity.\n  Qed.\n\n  (* Corollary of Bplus_correct *)\n  Lemma b64_plus_to_R (x y : binary64) :\n    is_finite _ _ x ≡ true ->\n    is_finite _ _ y ≡ true ->\n    no_overflow64 (round64 (B64R x + B64R y)) ->\n    B64R (b64_plus m x y) ≡ round64 (B64R x + B64R y).\n  Proof.\n    intros * XF YF B.\n    pose proof\n      Bplus_correct prec emax eq_refl eq_refl binop_nan_pl64 m x y\n      as COR.\n    autounfold with sugar64 in *.\n    subst prec emax fexp.\n    apply Rlt_bool_true in B.\n    rewrite B in COR.\n    tauto.\n  Qed.\n\n  Lemma b64_plus_finite (x y : binary64) :\n    is_finite _ _ x ≡ true ->\n    is_finite _ _ y ≡ true ->\n    no_overflow64 (round64 (B64R x + B64R y)) ->\n    is_finite _ _ (b64_plus m x y) ≡ true.\n  Proof.\n    intros *.\n    intros FX FY B.\n    pose proof\n      Bplus_correct prec emax eq_refl eq_refl binop_nan_pl64 m x y FX FY\n      as COR.\n    autounfold with sugar64 in *.\n    subst prec emax fexp.\n    apply Rlt_bool_true in B.\n    rewrite B in COR.\n    tauto.\n  Qed.\n\n  (* Corollary of Bplus_correct *)\n  Lemma b64_div_to_R (x y : binary64) :\n    is_finite _ _ x ≡ true ->\n    is_finite _ _ y ≡ true ->\n    B64R y <> 0 ->\n    no_overflow64 (round64 (B64R x / B64R y)) ->\n    B64R (b64_div m x y) ≡ round64 (B64R x / B64R y).\n  Proof.\n    intros * XF YF YO B.\n    pose proof\n      Bdiv_correct prec emax eq_refl eq_refl binop_nan_pl64 m x y\n      as COR.\n    autounfold with sugar64 in *.\n    subst prec emax fexp.\n    apply Rlt_bool_true in B.\n    rewrite B in COR.\n    tauto.\n  Qed.\n\n  Lemma b64_div_finite (x y : binary64) :\n    is_finite _ _ x ≡ true ->\n    is_finite _ _ y ≡ true ->\n    B64R y <> 0 ->\n    no_overflow64 (round64 (B64R x / B64R y)) ->\n    is_finite _ _ (b64_div m x y) ≡ true.\n  Proof.\n    intros *.\n    intros FX FY YO B.\n    pose proof\n      Bdiv_correct prec emax eq_refl eq_refl binop_nan_pl64 m x y YO\n      as COR.\n    autounfold with sugar64 in *.\n    subst prec emax fexp.\n    apply Rlt_bool_true in B.\n    rewrite B in COR.\n    destruct COR as [_ [FIN _]].\n    unfold b64_div.\n    congruence.\n  Qed.\n\n  Lemma b64_max_to_R (x y : binary64) :\n    is_finite _ _ x ≡ true ->\n    is_finite _ _ y ≡ true ->\n    B64R (Float64Max x y) ≡ Rmax (B64R x) (B64R y).\n  Proof.\n    intros FX FY.\n    unfold Float64Max.\n    pose proof Rcompare_spec (B64R x) (B64R y) as RC.\n    rewrite Bcompare_correct by assumption.\n    destruct x, y;\n      invc FX; invc FY.\n    all: repeat\n           match goal with\n           | |- context [Rmax (B64R ?x) (B64R ?y)] =>\n               generalize dependent x;\n               generalize dependent y\n           end;\n      intros.\n    all: unfold Rmax.\n    all: repeat break_match.\n    all: invc RC.\n    all: lra.\n  Qed.\n  \n  Lemma b64_max_finite (x y : binary64) :\n    is_finite _ _ x ≡ true ->\n    is_finite _ _ y ≡ true ->\n    is_finite _ _ (Float64Max x y) ≡ true.\n  Proof.\n    intros FX FY.\n    unfold Float64Max.\n    destruct x, y;\n      invc FX; invc FY.\n    all: repeat break_match; reflexivity.\n  Qed.\n\n  Lemma b64_abs_to_R (f : binary64) :\n    B64R (b64_abs f) ≡ Rabs (B64R f).\n  Proof.\n    apply B2R_Babs.\n  Qed.\n  \n  Lemma b64_abs_finite (f : binary64) :\n    is_finite _ _ f ≡ true ->\n    is_finite _ _ (b64_abs f) ≡ true.\n  Proof.\n    intros.\n    unfold b64_abs.\n    now rewrite is_finite_Babs.\n  Qed.\n\n  Lemma float64_subnormal_eps_correct (x : binary64) :\n    is_finite _ _ x ≡ true ->\n    lt64 b64_0 x ->\n    le64 float64_subnormal_eps x.\n  Proof.\n    intros F NZ.\n    destruct x; invc F; invc NZ.\n    break_if; invc H0.\n    unfold le64, b64_compare.\n    rewrite !Bcompare_correct in *; try reflexivity.\n    pose proof e0 as B.\n    eapply bounded_ge_emin in B; [| reflexivity].\n    unfold B64R.\n    cbn.\n    assert (MIN : bpow radix2 (3 - 1024 - 53)\n            ≡ @Defs.F2R radix2 {| Defs.Fnum := 1; Defs.Fexp := -1074 |})\n      by (cbv; lra).\n    rewrite MIN in *; clear MIN.\n    generalize dependent\n      (@Defs.F2R radix2 {| Defs.Fnum := 1; Defs.Fexp := -1074 |}).\n    intros.\n    destruct B; [right | left].\n    now rewrite Rcompare_Lt.\n    now rewrite Rcompare_Eq.\n  Qed.\n\n  Fact b64_0_correct : B64R b64_0 ≡ 0.\n  Proof. reflexivity. Qed.\n  \n  Fact b64_1_correct : B64R b64_1 ≡ 1.\n  Proof. cbv. lra. Qed.\n\nEnd Float64.\n\nGlobal Hint Unfold no_overflow64 round64 : sugar64.\n\nSection Raux.\n  \n  Lemma Rabs_no_error (eps x y : R) :\n    - eps <= x - y <= eps ->\n    - eps <= Rabs x - Rabs y <= eps.\n  Proof.\n    intros D.\n    unfold Rabs.\n    repeat break_if; lra.\n  Qed.\n\n  Lemma Rmax_no_error (eps1 x1 y1 eps2 x2 y2 : R) :\n    - eps1 <= x1 - y1 <= eps1 ->\n    - eps2 <= x2 - y2 <= eps2 ->\n    - Rmax eps1 eps2 <= Rmax x1 x2 - Rmax y1 y2 <= Rmax eps1 eps2.\n  Proof.\n    intros D.\n    unfold Rmax.\n    repeat break_if; lra.\n  Qed.\n\nEnd Raux.\n", "meta": {"author": "vzaliva", "repo": "helix", "sha": "5d0a71df99722d2011c36156f12b04875df7e1cb", "save_path": "github-repos/coq/vzaliva-helix", "path": "github-repos/coq/vzaliva-helix/helix-5d0a71df99722d2011c36156f12b04875df7e1cb/coq/Util/FloatUtil.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.28908008941461566}}
{"text": "(* M.t utilities. Part of the CertiCoq project.\n * Author: Anonymized, 2016\n *)\n\nFrom Coq Require Import NArith.BinNat Relations.Relations MSets.MSets\n         MSets.MSetRBT Lists.List micromega.Lia Sets.Ensembles Relations.Relations\n         Classes.Morphisms.\nFrom CertiCoq.LambdaANF Require Import Ensembles_util set_util functions List_util.\nFrom compcert.lib Require Import Coqlib Maps.\nRequire Import Libraries.maps_util LambdaANF.tactics.\n\nModule M := Maps.PTree. \n\nOpen Scope Ensembles_scope.\n\nDefinition key_set {A : Type} (map : M.t A) :=\n  [ set x : positive | match M.get x map with\n                           | Some x => True\n                           | None => False\n                         end ]. \n  \nDefinition sub_map {A : Type} (map1 map2 : M.t A) :=\n  forall x v, M.get x map1 = Some v ->\n              M.get x map2 = Some v.\n\nDefinition filter_opt {A} (pred : positive -> A -> bool) (o : option A) (i : positive) : option A :=\n  match o with\n  | None => None \n  | Some a => if pred (M.prev i) a then o else None \n  end.\n\nDefinition xfilter {A : Type} (pred : positive -> A -> bool) (m : M.t A) : positive -> M.t A :=\n  M.tree_rec (fun _ => M.empty _)\n    (fun l lrec o r rrec i => \n      let o' := filter_opt pred o i in\n      M.Node (lrec (i~0)%positive) o' (rrec (i~1)%positive))\n    m.\n\nLemma xfilter_node {A} (pred : positive -> A -> bool) (l : M.t A) (o : option A) (r : M.t A) i :\n  M.not_trivially_empty l o r ->\n  xfilter pred (M.Node l o r) i = \n  M.Node (xfilter pred l (i~0)) (filter_opt pred o i) (xfilter pred r (i~1)).\nProof.\n  intros hl.\n  unfold xfilter at 1.\n  rewrite M.unroll_tree_rec; auto.\nQed.\n\nLemma xgfilter (A: Type) (pred : positive -> A -> bool) (m : M.t A) \n      (i j : positive) : \n  M.get i (xfilter pred m j) =\n  match M.get i m with\n  | Some x => if pred (M.prev (M.prev_append i j)) x then Some x else None\n  | None => None\n  end.\nProof.\n  revert i j. induction m using M.tree_ind; intros i j; simpl.\n  - rewrite !M.gempty. reflexivity.\n  - rewrite M.gNode, xfilter_node; auto.\n    destruct i; simpl.\n    + now rewrite <- IHm0, M.gNode. \n    + now rewrite <- IHm, M.gNode.\n    + rewrite M.gNode. destruct o; reflexivity.\nQed.\n\nDefinition filter  {A : Type} (pred : positive -> A -> bool) (m : M.t A) : M.t A :=\n  xfilter pred m 1.\n\nLemma gfilter (A: Type) (pred : positive -> A -> bool) (m : M.t A) \n      (i : positive) : \n  M.get i (filter pred m) =\n  match M.get i m with\n  | Some x => if pred i x then Some x else None\n  | None => None\n  end.\nProof.\n  unfold filter. rewrite xgfilter. simpl. \n  rewrite <- M.prev_append_prev. simpl. \n  rewrite Maps.PTree.prev_involutive. reflexivity. \nQed.\n\n\nInstance ToMSet_key_set {A} (rho : M.t A) : ToMSet (key_set rho).\nProof. \n  eexists (@mset (FromList (map fst (M.elements rho))) _).\n  rewrite <- mset_eq, FromList_map_image_FromList.\n  split; intros x Hin.\n  - unfold Ensembles.In, key_set in *.\n    destruct (M.get x rho) eqn:Hget. \n    eexists (x, a). split; eauto.\n    eapply M.elements_correct. eassumption. \n    exfalso; eauto.\n  - destruct Hin as [[z a] [Hin Hget]]; subst.\n    unfold Ensembles.In, FromList in Hin. eapply M.elements_complete in Hin.\n    simpl. unfold key_set, Ensembles.In. now rewrite Hin.\nQed. \n\nDefinition eq_env_P {A}:  Ensemble M.elt -> M.t A -> M.t A -> Prop :=\n  fun S rho1 rho2 =>\n    forall x, S x -> M.get x rho1 = M.get x rho2.\n\nLemma eq_env_P_refl: forall {A} S (r:M.t A), eq_env_P S r r.\nProof.\n  intros; intro; intros. reflexivity.\nQed.\n\nLemma eq_env_P_sym: forall {A} S (r:M.t A) r', eq_env_P S r r' -> eq_env_P S r' r.\nProof.\n  intros; intro. intro. apply H in H0. auto.\nQed.\n\nLemma eq_env_P_trans: forall {A} S (r1:M.t A) r2 r3,\n    eq_env_P S r1 r2 -> eq_env_P S r2 r3 -> eq_env_P S r1 r3.\nProof.\n  intros. intro. intros.\n  specialize (H x H1).\n  specialize (H0 x H1).\n  rewrite H. auto.\nQed.\n\nLemma eq_env_P_antimon {A} S S' (rho1 rho2 : M.t A) :\n  eq_env_P S rho1 rho2 ->\n  S' \\subset S ->\n  eq_env_P S' rho1 rho2.\nProof.\n  intros. intro; intros. eapply H. eapply H0; eauto.\nQed.\n\nLemma eq_env_P_set_not_in_P_l':\n  forall  {A} (x : M.elt) (v : A)\n          (P : Ensemble M.elt) (rho1 rho2 : M.t A),\n    eq_env_P P  (M.set x v rho1) rho2 ->\n    Disjoint M.elt P (Singleton M.elt x) ->\n    eq_env_P P  rho1 rho2.\nProof.\n  intros. intro; intros.\n  specialize (H x0 H1).\n  rewrite M.gso in H. auto.\n  intro.\n  inv H0.\n  specialize (H3 x).\n  apply H3; auto.\nQed.\n\nFixpoint get_list {A} (xs: list M.elt) (rho: M.t A) : option (list A) :=\n  match xs with\n  | x :: xs' => match M.get x rho, get_list xs' rho with\n               | Some v, Some vs => Some (v::vs)\n               | _, _ => None\n               end\n  | nil => Some nil\n  end.\n\nFixpoint set_lists {A} (xs: list M.elt) (vs: list A) (rho: M.t A) : option (M.t A) :=\n  match xs, vs with\n  | x::xs', v::vs' => match set_lists xs' vs' rho with\n                     | Some rho' => Some (M.set x v rho')\n                     | None => None\n                     end\n  | nil, nil => Some rho\n  | _, _ => None\n  end.\n\nDefinition set_list {A:Type}  (l : list (M.elt * A)) (map: M.t A) : M.t A :=\n  fold_right (fun xv cmap => M.set (fst xv) (snd xv) cmap ) map l.\n\n(** Lemmas about [get_list] *)\nLemma get_list_In {A} (rho : M.t A) ys x vs :\n  get_list ys rho = Some vs ->\n  List.In x ys ->\n  exists v, M.get x rho = Some v.\nProof.\n  revert x vs. induction ys; intros x vs Hget H. inv H.\n  inv H; simpl in Hget.\n  - destruct (M.get x rho) eqn:Heq; try discriminate; eauto.\n  - destruct (M.get a rho) eqn:Heq; try discriminate; eauto.\n    destruct (get_list ys rho) eqn:Heq'; try discriminate; eauto.\nQed.\n\nLemma In_get_list {A} (xs : list M.elt) (rho : M.t A) :\n  (forall x, List.In x xs -> exists v, M.get x rho = Some v) ->\n  exists vs, get_list xs rho = Some vs.\nProof.\n  intros H. induction xs.\n  - eexists; simpl; eauto.\n  - edestruct IHxs.\n    + intros x Hin. eapply H. now constructor 2.\n    + edestruct H. now constructor.\n      eexists. simpl. erewrite H1, H0.\n      reflexivity.\nQed.\n\nLemma get_list_nth_get {A} (xs : list M.elt) (vs : list A) rho (x : M.elt) N :\n  get_list xs rho = Some vs ->\n  nthN xs N = Some x ->\n  exists v, nthN vs N = Some v /\\ M.get x rho = Some v.\nProof.\n  revert vs N; induction xs; intros vs N Hget Hnth.\n  - inv Hnth.\n  - simpl in Hget.\n    destruct (M.get a rho) eqn:Hget'; try discriminate.\n    destruct (get_list xs rho) eqn:Hget_list'; try discriminate.\n    inv Hget. destruct N.\n    + inv Hnth. eexists; simpl; eauto.\n    + edestruct IHxs as [v' [Hnth1 Hget1]]; eauto.\nQed.\n\nLemma get_list_set_neq {A} xs x (v : A) rho :\n  ~ List.In x xs ->\n  get_list xs (M.set x v rho) = get_list xs rho.\nProof.\n  intros Hin.\n  revert rho. induction xs; intros rho.\n  - reflexivity.\n  - simpl. rewrite M.gso.\n    + rewrite IHxs. reflexivity.\n      intros Hin'. eapply Hin. now constructor 2.\n    + intros Heq; subst. eapply Hin. now constructor.\nQed.\n\nLemma get_list_set_lists {A} xs (vs : list A) rho rho' :\n  NoDup xs ->\n  set_lists xs vs rho = Some rho' ->\n  get_list xs rho' = Some vs.\nProof.\n  revert rho' vs; induction xs; intros rho' vs Hnd Hset.\n  - inv Hset. destruct vs; try discriminate. reflexivity.\n  - inv Hnd. simpl in *.\n    destruct vs; try discriminate.\n    destruct (set_lists xs vs rho) eqn:Hset'; try discriminate. inv Hset.\n    rewrite M.gss. rewrite get_list_set_neq.\n    now erewrite IHxs; eauto. eassumption.\nQed.\n\nLemma get_list_set_lists_Disjoint {A} xs xs' (vs : list A) rho rho' :\n  Disjoint _ (FromList xs) (FromList xs') ->\n  set_lists xs vs rho = Some rho' ->\n  get_list xs' rho' = get_list xs' rho.\nProof with now eauto with Ensembles_DB.\n  revert rho' vs; induction xs; intros rho' vs Hd Hset.\n  - inv Hset. destruct vs; try discriminate. inv H0; reflexivity.\n  - simpl in *.\n    destruct vs; try discriminate.\n    destruct (set_lists xs vs rho) eqn:Hset'; try discriminate. inv Hset.\n    rewrite FromList_cons in Hd.\n    rewrite get_list_set_neq.\n    erewrite IHxs...\n    intros Hc; eapply Hd. constructor; eauto.\nQed.\n\nLemma get_list_reset {A} σ x y (v : A) rho l :\n  M.get (σ x) rho = Some v ->\n  ~ y \\in (image σ (Setminus _ (FromList l) (Singleton _ x))) ->\n  get_list (map σ l) rho = get_list (map (σ { x ~> y }) l) (M.set y v rho).\nProof with now eauto with Ensembles_DB.\n  intros Hget Hnin. induction l; eauto.\n  simpl. destruct (peq x a); subst.\n  - rewrite extend_gss, M.gss, Hget.\n    rewrite IHl. reflexivity.\n    intros Hc. eapply Hnin.\n    rewrite FromList_cons.\n    eapply image_monotonic; try eassumption...\n  - rewrite extend_gso; eauto.\n    rewrite M.gso.\n    rewrite IHl. reflexivity.\n    intros Hc. eapply Hnin.\n    rewrite FromList_cons.\n    eapply image_monotonic; try eassumption...\n    intros Hc. eapply Hnin.\n    subst. rewrite FromList_cons. eexists; split; eauto.\n    constructor; eauto.\n    intros Hc; inv Hc. congruence.\nQed.\n\nLemma get_list_reset_neq {A} σ x y (v : A) rho l :\n  ~ y \\in (image σ (Setminus _ (FromList l) (Singleton _ x))) ->\n  ~ List.In x l ->\n  get_list (map σ l) rho = get_list (map (σ { x ~> y }) l) (M.set y v rho).\nProof with now eauto with Ensembles_DB.\n  intros  Hnin. induction l; intros Hnin'; eauto.\n  simpl. destruct (peq x a); subst.\n  - exfalso. eapply Hnin'. now constructor.\n  - rewrite extend_gso; eauto.\n    rewrite M.gso.\n    rewrite IHl. reflexivity.\n    intros Hc. eapply Hnin.\n    rewrite FromList_cons.\n    eapply image_monotonic; try eassumption...\n    intros Hc. eapply Hnin'. now constructor 2.\n    intros Hc. subst. eapply Hnin.\n    rewrite FromList_cons. eexists; split; eauto.\n    constructor; eauto.\n    intros Hc; inv Hc. congruence.\nQed.\n\nLemma get_eq_get_list_eq {A} (rho rho' : M.t A) xs :\n  (forall z, M.get z rho = M.get z rho') ->\n  get_list xs rho = get_list xs rho'.\nProof.\n  induction xs; intros H; eauto.\n  simpl; f_equal.\n  rewrite IHxs; eauto.\n  rewrite H. reflexivity.\nQed.\n\nLemma get_list_app {A} m l1 l2 (v1 v2 : list A) :\n  get_list l1 m = Some v1 ->\n  get_list l2 m = Some v2 ->\n  get_list (l1 ++ l2) m = Some (v1 ++ v2).\nProof.\n  revert v1. induction l1; intros v1 Hget1 Hget2; simpl in *.\n  - inv Hget1. eauto.\n  - destruct (M.get a m) eqn:Hgeta; try discriminate.\n    destruct (get_list l1 m) eqn:Hget; try discriminate.\n    inv Hget1. simpl. erewrite IHl1; eauto.\nQed.\n\nLemma get_list_length_eq {A} l (vs : list A) rho :\n  get_list l rho = Some vs ->\n  length l = length vs.\nProof.\n  revert vs; induction l; intros vs Hget.\n  - inv Hget. eauto.\n  - simpl in Hget. destruct (M.get a rho); try discriminate.\n    destruct (get_list l rho); try discriminate.\n    inv Hget. simpl. f_equal; eauto.\nQed.\n\nLemma app_get_list {A} l1 l2 (vs : list A) rho :\n  get_list (l1 ++ l2) rho = Some vs ->\n  exists vs1 vs2,\n    get_list l1 rho = Some vs1 /\\\n    get_list l2 rho = Some vs2 /\\\n    vs = vs1 ++ vs2.\nProof.\n  revert vs. induction l1; intros vs Hget.\n  - simpl in Hget. repeat eexists; eauto.\n  - simpl in Hget.\n    destruct (M.get a rho) eqn:Hgeta; try discriminate.\n    destruct (get_list (l1 ++ l2) rho) eqn:Hgetl; try discriminate.\n    inv Hget.\n    edestruct IHl1 as [vs1 [vs2 [Hget1 [Hget2 Heq]]]].\n    reflexivity.\n    repeat eexists; eauto. simpl.\n    rewrite Hgeta, Hget1. reflexivity.\n    simpl. congruence.\nQed.\n\nLemma get_list_In_val {A} (rho : M.t A) ys v vs :\n  get_list ys rho = Some vs ->\n  List.In v vs ->\n  exists x, List.In x ys /\\ M.get x rho = Some v.\nProof.\n  revert v vs. induction ys; intros x vs Hget H.\n  - inv Hget. now inv H.\n  - simpl in *.\n    destruct (M.get a rho) eqn:Heq; try discriminate; eauto.\n    destruct (get_list ys rho) eqn:Heq'; try discriminate; eauto.\n    inv Hget. inv H; eauto.\n    edestruct IHys as [y [Hin Hget]]; eauto.\nQed.\n\n\n(** Lemmas about [set_lists]  *)\n\nLemma set_lists_Forall2_get {A} (P : A -> A -> Prop)\n      xs vs1 vs2 rho1 rho2 rho1' rho2' x :\n  Forall2 P vs1 vs2 ->\n  set_lists xs vs1 rho1 = Some rho1' ->\n  set_lists xs vs2 rho2 = Some rho2' ->\n  List.In x xs ->\n  exists v1 v2,\n    M.get x rho1' = Some v1 /\\\n    M.get x rho2' = Some v2 /\\ P v1 v2.\nProof.\n  revert rho1' rho2' vs1 vs2.\n  induction xs; simpl; intros rho1' rho2' vs1 vs2 Hall Hset1 Hset2 Hin.\n  - inv Hin.\n  - destruct (Coqlib.peq a x); subst.\n    + destruct vs1; destruct vs2; try discriminate.\n      destruct (set_lists xs vs1 rho1) eqn:Heq1;\n        destruct (set_lists xs vs2 rho2) eqn:Heq2; try discriminate.\n      inv Hset1; inv Hset2. inv Hall.\n      repeat eexists; try rewrite M.gss; eauto.\n    + destruct vs1; destruct vs2; try discriminate.\n      destruct (set_lists xs vs1 rho1) eqn:Heq1;\n        destruct (set_lists xs vs2 rho2) eqn:Heq2; try discriminate.\n      inv Hset1; inv Hset2. inv Hall. inv Hin; try congruence.\n      edestruct IHxs as [v1 [v2 [Hget1 [Hget2 HP]]]]; eauto.\n      repeat eexists; eauto; rewrite M.gso; eauto.\nQed.\n\nLemma get_set_lists_In_xs {A} x xs vs rho rho' :\n  x \\in (FromList xs) ->\n  set_lists xs vs rho = Some rho' ->\n  exists v : A, M.get x rho' = Some v.\nProof.\n  revert rho rho' vs. induction xs; intros rho rho' vs Hin Hset.\n  - rewrite FromList_nil in Hin. exfalso.\n    eapply not_In_Empty_set. eassumption.\n  - rewrite FromList_cons in Hin.\n    destruct vs; try discriminate.\n    simpl in Hset. destruct (set_lists xs vs rho) eqn:Hset_lists; try discriminate.\n    inv Hset. inv Hin.\n    + inv H. eexists. rewrite M.gss. reflexivity.\n    + destruct (Coqlib.peq x a); subst.\n      * eexists. now rewrite M.gss.\n      * edestruct IHxs; eauto.\n        eexists. simpl. rewrite M.gso; eauto.\nQed.\n\nLemma set_lists_not_In {A} (xs : list M.elt) (vs : list A)\n      (rho rho' : M.t A) (x : M.elt) :\n  set_lists xs vs rho = Some rho' ->\n  ~ List.In x xs ->\n  M.get x rho = M.get x rho'.\nProof.\n  revert vs rho'.\n  induction xs; simpl; intros vs rho' Hset Hin.\n  - destruct vs; congruence.\n  - destruct vs; try discriminate.\n    destruct (set_lists xs vs rho) eqn:Heq1; try discriminate. inv Hset.\n    rewrite M.gso; eauto.\nQed.\n\nLemma set_lists_length {A} (rho rho' rho1 : M.t A)\n      (xs : list M.elt) (vs1 vs2 : list A) :\n  length vs1 = length vs2 ->\n  set_lists xs vs1 rho = Some rho1 ->\n  exists rho2, set_lists xs vs2 rho' = Some rho2.\nProof.\n  revert vs1 vs2 rho1.\n  induction xs as [| x xs IHxs ]; intros vs1 vs2 rho1 Hlen Hset.\n  - inv Hset. destruct vs1; try discriminate. inv H0.\n    destruct vs2; try discriminate. eexists; simpl; eauto.\n  - destruct vs1; try discriminate. destruct vs2; try discriminate.\n    inv Hlen. simpl in Hset.\n    destruct (set_lists xs vs1 rho) eqn:Heq2; try discriminate.\n    edestruct (IHxs _ _ _ H0 Heq2) as  [vs2' Hset2].\n    eexists. simpl; rewrite Hset2; eauto.\nQed.\n\nLemma set_permut {A} rho x y (v1 v2 : A) z :\n  x <> y ->\n  M.get z (M.set x v1 (M.set y v2 rho)) =\n  M.get z (M.set y v2 (M.set x v1 rho)).\nProof.\n  intros Hnin. destruct (peq z x); subst.\n  - rewrite M.gss, M.gso, M.gss; eauto.\n  - rewrite (@M.gso _ z x); eauto.\n    destruct (peq z y); subst.\n    + rewrite !M.gss; eauto.\n    + rewrite !M.gso; eauto.\nQed.\n\nLemma set_set_lists_permut {A} rho rho' y ys (v : A) vs :\n  set_lists ys vs rho = Some rho' ->\n  ~ List.In y ys ->\n  exists rho'',\n    set_lists ys vs (M.set y v rho) = Some rho'' /\\\n    (forall z, M.get z (M.set y v rho') = M.get z rho'').\nProof.\n  revert vs rho'.\n  induction ys; intros vs rho' Hset Hin;\n  destruct vs; try discriminate.\n  - inv Hset. eexists; split; simpl; eauto.\n  - simpl in Hset.\n    destruct (set_lists ys vs rho) eqn:Heq; try discriminate.\n    inv Hset. edestruct IHys as [rho'' [Hset Hget]]; eauto.\n    intros Hc; eapply Hin; now constructor 2.\n    eexists; split.\n    simpl. rewrite Hset. reflexivity.\n    intros z. rewrite set_permut.\n    destruct (peq z a); subst.\n    + rewrite !M.gss; eauto.\n    + rewrite !(@M.gso _ z a); eauto.\n    + intros Hc. eapply Hin.\n      constructor; eauto.\nQed.\n\nLemma set_lists_length3 {A} (rho : M.t A) xs vs :\n  length xs = length vs ->\n  exists rho', set_lists xs vs rho = Some rho'.\nProof.\n  revert vs; induction xs; intros vs Hlen; destruct vs; try discriminate.\n  - eexists; simpl; eauto.\n  - inv Hlen.\n    edestruct IHxs as [rho' Hset]. eassumption.\n    eexists. simpl. rewrite Hset. reflexivity.\nQed.\n\nLemma set_lists_app {A} xs1 xs2 (vs1 vs2 : list A) rho rho' :\n  set_lists (xs1 ++ xs2) (vs1 ++ vs2) rho = Some rho' ->\n  length xs1 = length vs1 ->\n  exists rho'',\n    set_lists xs2 vs2 rho = Some rho'' /\\\n    set_lists xs1 vs1 rho'' = Some rho'.\nProof.\n  revert vs1 rho'. induction xs1; intros vs1 rho' Hset Hlen.\n  - destruct vs1; try discriminate.\n    eexists; split; eauto.\n  - destruct vs1; try discriminate.\n    inv Hlen. simpl in Hset.\n    destruct (set_lists (xs1 ++ xs2) (vs1 ++ vs2) rho) eqn:Heq; try discriminate.\n    inv Hset. edestruct IHxs1 as [rho'' [Hset1 Hset2]].\n    eassumption. eassumption.\n    eexists. split. eassumption. simpl; rewrite Hset2; reflexivity.\nQed.\n\n\nLemma set_lists_length_eq {A} rho rho' xs (vs : list A) :\n  set_lists xs vs rho = Some rho' ->\n  length xs = length vs.\nProof.\n  revert rho' vs; induction xs; intros rho' vs Hset.\n  - destruct vs; try discriminate. reflexivity.\n  - destruct vs; try discriminate.\n    simpl in Hset.\n    destruct (set_lists xs vs rho) eqn:Heq; try discriminate.\n    simpl. f_equal. inv Hset. eauto.\nQed.\n\nLemma get_list_reset_lst {A} σ xs ys (vs : list A) rho rho' l  :\n  set_lists ys vs rho = Some rho' ->\n  get_list (map σ xs) rho = Some vs ->\n  Disjoint _ (image σ (FromList l)) (FromList ys) ->\n  length xs = length ys ->\n  NoDup xs -> NoDup ys ->\n  get_list (map σ l) rho = get_list (map (σ <{ xs ~> ys }>) l) rho'.\nProof with now eauto with Ensembles_DB.\n  revert σ ys vs rho' rho. induction xs as [| x xs IHxs ];\n    intros σ ys vs rho' rho Hset Hget HD Hlen Hnd1 Hnd2.\n  - destruct ys; try discriminate.\n    inv Hget. inv Hset. reflexivity.\n  - destruct ys; try discriminate. simpl in *.\n    inv Hlen. destruct vs as [| v vs]; try discriminate.\n    destruct (set_lists ys vs rho) eqn:Hset'; try discriminate.\n    destruct (M.get (σ x) rho) eqn:Hget'; try discriminate.\n    destruct (get_list (map σ xs) rho) eqn:Hgetl; try discriminate.\n    inv Hget. inv Hset. inv Hnd1. inv Hnd2. rewrite !FromList_cons in HD.\n    assert (H : get_list (map ((σ <{ xs ~> ys }>) {x ~> e}) l) (M.set e v t) =\n                get_list (map ((σ <{ xs ~> ys }>)) l) t).\n    { destruct (in_dec peq x l).\n      - rewrite <- get_list_reset; try reflexivity.\n        rewrite extend_lst_gso; eauto.\n        erewrite <- set_lists_not_In. eassumption. eassumption.\n        intros Hc. eapply HD. constructor; eauto.\n        eexists; split; eauto.\n        intros Hc.\n        apply image_extend_lst_Included in Hc; eauto.\n        inv Hc; eauto. eapply HD. constructor; eauto.\n        eapply image_monotonic; [| eassumption ]...\n      - rewrite map_extend_not_In; eauto.\n        erewrite get_list_set_neq. reflexivity.\n        intros Hc. eapply in_map_iff in Hc.\n        destruct Hc as [x' [Heq Hin]].\n        destruct (in_dec peq x' xs).\n        + edestruct (extend_lst_gss σ) as [y' [Hin' Heq']]; eauto.\n          rewrite Heq in Hin'. subst.\n          subst. eauto.\n        + rewrite extend_lst_gso in Heq; eauto.\n          eapply HD. constructor; eauto.\n          eexists; eauto. }\n    rewrite H.\n    erewrite <- IHxs; eauto.\n    now eauto with Ensembles_DB.\nQed.\n\n\nLemma proper_get_list: forall A rho rho',\n    map_get_r A rho rho' ->\n    forall vs, get_list vs rho = get_list vs rho'.\nProof.\n  intros A rho rho' Hp.\n  induction vs; auto.\n  simpl. rewrite IHvs. rewrite Hp. reflexivity.\nQed.\n\n\nLemma eq_env_P_set_not_in_P_l (A : Type) (x : map_util.M.elt) (v : A)\n      (P : Ensemble map_util.M.elt) (rho1 rho2 : map_util.M.t A) : \n  eq_env_P P rho1 rho2 ->\n  ~ x \\in P ->\n          eq_env_P P (map_util.M.set x v rho1) rho2.\nProof.\n  intros Heq Hnin z Hin.\n  rewrite M.gso; eauto.\n  intros Hc; subst; contradiction. \nQed.\n\n\n(* [Dom_map] and [Range_map] *)\n\nDefinition Range_map {A:Type} sig:  Ensemble A:=\n  (fun x => exists y, M.get y sig = Some x).\n\nDefinition Dom_map {A:Type} sig : Ensemble (M.elt):=\n  (fun x => exists (y:A), M.get x sig = Some y).\n\nLemma Dom_map_remove {A:Type} sigma v :\n  (Dom_map (@M.remove A v sigma)) <--> (Dom_map sigma \\\\ [set v]).\nProof.\n  split; intros; intro; intros.\n  inv H.\n  split.\n  exists x0.\n  eapply gr_some.\n  apply H0.\n  intro. inv H.\n  rewrite M.grs in H0; auto. inv H0.\n  inv H.\n  inv H0.\n  exists x0.\n  rewrite M.gro; auto.\n  intro; apply H1. subst.\n  constructor.\nQed.\n\nLemma Dom_map_empty {A}:\n  (Dom_map (M.empty A)) <--> (Empty_set _).\nProof.\n  split; intro. intro. inv H. rewrite M.gempty in H0. inv H0.\n  intro. inv H.\nQed.\n\nLemma Dom_map_set A (sig: M.t A) x y :\n    (Dom_map (M.set x y sig)) <--> (x |: Dom_map sig).\nProof.\n  intros. split. intro. intro. inv H. destruct (peq x0 x).\n  subst; auto.\n  rewrite M.gso in H0 by auto.\n  right. exists x1; auto.\n  intro. intro. inv H. exists y. inv H0. rewrite M.gss.\n  auto.\n  destruct (peq x x0). subst. exists y.\n  rewrite M.gss. auto.\n  inv H0. exists x1. rewrite M.gso; auto.\nQed.\n\nLemma Dom_map_set_list {A} (sig: M.t A) lx ly :\n  List.length lx = List.length ly ->\n  (Dom_map (set_list (combine lx ly) sig)) <--> (FromList lx :|: Dom_map sig).\nProof.\n  revert ly; induction lx; intros ly.\n  - intros. destruct ly.\n    simpl. rewrite FromList_nil. auto with Ensembles_DB.\n    inv H.\n  - intros. destruct ly; inv H.\n    simpl. rewrite FromList_cons.\n    rewrite Dom_map_set.\n    apply IHlx in H1. rewrite H1. auto 25 with Ensembles_DB.\nQed.\n\nLemma Dom_map_set_lists {A} xs (vs : list A) rho rho' :\n  set_lists xs vs rho = Some rho' ->\n  Dom_map rho' <--> FromList xs :|: Dom_map rho.\nProof.\n  revert vs rho'. induction xs; intros vs rho' Hset.\n  - destruct vs; inv Hset. repeat normalize_sets. reflexivity.\n  - destruct vs; try now inv Hset.\n    simpl in Hset. destruct (set_lists xs vs rho) eqn:Hset1; inv Hset.\n    repeat normalize_sets. rewrite Dom_map_set. rewrite IHxs. now sets.\n    eassumption.\nQed.\n\nLemma Range_map_remove {A:Type} sigma v :\n  Range_map (@M.remove A v sigma) \\subset Range_map sigma.\nProof.\n  intros. intro. intros. inv H.\n  exists x0.\n  eapply gr_some.\n  apply H0.\nQed.\n\nLemma not_Range_map_eq {A} sig (x:A) :\n  ~ Range_map sig x ->\n  ~ (exists z, M.get z sig = Some x).\nProof.\n  intros. intro. apply H. inv H0. exists x0; auto.\nQed.\n\nLemma not_Dom_map_eq {A} (sig:M.t A) x :\n    ~ Dom_map sig x ->\n    M.get x sig = None.\nProof.\n  intro. intros.\n  destruct (M.get x sig) eqn:gxs.\n  exfalso; apply H. exists a; auto.\n  auto.\nQed.\n\nHint Resolve not_Range_map_eq not_Dom_map_eq : core.\n\nLemma Range_map_set_list {A} xs (vs : list A) :\n    Range_map (set_list (combine xs vs) (M.empty _)) \\subset FromList vs.\nProof.\n  revert vs; induction xs; intros.\n  - simpl. intro.\n    intro. inv H. rewrite M.gempty in H0. inv H0.\n  - simpl. specialize IHxs. destruct vs. simpl.\n    intro; intro; inv H. rewrite M.gempty in H0. inv H0.\n    simpl.\n    rewrite FromList_cons.\n    intro. intro.\n    inv H. destruct (peq x0 a).\n    subst.\n    rewrite M.gss in H0.\n    left. inv H0.\n    constructor.\n    right.\n    apply IHxs.\n    rewrite M.gso in H0 by auto.\n    exists x0. auto.\nQed.\n\nInstance Decidable_Dom_map {A} (m : M.t A) : Decidable (Dom_map m).\nProof.\n  constructor. intros x.\n  destruct (M.get x m) eqn:Heq; eauto.\n  left. eexists. eassumption.\n  right. intros [y Hget]. congruence.\nQed.\n\n(* TODO move *)\nLemma InList_snd:\n  forall {A B} (x:A) (l:list (B*A)),\n    List.In x (map snd l) <-> exists v, List.In (v, x) l.\nProof.\n  induction l; intros.\n  - split; intro H; inv H.\n    inv H0.\n  - split.\n    + intro. destruct a.\n      simpl in H. inv H.\n      exists b; constructor; auto.\n      apply IHl in H0. inv H0. exists x0.\n      constructor 2. auto.\n    + intro. inv H.\n      destruct a. simpl.\n      inv H0.\n      inv H; auto.\n      right.\n      apply IHl; eauto.\nQed.\n\nLemma Decidable_Range_map :\n  forall sig, @Decidable positive (Range_map sig).\nProof.\n  intros. constructor.\n  intro.\n  assert (Decidable (FromList (map snd (M.elements sig)))).\n  apply Decidable_FromList.\n  inv H.\n  specialize (Dec x).\n  inv Dec.\n  unfold FromList in H.\n  left. rewrite InList_snd in H.\n  destruct H.\n  apply M.elements_complete in H.\n  exists x0; auto.\n  right. intro. inv H0.\n  apply H.\n  apply InList_snd.\n  exists x0. apply M.elements_correct. auto.\nQed.\n\nLemma Range_set_Included {A} (sig : M.t A) a b :\n  ~ a \\in Dom_map sig ->\n          Range_map sig \\subset Range_map (M.set a b sig).\nProof.\n  intros Hc x [y Hget]. exists y. rewrite M.gso. eassumption.\n  intros Hc'; subst. eapply Hc; eexists; eauto.\nQed.\n\nLemma Range_set_list_Included {A} (sig : M.t A) l1 l2 :\n  Disjoint _ (FromList l1) (Dom_map sig) ->\n  NoDup l1 ->\n  length l1 = length l2 ->\n  Range_map sig \\subset Range_map (set_list (combine l1 l2) sig).\nProof.\n  revert l2; induction l1; intros; simpl. reflexivity.\n  destruct l2; simpl. now sets. normalize_sets.\n  eapply Included_trans; [| eapply Range_set_Included; sets ]. simpl.\n  eapply IHl1. now sets. inv H0; eassumption.\n  inv H1. reflexivity. inv H1. inv H0. rewrite (Dom_map_set_list sig l1 l2); eauto.\n  intros Hc; inv Hc; eauto. eapply H. constructor; eauto.\nQed.    \n\nLemma range_map_set_list {A} (ly : list A) sig lx :\n  Range_map (set_list (combine lx ly) sig) \\subset (Range_map sig :|: FromList ly).\nProof.\n  revert lx; induction ly.\n  - intros. intro. intro. destruct lx; simpl in H; auto.\n  - intros. destruct lx. simpl. auto with Ensembles_DB.\n    simpl. intro. intro.\n    inv H. destruct (peq x0 e).\n    + subst. rewrite M.gss in H0. inv H0. right; constructor; auto.\n    + rewrite M.gso in H0 by auto.\n      assert ( Range_map (set_list (combine lx ly) sig) x). exists x0; auto.\n      apply IHly in H.\n      inv H; auto. right. constructor 2; auto.\nQed.\n\n\n(* [sub_map] lemmas *) \n\nLemma sub_map_set {A} rho x (v : A) :\n  ~ x \\in Dom_map rho ->\n          sub_map rho (M.set x v rho).\nProof.\n  intros Hnin z1 v1 Hget1. rewrite M.gso; eauto.\n  intros hc. subst. eapply Hnin. eexists; eauto.\nQed.\n\nLemma sub_map_trans {A} (rho1 rho2 rho3 : M.t A) :\n  sub_map rho1 rho2 ->\n  sub_map rho2 rho3 ->\n  sub_map rho1 rho3.\nProof.\n  intros H1 H2 x v Hget. eauto.\nQed.\n\nLemma sub_map_refl {A} (rho : M.t A) :\n  sub_map rho rho.\nProof.\n  intro; intros; eauto.\nQed.\n\n\nLemma sub_map_set_lists {A} rho rho' xs (vs : list A) :\n  set_lists xs vs rho = Some rho' ->\n  NoDup xs ->\n  Disjoint _ (FromList xs) (Dom_map rho) ->\n  sub_map rho rho'.\nProof.\n  revert rho rho' vs; induction xs; intros rho rho' vs Hset; destruct vs; try now inv Hset.\n  simpl in Hset. destruct (set_lists xs vs rho) eqn:Hset'; inv Hset.\n  intros Hnd Hdis. inv Hnd. repeat normalize_sets. eapply sub_map_trans. eapply IHxs. eassumption. eassumption.\n  now sets. eapply sub_map_set. intros Hc. eapply Hdis. constructor. now left.\n  eapply Dom_map_set_lists in Hc; eauto. inv Hc; eauto. exfalso. contradiction.\nQed.\n\nLemma eq_env_P_sub_map {A} (rho1 rho2 : M.t A) x:\n  eq_env_P (Complement _ [set x]) rho1 rho2 ->\n  ~ x \\in Dom_map rho1 ->\n          sub_map rho1 rho2.\nProof.\n  intros Henv Hnin z v Hget.\n  rewrite <- Henv. eassumption. intros Hc. inv Hc.\n  eapply Hnin. eexists; eauto.\nQed.\n\nLemma eq_env_P_set_lists_not_in_P_l  (A : Type) (xs : list positive) (vs : list A)\n      (P : Ensemble map_util.M.elt) (rho1 rho1' rho2 : map_util.M.t A) :\n  eq_env_P P rho1 rho2 ->    \n  Disjoint _ P (FromList xs) ->\n  set_lists xs vs rho1 = Some rho1' -> \n  eq_env_P P rho1' rho2.\nProof.\n  intros Heq Hdis Hset x Hin.\n  destruct (Decidable_FromList xs). destruct (Dec x).\n  - exfalso. eapply Hdis. constructor; eauto.\n  - erewrite <- set_lists_not_In; [| eassumption | eassumption ]. eauto.\nQed.\n\n\nLemma Dom_map_sub_map {A : Type} (rho1 rho2 : M.t A) :\n  sub_map rho1 rho2 ->\n  Dom_map rho1 \\subset Dom_map rho2.\nProof.\n  intros H1 x [y Hin]. eapply H1 in Hin.\n  eexists; eauto.\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/map_util.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.28908008941461566}}
{"text": "(** * UseAuto: Theory and Practice of Automation in Coq Proofs *)\n\n(* Chapter written and maintained by Arthur Chargueraud *)\n\n(** In a machine-checked proof, every single detail has to be\n    justified.  This can result in huge proof scripts. Fortunately,\n    Coq comes with a proof-search mechanism and with several decision\n    procedures that enable the system to automatically synthesize\n    simple pieces of proof. Automation is very powerful when set up\n    appropriately. The purpose of this chapter is to explain the\n    basics of working of automation.\n\n    The chapter is organized in two parts. The first part focuses on a\n    general mechanism called \"proof search.\" In short, proof search\n    consists in naively trying to apply lemmas and assumptions in all\n    possible ways. The second part describes \"decision procedures\",\n    which are tactics that are very good at solving proof obligations\n    that fall in some particular fragment of the logic of Coq.\n\n    Many of the examples used in this chapter consist of small lemmas\n    that have been made up to illustrate particular aspects of automation.\n    These examples are completely independent from the rest of the Software\n    Foundations course. This chapter also contains some bigger examples\n    which are used to explain how to use automation in realistic proofs.\n    These examples are taken from other chapters of the course (mostly\n    from STLC), and the proofs that we present make use of the tactics\n    from the library [LibTactics.v], which is presented in the chapter\n    [UseTactics]. *)\n\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nRequire Import Maps.\nRequire Import Smallstep.\nRequire Import Stlc.\nRequire Import LibTactics.\n\n\n(* ################################################################# *)\n(** * Basic Features of Proof Search *)\n\n(** The idea of proof search is to replace a sequence of tactics\n    applying lemmas and assumptions with a call to a single tactic,\n    for example [auto]. This form of proof automation saves a lot of\n    effort. It typically leads to much shorter proof scripts, and to\n    scripts that are typically more robust to change.  If one makes a\n    little change to a definition, a proof that exploits automation\n    probably won't need to be modified at all. Of course, using too\n    much automation is a bad idea.  When a proof script no longer\n    records the main arguments of a proof, it becomes difficult to fix\n    it when it gets broken after a change in a definition. Overall, a\n    reasonable use of automation is generally a big win, as it saves a\n    lot of time both in building proof scripts and in subsequently\n    maintaining those proof scripts. *)\n\n\n(* ================================================================= *)\n(** ** Strength of Proof Search *)\n\n(** We are going to study four proof-search tactics: [auto], [eauto],\n    [iauto] and [jauto]. The tactics [auto] and [eauto] are builtin\n    in Coq. The tactic [iauto] is a shorthand for the builtin tactic\n    [try solve [intuition eauto]]. The tactic [jauto] is defined in\n    the library [LibTactics], and simply performs some preprocessing\n    of the goal before calling [eauto]. The goal of this chapter is\n    to explain the general principles of proof search and to give\n    rule of thumbs for guessing which of the four tactics mentioned\n    above is best suited for solving a given goal.\n\n    Proof search is a compromise between efficiency and\n    expressiveness, that is, a tradeoff between how complex goals the\n    tactic can solve and how much time the tactic requires for\n    terminating. The tactic [auto] builds proofs only by using the\n    basic tactics [reflexivity], [assumption], and [apply]. The tactic\n    [eauto] can also exploit [eapply]. The tactic [jauto] extends\n    [eauto] by being able to open conjunctions and existentials that\n    occur in the context.  The tactic [iauto] is able to deal with\n    conjunctions, disjunctions, and negation in a quite clever way;\n    however it is not able to open existentials from the context.\n    Also, [iauto] usually becomes very slow when the goal involves\n    several disjunctions.\n\n    Note that proof search tactics never perform any rewriting\n    step (tactics [rewrite], [subst]), nor any case analysis on an\n    arbitrary data structure or property (tactics [destruct] and\n    [inversion]), nor any proof by induction (tactic [induction]). So,\n    proof search is really intended to automate the final steps from\n    the various branches of a proof. It is not able to discover the\n    overall structure of a proof. *)\n\n\n(* ================================================================= *)\n(** ** Basics *)\n\n(** The tactic [auto] is able to solve a goal that can be proved\n    using a sequence of [intros], [apply], [assumption], and [reflexivity].\n    Two examples follow. The first one shows the ability for\n    [auto] to call [reflexivity] at any time. In fact, calling\n    [reflexivity] is always the first thing that [auto] tries to do. *)\n\nLemma solving_by_reflexivity :\n  2 + 3 = 5.\nProof. auto. Qed.\n\n(** The second example illustrates a proof where a sequence of\n    two calls to [apply] are needed. The goal is to prove that\n    if [Q n] implies [P n] for any [n] and if [Q n] holds for any [n],\n    then [P 2] holds. *)\n\nLemma solving_by_apply : forall (P Q : nat->Prop),\n  (forall n, Q n -> P n) ->\n  (forall n, Q n) ->\n  P 2.\nProof. auto. Qed.\n\n(** If we are interested to see which proof [auto] came up with,\n    one possibility is to look at the generated proof-term,\n    using the command:\n\n       [Print solving_by_apply.]\n   \n   The proof term is:\n\n   [fun (P Q : nat -> Prop) (H : forall n : nat, Q n -> P n) (H0 : forall n : nat, Q n)\n     => H 2 (H0 2)]\n\n   This essentially means that [auto] applied the hypothesis [H]\n   (the first one), and then applied the hypothesis [H0] (the\n   second one).\n\n*)\n\n(** The tactic [auto] can invoke [apply] but not [eapply]. So, [auto]\n    cannot exploit lemmas whose instantiation cannot be directly\n    deduced from the proof goal. To exploit such lemmas, one needs to\n    invoke the tactic [eauto], which is able to call [eapply].\n\n    In the following example, the first hypothesis asserts that [P n]\n    is true when [Q m] is true for some [m], and the goal is to prove\n    that [Q 1] implies [P 2].  This implication follows direction from\n    the hypothesis by instantiating [m] as the value [1].  The\n    following proof script shows that [eauto] successfully solves the\n    goal, whereas [auto] is not able to do so. *)\n\nLemma solving_by_eapply : forall (P Q : nat->Prop),\n  (forall n m, Q m -> P n) ->\n  Q 1 -> P 2.\nProof. auto. eauto. Qed.\n\n\n\n(* ================================================================= *)\n(** ** Conjunctions *)\n\n(** So far, we've seen that [eauto] is stronger than [auto] in the\n    sense that it can deal with [eapply]. In the same way, we are going\n    to see how [jauto] and [iauto] are stronger than [auto] and [eauto]\n    in the sense that they provide better support for conjunctions. *)\n\n(** The tactics [auto] and [eauto] can prove a goal of the form\n    [F /\\ F'], where [F] and [F'] are two propositions, as soon as\n    both [F] and [F'] can be proved in the current context.\n    An example follows. *)\n\nLemma solving_conj_goal : forall (P : nat->Prop) (F : Prop),\n  (forall n, P n) -> F -> F /\\ P 2.\nProof. auto. Qed.\n\n(** However, when an assumption is a conjunction, [auto] and [eauto]\n    are not able to exploit this conjunction. It can be quite\n    surprising at first that [eauto] can prove very complex goals but\n    that it fails to prove that [F /\\ F'] implies [F]. The tactics\n    [iauto] and [jauto] are able to decompose conjunctions from the context.\n    Here is an example. *)\n\nLemma solving_conj_hyp : forall (F F' : Prop),\n  F /\\ F' -> F.\nProof. auto. eauto. jauto. (* or [iauto] *) Qed.\n\n(** The tactic [jauto] is implemented by first calling a\n    pre-processing tactic called [jauto_set], and then calling\n    [eauto]. So, to understand how [jauto] works, one can directly\n    call the tactic [jauto_set]. *)\n\nLemma solving_conj_hyp' : forall (F F' : Prop),\n  F /\\ F' -> F.\nProof. intros. jauto_set. eauto. Qed.\n\n(** Next is a more involved goal that can be solved by [iauto] and\n    [jauto]. *)\n\nLemma solving_conj_more : forall (P Q R : nat->Prop) (F : Prop),\n  (F /\\ (forall n m, (Q m /\\ R n) -> P n)) ->\n  (F -> R 2) ->\n  Q 1 ->\n  P 2 /\\ F.\nProof. jauto. (* or [iauto] *) Qed.\n\n(** The strategy of [iauto] and [jauto] is to run a global analysis of\n    the top-level conjunctions, and then call [eauto].  For this\n    reason, those tactics are not good at dealing with conjunctions\n    that occur as the conclusion of some universally quantified\n    hypothesis. The following example illustrates a general weakness\n    of Coq proof search mechanisms. *)\n\nLemma solving_conj_hyp_forall : forall (P Q : nat->Prop),\n  (forall n, P n /\\ Q n) -> P 2.\nProof.\n  auto. eauto. iauto. jauto.\n  (* Nothing works, so we have to do some of the work by hand *)\n  intros. destruct (H 2). auto.\nQed.\n\n(** This situation is slightly disappointing, since automation is\n    able to prove the following goal, which is very similar. The\n    only difference is that the universal quantification has been\n    distributed over the conjunction. *)\n\nLemma solved_by_jauto : forall (P Q : nat->Prop) (F : Prop),\n  (forall n, P n) /\\ (forall n, Q n) -> P 2.\nProof. jauto. (* or [iauto] *) Qed.\n\n\n(* ================================================================= *)\n(** ** Disjunctions *)\n\n(** The tactics [auto] and [eauto] can handle disjunctions that\n    occur in the goal. *)\n\nLemma solving_disj_goal : forall (F F' : Prop),\n  F -> F \\/ F'.\nProof. auto. Qed.\n\n(** However, only [iauto] is able to automate reasoning on the\n    disjunctions that appear in the context. For example, [iauto] can\n    prove that [F \\/ F'] entails [F' \\/ F]. *)\n\nLemma solving_disj_hyp : forall (F F' : Prop),\n  F \\/ F' -> F' \\/ F.\nProof. auto. eauto. jauto. iauto. Qed.\n\n(** More generally, [iauto] can deal with complex combinations of\n    conjunctions, disjunctions, and negations. Here is an example. *)\n\nLemma solving_tauto : forall (F1 F2 F3 : Prop),\n  ((~F1 /\\ F3) \\/ (F2 /\\ ~F3)) ->\n  (F2 -> F1) ->\n  (F2 -> F3) ->\n  ~F2.\nProof. iauto. Qed.\n\n(** However, the ability of [iauto] to automatically perform a case\n    analysis on disjunctions comes with a downside: [iauto] may be\n    very slow. If the context involves several hypotheses with\n    disjunctions, [iauto] typically generates an exponential number of\n    subgoals on which [eauto] is called. One major advantage of [jauto]\n    compared with [iauto] is that it never spends time performing this\n    kind of case analyses. *)\n\n\n(* ================================================================= *)\n(** ** Existentials *)\n\n(** The tactics [eauto], [iauto], and [jauto] can prove goals whose\n    conclusion is an existential. For example, if the goal is [exists\n    x, f x], the tactic [eauto] introduces an existential variable,\n    say [?25], in place of [x]. The remaining goal is [f ?25], and\n    [eauto] tries to solve this goal, allowing itself to instantiate\n    [?25] with any appropriate value. For example, if an assumption [f\n    2] is available, then the variable [?25] gets instantiated with\n    [2] and the goal is solved, as shown below. *)\n\nLemma solving_exists_goal : forall (f : nat->Prop),\n  f 2 -> exists x, f x.\nProof.\n  auto. (* observe that [auto] does not deal with existentials, *)\n  eauto. (* whereas [eauto], [iauto] and [jauto] solve the goal *)\nQed.\n\n(** A major strength of [jauto] over the other proof search tactics is\n    that it is able to exploit the existentially-quantified\n    hypotheses, i.e., those of the form [exists x, P]. *)\n\nLemma solving_exists_hyp : forall (f g : nat->Prop),\n  (forall x, f x -> g x) ->\n  (exists a, f a) ->\n  (exists a, g a).\nProof.\n  auto. eauto. iauto. (* All of these tactics fail, *)\n  jauto.              (* whereas [jauto] succeeds. *)\n  (* For the details, run [intros. jauto_set. eauto] *)\nQed.\n\n\n(* ================================================================= *)\n(** ** Negation *)\n\n(** The tactics [auto] and [eauto] suffer from some limitations with\n    respect to the manipulation of negations, mostly related to the\n    fact that negation, written [~ P], is defined as [P -> False] but\n    that the unfolding of this definition is not performed\n    automatically. Consider the following example. *)\n\nLemma negation_study_1 : forall (P : nat->Prop),\n  P 0 -> (forall x, ~ P x) -> False.\nProof.\n  intros P H0 HX.\n  eauto. (* It fails to see that [HX] applies *)\n  unfold not in *. eauto.\nQed.\n\n(** For this reason, the tactics [iauto] and [jauto] systematically\n    invoke [unfold not in *] as part of their pre-processing. So,\n    they are able to solve the previous goal right away. *)\n\nLemma negation_study_2 : forall (P : nat->Prop),\n  P 0 -> (forall x, ~ P x) -> False.\nProof. jauto. (* or [iauto] *) Qed.\n\n(** We will come back later on to the behavior of proof search with\n    respect to the unfolding of definitions. *)\n\n\n(* ================================================================= *)\n(** ** Equalities *)\n\n(** Coq's proof-search feature is not good at exploiting equalities.\n    It can do very basic operations, like exploiting reflexivity\n    and symmetry, but that's about it. Here is a simple example\n    that [auto] can solve, by first calling [symmetry] and then\n    applying the hypothesis. *)\n\nLemma equality_by_auto : forall (f g : nat->Prop),\n  (forall x, f x = g x) -> g 2 = f 2.\nProof. auto. Qed.\n\n(** To automate more advanced reasoning on equalities, one should\n    rather try to use the tactic [congruence], which is presented at\n    the end of this chapter in the \"Decision Procedures\" section. *)\n\n\n(* ################################################################# *)\n(** * How Proof Search Works *)\n\n(* ================================================================= *)\n(** ** Search Depth *)\n\n(** The tactic [auto] works as follows.  It first tries to call\n    [reflexivity] and [assumption]. If one of these calls solves the\n    goal, the job is done. Otherwise [auto] tries to apply the most\n    recently introduced assumption that can be applied to the goal\n    without producing and error. This application produces\n    subgoals. There are two possible cases. If the sugboals produced\n    can be solved by a recursive call to [auto], then the job is done.\n    Otherwise, if this application produces at least one subgoal that\n    [auto] cannot solve, then [auto] starts over by trying to apply\n    the second most recently introduced assumption. It continues in a\n    similar fashion until it finds a proof or until no assumption\n    remains to be tried.\n\n    It is very important to have a clear idea of the backtracking\n    process involved in the execution of the [auto] tactic; otherwise\n    its behavior can be quite puzzling. For example, [auto] is not\n    able to solve the following triviality. *)\n\nLemma search_depth_0 :\n  True /\\ True /\\ True /\\ True /\\ True /\\ True.\nProof.\n  auto.\nAbort.\n\n(** The reason [auto] fails to solve the goal is because there are\n    too many conjunctions. If there had been only five of them, [auto]\n    would have successfully solved the proof, but six is too many.\n    The tactic [auto] limits the number of lemmas and hypotheses\n    that can be applied in a proof, so as to ensure that the proof\n    search eventually terminates. By default, the maximal number\n    of steps is five. One can specify a different bound, writing\n    for example [auto 6] to search for a proof involving at most\n    six steps. For example, [auto 6] would solve the previous lemma.\n    (Similarly, one can invoke [eauto 6] or [intuition eauto 6].)\n    The argument [n] of [auto n] is called the \"search depth.\"\n    The tactic [auto] is simply defined as a shorthand for [auto 5].\n\n    The behavior of [auto n] can be summarized as follows. It first\n    tries to solve the goal using [reflexivity] and [assumption]. If\n    this fails, it tries to apply a hypothesis (or a lemma that has\n    been registered in the hint database), and this application\n    produces a number of sugoals. The tactic [auto (n-1)] is then\n    called on each of those subgoals. If all the subgoals are solved,\n    the job is completed, otherwise [auto n] tries to apply a\n    different hypothesis.\n\n    During the process, [auto n] calls [auto (n-1)], which in turn\n    might call [auto (n-2)], and so on. The tactic [auto 0] only\n    tries [reflexivity] and [assumption], and does not try to apply\n    any lemma. Overall, this means that when the maximal number of\n    steps allowed has been exceeded, the [auto] tactic stops searching\n    and backtracks to try and investigate other paths. *)\n\n(** The following lemma admits a unique proof that involves exactly\n    three steps. So, [auto n] proves this goal iff [n] is greater than\n    three. *)\n\nLemma search_depth_1 : forall (P : nat->Prop),\n  P 0 ->\n  (P 0 -> P 1) ->\n  (P 1 -> P 2) ->\n  (P 2).\nProof.\n  auto 0. (* does not find the proof *)\n  auto 1. (* does not find the proof *)\n  auto 2. (* does not find the proof *)\n  auto 3. (* finds the proof *)\n          (* more generally, [auto n] solves the goal if [n >= 3] *)\nQed.\n\n(** We can generalize the example by introducing an assumption\n    asserting that [P k] is derivable from [P (k-1)] for all [k],\n    and keep the assumption [P 0]. The tactic [auto], which is the\n    same as [auto 5], is able to derive [P k] for all values of [k]\n    less than 5. For example, it can prove [P 4]. *)\n\nLemma search_depth_3 : forall (P : nat->Prop),\n  (* Hypothesis H1: *) (P 0) ->\n  (* Hypothesis H2: *) (forall k, P (k-1) -> P k) ->\n  (* Goal:          *) (P 4).\nProof. auto. Qed.\n\n(** However, to prove [P 5], one needs to call at least [auto 6]. *)\n\nLemma search_depth_4 : forall (P : nat->Prop),\n  (* Hypothesis H1: *) (P 0) ->\n  (* Hypothesis H2: *) (forall k, P (k-1) -> P k) ->\n  (* Goal:          *) (P 5).\nProof. auto. auto 6. Qed.\n\n(** Because [auto] looks for proofs at a limited depth, there are\n    cases where [auto] can prove a goal [F] and can prove a goal\n    [F'] but cannot prove [F /\\ F']. In the following example,\n    [auto] can prove [P 4] but it is not able to prove [P 4 /\\ P 4],\n    because the splitting of the conjunction consumes one proof step.\n    To prove the conjunction, one needs to increase the search depth,\n    using at least [auto 6]. *)\n\nLemma search_depth_5 : forall (P : nat->Prop),\n  (* Hypothesis H1: *) (P 0) ->\n  (* Hypothesis H2: *) (forall k, P (k-1) -> P k) ->\n  (* Goal:          *) (P 4 /\\ P 4).\nProof. auto. auto 6. Qed.\n\n\n(* ================================================================= *)\n(** ** Backtracking *)\n\n(** In the previous section, we have considered proofs where\n    at each step there was a unique assumption that [auto]\n    could apply. In general, [auto] can have several choices\n    at every step. The strategy of [auto] consists of trying all\n    of the possibilities (using a depth-first search exploration).\n\n    To illustrate how automation works, we are going to extend the\n    previous example with an additional assumption asserting that\n    [P k] is also derivable from [P (k+1)]. Adding this hypothesis\n    offers a new possibility that [auto] could consider at every step.\n\n    There exists a special command that one can use for tracing\n    all the steps that proof-search considers. To view such a\n    trace, one should write [debug eauto]. (For some reason, the\n    command [debug auto] does not exist, so we have to use the\n    command [debug eauto] instead.) *)\n\nLemma working_of_auto_1 : forall (P : nat->Prop),\n  (* Hypothesis H1: *) (P 0) ->\n  (* Hypothesis H2: *) (forall k, P (k-1) -> P k) ->\n  (* Hypothesis H3: *) (forall k, P (k+1) -> P k) ->\n  (* Goal:          *) (P 2).\n(* Uncomment \"debug\" in the following line to see the debug trace: *)\nProof. intros P H1 H2 H3. (* debug *) eauto. Qed.\n\n(** The output message produced by [debug eauto] is as follows.\n\n    depth=5\n    depth=4 apply H2\n    depth=3 apply H2\n    depth=3 exact H1\n\n    The depth indicates the value of [n] with which [eauto n] is\n    called. The tactics shown in the message indicate that the first\n    thing that [eauto] has tried to do is to apply [H2]. The effect of\n    applying [H2] is to replace the goal [P 2] with the goal [P 1].\n    Then, again, [H2] has been applied, changing the goal [P 1] into\n    [P 0]. At that point, the goal was exactly the hypothesis [H1].\n\n    It seems that [eauto] was quite lucky there, as it never even\n    tried to use the hypothesis [H3] at any time. The reason is that\n    [auto] always tried to use the [H2] first. So, let's permute\n    the hypotheses [H2] and [H3] and see what happens. *)\n\nLemma working_of_auto_2 : forall (P : nat->Prop),\n  (* Hypothesis H1: *) (P 0) ->\n  (* Hypothesis H3: *) (forall k, P (k+1) -> P k) ->\n  (* Hypothesis H2: *) (forall k, P (k-1) -> P k) ->\n  (* Goal:          *) (P 2).\nProof. intros P H1 H3 H2. (* debug *) eauto. Qed.\n\n(** This time, the output message suggests that the proof search\n    investigates many possibilities. If we print the proof term:\n\n      [Print working_of_auto_2.]\n\n    we observe that the proof term refers to [H3]. Thus the proof\n    is not the simplest one, since only [H2] and [H1] are needed.\n\n    In turns out that the proof goes through the proof obligation [P 3], \n    even though it is not required to do so. The following tree drawing\n    describes all the goals that [eauto] has been going through.\n\n    |5||4||3||2||1||0| -- below, tabulation indicates the depth\n\n    [P 2]\n    -> [P 3]\n       -> [P 4]\n          -> [P 5]\n             -> [P 6]\n                -> [P 7]\n                -> [P 5]\n             -> [P 4]\n                -> [P 5]\n                -> [P 3]\n          --> [P 3]\n             -> [P 4]\n                -> [P 5]\n                -> [P 3]\n             -> [P 2]\n                -> [P 3]\n                -> [P 1]\n       -> [P 2]\n          -> [P 3]\n             -> [P 4]\n                -> [P 5]\n                -> [P 3]\n             -> [P 2]\n                -> [P 3]\n                -> [P 1]\n          -> [P 1]\n             -> [P 2]\n                -> [P 3]\n                -> [P 1]\n             -> [P 0]\n                -> !! Done !!\n\n    The first few lines read as follows. To prove [P 2], [eauto 5]\n    has first tried to apply [H3], producing the subgoal [P 3].\n    To solve it, [eauto 4] has tried again to apply [H3], producing\n    the goal [P 4]. Similarly, the search goes through [P 5], [P 6]\n    and [P 7]. When reaching [P 7], the tactic [eauto 0] is called\n    but as it is not allowed to try and apply any lemma, it fails.\n    So, we come back to the goal [P 6], and try this time to apply\n    hypothesis [H2], producing the subgoal [P 5]. Here again,\n    [eauto 0] fails to solve this goal.\n\n    The process goes on and on, until backtracking to [P 3] and trying\n    to apply [H3] three times in a row, going through [P 2] and [P 1]\n    and [P 0]. This search tree explains why [eauto] came up with a\n    proof term starting with an application of [H3]. *)\n\n\n(* ================================================================= *)\n(** ** Adding Hints *)\n\n(** By default, [auto] (and [eauto]) only tries to apply the\n    hypotheses that appear in the proof context. There are two\n    possibilities for telling [auto] to exploit a lemma that have\n    been proved previously: either adding the lemma as an assumption\n    just before calling [auto], or adding the lemma as a hint, so\n    that it can be used by every calls to [auto].\n\n    The first possibility is useful to have [auto] exploit a lemma\n    that only serves at this particular point. To add the lemma as\n    hypothesis, one can type [generalize mylemma; intros], or simply\n    [lets: mylemma] (the latter requires [LibTactics.v]).\n\n    The second possibility is useful for lemmas that need to be\n    exploited several times. The syntax for adding a lemma as a hint\n    is [Hint Resolve mylemma]. For example, the lemma asserting than\n    any number is less than or equal to itself, [forall x, x <= x],\n    called [Le.le_refl] in the Coq standard library, can be added as a\n    hint as follows. *)\n\nHint Resolve Le.le_refl.\n\n(** A convenient shorthand for adding all the constructors of an\n    inductive datatype as hints is the command [Hint Constructors\n    mydatatype].\n\n    Warning: some lemmas, such as transitivity results, should\n    not be added as hints as they would very badly affect the\n    performance of proof search. The description of this problem\n    and the presentation of a general work-around for transitivity\n    lemmas appear further on. *)\n\n\n(* ================================================================= *)\n(** ** Integration of Automation in Tactics *)\n\n(** The library \"LibTactics\" introduces a convenient feature for\n    invoking automation after calling a tactic. In short, it suffices\n    to add the symbol star ([*]) to the name of a tactic. For example,\n    [apply* H] is equivalent to [apply H; auto_star], where [auto_star]\n    is a tactic that can be defined as needed.\n\n    The definition of [auto_star], which determines the meaning of the\n    star symbol, can be modified whenever needed. Simply write:\n\n       Ltac auto_star ::= a_new_definition.\n\n    Observe the use of [::=] instead of [:=], which indicates that the\n    tactic is being rebound to a new definition. So, the default\n    definition is as follows. *)\n\nLtac auto_star ::= try solve [ jauto ].\n\n(** Nearly all standard Coq tactics and all the tactics from\n    \"LibTactics\" can be called with a star symbol. For example, one\n    can invoke [subst*], [destruct* H], [inverts* H], [lets* I: H x],\n    [specializes* H x], and so on... There are two notable exceptions.\n    The tactic [auto*] is just another name for the tactic\n    [auto_star].  And the tactic [apply* H] calls [eapply H] (or the\n    more powerful [applys H] if needed), and then calls [auto_star].\n    Note that there is no [eapply* H] tactic, use [apply* H]\n    instead. *)\n\n(** In large developments, it can be convenient to use two degrees of\n    automation. Typically, one would use a fast tactic, like [auto],\n    and a slower but more powerful tactic, like [jauto]. To allow for\n    a smooth coexistence of the two form of automation, [LibTactics.v]\n    also defines a \"tilde\" version of tactics, like [apply~ H],\n    [destruct~ H], [subst~], [auto~] and so on. The meaning of the\n    tilde symbol is described by the [auto_tilde] tactic, whose\n    default implementation is [auto]. *)\n\n\nLtac auto_tilde ::= auto.\n\n(** In the examples that follow, only [auto_star] is needed. *)\n\n(** An alternative, possibly more efficient version of auto_star is the\n    following\":\n\n    Ltac auto_star ::= try solve [ eassumption | auto | jauto ].\n\n    With the above definition, [auto_star] first tries to solve the\n    goal using the assumptions; if it fails, it tries using [auto],\n    and if this still fails, then it calls [jauto]. Even though\n    [jauto] is strictly stronger than [eassumption] and [auto], it\n    makes sense to call these tactics first, because, when the\n    succeed, they save a lot of time, and when they fail to prove\n    the goal, they fail very quickly.\".\n\n*)\n\n(* ################################################################# *)\n(** * Examples of Use of Automation *)\n\n(** Let's see how to use proof search in practice on the main theorems\n    of the \"Software Foundations\" course, proving in particular\n    results such as determinism, preservation and progress. *)\n\n\n(* ================================================================= *)\n(** ** Determinism *)\n\nModule DeterministicImp.\n  Require Import Imp.\n\n(** Recall the original proof of the determinism lemma for the IMP\n    language, shown below. *)\n\nTheorem ceval_deterministic: forall c st st1 st2,\n  c / st \\\\ st1 ->\n  c / st \\\\ st2 ->\n  st1 = st2.\nProof.\n  intros c st st1 st2 E1 E2.\n  generalize dependent st2.\n  (induction E1); intros st2 E2; inversion E2; subst.\n  - (* E_Skip *) reflexivity.\n  - (* E_Ass *) reflexivity.\n  - (* E_Seq *)\n    assert (st' = st'0) as EQ1.\n    { (* Proof of assertion *) apply IHE1_1; assumption. }\n    subst st'0.\n    apply IHE1_2. assumption.\n  (* E_IfTrue *)\n  - (* b1 reduces to true *)\n    apply IHE1. assumption.\n  - (* b1 reduces to false (contradiction) *)\n    rewrite H in H5. inversion H5.\n  (* E_IfFalse *)\n  - (* b1 reduces to true (contradiction) *)\n    rewrite H in H5. inversion H5.\n  - (* b1 reduces to false *)\n      apply IHE1. assumption.\n  (* E_WhileEnd *)\n  - (* b1 reduces to true *)\n    reflexivity.\n  - (* b1 reduces to false (contradiction) *)\n    rewrite H in H2. inversion H2.\n  (* E_WhileLoop *)\n  - (* b1 reduces to true (contradiction) *)\n    rewrite H in H4. inversion H4.\n  - (* b1 reduces to false *)\n    assert (st' = st'0) as EQ1.\n    { (* Proof of assertion *) apply IHE1_1; assumption. }\n    subst st'0.\n    apply IHE1_2. assumption.\nQed.\n\n(** Exercise: rewrite this proof using [auto] whenever possible.\n    (The solution uses [auto] 9 times.) *)\n\nTheorem ceval_deterministic': forall c st st1 st2,\n  c / st \\\\ st1 ->\n  c / st \\\\ st2 ->\n  st1 = st2.\nProof.\n  (* FILL IN HERE *) admit.\nAdmitted.\n\n(** In fact, using automation is not just a matter of calling [auto]\n    in place of one or two other tactics. Using automation is about\n    rethinking the organization of sequences of tactics so as to\n    minimize the effort involved in writing and maintaining the proof.\n    This process is eased by the use of the tactics from\n    [LibTactics.v].  So, before trying to optimize the way automation\n    is used, let's first rewrite the proof of determinism:\n      - use [introv H] instead of [intros x H],\n      - use [gen x] instead of [generalize dependent x],\n      - use [inverts H] instead of [inversion H; subst],\n      - use [tryfalse] to handle contradictions, and get rid of\n        the cases where [beval st b1 = true] and [beval st b1 = false]\n        both appear in the context,\n      - stop using [ceval_cases] to label subcases. *)\n\nTheorem ceval_deterministic'': forall c st st1 st2,\n  c / st \\\\ st1 ->\n  c / st \\\\ st2 ->\n  st1 = st2.\nProof.\n  introv E1 E2. gen st2.\n  induction E1; intros; inverts E2; tryfalse.\n  - auto.\n  - auto.\n  - assert (st' = st'0). auto. subst. auto.\n  - auto.\n  - auto.\n  - auto.\n  - assert (st' = st'0). auto. subst. auto.\nQed.\n\n(** To obtain a nice clean proof script, we have to remove the calls\n    [assert (st' = st'0)]. Such a tactic invokation is not nice\n    because it refers to some variables whose name has been\n    automatically generated. This kind of tactics tend to be very\n    brittle.  The tactic [assert (st' = st'0)] is used to assert the\n    conclusion that we want to derive from the induction\n    hypothesis. So, rather than stating this conclusion explicitly, we\n    are going to ask Coq to instantiate the induction hypothesis,\n    using automation to figure out how to instantiate it. The tactic\n    [forwards], described in [LibTactics.v] precisely helps with\n    instantiating a fact. So, let's see how it works out on our\n    example. *)\n\nTheorem ceval_deterministic''': forall c st st1 st2,\n  c / st \\\\ st1 ->\n  c / st \\\\ st2 ->\n  st1 = st2.\nProof.\n  (* Let's replay the proof up to the [assert] tactic. *)\n  introv E1 E2. gen st2.\n  induction E1; intros; inverts E2; tryfalse.\n  - auto.\n  - auto.\n  (* We duplicate the goal for comparing different proofs. *)\n  - dup 4.\n\n  (* The old proof: *)\n  + assert (st' = st'0). apply IHE1_1. apply H1.\n    (* produces [H: st' = st'0]. *) skip.\n\n  (* The new proof, without automation: *)\n  + forwards: IHE1_1. apply H1.\n    (* produces [H: st' = st'0]. *) skip.\n\n  (* The new proof, with automation: *)\n  + forwards: IHE1_1. eauto.\n    (* produces [H: st' = st'0]. *) skip.\n\n  (* The new proof, with integrated automation: *)\n  + forwards*: IHE1_1.\n    (* produces [H: st' = st'0]. *) skip.\n\nAbort.\n\n(** To polish the proof script, it remains to factorize the calls\n    to [auto], using the star symbol. The proof of determinism can then\n    be rewritten in only four lines, including no more than 10 tactics. *)\n\nTheorem ceval_deterministic'''': forall c st st1 st2,\n  c / st \\\\ st1  ->\n  c / st \\\\ st2 ->\n  st1 = st2.\nProof.\n  introv E1 E2. gen st2.\n  induction E1; intros; inverts* E2; tryfalse.\n  - forwards*: IHE1_1. subst*.\n  - forwards*: IHE1_1. subst*.\nQed.\n\nEnd DeterministicImp.\n\n\n(* ================================================================= *)\n(** ** Preservation for STLC *)\n\nModule PreservationProgressStlc.\n  Require Import StlcProp.\n  Import STLC.\n  Import STLCProp.\n\n(** Consider the proof of perservation of STLC, shown below.\n    This proof already uses [eauto] through the triple-dot\n    mechanism. *)\n\nTheorem preservation : forall t t' T,\n  has_type empty t T  ->\n  t ==> t'  ->\n  has_type empty t' T.\nProof with eauto.\n  remember (@empty ty) as Gamma.\n  intros t t' T HT. generalize dependent t'.\n  (induction HT); intros t' HE; subst Gamma.\n  - (* T_Var *)\n    inversion HE.\n  - (* T_Abs *)\n    inversion HE.\n  - (* T_App *)\n    inversion HE; subst...\n    (* The ST_App1 and ST_App2 cases are immediate by induction, and\n       auto takes care of them *)\n    + (* ST_AppAbs *)\n      apply substitution_preserves_typing with T11...\n      inversion HT1...\n  - (* T_True *)\n    inversion HE.\n  - (* T_False *)\n    inversion HE.\n  - (* T_If *)\n    inversion HE; subst...\nQed.\n\n(** Exercise: rewrite this proof using tactics from [LibTactics]\n    and calling automation using the star symbol rather than the\n    triple-dot notation. More precisely, make use of the tactics\n    [inverts*] and [applys*] to call [auto*] after a call to\n    [inverts] or to [applys]. The solution is three lines long.*)\n\nTheorem preservation' : forall t t' T,\n  has_type empty t T  ->\n  t ==> t'  ->\n  has_type empty t' T.\nProof.\n  (* FILL IN HERE *) admit.\nAdmitted.\n\n\n(* ================================================================= *)\n(** ** Progress for STLC *)\n\n(** Consider the proof of the progress theorem. *)\n\nTheorem progress : forall t T,\n  has_type empty t T ->\n  value t \\/ exists t', t ==> t'.\nProof with eauto.\n  intros t T Ht.\n  remember (@empty ty) as Gamma.\n  (induction Ht); subst Gamma...\n  - (* T_Var *)\n    inversion H.\n  - (* T_App *)\n    right. destruct IHHt1...\n    + (* t1 is a value *)\n      destruct IHHt2...\n      * (* t2 is a value *)\n        inversion H; subst; try solve_by_invert.\n        exists ([x0:=t2]t)...\n      * (* t2 steps *)\n       destruct H0 as [t2' Hstp]. exists (tapp t1 t2')...\n    + (* t1 steps *)\n      destruct H as [t1' Hstp]. exists (tapp t1' t2)...\n  - (* T_If *)\n    right. destruct IHHt1...\n    destruct t1; try solve_by_invert...\n    inversion H. exists (tif x0 t2 t3)...\nQed.\n\n(** Exercise: optimize the above proof.\n    Hint: make use of [destruct*] and [inverts*].\n    The solution consists of 10 short lines. *)\n\nTheorem progress' : forall t T,\n  has_type empty t T ->\n  value t \\/ exists t', t ==> t'.\nProof.\n  (* FILL IN HERE *) admit.\nAdmitted.\n\nEnd PreservationProgressStlc.\n\n\n(* ================================================================= *)\n(** ** BigStep and SmallStep *)\n\nModule Semantics.\nRequire Import Smallstep.\n\n(** Consider the proof relating a small-step reduction judgment\n    to a big-step reduction judgment. *)\n\nTheorem multistep__eval : forall t v,\n  normal_form_of t v -> exists n, v = C n /\\ t \\\\ n.\nProof.\n  intros t v Hnorm.\n  unfold normal_form_of in Hnorm.\n  inversion Hnorm as [Hs Hnf]; clear Hnorm.\n  rewrite nf_same_as_value in Hnf. inversion Hnf. clear Hnf.\n  exists n. split. reflexivity.\n  induction Hs; subst.\n  - (* multi_refl *)\n    apply E_Const.\n  - (* multi_step *)\n    eapply step__eval. eassumption. apply IHHs. reflexivity.\nQed.\n\n(** Our goal is to optimize the above proof. It is generally\n    easier to isolate inductions into separate lemmas. So,\n    we are going to first prove an intermediate result\n    that consists of the judgment over which the induction\n    is being performed. *)\n\n(** Exercise: prove the following result, using tactics\n    [introv], [induction] and [subst], and [apply*].\n    The solution is 3 lines long. *)\n\nTheorem multistep_eval_ind : forall t v,\n  t ==>* v -> forall n, C n = v -> t \\\\ n.\nProof.\n  (* FILL IN HERE *) admit.\nAdmitted.\n\n(** Exercise: using the lemma above, simplify the proof of\n    the result [multistep__eval]. You should use the tactics\n    [introv], [inverts], [split*] and [apply*].\n    The solution is 2 lines long. *)\n\nTheorem multistep__eval' : forall t v,\n  normal_form_of t v -> exists n, v = C n /\\ t \\\\ n.\nProof.\n  (* FILL IN HERE *) admit.\nAdmitted.\n\n(** If we try to combine the two proofs into a single one,\n    we will likely fail, because of a limitation of the\n    [induction] tactic. Indeed, this tactic looses\n    information when applied to a property whose arguments\n    are not reduced to variables, such as [t ==>* (C n)].\n    You will thus need to use the more powerful tactic called\n    [dependent induction]. This tactic is available only after\n    importing the [Program] library, as shown below. *)\n\nRequire Import Program.\n\n(** Exercise: prove the lemma [multistep__eval] without invoking\n    the lemma [multistep_eval_ind], that is, by inlining the proof\n    by induction involved in [multistep_eval_ind], using the\n    tactic [dependent induction] instead of [induction].\n    The solution is 5 lines long. *)\n\nTheorem multistep__eval'' : forall t v,\n  normal_form_of t v -> exists n, v = C n /\\ t \\\\ n.\nProof.\n  (* FILL IN HERE *) admit.\nAdmitted.\n\nEnd Semantics.\n\n\n(* ================================================================= *)\n(** ** Preservation for STLCRef *)\n\nModule PreservationProgressReferences.\n  Require Import Coq.omega.Omega.\n  Require Import References.\n  Import STLCRef.\n  Hint Resolve store_weakening extends_refl.\n\n(** The proof of preservation for [STLCRef] can be found in chapter\n    [References].  The optimized proof script is more than twice\n    shorter.  The following material explains how to build the\n    optimized proof script.  The resulting optimized proof script for\n    the preservation theorem appears afterwards. *)\n\nTheorem preservation : forall ST t t' T st st',\n  has_type empty ST t T ->\n  store_well_typed ST st ->\n  t / st ==> t' / st' ->\n  exists ST',\n    (extends ST' ST /\\\n     has_type empty ST' t' T /\\\n     store_well_typed ST' st').\nProof.\n  (* old: [Proof. with eauto using store_weakening, extends_refl.]\n     new: [Proof.], and the two lemmas are registered as hints\n     before the proof of the lemma, possibly inside a section in\n     order to restrict the scope of the hints. *)\n\n  remember (@empty ty) as Gamma. introv Ht. gen t'.\n  (induction Ht); introv HST Hstep;\n    (* old: [subst; try solve_by_invert; inversion Hstep; subst;\n             try (eauto using store_weakening, extends_refl)]\n       new: [subst Gamma; inverts Hstep; eauto.]\n       We want to be more precise on what exactly we substitute,\n       and we do not want to call [try solve_by_invert] which\n       is way to slow. *)\n   subst Gamma; inverts Hstep; eauto.\n\n  (* T_App *)\n  - (* ST_AppAbs *)\n  (* old:\n      exists ST. inversion Ht1; subst.\n      split; try split... eapply substitution_preserves_typing... *)\n  (* new: we use [inverts] in place of [inversion] and [splits] to\n     split the conjunction, and [applys*] in place of [eapply...] *)\n  exists ST. inverts Ht1. splits*. applys* substitution_preserves_typing.\n\n  - (* ST_App1 *)\n  (* old:\n      eapply IHHt1 in H0...\n      inversion H0 as [ST' [Hext [Hty Hsty]]].\n      exists ST'... *)\n  (* new: The tactic [eapply IHHt1 in H0...] applies [IHHt1] to [H0].\n     But [H0] is only thing that [IHHt1] could be applied to, so\n     there [eauto] can figure this out on its own. The tactic\n     [forwards] is used to instantiate all the arguments of [IHHt1],\n     producing existential variables and subgoals when needed. *)\n  forwards: IHHt1. eauto. eauto. eauto.\n  (* At this point, we need to decompose the hypothesis [H] that has\n     just been created by [forwards]. This is done by the first part\n     of the preprocessing phase of [jauto]. *)\n  jauto_set_hyps; intros.\n  (* It remains to decompose the goal, which is done by the second\n     part of the preprocessing phase of [jauto]. *)\n  jauto_set_goal; intros.\n  (* All the subgoals produced can then be solved by [eauto]. *)\n  eauto. eauto. eauto.\n\n  -(* ST_App2 *)\n  (* old:\n      eapply IHHt2 in H5...\n      inversion H5 as [ST' [Hext [Hty Hsty]]].\n      exists ST'... *)\n  (* new: this time, we need to call [forwards] on [IHHt2],\n     and we call [jauto] right away, by writing [forwards*],\n     proving the goal in a single tactic! *)\n  forwards*: IHHt2.\n\n  (* The same trick works for many of the other subgoals. *)\n  - forwards*: IHHt.\n  - forwards*: IHHt.\n  - forwards*: IHHt1.\n  - forwards*: IHHt2.\n  - forwards*: IHHt1.\n\n  - (* T_Ref *)\n  + (* ST_RefValue *)\n    (* old:\n         exists (ST ++ T1::nil).\n         inversion HST; subst.\n         split.\n           apply extends_app.\n         split.\n           replace (TRef T1)\n             with (TRef (store_Tlookup (length st) (ST ++ T1::nil))).\n           apply T_Loc.\n           rewrite <- H. rewrite app_length, plus_comm. simpl. omega.\n           unfold store_Tlookup. rewrite <- H. rewrite app_nth2; try omega.\n           rewrite minus_diag. simpl. reflexivity.\n           apply store_well_typed_app; assumption. *)\n    (* new: In this proof case, we need to perform an inversion\n       without removing the hypothesis. The tactic [inverts keep]\n       serves exactly this purpose. *)\n    exists (ST ++ T1::nil). inverts keep HST. splits.\n    (* The proof of the first subgoal needs no change *)\n      apply extends_app.\n    (* For the second subgoal, we use the tactic [applys_eq] to avoid\n       a manual [replace] before [T_loc] can be applied. *)\n      applys_eq T_Loc 1.\n    (* To justify the inequality, there is no need to call [rewrite <- H],\n       because the tactic [omega] is able to exploit [H] on its own.\n       So, only the rewriting of [app_length] and the call to the\n       tactic [omega] remain, with a call to [simpl] to unfold the\n       definition of [app]. *)\n        rewrite app_length. simpl. omega.\n    (* The next proof case is hard to polish because it relies on the\n       lemma [app_nth1] whose statement is not automation-friendly.\n       We'll come back to this proof case further on. *)\n      unfold store_Tlookup. rewrite <- H. rewrite* app_nth2.\n    (* Last, we replace [apply ..; assumption] with [apply* ..] *)\n    rewrite minus_diag. simpl. reflexivity.\n    apply* store_well_typed_app.\n\n  - forwards*: IHHt.\n\n  - (* T_Deref *)\n  + (* ST_DerefLoc *)\n  (* old:\n      exists ST. split; try split...\n      destruct HST as [_ Hsty].\n      replace T11 with (store_Tlookup l ST).\n      apply Hsty...\n      inversion Ht; subst... *)\n  (* new: we start by calling [exists ST] and [splits*]. *)\n  exists ST. splits*.\n  (* new: we replace [destruct HST as [_ Hsty]] by the following *)\n  lets [_ Hsty]: HST.\n  (* new: then we use the tactic [applys_eq] to avoid the need to\n     perform a manual [replace] before applying [Hsty]. *)\n  applys_eq* Hsty 1.\n  (* new: we then can call [inverts] in place of [inversion;subst] *)\n  inverts* Ht.\n\n  - forwards*: IHHt.\n\n  - (* T_Assign *)\n  + (* ST_Assign *)\n  (* old:\n      exists ST. split; try split...\n      eapply assign_pres_store_typing...\n      inversion Ht1; subst... *)\n  (* new: simply using nicer tactics *)\n  exists ST. splits*. applys* assign_pres_store_typing. inverts* Ht1.\n\n  - forwards*: IHHt1.\n  - forwards*: IHHt2.\nQed.\n\n(** Let's come back to the proof case that was hard to optimize.\n    The difficulty comes from the statement of [nth_eq_last], which\n    takes the form [nth (length l) (l ++ x::nil) d = x]. This lemma is\n    hard to exploit because its first argument, [length l], mentions\n    a list [l] that has to be exactly the same as the [l] occuring in\n    [snoc l x]. In practice, the first argument is often a natural\n    number [n] that is provably equal to [length l] yet that is not\n    syntactically equal to [length l]. There is a simple fix for\n    making [nth_eq_last] easy to apply: introduce the intermediate\n    variable [n] explicitly, so that the goal becomes\n    [nth n (snoc l x) d = x], with a premise asserting [n = length l]. *)\n\nLemma nth_eq_last' : forall (A : Type) (l : list A) (x d : A) (n : nat),\n  n = length l -> nth n (l ++ x::nil) d = x.\nProof. intros. subst. apply nth_eq_last. Qed.\n\n(** The proof case for [ref] from the preservation theorem then\n    becomes much easier to prove, because [rewrite nth_eq_last']\n    now succeeds. *)\n\nLemma preservation_ref : forall (st:store) (ST : store_ty) T1,\n  length ST = length st ->\n  TRef T1 = TRef (store_Tlookup (length st) (ST ++ T1::nil)).\nProof.\n  intros. dup.\n\n  (* A first proof, with an explicit [unfold] *)\n  unfold store_Tlookup. rewrite* nth_eq_last'.\n\n  (* A second proof, with a call to [fequal] *)\n  fequal. symmetry. apply* nth_eq_last'.\nQed.\n\n(** The optimized proof of preservation is summarized next. *)\n\nTheorem preservation' : forall ST t t' T st st',\n  has_type empty ST t T ->\n  store_well_typed ST st ->\n  t / st ==> t' / st' ->\n  exists ST',\n    (extends ST' ST /\\\n     has_type empty ST' t' T /\\\n     store_well_typed ST' st').\nProof.\n  remember (@empty ty) as Gamma. introv Ht. gen t'.\n  induction Ht; introv HST Hstep; subst Gamma; inverts Hstep; eauto.\n  - exists ST. inverts Ht1. splits*. applys* substitution_preserves_typing.\n  - forwards*: IHHt1.\n  - forwards*: IHHt2.\n  - forwards*: IHHt.\n  - forwards*: IHHt.\n  - forwards*: IHHt1.\n  - forwards*: IHHt2.\n  - forwards*: IHHt1.\n  - exists (ST ++ T1::nil). inverts keep HST. splits.\n    apply extends_app.\n    applys_eq T_Loc 1.\n      rewrite app_length. simpl. omega.\n      unfold store_Tlookup. rewrite* nth_eq_last'.\n    apply* store_well_typed_app.\n  - forwards*: IHHt.\n  - exists ST. splits*. lets [_ Hsty]: HST.\n    applys_eq* Hsty 1. inverts* Ht.\n  - forwards*: IHHt.\n  - exists ST. splits*. applys* assign_pres_store_typing. inverts* Ht1.\n  - forwards*: IHHt1.\n  - forwards*: IHHt2.\nQed.\n\n\n(* ================================================================= *)\n(** ** Progress for STLCRef *)\n\n(** The proof of progress for [STLCRef] can be found in chapter\n    [References]. The optimized proof script is, here again, about\n    half the length. *)\n\nTheorem progress : forall ST t T st,\n  has_type empty ST t T ->\n  store_well_typed ST st ->\n  (value t \\/ exists t', exists st', t / st ==> t' / st').\nProof.\n  introv Ht HST. remember (@empty ty) as Gamma.\n  induction Ht; subst Gamma; tryfalse; try solve [left*].\n  - right. destruct* IHHt1 as [K|].\n    inverts K; inverts Ht1.\n     destruct* IHHt2.\n  - right. destruct* IHHt as [K|].\n    inverts K; try solve [inverts Ht]. eauto.\n  - right. destruct* IHHt as [K|].\n    inverts K; try solve [inverts Ht]. eauto.\n  - right. destruct* IHHt1 as [K|].\n    inverts K; try solve [inverts Ht1].\n     destruct* IHHt2 as [M|].\n      inverts M; try solve [inverts Ht2]. eauto.\n  - right. destruct* IHHt1 as [K|].\n    inverts K; try solve [inverts Ht1]. destruct* n.\n  - right. destruct* IHHt.\n  - right. destruct* IHHt as [K|].\n    inverts K; inverts Ht as M.\n      inverts HST as N. rewrite* N in M.\n  - right. destruct* IHHt1 as [K|].\n    destruct* IHHt2.\n     inverts K; inverts Ht1 as M.\n     inverts HST as N. rewrite* N in M.\nQed.\n\nEnd PreservationProgressReferences.\n\n\n(* ================================================================= *)\n(** ** Subtyping *)\n\nModule SubtypingInversion.\n  Require Import Sub.\n\n(** Consider the inversion lemma for typing judgment\n    of abstractions in a type system with subtyping. *)\n\nLemma abs_arrow : forall x S1 s2 T1 T2,\n  has_type empty (tabs x S1 s2) (TArrow T1 T2) ->\n     subtype T1 S1\n  /\\ has_type (update empty x S1) s2 T2.\nProof with eauto.\n  intros x S1 s2 T1 T2 Hty.\n  apply typing_inversion_abs in Hty.\n  destruct Hty as [S2 [Hsub Hty]].\n  apply sub_inversion_arrow in Hsub.\n  destruct Hsub as [U1 [U2 [Heq [Hsub1 Hsub2]]]].\n  inversion Heq; subst...\nQed.\n\n(** Exercise: optimize the proof script, using\n    [introv], [lets] and [inverts*]. In particular,\n    you will find it useful to replace the pattern\n    [apply K in H. destruct H as I] with [lets I: K H].\n    The solution is 4 lines. *)\n\nLemma abs_arrow' : forall x S1 s2 T1 T2,\n  has_type empty (tabs x S1 s2) (TArrow T1 T2) ->\n     subtype T1 S1\n  /\\ has_type (update empty x S1) s2 T2.\nProof.\n  (* FILL IN HERE *) admit.\nAdmitted.\n\n(** The lemma [substitution_preserves_typing] has already been used to\n    illustrate the working of [lets] and [applys] in chapter\n    [UseTactics]. Optimize further this proof using automation (with\n    the star symbol), and using the tactic [cases_if']. The solution\n    is 33 lines). *)\n\nLemma substitution_preserves_typing : forall Gamma x U v t S,\n  has_type (update Gamma x U) t S ->\n  has_type empty v U ->\n  has_type Gamma ([x:=v]t) S.\nProof.\n  (* FILL IN HERE *) admit.\nAdmitted.\n\nEnd SubtypingInversion.\n\n\n(* ################################################################# *)\n(** * Advanced Topics in Proof Search *)\n\n(* ================================================================= *)\n(** ** Stating Lemmas in the Right Way *)\n\n(** Due to its depth-first strategy, [eauto] can get exponentially\n    slower as the depth search increases, even when a short proof\n    exists. In general, to make proof search run reasonably fast, one\n    should avoid using a depth search greater than 5 or 6. Moreover,\n    one should try to minimize the number of applicable lemmas, and\n    usually put first the hypotheses whose proof usefully instantiates\n    the existential variables.\n\n    In fact, the ability for [eauto] to solve certain goals actually\n    depends on the order in which the hypotheses are stated. This point\n    is illustrated through the following example, in which [P] is\n    a property of natural numbers. This property is such that\n    [P n] holds for any [n] as soon as [P m] holds for at least one [m]\n    different from zero. The goal is to prove that [P 2] implies [P 1].\n    When the hypothesis about [P] is stated in the form\n    [forall n m, P m -> m <> 0 -> P n], then [eauto] works. However, with\n    [forall n m, m <> 0 -> P m -> P n], the tactic [eauto] fails. *)\n\nLemma order_matters_1 : forall (P : nat->Prop),\n  (forall n m, P m -> m <> 0 -> P n) -> P 2 -> P 1.\nProof.\n  eauto. (* Success *)\n  (* The proof: [intros P H K. eapply H. apply K. auto.] *)\nQed.\n\nLemma order_matters_2 : forall (P : nat->Prop),\n  (forall n m, m <> 0 -> P m -> P n) -> P 5 -> P 1.\nProof.\n  eauto. (* Failure *)\n\n  (* To understand why, let us replay the previous proof *)\n  intros P H K.\n  eapply H.\n  (* The application of [eapply] has left two subgoals,\n     [?X <> 0] and [P ?X], where [?X] is an existential variable. *)\n  (* Solving the first subgoal is easy for [eauto]: it suffices\n     to instantiate [?X] as the value [1], which is the simplest\n     value that satisfies [?X <> 0]. *)\n  eauto.\n  (* But then the second goal becomes [P 1], which is where we\n     started from. So, [eauto] gets stuck at this point. *)\nAbort.\n\n(** It is very important to understand that the hypothesis [forall n\n    m, P m -> m <> 0 -> P n] is eauto-friendly, whereas [forall n m, m\n    <> 0 -> P m -> P n] really isn't.  Guessing a value of [m] for\n    which [P m] holds and then checking that [m <> 0] holds works well\n    because there are few values of [m] for which [P m] holds. So, it\n    is likely that [eauto] comes up with the right one. On the other\n    hand, guessing a value of [m] for which [m <> 0] and then checking\n    that [P m] holds does not work well, because there are many values\n    of [m] that satisfy [m <> 0] but not [P m]. *)\n\n\n(* ================================================================= *)\n(** ** Unfolding of Definitions During Proof-Search *)\n\n(** The use of intermediate definitions is generally encouraged in a\n    formal development as it usually leads to more concise and more\n    readable statements. Yet, definitions can make it a little harder\n    to automate proofs. The problem is that it is not obvious for a\n    proof search mechanism to know when definitions need to be\n    unfolded. Note that a naive strategy that consists in unfolding\n    all definitions before calling proof search does not scale up to\n    large proofs, so we avoid it. This section introduces a few\n    techniques for avoiding to manually unfold definitions before\n    calling proof search. *)\n\n(** To illustrate the treatment of definitions, let [P] be an abstract\n    property on natural numbers, and let [myFact] be a definition\n    denoting the proposition [P x] holds for any [x] less than or\n    equal to 3. *)\n\nAxiom P : nat -> Prop.\n\nDefinition myFact := forall x, x <= 3 -> P x.\n\n(** Proving that [myFact] under the assumption that [P x] holds for\n    any [x] should be trivial. Yet, [auto] fails to prove it unless we\n    unfold the definition of [myFact] explicitly. *)\n\nLemma demo_hint_unfold_goal_1 :\n  (forall x, P x) -> myFact.\nProof.\n  auto.                (* Proof search doesn't know what to do, *)\n  unfold myFact. auto. (* unless we unfold the definition. *)\nQed.\n\n(** To automate the unfolding of definitions that appear as proof\n    obligation, one can use the command [Hint Unfold myFact] to tell\n    Coq that it should always try to unfold [myFact] when [myFact]\n    appears in the goal. *)\n\nHint Unfold myFact.\n\n(** This time, automation is able to see through the definition\n    of [myFact]. *)\n\nLemma demo_hint_unfold_goal_2 :\n  (forall x, P x) -> myFact.\nProof. auto. Qed.\n\n(** However, the [Hint Unfold] mechanism only works for unfolding\n    definitions that appear in the goal. In general, proof search does\n    not unfold definitions from the context. For example, assume we\n    want to prove that [P 3] holds under the assumption that [True ->\n    myFact]. *)\n\nLemma demo_hint_unfold_context_1 :\n  (True -> myFact) -> P 3.\nProof.\n  intros.\n  auto.                      (* fails *)\n  unfold myFact in *. auto.  (* succeeds *)\nQed.\n\n(** There is actually one exception to the previous rule: a constant\n    occuring in an hypothesis is automatically unfolded if the\n    hypothesis can be directly applied to the current goal. For example,\n    [auto] can prove [myFact -> P 3], as illustrated below. *)\n\nLemma demo_hint_unfold_context_2 :\n  myFact -> P 3.\nProof. auto. Qed.\n\n\n(* ================================================================= *)\n(** ** Automation for Proving Absurd Goals *)\n\n(** In this section, we'll see that lemmas concluding on a negation\n    are generally not useful as hints, and that lemmas whose\n    conclusion is [False] can be useful hints but having too many of\n    them makes proof search inefficient. We'll also see a practical\n    work-around to the efficiency issue. *)\n\n(** Consider the following lemma, which asserts that a number\n    less than or equal to 3 is not greater than 3. *)\n\nParameter le_not_gt : forall x,\n  (x <= 3) -> ~ (x > 3).\n\n(** Equivalently, one could state that a number greater than three is\n    not less than or equal to 3. *)\n\nParameter gt_not_le : forall x,\n  (x > 3) -> ~ (x <= 3).\n\n(** In fact, both statements are equivalent to a third one stating\n    that [x <= 3] and [x > 3] are contradictory, in the sense that\n    they imply [False]. *)\n\nParameter le_gt_false : forall x,\n  (x <= 3) -> (x > 3) -> False.\n\n(** The following investigation aim at figuring out which of the three\n    statments is the most convenient with respect to proof\n    automation. The following material is enclosed inside a [Section],\n    so as to restrict the scope of the hints that we are adding. In\n    other words, after the end of the section, the hints added within\n    the section will no longer be active.*)\n\nSection DemoAbsurd1.\n\n(** Let's try to add the first lemma, [le_not_gt], as hint,\n    and see whether we can prove that the proposition\n    [exists x, x <= 3 /\\ x > 3] is absurd. *)\n\nHint Resolve le_not_gt.\n\nLemma demo_auto_absurd_1 :\n  (exists x, x <= 3 /\\ x > 3) -> False.\nProof.\n  intros. jauto_set. (* decomposes the assumption *)\n  (* debug *) eauto. (* does not see that [le_not_gt] could apply *)\n  eapply le_not_gt. eauto. eauto.\nQed.\n\n(** The lemma [gt_not_le] is symmetric to [le_not_gt], so it will not\n    be any better. The third lemma, [le_gt_false], is a more useful\n    hint, because it concludes on [False], so proof search will try to\n    apply it when the current goal is [False]. *)\n\nHint Resolve le_gt_false.\n\nLemma demo_auto_absurd_2 :\n  (exists x, x <= 3 /\\ x > 3) -> False.\nProof.\n  dup.\n\n  (* detailed version: *)\n  intros. jauto_set. (* debug *) eauto.\n\n  (* short version: *)\n  jauto.\nQed.\n\n(** In summary, a lemma of the form [H1 -> H2 -> False] is a much more\n    effective hint than [H1 -> ~ H2], even though the two statments\n    are equivalent up to the definition of the negation symbol [~]. *)\n\n(** That said, one should be careful with adding lemmas whose\n    conclusion is [False] as hint. The reason is that whenever\n    reaching the goal [False], the proof search mechanism will\n    potentially try to apply all the hints whose conclusion is [False]\n    before applying the appropriate one.  *)\n\nEnd DemoAbsurd1.\n\n(** Adding lemmas whose conclusion is [False] as hint can be, locally,\n    a very effective solution. However, this approach does not scale\n    up for global hints.  For most practical applications, it is\n    reasonable to give the name of the lemmas to be exploited for\n    deriving a contradiction. The tactic [false H], provided by\n    [LibTactics] serves that purpose: [false H] replaces the goal\n    with [False] and calls [eapply H]. Its behavior is described next.\n    Observe that any of the three statements [le_not_gt], [gt_not_le]\n    or [le_gt_false] can be used. *)\n\nLemma demo_false : forall x,\n  (x <= 3) -> (x > 3) -> 4 = 5.\nProof.\n  intros. dup 4.\n\n  (* A failed proof: *)\n  - false. eapply le_gt_false.\n    + auto. (* here, [auto] does not prove [?x <= 3] by using [H] but\n             by using the lemma [le_refl : forall x, x <= x]. *)\n    (* The second subgoal becomes [3 > 3], which is not provable. *)\n    + skip.\n\n  (* A correct proof: *)\n  - false. eapply le_gt_false.\n    + eauto. (* here, [eauto] uses [H], as expected, to prove [?x <= 3] *)\n    + eauto. (* so the second subgoal becomes [x > 3] *)\n\n  (* The same proof using [false]: *)\n  - false le_gt_false. eauto. eauto.\n\n  (* The lemmas [le_not_gt] and [gt_not_le] work as well *)\n  - false le_not_gt. eauto. eauto.\nQed.\n\n(** In the above example, [false le_gt_false; eauto] proves the goal,\n    but [false le_gt_false; auto] does not, because [auto] does not\n    correctly instantiate the existential variable. Note that [false*\n    le_gt_false] would not work either, because the star symbol tries\n    to call [auto] first. So, there are two possibilities for\n    completing the proof: either call [false le_gt_false; eauto], or\n    call [false* (le_gt_false 3)]. *)\n\n\n(* ================================================================= *)\n(** ** Automation for Transitivity Lemmas *)\n\n(** Some lemmas should never be added as hints, because they would\n    very badly slow down proof search. The typical example is that of\n    transitivity results. This section describes the problem and\n    presents a general workaround.\n\n    Consider a subtyping relation, written [subtype S T], that relates\n    two object [S] and [T] of type [typ]. Assume that this relation\n    has been proved reflexive and transitive. The corresponding lemmas\n    are named [subtype_refl] and [subtype_trans]. *)\n\nParameter typ : Type.\n\nParameter subtype : typ -> typ -> Prop.\n\nParameter subtype_refl : forall T,\n  subtype T T.\n\nParameter subtype_trans : forall S T U,\n  subtype S T -> subtype T U -> subtype S U.\n\n(** Adding reflexivity as hint is generally a good idea,\n    so let's add reflexivity of subtyping as hint. *)\n\nHint Resolve subtype_refl.\n\n(** Adding transitivity as hint is generally a bad idea.  To\n    understand why, let's add it as hint and see what happens.\n    Because we cannot remove hints once we've added them, we are going\n    to open a \"Section,\" so as to restrict the scope of the\n    transitivity hint to that section. *)\n\nSection HintsTransitivity.\n\nHint Resolve subtype_trans.\n\n(** Now, consider the goal [forall S T, subtype S T], which clearly has\n    no hope of being solved. Let's call [eauto] on this goal. *)\n\nLemma transitivity_bad_hint_1 : forall S T,\n  subtype S T.\nProof.\n  intros. (* debug *) eauto. (* Investigates 106 applications... *)\nAbort.\n\n(** Note that after closing the section, the hint [subtype_trans]\n    is no longer active. *)\n\nEnd HintsTransitivity.\n\n(** In the previous example, the proof search has spent a lot of time\n    trying to apply transitivity and reflexivity in every possible\n    way.  Its process can be summarized as follows. The first goal is\n    [subtype S T]. Since reflexivity does not apply, [eauto] invokes\n    transitivity, which produces two subgoals, [subtype S ?X] and\n    [subtype ?X T]. Solving the first subgoal, [subtype S ?X], is\n    straightforward, it suffices to apply reflexivity. This unifies\n    [?X] with [S]. So, the second sugoal, [subtype ?X T],\n    becomes [subtype S T], which is exactly what we started from...\n\n    The problem with the transitivity lemma is that it is applicable\n    to any goal concluding on a subtyping relation. Because of this,\n    [eauto] keeps trying to apply it even though it most often doesn't\n    help to solve the goal. So, one should never add a transitivity\n    lemma as a hint for proof search. *)\n\n(** There is a general workaround for having automation to exploit\n    transitivity lemmas without giving up on efficiency. This workaround\n    relies on a powerful mechanism called \"external hint.\" This\n    mechanism allows to manually describe the condition under which\n    a particular lemma should be tried out during proof search.\n\n    For the case of transitivity of subtyping, we are going to tell\n    Coq to try and apply the transitivity lemma on a goal of the form\n    [subtype S U] only when the proof context already contains an\n    assumption either of the form [subtype S T] or of the form\n    [subtype T U]. In other words, we only apply the transitivity\n    lemma when there is some evidence that this application might\n    help.  To set up this \"external hint,\" one has to write the\n    following. *)\n\nHint Extern 1 (subtype ?S ?U) =>\n  match goal with\n  | H: subtype S ?T |- _ => apply (@subtype_trans S T U)\n  | H: subtype ?T U |- _ => apply (@subtype_trans S T U)\n  end.\n\n(** This hint declaration can be understood as follows.\n    - \"Hint Extern\" introduces the hint.\n    - The number \"1\" corresponds to a priority for proof search.\n      It doesn't matter so much what priority is used in practice.\n    - The pattern [subtype ?S ?U] describes the kind of goal on\n      which the pattern should apply. The question marks are used\n      to indicate that the variables [?S] and [?U] should be bound\n      to some value in the rest of the hint description.\n    - The construction [match goal with ... end] tries to recognize\n      patterns in the goal, or in the proof context, or both.\n    - The first pattern is [H: subtype S ?T |- _]. It indices that\n      the context should contain an hypothesis [H] of type\n      [subtype S ?T], where [S] has to be the same as in the goal,\n      and where [?T] can have any value.\n    - The symbol [|- _] at the end of [H: subtype S ?T |- _] indicates\n      that we do not impose further condition on how the proof\n      obligation has to look like.\n    - The branch [=> apply (@subtype_trans S T U)] that follows\n      indicates that if the goal has the form [subtype S U] and if\n      there exists an hypothesis of the form [subtype S T], then\n      we should try and apply transitivity lemma instantiated on\n      the arguments [S], [T] and [U]. (Note: the symbol [@] in front of\n      [subtype_trans] is only actually needed when the \"Implicit Arguments\"\n      feature is activated.)\n    - The other branch, which corresponds to an hypothesis of the form\n      [H: subtype ?T U] is symmetrical.\n\n    Note: the same external hint can be reused for any other transitive\n    relation, simply by renaming [subtype] into the name of that relation. *)\n\n(** Let us see an example illustrating how the hint works. *)\n\nLemma transitivity_workaround_1 : forall T1 T2 T3 T4,\n  subtype T1 T2 -> subtype T2 T3 -> subtype T3 T4 -> subtype T1 T4.\nProof.\n  intros. (* debug *) eauto. (* The trace shows the external hint being used *)\nQed.\n\n(** We may also check that the new external hint does not suffer from the\n    complexity blow up. *)\n\nLemma transitivity_workaround_2 : forall S T,\n  subtype S T.\nProof.\n  intros. (* debug *) eauto. (* Investigates 0 applications *)\nAbort.\n\n\n(* ################################################################# *)\n(** * Decision Procedures *)\n\n(** A decision procedure is able to solve proof obligations whose\n    statement admits a particular form. This section describes three\n    useful decision procedures. The tactic [omega] handles goals\n    involving arithmetic and inequalities, but not general\n    multiplications.  The tactic [ring] handles goals involving\n    arithmetic, including multiplications, but does not support\n    inequalities. The tactic [congruence] is able to prove equalities\n    and inequalities by exploiting equalities available in the proof\n    context. *)\n\n\n(* ================================================================= *)\n(** ** Omega *)\n\n(** The tactic [omega] supports natural numbers (type [nat]) as well as\n    integers (type [Z], available by including the module [ZArith]).\n    It supports addition, substraction, equalities and inequalities.\n    Before using [omega], one needs to import the module [Omega],\n    as follows. *)\n\nRequire Import Omega.\n\n(** Here is an example. Let [x] and [y] be two natural numbers\n    (they cannot be negative). Assume [y] is less than 4, assume\n    [x+x+1] is less than [y], and assume [x] is not zero. Then,\n    it must be the case that [x] is equal to one. *)\n\nLemma omega_demo_1 : forall (x y : nat),\n  (y <= 4) -> (x + x + 1 <= y) -> (x <> 0) -> (x = 1).\nProof. intros. omega. Qed.\n\n(** Another example: if [z] is the mean of [x] and [y], and if the\n    difference between [x] and [y] is at most [4], then the difference\n    between [x] and [z] is at most 2. *)\n\nLemma omega_demo_2 : forall (x y z : nat),\n  (x + y = z + z) -> (x - y <= 4) -> (x - z <= 2).\nProof. intros. omega. Qed.\n\n(** One can proof [False] using [omega] if the mathematical facts\n    from the context are contradictory. In the following example,\n    the constraints on the values [x] and [y] cannot be all\n    satisfied in the same time. *)\n\nLemma omega_demo_3 : forall (x y : nat),\n  (x + 5 <= y) -> (y - x < 3) -> False.\nProof. intros. omega. Qed.\n\n(** Note: [omega] can prove a goal by contradiction only if its\n    conclusion reduces to [False]. The tactic [omega] always fails\n    when the conclusion is an arbitrary proposition [P], even though\n    [False] implies any proposition [P] (by [ex_falso_quodlibet]). *)\n\nLemma omega_demo_4 : forall (x y : nat) (P : Prop),\n  (x + 5 <= y) -> (y - x < 3) -> P.\nProof.\n  intros.\n  (* Calling [omega] at this point fails with the message:\n    \"Omega: Can't solve a goal with proposition variables\" *)\n  (* So, one needs to replace the goal by [False] first. *)\n  false. omega.\nQed.\n\n\n(* ================================================================= *)\n(** ** Ring *)\n\n(** Compared with [omega], the tactic [ring] adds support for\n    multiplications, however it gives up the ability to reason on\n    inequations. Moreover, it supports only integers (type [Z]) and\n    not natural numbers (type [nat]). Here is an example showing how\n    to use [ring]. *)\n\nModule RingDemo.\n  Require Import ZArith.\n  Open Scope Z_scope.\n  (* Arithmetic symbols are now interpreted in [Z] *)\n\nLemma ring_demo : forall (x y z : Z),\n    x * (y + z) - z * 3 * x\n  = x * y - 2 * x * z.\nProof. intros. ring. Qed.\n\nEnd RingDemo.\n\n\n(* ================================================================= *)\n(** ** Congruence *)\n\n(** The tactic [congruence] is able to exploit equalities from the\n    proof context in order to automatically perform the rewriting\n    operations necessary to establish a goal. It is slightly more\n    powerful than the tactic [subst], which can only handle equalities\n    of the form [x = e] where [x] is a variable and [e] an\n    expression. *)\n\nLemma congruence_demo_1 :\n   forall (f : nat->nat->nat) (g h : nat->nat) (x y z : nat),\n   f (g x) (g y) = z ->\n   2 = g x ->\n   g y = h z ->\n   f 2 (h z) = z.\nProof. intros. congruence. Qed.\n\n(** Moreover, [congruence] is able to exploit universally quantified\n    equalities, for example [forall a, g a = h a]. *)\n\nLemma congruence_demo_2 :\n   forall (f : nat->nat->nat) (g h : nat->nat) (x y z : nat),\n   (forall a, g a = h a) ->\n   f (g x) (g y) = z ->\n   g x = 2 ->\n   f 2 (h y) = z.\nProof. congruence. Qed.\n\n(** Next is an example where [congruence] is very useful. *)\n\nLemma congruence_demo_4 : forall (f g : nat->nat),\n  (forall a, f a = g a) ->\n  f (g (g 2)) = g (f (f 2)).\nProof. congruence. Qed.\n\n(** The tactic [congruence] is able to prove a contradiction if the\n    goal entails an equality that contradicts an inequality available\n    in the proof context. *)\n\nLemma congruence_demo_3 :\n   forall (f g h : nat->nat) (x : nat),\n   (forall a, f a = h a) ->\n   g x = f x ->\n   g x <> h x ->\n   False.\nProof. congruence. Qed.\n\n(** One of the strengths of [congruence] is that it is a very fast\n    tactic. So, one should not hesitate to invoke it wherever it might\n    help. *)\n\n(* ################################################################# *)\n(** * Summary *)\n\n(** Let us summarize the main automation tactics available.\n\n    - [auto] automatically applies [reflexivity], [assumption], and [apply].\n\n    - [eauto] moreover tries [eapply], and in particular can instantiate\n      existentials in the conclusion.\n\n    - [iauto] extends [eauto] with support for negation, conjunctions, and\n      disjunctions. However, its support for disjunction can make it\n      exponentially slow.\n\n    - [jauto] extends [eauto] with support for  negation, conjunctions, and\n      existential at the head of hypothesis.\n\n    - [congruence] helps reasoning about equalities and inequalities.\n\n    - [omega] proves arithmetic goals with equalities and inequalities,\n      but it does not support multiplication.\n\n    - [ring] proves arithmetic goals with multiplications, but does not\n      support inequalities.\n\n    In order to set up automation appropriately, keep in mind the following\n    rule of thumbs:\n\n    - automation is all about balance: not enough automation makes proofs\n      not very robust on change, whereas too much automation makes proofs\n      very hard to fix when they break.\n\n    - if a lemma is not goal directed (i.e., some of its variables do not\n      occur in its conclusion), then the premises need to be ordered in\n      such a way that proving the first premises maximizes the chances of\n      correctly instantiating the variables that do not occur in the conclusion.\n\n    - a lemma whose conclusion is [False] should only be added as a local\n      hint, i.e., as a hint within the current section.\n\n    - a transitivity lemma should never be considered as hint; if automation\n      of transitivity reasoning is really necessary, an [Extern Hint] needs\n      to be set up.\n\n    - a definition usually needs to be accompanied with a [Hint Unfold].\n\n    Becoming a master in the black art of automation certainly requires\n    some investment, however this investment will pay off very quickly.\n*)\n\n(** $Date: 2016-07-13 12:41:41 -0400 (Wed, 13 Jul 2016) $ *)\n", "meta": {"author": "coqoon", "repo": "Software-Foundations", "sha": "a327b63aa8ff8543ae2cedee7a5960da05bbfaa7", "save_path": "github-repos/coq/coqoon-Software-Foundations", "path": "github-repos/coq/coqoon-Software-Foundations/Software-Foundations-a327b63aa8ff8543ae2cedee7a5960da05bbfaa7/Software Foundations/src/SF/UseAuto.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.28908008941461566}}
{"text": "\n\nRequire Import stdpp.tactics.\nRequire Import stdpp.fin_sets.\n\nRequire Import LocalTactics.\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nRequire Import DecEq.\nRequire Import SXML.\n\nRequire Import Steps.\nRequire Import IO.\n\n\nRequire Import SyntaxParams.\nRequire Import HeapParams.\nModule Globalization(varParams: SyntaxParams)(heapParams: HeapParams).\n  Module Import SXML_ := SXML.SXML varParams heapParams.\n\n\n(************\n\nDefinitions for globalization\n\n ************)\n\nFixpoint elim_defs\n         (vars: list var) (e: exp): exp\n  :=\n    match e with\n    | letsmall x se er =>\n      if member x vars\n      then (elim_defs vars er)\n      else letsmall x se (elim_defs vars er)\n    | letabs x xl el er =>\n      if member x vars\n      then (elim_defs vars er)\n      else letabs x xl (elim_defs vars el) (elim_defs vars er)\n    | branch vb et ef =>\n      branch vb\n        (elim_defs vars et)\n        (elim_defs vars ef)\n    | tail vf va => tail vf va\n    | ret x => ret x\n    end.\n\nTheorem elim_defs_nil :\n  forall e, elim_defs [] e = e.\nProof.\n  intros. induction e; simpl.\n  - rewrite -> IHe. reflexivity.\n  - rewrite -> IHe1. rewrite -> IHe2. reflexivity.\n  - rewrite -> IHe1. rewrite -> IHe2. reflexivity.\n  - reflexivity.\n  - reflexivity.\nQed.\nHint Resolve elim_defs_nil.\n\nLemma elim_defs_app :\n  forall ds1 ds2 e,\n    elim_defs ds1 (elim_defs ds2 e) =\n    elim_defs (ds1 ++ ds2) e.\nProof.\n  intros.\n  induction e; simpl; try solve [f_equal; assumption].\n  (* let small *)\n  - destruct (member v ds2); destruct (member v (ds1 ++ ds2)); simpl.\n    + exact IHe.\n    + destruct (member v ds1);\n      exfalso; apply n; apply in_or_app; right; assumption.\n    + destruct (member v ds1).\n      * exact IHe.\n      * rewrite -> in_app_iff in i.\n        destruct i; contradiction.\n    + destruct (member v ds1).\n      * exfalso. apply n0. apply in_or_app.\n        left. exact i.\n      * f_equal. exact IHe.\n  (* let abs *)\n  - destruct (member v ds2); destruct (member v (ds1 ++ ds2)); simpl.\n    + exact IHe2.\n    + exfalso. apply n. apply in_or_app; right; assumption.\n    + destruct (member v ds1).\n      * exact IHe2.\n      * rewrite -> in_app_iff in i.\n        destruct i; contradiction.\n    + destruct (member v ds1).\n      * exfalso. apply n0. apply in_or_app; left; assumption.\n      * f_equal; assumption.\nQed.\nHint Resolve elim_defs_app.\n\nLemma elim_defs_comm :\n  forall ds1 ds2 e,\n    elim_defs ds1 (elim_defs ds2 e) =\n    elim_defs ds2 (elim_defs ds1 e).\nProof.\n  intros.\n  induction e; simpl;\n  try solve [f_equal; assumption].\n  - destruct (member v ds1); destruct (member v ds2).\n    + assumption.\n    + rewrite <- IHe. simpl.\n      destruct (member v ds1); try contradiction. reflexivity.\n    + rewrite -> IHe. simpl.\n      destruct (member v ds2); try contradiction. reflexivity.\n    + simpl; destruct (member v ds1); destruct (member v ds2);\n        try contradiction.\n      f_equal. assumption.\n  - destruct (member v ds1); destruct (member v ds2).\n    + assumption.\n    + rewrite <- IHe2. simpl.\n      destruct (member v ds1); try contradiction. reflexivity.\n    + rewrite -> IHe2. simpl.\n      destruct (member v ds2); try contradiction. reflexivity.\n    + simpl; destruct (member v ds1); destruct (member v ds2);\n        try contradiction.\n      f_equal; assumption.\nQed.\n\nInductive defined var\n:=\n  | dtuple : list var -> defined var\n  | dabs : var -> exp -> defined var                                \n  | dconst : bool -> defined var\n.\n\nInductive defined_svalue (defs2: list (var * value)) : defined var -> svalue -> Prop\n  :=\n  | defined_stuple xs vals :\n      searches xs defs2 = Some vals ->\n      defined_svalue defs2 (dtuple _ xs) (stuple vals)\n  | defined_sclos xl cl el :\n      (forall x,\n          free_in x cl ->\n          x <> xl -> \n          exists v,\n          defs2 !! x = Some v /\\ el !! x = Some v) ->\n      defined_svalue defs2 (dabs _ xl cl) (sclos (xl, cl, el))\n.\nInductive defined_value : defined var -> value -> Prop\n  :=\n  | defined_tuple_vaddr xs a :\n      defined_value (dtuple _ xs) (vaddr a)\n  | defined_clos_vaddr xl el a :\n      defined_value (dabs _ xl el) (vaddr a)\n  | defined_vconst b :\n      defined_value (dconst _ b) (vconst b)\n.\n\nDefinition bind_defined (x: var) (def: defined var) (er: exp): exp\n  :=\n    match def with\n    | dtuple _ se => letsmall x (tupleExp se) er\n    | dconst _ b => letsmall x (constExp b) er\n    | dabs _ xl el => letabs x xl el er\n    end.\n\nFixpoint bind_globals \n         (terms: list (var * defined var)) (e: exp) : exp\n  :=\n    match terms with\n    | [] => e\n    | (bv, bd) :: ts => bind_globals ts (bind_defined bv bd e)\n    end.\nLemma bind_globals_app :\n  forall t1 t2 e,\n    bind_globals (t1 ++ t2) e =\n    bind_globals t2 (bind_globals t1 e).\nProof with eauto.\n  intros. generalize dependent e.\n  induction t1; intro e...\n  simpl. destruct a. apply IHt1.\nQed.\n\n(* Definition of globalize *)\nDefinition globalize \n         (terms: list (var * defined var)) (e: exp) : exp\n  :=\n    bind_globals terms (elim_defs (map fst terms) e).\n\nLemma globalize_nil :\n  forall p,\n    globalize [] p = p.\nProof.\n  intros; unfold globalize; simpl.\n  apply elim_defs_nil.\nQed.\nHint Resolve globalize_nil.\n\nInductive var_in_def : var -> defined var -> Prop\n  :=\n  | dv_tuple v vs :\n      In v vs ->\n      var_in_def v (dtuple _ vs)\n  | dv_abs v xl el :\n      free_in v el ->\n      v <> xl ->\n      var_in_def v (dabs _ xl el)\n.\nHint Constructors var_in_def.\n\nInductive defs_well_scoped : list (var * defined var) -> Type\n  (* in Type for random technical reasons to do with existentials *)\n  :=\n  | dv_nil : defs_well_scoped []\n  | dv_cons v d ds :\n      (forall v,\n        var_in_def v d ->\n        In v (map fst ds)) ->\n      defs_well_scoped ds ->\n      defs_well_scoped ((v, d) :: ds)\n.\nHint Constructors defs_well_scoped.\n\nLemma defs_well_scoped_drop : forall defs n,\n    defs_well_scoped defs ->\n    defs_well_scoped (drop n defs).\nProof with eauto.\n  intros.\n  generalize dependent n.\n  induction defs; intros.\n  - destruct n...\n  - destruct n; simpl.\n    + exact X.\n    + inversion X; subst.\n      apply IHdefs...\nQed.\n\nLemma map_option_all_some {X Y} : forall (f: X -> option Y) vs,\n    (forall v, In v vs -> { v2 : Y & f v = Some v2 }) ->\n    { vs2 & map_option f vs = Some vs2 }.\nProof.\n  intros. induction vs; simpl.\n  - eexists; reflexivity.\n  - destruct (X0 a) as [v2 ->].\n    + repeat constructor.\n    + destruct IHvs as [vs2 ->].\n      * intros. apply X0.\n        right. auto.\n      * eexists; reflexivity.\nQed.\n\n(************\n\nProofs about globalization\n\n ************)\n\n(* ..., If it's concrete the instance resolver has no problem,\n    no clue why it needs the extra help *)\nDefinition def_in_scope bd (e : env) := forall v, var_in_def v bd -> { vl & search v e = Some vl }.\n\nTheorem lookup_store_path_after_extend :\n  forall (h h': heap svalue) (a: addr) (sval: svalue),\n    forall (alloc1: alloc h sval = (a, h')),\n    forall (path : store_path) (v1 v2: value),\n      lookup_store_path h v1 path = Some v2 ->\n      lookup_store_path h' v1 path = Some v2.\nProof.\n  intros.\n  generalize dependent v1.\n  pose proof (heap_lookup_earlier _ _ _ _ alloc1) as lookup_carry.\n  induction path; intros; simpl in *; destruct v1; try done;\n    destruct (h !! a0) eqn:lookup1; subst; try discriminate;\n    rewrite -> (heap_lookup_some_later _ _ _ _ alloc1 a0 _ lookup1);\n    repeat case_match; subst; try done;\n    apply IHpath;\n    assumption.\nQed.\n\n(* Define our relations between machine states *)\n\n(* TODO move to set *)\nDefinition image {X Y XS YS : Type} `{Elements X XS} `{Empty YS, Union YS, Singleton Y YS} (f: X -> option Y) (xs : XS) : YS :=\n  list_to_set\n    (filter_map (fun x => f x)\n         (elements xs)).\n\n(*\nDefinition is_image {X Y XS YS} `{ElemOf X XS} `{ElemOf Y YS} (f : X -> option Y) (xs : XS) (ys: YS) :=\n  forall y,\n    elem_of y ys <-> exists x, elem_of x xs /\\ f x = Some y.\n\nTheorem image_is_image {X Y XS YS} `{FinSet X XS} `{SemiSet Y YS} (f : X -> option Y) (xs : XS) :\n  is_image f xs (image (YS:=YS) f xs).\nProof with auto.\n  intros.\n  unfold is_image, image.\n  intro y; split; intros.\n  - rewrite -> elem_of_union_list in H12.\n    destruct H12 as [X0 [X0In yIn]].\n    set_unfold.\n    destruct X0In as [x [? ?]].\n    exists x. subst; set_unfold.\n    done.\n  - rewrite -> elem_of_union_list.\n    set_unfold.\n    destruct H12 as [x [xIn ?]]; subst.\n    eexists.\n    split.\n    + exists x...\n    + rewrite -> H12. set_solver.\nQed.\n\nInstance set_unfold_image {X Y XS YS} `{FSX: FinSet X XS} `{FSY: SemiSet Y YS} {f: X -> option Y} {xs: XS} {y: Y}:\n  SetUnfoldElemOf y (image f xs) (exists x, elem_of x xs /\\ f x = Some y).\nProof.\n  constructor.\n  apply image_is_image.\nQed.\n*)\n\n\nLemma set_union_elements :\n  forall {X XS} `{FinSet X XS},\n    forall (xs: XS),\n    equiv (union_list (map singleton (elements xs))) xs.\nProof with eauto.\n  intros.\n  set_unfold.\n  split; intros.\n  - rewrite -> elem_of_union_list in H7.\n    destruct H7 as [X0 [X0In xIn]].\n    remember (elements xs) as xs'.\n    generalize dependent xs.\n    induction xs'; intros; subst; simpl in *.\n    + apply not_elem_of_nil in X0In. contradiction.\n    + set_unfold.\n      destruct X0In.\n      (* head *)\n      * subst. set_unfold. subst.\n        rewrite <- elem_of_elements.\n        rewrite <- Heqxs'.\n        constructor.\n      (* rest *)\n      * destruct H7 as [? [? yIn]].\n        subst. set_unfold. subst.\n        rewrite <- elem_of_elements.\n        rewrite -> elem_of_list_In in *.\n        rewrite <- Heqxs'.\n        right. assumption.\n  - rewrite -> elem_of_union_list.\n    exists (singleton x).\n    set_unfold.\n    split...\nQed.\n\nLemma image_union (addrs1 addrs2: addrs) f :\n    equiv (image f (union addrs1 addrs2))\n          (union (image f addrs1 : addrs) (image f addrs2 : addrs)).\nProof with eauto.\n  intros.\n  unfold image.\n  set_unfold.\n  intro x.\n  split; intros; deep_set_unfold.\n  - destruct H...\n  - destruct H; deprod...\nQed.\n\n(*\nLemma image_singleton (a1: addr) (af: addr -> option addr) :\n    equiv (image af ({[ a1 ]} : addrs))\n          (match (af a1) with\n           | Some a2 => {[ a2 ]}\n           | None => empty\n           end: addrs).\nProof with eauto.\n  unfold image. set_unfold.\n  intro.\n  rewrite -> elem_of_union_list.\n  split; intros; deep_set_unfold...\n  repeat eexists...\n  set_solver.\nQed.\n*)\n\n(* We need to have both future and past defs, because lifting a lambda will require eliminating\n   definitions before lifting it *)\nFixpoint defs_agree (defs: list (var * defined var)) (c: exp) {struct c} : Prop\n  :=\n  match c with\n  | letsmall v s cr =>\n    match s with\n    | tupleExp vs =>\n      match search v defs with\n      | Some (dtuple _ vs') => vs = vs' /\\ defs_agree defs cr\n      | Some _ => False\n      | None => defs_agree defs cr\n      end\n    | constExp b =>\n      match search v defs with\n      | Some (dconst _ b') => b = b' /\\ defs_agree defs cr\n      | Some _ => False\n      | None => defs_agree defs cr\n      end\n    | _ =>\n      match member v (map fst defs) with\n      | left _ => False\n      | right _ => defs_agree defs cr\n      end\n    end\n  | letabs v vl cl cr =>\n    match search v defs with\n    | Some (dabs _ vl' cl') => ~ In vl (map fst defs) /\\ vl = vl' /\\ elim_defs (map fst defs) cl = cl' /\\\n        defs_agree defs cl /\\ defs_agree defs cr\n    | Some _ => False\n    | None => ~ In vl (map fst defs) /\\ defs_agree defs cl /\\ defs_agree defs cr\n    end\n  | branch vb ct cf =>\n    defs_agree defs ct /\\ defs_agree defs cf\n  | tail _ _ => True\n  | ret _ => True\n  end.\n\nSection Relations.\n  Definition address_relation := list (addr * addr).\n\n  Definition code_related (defs : list (var * defined var)) (remaining: nat) c cg\n    := bind_globals (take remaining defs) (elim_defs (map fst defs) c) = cg /\\\n       defs_agree defs c.\n\n  Inductive val_related (ar: address_relation) : value -> value -> Prop :=\n  | vconst_related b : val_related ar (vconst b) (vconst b)\n  | vaddr_related a ag :\n      search a ar = Some ag ->\n      val_related ar (vaddr a) (vaddr ag).\n  Inductive env_related (ar: address_relation) defspast (xs xsg : vars): env -> env -> Prop :=\n  | env_vals_related e eg:\n      forall\n        (live_vars:\n           forall x,\n             elem_of x xs ->\n             e !! x <> None)\n      (pairs_related:\n         forall x v,\n          elem_of x xs ->\n          elem_of x xsg ->\n          e !! x = Some v ->\n          exists vg,\n          eg !! x = Some vg /\\\n          val_related ar v vg)\n      (global_vals_agree:\n         forall (x: var) (v vg: value),\n           In (x, vg) defspast ->\n           elem_of x xs ->\n           e !! x = Some v ->\n           val_related ar v vg)\n      (globals_present:\n         forall (x: var) (vg: value),\n           In (x, vg) defspast ->\n           elem_of x xsg ->\n             eg !! x = Some vg),\n      env_related ar defspast xs xsg e eg.\n  Inductive clos_related (ar: address_relation) (defs : list (var * defined var)) (defspast : list (var * value)): clos -> clos -> Prop :=\n  | clos_parts_related xl el cl elg clg :\n      code_related defs 0 cl clg ->\n      ~ In xl (map fst defspast) ->\n      env_related ar defspast\n                  (difference (free_vars cl) {[ xl ]})\n                  (difference (free_vars clg) {[ xl ]}) el elg ->\n      clos_related ar defs defspast (xl, cl, el) (xl, clg, elg).\n  Inductive sval_related ar defs defspast : svalue -> svalue -> Prop :=\n  | stuple_related vs vsg :\n      Forall2 (val_related ar) vs vsg ->\n      sval_related ar defs defspast (stuple vs) (stuple vsg)\n  | sclos_related clos closg :\n      clos_related ar defs defspast clos closg ->\n      sval_related ar defs defspast (sclos clos) (sclos closg).\n  Inductive stack_related ar defs defspast : list clos -> list clos -> Prop :=\n  | stack_nil_related :\n      stack_related ar defs defspast [] []\n  | stack_cons_related clos k closg kg :\n      clos_related ar defs defspast clos closg ->\n      stack_related ar defs defspast k kg ->\n      stack_related ar defs defspast (clos :: k) (closg :: kg).\n\n  Inductive heap_related ar defs defspast (h hg : heap svalue) :=\n  | heap_vals_related :\n      forall \n        (related_addrs:\n           forall (a: addr) sv, h !! a = Some sv ->\n                        exists ag svg,\n                          search a ar = Some ag /\\\n                          hg !! ag = Some svg /\\\n                          sval_related ar defs defspast sv svg)\n        (global_addrs:\n           (* Each variable has a past definitions\n              only for bindings before it *)\n           forall x v,\n             In (x, v) defspast ->\n                match v with\n                  (* incorrect value handled in env *)\n                | vaddr ag =>\n                  exists d svg,\n                  In (x, d) defs /\\\n                  hg !! ag = Some svg /\\\n                  defined_svalue defspast d svg\n                | _ => True\n                end),\n    heap_related ar defs defspast h hg.\n\n  Inductive state_related ar defs defspast remaining : state -> state -> Prop :=\n  | state_parts_related c e h k cg eg hg kg :\n      forall\n            (* addresses handled in heap *)\n            (defspast_sound_val:\n               forall x v, In (x, v) defspast -> exists d,\n                   In (x, d) defs /\\\n                   defined_value d v)\n            (defspast_same :\n               map fst defspast = drop remaining (map fst defs))\n            (defspast_valid :\n               valid_in_heap defspast hg)\n            (ar_heap_dom:\n               forall a ag,\n                 In (a, ag) ar ->\n                 h !! a <> None /\\ hg !! ag <> None)\n            (code_rel:\n              code_related defs remaining c cg)\n            (env_rel:\n              env_related ar defspast (free_vars c) (free_vars cg) e eg)\n            (heap_rel:\n              heap_related ar defs defspast h hg)\n            (stack_rel:\n               stack_related ar defs defspast k kg)\n            (ar_nodup:\n               NoDup (map fst ar)),\n      state_related ar defs defspast remaining (<< c, e, h, k >>) (<< cg, eg, hg, kg >>)\n  .\n\n  Lemma exists_fun_p {X Y} (P : Y -> Prop) :\n    forall (x: X) (y: Y) (f: X -> option Y),\n    (exists y, f x = Some y /\\ P y) ->\n    f x = Some y ->\n    P y.\n  Proof.\n    intros.\n    destruct H as [y0 [? ?]]; simplify_eq.\n    done.\n  Qed.\n\n  Lemma env_lookup_related : forall ar defspast xs xsg e eg x v vg,\n      env_related ar defspast xs xsg e eg ->\n      elem_of x xs ->\n      elem_of x xsg ->\n      e !! x = Some v ->\n      eg !! x = Some vg ->\n      val_related ar v vg.\n  Proof with eauto.\n    intros.\n    destruct H.\n    apply exists_fun_p with x (eg !!)...\n  Qed.\n\n  Lemma env_lookups_related : forall ar defspast fvs fvsg e eg xs vs vgs,\n      env_related ar defspast fvs fvsg e eg ->\n      (forall x, In x xs -> elem_of x fvs) ->\n      (forall x, In x xs -> elem_of x fvsg) ->\n      searches xs e = Some vs ->\n      searches xs eg = Some vgs ->\n      Forall2 (val_related ar) vs vgs.\n  Proof.\n    unfold searches.\n    intros.\n    generalize dependent vgs.\n    generalize dependent vs.\n    induction xs; simpl in *; intros vs eqvs vgs eqvgs; simplify_eq.\n    - constructor.\n    - forced (search a e).\n      forced (map_option (flip search e) xs).\n      forced (search a eg).\n      forced (map_option (flip search eg) xs).\n      simplify_eq.\n      constructor.\n      { eapply env_lookup_related; eauto. }\n      apply (IHxs (fun x fi => H0 x (or_intror fi)) (fun x fi => H1 x (or_intror fi)) l eq_refl l0 eq_refl).\n  Qed.\n\n  Lemma heap_lookup_related : forall {ar defs defspast h hg a ag sv svg},\n      heap_related ar defs defspast h hg ->\n      search a ar = Some ag ->\n      h !! a = Some sv ->\n      hg !! ag = Some svg ->\n      sval_related ar defs defspast sv svg.\n  Proof with eauto.\n    intros.\n    destruct H.\n    destruct (related_addrs a sv H1).\n    deprod.\n    simplify_eq...\n  Qed.\n\n\n  End Relations.\n  Hint Constructors val_related env_related clos_related sval_related stack_related heap_related state_related : related.\n  Hint Resolve env_lookup_related env_lookups_related heap_lookup_related : related.\n\n  (* For consistency, some relations are constructors with one variant,\n     so force them to unfold during search *)\n  Ltac unfold_simple_related :=\n    repeat match goal with\n    | H: code_related _ _ _ _ |- _ => unfold code_related in H\n    | H: clos_related _ _ _ _ |- _ => destruct H\n    | H: env_related _ _ _ _ |- _ => destruct H\n    | H: heap_related _ _ _ _ |- _ => destruct H\n    end.\n    \n(* Compatibility over heap extensions in both left and right sides *)\n  \n  (* Extending environments by related values are related *)\n\nLemma val_relate_alloc :\n  forall a ag ar v1 v2,\n    ~ addr_in v1 a ->\n    val_related ar v1 v2 ->\n    val_related ((a, ag) :: ar) v1 v2.\nProof with eauto.\n  intros.\n  inversion H0; subst; constructor.\n  simpl.\n  destruct (decEq a0 a); subst...\n  - exfalso...\nQed.\n\nLemma env_relate_new :\n  forall ar defspast xs xsg e1 e2 x v1 v2,\n    env_related ar defspast xs xsg e1 e2 ->\n    ~ In x (map fst defspast) ->\n    val_related ar v1 v2 ->\n    env_related ar defspast (union xs {[x]}) (union xsg {[x]}) ((x, v1) :: e1) ((x, v2) :: e2).\nProof with eauto.\n  intros.\n  destruct H.\n  constructor; intros; unfold lookup in *.\n  - simpl in *.\n    destruct (decEq x0 x); simplify_eq.\n    + discriminate.\n    + set_unfold. destruct H...\n  - simpl in *. destruct (decEq x0 x); simplify_eq.\n    + exists v2. split...\n    + apply pairs_related...\n      set_unfold. destruct H... contradiction.\n      set_unfold. destruct H2... contradiction.\n  - simpl in *.\n    destruct (decEq x0 x); simplify_eq.\n    + exfalso. apply H0. eauto with searches.\n    + apply global_vals_agree with x0...\n      set_unfold. forced H2...\n  - simpl in *.\n    destruct (decEq x0 x); simplify_eq.\n    + exfalso. apply H0. eauto with searches.\n    + apply globals_present...\n      set_unfold.\n      destruct H2...\n      contradiction.\nQed.\n\nLemma env_relate_alloc :\n  forall ar defspast xs xsg e1 e2 a ag,\n    env_related ar defspast xs xsg e1 e2 ->\n    ~ addr_in (e1, xs) a ->\n    env_related ((a, ag) :: ar) defspast xs xsg e1 e2.\nProof with eauto.\n  intros.\n  unfold addr_in, addr_in_env, not in H0.\n  destruct H. constructor...\n  (* pairs_related *)\n  - intros.\n    pose proof (pairs_related x v H H1 H2).\n    deprod.\n    exists vg. split...\n    apply val_relate_alloc...\n    intro.\n    inversion H4; subst.\n    eauto 10 with addr_in.\n    eauto 10 with addr_in.\n  (* *)\n  - intros.\n    pose proof (global_vals_agree x v vg H H1).\n    apply val_relate_alloc...\n    intro.\n    apply H0.\n    eauto 10 with addr_in.\nQed.\n\nLemma env_relate_subset :\n  forall ar defspast xs1 xs2 xsg1 xsg2 e1 e2,\n    env_related ar defspast xs2 xsg2 e1 e2 ->\n    subseteq xs1 xs2 ->\n    subseteq xsg1 xsg2 ->\n    env_related ar defspast xs1 xsg1 e1 e2.\nProof with eauto.\n  intros.\n  set_unfold.\n  destruct H; split; intros...\nQed.\n\nLemma search_head :\n  forall (a1 a2 : addr) ar,\n    search a1 ((a1, a2) :: ar) = Some a2.\nProof.\n  intros. simpl. rewrite -> decEq_refl. reflexivity.\nQed.\n\nHint Resolve env_relate_new env_relate_alloc : related.\n\nLemma stack_relate_alloc defs defspast a1 a2 ar s sg :\n  stack_related ar defs defspast s sg ->\n  ~ addr_in s a1 ->\n  stack_related ((a1, a2) :: ar) defs defspast s sg.\nProof with eauto.\n  intros.\n  induction H; constructor.\n  -- inversion H; subst. constructor...\n     assert (~ addr_in (el, difference (free_vars cl) {[xl]}) a1).\n     { intro. apply H0. eauto with addr_in. }\n     assert (forall x, elem_of x (free_vars cl ∖ {[xl]}) -> free_in x cl).\n     { intros. set_unfold. deprod... rewrite <- in_free_vars_iff_free_in... }\n     eauto with related.\n  -- apply IHstack_related.\n     eauto with addr_in.\nQed.\n\nHint Constructors val_related : related.\nHint Resolve search_head : related.\nHint Resolve val_relate_alloc stack_relate_alloc : related.\n\n\n(************\n Safety hypotheses\n ***********)\n\n\nDefinition defs2_addrs (defs2: list (var * value)): addrs :=\n  list_to_set (filter_map (fun x => value_to_addr (x.2)) defs2).\n\n\nDefinition clos_size_g defVars (cls: clos): nat\n  := match cls with\n      | (xl, el, cl) => 1 + size (difference (difference (free_vars el) {[xl]}) (list_to_set defVars))\n      end.\nDefinition svalue_size_g defVars (sv : svalue): nat\n  :=\n    match sv with\n    | sclos cls => clos_size_g defVars cls\n    | stuple vs => 1 + length vs\n    end.\n\nDefinition addrs_space_g defVars h (addrs1: addrs) :=\n    space_of (svalue_size_g defVars) h addrs1.\n\nInstance addrs_space_g_equiv {h defVars} : Proper (equiv ==> eq) (addrs_space_g defVars h).\nProof.\n  unfold Proper, respectful.\n  intros.\n  unfold addrs_space_g.\n  enough (Permutation (elements x) (elements y)).\n  unfold space_of.\n  rewrite -> H0. done.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nLemma clos_size_g_lt :\n  forall defVars clos,\n    clos_size_g defVars clos <= clos_size clos.\nProof.\n  intros.\n  unfold clos_size_g, clos_size.\n  destruct clos0 as [[xl cl] el].\n  enough (size (free_vars cl ∖ {[xl]} ∖ list_to_set defVars) <= size (free_vars cl ∖ {[xl]})) by lia.\n  apply subseteq_size.\n  set_solver.\nQed.\nLemma svalue_size_g_lt :\n  forall defVars sv,\n    svalue_size_g defVars sv <= svalue_size sv.\nProof with eauto.\n  intros.\n  destruct sv...\n  simpl. apply clos_size_g_lt.\nQed.\nLemma lookup_size_g_lt :\n  forall defVars h sv,\n    lookup_size (svalue_size_g defVars) h sv <= lookup_size svalue_size h sv.\nProof with eauto.\n  intros.\n  unfold lookup_size.\n  destruct (h !! sv)...\n  apply svalue_size_g_lt.\nQed.\nLemma addrs_space_g_lt :\n  forall defVars h addrs1,\n    addrs_space_g defVars h addrs1 <= space_of svalue_size h addrs1.\nProof with eauto.\n  intros.\n  unfold addrs_space_g, space_of.\n  induction (elements addrs1)...\n  simpl.\n  pose proof (lookup_size_g_lt defVars h a).\n  lia.\nQed.\n\nInductive globalize_safe (ar: address_relation) (defVars: list var) (defs2: list (var * value)) m n : state -> state -> Prop\n  :=\n    mk_globalize_safe c e h k cg eg hg kg :\n      forall\n        (af_safe : forall (addrs1: addrs),\n          closed h addrs1 -> \n          (1 + length defs2) * addrs_space0 h addrs1 + m >=\n          addrs_space0 hg (union (image (flip search ar) addrs1) (defs2_addrs defs2)))\n        (af_safe_g : forall (addrs1: addrs),\n          closed h addrs1 -> \n          addrs_space0 h addrs1 + n >=\n          addrs_space_g defVars hg (union (image (flip search ar) addrs1) (defs2_addrs defs2))),\n\n        globalize_safe\n          ar defVars defs2 m n\n          (<< c, e, h, k >>)%interp\n          (<< cg, eg, hg, kg >>)%interp.\n\n(************\n Main proofs of efficiency / justification\n - Initial steps: pivot through the globals in the target program,\n - Make single step with same head\n - Pivot through skipped source steps, leaving steps with the same head\n\n Thankfully for the single steps, we can split them up,\nbut in the others, Prop-Set divisions mean that they must be together\n ************)\n\nLemma closure_union_list :\n  forall h addrss,\n    heap_valid h ->\n    equiv\n      (closure _ h (union_list addrss))\n      (union_list (map (closure _ h) addrss)).\nProof with eauto.\n  intros.\n  induction addrss; simpl.\n  - apply closure_empty...\n  - rewrite -> closure_union...\n    rewrite -> IHaddrss.\n    reflexivity.\nQed.\n\nInstance image_proper {f} : Proper (equiv ==> equiv) (image f : addrs -> addrs).\nProof.\n  unfold Proper, respectful.\n  intros.\n  set_unfold.\n  set_solver.\nQed.\n\nLemma free_vars_elim_defs :\n  forall c defVars,\n    free_vars (elim_defs defVars c) ⊆ free_vars c ∪ list_to_set defVars.\nProof.\n  intros c defVars. deep_set_unfold.\n  rename H into x_in.\n  induction c; simpl; set_unfold.\n    - destruct (member v defVars) eqn:v_in_defs;\n      simpl in *; set_unfold.\n      + destruct (decEq x v); subst.\n        * right. apply elem_of_list_In; done.\n        * apply IHc in x_in.\n          destruct x_in; eauto.\n      + destruct x_in.\n        * eauto.\n        * destruct H.\n          apply IHc in H.\n          destruct H; eauto.\n    - destruct (member v defVars) eqn:v_in_defs;\n        simpl in *; set_unfold.\n      + apply IHc2 in x_in. destruct x_in; eauto.\n        destruct (decEq x v); subst.\n        * right. apply elem_of_list_In; done.\n        * left. right. done.\n      + destruct x_in.\n        * destruct H. apply IHc1 in H.\n          destruct H; eauto.\n        * destruct H; apply IHc2 in H.\n          destruct H; eauto.\n    - destruct x_in; subst; eauto.\n      destruct H.\n      + apply IHc1 in H.\n        destruct H; eauto.\n      + apply IHc2 in H.\n        destruct H; eauto.\n    - left. done.\n    - left. set_solver.\nQed.\n\nLemma free_vars_bind_globals :\n  forall c defs1 defs2,\n    defs_well_scoped (defs1 ++ defs2) ->\n    free_vars (bind_globals defs1 c) ⊆ free_vars c ∪ list_to_set (map fst (defs1 ++ defs2)).\nProof with eauto with searches free_in.\n  intros.\n  generalize dependent c.\n  induction defs1; intros.\n  - simpl. set_solver.\n  - inversion X; subst.\n    simpl. pose proof (IHdefs1 X0 (bind_defined v d c)).\n    transitivity (free_vars (bind_defined v d c) ∪ list_to_set (map fst (defs1 ++ defs2)))...\n    apply union_least; try solve [clear; set_solver].\n\n    clear H.\n    destruct d; simpl.\n    + set_unfold. intros.\n      pose proof (H0 x) as ix.\n      rewrite <- elem_of_list_In in ix.\n      deep_set_unfold.\n      destruct H; deprod...\n      right. right...\n    + set_unfold. intros.\n      pose proof (H0 x) as ix.\n      rewrite <- elem_of_list_In in ix.\n      deep_set_unfold.\n      destruct H; deprod...\n      right. right.\n      apply ix. constructor...\n    + set_unfold. intros.\n      forced H. deprod.\n      left...\nQed.\n\nLemma free_vars_related :\n  forall c defs remaining,\n    defs_well_scoped defs ->\n    free_vars (bind_globals (take remaining defs) (elim_defs (map fst defs) c)) ⊆\n              free_vars c ∪ list_to_set (map fst defs).\nProof with eauto.\n  intros.\n  transitivity (free_vars (elim_defs (map fst defs) c) ∪ list_to_set (map fst defs)).\n  - rewrite <- (take_drop remaining defs) at 2 3 4.\n    apply free_vars_bind_globals.\n    rewrite -> take_drop. exact X.\n  - apply union_least...\n    + apply free_vars_elim_defs.\n    + set_unfold. intros. deep_set_unfold.\n      right. exists (v, d).\n      repeat rewrite -> elem_of_list_In in *.\n      split...\nQed.\n\n(*** Initial Steps ***)\n\n(* Prove only safety, first, the relatedness comes in trivially\n   since the source program hasn't moved, and including it in here adds\n   extra requirements that muddy the induction.\n   We'll make sure all globals are live though and then re-establish relation. *)\n\n(* (addrs_space0 (iheap st) (defs2_addrs defs2)) *)\n\n    (* use code relation to split free variables correctly *)\n(* *)\n\n\nDefinition has_globals (defs2 : list (var * value)) (eg: env): Prop\n  :=\n    forall (x: var) v,\n    eg !! x = Some v <->\n    defs2 !! x = Some v.\n\nLemma in_fst_pair : forall {A B} x (ps : list (A * B)),\n    In x (map fst ps) ->\n    exists y, In (x, y) ps.\nProof with auto.\n  intros.\n  induction ps; try contradiction.\n  destruct H; subst.\n  - destruct a; simpl.\n    exists b...\n  - destruct (IHps H) as [y iny].\n    exists y. right...\nQed.\n\nLemma defined_svalue_extend : forall d sv defs x v,\n    ~ In x (map fst defs) ->\n    defined_svalue defs d sv ->\n    defined_svalue ((x, v) :: defs) d sv.\nProof with eauto.\n  intros.\n  destruct H0; constructor.\n  - unfold searches in *.\n    generalize dependent vals.\n    induction xs; intros vals lkps.\n    + simpl in *; congruence.\n    + simpl in *. destruct (decEq a x).\n      { subst. exfalso. apply H.\n        forced (search x defs). eauto with searches. }\n      forced (search a defs).\n      forced (map_option (flip search defs) xs).\n      simplify_eq.\n      rewrite -> IHxs with l...\n  - intros.\n    pose proof (H0 x0 H1 H2).\n    deprod.\n    exists v0. split...\n    simpl. destruct (decEq x0 x).\n    { subst. exfalso. apply H. eauto with searches. }\n    unfold lookup. simpl.\n    eauto with decEq.\nQed.\n\nLemma inner_scoped :\n  forall bx bd defs x,\n    defs_well_scoped defs ->\n\n    In (bx, bd) defs ->\n    var_in_def x bd ->\n    In x (map fst defs).\nProof with eauto.\n  intros. induction defs...\n  simpl in *.\n  inversion X; subst.\n  destruct H; simplify_eq; right...\nQed.\n\n\nLemma searches_extend x y (ps:env) ys l :\n  ~ In x (map fst ps) ->\n  searches l ps = Some ys ->\n  searches l ((x, y) :: ps) = Some ys.\nProof with eauto with searches.\n  intros.\n  generalize dependent ys.\n  unfold searches.\n  induction l; simpl; intros...\n  (* cons *)\n  forced (search a ps).\n  forced (map_option (flip search ps) l).\n  simplify_eq.\n  destruct (decEq a x); subst...\n  { contradict H... }\n  rewrite -> (IHl l0)...\nQed.\n\nDefinition defined_size (d: defined var) :=\n  match d with\n  | dconst _ _ => 0\n  | dabs _ xl cl => 1 + size (difference (free_vars cl) {[xl]})\n  | dtuple _ xs => 1 + length xs\n  end.\n\nDefinition defined_size_g defVars (d: defined var) :=\n  match d with\n  | dconst _ _ => 0\n  | dabs _ xl cl => 1 + size (difference (difference (free_vars cl) {[xl]}) (list_to_set defVars))\n  | dtuple _ xs => 1 + length xs\n  end.\n\nTheorem initial_step :\n  (* Take one step in the target,\n     given original state just before\n     the binding (bx, bd), incorporate it into\n     the definitions present in the environment\n\n     |     ...    |\n     |  defspast  |\n     +------------+\n     |  (bx, bd)  |\n     +------------+\n     | defsfuture |\n     |     ...    |\n\n     In effect, elements will be filtered from\n     the defsfuture portion into defspast, eventually being the identity\n     This is true without transparency since it appears in the type signature.\n\n     The environment eg serves as both the lookup for definitions, and the\n     environment of steps, but future steps will leave the definitions portion unchanged\n\n     It is important that defspast and the environment are equivalent so that e.g.\n     projections are still known to be in the globals\n  *)\n  forall bx bd defs n P sg sg' i,\n    NoDup (map fst defs) ->\n    defs_well_scoped defs ->\n\n    defs !! n = Some (bx, bd) ->\n\n    let s := start_state P in\n    state_related [] defs (ienv sg) (S n) s sg ->\n    step i sg sg' ->\n\n    state_related [] defs (ienv sg') n s sg' /\\\n    (addrs_space0 (iheap sg) (defs2_addrs (ienv sg)) = (sum_list (map defined_size (map snd (drop (S n) defs)))) ->\n     addrs_space0 (iheap sg') (defs2_addrs (ienv sg')) = (sum_list (map defined_size (map snd (drop n defs))))) /\\\n    (addrs_space_g (map fst defs) (iheap sg) (defs2_addrs (ienv sg)) = (sum_list (map (defined_size_g (map fst defs)) (map snd (drop (S n) defs)))) ->\n     addrs_space_g (map fst defs) (iheap sg') (defs2_addrs (ienv sg')) = (sum_list (map (defined_size_g (map fst defs)) (map snd (drop n defs))))).\nProof with eauto.\n  intros bx bd defs n P sg sg' i.\n  intros nodup0 scoped0 futureeq s.\n  intros rel0 stp.\n  inversion rel0; subst.\n  inversion code_rel as [<- agree0].\n  subst.\n  simpl in stp.\n  unfold s in *.\n  simpl start_state in *.\n  simpl iheap in *.\n  simpl ienv in *.\n\n  pose proof (drop_S defs _ _ futureeq) as drop_n.\n  pose (f_equal (map fst) drop_n) as drop_fstn.\n  simpl in drop_fstn.\n  repeat rewrite -> map_drop in drop_fstn.\n  assert (nodup_n: NoDup (drop n (map fst defs))) by (apply NoDup_drop; eauto).\n  rewrite -> drop_fstn in nodup_n.\n\n  assert (bx_new: ~ In bx (map fst eg)).\n  { rewrite -> defspast_same.\n    inversion nodup_n... }\n\n  replace (take (S n) defs) with (take n defs ++ [(bx, bd)]) in *\n    by (symmetry; apply take_S_r; eauto).\n  rewrite -> bind_globals_app in stp.\n    \n  destruct bd; inversion stp; simpl ienv in *; subst.\n  - simpl in *.\n    split. split...\n    (* def values *)\n    + intros. simpl in H.\n      destruct H; simplify_eq...\n      exists (dtuple var l). split...\n      * eauto with searches.\n      * constructor.\n    (* same *)\n    + simpl. symmetry. rewrite -> defspast_same. eapply drop_S...\n      rewrite -> list_lookup_fmap.\n      rewrite -> futureeq. simpl...\n    (* valid *)\n    + eauto 10 with addr_in.\n    (* code *)\n    + split...\n    (* env *)\n    + inversion env_rel; subst.\n      constructor; unfold lookup in *. simpl; intros.\n      * apply (live_vars x)...\n      * intros. discriminate H1.\n      * intros. simpl.\n        destruct H; simplify_eq.\n      * intros. simpl.\n        destruct (decEq x bx); destruct H; simplify_eq...\n        -- pose proof (globals_present bx vg H).\n           absurd (In bx (map fst eg)).\n           ++ inversion nodup_n; subst.\n              rewrite <- defspast_same in H4...\n           ++ eauto with searches.\n        -- apply globals_present...\n           rewrite -> bind_globals_app. simpl.\n           clear - n0 H0. set_unfold...\n    (* heap *)\n    + destruct heap_rel; constructor.\n      * intros.\n        pose proof (related_addrs a0 sv H).\n        deprod.\n        inversion H0.\n      * intros.\n        destruct v...\n        simpl in H.\n        destruct H; simplify_eq...\n        -- exists (dtuple var l).\n           exists (stuple vs).\n           repeat split_and...\n           ++ eauto with searches.\n           ++ eauto with heaps.\n           ++ apply defined_svalue_extend...\n              constructor...\n        -- pose proof (global_addrs x _ H).\n           simpl in H0.\n           deprod.\n           exists d, svg.\n           repeat split_and...\n           eauto with heaps.\n           apply defined_svalue_extend...\n    (* stack; empty *)\n    + inversion stack_rel; subst; constructor.\n    (* safe *)\n    + split; intros.\n      * assert (a_fresh : {[a]} ## (list_to_set (filter_map (λ x : var * value, value_to_addr x.2) eg) : addrs)).\n        { set_unfold. intros. subst.\n          assert (hg !! a = None) by eauto with heaps.\n          enough (hg !! a <> None) by congruence.\n          apply defspast_valid.\n          deep_set_unfold.\n          exists v, (vaddr a).\n          split...\n          assert (NoDup (map fst eg)).\n          { inversion nodup_n; subst. rewrite -> defspast_same... }\n          unfold lookup.\n          eauto with searches. }\n        simpl. rewrite -> drop_n. simpl.\n        rewrite <- H.\n        unfold defs2_addrs. simpl.\n        unfold addrs_space0, space_of.\n        rewrite -> elements_disj_union...\n        rewrite -> elements_singleton. simpl.\n        assert (h' !! a = Some (stuple vs)) by eauto with heaps.\n        unfold lookup_size.\n        rewrite -> H0. simpl.\n        f_equal.\n        replace (length l) with (length vs).\n        f_equal. f_equal.\n        apply map_ext_in.\n        intros.\n        assert (a0 <> a).\n        { rewrite <- elem_of_list_In in H1. set_unfold... }\n        assert (hg !! a0 = h' !! a0) by eauto with heaps.\n        destruct (hg !! a0) eqn:hga0.\n        rewrite <- H3...\n        rewrite <- H3...\n        { unfold searches in lkps.\n          eapply map_option_length with (flip search eg) (fun x => Some x) _...\n          clear. induction l; simpl...\n          rewrite -> IHl. reflexivity. }\n      * assert (a_fresh : {[a]} ## (list_to_set (filter_map (λ x : var * value, value_to_addr x.2) eg) : addrs)).\n        { set_unfold. intros. subst.\n          assert (hg !! a = None) by eauto with heaps.\n          enough (hg !! a <> None) by congruence.\n          apply defspast_valid.\n          deep_set_unfold.\n          exists v, (vaddr a).\n          split...\n          assert (NoDup (map fst eg)).\n          { inversion nodup_n; subst. rewrite -> defspast_same... }\n          unfold lookup.\n          eauto with searches. }\n        simpl. rewrite -> drop_n. simpl.\n        rewrite <- H.\n        unfold defs2_addrs. simpl.\n        unfold addrs_space_g, space_of.\n        rewrite -> elements_disj_union...\n        rewrite -> elements_singleton. simpl.\n        assert (h' !! a = Some (stuple vs)) by eauto with heaps.\n        unfold lookup_size.\n        rewrite -> H0. simpl.\n        f_equal.\n        replace (length l) with (length vs).\n        f_equal. f_equal.\n        apply map_ext_in.\n        intros.\n        assert (a0 <> a).\n        { rewrite <- elem_of_list_In in H1. set_unfold... }\n        assert (hg !! a0 = h' !! a0) by eauto with heaps.\n        destruct (hg !! a0) eqn:hga0.\n        rewrite <- H3...\n        rewrite <- H3...\n        { unfold searches in lkps.\n          eapply map_option_length with (flip search eg) (fun x => Some x) _...\n          clear. induction l; simpl...\n          rewrite -> IHl. reflexivity. }\n  (* same exact case, make lemma for alloc ?*)\n  - simpl in *.\n    split. split...\n    (* defspast -> defs *)\n    + intros. simpl in H.\n      destruct H; simplify_eq...\n      exists (dabs var v e). split...\n      * eauto with searches.\n      * constructor.\n    (* same *)\n    + simpl. symmetry. rewrite -> defspast_same. eapply drop_S...\n      rewrite -> list_lookup_fmap.\n      rewrite -> futureeq. simpl...\n    (* valid *)\n    + eauto 20 with addr_in.\n    (* code *)\n    + split...\n    (* env *)\n    + inversion env_rel; subst.\n      constructor; unfold lookup in *; simpl; intros...\n      * intros. apply (live_vars x)...\n      * discriminate.\n      * discriminate.\n      * intros. simpl.\n        destruct (decEq x bx); destruct H; simplify_eq...\n        -- pose proof (globals_present bx vg H).\n           absurd (In bx (map fst eg)).\n           ++ inversion nodup_n; subst.\n              rewrite <- defspast_same in H4...\n           ++ eauto with searches.\n\n        -- apply globals_present...\n           rewrite -> bind_globals_app. simpl.\n           clear - n0 H0. set_unfold...\n    (* heap *)\n    + destruct heap_rel; constructor.\n      * intros.\n        pose proof (related_addrs a0 sv H).\n        deprod.\n        inversion H0.\n      * intros.\n        destruct v0...\n        simpl in H.\n        destruct H; simplify_eq...\n        -- exists (dabs var v e), (sclos (v, e, eg)).\n           repeat split_and...\n           ++ eauto with searches.\n           ++ eauto with heaps.\n           ++ apply defined_svalue_extend...\n              constructor...\n              intros. unfold lookup. simpl.\n\n              pose proof (defs_well_scoped_drop defs n scoped0).\n              rewrite -> drop_n in X.\n              inversion X; subst.\n              rewrite -> map_drop in H2.\n              rewrite <- defspast_same in H2.\n              assert (var_in_def x0 (dabs var v e))...\n              pose proof (H2 x0 H1).\n              destruct (In_fst_search _ _ H3)...\n        -- pose proof (global_addrs x _ H).\n           simpl in H0.\n           deprod. exists d, svg. repeat split_and...\n           ++ eauto with heaps.\n           ++ apply defined_svalue_extend...\n    (* stack; empty *)\n    + inversion stack_rel; subst; constructor.\n    (* safe *)\n    + split; intros.\n      * assert (a_fresh : {[a]} ## (list_to_set (filter_map (λ x : var * value, value_to_addr x.2) eg) : addrs)).\n        { set_unfold. intros. subst.\n          assert (hg !! a = None) by eauto with heaps.\n          enough (hg !! a <> None) by congruence.\n          apply defspast_valid.\n          deep_set_unfold.\n          exists v0, (vaddr a).\n          split...\n          assert (NoDup (map fst eg)).\n          { inversion nodup_n; subst. rewrite -> defspast_same... }\n          unfold lookup.\n          eauto with searches. }\n        simpl. rewrite -> drop_n. simpl.\n        rewrite <- H.\n        unfold defs2_addrs. simpl.\n        unfold addrs_space0, space_of.\n        rewrite -> elements_disj_union...\n        rewrite -> elements_singleton. simpl.\n        assert (h' !! a = Some (sclos (v, e, eg))) by eauto with heaps.\n        unfold lookup_size.\n        rewrite -> H0. simpl.\n        do 3 f_equal.\n        apply map_ext_in.\n        intros.\n        assert (a0 <> a).\n        { rewrite <- elem_of_list_In in H1. set_unfold... }\n        assert (hg !! a0 = h' !! a0) by eauto with heaps.\n        destruct (hg !! a0) eqn:hga0.\n        rewrite <- H3...\n        rewrite <- H3...\n      * assert (a_fresh : {[a]} ## (list_to_set (filter_map (λ x : var * value, value_to_addr x.2) eg) : addrs)).\n        { set_unfold. intros. subst.\n          assert (hg !! a = None) by eauto with heaps.\n          enough (hg !! a <> None) by congruence.\n          apply defspast_valid.\n          deep_set_unfold.\n          exists v0, (vaddr a).\n          split...\n          assert (NoDup (map fst eg)).\n          { inversion nodup_n; subst. rewrite -> defspast_same... }\n          unfold lookup.\n          eauto with searches. }\n        simpl. rewrite -> drop_n. simpl.\n        rewrite <- H.\n        unfold defs2_addrs. simpl.\n        unfold addrs_space_g, space_of.\n        rewrite -> elements_disj_union...\n        rewrite -> elements_singleton. simpl.\n        assert (h' !! a = Some (sclos (v, e, eg))) by eauto with heaps.\n        unfold lookup_size.\n        rewrite -> H0. simpl.\n        f_equal. f_equal. f_equal.\n        apply map_ext_in.\n        intros.\n        assert (a0 <> a).\n        { rewrite <- elem_of_list_In in H1. set_unfold... }\n        assert (hg !! a0 = h' !! a0) by eauto with heaps.\n        destruct (hg !! a0) eqn:hga0.\n        rewrite <- H3...\n        rewrite <- H3...\n  (* const *)\n  - split. split...\n    + simpl. intros.\n      destruct H; simplify_eq...\n      exists (dconst var b).\n      split; try constructor.\n      eauto with searches.\n    + simpl. symmetry. rewrite -> defspast_same. eapply drop_S...\n      rewrite -> list_lookup_fmap.\n      rewrite -> futureeq. simpl...\n    + simpl ienv in *.\n      eauto with addr_in.\n    + simpl. intros.\n      split...\n    (* env *)\n    + inversion env_rel; subst.\n      constructor; unfold lookup in *; simpl; intros...\n      * apply (live_vars x)...\n      * discriminate.\n      * discriminate.\n      * intros. simpl.\n        destruct (decEq x bx); destruct H; simplify_eq...\n        -- pose proof (globals_present bx vg H).\n           absurd (In bx (map fst eg)).\n           ++ inversion nodup_n; subst.\n              rewrite <- defspast_same in H4...\n           ++ eauto with searches.\n        -- apply globals_present...\n           rewrite -> bind_globals_app. simpl.\n           clear - n0 H0. set_unfold...\n    (* heap *)\n    + inversion heap_rel; subst.\n      split...\n      * intros.\n        pose proof (related_addrs _ _ H).\n        deprod. simpl in H0; discriminate.\n      * intros.\n        simpl in H.\n        destruct H; simplify_eq...\n        pose proof (global_addrs _ _ H).\n        destruct v...\n        deprod.\n        exists d, svg. repeat split_and...\n        apply defined_svalue_extend...\n    + inversion stack_rel; constructor.\n    + split; intros. simpl.\n      * rewrite -> drop_n. simpl.\n        rewrite <- H...\n      * rewrite -> drop_n. simpl.\n        rewrite <- H...\nQed.\n\nLemma initial_safe :\n  forall defs remaining P sg,\n    state_related [] defs (ienv sg) remaining (start_state P) sg ->\n    globalize_safe [] (map fst defs) (ienv sg)\n                   (addrs_space0 (iheap sg) (defs2_addrs (ienv sg)))\n                   (addrs_space_g (map fst defs) (iheap sg) (defs2_addrs (ienv sg)))\n                   (start_state P) sg.\nProof with eauto.\n  intros.\n  inversion H; subst.\n  constructor.\n  - intros.\n    rewrite -> closed_empty_iff_empty in H0.\n    rewrite -> H0.\n    simpl.\n    unfold addrs_space0, space_of.\n    unfold image. \n    repeat rewrite -> elements_empty.\n    simpl.\n    rewrite -> Nat.mul_0_r. simpl.\n    setoid_replace (union empty (defs2_addrs eg)) with (defs2_addrs eg) by set_solver.\n    unfold ge. reflexivity.\n  - intros.\n    rewrite -> closed_empty_iff_empty in H0.\n    rewrite -> H0.\n    simpl.\n    unfold addrs_space_g, addrs_space0, space_of.\n    unfold image. \n    repeat rewrite -> elements_empty.\n    simpl.\n    setoid_replace (union empty (defs2_addrs eg)) with (defs2_addrs eg) by set_solver.\n    unfold ge.\n    induction (elements (defs2_addrs eg)); simpl...\nQed.\n\n(* TODO move this into SXML *)\nInductive same_head : exp -> exp -> Prop\n  :=\n  | same_small cr1 cr2 v se :\n      same_head (letsmall v se cr1) (letsmall v se cr2)\n  | same_abs v vl cl1 cr1 cl2 cr2 :\n      same_head (letabs v vl cl1 cr1) (letabs v vl cl2 cr2)\n  | same_branch v ct1 cf1 ct2 cf2 :\n      same_head (branch v ct1 cf1) (branch v ct2 cf2)\n  | same_tail vf va :\n      same_head (tail vf va) (tail vf va)\n  | same_ret v :\n      same_head (ret v) (ret v)\n.\n\nDefinition head_not_global (defVars: list var) (e: exp): Prop\n  :=\n    match e with\n    | letsmall x _ _ => not (In x defVars)\n    | letabs x xl cl cr => not (In x defVars)\n    | _ => True\n    end.\nDefinition head_global (defVars: list var) (e: exp): Prop\n  := (* this one is much less common *)\n    match e with\n    | letsmall x _ _ => In x defVars\n    | letabs x xl cl cr => In x defVars\n    | _ => False\n    end.\n\nLemma related_head_not_global :\n  forall defs c cg,\n    elim_defs defs c = cg ->\n    head_not_global defs cg.\nProof with eauto.\n  intros.\n  induction c; subst; simpl in *...\n  - destruct (member v defs); subst...\n  - destruct (member v defs); subst...\nQed.\n\nLemma sval_relate_alloc :\n  forall ar a ag defs defspast sv svg,\n    ~ addr_in sv a ->\n    sval_related ar defs defspast sv svg ->\n    sval_related ((a, ag) :: ar) defs defspast sv svg.\nProof with eauto.\n  intros.\n  destruct H0; constructor.\n  - (* Induction will mess with the tuple structure,\n           so we need to get this fact first *)\n    clear - H H0.\n    induction H0... constructor.\n    (* val related *)\n    + apply val_relate_alloc... eauto 20 with addr_in.\n    + apply IHForall2...\n      eauto 20 with addr_in.\n  - inversion H0; subst. constructor...\n    (* env *)\n    apply env_relate_alloc...\nQed.\n\n(* Common cases for related step *)\nLemma heap_relate_alloc defs defspast ar h hg h' hg' a ag sv svg :\n\n  alloc h sv = (a, h') ->\n  alloc hg svg = (ag, hg') ->\n\n  sval_related ar defs defspast sv svg ->\n  valid_in_heap h h ->\n  valid_in_heap sv h ->\n\n  heap_related ar defs defspast h hg ->\n  heap_related ((a, ag) :: ar) defs defspast h' hg'.\nProof with eauto 15 with addr_in heaps.\n  intros allocs allocsg svrel hvalid svvalid heaprel.\n  destruct heaprel as [heaprel heapglobals].\n  constructor.\n  - intros a0 sv0 lkp0. destruct (decEq a0 a); subst.\n    + exists ag.\n      exists svg.\n      simpl. rewrite -> decEq_refl.\n      repeat split; eauto with heaps.\n      assert (h' !! a = Some sv) by eauto with heaps. simplify_eq.\n\n      apply sval_relate_alloc...\n      addr_conflict h a.\n    + assert (h !! a0 = Some sv0) by eauto with heaps.\n      destruct (heaprel a0 sv0) as [ag0 [svg0 [arg [lkpg svgrel]]]]; try assumption.\n\n      exists ag0.\n      exists svg0.\n      simpl.\n      forced (decEq a0 a).\n      repeat split...\n\n      (* svals related *)\n      eapply sval_relate_alloc...\n      addr_conflict h a.\n  - clear - allocs allocsg heapglobals.\n    intros.\n    pose proof (heapglobals _ _ H).\n    destruct v...\n    deprod.\n    exists d, svg0...\nQed.\n\nDefinition sub_env (e1 e2 : env) := forall x, search x e1 = search x e2.\n\nInstance list_equiv_reflexive {X} {equiv: X -> X -> Prop}: `(Reflexive equiv) -> Reflexive (@list_equiv _ equiv).\nProof.\n  unfold Reflexive.\n  intros.\n  induction x; constructor.\n  - apply H.\n  - apply IHx.\nQed.\n\n\nLemma space_alloc ar (h h' hg hg' : heap svalue) a ag sv svg addrs1 defaddrs k n (size1 size2: svalue -> nat) :\n    alloc h sv = (a, h') ->\n    alloc hg svg = (ag, hg') ->\n    (forall a0, ~ In (a0, ag) ar) ->\n    ~ elem_of ag defaddrs ->\n\n    k >= 1 ->\n    k * size1 sv >= size2 svg ->\n    let addrs1' := difference addrs1 {[ a ]} in\n    k * space_of size1 h addrs1' + n ≥ space_of size2 hg (image (flip search ar) addrs1' ∪ defaddrs) ->\n    k * space_of size1 h' addrs1 + n ≥ space_of size2 hg' (image (flip search ((a, ag) :: ar)) addrs1 ∪ defaddrs).\nProof with eauto with searches.\n  intros allocs allocg ag_fresh1 ag_fresh2 k_pos sv_svg_size ? initial_space.\n  unfold space_of in *.\n\n  assert (image_ag_disj: (image (flip search ar) addrs1' : addrs) ## {[ ag ]}).\n  { unfold image. deep_set_unfold.\n    assert (In (x0, ag) ar)...\n    apply ag_fresh1 in H2...\n  }\n\n  assert (addrs'_same: forall a, elem_of a addrs1' -> h' !! a = h !! a).\n  { intros. assert (a0 <> a) by set_solver.\n    eauto with heaps. }\n  assert (addrs'_image_same:\n            forall (a: addr), elem_of a (image (flip search ar) addrs1' : addrs) -> hg' !! a = hg !! a).\n  { intros. deep_set_unfold.\n    eapply heap_lookup_earlier'...\n    intro. subst.\n    assert (In (x, ag) ar)...\n  }\n  assert (defaddrs_same : forall a, elem_of a defaddrs -> hg !! a = hg' !! a).\n  {\n    intros. assert (a0 <> ag) by (intro; subst; contradiction).\n    eauto with heaps.\n  }\n\n  assert (addrs1'_image: (image (flip search ((a, ag) :: ar)) addrs1' : addrs) = image (flip search ar) addrs1').\n  {\n    unfold image.\n    f_equal.\n    apply filter_map_ext_in.\n    intros. simpl.\n    unfold addrs1'. rewrite <- elem_of_list_In in H.\n    set_unfold. deprod. forced (decEq x a)...\n  }\n\n  destruct (decide (elem_of a addrs1)).\n\n  (* member *)\n  - assert (equiv addrs1 (union addrs1' {[ a ]})).\n    { set_unfold. intro.\n      destruct (decEq x a). subst.\n      split; intros...\n      split; intros...\n      forced H. deprod...\n    }\n    assert (addrs1' ## {[ a ]}) by set_solver.\n    rewrite -> H.\n    rewrite -> image_union.\n    rewrite -> elements_disj_union...\n\n    rewrite -> map_app.\n    rewrite -> sum_list_app.\n    \n    (* simplify image of a *)\n    unfold image at 2.\n    rewrite -> elements_singleton. simpl.\n    rewrite -> decEq_refl.\n\n    (* simplify image of addrs1' *)\n    rewrite -> addrs1'_image.\n\n    setoid_replace (option_to_set (Some ag) ∪ ∅ : addrs) with\n                   ({[ ag ]} : addrs) by (clear; set_solver).\n\n    setoid_replace (image (flip search ar) addrs1' ∪ {[ag]} ∪ defaddrs) with\n                   ({[ag]} ∪ (image (flip search ar) addrs1' ∪ defaddrs)) by (clear; set_solver).\n    rewrite -> elements_disj_union.\n    rewrite -> elements_singleton.\n    rewrite -> map_app.\n    rewrite -> sum_list_app.\n    simpl.\n\n    rewrite -> (map_ext_in (lookup_size size1 h') (lookup_size size1 h)).\n    rewrite -> (map_ext_in (lookup_size size2 hg') (lookup_size size2 hg)).\n    unfold lookup_size at 2.\n    unfold lookup_size at 2.\n    assert (lkpa: h' !! a = Some sv) by eauto with heaps.\n    assert (lkpag: hg' !! ag = Some svg) by eauto with heaps.\n    rewrite -> lkpa.\n    rewrite -> lkpag.\n    repeat rewrite -> Nat.add_0_r.\n\n    clear - initial_space k_pos sv_svg_size.\n    rewrite -> Nat.mul_add_distr_l.\n    assert (k * sum_list (map (lookup_size size1 h) (elements addrs1')) >=\n            sum_list (map (lookup_size size1 h) (elements addrs1'))).\n    { destruct k; try solve [inversion k_pos].\n      simpl. lia. }\n    lia.\n\n    (* map ext 2, image union defaddrs *)\n    + intros.\n      unfold lookup_size.\n      rewrite <- elem_of_list_In in H1.\n      deep_set_unfold.\n      destruct H1.\n      * rewrite -> (addrs'_image_same a0)...\n      * rewrite -> (defaddrs_same a0)...\n    (* map ext 1 *)\n    + intros.\n      rewrite <- elem_of_list_In in H1.\n      set_unfold.\n      apply addrs'_same in H1.\n      unfold lookup_size. rewrite -> H1.\n      reflexivity.\n    (* union disjoint *)\n    + clear - image_ag_disj ag_fresh2. set_solver.\n  - assert (H: equiv addrs1' addrs1) by set_solver.\n    rewrite -> H in initial_space.\n    rewrite <- H.\n    rewrite -> addrs1'_image.\n    rewrite -> H.\n    destruct k; try solve [inversion k_pos].\n    simpl.\n    (* copy-pasted *)\n    rewrite -> (map_ext_in (lookup_size size1 h') (lookup_size size1 h)).\n    rewrite -> (map_ext_in (lookup_size size2 hg') (lookup_size size2 hg)).\n    lia.\n    + intros.\n      unfold lookup_size.\n      rewrite <- H in H0.\n      rewrite <- elem_of_list_In in H0.\n      deep_set_unfold.\n      destruct H0.\n      * rewrite -> (addrs'_image_same a0)...\n      * rewrite -> (defaddrs_same a0)...\n    (* map ext 1 *)\n    + intros.\n      rewrite <- H in H0.\n      rewrite <- elem_of_list_In in H0.\n      set_unfold.\n      apply addrs'_same in H0.\n      unfold lookup_size. rewrite -> H0.\n      reflexivity.\nQed.\n\nTheorem clos_size_related :\n  forall ar defs defspast clos1 clos2,\n    clos_related ar defs defspast clos1 clos2 ->\n    (1 + length defs) * clos_size clos1 >= clos_size clos2.\nProof with eauto.\n  intros.\n  inversion H; subst.\n  destruct H0.\n  simpl in H0.\n  pose proof (free_vars_elim_defs cl (map fst defs)).\n\n  inversion H; subst.\n  unfold code_related in *.\n  simpl in H. deprod.\n  simpl take. simpl bind_globals.\n  pose (elim_defs (map fst defs) cl) as cl2.\n  assert (free_vars_subset: subseteq (free_vars cl2) (union (free_vars cl) (list_to_set (map fst defs)))).\n  {\n    subst cl2. simpl.\n    apply free_vars_elim_defs.\n  }\n  subst cl2.\n  simpl bind_globals in *.\n  simpl map in *.\n  simpl app in *.\n  remember (free_vars (elim_defs (map fst defs) cl)) as fv2.\n  remember (free_vars cl) as fv1.\n  remember (list_to_set (map fst defs)) as defVars.\n  assert (subseteq (difference fv2 {[xl]}) (union (difference fv1 {[xl]}) defVars))\n    by (clear - free_vars_subset; set_solver).\n  assert (size (difference fv2 {[xl]}) <= size (difference fv1 {[xl]}) + size defVars).\n  {\n    assert (size (difference fv2 {[xl]}) <= size (union (difference fv1 {[xl]}) defVars)).\n    { apply subseteq_size... }\n    enough (size (union (difference fv1 {[xl]}) defVars) <= size (difference fv1 {[xl]}) + size defVars) by lia.\n    rewrite -> size_union_alt.\n    enough (size (difference defVars (difference fv1 {[xl]})) <= size defVars) by lia.\n    clear.\n    apply subseteq_size.\n    set_solver.\n  }\n  simpl.\n  rewrite <- Heqfv1.\n  rewrite <- Heqfv2.\n  (* equal, but this is enough *)\n  assert (length (map fst defs) >= size defVars).\n  {\n    subst defVars. generalize (map fst defs).\n    clear.\n    induction l; simpl.\n    - rewrite -> size_empty...\n    - rewrite -> size_union_alt.\n      rewrite -> size_singleton.\n      enough (size (difference (list_to_set l : vars) {[a]}) <= size (list_to_set l: vars)) by lia.\n      apply subseteq_size. set_solver.\n  }\n  clear - H3 H7 H8.\n  rewrite -> map_length in H8.\n  rewrite -> Nat.mul_succ_r.\n  simpl.\n  lia.\nQed.\nTheorem clos_size_related_g :\n  forall ar defs defspast clos1 clos2,\n    clos_related ar defs defspast clos1 clos2 ->\n    clos_size clos1 >= clos_size_g (map fst defs) clos2.\nProof with eauto.\n  intros.\n  inversion H; subst.\n  destruct H0.\n  simpl in H0.\n  pose proof (free_vars_elim_defs cl (map fst defs)).\n\n  inversion H; subst.\n  unfold code_related in *.\n  simpl in H. deprod.\n  simpl take. simpl bind_globals.\n  pose (elim_defs (map fst defs) cl) as cl2.\n  assert (free_vars_subset: subseteq (free_vars cl2) (union (free_vars cl) (list_to_set (map fst defs)))).\n  {\n    subst cl2. simpl.\n    apply free_vars_elim_defs.\n  }\n  subst cl2.\n  simpl bind_globals in *.\n  simpl map in *.\n  simpl app in *.\n  remember (free_vars (elim_defs (map fst defs) cl)) as fv2.\n  remember (free_vars cl) as fv1.\n  remember (list_to_set (map fst defs)) as defVars.\n  assert (subseteq (difference fv2 {[xl]}) (union (difference fv1 {[xl]}) defVars))\n    by (clear - free_vars_subset; set_solver).\n  simpl.\n  rewrite <- Heqfv1.\n  rewrite <- Heqfv2.\n  rewrite <- HeqdefVars.\n  (* equal, but this is enough *)\n  clear - H3 H6.\n  unfold ge. apply le_n_S.\n  apply subseteq_size.\n  set_solver.\nQed.\n\nTheorem related_step ar defs defspast m n s sg s' sg' i :\n    same_head (icode s) (icode sg) ->\n\n    state_valid s ->\n    state_valid sg ->\n\n    NoDup (map fst defs) ->\n    True ->\n\n    step i s s' ->\n    step i sg sg' ->\n\n    state_related ar defs defspast 0 s sg\n    /\\ globalize_safe ar (map fst defs) defspast m n s sg ->\n    exists ar',\n      state_related ar' defs defspast 0 s' sg'\n      /\\ globalize_safe ar' (map fst defs) defspast m n s' sg'.\nProof with (auto || contradiction || eauto with related decEq).\n  intros head valid validg nodup samedefs st1 stg1 [rel0 safe0].\n  destruct rel0.\n  rewrite -> drop_0 in defspast_same.\n\n  inversion head; simpl in *; subst;\n    inversion st1; subst; inversion stg1; subst;\n      repeat unfold_simple_related;\n      destruct code_rel as [code_rel agree0];\n      pose proof (related_head_not_global (map fst defs) _ _ code_rel) as not_global.\n  (* tuple *)\n  - exists ((a, a0) :: ar).\n    split.\n    (* related *)\n    + split; simpl in not_global |- *...\n      * eauto with addr_in.\n      * intros. destruct H; simplify_eq...\n        -- split; eauto with heaps.\n        -- pose proof (ar_heap_dom _ _ H).\n           deprod. eauto with heaps.\n      * simpl in code_rel, agree0.\n        rewrite -> (not_In_if_member _ _ _ _ not_global) in code_rel.\n        inversion code_rel; subst.\n        intros.\n        constructor... destruct (search v defs)...\n        destruct d; deprod...\n      * rewrite <- defspast_same in not_global.\n        assert (~ addr_in (e, (free_vars (VAL v := tupleExp xs IN cr1)%exp)) a) by (intro; addr_conflict h a).\n        eapply env_relate_subset.\n        apply env_relate_new...\n        -- simpl. set_unfold. intros. destruct (decEq x v)...\n        -- simpl. set_unfold. intros. destruct (decEq x v)...\n      * eapply (heap_relate_alloc _ _ _ _ _ _ _ _ _ _ _ alloc_tuple alloc_tuple0); eauto 20 with addr_in.\n        -- constructor.\n           assert (forall x, In x xs -> free_in x (VAL v := tupleExp xs IN cr2)%exp).\n           { intros. apply free_smallExp.\n             constructor... }\n           eapply env_lookups_related...\n           { intros. simpl. set_unfold... left. rewrite -> elem_of_list_In... }\n           intros.\n           rewrite -> in_free_vars_iff_free_in...\n        -- assert (forall x, In x xs -> free_in x (VAL v := tupleExp xs IN cr1)) by eauto with free_in.\n           eauto 20 with addr_in.\n      * clear - stack_rel alloc_tuple valid.\n        induction stack_rel; (constructor; try done).\n        (* closure in stack *)\n        -- inversion H. subst; split; eauto with related decEq.\n           eapply env_relate_alloc...\n           addr_conflict h a.\n        (* rest of stack *)\n        -- apply IHstack_rel.\n           clear - valid.\n           unfold valid_in_heap, addr_in, addr_in_state in *.\n           intros. apply valid.\n           destruct H...\n           destruct H...\n           right. left.\n           eauto 20 with addr_in.\n      * assert (~ In a (map fst ar)).\n        { intro. apply In_fst_search in H.\n          deprod. assert (In (a, y) ar) by eauto with searches.\n          destruct (ar_heap_dom a y)...\n          addr_conflict h a. }\n        constructor...\n    (* safe *)\n    + assert (lens: length vs = length vs0) by (eapply (map_option_length _ _ xs); eauto).\n      destruct env_rel.\n      destruct heap_rel.\n      inversion safe0; subst.\n\n      assert (∀ a1 : addr, ¬ In (a1, a0) ar).\n      { unfold not. intros.\n\n        absurd ((hg !! a0) = None).\n        -- destruct (ar_heap_dom a1 a0)...\n        -- eauto with heaps. }\n      assert (a0 ∉ defs2_addrs defspast).\n      {intro.\n        unfold defs2_addrs in *.\n        set_unfold.\n        deprod.\n        rewrite -> elem_of_list_In in H0.\n        simpl in H1.\n        forced v1. simpl in H1.\n        simplify_eq.\n        assert (NoDup (map fst defspast)) by congruence.\n        assert (search v0 defspast = Some (vaddr a0)) by eauto with searches.\n\n        addr_conflict hg a0. }\n\n      constructor.\n      * intros. unfold addrs_space0, lookup_size in *.\n        apply space_alloc with h hg (stuple vs) (stuple vs0)...\n        (* size *)\n        -- lia.\n        -- simpl. rewrite -> lens. simpl. lia.\n        -- assert (closed h (difference addrs1 {[a]})).\n           { eapply closed_alloc_3... eauto 10 with addr_in. }\n           apply af_safe...\n      * intros. unfold addrs_space0, space_of, addrs_space_g, lookup_size in *.\n        rewrite <- (Nat.mul_1_l (sum_list _)) at 1.\n        unfold lookup_size in *.\n        apply space_alloc with h hg (stuple vs) (stuple vs0); simpl...\n        (* size *)\n        -- lia.\n        -- assert (closed h (difference addrs1 {[a]})).\n           { eapply closed_alloc_3... eauto 10 with addr_in. }\n           rewrite -> Nat.add_0_r.\n           apply af_safe_g...\n  (* app *)\n  - (* simplify all the lookup info *)\n    unfold lookup_object, lookup in *.\n    forced (search xa e).\n    forced (search xa eg).\n    forced (search xf e).\n    forced (search xf eg).\n    simplify_eq.\n    forced v4. forced v5. simplify_eq.\n    forced (heap_lookup _ a h).\n    forced (heap_lookup _ a0 hg).\n    inversion env_rel; simplify_eq.\n    unfold lookup in pairs_related.\n    destruct (pairs_related xf (vaddr a)) as [? [? vgrel]]...\n    { eauto with free_in. }\n    { eauto with free_in. }\n    inversion vgrel; simplify_eq.\n\n    (* via heap related, force closures related *)\n    pose proof (heap_lookup_related heap_rel H1 Heqo3 Heqo4) as H.\n    inversion H; subst; clear H.\n    inversion H3; subst; clear H3.\n    deprod.\n    exists ar.\n    split; try solve [inversion safe0; done].\n    deprod.\n    split...\n    (* env *)\n    * intros.\n      eapply env_relate_subset.\n      eapply env_relate_new...\n      eapply env_lookup_related with defspast _ _ e eg xa ...\n      { eauto with free_in. }\n      -- clear. simpl. set_unfold. destruct (decEq xa v)...\n      -- clear. simpl. set_unfold. intros. destruct (decEq x xl0)...\n      -- clear. simpl. set_unfold. intros. destruct (decEq x xl0)...\n    (* stack *)\n    * constructor...\n      constructor...\n      (* code *)\n      -- inversion code_rel; subst.\n         rewrite -> (not_In_if_member) in H0...\n         inversion H0; subst.\n         constructor...\n         simpl in agree0.\n         rewrite -> (not_In_if_member) in agree0...\n      -- congruence.\n      -- eapply env_relate_subset...\n         clear. simpl. set_unfold. intros. deprod. right...\n         clear. simpl. set_unfold. intros. deprod. right...\n  (* proj *)\n  - exists ar.\n    split; try solve [inversion safe0; done].\n    deprod.\n    split...\n    split...\n    (* code 1 *)\n    + clear - code_rel not_global.\n      deprod.\n      unfold code_related in *. simpl in *.\n      rewrite -> (not_In_if_member _ _ _ _ not_global) in code_rel.\n      inversion code_rel; done.\n    (* defs agree *)\n    + simpl in agree0. destruct (member v (map fst defs))...\n    (* env related *)\n    + unfold lookup_object in *.\n      forced (e !! xt).\n      forced (eg !! xt).\n      forced v2.\n      forced v3.\n      assert (search a ar = Some a0).\n      { assert (rel: val_related ar (vaddr a) (vaddr a0)).\n        eapply env_lookup_related; eauto with free_in.\n        simpl. inversion rel... }\n      assert (svrel: sval_related ar defs defspast (stuple vs) (stuple vs0)) by eauto with related.\n      inversion svrel; subst.\n\n      simpl in not_global.\n      eapply env_relate_subset.\n      apply env_relate_new...\n      * congruence.\n      * eapply (Forall2_nth _ vs vs0 i0 _ _ H2)...\n      * simpl. clear. set_unfold. intros. destruct (decEq x v)...\n      * simpl. clear. set_unfold. intros. destruct (decEq x v)...\n  (* write *)\n  - exists ar.\n    split; try solve [inversion safe0; done].\n    deprod.\n    split...\n    split...\n    + clear - code_rel not_global.\n      unfold code_related in *. simpl in *.\n      rewrite -> (not_In_if_member _ _ _ _ not_global) in code_rel.\n      congruence.\n    (* defs agree *)\n    + simpl in agree0. forced (member v (map fst defs))...\n    (* env related *)\n    + simpl in agree0.\n      forced (member v (map fst defs)).\n      eapply env_relate_subset.\n      eapply env_relate_new...\n      congruence.\n      * simpl. clear. set_unfold. intros. destruct (decEq x v)...\n      * simpl. clear. set_unfold. intros. destruct (decEq x v)...\n  (* const *)\n  - exists ar.\n    split; try solve [inversion safe0; done].\n    split...\n    split...\n    + clear - code_rel not_global.\n      deprod.\n      unfold code_related in *. simpl in *.\n      rewrite -> (not_In_if_member _ _ _ _ not_global) in code_rel.\n      congruence.\n    (* defs agree *)\n    + simpl in agree0. forced (member v (map fst defs))...\n      destruct (search v defs)...\n      destruct d...\n      deprod...\n    + rewrite <- defspast_same in not_global.\n      eapply env_relate_subset.\n      eapply env_relate_new...\n      * simpl. clear. set_unfold. intros. destruct (decEq x v)...\n      * simpl. clear. set_unfold. intros. destruct (decEq x v)...\n  (* abs *)\n  - unfold code_related in code_rel.\n    simpl elim_defs in *.\n    simpl bind_globals in *.\n    assert (agree1: defs_agree defs cl1).\n    { clear - agree0. simpl in agree0...\n      repeat case_match; deprod... }\n    assert (agree2: defs_agree defs cr1).\n    { clear - agree0. simpl in agree0...\n      repeat case_match; deprod... }\n\n    assert (abs_related: sval_related ar defs defspast (sclos (vl, cl1, e)) (sclos (vl, cl2, eg))).\n    {\n      constructor.\n      simpl in agree0.\n      assert (code_related defs 0 cl1 cl2).\n      { destruct (member v (map fst defs)) eqn:v_global;\n          simplify_eq; try done. }\n      simpl in env_rel.\n      destruct (search v defs)...\n      + forced d.\n        deprod... subst.\n        constructor...\n        congruence.\n        (* env *)\n        eapply env_relate_subset...\n        * clear. set_solver.\n        * clear. set_solver.\n      + deprod... subst.\n        constructor...\n        congruence.\n        (* env *)\n        eapply env_relate_subset...\n        * clear. set_solver.\n        * clear. set_solver.\n    }\n\n    exists ((a, a0) :: ar).\n    split.\n    (* related *)\n    + split...\n      * eauto with addr_in.\n      * simpl. intros.\n        destruct H.\n        -- simplify_eq.\n           split; eauto with heaps.\n        -- destruct (ar_heap_dom a1 ag H).\n           split; eauto with heaps.\n      * simpl in not_global.\n        rewrite -> (not_In_if_member _ _ _ _ not_global) in code_rel.\n        deprod. inversion code_rel; split...\n      (* env *)\n      * assert (valid_in_heap (e, free_vars (letabs v vl cl1 cr1)) h) by eauto 20 with addr_in.\n        assert (~ addr_in (e, free_vars (letabs v vl cl1 cr1)) a).\n        { intro. absurd (h !! a = None).\n          ++ eauto with addr_in.\n          ++ eauto with heaps.\n        }\n        assert (~ In v (map fst defspast)).\n        { rewrite -> defspast_same.\n          intro. simpl in agree0.\n          destruct (search v defs) eqn:eqs; eauto with searches.\n        }\n        eapply env_relate_subset.\n        eapply env_relate_new...\n        -- simpl. clear. set_unfold. intros. destruct (decEq x v)...\n        -- simpl. clear. set_unfold. intros. destruct (decEq x v)...\n      (* heap *)\n      * apply (heap_relate_alloc _ _ _ _ _ _ _ _ _ _ _ alloc_abs alloc_abs0);\n          try (eauto 20 with addr_in)...\n        do 2 intro. inversion H; subst.\n        apply valid. unfold addr_in, addr_in_state.\n        deprod.\n        right. right. exists x, v0. split... split... simpl... clear - H1. set_solver.\n      (* stack *)\n      * clear - alloc_abs stack_rel valid.\n        induction stack_rel; constructor.\n        -- inversion H; subst. constructor...\n           assert (valid_in_heap (el, difference (free_vars cl) {[xl]}) h) by eauto 20 with addr_in.\n           assert (~ addr_in (el, difference (free_vars cl) {[xl]}) a) by (intro; absurd (h !! a = None); eauto with addr_in || eauto with heaps).\n           eauto with related.\n        -- apply IHstack_rel.\n           rewrite <- (state_valid_product _ _ h _).\n           rewrite <- (state_valid_product _ _ h _) in valid.\n           deprod. repeat split...\n           unfold valid_in_heap in *.\n           intros. eauto with addr_in.\n      * assert (~ In a (map fst ar)).\n        { intro. apply In_fst_search in H.\n          deprod. assert (In (a, y) ar) by eauto with searches.\n          destruct (ar_heap_dom a y)...\n          addr_conflict h a. }\n        constructor...\n    (* safe *)\n    + destruct env_rel, heap_rel.\n      inversion safe0; subst.\n\n      assert (∀ a1 : addr, ¬ In (a1, a0) ar).\n      { unfold not. intros.\n\n        absurd ((hg !! a0) = None).\n        -- destruct (ar_heap_dom a1 a0)...\n        -- eauto with heaps. }\n      assert (a0 ∉ defs2_addrs defspast).\n      {intro.\n        unfold defs2_addrs in *.\n        set_unfold.\n        deprod.\n        rewrite -> elem_of_list_In in H0.\n        simpl in H1.\n        forced v1. simpl in H1.\n        simplify_eq.\n        assert (NoDup (map fst defspast)) by congruence.\n        assert (search v0 defspast = Some (vaddr a0)) by eauto with searches.\n\n        addr_conflict hg a0. }\n\n      inversion abs_related; subst.\n      assert (length defspast = length defs).\n      { do 2 rewrite <- (map_length fst).\n        congruence. }\n      constructor.\n      * intros. unfold addrs_space0, lookup_size in *.\n        apply space_alloc with h hg (sclos (vl, cl1, e)) (sclos (vl, cl2, eg))...\n        (* size *)\n        -- lia.\n        -- unfold svalue_size.\n           rewrite -> H1.\n           eapply (clos_size_related _ _ _ (vl, cl1, e) (vl, cl2, eg) H3 ).\n        -- assert (closed h (difference addrs1 {[a]})).\n          { eapply closed_alloc_3... eauto 10 with addr_in. }\n          apply af_safe...\n      * intros. unfold addrs_space0, addrs_space_g, space_of, lookup_size in *.\n        rewrite <- (Nat.mul_1_l (sum_list _)) at 1.\n        unfold lookup_size in *.\n        apply space_alloc with h hg (sclos (vl, cl1, e)) (sclos (vl, cl2, eg))...\n        (* size *)\n        -- unfold svalue_size, svalue_size_g.\n           rewrite -> Nat.mul_1_l.\n           eapply (clos_size_related_g _ _ _ (vl, cl1, e) (vl, cl2, eg) H3 ).\n        -- assert (closed h (difference addrs1 {[a]})).\n           { eapply closed_alloc_3... eauto 10 with addr_in. }\n           rewrite -> Nat.mul_1_l.\n           apply af_safe_g...\n  (* branch *)\n  - exists ar.\n    split; try solve [inversion safe0; done].\n    inversion env_rel; subst.\n    replace b with b0.\n    unfold code_related in *. simpl in code_rel.\n    inversion code_rel.\n    simpl in agree0.\n    deprod.\n    subst.\n    destruct b0; split; try solve [split; eauto]...\n    + eapply env_relate_subset...\n      simpl. clear. set_solver.\n      simpl. clear. set_solver.\n    + eapply env_relate_subset...\n      simpl. clear. set_solver.\n      simpl. clear. set_solver.\n    (* b0 must be the same as b by relatedness *)\n    + simpl lookup in *.\n      assert (H0: val_related ar (vconst b) (vconst b0)).\n      { eapply env_lookup_related...\n        simpl. clear. set_solver.\n        simpl. clear. set_unfold. left... }\n      inversion H0; subst; reflexivity.\n  (* ret *)\n  - inversion stack_rel; subst.\n    inversion H2; subst.\n    exists ar.\n    split; try solve [inversion safe0; done].\n    split...\n    eapply env_relate_subset.\n    eapply env_relate_new...\n    eapply env_lookup_related with defspast _ _ e eg v ...\n    simpl. set_solver.\n    simpl. set_solver.\n    clear. set_unfold. intros. destruct (decEq x xl0)...\n    clear. set_unfold. intros. destruct (decEq x xl0)...\nQed.\n\nTheorem source_step ar defs defspast s sg sg' i :\n  not_stuck s ->\n\n  same_head (icode s) (icode sg) ->\n  state_valid s ->\n\n  state_related ar defs defspast 0 s sg ->\n  step i sg sg' ->\n\n  exists s' : state, step i s s'.\nProof with eauto.\n  intros notstuck0 head valid rel stg.\n  destruct rel. inversion head; subst;\n  simpl icode in *; simplify_eq;\n    inversion notstuck0; subst;\n      try solve [inversion H];\n      try solve [pose proof (X true) as invalid; destruct invalid as [invalid _]; inversion invalid].\n  - replace i with (None: option io_evt).\n    exists s2...\n    inversion H; subst; inversion stg; subst; done || solve [inversion H3]...\n  - replace i with (Some (write k0)).\n    exists s2...\n    inversion stg; subst; inversion H; subst.\n    (* writes: same value *)\n    assert (rel: val_related ar (vconst k0) (vconst b)).\n    { eapply env_lookup_related...\n      simpl. clear. set_solver.\n      simpl. clear. set_solver.\n    }\n    inversion rel; done.\n  - replace i with (None: option io_evt).\n    exists s2...\n    inversion stg...\n  - inversion stg; subst.\n    exists s2...\n  - inversion stg; subst.\n    exists s2...\n  - inversion stg; subst.\n    solve [inversion stack_rel].\nQed.\n\n\n\nLemma env_extend_source_global :\n  forall ar defspast x v vg xs xsg e eg,\n    NoDup (map fst defspast) ->\n    In (x, vg) defspast ->\n    val_related ar v vg ->\n    env_related ar defspast xs xsg e eg ->\n    env_related ar defspast (union xs {[x]}) xsg ((x, v) :: e) eg.\nProof with eauto.\n  intros.\n  destruct H2; split...\n  (* source exists *)\n  - intros. set_unfold.\n    unfold lookup. simpl.\n    destruct (decEq x0 x)...\n    destruct H2...\n  (* pairs related *)\n  - intros.\n    unfold lookup in *. simpl search in *.\n    set_unfold.\n    destruct (decEq x0 x); simplify_eq...\n    destruct H2...\n    contradiction.\n  (* global vals agree *)\n  - intros.\n    unfold lookup in *. simpl search in *.\n    destruct (decEq x0 x)...\n    simplify_eq.\n    destruct (In_pair_unique _ _ _ _ H H0 H2).\n    exact H1.\n    set_unfold.\n    destruct H3... contradiction.\nQed.\n\nLemma heap_extend_source_global :\n  forall ar defs defspast a x ag sv svg h h' hg,\n    In (x, vaddr ag) defspast ->\n    alloc h sv = (a, h') ->\n    valid_in_heap sv h ->\n    valid_in_heap h h ->\n    hg !! ag = Some svg ->\n    sval_related ar defs defspast sv svg ->\n    heap_related ar defs defspast h hg ->\n    heap_related ((a, ag) :: ar) defs defspast h' hg.\nProof with eauto with heaps.\n  intros.\n  destruct H5; split...\n  (* pairs related *)\n  - intros. simpl search.\n    destruct (decEq a0 a); subst.\n    (* a0 = a *)\n    + exists ag, svg.\n      assert (h' !! a = Some sv)...\n      simplify_eq...\n       \n      repeat split_and...\n      apply sval_relate_alloc...\n      addr_conflict h a.\n    + assert (h !! a0 = Some sv0)...\n      pose proof (related_addrs _ _ H6).\n      deprod.\n      exists ag0, svg0.\n      repeat split_and...\n      apply sval_relate_alloc...\n      addr_conflict h a.\nQed.\n    \n\n(*** Skipped steps ***)\n\nLemma larger_safe :\n  forall ar defspast n h h' hg a ag sv size1 size2 k,\n    heap_valid h ->\n    alloc h sv = (a, h') ->\n    addr_in defspast ag ->\n    (forall addrs1,\n        closed h addrs1 ->\n        k * space_of size1 h addrs1 + n\n        ≥ space_of size2 hg (image (flip search ar) addrs1 ∪ defs2_addrs defspast)) ->\n  forall addrs1,\n    closed h' addrs1 ->\n  k * space_of size1 h' addrs1 + n\n  ≥ space_of size2 hg (image (flip search ((a, ag) :: ar)) addrs1 ∪ defs2_addrs defspast).\nProof with eauto.\n  intros.\n  pose (difference addrs1 {[a]}) as addrs1'.\n  assert (addrs1' ## {[a]}) by set_solver.\n  pose (decide (elem_of a addrs1)) as a_elem.\n  replace (space_of size1 h' addrs1) with\n          (space_of size1 h addrs1' +\n           if a_elem then size1 sv else 0).\n  setoid_replace (union (image (flip search ((a, ag) :: ar)) addrs1 : addrs) (defs2_addrs defspast)) with\n                 (union (image (flip search ar) addrs1' : addrs) (defs2_addrs defspast)).\n  assert (closed h addrs1') by (eapply closed_alloc_3; eauto).\n  pose proof (H2 _ H5).\n  rewrite -> Nat.mul_add_distr_l.\n  lia.\n  (* image addrs1 union globals is image addrs1' union globals *)\n  - deep_set_unfold.\n    intros. split; intros; deprod.\n    + destruct H5; try solve [right; assumption].\n      (* old in image *)\n      deprod.\n      destruct (decEq x0 a); simplify_eq.\n      (* equals a, in globals *)\n      * right. unfold addr_in, addr_in_env0 in H1.\n        deprod. unfold lookup in *. inversion H6; subst.\n        exists (x0, vaddr x); eauto with searches.\n      (* else, in old *)\n      * left...\n    + destruct H5; try solve [right; assumption].\n      (* old in image *)\n      deprod.\n      left. exists x0.\n      forced (decEq x0 a)...\n  (* addrs_space addrs1 addrs1' *)\n  - destruct a_elem.\n    (* in addrs1 *)\n    + setoid_replace addrs1 with (union addrs1' {[a]}) by (set_unfold; intros x; destruct (decEq x a); subst; intuition).\n      rewrite -> addrs_space_union...\n      pose (heap_extension_one H0) as h0.\n      rewrite -> (addrs_space_extension h0).\n      f_equal.\n      unfold addrs_space0, space_of. rewrite -> elements_singleton.\n      simpl. unfold lookup_size.\n      replace (h' !! a) with (Some sv) by eauto with heaps.\n      lia.\n      (* extension preserves  in addrs1' *)\n      * intros. assert (a0 <> a) by set_solver.\n        eauto with heaps.\n    (* no a in addrs1 *)\n    + setoid_replace addrs1 with addrs1' by set_solver.\n      pose (heap_extension_one H0) as h0.\n      rewrite -> (addrs_space_extension h0).\n      lia.\n      * intros. assert (a0 <> a) by set_solver.\n        eauto with heaps.\nQed.\n\n\n\n\n\nTheorem skip_source_step ar defs defspast m n s0 sg0 :\n    NoDup (map fst defs) ->\n    not_stuck s0 ->\n    state_valid s0 ->\n\n    state_related ar defs defspast 0 s0 sg0 ->\n\n    head_global (map fst defs) (icode s0) ->\n\n    exists (ar' : address_relation) (s1 : state),\n      (step None s0 s1 /\\\n       state_related ar' defs defspast 0 s1 sg0 /\\\n       (globalize_safe ar (map fst defs) defspast m n s0 sg0 ->\n        globalize_safe ar' (map fst defs) defspast m n s1 sg0)).\nProof with eauto.\n  intros nodup0 notstuck0 valid0 rel0 global0.\n  destruct rel0.\n  rewrite -> drop_0 in defspast_same.\n  assert (nodup1: NoDup (map fst defspast)) by congruence.\n\n  assert (hvalid : heap_valid h).\n  { apply heap_valid_in_heap_proj_l2r.\n    unfold state_valid in valid0.\n    rewrite <- state_valid_product in valid0.\n    deprod... }\n\n  destruct code_rel.\n  simpl in global0. unfold head_global in global0.\n  destruct c; simpl in global0; try contradiction;\n  inversion notstuck0; subst; try (inversion H); subst.\n  (* smallExp *)\n  - assert (global1: In v (map fst defspast)) by (rewrite -> defspast_same; exact global0).\n    simpl in H0.\n    inversion H1; subst; try (rewrite -> (In_if_member _ _ _ _ global0) in H0; contradiction).\n\n    apply In_map_fst_In in global1.\n    deprod.\n    pose proof (defspast_sound_val v y global1).\n    deprod.\n    destruct d; simpl in H0; try solve [rewrite -> (In_search _ _ _ nodup0 H) in H0; contradiction].\n    inversion H2; subst.\n    (* addr *)\n    + exists ((a, a0) :: ar).\n      exists (<< c, (v, vaddr a) :: e, h', k >>)%interp.\n      split...\n      split.\n      (* related *)\n      * split...\n        (* relation in heaps *)\n        -- intros. inversion heap_rel.\n           pose proof (global_addrs v (vaddr a0) global1).\n           simpl in H4. deprod.\n           destruct H3; simplify_eq; eauto with heaps.\n           destruct (ar_heap_dom a1 ag H3); eauto with heaps.\n        (* code related *)\n        -- pose proof (In_fst_search _ _ global0).\n           deprod.\n           rewrite -> X0 in H0.\n           forced y.\n           deprod...\n           split... f_equal. simpl.\n           rewrite -> In_if_member...\n        -- simpl in env_rel.\n           forced (member v (map fst defs)).\n           eapply env_relate_subset.\n           eapply env_extend_source_global...\n           ++ eauto with related.\n           ++ apply env_relate_alloc...\n              addr_conflict h a.\n           ++ clear. set_unfold. intros. destruct (decEq x v)...\n           ++ simpl. rewrite -> Heqs. reflexivity.\n        -- inversion heap_rel; subst.\n           pose proof (global_addrs _ _ global1). simpl in H3.\n           deprod.\n           replace d with (dtuple var l) in * by eauto with searches.\n           rewrite -> (In_search _ _ _ nodup0 H3) in H0.\n           eapply heap_extend_source_global; eauto 10 with addr_in...\n           ++ assert (In v (map fst defs)) by eauto with searches.\n              inversion H5; subst.\n              assert (valid_in_heap (e, free_vars (VAL v := tupleExp xs IN\n                                                                     c)) h) by eauto 20 with addr_in.\n              do 2 intro.\n              apply H7.\n              apply addr_in_searches with xs vs...\n              intros. simpl. clear - H10. rewrite <- elem_of_list_In in H10. set_solver.\n         \n           ++ inversion H5; subst.\n              constructor.\n              destruct env_rel. simpl in *.\n              forced (member v (map fst defs)).\n              deprod. subst.\n              clear - lkps H7 global_vals_agree.\n\n              generalize dependent vs.\n              generalize dependent vals.\n              unfold searches.\n              induction l; intros vgs lkpvgs vs lkpvs; simpl in *.\n              ** simplify_eq. constructor.\n              ** forced (search a defspast).\n                 forced (map_option (flip search defspast) l).\n                 forced (search a e).\n                 forced (map_option (flip search e) l).\n                 simplify_eq.\n                 constructor...\n                 --- apply global_vals_agree with a...\n                     eauto with searches.\n                     clear. set_solver.\n                 --- apply IHl...\n                     intros.\n                     apply global_vals_agree with x...\n                     clear - H0. set_solver.\n        -- apply stack_relate_alloc...\n           addr_conflict h a.\n        -- simpl.\n           assert (~ In a (map fst ar)).\n           { intro. apply In_fst_search in H3.\n             deprod. assert (In (a, y) ar) by eauto with searches.\n             destruct (ar_heap_dom a y)...\n             addr_conflict h a. }\n           constructor...\n      * intros safe0. inversion safe0; subst.\n        constructor.\n        -- intros addrs1 caddrs1.\n           eapply larger_safe...\n           unfold addr_in, addr_in_env0.\n           exists v, (vaddr a0). split...\n           eauto with searches.\n        -- intros addrs1 caddrs1.\n           rewrite <- (Nat.mul_1_l (addrs_space0 _ _)) at 1.\n           eapply larger_safe...\n           unfold addr_in, addr_in_env0.\n           exists v, (vaddr a0). split...\n           eauto with searches.\n           simpl; intros.\n           rewrite -> Nat.add_0_r...\n    (* constant *)\n    + pose proof (In_fst_search _ _ global0).\n      deprod.\n      rewrite -> X0 in H0.\n      forced y.\n      deprod; simplify_eq.\n      exists ar. exists (<< c, (v, vconst b0) :: e, h, k >>)%interp.\n      repeat split_and...\n      * split...\n        (* code *)\n        -- simpl. rewrite -> In_if_member...\n           split...\n        (* env *)\n        -- simpl. rewrite -> In_if_member...\n           assert (In (v, dconst var b0) defs) by eauto with searches.\n           destruct (In_fst_search _ _ global1) as [vg ?].\n           assert (In (v, vg) defspast) by eauto with searches.\n           eapply env_relate_subset.\n           eapply env_extend_source_global...\n           ++ destruct (defspast_sound_val v vg H2).\n              deprod.\n              assert (x = dconst var b0) by eauto with searches.\n              subst.\n              inversion H4...\n              constructor.\n           ++ simpl. clear.\n              set_unfold. intros; destruct (decEq x v)...\n           ++ simpl.\n              forced (member v (map fst defs))...\n      * intro safe0.\n        inversion safe0; split...\n  - pose proof (X true) as [? _].\n    inversion s0.\n  - inversion H1; subst.\n    simpl in H0. rewrite -> In_if_member in H0...\n    contradiction.\n  - inversion H1; subst.\n    simpl in H0.\n    destruct (search v defs) eqn:searchv.\n    + forced d. deprod.\n      simpl in *. subst.\n      forced (member v (map fst defs)).\n      assert (global1: In v (map fst defspast)) by congruence.\n      forced (search v defs).\n      simplify_eq.\n      pose proof (In_fst_search _ _ global1).\n      deprod.\n      assert (In (v, y) defspast) by eauto with searches.\n      pose proof (defspast_sound_val v y H0).\n      deprod.\n      assert (In (v, dabs var v1 (elim_defs (map fst defs) c1)) defs) by eauto with searches.\n      pose proof (In_pair_unique _ _ _ _ nodup0 H2 H6).\n      subst.\n      inversion H5; subst.\n\n      exists ((a, a0) :: ar). exists (<< c2, (v, vaddr a) :: e, h', k >>)%interp.\n\n      repeat split_and...\n      * split...\n        -- destruct heap_rel.\n           intros. destruct H7; simplify_eq...\n           ++ split; eauto with heaps.\n              pose proof (global_addrs v _ H0).\n              simpl in H7. deprod... eauto with heaps.\n           ++ pose proof (ar_heap_dom _ _ H7).\n              deprod; split; eauto with heaps.\n        -- split...\n        -- eapply env_relate_subset.\n           eapply env_extend_source_global...\n           { eauto with related. }\n           eapply env_relate_alloc...\n           addr_conflict h a.\n           ++ set_unfold. intros.\n              destruct (decEq x v)...\n           ++ reflexivity.\n        -- inversion heap_rel.\n           pose proof (global_addrs v _ H0).\n           simpl in H7. deprod.\n           \n           eapply heap_extend_source_global...\n           { do 2 intro.\n             inversion H10. deprod.\n             apply valid0.\n             unfold addr_in, addr_in_state.\n             right. right. simpl. exists x, v0.\n             repeat split_and...\n             clear - H12. set_solver. }\n           eauto 20 with addr_in.\n           pose proof (In_pair_unique _ _ _ _ nodup0 H2 H7).\n           subst.\n           inversion H9; subst.\n           constructor. constructor...\n           ++ constructor...\n           ++ congruence.\n           ++ destruct env_rel.\n              constructor...\n              ** intros. set_unfold. deprod...\n              ** intros. set_unfold.\n                 deprod. rewrite -> in_free_vars_iff_free_in in H11.\n                 pose proof (H13 x H11 H14).\n                 deprod. exists x0. split...\n                 eapply global_vals_agree...\n                 eauto with searches.\n              ** intros. set_unfold.\n                 deprod. rewrite -> in_free_vars_iff_free_in in H11.\n                 apply (global_vals_agree x v0 vg)...\n                 left. split... eauto with free_in.\n              ** intros. set_unfold.\n                 deprod.\n                 rewrite -> in_free_vars_iff_free_in in H11.\n                 pose proof (H13 x H11 H12).\n                 deprod...\n                 assert (In (x, x0) defspast) by eauto with searches.\n                 destruct (In_pair_unique defspast x _ _ nodup1 H10 H16).\n                 exact H15.\n        -- apply stack_relate_alloc...\n           addr_conflict h a.\n        -- simpl.\n           assert (~ In a (map fst ar)).\n           { intro. apply In_fst_search in H7.\n             deprod. assert (In (a, y) ar) by eauto with searches.\n             destruct (ar_heap_dom a y)...\n             addr_conflict h a. }\n           constructor...\n      * intros. inversion H7; subst. constructor.\n        -- eapply larger_safe...\n           unfold addr_in, addr_in_env0.\n           exists v, (vaddr a0). split...\n        -- intros.\n           rewrite <- (Nat.mul_1_l (addrs_space0 _ _)).\n           eapply larger_safe...\n           unfold addr_in, addr_in_env0.\n           exists v, (vaddr a0). split...\n           intros. simpl. rewrite -> Nat.add_0_r...\n    + contradict global0.\n      intro. pose proof (In_fst_search_not_None _ _ H).\n      contradiction.\n  - pose proof (X true) as [? _].\n    inversion s.\n  - inversion H1.\nQed.\n\nTheorem skip_source_steps ar defs defspast m n s0 sg0 :\n    NoDup (map fst defs) ->\n\n    not_stuck s0 ->\n    state_valid s0 ->\n\n    state_related ar defs defspast 0 s0 sg0 ->\n\n\n    exists (ar' : address_relation) (s1 : state) (stp: steps s0 s1),\n      (head_not_global (map fst defs) (icode s1) /\\\n       same_head (icode s1) (icode sg0) /\\\n       steps_io stp = [] /\\\n       state_related ar' defs defspast 0 s1 sg0 /\\\n       (globalize_safe ar (map fst defs) defspast m n s0 sg0 ->\n       globalize_safe ar' (map fst defs) defspast m n s1 sg0)).\nProof with try contradiction || eauto.\n  intros nodup0 notstuck0 valid0 rel0.\n  destruct s0 as [c0 e0 h0 k0].\n  generalize dependent k0.\n  generalize dependent h0.\n  generalize dependent e0.\n  generalize dependent ar.\n\n  induction c0; intros ar e0 h0 k0 notstuck0 valid0 rel0;\n    destruct sg0 as [cg0 eg0 hg0 kg0]; simpl ienv in *; simpl iheap in *;\n      inversion rel0; subst;\n        destruct code_rel as [code0 agree0]; simpl in agree0;\n  rewrite -> drop_0 in defspast_same.\n  (* letsmall *)\n  - pose (<< (VAL v := s IN c0)%exp, e0, h0, k0 >>)%interp as s0.\n    pose (<< cg0, eg0, hg0, kg0 >>)%interp as sg0.\n    destruct s.\n    (* tuple *)\n    + inversion notstuck0; try inversion H; subst.\n      * destruct (member v (map fst defs)) eqn:searchdefs.\n        -- pose proof (skip_source_step ar defs defspast m n s0 sg0 nodup0 notstuck0 valid0 rel0 i).\n           deprod.\n           destruct s1 as [c1 e1 h1 k1].\n           replace c1 with c0 in * by (inversion H0; eauto).\n           pose (<<c0, e1, h1, k1>>)%interp as s1.\n           assert (notstuck1: not_stuck s1) by (apply not_stuck_step with None s0; eauto).\n           assert (valid1: state_valid s1) by (apply state_valid_step with s0 None; eauto).\n           pose proof (IHc0 ar' e1 h1 k1 notstuck1 valid1 H1).\n           deprod.\n           pose (st_cons (st_refl s0) H0) as stp1.\n           exists ar'0. exists s2. exists (steps_compose stp1 stp).\n\n           repeat split_and...\n           rewrite -> steps_io_distrib. rewrite -> H5. unfold stp1.\n           simpl. reflexivity.\n        -- exists ar, s0, (st_refl s0)...\n           repeat split_and...\n           simpl.  rewrite -> searchdefs. constructor.\n      * pose proof (X true) as [impossible _].\n        inversion impossible.\n    (* app *)\n    + exists ar. exists s0... exists (st_refl _)...\n      repeat split_and...\n      simpl. intro. destruct (member v (map fst defs))...\n      simpl in *. destruct (member v (map fst defs)); simplify_eq; try constructor...\n    (* proj *)\n    + exists ar. exists s0... exists (st_refl _)...\n      repeat split_and...\n      simpl. intro. destruct (member v (map fst defs))...\n      simpl in *. destruct (member v (map fst defs)); simplify_eq; try constructor...\n    (* write *)\n    + exists ar. exists s0... exists (st_refl _)...\n      repeat split_and...\n      simpl. intro. destruct (member v (map fst defs))...\n      simpl in *. destruct (member v (map fst defs)); simplify_eq; try constructor...\n    (* read *)\n    + exists ar. exists s0... exists (st_refl _)...\n      repeat split_and...\n      simpl. intro. destruct (member v (map fst defs))...\n      simpl in *. destruct (member v (map fst defs)); simplify_eq; try constructor...\n    (* const *)\n    + destruct (search v defs) eqn:searchv.\n      (* skip *)\n      * forced d. deprod. subst. simpl.\n        assert (In v (map fst defs)) by eauto with searches.\n        forced (member v (map fst defs)).\n\n        pose proof (skip_source_step ar defs defspast m n s0 sg0 nodup0 notstuck0 valid0 rel0 i).\n        deprod.\n        assert (notstuck1: not_stuck s1) by eauto with steps.\n        assert (valid1: state_valid s1) by eauto with steps.\n        destruct s1.\n        replace icode0 with c0 in * by (inversion H1; eauto).\n        pose proof (IHc0 ar' _ _ _ notstuck1 valid1 H2).\n        deprod.\n        simpl in *.\n        forced (member v (map fst defs)).\n\n        pose (st_cons (st_refl _) H1) as stp1.\n        exists ar'0. exists s1. exists (steps_compose stp1 stp).\n\n        repeat split_and...\n        rewrite -> steps_io_distrib. rewrite -> H6. unfold stp1.\n        simpl. reflexivity.\n      * exists ar, s0, (st_refl s0)...\n        assert (~ In v (map fst defs)).\n        { intro. assert (search v defs <> None) by eauto with searches. contradiction. }\n        repeat split_and...\n        simpl in *. subst.\n        forced (member v (map fst defs)).\n        constructor.\n  (* abs, see if we should skip *)\n  - destruct (search v defs) eqn:searchv.\n    (* skip *)\n    + forced d. deprod. subst. simpl.\n      assert (In v (map fst defs)) by eauto with searches.\n      forced (member v (map fst defs)).\n\n      pose proof (skip_source_step ar defs defspast m n _ _ nodup0 notstuck0 valid0 rel0 i).\n      deprod.\n      assert (notstuck1: not_stuck s1) by eauto with steps.\n      assert (valid1: state_valid s1) by eauto with steps.\n      destruct s1.\n      replace icode0 with c0_2 in * by (inversion H1; eauto).\n      pose proof (IHc0_2 ar' _ _ _ notstuck1 valid1 H4).\n      deprod.\n      simpl in *.\n      forced (member v (map fst defs)).\n\n      pose (st_cons (st_refl _) H1) as stp1.\n      exists ar'0. exists s1. exists (steps_compose stp1 stp).\n\n      repeat split_and...\n      rewrite -> steps_io_distrib. rewrite -> H8. unfold stp1.\n      simpl. reflexivity.\n    + exists ar, (<< (letabs v v0 c0_1 c0_2), e0, h0, k0 >>)%interp, (st_refl _)...\n      assert (~ In v (map fst defs)).\n      { intro. assert (search v defs <> None) by eauto with searches. contradiction. }\n      repeat split_and...\n      simpl in *. subst.\n      forced (member v (map fst defs)).\n      constructor.\n (* branch *)\n  - exists ar.\n    exists (<< branch v c0_1 c0_2, e0, h0, k0 >>)%interp...\n    exists (st_refl _)...\n    simpl. repeat split_and...\n    subst. constructor.\n  (* tail *)\n  - exists ar.\n    exists (<< tail v v0, e0, h0, k0 >>)%interp...\n    exists (st_refl _)...\n    repeat split_and...\n    subst. constructor.\n  (* return *)\n  - exists ar.\n    exists (<< ret v, e0, h0, k0 >>)%interp...\n    exists (st_refl _)...\n    repeat split_and...\n    subst. constructor.\nQed.\n\nTheorem globalize_safe0 :\n  forall (P: exp) defs,\n    defs_agree defs P ->\n    defs_well_scoped defs ->\n    NoDup (map fst defs) ->\n\n    (forall x, ~ free_in x P) ->\n    not_stuck (start_state P) ->\n\n  forall (t: state) (stpt: steps (start_state (globalize defs P)) t),\n    (* initial steps, defs is partitioned, the start state is pinned down *)\n    (exists remaining,\n        remaining <= length defs /\\\n        steps_io stpt = [] /\\\n        istack t = [] /\\\n        state_related [] defs (ienv t) remaining (start_state P) t /\\\n        addrs_space0 (iheap t) (defs2_addrs (ienv t)) = sum_list (map defined_size (map snd (drop remaining defs))) /\\\n        addrs_space_g (map fst defs) (iheap t) (defs2_addrs (ienv t)) = sum_list (map (defined_size_g (map fst defs)) (map snd (drop remaining defs))))\n        \\/\n    (exists ar defspast\n            (s: state) (stps: steps (start_state P) s),\n        steps_io stpt = steps_io stps /\\\n        state_related ar defs defspast 0 s t /\\\n        globalize_safe ar (map fst defs) defspast\n                       (sum_list (map defined_size (map snd defs)))\n                       (sum_list (map (defined_size_g (map fst defs)) (map snd defs)))\n                       s t).\nProof with eauto.\n  intros P defs agree0 scoped0 nodup0 Pclosed Pnot_stuck t stpt.\n  remember (start_state (globalize defs P)) as t0.\n  induction stpt; subst; try pose proof (IHstpt eq_refl) as IHstpt.\n  - left.\n    exists (length defs).\n    repeat split_and...\n    (* related *)\n    + simpl. constructor; simpl; try constructor; intros; try solve [intros; discriminate || contradiction]...\n      * replace (length defs) with (length (map fst defs)) by apply map_length.\n        symmetry.\n        apply drop_all.\n      (* ar valid *)\n      * unfold valid_in_heap, addr_in, addr_in_env. simpl.\n        intros. deprod...\n        inversion H. deprod. unfold lookup, search in H0. discriminate.\n      (* code 1 *)\n      * simpl.\n        rewrite -> firstn_all.\n        reflexivity.\n      * rewrite -> in_free_vars_iff_free_in in H.\n        exfalso... apply Pclosed with x...\n      (* heap *)\n      * intros.\n        rewrite -> lookup_empty in H. discriminate.\n    (* safe *)\n    + rewrite -> drop_all. simpl.\n      unfold defs2_addrs. simpl.\n      unfold addrs_space0, space_of. rewrite -> elements_empty.\n      simpl. reflexivity.\n    + rewrite -> drop_all. simpl.\n      unfold defs2_addrs. simpl.\n      unfold addrs_space_g, space_of. rewrite -> elements_empty.\n      simpl. reflexivity.\n  - deprod.\n    destruct IHstpt.\n    (* still processing globals *)\n    + deprod.\n      destruct remaining.\n      (* finished, make a real step *)\n      { right. simpl in *; subst.\n        rewrite -> H0.\n        pose proof (skip_source_steps [] defs (ienv s2) (sum_list (map defined_size (map snd defs))) (sum_list (map (defined_size_g (map fst defs)) (map snd defs))) (start_state P) s2 nodup0 Pnot_stuck\n                   (state_valid_start P) H2).\n        deprod.\n        assert (notstuck1: not_stuck s1) by eauto with steps.\n        assert (valid1: state_valid s1) by eauto with steps.\n\n        pose proof (source_step ar' defs (ienv s2) s1 s2 s3 i notstuck1 H6 valid1 H8 s).\n        deprod.\n        assert (valid2: state_valid s2) by eauto with steps.\n\n        simpl in H2.\n\n        pose proof (initial_safe defs 0 P s2 H2).\n        rewrite -> H3 in H11.\n        rewrite -> H4 in H11.\n\n        pose proof (related_step ar' defs (ienv s2)\n                                 (sum_list (map defined_size (map snd defs)))\n                                 (sum_list (map (defined_size_g (map fst defs)) (map snd defs)))\n                                 s1 s2 s' s3 i H6 valid1 valid2 nodup0 I H10 s (conj H8 (H9 H11))).\n        deprod.\n        exists ar'0, (ienv s2), s'.\n        exists (st_cons stp H10).\n        simpl.\n        rewrite -> H7.\n        repeat split_and...\n      } (* need to merge into lemma *)\n      simpl in *; subst.\n\n      inversion H2; subst.\n      destruct code_rel.\n\n      destruct (lookup_lt_is_Some_2 defs remaining) as [(bx, bd)]. rewrite <- Nat.le_succ_l...\n      rewrite -> (take_S_r defs _ _ H7) in H5.\n      rewrite -> bind_globals_app in H5.\n      simpl in H5.\n\n      assert (lkpbx: ([]: env) !! bx = None) by eauto.\n      simpl in nodup0, scoped0, agree0.\n      pose (<< cg, eg, hg, kg >>)%interp as s2.\n      assert (envempty: forall (x: var), search x [] = (None : option value)) by reflexivity.\n      simpl in H3.\n      pose proof (initial_step bx bd defs remaining P s2 s3 i nodup0 scoped0 H7 H2 s)...\n      deprod.\n\n      inversion H7; subst.\n      simpl istack in *.\n      simpl ienv in *.\n      simpl iheap in *.\n      left.\n      exists remaining.\n      repeat split_and...\n      * lia.\n      * rewrite -> H0.\n        destruct bd; simpl in s; inversion s; reflexivity.\n      * inversion H8; subst. simpl in *. inversion stack_rel0...\n\n    (* No more defs to process, go through normal evaluation *)\n    + right. deprod.\n      (* all of these are true by the existence of any steps *)\n      assert (notstuck0: not_stuck s0) by eauto with steps.\n      assert (valid0: state_valid s0) by eauto with steps.\n      (* need to include in relation ? *)\n      pose proof (skip_source_steps ar defs defspast\n                                    (sum_list (map defined_size (map snd defs)))\n                                    (sum_list (map (defined_size_g (map fst defs)) (map snd defs)))\n                                    s0 s2 nodup0 notstuck0 valid0 H0) as skip.\n      deprod.\n      assert (notstuck1: not_stuck s1) by eauto with steps.\n      assert (valid1: state_valid s1) by eauto with steps.\n      assert (valid2: state_valid s2) by eauto with steps.\n      destruct (source_step ar' defs defspast s1 s2 s3 i) as [s1' ?]...\n      pose proof (related_step ar' defs defspast\n                               (sum_list (map defined_size (map snd defs)))\n                               (sum_list (map (defined_size_g (map fst defs)) (map snd defs)))\n                               s1 s2 s1' s3 i H3 valid1 valid2 nodup0 I H7 s (conj H5 (H6 H1))).\n      deprod.\n\n      exists ar'0, defspast, s1'.\n      exists (st_cons (steps_compose stps stp) H7).\n      simpl.\n      rewrite -> steps_io_distrib.\n      rewrite -> H4. simpl.\n      repeat split_and...\n      * rewrite -> H...\nQed.\nLemma clos_addr_in_src :\n  forall ar defs defspast clos closg a2,\n    forall (defspast_same : map fst defspast = map fst defs),\n    clos_related ar defs defspast clos closg ->\n    addr_in closg a2 ->\n    (exists a1,\n      In (a1, a2) ar /\\\n       addr_in clos a1) \\/\n      elem_of a2 (defs2_addrs defspast).\nProof with eauto.\n  intros.\n  inversion H; subst.\n  destruct H1.\n  rewrite -> firstn_O in *.\n  simpl in *.\n  inversion H3; subst.\n  pose proof (free_vars_elim_defs cl (map fst defs)).\n  unfold addr_in, addr_in_clos, addr_in, addr_in_env in *.\n  deep_set_unfold.\n  destruct (H1 _ H5).\n  + assert (el !! x <> None) by eauto.\n    forced (el !! x).\n    destruct (pairs_related x v0)...\n    deprod.\n    simplify_eq.\n    inversion H6; subst.\n    inversion H11; subst.\n    left.\n    exists a. split... eauto with searches.\n    unfold addr_in, addr_in_svalue, addr_in, addr_in_clos, addr_in, addr_in_env.\n    do 2 eexists. repeat split_and...\n    constructor.\n  + deprod. simplify_eq. simpl in *.\n    inversion H6; subst.\n    assert (In v0 (map fst defs)) by eauto with searches.\n    assert (In v0 (map fst defspast)) by congruence.\n    destruct (In_fst_search _ _ H10).\n    assert (In (v0, x) defspast) by eauto with searches.\n    pose proof (globals_present v0 x H11 (conj H5 H7)).\n    simplify_eq.\n    inversion H6; subst.\n    right.\n    exists (v0, vaddr a2)...\n    split...\n    eauto with searches.\nQed.\n\nLemma sval_addr_in_src :\n  forall ar defs defspast sv svg a2,\n    forall (samedefs: map fst defspast = map fst defs),\n    sval_related ar defs defspast sv svg ->\n    addr_in svg a2 ->\n    (exists a1,\n      In (a1, a2) ar /\\\n      addr_in sv a1) \\/\n    elem_of a2 (defs2_addrs defspast).\nProof with eauto.\n  intros.\n  inversion H; subst.\n  - inversion H0; subst.\n    deprod. clear H.\n    induction H1.\n    + inversion H2.\n    + simpl in H2.\n      destruct H2.\n      * subst.\n        inversion H3; subst.\n        inversion H; subst.\n        left.\n        exists a.\n        split.\n        -- eauto with searches.\n        -- eauto 20 with addr_in.\n      * destruct IHForall2...\n        eauto 20 with addr_in.\n        deprod.\n        left.\n        exists a1. split...\n        eauto 20 with addr_in.\n  - unfold addr_in, addr_in_svalue.\n    apply clos_addr_in_src with defs closg...\nQed.\n\nLemma image_closure :\n  forall ar defs defspast h hg,\n    (map fst defspast = map fst defs) ->\n    NoDup (map fst ar) ->\n    heap_valid h ->\n    heap_valid hg ->\n    heap_related ar defs defspast h hg ->\n    forall (ar_heap_dom: forall a1 a2,\n               In (a1, a2) ar -> h !! a1 <> None /\\ hg !! a2 <> None),\n\n    forall (addrs1 : addrs)\n      (addrs1_valid : forall a, elem_of a addrs1 -> h !! a <> None),\n    subseteq\n      (closure _ hg (@image addr addr addrs addrs addrs_elements addrs_empty addrs_union addrs_singleton\n                            (flip search ar) addrs1))\n      (union (image (flip search ar) (closure _ h addrs1)) (defs2_addrs defspast)).\nProof with eauto with searches.\n  intros ar defs defspast h hg samedefs arnodup ? ? ? ? ? ?.\n  unfold image in *.\n  deep_set_unfold. intros.\n  destruct H1.\n  induction x, H2 using (closure_ind H0); deep_set_unfold.\n  (* inject *)\n  - left. exists x. split...\n    + apply closure_inject...\n  (* descend *)\n  - destruct IH1; deep_set_unfold.\n    (* actual image *)\n    + assert (In (x, a) ar) by eauto with searches.\n      destruct (ar_heap_dom _ _ H5).\n      forced (h !! x).\n      destruct (sval_addr_in_src ar defs defspast s v a2 samedefs)...\n      * pose proof (related_addrs _ _ Heqo). deprod.\n        simplify_eq...\n      * left. deprod.\n        exists a1. repeat split_and; eauto with searches.\n        (* in closure *)\n        eapply closure_descend with x s...\n      * right. unfold defs2_addrs in H8.\n        set_unfold. deprod. set_unfold.\n        exists (v0, v1)...\n    + right.\n      rewrite -> elem_of_list_In in H3. pose proof (global_addrs _ _ H3).\n      simpl in H4. deprod...\n      inversion H6; subst...\n      * unfold addr_in, addr_in_svalue in H2. forced v. subst.\n        unfold addr_in, addr_in_svalue, addr_in, addr_in_list, addr_in in H2.\n        deprod. inversion H8; subst.\n        simplify_eq.\n        destruct (In_searches _ _ _ _ H7 H2).\n        deprod.\n        exists (x, vaddr a2). split...\n      * unfold addr_in, addr_in_svalue in H2. forced v. simplify_eq.\n        unfold addr_in, addr_in_svalue, addr_in, addr_in_clos, addr_in, addr_in_env, addr_in in H2.\n        deprod. inversion H8; subst.\n        exists (x, vaddr a2).\n        split...\n        set_unfold. deprod.\n        rewrite -> in_free_vars_iff_free_in in H5.\n        destruct (H7 x)... deprod...\n        simplify_eq...\nQed.\n\nLemma roots_subset :\nforall ar defs defspast c e k eg kg,\nforall (samedefs: map fst defspast = map fst defs)\n       (nodup0: NoDup (map fst ar))\n       (nodup1: NoDup (map fst defs))\n       (defspast_sound_val:\n          forall x v, In (x, v) defspast -> exists d,\n              In (x, d) defs /\\\n              defined_value d v),\n  env_related ar defspast (free_vars c) (free_vars (elim_defs (map fst defs) c)) e eg ->\n  stack_related ar defs defspast k kg ->\n  (⋃ map clos_addresses kg ∪ env_addresses (free_vars (elim_defs (map fst defs) c)) eg)\n  ⊆ image (flip search ar) (⋃ map clos_addresses k ∪ env_addresses (free_vars c) e) ∪ (defs2_addrs defspast).\nProof with eauto.\n  intros.\n  deep_set_unfold. rewrite -> elem_of_union_list in H1.\n  destruct H1.\n  (* stack *)\n  - pose proof (@addrs_iff clos _ _) as H4.\n    deep_set_unfold.\n    rewrite -> H4 in H2. clear H4.\n    unfold addr_in, addr_in_clos, addr_in in H2.\n    destruct y as [[xl cl] el].\n    refine\n      (match _ with\n       | or_introl (ex_intro _ a (conj p1 p2)) => or_introl (ex_intro _ a (conj (or_introl p1) p2))\n       | or_intror pf => or_intror pf\n       end).\n    rewrite -> elem_of_list_In in H3.\n    induction H0.\n    + inversion H3.\n    + destruct H3; simplify_eq...\n      * pose proof (clos_addr_in_src ar defs defspast _ _ x samedefs H0).\n        destruct H3.\n        { unfold addr_in, addr_in_clos, addr_in, addr_in_env.\n          deep_set_unfold.\n          exists x0, v... }\n        -- left. deep_set_unfold.\n           exists a1. split; eauto with searches.\n           left.\n           rewrite <- (@addrs_iff clos _ clos_addresses') in H4...\n        -- right.\n           inversion H0; subst.\n           deep_set_unfold.\n           exists (v0, vaddr x)...\n      * destruct IHstack_related...\n        left. deprod.\n        exists a. split...\n        simpl. set_solver.\n  (* env *)\n  - deprod.\n    forced (search x0 eg). forced v.\n    simplify_eq.\n    refine\n      (match _ with\n       | or_introl (ex_intro _ a (conj p1 p2)) => or_introl (ex_intro _ a (conj (or_intror p1) p2))\n       | or_intror pf => or_intror pf\n       end).\n    remember H1 as H2. clear HeqH2.\n    apply free_vars_elim_defs in H1.\n    deep_set_unfold.\n    destruct H1...\n    (* free in code  *)\n    + left.\n      inversion H; subst.\n      assert (e !! x0 <> None) by eauto.\n      forced (e !! x0).\n      pose proof (pairs_related x0 v H1 H2 Heqo0).\n      unfold lookup in *.\n      deprod. simplify_eq.\n      inversion H5; subst.\n      exists a. split...\n      exists x0. split...\n      rewrite -> Heqo0.\n      reflexivity.\n    (* global *)\n    + right.\n      deprod. simpl fst in *. simplify_eq.\n      inversion H; subst.\n      exists (v, vaddr x).\n      split...\n\n      rewrite -> elem_of_list_In in H3.\n      assert (In v (map fst defs)) by eauto with searches.\n      assert (In v (map fst defspast)) by congruence.\n      destruct (In_fst_search  _ _ H4).\n      assert (In (v, x0) defspast) by eauto with searches.\n      pose proof (defspast_sound_val v x0 H5).\n      deprod.\n      replace x1 with d in * by eauto with searches.\n\n      pose proof (globals_present v x0 H5 H2).\n      unfold lookup in *.\n      simplify_eq.\n      rewrite -> elem_of_list_In...\nQed.\n\nLemma globals_closed :\n  forall defs defspast hg,\n    heap_valid hg ->\n    (forall x v,\n      In (x, v) defspast ->\n        match v with\n          (* incorrect value handled in env *)\n        | vaddr ag =>\n          exists d svg,\n          In (x, d) defs /\\\n          hg !! ag = Some svg /\\\n          defined_svalue defspast d svg\n        | _ => True\n        end) ->\n    closed hg (defs2_addrs defspast).\nProof with eauto.\n  intros ? ? ? valid0 global_addrs.\n  unfold closed, set_Forall. deep_set_unfold.\n  intros. deprod. simpl snd in *. simplify_eq.\n  rewrite -> elem_of_list_In in H.\n  pose proof (global_addrs _ _ H). simpl in H0.\n  deprod. exists svg.\n  split...\n  intros.\n  inversion H2; subst; simpl in H3; set_unfold; deprod.\n  - rewrite -> elem_of_list_In in H3.\n    destruct (In_searches _ _ _ x1 H4 H3).\n    deprod.\n    rewrite <- elem_of_list_In in H6.\n    exists (x2, x1). split.\n    eauto with searches. \n    simpl. set_unfold...\n  - forced (search x1 el). forced v0.\n    deep_set_unfold.\n    rewrite -> in_free_vars_iff_free_in in H3.\n    pose proof (H4 x1 H3 H5).\n    deprod.\n    unfold lookup in *. simplify_eq.\n    assert (In (x1, vaddr x0) defspast) by eauto with searches.\n    rewrite <- elem_of_list_In in H7.\n    exists (x1, vaddr x0)...\nQed.\n\n(*** Relatedness + Safety is enough *)\nTheorem state_space_safe :\n  forall ar defs defspast m n s sg,\n    NoDup (map fst defs) ->\n    defs_well_scoped defs ->\n    NoDup (map fst ar) ->\n    state_valid s ->\n    state_valid sg ->\n\n    state_related ar defs defspast 0 s sg ->\n    globalize_safe ar (map fst defs) defspast m n s sg ->\n    (1 + length defs) * state_space s + m >= state_space sg.\nProof with eauto.\n  (* \n    addrs_space0 (iheap sg) (defs2_addrs defspast) = n -> *)\n  intros ar defs defspast m n s sg nodup0 scoped0 nodup1 valid validg rel safe.\n  unfold state_space.\n\n  destruct rel.\n  inversion safe; subst.\n  simpl iheap in *.\n\n  assert (defssame: map fst defspast = map fst defs) by (destruct code_rel; eauto).\n  assert (defslength_same : length defspast = length defs).\n  { do 2 rewrite <- (map_length fst).\n    congruence. }\n\n  assert (size (free_vars cg) <= size (free_vars c) + length defs).\n  { clear - code_rel nodup0 scoped0.\n    remember (map fst defs) as defVars.\n    rewrite <- (map_length fst defs). rewrite <- HeqdefVars.\n    \n    cut (subseteq (free_vars cg) (union (free_vars c) (list_to_set (map fst defs)))).\n    { rewrite <- HeqdefVars.\n      intro is_subset.\n      apply subseteq_size in is_subset.\n\n      transitivity (size (free_vars c ∪ list_to_set defVars))...\n      pose proof (size_union_alt (free_vars c) (list_to_set defVars)).\n      assert (@size vars _ (list_to_set defVars : vars) = length defVars).\n      { clear - nodup0.\n        induction defVars.\n        - rewrite -> list_to_set_nil.\n          rewrite -> size_empty.\n          simpl...\n        - rewrite -> list_to_set_cons.\n          inversion nodup0; subst.\n          assert ({[a]} ## (list_to_set defVars : vars)).\n          { set_unfold. intro.\n            intros; subst.\n            rewrite -> elem_of_list_In in H0.\n            contradiction.\n          }\n          rewrite -> (size_union _ _ H).\n          simpl. rewrite -> size_singleton.\n          f_equal. apply IHdefVars...\n      }\n      rewrite <- H0.\n      assert (size (difference (list_to_set defVars) (free_vars c)) <= size (list_to_set defVars: vars)).\n      { apply subseteq_size. set_solver. }\n      lia.\n    }\n    unfold code_related in *.\n    rewrite <- HeqdefVars in *.\n    simpl in code_rel. deprod. subst.\n    apply free_vars_elim_defs...\n  }\n  assert (env_size: (1 + length defs) * (1 + size (free_vars c)) >= size (free_vars cg)).\n  { rewrite -> Nat.mul_add_distr_l.\n    rewrite -> Nat.mul_1_r.\n    assert ((1 + length defs) * size (free_vars c) >= size (free_vars c)) by (simpl; lia).\n    lia. }\n          \n  assert ((1 + length defs) * sum_list (map clos_size k) >= sum_list (map clos_size kg)).\n  { simpl in stack_rel.\n    clear - stack_rel defssame.\n    induction stack_rel.\n    - simpl. lia.\n    - simpl. rewrite -> Nat.mul_add_distr_r in IHstack_rel.\n      rewrite -> Nat.mul_1_l in IHstack_rel.\n      rewrite -> Nat.mul_add_distr_l.\n      enough ((1 + length defs) * clos_size clos0 >= clos_size closg).\n      lia.\n\n      inversion H; subst.\n      inversion H0; subst.\n      simpl take.\n      eapply clos_size_related.\n      exact H.\n  }\n\n  remember (closure svalue_addresses' h (live_roots (<< c, e, h, k >>))) as addrs1'.\n  remember (defs2_addrs defspast) as global_addrs.\n  remember (union (global_addrs) (closure svalue_addresses' hg (live_roots (<< cg, eg, hg, kg >>)))) as addrs2'.\n  remember (closure svalue_addresses' hg (live_roots (<< cg, eg, hg, kg >>))) as addrs3'.\n  assert ((1 + length defspast) * addrs_space0 h addrs1' + m >= addrs_space0 hg addrs3').\n  {\n    unfold live_roots.\n\n    assert (H1: valid_in_heap h h) by eauto 20 with addr_in.\n    rewrite -> heap_valid_in_heap in H1.\n    assert (H2: valid_in_heap hg hg) by eauto 20 with addr_in.\n    rewrite -> heap_valid_in_heap in H2.\n    pose proof (closure_closed h (live_roots (<< c, e, h, k >>)) H1).\n    rewrite <- Heqaddrs1' in H3.\n    pose proof (af_safe addrs1' H3).\n    eapply Nat.le_trans with (addrs_space0 hg (image (flip search ar) addrs1' ∪ global_addrs))...\n    apply space_of_subset.\n    set_unfold.\n\n    subst addrs3'.\n    intros. \n    destruct code_rel.\n    simpl in H6.\n    rewrite -> Heqglobal_addrs.\n\n    assert (globals_closed : closed hg (defs2_addrs defspast)).\n    { apply globals_closed with defs...\n      inversion heap_rel... }\n    assert (globals_closure: equiv (closure _ hg (defs2_addrs defspast)) (defs2_addrs defspast))\n    by (apply closure_of_closed; eauto).\n\n    (* membership is decidable, so peirce's law lets us refine the subset deep in the branch *)\n    refine\n      (match (decide (elem_of x (defs2_addrs defspast))) with\n       | left global => or_intror global\n       | right not_global => _\n       end).\n\n    (* have to stage this a bit weird because of typeclass issues *)\n    pose proof (image_closure ar defs defspast h hg defssame nodup1 H1 H2 heap_rel ar_heap_dom).\n    (* duplicate globals in the union here, to apply better *)\n    deep_set_unfold.\n    apply H8.\n    (* all roots valid *)\n    { unfold closed, set_Forall in H3. intros.\n      apply valid. unfold addr_in, addr_in_state.\n      set_unfold.\n      destruct H6.\n      - right. left. unfold addr_in, addr_in_list.\n        rewrite -> elem_of_union_list in H6.\n        deprod. rewrite -> elem_of_list_In in H6.\n        clear - H6 H9.\n        induction k; simpl in *.\n        + contradiction.\n        + destruct H6.\n          * exists a. split...\n            rewrite <- addrs_iff.\n            unfold addresses, clos_addresses'.\n            congruence.\n          * pose proof (IHk H).\n            deprod. exists x...\n      (* env *)\n      - deep_set_unfold.\n        forced (search x1 e).\n        forced v. simplify_eq.\n        right. right.\n        exists x1...\n    }\n    (* image of roots is root *)\n    {\n      enough (elem_of x ((closure svalue_addresses' hg (image (flip search ar) (⋃ map clos_addresses k ∪ env_addresses (free_vars c) e))) ∪ (defs2_addrs defspast))).\n      { clear - H6 not_global. deep_set_unfold. destruct H6; try contradiction... }\n\n      deep_set_unfold.\n      destruct (globals_closure x) as [gcfw _].\n      refine (match _ with\n              | or_introl p => or_introl p\n              | or_intror q => or_intror (gcfw q)\n              end).\n\n      (* need simplification in here *)\n      pose proof (closure_union hg (image (flip search ar) (⋃ map clos_addresses k ∪ env_addresses (free_vars c) e)) (defs2_addrs defspast)). set_unfold.\n      destruct (H6 H2 x) as [fw _].\n      apply fw.\n\n      pose proof (roots_subset ar defs defspast c e k eg kg defssame nodup1 nodup0 defspast_sound_val env_rel stack_rel).\n      apply closure_monotonic with ((⋃ map clos_addresses kg ∪ env_addresses (free_vars (elim_defs (map fst defs) c)) eg) ∪ (defs2_addrs defspast))...\n      - clear - H9. set_solver.\n      - clear - H2 H5 H6 not_global globals_closure.\n        rewrite -> closure_union...\n        set_unfold. left...\n    }\n  }\n\n  fold addrs_space0.\n  remember (length defs) as l.\n  remember (sum_list (map clos_size k)).\n  remember (sum_list (map clos_size kg)).\n  remember (addrs_space0 h addrs1').\n  remember (addrs_space0 hg global_addrs).\n  remember (addrs_space0 hg addrs2').\n  remember (addrs_space0 hg addrs3').\n  remember (size (free_vars c)).\n  remember (size (free_vars cg)).\n  replace (length defspast) with l in * by assumption.\n  clear - H H0 H1 env_size.\n  (* need to simplify multiplication a bit *)\n  replace ((1 + l) * (1 + n2 + n6 + n0)) with ((1 + l) + (1 + l) * n2 + n6 + l * n6 + (1 + l) * n0) by lia.\n  lia.\nQed.\n\nDefinition state_space_g defVars st :=\n  match st with\n  | (<< c, _, h, k >>)%interp =>\n      let roots := live_roots st in\n      let addrs := closure svalue_addresses' h roots in\n      1 + space_of (svalue_size_g defVars) h addrs + size (difference (free_vars c) (list_to_set defVars)) + sum_list (map (clos_size_g defVars) k)\n  end.\n  \n(*** Relatedness + Safety is enough *)\nTheorem state_space_safe_g :\n  forall ar defs defspast m n s sg,\n    NoDup (map fst defs) ->\n    defs_well_scoped defs ->\n    NoDup (map fst ar) ->\n    state_valid s ->\n    state_valid sg ->\n\n    state_related ar defs defspast 0 s sg ->\n    globalize_safe ar (map fst defs) defspast m n s sg ->\n    state_space s + n >= state_space_g (map fst defs) sg.\nProof with eauto.\n  intros ar defs defspast m n s sg nodup0 scoped0 nodup1 valid validg rel safe.\n  unfold state_space, state_space_g.\n\n  destruct rel.\n  inversion safe; subst.\n  simpl iheap in *.\n\n  pose (map fst defs) as defVars.\n\n  assert (defssame: map fst defspast = map fst defs) by (destruct code_rel; eauto).\n  assert (defslength_same : length defspast = length defs).\n  { do 2 rewrite <- (map_length fst).\n    congruence. }\n\n  assert (size (free_vars c) >= size (difference (free_vars cg) (list_to_set defVars))).\n  { clear - code_rel nodup0 scoped0.\n    unfold code_related in *. simpl in code_rel.\n    deprod. subst.\n    pose proof (free_vars_elim_defs c defVars).\n    apply subseteq_size.\n    set_solver.\n  }\n          \n  assert (sum_list (map clos_size k) >= sum_list (map (clos_size_g defVars) kg)).\n  { simpl in stack_rel.\n    clear - stack_rel defssame.\n    induction stack_rel.\n    - simpl. lia.\n    - simpl.\n      enough (clos_size clos0 >= clos_size_g defVars closg) by lia.\n\n      inversion H; subst.\n      inversion H0; subst.\n      eapply clos_size_related_g.\n      exact H.\n  }\n\n  remember (closure svalue_addresses' h (live_roots (<< c, e, h, k >>))) as addrs1'.\n  remember (defs2_addrs defspast) as global_addrs.\n  remember (union (global_addrs) (closure svalue_addresses' hg (live_roots (<< cg, eg, hg, kg >>)))) as addrs2'.\n  remember (closure svalue_addresses' hg (live_roots (<< cg, eg, hg, kg >>))) as addrs3'.\n  assert (addrs_space0 h addrs1' + n >= addrs_space_g defVars hg addrs3').\n  {\n    assert (H1: valid_in_heap h h) by eauto 20 with addr_in.\n    rewrite -> heap_valid_in_heap in H1.\n    assert (H2: valid_in_heap hg hg) by eauto 20 with addr_in.\n    rewrite -> heap_valid_in_heap in H2.\n    pose proof (closure_closed h (live_roots (<< c, e, h, k >>)) H1).\n    rewrite <- Heqaddrs1' in H3.\n    pose proof (af_safe_g addrs1' H3).\n    eapply Nat.le_trans with (addrs_space_g defVars hg (image (flip search ar) addrs1' ∪ global_addrs))...\n    apply space_of_subset.\n    set_unfold.\n\n    subst addrs3'.\n    intros. \n    destruct code_rel.\n    simpl in H6.\n    rewrite -> Heqglobal_addrs.\n\n    assert (globals_closed : closed hg (defs2_addrs defspast)).\n    { apply globals_closed with defs...\n      inversion heap_rel... }\n    assert (globals_closure: equiv (closure _ hg (defs2_addrs defspast)) (defs2_addrs defspast))\n    by (apply closure_of_closed; eauto).\n\n    (* membership is decidable, so peirce's law lets us refine the subset deep in the branch *)\n    refine\n      (match (decide (elem_of x (defs2_addrs defspast))) with\n       | left global => or_intror global\n       | right not_global => _\n       end).\n\n    (* have to stage this a bit weird because of typeclass issues *)\n    pose proof (image_closure ar defs defspast h hg defssame nodup1 H1 H2 heap_rel ar_heap_dom).\n    (* duplicate globals in the union here, to apply better *)\n    deep_set_unfold.\n    apply H8.\n    (* all roots valid *)\n    { unfold closed, set_Forall in H3. intros.\n      apply valid. unfold addr_in, addr_in_state.\n      set_unfold.\n      destruct H6.\n      - right. left. unfold addr_in, addr_in_list.\n        rewrite -> elem_of_union_list in H6.\n        deprod. rewrite -> elem_of_list_In in H6.\n        clear - H6 H9.\n        induction k; simpl in *.\n        + contradiction.\n        + destruct H6.\n          * exists a. split...\n            rewrite <- addrs_iff.\n            unfold addresses, clos_addresses'.\n            congruence.\n          * pose proof (IHk H).\n            deprod. exists x...\n      (* env *)\n      - deep_set_unfold.\n        forced (search x1 e).\n        forced v. simplify_eq.\n        right. right.\n        exists x1...\n    }\n    (* image of roots is root *)\n    {\n      enough (elem_of x ((closure svalue_addresses' hg (image (flip search ar) (⋃ map clos_addresses k ∪ env_addresses (free_vars c) e))) ∪ (defs2_addrs defspast))).\n      { clear - H6 not_global. deep_set_unfold. destruct H6; try contradiction... }\n\n      deep_set_unfold.\n      destruct (globals_closure x) as [gcfw _].\n      refine (match _ with\n              | or_introl p => or_introl p\n              | or_intror q => or_intror (gcfw q)\n              end).\n\n      (* need simplification in here *)\n      pose proof (closure_union hg (image (flip search ar) (⋃ map clos_addresses k ∪ env_addresses (free_vars c) e)) (defs2_addrs defspast)). set_unfold.\n      destruct (H6 H2 x) as [fw _].\n      apply fw.\n\n      pose proof (roots_subset ar defs defspast c e k eg kg defssame nodup1 nodup0 defspast_sound_val env_rel stack_rel).\n      apply closure_monotonic with ((⋃ map clos_addresses kg ∪ env_addresses (free_vars (elim_defs (map fst defs) c)) eg) ∪ (defs2_addrs defspast))...\n      - clear - H9. set_solver.\n      - clear - H2 H5 H6 not_global globals_closure.\n        rewrite -> closure_union...\n        set_unfold. left...\n    }\n  }\n  rewrite -> drop_0 in defspast_same. rewrite -> defspast_same in *.\n\n  unfold defVars in *.\n  unfold addrs_space0, addrs_space_g in *.\n  remember (sum_list (map clos_size k)).\n  remember (sum_list (map (clos_size_g (map fst defs)) kg)).\n  remember (space_of svalue_size h addrs1').\n  remember (space_of (svalue_size_g (map fst defs)) hg global_addrs).\n  remember (space_of (svalue_size_g (map fst defs)) hg addrs2').\n  remember (space_of (svalue_size_g (map fst defs)) hg addrs3').\n  remember (size (free_vars c)).\n  remember (size (difference (free_vars cg) (list_to_set (map fst defs)))).\n  clear - H H0 H1.\n  (* need to simplify multiplication a bit *)\n  lia.\nQed.\n\n\nTheorem global_roots :\n  forall ar defs remaining P cg eg hg kg,\n    defs_well_scoped defs ->\n    map fst eg = drop remaining (map fst defs) ->\n    state_related ar defs eg remaining (start_state P) (<<cg, eg, hg, kg>>) ->\n    (⋃ map clos_addresses kg ∪ env_addresses (free_vars cg) eg)\n      ⊆ (defs2_addrs eg).\nProof with eauto.\n  intros ? ? ? ? ? ? ? ? scoped0 samedefs ?.\n  inversion H; subst.\n  inversion stack_rel; subst.\n  simpl. deep_set_unfold.\n  forced H0. clear Heqo.\n  deprod. \n  forced (search x0 eg).\n  forced v.\n  simplify_eq.\n  inversion code_rel; subst.\n  apply free_vars_related in H1...\n  set_unfold.\n  inversion env_rel; subst.\n  destruct H1...\n  - exists (x0, vaddr x). split...\n    eauto with searches.\n  - exists (x0, vaddr x). split...\n    eauto with searches.\nQed.\n\n\n(* Final theorem *)\n\nTheorem globalize_is_safe :\n  forall (P: exp) defs,\n    defs_agree defs P ->\n    defs_well_scoped defs ->\n    NoDup (map fst defs) ->\n\n    (forall x, ~ free_in x P) ->\n    not_stuck (start_state P) ->\n\n    let m := (sum_list (map defined_size (map snd defs))) in\n    let n := (sum_list (map (defined_size_g (map fst defs)) (map snd defs))) in\n    forall (t: state) (stpt: steps (start_state (globalize defs P)) t),\n      (exists (s: state) (stps: steps (start_state P) s),\n          steps_io stps = steps_io stpt /\\\n          (1 + length defs) * state_space s + m >= state_space t /\\\n          state_space s + n >= state_space_g (map fst defs) t).\nProof with eauto.\n  intros.\n  pose proof (globalize_safe0 P defs H X H0 H1 X0 t stpt).\n  destruct H2; deprod; simplify_eq.\n  - exists (start_state P). exists (st_refl _).\n    split...\n    pose proof (initial_safe defs remaining P t H5).\n    inversion H5; subst.\n    inversion env_rel; subst.\n    simpl state_space.\n    rewrite -> (Nat.mul_add_distr_l (1 + length defs) 1 _).\n    rewrite -> Nat.mul_1_r.\n\n    assert (forall xs, equiv (env_addresses xs []) empty).\n    { intros. unfold env_addresses. induction (elements xs)... }\n    rewrite -> H9.\n    assert (equiv (free_vars P) empty).\n    { set_unfold. intros. intro. apply (H1 x). eauto with free_in. }\n    rewrite -> H10.\n    rewrite -> size_empty.\n    unfold addrs_space0, addrs_space_g, space_of.\n    setoid_replace (union empty empty : addrs) with (empty : addrs) by (clear; set_solver).\n    rewrite -> closure_empty.\n    rewrite -> elements_empty. simpl.\n    replace (S (length defs + length defs * 0 + n)) with (S (length defs + n)) by lia.\n    simpl in *. subst.\n    simpl.\n    pose proof (global_roots [] defs remaining P _ _ _ _ X defspast_same H5).\n    unfold ge.\n\n    assert (heap_valid hg).\n    { assert (state_valid (<< _, eg, hg, [] >>)%interp) by eauto with steps.\n      eauto with addr_in. }\n\n    split.\n    + transitivity (S (addrs_space0 hg (defs2_addrs eg)) + size (free_vars (bind_globals (take remaining defs) (elim_defs (map fst defs) P)))).\n      * subst.\n        inversion code_rel; subst.\n        simpl in *. unfold addrs_space0.\n        apply le_n_S.\n        pose proof (closure_monotonic _ _ (defs2_addrs eg) H11 H4).\n        rewrite -> Nat.add_0_r.\n        transitivity\n          (sum_list\n            (map (lookup_size svalue_size hg)\n                (elements (closure svalue_addresses' hg (defs2_addrs eg))))\n          + size (free_vars (bind_globals (take remaining defs) (elim_defs (map fst defs) P)))).\n        -- apply Nat.add_le_mono_r.\n          apply sum_list_sublist.\n          apply map_sublist.\n          apply elements_submseteq.\n          assumption.\n        -- apply Nat.add_le_mono_r.\n          setoid_replace (closure svalue_addresses' hg (defs2_addrs eg)) with (defs2_addrs eg).\n          reflexivity.\n          eapply closure_of_closed...\n\n          apply globals_closed with defs...\n          inversion heap_rel...\n      * simpl. apply le_n_S.\n        rewrite -> H6. unfold n.\n        enough (size (free_vars (bind_globals (take remaining defs) (elim_defs (map fst defs) P))) <= length defs).\n        enough (sum_list (map defined_size (map snd (drop remaining defs))) <= sum_list (map defined_size (map snd defs))).\n        lia.\n        (* smaller list *)\n        {  apply sum_list_sublist.\n          apply map_sublist.\n          apply map_sublist.\n          apply sublist_submseteq.\n          apply sublist_drop. }\n        (* size free vars *)\n        { pose proof (free_vars_related P defs remaining X).\n          transitivity (size (free_vars P ∪ list_to_set (map fst defs))).\n          * apply subseteq_size.\n            exact H12.\n          * rewrite -> H10.\n            setoid_replace (union empty (list_to_set (map fst defs)) : vars) with \n              (list_to_set (map fst defs) :vars) by (clear; set_solver).\n            rewrite <- (map_length fst).\n            clear.\n            induction (map fst defs); simpl...\n            -- rewrite -> size_empty...\n            -- rewrite -> size_union_alt.\n              rewrite -> size_singleton.\n              apply le_n_S.\n              transitivity (size (list_to_set l : vars))...\n              apply subseteq_size.\n              set_solver.\n        }\n    + apply le_n_S.\n      inversion code_rel; deprod; subst.\n      simpl in *.\n      replace (size (free_vars (bind_globals (take remaining defs) (elim_defs (map fst defs) P)) ∖ list_to_set (map fst defs))) with 0.\n      repeat rewrite -> Nat.add_0_r.\n      unfold space_of.\n      unfold n.\n      * transitivity (sum_list\n                        (map (lookup_size (svalue_size_g (map fst defs)) hg)\n                             (elements\n                                (closure svalue_addresses' hg\n                                         (defs2_addrs eg))))).\n        -- apply sum_list_sublist.\n           apply map_sublist.\n           apply elements_submseteq.\n           apply closure_monotonic...\n        -- setoid_replace (closure svalue_addresses' hg (defs2_addrs eg)) with (defs2_addrs eg).\n           unfold addrs_space_g, space_of in H7.\n           rewrite -> H7.\n           (* drop <= full *)\n           apply sum_list_sublist.\n           apply map_sublist.\n           rewrite -> map_drop.\n           apply submseteq_drop.\n\n           eapply closure_of_closed...\n           apply globals_closed with defs...\n           inversion heap_rel...\n      (* free vars empty *)\n      * replace 0 with (size (empty : vars)) by (apply size_empty).\n        apply set_size_proper.\n        deep_set_unfold.\n        intros; split; try contradiction.\n        intros; deprod.\n        apply free_vars_related in H12...\n        set_unfold.\n        destruct H12...\n        apply H10 in H12...\n\n    + intro. intros. rewrite -> lookup_empty in H11. discriminate.\n  - exists s, stps.\n    split...\n    split...\n    + apply state_space_safe with ar defspast n...\n      * inversion H3...\n      * eauto with steps.\n      * eauto with steps.\n    + apply state_space_safe_g with ar defspast m...\n      * inversion H3...\n      * eauto with steps.\n      * eauto with steps.\nQed.\n\nEnd Globalization.\n\n\n(* need defs2 agrees with defs *)\n(*\nTheorem initial_steps :\n  forall defs cg,\n    defs_well_scoped defs ->\n    NoDup (map fst defs) ->\n\n    { eg : env &\n    { hg : heap svalue &\n          (steps\n             (<< bind_globals defs cg, [], empty, [] >>)%interp\n             (<< cg, eg, hg, [] >>)%interp *\n           (map fst defs = map fst eg) *\n           state_related  eg eg)%type\n    }}.\nProof with eauto with decEq.\n  intros defs cg scoped unique.\n  (* To make the induction go through, we pick c and cg to have\n     the binding at the front, so we need to generalize *)\n  generalize dependent cg.\n  unfold globals_present.\n  induction defs; intros cg.\n  - exists []. exists empty.\n    simpl.\n    repeat split; intros;\n      auto ||\n      discriminate ||\n      case_match; intro; contradiction.\n  - inversion scoped; subst.\n    pose (map fst defs) as defVars.\n    simpl in unique.\n    assert (defs_well_scoped defs) by (inversion scoped; eauto).\n    assert (NoDup (map fst defs)) by (inversion unique; eauto).\n    destruct (IHdefs X H (bind_defined v d cg)) as [eg0 [hg0 [[st0 same_globals] heap_globals]]].\n    destruct d.\n    (* We have  a lot of redundancy between cases that should ideally be factored out *)\n    + (* have to gather some values ahead of time *)\n      (* define tuple values *)\n      destruct (map_option_all_some (fun x => search x eg0) l).\n      { intros. enough (In v0 (map fst defs))...\n        rewrite -> same_globals in H2.\n        destruct (In_fst_search v0 eg0) as [a searchdefs]...\n      }\n      destruct (alloc hg0 (stuple x)) eqn:alloc1.\n      define (st1: (step None\n                      (<< bind_defined v (dtuple var l) cg, eg0, hg0, [] >>)%interp\n                      (<< cg, _, _, _ >>)%interp)).\n      { apply (step_tuple v l _ eg0 hg0 [] x a h)... }\n      exists ((v, vaddr a) :: eg0).\n      exists h.\n      repeat split; try done; try (inversion rel1; subst).\n      * apply (st_cons st0 st1).\n      * simpl. congruence.\n      * intro global. case_match.\n        intro global_in. subst.\n        destruct (((v, vaddr a) :: eg0) !! v0) eqn:search1.\n        unfold lookup in search1.\n        simpl in search1. subst.\n        destruct (decEq v0 v); simplify_eq.\n        -- exists a. exists (stuple x).\n           repeat split...\n           ++ simpl...\n           ++ simpl...\n           ++ eauto with heaps.\n           ++ inversion unique; subst.\n              assert (In (v, d) defs -> False) by eauto with searches.\n              forced global_in; simplify_eq.\n              apply defined_stuple.\n              clear - e H0 H3 unique heap_globals.\n              generalize dependent x.\n              induction l; intros x e...\n              simpl map_option in *.\n\n              forced (search a0 eg0).\n              forced (map_option (λ x : var, search x eg0) l). \n              simplify_eq.\n              rewrite IHl with l0...\n              unfold lookup. simpl.\n              destruct (decEq a0 v); simplify_eq...\n              { absurd (In v (map fst defs))... }\n              intros. inversion H. subst. apply H0...\n              constructor. right...\n        -- assert (In (v0, d) defs) by (forced global_in; assumption).\n           destruct (heap_globals (v0, d) H1) as [a' [sv [in1 [lkp1 [hlkp1 d0]]]]].\n           exists a'. exists sv.\n           deprod.\n           repeat split; simpl...\n           ++ eauto with heaps.\n           ++ clear - d0 same_globals unique scoped.\n              inversion unique; subst.\n              inversion d0; clear d0; subst; constructor.\n              ** generalize dependent vals.\n                 induction xs...\n                 intros vals H.\n                 simpl map_option in *.\n                 unfold lookup in *.\n                 forced (search a0 eg0).\n                 forced (map_option (flip search eg0) xs).\n                 simplify_eq.\n                 rewrite -> (IHxs l0)...\n                 simpl.\n                 destruct (decEq a0 v) as [->|neq]...\n\n                 contradict H1.\n                 enough (In (v, v0) eg0); eauto with searches.\n                 rewrite -> same_globals. eauto with searches.\n              ** unfold lookup in *.\n                 intros x0 x0_free x0_neq.\n                 simpl search in *.\n                 destruct (decEq x0 v)... subst.\n                 contradict H1.\n                 destruct (H v x0_free x0_neq) as [? [? _]].\n                 rewrite -> same_globals.\n                 eauto with searches.\n        (* search can't fail *)\n        -- unfold lookup in search1. simpl in search1.\n           destruct (decEq v0 v); simplify_eq.\n           contradict search1.\n           simpl In in global_in.\n           forced global_in; subst.\n           destruct (heap_globals (v0, d) i) as [? [? [? _]]].\n           deprod.\n           eauto with searches.\n    + destruct (alloc hg0 (sclos (v0, e, eg0))) eqn:alloc1.\n      exists ((v, vaddr a) :: eg0).\n      exists h.\n      repeat split...\n      * simpl. eapply (st_cons st0).\n        constructor...\n      * simpl. congruence.\n        (* FIXME copy-pasted *)\n      * intro global. case_match.\n        intro global_in.\n        destruct (((v, vaddr a) :: eg0) !! v1) eqn:search1.\n        unfold lookup in search1.\n        simpl in search1.\n        destruct (decEq v1 v); simplify_eq.\n        -- exists a. exists (sclos (v0, e, eg0)).\n           repeat split...\n           ++ simpl...\n           ++ simpl...\n           ++ eauto with heaps.\n           ++ inversion unique; subst.\n              assert (In (v, d) defs -> False) by eauto with searches.\n              forced global_in; simplify_eq.\n              apply defined_sclos.\n              clear - H0 unique scoped same_globals heap_globals.\n              intros x0 x0_free x0_neq.\n              enough (In x0 (map fst defs)).\n              ** unfold lookup.\n                 rewrite -> same_globals in H.\n                 destruct (In_fst_search x0 eg0 H) as [y search_x0].\n                 exists y. split...\n                 simpl. destruct (decEq x0 v)...\n                 subst. rewrite <- same_globals in H.\n                 inversion unique; subst.\n                 contradict H3...\n              ** apply H0. constructor...\n        (* copy-pasted, should fix *)\n        -- assert (In (v1, d) defs) by (forced global_in; assumption).\n           destruct (heap_globals (v1, d) H1) as [a' [sv [in1 [lkp1 [hlkp1 d0]]]]].\n           exists a'. exists sv.\n           deprod.\n           repeat split...\n           ++ simpl. forced (decEq v1 v)...\n           ++ simpl. forced (decEq v1 v)...\n           ++ eauto with heaps.\n           ++ clear - d0 same_globals unique scoped.\n              inversion unique; subst.\n              inversion d0; clear d0; subst; constructor.\n              ** generalize dependent vals.\n                 induction xs...\n                 intros vals H.\n                 simpl map_option in *.\n                 unfold lookup in *.\n                 forced (search a0 eg0).\n                 forced (map_option (flip search eg0) xs).\n                 simplify_eq.\n                 rewrite -> (IHxs l)...\n                 simpl.\n                 destruct (decEq a0 v) as [->|neq]...\n\n                 contradict H1.\n                 enough (In (v, v1) eg0); eauto with searches.\n                 rewrite -> same_globals. eauto with searches.\n              ** unfold lookup in *.\n                 intros x0 x0_free x0_neq.\n                 simpl search in *.\n                 destruct (decEq x0 v)... subst.\n                 contradict H1.\n                 destruct (H v x0_free x0_neq) as [? [? _]].\n                 rewrite -> same_globals.\n                 eauto with searches.\n        (* search can't fail *)\n        -- unfold lookup in search1. simpl in search1.\n           destruct (decEq v1 v); simplify_eq.\n           contradict search1.\n           simpl In in global_in.\n           forced global_in; subst.\n           destruct (heap_globals (v1, d) i) as [? [? [? _]]].\n           deprod.\n           eauto with searches.\nQed.\n*)\n", "meta": {"author": "jasoncarr0", "repo": "thesis-formalization-code", "sha": "5050eaa5180d47900bd7800ca9f5a80e60f6c896", "save_path": "github-repos/coq/jasoncarr0-thesis-formalization-code", "path": "github-repos/coq/jasoncarr0-thesis-formalization-code/thesis-formalization-code-5050eaa5180d47900bd7800ca9f5a80e60f6c896/Globalize.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.4726834766204329, "lm_q1q2_score": 0.28899016337374595}}
{"text": "(*  DEC 2.0 language specification.\n   Paolo Torrini  \n   Universite' de Lille - CRIStAL-CNRS\n*)\n\nRequire Import List.\nRequire Import Equality.\nRequire Import Eqdep.\nRequire Import PeanoNat.\nRequire Import Omega.\nRequire Import Eqdep FunctionalExtensionality Tactics.\nRequire Import JMeq.\nRequire Import ProofIrrelevance.\n\n\nRequire Import AuxLibI1.\nRequire Import TypSpecI1. \nRequire Import ModTypI1. \nRequire Import LangSpecI1. \nRequire Import StaticSemI1.\nRequire Import DynamicSemI1.\nRequire Import WeakenI1.\nRequire Import UniqueTypI1.\nRequire Import DerivDynI1.\nRequire Import TransPrelimI1.\nRequire Import TSoundnessI1.\nRequire Import SReducI1.\n\n\nImport ListNotations.\n\n\nModule Determ (IdT: ModTyp) <: ModTyp.\n\nModule SReducL := SReduc IdT.\nExport SReducL.\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\nOpen Scope type_scope.\n\n\n(** stepwise determinism *)\n\nDefinition UniqueEStep \n                     (fenv: funEnv) (env: valEnv)\n                     (s s1 s2: W) (n n1 n2: nat) (e e1 e2: Exp) :=\n    EStep fenv env (Conf Exp s n e) ((Conf Exp s1 n1 e1)) ->\n    EStep fenv env (Conf Exp s n e) ((Conf Exp s2 n2 e2)) -> \n        (s1 = s2) /\\ (n1 = n2) /\\ (e1 = e2).\n\n\nDefinition UniquePStep\n                     (fenv: funEnv) (env: valEnv)\n                     (s s1 s2: W) (n n1 n2: nat) (ps ps1 ps2: Prms) := \n    PStep fenv env (Conf Prms s n ps) ((Conf Prms s1 n1 ps1)) ->\n    PStep fenv env (Conf Prms s n ps) ((Conf Prms s2 n2 ps2)) -> \n       (s1 = s2) /\\ (n1 = n2) /\\ (ps1 = ps2).\n\n\n\n(*******************************************************)\n\nDefinition DPar_E (n9: nat) :=\n  fun (ftenv: funTC) (tenv: valTC) \n      (e: Exp) (t: VTyp) \n      (p: ExpTyping ftenv tenv e t) =>\n  forall (fenv: funEnv) (env: valEnv),                      \n    FEnvTyping fenv ftenv ->\n    EnvTyping env tenv ->\n  forall (n: nat), n <= n9 ->   \n  forall (s s1 s2: W) (n1 n2: nat) (e1 e2: Exp), \n         UniqueEStep fenv env s s1 s2 n n1 n2 e e1 e2.\n\n\nDefinition DPar_P (n9: nat) :=\n  fun (ftenv: funTC) (tenv: valTC) \n                (ps: Prms) (pt: PTyp) \n                (p: PrmsTyping ftenv tenv ps pt) => \n  forall (fenv: funEnv) (env: valEnv),                      \n    FEnvTyping fenv ftenv ->\n    EnvTyping env tenv ->\n  forall (n: nat), n <= n9 -> \n  forall (s s1 s2: W) (n1 n2: nat) (ps1 ps2: Prms),  \n          UniquePStep fenv env s s1 s2 n n1 n2 ps ps1 ps2.\n\n\nDefinition ExpTypingDet_mut (n: nat) :=\n  ExpTyping_mut (DPar_E n) (DPar_P n).\n\nDefinition PrmsTypingDet_mut (n: nat) :=\n  PrmsTyping_mut (DPar_E n) (DPar_P n).\n\n\n(************************************************************************)\n\nLemma deterAux1 (s1 s2: W) (n1 n2: nat) (v1 v2: Value) (e3 e4 e5 e6: Exp) :\n  Conf Exp s1 n1 (IfThenElse (Val v1) e3 e4) =\n  Conf Exp s2 n2 (IfThenElse (Val v2) e5 e6) ->\n  v1 = v2.\n  intros.\n  inversion H; subst.\n  auto.\n Defined.\n\nLemma deterAux2 (s1 s2: W) (n1 n2: nat) (e1 e2 e3 e4 e5 e6: Exp) :\n  Conf Exp s1 n1 (IfThenElse e1 e3 e4) =\n  Conf Exp s2 n2 (IfThenElse e2 e5 e6) ->\n  e1 = e2.\n  intros.\n  inversion H; subst.\n  auto.\n Defined.\n\n\nLemma ExpDeterm_Val (n: nat) :\n  forall (ftenv : funTC) (tenv : valTC) (v : Value) \n    (t : VTyp) (v0 : VTyping v t),\n  DPar_E n ftenv tenv (Val v) t (Val_Typing ftenv tenv v t v0).\n  unfold DPar_E.\n  unfold UniqueEStep.\n  intros.\n  inversion X0.\nDefined.\n\nLemma ExpDeterm_Var (n: nat) :\n  forall (ftenv : funTC) (tenv : valTC) (x : StaticSemL.Id) \n    (t : VTyp) (i : IdTyping tenv x t),\n    DPar_E n ftenv tenv (Var x) t (Var_Typing ftenv tenv x t i).\n  unfold DPar_E, UniqueEStep.\n  intros.\n  inversion X; subst.\n  inversion X0; subst.\n  rewrite H5 in H6.\n  inversion H6; subst.\n  auto.\nDefined.  \n\nLemma ExpDeterm_BindN (n: nat) :\n  forall (ftenv : funTC) (tenv : valTC) (e1 e2 : Exp) \n    (t1 t2 : VTyp) (e : ExpTyping ftenv tenv e1 t1),\n  DPar_E n ftenv tenv e1 t1 e ->\n  forall e0 : ExpTyping ftenv tenv e2 t2,\n  DPar_E n ftenv tenv e2 t2 e0 ->\n  DPar_E n ftenv tenv (BindN e1 e2) t2\n    (BindN_Typing ftenv tenv e1 e2 t1 t2 e e0).\n  unfold DPar_E, UniqueEStep.\n  intros.\n  inversion X; subst.\n  inversion X0; subst.\n  auto.\n  inversion X1.\n  inversion X0; subst.\n  inversion X1.\n  specialize (H fenv env H1 H2 n0 H3 s s1 s2 n1 n2 e1' e1'0 X1 X2).\n  destruct H as [c1 H].\n  destruct H as [c2 c3].\n  inversion c1; subst.\n  auto.\nDefined.\n\n\nLemma ExpDeterm_BindS (n: nat) :\n  forall (ftenv : funTC) (tenv tenv' : valTC) (x : StaticSemL.Id)\n    (e1 e2 : Exp) (t1 t2 : VTyp) (m : option VTyp) \n    (m0 : Maybe t1 m) (e : tenv' = (x, t1) :: tenv)\n    (e0 : ExpTyping ftenv tenv e1 t1),\n  DPar_E n ftenv tenv e1 t1 e0 ->\n  forall e3 : ExpTyping ftenv tenv' e2 t2,\n  DPar_E n ftenv tenv' e2 t2 e3 ->\n  DPar_E n ftenv tenv (BindS x m e1 e2) t2\n         (BindS_Typing ftenv tenv tenv' x e1 e2 t1 t2 m m0 e e0 e3).\n  unfold DPar_E, UniqueEStep.\n  intros.\n  inversion X; subst.\n  inversion X0; subst.\n  auto.\n  inversion X1.\n  inversion X0; subst.\n  inversion X1.\n  specialize (H fenv env H1 H2 n0 H3 s s1 s2 n1 n2 e1' e1'0 X1 X2).\n  destruct H as [c1 H].\n  destruct H as [c2 c3].\n  inversion c1; subst.\n  auto.\nDefined.  \n\nLemma ExpDeterm_BindMS (n: nat) :\n  forall (ftenv : funTC) (tenv tenv0 tenv1 : valTC) \n    (env0 : valEnv) (e : Exp) (t : VTyp) (e0 : EnvTyping env0 tenv0)\n    (e1 : tenv1 = tenv0 ++ tenv) (e2 : ExpTyping ftenv tenv1 e t),\n  DPar_E n ftenv tenv1 e t e2 ->\n  DPar_E n ftenv tenv (BindMS env0 e) t\n    (BindMS_Typing ftenv tenv tenv0 tenv1 env0 e t e0 e1 e2).\n  unfold DPar_E, UniqueEStep.\n  intros.\n  inversion X; subst.\n  inversion X0; subst.\n  auto.\n  inversion X1.\n  inversion X0; subst.\n  inversion X1.\n  assert (EnvTyping (env0 ++ env) (tenv0 ++ tenv)) as H1'.\n  eapply overrideEnvLemma.\n  assumption.\n  assumption.\n  specialize (H fenv (env0 ++ env) H0 H1' n0 H2 s s1 s2 n1 n2 e' e'0 X1 X2).\n  destruct H as [c1 H].\n  destruct H as [c2 c3].\n  inversion c1; subst.\n  auto.\nDefined.\n\n\nLemma ExpDeterm_IfThenElse (n: nat) :\n  forall (ftenv : funTC) (tenv : valTC) (e1 e2 e3 : Exp) \n    (t : VTyp) (e : ExpTyping ftenv tenv e1 Bool),\n  DPar_E n ftenv tenv e1 Bool e ->\n  forall e0 : ExpTyping ftenv tenv e2 t,\n  DPar_E n ftenv tenv e2 t e0 ->\n  forall e4 : ExpTyping ftenv tenv e3 t,\n  DPar_E n ftenv tenv e3 t e4 ->\n  DPar_E n ftenv tenv (IfThenElse e1 e2 e3) t\n         (IfThenElse_Typing ftenv tenv e1 e2 e3 t e e0 e4).\n  unfold DPar_E, UniqueEStep.\n  intros.\n  inversion X; subst.\n  inversion X0; subst.\n  auto.\n  eapply deterAux1 in H7.\n  unfold cst in H7.\n  eapply inj_pair2 in H7.\n  inversion H7.\n  inversion X0; subst.\n  rewrite <- H14.\n  rewrite <- H14.\n  auto.\n  inversion X1.\n  inversion X2.\n\n  inversion X0; subst.\n  eapply deterAux1 in H7.\n  unfold cst in H7.\n  eapply inj_pair2 in H7.\n  inversion H7.\n  auto.\n  inversion X1.\n  inversion X0; subst.\n  inversion X1.\n  inversion X1.\n  assert (s1 = s2 /\\ n1 = n2 /\\ e' = e'0).\n  eapply H.\n  exact H2.\n  exact H3.\n  exact H4.\n  exact X1.\n  exact X2.\n  destruct H5.\n  destruct H6.\n  rewrite H7.\n  auto.\nDefined.  \n\n\nLemma ExpDeterm_Apply0 :\n  forall (ftenv : funTC) (tenv : valTC) (x : StaticSemL.Id) \n    (e : Exp) (ps : Prms) (pt : PTyp) (t : VTyp) (p : Pure e)\n    (i : IdFTyping ftenv x (FT pt t)) (p0 : PrmsTyping ftenv tenv ps pt),\n  DPar_P 0 ftenv tenv ps pt p0 ->\n  forall e0 : ExpTyping ftenv tenv e Nat,\n  DPar_E 0 ftenv tenv e Nat e0 ->\n  DPar_E 0 ftenv tenv (Apply x ps e) t\n    (Apply_Typing ftenv tenv x e ps pt t p i p0 e0).\n  unfold DPar_E, DPar_P, UniqueEStep, UniquePStep.\n  intros.  \n  assert (n = 0) as q.\n  omega.\n  inversion q; subst.\n  clear H4.\n  inversion X0; subst.\n  inversion X; subst.\n  assert ( s1 = s2 /\\ n1 = n2 /\\ e'0 = e').\n  eapply H0.\n  exact H1.\n  exact H2.\n  exact H3.\n  exact X2.\n  exact X1.\n  destruct H4.\n  destruct H5.\n  inversion H6; subst.\n  auto.\n  inversion X1.\n  inversion X1.\n  \n  inversion X; subst.\n  inversion X2.\n\n  assert (s1 = s2 /\\ n1 = n2 /\\ ps'0 = ps').\n  eapply H.\n  exact H1.\n  exact H2.\n  exact H3.\n  exact X2.\n  exact X1.\n  destruct H4.\n  destruct H5.\n  inversion H6; subst.\n  auto.\n  assert (False).\n  destruct ps'.\n  eapply (NoPrmsStep fenv env (s1,0) (s2,n2)).\n  simpl.\n  exact X1.\n  exact X2.\n  inversion H4.\n\n  inversion X; subst.\n  inversion X2.\n\n  assert (False).\n  destruct ps'.\n  eapply (NoPrmsStep fenv env (s2,0) (s1,n1)).\n  simpl.\n  exact X2.\n  exact X1.\n  inversion H4.\n  unfold cst in H8.\n  eapply inj_pair2 in H8.\n  inversion H8; subst.\n  auto.\nDefined.  \n\n\nLemma ExpDeterm_Call0 :\n  forall (ftenv : funTC) (tenv : valTC) (x : StaticSemL.Id) \n    (ls : list Exp) (pt : PTyp) (t : VTyp) (i : IdFTyping ftenv x (FT pt t))\n    (p : PrmsTyping ftenv tenv (PS ls) pt),\n  DPar_P 0 ftenv tenv (PS ls) pt p ->\n  DPar_E 0 ftenv tenv (Call x (PS ls)) t\n         (Call_Typing ftenv tenv x ls pt t i p).\n  unfold DPar_E, DPar_P, UniqueEStep, UniquePStep.\n  intros.  \n  assert (n = 0) as q.\n  omega.\n  inversion q; subst.\n  clear H3.\n  inversion X0; subst.\n  inversion X; subst.\n  assert (s1 = s2 /\\ n1 = n2 /\\ ps'0 = ps').\n  eapply H.\n  exact H0.\n  exact H1.\n  exact H2.\n  exact X2.\n  exact X1.\n  destruct H3.\n  destruct H4.\n  inversion H5; subst.\n  auto.\n\n  eapply isValueList2IsValueT in X2.\n  assert (False).\n  destruct ps'.\n  eapply (NoPrmsStep fenv env (s1,0) (s2,n2)).\n  simpl.\n  exact X1.\n  exact X2.\n  inversion H3.\n\n  inversion X; subst.  \n  eapply isValueList2IsValueT in X1.\n  assert (False).\n  destruct ps'.\n  eapply (NoPrmsStep fenv env (s2,0) (s1,n1)).\n  simpl.\n  exact X2.\n  exact X1.\n  inversion H3.\n\n  rewrite H10 in H11.\n  inversion H11; subst.\n  auto.\nDefined.\n\n\nLemma ExpDeterm_Modify (n: nat) :\n  forall (ftenv : funTC) (tenv : valTC) (t1 t2 : VTyp) \n    (XF : XFun t1 t2) (e : Exp) (e0 : ExpTyping ftenv tenv e t1),\n  DPar_E n ftenv tenv e t1 e0 ->\n  DPar_E n ftenv tenv (Modify t1 t2 XF e) t2\n         (Modify_Typing ftenv tenv t1 t2 XF e e0).\n  unfold DPar_E, UniqueEStep.\n  intros.\n  inversion X; subst.\n  eapply inj_pair2 in H10.\n  eapply inj_pair2 in H10.\n  inversion H10; subst.\n  clear H3.\n\n  inversion X0; subst.\n  eapply inj_pair2 in H12.\n  inversion H12; subst.\n  clear H11 H3.\n  eapply inj_pair2 in H10.\n  eapply inj_pair2 in H10.\n  inversion H10; subst.\n  clear H3.\n  auto.\n  \n  inversion X1.\n\n  eapply inj_pair2 in H10.\n  eapply inj_pair2 in H10.\n  inversion H10; subst.\n  clear H3.\n  \n  inversion X0; subst.\n\n  eapply inj_pair2 in H10.\n  eapply inj_pair2 in H10.\n  inversion H10; subst.\n  clear H3.\n\n  inversion X1.\n  \n  eapply inj_pair2 in H10.\n  eapply inj_pair2 in H10.\n  inversion H10; subst.\n  clear H3.\n\n  assert (s1 = s2 /\\ n1 = n2 /\\ e' = e'0).\n  eapply H.\n  exact H0.\n  exact H1.\n  exact H2.\n  exact X1.\n  exact X2.\n  destruct H3.\n  destruct H4.\n  inversion H5; subst.\n  auto.\nDefined.\n\n\nLemma ExpDeterm_Nil (n: nat) :\n  forall (ftenv : funTC) (tenv : valTC),\n  DPar_P n ftenv tenv (PS []) (PT []) (PSNil_Typing ftenv tenv).\n  unfold DPar_P, UniquePStep.\n  intros.\n  inversion X0.\nDefined.\n\n\nLemma ExpDeterm_Cons (n: nat) :\n  forall (ftenv : funTC) (tenv : valTC) (e : Exp) (t : VTyp) \n    (es : list Exp) (ts : list VTyp) (e0 : ExpTyping ftenv tenv e t),\n  DPar_E n ftenv tenv e t e0 ->\n  forall p : PrmsTyping ftenv tenv (PS es) (PT ts),\n  DPar_P n ftenv tenv (PS es) (PT ts) p ->\n  DPar_P n ftenv tenv (PS (e :: es)) (PT (t :: ts))\n         (PSCons_Typing ftenv tenv e t es ts e0 p).\n  unfold DPar_P, UniquePStep, DPar_E, UniqueEStep.\n  intros.\n  inversion X; subst.\n  inversion X0; subst.\n  assert (s1 = s2 /\\ n1 = n2 /\\ PS es' = PS es'0).\n  eapply H0.\n  exact H1.\n  exact H2.\n  exact H3.\n  exact X1.\n  exact X2.\n  destruct H4.\n  destruct H5.\n  inversion H6; subst.\n  auto.\n\n  inversion X2.\n  inversion X0; subst.\n  inversion X1.\n  \n  assert (s1 = s2 /\\ n1 = n2 /\\ e' = e'0).\n  eapply H.\n  exact H1.\n  exact H2.\n  exact H3.\n  exact X1.\n  exact X2.\n\n  destruct H4.\n  destruct H5.\n  inversion H6; subst.\n  auto.\nDefined.\n\n\nLemma ExpDeterm_CallS (n: nat) \n  (IHn : forall (ftenv : funTC) (tenv : valTC) (e : Exp) (t : VTyp),\n         ExpTyping ftenv tenv e t ->\n         forall (fenv : funEnv) (env : valEnv),\n         FEnvTyping fenv ftenv ->\n         EnvTyping env tenv ->\n         forall n0 : nat,\n         n0 <= n ->\n         forall (s s1 s2 : W) (n1 n2 : nat) (e1 e2 : Exp),\n         UniqueEStep fenv env s s1 s2 n0 n1 n2 e e1 e2) : \n  forall (ftenv : funTC) (tenv : valTC) (x : Id) \n    (ls : list Exp) (pt : PTyp) (t : VTyp) (i : IdFTyping ftenv x (FT pt t))\n    (p : PrmsTyping ftenv tenv (PS ls) pt),\n  DPar_P (S n) ftenv tenv (PS ls) pt p ->\n  DPar_E (S n) ftenv tenv (Call x (PS ls)) t\n         (Call_Typing ftenv tenv x ls pt t i p).\n  unfold DPar_E, DPar_P, UniqueEStep, UniquePStep.\n  intros.  \n\n  inversion X0; subst.\n  inversion X; subst.\n  assert (s1 = s2 /\\ n1 = n2 /\\ ps'0 = ps').\n  eapply H.\n  exact H0.\n  exact H1.\n  exact H2.\n  exact X2.\n  exact X1.\n  destruct H3.\n  destruct H4.\n  inversion H5; subst.\n  auto.\n\n  eapply isValueList2IsValueT in X2.\n  assert (False).\n  destruct ps'.\n  eapply (NoPrmsStep fenv env (s1,0) (s2,n2)).\n  simpl.\n  exact X1.\n  exact X2.\n  inversion H3.\n\n  eapply isValueList2IsValueT in X2.\n  assert (False).\n  destruct ps'.\n  eapply (NoPrmsStep fenv env (s1,(S n1)) (s2,n2)).\n  simpl.\n  exact X1.\n  exact X2.\n  inversion H3.\n  \n  inversion X; subst.  \n  eapply isValueList2IsValueT in X1.\n  assert (False).\n  destruct ps'.\n  eapply (NoPrmsStep fenv env (s2,0) (s1,n1)).\n  simpl.\n  exact X2.\n  exact X1.\n  inversion H3.\n\n  rewrite H10 in H11.\n  inversion H11; subst.\n  auto.\n \n  inversion X; subst.\n  eapply isValueList2IsValueT in X1.\n  assert (False).\n  destruct ps'.\n  eapply (NoPrmsStep fenv env (s2,(S n2)) (s1,n1)).\n  simpl.\n  exact X2.\n  exact X1.\n  inversion H3.\n\n  rewrite H10 in H11.\n  inversion H11; subst.\n\n  inversion X1; subst.\n  inversion X2; subst.\n\n  eapply mapEq in H4.\n  inversion H4; subst.\n  auto.\nDefined.\n\n  \nLemma ExpDeterm_ApplyS (n: nat) \n  (IHn : forall (ftenv : funTC) (tenv : valTC) (e : Exp) (t : VTyp),\n         ExpTyping ftenv tenv e t ->\n         forall (fenv : funEnv) (env : valEnv),\n         FEnvTyping fenv ftenv ->\n         EnvTyping env tenv ->\n         forall n0 : nat,\n         n0 <= n ->\n         forall (s s1 s2 : W) (n1 n2 : nat) (e1 e2 : Exp),\n         UniqueEStep fenv env s s1 s2 n0 n1 n2 e e1 e2) :\n  forall (ftenv : funTC) (tenv : valTC) (x : Id) \n    (e : Exp) (ps : Prms) (pt : PTyp) (t : VTyp) (p : Pure e)\n    (i : IdFTyping ftenv x (FT pt t)) (p0 : PrmsTyping ftenv tenv ps pt),\n  DPar_P (S n) ftenv tenv ps pt p0 ->\n  forall e0 : ExpTyping ftenv tenv e Nat,\n  DPar_E (S n) ftenv tenv e Nat e0 ->\n  DPar_E (S n) ftenv tenv (Apply x ps e) t\n         (Apply_Typing ftenv tenv x e ps pt t p i p0 e0).\n  unfold DPar_E, DPar_P, UniqueEStep, UniquePStep.\n  intros.  \n\n  inversion X0; subst.\n  inversion X; subst.\n  assert ( s1 = s2 /\\ n1 = n2 /\\ e'0 = e').\n  eapply H0.\n  exact H1.\n  exact H2.\n  exact H3.\n  exact X2.\n  exact X1.\n  destruct H4.\n  destruct H5.\n  inversion H6; subst.\n  auto.\n  inversion X1.\n  inversion X1.\n  \n  inversion X; subst.\n  inversion X2.\n\n  assert (s1 = s2 /\\ n1 = n2 /\\ ps'0 = ps').\n  eapply H.\n  exact H1.\n  exact H2.\n  exact H3.\n  exact X2.\n  exact X1.\n  destruct H4.\n  destruct H5.\n  inversion H6; subst.\n  auto.\n  assert (False).\n  destruct ps'.\n  eapply (NoPrmsStep fenv env (s1,n0) (s2,n2)).\n  simpl.\n  exact X1.\n  exact X2.\n  inversion H4.\n\n  inversion X; subst.\n  inversion X2.\n\n  assert (False).\n  destruct ps'.\n  eapply (NoPrmsStep fenv env (s2,n0) (s1,n1)).\n  simpl.\n  exact X2.\n  exact X1.\n  inversion H4.\n  unfold cst in H8.\n  eapply inj_pair2 in H8.\n  inversion H8; subst.\n  auto.\nDefined.  \n  \n\nLemma ExpDeterm (n9: nat) :\n  forall (ftenv: funTC) (tenv: valTC) \n         (e: Exp) (t: VTyp),   \n      ExpTyping ftenv tenv e t -> \n  forall (fenv: funEnv) (env: valEnv),                      \n    FEnvTyping fenv ftenv ->\n    EnvTyping env tenv ->\n  forall (n: nat), n <= n9 ->   \n  forall (s s1 s2: W) (n1 n2: nat) (e1 e2: Exp), \n         UniqueEStep fenv env s s1 s2 n n1 n2 e e1 e2.\nProof.\ninduction n9.\neapply (ExpTypingDet_mut 0).\n- (* Val *)\n  eapply (ExpDeterm_Val 0).\n- (* Var *)\n  eapply (ExpDeterm_Var 0).\n- (* BindN *)\n  eapply (ExpDeterm_BindN 0).\n- (* BindS *)  \n  eapply (ExpDeterm_BindS 0).\n-  (* BindMS *)  \n  eapply (ExpDeterm_BindMS 0).\n-   (* IfThenElse *)\n  eapply (ExpDeterm_IfThenElse 0).\n-   (* Apply *)  \n  eapply ExpDeterm_Apply0. \n-   (* Call *)  \n  eapply ExpDeterm_Call0. \n- (* Modify *)\n  eapply (ExpDeterm_Modify 0).\n- eapply (ExpDeterm_Nil 0).\n- eapply (ExpDeterm_Cons 0).\n- eapply (ExpTypingDet_mut (S n9)).\n  * eapply (ExpDeterm_Val (S n9)).\n  * eapply (ExpDeterm_Var (S n9)).\n  * eapply (ExpDeterm_BindN (S n9)).\n  * eapply (ExpDeterm_BindS (S n9)).\n  * eapply (ExpDeterm_BindMS (S n9)).\n  * eapply (ExpDeterm_IfThenElse (S n9)).\n  * eapply (ExpDeterm_ApplyS n9).\n    assumption.\n  * eapply (ExpDeterm_CallS n9).\n    assumption.\n  * eapply (ExpDeterm_Modify (S n9)).\n  * eapply (ExpDeterm_Nil (S n9)).\n  * eapply (ExpDeterm_Cons (S n9)).\nDefined.\n\n\nLemma ExpDeterm_aux1 (n9 : nat)\n  (IHn9 : forall (ftenv : funTC) (tenv : valTC) (ps : Prms) (pt : PTyp),\n         PrmsTyping ftenv tenv ps pt ->\n         forall (fenv : funEnv) (env : valEnv),\n         FEnvTyping fenv ftenv ->\n         EnvTyping env tenv ->\n         forall n : nat,\n         n <= n9 ->\n         forall (s s1 s2 : W) (n1 n2 : nat) (ps1 ps2 : Prms),\n         UniquePStep fenv env s s1 s2 n n1 n2 ps ps1 ps2) : \n  forall (ftenv : funTC) (tenv : valTC) (e : Exp) (t : VTyp),\n  ExpTyping ftenv tenv e t ->\n  forall (fenv : funEnv) (env : valEnv),\n  FEnvTyping fenv ftenv ->\n  EnvTyping env tenv ->\n  forall n0 : nat,\n  n0 <= n9 ->\n  forall (s s1 s2 : W) (n1 n2 : nat) (e1 e2 : Exp),\n    UniqueEStep fenv env s s1 s2 n0 n1 n2 e e1 e2.\n  unfold UniquePStep, UniqueEStep in *.\n  intros.\n  assert (s1 = s2 /\\ n1 = n2 /\\ PS [e1] = PS [e2]).\n  eapply (IHn9 ftenv tenv (PS [e]) (PT [t])).\n  constructor.\n  assumption.\n  constructor.\n  eassumption.\n  eassumption.\n  exact H1.\n  econstructor.\n  exact X0.\n  econstructor.\n  exact X1.\n  destruct H2.\n  destruct H3.\n  inversion H4; subst.\n  auto.\nDefined.\n\n  \nLemma PrmsDeterm (n9: nat) :\n  forall (ftenv: funTC) (tenv: valTC) \n         (ps: Prms) (pt: PTyp),   \n      PrmsTyping ftenv tenv ps pt -> \n  forall (fenv: funEnv) (env: valEnv),                      \n    FEnvTyping fenv ftenv ->\n    EnvTyping env tenv ->\n  forall (n: nat), n <= n9 ->   \n  forall (s s1 s2: W) (n1 n2: nat) (ps1 ps2: Prms), \n         UniquePStep fenv env s s1 s2 n n1 n2 ps ps1 ps2.\nProof.\ninduction n9.\neapply (PrmsTypingDet_mut 0).\n- (* Val *)\n  eapply (ExpDeterm_Val 0).\n- (* Var *)\n  eapply (ExpDeterm_Var 0).\n- (* BindN *)\n  eapply (ExpDeterm_BindN 0).\n- (* BindS *)  \n  eapply (ExpDeterm_BindS 0).\n-  (* BindMS *)  \n  eapply (ExpDeterm_BindMS 0).\n-   (* IfThenElse *)\n  eapply (ExpDeterm_IfThenElse 0).\n-   (* Apply *)  \n  eapply ExpDeterm_Apply0. \n-   (* Call *)  \n  eapply ExpDeterm_Call0. \n- (* Modify *)\n  eapply (ExpDeterm_Modify 0).\n- eapply (ExpDeterm_Nil 0).\n- eapply (ExpDeterm_Cons 0).\n- eapply (PrmsTypingDet_mut (S n9)).\n  * eapply (ExpDeterm_Val (S n9)).\n  * eapply (ExpDeterm_Var (S n9)).\n  * eapply (ExpDeterm_BindN (S n9)).\n  * eapply (ExpDeterm_BindS (S n9)).\n  * eapply (ExpDeterm_BindMS (S n9)).\n  * eapply (ExpDeterm_IfThenElse (S n9)).\n  * eapply (ExpDeterm_ApplyS n9).\n    eapply (ExpDeterm_aux1 n9 IHn9).   \n  * eapply (ExpDeterm_CallS n9).\n    eapply (ExpDeterm_aux1 n9 IHn9).   \n  * eapply (ExpDeterm_Modify (S n9)).\n  * eapply (ExpDeterm_Nil (S n9)).\n  * eapply (ExpDeterm_Cons (S n9)).\nDefined.\n\n(*********************************************************************)\n\n(** Confluence of evaluation *)\n\nDefinition UniqueEClos (fenv: funEnv) (env: valEnv)\n           (s s1 s2: W) (n n1 n2: nat)\n           (e : Exp) (v1 v2: Value) :=\n    EClosure fenv env (Conf Exp s n e) ((Conf Exp s1 n1 (Val v1))) ->\n    EClosure fenv env (Conf Exp s n e) ((Conf Exp s2 n2 (Val v2))) -> \n        (n1 = n2) /\\ (s1 = s2) /\\ (v1 = v2).\n\nDefinition UniquePClos (fenv: funEnv) (env: valEnv)\n           (s s1 s2: W) (n n1 n2: nat)\n           (ps : Prms) (vs1 vs2: list Value) :=\n  PClosure fenv env (Conf Prms s n ps)\n              ((Conf Prms s1 n1 (PS (map Val vs1)))) ->\n  PClosure fenv env (Conf Prms s n ps)\n              ((Conf Prms s2 n2 (PS (map Val vs2)))) -> \n        (n1 = n2) /\\ (s1 = s2) /\\ (vs1 = vs2).\n\n\nLemma ExpConfluence (n: nat) :\n  forall (ftenv: funTC) (tenv: valTC) \n         (e: Exp) (t: VTyp),   \n      ExpTyping ftenv tenv e t -> \n  forall (fenv: funEnv) (D: FEnvWT fenv) (env: valEnv),                      \n    FEnvTyping fenv ftenv ->\n    EnvTyping env tenv ->\n  forall (n0: nat), n0 <= n ->   \n  forall (s s1 s2: W) (n1 n2: nat) (v1 v2: Value), \n         UniqueEClos fenv env s s1 s2 n0 n1 n2 e v1 v2.\nProof.\n  unfold UniqueEClos.\n  intros.  \n  dependent induction X0.\n  intros.\n  dependent destruction X1.\n  auto.\n  inversion e.\n  destruct p2.\n\n  assert (ExpTyping ftenv tenv qq t) as K1.\n  {- eapply (ExpSubjectRed fenv D ftenv tenv).\n     exact X.\n     exact H.\n     exact H0.\n     exact e0.\n  }\n  assert (fuel <= n) as q.\n  {- eapply StepIsEClos in e0.\n     eapply ExpDecrease in e0.\n     omega.\n  }   \n  assert (EClosure fenv env (Conf Exp state fuel qq)\n                   (Conf Exp s2 n2 (Val v2))) as K2.\n  {- inversion X1; subst.\n     inversion e0.\n     destruct p2.\n     assert (state0 = state /\\ fuel0 = fuel /\\ qq0 = qq).\n     {+ eapply ExpDeterm.\n        exact X.\n        exact H.\n        exact H0.\n        exact H1.\n        exact X2.\n        exact e0.\n     }\n     destruct H2.\n     destruct H3.\n     inversion H4; subst.\n     exact X3.\n  }\n  specialize (IHX0 qq K1 D H H0 fuel q state s1 n1 v1\n                   eq_refl eq_refl K2).\n  auto.\nDefined.\n  \n\nLemma PrmsConfluence (n: nat) :\n  forall (ftenv: funTC) (tenv: valTC) \n         (ps: Prms) (pt: PTyp),   \n      PrmsTyping ftenv tenv ps pt -> \n  forall (fenv: funEnv) (D: FEnvWT fenv) (env: valEnv),                      \n    FEnvTyping fenv ftenv ->\n    EnvTyping env tenv ->\n  forall (n0: nat), n0 <= n ->   \n  forall (s s1 s2: W) (n1 n2: nat) (vs1 vs2: list Value), \n         UniquePClos fenv env s s1 s2 n0 n1 n2 ps vs1 vs2.\nProof.\n  unfold UniquePClos.\n  intros.  \n  dependent induction X0.\n  intros.\n  dependent destruction X1.\n  eapply mapEq in x.\n  inversion x; subst.\n  auto.\n  destruct p2.\n  assert (isValueList2T (map Val vs1) vs1) as u1.\n  constructor.\n  eapply isValueList2IsValueT in u1.\n  assert (False).\n  destruct qq.\n  eapply (NoPrmsStep fenv env (s1,n1) (state,fuel)).\n  simpl.\n  exact p.\n  exact u1.\n  inversion H2.\n\n  destruct p2.\n  assert (PrmsTyping ftenv tenv qq pt) as K1.\n  {- eapply (PrmsSubjectRed fenv D ftenv tenv).\n     exact X.\n     exact H.\n     exact H0.\n     exact p. }\n  assert (fuel <= n) as q.\n  {- eapply StepIsPClos in p.\n     eapply PrmsDecrease in p.\n     omega.\n  }   \n  assert (PClosure fenv env (Conf Prms state fuel qq)\n                   (Conf Prms s2 n2 (PS (map Val vs2)))) as K2.\n  {- inversion X1; subst.\n     + assert (isValueList2T (map Val vs2) vs2) as u1.\n       constructor.\n       eapply isValueList2IsValueT in u1.\n       assert (False).\n       destruct qq.\n       eapply (NoPrmsStep fenv env (s2,n2) (state,fuel)).\n       simpl.\n       exact p.\n       exact u1.\n       inversion H2.\n     + \n     destruct p2.\n     assert (state0 = state /\\ fuel0 = fuel /\\ qq0 = qq).\n     {+ eapply PrmsDeterm.\n        exact X.\n        exact H.\n        exact H0.\n        exact H1.\n        exact X2.\n        exact p.\n     }\n     destruct H2.\n     destruct H3.\n     inversion H4; subst.\n     exact X3. \n  }   \n  specialize (IHX0 qq K1 D H H0 fuel q state s1 n1 vs1\n                   eq_refl eq_refl K2).\n  auto.\nDefined.  \n  \n    \nEnd Determ.\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/DetermI1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2889901633737459}}
{"text": "(** @Name Formalization of class diagrams\n    @version 1.1\n    @domains \n    @authors Feng sheng \n    @date 30/03/2017\n    @description class and object diagrams (Coq v8.2)\n**)\n\nRequire Import List.\nRequire Import String.\nRequire Import ListSet.\nRequire Import Arith.\nRequire Import Peano_dec.\n\nImport ListNotations.\n\nOpen Scope list_scope.\n\n(** ##### the structute of metamodel of class diagram #### **)\n\n(** ----- basic element ----- **)\nInductive NamedElement : Set :=\n| BNamedElement : nat -> string -> NamedElement.\n\n(** ----- classifier ----- **)\nInductive Classifier : Set :=\n| BClassifier (super : NamedElement).\n\n(** ----- operation ----- **)\nInductive Operation : Set :=\n| BOperation : NamedElement -> list string -> Operation.\n\n(** ----- Data Type ---- **)\nInductive DataType : Set :=\n| BDataType: Classifier -> DataType.\n\n(** ----- attribute, primitive data type, class ----- **)\nInductive Attribute : Set :=\n| BAttribute : NamedElement -> Classifier -> Attribute.\n\n\nInductive Class : Set :=\n| BClass : Classifier -> bool -> list Attribute -> Class.\n\n\n(** ----- association end ----- **)\nInductive Natural :=\n| Nat : nat -> Natural\n| Star : Natural.\n\nInductive AsEnd : Set :=\n| BAsEnd: string -> Class -> (Natural * Natural) -> AsEnd.\n\n(** ----- association ----- **)\nInductive asKind : Set :=\n| none : asKind\n| directed : asKind\n| aggregate : asKind\n| composite : asKind.\n\nInductive Assoc : Set :=\n| BAssoc: NamedElement -> asKind -> (AsEnd * AsEnd) -> Assoc.\n\n(** ----- generalization ----- **)\nInductive Gen : Set :=\n| BGen : Class -> Class -> Gen.\n\n(** ------------------------------- **)\n(** -------- Source Model --------- **)\nRecord SimpleUML : Set :=\n  mkSimpleUML {\n      MClass_Instance : list Class;\n      MAttr_Instance : list Attribute;\n      MDataType_Instance : list DataType;\n      MAssoc_Instance : list Assoc;\n      MGen_Instance : list Gen\n    }.\n\n\n(* ----- Equality Judgement ----- *)\nDefinition eqClassifier_dec : forall x y: Classifier, {x = y} + {x <> y}.\n  repeat decide equality.\nDefined.\n\nDefinition beqClassifier c c' :=\n  match eqClassifier_dec c c' with\n  | left _ => true\n  | right _ => false\n  end.\n\nDefinition eqAttribute_dec : forall x y: Attribute, {x = y} + {x <> y}.\n  repeat decide equality.\nDefined.\n\nDefinition beqAttribute a a' :=\n  match eqAttribute_dec a a' with\n  | left _ => true\n  | right _ => false\n  end.\n\nDefinition eqAssoc_dec : forall x y: Assoc, {x = y} + {x <> y}.\n  repeat decide equality.\nDefined.\n\nDefinition beqAssoc a a' :=\n  match eqAssoc_dec a a' with\n  | left _ => true\n  | right _ => false\n  end.\n\nDefinition eqAsEnd_dec : forall x y: AsEnd, {x = y} + {x <> y}.\n  repeat decide equality.\nDefined.\n\nDefinition beqAsEnd a a' :=\n  match eqAsEnd_dec a a' with\n  | left _ => true\n  | right _ => false\n  end.\n\nDefinition eqOperation_dec : forall x y: Operation, {x = y} + {x <> y}.\n  repeat decide equality.\nDefined.\n\nDefinition beqOperation o o' :=\n  match eqOperation_dec o o' with\n  | left _ => true\n  | right _ => false\n  end.\n\nFixpoint eqClass_dec (x y : Class) : {x = y} + {x <> y}.\n  repeat decide equality.\nDefined.\n\nDefinition beqClass c c' :=\n  match eqClass_dec c c' with\n  | left _ => true\n  | right _ => false\n  end.\n\nFixpoint eqGen_dec (x y : Gen) : {x = y} + {x <> y}.\n  repeat decide equality.\nDefined.\n\nDefinition beqGen g g' :=\n  match eqGen_dec g g' with\n  | left _ => true\n  | right _ => false\n  end.\n\n\n(** ---------- Functions --------- **)\n\n(** --- get all parents --- **)\nFixpoint parents' (l : list Gen) (c : Class) :=\nmatch l with\n| [] => []\n| (BGen p c') :: l' => if eqClass_dec c c' \n                       then p :: parents' l' c\n                       else parents' l' c\nend.\n\n\nFixpoint deduplicate (ls : list Class) :=\n  match ls with\n  | [] => []\n  | x :: [] => [x]\n  | x :: xs\n    => if leb (count_occ eqClass_dec ls x) 1\n       then deduplicate xs\n       else x :: deduplicate xs\n  end.\n\n\nRequire Import Coq.Sorting.Mergesort.\nRequire Import Coq.Lists.List.\n\n\nDefinition parents_step (l : list Gen) (cs : list Class) :=\n  deduplicate (cs ++ List.flat_map (parents' l) cs).\n\nFixpoint all_parents' (l : list Gen) (cs : list Class) (fuel : nat) :=\n  match fuel with\n  | 0 => cs\n  | S fuel'\n    => all_parents' l (parents_step l cs) fuel'\n  end.\n\nDefinition parents (l : list Gen) (c : Class) :=\n  deduplicate (all_parents' l (parents' l c) (List.length l)).\n\n(** ------------------projection--------------------- **)\n\n(** ----- get named element oid ----- **)\nDefinition NamedElement_oid (o : NamedElement) : nat :=\n  match o with\n    | (BNamedElement o _ ) => o\n  end.\n\n\n(** ----- get named element name ----- **)\nDefinition NamedElement_name (o : NamedElement) : string :=\n  match o with\n    | (BNamedElement _ n) => n\n  end.\n\n\n(** ------ get the basis of attribute ----- **)\nDefinition Attribute_super (a : Attribute) : NamedElement :=\n  match a with\n    | BAttribute s _ => s\n  end.\n\n\nDefinition Attribute_name (a : Attribute) : string :=\n  NamedElement_name (Attribute_super a).\n\n\nDefinition Attribute_oid (a : Attribute) : nat :=\n  NamedElement_oid (Attribute_super a).\n\n(** ------ get the classifier of attribute ----- **)\nDefinition Attribute_type (a : Attribute) : Classifier :=\n  match a with\n    | BAttribute _ c => c\n  end.\n\n\n(** ----- get the basis (name, abstract) of classifier ----- **)\nDefinition Classifier_super (c : Classifier) : NamedElement :=\n  match c with\n    | BClassifier s => s\n  end.\n\nDefinition Classifier_name (c : Classifier) : string :=\n  NamedElement_name (Classifier_super c).\n\nDefinition Classifier_oid (c : Classifier) :=\n  NamedElement_oid (Classifier_super c).\n\n\n(** ----- get the basis of class ------ **)\nDefinition Class_super (c : Class) : Classifier :=\n  match c with\n    | BClass c _ _  => c\n  end.\n\nDefinition Class_name (c : Class) : string :=\n  Classifier_name (Class_super c).\n\nDefinition Class_oid (c : Class) : nat :=\n  Classifier_oid (Class_super c).\n\n(** ----- get the abstract of class ----- **)\nDefinition Class_abstract (c : Class) : bool :=\n  match c with \n    | BClass _ a _ => a \n  end.\n\n(** ----- get the attributes of class ----- **)\nDefinition Class_attribute (c : Class) : list Attribute :=\n  match c with\n    | BClass _ _ a  => a\n  end.\n\n\n(** ----- get the classifier of primitive data type ------ **)\nDefinition DataType_super (p : DataType) : Classifier :=\n  match p with\n    | BDataType s => s\n  end.\n\nDefinition DataType_name (c : DataType) : string :=\n  Classifier_name (DataType_super c).\n\nDefinition DataType_oid (c : DataType) : nat :=\n  Classifier_oid (DataType_super c).\n\n(** ----- get the super class of generalization ----- **)\nDefinition Gen_src (g : Gen) : Class :=\n  match g with\n    | BGen s _ => s\n  end.\n\n(** ----- get the sub class of generalization ----- **)\nDefinition Gen_dest (g : Gen) : Class :=\n  match g with\n    | BGen _ sub => sub\n  end.\n\n\n(** ------ get the name of association end ----- **)\nDefinition AsEnd_name (a : AsEnd) : string :=\n  match a with\n  | BAsEnd n _ _  => n\n  end.\n\n(** ------ get the attached class of association end ----- **)\nDefinition AsEnd_class (a : AsEnd) : Class :=\n  match a with\n  | BAsEnd  _ c _  => c\n  end.\n\n(** ------ get the multipy of association ----- **)\nDefinition AsEnd_lower (a : AsEnd) : Natural:=\n  match a with\n    | BAsEnd _ _ l => fst l\n  end.\n\n\nDefinition AsEnd_upper (a : AsEnd) : Natural:=\n  match a with\n    | BAsEnd _ _ l => snd l\n  end.\n\n\n(** ----- get the name of association ------ **)\nDefinition Assoc_super (a : Assoc) : NamedElement :=\n  match a with\n    | BAssoc s _ _ => s\n  end.\n\n\nDefinition Assoc_name (a : Assoc) : string :=\n  NamedElement_name (Assoc_super a).\n\n\nDefinition Assoc_oid (a : Assoc) : nat :=\n  NamedElement_oid (Assoc_super a).\n\n\nDefinition Assoc_kind (a : Assoc) : asKind :=\n  match a with\n  | BAssoc _ k _ => k\n  end.\n\n\n(** ----- Get the ends of association ----- *)\nDefinition Assoc_node (a : Assoc) : AsEnd * AsEnd :=\n  match a with\n    | BAssoc _ _ k => k\n  end.\n\n\n(** ----- get the class of association ends ----- **)\nDefinition Assoc_src (a : Assoc) : Class :=\n  AsEnd_class (fst (Assoc_node a)).\n\n\nDefinition Assoc_dest (a : Assoc) : Class :=\n  AsEnd_class (snd (Assoc_node a)).\n\n\n(** --------- the set of each concept--------- *)\n\nDefinition Class_Instances (model : SimpleUML) :=\n  MClass_Instance model.\n\nDefinition DataType_Instances (model : SimpleUML) :=\n  MDataType_Instance model.\n\nDefinition Assoc_Instances (model : SimpleUML) :=\n  MAssoc_Instance model.\n\nDefinition Attribute_Instances (model : SimpleUML) :=\n  MAttr_Instance model.\n\nDefinition Gen_Instances (model : SimpleUML) :=\n  MGen_Instance model.\n\n\n(** ###### Structural Constraints ##### **)\n\nDefinition lstClassOid (model : SimpleUML) : list nat :=\n  map Class_oid (Class_Instances model).\n\nDefinition lstAttrOid (model : SimpleUML) : list nat :=\n  map Attribute_oid (Attribute_Instances model).\n\nDefinition lstDataOid (model : SimpleUML) : list nat :=\n  map DataType_oid (DataType_Instances model).\n\nDefinition lstAssocOid (model : SimpleUML) : list nat :=\n  map Assoc_oid (Assoc_Instances model).\n\n\nDefinition UniqueOid (model : SimpleUML) : Prop :=\n  NoDup (lstClassOid model ++ lstAttrOid model ++ \n         lstDataOid model ++ lstAssocOid model).\n\nDefinition UniqueClass (model : SimpleUML) : Prop :=\n  NoDup (Class_Instances model).\n\nDefinition UniqueDataType (model : SimpleUML) : Prop :=\n  NoDup (DataType_Instances model).\n\nDefinition UniqueAttribute (model : SimpleUML) : Prop :=\n  NoDup (Attribute_Instances model).\n\nDefinition UniqueAttrInClass (model : SimpleUML) : Prop :=\n  forall o: Class,  (In o (Class_Instances model)) ->\n    NoDup (Class_attribute o).\n\n\n(** ##### Non-structural Contraints ##### **)\n\nDefinition nsc_AttributeUniqueness (model : SimpleUML) : Prop :=\n  forall o : Class, \n    (In o (Class_Instances model)) ->\n    NoDup (map Attribute_name (Class_attribute o)).\n\n\nDefinition nsc_ClassUniqueness (model : SimpleUML) : Prop :=\n  NoDup (map Class_name (Class_Instances model)).\n\n\nDefinition nsc_DataTypeUniquenss (model : SimpleUML) : Prop :=\n  NoDup (map DataType_name (DataType_Instances model)).\n\n\nDefinition nsc_AssocUniqueness (model : SimpleUML) : Prop :=\n  NoDup (map Assoc_name (Assoc_Instances model)).\n\n\nDefinition NotSelfGenralization (model : SimpleUML) : Prop :=\n  forall g: Gen, (In g (Gen_Instances model)) ->\n    let sub := Gen_dest g in\n    ~ In sub (parents (Gen_Instances model) sub).\n\n(** ----- well formed ----- **)\n\nDefinition WellFormed (s : SimpleUML) :  Prop :=\n  UniqueClass s /\\ UniqueAttribute s /\\  UniqueDataType s /\\\n  UniqueAttrInClass s /\\ nsc_AttributeUniqueness s /\\ nsc_ClassUniqueness s /\\\n  nsc_DataTypeUniquenss s /\\ NotSelfGenralization s.\n\n\n\n\n", "meta": {"author": "shengfeng", "repo": "classdiagram", "sha": "10c5e69cfa07da418e29407c3af07adf909caba5", "save_path": "github-repos/coq/shengfeng-classdiagram", "path": "github-repos/coq/shengfeng-classdiagram/classdiagram-10c5e69cfa07da418e29407c3af07adf909caba5/src/cd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331606115021, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.28890034460258757}}
{"text": "Require 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.GlobalExtends.\n\nRequire Import Cryptol.EvalTac.\nRequire Import Cryptol.Eager.\nRequire Import Cryptol.Lib.\n\nImport HaskellListNotations.\n\nRequire Import HMAC.HMAC.\n\nRequire Import HMAC.HMAC_lib.\nRequire Import Cryptol.Prims.\n\nRequire Import List.\nImport ListNotations.\n\n\nLemma kinit_eval :\n  forall GE TE SE,\n    wf_env ge GE TE SE ->\n    forall (key : ext_val) keylen,\n      has_type key (bytestream keylen) ->\n      forall h hf,\n        good_hash h GE TE SE hf ->\n        forall digest t1 t2 t3 kexpr,\n          eager_eval_type GE TE t1 (tvnum (Z.of_nat keylen)) ->\n          eager_eval_type GE TE t2 (tvnum (Z.of_nat keylen)) ->\n          eager_eval_type GE TE t3 (tvnum digest) ->\n          eager_eval_expr GE TE SE kexpr (to_sval key) ->\n          eager_eval_expr GE TE SE (apply (tapply (EVar kinit) (ETyp t1 :: ETyp t2 :: ETyp t3 ::  nil)) (h :: kexpr :: nil)) (to_sval key).\nProof.\n  intros.\n  eapply good_hash_eval in H1. do 4 destruct H1.\n\n  \n  unfold bytestream in H0. inversion H0. subst.\n  gen_global (0,\"demote\").\n  gen_global (14,\">\").\n  gen_global (61,\"take\").\n  gen_global (34,\"#\").\n  gen_global (29,\"zero\").\n  gen_global (35,\"splitAt\").\n  \n  e. e. e. e. e.\n  gen_global kinit.\n  ag.\n  e. e. e. e. \n  e. \n  e. e. e. e.\n\n  ag. \n  \n  e. e. e. e.\n  ag.\n\n  e. e. e.\n\n  reflexivity. e. e. e.\n\n  ag.\n\n  e. e. e.\n  reflexivity.\n  e. lv. lv.\n  simpl. unfold strictnum.\n\n  \n  rewrite gt_not_refl; reflexivity.\n  simpl.\n\n  \n  use take_eval; try omega.\n  \n  use append_eval.\n\n  instantiate (1 := l). simpl. lv.\n\n  e. \n  ag.\n\n  e. e. \n\n  simpl.\n  f_equal. instantiate (1 := (repeat (eseq (repeat (ebit false) 8)) (length l))).\n  simpl.\n  f_equal.\n  rewrite map_repeat. simpl.\n  rewrite Nat2Z.id.\n  reflexivity.\n  reflexivity.\n  rewrite app_length.\n  rewrite Nat2Z.inj_add. omega.\n\n  unfold take_model.\n  rewrite Nat2Z.id.\n\n  simpl. f_equal.\n  rewrite firstn_app.\n  rewrite firstn_all.\n  replace (Datatypes.length l - Datatypes.length l)%nat with O by omega.\n  rewrite firstn_O. rewrite app_nil_r.\n  reflexivity.\nQed.\n\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/Kinit_eval.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.28890033765324624}}
{"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 htt Require Import domain.\nFrom DiSeL Require Import Freshness State EqTypeX DepMaps Protocols.\nFrom DiSeL Require Import Worlds NetworkSem Rely Actions Injection Process.\nFrom DiSeL Require Import Always HoareTriples InductiveInv.\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(*****************************************************************************\n\n[Unary Hoare-style specifications and auxiliary lemmas].\n\nThis file borrows basic definition of binary-to-unary Hoare triple\nencoding (i.e., logvar and binarify definitions) from the development\nof FCSL by Nanevski et al. \n\n(FCSL is available at http://software.imdea.org/fcsl)\n\n\n*****************************************************************************)\n\n(* Spec s is parametrized by a ghost variable of type A *)\nDefinition logvar {B A} (s : A -> spec B) : spec B := \n  (fun i => exists x : A, (s x).1 i, \n   fun y i m => forall x : A, (s x).2 y i m).\n\n(* Representing q as a unary postcondition, including the precondition *)\nDefinition binarify {A} (p : pre) (q : cont A) : spec A := \n  (p, fun i y m => p i -> q y m).\n\nNotation \"'DHT' [ this , W ] ( p , q ) \" := \n  (DTbin this W (binarify p q)) (at level 0, \n   format \"'[hv ' DHT  [ this , W ]  ( '[' p , '/' q ']' ) ']'\").  \n\n(* A unary Hoare-style specification  *)\nNotation \"{ x .. y }, 'DHT' [ this , W ] ( p , q )\" :=\n  (DTbin this W (logvar (fun x => .. (logvar (fun y => binarify p q)) .. )))\n   (at level 0, x binder, y binder, right associativity,\n    format \"'[hv ' { x .. y }, '/ ' DHT  [ this , W ]  ( '[' p , '/' q ']' ) ']'\").\n\nSection BasicRules.\n\nVariable this : nid.\n\n(* We can always assume coherence of the state *)\nLemma vrf_coh W A (e : DT this W A) i r : \n        (i \\In Coh W -> verify i e r) -> verify i e r.\nProof.\nby move=>H C; apply: H.\nQed.\n\n(* stability of preconditions *)\nLemma vrf_pre W A (e : DT this W A) i i' (k : cont A) : \n        verify i e k -> network_rely W this i i' -> verify i' e k. \nProof.\nmove=>H M Ci' t H'; case: (rely_coh M)=>Ci _.\nby apply: aft_imp (alw_envs (H Ci t H') M).\nQed.\n\n(* stability of postconditions *)\nLemma vrf_post W A (e : DT this W A) i (k : cont A) : \n        verify i e k ->\n        verify i e (fun x m => forall m', network_rely W this m m' -> k x m').\nProof.\nmove=>H Ci t H'; move: (alw_envsq (H Ci t H')).\napply: alw_imp=>s p Cs H2 s3 M v E; apply: H2 E _ M.\nQed.\n\n(* An inference rule for the sequential composition *)\nLemma bind_rule W A B (e1 : DT this W A) (e2 : A -> DT this W B) i \n             (q : cont A) (r : cont B) : \n        verify i e1 q -> \n        (forall y j, q y j -> j \\In Coh W  -> verify j (e2 y) r) ->\n        verify i (bind e1 e2) r.\nProof.\nmove=>H1 H2 Ci t [->|[t'][H3 H4]]. \n- by apply: alw_unfin=>//; move/alw_coh: (H1 Unfinished (prog_unfin e1)). \nby apply: aft_bnd H3 _; move/(H1 Ci): H4; apply: aft_imp=>y j Cj H; apply: H2.\nQed.\n\nArguments bind_rule [W A B e1 e2 i].\n\nLemma step W A B (e1 : DT this W A) (e2 : A -> DT this W B) i (r : cont B) : \n        verify i e1 (fun y m => verify m (e2 y) r) ->\n        verify i (bind e1 e2) r.\nProof. by move=>H; apply: (bind_rule (fun y m => verify m (e2 y) r)). Qed.\n\n(* Inference rules for the calls to an already verified function f *)\nLemma call_rule' W A i (f : DT this W A) (k : cont A) : \n  (* Verify precondition of the call *)\n  (i \\In Coh W -> pre_of f i) ->\n  (* Verify the rest out of the postcondition *)\n  (forall x m, post_of f i x m -> m \\In Coh W -> k x m) ->\n  verify i f k.\nProof.\ncase: f=>s [e] /= H H1 H2 Ci t H3.\napply: aft_imp (H i t (H1 Ci) Ci H3). \nby move=>v m Cm H4; apply: H2.\nQed.\n\n(* Same lemma for unary postconidtions *)\nLemma call_rule W A (p : Pred state) (q : A -> Pred state) i\n      {e} (k : cont A) : \n        (i \\In Coh W -> p i) -> \n        (forall x m, q x m -> m \\In Coh W -> k x m) ->\n        verify i (@with_spec this W A (binarify p q) e) k.\nProof. \nmove=>H1 H2; apply: vrf_coh=>C; apply: call_rule'=>//. \nby move=>x m /(_ (H1 C)); apply: H2.\nQed.\n\n\n(* Lemmas for manipulating with ghost variables *)\nSection GhostRules.\n\nVariables (W : world) (A B C : Type). \n\n(* Weakening of the continuation postcondition *)\nLemma vrf_mono (e : DT this W A) i (r1 r2 : cont A) : \n        r1 <== r2 -> verify i e r1 -> verify i e r2. \nProof. by move=>T H1 C' t; move/(H1 C'); apply: aft_imp=>v m _; apply: T. Qed.\n\nVariable (e : DT this W A).\n\n(* \"Uncurrying\" the ghosts in the specification s *)\nLemma ghE (s : B -> C -> spec A) : \n        conseq e (logvar (fun x => logvar (s x))) <->\n        conseq e (logvar (fun xy => s xy.1 xy.2)).\nProof.\nsplit.\n- move=>/= H1 i [[x y]] H2.\n  have: exists x1 y1, (s x1 y1).1 i by exists x, y. \n  by move/H1; apply: vrf_mono=>y1 m1 T1 [x2 y2]; apply: (T1 x2 y2). \nmove=>/= H1 i [x][y] H2.  \nhave: exists x, (s x.1 x.2).1 i by exists (x, y). \nby move/H1; apply: vrf_mono=>y1 m1 T1 x2 y2; apply: (T1 (x2, y2)).\nQed.\n\n(* Pulling the ghosts out of the specification *)\nLemma ghC (p : B -> pre) (q : B -> A -> pre) :\n        (forall i x, p x i -> i \\In Coh W -> verify i e (q x)) ->\n        conseq e (logvar (fun x => binarify (p x) (q x))).\nProof.\nmove=>H i /= [x Hp] Ci t Ht. \nhave S : alwsafe i t by apply: alw_imp (H i x Hp Ci Ci t Ht). \nby apply/aftA=>// y; apply/aftI=>// /H; apply.\nQed.\n\n\n(********************************************)\n(* Lemmas for instantiating ghost variables *)\n(********************************************)\nVariables (s : C -> spec A) (f : DTbin this W (logvar s)).\n\n(* helper lemma, to express the instantiation *)\nLemma gh_conseq t : conseq f (s t).\nProof.\ncase E: (s t)=>[a b] h /= H; apply: call_rule'=>[|x m]. \n- by exists t; rewrite E. \nby move/(_ t); rewrite E. \nQed.\n\n(* Instantiating the ghost of a call *)\nLemma gh_ex g i (k : cont A) : \n        verify i (do' (@gh_conseq g)) k ->\n        verify i (@with_spec this W A (logvar s) f) k.\nProof. by []. Qed.\n\nEnd GhostRules.\n\nArguments gh_ex [W A C s f].\n\nLemma act_rule W A (a: action W A this) i (r : cont A) :\n  (forall j, network_rely W this i j -> a_safe a j /\\\n   forall y k m, (exists pf : a_safe a j, a_step pf k y) -> network_rely W this k m -> r y m) ->\n        verify i (act a) r. \nProof.\nmove=>H C p; case=>Z; subst p; first by apply: (alw_unfin C).\napply: (alw_act C)=>j R; case: (H j R)=>{H}S H; exists S.\nsplit=>//k v m St R' v'[]<-.\nhave X: (exists pf : a_safe a j, a_step pf k v) by exists S.\nby apply: (H _ _ _ X R').\nQed.\n\n\nLemma ret_rule W A i (v : A) (r : cont A) : \n       (forall m, network_rely W this i m -> r v m) ->       \n       verify i (ret this W v) r. \nProof.\nmove=>H C p; case=>Z; subst p; first by apply: alw_unfin.\nby apply: alw_ret=>//m R v'[]<-; apply: H.\nQed.  \n\nEnd BasicRules.\n\n\nSection InjectLemmas.\n\nVariable this : nid.\nVariables (W V : world) (K : hooks) (A : Type) (w : injects V W K).\nNotation W2 := (inj_ext w).\n\nVariable (e1 : DT this V A).\n\nLemma inject_rule i j (r : cont A) : \n        i \\In Coh V -> \n        verify i e1 (fun x i' => forall j', \n          i' \\+ j' \\In Coh W -> network_rely W2 this j j' -> r x (i' \\+ j')) ->\n        verify (i \\+ j) (inject w e1) r.\nProof.\nmove=>Ci H C t [->|[t' [H' ->{t}]]]; first by apply: alw_unfin. \nmove/aft_inject: {H H'} (H Ci _ H'); move/(_ _ _ w _ C). \napply: aft_imp=>v s Cs [i'][j'][E] Ci' S'.\nby rewrite {s}E in Cs *; apply.\nQed.\n\nEnd InjectLemmas.\n\n\nSection InductiveInvLemmas.\n\n\nVariable pr : protocol.\n\nNotation l := (plab pr).\nVariable I : dstatelet -> pred nid -> Prop.\nVariable ii : InductiveInv pr I.\n\n(* Tailored modal always-lemma *)\n\nVariables (A : Type) (this: nid).\nNotation V := (mkWorld pr).\nNotation W := (mkWorld (ProtocolWithIndInv ii)).\n\nVariable (e : DT this V A).\n\n(*\n\n[Inferences rule for invariant strengthening]\n\nThis rule essentially means that we can always verify the program in\nstronger assumptions (i.e., in a protocol, enriched with the inductive\ninvariant), if we can provide this protocol in the first place. We can\nthen also make use of the invariant.\n\n *)\n\nNotation getS i := (getStatelet i l).\n\nLemma with_inv_rule' i (r : cont A) : \n  verify i e (fun x m =>\n              I (getS m) (nodes pr (getS m)) -> r x m) ->\n        verify i (with_inv ii e) r.\nProof.\nmove=> H C t [->|[t' [H' ->{t}]]]; first by apply: alw_unfin. \nmove/aft_ind_inv: {H H'}(H (with_inv_coh C) _ H')=>/(_ _ _ C).\napply: aft_imp=>v m _[C']; apply.\nby case: C'=>_ _ _ _/(_ l); rewrite prEq; case.\nQed.        \n\nLemma with_inv_rule i (r : cont A) : \n        verify i e (fun x m => r x m) ->\n        verify i (with_inv ii e) r.\nProof.\nmove=>H; apply: with_inv_rule'.\nby move=>H1 p H2; move: (H H1 p H2)=>G; apply: (aft_imp _ G).\nQed.\n\nEnd InductiveInvLemmas.\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/InferenceRules.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.4843800842769843, "lm_q1q2_score": 0.2889003376532462}}
{"text": "Require Import VST.progs.io_mem.\nRequire Import VST.progs.io_mem_specs.\nRequire Import VST.floyd.proofauto.\nRequire Import VST.floyd.library.\nRequire Import ITree.ITree.\n(*Import ITreeNotations.*)\nNotation \"t1 >>= k2\" := (ITree.bind t1 k2)\n  (at level 50, left associativity) : itree_scope.\nNotation \"x <- t1 ;; t2\" := (ITree.bind t1 (fun x => t2))\n  (at level 100, t1 at next level, right associativity) : itree_scope.\nNotation \"t1 ;; t2\" := (ITree.bind t1 (fun _ => t2))\n  (at level 100, 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\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nDefinition putchars_spec := DECLARE _putchars putchars_spec.\nDefinition getchars_spec := DECLARE _getchars getchars_spec.\n\n(* make a new exit_spec that only allows exit code 0 if the ITREE is fully used, or that exit is only done w/ 1,\nand put empty itree in main_post *)\n\n(* This tells us that exit(0) is never called, so if we terminate successfully, the postcondition of main\n  must hold. *)\nDefinition exit_spec := DECLARE _exit\n WITH i : Z\n PRE [1%positive OF tint]\n   PROP (repable_signed i; i <> 0) LOCAL(temp 1%positive (Vint (Int.repr i))) SEP()\n POST [ tvoid ]\n   PROP(False) LOCAL() SEP().\n\nLemma div_10_dec : forall n, 0 < n ->\n  (Z.to_nat (n / 10) < Z.to_nat n)%nat.\nProof.\n  intros.\n  change 10 with (Z.of_nat 10).\n  rewrite <- (Z2Nat.id n) by omega.\n  rewrite <- div_Zdiv by discriminate.\n  rewrite !Nat2Z.id.\n  apply Nat2Z.inj_lt.\n  rewrite div_Zdiv, Z2Nat.id by omega; simpl.\n  apply Z.div_lt; auto; omega.\nQed.\n\nProgram Fixpoint chars_of_Z (n : Z) { measure (Z.to_nat n) } : list int :=\n  let n' := n / 10 in\n  match n' <=? 0 with true => [Int.repr (n + char0)] | false => chars_of_Z n' ++ [Int.repr (n mod 10 + char0)] end.\nNext Obligation.\nProof.\n  apply div_10_dec.\n  symmetry in Heq_anonymous; apply Z.leb_nle in Heq_anonymous.\n  eapply Z.lt_le_trans, Z_mult_div_ge with (b := 10); omega.\nDefined.\n\n(* The function computed by print_intr *)\nProgram Fixpoint intr n { measure (Z.to_nat n) } : list int :=\n  match n <=? 0 with\n  | true => []\n  | false => intr (n / 10) ++ [Int.repr (n mod 10 + char0)]\n  end.\nNext Obligation.\nProof.\n  apply div_10_dec.\n  symmetry in Heq_anonymous; apply Z.leb_nle in Heq_anonymous; omega.\nDefined.\n\nDefinition replace_list {X} i (l : list X) (l' : list X) :=\n  sublist 0 i l ++ l' ++ sublist (i + Zlength l') (Zlength l) l.\n\nDefinition print_intr_spec :=\n DECLARE _print_intr\n  WITH sh : share, i : Z, buf : val, j : Z, contents : list val\n  PRE [ _i OF tuint, _buf OF tptr tuchar, _j OF tint ]\n    PROP (writable_share sh; 0 <= i <= Int.max_unsigned;\n               0 <= j; j + Zlength (intr i) <= Zlength contents < Int.max_signed)\n    LOCAL (temp _i (Vint (Int.repr i)); temp _buf buf; temp _j (Vint (Int.repr j)))\n    SEP (data_at sh (tarray tuchar (Zlength contents)) contents buf)\n  POST [ tint ]\n    PROP ()\n    LOCAL (temp ret_temp (Vint (Int.repr (j + Zlength (intr i)))))\n    SEP (data_at sh (tarray tuchar (Zlength contents)) (replace_list j contents (map Vint (intr i))) buf).\n\nDefinition print_int_spec :=\n DECLARE _print_int\n  WITH gv : globals, i : Z, tr : IO_itree\n  PRE [ _i OF tuint ]\n    PROP (0 <= i < 10000)\n    LOCAL (gvars gv; temp _i (Vint (Int.repr i)))\n    SEP (mem_mgr gv; ITREE (write_list (chars_of_Z i ++ [Int.repr newline]) ;; tr))\n  POST [ tvoid ]\n    PROP ()\n    LOCAL ()\n    SEP (mem_mgr gv; ITREE tr).\n\nDefinition for_loop i z (body : Z -> itree IO_event bool) :=\n  ITree.aloop (fun '(b, j) => if (b : bool) then inr true else if j <? z then inl (b <- body j ;; Ret (b, j + 1)) else inr false) (false, i).\n\nDefinition sum_Z l := fold_right Z.add 0 l.\n\nDefinition read_sum_inner n nums j :=\n  if orb (10 <=? Znth j nums) (Znth j nums <? 0) then Ret true\n  else write_list (chars_of_Z (n + sum_Z (sublist 0 (j + 1) nums)) ++ [Int.repr newline]);; Ret false.\n\nDefinition read_sum n lc : IO_itree :=\n  ITree.aloop (fun '(b, n, lc) => if (b : bool) then inr tt else\n  if zlt n 1000 then\n    let nums := map (fun c => Int.unsigned c - char0) lc in\n    inl (b <- for_loop 0 4 (read_sum_inner n nums) ;; if (b : bool) then Ret (true, n, lc) else\n    lc' <- read_list 4;; Ret (false, n + sum_Z nums, lc'))\n  else inr tt) (false, n, lc).\n\nDefinition main_itree := lc <- read_list 4;; read_sum 0 lc (* ;; exit 0 *).\n(* !! Making exit an effect and requiring it to be called at the end of a program is a good\n   way to get around the problem of dropping suffixes of an itree. *)\n\nDefinition main_spec :=\n DECLARE _main\n  WITH gv : globals\n  PRE  [] main_pre_ext prog main_itree nil gv\n  POST [ tint ] PROP () LOCAL () SEP (mem_mgr gv; ITREE (Ret tt)).\n(* making the post false forces user to call exit to terminate *)\n\n(* override default spec for exit *)\nDefinition library_G  {cs: compspecs} prog :=\n let defs := prog_defs prog in\n  try_spec \"_malloc\" malloc_spec' defs ++\n  try_spec \"_free\" free_spec' defs.\n\nLtac with_library prog G :=\n  let pr := eval unfold prog in prog in  \n let x := constr:(library_G pr ++ G) in\n  let x := eval cbv beta delta [app library_G] in x in\n  let x := simpl_prog_defs x in \n  let x := eval cbv beta iota zeta delta [try_spec] in x in \n  let x := eval simpl in x in \n    with_library' pr x.\n\nDefinition Gprog : funspecs := ltac:(with_library prog [putchars_spec; getchars_spec;\n  exit_spec; print_intr_spec; print_int_spec; main_spec]).\n\nLemma divu_repr : forall x y,\n  0 <= x <= Int.max_unsigned -> 0 <= y <= Int.max_unsigned ->\n  Int.divu (Int.repr x) (Int.repr y) = Int.repr (x / y).\nProof.\n  intros; unfold Int.divu.\n  rewrite !Int.unsigned_repr; auto.\nQed.\n\n(*Opaque bind.\n\nOpaque Nat.div Nat.modulo.*)\n\nLemma intr_eq : forall n, intr n =\n  match n <=? 0 with\n  | true => []\n  | false => intr (n / 10) ++ [Int.repr (n mod 10 + char0)]\n  end.\nProof.\n  intros.\n  unfold intr at 1.\n  rewrite Wf.WfExtensionality.fix_sub_eq_ext; simpl; fold intr.\n  destruct n; reflexivity.\nQed.\n\n(* missing from standard library *)\nLemma Zdiv_le_compat_r : forall m n p, p > 0 -> m <= n -> m / p <= n / p.\nProof.\n  intros; unfold Z.div.\n  pose proof (Z_div_mod m _ H) as Hm.\n  pose proof (Z_div_mod n _ H) as Hn.\n  destruct (Z.div_eucl m p), (Z.div_eucl n p).\n  destruct Hm, Hn; subst.\n  destruct (zle z z1); auto.\n  assert (p * z1 + p <= p * z); try omega.\n  rewrite <- Z.mul_succ_r.\n  apply Zmult_le_compat_l; omega.\nQed.\n\nLemma intr_lt : forall n, 0 < n -> Zlength (intr (n / 10)) = Zlength (intr n) - 1.\nProof.\n  intros.\n  rewrite (intr_eq n).\n  destruct (n <=? 0) eqn: Hn.\n  { apply Zle_bool_imp_le in Hn; omega. }\n  rewrite Zlength_app, Zlength_cons, Zlength_nil; omega.\nQed.\n\nLemma replace_list_nil : forall {X} i (l : list X), 0 <= i <= Zlength l -> replace_list i l [] = l.\nProof.\n  intros; unfold replace_list.\n  rewrite Zlength_nil, Z.add_0_r; simpl.\n  rewrite sublist_rejoin, sublist_same by omega; auto.\nQed.\n\nLemma replace_list_upd_snoc : forall {X} i (l l' : list X) x, 0 <= i -> i + Zlength l' < Zlength l ->\n  upd_Znth (i + Zlength l') (replace_list i l l') x = replace_list i l (l' ++ [x]).\nProof.\n  intros; unfold replace_list.\n  rewrite upd_Znth_app2; rewrite ?Zlength_sublist; try rep_omega.\n  f_equal.\n  rewrite Z.sub_0_r, Z.add_simpl_l, upd_Znth_app2; rewrite ?Zlength_sublist; try rep_omega.\n  rewrite Zminus_diag, Zlength_app, Zlength_cons, Zlength_nil, upd_Znth0, <- app_assoc; simpl; f_equal; f_equal.\n  rewrite Zlength_sublist by rep_omega.\n  rewrite sublist_sublist by rep_omega.\n  f_equal; omega.\n  { rewrite Zlength_app, Zlength_sublist; rep_omega. }\nQed.\n\nLemma body_print_intr: semax_body Vprog Gprog f_print_intr print_intr_spec.\nProof.\n  start_function.\n  forward.\n  forward_if (PROP ()\n    LOCAL (temp _k (Vint (Int.repr (j + Zlength (intr i) - 1))))\n    SEP (data_at sh (tarray tuchar (Zlength contents)) (replace_list j contents (map Vint (intr i))) buf)).\n  - forward.\n    rewrite divu_repr by rep_omega.\n    forward.\n    forward_call (sh, i / 10, buf, j, contents).\n    { rewrite intr_lt by omega; split; auto.\n      assert (i / 10 < i).\n      { apply Z.div_lt; omega. }\n      split; [split|]; try omega.\n      apply Z.div_pos; omega. }\n    rewrite modu_repr by (omega || computable).\n    forward.\n    { entailer!.\n      split; try rep_omega.\n      rewrite intr_lt; omega. }\n    entailer!.\n    { rewrite intr_lt by omega.\n      rewrite Z.add_sub_assoc; auto. }\n    rewrite (intr_eq i).\n    destruct (i <=? 0) eqn: Hi; [apply Zle_bool_imp_le in Hi; omega|].\n    pose proof (Z_mod_lt i 10).\n    rewrite <- (Zlength_map _ _ Vint), replace_list_upd_snoc.\n    rewrite (zero_ext_inrange 8 (Int.repr (i mod 10))), add_repr.\n    rewrite zero_ext_inrange, map_app.\n    apply derives_refl.\n    { rewrite Int.unsigned_repr; simpl; rep_omega. }\n    { rewrite Int.unsigned_repr; simpl; rep_omega. }\n    { omega. }\n    { rewrite Zlength_map, intr_lt; rep_omega. }\n  - forward.\n    entailer!.\n    (* spec has an off-by-one error *)\n    { admit. }\n    rewrite replace_list_nil by rep_omega; auto.\n  - forward.\n    rewrite Z.sub_simpl_r; entailer!.\nAdmitted.\n\nLemma chars_of_Z_eq : forall n, chars_of_Z n =\n  let n' := n / 10 in\n  match n' <=? 0 with true => [Int.repr (n + char0)] | false => chars_of_Z n' ++ [Int.repr (n mod 10 + char0)] end.\nProof.\n  intros.\n  unfold chars_of_Z at 1.\n  rewrite Wf.WfExtensionality.fix_sub_eq_ext; simpl; fold chars_of_Z.\n  destruct (_ <=? _); reflexivity.\nQed.\n\nLemma chars_of_Z_intr : forall n,\n  chars_of_Z n = if n <=? 0 then [Int.repr (n + char0)] else intr n.\nProof.\n  intros.\n  destruct (Z.leb_spec n 0).\n  { rewrite chars_of_Z_eq; simpl.\n    apply Zdiv_le_compat_r with (p := 10) in H; try omega.\n    rewrite Zdiv_0_l in H.\n    destruct (Z.leb_spec (n / 10) 0); auto; omega. }\n  induction n as [? IH] using (well_founded_induction (Zwf.Zwf_well_founded 0)).\n  rewrite chars_of_Z_eq, intr_eq.\n  destruct (n <=? 0) eqn: Hn; [apply Zle_bool_imp_le in Hn; omega|].\n  simpl.\n  destruct (n / 10 <=? 0) eqn: Hdiv.\n  - apply Zle_bool_imp_le in Hdiv.\n    assert (0 <= n / 10).\n    { apply Z.div_pos; omega. }\n    assert (n / 10 = 0) as Hz by omega.\n    rewrite Hz; simpl.\n    apply Z.div_small_iff in Hz as [|]; try omega.\n    rewrite Zmod_small; auto.\n  - apply Z.leb_nle in Hdiv.\n    rewrite IH; auto; try omega.\n    split; try omega.\n    apply Z.div_lt; auto; omega.\nQed.\n\nLemma intr_length : forall n a, 0 <= a -> n < Z.pow 10 a -> Zlength (intr n) <= a.\nProof.\n  induction n using (well_founded_induction (Zwf.Zwf_well_founded 0)); intros.\n  rewrite intr_eq.\n  destruct (Z.leb_spec n 0); [rewrite Zlength_nil; omega|].\n  rewrite Zlength_app.\n  assert (Zlength (intr (n / 10)) <= a - 1); [|rewrite Zlength_cons, Zlength_nil; omega].\n  assert (0 <= a - 1).\n  { destruct (Z.eq_dec a 0); subst; simpl in *; omega. }\n  apply H; auto.\n  - split; try omega.\n    apply Z.div_lt; auto; omega.\n  - apply Zmult_lt_reg_r with 10; try omega.\n    rewrite (Z.mul_comm (10 ^ _)), <- Z.pow_succ_r by auto.\n    unfold Z.succ; rewrite Z.sub_simpl_r.\n    eapply Z.le_lt_trans; eauto.\n    rewrite Z.mul_comm; apply Z.mul_div_le; omega.\nQed.\n\nLemma chars_of_Z_length : forall n a, 0 < a -> n < Z.pow 10 a -> Zlength (chars_of_Z n) <= a.\nProof.\n  intros.\n  rewrite chars_of_Z_intr.\n  destruct (Z.leb_spec n 0); [|apply intr_length; omega].\n  rewrite Zlength_cons, Zlength_nil; omega.\nQed.\n\nLemma body_print_int: semax_body Vprog Gprog f_print_int print_int_spec.\nProof.\n  start_function.\n  forward_call (tarray tuchar 5, gv).\n  { split; auto; simpl; computable. }\n  Intro buf.\n  forward_if (buf <> nullval).\n  { if_tac; entailer!. }\n  { forward_call 1.\n    rep_omega.\n    entailer!. }\n  { forward.\n    entailer!. }\n  Intros; rewrite if_false by auto.\n  forward_if (PROP ()\n    LOCAL (temp _buf buf; gvars gv; temp _i (Vint (Int.repr i));\n                 temp _k (Vint (Int.repr (Zlength (chars_of_Z i ++ [Int.repr newline])))))\n    SEP (mem_mgr gv; malloc_token Ews (tarray tuchar 5) buf;\n            data_at Ews (tarray tuchar 5) (map Vint (chars_of_Z i) ++ Vint (Int.repr newline) ::\n              list_repeat (Z.to_nat (4 - Zlength (chars_of_Z i))) Vundef) buf;\n            ITREE (write_list (chars_of_Z i ++ [Int.repr newline]);; tr))).\n  - Intros.\n    forward.\n    forward.\n    forward.\n    entailer!.\n  - Intros.\n    sep_apply data_at__data_at.\n    unfold default_val; simpl.\n    assert (Zlength (intr i) <= 4).\n    { apply intr_length; try omega.\n      apply H. }\n    forward_call.\n    { rewrite !Zlength_cons, Zlength_nil.\n      simpl; repeat (split; auto); rep_omega. }\n    forward.\n    { entailer!.\n      rewrite !Zlength_cons, Zlength_nil; rep_omega. }\n    forward.\n    entailer!.\n    { rewrite Zlength_app, Zlength_cons, Zlength_nil, chars_of_Z_intr.\n      destruct (Z.leb_spec i 0); auto; omega. }\n    unfold replace_list; simpl.\n    rewrite (sublist_list_repeat _ _ 5 Vundef).\n    rewrite !Zlength_cons, Zlength_nil, Zlength_map; simpl.\n    rewrite upd_Znth_app2.\n    rewrite Zlength_map, Zminus_diag, upd_Znth0, sublist_list_repeat; try omega.\n    apply derives_refl'.\n    f_equal.\n    rewrite chars_of_Z_intr.\n    destruct (Z.leb_spec i 0); try omega.\n    rewrite zero_ext_inrange.\n    f_equal; f_equal; f_equal; f_equal.\n    rewrite Zlength_list_repeat; try omega.\n    { simpl; rewrite Int.unsigned_repr; rep_omega. }\n    { rewrite Zlength_list_repeat; omega. }\n    { rewrite Zlength_map, Zlength_list_repeat; omega. }\n    { rewrite Zlength_map; rep_omega. }\n    { rewrite !Zlength_cons, Zlength_nil, Zlength_map; omega. }\n  - forward_call (Ews, buf, chars_of_Z i ++ [Int.repr newline],\n      5, list_repeat (Z.to_nat (4 - Zlength (chars_of_Z i))) Vundef, tr).\n    { rewrite map_app, <- app_assoc; simpl; cancel. }\n    forward_call (tarray tuchar 5, buf, gv).\n    { rewrite if_false by auto; cancel. }\n    forward.\nQed.\n\nLemma read_sum_eq : forall n lc, read_sum n lc ≈\n  if zlt n 1000 then\n    let nums := map (fun c => Int.unsigned c - char0) lc in\n    b <- for_loop 0 4 (read_sum_inner n nums) ;; if (b : bool) then Ret tt else\n    lc' <- read_list 4;; read_sum (n + sum_Z nums) lc'\n  else Ret tt.\nProof.\n  intros.\n  unfold read_sum.\n  rewrite unfold_aloop.\n  if_tac; [|reflexivity].\n  unfold ITree._aloop, id.\n  rewrite bind_bind.\n  apply eutt_bind; [|reflexivity].\n  intros [].\n  - rewrite Shallow.bind_ret, unfold_aloop.\n    reflexivity.\n  - rewrite bind_bind.\n    apply eutt_bind; [|reflexivity].\n    intro.\n    rewrite Shallow.bind_ret; reflexivity.\nQed.\n\nLemma for_loop_eq : forall i z body,\n  for_loop i z body ≈ if i <? z then b <- body i ;; if (b : bool) then Ret true else for_loop (i + 1) z body else Ret false.\nProof.\n  intros.\n  unfold for_loop.\n  rewrite unfold_aloop.\n  simple_if_tac; [|reflexivity].\n  unfold ITree._aloop, id.\n  rewrite bind_bind.\n  apply eutt_bind; [|reflexivity].\n  intros [].\n  - rewrite Shallow.bind_ret, unfold_aloop.\n    reflexivity.\n  - rewrite Shallow.bind_ret; reflexivity.\nQed.\n\nLemma sum_Z_app : forall l1 l2, sum_Z (l1 ++ l2) = sum_Z l1 + sum_Z l2.\nProof.\n  induction l1; auto; simpl; intros.\n  rewrite IHl1; omega.\nQed.\n\nLemma body_main: semax_body Vprog Gprog f_main main_spec.\nProof.\n  start_function.\n  replace_SEP 0 (ITREE main_itree).\n  { go_lower; apply has_ext_ITREE. }\n  forward.\n  rewrite <- (emp_sepcon (ITREE main_itree)); Intros.\n  replace_SEP 0 (mem_mgr gv).\n  { go_lower; apply create_mem_mgr. }\n  forward_call (tarray tuchar 4, gv).\n  { simpl; repeat (split; auto); rep_omega. }\n  Intro buf.\n  forward_if (buf <> nullval).\n  { if_tac; entailer!. }\n  { forward_call 1.\n    rep_omega.\n    entailer!. }\n  { forward.\n    entailer!. }\n  Intros; rewrite if_false by auto.\n  unfold main_itree.\n  forward_call (Ews, buf, 4, fun lc => read_sum 0 lc).\n  { simpl; cancel. }\n  Intros lc.\n  set (Inv := EX n : Z, EX lc : list int,\n    PROP (0 <= n < 1040; Forall (fun i => Int.unsigned i <= Byte.max_unsigned) lc)\n    LOCAL (temp _i (Vint (Int.repr 4)); temp _buf buf; temp _n (Vint (Int.repr n)); gvars gv)\n    SEP (ITREE (read_sum n lc); data_at Ews (tarray tuchar 4) (map Vint lc) buf;\n      mem_mgr gv; malloc_token Ews (tarray tuchar 4) buf)).\n  forward_while Inv.\n  { Exists 0 lc; entailer!. }\n  { entailer!. }\n  - clear dependent lc; rename lc0 into lc.\n    erewrite ITREE_ext by apply read_sum_eq.\n    rewrite if_true by auto; simpl ITREE.\n    set (nums := map (fun i => Int.unsigned i - char0) lc).\n    assert_PROP (Zlength lc = 4).\n    { entailer!.\n      rewrite Zlength_map in *; auto. }\n    assert (Zlength nums = 4) by (subst nums; rewrite Zlength_map; auto).\n    forward_for_simple_bound 4 (EX j : Z, PROP (0 <= n + sum_Z (sublist 0 j nums) < 1000 + 10 * j)\n     LOCAL (temp _i (Vint (Int.repr 4)); temp _buf buf; temp _n (Vint (Int.repr (n + sum_Z (sublist 0 j nums)))); gvars gv)\n     SEP (ITREE (b <- for_loop j 4\n         (read_sum_inner n nums) ;; if (b : bool) then Ret tt else lc' <- read_list 4 ;; read_sum (n + sum_Z nums) lc');\n             data_at Ews (tarray tuchar 4) (map Vint lc) buf; mem_mgr gv; malloc_token Ews (tarray tuchar 4) buf)).\n    + entailer!.\n      { omega. }\n    + simpl.\n      forward.\n      { entailer!.\n        rewrite zero_ext_inrange by (apply Forall_Znth; auto; omega).\n        apply Forall_Znth; auto; omega. }\n      forward.\n      rewrite zero_ext_inrange by (apply Forall_Znth; auto; omega).\n      forward_if (0 <= Int.unsigned (Znth i lc) - char0 < 10).\n      { forward_call (tarray tuchar 4, buf, gv).\n        { rewrite if_false by auto; cancel. }\n        forward.\n        entailer!.\n        apply ITREE_impl.\n        rewrite for_loop_eq.\n        destruct (Z.ltb_spec i 4); try omega.\n        unfold read_sum_inner at 2.\n        replace (_ || _)%bool with true.\n        rewrite !Shallow.bind_ret; reflexivity.\n        symmetry; rewrite orb_true_iff.\n        rewrite Int.unsigned_sub_borrow in *.\n        unfold Int.sub_borrow in *.\n        subst nums; rewrite Znth_map by omega.\n        rewrite (Int.unsigned_repr 48), Int.unsigned_zero, Z.sub_0_r in * by rep_omega.\n        destruct (zlt _ _); [right; apply Z.ltb_lt | left; apply Z.leb_le]; auto.\n        rewrite Int.unsigned_zero in *; simpl in *.\n        unfold char0; omega. }\n      { forward.\n        entailer!.\n        unfold Int.sub in *.\n        rewrite Int.unsigned_repr_eq, Int.unsigned_repr in * by computable.\n        pose proof (Int.unsigned_range (Znth i lc)).\n        destruct (zlt (Int.unsigned (Znth i lc)) char0).\n        { unfold char0 in *; rewrite <- Z_mod_plus_full with (b := 1), Zmod_small in *; rep_omega. }\n        unfold char0 in *; rewrite Zmod_small in *; omega. }\n      unfold Int.sub.\n      rewrite Int.unsigned_repr by computable.\n      forward.\n      rewrite add_repr.\n      erewrite ITREE_ext by (rewrite for_loop_eq; reflexivity).\n      destruct (Z.ltb_spec i 4); try omega.\n      unfold read_sum_inner at 2.\n      unfold nums; rewrite Znth_map by omega.\n      assert (((10 <=? Int.unsigned (Znth i lc) - char0) || (Int.unsigned (Znth i lc) - char0 <? 0))%bool = false) as Hin.\n      { rewrite orb_false_iff.\n        split; [apply Z.leb_nle | apply Z.ltb_nlt]; omega. }\n      rewrite Hin.\n      assert (sublist 0 (i + 1) nums = sublist 0 i nums ++ [Int.unsigned (Znth i lc) - char0]) as Hi.\n      { rewrite (sublist_split _ i (i + 1)), (sublist_one i (i + 1)) by omega.\n        f_equal; subst nums.\n        rewrite Znth_map by omega; auto. }\n      forward_call (gv, n + sum_Z (sublist 0 (i + 1) nums),\n        b <- for_loop (i + 1) 4 (read_sum_inner n nums) ;; if (b : bool) then Ret tt else lc' <- read_list 4 ;; read_sum (n + sum_Z nums) lc').\n      { entailer!.\n        rewrite Hi, sum_Z_app; simpl.\n        rewrite Z.add_assoc, Z.add_0_r; auto. }\n      { rewrite sepcon_assoc; apply sepcon_derives; cancel.\n        apply ITREE_impl; rewrite !bind_bind.\n        apply eutt_bind; [|reflexivity].\n        intros [].\n        rewrite Shallow.bind_ret; reflexivity. }\n      { rewrite Hi, sum_Z_app; simpl; omega. }\n      entailer!.\n      { rewrite Hi, sum_Z_app; simpl.\n        rewrite Z.add_0_r, Z.add_assoc; split; auto; omega. }\n    + erewrite ITREE_ext by (rewrite for_loop_eq; reflexivity).\n      destruct (Z.ltb_spec 4 4); try omega.\n      forward_call (Ews, buf, 4, fun lc' => read_sum (n + sum_Z nums) lc').\n      { rewrite sepcon_assoc; apply sepcon_derives; cancel.\n        apply ITREE_impl.\n        simpl; rewrite Shallow.bind_ret; reflexivity. }\n      Intros lc'.\n      forward.\n      rewrite sublist_same in * by auto.\n      Exists (n + sum_Z nums, lc'); entailer!.\n      apply derives_refl.\n  - subst Inv.\n    forward_call (tarray tuchar 4, buf, gv).\n    { rewrite if_false by auto; cancel. }\n    forward.\n    cancel; apply ITREE_impl.\n    rewrite read_sum_eq.\n    rewrite if_false; [reflexivity | omega].\nQed.\n\nDefinition ext_link := ext_link_prog prog.\n\nInstance Espec : OracleKind := IO_Espec ext_link.\n\nLemma prog_correct:\n  semax_prog_ext prog main_itree Vprog Gprog.\nProof.\nprove_semax_prog.\n(*semax_func_cons_ext.\n{ simpl; Intro i.\n  apply typecheck_return_value; auto. }\nsemax_func_cons_ext.\nsemax_func_cons body_print_intr.\nsemax_func_cons body_print_int.\nsemax_func_cons body_main.\nQed.*)\nAdmitted.\n\nRequire Import VST.veric.SequentialClight.\nRequire Import VST.progs.io_mem_dry.\n\nDefinition init_mem_exists : { m | Genv.init_mem prog = Some m }.\nProof.\n  unfold Genv.init_mem; simpl.\nAdmitted. (* seems true, but hard to prove -- can we compute it? *)\n\nDefinition init_mem := proj1_sig init_mem_exists.\n\nDefinition main_block_exists : {b | Genv.find_symbol (Genv.globalenv prog) (prog_main prog) = Some b}.\nProof.\n  eexists; simpl.\n  unfold Genv.find_symbol; simpl; reflexivity.\nQed.\n\nDefinition main_block := proj1_sig main_block_exists.\n\nTheorem prog_toplevel : exists q : Clight_new.corestate,\n  semantics.initial_core (Clight_new.cl_core_sem (globalenv prog)) 0 init_mem q init_mem (Vptr main_block Ptrofs.zero) [] /\\\n  forall n, @step_lemmas.dry_safeN _ _ _ _ Clight_sim.genv_symb_injective (Clight_sim.coresem_extract_cenv (Clight_new.cl_core_sem (globalenv prog)) (prog_comp_env prog))\n             (io_dry_spec ext_link) {| Clight_sim.CC.genv_genv := Genv.globalenv prog; Clight_sim.CC.genv_cenv := prog_comp_env prog |} n\n            main_itree q init_mem.\nProof.\n  edestruct whole_program_sequential_safety_ext with (V := Vprog) as (b & q & m' & Hb & Hq & Hsafe).\n  - apply juicy_dry_specs.\n  - apply dry_spec_mem.\n  - apply CSHL_Sound.semax_prog_ext_sound, prog_correct.\n  - apply (proj2_sig init_mem_exists).\n  - exists q.\n    rewrite (proj2_sig main_block_exists) in Hb; inv Hb.\n    assert (m' = init_mem); [|subst; auto].\n    destruct Hq; tauto.\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_io_mem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.4843800842769843, "lm_q1q2_score": 0.2889003307039048}}
{"text": "Require Import List.\nImport ListNotations.\n\nRequire Import Chord.Chord.\n\nRequire Import Chord.SystemReachable.\n\nDefinition has_first_succ (gst : global_state) (h : addr) (s : pointer) : Prop :=\n  exists st,\n    sigma gst h = Some st /\\\n    hd_error (succ_list st) = Some s.\n\nLemma has_first_succ_intro :\n  forall gst h s st,\n    sigma gst h = Some st ->\n    hd_error (succ_list st) = Some s ->\n    has_first_succ gst h s.\nProof.\n  intros.\n  eexists; eauto.\nQed.\n\nTheorem first_succ_never_self :\n  forall gst h s,\n    reachable_st gst ->\n    has_first_succ gst h s ->\n    h <> (addr_of s).\nProof.\n(*\nEasy consequence of the (difficult) Zave invariant.\n\nDIFFCULTY: 1\nUSED: In phase two.\n*)\nAdmitted.", "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/FirstSuccNeverSelf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2887758489809229}}
{"text": "From ch2o_compcert Require Export return_divs_ch2o_safe return_divs_csyntaxgen_simplified ch2o_compcertc_lp64 compcertc_compiler.\n\nLemma return_divs_compcertc_safe: compcertc_safe_program (λ z, z = 2) prog.\nProof.\napply soundness with (2:=return_divs_ch2o_safe).\neconstructor.\n- apply δ_main.\n- apply init_mem_ok.\n  reflexivity.\n- reflexivity.\n- reflexivity.\n- constructor.\n  constructor.\n  + constructor.\n    * constructor.\n      constructor; (unfold int_lower || unfold int_upper); simpl; lia.\n    * constructor.\n      constructor; (unfold int_lower || unfold int_upper); simpl; lia.\n  + constructor.\n    * constructor.\n      constructor; (unfold int_lower || unfold int_upper); simpl; lia.\n    * constructor.\n      constructor; (unfold int_lower || unfold int_upper); simpl; lia.\nQed.\n\nTheorem return_divs_asm_safe tp:\n  transf_c_program prog = OK tp →\n  asm_program_satisfies_spec tp (satisfies_postcondition (λ z, z = 2)).\nProof.\nintros.\napply transf_c_program_safe with (1:=H).\napply return_divs_compcertc_safe.\nQed.", "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/return_divs_asm_safe.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2887758489809229}}
{"text": "From Coq Require Import Reals Bool Relations RelationClasses List ListSet Setoid Permutation EqdepFacts ChoiceFacts Classical Sorting.\nImport ListNotations.\n\nFrom CasperCBC.Lib Require Import Preamble ListExtras ListSetExtras SortedLists.\nFrom CasperCBC Require Import VLSM.Equivocation VLSM.Decisions Lib.Measurable CBC.Protocol CBC.Common.\n\n(** * CBC Light Node Protocol *)\n\n(* Lists of state hashes *)\nDefinition justification_type (hash : Type) : Type := list hash.\n\n(* Messages *)\nDefinition message (C V hash : Type) : Type := C * V * justification_type hash.\n\n(* Light node states are sets of message *)\n(* Additionally, we don't care about sorting *)\nDefinition state C V hash := set (message C V hash).\n\nClass MessageHash message hash :=\n  { hash_message : message -> hash\n  }.\n\nClass InjectiveMessageHash message hash (Hmh : MessageHash message hash) :=\n  { hash_message_injective : Inj eq eq hash_message\n  }.\n\nSection LightNode_protocol_eq.\nContext\n  {hash C V : Type}\n  {HscH : StrictlyComparable hash}\n  {HscC : StrictlyComparable C}\n  {HscV : StrictlyComparable V}\n  {Hmh : MessageHash (message C V hash) hash}\n  {Hmhi : InjectiveMessageHash (message C V hash) hash Hmh}\n  {HmV : Measurable V}\n  {Hrt : ReachableThreshold V}\n  {He : Estimator (state C V hash) C}\n  (eq_H := @strictly_comparable_eq_dec _ HscH)\n  (eq_V := @strictly_comparable_eq_dec _ HscV)\n  .\n\nExisting Instance eq_H.\nExisting Instance eq_V.\n\nDefinition justification_type_inhabited : justification_type hash := [].\n\nDefinition justification_compare\n  : (justification_type hash -> justification_type hash -> comparison)\n  :=\n  list_compare compare.\n\nInstance about_justification_type\n  : StrictlyComparable (justification_type hash)\n  :=\n  { inhabited := justification_type_inhabited;\n    compare := list_compare compare;\n    compare_strictorder := list_compare_strict_order;\n  }.\n\nDefinition justification_add\n  : hash -> justification_type hash -> justification_type hash\n  :=\n  add_in_sorted_list_fn compare.\n\nDefinition justification_add_iff\n  :=\n  @add_in_sorted_list_iff hash compare compare_strictorder.\n\nDefinition justification_add_head\n  :=\n  @add_in_sorted_list_head hash compare compare_strictorder.\n\nDefinition justification_add_tail\n  :=\n  @add_in_sorted_list_tail hash compare compare_strictorder.\n\nDefinition justification_add_sorted\n  :=\n  @add_in_sorted_list_sorted hash compare compare_strictorder.\n\nDefinition justification_add_all\n  : list hash -> justification_type hash\n  :=\n  fold_right justification_add nil.\n\nLemma justification_sorted\n  : forall j : list hash,\n  LocallySorted (compare_lt compare) (justification_add_all j).\nProof.\n  induction j.\n  - simpl. constructor.\n  - apply justification_add_sorted. assumption.\nQed.\n\nLemma justification_set_eq\n  : forall hs : list hash,\n  set_eq hs (justification_add_all hs).\nProof.\n  induction hs; simpl.\n  - apply set_eq_refl.\n  - split; intros x Hin\n    ; (unfold justification_add; rewrite justification_add_iff) || apply justification_add_iff in Hin\n    ; destruct Hin as [Heq | Hin]\n    ; try (subst; left; reflexivity)\n    ;  right; apply IHhs; assumption.\nQed.\n\nLemma justification_add_all_injective\n  : forall hs1 hs2 : list hash,\n  justification_add_all hs1 = justification_add_all hs2 ->\n  set_eq hs1 hs2.\nProof.\n  intros.\n  apply (@set_equality_predicate hash (compare_lt compare) compare_lt_strict_order) in H;\n    try apply justification_sorted.\n  apply set_eq_tran with (justification_add_all hs1); try apply justification_set_eq.\n  apply set_eq_tran with (justification_add_all hs2); try assumption.\n  apply set_eq_comm. apply justification_set_eq.\nQed.\n\nDefinition justification_in\n  : hash -> list hash -> bool := inb decide_eq.\n\nInstance message_type\n  : StrictlyComparable (message C V hash)\n  :=\n  TripleStrictlyComparable C V (justification_type hash).\n\nInstance eq_message\n  : EqDecision (message C V hash)\n  :=\n  @strictly_comparable_eq_dec _ message_type.\n\n(* StrictlyComparable and CompareStrictOrder for message type comes for free *)\n\nDefinition estimate\n  (msg : message C V hash) : C\n  :=\n  match msg with (c, _, _) => c end.\n\nDefinition sender\n  (msg : message C V hash) : V\n  :=\n  match msg with (_, v, _) => v end.\n\nDefinition justification\n  (msg : message C V hash) : justification_type hash :=\n  match msg with (_, _, j) => j end.\n\n\nDefinition state_inhabited {C V hash} : state C V hash := [].\n\nDefinition state_compare\n  : (state C V hash -> state C V hash -> comparison) := list_compare compare.\n\nInstance about_state\n  : StrictlyComparable (state C V hash) :=\n  { inhabited := state_inhabited;\n    compare := list_compare compare;\n    compare_strictorder := list_compare_strict_order;\n  }.\n\nDefinition state0 C V hash : state C V hash := [].\n\nDefinition state_add\n  : message C V hash -> state C V hash -> state C V hash\n  :=\n  set_add decide_eq.\n\nDefinition state_remove\n  : message C V hash -> state C V hash -> state C V hash\n  :=\n  set_remove decide_eq.\n\nDefinition state_in\n  : message C V hash-> state C V hash-> bool\n  :=\n  set_mem decide_eq.\n\nDefinition state_union\n  : state C V hash-> state C V hash-> state C V hash\n  :=\n  set_union decide_eq.\n\nDefinition state_eq\n  (s1 s2 : state C V hash)\n  :=\n  incl s1 s2 /\\ incl s2 s1.\n\nLemma state_union_comm\n  : forall s1 s2 : state C V hash, state_eq (state_union s1 s2) (state_union s2 s1).\nProof.\n  intros; unfold state_eq; split;\n  intros x H_in;\n  now apply set_union_comm.\nQed.\n\nDefinition hash_state\n  (sigma : state C V hash) : justification_type hash :=\n  justification_add_all (map hash_message sigma).\n\nLemma hash_state_sorted\n  : forall sigma : state C V hash,\n  LocallySorted (compare_lt compare) (hash_state sigma).\nProof.\n  intros.\n  apply justification_sorted.\nQed.\n\nLemma hash_state_injective\n  : forall sigma1 sigma2 : state C V hash,\n  hash_state sigma1 = hash_state sigma2\n  <->\n  set_eq sigma1 sigma2.\nProof.\n  split; intros.\n  - apply justification_add_all_injective in H.\n    destruct H as [H12 H21].\n    split; intros x Hin\n    ; apply (in_map hash_message) in Hin\n    ; apply H12 in Hin || apply H21 in Hin\n    ; apply in_map_iff in Hin\n    ; destruct Hin as [x' [Heq Hin]]\n    ; apply hash_message_injective in Heq\n    ; subst; assumption.\n  - apply (@set_equality_predicate hash (compare_lt compare) compare_lt_strict_order); try apply hash_state_sorted.\n    unfold hash_state.\n    apply set_eq_tran with (map hash_message sigma2); try apply (justification_set_eq (map hash_message sigma2)).\n    apply set_eq_comm.\n    apply set_eq_tran with (map hash_message sigma1); try apply (justification_set_eq (map hash_message sigma1)).\n    apply map_set_eq. apply set_eq_comm. assumption.\nQed.\n\nLemma hash_state_in\n  : forall (sigma : state C V hash) msg,\n  In (hash_message msg) (hash_state sigma) <->\n  In msg sigma.\nProof.\n  unfold hash_state.\n  intros.\n  assert (H_s : set_eq (map hash_message sigma) (justification_add_all (map hash_message sigma)))\n      by apply justification_set_eq.\n  split; intro Hin.\n  - apply H_s in Hin.\n    apply in_map_iff in Hin.\n    destruct Hin as [msg' [Heq Hin]].\n    apply hash_message_injective in Heq. subst. assumption.\n  - apply H_s. apply in_map. assumption.\nQed.\n\nLemma hash_state_incl\n  : forall sigma1 sigma2 : state C V hash,\n  incl sigma1 sigma2 <-> incl (hash_state sigma1) (hash_state sigma2).\nProof.\n  intros.\n  assert (H_s1 : set_eq (map hash_message sigma1) (justification_add_all (map hash_message sigma1)))\n      by apply justification_set_eq.\n  assert (H_s2 : set_eq (map hash_message sigma2) (justification_add_all (map hash_message sigma2)))\n      by apply justification_set_eq.\n  unfold hash_state.\n  split; intro Hincl.\n  - intros h Hin.\n    apply H_s2. apply H_s1 in Hin.\n    apply in_map_iff. apply in_map_iff in Hin.\n    destruct Hin as [msg [H_mh Hin_m]].\n    apply Hincl in Hin_m.\n    exists msg. split; assumption.\n  - intros msg Hin. apply hash_state_in in Hin.\n    apply Hincl in Hin.\n    apply hash_state_in in Hin. assumption.\nQed.\n\nDefinition equivocating_messages\n  (msg1 msg2 : message C V hash) : bool\n  :=\n  match decide (msg1 = msg2) with\n  | left _  => false\n  | _ => match msg1, msg2 with (c1,v1,j1), (c2,v2,j2) =>\n      match decide (v1 = v2) with\n      | left _  => negb (inb decide_eq (hash_message msg1) j2) && negb (inb decide_eq (hash_message msg2) j1)\n      | right _ => false\n      end\n    end\n  end.\n\nDefinition equivocating_messages_prop\n  (msg1 msg2 : message C V hash) : Prop\n  :=\n  msg1 <> msg2 /\\ sender msg1 = sender msg2 /\\ ~ In (hash_message msg1) (justification msg2) /\\ ~ In (hash_message msg2) (justification msg1).\n\nLemma equivocating_messages_sender\n  : forall msg1 msg2 : message C V hash,\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 (decide ((c1, v1, j1) = (c2, v2, j2))).\n  rewrite decide_True in H; congruence.\n  rewrite decide_False in H.\n  destruct (decide (v1 = v2)).\n  assumption. inversion H. assumption.\nQed.\n\nLemma equivocating_messages_correct\n  : forall (msg1 msg2 : message C V hash),\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 decide_True in H; congruence.\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_function decide_eq) in H_absurd.\n      unfold equivocating_messages in H.\n      simpl in H_absurd.\n      rewrite H_absurd in H.\n      destruct (decide ((c1, v1, j1) = (c2, v2, j2))).\n      rewrite decide_True in H; congruence.\n      rewrite decide_False in H; try congruence.\n      destruct (decide (v1 = v2)); simpl in H; congruence.\n    + (* Proving msg2 is not in msg1's justification *)\n      intro H_absurd. apply (in_function decide_eq) in H_absurd.\n      unfold equivocating_messages in H.\n      simpl in H_absurd. rewrite H_absurd in H.\n      destruct (decide ((c1,v1,j1) = (c2,v2,j2))).\n      rewrite decide_True in H. inversion H.\n      assumption. rewrite decide_False in H.\n      destruct (decide (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    simpl in H_sender.\n    unfold equivocating_messages.\n    destruct (decide ((c1,v1,j1) = (c2,v2,j2))).\n    contradiction; try assumption.\n    rewrite decide_False; try assumption.\n    destruct (decide (v1 = v2)); try contradiction.\n    simpl in *.\n    apply andb_true_iff.\n    split\n    ; apply negb_true_iff\n    ; rewrite mirror_reflect_curry; try exact H_in1; try exact H_in2\n    ;  intros; split; apply (in_function decide_eq).\nQed.\n\nLemma equivocating_messages_correct'\n  : forall (msg1 msg2 : message C V hash),\n    equivocating_messages msg1 msg2 = false <-> ~ equivocating_messages_prop msg1 msg2.\nProof.\n  intros.\n  apply mirror_reflect_curry.\n  exact equivocating_messages_correct.\nQed.\n\nLemma equivocating_messages_comm\n  : forall msg1 msg2 : message C V hash,\n  equivocating_messages msg1 msg2 = equivocating_messages msg2 msg1.\nProof.\n  intros [(c1, v1) sigma1] [(c2, v2) sigma2].\n  unfold equivocating_messages.\n  destruct (decide ((c1, v1, sigma1) = (c2, v2, sigma2))).\n  rewrite decide_True.\n  rewrite decide_True. reflexivity.\n  symmetry; assumption.\n  assumption.\n  rewrite decide_False.\n  destruct (decide (v1 = v2)).\n  rewrite decide_False.\n  rewrite e. rewrite decide_True.\n  rewrite andb_comm. reflexivity. reflexivity.\n  intro Hnot; symmetry in Hnot; tauto.\n  rewrite decide_False.\n  rewrite decide_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  : forall msg1 msg2 : message C V hash,\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\nLemma non_equivocating_messages_sender\n  : forall msg1 msg2 : message C V hash,\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 decide_False.\n  - rewrite decide_False; try reflexivity. assumption.\n  - intro Heq. inversion Heq; subst; clear Heq. apply Hneq. reflexivity.\nQed.\n\nDefinition equivocating_in_state\n  (msg : message C V hash) (sigma : state C V hash) : bool\n  :=\n  existsb (equivocating_messages msg) sigma.\n\nDefinition equivocating_in_state_prop\n  (msg : message C V hash) (s : state C V hash) : Prop\n  :=\n  exists msg', In msg' s /\\ equivocating_messages_prop msg msg'.\n\nLemma equivocating_in_state_correct\n  : forall (msg : message C V hash) 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.\n    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  : forall (msg : message C V hash) 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  : forall sigma sigma',\n  incl sigma sigma' ->\n  forall msg,\n    equivocating_in_state_prop msg sigma ->\n    equivocating_in_state_prop msg sigma'.\nProof.\n  intros.\n  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  : forall msg sigma,\n  ~ In (sender msg) (set_map decide_eq sender sigma) ->\n  ~ equivocating_in_state_prop msg sigma.\nProof.\n  intros [(c, v) j] sigma Hnin. rewrite set_map_exists in Hnin. 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  (sigma : state C V hash) : set V\n  :=\n  set_map decide_eq sender (filter (fun msg => equivocating_in_state msg sigma) sigma).\n\nDefinition equivocating_senders_prop\n  (s : state C V hash) (lv : set V)\n  :=\n  forall v, In v lv <-> exists msg, In msg s /\\ sender msg = v /\\ equivocating_in_state_prop msg s.\n\nLemma equivocating_senders_correct\n  : forall s : state C V hash,\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  : forall sigma sigma' : state C V hash,\n  incl 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 hash=> equivocating_in_state msg sigma) sigma').\n  - apply filter_incl; assumption.\n  - apply filter_incl_fn. intro.\n    do 2 rewrite equivocating_in_state_correct.\n    apply equivocating_in_state_incl. assumption.\nQed.\n\nDefinition reach\n  (s1 s2 : state C V hash)\n  :=\n  incl s1 s2.\n\nLemma reach_refl\n  : forall s : state C V hash,\n  reach s s.\nProof. apply incl_refl. Qed.\n\nLemma reach_trans\n  : forall s1 s2 s3 : state C V hash,\n  reach s1 s2 -> reach s2 s3 -> reach s1 s3.\nProof. apply incl_tran. Qed.\n\nLemma reach_union\n  : forall s1 s2 : state C V hash,\n  reach s1 (state_union s1 s2).\nProof. intros s1 s2 x H_in; apply set_union_iff; left; assumption. Qed.\n\nLemma reach_morphism\n  : forall s1 s2 s3 : state C V hash,\n  reach s1 s2 -> state_eq s2 s3 -> reach s1 s3.\nProof. intros s1 s2 s3 H_reach H_eq x H_in. spec H_reach x H_in.\n       destruct H_eq as [H_eq _]. spec H_eq x H_reach; assumption.\nQed.\n\nDefinition fault_weight_state\n  (sigma : state C V hash) : R\n  :=\n  sum_weights (equivocating_senders sigma).\n\nLemma fault_weight_state_incl\n  : forall sigma sigma' : state C V hash,\n  incl 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  apply equivocating_senders_incl. assumption.\nQed.\n\n(* The not overweight condition *)\nDefinition not_heavy\n  (sigma : state C V hash) : Prop\n  :=\n  (fault_weight_state sigma <= proj1_sig threshold)%R.\n\nLemma not_heavy_subset\n  : forall sigma sigma' : state C V hash,\n  incl sigma sigma' ->\n  not_heavy sigma' ->\n  not_heavy sigma.\nProof.\n  unfold not_heavy.\n  intros.\n  apply Rle_trans with (fault_weight_state sigma'); try assumption.\n  apply fault_weight_state_incl; assumption.\nQed.\n\nLemma not_heavy_set_eq\n  : forall sigma sigma' : state C V hash,\n  set_eq sigma sigma' ->\n  not_heavy sigma ->\n  not_heavy sigma'.\nProof.\n  intros. destruct H.\n  apply (not_heavy_subset _ _ H1 H0).\nQed.\n\nInductive protocol_state\n  : state C V hash -> Prop\n  :=\n  | protocol_state_nil : protocol_state (state0 C V hash)\n  | protocol_state_cons : forall (j : state C V hash),\n    protocol_state j ->\n    forall (c : C),\n      valid_estimate c j ->\n      forall (v : V) (s : state C V hash),\n        In (c, v, hash_state j) s ->\n        protocol_state (set_remove decide_eq (c, v, hash_state j) s) ->\n        NoDup s ->\n        not_heavy s ->\n        protocol_state s.\n\n\nLemma protocol_state_nodup\n  : forall sigma : state C V hash,\n  protocol_state sigma ->\n  NoDup sigma.\nProof.\n  intros. inversion H; subst.\n  - constructor.\n  - assumption.\nQed.\n\nLemma not_extx_in_x\n  : forall c v (s s' : state C V hash),\n    protocol_state s ->\n    protocol_state s' ->\n    incl s' s ->\n    ~ In (hash_message (c, v, hash_state s)) (hash_state s').\nProof.\n  intros c v s s' PS PS'. induction PS'; intros Hincl Hin; apply hash_state_in in Hin.\n  - unfold state0 in Hin. inversion Hin.\n  - apply (set_remove_in_iff (c, v, hash_state s) (c0, v0, hash_state j) s0 H1 H0) in Hin.\n    destruct Hin as [Heq | Hin].\n    + inversion Heq; subst; clear Heq. apply hash_state_injective in H6. apply IHPS'1; try apply H6.\n      apply hash_state_in. apply Hincl in H0. apply H6.\n      assert (hash_state s = hash_state j) by (apply hash_state_injective; assumption).\n      rewrite H3. assumption.\n    + apply IHPS'2; try (apply hash_state_in; assumption).\n      apply incl_tran with s0; try assumption.\n      intros h Hin_h. apply set_remove_1 in Hin_h. assumption.\nQed.\n\nLemma not_in_self\n  : forall (s : state C V hash),\n    protocol_state s ->\n    forall (v : V),\n    ~ In (get_estimate s, v, hash_state s) s.\nProof.\n  intros s about_s v H_absurd.\n  assert (H_useful := not_extx_in_x (get_estimate s) v s s about_s about_s (incl_refl s)).\n  apply (in_map hash_message s (get_estimate s, v, hash_state s)) in H_absurd.\n  assert (H_eq := justification_set_eq (map hash_message s)).\n  destruct H_eq as [H_eq _].\n  spec H_eq (hash_message (get_estimate s, v, hash_state s)) H_absurd.\n  contradiction.\nQed.\n\nLemma not_in_self_relaxed\n  : forall (s : state C V hash),\n    protocol_state s ->\n    forall (c : C) (v : V),\n    ~ In (c, v, hash_state s) s.\nProof.\n  intros s about_s c v H_absurd.\n  assert (H_useful := not_extx_in_x c v s s about_s about_s (incl_refl s)).\n  apply (in_map hash_message s (c, v, hash_state s)) in H_absurd.\n  assert (H_eq := justification_set_eq (map hash_message s)).\n  destruct H_eq as [H_eq _].\n  spec H_eq (hash_message (c, v, hash_state s)) H_absurd.\n  contradiction.\nQed.\n\nLemma set_eq_protocol_state\n  : forall sigma : state C V hash,\n  protocol_state sigma ->\n  forall sigma',\n    set_eq sigma sigma' ->\n    NoDup sigma' ->\n    protocol_state sigma'.\nProof.\n  intros sigma H'.\n  induction H'; intros.\n  - destruct H. unfold state0 in *.\n    apply incl_empty in H1; subst. constructor.\n  - apply (set_eq_remove (c, v, hash_state j)) in H3 as Hset_eq; try assumption.\n    apply IHH'2 in Hset_eq.\n    apply (protocol_state_cons j H'1 c H v sigma'); try assumption.\n    + destruct H3. now apply (H3 (c, v, hash_state j)).\n    + apply (not_heavy_set_eq _ _ H3 H2).\n    + now apply set_remove_nodup.\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  : forall (msg : message C V hash) sigma1 c v,\n  In msg sigma1 ->\n  equivocating_messages msg (c, v, hash_state sigma1) = false.\nProof.\n  intros [(c0, v0) sigma']; intros.\n  unfold equivocating_messages.\n  destruct (decide ((c0, v0, sigma') = (c, v, hash_state sigma1))).\n  - (* In the case that these two messages are equal, they cannot be equivocating *)\n    now rewrite decide_True.\n  - (* In the case that these messages are not equal, *)\n    rewrite decide_False.\n    (* When their senders are equal *)\n    destruct (decide (v0 = v)).\n    + subst.\n      apply hash_state_in in H.\n      apply in_correct in H.\n      rewrite H.\n      tauto.\n    + reflexivity.\n    + assumption.\nQed.\n\nLemma equivocating_in_state_extend\n  :  forall c v (s : state C V hash),\n    ~ equivocating_in_state_prop (c, v, hash_state s) s.\nProof.\n  intros c v s H_absurd.\n  destruct H_absurd as [msg [H_in H_equiv]].\n  assert (H_useful := non_equivocating_messages_extend msg s c v H_in).\n  rewrite equivocating_messages_correct' in H_useful.\n  rewrite equivocating_messages_prop_swap in H_equiv.\n  contradiction.\nQed.\n\nLemma equivocating_senders_extend\n  : forall (sigma : state C V hash) c v,\n  equivocating_senders ((c, v, hash_state sigma) :: sigma) = equivocating_senders sigma.\nProof.\n  unfold equivocating_senders. intros.\n  (* Why doesn't the suff tactic work *)\n  simpl.\n  assert (H_irrefl : equivocating_messages (c, v, hash_state sigma) (c, v, hash_state sigma) = false).\n  { apply equivocating_messages_correct'.\n    intro H_absurd.\n    destruct H_absurd as [H_eq _].\n    contradiction. }\n  rewrite H_irrefl.\n  simpl.\n  assert (H_useful := equivocating_in_state_correct' (c,v,hash_state sigma) sigma).\n  assert (H_useful' := equivocating_in_state_extend c v sigma).\n  apply H_useful in H_useful'.\n  rewrite H_useful'.\n  f_equal.\n  apply filter_eq_fn.\n  intros.\n  split; intros.\n  - apply orb_prop in H0.\n    destruct H0.\n    exfalso.\n    assert (H_goal := non_equivocating_messages_extend a sigma c v H).\n    firstorder.\n    apply (H1 a). split; try assumption.\n\n    rewrite equivocating_messages_prop_swap.\n    apply equivocating_messages_correct.\n    assumption. assumption.\n  - apply orb_true_intro. tauto.\nQed.\n\nLemma protocol_state_not_heavy\n  : forall sigma : state C V hash,\n  protocol_state sigma ->\n  not_heavy sigma.\nProof.\n  intros. inversion H.\n  - unfold not_heavy. unfold fault_weight_state. simpl.\n    apply Rge_le. destruct threshold; easy.\n  - assumption.\nQed.\n\n(* Recording entire histories preserves protocol state-ness *)\nLemma copy_protocol_state\n  : forall s : state C V hash,\n  protocol_state s ->\n  forall v,\n    protocol_state ((get_estimate s, v, hash_state s) :: s).\nProof.\n  intros s Hps v.\n  apply protocol_state_cons with s (get_estimate s) v; try assumption; try apply get_estimate_correct; try apply incl_refl.\n  apply in_eq.\n  rewrite set_remove_first; easy.\n  apply NoDup_cons.\n  now apply not_in_self.\n  now apply protocol_state_nodup.\n  apply not_heavy_subset with ((get_estimate s,v,hash_state s) :: s).\n  - apply incl_refl.\n  - unfold not_heavy. unfold fault_weight_state.\n    rewrite equivocating_senders_extend.\n    apply protocol_state_not_heavy in Hps. assumption.\nQed.\n\nLemma about_prot_state\n  : forall (s1 s2 : state C V hash),\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 sig1 sig2 Hps1 Hps2.\n  induction Hps2; intros.\n  - simpl. assumption.\n  - clear IHHps2_1.\n    assert (protocol_state (state_union sig1 (set_remove decide_eq (c, v, hash_state j) s))).\n    { apply IHHps2_2.\n      apply not_heavy_subset with (state_union sig1 s); try assumption.\n      intro msg; intro Hin.\n      apply set_union_intro.\n      unfold state_union in Hin; apply set_union_elim in Hin.\n      destruct Hin; try (left; assumption).\n      right. apply (set_remove_1 _ _ _ _ H4).\n    }\n    clear IHHps2_2.\n    apply protocol_state_nodup in Hps1 as Hnodups1.\n    assert (HnodupUs1s' := H1).\n    apply (set_union_nodup decide_eq Hnodups1) in HnodupUs1s'.\n    destruct (in_dec decide_eq (c, v, hash_state j) sig1).\n    + apply set_eq_protocol_state with (state_union sig1 (set_remove decide_eq (c, v, hash_state j) s))\n      ; try assumption.\n      apply set_eq_remove_union_in; assumption.\n    + eapply (protocol_state_cons j Hps2_1 c H v); try assumption.\n      * apply set_union_iff. right. assumption.\n      * apply (set_remove_nodup decide_eq (c, v, hash_state j)) in HnodupUs1s' as Hnoduprem.\n        apply set_eq_protocol_state with (state_union sig1 (set_remove decide_eq (c, v, hash_state j) s))\n        ; try assumption.\n        apply set_eq_remove_union_not_in; assumption.\nQed.\n\nLemma equivocation_weight_compat\n  : forall s1 s2 : state C V hash,\n  (fault_weight_state s1 <= fault_weight_state (state_union s2 s1))%R.\nProof.\n  intros.\n  apply fault_weight_state_incl.\n  intros msg H_in.\n  apply set_union_iff. tauto.\nQed.\n\nDefinition LightNode_seteq\n  : CBC_protocol_eq\n  :=\n  {| consensus_values := C;\n    about_consensus_values := HscC;\n    validators := V;\n    about_validators := HscV;\n    t := threshold;\n    suff_val := reachable_threshold;\n    E := estimator;\n    prot_state := protocol_state;\n    Protocol.state := state C V hash;\n    Protocol.about_state := about_state;\n    Protocol.state0 := state0 C V hash;\n    Protocol.state_eq := set_eq;\n    Protocol.state_union := state_union;\n    Protocol.state_union_comm := state_union_comm;\n    Protocol.reach := reach;\n    Protocol.reach_refl := reach_refl;\n    Protocol.reach_trans := reach_trans;\n    Protocol.reach_union := reach_union;\n    Protocol.reach_morphism := reach_morphism;\n    Protocol.estimator_total := Decisions.estimator_total;\n    about_state0 := protocol_state_nil;\n    equivocation_weight := fault_weight_state;\n    Protocol.equivocation_weight_compat := equivocation_weight_compat;\n    Protocol.about_prot_state := about_prot_state;\n  |}.\nEnd LightNode_protocol_eq.\n\nDefinition pstate_light\n  (C V hash : Type)\n  {HscH : StrictlyComparable hash}\n  {HscC : StrictlyComparable C}\n  {HscV : StrictlyComparable V}\n  {Hmh : MessageHash (message C V hash) hash}\n  {Hmhi : InjectiveMessageHash (message C V hash) hash Hmh}\n  {HmV : Measurable V}\n  {Hrt : ReachableThreshold V}\n  {He : Estimator (state C V hash) C}\n  : Type\n  :=\n  {s : state C V hash | protocol_state s}.\n\nDefinition pstate_light_proj1\n  {C V hash : Type}\n  {HscH : StrictlyComparable hash}\n  {HscC : StrictlyComparable C}\n  {HscV : StrictlyComparable V}\n  {Hmh : MessageHash (message C V hash) hash}\n  {Hmhi : InjectiveMessageHash (message C V hash) hash Hmh}\n  {HmV : Measurable V}\n  {Hrt : ReachableThreshold V}\n  {He : Estimator (state C V hash) C}\n  (p : pstate_light C V hash) : state C V hash\n  :=\n  proj1_sig p.\n\nCoercion pstate_light_proj1 : pstate_light>-> state.\n\nSection LightNode.\n\nContext\n  {C V hash : Type}\n  {HscH : StrictlyComparable hash}\n  {HscC : StrictlyComparable C}\n  {HscV : StrictlyComparable V}\n  {Hmh : MessageHash (message C V hash) hash}\n  {Hmhi : InjectiveMessageHash (message C V hash) hash Hmh}\n  {HmV : Measurable V}\n  {Hrt : ReachableThreshold V}\n  {He : Estimator (state C V hash) C}\n  (eq_H := @strictly_comparable_eq_dec _ HscH)\n  (eq_V := @strictly_comparable_eq_dec _ HscV)\n  .\n\nExisting Instance eq_H.\nExisting Instance eq_V.\nExisting Instance eq_message.\nExisting Instance message_type.\nExisting Instance about_state.\n\nDefinition pstate_light_rel\n  : pstate_light C V hash -> pstate_light C V hash -> Prop :=\n  fun p1 p2 => incl (pstate_light_proj1 p1) (pstate_light_proj1 p2).\n\nDefinition non_trivial_pstate_light\n  (P : pstate_light C V hash -> Prop) :=\n  (exists (s1 : pstate_light C V hash), forall (s : pstate_light C V hash), pstate_light_rel s1 s -> P s)\n  /\\\n  (exists (s2 : pstate_light C V hash), forall (s : pstate_light C V hash), pstate_light_rel s2 s -> (P s -> False)).\n\n\nLemma not_heavy_singleton\n  : forall msg : message C V hash,\n  not_heavy [msg].\nProof.\n  intros [(c, v) j].\n  unfold not_heavy.\n  unfold fault_weight_state.\n  unfold equivocating_senders.\n  simpl. unfold equivocating_messages.\n  rewrite decide_True; try reflexivity. simpl.\n  apply Rge_le. destruct threshold. easy.\nQed.\n\nLemma protocol_state_singleton\n  : forall c v (j : state C V hash),\n  protocol_state j ->\n  valid_estimate c j ->\n  protocol_state [(c, v, hash_state j)].\nProof.\n  intros.\n  apply protocol_state_cons with j c v; try assumption.\n  - left. reflexivity.\n  - simpl. rewrite decide_True; constructor.\n  - constructor; try constructor. apply in_nil.\n  - apply not_heavy_singleton.\nQed.\n\n(* This is a critical property of the light node protocol *)\n(* Any duplicate-free subset of a protocol state (as list message) is itself a protocol state *)\nLemma protocol_state_incl\n  : forall (s : state C V hash),\n    protocol_state s ->\n    forall (s' : state C V hash),\n      NoDup s' ->\n      incl s' s ->\n      protocol_state s'.\nProof.\n  intros s about_s.\n  induction about_s; intros s' H_nodup H_incl.\n  - destruct s'.\n    + apply protocol_state_nil.\n    + spec H_incl m (in_eq m s'). inversion H_incl.\n  - destruct (classic (In (c,v,hash_state j) s')).\n    + spec IHabout_s2 (set_remove decide_eq (c,v,hash_state j) s').\n      apply protocol_state_cons with j c v; try assumption.\n      2 : now apply not_heavy_subset with s.\n      apply IHabout_s2.\n      now apply set_remove_nodup.\n      intros msg H_in.\n      destruct (classic (msg = (c,v,hash_state j))).\n      * subst.\n        assert (H_contra := set_remove_elim (c,v,hash_state j) s').\n        spec H_contra H_nodup.\n        contradiction.\n      * spec H_incl msg.\n        spec H_incl.\n        assert (H_useful := set_remove_iff decide_eq msg (c,v,hash_state j)).\n        spec H_useful s' H_nodup.\n        rewrite H_useful in H_in.\n        tauto.\n        apply set_remove_iff; try tauto.\n    + spec IHabout_s2 s'.\n      apply IHabout_s2.\n      assumption.\n      intros msg H_in.\n      assert (msg <> (c,v,hash_state j)).\n      { intros H_absurd. subst.\n        spec H_incl (c,v,hash_state j) H_in.\n        contradiction. }\n      apply set_remove_iff; try assumption.\n      split. 2 : assumption.\n      now apply (H_incl msg H_in).\nQed.\n\n(* We can now always construct an equivocation by splitting any protocol state into duplicate-free subsets of messages *)\nLemma binary_justification_nodup\n  : forall (vs : list V) (c1 c2 : C) (j1 j2 : state C V hash),\n  ~ set_eq j1 j2 ->\n  NoDup vs ->\n  NoDup (flat_map (fun v => [(c1, v, hash_state j1); (c2, v, hash_state j2)]) vs).\nProof.\n  intros.\n  induction vs.\n  - simpl. constructor.\n  - simpl.\n    apply NoDup_cons_iff in H0.\n    destruct H0 as [Hnin Hnodup]. constructor.\n    + intro H0. destruct H0.\n      * apply H. inversion H0; subst; clear H0.\n        apply hash_state_injective in H3.\n        now apply set_eq_comm.\n      * apply Hnin. apply in_flat_map in H0.\n        destruct H0 as [x [Hinx Hin]].\n        destruct Hin as [Heq | [Heq | Heq]]; inversion Heq; subst; assumption.\n    + apply IHvs in Hnodup. apply NoDup_cons_iff; split; try assumption. intro.\n      apply Hnin. apply in_flat_map in H0. destruct H0 as [x [Hinx Hin]].\n      destruct Hin as [Heq | [Heq | Heq]]; inversion Heq; subst; assumption.\nQed.\n\nLemma binary_justification_protocol_state\n  : forall vs c1 j1 c2 (j2 : state C V hash),\n    protocol_state j1 ->\n    protocol_state j2 ->\n    ~ set_eq j1 j2 ->\n    valid_estimate c1 j1 ->\n    valid_estimate c2 j2 ->\n    NoDup vs ->\n    not_heavy (flat_map (fun v => [(c1, v, hash_state j1); (c2, v, hash_state j2)]) vs) ->\n    protocol_state (flat_map (fun v => [(c1, v, hash_state j1); (c2, v, hash_state j2)]) vs).\nProof.\n  intros.\n  induction vs.\n  - simpl. constructor.\n  - apply NoDup_cons_iff in H4.\n    destruct H4 as [Hanin Hnodup].\n    simpl. apply protocol_state_cons with j1 c1 a; try assumption.\n    + left; reflexivity.\n    + simpl. rewrite decide_True; try reflexivity.\n      apply protocol_state_cons with j2 c2 a; try assumption.\n      * left; reflexivity.\n      * simpl. rewrite decide_True; try reflexivity.\n        apply IHvs; try assumption.\n        apply not_heavy_subset with (flat_map (fun v : V => [(c1, v, hash_state j1); (c2, v, hash_state j2)]) (a :: vs))\n        ; try assumption.\n        intros x Hin. apply in_flat_map in Hin. apply in_flat_map.\n        destruct Hin as [v [Hinv Hinx]].\n        exists v. split; try assumption. right. assumption.\n      * apply NoDup_cons_iff. split; try apply binary_justification_nodup; try assumption.\n        intro. apply Hanin.\n        apply in_flat_map in H4. destruct H4 as [x [Hinx Hin]].\n        destruct Hin as [Heq | [Heq | Heq]]; inversion Heq; subst; assumption.\n      * apply not_heavy_subset with (flat_map (fun v : V => [(c1, v, hash_state j1); (c2, v, hash_state j2)]) (a :: vs))\n        ; try assumption.\n        intros x Hin. apply in_flat_map.\n        { destruct Hin as [Heq | Hin].\n          - subst. exists a. split; try (left; reflexivity). right. left. reflexivity.\n          - apply in_flat_map in Hin. destruct Hin as [v [Hinv Hin]].\n            exists v. split; try assumption. right. assumption.\n        }\n    + apply NoDup_cons_iff. split.\n      * intro.\n        { destruct H4 as [Heq | Hin].\n          - apply H1. inversion Heq; subst; clear Heq.\n            apply hash_state_injective in H7.\n            now apply set_eq_comm.\n          - apply Hanin.\n            apply in_flat_map in Hin.\n            destruct Hin as [v [Hinv Hin]].\n            destruct Hin as [Heq | [Heq | Heq]]; inversion Heq; subst; assumption.\n        }\n      * apply NoDup_cons_iff.\n        { split.\n          - intro. apply Hanin.\n            apply in_flat_map in H4. destruct H4 as [v [Hinv Hin]].\n            destruct Hin as [Heq | [Heq | Heq]]; inversion Heq; subst; assumption.\n          - apply binary_justification_nodup; assumption.\n        }\nQed.\n\nLemma fault_weight_max\n  : forall sigma : state C V hash,\n  (fault_weight_state sigma <= sum_weights (set_map decide_eq sender sigma))%R.\nProof.\n  intros.\n  apply sum_weights_incl; try apply set_map_nodup.\n  unfold equivocating_senders.\n  apply set_map_incl.\n  intros x Hin.\n  apply filter_In in Hin. destruct Hin; assumption.\nQed.\n\n\nLemma exist_equivocating_messages\n  : forall vs,\n  vs <> nil ->\n  exists (j1 : state C V hash), exists j2, protocol_state j1 /\\ protocol_state j2 /\\ ~ set_eq j1 j2 /\\\n    exists c1, exists c2,\n      valid_estimate c1 j1 /\\ valid_estimate c2 j2 /\\\n      (forall v,\n        In v vs  ->\n          equivocating_messages (c1, v, hash_state j1) (c2, v, hash_state j2) = true).\nProof.\n  destruct (Decisions.estimator_total []) as [c Hc].\n  intros.\n  destruct vs; try (exfalso; apply H; reflexivity); clear H.\n  destruct (Decisions.estimator_total [(c, v, [])]) as [c' Hc'].\n  destruct (Decisions.estimator_total [(c', v, hash_state [(c, v, [])])]) as [c'' Hc''].\n  exists []. exists [(c', v, hash_state [(c, v, [])])]. repeat split; try constructor.\n  - apply (protocol_state_singleton c' v [(c, v, [])]) in Hc'; try constructor; try assumption.\n    apply (protocol_state_singleton c v []) in Hc; try constructor; assumption.\n  - intro. destruct H. apply incl_empty in H0. inversion H0.\n  - exists c. exists c''. repeat split; try assumption.\n    intros. unfold equivocating_messages. rewrite decide_False.\n    + rewrite decide_True; try reflexivity.\n      apply andb_true_iff. split; apply  negb_true_iff; apply in_correct'.\n      * unfold hash_state; simpl.\n        intro Hh. destruct Hh as [Hh | Hf]; try contradiction Hf.\n        apply hash_message_injective in Hh. discriminate Hh.\n      * simpl. intro Hf. contradiction Hf.\n    + intro. discriminate H0.\nQed.\n\nTheorem non_triviality_decisions_on_properties_of_protocol_states\n  : exists (p : pstate_light C V hash -> Prop), non_trivial_pstate_light p.\nProof.\n  (* Get a pivotal validator and its complement set *)\n  destruct exists_pivotal_validator as [v [vs [Hnodup [Hvnin [Hlte Hgt]]]]].\n  (* Get a pair of messages in which that validator is equivocating *)\n  destruct (exist_equivocating_messages (v :: vs)) as [j1 [j2 [Hj1ps [Hj2ps [Hneq12 [c1 [c2 [Hval1 [Hval2 Heqv]]]]]]]]].\n  intro H; inversion H.\n  (* The property is that of containing one equivocating partner message from this pivotal validator *)\n  exists (fun (p : pstate_light C V hash) => In (c1,v,hash_state j1) (proj1_sig p)).\n  split.\n  - (* The first state which does satisfy this property is the state containing just that one message *)\n    exists (exist protocol_state [(c1,v,hash_state j1)] (protocol_state_singleton c1 v j1 Hj1ps Hval1)).\n    intros sigma H.\n    apply H. left; reflexivity.\n  - (* The second state which does not satisfy the property is the state containing the message's equivocation partner, as well as messages from all the other validators in the complement set *)\n    assert (H_prot : protocol_state ((c2, v, hash_state j2) :: flat_map (fun v => [(c1, v, hash_state j1); (c2, v, hash_state j2)]) vs)).\n    { apply protocol_state_cons with j2 c2 v; try assumption.\n      * (* Proving that the message partner is in the new state *)\n        left; reflexivity.\n      * (* Proving that the new state without the message partner is a protocol state *)\n        simpl. rewrite decide_True; try reflexivity.\n        (* This state is a protocol state if it's not too heavy *)\n        apply binary_justification_protocol_state; try assumption.\n        unfold not_heavy, fault_weight_state.\n        apply Rle_trans with (sum_weights (set_map decide_eq sender (flat_map (fun v0 : V => [(c1, v0, hash_state j1); (c2, v0, hash_state j2)]) vs))); try apply fault_weight_max.\n        apply Rle_trans with (sum_weights vs); try assumption.\n        apply sum_weights_incl; try assumption; try apply set_map_nodup.\n        (* x is some arbitrary validator in vs *)\n        intros x Hin.\n        (* x has sent some message in the tl of the state *)\n        apply set_map_exists in Hin.\n        destruct Hin as [[(mc, mv) mj] [Hin Hveq]].\n        simpl in Hveq. subst.\n        apply in_flat_map in Hin.\n        destruct Hin as [mv [Hinv Hinm]].\n        destruct Hinm as [Hinm | [Hinm | Hinm]]\n        ; inversion Hinm; subst; assumption.\n      * (* Proving that the new state is duplicate-free *)\n        constructor; try (apply binary_justification_nodup; assumption).\n        rewrite in_flat_map. intro.\n        destruct H as [v'' [Hinv Hinm]].\n        apply Hvnin.\n        destruct Hinm as [Hinm | [Hinm | Hinm]]\n        ; inversion Hinm; subst; assumption.\n      * (* Proving that the new state is not *)\n        unfold not_heavy, fault_weight_state.\n        apply Rle_trans with (sum_weights vs); try assumption.\n        apply sum_weights_incl; try assumption; try apply set_map_nodup.\n        unfold equivocating_senders.\n        intros v0 Hinv0.\n        apply set_map_exists in Hinv0.\n        destruct Hinv0 as [[(c0, v0') j0] [Hin Heq]].\n        simpl in Heq; subst.\n        apply filter_In in Hin.\n        destruct Hin as [Hin Hequiv].\n        destruct Hin as [Heq | Hin]\n        ; try (\n          apply in_flat_map in Hin\n          ; destruct Hin as [v0' [Hinv0 [Hin | [Hin | Hin]]]]\n          ; inversion Hin; subst; clear Hin; assumption\n        ).\n        inversion Heq; subst; clear Heq. simpl in Hequiv.\n        unfold equivocating_messages in Hequiv.\n        rewrite decide_True in Hequiv; try reflexivity.\n        simpl in Hequiv.\n        apply existsb_exists in Hequiv.\n        destruct Hequiv as [[(mc, mv) mj] [Hin Hequiv]].\n        apply in_flat_map in Hin.\n        unfold equivocating_messages in Hequiv.\n        destruct (decide ((c0, v0, hash_state j2) = (mc, mv, mj)))\n        ; try (rewrite decide_True in Hequiv; try assumption; discriminate).\n        rewrite decide_False in Hequiv; try assumption.\n        destruct (decide (v0 = mv)); try discriminate; subst.\n        destruct Hin as [v0' [Hinv0 [Hin | [Hin | Hin]]]]\n        ; inversion Hin; subst; clear Hin; assumption. }\n    exists (exist protocol_state ((c2, v, hash_state j2)  :: flat_map (fun v : V => [(c1, v, hash_state j1); (c2, v, hash_state j2)]) vs) H_prot).\n    intros sigma Hincl Hin.\n    destruct sigma as [sigma about_sigma].\n    assert (Hpssigma := about_sigma).\n    apply protocol_state_not_heavy in Hpssigma.\n    apply (not_heavy_subset ((c1, v, hash_state j1) :: ((c2, v, hash_state j2) :: flat_map (fun v : V => [(c1, v, hash_state j1); (c2, v, hash_state j2)]) vs))) in Hpssigma.\n    * unfold not_heavy in Hpssigma.\n      unfold fault_weight_state in Hpssigma.\n      assert (Heq : ((c1, v, hash_state j1)\n                       :: (c2, v, hash_state j2)\n                       :: flat_map (fun v : V => [(c1, v, hash_state j1); (c2, v, hash_state j2)]) vs)\n                    = flat_map (fun v : V => [(c1, v, hash_state j1); (c2, v, hash_state j2)]) (v :: vs))\n      by reflexivity.\n      rewrite Heq in Hpssigma.\n      apply (Rplus_gt_compat_r (Measurable.weight v)) in Hgt.\n      unfold Rminus in Hgt.\n      rewrite Rplus_assoc in Hgt.\n      rewrite Rplus_opp_l in Hgt.\n      rewrite Rplus_0_r in Hgt.\n      apply Rgt_lt in Hgt.\n      apply (Rle_lt_trans _ _ _ Hpssigma) in Hgt.\n      { apply (Rle_lt_trans (sum_weights (v :: vs))) in Hgt.\n        - rewrite Rplus_comm in Hgt. simpl in Hgt.\n          apply Rlt_irrefl with (Measurable.weight v + sum_weights vs)%R.\n          assumption.\n        - apply sum_weights_incl.\n          + constructor; assumption.\n          + apply set_map_nodup.\n          + intros v0 Hin0. unfold equivocating_senders.\n            apply set_map_exists. exists (c1, v0, hash_state j1).\n            split; try reflexivity.\n            apply filter_In.\n            split.\n            * apply in_flat_map.\n              exists v0. split; try assumption.\n              left; reflexivity.\n            * apply existsb_exists. exists (c2, v0, hash_state j2).\n              split; try (apply Heqv; assumption).\n              apply in_flat_map.\n              exists v0. split; try assumption. right; left; reflexivity.\n      }\n    * intros msg Hinm.\n      destruct Hinm as [Heq | Hinm]; subst; try assumption.\n      apply Hincl. assumption.\nQed.\n\nTheorem no_local_confluence_prot_state_light\n  : exists (a a1 a2 : pstate_light C V hash),\n        pstate_light_rel a a1 /\\ pstate_light_rel a a2 /\\\n        ~ exists (a' : pstate_light C V hash), pstate_light_rel a1 a' /\\ pstate_light_rel a2 a'.\nProof.\n  assert (H_useful := non_triviality_decisions_on_properties_of_protocol_states).\n  destruct H_useful as [P [[ps1 about_ps1] [ps2 about_ps2]]].\n  exists (exist protocol_state (state0 C V hash) protocol_state_nil).\n  exists ps1, ps2. repeat split; try (red; simpl; easy).\n  intro Habsurd. destruct Habsurd as [s [Hs1 Hs2]].\n  spec about_ps1 s Hs1.\n  spec about_ps2 s Hs2. contradiction.\nQed.\n\nLemma pstate_light_eq_dec\n  : forall (p1 p2 : pstate_light C V hash), {p1 = p2} + {p1 <> p2}.\nProof.\n  intros p1 p2.\n  apply sigify_eq_dec.\nQed.\n\nLemma pstate_light_inhabited\n  : exists (p1 : pstate_light C V hash), True.\nProof. now exists (exist protocol_state (state0 C V hash) protocol_state_nil). Qed.\n\nLemma pstate_light_rel_refl\n  : Reflexive pstate_light_rel.\nProof.\n  red. intro p.\n  destruct p as [p about_p].\n  red. simpl. easy. Qed.\n\nLemma pstate_light_rel_trans\n  : Transitive pstate_light_rel.\nProof.\n  red; intros p1 p2 p3 H_12 H_23.\n  destruct p1 as [p1 about_p1];\n    destruct p2 as [p2 about_p2];\n    destruct p3 as [p3 about_p3];\n    simpl in *.\n  unfold pstate_rel in *; simpl in *.\n  now eapply incl_tran with p2.\nQed.\n\nInstance level0_light\n  : PartialOrder (pstate_light C V hash) :=\n  { A_eq_dec := pstate_light_eq_dec;\n    A_inhabited := pstate_light_inhabited;\n    A_rel := pstate_light_rel;\n    A_rel_refl := pstate_light_rel_refl;\n    A_rel_trans := pstate_light_rel_trans;\n  }.\n\nInstance level1_light\n  : PartialOrderNonLCish (pstate_light C V hash) :=\n  { no_local_confluence_ish := no_local_confluence_prot_state_light; }.\n\n(** Strong non-triviality **)\n(* Defining reachablity in terms of message sending *)\nDefinition in_future\n  (s1 s2 : state C V hash)\n  :=\n  incl s1 s2.\n\nDefinition next_future\n  (s1 s2 : state C V hash) :=\n  exists (msg : message C V hash), set_eq (set_add decide_eq msg s1) s2.\n\nDefinition in_past\n  (s1 s2 : state C V hash)\n  :=\n  incl s2 s1.\n\nDefinition no_common_future\n  (s1 s2 : pstate_light C V hash) :=\n  forall (s : pstate_light C V hash), in_future s1 s /\\ in_future s2 s -> False.\n\nDefinition yes_common_future\n  (s1 s2 : pstate_light C V hash)\n  :=\n  exists (s : pstate_light C V hash), in_future s1 s /\\ in_future s2 s.\n\nDefinition strong_nontriviality\n  :=\n  (* For every state, there exists a state *)\n  forall (s1 : pstate_light C V hash),\n  exists (s2 : pstate_light C V hash),\n    (* That is reachable in one step *)\n    next_future s1 s2 /\\\n    (* And there exists a third state *)\n    exists (s3 : pstate_light C V hash),\n      (* Such that s1 and s3 share a common future *)\n      yes_common_future s1 s3\n      /\\\n      (* But s2 and s3 don't. *)\n      no_common_future s2 s3.\n\n(* Here's how to construct an equivocation *)\nLemma about_equivocating_messages\n  : forall j : state C V hash, protocol_state j ->\n       forall v v',\n         v <> v' ->\n         equivocating_messages_prop (get_estimate j, v, hash_state j)\n                                    (get_estimate ((get_estimate j, v', hash_state j) :: j), v, hash_state ((get_estimate j, v', hash_state j) :: j)).\nProof.\n  intros j about_j v v' H_neq.\n  repeat split.\n  - intros H_absurd.\n    inversion H_absurd.\n    apply hash_state_injective in H1.\n    inversion H1.\n    spec H2 (get_estimate j, v', hash_state j) (in_eq (get_estimate j, v', hash_state j) j).\n    now apply not_in_self in H2.\n  - simpl; intros H_absurd.\n    apply hash_state_in in H_absurd.\n    inversion H_absurd.\n    + inversion H. apply H_neq. easy.\n    + now apply not_in_self in H.\n  - intros H_absurd.\n    apply hash_state_in in H_absurd.\n    assert (H_useful := not_extx_in_x (get_estimate ((get_estimate j, v', hash_state j) :: j)) v ((get_estimate j, v', hash_state j) :: j) j).\n    spec H_useful.\n    { now apply copy_protocol_state.  }\n    spec H_useful about_j.\n    spec H_useful.\n    now apply incl_tl.\n    apply H_useful.\n    apply hash_state_in.\n    assumption.\nQed.\n\n(* Defining the state that adds this minimal equivocation *)\nDefinition next_equivocation_state\n  (j : state C V hash) (v v' : V) : state C V hash :=\n  (* One equivocation partner *)\n  (get_estimate j, v, hash_state j)\n    ::\n    (* Other equivocation partner *)\n    (get_estimate ((get_estimate j, v', hash_state j) :: j), v, hash_state ((get_estimate j, v', hash_state j) :: j))\n    ::\n    (* Preparatory state *)\n    (get_estimate j, v', hash_state j)\n    ::\n    (* Original state *)\n    j.\n\n(* Explicit instances of various incl results *)\nLemma next_equivocation_state_incl\n  : forall (j : state C V hash) (v v' : V),\n    incl j (next_equivocation_state j v v').\nProof.\n  intros j v v' msg H_in.\n  unfold next_equivocation_state.\n  do 3 right.\n  assumption.\nQed.\n\nLemma next_equivocation_state_keeps_messages\n  : forall (j : state C V hash) (v v' : V) (msg : message C V hash),\n    In msg j ->\n    In msg (next_equivocation_state j v v').\nProof.\n  apply next_equivocation_state_incl.\nQed.\n\nLemma next_equivocation_state_keeps_equivocators\n  : forall (j : state C V hash) (v v' v0 : V),\n    In v (equivocating_senders j) ->\n    In v (equivocating_senders (next_equivocation_state j v v')).\nProof.\n  intros.\n  assert (H_incl := @equivocating_senders_incl hash C V _ _ _ _).\n  spec H_incl j (next_equivocation_state j v v') (next_equivocation_state_incl j v v').\n  now apply H_incl.\nQed.\n\nLemma next_equivocation_state_keeps_equivocating_messages\n  : forall (j : state C V hash) (v v' : V) (msg : message C V hash),\n    equivocating_in_state_prop msg j ->\n    equivocating_in_state_prop msg (next_equivocation_state j v v').\nProof.\n  intros.\n  assert (H_incl := equivocating_in_state_incl).\n  spec H_incl j (next_equivocation_state j v v') (next_equivocation_state_incl j v v').\n  now apply H_incl.\nQed.\n\n\nLemma about_equivocating_messages_in_state_l\n  : forall (j : state C V hash) v v',\n    protocol_state j ->\n    v <> v' ->\n    equivocating_in_state_prop (get_estimate j, v, hash_state j)\n                               (next_equivocation_state j v v').\nProof.\n  intros j v v' about_j H_neq.\n  exists (get_estimate ((get_estimate j, v', hash_state j) :: j), v, hash_state ((get_estimate j, v', hash_state j) :: j)).\n  split.\n  right.\n  left. reflexivity.\n  now apply about_equivocating_messages.\nQed.\n\nLemma about_equivocating_messages_in_state_r\n  : forall (j : state C V hash) v v',\n    protocol_state j ->\n    v <> v' ->\n    equivocating_in_state_prop (get_estimate ((get_estimate j, v', hash_state j) :: j), v, hash_state ((get_estimate j, v', hash_state j) :: j))\n                               (next_equivocation_state j v v').\nProof.\n  intros j v v' about_j H_neq.\n  exists (get_estimate j, v, hash_state j).\n  split.\n  left. reflexivity.\n  apply equivocating_messages_prop_swap.\n  now apply about_equivocating_messages.\nQed.\n\nLemma about_equivocating_messages_add_equivocator\n  : forall (j : state C V hash) v v',\n    protocol_state j ->\n      v <> v' ->\n      In v (equivocating_senders (next_equivocation_state j v v')).\nProof.\n  intros j v v' about_j H_neq.\n  apply equivocating_senders_correct.\n  exists (get_estimate j, v, hash_state j).\n  split.\n  unfold next_equivocation_state.\n  left; tauto.\n  split. reflexivity.\n  now apply about_equivocating_messages_in_state_l.\nQed.\n\nLemma equivocating_senders_sorted_extend\n  : forall (s : state C V hash) v,\n    set_eq (equivocating_senders s)\n           (equivocating_senders ((get_estimate s, v, hash_state s) :: s)).\nProof.\n  intros.\n  assert (H_useful := equivocating_senders_extend s (get_estimate s) v).\n  rewrite <- H_useful.\n  eapply set_eq_tran.\n  apply set_eq_refl.\n  apply set_eq_refl.\nQed.\n\nLemma equivocating_senders_fault_weight_eq\n  : forall s1 s2 : state C V hash,\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.\n  assumption.\nQed.\n\nLemma add_weight_one\n  : forall (j : state C V hash) (v' : V),\n    fault_weight_state j =\n    fault_weight_state ((get_estimate j, v', hash_state j) :: j).\nProof.\n  intros.\n  apply equivocating_senders_fault_weight_eq.\n  apply equivocating_senders_sorted_extend.\nQed.\n\nLemma add_weight_two\n  : forall (j : state C V hash) (v v' : V),\n    (fault_weight_state\n      ((get_estimate ((get_estimate j, v', hash_state j) :: j), v, hash_state ((get_estimate j, v', hash_state j) :: j))\n         :: (get_estimate j, v', hash_state j) :: j)) =\n    fault_weight_state\n      ((get_estimate j, v', hash_state j) :: j)%R.\nProof.\n  intros.\n  apply equivocating_senders_fault_weight_eq.\n  apply set_eq_comm.\n  apply equivocating_senders_sorted_extend.\nQed.\n\nLemma add_already_equivocating_sender\n  : forall (s : state C V hash),\n    protocol_state s ->\n    forall (msg : message C V hash),\n      In (sender msg) (equivocating_senders s) ->\n        set_eq (equivocating_senders s)\n               (equivocating_senders (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.\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    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      destruct H_v_in.\n      subst.\n      contradiction.\n      assumption.\n      rewrite equivocating_in_state_correct.\n      exists msg'_partner.\n      split.  destruct H_msg'_partner_in.\n      subst. destruct H_equiv.\n      destruct H1. contradiction.\n      assumption. assumption.\nQed.\n\n\nLemma equivocating_sender_add_in_sorted_iff\n  : forall (s : state C V hash) (msg : message C V hash) (v : V),\n    In v (equivocating_senders (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     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       destruct H_msg_partner. subst. inversion H_equiv.\n       contradiction. tauto.\n     + destruct H_equiv as [msg'_partner [H_msg'_partner H_equiv]].\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.\n      right; assumption.\n      split. destruct H_equiv. symmetry; tauto.\n      exists msg. split. apply in_eq.\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      right; tauto.\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      try right; tauto.\n      assumption.\nQed.\n\nLemma add_equivocating_sender\n  : forall (s : state C V hash),\n    protocol_state s ->\n    forall (msg : message C V hash),\n      (exists msg',\n          In msg' s /\\\n          equivocating_messages_prop msg msg') ->\n      set_eq (equivocating_senders (msg :: s))\n             (set_add decide_eq (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 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 (H_ignore := set_add_ignore s msg H_msg_in).\n    simpl in *. rewrite <- H_ignore.\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 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      * inversion H0_in. contradiction.\n        clear H0_in.\n        rewrite H_ignore in *.\n        rewrite equivocating_in_state_correct in H0_equiv.\n        destruct H0_equiv as [msg0_partner [H0_equivl H0_equivr]].\n        inversion H0_equivl.\n        subst. left.\n        destruct H0_equivr. tauto.\n        right.\n        subst.\n        spec H_senders (sender msg0).\n        apply H_senders.\n        exists msg0_partner.\n        repeat split. assumption. red in H0_equivr; symmetry; tauto.\n        exists msg0. split; try assumption.\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        apply in_eq.\n        rewrite equivocating_in_state_correct.\n        exists msg'. split; try assumption.\n        right; rewrite H_ignore; assumption.\n      * rewrite set_add_iff in H_mem.\n        destruct H_mem.\n        contradiction. rewrite H_ignore in *.\n        assert (H_goal := equivocating_senders_incl s (msg :: s)). spec H_goal. right; now apply incl_refl.\n        now apply H_goal.\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 decide_eq (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_eq.\n           rewrite equivocating_in_state_correct.\n           red. exists msg'.\n           split.\n           right; assumption.\n           assumption. 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           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           right; assumption.\n           assumption.\nQed.\n\nLemma add_weight_three\n  : forall (j : state C V hash) (v v' : V),\n    protocol_state j ->\n    ~ In v (equivocating_senders j) ->\n    v <> v' ->\n    fault_weight_state (next_equivocation_state j v v') =\n    (fault_weight_state\n      ((get_estimate ((get_estimate j, v', hash_state j) :: j), v, hash_state ((get_estimate j, v', hash_state j) :: j)) ::\n         ((get_estimate j, v', hash_state j) :: j)) +\n     proj1_sig (Measurable.weight v))%R.\nProof.\n  intros j v v' about_j H_notin H_neq.\n  assert (H_useful := add_equivocating_sender).\n  spec H_useful ((get_estimate ((get_estimate j, v', hash_state j) :: j), v, hash_state ((get_estimate j, v', hash_state j) :: j)) :: ((get_estimate j, v', hash_state j) :: j)).\n  spec H_useful.\n  { apply protocol_state_cons with ((get_estimate j, v', hash_state j) :: j) (get_estimate ((get_estimate j, v', hash_state j) :: j)) v; try assumption; try apply get_estimate_correct.\n    apply copy_protocol_state; try assumption; try apply get_estimate_correct.\n    apply in_eq.\n    rewrite set_remove_first.\n    apply copy_protocol_state; try assumption; try apply get_estimate_correct.\n    reflexivity.\n    apply NoDup_cons.\n    apply not_in_self.\n    apply copy_protocol_state; try assumption.\n    apply NoDup_cons. now apply not_in_self.\n    now apply protocol_state_nodup in about_j.\n    red.\n    rewrite <- (add_weight_one ((get_estimate j, v', hash_state j) :: j) v).\n    apply protocol_state_not_heavy; try assumption .\n    apply copy_protocol_state. assumption. }\n  spec H_useful (get_estimate j, v, hash_state j).\n  spec H_useful.\n  exists (get_estimate ((get_estimate j, v', hash_state j) :: j), v, hash_state ((get_estimate j, v', hash_state j) :: j)).\n  split.\n  apply in_eq. apply about_equivocating_messages; try assumption.\n  (* Now. *)\n  assert (H_inter := senders_fault_weight_eq (equivocating_senders\n                  ((get_estimate j, v, hash_state j) ::\n                     ((get_estimate\n                           ((get_estimate j, v', hash_state j) :: j), v,\n                        hash_state ((get_estimate j, v', hash_state j) :: j)) ::\n                        ((get_estimate j, v', hash_state j) :: j)))) (set_add decide_eq (sender (get_estimate j, v, hash_state j))\n                  (equivocating_senders\n                     ((get_estimate\n                           ((get_estimate j, v', hash_state j) :: j), v,\n                        hash_state ((get_estimate j, v', hash_state j) :: j)) ::\n                        ((get_estimate j, v', hash_state j) :: j))))).\n  spec H_inter.\n  apply set_map_nodup.\n  spec H_inter.\n  apply set_add_nodup.\n  apply set_map_nodup.\n  spec H_inter H_useful.\n  clear H_useful.\n  unfold fault_weight_state.\n  unfold next_equivocation_state.\n  rewrite H_inter.\n  simpl. clear H_inter.\n  assert (H_rewrite := sum_weights_in v (set_add decide_eq v\n       (equivocating_senders\n          ((get_estimate ((get_estimate j, v', hash_state j) :: j), v, hash_state ((get_estimate j, v', hash_state j) :: j)) ::\n             (get_estimate j, v', hash_state j) :: j)))).\n  spec H_rewrite.\n  apply set_add_nodup. apply set_map_nodup.\n  spec H_rewrite.\n  rewrite set_add_iff. tauto.\n  rewrite H_rewrite. clear H_rewrite.\n  rewrite Rplus_comm.\n  apply Rplus_eq_compat_r.\n  rewrite add_remove_inverse.\n  reflexivity.\n  assert (H_useful := equivocating_senders_sorted_extend).\n  assert (H_useful' := H_useful).\n  spec H_useful j v'.\n  spec H_useful' ((get_estimate j, v', hash_state j) :: j) v.\n  assert (H_tran := set_eq_tran _ _ _ H_useful H_useful').\n  clear H_useful H_useful'.\n  intros H_absurd.\n  destruct H_tran as [_ H_eq].\n  spec H_eq v H_absurd.\n  contradiction.\nQed.\n\nDefinition add_weight_under\n  (s : state C V hash) (v : V) :=\n  (fault_weight_state s + proj1_sig (Measurable.weight v) <= proj1_sig threshold)%R.\n\nLemma equivocation_adds_fault_weight\n  : forall (j : state C V hash),\n    protocol_state j ->\n    forall (v v' : V),\n      ~ In v (equivocating_senders j) ->\n      v <> v' ->\n      fault_weight_state (next_equivocation_state j v v') =\n      (fault_weight_state j + proj1_sig (Measurable.weight v))%R.\nProof.\n  intros j about_j v v' H_notin about_v.\n  rewrite add_weight_three; try assumption.\n  rewrite add_weight_two;\n  rewrite <- add_weight_one; easy.\nQed.\n\n(* Under not-overweight conditions, the resulting state is a protocol state *)\nTheorem next_equivocation_protocol_state\n  : forall j : state C V hash,\n    protocol_state j ->\n    forall v v',\n      ~ In v (equivocating_senders j) ->\n      v <> v' ->\n      (* This is the most minimal condition we need about fault weight *)\n      (add_weight_under j v ->\n       protocol_state (next_equivocation_state j v v')).\nProof.\n  intros j about_j v v' H_notin H_neq H_weight.\n  assert (H_useful := about_equivocating_messages j about_j v v' H_neq).\n  destruct H_useful as [H2_noteq [H2_sender [H2_left H2_right]]].\n  (* Now. *)\n  unfold next_equivocation_state.\n  (* Peeling first message *)\n  apply protocol_state_cons with j (get_estimate j) v; try apply get_estimate_correct; try apply about_j; try apply in_eq.\n  rewrite set_remove_first. 2 : reflexivity.\n  apply protocol_state_cons with ((get_estimate j, v', hash_state j) :: j) (get_estimate ((get_estimate j, v', hash_state j) :: j)) v; try assumption; try apply get_estimate_correct; try apply in_eq.\n  apply copy_protocol_state; try assumption; try apply get_estimate_correct; try apply in_eq.\n  rewrite set_remove_first. 2 : reflexivity.\n  apply copy_protocol_state; try assumption; try apply get_estimate_correct.\n  apply NoDup_cons; try apply not_in_self.\n  apply copy_protocol_state; try assumption; try apply get_estimate_correct.\n  apply NoDup_cons; try apply not_in_self; try assumption.\n  now apply protocol_state_nodup in about_j.\n  2 : apply NoDup_cons; try apply not_in_self; try assumption.\n  2 : { intros H_or.\n        apply in_inv in H_or.\n        destruct H_or.\n        inversion H.\n        apply hash_state_injective in H2.\n        destruct H2. spec H0 (get_estimate ((get_estimate j, v', hash_state j) :: j), v',\n                              hash_state j).\n        spec H0. apply in_eq.\n        apply not_in_self_relaxed in H0. auto. assumption.\n        inversion H. inversion H0. subst; auto.\n        now apply not_in_self in H0. }\n  red. rewrite add_weight_two.\n  rewrite <- add_weight_one with j v'.\n  now apply protocol_state_not_heavy in about_j.\n  apply NoDup_cons; try apply not_in_self; try assumption.\n  now apply copy_protocol_state.\n  apply NoDup_cons; try apply not_in_self; try assumption.\n  now apply protocol_state_nodup in about_j.\n  red.\n  replace ((get_estimate j, v, hash_state j)\n      :: (get_estimate ((get_estimate j, v', hash_state j) :: j), v,\n         hash_state ((get_estimate j, v', hash_state j) :: j))\n         :: (get_estimate j, v', hash_state j) :: j)\n    with (next_equivocation_state j v v').\n    rewrite equivocation_adds_fault_weight;\n      assumption.\n    unfold next_equivocation_state. reflexivity.\nQed.\n\n(* Under additional not-already-equivocating conditions, the resulting state actually adds weight *)\nLemma next_equivocation_adds_weight\n  : forall (s : state C V hash),\n    protocol_state s ->\n    forall (v : V),\n      (* If the weight is not over *)\n      add_weight_under s v ->\n      (* And the sender is not already equivocating *)\n      ~ In v (equivocating_senders s) ->\n      forall (v' : V),\n        v <> v' ->\n        (* Then we get a protocol state *)\n        protocol_state (next_equivocation_state s v v') /\\\n        (* With increased weight *)\n        fault_weight_state (next_equivocation_state s v v') =\n        (fault_weight_state s + proj1_sig (Measurable.weight v))%R.\nProof.\n  intros s about_s v H_not_heavy H_notin v' H_neq.\n  split.\n  apply next_equivocation_protocol_state; assumption.\n  rewrite equivocation_adds_fault_weight; easy.\nQed.\n\nFixpoint next_equivocation_rec'\n  (s : state C V hash) (vs : list V) (v0 : V) : state C V hash\n  :=\n  match vs with\n  | [] => s\n  | hd :: tl => next_equivocation_state (next_equivocation_rec' s tl v0) hd v0\n  end.\n\nLemma next_equivocations_keeps_messages\n  : forall (s : state C V hash) (vs : list V) (v0 : V),\n  forall (msg : message C V hash),\n    In msg s ->\n    In msg (next_equivocation_rec' s vs v0).\nProof.\n  intros s vs v0 msg H_in.\n  induction vs as [|hd tl IHvs].\n  - assumption.\n  - simpl.\n    now apply next_equivocation_state_keeps_messages.\nQed.\n\nLemma next_equivocations_keeps_equivocating_senders\n  : forall (s : state C V hash) (vs : list V) (v0 : V),\n  forall (v : V),\n    In v (equivocating_senders s) ->\n    In v (equivocating_senders (next_equivocation_rec' s vs v0)).\nProof.\n  intros s vs v0 v H_in.\n  induction vs as [|hd tl IHvs].\n  - assumption.\n  - simpl.\n    unfold next_equivocation_state.\n    do 3 (rewrite equivocating_sender_add_in_sorted_iff; right).\n    assumption.\nQed.\n\nLemma next_equivocation_equivocating_sender_cons\n  : forall (s : state C V hash),\n    protocol_state s ->\n    forall (hd : V) (v0 v : V),\n      v <> v0 ->\n      In v (equivocating_senders (next_equivocation_state s hd v0)) <->\n      v = hd \\/ In v (equivocating_senders s).\nProof.\n  intros s about_s hd v0 v H_neq.\n  split; intro H.\n  - unfold next_equivocation_state in H.\n    apply equivocating_sender_add_in_sorted_iff in H.\n    destruct H.\n    tauto.\n    apply equivocating_sender_add_in_sorted_iff in H.\n    destruct H.\n    tauto.\n    apply equivocating_sender_add_in_sorted_iff in H.\n    destruct H.\n    simpl in H. destruct H. contradiction.\n    tauto.\n  - destruct H.\n    subst.\n    now apply about_equivocating_messages_add_equivocator.\n    apply equivocating_senders_correct in H.\n    destruct H as [msg [H_in [H_sender H_equiv]]].\n    apply equivocating_senders_correct.\n    exists msg. repeat split.\n    unfold next_equivocation_state; right.\n    right.\n    right.\n    assumption. assumption.\n    now apply next_equivocation_state_keeps_equivocating_messages.\nQed.\n\nLemma next_equivocations_equivocating_senders_right\n  : forall (s : state C V hash) (vs : list V) (v0 v : V),\n    (In v vs -> v <> v0) ->\n    In v (equivocating_senders (next_equivocation_rec' s vs v0)) ->\n    In v vs \\/ In v (equivocating_senders s).\nProof.\n  intros s vs; induction vs as [|hd tl IHvs]; intros v0 v H_neq.\n  - intros.\n    simpl in H. tauto.\n  - intros.\n    spec IHvs v0 v.\n    spec IHvs.\n    { intros.\n      spec H_neq. right; assumption.\n      assumption. }\n    simpl in H.\n    apply equivocating_sender_add_in_sorted_iff in H.\n    destruct H as [[ ? ? ] | ?].\n    subst. left. simpl. tauto.\n    apply equivocating_sender_add_in_sorted_iff in H.\n    simpl in H.\n    destruct H as [[ ? ? ] | ?].\n    subst. left. apply in_eq.\n    apply equivocating_sender_add_in_sorted_iff in H.\n    simpl in H.\n    destruct H as [[ ? ? ] | ?].\n    subst.\n    (* Now. H0 must be false. *)\n    destruct H0 as [msg_absurd [H_in H_equiv]].\n    assert (H_contra := non_equivocating_messages_extend msg_absurd (next_equivocation_rec' s tl v0) (get_estimate (next_equivocation_rec' s tl v0)) v0).\n    spec H_contra H_in.\n    apply equivocating_messages_correct in H_equiv.\n    rewrite equivocating_messages_comm in H_equiv.\n    rewrite H_equiv in H_contra.\n    inversion H_contra.\n    spec IHvs H. destruct IHvs.\n    left; apply in_cons; assumption.\n    tauto.\nQed.\n\nLemma next_equivocations_equivocating_senders_left_weak\n  : forall (s : state C V hash) (vs : list V) (v0 v : V),\n    protocol_state (next_equivocation_rec' s vs v0) ->\n    (In v vs -> v <> v0) ->\n    In v vs ->\n    In v (equivocating_senders (next_equivocation_rec' s vs v0)).\nProof.\n  intros s vs; induction vs as [|hd tl IHvs]; intros v0 v H_prot H_neq H_in.\n  - inversion H_in.\n  - assert (H_prot_sub : protocol_state (next_equivocation_rec' s tl v0)).\n    { apply protocol_state_incl with (next_equivocation_rec' s (hd :: tl) v0).\n      assumption.\n      apply protocol_state_nodup in H_prot.\n      simpl in H_prot.\n      unfold next_equivocation_state in H_prot.\n      do 3 (apply NoDup_cons_iff in H_prot; destruct H_prot as [_ H_prot]).\n      assumption.\n      intros msg H_in_msg.\n      simpl; repeat right; assumption. }\n    spec IHvs v0 v.\n    spec IHvs H_prot_sub.\n    spec IHvs. intros. apply H_neq. auto.\n    (* Case analysis on where v is *)\n    destruct H_in as [H_eq | H_in].\n    * (* When we are looking at the hd element, *)\n      subst.\n      simpl.\n      apply about_equivocating_messages_add_equivocator.\n      assumption. apply H_neq. apply in_eq.\n    * spec IHvs H_in.\n      simpl.\n      assert (H_useful := @equivocating_senders_incl hash C V _ _ _ _).\n      spec H_useful (next_equivocation_rec' s tl v0) (next_equivocation_state (next_equivocation_rec' s tl v0) hd v0).\n      spec H_useful.\n      apply next_equivocation_state_incl.\n      apply H_useful. assumption.\nQed.\n\nLemma next_equivocations_add_weights\n  : forall (s : state C V hash),\n    protocol_state s ->\n    forall (vs : list V) (v0 : V),\n      NoDup vs ->\n      (* The sum weight is not over *)\n      (fault_weight_state s + sum_weights vs <= proj1_sig threshold)%R ->\n      (* None of the senders are already equivocating *)\n      (forall (v : V),\n          In v vs -> ~ In v (equivocating_senders s) /\\ v <> v0) ->\n      (* Then we end up with a protocol state *)\n      protocol_state (next_equivocation_rec' s vs v0) /\\\n      (* And s recursively adds the sums of all the weights in vs *)\n      fault_weight_state (next_equivocation_rec' s vs v0) =\n      (fault_weight_state s + sum_weights vs)%R.\nProof.\n  intros s about_s vs v0 H_nodup H_underweight H_disjoint.\n  induction vs as [|hd tl IHvs].\n  - (* Base case : no validators to add *)\n    split. assumption.\n    rewrite Rplus_0_r. reflexivity.\n  - (* Induction step *)\n    (* Discharging first premise *)\n    spec IHvs.\n    rewrite NoDup_cons_iff in H_nodup; tauto.\n    (* Discharging second premise *)\n    spec IHvs.\n    simpl in H_underweight.\n    apply (Rplus_le_reg_pos_r (fault_weight_state s + sum_weights tl) (proj1_sig (Measurable.weight hd)) (proj1_sig threshold)).\n    destruct (Measurable.weight hd). firstorder.\n    rewrite Rplus_assoc.\n    rewrite (Rplus_comm (sum_weights tl) (proj1_sig (Measurable.weight hd))).\n    rewrite <- Rplus_assoc.\n    rewrite <- Rplus_assoc in H_underweight.\n    assumption.\n    (* Discharging third premise *)\n    spec IHvs.\n    intros. spec H_disjoint v. spec H_disjoint.\n    right; assumption.\n    assumption.\n    (* Now. *)\n    destruct IHvs as [H_prot H_weight].\n    spec H_disjoint hd (in_eq hd tl).\n    assert (H_notin_tl : ~ In hd tl).\n    { rewrite NoDup_cons_iff in H_nodup.\n      tauto. }\n    destruct H_disjoint as [H_disjoint H_neq].\n    assert (H_rewrite := next_equivocations_equivocating_senders_right s tl v0 hd).\n    spec H_rewrite.\n    intros. assumption.\n    split.\n    + simpl.\n      apply next_equivocation_protocol_state; try assumption.\n      intros H_absurd.\n      spec H_rewrite H_absurd.\n      tauto.\n      (* Need a helper lemma about weight adding here *)\n      unfold add_weight_under.\n      rewrite H_weight. simpl in H_underweight.\n      rewrite <- Rplus_assoc in H_underweight.\n      rewrite Rplus_assoc.\n      rewrite (Rplus_comm (sum_weights tl) (proj1_sig (Measurable.weight hd))).\n      rewrite <- Rplus_assoc.\n      assumption.\n    + simpl.\n      rewrite (Rplus_comm (proj1_sig (Measurable.weight hd)) (sum_weights tl)).\n      rewrite <- Rplus_assoc.\n      rewrite <- H_weight.\n      apply equivocation_adds_fault_weight; try assumption.\n      intro H_absurd. spec H_rewrite H_absurd.\n      tauto.\nQed.\n\nDefinition potentially_pivotal_state\n  (v : V) (s : state C V hash) :=\n  (* We say that v is a pivotal validator for some state s iff : *)\n  (* v is not already equivocating in s *)\n  ~ In v (equivocating_senders s) /\\\n  (* There is a remaining list of validators *)\n  exists (vs : list V),\n    (* That is duplicate-free *)\n    NoDup vs /\\\n    (* Doesn't contain v *)\n    ~ In v vs /\\\n    (* That are all not already equivocating in s *)\n    (forall (v : V), In v vs -> ~ In v (equivocating_senders s)) /\\\n    (* That tip over s's fault weight but only with the help of v *)\n    (sum_weights ((equivocating_senders s) ++ vs) <= proj1_sig threshold)%R /\\\n    (sum_weights ((equivocating_senders s) ++ vs) >\n     proj1_sig threshold - proj1_sig (Measurable.weight v))%R.\n\n(* This is a critical lemma *)\nLemma all_pivotal_validator\n  : forall (s : state C V hash),\n    protocol_state s ->\n  exists (v : V),\n    potentially_pivotal_state v s.\nProof.\n  intros s about_s.\n  pose (@LightNode_seteq hash C V _ _ _ _ _ _ _) as protocol_eq.\n  destruct suff_val as [vs [Hvs Hweight]].\n  remember (equivocating_senders s) as eqv_s.\n  remember (set_diff decide_eq vs eqv_s) as vss.\n  assert (sum_weights (vss ++ eqv_s) > proj1_sig threshold)%R.\n  { apply Rge_gt_trans with (sum_weights vs); try assumption.\n    apply Rle_ge. apply sum_weights_incl; try assumption.\n    - rewrite Heqvss. apply diff_app_nodup; try assumption.\n      subst. unfold equivocating_senders. apply set_map_nodup.\n    - rewrite Heqvss. intros a Hin. apply in_app_iff.\n      rewrite set_diff_iff. apply or_and_distr_left.\n      split; try (left; assumption).\n      destruct (in_dec decide_eq a eqv_s); (left; assumption) || (right; assumption).\n  }\n  apply pivotal_validator_extension in H.\n  - destruct H as [vs' [Hnodup_vs' [Hincl_vs' [Hgt [v [Hin_v Hlt]]]]]].\n    exists v. split.\n    + subst. apply Hincl_vs' in Hin_v. apply set_diff_elim2 in Hin_v. assumption.\n    + exists (set_remove decide_eq v vs').\n      assert (NoDup (set_remove decide_eq v vs')) as Hnodup_remove\n      ; try apply set_remove_nodup; try assumption.\n      repeat split.\n      * assumption.\n      * try apply set_remove_elim; try assumption.\n      * intros. apply set_remove_1 in H. apply Hincl_vs' in H. subst.\n        apply set_diff_elim2 in H. assumption.\n      * subst. rewrite sum_weights_app in *. rewrite Rplus_comm in Hlt.\n        assumption.\n      * apply Rlt_gt. apply Rplus_lt_reg_r with (proj1_sig (weight v)).\n        unfold Rminus. rewrite Rplus_assoc. rewrite Rplus_opp_l.\n        rewrite Rplus_0_r. apply Rgt_lt.\n        apply Rge_gt_trans with (sum_weights (vs' ++ eqv_s)); try assumption.\n        unfold Rge. right. rewrite Rplus_comm.\n        rewrite sum_weights_app. rewrite (Rplus_comm (sum_weights (equivocating_senders s))) .\n        rewrite <- Rplus_assoc. rewrite sum_weights_app. subst.\n        apply Rplus_eq_compat_r.\n        symmetry. apply sum_weights_in; try assumption.\n  - subst. apply set_map_nodup.\n  - subst. apply protocol_state_not_heavy. assumption.\n  - subst. apply diff_app_nodup; try assumption.\n    apply set_map_nodup.\nQed.\n\nTheorem strong_nontriviality_full\n  (Hit : InhabitedTwice V)\n  (Hdc : DistinctChoice V)\n : strong_nontriviality.\nProof.\n  intros [s1 about_s1].\n  destruct (all_pivotal_validator s1 about_s1) as [v [H_v [vs [H_nodup [H_v_notin [H_disjoint [H_under H_over]]]]]]].\n  remember (exist protocol_state ((get_estimate s1,v,hash_state s1) :: s1) (copy_protocol_state s1 about_s1  v)) as s2.\n  (* Book-keeping *)\n  assert (H_s1_s2_senders : set_eq (equivocating_senders s1) (equivocating_senders (proj1_sig s2))) by (subst; apply equivocating_senders_sorted_extend).\n  assert (H_s1_s2_weight : fault_weight_state s1 = fault_weight_state (proj1_sig s2)) by (subst; apply add_weight_one).\n  exists s2.\n  (* Proving next-step relation is trivial. *)\n  split.\n  exists (get_estimate s1,v,hash_state s1); subst; simpl in *.\n  split; intros x H_in.\n  rewrite set_add_iff in H_in. destruct H_in. subst. apply in_eq.\n  right; tauto.\n  inversion H_in; subst; rewrite set_add_iff; tauto.\n  (* s3 is the state with equivocations from all the senders in vs recursively added to s1, in addition to (c,v,s1)'s equivocating partner message. *)\n  (* First we add the equivocating partner message *)\n  remember ((get_estimate ((get_estimate s1, get_distinct_sender v, hash_state s1) :: s1), v, hash_state ((get_estimate s1, get_distinct_sender v, hash_state s1) :: s1)) :: ((get_estimate s1, get_distinct_sender v, hash_state s1) :: s1)) as s1'.\n  (* Book-keeping step *)\n  assert (H_eq_senders : set_eq (equivocating_senders s1') (equivocating_senders s1)).\n  { subst.\n    assert (H_useful := equivocating_senders_sorted_extend ((get_estimate s1, get_distinct_sender v, hash_state s1) :: s1) v).\n    eapply set_eq_tran.\n    apply set_eq_comm. exact H_useful.\n    apply set_eq_comm. apply equivocating_senders_sorted_extend. }\n  assert (H_s_inter_weight : fault_weight_state s1' = fault_weight_state s1).\n  { apply equivocating_senders_fault_weight_eq; assumption. }\n  (* Now we are ready to construct s3 from s1' *)\n  (* And if we have set up everything correctly, the premises at this point in the proof are sufficient. *)\n  remember (next_equivocation_rec' s1' vs v) as s3.\n  assert (about_s3 : protocol_state s3).\n  { rewrite Heqs3. apply next_equivocations_add_weights.\n    { subst.\n      apply copy_protocol_state; try apply get_estimate_correct; try assumption.\n      apply copy_protocol_state; try apply get_estimate_correct; try assumption. }\n    assumption.\n    rewrite H_s_inter_weight. rewrite sum_weights_app in H_under.\n    assumption.\n    intros. spec H_disjoint v0 H.\n    destruct H_eq_senders as [H_left H_right].\n    spec H_right v0.\n    split. intro H_absurd. spec H_left v0 H_absurd.\n    contradiction. intro H_absurd. subst. contradiction. }\n  exists (exist protocol_state s3 about_s3).\n  repeat split.\n  - (* Proving that s1 and s3 share a common future *)\n    red. exists (exist protocol_state s3 about_s3).\n    split. simpl. red.\n    red. subst.\n    intros m0 H_in.\n    (* Need to prove that next_equivocation_rec' doesn't drop messages *)\n    apply next_equivocations_keeps_messages.\n    do 2 right.\n    assumption.\n    apply incl_refl.\n  - (* Proving that s2 and s3 don't share a common future *)\n    (* Arbitrary state in both s2 and s3 leads to a contradiction *)\n    red. intros [s about_s] H.\n    destruct H as [H_in2 H_in3].\n    assert (H_in2_copy := H_in2);\n      assert (H_in3_copy := H_in3).\n    (* Now we show that two equivocating messages are in s *)\n    (* First message *)\n    spec H_in2 (get_estimate s1,v,hash_state s1).\n    spec H_in2.\n    subst.\n    apply in_eq.\n    (* Second message *)\n    spec H_in3 (get_estimate\n                ((get_estimate s1, get_distinct_sender v, hash_state s1) :: s1), v,\n\n               hash_state ((get_estimate s1, get_distinct_sender v, hash_state s1) ::  s1)).\n    spec H_in3.\n    { (* Proving that this message is in s3 *)\n      assert (H_obv : In (get_estimate ((get_estimate s1, get_distinct_sender v, hash_state s1) ::  s1), v, hash_state ((get_estimate s1, get_distinct_sender v, hash_state s1) ::  s1)) s1').\n      { subst.\n        left. reflexivity. }\n      apply (next_equivocations_keeps_messages s1' vs v) in H_obv.\n      subst; assumption. }\n    (* Now we prove that these two messages are equivocating *)\n    simpl in *.\n    assert (H_equiv : equivocating_messages_prop (get_estimate s1,v,hash_state s1)\n                                                 (get_estimate ((get_estimate s1, get_distinct_sender v, hash_state s1) :: s1), v, hash_state ((get_estimate s1, get_distinct_sender v, hash_state s1) :: s1))).\n    apply about_equivocating_messages.\n    assumption. apply get_distinct_sender_correct.\n    (* Now we say that v will be an equivocating sender inside s *)\n    assert (H_v_in : In v (equivocating_senders s)).\n    { apply equivocating_senders_correct.\n      exists (get_estimate s1, v, hash_state s1).\n      repeat split; try assumption.\n      exists (get_estimate ((get_estimate s1, get_distinct_sender v, hash_state s1) :: s1), v, hash_state ( (get_estimate s1, get_distinct_sender v, hash_state s1) :: s1)).\n      split. assumption. assumption. }\n    clear H_in2 H_in3 H_equiv.\n    (* Now we say that v's weight will be inside s's fault weight *)\n    (* This part is a little tricky *)\n    assert (H_equivocators_s : incl (v :: (equivocating_senders (proj1_sig s2) ++ vs)) (equivocating_senders s)).\n    { intros v0 H_in0.\n      destruct H_in0 as [H_hd | H_tl].\n      + subst. assumption.\n      + apply in_app_iff in H_tl.\n        destruct H_tl as [H_left | H_right].\n        * eapply equivocating_senders_incl.\n          apply H_in2_copy.\n          assumption.\n        * assert (H_in_v0 : In v0 (equivocating_senders (next_equivocation_rec' s1' vs v))).\n          { apply next_equivocations_equivocating_senders_left_weak.\n            subst; assumption. intros.\n            2 : assumption.\n            intro H_absurd; subst; contradiction. }\n          rewrite <- Heqs3 in H_in_v0.\n          eapply equivocating_senders_incl.\n          exact H_in3_copy.\n          assumption.\n    }\n    assert (H_s_overweight : (proj1_sig (Measurable.weight v) + fault_weight_state (proj1_sig s2) + sum_weights vs <= fault_weight_state s)%R).\n    { replace ((proj1_sig (Measurable.weight v) + fault_weight_state (proj1_sig s2) + sum_weights vs))%R with (sum_weights ([v] ++ (equivocating_senders (proj1_sig s2)) ++ vs)).\n      apply sum_weights_incl.\n      { (* Proving mutual NoDup *)\n        apply nodup_append.\n        apply NoDup_cons. intros; inversion 1.\n        constructor.\n        apply nodup_append.\n        apply set_map_nodup. assumption.\n        { intros. intro Habsurd. spec H_disjoint a Habsurd.\n          destruct H_s1_s2_senders as [_ H_useful].\n          spec H_useful a H. contradiction.\n        }\n        { intros. intro Habsurd. spec H_disjoint a H.\n          destruct H_s1_s2_senders as [_ H_useful].\n          spec H_useful a Habsurd. contradiction. }\n        { intros. inversion H. intro Habsurd.\n          apply in_app_iff in Habsurd. destruct Habsurd.\n          destruct H_s1_s2_senders as [_ H_useful];\n            spec H_useful a H1.\n          subst; contradiction. subst; contradiction. inversion H0. }\n        { intros. intro Habsurd.\n          inversion Habsurd.\n          apply in_app_iff in H. destruct H.\n          destruct H_s1_s2_senders as [_ H_useful];\n            spec H_useful a H.\n          subst; contradiction. subst; contradiction. inversion H0. }\n      }\n      apply set_map_nodup. assumption.\n      do 2 rewrite sum_weights_app.\n      unfold fault_weight_state.\n      simpl. ring. }\n    apply protocol_state_not_heavy in about_s.\n    red in about_s.\n    assert (H_finale := Rle_trans _ _ _ H_s_overweight about_s). auto.\n    clear -H_finale H_over H_s1_s2_weight.\n    rewrite sum_weights_app in H_over.\n    unfold fault_weight_state in H_s1_s2_weight at 1.\n    rewrite H_s1_s2_weight in H_over.\n    apply (Rplus_gt_compat_l (proj1_sig (Measurable.weight v))) in H_over.\n    replace (proj1_sig (Measurable.weight v) + (proj1_sig threshold - proj1_sig (Measurable.weight v)))%R with (proj1_sig threshold)%R in H_over by ring.\n    rewrite <- Rplus_assoc in H_over.\n    apply Rgt_not_le in H_over.\n    contradiction.\nQed.\n\nEnd LightNode.\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/LightNode.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.28875231101188664}}
{"text": "Load \"preamble4D.v\".\n\n\n(* dans constructLemma(), requis par LAM *)\n(* dans la couche 0 *)\nLemma LAH1H2H3H4M : forall A B C H1 H2 H3 H4 M N P ,\nrk(A :: B :: C ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 ::  nil) = 4 -> rk(A :: H1 :: H2 :: H3 :: H4 ::  nil) = 5 ->\nrk(A :: B :: C :: M ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 :: M ::  nil) = 4 -> rk(A :: B :: C :: N ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: N ::  nil) = 4 -> rk(M :: N ::  nil) = 2 -> rk(A :: B :: C :: P ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: P ::  nil) = 4 -> rk(A :: H1 :: H2 :: H3 :: H4 :: M ::  nil) = 5.\nProof.\n\nintros A B C H1 H2 H3 H4 M N P \nHABCeq HH1H2H3H4eq HAH1H2H3H4eq HABCMeq HH1H2H3H4Meq HABCNeq HH1H2H3H4Neq HMNeq HABCPeq HH1H2H3H4Peq\n.\n\n(* dans constructProofaux(), preuve de 4 <= rg <= 5 pour AH1H2H3H4M requis par la preuve de (?)AH1H2H3H4M pour la règle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 5 pour AH1H2H3H4M requis par la preuve de (?)AH1H2H3H4M 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(HAH1H2H3H4Mm4 : rk(A :: H1 :: H2 :: H3 :: H4 :: M :: nil) >= 4).\n{\n\tassert(HH1H2H3H4mtmp : rk(H1 :: H2 :: H3 :: H4 :: nil) >= 4) by (solve_hyps_min HH1H2H3H4eq HH1H2H3H4m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (H1 :: H2 :: H3 :: H4 :: nil) (A :: H1 :: H2 :: H3 :: H4 :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (H1 :: H2 :: H3 :: H4 :: nil) (A :: H1 :: H2 :: H3 :: H4 :: M :: nil) 4 4 HH1H2H3H4mtmp 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(HAH1H2H3H4Mm5 : rk(A :: H1 :: H2 :: H3 :: H4 :: M :: nil) >= 5).\n{\n\tassert(HAH1H2H3H4mtmp : rk(A :: H1 :: H2 :: H3 :: H4 :: nil) >= 5) by (solve_hyps_min HAH1H2H3H4eq HAH1H2H3H4m5).\n\tassert(Hcomp : 5 <= 5) by (repeat constructor).\n\tassert(Hincl : incl (A :: H1 :: H2 :: H3 :: H4 :: nil) (A :: H1 :: H2 :: H3 :: H4 :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: H1 :: H2 :: H3 :: H4 :: nil) (A :: H1 :: H2 :: H3 :: H4 :: M :: nil) 5 5 HAH1H2H3H4mtmp Hcomp Hincl);apply HT.\n}\n\nassert(HAH1H2H3H4MM : rk(A :: H1 :: H2 :: H3 :: H4 :: M ::  nil) <= 5) by (apply rk_upper_dim).\nassert(HAH1H2H3H4Mm : rk(A :: H1 :: H2 :: H3 :: H4 :: M ::  nil) >= 1) by (solve_hyps_min HAH1H2H3H4Meq HAH1H2H3H4Mm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LAM : forall A B C H1 H2 H3 H4 M N P ,\nrk(A :: B :: C ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 ::  nil) = 4 -> rk(A :: H1 :: H2 :: H3 :: H4 ::  nil) = 5 ->\nrk(A :: B :: C :: M ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 :: M ::  nil) = 4 -> rk(A :: B :: C :: N ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: N ::  nil) = 4 -> rk(M :: N ::  nil) = 2 -> rk(A :: B :: C :: P ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: P ::  nil) = 4 -> rk(A :: M ::  nil) = 2.\nProof.\n\nintros A B C H1 H2 H3 H4 M N P \nHABCeq HH1H2H3H4eq HAH1H2H3H4eq HABCMeq HH1H2H3H4Meq HABCNeq HH1H2H3H4Neq HMNeq HABCPeq HH1H2H3H4Peq\n.\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 2 pour AM requis par la preuve de (?)AM pour la règle 2  *)\n(* Application de la règle 2 code (7 ou 8 dans la thèse) conclusion A*)\n(* marque des antécédents AUB AiB B: 4 -2 et -4*)\nassert(HAMm2 : rk(A :: M :: nil) >= 2).\n{\n\tassert(HH1H2H3H4MMtmp : rk(H1 :: H2 :: H3 :: H4 :: M :: nil) <= 4) by (solve_hyps_max HH1H2H3H4Meq HH1H2H3H4MM4).\n\tassert(HAH1H2H3H4Meq : rk(A :: H1 :: H2 :: H3 :: H4 :: M :: nil) = 5) by (apply LAH1H2H3H4M with (A := A) (B := B) (C := C) (H1 := H1) (H2 := H2) (H3 := H3) (H4 := H4) (M := M) (N := N) (P := P) ; assumption).\n\tassert(HAH1H2H3H4Mmtmp : rk(A :: H1 :: H2 :: H3 :: H4 :: M :: nil) >= 5) by (solve_hyps_min HAH1H2H3H4Meq HAH1H2H3H4Mm5).\n\tassert(HMmtmp : rk(M :: nil) >= 1) by (solve_hyps_min HMeq HMm1).\n\tassert(Hincl : incl (M :: nil) (list_inter (A :: M :: nil) (H1 :: H2 :: H3 :: H4 :: M :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: H1 :: H2 :: H3 :: H4 :: M :: nil) (A :: M :: H1 :: H2 :: H3 :: H4 :: M :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: M :: H1 :: H2 :: H3 :: H4 :: M :: nil) ((A :: M :: nil) ++ (H1 :: H2 :: H3 :: H4 :: M :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HAH1H2H3H4Mmtmp;try rewrite HT2 in HAH1H2H3H4Mmtmp.\n\tassert(HT := rule_2 (A :: M :: nil) (H1 :: H2 :: H3 :: H4 :: M :: nil) (M :: nil) 5 1 4 HAH1H2H3H4Mmtmp HMmtmp HH1H2H3H4MMtmp Hincl);apply HT.\n}\n\nassert(HAMM : rk(A :: M ::  nil) <= 2) (* dim : 4 *) by (solve_hyps_max HAMeq HAMM2).\nassert(HAMm : rk(A :: M ::  nil) >= 1) by (solve_hyps_min HAMeq HAMm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LAMN *)\n(* dans la couche 0 *)\nLemma LAH1H2H3H4MN : forall A B C H1 H2 H3 H4 M N P ,\nrk(A :: B :: C ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 ::  nil) = 4 -> rk(A :: H1 :: H2 :: H3 :: H4 ::  nil) = 5 ->\nrk(A :: B :: C :: M ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 :: M ::  nil) = 4 -> rk(A :: B :: C :: N ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: N ::  nil) = 4 -> rk(M :: N ::  nil) = 2 -> rk(A :: B :: C :: P ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: P ::  nil) = 4 -> rk(A :: H1 :: H2 :: H3 :: H4 :: M :: N ::  nil) = 5.\nProof.\n\nintros A B C H1 H2 H3 H4 M N P \nHABCeq HH1H2H3H4eq HAH1H2H3H4eq HABCMeq HH1H2H3H4Meq HABCNeq HH1H2H3H4Neq HMNeq HABCPeq HH1H2H3H4Peq\n.\n\n(* dans constructProofaux(), preuve de 4 <= rg <= 5 pour AH1H2H3H4MN requis par la preuve de (?)AH1H2H3H4MN pour la règle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 5 pour AH1H2H3H4MN requis par la preuve de (?)AH1H2H3H4MN 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(HAH1H2H3H4MNm4 : rk(A :: H1 :: H2 :: H3 :: H4 :: M :: N :: nil) >= 4).\n{\n\tassert(HH1H2H3H4mtmp : rk(H1 :: H2 :: H3 :: H4 :: nil) >= 4) by (solve_hyps_min HH1H2H3H4eq HH1H2H3H4m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (H1 :: H2 :: H3 :: H4 :: nil) (A :: H1 :: H2 :: H3 :: H4 :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (H1 :: H2 :: H3 :: H4 :: nil) (A :: H1 :: H2 :: H3 :: H4 :: M :: N :: nil) 4 4 HH1H2H3H4mtmp 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(HAH1H2H3H4MNm5 : rk(A :: H1 :: H2 :: H3 :: H4 :: M :: N :: nil) >= 5).\n{\n\tassert(HAH1H2H3H4mtmp : rk(A :: H1 :: H2 :: H3 :: H4 :: nil) >= 5) by (solve_hyps_min HAH1H2H3H4eq HAH1H2H3H4m5).\n\tassert(Hcomp : 5 <= 5) by (repeat constructor).\n\tassert(Hincl : incl (A :: H1 :: H2 :: H3 :: H4 :: nil) (A :: H1 :: H2 :: H3 :: H4 :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: H1 :: H2 :: H3 :: H4 :: nil) (A :: H1 :: H2 :: H3 :: H4 :: M :: N :: nil) 5 5 HAH1H2H3H4mtmp Hcomp Hincl);apply HT.\n}\n\nassert(HAH1H2H3H4MNM : rk(A :: H1 :: H2 :: H3 :: H4 :: M :: N ::  nil) <= 5) by (apply rk_upper_dim).\nassert(HAH1H2H3H4MNm : rk(A :: H1 :: H2 :: H3 :: H4 :: M :: N ::  nil) >= 1) by (solve_hyps_min HAH1H2H3H4MNeq HAH1H2H3H4MNm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LAMN *)\n(* dans la couche 0 *)\nLemma LH1H2H3H4MN : forall A B C H1 H2 H3 H4 M N P ,\nrk(A :: B :: C ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 ::  nil) = 4 -> rk(A :: H1 :: H2 :: H3 :: H4 ::  nil) = 5 ->\nrk(A :: B :: C :: M ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 :: M ::  nil) = 4 -> rk(A :: B :: C :: N ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: N ::  nil) = 4 -> rk(M :: N ::  nil) = 2 -> rk(A :: B :: C :: P ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: P ::  nil) = 4 -> rk(H1 :: H2 :: H3 :: H4 :: M :: N ::  nil) = 4.\nProof.\n\nintros A B C H1 H2 H3 H4 M N P \nHABCeq HH1H2H3H4eq HAH1H2H3H4eq HABCMeq HH1H2H3H4Meq HABCNeq HH1H2H3H4Neq HMNeq HABCPeq HH1H2H3H4Peq\n.\n\n(* dans constructProofaux(), preuve de 4 <= rg <= 5 pour H1H2H3H4MN requis par la preuve de (?)H1H2H3H4MN pour la règle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 5 pour H1H2H3H4MN requis par la preuve de (?)H1H2H3H4MN 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(HH1H2H3H4MNm4 : rk(H1 :: H2 :: H3 :: H4 :: M :: N :: nil) >= 4).\n{\n\tassert(HH1H2H3H4mtmp : rk(H1 :: H2 :: H3 :: H4 :: nil) >= 4) by (solve_hyps_min HH1H2H3H4eq HH1H2H3H4m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (H1 :: H2 :: H3 :: H4 :: nil) (H1 :: H2 :: H3 :: H4 :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (H1 :: H2 :: H3 :: H4 :: nil) (H1 :: H2 :: H3 :: H4 :: M :: N :: nil) 4 4 HH1H2H3H4mtmp 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(HH1H2H3H4MNM4 : rk(H1 :: H2 :: H3 :: H4 :: M :: N :: nil) <= 4).\n{\n\tassert(HH1H2H3H4MMtmp : rk(H1 :: H2 :: H3 :: H4 :: M :: nil) <= 4) by (solve_hyps_max HH1H2H3H4Meq HH1H2H3H4MM4).\n\tassert(HH1H2H3H4NMtmp : rk(H1 :: H2 :: H3 :: H4 :: N :: nil) <= 4) by (solve_hyps_max HH1H2H3H4Neq HH1H2H3H4NM4).\n\tassert(HH1H2H3H4mtmp : rk(H1 :: H2 :: H3 :: H4 :: nil) >= 4) by (solve_hyps_min HH1H2H3H4eq HH1H2H3H4m4).\n\tassert(Hincl : incl (H1 :: H2 :: H3 :: H4 :: nil) (list_inter (H1 :: H2 :: H3 :: H4 :: M :: nil) (H1 :: H2 :: H3 :: H4 :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (H1 :: H2 :: H3 :: H4 :: M :: N :: nil) (H1 :: H2 :: H3 :: H4 :: M :: H1 :: H2 :: H3 :: H4 :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (H1 :: H2 :: H3 :: H4 :: M :: H1 :: H2 :: H3 :: H4 :: N :: nil) ((H1 :: H2 :: H3 :: H4 :: M :: nil) ++ (H1 :: H2 :: H3 :: H4 :: N :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (H1 :: H2 :: H3 :: H4 :: M :: nil) (H1 :: H2 :: H3 :: H4 :: N :: nil) (H1 :: H2 :: H3 :: H4 :: nil) 4 4 4 HH1H2H3H4MMtmp HH1H2H3H4NMtmp HH1H2H3H4mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\nassert(HH1H2H3H4MNM : rk(H1 :: H2 :: H3 :: H4 :: M :: N ::  nil) <= 5) by (apply rk_upper_dim).\nassert(HH1H2H3H4MNm : rk(H1 :: H2 :: H3 :: H4 :: M :: N ::  nil) >= 1) by (solve_hyps_min HH1H2H3H4MNeq HH1H2H3H4MNm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LAMN : forall A B C H1 H2 H3 H4 M N P ,\nrk(A :: B :: C ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 ::  nil) = 4 -> rk(A :: H1 :: H2 :: H3 :: H4 ::  nil) = 5 ->\nrk(A :: B :: C :: M ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 :: M ::  nil) = 4 -> rk(A :: B :: C :: N ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: N ::  nil) = 4 -> rk(M :: N ::  nil) = 2 -> rk(A :: B :: C :: P ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: P ::  nil) = 4 -> rk(A :: M :: N ::  nil) = 3.\nProof.\n\nintros A B C H1 H2 H3 H4 M N P \nHABCeq HH1H2H3H4eq HAH1H2H3H4eq HABCMeq HH1H2H3H4Meq HABCNeq HH1H2H3H4Neq HMNeq HABCPeq HH1H2H3H4Peq\n.\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour AMN requis par la preuve de (?)AMN pour la règle 2  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 3 pour ABCMN requis par la preuve de (?)AMN pour la règle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour ABCMN requis par la preuve de (?)ABCMN pour la règle 1  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 5 pour ABCMN requis par la preuve de (?)ABCMN pour la règle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 5 pour ABCMN requis par la preuve de (?)ABCMN 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(HABCMNm3 : rk(A :: B :: C :: M :: N :: 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 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: B :: C :: nil) (A :: B :: C :: M :: N :: 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 : -2 -4 et 5*)\nassert(HABCMNM4 : rk(A :: B :: C :: M :: N :: nil) <= 4).\n{\n\tassert(HMMtmp : rk(M :: nil) <= 1) by (solve_hyps_max HMeq HMM1).\n\tassert(HABCNMtmp : rk(A :: B :: C :: N :: nil) <= 3) by (solve_hyps_max HABCNeq HABCNM3).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (M :: nil) (A :: B :: C :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: C :: M :: N :: nil) (M :: A :: B :: C :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (M :: A :: B :: C :: N :: nil) ((M :: nil) ++ (A :: B :: C :: N :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (M :: nil) (A :: B :: C :: N :: nil) (nil) 1 3 0 HMMtmp HABCNMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;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(HABCMNM3 : rk(A :: B :: C :: M :: N :: nil) <= 3).\n{\n\tassert(HABCMMtmp : rk(A :: B :: C :: M :: nil) <= 3) by (solve_hyps_max HABCMeq HABCMM3).\n\tassert(HABCNMtmp : rk(A :: B :: C :: N :: nil) <= 3) by (solve_hyps_max HABCNeq HABCNM3).\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 :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: C :: M :: N :: nil) (A :: B :: C :: M :: A :: B :: C :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: B :: C :: M :: A :: B :: C :: N :: nil) ((A :: B :: C :: M :: nil) ++ (A :: B :: C :: N :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (A :: B :: C :: M :: nil) (A :: B :: C :: N :: nil) (A :: B :: C :: nil) 3 3 3 HABCMMtmp HABCNMtmp HABCmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour AMN requis par la preuve de (?)AMN pour la règle 4  *)\n(* Application de la règle 4 code (7 ou 8 dans la thèse) concerne B (rang 2 et 3) *)\n(* marque des antécédents AUB AiB A: 5 4 et -4*)\n(* ensembles concernés AUB : A :: B :: C :: M :: N ::  de rang :  3 et 3 \t AiB : A :: M ::  de rang :  2 et 2 \t A : A :: B :: C :: M ::   de rang : 3 et 3 *)\nassert(HAMNm2 : rk(A :: M :: N :: nil) >= 2).\n{\n\tassert(HABCMMtmp : rk(A :: B :: C :: M :: nil) <= 3) by (solve_hyps_max HABCMeq HABCMM3).\n\tassert(HABCMNmtmp : rk(A :: B :: C :: M :: N :: nil) >= 3) by (solve_hyps_min HABCMNeq HABCMNm3).\n\tassert(HAMeq : rk(A :: M :: nil) = 2) by (apply LAM with (A := A) (B := B) (C := C) (H1 := H1) (H2 := H2) (H3 := H3) (H4 := H4) (M := M) (N := N) (P := P) ; assumption).\n\tassert(HAMmtmp : rk(A :: M :: nil) >= 2) by (solve_hyps_min HAMeq HAMm2).\n\tassert(Hincl : incl (A :: M :: nil) (list_inter (A :: B :: C :: M :: nil) (A :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: C :: M :: N :: nil) (A :: B :: C :: M :: A :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: B :: C :: M :: A :: M :: N :: nil) ((A :: B :: C :: M :: nil) ++ (A :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABCMNmtmp;try rewrite HT2 in HABCMNmtmp.\n\tassert(HT := rule_4 (A :: B :: C :: M :: nil) (A :: M :: N :: nil) (A :: M :: nil) 3 2 3 HABCMNmtmp HAMmtmp HABCMMtmp Hincl); apply HT.\n}\n\n(* Application de la règle 2 code (7 ou 8 dans la thèse) conclusion A*)\n(* marque des antécédents AUB AiB B: 4 -4 et 4*)\nassert(HAMNm3 : rk(A :: M :: N :: nil) >= 3).\n{\n\tassert(HH1H2H3H4MNeq : rk(H1 :: H2 :: H3 :: H4 :: M :: N :: nil) = 4) by (apply LH1H2H3H4MN with (A := A) (B := B) (C := C) (H1 := H1) (H2 := H2) (H3 := H3) (H4 := H4) (M := M) (N := N) (P := P) ; assumption).\n\tassert(HH1H2H3H4MNMtmp : rk(H1 :: H2 :: H3 :: H4 :: M :: N :: nil) <= 4) by (solve_hyps_max HH1H2H3H4MNeq HH1H2H3H4MNM4).\n\tassert(HAH1H2H3H4MNeq : rk(A :: H1 :: H2 :: H3 :: H4 :: M :: N :: nil) = 5) by (apply LAH1H2H3H4MN with (A := A) (B := B) (C := C) (H1 := H1) (H2 := H2) (H3 := H3) (H4 := H4) (M := M) (N := N) (P := P) ; assumption).\n\tassert(HAH1H2H3H4MNmtmp : rk(A :: H1 :: H2 :: H3 :: H4 :: M :: N :: nil) >= 5) by (solve_hyps_min HAH1H2H3H4MNeq HAH1H2H3H4MNm5).\n\tassert(HMNmtmp : rk(M :: N :: nil) >= 2) by (solve_hyps_min HMNeq HMNm2).\n\tassert(Hincl : incl (M :: N :: nil) (list_inter (A :: M :: N :: nil) (H1 :: H2 :: H3 :: H4 :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: H1 :: H2 :: H3 :: H4 :: M :: N :: nil) (A :: M :: N :: H1 :: H2 :: H3 :: H4 :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: M :: N :: H1 :: H2 :: H3 :: H4 :: M :: N :: nil) ((A :: M :: N :: nil) ++ (H1 :: H2 :: H3 :: H4 :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HAH1H2H3H4MNmtmp;try rewrite HT2 in HAH1H2H3H4MNmtmp.\n\tassert(HT := rule_2 (A :: M :: N :: nil) (H1 :: H2 :: H3 :: H4 :: M :: N :: nil) (M :: N :: nil) 5 2 4 HAH1H2H3H4MNmtmp HMNmtmp HH1H2H3H4MNMtmp Hincl);apply HT.\n}\n\nassert(HAMNM : rk(A :: M :: N ::  nil) <= 3) (* dim : 4 *) by (solve_hyps_max HAMNeq HAMNM3).\nassert(HAMNm : rk(A :: M :: N ::  nil) >= 1) by (solve_hyps_min HAMNeq HAMNm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LABCMN : forall A B C H1 H2 H3 H4 M N P ,\nrk(A :: B :: C ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 ::  nil) = 4 -> rk(A :: H1 :: H2 :: H3 :: H4 ::  nil) = 5 ->\nrk(A :: B :: C :: M ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 :: M ::  nil) = 4 -> rk(A :: B :: C :: N ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: N ::  nil) = 4 -> rk(M :: N ::  nil) = 2 -> rk(A :: B :: C :: P ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: P ::  nil) = 4 -> rk(A :: B :: C :: M :: N ::  nil) = 3.\nProof.\n\nintros A B C H1 H2 H3 H4 M N P \nHABCeq HH1H2H3H4eq HAH1H2H3H4eq HABCMeq HH1H2H3H4Meq HABCNeq HH1H2H3H4Neq HMNeq HABCPeq HH1H2H3H4Peq\n.\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour ABCMN requis par la preuve de (?)ABCMN pour la règle 1  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 5 pour ABCMN requis par la preuve de (?)ABCMN pour la règle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 5 pour ABCMN requis par la preuve de (?)ABCMN 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(HABCMNm3 : rk(A :: B :: C :: M :: N :: 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 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: B :: C :: nil) (A :: B :: C :: M :: N :: 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 : -2 -4 et 5*)\nassert(HABCMNM4 : rk(A :: B :: C :: M :: N :: nil) <= 4).\n{\n\tassert(HMMtmp : rk(M :: nil) <= 1) by (solve_hyps_max HMeq HMM1).\n\tassert(HABCNMtmp : rk(A :: B :: C :: N :: nil) <= 3) by (solve_hyps_max HABCNeq HABCNM3).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (M :: nil) (A :: B :: C :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: C :: M :: N :: nil) (M :: A :: B :: C :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (M :: A :: B :: C :: N :: nil) ((M :: nil) ++ (A :: B :: C :: N :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (M :: nil) (A :: B :: C :: N :: nil) (nil) 1 3 0 HMMtmp HABCNMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;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(HABCMNM3 : rk(A :: B :: C :: M :: N :: nil) <= 3).\n{\n\tassert(HABCMMtmp : rk(A :: B :: C :: M :: nil) <= 3) by (solve_hyps_max HABCMeq HABCMM3).\n\tassert(HABCNMtmp : rk(A :: B :: C :: N :: nil) <= 3) by (solve_hyps_max HABCNeq HABCNM3).\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 :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: C :: M :: N :: nil) (A :: B :: C :: M :: A :: B :: C :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: B :: C :: M :: A :: B :: C :: N :: nil) ((A :: B :: C :: M :: nil) ++ (A :: B :: C :: N :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (A :: B :: C :: M :: nil) (A :: B :: C :: N :: nil) (A :: B :: C :: nil) 3 3 3 HABCMMtmp HABCNMtmp HABCmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\nassert(HABCMNM : rk(A :: B :: C :: M :: N ::  nil) <= 5) by (apply rk_upper_dim).\nassert(HABCMNm : rk(A :: B :: C :: M :: N ::  nil) >= 1) by (solve_hyps_min HABCMNeq HABCMNm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LABCMP : forall A B C H1 H2 H3 H4 M N P ,\nrk(A :: B :: C ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 ::  nil) = 4 -> rk(A :: H1 :: H2 :: H3 :: H4 ::  nil) = 5 ->\nrk(A :: B :: C :: M ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 :: M ::  nil) = 4 -> rk(A :: B :: C :: N ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: N ::  nil) = 4 -> rk(M :: N ::  nil) = 2 -> rk(A :: B :: C :: P ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: P ::  nil) = 4 -> rk(A :: B :: C :: M :: P ::  nil) = 3.\nProof.\n\nintros A B C H1 H2 H3 H4 M N P \nHABCeq HH1H2H3H4eq HAH1H2H3H4eq HABCMeq HH1H2H3H4Meq HABCNeq HH1H2H3H4Neq HMNeq HABCPeq HH1H2H3H4Peq\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 3 <= rg <= 5 pour ABCMP requis par la preuve de (?)ABCMP pour la règle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 5 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 : -2 -4 et 5*)\nassert(HABCMPM4 : rk(A :: B :: C :: M :: P :: nil) <= 4).\n{\n\tassert(HMMtmp : rk(M :: nil) <= 1) by (solve_hyps_max HMeq HMM1).\n\tassert(HABCPMtmp : rk(A :: B :: C :: P :: nil) <= 3) by (solve_hyps_max HABCPeq HABCPM3).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (M :: nil) (A :: B :: C :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: C :: M :: P :: nil) (M :: A :: B :: C :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (M :: A :: B :: C :: P :: nil) ((M :: nil) ++ (A :: B :: C :: P :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (M :: nil) (A :: B :: C :: P :: nil) (nil) 1 3 0 HMMtmp HABCPMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;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) <= 5) 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 LH1H2H3H4MP : forall A B C H1 H2 H3 H4 M N P ,\nrk(A :: B :: C ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 ::  nil) = 4 -> rk(A :: H1 :: H2 :: H3 :: H4 ::  nil) = 5 ->\nrk(A :: B :: C :: M ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 :: M ::  nil) = 4 -> rk(A :: B :: C :: N ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: N ::  nil) = 4 -> rk(M :: N ::  nil) = 2 -> rk(A :: B :: C :: P ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: P ::  nil) = 4 -> rk(H1 :: H2 :: H3 :: H4 :: M :: P ::  nil) = 4.\nProof.\n\nintros A B C H1 H2 H3 H4 M N P \nHABCeq HH1H2H3H4eq HAH1H2H3H4eq HABCMeq HH1H2H3H4Meq HABCNeq HH1H2H3H4Neq HMNeq HABCPeq HH1H2H3H4Peq\n.\n\n(* dans constructProofaux(), preuve de 4 <= rg <= 5 pour H1H2H3H4MP requis par la preuve de (?)H1H2H3H4MP pour la règle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 5 pour H1H2H3H4MP requis par la preuve de (?)H1H2H3H4MP 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(HH1H2H3H4MPm4 : rk(H1 :: H2 :: H3 :: H4 :: M :: P :: nil) >= 4).\n{\n\tassert(HH1H2H3H4mtmp : rk(H1 :: H2 :: H3 :: H4 :: nil) >= 4) by (solve_hyps_min HH1H2H3H4eq HH1H2H3H4m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (H1 :: H2 :: H3 :: H4 :: nil) (H1 :: H2 :: H3 :: H4 :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (H1 :: H2 :: H3 :: H4 :: nil) (H1 :: H2 :: H3 :: H4 :: M :: P :: nil) 4 4 HH1H2H3H4mtmp 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(HH1H2H3H4MPM4 : rk(H1 :: H2 :: H3 :: H4 :: M :: P :: nil) <= 4).\n{\n\tassert(HH1H2H3H4MMtmp : rk(H1 :: H2 :: H3 :: H4 :: M :: nil) <= 4) by (solve_hyps_max HH1H2H3H4Meq HH1H2H3H4MM4).\n\tassert(HH1H2H3H4PMtmp : rk(H1 :: H2 :: H3 :: H4 :: P :: nil) <= 4) by (solve_hyps_max HH1H2H3H4Peq HH1H2H3H4PM4).\n\tassert(HH1H2H3H4mtmp : rk(H1 :: H2 :: H3 :: H4 :: nil) >= 4) by (solve_hyps_min HH1H2H3H4eq HH1H2H3H4m4).\n\tassert(Hincl : incl (H1 :: H2 :: H3 :: H4 :: nil) (list_inter (H1 :: H2 :: H3 :: H4 :: M :: nil) (H1 :: H2 :: H3 :: H4 :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (H1 :: H2 :: H3 :: H4 :: M :: P :: nil) (H1 :: H2 :: H3 :: H4 :: M :: H1 :: H2 :: H3 :: H4 :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (H1 :: H2 :: H3 :: H4 :: M :: H1 :: H2 :: H3 :: H4 :: P :: nil) ((H1 :: H2 :: H3 :: H4 :: M :: nil) ++ (H1 :: H2 :: H3 :: H4 :: P :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (H1 :: H2 :: H3 :: H4 :: M :: nil) (H1 :: H2 :: H3 :: H4 :: P :: nil) (H1 :: H2 :: H3 :: H4 :: nil) 4 4 4 HH1H2H3H4MMtmp HH1H2H3H4PMtmp HH1H2H3H4mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\nassert(HH1H2H3H4MPM : rk(H1 :: H2 :: H3 :: H4 :: M :: P ::  nil) <= 5) by (apply rk_upper_dim).\nassert(HH1H2H3H4MPm : rk(H1 :: H2 :: H3 :: H4 :: M :: P ::  nil) >= 1) by (solve_hyps_min HH1H2H3H4MPeq HH1H2H3H4MPm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LAMNP *)\n(* dans la couche 0 *)\nLemma LABCMNP : forall A B C H1 H2 H3 H4 M N P ,\nrk(A :: B :: C ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 ::  nil) = 4 -> rk(A :: H1 :: H2 :: H3 :: H4 ::  nil) = 5 ->\nrk(A :: B :: C :: M ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 :: M ::  nil) = 4 -> rk(A :: B :: C :: N ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: N ::  nil) = 4 -> rk(M :: N ::  nil) = 2 -> rk(A :: B :: C :: P ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: P ::  nil) = 4 -> rk(A :: B :: C :: M :: N :: P ::  nil) = 3.\nProof.\n\nintros A B C H1 H2 H3 H4 M N P \nHABCeq HH1H2H3H4eq HAH1H2H3H4eq HABCMeq HH1H2H3H4Meq HABCNeq HH1H2H3H4Neq HMNeq HABCPeq HH1H2H3H4Peq\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 3 <= rg <= 5 pour ABCMNP requis par la preuve de (?)ABCMNP pour la règle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 5 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 : -2 4 et 5*)\nassert(HABCMNPM4 : rk(A :: B :: C :: M :: N :: P :: nil) <= 4).\n{\n\tassert(HNMtmp : rk(N :: nil) <= 1) by (solve_hyps_max HNeq HNM1).\n\tassert(HABCMPeq : rk(A :: B :: C :: M :: P :: nil) = 3) by (apply LABCMP with (A := A) (B := B) (C := C) (H1 := H1) (H2 := H2) (H3 := H3) (H4 := H4) (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(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (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) (N :: A :: B :: C :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (N :: A :: B :: C :: M :: P :: nil) ((N :: nil) ++ (A :: B :: C :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (N :: nil) (A :: B :: C :: M :: P :: nil) (nil) 1 3 0 HNMtmp HABCMPMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;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) (H1 := H1) (H2 := H2) (H3 := H3) (H4 := H4) (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) <= 5) 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 LAMNP : forall A B C H1 H2 H3 H4 M N P ,\nrk(A :: B :: C ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 ::  nil) = 4 -> rk(A :: H1 :: H2 :: H3 :: H4 ::  nil) = 5 ->\nrk(A :: B :: C :: M ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 :: M ::  nil) = 4 -> rk(A :: B :: C :: N ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: N ::  nil) = 4 -> rk(M :: N ::  nil) = 2 -> rk(A :: B :: C :: P ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: P ::  nil) = 4 -> rk(A :: M :: N :: P ::  nil) = 3.\nProof.\n\nintros A B C H1 H2 H3 H4 M N P \nHABCeq HH1H2H3H4eq HAH1H2H3H4eq HABCMeq HH1H2H3H4Meq HABCNeq HH1H2H3H4Neq HMNeq HABCPeq HH1H2H3H4Peq\n.\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour AMNP requis par la preuve de (?)AMNP pour la règle 6  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour AMNP requis par la preuve de (?)AMNP pour la règle 5  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 5 pour ABCMNP requis par la preuve de (?)AMNP pour la règle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 5 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(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour AMNP requis par la preuve de (?)AMNP pour la règle 4  *)\n(* Application de la règle 4 code (7 ou 8 dans la thèse) concerne B (rang 2 et 4) *)\n(* marque des antécédents AUB AiB A: 5 4 et -4*)\n(* ensembles concernés AUB : A :: B :: C :: M :: N :: P ::  de rang :  3 et 5 \t AiB : A :: M ::  de rang :  2 et 2 \t A : A :: B :: C :: M ::   de rang : 3 et 3 *)\nassert(HAMNPm2 : rk(A :: M :: N :: P :: nil) >= 2).\n{\n\tassert(HABCMMtmp : rk(A :: B :: C :: M :: nil) <= 3) by (solve_hyps_max HABCMeq HABCMM3).\n\tassert(HABCMNPmtmp : rk(A :: B :: C :: M :: N :: P :: nil) >= 3) by (solve_hyps_min HABCMNPeq HABCMNPm3).\n\tassert(HAMeq : rk(A :: M :: nil) = 2) by (apply LAM with (A := A) (B := B) (C := C) (H1 := H1) (H2 := H2) (H3 := H3) (H4 := H4) (M := M) (N := N) (P := P) ; assumption).\n\tassert(HAMmtmp : rk(A :: M :: nil) >= 2) by (solve_hyps_min HAMeq HAMm2).\n\tassert(Hincl : incl (A :: M :: nil) (list_inter (A :: B :: C :: M :: nil) (A :: M :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: C :: M :: N :: P :: nil) (A :: B :: C :: M :: A :: M :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: B :: C :: M :: A :: M :: N :: P :: nil) ((A :: B :: C :: M :: nil) ++ (A :: M :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABCMNPmtmp;try rewrite HT2 in HABCMNPmtmp.\n\tassert(HT := rule_4 (A :: B :: C :: M :: nil) (A :: M :: N :: P :: nil) (A :: M :: nil) 3 2 3 HABCMNPmtmp HAMmtmp HABCMMtmp 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(HAMNPm3 : rk(A :: M :: N :: P :: nil) >= 3).\n{\n\tassert(HAMNeq : rk(A :: M :: N :: nil) = 3) by (apply LAMN with (A := A) (B := B) (C := C) (H1 := H1) (H2 := H2) (H3 := H3) (H4 := H4) (M := M) (N := N) (P := P) ; assumption).\n\tassert(HAMNmtmp : rk(A :: M :: N :: nil) >= 3) by (solve_hyps_min HAMNeq HAMNm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (A :: M :: N :: nil) (A :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: M :: N :: nil) (A :: M :: N :: P :: nil) 3 3 HAMNmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la règle 6 (code, 3 ou 4 dans la thèse) *)\n(* marque de l'antécédent : 4 *)\nassert(HAMNPM3 : rk(A :: M :: N :: P :: nil) <= 3).\n{\n\tassert(HABCMNPeq : rk(A :: B :: C :: M :: N :: P :: nil) = 3) by (apply LABCMNP with (A := A) (B := B) (C := C) (H1 := H1) (H2 := H2) (H3 := H3) (H4 := H4) (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(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (A :: M :: N :: P :: nil) (A :: B :: C :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (A :: M :: N :: P :: nil) (A :: B :: C :: M :: N :: P :: nil) 3 3 HABCMNPMtmp Hcomp Hincl);apply HT.\n}\n\nassert(HAMNPM : rk(A :: M :: N :: P ::  nil) <= 4) (* dim : 4 *) by (solve_hyps_max HAMNPeq HAMNPM4).\nassert(HAMNPm : rk(A :: M :: N :: P ::  nil) >= 1) by (solve_hyps_min HAMNPeq HAMNPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LH1H2H3H4MNP : forall A B C H1 H2 H3 H4 M N P ,\nrk(A :: B :: C ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 ::  nil) = 4 -> rk(A :: H1 :: H2 :: H3 :: H4 ::  nil) = 5 ->\nrk(A :: B :: C :: M ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 :: M ::  nil) = 4 -> rk(A :: B :: C :: N ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: N ::  nil) = 4 -> rk(M :: N ::  nil) = 2 -> rk(A :: B :: C :: P ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: P ::  nil) = 4 -> rk(H1 :: H2 :: H3 :: H4 :: M :: N :: P ::  nil) = 4.\nProof.\n\nintros A B C H1 H2 H3 H4 M N P \nHABCeq HH1H2H3H4eq HAH1H2H3H4eq HABCMeq HH1H2H3H4Meq HABCNeq HH1H2H3H4Neq HMNeq HABCPeq HH1H2H3H4Peq\n.\n\n(* dans constructProofaux(), preuve de 4 <= rg <= 5 pour H1H2H3H4MNP requis par la preuve de (?)H1H2H3H4MNP pour la règle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 5 pour H1H2H3H4MNP requis par la preuve de (?)H1H2H3H4MNP 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(HH1H2H3H4MNPm4 : rk(H1 :: H2 :: H3 :: H4 :: M :: N :: P :: nil) >= 4).\n{\n\tassert(HH1H2H3H4mtmp : rk(H1 :: H2 :: H3 :: H4 :: nil) >= 4) by (solve_hyps_min HH1H2H3H4eq HH1H2H3H4m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (H1 :: H2 :: H3 :: H4 :: nil) (H1 :: H2 :: H3 :: H4 :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (H1 :: H2 :: H3 :: H4 :: nil) (H1 :: H2 :: H3 :: H4 :: M :: N :: P :: nil) 4 4 HH1H2H3H4mtmp 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(HH1H2H3H4MNPM4 : rk(H1 :: H2 :: H3 :: H4 :: M :: N :: P :: nil) <= 4).\n{\n\tassert(HH1H2H3H4NMtmp : rk(H1 :: H2 :: H3 :: H4 :: N :: nil) <= 4) by (solve_hyps_max HH1H2H3H4Neq HH1H2H3H4NM4).\n\tassert(HH1H2H3H4MPeq : rk(H1 :: H2 :: H3 :: H4 :: M :: P :: nil) = 4) by (apply LH1H2H3H4MP with (A := A) (B := B) (C := C) (H1 := H1) (H2 := H2) (H3 := H3) (H4 := H4) (M := M) (N := N) (P := P) ; assumption).\n\tassert(HH1H2H3H4MPMtmp : rk(H1 :: H2 :: H3 :: H4 :: M :: P :: nil) <= 4) by (solve_hyps_max HH1H2H3H4MPeq HH1H2H3H4MPM4).\n\tassert(HH1H2H3H4mtmp : rk(H1 :: H2 :: H3 :: H4 :: nil) >= 4) by (solve_hyps_min HH1H2H3H4eq HH1H2H3H4m4).\n\tassert(Hincl : incl (H1 :: H2 :: H3 :: H4 :: nil) (list_inter (H1 :: H2 :: H3 :: H4 :: N :: nil) (H1 :: H2 :: H3 :: H4 :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (H1 :: H2 :: H3 :: H4 :: M :: N :: P :: nil) (H1 :: H2 :: H3 :: H4 :: N :: H1 :: H2 :: H3 :: H4 :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (H1 :: H2 :: H3 :: H4 :: N :: H1 :: H2 :: H3 :: H4 :: M :: P :: nil) ((H1 :: H2 :: H3 :: H4 :: N :: nil) ++ (H1 :: H2 :: H3 :: H4 :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (H1 :: H2 :: H3 :: H4 :: N :: nil) (H1 :: H2 :: H3 :: H4 :: M :: P :: nil) (H1 :: H2 :: H3 :: H4 :: nil) 4 4 4 HH1H2H3H4NMtmp HH1H2H3H4MPMtmp HH1H2H3H4mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\nassert(HH1H2H3H4MNPM : rk(H1 :: H2 :: H3 :: H4 :: M :: N :: P ::  nil) <= 5) by (apply rk_upper_dim).\nassert(HH1H2H3H4MNPm : rk(H1 :: H2 :: H3 :: H4 :: M :: N :: P ::  nil) >= 1) by (solve_hyps_min HH1H2H3H4MNPeq HH1H2H3H4MNPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LAH1H2H3H4MNP : forall A B C H1 H2 H3 H4 M N P ,\nrk(A :: B :: C ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 ::  nil) = 4 -> rk(A :: H1 :: H2 :: H3 :: H4 ::  nil) = 5 ->\nrk(A :: B :: C :: M ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 :: M ::  nil) = 4 -> rk(A :: B :: C :: N ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: N ::  nil) = 4 -> rk(M :: N ::  nil) = 2 -> rk(A :: B :: C :: P ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: P ::  nil) = 4 -> rk(A :: H1 :: H2 :: H3 :: H4 :: M :: N :: P ::  nil) = 5.\nProof.\n\nintros A B C H1 H2 H3 H4 M N P \nHABCeq HH1H2H3H4eq HAH1H2H3H4eq HABCMeq HH1H2H3H4Meq HABCNeq HH1H2H3H4Neq HMNeq HABCPeq HH1H2H3H4Peq\n.\n\n(* dans constructProofaux(), preuve de 4 <= rg <= 5 pour AH1H2H3H4MNP requis par la preuve de (?)AH1H2H3H4MNP pour la règle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 5 pour AH1H2H3H4MNP requis par la preuve de (?)AH1H2H3H4MNP 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(HAH1H2H3H4MNPm4 : rk(A :: H1 :: H2 :: H3 :: H4 :: M :: N :: P :: nil) >= 4).\n{\n\tassert(HH1H2H3H4mtmp : rk(H1 :: H2 :: H3 :: H4 :: nil) >= 4) by (solve_hyps_min HH1H2H3H4eq HH1H2H3H4m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (H1 :: H2 :: H3 :: H4 :: nil) (A :: H1 :: H2 :: H3 :: H4 :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (H1 :: H2 :: H3 :: H4 :: nil) (A :: H1 :: H2 :: H3 :: H4 :: M :: N :: P :: nil) 4 4 HH1H2H3H4mtmp 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(HAH1H2H3H4MNPm5 : rk(A :: H1 :: H2 :: H3 :: H4 :: M :: N :: P :: nil) >= 5).\n{\n\tassert(HAH1H2H3H4mtmp : rk(A :: H1 :: H2 :: H3 :: H4 :: nil) >= 5) by (solve_hyps_min HAH1H2H3H4eq HAH1H2H3H4m5).\n\tassert(Hcomp : 5 <= 5) by (repeat constructor).\n\tassert(Hincl : incl (A :: H1 :: H2 :: H3 :: H4 :: nil) (A :: H1 :: H2 :: H3 :: H4 :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: H1 :: H2 :: H3 :: H4 :: nil) (A :: H1 :: H2 :: H3 :: H4 :: M :: N :: P :: nil) 5 5 HAH1H2H3H4mtmp Hcomp Hincl);apply HT.\n}\n\nassert(HAH1H2H3H4MNPM : rk(A :: H1 :: H2 :: H3 :: H4 :: M :: N :: P ::  nil) <= 5) by (apply rk_upper_dim).\nassert(HAH1H2H3H4MNPm : rk(A :: H1 :: H2 :: H3 :: H4 :: M :: N :: P ::  nil) >= 1) by (solve_hyps_min HAH1H2H3H4MNPeq HAH1H2H3H4MNPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LMNP : forall A B C H1 H2 H3 H4 M N P ,\nrk(A :: B :: C ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 ::  nil) = 4 -> rk(A :: H1 :: H2 :: H3 :: H4 ::  nil) = 5 ->\nrk(A :: B :: C :: M ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 :: M ::  nil) = 4 -> rk(A :: B :: C :: N ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: N ::  nil) = 4 -> rk(M :: N ::  nil) = 2 -> rk(A :: B :: C :: P ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: P ::  nil) = 4 -> rk(M :: N :: P ::  nil) = 2.\nProof.\n\nintros A B C H1 H2 H3 H4 M N P \nHABCeq HH1H2H3H4eq HAH1H2H3H4eq HABCMeq HH1H2H3H4Meq HABCNeq HH1H2H3H4Neq HMNeq HABCPeq HH1H2H3H4Peq\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(HAMNPeq : rk(A :: M :: N :: P :: nil) = 3) by (apply LAMNP with (A := A) (B := B) (C := C) (H1 := H1) (H2 := H2) (H3 := H3) (H4 := H4) (M := M) (N := N) (P := P) ; assumption).\n\tassert(HAMNPMtmp : rk(A :: M :: N :: P :: nil) <= 3) by (solve_hyps_max HAMNPeq HAMNPM3).\n\tassert(HH1H2H3H4MNPeq : rk(H1 :: H2 :: H3 :: H4 :: M :: N :: P :: nil) = 4) by (apply LH1H2H3H4MNP with (A := A) (B := B) (C := C) (H1 := H1) (H2 := H2) (H3 := H3) (H4 := H4) (M := M) (N := N) (P := P) ; assumption).\n\tassert(HH1H2H3H4MNPMtmp : rk(H1 :: H2 :: H3 :: H4 :: M :: N :: P :: nil) <= 4) by (solve_hyps_max HH1H2H3H4MNPeq HH1H2H3H4MNPM4).\n\tassert(HAH1H2H3H4MNPeq : rk(A :: H1 :: H2 :: H3 :: H4 :: M :: N :: P :: nil) = 5) by (apply LAH1H2H3H4MNP with (A := A) (B := B) (C := C) (H1 := H1) (H2 := H2) (H3 := H3) (H4 := H4) (M := M) (N := N) (P := P) ; assumption).\n\tassert(HAH1H2H3H4MNPmtmp : rk(A :: H1 :: H2 :: H3 :: H4 :: M :: N :: P :: nil) >= 5) by (solve_hyps_min HAH1H2H3H4MNPeq HAH1H2H3H4MNPm5).\n\tassert(Hincl : incl (M :: N :: P :: nil) (list_inter (A :: M :: N :: P :: nil) (H1 :: H2 :: H3 :: H4 :: M :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: H1 :: H2 :: H3 :: H4 :: M :: N :: P :: nil) (A :: M :: N :: P :: H1 :: H2 :: H3 :: H4 :: M :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: M :: N :: P :: H1 :: H2 :: H3 :: H4 :: M :: N :: P :: nil) ((A :: M :: N :: P :: nil) ++ (H1 :: H2 :: H3 :: H4 :: M :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HAH1H2H3H4MNPmtmp;try rewrite HT2 in HAH1H2H3H4MNPmtmp.\n\tassert(HT := rule_3 (A :: M :: N :: P :: nil) (H1 :: H2 :: H3 :: H4 :: M :: N :: P :: nil) (M :: N :: P :: nil) 3 4 5 HAMNPMtmp HH1H2H3H4MNPMtmp HAH1H2H3H4MNPmtmp Hincl);apply HT.\n}\n\n\nassert(HMNPM : rk(M :: N :: P ::  nil) <= 3) (* dim : 4 *) 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 H1 H2 H3 H4 M N P ,\nrk(A :: B :: C ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 ::  nil) = 4 -> rk(A :: H1 :: H2 :: H3 :: H4 ::  nil) = 5 ->\nrk(A :: B :: C :: M ::  nil) = 3 -> rk(H1 :: H2 :: H3 :: H4 :: M ::  nil) = 4 -> rk(A :: B :: C :: N ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: N ::  nil) = 4 -> rk(M :: N ::  nil) = 2 -> rk(A :: B :: C :: P ::  nil) = 3 ->\nrk(H1 :: H2 :: H3 :: H4 :: P ::  nil) = 4 -> \n\t rk(M :: N :: P ::  nil) = 2  .\nProof.\n\nintros A B C H1 H2 H3 H4 M N P \nHABCeq HH1H2H3H4eq HAH1H2H3H4eq HABCMeq HH1H2H3H4Meq HABCNeq HH1H2H3H4Neq HMNeq HABCPeq HH1H2H3H4Peq\n.\nrepeat split.\n\n\tapply LMNP with (A := A) (B := B) (C := C) (H1 := H1) (H2 := H2) (H3 := H3) (H4 := H4) (M := M) (N := N) (P := P) ; assumption.\nQed .\n", "meta": {"author": "pascalschreck", "repo": "MatroidIncidenceProver", "sha": "e492d375a2264e6c908c9c47fe719c39e3f847f8", "save_path": "github-repos/coq/pascalschreck-MatroidIncidenceProver", "path": "github-repos/coq/pascalschreck-MatroidIncidenceProver/MatroidIncidenceProver-e492d375a2264e6c908c9c47fe719c39e3f847f8/matroidbasedIGprover/matroid_C_Coq/DevC/exemples/DG4d/etape1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.28875230577903194}}
{"text": "(**********************************************************************)\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 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(* 021101301 USA                                                     *)\n(**********************************************************************)\n\n(**********************************************************************)\n(*                    Extensions.v                                    *)\n(*                                                                    *)\n(*                     Barry Jay                                      *)\n(*                                                                    *)\n(**********************************************************************)\n\n\nRequire Import Omega Max Bool List.\nRequire Import IntensionalLib.SF_calculus.Test.  \nRequire Import IntensionalLib.SF_calculus.General.  \nRequire Import IntensionalLib.Wave_as_SF.SF_Terms.  \nRequire Import IntensionalLib.Wave_as_SF.SF_Tactics.  \nRequire Import IntensionalLib.Wave_as_SF.SF_reduction.  \nRequire Import IntensionalLib.Wave_as_SF.SF_Normal.  \nRequire Import IntensionalLib.Wave_as_SF.SF_Closed.  \nRequire Import IntensionalLib.Wave_as_SF.Substitution.  \nRequire Import IntensionalLib.Wave_as_SF.SF_Eval.  \nRequire Import IntensionalLib.Wave_as_SF.Star.  \nRequire Import IntensionalLib.Wave_as_SF.Wait.  \nRequire Import IntensionalLib.Wave_as_SF.Fixpoints.  \nRequire Import IntensionalLib.Wave_as_SF.Wave_Factor.  \nRequire Import IntensionalLib.Wave_as_SF.Wave_Factor2.  \nRequire Import IntensionalLib.Wave_as_SF.Equal.  \n\nLemma aux1: forall p q, S(S(S(S(S p)))) <= q ->\n                        pred (pred (pred (q - S p))) = q - S (S (S (S p))). \n  intros.\n  replace (pred (q - S p)) with (q - (S (S p)))  by omega.\n  replace (pred (q - S(S p))) with (q - (S (S (S p))))  by omega.\nomega.\nQed.\n\nLemma aux3 : forall M, pred (max match maxvar (lift 1 M) with\n             | 0 => 1\n             | S m' => S m'\n             end 1) = maxvar M - 0. \nProof.\nintros. rewrite max_pred. simpl. rewrite max_zero. \n  replace (maxvar M - 0) with (maxvar M) by omega.\nassert(maxvar M = 0 \\/ maxvar M <> 0) by decide equality. \ninversion H. unfold lift; rewrite lift_rec_closed. rewrite H0; auto. auto. \nclear H. \nassert(maxvar (lift 1 M) = S(maxvar M)). \ninduction M; split_all. gen_case H0 n. \nsimpl in *. noway.  \nsimpl in *. \nassert (maxvar M1 = 0 -> maxvar (lift_rec M1 0 1) = 0) by (split_all; rewrite lift_rec_closed; auto).\n\ngen3_case H0 H IHM1  (maxvar M1) . rewrite H; auto. \nunfold lift in *; rewrite IHM1; auto. \nassert (maxvar M2 = 0 -> maxvar (lift_rec M2 0 1) = 0) by (split_all; rewrite lift_rec_closed; auto).\ngen3_case H0 H1 IHM2  (maxvar M2) . rewrite H1; auto. \nrewrite IHM2; auto. \nrewrite H. auto. \nQed. \n\nLemma max_aux: forall m n, max m n = m \\/ max m n = n . \nProof. \ninduction m; split_all. induction n; split_all. \nassert(max m n = m \\/ max m n = n) by eapply2 IHm. \ninversion H; rewrite H0; auto. \nQed. \n\nLemma maxvar_lift_rec_compare: \nforall M p  n k, p>= maxvar M  -> p+k >= maxvar (lift_rec M n k).\nProof.\ninduction M; split_all. \nunfold relocate. elim(test n0 n); split_all.  omega. omega. omega. \nelim(max_is_max (maxvar M1) (maxvar M2)). intros. \neapply2 max_max2. \neapply2 IHM1. omega. \neapply2 IHM2. omega. \nQed. \n\n\nLemma lift_rec_misses: \nforall M n k, n >= maxvar M  -> lift_rec M n k = M. \nProof.\ninduction M; split_all. relocate_lt. auto. \nassert(max (maxvar M1) (maxvar M2) >= maxvar M1 /\\ max (maxvar M1) (maxvar M2) >= maxvar M2)\nby eapply2 max_is_max. split_all. \nrewrite IHM1; try omega. rewrite IHM2; auto; omega. \nQed.\n \nLemma maxvar_lift_rec_compare2: \nforall M N n k, maxvar M >= maxvar N -> maxvar (lift_rec M n k) >= maxvar (lift_rec N n k). \nProof.\ninduction M; split_all. \ngen_case H N.\n(* 5 *)  \nunfold relocate. elim(test n0 n); split_all. elim(test n0 n1); split_all; try noway. \nomega. omega. elim(test n0 n1); split_all; try noway. \n(* 4 *) \nomega. \n(* 3 *) \nunfold relocate. elim(test n0 n); split_all. \nassert(max (maxvar s) (maxvar s0) >= maxvar s /\\ max (maxvar s) (maxvar s0) >= maxvar s0) by eapply2 max_is_max. \nsplit_all. \nreplace (S(k+n)) with (S n + k) by omega. \neapply2 max_max2; eapply2 maxvar_lift_rec_compare; omega. \nassert(max (maxvar s) (maxvar s0) >= maxvar s /\\ max (maxvar s) (maxvar s0) >= maxvar s0) by eapply2 max_is_max. \nsplit_all. \nrewrite ! lift_rec_misses; try omega. \n(* 2 *) \nrewrite lift_rec_closed; auto. omega. \n(* 1 *) \nassert(max (maxvar M1) (maxvar M2)  = maxvar M1 \\/ \nmax (maxvar M1) (maxvar M2) = maxvar M2) by eapply2 max_aux. \nassert(max (maxvar (lift_rec M1 n k)) (maxvar (lift_rec M2 n k)) >=(maxvar (lift_rec M1 n k)) /\\ \nmax (maxvar (lift_rec M1 n k)) (maxvar (lift_rec M2 n k)) >=(maxvar (lift_rec M2 n k)))\nby eapply2 max_is_max. \nsplit_all. inversion H0. \nassert(maxvar (lift_rec M1 n k) >= maxvar (lift_rec N n k)). eapply2 IHM1; omega.  omega. \nassert(maxvar (lift_rec M2 n k) >= maxvar (lift_rec N n k)). eapply2 IHM2; omega.  omega. \nQed. \n\nLemma aux4 : forall M p,\n     match\n       pred\n         (pred\n            (maxvar (lift_rec M p 3) - p))\n     with\n     | 0 => 0\n     | S m' => m'\n     end = maxvar M - p\n.\nProof.\ninduction M; split_all.\n(* 2 *) \n case p; split_all. relocate_lt. \nsimpl. auto. \nunfold relocate. \nelim(test (S n0) n); split_all. \n(* 3 *) \ngen_case a n0. omega. \ngen_case a n1. gen_case a n. omega. \ngen_case a n2. gen_case a n. gen_case a n3. omega. \nunfold minus at 2; fold minus. \nassert(forall m n, m - (S n) = pred (m-n)) by (intros; omega). \nrewrite ! H. unfold pred at 3;  auto.\ncase (pred(pred (n-n3))); auto.  \n(* 2 *) \nassert(pred(pred(n-n0)) = 0) by omega. \nrewrite H. omega. \n(* 1 *) \nassert(max (maxvar M1) (maxvar M2) = maxvar M1 \\/ max (maxvar M1) (maxvar M2) = maxvar M2) by \neapply2 max_aux. \ninversion H.  rewrite H0. \nassert( maxvar(lift_rec M1 p 3) >= max (maxvar (lift_rec M1 p 3)) (maxvar (lift_rec M2 p 3))).\neapply2 max_max2. eapply2 maxvar_lift_rec_compare2. \nassert(max (maxvar M1) (maxvar M2) >= maxvar M2) by eapply2 max_is_max. \nrewrite H0 in H1. auto. \nassert(max (maxvar (lift_rec M1 p 3)) (maxvar (lift_rec M2 p 3))>= maxvar(lift_rec M1 p 3))\nby eapply2 max_is_max. \nassert(max (maxvar (lift_rec M1 p 3)) (maxvar (lift_rec M2 p 3)) = maxvar(lift_rec M1 p 3))\nby omega. \nrewrite H3. eapply2 IHM1. \n(* 1 *) \nassert( maxvar(lift_rec M2 p 3) >= max (maxvar (lift_rec M1 p 3)) (maxvar (lift_rec M2 p 3))).\neapply2 max_max2. eapply2 maxvar_lift_rec_compare2. \nassert(max (maxvar M1) (maxvar M2) >= maxvar M1) by eapply2 max_is_max. \nrewrite H0 in H1. auto. \nassert(max (maxvar (lift_rec M1 p 3)) (maxvar (lift_rec M2 p 3))>= maxvar(lift_rec M2 p 3))\nby eapply2 max_is_max. \nassert(max (maxvar (lift_rec M1 p 3)) (maxvar (lift_rec M2 p 3)) = maxvar(lift_rec M2 p 3))\nby omega. \nrewrite H3. rewrite H0. eapply2 IHM2. \nQed. \n\n\n\nDefinition swap M := App (App (Op Node) (App (Op Node) (App k_op M))) i_op.\n\nLemma swap_check : forall M N, sf_red (App (swap M) N) (App N M). \nProof. \nunfold swap; split_all; eval_tac. eval_tac.\neapply succ_red. eapply app_sf_red. eapply2 k_red.  eval_tac.  \neapply2 preserves_app_sf_red;  eval_tac. \nQed. \n\n(* \nLemma star_opt_swap : \nstar_opt (swap (Ref 0)) = App (App s_op (App k_op  (App s_op i_op ))) k_op .\nProof. split_all. Qed. \n*)\n\nDefinition case_app case (P1 P2 M : SF) := \n(star_opt (App (App (App (App Fop (Ref 0)) i_op) \n                               (lift 1 (star_opt (star_opt (App (App (App (App \n                               (lift 2 (case P1 (case P2 (App k_op (App k_op M)))))\n                               (Ref 1)) \n                                                       (App k_op (App k_op (App k_op i_op))))\n                                                  (Ref 0))\n                                             (App k_op i_op)))))) \n               (swap (Ref 0)))).\n\nLtac occurs_true_tac M := \nrewrite (star_opt_occurs_true M) at 1;\n[| rewrite ! occurs_app; replace (occurs0 (Ref 0)) with true by split_all; \nrewrite ? orb_true_r; auto | discriminate]. \n\nLtac occurs_false_tac M := \nrewrite (star_opt_occurs_false M) at 1; [| split_all]. \n\n(* restore \n\nDefinition s_op := \nstar_opt (star_opt (star_opt (App (App (Ref 2) (Ref 0)) \n                                  (App (Ref 1) (Ref 0))))).\n\n\nDefinition case_app_nf case (P1 P2 M: SF) := \n(App\n        (App s_op\n           (App\n              (App s_op\n                 (App (App s_op Fop) (App k_op  i_op )))\n              (App k_op \n                 (App\n                    (App s_op\n                       (App (App s_op (App k_op  s_op))\n                          (App\n                             (App s_op\n                                (case P1\n                                   (case P2 (App k_op  (App k_op  M)))))\n                             (App k_op \n                                (App k_op \n                                   (App k_op  (App k_op  i_op )))))))\n                    (App k_op  (App k_op  (App k_op  i_op )))))))\n        (App (App s_op (App k_op  (App s_op i_op ))) k_op )). \n\nLemma case_app_val : \nforall case P1 P2 M, sf_red (case_app case P1 P2 M) (case_app_nf case P1 P2 M).\nProof. \nintros; unfold case_app. \nunfold star_opt at 3;  unfold occurs0; fold occurs0. \nunfold lift; rewrite ! occurs_lift_rec_zero. simpl. \nrewrite subst_rec_lift_rec; try omega. \nrewrite ! occurs_lift_rec_zero. simpl. \nunfold subst; rewrite subst_rec_lift_rec; try omega. \nrewrite ! occurs_lift_rec_zero. simpl. \nrewrite subst_rec_lift_rec; try omega. \nrewrite ! lift_rec_null. \neapply2 preserves_app_sf_red. \neapply2 zero_red. \nQed. \n \n\n*) \n\nLemma program_app: forall M N, program (App M N) -> program M /\\ program N.\nProof. \nunfold program; intros. inversion H. \nsimpl in *; max_out; inversion H0; split; split; auto. \nQed. \n\nFixpoint is_program M := \nmatch M with \n| Ref _ => false \n| Op _ => true \n| App (Op _) M2 => is_program M2 \n| App (App (Op _) M1) M2 => is_program M1 && is_program M2\n| _ => false \nend. \n \n\n\nLemma program_is_program: forall M, program M <-> is_program M = true. \nProof.\ninduction M; intros; auto.  \n(* 3 *) \n  split. unfold program. simpl. intro c; inversion c; discriminate. \ndiscriminate.\n(* 2 *) \nsplit; intro; unfold program; split; auto. \n(* 1 *) \ngen_case IHM1 M1. \n(* 3 *) \n  split. unfold program. simpl. intro c; inversion c.  \ngen_case H0 (maxvar M2); discriminate. \nintro; discriminate. \n(* 2 *) \nsplit. unfold program.  intro. inversion H. \neapply2 IHM2. inversion H0; simpl in H1. \nassert(status (App (Op o) M2) = Passive). \neapply2 closed_implies_passive. \nrewrite H7 in H6; discriminate. \nsplit; auto. \nintro.\nassert(program M2) by eapply2 IHM2. \n split; auto. nf_out. inversion H0; auto.  \ncase o; auto. simpl; inversion H0; auto. \n(* 1 *) \ngen_case IHM1 s. \n(* 3 *) \n  split. unfold program. simpl. intro c; inversion c.  \ngen_case H0 (maxvar s0); gen_case H0 (maxvar M2); discriminate. \nintro; discriminate. \n(* 2 *) \nsplit. unfold program.  intro. inversion H.\nassert(is_program s0 = true). \neapply2 IHM1.  split; auto. nf_out. \ninversion H0. \nassert(status (App (App (Op o) s0) M2) = Passive). \neapply2 closed_implies_passive. \nrewrite H7 in H6; discriminate. inversion H4; auto. case o; auto. \nsimpl in *; max_out. \nrewrite H2; simpl. eapply2 IHM2.\neapply2 (program_app (App (Op o) s0) M2).\nintro. \napply eq_sym in H. \nassert(true = is_program s0 /\\ true = is_program M2) by eapply2 andb_true_eq.\ninversion H0. \nassert(program M2) by eapply2 IHM2. \nassert(program (App (Op o) s0)) by eapply2 IHM1. \ninversion H3; inversion H4. inversion H7. \nsplit. \nnf_out. case o; auto. case o; auto. simpl in *. \nrewrite H6; rewrite H8; auto.\n split; auto. nf_out. case o; auto. \nsimpl in *. rewrite H6; rewrite H8; auto.\n(* 1 *) \ngen_case IHM1 s1. \n(* 3 *) \n  split. unfold program. simpl. intro c; inversion c.  \ngen_case H0 (maxvar s2); gen_case H0 (maxvar s0);  gen_case H0 (maxvar M2);  discriminate. \nintro; discriminate. \n(* 2 *) \nsplit. unfold program.  intro. inversion H. inversion H0. \nassert(status (App (App (App (Op o) s2) s0) M2) = Passive). \neapply2 closed_implies_passive. \nrewrite H7 in H6; discriminate. inversion H6. \nintro.  discriminate. \nsplit; intro. \ninversion H.  inversion H0. \nassert(status (App (App (App (App s3 s4) s2) s0) M2) = Passive). \neapply2 closed_implies_passive. \nrewrite H7 in H6; discriminate. inversion H6. \ndiscriminate.\nQed. \n \nFixpoint case P M := \n(* case P M is applied to the argument and then the default function.\n   The default function is either discared or swapped to the left. \n   Indices in P are renumbered, with binding from left to right \n*)   \n match P with\n  | Ref _ => star_opt (App k_op M)               \n  | Op _ => star_opt (App (App (App Fop (Ref 0)) (App k_op (lift 1 M))) \n                            (App k_op (App k_op (swap (Ref 0)))))\n  | App P1 P2 => \nif is_program P \nthen star_opt (App (App (App (App equal_comb (Ref 0)) P) (App k_op (lift 1 M))) (swap (Ref 0)))\nelse case_app case P1 P2 M            \n                end\n.\n\n\nLemma case_leaf: forall M R, sf_red (App (App (case (Op Node)M) (Op Node)) R) M.\nProof. \nintros; unfold case.  \neapply transitive_red. eapply preserves_app_sf_red. \neapply2 star_opt_beta. auto.  unfold_op. \nunfold subst; rewrite ! subst_rec_app. rewrite ! subst_rec_ref. \ninsert_Ref_out.\nrewrite ! (subst_rec_closed Fop). 2: simpl; auto. \nunfold lift;  rewrite subst_rec_lift_rec; try omega.\n rewrite ! lift_rec_null.\nrewrite ! (subst_rec_closed (Op Node)). 2: simpl; auto.\neapply transitive_red. eapply preserves_app_sf_red.\neapply2 factor_leaf.  auto. eval_tac. \nQed.   \n\nFixpoint pattern_size P :=\n  match P with\n    | Ref _ => 1\n    | Op _ => 0\n    | App P1 P2 => pattern_size P1 + (pattern_size P2)\n  end.\n\n\n\nLemma lift_rec_preserves_pattern_size: forall M n k, pattern_size (lift_rec M n k) = pattern_size M. \nProof. induction M; split_all. Qed. \n\nLemma pattern_size_closed: forall M, maxvar M = 0 -> pattern_size M = 0. \nProof. induction M; split_all.  noway. rewrite IHM1; max_out; rewrite IHM2; max_out. Qed. \n\n(* restore ? \nLemma pattern_size_A_k : forall k, pattern_size (A_k k) = 0. \nProof. unfold A_k. intro. rewrite pattern_size_closed. auto. rewrite A_k_closed. auto. Qed. \n\nLemma pattern_size_omega_k : forall k, pattern_size (omega_k k) = 0. \nProof. unfold omega_k. intro. rewrite pattern_size_closed. auto. \nrewrite ? maxvar_star_opt. unfold maxvar; fold maxvar. \nrewrite?  maxvar_app_comb.   unfold maxvar; fold maxvar. rewrite A_k_closed.\nrewrite?  maxvar_app_comb.   unfold maxvar; fold maxvar. auto. \nQed. \n*)\n\nLemma pattern_size_lt_maxvar: forall P, maxvar P = 0 -> pattern_size P = 0. \nProof. induction P; split_all. omega.  max_out. Qed. \n\n\nLemma aux_lift_rec: forall M p n k, \nlift_rec (lift_rec M (p + n) k) p 3 = lift_rec (lift_rec (lift_rec M (p + n) k) p 2) (p+2) 1. \nProof. \nintros. rewrite (lift_rec_lift_rec (lift_rec M (p + n) k)); try omega. auto. \nQed. \n\nLemma lift_rec_preserves_case:\n  forall P M n k, lift_rec (case P M) n k = case P (lift_rec M (pattern_size P +n) k).\nProof.\n  induction P; intros. \n  (* 3 *)\n  unfold case, maxvar. rewrite lift_rec_preserves_star_opt. unfold_op. \n  unfold lift_rec; fold lift_rec.  unfold pattern_size. auto.\n  (* 2 *)\n    unfold case, maxvar, pattern_size, swap, lift_rec; fold lift_rec.\n  case o; unfold_op. \n    rewrite lift_rec_preserves_star_opt. \nunfold lift; rewrite ! lift_rec_app.\nrewrite (lift_rec_closed Fop). 2: simpl; auto. \n unfold lift, lift_rec; fold lift_rec. relocate_lt. \nunfold plus; fold plus. \nrewrite ! lift_lift_rec; try omega. auto. \n    (* 1 *) \n    unfold case; fold case. \nassert(is_program (App P1 P2) = true \\/ is_program (App P1 P2) <> true) by decide equality. \ninversion H. rewrite H0. \n(* 2 *) \nassert(program (App P1 P2)) by eapply2 program_is_program.  inversion H1.   \nrewrite lift_rec_preserves_star_opt. \nunfold swap; unfold_op. rewrite ! lift_rec_app. \nrewrite lift_rec_closed. 2: auto. unfold lift_rec; fold lift_rec. relocate_lt.\nrewrite 2? lift_rec_closed. 2: simpl in H3; max_out. 2: simpl in H3; max_out. \nrewrite pattern_size_closed. \nunfold lift; rewrite lift_lift_rec; try omega; auto. auto. \n(* 1 *) \nassert(is_program (App P1 P2) = false).\neapply2 not_true_iff_false. \nrewrite H1. \n(* 1 *) \n    unfold case_app, swap, lift. unfold_op.\nrewrite lift_rec_preserves_star_opt.\nrewrite ! lift_rec_app. \nrewrite lift_rec_closed. 2: simpl; auto.  \n  unfold lift_rec; fold lift_rec. relocate_lt. \nrewrite ! lift_rec_preserves_star_opt.\nrewrite ! lift_rec_app.\n     rewrite ! IHP1. rewrite ! IHP2.  \nrewrite ! lift_rec_app. \nrewrite lift_rec_closed. 2: simpl; auto.  \nrewrite ! (lift_rec_closed (Op Node)). 2: simpl; auto. \n2: simpl; auto. 2: simpl; auto. \n  unfold lift_rec at 5 7. relocate_lt. \n    unfold lift_rec; fold lift_rec. relocate_lt. \nunfold pattern_size; fold pattern_size.\nunfold plus; fold plus.\nf_equal. f_equal. f_equal. f_equal. \nf_equal. f_equal. f_equal. f_equal. \nf_equal. f_equal. f_equal. f_equal. \nf_equal. \n                    \nreplace (pattern_size P1 + 0) with (pattern_size P1) by auto.\nclear.  \nrewrite (lift_rec_lift_rec M); try omega.\nreplace((pattern_size P2 +\n                                          (pattern_size P1 + S (S (S n)))))\nwith ((1+2) + (pattern_size P2 + pattern_size P1 + n)) by omega. \nrewrite (lift_lift_rec M) at 1; try omega.\nreplace(pattern_size P2 + (pattern_size P1 + 2))\nwith (2+ (pattern_size P2 + pattern_size P1)) by omega. \nrewrite (lift_lift_rec); try omega.\nrewrite (lift_rec_lift_rec (lift_rec M _ _)); try omega.\nf_equal.  f_equal. omega.  \nQed.\n\n\nLemma aux2 : forall M N p k, subst_rec (lift_rec M p (1 + 2)) N\n     (S (S (S k)) + p) =\n   lift_rec (subst_rec M N (k + p))\n     p (1 + 2). \nProof. \nintros. unfold plus; fold plus. replace (S(S(S (k+ p)))) with (3+ (k+p)) by omega. \nrewrite subst_rec_lift_rec1; try omega. auto. \nQed. \n   \nLemma subst_rec_preserves_case:\n  forall P M N k, subst_rec (case P M) N k = case P (subst_rec M N (k+ pattern_size P)).\nProof.\n  induction P; intros. \n  (* 3 *)\n  unfold case, maxvar, pattern_size. rewrite subst_rec_preserves_star_opt.\n  unfold_op; unfold subst_rec; fold subst_rec.  replace (k+1) with (S k) by omega; auto. \n  (* 2 *)\n  unfold case, maxvar, swap. case o; unfold_op.  \n rewrite subst_rec_preserves_star_opt. \nrewrite ! subst_rec_app.\nrewrite subst_rec_closed. 2: simpl; omega.\nrewrite ! (subst_rec_closed (Op Node)). 2: simpl; omega.  \n  unfold subst_rec; fold subst_rec.\ninsert_Ref_out. \nunfold lift. rewrite (subst_rec_lift_rec1 M); try omega.\nunfold pattern_size; fold pattern_size.  \n  replace (k+0) with k by omega. auto.  \n  (* 1 *) \n  unfold case; fold case.\nassert(is_program (App P1 P2) = true \\/ is_program (App P1 P2) <> true) by decide equality. \ninversion H. rewrite H0. \n(* 2 *) \nassert(program (App P1 P2)) by eapply2 program_is_program.  inversion H1.   \nrewrite subst_rec_preserves_star_opt. \nunfold swap; unfold_op; rewrite ! subst_rec_app. \nrewrite subst_rec_closed. 2: rewrite equal_comb_closed; omega. \nunfold subst_rec; fold subst_rec. insert_Ref_out.  \nrewrite 2? subst_rec_closed. 2: simpl in H3; max_out. 2: simpl in H3; max_out. \nrewrite pattern_size_closed. 2: auto.  \nunfold lift; rewrite subst_rec_lift_rec1; try omega. \nreplace (k+0) with k by omega; auto.  \n(* 1 *) \nassert(is_program (App P1 P2) = false).\neapply2 not_true_iff_false. \nrewrite H1. \n(* 1 *) \n  unfold case_app. \nrewrite subst_rec_preserves_star_opt. \nrewrite ! subst_rec_app.\nrewrite subst_rec_closed. 2: simpl; omega. \nunfold lift; rewrite subst_rec_lift_rec1. 2: omega.   \n  unfold subst_rec; fold subst_rec. insert_Ref_out.\nrewrite ! subst_rec_preserves_star_opt. \nrewrite ! lift_rec_preserves_star_opt.\nrewrite ! subst_rec_app. \nrewrite ! lift_rec_preserves_case. \nrewrite ! (subst_rec_closed k_op). 2: simpl; omega.\nunfold subst_rec; fold subst_rec. \ninsert_Ref_out.   \nrewrite ! (subst_rec_closed i_op). 2: unfold_op; simpl; omega.\n2: unfold_op; simpl; omega.\n  rewrite IHP1. rewrite IHP2.  \n  unfold subst_rec; fold subst_rec. \nunfold pattern_size; fold pattern_size.\nrewrite ! lift_rec_app. \nrewrite ! lift_rec_preserves_case.\nrewrite ! (lift_rec_closed k_op). 2: simpl; omega.  2: simpl; omega. \nrewrite ! subst_rec_app.\nrewrite ! (subst_rec_closed k_op). 2: simpl; omega. \nrewrite ! lift_rec_app.\nrewrite ! (lift_rec_closed k_op). 2: simpl; omega.\nunfold swap, subst_rec; fold subst_rec. \nunfold lift_rec; fold lift_rec. relocate_lt.\ninsert_Ref_out. \nrewrite ! (subst_rec_closed i_op). 2: simpl; omega. \nrewrite ! (subst_rec_closed k_op). 2: simpl; omega. \nf_equal. f_equal. f_equal. f_equal. \nf_equal. f_equal. f_equal. f_equal. \nf_equal. f_equal. f_equal. f_equal. \nf_equal. \nrewrite (lift_rec_lift_rec); try omega.\nreplace (S (S k) + pattern_size P1 + pattern_size P2) with \n(2 + (pattern_size P2 + pattern_size P1 + k)) by omega. \nrewrite subst_rec_lift_rec1; try omega. \nrewrite lift_rec_lift_rec; try omega.     \nreplace  (k+ (pattern_size P1 + (pattern_size P2))) \n    with (pattern_size P2 + pattern_size P1 + k)\n      by omega. \nauto. \nQed.\n\n\nInductive pattern_normal : nat -> SF -> Prop :=\n| pnf_normal : forall j M, normal M -> pattern_normal j M\n(*  pattern_normal j (Ref n)\n| pnFop : forall j o, pattern_normal j (Op o)\n| pnf_active : forall j M1 M2, normal M1 -> normal j M2 -> \n                              status (App M1 M2) = Active -> \n                              pattern_normal j (App M1 M2)  \n*) \n| pnf_compound : forall j M1 M2, pattern_normal j M1 -> pattern_normal j M2 -> \n                              compound (App M1 M2) -> pattern_normal j (App M1 M2)\n| pnf_active : forall j M1 M2, pattern_normal j M1 -> pattern_normal j M2 -> \n                              status (App M1 M2) = Active -> pattern_normal j (App M1 M2)\n| pnf_break : forall j M1 M2, pattern_normal j M1 -> pattern_normal j M2 -> \n                              0 < maxvar M2 -> maxvar M2 <= j -> \n                              pattern_normal j (App M1 M2) \n(* actually, it is enough that one of the pattern variables occurs in M2 *) \n.\n\n(* \nLemma pattern_normal_1_occurs : \nforall M, pattern_normal 1 M -> \nnormal M \\/ exists M1 M2, M = App M1 M2 /\\ occurs0 M2 = true. \nProof.\ninduction M; split_all; try discriminate.  inversion H; subst.  auto. \nright; exists M1; exist M2. split; auto. \nclear - H5 H6. \ninduction M2; split_all; simpl in *. \nassert(n= 0) by omega. subst. auto. noway. \nassert(0< maxvar M2_1 \\/ 0< maxvar M2_2). \n\ngen_case H5 (maxvar M2_1);  gen_case H5 (maxvar M2_2). \nleft; omega. inversion H. \nrewrite IHM2_1; auto. \ngen_case H6 (maxvar M2_1). gen_case H6 (maxvar M2_2).\ngen_case H6 n.  gen_case H6 n0. noway. \nrewrite IHM2_2; auto. apply orb_true_r.  \ngen_case H6 (maxvar M2_1). gen_case H6 (maxvar M2_2).\ngen_case H6 n.  gen_case H6 n0. noway. \nQed. \n*) \n\nLemma pattern_normal_closed: \nforall M, maxvar M = 0 -> forall j, pattern_normal j M -> normal M. \nProof. \ninduction M; split_all. max_out. inversion H0; subst; auto.\neapply2 nf_compound. \nassert(status (App M1 M2) = Passive). \neapply2 (closed_implies_passive).  simpl; rewrite H1; rewrite H2; auto. \nrewrite H in H7; discriminate. \n   noway. \nQed. \n\nLemma occurs_maxvar_1: forall M, maxvar M = 1 -> occurs0 M = true.\nProof.\ninduction M; split_all. inversion H; subst. auto. noway. \ngen3_case IHM1 IHM2 H (maxvar M1). \nrewrite IHM2. apply orb_true_r. auto. \ngen3_case IHM1 IHM2 H (maxvar M2). \nrewrite IHM1. auto. auto. \ngen3_case IHM1 IHM2 H n. \nrewrite IHM1. auto. auto. \ngen3_case IHM1 IHM2 H n0. \nrewrite IHM2.  apply orb_true_r. auto. noway. \nQed. \n \n\n\nLemma occurs_false_subst_compound: \nforall M N, occurs0 M = false -> compound (subst_rec M N 0) -> compound M. \nProof.\ninduction M; split_all.\ngen2_case H H0 n.  discriminate. generalize H0; insert_Ref_out; intro. \ninversion H1.\nrewrite orb_false_iff in H. inversion H. \ninversion H0; subst. \ngen2_case H1 H4 M1.  gen2_case H1 H4 n. discriminate. \ngeneralize H4; insert_Ref_out; intro. discriminate. \ninversion H4; subst; auto. case o; auto.   discriminate.\ngen2_case H1 H4 M1.  gen2_case H1 H4 n. discriminate. \ngeneralize H4; insert_Ref_out; intro. discriminate. \ndiscriminate.  \ngen2_case H1 H4 s.  gen2_case H1 H4 n. discriminate. \ngeneralize H4; insert_Ref_out; intro. discriminate. \ninversion H4; subst; auto. case o; auto.   discriminate.\nQed. \n\n\nLemma occurs_false_subst_active: \nforall M N, occurs0 M = false -> status (subst_rec M N 0) = status M. \nProof.\nrank_tac. \ninduction p; split_all. assert (rank M >0) by eapply2 rank_positive. noway. \ngeneralize H H0; clear H H0; case M; intros. \n(* 3 *) \ngen_case H0 n.  discriminate.\n(* 2 *) \nsplit_all.\n(* 1 *)  \nsimpl in H0.  \nrewrite orb_false_iff in H0. inversion H0. clear H0 H2. \ngeneralize H H1; clear H H1; case s; intros. \n(* 3 *) \ngen_case H1 n.  discriminate.\n(* 2 *) \nsplit_all.\n(* 1 *)  \nsimpl in H1.  \nrewrite orb_false_iff in H1. inversion H1. \ngeneralize H H0; clear H H0; case s1; intros. \n(* 3 *) \ngen_case H0 n.  discriminate.\n(* 2 *) \nsplit_all.\n(* 1 *)  \nsimpl in H0.  \nrewrite orb_false_iff in H0. inversion H0. \ngeneralize H H3; clear H H3; case s3; intros. \n(* 3 *) \ngen_case H3 n.  discriminate.\n(* 2 *) \ngen_case H o. eapply2 IHp. simpl in *; omega. \n(* 1 *)  \nsimpl in H3.  \nrewrite orb_false_iff in H3. inversion H3. \nunfold subst_rec; fold subst_rec.\nreplace (status (App (App (App (App s5 s6) s4) s2) s0))\nwith (status (App (App (App s5 s6) s4) s2)) by auto. \nreplace (status\n  (App (App (App (App (subst_rec s5 N 0) (subst_rec s6 N 0)) (subst_rec s4 N 0)) (subst_rec s2 N 0))\n (subst_rec s0 N 0)))\nwith (status  (subst_rec (App (App (App s5 s6) s4) s2) N 0)) by auto. \neapply2 IHp. simpl in *; omega.  simpl in *; auto. \nrewrite H2; rewrite H4; rewrite H5; rewrite H6; auto.\nQed. \n \n\n\nLemma occurs_false_subst_normal2: \nforall M N, occurs0 M = false -> normal (subst_rec M N 0) -> normal M. \nProof.\ninduction M; split_all.\ninversion H0; subst. rewrite orb_false_iff in H. inversion H. \neapply2 nf_active.      \nreplace(App (subst_rec M1 N 0) (subst_rec M2 N 0)) with (subst_rec (App M1 M2) N 0)  in H5 by auto. \nrewrite occurs_false_subst_status in H5. auto. split_all.\nrewrite H1; rewrite H2; auto. \nrewrite orb_false_iff in H. inversion H. \napply nf_compound. eapply2 IHM1. eapply2 IHM2. \nreplace(App (subst_rec M1 N 0) (subst_rec M2 N 0)) with (subst_rec (App M1 M2) N 0)  in H5 by auto. \napply occurs_false_subst_compound in H5. auto. \nsimpl; rewrite H1; rewrite H2; auto. \nQed.\n\nLemma normal_star_opt_app: \nforall M1 M2, occurs0 (App M1 M2)  = true \n-> normal (star_opt M1) -> normal (star_opt M2) -> \nnormal (star_opt (App M1 M2)).\nProof.\nintros.  unfold star_opt; fold star_opt. simpl in H. \nrewrite orb_true_iff in H.  inversion H. rewrite H2. \neapply2 nf_compound. \nassert(occurs0 M1 = true \\/ occurs0 M1 <> true) by decide equality. \ninversion H3. \n(* 2 *) \nrewrite H4. eapply2 nf_compound.\n(* 1 *)  \nassert(occurs0 M1 = false). gen_case H4 (occurs0 M1). \nassert False by eapply2 H4; noway. \nrewrite H5. \nrewrite (star_opt_occurs_false) in H0. 2: auto. \ninversion H0; subst. \ninversion H10. \ngen2_case H1 H2 M2. \ngen2_case H1 H2 n; discriminate. discriminate. \nrewrite H2. \nunfold_op; eapply2 nf_compound. \nrewrite star_opt_occurs_false; auto.\nQed. \n\n(* delete \nLemma pattern_normal_subst_occurs_false: \nforall M j, occurs0 M = false -> pattern_normal j M  -> \npattern_normal (pred j) (subst M s_op). \nProof. \ninduction M; split_all. \ngen2_case H H0 n; unfold subst, subst_rec; insert_Ref_out. \ndiscriminate. eapply2 pnf_normal. \nunfold subst, subst_rec; eapply2 pnf_normal. \nrewrite orb_false_iff in H. inversion H. \ninversion H0; subst. \neapply2 pnf_normal. \nunfold subst. eapply2 occurs_false_subst_normal. \nsimpl; rewrite H1; rewrite H2; auto.\neapply2 pnf_compound.  fold subst_rec.  \neapply2 occurs_false_subst_normal. fold subst_rec.\n assert(compound (subst_rec (App M1 M2) s_op 0)).  \n(eapply2 subst_rec_preserves_compounds).\nsimpl in H3. auto. \nunfold subst, subst_rec; fold subst_rec. \napply pnf_break; fold subst_rec.\neapply2 IHM1. eapply2 IHM2. \n  \n\nassert(maxvar M2noway. \n\n\n\n  inversion H1; subst; auto. \ne\n\nauto. \n\n*) \n\n\nLemma occurs_false_subst_rec_maxvar_gt0 : \nforall M, occurs0 M = false -> 0< maxvar M -> \nforall N, 0 < maxvar (subst_rec M N 0). \nProof.\ninduction M; split_all; subst.  \nsimpl in *. gen_case H n. discriminate. omega. \nsimpl in *. \nassert(occurs0 M1 = false /\\ occurs0 M2 = false). eapply2 orb_false_iff. \ninversion H. \nassert(0< maxvar M1 \\/ 0< maxvar M2). \ngen_case H0 (maxvar M1). left; omega. \ninversion H2; subst. inversion H1. \nassert(0< (maxvar (subst_rec M1 N 0))) by eapply2 IHM1. \nassert(Nat.max (maxvar (subst_rec M1 N 0)) (maxvar (subst_rec M2 N 0)) >= \nmaxvar (subst_rec M1 N 0)) by eapply2 max_is_max.  omega.  inversion H1. \nassert(0< (maxvar (subst_rec M2 N 0))) by eapply2 IHM2. \nassert(Nat.max (maxvar (subst_rec M1 N 0)) (maxvar (subst_rec M2 N 0)) >= \nmaxvar (subst_rec M2 N 0)) by eapply2 max_is_max.  omega.\nQed. \n\nLemma occurs_false_subst_rec_maxvar_lt : \nforall M, occurs0 M = false ->  forall j, maxvar M <= j -> \nforall N, maxvar (subst_rec M N 0) <= pred j.  \nProof.\ninduction M; split_all; subst.  simpl in *.\n gen2_case H H0 n. discriminate. omega. omega. \n simpl in *. \nassert(occurs0 M1 = false /\\ occurs0 M2 = false). eapply2 orb_false_iff. \ninversion H1. \nassert (Nat.max (maxvar M1) (maxvar M2)  >= maxvar M1) by eapply2 max_is_max. \nassert (Nat.max (maxvar M1) (maxvar M2)  >= maxvar M2) by eapply2 max_is_max. \nassert(maxvar M1 <= j /\\ maxvar M2 <= j). \nsplit; omega.  inversion H6.\nassert(pred j >=  Nat.max (maxvar (subst_rec M1 N 0)) (maxvar (subst_rec M2 N 0))). \neapply2 max_max2.  omega. \nQed. \n\n\nLemma occurs_false_subst_pattern_normal: \nforall M j N, occurs0 M = false -> pattern_normal j M -> pattern_normal (pred j) (subst_rec M N 0). \nProof.\ninduction M; split_all.\n(* 3 *) \ngen2_case H H0 n. discriminate.  insert_Ref_out. eapply2 pnf_normal.\n(* 2 *)  \neapply2 pnf_normal.\n(* 1 *)    \nassert(occurs0 M1 = false /\\ occurs0 M2 = false) by eapply2 orb_false_iff. \ninversion H1. \ninversion H0.\n(* 4 *) \n eapply2 pnf_normal. \nassert(normal (subst_rec (App M1 M2) N 0)) by eapply2 occurs_false_subst_normal. \nsimpl in H7; auto.\n(* 3 *) \neapply2 pnf_compound. \nassert(compound (subst_rec (App M1 M2) N 0)) by eapply2 subst_rec_preserves_compounds. \nsimpl in H10; auto.\n(* 2 *)\neapply2 pnf_active. \nreplace (App (subst_rec M1 N 0) (subst_rec M2 N 0)) with (subst_rec (App M1 M2) N 0) by auto. \nrewrite occurs_false_subst_status.  auto. simpl; auto. \n(* 1 *) \n subst. \neapply pnf_break. eapply2 IHM1. eapply2 IHM2.\n(* 2 *)  \neapply2 occurs_false_subst_rec_maxvar_gt0.\neapply2 occurs_false_subst_rec_maxvar_lt. \nQed. \n\nLemma pattern_normal_star_opt: \nforall M j, pattern_normal j M -> pattern_normal (pred j) (star_opt M). \nProof. \ninduction M; intros. \n(* 3 *) \neapply2 pnf_normal. eapply2 star_opt_normal.  \n(* 2 *) \neapply2 pnf_normal. eapply2 star_opt_normal.  \n(* 1 *) \n subst; inversion H; subst. \n(* 4 *) \neapply2 pnf_normal. eapply2 star_opt_normal.\n(* 3 *)   \nunfold star_opt; fold star_opt. \nassert(occurs0 M1 = true \\/ occurs0 M1 <> true) by decide equality. \ninversion H0. \n(* 4 *) \nrewrite H1. eapply2 pnf_compound. eapply2 pnf_compound.  eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_normal. \n(* 3 *)  \nassert(pattern_normal  (pred j) (star_opt M2)) by eapply2 IHM2. \nassert(occurs0 M1 = false). gen_case H1 (occurs0 M1).  \nassert False by eapply2 H1; noway. \nrewrite H6.\nassert(pattern_normal (pred j) (subst_rec M1 (Op Node) 0)) .\neapply2 occurs_false_subst_pattern_normal.\nassert(pattern_normal (pred j) (star_opt M1)) by eapply2 IHM1. \nclear IHM1 IHM2 H H0 H1 . \n(* 3 *)  \nunfold subst, subst_rec; fold subst_rec. \nassert(pattern_normal (pred j) (App (App (Op Node) (App (Op Node) (star_opt M2))) (star_opt M1))). \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_normal. \nassert(occurs0 M2 = false -> \n  pattern_normal (pred j) (App k_op (App (subst_rec M1 (Op Node) 0) (subst_rec M2 (Op Node) 0)))). \nintro. \nassert(pattern_normal (pred j) (subst_rec M2 (Op Node) 0)).\nrewrite star_opt_occurs_false in H3.  2: auto. \ninversion H3; subst; auto.\neapply2 pnf_normal.  inversion H1; auto. \neapply2 pnf_compound. unfold_op;  eapply2 pnf_normal. \n2: unfold_op; auto. \neapply2 pnf_compound.  \nassert(compound (subst_rec (App M1 M2) (Op Node) 0)).  \n(eapply2 subst_rec_preserves_compounds).\nsimpl in H9.  inversion H9; subst; auto.\n(* 3 *) \ngen3_case H H0 H7 M2. gen3_case H H0 H7 n. \ngen3_case H H0 H7 (occurs0 s || occurs0 s0). \n(* 2 *) \nunfold star_opt; fold star_opt. \nassert(occurs0 M1 = true \\/ occurs0 M1 <> true) by decide equality. \ninversion H0. \n(* 3 *) \nrewrite H1. eapply2 pnf_compound. eapply2 pnf_compound.  eapply2 pnf_normal.\n eapply2 pnf_compound.  eapply2 pnf_normal.\n(* 2 *)  \nassert(pattern_normal  (pred j) (star_opt M2)) by eapply2 IHM2. \nassert(occurs0 M1 = false). gen_case H1 (occurs0 M1). \nassert False by eapply2 H1; noway. \nrewrite H6.\nassert(pattern_normal (pred j) (subst_rec M1 (Op Node) 0)) .\neapply2 occurs_false_subst_pattern_normal.\nassert(pattern_normal (pred j) (star_opt M1)) by eapply2 IHM1. \nclear IHM1 IHM2 H H0 H1 . \n(* 2 *)  \nunfold subst, subst_rec; fold subst_rec. \nassert(pattern_normal (pred j) (App (App (Op Node) (App (Op Node) (star_opt M2))) (star_opt M1))). \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. eapply2 pnf_compound. eapply2 pnf_normal. \nassert(occurs0 M2 = false -> \n  pattern_normal (pred j) (App k_op (App (subst_rec M1 (Op Node) 0) (subst_rec M2 (Op Node) 0)))). \nintro. \nassert(pattern_normal (pred j) (subst_rec M2 (Op Node) 0)).\nrewrite star_opt_occurs_false in H3.  2: auto. \ninversion H3; subst; auto.\neapply2 pnf_normal.  inversion H1; auto. \neapply2 pnf_compound. unfold_op;  eapply2 pnf_normal. \n2: unfold_op; auto. \neapply2 pnf_active.\nreplace (App (subst_rec M1 (Op Node) 0) (subst_rec M2 (Op Node) 0)) with \n(subst_rec (App M1 M2) (Op Node) 0) by auto. \nrewrite occurs_false_subst_status. auto.  \nsimpl; rewrite H6; rewrite H0; auto. \n(* 2 *) \ngen3_case H H0 H7 M2. gen3_case H H0 H7 n. \ngen3_case H H0 H7 (occurs0 s || occurs0 s0). \n(* 1 *) \nSet Keep Proof Equalities.\nassert(M2 = Ref 0 \\/ M2 <> Ref 0) by repeat decide equality. \ninversion H0; subst.  \nassert(occurs0 M1 = true \\/ occurs0 M1 <> true) by decide equality. \ninversion H1; subst. \n(* 3 *) \nunfold star_opt; fold star_opt. rewrite H4. \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_normal. \nassert(occurs0 M1 = false). \ngen_case H4 (occurs0 M1).  assert False by eapply2 H4; noway.  \nunfold star_opt; fold star_opt. rewrite H7.\neapply2 occurs_false_subst_pattern_normal. \nassert(occurs0 M1 = true \\/ occurs0 M1 <> true) by decide equality. \ninversion H4; subst. \n(* 2 *) \nunfold star_opt; fold star_opt. rewrite H7. \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_normal. \nassert(occurs0 M1 = false). \ngen_case H7 (occurs0 M1).  assert False by eapply2 H7; noway.  \nunfold star_opt; fold star_opt. rewrite H8.\n(* 1 *) \nassert(pattern_normal  (pred j) (star_opt M2)) by eapply2 IHM2. \nassert(pattern_normal (pred j) (subst_rec M1 (Op Node) 0)) .\neapply2 occurs_false_subst_pattern_normal.\nassert(pattern_normal (pred j) (star_opt M1)) by eapply2 IHM1. \n(* 1 *)  \nunfold subst, subst_rec; fold subst_rec. \nassert(pattern_normal (pred j) (App (App (Op Node) (App (Op Node) (star_opt M2))) (star_opt M1))). \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal.  eapply2 pnf_compound. eapply2 pnf_normal. \nassert(occurs0 M2 = false -> \n  pattern_normal (pred j) (App k_op (App (subst_rec M1 (Op Node) 0) (subst_rec M2 (Op Node) 0)))). \nintro. \nassert(pattern_normal (pred j) (subst_rec M2 (Op Node) 0)).\nrewrite star_opt_occurs_false in H9.  2: auto. \neapply2 occurs_false_subst_pattern_normal. unfold_op. \neapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_break. \neapply2 occurs_false_subst_rec_maxvar_gt0. \neapply2 occurs_false_subst_rec_maxvar_lt. \n(* 1 *) \ngen3_case H10 H12 H13 M2. gen3_case H10 H12 H13 n. \ngen3_case H10 H12 H13 (occurs0 s || occurs0 s0). \nQed. \n\n\nLemma pattern_normal_zero: forall M, pattern_normal 0 M -> normal M. \nProof. \ninduction M; split_all. inversion H; subst. auto. \neapply2 nf_compound.  eapply2 nf_active. noway. \nQed. \n\n\nLemma pattern_normal_gt: \nforall j M, pattern_normal j M -> forall k, j <= k -> pattern_normal k M. \nProof.\nintros j M pn; induction pn; split_all. \neapply2 pnf_normal. eapply2 pnf_compound. eapply2 pnf_active. eapply2 pnf_break.  omega. \nQed. \n\n\nLemma pattern_normal_app_comb: forall M N j, pattern_normal j M -> pattern_normal j N -> \npattern_normal j (app_comb M N). \nProof. \nintros. replace (app_comb M N) with \n(App (App (Op Node) (App (Op Node) i_op)) (App (App (Op Node) (App (Op Node) (App k_op N))) (App k_op M))) by auto. \nunfold_op. eapply2 pnf_compound.  eapply2 pnf_compound. eapply2 pnf_normal.  \nunfold_op. eapply2 pnf_compound.  eapply2 pnf_normal.  \neapply2 pnf_compound.  eapply2 pnf_compound.  eapply2 pnf_normal.\neapply2 pnf_normal.  eapply2 pnf_normal. \neapply2 pnf_compound.  eapply2 pnf_compound.  eapply2 pnf_normal.\neapply2 pnf_compound.  eapply2 pnf_normal.\neapply2 pnf_compound.  eapply2 pnf_normal.\neapply2 pnf_compound.  eapply2 pnf_normal.\nQed. \n\n(* restore ? \n\nLemma case_normal: \nforall (P M : SF), normal M -> normal (case P M).\nProof.\n  induction P; intros.\n  (* 3 *)\n  unfold case, maxvar.   eapply2 star_opt_normal. unfold_op; split_all. \n  (* 2 *) \nunfold case, swap; unfold_op; intros. case o; nf_out. \napply nf_active. nf_out. eapply2 nf_active; nf_out. \neapply2 nf_active; nf_out. \nunfold lift; apply lift_rec_preserves_normal; auto. \nnf_out. cbv; auto.  \napply nf_active. nf_out.\nrepeat (apply nf_active; nf_out). \nunfold lift; apply lift_rec_preserves_normal; auto. \nnf_out. cbv; auto.  \n  (* 1 *) \n  unfold case; fold case; unfold case_app_nf. \nassert(is_program (App P1 P2) = true \\/ is_program (App P1 P2) <> true) by decide equality. \ninversion H0. rewrite H1. \n(* 2 *) \nrewrite star_opt_occurs_true. 2: cbv; auto. 2: unfold swap; discriminate. \nrewrite star_opt_occurs_true. 2: cbv; auto. 2: unfold swap; discriminate. \nrewrite star_opt_occurs_true. 2: cbv; auto. 2: unfold swap; discriminate. \nrewrite star_opt_eta.\nnf_out.  \nunfold subst; rewrite subst_rec_closed. eapply2 equal_comb_normal. \nrewrite equal_comb_closed; omega. \nassert(program (App P1 P2)) by eapply2 program_is_program. inversion H2; auto. \nunfold lift; apply lift_rec_preserves_normal. auto. \nunfold swap; unfold_op; nf_out.  \neapply2 occurs_closed. \n(* 1 *) \nassert(is_program (App P1 P2) = false).\neapply2 not_true_iff_false. \nrewrite H2. \n(* 1 *) \n  unfold case_app_nf, swap. unfold_op; nf_out. \ninversion H; eapply2 IHP1;  eapply2 IHP2. \neapply2 nf_compound. eapply2 nf_compound. \nQed. \n\n\n*) \n (* \nLemma case_pattern_normal: \nforall (P M : SF) j, pattern_normal j M -> \npattern_normal (j - (pattern_size P)) (case P M).\nProof.\n  induction P; intros. \n  (* 3 *)\n  unfold pattern_size. unfold case. \nreplace (j-1) with (pred j) by omega. \neapply pattern_normal_star_opt; auto. \nunfold_op. eapply2 pnf_compound. eapply2 pnf_normal. \n(* 2 *) \nunfold pattern_size, case; simpl. replace (j-0) with j by omega. \ncase o. \n(* 3 *) \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \nunfold subst, subst_rec; eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_normal. nf_out. \nunfold subst, subst_rec; eapply2 pnf_normal. unfold_op. nf_out. \nunfold_op; eapply2 pnf_compound. eapply2 pnf_normal. \nunfold subst, subst_rec; eapply2 pnf_normal. \nunfold_op; eapply2 pnf_compound. eapply2 pnf_normal. \nunfold subst, subst_rec; eapply2 pnf_normal. \n2:unfold_op; eapply2 pnf_compound. \n2: eapply2 pnf_normal. 2: nf_out.  \n2: unfold subst, subst_rec; nf_out. \n2:unfold subst, subst_rec; eapply2 pnf_normal. \n2: unfold_op; eapply2 pnf_compound. \n2: unfold subst, subst_rec; eapply2 pnf_normal. \n2: unfold subst, subst_rec; eapply2 pnf_normal. \n2: nf_out.  \n(* 3 *) \nunfold lift. rewrite ! occurs_lift_rec_zero. gen_case H M. gen_case H n. relocate_lt. \nunfold_op. eapply2 pnf_compound.  eapply2 pnf_normal. \neapply2 pnf_normal. unfold subst; nf_out.  insert_Ref_out; auto. \nrelocate_lt. eapply2 pnf_normal. unfold subst; nf_out.  insert_Ref_out; auto. \neapply2 pnf_normal. unfold subst; nf_out. \nunfold_op; eapply2 pnf_compound. eapply2 pnf_normal.\nunfold subst, subst_rec; fold subst_rec. \nrewrite ! subst_rec_lift_rec; try omega.  rewrite ! lift_rec_null. \neapply2 pnf_compound. eapply2 pnf_normal.\n(* 2 *) \nunfold subst, subst_rec; fold subst_rec. \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_normal. unfold_op; unfold subst_rec; nf_out. \neapply2 pnf_normal. unfold_op; unfold subst_rec; nf_out. \neapply2 pnf_normal. unfold_op; unfold subst_rec; nf_out. \neapply2 pnf_normal. unfold_op; unfold subst_rec; nf_out. \n2: eapply2 pnf_normal; unfold_op; unfold subst_rec; nf_out. \n(* 2 *) \nunfold lift. gen_case H M; unfold lift_rec; fold lift_rec. \ngen_case H n. relocate_lt. unfold plus. insert_Ref_out.\neapply2 pnf_normal; nf_out. \neapply2 pnf_normal; nf_out. \nrelocate_lt. unfold plus. insert_Ref_out. nf_out. \neapply2 pnf_normal; nf_out. \n(* 2 *) \nrewrite ! occurs_lift_rec_zero. simpl. \nrewrite ! subst_rec_lift_rec; try omega. rewrite ! lift_rec_null.\nunfold_op; eapply2 pnf_compound. eapply2 pnf_normal.  eapply2 pnf_compound. \neapply2 pnf_normal.\n(* 1 *) \nunfold pattern_size; fold pattern_size. \nunfold case; fold case.\nassert(is_program (App P1 P2) = true \\/ is_program (App P1 P2) <> true) by decide equality. \ninversion H0. rewrite H1. \n(* 2 *) \nrewrite star_opt_occurs_true. 2: cbv; auto. 2: unfold swap; discriminate. \nrewrite star_opt_occurs_true. 2: cbv; auto. 2: unfold swap; discriminate. \nrewrite star_opt_occurs_true. 2: cbv; auto. 2: unfold swap; discriminate. \nrewrite star_opt_eta.\neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal.  \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal.  \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal.  \neapply2 pnf_normal. unfold subst; rewrite subst_rec_closed. \neapply2 equal_comb_normal. rewrite equal_comb_closed; omega. \neapply2 pnf_normal. eapply2 star_opt_normal. \nassert(program (App P1 P2)) by eapply2 program_is_program. \ninversion H2; auto. \nunfold_op. rewrite star_opt_occurs_false.\nunfold lift, subst_rec; fold subst_rec.   \nrewrite subst_rec_lift_rec; try omega. rewrite lift_rec_null. \neapply2 pnf_compound. \nunfold_op; eapply2 pnf_normal.   \neapply2 pnf_compound. eapply2 pnf_normal. \nrewrite ! pattern_size_closed. \nreplace (j-(0+0)) with j by omega. auto. \nassert(program (App P1 P2)) by eapply2 program_is_program. \ninversion H2.  simpl in H4; max_out. \nassert(program (App P1 P2)) by eapply2 program_is_program. \ninversion H2.  simpl in H4; max_out. \nunfold_op; auto. \nunfold occurs0; fold occurs0. \nunfold lift; rewrite occurs_lift_rec_zero.  auto. \neapply2 pnf_normal. unfold swap; unfold_op; nf_out. \neapply2 occurs_closed. \n(* 1 *) \nassert(is_program (App P1 P2) = false).\neapply2 not_true_iff_false. \nrewrite H2. \n(* 1 *) \n  unfold case_app_nf, swap. unfold_op; nf_out. \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal.  \neapply2 pnf_compound. eapply2 pnf_normal.  nf_out. \neapply2 pnf_compound. eapply2 pnf_normal.  \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal.  \neapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal.\n2: eapply2 pnf_normal. 2: nf_out.   \n2: eapply2 pnf_normal. 2: nf_out.   \n2: unfold_op; auto. 2: eapply2 pnf_normal.  2: nf_out.\n(* 1 *) \nreplace (j - (pattern_size P1 + pattern_size P2)) with (j - pattern_size P2 - pattern_size P1)\nby omega. \neapply2 IHP1. eapply2 IHP2. \nunfold_op;  eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_normal.\nQed. \n \n\n *) \n\n\n\n(* matching *) \n\nInductive matching : SF -> SF -> list SF -> Prop :=\n| match_ref : forall i M, matching (Ref i) M (cons M nil)\n| match_op: forall o, matching (Op o) (Op o) nil\n| match_app: forall p1 p2 M1 M2 sigma1 sigma2,\n               (compound (App p1 p2) \\/ status (App p1 p2) = Active) -> compound (App M1 M2) ->\n               matching p1 M1 sigma1 -> matching p2 M2 sigma2 ->\n               matching (App p1 p2) (App M1 M2) ((map (lift (length sigma1)) sigma2) ++ sigma1)\n.\n\nHint Constructors matching.\n\nLemma matching_lift:\n  forall P M sigma, matching P M sigma -> forall k, matching P (lift k M) (map (lift k) sigma). \nProof.\n  induction P; split_all; inversion H; subst; unfold map; fold map; auto. \n(* 2 *) \nreplace (lift k (App M1 M2)) with (App (lift k M1) (lift k M2)) by (unfold lift; auto). \nreplace(fix map (l : list SF) : list SF :=\n            match l with\n            | nil => nil\n            | a :: t => lift (length sigma1) a :: map t\n            end) with (map (lift (length sigma1))) by auto.\nreplace (fix map (l : list SF) : list SF :=\n         match l with\n         | nil => nil\n         | a :: t => lift k a :: map t\n         end) with (map (lift k)) by auto. \nrewrite map_app.\nreplace (map (lift k) (map (lift (length sigma1)) sigma2)) with\n         (map (lift (length (map (lift k) sigma1))) (map (lift k) sigma2)).\neapply2 match_app. \nreplace (App (lift k M1) (lift k M2)) with  (lift k (App M1 M2)) by (unfold lift; auto). \nunfold lift. eapply2 lift_rec_preserves_compound. \nclear. induction sigma2; split_all. rewrite IHsigma2. rewrite map_length. \nunfold lift; repeat rewrite lift_rec_lift_rec; try omega. \nreplace (length sigma1 + k) with (k+ length sigma1) by omega. auto.\nQed.\n\n\nLemma max_pred: forall m n, pred (max m n) = max (pred m) (pred n). \nProof. double induction m n; intros; auto. case n; intros; auto. Qed. \n\n\nLemma program_matching: forall M, program M -> matching M M nil. \nProof.\n  induction M; split_all.\n  inversion H; split_all. simpl in *; noway. \n  inversion H; split_all. inversion H0.\n  assert(status (App M1 M2) = Passive) by eapply2 closed_implies_passive.\n  rewrite H6 in H7; discriminate.\n  replace (nil: list SF)\n  with (List.map (lift (length (nil: list SF))) (nil: list SF) ++ (nil: list SF))\n    by split_all.\n  eapply2 match_app. simpl in *. max_out. eapply2 IHM1. unfold program; auto.\n  simpl in *. max_out. eapply2 IHM2. unfold program; auto.\nQed. \n\nLemma program_matching2: forall M sigma, matching M M sigma -> maxvar M = 0 -> program M. \nProof.\n  induction M; split_all. noway. unfold program; auto. \n  inversion H; split_all; subst. unfold program; split; auto.  eapply2 nf_compound. \n  eapply2 IHM1. max_out.  eapply2 IHM2. max_out. \nQed. \n\n\n\n  \nLemma pattern_is_closed: \nforall P, maxvar P = 0 -> forall M sigma, matching P M sigma -> M = P /\\ sigma = nil. \nProof. \ninduction P; intros; inversion H; subst.  \n(* 2 *) \ninversion H0; auto. \n(* 1 *) \ninversion H0; subst; simpl in *; max_out. \nassert(M1 = P1 /\\ sigma1 = nil). eapply2 IHP1 . \nassert(M2 = P2 /\\ sigma2 = nil). eapply2 IHP2 . \nsplit_all; subst. inversion H2; inversion H7; subst; split; auto.  \nQed. \n\n\n\nLemma maxvar_case_app : \nforall P1 P2, \n(forall M : SF, maxvar (case P1 M) = maxvar M - pattern_size P1) -> \n(forall M : SF, maxvar (case P2 M) = maxvar M - pattern_size P2) -> \nforall M, maxvar (case_app case P1 P2 M) = maxvar M - pattern_size (App P1 P2). \nProof. \nintros. unfold case_app. \nrewrite maxvar_star_opt. \nunfold_op. unfold maxvar; fold maxvar.  unfold max; fold max. \nunfold lift; rewrite ! lift_rec_preserves_star_opt. \nunfold lift_rec; fold lift_rec. \nrewrite lift_rec_lift_rec; try omega. \nrewrite ! maxvar_star_opt. \nrelocate_lt. \nrewrite ! lift_rec_preserves_case. \nunfold lift_rec; fold lift_rec. \nunfold maxvar; fold maxvar. \nunfold max; fold max. \nrewrite H; rewrite H0. \nunfold maxvar; fold maxvar. \nunfold max; fold max. \nrewrite ! max_pred. simpl. rewrite ! max_zero. \n\nreplace (pattern_size P2 + (pattern_size P1 + 0)) \nwith (pattern_size P1 + pattern_size P2) by omega. \nreplace (maxvar (lift_rec M (pattern_size P1 + pattern_size P2) 3) -\n             pattern_size P2 - pattern_size P1)\nwith (maxvar (lift_rec M (pattern_size P1 + pattern_size P2) 3) -\n             (pattern_size P1 + pattern_size P2)) by omega.\nclear. induction M; split_all. \ncase (pattern_size P1 + pattern_size P2); split_all.\n(* 3 *) \nunfold relocate. elim(test 0 n); split_all.  noway.\n(* 2 *) \nunfold relocate. elim(test (S n0) n); split_all.\ngen_case a n0; try omega.\ngen_case a n1; try omega.\ngen_case a n2; try omega.\nomega. \n(* 1 *) \nrewrite max_minus.\nrewrite ! max_pred. \nrewrite IHM1.  rewrite IHM2. \nrewrite max_minus. auto. \nQed. \n\n\n\nLemma maxvar_lift: forall M, pred (maxvar (lift 1 M)) = maxvar M. \nProof.\ninduction M; split_all. relocate_lt. omega. \nrewrite max_pred. unfold lift in *. auto. \nQed. \n\nLemma occurs0_lift: \nforall M k, occurs0 (lift (S k) M) = false.\nProof.\ninduction M; split_all. \nrelocate_lt.  replace (S k + n) with (S (k+n)) by omega. auto.  \nunfold lift in *. rewrite IHM1; auto. rewrite IHM2; auto. \nQed. \n \n\nLemma maxvar_case : forall P M, maxvar (case P M) = maxvar M - (pattern_size P).\nProof.\n  induction P; intros; unfold case; fold case; unfold maxvar; fold maxvar.\n  (* 3 *)\n  rewrite maxvar_star_opt. split_all. omega. \n  (* 2 *)\ncase o; unfold_op; unfold pattern_size.  \n  rewrite maxvar_star_opt. simpl. \nreplace (maxvar M - 0) with (maxvar M) by omega.\nrewrite max_pred. simpl. \nrewrite max_zero.   \nassert(pred (maxvar (lift 1 M)) = maxvar M) by eapply2 maxvar_lift. \ngen_case H (maxvar (lift 1 M)).\n(* 1 *)\nassert(is_program (App P1 P2) = true \\/ is_program(App P1 P2) <> true)\nby decide equality. \ninversion H. \nrewrite H0.\nrewrite maxvar_star_opt.   \nrewrite ! maxvar_app. \nrewrite equal_comb_closed. simpl.  \nassert(program (App P1 P2)) by eapply2 program_is_program. \ninversion H1. simpl in H3. max_out. rewrite H4. rewrite H5. simpl. \nrewrite max_pred. \nassert(pred (maxvar (lift 1 M)) = maxvar M) by eapply2 maxvar_lift. \ngen_case H3 (maxvar (lift 1 M)).\nrewrite <- H3. \nrewrite ! pattern_size_closed; auto.\nrewrite ! pattern_size_closed; auto.\nsimpl; rewrite max_zero; auto. omega. \n(* 1 *) \nassert(is_program (App P1 P2) = false) by \neapply2 not_true_iff_false. \nrewrite H1. \n(* 1 *) \nunfold case_app. \n  rewrite maxvar_star_opt. simpl.  \nrewrite orb_true_r. rewrite ! orb_false_r.\nrewrite occurs0_lift. \nassert(pred (maxvar\n         (lift 1\n            (star_opt\n               (App\n                  (App (Op Node)\n                     (App (Op Node)\n                        (App k_op (subst (App k_op i_op) (Op Node)))))\n                  (subst\n                     (App\n                        (App\n                           (lift 2\n                              (case P1 (case P2 (App k_op (App k_op M)))))\n                           (Ref 1)) (App k_op (App k_op (App k_op i_op))))\n                     (Op Node)))))) = \nmaxvar (star_opt\n               (App\n                  (App (Op Node)\n                     (App (Op Node)\n                        (App k_op (subst (App k_op i_op) (Op Node)))))\n                  (subst\n                     (App\n                        (App\n                           (lift 2\n                              (case P1 (case P2 (App k_op (App k_op M)))))\n                           (Ref 1)) (App k_op (App k_op (App k_op i_op))))\n                     (Op Node))))) by \neapply2 maxvar_lift. \ngen_case H2 (maxvar\n          (lift 1\n             (star_opt\n                (App\n                   (App (Op Node)\n                      (App (Op Node)\n                         (App k_op (subst (App k_op i_op) (Op Node)))))\n                   (subst\n                      (App\n                         (App\n                            (lift 2\n                               (case P1 (case P2 (App k_op (App k_op M)))))\n                            (Ref 1)) (App k_op (App k_op (App k_op i_op))))\n                      (Op Node)))))).\nrewrite ! orb_true_r in *. simpl in *.  \nclear - IHP1 IHP2 H2. \nunfold lift in *; rewrite subst_rec_lift_rec in *; try omega.\nreplace (lift_rec (case P1 (case P2 (App k_op (App k_op M)))) 0 1) with \n(lift 1  (case P1 (case P2 (App k_op (App k_op M))))) in * by auto. \nrewrite occurs0_lift in *.\nunfold subst, lift in *; rewrite subst_rec_lift_rec in *; try omega.\nrewrite lift_rec_null in *. \nrewrite max_zero in *.\nrewrite IHP1 in H2; auto. rewrite IHP2 in H2. simpl in *. omega. \n(* 1 *)     \nrewrite orb_true_r in *. simpl in *.  \nclear H H0 H1. \nunfold lift in *; rewrite subst_rec_lift_rec in *; try omega.\nreplace (lift_rec (case P1 (case P2 (App k_op (App k_op M)))) 0 1) with \n(lift 1  (case P1 (case P2 (App k_op (App k_op M))))) in * by auto. \nrewrite occurs0_lift in *.\nunfold subst, lift in *; rewrite subst_rec_lift_rec in *; try omega.\nrewrite lift_rec_null in *. \nrewrite max_zero in *.\nrewrite IHP1 in H2; auto. rewrite IHP2 in H2. simpl in *. omega. \nQed. \n\n\nLemma program_matching3: \nforall P M sigma, matching P M sigma -> maxvar P = 0 -> M = P /\\ sigma = nil. \nProof.\n  induction P; split_all. noway. \n  inversion H; split_all; subst. \n  inversion H; split_all; subst. \n  simpl in H0; max_out. \n  assert(M1 = P1 /\\ sigma1 = nil) by eapply2 IHP1.  \n  assert(M2 = P2 /\\ sigma2 = nil) by eapply2 IHP2.   \n  inversion H0; inversion H6; subst; split; cbv; auto.  \nQed. \n\nLemma case_by_matching:\n  forall P N sigma,  matching P N sigma ->\n                     forall M, sf_red (App (case P M) N) (App k_op (fold_left subst sigma M)). \nProof.\n  induction P; intros.\n  (* 3 *)\n  inversion H; subst. unfold fold_left.  unfold case; unfold_op.  eapply2 star_opt_beta.\n  (* 2 *)\n  inversion H; subst. unfold fold_left.  unfold case; unfold_op. case o. \n  eapply transitive_red. eapply2 star_opt_beta. \n  unfold subst; rewrite ! subst_rec_app. \nrewrite subst_rec_closed. 2: simpl; omega. \nunfold subst_rec; fold subst_rec. insert_Ref_out. unfold lift, lift_rec; fold lift_rec.\nrewrite subst_rec_lift_rec; try omega. rewrite lift_rec_null. \neapply transitive_red. eapply2 factor_leaf.  \n  eval_tac. \n  (* 1 *) \n  unfold case; fold case. \nassert(is_program (App P1 P2) = true \\/ is_program(App P1 P2) <> true)\nby decide equality. \ninversion H0. \nrewrite H1. \neapply transitive_red. \neapply2 star_opt_beta.\nunfold subst; rewrite ! subst_rec_app. \nrewrite subst_rec_closed. 2: rewrite equal_comb_closed; omega. \nunfold lift; rewrite subst_rec_lift_rec; try omega. \nunfold subst_rec; fold subst_rec.\ninsert_Ref_out. unfold lift; rewrite ! lift_rec_null.   \nunfold swap; unfold_op. unfold subst, subst_rec; fold subst_rec. insert_Ref_out. \nunfold lift; rewrite ! lift_rec_null.\nassert(program (App P1 P2)) by eapply2 program_is_program. \ninversion H2; subst. simpl in H4; max_out. \nrewrite ! subst_rec_closed; try omega.   \nassert(N = App P1 P2 /\\ sigma = nil). \neapply2 program_matching3. simpl; auto. rewrite H5; rewrite H6; auto. \ninversion H4; subst. \neapply transitive_red. eapply preserves_app_sf_red. \neapply preserves_app_sf_red. \neapply2 equal_programs. auto. auto. \nunfold_op; eval_tac.\n(* 1 *)  \nassert(is_program (App P1 P2) = false) by \neapply2 not_true_iff_false. \nrewrite H2. \n(* 1 *) \n  unfold case_app. \neapply transitive_red. eapply2 star_opt_beta. \nunfold subst; rewrite ! subst_rec_app. \nrewrite subst_rec_closed. 2: simpl; auto. \nunfold subst_rec; fold subst_rec. insert_Ref_out. unfold lift; rewrite lift_rec_null. \nrewrite subst_rec_lift_rec; try omega.\nrewrite subst_rec_closed. 2: simpl; auto. \ninversion H; subst. inversion H6; subst.\n(* 2 *)  \neapply transitive_red. eapply preserves_app_sf_red. eapply2 factor_stem.\nunfold swap; simpl. insert_Ref_out. unfold lift; rewrite lift_rec_null. auto. \nrewrite ! lift_rec_preserves_star_opt.    \n  eapply transitive_red. eapply preserves_app_sf_red. eapply2 star_opt_beta2. auto. \nunfold subst; simpl. insert_Ref_out.\nunfold lift; rewrite ! lift_rec_null.\nrewrite ! subst_rec_lift_rec; try omega.\nrewrite ! lift_rec_null. \neapply transitive_red. eapply preserves_app_sf_red. \n  eapply preserves_app_sf_red. eapply preserves_app_sf_red. \n  eapply preserves_app_sf_red.\neapply2 IHP1. all: auto. \neapply transitive_red. eapply preserves_app_sf_red. \n  eapply preserves_app_sf_red. eapply preserves_app_sf_red. \n   eapply succ_red. eapply2 k_red. all: auto.  \nrewrite fold_subst_list. rewrite fold_subst_list. rewrite fold_subst_list.\neapply transitive_red. eapply list_subst_preserves_sf_red. \neapply preserves_app_sf_red. eapply preserves_app_sf_red.\neapply IHP2. eapply2 matching_lift. \nunfold lift; simpl. auto. unfold lift; simpl. auto. \neapply transitive_red. eapply list_subst_preserves_sf_red. \nunfold_op.  eapply transitive_red. eapply preserves_app_sf_red. \neapply succ_red. eapply2 k_red.  auto. auto. auto. \nrepeat rewrite list_subst_preserves_app. repeat rewrite list_subst_preserves_op. \neval_tac.   repeat eapply2 preserves_app_sf_red.\nrewrite fold_left_app. auto.\n(* 1 *) \neapply transitive_red. eapply preserves_app_sf_red. eapply2 factor_fork.\nunfold swap; simpl. insert_Ref_out. unfold lift; rewrite lift_rec_null. auto. \nrewrite ! lift_rec_preserves_star_opt.    \n  eapply transitive_red. eapply preserves_app_sf_red. eapply2 star_opt_beta2. auto. \nunfold subst; simpl. insert_Ref_out.\nunfold lift; rewrite ! lift_rec_null.\nrewrite ! subst_rec_lift_rec; try omega.\nrewrite ! lift_rec_null. \neapply transitive_red. eapply preserves_app_sf_red. \n  eapply preserves_app_sf_red. eapply preserves_app_sf_red. \n  eapply preserves_app_sf_red.\neapply2 IHP1. all: auto. \neapply transitive_red. eapply preserves_app_sf_red. \n  eapply preserves_app_sf_red. eapply preserves_app_sf_red. \n   eapply succ_red. eapply2 k_red. all: auto.  \nrewrite fold_subst_list. rewrite fold_subst_list. rewrite fold_subst_list.\neapply transitive_red. eapply list_subst_preserves_sf_red. \neapply preserves_app_sf_red. eapply preserves_app_sf_red.\neapply IHP2. eapply2 matching_lift. \nunfold lift; simpl. auto. unfold lift; simpl. auto. \neapply transitive_red. eapply list_subst_preserves_sf_red. \nunfold_op.  eapply transitive_red. eapply preserves_app_sf_red. \neapply succ_red. eapply2 k_red.  auto. auto. auto. \nrepeat rewrite list_subst_preserves_app. repeat rewrite list_subst_preserves_op. \neval_tac.   repeat eapply2 preserves_app_sf_red.\nrewrite fold_left_app. auto.\n \nQed. \n\n\n\n\nDefinition extension P M R := App (App (Op Node) (App (Op Node)  (App k_op R))) (case P M). \n\nProposition extensions_by_matching:\n  forall P N sigma,  matching P N sigma ->\n                     forall M R, sf_red (App (extension P M R) N) (fold_left subst sigma M) .\nProof.\n  intros. unfold extension. eapply succ_red. eapply2 s_red.\n  eapply transitive_red. eapply preserves_app_sf_red. eapply2 case_by_matching. eval_tac. eval_tac.\nQed.\n\n\n\nLemma lift_rec_preserves_extension: \n  forall P M R n k, lift_rec (extension P M R) n k =\n                    extension P (lift_rec M (pattern_size P +n) k) (lift_rec R n k).\nProof.\n  intros. unfold extension. unfold_op. unfold lift_rec; fold lift_rec.\nrewrite lift_rec_preserves_case. auto. \nQed.\n\n\nLemma subst_rec_preserves_extension: \n  forall P M R N k, subst_rec (extension P M R) N k =\n                    extension P (subst_rec M N (k+ pattern_size P)) (subst_rec R N k).\nProof.\n  intros. unfold extension. unfold_op. unfold subst_rec; fold subst_rec.\nrewrite subst_rec_preserves_case. auto. \nQed.\n\n \n\nLemma maxvar_extension : \nforall P M R, maxvar (extension P M R) = max (maxvar M - (pattern_size P)) (maxvar R).\nProof.  intros. unfold extension; simpl. rewrite maxvar_case. auto. rewrite max_swap. auto. Qed. \n\n\nLemma extension_ref: forall i M R N, sf_red (App (extension (Ref i) M R) N)  (subst_rec M N 0).\nProof.\n  split_all. unfold extension. unfold_op.  eapply succ_red. eapply2 s_red.\n  unfold case. unfold_op. eapply transitive_red. eapply preserves_app_sf_red.\n  eapply2 star_opt_beta. eval_tac. unfold subst; split_all. eval_tac.\nQed. \n\nLemma extension_op : forall o M R, sf_red (App (extension (Op o) M R) (Op o)) M.\nProof.\n  intros. unfold extension, case; unfold_op.  \neapply succ_red. eapply2 s_red. \ncase o. \neapply transitive_red. eapply preserves_app_sf_red. \neapply2 star_opt_beta. eval_tac.\nunfold subst; rewrite ! subst_rec_app. \nrewrite subst_rec_closed. 2: simpl; auto. \nunfold subst_rec; fold subst_rec.  insert_Ref_out. \nunfold lift, lift_rec; fold lift_rec. \nrewrite subst_rec_lift_rec; try omega. \nunfold subst; simpl. insert_Ref_out. \nunfold lift; rewrite ! lift_rec_null. \neapply transitive_red. eapply preserves_app_sf_red. eapply2 factor_leaf. auto. eval_tac. \nQed.\n\n\nLemma extension_op_fail : \nforall o M R N, factorable N -> Op o <> N -> sf_red (App (extension (Op o) M R) N) (App R N).\nProof.\n  intros. unfold extension, case; unfold_op; unfold maxvar. \n  eapply succ_red. apply s_red. auto. auto. auto. \ngeneralize H0; case o; intro.\neapply transitive_red. eapply preserves_app_sf_red. eapply2 star_opt_beta. \neval_tac. \nunfold swap; unfold_op. unfold subst; rewrite ! subst_rec_app. \nrewrite subst_rec_closed. \n2: simpl; omega. \nunfold subst_rec; fold subst_rec. insert_Ref_out. \nunfold lift; rewrite lift_rec_null.\nrewrite subst_rec_lift_rec; try omega. \nrewrite ! lift_rec_null.  \ninversion H. inversion H2; subst.\ngen_case H0 o; gen_case H0 x; congruence. \ninversion H2; subst.  \n eapply transitive_red. eapply preserves_app_sf_red. eapply2 factor_stem. auto. \neval_tac. eval_tac. \n eapply transitive_red. eapply preserves_app_sf_red. eapply succ_red. \neapply2 k_red. auto.  eval_tac.  auto. \n eapply transitive_red. eapply preserves_app_sf_red. eapply2 factor_fork. auto. \neval_tac. eval_tac.   \neapply transitive_red. eapply preserves_app_sf_red. eapply succ_red. eapply2 k_red. auto. \neval_tac. auto. \nQed. \n\nLemma subst_rec_preserves_compound: \nforall (M: SF), compound M -> forall N k, compound(subst_rec M N k).\nProof. intros M c; induction c; unfold subst; split_all. Qed. \n\n\nLemma swapred: forall N R, sf_red (App (swap N) R) (App R N). \nProof.\nintros; unfold swap; unfold_op. eval_tac. eval_tac. \neapply2 preserves_app_sf_red. eval_tac. eval_tac. \nQed. \n\n\n\nLemma extension_compound_op: forall P1 P2 M R o, compound (App P1 P2) -> \nsf_red (App (extension (App P1 P2) M R) (Op o)) (App R (Op o)). \nProof. \n  intros. unfold extension, case; fold case. \neapply succ_red. eapply2 s_red. \nassert(is_program (App P1 P2) = true \\/ is_program(App P1 P2) <> true)\nby decide equality. \ninversion H0. \nrewrite H1.\neapply transitive_red. eapply preserves_app_sf_red. \neapply2 star_opt_beta. \neval_tac. \nunfold subst; rewrite ! subst_rec_app. \nrewrite subst_rec_closed. \n2: rewrite equal_comb_closed; omega. \nunfold subst_rec; fold subst_rec. \ninsert_Ref_out. unfold lift; rewrite ! lift_rec_null. \nunfold swap, subst_rec; fold subst_rec.  \nassert(program (App P1 P2)) by eapply2 program_is_program.\ninversion H2. simpl in H4; max_out.\nrewrite ! subst_rec_lift_rec; try omega.\nrewrite lift_rec_null.  \nrewrite ! subst_rec_closed; auto; try omega. \neapply transitive_red. eapply preserves_app_sf_red. \neapply preserves_app_sf_red. eapply preserves_app_sf_red. \neapply2 unequal_op. \neapply2 programs_are_factorable.  discriminate. auto. auto. auto. \nunfold_op; eval_tac. eval_tac. eval_tac. \neapply2 preserves_app_sf_red;  eval_tac.\n(* 1 *) \nassert(is_program (App P1 P2) = false) by \neapply2 not_true_iff_false. \nrewrite H2.\nunfold case_app.  \neapply transitive_red.  eapply preserves_app_sf_red. eapply2 star_opt_beta. eval_tac. \n unfold subst; rewrite ! subst_rec_app. \nrewrite subst_rec_closed. \n2: simpl; omega. \nunfold subst_rec; fold subst_rec. \ninsert_Ref_out. unfold lift; rewrite ! lift_rec_null. \nrewrite ! subst_rec_lift_rec; try omega.\nrewrite lift_rec_null.  \nrewrite subst_rec_closed. 2: simpl; omega. \ncase o. \neapply transitive_red. eapply preserves_app_sf_red. \neapply preserves_app_sf_red. eapply2 factor_leaf. all: auto. \neval_tac. eval_tac. eval_tac. \neapply transitive_red. eapply preserves_app_sf_red. \neapply succ_red. eapply2 k_red. auto.  \neval_tac. insert_Ref_out. unfold lift; rewrite lift_rec_null.  auto.  \nQed. \n\n(* \nLemma extension_normal: forall P M  R,normal M -> normal R -> normal (extension P M R).\nProof.\n  induction P; unfold extension; unfold_op; intros; \n  eapply2 nf_compound; eapply2 nf_compound; eapply2 case_normal. \nQed. \n\n\n\nLemma extension_pattern_normal: \nforall P M R j, pattern_normal (pattern_size P + j) M -> pattern_normal j R -> \npattern_normal j (extension P M R).\nProof.\n  induction P; unfold extension; unfold_op; intros; \n  eapply2 pnf_compound; eapply2 pnf_compound; try (eapply2 pnf_normal; fail); \nmatch goal with | |- pattern_normal ?j (case ?P _) => \nreplace j with (pattern_size P + j - (pattern_size P)) by omega;  \neapply2 case_pattern_normal\nend. \nQed. \n\n*) \n \nLemma active_not_closed: forall P, status P = Active -> maxvar P <>0. \nProof.\nintros. assert(maxvar P = 0 \\/ maxvar P <> 0) by decide equality. \ninversion H0. assert(status P = Passive) by eapply2 closed_implies_passive. \nrewrite H in *. discriminate. \nauto. \nQed. \n \nInductive matchfail : SF -> SF -> Prop :=\n| matchfail_op: forall o M, factorable M -> Op o <> M -> matchfail (Op o) M\n| matchfail_compound_op: forall p1 p2 o, compound (App p1 p2) -> matchfail (App p1 p2) (Op o)\n| matchfail_active_op: forall p1 p2 o, status (App p1 p2) = Active -> matchfail (App p1 p2) (Op o)\n| matchfail_stem: forall p M, \n               matchfail p M -> matchfail (App (Op Node) p) (App (Op Node) M)\n| matchfail_fork_l: forall p1 p2 M1 M2, \n               matchfail p1 M1 -> matchfail (App (App (Op Node) p1) p2) (App (App (Op Node) M1) M2) \n| matchfail_fork_r: forall p1 p2 M1 M2, \n               matchfail p2 M2-> matchfail (App (App (Op Node) p1) p2) (App (App (Op Node) M1) M2)\n| matchfail_active_l: forall p1 p2 M1 M2, status(App p1 p2) = Active -> compound (App M1 M2) ->\n               matchfail p1 M1 -> matchfail (App p1 p2) (App M1 M2)\n| matchfail_active_r: forall p1 p2 M1 M2 sigma1, status (App p1 p2) = Active -> compound (App M1 M2) ->\n               matching p1 M1 sigma1 -> matchfail p2 M2 -> matchfail (App p1 p2) (App M1 M2)\n.\n\nHint Constructors matchfail. \n\n\nLemma matchfail_lift: forall P M, matchfail P M -> forall k, matchfail P (lift k M).\nProof.\n  induction P; split_all; inversion H; subst; unfold lift, lift_rec; fold lift_rec. \n(* 8 *) \n  gen2_case H1 H2 M. inversion H1; split_all. inversion H0. discriminate.  inv1 compound.\n  eapply2 matchfail_op. unfold lift.  inversion H1; split_all. inversion H0; discriminate. \n unfold factorable. right.\n  replace (App (lift_rec s 0 k) (lift_rec s0 0 k)) with (lift_rec (App s s0) 0 k) by auto. \n  eapply2 lift_rec_preserves_compound. discriminate. \n(* 7 *) \nunfold lift; split_all. \nunfold lift; split_all. \n(* 5 *) \neapply2 matchfail_stem.\n(* 4 *) \neapply2 matchfail_fork_l.\nassert(matchfail (App (Op Node) p1) (lift k (App (Op Node) M1))) .\neapply2 IHP1 .\nunfold lift, lift_rec in *; fold lift_rec in *. inversion H0; auto. inversion H6. \n(* 3 *)\neapply2 matchfail_fork_r.\n(* 2 *) \napply matchfail_active_l. auto. \nreplace (App (lift_rec M1 0 k) (lift_rec M2 0 k)) with (lift_rec (App M1 M2) 0 k) by auto. \neapply2 lift_rec_preserves_compound.\neapply2 IHP1. \n(* 1 *) \neapply matchfail_active_r. auto. \nreplace (App (lift_rec M1 0 k) (lift_rec M2 0 k)) with (lift_rec (App M1 M2) 0 k) by auto. \neapply2 lift_rec_preserves_compound.\neapply2 matching_lift. eapply2 IHP2. \nQed.\n\nLemma matchfail_unequal : \nforall P M, maxvar P = 0 -> matchfail P M -> sf_red (App (App equal_comb M) P) (App k_op i_op). \nProof. \ninduction P; split_all. inversion H0; subst. \ninversion H0; split_all; subst; split_all. \ninversion H2. inversion H1; subst. eapply2 unequal_op.  unfold factorable; eauto. \neapply2 unequal_compound_op. \n(* 1 *) \ninversion H0; subst.\n(* 7 *)  \neapply2 unequal_op. unfold factorable; auto.  discriminate.\n(* 6 *)  \nassert(status (App P1 P2) = Passive). eapply2 closed_implies_passive. \nrewrite H1 in H4; discriminate.\n(* 5 *)  \neapply transitive_red. eapply2 equal_compounds. simpl. \neapply transitive_red. eapply preserves_app_sf_red. eapply preserves_app_sf_red.\neapply2 equal_comb_op. \neapply2 IHP2. auto.  eval_tac.\n(* 4 *) \neapply transitive_red. eapply2 equal_compounds. simpl. \neapply transitive_red. eapply preserves_app_sf_red. eapply preserves_app_sf_red.\neapply2 IHP1. simpl in *; max_out. auto. auto. eval_tac. eval_tac. \n(* 3 *) \neapply transitive_red. eapply2 equal_compounds. simpl. \neapply transitive_red. eapply preserves_app_sf_red. eapply preserves_app_sf_red.\nauto. eapply2 IHP2. simpl in *; max_out. auto. auto. eval_tac. eval_tac. \neapply transitive_red. eapply preserves_app_sf_red. eapply preserves_app_sf_red.\n\n\n  \neapply2 equal_compounds. auto. auto. simpl. \neapply transitive_red. eapply preserves_app_sf_red. eapply preserves_app_sf_red.\neapply preserves_app_sf_red. eapply preserves_app_sf_red.\neapply2 equal_comb_op.\nassert(\n\n\n eappy2 IHP1. \neapply2 equal_compounds. auto. auto. simpl. \n\n\n eapply2 IHP2. max_out.  simpl. eapply2 equal_comb_op. \neapply2 IHP2. auto.  eval_tac.\n\nassert(status (App P1 P2) = Passive). eapply2 closed_implies_passive. \nrewrite H1 in H3; discriminate. \nassert(status (App P1 P2) = Passive). eapply2 closed_implies_passive. \nrewrite H1 in H3; discriminate. \nQed. \n\n\nLemma case_by_matchfail:\n  forall P N R,  matchfail P N  -> forall M, sf_red (App (App (case P M) N) R) (App R N). \nProof.\n  induction P; intros; inversion H; subst.\n  (* 7 *)\n  unfold case; fold case. \ngeneralize H2; clear H2; case o; intro. \neapply transitive_red. eapply preserves_app_sf_red.\neapply2 star_opt_beta.  auto. \nunfold subst; rewrite ! subst_rec_app.\nrewrite subst_rec_closed. \nunfold lift; rewrite ! subst_rec_lift_rec; try omega.\nrewrite lift_rec_null. \n2: simpl; omega. \nunfold swap, subst_rec; fold subst_rec. \ninsert_Ref_out. \nrewrite ! subst_rec_closed. \n2: simpl; auto. 2: simpl; auto. \nunfold lift; rewrite lift_rec_null. \ninversion H1. inversion H0. subst.\ngen_case H2 x; congruence. \ninversion H0; subst. \neapply transitive_red. eapply preserves_app_sf_red. \neapply2 factor_stem. auto. eval_tac. eval_tac.\neapply transitive_red. eapply preserves_app_sf_red. \neapply succ_red. eapply2 k_red. auto.  eval_tac.  auto. \neapply transitive_red. eapply preserves_app_sf_red. \neapply2 factor_fork. auto. eval_tac. eval_tac.\neapply transitive_red. eapply preserves_app_sf_red. \neapply succ_red. eapply2 k_red. auto.  eval_tac.  auto.\n  (* 6 *) \n  unfold case; fold case.\nassert(is_program (App P1 P2) = true \\/ is_program(App P1 P2) <> true)\nby decide equality. \ninversion H0. \nrewrite H1. \nassert(program (App P1 P2)) by eapply2 program_is_program. \neapply transitive_red.  eapply preserves_app_sf_red. \neapply2 star_opt_beta. auto. \nunfold subst; rewrite ! subst_rec_app. rewrite subst_rec_closed.\nunfold  subst_rec; fold subst_rec.  \ninsert_Ref_out. 2: rewrite equal_comb_closed; omega. \nunfold lift; rewrite subst_rec_lift_rec; try omega. rewrite ! lift_rec_null.\nreplace (subst_rec (swap (Ref 0)) (Op o) 0) \nwith  (swap (Op o)) by (unfold swap; unfold_op; unfold subst_rec; auto). \nrewrite ! subst_rec_closed. \n2: unfold_op; auto.  \neapply transitive_red. eapply preserves_app_sf_red. \neapply preserves_app_sf_red. eapply preserves_app_sf_red. \neapply2 unequal_op. \neapply2 programs_are_factorable.  discriminate. auto. auto. auto. \nunfold_op; eval_tac. eval_tac. eval_tac.  \neapply2 preserves_app_sf_red;  eval_tac.\ninversion H2. simpl in H5; max_out; omega. \ninversion H2; simpl in H5; max_out; omega. \n(* 6 *) \nassert(is_program (App P1 P2) = false) by \neapply2 not_true_iff_false. \nrewrite H2. \nunfold case_app.\neapply transitive_red. eapply preserves_app_sf_red. \neapply2 star_opt_beta. auto. \nunfold subst; rewrite ! subst_rec_app.\nrewrite subst_rec_closed. \nunfold lift; rewrite ! subst_rec_lift_rec; try omega.\nrewrite lift_rec_null. \n2: simpl; omega. \nunfold swap, subst_rec; fold subst_rec. \ninsert_Ref_out. \nrewrite ! subst_rec_closed. \n2: simpl; auto. 2: simpl; auto. \nunfold lift; rewrite lift_rec_null. \ncase o.\neapply transitive_red. eapply preserves_app_sf_red. \neapply preserves_app_sf_red. \neapply2 factor_leaf.  auto. auto. \n eval_tac. eval_tac.  eval_tac.\neapply transitive_red. eapply preserves_app_sf_red. \n   eval_tac. eval_tac. auto. \n(* 5 *) \nunfold case; fold case.\nassert(is_program (App P1 P2) = true \\/ is_program(App P1 P2) <> true)\nby decide equality. \ninversion H0. \nassert(program (App P1 P2)) by eapply2 program_is_program.\ninversion H2. \nassert(status (App P1 P2) = Passive) by eapply2 closed_implies_passive.\nrewrite H6 in H3; discriminate.  \n(* 5 *) \nassert(is_program (App P1 P2) = false) by \neapply2 not_true_iff_false. \nrewrite H2. \nunfold case_app.  eapply transitive_red. eapply preserves_app_sf_red. \neapply2 star_opt_beta. auto. \nunfold subst; rewrite ! subst_rec_app.\nrewrite subst_rec_closed. \nunfold lift; rewrite ! subst_rec_lift_rec; try omega.\nrewrite lift_rec_null. \n2: simpl; omega. \nunfold swap, subst_rec; fold subst_rec. \ninsert_Ref_out. \nrewrite ! subst_rec_closed. \n2: simpl; auto. 2: simpl; auto. \nunfold lift; rewrite lift_rec_null. \ncase o.\neapply transitive_red. eapply preserves_app_sf_red. \neapply preserves_app_sf_red. \neapply2 factor_leaf.  auto. auto. \n eval_tac. eval_tac.  eval_tac.\neapply transitive_red. eapply preserves_app_sf_red. \n   eval_tac. eval_tac. auto. \n(* 4 *) \n  unfold case; fold case.\nassert(is_program (App P1 P2) = true \\/ is_program(App P1 P2) <> true)\nby decide equality. \ninversion H0. \nrewrite H1. \nassert(program (App P1 P2)) by eapply2 program_is_program. \neapply transitive_red.  eapply preserves_app_sf_red. \neapply2 star_opt_beta. auto. \nunfold subst; rewrite ! subst_rec_app. rewrite subst_rec_closed. \nunfold subst_rec; fold subst_rec. insert_Ref_out. 2: rewrite equal_comb_closed; omega. \nunfold lift; rewrite subst_rec_lift_rec; try omega. rewrite ! lift_rec_null.\nreplace (subst_rec (swap (Ref 0)) (App M1 M2) 0)\nwith (swap (App M1 M2))\nby (unfold swap; unfold_op; unfold subst_rec; fold subst_rec; \ninsert_Ref_out; unfold lift; rewrite lift_rec_null; auto). \nrewrite ! subst_rec_closed. \n2: unfold_op; auto.  \neapply transitive_red. eapply preserves_app_sf_red. \neapply preserves_app_sf_red. eapply preserves_app_sf_red. \neapply2 equal_compounds. auto. auto. auto.  simpl. \neapply transitive_red. eapply preserves_app_sf_red.  eapply preserves_app_sf_red. \neapply preserves_app_sf_red.  eapply preserves_app_sf_red. eapply preserves_app_sf_red. \neapply2 matchfail_unequal. inversion H4.  simpl in H7; max_out. auto. auto. auto. auto. auto. \neval_tac. eval_tac. eval_tac. eval_tac. \neapply2 preserves_app_sf_red; eval_tac. \ninversion H4; simpl in H7; max_out; omega. \ninversion H4; simpl in H7; max_out; omega. \nassert(is_program (App P1 P2) = false) by \neapply2 not_true_iff_false. \nrewrite H4. \nunfold case_app.\neapply transitive_red.  eapply preserves_app_sf_red. \neapply2 star_opt_beta. auto. \nunfold subst; rewrite ! subst_rec_app. rewrite subst_rec_closed. \nunfold subst_rec; fold subst_rec. insert_Ref_out. 2: simpl; omega. \nunfold lift; rewrite subst_rec_lift_rec; try omega. rewrite ! lift_rec_null.\nreplace (subst_rec (swap (Ref 0)) (App M1 M2) 0)\nwith (swap (App M1 M2))\nby (unfold swap; unfold_op; unfold subst_rec; fold subst_rec; \ninsert_Ref_out; unfold lift; rewrite lift_rec_null; auto). \nrewrite ! subst_rec_closed. \n2: unfold_op; auto.\n(* 4 *) \ninversion H3; subst.   \neapply transitive_red. eapply preserves_app_sf_red. \neapply preserves_app_sf_red.\neapply2 factor_stem.\nauto. auto.  \neapply transitive_red. eapply preserves_app_sf_red. \neapply preserves_app_sf_red.\n eapply star_opt_beta2.  auto. auto.\nunfold subst; rewrite ! subst_rec_app. \nunfold lift; rewrite ! subst_rec_lift_rec; try omega. rewrite ! lift_rec_null.\nunfold subst_rec; fold subst_rec. insert_Ref_out. unfold_op. \nunfold subst_rec; fold subst_rec. insert_Ref_out.\nunfold lift;  rewrite ! lift_rec_null. \nrewrite ! subst_rec_lift_rec; try omega.\nrewrite ! lift_rec_null.   \neapply transitive_red. eapply preserves_app_sf_red.  eapply preserves_app_sf_red. \neapply preserves_app_sf_red.  eapply preserves_app_sf_red. \neapply2 IHP1. auto. auto. auto. auto. eval_tac. eval_tac. eval_tac. \neapply transitive_red. eapply preserves_app_sf_red. \neapply succ_red. eapply2 k_red.  auto. eval_tac.  auto. \n(* 4 *) \neapply transitive_red. eapply preserves_app_sf_red. \neapply preserves_app_sf_red.\neapply2 factor_fork.\nauto. auto.  \neapply transitive_red. eapply preserves_app_sf_red. \neapply preserves_app_sf_red.\n eapply star_opt_beta2.  auto. auto.\nunfold subst; rewrite ! subst_rec_app. \nunfold lift; rewrite ! subst_rec_lift_rec; try omega. rewrite ! lift_rec_null.\nunfold subst_rec; fold subst_rec. insert_Ref_out. unfold_op. \nunfold subst_rec; fold subst_rec. insert_Ref_out.\nunfold lift;  rewrite ! lift_rec_null. \nrewrite ! subst_rec_lift_rec; try omega.\nrewrite ! lift_rec_null.   \neapply transitive_red. eapply preserves_app_sf_red.  eapply preserves_app_sf_red. \neapply preserves_app_sf_red.  eapply preserves_app_sf_red. \neapply2 IHP1. auto. auto. auto. auto. eval_tac. eval_tac. eval_tac. \neapply transitive_red. eapply preserves_app_sf_red. \neapply succ_red. eapply2 k_red.  auto. eval_tac.  auto.\n(* 3 *) \n  unfold case; fold case.\nassert(is_program (App P1 P2) = true \\/ is_program(App P1 P2) <> true)\nby decide equality. \ninversion H0. \nrewrite H1. \nassert(program (App P1 P2)) by eapply2 program_is_program. \neapply transitive_red.  eapply preserves_app_sf_red. \neapply2 star_opt_beta. auto. \nunfold subst; rewrite ! subst_rec_app. rewrite subst_rec_closed. \nunfold subst_rec; fold subst_rec. insert_Ref_out. 2: rewrite equal_comb_closed; omega. \nunfold lift; rewrite subst_rec_lift_rec; try omega. rewrite ! lift_rec_null.\nreplace (subst_rec (swap (Ref 0)) (App M1 M2) 0)\nwith (swap (App M1 M2))\nby (unfold swap; unfold_op; unfold subst_rec; fold subst_rec; \ninsert_Ref_out; unfold lift; rewrite lift_rec_null; auto). \nrewrite ! subst_rec_closed. \n2: unfold_op; auto.   \neapply transitive_red. eapply preserves_app_sf_red. \neapply preserves_app_sf_red. eapply preserves_app_sf_red. \neapply2 equal_compounds. auto. auto. auto.  simpl. \neapply transitive_red. eapply preserves_app_sf_red.  eapply preserves_app_sf_red. \neapply preserves_app_sf_red.  eapply preserves_app_sf_red. eapply preserves_app_sf_red. \nassert(M1 = P1 /\\ sigma1 = nil). eapply2 program_matching3. inversion H5. simpl in *; max_out.\n inversion H7; subst. \neapply2 equal_programs. eapply2 (program_app P1 P2).\neapply2 matchfail_unequal. inversion H5; simpl in *; max_out. \nauto. auto. auto.  auto. eval_tac. eval_tac. eval_tac.  \neapply2 preserves_app_sf_red; eval_tac. \ninversion H5; simpl in *; max_out; omega. \ninversion H5; simpl in *; max_out; omega. \nassert(is_program (App P1 P2) = false) by \neapply2 not_true_iff_false.\nrewrite H5. \n(* 3 *)  \nunfold case_app.\neapply transitive_red.  eapply preserves_app_sf_red. \neapply2 star_opt_beta. auto. \nunfold subst; rewrite ! subst_rec_app. rewrite subst_rec_closed. \nunfold subst_rec; fold subst_rec. insert_Ref_out. 2: simpl; omega. \nunfold lift; rewrite subst_rec_lift_rec; try omega. rewrite ! lift_rec_null.\nreplace (subst_rec (swap (Ref 0)) (App M1 M2) 0)\nwith (swap (App M1 M2))\nby (unfold swap; unfold_op; unfold subst_rec; fold subst_rec; \ninsert_Ref_out; unfold lift; rewrite lift_rec_null; auto). \nrewrite ! subst_rec_closed. \n2: unfold_op; auto.\n(* 3 *) \ninversion H3; subst.   \neapply transitive_red. eapply preserves_app_sf_red. \neapply preserves_app_sf_red.\neapply2 factor_stem.\nauto. auto.  \neapply transitive_red. eapply preserves_app_sf_red. \neapply preserves_app_sf_red.\n eapply star_opt_beta2.  auto. auto.\nunfold subst; rewrite ! subst_rec_app. \nunfold lift; rewrite ! subst_rec_lift_rec; try omega. rewrite ! lift_rec_null.\nunfold subst_rec; fold subst_rec. insert_Ref_out. unfold_op. \nunfold subst_rec; fold subst_rec. insert_Ref_out.\nunfold lift;  rewrite ! lift_rec_null. \nrewrite ! subst_rec_lift_rec; try omega.\nrewrite ! lift_rec_null.   \neapply transitive_red. eapply preserves_app_sf_red.  eapply preserves_app_sf_red. \neapply preserves_app_sf_red.  eapply preserves_app_sf_red. eapply preserves_app_sf_red.\neapply2 case_by_matching.  auto. auto. auto. auto. auto.  \neapply transitive_red. eapply preserves_app_sf_red.  eapply preserves_app_sf_red. \neapply preserves_app_sf_red.  eapply preserves_app_sf_red. eapply succ_red. eapply2 k_red.\nauto. auto. auto. auto. auto.  \nrewrite ! fold_subst_list.\neapply transitive_red. eapply list_subst_preserves_sf_red. \neapply preserves_app_sf_red. eapply preserves_app_sf_red.\neapply IHP2. eapply2 matchfail_lift. \nunfold lift; simpl. auto. auto.  unfold lift; simpl. \neapply transitive_red. eapply list_subst_preserves_sf_red. eval_tac. \neapply transitive_red. eapply list_subst_preserves_sf_red. eval_tac. \nrepeat rewrite list_subst_preserves_app. repeat rewrite list_subst_preserves_op. eval_tac. \n eapply transitive_red. eapply preserves_app_sf_red. eapply succ_red.  eapply2 k_red. auto. \neapply succ_red.  eapply2 k_red. auto.   \nreplace(lift_rec R 0 (length sigma1)) with (lift (length sigma1) R) by auto. \nreplace(lift_rec M2 0 (length sigma1)) with (lift (length sigma1) M2) by auto.\neapply2 preserves_app_sf_red. \n rewrite list_subst_lift; auto.  rewrite ! list_subst_lift; auto.\n(* 3 *) \neapply transitive_red. eapply preserves_app_sf_red. \neapply preserves_app_sf_red.\neapply2 factor_fork.\nauto. auto.  \neapply transitive_red. eapply preserves_app_sf_red. \neapply preserves_app_sf_red.\n eapply star_opt_beta2.  auto. auto.\nunfold subst; rewrite ! subst_rec_app. \nunfold lift; rewrite ! subst_rec_lift_rec; try omega. rewrite ! lift_rec_null.\nunfold subst_rec; fold subst_rec. insert_Ref_out. unfold_op. \nunfold subst_rec; fold subst_rec. insert_Ref_out.\nunfold lift;  rewrite ! lift_rec_null. \nrewrite ! subst_rec_lift_rec; try omega.\nrewrite ! lift_rec_null.   \neapply transitive_red. eapply preserves_app_sf_red.  eapply preserves_app_sf_red. \neapply preserves_app_sf_red.  eapply preserves_app_sf_red. eapply preserves_app_sf_red.\neapply2 case_by_matching.  auto. auto. auto. auto. auto.  \neapply transitive_red. eapply preserves_app_sf_red.  eapply preserves_app_sf_red. \neapply preserves_app_sf_red.  eapply preserves_app_sf_red. eapply succ_red. eapply2 k_red.\nauto. auto. auto. auto. auto.  \nrewrite ! fold_subst_list.\neapply transitive_red. eapply list_subst_preserves_sf_red. \neapply preserves_app_sf_red. eapply preserves_app_sf_red.\neapply IHP2. eapply2 matchfail_lift. \nunfold lift; simpl. auto. auto.  unfold lift; simpl. \neapply transitive_red. eapply list_subst_preserves_sf_red. eval_tac. \neapply transitive_red. eapply list_subst_preserves_sf_red. eval_tac. \nrepeat rewrite list_subst_preserves_app. repeat rewrite list_subst_preserves_op. eval_tac. \n eapply transitive_red. eapply preserves_app_sf_red. eapply succ_red.  eapply2 k_red. auto. \neapply succ_red.  eapply2 k_red. auto.   \nreplace(lift_rec R 0 (length sigma1)) with (lift (length sigma1) R) by auto. \nreplace(lift_rec M0 0 (length sigma1)) with (lift (length sigma1) M0) by auto.\nreplace(lift_rec M2 0 (length sigma1)) with (lift (length sigma1) M2) by auto.\neapply2 preserves_app_sf_red. \n rewrite list_subst_lift; auto.  rewrite ! list_subst_lift; auto.\n(* 2 *) \n unfold case; fold case.\nassert(is_program (App P1 P2) = true \\/ is_program(App P1 P2) <> true)\nby decide equality. \ninversion H0. \nrewrite H1. \nassert(program (App P1 P2)) by eapply2 program_is_program.\nassert(factorable (App P1 P2)) by eapply2 programs_are_factorable. \ninversion H6; subst. inversion H7; discriminate. \ninversion H7; subst; simpl in H2; discriminate.   \nassert(is_program (App P1 P2) = false) by \neapply2 not_true_iff_false.\nrewrite H4. \n(* 2 *)  \nunfold case_app.\neapply transitive_red.  eapply preserves_app_sf_red. \neapply2 star_opt_beta. auto. \nunfold subst; rewrite ! subst_rec_app. rewrite subst_rec_closed. \nunfold subst_rec; fold subst_rec. insert_Ref_out. 2: simpl; omega. \nunfold lift; rewrite subst_rec_lift_rec; try omega. rewrite ! lift_rec_null.\nreplace (subst_rec (swap (Ref 0)) (App M1 M2) 0)\nwith (swap (App M1 M2))\nby (unfold swap; unfold_op; unfold subst_rec; fold subst_rec; \ninsert_Ref_out; unfold lift; rewrite lift_rec_null; auto). \nrewrite ! subst_rec_closed. \n2: unfold_op; auto.\n(* 2 *) \ninversion H3; subst.   \neapply transitive_red. eapply preserves_app_sf_red. \neapply preserves_app_sf_red.\neapply2 factor_stem.\nauto. auto.  \neapply transitive_red. eapply preserves_app_sf_red. \neapply preserves_app_sf_red.\n eapply star_opt_beta2.  auto. auto.\nunfold subst; rewrite ! subst_rec_app. \nunfold lift; rewrite ! subst_rec_lift_rec; try omega. rewrite ! lift_rec_null.\nunfold subst_rec; fold subst_rec. insert_Ref_out. unfold_op. \nunfold subst_rec; fold subst_rec. insert_Ref_out.\nunfold lift;  rewrite ! lift_rec_null. \nrewrite ! subst_rec_lift_rec; try omega.\nrewrite ! lift_rec_null.   \neapply transitive_red. eapply preserves_app_sf_red.  eapply preserves_app_sf_red. \neapply preserves_app_sf_red.  eapply preserves_app_sf_red.\neapply2 IHP1. auto. auto. auto. auto.  eval_tac. eval_tac. eval_tac. \neapply transitive_red. eapply preserves_app_sf_red.  eapply succ_red. eapply2 k_red.\nauto. eval_tac. auto. \n(* 2 *) \neapply transitive_red. eapply preserves_app_sf_red. \neapply preserves_app_sf_red.\neapply2 factor_fork.\nauto. auto.  \neapply transitive_red. eapply preserves_app_sf_red. \neapply preserves_app_sf_red.\n eapply star_opt_beta2.  auto. auto.\nunfold subst; rewrite ! subst_rec_app. \nunfold lift; rewrite! subst_rec_lift_rec; try omega. rewrite ! lift_rec_null.\nunfold subst_rec; fold subst_rec. insert_Ref_out. unfold_op. \nunfold subst_rec; fold subst_rec. insert_Ref_out.\nunfold lift;  rewrite ! lift_rec_null. \nrewrite ! subst_rec_lift_rec; try omega.\nrewrite ! lift_rec_null.   \neapply transitive_red. eapply preserves_app_sf_red.  eapply preserves_app_sf_red. \neapply preserves_app_sf_red.  eapply preserves_app_sf_red.\neapply2 IHP1. auto. auto. auto. auto.  eval_tac. eval_tac. eval_tac. \neapply transitive_red. eapply preserves_app_sf_red.  eapply succ_red. eapply2 k_red.\nauto. eval_tac. auto. \n(* 1 *) \n unfold case; fold case.\nassert(is_program (App P1 P2) = true \\/ is_program(App P1 P2) <> true)\nby decide equality. \ninversion H0. \nrewrite H1. \nassert(program (App P1 P2)) by eapply2 program_is_program. \nassert(factorable (App P1 P2)) by eapply2 programs_are_factorable. \ninversion H7; subst. inversion H8; discriminate.  \ninversion H8; subst; simpl in H2; discriminate.\n(* 1 *) \nassert(is_program (App P1 P2) = false) by \neapply2 not_true_iff_false.\nrewrite H5. \n(* 3 *)  \nunfold case_app.\neapply transitive_red.  eapply preserves_app_sf_red. \neapply2 star_opt_beta. auto. \nunfold subst; rewrite ! subst_rec_app. rewrite subst_rec_closed. \nunfold subst_rec; fold subst_rec. insert_Ref_out. 2: simpl; omega. \nunfold lift; rewrite subst_rec_lift_rec; try omega. rewrite ! lift_rec_null.\nreplace (subst_rec (swap (Ref 0)) (App M1 M2) 0)\nwith (swap (App M1 M2))\nby (unfold swap; unfold_op; unfold subst_rec; fold subst_rec; \ninsert_Ref_out; unfold lift; rewrite lift_rec_null; auto). \nrewrite ! subst_rec_closed. \n2: unfold_op; auto.\n(* 1 *) \ninversion H3; subst.   \neapply transitive_red. eapply preserves_app_sf_red. \neapply preserves_app_sf_red.\neapply2 factor_stem.\nauto. auto.  \neapply transitive_red. eapply preserves_app_sf_red. \neapply preserves_app_sf_red.\n eapply star_opt_beta2.  auto. auto.\nunfold subst; rewrite ! subst_rec_app. \nunfold lift; rewrite ! subst_rec_lift_rec; try omega. rewrite ! lift_rec_null.\nunfold subst_rec; fold subst_rec. insert_Ref_out. unfold_op. \nunfold subst_rec; fold subst_rec. insert_Ref_out.\nunfold lift;  rewrite ! lift_rec_null. \nrewrite ! subst_rec_lift_rec; try omega.\nrewrite ! lift_rec_null.   \neapply transitive_red. eapply preserves_app_sf_red.  eapply preserves_app_sf_red. \neapply preserves_app_sf_red.  eapply preserves_app_sf_red. eapply preserves_app_sf_red.\neapply2 case_by_matching.  auto. auto. auto. auto. auto.  \neapply transitive_red. eapply preserves_app_sf_red.  eapply preserves_app_sf_red. \neapply preserves_app_sf_red.  eapply preserves_app_sf_red. eapply succ_red. eapply2 k_red.\nauto. auto. auto. auto. auto.  \nrewrite ! fold_subst_list.\neapply transitive_red. eapply list_subst_preserves_sf_red. \neapply preserves_app_sf_red. eapply preserves_app_sf_red.\neapply IHP2. eapply2 matchfail_lift. \nunfold lift; simpl. auto. auto.  unfold lift; simpl. \neapply transitive_red. eapply list_subst_preserves_sf_red. eval_tac. \neapply transitive_red. eapply list_subst_preserves_sf_red. eval_tac. \nrepeat rewrite list_subst_preserves_app. repeat rewrite list_subst_preserves_op. eval_tac. \n eapply transitive_red. eapply preserves_app_sf_red. eapply succ_red.  eapply2 k_red. auto. \neapply succ_red.  eapply2 k_red. auto.   \nreplace(lift_rec R 0 (length sigma1)) with (lift (length sigma1) R) by auto. \nreplace(lift_rec M2 0 (length sigma1)) with (lift (length sigma1) M2) by auto.\neapply2 preserves_app_sf_red. \n rewrite list_subst_lift; auto.  rewrite ! list_subst_lift; auto.\n(* 1 *) \neapply transitive_red. eapply preserves_app_sf_red. \neapply preserves_app_sf_red.\neapply2 factor_fork.\nauto. auto.  \neapply transitive_red. eapply preserves_app_sf_red. \neapply preserves_app_sf_red.\n eapply star_opt_beta2.  auto. auto.\nunfold subst; rewrite ! subst_rec_app. \nunfold lift; rewrite ! subst_rec_lift_rec; try omega. rewrite ! lift_rec_null.\nunfold subst_rec; fold subst_rec. insert_Ref_out. unfold_op. \nunfold subst_rec; fold subst_rec. insert_Ref_out.\nunfold lift;  rewrite ! lift_rec_null. \nrewrite ! subst_rec_lift_rec; try omega.\nrewrite ! lift_rec_null.   \neapply transitive_red. eapply preserves_app_sf_red.  eapply preserves_app_sf_red. \neapply preserves_app_sf_red.  eapply preserves_app_sf_red. eapply preserves_app_sf_red.\neapply2 case_by_matching.  auto. auto. auto. auto. auto.  \neapply transitive_red. eapply preserves_app_sf_red.  eapply preserves_app_sf_red. \neapply preserves_app_sf_red.  eapply preserves_app_sf_red. eapply succ_red. eapply2 k_red.\nauto. auto. auto. auto. auto.  \nrewrite ! fold_subst_list.\neapply transitive_red. eapply list_subst_preserves_sf_red. \neapply preserves_app_sf_red. eapply preserves_app_sf_red.\neapply IHP2. eapply2 matchfail_lift. \nunfold lift; simpl. auto. auto.  unfold lift; simpl. \neapply transitive_red. eapply list_subst_preserves_sf_red. eval_tac. \neapply transitive_red. eapply list_subst_preserves_sf_red. eval_tac. \nrepeat rewrite list_subst_preserves_app. repeat rewrite list_subst_preserves_op. eval_tac. \n eapply transitive_red. eapply preserves_app_sf_red. eapply succ_red.  eapply2 k_red. auto. \neapply succ_red.  eapply2 k_red. auto.   \nreplace(lift_rec R 0 (length sigma1)) with (lift (length sigma1) R) by auto. \nreplace(lift_rec M0 0 (length sigma1)) with (lift (length sigma1) M0) by auto.\nreplace(lift_rec M2 0 (length sigma1)) with (lift (length sigma1) M2) by auto.\neapply2 preserves_app_sf_red. \n rewrite list_subst_lift; auto.  rewrite ! list_subst_lift; auto.\nQed. \n\n\n\nProposition extensions_by_matchfail:\n  forall P N,  matchfail P N -> forall M R, sf_red (App (extension P M R) N) (App R N).\nProof.\n  intros. unfold extension. eval_tac. \n  eapply transitive_red. eapply2 case_by_matchfail.  \n  eapply transitive_red. eapply preserves_app_sf_red. eapply succ_red. eapply2 k_red. auto. \nauto. auto. \nQed. \n\nLemma match_program: \nforall P M, normal P -> program M -> matchfail P M \\/ exists sigma, matching P M sigma.\nProof. \ninduction P; split_all. \n(* 3 *) \nright. exist (cons M nil). \n(* 2 *) \ngen_case H0 M. inversion H0; split_all.  simpl in *; discriminate. \ncase o; case o0; split_all. \nright; eauto. \nleft; auto; eapply2 matchfail_op. eapply2 programs_are_factorable. discriminate. \n(* 1 *) \ngen_case H0 M; inversion H0; auto. \n(* 2 *) \nsimpl in *; discriminate. \n(* 2 *) \ninversion H; subst; left; auto. \n(* 1 *) \ninversion H; subst. inversion H1; subst.\n(* 3 *)  \nassert(status (App s s0) = Passive) by eapply2 closed_implies_passive. \nrewrite H3 in H10; discriminate. \n(* 2 *) \nsimpl in H2; max_out. \nassert(matchfail P1 s \\/ (exists sigma : list SF, matching P1 s sigma)).\neapply2 IHP1. unfold program; split_all. \nassert(matchfail P2 s0 \\/ (exists sigma : list SF, matching P2 s0 sigma)). \neapply2 IHP2. unfold program; split_all. \n(* 2 *) \ninversion H2. left; eapply2 matchfail_active_l.\ninversion H11. \ninversion H12. left; eapply2 matchfail_active_r.\ninversion H12; inversion H13. \nright; exist (map (lift (length x)) x0++x). \n(* 1 *) \ninversion H1; subst.\n(* 3 *)  \nassert(status (App s s0) = Passive) by eapply2 closed_implies_passive. \nrewrite H3 in H10; discriminate. \n(* 1 *) \nsimpl in H2; max_out. \nassert(matchfail P1 s \\/ (exists sigma : list SF, matching P1 s sigma)).\neapply2 IHP1. unfold program; split_all. \nassert(matchfail P2 s0 \\/ (exists sigma : list SF, matching P2 s0 sigma)). \neapply2 IHP2. unfold program; split_all. \n(* 2 *) \ninversion H2. left; eapply2 matchfail_compound_l. \ninversion H11; inversion H12; subst. left; eapply2 matchfail_compound_r. \ninversion H13; subst. right; eauto.\nQed. \n\n", "meta": {"author": "Barry-Jay", "repo": "Tree-calculus", "sha": "6959925d2b851020b6945036078a97c0b2a0d19f", "save_path": "github-repos/coq/Barry-Jay-Tree-calculus", "path": "github-repos/coq/Barry-Jay-Tree-calculus/Tree-calculus-6959925d2b851020b6945036078a97c0b2a0d19f/experiment_Extension.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.5, "lm_q1q2_score": 0.28874768259290584}}
{"text": "(*****************************************************************\n\n Type indexed enriched coproducts\n\n In this file, we define type indexed coproducts for enriched\n categories. The ideas are similar as for binary coproducts; the\n only difference being that instead of having two summands, the\n summands are indexed by a type.\n\n Content\n 1. Cocones of enriched coproducts\n 2. Coproducts in an enriched category\n 3. Being a coproduct is a proposition\n 4. Coproducts in the underlying category\n 5. Builders for coproducts\n 6. Coproducts are closed under iso\n 7. Coproducts are isomorphic\n 8. Enriched categories with coproducts\n\n *****************************************************************)\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Isos.\nRequire Import UniMath.CategoryTheory.Core.Univalence.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.Monoidal.Categories.\nRequire Import UniMath.CategoryTheory.EnrichedCats.Enrichment.\nRequire Import UniMath.CategoryTheory.limits.products.\nRequire Import UniMath.CategoryTheory.limits.coproducts.\n\nImport MonoidalNotations.\nLocal Open Scope cat.\nLocal Open Scope moncat.\n\nSection EnrichedCoproducts.\n  Context {V : monoidal_cat}\n          {C : category}\n          (E : enrichment C V)\n          {J : UU}\n          (D : J → C).\n\n  (**\n   1. Cocones of enriched coproducts\n   *)\n  Definition enriched_coprod_cocone\n    : UU\n    := ∑ (a : C), ∏ (j : J), I_{V} --> E ⦃ D j , a ⦄.\n\n  Coercion ob_enriched_coprod_cocone\n           (a : enriched_coprod_cocone)\n    : C\n    := pr1 a.\n\n  Definition enriched_coprod_cocone_in\n             (a : enriched_coprod_cocone)\n             (j : J)\n    : D j --> a\n    := enriched_to_arr E (pr2 a j).\n\n  Definition make_enriched_coprod_cocone\n             (a : C)\n             (p : ∏ (j : J), I_{V} --> E ⦃ D j , a ⦄)\n    : enriched_coprod_cocone\n    := a ,, p.\n\n  (**\n   2. Coproducts in an enriched category\n   *)\n  Definition is_coprod_enriched\n             (a : enriched_coprod_cocone)\n    : UU\n    := ∏ (w : C),\n       isProduct\n         J V\n         (λ j, E ⦃ D j , w ⦄)\n         (E ⦃ a , w ⦄)\n         (λ j, precomp_arr E w (enriched_coprod_cocone_in a j)).\n\n  Definition is_coprod_enriched_to_Product\n             {a : enriched_coprod_cocone}\n             (Ha : is_coprod_enriched a)\n             (w : C)\n    : Product\n        J V\n        (λ j, E ⦃ D j , w ⦄).\n  Proof.\n    use make_Product.\n    - exact (E ⦃ a , w ⦄).\n    - exact (λ j, precomp_arr E w (enriched_coprod_cocone_in a j)).\n    - exact (Ha w).\n  Defined.\n\n  Definition coprod_enriched\n    : UU\n    := ∑ (a : enriched_coprod_cocone),\n       is_coprod_enriched a.\n\n  Coercion cocone_of_coprod_enriched\n           (a : coprod_enriched)\n    : enriched_coprod_cocone\n    := pr1 a.\n\n  Coercion coprod_enriched_is_coprod\n           (a : coprod_enriched)\n    : is_coprod_enriched a\n    := pr2 a.\n\n  (**\n   3. Being a coproduct is a proposition\n   *)\n  Proposition isaprop_is_coprod_enriched\n              (a : enriched_coprod_cocone)\n    : isaprop (is_coprod_enriched a).\n  Proof.\n    repeat (use impred ; intro).\n    apply isapropiscontr.\n  Qed.\n\n  (**\n   4. Coproducts in the underlying category\n   *)\n  Section InUnderlying.\n    Context {a : enriched_coprod_cocone}\n            (Ha : is_coprod_enriched a).\n\n    Definition is_coprod_enriched_arrow\n               {w : C}\n               (f : ∏ (j : J), D j --> w)\n      : a --> w.\n    Proof.\n      refine (enriched_to_arr E _).\n      use (ProductArrow _ _ (is_coprod_enriched_to_Product Ha w)).\n      exact (λ j, enriched_from_arr E (f j)).\n    Defined.\n\n    Proposition is_coprod_enriched_arrow_in\n                {w : C}\n                (f : ∏ (j : J), D j --> w)\n                (j : J)\n      : enriched_coprod_cocone_in a j · is_coprod_enriched_arrow f\n        =\n        f j.\n    Proof.\n      unfold is_coprod_enriched_arrow, enriched_coprod_cocone_in.\n      use (invmaponpathsweq (make_weq _ (isweq_enriched_from_arr E _ _))) ; cbn.\n      refine (_ @ ProductPrCommutes\n                    _ _ _\n                    (is_coprod_enriched_to_Product Ha w)\n                    _\n                    (λ j, enriched_from_arr E (f j))\n                    j).\n      cbn.\n      unfold precomp_arr, enriched_coprod_cocone_in.\n      rewrite enriched_from_arr_comp.\n      rewrite !assoc.\n      apply maponpaths_2.\n      rewrite tensor_rinvunitor.\n      rewrite !assoc'.\n      rewrite mon_linvunitor_I_mon_rinvunitor_I.\n      apply maponpaths.\n      rewrite <- tensor_split'.\n      rewrite !enriched_from_to_arr.\n      apply idpath.\n    Qed.\n\n    Proposition is_coprod_enriched_arrow_eq\n                {w : C}\n                {f g : a --> w}\n                (q : ∏ (j : J),\n                     enriched_coprod_cocone_in a j · f\n                     =\n                     enriched_coprod_cocone_in a j · g)\n      : f = g.\n    Proof.\n      refine (!(enriched_to_from_arr E _) @ _ @ enriched_to_from_arr E _).\n      apply maponpaths.\n      use (ProductArrow_eq\n               _ _ _\n               (is_coprod_enriched_to_Product Ha w)).\n      intro j.\n      cbn.\n      unfold precomp_arr.\n      rewrite !assoc.\n      rewrite !tensor_rinvunitor.\n      rewrite !assoc'.\n      rewrite !(maponpaths (λ z, _ · z) (assoc _ _ _)).\n      rewrite <- !tensor_split'.\n      use (invmaponpathsweq (make_weq _ (isweq_enriched_to_arr E _ _))) ; cbn.\n      rewrite !assoc.\n      rewrite mon_rinvunitor_I_mon_linvunitor_I.\n      rewrite <- !(enriched_to_arr_comp E).\n      exact (q j).\n    Qed.\n\n    Definition underlying_Coproduct\n      : Coproduct J C D.\n    Proof.\n      use make_Coproduct.\n      - exact a.\n      - exact (enriched_coprod_cocone_in a).\n      - intros w f.\n        use iscontraprop1.\n        + abstract\n            (use invproofirrelevance ;\n             intros φ₁ φ₂ ;\n             use subtypePath ; [ intro ; use impred ; intro ; apply homset_property | ] ;\n             exact (is_coprod_enriched_arrow_eq\n                      (λ j, pr2 φ₁ j @ !(pr2 φ₂ j)))).\n        + exact (is_coprod_enriched_arrow f\n                 ,,\n                 is_coprod_enriched_arrow_in f).\n    Defined.\n  End InUnderlying.\n\n  (**\n   5. Builders for coproducts\n   *)\n  Definition make_is_coprod_enriched\n             (a : enriched_coprod_cocone)\n             (sum : ∏ (w : C) (v : V)\n                      (f : ∏ (j : J), v --> E ⦃ D j , w ⦄),\n                     v --> E ⦃ a , w ⦄)\n             (in_sum : ∏ (w : C) (v : V)\n                         (f : ∏ (j : J), v --> E ⦃ D j , w ⦄)\n                         (j : J),\n                       sum w v f · precomp_arr E w (enriched_coprod_cocone_in a j)\n                       =\n                       f j)\n             (sum_eq : ∏ (w : C) (v : V)\n                         (φ₁ φ₂ : v --> E ⦃ a , w ⦄)\n                         (q : ∏ (j : J),\n                          φ₁ · precomp_arr E w (enriched_coprod_cocone_in a j)\n                          =\n                          φ₂ · precomp_arr E w (enriched_coprod_cocone_in a j)),\n                       φ₁ = φ₂)\n    : is_coprod_enriched a.\n  Proof.\n    intro w.\n    use make_isProduct.\n    { apply homset_property. }\n    intros v f.\n    use iscontraprop1.\n    - abstract\n        (use invproofirrelevance ;\n         intros φ₁ φ₂ ;\n         use subtypePath ; [ intro ; use impred ; intro ; apply homset_property | ] ;\n         exact (sum_eq\n                  w v\n                  (pr1 φ₁) (pr1 φ₂)\n                  (λ j, pr2 φ₁ j @ !(pr2 φ₂ j)))).\n    - simple refine (_ ,, _).\n      + exact (sum w v f).\n      + exact (in_sum w v f).\n  Defined.\n\n  Definition coprod_enriched_to_prod\n             (PV : Products J V)\n             (a : enriched_coprod_cocone)\n             (w : C)\n    : E ⦃ a , w ⦄ --> PV (λ j, E ⦃ D j , w ⦄).\n  Proof.\n    use ProductArrow.\n    exact (λ j, precomp_arr E w (enriched_coprod_cocone_in a j)).\n  Defined.\n\n  Definition make_is_coprod_enriched_from_z_iso\n             (PV : Products J V)\n             (a : enriched_coprod_cocone)\n             (Ha : ∏ (w : C),\n                   is_z_isomorphism (coprod_enriched_to_prod PV a w))\n    : is_coprod_enriched a.\n  Proof.\n    intro w.\n    use (isProduct_z_iso _ _ _ _ (pr2 (PV (λ j, E ⦃ D j , w ⦄)))).\n    - exact (z_iso_inv (_ ,, Ha w)).\n    - abstract\n        (intro j ;\n         unfold coprod_enriched_to_prod ; cbn ;\n         refine (!_) ;\n         apply (ProductPrCommutes _ _ _ (PV (λ j, E ⦃ D j , w ⦄)))).\n  Defined.\n\n  Section CoproductFromUnderlying.\n    Context (PV : Products J V)\n            (a : enriched_coprod_cocone)\n            (coprod : isCoproduct J C D a (enriched_coprod_cocone_in a))\n            (w : C).\n\n    Definition coprod_from_underlying_arr_map\n               (f : I_{V} --> PV (λ j, E ⦃ D j , w ⦄))\n      : I_{V} --> E ⦃ a , w ⦄.\n    Proof.\n      apply enriched_from_arr.\n      use (CoproductArrow _ _ (make_Coproduct _ _ _ _ _ coprod)).\n      intro j.\n      exact (enriched_to_arr E (f · ProductPr _ _ _ j)).\n    Defined.\n\n    Proposition coprod_from_underlying_arr_map_eq₁\n                (f : I_{V} --> E ⦃ a , w ⦄)\n      : coprod_from_underlying_arr_map (f · coprod_enriched_to_prod PV a w)\n        =\n        f.\n    Proof.\n      unfold coprod_from_underlying_arr_map.\n      refine (_ @ enriched_from_to_arr E f).\n      apply maponpaths.\n      use (CoproductArrow_eq\n             _ _ _\n             (make_Coproduct _ _ _ _ _ coprod)).\n      unfold coprod_enriched_to_prod.\n      intro j.\n      rewrite CoproductInCommutes ; cbn.\n      rewrite (enriched_to_arr_comp E).\n      apply maponpaths.\n      rewrite !assoc'.\n      etrans.\n      {\n        apply maponpaths.\n        apply (ProductPrCommutes _ _ _ (PV (λ k, E ⦃ D k , w ⦄)) _ _ j).\n      }\n      unfold precomp_arr.\n      rewrite !assoc.\n      rewrite tensor_rinvunitor.\n      rewrite mon_linvunitor_I_mon_rinvunitor_I.\n      rewrite !assoc'.\n      apply maponpaths.\n      rewrite !assoc.\n      rewrite <- tensor_split'.\n      rewrite enriched_from_to_arr.\n      apply idpath.\n    Qed.\n\n    Proposition coprod_from_underlying_arr_map_eq₂\n                (f : I_{V} --> PV (λ j, E ⦃ D j , w ⦄))\n      : coprod_from_underlying_arr_map f · coprod_enriched_to_prod PV a w\n        =\n        f.\n    Proof.\n      unfold coprod_from_underlying_arr_map.\n      use (ProductArrow_eq\n             _ _ _\n             (PV (λ j, E ⦃ D j , w ⦄))).\n      unfold coprod_enriched_to_prod.\n      intro j.\n      rewrite !assoc'.\n      etrans.\n      {\n        apply maponpaths.\n        apply (ProductPrCommutes _ _ _ (PV (λ k, E ⦃ D k , w ⦄)) _ _ j).\n      }\n      rewrite enriched_from_arr_precomp.\n      refine (_ @ enriched_from_to_arr E _).\n      apply maponpaths.\n      apply (CoproductInCommutes _ _ _ (make_Coproduct _ _ _ _ _ coprod)).\n    Qed.\n  End CoproductFromUnderlying.\n\n  Definition make_is_coprod_enriched_from_underlying\n             (PV : Products J V)\n             (a : enriched_coprod_cocone)\n             (prod : isCoproduct\n                       J C D\n                       a\n                       (enriched_coprod_cocone_in a))\n             (HV : conservative_moncat V)\n    : is_coprod_enriched a.\n  Proof.\n    use (make_is_coprod_enriched_from_z_iso PV).\n    intros w.\n    use HV.\n    use isweq_iso.\n    - exact (coprod_from_underlying_arr_map PV a prod w).\n    - exact (coprod_from_underlying_arr_map_eq₁ PV a prod w).\n    - exact (coprod_from_underlying_arr_map_eq₂ PV a prod w).\n  Defined.\n\n  (**\n   6. Coproducts are closed under iso\n   *)\n  Section CoprodIso.\n    Context (a : enriched_coprod_cocone)\n            (Ha : is_coprod_enriched a)\n            (b : C)\n            (f : z_iso b a).\n\n    Definition enriched_coprod_cocone_from_iso\n      : enriched_coprod_cocone\n      := make_enriched_coprod_cocone\n           b\n           (λ j, enriched_from_arr E (enriched_coprod_cocone_in a j · inv_from_z_iso f)).\n\n    Definition is_coprod_enriched_from_iso\n      : is_coprod_enriched enriched_coprod_cocone_from_iso.\n    Proof.\n      intros w.\n      use (isProduct_z_iso _ _ _ _ (Ha w)).\n      - exact (precomp_arr_z_iso E w f).\n      - abstract\n          (intro j ;\n           cbn ;\n           rewrite <- precomp_arr_comp ;\n           apply maponpaths ;\n           unfold enriched_coprod_cocone_from_iso ; cbn ;\n           unfold  enriched_coprod_cocone_in ; cbn ;\n           rewrite enriched_to_from_arr ;\n           apply idpath).\n    Defined.\n  End CoprodIso.\n\n  (**\n   7. Coproducts are isomorphic\n   *)\n  Definition map_between_coproduct_enriched\n             {a b : enriched_coprod_cocone}\n             (Ha : is_coprod_enriched a)\n             (Hb : is_coprod_enriched b)\n    : b --> a\n    := is_coprod_enriched_arrow\n         Hb\n         (enriched_coprod_cocone_in a).\n\n  Lemma iso_between_coproduct_enriched_inv\n        {a b : enriched_coprod_cocone}\n        (Ha : is_coprod_enriched a)\n        (Hb : is_coprod_enriched b)\n    : map_between_coproduct_enriched Ha Hb · map_between_coproduct_enriched Hb Ha\n      =\n      identity _.\n  Proof.\n    unfold map_between_coproduct_enriched.\n    use (is_coprod_enriched_arrow_eq Hb).\n    intro j.\n    rewrite !assoc.\n    rewrite !is_coprod_enriched_arrow_in.\n    rewrite id_right.\n    apply idpath.\n  Qed.\n\n  Definition iso_between_coproduct_enriched\n             {a b : enriched_coprod_cocone}\n             (Ha : is_coprod_enriched a)\n             (Hb : is_coprod_enriched b)\n    : z_iso a b.\n  Proof.\n    use make_z_iso.\n    - exact (map_between_coproduct_enriched Hb Ha).\n    - exact (map_between_coproduct_enriched Ha Hb).\n    - split.\n      + apply iso_between_coproduct_enriched_inv.\n      + apply iso_between_coproduct_enriched_inv.\n  Defined.\nEnd EnrichedCoproducts.\n\n(**\n 8. Enriched categories with coproducts\n *)\nDefinition enrichment_coprod\n           {V : monoidal_cat}\n           {C : category}\n           (E : enrichment C V)\n           (J : UU)\n  : UU\n  := ∏ (D : J → C),\n     ∑ (a : enriched_coprod_cocone E D),\n     is_coprod_enriched E D a.\n\nProposition isaprop_enrichment_coprod\n            {V : monoidal_cat}\n            {C : category}\n            (HC : is_univalent C)\n            (E : enrichment C V)\n            (J : UU)\n  : isaprop (enrichment_coprod E J).\nProof.\n  use invproofirrelevance.\n  intros φ₁ φ₂.\n  use funextsec ; intro D.\n  use subtypePath.\n  {\n    intro.\n    apply isaprop_is_coprod_enriched.\n  }\n  use total2_paths_f.\n  - use (isotoid _ HC).\n    use iso_between_coproduct_enriched.\n    + exact (pr2 (φ₁ D)).\n    + exact (pr2 (φ₂ D)).\n  - rewrite transportf_sec_constant.\n    use funextsec.\n    intro j.\n    rewrite transportf_enriched_arr_r.\n    rewrite idtoiso_isotoid.\n    cbn.\n    refine (_ @ enriched_from_to_arr E _).\n    apply maponpaths.\n    unfold map_between_coproduct_enriched ; cbn.\n    etrans.\n    {\n      apply is_coprod_enriched_arrow_in.\n    }\n    apply idpath.\nQed.\n\nDefinition cat_with_enrichment_coproduct\n           (V : monoidal_cat)\n           (J : UU)\n  : UU\n  := ∑ (C : cat_with_enrichment V), enrichment_coprod C J.\n\nCoercion cat_with_enrichment_coproduct_to_cat_with_enrichment\n         {V : monoidal_cat}\n         {J : UU}\n         (C : cat_with_enrichment_coproduct V J)\n  : cat_with_enrichment V\n  := pr1 C.\n\nDefinition coproducts_of_cat_with_enrichment\n           {V : monoidal_cat}\n           {J : UU}\n           (C : cat_with_enrichment_coproduct V J)\n  : enrichment_coprod C J\n  := pr2 C.\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/EnrichedCats/Colimits/EnrichedCoproducts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.28874176139571506}}
{"text": "Require Import PerformanceExperiments.LetIn.\nRequire Import PerformanceExperiments.Lock.\n\nReserved Notation \"'nllet' x := v 'in' f\"\n         (at level 200, f at level 200,\n          format \"'nllet'  x  :=  v  'in' '//' f\").\nDefinition LockedLet_In_nat : nat -> (nat -> nat) -> nat\n  := lock (@Let_In_nd nat nat).\nNotation \"'nllet' x := v 'in' f\"\n  := (LockedLet_In_nat v (fun x => f)).\nDefinition lock_Let_In_nat : @Let_In_nd nat nat = LockedLet_In_nat\n  := eq_sym (unlock _).\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/LockedLetIn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2887417551488881}}
{"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 * StateImplication.v\n * This file contains many defintions and tactics useful in proving that one state\n * implies another.  The key tactic is one that pairs off components of a state.\n *\n * Key definitions:\n *     stateImplication\n *     prove_implication\n *\n **********************************************************************************)\n\nRequire Import Omega.\nRequire Export SfLib.\nRequire Export ImpHeap.\nRequire Export AbsState.\nRequire Export PickElement.\nRequire Export AbsStateInstance.\n\n(* Glue stuff *)\nFixpoint no_cell_terms (s : absState) : bool :=\n    match s with\n    | AbsStar a b => if no_cell_terms a then no_cell_terms b else false\n    | AbsExists e s => no_cell_terms s\n    | AbsExistsT s => no_cell_terms s\n    | AbsAll e s => no_cell_terms s\n    | AbsEach e s => no_cell_terms s\n    | AbsLeaf (AbsCellId) l => false\n    | _ => true\n    end.\n\nFixpoint no_r_terms (s : absState) : bool :=\n    match s with\n    | AbsStar a b => if no_r_terms a then no_r_terms b else false\n    | AbsExists e s => no_r_terms s\n    | AbsExistsT s => no_r_terms s\n    | AbsAll e s => no_r_terms s\n    | AbsEach e s => no_r_terms s\n    | AbsLeaf (Id x) l => if (beq_nat x 3) (*AbsCell*) then true else if (beq_nat x 1) (*AbsPredicate*) then true else false\n    | _ => true\n    end.\n\nFixpoint r_term_list (s : absState) : list absState :=\n    match s return list (absState) with\n    | AbsStar a b => (r_term_list a)++(r_term_list b)\n    | AbsExists e s => r_term_list s\n    | AbsExistsT s => r_term_list s\n    | AbsAll e s => r_term_list s\n    | AbsEach e s => r_term_list s\n    | AbsLeaf (Id x) l => if beq_nat x 1 then nil else if beq_nat x 3 then nil else (AbsLeaf (Id x) l)::nil\n    | _ => nil\n    end.\n\nFixpoint predicate_list(s : absState) : list absState :=\n    match s return list absState with\n    | AbsStar a b => (predicate_list a)++(predicate_list b)\n    | AbsExists e s => predicate_list s\n    | AbsExistsT s => predicate_list s\n    | AbsAll e s => predicate_list s\n    | AbsEach e s => predicate_list s\n    | AbsLeaf (AbsPredicateId) l => (AbsLeaf (AbsPredicateId) l)::nil\n    | _ => nil\n    end.\n\nFixpoint strip_front_exists (s : absState) : (absState * nat) :=\n    match s with\n    | AbsExistsT s => match strip_front_exists s with\n                      (st,n) => (st,n+1)\n                      end\n    (*| AbsExists i l s => match strip_front_exists s with\n                         (st,n) => (st,n+1)\n                         end*)\n    | _ => (s,0)\n    end.\n\nFixpoint map_over (l : list (nat * nat)) (v : nat) :=\n    match l with\n    | nil => 0\n    | ((x1,x2)::r) => if beq_nat x2 v then x1 else map_over r v\n    end.\n\nFixpoint map_over_exp (l : list (nat * nat)) (limit1 : nat) (limit2 : nat) (e : absExp) : absExp :=\n   match e return absExp with\n   | AbsConstVal v => AbsConstVal v\n   | AbsVar v => AbsVar v\n   | AbsQVar v => AbsQVar (if ble_nat limit2 v then (v+limit1)-limit2 else map_over l v)\n   | AbsFun i ll => AbsFun i (map (map_over_exp l limit1 limit2) ll)\n   end.\n\nFixpoint map_over_state (l : list (nat * nat)) (limit1 : nat) (limit2 : nat) (s : absState) : absState :=\n   match s return absState with\n    | AbsStar s1 s2 => (AbsStar (map_over_state l limit1 limit2 s1) (map_over_state l limit1 limit2 s2))\n    | AbsOrStar s1 s2 => (AbsOrStar (map_over_state l limit1 limit2 s1) (map_over_state l limit1 limit2 s2))\n    | AbsExists e s => AbsExists (map_over_exp l limit1 limit2 e) (map_over_state (push_pairs l) (S limit1) (S limit2) s)\n    | AbsExistsT s => AbsExistsT (map_over_state (push_pairs l) (S limit1) (S limit2) s)\n    | AbsAll e s => AbsAll (map_over_exp l limit1 limit2 e) (map_over_state (push_pairs l) (S limit1) (S limit2) s)\n    | AbsEach e s => AbsEach (map_over_exp l limit1 limit2 e) (map_over_state (push_pairs l) (S limit1) (S limit2) s)\n    | AbsEmpty => AbsEmpty\n    | AbsNone => AbsNone\n    | AbsAny => AbsAny\n    | AbsLeaf i ll => AbsLeaf i (map (map_over_exp l limit1 limit2) ll)\n    | AbsAccumulate i e1 e2 e3 => AbsAccumulate i (map_over_exp l limit1 limit2 e1) (map_over_exp (push_pairs l) (S limit1) (S limit2) e2) (map_over_exp l limit1 limit2 e3)\n    | AbsMagicWand s1 s2 => AbsMagicWand (map_over_state l limit1 limit2 s1) (map_over_state l limit1 limit2 s2)\n    | AbsUpdateVar s i e => AbsUpdateVar (map_over_state l limit1 limit2 s) i (map_over_exp l limit1 limit2 e)\n    | AbsUpdateWithLoc s i e => AbsUpdateWithLoc (map_over_state l limit1 limit2 s) i (map_over_exp l limit1 limit2 e)\n    | AbsUpdateLoc s i e => AbsUpdateLoc (map_over_state l limit1 limit2 s) (map_over_exp l limit1 limit2 i) (map_over_exp l limit1 limit2 e)\n    | AbsUpdState s1 s2 s3 => AbsUpdState (map_over_state l limit1 limit2 s1) (map_over_state l limit1 limit2 s2) (map_over_state l limit1 limit2 s3)\n    | AbsClosure s ll => AbsClosure s (map (map_over_exp l limit1 limit2) ll)\n   end.\n\nFixpoint mem1 (x : nat) (m : list (nat * nat)) :=\n    match m with\n    | nil => false\n    | ((a,b)::r) => if beq_nat a x then true else mem1 x r\n    end.\n\nFixpoint mem2 (x : nat) (m : list (nat * nat)) :=\n    match m with\n    | nil => false\n    | ((a,b)::r) => if beq_nat b x then true else mem2 x r\n    end.\n\nFixpoint complete_mapping1 (x1 : nat) (l1 : nat) (l2 : nat) (s2 : absState) (m : list (nat * nat)) :=\n    match x1 with\n    | 0 => (m,l1,l2,s2)\n    | S x1' => if mem1 x1' m then complete_mapping1 x1' l1 l2 s2 m\n               else complete_mapping1 x1' l1 (l2+1) (addStateVar l2 s2) ((x1',l2)::m)\n    end.\n\nFixpoint complete_mapping2 (x2 : nat) (l1 : nat) (l2 : nat) (s1 : absState) (m : list (nat * nat)) :=\n    match x2 with\n    | 0 => (m,l1,l2,s1)\n    | S x2' => if mem2 x2' m then complete_mapping2 x2' l1 l2 s1 m\n               else complete_mapping2 x2' (l1+1) l2 (addStateVar l1 s1) ((l1,x2')::m)\n    end.\n\nFixpoint complete_mapping (l1 : nat) (l2 : nat) (m : list (nat * nat))\n                          (s1 : absState) (s2 : absState) :=\n    match complete_mapping1 l1 l1 l2 s2 m with\n    | (m',l1',l2',s2') => match complete_mapping2 l2' l1' l2' s1 m' with\n                          | (m'',l1'',l2'',s1'') => (m'',l1'',l2'',s1'',s2')\n                          end\n    end.\n\nFixpoint prove_state_implication (tl : nat) (s1: absState) (s2 : absState) (e : env) (h : heap) : Prop :=\n    match tl return Prop with\n    | 0 => realizeState s1 nil (e,h) -> realizeState s2 nil (e,empty_heap)\n    | S n => exists x, prove_state_implication n (instantiateState s1 x) (instantiateState s2 x) e h\n    end.\n\nFixpoint incrementLeft (pairs : list (nat * nat)) :=\n    match pairs with\n    | ((a,b)::c) => ((S a),b)::(incrementLeft c)\n    | nil => nil\n    end.\n\nFixpoint incrementRight (pairs : list (nat * nat)) :=\n    match pairs with\n    | ((a,b)::c) => (a,(S b))::(incrementLeft c)\n    | nil => nil\n    end.\n\n(*\n * This top level definition is responsible for proving implications.  It works by first pairing off\n * identical components and then setting up a proof goal for the remainder.\n *)\nInductive prove_implication : list (nat * nat) -> absState -> nat -> absState -> nat -> list (nat * nat) -> absState -> Prop :=\n    | CILPairR : forall s1 s2 s1' s2' l1 l2 vars vars' vars'' limit1 limit2 tl,\n               Some (s1',s2',l1,l2,vars') = pick2RsNiF s1 s2 vars limit1 limit2 (@nil (list absExp)) (@nil (list absExp)) ->\n               (*pick2RsNi s1 s2 vars limit1 limit2 (@nil (list absExp)) (@nil (list absExp )) l1 l2 s1' s2' vars' ->*)\n               prove_implication vars' s1' limit1 s2' limit2 vars'' tl ->\n               prove_implication vars s1 limit1 s2 limit2 vars'' tl\n    | CILPairUpdateWithLoc : forall s1 s2 s1' s2' i1 i2 s1'' s2'' l1 l2 vars vars' vars'' limit1 limit2 tl tl' vars''',\n               Some (s1',s2',(AbsUpdateWithLoc s1'' i1 l1),(AbsUpdateWithLoc s2'' i2 l2),vars') = pick2UpdateWithLocsNiF s1 s2 vars limit1 limit2 (@nil (list absExp)) (@nil (list absExp)) ->\n               prove_implication vars' s1' limit1 s2' limit2 vars'' tl ->\n               prove_implication vars'' s1'' limit1 s2'' limit2 vars''' tl' ->\n               prove_implication vars s1 limit1 s2 limit2 vars''' (tl ** (AbsUpdateWithLoc tl' i1 l1))\n    (*| CILPairCell : forall s1 s2 s1' s2' loc1 loc2 val1 val2 vars vars' vars'' limit1 limit2 tl,\n               pick2Cells s1 s2 vars limit1 limit2 nil nil loc1 loc2 val1 val2 s1' s2' vars' ->\n               prove_implication vars' s1' limit1 s2' limit2 vars'' tl ->\n               prove_implication vars s1 limit1 s2 limit2 vars'' tl*)\n    | CILFinish : forall vars limit1 limit2 s1 s2,\n                  prove_implication vars s1 limit1 s2 limit2 vars s1.\n\nLtac prove_implication := (eapply CILPairR;[solve [compute;reflexivity] | prove_implication]) ||\n                          (eapply CILPairUpdateWithLoc;[solve [compute;reflexivity] | prove_implication | prove_implication]) ||\n                          (eapply CILFinish;simpl;reflexivity).\n\nFunction  stripUpdateWithLocs (s : absState) :=\n    match s with\n    | AbsUpdateWithLoc ss i v => match substVarState (addStateVar 0 (stripUpdateWithLocs ss)) i v(0) with\n                                 | Some x => (AbsExistsT x)\n                                 | _ => AbsUpdateWithLoc ss i v\n                                 end\n    | (a ** b) => ((stripUpdateWithLocs a) ** (stripUpdateWithLocs b))\n    | AbsUpdateVar ss i v => AbsUpdateVar (stripUpdateWithLocs ss) i v\n    | x => x\n    end.\n\n(*\n * The top level state implication theorem.  One state implies another if we\n * can first pair off many of the identical components and then prove that\n * the first state implies the remaining components.\n *)\nTheorem stateImplication : forall s state1 (state2 : absState) state1' tl1 tl2 state2' state2'' vars mx l1x l2x state1x state2x state2x' bb,\n    realizeState state1 bb s ->\n    (state1',tl1) = remove_top_existentials state1 ->\n    (state2',tl2) = remove_top_existentials state2 ->\n    prove_implication nil state2' tl2 state1' tl1 vars state2'' ->\n    (mx,l2x,l1x,state2x,state1x) = complete_mapping tl2 tl1 vars state2'' state1' ->\n    state2x' = map_over_state mx l1x l2x state2x ->\n    (forall e h b, length b=l1x-> (realizeState state1x (bb++b) (e,h)) -> (exists bbb, realizeState (stripUpdateWithLocs state2x') (bb++bbb) (e,empty_heap))) ->\n    realizeState state2 bb s.\nProof. admit. Admitted.\n\nDefinition basicStateImplication := stateImplication.\n\n(*\n * The tactics below are all useful in applying the stateImplication\n * theorem above and performing other useful tasks in proving an\n * implication\n *)\nLtac stateImplication :=\n    eapply stateImplication;[\n        crunch |\n        (simpl; reflexivity) |\n        (simpl; reflexivity) |\n        prove_implication |\n        (simpl; reflexivity) |\n        (simpl; reflexivity) |\n        idtac].\nLtac basicStateImplication :=\n    eapply stateImplication;[\n        crunch |\n        (simpl; reflexivity) |\n        (simpl; reflexivity) |\n        prove_implication |\n        (simpl; reflexivity) |\n        (simpl; reflexivity) |\n        idtac].\n\nLtac reduceHyp :=\n    match goal with\n    | [ H: 1 = 0 |- _ ] => inversion H\n    | [ H: 0 = 1 |- _ ] => inversion H\n    | [ H: true = false |- _ ] => inversion H\n    | [ H: false = true |- _ ] => inversion H\n    | [ H: None = Some _ |- _ ] => inversion H\n    | [ H: Some _ = None |- _ ] => inversion H\n    | [ H: 0 <> 0 |- _ ] => omega\n    | [ H: 1 <> 1 |- _ ] => omega\n    | [H: context [if beq_nat ?X ?Y then _ else _] |- _] => let x:= fresh in remember (beq_nat X Y) as x; destruct x; compute in H\n    | [ H: true = beq_nat _ _ |- _ ] => apply beq_nat_eq in H;subst\n    (*| [H: absEval (AbsVar _) _ _ |- _] => inversion H;subst;clear H\n    | [H: absEval (AbsNatVal _) _ _ |- _] => inversion H;subst;clear H\n    | [H: absEval (AbsHeapVal _) _ _ |- _] => inversion H;subst;clear H\n    | [H: context [beq_nat 1 1] |- _ ] => compute in H\n    | [H: context [beq_nat 1 0] |- _ ] => compute in H\n    | [H: context [beq_nat 0 1] |- _ ] => compute in H\n    | [H: context [beq_nat 0 0] |- _ ] => compute in H*)\n    | [H: 1 = 1 |- _] => inversion H; subst; clear H\n    | [H: 1 = 0 |- _] => inversion H; subst; clear H\n    | [H: 0 = 1 |- _] => inversion H; subst; clear H\n    | [H: 0 = 0 |- _] => inversion H; subst; clear H\n    | [H: NatValue _ = NatValue _ |- _] => inversion H; subst; clear H\n    (*| [H: HeapValue _ = HeapValue _ |- _] => inversion H; subst; clear H*)\n    | [H: OtherValue _ = OtherValue _ |- _] => inversion H; subst; clear H\n    | [H: NoValue = NoValue |- _] => inversion H; subst; clear H\n    | [H: realizeState _ _ _ |- _] => inversion H; subst; clear H\n    | [H: basicState _ _ _ |- _] => inversion H; subst; clear H\n    (*| [H: absEval (AbsQVar _) _ _ |- _] => inversion H; subst; clear H\n    | [H: absEval (AbsHeapRef _ _) _ _ |- _] => inversion H; subst; clear H\n    | [H: absEval (AbsPlus _ _) _ _ |- _] => inversion H; subst; clear H\n    | [H: absEval (AbsMinus _ _) _ _ |- _] => inversion H; subst; clear H\n    | [H: absEval (AbsTimes _ _) _ _ |- _] => inversion H; subst; clear H\n    | [H: absEval (AbsImply _ _) _ _ |- _] => inversion H; subst; clear H\n    | [H: absEval (AbsNot _) _ _ |- _] => inversion H; subst; clear H\n    | [H: absEval (AbsAnd _ _) _ _ |- _] => inversion H; subst; clear H\n    | [H: absEval (AbsOr _ _) _ _ |- _] => inversion H; subst; clear H\n    | [H: absEval (AbsIte _ _ _) _ _ |- _] => inversion H; subst; clear H\n    | [H: absEval (AbsEqual _ _) _ (NatValue 0) |- _] => inversion H; subst; clear H\n    | [H: absEval (AbsEqual _ _) _ (NatValue 1) |- _] => inversion H; subst; clear H\n    | [H: absEval (AbsLess _ _) _ (NatValue 0) |- _] => inversion H; subst; clear H\n    | [H: absEval (AbsLess _ _) _ (NatValue 1) |- _] => inversion H; subst; clear H\n    | [H: absEval (AbsRMember _ _ _ _ _) _ (NatValue 0) |- _] => inversion H; subst; clear H\n    | [H: absEval (AbsRInclude _ _ _ _ _) _ (NatValue 0) |- _] => inversion H; subst; clear H\n    | [H: absEval (AbsRMember _ _ _ _ _) _ (NatValue 1) |- _] => inversion H; subst; clear H\n    | [H: absEval (AbsRInclude _ _ _ _ _) _ (NatValue 1) |- _] => inversion H; subst; clear H\n    | [H: absEval (AbsEqual _ _) _ (NatValue 1) |- _] => inversion H; subst; clear H*)\n    | [H: context [instantiateState _ _] |- _ ] => compute in H\n    | [H: exists _, _ |- _] => inversion H; subst; clear H\n    | [H: context [(match env_p ?Y ?Z with | Some _ => _ | None => _ end)] |- _] => let xx:=fresh in remember (env_p Y Z) as xx; destruct xx; compute in H\n    (*| [H: context [btnat _] |- _] => unfold btnat in H*)\n    | [H: context [basicEval _ _] |- _] => unfold basicEval in H\n    (*| [H: context [AbsEqualId] |- _] => unfold AbsEqualId in H*)\n    (*| [H: context [absCanEvalList _ _] |- _] => compute in H*)\n    | [H: Some _ = Some _ |- _] => inversion H; subst; clear H\n    end.\n\nLtac propagate :=\n           match goal with\n           | [H: fst ?s _ = Some _, C:concreteCompose ?s _ _ |- _] => erewrite composeEnvPropagate1 in H;[idtac|apply C]\n           | [H: fst ?s _ = Some _, C:concreteCompose _ ?s _ |- _] => erewrite composeEnvPropagate2 in H;[idtac|apply C]\n           | [H: Some _ = fst ?s _, C:concreteCompose ?s _ _ |- _] => erewrite composeEnvPropagate1 in H;[idtac|apply C]\n           | [H: Some _ = fst ?s _, C:concreteCompose _ ?s _ |- _] => erewrite composeEnvPropagate2 in H;[idtac|apply C]\n           end.\n\nLtac reduceHypothesis := repeat reduceHyp.\n\nLtac simplHyp := repeat match goal with\n                 | [H: _ = fst (_,_) _ |- _] => simpl in H\n                 | [H: fst (_,_) _ = _ |- _] => simpl in H\n                 | [H1: ?x ?y = Some _, H2: ?x ?y = Some _ |- _] => rewrite H1 in H2\n                 | [H1: Some _ = ?x ?y, H2: Some _ = ?x ?y |- _] => rewrite <- H1 in H2\n                 | [H: Some _ = Some _ |- _] => inversion H; subst; clear H\n                 end.\n\nLtac tryEmptyCompose := apply emptyConcreteCompose || idtac.\n\nLtac simplifyEval :=\n     match goal with\n     | [H: Some _ = ?e ?v |- context [?e ?v]] => rewrite <- H;simpl;try simplifyEval\n     | [H: ?e ?v = Some _ |- context [?e ?v]] => rewrite H;simpl;try simplifyEval\n     | [ |- context [env_p _ _]] => unfold env_p;simpl;try simplifyEval\n     | [ |- context [env_p _]] => unfold env_p;simpl;try simplifyEval\n     (*| [ |- context [btnat _]] => unfold btnat*)\n     | [ |- _ = _] => reflexivity\n     (*| [ |- context [AbsEqualId] ] => unfold AbsEqualId; simpl; try simplifyEval\n     | [ |- context [AbsEqualId] ] => unfold AbsOrId; simpl; try simplifyEval\n     | [ |- context [AbsEqualId] ] => unfold AbsRMemberId; simpl; try simplifyEval*)\n     | [ |- context [basicEval (Id _) _] ] => unfold basicEval; simpl; try simplifyEval\n     end.\n\nLtac decomposeR :=\n    match goal with\n    | [ |- Tree 0 _ _ _ empty_heap ] => eapply TreeBase;[omega | unfold empty_heap; reflexivity ]\n    end.\n\nLtac decomposeBasicState :=\n    match goal with\n    (*| [ |- context [Id 2] ] => try decomposeBasicState*)\n    | [ |- basicState (AbsTreeId) (NatValue _::_::NatValue _::_) _] => eapply BStateTree; [try decomposeR | simplifyStripNatValues]\n    | [ |- basicState (AbsPredicateId) _ _] => eapply BTStatePredicate;[ omega | intros; simpl; reflexivity ]\n    | [ |- _ ] => simpl; simplifyEval; try decomposeBasicState\n    end.\n\nLtac decomposeTheState :=\n    match goal with\n    | [ |- realizeState (AbsStar _ _) _ _] => eapply RSCompose;[try decomposeTheState | try decomposeTheState | tryEmptyCompose]\n    | [ |- realizeState AbsEmpty _ _] => (eapply RSEmpty;simpl;unfold empty_heap;reflexivity)\n    | [ |- realizeState (AbsLeaf _ _) _ _] => eapply RSR;[simpl;reflexivity | idtac]\n    | [ |- realizeState (AbsAll _ _) _ _] => eapply RSAll;[simpl;reflexivity | simpl;reflexivity | simpl | idtac]\n    (*| [ |- realizeStateList ((AbsExistsT _)::_) _] => eapply RSLExistsU;eapply ex_intro;simpl\n    | [ |- realizeStateList ((AbsExists _ _ _)::_) _] => eapply RSLExists;eapply ex_intro;simpl\n    | [ |- realizeStateList ((AbsEach _ _ _)::_) _] => eapply RSLEach;intros;simpl;decomposeTheState\n    | [ |- realizeStateList ((AbsAccumulate _ _ _ _ _ _)::_) _ ] => eapply RSLAccumulate;[simpl;reflexivity|simpl;reflexivity|idtac|simpl;reflexivity]\n    | [ |- absEval _ _ _] => decomposeEval\n    | [ H:?X <>?X |- _] => let H1 := fresh in assert (X = X) as H1; reflexivity; apply H in H; inversion H*)\n    end.\n(*\n * The following definition is used to simplify the reduction of realizeState\n *)\nFixpoint destructState (a : absState) (bindings : list (@Value unit)) (s : state) : Prop :=\n    match a with\n    | AbsStar as1 as2 => exists h1 h2,\n                         (destructState as1 bindings (fst s,h1) /\\\n                          destructState as2 bindings (fst s,h2) /\\\n                          (forall v, h1 v=None \\/ h2 v=None) /\\\n                          compose_heaps h1 h2=(snd s))\n    | AbsOrStar as1 as2 => (destructState as1 bindings s) \\/ (destructState as2 bindings s)\n    | AbsExists e a => forall  e rl,\n                       absEval (env_p s) bindings e = (ListValue rl) ->\n                       (exists x, In x rl /\\\n                           destructState a (bindings++(x::nil)) s)\n    | AbsExistsT a => (exists x, destructState a (bindings++(x::nil)) s)\n    | AbsAccumulate i e1 e2 e3 => forall v3 vl,\n                    absEval (env_p s) bindings e1 = (ListValue vl) ->\n                    absEval (env_p s) bindings e3 = v3 ->\n                    basicAccumulate i (env_p s) bindings vl e2 v3\n    | AbsAll e a => forall rl,\n                    absEval (env_p s) bindings e = ListValue rl ->\n                    (forall x, In x rl ->\n                               destructState a (bindings++(x::nil)) s)\n    | AbsEach e a => forall v rl states l,\n                     absEval (env_p s) bindings e = v ->\n                     v = ListValue rl ->\n                     allFirsts rl l ->\n                     allSeconds states l ->\n                     (forall x y, In (x,y) l -> destructState a (bindings++(x::nil)) y) ->\n                     fold_compose states s\n    | AbsEmpty => (forall x, snd s x=None)\n    | AbsAny => True\n    | AbsNone => False\n    | AbsLeaf i el => basicState i (map (absEval (env_p s) bindings) el) (snd s)\n    | AbsMagicWand as1 as2 => exists h1 h2,\n                            (destructState as1 bindings (fst s,h1) /\\\n                             destructState as2 bindings (fst s,h2) /\\\n                             (forall v, ~(h1 v=None) \\/ h2 v=None) /\\\n                             compose_heaps h2 (snd s)=h1)\n    | AbsUpdateVar ss i e => destructState ss bindings s\n    | AbsUpdateWithLoc ss i e => destructState ss bindings s\n    | AbsUpdateLoc ss i e => destructState ss bindings s\n    | AbsUpdState s1 s2 s3 => destructState s1 bindings s\n    | AbsClosure ss el => destructState ss (map (absEval (env_p s) bindings) el) (empty_env,heap_p s)\n    end.\n\nTheorem realizeDestructThm : forall s b st,\n    @realizeState s b st -> destructState s b st.\nProof. admit. Admitted.\n\nLtac removeExistentials :=\n    repeat (match goal with\n     | [ H:realizeState (AbsExistsT _) _ _ |- _ ] => (inversion H; subst; clear H)\n     | [ H: exists _, _ |- _ ] => (inversion H;subst;clear H)\n     end).\n\nTheorem pickAssertion : forall fs s e P P' bind bind2 x,\n    realizeState P bind s ->\n    spickElement P ([e]) P' ->\n    fst s = fs ->\n    x<>0 ->\n    noQVarExp e=true ->\n    absEval fs bind2 e = NatValue x.\nProof. admit. Admitted.\n\nTheorem pickTerm : forall P bind s fs e P',\n    realizeState P bind s ->\n    spickElement P e P' ->\n    allPredicates e ->\n    fst s = fs ->\n    realizeState e bind (fs,empty_heap).\nProof. admit. Admitted.\n\nLtac solvePickTerm X := eapply pickTerm;[apply X | solveSPickElement | solveAllPredicates | simpl; reflexivity].\n\nTheorem pickData : forall P bind s fs e P',\n    realizeState P bind s ->\n    spickElement P e P' ->\n    fst s = fs ->\n    (exists h, realizeState e bind (fs,h)).\nProof. admit. Admitted.\n\nLtac solvePickData X := eapply pickData;[apply X | solveSPickElement | simpl; reflexivity].\n\nTheorem concreteComposeEmpty : forall s1 s2 eee,\n    concreteCompose s1 s2 (eee, empty_heap) <-> s1=(eee, empty_heap) /\\ s2=(eee, empty_heap).\nProof. admit. Admitted.\n\nTheorem nth_replace_same {t} : forall l m n (vv:t) x, m=n -> n < length l -> nth m (replacenth l n vv) x=vv.\n        Proof.\n            induction l.\n            intros. inversion H0.\n            destruct n. intros. rewrite H. simpl. reflexivity.\n            intros. rewrite H. simpl. rewrite IHl. reflexivity. reflexivity. simpl in H0. inversion H0.\n            omega. omega.\n        Qed.\n\nTheorem nth_replace_diff {t} : forall l m n (vv:t) x, m<>n -> nth m (replacenth l n vv) x=nth m l x.\n        Proof.\n            induction l.\n            intros. simpl. reflexivity.\n            intros. simpl. destruct n. destruct m. elim H. reflexivity. simpl. reflexivity.\n            destruct m. simpl. reflexivity. simpl. rewrite IHl. reflexivity. omega.\n        Qed.\n\nDefinition validPredicate {ev} (p : @Value ev) :=\n    match p with\n    | NatValue 0 => false\n    | NatValue _ => true\n    | _ => false\n    end.\n\nFixpoint replaceExp (e : absExp ) (val: absExp) (rep:absExp) : absExp :=\n   if beq_absExp e val then rep\n   else\n   match e with\n   | AbsConstVal x => AbsConstVal x\n   | AbsVar v => AbsVar v\n   | AbsQVar v => AbsQVar v\n   | AbsFun i l => AbsFun i (map (fun x => replaceExp x val rep) l)\n   end.\n\nFixpoint replaceState (s : absState) (val: absExp) (rep: absExp) : absState :=\n   match s with\n    | AbsStar s1 s2 => (AbsStar (replaceState s1 val rep) (replaceState s2 val rep))\n    | AbsOrStar s1 s2 => (AbsOrStar (replaceState s1 val rep) (replaceState s2 val rep))\n    | AbsExistsT s => AbsExistsT (replaceState s val rep)\n    | AbsExists e s => AbsExists (replaceExp e val rep) (replaceState s val rep)\n    | AbsAll e s => AbsAll (replaceExp e val rep) (replaceState s val rep)\n    | AbsEach e s => AbsEach (replaceExp e val rep) (replaceState s val rep)\n    | AbsEmpty => AbsEmpty\n    | AbsNone => AbsNone\n    | AbsAny => AbsAny\n    | AbsLeaf i l => AbsLeaf i (map (fun x => replaceExp x val rep) l)\n    | AbsAccumulate id e1 e2 e3 => AbsAccumulate id (replaceExp e1 val rep) (replaceExp e2 val rep) (replaceExp e3 val rep)\n    | AbsMagicWand s1 s2 => AbsMagicWand (replaceState s1 val rep) (replaceState s2 val rep)\n    | AbsUpdateVar s i v => AbsUpdateVar (replaceState s val rep) i (replaceExp v val rep)\n    | AbsUpdateWithLoc s i v => AbsUpdateWithLoc (replaceState s val rep) i (replaceExp v val rep)\n    | AbsUpdateLoc s i v => AbsUpdateLoc (replaceState s val rep) (replaceExp i val rep) (replaceExp v val rep)\n     | AbsUpdState s1 s2 s3 => AbsUpdState (replaceState s1 val rep) (replaceState s2 val rep) (replaceState s3 val rep)\n    | AbsClosure s l => AbsClosure s (map (fun x => replaceExp x val rep) l)\n   end.\n\nFixpoint pair_check {a} (f : a -> a -> bool) (l1 : list a) (l2 : list a) :=\n    match l1,l2 with\n    | nil,nil => true\n    | (a::b),(c::d) => if f a c then pair_check f b d else false\n    | _,_ => false\n    end.\n\nFixpoint equivExp (e1 : absExp) (e2 : absExp) (val:absExp) (rep:absExp) : bool :=\n   if beq_absExp e1 e2 then true\n   else if beq_absExp e1 val && beq_absExp e2 rep then true\n   else if beq_absExp e1 rep && beq_absExp e2 val then true\n   else\n   match e1,e2 with\n   | AbsFun i1 l1,AbsFun i2 l2 => if beq_id i1 i2 then\n                                      (fix go ll1 ll2 := match ll1,ll2 with\n                                                        | nil, nil => true\n                                                        | (ff1::rr1), (ff2::rr2) =>\n                                                          if equivExp ff1 ff2 val rep then go rr1 rr2 else false\n                                                        | _, _ => false\n                                                        end) l1 l2\n                                  else false\n   | _,_ => false\n   end.\n\nFixpoint equivState (s1 : absState) (s2 : absState) (val: absExp) (rep: absExp) : bool :=\n   match s1,s2 with\n    | AbsStar s1a s1b,AbsStar s2a s2b => (equivState s1a s2a val rep) && (equivState s1b s2b val rep)\n    | AbsOrStar s1a s1b,AbsOrStar s2a s2b => (equivState s1a s2a val rep) && (equivState s1b s2b val rep)\n    | AbsExistsT s1, AbsExistsT s2 => (equivState s1 s2 val rep)\n    | AbsExists e1 s1, AbsExists e2 s2 => (equivExp e1 e2 val rep) && (equivState s1 s2 val rep)\n    | AbsAll e1 s1, AbsAll e2 s2 => (equivExp e1 e2 val rep) && (equivState s1 s2 val rep)\n    | AbsEach e1 s1, AbsEach e2 s2 => (equivExp e1 e2 val rep) && (equivState s1 s2 val rep)\n    | AbsEmpty, AbsEmpty => true\n    | AbsLeaf i1 l1, AbsLeaf i2 l2 =>\n                                  if beq_id i1 i2 then\n                                      (fix go ll1 ll2 := match ll1,ll2 with\n                                                        | nil, nil => true\n                                                        | (ff1::rr1), (ff2::rr2) =>\n                                                          if equivExp ff1 ff2 val rep then go rr1 rr2 else false\n                                                        | _, _ => false\n                                                        end) l1 l2\n                                  else false\n    | AbsAccumulate i1 e1a e1b e1c, AbsAccumulate i2 e2a e2b e2c =>\n             (equivExp e1a e2a val rep) && (equivExp e1b e2b val rep) && (equivExp e1c e2c val rep)\n    | _, _ => false\n   end.\n\nFixpoint maxBindingExp (e : absExp ) : nat :=\n   match e with\n   | AbsConstVal x => 0\n   | AbsVar v => 0\n   | AbsQVar v => S v\n   | AbsFun i l => fold_left (fun x y => if ble_nat x y then y else x) (map maxBindingExp l) 0\n   end.\n\nFixpoint clipBinding {ev} (b : list (@Value ev)) (n : nat) :=\n    match b,n with\n    | (f::r),(S n') => f::(clipBinding r n')\n    | _,_ => nil\n    end.\n\nTheorem expressionSubLR : forall b b' b'' p st e h exp1 exp2 p',\n    realizeState ([p]) b st ->\n    validPredicate (absEval e b'' (exp1====exp2))=true ->\n    b' = clipBinding b (maxBindingExp (exp1====exp2)) ->\n    b' = clipBinding b'' (maxBindingExp (exp1====exp2)) ->\n    st = (e,h) ->\n    p' = replaceExp p exp1 exp2 ->\n    realizeState ([p']) b st.\nProof. admit. Admitted.\n\nTheorem expressionNotEqualZero1 : forall b b' b'' p st e h exp p',\n    realizeState (p) b st ->\n    false=validPredicate (absEval e b'' (#0====exp)) ->\n    b' = clipBinding b (maxBindingExp (exp)) ->\n    b' = clipBinding b'' (maxBindingExp (exp)) ->\n    st = (e,h) ->\n    p' = replaceState p ((#0) <<<< exp) (#1) ->\n    realizeState (p') b st.\nProof. admit. Admitted.\n\nTheorem expressionNotEqualZero2 : forall b b' b'' p st e h exp p',\n    realizeState (p) b st ->\n    false=validPredicate (absEval e b'' (#0====exp)) ->\n    b' = clipBinding b (maxBindingExp (exp)) ->\n    b' = clipBinding b'' (maxBindingExp (exp)) ->\n    st = (e,h) ->\n    p' = replaceState p ((#0) ==== exp) (#0) ->\n    realizeState (p') b st.\nProof. admit. Admitted.\n\nTheorem expressionNotEqualZero3 : forall b b' b'' p st e h exp p',\n    realizeState (p) b st ->\n    false=validPredicate (absEval e b'' (#0====exp)) ->\n    b' = clipBinding b (maxBindingExp (exp)) ->\n    b' = clipBinding b'' (maxBindingExp (exp)) ->\n    st = (e,h) ->\n    p' = replaceState p (exp ==== (#0)) (#0) ->\n    realizeState (p') b st.\nProof. admit. Admitted.\n\nTheorem expressionSubRL : forall b b' b'' p st e h exp1 exp2 p',\n    realizeState (p) b st ->\n    validPredicate (absEval e b'' (exp1====exp2))=true ->\n    b' = clipBinding b (maxBindingExp (exp1====exp2)) ->\n    b' = clipBinding b'' (maxBindingExp (exp1====exp2)) ->\n    st = (e,h) ->\n    p' = replaceState p exp2 exp1 ->\n    realizeState (p') b st.\nProof. admit. Admitted.\n\nTheorem expressionSubRSLR : forall b b' b'' p st exp1 exp2 p',\n    realizeState ([exp1====exp2]) b'' st ->\n    realizeState (p) b st ->\n    b' = clipBinding b (maxBindingExp (exp1====exp2)) ->\n    b' = clipBinding b'' (maxBindingExp (exp1====exp2)) ->\n    p' = replaceState p exp1 exp2 ->\n    realizeState (p') b st.\nProof. admit. Admitted.\n\nTheorem expressionSubRSNeg : forall b b' b'' p st exp1 p',\n    realizeState ([~~exp1]) b'' st ->\n    realizeState (p) b st ->\n    b' = clipBinding b (maxBindingExp (exp1)) ->\n    b' = clipBinding b'' (maxBindingExp (exp1)) ->\n    p' = replaceState p exp1 (#0) ->\n    realizeState (p') b st.\nProof. admit. Admitted.\n\nTheorem expressionSubRSRL : forall b b' b'' p st exp1 exp2 p',\n    realizeState ([exp1====exp2]) b'' st ->\n    realizeState (p) b st ->\n    b' = clipBinding b (maxBindingExp (exp1====exp2)) ->\n    b' = clipBinding b'' (maxBindingExp (exp1====exp2)) ->\n    p' = replaceState p exp2 exp1 ->\n    realizeState (p') b st.\nProof. admit. Admitted.\n\nTheorem expressionSubEval : forall b b' b'' p st exp val p' e,\n    @NatValue unit val = absEval e b' exp ->\n    realizeState (p) b'' st ->\n    e = (fst st) ->\n    p' = replaceState p  exp (#val) ->\n    b = clipBinding b' (maxBindingExp exp) ->\n    b = clipBinding b'' (maxBindingExp exp) ->\n    realizeState (p') b'' st.\nProof. admit. Admitted.\n\nTheorem expressionSubEvalEval : forall b p st exp1 exp2 p' e,\n    absEval e b exp2 = absEval e b exp1 ->\n    realizeState (p) b st ->\n    e = (fst st) ->\n    p' = replaceState p  exp1 exp2 ->\n    realizeState (p') b st.\nProof. admit. Admitted.\n\nTheorem expressionSubGRSLR : forall b b' b'' p st exp1 exp2 p',\n    realizeState ([exp1====exp2]) b'' st ->\n    b' = clipBinding b (maxBindingExp (exp1====exp2)) ->\n    b' = clipBinding b'' (maxBindingExp (exp1====exp2)) ->\n    p' = replaceExp p exp1 exp2 ->\n    realizeState ([p']) b st ->\n    realizeState ([p]) b st.\nProof. admit. Admitted.\n\nTheorem expressionSubGRSRL : forall b b' b'' p st exp1 exp2 p',\n    realizeState ([exp1====exp2]) b'' st ->\n    b' = clipBinding b (maxBindingExp (exp1====exp2)) ->\n    b' = clipBinding b'' (maxBindingExp (exp1====exp2)) ->\n    p' = replaceExp p exp2 exp1 ->\n    realizeState ([p']) b st ->\n    realizeState ([p]) b st.\nProof. admit. Admitted.\n\nTheorem expressionSubGLR : forall b b' e b'' p st exp1 exp2 p',\n    validPredicate (absEval e b'' (exp1====exp2))=true ->\n    e = (fst st) ->\n    b' = clipBinding b (maxBindingExp (exp1====exp2)) ->\n    b' = clipBinding b'' (maxBindingExp (exp1====exp2)) ->\n    p' = replaceExp p exp1 exp2 ->\n    realizeState ([p']) b st ->\n    realizeState ([p]) b st.\nProof. admit. Admitted.\n\nTheorem expressionSubGRL : forall b b' b'' p st exp1 exp2 p' e,\n    validPredicate (absEval e b'' (exp1====exp2))=true ->\n    e = (fst st) ->\n    b' = clipBinding b (maxBindingExp (exp1====exp2)) ->\n    b' = clipBinding b'' (maxBindingExp (exp1====exp2)) ->\n    p' = replaceState p exp2 exp1 ->\n    realizeState (p') b st ->\n    realizeState (p) b st.\nProof. admit. Admitted.\n\nTheorem expressionSubGRSNeg : forall b b' b'' p st exp p' e,\n    realizeState ([exp]) b'' st ->\n    b' = clipBinding b (maxBindingExp (exp)) ->\n    b' = clipBinding b'' (maxBindingExp (exp)) ->\n    p' = replaceExp p (~~exp) (#0) ->\n    e = (fst st) ->\n    absEval e b p=\n    absEval e b p'.\nProof. admit. Admitted.\n\nTheorem expressionSubGRSOr1 : forall b b' b'' p st exp p' e x y,\n    realizeState ([exp]) b'' st ->\n    b' = clipBinding b (maxBindingExp (exp)) ->\n    b' = clipBinding b'' (maxBindingExp (exp)) ->\n    p' = replaceState p ((exp\\\\//x)//\\\\y) (y) ->\n    e = (fst st) ->\n    realizeState (p') b st ->\n    realizeState (p) b st.\nProof. admit. Admitted.\n\nTheorem expressionSubGRSOr2 : forall b b' b'' p st exp p' e x y,\n    realizeState ([exp]) b'' st ->\n    b' = clipBinding b (maxBindingExp (exp)) ->\n    b' = clipBinding b'' (maxBindingExp (exp)) ->\n    p' = replaceState p ((x\\\\//exp)//\\\\y) (y) ->\n    e = (fst st) ->\n    realizeState (p') b st ->\n    realizeState (p) b st.\nProof. admit. Admitted.\n\nTheorem expressionSubGRSNeg1 : forall b b' b'' p st exp p' e,\n    realizeState ([exp]) b'' st ->\n    b' = clipBinding b (maxBindingExp (exp)) ->\n    b' = clipBinding b'' (maxBindingExp (exp)) ->\n    p' = replaceState p (~~exp) (#0) ->\n    e = (fst st) ->\n    realizeState (p') b st ->\n    realizeState (p) b st.\nProof. admit. Admitted.\n\nTheorem expressionSubRSVP : forall b b' b'' p st exp1 exp2 p' eee,\n    realizeState ([exp1====exp2]) b st ->\n    b' = clipBinding b (maxBindingExp (exp1====exp2)) ->\n    b' = clipBinding b'' (maxBindingExp (exp1====exp2)) ->\n    p' = replaceExp p exp1 exp2 ->\n    eee = fst st ->\n    validPredicate (absEval eee b'' p)=validPredicate (absEval eee b'' p').\nProof. admit. Admitted.\n\nTheorem removeQuantVar : forall n b e h var exp1 exp2,\n    realizeState exp2 b (e,h) ->\n    nth n b NoValue = NatValue (e var) ->\n    equivState exp1 exp2 (!!var) (v(n)) = true ->\n    realizeState exp1 b (e,h).\nProof. admit. Admitted.\n\nFixpoint removeReplaceExp (loc1 : absExp) (loc2 : absExp) (exp : absExp) :=\n    match exp with\n    | AbsFun (AbsNthId) (p::q::nil) =>\n                match p,q with\n                | (AbsFun (AbsReplaceNthId) (base::l1::val::nil)),l2 =>\n                    if (beq_absExp loc1 l1 && beq_absExp loc2 l2) ||\n                       (beq_absExp loc1 l2 && beq_absExp loc2 l1) then\n                        AbsFun (AbsNthId) (base::l2::nil)\n                    else\n                        AbsFun (AbsNthId) (p::q::nil)\n                | _,_ => AbsFun (AbsNthId) (p::q::nil)\n                end\n    | (AbsFun i l) => AbsFun i (map (removeReplaceExp loc1 loc2) l)\n    | x => x\n    end.\n\nFixpoint removeReplaceState (loc1 : absExp) (loc2 : absExp) (s:absState) : absState :=\n   match s with\n    | AbsStar s1 s2 => (AbsStar (removeReplaceState loc1 loc2 s1) (removeReplaceState loc1 loc2 s2))\n    | AbsOrStar s1 s2 => (AbsOrStar (removeReplaceState loc1 loc2 s1) (removeReplaceState loc1 loc2 s2))\n    | AbsExistsT s => AbsExistsT (removeReplaceState loc1 loc2 s)\n    | AbsExists e s => AbsExists (removeReplaceExp loc1 loc2 e) (removeReplaceState loc1 loc2 s)\n    | AbsAll e s => AbsAll (removeReplaceExp loc1 loc2 e) (removeReplaceState loc1 loc2 s)\n    | AbsEach e s => AbsEach (removeReplaceExp loc1 loc2 e) (removeReplaceState loc1 loc2 s)\n    | AbsEmpty => AbsEmpty\n    | AbsNone => AbsNone\n    | AbsAny => AbsAny\n    | AbsLeaf i l => AbsLeaf i (map (removeReplaceExp loc1 loc2) l)\n    | AbsAccumulate i e1 e2 e3 => AbsAccumulate i (removeReplaceExp loc1 loc2 e1) (removeReplaceExp loc1 loc2 e2) (removeReplaceExp loc1 loc2 e3)\n    | AbsMagicWand s1 s2 => AbsMagicWand (removeReplaceState loc1 loc2 s1) (removeReplaceState loc1 loc2 s2)\n    | AbsUpdateVar s i v => AbsUpdateVar (removeReplaceState loc1 loc2 s) i (removeReplaceExp loc1 loc2 v)\n    | AbsUpdateWithLoc s i v => AbsUpdateWithLoc (removeReplaceState loc1 loc2 s) i (removeReplaceExp loc1 loc2 v)\n    | AbsUpdateLoc s i v => AbsUpdateLoc (removeReplaceState loc1 loc2 s) (removeReplaceExp loc1 loc2 i) (removeReplaceExp loc1 loc2 v)\n    | AbsUpdState s1 s2 s3 => AbsUpdState (removeReplaceState loc1 loc2 s1) (removeReplaceState loc1 loc2 s2) (removeReplaceState loc1 loc2 s3)\n    | AbsClosure s l => AbsClosure s (map (removeReplaceExp loc1 loc2) l)\n   end.\n\nTheorem removeReplace : forall b b' b'' p st e h exp1 exp2 p',\n    realizeState (p) b st ->\n    validPredicate (absEval e b'' (exp1====exp2))=false ->\n    b' = clipBinding b (maxBindingExp (exp1====exp2)) ->\n    b' = clipBinding b'' (maxBindingExp (exp1====exp2)) ->\n    st = (e,h) ->\n    p' = removeReplaceState exp1 exp2 p ->\n    realizeState (p') b st.\nProof. admit. Admitted.\n\nFixpoint removeReplaceSameExp (l : absExp) (loc : absExp) (exp : absExp) :=\n    match exp with\n    | AbsFun (AbsNthId) (p::q::nil) =>\n                match p,q with\n                | (AbsFun (AbsReplaceNthId) (base::l1::val::nil)),l2 =>\n                    if beq_absExp base l && beq_absExp l1 l2 &&\n                       beq_absExp l1 loc then\n                        val\n                    else\n                        AbsFun (AbsNthId) (p::q::nil)\n                | _,_ => AbsFun (AbsNthId) (p::q::nil)\n                end\n    | (AbsFun i ll) => AbsFun i (map (removeReplaceSameExp l loc) ll)\n    | x => x\n    end.\n\nFixpoint removeReplaceSameState (loc1 : absExp) (loc2 : absExp) (s:absState) : absState :=\n   match s with\n    | AbsStar s1 s2 => (AbsStar (removeReplaceSameState loc1 loc2 s1) (removeReplaceSameState loc1 loc2 s2))\n    | AbsOrStar s1 s2 => (AbsOrStar (removeReplaceSameState loc1 loc2 s1) (removeReplaceSameState loc1 loc2 s2))\n    | AbsExistsT s => AbsExistsT (removeReplaceSameState loc1 loc2 s)\n    | AbsExists e s => AbsExists (removeReplaceSameExp loc1 loc2 e) (removeReplaceSameState loc1 loc2 s)\n    | AbsAll e s => AbsAll (removeReplaceSameExp loc1 loc2 e) (removeReplaceSameState loc1 loc2 s)\n    | AbsEach e s => AbsEach (removeReplaceSameExp loc1 loc2 e) (removeReplaceSameState loc1 loc2 s)\n    | AbsEmpty => AbsEmpty\n    | AbsNone => AbsNone\n    | AbsAny => AbsAny\n    | AbsLeaf i l => AbsLeaf i (map (removeReplaceSameExp loc1 loc2) l)\n    | AbsAccumulate i e1 e2 e3 => AbsAccumulate i (removeReplaceSameExp loc1 loc2 e1) (removeReplaceSameExp loc1 loc2 e2) (removeReplaceSameExp loc1 loc2 e3)\n    | AbsMagicWand s1 s2 => AbsMagicWand (removeReplaceSameState loc1 loc2 s1) (removeReplaceSameState loc1 loc2 s2)\n    | AbsUpdateVar s i v => AbsUpdateVar (removeReplaceSameState loc1 loc2 s) i (removeReplaceSameExp loc1 loc2 v)\n    | AbsUpdateWithLoc s i v => AbsUpdateWithLoc (removeReplaceSameState loc1 loc2 s) i (removeReplaceSameExp loc1 loc2 v)\n    | AbsUpdateLoc s i v => AbsUpdateLoc (removeReplaceSameState loc1 loc2 s) (removeReplaceSameExp loc1 loc2 i) (removeReplaceSameExp loc1 loc2 v)\n    | AbsUpdState s1 s2 s3 => AbsUpdState (removeReplaceSameState loc1 loc2 s1) (removeReplaceSameState loc1 loc2 s2) (removeReplaceSameState loc1 loc2 s3)\n    | AbsClosure s l => AbsClosure s (map (removeReplaceSameExp loc1 loc2) l)\n   end.\n\nTheorem removeReplaceSame : forall b p st l loc p' ll n,\n    realizeState ([p]) b st ->\n    p' = removeReplaceSameExp l loc p ->\n    ListValue ll = absEval (fst st) b l ->\n    NatValue n = absEval (fst st) b loc ->\n    n < length ll ->\n    realizeState ([p']) b st.\nProof. admit. Admitted.\n\nTheorem realizeValidPredicate : forall st e h exp b,\n    st = (e,h) ->\n    (validPredicate (absEval e b exp)=true <-> realizeState ([exp]) b st).\nProof. admit. Admitted.\n\nTheorem validPredicateSymmetry : forall b e exp1 exp2,\n    validPredicate (absEval e b (exp1====exp2))=\n    validPredicate (absEval e b (exp2====exp1)).\nProof. admit. Admitted.\n\nFunction mapSum (env : id -> nat) (b : list (@Value unit)) (values : list (@Value unit)) (e : absExp) : nat :=\n  match values with\n  | nil => 0\n  | (ff::rr) => match (absEval env (b++(ff::nil)) e) with\n                | NatValue x => (mapSum env b rr e)+x\n                | _ => mapSum env b rr e\n                end\n  end.\n\nFunction singlePred (s : absState) :=\n    match s with\n    | [x] => Some x\n    | (a ** b) => match singlePred a,singlePred b with\n                | Some a,Some b => Some (a //\\\\ b)\n                | _,_ => None\n                end\n    | (a *\\/* b) => match singlePred a,singlePred b with\n                  | Some a,Some b => Some (a \\\\// b)\n                  | _,_ => None\n                  end\n    | _ => None\n    end.\n\nTheorem andSum8 : forall v0 v1 v2 v3 v4 v5 v6 v7 vv v r e s state ee,\n    realizeState (SUM(r,e,v)) (v0::v1::v2::v3::v4::v5::v6::v7::nil) s ->\n    (forall x, In x vv ->\n               realizeState state (v0::v1::v2::v3::v4::v5::v6::v7::x::nil) s) ->\n    Some ee = singlePred state ->\n    (@ListValue unit vv) = absEval (fst s) (v0::v1::v2::v3::v4::v5::v6::v7::nil) r ->\n    realizeState (SUM(r,ee //\\\\ e,v)) (v0::v1::v2::v3::v4::v5::v6::v7::nil) s.\nProof. admit. Admitted.\n\nTheorem implySum8x10 : forall v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 vv v r e s state ee,\n    realizeState (SUM(r,e,v)) (v0::v1::v2::v3::v4::v5::v6::v7::v8::v9::nil) s ->\n    (forall x, In x vv ->\n               realizeState state (v0::v1::v2::v3::v4::v5::v6::v7::x::nil) s) ->\n    Some ee = (singlePred state) ->\n    (@ListValue unit vv) = absEval (fst s) (v0::v1::v2::v3::v4::v5::v6::v7::v8::v9::nil) r ->\n    realizeState (SUM(r,(~~(addExpVar 8 (addExpVar 8 ee))) \\\\// e,v)) (v0::v1::v2::v3::v4::v5::v6::v7::v8::v9::nil) s.\nProof. admit. Admitted.\n\nTheorem andSum8x10 : forall v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 vv v r e s state ee,\n    realizeState (SUM(r,e,v)) (v0::v1::v2::v3::v4::v5::v6::v7::v8::v9::nil) s ->\n    (forall x, In x vv ->\n               realizeState state (v0::v1::v2::v3::v4::v5::v6::v7::x::nil) s) ->\n    Some ee = (singlePred state) ->\n    (@ListValue unit vv) = absEval (fst s) (v0::v1::v2::v3::v4::v5::v6::v7::v8::v9::nil) r ->\n    realizeState (SUM(r,((addExpVar 8 (addExpVar 8 ee))) //\\\\ e,v)) (v0::v1::v2::v3::v4::v5::v6::v7::v8::v9::nil) s.\nProof. admit. Admitted.\n\nTheorem resolveSum8x10 : forall v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 vv v r e s state ee ff,\n    realizeState (SUM(r,e,v)) (v0::v1::v2::v3::v4::v5::v6::v7::v8::v9::nil) s ->\n    (forall x, In x vv ->\n               realizeState state (v0::v1::v2::v3::v4::v5::v6::v7::x::nil) s) ->\n    Some ee = (singlePred state) ->\n    (forall x s, In x vv ->\n                 realizeState ([((addExpVar 8 (addExpVar 8 ee)))]) (v0::v1::v2::v3::v4::v5::v6::v7::v8::v9::x::nil) (s,empty_heap) ->\n                 realizeState ([e====ff]) (v0::v1::v2::v3::v4::v5::v6::v7::v8::v9::x::nil) (s,empty_heap)) ->\n    (@ListValue unit vv) = absEval (fst s) (v0::v1::v2::v3::v4::v5::v6::v7::v8::v9::nil) r ->\n    realizeState (SUM(r,ff,v)) (v0::v1::v2::v3::v4::v5::v6::v7::v8::v9::nil) s.\nProof. admit. Admitted.\n\nTheorem resolveSum9x10 : forall v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 vv v r e s state ee ff,\n    realizeState (SUM(r,e,v)) (v0::v1::v2::v3::v4::v5::v6::v7::v8::v9::nil) s ->\n    (forall x, In x vv ->\n               realizeState state (v0::v1::v2::v3::v4::v5::v6::v7::v8::x::nil) s) ->\n    Some ee = (singlePred state) ->\n    (forall x s, In x vv ->\n                 realizeState ([(addExpVar 9 ee)]) (v0::v1::v2::v3::v4::v5::v6::v7::v8::v9::x::nil) (s,empty_heap) ->\n                 realizeState ([e====ff]) (v0::v1::v2::v3::v4::v5::v6::v7::v8::v9::x::nil) (s,empty_heap)) ->\n    (@ListValue unit vv) = absEval (fst s) (v0::v1::v2::v3::v4::v5::v6::v7::v8::v9::nil) r ->\n    realizeState (SUM(r,ff,v)) (v0::v1::v2::v3::v4::v5::v6::v7::v8::v9::nil) s.\nProof. admit. Admitted.\n\nTheorem sumDiff : forall s b r e s1 s2 sd x,\n    realizeState (SUM(r,(e //\\\\ x),(#s1))) b s ->\n    realizeState (SUM(r,e,(#s2))) b s ->\n    sd = s2-s1 ->\n    realizeState (SUM(r,(e //\\\\ (~~x)),(#sd))) b s.\nProof. admit. Admitted.\n\nTheorem sumAllConv : forall r e b s,\n    realizeState (SUM(r,e,#0)) b s ->\n    realizeState (AbsAll r ([~~e])) b s.\nProof. admit. Admitted.\n\nFunction deletenth {t} (x : nat) (l : list t) :=\n    match x,l with\n    | 0, (f::r) => Some r\n    | (S n),(f::r) => match deletenth n r with\n                      | Some l => Some (f::l)\n                      | _ => None\n                      end\n    | _,_ => None\n    end.\n\nTheorem dumpVar : forall state b s n b',\n    realizeState state b s ->\n    hasVnState state n=false ->\n    Some b' = deletenth n b ->\n    realizeState (removeStateVar n state) b' s.\nProof. admit. Admitted.\n\nTheorem dumpVar2 : forall state b s n b',\n    realizeState (removeStateVar n state) b' s ->\n    hasVnState state n=false ->\n    Some b' = deletenth n b ->\n    realizeState state b s.\nProof. admit. Admitted.\n\nTheorem mapSumExists : forall v e b vals exp,\n    S v = mapSum e b vals exp ->\n    exists x, In x vals /\\ realizeState ([exp]) (b++(x::nil)) (e,empty_heap).\nProof. admit. Admitted.\n\nTheorem mapSumNeg : forall e b vals exp,\n    0 = mapSum e b vals exp ->\n    forall x, In x vals -> realizeState ([~~exp]) (b++(x::nil)) (e,empty_heap).\nProof. admit. Admitted.\n\nTheorem subRangeSet {ev} : forall x rl rl0 n v,\n    rangeSet (ListValue (@findRecord ev n v)) = ListValue rl0 ->\n    In x rl0 ->\n    In (@NatValue ev n) rl ->\n    rangeSet v = ListValue rl ->\n    In x rl.\nProof. admit. Admitted.\n\nFunction replacenth {t} (x : nat) (e : t) (l : list t) :=\n    match x,l with\n    | 0, (f::r) => Some (e::r)\n    | (S n),(f::r) => match replacenth n e r with\n                      | Some l => Some (f::l)\n                      | _ => None\n                      end\n    | _,_ => None\n    end.\n\nTheorem subBoundVar : forall b eee exp b' p p' n,\n    nth n b' NoValue = absEval eee b exp ->\n    realizeState p b' (eee, empty_heap) ->\n    Some b = replacenth n (nth n b NoValue) b' ->\n    p' = replaceState p v(n) exp ->\n    realizeState p' b (eee,empty_heap).\nProof. admit. Admitted.\n\nTheorem arrayLength : forall v len n b st l,\n    realizeState (ARRAY(v,#len,v(n))) b st ->\n    nth n b NoValue = ListValue l ->\n    length l = len.\nProof. admit. Admitted.\n\nTheorem sumExists : forall b eee r e n,\n    realizeState (SUM(r,e,(#(S n)))) b (eee,empty_heap) ->\n    realizeState (AbsExists r ([e])) b (eee,empty_heap).\nProof. admit. Admitted.\n\nTheorem reverse: forall st x y b,\n    realizeState ([x====y]) b st ->\n    realizeState ([y====x]) b st.\nProof. admit. Admitted.\n\nTheorem entailmentUnusedUpdated : forall s b state v e,\n     realizeState (AbsUpdateVar state v e) b s ->\n     hasVarState state v=false ->\n     realizeState state b s.\nProof.\n    admit.\nAdmitted.\n\n\nFunction allEmpty (s : absState) :=\n    match s with\n    | AbsEmpty => true\n    | AbsStar a b => if allEmpty a then allEmpty b else false\n    | AbsOrStar a b => if allEmpty a then allEmpty b else false\n    | _ => false\n    end.\n    \nTheorem emptyRealizeState : forall s b e,\n    allEmpty(s)=true ->\n    @realizeState s b (e,empty_heap).\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", "meta": {"author": "kendroe", "repo": "CoqPIE", "sha": "946009445e532dd4632a11a58a64f72a1dd28304", "save_path": "github-repos/coq/kendroe-CoqPIE", "path": "github-repos/coq/kendroe-CoqPIE/CoqPIE-946009445e532dd4632a11a58a64f72a1dd28304/PEDANTIC/stateImplication.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.28874174890206106}}
{"text": "Require Import Common. \nRequire RTL Core. \nImport Core. \nSection t. \n  \n  Variable Phi : state. \n  Notation updates := (Tuple.of_list (option ∘ Core.eval_sync) Phi). \n  \n  Section defs. \n  Variable R : type -> Type. \n\n  (** Combinational bindings (expressions, register reads)  *)\n  (* Inductive bind (t : type) : Type :=  *)\n  (* | bind_expr :  expr R t ->  bind t *)\n  (* | bind_reg_read : var Phi (Treg t) -> bind t *)\n  (* | bind_regfile_read : forall n, var Phi (Tregfile n t) -> forall p, R (Tlift (W p)) -> bind t.  *)\n\n  (* Inductive telescope (A : Type): Type := *)\n  (* | telescope_end : A -> telescope A *)\n  (* | telescope_bind : forall arg, bind arg -> (R arg -> telescope A) -> telescope A.  *)\n  \n  \n  Inductive effect  : sync -> Type :=\n  | effect_reg_write : forall t,  R t -> R Bool -> effect (Treg t)\n  | effect_regfile_write : forall n t,  R t -> R (Tlift (Tfin n)) -> R Bool -> \n                                                effect (Tregfile n t). \n  \n  Definition effects := Tuple.of_list (effect) Phi. \n\n  Definition block t := RTL.telescope Phi R (R t * expr R Bool *  effects). \n  \n  (* Fixpoint compose {t B}  *)\n  (*                  (tA : block t) *)\n  (*                  (f : R t -> expr R Bool -> effects -> telescope B) : *)\n  (*   telescope B := *)\n  (*   match tA with *)\n  (*     | telescope_end ((r,g),e) => f r g e *)\n  (*     | telescope_bind arg b cont => telescope_bind _ arg b (fun x => compose (cont x) f)  *)\n  (*   end.  *)\n  \n  Notation \"x <- e1 ; e2\" := (telescope_bind _ _ e1 (fun x => e2)) (right associativity, at level 80, e1 at next level).  \n    \n  Notation \"[< r , g , e >] :- t1 ; t2 \" := (compose t1 (fun r g e => t2)) (right associativity, at level 80, e1 at next level). \n  Notation \" & e \" := (telescope_end _ e) (at level 71). \n  Arguments Tuple.set {T F l t} _ _ _.  \n  Definition compile {t} (B : RTL.block Phi R) : block t. \n  \n\n  Definition compile_effect t (E : RTL.effect Phi R) (B : block t) : block t. \n  refine (let compile := fix compile {t} (G : R Bool) E (U : block t) : block t :=  \n              match E with               \n                | RTL.effect_guard guard L => \n                    x <- bind_expr _ (!G && guard)%expr;                     \n                    List.fold_right\n                        (fun e acc => compile x e acc                                       \n                        ) U L\n                | RTL.effect_reg_write t var val => \n                    [< r, g, acc >] :- U; _\n                | RTL.effect_regfile_write n t var adr val => \n                    [< r, g, acc >] :- U; _ \n                                  end in _). \n  (* reg write *)\n  refine (let old := Tuple.get _ _ var acc in _). \n  inversion old. subst.\n  refine (we <- bind_expr _ (!X0 || !G)%expr ; \n          w <- bind_expr _ (Emux _ _ (!X0) (!X) (!val) )%expr ; \n          & (Tuple.set var (effect_reg_write _ w we) acc )\n         ).\n\n  (* regfile write *)\n  refine (let old := Tuple.get _ _ var acc in _). \n  inversion old. subst.   \n  refine \n    (\n      we <- bind_expr _ (!X1 || !G)%expr; \n      wadr <- bind_expr _ (Emux _ _ (!X1) (!X0) (!adr)); \n      wdata <- bind_expr _ (Emux _ _ (!X1) (!X) (!val)); \n      & (Tuple.set var (effect_regfile_write _ _ wdata wadr we) acc)\n    )%expr. \n\n  refine (true <- bind_expr _ (#b true); \n          compile true E B\n         )%expr. \n  Defined. \n    \n  let compile := fix compile B :=\n      match B with \n        | RTL.telescope_end E \n     \n                   \n  induction B. \n  refine (acc :- B; _). \n  \n\n\n  Arguments effect_guard guard%expr effects%list. \n  \n  (** * Compilation *)\n  (** This 'smart constructor' reduces the size of the guard, by using\n  the fact that [true] is a neutral element for [&&] *)\n  \n  Definition andb (a b : expr R Bool): expr R Bool :=\n    match a, b with \n      | Econstant Tbool x, o \n      | o, Econstant Tbool x => if x then o else (#b false)%expr\n      | _, _ => (a && b)%expr\n    end. \n  \n  (**  The compilation function itself *)\n  Variable varunit : R Unit. \n  \n  Definition convert  l : DList.T (expr R) l -> Tuple.of_list (expr R) l := DList.to_tuple (fun t X => X). \n\n  Fixpoint map T F F' (G : forall t, F t -> F' t) (l : list T) : Tuple.of_list F l -> Tuple.of_list F' l:=\n    match l with \n      | nil => fun x => x\n      | cons t q => fun x => (G t (fst x), map T F F' G q (snd x))\n    end. \n\n  Arguments map {T F F'} G l _. \n  (*  fst (DList.T_fold' eval_expr [t] exprs) =\n   eval_expr t\n     (fst\n        (DList.T_fold' (fun (t0 : type) (X : expr eval_type t0) => X) [t] exprs))\n\n*)\n  \n  Definition compile  t (a : action Phi R t) : telescope (R t * expr R Bool * list effect).  \n  refine (\n      let f := fix compile t (a : action Phi R t) : telescope (R t * expr R Bool * list effect):= \n          match a with \n            | Return t exp =>  \n                x <- (bind_expr _ exp); \n                & (x, #b true, nil)\n            | Bind t u A F => \n                [< rA, gA, eA >] :- compile _ A;\n                [< rB, gB, eB >] :- compile _ (F rA); \n                & (rB, andb gA gB, List.app eA eB)             \n            | Assert exp => \n                x <- (bind_expr _ exp); \n                & (varunit, !x, nil)%expr\n            | Primitive args res p exprs => _\n            (* | Try A =>  *)\n            (*     [< rA, gA, eA >] :- compile _ A; *)\n            (*     let e := effect_guard gA eA in *)\n            (*       & (varunit, #b true, [e])%list *)\n            (*     (* & (varunit, gA, eA) *) *)\n            | OrElse t A A' => \n                [< rA, gA, eA >] :- compile _ A;\n                [< rA', gA', eA' >] :- compile _ A';\n                let e := effect_guard gA eA in \n                let e' := effect_guard ((~ gA) &&  gA')%expr eA' in \n                  r <- (bind_expr _ (Emux _ _ gA (!rA) (!rA'))%expr); \n                  & ( r , (gA || gA')%expr , [e;e'])%list\n          end in f t a).\n  (* primitive *)\n  revert exprs. \n  refine (match p with\n            | register_read t v => _\n            | register_write t v => _\n            | regfile_read n t v p => _\n            | regfile_write n t v p => _\n          end); clear p; intros exprs. \n  (* register read *)\n  refine (x <- (bind_reg_read _ v); &(x, #b true, nil)). \n  (* register write *)\n  refine ( let env := convert _ exprs in \n             let w := fst env in \n               x <- bind_expr _ w; \n           let e := ([effect_reg_write _ v x])%list  in \n             &( varunit, #b true, e)\n         ). \n  (* register file read *)\n  refine ( let env := convert _ exprs in \n             let adr := fst env in \n               adr <- bind_expr _ adr; \n           x <- bind_regfile_read _ _ v _ adr; \n           &( x, #b true, nil)\n         ). \n  (* register file write *)\n  refine ( let env := convert _ exprs in \n             match env with \n               | (adr, (w, _)) => \n                   adr <- bind_expr _ adr; \n                   w <- bind_expr _ w;\n                   let e :=  ([effect_regfile_write _ _ v _ adr w])%list in                      \n                     &( varunit, #b true, e)                      \n             end\n         ). \n    (* or else *)\n  \n  Defined. \n  \n  Definition wrap t (T : preblock t) : block. \n  Proof. \n    eapply compose. apply T. \n    intros _ g e. \n    refine (            let e := effect_guard g e in \n                          & (cons e nil )). \n  Defined. \n  End defs. \n  \n  (** * Semantics *)\n  Section sem. \n    Variable st : eval_state Phi. \n    Definition eval_bind t (b : bind eval_type t) : (eval_type t).\n    refine (match b with\n              | bind_expr x =>  (eval_expr _ x)\n              | bind_reg_read v => (Tuple.get _ _ v st)\n              | bind_regfile_read n v p adr => \n                  let rf := Tuple.get Phi (Tregfile n t) v st in\n                    Regfile.get rf (Word.unsigned adr)                \n            end\n           ). \n    Defined. \n    \n    Definition up {A} (x : option A) y := match x with None => y | Some y => y end.  \n                                                                \n    Fixpoint eval_effect (e :effect eval_type) (Delta : updates) : updates :=    \n      match e with \n        | effect_guard g l' => \n            let fix eval_effects l Delta := \n                match l with \n                  | nil => Delta\n                  | cons e q =>  \n                      let Delta := eval_effect e Delta in \n                        eval_effects q Delta\n                end in     \n              match eval_expr _ g with \n                | true =>  (* match eval_effects l' Delta with *)\n                    (*     | Some Delta => Some Delta *)\n                    (*     | None => Some Delta *)\n                        (* end                         *)\n                    eval_effects l' Delta\n                | false => Delta\n            end\n      | effect_reg_write t v w =>                                               \n          Core.Diff.add Phi Delta (Treg t) v w \n      | effect_regfile_write  n t v p adr w  =>  \n          let rf := Tuple.get Phi (Tregfile n t) v st in                          \n            let rf := Regfile.set rf (Word.unsigned adr) w in \n              Core.Diff.add Phi Delta (Tregfile n t) v rf            \n    end. \n  \n    Fixpoint eval_effects ( l : list (effect eval_type)) Delta : updates :=\n      match l with \n        | nil =>  Delta\n        | cons e q => (* do Delta <- eval_effect e Delta;  *)\n            let Delta :=  (eval_effect e Delta) in \n            eval_effects q Delta\n      end. \n  \n    Lemma fold_eval_effects :\n      (fix eval_effects l Delta := \n       match l with \n                | nil =>  Delta\n                | cons e q => \n                    let Delta := (eval_effect e Delta) in \n                      (* do Delta <- eval_effect e Delta;  *)\n                      eval_effects q Delta\n       end)= eval_effects .\n    Proof. \n      unfold eval_effects. reflexivity.\n    Qed. \n    \n    (* Lemma eval_effects_cons  t q Delta :  *)\n    (*   eval_effects (t :: q) Delta = do Delta' <- eval_effect  t Delta; eval_effects q Delta'.  *)\n    (* Proof. *)\n    (*   reflexivity.  *)\n    (* Qed.  *)\n    \n    (* Lemma eval_effect_guard (gA : expr eval_type Bool) eA Delta:  *)\n    (*   eval_expr  _ gA = true -> *)\n    (*   eval_effect  (effect_guard eval_type gA eA) Delta = eval_effects eA Delta.  *)\n    (* Proof.  *)\n    (*   intros. simpl. rewrite (fold_eval_effects).  *)\n    (*   rewrite H. reflexivity.  *)\n    (* Qed.  *)\n\n    Fixpoint eval_preblock t  (T : preblock  eval_type t) :\n      updates -> option (eval_type t * updates) := \n      match T with\n        | telescope_bind arg bind cont => \n            fun Delta => \n              let res := eval_bind _ bind in\n              eval_preblock _ (cont res) Delta\n        | telescope_end (p, g, e) => fun Delta =>\n                                      let g := eval_expr _ g  in             \n                                      if g then                                         \n                                        Some (p, eval_effects e Delta)\n                                      else None\n    end. \n  \n  \n    Fixpoint eval_block (a : block eval_type) {struct a}: updates ->  updates :=\n      match a with\n        | telescope_bind arg bind cont => \n            fun Delta => \n              let res  := eval_bind _ bind in \n                eval_block (cont res) Delta\n        | telescope_end effects => eval_effects effects\n      end. \n    \n  End sem. \n\n\n  Notation \"x <-- e1 ; e2\" := (telescope_bind  _ _ _ e1 (fun x => e2)) (right associativity, at level 80, e1 at next level).  \n  Notation \" & e \" := (telescope_end  _ _ e) (at level 71). \n  Notation \"[< r , g , e >] :- t1 ; t2 \" := (compose  _ t1 (fun r g e => t2)) (right associativity, at level 80, t1 at next level). \n  \n  Section correctness. \n  \n    \n    \n    Notation C := (compile eval_type tt). \n    Lemma eval_andb_true x y : (eval_expr Bool (andb eval_type x y)) = (eval_expr Bool x && eval_expr Bool y)%bool.\n    Proof.\n      Require Import Equality. \n      dependent destruction x. simpl. \n    Admitted.  \n\n    Lemma eval_effects_append  st e f (Delta : updates) : \n      eval_effects st (e ++ f) Delta = \n                   eval_effects st f (eval_effects st e Delta).              \n    Proof. \n      revert Delta. \n      induction e. \n      + reflexivity. \n      + intros Delta.\n        \n        simpl. rewrite IHe. reflexivity.  \n\n    Qed. \n\n    Variable st : eval_state Phi. \n\n    Notation \"B / Delta \" := (eval_preblock st _ B Delta). \n    Theorem CPS_compile_correct t (a : action Phi eval_type t)  Delta:\n      eval_preblock st _ (C t a ) Delta =  (Core.Sem.eval_action a st Delta).\n    Proof. \n      revert Delta. \n      induction a. \n      - intros.  reflexivity. \n      - intros Delta. simpl. unfold  Sem.Dyn.Bind. rewrite <- IHa.\n        transitivity (do ed <- (C t a) / Delta ; \n                      let (e,d) := ed in \n                      eval_preblock st u (C u (f e)) d\n                   ); \n        [|destruct  ((C t a) / Delta) as [[ e d ]| ]; simpl; easy]. \n        clear IHa H.\n        generalize (C t a) as T. intros T. clear a.\n        \n        induction T. destruct a as [[rA gA] eA]. \n        simpl in *. \n        case_eq (eval_expr Bool gA); intros H.  simpl.\n        induction (C u (f rA)). destruct a as [[rB gB] eB]. simpl. \n        * rewrite eval_effects_append. rewrite eval_andb_true. rewrite H. simpl. reflexivity. \n        * simpl. rewrite H0. reflexivity.         \n\n        * induction (C u (f rA)). destruct a as [[rB gB] eB]. simpl. \n          rewrite eval_andb_true. rewrite H. reflexivity.  \n          simpl. rewrite H0. reflexivity. \n        * simpl. rewrite H. reflexivity.\n\n      - simpl. intros. \n          Ltac t :=\n            repeat match goal with \n                     | |- context [check ?x ; ?y] => \n                         let H := fresh \"check\" in \n                           case_eq x; intros H\n                   end. \n          t; trivial. \n      -                         (* primitive *)\n      intros. destruct p.  \n        +  simpl. reflexivity. \n        + simpl.\n              \n          set (x := DList.to_tuple eval_expr exprs). \n          replace (x) with (fst x, snd x) by (destruct x; reflexivity).\n\n          Lemma convert_commute  l (dl : DList.T (expr eval_type) l): map  _ _ _ (eval_expr) l (convert _ l dl) = DList.to_tuple (eval_expr) dl. \n          Proof. \n            induction dl. simpl. reflexivity. \n            simpl. f_equal. apply IHdl. \n          Qed. \n          simpl. \n    \n          replace (eval_expr t (fst (convert eval_type [t] exprs))) with (fst x). reflexivity. \n          subst x. rewrite <- convert_commute. simpl. reflexivity.  \n\n        + simpl. \n          rewrite <- convert_commute. simpl. reflexivity.\n        + simpl. \n          rewrite <- convert_commute. simpl. \n          case_eq (convert eval_type ([Tlift (W p); t])%list exprs). \n          intros adr [value tt] H.  simpl. simpl in tt.           \n          reflexivity. \n\n      - intros. simpl.   unfold Sem.Dyn.OrElse. \n        rewrite <- IHa1, <- IHa2 . clear IHa1 IHa2. \n        generalize (C t a1); intros T; generalize (C t a2); intros T'. \n        induction T as [[[rA gA] eA] |]; simpl.\n        induction T' as [[[rA' gA'] eA'] |]. simpl compose.\n        t. simpl. rewrite check0. simpl.  t. reflexivity. \n        simpl. rewrite check0. simpl. t; reflexivity.  \n        simpl. rewrite H. reflexivity. \n        simpl. rewrite H. reflexivity.\n\n    Qed.\nEnd correctness. \nEnd t. \nArguments telescope_bind {Phi R A arg}  _ _.  \nNotation \"'DO' X <- E ; F\" := (telescope_bind E (fun X => F)).  \nNotation \"'RETURN' X\" := (telescope_end _ _ _ X). \nArguments bind_expr  {Phi R t} _%expr. \nNotation \"[: v ]\" := (bind_reg_read _ _ _ v).   \n(* Section test.  *)\n(*   Require Import MOD.  *)\n(*   Definition Z (t : type) := unit.  *)\n(*   Eval compute in compile _ Z _ _  (iterate 5 Z) .  *)\n\n(*   Eval compute in compile _ Z _ _ (done 5 Z).  *)\n\n(* End test.  *)\n\n(* Section test2.  *)\n(*   Require Import Isa.  *)\n(*   Eval compute in compile _ _ 0 _ (loadi_rule 5 (fun _ => nat)).  *)\n\n(*   Eval compute in compile _ _ 0 _ (store_rule 5 (fun _ => nat)).  *)\n\n(* End test2.  *)\n\n", "meta": {"author": "braibant", "repo": "Synthesis", "sha": "922982aaddb8a7a16101ff304c45d24a6265dc2e", "save_path": "github-repos/coq/braibant-Synthesis", "path": "github-repos/coq/braibant-Synthesis/Synthesis-922982aaddb8a7a16101ff304c45d24a6265dc2e/attic/BackEnd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307806984443, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.28874174890206106}}
{"text": "\nRequire Export Iron.Language.SystemF2Effect.Step.TypeC.\nRequire Export Iron.Language.SystemF2Effect.Store.LiveS.\nRequire Export Iron.Language.SystemF2Effect.Store.LiveE.\n\n\n(* When a well typed expression transitions to the next state\n   then its type is preserved. *)\nTheorem preservation\n :  forall se sp sp' ss ss' fs fs' x x' t e\n ,  WfFS   se sp ss  fs\n -> LiveS ss fs -> LiveE  fs e\n -> TypeC  nil nil se sp fs  x   t  e    \n -> StepF  ss  sp  fs x  ss' sp' fs' x'   \n -> (exists se' e'\n    ,  WfFS  se' sp' ss' fs'\n    /\\ LiveS ss' fs'    \n    /\\ LiveE fs' e'\n    /\\ SubsVisibleT  nil sp' sp  e  e'\n    /\\ TypeC nil nil se' sp' fs' x' t e').\nProof.\n intros se sp sp' ss ss' fs fs' x x' t e.\n intros HH HLS HLE HC HS. \n gen t e.\n induction HS; intros.\n\n\n (*********************************************************)\n (* Pure evaluation. *)\n Case \"SfStep\". \n { inverts_typec. \n   exists se. \n   exists e. \n   intuition.\n\n   (* Original effect visibly subsumes effect of result. *)\n   - apply subsVisibleT_refl.\n     eauto.\n\n   (* Resulting configuration is well typed. *)\n   - eapply TcExp; eauto.\n     eapply stepp_preservation; eauto.\n }\n\n\n (*********************************************************)\n (* Push let context. *)\n Case \"SfLetPush\".\n { exists se.\n   exists e.\n   intuition.\n   \n   (* Frame stack with new FLet frame is well formed. *)\n   - inverts HH. split; auto.\n     unfold StoreP in *. rip.\n     + inverts H3. nope. eauto.\n     + inverts H3. nope. eauto.\n    \n   (* All store bindings mentioned by frame stack are still live. *)\n   - eapply liveS_push_flet; auto.\n\n   (* Original effect visibly subsumes effect of result. *)\n   - inverts_typec.\n     eapply subsVisibleT_refl; eauto.\n\n   (* Resulting configuation is well typed. *)\n   - inverts_typec.\n     eapply TcExp \n      with (t1 := t) (e1 := e0) (e2 := TSum e3 e2).\n      + eapply EqTrans.\n        * eapply EqSumAssoc; eauto.\n        * auto.\n      + auto.\n      + eapply TfConsLet; eauto.\n }\n\n\n (*********************************************************)\n (* Pop let context and substitute. *)\n Case \"SfLetPop\".\n { exists se.\n   exists e.\n   intuition.\n\n   (* Store is still well formed. *)\n   - inverts HH. split; auto.\n     unfold StoreP in *. \n     rip; firstorder.  \n\n   (* After popping top FLet frame, effects of result are still \n      to live regions. *)\n   - eapply liveE_pop_flet; eauto.\n\n   (* Original effect visibly subsumes effect of result. *)\n   - inverts_typec.\n     eapply subsVisibleT_refl; eauto.\n\n   (* Resulting configuration is well typed. *)\n   - inverts_typec.\n     eapply TcExp  \n      with (t1 := t3) (e1 := e0) (e2 := e3).\n      + eapply EqTrans.\n        * eapply equivT_sum_left; auto.\n          have (KindT nil sp e0 KEffect).\n          have (KindT nil sp e3 KEffect).\n          eapply KiSum; eauto.\n        * auto.\n      + eapply subst_val_exp; eauto.\n      + auto.\n } \n\n\n (*********************************************************)\n (* Create a private region. *)\n Case \"SfPrivatePush\".\n { inverts_typec.\n   set (r := TRgn p).\n   exists se.\n   exists (TSum (substTT 0 r e0) (substTT 0 r e2)).\n\n   have (SumKind KEffect).\n\n   have (KindT (nil :> KRegion) sp e0 KEffect).\n\n   have (KindT nil sp e1 KEffect)\n    by  (eapply equivT_kind_left; eauto).\n   have (ClosedT e1).\n\n   have (KindT nil sp e2 KEffect)\n    by  (eapply equivT_kind_left; eauto).\n   have (ClosedT e2).\n   intuition.\n\n   (* All store bindings mentioned by resulting frame stack\n      are still live. *)\n   - inverts HH.\n     subst p.\n     eapply liveS_push_fpriv_none_allocRegion; eauto.\n\n   (* Resulting effect is to live regions. *)\n   - eapply liveE_sum_above.\n     + eapply liveE_phase_change.\n\n       have HLL: (liftTT 1 0 e1 = maskOnVarT 0 e0)\n        by  (eapply lowerTT_some_liftTT; eauto).\n       rrwrite (liftTT 1 0 e1 = e1) in HLL.\n\n       have (SubsT nil sp e e1 KEffect) \n        by  (eapply EqSym in H0; eauto).\n\n       have (LiveE fs e1).\n\n       have HLW: (LiveE (fs :> FPriv None p) e1).\n       rewrite HLL in HLW.\n\n       have HL0: (LiveE (fs :> FPriv None p) e0) \n        by (eapply liveE_maskOnVarT; eauto).\n\n       trivial.\n\n     + have (SubsT nil sp e e2 KEffect)\n        by  (eapply EqSym in H0; eauto).\n\n       have (LiveE fs e2).\n       have (LiveE (fs :> FPriv None p) e2).\n       rrwrite (substTT 0 r e2 = e2); auto.\n       \n   (* Effect of result is subsumed by previous. *)\n   - rrwrite ( TSum (substTT 0 r e0) (substTT 0 r e2)\n             = substTT 0 r (TSum e0 e2)).\n     have (ClosedT e).\n     rgwrite (e = substTT 0 r e)\n      by (symmetry; eauto).\n\n     simpl.\n     set (sp' := SRegion p <: sp).\n     assert (SubsVisibleT nil sp' sp (substTT 0 r e) (substTT 0 r e0)).\n     { have HE: (EquivT       nil sp' e (TSum e1 e2) KEffect)\n        by (subst sp'; eauto).\n\n       have HS: (SubsT        nil sp' e e1 KEffect)\n        by (subst sp'; eauto).\n      \n       apply lowerTT_some_liftTT in H5.\n\n       assert   (SubsVisibleT nil sp' sp (liftTT 1 0 e) (liftTT 1 0 e1)) as HV.\n        rrwrite (liftTT 1 0 e  = e).\n        rrwrite (liftTT 1 0 e1 = e1).\n        eapply subsT_subsVisibleT.\n        auto.\n       rewrite H5 in HV.\n\n       rrwrite (liftTT  1 0 e = e) in HV.\n       rrwrite (substTT 0 r e = e).\n       eapply subsVisibleT_mask; eauto.\n     }\n\n     assert (SubsVisibleT nil sp' sp (substTT 0 r e) (substTT 0 r e2)).\n     { rrwrite (substTT 0 r e  = e).\n       rrwrite (substTT 0 r e2 = e2).\n\n       have HE: (EquivT nil sp' e (TSum e1 e2) KEffect)\n        by (subst sp'; eauto).\n        \n       eapply SbEquiv in HE.\n       eapply SbSumAboveRight in HE.\n       eapply subsT_subsVisibleT. auto. auto.\n     }\n \n     unfold SubsVisibleT.\n      simpl.\n      apply SbSumAbove; auto.\n\n   (* Result expression is well typed. *)\n   - rrwrite (substTT 0 r e2 = e2).\n     eapply TcExp \n       with (sp := SRegion p <: sp) \n            (t1 := substTT 0 r t0)\n            (e1 := substTT 0 r e0)\n            (e2 := substTT 0 r e2); auto.\n\n     (* Type of result is equivlent to before *)\n     + rrwrite (substTT 0 r e2 = e2).\n       eapply EqRefl.\n        eapply KiSum; auto.\n         * eapply subst_type_type. \n            eauto.\n            subst r. eauto.\n\n     (* Type is preserved after substituting region handle. *)\n     + rgwrite (nil = substTE 0 r nil).\n       rgwrite (se  = substTE 0 r se)\n        by (inverts HH; symmetry; auto).\n\n       eapply subst_type_exp with (k2 := KRegion).\n       * rrwrite (liftTE 0 nil = nil).\n         rrwrite (liftTE 0 se  = se) \n          by (inverts HH; auto).\n         auto.\n       * subst r.\n         eapply KiRgn.\n         rgwrite (SRegion p <: sp = sp ++ (nil :> SRegion p)).\n         eapply in_app_right; auto.\n\n     (* New frame stack is well typed. *)\n     + eapply TfConsPriv; eauto 2.\n\n       (* Effect of frame stack is still to live regions *)\n       * rrwrite (substTT 0 r e2 = e2).\n         have    (SubsT nil sp e e2 KEffect) \n          by     (eapply EqSym in H0; eauto).\n         eapply  liveE_subsT; eauto.\n\n       (* Frame stack is well typed after substituting region handle.\n          The initial type and effect are closed, so substituting\n          the region handle into them doesn't do anything. *)\n       * assert (ClosedT t0).\n         { have HK: (KindT  (nil :> KRegion) sp t0 KData).\n           eapply kind_wfT in HK.\n           simpl in HK.\n\n           have (~FreeT 0 t0) \n            by (eapply lowerTT_freeT; eauto).\n           eapply freeT_wfT_drop; eauto.\n         }\n\n         rrwrite (substTT 0 r t0 = t0).\n         rrwrite (substTT 0 r e2 = e2).\n         rrwrite (t1 = t0)\n          by (eapply lowerTT_closedT; eauto).\n         eauto.\n }\n\n\n (*********************************************************)\n (* Pop a private region from the frame stack. *)\n Case \"SfPrivatePop\".\n { inverts_typec.\n\n   (* We can only pop if there is at least on region in the store. *)\n   destruct sp.\n\n   (* No regions in store. *)\n   - inverts HH. rip. \n     unfold StoreP in *. rip.\n     have (In (FPriv None p) (fs :> FPriv None p)).\n     have (In (SRegion p) nil) by firstorder.\n     nope.\n\n   (* At least one region in store. *)\n   - destruct s.\n     exists se.\n     exists e2.\n     intuition.\n\n     (* Frame stack is still well formed after popping the top FUse frame *)\n     + eapply wfFS_region_deallocate; auto.\n\n     (* After popping top FUse,\n        all store bindings mentioned by frame stack are still live. *)\n     + eapply liveS_deallocRegion; eauto.\n\n     (* New effect subsumes old one. *)\n     + eapply subsT_subsVisibleT. \n       have (EquivT nil (sp :> SRegion n) e2 e KEffect).\n       eauto.\n\n     (* Resulting configuation is well typed. *)\n     + eapply TcExp \n         with (sp := sp :> SRegion n)\n              (e1 := TBot KEffect)\n              (e2 := e2); eauto.\n\n       eapply EqSym; eauto.\n }\n\n\n (*********************************************************)\n (* Push an extend frame on the stack. *)\n Case \"SfExtendPush\".\n { inverts_typec.\n   set (r1 := TRgn p1).\n   set (r2 := TRgn p2).\n   exists se.\n   exists (TSum (substTT 0 r2 e0) (TSum e2 (TAlloc r1))).\n   intuition.\n   \n   (* Updated store is well formed. *)\n   - inverts_kind. \n     eapply wfFS_push_priv_ext; auto.\n\n   (* Updated store is live relative to frame stack. *)\n   - inverts HH.\n     subst p2.\n     eapply liveS_push_fpriv_some_allocRegion; eauto.\n\n     assert (SubsT nil sp e (TAlloc (TRgn p1)) KEffect).\n     { have (SubsT nil sp e (TSum (TSum eL (TAlloc (TRgn p1))) e2) KEffect).\n       eapply SbSumAboveLeft; eauto.\n     }\n\n     have (LiveE fs (TAlloc (TRgn p1))).\n     eapply liveSP_from_effect; eauto.\n      snorm.\n     \n   (* Frame stack is live relative to effect. *)\n   - apply liveE_sum_above.\n     + assert (ClosedT eL).\n       { have (KindT nil sp (TSum (TSum eL (TAlloc (TRgn p1))) e2) KEffect).\n         inverts_kind. eauto.\n       }\n\n       have HLL: (liftTT 1 0 eL = maskOnVarT 0 e0)\n        by  (eapply lowerTT_some_liftTT; eauto).\n       rrwrite (liftTT 1 0 eL = eL) in HLL.\n\n       have (LiveE fs (TSum (TSum eL (TAlloc (TRgn p1))) e2))\n        by (eapply liveE_equivT_left; eauto).\n       have (LiveE fs eL).\n\n       apply liveE_phase_change.\n\n       have HLW: (LiveE (fs :> FPriv (Some p1) p2) eL).\n       rewrite HLL in HLW.\n\n       eapply liveE_maskOnVarT; eauto.\n\n    + have (SubsT nil sp e (TSum (TSum eL (TAlloc (TRgn p1))) e2) KEffect).\n      apply liveE_sum_above.\n      * have (SubsT nil sp e e2 KEffect).\n        eapply liveE_subsT; eauto.\n      * have (SubsT nil sp e (TAlloc (TRgn p1)) KEffect).\n        eapply liveE_subsT; eauto.\n      \n   (* Effect of result is subsumed by previous. *)\n   - set (sp' := SRegion p2 <: sp).\n     have (KindT nil sp    (TSum (TSum eL (TAlloc (TRgn p1))) e2) KEffect).\n     have (SubsT nil sp' e (TSum (TSum eL (TAlloc (TRgn p1))) e2) KEffect)\n      by (subst sp'; eapply subsT_stprops_snoc; eauto).\n\n     inverts_kind.\n\n     assert (SubsVisibleT nil sp' sp e (substTT 0 r2 e0)) as HE1.\n     { eapply subsVisibleT_mask\n        with (p := p2); auto.\n\n       have HL: (liftTT 1 0 eL = maskOnVarT 0 e0)\n        by (apply lowerTT_some_liftTT; auto).\n\n       rewrite <- HL.\n       rgwrite (liftTT 1 0 eL = eL).\n       eapply subsT_subsVisibleT.\n       eapply SbSumAboveLeft; eauto.\n      }\n\n     assert (SubsVisibleT nil sp' sp e e2)          as HE2.\n     { eapply subsT_subsVisibleT.\n       eapply SbSumAboveRight; eauto.\n     }\n\n     assert (SubsVisibleT nil sp' sp e (TAlloc r1)) as HE3.\n     { subst r1.\n       eapply subsT_subsVisibleT.\n       eapply SbSumAboveLeft; eauto.\n     }\n     eauto.\n\n   (* Resulting state is well typed. *)\n   - eapply TcExp\n       with (e1 := substTT 0 r2 e0)\n            (e2 := TSum e2 (TAlloc r1))\n            (t1 := substTT 0 r2 t0).\n     (* Equivalence of result effect *)\n     + eapply EqRefl.\n       eapply KiSum; auto.\n       * subst r2.\n         have (KindT (nil :> KRegion) sp                 e0 KEffect).\n         have (KindT (nil :> KRegion) (SRegion p2 <: sp) e0 KEffect).\n         have (KindT nil (SRegion p2 <: sp) (TRgn p2) KRegion).\n         eapply subst_type_type. eauto. eauto.\n       * apply equivT_kind_left in H0.\n         inverts_kind. subst r1.\n         eapply KiSum; auto.\n         eapply KiCon1. snorm. eauto.\n   \n     (* Expression with new region subst is well typed. *)\n     + rgwrite (nil = substTE 0 r2 nil).\n       rgwrite (se  = substTE 0 r2 se)\n        by (inverts HH; symmetry; auto).\n\n       eapply subst_type_exp.\n       * eapply typex_stprops_snoc.\n         rgwrite (nil = liftTE 0 nil).\n         rgwrite (se  = liftTE 0 se)\n          by (inverts HH; symmetry; auto).\n         eauto.\n       * subst r2. eauto.\n\n     (* Extended frame stack is well typed. *)\n     + have (KindT (nil :> KRegion) sp t0 KData).\n       have (not (In (SRegion p2) sp))\n        by (subst p2; auto).\n       eapply TfConsExt; eauto.\n       * inverts_kind. eauto.\n       * eapply typeF_freshSuppFs; eauto.\n       * have (LiveE fs (TSum (TSum eL (TAlloc (TRgn p1))) e2))\n          by (eapply liveE_equivT_left; eauto).\n         eapply liveE_sum_above.\n          eapply liveE_sum_above_right; eauto.\n          eapply liveE_sum_above_left  in H4.\n          eapply liveE_sum_above_right in H4.\n          trivial.\n       * erewrite mergeT_substTT.\n         eapply typeF_stprops_snoc. auto.\n         eauto. eauto.\n  }\n\n (*********************************************************)\n (* Pop and extend frame from the stack, \n    and merge the new region with the old one. *)\n Case \"SfExtendPop\".\n { inverts_typec.\n   set (r1 := TRgn p1).\n   set (r2 := TRgn p2).\n   exists (mergeTE p1 p2 se).\n   exists e0.\n   intuition.\n\n   (* Updated store is well formed. *)\n   - rrwrite (map (mergeB p1 p2) ss = mergeBs p1 p2 ss).\n     eapply wfFS_pop_priv_ext; eauto.\n    \n   (* Updated store is live relative to frame stack. *)\n   - SCase \"LiveS\".\n     eapply liveS_mergeB.\n     + have (LiveSF ss (FPriv (Some p1) p2)).\n       unfold LiveSF in H0.\n       unfold LiveSP. intros.\n       eapply H0 in H1. inverts H1. auto.\n     + have (LiveS ss fs).\n       auto.\n\n   (* Frame stack is live relative to effect. *) \n   - SCase \"LiveE\".\n     eapply liveE_sum_above_left; eauto.\n\n   (* Effect of result is subsumed by previous. *)\n   - SCase \"SubsVisibleT\".\n     eapply subsT_subsVisibleT.\n     set (e' := (TSum (TBot KEffect) (TSum e0 (TAlloc (TRgn p1))))).\n     have (KindT  nil sp e'   KEffect).\n     have (EquivT nil sp e e' KEffect).\n     eapply SbSumAboveRight; eauto.\n\n   (* Resulting state is well typed. *)\n   - SCase \"TypeC\".\n     eapply TcExp\n       with (t1 := mergeT p1 p2 t1)\n            (e1 := TBot KEffect)\n            (e2 := e0).\n\n     (* Equivalence of result effect. *)\n     + have (KindT nil sp (TSum (TBot KEffect) \n                          (TSum e0 (TAlloc (TRgn p1)))) KEffect).\n       inverts_kind.\n       eapply EqSym; eauto.\n\n     (* Result value is well typed. *)\n     + rgwrite (nil                    = mergeTE p1 p2 nil).\n       rgwrite (XVal (mergeV p1 p2 v1) = mergeX  p1 p2 (XVal v1)).\n       rgwrite (TBot KEffect           = mergeT  p1 p2 (TBot KEffect)).\n       eapply mergeX_typeX. auto. eauto.\n\n     (* Popped frame stack is well typed. *)\n     + rgwrite (nil = mergeTE p1 p2 nil).\n       eapply typeF_mergeTE; eauto.\n }\n\n (*********************************************************)\n (* Allocate a reference. *)\n Case \"SfStoreAlloc\".\n { inverts HC.\n   inverts H0.\n   exists (TRef   (TRgn p1) t2 <: se).\n   exists e2.\n   intuition.\n\n   (* Store is well formed after adding a binding. *)\n   - remember (TRgn p1) as r.\n\n     have (SubsT nil sp e (TAlloc r) KEffect)\n      by  (eapply EqSym in H; eauto).\n\n     have (LiveE fs (TAlloc r)).\n     subst r.\n\n     eapply wfFS_stbind_snoc; auto.\n     inverts_kind. auto.\n\n   (* Resulting effects are to live regions. *)\n   - have  (SubsT nil sp e e2 KEffect)\n      by   (eapply EqSym in H; eauto).\n     eapply liveE_subsT; eauto.\n\n   (* Original effect visibly subsumes resulting one. *)\n   - eapply EqSym in H.\n      eapply subsT_subsVisibleT; eauto.\n      eauto. eauto.\n\n   (* Resulting configuation is well typed. *)\n   - eapply TcExp\n      with (t1 := TRef (TRgn p1) t2)\n           (e1 := TBot KEffect)\n           (e2 := e2).\n     + eapply EqSym.\n        * eauto. \n        * eapply KiSum; eauto.\n        * eapply equivT_sum_left; eauto.\n     + eapply TxVal.\n       eapply TvLoc.\n        have    (length se = length ss).\n        rrwrite (length ss = length se).\n        eauto. eauto.\n     + eapply typeF_stenv_snoc; eauto.\n }\n\n\n (*********************************************************)\n (* Read from a reference. *)\n Case \"SfStoreRead\".\n { inverts HC.\n   exists se.\n   exists e2. \n   intuition.\n\n   (* Resulting effects are to live regions. *)\n   - have  (SubsT nil sp e e2 KEffect)\n      by   (eapply EqSym in H0; eauto).\n     eapply liveE_subsT; eauto.\n\n   (* Original effect visibly subsumes resulting one. *)\n   - eapply EqSym in H0.\n      eapply subsT_subsVisibleT; eauto.\n      eauto. eauto.\n\n   (* Resulting configutation is well typed. *)\n   - eapply TcExp\n      with (t1 := t1)\n           (e1 := TBot KEffect)\n           (e2 := e2).\n     + eapply EqSym; eauto.\n     + inverts H1.\n       inverts H12.\n       eapply TxVal.\n        inverts HH. rip.\n        eapply storet_get_typev; eauto.\n     + eauto.\n }\n\n\n (*********************************************************)\n (* Write to a reference. *)\n Case \"SfStoreWrite\".\n { inverts HC.\n   exists se.\n   exists e2.\n   intuition.\n\n   (* Resulting store is well formed. *)\n   - inverts_type.\n     eapply wfFS_stbind_update; eauto.\n     inverts_kind; auto.\n\n   (* All store bindings mentioned by frame stack are still live. *)\n   - eapply liveS_stvalue_update.\n     + inverts_type.\n       remember (TRgn p) as r.\n\n       have (SubsT nil sp e (TWrite r) KEffect)\n        by  (eapply EqSym in H0; eauto).\n\n       have (LiveE fs (TWrite r))\n        by  (eapply liveE_subsT; eauto).\n\n       eapply liveE_fpriv_in with (e := TWrite r).\n       * subst r. snorm. \n       * subst r. snorm.\n     + auto.\n\n   (* Resulting effects are to live regions. *)\n   - have  (SubsT nil sp e e2 KEffect)\n      by   (eapply EqSym in H0; eauto).\n     eapply liveE_subsT; eauto.\n\n   (* Original effect visibly subsumes resulting one. *)\n    - eapply EqSym in H0.\n      eapply subsT_subsVisibleT; eauto.\n       eauto. eauto.\n\n   (* Resulting configuration is well typed. *)\n   - eapply TcExp\n      with (t1 := t1)\n           (e1 := TBot KEffect)\n           (e2 := e2).\n     + eapply EqSym; eauto.\n     + inverts_type.\n       eapply TxVal.\n        inverts HH. rip.\n     + eauto.\n }\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/Preservation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.28865375806793864}}
{"text": "Require Import Coq.Lists.List.\nRequire Import BinNums ZArith Lia.\n\nImport ListNotations.\n\nFrom compcert Require Import Integers Floats.\n\nRequire Import Types.\n\nInductive value : Type :=\n| Vunit\n| Vbool: bool -> value\n| Vint: intsize -> signedness -> int -> value\n| Vint64: signedness -> int64 -> value\n| Vfloat32: float32 -> value\n| Vfloat64: float -> value\n(* | Vmutarr: positive -> value *)\n| Varr: positive -> list value -> value.\n\n(* Definition Vzero64 := Vint64 Unsigned Int64.zero.\n   Definition Vone64 := Vint64 Unsigned Int64.one.\n\n   Definition Vzero32 := Vint I32 Unsigned Int.zero.\n   Definition Vone32 := Vint I32 Unsigned Int.one.\n\n   Definition Vzero16 := Vint I16 Unsigned Int.zero.\n   Definition Vone16 := Vint I16 Unsigned Int.one.\n\n   Definition Vzero8 := Vint I8 Unsigned Int.zero.\n   Definition Vone8 := Vint I8 Unsigned Int.one. *)\n\nDefinition Vtrue := Vbool true.\nDefinition Vfalse := Vbool false.\n\nDefinition shrink (v: value) :=\n  match v with\n  | Vint I8 Unsigned n => Vint I8 Unsigned (Int.zero_ext 8 n)\n  | Vint I8 Signed n => Vint I8 Signed (Int.sign_ext 8 n)\n  | Vint I16 Unsigned n => Vint I16 Unsigned (Int.zero_ext 16 n)\n  | Vint I16 Signed n => Vint I16 Signed (Int.sign_ext 16 n)\n  | _ => v\n  end.\n\nTheorem shrink_shrink:\n  forall v, shrink v = shrink (shrink v).\nProof.\n  intro. destruct v; try reflexivity.\n  destruct i, s; try reflexivity; simpl;\n    ((rewrite Int.sign_ext_idem by lia) || (rewrite Int.zero_ext_idem by lia));\n    reflexivity.\nQed.\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/BValues.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2886537516353661}}
{"text": "(* PREAMBLE *)\n\nFrom compcert.cfrontend           Require Csem.\nFrom compcert.common              Require Values.\nFrom compcert.lib                 Require Coqlib.\n\nFrom trancert.lib                 Require All.\nFrom trancert.properties.memory   Require Permissions.\nFrom trancert.simulations.memory.bijection\n                                  Require Def ToInjection.\n\n\nImport lib.All\n       bijection.Def bijection.AST\n       Coqlib bijection.ToInjection\n       common.Values\n       Values.Val\n       memory.Permissions\n       Memory Mem.\n\n\nSection Store.\n\n  Theorem store_mapped_biject:\n    forall M (chunk : AST.memory_chunk) (m1 : mem)\n      (b1 : block) (ofs : Z) (v1 : val)\n      (n1 m2 : mem) (b2 : block) (v2 : val),\n      biject M m1 m2 ->\n\n      store chunk m1 b1 ofs v1 = Some n1 ->\n      m_fwd M b1 = Some b2 ->\n      biject_value (m_fwd M) v1 v2 ->\n\n      exists n2 : mem,\n        store chunk m2 b2 ofs v2 = Some n2 /\\\n        biject M n1 n2.\n  Proof.\n    intros M chunk m1 b1 ofs v1 n1 m2 b2 v2 Hbiject Hstore Hf Hmap.\n\n    assert (Hinj: Val.inject (m_fwd M) v1 v2) by exact (biject_value_inject (m_fwd M) v1 v2 Hmap).\n\n    destruct Hbiject.\n    exploit store_mapped_inject; try eapply mb_inj__fwd; eauto.\n    eapply embedding_meminj_some. eassumption.\n    rewrite Z.add_0_r.\n    intros (n2 & Hstore' & Hinject').\n\n    exploit store_mapped_inject; try eapply mb_inj__bwd; eauto.\n    {\n      apply M in Hf.\n      eapply embedding_meminj_some. eassumption.\n    }\n    {\n      eapply biject_value_symm in Hmap; eauto; last by apply M.\n      by eapply biject_value_inject; eassumption.\n    }\n\n    rewrite Z.add_0_r.\n    intros (n3 & Hstore'' & Hinject'').\n    rewrite Hstore in Hstore''. inv Hstore''.\n\n    exists n2.\n    split; auto.\n    econstructor; eauto.\n    erewrite nextblock_store; eauto.\n    erewrite nextblock_store; eauto.\n  Qed.\n\n\n  (** Modifying a block which is not mapped by bijection. *)\n  Theorem store_unmapped_biject:\n    forall M (chunk : AST.memory_chunk) (m1 : mem)\n           (b1 : Values.block) (ofs : Z) (v1 : Values.val)\n           (n1 m2 : mem),\n      biject M m1 m2 ->\n      store chunk m1 b1 ofs v1 = Some n1 ->\n      m_fwd M b1 = None ->\n      biject M n1 m2.\n  Proof.\n    intros until m2.\n    intros [] Hstore Hf.\n    constructor; auto.\n    - by erewrite nextblock_store; eauto.\n    - exploit store_unmapped_inject; [eapply mb_inj__fwd| | | ]; eauto.\n      by eapply embedding_meminj_none.\n    - exploit store_outside_inject; [eapply mb_inj__bwd | | | ]; eauto.\n      intros b' delta ofs' H H0 H1.\n      apply embedding_meminj_none in Hf.\n      unfold to_meminj, option_map in *.\n      repeat option_cases.\n      inv H.\n      apply M in Heq.\n      congruence.\n  Qed.\n\n  (** Modifying a block which is not mapped by bijection. *)\n  Theorem store_outside_biject:\n    forall M (m1 m2 : mem) (chunk : AST.memory_chunk)\n      (b : Values.block) (ofs : Z) (v : Values.val) (m2' : mem),\n      biject M m1 m2 ->\n      (forall (b' : Values.block) (ofs' : Z),\n          m_fwd M b' = Some b ->\n          perm m1 b' ofs' Cur Readable ->\n          ~ ofs <= ofs' < ofs + Memdata.size_chunk chunk)%Z ->\n      store chunk m2 b ofs v = Some m2' ->\n      biject M m1 m2'.\n  Proof.\n    intros M m1 m2 chunk b ofs v m2' [] Hcond Hstore.\n    constructor; auto.\n    - erewrite nextblock_store; eauto.\n    - eapply store_outside_inject ; eauto.\n      intros b' delta ofs' H H0 H1.\n      edestruct to_meminj_delta; eauto.\n      subst delta.\n      rewrite Z.add_0_r in H1.\n      eapply Hcond; eauto.\n    - eapply store_unmapped_inject; eauto.\n      destruct (to_meminj (m_bwd M) b) eqn: Hg; auto.\n      destruct p.\n      edestruct to_meminj_delta; eauto. subst z.\n      exfalso.\n      eapply M in H.\n      eapply Hcond with (ofs' := ofs) in H.\n      eapply H; destruct chunk; simpl; omega.\n      replace (ofs) with (ofs + 0)%Z; last by rewrite Z.add_0_r.\n      eapply perm_inject; eauto.\n      eapply store_valid_access_3 in Hstore; eauto.\n      unfold valid_access in *.\n      decomp.\n      eapply perm_read_from_writable; eauto.\n      destruct chunk; simpl; omega.\n  Qed.\n\nEnd Store.\n\n(** ** [storebytes] commutation *)\n\nSection Storebytes.\n\n  (** Parallel [storebytes] in bijected memories. *)\n  Theorem storebytes_mapped_biject:\n    forall M (m1 : mem) (b1 : Values.block)\n           (ofs : Z) (bytes1 : list Memdata.memval) (n1 m2 : mem)\n           (b2 : Values.block) (bytes2 : list Memdata.memval),\n      biject M m1 m2 ->\n      storebytes m1 b1 ofs bytes1 = Some n1 ->\n      m_fwd M b1 = Some b2 ->\n      list_forall2 (biject_memval (m_fwd M)) bytes1 bytes2 ->\n      exists n2 : mem, storebytes m2 b2 ofs bytes2 = Some n2 /\\ biject M n1 n2.\n  Proof.\n    intros until bytes2.\n    intros [] Hstore Hf Hlist.\n    edestruct storebytes_mapped_inject as (n2 & Hstore2 & Hinject); try eapply mb_inj__fwd; eauto.\n    { eapply embedding_meminj_some. eassumption. }\n    { eapply list_forall2_imply; eauto 2. intros. by apply biject_memval_inject. }\n    rewrite Z.add_0_r in Hstore2.\n    exists n2.\n    split; auto.\n    constructor; auto.\n    - by erewrite nextblock_storebytes; eauto 2.\n    - erewrite nextblock_storebytes; eauto 2.\n    - edestruct storebytes_mapped_inject as (n3 &Hstore' & Hinject'); try eapply mb_inj__bwd; eauto.\n      + by apply M in Hf; apply embedding_meminj_some; eauto.\n      + eapply list_forall2_inv in Hlist; eauto.\n        intros a1 a2 H.\n        apply biject_memval_inject.\n        eapply biject_memval_symm; eauto.\n        by apply M.\n      + rewrite -> Z.add_0_r in *.\n        rewrite Hstore' in Hstore. by autoinj.\n  Qed.\n\n\n  (** [storebytes] in a discarded block. *)\n  Theorem storebytes_unmapped_biject:\n    forall M (m1 : mem) (b1 : Values.block)\n      (ofs : Z) (bytes1 : list Memdata.memval) (n1 m2 : mem),\n      biject M m1 m2 ->\n      storebytes m1 b1 ofs bytes1 = Some n1 ->\n      m_fwd M b1 = None ->\n      biject M n1 m2.\n  Proof.\n    intros M m1 b1 ofs bytes1 n1 m2 [] Hstore Hf.\n    constructor; auto.\n    - erewrite nextblock_storebytes; eauto.\n    - eapply storebytes_unmapped_inject in Hstore; eauto.\n      by eapply embedding_meminj_none.\n    - exploit storebytes_outside_inject; eauto.\n      intros b' ofs' _ H _ _.\n      apply meminj_embedding_some in H.\n      apply M in H.\n      congruence.\n  Qed.\n\n\n  (** Auxiliary lemma: [storebytes] when a list of values to store is empty *)\n  Lemma storebytes_outside_biject_nil:\n    forall M (m1 m2 : mem) (b : Values.block)\n           (ofs : Z) (m2' : mem),\n      biject M m1 m2 ->\n      storebytes m2 b ofs nil = Some m2' ->\n      biject M m1 m2'.\n  Proof.\n    intros M m1 m2 b ofs m2' [] H0.\n    constructor; auto.\n    - erewrite nextblock_storebytes; eauto.\n    - eapply storebytes_outside_inject; eauto.\n      intros b' delta ofs' H H1 H2.\n      exploit to_meminj_delta; eauto.\n      intros. decomp. subst. simpl in *.\n      rewrite Z.add_0_r in H5 H2.\n      omega.\n    - simpl in *.\n      constructor.\n      destruct mb_inj__bwd.\n      + constructor.\n        * apply storebytes_access in H0.\n          eauto.\n          destruct mi_inj0.\n          intros. unfold perm in *.\n          by rewrite H0 in H1; eauto.\n        * intros.\n          apply to_meminj_delta in H.\n          decomp. subst.\n          apply Z.divide_0_r.\n        * intros.\n          pose proof H0 as Hperm.\n          apply storebytes_access in Hperm.\n          apply storebytes_mem_contents in H0.\n          apply to_meminj_delta in H; decomp; subst.\n          rewrite H0.\n          simpl.\n          rewrite Maps.PMap.gsident.\n          destruct mi_inj0.\n          eapply mi_memval0; eauto.\n          ** by eapply embedding_meminj_some.\n          ** unfold perm in *.\n             by rewrite -Hperm.\n    + unfold valid_block in *.\n      erewrite nextblock_storebytes; eauto.\n      intros b0 H.\n      destruct mb_inj__bwd.\n        by eapply mi_freeblocks0.\n    + intros b0 b' delta H.\n      destruct mb_inj__bwd.\n      by eapply mi_mappedblocks0; eauto.\n    + destruct mb_inj__bwd.\n      unfold meminj_no_overlap.\n      intros b1 b1' delta1 b2 b2' delta2 ofs1 ofs2 H H1 H2 H3 H4.\n      apply storebytes_access in H0.\n      unfold perm in *.\n      rewrite H0 in H3 H4.\n      eapply mi_no_overlap0; eauto.\n    + intros b0 b' delta ofs0 H H1.\n      destruct mb_inj__bwd. unfold perm in *.\n      apply storebytes_access in H0.\n        by rewrite H0 in H1; eauto.\n    + intros b1 ofs0 b2 delta k p H H1.\n      destruct mb_inj__bwd. unfold perm in *.\n      apply storebytes_access in H0.\n        by rewrite H0; eauto.\n  Qed.\n\n  (** [storebytes] into a block without preimage. *)\n  Theorem storebytes_outside_biject:\n    forall M (m1 m2 : mem) (b : Values.block)\n           (ofs : Z) (bytes2 : list Memdata.memval) (m2' : mem),\n      biject M m1 m2 ->\n\n      (forall (b' : Values.block) (ofs' : Z),\n          m_fwd M b' = Some b ->\n          perm m1 b' ofs' Cur Readable ->\n          ~ ofs <= ofs'< ofs + Z.of_nat (length bytes2) )%Z ->\n\n      storebytes m2 b ofs bytes2 = Some m2' ->\n      biject M m1 m2'.\n  Proof.\n    intros M m1 m2 b ofs bytes2 m2' H Hcond Hstore.\n    destruct bytes2; [ eapply storebytes_outside_biject_nil; eauto|].\n\n    destruct H.\n\n    constructor; auto.\n    - erewrite nextblock_storebytes; eauto.\n    - eapply storebytes_outside_inject in Hstore; eauto.\n      intros b' delta ofs' H H0 H1.\n      eapply Hcond; simpl; eauto 2.\n      + by eapply meminj_embedding_some; eauto.\n      + edestruct to_meminj_delta; eauto. subst.\n        rewrite Z.add_0_r in H1.\n        simpl in *.\n        omega.\n    - exploit storebytes_unmapped_inject; eauto.\n      destruct (m_bwd M b) eqn: Hg; auto; last by eapply embedding_meminj_none.\n      exfalso.\n      pose proof Hg as Hf.\n      apply M in Hf.\n      eapply (Hcond p ofs); eauto.\n      + apply storebytes_range_perm in Hstore.\n        eapply range_perm_inj with (delta:=0%Z) in Hstore; try by (eapply embedding_meminj_some; eapply Hg).\n        * repeat rewrite Z.add_0_r in Hstore.\n          eapply perm_read_from_writable in Hstore; eauto.\n          simpl. rewrite Zpos_P_of_succ_nat . omega.\n        * eapply mb_inj__bwd.\n      + simpl.\n        rewrite Zpos_P_of_succ_nat .\n        omega.\n  Qed.\n\n\nEnd Storebytes.\n", "meta": {"author": "sayon", "repo": "trancert", "sha": "eb5c94c75067782158522f61bdd7cc902bf74185", "save_path": "github-repos/coq/sayon-trancert", "path": "github-repos/coq/sayon-trancert/trancert-eb5c94c75067782158522f61bdd7cc902bf74185/simulations/memory/bijection/Store.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2886537452027935}}
{"text": "(* We show that the bin product of a presentable  signature with the tautological  signature\nis presentable (actually it is also true of any bin products of presentable  arities)\n\n- if a category is distributive, then the functor category  also, the\nLeft module category also and the ()-signature category as well.\n *)\n\nRequire Import UniMath.Foundations.PartD.\nRequire Import UniMath.Foundations.Propositions.\nRequire Import UniMath.Foundations.Sets.\n(* Require Import UniMath.SubstitutionSystems.FromBindingSigsToMonads_Summary. *)\nRequire Import UniMath.SubstitutionSystems.BindingSigToMonad.\nRequire Import UniMath.SubstitutionSystems.Signatures.\nRequire Import UniMath.SubstitutionSystems.SignatureCategory.\nRequire Import UniMath.SubstitutionSystems.BinProductOfSignatures.\n\nRequire Import UniMath.CategoryTheory.Core.Prelude.\nRequire Import UniMath.CategoryTheory.FunctorCategory.\nRequire Import UniMath.CategoryTheory.categories.HSET.All.\n\nRequire Import UniMath.CategoryTheory.Epis.\nRequire Import UniMath.CategoryTheory.limits.coproducts.\nRequire Import UniMath.CategoryTheory.limits.bincoproducts.\nRequire Import UniMath.CategoryTheory.limits.coproducts.\nRequire Import UniMath.CategoryTheory.limits.binproducts.\nRequire Import UniMath.CategoryTheory.limits.terminal.\nRequire Import UniMath.CategoryTheory.EpiFacts.\nRequire Import UniMath.Combinatorics.Lists.\nRequire Import UniMath.CategoryTheory.whiskering.\nRequire Import Modules.Prelims.lib.\n\n\n\nRequire Import Modules.Prelims.CoproductsComplements.\nRequire Import Modules.Signatures.Signature.\nRequire Import Modules.Signatures.SigWithStrengthToSignature.\nRequire Import Modules.Signatures.BindingSig.\nRequire Import Modules.Signatures.PresentableSignature.\nRequire Import Modules.Signatures.SignatureBinproducts.\nRequire Import Modules.Signatures.SignatureCoproduct.\nRequire Import Modules.Signatures.SignaturesColims.\nRequire Import Modules.Signatures.PresentableSignatureCoproducts.\nRequire Import Modules.Signatures.HssSignatureCommutation.\n\n\nRequire Import Modules.Prelims.LModulesBinProducts.\nRequire Import Modules.Prelims.LModulesCoproducts.\nRequire Import Modules.Prelims.BinProductComplements.\n\nRequire Import UniMath.CategoryTheory.Monads.Monads.\nRequire Import UniMath.CategoryTheory.Monads.LModules. \nRequire Import UniMath.CategoryTheory.DisplayedCats.Constructions.\n(* Require Import Modules.Signatures.FullArToRaw. *)\nOpen Scope cat.\n\n\n(* inspiré de PresentableSignatureCoproducts pour les coproduits *)\n(* TODO faire une section à part *)\n\nSection CoprodAr.\n  Context {C : category} (bp : BinProducts C) (bcp : BinCoproducts C)\n          (T : Terminal C) (cp : ∏ (I:hSet), Coproducts I C).\n\n  Local Notation PO := (BinProductObject _). Local Notation CPO := (CoproductObject _ _).\n  Let MOD R  := category_LModule (B:= C) R C.\n  Let Sig_bp := signature_BinProducts  bp.\n  Let Sig_cp I := signature_Coproducts  (cp I).\n\n  Let bpFunct :=\n    (BinProducts_functor_precat C C bp).\n  Let cpFunct (Z : hSet) :=\n    (Coproducts_functor_precat Z C C (cp Z)).\n\n  Let bpMOD (R : Monad C) :=\n    (LModule_BinProducts R bp).\n\n  Let cpMOD (R : Monad C) (Z : hSet) :=\n    (LModule_Coproducts C R (cp Z) ).\n\n\n\n  Let toSig sig :=\n    (BindingSigToSignature bp\n                           bcp T sig\n                           (cp ((BindingSigIndexhSet sig)) )).\n\n\n  (** * distributivity lifts to functor categories, left modules categories, signature category\n\nTODO move these lemmas in a different file\n   *)\nHypothesis (isDistC : ∏ (I : hSet) , bp_coprod_isDistributive bp\n                                         (cp I)).\n(* TODO déplacer ces lemms qq part *)\nLemma functor_cat_isDistributive (Z : hSet) (R : Monad C) :\n  bp_coprod_isDistributive\n    (C :=  [C,C])\n    (bpFunct)\n    (cpFunct Z)  .\nProof.\n  intros B X.\n  apply functor_iso_if_pointwise_iso.\n  intro c.\n  apply isDistC.\nDefined.\n\nLemma LMod_isDistributive_inv_laws (Z :hSet) (R : Monad C) B (X : LModule _ _) :\n  LModule_Mor_laws R (T := PO (bpMOD R (CPO (cpMOD R Z B)) X) : LModule _ _)\n                   (T' := CPO (cpMOD R Z (fun o => PO (bpMOD R _ _) )):LModule _ _)\n                   (inv_from_iso\n                           (iso_from_isDistributive _ _\n                                                    (functor_cat_isDistributive Z R )\n                                                    (fun z => (B z : LModule _ _) : functor _ _)\n                                                    (X : functor _ _))).\nProof.\n  intro c.\n  cbn.\n  repeat rewrite id_right.\n  unfold LModule_coproduct_mult_data; cbn.\n  apply iso_inv_on_right.\n  rewrite assoc.\n  apply iso_inv_on_left.\n  set (i :=   bp_coprod_mor (cpMOD R _ B)\n                            (fun o => bpMOD R _ _) (bpMOD R _ X) (cpMOD R _ _)).\n  apply  ( LModule_Mor_σ R i).\nQed.\n\nDefinition LMod_isDistributive_inv (Z :hSet) (R : Monad C) B (X : LModule _ _) :\n  LModule_Mor R\n              (PO (bpMOD R (CPO (cpMOD R Z B)) X) : LModule _ _)\n              (CPO (cpMOD R Z (fun o => PO (bpMOD R _ _) )):LModule _ _) :=\n  _ ,, LMod_isDistributive_inv_laws Z R B X.\n\nLemma LMod_isDistributive_is_inverse (Z : hSet) R B X :\n  is_inverse_in_precat\n    (bp_coprod_mor (LModule_Coproducts C R (cp Z) B)\n       (λ o : Z, LModule_BinProducts R bp (B o) X)\n       (LModule_BinProducts R bp (CPO (LModule_Coproducts C R (cp Z) B)) X)\n       (LModule_Coproducts C R (cp Z)\n          (λ o : Z, PO (LModule_BinProducts R bp (B o) X))))\n    (LMod_isDistributive_inv Z R B X).\nProof.\n    set (h := (iso_from_isDistributive _ _\n                                          (functor_cat_isDistributive Z R)\n                                          ((B : Z -> LModule _ _) : Z -> functor _ _)\n                                          ((X : LModule _ _) : functor _ _)\n                 )).\n    split; apply LModule_Mor_equiv; try apply homset_property.\n    + cbn; apply (iso_inv_after_iso h).\n    + cbn; apply (iso_after_iso_inv h).\nQed.\n\nLemma LMod_isDistributive (Z : hSet) (R : Monad C) :\n  bp_coprod_isDistributive\n    (C :=  MOD R)\n    (LModule_BinProducts R bp)\n    (LModule_Coproducts C R (cp Z) )  .\nProof.\n  intros B X.\n  eapply is_iso_qinv.\n  apply LMod_isDistributive_is_inverse.\nDefined.\n\n(* TODO : déplacer ce lemme qq part *)\nLemma Sig_isDistributive_inv_law (Z :hSet) (X : signature C) (B : Z -> signature C) :\n  is_signature_Mor  (PO (Sig_bp  (CPO (Sig_cp  Z B)) X) : signature _ )\n                   ( CPO (Sig_cp  Z (fun o => PO (Sig_bp  _ _) )):signature _)\n                   (fun R => LMod_isDistributive_inv Z R (fun z => B z R) (X R)).\nProof.\n  intros R S f.\n    set (h := fun R => (iso_from_isDistributive _ _\n                                          (functor_cat_isDistributive Z R)\n                                          (fun z => B z R : functor _ _)\n                                          ((X R : LModule _ _) : functor _ _)\n                 )).\n    apply pathsinv0.\n  apply (iso_inv_on_right _ _ _ (h R)).\n  rewrite assoc.\n  apply (iso_inv_on_left _ _ _ _ (h S)).\n  set  (i :=   bp_coprod_mor (Sig_cp _ B)\n                            (fun o => Sig_bp _ _) (Sig_bp _ X) (Sig_cp  _ _)).\n  apply pathsinv0.\n  apply (signature_Mor_ax i f) .\nQed.\n\nDefinition Sig_isDistributive_inv (Z :hSet) (X : signature C) (B : Z -> signature C) :\n  signature_Mor  (PO (Sig_bp  (CPO (Sig_cp  Z B)) X) : signature _ )\n             ( CPO (Sig_cp  Z (fun o => PO (Sig_bp  _ _) )):signature _) :=\n  _ ,, Sig_isDistributive_inv_law Z X B.\n\nLemma Sig_isDistributive_is_inverse (Z : hSet) (B : Z -> signature C) (X :signature C) :\n  is_inverse_in_precat\n    (bp_coprod_mor (Sig_cp Z B)\n       (λ o : Z, Sig_bp (B o) X)\n       (Sig_bp (CPO (Sig_cp ( Z) B)) X)\n       (Sig_cp Z (λ o : Z, PO (Sig_bp  (B o) X))))\n    (Sig_isDistributive_inv Z X B).\nProof.\n    set (h := fun R => (iso_from_isDistributive _ _\n                                          (LMod_isDistributive Z R)\n                                          (fun z => B z R  )\n                                          ((X R : LModule _ _) )\n                 )).\n    set (h' := fun R => (iso_from_isDistributive _ _\n                                          (functor_cat_isDistributive Z R)\n                                          (fun z => B z R : functor _ _)\n                                          ((X R : LModule _ _) : functor _ _)\n                 )).\n    split; apply signature_Mor_eq;   intro R; apply LModule_Mor_equiv;\n    try apply homset_property.\n    + cbn; apply (iso_inv_after_iso (h' R)).\n    + cbn; apply (iso_after_iso_inv (h' R)).\nQed.\n\nLemma Sig_isDistributive (Z : hSet)  :\n  bp_coprod_isDistributive\n    (C :=  signature_category )\n    Sig_bp\n    (Sig_cp  Z).\nProof.\n  intros B X.\n  eapply is_iso_qinv.\n  apply Sig_isDistributive_is_inverse.\nDefined.\n  (** * The product of a presentable signature with the tautological signature is presentable \n\nIt requires that the base category is distributive and that bin products\nof epimorphisms are epimorphisms in the functor category.\n\n*)\nDefinition isEpiBinProd :=\n   ∏ (X X' Y Y' : functor C C) (f : nat_trans X X') (g : nat_trans Y Y')\n                        (epif : isEpi (C :=  [C,C]) f)(epig : isEpi (C :=  [C,C]) g),\n                      isEpi (C:=[C,C]) (BinProductOfArrows _ (bpFunct _ _)\n                                                           (bpFunct _ _) f g).\n\nHypothesis\n  (epiBinProd : isEpiBinProd).\n\n\n  Context {a : signature C} .\n  Context (pres_a : isPresentable bp bcp T cp a).\n  Let Ba : BindingSig := p_sig pres_a.\n  Let I : hSet := BindingSigIndexhSet Ba.\n  Let Sa' : I -> list nat := BindingSigMap Ba.\n\n  Let Fa :  signature_Mor (sigWithStrength_to_sig (C:= C) (toSig Ba)) a := p_mor pres_a.\n  Let epiFa : ∏ (R : Monad C), (isEpi (C := [_, _]) (pr1 (Fa R))) :=\n    epi_p_mor pres_a.\n\n\n  Local Notation SIG := (Signature_category C C C).\n\n\n  (**\n[[ a_1, a_2,.. ] , [b_1, b_2, ...], ..]\nbecomes\n[[0 , a_1, a_2,.. ] , [0 , b_1, b_2, ...], ..]\n*)\n  Let b : signature _ := PO (Sig_bp a tautological_signature).\n  Definition har_binprodR_p_sig : BindingSig :=\n    make_BindingSig (BindingSigIsaset (p_sig pres_a))\n                 (λ i : BindingSigIndex (p_sig pres_a), cons 0 (BindingSigMap (p_sig pres_a) i)).\n\n  Let p_alg_ar' := sigWithStrength_to_sig (C:=C) (toSig har_binprodR_p_sig).\n\n\n  Let FuncCP :=\n    Coproducts_functor_precat  (BindingSigIndex (p_sig pres_a))\n                               C C (cp (BindingSigIndexhSet (p_sig pres_a))) .\n\n  Let FuncBP :=\n    BinProducts_functor_precat C C bp .\n\n\n\n  Let cpSig  : Coproducts I SIG\n    := Coproducts_Signature_category _ C _ _ (cp I).\n  Let bpSig  : BinProducts  SIG\n    := BinProducts_Signature_category _ C  bp _.\n\n  (* TODO : move this somewhere else *)\n  Lemma Const1Sig_isTerminal : isTerminal SIG (SignatureExamples.ConstConstSignature C C _ T).\n  Proof.\n    intro S.\n    use make_iscontr.\n    - use tpair.\n      {\n      use make_nat_trans.\n      + intro x.\n        use make_nat_trans.\n        * intro c.\n          apply TerminalArrow.\n        * intros z z' f.\n          etrans;[apply TerminalArrowUnique|]; apply pathsinv0; apply TerminalArrowUnique.\n      + intros c c' f.\n        apply nat_trans_eq; [  apply homset_property|]. \n        intro z.\n          etrans;[apply TerminalArrowUnique|]; apply pathsinv0; apply TerminalArrowUnique.\n      }\n      cbn.\n      intros X Y .\n      apply nat_trans_eq; [  apply homset_property|]. \n      intro z.\n      etrans;[apply TerminalArrowUnique|]; apply pathsinv0; apply TerminalArrowUnique. \n    - intros f.\n      apply SignatureMor_eq.\n      apply nat_trans_eq; [  apply (homset_property [C,C])|]. \n      intro z.\n      apply nat_trans_eq; [  apply homset_property|]. \n      intro z'.\n      apply TerminalArrowUnique.\n  Defined.\n\n  Definition TerminalSignature : Terminal SIG := make_Terminal _ Const1Sig_isTerminal.\n\n\n\n\n  Lemma Signature_to_signature_cons_iso n ar :\n    iso (C := SIG) ( (Arity_to_Signature bp bcp T (cons n ar)))\n        (BinProductObject _ (bpSig \n                               (precomp_option_iter_Signature bcp T n)\n                               (Arity_to_Signature bp bcp T ar)\n        )).\n  Proof.\n    apply iso_inv_from_iso.\n    revert  n.\n    pattern ar.\n    apply list_ind; clear ar.\n    - intro n.\n      cbn -[bpSig].\n      apply (BinProductWith1_iso  (TerminalSignature) (bpSig _ _)).\n    - intros n ar .\n      (* revert n. *)\n      intros HI n2.\n      apply identity_iso.\n  Defined.\n\n  \n\n\n\nDefinition har_binprodR_commute_mor_mod \n  :  iso (C := signature_category)  (p_alg_ar' )\n                ((PO (Sig_bp (sigWithStrength_to_sig (C := C) (toSig Ba)) tautological_signature) : signature C)\n                ) .\nProof.\n  unfold p_alg_ar'.\n  eapply iso_comp.\n  {\n    (* apply morphism_from_iso. *)\n    eapply iso_comp;[ apply coprod_sigs_har_iso|].\n    eapply iso_comp.\n    {\n      eapply (coprod_pw_iso (C:=signature_category) _ (Sig_cp  I _)).\n      intro o.\n      eapply iso_comp.\n      {\n        eapply (functor_on_iso (sigWithStrength_to_sig_functor)).\n        apply Signature_to_signature_cons_iso.\n      }\n      eapply (iso_comp (C := signature_category)).\n      - apply binprod_sigs_har_iso.\n      - apply BinProduct_commutative_iso.\n      (* - apply binprod_sigs_har_iso. *)\n      (* - apply binprod_sigs_har_iso. *)\n      (* (* eapply iso_comp. *) *)\n      (* - apply binprod_sigs_har_iso. *)\n      (* - apply BinProduct_commutative_iso. *)\n    }\n\n    apply (iso_from_isDistributive (C:=signature_category)).\n    apply Sig_isDistributive.\n  }\n  apply BinProduct_pw_iso.\n  - apply iso_inv_from_iso.\n    (* eapply iso_comp. *)\n    (* + eapply (functor_on_iso sigWithStrength_to_sig_functor). *)\n    (*   apply Signature_to_signature_fold_iso. *)\n    apply coprod_sigs_har_iso.\n  - apply tauto_sigs_har_iso.\nDefined.\n\n  Definition har_binprodR_p_mor  : signature_Mor p_alg_ar' b.\n    eapply (compose (C := signature_category)).\n    - apply har_binprodR_commute_mor_mod.\n    - apply BinProductOfArrows.\n      + apply Fa.\n      + apply identity.\n  Defined.\n\n  Lemma har_binprodR_epi_p_mor\n        (R : Monad C) : isEpi (C := [_,_])\n                                                     (har_binprodR_p_mor R : nat_trans _ _).\n  Proof.\n    apply (isEpi_comp ([C,C]) ((morphism_from_iso har_binprodR_commute_mor_mod\n                        : signature_Mor _ _) R : nat_trans _ _)).\n    - apply is_iso_isEpi.\n      apply is_z_iso_from_is_iso.\n      set (i := functor_on_iso (forget_Sig R) har_binprodR_commute_mor_mod).\n       apply ( (functor_on_iso_is_iso _ _ (LModule_forget_functor R C)) _ _ i).\n    - apply epiBinProd.\n      + apply epiFa.\n      + apply identity_isEpi.\n  Qed.\n\n  Definition har_binprodR_isPresentable : isPresentable bp bcp T cp b :=\n    _ ,, _ ,, har_binprodR_epi_p_mor.\n\nEnd CoprodAr.\n", "meta": {"author": "UniMath", "repo": "largecatmodules", "sha": "8cbed6c2aebc278fc1f3cb1c7373a07cd200495c", "save_path": "github-repos/coq/UniMath-largecatmodules", "path": "github-repos/coq/UniMath-largecatmodules/largecatmodules-8cbed6c2aebc278fc1f3cb1c7373a07cd200495c/Modules/Signatures/PresentableSignatureBinProdR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521105, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2886132388436676}}
{"text": "(* ************************************************************************** *)\n(*                                                                            *)\n(* Verified Flash Translation Layer                                           *)\n(*                                                                            *)\n(*                                                                            *)\n(* ************************************************************************** *)\n\n(* \n\nChangeLog: \n\n  1. we only have PMTs for log blocks. While in the previous version, every \n     block has a PMT (20140523)\n  2. alloc_block routine doesn't update BIT, because it doesn't know the new allocated\n     block is a data block or a log block  (20140523)\n*)\n\n(* ************* ************************************* *****)\n(* ftl interface *)\n\nRequire Import ListEx.\nRequire Import Monad.\nRequire Import Data.\n\nRequire Import Params.\nRequire Import Nand.\n\n(* \n\n       BFTL Flash Translation Layer (Version 0.1) \n\n  BFTL is a simplified verion of BAST[1], which is an FTL algorithm\nproposed by Jesung Kim et.al. The classic algorithm uses a mapping\ntable at the block level, while using log blocks . BAST uses simple\ntechniques to assure the consistency of FTL meta-data under unexpected\npower-loss.\n\n  We build a simplified version of BAST, called BFTL, in Coq, in order\nto verify the core algorithm of the FTL. The BFTL is runnable in Coq\nand we can test the algorithm by the command 'Eval'. But we haven't\nstarted to work on the feature of power-loss recovery yet. The\ninterface of BFTL consists of only three operations, ftl_init(),\nftl_read() and ftl_write().\n\n[1] A space-efficient flash translation layer for compact flash systems.\n  \n *)\n\nDefinition bvalid_logical_block_no (lbn: block_no) := blt_nat lbn MAX_LOGICAL_BLOCKS.\n\n(* ************* ************************************* *****)\n(* \n\n* FTL Data Structures\n\n** Block mapping table\n\n  FTL translates a logical address (lbn, page offset) to a phyiscal page number\nvia a mapping table. BFTL adopts a block-level mapping table and transfer\na logical block number into two phyiscal block numbers. One of those is a phyiscal\nblock for data, the other is for logging. Each entry in the table is a pair of \nphysical block numbers. The block mapping table is defined as a list of entries.\n\n  Two operations are provided for the block mapping table, bmt_get and bmt_update.\nBoth of them return either a value or none.\n\n*)\n\nDefinition bmt_record := prod (option block_no) (option block_no).\n\nDefinition block_mapping_table := list bmt_record.\n\nDefinition bmt_get (bmt: block_mapping_table) (lbn: block_no) : option bmt_record :=\n  list_get bmt lbn.\n\nDefinition bmt_update (bmt: block_mapping_table) (lbn: block_no) (record : bmt_record)\n     : option block_mapping_table :=\n  match record with\n    | (d, l) =>\n      (list_set bmt lbn (d, l))\n  end.\n\nDefinition bmt_len (bmt: block_mapping_table) : nat := \n  length bmt.\n\n(* \n\n** block info table\n\n  Different from the original BAST, BFTL uses a separate table to store the block \ninformation, including block state, erase counter, page mapping table in each block,\nand the programmable page. \n\n  In BFTL, a block is invalid if all pages in the block are invalid, and it could\nbe erased when needed. A block is erased if it isn't programmed after erased. A\nblock is in the state of \"used\" if it is used as a data block or a log block. The \nused state is bound with a block number that reversely links to the logical block\nnumber in the block mapping table. It is assured that any used block presents in \nthe block mapping table.\n\n  There is one page mapping table for each block in the block info table. Each \nentry of the table is the logical page offset of the logical address. For instance, \nin a log block (b0), the page mapping table is like \n         \n   [..., 1,0,1,2,2,3,1],\n\nand the pages in the block are:\n\n   [..., d0,d1,d2,d3,d4,d5,d6],\n\nthe logical address, (lbn, 2), will be translated to a physical (b0, _). \n  \n  \n*)\n\nInductive pmt_entry : Set :=\n  | pmte_empty\n  | pmte_log (off: page_off).\n\nDefinition page_mapping_table := list pmt_entry.\n\nInductive ftl_block_state : Set :=\n  | bs_invalid\n  | bs_erased\n  | bs_data (lbn: block_no)\n  | bs_log (lbn: block_no) (pmt: page_mapping_table).\n\nDefinition pmt_len (pmt: page_mapping_table) : nat :=\n  length pmt.\n\nDefinition pmt_get (pmt: page_mapping_table) (loc: page_off) : option pmt_entry :=\n  list_get pmt loc.\n\nDefinition beq_pmt_entry (pe1 pe2: pmt_entry) : bool :=\n  match pe1, pe2 with\n    | pmte_empty, pmte_empty => true\n    | pmte_log off1, pmte_log off2 => beq_nat off1 off2\n    | _, _ => false\n  end.\n\nDefinition pmt_find (pmt: page_mapping_table) (pe: pmt_entry) : option page_off := \n  list_find beq_pmt_entry pmt pe.\n\nDefinition pmt_find_rev (pmt: page_mapping_table) (pe: pmt_entry) : option page_off :=\n  list_find_rev beq_pmt_entry pmt pe.\n\nDefinition pmt_update (pmt: page_mapping_table) (loc: page_off) (off: page_off)\n   : option page_mapping_table :=\n  list_set pmt loc (pmte_log off).\n\nDefinition blank_pmt : page_mapping_table := list_repeat_list PAGES_PER_BLOCK pmte_empty.\n\nRecord block_info : Set := \n  mk_bi {\n      bi_state: ftl_block_state;\n      bi_used_pages: nat;\n      bi_erase_count: nat\n    }.\n\nDefinition bi_set_state (bi : block_info) (bi_state : ftl_block_state) : block_info :=\n  mk_bi bi_state (bi_used_pages bi) (bi_erase_count bi).\n\nDefinition block_info_table :=  list block_info.\n\nDefinition bit_get (bit: block_info_table) (b: block_no) \n     : option block_info := \n  list_get bit b.\n\nDefinition bit_update (bit: block_info_table) (b: block_no) (bi: block_info)\n      : option block_info_table := \n  list_set bit b bi.\n\n(* In FTL, a block is initialized to be 'bs_invalid' *)\nDefinition blank_bi : block_info := \n  mk_bi bs_erased 0 0.\n\n(* \n\n** Free block queue\n\nFree blocks are those not used, and each of them can be invalid or\nerased (filled with \\og{0xFF}). All the free blocks are put into a \nqueue, where a new allocated block is get from the head.\n \nThe number of free block queue is important. If it is below a certain\nnumber, mBFTL will invoke GC process to free more blocks into the\nqueue.  Since new blocks are needed in the GC process, mBFTL is\nrequired to keep the number of free blocks above a threshold.\nOtherwise, the GC process will go stuck and mBFTL will run out of\nblocks.\n\n*)\n\nDefinition block_queue := list block_no.\n\nDefinition fbq_enq (fbq : block_queue) (b : block_no) : option (block_queue) :=\n  Some (list_append fbq b).\n\nDefinition fbq_deq (fbq : block_queue) : option (prod block_no (block_queue)) := \n  match fbq with\n    | nil => None\n    | cons b fbq' => Some (b, fbq')\n  end.\n\nDefinition fbq_in (fbq: list block_no) (pbn: block_no) : bool := list_inb beq_nat fbq pbn.\n\nDefinition fbq_get (fbq: list block_no) (i: nat) : option block_no := list_get fbq i.\n\nDefinition check_block_is_full (bi: block_info) : bool :=\n  match blt_nat (bi_used_pages bi) PAGES_PER_BLOCK with \n    | true => false\n    | false => true\n  end.\n\n\nRecord FTL : Set := \n  mk_FTL {\n      ftl_bi_table: block_info_table;\n      ftl_bm_table: block_mapping_table;\n      ftl_free_blocks: block_queue\n    }.\n\nDefinition ftl_update_bit (f: FTL) (bit: block_info_table) : option FTL :=\n  ret mk_FTL bit (ftl_bm_table f) (ftl_free_blocks f).\n\nDefinition ftl_update_fbq (f: FTL) (fbq: block_queue) : option FTL :=\n  ret mk_FTL (ftl_bi_table f) (ftl_bm_table f) fbq.\n\nInductive freebq_state : Set :=\n  | fbqs_abundant\n  (* | fbqs_needgc *)\n  | fbqs_scarce.\n\n(* IMPORTANT !!! *)\nDefinition check_freebq_count (freebq: block_queue): freebq_state :=\n  match (ble_nat MIN_FREE_BLOCKS (length freebq)) with\n    | false => fbqs_scarce\n    | true => fbqs_abundant\n  end.\n\nDefinition bit_init : block_info_table :=\n  list_repeat_list BLOCKS blank_bi.\n\nDefinition bmt_init : block_mapping_table :=\n  list_repeat_list MAX_LOGICAL_BLOCKS (None, None). \n\n (* check_good_blocks (i : nat) : block_queue := *)\n (*  match i with *)\n (*    | 0 => nil *)\n (*    | S i' => cons i' (check_good_blocks i') (* we assume all blocks are flawless *) *)\n (*  end. *)\n\nDefinition fbq_init : block_queue :=\n  list_make_nat_list BLOCKS.\n\nDefinition ftl_init : FTL :=\n  mk_FTL bit_init bmt_init fbq_init.\n\n(* \nerrcode 2 : FTL inconsistent \n*)\n(*\n\n  global invariants:\n\n  pre-condition: (1) 0 <= lbn < MAX_LOGICAL_BLOCKS \n                 (2) 0 <= poff < LOGICAL_PAGES_PER_BLOCK\n\n*)\n\n(* \n  bk: the log block \n  poff: the logical page address that we are looking for\n  pgn: the next free page in the block \n \n  @return: the physical offset of the page we are looking for  \n\n*)\n\nDefinition find_page_in_log_block (bi: block_info) (off: page_off) : option page_off :=\n  match (bi_state bi) with \n    | bs_log lbn pmt => (pmt_find_rev pmt (pmte_log off))\n    | _ => None\n  end.\n\nDefinition find_empty_page_in_block (bi: block_info): option page_off :=\n  match blt_nat (bi_used_pages bi) PAGES_PER_BLOCK with \n    | true => Some (bi_used_pages bi)\n    | false => None\n  end.\n  \n(* **************************************************** \n\n   * ReadBlock/WriteBlock Operations\n*)\n\n\nDefinition read_log_block (c: chip) (bi: block_info) (pbn_log: block_no) (off: page_off) : option data :=\n  (* find the lastest log page for \"poff\" in 'bk' , return the log-location *)\n  do loc <-- (find_page_in_log_block bi off);\n\n  (* read the page from \"loc\" in pbn_log *)\n  do [d, o] <-- (nand_read_page c pbn_log loc); \n\n  (* return the data in the page *)\n  ret d.\n\nDefinition read_data_block (c: chip) (pbn_data: block_no) (off: page_off) : option data :=\n  (* read the page from \"off\" in pbn_data *)\n  do [d, o] <-- (nand_read_page c pbn_data off);\n\n  (* return the data in the page *)\n  ret d.\n\nDefinition write_data_block (c: chip) (pbn_bi: block_info) (pbn: block_no) \n           (loc: page_off) (d: data): option (prod chip block_info) := \n  (* write the data to \"pbn#loc\", return c' *)\n  do c' <-- (nand_write_page c pbn loc d init_page_oob);\n\n  (* return bi := <bi_state, used+1, ec> *)\n  let bi' := mk_bi (bi_state pbn_bi) ((bi_used_pages pbn_bi)+1) (bi_erase_count pbn_bi)  in\n\n  ret  (c', bi').\n\n(* *)\n\nDefinition bi_lbn (bi: block_info) : option block_no :=\n  match (bi_state bi) with\n    | bs_log lbn pmt => Some lbn\n    | bs_data lbn => Some lbn\n    | _ => None\n  end.\n\nDefinition bi_pm_table (bi: block_info) : option page_mapping_table :=\n  match (bi_state bi) with\n    | bs_log lbn pmt => Some pmt\n    | _ => None\n  end.\n\nDefinition write_log_block (c: chip) (pbn_bi: block_info) (pbn: block_no) \n           (off: page_off) (d: data) : option (prod chip block_info) := \n  do loc <-- (find_empty_page_in_block pbn_bi);\n  \n  do c' <-- (nand_write_page c pbn loc d init_page_oob);\n  \n  do pmt <-- bi_pm_table pbn_bi;\n\n  (* update pm_table: {loc --> off } *)\n  do pmt' <-- pmt_update pmt loc off;\n\n  do lbn <-- bi_lbn pbn_bi;\n    \n  let bi' := mk_bi (bs_log lbn pmt') ((bi_used_pages pbn_bi)+1)  (bi_erase_count pbn_bi) in\n  ret (c', bi').\n\n(* **************************************************** \n\n* Alloc_Block \n\nAllocation block routine, no GC yet. But I believe that it will be \nnot difficult to add a simple GC. \n\n*)\n\nDefinition alloc_block (c: chip) (f: FTL) : option (prod block_no (prod chip FTL)) :=\n  let bmt := ftl_bm_table f in\n  let bit := ftl_bi_table f in\n  let fbq := ftl_free_blocks f in\n  match (check_freebq_count fbq) with\n    | fbqs_abundant =>\n        do [b, fbq'] <-- fbq_deq fbq; \n        do bi_free <-- bit_get bit b;\n        match bi_state bi_free with\n          | bs_erased => \n              (* TODO:  we don't need to update bit. *)\n              do bit' <-- bit_update bit b (mk_bi bs_erased 0 (bi_erase_count bi_free));\n              ret (b, (c, (mk_FTL bit' bmt fbq')))\n          | bs_invalid => \n              do c' <-- nand_erase_block c b;\n              do bit' <-- bit_update bit b (mk_bi bs_erased 0 (1 + bi_erase_count bi_free));\n              ret (b, (c', (mk_FTL bit' bmt fbq')))\n\n          | bs_data _ => None\n\n          | bs_log _ _ => None\n        end \n  \n    | _ => None\n  end.\n\n(* **************************************************** \n\n* Auxiliary Routines for update Meta-Data \n\n*)\n\n(*  The function (bit_set_state bit pbn st) :  \n      bit{pbn->bi},  bi' = bi{bs_state:=st},  bit'{pbn->bi'}\n*)\n\nDefinition bit_set_state (bit: block_info_table) (pbn: block_no) (st: ftl_block_state) \n  : option block_info_table :=\n  do bi <-- bit_get bit pbn;\n  do bi' <-- Some (mk_bi st (bi_used_pages bi) (bi_erase_count bi));\n  do bit' <-- bit_update bit pbn bi';\n  ret bit'.\n\nDefinition bit_get_bstate (f: FTL) (pbn: block_no) : option ftl_block_state := \n  do bi <-- bit_get (ftl_bi_table f) pbn;\n  ret (bi_state bi).\n\n(* **************************************************** \n\n* Free_Block \n \nFree a unused block back to the free block queue. It doesn't erase the data until FTL\ntries to write new data into it.\n\n*)\n\nDefinition free_block (bit: block_info_table) (fbq: block_queue) (pbn: block_no)\n  : option (prod block_info_table (block_queue)) :=\n  do bi <-- bit_get bit pbn;\n  do bi' <-- Some (mk_bi bs_invalid (bi_used_pages bi) (bi_erase_count bi));\n  do bit' <-- bit_update bit pbn bi';\n  do fbq' <-- fbq_enq fbq pbn;\n  ret (bit', fbq').\n\nDefinition zero_page := (zero_data PAGE_DATA_SIZE).\n\nFixpoint merge_block_fix (c: chip) (pl_bi: block_info) (pf_bi: block_info) \n         (pd: option block_no) (pl: block_no) (pf: block_no) (* (D, L, F) *)\n         (poi: nat) (* offset *) {struct poi} : option (prod chip block_info) := \n  match poi with\n    | O => ret (c, pf_bi)\n\n    | S poi' => \n           let off := poi' in\n           (* firstly, write the pages with lower no *)\n           do [c', pf_bi'] <-- (merge_block_fix c pl_bi pf_bi pd pl pf poi');\n           match (read_log_block c' pl_bi pl off) with \n             | Some d => \n                 write_data_block c' pf_bi' pf off d\n             | None => \n               (\n                 match pd with\n                   | None => \n                       do [c'', pf_bi''] <-- write_data_block c' pf_bi' pf off zero_page;\n                       ret (c'', pf_bi'')\n                   | Some pbn_data =>\n                     do d <-- (read_data_block c' pbn_data off); (* by Inv ##11 *)\n                     do [c'', pf_bi''] <-- write_data_block c' pf_bi' pf off d;  \n                     ret (c'', pf_bi'')\n                 end\n               )\n           end\n  end.\n\nDefinition merge_block (c: chip) (f: FTL) (lbn : block_no) : option (chip * FTL) % type :=\n  do bit <-- Some (ftl_bi_table f);\n  do bmt <-- Some (ftl_bm_table f);\n  do fbq <-- Some (ftl_free_blocks f);\n  do entry_to_merge <-- bmt_get bmt lbn;\n  match entry_to_merge with\n    | (opt_bd, Some bl) =>\n      do [bf, cfx] <-- alloc_block c f;\n      do [c', f'] <-- Some cfx;\n      do bit' <-- Some (ftl_bi_table f') ;\n      do bmt' <-- Some (ftl_bm_table f');\n      do fbq' <-- Some (ftl_free_blocks f');\n\n      (* merge_block_fix *)\n      do bi_log <-- bit_get bit' bl;\n      do bi_free <-- bit_get bit' bf;\n      do [c_m, bi_new_data] <-- merge_block_fix c' bi_log bi_free opt_bd bl bf PAGES_PER_BLOCK;\n      do bmt_m <-- bmt_update bmt' lbn (Some bf, None);\n      do bit_m <-- bit_update bit' bf \n                              (bi_set_state bi_new_data (bs_data lbn));\n\n      (* free_block bl *)\n      do [bit_f, fbq_f] <-- free_block bit_m fbq' bl;\n\n      match opt_bd with\n        | None => ret (c_m, (mk_FTL bit_f bmt_m fbq_f))\n        | Some bd =>\n          (* free_block bd *)\n          do [bit_f2, fbq_f2] <-- free_block bit_f fbq_f bd;\n          ret (c_m, (mk_FTL bit_f2 bmt_m fbq_f2))\n      end\n        \n    | (_, _) => None\n\n  end.\n\n(* **************************************************** \n\n* FTL read rouine \n\n*)\n\nDefinition FTL_read (c: chip) (f: FTL) (lbn : block_no) (off: page_off) : option data := \n  let bit := ftl_bi_table f in \n  let bmt := ftl_bm_table f in \n  test bvalid_page_off off;\n  do bmt_entry <-- bmt_get bmt lbn;\n  match bmt_entry with\n    | (Some pbn_data, Some pbn_log) => \n      do pbn_log_bi <-- (bit_get bit pbn_log);\n      match (read_log_block (c: chip) pbn_log_bi (pbn_log: block_no) (off: page_off)) with\n       | Some d => ret d\n       | None =>  \n        (\n           do d <-- (read_data_block (c: chip) (pbn_data: block_no) off);\n           ret d\n        )\n      end\n\n    | (None, Some pbn_log) => \n      do pbn_log_bi <-- (bit_get bit pbn_log);\n      match (read_log_block (c: chip) pbn_log_bi (pbn_log: block_no) (off: page_off)) with\n       | Some d => ret d\n       | None => ret zero_page\n      end\n\n    | (Some pbn_data, None) => \n       do d <-- (read_data_block (c: chip) (pbn_data: block_no) off);\n       ret d\n    | (None, None) => ret zero_page\n  end.\n\nDefinition bmt_update_log (bmt: block_mapping_table) (lbn: block_no) (pbn: block_no) \n  : option block_mapping_table :=\n  do bme <-- bmt_get bmt lbn;\n  do [data, log] <-- Some bme;\n  do bme' <-- Some (data, Some pbn);\n  do bmt' <-- bmt_update bmt lbn bme';\n  ret bmt'.\n\nDefinition bmt_update_data (bmt: block_mapping_table) (lbn: block_no) (pbn: block_no) \n  : option block_mapping_table :=\n  do bme <-- bmt_get bmt lbn;\n  do [data, log] <-- Some bme;\n  do bme' <-- Some (Some pbn, log);\n  do bmt' <-- bmt_update bmt lbn bme';\n  ret bmt'.\n  \n(* **************************************************** \n\n* FTL write rouine \n\n*)\n\nDefinition FTL_write (c: chip) (f: FTL) (lbn : block_no) (poff: page_off) (d: data)\n             : option (prod chip FTL) := \n  (* aux def *)\n  test bvalid_page_off poff;\n  let bit := ftl_bi_table f in\n  let bmt := ftl_bm_table f in\n  let fbq := ftl_free_blocks f in\n  do bmt_entry <-- bmt_get bmt lbn;  (* by Inv #10. *)\n  match bmt_entry with\n    (* 1st case: {lbn -> _ ,  pbn_log}*)\n    | (opt_pbn_data, Some pbn_log) => \n      do bi_log <-- bit_get bit pbn_log; (* by Inv #1 *)\n      match (check_block_is_full bi_log) with \n\n        | true =>  \n          (* the log block is full, so we have to merge data & log *)\n          do [c', ftl'] <-- merge_block c f lbn;  (* merge preserves $1 $2 *)\n\n          (* allocate another new block for the new log block *)\n          do [pbn_log_new, pack'] <-- alloc_block c' ftl';  (* by Inv #9 *)\n          let (c_a, f_a) := (pack' : prod chip FTL) in \n          do bi_log_new <-- bit_get (ftl_bi_table f_a) pbn_log_new; (* by Inv #9 *)\n          do bi_log_new' <-- Some (bi_set_state bi_log_new (bs_log lbn blank_pmt)); (* trivial *)\n          do [c_w, bi_log_new''] <-- write_log_block c_a bi_log_new' pbn_log_new poff d; (* *)\n          do bmt_w <-- bmt_update_log (ftl_bm_table f_a) lbn pbn_log_new;\n          do bit_w <-- bit_update (ftl_bi_table f_a) pbn_log_new bi_log_new'';\n          ret (c_w, (mk_FTL bit_w bmt_w (ftl_free_blocks f_a)))\n\n        (* the log block is not full, then we write the log block directly *)\n        | false =>           \n          do [c', bi_log'] <-- write_log_block c bi_log pbn_log poff d;\n          do bit' <-- bit_update bit pbn_log bi_log';\n          ret (c', (mk_FTL bit' bmt fbq))\n      end\n\n    (* 2nd case: {lbn -> _, X} *)\n    | (_, None) =>\n        do [pbn_log, pack] <-- alloc_block c f; \n        let (c_a, f_a) := (pack : prod chip FTL) in \n        let bmt_a := ftl_bm_table f_a in\n        let bit_a := ftl_bi_table f_a in\n        let fbq_a := ftl_free_blocks f_a in\n        do bi_log <-- bit_get bit_a pbn_log;\n        do bi_log' <-- Some (bi_set_state bi_log (bs_log lbn blank_pmt));\n        do [c_w, bi_log''] <-- write_log_block c_a bi_log' pbn_log poff d;\n        do bmt_w <-- bmt_update_log bmt lbn pbn_log; \n        do bit_w <-- bit_update bit_a pbn_log bi_log'';\n        ret (c_w, (mk_FTL bit_w bmt_w fbq_a))\n  end.\n\n(*  -------------------------------------------------------------\n\n  Definitions\n\n*)\n\nDefinition check_data_block (bi: block_info) : bool :=\n  match bi_state bi with\n    | bs_data _ => true\n    | _ => false\n  end.\n\nDefinition check_log_block (bi: block_info) : bool :=\n  match bi_state bi with\n    | bs_log _ _ => true\n    | _ => false\n  end.\n\nDefinition check_used_block (bi: block_info) : bool :=\n  match bi_state bi with\n    | bs_data _ => true\n    | bs_log _ _ => true\n    | _ => false\n  end.\n\n(*  -------------------------------------------------------------\n\n  Lemmas  \n\n*)\n\nFact PBN_is_greater_than_2_LBN : \n    BLOCKS >= MIN_FREE_BLOCKS + 2 * MAX_LOGICAL_BLOCKS.\nProof.\n  simpl.\n  unfold BLOCKS.\n  omega.\nQed.\n", "meta": {"author": "vittayang", "repo": "coqnand", "sha": "dd538809cf926e04d8de9912521d4e2dfc32189e", "save_path": "github-repos/coq/vittayang-coqnand", "path": "github-repos/coq/vittayang-coqnand/coqnand-dd538809cf926e04d8de9912521d4e2dfc32189e/Bast0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2886132327848495}}
{"text": "(*\n(C) Copyright 2010, COQTAIL team\n\nProject Info: http://sourceforge.net/projects/coqtail/\n\nThis library is free software; you can redistribute it and/or modify it\nunder the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation; either version 2.1 of the License, or\n(at your option) any later version.\n\nThis library is distributed in the hope that it will be useful, but\nWITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\nor FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\nLicense for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,\nUSA.\n*)\n\nRequire Export Reals.\nRequire Export MyReals.\nRequire Export Rsequence_def Rsequence_facts Rsequence_sums_facts.\nRequire Export Rseries_def.\nRequire Import Rpser_def Rpser_sums Rpser_sums_facts Rpser_derivative.\nRequire Import Rpser_radius_facts Rpser_taylor.\nRequire Import Lra.\nRequire Import Rintegral.\nRequire Import Rseries_facts.\nRequire Import Rseries_RiemannInt.\nRequire Import Rsequence_subsequence.\nRequire Import Rtactic.\n\n(* begin hide *)\nLemma continuity_pt_eq_compat :\n  forall f g x, (exists alp, alp > 0 /\\ forall y, R_dist x y < alp -> f y = g y) ->\n  continuity_pt f x -> continuity_pt g x.\nProof.\nintros f g x [alp1 [Halp1 H1]] H.\nintros eps Heps.\ndestruct (H eps Heps) as [alp2 [Halp2 H2]].\nexists (Rmin alp1 alp2); split.\napply Rmin_pos_lt; assumption.\nintros u Hu.\nrepeat rewrite <- H1.\napply H2.\nsplit; intuition.\nunfold Rmin in * |- ; destruct Rle_dec; lra.\nrewrite R_dist_eq; assumption.\napply Rlt_le_trans with (Rmin alp1 alp2).\n  destruct Hu as [_ Hu].\n  rewrite R_dist_sym; apply Hu.\n  apply Rmin_l.\nQed.\n(* end hide *)\n\n(** ** Taylor series of ln *)\n\n(** * Taylor series of ln (1 - x) *)\n\nSection ln_minus.\n\nLet Un n :=\nmatch n with\n| 0 => 0\n| _ => - / (INR n)\nend.\n\nLemma ln_minus_cv_radius : Cv_radius_weak Un 1.\nProof.\nexists 1; intros m [n Hn]; subst m.\nunfold gt_abs_pser, gt_pser, Rseq_abs, Rseq_mult.\nrewrite pow1; rewrite Rmult_1_r.\nunfold Un; destruct n.\n  rewrite Rabs_R0; apply Rle_0_1.\n  assert (Hle : 1 <= INR (S n)).\n    rewrite S_INR.\n    pattern 1 at 1; rewrite <- Rplus_0_l.\n    apply Rplus_le_compat_r.\n    apply pos_INR.\n  rewrite Rabs_Ropp.\n  rewrite Rabs_Rinv; [|intros Hc; lra].\n  rewrite Rabs_right; [|lra].\n  apply (Rmult_le_reg_l (INR (S n))); [lra|].\n  rewrite Rinv_r; [lra|intros Hc; lra].\nQed.\n(* begin hide *)\n\nLemma sum_f_R0_Ropp_compat : forall An n, - sum_f_R0 An n = sum_f_R0 (-An)%Rseq n.\nProof.\nintros An n ; induction n.\n reflexivity.\n simpl ; rewrite Ropp_plus_distr ; rewrite IHn ; reflexivity.\nQed.\n(* end hide *)\n\nLemma ln_minus_finite_cv_radius : finite_cv_radius Un 1.\nProof.\n assert (Un_decr : Un_decreasing (- (fun n => Un (S n)))%Rseq).\n  assert (Hrew : forall n, Un (S n) = -/ INR (S n)).\n   intro ; reflexivity.\n   intro n ; unfold Rseq_opp ; repeat rewrite Hrew, Ropp_involutive.\n   apply Rle_Rinv ; intuition.\n  assert (Un_cv_0 : Un_cv (fun n : nat => - Un (S n)) 0).\n  replace (fun n : nat => Un (S n)) with (fun n => - / INR (S n)).\n  rewrite <- Ropp_involutive ;  do 2 apply Rseq_cv_opp_compat.\n  apply Rseq_cv_pos_infty_inv_compat.\n  intro M.\n  assert (lt_0_1 : (0 < 1)%nat) by auto ;\n  destruct (Rseq_poly_cv 1 lt_0_1 M) as [N HN] ;\n  exists N ; intros n n_gt_N ; apply Rlt_trans with (INR n).\n  rewrite <- pow_1 ; apply HN ; assumption.\n  intuition.\n  reflexivity.\n destruct (alternated_series (fun n => - Un (S n)) Un_decr Un_cv_0) as [l Hl].\n\n rewrite <- Rabs_R1.\n rewrite <- Rabs_Ropp.\n apply Rpser_finite_cv_radius_caracterization with l.\n unfold Pser, infinite_sum.\n intros eps eps_pos ; destruct (Hl eps eps_pos) as [N HN] ; exists (S N) ;\n intros n n_lb ; unfold R_dist.\n rewrite <- Rabs_Ropp.\n rewrite Ropp_minus_distr.\n assert (Hrew := (Rseq_pps_opp_compat Un (-1) n)) ; unfold Rseq_opp in Hrew ;\n unfold Rminus . change (-(1)) with (-1). rewrite <- Hrew.\n apply Rle_lt_trans with (R_dist (sum_f_R0 (tg_alt (fun n0 : nat => - Un (S n0))) (pred n)) l).\n right ; rewrite <- Rabs_Ropp ; unfold R_dist ; apply Rabs_eq_compat.\n clear - n_lb; induction n ; unfold tg_alt.\n inversion n_lb.\n simpl pred.\n clear ; induction n.\n  compute ; field.\n  unfold Rseq_pps, Rseq_sum in *.\n  rewrite tech5.\n  repeat rewrite Ropp_plus_distr in *.\n  rewrite <- Rplus_assoc.\n  rewrite IHn.\n  unfold Rminus ; rewrite tech5.\n  repeat rewrite Rplus_assoc ; apply Rplus_eq_compat_l.\n  rewrite Rplus_comm ; apply Rplus_eq_compat_r.\n  unfold gt_pser. unfold Rseq_mult. simpl pow. ring.\n  apply HN ; intuition.\n\n intros M Hconv.\n unfold Rpser_abs in *.\n(*\n rewrite Rabs_Ropp; rewrite Rabs_R1.\n intros M Hconv.\n*) pose (fun n => match n with O => 0 | S _ => / INR n end) as An.\n apply Rseq_cv_not_infty with (sum_f_R0 An); split.\n  exists M.\n  refine (proj1 (Rser_cv_ext _ An M _) Hconv).\n  intros [|n].\n   simpl. unfold gt_abs_pser. unfold Rseq_abs. unfold gt_pser. \n   unfold Rseq_mult. simpl. rewrite Rmult_0_l. rewrite Rabs_R0. reflexivity.\n   \n   unfold Un, An.\n   unfold gt_abs_pser. unfold Rseq_abs. unfold gt_pser. \n   unfold Rseq_mult. rewrite Rabs_mult.\n   rewrite pow_1_abs.\n   rewrite Rabs_Ropp. \n   rewrite Rabs_pos_eq; [ | apply Rlt_le; apply Rinv_0_lt_compat; INR_solve].\n   ring.\n \n apply Rseq_cv_pos_infty_shift_compat.\n eapply Rseq_cv_pos_infty_eq_compat.\n  2:eapply Rseq_equiv_cv_pos_infty_compat.\n   2:apply Rseq_equiv_sym.\n   2:apply harmonic_series_equiv.\n  \n  intro n; unfold Rseq_shift.\n   induction n.\n    simpl; ring.\n    \n    rewrite tech5.\n    rewrite IHn.\n    reflexivity.\n   \n   apply Rseq_subseq_cv_pos_infty_compat with (fun n => ln (INR n)).\n    exists (exist _ _ (extractor_Rseq_iter_S 2)).\n    unfold extracted, is_extractor.\n    reflexivity.\n    \n    apply Rseq_ln_cv.\nQed.\n\nLet sum x := weaksum_r Un 1 ln_minus_cv_radius x.\n\nLemma ln_minus_taylor_sum :\n  forall x, Rabs x < 1 -> sum x = (ln (1 - x)).\nProof.\nintros x Hx.\npose (f := comp ln (fct_cte 1 - id)).\npose (df := fun u => / (1 - u) * (0 - 1)).\nassert (Hb : forall u, Rmin 0 x <= u <= Rmax 0 x -> -1 < u < 1).\n  destruct (Rabs_def2 x 1 Hx) as [Hmax Hmin].\n  intros u [Hul Hur].\n    unfold Rmin, Rmax in Hul, Hur.\n    destruct Rle_dec; split; lra.\npose (Hcv := ln_minus_cv_radius).\npose (g := weaksum_r Un 1 Hcv).\npose (dg := weaksum_r_derive Un 1 Hcv).\ndestruct Rint_derive2\n  with (f := f) (a := 0) (b := x) (d := df) as [pr HI].\n  intros u Hu.\n  apply derivable_pt_lim_comp.\n  apply derivable_pt_lim_minus.\n  apply derivable_pt_lim_const.\n  apply derivable_pt_lim_id.\n  apply derivable_pt_lim_ln.\n  apply Rgt_minus; apply (Hb u Hu).\n  intros u Hu.\n  apply continuity_pt_mult.\n  apply continuity_pt_inv.\n  apply continuity_pt_minus.\n  apply continuity_pt_const; unfold constant; auto.\n  apply derivable_continuous_pt; apply derivable_pt_id.\n  apply Rgt_not_eq; apply Rgt_minus; apply (Hb u Hu).\n  apply continuity_pt_minus.\n  apply continuity_pt_const; unfold constant; auto.\n  apply continuity_pt_const; unfold constant; auto.\nassert (Heq : forall u, -1 < u < 1 -> dg u = df u).\n  intros u [Hul Hur]; unfold df, dg.\n  replace (/ (1 - u) * (0 - 1))\n    with (- / (1 - u)) by (field; intros Hc; lra).\n  assert (Habs : Rabs u < 1).\n    unfold Rabs; destruct Rcase_abs; lra.\n  assert (Hser1 := weaksum_r_derive_sums Un 1 Hcv u Habs).\n  assert (Hser2 := GP_infinite u Habs).\n  eapply Rseq_cv_unique.\n    apply Hser1.\n    assert (Hrw : - sum_f_R0 (fun n => 1 * u ^ n) ==\n      sum_f_R0 (fun n => An_deriv Un n * u ^ n)).\n      unfold An_deriv.\n      unfold Rseq_opp; intros n; induction n.\n        simpl; unfold Rseq_shift, Rseq_mult; simpl; field.\n        simpl sum_f_R0 at 1; rewrite Ropp_plus_distr.\n        rewrite IHn.\n        simpl; apply Rplus_eq_compat_l; destruct n.\n          simpl. unfold Rseq_shift, Rseq_mult; simpl; field.\n          unfold Rseq_shift. unfold Rseq_mult. unfold Un.\n          field; assert (H := pos_INR (S n)); intros Hc. do 2 rewrite S_INR in Hc.\n          lra.\n    eapply Rseq_cv_eq_compat; unfold Rseq_pps, Rseq_sum, gt_pser. \n    erewrite <- Hrw. reflexivity. apply Rseq_cv_opp_compat; apply Hser2.\nedestruct Rint_eq_compat\n  with (f := df) (g := dg) (a := 0) (b := x) as [pr2 HI2].\n  intros u Hu.\n  apply Heq; apply Hb; assumption.\n  exists pr; apply HI.\ndestruct Rint_derive2\n  with (f := g) (a := 0) (b := x) (d := dg) as [pr3 HI3].\n  intros u Hu.\n  apply derivable_pt_lim_weaksum_r.\n  apply Hb in Hu.\n  destruct Hu as [Hul Hur].\n  unfold Rabs; destruct Rcase_abs; lra.\n  intros u Hu.\n  assert (Hu2 := Hb u Hu).\n  destruct Hu2 as [Hul Hur].\n  assert (Hct : continuity_pt df u).\n    unfold df.\n    apply continuity_pt_mult.\n    apply continuity_pt_inv; [|intros Hc; lra].\n    apply continuity_pt_minus.\n    apply continuity_pt_const; unfold constant; auto.\n    apply derivable_continuous_pt; apply derivable_pt_id.\n    apply continuity_pt_const; unfold constant; auto.\n  eapply continuity_pt_eq_compat; [|apply Hct].\n    pose (alp1 := u / 2 + / 2).\n    pose (alp2 := /2 - u / 2).\n    exists (Rmin alp1 alp2); split.\n    apply Rmin_pos_lt.\n      unfold alp1; lra.\n      unfold alp2; lra.\n    intros y Hy; symmetry.\n    apply Heq.\n    unfold alp1, alp2, R_dist, Rabs, Rmin in *.\n    destruct Rcase_abs as [Hc|Hc] in Hy;\n    destruct Rle_dec as [Hl|Hl] in Hy;\n    split; try lra;\n      try apply Rnot_le_lt in Hl; lra.\nassert (Hint : Rint dg 0 x (f x - f 0)).\n  apply Rint_eq_compat with (f := df).\n  intros u Hu.\n  apply Heq; apply Hb; assumption.\n  exists pr; assumption.\nassert (Heq_fun : g x - g 0 = f x - f 0).\n  eapply Rint_uniqueness.\n    exists pr3; assumption.\n    assumption.\nreplace (ln (1 - x)) with (weaksum_r Un 1 Hcv x).\n  unfold sum, Hcv; reflexivity.\nunfold f, g, comp, fct_cte, id, minus_fct in Heq_fun; hnf in Heq_fun.\nreplace (1 - 0) with 1 in Heq_fun by ring; rewrite ln_1 in Heq_fun.\nrewrite Rminus_0_r in Heq_fun.\nreplace (weaksum_r Un 1 Hcv 0) with 0 in Heq_fun.\nrewrite Rminus_0_r in Heq_fun; assumption.\nsymmetry.\neapply Rseq_cv_unique.\napply weaksum_r_sums; rewrite Rabs_R0; lra.\nintros eps Heps; exists 0%nat; intros n _.\nunfold Rseq_pps, gt_pser.\nrewrite sum_eq_R0.\nrewrite R_dist_eq; assumption.\nintros m _; unfold Un; destruct m.\n  unfold Rseq_mult.\n  field.\n  unfold Rseq_mult.\n  rewrite pow_ne_zero; [field|].\n    apply not_0_INR; auto.\n    auto.\nQed.\n\nLemma ln_minus_taylor :\n  forall x, Rabs x < 1 -> Pser Un x (ln (1 - x)).\nProof.\nintros x Hx.\nrewrite <- ln_minus_taylor_sum; [|assumption].\napply weaksum_r_sums; assumption.\nQed.\n\nEnd ln_minus.\n\n\n(** * Taylor series of ln (1 + x) *)\n\nSection ln_plus.\n\nLet Un n :=\nmatch n with\n| 0 => 0 \n| _ => (- 1) ^ (S n) / (INR n)\nend.\n\nLemma ln_plus_cv_radius : Cv_radius_weak Un 1.\nProof.\nexists 1; intros m [n Hn]; subst m.\nunfold gt_abs_pser, gt_pser, Rseq_abs, Rseq_mult.\nrewrite pow1; rewrite Rmult_1_r.\nunfold Un; destruct n.\n  rewrite Rabs_R0; apply Rle_0_1.\n  assert (Hle : 1 <= INR (S n)).\n    rewrite S_INR.\n    pattern 1 at 1; rewrite <- Rplus_0_l.\n    apply Rplus_le_compat_r.\n    apply pos_INR.\n  unfold Rdiv; rewrite Rabs_mult.\n  rewrite pow_1_abs; rewrite Rmult_1_l.\n  rewrite Rabs_Rinv; [|intros Hc; lra].\n  rewrite Rabs_right; [|lra].\n  apply (Rmult_le_reg_l (INR (S n))); [lra|].\n  rewrite Rinv_r; [lra|intros Hc; lra].\nQed.\n\nLet sum x := weaksum_r Un 1 ln_plus_cv_radius x.\n\nLemma ln_plus_taylor_sum :\n  forall x, Rabs x < 1 -> sum x = (ln (1 + x)).\nProof.\nintros x Hx.\nassert (Hmx : Rabs (- x) < 1).\n  rewrite Rabs_Ropp; assumption.\nreplace (1 + x) with (1 - (- x)) by ring.\neapply trans_eq; [|apply ln_minus_taylor_sum; assumption].\neapply Rseq_cv_unique.\n  apply weaksum_r_sums; assumption.\neapply Rseq_cv_eq_compat; [|apply weaksum_r_sums; assumption].\nintros n; apply sum_eq; intros i Hi; unfold Un.\nunfold gt_pser. unfold Rseq_mult.\ndestruct i; [field|].\nreplace (- x) with (- 1 * x) by ring.\nrewrite Rpow_mult_distr.\nrepeat rewrite <- tech_pow_Rmult; field.\nauto with real.\nQed.\n\nLemma ln_plus_taylor :\n  forall x, Rabs x < 1 -> Pser Un x (ln (1 + x)).\nProof.\nintros x Hx.\nrewrite <- ln_plus_taylor_sum; [|assumption].\napply weaksum_r_sums; assumption.\nQed.\n\nEnd ln_plus.\n", "meta": {"author": "coqtail", "repo": "coqtail", "sha": "96799cc6901b9cdb1c5f47add0f9cd6584fdd389", "save_path": "github-repos/coq/coqtail-coqtail", "path": "github-repos/coq/coqtail-coqtail/coqtail-96799cc6901b9cdb1c5f47add0f9cd6584fdd389/src/Reals/RTaylor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.2884090824379899}}
{"text": "(*\n  This is a dummy file for interactively observing how\n  the step_solver tactics work on a concrete program.\n  (especially that it's not getting stuck in the semantics,\n   and that the example configuration is well-formed).\n *)\n\nRequire Import himp_steps.\nRequire Import himp_syntax_sugar.\nRequire Import himp_tactics.\n\nRequire Import ZArith.\n\nLtac step_solver :=\n  econstructor (solve[simpl;eauto;equate_maps;eauto]).\n\n(*\nLtac step_solver := econstructor (solve[simpl;try reflexivity;eauto with step_hints]);idtac.\n*)\n\nGoal\n reaches kstep\n      (KCfg (kra (SWhile (BLt (EVar \"x\") (ECon 13))\n                         (Seq (SAssign \"cur\" EAlloc)\n                         (Seq (HAssign (EVar \"cur\")\n                                       (EBuild\n                                          (\"val\" s|-> KId \"x\"\n                                          :* \"next\" s|-> KId \"prev\")))\n                         (Seq (SAssign \"prev\" (EVar \"cur\"))\n                              (SAssign \"x\" (EPlus (EVar \"x\") (ECon 1)))))))\n                 kdot)\n       (\"x\" s|-> KInt 10 :* \"cur\" s|-> (KUndef undef) :* \"prev\" s|-> KInt 0 :* mapEmpty)\n       nil\n       mapEmpty\n       mapEmpty\n       1)\n      (fun c => kcell c = kdot).\n\nSet Printing Coercions.\n\ndo 40 (eapply rstep;[step_solver|]).\ndo 40 (eapply rstep;[step_solver|]).\ndo 40 (eapply rstep;[step_solver|]).\ndo 9 (eapply rstep;[step_solver|]).\napply rdone. reflexivity.\nQed.\n", "meta": {"author": "Formal-Systems-Laboratory", "repo": "coinduction", "sha": "1031da11c4a4523ea9b7347036b6bdabc7620e1d", "save_path": "github-repos/coq/Formal-Systems-Laboratory-coinduction", "path": "github-repos/coq/Formal-Systems-Laboratory-coinduction/coinduction-1031da11c4a4523ea9b7347036b6bdabc7620e1d/coinduction-proofs/himp/exec_test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.28840907444608993}}
{"text": "From mathcomp Require Import ssreflect ssrfun.\n\nRequire Import lib.utils.\n\n(* Monadic function composition *)\nDefinition opt_compose {A B C}\n                       (f : B -> option C)\n                       (g : A -> option B)\n                       : A -> option C :=\n  obind f \\o g.\nInfix \"<=<\" := opt_compose (at level 30).\nArguments opt_compose {A B C} f g / x.\n\nInfix \"$\"   := (fun f x => f x) (at level 150, left associativity).\nInfix \"<$>\" := option_map       (at level 130, left associativity).\nInfix \"=<<\" := obind            (at level 130, left associativity).\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/lib/haskell_notation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.28840907444608993}}
{"text": "Require Import Arith.Compare_dec.\nRequire Import List.\nRequire Import Map.\nRequire Import Monad.\n\nSet Implicit Arguments.\n\nModule List.\n  Import Monad.\n\n  (** List map with index *)\n  Definition mapi (A B: Type) (f: A -> nat -> B) (l: list A): list B :=\n    let fix aux (l: list A) (i: nat): list B :=\n      match l with\n      | nil => nil\n      | x :: l' => (f x i) :: (aux l' (S i))\n      end\n    in\n      aux l 0.\n\n  (** Evaluate each action in the list from left to right\n      and collect the results. *)\n  Definition do (sig: Sig.t) (T: Type) (l: list (M sig T))\n    : M sig (list T) :=\n    fold_right (fun x l' =>\n      let! x := x in\n      let! l' := l' in\n      ret (x :: l'))\n      (ret nil) l.\n\n  (** Apply an effectful function to each element of a list. *)\n  Definition iter (sig: Sig.t) (T: Type)\n    (f: T -> M sig unit) (l: list T): M sig unit :=\n    do! do (map f l) in\n    ret tt.\nEnd List.\n\n(** A data structure for arrays implemented in the monad. *)\n(* FIXME: Implement it using a more efficient data structure. *)\nModule Array.\n  Import Monad.\n\n  Definition internal_t (T: Type): Type :=\n    list T.\n\n  Definition t (sig: Sig.t) (T: Type): Type :=\n    Ref.t sig (internal_t T).\n\n  (** Read a value. *)\n  Definition read (sig: Sig.t) (T: Type) (array: t sig T) (index: nat)\n    : M sig T :=\n    let! l := !array in\n    match nth_error l index with\n    | Some v => ret v\n    | None => error \"Invalid array read\"\n    end.\n\n  (** Write a value. *)\n  Definition write (sig: Sig.t) (T: Type) (array: t sig T) (index: nat) (v: T)\n    : M sig unit :=\n    let! l := !array in\n    match lt_dec index (length l) with\n    | left _ => array :=! (firstn index l ++ (v :: nil) ++ skipn (S index) l)\n    | right _ => error \"Invalid array write\"\n    end.\n\n  (** Modify an array applying a function to each element. *)\n  Definition map (sig: Sig.t) (T: Type) (array: t sig T)\n    (f: T -> nat -> M sig T): M sig unit :=\n    let! l := !array in\n    let! l := List.do (List.mapi f l) in\n    array :=! l.\n\n  (** Convert to a persistent list. *)\n  Definition to_list (sig: Sig.t) (T: Type) (array: t sig T)\n    : M sig (list T) :=\n    !array.\nEnd Array.\n\n(** An mutable associative data structure. *)\nModule Hash (Map: IMap).\n  Import Monad.\n\n  Definition internal_t (T: Type): Type := Map.t T.\n\n  Definition t (sig: Sig.t) (T: Type) := Ref.t sig (internal_t T).\n\n  (** Evaluate each action in the hash table. *)\n  Definition do (sig: Sig.t) (T: Type) (map: internal_t (M sig T))\n    : M sig (internal_t T) :=\n    Map.fold (fun k x map' =>\n      let! x := x in\n      let! map' := map' in\n      ret (Map.add k x map'))\n      map (ret (Map.empty _)).\n\n  (** Read a value. *)\n  Definition read (sig: Sig.t) (T: Type) (hash: t sig T)\n    (key: Map.key): M sig T :=\n    let! map := !hash in\n    match Map.find key map with\n    | None => error \"Hash read: not found\"\n    | Some v => ret v\n    end.\n\n  (** Write a value. *)\n  Definition write (sig: Sig.t) (T: Type) (hash: t sig T)\n    (key: Map.key) (value: T): M sig unit :=\n    let! map := !hash in\n    match Map.find key map with\n    | None => error \"Hash write: not found\"\n    | Some _ => hash :=! Map.add key value map\n    end.\n\n  (** Iterate a function over each element. *)\n  Definition iter (sig: Sig.t) (T: Type) (hash: t sig T)\n    (f: Map.key -> T -> M sig unit): M sig unit :=\n    let! map := !hash in\n    do! do (Map.mapi f map) in\n    ret tt.\n\n  (** Convert to a persistent map. *)\n  Definition to_map (sig: Sig.t) (T: Type) (hash: t sig T)\n    : M sig (Map.t T) :=\n    !hash.\nEnd Hash.\n", "meta": {"author": "clarus", "repo": "cybele", "sha": "1843e4a181f854717b2820085089582acdc50525", "save_path": "github-repos/coq/clarus-cybele", "path": "github-repos/coq/clarus-cybele/cybele-1843e4a181f854717b2820085089582acdc50525/theories/DataStructures.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.28840907444608993}}
{"text": "(** * A variant of the [Comp] monad laws using [apply] *)\nRequire Import Coq.Strings.String Coq.Sets.Ensembles.\nRequire Import Fiat.Common.\nRequire Import Fiat.Computation.Core Fiat.Computation.Monad Fiat.Computation.SetoidMorphisms.\n\n(** ** Helper monad laws, on the left side of a [refine] *)\n\nSection monad.\n  Local Ltac t := intro H; autorewrite with refine_monad; exact H.\n\n  Lemma refine_bind_bind_helper X Y Z (f : X -> Comp Y) (g : Y -> Comp Z) x y\n  : refine (Bind x (fun u => Bind (f u) g)) y\n    -> refine (Bind (Bind x f) g) y.\n  Proof. t. Qed.\n\n  Lemma refine_bind_unit_helper X Y (f : X -> Comp Y) x y\n  : refine (f x) y\n    -> refine (Bind (Return x) f) y.\n  Proof. t. Qed.\n\n  Lemma refine_unit_bind_helper X (x : Comp X) y\n  : refine x y\n    -> refine (Bind x (@Return X)) y.\n  Proof. t. Qed.\n\n  (** XXX This is a terribly ugly tactic that should be improved *)\n  Local Ltac t2 :=\n    unfold refine; intros;\n    specialize_all_ways;\n    computes_to_inv; eauto;\n    computes_to_econstructor; eauto.\n\n  Lemma refine_under_bind_helper X Y (f f' : X -> Comp Y) x x' y\n  : (forall y, refine x y -> refine x' y)\n    -> (forall x0 y, refine (f x0) y -> refine (f' x0) y)\n    -> refine (Bind x f) y\n    -> refine (Bind x' f') y.\n  Proof. t2. Qed.\n\n  Lemma refine_under_bind_helper_1 X Y (f : X -> Comp Y) x x' y\n  : (forall y, refine x y -> refine x' y)\n    -> refine (Bind x f) y\n    -> refine (Bind x' f) y.\n  Proof. t2. Qed.\n\n  Lemma refine_under_bind_helper_2 X Y (f f' : X -> Comp Y) x y\n  : (forall x0 y, refine (f x0) y -> refine (f' x0) y)\n    -> refine (Bind x f) y\n    -> refine (Bind x f') y.\n  Proof. t2. Qed.\nEnd monad.\n\nLtac simplify_with_applied_monad_laws :=\n  progress repeat first [ apply refine_bind_unit_helper\n                        | apply refine_unit_bind_helper\n                        | apply refine_bind_bind_helper\n                        | eapply refine_under_bind_helper; [ let H := fresh in\n                                                             intros ? H;\n                                                               simplify_with_applied_monad_laws;\n                                                               exact H\n                                                           | let H := fresh in\n                                                             intros ? ? H;\n                                                               simplify_with_applied_monad_laws;\n                                                               exact H\n                                                           | ]\n                        | eapply refine_under_bind_helper_1; [ let H := fresh in\n                                                               intros ? H;\n                                                                 simplify_with_applied_monad_laws;\n                                                                 exact H\n                                                             | ]\n                        | eapply refine_under_bind_helper_2; [ let H := fresh in\n                                                               intros ? ? H;\n                                                                 simplify_with_applied_monad_laws;\n                                                                 exact H\n                                                             | ] ].\n\nTactic Notation \"simplify\" \"with\" \"monad\" \"laws\" :=\n  simplify_with_applied_monad_laws.\n\n(* Ideally we would throw refineEquiv_under_bind in here as well, but it gets stuck *)\n\nTactic Notation \"autorewrite\" \"with\" \"monad\" \"laws\" :=\n  repeat first [ setoid_rewrite refineEquiv_bind_bind\n               | setoid_rewrite refineEquiv_bind_unit\n               | setoid_rewrite refineEquiv_unit_bind].\n\nLtac interleave_autorewrite_refine_monad_with tac :=\n  repeat first [ reflexivity\n               | progress tac\n               | progress autorewrite with refine_monad\n               (*| rewrite refine_bind_bind'; progress tac\n               | rewrite refine_bind_unit'; progress tac\n               | rewrite refine_unit_bind'; progress tac\n               | rewrite <- refine_bind_bind; progress tac\n               | rewrite <- refine_bind_unit; progress tac\n               | rewrite <- refine_unit_bind; progress tac ]*)\n               | rewrite <- !refineEquiv_bind_bind; progress tac\n               | rewrite <- !refineEquiv_bind_unit; progress tac\n               | rewrite <- !refineEquiv_unit_bind; progress tac\n               (*| rewrite <- !refineEquiv_under_bind; progress tac *)].\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/Computation/ApplyMonad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.28840907444608993}}
{"text": "\nRequire 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 ReflParam.indType.\nRequire Import SquiggleEq.substitution.\nRequire Import ReflParam.PiTypeR.\nImport ListNotations.\nOpen Scope string_scope.\n\nRequire Import ReflParam.Trecord.\nRequire Import squiggle2.\n\nSection iff.\n\n   Lemma xx (Tm Tm₂ : Set) (Tm_R : BestRel Tm Tm₂) : False.\n    set (f:= Top_squiggle2_evaln_pmtcty_RR _ _ Tm_R).\n    simpl in f.\n    destruct Tm_R as [Tm_R Rtot Rone].\n    simpl in f.\n    unfold  Top_squiggle2_evaln_pmtcty_RR in f.\n    simpl BestR in f.\n    simpl in Rtot.\n  Abort.\n\n   Variables\n      (Tm Tm₂ : Set)\n\n      (Tm_R : Tm -> Tm₂ -> Prop)\n\n      (Rtot : TotalHeteroRel Tm_R)\n\n      (elimTerm : Tm -> tmExt Tm) (elimTerm₂ : Tm₂ -> tmExt Tm₂)\n\n      (elimTerm_R : forall (a1 : Tm) (a2 : Tm₂),\n                       Tm_R a1 a2 ->\n                       Top_squiggle2_tmExt_pmtcty_RR0 Tm Tm₂ Tm_R (elimTerm a1) (elimTerm₂ a2))\n\n      (applyBtm : Tm -> Tm -> Tm) (applyBtm₂ : Tm₂ -> Tm₂ -> Tm₂)\n\n      (applyBtm_R : forall (a1 : Tm) (a2 : Tm₂),\n                       Tm_R a1 a2 ->\n                       forall (a3 : Tm) (a4 : Tm₂),\n                         Tm_R a3 a4 -> Tm_R (applyBtm a1 a3) (applyBtm₂ a2 a4)).\n\n   Section eval.\n   Variables\n      (n n₂ : nat) (n_R : Coq_Init_Datatypes_nat_pmtcty_RR0 n n₂)\n      (t : Tm) (t₂ : Tm₂) (t_R : Tm_R t t₂).\n\n   Lemma evalnUni:\n\n     Top_squiggle2_option_pmtcty_RR0 Tm Tm₂ Tm_R\n                                     (evaln _ elimTerm applyBtm n t)\n                                     (evaln _ elimTerm₂ applyBtm₂ n₂ t₂).\n\n     set (ff := proj1_sig (projT2 (dependsOnlyOnRelEvaln _ _ Tm_R))\n                          _ _ elimTerm_R _ _ applyBtm_R\n                          _ _ n_R _ _ t_R).\n  exact ff.\n   Qed.\n   End eval.\n   Variables\n      (n n₂ : nat) (n_R : Coq_Init_Datatypes_nat_pmtcty_RR0 n n₂)\n      (tl : Tm) (tl₂ : Tm₂) (tl_R : Tm_R tl tl₂)\n      (tr : Tm) (tr₂ : Tm₂) (tr_R : Tm_R tr tr₂).\n\n   Require Import squiggle3.\n   Lemma obsEqUni:\n     (obsEq _ elimTerm applyBtm (evaln _ elimTerm applyBtm) n tl tr)\n       <->\n     (obsEq _ elimTerm₂ applyBtm₂ (evaln _ elimTerm₂ applyBtm₂) n₂ tl₂ tr₂).\n   Proof.\n     set (ff := proj1_sig (projT2 (obsEqExistsAOneFreeImpl _ _ Tm_R Rtot))\n                          _ _ elimTerm_R _ _ applyBtm_R\n                          _ _ evalnUni\n                          _ _ n_R _ _ tl_R _ _ tr_R).\n  pose proof (Trecord.Rtot ff) as Ht.\n  simpl in Ht.\n  apply Prop_RSpec in Ht.\n  apply fst in Ht.\n  unfold IffRel in Ht.\n  apply tiffIff in Ht.\n  apply Ht.\n     \n  Qed.\n   \nEnd iff.\n\nCheck obsEqUni.\nPrint Assumptions obsEqUni.", "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/test-suite/iso/squiggle3Thm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.28839056639163574}}
{"text": "Require Import Software.Language.DynamicBinding.\nRequire Import Software.Language.State.\nRequire Import Software.Language.ExecutionProp.\nRequire Import Software.Language.Syntax.\nImport ObjectOrientedNotations.\n\nOpen Scope oo_scope.\n\nDefinition wf_ex (x : term) (st : state) : Prop :=\n  exists var ref at_start count first,\n      x = tvar var\n  /\\  read_sk_hd var st = tref ref\n  /\\  read_sr ref st = tcl \"NatRangeIterator\" <(tbool at_start, tnat count, tnat first)>.\n\nDefinition wf x var ref st at_start count first : Prop :=\n      x = tvar var\n  /\\  read_sk_hd var st = tref ref\n  /\\  read_sr ref st = tcl \"NatRangeIterator\" <(tbool at_start, tnat count, tnat first)>.\n\nLemma wf_implies_wf_ex:\n  forall x var ref st at_start count first,\n  wf x var ref st at_start count first ->\n  wf_ex x st.\nProof.\n  Abort.\n\nSection Specs.\n\nVariable exec_step : exec_step_relation.\n\nNotation \"t1 '/' st1 '==>' t2 '/' st2\" := (exec_step (Cexec_state t1 st1) (Cexec_state t2 st2))\n  (at level 40, st1 at level 39, t2 at level 39, format \"'[' t1 / st1 '==>' t2 / st2 ']'\").\n\nNotation \"t1 '/' st1 '==>*' t2 '/' st2\" := (multi exec_step (Cexec_state t1 st1) (Cexec_state t2 st2))\n  (at level 40, st1 at level 39, t2 at level 39, format \"'[' t1 / st1 '==>*' t2 / st2 ']'\").\n\nDefinition get_at_start : Prop :=\n  forall x var ref st at_start count first,\n  wf x var ref st at_start count first ->\n  (x # \"get_at_start\"|()|) / st ==>* (tbool at_start) / st.\n\nDefinition get_count : Prop :=\n  forall x var ref st at_start count first,\n  wf x var ref st at_start count first ->\n  (x # \"get_count\"|()|) / st ==>* (tnat count) / st.\n\nDefinition get_first : Prop :=\n  forall x var ref st at_start count first,\n  wf x var ref st at_start count first ->\n  (x # \"get_first\"|()|) / st ==>* (tnat first) / st.\n\nDefinition set_at_start : Prop :=\n  forall x var ref st at_start count first,\n  wf x var ref st at_start count first ->\n  forall val,\n  (x # \"set_at_start\"|(val)|) / st ==>* tvoid / write_sr ref (tcl \"NatRangeIterator\" <(val, tnat count, tnat first)>) st.\n\nDefinition set_count : Prop :=\n  forall x var ref st at_start count first,\n  wf x var ref st at_start count first ->\n  forall val,\n  (x # \"set_count\"|(val)|) / st ==>* tvoid / write_sr ref (tcl \"NatRangeIterator\" <(tbool at_start, val, tnat first)>) st.\n\nDefinition set_first : Prop :=\n  forall x var ref st at_start count first,\n  wf x var ref st at_start count first ->\n  forall val,\n  (x # \"set_first\"|(val)|) / st ==>* tvoid / write_sr ref (tcl \"NatRangeIterator\" <(tbool at_start, tnat count, val)>) st.\n\nDefinition off_true : Prop :=\n  forall x var ref st at_start count first,\n  wf x var ref st at_start count first ->\n  count = 0 \\/ at_start = true ->\n  (x # \"off\"|()|) / st ==>* (tbool true) / st.\n\nDefinition off_false : Prop :=\n  forall x var ref st at_start count first,\n  wf x var ref st at_start count first ->\n  lt 0 count /\\ at_start = false ->\n  (x # \"off\"|()|) / st ==>* (tbool false) / st.\n\nDefinition after_true : Prop :=\n  forall x var ref st at_start count first,\n  wf x var ref st at_start count first ->\n  count = 0 /\\ at_start = false ->\n  (x # \"after\"|()|) / st ==>* (tbool true) / st.\n\nDefinition after_false : Prop :=\n  forall x var ref st at_start count first,\n  wf x var ref st at_start count first ->\n  lt 0 count \\/ at_start = true ->\n  (x # \"after\"|()|) / st ==>* (tbool true) / st.\n\nDefinition forth_at_start : Prop :=\n  forall x var ref st at_start count first,\n  wf x var ref st at_start count first ->\n  at_start = true ->\n  (x # \"forth\"|()|) / st ==>* tvoid / write_sr ref (tcl \"NatRangeIterator\" <(tbool false, tnat count, tnat first)>) st.\n\nDefinition forth : Prop :=\n  forall x var ref st at_start count first,\n  wf x var ref st at_start count first ->\n  at_start = false ->\n  (x # \"forth\"|()|) / st ==>* tvoid / write_sr ref (tcl \"NatRangeIterator\" <(tbool at_start, tnat (count - 1), tnat (first + 1))>) st.\n\nDefinition item : Prop :=\n  forall x var ref st at_start count first,\n  wf x var ref st at_start count first ->\n  (x # \"item\"|()|) / st ==>* (tnat first) / st.\n\nEnd Specs.\n\nClose Scope oo_scope.\n\n", "meta": {"author": "jlapolla", "repo": "coq-oo", "sha": "510e5e471d06c1fa805528cff305e6a287e74686", "save_path": "github-repos/coq/jlapolla-coq-oo", "path": "github-repos/coq/jlapolla-coq-oo/coq-oo-510e5e471d06c1fa805528cff305e6a287e74686/Software/Doc/Example/Specification/Package/NatRangeIterator.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.2883808835179324}}
{"text": "From Coq Require Export ZArith NArith List String Ascii.\nFrom stdpp Require Import gmap.\nImport ListNotations.\n\nSet Implicit Arguments.\n\n(* dirty preprocessing will insert an empty string *)\nNotation \"'input' tbl _r0 r1 .. rn\" := (tbl%string, cons r1%string .. (cons rn%string nil) ..)\n  (at level 200, tbl at level 0, _r0 at level 0, r1 at level 0, rn at level 0, only parsing).\n\nDefinition example := input\n\"..#.#..#####.#.#.#.###.##.....###.##.#..###.####..#####..#....#..#..##..##\n#..######.###...####..#..#####..##..#.#####...##.#.#..#.##..#.#......#.###\n.######.###.####...#.##.##..#..#..#####.....#.#....###..#.##......#.....#.\n.#..#..##..#...##.######.####.####.#.#...#.......#..#.#.#...####.##.#.....\n.#..#...##.#.##..#...##.#.##..###.#......#.#.......#.#.#.####.###.##...#..\n...####.#..#..#.##.#....##..#.####....##...##..#...#......#.#.......#.....\n..##..####..#...#.#.#...##..#.#..###..#####........#..####......#..#\"\n\"\"\n\"#..#.\"\n\"#....\"\n\"##..#\"\n\"..#..\"\n\"..###\"\n.\n\nInductive cellstate := On | Off.\n\nDefinition foldli {A B} (f : N -> A -> B -> B) (b : B) (xs : list A) : B :=\n  fold_right (fun x go i b => go (N.succ i) (f i x b)) (fun _ b => b) xs 0%N b.\n\nDefinition _mk_table (s : string) : gmap N unit :=\n  foldli (fun i c => if (c =? \"#\")%char then insert i tt else fun m => m) empty\n    (filter (fun c => (c =? \"#\") || (c =? \".\"))%bool%char (list_ascii_of_string s)).\n\nDefinition mk_table (s : string) : N -> cellstate :=\n  let t := _mk_table s in\n  fun i => match lookup i t with\n    | None => Off\n    | Some _ => On\n    end.\n\nDefinition point : Type := Z * Z.\n\nDefinition mk_grid : list string -> list (list cellstate) :=\n  map (fun row => map (fun c => if (c =? \"#\")%char then On else Off) (list_ascii_of_string row)).\n\nDefinition shifts0 {A} (x0 : A) : list (list A -> list A) :=\n  [fun x => x; fun x => x0 :: x; fun x => x0 :: x0 :: x].\n\nDefinition shifts {A} (x0 : A) : list (list (list A) -> list (list A)) := Eval cbn in\n  List.rev' (map (fun '(f, g) x => f (g x))\n    (list_prod\n      (shifts0 [])\n      ((fun x => x) :: List.tl (map (@map _ _) (shifts0 x0))))).\n\nDefinition snocbit (i : N) (b : cellstate) :=\n  match b with\n  | On => N.succ_double i\n  | Off => N.double i\n  end.\n\nFixpoint zip_with_extend {A B C} (f : A -> B -> C) (x0 : A) (y0 : B)\n    (xs : list A) (ys : list B) : list C :=\n  match xs, ys with\n  | x :: xs, y :: ys => f x y :: zip_with_extend f x0 y0 xs ys\n  | [], _ => map (f x0) ys\n  | _, [] => map (fun x => f x y0) xs\n  end.\n\nDefinition nine (def : cellstate) (g : list (list cellstate)) : list (list N) :=\n  let zz def' := zip_with_extend (zip_with_extend snocbit def' def) [] [] in\n  snd (fold_left (fun '(def', g') z => (snocbit def' def, zz def' g' (z g))) (shifts def) (0%N, [])).\n\nDefinition step (f : N -> cellstate) '((def, g) : cellstate * list (list cellstate))\n  : cellstate * list (list cellstate) :=\n  let newdef :=\n    match def with\n    | Off => f 0%N\n    | On => f 511%N\n    end in\n  (newdef, map (map f) (nine def g)).\n\nDefinition sum_with {A} (f : A -> N) (xs : list A) : N :=\n  fold_left (fun i x => i + f x)%N xs 0%N.\n\nDefinition count '((def, g) : cellstate * list (list cellstate)) : N :=\n  match def with\n  | On => 9999999999%N (* Boo *)\n  | Off => sum_with (sum_with (fun c => match c with On => 1 | Off => 0 end)%N) g\n  end.\n\nDefinition enhance (n : N) (f : N -> cellstate)\n  : cellstate * list (list cellstate) -> cellstate * list (list cellstate) :=\n  N.iter n (step f).\n\nDefinition solve '(t, g) :=\n  let t := mk_table t in\n  let g := (Off, mk_grid g) in\n  count (enhance 2 t g).\n\n(* Compute solve example. *)\n(*\nCompute\n  let '(t, g) := example in\n  let t := mk_table t in\n  let g := (Off, mk_grid g) in\n  step t (step t g).\n*)\n\nDefinition solve2 '(t, g) :=\n  let t := mk_table t in\n  let g := (Off, mk_grid g) in\n  count (enhance 50 t g).\n\n(* Compute solve2 example. *)\n\nDefinition solve12 '(t, g) :=\n  let t := mk_table t in\n  let g := (Off, mk_grid g) in\n  (count (enhance 2 t g), count (enhance 50 t g)).\n", "meta": {"author": "Lysxia", "repo": "advent-of-coq-2021", "sha": "1416cf87898d4991fa918e8d1142f45fbde269e9", "save_path": "github-repos/coq/Lysxia-advent-of-coq-2021", "path": "github-repos/coq/Lysxia-advent-of-coq-2021/advent-of-coq-2021-1416cf87898d4991fa918e8d1142f45fbde269e9/src/aoc20.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2883808763210185}}
{"text": "Add LoadPath \"vst\".\nRequire Import msl.Coqlib2.\nRequire Import msl.log_normalize.\nRequire Import msl.eq_dec.\nRequire Import Coq.Unicode.Utf8.\nRequire Import Coq.Program.Equality.\n\nRequire Import Types.\nRequire Import Judge.\nRequire Import Subst.\nRequire Import ProgramLogic.\nRequire Import Translation.\nRequire Import Language.\nRequire Import WFLemmas.\nRequire Import SubstLemmas.\nRequire Import EvalLemmas.\nRequire Import Tactics.\nRequire Import List.\nImport ListNotations.\n\nLemma forall_p_combine :\n  forall (X Y : Type) (P : Y -> Prop) (xs : list X) (ys : list Y),\n    length xs = length ys ->\n    Forall P ys -> \n    Forall (fun xy => P (snd xy)) (combine xs ys).\nProof.\n  intros.\n  rewrite Forall_forall in *.\n  intros.\n  destruct x as [x y].\n  simpl in *.\n  pose (combine_split xs ys H).\n  specialize (H0 y).\n  apply in_combine_r in H1.\n  apply H0.\n  assumption.\nQed.\n\nLemma sub_eq_expr :\n  forall (e : expr) x x', \n    subst (subst_one x (var_e x')) e \n    = subst (fun i => if eq_dec i x then x' else i) e.\nProof.\n  induction e.\n  * reflexivity.\n  * intros. unfold subst. simpl. unfold subst_one. foo. \n  * intros.\n    unfold subst at 1.\n    unfold Subst_var_expr.\n    unfold Language.subst_expr.\n    rewrite IHe1.\n    rewrite IHe2.\n    reflexivity.\nQed.\n  \nLemma sub_eq :\n  forall (p : reft_prop) x x', \n    subst (subst_one x (var_e x')) p \n    = subst (fun i => if eq_dec i x then x' else i) p.\nProof.\n  intros.\n  induction p.\n  constructor.\n  unfold subst.\n  unfold Subst_prop, Subst_prop_var, subst_prop, subst_prop_var.\n  rewrite sub_eq_expr.\n  rewrite sub_eq_expr.\n  reflexivity.\n  unfold subst in *.\n  simpl.\n  rewrite IHp.\n  reflexivity.\n  unfold subst in *.\n  simpl.\n  rewrite IHp1.\n  rewrite IHp2.\n  reflexivity.\n  unfold subst in *.\n  simpl.\n  rewrite IHp1.\n  rewrite IHp2.\n  reflexivity.\nQed.\n\nLemma subst_vv_ty:\n  forall x x' T,\n    x <> ν ->\n    sep_ty (var_e x) T \n    |-- subst (subst_one ν x') (sep_ty (var_e x) T).\nProof.\n  intros.\n  unfold subst.\n  unfold sep_ty.\n  destruct T as [b p].\n  rewrite subst_distr_andp.\n  apply andp_derives.\n  rewrite subst_distr_andp.\n  apply andp_derives.\n  unfold sep_base.\n  unfold subst, Subst_pred, subst_pred.\n  simpl in *.\n  intro w.\n  apply exp_left.\n  intro vv.\n  rewrite <- exp_andp1.\n  apply andp_derives.\n  normalize.\n  apply (exp_right vv).\n  apply prop_right.\n  unfold subst_one. \n  destruct (eq_dec x ν).\n    congruence.\n    rewrite <- H0. reflexivity.\n  apply derives_refl.\n  intro w.\n  unfold subst at 2, Subst_pred, subst_pred.\n  repeat rewrite <- subst_ty_prop.\n  unfold subst, Subst_pred, subst_pred.\n  assert\n     ((λ i : var, eval w (subst_one ν (var_e x) i))\n      = (λ i : var,\n               eval (fun i0 => eval w (subst_one ν x' i0), hp w)\n                    (subst_one ν (var_e x) i))).\n  extensionality i.\n  unfold subst_one. \n  destruct (eq_dec i ν). \n  simpl.\n  destruct (eq_dec x ν). intuition. reflexivity.\n  destruct (eq_dec i ν). intuition. simpl.\n  destruct (eq_dec i ν). intuition. reflexivity.\n  rewrite <- H0.\n  simpl.\n  apply derives_refl.\n  normalize.\nQed.\n \nLemma vv_sub_env :\n  forall G,  \n    var_not_in ν G -> \n      (forall x,\n         sep_env G |-- subst (subst_one ν x) (sep_env G)).\nProof.\n  intro G.\n  induction G.\n  + simpl. trivial.\n  + destruct a as [b p].\n    unfold sep_env in *.\n    fold sep_env in *.\n    intro H.\n    intro e.\n    repeat rewrite subst_distr_andp.\n    apply andp_derives.\n    apply andp_derives.\n    apply subst_vv_ty.\n    unfold var_not_in in H.\n    rewrite Forall_forall in H.\n    apply H with (x := (b, p)).\n    left. reflexivity.\n    apply IHG.\n    inversion H.\n    assumption.\n    trivial.\nQed.\n\nLemma vv_sub_guards :\n  forall G Grds,\n    wf_guards G Grds -> \n      forall (x : expr),\n      sep_guards Grds |-- subst (subst_one ν x) (sep_guards Grds).\nProof.\n  intros G Grds.\n  induction Grds as [| p].\n  + simpl. trivial.\n  + intros wf x.\n    unfold sep_guards in *; fold sep_guards in *.\n    inversion wf. subst.\n    pose (wf_guards_vv_nonfree G Grds H2).\n    repeat rewrite subst_distr_andp.\n    repeat apply andp_derives.\n    rewrite subst_nonfree_prop.\n    apply derives_refl.\n    apply H1.\n    apply n.\n    trivial.\nQed.\n\nLemma subtype_interp_pred :\n  forall Γ Ξ φ φ' x b,\n    var_not_in ν Γ ->\n    wf_guards Γ Ξ -> \n    subtype Γ Ξ { ν : b | φ } { ν : b | φ' } -> \n    (sep_env Γ && sep_guards Ξ) |-- \n      sep_pred (subst (subst_one ν x) φ) --> \n      sep_pred (subst (subst_one ν x) φ').\nProof.\n  intros.\n  inversion H1. subst.\n  simpl.\n  intro.\n  rewrite <- (subst_ty_prop φ (subst_one ν x) x0).\n  rewrite <- (subst_ty_prop φ' (subst_one ν x) x0).\n  apply derives_trans with\n    (Q := subst (subst_one ν x) (sep_env Γ) x0 &&\n          subst (subst_one ν x) (sep_guards Ξ) x0).\n  apply andp_derives.\n  apply vv_sub_env; assumption.\n  apply vv_sub_guards with (G := Γ); assumption.\n  unfold subst, Subst_pred, subst_pred.\n  simpl in H5.\n  apply H5.\nQed.\n\nLemma subtype_interp :\n  forall Γ Ξ φ φ' x b,\n    var_not_in ν Γ ->\n    wf_guards Γ Ξ ->\n    subtype Γ Ξ { ν : b | φ } { ν : b | φ' } -> \n      sep_env Γ && sep_guards Ξ |-- \n              sep_ty x { ν : b | φ } --> sep_ty x { ν : b | φ' }.\nProof.\n  intros.\n  unfold sep_ty.\n  rewrite <- imp_andp_adjoint.\n  repeat apply andp_right.\n  apply andp_left2. apply andp_left1. apply andp_left1. apply derives_refl.\n  apply derives_trans with (Q := (sep_pred (subst (subst_one ν x) φ) \n                              && (sep_pred (subst (subst_one ν x) φ) \n                                 --> sep_pred (subst (subst_one ν x) φ')))).\n  apply andp_right.\n  apply andp_left2. apply andp_left1. apply andp_left2. apply derives_refl.\n  apply andp_left1. apply subtype_interp_pred with (b := b); assumption.\n  apply modus_ponens.\n  repeat apply andp_left1.\n  apply sep_env_pure.\nQed.\n\nLemma vv_sub_env_eval :\n  forall e ν x v w,\n    x <> ν -> \n    eval w (subst (subst_one ν (var_e x)) e)\n    = eval (λ i : var, eval w (subst_one ν v i), hp w) (subst (subst_one ν (var_e x)) e).\nProof.\n  induction e.\n  + intros. unfold subst, subst_one. reflexivity.\n  + intros. unfold subst, subst_one.\n    foo.\n  + intros. unfold subst, subst_one in *. \n            unfold Subst_var_expr, subst_var, Language.subst_expr.\n            simpl in *.\n            unfold Subst_var_expr in *.\n            rewrite IHe1 with (v:=v).\n            rewrite IHe2 with (v:=v).\n            reflexivity.\n            assumption.\n            assumption.\nQed.\n\nLemma vv_sub_env_prop :\n  forall p ν x v w,\n    x <> ν ->\n    sep_pred (subst (subst_one ν (var_e x)) p) w =\n    sep_pred (subst (subst_one ν (var_e x)) p)\n             (λ i : var, eval w (subst_one ν v i), hp w).\nProof.\n  intros.\n  induction p.\n  + constructor.\n  + destruct b. unfold subst, Subst_prop, subst_prop. simpl.\n    rewrite <- vv_sub_env_eval with (v := v).\n    rewrite <- vv_sub_env_eval with (v := v).\n    reflexivity.\n    assumption.\n    assumption.\n  + simpl in *. unfold subst in *. unfold imp.\n    rewrite IHp.\n    reflexivity.\n  + simpl. unfold subst, Subst_prop in *. \n    unfold andp.\n    rewrite IHp1.\n    rewrite IHp2.\n    reflexivity.\n  + simpl. unfold subst, Subst_prop in *. \n    unfold orp.\n    rewrite IHp1.\n    rewrite IHp2.\n    reflexivity.\nQed.\n\nLemma vv_sub_env_ty :\n  forall T x v,\n    x <> ν ->\n    sep_ty (var_e x) T |-- subst (subst_one ν v) (sep_ty (var_e x) T).\nProof.\n  intros.\n  unfold sep_ty in *.\n  destruct T as [b p].\n  repeat rewrite subst_distr_andp.\n  repeat apply andp_derives.\n  unfold subst. \n  unfold Subst_pred, subst_pred, subst_one.\n  unfold sep_base.\n  apply exp_left.\n  intro vv.\n  simpl.\n  intro w.\n  rewrite <- exp_andp1.\n  apply andp_derives.\n  apply prop_left.\n  intro EQ.\n  apply (exp_right vv).\n  apply prop_right.\n  destruct (eq_dec x ν). intuition. assumption.\n  trivial.\n  intro w.\n  rewrite vv_sub_env_prop with (v:= v).\n  apply derives_refl.\n  assumption.\n  trivial.\nQed.\n\nLemma subst_vv_env :\n  forall Γ,\n    var_not_in ν Γ ->\n    nonfreevars (sep_env Γ) ν.\nProof.\n  intros.\n  induction Γ.\n  + unfold nonfreevars. intro. apply derives_refl.\n  + unfold sep_env. destruct a as [x [b p]].\n    fold sep_env.\n    unfold nonfreevars.\n    intro e.\n    repeat rewrite subst_distr_andp.\n    repeat apply andp_derives.\n    apply vv_sub_env_ty.\n      unfold var_not_in in H.\n      rewrite Forall_forall in H.\n      apply (H (x, { ν : b | p })); left; reflexivity.\n    apply IHΓ.\n    inversion H.\n    assumption.\n    trivial.\nQed.\n\nLemma sep_env_base_var :\n  forall Γ x b p,\n    (x, { ν : b | p }) ∈ Γ ->\n    sep_env Γ |-- sep_base (var_e x) b.\nProof.\n  induction Γ.\n  + intros. inversion H.\n  + intros. \n    apply in_inv in H. \n    destruct a as [x' [b' p']].\n    destruct H.\n    inversion H. subst.\n    apply andp_left1.\n    apply andp_left1.\n    apply andp_left1.\n    apply andp_left1.\n    apply derives_refl.\n    unfold sep_env; fold sep_env.\n    apply andp_left1.\n    apply andp_left2.\n    apply (IHΓ _ _ p).\n    assumption.\nQed.\n\nLemma sep_env_base_val :\n  forall Γ (v : value),\n    sep_env Γ |-- sep_base v (base_of_val v).\nProof.\n  intros.\n  unfold sep_base.\n  destruct (base_of_val v), v.\n  unfold base_of_type.\n  apply (exp_right n).\n  simpl. intro. apply andp_right. apply prop_right. reflexivity.\n  apply sep_env_pure.\nQed.\n\nLemma type_interp :\n  forall Γ Ξ x T,\n    var_not_in ν Γ ->\n    expr_type Γ Ξ x T ->\n    wf_guards Γ Ξ -> \n    sep_env Γ && sep_guards Ξ |-- sep_ty x T.\nProof.\n  intros Γ Ξ x T vvnotin ET. (* [ ν b φ ]  w SE ET. *)\n  unfold sep_ty.\n  dependent induction ET.\n  {\n    intros wfg.\n    apply andp_right.\n    apply andp_right.\n    apply andp_left1. \n    apply sep_env_base_val.\n    intro w.\n    simpl.\n    apply andp_right.\n    apply prop_right.\n    unfold subst, Subst_var_expr, subst_one. simpl. foo.\n    apply andp_left1; apply sep_env_pure.\n    apply andp_left1; apply sep_env_pure.\n  }\n  {\n    intros wfg.\n    apply andp_right.\n    apply andp_right.\n  * apply andp_left1; apply sep_env_base_var with (p := φ); assumption.\n  * clear wfg.\n    apply andp_left1.\n    induction Γ.\n    + intuition.\n    + intros. \n      destruct a as [x' [ b' p' ]].\n      apply in_inv in H.\n      destruct H.\n      inversion H; subst.\n      unfold sep_env; fold sep_env.\n      apply andp_left1.\n      apply andp_left1.\n      apply andp_left1.\n      apply andp_left2.\n      solve [intuition].\n      unfold sep_env; fold sep_env.\n      apply andp_left1.\n      apply andp_left2.\n      apply IHΓ.\n      inversion vvnotin. assumption.\n      assumption.\n   * apply andp_left1; apply sep_env_pure.\n  }\n  {\n    fold (sep_ty e T) in IHET.\n    fold (sep_ty e T').\n    intro.\n    apply derives_trans with (Q := sep_env Γ && sep_guards Ξ && sep_ty e T).\n    apply andp_right.\n    apply andp_right.\n      apply andp_left1; apply derives_refl.\n      apply andp_left2; apply derives_refl.\n      apply IHET; assumption.\n    apply imp_andp_adjoint.\n    destruct T, T'. inversion H0. subst.\n    apply subtype_interp; assumption.\n  }\nQed.\n\nLemma types_interp :\n  forall Γ Ξ xs ts,\n    var_not_in ν Γ ->  \n    wf_guards Γ Ξ ->\n    tc_list Γ Ξ (combine xs ts) ->\n    sep_env Γ && sep_guards Ξ |-- sep_env (combine xs ts).\nProof.\n  intros.\n  unfold tc_list in H1.\n  rewrite Forall_forall in H1.\n  unfold sep_env.\n  induction (combine xs ts).\n  + normalize. apply andp_left1. apply sep_env_pure.\n  + destruct a. \n    fold sep_env.\n    apply andp_right.\n    apply andp_right.\n    apply type_interp with (Γ := Γ);\n      [ assumption | apply H1 with (x := (v,r)); left; reflexivity | assumption].\n    apply IHl. \n    intro. intro.\n    apply H1.\n    unfold In. right. apply H2.\n    apply andp_left1; apply sep_env_pure.\nQed.\n\nLemma funspec_nomem :\n  forall Φ p, \n    fun_not_in p Φ ->\n    Forall (fun ps => fst4 ps <> p) (sep_proc_env Φ).\nProof.\n  intros.\n  induction Φ.\n  + constructor.\n  + rewrite Forall_forall in *.\n    intros [ [[p' pr] P] Q ] mem.\n    destruct a as [p'' [s t]].\n    unfold sep_proc_env in mem. fold sep_proc_env in mem.\n    apply in_inv in mem.\n    destruct mem.\n    simpl in *.\n    unfold sep_schema in H0.\n    destruct t.\n    destruct s_ret.\n    inversion H0. subst.\n    unfold fun_not_in in H.\n    rewrite Forall_forall in H.\n    specialize (H (p', (s, {| s_formals := s_formals; s_formal_ts := s_formal_ts; s_ret := (v,r) |}))).\n    apply H.\n    left. reflexivity.\n    apply IHΦ.\n    inversion H. assumption.\n    assumption.\nQed.\n    \nLemma funspec_interp :\n  forall F f p t,\n    In (f, (p,t)) F -> In (sep_schema f p t) (sep_proc_env F).\nProof.\n  intros.\n  induction F.\n  + inversion H.\n  + destruct H. destruct a. destruct p1. inversion H. subst.\n    apply in_inv. left. reflexivity.\n    apply IHF in H.\n    unfold sep_proc_env.\n    destruct a.\n    destruct p1.\n    simpl.\n    right.\n    apply H.\nQed.\n(* Lemma sep_pred_pure : *)\n(*   forall p Q, *)\n(*     (sep_pred p && emp) && Q = sep_pred p * Q. *)\n(* Proof. *)\n(*   intros. *)\n(*   induction p. *)\n(*   simpl. *)\n(*   extensionality. *)\n(*   rewrite <- sepcon_emp at 1. *)\n(*   rewrite sepcon_comm. *)\n(*   apply pred_ext. *)\n(*   apply sepcon_derives. *)\n(*   apply prop_right. trivial. *)\n(*   apply andp_left2. apply derives_refl. *)\n  \n(*   unfold pure. *)\n(*   induction p. *)\n(*   simpl.  *)\n(*   repeat intro. *)\n(*   repeat (unfold join, Join_fun, Join_lower, Join_discrete in H0; hnf in H0). *)\n(*   destruct H0. *)\n(*   destruct a. destruct a0. destruct b. *)\n(*   unfold TT, prop in H. simpl in H. *)\n(*   unfold pure. *)\n\n(*   unfold identity. *)\n(*   hnf. *)\n(*   repeat intro. *)\n\n(*   unfold join in H0. *)\n(*   unfold Join_world in H0. *)\n(*   destruct a. *)\n(*   destruct a0. *)\n(*   destruct b.  *)\n(*   simpl in H0. *)\n(*   hnf in H0. *)\n(*   destruct H0. *)\n(*   simpl in *. *)\n(*   unfold join in *. *)\n(*   hnf in *. *)\n(*   unfold join, Join_equiv in *. *)\n(*   unfold join, Join_lower, Join_discrete in H1. *)\n(*   destruct H0 with (x := V 0). *)\n  \n\nLemma sep_ty_pure_subst :\n  forall x t θ,\n    pure (subst θ (sep_ty x t)).\nProof.\n  intros.\n  unfold pure.\n  destruct t.\n  unfold subst, sep_ty, Subst_pred, subst_pred.\n  intro w.\n  simpl.\n  apply andp_left2.\n  trivial.\nQed.\n\n(* Lemma sep_env_pure : *)\n(*   forall G, *)\n(*     pure (sep_env G). *)\n(* Proof. *)\n(*   intros. *)\n(*   unfold pure. *)\n(*   intro. intro. *)\n(*   unfold identity. *)\n(*   intros w1 w2. *)\n(*   intros. *)\n(*   apply H0. *)\n(* Qed. *)\n\n(* Lemma sep_guards_pure : *)\n(*   forall G, *)\n(*     pure (sep_guards G). *)\n(* Proof. *)\n(*   unfold pure. *)\n(*   unfold identity. *)\n(*   intros. *)\n(*   intro. *)\n(*   intro. *)\n(*   intros w1 w2. *)\n(*   intro. *)\n(*   apply H0. *)\n(* Qed. *)\n\nLemma sep_proof_skip :\n  forall Φ Ξ Γ Γ' (J : (Φ ; Γ ; Ξ) ⊢ skip_s ::: Γ'), \n    sep_proc_env Φ |- {{ sep_env Γ * sep_guards Ξ }} skip_s {{ sep_env Γ' * sep_guards Ξ }}.\nProof.\n  intros. inversion J. subst. constructor.\nQed.\n\nLemma sep_proof_assign :\n  forall Φ Ξ Γ Γ' x e (J : (Φ ; Γ ; Ξ)⊢ assign_s x e ::: Γ'), \n    wf_env Γ ->\n    wf_guards Γ Ξ ->\n    sep_proc_env Φ |- {{ sep_env Γ * sep_guards Ξ }} assign_s x e {{ sep_env Γ' * sep_guards Ξ }}.\nProof.\n  intros Φ Ξ Γ Γ' x e J wfenv wfguards.\n  inversion J. subst.\n  apply semax_frame.\n  apply semax_pre_post with (P' := (EX v : value, (eval_to e v))\n                                              && (subst_pred (subst_one x e )\n                                                             (sep_env ((x, {ν : τ | (var_e ν) .= e }) :: Γ))))\n                            (Q' := sep_env ((x,{ν : τ | (var_e ν) .= e }) :: Γ)).\n  apply andp_right.\n  unfold eval_to.\n  simpl.\n  intro w.\n  rewrite <- exp_andp1.\n  apply andp_right.\n  apply (expr_eval Γ Ξ e τ φ H7).\n  purity.\n  apply derives_trans with (Q := sep_env Γ && subst_pred (subst_one x e) (sep_env Γ)).\n  simpl. intro w.\n  rewrite subst_dom_env. \n    apply andp_right; trivial.\n    assumption.\n    split. unfold subst_one. foo.\n    intros x' x'_in.\n    unfold subst_one. destruct (eq_dec x' x). subst.\n    unfold var_in, var_not_in in *.\n    rewrite Forall_forall in *.\n    destruct x'_in.\n    apply H5 in H.\n    contradiction H. reflexivity. reflexivity.\n    unfold subst_one. destruct (eq_dec ν x); congruence.\n  apply subst_env_eq_expr with (Grds := Ξ) (φ := φ).\n  assumption.\n  apply derives_refl.\n  rewrite exp_andp1.\n  apply semax_assign with (e := e) (x := x) (P := (sep_env ((x, {ν : τ | var_e ν .= e}) :: Γ))).\n  unfold subset.\n  intros.\n  inversion H. subst.\n  apply wf_guards_nonfree with (Γ := Γ); assumption.\nQed.\n\nLemma sep_args_sub :\n  forall Γ Ξ (xs' : list var) ts' (θ : subst_t var var) xs ts,\n    length xs = length ts ->\n    xs' = subst θ xs ->\n    ts' = subst θ ts ->\n    tc_list Γ Ξ (combine xs' ts') ->\n    var_not_in ν Γ -> \n    wf_guards Γ Ξ ->\n    sep_env Γ && sep_guards Ξ |-- sep_env (subst θ (combine xs ts)).\nProof.\n  intros.\n  assert (C: subst θ (combine xs ts) =\n                      combine xs' ts').\n    rewrite H0. rewrite H1.\n    rewrite <- subst_combine with (xs := xs) (ys := ts).\n    reflexivity.\n    assumption.\n  rewrite C.\n  apply types_interp; assumption.\nQed.\n\nLemma sep_env_cons :\n  forall x t Γ,\n    sep_ty (var_e x) t * sep_env Γ |-- sep_env ((x,t) :: Γ).\nProof.\n  intros.\n  unfold sep_env at 2. fold sep_env.\n  rewrite <- sepcon_emp at 1.\n  rewrite <- sepcon_pure_andp.\n  rewrite <- sepcon_pure_andp.\n  apply sepcon_derives.\n  apply sepcon_derives.\n  apply derives_refl.\n  apply derives_refl.\n  apply derives_refl.\n  apply sep_ty_pure.\n  apply sep_env_pure.\n  unfold pure. apply andp_left1. apply sep_ty_pure.\n  apply derives_refl.\nQed.\n  \nLemma sep_env_cons_sub :\n  forall x b p θ Γ,\n    θ ν = ν -> (forall x , θ x = ν -> x = ν) ->\n    subst θ (sep_ty (var_e x) { ν : b | p }) * sep_env Γ\n    |-- sep_env ((subst θ (x,{ ν : b | p })) :: Γ).\nProof.\n  intros x b p θ Γ vv_id vv_im.\n  unfold sep_env; fold sep_env.\n  rewrite sepcon_pure_andp.\n  simpl.\n  intro w.\n  apply andp_right.\n  apply andp_derives.\n  rewrite subst_lift_assert.\n  rewrite <- subst_ty_distr. \n  unfold sep_ty. simpl.\n  apply andp_derives.\n  apply andp_derives.\n  unfold subst, Subst_var_var. apply derives_refl.\n  unfold subst. simpl.\n  rewrite subst_lift_pred. unfold subst. simpl. apply derives_refl.\n  apply derives_refl.\n  rewrite vv_id. reflexivity.\n  apply subst_vv_not_in_range.\n  intro v. split. apply vv_im. intro. rewrite H. assumption.\n  apply derives_refl.\n  apply andp_left2. apply sep_env_pure.\n  apply sep_ty_pure_subst.\n  apply sep_env_pure.\nQed.\n\nLemma sep_proof_proc_ret :\n  forall (θ : subst_t var var) x t Γ, \n    θ ν = ν -> (forall x, θ x = ν -> x = ν) ->\n    wf_type (subst θ (x,t) :: Γ) (subst θ t)  ->\n   (subst θ (sep_ty (var_e x) t)) * sep_env Γ |--\n    sep_env ((subst θ (x,t)) :: Γ).\nProof.\n  intros θ x t Γ vvid vvim wf H.\n  destruct t as [ b p ].\n  simpl in *.\n  apply sep_env_cons_sub. \n  assumption.\n  assumption.\nQed.\n\nLemma sep_proof_proc_sub :\n  forall x v θ,\n    v  = subst θ x ->\n    (forall x', θ x' = v <-> x = x') ->\n    unique_sub θ x.\nProof.\n  intros x v θ vdef subprop.\n  unfold unique_sub.\n  exists v.\n  split.\n  symmetry. apply vdef.\n  intros.\n  unfold not_free_in.\n  specialize (subprop x0).\n  destruct subprop.\n  intuition.\n  apply H.\n  symmetry.\n  intuition.\nQed.\n\nLemma sep_proof_proc_mod :\n  forall f xs x x',\n    modvars (proc_s f xs x []) x' -> x = x'.\nProof.\n  intros.\n  inversion H.\n  intuition.\n  reflexivity.\nQed.\n\nLtac wfenv_ty_t :=\n  match goal with \n    | [ X : ?x = ?a, Y : ?y = ?b, H : wf_type _ _ |- _ ] =>\n      rewrite X in H; rewrite Y in H; assumption\n    | [ H : (?x, ?y) = subst _ (_, _) |- _ ] => \n      unfold subst, Subst_prod, subst_prod in H; inversion H; wfenv_ty_t\n    | [ H : wf_env (subst ?x (?f ?z) :: ?G) |- wf_type (subst ?x (?f ?z) :: ?G) _ ]  =>\n      inversion H; destruct (f z); simpl in *; wfenv_ty_t\n  end.\n\nLemma lift_assert :\n  forall {P Q : assert} w, P |-- Q ->(P w |-- Q w).\nProof.\n  intros.\n  apply H.\nQed.\n\nLemma sep_proof_proccall :\n  forall Φ Ξ Γ Γ' f xs v (J : (Φ ; Γ ; Ξ) ⊢ proc_s f xs v [] ::: Γ'),\n    wf_env Γ ->\n    wf_guards Γ Ξ ->\n    sep_proc_env Φ |- {{ sep_env Γ * sep_guards Ξ }} proc_s f xs v [] {{ sep_env Γ' * sep_guards Ξ }}.\nProof.\n  intros until v. \n  intros J wf wfg.\n  inversion J as [ | ? ? ? ? ? p S ? ? θ θS fmem wfS wfθ \n                     ? ? ? ? retid substid wfenv wfsubty tclist\n                     | | | ]. \n  simpl in *. subst.\n  destruct S as [fxs fts [rx rt]] eqn:S_def.\n  simpl in *.\n  apply funspec_interp in fmem.\n  unfold sep_schema in fmem. \n  apply semax_pre_post with \n  (P' := ((Subst.subst θ (sep_env (combine fxs fts)))) * (sep_env Γ * sep_guards Ξ)) \n  (Q' := ((Subst.subst θ (sep_ty (var_e rx) rt))) * (sep_env Γ * sep_guards Ξ)).\n  intro w.\n  simpl.\n  rewrite <- (subst_in_env Γ).\n  rewrite sepcon_pure_andp at 1.\n2: purity.\n2: purity.\n  rewrite (sepcon_pure_andp (sep_env (subst θ (combine fxs fts)) w)). \n2: purity.\n2: purity.\n  apply andp_right.\n  pose sep_args_sub as argstc; simpl in argstc; apply argstc with (xs' := subst θ fxs) (ts' := subst θ fts).\n  inversion wfS; assumption.\n  reflexivity.\n  reflexivity.\n  assumption.\n  apply wf_env_no_vv; assumption.\n  assumption.\n  rewrite sepcon_pure_andp; try apply derives_refl; purity.\n  wfsubst θ.\n  assumption.\n  assumption.\n  rewrite subst_combine.\n  apply forall_p_combine.\n  inversion wfS; repeat rewrite <- subst_length; assumption.\n  assumption.\n  inversion wfS; assumption.\n  rewrite <- sepcon_assoc.\n  simpl.\n  intro w.\n  apply sepcon_derives.\n  pose sep_proof_proc_ret as RT; simpl in RT; apply RT.\n  apply wfθ; reflexivity.\n  apply wfθ.\n  inversion wfenv; assumption.\n  apply derives_refl.\n  apply semax_frame.\n  subst.\n  assert (A : subst θ (proc_s f fxs rx []) = proc_s f (subst θ fxs) (subst θ rx) []).\n  unfold subst at 1. simpl. reflexivity.\n  rewrite <- A.\n  apply semax_subst.\n  apply (semax_proc f (mkProc fxs rx [] p)).\n  assumption.\n  intros.\n  assert (rx = x) by \n      (apply sep_proof_proc_mod with (f:=f) (xs:= fxs); assumption).\n  subst.\n  apply sep_proof_proc_sub with (v := subst θ x).\n  reflexivity.\n  intros.\n  specialize (retid x').\n  constructor; intro; [ symmetry | idtac ]; apply retid; [ idtac | symmetry]; assumption.\n  unfold subset.\n  intros.\n  unfold nonfreevars.\n  intros.\n  assert (A : subst θ rx = x).\n    apply sep_proof_proc_mod with (f := f) (xs := subst θ fxs).\n    assumption.\n  assert (B : x <> ν).\n    inversion wfenv.\n    rewrite <- A.\n    assumption.\n  rewrite sepcon_pure_andp.\n2: purity.\n2: purity.\n  rewrite subst_distr_andp.\n  apply andp_derives.\n  simpl.\n  unfold subst, Subst_pred.\n  intro w.\n  rewrite subst_dom_env.\n    apply derives_refl.\n    assumption.\n    apply subst_one_is_disj.\n    assumption.\n    assumption.\n    inversion wfenv. rewrite <- A. assumption.\n    unfold subst_one. foo.\n  intro w.\n  rewrite subst_dom_guards with (Γ := Γ).\n  apply derives_refl.\n  assumption.\n  apply subst_one_is_disj.\n  assumption.\n  assumption.\n  inversion wfenv. rewrite <- A. assumption.\nQed.\n\nLemma subtype_same_base :\n  forall Ξ Γ b b' p p',\n    subtype Γ Ξ { ν : b | p } { ν : b' | p' } ->\n    subtype Γ Ξ { ν : b | p } { ν : b | p' }.\nProof.\n  intros.\n  inversion H.\n  subst.\n  assumption.\nQed.\n\nLemma types_interp2 :\n  forall Ξ Γ Γ', \n    wf_env Γ -> wf_guards Γ Ξ ->\n   (forall x t, (x,t) ∈ Γ' -> (exists t1, (x,t1) ∈ Γ /\\ subtype Γ Ξ t1 t)) ->\n   sep_env Γ && sep_guards Ξ |-- sep_env Γ'.\nProof.\n  intros Ξ Γ Γ' wfe wfg H.\n  induction Γ' as [| [x t]].\n  + apply andp_right. normalize. purity.\n  + unfold sep_env; fold sep_env.\n    apply andp_right.\n    apply andp_right.\n    specialize (H x t).\n    destruct H. left. reflexivity.\n    destruct t as [b p].\n    destruct x0 as [b0 p0].\n    apply derives_trans with (Q := sep_env Γ && sep_guards Ξ && sep_ty (var_e x) {ν : b | p0}).\n    apply andp_right. trivial. apply type_interp.\n    apply wf_env_no_vv.\n    exact wfe.\n    constructor.\n    destruct H. inversion H0. subst.\n    apply H.\n    exact wfg.\n    rewrite imp_andp_adjoint.\n    pose subtype_interp as ST. simpl in ST. simpl. apply ST.\n    apply wf_env_no_vv.\n    exact wfe.\n    exact wfg.\n    destruct H.\n    inversion H0; subst.\n    assumption.\n    apply IHΓ'.\n    intros x0 t0 x0mem.\n    apply H.\n    right.\n    apply x0mem.\n    purity.\nQed.\n\nLemma join_swap :\n  forall Γ1 Γ2 Γ' Ξ,\n    join_env Ξ Γ1 Γ2 Γ' <-> join_env Ξ Γ2 Γ1 Γ'.\nProof.\n  intros.\n  unfold join_env.\n  constructor.\n  intros [a [b c]].\n  split.\n  assumption.\n  split.\n  intros xt.\n  specialize (b xt).\n  rewrite and_comm.\n  apply b.\n  unfold join_var in *.\n  rewrite Forall_forall in *.\n  intros [x t].\n  intro.\n  destruct c with (x,t).\n  apply H.\n  split.\n  apply H0.\n  rewrite and_comm.\n  apply H1.\n  intros [a [b c]].\n  split.\n  assumption.\n  split.\n  intros xt.\n  specialize (b xt).\n  rewrite and_comm.\n  apply b.\n  unfold join_var in *.\n  rewrite Forall_forall in *.\n  intros [x t].\n  intro.\n  destruct c with (x,t).\n  apply H.\n  split.\n  apply H0.\n  rewrite and_comm.\n  apply H1.\nQed.\n  \nLemma join_interp :\n  forall Γ1 Γ2 Γ' Ξ ,\n    wf_env Γ1 -> wf_env Γ2 -> wf_guards Γ1 Ξ ->\n    join_env Ξ Γ1 Γ2 Γ' ->\n    (sep_env Γ1 && sep_guards Ξ) |-- sep_env Γ' && sep_guards Ξ.\nProof.\n  intros until Ξ.\n  intros wf1 wf2 wfg J.\n  apply andp_right.\n  destruct J as [wfJ [J1 J2]].\n  rewrite Forall_forall in J2.\n  unfold join_var in J2.\n  apply types_interp2.\n  assumption.\n  assumption.\n  intros x t xtmem.\n  specialize (J2 (x,t) xtmem).\n  apply J2.\n  apply andp_left2; apply derives_refl.\nQed.\n\nLemma sep_proof_if_derives :\n  forall Ξ Γ Γ1 Γ2 Γ' e t g,\n    wf_env Γ ->\n    wf_env Γ1 ->\n    wf_env Γ2 ->\n    wf_guards Γ Ξ ->\n    wf_guards Γ1 Ξ ->\n    wf_guards Γ2 Ξ ->\n    join_env Ξ Γ1 Γ2 Γ' ->\n    expr_type Γ Ξ e t ->\n    (* (Φ; Γ; not_r (e .= int_v 0) :: Ξ)⊢s1 ::: (Γ1) -> *)\n    (* (Φ; Γ; (e .= int_v 0) :: Ξ)⊢s2 ::: (Γ2) -> *)\n    sep_env Γ1 * sep_guards (g :: Ξ) |-- sep_env Γ' && sep_guards Ξ.\nProof.\n  intros until g. intros wf wf1 wf2 wfg wfg1 wfg2 joinenv et.\n  unfold sep_guards; fold sep_guards.\n  rewrite sepcon_pure_andp.\n2: purity.\n2: purity.\n  repeat rewrite <- andp_assoc.\n  apply andp_left1.\n  rewrite andp_assoc.\n  rewrite andp_comm.\n  rewrite andp_assoc.\n  apply andp_left2.\n  rewrite andp_comm.\n  apply join_interp with (Γ2 := Γ2); assumption.\nQed.\n\nLemma wf_guard_expr_type1 :\n  forall Γ Ξ e t,\n    wf_env Γ ->\n    expr_type Γ Ξ e t ->\n    wf_guard Γ (e .= int_v 1).\nProof.\n  intros.\n  split.\n  repeat constructor.\n  apply wf_expr_ty_expr with Ξ t.\n    assumption.\n  simpl. rewrite  app_nil_r.\n  apply wf_expr_ty_expr_fv with Γ Ξ t; assumption.\nQed.\n\nLemma wf_guard_expr_type2 :\n  forall Γ Ξ e t,\n    wf_env Γ ->\n    expr_type Γ Ξ e t ->\n    wf_guard Γ (e .= int_v 0).\nProof.\n  intros.\n  split.\n  repeat constructor.\n  apply wf_expr_ty_expr with Ξ t.\n    assumption.\n  simpl. rewrite  app_nil_r.\n  apply wf_expr_ty_expr_fv with Γ Ξ t; assumption.\nQed.\n\nLemma sep_proof_if :\n  forall Φ Ξ Γ Γ1 Γ2 Γ' s1 s2 e t,\n    wf_env Γ ->\n    wf_guards Γ Ξ ->\n    expr_type Γ Ξ e t ->\n    (Φ; Γ; (e .= int_v 1) :: Ξ)⊢s1 ::: (Γ1) ->\n    (Φ; Γ; (e .= int_v 0) :: Ξ)⊢s2 ::: (Γ2) ->\n    join_env Ξ Γ1 Γ2 Γ' ->\n    (wf_env Γ\n         → wf_guards Γ ((e .= int_v 1) :: Ξ)\n           → sep_proc_env Φ |- \n             {{sep_env Γ * sep_guards ((e .= int_v 1) :: Ξ)}}s1\n             {{sep_env Γ1 * sep_guards ((e .= int_v 1) :: Ξ)}}) ->\n    (wf_env Γ\n       → wf_guards Γ ((e .= int_v 0) :: Ξ)\n         → sep_proc_env Φ |- \n           {{sep_env Γ * sep_guards ((e .= int_v 0) :: Ξ)}}s2\n           {{sep_env Γ2 * sep_guards ((e .= int_v 0) :: Ξ)}}) ->\n    sep_proc_env Φ |- {{ sep_env Γ && sep_guards Ξ }} \n                        if_s e s1 s2 \n                        {{ sep_env Γ' && sep_guards Ξ }}.\nProof.\n  intros until t.\n  intros wf wfg et H1 H2 joinenv IH1 IH2.\n  assert (WF1 : wf_env Γ1).\n    apply wf_env_stmt with Φ Γ ((e .= int_v 1) :: Ξ) s1; assumption.\n  assert (WF2 : wf_env Γ2).\n    apply wf_env_stmt with Φ Γ (((e .= int_v 0)) :: Ξ) s2; assumption.\n  assert (WFG1 : wf_guards Γ1 ((e .= int_v 1) :: Ξ)).\n    apply wf_guards_stmt with Φ Γ s1. assumption. assumption.\n    apply Forall_cons. \n      apply wf_guard_expr_type1 with Ξ t; assumption. \n      assumption.\n  assert (WFG2 : wf_guards Γ2 ((e .= int_v 0) :: Ξ)).\n    apply wf_guards_stmt with Φ Γ s2. assumption. assumption.\n    apply Forall_cons. \n      apply wf_guard_expr_type2 with Ξ t; assumption. \n      assumption.\n  apply semax_if.\n  rewrite andp_comm.\n  rewrite andp_assoc.\n  rewrite andp_comm with (P := sep_guards Ξ).\n  apply semax_pre_post with (P' := sep_env Γ * sep_guards ((e .= int_v 1) :: Ξ))\n                            (Q' := sep_env Γ1 * sep_guards ((e .= int_v 1) :: Ξ)).\n  rewrite sepcon_pure_andp.\n    repeat apply andp_right.\n    apply andp_left1. apply derives_refl.\n    apply andp_left2. apply andp_left1. \n    unfold eval_to. simpl. intro. apply andp_left1. apply derives_refl.\n    apply andp_left1. purity.\n    fold sep_guards.\n    do 2 apply andp_left2. apply derives_refl.\n    apply andp_left1. purity.\n    purity.\n    apply sep_guard_pure.\n  apply sep_proof_if_derives with Γ Γ2 e t.  \n    assumption.\n    assumption.\n    assumption.\n    assumption.\n    inversion WFG1; assumption.\n    inversion WFG2; assumption.\n    assumption.\n    assumption.\n  apply IH1.\n  assumption.\n  apply Forall_cons.\n    apply wf_guard_expr_type1 with Ξ t; assumption.\n    assumption.\n  apply semax_pre_post with (P' := sep_env Γ * sep_guards ((e .= int_v 0) :: Ξ))\n                            (Q' := sep_env Γ2 * sep_guards ((e .= int_v 0) :: Ξ)).\n    rewrite sepcon_pure_andp.\n    repeat apply andp_right.\n    apply andp_left2. apply andp_left1. apply derives_refl.\n    apply andp_left1. unfold eval_to. intro. apply andp_left1. apply derives_refl.\n    apply andp_left2. purity.\n    fold sep_guards.\n    apply andp_left2. apply andp_left2. apply derives_refl.\n    apply andp_left2. purity.\n    purity.\n    apply sep_guard_pure.\n  apply sep_proof_if_derives with Γ Γ1 e t;\n    repeat first [ assumption | inversion WFG1; assumption | inversion WFG2; assumption].\n  apply join_swap. assumption.\n  apply IH2.\n  assumption.\n  apply Forall_cons.\n    apply wf_guard_expr_type2 with Ξ t; assumption.\n    assumption.\nQed.\n\nTheorem sep_proof_stmt :\n  forall Φ Ξ Γ Γ' s (J : (Φ ; Γ ; Ξ) ⊢ s ::: Γ'),\n    wf_env Γ ->\n    wf_guards Γ Ξ ->\n    sep_proc_env Φ |- {{ sep_env Γ && sep_guards Ξ }} s {{ sep_env Γ' && sep_guards Ξ }}.\nProof.\n  intros.\n  rewrite <- sepcon_pure_andp.\n  rewrite <- sepcon_pure_andp.\n  dependent induction J.\n  + apply sep_proof_skip with (Φ := Φ) (Ξ := Ξ). constructor.\n  + apply sep_proof_proccall with (Φ := Φ) (Ξ := Ξ).\n    econstructor; eauto.\n    assumption.\n    assumption.\n  + apply sep_proof_assign with (Φ := Φ) (Ξ := Ξ). \n    econstructor; eauto.\n    assumption.\n    assumption.\n  + repeat rewrite sepcon_pure_andp.\n    apply sep_proof_if with Γ1 Γ2 { ν : int_t | p }; assumption.\n    purity.\n    purity.\n    purity.\n    purity.\n  + apply semax_seq with (Q := sep_env Γ' * sep_guards Ξ).\n    apply IHJ1; assumption.\n    apply IHJ2. \n    apply wf_env_stmt with (P := Φ) (G := Γ) (X := Ξ) (s := s1); assumption.\n    apply wf_guards_stmt with (P := Φ) (G := Γ) (X := Ξ) (s := s1); assumption.\n + apply sep_env_pure.\n + apply sep_guard_pure.\n + apply sep_env_pure.\n + apply sep_guard_pure.\nQed.\n\nCorollary type_safety_stmt :\n  forall Φ Γ s, (Φ ; [] ; []) ⊢ s ::: Γ -> sep_proc_env Φ |- {{ emp }} s {{ TT }}.\nProof.\n  intros.\n  assert (wf_env nil). constructor.\n  assert (wf_guards nil nil). constructor.\n  apply semax_pre_post with (P' := sep_env nil && sep_guards nil) \n                            (Q' := sep_env Γ && sep_guards nil);\n  first [ apply sep_proof_stmt with (Φ := Φ) (Ξ := []); assumption\n        | unfold sep_guards; normalize ].\nQed.\n\nTheorem sep_proof_program :\n  forall Φ p,\n    prog_type Φ p -> semax_prog (sep_proc_env Φ) p.\nProof.\n  intros Φ p H.\n  induction H.\n  + constructor.\n    apply type_safety_stmt with Γ; assumption.\n  + assert (WFΓ : wf_env Γ).\n      inversion H.\n      pose (wf_env_stmt _ _ Γ _ body H9 H5).\n      apply w.\n    destruct pr. \n    simpl in *.\n    subst.\n    pose (@semax_procdecl_p (sep_proc_env Φ)\n                           e\n                           body\n                           (sep_schema p (seq_s body (return_s e)) S)\n                           prog) as P.\n    unfold sep_schema in P.\n    destruct S.\n    destruct s_ret.\n    simpl in *.\n    simpl in *.\n    apply P.\n    reflexivity.\n    apply funspec_nomem.\n    assumption.\n    simpl in *.\n    apply semax_pre_post with (P' := sep_env (combine s_formals s_formal_ts) && sep_guards [])\n                              (Q' := sep_env Γ && sep_guards []).\n    apply andp_right. \n      apply derives_refl. \n      unfold sep_guards. apply andp_right. normalize. purity.\n    destruct r as [ τ φ ].\n    apply derives_trans with (Q := sep_ty (subst (subst_one v e) (var_e v)) \n                                         (subst (subst_one v e) {ν : τ | φ})).\n    unfold subst, Subst_var_expr, subst_one at 1, Language.subst_expr.\n    destruct (eq_dec v v).\n    apply type_interp.\n    inversion H.\n    apply wf_env_no_vv. \n    apply WFΓ.\n    assumption.\n    constructor.\n    intuition.\n    intro.\n    rewrite subst_ty_distr. apply derives_refl.\n    inversion H.\n    clear P. clear H1.\n    inversion H3.\n    unfold subst_one.\n    destruct (eq_dec ν v). intuition. subst. reflexivity.\n    assert (NEQ : v <> ν).\n    inversion H.\n    inversion H3. assumption.\n    apply subst_vv_not_in_range_exp.\n    apply wf_expr_ty_expr_fv with (Γ := Γ) (Ξ := []) (T := subst (subst_one v e) { ν : τ | φ }).\n    apply WFΓ.\n    assumption.\n    apply sep_proof_stmt in H5.\n    apply H5.\n    inversion H.\n    apply H2.\n    constructor.\n    apply IHprog_type.\nQed.", "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/TranslationLemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2883808763210185}}
{"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 computation_preserves_lib.\n\n\nDefinition opabs_of_lib_entry {o} (e : @library_entry o) : opabs :=\n  match e with\n  | lib_abs oa _ _ _ => oa\n  end.\n\nDefinition matching_entries {o} (entry1 entry2 : @library_entry o) : Prop :=\n  matching_entry_sign (opabs_of_lib_entry entry1) (opabs_of_lib_entry entry2).\n\nFixpoint entry_in_library {o} (entry : @library_entry o) (lib : library) : Prop :=\n  match lib with\n  | [] => False\n  | entry' :: entries =>\n    entry = entry'\n    \\/\n    (~ matching_entries entry entry'\n       # entry_in_library entry entries)\n  end.\n\n(* [lib1] extends [lib0] *)\nDefinition lib_extends {o} (lib1 lib0 : @library o) : Prop :=\n  forall entry, entry_in_library entry lib0 -> entry_in_library entry lib1.\n\nDefinition in_lib {o}\n           (opabs : opabs)\n           (lib   : @library o) :=\n  exists (e : library_entry),\n    List.In e lib\n    /\\ matching_entry_sign opabs (opabs_of_lib_entry e).\n\nDefinition entry_not_in_lib {o} (e : @library_entry o) (l : @library o) :=\n  !in_lib (opabs_of_lib_entry e) l.\n\nHint Resolve matching_entry_sign_sym : slow.\n\nLemma entry_in_library_implies_in {o} :\n  forall (entry : @library_entry o) lib,\n    entry_in_library entry lib -> List.In entry lib.\nProof.\n  induction lib; auto; introv h; simpl in *.\n  repndors; subst; tcsp.\nQed.\nHint Resolve entry_in_library_implies_in : slow.\n\nLemma lib_extends_cons_implies {o} :\n  forall (e : @library_entry o) (lib lib0 : library),\n    entry_not_in_lib e lib0\n    -> lib_extends lib (e :: lib0)\n    -> lib_extends lib lib0.\nProof.\n  introv ni ext i.\n  apply ext; simpl; clear ext.\n  right; dands; auto; intro m.\n  destruct ni.\n\n  exists entry.\n  dands; eauto 3 with slow.\nQed.\n\nLemma lib_extends_refl {o} :\n  forall (lib : @library o), lib_extends lib lib.\nProof.\n  introv i; auto.\nQed.\nHint Resolve lib_extends_refl : slow.\n\nLemma entry_in_library_implies_find_entry {o} :\n  forall (lib : @library o) abs opabs vars bs rhs correct,\n    matching_entry abs opabs vars bs\n    -> entry_in_library (lib_abs opabs vars rhs correct) lib\n    -> find_entry lib abs bs = Some (lib_abs opabs vars rhs correct).\nProof.\n  induction lib; introv m e; simpl in *; tcsp.\n  destruct a.\n  repndors; repnd.\n\n  - inversion e; subst; clear e.\n    boolvar; tcsp.\n\n    + pose proof (correct_abs_proof_irrelevance _ _ _ correct correct0) as xx; subst; auto.\n\n    + apply not_matching_entry_iff in n; tcsp.\n\n  - boolvar; tcsp.\n    apply matching_entry_implies_sign in m.\n    apply matching_entry_implies_sign in m0.\n    destruct e0.\n    unfold matching_entries; simpl.\n\n    eapply matching_entry_sign_trans;[|eauto].\n    eapply matching_entry_sign_sym;auto.\nQed.\n\nLemma find_entry_some_decomp {o} :\n  forall (lib : @library o) abs bs e,\n    find_entry lib abs bs = Some e\n    <=> {lib1 : library\n         & {lib2 : library\n         & {oa : opabs\n         & {vars : list sovar_sig\n         & {rhs : SOTerm\n         & {correct : correct_abs oa vars rhs\n         & lib = lib1 ++ e :: lib2\n         # e = lib_abs oa vars rhs correct\n         # matching_entry abs oa vars bs\n         # find_entry lib1 abs bs = None }}}}}}.\nProof.\n  induction lib; introv; split; introv h; simpl in *; ginv.\n\n  - exrepnd.\n    destruct lib1; ginv.\n\n  - destruct a.\n    boolvar; ginv.\n\n    + exists ([] : @library o) lib opabs vars rhs correct; simpl.\n      dands; auto.\n\n    + apply IHlib in h; exrepnd; subst; clear IHlib.\n      exists (lib_abs opabs vars rhs correct :: lib1) lib2 oa vars0 rhs0 correct0.\n      dands; auto.\n      simpl; boolvar; auto.\n      apply not_matching_entry_iff in n; tcsp.\n\n  - exrepnd; subst.\n    destruct a.\n    destruct lib1; simpl in *; ginv.\n\n    + inversion h0; subst; clear h0.\n      pose proof (correct_abs_proof_irrelevance _ _ _ correct correct0) as xx; subst; auto.\n      boolvar; auto.\n      apply not_matching_entry_iff in n; tcsp.\n\n    + boolvar; ginv.\n      apply IHlib.\n      exists lib1 lib2 oa vars rhs correct; dands; auto.\nQed.\n\nLemma implies_entry_in_library_app_right {o} :\n  forall (lib1 lib2 : @library o) e,\n    entry_in_library e lib2\n    -> (forall e', LIn e' lib1 -> ~ matching_entries e e')\n    -> entry_in_library e (lib1 ++ lib2).\nProof.\n  induction lib1; introv h q; simpl in *; auto.\n  right; dands; auto.\nQed.\n\nLemma matching_entry_trans_right {o} :\n  forall abs1 abs2 abs3 vars1 vars2 (bs : list (@BTerm o)),\n    matching_entry abs1 abs2 vars1 bs\n    -> matching_entry abs2 abs3 vars2 bs\n    -> matching_entry abs1 abs3 vars2 bs.\nProof.\n  introv m1 m2; unfold matching_entry in *; repnd; dands; tcsp;\n    try (complete (allrw; auto)).\n  eapply matching_parameters_trans; eauto.\nQed.\n\nLemma matching_entry_sym {o} :\n  forall abs1 abs2 vars (bs : list (@BTerm o)),\n    matching_entry abs1 abs2 vars bs\n    -> matching_entry abs2 abs1 vars bs.\nProof.\n  introv m; unfold matching_entry in *; repnd; dands; tcsp;\n    try (complete (allrw; auto)).\n  apply matching_parameters_sym; auto.\nQed.\n\nLemma matching_entry_preserves_find_entry {o} :\n  forall (lib : @library o) abs1 abs2 vars bs,\n    matching_entry abs1 abs2 vars bs\n    -> find_entry lib abs1 bs = find_entry lib abs2 bs.\nProof.\n  induction lib; introv m; simpl in *; auto.\n  destruct a.\n  boolvar; auto.\n  - apply not_matching_entry_iff in n.\n    apply matching_entry_sym in m.\n    eapply matching_entry_trans_right in m0;[|exact m]; tcsp.\n  - apply not_matching_entry_iff in n.\n    eapply matching_entry_trans_right in m0;[|exact m]; tcsp.\n  - eapply IHlib; eauto.\nQed.\n\nLemma matching_entry_sign_implies_matching_entry {o} :\n  forall (abs1 abs2 : opabs) (vars : list sovar_sig) (bs : list (@BTerm o)),\n    matching_bterms vars bs\n    -> matching_entry_sign abs1 abs2\n    -> matching_entry abs1 abs2 vars bs.\nProof.\n  introv h m; unfold matching_entry_sign in m; unfold matching_entry.\n  repnd; dands; auto.\nQed.\n\nLemma matching_entry_implies_matching_bterms {o} :\n  forall (abs1 abs2 : opabs) (vars : list sovar_sig) (bs : list (@BTerm o)),\n    matching_entry abs1 abs2 vars bs\n    -> matching_bterms vars bs.\nProof.\n  introv m; unfold matching_entry in m; tcsp.\nQed.\n\nLemma correct_abs_implies_matching_sign {o} :\n  forall abs vars (t : @SOTerm o),\n    correct_abs abs vars t\n    -> matching_sign vars (opabs_sign abs).\nProof.\n  introv cor.\n  unfold correct_abs in cor; tcsp.\nQed.\n\nLemma matching_entry_sign_implies_eq_opabs_signs :\n  forall abs1 abs2,\n    matching_entry_sign abs1 abs2\n    -> opabs_sign abs1 = opabs_sign abs2.\nProof.\n  introv m; unfold matching_entry_sign in m; tcsp.\nQed.\n\nLemma find_entry_none_implies {o} :\n  forall (lib : @library o) abs bs e vars rhs correct,\n    matching_sign vars (opabs_sign abs)\n    -> matching_sign vars (map num_bvars bs)\n    -> find_entry lib abs bs = None\n    -> LIn e lib\n    -> ~ matching_entries (lib_abs abs vars rhs correct) e.\nProof.\n  induction lib; introv ms1 ms2 fe i; simpl in *; tcsp.\n  destruct a; repndors; subst; boolvar; tcsp.\n\n  - unfold matching_entries; simpl; intro h.\n    apply not_matching_entry_iff in n.\n    destruct n.\n    apply matching_entry_sign_implies_matching_entry; auto.\n    apply matching_bterms_as_matching_sign.\n    apply correct_abs_implies_matching_sign in correct0.\n    unfold matching_sign in *.\n\n    apply matching_entry_sign_implies_eq_opabs_signs in h.\n    rewrite correct0.\n    rewrite <- h.\n    rewrite <- ms1; rewrite <- ms2; auto.\n\n  - eapply IHlib; eauto.\nQed.\n\nLemma entry_in_libray_implies_find_entry_some {o} :\n  forall lib abs oa vars (t : @SOTerm o) bs correct,\n    matching_entry abs oa vars bs\n    -> entry_in_library (lib_abs oa vars t correct) lib\n    -> find_entry lib abs bs = Some (lib_abs oa vars t correct).\nProof.\n  induction lib; introv m i; simpl in *; tcsp.\n  destruct a; simpl in *.\n  repndors; repnd.\n\n  - inversion i; subst; clear i.\n    pose proof (correct_abs_proof_irrelevance _ _ _ correct correct0) as xx; subst; auto.\n    boolvar; auto.\n    apply not_matching_entry_iff in n; tcsp.\n\n  - unfold matching_entries in i0; simpl in i0.\n    boolvar; ginv.\n\n    + destruct i0.\n      eapply matching_entry_implies_sign.\n      eapply matching_entry_trans_right;[|exact m0].\n      apply matching_entry_sym;eauto.\n\n    + apply IHlib; auto.\nQed.\n\nLemma lib_extends_preserves_find_entry {o} :\n  forall (lib1 lib2 : @library o) abs bs (e : library_entry),\n    lib_extends lib2 lib1\n    -> find_entry lib1 abs bs = Some e\n    -> find_entry lib2 abs bs = Some e.\nProof.\n  introv ext fe.\n  apply find_entry_some_decomp in fe; exrepnd; subst.\n\n  pose proof (ext (lib_abs oa vars rhs correct)) as h.\n  simpl in h; autodimp h hyp.\n\n  { apply implies_entry_in_library_app_right;[simpl; tcsp|].\n    pose proof (matching_entry_preserves_find_entry lib0 abs oa vars bs) as q.\n    autodimp q hyp.\n    rewrite q in fe1; clear q.\n    applydup @matching_entry_implies_matching_bterms in fe3.\n    dup correct as ms.\n    apply correct_abs_implies_matching_sign in ms.\n    rw @matching_bterms_as_matching_sign in fe0.\n    introv i; eapply find_entry_none_implies; eauto. }\n\n  apply entry_in_libray_implies_find_entry_some; auto.\nQed.\n\nLemma compute_step_preserves_lib_extends {o} :\n  forall (lib1 lib2 : library)\n         (ext  : lib_extends lib2 lib1) (* lib2 extends lib1 *)\n         (a b  : @NTerm o)\n         (comp : compute_step lib1 a = csuccess b),\n    compute_step lib2 a = csuccess b.\nProof.\n  nterm_ind1s a as [v|f ind|op bs ind] Case; introv comp.\n\n  - Case \"vterm\".\n    csunf comp; allsimpl; ginv.\n\n  - Case \"sterm\".\n    csunf comp; allsimpl; ginv.\n\n  - Case \"oterm\".\n    dopid op as [can|ncan|exc|abs] SCase.\n\n    + SCase \"Can\".\n      csunf comp; allsimpl; ginv.\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      { 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 \"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\n          + csunf; simpl.\n            apply isexc_implies2 in comp0; exrepnd; subst.\n            dcwf h; simpl; auto.\n\n          + fold_terms.\n            rewrite compute_step_eapply_iscan_isnoncan_like; auto.\n            pose proof (ind arg2 arg2 []) as h; clear ind.\n            repeat (autodimp h hyp); eauto 3 with slow.\n            apply h in comp1; clear h.\n            rewrite comp1; auto.\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.\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\n                + unfold mk_nseq in *; allsimpl; ginv.\n                  csunf; simpl.\n                  dcwf h; simpl.\n                  boolvar; simpl; auto; try omega.\n                  rewrite Znat.Nat2Z.id; auto.\n\n              - fold_terms; rewrite compute_step_eapply_iscan_isexc; auto.\n\n              - fold_terms; rewrite compute_step_eapply_iscan_isnoncan_like; auto.\n\n                pose proof (ind arg2 arg2 []) as q; clear ind.\n                repeat (autodimp q hyp); eauto 2 with slow.\n                apply q in comp1; clear q.\n                rewrite comp1; auto.\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            }\n\n            {\n              SSSCase \"NSpread\".\n\n              csunf comp; allsimpl.\n              apply compute_step_spread_success in comp.\n              repndors; exrepnd; subst; 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            }\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            }\n\n            {\n              SSSCase \"NCbv\".\n\n              csunf comp; allsimpl.\n              apply compute_step_cbv_success in comp.\n              repndors; exrepnd; subst; 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            }\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            }\n\n            {\n              SSSCase \"NMinus\".\n\n              csunf comp; allsimpl.\n              apply compute_step_minus_success in comp.\n              repndors; exrepnd; subst; auto.\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            }\n\n            {\n              SSSCase \"NParallel\".\n\n              csunf comp; allsimpl.\n              apply compute_step_parallel_success in comp.\n              repndors; exrepnd; subst; auto.\n            }\n\n            {\n              SSSCase \"NCompOp\".\n\n              apply compute_step_ncompop_can1_success in comp; repnd.\n              repndors; exrepnd; allsimpl; subst; tcsp.\n\n              - csunf; simpl.\n                dcwf h.\n\n              - rewrite compute_step_ncompop_ncanlike2; auto.\n                dcwf h.\n                pose proof (ind t t []) as q; clear ind.\n                repeat (autodimp q hyp); eauto 2 with slow.\n                apply q in comp4; clear q.\n                rewrite comp4; auto.\n\n              - csunf; simpl.\n                apply isexc_implies2 in comp1; exrepnd; subst.\n                dcwf h; simpl; auto.\n            }\n\n            {\n              SSSCase \"NArithOp\".\n\n              apply compute_step_narithop_can1_success in comp; repnd.\n              repndors; exrepnd; allsimpl; subst; tcsp.\n\n              - csunf; simpl.\n                dcwf h.\n\n              - rewrite compute_step_narithop_ncanlike2; auto.\n                dcwf h.\n                pose proof (ind t t []) as q; clear ind.\n                repeat (autodimp q hyp); eauto 2 with slow.\n                apply q in comp4; clear q.\n                rewrite comp4; auto.\n\n              - csunf; simpl.\n                apply isexc_implies2 in comp1; exrepnd; subst.\n                dcwf h; simpl; auto.\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            }\n\n          + SSCase \"NCan\".\n\n            csunf comp; allsimpl.\n            remember (compute_step lib1 (oterm (NCan ncan2) bts)) as c.\n            destruct c; allsimpl; ginv.\n            symmetry in Heqc.\n\n            pose proof (ind (oterm (NCan ncan2) bts) (oterm (NCan ncan2) bts) []) as q; clear ind.\n            repeat (autodimp q hyp); eauto 2 with slow.\n            apply q in Heqc; clear q.\n            csunf; simpl.\n            rewrite Heqc; auto.\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\n            * csunf; simpl; auto.\n              rewrite compute_step_catch_if_diff; auto.\n\n          + SSCase \"Abs\".\n\n            csunf comp; allsimpl.\n            remember (compute_step lib1 (oterm (Abs abs2) bts)) as c.\n            destruct c; allsimpl; ginv.\n            symmetry in Heqc.\n\n            pose proof (ind (oterm (Abs abs2) bts) (oterm (Abs abs2) bts) []) as q; clear ind.\n            repeat (autodimp q hyp); eauto 2 with slow.\n            apply q in Heqc; clear q.\n            csunf; simpl.\n            rewrite Heqc; auto.\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\n        - rewrite compute_step_fresh_if_isvalue_like2; auto.\n\n        - fold (mk_fresh n t).\n          rewrite compute_step_fresh_if_isnoncan_like; 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 2 with slow.\n          { rewrite simple_osize_subst; eauto 2 with slow. }\n          apply q in comp2; clear q.\n          remember (get_fresh_atom t) as a; simpl.\n          rewrite comp2; simpl; auto.\n      }\n\n    + SCase \"Exc\".\n\n      csunf comp; allsimpl; ginv.\n\n    + SCase \"Abs\".\n\n      csunf comp; allsimpl.\n      apply compute_step_lib_success in comp.\n      exrepnd; subst.\n\n      csunf; simpl.\n\n      apply (found_entry_implies_compute_step_lib_success _ _ _ _ _ _ correct).\n      eapply lib_extends_preserves_find_entry; eauto.\nQed.\n\nLemma reduces_in_atmost_k_steps_preserves_lib_extends {o} :\n  forall (lib1 lib2 : library)\n         (ext  : lib_extends lib2 lib1) (* lib2 extends lib1 *)\n         (a b  : @NTerm o)\n         (n : nat)\n         (comp : reduces_in_atmost_k_steps lib1 a b n),\n    reduces_in_atmost_k_steps lib2 a b n.\nProof.\n  introv ext r.\n  revert dependent a.\n  induction n; introv r.\n\n  - allrw @reduces_in_atmost_k_steps_0; auto.\n\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    exists u; dands; auto.\n    eapply compute_step_preserves_lib_extends; eauto.\nQed.\n\nLemma reduces_to_preserves_lib_extends {o} :\n  forall (lib1 lib2 : library)\n         (ext  : lib_extends lib2 lib1) (* lib2 extends lib1 *)\n         (a b  : @NTerm o)\n         (comp : reduces_to lib1 a b),\n    reduces_to lib2 a b.\nProof.\n  introv ext r.\n  unfold reduces_to in *; exrepnd.\n  exists k.\n  eapply reduces_in_atmost_k_steps_preserves_lib_extends; eauto.\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/computation_lib_extends.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2883808691241044}}
{"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import BaremoreSMC.Spec.\nRequire Import AbsAccessor.Spec.\n\nLocal Open Scope Z_scope.\n\nSection SpecLow.\n\n  Definition granule_undelegate_ops_spec0 (g: Pointer) (addr: Z64) (adt: RData) : option RData :=\n    match g, addr with\n    | (_g_base, _g_ofst), VZ64 _addr =>\n      rely is_int64 _addr;\n      when adt == smc_mark_nonsecure_spec (VZ64 _addr) adt;\n      when adt == granule_set_state_spec (_g_base, _g_ofst) 0 adt;\n      when adt == granule_unlock_spec (_g_base, _g_ofst) 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/RmiOps/LowSpecs/granule_undelegate_ops.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.28837770943708557}}
{"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 csubst.\n\n\nLemma lsubstc_app_cover1 {o} :\n  forall (t : @NTerm o) sub1 sub2 p c (c' : cover_vars t sub1),\n    lsubstc t p (sub1 ++ sub2) c\n    = lsubstc t p sub1 c'.\nProof.\n  introv.\n  apply cterm_eq; simpl.\n  unfold csubst.\n  rw <- @csub2sub_app.\n  rw <- @simple_lsubst_app.\n  - rw @lsubst_trivial; auto.\n    introv i.\n    applydup @in_csub2sub in i; dands; auto.\n    introv k.\n    pose proof (eqvars_free_vars_disjoint t (csub2sub sub1)) as h.\n    eapply eqvars_prop in h; apply h in k; clear h.\n    rw in_app_iff in k; rw in_remove_nvars in k.\n    dorn k; repnd.\n    + rw @cover_vars_eq in c'.\n      rw subvars_prop in c'.\n      apply c' in k0.\n      rw @dom_csub_eq in k; auto.\n    + apply in_sub_free_vars_iff in k; exrepnd.\n      apply in_sub_keep_first in k0; repnd.\n      apply sub_find_some in k2.\n      apply in_csub2sub in k2.\n      destruct k2 as [cl wf].\n      rw cl in k1; sp.\n  - introv i; apply in_csub2sub in i; sp.\n  - introv i; apply in_csub2sub in i; sp.\nQed.\n\nLemma csubst_snoc_app_move_to_last {o} :\n  forall (t : @NTerm o) s1 s2 x a,\n    !LIn x (dom_csub s2)\n    -> csubst t (snoc s1 (x, a) ++ s2)\n       = csubst t (snoc (s1 ++ s2) (x, a)).\nProof.\n  introv ni1.\n  rw <- snoc_append_l.\n  symmetry.\n  rw <- @csubst_app.\n  rewrite <- (csubst_swap (csubst t s1) s2); auto.\n  rw @csubst_app.\n  rw <- snoc_append_r; auto.\nQed.\n\nLemma lsubstc_snoc_app_move_to_last {o} :\n  forall (t : @NTerm o) s1 s2 x a w c,\n    !LIn x (dom_csub s2)\n    -> {c' : cover_vars t (snoc (s1 ++ s2) (x,a))\n        $ lsubstc t w (snoc s1 (x,a) ++ s2) c\n          = lsubstc t w (snoc (s1 ++ s2) (x,a)) c'}.\nProof.\n  introv ni.\n\n  assert (cover_vars t (snoc (s1 ++ s2) (x,a))) as cv.\n  allrw @cover_vars_eq; allrw subvars_eq.\n  introv i; applydup c in i.\n  allrw @dom_csub_app; allrw @dom_csub_snoc; allrw @dom_csub_app; allsimpl.\n  allrw in_app_iff; allrw in_snoc; allrw in_app_iff.\n  sp; subst; sp.\n\n  exists cv.\n\n  apply cterm_eq; simpl.\n  apply csubst_snoc_app_move_to_last; auto.\nQed.\n\nLemma csubst_snoc_app_move_down {o} :\n  forall (t : @NTerm o) s1 s2 s3 x a,\n    !LIn x (dom_csub s2)\n    -> csubst t ((snoc s1 (x, a) ++ s2) ++ s3)\n       = csubst t (snoc (s1 ++ s2) (x, a) ++ s3).\nProof.\n  introv ni1.\n  rw <- @csubst_app.\n  symmetry; rw <- @csubst_app.\n  rw @csubst_snoc_app_move_to_last; auto.\nQed.\n\nLemma lsubstc_snoc_app_move_down {o} :\n  forall (t : @NTerm o) s1 s2 s3 x a w c,\n    !LIn x (dom_csub s2)\n    -> {c' : cover_vars t (snoc (s1 ++ s2) (x,a) ++ s3)\n        $ lsubstc t w ((snoc s1 (x,a) ++ s2) ++ s3) c\n          = lsubstc t w (snoc (s1 ++ s2) (x,a) ++ s3) c'}.\nProof.\n  introv ni.\n\n  assert (cover_vars t (snoc (s1 ++ s2) (x,a) ++ s3)) as cv.\n  allrw @cover_vars_eq; allrw subvars_eq.\n  introv i; applydup c in i.\n  allrw @dom_csub_app; allrw @dom_csub_snoc; allrw @dom_csub_app; allsimpl.\n  allrw in_app_iff; allrw in_snoc; allrw in_app_iff.\n  sp; subst; sp.\n\n  exists cv.\n\n  apply cterm_eq; simpl.\n  apply csubst_snoc_app_move_down; auto.\nQed.\n\nLemma lsubstc_snoc_app_move_down2 {o} :\n  forall (t : @NTerm o) s1 s2 s3 x a w c,\n    !LIn x (dom_csub s2)\n    -> {c' : cover_vars t ((snoc s1 (x,a) ++ s2) ++ s3)\n        $ lsubstc t w (snoc (s1 ++ s2) (x,a) ++ s3) c\n          = lsubstc t w ((snoc s1 (x,a) ++ s2) ++ s3) c'}.\nProof.\n  introv ni.\n\n  assert (cover_vars t ((snoc s1 (x,a) ++ s2) ++ s3)) as cv.\n  allrw @cover_vars_eq; allrw subvars_eq.\n  introv i; applydup c in i.\n  allrw @dom_csub_app; allrw @dom_csub_snoc; allrw @dom_csub_app; allsimpl.\n  allrw in_app_iff; allrw in_snoc; allrw in_app_iff.\n  sp; subst; sp.\n\n  exists cv.\n\n  apply cterm_eq; simpl.\n  symmetry; apply csubst_snoc_app_move_down; auto.\nQed.\n\nLemma subst_preserves_isprog_vars {p} :\n  forall (t : @NTerm p) (v : NVar) (u : NTerm) vs,\n    isprog_vars (v :: vs) t\n    -> isprog_vars vs u\n    -> isprog_vars vs (subst t v u).\nProof.\n  introv ispt ispu.\n  unfold lsubst.\n  allrw @isprog_vars_eq; repnd; dands.\n  - unfold subst.\n    pose proof (eqvars_free_vars_disjoint t [(v,u)]) as eqv; simpl in eqv.\n    allrw subvars_prop; introv i.\n    eapply eqvars_prop in eqv.\n    apply eqv in i; clear eqv.\n    apply in_app_iff in i; dorn i.\n    + apply in_remove_nvars in i; rw in_single_iff in i; repnd.\n      discover; allsimpl; sp.\n    + revert i; boolvar; intro i; allsimpl; tcsp.\n      allrw app_nil_r.\n      discover; sp.\n  - apply lsubst_wf_iff; auto.\n    unfold wf_sub, sub_range_sat; simpl; simpl; introv k; sp; cpx.\nQed.\n\nLemma cover_vars_isprog_vars {o} :\n  forall (t : @NTerm o) sub vs1 vs2,\n    wf_term t\n    -> eqvars vs2 (vs1 ++ dom_csub sub)\n    -> (cover_vars_upto t sub vs1 <=> isprog_vars vs2 t).\nProof.\n  introv wf eqv.\n  unfold cover_vars_upto.\n  rw @isprog_vars_eq.\n  rw eqvars_prop in eqv.\n  split; intro k; repnd; dands; auto.\n  - allrw subvars_prop; introv i.\n    discover; auto.\n  - apply nt_wf_eq; auto.\n  - allrw subvars_prop; introv i.\n    discover; auto.\nQed.\n\nLemma cover_vars_implies_isprog_vars {o} :\n  forall (t : @NTerm o) sub vs1 vs2,\n    wf_term t\n    -> subvars (vs1 ++ dom_csub sub) vs2\n    -> cover_vars_upto t sub vs1\n    -> isprog_vars vs2 t.\nProof.\n  introv wf eqv cv.\n  unfold cover_vars_upto in cv.\n  rw @isprog_vars_eq.\n  allrw subvars_prop; dands.\n  - introv i; discover; auto.\n  - apply nt_wf_eq; auto.\nQed.\n\nLemma lsubstc_subst_snoc_eq_ex {o} :\n  forall (s : @CSub o)\n         (b : NTerm)\n         (x y : NVar)\n         (a : CTerm)\n         (w1 : wf_term (subst b x (mk_var y)))\n         (c1 : cover_vars (subst b x (mk_var y)) (snoc s (y, a))),\n    !LIn y (bound_vars b)\n    -> !LIn y (dom_csub s)\n    -> (y <> x -> !LIn y (free_vars b))\n    -> {w2 : wf_term b\n        & {c2 : cover_vars_upto b (csub_filter s [x]) [x]\n        & lsubstc (subst b x (mk_var y)) w1 (snoc s (y, a)) c1\n          = substc a x (lsubstc_vars b w2 (csub_filter s [x]) [x] c2)}}.\nProof.\n  introv ni1 ni2 ni3.\n\n  assert (wf_term b) as w2 by (apply lsubst_wf_term in w1; auto).\n  exists w2.\n\n  assert (cover_vars_upto b (csub_filter s [x]) [x]) as c2.\n  allrw @cover_vars_eq.\n  unfold cover_vars_upto.\n  allrw subvars_prop; introv i; simpl.\n  destruct (deq_nvar x x0); subst; tcsp.\n  right.\n  rw @dom_csub_csub_filter; rw in_remove_nvars; rw in_single_iff; dands; tcsp.\n  pose proof (c1 x0) as h; autodimp h hyp.\n  pose proof (eqvars_free_vars_disjoint b [(x,mk_var y)]) as eqv.\n  rw eqvars_prop in eqv; apply eqv; clear eqv; simpl.\n  rw in_app_iff; rw in_remove_nvars; rw in_single_iff; left; sp.\n  rw @dom_csub_snoc in h; simpl in h; rw in_snoc in h; dorn h; tcsp; subst.\n  autodimp ni3 hyp; sp.\n\n  exists c2.\n  apply lsubstc_subst_snoc_eq; sp.\nQed.\n\nLemma lsubst_aux_swap_context {o} :\n  forall t (s1 s2 s : @Sub o) v u,\n    (forall v t, LIn (v, t) s -> isprogram t)\n    -> isprogram u\n    -> !LIn v (dom_sub s)\n    -> lsubst_aux t ((s1 ++ (v, u) :: s) ++ s2) = lsubst_aux t ((s1 ++ snoc s (v, u)) ++ s2).\nProof.\n  nterm_ind t as [v|f|op lbt ind] Case; simpl; intros; auto.\n\n  - Case \"vterm\".\n    repeat (rw @sub_find_app).\n    rw @sub_find_snoc; simpl; boolvar.\n    + remember (sub_find s1 v) as s1n; destruct s1n; symmetry in Heqs1n; auto.\n      remember (sub_find s v) as sn; destruct sn; symmetry in Heqsn; auto.\n      apply sub_find_some in Heqsn.\n      apply in_dom_sub in Heqsn; sp.\n    + remember (sub_find s1 v) as s1n; destruct s1n; symmetry in Heqs1n; auto.\n      remember (sub_find s v) as sn; destruct sn; symmetry in Heqsn; auto.\n\n  - Case \"oterm\".\n    apply oterm_eq; auto.\n    apply eq_maps; introv i.\n    destruct x; simpl.\n    apply bterm_eq; auto.\n\n    repeat (rw @sub_filter_app); simpl.\n    repeat (rw @sub_filter_snoc); boolvar; auto.\n\n    eapply ind; eauto; introv;\n    try (rw @in_sub_filter);\n    try (rw <- @dom_sub_sub_filter);\n    try (rw in_remove_nvars);\n    intro k; repnd; discover; sp.\nQed.\n\nLemma range_snoc {p} :\n  forall (s : @Sub p) v t,\n    range (snoc s (v, t))\n    = snoc (range s) t.\nProof.\n  introv; unfold range; rw map_snoc; sp.\nQed.\n\nLemma lsubst_swap_context {o} :\n  forall t (s1 s2 s : @Sub o) v u,\n    (forall v t, LIn (v, t) s -> isprogram t)\n    -> (forall v t, LIn (v, t) s1 -> isprogram t)\n    -> (forall v t, LIn (v, t) s2 -> isprogram t)\n    -> isprogram u\n    -> !LIn v (dom_sub s)\n    -> lsubst t ((s1 ++ (v, u) :: s) ++ s2) = lsubst t ((s1 ++ snoc s (v, u)) ++ s2).\nProof.\n  introv k1 k2 k3 isp ni.\n  change_to_lsubst_aux4;\n    try (complete (allrw @range_app; allsimpl; try (rw @range_snoc);\n                   allrw flat_map_app; allrw flat_map_snoc; allsimpl;\n                   destruct isp as [cl w]; rw cl;\n                   repeat (rw @closed_sub; auto); simpl; sp)).\n  apply lsubst_aux_swap_context; auto.\nQed.\n\nLemma csubst_swap_context {o} :\n  forall t (s1 s2 s : @CSub o) v u,\n    !LIn v (dom_csub s)\n    -> csubst t ((s1 ++ (v, u) :: s) ++ s2)\n       = csubst t ((s1 ++ snoc s (v, u)) ++ s2).\nProof.\n  intros.\n  unfold csubst; simpl.\n  repeat (rw <- @csub2sub_app); simpl.\n  allrw @csub2sub_snoc.\n  apply lsubst_swap_context; auto;\n  try (complete (intros; allapply @in_csub2sub; sp)).\n  rw @dom_csub_eq; auto.\nQed.\n\nLemma csubst_subst_snoc_eq2 {o} :\n  forall s b x y (a : @CTerm o),\n    !LIn y (bound_vars b)\n    -> !LIn y (dom_csub s)\n    -> !LIn x (dom_csub s)\n    -> x <> y\n    -> csubst (subst b x (mk_var y)) (snoc s (y, a))\n       = csubst b (snoc (snoc s (x, a)) (y, a)).\nProof.\n  introv ni1 ni2 ni3 ni4.\n  unfold subst, csubst.\n  rewrite simple_lsubst_lsubst; simpl;\n  [\n  | complete (intros; sp; cpx; simpl; rw disjoint_singleton_l; auto)\n  | complete (intros; allapply @in_csub2sub; auto)].\n\n  change_to_lsubst_aux4;\n    [ |\n      simpl;\n        apply disjoint_app_r;\n        rw disjoint_flat_map_r;\n        dands; [remember (sub_find (csub2sub (snoc s (y,a))) y) as k; destruct k; symmetry in Heqk|]; simpl;\n        [ complete (apply sub_find_some in Heqk; apply in_csub2sub in Heqk;\n                    destruct Heqk as [cl k]; rw cl; sp)\n        | complete (rw disjoint_singleton_r; auto)\n        | ]; introv k;\n        apply in_range in k; exrepnd;\n        apply in_csub2sub in k0; auto; destruct k0 as [cl k]; rw cl; sp\n    ].\n\n  simpl.\n\n  rw @csub2sub_snoc.\n  rw @sub_find_snoc.\n\n  pose proof (sub_find_none_iff (csub2sub s) y) as k.\n  rw @dom_csub_eq in k; apply k in ni2; rw ni2; boolvar.\n\n  rw snoc_as_append.\n  pose proof (lsubst_aux_swap_context b []) as h; simpl in h.\n  rw h; auto.\n  rw <- snoc_as_append.\n  repeat (rw @csub2sub_snoc); auto.\n  intros; allapply @in_csub2sub; sp.\n  rw @dom_csub_eq; auto.\nQed.\n\nLemma lsubstc_subst_snoc_eq2 {o} :\n  forall (s : @CSub o) b x y a w1 w2 c1 c2,\n    !LIn y (bound_vars b)\n    -> !LIn y (dom_csub s)\n    -> !LIn x (dom_csub s)\n    -> x <> y\n    -> lsubstc (subst b x (mk_var y)) w1 (snoc s (y, a)) c1\n       = lsubstc b w2 (snoc (snoc s (x, a)) (y, a)) c2.\nProof.\n  intros.\n\n  apply cterm_eq; simpl.\n  apply csubst_subst_snoc_eq2; auto.\nQed.\n\nLemma lsubstc_subst_snoc_eq2_ex {o} :\n  forall (s : @CSub o)\n         (b : NTerm)\n         (x y : NVar)\n         (a : CTerm)\n         (w1 : wf_term (subst b x (mk_var y)))\n         (c1 : cover_vars (subst b x (mk_var y)) (snoc s (y, a))),\n    !LIn y (bound_vars b)\n    -> !LIn y (dom_csub s)\n    -> !LIn x (dom_csub s)\n    -> x <> y\n    -> {w2 : wf_term b\n        & {c2 : cover_vars b (snoc (snoc s (x,a)) (y,a))\n        & lsubstc (subst b x (mk_var y)) w1 (snoc s (y, a)) c1\n          = lsubstc b w2 (snoc (snoc s (x,a)) (y,a)) c2}}.\nProof.\n  introv ni1 ni2.\n\n  assert (wf_term b) as w2 by (apply lsubst_wf_term in w1; auto).\n  exists w2.\n\n  assert (cover_vars b (snoc (snoc s (x,a)) (y,a))) as c2.\n  allrw @cover_vars_eq; allrw subvars_prop; introv i; simpl.\n  repeat (rw @dom_csub_snoc); simpl; repeat (rw in_snoc).\n  destruct (deq_nvar x x0); subst; tcsp.\n  pose proof (c1 x0) as h; autodimp h hyp.\n  pose proof (eqvars_free_vars_disjoint b [(x,mk_var y)]) as eqv.\n  rw eqvars_prop in eqv; apply eqv; clear eqv; simpl.\n  rw in_app_iff; rw in_remove_nvars; rw in_single_iff; left; sp.\n  rw @dom_csub_snoc in h; simpl in h; rw in_snoc in h; dorn h; tcsp; subst.\n\n  exists c2.\n\n  apply lsubstc_subst_snoc_eq2; auto.\nQed.\n\nLemma lsubst_aux_snoc_cover_vars {p} :\n  forall (t : @NTerm p) sub v u,\n    (LIn v (free_vars t) -> LIn v (dom_sub sub))\n    -> lsubst_aux t (snoc sub (v, u)) = lsubst_aux t sub.\nProof.\n  nterm_ind t as [v|f|o lbt ind] Case; simpl; introv ni; auto.\n\n  - Case \"vterm\".\n    allunfold @covered; allsimpl; allrw subvars_singleton_l.\n    rw @sub_find_snoc.\n    remember (sub_find sub v); destruct o; symmetry in Heqo; sp.\n    boolvar; auto.\n    applydup @sub_find_none2 in Heqo; sp.\n\n  - Case \"oterm\".\n    f_equal.\n    apply eq_maps; sp.\n    destruct x; simpl.\n\n    rw @sub_filter_snoc; boolvar; auto.\n    apply bterm_eq; auto.\n    apply ind with (lv := l); auto.\n\n    introv i.\n    rw <- @dom_sub_sub_filter.\n    apply in_remove_nvars; dands; auto.\n    assert (LIn v (flat_map free_vars_bterm lbt)); discover; auto.\n    apply lin_flat_map.\n    exists (bterm l n); dands; auto.\n    simpl; apply in_remove_nvars; sp.\nQed.\n\nLemma lsubst_snoc_cover_vars {p} :\n  forall (t : @NTerm p) sub v u,\n    disjoint (bound_vars t) (flat_map free_vars (range sub))\n    -> disjoint (bound_vars t) (free_vars u)\n    -> (LIn v (free_vars t) -> LIn v (dom_sub sub))\n    -> lsubst t (snoc sub (v, u)) = lsubst t sub.\nProof.\n  introv d1 d2 ni.\n  change_to_lsubst_aux4.\n  - apply lsubst_aux_snoc_cover_vars; auto.\n  - allrw @range_snoc.\n    allrw flat_map_snoc.\n    allrw disjoint_app_r; sp.\nQed.\n\nLemma prog_sub_nil {o} : @prog_sub o [].\nProof.\n  unfold prog_sub, sub_range_sat; simpl; sp.\nQed.\nHint Immediate prog_sub_nil.\n\nLemma closed_sub_cl {p} :\n  forall (sub : @Sub p),\n    (forall v t, LIn (v, t) sub -> closed t)\n    -> flat_map free_vars (range sub) = [].\nProof.\n  induction sub; allsimpl; introv h; auto.\n  destruct a; allsimpl.\n  pose proof (h n n0) as k; autodimp k hyp.\n  rw k.\n  rw IHsub; auto.\n  introv i; eapply h; eauto.\nQed.\n\nLemma disjoint_sub_if_cl {p} :\n  forall (sub : @Sub p),\n    (forall v t, LIn (v, t) sub -> closed t)\n    -> forall t : @NTerm p, disjoint (bound_vars t) (flat_map free_vars (range sub)).\nProof.\n  introv i.\n  rw @closed_sub_cl; auto.\nQed.\n\nLemma dom_sub_lsubst_sub {o} :\n  forall (sub1 sub2 : @Sub o),\n    dom_sub (lsubst_sub sub1 sub2) = dom_sub sub1.\nProof.\n  induction sub1; introv; simpl; auto.\n  destruct a; simpl.\n  apply eq_cons; 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/subst_props.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.28837407253946307}}
{"text": "From CoreErlang.BigStep Require Export DeterminismHelpers.\n\n(** Proofs about the semantics *)\n\nImport ListNotations.\n(* Import Coq.Init.Logic. *)\n\nProposition length_split_eq {A B : Type} (l : list (A * B)) :\n  length (fst (split l)) = length (snd (split l)).\nProof.\n  rewrite split_length_l, split_length_r. auto.\nQed.\n\nProposition split_eq {A B : Type} {l l0 : list (A * B)} : \n  split l = split l0 <-> l = l0.\nProof.\n  split; generalize dependent l0.\n  * induction l; intros.\n    - inversion H. destruct l0.\n      + reflexivity.\n      + inversion H1. destruct p. destruct (split l0). inversion H2.\n    - destruct l0.\n      + inversion H. destruct a. destruct (split l). inversion H1.\n      + inversion H. subst. assert (split l = split l0). {\n        destruct a, p. destruct (split l), (split l0). inversion H1. subst. auto.\n        }\n        pose (IH := IHl l0 H0).\n        destruct a, p. destruct (split l), (split l0) in H1. inversion H1. rewrite IH. auto.\n  * intros. rewrite H. reflexivity.\nQed.\n\nTheorem determinism :\n(\n  forall {env modules own_module id e eff id' v1 eff'},\n  |env, modules, own_module, id, e, eff| -e> | id', v1, eff'|\n->\n  (forall v2 eff'' id'', |env, modules, own_module, id, e, eff| -e> |id'', v2, eff''| -> v1 = v2 /\\ eff' = eff''\n      /\\ id' = id'')\n).\nProof.\n  intros env modules own_module id e eff id' v1 eff' H. induction H; intros.\n\n  (* VALUE LIST *)\n  * inversion H6; subst.\n    - pose (P := explist_equality _ _ _ _ _ _ _ H3 H11 H8 H9 H H0 H1 H10).\n      destruct P. destruct H5. subst. auto.\n    - pose (P := explist_prefix_eq _ _ _ _ _ _ _ _ _ _ _ H H0 H10 H8 H1 H11 H3 H12 H17).\n      inversion P.\n\n  (* VALUE LIST EXCEPTION *)\n  * inversion H6; subst.\n    - epose (P := explist_prefix_eq_rev _ _ _ _ _ _ _ _ _ _ _ H4 H11 IHeval_expr H H1 H8 H9 H10 H2).\n      inversion P.\n    - epose (P := exception_equality _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H4 H17 IHeval_expr H12\n        _ _ _ _ _ _ _ _).\n      destruct P, H7, H9. subst. auto.\n      Unshelve.\n      all: auto.\n\n(*   (* SINGLE EXPRESSION *)\n  * apply H. inversion H0. auto. *)\n\n  (* NIL *)\n  * inversion H. auto.\n\n  (* LIT *)\n  * inversion H. auto.\n\n  (* VAR *)\n  * inversion H0. subst. rewrite H6 in H. inversion H. auto.\n\n  (* FUNID *)\n  * inversion H0.\n    - subst. rewrite H6 in H. inversion H. auto.\n    - congruence.\n\n  (* FUNID WITH MODULE *)\n  * inversion H3.\n    - subst. congruence. \n    - subst. rewrite H6 in H0. inversion H0. subst. auto.\n\n  (* FUN *)\n  * inversion H. auto.\n\n  (* TUPLE *)\n  * inversion H6; subst.\n    - pose (P := explist_equality _ _ _ _ _ _ _ H3 H11 H8 H9 H H0 H1 H10).\n      destruct P, H5. subst. auto.\n    - pose (P := explist_prefix_eq _ _ _ _ _ _ _ _ _ _ _ H H0 H10 H8 H1 H11 H3 H12 H17).\n      inversion P.\n\n  (* CONS *)\n  * inversion H1; subst.\n    - apply IHeval_expr1 in H8. destruct H8, H3. inversion H2. subst.\n      apply IHeval_expr2 in H13. destruct H13, H4. inversion H3. subst. auto.\n    - apply IHeval_expr1 in H12. destruct H12. congruence.\n    - apply IHeval_expr1 in H8. destruct H8, H3. inversion H2. subst.\n      apply IHeval_expr2 in H13. destruct H13, H4. congruence.\n\n  (* CASE *)\n  * inversion H6; subst.\n    - apply IHeval_expr1 in H9. destruct H9, H8. inversion H7. subst.\n      pose (P := index_case_equality _ _ _ _ _ _ _ _ _ _ H3 H12 H1 H11 H17 H4 IHeval_expr2).\n      assert (i = i0). { auto. }\n      clear P. subst. rewrite H1 in H11. inversion H11. subst.\n      apply IHeval_expr2 in H17. apply IHeval_expr3 in H22. auto.\n    - apply IHeval_expr1 in H17. destruct H17. congruence.\n    - apply IHeval_expr1 in H13. destruct H13, H8. inversion H7. subst.\n      pose (P := H18 i H0 _ _ _ H1).\n      apply IHeval_expr2 in P. destruct P. inversion H8.\n\n  (* CALL *)\n   * inversion H9; subst.\n    - apply IHeval_expr1 in H16. destruct H16, H10. inversion H8. subst.\n      apply IHeval_expr2 in H17. destruct H17, H11. inversion H10. subst. \n      pose (P := explist_equality _ _ _ _ _ _ _ H5 H18 H13 H14 H H0 H1 H15).\n      destruct P, H12. subst. rewrite H7 in H28. inversion H28. auto.\n    - apply IHeval_expr1 in H16. destruct H16 , H10. inversion H8. subst.\n      apply IHeval_expr2 in H17. destruct H17  , H11. inversion H10. subst.\n      congruence.\n    - apply IHeval_expr1 in H17. destruct H17  , H10. destruct H8. subst.\n      apply IHeval_expr2 in H22. destruct H22  , H10. destruct H8. subst.\n      pose (P := explist_prefix_eq _ _ _ _ _ _ _ _ _ _ _ H H0 H15 H13 H1 H16 H5 H27 H28).\n      inversion P.\n    - apply IHeval_expr1 in H21. destruct H21. congruence.  \n    - apply IHeval_expr1 in H21. destruct H21, H10. inversion H8. subst.\n      apply IHeval_expr2 in H22. destruct H22. congruence.\n    - apply IHeval_expr1 in H16. destruct H16, H10. inversion H8. subst. congruence.  \n    - apply IHeval_expr1 in H16. destruct H16, H10. inversion H8. subst.\n      apply IHeval_expr2 in H17. destruct H17, H11. inversion H10. subst. congruence.\n\n  * inversion H8; subst.\n    - apply IHeval_expr1 in H15. destruct H15, H10. inversion H9. subst.\n      apply IHeval_expr2 in H16. destruct H16, H11. inversion H10. subst. \n      pose (P := explist_equality _ _ _ _ _ _ _ H5 H17 H12 H13 H H0 H1 H14).\n      destruct P , H15. subst. congruence.\n    - apply IHeval_expr1 in H15. destruct H15, H10. inversion H9. subst.\n      apply IHeval_expr2 in H16. destruct H16, H11. inversion H10. subst. \n      pose (P := explist_equality _ _ _ _ _ _ _ H5 H21 H12 H13 H H0 H1 H14).\n      destruct P , H15. subst. rewrite H6 in H26. inversion H26. subst.\n      apply IHeval_expr3 in H27. destruct H27, H15. inversion H11. subst. auto. \n\n    - apply IHeval_expr1 in H16. destruct H16, H10. inversion H9. subst.\n      apply IHeval_expr2 in H21. destruct H21, H11. inversion H10. subst. \n      pose (P := explist_prefix_eq _ _ _ _ _ _ _ _ _ _ _ H H0 H14 H12 H1 H15 H5 H26 H27).\n      inversion P.\n    - apply IHeval_expr1 in H20. destruct H20, H10. congruence.\n    - apply IHeval_expr1 in H20. destruct H20, H10. inversion H9. subst.\n      apply IHeval_expr2 in H21. destruct H21, H11. congruence.\n    - apply IHeval_expr1 in H15. destruct H15, H10. inversion H9. subst.\n      apply IHeval_expr2 in H16. destruct H16, H11. inversion H10. subst. congruence.\n    - apply IHeval_expr1 in H15. destruct H15, H10. inversion H9. subst.\n      apply IHeval_expr2 in H16. destruct H16, H11. inversion H10. subst. congruence.  \n\n\n\n\n  (* PRIMOP *)\n  * inversion H6; subst.\n    - pose (P := explist_equality vals vals0 eff eff4 id ids ids0 H3 H12 H9 H10 H H0 H1 H11).\n      destruct P, H7. subst. rewrite H4 in H17. inversion H17. auto.\n    - pose (P := explist_prefix_eq _ _ _ _ _ _ _ _ _ _ _ H H0 H11 H9 H1 H12 H3 H17 H22).\n      inversion P.\n\n  (* APP *)\n  * inversion H7; subst.\n    - apply IHeval_expr1 in H11. destruct H11, H9. inversion H8. subst.\n      pose (P := explist_equality _ _ _ _ _ _ _ H5 H19 H10 H13 H H2 H3 H14).\n      destruct P, H11. subst. apply IHeval_expr2. auto.\n    - apply IHeval_expr1 in H18. destruct H18. congruence.\n    - apply IHeval_expr1 in H14. destruct H14, H9. inversion H8. subst.\n      pose (P := explist_prefix_eq _ _ _ _ _ _ _ _ _ _ _ H H2 H12 H10 H3 H13 H5 H19 H24).\n      inversion P.\n    - apply IHeval_expr1 in H13. destruct H13, H9. inversion H8. subst.\n      congruence.\n    - apply IHeval_expr1 in H13. destruct H13, H9. inversion H8. subst.\n      lia.\n\n  (* LET *)\n  * inversion H2; subst.\n    - apply IHeval_expr1 in H10. destruct H10, H4. inversion H3. subst.\n      apply IHeval_expr2 in H16. auto.\n    - apply IHeval_expr1 in H14. destruct H14. congruence.\n\n  (* SEQ *)\n  * inversion H1; subst.\n    - apply IHeval_expr1 in H8. destruct H8, H3. inversion H2. subst.\n      apply IHeval_expr2 in H13. auto.\n    - apply IHeval_expr1 in H12. destruct H12. inversion H2.\n\n  (* LETREC *)\n  * inversion H0. subst. apply IHeval_expr in H11. auto.\n\n  (* MAP *)\n  * inversion H9; subst.\n    - assert (exps = exps0). { auto. } rewrite <- H6 in *.\n      assert (length vals0 = length l * 2). { unfold vals0. rewrite H12. eapply length_make_map_vals. lia. }\n      assert (length vals = length l * 2). { unfold vals. rewrite H0. eapply length_make_map_vals. lia. }\n      assert (length exps = length l * 2). { unfold exps. apply length_make_map_exps. }\n      rewrite <- H10 in *.\n      pose (P := explist_equality _ _ _ _ _ _ _ H4 H15 (eq_sym H7) H13 (eq_sym H8) H1 H2 H14).\n      destruct P. destruct H18. subst.\n      unfold vals, vals0 in H18. apply make_map_vals_eq in H18.\n      2-4: lia.\n      destruct H18. subst. rewrite H16 in H5. inversion H5. subst. auto.\n    - assert (length exps = length vals). { unfold vals. unfold exps. rewrite length_make_map_vals. rewrite length_make_map_exps. lia. rewrite <- H, <- H0. auto. }\n      assert (length eff4 = length vals0).\n      {\n        unfold vals0. case_eq (modulo_2 (length eff4)); intros.\n        * rewrite e in *. rewrite length_make_map_vals. rewrite Nat.add_0_r in H13.\n          2: lia. rewrite H13. simpl. apply n_div_2_mod_0. lia.\n        * rewrite e in *. rewrite length_make_map_vals2. 2: lia.\n          rewrite H12. apply n_div_2_mod_1. lia.\n      }\n      rewrite H7 in H16, H21.\n      epose (P := explist_prefix_eq _ _ _ _ _ _ _ _ _ _ _ H6 _ _ _ _ _ H4 H16 H21).\n      inversion P.\n      Unshelve.\n      + unfold exps. rewrite length_make_map_exps. lia.\n      + auto.\n      + unfold vals0, exps.\n        rewrite length_make_map_exps.\n        unfold vals0. case_eq (modulo_2 (length eff4)); intros.\n        ** rewrite e in *. rewrite length_make_map_vals. rewrite Nat.add_0_r in H13.\n          2: lia. rewrite H13. rewrite <- n_div_2_mod_0. lia. lia.\n        ** rewrite e in *. rewrite length_make_map_vals2. 2: lia.\n          rewrite H12. rewrite <- n_div_2_mod_1. lia. lia.\n      + unfold exps. rewrite length_make_map_exps. lia.\n      + lia.\n\n  (* CONS TL EXCEPTION *)\n  * inversion H0; subst.\n    - apply IHeval_expr in H7. destruct H7. congruence.\n    - apply IHeval_expr in H11. auto.\n    - apply IHeval_expr in H7. destruct H7. congruence.\n\n  (* CONS HEAD EXCEPTION *)\n  * inversion H1; subst.\n    - apply IHeval_expr1 in H8. destruct H8, H3. inversion H2. subst.\n      apply IHeval_expr2 in H13. destruct H13. congruence.\n    - apply IHeval_expr1 in H12. destruct H12. congruence.\n    - apply IHeval_expr1 in H8. destruct H8, H3. inversion H2. subst.\n      apply IHeval_expr2 in H13. destruct H13, H4. inversion H2. auto.\n\n  (* TUPLE EXCEPTION *)\n  * inversion H6; subst.\n    - epose (P := explist_prefix_eq_rev _ _ _ _ _ _ _ _ _ _ _ H4 H11 IHeval_expr _ _ _ _ _ _).\n      inversion P. Unshelve. all: auto.\n    - epose (P := exception_equality _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H4 H17 IHeval_expr H12\n        _ _ _ _ _ _ _ _).\n      destruct P, H7, H9. subst. auto.\n      Unshelve. all: auto.\n\n  (* TRY *)\n  * inversion H2; subst.\n    - apply IHeval_expr1 in H16. destruct H16, H4. inversion H3. subst.\n      apply IHeval_expr2 in H18. destruct H18, H5. auto.\n    - apply IHeval_expr1 in H16. destruct H16. congruence.\n\n  (* CATCH *)\n  * inversion H1; subst.\n    - apply IHeval_expr1 in H15. destruct H15. congruence.\n    - apply IHeval_expr1 in H15. destruct H15, H3. inversion H2. subst.\n      apply IHeval_expr2 in H16. destruct H16, H4. auto.\n\n  (* CASE EXCEPTION *)\n  * inversion H0; subst.\n    - apply IHeval_expr in H3. destruct H3. congruence.\n    - apply IHeval_expr in H11. auto.\n    - apply IHeval_expr in H7. destruct H7. congruence.\n\n  (* CASE IFCLAUSE EXCEPTION *)\n  * inversion H2; subst.\n    - apply IHeval_expr in H5. destruct H5, H4. inversion H3. subst.\n      pose (P := H1 i H6 _ _ _ H7 _ _ _ H13). destruct P. inversion H4.\n    - apply IHeval_expr in H13. destruct H13. congruence.\n    - apply IHeval_expr in H9. destruct H9, H4. inversion H3. subst.\n      auto.\n\n  (* CALL *)\n  \n   * inversion H8; subst.\n    - apply IHeval_expr1 in H15. destruct H15, H9. destruct H0. subst.\n      apply IHeval_expr2 in H16. destruct H16, H9. destruct H0. subst.\n      epose (P := explist_prefix_eq_rev _ _ _ _ _ _ _ _ _ _ _ H6 H17 IHeval_expr3 _ _ _ _ _ _).\n      inversion P. Unshelve. all: auto.\n    - apply IHeval_expr1 in H15. destruct H15, H9. destruct H0. subst.\n      apply IHeval_expr2 in H16. destruct H16, H9. destruct H0. subst.\n      epose (P := explist_prefix_eq_rev _ _ _ _ _ _ _ _ _ _ _ H6 H21 IHeval_expr3 _ _ _ _ _ _).\n      inversion P. Unshelve. all: auto.\n      \n    - apply IHeval_expr1 in H16. destruct H16, H9. destruct H0. subst.\n      apply IHeval_expr2 in H21. destruct H21, H9. destruct H0. subst.\n    \n      epose (P := exception_equality _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H6 H27 IHeval_expr3 H26\n        _ _ _ _ _ _ _ _).\n      destruct P, H9, H10. subst. auto.\n      Unshelve. all: auto.\n    - apply IHeval_expr1 in H20. destruct H20. congruence. \n    - apply IHeval_expr1 in H20. destruct H20, H9. inversion H9. subst.\n      apply IHeval_expr2 in H21. destruct H21. congruence.  \n    - apply IHeval_expr1 in H15. destruct H15, H9. inversion H0. subst.\n      apply IHeval_expr2 in H16. destruct H16, H10. inversion H9. subst.\n      epose (P := explist_prefix_eq_rev _ _ _ _ _ _ _ _ _ _ _ H6 H17 IHeval_expr3 _ _ _ _ _ _).\n      inversion P. Unshelve. all: auto.\n    - apply IHeval_expr1 in H15. destruct H15, H9. inversion H0. subst.\n      apply IHeval_expr2 in H16. destruct H16, H10. inversion H9. subst.  \n      epose (P := explist_prefix_eq_rev _ _ _ _ _ _ _ _ _ _ _ H6 H17 IHeval_expr3 _ _ _ _ _ _).\n      inversion P. Unshelve. all: auto.\n\n  * inversion H0; subst.\n    - apply IHeval_expr in H7. destruct H7. congruence. (* ezekhez kene egy tactic *)\n    -  apply IHeval_expr in H7. destruct H7. congruence.\n    - apply IHeval_expr in H8. destruct H8. congruence. \n    - apply IHeval_expr in H12. destruct H12. auto.\n    - apply IHeval_expr in H12. destruct H12. congruence.\n    - apply IHeval_expr in H7. destruct H7. congruence.\n    - apply IHeval_expr in H7. destruct H7. congruence.\n  * inversion H1; subst.\n    - apply IHeval_expr1 in H8. destruct H8, H3. inversion H2. subst.\n      apply IHeval_expr2 in H9. destruct H9, H4. congruence.\n    - apply IHeval_expr1 in H8. destruct H8, H3. inversion H2. subst.\n      apply IHeval_expr2 in H9. destruct H9, H4. congruence.\n    - apply IHeval_expr1 in H9. destruct H9, H3. subst.\n      apply IHeval_expr2 in H14. destruct H14 , H4. congruence.\n    - apply IHeval_expr1 in H13. destruct H13, H3. congruence. \n    - apply IHeval_expr1 in H13. destruct H13, H3. inversion H2. subst.\n      apply IHeval_expr2 in H14. destruct H14. inversion H3. subst. auto.  \n     \n    - apply IHeval_expr1 in H8. destruct H8, H3. inversion H2. subst.\n      apply IHeval_expr2 in H9. destruct H9, H4. inversion H3.\n    - apply IHeval_expr1 in H8. destruct H8, H3. inversion H2. subst.\n      apply IHeval_expr2 in H9. destruct H9, H4. inversion H3.  \n  * inversion H9; subst.\n    - apply IHeval_expr1 in H16. destruct H16, H8. inversion H7. subst.\n      apply IHeval_expr2 in H17. destruct H17, H10. inversion H10. congruence.\n    - apply IHeval_expr1 in H16. destruct H16, H8. inversion H7. subst.\n      apply IHeval_expr2 in H17. destruct H17, H10. inversion H10. congruence.\n    - apply IHeval_expr1 in H17. destruct H17, H8. inversion H7. subst.\n      apply IHeval_expr2 in H22. destruct H22, H10. inversion H8. subst.\n      epose (P := explist_prefix_eq _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H5 H27 H28).\n      destruct P. Unshelve. all: auto.\n    - apply IHeval_expr1 in H21. destruct H21, H8. inversion H7. \n    - apply IHeval_expr1 in H21. destruct H21, H8. inversion H7. subst.\n      apply IHeval_expr2 in H22. destruct H22. inversion H8.\n    - apply IHeval_expr1 in H16. destruct H16, H8. inversion H7. subst.\n      apply IHeval_expr2 in H17. destruct H17, H10. inversion H8. subst.\n      epose (P := explist_equality _ _ _ _ _ _ _ H5 H18 _ _ _ _ _ _).\n      destruct P, H11. subst. auto. Unshelve. all: auto. \n    - apply IHeval_expr1 in H16. destruct H16, H8. inversion H7. subst.\n      apply IHeval_expr2 in H17. destruct H17, H10. inversion H8. subst. congruence.\n     \n  * inversion H9; subst.\n    - apply IHeval_expr1 in H16. destruct H16, H8. inversion H7. subst.\n      apply IHeval_expr2 in H17. destruct H17, H10. inversion H8. subst. congruence.\n   - apply IHeval_expr1 in H16. destruct H16, H8. inversion H7. subst.\n      apply IHeval_expr2 in H17. destruct H17, H10. inversion H8. subst. congruence.\n    - apply IHeval_expr1 in H17. destruct H17, H8. inversion H7. subst.\n      apply IHeval_expr2 in H22. destruct H22, H10. inversion H8. subst. \n      epose (P := explist_prefix_eq _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H5 H27 H28).\n      destruct P. Unshelve. all: auto.\n    - apply IHeval_expr1 in H21. destruct H21. congruence.\n    - apply IHeval_expr1 in H21. destruct H21, H8. inversion H7. subst.\n      apply IHeval_expr2 in H22. destruct H22. congruence.\n    - apply IHeval_expr1 in H16. destruct H16, H8. inversion H7. subst.\n      apply IHeval_expr2 in H17. destruct H17, H10. inversion H8. subst. congruence.\n    - apply IHeval_expr1 in H16. destruct H16, H8. inversion H7. subst.\n      apply IHeval_expr2 in H17. destruct H17, H10. inversion H8. subst.\n      epose (P := explist_equality _ _ _ _ _ _ _ H5 H18 _ _ _ _ _ _).\n      destruct P, H11. subst. auto. Unshelve. all: auto. \n\n\n  (* PRIMOP *)\n  * inversion H6; subst.\n    - epose (P := explist_prefix_eq_rev _ _ _ _ _ _ _ _ _ _ _ H4 H12 IHeval_expr _ _ _ _ _ _).\n      inversion P. Unshelve. all: auto.\n    - epose (P := exception_equality _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H4 H22 IHeval_expr H17\n        _ _ _ _ _ _ _ _).\n      destruct P, H7, H8. subst. auto.\n      Unshelve. all: auto.\n\n  (* APP FUNEXP EXCEPTION *)\n  * inversion H0; subst.\n    - apply IHeval_expr in H4. destruct H4. congruence.\n    - apply IHeval_expr in H11. auto.\n    - apply IHeval_expr in H7. destruct H7. congruence.\n    - apply IHeval_expr in H6. destruct H6. congruence.\n    - apply IHeval_expr in H6. destruct H6. congruence.\n\n  (* APP PARAM EXCEPTION *)\n  * inversion H7; subst.\n    - apply IHeval_expr1 in H11. destruct H11, H8. inversion H0. subst.\n      epose (P := explist_prefix_eq_rev _ _ _ _ _ _ _ _ _ _ _ H5 H19 IHeval_expr2 _ _ _ _ _ _).\n      inversion P.\n      Unshelve. all: auto.\n    - apply IHeval_expr1 in H18. destruct H18. congruence.\n    - apply IHeval_expr1 in H14. destruct H14, H8. inversion H0. subst.\n      epose (P := exception_equality _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H5 H24 IHeval_expr2 H19\n        _ _ _ _ _ _ _ _).\n      destruct P, H9, H11. subst. auto.\n      Unshelve. all: auto.\n    - apply IHeval_expr1 in H13. destruct H13, H8. inversion H0. subst.\n      epose (P := explist_prefix_eq_rev _ _ _ _ _ _ _ _ _ _ _ H5 H14 IHeval_expr2 _ _ _ _ _ _).\n      inversion P.\n      Unshelve. all: auto.\n    - apply IHeval_expr1 in H13. destruct H13, H8. inversion H0. subst.\n      epose (P := explist_prefix_eq_rev _ _ _ _ _ _ _ _ _ _ _ H5 H14 IHeval_expr2 _ _ _ _ _ _).\n      inversion P.\n      Unshelve. all: auto.\n\n  (* APP BADFUN EXCEPTION *)\n  * inversion H8; subst.\n    - apply IHeval_expr in H12. destruct H12, H7. inversion H6. subst.\n      congruence.\n    - apply IHeval_expr in H19. destruct H19. congruence.\n    - apply IHeval_expr in H15. destruct H15, H7. inversion H6. subst.\n      epose (P := explist_prefix_eq _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H4 H20 H25).\n      inversion P.\n      Unshelve. all: auto.\n    - apply IHeval_expr in H14. destruct H14, H7. inversion H6. subst.\n      epose (P := explist_equality _ _ _ _ _ _ _ H4 H15 _ _ _ _ _ _).\n      destruct P. destruct H9. subst. auto. Unshelve. all: auto.\n    - apply IHeval_expr in H14. destruct H14, H7. inversion H6. subst.\n      congruence.\n\n  (* APP BADARITY EXCEPTION *)\n  * inversion H8; subst.\n    -  apply IHeval_expr in H12. destruct H12, H7. inversion H6. subst.\n      congruence.\n    - apply IHeval_expr in H19. destruct H19. congruence.\n    - apply IHeval_expr in H15. destruct H15, H7. inversion H6. subst.\n      epose (P := explist_prefix_eq _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H4 H20 H25).\n      inversion P.\n      Unshelve. all: auto.\n    - apply IHeval_expr in H14. destruct H14, H7. inversion H6. subst.\n      congruence.\n    - apply IHeval_expr in H14. destruct H14, H7. inversion H6. subst.\n      epose (P := explist_equality _ _ _ _ _ _ _ H4 H15 _ _ _ _ _ _).\n      destruct P. destruct H9. subst. auto.\n      Unshelve. all: auto.\n\n  (* LET EXCEPTION *)\n  * inversion H0; subst.\n    - apply IHeval_expr in H8. destruct H8. congruence.\n    - apply IHeval_expr in H12. auto.\n\n  (* SEQ EXCEPTION *)\n  * inversion H0; subst.\n    - apply IHeval_expr in H7. destruct H7. congruence.\n    - apply IHeval_expr in H11. auto.\n\n\n  (* MAP EXCEPTION *)\n  * inversion H7; subst.\n    - assert (length eff = length vals). \n      { \n        unfold vals.\n        case_eq (modulo_2 (length eff)); intros.\n        * rewrite e in *. rewrite length_make_map_vals. rewrite Nat.add_0_r in H1.\n          2: lia. rewrite H1. simpl. apply n_div_2_mod_0. lia.\n        * rewrite e in *. rewrite length_make_map_vals2. 2: lia.\n          rewrite H0. apply n_div_2_mod_1. lia.\n      }\n      rewrite H2 in H5, IHeval_expr.\n      epose (P := explist_prefix_eq_rev _ _ _ _ _ _ _ _ _ _ _ H5 H13 IHeval_expr _ _ _ _ _ _).\n      inversion P.\n      Unshelve.\n      + unfold vals, exps. rewrite length_make_map_exps.\n        case_eq (modulo_2 (length eff)); intros.\n        ** rewrite e in *. rewrite length_make_map_vals. rewrite Nat.add_0_r in H1.\n           2: lia. rewrite H1. rewrite <- n_div_2_mod_0. lia. lia.\n        ** rewrite e in *. rewrite length_make_map_vals2. 2: lia.\n           rewrite H0. rewrite <- n_div_2_mod_1. lia. lia.\n      + lia.\n      + unfold vals0. rewrite length_make_map_vals. 2: lia.\n        unfold exps. rewrite length_make_map_exps. lia.\n      + unfold exps. rewrite length_make_map_exps. lia.\n      + unfold exps. rewrite length_make_map_exps. lia.\n      + lia.\n    - epose (P := exception_equality _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H5 H19 IHeval_expr H14\n        _ _ _ _ _ _ _ _).\n      destruct P, H8, H12. subst. apply IHeval_expr in H19. auto.\n      Unshelve.\n      all: try lia.\n      + unfold vals. case_eq (modulo_2 (length eff)); intros.\n        ** rewrite e in *. rewrite length_make_map_vals. rewrite Nat.add_0_r in H1.\n          2: lia. rewrite H1. rewrite <- n_div_2_mod_0. lia. lia.\n        ** rewrite e in *. rewrite length_make_map_vals2. 2: lia.\n          rewrite H0. rewrite <- n_div_2_mod_1. lia. lia.\n      + unfold exps. rewrite length_make_map_exps. lia.\n      + unfold vals0. case_eq (modulo_2 (length eff4)); intros.\n        ** rewrite e in *. rewrite length_make_map_vals. rewrite Nat.add_0_r in H11.\n           2: lia. rewrite H11. rewrite <- n_div_2_mod_0. lia. lia.\n        ** rewrite e in *. rewrite length_make_map_vals2. 2: lia.\n           rewrite H10. rewrite <- n_div_2_mod_1. lia. lia.\n      + unfold exps. rewrite length_make_map_exps. lia.\nQed.\n\n\n(** Helper about variables contained in a list of expression *)\nProposition list_variables_not_in (x : Var) (exps : list Expression) :\n~ In x ((flat_map variables exps)) ->\n(forall exp : Expression, In exp exps -> ~ In x (variables exp)).\nProof.\n  intros. induction exps.\n  * inversion H0.\n  * simpl in H. assert (~ In x (variables a) /\\ ~ In x (flat_map variables exps)).\n    {\n      unfold not in *. split; intros.\n      * apply H. apply in_or_app. left. assumption.\n      * apply H. apply in_or_app. right. assumption.\n    }\n    inversion H1. inversion H0.\n    - subst. assumption.\n    - apply IHexps.\n      + assumption.\n      + assumption.\nQed.\n\n(** Helpers regarding variables and their containment *)\nProposition var_not_in_neq (var s : Var):\n  ~(In var (variables (EVar s))) ->\n  s <> var.\nProof.\n  intros. unfold not in *. intro. apply H. rewrite H0. simpl. left. reflexivity.\nQed.\n\nProposition var_neq_not_in (var s : Var) :\n  s <> var -> \n  ~(In var (variables (EVar s))).\nProof.\n  intros. unfold not in *. intro. destruct (string_dec s var).\n  * exact (H e).\n  * apply H. inversion H0.\n    - assumption.\n    - inversion H1.\nQed.\n\n(** New variable binding doesn't affect previous ones *)\nProposition irrelevant_append (env : Environment) (s var : Var) (val : Value) (t : option ValueSequence):\n  s <> var ->\n  get_value env (inl s) = t <->\n  get_value (append_vars_to_env [var] [val] env) (inl s) = t.\nProof.\n  intros; split; intro.\n  * simpl. induction env.\n    - simpl in *. subst. apply eqb_neq in H. rewrite H. reflexivity.\n    - destruct a. assert (get_value ((s0, v) :: env) (inl s) = t). { auto. }\n      unfold get_value in H0. case_eq (var_funid_eqb (inl s) s0).\n      + intro. rewrite H2 in H0. subst. inversion H2. destruct s0.\n        ** apply eqb_eq in H3. subst. simpl. apply eqb_neq in H. rewrite H. simpl.\n           rewrite eqb_refl. reflexivity.\n        ** inversion H3.\n      + intros. simpl in H1. destruct s0.\n        ** inversion H2. rewrite H4 in H1. simpl. destruct ((v0 =? var)%string).\n          ++ simpl. apply eqb_neq in H. rewrite H. assumption.\n          ++ simpl. rewrite H4. apply eqb_neq in H. simpl. exact (IHenv H1).\n        ** simpl. exact (IHenv H1).\n  * simpl in H0. induction env.\n    - simpl in H0. apply eqb_neq in H. rewrite H in H0. subst. simpl. reflexivity.\n    - destruct a. simpl in *. case_eq (var_funid_eqb s0 (inl var)).\n      + intro. destruct s0.\n        ** inversion H1. apply eqb_eq in H3. rewrite H3. apply eqb_neq in H. rewrite H.\n           rewrite H1 in H0. simpl in H0. rewrite H in H0. assumption.\n        **  rewrite H1 in H0. simpl in H0. apply eqb_neq in H. rewrite H in H0. assumption.\n      + intro. destruct s0.\n        ** inversion H1. case_eq ((s =? v0)%string); intro.\n          -- rewrite H1 in H0. simpl in H0. rewrite H2 in H0. assumption.\n          -- rewrite H1 in H0. simpl in H0. rewrite H2 in H0. exact (IHenv H0).\n        ** rewrite H1 in H0. simpl in H0. exact (IHenv H0).\nQed.\n\n(** New variable binding doesn't affect previous ones *)\nProposition irrelevant_append_eq (env : Environment) (s var : Var) (val : Value):\n  s <> var ->\n  get_value env (inl s) = get_value (append_vars_to_env [var] [val] env) (inl s).\nProof.\n  intros. pose (IRA := irrelevant_append env s var val (get_value env (inl s)) H).\n  assert (get_value env (inl s) = get_value env (inl s)). reflexivity. inversion IRA.\n  pose (P1 := H1 H0). apply eq_sym. assumption.\nQed.\n\n(* Theorem variable_irrelevancy (env: Environment) (cl : Closures) (e : Expression) (t val : Value) (var : Var) :\n  ~(In var (variables e)) -> (forall env' a b, t <> VClosure env' a b) ->\n  |env, cl, e| -e> t <->\n  |append_vars_to_env [var] [val] env, cl, e| -e> t.\nProof.\n  intro. split; intro. \n  * induction H1 using eval_expr_ind_extended.\n    - apply eval_lit.\n    - assert (get_value env (inl s) = get_value (append_vars_to_env [var] [val] env) (inl s)). { apply (var_not_in_neq) in H. pose (irrelevant_append_eq env s var val H). assumption. } rewrite H1. apply eval_var.\n    - admit.\n    - pose (H0 (inl env) (snd (split l)) e).  unfold not in n. assert (VClosure (inl env) (snd (split l)) e = VClosure (inl env) (snd (split l)) e). reflexivity. pose (n H1). inversion f.\n    - apply eval_tuple.\n      + assumption.\n      + intros. apply H3; try(assumption).\n        ** simpl in H. apply (list_variables_not_in) with (exps := exps). assumption. apply in_combine_l in H4. assumption.\n        ** intros.\nQed.*)\n\n(** Last append result *)\nProposition get_value_here (env : Environment) (var : Var + FunctionIdentifier) (val : Value):\nget_value (insert_value env var val) var = Some [val].\nProof.\n  induction env.\n  * simpl. rewrite var_funid_eqb_refl. reflexivity.\n  * simpl. destruct a. case_eq (var_funid_eqb s var); intro.\n    - simpl. rewrite var_funid_eqb_refl. reflexivity.\n    - simpl. rewrite var_funid_eqb_sym, H. assumption.\nQed.\n\n(** Previous append result *)\nProposition get_value_there (env : Environment) (var var' : Var + FunctionIdentifier) \n     (val : Value):\nvar <> var' ->\nget_value (insert_value env var val) var' = get_value env var'.\nProof.\n  intro. induction env.\n  * simpl. apply var_funid_eqb_neq in H. rewrite var_funid_eqb_sym in H. rewrite H. reflexivity.\n  * simpl. destruct a. case_eq (var_funid_eqb s var); intro.\n    - apply var_funid_eqb_eq in H0. assert (var <> var'). auto. rewrite <- H0 in H.\n      apply var_funid_eqb_neq in H. rewrite var_funid_eqb_sym in H. rewrite H. simpl. apply var_funid_eqb_neq in H1.\n      rewrite var_funid_eqb_sym in H1. rewrite H1. reflexivity.\n    - simpl. case_eq (var_funid_eqb var' s); intros.\n      + reflexivity.\n      + apply IHenv.\nQed.\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/BigStep/SemanticsProofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.542863297964157, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.2883740723391505}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n  Copyright 201% 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\n\nRequire Export alphaeq.\nRequire Export cvterm2.\nRequire Export terms_props.\n\nLemma fold_image {p} :\n  forall (a b : @NTerm p), oterm (Can NImage) [ nobnd a, nobnd b ] = mk_image a b.\nProof.\n  sp.\nQed.\n\nLemma lsubstc_mk_image {o} :\n  forall A B sub,\n  forall wA : wf_term A,\n  forall wB : @wf_term o B,\n  forall w  : wf_term (mk_image A B),\n  forall cA : cover_vars A sub,\n  forall cB : cover_vars B sub,\n  forall c  : cover_vars (mk_image A B) sub,\n   lsubstc (mk_image A B) w sub c =\n             mkc_image (lsubstc A wA sub cA)\n                         (lsubstc B wB sub cB).\nProof.\n  sp; unfold lsubstc; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r.\n  allrw @fold_nobnd;\n  rw @fold_image; auto.\nQed.\n\nLemma lsubstc_mk_image_ex {p} :\n  forall t1 t2 sub,\n  forall w  : wf_term (@mk_image p t1 t2),\n  forall c  : cover_vars (mk_image t1 t2) sub,\n    {w1 : wf_term t1\n     & {w2 : wf_term t2\n     & {c1 : cover_vars t1 sub\n     & {c2 : cover_vars t2 sub\n        & lsubstc (mk_image t1 t2) w sub c\n             = mkc_image (lsubstc t1 w1 sub c1)\n                        (lsubstc t2 w2 sub c2)}}}}.\nProof.\n  sp.\n\n  assert (wf_term t1) as w1.\n  { allrw <- @wf_image_iff; sp. }\n\n  assert (wf_term t2) as w2.\n  { allrw <- @wf_image_iff; sp. }\n\n  assert (cover_vars t1 sub) as c1.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  assert (cover_vars t2 sub) as c2.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists w1 w2 c1 c2.\n  apply lsubstc_mk_image.\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_image.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.2883740644816865}}
{"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(** Preservation of typing during register allocation. *)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import Errors.\nRequire Import AST.\nRequire Import Op.\nRequire Import Registers.\nRequire Import RTL.\nRequire Import Locations.\nRequire Import LTL.\nRequire Import Coloring.\nRequire Import Coloringproof.\nRequire Import Allocation.\nRequire Import Allocproof.\nRequire Import RTLtyping.\nRequire Import LTLtyping.\nRequire Import Conventions.\n\n(** This file proves that register allocation (the translation from\n  RTL to LTL defined in file [Allocation]) preserves typing:\n  given a well-typed RTL input, it produces LTL code that is\n  well-typed. *)\n\nSection WITHEF.\nContext `{Hsc: SyntaxConfiguration}.\n\nSection TYPING_FUNCTION.\n\nVariable f: RTL.function.\nVariable env: regenv.\nVariable live: PMap.t Regset.t.\nVariable alloc: reg -> loc.\nVariable tf: LTL.function.\n\nHypothesis TYPE_RTL: type_function f = OK env.\nHypothesis LIVE: analyze f = Some live.\nHypothesis ALLOC: regalloc f live (live0 f live) env = Some alloc.\nHypothesis TRANSL: transf_function f = OK tf.\n\nLemma wt_rtl_function: RTLtyping.wt_function f env.\nProof.\n  apply type_function_correct; auto.\nQed.\n\nLemma alloc_type: forall r, Loc.type (alloc r) = env r.\nProof.\n  intro. eapply regalloc_preserves_types; eauto.\nQed.\n\nLemma alloc_types:\n  forall rl, List.map Loc.type (List.map alloc rl) = List.map env rl.\nProof.\n  intros. rewrite list_map_compose. apply list_map_exten.\n  intros. symmetry. apply alloc_type. \nQed.\n\nLemma alloc_acceptable: \n  forall r, loc_acceptable (alloc r).\nProof.\n  intros. eapply regalloc_acceptable; eauto.\nQed.\n\nLemma allocs_acceptable:\n  forall rl, locs_acceptable (List.map alloc rl).\nProof.\n  intros. eapply regsalloc_acceptable; eauto.\nQed.\n\nRemark transf_unroll:\n  tf = transf_fun f live alloc.\nProof.\n  generalize TRANSL. unfold transf_function.\n  rewrite TYPE_RTL. rewrite LIVE. rewrite ALLOC. congruence.\nQed.\n\nLemma valid_successor_transf:\n  forall s,\n  RTLtyping.valid_successor f s ->\n  LTLtyping.valid_successor tf s.\nProof.\n  unfold RTLtyping.valid_successor, LTLtyping.valid_successor.\n  intros s [i AT].\n  rewrite transf_unroll; simpl. rewrite PTree.gmap. \n  rewrite AT. exists (transf_instr f live alloc s i). auto.\nQed.  \n\nHint Resolve alloc_acceptable allocs_acceptable: allocty.\nHint Rewrite alloc_type alloc_types: allocty.\nHint Resolve valid_successor_transf: allocty.\n\n(** * Type preservation during translation from RTL to LTL *)\n\nLtac WT := \n  constructor; auto with allocty; autorewrite with allocty; auto.\n\nLemma wt_transf_instr:\n  forall pc instr,\n  RTLtyping.wt_instr env f instr ->\n  f.(RTL.fn_code)!pc = Some instr ->\n  wt_instr tf (transf_instr f live alloc pc instr).\nProof.\n  intros. inv H; simpl.\n  (* nop *)\n  WT.\n  (* move *)\n  destruct (Regset.mem r live!!pc).\n  destruct (is_redundant_move Omove (r1 :: nil) r alloc); WT.\n  WT.\n  (* other ops *)\n  destruct (Regset.mem res live!!pc).\n  destruct (is_redundant_move op args res alloc); WT.\n  WT.\n  (* load *)\n  destruct (Regset.mem dst live!!pc); WT.\n  (* store *)\n  WT.\n  (* call *)\n  exploit regalloc_correct_1; eauto. unfold correct_alloc_instr. \n  intros [A1 [A2 A3]]. \n  WT.\n  destruct ros; simpl; auto. \n  split. autorewrite with allocty; auto.\n  split. auto with allocty. auto.\n  (* tailcall *)\n  exploit regalloc_correct_1; eauto. unfold correct_alloc_instr. \n  intro A1.\n  WT.\n  destruct ros; simpl; auto. \n  split. autorewrite with allocty; auto.\n  split. auto with allocty. auto.\n  rewrite transf_unroll; auto.\n  (* builtin *)\n  WT.\n  (* cond *)\n  WT.\n  (* jumptable *)\n  WT. \n  (* return *)\n  WT.\n  rewrite transf_unroll; simpl. \n  destruct optres; simpl. autorewrite with allocty. auto. auto.\n  destruct optres; simpl; auto with allocty.\nQed.\n\nEnd TYPING_FUNCTION.\n\nLemma wt_transf_function:\n  forall f tf,\n  transf_function f = OK tf -> wt_function tf.\nProof.\n  intros. generalize H; unfold transf_function.\n  caseEq (type_function f). intros env TYP. \n  caseEq (analyze f). intros live ANL.\n  change (transfer f (RTL.fn_entrypoint f)\n                     live!!(RTL.fn_entrypoint f))\n    with (live0 f live).\n  caseEq (regalloc f live (live0 f live) env).\n  intros alloc ALLOC.\n  intro EQ; injection EQ; intro.\n  assert (RTLtyping.wt_function f env). apply type_function_correct; auto.\n  inversion H1.\n  constructor; rewrite <- H0; simpl.\n  rewrite (alloc_types _ _ _ _ ALLOC). auto.\n  eapply regsalloc_acceptable; eauto.\n  eapply regalloc_norepet_norepet; eauto.\n  eapply regalloc_correct_2; eauto.\n  intros until instr. rewrite PTree.gmap. \n  caseEq (RTL.fn_code f)!pc; simpl; intros.\n  inversion H3. eapply wt_transf_instr; eauto. congruence. discriminate.\n  eapply valid_successor_transf; eauto. congruence. \n  congruence. congruence. congruence.\nQed.\n\nLemma wt_transf_fundef:\n  forall f tf,\n  transf_fundef f = OK tf -> wt_fundef tf.\nProof.\n  intros until tf; destruct f; simpl. \n  caseEq (transf_function f); simpl. intros g TF EQ. inversion EQ.\n  constructor. eapply wt_transf_function; eauto.\n  congruence.\n  intros. inversion H. constructor. \nQed.\n\nLemma program_typing_preserved:\n  forall (p: RTL.program) (tp: LTL.program),\n  transf_program p = OK tp ->\n  LTLtyping.wt_program tp.\nProof.\n  intros; red; intros.\n  generalize (transform_partial_program_function transf_fundef p i f H H0).\n  intros [f0 [IN TRANSF]].\n  apply wt_transf_fundef with f0; auto.\nQed.\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/Alloctyping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.2883740644816865}}
{"text": "#[global]\nSet Primitive Projections.\n#[global]\nUnset Printing Primitive Projection Parameters.\n\n#[global]\nSet Universe Polymorphism.\n\n#[global]\nSet Default Goal Selector \"!\".\n\nRequire Import Coq.Unicode.Utf8.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Coq.Setoids.Setoid.\nRequire Import Coq.Classes.SetoidClass.\nRequire Psatz.\nRequire Import Recdef.\n\nImport IfNotations.\nImport ListNotations.\n\nClose Scope nat.\n\nReserved Notation \"'some' x .. y , P\"\n         (at level 200, x binder, y binder, right associativity,\n          format \"'[ ' '[ ' 'some'  x .. y ']' ,  '/' P ']'\").\n\n#[universes(cumulative)]\nRecord someT [A] (P: A → Type) := some_intro { head: A ; tail: P head ; }.\n\nArguments some_intro [A P].\nArguments head [A P].\nArguments tail [A P].\n\nModule SomeNotations.\n  Add Printing Let someT.\n\n  Notation \"'some' x .. y , P\" := (someT (λ x, .. (someT (λ y,  P)) .. )) : type_scope.\nEnd SomeNotations.\n\n\nModule CylPoly.\n  #[universes(cumulative)]\n  Record Poly := {\n    pos: Type ;\n    dir: pos → string → Type ;\n  }.\n\n  Coercion pos: Poly >-> Sortclass.\n\n  Definition CoYo (Γ: string → Type) : Poly := {|\n    pos := unit ;\n    dir _ := Γ ;\n  |}.\n\n  Definition K A: Poly := {| dir (_: A) _ := Empty_set |}.\n\n  Definition I: Poly := {|\n    pos := unit ;\n    dir _ _ := unit  ;\n  |}.\n\n  Record ext (P: Poly) (Γ: string → Type) :=\n    sup {\n        tag: _ ;\n        field v: dir P tag v → Γ v ;\n      }.\n\n  Arguments sup {P Γ}.\n  Arguments tag {P Γ}.\n  Arguments field {P Γ}.\n\n  Coercion ext: Poly >-> Funclass.\n\n  Definition map {H: Poly} {A B} (f: ∀ v, A v → B v) (x: H A): H B :=\n      sup (tag x) (fun v y => f v (field x v y)).\n\n  Definition Π {A: Type} (p: A → Poly): Poly :=\n    {|\n    pos := ∀ i, pos (p i) ;\n    dir s x := someT (fun i => dir (p i) (s i) x) ;\n    |}.\n  Definition exp A B := Π (λ _: A, B).\n\n Definition bind (p: Poly) (q: string → Poly): Poly :=\n    {|\n    pos := p (λ x, pos (q x)) ;\n    dir s x :=\n      someT (fun i => dir (q x) (field s x i) x) ;\n    |}.\n\n  Definition compose x q p := bind p (λ y, exp (y = x) q).\n\n  Definition Σ {A} (p: A → Poly): Poly :=\n    {|\n    pos := someT (fun i => pos (p i)) ;\n    dir s x := dir (p (head s)) (tail s) x ;\n    |}.\n\n  Definition prod (p q: Poly): Poly :=\n    {|\n    pos := pos p * pos q ;\n    dir '(x, y) v := dir p x v + dir q y v ;\n    |}.\n\n  Definition sum (p q: Poly): Poly :=\n    {|\n    pos := pos p + pos q ;\n    dir s v :=\n      match s with\n      | inl x' => dir p x' v\n      | inr x' => dir q x' v\n      end ;\n    |}.\n\n\n  (* FIXME hacky *)\n  Definition V x: Poly := CoYo (λ y, x = y).\n  Definition subst (x: string) (A: Type) Γ := λ y, if string_dec x y then A else Γ y.\n\n  Definition scope (x: string) (A: Type) (Γ: string → Type) :=\n    λ y, {_: A | x = y } + { _: Γ y | x ≠ y }.\n\n  Definition All x S: Poly := CoYo (λ y, x = y → S).\n\n  Infix \"*\" := prod.\n  Infix \"+\" := sum.\n\n\n  (* FIXME not good *)\n  Definition diag (x y: string) :=\n    Σ (λ (Γ: string → Type), {|\n         pos := Γ x → Γ y ;\n         dir _ := Γ ;\n       |}).\n\n  Infix \"~>\" := diag (at level 30).\n\n  Inductive w x (p: Poly) (Γ: string → Type) :=\n  | rec (_: p (scope x (w x p Γ) Γ)).\n\n  Definition mt := λ _: string, Empty_set.\n  Definition put (x: string) (A: Type) Γ := λ y, if string_dec x y then A else Γ y.\n\n  Fixpoint oflist (l: list (string * Type)): string → Type :=\n    match l with\n    | nil => mt\n    | cons (X, A) T => put X A (oflist T)\n    end.\n\n  Open Scope string_scope.\n\n  Example plist A := w \"x\" (K unit + K A * V \"x\") mt.\n  Example pnil {A}: plist A.\n  Proof.\n    cbn in *.\n    exists.\n    exists (inl tt).\n    cbn in *.\n    intros ? ?.\n    contradiction.\n  Defined.\n\n  Example pcons {A} (h: A) (t: plist A): plist A.\n  Proof.\n    cbn in *.\n    exists.\n    exists (inr (h, tt)).\n    cbn in *.\n    intros ? [?|?].\n    1: contradiction.\n    subst.\n    left.\n    exists.\n    2: reflexivity.\n    apply t.\n  Defined.\n\n  Fixpoint poflist {A} (l: list A): plist A :=\n    match l with\n    | nil => pnil\n    | cons H T => pcons H (poflist T)\n    end.\n\n  Example foo {A B} (x: A) (y: B): ext (V \"x\" * V \"y\") (oflist [(\"x\", A) ; (\"y\", B)]).\n    exists (tt, tt).\n    intros ? [?|?].\n    all: cbn in *.\n    all: subst.\n    - apply x.\n    - apply y.\n  Defined.\n\n  Example gar {A B} (f: A → B): ext (\"x\" ~> \"y\") (oflist [(\"x\", A) ; (\"y\", B)]).\n  Proof.\n    cbn.\n    eexists (some_intro (oflist [(\"x\", A) ; (\"y\", B)]) _).\n    Unshelve.\n    2: {\n      cbn.\n      apply f.\n    }\n    cbn.\n    intros.\n    auto.\n  Defined.\n\n  Example bar := poflist [\"foo\" ; \"bar\" ; \"xar\"].\nEnd CylPoly.\n\n(* Free monad on a polynomial endofunctor *)\nModule Poly.\n  #[universes(cumulative)]\n   Record Poly := {\n    pos: Type ;\n    dir: pos → Type ;\n  }.\n\n  Coercion pos: Poly >-> Sortclass.\n\n  (* Definition K A: Poly := {| dir (_: A) := Empty_set |}. *)\n\n  Record ext (P: Poly) A :=\n    sup {\n        tag: _ ;\n        field: dir P tag → A ;\n      }.\n\n  Arguments sup {P A}.\n  Arguments tag {P A}.\n  Arguments field {P A}.\n\n  Infix \"!\" := field (at level 30).\n\n  Coercion ext: Poly >-> Funclass.\n\n  Definition X: Poly := {| dir (_: unit) := unit |}.\n\n  Definition CoYo (A:  Type) : Poly := {|\n    pos := unit ;\n    dir _ := A ;\n  |}.\n\n  Definition compose (p q: Poly): Poly :=\n    {|\n    pos := p (pos q) ;\n    dir s := someT (fun i => dir q (s ! i)) ;\n    |}.\n  Infix \"∘\" := compose (at level 30).\n\n  Definition Π {A} (p: A → Poly): Poly :=\n    {|\n    pos := ∀ i, pos (p i) ;\n    dir s := someT (fun i => dir (p i) (s i)) ;\n    |}.\n  Definition Σ {A} (p: A → Poly): Poly :=\n    {|\n    pos := someT (fun i => pos (p i)) ;\n    dir s := dir (p (head s)) (tail s) ;\n    |}.\n\n  Definition prod (p q: Poly): Poly :=\n    {|\n    pos := pos p * pos q ;\n    dir '(x, y) := dir p x + dir q y ;\n    |}.\n\n  Definition sum (p q: Poly): Poly :=\n    {|\n    pos := pos p + pos q ;\n    dir s :=\n      match s with\n      | inl x' => dir p x'\n      | inr x' => dir q x'\n      end ;\n    |}.\n\n  Infix \"*\" := prod.\n  Infix \"+\" := sum.\n\n  Definition exp A B := Π (λ _: A, B).\nEnd Poly.\n\nModule PolyCat.\n  Module Import Cat.\n    Inductive Obj := init | term | sum (_ _: Obj) | exp (_ _: Obj).\n    Inductive Mor: Obj → Obj → Type :=\n    | id A: Mor A A\n    | compose {A B C}: Mor B C → Mor A B → Mor A C\n    | absurd {A}: Mor init A\n    .\n  End Cat.\n\n  Module Import Dis.\n    Record Dis := {\n      pos: Type ;\n      dir: pos → Obj ;\n    }.\n\n    Record Mor (A B: Dis) := {\n      pos_Mor: pos A → pos B  ;\n      dir_Mor x: Cat.Mor (dir B (pos_Mor x)) (dir A x) ;\n    }.\n\n    Arguments pos_Mor {A B}.\n    Arguments dir_Mor {A B}.\n\n    Record ext (P: Dis) (x: Obj) := sup {\n       tag: pos P ;\n       field: Cat.Mor (dir P tag) x ;\n    }.\n\n    Arguments sup {P x}.\n    Arguments tag {P x}.\n    Arguments field {P x}.\n\n    Coercion ext: Dis >-> Funclass.\n\n    Definition Yo (x: Obj): Dis := {| dir (_: unit) := x |}.\n    Definition K (x: Type): Dis := {| dir (_: x) := init |}.\n\n    Definition Π {A} (p: A → Dis): Dis :=\n    {|\n      pos := A * (∀ i, pos (p i)) ;\n      dir '(x, f) := dir (p x) (f x) ;\n    |}.\n\n    Definition Σ {A} (p: A → Dis): Dis := {|\n      pos := someT (fun i => pos (p i)) ;\n      dir s := dir (p (head s)) (tail s) ;\n    |}.\n\n    Definition prod (p q: Dis): Dis := {|\n      pos := pos p * pos q ;\n      dir '(x, y) := sum (dir p x) (dir q y) ;\n     |}.\n\n    Definition sum (p q: Dis): Dis := {|\n      pos := pos p + pos q ;\n      dir v :=\n        match v with\n        | inl v' => dir p v'\n        | inr v' => dir q v'\n        end ;\n     |}.\n  End Dis.\n\n  #[universes(cumulative)]\n  Record Poly := {\n    pos: Dis ;\n    dir: Dis.Mor pos {| pos := Dis ; dir _ := init ; |} ;\n  }.\n\n  #[program]\n  Definition X: Poly := {|\n    pos := Yo term ;\n    dir := {|\n            pos_Mor _ := Yo term ;\n            dir_Mor _ := absurd ;\n           |} ;\n  |}.\n\n  #[program]\n  Definition CoYo (A: Dis) : Poly := {|\n    pos := Yo term  ;\n    dir := {|\n            pos_Mor _ := A ;\n            dir_Mor _ := absurd ;\n          |}\n  |}.\n\n  (* Definition comp (p q: Poly): Poly := *)\n  (*   {| *)\n  (*   pos := p (pos q) ; *)\n  (*   dir s := someT (fun i => dir q (field s i)) ; *)\n  (*   |}. *)\n  (* Infix \"∘\" := compose (at level 30). *)\n\n  #[program]\n  Definition Σ {A} (p: A → Poly): Poly :=\n    {|\n    pos := Σ (fun i => pos (p i)) ;\n    dir :=\n      {|\n        pos_Mor x := pos (p (head x)) ;\n        dir_Mor x := _ ;\n       |}\n    |}.\n\n  #[program]\n  Definition Π {A} (p: A → Poly): Poly :=\n    {|\n    pos := Π (λ i, pos (p i)) ;\n    dir := {|\n            pos_Mor '(x, f) := _ ;\n          |}\n  |}.\n\n  Next Obligation.\n  Proof.\n    cbn in *.\n    apply (dir (p (head x))).\n  Defined.\n\n  #[program]\n  Definition K A: Poly := {|\n    pos := A ;\n    dir := {|\n            pos_Mor _ := Yo init ;\n            dir_Mor _ := absurd ;\n          |} ;\n  |}.\n\n\n  #[program]\n  Definition prod (p q: Poly): Poly :=\n    {|\n     pos := Dis.prod (pos p) (pos q) ;\n     dir :=\n       {|\n         pos_Mor '(x, y) := Yo (Cat.sum (Dis.dir (pos p) x) (Dis.dir (pos q) y)) ;\n         dir_Mor _ := absurd ;\n       |} ;\n    |}.\n\n  #[program]\n  Definition sum (p q: Poly): Poly :=\n    {|\n    pos := sum (pos p) (pos q) ;\n    dir :=\n      {|\n        pos_Mor v :=\n          match v with\n          | inl v' => Yo (Dis.dir (pos p) v')\n          | inr v' => Yo (Dis.dir (pos q) v')\n          end ;\n        dir_Mor _ := absurd ;\n      |}\n    |}.\n\n  Infix \"*\" := prod.\n  Infix \"+\" := sum.\n\n  (* Definition exp A B := Π (λ _: A, B). *)\nEnd PolyCat.\n\nModule Span.\n  #[universes(cumulative)]\n   Record span A B := {\n    s: Type ;\n    π1: s → A ;\n    π2: s → B ;\n  }.\n\n  Arguments s {A B}.\n  Arguments π1 {A B}.\n  Arguments π2 {A B}.\n  Coercion s: span >-> Sortclass.\n\n  Definition id A: span A A := {| π1 x := x ; π2 x := x |}.\n  Definition compose {A B C} (f: span B C) (g: span A B) := {|\n    s := { xy : s f * s g | π1 f (fst xy) = π2 g (snd xy) } ;\n    π1 x := π1 g (snd (proj1_sig x)) ;\n    π2 x := π1 f (fst (proj1_sig x)) ;\n  |}.\n\n  Infix \"∘\" := compose (at level 30).\n\n  #[universes(cumulative)]\n  Class Span_Mor {A B} {s: span A B} {t: span A B} (f: s → t) := {\n    map_π1 x: π1 t (f x) = π1 s x ;\n    map_π2 x: π2 t (f x) = π2 s x ;\n  }.\n\n  Inductive ext {A B} (p: span A B): A → B → Type :=\n  | sup x : ext p (π1 p x) (π2 p x).\n\n  Coercion ext: span >-> Funclass.\n\n\n  Definition map {A B} (f: A → B): span A B :=\n    {| π1 x := x ;\n       π2 := f ;\n     |}.\n\n  Definition K {A B} (x: A) (y: B): span A B :=\n    {|\n    s := unit ;\n    π1 _ := x ;\n    π2 _ := y ;\n    |}.\n\n  Definition transpose {A B} (p: span A B): span B A :=\n    {|\n    s := s p ;\n    π1 := π2 p ;\n    π2 := π1 p ;\n    |}.\n\n  Definition sum {A B} (p q: span A B): span A B :=\n    {|\n    s := s p + s q ;\n    π1 s :=\n      match s with\n      | inl x' => π1 p x'\n      | inr x' => π1 q x'\n      end ;\n    π2 s :=\n      match s with\n      | inl x' => π2 p x'\n      | inr x' => π2 q x'\n      end ;\n    |}.\n\n  Definition Σ {B C} {A: span B C} (p: A → span B C): span B C :=\n    {|\n    s := someT (fun i => s (p i)) ;\n    π1 s := π1 (p (head s)) (tail s) ;\n    π2 s := π2 (p (head s)) (tail s) ;\n    |}.\n\n\n  Definition prod {A B} (f g: span A B): span A B :=\n    {|\n    s := { xy : s f * s g |\n           π1 f (fst xy) = π1 g (snd xy) ∧\n           π2 f (fst xy) = π2 g (snd xy)\n         } ;\n    π1 s := π1 f (fst (proj1_sig s)) ;\n    π2 s := π2 f (fst (proj1_sig s)) ;\n    |}.\n\n  (* Not sure about this *)\n  Definition Π {B C} {A} (p: A → span B C): span B C :=\n    {|\n    s := { xy :\n             A *\n             (∀ i, s (p i)) |\n           (∀ i j,\n           π1 (p i) (snd xy i) = π1 (p j) (snd xy j) ∧\n           π2 (p i) (snd xy i) = π2 (p j) (snd xy j))\n         } ;\n    π1 s :=\n      let y := fst (proj1_sig s) in\n      π1 (p y) (snd (proj1_sig s) y) ;\n    π2 s :=\n      let y := fst (proj1_sig s) in\n      π2 (p y) (snd (proj1_sig s) y) ;\n    |}.\n\n  Record Poly B C := {\n    S: span B C ;\n    π: S → Type ;\n  }.\n\n  #[program]\n  Definition poly {B C} (S: span B C) (p: S → span B C) (X: span B C) :=\n    Σ (λ y: S,\n            {|\n              s := p y → X ;\n              π1 f := _ ;\n              π2 f := _ ;\n            |}).\n\n  Next Obligation.\n  Check poly.\n  Infix \"∧\" := prod.\n  Infix \"∨\" := sum.\n\n  Check poly.\n  Notation \"'Σ' x .. y , P\" := (Σ (λ x, .. (Σ (λ y,  P)) .. ))\n         (at level 200, x binder, y binder, right associativity,\n          format \"'[ ' '[ ' 'Σ'  x .. y ']' ,  '/' P ']'\").\nEnd Span.\nModule Stlc.\n  Import Span.\n\n\n  Inductive sort :=\n  | pt\n  | exp (τ0 τ1: sort).\n\n  Inductive term :=\n  | lam (x: string) (τ: sort) (e: term)\n  | app (e0 e1: term)\n  | var (x: string)\n  .\n\n  Definition env := list (string * sort).\n\n  Inductive fact := ofty (Γ: env) (e: term) (τ: sort).\n  Notation \"Γ ⊢ e ∈ τ\" := (ofty Γ e τ) (at level 30).\n\n  Example judge: span (list fact) (list fact) :=\n    Σ A,\n      K A [] ∨\n    Σ A B T,\n      K (A :: B :: T)\n        (B :: A :: T) ∨\n    Σ A B T,\n      K (A :: B :: T)\n        (A :: T) ∨\n    Σ A B T,\n      K (A :: B :: T)\n        (B :: T) ∨\n    Σ Γ e τ T,\n      K (Γ ⊢ e ∈ τ :: T)\n        (Γ ⊢ e ∈ τ :: T)\n  .\n\n  Inductive rule {Γ: string → fact} :=\n  | ignore_rule (A: list fact)\n  | swap_rule (T: list fact) (A B: fact)\n  | fst_rule (T: list fact) (A B: fact)\n  | snd_rule (T: list fact) (A B: fact)\n\n  | lookup_rule (T: list fact) (x: string)\n  .\n  Arguments rule: clear implicits.\n\n  Example judge (Γ: string → fact) (r: rule Γ): (list fact * list fact) :=\n    match r with\n    | ignore_rule A =>\n      (A,\n       [])\n    | lookup_rule T x =>\n      (T,\n       Γ x :: T)\n    | swap_rule T A B =>\n      (A :: B :: T,\n       B :: A :: T)\n    | fst_rule T A B =>\n      (A :: B :: T,\n       A :: T)\n    | snd_rule T A B =>\n      (A :: B :: T,\n       B :: T)\n    end.\n\n  Example theory: displayed fact := {|\n    map e := {|\n              π1 r := fst (judge e r) ;\n              π2 r := snd (judge e r) ;\n            |} ;\n  |}.\n  Definition theorem := free theory.\n\n  Example ignore Γ A: theorem Γ A [] := sup (map theory _) (ignore_rule A).\n  Example lookup Γ x: theorem Γ [] [Γ x] := sup (map theory _) (lookup_rule [] x).\n\n  Example swap' Γ A B T: theorem Γ (A :: B :: T) (B :: A :: T) := sup (map theory _) (swap_rule T A B).\n\n  Example app' Γ e0 e1 τ0 τ1: free theory _ [_ ; _] [_] := sup (map theory _) (app_rule Γ e0 e1 τ0 τ1).\n\n  Check app'.\n  Definition sort_dec (x y: sort): {x = y} + {x ≠ y}.\n  Proof.\n    decide equality.\n  Defined.\nx\n  Function lookup (x: string) (Γ: env): option sort :=\n    match Γ with\n\n    | (y, τ) :: T => if string_dec x y then Some τ else lookup x T\n    | _ => None\n    end.\n\n  Function infer (Γ: env) (e: term): option sort :=\n    match e with\n    | var x => lookup x Γ\n    | lam x τ0 e =>\n      if infer ((x, τ0)::Γ) e is Some τ1\n      then\n        Some (exp τ0 τ1)\n      else\n        None\n    | app e0 e1 =>\n      if infer Γ e0 is Some (exp τ0 τ1)\n      then\n        if infer Γ e1 is Some τ0'\n        then\n          if sort_dec τ0 τ0'\n          then\n            Some τ1\n          else\n            None\n        else\n          None\n      else\n        None\n    end.\n\n  Definition sound {Γ e τ}:\n    infer Γ e = Some τ →\n    theorem [] [Γ ⊢ e ∈ τ].\n  Proof.\n    generalize dependent τ.\n    functional induction (infer Γ e).\n    all: intros τ p.\n    all: inversion p.\n    all: subst.\n    2: {\n      refine (lam' Γ x τ0 τ1 e0 ∘ _).\n      apply IHo.\n      auto.\n    }\n    2: {\n      refine (app' Γ e0 e1 τ0 τ ∘ _).\n      cbn.\n      \n    induction e.\n    all: intros Γ A p.\n    all: cbn in *.\n    all: inversion p.\n    all: subst.\n    - Check (IHe ((x, τ) :: Γ) A p).\n      all: subst.\n      + cbn.\nEnd Stlc.\n\nModule Import Finite.\n  Fixpoint fin (n: nat) :=\n    match n with\n    | O => Empty_set\n    | S n' => option (fin n')\n    end.\n\n  Definition swap N (x: fin (2 + N)): fin (2 + N) :=\n    match x with\n    | Some (Some e) => Some (Some e)\n    | Some None => None\n    | None => Some None\n    end.\n\n  Definition weaken N (x: fin N): fin (S N) := Some x.\n\n  Definition contract N (x: fin (2 + N)): fin (S N) :=\n    match x with\n    | Some (Some e) => Some e\n    | Some None => None\n    | None => None\n    end.\n\n  (* Not really sure about this *)\n  Definition fold N (x: fin (N + N)): fin N.\n  Proof.\n    induction N.\n    - cbn in *.\n      contradiction.\n    - cbn in *.\n      rewrite Nat.add_comm in x.\n      cbn in *.\n      refine (match x with\n              | Some (Some x') => Some (IHN x')\n              | _ => None\n              end).\n  Defined.\n\nEnd Finite.\n\n(* Free category on an endospan/free monad in Span(Set) *)\nModule Cat.\n  Import Span.\n\n  (* Doesn't seem right *)\n  #[universes(cumulative)]\n   Inductive free {Obj} (H: span Obj Obj): Obj → Obj → Type :=\n  | id A: free H A A\n  | compose {A B C}: free H B C → free H A B → free H A C\n  | sup x: free H (π1 H x) (π2 H x)\n  .\n  Arguments id {Obj H}.\n  Arguments compose {Obj H A B C}.\n  Arguments sup {Obj}.\nEnd Cat.\n\n(* Free indexed category on a displayed category *)\nModule IxCat.\n  Import Span.\n  Import Cat.\n\n  Record displayed C := {\n    op: C → Type ;\n    map (c: C): span (op c) (op c) ;\n  }.\n\n  Arguments op {C}.\n  Arguments map {C}.\n\n  Coercion op: displayed >-> Funclass.\n\n  (* A displayed category C -> Span defines a functor D -> C *)\n\n  Definition free {V} (H: displayed V) Γ := free (map H Γ).\nEnd IxCat.\n\nModule CylCat.\n  Import Span.\n  Import Cat.\n  Import IxCat.\n\n  Definition displayed V := displayed (string → V).\n\n  (* A cylindrified displayed category [string, V] -> Span defines an\n  indexed category [string, V] → Cat *)\n  Definition free {V} (H: displayed V) Γ := free H Γ.\nEnd CylCat.\n\n\n\n(* Free indexed monad on an indexed polynomial endofunctor *)\nModule IxPoly.\n   #[universes(cumulative)]\n   Record Poly Env := {\n    pos: Type ;\n    dir: pos → Env → Type ;\n  }.\n\n   Arguments pos {Env}.\n   Arguments dir {Env}.\n\n   Definition X Γ: Poly Γ := {|\n     dir (_: unit) _ := unit ;\n   |}.\n  (* Definition K A: Poly := {| dir (_: A) := Empty_set |}. *)\n\n  (* Definition Π {A} (p: A → Poly): Poly := *)\n  (*   {| *)\n  (*   pos := ∀ i, pos (p i) ; *)\n  (*   dir s := Σ i, dir (p i) (s i) ; *)\n  (*   |}. *)\n  (* Definition Sum {A} (p: A → Poly): Poly := *)\n  (*   {| *)\n  (*   pos := Σ i, pos (p i) ; *)\n  (*   dir s := dir (p (head s)) (tail s) ; *)\n  (*   |}. *)\n\n  (* Definition prod (p q: Poly): Poly := *)\n  (*   {| *)\n  (*   pos := pos p * pos q ; *)\n  (*   dir '(x, y) := dir p x + dir q y ; *)\n  (*   |}. *)\n\n  (* Definition sum (p q: Poly): Poly := *)\n  (*   {| *)\n  (*   pos := pos p + pos q ; *)\n  (*   dir s := *)\n  (*     match s with *)\n  (*     | inl x' => dir p x' *)\n  (*     | inr x' => dir q x' *)\n  (*     end ; *)\n  (*   |}. *)\n\n  (* Infix \"*\" := prod. *)\n  (* Infix \"+\" := sum. *)\n\n  #[universes(cumulative)]\n  Inductive free {Env} (H: Poly Env) A: Env → Type :=\n  | var {Γ}: A Γ → free H A Γ\n  | sup {Γ} x: (dir H x Γ → free H A Γ) → free H A Γ.\n  Arguments var {Env H A Γ}.\n  Arguments sup {Env H A Γ}.\n\n  Definition map {Env} {H: Poly Env} {A B} (f: ∀ Γ, A Γ → B Γ): ∀ {Γ}, free H A Γ → free H B Γ :=\n    fix loop Γ x :=\n      match x with\n      | var v => var (f _ v)\n      | sup x p => sup x (fun y => loop _ (p y))\n      end.\n  Definition join {Env} {H: Poly Env} {A}: ∀ {Γ}, free H (free H A) Γ → free H A Γ :=\n    fix loop Γ x :=\n      match x with\n      | var v => v\n      | sup x p => sup x (fun y => loop _ (p y))\n      end.\nEnd IxPoly.\n\n(* Free indexed category on an indexed endospan/free indexed monad in Span(Set) *)\n  Record bundle B := {\n    dom: Type ;\n    π: dom → B;\n  }.\n  Arguments dom {B}.\n  Arguments π {B}.\n  Coercion dom: bundle >-> Sortclass.\n\n  #[universes(cumulative)]\n   Record span {Env} (A B: bundle Env) := {\n    s: Type ;\n    π1: s → A ;\n    π2: s → B ;\n  }.\n\n  Arguments s {Env A B}.\n  Arguments π1 {Env A B}.\n  Arguments π2 {Env A B}.\n\n  Coercion s: span >-> Sortclass.\n\n  #[universes(cumulative)]\n   Inductive free {Env} {Obj: bundle Env} (H: span Obj Obj): Env → Obj → Obj → Type :=\n  | id {Γ} A: free H Γ A A\n  | compose {Γ} {A B C}: free H Γ B C → free H Γ A B → free H Γ A C\n\n  | sup x: (π Obj (π1 H x) = π Obj (π2 H x)) →\n            free H (π Obj (π1 H x)) (π1 H x) (π2 H x)\n  .\n  Arguments id {Env Obj H Γ}.\n  Arguments compose {Env Obj H Γ A B C}.\n  Arguments sup {Env Obj}.\nEnd IxCat.\n", "meta": {"author": "mstewartgallus", "repo": "playground", "sha": "eb0818baaaa4c80f62227fd6626cdc3136c5bced", "save_path": "github-repos/coq/mstewartgallus-playground", "path": "github-repos/coq/mstewartgallus-playground/playground-eb0818baaaa4c80f62227fd6626cdc3136c5bced/polyendoprofunctor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.28837406448168645}}
{"text": "From Coq Require Import ssreflect ssrbool ssrfun.\nFrom mathcomp Require Import eqtype seq.\nFrom pcm Require Import options axioms pred.\nFrom pcm Require Import pcm unionmap heap automap.\nFrom htt Require Import model heapauto.\nFrom htt Require Import llist.\n\nRecord queue (T : Type) : Type := Queue {front: ptr; back: ptr}.\nDefinition EmptyQueue : exn := exn_from_nat 100.\n\nModule Queue.\nSection Queue.\nVariable T : Type.\nNotation queue := (queue T).\n\n(* a queue is specified as a singly-linked list split into an initial segment and a last node *)\nDefinition is_queue (fr bq : ptr) (xs : seq T) :=\n  if fr == null then [Pred h | [/\\ bq = null, xs = [::] & h = Unit]]\n  else [Pred h | exists xt x h',\n                 [/\\ xs = rcons xt x,\n                     valid (h' \\+ (bq :-> x \\+ bq .+ 1 :-> null)),\n                     h = h' \\+ (bq :-> x \\+ bq .+ 1 :-> null) &\n                     h' \\In lseg fr bq xt]].\n\n(* the structure itself is a pair of pointers to body + last node *)\n(* insertion happens at the last node, and removal at the head *)\nDefinition shape (q : queue) (xs : seq T) :=\n  [Pred h | exists fr bq h',\n    [/\\ valid (front q :-> fr \\+ (back q :-> bq \\+ h')),\n        h = front q :-> fr \\+ (back q :-> bq \\+ h') &\n        h' \\In is_queue fr bq xs]].\n\n(* well-formed queue is a valid heap *)\n\nLemma shapeD q xs h : h \\In shape q xs -> valid h.\nProof. by case=>h1[bq][h'] [] D ->. Qed.\n\n(* empty queue is a pair of null pointers *)\n\nLemma is_queue_nil fr bq h :\n        h \\In is_queue fr bq [::] -> [/\\ fr = null, bq = null & h = Unit].\nProof.\nby rewrite /is_queue; case: eqP=>[->[-> _ ->] | _ [[|y xt][x][h'][]]].\nQed.\n\n(* restructuring the specification for combined list *)\n\nLemma is_queue_rcons fr bq xt x h :\n         h \\In is_queue fr bq (rcons xt x) <->\n         (exists h', [/\\ valid (h' \\+ (bq :-> x \\+ bq .+ 1 :-> null)),\n                         h = h' \\+ (bq :-> x \\+ bq .+ 1 :-> null) &\n                         h' \\In lseg fr bq xt]).\nProof.\nrewrite /is_queue; split.\n- case: eqP; first by move=>-> []; case: xt.\n  by move=>N [xt'][x'][h'][/rcons_inj [->->] ???]; exists h'.\ncase=>h' [D -> H]; case: eqP H=>[->|_ H]; last by vauto.\nmove: (D)=>/[swap]; case/(lseg_null (validL D))=>->->->.\nby rewrite unitL validPtUn.\nQed.\n\n(* pointers should agree in a well-formed queue *)\n\nLemma backfront fr bq xs h :\n        h \\In is_queue fr bq xs -> (fr == null) = (bq == null).\nProof.\nrewrite /is_queue; case: ifP=>[E [->]_ _| E [xt][x][h'][_] D] //.\nby case: eqP D=>// -> /validR; rewrite validPtUn.\nQed.\n\n(* main methods *)\n\n(* new queue is a pair of pointers to an empty segment *)\n\nProgram Definition new :\n          STsep (emp, [vfun v => shape v [::]]) :=\n  Do (x <-- alloc null;\n      y <-- alloc null;\n      ret (Queue T x y)).\nNext Obligation.\n(* run the complete program *)\nmove=>[] _ /= ->; step=>x; step=>y; step=>V.\n(* massage the heap to fit the postcondition *)\nby exists null, null, Unit; rewrite !unitR /= in V *; rewrite joinC.\nQed.\n\n(* freeing a queue, possible only when it's empty *)\n\nProgram Definition free (q : queue) :\n          STsep (shape q [::], [vfun _ h => h = Unit]) :=\n  Do (dealloc (front q);;\n      dealloc (back q)).\nNext Obligation.\n(* pull out ghosts and precondition *)\nmove=>q [] _ /= [fr][bq][h][/[swap]->/[swap]].\n(* both pointers are null *)\ncase/is_queue_nil=>->->->; rewrite unitR=>V.\n(* run the program *)\nby do 2![step]=>_; rewrite unitR.\nQed.\n\n(* for enqueue/dequeue we manipulate the underlying segment directly *)\n\n(* enqueuing is adding a node at the end *)\n\nProgram Definition enq (q : queue) (x : T) :\n  {xs}, STsep (shape q xs,\n               [vfun _ => shape q (rcons xs x)]) :=\n  Do (next <-- allocb null 2;\n      next ::= x;;\n      ba <-- !back q;\n      back q ::= next;;\n      (if (ba : ptr) == null\n         then front q\n         else ba .+ 1) ::= next).\nNext Obligation.\n(* pull out ghosts + precondition *)\nmove=>q x [xs][] _ /= [fr][bq][h'][D -> H].\n(* create the new last node and change the back pointer *)\nstep=>next; do 3!step.\n(* as the pointers agree, test the front one to reason structurally *)\nrewrite -(backfront H) unitR; case: ifP H=>Ef; rewrite /is_queue ?Ef.\n- (* the queue was empty, set the front pointer to new node *)\n  case=>_->->; step; rewrite unitR=>V.\n  (* massage the heap and restructure the goal *)\n  exists next, next, (next :-> x \\+ next.+ 1 :-> null).\n  rewrite joinA joinC; split=>//; apply/(@is_queue_rcons _ _ [::]).\n  by exists Unit; rewrite unitL; split=>//; exact: (validL V).\n(* the queue wasn't empty, link the new node to the last one *)\ncase=>s2[x2][i2][->] {}D -> H2; step=>V.\n(* massage the heap and simplify the goal *)\nexists fr, next, (i2 \\+ bq :-> x2 \\+ bq.+ 1 :-> next \\+ next :-> x \\+ next.+ 1 :-> null).\nsplit; first by apply: (validX V).\n- by rewrite joinC !joinA.\n(* the new node conforms to the queue spec *)\napply/is_queue_rcons; exists (i2 \\+ bq :-> x2 \\+ bq.+ 1 :-> next).\nrewrite joinA; split=>//; first by apply: (validX V).\n(* assemble the old queue back *)\nby apply/lseg_rcons; exists bq, i2; rewrite joinA.\nQed.\n\n(* dequeuing is removing the head node and adjusting pointers *)\n\nProgram Definition deq (q : queue) :\n  {xs}, STsep (shape q xs,\n               fun y h => shape q (behead xs) h /\\\n                 match y with Val v => xs = v :: behead xs\n                            | Exn e => e = EmptyQueue /\\ xs = [::] end) :=\n  Do (fr <-- !front q;\n      if (fr : ptr) == null then throw EmptyQueue\n      else\n        x <-- !fr;\n        next <-- !fr .+ 1;\n        front q ::= next;;\n        dealloc fr;;\n        dealloc fr .+ 1;;\n        if (next : ptr) == null\n          then back q ::= null;;\n               ret x\n        else ret x).\nNext Obligation.\n(* pull out ghosts + precondition *)\nmove=>q [xs][] _ /= [fr][bq][h][D -> H].\n(* read the list, branch *)\nstep; case: ifP H=>Ef; rewrite /is_queue Ef.\n- (* list is empty, throw an exception *)\n  case=>->->->/=; step=>V; split=>//.\n  (* massage and simplify *)\n  exists fr, null, Unit; rewrite unitR in V *; split=>//.\n  by rewrite Ef.\n(* deconstruct the initial segment *)\ncase=>[[|y xt]][x][h'][->] {}D {h}-> /=.\n- (* segment is empty, so dequeuing returns the last node *)\n  case=>->->; do 7!step; rewrite !unitR=>V; split=>//.\n  by exists null, null, Unit; rewrite unitR.\n(* segment is non-empty, run up to the branching point *)\ncase=>next [h2][->] H; do 5!step; rewrite !unitL.\ncase: ifP H=>[/eqP ->|N] H.\n- (* null pointer is in the middle of the segment *)\n  do 2![step]=>V2.\n  (* this contradicts heap validity *)\n  case/(lseg_null (validX V2)): H D=>/=-> _ _ /validR.\n  by rewrite validPtUn.\n(* return the segment head and simplify *)\nstep=>V; split=>//; exists next, bq, (h2 \\+ (bq :-> x \\+ bq .+ 1 :-> null)).\nby rewrite N; split=>//; vauto; apply: (validX V).\nQed.\n\nEnd Queue.\nEnd Queue.\n", "meta": {"author": "imdea-software", "repo": "htt", "sha": "cb1fb44953ba32dec2880662e5e2da47f3f74245", "save_path": "github-repos/coq/imdea-software-htt", "path": "github-repos/coq/imdea-software-htt/htt-cb1fb44953ba32dec2880662e5e2da47f3f74245/examples/queue.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2883474278329949}}
{"text": "Require Import\nCrypto.AbstractInterpretation.AbstractInterpretation\nCrypto.AbstractInterpretation.Proofs\nCrypto.AbstractInterpretation.Wf\nCrypto.AbstractInterpretation.WfExtra\nCrypto.AbstractInterpretation.ZRange\nCrypto.AbstractInterpretation.ZRangeProofs\nCrypto.Algebra.Field\nCrypto.Algebra.Field_test\nCrypto.Algebra.Group\nCrypto.Algebra.Hierarchy\nCrypto.Algebra.IntegralDomain\nCrypto.Algebra.Monoid\nCrypto.Algebra.Nsatz\nCrypto.Algebra.NsatzTactic\nCrypto.Algebra.Ring\nCrypto.Algebra.ScalarMult\nCrypto.Algebra.SubsetoidRing\nCrypto.Arithmetic.BYInv\nCrypto.Arithmetic.BarrettReduction\nCrypto.Arithmetic.BarrettReduction.Generalized\nCrypto.Arithmetic.BarrettReduction.HAC\nCrypto.Arithmetic.BarrettReduction.RidiculousFish\nCrypto.Arithmetic.BarrettReduction.Wikipedia\nCrypto.Arithmetic.BaseConversion\nCrypto.Arithmetic.Core\nCrypto.Arithmetic.FLia\nCrypto.Arithmetic.FancyMontgomeryReduction\nCrypto.Arithmetic.Freeze\nCrypto.Arithmetic.ModOps\nCrypto.Arithmetic.ModularArithmeticPre\nCrypto.Arithmetic.ModularArithmeticTheorems\nCrypto.Arithmetic.MontgomeryReduction.Definition\nCrypto.Arithmetic.MontgomeryReduction.Proofs\nCrypto.Arithmetic.Partition\nCrypto.Arithmetic.PrimeFieldTheorems\nCrypto.Arithmetic.Primitives\nCrypto.Arithmetic.Saturated\nCrypto.Arithmetic.UniformWeight\nCrypto.Arithmetic.WordByWordMontgomery\nCrypto.ArithmeticCPS.BaseConversion\nCrypto.ArithmeticCPS.Core\nCrypto.ArithmeticCPS.Freeze\nCrypto.ArithmeticCPS.ModOps\nCrypto.ArithmeticCPS.Saturated\nCrypto.ArithmeticCPS.WordByWordMontgomery\nCrypto.Assembly.Equality\nCrypto.Assembly.Equivalence\nCrypto.Assembly.EquivalenceProofs\nCrypto.Assembly.Parse\nCrypto.Assembly.Parse.Examples.boringssl_nasm_full_mul_p256\nCrypto.Assembly.Parse.Examples.fiat_25519_carry_square_optimised\nCrypto.Assembly.Parse.Examples.fiat_25519_carry_square_optimised_seed10\nCrypto.Assembly.Parse.Examples.fiat_25519_carry_square_optimised_seed20\nCrypto.Assembly.Parse.Examples.fiat_p256_mul_optimised_seed11\nCrypto.Assembly.Parse.Examples.fiat_p256_mul_optimised_seed12\nCrypto.Assembly.Parse.Examples.fiat_p256_mul_optimised_seed4\nCrypto.Assembly.Parse.Examples.fiat_p256_square_optimised_seed103\nCrypto.Assembly.Parse.Examples.fiat_p256_square_optimised_seed46\nCrypto.Assembly.Parse.Examples.fiat_p256_square_optimised_seed6\nCrypto.Assembly.Parse.TestAsm\nCrypto.Assembly.Symbolic\nCrypto.Assembly.Syntax\nCrypto.BoundsPipeline\nCrypto.CLI\nCrypto.COperationSpecifications\nCrypto.CastLemmas\nCrypto.CompilersTestCases\nCrypto.Curves.Edwards.AffineProofs\nCrypto.Curves.Edwards.Pre\nCrypto.Curves.Edwards.XYZT.Basic\nCrypto.Curves.Edwards.XYZT.Precomputed\nCrypto.Curves.EdwardsMontgomery\nCrypto.Curves.Montgomery.Affine\nCrypto.Curves.Montgomery.AffineInstances\nCrypto.Curves.Montgomery.AffineProofs\nCrypto.Curves.Montgomery.XZ\nCrypto.Curves.Montgomery.XZProofs\nCrypto.Curves.Weierstrass.Affine\nCrypto.Curves.Weierstrass.AffineProofs\nCrypto.Curves.Weierstrass.Jacobian\nCrypto.Curves.Weierstrass.Projective\nCrypto.Demo\nCrypto.Fancy.Barrett256\nCrypto.Fancy.Compiler\nCrypto.Fancy.Montgomery256\nCrypto.Fancy.Prod\nCrypto.Fancy.Spec\nCrypto.Language.API\nCrypto.Language.APINotations\nCrypto.Language.IdentifierParameters\nCrypto.Language.IdentifiersBasicGENERATED\nCrypto.Language.IdentifiersGENERATED\nCrypto.Language.IdentifiersGENERATEDProofs\nCrypto.Language.InversionExtra\nCrypto.Language.PreExtra\nCrypto.Language.UnderLetsProofsExtra\nCrypto.Language.WfExtra\nCrypto.MiscCompilerPasses\nCrypto.MiscCompilerPassesProofs\nCrypto.MiscCompilerPassesProofsExtra\nCrypto.Primitives.MxDHRepChange\nCrypto.PushButtonSynthesis.BYInversionReificationCache\nCrypto.PushButtonSynthesis.BarrettReduction\nCrypto.PushButtonSynthesis.BarrettReductionReificationCache\nCrypto.PushButtonSynthesis.BaseConversion\nCrypto.PushButtonSynthesis.BaseConversionReificationCache\nCrypto.PushButtonSynthesis.FancyMontgomeryReduction\nCrypto.PushButtonSynthesis.FancyMontgomeryReductionReificationCache\nCrypto.PushButtonSynthesis.InvertHighLow\nCrypto.PushButtonSynthesis.Primitives\nCrypto.PushButtonSynthesis.ReificationCache\nCrypto.PushButtonSynthesis.SaturatedSolinas\nCrypto.PushButtonSynthesis.SaturatedSolinasReificationCache\nCrypto.PushButtonSynthesis.SmallExamples\nCrypto.PushButtonSynthesis.UnsaturatedSolinas\nCrypto.PushButtonSynthesis.UnsaturatedSolinasReificationCache\nCrypto.PushButtonSynthesis.WordByWordMontgomery\nCrypto.PushButtonSynthesis.WordByWordMontgomeryReificationCache\nCrypto.Rewriter.All\nCrypto.Rewriter.AllTacticsExtra\nCrypto.Rewriter.Passes.AddAssocLeft\nCrypto.Rewriter.Passes.Arith\nCrypto.Rewriter.Passes.ArithWithCasts\nCrypto.Rewriter.Passes.FlattenThunkedRects\nCrypto.Rewriter.Passes.MulSplit\nCrypto.Rewriter.Passes.MultiRetSplit\nCrypto.Rewriter.Passes.NBE\nCrypto.Rewriter.Passes.NoSelect\nCrypto.Rewriter.Passes.RelaxBitwidthAdcSbb\nCrypto.Rewriter.Passes.StripLiteralCasts\nCrypto.Rewriter.Passes.Test\nCrypto.Rewriter.Passes.ToFancy\nCrypto.Rewriter.Passes.ToFancyWithCasts\nCrypto.Rewriter.Passes.UnfoldValueBarrier\nCrypto.Rewriter.PerfTesting.Core\nCrypto.Rewriter.PerfTesting.StandaloneOCamlMain\nCrypto.Rewriter.Rules\nCrypto.Rewriter.RulesProofs\nCrypto.Rewriter.TestRules\nCrypto.Rewriter.TestRulesProofs\nCrypto.SlowPrimeSynthesisExamples\nCrypto.Spec.CompleteEdwardsCurve\nCrypto.Spec.Curve25519\nCrypto.Spec.ModularArithmetic\nCrypto.Spec.MontgomeryCurve\nCrypto.Spec.MxDH\nCrypto.Spec.Test.X25519\nCrypto.Spec.WeierstrassCurve\nCrypto.StandaloneDebuggingExamples\nCrypto.StandaloneHaskellMain\nCrypto.StandaloneOCamlMain\nCrypto.Stringification.C\nCrypto.Stringification.Go\nCrypto.Stringification.IR\nCrypto.Stringification.JSON\nCrypto.Stringification.Java\nCrypto.Stringification.Language\nCrypto.Stringification.Rust\nCrypto.Stringification.Zig\nCrypto.TAPSort\nCrypto.UnsaturatedSolinasHeuristics\nCrypto.UnsaturatedSolinasHeuristics.Tests\nCrypto.Util.AdditionChainExponentiation\nCrypto.Util.Arg\nCrypto.Util.AutoRewrite\nCrypto.Util.Bool\nCrypto.Util.Bool.Equality\nCrypto.Util.Bool.IsTrue\nCrypto.Util.Bool.LeCompat\nCrypto.Util.Bool.Reflect\nCrypto.Util.CPSNotations\nCrypto.Util.CPSUtil\nCrypto.Util.Comparison\nCrypto.Util.Compose\nCrypto.Util.Curry\nCrypto.Util.Decidable\nCrypto.Util.Decidable.Bool2Prop\nCrypto.Util.Decidable.Decidable2Bool\nCrypto.Util.DefaultedTypes\nCrypto.Util.DynList\nCrypto.Util.Equality\nCrypto.Util.ErrorT\nCrypto.Util.ErrorT.List\nCrypto.Util.ErrorT.Show\nCrypto.Util.FSets.FMapBool\nCrypto.Util.FSets.FMapEmpty\nCrypto.Util.FSets.FMapFacts\nCrypto.Util.FSets.FMapFlip\nCrypto.Util.FSets.FMapInterface\nCrypto.Util.FSets.FMapIso\nCrypto.Util.FSets.FMapN\nCrypto.Util.FSets.FMapOption\nCrypto.Util.FSets.FMapProd\nCrypto.Util.FSets.FMapSect\nCrypto.Util.FSets.FMapSum\nCrypto.Util.FSets.FMapTrie\nCrypto.Util.FSets.FMapTrie.Shape\nCrypto.Util.FSets.FMapTrie.ShapeEx\nCrypto.Util.FSets.FMapTrieEx\nCrypto.Util.FSets.FMapUnit\nCrypto.Util.FSets.FMapZ\nCrypto.Util.Factorize\nCrypto.Util.FixCoqMistakes\nCrypto.Util.FsatzAutoLemmas\nCrypto.Util.FueledLUB\nCrypto.Util.GlobalSettings\nCrypto.Util.HList\nCrypto.Util.HProp\nCrypto.Util.IdfunWithAlt\nCrypto.Util.IffT\nCrypto.Util.Isomorphism\nCrypto.Util.LetIn\nCrypto.Util.LetInMonad\nCrypto.Util.Level\nCrypto.Util.ListUtil\nCrypto.Util.ListUtil.CombineExtend\nCrypto.Util.ListUtil.Concat\nCrypto.Util.ListUtil.Filter\nCrypto.Util.ListUtil.FoldBool\nCrypto.Util.ListUtil.FoldMap\nCrypto.Util.ListUtil.Forall\nCrypto.Util.ListUtil.ForallIn\nCrypto.Util.ListUtil.GroupAllBy\nCrypto.Util.ListUtil.IndexOf\nCrypto.Util.ListUtil.NthExt\nCrypto.Util.ListUtil.Partition\nCrypto.Util.ListUtil.Permutation\nCrypto.Util.ListUtil.PermutationCompat\nCrypto.Util.ListUtil.RemoveN\nCrypto.Util.ListUtil.SetoidList\nCrypto.Util.ListUtil.SetoidListFlatMap\nCrypto.Util.ListUtil.SetoidListRev\nCrypto.Util.ListUtil.Split\nCrypto.Util.ListUtil.StdlibCompat\nCrypto.Util.Listable\nCrypto.Util.Logic\nCrypto.Util.Logic.Exists\nCrypto.Util.Logic.ExistsEqAnd\nCrypto.Util.Logic.Forall\nCrypto.Util.Logic.ImplAnd\nCrypto.Util.Logic.ProdForall\nCrypto.Util.Loops\nCrypto.Util.MSets.FMapPositive.Equality\nCrypto.Util.MSets.MSetIso\nCrypto.Util.MSets.MSetN\nCrypto.Util.MSets.MSetPositive.Equality\nCrypto.Util.MSets.MSetPositive.Facts\nCrypto.Util.MSets.MSetPositive.Show\nCrypto.Util.MSets.MSetSum\nCrypto.Util.MSets.Show\nCrypto.Util.NUtil.Sorting\nCrypto.Util.NUtil.Testbit\nCrypto.Util.NUtil.WithoutReferenceToZ\nCrypto.Util.NatUtil\nCrypto.Util.Notations\nCrypto.Util.NumTheoryUtil\nCrypto.Util.Option\nCrypto.Util.OptionList\nCrypto.Util.PER\nCrypto.Util.ParseTaps\nCrypto.Util.PartiallyReifiedProp\nCrypto.Util.Pointed\nCrypto.Util.PointedProp\nCrypto.Util.Pos\nCrypto.Util.PrimitiveHList\nCrypto.Util.PrimitiveProd\nCrypto.Util.PrimitiveSigma\nCrypto.Util.Prod\nCrypto.Util.QUtil\nCrypto.Util.Relations\nCrypto.Util.SideConditions.Autosolve\nCrypto.Util.SideConditions.CorePackages\nCrypto.Util.SideConditions.ModInvPackage\nCrypto.Util.SideConditions.ReductionPackages\nCrypto.Util.SideConditions.RingPackage\nCrypto.Util.Sigma\nCrypto.Util.Sigma.Associativity\nCrypto.Util.Sigma.Lift\nCrypto.Util.Sigma.MapProjections\nCrypto.Util.Sigma.Related\nCrypto.Util.Sorting.Sorted.Proper\nCrypto.Util.Strings.Ascii\nCrypto.Util.Strings.Decimal\nCrypto.Util.Strings.NamingConventions\nCrypto.Util.Strings.Parse.Common\nCrypto.Util.Strings.ParseArithmetic\nCrypto.Util.Strings.ParseArithmeticToTaps\nCrypto.Util.Strings.Show\nCrypto.Util.Strings.Sorting\nCrypto.Util.Strings.String\nCrypto.Util.Strings.StringMap\nCrypto.Util.Strings.String_as_OT\nCrypto.Util.Strings.String_as_OT_old\nCrypto.Util.Strings.Subscript\nCrypto.Util.Strings.Superscript\nCrypto.Util.Structures.Equalities\nCrypto.Util.Structures.Equalities.Bool\nCrypto.Util.Structures.Equalities.Empty\nCrypto.Util.Structures.Equalities.Iso\nCrypto.Util.Structures.Equalities.List\nCrypto.Util.Structures.Equalities.Option\nCrypto.Util.Structures.Equalities.Prod\nCrypto.Util.Structures.Equalities.Project\nCrypto.Util.Structures.Equalities.Sum\nCrypto.Util.Structures.Equalities.Unit\nCrypto.Util.Structures.Orders\nCrypto.Util.Structures.Orders.Bool\nCrypto.Util.Structures.Orders.Empty\nCrypto.Util.Structures.Orders.Flip\nCrypto.Util.Structures.Orders.Iso\nCrypto.Util.Structures.Orders.List\nCrypto.Util.Structures.Orders.Option\nCrypto.Util.Structures.Orders.Prod\nCrypto.Util.Structures.Orders.Sum\nCrypto.Util.Structures.Orders.Unit\nCrypto.Util.Structures.OrdersEx\nCrypto.Util.Sum\nCrypto.Util.Sumbool\nCrypto.Util.Tactics\nCrypto.Util.Tactics.AllInstances\nCrypto.Util.Tactics.AllSuccesses\nCrypto.Util.Tactics.AppendUnderscores\nCrypto.Util.Tactics.Beta1\nCrypto.Util.Tactics.BreakMatch\nCrypto.Util.Tactics.CPSId\nCrypto.Util.Tactics.CacheTerm\nCrypto.Util.Tactics.ChangeInAll\nCrypto.Util.Tactics.ClearAll\nCrypto.Util.Tactics.ClearDuplicates\nCrypto.Util.Tactics.ClearHead\nCrypto.Util.Tactics.ClearbodyAll\nCrypto.Util.Tactics.ConstrFail\nCrypto.Util.Tactics.Contains\nCrypto.Util.Tactics.ConvoyDestruct\nCrypto.Util.Tactics.CountBinders\nCrypto.Util.Tactics.DebugPrint\nCrypto.Util.Tactics.Delta1\nCrypto.Util.Tactics.DestructHead\nCrypto.Util.Tactics.DestructHyps\nCrypto.Util.Tactics.DestructTrivial\nCrypto.Util.Tactics.DoWithHyp\nCrypto.Util.Tactics.ESpecialize\nCrypto.Util.Tactics.ETransitivity\nCrypto.Util.Tactics.EvarExists\nCrypto.Util.Tactics.EvarNormalize\nCrypto.Util.Tactics.FindHyp\nCrypto.Util.Tactics.Forward\nCrypto.Util.Tactics.GeneralizeOverHoles\nCrypto.Util.Tactics.GetGoal\nCrypto.Util.Tactics.HasBody\nCrypto.Util.Tactics.Head\nCrypto.Util.Tactics.HeadConstrEq\nCrypto.Util.Tactics.HeadUnderBinders\nCrypto.Util.Tactics.InHypUnderBindersDo\nCrypto.Util.Tactics.MoveLetIn\nCrypto.Util.Tactics.NormalizeCommutativeIdentifier\nCrypto.Util.Tactics.Not\nCrypto.Util.Tactics.OnSubterms\nCrypto.Util.Tactics.PoseTermWithName\nCrypto.Util.Tactics.PrintContext\nCrypto.Util.Tactics.PrintGoal\nCrypto.Util.Tactics.Revert\nCrypto.Util.Tactics.RevertUntil\nCrypto.Util.Tactics.RewriteHyp\nCrypto.Util.Tactics.RunTacticAsConstr\nCrypto.Util.Tactics.SetEvars\nCrypto.Util.Tactics.SetoidSubst\nCrypto.Util.Tactics.SideConditionsBeforeToAfter\nCrypto.Util.Tactics.SimplifyProjections\nCrypto.Util.Tactics.SimplifyRepeatedIfs\nCrypto.Util.Tactics.SpecializeAllWays\nCrypto.Util.Tactics.SpecializeBy\nCrypto.Util.Tactics.SpecializeUnderBindersBy\nCrypto.Util.Tactics.SplitInContext\nCrypto.Util.Tactics.SubstEvars\nCrypto.Util.Tactics.SubstLet\nCrypto.Util.Tactics.Test\nCrypto.Util.Tactics.TransparentAssert\nCrypto.Util.Tactics.UnfoldArg\nCrypto.Util.Tactics.UnifyAbstractReflexivity\nCrypto.Util.Tactics.UniquePose\nCrypto.Util.Tactics.VM\nCrypto.Util.Tactics.WarnIfGoalsRemain\nCrypto.Util.Tactics.Zeta1\nCrypto.Util.TagList\nCrypto.Util.Telescope.Core\nCrypto.Util.Telescope.Equality\nCrypto.Util.Telescope.Instances\nCrypto.Util.Tower\nCrypto.Util.Tuple\nCrypto.Util.Unit\nCrypto.Util.Wf\nCrypto.Util.Wf1\nCrypto.Util.Wf2\nCrypto.Util.ZBounded\nCrypto.Util.ZRange\nCrypto.Util.ZRange.BasicLemmas\nCrypto.Util.ZRange.CornersMonotoneBounds\nCrypto.Util.ZRange.LandLorBounds\nCrypto.Util.ZRange.Operations\nCrypto.Util.ZRange.OperationsBounds\nCrypto.Util.ZRange.Show\nCrypto.Util.ZRange.SplitBounds\nCrypto.Util.ZRange.SplitRangeBounds\nCrypto.Util.ZUtil\nCrypto.Util.ZUtil.AddGetCarry\nCrypto.Util.ZUtil.AddModulo\nCrypto.Util.ZUtil.ArithmeticShiftr\nCrypto.Util.ZUtil.Bitwise\nCrypto.Util.ZUtil.CC\nCrypto.Util.ZUtil.CPS\nCrypto.Util.ZUtil.Combine\nCrypto.Util.ZUtil.Definitions\nCrypto.Util.ZUtil.DistrIf\nCrypto.Util.ZUtil.Div\nCrypto.Util.ZUtil.Div.Bootstrap\nCrypto.Util.ZUtil.Divide\nCrypto.Util.ZUtil.EquivModulo\nCrypto.Util.ZUtil.Ge\nCrypto.Util.ZUtil.Hints\nCrypto.Util.ZUtil.Hints.Core\nCrypto.Util.ZUtil.Hints.PullPush\nCrypto.Util.ZUtil.Hints.ZArith\nCrypto.Util.ZUtil.Hints.Ztestbit\nCrypto.Util.ZUtil.Land\nCrypto.Util.ZUtil.LandLorBounds\nCrypto.Util.ZUtil.LandLorShiftBounds\nCrypto.Util.ZUtil.Le\nCrypto.Util.ZUtil.Lnot\nCrypto.Util.ZUtil.LnotModulo\nCrypto.Util.ZUtil.Log2\nCrypto.Util.ZUtil.Lor\nCrypto.Util.ZUtil.Ltz\nCrypto.Util.ZUtil.Lxor\nCrypto.Util.ZUtil.ModExp\nCrypto.Util.ZUtil.ModInv\nCrypto.Util.ZUtil.Modulo\nCrypto.Util.ZUtil.Modulo.Bootstrap\nCrypto.Util.ZUtil.Modulo.PullPush\nCrypto.Util.ZUtil.Morphisms\nCrypto.Util.ZUtil.Mul\nCrypto.Util.ZUtil.MulSplit\nCrypto.Util.ZUtil.N2Z\nCrypto.Util.ZUtil.Nat2Z\nCrypto.Util.ZUtil.Notations\nCrypto.Util.ZUtil.Odd\nCrypto.Util.ZUtil.Ones\nCrypto.Util.ZUtil.OnesFrom\nCrypto.Util.ZUtil.Opp\nCrypto.Util.ZUtil.Peano\nCrypto.Util.ZUtil.Pow\nCrypto.Util.ZUtil.Pow2\nCrypto.Util.ZUtil.Pow2Mod\nCrypto.Util.ZUtil.Quot\nCrypto.Util.ZUtil.Rshi\nCrypto.Util.ZUtil.Sgn\nCrypto.Util.ZUtil.Shift\nCrypto.Util.ZUtil.SignBit\nCrypto.Util.ZUtil.Sorting\nCrypto.Util.ZUtil.Stabilization\nCrypto.Util.ZUtil.Tactics\nCrypto.Util.ZUtil.Tactics.CompareToSgn\nCrypto.Util.ZUtil.Tactics.DivModToQuotRem\nCrypto.Util.ZUtil.Tactics.DivideExistsMul\nCrypto.Util.ZUtil.Tactics.LinearSubstitute\nCrypto.Util.ZUtil.Tactics.LtbToLt\nCrypto.Util.ZUtil.Tactics.PeelLe\nCrypto.Util.ZUtil.Tactics.PrimeBound\nCrypto.Util.ZUtil.Tactics.PullPush\nCrypto.Util.ZUtil.Tactics.PullPush.Modulo\nCrypto.Util.ZUtil.Tactics.ReplaceNegWithPos\nCrypto.Util.ZUtil.Tactics.RewriteModSmall\nCrypto.Util.ZUtil.Tactics.SimplifyFractionsLe\nCrypto.Util.ZUtil.Tactics.SolveRange\nCrypto.Util.ZUtil.Tactics.SolveTestbit\nCrypto.Util.ZUtil.Tactics.SplitMinMax\nCrypto.Util.ZUtil.Tactics.ZeroBounds\nCrypto.Util.ZUtil.Tactics.Ztestbit\nCrypto.Util.ZUtil.Testbit\nCrypto.Util.ZUtil.TruncatingShiftl\nCrypto.Util.ZUtil.TwosComplement\nCrypto.Util.ZUtil.Z2Nat\nCrypto.Util.ZUtil.ZSimplify\nCrypto.Util.ZUtil.ZSimplify.Autogenerated\nCrypto.Util.ZUtil.ZSimplify.Core\nCrypto.Util.ZUtil.ZSimplify.Simple\nCrypto.Util.ZUtil.Zselect\n.\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/Everything.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2883474212175693}}
{"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(*           Hui Zhang <sa512073@mail.ustc.edu.cn>                            *)\n(*                                     School of Software Engineering, USTC   *)\n(*                                                                            *)\n(* ************************************************************************** *)\n\n\nRequire Import LibEx.\nRequire Import bnat.\nRequire Import List.\nRequire Import ListEx.\nRequire Import Data.\n\nRequire Import Params.\nRequire Import Nand.\nRequire Import Bast0.\nRequire Import FTLProp.\n\nRequire Import Framework.\n\nRequire Import Inv.\nRequire Import FTLLems4.\n\n(* To prove the theorem above, we need define a relation, R, saying the flash_device \n   is equal to a hard_disk at every address.\n*)\n\nDefinition Inv (fld: flash_device) : Prop := \n  let (c, f) := fld in Inv.Inv c f.\n\nLemma R_init : R hdd_init fld_init.\nProof.\n  unfold R, hdd_init, fld_init.\n  intros sec.\n  unfold hdd_read, fld_read.\n  destruct (bvalid_sector_no sec) eqn:Hvsec.\n  rewrite list_get_list_repeat_list.\n  destruct (lpn_to_lbn_off sec) as [lbn off] eqn:Hlpn.\n  assert (Hvoff : bvalid_page_off off = true).\n    apply valid_lpn_implies_valid_off with sec lbn; trivial.\n  assert (Hvlbn : bvalid_logical_block_no lbn = true).\n    apply valid_lpn_implies_valid_lbn with sec off; trivial.\n  rewrite ftl_read_ftl_init; trivial.\n    apply blt_true_lt; trivial.\n  destruct (lpn_to_lbn_off sec) as [lbn off] eqn:Hlpn.\n  assert (Hvoff : bvalid_page_off off = true).\n    apply invalid_lpn_implies_valid_off with sec lbn; trivial.\n  assert (Hvlbn : bvalid_logical_block_no lbn = false).\n    apply invalid_lpn_implies_invalid_lbn with sec off; trivial.\n  unfold FTL_read.\n  rewrite Hvoff.\n  unfold ftl_init.\n  unfold bmt_get, bmt_init.\n  unfold ftl_bm_table.\n  rewrite list_get_list_repeat_list_none; trivial.\n  apply blt_false_le; trivial.\nQed.\n\nLemma fld_write_R_preservation : \n  forall hdd hdd' fld fld' sec d,\n    Inv fld\n    -> R hdd fld\n    -> hdd_write hdd sec d = Some hdd'\n    -> fld_write fld sec d = Some fld'\n    -> R hdd' fld'.\nProof.\n  unfold R; intros.\n  destruct (beq_nat_dec sec sec0).\n    desbnat.\n    subst sec0.\n    destruct fld as [c f]. \n    destruct fld' as [c' f'].\n    unfold fld_write in H2.\n    destruct (lpn_to_lbn_off sec) as [lbn lpo] eqn:Hsec.\n    unfold fld_read.\n    rewrite hdd_read_write_at_same_addr with hdd sec d hdd'; trivial.\n    rewrite Hsec.\n    rewrite ftl_read_write_at_same_addr with c f lbn lpo d c' f'; trivial.\n  desbnat.\n  unfold fld_read.\n  destruct fld as [c f]. \n  destruct fld' as [c' f'].\n  rewrite hdd_read_write_not_same_addr with hdd sec sec0 d hdd'; trivial.\n  rewrite H0.\n  unfold fld_read.\n  destruct (lpn_to_lbn_off sec0) as [lbn' lpo'] eqn:Hsec0.\n  unfold fld_write in H2.\n  destruct (lpn_to_lbn_off sec) as [lbn lpo] eqn:Hsec.\n  rewrite (ftl_read_write_not_same_addr c f  lbn lpo d c' f' H H2 lbn' lpo'); trivial.\n  destruct (addr_neq_trans_implies_neq sec sec0 lbn lpo lbn' lpo'); trivial.\n  left; trivial.\n  destruct H3.\n  right; auto.\nQed.\n\nLemma fld_run_deterministic : \n  forall fld cmd fld1 bh1 fld2 bh2,\n    fld_run fld cmd fld1 bh1 \n    -> fld_run fld cmd fld2 bh2\n    -> fld1 = fld2 /\\ bh1 = bh2.\nProof.\n  intros.\n  destruct cmd.\n    simpl in * .\n    destruct H as [d1 [H11 [H12 H13]]].\n    destruct H0 as [d2 [H21 [H22 H23]]].\n    rewrite H11 in H21.\n    inversion H21.\n    subst.\n    split; trivial.\n  simpl in * .\n  destruct H as [H11 H12].\n  destruct H0 as [H21 H22].\n  rewrite H11 in H21.\n  inversion H21; subst.\n  split; trivial.\nQed.\n\nLemma Inv_fld_init : Inv fld_init.\nProof.\n  unfold Inv, fld_init.\n  apply Inv_ftl_init; trivial.\nQed.\n\nLemma fld_write_Inv : \n  forall hdd hdd' fld sec d,\n    Inv fld\n    -> hdd_write hdd sec d = Some hdd'\n    -> exists fld', fld_write fld sec d = Some fld'\n                    /\\ Inv fld'.\nProof.\n  intros.\n  destruct fld as [c f].\n  unfold fld_write.\n  destruct (lpn_to_lbn_off sec) as [lbn off] eqn:Ha.\n  assert (Hv: valid_sector_no sec).\n    eapply hdd_write_some_implies_valid_addr; eauto.\n  assert (Hb: valid_logical_block_no lbn).\n    eapply valid_lpn_implies_valid_lbn; eauto.\n  assert (Ho: valid_page_off off).\n    eapply valid_lpn_implies_valid_off; eauto.\n  destruct (ftl_write_Inv c f lbn off d) as [c' [f' [Hx Hy]]]; auto.\n  exists (c', f').\n  split; trivial.\nQed.\n\nLemma simu_one_step_progress : \n  forall cmd : command, \n    forall (hdd hdd': hard_disk) (bh: behav) (fld: flash_device),\n      Inv fld\n      -> R hdd fld\n      -> hdd_run hdd cmd hdd' bh\n      -> exists fld': flash_device, fld_run fld cmd fld' bh.\nProof.  \n  intros.\n  destruct cmd.\n  intros.\n  exists fld.\n  inversion H1.\n  subst hdd0 sec hdd' bh.\n  unfold fld_run.\n  inversion H1.\n  subst hdd0 lpn0 d0.\n  clear H3.\n  exists d.\n  split.\n    unfold R in H0.\n    rewrite <- H0; trivial.\n  split; trivial.\n  inversion H1.\n  subst hdd0 sec d0 hdd'0 bh.\n  destruct (fld_write_Inv hdd hdd' fld lpn d H Hdw) as [fld' [Hfld' Hinv]].\n  exists fld'; trivial.\n  unfold fld_run.\n  split; trivial.\nQed.    \n\n Lemma simu_one_step_preservation : \n  forall cmd : command, \n    forall (hdd hdd': hard_disk) (bh: behav) (fld fld': flash_device),\n      Inv fld\n      -> R hdd fld\n      -> hdd_run hdd cmd hdd' bh\n      -> fld_run fld cmd fld' bh\n      -> Inv fld' /\\ R hdd' fld'.\nProof.  \n  intros.\n  destruct cmd.\n  inversion H1.\n  subst hdd0 sec hdd' bh.\n  unfold fld_run in H2.\n  destruct H2 as [dx [Hfr [Hdx Hfld']]].\n  subst fld'.\n  injection Hdx.\n  intro; subst dx.\n  split; trivial.\n  inversion H1.\n  subst hdd0 sec hdd'0 d0 bh.\n  unfold fld_run in H2.\n  destruct H2 as [Hfw _].\n  destruct (fld_write_Inv hdd hdd' fld lpn d H Hdw) as [fld'' [Hfld' Hinv']].\n  assert (fld'' = fld').\n    rewrite Hfw in Hfld'.\n    injection Hfld'; auto.\n  subst fld''.\n  split; trivial.\n  apply fld_write_R_preservation with hdd fld lpn d; trivial. \nQed.\n\nLemma simu_multi_steps_progress : \n  forall cl : list command, \n    forall (hd hd': hard_disk) (B: behavior) (fl: flash_device),\n      Inv fl\n      -> R hd fl\n      -> hdd_run_cmd_list hd cl hd' B\n      -> exists fl': flash_device, fld_run_cmd_list fl cl fl' B.\nProof.\n  induction cl.\n    intros.\n    destruct B.\n      exists fl; trivial.\n    simpl in H1.\n    simpl. trivial.\n    simpl in H1.\n    destruct H1.\n  intros.\n  destruct B.\n    simpl in H1.\n    destruct H1.\n  simpl in H1.\n  destruct H1 as [hd'' [H1 H2]].\n  rename a into cmd.\n  rename b into bh.\n  destruct (simu_one_step_progress cmd hd hd'' bh fl H H0 H1) as [fl'' Hfl''].\n  destruct (simu_one_step_preservation cmd hd hd'' bh fl fl'' H H0 H1 Hfl'') as [Hx1 Hx2].\n  assert (Hx := IHcl hd'' hd' B fl'' Hx1 Hx2 H2).\n  destruct Hx as [fl' Hfl'].\n  exists fl'.\n  simpl.\n  exists fl''; split; trivial.\nQed.\n\nLemma simu_multi_steps_preservation : \n  forall cl : list command, \n    forall (hd hd': hard_disk) (B: behavior) (fl fl': flash_device),\n      Inv fl\n      -> R hd fl\n      -> hdd_run_cmd_list hd cl hd' B\n      -> fld_run_cmd_list fl cl fl' B\n      -> Inv fl' /\\ R hd' fl'.\nProof.\n  induction cl.\n    intros.\n    destruct B.\n      simpl in H1.\n      simpl in H2.\n      subst; trivial.\n      split; trivial.\n    simpl in H1.\n    destruct H1.\n  intros.\n  destruct B.\n    simpl in H1.\n    destruct H1.\n  simpl in H1.\n  destruct H1 as [hd'' [H11 H12]].\n  rename a into cmd.\n  rename b into bh.\n  simpl in H2.\n  destruct H2 as [fl'' [H21 H22]].\n  destruct (simu_one_step_preservation cmd hd hd'' bh fl fl'' H H0 H11 H21) as [Hx1 Hx2].\n  eapply IHcl; eauto.\nQed.\n\nTheorem Correctness : \n  forall cl : list command, \n    forall (hd hd': hard_disk) (B: behavior) (fl: flash_device),\n      hdd_run_cmd_list hdd_init cl hd' B\n      -> exists fl': flash_device, fld_run_cmd_list fld_init cl fl' B.\nProof.\n  intros.\n  apply simu_multi_steps_progress with hdd_init hd'; trivial.\n  apply Inv_fld_init.\n  apply R_init.\nQed.\n\n", "meta": {"author": "gy001", "repo": "veriFTL", "sha": "c594b083d12222cd13507acb1bef705f6f2d882e", "save_path": "github-repos/coq/gy001-veriFTL", "path": "github-repos/coq/gy001-veriFTL/veriFTL-c594b083d12222cd13507acb1bef705f6f2d882e/bast0-coq/Verification.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2883474212175693}}
{"text": "From Perennial.program_proof Require Import grove_prelude.\nFrom Goose.github_com.mit_pdos.gokv Require Import memkv.\nFrom Perennial.program_proof.memkv Require Export memkv_shard_definitions common_proof.\n\nSection memkv_put_proof.\n\nContext `{!heapGS Σ, erpcG Σ, urpcregG Σ, kvMapG Σ}.\n\nLocal Ltac Zify.zify_post_hook ::= Z.div_mod_to_equations.\n\nLemma wp_PutRPC (s args_ptr reply_ptr:loc) val_sl args γ Q :\n  is_KVShardServer s γ -∗\n  {{{\n       own_PutRequest args_ptr val_sl args ∗\n       (∃ dummy_rep, own_PutReply reply_ptr dummy_rep) ∗\n       (PreShardPut γ.(kv_gn) args.(PR_Key) Q args.(PR_Value))\n  }}}\n    KVShardServer__PutRPC #s #args_ptr #reply_ptr\n  {{{\n       rep, RET #();\n       own_PutReply reply_ptr rep ∗\n       (PostShardPut γ.(kv_gn) args.(PR_Key) Q args.(PR_Value)) rep\n  }}}.\nProof.\n  iIntros \"#His_shard !#\" (Φ) \"Hpre HΦ\".\n  iDestruct \"Hpre\" as \"(Hargs & Hrep & Hpre)\".\n  iNamed \"Hargs\". iNamed \"Hrep\".\n\n  wp_lam.\n  wp_pures.\n\n  iNamed \"His_shard\".\n  wp_loadField.\n  wp_apply (acquire_spec with \"[$HmuInv]\").\n  iIntros \"[Hlocked Hown]\".\n\n  iNamed \"Hown\".\n\n  wp_pures.\n  wp_lam.\n  wp_pures.\n\n  wp_pures.\n  wp_loadField.\n  wp_apply (wp_shardOf).\n  wp_pures.\n  wp_loadField.\n\n  iDestruct (typed_slice.is_slice_small_acc with \"HshardMap_sl\") as \"[HshardMap_sl HshardMap_sl_close]\".\n  set (sid:=shardOfC args.(PR_Key)) in *.\n\n  assert (∃ b, shardMapping !! int.nat sid = Some b) as [? ?].\n  {\n    eapply list_lookup_lt.\n    move: HshardMapLength. rewrite /sid /shardOfC /uNSHARD.\n    word.\n  }\n  wp_apply (typed_slice.wp_SliceGet with \"[$HshardMap_sl]\").\n  {\n    iPureIntro. done.\n  }\n  iIntros \"HshardMap_sl\".\n  wp_pures.\n\n  wp_if_destruct.\n  { (* have the shard *)\n    wp_loadField.\n    wp_loadField.\n    wp_loadField.\n    iDestruct (is_slice_split with \"Hkvss_sl\") as \"[Hkvss_sl Hkvss_sl_close]\".\n    iDestruct (big_sepS_elem_of_acc _ _ sid with \"HownShards\") as \"[HownShard HownShards]\".\n    { set_solver. }\n    iDestruct \"HownShard\" as \"[%Hbad|HownShard]\".\n    { exfalso. done. }\n    iDestruct \"HownShard\" as (kvs_ptr m mv) \"(HshardGhost & %Hkvs_lookup & %Hdom_kvs & HkvsMap & HvalSlices)\".\n    wp_apply (slice.wp_SliceGet _ _ _ _ _ _ _ (#kvs_ptr) with \"[Hkvss_sl]\").\n    {\n      iFrame \"Hkvss_sl\".\n      iPureIntro.\n      rewrite list_lookup_fmap.\n      rewrite Hkvs_lookup.\n      done.\n    }\n    iIntros \"[Hkvss_sl %Hkvs_ty]\".\n\n    wp_apply (map.wp_MapInsert with \"[$HkvsMap]\").\n    iIntros \"HkvsMap\".\n    wp_pures.\n    wp_storeField.\n    iDestruct (big_sepS_delete _ _ args.(PR_Key) with \"HshardGhost\") as \"[Hghost HshardGhost]\".\n    { set_solver. }\n    iDestruct \"Hghost\" as \"[%Hbad|Hkvptsto]\".\n    { exfalso; done. }\n\n    (* Get Q by using fupd *)\n    unfold PreShardPut.\n    iApply fupd_wp.\n    iMod \"Hpre\".\n    iDestruct \"Hpre\" as (v0) \"(Hkvptsto2 & HfupdQ)\".\n    iMod (kvptsto_update args.(PR_Value) with \"Hkvptsto Hkvptsto2\") as \"[Hkvptsto Hkvptsto2]\".\n    iMod (\"HfupdQ\" with \"Hkvptsto\") as \"Q\".\n    iModIntro.\n\n\n    iDestruct (\"HshardMap_sl_close\" with \"HshardMap_sl\") as \"HshardMap_sl\".\n    wp_loadField.\n    wp_apply (release_spec with \"[> -HΦ Q HKey Hrep]\").\n    {\n      iFrame \"HmuInv Hlocked\".\n      iMod (readonly_load with \"HValue_sl\") as (?) \"HValue_sl'\".\n      iModIntro. iNext.\n      iExists _,_,_, _, _, _.\n      iFrame.\n      iSplitL \"\"; first done.\n      iSplitL \"\"; first done.\n      iApply \"HownShards\".\n      iRight.\n      iExists _, _, _.\n      iFrame.\n      instantiate (1:=(<[args.(PR_Key):=args.(PR_Value)]> m)).\n      iSplitL \"HshardGhost Hkvptsto2\".\n      {\n        iApply (big_sepS_delete _ _ args.(PR_Key) with \"[-]\").\n        { set_solver. }\n        iSplitL \"Hkvptsto2\".\n        {\n          iRight.\n          rewrite lookup_insert.\n          iFrame.\n        }\n        iApply (big_sepS_impl with \"HshardGhost\").\n        iModIntro; iIntros.\n        rewrite lookup_insert_ne; last first.\n        { set_solver. }\n        iFrame.\n      }\n      iSplitL \"\"; first done.\n      iSplitL \"\".\n      { rewrite ?dom_insert_L //; eauto. iPureIntro; congruence. }\n      iApply (big_sepS_delete _ _ args.(PR_Key) with \"[-]\").\n      { set_solver. }\n      iSplitL \"HValue_sl'\".\n      {\n        simpl. iRight.\n        iExists _. iExists val_sl.\n        rewrite lookup_insert.\n        rewrite lookup_insert.\n        by iFrame.\n      }\n      iDestruct (big_sepS_delete _ _ args.(PR_Key) with \"HvalSlices\") as \"[_ HvalSlices]\".\n      { set_solver. }\n      iApply (big_sepS_impl with \"HvalSlices\").\n      iModIntro.\n      iIntros.\n      rewrite lookup_insert_ne; last first.\n      { set_solver. }\n      rewrite lookup_insert_ne; last first.\n      { set_solver. }\n      iFrame.\n    }\n    wp_pures. iModIntro. iApply \"HΦ\".\n    iSplitL \"Hrep\".\n    {\n      instantiate (1:=mkPutReplyC _).\n      iFrame.\n    }\n    iRight.\n    iSimpl.\n    by iFrame.\n  }\n  { (* don't have shard *)\n    wp_storeField.\n\n    wp_loadField.\n    iSpecialize (\"HshardMap_sl_close\" with \"HshardMap_sl\").\n    wp_apply (release_spec with \"[-HΦ Hpre HKey Hrep]\").\n    {\n      iFrame \"HmuInv Hlocked\".\n      iNext.\n      iExists _,_,_, _, _, _.\n      iFrame.\n      done.\n    }\n    wp_pures. iModIntro. iApply \"HΦ\".\n    iSplitL \"Hrep\".\n    {\n      instantiate (1:=mkPutReplyC _).\n      iFrame.\n    }\n    iLeft.\n    iSimpl.\n    by iFrame.\n  }\nQed.\n\nEnd memkv_put_proof.\n\nLtac Zify.zify_post_hook ::= idtac.\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/memkv/memkv_put_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878414043816, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2883474146021437}}
{"text": "From stdpp Require Export telescopes.\nFrom iris.bi Require Export bi.\nFrom iris.prelude Require Import options.\nImport bi.\n\n(* This cannot import the proofmode because it is imported by the proofmode! *)\n\n(** Telescopic quantifiers *)\nDefinition bi_texist {PROP : bi} {TT : tele@{Quant}} (Ψ : TT → PROP) : PROP :=\n  tele_fold (@bi_exist PROP) (λ x, x) (tele_bind Ψ).\nGlobal Arguments bi_texist {_ !_} _ /.\nDefinition bi_tforall {PROP : bi} {TT : tele@{Quant}} (Ψ : TT → PROP) : PROP :=\n  tele_fold (@bi_forall PROP) (λ x, x) (tele_bind Ψ).\nGlobal Arguments bi_tforall {_ !_} _ /.\n\nNotation \"'∃..' x .. y , P\" := (bi_texist (λ x, .. (bi_texist (λ y, P)) .. )%I)\n  (at level 200, x binder, y binder, right associativity,\n  format \"∃..  x  ..  y ,  P\") : bi_scope.\nNotation \"'∀..' x .. y , P\" := (bi_tforall (λ x, .. (bi_tforall (λ y, P)) .. )%I)\n  (at level 200, x binder, y binder, right associativity,\n  format \"∀..  x  ..  y ,  P\") : bi_scope.\n\nSection telescopes.\n  Context {PROP : bi} {TT : tele@{Quant}}.\n  Implicit Types Ψ : TT → PROP.\n\n  Lemma bi_tforall_forall Ψ : bi_tforall Ψ ⊣⊢ bi_forall Ψ.\n  Proof.\n    symmetry. unfold bi_tforall. induction TT as [|X ft IH].\n    - simpl. apply (anti_symm _).\n      + by rewrite (forall_elim TargO).\n      + rewrite -forall_intro; first done.\n        intros p. rewrite (tele_arg_O_inv p) /= //.\n    - simpl. apply (anti_symm _); apply forall_intro; intros a.\n      + rewrite /= -IH. apply forall_intro; intros p.\n        by rewrite (forall_elim (TargS a p)).\n      + destruct a=> /=.\n        setoid_rewrite <- IH.\n        rewrite 2!forall_elim. done.\n  Qed.\n\n  Lemma bi_texist_exist Ψ : bi_texist Ψ ⊣⊢ bi_exist Ψ.\n  Proof.\n    symmetry. unfold bi_texist. induction TT as [|X ft IH].\n    - simpl. apply (anti_symm _).\n      + apply exist_elim; intros p.\n        rewrite (tele_arg_O_inv p) //.\n      + by rewrite -(exist_intro TargO).\n    - simpl. apply (anti_symm _); apply exist_elim.\n      + intros p. destruct p => /=.\n        by rewrite -exist_intro -IH -exist_intro.\n      + intros x.\n        rewrite /= -IH. apply exist_elim; intros p.\n        by rewrite -(exist_intro (TargS x p)).\n  Qed.\n\n  Global Instance bi_tforall_ne n :\n    Proper (pointwise_relation _ (dist n) ==> dist n) (@bi_tforall PROP TT).\n  Proof. intros ?? EQ. rewrite !bi_tforall_forall. rewrite EQ //. Qed.\n  Global Instance bi_tforall_proper :\n    Proper (pointwise_relation _ (⊣⊢) ==> (⊣⊢)) (@bi_tforall PROP TT).\n  Proof. intros ?? EQ. rewrite !bi_tforall_forall. rewrite EQ //. Qed.\n\n  Global Instance bi_texist_ne n :\n    Proper (pointwise_relation _ (dist n) ==> dist n) (@bi_texist PROP TT).\n  Proof. intros ?? EQ. rewrite !bi_texist_exist. rewrite EQ //. Qed.\n  Global Instance bi_texist_proper :\n    Proper (pointwise_relation _ (⊣⊢) ==> (⊣⊢)) (@bi_texist PROP TT).\n  Proof. intros ?? EQ. rewrite !bi_texist_exist. rewrite EQ //. Qed.\n\n  Global Instance bi_tforall_absorbing Ψ :\n    (∀ x, Absorbing (Ψ x)) → Absorbing (∀.. x, Ψ x).\n  Proof. rewrite bi_tforall_forall. apply _. Qed.\n  Global Instance bi_tforall_persistent `{!BiPersistentlyForall PROP} Ψ :\n    (∀ x, Persistent (Ψ x)) → Persistent (∀.. x, Ψ x).\n  Proof. rewrite bi_tforall_forall. apply _. Qed.\n\n  Global Instance bi_texist_affine Ψ :\n    (∀ x, Affine (Ψ x)) → Affine (∃.. x, Ψ x).\n  Proof. rewrite bi_texist_exist. apply _. Qed.\n  Global Instance bi_texist_absorbing Ψ :\n    (∀ x, Absorbing (Ψ x)) → Absorbing (∃.. x, Ψ x).\n  Proof. rewrite bi_texist_exist. apply _. Qed.\n  Global Instance bi_texist_persistent Ψ :\n    (∀ x, Persistent (Ψ x)) → Persistent (∃.. x, Ψ x).\n  Proof. rewrite bi_texist_exist. apply _. Qed.\n\n  Global Instance bi_tforall_timeless Ψ :\n    (∀ x, Timeless (Ψ x)) → Timeless (∀.. x, Ψ x).\n  Proof. rewrite bi_tforall_forall. apply _. Qed.\n\n  Global Instance bi_texist_timeless Ψ :\n    (∀ x, Timeless (Ψ x)) → Timeless (∃.. x, Ψ x).\n  Proof. rewrite bi_texist_exist. apply _. Qed.\nEnd telescopes.\n", "meta": {"author": "amintimany", "repo": "iris", "sha": "03eaffa3b28bffc561b93f30a3ba40bab8ae1fd1", "save_path": "github-repos/coq/amintimany-iris", "path": "github-repos/coq/amintimany-iris/iris-03eaffa3b28bffc561b93f30a3ba40bab8ae1fd1/iris/bi/telescopes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878414043814, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.28834741460214364}}
{"text": "(* Do not edit this file, it was generated automatically *)\nRequire Import VST.floyd.proofauto.\nRequire Import VST.progs64.union.\n#[export] Instance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nImport Memdata.\n\nDefinition Gprog : funspecs :=\n    ltac:(with_library prog (@nil(ident*funspec))).\n\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\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, SpecFloat.bounded prec emax m e = true ->\n    Z.pos m < 2 ^ prec.\nProof.\nintros.\nunfold SpecFloat.bounded in H.\nrewrite andb_true_iff in H.\ndestruct H as [H H0].\napply Z.leb_le in H0.\nunfold SpecFloat.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.\n  unfold SpecFloat.fexp, SpecFloat.emin in H. 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                 _ 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 SpecFloat.bounded, SpecFloat.emin in *.\nrewrite andb_true_iff in e0.\ndestruct e0 as [H' ?H].\nassert (-149 <= e). {\n clear - H'.\n unfold SpecFloat.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).\nunfold SpecFloat.fexp, SpecFloat.emin in *. \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": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs64/verif_union.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878414043816, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.28834741460214364}}
{"text": "From iris.program_logic Require Export weakestpre hoare.\nFrom iris.heap_lang Require Export lang proofmode notation.\nFrom iris.algebra Require Import excl.\nFrom iris_examples.concurrent_stacks Require Import specs.\n\n(** Stack 4: Helping, CAP spec. *)\n\nDefinition mk_offer : val :=\n  λ: \"v\", (\"v\", ref #0).\nDefinition revoke_offer : val :=\n  λ: \"v\", if: CAS (Snd \"v\") #0 #2 then SOME (Fst \"v\") else NONE.\nDefinition take_offer : val :=\n  λ: \"v\", if: CAS (Snd \"v\") #0 #1 then SOME (Fst \"v\") else NONE.\n\nDefinition mk_mailbox : val := λ: \"_\", ref NONEV.\nDefinition put : val :=\n  λ: \"r\" \"v\",\n    let: \"off\" := mk_offer \"v\" in\n    \"r\" <- SOME \"off\";;\n    revoke_offer \"off\".\nDefinition get : val :=\n  λ: \"r\",\n    let: \"offopt\" := !\"r\" in\n    match: \"offopt\" with\n      NONE => NONE\n    | SOME \"x\" => take_offer \"x\"\n    end.\n\nDefinition mk_stack : val := λ: \"_\", (mk_mailbox #(), ref NONEV).\nDefinition push : val :=\n  rec: \"push\" \"p\" \"v\" :=\n    let: \"mailbox\" := Fst \"p\" in\n    let: \"s\" := Snd \"p\" in\n    match: put \"mailbox\" \"v\" with\n      NONE => #()\n    | SOME \"v'\" =>\n      let: \"tail\" := ! \"s\" in\n      let: \"new\" := SOME (ref (\"v'\", \"tail\")) in\n      if: CAS \"s\" \"tail\" \"new\" then #() else \"push\" \"p\" \"v'\"\n    end.\nDefinition pop : val :=\n  rec: \"pop\" \"p\" :=\n    let: \"mailbox\" := Fst \"p\" in\n    let: \"s\" := Snd \"p\" in\n    match: get \"mailbox\" with\n      NONE =>\n      match: !\"s\" with\n        NONE => NONEV\n      | SOME \"l\" =>\n        let: \"pair\" := !\"l\" in\n        if: CAS \"s\" (SOME \"l\") (Snd \"pair\")\n        then SOME (Fst \"pair\")\n        else \"pop\" \"p\"\n      end\n    | SOME \"x\" => SOME \"x\"\n    end.\n\nDefinition channelR := exclR unitR.\nClass channelG Σ := {channel_inG :> inG Σ channelR}.\n\nSection proofs.\n  Context `{!heapG Σ, !channelG Σ} (N : namespace).\n\n  Implicit Types l : loc.\n\n  Definition Nside_channel := N .@ \"side_channel\".\n  Definition Nstack := N .@ \"stack\".\n  Definition Nmailbox := N .@ \"mailbox\".\n\n  Definition inner_mask : coPset := ⊤ ∖ ↑Nside_channel ∖ ↑Nstack.\n\n  Lemma inner_mask_includes :\n     ⊤ ∖ ↑ N ⊆ inner_mask.\n  Proof. solve_ndisj. Qed.\n\n  Lemma inner_mask_promote (P Q : iProp Σ) :\n     (P ={⊤ ∖ ↑ N}=∗ Q) -∗ (P ={inner_mask}=∗ Q).\n  Proof.\n    iIntros \"Himp P\".\n    iMod (fupd_intro_mask' inner_mask (⊤ ∖ ↑ N)) as \"H\"; first by apply inner_mask_includes.\n    iDestruct (\"Himp\" with \"P\") as \"HQ\".\n    iMod \"HQ\".\n    by iMod \"H\".\n  Qed.\n\n  Definition revoke_tok γ := own γ (Excl ()).\n  Definition can_push P Q v : iProp Σ :=\n    (∀ (xs : list val), P xs ={inner_mask}=∗ P (v :: xs) ∗ Q #())%I.\n  Definition access_inv (P : list val → iProp Σ) : iProp Σ :=\n    (|={⊤ ∖ ↑Nside_channel, inner_mask}=> ∃ vs, (▷ P vs) ∗\n      ((▷ P vs) ={inner_mask, ⊤ ∖ ↑Nside_channel}=∗ True))%I.\n\n  Definition stages γ P Q l (v : val) :=\n    ((l ↦ #0 ∗ can_push P Q v)  ∨\n     (l ↦ #1 ∗ Q #()) ∨\n     (l ↦ #1 ∗ revoke_tok γ) ∨\n     (l ↦ #2 ∗ revoke_tok γ))%I.\n\n  Definition is_offer γ P Q (v : val) : iProp Σ :=\n    (∃ v' l, ⌜v = (v', #l)%V⌝ ∗ inv Nside_channel (stages γ P Q l v'))%I.\n\n  Lemma mk_offer_works P Q v :\n    {{{ can_push P Q v }}}\n      mk_offer v\n    {{{ o γ, RET o; is_offer γ P Q o ∗ revoke_tok γ }}}.\n  Proof.\n    iIntros (Φ) \"HP HΦ\".\n    rewrite -wp_fupd.\n    wp_lam. wp_alloc l as \"Hl\".\n    iMod (own_alloc (Excl ())) as (γ) \"Hγ\"; first done.\n    iMod (inv_alloc Nside_channel _ (stages γ P Q l v) with \"[Hl HP]\") as \"#Hinv\".\n    { iNext; iLeft; iFrame. }\n    wp_pures; iModIntro; iApply \"HΦ\"; iFrame; iExists _, _; auto.\n  Qed.\n\n  Lemma revoke_works γ P Q v :\n    {{{ is_offer γ P Q v ∗ revoke_tok γ }}}\n      revoke_offer v\n    {{{ v', RET v'; (∃ v'' : val, ⌜v' = InjRV v''⌝ ∗ can_push P Q v'') ∨ (⌜v' = InjLV #()⌝ ∗ (Q #())) }}}.\n  Proof.\n    iIntros (Φ) \"[Hinv Hγ] HΦ\". iDestruct \"Hinv\" as (v' l) \"[-> #Hinv]\".\n    wp_lam. wp_pures. wp_bind (CmpXchg _ _ _).\n    iInv Nside_channel as \"Hstages\" \"Hclose\".\n    iDestruct \"Hstages\" as \"[[Hl HP] | [[Hl HQ] | [[Hl H] | [Hl H]]]]\".\n    - wp_cmpxchg_suc.\n      iMod (\"Hclose\" with \"[Hl Hγ]\") as \"_\".\n      { iNext; iRight; iRight; iFrame. }\n      iModIntro.\n      wp_pures.\n      by iApply \"HΦ\"; iLeft; iExists _; iFrame.\n    - wp_cmpxchg_fail.\n      iMod (\"Hclose\" with \"[Hl Hγ]\") as \"_\".\n      { iNext; iRight; iRight; iLeft; iFrame. }\n      iModIntro.\n      wp_pures.\n      iApply (\"HΦ\" with \"[HQ]\"); iRight; auto.\n    - wp_cmpxchg_fail.\n      iDestruct (own_valid_2 with \"H Hγ\") as %[].\n    - wp_cmpxchg_fail.\n      iDestruct (own_valid_2 with \"H Hγ\") as %[].\n  Qed.\n\n  Lemma take_works γ P Q Q' o Ψ :\n    let do_pop : iProp Σ :=\n        (∀ v xs, P (v :: xs) ={inner_mask}=∗ P xs ∗ Ψ (SOMEV v))%I in\n    {{{ is_offer γ P Q o ∗ access_inv P ∗ (do_pop ∧ Q') }}}\n      take_offer o\n    {{{ v', RET v';\n        (∃ v'' : val, ⌜v' = InjRV v''⌝ ∗ Ψ v') ∨ (⌜v' = InjLV #()⌝ ∗ (do_pop ∧ Q')) }}}.\n  Proof.\n    simpl; iIntros (Φ) \"[H [Hopener Hupd]] HΦ\"; iDestruct \"H\" as (v l) \"[-> #Hinv]\".\n    wp_lam. wp_proj. wp_bind (CmpXchg _ _ _).\n    iInv Nside_channel as \"Hstages\" \"Hclose\".\n    iDestruct \"Hstages\" as \"[[Hl Hpush] | [[Hl HQ] | [[Hl Hγ] | [Hl Hγ]]]]\".\n    - iMod \"Hopener\" as (xs) \"[HP Hcloser]\".\n      wp_cmpxchg_suc.\n      iMod (\"Hpush\" with \"HP\") as \"[HP HQ]\".\n      iMod (\"Hupd\" with \"HP\") as \"[HP HΨ]\".\n      iMod (\"Hcloser\" with \"HP\") as \"_\".\n      iMod (\"Hclose\" with \"[Hl HQ]\") as \"_\".\n      { iRight; iLeft; iFrame. }\n      iApply fupd_intro_mask; first done.\n      wp_pures.\n      iApply \"HΦ\"; iLeft; auto.\n    - wp_cmpxchg_fail.\n      iMod (\"Hclose\" with \"[Hl HQ]\") as \"_\".\n      { iRight; iLeft; iFrame. }\n      iModIntro.\n      wp_pures.\n      iApply \"HΦ\"; auto.\n    - wp_cmpxchg_fail.\n      iMod (\"Hclose\" with \"[Hl Hγ]\").\n      { iRight; iRight; iFrame. }\n      iModIntro.\n      wp_pures.\n      iApply \"HΦ\"; auto.\n    - wp_cmpxchg_fail.\n      iMod (\"Hclose\" with \"[Hl Hγ]\").\n      { iRight; iRight; iFrame. }\n      iModIntro.\n      wp_pures.\n      iApply \"HΦ\"; auto.\n  Qed.\n\n  Definition mailbox_inv P l : iProp Σ :=\n    (l ↦ NONEV ∨ (∃ v' γ Q, l ↦ SOMEV v' ∗ is_offer γ P Q v'))%I.\n\n  Definition is_mailbox P v : iProp Σ :=\n    (∃ l, ⌜v = #l⌝ ∗ inv Nmailbox (mailbox_inv P l))%I.\n\n  Lemma mk_mailbox_works P :\n    {{{ True }}} mk_mailbox #() {{{ v, RET v; is_mailbox P v }}}.\n  Proof.\n    iIntros (Φ) \"_ HΦ\".\n    rewrite -wp_fupd. wp_lam. wp_alloc l as \"Hl\".\n    iMod (inv_alloc Nmailbox _ (mailbox_inv P l) with \"[Hl]\") as \"#Hinv\".\n    { iNext; by iLeft. }\n    iModIntro.\n    iApply \"HΦ\"; iExists _; auto.\n  Qed.\n\n  Lemma get_works Q P Ψ mailbox :\n    let do_pop : iProp Σ :=\n        (∀ v xs, P (v :: xs) ={inner_mask}=∗ P xs ∗ Ψ (SOMEV v))%I in\n    {{{ is_mailbox P mailbox ∗ access_inv P ∗ (do_pop ∧ Q) }}}\n      get mailbox\n    {{{ ov, RET ov; (∃ v, ⌜ov = SOMEV v⌝ ∗ Ψ ov) ∨ (⌜ov = NONEV⌝ ∗ (do_pop ∧ Q)) }}}.\n  Proof.\n    simpl; iIntros (Φ) \"[Hmail [Hopener Hpush]] HΦ\". iDestruct \"Hmail\" as (l) \"[-> #Hmail]\".\n    wp_lam. wp_bind (Load _).\n    iInv Nmailbox as \"[Hnone | Hsome]\" \"Hclose\".\n    - wp_load.\n      iMod (\"Hclose\" with \"[Hnone]\") as \"_\".\n      { by iLeft. }\n      iModIntro.\n      wp_pures.\n      iApply \"HΦ\"; iRight; by iFrame.\n    - iDestruct \"Hsome\" as (v' γ Q') \"[Hl #Hoffer]\".\n      wp_load.\n      iMod (\"Hclose\" with \"[Hl Hoffer]\") as \"_\".\n      { iNext; iRight; iExists _, _, _; by iFrame. }\n      iModIntro.\n      wp_let. wp_match. wp_apply (take_works with \"[Hpush Hopener]\"); by iFrame.\n  Qed.\n\n  Lemma put_works P Q mailbox v :\n    {{{ is_mailbox P mailbox ∗ can_push P Q v }}}\n      put mailbox v\n    {{{ o, RET o; (∃ v', ⌜o = SOMEV v'⌝ ∗ can_push P Q v') ∨ (⌜o = NONEV⌝ ∗ Q #()) }}}.\n  Proof.\n    iIntros (Φ) \"[Hmail Hpush] HΦ\". iDestruct \"Hmail\" as (l) \"[-> #Hmail]\".\n    wp_lam. wp_let. wp_apply (mk_offer_works with \"Hpush\").\n    iIntros (o γ) \"[#Hoffer Hrev]\".\n    wp_let. wp_bind (Store _ _). wp_pures.\n    iInv Nmailbox as \"[Hnone | Hsome]\" \"Hclose\".\n    - wp_store.\n      iMod (\"Hclose\" with \"[Hnone]\") as \"_\".\n      { iNext; iRight; iExists _, _, _; by iFrame. }\n      iModIntro.\n      wp_pures.\n      wp_apply (revoke_works with \"[Hrev]\"); first auto.\n      iIntros (v') \"H\"; iApply \"HΦ\"; auto.\n    - iDestruct \"Hsome\" as (? ? ?) \"[Hl _]\". wp_store.\n      iMod (\"Hclose\" with \"[Hl]\") as \"_\".\n      { iNext; iRight; iExists _, _, _; by iFrame. }\n      iModIntro.\n      wp_pures.\n      wp_apply (revoke_works with \"[Hrev]\"); first auto.\n      iIntros (v') \"H\"; iApply \"HΦ\"; auto.\n  Qed.\n\n  Local Notation \"l ↦{-} v\" := (∃ q, l ↦{q} v)%I\n    (at level 20, format \"l  ↦{-}  v\") : bi_scope.\n\n  Lemma partial_mapsto_duplicable l v :\n    l ↦{-} v -∗ l ↦{-} v ∗ l ↦{-} v.\n  Proof.\n    iIntros \"H\"; iDestruct \"H\" as (?) \"[Hl Hl']\"; iSplitL \"Hl\"; eauto.\n  Qed.\n\n  Lemma partial_mapsto_agree l v1 v2 :\n    l ↦{-} v1 -∗ l ↦{-} v2 -∗ ⌜v1 = v2⌝.\n  Proof.\n    iIntros \"H1 H2\".\n    iDestruct \"H1\" as (?) \"H1\".\n    iDestruct \"H2\" as (?) \"H2\".\n    iApply (mapsto_agree with \"H1 H2\").\n  Qed.\n\n  Definition oloc_to_val (ol: option loc) : val :=\n    match ol with\n    | None => NONEV\n    | Some loc => SOMEV (#loc)\n    end.\n  Local Instance oloc_to_val_inj : Inj (=) (=) oloc_to_val.\n  Proof. intros [|][|]; simpl; congruence. Qed.\n\n  Fixpoint is_list xs v : iProp Σ :=\n    (match xs, v with\n     | [], None => True\n     | x :: xs, Some l => ∃ t, l ↦{-} (x, oloc_to_val t)%V ∗ is_list xs t\n     | _, _ => False\n     end)%I.\n\n  Lemma is_list_dup xs v :\n    is_list xs v -∗ is_list xs v ∗ match v with\n      | None => True\n      | Some l => ∃ h t, l ↦{-} (h, oloc_to_val t)%V\n      end.\n  Proof.\n    destruct xs, v; simpl; auto; first by iIntros \"[]\".\n    iIntros \"H\"; iDestruct \"H\" as (t) \"(Hl & Hstack)\".\n    iDestruct (partial_mapsto_duplicable with \"Hl\") as \"[Hl1 Hl2]\".\n    iSplitR \"Hl2\"; first by (iExists _; iFrame). by iExists _, _.\n  Qed.\n\n  Lemma is_list_empty xs :\n    is_list xs None -∗ ⌜xs = []⌝.\n  Proof.\n    destruct xs; iIntros \"Hstack\"; auto.\n  Qed.\n\n  Lemma is_list_cons xs l h t :\n    l ↦{-} (h, t)%V -∗\n    is_list xs (Some l) -∗\n    ∃ ys, ⌜xs = h :: ys⌝.\n  Proof.\n    destruct xs; first by iIntros \"? %\".\n    iIntros \"Hl Hstack\"; iDestruct \"Hstack\" as (t') \"(Hl' & Hrest)\".\n    iDestruct (partial_mapsto_agree with \"Hl Hl'\") as \"%\"; simplify_eq; iExists _; auto.\n  Qed.\n\n  Definition stack_inv P l :=\n    (∃ v xs, l ↦ oloc_to_val v ∗ is_list xs v ∗ P xs)%I.\n\n  Definition is_stack_pred P v :=\n    (∃ mailbox l, ⌜v = (mailbox, #l)%V⌝ ∗ is_mailbox P mailbox ∗ inv Nstack (stack_inv P l))%I.\n\n  Theorem mk_stack_works (P : list val → iProp Σ) :\n    {{{ P [] }}} mk_stack #() {{{ v, RET v; is_stack_pred P v }}}.\n  Proof.\n    iIntros (Φ) \"HP HΦ\".\n    rewrite -wp_fupd.\n    wp_lam.\n    wp_alloc l as \"Hl\".\n    wp_apply mk_mailbox_works ; first done. iIntros (v) \"#Hmailbox\".\n    iMod (inv_alloc Nstack _ (stack_inv P l) with \"[Hl HP]\") as \"#Hinv\".\n    { by iNext; iExists None, []; iFrame. }\n    wp_pures. iModIntro; iApply \"HΦ\"; iExists _; auto.\n  Qed.\n\n  Theorem push_works P s v Ψ :\n    {{{ is_stack_pred P s ∗ ∀ xs, P xs ={⊤ ∖ ↑ N}=∗ P (v :: xs) ∗ Ψ #()}}}\n      push s v\n    {{{ RET #(); Ψ #() }}}.\n  Proof.\n    iIntros (Φ) \"[Hstack Hupd] HΦ\". iDestruct \"Hstack\" as (mailbox l) \"(-> & #Hmailbox & #Hinv)\".\n    iAssert (∀ (xs : list val), P xs ={inner_mask}=∗ P (v :: xs) ∗ Ψ #())%I with \"[Hupd]\" as \"Hupd\".\n    { iIntros (xs). by iApply inner_mask_promote. }\n    iLöb as \"IH\" forall (v).\n    wp_lam. wp_pures.\n    wp_apply (put_works with \"[Hupd]\"); first auto. iIntros (o) \"H\".\n    iDestruct \"H\" as \"[Hsome | [-> HΨ]]\".\n    - iDestruct \"Hsome\" as (v') \"[-> Hupd]\".\n      wp_match.\n      wp_bind (Load _).\n      iInv Nstack as (list xs) \"(Hl & Hlist & HP)\" \"Hclose\".\n      wp_load.\n      iMod (\"Hclose\" with \"[Hl Hlist HP]\") as \"_\".\n      { iNext; iExists _, _; iFrame. }\n      clear xs.\n      iModIntro.\n      wp_let. wp_alloc l' as \"Hl'\". wp_pures. wp_bind (CmpXchg _ _ _).\n      iInv Nstack as (list' xs) \"(Hl & Hlist & HP)\" \"Hclose\".\n      destruct (decide (list = list')) as [ -> |].\n      * wp_cmpxchg_suc. { destruct list'; left; done. }\n        iMod (fupd_intro_mask' (⊤ ∖ ↑Nstack) inner_mask) as \"Hupd'\"; first solve_ndisj.\n        iMod (\"Hupd\" with \"HP\") as \"[HP HΨ]\".\n        iMod \"Hupd'\" as \"_\".\n        iMod (\"Hclose\" with \"[Hl Hl' HP Hlist]\") as \"_\".\n        { iNext; iExists (Some _), (v' :: xs); iFrame; iExists _; iFrame; auto. }\n        iModIntro.\n        wp_pures.\n        by iApply (\"HΦ\" with \"HΨ\").\n      * wp_cmpxchg_fail.\n      { destruct list, list'; simpl; congruence. }\n      { destruct list'; left; done. }\n        iMod (\"Hclose\" with \"[Hl HP Hlist]\").\n        { iExists _, _; iFrame. }\n        iModIntro.\n        wp_pures.\n        iApply (\"IH\" with \"HΦ Hupd\").\n    - wp_match. iApply (\"HΦ\" with \"HΨ\").\n  Qed.\n\n  Theorem pop_works P s Ψ :\n    {{{ is_stack_pred P s ∗\n        (∀ v xs, P (v :: xs) ={⊤ ∖ ↑ N}=∗ P xs ∗ Ψ (SOMEV v)) ∧\n        (P [] ={⊤ ∖ ↑ N}=∗ P [] ∗ Ψ NONEV) }}}\n      pop s\n    {{{ v, RET v; Ψ v }}}.\n  Proof.\n    iIntros (Φ) \"(Hstack & Hupd) HΦ\".\n    iDestruct \"Hstack\" as (mailbox l) \"(-> & #Hmailbox & #Hinv)\".\n    iDestruct (bi.and_mono_r with \"Hupd\") as \"Hupd\"; first apply inner_mask_promote.\n    iDestruct (bi.and_mono_l _ _ (∀ (v : val) (xs : list val), _)%I with \"Hupd\") as \"Hupd\".\n    { iIntros \"Hupdcons\". iIntros (v xs). iSpecialize (\"Hupdcons\" $! v xs). iApply (inner_mask_promote with \"Hupdcons\"). }\n    iLöb as \"IH\".\n    wp_lam. wp_proj. wp_let. wp_proj. wp_let.\n    wp_apply (get_works _ _ (λ v, Ψ v) with \"[Hupd]\").\n    { iSplitR; first done.\n      iFrame.\n      iInv Nstack as (v xs) \"(Hl & Hlist & HP)\" \"Hclose\".\n      iModIntro.\n      iExists xs; iSplitL \"HP\"; first auto.\n      iIntros \"HP\".\n      iMod (\"Hclose\" with \"[HP Hl Hlist]\") as \"_\".\n      { iNext; iExists _, _; iFrame. }\n      auto. }\n    iIntros (ov) \"[Hsome | [-> Hupd]]\".\n    - iDestruct \"Hsome\" as (v) \"[-> HΨ]\".\n      wp_pures.\n      iApply (\"HΦ\" with \"HΨ\").\n    - wp_match. wp_bind (Load _).\n      iInv Nstack as (v xs) \"(Hl & Hlist & HP)\" \"Hclose\".\n      wp_load.\n      iDestruct (is_list_dup with \"Hlist\") as \"[Hlist H]\".\n    destruct v as [l'|]; last first.\n      * iDestruct (is_list_empty with \"Hlist\") as %->.\n        iMod (fupd_intro_mask' (⊤ ∖ ↑Nstack) inner_mask) as \"Hupd'\"; first solve_ndisj.\n        iMod (\"Hupd\" with \"HP\") as \"[HP HΨ]\".\n        iMod \"Hupd'\" as \"_\".\n        iMod (\"Hclose\" with \"[Hlist Hl HP]\") as \"_\".\n        { iNext; iExists _, _; iFrame. }\n        iModIntro.\n        wp_match.\n        iApply (\"HΦ\" with \"HΨ\").\n      * iDestruct \"H\" as (h t) \"Hl'\".\n        iMod (\"Hclose\" with \"[Hlist Hl HP]\") as \"_\".\n        { iNext; iExists _, _; iFrame. }\n        iModIntro.\n        wp_match. wp_bind (Load _).\n        iInv Nstack as (v xs') \"(Hl & Hlist & HP)\" \"Hclose\".\n        iDestruct \"Hl'\" as (q) \"Hl'\".\n        wp_load.\n        iMod (\"Hclose\" with \"[Hlist Hl HP]\") as \"_\".\n        { iNext; iExists _, _; iFrame. }\n        iModIntro.\n        wp_pures. wp_bind (CmpXchg _ _ _).\n        iInv Nstack as (v' xs'') \"(Hl & Hlist & HP)\" \"Hclose\".\n        destruct (decide (v' = (Some l'))) as [ -> |].\n        + wp_cmpxchg_suc.\n          iDestruct (is_list_cons with \"[Hl'] Hlist\") as (ys) \"%\"; first by iExists _.\n          simplify_eq.\n          iMod (fupd_intro_mask' (⊤ ∖ ↑Nstack) inner_mask) as \"Hupd'\"; first solve_ndisj.\n          iDestruct \"Hupd\" as \"[Hupdcons _]\".\n          iMod (\"Hupdcons\" with \"HP\") as \"[HP HΨ]\".\n          iMod \"Hupd'\" as \"_\".\n          iDestruct \"Hlist\" as (t') \"(Hl'' & Hlist)\".\n          iDestruct \"Hl''\" as (q') \"Hl''\".\n          iDestruct (mapsto_agree with \"Hl' Hl''\") as \"%\"; simplify_eq.\n          iMod (\"Hclose\" with \"[Hlist Hl HP]\") as \"_\".\n          { iNext; iExists _, _; iFrame. }\n          iModIntro.\n          wp_pures.\n          iApply (\"HΦ\" with \"HΨ\").\n        + wp_cmpxchg_fail. { destruct v'; simpl; congruence. }\n          iMod (\"Hclose\" with \"[Hlist Hl HP]\") as \"_\".\n          { iNext; iExists _, _; iFrame. }\n          iModIntro.\n          wp_pures.\n          iApply (\"IH\" with \"HΦ Hupd\").\n  Qed.\nEnd proofs.\n\nProgram Definition spec {Σ} `{heapG Σ, channelG Σ} : concurrent_stack Σ :=\n  {| is_stack := is_stack_pred; new_stack := mk_stack; stack_push := push; stack_pop := pop |} .\nSolve Obligations of spec with eauto using pop_works, push_works, mk_stack_works.\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/concurrent_stacks/concurrent_stack4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.5273165233795672, "lm_q1q2_score": 0.288304069292466}}
{"text": "Class MFix (m:Type->Type) : Type :=\n  { mfix : forall {A B:Type}, ((A -> m B) -> (A -> m B)) -> (A -> m B) }.\n\nDefinition mfix2 {m} {MFix_:MFix m} {A B C}\n    (ff:(A -> B -> m C) -> A -> B -> m C) (a:A) (b:B) : m C :=\n  let ff' (f:A*B -> m C) (ab:A*B) : m C :=\n    let f' (a:A) (b:B) : m C := f (a,b) in \n    let (a,b) := ab in\n    ff f' a b\n  in mfix ff' (a,b).\n\nDefinition mfix3 {m} {MFix_:MFix m} {A B C D}\n    (ff:(A -> B -> C -> m D) -> A -> B -> C -> m D) (a:A) (b:B) (c:C) : m D :=\n  let ff' (f:A*B*C -> m D) (abc:A*B*C) : m D :=\n    let f' (a:A) (b:B) (c:C) : m D := f (a,b,c) in \n    let '(a,b,c) := abc in\n    ff f' a b c\n  in mfix ff' (a,b,c).\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/MonadFix.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.288304061503496}}
{"text": "(** From the Coq manual, updated to work with the current (8.4)\n   standard library *)\nRequire Import List.\nRequire Import Permutation.\nLtac permutAux n :=\nmatch goal with\n| |- (Permutation ?l ?l) => reflexivity\n| |- (Permutation (?a :: ?l1) (?a :: ?l2)) =>\n    let newn := eval compute in (length l1) in\n    (apply perm_skip; permutAux newn)\n| |- (Permutation (?a :: ?l1) ?l2) =>\n    match eval compute in n with\n    | 1 => fail\n    | _ =>\n        let l1' := constr:(l1 ++ a :: nil) in\n        (apply (@perm_trans _ (a :: l1) l1' l2);\n          [ apply Permutation_cons_append | compute; permutAux (pred n) ])\n    end\nend.\n\n(** Permutation solver *)\nLtac permut :=\n  match goal with\n  | |- (Permutation ?l1 ?l2) =>\n      match eval compute in (length l1 = length l2) with\n      | (?n = ?n) => permutAux n\n      end\n  end.\n\n(*\nNotation \"[ x , .. , y ]\" := (x :: .. (y :: nil) ..) : list_scope.\nLemma fu : Permutation [1,2,3] [3,1,2].\nProof. permut. Qed.\n*)", "meta": {"author": "acowley", "repo": "LinearLogic", "sha": "fc283d02522eaee7d8abdae83c6cfc5065d8d610", "save_path": "github-repos/coq/acowley-LinearLogic", "path": "github-repos/coq/acowley-LinearLogic/LinearLogic-fc283d02522eaee7d8abdae83c6cfc5065d8d610/PermutationHelpers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.288304061503496}}
{"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 int.MinMax.\n\n(* Why3 assumption *)\nInductive list (a:Type) {a_WT:WhyType a} :=\n  | Nil : list a\n  | Cons : a -> (list a) -> list a.\nAxiom list_WhyType : forall (a:Type) {a_WT:WhyType a}, WhyType (list a).\nExisting Instance list_WhyType.\nImplicit Arguments Nil [[a] [a_WT]].\nImplicit Arguments Cons [[a] [a_WT]].\n\nAxiom map : forall (a:Type) {a_WT:WhyType a} (b:Type) {b_WT:WhyType b}, Type.\nParameter map_WhyType : forall (a:Type) {a_WT:WhyType a}\n  (b:Type) {b_WT:WhyType b}, WhyType (map a b).\nExisting Instance map_WhyType.\n\nParameter get: forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  (map a b) -> a -> b.\n\nParameter set: forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  (map a b) -> a -> b -> (map a b).\n\nAxiom Select_eq : forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  forall (m:(map a b)), forall (a1:a) (a2:a), forall (b1:b), (a1 = a2) ->\n  ((get (set m a1 b1) a2) = b1).\n\nAxiom Select_neq : forall {a:Type} {a_WT:WhyType a}\n  {b:Type} {b_WT:WhyType b}, forall (m:(map a b)), forall (a1:a) (a2:a),\n  forall (b1:b), (~ (a1 = a2)) -> ((get (set m a1 b1) a2) = (get m a2)).\n\nParameter const: forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  b -> (map a b).\n\nAxiom Const : forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  forall (b1:b) (a1:a), ((get (const b1:(map a b)) a1) = b1).\n\n(* Why3 assumption *)\nInductive datatype  :=\n  | TYunit : datatype \n  | TYint : datatype \n  | TYbool : datatype .\nAxiom datatype_WhyType : WhyType datatype.\nExisting Instance datatype_WhyType.\n\n(* Why3 assumption *)\nInductive value  :=\n  | Vvoid : value \n  | Vint : Z -> value \n  | Vbool : bool -> value .\nAxiom value_WhyType : WhyType value.\nExisting Instance value_WhyType.\n\n(* Why3 assumption *)\nInductive operator  :=\n  | Oplus : operator \n  | Ominus : operator \n  | Omult : operator \n  | Ole : operator .\nAxiom operator_WhyType : WhyType operator.\nExisting Instance operator_WhyType.\n\nAxiom mident : Type.\nParameter mident_WhyType : WhyType mident.\nExisting Instance mident_WhyType.\n\n(* Why3 assumption *)\nInductive ident  :=\n  | mk_ident : Z -> ident .\nAxiom ident_WhyType : WhyType ident.\nExisting Instance ident_WhyType.\n\n(* Why3 assumption *)\nDefinition ident_index(v:ident): Z := match v with\n  | (mk_ident x) => x\n  end.\n\n(* Why3 assumption *)\nInductive term_node  :=\n  | Tvalue : value -> term_node \n  | Tvar : ident -> term_node \n  | Tderef : mident -> term_node \n  | Tbin : term -> operator -> term -> term_node \n  with term  :=\n  | mk_term : term_node -> Z -> term .\nAxiom term_WhyType : WhyType term.\nExisting Instance term_WhyType.\n\nAxiom term_node_WhyType : WhyType term_node.\nExisting Instance term_node_WhyType.\n\n(* Why3 assumption *)\nDefinition term_maxvar(v:term): Z := match v with\n  | (mk_term x x1) => x1\n  end.\n\n(* Why3 assumption *)\nDefinition term_node1(v:term): term_node :=\n  match v with\n  | (mk_term x x1) => x\n  end.\n\n(* Why3 assumption *)\nFixpoint var_occurs_in_term(x:ident) (t:term) {struct t}: Prop :=\n  match t with\n  | (mk_term (Tvalue _) _) => False\n  | (mk_term (Tvar i) _) => (x = i)\n  | (mk_term (Tderef _) _) => False\n  | (mk_term (Tbin t1 _ t2) _) => (var_occurs_in_term x t1) \\/\n      (var_occurs_in_term x t2)\n  end.\n\n(* Why3 assumption *)\nDefinition term_inv(t:term): Prop := forall (x:ident), (var_occurs_in_term x\n  t) -> ((ident_index x) <= (term_maxvar t))%Z.\n\n(* Why3 assumption *)\nDefinition mk_tvalue(v:value): term := (mk_term (Tvalue v) (-1%Z)%Z).\n\nAxiom mk_tvalue_inv : forall (v:value), (term_inv (mk_tvalue v)).\n\n(* Why3 assumption *)\nDefinition mk_tvar(i:ident): term := (mk_term (Tvar i) (ident_index i)).\n\nAxiom mk_tvar_inv : forall (i:ident), (term_inv (mk_tvar i)).\n\n(* Why3 assumption *)\nDefinition mk_tderef(r:mident): term := (mk_term (Tderef r) (-1%Z)%Z).\n\nAxiom mk_tderef_inv : forall (r:mident), (term_inv (mk_tderef r)).\n\n(* Why3 assumption *)\nDefinition mk_tbin(t1:term) (o:operator) (t2:term): term := (mk_term (Tbin t1\n  o t2) (Zmax (term_maxvar t1) (term_maxvar t2))).\n\nAxiom mk_tbin_inv : forall (t1:term) (t2:term) (o:operator),\n  ((term_inv t1) /\\ (term_inv t2)) -> (term_inv (mk_tbin t1 o t2)).\n\n(* Why3 assumption *)\nInductive fmla  :=\n  | Fterm : term -> fmla \n  | Fand : fmla -> fmla -> fmla \n  | Fnot : fmla -> fmla \n  | Fimplies : fmla -> fmla -> fmla \n  | Flet : ident -> term -> fmla -> fmla \n  | Fforall : ident -> datatype -> fmla -> fmla .\nAxiom fmla_WhyType : WhyType fmla.\nExisting Instance fmla_WhyType.\n\n(* Why3 assumption *)\nInductive stmt  :=\n  | Sskip : stmt \n  | Sassign : mident -> term -> stmt \n  | Sseq : stmt -> stmt -> stmt \n  | Sif : term -> stmt -> stmt -> stmt \n  | Sassert : fmla -> stmt \n  | Swhile : term -> fmla -> stmt -> stmt .\nAxiom stmt_WhyType : WhyType stmt.\nExisting Instance stmt_WhyType.\n\n(* Why3 assumption *)\nDefinition type_value(v:value): datatype :=\n  match v with\n  | Vvoid => TYunit\n  | (Vint int) => TYint\n  | (Vbool bool1) => TYbool\n  end.\n\n(* Why3 assumption *)\nInductive type_operator : operator -> datatype -> datatype\n  -> datatype -> Prop :=\n  | Type_plus : (type_operator Oplus TYint TYint TYint)\n  | Type_minus : (type_operator Ominus TYint TYint TYint)\n  | Type_mult : (type_operator Omult TYint TYint TYint)\n  | Type_le : (type_operator Ole TYint TYint TYbool).\n\n(* Why3 assumption *)\nDefinition type_stack  := (list (ident* datatype)%type).\n\nParameter get_vartype: ident -> (list (ident* datatype)%type) -> datatype.\n\nAxiom get_vartype_def : forall (i:ident) (pi:(list (ident* datatype)%type)),\n  match pi with\n  | Nil => ((get_vartype i pi) = TYunit)\n  | (Cons (x, ty) r) => ((x = i) -> ((get_vartype i pi) = ty)) /\\\n      ((~ (x = i)) -> ((get_vartype i pi) = (get_vartype i r)))\n  end.\n\n(* Why3 assumption *)\nDefinition type_env  := (map mident datatype).\n\n(* Why3 assumption *)\nInductive type_term : (map mident datatype) -> (list (ident* datatype)%type)\n  -> term -> datatype -> Prop :=\n  | Type_value : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (v:value) (m:Z), (type_term sigma pi\n      (mk_term (Tvalue v) m) (type_value v))\n  | Type_var : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (v:ident) (m:Z) (ty:datatype), ((get_vartype v\n      pi) = ty) -> (type_term sigma pi (mk_term (Tvar v) m) ty)\n  | Type_deref : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (v:mident) (m:Z) (ty:datatype), ((get sigma\n      v) = ty) -> (type_term sigma pi (mk_term (Tderef v) m) ty)\n  | Type_bin : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (t1:term) (t2:term) (op:operator) (m:Z) (ty1:datatype)\n      (ty2:datatype) (ty:datatype), (type_term sigma pi t1 ty1) ->\n      ((type_term sigma pi t2 ty2) -> ((type_operator op ty1 ty2 ty) ->\n      (type_term sigma pi (mk_term (Tbin t1 op t2) m) ty))).\n\n(* Why3 assumption *)\nInductive type_fmla : (map mident datatype) -> (list (ident* datatype)%type)\n  -> fmla -> Prop :=\n  | Type_term : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (t:term), (type_term sigma pi t TYbool) ->\n      (type_fmla sigma pi (Fterm t))\n  | Type_conj : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (f1:fmla) (f2:fmla), (type_fmla sigma pi f1) ->\n      ((type_fmla sigma pi f2) -> (type_fmla sigma pi (Fand f1 f2)))\n  | Type_neg : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (f:fmla), (type_fmla sigma pi f) -> (type_fmla sigma\n      pi (Fnot f))\n  | Type_implies : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (f1:fmla) (f2:fmla), (type_fmla sigma pi f1) ->\n      ((type_fmla sigma pi f2) -> (type_fmla sigma pi (Fimplies f1 f2)))\n  | Type_let : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (x:ident) (t:term) (f:fmla) (ty:datatype),\n      (type_term sigma pi t ty) -> ((type_fmla sigma (Cons (x, ty) pi) f) ->\n      (type_fmla sigma pi (Flet x t f)))\n  | Type_forall1 : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (x:ident) (f:fmla), (type_fmla sigma (Cons (x, TYint)\n      pi) f) -> (type_fmla sigma pi (Fforall x TYint f))\n  | Type_forall2 : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (x:ident) (f:fmla), (type_fmla sigma (Cons (x, TYbool)\n      pi) f) -> (type_fmla sigma pi (Fforall x TYbool f))\n  | Type_forall3 : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (x:ident) (f:fmla), (type_fmla sigma (Cons (x, TYunit)\n      pi) f) -> (type_fmla sigma pi (Fforall x TYunit f)).\n\n(* Why3 assumption *)\nInductive type_stmt : (map mident datatype) -> (list (ident* datatype)%type)\n  -> stmt -> Prop :=\n  | Type_skip : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)), (type_stmt sigma pi Sskip)\n  | Type_seq : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (s1:stmt) (s2:stmt), (type_stmt sigma pi s1) ->\n      ((type_stmt sigma pi s2) -> (type_stmt sigma pi (Sseq s1 s2)))\n  | Type_assigns : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (x:mident) (t:term) (ty:datatype), ((get sigma\n      x) = ty) -> ((type_term sigma pi t ty) -> (type_stmt sigma pi\n      (Sassign x t)))\n  | Type_if : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (t:term) (s1:stmt) (s2:stmt), (type_term sigma pi t\n      TYbool) -> ((type_stmt sigma pi s1) -> ((type_stmt sigma pi s2) ->\n      (type_stmt sigma pi (Sif t s1 s2))))\n  | Type_assert : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (p:fmla), (type_fmla sigma pi p) -> (type_stmt sigma\n      pi (Sassert p))\n  | Type_while : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (guard:term) (body:stmt) (inv:fmla), (type_fmla sigma\n      pi inv) -> ((type_term sigma pi guard TYbool) -> ((type_stmt sigma pi\n      body) -> (type_stmt sigma pi (Swhile guard inv body)))).\n\n(* Why3 assumption *)\nDefinition env  := (map mident value).\n\n(* Why3 assumption *)\nDefinition stack  := (list (ident* value)%type).\n\nParameter get_stack: ident -> (list (ident* value)%type) -> value.\n\nAxiom get_stack_def : forall (i:ident) (pi:(list (ident* value)%type)),\n  match pi with\n  | Nil => ((get_stack i pi) = Vvoid)\n  | (Cons (x, v) r) => ((x = i) -> ((get_stack i pi) = v)) /\\ ((~ (x = i)) ->\n      ((get_stack i pi) = (get_stack i r)))\n  end.\n\nAxiom get_stack_eq : forall (x:ident) (v:value) (r:(list (ident*\n  value)%type)), ((get_stack x (Cons (x, v) r)) = v).\n\nAxiom get_stack_neq : forall (x:ident) (i:ident) (v:value) (r:(list (ident*\n  value)%type)), (~ (x = i)) -> ((get_stack i (Cons (x, v) r)) = (get_stack i\n  r)).\n\nParameter eval_bin: value -> operator -> value -> value.\n\nAxiom eval_bin_def : forall (x:value) (op:operator) (y:value), match (x,\n  y) with\n  | ((Vint x1), (Vint y1)) =>\n      match op with\n      | Oplus => ((eval_bin x op y) = (Vint (x1 + y1)%Z))\n      | Ominus => ((eval_bin x op y) = (Vint (x1 - y1)%Z))\n      | Omult => ((eval_bin x op y) = (Vint (x1 * y1)%Z))\n      | Ole => ((x1 <= y1)%Z -> ((eval_bin x op y) = (Vbool true))) /\\\n          ((~ (x1 <= y1)%Z) -> ((eval_bin x op y) = (Vbool false)))\n      end\n  | (_, _) => ((eval_bin x op y) = Vvoid)\n  end.\n\n(* Why3 assumption *)\nFixpoint eval_term(sigma:(map mident value)) (pi:(list (ident* value)%type))\n  (t:term) {struct t}: value :=\n  match t with\n  | (mk_term (Tvalue v) _) => v\n  | (mk_term (Tvar id) _) => (get_stack id pi)\n  | (mk_term (Tderef id) _) => (get sigma id)\n  | (mk_term (Tbin t1 op t2) _) => (eval_bin (eval_term sigma pi t1) op\n      (eval_term sigma pi t2))\n  end.\n\n(* Why3 assumption *)\nFixpoint eval_fmla(sigma:(map mident value)) (pi:(list (ident* value)%type))\n  (f:fmla) {struct f}: Prop :=\n  match f with\n  | (Fterm t) => ((eval_term sigma pi t) = (Vbool true))\n  | (Fand f1 f2) => (eval_fmla sigma pi f1) /\\ (eval_fmla sigma pi f2)\n  | (Fnot f1) => ~ (eval_fmla sigma pi f1)\n  | (Fimplies f1 f2) => (eval_fmla sigma pi f1) -> (eval_fmla sigma pi f2)\n  | (Flet x t f1) => (eval_fmla sigma (Cons (x, (eval_term sigma pi t)) pi)\n      f1)\n  | (Fforall x TYint f1) => forall (n:Z), (eval_fmla sigma (Cons (x,\n      (Vint n)) pi) f1)\n  | (Fforall x TYbool f1) => forall (b:bool), (eval_fmla sigma (Cons (x,\n      (Vbool b)) pi) f1)\n  | (Fforall x TYunit f1) => (eval_fmla sigma (Cons (x, Vvoid) pi) f1)\n  end.\n\nParameter msubst_term: term -> mident -> ident -> term.\n\nAxiom msubst_term_def : forall (t:term) (r:mident) (v:ident),\n  match t with\n  | (mk_term ((Tvalue _)|(Tvar _)) _) => ((msubst_term t r v) = t)\n  | (mk_term (Tderef x) _) => ((r = x) -> ((msubst_term t r\n      v) = (mk_tvar v))) /\\ ((~ (r = x)) -> ((msubst_term t r v) = t))\n  | (mk_term (Tbin t1 op t2) _) => ((msubst_term t r\n      v) = (mk_tbin (msubst_term t1 r v) op (msubst_term t2 r v)))\n  end.\n\nParameter subst_term: term -> ident -> ident -> term.\n\nAxiom subst_term_def : forall (t:term) (r:ident) (v:ident),\n  match t with\n  | (mk_term ((Tvalue _)|(Tderef _)) _) => ((subst_term t r v) = t)\n  | (mk_term (Tvar x) _) => ((r = x) -> ((subst_term t r\n      v) = (mk_tvar v))) /\\ ((~ (r = x)) -> ((subst_term t r v) = t))\n  | (mk_term (Tbin t1 op t2) _) => ((subst_term t r\n      v) = (mk_tbin (subst_term t1 r v) op (subst_term t2 r v)))\n  end.\n\n(* Why3 assumption *)\nDefinition fresh_in_term(id:ident) (t:term): Prop :=\n  ((term_maxvar t) < (ident_index id))%Z.\n\nAxiom eval_msubst_term : forall (sigma:(map mident value)) (pi:(list (ident*\n  value)%type)) (e:term) (x:mident) (v:ident), (fresh_in_term v e) ->\n  ((eval_term sigma pi (msubst_term e x v)) = (eval_term (set sigma x\n  (get_stack v pi)) pi e)).\n\nAxiom eval_subst_term : forall (sigma:(map mident value)) (pi:(list (ident*\n  value)%type)) (e:term) (x:ident) (v:ident), (fresh_in_term v e) ->\n  ((eval_term sigma pi (subst_term e x v)) = (eval_term sigma (Cons (x,\n  (get_stack v pi)) pi) e)).\n\nAxiom eval_term_change_free : forall (t:term) (sigma:(map mident value))\n  (pi:(list (ident* value)%type)) (id:ident) (v:value), (fresh_in_term id\n  t) -> ((eval_term sigma (Cons (id, v) pi) t) = (eval_term sigma pi t)).\n\n(* Why3 assumption *)\nFixpoint fresh_in_fmla(id:ident) (f:fmla) {struct f}: Prop :=\n  match f with\n  | (Fterm e) => (fresh_in_term id e)\n  | ((Fand f1 f2)|(Fimplies f1 f2)) => (fresh_in_fmla id f1) /\\\n      (fresh_in_fmla id f2)\n  | (Fnot f1) => (fresh_in_fmla id f1)\n  | (Flet y t f1) => (~ (id = y)) /\\ ((fresh_in_term id t) /\\\n      (fresh_in_fmla id f1))\n  | (Fforall y ty f1) => (~ (id = y)) /\\ (fresh_in_fmla id f1)\n  end.\n\n(* Why3 assumption *)\nFixpoint subst(f:fmla) (x:ident) (v:ident) {struct f}: fmla :=\n  match f with\n  | (Fterm e) => (Fterm (subst_term e x v))\n  | (Fand f1 f2) => (Fand (subst f1 x v) (subst f2 x v))\n  | (Fnot f1) => (Fnot (subst f1 x v))\n  | (Fimplies f1 f2) => (Fimplies (subst f1 x v) (subst f2 x v))\n  | (Flet y t f1) => (Flet y (subst_term t x v) (subst f1 x v))\n  | (Fforall y ty f1) => (Fforall y ty (subst f1 x v))\n  end.\n\n(* Why3 assumption *)\nFixpoint msubst(f:fmla) (x:mident) (v:ident) {struct f}: fmla :=\n  match f with\n  | (Fterm e) => (Fterm (msubst_term e x v))\n  | (Fand f1 f2) => (Fand (msubst f1 x v) (msubst f2 x v))\n  | (Fnot f1) => (Fnot (msubst f1 x v))\n  | (Fimplies f1 f2) => (Fimplies (msubst f1 x v) (msubst f2 x v))\n  | (Flet y t f1) => (Flet y (msubst_term t x v) (msubst f1 x v))\n  | (Fforall y ty f1) => (Fforall y ty (msubst f1 x v))\n  end.\n\nAxiom subst_fresh : forall (f:fmla) (x:ident) (v:ident), (fresh_in_fmla x\n  f) -> ((subst f x v) = f).\n\nAxiom let_subst : forall (t:term) (f:fmla) (x:ident) (id':ident) (id:mident),\n  ((msubst (Flet x t f) id id') = (Flet x (msubst_term t id id') (msubst f id\n  id'))).\n\nAxiom eval_msubst : forall (f:fmla) (sigma:(map mident value)) (pi:(list\n  (ident* value)%type)) (x:mident) (v:ident), (fresh_in_fmla v f) ->\n  ((eval_fmla sigma pi (msubst f x v)) <-> (eval_fmla (set sigma x\n  (get_stack v pi)) pi f)).\n\nAxiom eval_subst : forall (f:fmla) (sigma:(map mident value)) (pi:(list\n  (ident* value)%type)) (x:ident) (v:ident), (fresh_in_fmla v f) ->\n  ((eval_fmla sigma pi (subst f x v)) <-> (eval_fmla sigma (Cons (x,\n  (get_stack v pi)) pi) f)).\n\nAxiom eval_swap : forall (f:fmla) (sigma:(map mident value)) (pi:(list\n  (ident* value)%type)) (id1:ident) (id2:ident) (v1:value) (v2:value),\n  (~ (id1 = id2)) -> ((eval_fmla sigma (Cons (id1, v1) (Cons (id2, v2) pi))\n  f) <-> (eval_fmla sigma (Cons (id2, v2) (Cons (id1, v1) pi)) f)).\n\nAxiom eval_same_var : forall (f:fmla) (sigma:(map mident value)) (pi:(list\n  (ident* value)%type)) (id:ident) (v1:value) (v2:value), (eval_fmla sigma\n  (Cons (id, v1) (Cons (id, v2) pi)) f) <-> (eval_fmla sigma (Cons (id, v1)\n  pi) f).\n\nAxiom eval_change_free : forall (f:fmla) (sigma:(map mident value)) (pi:(list\n  (ident* value)%type)) (id:ident) (v:value), (fresh_in_fmla id f) ->\n  ((eval_fmla sigma (Cons (id, v) pi) f) <-> (eval_fmla sigma pi f)).\n\n(* Why3 assumption *)\nDefinition valid_fmla(p:fmla): Prop := forall (sigma:(map mident value))\n  (pi:(list (ident* value)%type)), (eval_fmla sigma pi p).\n\nAxiom let_equiv : forall (id:ident) (id':ident) (t:term) (f:fmla),\n  forall (sigma:(map mident value)) (pi:(list (ident* value)%type)),\n  (fresh_in_fmla id' f) -> ((eval_fmla sigma pi (Flet id' t (subst f id\n  id'))) -> (eval_fmla sigma pi (Flet id t f))).\n\nAxiom let_equiv2 : forall (id:ident) (id':ident) (t:term) (f:fmla),\n  forall (sigma:(map mident value)) (pi:(list (ident* value)%type)),\n  (fresh_in_fmla id' f) -> ((eval_fmla sigma pi (Flet id' t (subst f id\n  id'))) -> (eval_fmla sigma pi (Flet id t f))).\n\nAxiom let_implies : forall (id:ident) (t:term) (p:fmla) (q:fmla),\n  (valid_fmla (Fimplies p q)) -> (valid_fmla (Fimplies (Flet id t p) (Flet id\n  t q))).\n\n(* Why3 assumption *)\nFixpoint fresh_in_stmt(id:ident) (s:stmt) {struct s}: Prop :=\n  match s with\n  | Sskip => True\n  | (Sseq s1 s2) => (fresh_in_stmt id s1) /\\ (fresh_in_stmt id s2)\n  | (Sassign _ t) => (fresh_in_term id t)\n  | (Sif t s1 s2) => (fresh_in_term id t) /\\ ((fresh_in_stmt id s1) /\\\n      (fresh_in_stmt id s2))\n  | (Sassert f) => (fresh_in_fmla id f)\n  | (Swhile cond inv body) => (fresh_in_term id cond) /\\ ((fresh_in_fmla id\n      inv) /\\ (fresh_in_stmt id body))\n  end.\n\n(* Why3 assumption *)\nInductive one_step : (map mident value) -> (list (ident* value)%type) -> stmt\n  -> (map mident value) -> (list (ident* value)%type) -> stmt -> Prop :=\n  | one_step_assign : forall (sigma:(map mident value)) (sigma':(map mident\n      value)) (pi:(list (ident* value)%type)) (x:mident) (t:term),\n      (sigma' = (set sigma x (eval_term sigma pi t))) -> (one_step sigma pi\n      (Sassign x t) sigma' pi Sskip)\n  | one_step_seq_noskip : forall (sigma:(map mident value)) (sigma':(map\n      mident value)) (pi:(list (ident* value)%type)) (pi':(list (ident*\n      value)%type)) (s1:stmt) (s1':stmt) (s2:stmt), (one_step sigma pi s1\n      sigma' pi' s1') -> (one_step sigma pi (Sseq s1 s2) sigma' pi' (Sseq s1'\n      s2))\n  | one_step_seq_skip : forall (sigma:(map mident value)) (pi:(list (ident*\n      value)%type)) (s:stmt), (one_step sigma pi (Sseq Sskip s) sigma pi s)\n  | one_step_if_true : forall (sigma:(map mident value)) (pi:(list (ident*\n      value)%type)) (t:term) (s1:stmt) (s2:stmt), ((eval_term sigma pi\n      t) = (Vbool true)) -> (one_step sigma pi (Sif t s1 s2) sigma pi s1)\n  | one_step_if_false : forall (sigma:(map mident value)) (pi:(list (ident*\n      value)%type)) (t:term) (s1:stmt) (s2:stmt), ((eval_term sigma pi\n      t) = (Vbool false)) -> (one_step sigma pi (Sif t s1 s2) sigma pi s2)\n  | one_step_assert : forall (sigma:(map mident value)) (pi:(list (ident*\n      value)%type)) (f:fmla), (eval_fmla sigma pi f) -> (one_step sigma pi\n      (Sassert f) sigma pi Sskip)\n  | one_step_while_true : forall (sigma:(map mident value)) (pi:(list (ident*\n      value)%type)) (cond:term) (inv:fmla) (body:stmt), (eval_fmla sigma pi\n      inv) -> (((eval_term sigma pi cond) = (Vbool true)) -> (one_step sigma\n      pi (Swhile cond inv body) sigma pi (Sseq body (Swhile cond inv body))))\n  | one_step_while_falsee : forall (sigma:(map mident value)) (pi:(list\n      (ident* value)%type)) (cond:term) (inv:fmla) (body:stmt),\n      (eval_fmla sigma pi inv) -> (((eval_term sigma pi\n      cond) = (Vbool false)) -> (one_step sigma pi (Swhile cond inv body)\n      sigma pi Sskip)).\n\n(* Why3 assumption *)\nInductive many_steps : (map mident value) -> (list (ident* value)%type)\n  -> stmt -> (map mident value) -> (list (ident* value)%type) -> stmt\n  -> Z -> Prop :=\n  | many_steps_refl : forall (sigma:(map mident value)) (pi:(list (ident*\n      value)%type)) (s:stmt), (many_steps sigma pi s sigma pi s 0%Z)\n  | many_steps_trans : forall (sigma1:(map mident value)) (sigma2:(map mident\n      value)) (sigma3:(map mident value)) (pi1:(list (ident* value)%type))\n      (pi2:(list (ident* value)%type)) (pi3:(list (ident* value)%type))\n      (s1:stmt) (s2:stmt) (s3:stmt) (n:Z), (one_step sigma1 pi1 s1 sigma2 pi2\n      s2) -> ((many_steps sigma2 pi2 s2 sigma3 pi3 s3 n) ->\n      (many_steps sigma1 pi1 s1 sigma3 pi3 s3 (n + 1%Z)%Z)).\n\nAxiom steps_non_neg : forall (sigma1:(map mident value)) (sigma2:(map mident\n  value)) (pi1:(list (ident* value)%type)) (pi2:(list (ident* value)%type))\n  (s1:stmt) (s2:stmt) (n:Z), (many_steps sigma1 pi1 s1 sigma2 pi2 s2 n) ->\n  (0%Z <= n)%Z.\n\nAxiom many_steps_seq : forall (sigma1:(map mident value)) (sigma3:(map mident\n  value)) (pi1:(list (ident* value)%type)) (pi3:(list (ident* value)%type))\n  (s1:stmt) (s2:stmt) (n:Z), (many_steps sigma1 pi1 (Sseq s1 s2) sigma3 pi3\n  Sskip n) -> exists sigma2:(map mident value), exists pi2:(list (ident*\n  value)%type), exists n1:Z, exists n2:Z, (many_steps sigma1 pi1 s1 sigma2\n  pi2 Sskip n1) /\\ ((many_steps sigma2 pi2 s2 sigma3 pi3 Sskip n2) /\\\n  (n = ((1%Z + n1)%Z + n2)%Z)).\n\nAxiom one_step_change_free : forall (s:stmt) (s':stmt) (sigma:(map mident\n  value)) (sigma':(map mident value)) (pi:(list (ident* value)%type))\n  (pi':(list (ident* value)%type)) (id:ident) (v:value), (fresh_in_stmt id\n  s) -> ((one_step sigma (Cons (id, v) pi) s sigma' pi' s') ->\n  (one_step sigma pi s sigma' pi' s')).\n\n(* Why3 assumption *)\nDefinition valid_triple(p:fmla) (s:stmt) (q:fmla): Prop := forall (sigma:(map\n  mident value)) (pi:(list (ident* value)%type)), (eval_fmla sigma pi p) ->\n  forall (sigma':(map mident value)) (pi':(list (ident* value)%type)) (n:Z),\n  (many_steps sigma pi s sigma' pi' Sskip n) -> (eval_fmla sigma' pi' q).\n\n(* Why3 assumption *)\nDefinition total_valid_triple(p:fmla) (s:stmt) (q:fmla): Prop :=\n  forall (sigma:(map mident value)) (pi:(list (ident* value)%type)),\n  (eval_fmla sigma pi p) -> exists sigma':(map mident value),\n  exists pi':(list (ident* value)%type), exists n:Z, (many_steps sigma pi s\n  sigma' pi' Sskip n) /\\ (eval_fmla sigma' pi' q).\n\nParameter x: ident.\n\nParameter y: mident.\n\nRequire Import Why3.\nLtac ae := why3 \"alt-ergo\" timelimit 3.\n\n(* Why3 goal *)\nTheorem Test55 : ((eval_term (const (Vint 0%Z):(map mident value)) (Cons (x,\n  (Vint 42%Z)) (Nil :(list (ident* value)%type))) (mk_tbin (mk_tvar x) Oplus\n  (mk_tvalue (Vint 13%Z)))) = (Vint 55%Z)).\nsimpl.\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/hoare_logic/draft/blocking_semantics3/blocking_semantics3_TestSemantics_Test55_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.28830406150349597}}
{"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\nRequire Export LanguageModuleDef.\nRequire Export StaticSemantics.\nRequire Export DynamicSemanticsHeapObjects.\nRequire Export TacticNotations.\n\n(* Bug, Miswrote theorem. I like the forall quantified version although\n   I can naturally express this with exists.  *)\n(* This is not the right induction just whacking a length on it. *)\n(* I need to induct on path extension, perhaps reverse paths? *)\n\nFunctional Scheme rev_ind := Induction for rev Sort Prop.\n\nLemma A_11_Heap_Object_Safety_1:\n  forall (v1 : E),\n      forall (p : Path) (v2 : E) (v3 : E),\n        get v1 p v2 ->\n        get v1 p v3 -> \n        v2 = v3. \nProof.\n  intros v1.\n  induction v1;\n   try (intros p v2 v3 getv1pv2 getv1pv3;\n        inversion getv1pv2;\n        inversion getv1pv3;\n        try reflexivity;\n        crush).\n  (* 1,2 should invert on getv1pv* why didn't it? *)\n  specialize (IHv1_1 p0 v3 v2).\n  apply IHv1_1 in H14.\n  crush.\n  assumption.\n  \n  specialize (IHv1_2 p0 v3 v2).\n  apply IHv1_2 in H14.\n  crush.\n  assumption.\n\n  specialize (IHv1 p0 v2 v3).\n  apply IHv1 in H6.\n  crush.\n  assumption.\nQed.\n\nLemma A_11_Heap_Object_Safety_2:\n  forall (v0 : E) (p1 : Path) (v1 : E),\n    Value v0 ->\n    Value v1 ->\n    get v0 p1 v1 ->\n    forall (p2 : Path) (v2 : E),\n      Value v2 ->\n      get v0 (p1 ++ p2) v2 ->\n      get v1 p2 v2.\nProof.\n  (* Try induction on the values. *)\n  intros v0.\n  (* Try to learn to get rid of silly goals. *)\n  induction v0; \n    try ( \n        intros p1 v1 val0 val1 getv0p1v1;\n        inversion getv0p1v1;\n        intros p2 v2 valv2;\n        intros get;\n        inversion get;\n        crush).\n  intros p1;\n  induction p1 as [| pe1 p1'].\n  Case \"pair and p1=[]\".\n   intros v1 valpair valv1 getcpair p2 v2 valv2 getcpairnil.\n   inversion getcpair.\n   crush.\n\n  (* A pair and a pack, nice strong induction hypotheses. *)\n  Case \"pair and pe1::p1\".\n    SCase \"pe1= i which won't work\".\n    intros v1 valpair valv1 getcpair p2 v2 valv2 getcpairnil.\n    destruct pe1; try destruct i.\n    SSCase \"pe1=zero_pe\".\n    inversion valpair; inversion getcpair; inversion getcpairnil; crush.\n    specialize (IHv0_1 p1' v1 H1 H6 H10 p2 v2 H14 H18).\n    assumption.\n    SSCase \"pe1=one_pe\".\n    inversion valpair.\n    inversion getcpair.\n    inversion getcpairnil.\n    crush.\n    specialize (IHv0_2 p1' v1 H2 H6  H10 p2 v2 H14 H18).\n    assumption.\n    SSCase \"pe1=u_pe\".\n     inversion getcpair.\n   Case \"v0 is pack\".\n    intros p1 v1 valpack valv1.\n    destruct p1.\n    SCase \"p1 is []\".\n    intros getpack p2 v2 valv2 getpackp2.\n    rewrite app_nil_l in getpackp2.\n    inversion valpack; inversion getpack; inversion getpackp2; crush.\n    SCase \"p1 is \".\n     destruct p.\n     intros integerpath.\n     inversion integerpath.\n     inversion valpack.\n     intros getpacku p2 v2 valv2 step.\n     inversion getpacku.\n     crush.\n     inversion step.\n     crush.\n     apply IHv0 with (p1:= p1); try assumption.\nQed.\n\nLemma A_11_Heap_Object_Safety_3:\n  forall (h : Heap) (u : Upsilon) (g : Gamma) \n         (x : EVar) (vhx v1 : E) (t1 t2: Tau) \n         (p1 p2 : Path),\n    Value v1 ->\n    refp h u ->\n    htyp u g h g ->\n    H.map h x = Some vhx ->\n    get vhx p1 v1 ->\n    rtyp D.empty u g v1 t1 ->\n    gettype u x p1 t1 p2 t2 ->\n    (exists (v2 : E),\n       get vhx (p1 ++ p2) v2 /\\ \n       rtyp D.empty u g v2 t2) /\\\n    (forall (v2' : E),\n       Value v2' ->\n       (exists (v1' : E),\n          Value v1' ->\n          set v1 p2 v2' v1')).\nProof.\n  intros h u g x vhx v1 t1 t2 p1 p2.\n  intros valv1 refpder htypder getHder getder rtypder gettypeder.\n  split.\n  (* Try induction v1, p. \n  induction v1; induction p2. 24 uncrushable goals. *)\n  (* Try functional induction on get type, 12/24.*)\n  gettype_ind_cases (induction gettypeder) Case;\n    try inversion gettypeder;   (* 12/24 *)\n    try (rewrite app_nil_r;\n         apply ex_intro with (x:=v1);\n         split;\n         assumption;\n         inversion gettypeder;\n         assumption). (* 8/12 *)\n  (* Well I chopped the goals down, but now is it actually provable? *)\n  (* Scotch whisky society, 10.76, bunnahbin distilery,\n     like smoking a hookah over oyster shells. *)\n  crush.\n(* Why can I not clear the bad goals with an inversion on rtypder? *)\n(* destruct v1.  *)\n(*  induction v1 *)\n(* induction rtypder ? *)\n  (* Have to get more in the context and then destruct v1. *)\n  (* But it's an existential. *)\n  (* assert (A: get v1 (i_pe zero_pe) v2). *)\n  admit.\n  admit.\n  admit.\n  admit.\n  admit.\n  admit.\n  admit.\nAdmitted.\n\nLemma gettype_nil_path:\n  forall (u : Upsilon) (x : EVar) (p : Path) (t1 t2 : Tau),\n    gettype u x p t1 [] t2 ->\n     t1 = t2.\nProof.\n  intros u x p t1 t2.\n  induction t1.\n  crush.\n  crush.\n  crush.\n  crush.\n  crush.\n  crush.\n  intros.\nAdmitted.\n(* \n  destruct p0.\n  compute in H.\n  crush.\n  compute in H.\n  crush.\nQed.  \n*)\nLemma A_11_Heap_Object_Safety_3_induction_tests:\n  forall (h : Heap) (u : Upsilon) (g : Gamma) \n         (x : EVar) (vhx v1 : E) (t1 t2: Tau) \n         (p1 p2 : Path),\n    refp h u ->\n    htyp u g h g ->\n    H.map h x = Some vhx ->\n    Value v1 ->\n    get vhx p1 v1 ->\n    rtyp D.empty u g v1 t1 ->\n    gettype u x p1 t1 p2 t2 ->\n    (exists (v2 : E),\n       get vhx (p1 ++ p2) v2 /\\ \n       rtyp D.empty u g v2 t2) /\\\n    (forall (v2' : E),\n       Value v2' ->\n       (exists (v1' : E),\n          Value v1' ->\n          set v1 p2 v2' v1')).\nProof.\nAdmitted. \n(*\n  intros h u g x vhx v1 t1 t2 p1 p2.\n  intros refpder htypder valv1 H.mapder getder rtypder.\n  induction p2; try destruct a; try destruct i.\n  Case \"p2=[]\".\n   intros gettypeder.\n   apply gettype_nil_path in gettypeder.\n   crush.\n   apply ex_intro with (x:=v1).\n   split.\n   SCase \"get\".\n    rewrite app_nil_r.\n    assumption.\n    assumption.\n   SCase \"set\".\n    apply ex_intro with (x:=v1).\n    intros.\n    assert (E: v1 = v2').\n    admit. (* TODO apply both halves of the theorem in this goal. *)\n    rewrite E.\n    constructor.\n    assumption.\n    assumption.\n  Case \"p = zero_pe :: p2\".\n   intros gettypeder.\n   destruct t1. \n  (* Have to sequentially invert as this is unfolding some things we don't want.*)\n  (* Just clearing meaningless goals. *)\n   inversion gettypeder. \n   inversion gettypeder.   \n   Focus 2.\n   inversion gettypeder.\n   Focus 2.\n   inversion gettypeder.\n   Focus 2.\n   inversion gettypeder.\n   (* Dan's one inversion is really three. *)\n   destruct v1; inversion H.mapder; inversion rtypder. \n   (* And crush is unfolding a gettypeder. *)\n   apply A_10_Path_Extension_1_A with (v0:=v1_1 ) (v1:=v1_2) in getder.\n\n   admit.\n   admit.\n   constructor; assumption.\n   reflexivity.\n  Case \"p = one_pe :: p2\".\n   admit.\n  Case \"p = u_pe :: p2\".\n   admit.\nAdmitted.\n\nCheck A_11_Heap_Object_Safety_3.\n*)\n\nLemma A_11_Heap_Object_Safety_3_Corollary :\n  forall (h : Heap) (u : Upsilon) (g : Gamma) \n         (x : EVar) (v1 : E) (t1 t2: Tau) \n         (p2 : Path),\n    Value v1 ->\n    refp h u ->\n    htyp u g h g ->\n    H.map h x = Some v1 ->\n    get v1 [] v1 ->\n    rtyp D.empty u g v1 t1 ->\n    gettype u x [] t1 p2 t2 ->\n    (exists (v2 : E),\n       get v1 ([] ++ p2) v2 /\\ \n       rtyp D.empty u g v2 t2) /\\\n    (forall (v2' : E),\n       Value v2' ->\n       (exists (v1' : E),\n          Value v1' ->\n          set v1 p2 v2' v1')).\nProof.\n  intros h u g x v1 t1 t2 p2.\n  intros valv1 refpder htypder getHmapder getder rtypder gettypeder.\n  apply A_11_Heap_Object_Safety_3 with (h:=h) (x:=x) (t1:=t1);\n    try assumption;\n    try constructor;\n    try assumption.\nQed.\n\n(*\nLemma A_11_Heap_Object_Safety_4: \n  forall (h : Heap) (u : Upsilon) (g : Gamma) \n         (x : EVar) (vhx v1 : E) (t1 t2: Tau) \n         (p1 p2 : Path),\n    Value v1 ->\n    refp h u ->\n    htyp u g h g ->\n    H.map h x = Some vhx ->\n    get vhx p1 v1 ->\n    rtyp D.empty u g v1 t1 ->\n    gettype u x p1 t1 p2 t2 ->\n    (exists (v2 : E),\n       get vhx (p1 ++ p2) v2 /\\ \n       rtyp D.empty u g v2 t2) /\\\n    (forall (v2' : E),\n       Value v2' ->\n       (exists (v1' : E),\n          Value v1' ->\n          set v1 p2 v2' v1')) -> \n    ASGN [] t2 ->\n    forall (p':P), \n      getU u x (p1++p2++p') = None.\nProof.\n  (* By lemmas and case analysis on t2. *)\n  intros h u g x vhx v1 t1 t2 p1 p2.\n  intros valv1 refpder htypder H.mapder getder rtypder gettypeder.\n  intros big.\n  intros asgnder.\n  intros p'.\n  induction t2.\n  Case \"t2 = tvar t\".\n   inversion asgnder.\n   assert (H1': getD [] t = None).\n   apply getD_from_nil_None.\n   rewrite H1 in H1'.\n   inversion H1'.\n  Case \"t2 = cint\".\n   admit.\n  Case \"t2 = cross\".\n   admit.\n  Case \"t2 = arrow\".\n   admit.\n  Case \"t2 = ptype\".\n   admit.\n  Case \"t2 = utype\".\n   admit.\n  Case \"t2 = etype\".\n   admit.\nAdmitted.\n\n(* TODO \nLemma A_11_Heap_Object_Safety_5.\nAdmitted.\nLemma A_11_Heap_Object_Safety_5_Corollary.\nAdmitted.\n*)\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/HeapObjectSafetyProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.28830406150349597}}
{"text": "Require Export Structure.\nRequire Export Categories.Typ.\n\nModule Topology.\n\nModule obj.\n\nStructure mixin_of T := Mixin {\n  open: (T -> Prop) -> Prop;\n  open_all: open (fun _ => True);\n  open_union {I} (F: I -> T -> Prop): (forall i, open (F i)) -> open (fun x => exists i, F i x);\n  open_and (A B: T -> Prop): open A -> open B -> open (fun x => A x /\\ B x);\n}.\n\nLemma mixin_eq {T} (c d: mixin_of T): c = d <-> (forall P, open T c P <-> open T d P).\nProof.\n  split.\n  now intros [].\n  destruct c as [c c1 c2 c3], d as [d d1 d2 d3]; simpl.\n  intros H.\n  enough (c = d); [subst d|].\n  f_equal; apply proof_irrelevance.\n  extensionality P.\n  apply propositional_extensionality.\n  apply H.\nQed.\n\nStructure type := Pack { sort: Type; _: mixin_of sort }.\n\nNotation class_of := mixin_of (only parsing).\n\nSection ClassDef.\nLocal Coercion sort: type >-> Sortclass.\n\nVariable (T: type).\nDefinition class := match T return mixin_of T with Pack _ c => c end.\n\nLet xT := match T with Pack T _ => T end.\nNotation xclass := (class: mixin_of xT).\n\nEnd ClassDef.\n\nModule Exports.\nCoercion sort: type >-> Sortclass.\n\nDefinition open (T: type): (T -> Prop) -> Prop := @open T (class T).\nDefinition open_all (T: type): open T (fun _ => True) := @open_all T (class T).\nDefinition open_union (T: type): forall {I} (F: I -> T -> Prop), (forall i, open T (F i)) -> open T (fun x => exists i, F i x) := @open_union T (class T).\nDefinition open_and (T: type): forall (A B: T -> Prop), open T A -> open T B -> open T (fun x => A x /\\ B x) := @open_and T (class T).\n\nLemma open_all' (T: type) (P: T -> Prop): (forall x, P x) -> open T P.\nProof.\n  intros H.\n  replace P with (fun _: T => True).\n  apply open_all.\n  extensionality x.\n  now apply propositional_extensionality.\nQed.\n\nLemma open_never' (T: type) (P: T -> Prop): (forall x, ~P x) -> open T P.\nProof.\n  intros H.\n  replace P with (fun x: T => exists i: False, (fun _ _ => True) i x).\n  now apply open_union.\n  extensionality x.\n  apply propositional_extensionality.\n  split.\n  intros [[] _].\n  intros Hx.\n  now specialize (H x).\nQed.\n\nLemma open_never (T: type): open T (fun _ => False).\nProof. now apply open_never'. Qed.\n\nLemma open_or (T: type) (A B: T -> Prop): open T A -> open T B -> open T (fun x => A x \\/ B x).\nProof.\n  intros HA HB.\n  cut (open T (fun x => exists b, (fun b: bool => if b then A else B) b x)).\n  change (?P -> ?Q) with (impl P Q).\n  f_equiv.\n  extensionality x.\n  apply propositional_extensionality.\n  split.\n  + intros [[] Hx].\n    all: now [> left | right].\n  + intros [Hx | Hx].\n    now exists true.\n    now exists false.\n  + apply open_union.\n    now intros [].\nQed.\n\nLemma open_filter (T: type) (P: Prop) (A: T -> Prop): (P -> open T A) -> open T (fun x => P /\\ A x).\nProof.\n  intros HA.\n  destruct (classic P).\n  specialize (HA H).\n  revert HA.\n  change (?P -> ?Q) with (impl P Q).\n  f_equiv.\n  extensionality x.\n  now apply propositional_extensionality.\n  now apply open_never'.\nQed.\n\nLemma open_union' (T: type) (F: (T -> Prop) -> Prop): (forall P, F P -> open T P) -> open T (fun x => exists P, F P /\\ P x).\nProof.\n  intros H.\n  specialize (fun P => H (proj1_sig P) (proj2_sig P)).\n  apply open_union in H.\n  revert H.\n  change (?P -> ?Q) with (impl P Q).\n  f_equiv.\n  extensionality x.\n  apply propositional_extensionality.\n  split.\n  + intros [[P HP] Hx].\n    now exists P.\n  + intros [P [HP Hx]].\n    now exists (exist _ P HP).\nQed.\n\nInstance open_iff (T: type): Proper (pointwise_relation T iff ==> iff) (open T).\nProof.\n  intros P Q H.\n  f_equiv.\n  extensionality x.\n  now apply propositional_extensionality.\nQed.\n\nEnd Exports.\nEnd obj.\nExport obj.Exports.\nNotation obj := obj.type.\n\nStructure hom (X Y: obj) := Hom {\n  map: X -> Y;\n  continue (P: Y -> Prop): open Y P -> open X (fun x => P (map x));\n}.\n\nArguments map {X Y} h x.\nArguments continue {X Y} h P H.\n\nCoercion map: hom >-> Funclass.\n\nLemma hom_eq {X Y: obj} (f g: hom X Y): f = g <-> forall x, f x = g x.\nProof.\n  split.\n  now intros [].\n  destruct f as [f Hf], g as [g Hg]; simpl.\n  intros H.\n  enough (f = g); [subst g|].\n  f_equal; apply proof_irrelevance.\n  now extensionality x.\nQed.\n\nProgram Definition cat_mixin := Category.Mixin obj hom\n  (fun X => {|\n    map x := x;\n    continue P H := H;\n  |})\n  (fun X Y Z f g => {|\n    map x := f (g x);\n    continue P H := continue g _ (continue f P H);\n  |})\n  _ _ _.\nNext Obligation.\n  now destruct f.\nQed.\nNext Obligation.\n  now destruct f.\nQed.\n\nCanonical cat := Category.Pack obj cat_mixin.\n\nClass Basis {I T} (F: I -> T -> Prop) :=\n  basis: (forall x, exists i, F i x) /\\\n  (forall i j x, F i x -> F j x -> exists k, F k x /\\ (forall x, F k x -> F i x /\\ F j x)).\n\nProgram Definition basis_mixin {I T} (F: I -> T -> Prop) (H: Basis F) := obj.Mixin T (fun P => exists G: I -> Prop, (fun x => exists i, G i /\\ F i x) = P) _ _ _.\nNext Obligation.\n  exists (fun _ => True).\n  extensionality x.\n  apply propositional_extensionality.\n  split; intros _.\n  constructor.\n  destruct (proj1 H x) as [i Hi].\n  now exists i.\nQed.\nNext Obligation.\n  rename I0 into J.\n  apply ex_forall in H0.\n  destruct H0 as [G HG].\n  apply functional_extensionality_dep in HG.\n  subst F0.\n  exists (fun i => exists j, G j i).\n  extensionality x.\n  apply propositional_extensionality.\n  split.\n  + intros [i [[j Hj] Hi]].\n    now exists j, i.\n  + intros [j [i [Hj Hi]]].\n    exists i; split.\n    now exists j.\n    exact Hi.\nQed.\nNext Obligation.\n  rename H0 into L, H1 into R.\n  exists (fun i => exists l r, (L l /\\ R r) /\\ forall x, F i x -> F l x /\\ F r x).\n  extensionality x.\n  apply propositional_extensionality.\n  split.\n  + intros [i [[l [r [[Hl Hr] Hi]]] Hx]].\n    apply Hi in Hx.\n    split.\n    now exists l.\n    now exists r.\n  + intros [[l [Hl H1]] [r [Hr H2]]].\n    destruct (proj2 H l r x H1 H2) as [i [Hx Hi]].\n    exists i; split.\n    now exists l, r.\n    exact Hx.\nQed.\n\nLemma basis_open {I T} (F: I -> T -> Prop) (HF: Basis F) (P: T -> Prop): (exists i, forall x, F i x <-> P x) -> obj.open T (basis_mixin F HF) P.\nProof.\n  intros [i Hi].\n  exists (eq i).\n  extensionality x.\n  apply propositional_extensionality.\n  rewrite <- Hi.\n  split.\n  now intros [_ [[] Hx]].\n  intros Hx.\n  now exists i.\nQed.\n\nLemma basis_continue {S: obj} {I T} (F: I -> T -> Prop) (HF: Basis F) (f: S -> T): (forall P: T -> Prop, obj.open T (basis_mixin F HF) P -> open S (fun x => P (f x))) <-> (forall i, open S (fun x => F i (f x))).\nProof.\n  split.\n  + intros H i.\n    apply H, basis_open.\n    now exists i.\n  + intros H _ [P []].\n    apply open_union.\n    intros i.\n    now apply open_filter.\nQed.\n\nInstance open_basis (T: obj): Basis (fun P x => open T P /\\ P x).\nProof.\n  split.\n  + intros x.\n    exists (fun _ => True); split.\n    apply open_all.\n    exact I.\n  + intros L R x [HL Lx] [HR Rx].\n    exists (fun x => L x /\\ R x); split.\n    split.\n    now apply open_and.\n    all: easy.\nQed.\n\nLemma open_basis_eq (T: obj): basis_mixin (fun P x => open T P /\\ P x) _ = obj.class T.\nProof.\n  apply obj.mixin_eq.\n  intros P.\n  split.\n  + revert P.\n    apply basis_continue.\n    intros i.\n    now apply open_filter.\n  + intros HP.\n    apply basis_open.\n    now exists P.\nQed.\n\nProgram Definition sig_mixin {T: obj} (P: T -> Prop) := basis_mixin (fun Q (x: sig P) => open T Q /\\ Q (proj1_sig x)) _.\nNext Obligation.\n  split.\n  + intros x.\n    exists (fun _ => True); split.\n    apply open_all.\n    exact I.\n  + intros L R x Lx Rx.\n    exists (fun x => L x /\\ R x); split.\n    split.\n    now apply open_and.\n    all: easy.\nQed.\n\nCanonical sig {T: obj} (P: T -> Prop) := obj.Pack (sig P) (sig_mixin P).\n\nProgram Canonical proj1_sig {T: obj} {P: T -> Prop} := {|\n  map := @proj1_sig T P;\n|}.\nNext Obligation.\n  apply basis_open.\n  now exists P0.\nQed.\n\nModule Open.\n\nStructure obj (T: obj) := Obj {\n  class: T -> Prop;\n  class_open: open T class;\n}.\n\nArguments class {T} o t.\nArguments class_open {T} o.\nCoercion class: obj >-> Funclass.\n\nDefinition hom {T} (X Y: obj T) := forall x, X x -> Y x.\n\nLemma obj_eq {T} (X Y: obj T): X = Y <-> forall x, X x <-> Y x.\nProof.\n  split.\n  now intros [].\n  destruct X as [X HX], Y as [Y HY]; simpl.\n  intros H.\n  enough (X = Y); [subst Y|].\n  f_equiv; apply proof_irrelevance.\n  extensionality x.\n  apply propositional_extensionality.\n  apply H.\nQed.\n\nLemma hom_eq {T} {X Y: obj T} (f g: hom X Y): f = g.\nProof. apply proof_irrelevance. Qed.\n\nProgram Definition cat_mixin T := Category.Mixin (obj T) hom\n  (fun X x H => H)\n  (fun X Y Z f g x H => f x (g x H))\n  _ _ _.\n\nCanonical cat T := Category.Pack (obj T) (cat_mixin T).\n\nProgram Definition Proj {T} := {|\n  fobj (U: cat T) := sig U;\n  fmap U V f := {|\n    map x := exist _ (proj1_sig x) (f (proj1_sig x) (proj2_sig x));\n  |};\n|}.\nNext Obligation.\n  revert P H.\n  apply basis_continue.\n  intros P; simpl.\n  apply basis_open.\n  now exists P.\nQed.\nNext Obligation.\n  apply Topology.hom_eq; simpl.\n  now intros [x Hx].\nQed.\nNext Obligation.\n  now apply Topology.hom_eq.\nQed.\n\nDefinition preimg {S T} (f: T ~> S) (X: obj S): obj T := {|\n  class x := X (f x);\n  class_open := continue f X (class_open X);\n|}.\n\nDefinition preimg_inc {S T} (f: T ~> S) (X Y: obj S): X ~> Y -> preimg f X ~> preimg f Y.\nProof.\n  intros H x.\n  exact (H (f x)).\nQed.\n\nProgram Canonical Preimg {S T} (f: T ~> S): Functor (cat S) (cat T) := {|\n  fobj := preimg f;\n  fmap := preimg_inc f;\n|}.\nNext Obligation.\n  apply hom_eq.\nQed.\nNext Obligation.\n  apply hom_eq.\nQed.\n\nProgram Definition img {S T} (f: S ~> T) (X: obj S): obj T := {|\n  class y := exists Y, hom (preimg f Y) X /\\ Y y;\n|}.\nNext Obligation.\n  apply open_union.\n  intros Y.\n  destruct (classic (hom (preimg f Y) X)).\n  generalize (class_open Y).\n  change (?P -> ?Q) with (impl P Q).\n  f_equiv.\n  extensionality y.\n  now apply propositional_extensionality.\n  now apply open_never'.\nQed.\n\nDefinition img_inc {S T} (f: S ~> T) (X Y: obj S): X ~> Y -> img f X ~> img f Y.\nProof.\n  intros H y [Z [HZ Hy]].\n  exists Z; split.\n  intros z Hz.\n  apply H, HZ, Hz.\n  exact Hy.\nQed.\n\nProgram Canonical Img {S T} (f: S ~> T): Functor (cat S) (cat T) := {|\n  fobj := img f;\n  fmap := img_inc f;\n|}.\nNext Obligation.\n  apply hom_eq.\nQed.\nNext Obligation.\n  apply hom_eq.\nQed.\n\nLemma img_unit {S T} (f: S ~> T) (X: obj T): X ~> Img f (Preimg f X).\nProof.\n  intros x Hx.\n  exists X; split.\n  2: exact Hx.\n  intros y Hy.\n  exact Hy.\nQed.\n\nProgram Canonical imgU {S T} (f: S ~> T): id (cat T) ~> Img f ∘ Preimg f := {|\n  transform := img_unit f;\n|}.\nNext Obligation.\n  apply hom_eq.\nQed.\n\nLemma img_counit {S T} (f: S ~> T) (X: obj S): Preimg f (Img f X) ~> X.\nProof.\n  intros x [Y [H Hx]].\n  apply H, Hx.\nQed.\n\nProgram Canonical imgCU {S T} (f: S ~> T): Preimg f ∘ Img f ~> id (cat S) := {|\n  transform := img_counit f;\n|}.\nNext Obligation.\n  apply hom_eq.\nQed.\n\nLemma img_adjoint_by {S T} (f: S ~> T): adjoint_by (Preimg f) (Img f) (imgU f) (imgCU f).\nProof.\n  apply adjoint_by_alt; split.\n  all: intros X.\n  all: apply hom_eq.\nQed.\n\nProgram Definition top_mixin T := TopCategory.Mixin (cat T)\n  {|\n    class _ := True;\n    class_open := open_all T;\n  |}\n  (fun _ _ _ => I)\n  _.\nNext Obligation.\n  apply hom_eq.\nQed.\n\nCanonical top T := TopCategory.Pack (cat T) (top_mixin T).\n\nProgram Definition prod_mixin T := ProdCategory.Mixin (cat T)\n  (fun X Y => {|\n    class x := X x /\\ Y x;\n  |})\n  (fun X Y Z f g x H => conj (f x H) (g x H))\n  (fun X Y x => @proj1 _ _)\n  (fun X Y x => @proj2 _ _)\n  _.\nNext Obligation.\n  apply open_and.\n  all: apply class_open.\nQed.\nNext Obligation.\n  repeat split; intros.\n  all: apply hom_eq.\nQed.\n\nCanonical prod T := ProdCategory.Pack (cat T) (prod_mixin T).\n\nLemma preimg_prod {S T} (f: T ~> S) (X Y: obj S): preimg f (X × Y) = preimg f X × preimg f Y.\nProof. now apply obj_eq. Qed.\n\nLemma img_prod {S T} (f: S ~> T) (X Y: obj S): img f (X × Y) = img f X × img f Y.\nProof.\n  apply obj_eq.\n  intros x.\n  split.\n  + intros [Z [HZ Hx]].\n    split.\n    all: exists Z; split.\n    2, 4: exact Hx.\n    all: intros z Hz.\n    all: apply HZ, Hz.\n  + intros [[L [HL Lx]] [R [HR Rx]]].\n    exists (L × R); split.\n    2: now split.\n    intros z Hz; split.\n    apply HL, Hz.\n    apply HR, Hz.\nQed.\n\nProgram Definition coprod_mixin T := CoprodCategory.Mixin (cat T)\n  (fun X Y => {|\n    class x := X x \\/ Y x;\n  |})\n  (fun X Y Z f g x H =>\n    match H with\n    | or_introl H => f x H\n    | or_intror H => g x H\n    end\n  )\n  (fun X Y x => @or_introl _ _)\n  (fun X Y x => @or_intror _ _)\n  _.\nNext Obligation.\n  apply open_or.\n  all: apply class_open.\nQed.\nNext Obligation.\n  repeat split; intros.\n  all: apply hom_eq.\nQed.\n\nCanonical coprod T := CoprodCategory.Pack (cat T) (coprod_mixin T).\n\nProgram Definition scoprod_mixin T := SCoprodCategory.Mixin (cat T)\n  (fun I F => {|\n    class x := exists i, F i x;\n  |})\n  _ _ _.\nNext Obligation.\n  apply open_union.\n  intros i.\n  apply class_open.\nQed.\nNext Obligation.\n  intros x [i H].\n  exact (X0 i x H).\nQed.\nNext Obligation.\n  intros x H; simpl.\n  now exists i.\nQed.\nNext Obligation.\n  split; intros.\n  all: apply hom_eq.\nQed.\n\nCanonical scoprod T := SCoprodCategory.Pack (cat T) (scoprod_mixin T).\n\nLemma preimg_scoprod {I S T} (f: T ~> S) (F: I -> obj S): preimg f (∑ i, F i) = ∑ i, preimg f (F i).\nProof. now apply obj_eq. Qed.\n\nLemma img_scoprod {I S T} (f: S ~> T) (F: I -> obj S): ∑ i, img f (F i) ~> img f (∑ i, F i).\nProof.\n  intros y [i [Y [HY Hy]]].\n  exists Y; split.\n  2: exact Hy.\n  intros x H.\n  exists i.\n  apply HY, H.\nQed.\n\nEnd Open.\n\nNotation Open := Open.cat.\n\nModule OpenN.\nImport Open.\n\nStructure obj (T: Topology.obj) (x: T) := Obj {\n  forget: Open.obj T;\n  class_point: forget x;\n}.\n\nArguments forget {T x} o.\nArguments class_point {T x} o.\nCoercion forget: obj >-> Open.obj.\n\nDefinition hom {T x} (X Y: obj T x) := Open.hom X Y.\n\nLemma obj_eq {T x} (X Y: obj T x): X = Y <-> forall x, X x <-> Y x.\nProof.\n  rewrite <- Open.obj_eq.\n  split.\n  now intros [].\n  destruct X as [X HX], Y as [Y HY]; simpl.\n  intros H.\n  subst Y.\n  f_equiv; apply proof_irrelevance.\nQed.\n\nLemma hom_eq {T x} {X Y: obj T x} (f g: hom X Y): f = g.\nProof. apply proof_irrelevance. Qed.\n\nProgram Definition cat_mixin T x := Category.Mixin (obj T x) hom\n  (fun X x H => H)\n  (fun X Y Z f g x H => f x (g x H))\n  _ _ _.\n\nCanonical cat T x := Category.Pack (obj T x) (cat_mixin T x).\n\nProgram Definition top_mixin T x := TopCategory.Mixin (cat T x)\n  {|\n    forget := 1;\n    class_point := I;\n  |}\n  (fun _ _ _ => I)\n  _.\nNext Obligation.\n  apply hom_eq.\nQed.\n\nCanonical top T x := TopCategory.Pack (cat T x) (top_mixin T x).\n\nProgram Definition prod_mixin T x := ProdCategory.Mixin (cat T x)\n  (fun X Y => {|\n    forget := forget X × Y;\n    class_point := conj (class_point X) (class_point Y);\n  |})\n  (fun X Y Z f g x H => conj (f x H) (g x H))\n  (fun X Y x => @proj1 _ _)\n  (fun X Y x => @proj2 _ _)\n  _.\nNext Obligation.\n  repeat split; intros.\n  all: apply hom_eq.\nQed.\n\nCanonical prod T x := ProdCategory.Pack (cat T x) (prod_mixin T x).\n\nProgram Definition coprod_mixin T x := CoprodCategory.Mixin (cat T x)\n  (fun X Y => {|\n    forget := forget X + Y;\n  |})\n  (fun X Y Z f g x H =>\n    match H with\n    | or_introl H => f x H\n    | or_intror H => g x H\n    end\n  )\n  (fun X Y x => @or_introl _ _)\n  (fun X Y x => @or_intror _ _)\n  _.\nNext Obligation.\n  left.\n  apply class_point.\nQed.\nNext Obligation.\n  repeat split; intros.\n  all: apply hom_eq.\nQed.\n\nCanonical coprod T x := CoprodCategory.Pack (cat T x) (coprod_mixin T x).\n\nDefinition forget_inc {T x} (X Y: obj T x) (H: hom X Y): Open.hom (forget X) (forget Y) := H.\n\nProgram Canonical Forget {T x}: Functor (cat T x) (Open T) := {|\n  fobj := @forget T x;\n  fmap := forget_inc;\n|}.\n\nEnd OpenN.\n\nNotation OpenN := OpenN.cat.\n\nProgram Definition empty_mixin := obj.Mixin Empty_set (fun _ => True) _ _ _.\nCanonical empty := obj.Pack Empty_set empty_mixin.\n\nProgram Definition botCat_mixin := BotCategory.Mixin cat\n  empty\n  (fun T => {|\n    map := Empty_set_rect (fun _ => T);\n    continue P _ := I;\n  |})\n  _.\nNext Obligation.\n  now apply hom_eq.\nQed.\nCanonical botCat := BotCategory.Pack cat botCat_mixin.\n\nProgram Definition unit_mixin := obj.Mixin unit (fun _ => True) _ _ _.\nCanonical unit := obj.Pack unit unit_mixin.\n\nProgram Definition topCat_mixin := TopCategory.Mixin cat\n  unit\n  (fun T => {|\n    map _ := tt;\n  |})\n  _.\nNext Obligation.\n  destruct (classic (P tt)).\n  now apply open_all'.\n  now apply open_never'.\nQed.\nNext Obligation.\n  apply hom_eq; simpl.\n  intros x.\n  now destruct (f x).\nQed.\nCanonical topCat := TopCategory.Pack cat topCat_mixin.\n\nProgram Definition sum_mixin (T U: obj) := obj.Mixin (T + U) (fun P => open T (fun x => P (inl x)) /\\ open U (fun x => P (inr x))) _ _ _.\nNext Obligation.\n  split; apply open_all.\nQed.\nNext Obligation.\n  split; apply open_union.\n  all: intros i; apply H.\nQed.\nNext Obligation.\n  now split; apply open_and.\nQed.\nCanonical sum (T U: obj) := obj.Pack (T + U) (sum_mixin T U).\n\nProgram Canonical inl {T U: obj} := {|\n  map := @inl T U;\n|}.\nNext Obligation.\n  apply H.\nQed.\n\nProgram Canonical inr {T U: obj} := {|\n  map := @inr T U;\n|}.\nNext Obligation.\n  apply H.\nQed.\n\nProgram Definition coprodCat_mixin := CoprodCategory.Mixin cat sum\n  (fun L R T f g => {|\n    map x := match x with Datatypes.inl x => f x | Datatypes.inr x => g x end;\n  |})\n  (@inl) (@inr)\n  _.\nNext Obligation.\n  now split; apply continue.\nQed.\nNext Obligation.\n  split.\n  + intros H.\n    subst h.\n    now split; apply hom_eq.\n  + intros [].\n    subst f g.\n    apply hom_eq; simpl.\n    now intros [].\nQed.\nCanonical coprodCat := CoprodCategory.Pack cat coprodCat_mixin.\n\nProgram Definition prod_mixin (T U: obj) := basis_mixin (fun (P: (T -> Prop) * (U -> Prop)) p => (open T (fst P) /\\ open U (snd P)) /\\ fst P (fst p) /\\ snd P (snd p)) _.\nNext Obligation.\n  split.\n  + intros [x y].\n    exists (fun _ => True, fun _ => True); split.\n    split; apply open_all.\n    now split.\n  + intros [L1 R1] [L2 R2] p [H1 Hp1] [H2 Hp2]; simpl in *.\n    exists (fun x => L1 x /\\ L2 x, fun y => R1 y /\\ R2 y); split.\n    split.\n    now split; apply open_and.\n    now split.\n    clear p Hp1 Hp2.\n    now intros p [_]; simpl in *.\nQed.\nCanonical prod (T U: obj) := obj.Pack (T * U) (prod_mixin T U).\n\nProgram Canonical fst {T U: obj} := {|\n  map := @fst T U;\n|}.\nNext Obligation.\n  apply basis_open.\n  exists (P, (fun _ => True)); simpl.\n  intros p; split.\n  easy.\n  intros Hp.\n  do 2 split.\n  exact H.\n  apply open_all.\n  exact Hp.\n  exact I.\nQed.\n\nProgram Canonical snd {T U: obj} := {|\n  map := @snd T U;\n|}.\nNext Obligation.\n  apply basis_open.\n  exists ((fun _ => True), P); simpl.\n  intros p; split.\n  easy.\n  intros Hp.\n  do 2 split.\n  apply open_all.\n  exact H.\n  exact I.\n  exact Hp.\nQed.\n\nProgram Definition prodCat_mixin := ProdCategory.Mixin cat prod\n  (fun L R T f g => {|\n    map x := (f x, g x);\n  |})\n  (@fst) (@snd)\n  _.\nNext Obligation.\n  revert P H.\n  apply basis_continue.\n  intros [P Q]; simpl.\n  apply open_filter.\n  intros [HP HQ].\n  apply open_and.\n  all: now apply continue.\nQed.\nNext Obligation.\n  split.\n  + intros H.\n    subst h.\n    now split; apply hom_eq.\n  + intros [].\n    subst f g.\n    apply hom_eq; simpl.\n    intros x.\n    now destruct (h x).\nQed.\nCanonical prodCat := ProdCategory.Pack cat prodCat_mixin.\n\nProgram Definition sigT_mixin {I} (F: I -> obj) := obj.Mixin (sigT F) (fun P => forall i, open (F i) (fun x => P (existT F i x))) _ _ _.\nNext Obligation.\n  apply open_all.\nQed.\nNext Obligation.\n  now apply open_union.\nQed.\nNext Obligation.\n  now apply open_and.\nQed.\nCanonical sigT {I} (F: I -> obj) := obj.Pack (sigT F) (sigT_mixin F).\n\nProgram Canonical existT {I} (F: I -> obj) (i: I) := {|\n  map := existT F i;\n|}.\n\nProgram Canonical sigT_map {I T F} (f: forall i: I, hom (F i) T) := {|\n  map := sigT_rect (fun _ => T) f;\n|}.\nNext Obligation.\n  intros i; simpl.\n  now apply continue.\nQed.\n\nProgram Definition scoprodCat_mixin := SCoprodCategory.Mixin cat (@sigT)\n  (@sigT_map) (@existT) _.\nNext Obligation.\n  split.\n  + intros H.\n    subst g.\n    intros i.\n    now apply hom_eq.\n  + intros H.\n    apply functional_extensionality_dep in H.\n    subst f.\n    apply hom_eq; simpl.\n    now intros [].\nQed.\nCanonical scoprodCat := SCoprodCategory.Pack cat scoprodCat_mixin.\n\nProgram Definition Prod_mixin {I} (F: I -> obj) := basis_mixin (fun l (f: forall i, F i) => List.Forall (fun P => (exists i (Q: F i -> Prop), open (F i) Q /\\ (fun f => Q (f i)) = P) /\\ P f) l) _.\nNext Obligation.\n  split.\n  + intros f.\n    now exists nil.\n  + intros l r f Hl Hr.\n    exists (l ++ r)%list; split.\n    now apply List_Forall_app.\n    clear f Hl Hr.\n    intros f.\n    apply List_Forall_app.\nQed.\n\nDefinition Prod {I} (F: I -> obj) := obj.Pack (forall i, F i) (Prod_mixin F).\n\nProgram Definition sprodCat_mixin := SProdCategory.Mixin cat (@Prod)\n  (fun I T F f => {|\n    map x i := f i x;\n  |})\n  (fun I F i => {|\n    map f := f i;\n  |}) _.\nNext Obligation.\n  revert P H.\n  apply basis_continue.\n  intros l.\n  setoid_rewrite List_Forall_and.\n  apply open_filter.\n  intros Hl.\n  induction Hl.\n  now apply open_all'.\n  setoid_rewrite List_Forall_cons.\n  apply open_and, IHHl.\n  destruct H as [i [Q [HQ Hx]]].\n  subst x.\n  now apply continue.\nQed.\nNext Obligation.\n  apply basis_open.\n  exists ((fun f => P (f i)) :: nil)%list.\n  intros f.\n  rewrite List_Forall_cons.\n  split.\n  now intros [[_ Hi] _].\n  intros Hi.\n  repeat split; [..|easy].\n  now exists i, P.\n  exact Hi.\nQed.\nNext Obligation.\n  split.\n  + intros H.\n    subst g.\n    intros i.\n    now apply hom_eq.\n  + intros H.\n    apply functional_extensionality_dep in H.\n    subst f.\n    now apply hom_eq.\nQed.\nCanonical sprodCat := SProdCategory.Pack cat sprodCat_mixin.\n\nProgram Definition Pull_mixin {X Y Z: obj} (f: X ~> Z) (g: Y ~> Z) := basis_mixin (fun (P: ((X -> Prop) * (Y -> Prop))) (p: PullTyp f g) => (open X (Datatypes.fst P) /\\ open Y (Datatypes.snd P)) /\\ Datatypes.fst P (pfst p) /\\ Datatypes.snd P (psnd p)) _.\nNext Obligation.\n  split.\n  + intros p.\n    exists (fun _ => True, fun _ => True); split.\n    split; apply open_all.\n    split; exact I.\n  + intros [L1 R1] [L2 R2] p [H1 Hp1] [H2 Hp2]; simpl in *.\n    exists (fun x => L1 x /\\ L2 x, fun y => R1 y /\\ R2 y); split.\n    split.\n    now split; apply open_and.\n    now split.\n    clear p Hp1 Hp2.\n    now intros p [_ [Hp1 Hp2]]; simpl in *.\nQed.\nCanonical Pull {X Y Z: obj} (f: X ~> Z) (g: Y ~> Z) := obj.Pack (PullTyp f g) (Pull_mixin f g).\n\nProgram Canonical pfst {X Y Z: obj} {f: X ~> Z} {g: Y ~> Z} := {|\n  map := @pfst X Y Z f g;\n|}.\nNext Obligation.\n  apply basis_open.\n  exists (P, fun _ => True).\n  intros p; split; simpl.\n  now intros [_ [Hp _]].\n  intros Hp; repeat split.\n  exact H.\n  apply open_all.\n  exact Hp.\nQed.\n\nProgram Canonical psnd {X Y Z: obj} {f: X ~> Z} {g: Y ~> Z} := {|\n  map := @psnd X Y Z f g;\n|}.\nNext Obligation.\n  apply basis_open.\n  exists (fun _ => True, P).\n  intros p; split; simpl.\n  now intros [_ [_ Hp]].\n  intros Hp; repeat split.\n  apply open_all.\n  exact H.\n  exact Hp.\nQed.\n\nProgram Definition pullCat_mixin := PullCategory.Mixin cat (@Pull)\n  (@pfst) (@psnd)\n  _\n  (fun X Y Z V f g p1 p2 H => {|\n    map x := {|\n      PullTyp.pfst := p1 x;\n      PullTyp.psnd := p2 x;\n      PullTyp.comm := f_equal (fun f => map f x) H;\n    |};\n  |}) _ _ _.\nNext Obligation.\n  apply hom_eq, PullTyp.comm.\nQed.\nNext Obligation.\n  revert P H0.\n  apply basis_continue.\n  intros [L R]; simpl.\n  apply open_filter.\n  intros [HL HR].\n  apply open_and.\n  all: now apply continue.\nQed.\nNext Obligation.\n  now apply hom_eq.\nQed.\nNext Obligation.\n  now apply hom_eq.\nQed.\nNext Obligation.\n  apply hom_eq; simpl.\n  intros e.\n  now apply PullTyp.t_eq.\nQed.\n\nCanonical pullCat := PullCategory.Pack cat pullCat_mixin.\n\nProgram Canonical Forget: Functor cat Typ := {|\n  fobj := obj.sort;\n  fmap := @map;\n|}.\n\nProgram Definition discrete_mixin T := obj.Mixin T (fun _ => True) _ _ _.\nDefinition discrete T := obj.Pack T (discrete_mixin T).\n\nProgram Definition discrete_map {S T} (f: S -> T): discrete S ~> discrete T := {|\n  map := f;\n|}.\n\nProgram Canonical Discrete: Functor Typ cat := {|\n  fobj := discrete;\n  fmap := @discrete_map;\n|}.\n\nProgram Definition discreteU: id Typ ~> Forget ∘ Discrete := {|\n  transform T x := x;\n|}.\n\nProgram Definition discrete_unit (T: obj): discrete T ~> T := {|\n  map x := x;\n  continue P H := I;\n|}.\n\nProgram Canonical discreteCU: Discrete ∘ Forget ~> id cat := {|\n  transform := discrete_unit;\n|}.\n\nLemma discrete_adjoint: adjoint_by Discrete Forget discreteU discreteCU.\nProof.\n  apply adjoint_by_alt.\n  split.\n  + intros T.\n    now apply hom_eq.\n  + intros T.\n    now extensionality x.\nQed.\n\nProgram Definition indiscrete_mixin T := obj.Mixin T (fun P => (fun _ => False) = P \\/ (fun _ => True) = P) _ _ _.\nNext Obligation.\n  destruct (classic (forall i, (fun _ => False) = F i)).\n  apply functional_extensionality_dep in H0.\n  subst F.\n  left.\n  extensionality x.\n  apply propositional_extensionality.\n  split.\n  intros [].\n  intros [_ []].\n  apply not_all_ex_not in H0.\n  destruct H0 as [i Hi].\n  destruct (H i).\n  contradiction.\n  right.\n  extensionality x.\n  apply propositional_extensionality.\n  split; intros _.\n  exists i.\n  now rewrite <- H0.\n  constructor.\nQed.\nNext Obligation.\n  destruct H, H0.\n  all: subst A B.\n  all: [> left..| right].\n  all: extensionality x.\n  all: now apply propositional_extensionality.\nQed.\nDefinition indiscrete T := obj.Pack T (indiscrete_mixin T).\n\nProgram Definition indiscrete_map {S T} (f: S -> T): indiscrete S ~> indiscrete T := {|\n  map := f;\n|}.\nNext Obligation.\n  destruct H; subst P.\n  apply open_never.\n  apply open_all.\nQed.\n\nProgram Canonical Indiscrete: Functor Typ cat := {|\n  fobj := indiscrete;\n  fmap := @indiscrete_map;\n|}.\nNext Obligation.\n  now apply hom_eq.\nQed.\nNext Obligation.\n  now apply hom_eq.\nQed.\n\nProgram Definition indiscrete_unit (T: obj): T ~> indiscrete T := {|\n  map x := x;\n|}.\nNext Obligation.\n  destruct H; subst P.\n  apply open_never.\n  apply open_all.\nQed.\n\nProgram Canonical indiscreteU: id cat ~> Indiscrete ∘ Forget := {|\n  transform := indiscrete_unit;\n|}.\nNext Obligation.\n  now apply hom_eq.\nQed.\n\nProgram Definition indiscreteCU: Forget ∘ Indiscrete ~> id Typ := {|\n  transform T x := x;\n|}.\n\nLemma indiscrete_adjoint: adjoint_by Forget Indiscrete indiscreteU indiscreteCU.\nProof.\n  apply adjoint_by_alt.\n  split.\n  + intros T.\n    now extensionality x.\n  + intros T.\n    now apply hom_eq.\nQed.\n\nEnd Topology.\n\nExport Topology.obj.Exports.\nCoercion Topology.map: Topology.hom >-> Funclass.\nCanonical Topology.Open.Preimg.\nCanonical Topology.Open.Img.\nCanonical Topology.Open.imgU.\nCanonical Topology.Open.imgCU.\nCanonical Topology.Open.cat.\nCanonical Topology.Open.prod.\nCanonical Topology.Open.coprod.\nCanonical Topology.Open.scoprod.\nCoercion Topology.Open.class: Topology.Open.obj >-> Funclass.\nCanonical Topology.OpenN.cat.\nCanonical Topology.OpenN.prod.\nCanonical Topology.OpenN.coprod.\nCanonical Topology.OpenN.Forget.\nCoercion Topology.OpenN.forget: Topology.OpenN.obj >-> Topology.Open.obj.\nCanonical Topology.sig.\nCanonical Topology.empty.\nCanonical Topology.unit.\nCanonical Topology.sum.\nCanonical Topology.prod.\nCanonical Topology.inl.\nCanonical Topology.inr.\nCanonical Topology.fst.\nCanonical Topology.snd.\nCanonical Topology.sigT.\nCanonical Topology.existT.\nCanonical Topology.cat.\nCanonical Topology.botCat.\nCanonical Topology.topCat.\nCanonical Topology.coprodCat.\nCanonical Topology.prodCat.\nCanonical Topology.scoprodCat.\nCanonical Topology.sprodCat.\nCanonical Topology.Forget.\nCanonical Topology.Discrete.\nCanonical Topology.discreteCU.\nCanonical Topology.Indiscrete.\nCanonical Topology.indiscreteU.\nNotation Topology := Topology.cat.\n", "meta": {"author": "adamAndMath", "repo": "Category", "sha": "1d230ee099a3ec7bd21306a404f38b2b3f3c3865", "save_path": "github-repos/coq/adamAndMath-Category", "path": "github-repos/coq/adamAndMath-Category/Category-1d230ee099a3ec7bd21306a404f38b2b3f3c3865/Categories/Topology.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.28830406150349597}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Relations RelationClasses.\nRequire Import ExtLib.Core.Type.\nRequire Import ExtLib.Core.RelDec.\nRequire Import ExtLib.Structures.Proper.\nRequire Import ExtLib.Data.SigT.\nRequire Import ExtLib.Data.Member.\nRequire Import ExtLib.Data.ListNth.\nRequire Import ExtLib.Data.Option.\nRequire Import ExtLib.Tactics.\nRequire Import Coq.Classes.Morphisms.\n\nSet Implicit Arguments.\nSet Strict Implicit.\nSet Asymmetric Patterns.\nSet Universe Polymorphism.\nSet Printing Universes.\n\nLemma app_ass_trans@{X}\n: forall {T : Type@{X} } (a b c : list T), (a ++ b) ++ c = a ++ b ++ c.\nProof.\n  induction a; simpl.\n  reflexivity.\n  intros. destruct (IHa b c). reflexivity.\nDefined.\n\nLemma app_nil_r_trans : forall {T : Type} (a : list T), a ++ nil = a.\nProof.\n  induction a; simpl.\n  reflexivity.\n  refine match IHa in _ = X return _ = _ :: X with\n         | eq_refl => eq_refl\n         end.\nDefined.\n\nMonomorphic Universe hlist_large.\n\n(** Core Type and Functions **)\nSection hlist.\n  Polymorphic Universe Ui Uv.\n\n  Context {iT : Type@{Ui}}.\n  Variable F : iT -> Type@{Uv}.\n\n  Inductive hlist : list iT -> Type :=\n  | Hnil  : hlist nil\n  | Hcons : forall l ls, F l -> hlist ls -> hlist (l :: ls).\n\n  Definition hlist_hd {a b} (hl : hlist (a :: b)) : F a :=\n    match hl in hlist x return match x return Type@{Uv} with\n                               | nil => unit\n                               | l :: _ => F l\n                               end with\n    | Hnil => tt\n    | Hcons _ _ x _ => x\n    end.\n\n  Definition hlist_tl {a b} (hl : hlist (a :: b)) : hlist b :=\n    match hl in hlist x return match x return Type@{hlist_large} with\n                                 | nil => unit\n                                 | _ :: ls => hlist ls\n                               end with\n      | Hnil => tt\n      | Hcons _ _ _ x => x\n    end.\n\n  Lemma hlist_eta : forall ls (h : hlist ls),\n    h = match ls as ls return hlist ls -> hlist ls with\n        | nil => fun _ => Hnil\n        | a :: b => fun h => Hcons (hlist_hd h) (hlist_tl h)\n        end h.\n  Proof.\n    intros. destruct h; auto.\n  Qed.\n\n  Fixpoint hlist_app ll lr (h : hlist ll) : hlist lr -> hlist (ll ++ lr) :=\n    match h in hlist ll return hlist lr -> hlist (ll ++ lr) with\n    | Hnil => fun x => x\n    | Hcons _ _ hd tl => fun r => Hcons hd (hlist_app tl r)\n    end.\n\n  Lemma hlist_app_nil_r\n  : forall ls (h : hlist ls),\n      hlist_app h Hnil =\n      match eq_sym (app_nil_r_trans ls) in _ = t return hlist t with\n      | eq_refl => h\n      end.\n  Proof.\n    induction h; simpl; intros; auto.\n    rewrite IHh at 1.\n    unfold eq_trans. unfold f_equal. unfold eq_sym.\n    clear. revert h.\n    generalize dependent (app_nil_r_trans ls).\n    destruct e. reflexivity.\n  Qed.\n\n  Fixpoint hlist_rev' ls ls' (h : hlist ls) : hlist ls' -> hlist (rev ls ++ ls') :=\n    match h in hlist ls return hlist ls' -> hlist (rev ls ++ ls') with\n    | Hnil => fun h => h\n    | Hcons l ls0 x h' => fun hacc =>\n      match app_ass_trans (rev ls0) (l :: nil) ls' in _ = t\n            return hlist t -> hlist _\n      with\n      | eq_refl => fun x => x\n      end (@hlist_rev' _ (l :: ls') h' (Hcons x hacc))\n    end.\n\n  Definition hlist_rev ls (h : hlist ls) : hlist (rev ls) :=\n    match app_nil_r_trans (rev ls) in _ = t return hlist t with\n      | eq_refl => hlist_rev' h Hnil\n    end.\n\n  Lemma hlist_rev_nil : hlist_rev Hnil = Hnil.\n  Proof.\n    reflexivity.\n  Qed.\n\n  (** TODO: I need hlist_rev_cons **)\n\n  (** Equivalence **)\n  (** TODO: This should change to relations **)\n  Section equiv.\n    Variable eqv : forall x, relation (F x).\n\n    Inductive equiv_hlist : forall ls, hlist ls -> hlist ls -> Prop :=\n    | hlist_eqv_nil : equiv_hlist Hnil Hnil\n    | hlist_eqv_cons : forall l ls x y h1 h2, eqv x y -> equiv_hlist h1 h2 ->\n      @equiv_hlist (l :: ls) (Hcons x h1) (Hcons y h2).\n\n    Global Instance Reflexive_equiv_hlist (R : forall t, Reflexive (@eqv t)) ls\n    : Reflexive (@equiv_hlist ls).\n    Proof.\n      red. induction x; constructor; auto. reflexivity.\n    Qed.\n\n    Global Instance Symmetric_equiv_hlist (R : forall t, Symmetric (@eqv t)) ls\n    : Symmetric (@equiv_hlist ls).\n    Proof.\n      red. induction 1.\n      { constructor. }\n      { constructor. symmetry. assumption. auto. }\n    Qed.\n\n    Global Instance Transitive_equiv_hlist (R : forall t, Transitive (@eqv t)) ls\n    : Transitive (@equiv_hlist ls).\n    Proof.\n      red. induction 1.\n      { intro; assumption. }\n      { rewrite (hlist_eta z).\n        refine\n          (fun H' =>\n             match H' in @equiv_hlist ls X Y\n                   return\n                   match ls as ls return hlist ls -> hlist ls -> Prop with\n                     | nil => fun _ _ : hlist nil => True\n                     | l :: ls => fun (X Y : hlist (l :: ls)) =>\n                                    forall Z x xs,\n                                      eqv (hlist_hd Z) (hlist_hd X) ->\n                                      equiv_hlist xs (hlist_tl X) ->\n                                      (forall z : hlist ls,\n                                         equiv_hlist (hlist_tl X) z ->\n                                         equiv_hlist (hlist_tl Z) z) ->\n                                      @equiv_hlist (l :: ls) Z Y\n                   end X Y\n             with\n               | hlist_eqv_nil => I\n               | hlist_eqv_cons l ls x y h1 h2 pf pf' => _\n             end (Hcons x h1) x _ H H0 (@IHequiv_hlist)).\n        intros. rewrite (hlist_eta Z).\n        constructor. simpl in *. etransitivity. eassumption. eassumption.\n        eapply H3. simpl in *. eassumption. }\n    Qed.\n\n    Lemma equiv_hlist_Hcons\n    : forall ls i a b (c : hlist ls) d,\n        equiv_hlist (Hcons a c) (@Hcons i ls b d) ->\n        (@eqv i a b /\\ equiv_hlist c d).\n    Proof.\n      clear. intros.\n      refine\n        match H in @equiv_hlist ls' l r\n              return match ls' as ls' return hlist ls' -> hlist ls' -> _ with\n                       | nil => fun _ _ => True\n                       | l :: ls => fun l r =>\n                                      eqv (hlist_hd l) (hlist_hd r) /\\\n                                      equiv_hlist (hlist_tl l) (hlist_tl r)\n                     end l r\n        with\n          | hlist_eqv_nil => I\n          | hlist_eqv_cons _ _ _ _ _ _ pf pf' => conj pf pf'\n        end.\n    Defined.\n\n    Lemma equiv_hlist_app\n    : forall a b (c c' : hlist a)  (d d' : hlist b),\n        (equiv_hlist c c' /\\ equiv_hlist d d')\n        <->\n        equiv_hlist (hlist_app c d) (hlist_app c' d').\n    Proof.\n      clear. split.\n      - destruct 1.\n        induction H.\n        + assumption.\n        + simpl. constructor; auto.\n      - induction c.\n        + rewrite (hlist_eta c').\n          simpl; intros; split; auto. constructor.\n        + rewrite (hlist_eta c'); simpl.\n          specialize (IHc (hlist_tl c')).\n          intro.\n          eapply equiv_hlist_Hcons in H. intuition.\n          constructor; auto.\n    Qed.\n\n    Global Instance Injection_equiv_hlist_cons ls i a b (c : hlist ls) d\n    : Injective (equiv_hlist (Hcons a c) (@Hcons i ls b d)) :=\n    { result := @eqv i a b /\\ equiv_hlist c d\n    ; injection := @equiv_hlist_Hcons _ _ _ _ _ _ }.\n\n    Global Instance Injection_equiv_hlist_app a b (c c' : hlist a) (d d' : hlist b)\n    : Injective (equiv_hlist (hlist_app c d) (hlist_app c' d')) :=\n    { result := equiv_hlist c c' /\\ equiv_hlist d d'\n    ; injection := fun x => proj2 (@equiv_hlist_app _ _ _ _ _ _) x }.\n\n  End equiv.\n\n  Lemma hlist_nil_eta : forall (h : hlist nil), h = Hnil.\n  Proof.\n    intros; rewrite (hlist_eta h); reflexivity.\n  Qed.\n\n  Lemma hlist_cons_eta : forall a b (h : hlist (a :: b)),\n    h = Hcons (hlist_hd h) (hlist_tl h).\n  Proof.\n    intros; rewrite (hlist_eta h); reflexivity.\n  Qed.\n\n  Lemma Hcons_inv\n  : forall l ls a b c d,\n      @eq (hlist (l :: ls)) (Hcons a b) (Hcons c d) ->\n      a = c /\\ b = d.\n  Proof.\n    intros.\n    refine (\n        match H as K in _ = Z\n              return match Z in hlist LS\n                           return match LS with\n                                    | nil => Prop\n                                    | l :: ls => F l -> hlist ls -> Prop\n                                  end\n                     with\n                       | Hcons X Y x y => fun a b => a = x /\\ b = y\n                       | Hnil => True\n                     end a b\n        with\n          | eq_refl => conj eq_refl eq_refl\n        end).\n  Qed.\n\n  Global Instance Injection_hlist_cons ls t (a : F t) (b : hlist ls) c d\n  : Injective (Hcons a b = Hcons c d) :=\n    { result := a = c /\\ b = d\n    ; injection := @Hcons_inv t ls a b c d\n    }.\n\n\n  Theorem equiv_eq_eq : forall ls (x y : hlist ls),\n                          equiv_hlist (fun x => @eq _) x y <-> x = y.\n  Proof.\n    induction x; simpl; intros.\n    { split. inversion 1. rewrite hlist_nil_eta. reflexivity.\n      intros; subst; constructor. }\n    { split.\n      { intro. rewrite (hlist_eta y).\n        specialize (IHx (hlist_tl y)).\n        refine (match H in @equiv_hlist _ LS X Y\n                      return match X in hlist LS\n                                   return F match LS with\n                                              | nil => l\n                                              | l :: _ => l\n                                            end ->\n                                          hlist match LS with\n                                                  | nil => ls\n                                                  | _ :: ls => ls\n                                                end ->\n                                          Prop\n                             with\n                               | Hnil => fun _ _ => True\n                               | Hcons a b c d => fun x y =>\n                                                    (equiv_hlist (fun x0 : iT => eq) d y <-> d = y) ->\n                                                    @Hcons a b c d = Hcons x y\n                             end (match LS as LS return hlist LS -> F match LS with\n                                                                        | nil => l\n                                                                        | l :: _ => l\n                                                                      end\n                                  with\n                                    | nil => fun _ => f\n                                    | l :: ls => hlist_hd\n                                  end Y)\n                                 (match LS as LS return hlist LS -> hlist match LS with\n                                                                            | nil => ls\n                                                                            | _ :: ls => ls\n                                                                          end\n                                  with\n                                    | nil => fun _ => x\n                                    | l :: ls => hlist_tl\n                                  end Y)\n                with\n                  | hlist_eqv_nil => I\n                  | hlist_eqv_cons l ls x y h1 h2 pf1 pf2 => _\n                end IHx).\n        simpl.\n        subst. intros.\n        f_equal. apply H0. assumption. }\n      { intros; subst. constructor; auto.\n        reflexivity. } }\n  Qed.\n\n  Fixpoint hlist_get ls a (m : member a ls) : hlist ls -> F a :=\n    match m in member _ ls return hlist ls -> F a with\n      | MZ _ => hlist_hd\n      | MN _ _ r => fun hl => hlist_get r (hlist_tl hl)\n    end.\n\n  Fixpoint hlist_nth_error {ls} (hs : hlist ls) (n : nat)\n    : option (match nth_error ls n with\n                | None => unit\n                | Some x => F x\n              end) :=\n    match hs in hlist ls return option (match nth_error ls n with\n                                          | None => unit\n                                          | Some x => F x\n                                        end)\n      with\n      | Hnil => None\n      | Hcons l ls h hs =>\n        match n as n return option (match nth_error (l :: ls) n with\n                                      | None => unit\n                                      | Some x => F x\n                                    end)\n          with\n          | 0 => Some h\n          | S n => hlist_nth_error hs n\n        end\n    end.\n\n  Polymorphic Fixpoint hlist_nth ls (h : hlist ls) (n : nat) :\n    match nth_error ls n return Type with\n      | None => unit\n      | Some t => F t\n    end :=\n    match h in hlist ls , n as n\n      return match nth_error ls n with\n               | None => unit\n               | Some t => F t\n             end\n      with\n      | Hnil , 0 => tt\n      | Hnil , S _ => tt\n      | Hcons _ _ x _ , 0 => x\n      | Hcons _ _ _ h , S n => hlist_nth h n\n    end.\n\n  Fixpoint nth_error_hlist_nth ls (n : nat)\n  : option (hlist ls -> match nth_error ls n with\n                          | None => Empty_set\n                          | Some x => F x\n                        end) :=\n    match ls as ls\n          return option (hlist ls -> match nth_error ls n with\n                                       | None => Empty_set\n                                       | Some x => F x\n                                     end)\n    with\n      | nil => None\n      | l :: ls =>\n        match n as n\n              return option (hlist (l :: ls) -> match nth_error (l :: ls) n with\n                                                  | None => Empty_set\n                                                  | Some x => F x\n                                                end)\n        with\n          | 0 => Some hlist_hd\n          | S n =>\n            match nth_error_hlist_nth ls n with\n              | None => None\n              | Some f => Some (fun h => f (hlist_tl h))\n            end\n        end\n    end.\n\n  Definition cast1 T l\n  : forall (l' : list T) n v,\n      nth_error l n = Some v -> Some v = nth_error (l ++ l') n.\n  Proof.\n    induction l. intros.\n    { exfalso. destruct n; inversion H. }\n    { destruct n; simpl; intros; auto. }\n  Defined.\n\n  Definition cast2 T l\n  : forall (l' : list T) n,\n      nth_error l n = None ->\n      nth_error l' (n - length l) = nth_error (l ++ l') n.\n  Proof.\n    induction l; simpl.\n    { destruct n; simpl; auto. }\n    { destruct n; simpl; auto.\n      inversion 1. }\n  Defined.\n\n  Theorem hlist_nth_hlist_app\n  : forall l l' (h : hlist l) (h' : hlist l') n,\n    hlist_nth (hlist_app h h') n =\n    match nth_error l n as k\n      return nth_error l n = k ->\n      match nth_error (l ++ l') n return Type with\n        | None => unit\n        | Some t => F t\n      end\n    with\n      | Some _ => fun pf =>\n        match\n          cast1 _ _ _ pf in _ = z ,\n          eq_sym pf in _ = w\n          return match w return Type with\n                   | None => unit\n                   | Some t => F t\n                 end ->\n                 match z return Type with\n                   | None => unit\n                   | Some t => F t\n                 end\n        with\n          | eq_refl , eq_refl => fun x => x\n        end (hlist_nth h n)\n      | None => fun pf =>\n        match cast2 _ _ _ pf in _ = z\n          return match z with\n                   | Some t => F t\n                   | None => unit\n                 end\n        with\n          | eq_refl => hlist_nth h' (n - length l)\n        end\n    end eq_refl.\n  Proof.\n    induction h; simpl; intros.\n    { destruct n; simpl in *; reflexivity. }\n    { destruct n; simpl.\n      { reflexivity. }\n      { rewrite IHh. reflexivity. } }\n  Qed.\n\n  Section type.\n    Variable eqv : forall x, type (F x).\n\n    Global Instance type_hlist (ls : list iT): type (hlist ls) :=\n    { equal := @equiv_hlist (fun x => @equal _ (eqv x)) ls\n    ; proper :=\n      (fix recur ls (h : hlist ls) : Prop :=\n        match h with\n          | Hnil => True\n          | Hcons _ _ x y => proper x /\\ recur _ y\n        end) ls\n    }.\n\n    Variable eqvOk : forall x, typeOk (eqv x).\n\n    Global Instance typeOk_hlist (ls : list iT): typeOk (type_hlist ls).\n    Proof.\n      constructor.\n      { induction ls; intros.\n        { rewrite (hlist_eta x) in *. rewrite (hlist_eta y) in *.\n          clear. compute; auto. }\n        { rewrite (hlist_eta x) in *. rewrite (hlist_eta y) in *.\n          simpl in H.\n          inv_all. eapply IHls in H1.\n          eapply only_proper in H0; eauto.\n          simpl; tauto. } }\n      { intro. induction ls; simpl.\n        { rewrite (hlist_eta x); intros; constructor. }\n        { rewrite (hlist_eta x); intros; intuition; constructor.\n          eapply preflexive; [ | eauto with typeclass_instances ].\n          eauto with typeclass_instances.\n          eapply IHls; eauto. } }\n      { red. induction 1.\n        { constructor. }\n        { constructor. symmetry. assumption. assumption. } }\n      { red. induction 1.\n        { auto. }\n        { intro H1.\n          etransitivity; [ | eassumption ].\n          constructor; eauto. } }\n    Qed.\n\n    Global Instance proper_hlist_app l l' : proper (@hlist_app l l').\n    Proof.\n      do 6 red. induction 1; simpl; auto.\n      { intros. constructor; eauto.\n        eapply IHequiv_hlist. exact H1. }\n    Qed.\n\n    Lemma hlist_app_assoc : forall ls ls' ls''\n                                 (a : hlist ls) (b : hlist ls') (c : hlist ls''),\n      hlist_app (hlist_app a b) c =\n      match eq_sym (app_ass_trans ls ls' ls'') in _ = t return hlist t with\n        | eq_refl => hlist_app a (hlist_app b c)\n      end.\n    Proof.\n      intros ls ls' ls''.\n      generalize (eq_sym (app_assoc_reverse ls ls' ls'')).\n      induction ls; simpl; intros.\n      { rewrite (hlist_eta a); simpl.\n        reflexivity. }\n      { rewrite (hlist_eta a0). simpl.\n        inversion H.\n        erewrite (IHls H1).\n        unfold f_equal. unfold eq_trans. unfold eq_sym.\n        generalize (app_ass_trans ls ls' ls'').\n        rewrite <- H1.\n        clear. intro.\n        generalize dependent (hlist_app (hlist_tl a0) (hlist_app b c)).\n        destruct e. reflexivity. }\n    Qed.\n\n    Lemma hlist_app_assoc'\n      : forall (ls ls' ls'' : list iT)\n               (a : hlist ls) (b : hlist ls') (c : hlist ls''),\n        hlist_app a (hlist_app b c) =\n        match\n          app_ass_trans ls ls' ls'' in (_ = t) return (hlist t)\n        with\n        | eq_refl => hlist_app (hlist_app a b) c\n        end.\n    Proof.\n      clear. intros.\n      generalize (hlist_app_assoc a b c).\n      generalize (hlist_app (hlist_app a b) c).\n      generalize (hlist_app a (hlist_app b c)).\n      destruct (app_ass_trans ls ls' ls'').\n      simpl. auto.\n    Qed.\n\n    Fixpoint hlist_split ls ls' : hlist (ls ++ ls') -> hlist ls * hlist ls' :=\n      match ls as ls return hlist (ls ++ ls') -> hlist ls * hlist ls' with\n        | nil => fun h => (Hnil, h)\n        | l :: ls => fun h =>\n                       let (a,b) := @hlist_split ls ls' (hlist_tl h) in\n                       (Hcons (hlist_hd h) a, b)\n      end.\n\n    Lemma hlist_app_hlist_split : forall ls' ls (h : hlist (ls ++ ls')),\n      hlist_app (fst (hlist_split ls ls' h)) (snd (hlist_split ls ls' h)) = h.\n    Proof.\n      induction ls; simpl; intros; auto.\n      rewrite (hlist_eta h); simpl.\n      specialize (IHls (hlist_tl h)).\n      destruct (hlist_split ls ls' (hlist_tl h)); simpl in *; auto.\n      f_equal. auto.\n    Qed.\n\n    Lemma hlist_split_hlist_app : forall ls' ls (h : hlist ls) (h' : hlist ls'),\n      hlist_split _ _ (hlist_app h h') = (h,h').\n    Proof.\n      induction ls; simpl; intros.\n      { rewrite (hlist_eta h); simpl; auto. }\n      { rewrite (hlist_eta h); simpl.\n        rewrite IHls. reflexivity. }\n    Qed.\n\n  End type.\n\n  Lemma hlist_hd_fst_hlist_split\n  : forall t (xs ys : list _) (h : hlist (t :: xs ++ ys)),\n      hlist_hd (fst (hlist_split (t :: xs) ys h)) = hlist_hd h.\n  Proof.\n    simpl. intros.\n    match goal with\n    | |- context [ match ?X with _ => _ end ] =>\n      destruct X\n    end. reflexivity.\n  Qed.\n\n  Lemma hlist_tl_fst_hlist_split\n  : forall t (xs ys : list _) (h : hlist (t :: xs ++ ys)),\n      hlist_tl (fst (hlist_split (t :: xs) ys h)) =\n      fst (hlist_split xs ys (hlist_tl h)).\n  Proof.\n    simpl. intros.\n    match goal with\n    | |- context [ match ?X with _ => _ end ] =>\n      remember X\n    end. destruct p. simpl.\n    change h0 with (fst (h0, h1)).\n    f_equal; trivial.\n  Qed.\n\n  Lemma hlist_tl_snd_hlist_split\n  : forall t (xs ys : list _) (h : hlist (t :: xs ++ ys)),\n      snd (hlist_split xs ys (hlist_tl h)) =\n      snd (hlist_split (t :: xs) ys h).\n  Proof.\n    simpl. intros.\n    match goal with\n    | |- context [ match ?X with _ => _ end ] =>\n      remember X\n    end. destruct p.\n    simpl.\n    change h1 with (snd (h0, h1)).\n    rewrite Heqp. reflexivity.\n  Qed.\n\n  Polymorphic Fixpoint nth_error_get_hlist_nth (ls : list iT) (n : nat) {struct ls} :\n    option {t : iT & hlist ls -> F t} :=\n    match\n      ls as ls0\n      return option {t : iT & hlist ls0 -> F t}\n    with\n      | nil => None\n      | l :: ls0 =>\n        match\n          n as n0\n          return option {t : iT & hlist (l :: ls0) -> F t}\n        with\n          | 0 =>\n            Some (@existT _ (fun t => hlist (l :: ls0) -> F t)\n                          l (@hlist_hd _ _))\n          | S n0 =>\n            match nth_error_get_hlist_nth ls0 n0 with\n              | Some (existT x f) =>\n                Some (@existT _ (fun t => hlist _ -> F t)\n                              x (fun h : hlist (l :: ls0) => f (hlist_tl h)))\n              | None => None\n            end\n        end\n    end.\n\n  Theorem nth_error_get_hlist_nth_Some\n    : forall ls n s,\n      nth_error_get_hlist_nth ls n = Some s ->\n      exists pf : nth_error ls n = Some (projT1 s),\n      forall h, projT2 s h = match pf in _ = t\n                                   return match t return Type with\n                                            | Some t => F t\n                                            | None => unit\n                                          end\n                             with\n                               | eq_refl => hlist_nth h n\n                             end.\n  Proof.\n    induction ls; simpl; intros; try congruence.\n    { destruct n.\n      { inv_all; subst; simpl.\n        exists (eq_refl).\n        intros. rewrite (hlist_eta h). reflexivity. }\n      { forward. inv_all; subst.\n        destruct (IHls _ _ H0); clear IHls.\n        simpl in *. exists x0.\n        intros.\n        rewrite (hlist_eta h). simpl. auto. } }\n  Qed.\n\n  Theorem nth_error_get_hlist_nth_None\n  : forall ls n,\n      nth_error_get_hlist_nth ls n = None <->\n      nth_error ls n = None.\n  Proof.\n    induction ls; simpl; intros; try congruence.\n    { destruct n; intuition. }\n    { destruct n; simpl; try solve [ intuition congruence ].\n      specialize (IHls n). forward. }\n  Qed.\n\n  Lemma nth_error_get_hlist_nth_weaken\n  : forall ls ls' n x,\n      nth_error_get_hlist_nth ls n = Some x ->\n      exists z,\n        nth_error_get_hlist_nth (ls ++ ls') n =\n        Some (@existT iT (fun t => hlist (ls ++ ls') -> F t) (projT1 x) z)\n        /\\ forall h h', projT2 x h = z (hlist_app h h').\n  Proof.\n    intros ls ls'. revert ls.\n    induction ls; simpl; intros; try congruence.\n    { destruct n; inv_all; subst.\n      { simpl. eexists; split; eauto.\n        intros. rewrite (hlist_eta h). reflexivity. }\n      { forward. inv_all; subst. simpl.\n        apply IHls in H0. forward_reason.\n        rewrite H. eexists; split; eauto.\n        intros. rewrite (hlist_eta h). simpl in *.\n        auto. } }\n  Qed.\n\n  Lemma nth_error_get_hlist_nth_appL\n  : forall tvs' tvs n,\n      n < length tvs ->\n      exists x,\n        nth_error_get_hlist_nth (tvs ++ tvs') n = Some x /\\\n        exists y,\n          nth_error_get_hlist_nth tvs n = Some (@existT _ _ (projT1 x) y) /\\\n          forall vs vs',\n            (projT2 x) (hlist_app vs vs') = y vs.\n  Proof.\n    clear. induction tvs; simpl; intros.\n    { exfalso; inversion H. }\n    { destruct n.\n      { clear H IHtvs.\n        eexists; split; eauto. eexists; split; eauto.\n        simpl. intros. rewrite (hlist_eta vs). reflexivity. }\n      { apply Lt.lt_S_n in H.\n        { specialize (IHtvs _ H).\n          forward_reason.\n          rewrite H0. rewrite H1.\n          forward. subst. simpl in *.\n          eexists; split; eauto.\n          eexists; split; eauto. simpl.\n          intros. rewrite (hlist_eta vs). simpl. auto. } } }\n  Qed.\n\n  Lemma nth_error_get_hlist_nth_appR\n  : forall tvs' tvs n x,\n      n >= length tvs ->\n      nth_error_get_hlist_nth (tvs ++ tvs') n = Some x ->\n      exists y,\n        nth_error_get_hlist_nth tvs' (n - length tvs) = Some (@existT _ _ (projT1 x) y) /\\\n        forall vs vs',\n          (projT2 x) (hlist_app vs vs') = y vs'.\n  Proof.\n    clear. induction tvs; simpl; intros.\n    { rewrite <- Minus.minus_n_O.\n      rewrite H0. destruct x. simpl.\n      eexists; split; eauto. intros.\n      rewrite (hlist_eta vs). reflexivity. }\n    { destruct n.\n      { inversion H. }\n      { assert (n >= length tvs) by (eapply le_S_n; eassumption). clear H.\n        { forward. inv_all; subst. simpl in *.\n          specialize (IHtvs _ _ H1 H0).\n          simpl in *.\n          forward_reason.\n          rewrite H.\n          eexists; split; eauto.\n          intros. rewrite (hlist_eta vs). simpl. auto. } } }\n  Qed.\n\nEnd hlist.\n\nArguments Hnil {_ _}.\nArguments Hcons {_ _ _ _} _ _.\nArguments equiv_hlist {_ F} R {_} _ _ : rename.\n\n(** Weak Map\n ** This is weak because it does not change the key type\n **)\nSection hlist_map.\n  Variable A : Type.\n  Variables F G : A -> Type.\n  Variable ff : forall x, F x -> G x.\n\n  Fixpoint hlist_map (ls : list A) (hl : hlist F ls) {struct hl} : hlist G ls :=\n    match hl in @hlist _ _ ls return hlist G ls with\n      | Hnil => Hnil\n      | Hcons _ _ hd tl =>\n        Hcons (ff hd) (hlist_map tl)\n    end.\n\n  Theorem hlist_app_hlist_map\n    : forall ls ls' (a : hlist F ls) (b : hlist F ls'),\n      hlist_map (hlist_app a b) =\n      hlist_app (hlist_map a) (hlist_map b).\n  Proof.\n    induction a. simpl; auto.\n    simpl. intros. f_equal. auto.\n  Qed.\n\nEnd hlist_map.\n\nArguments hlist_map {_ _ _} _ {_} _.\n\n\nSection hlist_map_rules.\n  Variable A : Type.\n  Variables F G G' : A -> Type.\n  Variable ff : forall x, F x -> G x.\n  Variable gg : forall x, G x -> G' x.\n\n  Theorem hlist_map_hlist_map : forall ls (hl : hlist F ls),\n      hlist_map gg (hlist_map ff hl) = hlist_map (fun _ x => gg (ff x)) hl.\n  Proof.\n    induction hl; simpl; f_equal. assumption.\n  Defined.\n\n  Theorem hlist_get_hlist_map : forall ls t (hl : hlist F ls) (m : member t ls),\n      hlist_get m (hlist_map ff hl) = ff (hlist_get m hl).\n  Proof.\n    induction m; simpl.\n    { rewrite (hlist_eta hl). reflexivity. }\n    { rewrite (hlist_eta hl). simpl. auto. }\n  Defined.\n\n  Lemma hlist_map_ext : forall (ff gg : forall x, F x -> G x),\n      (forall x t, ff x t = gg x t) ->\n      forall ls (hl : hlist F ls),\n        hlist_map ff hl = hlist_map gg hl.\n  Proof.\n    induction hl; simpl; auto.\n    intros. f_equal; auto.\n  Defined.\n\nEnd hlist_map_rules.\n\nLemma equiv_hlist_map\n: forall T U (F : T -> Type) (R : forall t, F t -> F t -> Prop)\n         (R' : forall t, U t -> U t -> Prop)\n         (f g : forall t, F t -> U t),\n    (forall t (x y : F t), R t x y -> R' t (f t x) (g t y)) ->\n    forall  ls (a b : hlist F ls),\n      equiv_hlist R a b ->\n      equiv_hlist R' (hlist_map f a) (hlist_map g b).\nProof.\n  clear. induction 2; simpl; intros.\n  - constructor.\n  - constructor; eauto.\nQed.\n\n\n(** Linking Heterogeneous Lists and Lists **)\n\nSection hlist_gen.\n  Variable A : Type.\n  Variable F : A -> Type.\n  Variable f : forall a, F a.\n\n  Fixpoint hlist_gen ls : hlist F ls :=\n    match ls with\n    | nil => Hnil\n    | cons x ls' => Hcons (f x) (hlist_gen ls')\n    end.\n\n  Lemma hlist_get_hlist_gen : forall ls t (m : member t ls),\n    hlist_get m (hlist_gen ls) = f t.\n  Proof.\n    induction m; simpl; auto.\n  Qed.\n\n  (** This function is a generalisation of [hlist_gen] in which the function [f]\n    takes the additional parameter [member a ls]. **)\n  Fixpoint hlist_gen_member ls : (forall a, member a ls -> F a) -> hlist F ls :=\n    match ls as ls return ((forall a : A, member a ls -> F a) -> hlist F ls) with\n    | nil => fun _ => Hnil\n    | a :: ls' => fun fm =>\n        Hcons (fm a (MZ a ls'))\n          (hlist_gen_member (fun a' (M : member a' ls') => fm a' (MN a M)))\n    end.\n\n  Lemma hlist_gen_member_hlist_gen : forall ls,\n    hlist_gen_member (fun a _ => f a) = hlist_gen ls.\n  Proof.\n    induction ls; simpl; f_equal; auto.\n  Qed.\n\n  Lemma hlist_gen_member_ext : forall ls (f g : forall a, member a ls -> F a),\n    (forall x M, f x M = g x M) ->\n    hlist_gen_member f = hlist_gen_member g.\n  Proof.\n    intros. induction ls; simpl; f_equal; auto.\n  Qed.\n\nEnd hlist_gen.\n\nArguments hlist_gen {A F} f ls.\n\nLemma hlist_gen_member_hlist_map : forall A (F G : A -> Type) (ff : forall t, F t -> G t) ls f,\n  hlist_map ff (hlist_gen_member F (ls := ls) f) = hlist_gen_member G (fun a M => ff _ (f _ M)).\nProof.\n  intros. induction ls; simpl; f_equal; auto.\nQed.\n\nLemma hlist_gen_hlist_map : forall A (F G : A -> Type) (ff : forall t, F t -> G t) f ls,\n  hlist_map ff (hlist_gen f ls) = hlist_gen (fun a => ff _ (f a)) ls.\nProof.\n  intros. do 2 rewrite <- hlist_gen_member_hlist_gen. apply hlist_gen_member_hlist_map.\nQed.\n\nLemma hlist_gen_ext : forall A F (f g : forall a, F a),\n  (forall x, f x = g x) ->\n  forall ls : list A, hlist_gen f ls = hlist_gen g ls.\nProof.\n  intros. do 2 rewrite <- hlist_gen_member_hlist_gen. apply hlist_gen_member_ext. auto.\nQed.\n\nGlobal Instance Proper_hlist_gen : forall A F,\n  Proper (forall_relation (fun _ => eq) ==> forall_relation (fun _ => eq))\n         (@hlist_gen A F).\nProof.\n  repeat intro. apply hlist_gen_ext. auto.\nQed.\n\nLemma equiv_hlist_gen : forall T (F : T -> Type) (f : forall t, F t) f'\n    (R : forall t, F t -> F t -> Prop),\n  (forall t, R t (f t) (f' t)) ->\n  forall ls,\n    equiv_hlist R (hlist_gen f ls) (hlist_gen f' ls).\nProof.\n  induction ls; simpl; constructor; auto.\nQed.\n\nGlobal Instance Proper_equiv_hlist_gen : forall A (F : A -> Type) R,\n  Proper (forall_relation R ==> forall_relation (@equiv_hlist _ _ R))\n         (@hlist_gen A F).\nProof.\n  repeat intro. apply equiv_hlist_gen. auto.\nQed.\n\nFixpoint hlist_erase {A B} {ls : list A} (hs : hlist (fun _ => B) ls) : list B :=\n  match hs with\n  | Hnil => nil\n  | Hcons _ _ x hs' => cons x (hlist_erase hs')\n  end.\n\nLemma hlist_erase_hlist_gen : forall A B ls (f : A -> B),\n  hlist_erase (hlist_gen f ls) = map f ls.\nProof.\n  induction ls; simpl; intros; f_equal; auto.\nQed.\n\n\n(** Linking Heterogeneous Lists and Predicates **)\n\nSection hlist_Forall.\n  Variable A : Type.\n  Variable P : A -> Prop.\n\n  Fixpoint hlist_Forall ls (hs : hlist P ls) : Forall P ls :=\n    match hs with\n    | Hnil => Forall_nil _\n    | Hcons _ _ H hs' => Forall_cons _ H (hlist_Forall hs')\n    end.\n\nEnd hlist_Forall.\n\n\n(** Heterogeneous Relations **)\nSection hlist_rel.\n  Variable A : Type.\n  Variables F G : A -> Type.\n  Variable R : forall x : A, F x -> G x -> Prop.\n\n  Inductive hlist_hrel : forall ls, hlist F ls -> hlist G ls -> Prop :=\n  | hrel_Hnil : hlist_hrel Hnil Hnil\n  | hrel_Hcons : forall t ts x y xs ys, @R t x y -> @hlist_hrel ts xs ys ->\n                                        @hlist_hrel (t :: ts) (Hcons x xs) (Hcons y ys).\n\nEnd hlist_rel.\n\nSection hlist_rel_map.\n  Variable A : Type.\n  Variables F G F' G' : A -> Type.\n  Variable R : forall x : A, F x -> G x -> Prop.\n  Variable R' : forall x : A, F' x -> G' x -> Prop.\n  Variable ff : forall x : A, F x -> F' x.\n  Variable gg : forall x : A, G x -> G' x.\n\n  Hypothesis R_ff_R' :\n    forall t x y, @R t x y ->\n                  @R' t (ff x) (gg y).\n\n  Theorem hlist_hrel_map\n  : forall ls xs ys,\n      @hlist_hrel A F G R ls xs ys ->\n      @hlist_hrel A F' G' R' ls (hlist_map ff xs) (hlist_map gg ys).\n  Proof.\n    induction 1; simpl; constructor; eauto.\n  Qed.\n\n  Theorem hlist_hrel_cons\n  : forall l ls x xs y ys,\n      @hlist_hrel A F G R (l :: ls) (Hcons x xs) (Hcons y ys) ->\n      @R l x y /\\ @hlist_hrel A F G R ls xs ys.\n  Proof.\n    intros.\n    refine\n      match H in @hlist_hrel _ _ _ _ ls' xs' ys'\n            return\n            match ls' as ls' return hlist F ls' -> hlist G ls' -> Prop with\n              | nil => fun _ _ => True\n              | l' :: ls' => fun x y =>\n                   R (hlist_hd x) (hlist_hd y)\n                /\\ hlist_hrel R (hlist_tl x) (hlist_tl y)\n            end xs' ys'\n      with\n        | hrel_Hnil => I\n        | hrel_Hcons _ _ _ _ _ _ pf pf' => conj pf pf'\n      end.\n  Qed.\n\n  Theorem hlist_hrel_app\n  : forall l ls x xs y ys,\n      @hlist_hrel A F G R (l ++ ls) (hlist_app x xs) (hlist_app y ys) ->\n      @hlist_hrel A F G R l x y /\\ @hlist_hrel A F G R ls xs ys.\n  Proof.\n    induction x.\n    + intros xs y ys. rewrite (hlist_eta y).\n      simpl; intros; split; auto. constructor.\n    + intros xs y ys. rewrite (hlist_eta y).\n      intros. eapply hlist_hrel_cons in H.\n      destruct H.\n      apply IHx in H0.\n      intuition. constructor; auto.\n  Qed.\n\nEnd hlist_rel_map.\n\nTheorem hlist_hrel_equiv\n: forall T (F : T -> Type) (R : forall t, F t -> F t -> Prop) ls (h h' : hlist F ls),\n    hlist_hrel R h h' ->\n    equiv_hlist R h h'.\nProof.\n  induction 1; constructor; auto.\nQed.\n\nTheorem hlist_hrel_flip\n: forall T (F G : T -> Type) (R : forall t, F t -> G t -> Prop) ls\n         (h : hlist F ls) (h' : hlist G ls),\n    hlist_hrel R h h' ->\n    hlist_hrel (fun t a b => R t b a) h' h.\nProof.\n  induction 1; constructor; auto.\nQed.\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/HList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.28830405338077963}}
{"text": "(* [mono_nat] must go first otherwise the default scope becomes nat. *)\nFrom iris.base_logic Require Import mono_nat.\nFrom Perennial.program_proof Require Import\n     mvcc_prelude mvcc_ghost mvcc_inv\n     txnmgr_repr txnmgr_mk txnmgr_new txnmgr_activate_gc\n     txn_repr txn_get txn_put txn_delete txn_do_txn.\nFrom Goose.github_com.mit_pdos.go_mvcc Require Import examples.\nFrom Perennial.goose_lang Require Import grove_ffi_adequacy.\n\nSection program.\nContext `{!heapGS Σ, !mvcc_ghostG Σ}.\n\nDefinition P_Hello (r : dbmap) := ∃ v, r = {[ (U64 0) := v ]}.\nDefinition Q_Hello (r w : dbmap) := w = {[ (U64 0) := Nil ]}.\n\nTheorem wp_hello txn tid r γ τ :\n  {{{ own_txn txn tid r γ τ ∗ ⌜P_Hello r⌝ ∗ txnmap_ptstos τ r }}}\n    hello #txn\n  {{{ (ok : bool), RET #ok;\n      own_txn txn tid r γ τ ∗\n      if ok\n      then ∃ w, ⌜Q_Hello r w ∧ dom r = dom w⌝ ∗\n                txnmap_ptstos τ w\n      else True\n  }}}.\nProof.\n  iIntros (Φ) \"(Htxn & %HP & Hpt) HΦ\".\n  wp_call.\n  unfold txnmap_ptstos.\n  destruct HP as [v HP].\n  rewrite HP.\n  rewrite big_sepM_singleton.\n\n  (***********************************************************)\n  (* txn.Put(0, \"hello\")                                     *)\n  (* txn.Get(0)                                              *)\n  (* txn.Delete(0)                                           *)\n  (* return true                                             *)\n  (***********************************************************)\n  wp_apply (wp_txn__Put with \"[$Htxn $Hpt]\").\n  iIntros \"[Htxn Hpt]\".\n  wp_apply (wp_txn__Get with \"[$Htxn $Hpt]\").\n  iIntros (u found) \"[Htxn [Hpt %Hu]]\".\n  wp_pures.\n  wp_apply (wp_txn__Delete with \"[$Htxn $Hpt]\").\n  iIntros (ok) \"[Htxn Hpt]\".\n  wp_pures.\n  iApply \"HΦ\".\n  iFrame.\n  iModIntro.\n  iExists {[ (U64 0) := Nil ]}.\n  rewrite big_sepM_singleton.\n  iFrame.\n  iPureIntro.\n  unfold Q_Hello.\n  set_solver.\nQed.\n\nTheorem wp_Hello (txn : loc) γ :\n  ⊢ {{{ own_txn_uninit txn γ }}}\n    <<< ∀∀ (v : dbval), dbmap_ptsto γ (U64 0) 1 v >>>\n      Hello #txn @ ↑mvccN\n    <<< ∃∃ (ok : bool), if ok then dbmap_ptsto γ (U64 0) 1 Nil else dbmap_ptsto γ (U64 0) 1 v >>>\n    {{{ RET #(); own_txn_uninit txn γ }}}.\nProof.\n  iIntros \"!>\".\n  iIntros (Φ) \"Htxn HAU\".\n  wp_call.\n\n  (***********************************************************)\n  (* body := func(txn *txn.Txn) bool {                       *)\n  (*     return hello(txn)                                   *)\n  (* }                                                       *)\n  (* ok := t.DoTxn(body)                                     *)\n  (***********************************************************)\n  wp_apply (wp_txn__DoTxn_xres _ _ P_Hello Q_Hello with \"[$Htxn]\").\n  { unfold Q_Hello. apply _. }\n  { unfold spec_body_xres.\n    clear Φ.\n    iIntros (tid r τ Φ) \"(Htxn & %HP & Htxnpt) HΦ\".\n    wp_pures.\n    wp_apply (wp_hello with \"[$Htxn $Htxnpt]\"); first done.\n    iApply \"HΦ\".\n  }\n  iMod \"HAU\".\n  iModIntro.\n  iDestruct \"HAU\" as (v) \"[Hdbpt HAU]\".\n  iExists {[ (U64 0) := v ]}.\n  iSplitL \"Hdbpt\".\n  { unfold dbmap_ptstos.\n    rewrite big_sepM_singleton.\n    iFrame.\n    iPureIntro.\n    unfold P_Hello.\n    by eauto.\n  }\n  iIntros (ok w) \"Hdbpt\".\n  iFrame.\n  destruct ok eqn:E.\n  { (* Case COMMIT. *)\n    unfold Q_Hello.\n    iDestruct \"Hdbpt\" as \"[%HQ Hdbpt]\".\n    rewrite HQ /dbmap_ptstos big_sepM_singleton.\n    iMod (\"HAU\" $! true with \"Hdbpt\") as \"HΦ\".\n    iIntros \"!> Htxn\".\n    wp_pures.\n    by iApply \"HΦ\".\n  }\n  { (* Case ABORT. *)\n    rewrite /dbmap_ptstos big_sepM_singleton.\n    iMod (\"HAU\" $! false with \"Hdbpt\") as \"HΦ\".\n    iIntros \"!> Htxn\".\n    wp_pures.\n    by iApply \"HΦ\".\n  } \nQed.\n\nTheorem wp_CallHello :\n  {{{ True }}}\n    CallHello #()\n  {{{ RET #(); True }}}.\nProof using heapGS0 mvcc_ghostG0 Σ.\n  iIntros (Φ) \"_ HΦ\".\n  wp_call.\n\n  (***********************************************************)\n  (* db := txn.MkTxnMgr()                                    *)\n  (* db.ActivateGC()                                         *)\n  (* txn := db.New()                                         *)\n  (* Hello(txn)                                              *)\n  (***********************************************************)\n  wp_apply wp_MkTxnMgr.\n  iIntros (γ mgr) \"[#Hmgr Hdbpts]\".\n  wp_pures.\n  wp_apply (wp_txnMgr__ActivateGC with \"Hmgr\").\n  wp_pures.\n  wp_apply (wp_txnMgr__New with \"Hmgr\").\n  iIntros (txn) \"Htxn\".\n  wp_pures.\n  wp_apply (wp_Hello with \"Htxn\").\n  iApply ncfupd_mask_intro; first set_solver.\n  iIntros \"Hmask\".\n  iDestruct (big_sepM_lookup _ _ (U64 0) with \"Hdbpts\") as \"Hdbpt\".\n  { rewrite lookup_gset_to_gmap_Some.\n    split; [set_solver | reflexivity].\n  }\n  iExists Nil.\n  iFrame.\n  iIntros (ok) \"Hdbpt\".\n  iMod \"Hmask\" as \"_\".\n  iIntros \"!> Htxn\".\n  wp_pures.\n  by iApply \"HΦ\".\nQed.\n\nEnd program.\n\nModule closed_proof.\n\n  Import adequacy.\n\n  Definition helloΣ := #[heapΣ; mvcc_ghostΣ].\n\n  Lemma hello_adequate σ g :\n    σ.(world).(grove_node_files) = ∅ →\n    g.(global_world).(grove_net) = ∅ →\n    recovery_adequacy.adequate_failstop (CallHello #()) σ g (λ v _ _, v = #()).\n  Proof.\n    intros Hfiles Hnet. eapply (grove_ffi_single_node_adequacy_failstop helloΣ).\n    { rewrite Hnet. done. }\n    { rewrite Hfiles. done. }\n    iIntros (hHeap) \"_ _ !>\". iApply wp_CallHello; auto.\n  Qed.\nEnd closed_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/mvcc/examples_hello.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2882706539739431}}
{"text": "(*******************************************************************\n * Este archivo especifica el estado.\n * \n ******************************************************************)\n\n(* Shortcut notation for partial functions *)\nDefinition partial a b := a -> option b.\nNotation \"a ⇸ b\" := (partial a b) (at level 51, right associativity).\n\nSection State.\n\n  (** Identificadores de OSs e Hypercalls *)\n  Parameter os_ident : Set.\n  Parameter os_ident_eq : forall oi1 oi2 : os_ident, {oi1 = oi2} + {oi1 <> oi2}.\n\n  Parameter Hyperv_call : Set.\n\n  (* Memoria y direcciones *)\n\n  (** Direcciones Virtuales. **)\n  Parameter vadd : Set.\n  Parameter vadd_eq : forall va1 va2 : vadd, {va1 = va2} + {va1 <> va2}.\n\n  (** Direcciones de Máquina. **)\n  Parameter madd :  Set.\n  Parameter madd_eq : forall ma1 ma2 : madd, {ma1 = ma2} + {ma1 <> ma2}.\n\n  (** Direcciones Físicas **)\n  Parameter padd : Set.\n  Parameter padd_eq : forall pa1 pa2 : padd, {pa1 = pa2} + {pa1 <> pa2}.\n\n  (** Memory values. **)\n  Parameter value : Set.\n  Parameter value_eq : forall val1 val2 : value, {val1 = val2} + {val1 <> val2}.\n\n\n  (* Environment *)\n  Record context : Set :=\n    Context {\n        (** una dirección virtual es accesible, no está reserveda por el HV **)\n        ctxt_vadd_accessible: vadd -> bool;\n        (** guest Oss (Confiable/No Confiable) **)\n        ctxt_oss : os_ident -> bool\n      }.\n  \n\n  (* Operative Systems *)\n  Record os := mk_os { curr_page : padd; hcall : option Hyperv_call }.\n\n  Definition oss_map := os_ident ⇸ os.\n\n\n  (* Execution Modes *)\n  Inductive exec_mode := usr | svc.\n  Inductive os_activity := running | waiting.\n\n\n  (* Memory Mappings *)\n  Definition hypervisor_map := os_ident ⇸ padd ⇸ madd.\n\n  Inductive content :=\n  | RW (v : option value)\n  | PT (va_to_ma : vadd ⇸ madd)\n  | Other.\n\n  Definition is_RW c :=\n    match c with\n    | RW _ => True\n    | _ => False\n    end.\n\n  Inductive page_owner :=\n  | Hyp\n  | Os (osi : os_ident)\n  | No_Owner.\n\n  Record page := mk_page { page_content : content; page_owned_by : page_owner }.\n\n  Definition system_memory := madd ⇸ page.\n\n  Definition update mem addr page : system_memory :=\n    fun addr' => if madd_eq addr' addr\n                 then Some page\n                 else mem addr'.\n \n\n  (* States *)\n  Record State :=\n    mk_State {\n        active_os : os_ident;\n        aos_exec_mode : exec_mode;\n        aos_activity : os_activity;\n        oss : oss_map;\n        hypervisor : hypervisor_map;\n        memory : system_memory\n      }.\n\n  \n  Definition va_mapped_to_ma (s : State) (va : vadd) (ma : madd) :=\n    exists (curr_os : os)           (* SO actual *)        \n           (ph_map : padd ⇸ madd)  (* mappings del HV para el SO actual *)\n           (curr_pt_addr : madd)    (* dirección  de la PT del SO actual *)\n           (pt : page)              (* PT del SO actual *)\n           (vt_map : vadd ⇸ madd), (* mappings de la PT del SO actual *)\n      oss s (active_os s) = Some curr_os            \n      /\\ hypervisor s (active_os s) = Some ph_map    \n      /\\ ph_map (curr_page curr_os) = Some curr_pt_addr\n      /\\ memory s curr_pt_addr = Some pt\n      /\\ page_content pt = PT vt_map\n      /\\ vt_map va = Some ma.\n\n  Definition trusted_os (ctxt : context) (s : State) : Prop :=\n    ctxt_oss ctxt (active_os s) = true. \n\nEnd State.\n", "meta": {"author": "agustinmista", "repo": "coq", "sha": "b88431c1bed91cf0d9a69f5a058504edd19482ce", "save_path": "github-repos/coq/agustinmista-coq", "path": "github-repos/coq/agustinmista-coq/coq-b88431c1bed91cf0d9a69f5a058504edd19482ce/virt/State.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584175005616829, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.28827065397394297}}
{"text": "From iris.program_logic Require Export language ectx_language ectxi_language.\nFrom st.prelude Require Export autosubst generic lang_base.\n\n(** The syntax of expressions *)\nInductive expr :=\n| Var (x : var)\n| LetIn (e1 : expr) (e2 : {bind 1 of expr})\n| Lam (e : {bind 1 of expr})\n(* | Fix (e : expr) *)\n(* | Rec (e : {bind 2 of expr}) *)\n| App (e1 e2 : expr)\n(* Base Types *)\n| Lit (l : base_lit)\n| BinOp (op : bin_op) (e1 e2 : expr)\n| If (e0 e1 e2 : expr)\n| Seq (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 : {bind expr}) (e2 : {bind expr})\n(* Recursive Types *)\n| Fold (e : expr)\n| Unfold (e : expr)\n(** Polymorphic Types *)\n(* | TLam (e : expr) *)\n(* | TApp (e : expr). *)\n(* Virt Step *)\n| VirtStep (e : expr).\n\nCoercion LitInt : Z >-> base_lit.\nCoercion LitBool : bool >-> base_lit.\nCoercion Lit : base_lit >-> expr.\nCoercion App : expr >-> Funclass.\nCoercion Var : var >-> expr.\n\nDeclare Scope expr_no_st_scope.\nDelimit Scope expr_no_st_scope with Eₙₒ.\nNotation \"% x\" := (Var x%nat) (at level 8, format \"% x\") : expr_no_st_scope.\n\nNotation \"()\" := (Lit LitUnit) : expr_no_st_scope.\nNotation \"( e1 , e2 , .. , en )\" := (Pair .. (Pair e1 e2) .. en) : expr_no_st_scope.\n\nNotation \"e1 + e2\" := (BinOp PlusOp e1%Eₙₒ e2%Eₙₒ) : expr_no_st_scope.\nNotation \"e1 - e2\" := (BinOp MinusOp e1%Eₙₒ e2%Eₙₒ) : expr_no_st_scope.\nNotation \"e1 ≤ e2\" := (BinOp LeOp e1%Eₙₒ e2%Eₙₒ) : expr_no_st_scope.\nNotation \"e1 < e2\" := (BinOp LtOp e1%Eₙₒ e2%Eₙₒ) : expr_no_st_scope.\nNotation \"e1 = e2\" := (BinOp EqOp e1%Eₙₒ e2%Eₙₒ) : expr_no_st_scope.\n\nInstance Var_Inj : Inj eq eq Var. intros x1 x2 eq. by inversion eq. Qed.\n\nInstance Ids_expr : Ids expr. derive. Defined.\nInstance Rename_expr : Rename expr. derive. Defined.\nInstance Subst_expr : Subst expr. derive. Defined.\nInstance SubstLemmas_expr : SubstLemmas expr. derive. Qed.\n\nLemma Var_closed_n_lt (x : var) n (p : Closed_n n (Var x)) : x < n.\nProof. apply ids_lt_Closed_n. apply p. Qed.\n\n(** Values for STLang *)\nInductive val :=\n| LamV (e : {bind 1 of expr})\n(* | RecV (e : {bind 2 of expr}) *)\n(* | TLamV (e : {bind 1 of expr}) *)\n| LitV (v : base_lit)\n| PairV (v1 v2 : val)\n| InjLV (v : val)\n| InjRV (v : val)\n| FoldV (v : val).\n\nCoercion LitV : base_lit >-> val.\n\nDeclare Scope val_no_st_scope.\nDelimit Scope val_no_st_scope with Vₙₒ.\n\nNotation \"()\" := (LitV LitUnit) : val_no_st_scope.\nNotation \"( v1 , v2 , .. , vn )\" := (PairV .. (PairV v1 v2) .. vn) : val_no_st_scope.\n\nFixpoint of_val (v : val) : expr :=\n match v with\n | LamV e => Lam e\n (* | RecV e => Rec e *)\n (* | TLamV e => TLam e *)\n | LitV v => Lit v\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 | FoldV v => Fold (of_val v)\n end.\n\n(* Notation \"# v\" := (of_val v%Vₙₒ) (at level 8, format \"# v\") : expr_no_st_scope. *)\nCoercion of_val : val >-> expr.\n\nDefinition subst_list_val (vs : list val) : var → expr := subst_list (map of_val vs).\n\nLemma subst_list_val_cons v vs : of_val v .: subst_list_val vs = subst_list_val (v :: vs).\nProof. intros. by asimpl. Qed.\n\nLemma subst_list_val_snoc vs v : subst_list_val (vs ++ [v]) = (upn (length vs) (of_val v .: ids)) >> (subst_list_val vs).\nProof. by rewrite /subst_list_val map_app subst_list_snoc map_length. Qed.\n\n(* Lemma var_subst_list_val_lt_length (vs : list val) (x : var) (p : x < length vs) : *)\n(*   (exists v : val, vs !! x = Some v ∧ (Var x).[subst_list_val vs] = v). *)\n(* Proof. *)\n(*   destruct (vs !! x) eqn:eq. exists v. split; auto. apply ids_subst_list_lookup. by rewrite list_lookup_fmap eq /=. *)\n(*   assert (length vs ≤ x). by apply lookup_ge_None. lia. *)\n(* Qed. *)\nLemma Var_subst_list_closed_n_length (vs : list val) (x : var) (p : Closed_n (length vs) (Var x)) :\n  (exists v : val, vs !! x = Some v ∧ (Var x).[subst_list_val vs] = v).\nProof.\n  destruct (vs !! x) eqn:eq. exists v. split; auto. apply ids_subst_list_lookup. by rewrite list_lookup_fmap eq /=.\n  assert (length vs ≤ x). by apply lookup_ge_None.\n  assert (x < length vs). by apply ids_lt_Closed_n. lia.\nQed.\n\nLemma Var_subst_list_val_lookup (x : var) (ts : list val) t (H : ts !! x = Some t) :\n  (ids x).[subst_list_val ts] = t.\nProof. rewrite /subst_list_val. apply ids_subst_list_lookup. by rewrite list_lookup_fmap H. Qed.\n\n(* Lemma var_subst_list_val (vs : list val) (x : var) : *)\n(*   (exists v : val, vs !! x = Some v ∧ (Var x).[subst_list_val vs] = v) ∨ (vs !! x = None). *)\n(* Proof. *)\n(*   destruct (vs !! x) eqn:eq. *)\n(*   - left. exists v. split; auto. apply ids_subst_list_lookup. by rewrite list_lookup_fmap eq /=. *)\n(*   - by right. *)\n(* Qed. *)\n\nFixpoint to_val (e : expr) : option val :=\n match e with\n | Lam e => Some (LamV e)\n (* | Rec e => Some (RecV e) *)\n (* | TLam e => Some (TLamV e) *)\n | Lit e => Some (LitV e)\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 | Fold e => v ← to_val e; Some (FoldV v)\n | _ => None\n end.\n\nFixpoint val_subst (v : val) (σ : var → expr) : val :=\n  match v with\n  | LamV e => LamV (e.[up σ])\n  | LitV v => LitV v\n  | PairV v1 v2 => PairV (val_subst v1 σ) (val_subst v2 σ)\n  | InjLV v => InjLV (val_subst v σ)\n  | InjRV v => InjRV (val_subst v σ)\n  | FoldV v => FoldV (val_subst v σ)\n  end.\n\nNotation \"v .{ sigma }\" := (val_subst v sigma)\n  (at level 2, sigma at level 200, left associativity,\n   format \"v .{ sigma }\" ).\n\nNotation \"v .{ t /}\" := (val_subst v (t .: ids))\n  (at level 2, t at level 200, left associativity,\n   format \"v .{ t /}\") : subst_scope.\n\nLemma val_subst_valid (v : val) (σ : var → expr) : (of_val v).[σ] = (val_subst v σ).\nProof. induction v; asimpl; try done; (by rewrite IHv1 IHv2) || by rewrite IHv. Qed.\n\nLemma val_subst_comp (v : val) (σ σ' : var → expr) : v.{σ}.{σ'} = v.{σ >> σ'}.\nProof. induction v; asimpl; try done; (by rewrite IHv1 IHv2) || by rewrite IHv. Qed.\n\nLemma to_of_val v : to_val (of_val v) = Some v.\nProof.\n by induction v; try simplify_option_eq; repeat f_equal; try apply (proof_irrel _).\nQed.\nLemma of_to_val e v : to_val e = Some v → of_val v = e.\nProof.\n revert v; induction e; intros v ?; simplify_option_eq; auto with f_equal.\nQed.\n\n(** Equality and other typeclass stuff *)\nInstance of_val_inj : Inj (=) (=) of_val.\nProof. by intros ?? Hv; apply (inj Some); rewrite -!to_of_val Hv. Qed.\n\nInstance base_lit_eq_dec : EqDecision base_lit.\nProof. solve_decision. Defined.\nInstance bin_op_eq_dec : EqDecision bin_op.\nProof. solve_decision. Defined.\nInstance expr_eq_dec : EqDecision expr.\nProof. solve_decision. Defined.\nInstance val_eq_dec : EqDecision val.\nProof.\n refine (λ v v', cast_if (decide (of_val v = of_val v')));\n   abstract naive_solver.\nDefined.\n\nGlobal Instance val_inhabited : Inhabited val := populate ()%Vₙₒ.\n(* Instance expr_inhabited : Inhabited expr := populate (Lit LitUnit). *)\n(* Instance val_inhabited : Inhabited val := populate (LitV LitUnit). *)\n(* Canonical Structure stateC := leibnizO state. *)\n(* Canonical Structure valC := leibnizO val. *)\n(* Canonical Structure eff_valC := leibnizO eff_val. *)\n(* Canonical Structure exprC := leibnizO expr. *)\n\n(** Evaluation contexts *)\nInductive ectx_item :=\n(* | FixCtx *)\n| LetInCtx (e2 : expr)\n| AppLCtx (e2 : expr)\n| AppRCtx (v1 : val)\n(* | TAppCtx *)\n| PairLCtx (e2 : expr)\n| PairRCtx (v1 : val)\n| FstCtx\n| SndCtx\n| InjLCtx\n| InjRCtx\n| CaseCtx (e1 : {bind expr}) (e2 : {bind expr})\n| IfCtx (e2 : expr) (e3 : expr)\n| BinOpLCtx (op : bin_op) (e2 : expr)\n| BinOpRCtx (op : bin_op) (v1 : val)\n| SeqCtx (e2 : expr)\n| FoldCtx\n| UnfoldCtx\n| VirtStepCtx.\n\nDefinition fill_item (Ki : ectx_item) (e : expr) : expr :=\n match Ki with\n (* | FixCtx => Fix e *)\n | LetInCtx e2 => LetIn e e2\n | AppLCtx e2 => App e e2\n | AppRCtx v1 => App (of_val v1) e\n (* | TAppCtx => TApp e *)\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 | IfCtx e1 e2 => If e e1 e2\n | BinOpLCtx op e2 => BinOp op e e2\n | BinOpRCtx op v1 => BinOp op (of_val v1) e\n | SeqCtx e2 => Seq e e2\n | FoldCtx => Fold e\n | UnfoldCtx => Unfold e\n | VirtStepCtx => VirtStep e\n end.\n\n(** The stepping relation *)\n\nDefinition bin_op_eval (op : bin_op) (z1 z2 : Z) : val :=\n match op with\n | PlusOp => LitV $ LitInt (z1 + z2)%Z\n | MinusOp => LitV $ LitInt (z1 - z2)\n | LeOp => LitV $ LitBool $ bool_decide (z1 ≤ z2)%Z\n | LtOp => LitV $ LitBool $ bool_decide (z1 < z2)%Z\n | EqOp => LitV $ LitBool $ bool_decide (z1 = z2)\n end.\n\nDefinition state : Type := ().\n\nInductive head_step : expr → state → list Empty_set → expr → state → list expr → Prop :=\n(* β *)\n  LetIn_head_step e1 v1 e2 σ :\n   to_val e1 = Some v1 →\n   head_step (LetIn e1 e2) σ [] e2.[e1/] σ []\n| App_Lam_head_step e1 e2 v2 σ :\n   to_val e2 = Some v2 →\n   head_step (App (Lam e1) e2) σ [] e1.[e2/] σ []\n(* | App_Rec_head_step e1 e2 v2 σ : *)\n   (* to_val e2 = Some v2 → *)\n   (* head_step (App (Rec e1) e2) σ [] e1.[(Rec e1), e2/] σ [] *)\n(* fix *)\n(* | Fix_head_step e σ : *)\n    (* head_step (Fix (Lam e)) σ [] e.[Fix (Lam e)/] σ [] *)\n(* binary operation *)\n| BinOp_head_step op e1 e2 z1 z2 σ :\n   to_val e1 = Some (LitV $ LitInt z1) → to_val e2 = Some (LitV $ LitInt z2) →\n   head_step (BinOp op e1 e2) σ [] (of_val (bin_op_eval op z1 z2)) σ []\n(* if *)\n| If_True_head_step e1 e2 σ :\n   head_step (If (Lit $ LitBool true) e1 e2) σ [] e1 σ []\n| If_False_head_step e1 e2 σ :\n   head_step (If (Lit $ LitBool false) e1 e2) σ [] e2 σ []\n(* seq *)\n| Seq_Unit_head_step e1 e2 σ :\n    to_val e1 = Some ()%Vₙₒ →\n    head_step (Seq e1 e2) σ [] e2 σ []\n(* Products *)\n| Fst_Pair_head_step e1 v1 e2 v2 σ :\n   to_val e1 = Some v1 → to_val e2 = Some v2 →\n   head_step (Fst (Pair e1 e2)) σ [] e1 σ []\n| Snd_Pair_head_step e1 v1 e2 v2 σ :\n   to_val e1 = Some v1 → to_val e2 = Some v2 →\n   head_step (Snd (Pair e1 e2)) σ [] e2 σ []\n(* Sums *)\n| Case_InjL_head_step e0 v0 e1 e2 σ :\n   to_val e0 = Some v0 →\n   head_step (Case (InjL e0) e1 e2) σ [] e1.[e0/] σ []\n| Case_InjR_head_step e0 v0 e1 e2 σ :\n   to_val e0 = Some v0 →\n   head_step (Case (InjR e0) e1 e2) σ [] e2.[e0/] σ []\n(* Recursive Types *)\n| Unfold_Fold_head_step e v σ :\n   to_val e = Some v →\n   head_step (Unfold (Fold e)) σ [] e σ []\n(* Polymorphic Types *)\n(* | TBeta e σ : *)\n   (* head_step (TApp (TLam e)) σ [] e σ []. *)\n| VirtStep_Lam_head_step e σ :\n   head_step (VirtStep (Lam e)) σ [] (Lam (VirtStep ((Lam e).[ren (+1)] (VirtStep %0))))%Eₙₒ σ []\n| VirtStep_Lit_head_step bl σ :\n   head_step (VirtStep (Lit bl)) σ [] (Lit bl) σ []\n| VirtStep_Pair_head_step e1 v1 e2 v2 σ :\n   to_val e1 = Some v1 →\n   to_val e2 = Some v2 →\n   head_step (VirtStep (Pair e1 e2)) σ [] (Pair (VirtStep e1) (VirtStep e2)) σ []\n| VirtStep_InjL_head_step e v σ :\n   to_val e = Some v →\n   head_step (VirtStep (InjL e)) σ [] (InjL (VirtStep e)) σ []\n| VirtStep_InjR_head_step e v σ :\n   to_val e = Some v →\n   head_step (VirtStep (InjR e)) σ [] (InjR (VirtStep e)) σ []\n| VirtStep_Fold_head_step e v σ :\n   to_val e = Some v →\n   head_step (VirtStep (Fold e)) σ [] (Fold (VirtStep e)) σ [].\n\nLemma App_Lam_head_step' (e' e1 e2 : expr) v2 (eq : e1.[e2/] = e') σ (H : to_val e2 = Some v2) :\n  head_step (Lam e1 e2) σ [] e' σ [].\nProof. rewrite -eq. by eapply App_Lam_head_step. Qed.\n\nInstance fill_item_inj Ki : Inj (=) (=) (fill_item Ki).\nProof. destruct Ki; intros ???; simplify_eq/=; auto with f_equal. Qed.\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.\nLemma val_stuck e1 σ1 κ e2 σ2 efs :\n head_step e1 σ1 κ e2 σ2 efs → to_val e1 = None.\nProof. destruct 1; done. Qed.\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.\n destruct Ki; inversion_clear 1; simplify_option_eq; eauto.\nQed.\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\nLemma st_ectxi_lang_mixin : EctxiLanguageMixin of_val to_val fill_item head_step.\nProof.\n  split; eauto using to_of_val, of_to_val,\n  val_stuck, fill_item_val, fill_item_no_val_inj,\n head_ctx_step_val, fill_item_inj.\nQed.\n\nCanonical Structure STLCmuVS_ectxi_lang : ectxiLanguage := EctxiLanguage st_ectxi_lang_mixin.\nCanonical Structure STLCmuVS_ectx_lang : ectxLanguage := EctxLanguageOfEctxi STLCmuVS_ectxi_lang.\nCanonical Structure STLCmuVS_lang : language := LanguageOfEctx STLCmuVS_ectx_lang.\n\nLemma fill_val (e : expr) (K : list ectx_item):\n  is_Some (to_val (fill K e)) -> is_Some (to_val e).\nProof.\n  move=> [v h]. destruct (to_val e) eqn:eq.\n    by exists v0.\n    have fill_not_val: to_val (fill K e) = None. eauto using fill_not_val.\n    congruence.\nQed.\n\nCanonical Structure valO := valO STLCmuVS_lang.\nCanonical Structure exprO := exprO STLCmuVS_lang.\n\n(* Arguments val_stuck {_ _ _ _ _} _. *)\n(* Arguments fill_val {_ _} _. *)\n\n(* Wrapper around prim_step *)\n\nDefinition STLCmuVS_step (e1 e2 : expr) : Prop := prim_step e1 tt [] e2 tt [].\n\n(* We do not use forks, nor prophecy variables. *)\n\nLemma head_step_no_forks e σ κ e' σ' efs : head_step e σ κ e' σ' efs → efs = [].\nProof. intros H. by inversion H. Qed.\n\nLemma prim_step_no_forks (e : expr) σ κ e' σ' efs : prim_step e σ κ e' σ' efs → efs = [].\nProof. intros H. inversion H. by eapply head_step_no_forks. Qed.\n\nLemma head_step_no_obs e σ κ e' σ' efs : head_step e σ κ e' σ' efs → κ = [].\nProof. intros H. by inversion H. Qed.\n\nLemma prim_step_no_obs (e : expr) σ κ e' σ' efs : prim_step e σ κ e' σ' efs → κ = [].\nProof. intros H. inversion H. by eapply head_step_no_obs. Qed.\n\n(* Our language is deterministic *)\n\nLemma head_step_det e e1 σ1 κ1 σ1' efs1 e2 σ2 κ2 σ2' efs2 : head_step e σ1 κ1 e1 σ1' efs1 → head_step e σ2 κ2 e2 σ2' efs2 → e1 = e2.\nProof. intros H1 H2. inversion H1; inversion H2; ((by simplify_eq) || (try done) || simplify_eq; inversion G2). Qed.\n\nLemma prim_step_det (e e1 e2 : expr) σ κ : prim_step e σ κ e1 σ [] → prim_step e σ κ e2 σ [] → e1 = e2.\nProof.\n  intros H1 H2.\n  inversion H1. inversion H2. simplify_eq. simpl in *.\n  assert (K = K0) as <-.\n  { destruct (step_by_val K K0 _ _ σ κ e2'0 σ [] H4) as [Kred eq] ; try done; try by eapply val_stuck.\n    assert (H4' : fill K0 e1'0 = fill K e1'); first done.\n    destruct (step_by_val K0 K _ _ σ κ e2' σ [] H4') as [Kred' eq'] ; try done; try by eapply val_stuck.\n    rewrite eq in eq'. simpl in *. assert (length K = length (Kred' ++ Kred ++ K)). simpl in *. by rewrite -eq'.\n    do 2 rewrite app_length in H. assert (Kred = []) as ->. apply length_zero_iff_nil. lia. by rewrite eq. }\n  f_equal. assert (e1' = e1'0) as ->. apply (fill_inj K _ _ H4). by eapply head_step_det.\nQed.\n\n(* Our language is pure *)\n\nLemma prim_step_pure (e1 e2 : expr) σ1 σ2 κ efs : prim_step e1 σ1 κ e2 σ2 efs → pure_step e1 e2.\nProof.\n  intros Hprim.\n  assert (efs = []) as ->. by eapply prim_step_no_forks.\n  assert (κ = []) as ->. by eapply prim_step_no_obs.\n  destruct σ1, σ2.\n  split.\n  intros σ. destruct σ. rewrite /reducible_no_obs. by exists e2, tt, [].\n  intros.\n  assert (efs = []) as ->. by eapply prim_step_no_forks.\n  assert (κ = []) as ->. by eapply prim_step_no_obs.\n  destruct σ1, σ2. by erewrite (prim_step_det _ _ _ _ _ H).\nQed.\n\n(* Wrappers around lemmas *)\n\nLemma STLCmuVS_pure e1 e2 : STLCmuVS_step e1 e2 <-> pure_step e1 e2.\nProof.\n  split. apply prim_step_pure. intro H. inversion H.\n  destruct (pure_step_safe tt) as [e2' [σ [efs Hp]]].\n  destruct σ. by destruct (pure_step_det _ _ _ _ _ Hp) as [a [b [-> ->]]].\nQed.\n\nLemma STLCmuVS_step_ctx K `{!LanguageCtx K} e1 e2 : STLCmuVS_step e1 e2 → STLCmuVS_step (K e1) (K e2).\nProof. intro. apply STLCmuVS_pure. apply pure_step_ctx. auto. by apply STLCmuVS_pure. Qed.\n\nLemma rtc_STLCmuVS_step_ctx K `{!LanguageCtx K} e1 e2 : rtc STLCmuVS_step e1 e2 → rtc STLCmuVS_step (K e1) (K e2).\nProof. eauto using rtc_congruence, STLCmuVS_step_ctx. Qed.\n\nLemma nsteps_STLCmuVS_step_ctx K `{!LanguageCtx K} n e1 e2 : nsteps STLCmuVS_step n e1 e2 → nsteps STLCmuVS_step n (K e1) (K e2).\nProof. eauto using nsteps_congruence, STLCmuVS_step_ctx. Qed.\n\nLemma nsteps_PureExec (e1 e2 : expr) n : nsteps STLCmuVS_step n e1 e2 <-> PureExec True n e1 e2.\nProof.\n  split. intros s t. eapply nsteps_congruence with (f := id). by apply STLCmuVS_pure. auto.\n  intro H. eapply nsteps_congruence with (f := id). apply STLCmuVS_pure. apply pure_exec. auto.\nQed.\n\nLemma rtc_PureExec (e1 e2 : expr) : rtc STLCmuVS_step e1 e2 <-> ∃ n, PureExec True n e1 e2.\nProof.\n  split.\n  intro H. assert (H' : rtc pure_step e1 e2).\n  eapply rtc_subrel. by apply STLCmuVS_pure. auto. destruct (iffLR (rtc_nsteps _ _) H') as [n H'']. exists n. intros _. done.\n  intro d. destruct d as [n H]. eapply rtc_nsteps. exists n. by eapply nsteps_PureExec.\nQed.\n\nLemma step_PureExec (e1 e2 : expr) : STLCmuVS_step e1 e2 → PureExec True 1 e1 e2.\nProof. intros s t. apply nsteps_once. by apply STLCmuVS_pure. Qed.\n\nDefinition STLCmuVS_halts (e : STLCmuVS.lang.expr) : Prop :=\n  ∃ (v : STLCmuVS.lang.val), rtc STLCmuVS_step e (STLCmuVS.lang.of_val v).\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/lang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.2881991075820532}}
{"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(*\tDiagonal Functor (used in the definition of Cartesian) \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\nRequire Export PROD.\nRequire Export Functor.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nSection diag.\n\nVariable C : Category.\n\nDefinition Diag_ob (c : C) := Build_POb c c.\n\n Section diag_map_def.\n\n Variable a b : C.\n \n Definition Diag_mor (f : a --> b) :=\n   Build_Pmor (u:=Diag_ob a) (t:=Diag_ob b) f f. \n\n Lemma Diag_map_law : Map_law Diag_mor.\n Proof.\n unfold Map_law, Diag_mor in |- *; simpl in |- *.\n intros f g H; unfold Equal_Pmor in |- *; simpl in |- *.\n split; trivial.\n Qed.\n\n Canonical Structure Diag_map := Build_Map Diag_map_law.\n\n End diag_map_def.\n\nLemma Diag_comp_law : Fcomp_law Diag_map.\nProof.\nunfold Fcomp_law, Diag_map, Diag_mor in |- *; simpl in |- *.\nunfold Equal_Pmor in |- *; simpl in |- *.\nintros a b c f g; split; apply Refl.\nQed.\n\nLemma Diag_id_law : Fid_law Diag_map.\nProof.\nunfold Fid_law, Diag_map, Diag_mor in |- *; simpl in |- *.\nunfold Equal_Pmor, Id_PROD in |- *; simpl in |- *.\nintro a; split; apply Refl.\nQed.\n\nCanonical Structure Diag := Build_Functor Diag_comp_law Diag_id_law. \n\nEnd diag.\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/CCC/Diagonal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.28819909939536564}}
{"text": "(** * Functors to cat are pseudofunctors *)\nRequire Import Category.Core Functor.Core NaturalTransformation.Core.\nRequire Import Functor.Composition.Core NaturalTransformation.Composition.Core NaturalTransformation.Composition.Laws.\nRequire Import Functor.Identity.\nRequire Import Pseudofunctor.Core.\nRequire Import Cat.Core.\nRequire Import FunctorCategory.Core.\nRequire Import FunctorCategory.Morphisms NaturalTransformation.Isomorphisms.\nRequire Import Category.Morphisms NaturalTransformation.Paths.\nRequire Import Basics.PathGroupoids Basics.Trunc.\n\nSet Universe Polymorphism.\nSet Implicit Arguments.\nGeneralizable All Variables.\nSet Asymmetric Patterns.\n\nLocal Open Scope path_scope.\nLocal Open Scope morphism_scope.\n\n(** Every functor to Cat is a pseudofunctor *)\nSection of_functor.\n  Context `{Funext}.\n  Variable C : PreCategory.\n  Context `{HP : forall C D, P C -> P D -> IsHSet (Functor C D)}.\n\n  Local Notation cat := (@sub_pre_cat _ P HP).\n\n  Variable F : Functor C cat.\n\n  Definition path_functor_helper A B (F1 F2 : Functor A B) (pf1 pf2 : F1 = F2)\n  : P A -> P B -> pf1 = pf2\n    := fun PA PB => @path_ishprop _ (@HP A B PA PB F1 F2) _ _.\n\n  Local Hint Extern 0 (P ?x.1) => exact x.2 : core.\n\n  Local Tactic Notation \"transitivity_idtoiso\" open_constr(hyp) :=\n    lazymatch goal with\n      | [ |- ?f (Category.Morphisms.idtoiso ?C _) = _ ] => etransitivity (f (Category.Morphisms.idtoiso C hyp));\n                                       [ do 2 refine (ap _ _); (* https://coq.inria.fr/bugs/show_bug.cgi?id=3626 *)\n                                         apply path_functor_helper;\n                                         simpl; trivial\n                                       | path_natural_transformation ]\n    end.\n\n  Local Ltac pseudofunctor_t :=\n    intros;\n    unfold natural_transformation_of_natural_isomorphism;\n    rewrite ?idtoiso_whisker_r, ?idtoiso_whisker_l;\n    repeat (\n        let C := match goal with |- @paths (@NaturalTransformation ?C ?D ?F ?G) _ _ => constr:((C -> D)%category) end in\n        first [ eapply (@iso_moveL_pV C)\n              | eapply (@iso_moveL_Vp C)\n              | eapply (@iso_moveL_pM C)\n              | eapply (@iso_moveL_Mp C) ];\n        simpl\n      );\n    rewrite ?idtoiso_inv;\n    simpl;\n    change @NaturalTransformation.Composition.Core.compose\n    with (fun C D F G H => Category.Core.compose (C := C -> D) (s := F) (d := G) (d' := H));\n    cbv beta;\n    rewrite ?idtoiso_comp;\n    first [ transitivity_idtoiso (Functor.Composition.Laws.left_identity _)\n          | transitivity_idtoiso ((Functor.Composition.Laws.left_identity _)^)\n          | transitivity_idtoiso (Functor.Composition.Laws.right_identity _)\n          | transitivity_idtoiso ((Functor.Composition.Laws.right_identity _)^)\n          | transitivity_idtoiso (Functor.Composition.Laws.associativity _ _ _)\n          | transitivity_idtoiso ((Functor.Composition.Laws.associativity _ _ _)^) ];\n    rewrite eta_idtoiso;\n    simpl;\n    rewrite ?ap_V, ?Functor.Composition.Laws.left_identity_fst, ?Functor.Composition.Laws.right_identity_fst, ?Functor.Composition.Laws.associativity_fst;\n    try reflexivity.\n\n  (* The following helpers were generated with\n<<\nintros.\n    repeat match goal with\n             | [ |- context[idtoiso ?C (?f ?x)] ] => generalize (f x); intro\n             | [ |- context[MorphismOf ?F ?f] ] => generalize dependent (MorphismOf F f); repeat (let x := fresh \"x\" in intro x)\n             | [ |- context[ObjectOf ?F ?f] ] => generalize dependent (ObjectOf F f); repeat (let x := fresh \"x\" in intro x)\n           end.\n    simpl in *.\n    unfold SubPreCatCat.\n    simpl in *.\n    clear.\n    destruct_head_hnf @sig.\n    simpl in *.\n    repeat match goal with\n             | [ H : _ |- _ ] => revert H\n           end.\n    intros H P.\n>> *)\n\n  Lemma pseudofunctor_of_functor__composition_of\n        {x0 x1 x2 x : PreCategory}\n        {x7 x11 : Functor x0 x1}\n        {x12 : x7 = x11}\n        {x6 : Functor x0 x2} {x9 : Functor x2 x1}\n        {x14 : x11 = (x9 o x6)%functor}\n        {x4 : Functor x0 x} {x5 : Functor x x1}\n        {x8 : x7 = (x5 o x4)%functor} {x10 : Functor x x2}\n        {x13 : x6 = (x10 o x4)%functor} {x15 : x5 = (x9 o x10)%functor}\n        (H0' : P x0) (H1' : P x1) (H2' : P x2) (H' : P x)\n  : ((associator_1 x9 x10 x4)\n       o ((idtoiso (x -> x1) x15 : morphism _ _ _)\n            oR x4\n            o (idtoiso (x0 -> x1) x8 : morphism _ _ _)))%natural_transformation\n    = (x9\n         oL (idtoiso (x0 -> x2) x13 : morphism _ _ _)\n         o ((idtoiso (x0 -> x1) x14 : morphism _ _ _)\n              o (idtoiso (x0 -> x1) x12 : morphism _ _ _)))%natural_transformation.\n  Proof.\n    clear F.\n    symmetry; simpl; pseudofunctor_t.\n  Qed.\n\n  Lemma pseudofunctor_of_functor__left_identity_of\n        {x0 x : PreCategory}\n        {x2 : Functor x x} {x3 : x2 = 1%functor}\n        {x4 x5 : Functor x0 x} {x6 : x4 = x5} {x7 : x4 = (x2 o x5)%functor}\n        (H0' : P x0) (H' : P x)\n  : ((Category.Morphisms.idtoiso (x -> x) x3 : morphism _ _ _)\n       oR x5\n       o (Category.Morphisms.idtoiso (x0 -> x) x7 : morphism _ _ _))%natural_transformation\n    = ((NaturalTransformation.Composition.Laws.left_identity_natural_transformation_2 x5)\n         o (Category.Morphisms.idtoiso (x0 -> x) x6 : morphism _ _ _))%natural_transformation.\n  Proof.\n    clear F.\n    simpl; pseudofunctor_t.\n  Qed.\n\n  Lemma pseudofunctor_of_functor__right_identity_of\n        {x0 x : PreCategory}\n        {x4 : Functor x0 x0} {x5 : x4 = 1%functor}\n        {x2 x3 : Functor x0 x} {x6 : x2 = x3} {x7 : x2 = (x3 o x4)%functor}\n        (H0' : P x0) (H' : P x)\n  : (x3\n       oL (Category.Morphisms.idtoiso (x0 -> x0) x5 : morphism _ _ _)\n       o (Category.Morphisms.idtoiso (x0 -> x) x7 : morphism _ _ _))%natural_transformation\n    = ((NaturalTransformation.Composition.Laws.right_identity_natural_transformation_2 x3)\n         o (Category.Morphisms.idtoiso (x0 -> x) x6 : morphism _ _ _))%natural_transformation.\n  Proof.\n    clear F.\n    simpl; pseudofunctor_t.\n  Qed.\n\n  Definition pseudofunctor_of_functor : Pseudofunctor C\n    := Build_Pseudofunctor\n         C\n         (fun x => pr1 (F x))\n         (fun s d m => F _1 m)\n         (fun s d d' m0 m1 => Category.Morphisms.idtoiso (_ -> _) (composition_of F _ _ _ m1 m0))\n         (fun x => Category.Morphisms.idtoiso (_ -> _) (identity_of F x))\n         (fun w x y z _ _ _ => pseudofunctor_of_functor__composition_of (F w).2 (F z).2 (F y).2 (F x).2)\n         (fun x y _ => pseudofunctor_of_functor__left_identity_of (F x).2 (F y).2)\n         (fun x y _ => pseudofunctor_of_functor__right_identity_of (F x).2 (F y).2).\nEnd of_functor.\n\nDefinition FunctorToCat `{Funext} {C} `{HP : forall C D, P C -> P D -> IsHSet (Functor C D)}\n  := Functor C (@sub_pre_cat _ P HP).\nIdentity Coercion functor_to_cat_id : FunctorToCat >-> Functor.\nDefinition pseudofunctor_of_functor_to_cat `(F : @FunctorToCat H C P HP)\n  := @pseudofunctor_of_functor _ C P HP F.\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/Pseudofunctor/FromFunctor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.28819909939536564}}
{"text": "(** * Axioms used in the ITree library. *)\n\n(** Other ITree modules should import this to avoid accidentally using more\n   axioms elsewhere. *)\n\nFrom Coq Require Import\n  Logic.Classical_Prop\n  Logic.ClassicalChoice\n  Logic.EqdepFacts\n  Logic.FunctionalExtensionality\n.\n\n(* Must be imported to use [ddestruction] *)\nFrom Coq Require Export\n  Program.Equality\n.\n\nSet Implicit Arguments.\n\n(* The following tactics may be used:\n   - [dependent destruction]\n   - [dependent induction] *)\nLtac ddestruction :=\n  repeat lazymatch goal with | H : existT _ _ _ = _ |- _ => dependent destruction H end.\n\n(* Consequence of UIP; used by tactic [dependent destrcution] *)\nDefinition eq_rect_eq := Eqdep.Eq_rect_eq.eq_rect_eq.\n\nDefinition classic := Classical_Prop.classic.\n\nDefinition choice := ClassicalChoice.choice.\n\nDefinition functional_extensionality := @FunctionalExtensionality.functional_extensionality.\n\n(* From Coq.Logic.ChoiceFacts *)\nDefinition GuardedFunctionalChoice_on {A B} :=\n  forall P : A -> Prop, forall R : A -> B -> Prop,\n    inhabited B ->\n    (forall x : A, P x -> exists y : B, R x y) ->\n    (exists f : A->B, forall x, P x -> R x (f x)).\nAxiom guarded_choice : forall {A B}, @GuardedFunctionalChoice_on A B.\n\nInductive mwitness : Type :=\n| Witness (P : Type) (_ : P)\n| NoWitness.\n\nLemma classicT_inhabited : inhabited (forall (P : Type), P + (P -> False)).\nProof.\n  destruct (choice (fun (P : Type) (b : mwitness) =>\n    match b with @Witness Q _ => P = Q | NoWitness => P -> False end)) as [f H].\n  { intros P; destruct (classic (inhabited P)) as [[x] | ];\n      [exists (Witness x) | exists NoWitness]; auto. }\n  constructor. intros P; specialize (H P); destruct (f P); [subst | ]; auto.\nQed.\n", "meta": {"author": "DeepSpec", "repo": "InteractionTrees", "sha": "8e28e2ee08496c696e03916a22d93c39559a9715", "save_path": "github-repos/coq/DeepSpec-InteractionTrees", "path": "github-repos/coq/DeepSpec-InteractionTrees/InteractionTrees-8e28e2ee08496c696e03916a22d93c39559a9715/theories/Axioms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.5234203489363239, "lm_q1q2_score": 0.2881990916756967}}
{"text": "(***\n *** A version of the computation monad using the option-set monad\n ***)\n\nFrom Coq Require Export Morphisms Setoid Program.Equality.\nFrom ITree Require Export ITree ITreeFacts.\nFrom Paco Require Import paco.\n\nInfix \">>=\" := ITree.bind (at level 58, left associativity).\nNotation \"m1 >> m2\" := (m1 >>= fun _ => m2) (at level 58, left associativity).\n\nVariant SpecEvent (E:Type -> Type) (A:Type) : Type :=\n| Spec_vis : E A -> SpecEvent E A\n| Spec_forall : SpecEvent E A\n| Spec_exists : SpecEvent E A\n.\n\nArguments Spec_vis {E A}.\nArguments Spec_forall {E A}.\nArguments Spec_exists {E A}.\n\n(* An ITree that defines a set of ITrees *)\nDefinition itree_spec E A : Type := itree (SpecEvent E) A.\n\n(* The body of an itree_spec, inside the observe projection *)\nDefinition itree_spec' E A : Type := itree' (SpecEvent E) A.\n\nInductive satisfiesF {E A} (satisfies : itree_spec E A -> itree E A -> Prop)\n  : itree_spec' E A -> itree' E A -> Prop :=\n| Satisfies_Ret a : satisfiesF satisfies (RetF a) (RetF a)\n| Satisfies_Tau spec tree :\n    satisfies spec tree ->\n    satisfiesF satisfies (TauF spec) (TauF tree)\n| Satisfies_TauL spec tree :\n    satisfiesF satisfies (observe spec) tree ->\n    satisfiesF satisfies (TauF spec) tree\n| Satisfies_TauR spec tree :\n    satisfiesF satisfies spec (observe tree) ->\n    satisfiesF satisfies spec (TauF tree)\n| Satisfies_Vis X (e:E X) spec tree :\n    (forall x, satisfies (spec x) (tree x)) ->\n    satisfiesF satisfies (VisF (Spec_vis e) spec) (VisF e tree)\n| Satisfies_Forall X spec tree :\n    (forall x:X, satisfies (spec x) tree) ->\n    satisfiesF satisfies (VisF Spec_forall spec) (observe tree)\n| Satisfies_Exists X spec tree :\n    (exists x:X, satisfies (spec x) tree) ->\n    satisfiesF satisfies (VisF Spec_exists spec) (observe tree)\n.\n\nHint Constructors satisfiesF.\n\nInstance Proper_satisfies_satisfiesF {E A} :\n  Proper (pointwise_relation _ (pointwise_relation _ Basics.impl) ==>\n          eq ==> eq ==> Basics.impl) (@satisfiesF E A).\nProof.\n  intros R1 R2 implR spec1 spec2 e_spec tree1 tree2 e_tree sats.\n  rewrite <- e_spec; rewrite <- e_tree.\n  clear e_spec spec2 e_tree tree2.\n  induction sats; constructor; intros; try (apply implR; apply H); try assumption.\n  destruct H as [ x H ]. exists x. apply implR; assumption.\nQed.\n\nLemma satisfiesF_mono {E A} (sats1 sats2:itree_spec E A -> itree E A -> Prop)\n         (sub_sats:forall spec tree, sats1 spec tree -> sats2 spec tree) :\n  forall spec tree,\n    satisfiesF sats1 spec tree -> satisfiesF sats2 spec tree.\nProof.\n  intros.\n  apply (Proper_satisfies_satisfiesF sats1 sats2 sub_sats _ _ eq_refl _ _ eq_refl H).\nQed.\n\nDefinition satisfies_ {E A} satisfies spec tree :=\n  @satisfiesF E A satisfies (observe spec) (observe tree).\n\n\nLemma satisfies__mono E A : monotone2 (@satisfies_ E A).\nProof.\n  intros spec tree r1 r2 sats sub12. unfold satisfies_.\n  induction sats; constructor; try assumption.\n  { apply sub12; assumption. }\n  { intros; apply sub12. apply H. }\n  { intros; apply sub12. apply H. }\n  { destruct H as [ x H ]. exists x. apply sub12. apply H. }\nQed.\n\nHint Resolve satisfies__mono : paco.\n\nDefinition satisfies {E A} spec tree := paco2 (@satisfies_ E A) bot2 spec tree.\n\nInstance Proper_observing_paco2_satisfies_impl E A r :\n  Proper (observing eq ==> observing eq ==> iff) (paco2 (@satisfies_ E A) r).\nProof.\n  intros spec1 spec2 [ Rspec ] tree1 tree2 [ Rtree ].\n  split; intro; punfold H; pfold; unfold satisfies_;\n    [ rewrite <- Rtree; rewrite <- Rspec | rewrite Rtree; rewrite Rspec ];\n    apply H.\nQed.\n\nInstance Proper_observing_satisfies E A :\n  Proper (observing eq ==> observing eq ==> iff) (@satisfies E A).\nProof.\n  apply Proper_observing_paco2_satisfies_impl.\nQed.\n\nLtac simpobs x := apply simpobs in x.\n\nLtac weaken_bis Hb := match type of Hb with ?x ≅ ?y => assert (x ≈ y); try (rewrite Hb; reflexivity) end.\n\nLemma satisfies_eutt_spec_tau_vis_aux: forall (E : Type -> Type) (A u : Type) (e : SpecEvent E u)\n                                         (k1 k2 : u -> itree (SpecEvent E) A),\n    (forall v : u, paco2 (eqit_ eq true true id) bot2 (k1 v) (k2 v)) ->\n    forall (r : itree_spec E A -> itree E A -> Prop) (tree0 : itree E A),\n      (forall (P1 P2 : itree_spec E A) (tree : itree E A),\n          satisfies P1 tree -> P1 ≈ P2 -> r P2 tree) ->\n      satisfiesF (upaco2 satisfies_ bot2) (VisF e k1) (observe tree0) ->\n      satisfiesF (upaco2 satisfies_ r) (VisF e k2) (observe tree0).\nProof.\n  intros E A u e k1 k2 REL r tree0 CIH H.\n  dependent induction H.\n  - rewrite <- x. constructor. eapply IHsatisfiesF; eauto.\n  - rewrite <- x. constructor. intros. right.\n    pclearbot. eapply CIH; eauto. apply H.\n  - rewrite <- x. constructor. right. pclearbot; eapply CIH; eauto.\n    apply H.\n  - rewrite <- x. constructor. destruct H as [x' Hx' ]. pclearbot.\n    exists x'. right. eapply CIH; eauto.\nQed.\n\nLemma satisfiesF_TauL: forall (E : Type -> Type) (A : Type) (t1 : itree (SpecEvent E) A)\n                         (tree0 : itree E A),\n    satisfiesF (upaco2 satisfies_ bot2) (TauF t1) (observe tree0) ->\n    satisfiesF (upaco2 satisfies_ bot2) (observe t1) (observe tree0).\nProof.\n  intros E A t1 tree0 H.\n  dependent induction H; auto.\n  - pclearbot. rewrite <- x. constructor. punfold H.\n  - rewrite <- x. constructor. eapply IHsatisfiesF; eauto.\nQed.\n\n(* Requires coinduction because the forall and exist states *)\nLemma satisfies_TauR:\n  forall (E : Type -> Type) (A : Type) (P : itree_spec E A) (t : itree E A),\n    satisfies P (Tau t) ->\n    satisfies P t.\nProof.\n  intros E A. pcofix CIH. intros P t HP.\n  pfold. red.\n  punfold HP. red in HP. dependent induction HP; pclearbot; auto.\n  - rewrite <- x. constructor. pstep_reverse. eapply paco2_mon; eauto.\n    intuition.\n  - rewrite <- x. constructor. eapply IHHP; eauto.\n  - pstep_reverse. clear IHHP. eapply paco2_mon with (r := bot2); intuition.\n  - rewrite <- x0. cbn in x. constructor. right.\n    eapply CIH; eauto. pfold. red. cbn. rewrite <- x. pstep_reverse.\n  - rewrite <- x0. constructor. destruct H as [x' Hx']. pclearbot.\n    exists x'. right. eapply CIH. pfold. red. rewrite <- x. pstep_reverse.\nQed.\n\nLemma satisfies_eutt_spec_l E A (P1 P2:itree_spec E A) tree :\n  satisfies P1 tree -> eutt eq P1 P2 -> satisfies P2 tree.\nProof.\n  revert P1 P2 tree. pcofix CIH. intros P1 P2 tree HP HP12.\n  punfold HP. red in HP. pfold. red. punfold HP12. red in HP12.\n  dependent induction HP.\n  - rewrite <- x. rewrite <- x0 in HP12. dependent induction HP12; auto.\n    + rewrite <- x. constructor.\n    + rewrite <- x. constructor. eapply IHHP12; eauto.\n  - pclearbot.\n    remember (observe P2) as oP2. clear HeqoP2 P2.\n    assert ((exists P2', oP2 = TauF P2') \\/ (forall P2', oP2 <> TauF P2') ).\n    { destruct oP2; eauto; right; repeat intro; discriminate. }\n    rewrite <- x. rewrite <- x0 in HP12. clear x0 x.\n    destruct H0 as [ [P2' HP2'] | HP2' ].\n    + subst. constructor. right. eapply CIH; eauto.\n      rewrite <- tau_eutt. setoid_rewrite <- tau_eutt at 3.\n      pfold. auto.\n    + inversion HP12; try (exfalso; eapply HP2'; eauto; fail); subst.\n       clear HP12. punfold H. red in H.\n       dependent induction REL; intros; subst;\n       try (exfalso; eapply HP2'; eauto; fail).\n       * constructor. rewrite <- x in H.\n         clear CIH HP2' x. dependent induction H; try constructor.\n         ++ rewrite <- x. constructor.\n         ++ rewrite <- x. constructor. apply IHsatisfiesF; auto.\n       * rewrite <- x in H. constructor. pclearbot.\n         eapply satisfies_eutt_spec_tau_vis_aux; eauto.\n       * eapply IHREL; auto. rewrite <- x in H.\n         eapply satisfiesF_TauL; eauto.\n  - eapply IHHP; eauto. rewrite <- x in HP12.\n    assert (Tau spec ≈ P2); try (pfold; auto; fail).\n    rewrite tau_eutt in H. punfold H.\n  - rewrite <- x. constructor. eapply IHHP; eauto.\n  - rewrite <- x. rewrite <- x0 in HP12. dependent induction HP12.\n    + rewrite <- x. constructor. pclearbot. intros.  right. eapply CIH; eauto.\n      apply H.\n    + rewrite <- x. constructor. eapply IHHP12; eauto.\n  - rewrite <- x0 in HP12. dependent induction HP12.\n    + rewrite <- x. constructor. pclearbot. intros. right. eapply CIH; eauto.\n      pfold. red. rewrite <- x1.\n      specialize (H x2). punfold H.\n    + rewrite <- x. constructor. eapply IHHP12; eauto.\n  - rewrite <- x0 in HP12. rewrite <- x. clear x tree. dependent induction HP12.\n    + rewrite <- x. constructor. destruct H as [x' Hx']. pclearbot.\n      exists x'. right. eapply CIH; eauto.\n    + rewrite <- x. constructor. eapply IHHP12; eauto.\nQed.\n\nLemma satisfies_eutt_spec_r E A (P:itree_spec E A) (t1 t2 : itree E A) :\n  satisfies P t1 -> t1 ≈ t2 -> satisfies P t2.\nProof.\n  revert P t1 t2. pcofix CIH. intros P t1 t2 HP Ht12.\n  pfold. red. punfold Ht12. red in Ht12. punfold HP. red in HP.\n  dependent induction Ht12.\n  - rewrite <- x. rewrite <- x0 in HP. clear x x0.\n    dependent induction HP; auto;\n    try (rewrite <- x; auto).\n    + rewrite <- x0. pclearbot. constructor.\n      intros. right. eapply CIH; try apply H. reflexivity.\n    + rewrite <- x0. constructor. destruct H as [x' Hx']. pclearbot.\n      exists x'. right. eapply CIH; eauto. reflexivity.\n      (* Tau Tau case *)\n  - pclearbot. remember (observe P) as oP. clear HeqoP P.\n    assert ( (exists P, oP = TauF P) \\/ (forall P, oP <> TauF P) ).\n    { destruct oP; eauto; right; repeat intro; discriminate. }\n    destruct H as [ [P HoP] | HoP].\n    + subst. rewrite <- x. constructor. right. eapply CIH; eauto.\n      apply satisfies_TauR. pfold. red. apply satisfiesF_TauL. simpl.\n      rewrite x0. auto.\n    + rewrite <- x. rewrite <- x0 in HP.\n      inversion HP; try (exfalso; eapply HoP; eauto; fail).\n      * subst. clear HP. clear x x0. punfold REL. red in REL. constructor.\n        dependent induction H1; try (exfalso; eapply HoP; eauto; fail).\n        ++ rewrite <- x in REL. clear x. dependent induction REL;\n           try (rewrite <- x; auto).\n        ++ eapply IHsatisfiesF; auto. pstep_reverse.\n           assert (m1 ≈ m2); try (pfold; auto; fail). simpobs x. rewrite x in H.\n           rewrite tau_eutt in H. auto.\n        ++ rewrite <- x in REL. clear x. dependent induction REL.\n           ** rewrite <- x; auto. constructor. right.\n              pclearbot. eapply CIH; eauto. apply H.\n           ** rewrite <- x. constructor. eapply IHREL; eauto.\n        ++ pclearbot. constructor. right. eapply CIH; eauto. pfold. red.\n           rewrite <- x. pstep_reverse.\n        ++ constructor. destruct H as [x' Hx']. pclearbot. exists x'. right.\n           eapply CIH; eauto. simpobs x. rewrite <- itree_eta in x. rewrite <- x.\n           pfold. auto.\n      * constructor. constructor. right. pclearbot. eapply CIH; eauto.\n        apply satisfies_TauR. pfold. red. cbn. rewrite <- H. pstep_reverse.\n      * constructor. constructor. destruct H1 as [x' Hx' ]. pclearbot.\n        exists x'. right. eapply CIH; eauto. symmetry in H. simpobs H.\n        rewrite H. rewrite tau_eutt. auto.\n  - rewrite <- x. rewrite <- x0 in HP. clear x x0. dependent induction HP.\n    + rewrite <- x. constructor. eapply IHHP; eauto.\n    + rewrite <- x. constructor. intros. right.\n      pclearbot. eapply CIH; eauto. apply H.\n    + rewrite <- x0. pclearbot.\n      assert (VisF e k2 = observe (Vis e k2) ); auto. rewrite H0.\n      constructor. intros. right. eapply CIH; try apply H.\n      symmetry in x. simpobs x. rewrite x.\n      pfold. red. constructor. auto.\n    + rewrite <- x0. assert (VisF e k2 = observe (Vis e k2) ); auto.\n      rewrite H0. constructor. destruct H as [x' Hx']. pclearbot.\n      exists x'. right. eapply CIH; eauto. symmetry in x. simpobs x.\n      rewrite x. pfold. constructor. left. auto.\n  - eapply IHHt12; auto. rewrite <- x in HP. pstep_reverse.\n    apply satisfies_TauR. pfold. auto.\n  - rewrite <- x. constructor.\n    eapply IHHt12; eauto.\nQed.\n\nInstance proper_eutt_satisfies E R : Proper (@eutt (SpecEvent E) R R eq ==> eutt eq ==> iff) satisfies.\nProof.\n  intros P Q HPQ t1 t2 Ht12. split; intros.\n  - eapply satisfies_eutt_spec_r; eauto. eapply satisfies_eutt_spec_l; eauto.\n  - symmetry in HPQ. symmetry in Ht12. eapply satisfies_eutt_spec_r; eauto. eapply satisfies_eutt_spec_l; eauto.\nQed.\n\n(* infinte forall exist chains *)\n\nCoFixpoint top_spec {E: Type -> Type} {A : Type} : itree_spec E A := Vis Spec_forall (fun _ : unit => top_spec).\n\nLemma top_spec_is_top : forall E R (t : itree E R), satisfies top_spec t.\nProof.\n  intros E R. pcofix CIH. intros. pfold. red. cbn. constructor. intros. right. auto.\nQed.\n\nDefinition bottom_spec {E : Type -> Type} {A : Type} : itree_spec E A := Vis Spec_exists (fun v : void => match v with end).\n\nLemma bottom_spec_is_bottom : forall E R (t : itree E R), ~ satisfies bottom_spec t.\nProof.\n  intros E R t Hcontra. punfold Hcontra. red in Hcontra. cbn in *. dependent induction Hcontra; eauto.\n  destruct H as [ [] _ ].\nQed.\n\nDefinition and_spec {E : Type -> Type} {A : Type} (P Q : itree_spec E A) :=\n  Vis Spec_forall (fun b : bool => if b then P else Q).\n\nDefinition or_spec {E : Type -> Type} {A : Type} (P Q : itree_spec E A) :=\n  Vis Spec_exists (fun b : bool => if b then P else Q).\n\nLemma and_spec_is_and : forall E R (t : itree E R) (P Q : itree_spec E R),\n    satisfies (and_spec P Q) t <-> (satisfies P t /\\ satisfies Q t).\nProof.\n  split; [split | idtac]; intros.\n  - punfold H. red in H. pfold. red. cbn in H. dependent induction H.\n    + rewrite <- x. constructor. eauto.\n    + simpobs x. rewrite <- itree_eta in x. pclearbot. pstep_reverse.\n      specialize (H true). cbn in *. rewrite x. auto.\n  - punfold H. red in H. pfold. red. cbn in H. dependent induction H.\n    + rewrite <- x. constructor. eauto.\n    + simpobs x. rewrite <- itree_eta in x. pclearbot. pstep_reverse.\n      specialize (H false). cbn in *. rewrite x. auto.\n  - destruct H. pfold. red. cbn. constructor. intros; destruct x; left; auto.\nQed.\n\nLemma or_spec_is_or : forall E R (t : itree E R) (P Q : itree_spec E R),\n    satisfies (or_spec P Q) t <-> (satisfies P t \\/ satisfies Q t).\nProof.\n  split; intros; [idtac | destruct H] .\n  - punfold H. red in H. cbn in *. dependent induction H; [ simpobs x | idtac ].\n    + setoid_rewrite x. setoid_rewrite tau_eutt. eapply IHsatisfiesF; eauto.\n    + simpobs x. rewrite <- itree_eta in x. setoid_rewrite x.\n      destruct H as [ [ | ] H ]; pclearbot; eauto.\n  - pfold. red. cbn. constructor. exists true. auto.\n  - pfold. red. cbn. constructor. exists false. auto.\nQed.\n\nLemma or_spec_bind : forall E R S (P Q : itree_spec E R) (k : R -> itree_spec E S),\n    (or_spec P Q) >>= k ≈ or_spec (P >>= k) (Q >>= k).\nProof.\n  intros. unfold or_spec. rewrite bind_vis. pfold. constructor.\n  intros; left.\n  enough ( (if v then P else Q) >>= k ≈ if v then P >>= k else Q >>= k ); auto.\n  destruct v; reflexivity.\nQed.\n\nLemma and_spec_bind : forall E R S (P Q : itree_spec E R) (k : R -> itree_spec E S),\n    (and_spec P Q) >>= k ≈ and_spec (P >>= k) (Q >>= k).\nProof.\n  intros. unfold and_spec.\n  pfold. red. cbn. constructor.\n  intros; left.\n  enough ( (if v then P else Q) >>= k ≈ if v then P >>= k else Q >>= k ); auto.\n  destruct v; reflexivity.\nQed.\n\n(*\nDefinition imp_spec {E R} (P Q : itree_spec E R) := \n  Vis Spec_forall (fun _ : satisfies P t => Q)\n*)\n\n\n(* The proposition that a is returned by an itree along some path *)\nInductive is_itree_retval' {E A} : itree' E A -> A -> Prop :=\n| iirv_ret a : is_itree_retval' (RetF a) a\n| iirv_tau tree a :\n    is_itree_retval' (observe tree) a -> is_itree_retval' (TauF tree) a\n| iirv_vis {X} (ev:E X) tree a x :\n    is_itree_retval' (observe (tree x)) a ->\n    is_itree_retval' (VisF ev tree) a\n.\n\nDefinition is_itree_retval {E A} tree a := @is_itree_retval' E A (observe tree) a.\n\nInstance Proper_observing_is_itree_retval E A :\n  Proper (observing eq ==> eq ==> iff) (@is_itree_retval E A).\nProof.\n  intros m1 m2 [ em ] a1 a2 ea. rewrite <- ea. unfold is_itree_retval.\n  rewrite em. reflexivity.\nQed.\n\n\nLemma bind_satisfies_bind E A B (P:itree_spec E A) (Q:A -> itree_spec E B)\n      (m:itree E A) (f:A -> itree E B) :\n  satisfies P m ->\n  (forall a, is_itree_retval m a -> satisfies (Q a) (f a)) ->\n  satisfies (P >>= Q) (m >>= f).\nProof.\n  intro sats; revert P m sats. pcofix CIH.\n  intros P m sats satsQ; punfold sats. unfold satisfies_ at 1 in sats.\n  remember (observe P) as obsP eqn: e_obsP.\n  remember (observe m) as obsm eqn: e_obsm.\n  revert P m e_obsP e_obsm satsQ. induction sats; intros.\n  { rewrite <- (observing_intros _ (Ret a) _ e_obsP).\n    rewrite <- (observing_intros _ (Ret a) _ e_obsm).\n    repeat rewrite bind_ret_.\n    eapply paco2_mon_bot; [ apply satsQ | intros; eassumption ].\n    rewrite <- (observing_intros _ (Ret a) _ e_obsm). constructor. }\n  { rewrite <- (observing_intros _ (Tau _) _ e_obsP).\n    rewrite <- (observing_intros _ (Tau _) _ e_obsm).\n    repeat rewrite bind_tau_.\n    pfold. apply Satisfies_Tau. right. pclearbot. apply CIH; [ assumption | ].\n    intros a iirv. apply satsQ.\n    rewrite <- (observing_intros _ (Tau _) _ e_obsm).\n    constructor. assumption. }\n  { rewrite <- (observing_intros _ (Tau _) _ e_obsP). rewrite bind_tau_.\n    pfold. apply Satisfies_TauL.\n    set (IHapp := IHsats spec m eq_refl e_obsm satsQ). punfold IHapp. }\n  { rewrite <- (observing_intros _ (Tau _) _ e_obsm). rewrite bind_tau_.\n    pfold. apply Satisfies_TauR.\n    assert (paco2 satisfies_ r (P >>= Q) (tree >>= f)) as IHapp;\n      [ | punfold IHapp ].\n    apply IHsats; [ assumption | reflexivity | ].\n    intros. apply satsQ. rewrite <- (observing_intros _ (Tau _) _ e_obsm).\n    constructor. assumption. }\n  { rewrite <- (observing_intros _ (Vis _ _) _ e_obsP).\n    rewrite <- (observing_intros _ (Vis _ _) _ e_obsm).\n    repeat rewrite bind_vis_. pfold.\n    apply Satisfies_Vis. intro x. right. apply CIH.\n    - pclearbot. apply H.\n    - intros. apply satsQ. rewrite <- (observing_intros _ (Vis _ _) _ e_obsm).\n      econstructor. eassumption. }\n  { rewrite <- (observing_intros _ (Vis _ _) _ e_obsP).\n    rewrite <- (observing_intros _ _ _ e_obsm).\n    rewrite bind_vis_. pfold. apply Satisfies_Forall. intro x. right. apply CIH.\n    - pclearbot. apply H.\n    - intros. apply satsQ.\n      rewrite <- (observing_intros _ _ _ e_obsm). assumption. }\n  { rewrite <- (observing_intros _ (Vis _ _) _ e_obsP).\n    rewrite <- (observing_intros _ _ _ e_obsm).\n    rewrite bind_vis_. pfold.\n    destruct H as [ x H ]. apply Satisfies_Exists. exists x. right. apply CIH.\n    - pclearbot. apply H.\n    - intros. apply satsQ.\n      rewrite <- (observing_intros _ _ _ e_obsm). assumption. }\nQed.\n\nNotation \" x : T <- m1 ;; m2\" := (ITree.bind m1 (fun x : T=> m2) ) (at level 40).\n\nSection l_bind_satisfies_bind_counter.\n  Variant NonDet : Type -> Type := Choose : NonDet bool.\n\n  Definition m_counter : itree NonDet unit :=\n    x : bool <- ITree.trigger Choose ;;\n    if x then Ret tt else y : bool <- ITree.trigger Choose;; Ret tt.\n\n  Definition P_counter : itree_spec NonDet unit :=\n    x : bool <- ITree.trigger (Spec_vis Choose);; Ret tt.\n\n  Definition Q_counter : unit -> itree_spec NonDet unit :=\n    fun _ => or_spec (Ret tt) ( x : bool <- ITree.trigger (Spec_vis Choose);; Ret tt  ).\n\n  Lemma m_counter_sats_P_bind_Q_counter : satisfies (P_counter >>= Q_counter) m_counter.\n  Proof.\n    pfold. red. cbn. constructor. left. destruct x.\n    - pfold. red. cbn.\n      assert (RetF (E:= NonDet) tt = observe (Ret tt)); auto.\n      rewrite H. constructor. exists true. left. pfold; constructor.\n    - pfold. red. cbn. assert (VisF Choose (fun x : bool => _ : bool <- Ret x;; Ret tt) =\n                               observe (Vis Choose (fun x : bool => _ : bool <- Ret x;; Ret tt) ) ); auto.\n      rewrite H. constructor. exists false. left. pfold. red. cbn.\n      rewrite H. constructor. intros [ | ]; left; pfold; red; cbn; auto.\n   Qed.\n\n  Lemma satifies_P_counter : forall m, satisfies P_counter m ->\n                                  m ≈ (x : bool <- ITree.trigger Choose;; Ret tt).\n  Proof.\n    intros. unfold P_counter in *. punfold H. red in H. pfold. red. cbn in *.\n    dependent induction H.\n    - rewrite <- x. constructor; auto.\n    - rewrite <- x. constructor. left. pclearbot. specialize (H v).\n      assert (satisfies (_ : bool <- Ret v;; Ret tt) (tree v) ); auto.\n      enough (tree v ≈ ( _ : bool <- Ret v;; Ret tt) ); auto. rewrite bind_ret_l.\n      rewrite bind_ret_l in H0. symmetry. clear x H m.\n      pfold. red. punfold H0. red in H0. cbn in *.\n      remember (observe (tree v) ) as ot. clear Heqot tree v. dependent induction H0; auto.\n  Qed.\n\n  Definition m0_counter : itree NonDet unit := x : bool <- ITree.trigger Choose;; Ret tt.\n\n  Lemma m0_counter_no_continuation : forall k,\n      ~ m0_counter >>= k ≈ m_counter .\n  Proof.\n    unfold m0_counter, m_counter.\n    intros k Hcontra. repeat rewrite bind_trigger in Hcontra.\n    rewrite bind_vis in Hcontra. apply eqit_inv_vis in Hcontra as [_ Hcontra] .\n    specialize (Hcontra true) as Hktrue. specialize (Hcontra false) as Hkfalse.\n    cbn in *. rewrite bind_ret_l in Hktrue. rewrite bind_ret_l in Hkfalse.\n    rewrite Hktrue in Hkfalse. pinversion Hkfalse.\n  Qed.\n\n  Lemma not_l_bind_satisfies_bind_aux : exists E R S\n               (m : itree E R) (P : itree_spec E S) (Q : S -> itree_spec E R),\n      satisfies (P >>= Q) m /\\ (forall m0 k, satisfies P m0 -> ~ (m0 >>= k ≈ m) ).\n    Proof.\n      exists NonDet, unit, unit, m_counter, P_counter, Q_counter.\n      split; try apply m_counter_sats_P_bind_Q_counter.\n      intros. apply satifies_P_counter in H. rewrite H. fold m0_counter.\n      apply m0_counter_no_continuation.\n    Qed.\n\n\nEnd l_bind_satisfies_bind_counter.\n\nLemma not_l_bind_satisfies_bind : ~ forall E R S\n            (m : itree E R) (P : itree_spec E S) (Q : S -> itree_spec E R),\n       satisfies (P >>= Q) m -> exists m0 k, satisfies P m0 /\\ (forall a, is_itree_retval m0 a -> satisfies (Q a) (k a) ) /\\ (m0 >>= k ≈ m).\nProof.\n  destruct not_l_bind_satisfies_bind_aux as [ E [R [S [m [P [Q  [H0 H1] ] ] ] ] ] ].\n  intros Hcontra. specialize (Hcontra E R S m P Q H0).\n  destruct Hcontra as [m0 [k [Hsat [ _ Heutt] ] ] ]. eapply H1; eauto.\nQed.\n\n(* Our event type = errors *)\nInductive CompMEvent : Type -> Type :=\n| ErrorEvent : CompMEvent False\n.\n\n(* Our computations are sets of ITrees. That is, they are really more like\nspecifications of computations *)\nDefinition CompM (A:Type) : Type := itree_spec CompMEvent A.\n", "meta": {"author": "GaloisInc", "repo": "saw-core-coq", "sha": "91d7dae3272d93906b1068e15d0312dddfa64d64", "save_path": "github-repos/coq/GaloisInc-saw-core-coq", "path": "github-repos/coq/GaloisInc-saw-core-coq/saw-core-coq-91d7dae3272d93906b1068e15d0312dddfa64d64/coq/handwritten/CryptolToCoq/CompM_ITrees.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.28805922893963287}}
{"text": "Require Import List.\nImport ListNotations.\n\nRequire Import FSets FSets.FMapAVL FSets.FMapFacts.\n\nFrom Verbatim Require Import state.\nFrom Verbatim Require Import memo.\nFrom Verbatim Require Import ltac.\nFrom Verbatim Require Import Orders.\nFrom Verbatim Require Import tape.\n\n\n\nModule FMemo (STT : state.T) <: MEMO STT.\n\n  Import STT.Ty.\n  Import STT.Defs.\n  Import STT.R.Defs.\n\n  Module Pointer_as_UOT <: UsualOrderedType := UOT_from_UCT Pointer_as_UCT.\n  Module FM := FMapAVL.Make Pointer_as_UOT.\n  Module FMF := FMapFacts.Facts FM.\n\n  Definition Memo : Type := @Tape (FM.t (option (String * String * index))).\n  Definition emptyMemo : Memo := ([],[]).\n  \n  Definition get_Memo (M : Memo) (pnt : Pointer) (i : index)\n    : option (option (String * String * index)) :=\n    match get_Tape (index2nat i) M with\n    | None => None\n    | Some MP => FM.find pnt MP\n    end.\n  \n  Definition set_Memo (M : Memo) (pnt : Pointer) (i : index)\n             (o : (option (String * String * index))) : Memo :=\n    match get_Tape (index2nat i) M with\n    | None => set_Tape (FM.add pnt o (@FM.empty (option (String * String * index))))\n                      (index2nat i)\n                      M\n    | Some MP => set_Tape (FM.add pnt o (MP)) (index2nat i) M\n    end.\n\n  Lemma correct_Memo : forall M ptr i o, get_Memo (set_Memo M ptr i o) ptr i = Some o.\n  Proof.\n    intros. unfold get_Memo. unfold set_Memo. repeat dm.\n    - rewrite get_of_set_eq in E; repeat inj_all. apply FMF.add_eq_o; auto.\n    - rewrite get_of_set_eq in E; repeat inj_all. apply FMF.add_eq_o; auto.\n    - rewrite get_of_set_eq in E; discriminate.\n    - rewrite get_of_set_eq in E; discriminate.\n  Qed.\n\n  Lemma bar : forall i i', i <> i' -> index2nat i <> index2nat i'.\n  Admitted.\n  \n  Lemma correct_Memo_moot : forall M ptr ptr' i i' o,\n      (ptr <> ptr' \\/ i <> i')\n      -> \n      get_Memo (set_Memo M ptr' i' o) ptr i = get_Memo M ptr i.\n  Proof.\n    intros. unfold get_Memo. unfold set_Memo.\n    destruct (Pointer_as_UOT.eq_dec ptr ptr') eqn:E;\n      destruct (index_eq_dec i i'); destruct H;\n        repeat dm; try contradiction.\n  Admitted.\n    \n  Lemma correct_emptyMemo : forall stt z, get_Memo emptyMemo stt z = None.\n  Proof.\n    intros. unfold get_Memo. unfold emptyMemo. unfold get_Tape. repeat dm.\n    sis.\n  Admitted.\n\nEnd FMemo.\n\n\nModule memoTFn (STT' : state.T) <: memo.T.\n  Module STT := STT'.\n  Module MemTy <: MEMO STT := FMemo STT.\n  Module Defs := memo.MemoDefsFn STT MemTy.\nEnd memoTFn.\n", "meta": {"author": "egolf-cs", "repo": "Verbatim", "sha": "97133d764ca742c7abe190808b304e2c535bb19c", "save_path": "github-repos/coq/egolf-cs-Verbatim", "path": "github-repos/coq/egolf-cs-Verbatim/Verbatim-97133d764ca742c7abe190808b304e2c535bb19c/Verbatim/memo/concrete_memo1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.28805922893963276}}
{"text": "Module Type TIT.\n\nInductive X:Set:=\n b:X.\nEnd TIT.\n\n\nModule Type TOTO.\nDeclare Module t:TIT.\nInductive titi:Set:=\n a:t.X->titi.\nEnd TOTO.\n\n\nModule toto (ta:TOTO).\nModule ti:=ta.t.\n\nDefinition ex1:forall (c d:ti.X), (ta.a d)=(ta.a c) -> d=c.\nintros.\ninjection H.\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/1545.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.4921881357207955, "lm_q1q2_score": 0.28797984629537404}}
{"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 cequiv_props2.\nRequire Export compare_cterm.\nRequire Export cequiv_bind.\nRequire Export subst_tacs.\n\n\nLemma hasvaluec_mkc_try_implies {o} :\n  forall lib t n v (c : @CVTerm o [v]),\n    hasvaluec lib (mkc_try t n v c)\n    ->\n    (\n      {u : CTerm\n       & reduces_toc lib t u\n       # iscvalue u\n       # reduces_toc lib (mkc_try t n v c) (mkc_atom_eq n n u mkc_bottom)\n      }\n      [+]\n      {m : CTerm\n       & {u : CTerm\n       & reduces_toc lib t (mkc_exception m u)\n       # reduces_toc lib (mkc_try t n v c) (mkc_atom_eq n m (substc u v c) (mkc_exception m u))\n      } }\n    ).\nProof.\n  introv hv.\n  destruct_cterms; simpl in *.\n  unfold reduces_toc; simpl.\n  unfold hasvaluec in *; simpl in *.\n  unfold hasvalue in hv; exrepnd.\n  unfold computes_to_value in hv0; repnd.\n  unfold reduces_to in hv1; exrepnd.\n  unfold iscvalue; simpl.\n\n  revert dependent x0.\n\n  induction k; introv ispx0 r.\n\n  {\n    allrw @reduces_in_atmost_k_steps_0; subst.\n    inversion hv0; subst; simpl in *; tcsp.\n  }\n\n  {\n    allrw @reduces_in_atmost_k_steps_S; exrepnd.\n\n    csunf r1; simpl in *.\n\n    destruct x0 as [z|F|op bs]; ginv.\n\n    {\n      left.\n      exists (mk_ct (sterm F) ispx0); simpl.\n      dands; eauto 3 with slow.\n    }\n\n    {\n      dopid op as [can|ncan|exc|abs] Case; simpl; ginv; auto.\n\n      - left.\n        exists (mk_ct (oterm (Can can) bs) ispx0); simpl.\n        dands; eauto 3 with slow.\n\n      - remember (compute_step lib (oterm (NCan ncan) bs)) as cs.\n        destruct cs; simpl in *; ginv.\n        symmetry in Heqcs.\n        fold_terms.\n        applydup @preserve_compute_step in Heqcs; eauto 2 with slow.\n        applydup IHk in r0; auto; eauto 2 with slow;[].\n        repndors; exrepnd; destruct_cterms; simpl in *.\n\n        + left.\n          exists (mk_ct x0 i0); simpl; dands; auto.\n\n          * eapply reduces_to_if_split2; eauto.\n\n          * eapply reduces_to_trans;[|eauto].\n            apply reduces_to_prinarg; eauto 2 with slow.\n\n        + right.\n          exists (mk_ct x2 i2) (mk_ct x0 i0); simpl; dands; auto.\n\n          * eapply reduces_to_if_split2; eauto.\n\n          * eapply reduces_to_trans;[|eauto].\n            apply reduces_to_prinarg; eauto 2 with slow.\n\n      - destruct bs as [|b1 bs]; simpl in *; ginv.\n        destruct b1 as [l1 t1]; simpl in *; ginv.\n        destruct l1 as [|v1 l1]; simpl in *; ginv.\n        destruct bs as [|b2 bs]; simpl in *; ginv.\n        destruct b2 as [l2 t2]; simpl in *; ginv.\n        destruct l2 as [|v2 l2]; simpl in *; ginv.\n        destruct bs as [|]; simpl in *; ginv.\n        fold_terms.\n        right.\n\n        allrw @isprog_exception_iff; repnd.\n        exists (mk_ct t1 ispx1) (mk_ct t2 ispx0); simpl.\n        dands; eauto 2 with slow.\n\n      - remember (compute_step lib (oterm (Abs abs) bs)) as cs.\n        destruct cs; simpl in *; ginv.\n        symmetry in Heqcs.\n        fold_terms.\n        applydup @preserve_compute_step in Heqcs; eauto 2 with slow.\n        applydup IHk in r0; auto; eauto 2 with slow;[].\n        repndors; exrepnd; destruct_cterms; simpl in *.\n\n        + left.\n          exists (mk_ct x0 i0); simpl; dands; auto.\n\n          * eapply reduces_to_if_split2; eauto.\n\n          * eapply reduces_to_trans;[|eauto].\n            apply reduces_to_prinarg; eauto 2 with slow.\n\n        + right.\n          exists (mk_ct x2 i2) (mk_ct x0 i0); simpl; dands; auto.\n\n          * eapply reduces_to_if_split2; eauto.\n\n          * eapply reduces_to_trans;[|eauto].\n            apply reduces_to_prinarg; eauto 2 with slow.\n    }\n  }\nQed.\n\nLemma computes_to_valc_excc_false {o} :\n  forall lib (a b n c : @CTerm o),\n    computes_to_valc lib a b\n    -> computes_to_excc lib n a c\n    -> False.\nProof.\n  introv compv compe.\n  destruct_cterms; simpl in *.\n  unfold computes_to_valc in *; unfold computes_to_excc in *; simpl in *.\n  destruct compv as [r iv].\n  eapply reduces_to_eq_val_like in compe; try (exact r); eauto 3 with slow.\n  subst.\n  inversion iv; subst; simpl in *; auto.\nQed.\n\nLemma hasvaluec_mkc_try2_implies {o} :\n  forall lib t1 t2 n1 n2 v (c1 c2 : @CVTerm o [v]),\n    hasvaluec lib (mkc_try t1 n1 v c1)\n    -> hasvaluec lib (mkc_try t2 n2 v c2)\n    -> cequivc lib t1 t2\n    ->\n    (\n      {u1 : CTerm\n       & {u2 : CTerm\n       & reduces_toc lib t1 u1\n       # reduces_toc lib t2 u2\n       # iscvalue u1\n       # iscvalue u2\n       # cequivc lib u1 u2\n       # reduces_toc lib (mkc_try t1 n1 v c1) (mkc_atom_eq n1 n1 u1 mkc_bottom)\n       # reduces_toc lib (mkc_try t2 n2 v c2) (mkc_atom_eq n2 n2 u2 mkc_bottom)\n      }}\n      [+]\n      {m1 : CTerm\n       & {m2 : CTerm\n       & {u1 : CTerm\n       & {u2 : CTerm\n       & reduces_toc lib t1 (mkc_exception m1 u1)\n       # reduces_toc lib t2 (mkc_exception m2 u2)\n       # reduces_toc lib (mkc_try t1 n1 v c1) (mkc_atom_eq n1 m1 (substc u1 v c1) (mkc_exception m1 u1))\n       # reduces_toc lib (mkc_try t2 n2 v c2) (mkc_atom_eq n2 m2 (substc u2 v c2) (mkc_exception m2 u2))\n      }}}}\n    ).\nProof.\n  introv hv1 hv2 ceqt.\n  apply hasvaluec_mkc_try_implies in hv1.\n  apply hasvaluec_mkc_try_implies in hv2.\n  repndors; exrepnd.\n\n  - left.\n    exists u0 u; dands; auto.\n    eapply cequivc_trans;\n      [apply cequivc_sym;\n       apply reduces_toc_implies_cequivc;\n       eauto\n      |].\n    eapply cequivc_trans;[eauto|].\n    apply reduces_toc_implies_cequivc.\n    eauto.\n\n  - assert False; tcsp.\n    eapply cequivc_trans in ceqt;\n      [|apply cequivc_sym;\n        apply reduces_toc_implies_cequivc;\n        eauto].\n    apply cequivc_sym in ceqt.\n    eapply cequivc_trans in ceqt;\n      [|apply cequivc_sym;\n        apply reduces_toc_implies_cequivc;\n        eauto].\n    apply cequivc_sym in ceqt.\n    apply (cequivc_mkc_exception _ _ _ m u0) in ceqt;\n      [|destruct_cterms;\n        unfold computes_to_excc; simpl;\n        apply computes_to_exception_refl].\n    exrepnd.\n    apply (computes_to_valc_refl lib) in hv3.\n\n    eapply computes_to_valc_excc_false in ceqt0; eauto.\n\n  - assert False; tcsp.\n    eapply cequivc_trans in ceqt;\n      [|apply cequivc_sym;\n        apply reduces_toc_implies_cequivc;\n        eauto].\n    apply cequivc_sym in ceqt.\n    eapply cequivc_trans in ceqt;\n      [|apply cequivc_sym;\n        apply reduces_toc_implies_cequivc;\n        eauto].\n    apply (cequivc_mkc_exception _ _ _ m u) in ceqt;\n      [|destruct_cterms;\n        unfold computes_to_excc; simpl;\n        apply computes_to_exception_refl].\n    exrepnd.\n    apply (computes_to_valc_refl lib) in hv4.\n\n    eapply computes_to_valc_excc_false in ceqt0; eauto.\n\n  - right.\n    exists m0 m u0 u; dands; auto.\nQed.\n\nLemma approx_star_bterm_nobnd_iff {o} :\n  forall lib op (a b : @NTerm o),\n    op <> NCan NFresh\n    -> approx_star_bterm lib op (nobnd a) (nobnd b)\n       <=> approx_star lib a b.\nProof.\n  introv opd.\n  unfold approx_star_bterm, blift_sub.\n  split; intro h; exrepnd.\n\n  - repndors; repnd; tcsp.\n    apply alpha_eq_bterm_nobnd in h2.\n    apply alpha_eq_bterm_nobnd in h0.\n    exrepnd.\n    unfold nobnd in *; ginv.\n    eapply approx_star_alpha_fun_l;[|apply alpha_eq_sym;eauto].\n    eapply approx_star_alpha_fun_r;[|apply alpha_eq_sym;eauto].\n    auto.\n\n  - exists ([] : list NVar) a b.\n    dands; auto.\nQed.\n\nLemma implies_approx_try {o} :\n  forall lib a1 a2 b1 b2 v (t1 t2 : @NTerm o),\n    isprog a1\n    -> isprog a2\n    -> isprog b1\n    -> isprog b2\n    -> isprog_vars [v] t1\n    -> isprog_vars [v] t2\n    -> cequiv lib a1 a2\n    -> cequiv lib b1 b2\n    -> (forall u : NTerm, isprog u -> cequiv lib (subst t1 v u) (subst t2 v u))\n    -> approx lib (mk_try a1 b1 v t1) (mk_try a2 b2 v t2).\nProof.\n  introv ispa1 ispa2 ispb1 ispb2 isp1 isp2 ceqa ceqb imp.\n\n  apply howetheorem1;\n    try (apply isprogram_try);\n    eauto 3 with slow;\n    try (complete (apply isprog_vars_eq in isp1; tcsp));\n    try (complete (apply isprog_vars_eq in isp2; tcsp)).\n\n  apply approx_star_congruence; unfold num_bvars; simpl; auto.\n\n  allrw @approx_starbts_cons.\n  dands; auto;\n    try (apply approx_star_bterm_nobnd_iff;\n         auto; try (complete (intro xx; inversion xx)));\n    eauto 3 with slow.\n\n  - apply le_bin_rel_approx1_eauto; auto.\n    destruct ceqa; tcsp.\n\n  - apply le_bin_rel_approx1_eauto; auto.\n    destruct ceqb; tcsp.\n\n  - unfold approx_star_bterm, blift_sub.\n    exists [v] t1 t2; dands; auto.\n    left; dands; auto; try (complete (intro xx; inversion xx)).\n\n    apply approx_star_iff_approx_open.\n    apply approx_open_simpler_equiv.\n\n    unfold simpl_olift.\n    dands; eauto 3 with slow.\n    introv ps ispt1 ispt2.\n\n    applydup @isprog_vars_eq in isp1.\n    applydup @isprog_vars_eq in isp2.\n    repnd.\n\n    pose proof (cl_lsubst_trim_select t1 sub [v] mk_axiom) as q1.\n    simpl in q1.\n    repeat (autodimp q1 hyp); eauto 3 with slow.\n\n    {\n      introv i.\n      split; intro q; repndors; subst; tcsp.\n      - apply isprogram_lsubst_iff in ispt1; repnd.\n        apply ispt1 in i; exrepnd.\n        apply sub_find_some in i1.\n        apply in_sub_eta in i1; tcsp.\n      - apply subvars_eq in isp5; apply isp5 in i; simpl in i; auto.\n    }\n\n    pose proof (cl_lsubst_trim_select t2 sub [v] mk_axiom) as q2.\n    simpl in q2.\n    repeat (autodimp q2 hyp); eauto 3 with slow.\n\n    {\n      introv i.\n      split; intro q; repndors; subst; tcsp.\n      - apply isprogram_lsubst_iff in ispt2; repnd.\n        apply ispt2 in i; exrepnd.\n        apply sub_find_some in i1.\n        apply in_sub_eta in i1; tcsp.\n      - apply subvars_eq in isp4; apply isp4 in i; simpl in i; auto.\n    }\n\n    rewrite q1, q2.\n    pose proof (imp (sub_find_def sub v mk_axiom)) as q.\n    autodimp q hyp.\n\n    { apply implies_isprog_sub_find_def; auto. }\n\n    destruct q; tcsp.\nQed.\n\nLemma implies_approxc_try {o} :\n  forall lib a1 a2 b1 b2 v (t1 t2 : @CVTerm o [v]),\n    cequivc lib a1 a2\n    -> cequivc lib b1 b2\n    -> (forall u : CTerm, cequivc lib (substc u v t1) (substc u v t2))\n    -> approxc lib (mkc_try a1 b1 v t1) (mkc_try a2 b2 v t2).\nProof.\n  introv ceqa ceqb imp.\n  destruct_cterms.\n  allunfold @cequivc; allsimpl.\n  allunfold @approxc; allsimpl.\n\n  apply implies_approx_try; auto.\n  introv isp.\n  apply isprogram_eq in isp.\n  pose proof (imp (mk_cterm u isp)) as k; allsimpl; auto.\nQed.\n\nLemma implies_cequivc_try {o} :\n  forall lib a1 a2 b1 b2 v (t1 t2 : @CVTerm o [v]),\n    cequivc lib a1 a2\n    -> cequivc lib b1 b2\n    -> (forall u : CTerm, cequivc lib (substc u v t1) (substc u v t2))\n    -> cequivc lib (mkc_try a1 b1 v t1) (mkc_try a2 b2 v t2).\nProof.\n  introv ceqa ceqb imp.\n  apply cequivc_iff_approxc; dands.\n  - apply implies_approxc_try; auto.\n  - apply implies_approxc_try; auto; introv; apply cequivc_sym; auto.\nQed.\n\nLemma implies_approx_atom_eq {o} :\n  forall lib (a1 a2 b1 b2 c1 c2 d1 d2 : @NTerm o),\n    isprog a1\n    -> isprog a2\n    -> isprog b1\n    -> isprog b2\n    -> isprog c1\n    -> isprog c2\n    -> isprog d1\n    -> isprog d2\n    -> cequiv lib a1 a2\n    -> cequiv lib b1 b2\n    -> cequiv lib c1 c2\n    -> cequiv lib d1 d2\n    -> approx lib (mk_atom_eq a1 b1 c1 d1) (mk_atom_eq a2 b2 c2 d2).\nProof.\n  introv ispa1 ispa2 ispb1 ispb2 ispc1 ispc2 ispd1 ispd2; introv ceqa ceqb ceqc ceqd.\n\n  apply howetheorem1;\n    try (apply isprogram_mk_atom_eq; dands; eauto 2 with slow).\n\n  apply approx_star_congruence; unfold num_bvars; simpl; auto.\n\n  allrw @approx_starbts_cons.\n  dands; auto;\n    try (apply approx_star_bterm_nobnd_iff;\n         auto; try (complete (intro xx; inversion xx)));\n    eauto 3 with slow.\n\n  - apply le_bin_rel_approx1_eauto; auto.\n    destruct ceqa; tcsp.\n\n  - apply le_bin_rel_approx1_eauto; auto.\n    destruct ceqb; tcsp.\n\n  - apply le_bin_rel_approx1_eauto; auto.\n    destruct ceqc; tcsp.\n\n  - apply le_bin_rel_approx1_eauto; auto.\n    destruct ceqd; tcsp.\nQed.\n\nLemma implies_approxc_atom_eq {o} :\n  forall lib (a1 a2 b1 b2 c1 c2 d1 d2 : @CTerm o),\n    cequivc lib a1 a2\n    -> cequivc lib b1 b2\n    -> cequivc lib c1 c2\n    -> cequivc lib d1 d2\n    -> approxc lib (mkc_atom_eq a1 b1 c1 d1) (mkc_atom_eq a2 b2 c2 d2).\nProof.\n  introv ceqa ceqb ceqc ceqd.\n  destruct_cterms.\n  allunfold @cequivc; allsimpl.\n  allunfold @approxc; allsimpl.\n\n  apply implies_approx_atom_eq; auto.\nQed.\n\nLemma implies_cequivc_atom_eq {o} :\n  forall lib (a1 a2 b1 b2 c1 c2 d1 d2 : @CTerm o),\n    cequivc lib a1 a2\n    -> cequivc lib b1 b2\n    -> cequivc lib c1 c2\n    -> cequivc lib d1 d2\n    -> cequivc lib (mkc_atom_eq a1 b1 c1 d1) (mkc_atom_eq a2 b2 c2 d2).\nProof.\n  introv ceqa ceqb ceqc ceqd.\n  apply cequivc_iff_approxc; dands.\n  - apply implies_approxc_atom_eq; auto.\n  - apply implies_approxc_atom_eq; auto; introv; apply cequivc_sym; auto.\nQed.\n\nLemma cover_vars_atom_eq {o} :\n  forall (a b c d : @NTerm o) sub,\n    cover_vars (mk_atom_eq a b c d) sub\n    <=> cover_vars a sub\n        # cover_vars b sub\n        # cover_vars c sub\n        # cover_vars d sub.\nProof.\n  sp; repeat (rw cover_vars_eq); simpl.\n  repeat (rw remove_nvars_nil_l).\n  repeat (rw app_nil_r).\n  repeat (rw subvars_app_l); sp; split; sp.\nQed.\n\nLemma reduces_toc_iscvalue_implies_hasvaluec {o} :\n  forall lib (t u : @CTerm o),\n    reduces_toc lib t u\n    -> iscvalue u\n    -> hasvaluec lib t.\nProof.\n  introv r i.\n  unfold reduces_toc in r.\n  unfold iscvalue in i.\n  unfold hasvaluec.\n  destruct_cterms; simpl in *.\n  exists x.\n  split; auto.\nQed.\n\nLemma implies_approx_exception {o} :\n  forall lib (a1 a2 b1 b2 : @NTerm o),\n    isprog a1\n    -> isprog a2\n    -> isprog b1\n    -> isprog b2\n    -> cequiv lib a1 a2\n    -> cequiv lib b1 b2\n    -> approx lib (mk_exception a1 b1) (mk_exception a2 b2).\nProof.\n  introv ispa1 ispa2 ispb1 ispb2 ceqa ceqb.\n\n  apply howetheorem1;\n    try (apply isprogram_exception; dands; eauto 2 with slow).\n\n  apply approx_star_congruence; unfold num_bvars; simpl; auto.\n\n  allrw @approx_starbts_cons.\n  dands; auto;\n    try (apply approx_star_bterm_nobnd_iff;\n         auto; try (complete (intro xx; inversion xx)));\n    eauto 3 with slow.\n\n  - apply le_bin_rel_approx1_eauto; auto.\n    destruct ceqa; tcsp.\n\n  - apply le_bin_rel_approx1_eauto; auto.\n    destruct ceqb; tcsp.\nQed.\n\nLemma implies_approxc_exception {o} :\n  forall lib (a1 a2 b1 b2 : @CTerm o),\n    cequivc lib a1 a2\n    -> cequivc lib b1 b2\n    -> approxc lib (mkc_exception a1 b1) (mkc_exception a2 b2).\nProof.\n  introv ceqa ceqb.\n  destruct_cterms.\n  allunfold @cequivc; allsimpl.\n  allunfold @approxc; allsimpl.\n  apply implies_approx_exception; auto.\nQed.\n\nLemma implies_cequivc_exception {o} :\n  forall lib (a1 a2 b1 b2 : @CTerm o),\n    cequivc lib a1 a2\n    -> cequivc lib b1 b2\n    -> cequivc lib (mkc_exception a1 b1) (mkc_exception a2 b2).\nProof.\n  introv ceqa ceqb.\n  apply cequivc_iff_approxc; dands.\n  - apply implies_approxc_exception; auto.\n  - apply implies_approxc_exception; auto; introv; apply cequivc_sym; auto.\nQed.\n\nLemma simple_lsubstc_subst_ex2 {p} :\n  forall (t : @NTerm p) x B ws s cs wt ct,\n    {wb : wf_term B\n     & {cb : cover_vars_upto B (csub_filter s [x]) [x]\n     & alphaeqc\n         (lsubstc (subst B x t) ws s cs)\n         (substc (lsubstc t wt s ct) x (lsubstc_vars B wb (csub_filter s [x]) [x] cb))\n    }}.\nProof.\n  introv.\n\n  pose proof (change_bvars_alpha_wspec (free_vars t) B) as q.\n  destruct q as [B' [q1 q2] ].\n\n  assert (wf_term (subst B' x t)) as wf.\n  {\n    allrw @wf_term_eq.\n    unfold subst in *.\n    allrw @nt_wf_lsubst_iff; repnd; dands; auto; simpl in *.\n    { apply alphaeq_preserves_wf in q2; apply q2; auto. }\n    introv i j.\n    boolvar; ginv.\n    apply alphaeq_preserves_free_vars in q2; rewrite <- q2 in i.\n    eapply ws;[eauto|]; boolvar; auto.\n  }\n\n  assert (cover_vars (subst B' x t) s) as cov.\n  {\n    unfold cover_vars in *.\n    unfold over_vars in *.\n\n    eapply subvars_eqvars;[|apply eqvars_sym;apply eqvars_free_vars_disjoint].\n    eapply subvars_eqvars in cs;[|apply eqvars_free_vars_disjoint].\n    simpl in *.\n    apply alphaeq_preserves_free_vars in q2; rewrite <- q2.\n    auto.\n  }\n\n  pose proof (simple_lsubstc_subst_ex t x B' wf s cov wt ct q1) as h.\n  exrepnd.\n\n  assert (wf_term B) as wB.\n  { apply lsubst_wf_term in ws; auto. }\n\n  assert (cover_vars_upto B (csub_filter s [x]) [x]) as cB.\n  {\n    rw @cover_vars_eq in cs.\n    unfold cover_vars_upto in *.\n    apply alphaeq_preserves_free_vars in q2; rewrite q2.\n    auto.\n  }\n\n  exists wB cB.\n\n  unfold alphaeqc; simpl.\n\n  pose proof (lsubst_alpha_congr2 (subst B x t) (subst B' x t) (csub2sub s)) as q.\n  autodimp q hyp.\n  { apply lsubst_alpha_congr2; auto. }\n  eapply alpha_eq_trans;[exact q|]; clear q.\n\n  assert (get_cterm (lsubstc (subst B' x t) wf s cov)\n          = get_cterm (substc (lsubstc t wt s ct) x (lsubstc_vars B' wb (csub_filter s [x]) [x] cb))) as xx.\n  { rewrite h1; auto. }\n  simpl in xx.\n  unfold csubst in xx.\n  rewrite xx; clear xx.\n\n  allrw @fold_csubst.\n  apply lsubst_alpha_congr2.\n  apply lsubst_alpha_congr2.\n  apply alpha_eq_sym; auto.\nQed.\n\nLemma lsubstc_subst_snoc_aeq {o} :\n  forall s (b : @NTerm o) x y a w1 w2 c1 c2,\n    !LIn y (dom_csub s)\n    -> (y <> x -> !LIn y (free_vars b))\n    -> alphaeqc\n         (lsubstc (subst b x (mk_var y)) w1 (snoc s (y, a)) c1)\n         (substc a x (lsubstc_vars b w2 (csub_filter s [x]) [x] c2)).\nProof.\n  introv ni d.\n\n  pose proof (change_bvars_alpha_wspec [y] b) as q.\n  destruct q as [b' [q1 q2] ].\n  allrw disjoint_singleton_l.\n\n  assert (wf_term b') as wfb'.\n  {\n    allrw @wf_term_eq.\n    unfold subst in *.\n    allrw @nt_wf_lsubst_iff; repnd; dands; auto; simpl in *.\n    apply alphaeq_preserves_wf in q2; apply q2; auto.\n  }\n\n  assert (wf_term (subst b' x (mk_var y))) as wsb'.\n  {\n    allrw @wf_term_eq.\n    unfold subst in *.\n    allrw @nt_wf_lsubst_iff; repnd; dands; auto; simpl in *.\n    introv i j.\n    boolvar; ginv.\n    eauto 3 with slow.\n  }\n\n  assert (cover_vars (subst b' x (mk_var y)) (snoc s (y, a))) as covsb'.\n  {\n    unfold cover_vars in *.\n    unfold over_vars in *.\n\n    eapply subvars_eqvars;[|apply eqvars_sym;apply eqvars_free_vars_disjoint].\n    eapply subvars_eqvars in c1;[|apply eqvars_free_vars_disjoint].\n    simpl in *.\n    apply alphaeq_preserves_free_vars in q2; rewrite <- q2.\n    auto.\n  }\n\n  assert (cover_vars_upto b' (csub_filter s [x]) [x]) as covub'.\n  {\n    unfold cover_vars_upto in *.\n    apply alphaeq_preserves_free_vars in q2; rewrite <- q2; auto.\n  }\n\n  pose proof (lsubstc_subst_snoc_eq s b' x y a wsb' wfb' covsb' covub') as xx.\n  repeat (autodimp xx hyp).\n  { apply alphaeq_preserves_free_vars in q2; rewrite <- q2; auto. }\n\n  assert (get_cterm (lsubstc (subst b' x (mk_var y)) wsb' (snoc s (y, a)) covsb')\n          = get_cterm (substc a x (lsubstc_vars b' wfb' (csub_filter s [x]) [x] covub'))) as yy.\n  { rewrite xx; auto. }\n  clear xx; simpl in yy.\n\n  destruct_cterms.\n  unfold alphaeqc; simpl in *.\n  unfold csubst in *; simpl in *.\n  allrw @csub2sub_snoc; simpl in *.\n\n  eapply alpha_eq_trans;\n    [apply lsubst_alpha_congr2;\n     apply lsubst_alpha_congr2;\n     exact q2\n    |].\n  allrw @fold_subst.\n  rewrite yy; clear yy.\n  apply lsubst_alpha_congr2.\n  apply lsubst_alpha_congr2.\n  apply alpha_eq_sym; auto.\nQed.\n\nLemma cequivc_exception_implies {o} :\n  forall lib (a1 a2 b1 b2 : @CTerm o),\n    cequivc lib (mkc_exception a1 b1) (mkc_exception a2 b2)\n    -> cequivc lib a1 a2 # cequivc lib b1 b2.\nProof.\n  introv ceq.\n  destruct_cterms.\n  unfold cequivc in *; simpl in *.\n  destruct ceq as [apr1 apr2].\n\n  apply approx_exception in apr1.\n  apply approx_exception in apr2.\n  exrepnd.\n  apply reduces_to_if_isvalue_like in apr4; eauto 3 with slow.\n  apply reduces_to_if_isvalue_like in apr0; eauto 3 with slow.\n  ginv.\n  unfold cequiv.\n  dands; 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/cequiv/cequiv_props5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2879798391736617}}
{"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\nRequire Import List. Import ListNotations.\nRequire Import Arith Omega.\nRequire Import Coq.Strings.String.\n\n\nLemma TypedReduce_toparr_normal_typed : forall A B,\n    topLike (t_arrow A B) -> Etyping nil (e_abs t_top e_top B) (t_arrow A B).\nProof.\n  intros Ht A B.\n  eapply Etyp_abs.\n  intros x H.\n  apply Etyp_top.\n  solve_uniq.\n  auto.\n  inverts B.\n  apply toplike_super_top.\n  auto.\n  Unshelve.\n  pick fresh x.\n  exact (singleton x).\nQed.\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  - (* toparr *)\n    remember (e_abs t_top e_top B).\n    induction* Red2;\n      inversion Heqe.\n    subst.\n    exfalso.\n    apply H2.\n    forwards*: toplike_sub H0 H4.\n  - (* v1 = abs A e D *)\n    remember (e_abs A e D).\n    induction* Red2;\n      try solve [inversion Heqe0];\n      try solve [inversion Ord].\n    inverts* Heqe0.\n    constructor.\n    inverts* H2.\n    assumption.\n    assumption.\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\n\nLemma consistent_afterTR : forall v A B C v1 v2, value v -> Etyping nil v 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  lets Lc: typing_regular_1 Typ.\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  - inverts* Val.\n    inverts* H4.\n  - inverts* Val.\n  - inverts* Val.\nQed.\n  \nLemma TypedReduce_preservation: forall v A v' B,\n    value v -> TypedReduce v A v'-> Etyping nil v B -> Etyping nil v' A.\nProof.\n  introv Val Red.\n  lets Red': Red.\n  gen B.\n  induction Red; introv Typ;\n    lets Lc  : typing_regular_1 Typ;\n    try solve [constructor*].\n  - Case \"toparr\".\n    forwards*: TypedReduce_toparr_normal_typed.\n  - Case \"absv\".\n    inverts Lc.\n    assert (lc_exp (e_abs A e D)) by eauto.\n    inverts Typ.\n    sapply~ Etyp_abs;\n      auto_sub.\n  - Case \"mergel\".\n    inverts Val.\n    inverts Typ;\n    forwards*: IHRed.\n  - Case \"merger\".\n    inverts Val.\n    inverts Typ;\n    forwards*: IHRed.\n  - Case \"merge_and\".\n    forwards: IHRed1 Val Red1 Typ.\n    forwards: IHRed2 Val Red2 Typ.\n    lets Con: consistent_afterTR Val Typ Red1 Red2.\n    apply~ Etyp_mergev.\n    constructor.\n    forwards*: TypedReduce_prv_value Val Red1.\n    forwards*: TypedReduce_prv_value Val Red2.\nQed.\n\n\nTheorem preservation : forall e e' A,\n    Etyping nil e A ->\n    step e e' ->\n    Etyping nil e' A.\nProof.\n  introv Typ. gen e'.\n  lets Typ' : Typ.\n  inductions Typ;\n    try solve [introv J; inverts* J].\n  - Case \"typing_app\".\n    introv J.\n    inverts* J.\n    (* e_absv A0 . e : B0->D  v *)\n    inverts Typ2.\n    eapply Etyp_anno.\n    pick_fresh x.\n    rewrite* (@subst_exp_intro x).\n    remember nil as G.\n    rewrite_env(nil++G).\n    sapply* Etyping_subst.\n    subst.\n    forwards*: TypedReduce_preservation H4.\n    auto. \n  - Case \"typing_anno\".\n    introv J.\n    inverts J.\n    + forwards*: TypedReduce_preservation H4.\n    + forwards*: IHTyp.\n  - Case \"typing_fix\".\n    introv J.\n    inverts* J.\n    pick_fresh x.\n    rewrite* (@subst_exp_intro x).\n    remember nil as G.\n    rewrite_env(nil++G).\n    sapply* Etyping_subst.\n  - Case \"typing_mergev\".\n    introv J.\n    inverts J.\n    + inverts H0.\n      forwards*: step_not_value H5 H6.\n    + inverts H0.\n      forwards*: step_not_value H7 H6.\nQed.\n\n\nLemma TypedReduce_progress: forall v A B,\n    value v -> Etyping [] v A -> sub A B -> exists v', TypedReduce v B v'.\nProof.\n  introv Val Typ Sub.\n  gen A B.\n  induction v; try solve [inverts* Val];\n    intros;\n    try solve [\n      inverts Typ;\n      match goal with\n      | |- ( exists _ , TypedReduce _ ?B  _ ) =>\n        induction B\n      end;\n      inverts* Sub;\n      try solve [\n      match goal with\n      | _ : (sub t_top _) |- ( exists _ , TypedReduce _ (t_arrow _ _) _ ) =>\n        ( exists;\n          apply~ TReduce_toparr;\n          apply~ toplike_super_top;\n          destruct~ IHB2 as [v2 Tyr2] )\n      | |- ( exists _ , TypedReduce _ (t_and _ _ ) _ ) =>\n        ( destruct~ IHB1 as [v1 Tyr1];\n          destruct~ IHB2 as [v2 Tyr2];\n          exists*                     )\n      end ] ].\n  - Case \"e_absv\".\n    lets* [C [? ?]]: abs_typing_canonical Typ.\n    subst.\n    lets Lc: value_lc Val.\n    induction B0; \n      try solve [inverts* Sub].\n    + SCase \"t_arr\".\n      lets [St | [S1 S2]]: sub_inversion_arrow Sub;\n        destruct (toplike_decidable(t_arrow B0_1 B0_2));\n        exists;\n        try solve [\n              apply~ TReduce_toparr;\n              inverts* H ].\n      * exfalso.\n        apply H.\n        constructor.\n        apply~ toplike_super_top.\n      * (* not toplike case *)\n        apply~ TReduce_arrow.\n        auto_sub.\n      Unshelve.\n      eauto.\n    + SCase \"t_and\".\n      destruct~ IHB0_1 as [v1 Tyr1].\n      auto_sub.\n      destruct~ IHB0_2 as [v2 Tyr2].\n      auto_sub.\n      exists*.\n  - Case \"e_merge\".\n    lets Lc: value_lc Val.\n    inverts Val.\n    induction B.\n    + SSCase \"B:=Int\".\n      inverts Typ;\n      inverts* Sub.\n      lets* [? ?]: IHv1 H6.\n      lets* [? ?]: IHv2 H6.\n      lets* [? ?]: IHv1 H8.\n      lets* [? ?]: IHv2 H8.\n    + SSCase \"B:=Top\".\n      inverts Typ;\n      assert (sub A0 t_top) by auto;\n      lets* [? ?]: IHv1 H1 H.\n    + SSCase \"B:=Arrow\".\n      inverts Typ;\n      try solve [lets* [S | S]: sub_inversion_andl_arrr Sub;\n      [ forwards* [? ?]: IHv1 S | forwards* [? ?]: IHv2 S ] ].\n    + SSCase \"B:=B1&B2\".\n      inverts Typ;\n      (lets* [vb1' Tyrb1] : IHB1; try auto_sub;\n       lets* [vb2' Tyrb2] : IHB2; try auto_sub).\nQed.      \n\nTheorem progress : forall e A,\n    Etyping nil e A ->\n    value e \\/ exists e', step e e'.\nProof.\n  introv Typ. lets Typ': Typ.\n  inductions Typ; \n      lets Lc  : typing_regular_1 Typ';\n      try solve [left*];\n      try solve [right*].\n  - Case \"var\".\n    invert H0.\n  - Case \"app\".\n    right.\n    destruct~ IHTyp2 as [Val1 | [e1' Red2]].\n    destruct~ IHTyp1 as [Val2 | [e2' Red1]].\n    inverts* Typ2;\n      try solve [\n            inverts Val1 ].\n    + SCase \"e_app (e_absv _ _) v2\".\n      lets* (v2' & Tyr): TypedReduce_progress Typ1 H4.\n    + SCase \"e_app v1 e2\".\n      inverts Lc.\n      inverts* H1.\n    + SCase \"e_app e1 e2\".\n      forwards*: typing_regular_1 Typ1.\n  - Case \"merge\".\n    forwards*: typing_regular_1 Typ1.\n    forwards*: typing_regular_1 Typ2.\n    destruct~ IHTyp1 as [ Val1 | [t1' Red1]];\n      destruct~ IHTyp2 as [ Val2 | [t2' Red2]];\n      subst.\n    + SCase \"e_merge v1 e2\".\n      inverts* Typ1.\n    + SCase \"e_merge e1 v2\".\n      inverts* Typ2.\n    + SCase \"e_merge e1 e2\".\n      inverts* Typ2.\n  - Case \"anno\".\n    right.\n    destruct~ IHTyp as [ Val | [t' Red]].\n    + SCase \"e_anno v A\".\n      lets* (v1' & Tyr) : TypedReduce_progress Val Typ H.\n    + SCase \"e_anno e A\".\n      forwards*: Step_anno Red.\nQed.\n\n\n\nTheorem preservation_multi_step : forall e e' A,\n    nil |= e ~: A ->\n    e ->* e' ->\n    nil |= e' ~: A.\nProof.\n  introv Typ Red.\n  induction* Red.\n  lets*: preservation Typ H.\nQed.\n\n\nTheorem type_safety : forall e e' A,\n    nil |= e ~: A ->\n    e ->* e' ->\n    value e \\/ exists e'', step e e''.\nProof.\n  introv Typ Red.\n  induction Red.\n  lets*: progress Typ.\n  lets*: preservation Typ H.\nQed.\n", "meta": {"author": "RealAnonymous2019", "repo": "TypeDirectedOS", "sha": "8d98e87b269cb18cc7a57bb366f46eca70c8e738", "save_path": "github-repos/coq/RealAnonymous2019-TypeDirectedOS", "path": "github-repos/coq/RealAnonymous2019-TypeDirectedOS/TypeDirectedOS-8d98e87b269cb18cc7a57bb366f46eca70c8e738/main_version/coq/Type_Safety.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.287897040705774}}
{"text": "(*\n * © 2019 XXX.\n * \n * SPDX-License-Identifier: MIT\n * \n *)\nFrom Coq Require Import\n     List\n     Eqdep\n     Lia\n.\n\nFrom SPICY Require Import\n     MyPrelude\n     AdversaryUniverse\n     Automation\n     Keys\n     Maps\n     Messages\n     MessageEq\n     RealWorld\n     Simulation\n     Tactics\n\n     Theory.KeysTheory\n\n     ModelCheck.ModelCheck\n     ModelCheck.SafeProtocol\n     ModelCheck.UniverseEqAutomation\n     ModelCheck.ProtocolFunctions\n     ModelCheck.PartialOrderReduction\n     ModelCheck.SilentStepElimination\n.\n\nFrom SPICY Require\n     IdealWorld\n     RealWorld\n     ChMaps\n.\n\nFrom Frap Require \n     Sets\n.\n\nImport ChMaps.ChMapNotation\n       ChMaps.ChNotation.\n\nSet Implicit Arguments.\n\nModule SimulationAutomation.\n\n  #[export] Hint Constructors RealWorld.msg_accepted_by_pattern : core.\n  #[export] Hint Extern 1 (_ $k++ _ $? _ = Some _) => solve [ solve_perm_merges ] : core.\n\n  Module T.\n    Import RealWorld.\n\n    Lemma message_match_not_match_pattern_different :\n      forall t1 t2 (msg1 : crypto t1) (msg2 : crypto t2) cs suid froms pat,\n        ~ msg_accepted_by_pattern cs suid froms pat msg1\n        -> msg_accepted_by_pattern cs suid froms pat msg2\n        -> existT _ _ msg1 <> existT _ _ msg2.\n    Proof.\n      intros.\n      unfold not; intros.\n      generalize (projT1_eq H1); intros EQ; simpl in EQ; subst.\n      eapply inj_pair2 in H1; subst.\n      contradiction.\n    Qed.\n\n    Lemma message_queue_split_head :\n      forall t1 t2 (msg1 : crypto t1) (msg2 : crypto t2) qmsgs qmsgs1 qmsgs2\n        cs suid froms pat,\n\n        existT _ _ msg2 :: qmsgs = qmsgs1 ++ existT _ _ msg1 :: qmsgs2\n        -> msg_accepted_by_pattern cs suid froms pat msg1\n        -> ~ msg_accepted_by_pattern cs suid froms pat msg2\n        -> Forall (fun '(existT _ _ msg') => ~ msg_accepted_by_pattern cs suid froms pat msg') qmsgs1\n        -> exists qmsgs1',\n            qmsgs1 = (existT _ _ msg2) :: qmsgs1'.\n    Proof.\n      intros.\n      destruct qmsgs1.\n      - rewrite app_nil_l in H.\n        eapply message_match_not_match_pattern_different in H0; eauto.\n        invert H; contradiction.\n\n      - rewrite <- app_comm_cons in H.\n        invert H; eauto.\n    Qed.\n\n    Lemma message_queue_solve_head :\n      forall t1 t2 (msg1 : crypto t1) (msg2 : crypto t2) qmsgs qmsgs1 qmsgs2\n        cs suid froms pat,\n\n        existT _ _ msg2 :: qmsgs = qmsgs1 ++ existT _ _ msg1 :: qmsgs2\n        -> msg_accepted_by_pattern cs suid froms pat msg1\n        -> msg_accepted_by_pattern cs suid froms pat msg2\n        -> Forall (fun '(existT _ _ msg') => ~ msg_accepted_by_pattern cs suid froms pat msg') qmsgs1\n        -> qmsgs1 = []\n          /\\ qmsgs2 = qmsgs\n          /\\ existT _ _ msg1 = existT _ _ msg2.\n    Proof.\n      intros.\n      subst.\n      destruct qmsgs1.\n\n      rewrite app_nil_l in H\n      ; invert H\n      ; eauto.\n\n      exfalso.\n      rewrite <- app_comm_cons in H.\n      invert H; eauto.\n      invert H2; contradiction.\n    Qed.\n\n    Ltac pr_message cs uid froms pat msg :=\n      (assert (msg_accepted_by_pattern cs uid froms pat msg)\n        by (econstructor; eauto))\n      || (assert (~ msg_accepted_by_pattern cs uid froms pat msg)\n          by (let MA := fresh \"MA\" in  unfold not; intros MA; invert MA; clean_map_lookups)).\n\n    Ltac cleanup_msg_queue :=\n      repeat (\n          invert_base_equalities1 ||\n          match goal with\n          | [ H : context [ (_ :: _) ++ _ ] |- _ ] =>\n            rewrite <- app_comm_cons in H\n          end ).\n\n    Ltac process_message_queue :=\n      cleanup_msg_queue;\n      match goal with\n      | [ H : (existT _ _ ?m) :: ?msgs = ?msgs1 ++ (existT _ _ ?msg) :: ?msgs2,\n              M : msg_accepted_by_pattern ?cs ?suid ?froms ?pat ?msg\n          |- _ ] =>\n\n        pr_message cs suid froms pat m\n        ; match goal with\n          | [ MSA : msg_accepted_by_pattern cs suid froms pat m\n                    , HD : Forall _ msgs1\n              |- _ ] =>\n            idtac \"solving \" H M MSA HD\n            ; pose proof (message_queue_solve_head _ H M MSA HD)\n            ; split_ex; subst\n            ; cleanup_msg_queue; subst\n          | [ MSA : ~ msg_accepted_by_pattern cs suid froms pat m\n                    , HD : Forall _ msgs1\n              |- _ ] =>\n            idtac \"splitting\"\n            ; pose proof (message_queue_split_head _ H M MSA HD)\n            ; split_ex; subst\n            ; invert HD\n            ; cleanup_msg_queue; subst\n            ; process_message_queue (* recurse *)\n          end\n      end.\n\n    Ltac step_usr_hyp H cmd :=\n      match cmd with\n      | Return _ => apply step_user_inv_ret in H; contradiction\n      | Bind _ _ => apply step_user_inv_bind in H; split_ands; split_ors; split_ands; subst; try discriminate\n      | Gen => apply step_user_inv_gen in H\n      | Send _ _ => apply step_user_inv_send in H\n      | Recv _ => apply step_user_inv_recv in H; split_ex; subst; process_message_queue\n      | SignEncrypt _ _ _ _ => apply step_user_inv_enc in H\n      | Decrypt _ => apply step_user_inv_dec in H\n      | Sign _ _ _ => apply step_user_inv_sign in H\n      | Verify _ _ => apply step_user_inv_verify in H\n      | GenerateKey _ _ => apply step_user_inv_genkey in H\n      | _ => idtac \"***Missing inversion: \" cmd; invert H\n      end; split_ex; subst.\n\n    Lemma inv_univ_silent_step :\n      forall t__hon t__adv ru ru' suid b,\n        lameAdv b ru.(RealWorld.adversary)\n        -> @RealWorld.step_universe t__hon t__adv suid ru Silent ru'\n        -> exists uid ud usrs adv cs gks ks qmsgs mycs froms sents cur_n cmd,\n            ru.(RealWorld.users) $? uid = Some ud\n            /\\ step_user Silent (Some uid)\n                        (build_data_step ru ud)\n                        (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n            /\\ ru' = buildUniverse usrs adv cs gks uid {| 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    Proof.\n      intros * LAME STEP\n      ; invert STEP.\n\n      - unfold mkULbl in H2\n        ; destruct lbl\n        ; try discriminate\n        ; eauto 20.\n\n      - unfold lameAdv in LAME.\n        unfold build_data_step in H\n        ; rewrite LAME in H\n        ; invert H.\n    Qed.\n\n    Lemma inv_univ_labeled_step :\n      forall t__hon t__adv ru ru' suid uid a,\n        @RealWorld.step_universe t__hon t__adv suid ru (Action (uid,a)) ru'\n        -> exists ud usrs adv cs gks ks qmsgs mycs froms sents cur_n cmd,\n          ru.(RealWorld.users) $? uid = Some ud\n          /\\ suid = Some uid\n          /\\ step_user (@Action RealWorld.action a) (Some uid)\n                      (build_data_step ru ud)\n                      (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n          /\\ ru' = buildUniverse usrs adv cs gks uid {| 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    Proof.\n      intros * STEP\n      ; invert STEP.\n\n      unfold mkULbl in H2\n      ; destruct lbl\n      ; try discriminate.\n\n      invert H2; eauto 20.\n    Qed.\n\n    Ltac rw_step1 :=\n      match goal with\n\n      (* Only take a user step if we have chosen a user *)\n      | [ H : RealWorld.step_user _ (Some ?u) _ _ |- _ ] =>\n        progress simpl in H\n      | [ H : RealWorld.step_user _ (Some ?u) (_,_,_,_,_,_,_,_,_,_,?cmd) _ |- _ ] =>\n        is_not_var u;\n        step_usr_hyp H cmd\n\n      | [ STEP : RealWorld.step_user _ None (_,_,_,_,_,_,_,_,_,_,RealWorld.protocol ?adv) _\n        , LAME : lameAdv _ ?adv |- _ ] => pose proof (adv_no_step LAME STEP); contradiction\n\n      | [ H : RealWorld.step_user _ _ (build_data_step _ _) _ |- _ ] =>\n        unfold build_data_step in H; autounfold with user_build in H; simpl in H\n\n      | [ |- context [RealWorld.buildUniverse _ _ _ _ _ _] ] =>\n        unfold RealWorld.buildUniverse\n\n      | [ H: step_universe _ ?U Silent _ |- _ ] =>\n        is_not_var U\n        ; eapply inv_univ_silent_step in H\n        ; eauto\n        ; split_ex\n        ; subst\n\n      | [ H: step_universe _ ?U (Action _) _ |- _ ] =>\n        is_not_var U\n        ; eapply inv_univ_labeled_step in H\n        ; eauto\n        ; split_ex\n        ; subst\n      end.\n\n    Ltac prove_alignment1 :=\n      equality1 ||\n      match goal with\n      | [ |- labels_align _ ] => unfold labels_align; intros\n      | [ H : _ \\/ False |- _ ] =>\n        destruct H; [|contradiction]\n      | [ H : _ \\/ ?r |- _ ] =>\n        destruct H\n      | [ H : indexedRealStep _ _ _ _ |- _ ] => invert H\n      | [ H : users _ $? _ = Some _ |- _ ] =>\n        progress (autounfold in H; simpl in H)\n      (* | [ H : _ $+ (_,_) $? _ = Some _ |- _ ] => progress clean_map_lookups *)\n      | [ H : _ $+ (?k1,_) $? ?k2 = Some _ |- _ ] => destruct (k1 ==n k2); subst\n      | [ H : step_user (Action _) (Some ?uid) _ _ |- _ ] =>\n        progress (autounfold in H; unfold RealWorld.build_data_step in H; simpl in H)\n      | [ H : step_user _ (Some ?u) (_,_,_,_,_,_,_,_,_,_,?cmd) _ |- _ ] =>\n        is_not_var u; is_not_evar u;\n        step_usr_hyp H cmd\n      | [ |- exists _ _ _, _ ] => simpl; (do 3 eexists); repeat simple apply conj\n      end.\n      (* || equality1. *)\n    \n    Lemma label_align_step_split :\n      forall t__hon t__adv st st',\n        @step t__hon t__adv st st'\n        -> labels_align st\n        -> forall ru ru' iu iu' b b' a,\n            st = (ru,iu,b)\n            -> st' = (ru',iu',b')\n            -> lameAdv a ru.(adversary)\n            -> b = b'\n              /\\ exists uid,\n                ( indexedRealStep uid Silent ru ru' /\\ iu = iu' )\n                \\/ exists iu0 ra ia, \n                  indexedRealStep uid (Action ra) ru ru'\n                  /\\ (indexedIdealStep uid Silent) ^* iu iu0\n                  /\\ indexedIdealStep uid (Action ia) iu0 iu'\n                  /\\ action_matches (all_ciphers ru) (all_keys ru) (uid,ra) ia.\n    Proof.\n      intros.\n      subst; invert H; try contradiction.\n\n      - invert H2;\n          try \n            match goal with\n            | [ H : Silent = mkULbl ?lbl _ |- _ ] => unfold mkULbl in H; destruct lbl; try discriminate\n            end;\n          split; eexists; left; eauto.\n        unfold build_data_step in *; unfold lameAdv in H3; rewrite H3 in *.\n        invert H.\n      - split; eexists; right; eauto 10.\n\n        Unshelve.\n        auto.\n    Qed.\n\n    Lemma label_align_indexedModelStep_split :\n      forall t__hon t__adv st st' uid,\n        @indexedModelStep t__hon t__adv uid st st'\n        -> labels_align st\n        -> forall ru ru' iu iu' b b' a,\n            st = (ru,iu,b)\n            -> st' = (ru',iu',b')\n            -> lameAdv a ru.(adversary)\n            -> b = b'\n              /\\ ( (indexedRealStep uid Silent ru ru' /\\ iu = iu')\n                \\/ (exists iu0 ra ia, \n                  indexedRealStep uid (Action ra) ru ru'\n                  /\\ (indexedIdealStep uid Silent) ^* iu iu0\n                  /\\ indexedIdealStep uid (Action ia) iu0 iu'\n                  /\\ action_matches (all_ciphers ru) (all_keys ru) (uid,ra) ia)).\n    Proof.\n      intros;\n        subst; invert H; try contradiction; eauto 12.\n    Qed.\n\n\n  End T.\n\n  Import T.\n  Export T.\n\n  Ltac fill_unification_var_ineq uni v :=\n    match goal with\n    | [ H : ?uni' = v -> False |- _ ] => unify uni uni'\n    | [ H : v = ?uni' -> False |- _ ] => unify uni uni'\n    end.\n\n  Ltac solve_simple_ineq :=\n    repeat\n      match goal with\n      | [ |- ?kid1 <> ?kid2 ] =>\n          congruence\n        || (is_evar kid1; fill_unification_var_ineq kid1 kid2)\n        || (is_evar kid2; fill_unification_var_ineq kid2 kid1)\n        || (is_not_var kid1; progress unfold kid1)\n        || (is_not_var kid2; progress unfold kid2)\n      end.\n\n  Ltac solve_concrete_maps1 :=\n    clean_map_lookups1\n    || ChMaps.ChMap.clean_map_lookups1\n    || match goal with\n      (* | [ H : Some _ = Some _ |- _ ] => invert H *)\n      (* | [ H : Some _ = None |- _ ] => discriminate *)\n      (* | [ H : None = Some _ |- _ ] => discriminate *)\n      | [ H : mkKeys _ $? _ = _ |- _ ] => unfold mkKeys in H; simpl in H\n\n      | [ H : ?m $? _ = _ |- _ ] => progress (unfold m in H)\n      | [ H : ?m #? _ = _ |- _ ] => progress (unfold m in H)\n      | [ |- context [ ?m $? _ ] ] => progress (unfold m)\n      | [ |- context [ ?m #? _ ] ] => progress (unfold m)\n                                             \n      | [ H : ?m $+ (?k1,_) $? ?k2 = _ |- _ ] =>\n        progress ( repeat ( rewrite add_neq_o in H by solve_simple_ineq ) )\n      | [ H : ?m #+ (?k1,_) #? ?k2 = _ |- _ ] =>\n        progress ( repeat ( rewrite ChMaps.ChMap.F.add_neq_o in H by solve_simple_ineq ) )\n      | [ |- context [ _ $+ (?kid2,_) $? ?kid1 ] ] =>\n        progress ( repeat ( rewrite add_neq_o by solve_simple_ineq ) )\n      | [ |- context [ _ #+ (?kid2,_) #? ?kid1 ] ] =>\n        progress ( repeat ( rewrite ChMaps.ChMap.F.add_neq_o by solve_simple_ineq ) )\n\n      | [ H : In ?k ?m -> False |- _ ] =>\n        is_not_var k;\n        assert (In k m) by (clear H; rewrite in_find_iff; unfold not; intros; repeat solve_concrete_maps1);\n        contradiction\n      | [ H : In _ _ |- _ ] => rewrite in_find_iff in H\n      | [ H : ~ In _ _ |- _ ] => rewrite not_find_in_iff in H\n      | [ |- ~ In _ _ ] => rewrite not_find_in_iff; try eassumption\n      | [ H : In ?x ?xs -> False |- _ ] => change (In x xs -> False) with (~ In x xs) in H\n\n      | [ H : ChMaps.ChMap.Map.In ?k ?m -> False |- _ ] =>\n        is_not_var k\n        ; assert (ChMaps.ChMap.Map.In k m)\n          by (clear H; rewrite ChMaps.ChMap.F.in_find_iff; unfold not; intros; repeat solve_concrete_maps1)\n        ; contradiction\n      | [ H : ChMaps.ChMap.Map.In _ _ |- _ ] => rewrite ChMaps.ChMap.F.in_find_iff in H\n      | [ H : ~ ChMaps.ChMap.Map.In _ _ |- _ ] => rewrite ChMaps.ChMap.F.not_find_in_iff in H\n      | [ |- ~ ChMaps.ChMap.Map.In _ _ ] => rewrite ChMaps.ChMap.F.not_find_in_iff; try eassumption\n      | [ H : ChMaps.ChMap.Map.In ?x ?xs -> False |- _ ] =>\n        change (ChMaps.ChMap.Map.In x xs -> False) with (~ ChMaps.ChMap.Map.In x xs) in H\n\n      | [ |- context [ next_key ] ] => progress (unfold next_key; simpl)\n\n      | [ |- _ $+ (?k1,_) $? ?k2 = _ ] =>\n        is_not_evar k2; is_not_evar k2; (is_var k1 || is_var k2)\n        ; destruct (k1 ==n k2); subst; try contradiction\n\n      | [ |- _ #+ (?k1,_) #? ?k2 = _ ] =>\n        is_not_evar k2; is_not_evar k2; (is_var k1 || is_var k2)\n        ; destruct (ChMaps.ChMap.F.eq_dec k1 k2); subst; try contradiction\n                                           \n      | [ |- context [ add_key_perm _ _ _ ]] => progress (unfold add_key_perm)\n\n      | [ |- _ = _ ] => reflexivity\n      | [ |- _ $+ (_,_) = _ ] => apply map_eq_Equal; unfold Equal; intros\n      | [ |- _ #+ (_,_) = _ ] => apply ChMaps.ChMap.map_eq_Equal; unfold ChMaps.ChMap.Map.Equal; intros\n\n      | [ |- Some _ = Some _ ] => f_equal\n      | [ |- {| RealWorld.key_heap := _ |} = _ ] => f_equal\n      | [ |- _ $? _ = _ ] => eassumption\n      | [ |- _ #? _ = _ ] => eassumption\n\n                             \n      | [ H : ?m $+ (?k1,_) $? ?k2 = _ |- _ $+ (_,_) $? _ = _ ] =>\n        (is_var k1 || is_var k2); idtac \"destructing1 \" k1 k2; destruct (k1 ==n k2); subst\n      | [ H : ?m $+ (?k1,_) $? ?k2 = _ |- (match _ $+ (_,_) $? _ with _ => _ end) $? _ = _ ] =>\n        (is_var k1 || is_var k2); idtac \"destructing2 \" k1 k2; destruct (k1 ==n k2); subst\n      | [ H : ?m #+ (?k1,_) #? ?k2 = _ |- _ #+ (_,_) #? _ = _ ] =>\n        (is_var k1 || is_var k2); idtac \"#destructing1 \" k1 k2; destruct (ChMaps.ChMap.F.eq_dec k1 k2); subst\n      | [ H : ?m #+ (?k1,_) #? ?k2 = _ |- (match _ #+ (_,_) #? _ with _ => _ end) #? _ = _ ] =>\n        (is_var k1 || is_var k2); idtac \"#destructing2 \" k1 k2; destruct (ChMaps.ChMap.F.eq_dec k1 k2); subst\n      end.\n\n  Ltac solve_concrete_maps := repeat solve_concrete_maps1.\n\n  Ltac churn2 :=\n    (repeat equality1); subst; rw_step1; intuition idtac; split_ex; intuition idtac; subst; try discriminate; solve_concrete_maps.\n\n  Ltac churn :=\n    repeat churn2.\n\n  Ltac i_single_silent_step :=\n      eapply IdealWorld.LStepBindProceed\n    || eapply IdealWorld.LStepGen\n    || eapply IdealWorld.LStepCreateChannel\n  .\n\n  Ltac r_single_silent_step :=\n      eapply RealWorld.StepBindProceed\n    || eapply RealWorld.StepGen\n    (* || eapply RealWorld.StepRecvDrop *)\n    || eapply RealWorld.StepEncrypt\n    || eapply RealWorld.StepDecrypt\n    || eapply RealWorld.StepSign\n    || eapply RealWorld.StepVerify\n    || eapply RealWorld.StepGenerateKey\n  .\n\n  Ltac pick_user uid :=\n    match goal with\n    | [ |- _ $? ?euid = Some _ ] => unify euid uid\n    end; reflexivity.\n\n  Ltac istep_univ uid :=\n    eapply IdealWorld.LStepUser'; simpl; swap 2 3; [ pick_user uid | ..];\n      (try eapply @eq_refl); (try f_equal); simpl.\n  Ltac rstep_univ uid :=\n    eapply  RealWorld.StepUser; simpl; swap 2 3; [ pick_user uid | ..]; (try eapply @eq_refl); simpl.\n\n  Ltac rw H :=\n    (rewrite ChMaps.ChMap.F.add_neq_o in H by congruence)\n    || (rewrite ChMaps.ChMap.F.add_eq_o in H by congruence).\n\n  Ltac solve_ideal_step_stuff1 :=\n    match goal with\n    | [ H : context [ _ #+ (_,_) #? _ ] |- _ ] => progress (repeat rw H)\n    | [ Heq : ?k = _, H : _ #+ (?k1,_) #? ?k2 = None |- _ ] =>\n      match k2 with\n      | # k => idtac k\n      | _ => fail 1\n      end;\n      assert (k1 <> k2)\n        by (destruct (ChMaps.ChMap.F.eq_dec k1 k2); clear Heq; try assumption;\n            unfold ChMaps.ChannelType.eq in *; subst; ChMaps.ChMap.clean_map_lookups);\n      ChMaps.ChMap.clean_map_lookups\n    | [ H : # ?x = # ?y -> False |- _ ] => assert (x <> y) by congruence; clear H\n    | [ |- Forall _ _ ] => econstructor\n    | [ |- {| IdealWorld.channel_vector := _; IdealWorld.users := _ |} = _] => smash_universe; solve_concrete_maps\n    | [ |- _ = {| IdealWorld.channel_vector := _; IdealWorld.users := _ |}] => smash_universe; solve_concrete_maps\n    | [ |- IdealWorld.screen_msg _ _ ] => econstructor\n    | [ |- IdealWorld.permission_subset _ _ ] => econstructor\n    | [ |- IdealWorld.check_perm _ _ _ ] => unfold IdealWorld.check_perm\n    | [ |- ?m #? (# ?k) = None ] =>\n      solve [ is_evar k; unify k (ChMaps.next_key_nat m); apply ChMaps.next_key_not_in; trivial ]\n    | [ |- context [ ChMaps.next_key_nat ?m ]] =>\n      match goal with\n      | [ |- context [ IdealWorld.addMsg ] ] => unfold IdealWorld.addMsg; simpl\n      | _ => \n        idtac \"posing\"\n        ; pose proof (ChMaps.next_key_not_in m _ eq_refl)\n        ; let k := fresh \"k\" in\n          let Heq := fresh \"Heq\"\n          in remember (ChMaps.next_key_nat m) as k eqn:Heq\n      end\n    (* | [ |- context [ match ?m $+ (?kid1,_) $? ?kid1 with _ => _ end ] ] => *)\n    (*   rewrite add_eq_o by trivial *)\n    | [ |- context [ match ?m $+ (?kid2,_) $? ?kid1 with _ => _ end] ] =>\n      progress (\n          repeat (\n              ( rewrite add_eq_o by trivial)\n              || (rewrite add_neq_o by solve_simple_ineq)\n            )\n        )\n    | [ |- context [ #0 #? _ ]] => rewrite ChMaps.ChMap.lookup_empty_none\n    | [ |- _ = _ ] => subst; reflexivity\n    | [ |- context [ _ $? _ ] ] => progress solve_concrete_maps\n    | [ |- context [ _ #? _ ] ] => progress solve_concrete_maps\n    | [ H : match _ $+ (?k1,_) $? ?k2 with _ => _ end |- _ ] =>\n      try (\n          progress (\n              repeat ((  rewrite add_eq_o in H by trivial)\n                      || (rewrite add_neq_o in H by solve_simple_ineq)\n                      || (rewrite lookup_empty_none in H))\n        ))\n      || destruct (k1 ==n k2); subst\n    end; simpl.\n\n  Ltac solve_ideal_step_stuff := repeat solve_ideal_step_stuff1.\n\n  Ltac isilent_step_univ uid :=\n    eapply IdealWorld.LStepUser'; simpl; swap 2 3; [ pick_user uid | ..]; (try simple eapply @eq_refl);\n    ((eapply IdealWorld.LStepBindRecur; i_single_silent_step; solve [ solve_ideal_step_stuff; eauto 2  ])\n     || (i_single_silent_step; solve [ solve_ideal_step_stuff; eauto 2 ])).\n  Ltac rsilent_step_univ uid :=\n    eapply  RealWorld.StepUser; simpl; swap 2 3; [ pick_user uid | ..]; (try simple eapply @eq_refl);\n      ((eapply RealWorld.StepBindRecur; r_single_silent_step) || r_single_silent_step).\n\n  Ltac single_silent_multistep usr_step := eapply TrcFront; [usr_step |]; simpl.\n  Ltac single_silent_multistep3 usr_step := eapply Trc3Front; swap 1 2; [usr_step |..]; simpl; trivial.\n  \n  Ltac real_single_silent_multistep uid := single_silent_multistep3 ltac:(rsilent_step_univ uid).\n  Ltac ideal_single_silent_multistep uid := single_silent_multistep ltac:(isilent_step_univ uid).\n\n  Ltac figure_out_ideal_user_step step_tac U1 U2 :=\n    match U1 with\n    | context [ add ?u ?usr1 _ ] =>\n      match U2 with\n      | context [ add u ?usr2 _ ] =>\n        let p1 := constr:(IdealWorld.protocol usr1) in\n        let p2 := constr:(IdealWorld.protocol usr2) in\n        does_not_unify p1 p2; step_tac u\n      end\n    end.\n\n  Ltac figure_out_real_user_step step_tac U1 U2 :=\n    match U1 with\n    | context [ add ?u ?usr1 _ ] =>\n      match U2 with\n      | context [ add u ?usr2 _ ] =>\n        let p1 := constr:(RealWorld.protocol usr1) in\n        let p2 := constr:(RealWorld.protocol usr2) in\n        does_not_unify p1 p2; step_tac u\n      end\n    end.\n\n  #[export] Remove Hints TrcRefl TrcFront Trc3Refl Trc3Front : core.\n  #[export] Hint Extern 1 (_ ^* ?U ?U) => apply TrcRefl : core.\n\n  #[export] Remove Hints\n         eq_sym (* includes_lookup *)\n         trans_eq_bool mult_n_O plus_n_O eq_add_S f_equal_nat : core.\n\n  #[export] Hint Constructors action_matches : core.\n  #[export] Hint Resolve IdealWorld.LStepSend IdealWorld.LStepRecv' : core.\n\n  Lemma TrcRefl' :\n    forall {A} (R : A -> A -> Prop) x1 x2,\n      x1 = x2 ->\n      trc R x1 x2.\n  Proof.\n    intros. subst. apply TrcRefl.\n  Qed.\n\n  Lemma Trc3Refl' :\n    forall {A B} (R : A -> B -> A -> Prop) x1 x2 P,\n      x1 = x2 ->\n      trc3 R P x1 x2.\n  Proof.\n    intros. subst. apply Trc3Refl.\n  Qed.\n  \n  Ltac solve_refl :=\n    solve [\n        eapply TrcRefl\n      | eapply TrcRefl'; simpl; eauto ].\n\n  Ltac solve_refl3 :=\n    solve [\n        eapply Trc3Refl\n      | eapply Trc3Refl'; simpl; smash_universe; solve_concrete_maps ].\n\n  Ltac simpl_real_users_context :=\n    simpl;\n    repeat\n      match goal with\n      | [ |- context [ RealWorld.buildUniverse ] ] => progress (unfold RealWorld.buildUniverse; simpl)\n      | [ |- context [ {| RealWorld.users := ?usrs |}] ] => progress canonicalize_map usrs\n      (* | [ |- context [ RealWorld.mkUniverse ?usrs _ _ _] ] => canonicalize_map usrs *)\n      end.\n\n  Ltac simpl_ideal_users_context :=\n    simpl;\n    repeat\n      match goal with\n      | [ |- context [ {| IdealWorld.users := ?usrs |}] ] => progress canonicalize_map usrs\n      end.\n\n  Ltac rss_clean uid := real_single_silent_multistep uid; [ solve [eauto 3] .. |].\n\n  Ltac ideal_silent_multistep :=\n    simpl_ideal_users_context;\n    match goal with\n    | [ |- istepSilent ^* ?U1 ?U2 ] =>\n      is_not_evar U1; is_not_evar U2;\n      first [\n          solve_refl\n        | figure_out_ideal_user_step ideal_single_silent_multistep U1 U2 ]\n    end.\n\n  Ltac single_step_ideal_universe :=\n    simpl_ideal_users_context;\n    match goal with\n    | [ |- IdealWorld.lstep_universe _ ?U1 _ ?U2] =>\n      match U1 with\n      | IdealWorld.construct_universe _ ?usrs1 =>\n        match U2 with\n        | IdealWorld.construct_universe _ ?usrs2 =>\n          figure_out_ideal_user_step istep_univ usrs1 usrs2\n        end\n      end\n    end.\n\n  Ltac single_labeled_ideal_step uid :=\n    eapply IdealWorld.LStepUser' with (u_id := uid);\n    [ solve [ solve_concrete_maps ] | simpl | reflexivity ];\n    eapply IdealWorld.LStepBindRecur;\n    ( (eapply IdealWorld.LStepRecv'; solve [ solve_ideal_step_stuff ])\n      || (eapply IdealWorld.LStepSend; solve [ solve_ideal_step_stuff ])).\n\n  Ltac step_each_ideal_user U :=\n    match U with\n    | ?usrs $+ (?AB,_) =>\n      idtac \"stepping \" AB; (single_labeled_ideal_step AB || step_each_ideal_user usrs)\n    end.\n\n  (* TODO: during canonicalization, cleanup the channels map *)\n  Local Ltac blah1 :=\n    match goal with\n    | [ |- context [ IdealWorld.addMsg ]] => unfold IdealWorld.addMsg; simpl\n    | [ |- context [ ?m #? _ ]] => progress unfold m\n    | [ |- context [ _ #+ (?k1,_) #? ?k1 ]] => rewrite ChMaps.ChMap.F.add_eq_o by trivial\n    | [ |- context [ _ #+ (?k1,_) #? ?k2 ]] => rewrite ChMaps.ChMap.F.add_neq_o by congruence\n    end.\n\n  Ltac step_ideal_user :=\n    match goal with\n    | [ |- IdealWorld.lstep_universe _ _ (Action _) ?U' ] =>\n      is_evar U'; simpl_ideal_users_context; (repeat blah1);\n      match goal with\n      | [ |- IdealWorld.lstep_universe\n            {| IdealWorld.users := ?usrs; IdealWorld.channel_vector := _ |} _ _ ] =>\n        step_each_ideal_user usrs\n      end\n    end.\n\n  Ltac idealUserSilentStep :=\n    (eapply IdealWorld.LStepBindRecur; i_single_silent_step; solve [ solve_ideal_step_stuff; eauto 2  ])\n    || (i_single_silent_step; solve [ solve_ideal_step_stuff; eauto 2 ]).\n\n  Ltac indexedIdealSilentStep :=\n    econstructor; simpl; [ solve [ clean_map_lookups; trivial ]\n                         | solve [ idealUserSilentStep ]\n                         | reflexivity ].\n\n  Ltac solve_indexed_silent_multistep :=\n    simpl_ideal_users_context;\n    eapply TrcFront; [ indexedIdealSilentStep |].\n\n  Ltac unBindi :=\n    match goal with\n    | [ |- IdealWorld.lstep_user _ (Action _) (_,IdealWorld.Bind _ _,_) _ ] =>\n      eapply IdealWorld.LStepBindRecur\n    end.\n\n  Ltac ideal_user_labeled_step :=\n    simpl\n    ; repeat unBindi\n    ; match goal with\n      | [ |- IdealWorld.lstep_user _ (Action _) (_,IdealWorld.Recv _,_) _ ] =>\n        eapply IdealWorld.LStepRecv'; solve_ideal_step_stuff\n      | [ |- IdealWorld.lstep_user _ (Action _) (_,IdealWorld.Send _ _,_) _ ] =>\n        eapply IdealWorld.LStepSend; solve_ideal_step_stuff\n      end.\n  \n  Ltac indexedIdealStep :=\n    match goal with\n    | [ |- indexedIdealStep _ (Action _) _ ?U' ] =>\n      is_evar U'; simpl_ideal_users_context; (repeat blah1);\n      econstructor; simpl; [ solve [ clean_map_lookups; trivial ]\n                           | ideal_user_labeled_step\n                           | reflexivity ]\n    end.\n\n  #[export] Hint Extern 1 ((indexedIdealStep _ Silent) ^* _ _) =>\n    repeat solve_indexed_silent_multistep; solve_refl : core.\n\n  #[export] Hint Extern 1 (indexedIdealStep _ (Action _) _ _) => indexedIdealStep : core.\n\n  #[export] Hint Extern 1 (istepSilent ^* _ _) => ideal_silent_multistep : core.\n\n  #[export] Hint Extern 1 ({| IdealWorld.channel_vector := _; IdealWorld.users := _ |} = _) => smash_universe; solve_concrete_maps : core.\n  #[export] Hint Extern 1 (_ = {| IdealWorld.channel_vector := _; IdealWorld.users := _ |}) => smash_universe; solve_concrete_maps : core.\n\n  #[export] Hint Extern 1 (IdealWorld.lstep_universe _ _ _) => step_ideal_user : core.\n  \n  #[export] Hint Extern 1 (List.In _ _) => progress simpl : core.\n  #[export] Hint Extern 1 (~ In ?k ?m) =>\n     solve_concrete_maps : core.\n\n  #[export] Hint Extern 1 (action_adversary_safe _ _ _ = _) => unfold action_adversary_safe; simpl : core.\n  #[export] Hint Extern 1 (IdealWorld.screen_msg _ _) => econstructor; progress simpl : core.\n\n  #[export] Hint Extern 1 (_ = RealWorld.addUserKeys _ _) => unfold RealWorld.addUserKeys, map; simpl : core.\n\n  #[export] Hint Extern 1 (_ $+ (_,_) = _) =>\n    reflexivity || (solve [ solve_concrete_maps ] ) || (progress m_equal) || (progress clean_map_lookups) : core.\n  #[export] Hint Extern 1 (_ $? _ = _) =>\n    reflexivity || (solve [ solve_concrete_maps ] ) || (progress m_equal) || (progress clean_map_lookups) : core.\n  #[export] Hint Extern 1 (_ #+ (_,_) = _) =>\n    reflexivity || (solve [ solve_concrete_maps ] ) || (progress ChMaps.m_equal) || (progress ChMaps.ChMap.clean_map_lookups) : core.\n  #[export] Hint Extern 1 (_ #? _ = _) =>\n    reflexivity || (solve [ solve_concrete_maps ] ) || (progress ChMaps.m_equal) || (progress ChMaps.ChMap.clean_map_lookups) : core.\n\n  Local Ltac merge_perms_helper :=\n    repeat match goal with\n           | [ |- _ = _ ] => reflexivity\n           | [ |- _ $? _ = _ ] => solve_concrete_maps\n           end.\n  \n  Ltac solve_action_matches1 :=\n    match goal with\n    | [ |- content_eq _ _ _ ] => progress simpl\n    | [ |- action_matches _ _ _ _ ] => progress simpl_real_users_context\n    | [ |- action_matches _ _ _ _ ] => progress simpl_ideal_users_context\n    | [ H : ?cs $? ?cid = Some (SigCipher _ _ _ _ )\n        |- action_matches ?cs _ (_,RealWorld.Output (SignedCiphertext ?cid) _ _ _) _ ] => eapply OutSig\n    | [ H : ?cs $? ?cid = Some (SigEncCipher _ _ _ _ _ )\n        |- action_matches ?cs _ (_,RealWorld.Output (SignedCiphertext ?cid) _ _ _) _ ] => eapply OutEnc\n    | [ H : ?cs $? ?cid = Some (SigCipher _ _ _ _ )\n        |- action_matches ?cs _ (_,RealWorld.Input (SignedCiphertext ?cid) _ _) _ ] => eapply InpSig\n    | [ H : ?cs $? ?cid = Some (SigEncCipher _ _ _ _ _ )\n        |- action_matches ?cs _ (_,RealWorld.Input (SignedCiphertext ?cid) _ _) _ ] => eapply InpEnc\n    | [ |- action_matches ?cs _ (_,RealWorld.Output (SignedCiphertext ?cid) _ _ _) _ ] =>\n      match cs with\n      | context [ _ $+ (cid, SigCipher _ _ _ _)] => eapply OutSig\n      | context [_ $+ (cid, SigEncCipher _ _ _ _ _)] => eapply OutEnc\n      end\n    | [ |- action_matches ?cs _ (_,RealWorld.Input (SignedCiphertext ?cid) _ _) _ ] =>\n      match cs with\n      | context[ _ $+ (cid, SigCipher _ _ _ _)] => eapply InpSig\n      | context[ _ $+ (cid, SigEncCipher _ _ _ _ _)] => eapply InpEnc\n      end\n    | [ H : _ $+ (?k1,_) $? ?k2 = Some ?d__rw |- context [ RealWorld.key_heap ?d__rw $? _ = Some _ ] ] =>\n      is_var d__rw; is_var k2; is_not_var k1;\n      destruct (k1 ==n k2); subst; clean_map_lookups; simpl\n    | [ H : ?P $? _ = Some {| IdealWorld.read := _; IdealWorld.write := _ |} |- _ ] =>\n      simpl in *; unfold P in H; solve_concrete_maps\n    | [ |- _ $? _ = Some _ ] => progress solve_concrete_maps\n    | [ |- context [ IdealWorld.addMsg ]] => unfold IdealWorld.addMsg; simpl\n    | [ |- context [ ?m #? _ ]] => progress unfold m\n    | [ |- context [ _ #+ (?k1,_) #? ?k1 ]] => rewrite ChMaps.ChMap.F.add_eq_o by trivial\n    | [ |- context [ _ #+ (?k1,_) #? ?k2 ]] => rewrite ChMaps.ChMap.F.add_neq_o by congruence\n    | [ |- context [ IdealWorld.perm_intersection ] ] =>\n      unfold IdealWorld.perm_intersection; simpl\n    | [ H : _ $k++ _ $? _ = Some ?b |- context [ ?b ]] =>\n      solve [ solve_perm_merges; solve_concrete_maps ]\n    | [ |- _ $k++ _ $? _ = Some _ ] =>\n      solve [ erewrite merge_perms_adds_ks1; (swap 2 4; merge_perms_helper) ]\n      || solve [ erewrite merge_perms_adds_ks2; (swap 2 4; merge_perms_helper) ]\n    | [ H : match _ $+ (?k1,_) $? ?k1 with _ => _ end = _ |- _ ] =>\n      rewrite add_eq_o in H by trivial\n    | [ H : match _ $+ (?k1,_) $? ?k2 with _ => _ end = _ |- _ ] =>\n      rewrite add_neq_o in H by congruence\n    | [ |- _ <-> _ ] => split\n    | [ |- _ -> _ ] => intros\n    | [ |- _ = _ ] => reflexivity\n    | [ |- _ /\\ _ ] => split\n    | [ |- context [ _ $? _ ]] =>\n      progress (\n          repeat (\n              (rewrite add_eq_o by trivial)\n              || (rewrite add_neq_o by congruence)\n              || (rewrite lookup_empty_none by congruence)\n            )\n        )\n    end; split_ex; simpl in *.\n\n  #[export] Hint Extern 1 (action_matches _ _ _ _) =>\n    repeat (solve_action_matches1)\n  ; NatMap.clean_map_lookups\n  ; ChMaps.ChMap.clean_map_lookups : core.\n\n  #[export] Hint Resolve\n       findUserKeys_foldfn_proper\n       findUserKeys_foldfn_transpose : core.\n  \n  Lemma findUserKeys_add_reduce :\n    forall {A} (usrs : RealWorld.honest_users A) u_id ks p qmsgs mycs froms sents cur_n,\n      ~ In u_id usrs\n      -> RealWorld.findUserKeys (usrs $+ (u_id, {| RealWorld.key_heap := ks;\n                                      RealWorld.protocol := p;\n                                      RealWorld.msg_heap := qmsgs;\n                                      RealWorld.c_heap := mycs;\n                                      RealWorld.from_nons := froms;\n                                      RealWorld.sent_nons := sents;\n                                      RealWorld.cur_nonce := cur_n |})) = RealWorld.findUserKeys usrs $k++ ks.\n  Proof.\n    intros.\n    unfold RealWorld.findUserKeys.\n    rewrite fold_add; eauto.\n  Qed.\n\n  Lemma findUserKeys_empty_is_empty :\n    forall A, @RealWorld.findUserKeys A $0 = $0.\n  Proof. trivial. Qed.\n  \n  #[export] Hint Constructors RealWorld.msg_pattern_safe : core.\n\n  Lemma reduce_merge_perms :\n    forall perms1 perms2 kid perm1 perm2,\n        perm1 = match perms1 $? kid with\n                | Some p => p\n                | None => false\n                end\n      -> perm2 = match perms2 $? kid with\n                | Some p => p\n                | None => false\n                end\n      -> (perms1 $? kid = None -> perms2 $? kid = None -> False)\n      -> perms1 $k++ perms2 $? kid = Some (perm1 || perm2).\n  Proof.\n    intros; solve_perm_merges; subst; eauto.\n    - rewrite orb_false_r; auto.\n    - exfalso; eauto.\n  Qed.\n  \n  Ltac solve_concrete_perm_merges :=\n    repeat \n      match goal with\n      | [ |- context [true || _]  ] => rewrite orb_true_l\n      | [ |- context [_ || true]  ] => rewrite orb_true_r\n      | [ |- context [$0 $k++ _] ] => rewrite merge_perms_left_identity\n      | [ |- context [_ $k++ $0] ] => rewrite merge_perms_right_identity\n      | [ |- context [_ $k++ _]  ] => erewrite reduce_merge_perms by (clean_map_lookups; eauto)\n      end; trivial.\n\n  Ltac simplify_terms :=\n    unfold RealWorld.msg_honestly_signed\n         , RealWorld.msg_signing_key\n         , RealWorld.msg_to_this_user\n         , RealWorld.msg_destination_user\n         , RealWorld.cipher_signing_key\n         , RealWorld.honest_keyb\n         , RealWorld.cipher_nonce\n         , add_key_perm.\n\n  Ltac assert_lkp ks k tac :=\n    let ev' := fresh \"ev\"\n    in  evar (ev' : option bool);\n        let ev := eval unfold ev' in ev'\n          in (clear ev'\n              ; match ks with\n                | ?ks1 $k++ ?ks2 => assert (ks $? k = ev) by tac\n                | _ => assert (ks $? k = ev) by tac\n                end).\n\n  Ltac bldLkup ks k tac :=\n    match goal with\n    | [ H : ks $? k = ?ans |- _ ] => idtac (* idtac \"done with: \" ks *)\n    | _ => \n      match ks with\n      | ?ks1 $k++ ?ks2 => (* idtac \"splitting: \" ks1 \" and \" ks2; *) bldLkup ks1 k tac; bldLkup ks2 k tac\n      | _ => idtac (* \"will build: \" ks *)\n      end; assert_lkp ks k tac\n    end.\n\n  Ltac prove_lookup :=\n    solve [\n        repeat\n          match goal with\n          | [ |- None = _ ] => reflexivity\n          | [ |- Some _ = _ ] => reflexivity\n          | [ |- $0 $? _ = _ ] => rewrite lookup_empty_none\n          | [ |- ?ks $+ (?k1,_) $? ?k2 = _ ] =>\n            (rewrite add_eq_o by trivial)\n            || (rewrite add_neq_o by auto 2)\n            || fail 2\n          | [ |- ?m $? _ = _ ] => progress (unfold m)\n          | [ H1 : ?ks1 $? ?kid = Some _\n                   , H2 : ?ks2 $? ?kid = Some _ |- ?ks1 $k++ ?ks2 $? ?kid = _ ]\n            => rewrite (merge_perms_chooses_greatest _ _ H1 H2) by trivial; unfold greatest_permission; simpl\n          | [ H1 : ?ks1 $? ?kid = Some _\n                   , H2 : ?ks2 $? ?kid = None |- ?ks1 $k++ ?ks2 $? ?kid = _ ]\n            => rewrite (merge_perms_adds_ks1 _ _ _ H1 H2) by trivial\n          | [ H1 : ?ks1 $? ?kid = None\n                   , H2 : ?ks2 $? ?kid = Some _ |- ?ks1 $k++ ?ks2 $? ?kid = _ ]\n            => rewrite (merge_perms_adds_ks2 _ _ _ H1 H2) by trivial\n          | [ H1 : ?ks1 $? ?kid = None\n                   , H2 : ?ks2 $? ?kid = None |- ?ks1 $k++ ?ks2 $? ?kid = _ ]\n            => rewrite (merge_perms_adds_no_new_perms _ _ _ H1 H2) by trivial\n          | [ H : ?ks1 $? ?kid = _ |- ?ks1 $k++ ?ks2 $? ?kid = _ ] =>\n            assert_lkp ks2 kid prove_lookup\n          | [ H : ?ks2 $? ?kid = _ |- ?ks1 $k++ ?ks2 $? ?kid = _ ] =>\n            assert_lkp ks1 kid prove_lookup\n          | [ |- ?ks1 $k++ ?ks2 $? ?kid = _ ] =>\n            assert_lkp ks1 kid prove_lookup\n            ; assert_lkp ks2 kid prove_lookup\n          end\n      ].\n\n  Ltac solve_merges :=\n    repeat\n      match goal with\n      | [ |- context [true || _]  ] => rewrite orb_true_l\n      | [ |- context [_ || true]  ] => rewrite orb_true_r\n      | [ |- context [ _ $k++ $0 ] ] => rewrite merge_perms_right_identity\n      | [ |- context [ $0 $k++ _ ] ] => rewrite merge_perms_left_identity\n      | [ RW : ?ks $? ?k = _ |- context [ ?ks $? ?k ] ] => rewrite RW\n      | [ |- context [ ?ks $? ?k ] ] => (* idtac \"building: \" ks; *) bldLkup ks k prove_lookup\n      end; trivial.\n\n  Lemma reduce_merge_perms_r :\n    forall perms1 perms2 kid p2,\n      perms1 $? kid = None\n      -> perms1 $k++ (perms2 $+ (kid,p2)) = perms1 $+ (kid,p2) $k++ (perms2 $- kid).\n  Proof.\n    intros.\n    eapply map_eq_Equal; unfold Equal; intros.\n    cases (perms1 $? y);\n      cases (perms2 $? y);\n      destruct (kid ==n y); subst;\n        clean_map_lookups.\n\n    - erewrite !merge_perms_chooses_greatest; try reflexivity; clean_map_lookups; eauto.\n\n    - erewrite merge_perms_adds_ks1 with (ks1 := perms1) (ks2 := perms2 $+ (kid, p2)); eauto.\n      erewrite merge_perms_adds_ks1 with (ks1 := perms1 $+ (kid, p2)) (ks2 := perms2 $- kid); eauto.\n\n    - erewrite merge_perms_adds_ks2 with (ks1 := perms1) (ks2 := perms2 $+ (y, p2)); eauto.\n      erewrite merge_perms_adds_ks1 with (ks1 := perms1 $+ (y, p2)) (ks2 := perms2 $- y); eauto.\n\n    - erewrite merge_perms_adds_ks2 with (ks1 := perms1) (ks2 := perms2 $+ (kid, p2) ); eauto.\n      erewrite merge_perms_adds_ks2 with (ks1 := perms1 $+ (kid, p2)) (ks2 := perms2 $- kid); eauto.\n\n    - erewrite merge_perms_adds_ks2 with (ks1 := perms1); eauto; clean_map_lookups; try reflexivity.\n      erewrite merge_perms_adds_ks1 with (ks1 := perms1 $+ (y, p2)) (ks2 := perms2 $- y); eauto.\n\n    - rewrite !merge_perms_adds_no_new_perms; eauto.\n\n  Qed.\n\n  Lemma reduce_merge_perms_both :\n    forall perms1 perms2 kid p1 p2,\n      perms1 $? kid = Some p1\n      -> perms1 $k++ (perms2 $+ (kid,p2)) = perms1 $+ (kid,greatest_permission p1 p2) $k++ (perms2 $- kid).\n  Proof.\n    intros.\n    eapply map_eq_Equal; unfold Equal; intros.\n    cases (perms1 $? y);\n      cases (perms2 $? y);\n      destruct (kid ==n y); subst;\n        clean_map_lookups.\n\n    - erewrite merge_perms_chooses_greatest; eauto; clean_map_lookups; try reflexivity.\n      erewrite merge_perms_adds_ks1 with (ks1 := perms1 $+ (y, greatest_permission b p2)) (ks2 := perms2 $- y); eauto.\n\n    - erewrite !merge_perms_chooses_greatest; try reflexivity; clean_map_lookups; trivial.\n\n    - erewrite merge_perms_chooses_greatest; eauto; clean_map_lookups; try reflexivity.\n      erewrite merge_perms_adds_ks1 with (ks1 := perms1 $+ (y, greatest_permission b p2)) (ks2 := perms2 $- y); eauto.\n\n    - erewrite merge_perms_adds_ks1 with (ks1 := perms1) (ks2 := perms2 $+ (kid, p2)); eauto.\n      erewrite merge_perms_adds_ks1 with (ks1 := perms1 $+ (kid, greatest_permission p1 p2)) (ks2 := perms2 $- kid); eauto.\n\n    - erewrite merge_perms_adds_ks2 with (ks1 := perms1) (ks2 := perms2 $+ (kid, p2)); eauto.\n      erewrite merge_perms_adds_ks2 with (ks1 := perms1 $+ (kid, greatest_permission p1 p2)) (ks2 := perms2 $- kid); eauto.\n\n    - rewrite !merge_perms_adds_no_new_perms; eauto.\n\n  Qed.\n\n  Ltac xx := clean_map_lookups;\n             try match goal with\n                 | [ |- $0 $? _ = _ ] => rewrite lookup_empty_none\n                 end;\n             eauto.\n\n  Ltac find_merge_rewrite ks1 ks2 :=\n    match ks1 with\n    | ?ks1' $k++ ?ks2' =>\n      find_merge_rewrite ks1' ks2'\n    | _ => match ks2 with\n          | ?ks $+ (?k,?p) =>\n            assert_lkp ks1 k xx\n            ; match goal with\n              | [ H : ks1 $? k = ?opt |- _ ] =>\n                match opt with\n                | Some ?p' =>\n                  rewrite reduce_merge_perms_both with (perms1 := ks1) (perms2 := ks) (kid := k) (p1 := p') (p2 := p)\n                | None =>\n                  rewrite reduce_merge_perms_r with (perms1 := ks1) (perms2 := ks) (kid := k) (p2 := p)\n                end\n              end\n          end\n    end.\n\n  Lemma remove_empty :\n    forall k V, (@empty V) $- k = $0.\n  Proof.\n    intros.\n    eapply map_eq_Equal; unfold Equal; intros; eauto.\n  Qed.\n\n  Ltac elim_removes1 :=\n    (rewrite !map_add_remove_eq by trivial)\n    || (rewrite !map_add_remove_neq by eauto)\n    || (rewrite !remove_empty).\n\n  Ltac elim_removes := repeat elim_removes.\n\n  Ltac reduce_merges :=\n    repeat\n      match goal with\n      | [ |- context [true || _]  ] => rewrite orb_true_l\n      | [ |- context [_ || true]  ] => rewrite orb_true_r\n      | [ |- context [ _ $k++ $0 ] ] => rewrite merge_perms_right_identity\n      | [ |- context [ $0 $k++ _ ] ] => rewrite merge_perms_left_identity\n      | [ |- context [ _ $- _ ]] => elim_removes1\n      | [ |- context [ ?ks1 $k++ ?ks2 ]] =>\n        find_merge_rewrite ks1 ks2\n      | [ RW : ?ks $? ?k = _ |- context [ ?ks $? ?k ] ] => rewrite RW\n      end; trivial.\n\n  Ltac has_key ks k :=\n    match ks with\n    | context [ _ $+ (k,_) ] => idtac\n    end.\n  \n  Ltac solve_merges1 :=\n    match goal with\n    | [ H : Some _ = Some _ |- _ ] => injection H; subst\n    | [ H : Some _ = None |- _ ] => discriminate H\n    | [ H : None = Some _ |- _ ] => discriminate H\n    | [ H : findKeysMessage _ $? _ = _ |- _ ] => progress (simpl in H)\n    | [ H : ?ks $? ?k = _ |- _ ] =>\n      progress (\n          repeat (\n              (rewrite add_eq_o in H by trivial)\n              || (rewrite add_neq_o in H by congruence)\n              || (rewrite lookup_empty_none in H by congruence)\n            )\n        )\n    | [ H : _ $+ (?k1,_) $? ?k2 = _ |- _ ] =>\n      destruct (k1 ==n k2); subst\n    | [ H : _ $k++ _ $? _ = None  |- _ ] =>\n      apply merge_perms_no_disappear_perms in H\n      ; destruct H\n    | [ H : _ $k++ _ $? ?kid = Some _  |- _ ] =>\n      apply merge_perms_split in H\n      ; destruct H\n    | [ |- context [ ?kss1 $k++ ?kss2 $? ?ky ] ] =>\n      has_key kss1 ky; has_key kss2 ky\n      ; erewrite merge_perms_chooses_greatest\n          with (ks1 := kss1) (ks2 := kss2) (k := ky) (k' := ky)\n    | [ |- context [ ?kss1 $k++ ?kss2 $? ?ky ] ] =>\n      has_key kss1 ky\n      ; erewrite merge_perms_adds_ks1\n          with (ks1 := kss1) (ks2 := kss2) (k := ky)\n      ; try reflexivity\n    | [ |- context [ ?kss1 $k++ ?kss2 $? ?ky ] ] =>\n      has_key kss2 ky\n      ; erewrite merge_perms_adds_ks2\n          with (ks1 := kss1) (ks2 := kss2) (k := ky)\n      ; try reflexivity\n    | [ |- context [ ?kss1 $k++ ?kss2 $? ?ky ] ] =>\n      erewrite merge_perms_adds_no_new_perms\n        with (ks1 := kss1) (ks2 := kss2) (k := ky)\n    | [ |- ?ks $? ?k = _ ] =>\n      progress (\n          repeat (\n              (rewrite add_eq_o by trivial)\n              || (rewrite add_neq_o by congruence)\n              || (rewrite lookup_empty_none by congruence)\n            )\n        )\n    | [ |- _ = _ ] => (progress simpl) || reflexivity\n    end.\n\n  Ltac solve_honest_actions_safe1 :=\n    solve_merges1 ||\n    match goal with\n    | [ H : _ = {| RealWorld.users := _;\n                   RealWorld.adversary := _;\n                   RealWorld.all_ciphers := _;\n                   RealWorld.all_keys := _ |} |- _ ] => invert H\n\n    | [ |- honest_cmds_safe _ ] => unfold honest_cmds_safe; intros; simpl in *\n    | [ |- next_cmd_safe _ _ _ _ _ _ ] => unfold next_cmd_safe; intros\n    | [ H : _ $+ (?id1,_) $? ?id2 = _ |- _ ] => is_var id2; destruct (id1 ==n id2); subst; clean_map_lookups\n    | [ H : nextAction _ _ |- _ ] => invert H\n\n    | [ H : mkKeys _ $? _ = _ |- _ ] => unfold mkKeys in H; simpl in H\n    | [ |- context [ RealWorld.findUserKeys ?usrs ] ] => canonicalize_map usrs\n    | [ |- context [ RealWorld.findUserKeys _ ] ] =>\n      rewrite !findUserKeys_add_reduce, findUserKeys_empty_is_empty by eauto\n    | [ H : RealWorld.findKeysMessage _ $? _ = _ |- _ ] => progress (simpl in H)\n    | [ |- (_ -> _) ] => intros\n    | [ |- context [ _ $+ (_,_) $? _ ] ] => progress clean_map_lookups\n    | [ |- RealWorld.msg_pattern_safe _ _ ] => econstructor\n    | [ |- RealWorld.honest_key _ _ ] => econstructor\n    (* | [ |- context [_ $k++ _ ] ] => progress reduce_merges *)\n    (* | [ |- context [_ $k++ _ $? _ ] ] => progress solve_merges *)\n    | [ |- context [ ?m $? _ ] ] => unfold m\n    | [ |- Forall _ _ ] => econstructor\n    | [ |- exists x y, (_ /\\ _)] => (do 2 eexists); repeat simple apply conj; eauto 2\n    | [ |- _ /\\ _ ] => repeat simple apply conj\n    | [ |- ~ List.In _ _ ] => progress simpl\n    | [ |- ~ (_ \\/ _) ] => unfold not; intros; split_ors; subst; try contradiction\n    | [ H : (_,_) = (_,_) |- _ ] => invert H\n    end.\n\n  Ltac solve_honest_actions_safe :=\n    repeat (solve_honest_actions_safe1 || (progress simplify_terms) (* ; simpl; cbn *)).\n\n  Ltac solve_labels_align :=\n    (do 3 eexists); repeat (simple apply conj);\n    [ solve [ eauto ]\n    | indexedIdealStep; simpl\n    | subst; repeat solve_action_matches1; clean_map_lookups; ChMaps.ChMap.clean_map_lookups\n    ]; eauto; simpl; eauto.\n\nEnd SimulationAutomation.\n\nImport SimulationAutomation Sets.\nModule Foo <: EMPTY.\nEnd Foo.\nModule Import SN := SetNotations(Foo).\n\nLtac univ_equality1 :=\n  match goal with\n  | [ |- _ = _ ] => reflexivity\n  | [ |- _ /\\ _ ] => repeat simple apply conj\n  | [ |- (_,_) = (_,_) ] => rewrite pair_equal_spec\n  | [ |- {| RealWorld.users := _ |} = _ ] => eapply real_univ_eq_fields_eq\n  | [ |- {| IdealWorld.users := _ |} = _ ] => eapply ideal_univ_eq_fields_eq\n  end\n  || ( progress m_equal )\n  || ( progress ChMaps.m_equal ).\n\nLtac univ_equality := progress (repeat univ_equality1).\n\nLtac sets0 := Sets.sets ltac:(simpl in *\n                              ; intuition (subst; auto; try congruence; try univ_equality; try lia)).\nLtac sets' :=\n  propositional;\n  try match goal with\n      | [ |- @eq (?T -> Prop) _ _ ] =>\n        change (T -> Prop) with (set T)\n      end;\n  try match goal with\n      | [ |- @eq (set _) _ _ ] =>\n        let x := fresh \"x\" in\n        apply sets_equal; intro x;\n        repeat match goal with\n               | [ H : @eq (set _) _ _ |- _ ] => apply (f_equal (fun f => f x)) in H;\n                                               apply eq_iff in H\n               end\n      end; sets0;\n  try match goal with\n      | [ H : @eq (set ?T) _ _, x : ?T |- _ ] =>\n        repeat match goal with\n               | [ H : @eq (set T) _ _ |- _ ] => apply (f_equal (fun f => f x)) in H;\n                                               apply eq_iff in H\n               end;\n        solve [ sets0 ]\n      end.\n\nTactic Notation \"sets\" := sets'.\n\nModule SetLemmas.\n  Lemma setminus_empty_subtr : forall {A} (s : set A),\n      s \\setminus {} = s.\n  Proof. sets. Qed.\n\n  Lemma setminus_empty_minu : forall {A} (s : set A),\n      {} \\setminus s = {}.\n  Proof. sets. Qed.\n\n  Lemma setminus_self : forall {A} (s : set A),\n      s \\setminus s = {}.\n  Proof. sets. Qed.\n\n  Lemma setminus_other : forall {A} (s1 s2 : set A),\n      s1 \\cap s2 = {} -> s1 \\setminus s2 = s1.\n  Proof. sets. Qed.\n\n  Lemma setminus_distr_subtr : forall {A} (s1 s2 s3 : set A),\n      (s1 \\cup s2) \\setminus s3 = (s1 \\setminus s3) \\cup (s2 \\setminus s3).\n  Proof. sets. Qed.\n\n  Lemma setminus_distr_minu : forall {A} (s1 s2 s3 : set A),\n      s1 \\setminus (s2 \\cup s3) = (s1 \\setminus s2) \\cap (s1 \\setminus s3).\n  Proof. sets. Qed.\n\n  Lemma union_self : forall {A} (s : set A),\n      s \\cup s = s.\n  Proof. sets. Qed.\n\n  Lemma  union_self_thru : forall {A} (s1 s2 : set A), s1 \\cup (s1 \\cup s2) = s1 \\cup s2.\n  Proof. sets. Qed.\n\n  Lemma union_empty_r : forall {A} (s : set A),\n      s \\cup {} = s.\n  Proof. sets. Qed.\n\n  Lemma union_empty_l : forall {A} (s : set A),\n      {} \\cup s = s.\n  Proof. sets. Qed.\n\n  Lemma intersect_self : forall {A} (s : set A),\n      s \\cap s = s.\n  Proof. sets. Qed.\n\n  Lemma intersect_empty_r : forall {A} (s : set A),\n      s \\cap {} = {}.\n  Proof. sets. Qed.\n\n  Lemma intersect_empty_l : forall {A} (s : set A),\n      {} \\cap s = {}.\n  Proof. sets. Qed.\nEnd SetLemmas.\n\nModule Tacs.\n  Import SetLemmas.\n\n  Ltac simpl_sets1 disj_tac :=\n    match goal with\n    | [|- context[?s' \\cup ?s']] =>\n      rewrite union_self\n        with (s := s')\n    | [|- context[?s1' \\cup (?s1' \\cup ?s2')]] =>\n      rewrite union_self_thru\n        with (s1 := s1') (s2 := s2')\n    | [|- context[?s' \\cup {}]] =>\n      rewrite union_empty_r\n        with (s := s')\n    | [|- context[{} \\cup ?s']] =>\n      rewrite union_empty_l\n        with (s := s')\n    | [|- context[?s' \\cap ?s']] =>\n      rewrite intersect_self\n        with (s := s')\n    | [|- context[?s' \\cap {}]] =>\n      rewrite intersect_empty_r\n        with (s := s')\n    | [|- context[{} \\cap ?s']] =>\n      rewrite intersect_empty_l\n        with (s := s')\n    | [|- context[?s' \\setminus ?s']] =>\n      rewrite setminus_self\n        with (s := s')\n    | [|- context[?s' \\setminus {}]] =>\n      rewrite setminus_empty_subtr\n        with (s := s')\n    | [|- context[{} \\setminus ?s']] =>\n      rewrite setminus_empty_minu\n        with (s := s')\n    | [|- context[(?s1' \\cup ?s2') \\setminus ?s3']] =>\n      rewrite setminus_distr_subtr\n        with (s1 := s1') (s2 := s2') (s3 := s3')\n    | [|- context[?s1' \\setminus (?s2' \\cup ?s3')]] =>\n      rewrite setminus_distr_minu\n        with (s1 := s1') (s2 := s2') (s3 := s3')\n    | [|- context[?s1' \\setminus ?s2']] =>\n      rewrite setminus_other\n        with (s1 := s1') (s2 := s2') by disj_tac\n    end.\n\n  Ltac sets_invert :=\n    repeat match goal with\n           | [H : (_ \\cup _) _ |- _] => invert H\n           | [H : (_ \\cap _) _ |- _] => invert H\n           | [H : [_ | _] _ |- _] => invert H\n           | [H : (_ \\setminus _) _ |- _] => invert H\n           | [H : _ \\in _ |- _] => invert H\n           | [H : (complement _) _ |- _] => invert H\n           | [H : { } _ |- _] => invert H\n           | [H : { _ } _ |- _] => invert H\n           | [H : _ \\/ False |- _ ] => destruct H; [ | contradiction]\n           end.\n\n  Ltac case_lookup H :=\n    match type of H with\n    | ?m $? ?k = Some ?v =>\n      let t := type of v in\n      repeat match m with\n             | context[add ?k' ?v' _ ] =>\n               let t' := type of v'\n               in unify t t'\n                  ; match goal with\n                    | [e : k = k' |- _] => fail 2\n                    | [n : k <> k' |- _] => fail 2\n                    | _ => destruct (k ==n k')\n                    end\n             end\n      ; subst\n      ; simpl in *\n      ; clean_map_lookups\n      ; simpl in *\n    end.\n\n  Lemma map_sym : forall {v} (m : NatMap.t v) k1 k2 v1 v2,\n      k1 <> k2\n      -> m $+ (k1, v1) $+ (k2, v2) = m $+ (k2, v2) $+ (k1, v1).\n  Proof. intros; maps_equal. Qed.\n\n  Ltac reorder_usrs n :=\n    repeat match n with\n           | context[add ?a ?va (add ?b ?vb ?rest)] =>\n             match eval cbv in (Nat.leb a b) with\n               | true =>\n                 rewrite map_sym\n                   with (m := rest) (k1 := b) (k2 := a) (v1 := vb) (v2 := va)\n                   by auto\n             end\n           end.\n\n  Tactic Notation \"simpl_sets\" := repeat (simpl_sets1 ltac:(shelve)).\n  Tactic Notation \"simpl_sets\" tactic(disj_tac) := repeat (simpl_sets1 ltac:(disj_tac)).\n\n  Tactic Notation \"ifnot\" tactic(t) \"at\" int_or_var(lvl) := tryif t then fail lvl else idtac.\n  Tactic Notation \"ifnot\" tactic(t) := ifnot t at 0.\n  Tactic Notation \"concrete\" constr(x) \"at\" int_or_var(lvl) :=\n    (ifnot (is_var x) at lvl); (ifnot (is_evar x) at lvl).\n  Tactic Notation \"concrete\" constr(x) := concrete x at 0.\n  Tactic Notation \"concrete\" \"iuniv\" constr(u) :=\n    match u with\n    | {| IdealWorld.channel_vector := ?cv\n         ; IdealWorld.users := ?usrs |} =>\n      concrete cv; concrete usrs\n    end.\n  Tactic Notation \"concrete\" \"iproc\" constr(p) :=\n    match p with\n    | (IdealWorld.protocol ?p) => concrete p at 1\n    | _ => concrete p at 1\n    end.\n\n  Tactic Notation \"canonicalize\" \"rusers\" :=\n    repeat match goal with\n           | [|- context[{| RealWorld.users := ?usrs\n                           ; RealWorld.adversary := _\n                           ; RealWorld.all_ciphers := _\n                           ; RealWorld.all_keys := _ |}]] =>\n             progress canonicalize_concrete_map usrs\n           end.\n\n  Tactic Notation \"canonicalize\" \"iusers\" :=\n    repeat match goal with\n           | [|- context[{| IdealWorld.channel_vector := _\n                           ; IdealWorld.users := ?usrs |}]] =>\n             progress canonicalize_concrete_map usrs\n           end.\n\n  Tactic Notation \"canonicalize\" \"users\" :=\n    canonicalize rusers; canonicalize iusers.\n\nEnd Tacs.\n\nImport Tacs.\n\nModule Gen.\n  Import\n    SetLemmas.\n\n  #[export] Hint Unfold oneStepClosure oneStepClosure_current oneStepClosure_new : osc.\n\n  Lemma oneStepClosure_grow : forall state (sys : trsys state) (inv1 inv2 : state -> Prop),\n      (forall st st', inv1 st -> sys.(Step) st st' -> inv2 st')\n      -> oneStepClosure sys inv1 (inv1 \\cup inv2).\n  Proof. sets; repeat autounfold with osc in *; propositional; eauto. Qed.\n\n  Lemma msc_step_alt : forall {state} (sys : trsys state) wl wl' inv inv',\n      oneStepClosure_new sys wl wl'\n      -> wl' \\cap (wl \\cup inv) = { }\n      -> multiStepClosure sys ((inv \\cup wl) \\cup wl') wl' inv'\n      -> multiStepClosure sys (inv \\cup wl) wl inv'.\n  Proof.\n    Ltac uf := repeat autounfold with osc in *.\n    intros.\n    apply MscStep with (inv'0 := (wl \\cup wl')).\n    - uf; sets; firstorder.\n    - replace ((inv \\cup wl) \\cup (wl \\cup wl'))\n        with (inv \\cup wl \\cup wl') by sets.\n      replace (((wl \\cup wl') \\setminus (inv \\cup wl)))\n        with wl' by sets.\n      assumption.\n  Qed.\n\n  Lemma in_empty_map_contra : (forall {t} x, Map.In (elt := t) x $0 -> False).\n  Proof. propositional. invert H. invert H0. Qed.\n\n  Lemma incl_empty_empty : (forall {t}, @incl t [] []).\n  Proof. cbv; auto. Qed.\n\n  #[export] Hint Resolve\n       incl_empty_empty : core.\n\n  Ltac concrete_isteps :=\n    match goal with\n    | [H : indexedIdealStep _ _ _ _ |- _ ] =>\n      invert H\n    | [H : (indexedIdealStep _ Silent)^* ?u _ |- _] =>\n      concrete iuniv u; invert H\n    | [H : istepSilent^* ?u _ |- _] =>\n      concrete iuniv u; invert H\n    | [H : istepSilent ?u _ |- _] =>\n      concrete iuniv u; invert H\n    | [H : IdealWorld.lstep_universe ?u _ _ |- _] =>\n      concrete iuniv u; invert H\n    | [H : IdealWorld.lstep_user _ _ (_, ?p, _) _ |- _] =>\n      concrete iproc p; invert H\n    end.\n\n  Ltac simplify :=\n    repeat (unifyTails);\n    repeat match goal with\n           | [ H : True |- _ ] => clear H\n           end;\n    repeat progress (simpl in *; intros; try autorewrite with core in *);\n                     repeat (normalize_set || doSubtract).\n\n  Ltac infer_istep :=\n    match goal with\n    | [H : IdealWorld.lstep_user _ _ (_, ?u.(IdealWorld.protocol), _) _,\n           L : ?m $? ?u_id = Some ?u |- _] =>\n      case_lookup L\n    end.\n\n  Ltac istep := repeat ((repeat concrete_isteps); try infer_istep).\n\n  Ltac incorp :=\n    let rec preconditions acc :=\n        (match goal with\n         | [H : ?P |- _] =>\n           match type of P with\n           | Prop =>\n             match eval hnf in acc with\n             | context[P] => fail 1\n             | _ =>\n               let acc' := eval hnf in (P /\\ acc)\n                 in preconditions acc'\n             end\n           end\n         | _ => acc\n         end)\n    in let rec existentialize p :=\n           (match goal with\n            | [x : ?A |- _] =>\n              match type of A with\n              | Prop => fail 1\n              | _ =>\n                match A with\n                | ((RealWorld.universe _ _) * (IdealWorld.universe _) * bool)%type =>\n                  fail 2\n                | _  =>\n                  match p with\n                  | context[x] =>\n                    match eval pattern x in p with\n                    | ?g _ =>\n                      let p' := (eval hnf in (exists y : A, g y))\n                      in existentialize p'\n                    end\n                  end\n                end\n              end\n            | _ => p\n            end)\n       in let conds := (preconditions True) in\n          match goal with\n          | [|- ?i ?v] =>\n            is_evar i\n            ; let lp := constr:(exists x , conds /\\ x = v) in\n              let p := fresh \"p\" in\n              let p' := fresh \"p'\" in\n              let x := fresh \"x\" in\n              assert (p : lp) by (eexists; intuition eauto)\n              ; destruct p as [x p']\n              ; let lp' := type of p'\n                in clear p'\n                   ; let lp'' := existentialize lp'\n                     in match eval pattern x in lp'' with\n                        | ?f _ =>\n                          clear x\n                          ; let scomp := (eval simpl in [e | (f e)])\n                            in instantiate (1 := (scomp \\cup _))\n                        end\n          end.\n\n  Ltac solve_returns_align1 :=\n    match goal with\n    | [ H : users _ $? _ = Some _ |- _ ] => progress (simpl in H)\n    | [ H1 : _ $? ?u = Some ?ud, H2 : protocol ?ud = Return _ |- _ ] =>\n      progress (\n          repeat (  (rewrite add_eq_o in H1 by trivial)\n                    || (rewrite add_neq_o in H1 by congruence)\n                    || (rewrite lookup_empty_none in H1; discriminate H1)\n                 )\n        )\n    | [ H1 : _ $+ (?u1,_) $? ?u2 = Some ?ud, H2 : protocol ?ud = Return _ |- _ ] =>\n      destruct (u1 ==n u2); subst\n    | [ H1 : Some _ = Some ?ud, H2 : protocol ?ud = Return _ |- _ ] =>\n      injection H1; subst\n    | [ H : _ = Return _ |- _ ] =>\n      discriminate H\n    end.\n\n  Ltac idealUnivSilentStep uid :=\n    eapply IdealWorld.LStepUser with (u_id := uid)\n    ; simpl\n    ; [ solve [ clean_map_lookups; trivial ]\n      | solve [ idealUserSilentStep ]\n      ].\n\n  Ltac step_ideal1 uid :=\n    idtac \"stepping \" uid\n    ; eapply TrcFront\n    ; [ idealUnivSilentStep uid |].\n  \n  Ltac multistep_ideal usrs :=\n    simpl_ideal_users_context;\n    match usrs with\n    | ?us $+ (?uid,_) =>\n      idtac \"multi stepping \" uid\n      ; (repeat step_ideal1 uid)\n      ; multistep_ideal us\n    | _ => eapply TrcRefl\n    end.\n\n  Ltac run_ideal_silent_steps_to_end :=\n    simpl_ideal_users_context;\n    match goal with\n    | [ |- istepSilent ^* {| IdealWorld.users := ?usrs |} ?U ] =>\n      is_evar U\n      ; multistep_ideal usrs\n    end.\n\n  Ltac solve_real_step_stuff1 :=\n    equality1\n    || solve_merges1\n    || match goal with\n      | [ |- RealWorld.keys_mine _ _ ] =>\n        simpl in *; hnf\n      | [ |- ?m $? next_key ?m = None ] =>\n        apply Maps.next_key_not_in\n        ; trivial\n      | [ |- ~ Map.In (next_key ?m) ?m ] =>\n        rewrite not_find_in_iff\n        ; apply Maps.next_key_not_in\n        ; trivial\n      | [ H : _ $+ (?k1,_) $? ?kid = Some _  |- context [ ?kid ] ] =>\n        is_var kid\n        ; destruct (k1 ==n kid); subst; clean_map_lookups\n      | [ |- context [ $0 $? _ ]] =>\n        rewrite lookup_empty_none\n      | [ |- _ $? _ = _ ] =>\n        clean_map_lookups\n      | [ |- _ -> _ ] => intros\n      | [ |- _ ] => ( progress simpl ) || ( progress hnf )\n      end.\n  \n  Ltac solve_indexedRealStep :=\n    repeat (match goal with [ |- exists _ , _ ] => eexists end)\n    ; econstructor; [\n      solve [ simpl; clean_map_lookups; trivial ]\n    | autounfold; unfold RealWorld.build_data_step; simpl;\n      repeat ( match goal with\n               | [ |- RealWorld.step_user _ _ _ _ ] => solve [ eapply RealWorld.StepBindProceed; eauto ]\n               | [ |- RealWorld.step_user _ _ _ _ ] => eapply RealWorld.StepBindRecur; eauto\n               | [ |- RealWorld.step_user _ _ (_,_,?cs,?gks,_,_,_,_,_,_,?cmd) _ ] =>\n                 match cmd with\n                 | RealWorld.SignEncrypt _ _ _ _ =>\n                   eapply RealWorld.StepEncrypt with (c_id := next_key cs)\n                 | RealWorld.Sign _ _ _ =>\n                   eapply RealWorld.StepSign with (c_id := next_key cs)\n                 | RealWorld.GenerateKey _ _ => \n                   eapply RealWorld.StepGenerateKey with (k_id := next_key gks)\n                 | _ => econstructor\n                 end\n               end\n             )\n      ; trivial (* take a first pass to get the simple stuff *)\n      ; repeat (solve_real_step_stuff1; trivial)\n      ; eauto\n\n    | reflexivity ].\n\n  Ltac find_indexed_real_step usrs uid :=\n    match usrs with\n    | ?us $+ (?u,_) =>\n      (unify uid u; solve [ solve_indexedRealStep ])\n      || find_indexed_real_step us uid\n    | $0 =>\n      fail 1\n    end.\n\n  (* note the automation here creates a bunch of extra existentials while \n   * doint the search for available steps.  This creates several nats\n   * that need to be resolved at the end of proofs that use it.  \n   * Should look at fixing this. *)\n  Ltac find_step_or_solve :=\n    simpl in *;\n    match goal with\n    | [ H1 : forall _ _ _, indexedRealStep _ _ ?ru _ -> False\n        , H2 : ?usrs $? _ = Some ?ur\n        , H3 : RealWorld.protocol ?ur = RealWorld.Return _ |- _ ] =>\n\n      ( assert (exists uid lbl ru', indexedRealStep uid lbl ru ru')\n        by (eexists ?[uid]; (do 2 eexists); find_indexed_real_step usrs ?uid)\n        ; split_ex; exfalso; eauto\n      )\n      || ( repeat solve_returns_align1\n          ; ( (do 3 eexists); simpl in *; (repeat equality1) \n              ; subst\n              ; repeat simple apply conj\n              ; [ solve [ run_ideal_silent_steps_to_end ]\n                | solve [ simpl; clean_map_lookups; trivial ]\n                | reflexivity\n                | reflexivity\n                ]\n        ))\n    end.\n\n  Ltac invert_commutes :=\n    match goal with\n    | [ H : commutes (RealWorld.Recv _) _ |- _ ] => invert H\n    | [ H : commutes (RealWorld.Send _ _) _ |- _ ] => invert H\n    | [ H : commutes _ _ |- _ ] => fail 2\n    end.\n\n  Ltac non_commuter uid :=\n    exists uid; eexists; repeat simple apply conj; [\n        congruence\n      | solve [ autounfold; simpl; clean_map_lookups; trivial ]\n      | solve [ intros; simpl; trivial] ].\n\n  Ltac non_commuter_all uids :=\n    match uids with\n    | [] => fail 2\n    | (?uid :: ?uids') => (non_commuter uid) || (non_commuter_all uids')\n    end.\n\n  Ltac non_commuters := non_commuter_all [0;1;2;3;4;5].\n\n  Ltac discharge_nextStep2 :=\n    repeat \n      match goal with\n      | [ H : (forall _ _, ~ indexedRealStep ?uid _ ?ru _)\n            \\/ (exists _ _, ?uid <> _ /\\ _ $? _ = Some _ /\\ (forall _, ?sums $? _ = Some _ -> commutes ?proto _ -> False))\n          |- _ ] => split_ex; exfalso; destruct H\n      | [ H : (forall _ _, ~ indexedRealStep ?uid _ ?ru _), ARG : indexedRealStep ?uid _ ?ru _ |- _ ] =>\n        eapply H in ARG; contradiction\n      | [ H : summarize_univ ?ru ?sums, \n         ARG : (forall _, ?sums $? ?uid = Some _ -> commutes _ _),\n         USR :  _ $? ?uid = Some _\n          |- _ ] =>\n        specialize (H _ _ {| sending_to := { } |} USR); split_ex\n      | [ H : ?sums $? ?uid = Some _,\n          COMM : (forall _, ?sums $? ?uid = Some _ -> commutes _ _)\n          |- _ ] =>\n        specialize (COMM _ H); simpl in COMM; contradiction\n      end.\n\n  Lemma upper_users_cant_step_rewrite :\n    forall A B (U : RealWorld.universe A B) uid,\n      (forall uid' ud' U', U.(RealWorld.users) $? uid' = Some ud' -> uid' > uid -> ~ indexedRealStep uid' Silent U U')\n      -> (forall uid' U', uid' > uid -> ~ indexedRealStep uid' Silent U U').\n  Proof.\n    intros * H * INEQ.\n    unfold not; intros IRS.\n    invert IRS; eauto.\n    eapply H; eauto.\n  Qed.\n\n  Lemma sstep_inv_silent :\n    forall A B (U U' : RealWorld.universe A B) uid U__i b st',\n      indexedRealStep uid Silent U U'\n      -> (forall uid' U', uid' > uid -> ~ indexedRealStep uid' Silent U U')\n      -> stepSS (U,U__i,b) st'\n      -> exists U__r,\n          indexedModelStep uid (U,U__i,b) (U__r,U__i,b)\n          /\\ indexedRealStep uid Silent U U__r\n          /\\ st' = (U__r,U__i,b).\n  Proof.\n    intros.\n    invert H1; repeat equality1.\n    destruct (u_id ==n uid); subst.\n    - invert H2; clear_mislabeled_steps; clean_map_lookups.\n      invert H5; clear_mislabeled_steps.\n      eexists; eauto 8.\n    - invert H2.\n      + invert H5; try solve [ clear_mislabeled_steps ].\n        apply not_eq in n; split_ors.\n        * assert (uid > u_id) as GT by lia.\n          specialize (H4 _ U' GT); contradiction.\n        * assert (u_id > uid) as GT by lia.\n          specialize (H0 _ ru' GT); contradiction.\n      + eapply H3 in H; contradiction.\n  Qed.\n\n  Lemma sstep_inv_labeled :\n    forall A B st st' ru,\n      (forall uid U', ~ @indexedRealStep A B uid Silent ru U')\n      -> @stepSS A B st st'\n      -> labels_align st\n      -> forall ru' iu iu' b b',\n          st = (ru,iu,b)\n          -> st' = (ru',iu',b')\n          -> b = b'\n            /\\ (exists uid iu0 ra ia, \n                  indexedRealStep uid (Action ra) ru ru'\n                  /\\ (indexedIdealStep uid Silent) ^* iu iu0\n                  /\\ indexedIdealStep uid (Action ia) iu0 iu'\n                  /\\ action_matches (RealWorld.all_ciphers ru) (RealWorld.all_keys ru) (uid,ra) ia).\n  Proof.\n    intros; subst.\n    invert H0; clear_mislabeled_steps.\n    repeat equality1.\n\n    invert H2.\n    specialize (H u_id U'); simpl in *; contradiction.\n\n    invert H5; try contradiction; eauto 12.\n    clear_mislabeled_steps.\n  Qed.\n\n  Ltac rstep :=\n    repeat (autounfold\n            ; equality1\n              || (progress ( simpl in * ))\n              || discriminate\n              || match goal with\n                | [H : action_matches _ _ _ _ |- _] =>\n                  invert H\n                | [ H : forall _ _ _, _ -> _ -> _ -> _ <-> _ |- _ ] => clear H\n                | [ H : forall _ _ _ _, _ -> _ -> _ -> _ -> _ <-> _ |- _ ] => clear H\n                | [ H : (forall _ _ _, indexedRealStep _ _ ?ru _ -> exists _ _ _, (indexedIdealStep _ _) ^* ?iu _ /\\ _) |- _ ] =>\n                  clear H\n                | [ H : summarize_univ _ _ |- _ ] => clear H\n\n                | [H : indexedRealStep _ _ _ _ |- _ ] =>\n                  invert H\n                | [H : RealWorld.step_universe _ ?u _ _ |- _] =>\n                  concrete u; churn\n                | [H : RealWorld.step_user _ None _ _ |- _] =>\n                  invert H\n                | [H : RealWorld.step_user _ _ ?u _ |- _] =>\n                  concrete u; churn\n                end).\n\n  Ltac prove_gt_pred :=\n    intros\n    ; simpl in *\n    ; repeat \n        match goal with\n        | [ H : context [ _ $+ (_,_) $- _ ] |- _ ] =>\n          repeat (\n              (rewrite map_add_remove_neq in H by congruence)\n              || (rewrite map_add_remove_eq in H by trivial)\n              || (rewrite remove_empty in H)\n            )\n        | [ H : _ $+ (?uid,_) $? ?uid' = Some _ |- _ ] =>\n          destruct (uid ==n uid'); subst; clean_map_lookups; try lia\n        | [ |- ~ indexedRealStep _ _ _ _ ] => unfold not; intros; rstep\n        end.\n\n  Ltac assert_gt_pred U uid :=\n    let P := fresh \"P\"\n    in assert (forall uid' ud' U', U.(RealWorld.users) $? uid' = Some ud'\n                              -> uid' > uid\n                              -> ~ indexedRealStep uid' Silent U U') as P by prove_gt_pred\n       ; pose proof (upper_users_cant_step_rewrite P); clear P\n  .\n\n  Ltac assert_no_silents U :=\n    let P := fresh \"P\"\n    in assert (forall uid U', ~ indexedRealStep uid Silent U U') as P by prove_gt_pred\n  .\n\n  Ltac find_silent U us :=\n    let MAX := fresh \"MEQ\"\n    in  remember (O.max_elt us) eqn:MAX\n        ; unfold O.max_elt in MAX\n        ; simpl in MAX\n        ; match type of MAX with\n          | _ = Some (?uid,?u) =>\n            ( ( assert (exists U', indexedRealStep uid Silent U U') by solve_indexedRealStep\n                ; assert_gt_pred U uid)\n              || find_silent U (us $- uid)\n            ) || assert_no_silents U\n          end\n        ; subst; split_ex\n  .\n\n  Ltac inv_stepSS1 :=\n    match goal with\n    | [ STEP : stepSS (?U,_,_) _\n      , IRS : indexedRealStep ?uid Silent ?U _\n      , P : (forall _ _, _ > ?uid -> _)\n        |- _ ] =>\n\n      pose proof (sstep_inv_silent IRS P STEP)\n      ; clear STEP IRS P\n      ; split_ex\n      ; subst\n\n    | [ STEP : stepSS (?ru,?iu,?b) _\n      , P : (forall _ _, ~ indexedRealStep _ Silent _  _)\n        |- _ ] =>\n\n      progress ( unfold not in P )\n\n    | [ STEP : stepSS (?ru,?iu,?b) (_,_,_)\n      , P : (forall _ _, indexedRealStep _ Silent _ _ -> False)\n        |- _ ] =>\n\n      concrete ru\n      ; match goal with\n        | [ LA : labels_align (?ru,?iu,?b) |- _ ] =>\n          pose proof (sstep_inv_labeled P STEP LA eq_refl eq_refl )\n          ; split_ex; subst\n          ; clear STEP P LA\n\n        | _ =>\n          idtac \"proving alignment 4\"\n          ; assert (labels_align (ru,iu,b)) by ((repeat prove_alignment1); eauto)\n        end\n\n    | [ STEP : stepSS ?st ?st'\n      , P : (forall _ _, indexedRealStep _ Silent _ _ -> False)\n        |- _ ] =>\n\n      match st with\n      | (_,_,_) => idtac\n      | _ => destruct st as [[?ru ?iu] ?b]\n      end\n      ; match st' with\n        | (_,_,_) => idtac\n        | _ => destruct st' as [[?ru' ?iu'] ?b']\n        end\n\n    | [ H : stepSS (?U,_,_) _ |- _ ] =>\n      match U with\n      | {| RealWorld.users := ?usrs |} =>\n        find_silent U usrs\n      end\n        \n    | [ IMS : indexedModelStep ?uid (?U,_,_) _\n      , IRS : indexedRealStep ?uid _ ?U _ \n        |- _ ] => clear IMS\n\n    end.\n\n  Ltac step_model1 :=\n    match goal with\n    | [H : Step _ _ _ |- _] =>\n      simpl in H\n    | [H : exists _, _ |- _] =>\n      destruct H; split_ex; subst (* invert H; propositional; subst *)\n    | [ H : nextAction _ _ |- _ ] =>\n      progress (simpl in H)\n    | [ H : nextAction ?cmd1 ?cmd2 |- _ ] =>\n      is_var cmd2;\n      match cmd1 with (* doubt this is general enough *)\n      | (RealWorld.protocol ?ud) => concrete ud || fail 1\n      | _ => concrete cmd1\n      end; invert H\n\n    | [ H : O.max_elt _ = Some _ |- _ ] => \n      unfold O.max_elt in H; simpl in H; invert H\n    | [H : In _ $0 |- _] =>\n      apply in_empty_map_contra in H; contradiction\n      (* invert H *)\n    | [H : Raw.PX.MapsTo _ _ $0 |- _] =>\n      invert H\n    | [H : (existT _ _ _) = (existT _ _ _) |- _] =>\n      invert H\n\n    | [ S : step ?st ?st' |- _ ] =>\n      concrete st; is_var st';\n      match st' with\n      | (_,_,_) => fail 2\n      | (?f,_) => destruct f as [?ru ?iu]\n      | _ => destruct st' as [[?ru ?iu] ?b]\n      end\n    | [ S : step ?st _ |- _ ] =>\n      concrete st;\n      match goal with\n      | [ LA : labels_align ?st |- _ ] =>\n        eapply label_align_step_split in S; (reflexivity || eauto 2); split_ex; split_ors; split_ex; subst\n      | _ =>\n        idtac \"proving alignment 1\"; assert (labels_align st) by ((repeat prove_alignment1); eauto)\n      end\n    | [ S : stepC ?st _ |- _ ] =>\n      concrete st; invert S\n\n    | [ H : nextStep _ _ _ |- _ ] => invert H\n    | [ S : indexedModelStep ?uid ?st _ |- _ ] =>\n      concrete st;\n      match goal with\n      | [ LA : labels_align ?st |- _ ] =>\n        eapply label_align_indexedModelStep_split in S; (reflexivity || eauto 2); split_ex; split_ors; split_ex; subst\n      | _ =>\n        idtac \"proving alignment 2\"; assert (labels_align st) by ((repeat prove_alignment1); eauto)\n      end\n    | [ H : (forall _ _, ~ indexedRealStep ?uid _ ?ru _)\n          \\/ (exists _ _, ?uid <> _ /\\ _ $? _ = Some _ /\\ (forall _, ?sums $? _ = Some _ -> commutes ?proto _ -> False))\n      , S : summarize_univ ?ru ?sums\n        |- _ ] =>\n      ( (assert (exists lbl ru', indexedRealStep uid lbl ru ru') by solve_indexedRealStep )\n      ; (assert (exists uid2 ud2, uid <> uid2\n                           /\\ ru.(RealWorld.users) $? uid2 = Some ud2\n                           /\\ (forall s, sums $? uid2 = Some s -> commutes proto s)) by non_commuters ))\n      ; discharge_nextStep2 (* clear this goal since the preconditions weren't satisfied *)\n    end.\n\n  Ltac gen_val_typ t :=\n    match t with\n    | Nat    => constr:(0)\n    | Bool   => constr:(true)\n    | Unit   => constr:(tt)\n    | Access => constr:((0,false))\n    | (TPair ?t1 ?t2) =>\n      let v1 := gen_val_typ t1 in\n      let v2 := gen_val_typ t2\n      in constr:((v1,v2))\n                  \n    end.\n\n  Ltac gen_msg t :=\n    match t with\n    | Access => let v := gen_val_typ Access in constr:(message.Permission v)\n    | Nat    => let v := gen_val_typ Nat in constr:(message.Content v)\n    | (TPair ?t1 ?t2) =>\n      let m1 := gen_msg t1 in\n      let m2 := gen_msg t2 in\n      constr:(message.MsgPair m1 m2)\n    end.\n\n  Ltac gen_crypto t :=\n    let m := gen_msg t in constr:(Content m).\n\n  Ltac gen_val_cmd_typ ct :=\n    match ct with\n    | Base ?t    => gen_val_typ t\n    | Message ?t => gen_msg t\n    | Crypto ?t  => gen_crypto t\n    | UPair ?t1 ?t2 =>\n      let v1 := gen_val_cmd_typ t1 in\n      let v2 := gen_val_cmd_typ t2 in constr:((v1,v2))\n    end.\n\n  (* We have to be careful here when inverting the model checking terms.  If we run injection\n   * on universes which only differ in their protocols, it seems that this fact gets erased.\n   * I am not entirely sure why this happens.  For this reason, we carefully do the inversions\n   * here manually rather than running injection.\n   * \n   *)\n  Ltac univ_equality_discr :=\n    discriminate ||\n    match goal with\n    | [ H : RealWorld.Bind _ _ = RealWorld.Bind _ _ |- _ ] =>\n      apply invert_bind_eq in H; split_ex\n    | [ H1 : ?x = ?y1, H2 : ?x = ?y2 |- _ ] =>\n      rewrite H1 in H2\n      ; clear H1\n    | [ H1 : ?x = ?y1, H2 : ?y2 = ?x |- _ ] =>\n      rewrite H1 in H2\n      ; clear H1\n    | [ H : (?x1,?y1) = (?x2,?y2) |- _ ] =>\n      apply tuple_eq_inv in H; split_ex; subst\n    | [ H : {| users := _ |} = {| users := _ |} |- _ ] =>\n      apply split_real_univ_fields in H; split_ex\n    | [ H : Some _ = Some _ |- _ ] =>\n      apply some_eq_inv in H; split_ex; subst\n    | [ H : {| key_heap := _ |} = {| key_heap := _ |} |- _ ] =>\n      apply split_real_user_data_fields in H; split_ex; subst\n    | [ H : _ $+ (_,_) = _ |- _ ] =>\n      apply map_eq_fields_eq in H; clean_map_lookups\n    | [ H : << ?t >> -> _ = _ |- _ ] =>\n      let vt := gen_val_cmd_typ t\n      in specialize (H vt)\n    end.\n\n  Ltac tidy :=\n    autounfold\n    ; intros\n    ; sets_invert\n    ; propositional\n    ; subst\n    ; clean_map_lookups\n    ; subst\n    ; idtac \"discriminating univ - tidy\"\n    ; repeat (\n          univ_equality_discr\n          (* equality has to run after univ equality discrimination because equality1 uses injeection\n           * which isn't always safe to use on universes.  See comment on univ_equality_discr \n           *)\n          || equality1   \n          || inv_stepSS1\n          || step_model1\n        )\n    ; idtac \"discriminating univ - tidy done\"\n  .\n\n  Ltac s := simpl in *.\n\n  Ltac cleanup :=\n    repeat (\n        equality1\n        || match goal with\n          | [ H : True |- _ ] => clear H\n          | [ H : ?X = ?X |- _ ] => clear H\n          | [ H : ?x <> ?y |- _ ] =>\n            match type of x with\n            | nat => concrete x; concrete y; clear H\n            end\n          | [ H : ?x = ?y -> False |- _ ] =>\n            match type of x with\n            | nat => concrete x; concrete y; clear H\n            end\n          | [ H: RealWorld.keys_mine _ $0 |- _ ] => clear H\n          | [ H : _ $+ (?k1,_) $? ?k2 = None |- _ ] =>\n              (rewrite add_neq_o in H by solve_simple_ineq)\n            || (rewrite add_eq_o in H by trivial)\n            || (destruct (k1 ==n k2); subst)\n          | [ H : context [ ChMaps.ChannelType.eq _ _ ] |- _ ] => unfold ChMaps.ChannelType.eq in H\n          | [ H : _ #+ (?k1,_) #? ?k2 = None |- _ ] =>\n              (rewrite ChMaps.ChMap.F.add_neq_o in H by solve_simple_ineq)\n            || (rewrite ChMaps.ChMap.F.add_eq_o in H by trivial)\n            || (destruct (ChMaps.ChMap.F.eq_dec k1 k2); subst)\n\n          | [ H : context [ _ #+ (?k,_) #? ?k ] |- _ ] =>\n            is_not_evar k\n            ; rewrite ChMaps.ChMap.F.add_eq_o in H by trivial\n          | [ H : context [ _ #+ (?k1,_) #? ?k2 ] |- _ ] =>\n            is_not_evar k1\n            ; is_not_evar k2\n            ; rewrite ChMaps.ChMap.F.add_neq_o in H by congruence\n          | [ H : mkKeys _ $? _ = _ |- _ ] => unfold mkKeys in H; simpl in H\n          | [ H : RealWorld.msg_accepted_by_pattern _ _ _ _ _ |- _ ] => clear H\n          | [ H : ~ RealWorld.msg_accepted_by_pattern _ _ _ _ _ |- _ ] => clear H\n          | [ H : RealWorld.msg_accepted_by_pattern _ _ _ _ _ -> False |- _ ] => clear H\n          | [ H : IdealWorld.screen_msg _ _ |- _ ] => invert H\n          | [ H : IdealWorld.permission_subset _ _ |- _ ] => invert H\n          | [ H : IdealWorld.check_perm _ _ _ |- _ ] => unfold IdealWorld.check_perm in H\n          | [ H : context [ IdealWorld.addMsg _ _ _ ] |- _ ] => unfold IdealWorld.addMsg in H; simpl in H\n          | [ H : Forall _ [] |- _ ] => clear H\n          | [ H : context [true || _]  |- _] => rewrite orb_true_l in H\n          | [ H : context [_ || true]  |- _] => rewrite orb_true_r in H\n          | [ H : context [false || _]  |- _] => rewrite orb_false_l in H\n          | [ H : context [_ || false]  |- _] => rewrite orb_false_r in H\n          | [ H : context [$0 $k++ _] |- _] => rewrite merge_perms_left_identity in H\n          | [ H : context [_ $k++ $0] |- _] => rewrite merge_perms_right_identity in H\n          | [ H : context [_ $k++ _]  |- _] =>\n            erewrite reduce_merge_perms in H by (clean_map_lookups; eauto)\n          | [ H : context [_ $k++ _]  |- _] =>\n            unfold merge_perms, add_key_perm, fold in H; simpl in H; clean_map_lookups\n\n          | [ H : context [ _ $+ (?k1,_) $? ?k2] |- _ ] =>\n              (rewrite add_neq_o in H by solve_simple_ineq)\n            || (rewrite add_eq_o in H by trivial)\n          | [ H : context [ ?m $? _ ] |- _ ] =>\n            progress (unfold m in H)\n\n          | [ |- context [$0 $k++ _] ] => rewrite !merge_perms_left_identity\n          | [ |- context [_ $k++ $0] ] => rewrite !merge_perms_right_identity \n          end\n      ).\n\n  Ltac close :=\n    match goal with\n    | [|- [_ | _] (?ru, ?iu, _)] =>\n      concrete ru\n      ; concrete iuniv iu\n      ; tidy\n      (* ; repeat( progress (subst; cleanup) ) *)\n      ; repeat eexists\n      ; propositional\n      ; solve[ eauto\n             | canonicalize users\n               ; repeat univ_equality1 ]\n    | [|- (?inv1 \\cup ?inv2) (?ru, ?iu, _)] =>\n      concrete inv1\n      ; concrete ru\n      ; concrete iuniv iu\n      ; solve[ idtac \"trying left\"; left; close\n             | idtac \"left fails; trying right\"; right; close\n             | idtac \"something is horribly wrong\" (* prevent an infinite loop *)\n             ]\n    | [|- ?inv (?ru, ?iu, _)] =>\n      is_evar inv\n      ; concrete ru\n      ; concrete iuniv iu\n      ; repeat equality1\n      ; solve_concrete_maps\n      ; canonicalize users\n      ; clean_context\n      ; repeat( progress (subst; cleanup) )\n      (* ; cleanup *)\n      ; NatMap.clean_map_lookups\n      ; ChMaps.ChMap.clean_map_lookups\n      ; incorp\n      ; solve[ close ]\n    end.\n\n  Ltac gen1' :=\n    simplify\n    ; tidy\n    ; idtac \"rstep start\"\n    ; rstep\n    ; idtac \"istep start\"\n    ; istep\n    ; idtac \"istep done\"\n    ; subst\n    ; canonicalize users\n    ; idtac \"close start\"\n    ; repeat close\n    ; idtac \"close done\".\n\n  Locate intersect_empty_l.\n\n  Ltac normalize_set_arg s :=\n    match s with\n    | context[@union ?A ?X ?Y] =>\n      quote (@union A X Y) (@nil A)\n            ltac:(fun e env =>\n                    change (@union A X Y) with (interp_setexpr env e));\n      rewrite <- normalize_setexpr_ok; sets_cbv\n    end.\n\n  Ltac gen1 :=\n    match goal with\n    | [|- multiStepClosure _ _ { } _] =>\n      eapply MscDone\n    | [|- multiStepClosure _ {(_,_,_)} {(_,_,_)} _] =>\n      eapply MscStep\n      ; [ solve[ apply oneStepClosure_grow; repeat gen1' ]\n        | simplify; simpl_sets (sets; tidy)]\n    | [|- multiStepClosure _ (?pr \\cup ?wl) ?wl _] =>\n      progress ( normalize_set_arg pr ; normalize_set_arg wl )\n    | [|- multiStepClosure _ (_ \\cup ?wl) ?wl _] =>\n      eapply msc_step_alt\n      ; [ solve[ unfold oneStepClosure_new; repeat gen1' ]\n        | solve[ idtac \"proving empty intersection\"\n                 ; simplify\n                 ; sets\n                 ; split_ex\n                 ; propositional\n                 ; idtac \"preparing to discriminate universes\"\n                 (* equality has to run after univ equality discrimination because equality1 uses injeection\n                  * which isn't always safe to use on universes.  See comment on univ_equality_discr \n                  *)\n                 ; repeat (univ_equality_discr || equality1)\n                 ; idtac \"universes discriminated\"\n               | eapply intersect_empty_l]\n        | rewrite ?union_empty_r ]\n    end.\n\n  (* Use this to generate the invariant *)\n  Ltac gen := repeat gen1.\n\n  Ltac discr_sets :=\n    simplify\n    ; sets\n    ; split_ex\n\n    (* equality has to run after univ equality discrimination because equality1 uses injeection\n     * which isn't always safe to use on universes.  See comment on univ_equality_discr \n     *)\n    ; repeat (univ_equality_discr || equality1).\n\n  Ltac dedup_worklist wl k :=\n    let rec dedup_wl acc wl :=\n        idtac \"iterating\";\n        match wl with\n        | ?s1 \\cup ?s2 =>\n          ( assert ( acc \\cap s1 = { } ) by discr_sets\n            ; dedup_wl (acc \\cup s1) s2 )\n          || dedup_wl acc s2\n        | ?s => \n          ( assert ( acc \\cap s = { } ) by discr_sets\n            ; k (acc \\cup s) )\n          || k acc\n        end\n\n    in idtac \"wl\";\n       match wl with\n       | { } \\cup ?s  => dedup_worklist s k\n       | ?s1 \\cup ?s2 => dedup_wl s1 s2\n       | ?s1          => k s1\n       end.\n\nEnd Gen.\n                     \n(* Helps with initial universe state proofs *)\nLtac focus_user :=\n  repeat\n    match goal with\n    | [ H : _ $+ (?k1,_) $? ?k2 = Some ?v |- _ ] =>\n      is_var v;\n      match type of v with\n      | RealWorld.user_data _ => idtac\n      end; destruct (k1 ==n k2); subst; clean_map_lookups\n    end.\n\n", "meta": {"author": "usenix21-paper58", "repo": "paper58", "sha": "e5117b0cb1d749df1768c9098aee7112ae16d8e9", "save_path": "github-repos/coq/usenix21-paper58-paper58", "path": "github-repos/coq/usenix21-paper58-paper58/paper58-e5117b0cb1d749df1768c9098aee7112ae16d8e9/src/ModelCheck/ProtocolAutomation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.287897040705774}}
{"text": "From iris.proofmode Require Import tactics.\nFrom iris.algebra Require Import frac agree csum.\nFrom iris.program_logic Require Export weakestpre hoare.\nFrom iris.heap_lang Require Export lang.\nFrom iris.heap_lang Require Import assert proofmode notation adequacy.\nFrom iris.heap_lang.lib Require Import par.\nSet Default Proof Using \"Type\".\n\n(** This is the introductory example from Ralf's PhD thesis.\nThe difference to [one_shot] is that [set] asserts to be called only once. *)\n\nDefinition one_shot_example : val := λ: <>,\n  let: \"x\" := ref NONE in (\n  (* set *) (λ: \"n\",\n    assert: CAS \"x\" NONE (SOME \"n\")),\n  (* check  *) (λ: <>,\n    let: \"y\" := !\"x\" in λ: <>,\n      let: \"y'\" := !\"x\" in\n      match: \"y\" with\n        NONE => #()\n      | SOME <> => assert: \"y\" = \"y'\"\n      end)).\n\nDefinition one_shotR := csumR fracR (agreeR ZO).\nDefinition Pending (q : Qp) : one_shotR := Cinl q.\nDefinition Shot (n : Z) : one_shotR := Cinr (to_agree n).\n\nClass one_shotG Σ := { one_shot_inG :> inG Σ one_shotR }.\nDefinition one_shotΣ : gFunctors := #[GFunctor one_shotR].\nInstance subG_one_shotΣ {Σ} : subG one_shotΣ Σ → one_shotG Σ.\nProof. solve_inG. Qed.\n\nSection proof.\nLocal Set Default Proof Using \"Type*\".\nContext `{!heapG Σ, !one_shotG Σ}.\n\nDefinition one_shot_inv (γ : gname) (l : loc) : iProp Σ :=\n  (l ↦ NONEV ∗ own γ (Pending (1/2)%Qp) ∨\n   ∃ n : Z, l ↦ SOMEV #n ∗ own γ (Shot n))%I.\n\nLocal Hint Extern 0 (environments.envs_entails _ (one_shot_inv _ _)) =>\n  unfold one_shot_inv : core.\n\nLemma pending_split γ q :\n  own γ (Pending q) ⊣⊢ own γ (Pending (q/2)) ∗ own γ (Pending (q/2)).\nProof.\n  rewrite /Pending. rewrite -own_op -Cinl_op. rewrite frac_op' Qp_div_2 //.\nQed.\n\nLemma pending_shoot γ n :\n  own γ (Pending 1%Qp) ==∗ own γ (Shot n).\nProof.\n  iIntros \"Hγ\". iMod (own_update with \"Hγ\") as \"$\"; last done.\n  by apply cmra_update_exclusive with (y:=Shot n).\nQed.\n\nLemma wp_one_shot (Φ : val → iProp Σ) :\n  (∀ (f1 f2 : val) (T : iProp Σ), T ∗\n    □ (∀ n : Z, T -∗ WP f1 #n {{ w, True }}) ∗\n    □ WP f2 #() {{ g, □ WP g #() {{ _, True }} }} -∗ Φ (f1,f2)%V)\n  ⊢ WP one_shot_example #() {{ Φ }}.\nProof.\n  iIntros \"Hf /=\". pose proof (nroot .@ \"N\") as N.\n  rewrite -wp_fupd. wp_lam. wp_alloc l as \"Hl\".\n  iMod (own_alloc (Pending 1%Qp)) as (γ) \"Hγ\"; first done.\n  iDestruct (pending_split with \"Hγ\") as \"[Hγ1 Hγ2]\".\n  iMod (inv_alloc N _ (one_shot_inv γ l) with \"[Hl Hγ2]\") as \"#HN\".\n  { iNext. iLeft. by iFrame. }\n  wp_pures. iModIntro. iApply (\"Hf\" $! _ _ (own γ (Pending (1/2)%Qp))).\n  iSplitL; first done. iSplit.\n  - iIntros (n) \"!> Hγ1\". wp_pures.\n    iApply wp_assert. wp_pures. wp_bind (CmpXchg _ _ _).\n    iInv N as \">[[Hl Hγ2]|H]\"; last iDestruct \"H\" as (m) \"[Hl Hγ']\".\n    + iDestruct (pending_split with \"[$Hγ1 $Hγ2]\") as \"Hγ\".\n      iMod (pending_shoot _ n with \"Hγ\") as \"Hγ\".\n      wp_cmpxchg_suc. iModIntro. iSplitL; last (wp_pures; by eauto).\n      iNext; iRight; iExists n; by iFrame.\n    + by iDestruct (own_valid_2 with \"Hγ1 Hγ'\") as %?.\n  - iIntros \"!> /=\". wp_lam. wp_bind (! _)%E.\n    iInv N as \">Hγ\".\n    iAssert (∃ v, l ↦ v ∗ (⌜v = NONEV⌝ ∗ own γ (Pending (1/2)%Qp) ∨\n       ∃ n : Z, ⌜v = SOMEV #n⌝ ∗ own γ (Shot n)))%I with \"[Hγ]\" as \"Hv\".\n    { iDestruct \"Hγ\" as \"[[Hl Hγ]|Hl]\"; last iDestruct \"Hl\" as (m) \"[Hl Hγ]\".\n      + iExists NONEV. iFrame. eauto.\n      + iExists (SOMEV #m). iFrame. eauto. }\n    iDestruct \"Hv\" as (v) \"[Hl Hv]\". wp_load.\n    iAssert (one_shot_inv γ l ∗ (⌜v = NONEV⌝ ∨ ∃ n : Z,\n      ⌜v = SOMEV #n⌝ ∗ own γ (Shot n)))%I with \"[Hl Hv]\" as \"[Hinv #Hv]\".\n    { iDestruct \"Hv\" as \"[[% ?]|Hv]\"; last iDestruct \"Hv\" as (m) \"[% ?]\"; subst.\n      + Show. iSplit. iLeft; by iSplitL \"Hl\". eauto.\n      + iSplit. iRight; iExists m; by iSplitL \"Hl\". eauto. }\n    iSplitL \"Hinv\"; first by eauto.\n    iModIntro. wp_pures. iIntros \"!>\". wp_lam. wp_bind (! _)%E.\n    iInv N as \"Hinv\".\n    iDestruct \"Hv\" as \"[%|Hv]\"; last iDestruct \"Hv\" as (m) \"[% Hγ']\"; subst.\n    + iDestruct \"Hinv\" as \"[[Hl >Hγ]|H]\"; last iDestruct \"H\" as (m') \"[Hl Hγ]\";\n      wp_load; iModIntro; (iSplitL \"Hl Hγ\"; first by eauto with iFrame);\n      wp_pures; done.\n    + iDestruct \"Hinv\" as \"[[Hl >Hγ]|H]\"; last iDestruct \"H\" as (m') \"[Hl Hγ]\".\n      { by iDestruct (own_valid_2 with \"Hγ Hγ'\") as %?. }\n      wp_load. Show.\n      iDestruct (own_valid_2 with \"Hγ Hγ'\") as %?%to_agree_op_inv_L; subst.\n      iModIntro. iSplitL \"Hl Hγ\"; first by eauto with iFrame.\n      wp_pures. iApply wp_assert. wp_op. by case_bool_decide.\nQed.\n\nLemma ht_one_shot (Φ : val → iProp Σ) :\n  ⊢ {{ True }} one_shot_example #()\n    {{ ff, ∃ T, T ∗\n      (∀ n : Z, {{ T }} Fst ff #n {{ _, True }}) ∗\n      {{ True }} Snd ff #() {{ g, {{ True }} g #() {{ _, True }} }}\n    }}.\nProof.\n  iIntros \"!> _\". iApply wp_one_shot. iIntros (f1 f2 T) \"(HT & #Hf1 & #Hf2)\".\n  iExists T. iFrame \"HT\". iSplit.\n  - iIntros (n) \"!> HT\". wp_apply \"Hf1\". done.\n  - iIntros \"!> _\". wp_apply (wp_wand with \"Hf2\"). by iIntros (v) \"#? !> _\".\nQed.\nEnd proof.\n\n(* Have a client with a closed proof. *)\nDefinition client : expr :=\n  let: \"ff\" := one_shot_example #() in\n  (Fst \"ff\" #5 ||| let: \"check\" := Snd \"ff\" #() in \"check\" #()).\n\nSection client.\n  Context `{!heapG Σ, !one_shotG Σ, !spawnG Σ}.\n\n  Lemma client_safe : ⊢ WP client {{ _, True }}.\n  Proof using Type*.\n    rewrite /client. wp_apply wp_one_shot. iIntros (f1 f2 T) \"(HT & #Hf1 & #Hf2)\".\n    wp_let. wp_apply (wp_par with \"[HT]\").\n    - wp_apply \"Hf1\". done.\n    - wp_proj. wp_bind (f2 _)%E. iApply wp_wand; first by iExact \"Hf2\".\n      iIntros (check) \"Hcheck\". wp_pures. iApply \"Hcheck\".\n    - auto.\n  Qed.\nEnd client.\n\n(** Put together all library functors. *)\nDefinition clientΣ : gFunctors := #[ heapΣ; one_shotΣ; spawnΣ ].\n(** This lemma implicitly shows that these functors are enough to meet\nall library assumptions. *)\nLemma client_adequate σ : adequate NotStuck client σ (λ _ _, True).\nProof. apply (heap_adequacy clientΣ)=> ?. iIntros \"_\". iApply client_safe. Qed.\n", "meta": {"author": "SkySkimmer", "repo": "iris", "sha": "186d9ece07e210e92be28eb0e1a42f5d5fe6f1b5", "save_path": "github-repos/coq/SkySkimmer-iris", "path": "github-repos/coq/SkySkimmer-iris/iris-186d9ece07e210e92be28eb0e1a42f5d5fe6f1b5/tests/one_shot_once.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2878970345390851}}
{"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 branch tunneling optimization. *)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import UnionFind.\nRequire Import AST.\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 Tunneling.\n\n(** * Properties of the branch map computed using union-find. *)\n\n(** A variant of [record_goto] that also incrementally computes a measure [f: node -> nat]\n  counting the number of [Lnop] instructions starting at a given [pc] that were eliminated. *)\n\nDefinition measure_edge (u: U.t) (pc s: node) (f: node -> nat) : node -> nat :=\n  fun x => if peq (U.repr u s) pc then f x\n           else if peq (U.repr u x) pc then (f x + f s + 1)%nat\n           else f x.\n\nDefinition record_goto' (uf: U.t * (node -> nat)) (pc: node) (b: bblock) : U.t * (node -> nat) :=\n  match b with\n  | Lbranch s :: b' => let (u, f) := uf in (U.union u pc s, measure_edge u pc s f)\n  | _ => uf\n  end.\n\nDefinition branch_map_correct (c: code) (uf: U.t * (node -> nat)): Prop :=\n  forall pc,\n  match c!pc with\n  | Some(Lbranch s :: b) =>\n      U.repr (fst uf) pc = pc \\/ (U.repr (fst uf) pc = U.repr (fst uf) s /\\ snd uf s < snd uf pc)%nat\n  | _ =>\n      U.repr (fst uf) pc = pc\n  end.\n\nLemma record_gotos'_correct:\n  forall c,\n  branch_map_correct c (PTree.fold record_goto' c (U.empty, fun (x: node) => O)).\nProof.\n  intros.\n  apply PTree_Properties.fold_rec with (P := fun c uf => branch_map_correct c uf).\n\n(* extensionality *)\n  intros. red; intros. rewrite <- H. apply H0.\n\n(* base case *)\n  red; intros; simpl. rewrite PTree.gempty. apply U.repr_empty.\n\n(* inductive case *)\n  intros m uf pc bb; intros. destruct uf as [u f]. \n  assert (PC: U.repr u pc = pc). \n    generalize (H1 pc). rewrite H. auto.\n  assert (record_goto' (u, f) pc bb = (u, f)\n          \\/ exists s, exists bb', bb = Lbranch s :: bb' /\\ record_goto' (u, f) pc bb = (U.union u pc s, measure_edge u pc s f)).\n    unfold record_goto'; simpl. destruct bb; auto. destruct i; auto. right. exists s; exists bb; auto.\n  destruct H2 as [B | [s [bb' [EQ B]]]].\n\n(* u and f are unchanged *)\n  rewrite B.\n  red. intro pc'. simpl. rewrite PTree.gsspec. destruct (peq pc' pc). subst pc'. \n  destruct bb; auto. destruct i; auto.\n  apply H1. \n\n(* b is Lbranch s, u becomes union u pc s, f becomes measure_edge u pc s f *)\n  rewrite B.\n  red. intro pc'. simpl. rewrite PTree.gsspec. destruct (peq pc' pc). subst pc'. rewrite EQ.\n\n(* The new instruction *)\n  rewrite (U.repr_union_2 u pc s); auto. rewrite U.repr_union_3. \n  unfold measure_edge. destruct (peq (U.repr u s) pc). auto. right. split. auto.\n  rewrite PC. rewrite peq_true. omega.\n\n(* An old instruction *)\n  assert (U.repr u pc' = pc' -> U.repr (U.union u pc s) pc' = pc').\n    intro. rewrite <- H2 at 2. apply U.repr_union_1. congruence. \n  generalize (H1 pc'). simpl. destruct (m!pc'); auto. destruct b; auto. destruct i; auto.\n  intros [P | [P Q]]. left; auto. right.\n  split. apply U.sameclass_union_2. auto.\n  unfold measure_edge. destruct (peq (U.repr u s) pc). auto.\n  rewrite P. destruct (peq (U.repr u s0) pc). omega. auto. \nQed.\n\nDefinition record_gotos' (f: function) :=\n  PTree.fold record_goto' f.(fn_code) (U.empty, fun (x: node) => O).\n\nLemma record_gotos_gotos':\n  forall f, fst (record_gotos' f) = record_gotos f.\nProof.\n  intros. unfold record_gotos', record_gotos. \n  repeat rewrite PTree.fold_spec.\n  generalize (PTree.elements (fn_code f)) (U.empty) (fun _ : node => O).\n  induction l; intros; simpl.\n  auto.\n  unfold record_goto' at 2. unfold record_goto at 2. \n  destruct (snd a). apply IHl. destruct i; apply IHl.\nQed.\n\nDefinition branch_target (f: function) (pc: node) : node :=\n  U.repr (record_gotos f) pc.\n\nDefinition count_gotos (f: function) (pc: node) : nat :=\n  snd (record_gotos' f) pc.\n\nTheorem record_gotos_correct:\n  forall f pc,\n  match f.(fn_code)!pc with\n  | Some(Lbranch s :: b) =>\n       branch_target f pc = pc \\/\n       (branch_target f pc = branch_target f s /\\ count_gotos f s < count_gotos f pc)%nat\n  | _ => branch_target f pc = pc\n  end.\nProof.\n  intros. \n  generalize (record_gotos'_correct f.(fn_code) pc). simpl.\n  fold (record_gotos' f). unfold branch_map_correct, branch_target, count_gotos.\n  rewrite record_gotos_gotos'. auto.\nQed.\n\n(** * Preservation of semantics *)\n\nSection PRESERVATION.\n\nVariable prog: program.\nLet tprog := tunnel_program prog.\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  Genv.find_funct tge v = Some (tunnel_fundef f).\nProof (@Genv.find_funct_transf _ _ _ tunnel_fundef prog).\n\nLemma function_ptr_translated:\n  forall v f,\n  Genv.find_funct_ptr ge v = Some f ->\n  Genv.find_funct_ptr tge v = Some (tunnel_fundef f).\nProof (@Genv.find_funct_ptr_transf _ _ _ tunnel_fundef prog).\n\nLemma symbols_preserved:\n  forall id,\n  Genv.find_symbol tge id = Genv.find_symbol ge id.\nProof (@Genv.find_symbol_transf _ _ _ tunnel_fundef prog).\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 _ _ _ tunnel_fundef prog).\n\nLemma sig_preserved:\n  forall f, funsig (tunnel_fundef f) = funsig f.\nProof.\n  destruct f; reflexivity.\nQed.\n\nLemma find_function_translated:\n  forall ros ls f,\n  find_function ge ros ls = Some f ->\n  find_function tge ros ls = Some (tunnel_fundef f).\nProof.\n  intros until f. destruct ros; simpl.\n  intro. 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(** The proof of semantic preservation is a simulation argument\n  based on diagrams of the following form:\n<<\n           st1 --------------- st2\n            |                   |\n           t|                  ?|t\n            |                   |\n            v                   v\n           st1'--------------- st2'\n>>\n  The [match_states] predicate, defined below, captures the precondition\n  between states [st1] and [st2], as well as the postcondition between\n  [st1'] and [st2'].  One transition in the source code (left) can correspond\n  to zero or one transition in the transformed code (right).  The\n  \"zero transition\" case occurs when executing a [Lgoto] instruction\n  in the source code that has been removed by tunneling.\n\n  In the definition of [match_states], note that only the control-flow\n  (in particular, the current program point [pc]) is changed:\n  the values of locations and the memory states are identical in the\n  original and transformed codes. *)\n\nDefinition tunneled_block (f: function) (b: bblock) :=\n  tunnel_block (record_gotos f) b.\n\nDefinition tunneled_code (f: function) :=\n  PTree.map1 (tunneled_block f) (fn_code f).\n\nInductive match_stackframes: stackframe -> stackframe -> Prop :=\n  | match_stackframes_intro:\n      forall f sp ls0 bb,\n      match_stackframes\n         (Stackframe f sp ls0 bb)\n         (Stackframe (tunnel_function f) sp ls0 (tunneled_block f bb)).\n\nInductive match_states: state * mem -> state * mem -> Prop :=\n  | match_states_intro:\n      forall s f sp pc ls m ts,\n      Forall2 match_stackframes s ts ->\n      match_states (State s f sp pc ls, m)\n                   (State ts (tunnel_function f) sp (branch_target f pc) ls, m)\n  | match_states_block:\n      forall s f sp bb ls m ts,\n      Forall2 match_stackframes s ts ->\n      match_states (Block s f sp bb ls, m)\n                   (Block ts (tunnel_function f) sp (tunneled_block f bb) ls, m)\n  | match_states_interm:\n      forall s f sp pc bb ls m ts,\n      Forall2 match_stackframes s ts ->\n      match_states (Block s f sp (Lbranch pc :: bb) ls, m)\n                   (State ts (tunnel_function f) sp (branch_target f pc) ls, m)\n  | match_states_call:\n      forall s f ls m ts,\n      Forall2 match_stackframes s ts ->\n      match_states (Callstate s f ls, m)\n                   (Callstate ts (tunnel_fundef f) ls, m)\n  | match_states_return:\n      forall s ls m ts,\n      Forall2 match_stackframes s ts ->\n      match_states (Returnstate s ls, m)\n                   (Returnstate ts ls, m).\n\n(** To preserve non-terminating behaviours, we show that the transformed\n  code cannot take an infinity of \"zero transition\" cases.\n  We use the following [measure] function over source states,\n  which decreases strictly in the \"zero transition\" case. *)\n\nDefinition measure (st: state * mem) : nat :=\n  match st with\n  | (State s f sp pc ls, m) => (count_gotos f pc * 2)%nat\n  | (Block s f sp (Lbranch pc :: _) ls, m) => (count_gotos f pc * 2 + 1)%nat\n  | (Block s f sp bb ls, m) => 0%nat\n  | (Callstate s f ls, m) => 0%nat\n  | (Returnstate s ls, m) => 0%nat\n  end.\n\nLemma match_parent_locset:\n  forall s ts,\n  Forall2 match_stackframes s ts ->\n  parent_locset ts = parent_locset s.\nProof.\n  induction 1; simpl. auto. inv H; auto.\nQed.\n\nLemma tunnel_step_correct:\n  forall st1 t st2, step ge st1 t st2 ->\n  forall st1' (MS: match_states st1 st1'),\n  (exists st2', step tge st1' t st2' /\\ match_states st2 st2')\n  \\/ (measure st2 < measure st1 /\\ t = E0 /\\ match_states st2 st1')%nat.\nProof.\n  induction 1; intros; try inv MS.\n\n  (* entering a block *)\n  assert (DEFAULT: branch_target f pc = pc ->\n    (exists st2' : state * mem,\n     step tge (State ts (tunnel_function f) sp (branch_target f pc) rs, m) E0 st2'\n     /\\ match_states (Block s f sp bb rs, m) st2')).\n  intros. rewrite H0. econstructor; split. \n  econstructor. simpl. rewrite PTree.gmap1. rewrite H. simpl. eauto. \n  econstructor; eauto.\n\n  generalize (record_gotos_correct f pc). rewrite H. \n  destruct bb; auto. destruct i; auto. \n  intros [A | [B C]]. auto. \n  right. split. simpl. omega. \n  split. auto.\n  rewrite B. econstructor; eauto.\n\n  (* Lop *)\n  left; simpl; econstructor; split.\n  eapply exec_Lop with (v := v); eauto.\n  rewrite <- H. apply eval_operation_preserved. exact symbols_preserved.\n  econstructor; eauto.\n  (* Lload *)\n  left; simpl; econstructor; split.\n  eapply exec_Lload with (a := a). \n  rewrite <- H. apply eval_addressing_preserved. exact symbols_preserved.\n  eauto. eauto.\n  econstructor; eauto.\n  (* Lgetstack *)\n  left; simpl; econstructor; split.\n  econstructor; eauto.\n  econstructor; eauto.\n  (* Lsetstack *)\n  left; simpl; econstructor; split.\n  econstructor; eauto.\n  econstructor; eauto.\n  (* Lstore *)\n  left; simpl; econstructor; split.\n  eapply exec_Lstore with (a := a).\n  rewrite <- H. apply eval_addressing_preserved. exact symbols_preserved.\n  eauto. eauto.\n  econstructor; eauto.\n  (* Lcall *)\n  left; simpl; econstructor; split. \n  eapply exec_Lcall with (fd := tunnel_fundef fd); eauto.\n  apply find_function_translated; auto.\n  rewrite sig_preserved. auto.\n  econstructor; eauto.\n  constructor; auto. \n  constructor; auto.\n  (* Ltailcall *)\n  left; simpl; econstructor; split. \n  eapply exec_Ltailcall with (fd := tunnel_fundef fd); eauto.\n  erewrite match_parent_locset; eauto. \n  apply find_function_translated; auto.\n  apply sig_preserved.\n  erewrite <- match_parent_locset; eauto.\n  econstructor; eauto.\n  (* Lbuiltin *)\n  left; simpl; econstructor; split.\n  eapply exec_Lbuiltin; eauto. \n  eapply builtin_call_symbols_preserved'; eauto.\n  exact symbols_preserved. exact varinfo_preserved.\n  econstructor; eauto.\n  (* Lannot *)\n  left; simpl; econstructor; split.\n  eapply exec_Lannot; eauto. \n  eapply builtin_call_symbols_preserved'; eauto.\n  exact symbols_preserved. exact varinfo_preserved.\n  econstructor; eauto.\n\n  (* Lbranch (preserved) *)\n  left; simpl; econstructor; split.\n  eapply exec_Lbranch; eauto. \n  fold (branch_target f pc). econstructor; eauto.\n  (* Lbranch (eliminated) *)\n  right; split. simpl. omega. split. auto. constructor; auto. \n\n  (* Lcond *)\n  left; simpl; econstructor; split.\n  eapply exec_Lcond; eauto.\n  destruct b; econstructor; eauto.\n  (* Ljumptable *)\n  left; simpl; econstructor; split.\n  eapply exec_Ljumptable. \n  eauto. rewrite list_nth_z_map. change U.elt with node. rewrite H0. reflexivity. eauto.\n  econstructor; eauto. \n  (* Lreturn *)\n  left; simpl; econstructor; split.\n  eapply exec_Lreturn; eauto.\n  erewrite <- match_parent_locset; eauto.\n  constructor; auto.\n  (* internal function *)\n  left; simpl; econstructor; split.\n  eapply exec_function_internal; eauto.\n  simpl. econstructor; eauto. \n  (* external function *)\n  left; simpl; econstructor; split.\n  eapply exec_function_external; eauto.\n  eapply external_call_symbols_preserved'; eauto.\n  exact symbols_preserved. exact varinfo_preserved.\n  simpl. econstructor; eauto. \n  (* return *)\n  inv H3. inv H1.\n  left; econstructor; split.\n  eapply exec_return; eauto.\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  exists (Callstate nil (tunnel_fundef f) (Locmap.init Vundef), m0); split.\n  econstructor; eauto.\n  apply Genv.init_mem_transf; auto.\n  change (prog_main tprog) with (prog_main prog).\n  rewrite symbols_preserved. eauto.\n  apply function_ptr_translated; auto.\n  rewrite <- H3. apply sig_preserved. \n  constructor. constructor.\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 (LTL.semantics prog) (LTL.semantics tprog).\nProof.\n  eapply forward_simulation_opt.\n  eexact symbols_preserved.\n  eexact transf_initial_states.\n  eexact transf_final_states.\n  eexact tunnel_step_correct. \nQed.\n\nEnd PRESERVATION.\n", "meta": {"author": "robbertkrebbers", "repo": "compcert", "sha": "524c26591e884a3676a5fbef77d8c79193955b82", "save_path": "github-repos/coq/robbertkrebbers-compcert", "path": "github-repos/coq/robbertkrebbers-compcert/compcert-524c26591e884a3676a5fbef77d8c79193955b82/backend/Tunnelingproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.287893102723159}}
{"text": "(* type_remove *)\nRequire Import Capabilities_Conv.\nRequire Import References.\nRequire Import Capabilities.\nRequire Import AccessRights.\nRequire Import AccessRightSets.\nRequire Import Sumbool_dec.\nRequire Import Bool.\nRequire Import OrderedTypeEquiv.\n\n\nModule MakeCapConv (Ref: ReferenceType) (Cap:CapabilityType Ref) : CapabilityConv Ref Cap.\n\n  Module Cap_Equiv := OT_Equiv Cap.\n  Definition CapEQ := Cap_Equiv.Equiv.\n\n  Module Ref_Equiv := OT_Equiv Ref.\n  Definition RefEQ := Ref_Equiv.Equiv.\n\n  Definition hasRight c rgt:= ARSet.In rgt (Cap.rights c).\n  \n  Theorem mkCap_target: forall t r,\n    Ref.eq (Cap.target (Cap.mkCap t r)) t.\n  Proof.\n    intros.\n    generalize (Cap.mkCap_eq t r (Cap.mkCap t r)); intros.\n    destruct H; clear H.\n    generalize (H0 (Cap.eq_refl _)); intros; clear H0.\n    destruct H.\n    apply Ref.eq_sym; auto.\n  Qed.\n\n  Theorem mkCap_rights: forall t r,\n    ARSet.eq\n    (Cap.rights (Cap.mkCap t r)) r.\n  Proof.\n    intros.\n    generalize (Cap.mkCap_eq t r (Cap.mkCap t r)); intros.\n    destruct H; clear H.\n    generalize (H0 (Cap.eq_refl _)); intros; clear H0.\n    destruct H.\n    apply ARSet.eq_sym; auto.\n  Qed.\n\n  Theorem mkCap_equiv: forall a a' r r',\n    Ref.eq a a' ->\n    ARSet.eq r r' ->\n    Cap.eq (Cap.mkCap a r) (Cap.mkCap a' r').\n  Proof.\n    intros.\n    generalize (Cap.mkCap_eq a r (Cap.mkCap a' r')).\n    intros H1.\n    destruct H1.\n    apply H1.\n    split.\n    apply Ref.eq_trans with a'; auto.\n    apply Ref.eq_sym; apply mkCap_target.\n    apply ARSet.eq_trans with r'; auto.\n    apply ARSet.eq_sym; apply mkCap_rights.\n  Qed.\n\n  (* inter_eq is just inter_m, but we don't use it anymore. *)\n\n  Theorem weaken_target_eq : forall cap,\n    Ref.eq (Cap.target (Cap.weaken cap)) (Cap.target cap).\n  Proof.\n    intros.\n    generalize (Cap.weaken_eq cap); intros Hcap_eq.\n      (* for some reason, we can't use ... ; [ ... | ... ]. for this one. *)\n    eapply Ref.eq_trans.\n    eapply Cap.target_eq; eapply Hcap_eq.\n    rewrite mkCap_target; eauto.\n  Qed.\n\n\n\n  Theorem In_weak_weaken : forall cap rgt,\n    ARSet.In rgt (Cap.rights (Cap.weaken cap)) -> rgt = wk.\n  Proof.\n    intros.\n    generalize (Cap.weaken_eq cap); intros.\n    case (bool_dec \n      (true_bool_of_sumbool\n        (ARSetProps.In_dec wk\n          (Cap.rights cap))\n        || true_bool_of_sumbool\n          (ARSetProps.In_dec rd\n            (Cap.rights cap))) true); intros Hdec;\n    [|eapply not_true_is_false in Hdec]; rewrite Hdec in *; clear Hdec;\n\n      (eapply Cap.rights_eq in H0;\n        generalize mkCap_rights; intros Hrights; eapply ARSet.eq_sym in Hrights;\n          apply ARSet.eq_sym in H0; eapply ARSet.eq_trans in H0; [clear Hrights | apply Hrights];\n            eapply AccessRight.eq_sym; eapply H0 in H; \n              solve[ eapply ARSetFacts.singleton_iff; eauto | eapply ARSetFacts.empty_iff in H; contradiction]).\n  Qed.\n\n\n  Theorem weaken_singleton_or_empty: forall cap,\n    {ARSet.eq (Cap.rights (Cap.weaken cap)) (ARSet.singleton wk)} + \n    {ARSet.eq (Cap.rights (Cap.weaken cap)) (ARSet.empty)}.\n  Proof.\n    intros; generalize (Cap.weaken_eq cap); intros Hcap_eq; intros.\n\n    case (bool_dec \n      (true_bool_of_sumbool\n        (ARSetProps.In_dec wk\n          (Cap.rights cap))\n        || true_bool_of_sumbool\n          (ARSetProps.In_dec rd\n            (Cap.rights cap))) true); intros Hdec;\n    [|eapply not_true_is_false in Hdec]; rewrite Hdec in *;\n      [eapply orb_prop in Hdec| eapply orb_false_elim in Hdec]; clear Hdec;\n        [left | right]; eapply Cap.rights_eq in Hcap_eq; rewrite mkCap_rights in Hcap_eq; auto.\n  Qed.\n\n    (* generalize and toss somewhere *)\n  Theorem singleton_is_not_empty: forall x,\n    ~ ARSet.Equal ARSet.empty (ARSet.singleton x).\n  Proof.\n    intros.\n    unfold ARSet.Equal.\n    intro H.\n    generalize (H x); clear H; intro H.\n    eapply iff_sym in H.\n    eapply iff_trans in H;[| eapply iff_sym; eapply ARSetFacts.singleton_iff].\n    destruct H.\n    generalize (H (refl_equal _)).\n    eapply ARSetFacts.empty_iff.\n  Qed.\n\n  Theorem weaken_rights_weak_eq:forall cap,\n    ARSet.In wk (Cap.rights cap) \\/ ARSet.In rd (Cap.rights cap) <->\n    ARSet.eq (Cap.rights (Cap.weaken cap)) (ARSet.singleton wk).\n  Proof.\n    intros; generalize (Cap.weaken_eq cap); intros Hcap_eq; split; intros.\n\n    eapply ARSet.eq_trans; [eapply Cap.rights_eq; eapply Hcap_eq |].\n    destruct H as [H | H];\n      unfold true_bool_of_sumbool; rewrite (proof_r_true_bool_of_sumbool _ _ H); simpl;\n        try rewrite orb_true_r;\n          rewrite mkCap_rights; apply ARSet.eq_refl.\n    \n    case (bool_dec \n      (true_bool_of_sumbool\n        (ARSetProps.In_dec wk\n          (Cap.rights cap))\n        || true_bool_of_sumbool\n          (ARSetProps.In_dec rd\n            (Cap.rights cap))) true); intros Hdec;\n    [|eapply not_true_is_false in Hdec]; rewrite Hdec in *;\n      [eapply orb_prop in Hdec| eapply orb_false_elim in Hdec].\n    \n    (* true case *)\n    unfold true_bool_of_sumbool in *;\n      destruct Hdec as [Hdec | Hdec]; eapply true_bool_of_sumbool_l in Hdec; intuition.\n    (* false case *)\n    clear Hdec.\n    eapply Cap.rights_eq in Hcap_eq.\n    eapply ARSet.eq_trans in Hcap_eq; [clear H| eapply ARSet.eq_sym; apply H].\n    eapply ARSet.eq_sym in Hcap_eq; eapply ARSet.eq_trans in Hcap_eq;\n      [| eapply ARSet.eq_sym; eapply mkCap_rights].\n    idtac.\n    eapply singleton_is_not_empty in Hcap_eq; contradiction.\n  Qed.\n\n  Theorem In_weaken_singleton: forall cap,\n    ARSet.In wk (Cap.rights (Cap.weaken cap)) ->\n    ARSet.eq (Cap.rights (Cap.weaken cap)) (ARSet.singleton wk).\n  Proof.\n    intros.\n    case (weaken_singleton_or_empty cap); intros; auto.\n    eapply e in H.\n    eapply ARSetFacts.empty_iff in H; contradiction.\n  Qed.\n\n  Theorem weaken_equiv: forall cap cap',\n    Cap.eq cap cap' ->\n    Cap.eq (Cap.weaken cap) (Cap.weaken cap').\n  Proof.\n    intros.\n    eapply Cap.eq_trans; [eapply Cap.weaken_eq|].\n    eapply Cap.eq_sym; eapply Cap.eq_trans; [apply Cap.weaken_eq|].\n    eapply mkCap_equiv; [eapply Cap.target_eq; auto|].\n    apply Cap.rights_eq in H.\n    case (ARSetProps.In_dec wk (Cap.rights cap)); intros Hweak; simpl; \n      [eapply H in Hweak; \n        unfold true_bool_of_sumbool; rewrite (proof_r_true_bool_of_sumbool _ _ Hweak); simpl;\n          apply ARSet.eq_refl|].\n    case (ARSetProps.In_dec rd (Cap.rights cap)); intros Hread; simpl;\n      [eapply H in Hread;\n        unfold true_bool_of_sumbool; rewrite (proof_r_true_bool_of_sumbool _ _ Hread); simpl;\n          rewrite orb_true_r; apply ARSet.eq_refl|].\n    unfold true_bool_of_sumbool; repeat progress (rewrite proof_l_true_bool_of_sumbool); simpl;\n      try apply ARSet.eq_refl.\n    intro; apply Hread; eapply H; auto.\n    intro; apply Hweak; eapply H; auto.\n  Qed.\n\nEnd MakeCapConv.\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/Capabilities_ConvImpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.287893096370178}}
{"text": "Require Import Core.Tactics Core.PtrLemmas.\nRequire Import StructTact.StructTactics Psatz.\nRequire Import SepLemmas.\nRequire Import VstSpec AbstractSpec AbstractSpecLemmas.\nRequire Import VST.floyd.proofauto Psatz.\nRequire Import Clight.INTEGER.\nArguments valid_pointer p : simpl never.\n\nLtac test_order_ptrs_tac p1 p2 :=\n          unfold test_order_ptrs; simpl;\n          destruct peq; [simpl|contradiction];\n          apply andp_right;\n          [try (apply derives_trans with (Q := valid_pointer p1);\n          entailer!;\n          apply valid_pointer_weak) | try (\n          apply derives_trans with (Q := valid_pointer p2);\n          entailer!;\n          apply valid_pointer_weak)]. \n\nLemma body_asn_strtoimax_lim : semax_body Vprog Gprog f_asn_strtoimax_lim\n                                          asn_strtoimax_lim_vst_spec.\nProof.\n  start_function.\n  pose (upper_boundary := (\n         (Int64.divs\n            (Int64.shru (Int64.not (Int64.repr (Int.signed (Int.repr 0))))\n                        (Int64.repr (Int.unsigned (Int.repr 1))))\n            (Int64.repr (Int.signed (Int.repr 10)))))).\n  pose (last_digit_max := ((Int64.mods\n                                    (Int64.shru\n                                       (Int64.not (Int64.repr 0))\n                                       (Int64.repr 1))\n                                    (Int64.repr 10)))).\n  rename H into EQB.\n  rename H0 into LEN.\n  all: repeat forward; try entailer!.         \n  1-2: break_and; inversion H7.\n  destruct Z.ltb eqn:IFCON.\n  - (* str < end' = true *)\n    all: Intros.\n    forward_if; apply Z.ltb_lt in IFCON.\n    + (* Valid pointer proof *)\n     test_order_ptrs_tac (Vptr end'_b str_ofs) (Vptr end'_b end'_ofs).\n    + (*  srt >= end' from forward_if : contradiction *)\n      forward.\n      apply typed_true_ptr_ge in H.\n      rewrite Z.geb_le in H; Lia.lia.\n    + (*  str < end' = true from forward_if, go further in the branch *)\n      rewrite EQB in H; apply typed_false_ptr_ge in H.\n      rewrite Z.gtb_lt in H.\n      assert (0 < Ptrofs.unsigned end'_ofs - Ptrofs.unsigned str_ofs)\n        by Lia.lia.\n      destruct ls.\n      replace (Zlength []) with (0) in LEN by reflexivity.\n      Lia.lia.\n      erewrite split_non_empty_list with (ls' := ls) (i := i) (ofs := str_ofs).\n      autorewrite with sublist in LEN.\n      assert (Zlength ls = (Ptrofs.unsigned end'_ofs - \n                                 Ptrofs.unsigned str_ofs) - 1) as LS_len by nia.\n      Intros.\n      repeat forward.\n           pose (sep_precondition :=\n              SEP  (\n                   valid_pointer (Vptr end'_b end'_ofs);\n                   valid_pointer (Vptr str_b str_ofs);\n                   valid_pointer (Vptr end'_b (Ptrofs.add str_ofs (Ptrofs.repr (Zlength (i :: ls))))); \n                   data_at sh_str tschar (Vbyte i) (Vptr str_b str_ofs);\n                   data_at sh_str (tarray tschar (Zlength ls)) (map Vbyte ls)\n                           (Vptr str_b (Ptrofs.add str_ofs Ptrofs.one));\n                   data_at sh_end (tptr tschar) (Vptr end'_b end'_ofs)\n                           (Vptr end_b end_ofs);\n                   data_at sh_intp tlong v (Vptr intp_b intp_ofs))).\n      forward_if (\n          if Byte.signed i =? 45\n          then PROP( 0 < Zlength ls )\n               LOCAL(temp _sign (Vint (Int.repr (-1)));\n                     temp _str (Vptr end'_b\n                                     (Ptrofs.add str_ofs (Ptrofs.repr 1)));\n                     temp _end (Vptr end_b end_ofs); \n                     temp _intp (Vptr intp_b intp_ofs);\n                     temp _last_digit_max\n                          (Vlong (Int64.add last_digit_max Int64.one));\n                     temp _upper_boundary (Vlong upper_boundary))\n               sep_precondition\n          else if Byte.signed i =? 43\n               then PROP( 0 < Zlength ls )\n                    LOCAL(temp _str (Vptr end'_b \n                                          (Ptrofs.add str_ofs (Ptrofs.repr 1)));\n                         temp _end (Vptr end_b end_ofs); \n                     temp _intp (Vptr intp_b intp_ofs))\n                    sep_precondition\n               else !!(Byte.signed i =? 43 = false /\\\n                       Byte.signed i =? 45 = false)).\n        * (* if *str = '-' = Int.repr 45 *)\n        forward.\n        entailer!.\n        { replace (Int64.repr 0) with (Int64.zero) by reflexivity; \n            replace (Int64.repr 1) with (Int64.one) by reflexivity.\n          rewrite Int64.not_zero.\n          unfold Int64.mods, Int64.shru, Z.shiftr.\n          rewrite Int64.unsigned_mone, Int64.unsigned_one; simpl.\n          repeat rewrite Int64.signed_repr;\n            unfold Int64.min_signed, Int64.max_signed;\n            unfold Int64.half_modulus, Int64.modulus;\n            cbn; Lia.lia. }\n        repeat forward.\n        forward_if.\n        ** unfold test_order_ptrs; simpl.\n           destruct peq; [simpl|contradiction].\n           apply andp_right.\n           apply derives_trans with\n               (Q := valid_pointer (Vptr end'_b (Ptrofs.add str_ofs (Ptrofs.repr 1)))).\n           destruct ls.\n           -- autorewrite with sublist.\n              simpl; entailer!.\n           -- autorewrite with sublist.\n              entailer!.\n           --  apply valid_pointer_weak.\n           --\n           entailer!.\n           apply derives_trans with (Q := valid_pointer (Vptr end'_b end'_ofs)).\n           entailer!.\n           apply valid_pointer_weak.\n           (* end_ofs <= str_ofs + 1, return EXPECT_MORE *)\n        ** repeat forward.\n           rename H2 into IFCON2.\n           apply typed_true_ptr_ge in IFCON2.\n           replace (Ptrofs.add str_ofs (Ptrofs.mul (Ptrofs.repr 1) \n                                                   (Ptrofs.of_ints (Int.repr 1))))\n             with (Ptrofs.add str_ofs Ptrofs.one) in * by auto with ptrofs.\n           apply Z.geb_le in IFCON2.\n           replace (Ptrofs.unsigned (Ptrofs.add str_ofs Ptrofs.one)) \n             with (Ptrofs.unsigned str_ofs + 1) in *. (* follows from IFCON *)\n           assert (Ptrofs.unsigned end'_ofs - Ptrofs.unsigned str_ofs - 1 = 0) as Z \n               by nia.\n           assert (ls = []) as CONTENT.\n           rewrite Z in LS_len.\n           apply Zlength_nil_inv; assumption.\n           rewrite CONTENT.\n           unfold is_sign, plus_char, minus_char.\n           assert ((Byte.signed i =? 45) = true) as IS.\n           Zbool_to_Prop. eassumption.\n           bool_rewrite.\n           replace ((Byte.signed i =? 43) || true)%bool with true by intuition.\n           simpl.\n           entailer!.\n           simpl.\n           autorewrite with sublist.\n           simpl.\n           erewrite data_at_zero_array_eq.\n           erewrite data_at_singleton_array_eq.\n           entailer!.\n           all: auto; try econstructor.\n           ptrofs_compute_add_mul.\n           auto with ptrofs.\n           replace (Ptrofs.unsigned Ptrofs.one) with 1 by auto with ptrofs.\n           autorewrite with sublist in *|-.\n           assert (0 <= (Zlength ls)) by eapply Zlength_nonneg.\n           replace (Z.succ (Zlength ls)) with (Zlength ls + 1) in *.\n           assert (0 <= Ptrofs.unsigned str_ofs).\n           eapply Ptrofs.unsigned_range.\n           nia.\n           nia.      \n        ** (* str_ofs + 1 < end_ofs *)\n          forward.\n          rename H2 into IFCON2.\n          subst.\n          apply typed_false_ptr_ge in IFCON2.\n          autorewrite with norm in *.\n          replace (Ptrofs.unsigned\n                         (Ptrofs.add str_ofs (Ptrofs.repr 1)))\n            with (Ptrofs.unsigned str_ofs  + 1) in *\n               by (autorewrite with norm;\n                   ptrofs_compute_add_mul;\n                   rep_omega_setup;\n                   nia).\n          rewrite E.\n          unfold sep_precondition. entailer!.   \n          apply Zgt_is_gt_bool in IFCON2.\n          nia.          \n      * (* if *str = '+' *)\n        repeat forward.\n        forward_if.\n        unfold test_order_ptrs; simpl.\n           destruct peq; [simpl|contradiction].\n           apply andp_right.\n           apply derives_trans with\n               (Q := valid_pointer (Vptr end'_b (Ptrofs.add str_ofs (Ptrofs.repr 1)))).\n           destruct ls.\n           autorewrite with sublist.\n              simpl; entailer!.\n           autorewrite with sublist.\n              entailer!.\n            apply valid_pointer_weak.\n          \n           entailer!.\n           apply derives_trans with (Q := valid_pointer (Vptr end'_b end'_ofs)).\n           entailer!.\n           apply valid_pointer_weak.\n           subst.\n           rewrite_comparison.\n           autorewrite with norm in H2.\n           replace (Ptrofs.unsigned\n                         (Ptrofs.add str_ofs (Ptrofs.repr 1)))\n            with (Ptrofs.unsigned str_ofs  + 1) in *\n               by (autorewrite with norm;\n                   ptrofs_compute_add_mul;\n                   rep_omega_setup;\n                   nia).\n           apply Z.geb_le in H2.\n        forward.\n        forward.       \n        assert (ls = []) as N.\n        autorewrite with sublist in *|-.\n        apply Zlength_nil_inv.\n        nia.\n        rewrite N.\n        unfold is_sign, plus_char, minus_char.\n        assert ((Byte.signed i =? 43) = true) as IS.\n        Zbool_to_Prop.\n        nia.\n        bool_rewrite.\n        auto.\n        simpl.\n        entailer!.\n        erewrite data_at_singleton_array_eq.\n        instantiate (1 :=  (Vbyte i)).\n        entailer!.\n        rewrite data_at_zero_array_eq.\n        entailer!.\n        all: try auto.\n        subst.\n        rewrite_comparison.\n          autorewrite with norm in *.\n          replace (Ptrofs.unsigned\n                         (Ptrofs.add str_ofs (Ptrofs.repr 1)))\n            with (Ptrofs.unsigned str_ofs  + 1) in *\n               by (autorewrite with norm;\n                   ptrofs_compute_add_mul;\n                   rep_omega_setup;\n                   nia).\n          apply Zgt_is_gt_bool in H2.\n        forward.\n        rewrite E.\n        subst.\n         unfold sep_precondition.\n         entailer!.\n      * (* default case *) \n        forward.\n        replace (Byte.signed i =? 45) with false.\n        replace (Byte.signed i =? 43) with false.\n        unfold sep_precondition. entailer.\n        assert ((Int.repr (Byte.signed i)) <> (Int.repr 43)).\n        intuition.\n        rewrite H2 in *.\n        intuition.\n         eapply repr_neq_e in H2.\n         symmetry.\n         Zbool_to_Prop.\n         nia.\n         assert ((Int.repr (Byte.signed i)) <> (Int.repr 45)).\n        intuition.\n        rewrite H2 in *.\n        intuition.\n         eapply repr_neq_e in H2.\n         symmetry.\n         Zbool_to_Prop.\n         nia.\n      * (* Loop *)\n\n        repeat break_if;\n          unfold sep_precondition.\n        ** \n          assert (is_sign i = true) as SGN \n              by (unfold is_sign, minus_char; bool_rewrite; intuition).\n          assert (Byte.signed i =? minus_char = true) as MCH \n              by (unfold is_sign, minus_char; bool_rewrite; intuition).\n          assert (Byte.signed i =? plus_char = false) as PCH \n              by (rewrite Z.eqb_eq in Heqb; rewrite Heqb; intuition).\n          forward.\n          remember (Ptrofs.add str_ofs Ptrofs.one) as str_ofs'.\n           remember (Int64.unsigned upper_boundary) as ub.\n           remember (i :: ls) as ls'.\n           forward_loop (\n               EX j : Z, EX vl : Z,\n                 let i' := Ptrofs.add str_ofs (Ptrofs.repr (j + 1)) in\n                (* let b := if Ptrofs.unsigned str_ofs + j + 1 >=?\n                             Ptrofs.unsigned end'_ofs then false else true in *)\n                 PROP(0 <= j <= Zlength ls;\n                      Ptrofs.unsigned str_ofs + j + 1 < Ptrofs.modulus;\n                      forall (i : Z), 0 <= i < j -> is_digit (Znth i ls) = true;\n                        bounded (value_until j ls true 0 1) = true)\n                 LOCAL(temp _end (Vptr end_b end_ofs); \n                       temp _intp (Vptr intp_b intp_ofs);\n                       temp _str (Vptr end'_b i');\n                       temp _value (Vlong (Int64.repr (value_until j ls true 0 1)));\n                       temp _sign (Vint (Int.repr ((*(if b then 1 else *) -1)));\n                       temp _upper_boundary (Vlong upper_boundary);\n                       temp _last_digit_max\n                            (Vlong (Int64.add last_digit_max Int64.one)))\n                 SEP(\n                    valid_pointer (Vptr end'_b (Ptrofs.add str_ofs \n                                                              (Ptrofs.repr (Zlength (i :: ls)))));\n                   valid_pointer (Vptr end'_b str_ofs) ;\n                   valid_pointer (Vptr end'_b end'_ofs) ;\n                   (* str |-> i *)                  \n                   data_at sh_str tschar (Vbyte i)\n                           (Vptr end'_b str_ofs);                  \n                   (* str + 1 |-> sublist 1 (j + 1) ls *)\n                   data_at sh_str (tarray tschar j)\n                           (map Vbyte (sublist 0 j ls))\n                            (Vptr end'_b str_ofs');                   \n                   (* str + j + 1 |-> sublist (j + 1) |ls'| ls'  *)\n                   data_at sh_str (tarray tschar (Zlength ls - j))\n                           (map Vbyte (sublist j (Zlength ls) ls))\n                           (Vptr end'_b i') ; \n                   data_at sh_end (tptr tschar) (Vptr end'_b end'_ofs)\n                           (Vptr end_b end_ofs) ;\n                   data_at sh_intp tlong v (Vptr intp_b intp_ofs)))\n               \n           break: (EX j : Z, \n                    let b := if Ptrofs.unsigned str_ofs + j + 1 >=? \n                                Ptrofs.unsigned end'_ofs then true else false in\n                    PROP(0 <= j <= Zlength ls;\n                        forall i, 0 <= i < Zlength ls -> \n                             is_digit (Znth i ls) = true;\n                         bounded (value (Z_of_string_loop ls 0 1 b)) = true)\n                    LOCAL(\n                      temp _value (Vlong (Int64.repr (value (Z_of_string_loop ls 0 1 b))));\n                      temp _sign (Vint (Int.repr (if b then -1 else 1)));\n\n                      temp _end (Vptr end_b end_ofs); \n                      temp _intp (Vptr intp_b intp_ofs);\n                      temp _str (Vptr end'_b \n                                 (Ptrofs.add str_ofs \n                                             (Ptrofs.repr (Zlength ls + 1)))))\n\n                    SEP(\n                       valid_pointer (Vptr end'_b (Ptrofs.add str_ofs \n                                                              (Ptrofs.repr (Zlength (i :: ls)))));\n                      valid_pointer (Vptr end'_b end'_ofs);\n                      valid_pointer (Vptr end'_b str_ofs);\n                      data_at sh_str (tarray tschar (Zlength ls + 1)) \n                              (map Vbyte (i::ls)) (Vptr end'_b str_ofs); \n                      data_at sh_end (tptr tschar) (Vptr end'_b end'_ofs) \n                              (Vptr end_b end_ofs);\n                      data_at sh_intp (tlong) v (Vptr intp_b intp_ofs))).\n           (* BREAK IMPLIES THE REST OF THE FUNCTION *)\n           3: \n             { Intro j.\n               forward.\n               forward.\n               entailer!.\n               unfold bounded in *.\n               rewrite andb_true_iff in *.\n               repeat rewrite Z.leb_le in *.\n               break_if.\n               1-2: repeat rewrite Int64.signed_repr;\n               repeat rewrite Int.signed_repr;\n               rep_omega_setup;\n               assert (0 <= value (Z_of_string_loop ls 0 1 true)) by \n               (eapply loop_non_neg; nia);\n               try nia;\n               try rep_omega.\n               forward.\n               erewrite OK_sign_res.\n               all: unfold sign_to_bool.\n               all: try bool_rewrite.\n               simpl.\n               break_if;\n                 autorewrite with sublist; try entailer!;\n               replace (-1 * value (Z_of_string_loop ls 0 1 true))%Z with\n                   (- value (Z_of_string_loop ls 0 1 true)) by nia.\n               try erewrite value_false_eq_neg_value_true0.\n               try entailer!.\n               all: try (eassumption || nia || auto).\n               break_if; try eassumption.\n               eapply bounded_true_to_false; eassumption. }\n           ***\n             Exists 0 0.\n             entailer!.\n             { intros. nia. }\n             autorewrite with sublist.\n             erewrite data_at_zero_array_eq.\n             entailer!.\n             all: try (erewrite sublist_1_cons || autorewrite with sublist);\n               autorewrite with sublist; (reflexivity || auto with zarith || auto).\n           ***\n             Intros j vl.\n             assert (0 <= value_until j ls true 0 1) as NN \n                 by (eapply loop_non_neg; nia).\n              assert (bounded (value_until j ls false 0 1) = true) as BF\n                      by (eapply bounded_true_to_false;\n                 eassumption) .\n               assert (value_until j ls false 0 1 <= 0) as NNF \n                 by (eapply loop_neg; nia).\n               assert (bounded 0 = true) as B0.\n               { unfold bounded.\n                 rewrite andb_true_iff in *.\n                 repeat Zbool_to_Prop.\n                 cbn.\n                 nia. }\n               assert (Int64.min_signed <= value_until j ls true 0 1 <= Int64.max_signed)\n                 as BP by\n               (erewrite bounded_bool_to_Prop in H6; eassumption).\n             forward.\n             forward_if.\n           3:\n             { (* BREAK: str + j + 1 >= end *)\n             forward.\n             rewrite_comparison.\n             replace (Ptrofs.unsigned (Ptrofs.add str_ofs (Ptrofs.repr (j + 1))))\n                     with (Ptrofs.unsigned str_ofs + j + 1) in *\n               by (autorewrite with norm;\n                   ptrofs_compute_add_mul;\n                   rep_omega_setup;\n                   nia).\n             (* post-if implies break condition *)\n             { Exists j.\n               replace (Ptrofs.unsigned str_ofs + j + 1 >=?\n                                                        Ptrofs.unsigned end'_ofs)\n                       with true.\n               replace j with (Zlength ls) in * by nia.\n               replace (Zlength ls + 1) with\n                   (Zlength (i::ls)) by (autorewrite with sublist; nia).\n               erewrite  split_data_at_sublist_tschar with \n                   (ls := i :: ls) (j := 1).\n               autorewrite with sublist.\n               replace (Z.succ (Zlength ls) - 1)\n                           with (Zlength ls) by nia.     \n               \nautorewrite with  sublist in *.\n               entailer!.\n               erewrite data_at_zero_array_eq.\n               entailer!.\n               replace (sublist 1 (Z.succ (Zlength ls)) (i :: ls)) with\n                   ls.\n               erewrite data_at_singleton_array_eq.\n               entailer!.\n               auto.\n               replace (Z.succ (Zlength ls) - 1)\n                 with (Zlength ls) by nia.\n               all: try (erewrite sublist_1_cons || autorewrite with sublist);\n                 autorewrite with sublist; \n                 (reflexivity || auto with zarith || auto).\n               symmetry.\n               erewrite Z.geb_le.\n               nia. }\n             }\n           \n            (* normal: str + j + 1 <  end *)\n           (* pointer comparison *)\n             { unfold test_order_ptrs; simpl.\n               destruct peq; [simpl|contradiction].\n               apply andp_right.\n               destruct (Z_lt_le_dec j (Zlength ls)).\n               * apply derives_trans with (Q := valid_pointer\n                                        (Vptr end'_b (Ptrofs.add str_ofs \n                                                        (Ptrofs.repr (j + 1))))).\n                 entailer!.\n                 apply valid_pointer_weak.\n               * apply derives_trans with \n                     (Q := valid_pointer (Vptr end'_b end'_ofs)).\n                 entailer!.\n                 replace end'_ofs with (Ptrofs.add str_ofs (Ptrofs.repr (j + 1))).\n                 apply valid_pointer_weak.\n                 { autorewrite with sublist in LEN.\n                   replace (Zlength ls) with j in LEN by nia.\n                   assert (Ptrofs.unsigned str_ofs + 1 + j = \n                           Ptrofs.unsigned end'_ofs) by nia.\n                   ptrofs_compute_add_mul.\n                   replace end'_ofs with (Ptrofs.repr (Ptrofs.unsigned end'_ofs))\n                     by auto with ints.\n                   f_equal.\n                   all: rep_omega_setup; try nia. }\n               * apply derives_trans with (Q := valid_pointer (Vptr end'_b end'_ofs)).\n                 entailer!.\n                 apply valid_pointer_weak.\n             }\n             (* str + j + 1 <  end *)\n           { rewrite_comparison.\n             assert (Ptrofs.unsigned (Ptrofs.add str_ofs (Ptrofs.repr (j + 1)))\n                     <? Ptrofs.unsigned end'_ofs = true) as P.\n             erewrite Z.ltb_lt.\n             eassumption.            \n             replace (Ptrofs.unsigned (Ptrofs.add str_ofs (Ptrofs.repr (j + 1)))) \n                           with (Ptrofs.unsigned str_ofs + (j + 1)) in * by\n                 (ptrofs_compute_add_mul;\n                  rep_omega_setup;\n                  nia).\n             assert (j < Zlength ls) as jLS by nia.\n             assert (0 < Zlength (sublist j (Zlength ls) ls)) by\n                  (autorewrite with sublist; nia).\n             (* reading a char i0 *)\n             edestruct sublist_first with (j := j) (ls := ls) as [i0 Sub];\n               try nia.\n             econstructor.\n             instantiate (1 := 0).\n             cbv; easy.\n              assert (Znth j ls = i0) as ZN.\n             { replace (i0 :: sublist (j + 1) (Zlength ls) ls)\n                       with (app [i0] (sublist (j + 1) (Zlength ls) ls))\n                            in Sub.\n               erewrite <- sublist_rejoin' \n                        with (mid := j + 1)\n                             (mid' := j + 1) in Sub.\n               eapply app_inv_tail in Sub.\n               erewrite  sublist_len_1 in Sub.\n               inversion Sub.\n               all: auto.\n               all: try nia. }                   \n             assert (data_at sh_str (tarray tschar (Zlength ls - j))\n                             (map Vbyte (sublist j (Zlength ls) ls))\n                             (Vptr end'_b (Ptrofs.add str_ofs (Ptrofs.repr (j + 1)))) = \n                             data_at sh_str tschar (Vbyte i0)\n                                     (Vptr end'_b (Ptrofs.add str_ofs (Ptrofs.repr (j + 1)))) *\n                             data_at sh_str (tarray tschar\n                                                    (Zlength (sublist (j + 1) (Zlength ls) ls)))\n                                     (map Vbyte (sublist (j + 1) (Zlength ls) ls))\n                                     (Vptr end'_b (Ptrofs.add (Ptrofs.add str_ofs\n                                            (Ptrofs.repr (j + 1))) Ptrofs.one))) as DATA_AT1.\n             { erewrite Sub.\n               replace (Zlength ls - j) with\n                   (Zlength ((i0::(sublist (j + 1) (Zlength ls) ls)))).\n               erewrite split_non_empty_list with \n                   (i := i0) \n                   (ls' := (sublist (j + 1) (Zlength ls) ls))\n                   (ofs := (Ptrofs.add str_ofs (Ptrofs.repr (j + 1)))); \n                 try reflexivity.\n               1-2: autorewrite with sublist;\n                 ptrofs_compute_add_mul;\n                 rep_omega_setup; try nia. }   \n              assert (data_at sh_str (tarray tschar (Zlength ls)) (map Vbyte ls)\n                             (Vptr end'_b (Ptrofs.add str_ofs Ptrofs.one)) =\n                     data_at sh_str (tarray tschar j) (map Vbyte (sublist 0 j ls))\n                             (Vptr end'_b (Ptrofs.add str_ofs Ptrofs.one)) *\n                     data_at sh_str (tarray tschar (Zlength ls - j))\n                             (map Vbyte (sublist j (Zlength ls) ls))\n          (Vptr end'_b (Ptrofs.add str_ofs (Ptrofs.repr (j + 1))))) as DATA_AT2.\n             { replace (Ptrofs.add str_ofs (Ptrofs.repr (j + 1))) with\n                 (Ptrofs.add (Ptrofs.add str_ofs Ptrofs.one) (Ptrofs.repr j)).\n               erewrite <- split_data_at_sublist_tschar; try\n               reflexivity. \n               all: \n                ptrofs_compute_add_mul;\n                replace (Ptrofs.unsigned Ptrofs.one)\n                           with 1 by auto with ptrofs;\n                rep_omega_setup; try (nia || f_equal); try nia. }\n\n             assert (\n               data_at sh_str (tarray tschar (Zlength ls)) (map Vbyte ls)\n                             (Vptr end'_b (Ptrofs.add str_ofs Ptrofs.one)) =\n               data_at sh_str (tarray tschar (j + 1)) (map Vbyte (sublist 0 (j + 1) ls))\n                             (Vptr end'_b (Ptrofs.add str_ofs Ptrofs.one)) *\n                     data_at sh_str (tarray tschar (Zlength ls - (j + 1)))\n                             (map Vbyte (sublist (j + 1) (Zlength ls) ls))\n                             (Vptr end'_b (Ptrofs.add str_ofs (Ptrofs.repr (j + 1 + 1)))))\n             as DATA_AT3.\n             { replace (Ptrofs.add str_ofs (Ptrofs.repr (j + 1 + 1))) \n                 with (Ptrofs.add (Ptrofs.add str_ofs Ptrofs.one) (Ptrofs.repr (j + 1))).\n               erewrite <- split_data_at_sublist_tschar.\n               reflexivity.\n               all: \n                 ptrofs_compute_add_mul;\n                 replace (Ptrofs.unsigned Ptrofs.one)\n                   with 1 by auto with ptrofs;\n                 rep_omega_setup; try (nia || f_equal); try nia. }\n             erewrite DATA_AT1.\n             Intros.\n             forward.\n             forward_if (temp _t'2\n                              (if 48 <=? Byte.signed i0 \n                               then (Val.of_bool (Byte.signed i0 <=? 57))\n                               else  Vfalse)).\n             forward.\n             forward.\n             entailer!.\n             { erewrite Z.ge_le_iff in *.\n               erewrite <- Z.leb_le in *.\n               break_if.\n               replace (negb (Int.lt (Int.repr 57) \n                                     (Int.repr (Byte.signed (Znth j ls)))))\n                 with (Byte.signed (Znth j ls) <=? 57).\n               destruct (Byte.signed (Znth j ls) <=? 57); easy.\n               eapply Zge_bool_Intge.\n               easy. }\n             forward.\n             entailer!.\n             { break_if.\n               try rewrite <- Zle_is_le_bool in *.\n               nia.\n               reflexivity. }\n             \n             forward_if.\n             eapply typed_true_to_digit in H9.\n             pose proof (is_digit_to_Z i0 H9).\n             forward.\n             forward.\n             forward_if.\n            (* Case:  vl < ub *)\n           { lt_ub_to_Z H10; \n             lt_ub_to_Z H11; \n             try nia.\n             forward.\n             entailer!.\n             { repeat rewrite Int64.signed_repr;\n                 try eapply lt_ub_to_next_bounded_Prop;\n                 try eassumption; try nia. }\n             forward.\n             (* show that loop invariant holds after normal  loop body execution *)\n             Exists (j + 1) (value_until (j + 1) ls true 0 1).\n             entailer!.\n             erewrite next_value_lt_ub with (i := Znth j ls).\n             repeat split; try nia.\n             eapply app_is_digit; try nia; try eassumption.\n             apply lt_ub_to_next_bounded_bool.\n             all: try eassumption; try nia; auto.\n             entailer!.\n             erewrite sepcon_assoc.\n             erewrite <- DATA_AT1.\n             rewrite <- DATA_AT2, <- DATA_AT3.\n             entailer!.\n           } \n           lt_ub_to_Z H11.\n             forward_if.\n             lt_ub_to_Z H12.\n\n           (* vl == ub *)\n           { forward_if.\n             lt_ub_to_Z H13.                          \n             (* d <= last_digit_max *)\n             { forward_if \n                 (PROP ( )\n     LOCAL (\n       temp _value (Vlong (Int64.repr \n(- value (Z_of_string_loop (sublist 0 j ls) 0 1 true) * 10 - (Byte.signed i0 - 48))));\n       temp _sign (Vint (Int.repr 1));\n\n       temp _d (Vint (Int.sub (Int.repr (Byte.signed i0)) (Int.repr 48)));\n       temp _t'6 (Vbyte i0);\n       temp _t'2 (if 48 <=? Byte.signed i0 \n                  then Val.of_bool (Byte.signed i0 <=? 57) \n                  else Vfalse);\n       temp _t'7 (Vbyte i0); temp _t'9 (Vptr end'_b end'_ofs); \n       temp _end (Vptr end_b end_ofs);\n       temp _intp (Vptr intp_b intp_ofs);\n       temp _str (Vptr end'_b (Ptrofs.add str_ofs (Ptrofs.repr (j + 1))));\n       \n       temp _upper_boundary (Vlong upper_boundary);\n       temp _last_digit_max (Vlong (Int64.add last_digit_max Int64.one)))\n     SEP (\n       valid_pointer (Vptr end'_b (Ptrofs.add str_ofs (Ptrofs.repr (Zlength (i :: ls)))));\n       valid_pointer (Vptr end'_b str_ofs);\n       valid_pointer (Vptr end'_b end'_ofs);\n       data_at sh_str tschar (Vbyte i) (Vptr end'_b str_ofs);\n       data_at sh_str (tarray tschar j) (map Vbyte (sublist 0 j ls)) (Vptr end'_b str_ofs');\n       data_at sh_str tschar (Vbyte i0) (Vptr end'_b (Ptrofs.add str_ofs (Ptrofs.repr (j + 1))));\n       data_at sh_str (tarray tschar (Zlength (sublist (j + 1) (Zlength ls) ls))) \n               (map Vbyte (sublist (j + 1) (Zlength ls) ls))\n               (Vptr end'_b (Ptrofs.add (Ptrofs.add str_ofs (Ptrofs.repr (j + 1))) Ptrofs.one));\n       data_at sh_end (tptr tschar) (Vptr end'_b end'_ofs) (Vptr end_b end_ofs);\n       data_at sh_intp tlong v (Vptr intp_b intp_ofs))).             \n               (* 0 < s *)\n             easy. \n               (* s = -1 *)\n             forward.\n             forward.\n             entailer!.\n             (*\n               (Eunop Oneg (Etempvar _value tlong) tlong)\n               going through typechecking functions I found where FF comes from:\n               look at isUnOpResultType or just do Compute below to see it.\n              *)\n             Compute (isUnOpResultType Oneg (Etempvar _value tlong) tlong).\n             (* typecheck error: DEBUG THIS *)\n             admit.\n             entailer.\n             forward.\n             forward.\n             forward_if.\n             3: { \n             (* BREAK: str + j + 1 + 1 >= end *)\n             forward.\n             rewrite_comparison.\n             replace (Ptrofs.unsigned\n          (Ptrofs.add (Ptrofs.add str_ofs (Ptrofs.repr (j + 1)))\n             (Ptrofs.mul (Ptrofs.repr 1) (Ptrofs.of_ints (Int.repr 1)))))\n                     with (Ptrofs.unsigned str_ofs + j + 1 + 1) in *\n               by (autorewrite with norm;\n                   ptrofs_compute_add_mul;\n                   rep_omega_setup;\n                   nia).\n             (* post-if implies break condition *)\n             { Exists j.\n               replace (Ptrofs.unsigned str_ofs + j + 1 >=?\n                                                        Ptrofs.unsigned end'_ofs)\n                 with false.\n               entailer!.\n                repeat split; try easy.\n                replace (Zlength ls) with (j + 1) by nia.\n               eapply app_is_digit; try easy.\n               replace ls with (sublist 0 (j + 1) ls).\n               {\n               rewrite next_value_lt_ub with (i := Znth j ls).\n               eapply eq_ub_bounded_minus.\n               eapply loop_neg; nia.\n               apply is_digit_to_Z in H9; assumption.\n               erewrite value_false_eq_neg_value_true0.\n               all: try (nia || eassumption || auto). }\n               replace (j + 1) with (Zlength ls) by nia.\n               autorewrite with sublist; auto.\n\n               do 2 f_equal.\n\n               replace ls with (sublist 0 (j + 1) ls) at 1.\n               rewrite  next_value_lt_ub with (i := Znth j ls).\n               unfold Z_of_char.\n               replace (0) with (-0) by lia.\n               rewrite value_false_eq_neg_value_true.\n               reflexivity.\n               all: try eassumption; try nia; auto.\n               autorewrite with sublist; auto.\n               replace (j + 1) with (Zlength ls) by nia.\n               autorewrite with sublist; auto.\n               erewrite sepcon_assoc.\n               erewrite <- DATA_AT1.\n               erewrite sepcon_assoc.\n               erewrite <- DATA_AT2.\n\n           assert (data_at sh_str tschar (Vbyte i) (Vptr end'_b str_ofs) *\n                    data_at sh_str (tarray tschar (Zlength ls)) (map Vbyte ls)\n                       (Vptr end'_b (Ptrofs.add str_ofs Ptrofs.one)) =\n                       data_at sh_str (tarray tschar (Zlength ls + 1)) (Vbyte i :: map Vbyte ls)\n                       (Vptr end'_b str_ofs)) as DATA_AT4.\n           { erewrite <- split_non_empty_list with (ls := i::ls);\n               autorewrite with sublist in H1;\n               autorewrite with sublist;\n               try reflexivity; try nia.\n           }\n               \n           erewrite DATA_AT4.\n           entailer!.\n           rewrite Z.geb_leb; symmetry; rewrite Z.leb_gt; lia. } } \n             (* compare pointers *)\n             { autorewrite with sublist.\n               unfold test_order_ptrs; simpl.\n               destruct peq; [simpl|contradiction].\n               apply andp_right.\n               destruct (Z_lt_le_dec (j + 1) (Zlength ls)).\n               * apply derives_trans with (Q := valid_pointer\n                                                  (Vptr end'_b\n                                                        (Ptrofs.add\n                                                           (Ptrofs.add\n                                                              str_ofs Ptrofs.one)\n                                                           (Ptrofs.repr (j + 1))))).\n                 entailer!.\n                 replace (Ptrofs.add (Ptrofs.add str_ofs (Ptrofs.repr (j + 1))) Ptrofs.one)\n                   with\n                     (Ptrofs.add (Ptrofs.add str_ofs Ptrofs.one) (Ptrofs.repr (j + 1))).\n                 entailer!.\n                 rewrite Ptrofs.add_assoc.\n                 rewrite Ptrofs.add_assoc.\n                 f_equal.\n                 rewrite Ptrofs.add_commut.\n                 reflexivity.\n                 replace (Ptrofs.add (Ptrofs.add str_ofs Ptrofs.one) (Ptrofs.repr (j + 1)))\n                   with\n                     (Ptrofs.add str_ofs (Ptrofs.repr (j + 1 + 1))).\n                 apply valid_pointer_weak.\n                 replace (Ptrofs.unsigned Ptrofs.one) with 1\n                   by auto with ptrofs.\n                 ptrofs_compute_add_mul;\n                   rep_omega_setup; try nia;\n                      replace (Ptrofs.unsigned Ptrofs.one) with 1\n                   by auto with ptrofs.\n                 f_equal.\n                 all: nia.\n               *  apply derives_trans with (Q := valid_pointer (Vptr end'_b end'_ofs)).\n                 entailer!.\n                 replace end'_ofs with (Ptrofs.add str_ofs (Ptrofs.repr (j + 1 + 1))).\n                 apply valid_pointer_weak.\n                \n                 autorewrite with sublist in LEN.\n                 replace (Zlength ls) with (j + 1) in LEN by nia.\n                 assert (Ptrofs.unsigned str_ofs + j + 1 + 1 = Ptrofs.unsigned end'_ofs)\n                   by nia.\n                 ptrofs_compute_add_mul.\n                 replace end'_ofs with (Ptrofs.repr (Ptrofs.unsigned end'_ofs))\n                   by auto with ints.\n                 f_equal.\n                 all: try (rep_omega_setup; nia).\n               * apply derives_trans with (Q := valid_pointer (Vptr end'_b end'_ofs)).\n                 entailer!.\n                 apply valid_pointer_weak.\n               }\n\n             assert (data_at sh_str tschar (Vbyte i) (Vptr end'_b str_ofs) *\n                          data_at sh_str (tarray tschar (Zlength ls)) (map Vbyte ls)\n                                  (Vptr end'_b (Ptrofs.add str_ofs Ptrofs.one)) =\n                          data_at sh_str (tarray tschar (Zlength ls + 1))\n                                  (Vbyte i :: map Vbyte ls)\n                                  (Vptr end'_b str_ofs)) as DATA_AT4.\n                  { erewrite <- split_non_empty_list with (ls := i::ls);\n                      subst; autorewrite with sublist in H1;\n                      autorewrite with sublist;\n                      try reflexivity; try nia. }\n\n              forward.\n             rewrite_comparison.\n             replace  (Ptrofs.unsigned\n          (Ptrofs.add (Ptrofs.add str_ofs (Ptrofs.repr (j + 1)))\n             (Ptrofs.mul (Ptrofs.repr 1) (Ptrofs.of_ints (Int.repr 1)))))\n                                         with \n                                           (Ptrofs.unsigned str_ofs + j + 1 + 1) in *\n               by (normalize;ptrofs_compute_add_mul;\n                rep_omega_setup;\n               nia).\n             assert (0 < Zlength (sublist (j + 1) (Zlength ls) ls)).\n\n             { subst.               \n               destruct (Z_lt_le_dec (Ptrofs.unsigned str_ofs + j + 1 + 1) Ptrofs.modulus).                       *\n               erewrite Zlength_sublist.\n               all: try nia.\n               *\n                autorewrite with norm in H11.\n                ptrofs_compute_add_mul.\n                all: try (rep_omega_setup;\n               nia).\n               }\n             edestruct sublist_first with (j := j + 1) (ls := ls) as [i1 Sub2];\n               try nia.\n             econstructor.\n             instantiate (1 := 0); cbv; auto.\n\n            assert (data_at sh_str (tarray tschar (Zlength ls - (j + 1)))\n       (map Vbyte (sublist (j + 1) (Zlength ls) ls))\n       (Vptr end'_b (Ptrofs.add (Ptrofs.add str_ofs (Ptrofs.repr (j + 1))) Ptrofs.one)) =\n        data_at sh_str tschar (Vbyte i1)\n       (Vptr end'_b (Ptrofs.add (Ptrofs.add str_ofs (Ptrofs.repr (j + 1))) Ptrofs.one)) *\n     data_at sh_str (tarray tschar (Zlength (sublist (j + 1 + 1) (Zlength ls) ls)))\n       (map Vbyte (sublist (j + 1 + 1) (Zlength ls) ls))\n       (Vptr end'_b\n          (Ptrofs.add (Ptrofs.add (Ptrofs.add str_ofs (Ptrofs.repr (j + 1))) Ptrofs.one)\n             Ptrofs.one))) as DATA_AT5.\n            {         \n            erewrite Sub2.\n             (* reading a char i1 *)\n            replace (Zlength ls - (j + 1)) with \n                (Zlength (i1::(sublist (j + 1 + 1) (Zlength ls) ls))).\n            erewrite split_non_empty_list with\n                 (i := i1) (ls' := (sublist (j + 1 + 1) (Zlength ls) ls))\n                 (ofs :=  (Ptrofs.add (Ptrofs.add str_ofs \n                                                  (Ptrofs.repr (j + 1))) Ptrofs.one));\n             auto.\n            all:      \n              autorewrite with sublist;  \n              ptrofs_compute_add_mul; \n              replace (Ptrofs.unsigned Ptrofs.one)  with 1 by normalize;\n                try (rep_omega_setup;\n               nia). }\n\n            autorewrite with sublist.\n            erewrite  DATA_AT5.\n              (* str + j + 1 < end *)\n             Intros.\n             forward.\n             forward_if  \n               (temp _t'1 (if 48 <=? Byte.signed i1\n                           then Val.of_bool (Byte.signed i1 <=?  57) \n                           else Vfalse)).\n             forward.\n             forward.\n             entailer!.\n             \n             { erewrite Z.ge_le_iff in *.\n               erewrite <- Z.leb_le in *.\n               break_if.\n               replace (negb (Int.lt (Int.repr 57) (Int.repr (Byte.signed i1))))\n                 with (Byte.signed i1 <=? 57).\n               destruct (Byte.signed i1 <=? 57); easy.\n               eapply Zge_bool_Intge.\n               easy. }\n             forward.\n             entailer!.\n               { break_if.\n               try rewrite <- Zle_is_le_bool in *.\n               nia.\n               reflexivity. }\n              \n               assert (Znth (j + 1) ls = i1) as ZN1.\n               { replace (i1 :: sublist (j + 1 + 1) (Zlength ls) ls)\n                   with (app [i1] (sublist (j + 1 + 1) (Zlength ls) ls))\n                   in Sub2.\n                 erewrite <- sublist_rejoin' \n                   with (mid := (j + 1) + 1)\n                        (mid' := (j + 1) + 1)\n                   in Sub2.\n                 eapply app_inv_tail in Sub2.\n                 erewrite  sublist_len_1 in Sub2.\n                 inversion Sub2.\n                 all: auto.\n                 all: try nia.\n               }\n               assert ( 0 <= value_until (j + 1) ls true 0 1) as NN1 by (eapply loop_non_neg; nia).\n\n               forward_if.\n\n                (* ERROR RANGE spec *)\n               {rewrite <- ZN1 in *.\n                rewrite <- ZN in *.\n                eapply typed_true_to_digit in H16.\n                assert (bounded (value_until (j + 1) ls false 0 1) = true) \n                  as Boundf.\n                {  rewrite next_value_lt_ub with (i := Znth j ls).\n                   eapply eq_ub_bounded_minus.\n                   eapply loop_neg; nia.\n                   apply is_digit_to_Z in H9; assumption.\n                   erewrite value_false_eq_neg_value_true0.\n                   all: try nia; try\n                                   assumption; auto. }\n                \n                assert (bounded (value_until ((j + 1) + 1) ls false 0 1) = false) \n                  as BoundF.\n                \n                { \n                  erewrite next_value_lt_ub with \n                      (j := j + 1) (i := (Znth (j + 1) ls)).\n                  \n                  apply lt_ub_not_bounded_minus.\n                  eapply is_digit_to_Z in H16.\n                  nia.\n                  rewrite next_value_lt_ub with (i := Znth j ls).\n                  eapply eq_ub_next_gt_ub_minus.\n                  eapply loop_neg; nia.\n                  eapply is_digit_to_Z in H9.\n                  nia.\n                  erewrite value_false_eq_neg_value_true0.\n                  all: try nia;\n                    try eassumption; auto.\n                  eapply app_is_digit.\n                  all: try nia;\n                    try eassumption; auto. }\n\n                  assert (j + 1 + 1 <= Zlength ls) as LS_len2 by nia.\n\n                  assert (res (Z_of_string_loop ls 0 1 false) = ERROR_RANGE) as Result_loop.\n                  { \n                    assert ((Zlength (sublist 0 (j + 1 + 1) ls))\n                            =  (j + 1 + 1)) as SB\n                        by  (erewrite Zlength_sublist;\n                             subst;\n                             try nia).\n                    edestruct all_digits_OK_or_ERROR_RANGE_loop\n                      with (ls := (sublist 0 (j + 1 + 1) ls)) (v:= 0) (i := 1)\n                    (b := false); try rewrite SB.\n                    eapply app_is_digit;  try rewrite SB;\n                      try nia.\n                    eapply app_is_digit;  try rewrite SB;\n                      try nia.                  \n                    intros.\n                    erewrite Znth_sublist.\n                    normalize.\n                    all: try nia; try eassumption.\n                    all: try erewrite Znth_sublist;\n                      try nia; normalize; subst; try eassumption.\n                    assert (res (Z_of_string_loop (sublist 0 (j + 1 + 1) ls) 0 1 false) = OK).\n                    erewrite H17.\n                    auto.\n                    eapply OK_bounded_loop\n                      with (ls := sublist 0 (j + 1 + 1) ls) (b := false) in H18.\n                    congruence.\n                    eassumption.\n                    eapply sublist_ERROR_RANGE with (j := j + 1 + 1) in H17.\n                    rewrite H17.\n                    auto.\n                    nia. }\n\n                  assert (res (Z_of_string (i :: ls)) = ERROR_RANGE) as Result.\n                  {\n                    simpl.\n                    repeat bool_rewrite.\n                    break_match. \n                    autorewrite with sublist in H2;\n                      try nia.\n                    eassumption.\n                  }                 \n                  assert (index (Z_of_string_loop ls 0 1 false) = j + 1 + 1) as Index_loop.\n                  { eapply ERROR_RANGE_index; try eassumption;\n                      try nia.\n                  }\n                  assert (index (Z_of_string (i :: ls)) = j + 1 + 1) as Index.\n                  {  simpl.\n                    repeat bool_rewrite.\n                    break_match. \n                    autorewrite with sublist in H2;\n                      try nia.\n                    eassumption. }                 \n                  forward.\n                  erewrite Result, Index.\n                  replace (Zlength (i :: ls)) with (Z.succ (Zlength ls)).\n                  entailer!.\n                  autorewrite with sublist in DATA_AT1.\n                  erewrite sepcon_assoc.\n                  erewrite <- DATA_AT5.\n                  erewrite sepcon_assoc.\n                  erewrite <- DATA_AT1.\n                  erewrite sepcon_assoc.\n                  erewrite <- DATA_AT2.\n                  erewrite DATA_AT4.\n                  autorewrite with sublist.\n                  entailer!.\n                  autorewrite with sublist; reflexivity.  }                               \n               forward.\n               forward.\n\n               erewrite EXTRA_DATA_sign_res with (j := j + 1).\n               unfold sign_to_bool.\n               bool_rewrite.\n               simpl.\n                erewrite next_value_lt_ub with (i := (Znth j ls)).\n                erewrite value_false_eq_neg_value_true0.\n               replace (Zlength (i :: ls)) with (Z.succ (Zlength ls))\n                                               by (autorewrite with sublist; nia).\n               entailer!.\n               autorewrite with sublist in DATA_AT1.\n               erewrite sepcon_assoc.\n               erewrite <- DATA_AT5.\n               erewrite sepcon_assoc.\n               erewrite <- DATA_AT1.\n               erewrite sepcon_assoc.\n               erewrite <- DATA_AT2.\n               erewrite DATA_AT4.\n               autorewrite with sublist.\n               entailer!.\n                all: try (eassumption || nia|| auto).\n               eapply app_is_digit.\n                all: try (eassumption || nia || auto).\n                unfold sign_to_bool. bool_rewrite.\n                 {  rewrite next_value_lt_ub with (i := Znth j ls).\n                     eapply eq_ub_bounded_minus.\n                     eapply loop_neg; nia.\n                     \n                     apply is_digit_to_Z in H9; assumption.\n                     erewrite value_false_eq_neg_value_true0.\n                     all: try nia; try\n                     assumption; auto. }\n                 eapply typed_false_to_digit in H16.\n                 eassumption.\n                 }\n             apply is_digit_to_Z in H9.\n             unfold Z_of_char in *.\n             cbn.\n             nia.  \n             (* end of vl = ub && d <= last_digit *)\n\n             (* vl > ub && d > ld, out of range *)\n             { lt_ub_to_Z H13.\n               \n              assert (bounded (value_until (j + 1) ls false 0 1) = false) as Bound.\n               { \n                 erewrite next_value_lt_ub.\n                 eapply  eq_ub_not_bounded_minus.\n                 eapply loop_neg; nia.\n                 eapply is_digit_to_Z; eassumption.\n                 erewrite value_false_eq_neg_value_true0.\n\n                 all:  unfold Z_of_char in *;\n                   try eassumption; try nia. \n               } \n               repeat forward.\n               erewrite ERROR_RANGE_sign_res.\n               simpl.\n               entailer!.\n               { autorewrite with sublist in DATA_AT1.\n                 erewrite sepcon_assoc.    \n                 autorewrite with sublist.\n                  (erewrite <- DATA_AT1). \n                   erewrite sepcon_assoc.    \n                   erewrite <- DATA_AT2.\n                  assert (data_at sh_str tschar (Vbyte i) (Vptr end'_b str_ofs) *\n                          data_at sh_str (tarray tschar (Zlength ls)) (map Vbyte ls)\n                                  (Vptr end'_b (Ptrofs.add str_ofs Ptrofs.one)) =\n                          data_at sh_str (tarray tschar (Zlength ls + 1))\n                                  (Vbyte i :: map Vbyte ls)\n                                  (Vptr end'_b str_ofs)) as DATA_AT4.\n                  { erewrite <- split_non_empty_list with (ls := i::ls);\n                      autorewrite with sublist in H1;\n                      autorewrite with sublist;\n                      try reflexivity; try nia. }\n                  erewrite DATA_AT4.\n                 autorewrite with sublist.\n                 entailer!. }\n                all: try  eapply bounded_bool_to_Prop in H6; \n                 unfold sign_to_bool; try bool_rewrite;\n                 try nia; try eassumption.\n               eapply is_digit_to_Z in H9.\n               unfold Z_of_char in *.\n               cbn.\n               nia. }\n             } (* end of case vl = ub && d > last_digit *)\n           nia.\n           \n             (* case vl > ub *) \n             { \n              lt_ub_to_Z H12.\n              assert (value_until j ls true 0 1 > AbstractSpec.upper_boundary)\n                     by nia.\n              assert (bounded (value_until (j + 1) ls false 0 1) = false) as Bound.\n              { erewrite next_value_lt_ub.\n                eapply lt_ub_not_bounded_minus.\n                eapply is_digit_to_Z; eassumption.\n                erewrite value_false_eq_neg_value_true0.\n                all: unfold Z_of_char in *;\n                  try eassumption; try nia. }                \n               repeat forward.\n              erewrite ERROR_RANGE_sign_res.\n              simpl.\n               entailer!.\n               { \n                erewrite sepcon_assoc.      \n                 erewrite <- DATA_AT1.\n                 erewrite sepcon_assoc.    \n                 erewrite <- DATA_AT2. \n                  assert (data_at sh_str tschar (Vbyte i) (Vptr end'_b str_ofs) *\n                          data_at sh_str (tarray tschar (Zlength ls)) (map Vbyte ls)\n                                  (Vptr end'_b (Ptrofs.add str_ofs Ptrofs.one)) =\n                          data_at sh_str (tarray tschar (Zlength ls + 1))\n                                  (Vbyte i :: map Vbyte ls)\n                                  (Vptr end'_b str_ofs)) as DATA_AT4.\n                  { erewrite <- split_non_empty_list with (ls := i::ls);\n                      autorewrite with sublist in H1;\n                      autorewrite with sublist; \n                      try reflexivity; try nia. }\n                  erewrite DATA_AT4.\n                 autorewrite with sublist.\n                 entailer!. }\n               all: try unfold sign_to_bool; try bool_rewrite; \n                 try eassumption; try nia. }                         \n             nia.\n             (* i0 non-digit: extra data *)\n           { eapply typed_false_to_digit in H9.\n             forward.\n             forward.\n             forward.\n             erewrite EXTRA_DATA_sign_res with (j := j).\n                simpl.\n                unfold sign_to_bool.\n                bool_rewrite.\n                 erewrite value_false_eq_neg_value_true0.\n             entailer!.\n             { erewrite sepcon_assoc.      \n               erewrite <- DATA_AT1.\n               erewrite sepcon_assoc.    \n               erewrite <- DATA_AT2.\n               assert (data_at sh_str tschar (Vbyte i) (Vptr end'_b str_ofs) *\n                       data_at sh_str (tarray tschar (Zlength ls)) (map Vbyte ls)\n                               (Vptr end'_b (Ptrofs.add str_ofs Ptrofs.one)) =\n                       data_at sh_str (tarray tschar (Zlength ls + 1))\n                               (Vbyte i :: map Vbyte ls)\n                               (Vptr end'_b str_ofs)) as DATA_AT4.\n               { erewrite <- split_non_empty_list with (ls := i::ls);\n                   autorewrite with sublist in H1;\n                   autorewrite with sublist;\n                   try reflexivity; try nia. }\n               erewrite DATA_AT4.\n                 autorewrite with sublist.\n                 entailer!. }\n               all: try (nia || eassumption); auto.\n             destruct ((sign_to_bool i)); try eassumption.\n             }\n  }   \n        ** \n        ** admit.\n        * reflexivity.\n        * nia.\n  - (* str >= end *)\n    all: try apply Z.ltb_ge in IFCON.\n    forward_if.\n    (* Valid pointer proof *)\n    { unfold test_order_ptrs; simpl.\n      destruct peq; [simpl|contradiction].\n      apply andp_right.\n      * apply derives_trans with (Q := valid_pointer (Vptr end'_b str_ofs)).\n        entailer!.\n        apply valid_pointer_weak.\n      * apply derives_trans with (Q := valid_pointer (Vptr end'_b end'_ofs)).\n        entailer!.\n        apply valid_pointer_weak. }\n\n    + (* str >= end, return INVAL *)\n      forward.\n      try apply Z.ltb_ge in IFCON.\n      autorewrite with sublist in *|-.\n      try apply Z.ltb_ge in IFCON.\n      assert ((Ptrofs.unsigned end'_ofs - Ptrofs.unsigned str_ofs) <= 0)\n             by nia.\n      assert (Zlength ls = 0) as L by nia.\n      subst.\n      pose proof Zlength_nil_inv ls L as NIL.\n      rewrite NIL; simpl; entailer!.\n    +  (* end' <= str = true || str < end' = true (from forward_if) *)\n      try apply Z.ltb_lt in IFCON.\n      rewrite EQB in H; apply typed_false_ptr_ge in H.\n      rewrite Z.gtb_lt in H. lia.\nAdmitted.\n", "meta": {"author": "asosyuk", "repo": "asn1verification", "sha": "55395d63c2dcd512a28d9cd42d788e12f91e7641", "save_path": "github-repos/coq/asosyuk-asn1verification", "path": "github-repos/coq/asosyuk-asn1verification/asn1verification-55395d63c2dcd512a28d9cd42d788e12f91e7641/doc/strtoimax/C_strtoimax/VstProof/Proof_new.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.287893090017197}}
{"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 Equivalence.\nRequire Import Morphisms.\nRequire Import Setoid.\nRequire Import EquivDec.\nRequire Import Program.\nRequire Import String.\nRequire Import List.\nRequire Import Arith.\nRequire Import DataRuntime.\nRequire Import cNNRC.\nRequire Import cNNRCNorm.\nRequire Import cNNRCEq.\nRequire Import NNRC.\n\nSection NNRCEq.\n  Context {fruntime:foreign_runtime}.\n\n  (** Equivalence between expressions in the Named Nested Relational Calculus *)\n\n  (** Semantics of NNRC *)\n  Definition nnrc_eq (e1 e2:nnrc) : Prop :=\n    forall (h:brand_relation_t),\n    forall (cenv:bindings),\n    forall (env:bindings),\n      Forall (data_normalized h) (map snd cenv) ->\n      Forall (data_normalized h) (map snd env) ->\n      @nnrc_eval _ h cenv env e1 = @nnrc_eval _ h cenv env e2.\n\n  Global Instance nnrc_equiv : Equivalence nnrc_eq.\n  Proof.\n    constructor.\n    - unfold Reflexive, nnrc_eq.\n      intros; reflexivity.\n    - unfold Symmetric, nnrc_eq.\n      intros; rewrite (H h cenv env) by trivial; reflexivity.\n    - unfold Transitive, nnrc_eq.\n      intros; rewrite (H h cenv env) by trivial;\n      rewrite (H0 h cenv env) by trivial; reflexivity.\n  Qed.\n\n  (* all the nnrc constructors are proper wrt. equivalence *)\n\n  (* NNRCGetConstant *)\n  Global Instance proper_NNRCGetConstant : Proper (eq ==> nnrc_eq) NNRCGetConstant.\n  Proof.\n    unfold Proper, respectful, nnrc_eq.\n    intros; rewrite H; reflexivity.\n  Qed.\n\n  (* NNRCVar *)\n  Global Instance proper_NNRCVar : Proper (eq ==> nnrc_eq) NNRCVar.\n  Proof.\n    unfold Proper, respectful, nnrc_eq.\n    intros; rewrite H; reflexivity.\n  Qed.\n\n  (* NNRCConst *)\n  Global Instance proper_NNRCConst : Proper (eq ==> nnrc_eq) NNRCConst.\n  Proof.\n    unfold Proper, respectful, nnrc_eq.\n    intros; rewrite H; reflexivity.\n  Qed.\n\n  (* NNRCBinop *)\n  \n  Global Instance proper_NNRCBinop : Proper (binary_op_eq ==> nnrc_eq ==> nnrc_eq ==> nnrc_eq) NNRCBinop.\n  Proof.\n    generalize proper_cNNRCBinop; intros Hnnrc_core_prop.\n    unfold Proper, respectful, nnrc_eq, nnrc_eval; intros.\n    apply Hnnrc_core_prop; auto.\n  Qed.\n\n  (* NNRCUnnop *)\n\n  Global Instance proper_NNRCUnnop : Proper (unary_op_eq ==> nnrc_eq ==> nnrc_eq) NNRCUnop.\n  Proof.\n    generalize proper_cNNRCUnop; intros Hnnrc_core_prop.\n    unfold Proper, respectful, nnrc_eq, nnrc_eval; intros.\n    apply Hnnrc_core_prop; auto.\n  Qed.\n    \n  (* NNRCLet *)\n  \n  Global Instance proper_NNRCLet : Proper (eq ==> nnrc_eq ==> nnrc_eq ==> nnrc_eq) NNRCLet.\n  Proof.\n    generalize proper_cNNRCLet; intros Hnnrc_core_prop.\n    unfold Proper, respectful, nnrc_eq, nnrc_eval; intros.\n    apply Hnnrc_core_prop; auto.\n  Qed.\n\n  (* NNRCFor *)\n\n  Global Instance proper_NNRCFor : Proper (eq ==> nnrc_eq ==> nnrc_eq ==> nnrc_eq) NNRCFor.\n  Proof.\n    generalize proper_cNNRCFor; intros Hnnrc_core_prop.\n    unfold Proper, respectful, nnrc_eq, nnrc_eval; intros.\n    apply Hnnrc_core_prop; auto.\n  Qed.\n\n  (* NNRCIf *)\n  \n  Global Instance proper_NNRCIf : Proper (nnrc_eq ==> nnrc_eq ==> nnrc_eq ==> nnrc_eq) NNRCIf.\n  Proof.\n    generalize proper_cNNRCIf; intros Hnnrc_core_prop.\n    unfold Proper, respectful, nnrc_eq, nnrc_eval; intros.\n    apply Hnnrc_core_prop; auto.\n  Qed.\n\n  (* NNRCEither *)\n  Global Instance proper_NNRCEither : Proper (nnrc_eq ==> eq ==> nnrc_eq ==> eq ==> nnrc_eq ==> nnrc_eq) NNRCEither.\n  Proof.\n    generalize proper_cNNRCEither; intros Hnnrc_core_prop.\n    unfold Proper, respectful, nnrc_eq, nnrc_eval; intros.\n    apply Hnnrc_core_prop; auto.\n  Qed.\n\n  (* NNRCGroupBy *)\n  Global Instance proper_NNRCGroupBy : Proper (eq ==> eq ==> nnrc_eq ==> nnrc_eq) NNRCGroupBy.\n  Proof.\n    unfold Proper, respectful; intros.\n    unfold nnrc_eq in *.\n    unfold nnrc_eval in *.\n    simpl (nnrc_to_nnrc_base (NNRCGroupBy x x0 x1)).\n    simpl (nnrc_to_nnrc_base (NNRCGroupBy y y0 y1)).\n    subst.\n    unfold nnrc_group_by.\n    intros.\n    simpl.\n    rewrite H1.\n    reflexivity.\n    assumption.\n    assumption.\n  Qed.\n\nEnd NNRCEq.\n\nNotation \"X ≡ᶜ Y\" := (nnrc_eq X Y) (at level 90) : nnrc_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/NNRC/Lang/NNRCEq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.2878845253438698}}
{"text": "(** * Identity adjunction [1 ⊣ 1] *)\nRequire Import Category.Core Functor.Core NaturalTransformation.Core.\nRequire Import Functor.Identity NaturalTransformation.Identity.\nRequire Import Adjoint.UnitCounit Adjoint.Core.\n\nSet Universe Polymorphism.\nSet Implicit Arguments.\nGeneralizable All Variables.\nSet Asymmetric Patterns.\n\nSection identity.\n  (** There is an identity adjunction.  It does the obvious thing. *)\n\n  Definition identity C : @Adjunction C C 1 1\n    := @Build_AdjunctionUnitCounit\n         C C 1 1\n         1\n         1\n         (fun _ => identity_identity _ _)\n         (fun _ => identity_identity _ _).\nEnd identity.\n\nModule Export AdjointIdentityNotations.\n  Notation \"1\" := (identity _) : adjunction_scope.\nEnd AdjointIdentityNotations.\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/Identity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.28788451018631095}}
{"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 angles_vecteurs.\nSet Implicit Arguments.\nUnset Strict Implicit.\n(* Le plan est orienté et on utilise le cercle trigonométrique*)\n\nDefinition repere_orthonormal_direct (O I J : PO) :=\n  image_angle pisurdeux = cons_AV (vec O I) (vec O J) /\\\n  scalaire (vec O I) (vec O I) = 1 /\\ scalaire (vec O J) (vec O J) = 1.\nParameter cos : R -> R.\nParameter sin : R -> R.\nParameter Cos : AV -> R.\nParameter Sin : AV -> R.\n(* cosinus et sinus d'un angle (ou d'un réel) sont obtenus par projections\n   du point image du cercle trigonométrique sur les axes de coordonnées*)\n\nAxiom\n  def_cos :\n    forall (A B C : PO) (x : R),\n    distance A B = 1 ->\n    distance A C = 1 ->\n    image_angle x = cons_AV (vec A B) (vec A C) ->\n    cos x = scalaire (vec A B) (vec A C).\n\nAxiom\n  def_sin :\n    forall (A B C D : PO) (x : R),\n    distance A B = 1 ->\n    distance A C = 1 ->\n    image_angle x = cons_AV (vec A B) (vec A C) ->\n    repere_orthonormal_direct A B D -> sin x = scalaire (vec A C) (vec A D).\n\nAxiom\n  def_Cos :\n    forall A B C : PO,\n    distance A B = 1 ->\n    distance A C = 1 ->\n    Cos (cons_AV (vec A B) (vec A C)) = scalaire (vec A B) (vec A C).\n\nAxiom\n  def_Sin :\n    forall A B C D : PO,\n    distance A B = 1 ->\n    distance A C = 1 ->\n    repere_orthonormal_direct A B D ->\n    Sin (cons_AV (vec A B) (vec A C)) = scalaire (vec A C) (vec A D).\n\nLemma ROND_RON :\n forall O I J : PO,\n repere_orthonormal_direct O I J -> repere_orthonormal O I J.\nunfold repere_orthonormal_direct, repere_orthonormal in |- *; intros.\nelim H; intros H0 H1; try clear H; try exact H1.\nsplit; [ auto with geo | try assumption ].\nQed.\n#[export] Hint Resolve ROND_RON: geo.\n\nDefinition repere_orthonormal_indirect (O I J : PO) :=\n  image_angle pisurdeux = cons_AV (vec O J) (vec O I) /\\\n  scalaire (vec O I) (vec O I) = 1 /\\ scalaire (vec O J) (vec O J) = 1.\n\nLemma ROND_RONI :\n forall O I J : PO,\n repere_orthonormal_direct O I J -> repere_orthonormal_indirect O J I.\nunfold repere_orthonormal_indirect, repere_orthonormal_direct in |- *.\nintros O I J H; try assumption.\nelim H; intros H0 H1; try clear H; try exact H1.\nelim H1; intros H H2; try clear H1; try exact H2.\nsplit; [ auto | split; [ auto | try assumption ] ].\nQed.\n\nLemma ROND_new :\n forall O I J K : PO,\n repere_orthonormal_direct O I J ->\n vec O K = mult_PP (-1) (vec O I) -> repere_orthonormal_direct O J K.\nunfold repere_orthonormal_indirect, repere_orthonormal_direct in |- *.\nintros O I J K H H0; try assumption.\nelim H; intros H1 H2; elim H2; intros H3 H4; try clear H2 H; try exact H4.\ncut (scalaire (vec O K) (vec O K) = 1); intros.\nsplit; [ auto | split; [ auto | try assumption ] ].\nreplace pisurdeux with (- pisurdeux + pi).\ncut (image_angle (- pisurdeux) = cons_AV (vec O J) (vec O I)); intros.\ncut (image_angle pi = cons_AV (vec O I) (vec O K)); intros.\nrewrite add_mes_compatible.\nrewrite H5; rewrite H2; rewrite Chasles; auto with geo.\nreplace (vec O K) with (vec I O).\nrewrite <- angle_plat; auto with geo.\nrewrite H0.\nunfold vec in |- *; RingPP.\napply mes_oppx; auto with geo.\nunfold pi in |- *; ring.\nrewrite H0.\nSimplscal; rewrite H3; ring.\nQed.\n\nLemma existence_ROND_AB :\n forall A B : PO,\n distance A B = 1 -> exists C : PO, repere_orthonormal_direct A B C.\nintros.\nelim\n existence_representant_angle\n  with (A := A) (B := B) (C := A) (x := pisurdeux);\n [ intros C H0; elim H0; intros H1 H2; try clear H0; try exact H2 | auto ].\nexists C; unfold repere_orthonormal_direct in |- *.\nsplit; [ try assumption | idtac ].\nsplit; auto with geo.\nQed.\n\nLemma cos_deux_mes :\n forall x y : R, image_angle x = image_angle y -> cos x = cos y.\nintros.\nelim existence_AB_unitaire; intros A H1; elim H1; intros B H0; try clear H1.\nelim existence_representant_angle with (A := A) (B := B) (C := A) (x := x);\n [ intros C H1; elim H1; intros; try clear H1 | auto ].\nrewrite (def_cos (A:=A) (B:=B) (C:=C) (x:=x)); auto.\nrewrite (def_cos (A:=A) (B:=B) (C:=C) (x:=y)); auto.\nrewrite <- H3; auto.\nQed.\n\nLemma cos_paire : forall x : R, cos (- x) = cos x.\nintros.\nelim existence_AB_unitaire; intros A H; elim H; intros B H0; try clear H;\n try exact H0.\nelim existence_representant_angle with (A := A) (B := B) (C := A) (x := x);\n [ intros C H; elim H; intros H1 H2; try clear H; try exact H2 | auto ].\nrewrite (def_cos (A:=A) (B:=B) (C:=C) (x:=x)); auto.\ncut (image_angle (- x) = cons_AV (vec A C) (vec A B)); intros.\nrewrite (def_cos (A:=A) (B:=C) (C:=B) (x:=- x)); auto.\nrewrite scalaire_sym; auto.\napply mes_oppx; auto with geo.\nQed.\n\nLemma cos_periodique : forall x : R, cos (x + deuxpi) = cos x.\nintros.\nelim existence_AB_unitaire; intros A H; elim H; intros B H0; try clear H;\n try exact H0.\nelim existence_representant_angle with (A := A) (B := B) (C := A) (x := x);\n [ intros C H; elim H; intros H1 H2; try clear H; try exact H2 | auto ].\nrewrite (def_cos (A:=A) (B:=B) (C:=C) (x:=x)); auto.\ncut (image_angle (x + deuxpi) = cons_AV (vec A B) (vec A C)); intros.\nrewrite (def_cos (A:=A) (B:=B) (C:=C) (x:=x + deuxpi)); auto.\napply mesure_mod_deuxpi; auto with geo.\nQed.\n\nLemma sin_deux_mes :\n forall x y : R, image_angle x = image_angle y -> sin x = sin y.\nintros.\nelim existence_AB_unitaire; intros A H1; elim H1; clear H1; intros B H0.\nelim existence_ROND_AB with (A := A) (B := B); [ intros D H10 | auto ].\nelim existence_representant_angle with (A := A) (B := B) (C := A) (x := x);\n [ intros C H1; elim H1; intros; try clear H1 | auto ].\nrewrite (def_sin (A:=A) (B:=B) (C:=C) (D:=D) (x:=x)); auto.\nrewrite (def_sin (A:=A) (B:=B) (C:=C) (D:=D) (x:=y)); auto.\nrewrite <- H3; auto.\nQed.\n\nLemma sin_periodique : forall x : R, sin (x + deuxpi) = sin x.\nintros.\nelim existence_AB_unitaire; intros A H; elim H; intros B H0; try clear H;\n try exact H0.\nelim existence_ROND_AB with (A := A) (B := B); [ intros D H10 | auto ].\nelim existence_representant_angle with (A := A) (B := B) (C := A) (x := x);\n [ intros C H; elim H; intros H1 H2; try clear H; try exact H2 | auto ].\nrewrite (def_sin (A:=A) (B:=B) (C:=C) (D:=D) (x:=x)); auto.\ncut (image_angle (x + deuxpi) = cons_AV (vec A B) (vec A C)); intros.\nrewrite (def_sin (A:=A) (B:=B) (C:=C) (D:=D) (x:=x + deuxpi)); auto.\napply mesure_mod_deuxpi; auto with geo.\nQed.\n\nLemma sin_cos_pisurdeux_moins_x : forall x : R, sin x = cos (pisurdeux + - x).\nintros.\nelim existence_AB_unitaire; intros A H; elim H; intros B H0; try clear H;\n try exact H0.\nelim existence_representant_angle with (A := A) (B := B) (C := A) (x := x);\n [ intros C H; elim H; intros H1 H2; try clear H; try exact H2 | auto ].\nelim existence_ROND_AB with (A := A) (B := B);\n [ intros D H; try exact H | auto ].\nrewrite (def_sin (A:=A) (B:=B) (C:=C) (D:=D) (x:=x)); auto.\ncut (image_angle (- x) = cons_AV (vec A C) (vec A B)); intros.\nreplace (pisurdeux + - x) with (- x + pisurdeux); try ring.\nelim H; intros.\nelim H5; intros H6 H7; try clear H5; try exact H7.\nrewrite (def_cos (A:=A) (B:=C) (C:=D) (x:=- x + pisurdeux)); auto with geo.\nrewrite add_mes_compatible.\nrewrite H3; rewrite H4; rewrite Chasles; auto with geo.\napply mes_oppx; auto with geo.\nQed.\n\nLemma cos_sin_pisurdeux_moins_x : forall x : R, cos x = sin (pisurdeux + - x).\nintros.\nrewrite sin_cos_pisurdeux_moins_x.\nreplace (pisurdeux + - (pisurdeux + - x)) with x; try ring.\nQed.\n\nLemma cos_zero : cos 0 = 1.\nelim existence_AB_unitaire; intros A H; elim H; intros B H0; try clear H;\n try exact H0.\nrewrite (def_cos (A:=A) (B:=B) (C:=B) (x:=0)); auto with geo.\nrewrite <- angle_nul; auto with geo.\nQed.\n\nLemma sin_zero : sin 0 = 0.\nelim existence_AB_unitaire; intros A H; elim H; intros B H0; try clear H;\n try exact H0.\nelim existence_ROND_AB with (A := A) (B := B); [ intros D H | auto ].\nelim H; intros.\nrewrite (def_sin (A:=A) (B:=B) (C:=B) (D:=D) (x:=0)); auto with geo.\nrewrite <- angle_nul; auto with geo.\nQed.\n\nLemma cos_pisurdeux : cos pisurdeux = 0.\nelim existence_AB_unitaire; intros A H; elim H; intros B H0; try clear H;\n try exact H0.\nelim existence_ROND_AB with (A := A) (B := B); [ intros D H | auto ].\nelim H; intros.\nelim H2; intros H3 H4; try clear H2; try exact H4.\nrewrite (def_cos (A:=A) (B:=B) (C:=D) (x:=pisurdeux)); auto with geo.\nQed.\n\nLemma sin_pisurdeux : sin pisurdeux = 1.\nelim existence_AB_unitaire; intros A H; elim H; intros B H0; try clear H;\n try exact H0.\nelim existence_ROND_AB with (A := A) (B := B); [ intros D H | auto ].\nelim H; intros.\nelim H2; intros H3 H4; try clear H2; try exact H4.\nrewrite (def_sin (A:=A) (B:=B) (C:=D) (D:=D) (x:=pisurdeux)); auto with geo.\nQed.\n\nLemma cos_pi : cos pi = -1.\nelim existence_AB_unitaire; intros A H; elim H; intros B H0; try clear H;\n try exact H0.\nelim\n existence_representant_mult_vecteur\n  with (A := A) (B := A) (C := B) (k := -1); intros D H1.\ncut (scalaire (vec A D) (vec A D) = 1); intros.\nrewrite (def_cos (A:=A) (B:=B) (C:=D) (x:=pi)); auto with geo.\nrewrite H1.\nSimplscal; rewrite carre_scalaire_distance; rewrite H0; ring.\nreplace (vec A D) with (vec B A).\nrewrite <- angle_plat; auto with geo.\nrewrite H1.\nRingvec.\nrewrite H1.\nSimplscal; rewrite carre_scalaire_distance; rewrite H0; ring.\nQed.\n\nLemma sin_pi : sin pi = 0.\nelim existence_AB_unitaire; intros A H; elim H; intros B H0; try clear H;\n try exact H0.\nelim existence_ROND_AB with (A := A) (B := B); [ intros D H | auto ].\nelim H; intros.\nelim H2; intros H4 H5; try clear H2; try exact H4.\nelim\n existence_representant_mult_vecteur\n  with (A := A) (B := A) (C := B) (k := -1); intros E H3.\nrewrite (def_sin (A:=A) (B:=B) (C:=E) (D:=D) (x:=pi)); auto.\nrewrite H3.\ncut (scalaire (vec A B) (vec A D) = 0); auto with geo; intros.\nSimplscal; rewrite H2; ring.\ncut (scalaire (vec A E) (vec A E) = 1); auto with geo; intros.\nrewrite H3.\nSimplscal; rewrite H4; ring.\nreplace (vec A E) with (vec B A).\nrewrite <- angle_plat; auto with geo.\nrewrite H3.\nRingvec.\nQed.\n\nLemma coordonnees_cos_sin :\n forall (x : R) (O I J M : PO),\n repere_orthonormal_direct O I J ->\n image_angle x = cons_AV (vec O I) (vec O M) ->\n distance O M = 1 ->\n vec O M = add_PP (mult_PP (cos x) (vec O I)) (mult_PP (sin x) (vec O J))\n :>PP.\nintros.\nelim H; intros.\nelim H3; intros H4 H5; try clear H3; try exact H5.\nrewrite (def_sin (A:=O) (B:=I) (C:=M) (D:=J) (x:=x)); auto with geo.\nrewrite (def_cos (A:=O) (B:=I) (C:=M) (x:=x)); auto with geo.\npattern (vec O M) at 1 in |- *.\nrewrite (coordonnees_scalaire_base (O:=O) (I:=I) (J:=J) M); auto with geo.\nrewrite scalaire_sym; auto.\nQed.\n\nLemma calcul_cos_sin :\n forall (x a b : R) (O I J M : PO),\n repere_orthonormal_direct O I J ->\n image_angle x = cons_AV (vec O I) (vec O M) ->\n distance O M = 1 ->\n vec O M = add_PP (mult_PP a (vec O I)) (mult_PP b (vec O J)) :>PP ->\n a = cos x /\\ b = sin x.\nintros.\napply unicite_coordonnees with (2 := H2); auto with geo.\napply coordonnees_cos_sin; auto.\nQed.\n\nLemma trigo_Pythagore : forall x : R, Rsqr (cos x) + Rsqr (sin x) = 1.\nunfold Rsqr in |- *; intros.\nelim existence_AB_unitaire; intros A H; elim H; intros B H0; try clear H;\n try exact H0.\nelim existence_representant_angle with (A := A) (B := B) (C := A) (x := x);\n [ intros C H; elim H; intros H1 H2; try clear H; try exact H2 | auto ].\nelim existence_ROND_AB with (A := A) (B := B); [ intros D H | auto ].\nelim H; intros.\ncut\n (vec A C = add_PP (mult_PP (cos x) (vec A B)) (mult_PP (sin x) (vec A D)));\n intros.\nreplace 1 with (scalaire (vec A C) (vec A C)); auto with geo.\nrewrite H5.\nSimplscal.\nelim H4; intros H6 H7; try clear H4; try exact H7.\nrewrite H7; rewrite H6.\nrewrite (pisurdeux_scalaire_nul (A:=A) (B:=B) (C:=D)); auto.\nrewrite scalaire_sym.\nrewrite (pisurdeux_scalaire_nul (A:=A) (B:=B) (C:=D)); auto.\nring.\napply coordonnees_cos_sin; auto.\nQed.\n\nLemma pisurdeux_plus_x :\n forall x : R, cos (pisurdeux + x) = - sin x /\\ sin (pisurdeux + x) = cos x.\nintros.\nelim existence_AB_unitaire; intros A H; elim H; intros B H0; try clear H;\n try exact H0.\nelim existence_ROND_AB with (A := A) (B := B); [ intros D H10 | auto ].\nelim\n existence_representant_angle\n  with (A := A) (B := B) (C := A) (x := pisurdeux + x);\n [ intros C H; elim H; intros H1 H2; try clear H; try exact H2 | auto ].\nelim H10; intros.\nelim H3; intros H6 H7; try clear H3; try exact H7.\nelim\n existence_representant_mult_vecteur\n  with (A := A) (B := A) (C := B) (k := -1); intros E H4.\ncut (image_angle x = cons_AV (vec A D) (vec A C)); intros.\ngeneralize\n (coordonnees_cos_sin (x:=pisurdeux + x) (O:=A) (I:=B) (J:=D) (M:=C));\n intros.\ngeneralize (coordonnees_cos_sin (x:=x) (O:=A) (I:=D) (J:=E) (M:=C)); intros.\ncut\n (vec A C = add_PP (mult_PP (- sin x) (vec A B)) (mult_PP (cos x) (vec A D)));\n intros.\napply unicite_coordonnees with (3 := H9); auto with geo.\nrewrite H8; auto.\nrewrite H4.\nunfold vec in |- *; RingPP.\napply ROND_new with B; auto.\nreplace x with (- pisurdeux + (pisurdeux + x)); try ring.\nreplace (cons_AV (vec A D) (vec A C)) with\n (plus (cons_AV (vec A D) (vec A B)) (cons_AV (vec A B) (vec A C))).\nreplace (cons_AV (vec A D) (vec A B)) with (image_angle (- pisurdeux)).\nrewrite <- H2.\napply add_mes_compatible.\napply mes_oppx; auto with geo.\napply Chasles; auto with geo.\nQed.\n\nLemma sin_impaire : forall x : R, sin (- x) = - sin x.\nintros.\nelim pisurdeux_plus_x with (x := - x); intros H H0;\n try clear pisurdeux_plus_x; try exact H.\nreplace (sin (- x)) with (-1 * - sin (- x)).\nrewrite <- H.\nreplace (- x + pisurdeux) with (pisurdeux + - x).\nrewrite <- sin_cos_pisurdeux_moins_x.\nring.\nring.\nring.\nQed.\n\nLemma pi_moins_x :\n forall x : R, cos (pi + - x) = - cos x /\\ sin (pi + - x) = sin x.\nintros.\nunfold pi in |- *.\nreplace (pisurdeux + pisurdeux + - x) with (pisurdeux + (pisurdeux + - x)).\nelim pisurdeux_plus_x with (x := pisurdeux + - x); intros H H0;\n try clear pisurdeux_plus_x; try exact H0.\nrewrite H0; rewrite H.\nsplit; [ try assumption | idtac ].\nrewrite cos_sin_pisurdeux_moins_x; auto.\nrewrite sin_cos_pisurdeux_moins_x; auto.\nring.\nQed.\n\nLemma pi_plus_x :\n forall x : R, cos (pi + x) = - cos x /\\ sin (pi + x) = - sin x.\nintros.\nelim pi_moins_x with (x := - x); intros H H0; try clear pi_moins_x;\n try exact H0.\nreplace (pi + x) with (pi + - - x).\nrewrite H0; rewrite H.\nsplit; [ try assumption | idtac ].\nrewrite cos_paire; auto.\nrewrite sin_impaire; auto.\nring.\nQed.\n\nTheorem cos_diff :\n forall a b : R, cos (a + - b) = cos a * cos b + sin a * sin b.\nintros.\nelim existence_AB_unitaire; intros A H; elim H; intros B H0; try clear H;\n try exact H0.\nelim existence_ROND_AB with (A := A) (B := B); [ intros D H10 | auto ].\nelim existence_representant_angle with (A := A) (B := B) (C := A) (x := a);\n [ intros C H; elim H; intros H1 H2; try clear H; try exact H2 | auto ].\nelim existence_representant_angle with (A := A) (B := B) (C := A) (x := b);\n [ intros E H; elim H; intros H3 H4; try clear H; try exact H4 | auto ].\ngeneralize (coordonnees_cos_sin (x:=a) (O:=A) (I:=B) (J:=D) (M:=C)); intros H.\ngeneralize (coordonnees_cos_sin (x:=b) (O:=A) (I:=B) (J:=D) (M:=E)); intros.\nreplace (cos a * cos b + sin a * sin b) with (scalaire (vec A C) (vec A E)).\ncut (image_angle (a + - b) = cons_AV (vec A E) (vec A C)); intros.\nrewrite (def_cos (A:=A) (B:=E) (C:=C) (x:=a + - b)); auto.\nrewrite scalaire_sym; auto.\nreplace (cons_AV (vec A E) (vec A C)) with\n (plus (cons_AV (vec A E) (vec A B)) (cons_AV (vec A B) (vec A C))).\nreplace (cons_AV (vec A E) (vec A B)) with (image_angle (- b)).\nrewrite <- H2.\nreplace (a + - b) with (- b + a).\napply add_mes_compatible.\nring.\napply mes_oppx; auto with geo.\napply Chasles; auto with geo.\nrewrite H5; auto.\nrewrite H; auto.\nSimplscal.\nelim H10; intros.\nelim H7; intros H8 H9; try clear H7; try exact H9.\ncut (scalaire (vec A B) (vec A D) = 0); auto with geo; intros.\nrewrite H9; rewrite H8; rewrite H7.\nrewrite scalaire_sym; rewrite H7.\nring.\nQed.\n\nLemma cos_som :\n forall a b : R, cos (a + b) = cos a * cos b + - (sin a * sin b).\nintros.\nreplace (a + b) with (a + - - b).\nrewrite (cos_diff a (- b)).\nrewrite cos_paire.\nrewrite sin_impaire.\nring.\nring.\nQed.\n\nLemma sin_som : forall a b : R, sin (a + b) = sin a * cos b + sin b * cos a.\nintros.\nreplace (sin (a + b)) with (cos (pisurdeux + - (a + b))).\nreplace (pisurdeux + - (a + b)) with (pisurdeux + - a + - b).\nrewrite cos_diff.\nrewrite <- sin_cos_pisurdeux_moins_x.\nrewrite <- cos_sin_pisurdeux_moins_x.\nring.\nring.\nrewrite <- sin_cos_pisurdeux_moins_x; auto.\nQed.\n\nLemma sin_diff :\n forall a b : R, sin (a + - b) = sin a * cos b + - (sin b * cos a).\nintros.\nrewrite sin_som.\nrewrite cos_paire.\nrewrite sin_impaire.\nring.\nQed.\n\nLemma duplication_cos : forall a : R, cos (2 * a) = 2 * Rsqr (cos a) + -1.\nintros.\nrepeat rewrite double.\nrewrite cos_som.\nreplace (-1) with (-(1)) by ring.\nrewrite <- (trigo_Pythagore a).\nunfold Rsqr; ring.\nQed.\n\nLemma duplication_cos2 : forall a : R, cos (2 * a) = 1 + - (2 * Rsqr (sin a)).\nintros.\nrepeat rewrite double.\nrewrite cos_som.\nrewrite <- (trigo_Pythagore a).\nunfold Rsqr; ring.\nQed.\n\nLemma duplication_sin : forall a : R, sin (2 * a) = 2 * (sin a * cos a).\nintros.\nrepeat rewrite double.\nrewrite sin_som; auto.\nQed.\n\nLemma coordonnees_polaires_cartesiennes :\n forall (x y a r : R) (O I J M : PO),\n repere_orthonormal_direct O I J ->\n O <> M ->\n r = distance O M ->\n image_angle a = cons_AV (vec O I) (vec O M) ->\n vec O M = add_PP (mult_PP x (vec O I)) (mult_PP y (vec O J)) :>PP ->\n x = r * cos a /\\ y = r * sin a.\nintros.\napply unicite_coordonnees with (2 := H3); auto with geo.\nelim existence_representant_unitaire with (A := O) (B := M);\n [ intros C H4; try clear existence_unitaire; try exact H4 | auto ].\nrewrite (distance_vecteur (A:=O) (B:=M)); auto.\nrewrite <- H4.\nrewrite (coordonnees_cos_sin (x:=a) (O:=O) (I:=I) (J:=J) (M:=C)); auto.\nrewrite <- H1.\nunfold vec in |- *; RingPP.\nrewrite H2.\nrewrite H4.\ninversion H.\nelim H6; intros H7 H8; try clear H6; try exact H7.\nrewrite angles_representants_unitaires; auto with geo.\nreplace (representant_unitaire (vec O I)) with (vec O I); auto with geo.\nelim def_representant_unitaire2 with (A := O) (B := M) (C := C);\n [ intros; elim H6; intros H7 H8; try clear H6 def_representant_unitaire2;\n    auto with geo\n | auto\n | auto ].\nQed.\n\nLemma trivial_cos_Cos :\n forall (A B C : PO) (x : R),\n distance A B = 1 ->\n distance A C = 1 ->\n image_angle x = cons_AV (vec A B) (vec A C) ->\n cos x = Cos (cons_AV (vec A B) (vec A C)).\nintros.\nrewrite (def_cos (A:=A) (B:=B) (C:=C) (x:=x)); auto.\nrewrite (def_Cos (A:=A) (B:=B) (C:=C)); auto.\nQed.\n\nLemma egalite_cos_Cos :\n forall (A B C : PO) (x : R),\n A <> B ->\n A <> C ->\n image_angle x = cons_AV (vec A B) (vec A C) ->\n cos x = Cos (cons_AV (vec A B) (vec A C)).\nintros.\nelim existence_representant_unitaire with (A := A) (B := B);\n [ intros B' H2; try clear existence_representant_unitaire; try exact H2\n | auto ].\nelim existence_representant_unitaire with (A := A) (B := C);\n [ intros C' H3; try clear existence_representant_unitaire; try exact H3\n | auto ].\nrewrite (trivial_cos_Cos (A:=A) (B:=B') (C:=C') (x:=x)); auto.\nrewrite H2; rewrite H3; auto.\nrewrite angles_representants_unitaires; auto.\nelim def_representant_unitaire2 with (A := A) (B := B) (C := B'); auto;\n intros.\nelim H5; auto with geo.\nelim def_representant_unitaire2 with (A := A) (B := C) (C := C'); auto;\n intros.\nelim H5; auto with geo.\nrewrite H2; rewrite H3; rewrite H1; rewrite angles_representants_unitaires;\n auto with geo.\nQed.\n\nLemma trivial_sin_Sin :\n forall (A B C D : PO) (x : R),\n distance A B = 1 ->\n distance A C = 1 ->\n image_angle x = cons_AV (vec A B) (vec A C) ->\n repere_orthonormal_direct A B D -> sin x = Sin (cons_AV (vec A B) (vec A C)).\nintros.\nrewrite (def_sin (A:=A) (B:=B) (C:=C) (D:=D) (x:=x)); auto.\nrewrite (def_Sin (A:=A) (B:=B) (C:=C) (D:=D)); auto.\nQed.\n\nLemma egalite_sin_Sin :\n forall (A B C : PO) (x : R),\n A <> B ->\n A <> C ->\n image_angle x = cons_AV (vec A B) (vec A C) ->\n sin x = Sin (cons_AV (vec A B) (vec A C)).\nintros.\nelim existence_representant_unitaire with (A := A) (B := B);\n [ intros B' H2; try clear existence_representant_unitaire; try exact H2\n | auto ].\nelim existence_ROND_AB with (A := A) (B := B'); [ intros D H10 | auto ].\nelim existence_representant_unitaire with (A := A) (B := C);\n [ intros C' H3; try clear existence_representant_unitaire; try exact H3\n | auto ].\nrewrite (trivial_sin_Sin (A:=A) (B:=B') (C:=C') (D:=D) (x:=x)); auto.\nrewrite H2; rewrite H3; auto.\nrewrite angles_representants_unitaires; auto.\nelim def_representant_unitaire2 with (A := A) (B := B) (C := B'); auto;\n intros.\nelim H5; auto with geo.\nelim def_representant_unitaire2 with (A := A) (B := C) (C := C'); auto;\n intros.\nelim H5; auto with geo.\nrewrite H2; rewrite H3; rewrite H1; rewrite angles_representants_unitaires;\n auto.\nelim def_representant_unitaire2 with (A := A) (B := B) (C := B');\n auto with geo; intros.\nelim H4; auto with geo.\nQed.\n\nLemma coordonnees_Cos_Sin :\n forall O I J M : PO,\n repere_orthonormal_direct O I J ->\n distance O M = 1 ->\n vec O M =\n add_PP (mult_PP (Cos (cons_AV (vec O I) (vec O M))) (vec O I))\n   (mult_PP (Sin (cons_AV (vec O I) (vec O M))) (vec O J)) :>PP.\nintros.\nelim H; intros.\nelim H2; intros H4 H5; try clear H2.\nmesure O I O M.\nrewrite H2.\nrewrite <- (trivial_sin_Sin (A:=O) (B:=I) (C:=M) (D:=J) (x:=x));\n auto with geo.\nrewrite <- (trivial_cos_Cos (A:=O) (B:=I) (C:=M) (x:=x)); auto with geo.\napply coordonnees_cos_sin; auto.\nQed.\n\nLemma calcul_Cos_Sin :\n forall (a b : R) (O I J M : PO),\n repere_orthonormal_direct O I J ->\n distance O M = 1 ->\n vec O M = add_PP (mult_PP a (vec O I)) (mult_PP b (vec O J)) :>PP ->\n a = Cos (cons_AV (vec O I) (vec O M)) /\\\n b = Sin (cons_AV (vec O I) (vec O M)).\nintros.\nelim H; intros.\nelim H3; intros H4 H5; try clear H3.\nmesure O I O M.\nrewrite H3.\nrewrite <- (trivial_sin_Sin (A:=O) (B:=I) (C:=M) (D:=J) (x:=x));\n auto with geo.\nrewrite <- (trivial_cos_Cos (A:=O) (B:=I) (C:=M) (x:=x)); auto with geo.\napply (calcul_cos_sin (x:=x) (a:=a) (b:=b) (O:=O) (I:=I) (J:=J) (M:=M)); auto.\nQed.\n\nAxiom\n  egalite_angle_trigo :\n    forall x y : R,\n    sin x = sin y -> cos x = cos y -> image_angle x = image_angle y.\n\n#[export] Hint Resolve egalite_angle_trigo: geo.\n\nLemma egalite_angle_PiPres_trigo:\n    forall x y :R,\n    sin x = -sin y ->cos x = -cos y -> image_angle x = image_angle (y+pi).\nintros x y H H0.\ndestruct (@pi_plus_x y) as [H1 H2].\nrewrite <-H2 in H.\nrewrite <-H1 in H0.\nreplace (y+pi) with (pi +y);auto with real.\napply egalite_angle_trigo;auto.\nQed.\n", "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/trigo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.2878845101863109}}
{"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                Classical Definition of CCC                          *)\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\nRequire Export Exponents.\nRequire Export CatProperty.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nStructure IsCartesian (C : Category) : Type := \n  {Car_terminal :> Terminal C; Car_BP :> HasBinProd C}.\n\nStructure Cartesian : Type := \n  {Car_Cat :> Category; Prf_isCartesian :> IsCartesian Car_Cat}.\n\nStructure IsCCC (C : Category) : Type := \n  {CCC_isCar :> IsCartesian C; CCC_exponent :> HasExponent CCC_isCar}.\n\n(* CCC Type *)\n\nStructure CCC : Type :=  {CCC_Car :> Cartesian; Prf_isCCC :> IsCCC CCC_Car}.\n\n(*\nVariable C       : CCC.\nVariable a, b, c : C.\n\nLemma Eq_CCC : (Iso (H_expo C a (H_obj_prod C b c)) (H_expo C (H_expo C a b) c)).\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/CATEGORY/CONSTRUCTIONS/CCC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2878216225833632}}
{"text": "\nRequire Import CpdtTactics.\nFrom Coq Require Import Lists.List.\nFrom Coq Require Import Bool.Bool.\nFrom Coq Require Import Sorting.Permutation.\nFrom Coq Require Import Arith.PeanoNat.\nFrom Coq Require Import Arith.Peano_dec.\nFrom Coq Require Import Classes.Equivalence.\nFrom Coq Require Import Strings.String.\nRequire Import Maps.\nRequire NMaps.\nImport ListNotations.\n\nFrom Coq Require Import Relations.Relations.\nFrom Coq Require Import Relations.Relation_Definitions.\nHint Constructors clos_refl_trans_1n.\n\nHint Constructors Permutation.Permutation.\n\nLtac inv H := inversion H; subst; clear H.\nLtac dtr := repeat (match goal with\n                    | [H : _ /\\ _ |- _] => destruct H\n                    | [H : exists _ , _ |- _] => destruct H\n                    end).\nLtac exi := eapply ex_intro.\n\nSet Implicit Arguments.\n\nDefinition key := nat.\nDefinition label := nat.\nDefinition keyset := (list key).\nDefinition result := nat.\n\n(* ***********************frontend *)\n\nInductive type : Type :=\n| Node : type\n| Result : type\n| Keyset : type\n| Label : type -> type\n| Arrow : type -> type -> bool -> type.\nHint Constructors type.\n\nInductive term : Type :=\n| t_var : string -> term\n| t_app : term -> term -> term\n| t_abs : string -> type -> term -> term\n| t_label : label -> term\n| t_result : result -> term\n| t_ks_nil : term\n| t_ks_cons : term -> term -> term\n| t_downarrow : term -> term\n| t_emit_pfold : label -> term -> term -> term -> term\n| t_emit_pmap : label -> term -> term -> term\n| t_emit_add : label -> term -> term -> term\n| t_node : term -> term -> term -> term\n| t_na1 : term -> term\n| t_na2 : term -> term\n| t_na3 : term -> term\n| t_fix : type -> term -> term.\nHint Constructors term.\n\nInductive value : term -> Prop :=\n| v_abs : forall x T t,\n          value (t_abs x T t)\n| v_result : forall result,\n             value (t_result result)\n| v_label : forall label,\n             value (t_label label)\n| v_keyset_nil : value (t_ks_nil)\n| v_keyset_cons : forall k ks,\n                  value k ->\n                  value ks ->\n                  value (t_ks_cons k ks)\n| v_node : forall k p es,\n    value k ->\n    value p ->\n    value es ->\n    value (t_node k p es).\nHint Constructors value.\nDefinition noop : term := t_result 0.\n\nReserved Notation \"'#[' x ':=' s ']' t\" (at level 20).\n\nFixpoint e_subst (x : string) (s : term) (t : term) : term :=\n  match t with\n  | t_var x' =>\n      if eqb_string x x' then s else t\n  | t_abs x' T t1 =>\n      t_abs x' T (if eqb_string x x' then t1 else (#[x:=s] t1))\n  | t_app t1 t2 =>\n      t_app (#[x:=s] t1) (#[x:=s] t2)\n  | t_label l =>\n      t_label l\n  | t_result r =>\n      t_result r\n  | t_ks_nil => t_ks_nil\n  | t_ks_cons k ks =>\n      t_ks_cons (#[x:=s] k) (#[x:=s] ks)\n  | t_downarrow t =>\n      t_downarrow (#[x:=s] t)\n  | t_emit_pfold l t1 t2 t3 =>\n      t_emit_pfold l (#[x:=s] t1) (#[x:=s] t2) (#[x:=s] t3)\n  | t_emit_pmap l t1 t2 =>\n      t_emit_pmap l (#[x:=s] t1) (#[x:=s] t2)\n  | t_emit_add l t1 t2 =>\n      t_emit_add l (#[x:=s] t1) (#[x:=s] t2)\n  | t_node k p es =>\n      t_node (#[x:=s]k) (#[x:=s]p) (#[x:=s]es)\n  | t_na1 t =>\n      t_na1 (#[x:=s]t)\n  | t_na2 t =>\n      t_na2 (#[x:=s]t)\n  | t_na3 t =>\n      t_na3 (#[x:=s]t)\n  | t_fix T t =>\n      t_fix T (#[x:=s] t)\n  end\nwhere \"'#[' x ':=' s ']' t\" := (e_subst x s t).\n\n(* ***********************end frontend *)\n\nDefinition payload := term.\nDefinition edgeset := term.\nHint Unfold edgeset.\n\nInductive node : Type :=\n| N : key -> payload -> edgeset -> node.\nHint Constructors node.\n\nInductive operation : Type :=\n| pmap : term -> keyset -> operation\n| add : key -> payload -> operation\n| pfold : term -> term -> keyset -> operation.\nHint Constructors operation.\n\nDefinition target op :=\nmatch op with\n| pmap _ ks => ks\n| add _ _ => []\n| pfold _ _ ks => ks\nend.\nHint Unfold target.\n\nDefinition not_add op : Prop :=\nmatch op with\n| pmap _ _ => True\n| add _ _ => False\n| pfold _ _ _ => True\nend.\nHint Unfold not_add.\n\nDefinition is_fold op : Prop :=\nmatch op with\n| pmap _ _ => False\n| add _ _ => False\n| pfold _ _ _ => True\nend.\n\nDefinition not_fold_or_done op := (not (is_fold op)) \\/ (exists t1 v t2, op = pfold t1 (t_result v) t2).\nHint Unfold not_fold_or_done.\n\nDefinition final : forall (op : operation), not_fold_or_done op -> result.\nrefine (fun op:operation =>\n        match op return not_fold_or_done op -> result with\n        | pmap _ ks => fun _ => 0\n        | add k _ => fun _ => k\n        | pfold _ (t_result v) _ => fun _ => v\n        | _ => _\n        end).\nintros. exact 1.\nintros. exact 1.\nintros. exact 1.\nintros. exact 1.\nintros. exact 1.\nintros. exact 1.\nintros. exact 1.\nintros. exact 1.\nintros. exact 1.\nintros. exact 1.\nintros. exact 1.\nintros. exact 1.\nintros. exact 1.\nintros. exact 1.\nintros. exact 1.\nDefined.\nHint Unfold final.\n\nInductive labeled_operation : Type :=\n| lo : label -> operation -> labeled_operation.\nHint Constructors labeled_operation.\n\nNotation \"l ->> o\" := (lo l o) (at level 40).\n\nInductive labeled_result : Type :=\n| lr : label -> result -> labeled_result.\nHint Constructors labeled_result.\n\nNotation \"l ->>> r\" := (lr l r) (at level 40).\n\nNotation ostream := (list labeled_operation).\nNotation rstream := (list labeled_result).\n\nInductive station : Type :=\n| St : node -> ostream -> station.\nHint Constructors station.\nNotation \"<< n ; os >>\" := (St n os).\n\nNotation backend := (list station).\n\nInductive config : Type :=\n| C : backend -> ostream -> rstream -> term -> config.\nHint Constructors config.\n\nDefinition get_node (s : station) :=\nmatch s with\n| <<n; _>> => n\nend.\nHint Unfold get_node.\n\nDefinition get_ostream (s : station) :=\nmatch s with\n| <<_; os>> => os\nend.\nHint Unfold get_ostream.\n\nDefinition getKey (n : node) :=\nmatch n with\n  | N k _ _ => k\nend.\nHint Unfold getKey.\n\nDefinition get_payload (n : node) :=\nmatch n with\n  | N _ p _ => p\nend.\nHint Unfold get_payload.\n\n(* ****** typing *)\nDefinition context := partial_map type.\nDefinition lcontext := NMaps.partial_map type.\n\nDefinition nempty {A : Type} := (@NMaps.empty A).\nNotation \"x '#->' v ';' m\" := (NMaps.update m x v) (at level 100, v at next level, right associativity).\n\nInductive has_type : context -> lcontext -> term -> type -> bool -> Prop :=\n| T_Var : forall Gamma ll x T,\n    Gamma x = Some T ->\n    has_type Gamma ll (t_var x) T false\n| T_Abs : forall Gamma ll x T11 T12 t12 E,\n    has_type (x |-> T11 ; Gamma) ll t12 T12 E ->\n    has_type Gamma ll (t_abs x T11 t12) (Arrow T11 T12 E) false\n| T_App : forall T11 T12 Gamma ll t1 t2 E1 E2 E3,\n    has_type Gamma ll t1 (Arrow T11 T12 E1) E2 ->\n    has_type Gamma ll t2 T11 E3 ->\n    has_type Gamma ll (t_app t1 t2) T12 (E1 || E2 || E3)\n| T_Result : forall r Gamma ll,\n    has_type Gamma ll (t_result r) Result false\n| T_KS_Nil : forall Gamma ll,\n    has_type Gamma ll t_ks_nil Keyset false\n| T_KS_Cons : forall k ks Gamma ll E1 E2,\n    has_type Gamma ll k Result E1 ->\n    has_type Gamma ll ks Keyset E2 ->\n    has_type Gamma ll (t_ks_cons k ks) Keyset (E1 || E2)\n| T_Downarrow : forall ft t Gamma ll E,\n    has_type Gamma ll t (Label ft) E ->\n    has_type Gamma ll (t_downarrow t) ft E\n| T_Label : forall l Gamma ll T,\n    ll l = Some T ->\n    has_type Gamma ll (t_label l) (Label T) false\n| T_Emit_PFold : forall l t1 t2 t3 Gamma ll E1 E2 E3,\n    has_type Gamma ll t1 (Arrow Result (Arrow Result Result false) false) E1 ->\n    has_type Gamma ll t2 Result E2 ->\n    has_type Gamma ll t3 Keyset E3 ->\n    has_type Gamma ll (t_emit_pfold l t1 t2 t3) (Label Result) true\n| T_Emit_PMap : forall l t1 t2 Gamma ll E1 E2,\n    has_type Gamma ll t1 (Arrow Result Result false) E1 ->\n    has_type Gamma ll t2 Keyset E2 ->\n    has_type Gamma ll (t_emit_pmap l t1 t2) (Label Result) true\n| T_Emit_Add : forall l t1 t2 Gamma ll E1 E2,\n    has_type Gamma ll t1 Result E1 ->\n    has_type Gamma ll t2 Result E2 ->\n    has_type Gamma ll (t_emit_add l t1 t2) (Label Result) true\n| T_Node : forall k p es Gamma ll E1 E2 E3,\n    has_type Gamma ll k Result E1 ->\n    has_type Gamma ll p Result E2 ->\n    has_type Gamma ll es Keyset E3 ->\n    has_type Gamma ll (t_node k p es) Node (E1 || E2 || E3)\n| T_Na1 : forall t Gamma ll E,\n    has_type Gamma ll t Node E ->\n    has_type Gamma ll (t_na1 t) Result E\n| T_Na2 : forall t Gamma ll E,\n    has_type Gamma ll t Node E ->\n    has_type Gamma ll (t_na2 t) Result E\n| T_Na3 : forall t Gamma ll E,\n    has_type Gamma ll t Node E ->\n    has_type Gamma ll (t_na3 t) Keyset E\n| T_Fix : forall t T Gamma ll E2 E3 E4,\n    has_type Gamma ll t (Arrow (Arrow T T (E2 || E3)) (Arrow T T E2) E3) E4 ->\n    has_type Gamma ll (t_fix T t) (Arrow T T (E2 || E3)) E4.\nHint Constructors has_type.\n\nInductive well_typed_operation : lcontext -> operation -> Prop :=\n| WTO_PFold : forall t1 t2 ks ll,\n    value t1 ->\n    has_type empty ll t1 (Arrow Result (Arrow Result Result false) false) false ->\n    has_type empty ll t2 Result false ->\n    well_typed_operation ll (pfold t1 t2 ks)\n| WTO_PMap : forall t ks ll,\n    value t ->\n    has_type empty ll t (Arrow Result Result false) false ->\n    well_typed_operation ll (pmap t ks)\n| WTO_Add : forall k t ll,\n    has_type empty ll t Result false ->\n    well_typed_operation ll (add k t).\nHint Constructors well_typed_operation.\n\nDefinition op_type (op : operation) : type :=\nmatch op with\n| pmap _ _ => Result\n| add _ _ => Result\n| pfold _ _ _ => Result\nend.\nHint Unfold op_type.\n\nInductive well_typed_top_ostream : lcontext -> lcontext -> ostream -> Prop :=\n| WTTO_nil : forall ll,\n    well_typed_top_ostream ll ll []\n| WTTO_cons : forall l op os ll ll',\n    (match op with\n     | pfold _ t _ => exists r, t = t_result r\n     | _ => True\n     end) ->\n    well_typed_top_ostream (l#->(op_type op);ll) ll' os ->\n    well_typed_operation ll op ->\n    well_typed_top_ostream ll ll' (l ->> op :: os).\nHint Constructors well_typed_top_ostream.\n\nInductive well_typed_ostream : lcontext -> lcontext -> ostream -> Prop :=\n| WTO_nil : forall ll,\n    well_typed_ostream ll ll []\n| WTO_cons : forall l op os ll ll',\n    well_typed_ostream (l#->(op_type op);ll) ll' os ->\n    well_typed_operation ll op ->\n    well_typed_ostream ll ll' (l ->> op :: os).\nHint Constructors well_typed_ostream.\n\nInductive well_typed_backend : lcontext -> lcontext -> backend -> Prop :=\n| WTB_nil : forall ll,\n    well_typed_backend ll ll []\n| WTB_cons : forall k t es os b ll ll' ll'',\n    has_type empty ll' t Result false ->\n    has_type empty ll' es Keyset false ->\n    well_typed_ostream ll' ll'' os ->\n    well_typed_backend ll ll' b ->\n    well_typed_backend ll ll'' (<<N k t es; os>> :: b).\nHint Constructors well_typed_backend.\n\nFixpoint rstream_types (rs : rstream) : lcontext :=\nmatch rs with\n| [] => nempty\n| l ->>> r :: rs => (l#->Result;(rstream_types rs))\nend.\n\nInductive config_has_type : config -> type -> bool -> Prop :=\n| CT : forall b os rs t T E ll ll',\n    well_typed_backend (rstream_types rs) ll b ->\n    well_typed_top_ostream ll ll' os ->\n    has_type empty ll' t T E ->\n    config_has_type (C b os rs t) T E.\nHint Constructors config_has_type.\n\nFixpoint ostream_types (os : ostream) z : lcontext :=\nmatch os with\n| [] => z\n| l ->> op :: os => (l#->(op_type op);ostream_types os z)\nend.\n\nFixpoint backend_types (b : backend) z : lcontext :=\nmatch b with\n| [] => z\n| <<N k t es; os>> :: b => ostream_types os (backend_types b z)\nend.\n\nAxiom fresh_labels : forall (l:label) l', l <> l'.\nHint Immediate fresh_labels.\nAxiom fresh_keys : forall (k:key) k', k <> k'.\nHint Immediate fresh_keys.\n\nLemma ostream_types_zero_lift : forall os l T ll,\n  ostream_types os (l#->T;ll) = (l#->T;(ostream_types os ll)).\nProof using.\n  induction os; intros; auto.\n  - destruct a. crush. apply NMaps.update_permute; auto.\nQed.\nHint Resolve ostream_types_zero_lift.\n\nLemma wt_to_ostream_types : forall os ll ll',\n  well_typed_ostream ll ll' os ->\n  ll' = ostream_types os ll.\nProof using.\n  induction os; intros.\n  - inv H; auto.\n  - destruct a; simpl; inv H; apply IHos in H4. subst. apply ostream_types_zero_lift.\nQed.\nHint Resolve wt_to_ostream_types.\n\nLemma wt_to_top_ostream_types : forall os ll ll',\n  well_typed_top_ostream ll ll' os ->\n  ll' = ostream_types os ll.\nProof using.\n  induction os; intros.\n  - inv H; auto.\n  - destruct a; simpl; inv H; apply IHos in H6. subst. apply ostream_types_zero_lift.\nQed.\nHint Resolve wt_to_top_ostream_types.\n\nLemma wt_to_backend_types : forall b ll ll',\n  well_typed_backend ll ll' b ->\n  ll' = backend_types b ll.\nProof using.\n  induction b; intros.\n  - inv H; auto.\n  - inv H; apply IHb in H7; crush.\nQed.\nHint Resolve wt_to_backend_types.\n\n(* ****** end typing *)\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\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| 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\n(* S_Complete *)\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\nInductive well_typed : config -> Prop :=\n| WT : forall c,\n    distinct (config_keys c) ->\n    distinct (config_labels c) ->\n    (exists T b, config_has_type c T b) ->\n    well_typed c.\nHint Constructors well_typed.\n\nExample wt : well_typed (C [<<(N 1 (t_result 2) t_ks_nil); [5 ->> pmap (t_abs \"x\" Result (t_var \"x\")) []]>>; <<(N 2 (t_result 3) t_ks_nil); [4 ->> pmap (t_abs \"x\" Result (t_var \"x\")) []]>>] [2 ->> pmap (t_abs \"x\" Result (t_var \"x\")) []; 3 ->> pmap (t_abs \"x\" Result (t_var \"x\")) []] [1 ->>> 2] noop).\nProof using.\n  eapply WT; repeat crush; repeat (eapply distinct_many; crush).\n  unfold noop; eauto.\n  exists Result, false.\n  econstructor; eauto.\n  econstructor; eauto.\n  econstructor; eauto.\n  econstructor; eauto.\nQed.\n\nLemma cons_to_app :\n  forall A (x : A) xs,\n  x :: xs = [x] ++ xs.\nProof using.\n  intros.\n  crush.\nQed.\n\nHint Rewrite List.app_assoc.\nHint Rewrite List.app_nil_r.\nHint Rewrite List.app_comm_cons.\n\nDefinition get_config_rstream (c : config) :=\nmatch c with\n| C _ _ rs _ => rs\nend.\nDefinition get_config_backend (c : config) :=\nmatch c with\n| C b _ _ _ => b\nend.\n\nLemma free_in_lcontext : forall l t T E Gamma ll,\n   lappears_free_in l t ->\n   has_type Gamma ll t T E ->\n   exists T', ll l = Some T'.\nProof using.\n  intros x t T E Gamma ll H H0. generalize dependent Gamma.\n  generalize dependent T.\n  generalize dependent E.\n  induction H;\n         intros; try solve [inversion H0; eauto].\nQed.\n\nLtac copy H := let h := fresh \"H\" in assert (h := H).\nLtac capply H1 H2 := copy H2; apply H1 in H2.\nLtac ceapply H1 H2 := copy H2; eapply H1 in H2.\nTactic Notation \"capply\" ident(h1) \"in\" ident(h2) := capply h1 h2.\nTactic Notation \"ceapply\" ident(h1) \"in\" ident(h2) := ceapply h1 h2.\n\nLtac wtbt := match goal with\n             | [H : well_typed_backend _ _ _ |- _] => apply wt_to_backend_types in H; subst\n             end.\nLtac wtost := match goal with\n              | [H : well_typed_ostream _ _ _ |- _] => apply wt_to_ostream_types in H; subst\n              end.\nLtac wttost := match goal with\n               | [H : well_typed_top_ostream _ _ _ |- _] => apply wt_to_top_ostream_types in H; subst\n               end.\nLtac wtbt' := match goal with\n              | [H : well_typed_backend _ _ _ |- _] => copy H; apply wt_to_backend_types in H; subst\n              end.\nLtac wttost' := match goal with\n                | [H : well_typed_top_ostream _ _ _ |- _] => copy H; apply wt_to_top_ostream_types in H; subst\n                end.\nLtac wtost' := match goal with\n               | [H : well_typed_ostream _ _ _ |- _] => copy H; apply wt_to_ostream_types in H; subst\n               end.\n\nLemma result_in_dec : forall rs l, (exists v, In (l ->>> v) rs) \\/ (not (exists v, In (l ->>> v) rs)).\nProof using.\n  induction rs; intros.\n  - right; crush.\n  - destruct IHrs with (l:=l).\n    + left. destruct H. exists x. crush.\n    + destruct a.\n      destruct (Nat.eq_dec l0 l).\n      * subst. left. exists r. crush.\n      * right. intro.\n        destruct H0.\n        apply List.in_inv in H0.\n        {\n        destruct H0.\n        - crush.\n        - apply H. exists x. crush.\n        }\nQed.\n\nLemma op_in_dec : forall os l, (exists op, In (l ->> op) os) \\/ (not (exists op, In (l ->> op) os)).\nProof using.\n  induction os; intros.\n  - right; crush.\n  - destruct IHos with (l:=l).\n    + left. destruct H. exists x. crush.\n    + destruct a.\n      destruct (Nat.eq_dec l0 l).\n      * subst. left. exists o. crush.\n      * right. intro.\n        destruct H0.\n        apply List.in_inv in H0.\n        {\n        destruct H0.\n        - crush.\n        - apply H. exists x. crush.\n        }\nQed.\n\nLemma op_in_backend_dec : forall b l, (exists b1 s b2 op, b = b1 ++ s :: b2 /\\ In (l ->> op) (get_ostream s)) \\/ (not (exists b1 s b2 op, b = b1 ++ s :: b2 /\\ In (l ->> op) (get_ostream s))).\nProof using.\n  induction b; intros.\n  - right; crush. destruct x; crush.\n  - destruct IHb with (l:=l); dtr.\n    + left. exists (a::x), x0, x1, x2. crush.\n    + destruct a.\n      destruct (@op_in_dec l0 l); dtr; eauto.\n      * left. exists [], <<n;l0>>, b, x. eauto.\n      * right. intro; dtr; apply H.\n        {\n        destruct x; simpl in *.\n        - inv H1.\n          exfalso; apply H0; eauto.\n        - inv H1. exists x, x0, x1, x2. eauto.\n        }\nQed.\n\nLemma lcontext_in_or_os : forall os l ll T,\n  (ostream_types os ll) l = Some T ->\n  (exists op, In (l ->> op) os) \\/ ll l = Some T.\nProof using.\n  induction os; intros; auto.\n  destruct a. simpl in H. destruct (Nat.eq_dec l0 l).\n  - left. exi; crush.\n  - replace ((l0#->(op_type o); ostream_types os ll) l) with ((ostream_types os ll) l) in *.\n    destruct (@IHos l ll T); dtr; auto.\n    left; exists x; crush.\n    rewrite NMaps.update_neq; eauto.\nQed.\n\nLemma lcontext_in_or_b : forall b l ll T,\n  (backend_types b ll) l = Some T ->\n  (exists b1 s b2 op, b = b1 ++ s :: b2 /\\ In (l ->> op) (get_ostream s)) \\/ ll l = Some T.\nProof using.\n  induction b; intros; auto.\n  destruct a. destruct n. simpl in H.\n  apply lcontext_in_or_os in H. destruct H; dtr.\n  - left. exists [], <<N k p e; l0>>, b, x. eauto.\n  - apply IHb in H. destruct H; dtr.\n    + left. exists (<<N k p e; l0>> :: x), x0, x1, x2. crush.\n    + eauto.\nQed.\n\nLemma type_in_rstream : forall rs l T,\n  (rstream_types rs) l = Some T ->\n  exists v, In (l ->>> v) rs.\nProof using.\n  induction rs; intros.\n  - inv H.\n  - destruct a. rename l0 into n.\n    destruct (Nat.eq_dec l n); subst.\n    + exists r. crush.\n    + simpl in H.\n      replace ((n#->Result; rstream_types rs) l) with ((rstream_types rs) l) in *.\n      apply IHrs in H; dtr. exists x; crush.\n      rewrite NMaps.update_neq; auto.\nQed.\n\nLemma all_labels : forall t l b os rs,\n    lappears_free_in l t ->\n    well_typed (C b os rs t) ->\n    (exists v, In (l ->>> v) rs) \\/ (exists op, In (l ->> op) os) \\/ (exists op b1 s b2, b = b1 ++ s :: b2 /\\ In (l ->> op) (get_ostream s)).\nProof using.\n  intros.\n  inv H0.\n  destruct H3 as [T[E]].\n  inv H0.\n  eapply free_in_lcontext in H; eauto.\n  destruct H.\n  wtbt.\n  wttost.\n  destruct (@op_in_dec os l); dtr; eauto.\n  destruct (@result_in_dec rs l); dtr; eauto.\n  destruct (@op_in_backend_dec b l); dtr.\n  - right. right. exi; eauto.\n  - exfalso.\n    destruct (@lcontext_in_or_os os l (backend_types b (rstream_types rs)) x); auto.\n    destruct (@lcontext_in_or_b b l (rstream_types rs) x); auto.\n    apply H3.\n    apply type_in_rstream in H6. eauto.\nQed.\n\nLemma cons_app :\n  forall {A: Type} (x : A) xs,\n  x :: xs = [x] ++ xs.\nProof using.\n  crush.\nQed.\n\nLtac ssame := subst; match goal with\n                     | [ H : C _ _ _ _ = C _ _ _ _ |- _ ] => inversion H\n                     end; subst.\nLtac ssame' := subst; match goal with\n                      | [ H : C _ _ _ _ = C _ _ _ _ |- _ ] => inv H\n                      end.\n\nLemma frontend_no_value :\n  forall t rs os t',\n  FRf t rs ==> FRt t' os ->\n  ~ (value t).\nProof using.\n  induction t; intros; try solve [inv H].\n  - intro. inv H0.\n  - inv H.\n    + apply IHt1 in H1. intro. inv H. auto.\n    + apply IHt2 in H6. intro. inv H. auto.\n  - inv H.\n    + intro. inv H.\n    + apply IHt in H1. intro. inv H.\n  - inv H.\n    + intro. inv H.\n    + apply IHt1 in H1. intro. inv H.\n    + apply IHt2 in H8. intro. inv H.\n    + apply IHt3 in H9. intro. inv H.\n  - inv H.\n    + intro. inv H.\n    + apply IHt1 in H1. intro. inv H.\n    + apply IHt2 in H7. intro. inv H.\n  - inv H.\n    + intro. inv H.\n    + apply IHt1 in H1. intro. inv H.\n    + apply IHt2 in H7. intro. inv H.\n  - inv H.\n    + apply IHt1 in H1. intro. inv H. auto.\n    + apply IHt2 in H7. intro. inv H. auto.\n    + apply IHt3 in H8. intro. inv H. auto.\n  - inv H; intro; inv H.\n  - inv H; intro; inv H.\n  - inv H; intro; inv H.\n  - inv H; intro; inv H.\nQed.\n\nLtac narrow_terms := try (match goal with\n                          | [H : value _ |- _] => inv H\n                          end);\n                     try (match goal with\n                          | [H : empty _ = Some _ |- _] => inv H\n                          end);\n                     try solve [match goal with\n                                | [H : has_type _ _ _ _ _ |- _] => inv H\n                                end].\n\n(* ****** typing *)\nLemma canonical_forms_fun : forall t T1 T2 E1 E2 ll,\n  has_type empty ll t (Arrow T1 T2 E1) E2 ->\n  value t ->\n  exists x u, t = t_abs x T1 u.\nProof using.\n  intros t T1 T2 E1 E2 ll HT HVal.\n  inversion HVal; intros; subst; try inversion HT; subst; auto; narrow_terms; eauto.\nQed.\n\nLemma canonical_forms_result : forall t E ll,\n  has_type empty ll t Result E ->\n  value t ->\n  exists r, t = t_result r.\nProof using.\n  destruct t; intros; try solve [inv H0; inv H].\n  eauto.\nQed.\nHint Resolve canonical_forms_result.\n\nLemma canonical_forms_label : forall t E T ll,\n  has_type empty ll t (Label T) E ->\n  value t ->\n  exists l, t = t_label l.\nProof using.\n  destruct t; intros; try solve [inv H0; inv H].\n  eauto.\nQed.\nHint Resolve canonical_forms_label.\n\nInductive dry_backend : backend -> Prop :=\n| dry_backend_empty : dry_backend []\n| dry_backend_cons : forall s b, dry_backend b -> value (get_payload (get_node s)) -> get_ostream s = [] -> dry_backend (s::b).\nHint Constructors dry_backend.\nInductive dry : config -> Prop :=\n| dry_ : forall b rs v, dry_backend b -> value v -> dry (C b [] rs v).\nHint Constructors dry.\n\nLemma dry_backend_dist : forall b b1 b2,\n  b = b1 ++ b2 ->\n  dry_backend b ->\n  dry_backend b1 /\\ dry_backend b2.\nProof using.\n  induction b; intros.\n  - assert (b1 = []). destruct b1. destruct b2. eauto. inv H. inv H.\n    assert (b2 = []). destruct b1. destruct b2. eauto. inv H. inv H.\n    crush.\n  - destruct b1; destruct b2; inv H.\n    + split; eauto.\n    + split; eauto.\n      constructor; inv H0; crush.\n    + split.\n      constructor; inv H0; crush.\n      * apply IHb with (b3:=b1) (b4:=s0::b2) in H2; eauto; crush.\n      * inv H0. apply IHb with (b3:=b1) (b4:=s0::b2) in H2; eauto; crush.\nQed.\n\nLemma dry_no_in : forall b s n os,\n  dry_backend b ->\n  In s b ->\n  s = <<n; os>> ->\n  os = [].\nProof using.\n  induction b; intros.\n  - crush.\n  - crush.\n    + inv H. auto.\n    + inv H. eauto.\nQed.\n\nLemma value_dec : forall t, value t \\/ ~ value t.\nProof using.\n  induction t; try solve [right; intro; inv H1]; try solve [right; intro; inv H]; try solve [left; eauto].\n  - destruct IHt1; destruct IHt2; try solve [eauto]; right; intro; inv H1; eauto.\n  - destruct IHt1; destruct IHt2; destruct IHt3; try solve [eauto]; right; intro; inv H2; eauto.\nQed.\n\nInductive next_reduction : term -> term -> Prop :=\n| nr_app1 : forall t1 t2 t1', not (value t1) -> next_reduction t1 t1' -> next_reduction (t_app t1 t2) t1'\n| nr_app2 : forall t1 t2 t2', value t1 -> not (value t2) -> next_reduction t2 t2' -> next_reduction (t_app t1 t2) t2'\n| nr_app : forall t1 t2, value t1 -> value t2 -> next_reduction (t_app t1 t2) (t_app t1 t2)\n| nr_var : forall x, next_reduction (t_var x) (t_var x)\n| nr_ks_cons1 : forall t1 t2 t1', not (value t1) -> next_reduction t1 t1' -> next_reduction (t_ks_cons t1 t2) t1'\n| nr_ks_cons2 : forall t1 t2 t2', value t1 -> not (value t2) -> next_reduction t2 t2' -> next_reduction (t_ks_cons t1 t2) t2'\n| nr_downarrow : forall t t', not (value t) -> next_reduction t t' -> next_reduction (t_downarrow t) t'\n| nr_downarrow_claim : forall t, value t -> next_reduction (t_downarrow t) (t_downarrow t)\n| nr_emit_pfold1 : forall l t1 t2 t3 t', not (value t1) -> next_reduction t1 t' -> next_reduction (t_emit_pfold l t1 t2 t3) t'\n| nr_emit_pfold2 : forall l t1 t2 t3 t', value t1 -> not (value t2) -> next_reduction t2 t' -> next_reduction (t_emit_pfold l t1 t2 t3) t'\n| nr_emit_pfold3 : forall l t1 t2 t3 t', value t1 -> value t2 -> not (value t3) -> next_reduction t3 t' -> next_reduction (t_emit_pfold l t1 t2 t3) t'\n| nr_emit_pfold : forall l t1 t2 t3, value t1 -> value t2 -> value t3 -> next_reduction (t_emit_pfold l t1 t2 t3) (t_emit_pfold l t1 t2 t3)\n| nr_emit_pmap1 : forall l t1 t2 t', not (value t1) -> next_reduction t1 t' -> next_reduction (t_emit_pmap l t1 t2) t'\n| nr_emit_pmap2 : forall l t1 t2 t', value t1 -> not (value t2) -> next_reduction t2 t' -> next_reduction (t_emit_pmap l t1 t2) t'\n| nr_emit_pmap : forall l t1 t2, value t1 -> value t2 -> next_reduction (t_emit_pmap l t1 t2) (t_emit_pmap l t1 t2)\n| nr_emit_add1 : forall l t1 t2 t', not (value t1) -> next_reduction t1 t' -> next_reduction (t_emit_add l t1 t2) t'\n| nr_emit_add2 : forall l t1 t2 t', value t1 -> not (value t2) -> next_reduction t2 t' -> next_reduction (t_emit_add l t1 t2) t'\n| nr_emit_add : forall l t1 t2, value t1 -> value t2 -> next_reduction (t_emit_add l t1 t2) (t_emit_add l t1 t2)\n| nr_node1 : forall t1 t2 t3 t1', not (value t1) -> next_reduction t1 t1' -> next_reduction (t_node t1 t2 t3) t1'\n| nr_node2 : forall t1 t2 t3 t2', value t1 -> not (value t2) -> next_reduction t2 t2' -> next_reduction (t_node t1 t2 t3) t2'\n| nr_node3 : forall t1 t2 t3 t3', value t1 -> value t2 -> not (value t3) -> next_reduction t3 t3' -> next_reduction (t_node t1 t2 t3) t3'\n| nr_na1 : forall t t', not (value t) -> next_reduction t t' -> next_reduction (t_na1 t) t'\n| nr_na2 : forall t t', not (value t) -> next_reduction t t' -> next_reduction (t_na2 t) t'\n| nr_na3 : forall t t', not (value t) -> next_reduction t t' -> next_reduction (t_na3 t) t'\n| nr_na1_get : forall t, value t -> next_reduction (t_na1 t) (t_na1 t)\n| nr_na2_get : forall t, value t -> next_reduction (t_na2 t) (t_na2 t)\n| nr_na3_get : forall t, value t -> next_reduction (t_na3 t) (t_na3 t)\n| nr_fix : forall t t' T, not (value t) -> next_reduction t t' -> next_reduction (t_fix T t) t'\n| nr_fix_fix : forall t T, value t -> next_reduction (t_fix T t) (t_fix T t).\nHint Constructors next_reduction.\n\nLtac find_type := match goal with\n                 | [H : has_type _ _ _ _ _ |- _] => inv H; eauto\n                 | [H : config_has_type _ _ _ |- _] => inv H; find_type\n                 end.\nLtac easy_wt := inversion WT; split; try split; crush; find_type.\n\nLtac can_fun :=\n    match goal with\n    | [H : has_type empty _ ?t (Arrow _ _ _) _, H' : value ?t |- _] =>\n      let x := fresh \"x\" in let u := fresh \"u\" in apply canonical_forms_fun in H; [|assumption]; destruct H as [x[u]]; subst t\n    end.\n\nLtac can_res :=\n    match goal with\n    | [H : has_type empty _ ?t Result _, H' : value ?t |- _] =>\n      let r := fresh \"r\" in apply canonical_forms_result in H; [|assumption]; destruct H as [r]; subst t\n    end.\n\nLtac can_lab :=\n    match goal with\n    | [H : has_type empty _ ?t (Label _) _, H' : value ?t |- _] =>\n      let l := fresh \"l\" in apply canonical_forms_label in H; [|assumption]; destruct H as [l]; subst t\n    end.\n\nLemma next_reduction_to_reduction' :\n  forall t rs b os t',\n  well_typed (C b os rs t) ->\n  next_reduction t t' ->\n  (exists t'' os', FRf t rs ==> FRt t'' os') \\/ (exists l, t' = t_downarrow (t_label l) /\\ not (exists v, In (l ->>> v) rs)).\nProof using.\n  intros t rs b os t' WT NR.\n  induction NR; subst.\n  - destruct IHNR; dtr; [try solve [easy_wt]| |]; try solve [eauto].\n  - destruct IHNR; dtr; [try solve [easy_wt]| |]; try solve [eauto].\n  - inv WT. dtr. inv H3. inv H12. can_fun. left. eauto.\n  - inv WT; dtr. inv H1. inv H10. inv H4.\n  - destruct IHNR; dtr; [try solve [easy_wt]| |]; try solve [eauto].\n  - destruct IHNR; dtr; [try solve [easy_wt]| |]; try solve [eauto].\n  - destruct IHNR; dtr; [try solve [easy_wt]| |]; try solve [eauto].\n  - inv WT; dtr. inv H2. inv H11. can_lab.\n    destruct (result_in_dec rs l).\n    + destruct H2. eauto.\n    + right. eauto.\n  - destruct IHNR; dtr; [try solve [easy_wt]| |]; try solve [eauto].\n  - destruct IHNR; dtr; [try solve [easy_wt]| |]; try solve [eauto].\n  - destruct IHNR; dtr; [try solve [easy_wt]| |]; try solve [eauto].\n  - eauto.\n  - destruct IHNR; dtr; [try solve [easy_wt]| |]; try solve [eauto].\n  - destruct IHNR; dtr; [try solve [easy_wt]| |]; try solve [eauto].\n  - eauto.\n  - destruct IHNR; dtr; [try solve [easy_wt]| |]; try solve [eauto].\n  - destruct IHNR; dtr; [try solve [easy_wt]| |]; try solve [eauto].\n  - inv WT; dtr. inv H3. inv H12. can_res. can_res.\n    eauto.\n  - destruct IHNR; dtr; [try solve [easy_wt]| |]; try solve [eauto].\n  - destruct IHNR; dtr; [try solve [easy_wt]| |]; try solve [eauto].\n  - destruct IHNR; dtr; [try solve [easy_wt]| |]; try solve [eauto].\n  - destruct IHNR; dtr; [try solve [easy_wt]| |]; try solve [eauto].\n  - destruct IHNR; dtr; [try solve [easy_wt]| |]; try solve [eauto].\n  - destruct IHNR; dtr; [try solve [easy_wt]| |]; try solve [eauto].\n  - inv WT; dtr. inv H2. inv H11. destruct t; narrow_terms. eauto.\n  - inv WT; dtr. inv H2. inv H11. destruct t; narrow_terms. eauto.\n  - inv WT; dtr. inv H2. inv H11. destruct t; narrow_terms; eauto.\n  - destruct IHNR; dtr; [try solve [easy_wt]| |]; try solve [eauto].\n  - eauto.\nUnshelve.\nauto.\nauto.\nQed.\n\nLemma next_reduction_to_reduction :\n  forall t t' rs b os,\n  well_typed (C b os rs t) ->\n  next_reduction t t' ->\n  (exists t'' os', C b os rs t --> C b (os ++ os') rs t'') \\/ (exists l, t' = t_downarrow (t_label l) /\\ not (exists v, In (l ->>> v) rs)).\nProof using.\n  intros t t' rs0 b0 os0 WT NR.\n  apply next_reduction_to_reduction' with (t':=t') in WT; auto. destruct WT; dtr; eauto.\nQed.\n\nLemma term_to_next_reduction :\n  forall t b os rs, well_typed (C b os rs t) -> not (value t) -> exists t', next_reduction t t'.\nProof using.\n  induction t; intros b os rs WT; intros; eauto.\n  - destruct (value_dec t1); destruct (value_dec t2); eauto.\n    + copy H1. eapply IHt2 in H1. destruct H1. eauto. easy_wt.\n    + copy H0. eapply IHt1 in H0. destruct H0. eauto. easy_wt.\n    + copy H0. eapply IHt1 in H0. destruct H0. eauto. easy_wt.\n  - crush.\n  - crush.\n  - crush.\n  - crush.\n  - destruct (value_dec t1); destruct (value_dec t2).\n    + assert (value (t_ks_cons t1 t2)) by eauto; crush.\n    + remember H1. clear Heqn. eapply IHt2 in H1. destruct H1. eauto. easy_wt.\n    + remember H0. clear Heqn. eapply IHt1 in H0. destruct H0. eauto. easy_wt.\n    + remember H0. clear Heqn. eapply IHt1 in H0. destruct H0. eauto. easy_wt.\n  - destruct (value_dec t).\n    + assert (exists l, t = t_label l).\n      {\n        inversion WT; dtr. find_type; narrow_terms.\n      }\n      destruct H1. info_eauto.\n    + remember H0. clear Heqn. eapply IHt in H0. destruct H0. eauto. easy_wt.\n  - destruct (value_dec t1).\n    + destruct (value_dec t2).\n      * {\n        destruct (value_dec t3).\n        - eauto.\n        - remember H2. clear Heqn. eapply IHt3 in H2. destruct H2. eauto. easy_wt.\n        }\n      * remember H1. clear Heqn. eapply IHt2 in H1. destruct H1. eauto. easy_wt.\n    + remember H0. clear Heqn. eapply IHt1 in H0. destruct H0. eauto. easy_wt.\n  - destruct (value_dec t1).\n    + destruct (value_dec t2).\n      * eauto.\n      * remember H1. clear Heqn. eapply IHt2 in H1. destruct H1. eauto. easy_wt.\n    + remember H0. clear Heqn. eapply IHt1 in H0. destruct H0. eauto. easy_wt.\n  - destruct (value_dec t1).\n    + destruct (value_dec t2).\n      * eauto.\n      * remember H1. clear Heqn. eapply IHt2 in H1. destruct H1. eauto. easy_wt.\n    + remember H0. clear Heqn. eapply IHt1 in H0. destruct H0. eauto. easy_wt.\n  - destruct (value_dec t1).\n    + destruct (value_dec t2).\n      * destruct (value_dec t3); [exfalso; apply H; eauto|].\n        ceapply IHt3 in H2; dtr; eauto; easy_wt.\n      * ceapply IHt2 in H1; dtr; eauto; easy_wt.\n    + ceapply IHt1 in H0; dtr; eauto; easy_wt.\n  - destruct (value_dec t).\n    + eauto.\n    + ceapply IHt in H0; dtr. eauto. easy_wt.\n  - destruct (value_dec t).\n    + eauto.\n    + ceapply IHt in H0; dtr. eauto. easy_wt.\n  - destruct (value_dec t).\n    + eauto.\n    + ceapply IHt in H0; dtr. eauto. easy_wt.\n  - destruct (value_dec t0).\n    + eauto.\n    + ceapply IHt in H0; dtr. eauto. easy_wt.\nQed.\n\nLemma well_typed_backend_dist' : forall b b' ll ll',\n  well_typed_backend ll ll' (b ++ b') ->\n  exists ll'', well_typed_backend ll'' ll' b /\\ well_typed_backend ll ll'' b'.\nProof using.\n  induction b; intros.\n  - exists ll'; crush.\n  - simpl in *. inv H. apply IHb in H7; dtr. exi; eauto.\nQed.\nHint Resolve well_typed_backend_dist'.\n\nLemma well_typed_backend_empty : forall ll ll',\n  well_typed_backend ll ll' [] ->\n  ll = ll'.\nProof using.\n  intros; inv H; auto.\nQed.\nHint Resolve well_typed_backend_empty.\n\nLemma well_typed_ostream_empty : forall ll ll',\n  well_typed_ostream ll ll' [] ->\n  ll = ll'.\nProof using.\n  intros; inv H; auto.\nQed.\nHint Resolve well_typed_ostream_empty.\n\nLemma well_typed_backend_dist : forall b b' ll ll' ll'',\n  well_typed_backend ll'' ll' b ->\n  well_typed_backend ll ll'' b' ->\n  well_typed_backend ll ll' (b ++ b').\nProof using.\n  induction b; intros.\n  - replace ll' with ll'' in * by auto; eauto.\n  - simpl; destruct a; destruct n; inv H; econstructor; eauto.\nQed.\nHint Resolve well_typed_backend_dist.\n\nLtac wtbdist := match goal with\n                | [H : well_typed_backend _ _ (_ ++ _) |- _] => apply well_typed_backend_dist' in H; dtr\n                end.\n\nLemma graph_typing : forall b1 b2 os0 rs0 os t0 k t es,\n    well_typed (C (b1 ++ <<N k t es; os>> :: b2) os0 rs0 t0) ->\n    has_type empty (backend_types b2 (rstream_types rs0)) t Result false.\nProof using.\n  intros.\n  inv H.\n  dtr.\n  inv H.\n  wtbdist.\n  inv H2.\n  wtbt.\n  auto.\nQed.\n\nLemma well_typed_ostream_dist' : forall os os' ll ll',\n  well_typed_ostream ll ll' (os ++ os') ->\n  exists ll'', well_typed_ostream ll ll'' os /\\ well_typed_ostream ll'' ll' os'.\nProof using.\n  induction os; intros.\n  - eauto.\n  - simpl in *; destruct a; inv H; apply IHos in H4; dtr; exists x; crush.\nQed.\nHint Resolve well_typed_ostream_dist'.\n\nLemma well_typed_ostream_dist : forall os os' ll ll' ll'',\n  well_typed_ostream ll ll'' os ->\n  well_typed_ostream ll'' ll' os' ->\n  well_typed_ostream ll ll' (os ++ os').\nProof using.\n  induction os; intros.\n  - inv H; subst; auto.\n  - simpl; destruct a; destruct o; constructor; inv H; eauto.\nQed.\nHint Resolve well_typed_ostream_dist.\n\nLtac wtosdist := match goal with\n             | [H : well_typed_ostream _ _ (_ ++ _) |- _] => apply well_typed_ostream_dist' in H; dtr\n             end.\n\nLemma graph_typing' : forall b1 n os l f v ks os' b2 os0 rs0 t0,\n    well_typed (C (b1 ++ <<n; os ++ l ->> pfold f v ks :: os'>> :: b2) os0 rs0 t0) ->\n    has_type empty (ostream_types os (backend_types b2 (rstream_types rs0))) v Result false.\nProof using.\n  intros.\n  inv H; dtr.\n  inv H.\n  wtbdist.\n  inv H2.\n  wtosdist.\n  inv H3.\n  inv H15.\n  wtbt.\n  wtost.\n  wtost.\n  auto.\nQed.\n\nLemma well_typed_top_ostream_dist : forall os os' ll ll' ll'',\n  well_typed_top_ostream ll ll'' os ->\n  well_typed_top_ostream ll'' ll' os' ->\n  well_typed_top_ostream ll ll' (os ++ os').\nProof using.\n  induction os; intros.\n  - inv H; auto.\n  - simpl; destruct a; destruct o; constructor; inv H; eauto.\nQed.\nHint Resolve well_typed_top_ostream_dist.\n\nLemma well_typed_top_ostream_dist' : forall os os' ll ll',\n  well_typed_top_ostream ll ll' (os ++ os') ->\n  exists ll'', well_typed_top_ostream ll ll'' os /\\ well_typed_top_ostream ll'' ll' os'.\nProof using.\n  induction os; intros.\n  - eauto.\n  - simpl in *; destruct a; inv H; apply IHos in H6; dtr; exists x; crush.\nQed.\nHint Resolve well_typed_top_ostream_dist'.\n\nLtac wttosdist := match goal with\n                  | [H : well_typed_top_ostream _ _ (_ ++ _) |- _] => apply well_typed_top_ostream_dist' in H; dtr\n                  end.\n\nLemma graph_typing''' : forall b os l f v ks os' rs0 t0,\n    well_typed (C b (os ++ l ->> pfold f v ks :: os') rs0 t0) ->\n    has_type empty (ostream_types os (rstream_types rs0)) v Result false.\nProof using.\n  intros.\n  inv H; dtr.\n  inv H.\n  wttosdist.\n  inv H2; dtr; subst; auto.\nQed.\n\nLemma graph_typing'' : forall b1 n os l f v ks os' b2 os0 rs0 t0,\n    well_typed (C (b1 ++ <<n; os ++ l ->> pfold f v ks :: os'>> :: b2) os0 rs0 t0) ->\n    has_type empty (ostream_types os (backend_types b2 (rstream_types rs0))) f (Arrow Result (Arrow Result Result false) false) false.\nProof using.\n  intros.\n  inv H; dtr.\n  inv H.\n  wtbdist.\n  inv H2.\n  wtosdist.\n  inv H3.\n  inv H15.\n  wtbt.\n  wtost.\n  wtost.\n  auto.\nQed.\n\nLemma value_no_emit : forall v Gamma ll T E,\n  has_type Gamma ll v T E ->\n  value v ->\n  E = false.\nProof using.\n  induction v; intros; try solve [inv H0]; try solve [inv H; eauto]; eauto.\n  - inv H0. inv H. apply IHv1 in H6; auto. apply IHv2 in H9; auto. subst. auto.\n  - inv H0. inv H. apply IHv1 in H8; auto. apply IHv2 in H11; auto. apply IHv3 in H12; auto. subst. auto.\nQed.\n\nLemma emittability' : forall t T t' rs os ll,\n  has_type empty ll t T false ->\n  FRf t rs ==> FRt t' os ->\n  os = [].\nProof using.\n  induction t; intros T t' rs os ll HHT Hstep.\n  - inv Hstep.\n  - inv Hstep.\n    + auto.\n    + inv HHT.\n      eapply IHt1 in H0; eauto.\n      destruct E1; destruct E2; destruct E3; try solve [inv H4]; eauto.\n    + inv HHT.\n      eapply IHt2 in H5; eauto.\n      destruct E1; destruct E2; destruct E3; try solve [inv H4]; eauto.\n  - exfalso; apply frontend_no_value in Hstep; eauto.\n  - exfalso; apply frontend_no_value in Hstep; eauto.\n  - exfalso; apply frontend_no_value in Hstep; eauto.\n  - exfalso; apply frontend_no_value in Hstep; eauto.\n  - inv Hstep.\n    + inv HHT.\n      eapply IHt1 in H0; eauto.\n      destruct E1; destruct E2; try solve [inv H4]; eauto.\n    + inv HHT.\n      eapply IHt2 in H5; eauto.\n      destruct E1; destruct E2; try solve [inv H4]; eauto.\n  - inv Hstep.\n    + auto.\n    + eapply IHt in H0; eauto.\n      inv HHT. eauto.\n  - inv Hstep; inv HHT.\n  - inv Hstep; inv HHT.\n  - inv Hstep; inv HHT.\n  - inv Hstep; inv HHT.\n    + eapply IHt1 in H0; eauto.\n      destruct E1; destruct E2; destruct E3; try solve [inv H5]; eauto.\n    + eapply IHt2 in H6; eauto.\n      destruct E1; destruct E2; destruct E3; try solve [inv H5]; eauto.\n    + eapply IHt3 in H7; eauto.\n      destruct E1; destruct E2; destruct E3; try solve [inv H5]; eauto.\n  - inv Hstep; inv HHT; eauto.\n  - inv Hstep; inv HHT; eauto.\n  - inv Hstep; inv HHT; eauto.\n  - inv Hstep; inv HHT; eauto.\nQed.\n\nLemma list_not_cons_self : forall {A : Type} (x : A) xs,\n    x :: xs = xs -> False.\nProof using.\n  induction xs; crush.\nQed.\nHint Resolve list_not_cons_self.\n\nLemma list_not_cons_self' : forall {A : Type} (x : A) xs,\n  xs ++ [x] = xs -> False.\nProof using.\n  induction xs; crush.\nQed.\nHint Resolve list_not_cons_self'.\n\nLemma list_app_self_nil : forall {A : Type} (xs : list A) ys,\n  xs = xs ++ ys -> ys = [].\nProof using.\n  induction xs; crush.\nQed.\nHint Resolve list_app_self_nil.\n\nLemma emittability : forall t T b os rs t' os' ll,\n  has_type empty ll t T false ->\n  C b os rs t --> C b (os ++ os') rs t' ->\n  os' = [].\nProof using.\n  intros t T b os rs t' os' ll HHT Hstep.\n  inv Hstep; ssame'; try solve [exfalso; eauto]; try solve [eauto].\n  - eapply emittability' in H5; eauto.\n    apply List.app_inv_head in H0; subst; auto.\nQed.\n\nLemma nr_to_lafi : forall t l,\n  next_reduction t (t_downarrow (t_label l)) ->\n  lappears_free_in l t.\nProof using.\n  induction t; intros; inv H; try solve [apply IHt1 in H4; auto]; try solve [apply IHt2 in H5; auto]; try solve [apply IHt3 in H6; auto]; try solve [apply IHt in H2; auto].\n  - auto.\n  - apply IHt1 in H6; auto.\n  - apply IHt2 in H7; auto.\n  - apply IHt3 in H8; auto.\n  - apply IHt1 in H5; auto.\n  - apply IHt2 in H6; auto.\n  - apply IHt1 in H5; auto.\n  - apply IHt2 in H6; auto.\n  - apply IHt1 in H5; auto.\n  - apply IHt2 in H6; auto.\n  - apply IHt3 in H7; auto.\n  - apply IHt in H4; auto.\nQed.\n\nLemma dependent_load_after : forall k t es l c b1 b2 os os0 rs0 term0,\n  c = C (b1 ++ <<N k t es; os>> :: b2) os0 rs0 term0 ->\n  next_reduction t (t_downarrow (t_label l)) ->\n  well_typed c ->\n  (exists v, In (l ->>> v) rs0) \\/ (exists n' op b2' b2'' os'', b2 = b2' ++ <<n'; os''>> :: b2'' /\\ In (l ->> op) os'').\nProof using.\n  intros; subst.\n  inv H1; dtr.\n  inv H1.\n  wtbdist.\n  inv H3.\n  apply nr_to_lafi in H0.\n  eapply free_in_lcontext in H12; eauto.\n  dtr.\n  wtbt.\n  apply lcontext_in_or_b in H3; destruct H3; dtr.\n  - right. destruct x4. exists n, x6, x3, x5, l0. eauto.\n  - left. apply type_in_rstream in H3; auto.\nQed.\n\nLemma dependent_loadpfold_after : forall l' l c b1 b2 t1 t2 t3 n os os' os0 rs0 term0,\n  c = C (b1 ++ <<n; os ++ l' ->> pfold t1 t2 t3 :: os'>> :: b2) os0 rs0 term0 ->\n  next_reduction t2 (t_downarrow (t_label l)) ->\n  well_typed c ->\n  (exists v, In (l ->>> v) rs0) \\/ (exists op, In (l ->> op) os) \\/ (exists n' op b2' b2'' os'', b2 = b2' ++ <<n'; os''>> :: b2'' /\\ In (l ->> op) os'').\nProof using.\n  intros; subst.\n  inv H1; dtr.\n  inv H1.\n  wtbdist.\n  inv H3.\n  wtosdist.\n  inv H4.\n  inv H16.\n  apply nr_to_lafi in H0.\n  eapply free_in_lcontext with (l:=l) in H17; eauto; dtr.\n  wtbt.\n  wtost.\n  wtost.\n  apply lcontext_in_or_os in H4; destruct H4; dtr; eauto.\n  - apply lcontext_in_or_b in H3; destruct H3; dtr; eauto.\n    + right. right. destruct x2. exists n, x5, x1, x4, l0. eauto.\n    + left. apply type_in_rstream in H3; auto.\nQed.\n\nLemma distinct_deduce1 : forall b l os os' rs,\n  distinct (backend_labels b ++ l :: ostream_labels os ++ ostream_labels os' ++ rstream_labels rs) ->\n  distinct (rstream_labels rs).\nProof using.\n  intros.\n  apply distinct_concat in H; dtr.\n  apply distinct_remove in H0; dtr.\n  apply distinct_concat in H0; dtr.\n  apply distinct_concat in H2; dtr.\n  auto.\nQed.\nHint Resolve distinct_deduce1.\n\nLemma distinct_deduce2 : forall l os os' rs,\n  distinct (l :: ostream_labels os ++ ostream_labels os' ++ rstream_labels rs) ->\n  distinct (rstream_labels rs).\nProof using.\n  intros.\n  apply distinct_remove in H; dtr.\n  apply distinct_concat in H; dtr.\n  apply distinct_concat in H1; dtr.\n  auto.\nQed.\nHint Resolve distinct_deduce2.\n\nLemma op_reduction_exists : forall c b b1 b2 rs0 os0 term0 k t es os l op,\n  well_typed c ->\n  c = C b os0 rs0 term0 ->\n  b = b1 ++ <<N k t es; l ->> op :: os>> :: b2 ->\n  exists c', C b os0 rs0 term0 --> c'.\nProof using.\n  intros c b b1 b2 rs0 os0 term0 k t es os l op WT Hceq Hbeq.\n  destruct op; subst. rename k0 into l0.\n  - destruct (List.in_dec Nat.eq_dec k l0).\n    + eapply ex_intro; eapply S_PMap; eauto.\n    + destruct b2.\n      * eapply ex_intro; eapply S_Last; eauto.\n      * destruct s. eapply ex_intro; eapply S_Prop; eauto; crush.\n  - destruct b2.\n    + eapply ex_intro; eapply S_Last; eauto.\n    + destruct s. eapply ex_intro; eapply S_Prop; eauto; crush.\n  - rename k0 into l0.\n    destruct (List.in_dec Nat.eq_dec k l0).\n    + eapply ex_intro; eapply S_PFold; eauto.\n      Unshelve.\n      auto.\n      auto.\n    + destruct b2.\n      * {\n        destruct (value_dec t1).\n        - assert (has_type empty (rstream_types rs0) t1 Result false) by (eapply graph_typing' with (os:=[]) (b2:=[]); eauto).\n          destruct t1; try solve [inv H]; try solve [inv H0].\n          eapply ex_intro; eapply S_Last; eauto.\n          Unshelve.\n          right; eauto.\n        - rename H into HNV. eapply term_to_next_reduction with (b:=[]) (os:=[]) (rs:=rs0) in HNV.\n          + dtr. copy H. rename H0 into HNR. apply next_reduction_to_reduction' with (b:=[]) (os:=[]) (rs:=rs0) (t:=t1) in H.\n            * {\n              destruct H; dtr.\n              - exi. eapply S_LoadPFold with (b1:=b1) (b2:=[]) (os:=[]) (t1:=t1) (t1':=x0); eauto. crush.\n                assert (x1 = []).\n                {\n                  eapply emittability' in H; eauto.\n                  instantiate (1:=Result).\n                  instantiate (1:=rstream_types rs0).\n                  inv WT; dtr. inv H2. apply well_typed_backend_dist' in H9; dtr.\n                  inv H3. inv H15. inv H9. wtbt. auto.\n                }\n                subst.\n                auto.\n              - subst. eapply dependent_loadpfold_after with (os:=[]) (b2:=[]) in HNR.\n                + destruct HNR.\n                  * exfalso; eauto.\n                  * {\n                    destruct H.\n                    - dtr. exfalso. auto.\n                    - dtr. exfalso. destruct x2; inv H.\n                    }\n                + instantiate (1:=term0).\n                  instantiate (1:=os0).\n                  instantiate (1:=os).\n                  instantiate (1:=l0).\n                  instantiate (1:=t0).\n                  instantiate (1:=l).\n                  instantiate (1:=N k t es).\n                  instantiate (1:=b1).\n                  auto.\n                + auto.\n              }\n            * inv WT; dtr. inv H2. wtbdist. inv H3. inv H15. inv H9. split; try split; eauto.\n              crush. crush. eauto.\n          + inv WT; dtr. split; try split; eauto. crush. crush. apply distinct_concat in H0; dtr.\n            eauto.\n            inv H1. wtbdist. inv H2. inv H14. inv H8. eauto.\n        }\n      * destruct s. eapply ex_intro; eapply S_Prop; eauto; crush.\nQed.\n\nLemma ll_update : forall t Gamma l T' ll T E,\n  has_type Gamma ll t T E ->\n  has_type Gamma (l #-> T'; ll) t T E.\nProof using.\n  induction t; intros; try solve [inv H; eauto].\n  - inv H. assert (l0 <> l) by (apply fresh_labels). constructor.\n    replace ((l0#->T';ll) l) with (ll l); auto.\n    rewrite NMaps.update_neq; auto.\nQed.\nHint Resolve ll_update.\n\nLemma ht_ostream_extension : forall os ll t T E,\n  has_type empty ll t T E ->\n  has_type empty (ostream_types os ll) t T E.\nProof using.\n  induction os; intros; auto.\n  destruct a; simpl.\n  apply IHos in H; eauto.\nQed.\nHint Resolve ht_ostream_extension.\n\nLemma ht_backend_extension : forall b ll t T E,\n  has_type empty ll t T E ->\n  has_type empty (backend_types b ll) t T E.\nProof using.\n  induction b; intros; auto.\n  destruct a; destruct n; simpl.\n  apply IHb in H; eauto.\nQed.\nHint Resolve ht_backend_extension.\n\nLemma ll_extract_ostream : forall os l T ll,\n    ostream_types os (l#->T;ll) = (l#->T;ostream_types os ll).\nProof using.\n  induction os; intros; auto.\nQed.\n\nLemma ll_extract_backend : forall b l T ll,\n    backend_types b (l#->T;ll) = (l#->T;backend_types b ll).\nProof using.\n  induction b; intros; auto.\n  destruct a; destruct n; simpl.\n  rewrite <- ll_extract_ostream. rewrite IHb. auto.\nQed.\n\nLemma ll_swap_ostream_backend : forall os b ll,\n  ostream_types os (backend_types b ll) = backend_types b (ostream_types os ll).\nProof using.\n  induction os; intros; auto.\n  destruct a; simpl. rewrite ll_extract_backend. crush.\nQed.\n\nLemma ll_swap_backend : forall b b' ll,\n  backend_types b (backend_types b' ll) = backend_types b' (backend_types b ll).\nProof using.\n  induction b; intros; auto.\n  destruct a; destruct n; simpl. rewrite IHb. rewrite ll_swap_ostream_backend. auto.\nQed.\n\nLemma ht_ostream_extract : forall os ll l T' t T E,\n  has_type empty (ostream_types os (l#->T';ll)) t T E ->\n  has_type empty (l#->T';ostream_types os ll) t T E.\nProof using.\n  induction os; intros; auto.\n  destruct a; simpl in *.\n  repeat (rewrite ll_extract_ostream in H). rename l0 into n.\n  replace (n #-> op_type o; l #-> T'; ostream_types os ll)\n          with (l#->T';n #-> op_type o; ostream_types os ll) in H.\n  auto.\n  apply NMaps.update_permute; apply fresh_labels.\nQed.\n\nLemma ht_ostream_extract' : forall os ll l T' t T E,\n  has_type empty (l#->T';ostream_types os ll) t T E ->\n  has_type empty (ostream_types os (l#->T';ll)) t T E.\nProof using.\n  induction os; intros; auto.\n  destruct a; simpl in *.\n  repeat (rewrite ll_extract_ostream). rename l0 into n.\n  replace (n #-> op_type o; l #-> T'; ostream_types os ll)\n          with (l#->T';n #-> op_type o; ostream_types os ll).\n  auto.\n  apply NMaps.update_permute; apply fresh_labels.\nQed.\n\nLemma ht_ostream_extension' : forall os l T' ll t T E,\n  has_type empty (ostream_types os ll) t T E ->\n  has_type empty (ostream_types os (l#->T';ll)) t T E.\nProof using.\n  intros.\n  apply ht_ostream_extract'. auto.\nQed.\nHint Resolve ht_ostream_extension'.\n\nLemma ht_backend_extract' : forall b ll l T' t T E,\n  has_type empty (l#->T';backend_types b ll) t T E ->\n  has_type empty (backend_types b (l#->T';ll)) t T E.\nProof using.\n  induction b; intros; auto.\n  destruct a; destruct n; simpl in *.\n  rewrite ll_extract_backend.\n  rewrite ll_extract_ostream.\n  auto.\nQed.\n\nLemma ht_backend_extension' : forall b l T' ll t T E,\n  has_type empty (backend_types b ll) t T E ->\n  has_type empty (backend_types b (l#->T';ll)) t T E.\nProof using.\n  intros.\n  apply ht_backend_extract'. auto.\nQed.\nHint Resolve ht_backend_extension'.\n\nLemma wt_operation_extension : forall ll l T op,\n  well_typed_operation ll op ->\n  well_typed_operation (l#->T;ll) op.\nProof using.\n  intros.\n  inv H; econstructor; eauto.\nQed.\nHint Resolve wt_operation_extension.\n\nLemma wt_ostream_build : forall os ll ll',\n  well_typed_ostream ll ll' os ->\n  well_typed_ostream ll (ostream_types os ll) os.\nProof using.\n  induction os; intros; auto.\n  destruct a; simpl in *.\n  wtost'. simpl in *. auto.\nQed.\n\nLemma wt_ostream_extension : forall os ll ll' l T,\n  well_typed_ostream ll ll' os ->\n  exists ll'', well_typed_ostream (l#->T;ll) ll'' os.\nProof using.\n  induction os; intros; eauto.\n  destruct a; simpl in *. inv H. eapply IHos with (l:=l) (T:=T) in H4; dtr.\n  wtost'. exi. econstructor; eauto.\n  eapply wt_ostream_build.\n  destruct o; simpl in *;\n  replace (l0 #-> Result; l #-> T; ll) with (l#->T;l0 #-> Result;ll); eauto; apply NMaps.update_permute; apply fresh_labels.\nQed.\nHint Resolve wt_ostream_extension.\n\nLemma wt_ostream_backend_extract' : forall b os ll ll' l T,\n  well_typed_ostream (l#->T;backend_types b ll) ll' os ->\n  exists ll'', well_typed_ostream (backend_types b (l#->T;ll)) ll'' os.\nProof using.\n  induction b; intros; eauto.\n  destruct a; destruct n; simpl in *.\n  wtost'.\n  rewrite ll_extract_backend.\n  rewrite ll_extract_ostream.\n  eauto.\nQed.\n\nLemma wt_ostream_backend_extension' : forall b os l T ll ll',\n  well_typed_ostream (backend_types b ll) ll' os ->\n  exists ll'', well_typed_ostream (backend_types b (l#->T;ll)) ll'' os.\nProof using.\n  intros.\n  eapply wt_ostream_extension with (l:=l) (T:=T) in H; dtr.\n  eapply wt_ostream_backend_extract'. eauto.\nQed.\nHint Resolve wt_ostream_backend_extension'.\n\nLemma wt_backend_build : forall b ll ll',\n  well_typed_backend ll ll' b ->\n  well_typed_backend ll (backend_types b ll) b.\nProof using.\n  induction b; intros; auto.\n  destruct a; destruct n; simpl in *.\n  wtbt'. simpl in *. auto.\nQed.\n\nLemma wt_backend_extension : forall b ll ll' l T,\n  well_typed_backend ll ll' b ->\n  exists ll'', well_typed_backend (l#->T;ll) ll'' b.\nProof using.\n  induction b; intros; eauto.\n  destruct a; destruct n; simpl in *.\n  inv H.\n  wtbt'. wtost'.\n  eapply IHb with (l:=l) (T:=T) in H; dtr.\n  exists (ostream_types l0 (backend_types b (l#->T;ll))).\n  econstructor. Focus 4.\n  - eauto.\n  - wtbt. wtost. eauto.\n  - wtbt. wtost. eauto.\n  - wtbt'. wtost'. apply wt_ostream_extension with (l:=l) (T:=T) in H; dtr.\n    eapply wt_ostream_build.\n    rewrite ll_extract_backend. eauto.\nQed.\nHint Resolve wt_backend_extension.\n\nLemma load_exists : forall c b b1 b2 rs0 os0 term0 k t es os,\n  well_typed c ->\n  c = C b os0 rs0 term0 ->\n  b = b1 ++ <<N k t es; os>> :: b2 ->\n  not (value t) ->\n  exists c', C b os0 rs0 term0 --> c'.\nProof using.\n  intros c b b1 b2 rs0 os0 term0 k t es os WT Hceq Hbeq HNV.\n  assert (has_type empty (backend_types b2 (rstream_types rs0)) t Result false) by (subst; eapply graph_typing; eauto).\n  destruct t; try solve [inv H; inv H3].\n  - eapply term_to_next_reduction in HNV; subst; dtr.\n    + copy H0. rename H1 into HNR. eapply next_reduction_to_reduction' with (rs:=rs0) in H0.\n      * {\n        destruct H0; dtr.\n        - assert (x1 = []) by (eapply emittability'; eauto); subst.\n          exi. eapply S_Load; eauto.\n        - subst.\n          edestruct dependent_load_after with (c:=C (b1 ++ << N k (t_app t1 t2) es; os >> :: b2) os0 rs0 term0) (l:=x0); eauto; dtr.\n          + exfalso; eauto.\n          + apply List.in_split in H2; dtr.\n            subst.\n            replace ((b1 ++ << N k (t_app t1 t2) es; os >> :: x2 ++ << x; x5 ++ x0 ->> x1 :: x6 >> :: x3))\n                    with (((b1 ++ << N k (t_app t1 t2) es; os >> :: x2) ++ << x; x5 ++ x0 ->> x1 :: x6 >> :: x3)) by crush.\n            destruct x. destruct x5; simpl.\n            * eapply op_reduction_exists; eauto. crush.\n            * destruct l. eapply op_reduction_exists; eauto. crush.\n        }\n      * instantiate (1:=os0).\n        instantiate (1:=b1 ++ << N k (t_app t1 t2) es; os >> :: b2).\n        inv WT; dtr.\n        split; try split; eauto.\n        inv H3.\n        exists Result, false.\n        econstructor.\n        eauto.\n        eauto.\n        wtbdist.\n        inv H4.\n        wtbt.\n        wtbt.\n        wtost.\n        wttost.\n        auto.\n    + instantiate (1:=rs0).\n      instantiate (1:=os0).\n      instantiate (1:=b1 ++ << N k (t_app t1 t2) es; os >> :: b2).\n      inv WT; dtr.\n      split; try split; eauto.\n      inv H2.\n      exists Result, false.\n      econstructor.\n      eauto.\n      eauto.\n      wtbdist.\n      inv H3.\n      wtbt.\n      wtbt.\n      wtost.\n      wttost.\n      auto.\n  - exfalso. auto.\n  - eapply term_to_next_reduction in HNV; subst; dtr.\n    + copy H0. rename H1 into HNR. eapply next_reduction_to_reduction' with (rs:=rs0) in H0.\n      * {\n        destruct H0; dtr.\n        - assert (x1 = []) by (eapply emittability'; eauto); subst.\n          exi. eapply S_Load; eauto.\n        - subst.\n          edestruct dependent_load_after with (c:=C (b1 ++ << N k (t_downarrow t) es; os >> :: b2) os0 rs0 term0) (l:=x0); eauto; dtr.\n          + exfalso; eauto.\n          + apply List.in_split in H2; dtr.\n            subst.\n            replace ((b1 ++ << N k (t_downarrow t) es; os >> :: x2 ++ << x; x5 ++ x0 ->> x1 :: x6 >> :: x3))\n                    with (((b1 ++ << N k (t_downarrow t) es; os >> :: x2) ++ << x; x5 ++ x0 ->> x1 :: x6 >> :: x3)) by crush.\n            destruct x. destruct x5; simpl.\n            * eapply op_reduction_exists; eauto. crush.\n            * destruct l. eapply op_reduction_exists; eauto. crush.\n        }\n      * instantiate (1:=os0).\n        instantiate (1:=(b1 ++ << N k (t_downarrow t) es; os >> :: b2)).\n        inv WT; dtr.\n        split; try split; eauto.\n        inv H3.\n        exists Result, false.\n        econstructor.\n        eauto.\n        eauto.\n        wtbdist.\n        inv H4.\n        wtbt.\n        wtbt.\n        wtost.\n        wttost.\n        auto.\n    + instantiate (1:=rs0).\n      instantiate (1:=os0).\n      instantiate (1:=(b1 ++ << N k (t_downarrow t) es; os >> :: b2)).\n      inv WT; dtr.\n      split; try split; eauto.\n      inv H2.\n      exists Result, false.\n      econstructor.\n      eauto.\n      eauto.\n      wtbdist.\n      inv H3.\n      wtbt.\n      wtbt.\n      wtost.\n      wttost.\n      auto.\n  - eapply term_to_next_reduction in HNV; subst; dtr.\n    + copy H0. rename H1 into HNR. eapply next_reduction_to_reduction' with (rs:=rs0) in H0.\n      * {\n        destruct H0; dtr.\n        - assert (x1 = []) by (eapply emittability'; eauto); subst.\n          exi. eapply S_Load; eauto.\n        - subst.\n          edestruct dependent_load_after with (c:=C (b1 ++ << N k (t_na1 t) es; os >> :: b2) os0 rs0 term0) (l:=x0); eauto; dtr.\n          + exfalso; eauto.\n          + apply List.in_split in H2; dtr.\n            subst.\n            replace ((b1 ++ << N k (t_na1 t) es; os >> :: x2 ++ << x; x5 ++ x0 ->> x1 :: x6 >> :: x3))\n                    with (((b1 ++ << N k (t_na1 t) es; os >> :: x2) ++ << x; x5 ++ x0 ->> x1 :: x6 >> :: x3)) by crush.\n            destruct x. destruct x5; simpl.\n            * eapply op_reduction_exists; eauto. crush.\n            * destruct l. eapply op_reduction_exists; eauto. crush.\n        }\n      * instantiate (1:=os0).\n        instantiate (1:=(b1 ++ << N k (t_na1 t) es; os >> :: b2)).\n        inv WT; dtr.\n        split; try split; eauto.\n        inv H3.\n        exists Result, false.\n        econstructor.\n        eauto.\n        eauto.\n        wtbdist.\n        inv H4.\n        wtbt.\n        wtbt.\n        wtost.\n        wttost.\n        auto.\n    + instantiate (1:=rs0).\n      instantiate (1:=os0).\n      instantiate (1:=(b1 ++ << N k (t_na1 t) es; os >> :: b2)).\n      inv WT; dtr.\n      split; try split; eauto.\n      inv H2.\n      exists Result, false.\n      econstructor.\n      eauto.\n      eauto.\n      wtbdist.\n      inv H3.\n      wtbt.\n      wtbt.\n      wtost.\n      wttost.\n      auto.\n  - eapply term_to_next_reduction in HNV; subst; dtr.\n    + copy H0. rename H1 into HNR. eapply next_reduction_to_reduction' with (rs:=rs0) in H0.\n      * {\n        destruct H0; dtr.\n        - assert (x1 = []) by (eapply emittability'; eauto); subst.\n          exi. eapply S_Load; eauto.\n        - subst.\n          edestruct dependent_load_after with (c:=C (b1 ++ << N k (t_na2 t) es; os >> :: b2) os0 rs0 term0) (l:=x0); eauto; dtr.\n          + exfalso; eauto.\n          + apply List.in_split in H2; dtr.\n            subst.\n            replace ((b1 ++ << N k (t_na2 t) es; os >> :: x2 ++ << x; x5 ++ x0 ->> x1 :: x6 >> :: x3))\n                    with (((b1 ++ << N k (t_na2 t) es; os >> :: x2) ++ << x; x5 ++ x0 ->> x1 :: x6 >> :: x3)) by crush.\n            destruct x. destruct x5; simpl.\n            * eapply op_reduction_exists; eauto. crush.\n            * destruct l. eapply op_reduction_exists; eauto. crush.\n        }\n      * instantiate (1:=os0).\n        instantiate (1:=(b1 ++ << N k (t_na2 t) es; os >> :: b2)).\n        inv WT; dtr.\n        split; try split; eauto.\n        inv H3.\n        exists Result, false.\n        econstructor.\n        eauto.\n        eauto.\n        wtbdist.\n        inv H4.\n        wtbt.\n        wtbt.\n        wtost.\n        wttost.\n        auto.\n    + instantiate (1:=rs0).\n      instantiate (1:=os0).\n      instantiate (1:=(b1 ++ << N k (t_na2 t) es; os >> :: b2)).\n      inv WT; dtr.\n      split; try split; eauto.\n      inv H2.\n      exists Result, false.\n      econstructor.\n      eauto.\n      eauto.\n      wtbdist.\n      inv H3.\n      wtbt.\n      wtbt.\n      wtost.\n      wttost.\n      auto.\nQed.\n\nLemma cht_app1 : forall b os rs t1 t2 T E,\n  config_has_type (C b os rs (t_app t1 t2)) T E ->\n  exists T' E', config_has_type (C b os rs t1) T' E'.\nProof using.\n  intros. inv H. inv H8. eauto.\nQed.\nHint Resolve cht_app1.\n\nLemma cht_app2 : forall b os rs t1 t2 T E,\n  config_has_type (C b os rs (t_app t1 t2)) T E ->\n  exists T' E', config_has_type (C b os rs t2) T' E'.\nProof using.\n  intros. inv H. inv H8. eauto.\nQed.\nHint Resolve cht_app2.\n\nLemma cht_ks1 : forall b os rs t1 t2 T E,\n  config_has_type (C b os rs (t_ks_cons t1 t2)) T E ->\n  exists T' E', config_has_type (C b os rs t1) T' E'.\nProof using.\n  intros. inv H. inv H8. eauto.\nQed.\nHint Resolve cht_ks1.\n\nLemma cht_ks2 : forall b os rs t1 t2 T E,\n  config_has_type (C b os rs (t_ks_cons t1 t2)) T E ->\n  exists T' E', config_has_type (C b os rs t2) T' E'.\nProof using.\n  intros. inv H. inv H8. eauto.\nQed.\nHint Resolve cht_ks2.\n\nLemma cht_downarrow : forall b os rs t T E,\n  config_has_type (C b os rs (t_downarrow t)) T E ->\n  exists T' E', config_has_type (C b os rs t) T' E'.\nProof using.\n  intros. inv H. inv H8. eauto.\nQed.\nHint Resolve cht_downarrow.\n\nLemma cht_pfold1 : forall b os rs l t1 t2 t3 T E,\n  config_has_type (C b os rs (t_emit_pfold l t1 t2 t3)) T E ->\n  exists T' E', config_has_type (C b os rs t1) T' E'.\nProof using.\n  intros. inv H. inv H8. eauto.\nQed.\nHint Resolve cht_pfold1.\n\nLemma cht_pfold2 : forall b os rs l t1 t2 t3 T E,\n  config_has_type (C b os rs (t_emit_pfold l t1 t2 t3)) T E ->\n  exists T' E', config_has_type (C b os rs t2) T' E'.\nProof using.\n  intros. inv H. inv H8. eauto.\nQed.\nHint Resolve cht_pfold2.\n\nLemma cht_pfold3 : forall b os rs l t1 t2 t3 T E,\n  config_has_type (C b os rs (t_emit_pfold l t1 t2 t3)) T E ->\n  exists T' E', config_has_type (C b os rs t3) T' E'.\nProof using.\n  intros. inv H. inv H8. eauto.\nQed.\nHint Resolve cht_pfold3.\n\nLemma cht_pmap1 : forall b os rs l t1 t2 T E,\n  config_has_type (C b os rs (t_emit_pmap l t1 t2)) T E ->\n  exists T' E', config_has_type (C b os rs t1) T' E'.\nProof using.\n  intros. inv H. inv H8. eauto.\nQed.\nHint Resolve cht_pmap1.\n\nLemma cht_pmap2 : forall b os rs l t1 t2 T E,\n  config_has_type (C b os rs (t_emit_pmap l t1 t2)) T E ->\n  exists T' E', config_has_type (C b os rs t2) T' E'.\nProof using.\n  intros. inv H. inv H8. eauto.\nQed.\nHint Resolve cht_pmap2.\n\nLemma cht_add1 : forall b os rs l t1 t2 T E,\n  config_has_type (C b os rs (t_emit_add l t1 t2)) T E ->\n  exists T' E', config_has_type (C b os rs t1) T' E'.\nProof using.\n  intros. inv H. inv H8. eauto.\nQed.\nHint Resolve cht_add1.\n\nLemma cht_add2 : forall b os rs l t1 t2 T E,\n  config_has_type (C b os rs (t_emit_add l t1 t2)) T E ->\n  exists T' E', config_has_type (C b os rs t2) T' E'.\nProof using.\n  intros. inv H. inv H8. eauto.\nQed.\nHint Resolve cht_add2.\n\nLemma waiting_fold_value : forall b os rs l t t1 t2 t3,\n  well_typed (C b (l ->> pfold t1 t2 t3 :: os) rs t) ->\n  value t2.\nProof using.\n  intros.\n  inv H.\n  dtr.\n  inv H.\n  inv H9.\n  dtr. subst. auto.\nQed.\n\nTheorem progress : forall b os rs t,\n  well_typed (C b os rs t) ->\n  value t \\/ exists c', (C b os rs t) --> c'.\nProof with eauto.\n  intros b os rs t WT.\n  inversion WT. destruct H1 as [T [E]]. rename H1 into ET. rename H into Hdk. rename H0 into Hdl. subst c. inv ET. clear H5 H6. rename H7 into ET.\n  remember (@empty type) as Gamma.\n  induction ET; subst Gamma...\n  - inversion H.\n  - right. destruct IHET1...\n    + inversion WT. split; crush; eauto.\n    + destruct IHET2...\n      * inversion WT. split; crush; eauto.\n      * assert (exists x0 t0, t1 = t_abs x0 T11 t0).\n        {\n          apply canonical_forms_fun in ET1.\n          destruct ET1.\n          destruct H1.\n          exists x.\n          exists x0...\n          assumption.\n        }\n        destruct H1.\n        destruct H1.\n        exists (C b (os ++ []) rs (#[x:=t2]x0))...\n        can_fun. inv H1. eauto.\n      * destruct H0.\n        inversion H0; ssame; eauto.\n    + destruct H.\n      inversion H; ssame; eauto.\n  - destruct IHET1...\n    + inversion WT. split; crush; eauto.\n    + destruct IHET2...\n      * inversion WT. split; crush; eauto.\n      * right; destruct H0.\n        inversion H0; ssame; eauto.\n    + right; destruct H.\n      inversion H; ssame; eauto.\n  - destruct IHET...\n    + inversion WT. split; crush; eauto.\n    + right.\n      inversion H; subst; try solve [inv ET].\n      * remember WT as WT'.\n        clear HeqWT'.\n        apply all_labels with (l:=label0) in WT; auto.\n        {\n        destruct WT; dtr.\n        - eauto.\n        - destruct H0; dtr.\n          + apply List.in_split in H0; dtr; subst.\n            destruct x0; [|destruct l].\n            * simpl; destruct x; destruct b; eauto; destruct s; eauto.\n            * simpl; destruct o; eauto; destruct b; eauto; destruct s; eauto.\n          + simpl in *.\n            destruct x1.\n            simpl in *.\n            destruct l.\n            * crush.\n            * destruct l.\n              destruct n.\n              eapply op_reduction_exists with (b1:=x0) (b2:=x2); eauto.\n        }\n    + right.\n      destruct H.\n      destruct x.\n      inversion H; ssame; eauto.\n  - right. destruct IHET1...\n    + inversion WT. split; crush; eauto.\n    + destruct IHET2...\n      * inversion WT. split; crush; eauto.\n      * {\n        destruct IHET3...\n        - inversion WT. split; crush; eauto.\n        - destruct H1. inversion H1; ssame; eauto.\n        }\n      * destruct H0. inversion H0; ssame; eauto.\n    + destruct H. inversion H; ssame; eauto.\n  - right. destruct IHET1...\n    + inversion WT. split; crush; eauto.\n    + destruct IHET2...\n      * inversion WT. split; crush; eauto.\n      * destruct H0. inversion H0; ssame; eauto.\n    + destruct H.\n      inversion H; ssame; eauto.\n  - right. destruct IHET1...\n    + inversion WT. split; crush; eauto.\n    + destruct IHET2...\n      * inversion WT. split; crush; eauto.\n      * destruct t1; try solve [inv ET1; inv H3]; try solve [inv H].\n        destruct t2; try solve [inv ET2; inv H3]; try solve [inv H0].\n        eauto.\n      * destruct H0. inversion H0; ssame; eauto.\n    + destruct H.\n      inversion H; ssame; eauto.\n  - destruct IHET1...\n    + inversion WT. split; crush; eauto.\n      inv H1. inv H10.\n      exists Result, E0.\n      econstructor. eauto. eauto. eauto.\n    + destruct IHET2...\n      * inversion WT. split; crush; eauto.\n        inv H2. inv H11.\n        exists Result, E4.\n        econstructor. eauto. eauto. eauto.\n      * {\n        destruct IHET3...\n        - inversion WT. split; crush; eauto.\n          inv H3. inv H12.\n          exists Keyset, E5.\n          econstructor. eauto. eauto. eauto.\n        - right. dtr. inv H1; ssame; eauto.\n        }\n      * right. dtr. inv H0; ssame; eauto.\n    + right. dtr. inv H; ssame; eauto.\n  - destruct IHET...\n    + inv WT. split; try split; eauto; dtr. inv H1. inv H10. exi; eauto.\n    + destruct t; narrow_terms. eauto.\n    + right. dtr. inv H; ssame; eauto.\n  - destruct IHET...\n    + inv WT. split; try split; eauto; dtr. inv H1. inv H10. exi; eauto.\n    + destruct t; narrow_terms. eauto.\n    + right. dtr. inv H; ssame; eauto.\n  - destruct IHET...\n    + inv WT. split; try split; eauto; dtr. inv H1. inv H10. exi; eauto.\n    + destruct t; narrow_terms. eauto.\n    + right. dtr. inv H; ssame; eauto.\n  - destruct IHET...\n    + inv WT. split; try split; eauto; dtr. inv H1. inv H10. exi; eauto.\n    + right. dtr. inv H; ssame; eauto.\nUnshelve.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nassert (value t0) by (eapply waiting_fold_value; eauto). inv WT'. dtr. inv H3. inv H11. inv H13. can_res. right. eauto.\nauto.\nauto.\nassert (value t0) by (eapply waiting_fold_value; eauto). inv WT'. dtr. inv H3. inv H11. inv H13. can_res. right. eauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nQed.\n\nLemma app_empty :\n  forall {A : Type} (xs : list A) ys,\n  [] = xs ++ ys -> xs = [] /\\ ys = [].\nProof using.\n  induction xs; crush.\nQed.\n\nLemma app_empty' :\n  forall {A : Type} (xs : list A) ys,\n  xs ++ ys = [] -> xs = [] /\\ ys = [].\nProof using.\n  induction xs; crush.\nQed.\n\nLemma wt_cons : forall b a ll ll',\n  well_typed_backend ll ll' (a :: b) ->\n  exists ll'', well_typed_backend ll ll'' b.\nProof using.\n  intros.\n  inv H.\n  eauto.\nQed.\nHint Resolve wt_cons.\n\nLemma dck_cons : forall a b os rs t,\n  distinct (config_keys (C (a :: b) os rs t)) ->\n  distinct (config_keys (C b os rs t)).\nProof using.\n  intros.\n  unfold config_keys in *.\n  simpl in H.\n  rewrite cons_app in H.\n  apply distinct_concat in H.\n  crush.\nQed.\nHint Resolve dck_cons.\n\nLemma dcl_cons : forall a b os rs t,\n  distinct (config_labels (C (a :: b) os rs t)) ->\n  distinct (config_labels (C b os rs t)).\nProof using.\n  intros.\n  unfold config_labels in *.\n  simpl in H.\n  unfold backend_labels in H.\n  simpl in H.\n  rewrite <- List.app_assoc in H.\n  apply distinct_concat in H.\n  crush.\nQed.\nHint Resolve dcl_cons.\n\nTheorem progress' : forall b os rs t,\n  well_typed (C b os rs t) ->\n  dry (C b os rs t) \\/ exists c', (C b os rs t) --> c'.\nProof using.\n  intros b os rs t WT.\n  inversion WT. subst c. destruct H1 as [T [E]]. rename H into Hdk; rename H0 into Hdl. inv H1. rename H7 into Hwtb. rename H6 into Hwtto. rename H8 into ET.\n  remember WT as WT'. clear HeqWT'. apply progress with (b:=b) (os:=os) (rs:=rs) in WT'.\n  destruct WT'.\n  - destruct os.\n    * {\n      generalize dependent ll.\n      generalize dependent ll'.\n      induction b; intros ll' ET ll Hwtb Hwtto.\n      - crush.\n      - destruct a as [n os].\n        destruct os.\n        + assert (dry (C b [] rs t) \\/ (exists c' : config, C b [] rs t --> c')).\n          {\n            eapply IHb.\n            inversion WT.\n            split; try split; crush.\n            - apply distinct_remove in H0; dtr. auto.\n            - exists x, x0. inv H2.\n              econstructor; eauto.\n              inv H9.\n              replace ll0 with ll'1 in * by auto.\n              wtbt'.\n              auto.\n            - eapply dck_cons; eauto.\n            - eapply dcl_cons; eauto.\n            - instantiate (1:=ll'); auto.\n            - instantiate (1:=ll). inv Hwtb.\n              replace ll with ll'0 in * by auto; auto.\n            - auto.\n          }\n          destruct H0.\n          * destruct n.\n            {\n            destruct (value_dec p).\n            - left.\n              constructor; eauto.\n              constructor; eauto.\n              inv H0; eauto.\n            - right.\n              copy WT.\n              eapply load_exists with (os:=[]) (b1:=[]) (b2:=b) (k:=k) (rs0:=rs) (t:=p) (es:=e) in H2; eauto.\n            }\n          * right.\n            destruct H0.\n            {\n            inversion H0; ssame; try solve [match goal with | [H : value _ |- _] => inv H end].\n            - eapply ex_intro; eauto.\n            - eapply ex_intro; eapply S_PMap; eauto; crush.\n            - eapply ex_intro; eapply S_PFold; eauto; crush.\n            - eapply ex_intro; eapply S_Last; eauto; crush.\n              Unshelve.\n              auto.\n            - eapply ex_intro; eapply S_FusePMap; eauto; crush.\n              Unshelve.\n              auto.\n            - eapply ex_intro; eapply S_SwapReads with (f':=f'); eauto; crush.\n            - eapply ex_intro; eapply S_Prop; eauto; crush.\n            - exi; eapply S_Load; eauto; crush.\n            - exi; eapply S_LoadPFold; eauto; crush.\n            }\n        + right.\n          destruct l as [l op].\n          destruct n.\n          eapply op_reduction_exists with (b1:=[]); eauto.\n          crush.\n    }\n    * destruct l as [l op].\n      right.\n      {\n      destruct op.\n      - destruct b.\n        + eapply ex_intro; eapply S_Empty; eauto.\n        + destruct s; eapply ex_intro; eapply S_First; eauto; crush.\n      - eapply ex_intro; eapply S_Add; eauto.\n      - destruct b.\n        + eapply ex_intro; eapply S_Empty; eauto.\n          Unshelve.\n          auto.\n          auto.\n          assert (value t1) by (eapply waiting_fold_value; eauto).\n          assert (has_type empty (rstream_types rs) t1 Result false) by (eapply graph_typing''' with (os:=[]); eauto).\n          destruct t1; try solve [inv H; inv H4]; try solve [inv H0]; try solve [inv H1].\n          right. eauto.\n        + destruct s; eapply ex_intro; eapply S_First; eauto; crush.\n      }\n  - right. assumption.\nQed.\n\nInductive appears_free_in : string -> term -> Prop :=\n| afi_var : forall x,\n    appears_free_in x (t_var x)\n| afi_app1 : forall x t1 t2,\n    appears_free_in x t1 ->\n    appears_free_in x (t_app t1 t2)\n| afi_app2 : forall x t1 t2,\n    appears_free_in x t2 ->\n    appears_free_in x (t_app t1 t2)\n| afi_abs : forall x y T11 t12,\n    y <> x  ->\n    appears_free_in x t12 ->\n    appears_free_in x (t_abs y T11 t12)\n| afi_ks1 : forall x k ks,\n    appears_free_in x k ->\n    appears_free_in x (t_ks_cons k ks)\n| afi_ks2 : forall x k ks,\n    appears_free_in x ks ->\n    appears_free_in x (t_ks_cons k ks)\n| afi_node1 : forall x k p es,\n    appears_free_in x k ->\n    appears_free_in x (t_node k p es)\n| afi_node2 : forall x k p es,\n    appears_free_in x p ->\n    appears_free_in x (t_node k p es)\n| afi_node3 : forall x k p es,\n    appears_free_in x es ->\n    appears_free_in x (t_node k p es)\n| afi_downarrow : forall x t,\n    appears_free_in x t ->\n    appears_free_in x (t_downarrow t)\n| afi_emit_getpay1 : forall x l t1 t2 t3,\n    appears_free_in x t1 ->\n    appears_free_in x (t_emit_pfold l t1 t2 t3)\n| afi_emit_getpay2 : forall x l t1 t2 t3,\n    appears_free_in x t2 ->\n    appears_free_in x (t_emit_pfold l t1 t2 t3)\n| afi_emit_getpay3 : forall x l t1 t2 t3,\n    appears_free_in x t3 ->\n    appears_free_in x (t_emit_pfold l t1 t2 t3)\n| afi_emit_pmap1 : forall x l t1 t2,\n    appears_free_in x t1 ->\n    appears_free_in x (t_emit_pmap l t1 t2)\n| afi_emit_pmap2 : forall x l t1 t2,\n    appears_free_in x t2 ->\n    appears_free_in x (t_emit_pmap l t1 t2)\n| afi_emit_add1 : forall x l t1 t2,\n    appears_free_in x t1 ->\n    appears_free_in x (t_emit_add l t1 t2)\n| afi_emit_add2 : forall x l t1 t2,\n    appears_free_in x t2 ->\n    appears_free_in x (t_emit_add l t1 t2)\n| afi_na1 : forall x t,\n    appears_free_in x t ->\n    appears_free_in x (t_na1 t)\n| afi_na2 : forall x t,\n    appears_free_in x t ->\n    appears_free_in x (t_na2 t)\n| afi_na3 : forall x t,\n    appears_free_in x t ->\n    appears_free_in x (t_na3 t)\n| afi_fix : forall x t T,\n    appears_free_in x t ->\n    appears_free_in x (t_fix T t).\nHint Constructors appears_free_in.\n\nDefinition closed (t:term) :=\n  forall x, ~ appears_free_in x t.\n\nDefinition lclosed (t:term) :=\n  forall l, ~ lappears_free_in l t.\n\nLemma free_in_context : forall x t T E Gamma ll,\n   appears_free_in x t ->\n   has_type Gamma ll t T E ->\n   exists T', Gamma x = Some T'.\nProof using.\n  intros x t T E Gamma ll H H0. generalize dependent Gamma.\n  generalize dependent T.\n  generalize dependent E.\n  induction H;\n         intros; try solve [inversion H0; eauto].\n  - (* afi_abs *)\n    inversion H1; subst.\n    apply IHappears_free_in in H9.\n    rewrite update_neq in H9; assumption.\nQed.\n\nCorollary typable_empty__lclosed : forall t T E Gamma,\n    has_type Gamma nempty t T E ->\n    lclosed t.\nProof using.\n  unfold lclosed. intros. intro.\n  eapply free_in_lcontext with (ll:=nempty) in H0.\n  destruct H0.\n  inv H0.\n  eauto.\nQed.\n\nCorollary typable_empty__closed : forall t T E ll,\n    has_type empty ll t T E ->\n    closed t.\nProof using.\n  unfold closed. intros. intro.\n  eapply free_in_context with (Gamma:=empty) in H0.\n  destruct H0.\n  inv H0.\n  eauto.\nQed.\n\nLemma lcontext_invariance : forall ll ll' Gamma t T E,\n     has_type Gamma ll t T E ->\n     (forall l, lappears_free_in l t -> ll l = ll' l) ->\n     has_type Gamma ll' t T E.\nProof with eauto.\n  intros.\n  generalize dependent ll'.\n  induction H; intros; auto; try solve [econstructor; eauto].\n  - apply T_Label. rewrite <- H0...\nQed.\n\nLemma context_invariance : forall Gamma Gamma' ll t T E,\n     has_type Gamma ll t T E ->\n     (forall x, appears_free_in x t -> Gamma x = Gamma' x) ->\n     has_type Gamma' ll t T E.\nProof with eauto.\n  intros.\n  generalize dependent Gamma'.\n  induction H; intros; auto; try solve [econstructor; eauto].\n  - (* T_Var *)\n    apply T_Var. rewrite <- H0...\n  - (* T_Abs *)\n    apply T_Abs.\n    apply IHhas_type. intros x1 Hafi.\n    unfold update. unfold t_update. destruct (eqb_string x x1) eqn: Hx0x1...\n    rewrite eqb_string_false_iff in Hx0x1. auto.\nQed.\n\nLemma substitution_preserves_typing : forall Gamma ll x U t v T E1,\n  has_type (x |-> U ; Gamma) ll t T E1 ->\n  has_type empty ll v U false ->\n  has_type Gamma ll (#[x:=v]t) T E1.\nProof with eauto.\n  intros Gamma ll x U t v T E1 Ht Ht'.\n  generalize dependent Gamma. generalize dependent T. generalize dependent E1. generalize dependent Ht'. generalize dependent ll.\n  induction t; intros ll Ht' E1 T Gamma H;\n    inversion H; subst; simpl...\n  - (* var *)\n    rename s into y. destruct (eqb_stringP x y) as [Hxy|Hxy].\n    + (* x=y *)\n      subst.\n      rewrite update_eq in H3.\n      inversion H3; subst.\n      eapply context_invariance.\n      * eapply lcontext_invariance. eassumption.\n        auto.\n      * apply typable_empty__closed in Ht'. unfold closed in Ht'.\n        intros.  apply (Ht' x) in H0. inversion H0.\n    + (* x<>y *)\n      apply T_Var. rewrite update_neq in H3...\n  - (* abs *)\n    rename s into y. rename t into T. apply T_Abs.\n    destruct (eqb_stringP x y) as [Hxy | Hxy].\n    + (* x=y *)\n      subst. rewrite update_shadow in H7. apply H7.\n    + (* x<>y *)\n      apply IHt. assumption. eapply context_invariance...\n      intros z Hafi. unfold update, t_update.\n      destruct (eqb_stringP y z) as [Hyz | Hyz]; subst; trivial.\n      rewrite <- eqb_string_false_iff in Hxy.\n      rewrite Hxy...\nQed.\n\nLemma emit_well_typed_top_ostream : forall t b os os' rs t' T E,\n  config_has_type (C b os rs t) T E ->\n  FRf t rs ==> FRt t' os' ->\n  exists ll, well_typed_top_ostream (ostream_types os (backend_types b (rstream_types rs))) ll os'.\nProof using.\n  induction t; intros;\n  rename H into HT;\n  inversion HT; subst;\n  inv H8.\n  - inv H3.\n  - inversion H0; eauto.\n  - inversion H0; eauto.\n  - inversion H0; eauto.\n  - inversion H0; eauto.\n  - inversion H0; eauto.\n  - inversion H0; eauto.\n  - inversion H0; eauto.\n  - inversion H0; eauto; subst.\n    + econstructor. econstructor; eauto.\n      constructor; eauto.\n      * wtbt. wttost. assert (E1 = false) by (eapply value_no_emit; eauto); subst.\n        auto.\n      * wtbt. wttost. assert (E2 = false) by (eapply value_no_emit; eauto); subst.\n        auto.\n  - inversion H0; eauto; subst.\n    + econstructor. econstructor; eauto.\n      constructor; eauto.\n      assert (E1 = false) by (eapply value_no_emit; eauto); subst.\n      wtbt. wttost. auto.\n  - inversion H0; eauto.\n  - inversion H0; eauto.\n  - inversion H0; eauto.\n  - inversion H0; eauto.\n  - inversion H0; eauto.\n  - inversion H0; eauto.\nQed.\nHint Resolve emit_well_typed_top_ostream.\n\nLemma wt_btop_cons : forall n os os0 op b l ll ll' ll'',\n  well_typed_backend ll ll' (<<n; os>> :: b) ->\n  well_typed_top_ostream ll' ll'' (l ->> op :: os0) ->\n  exists ll''', well_typed_backend ll ll''' (<<n; os ++ [l ->> op]>> :: b).\nProof using.\n  intros.\n  inv H.\n  inv H0.\n  destruct op; eauto.\nQed.\nHint Resolve wt_btop_cons.\n\nLemma wt_top_to_ht1 : forall l k v os ll ll',\n  well_typed_top_ostream ll ll' (l ->> add k v :: os) ->\n  has_type empty ll v Result false.\nProof using.\n  intros. inv H. inv H7. auto.\nQed.\nHint Resolve wt_top_to_ht1.\n\nLemma wt_to_wt1 : forall b1 k v es l f ks os b2 ll ll',\n  well_typed_backend ll ll' (b1 ++ << N k v es; l ->> pmap f ks :: os >> :: b2) ->\n  well_typed_backend ll ll' (b1 ++ << N k (t_app f v) es; l ->> pmap f (remove Nat.eq_dec k ks) :: os >> :: b2).\nProof using.\n  intros.\n  wtbdist.\n  eapply well_typed_backend_dist; eauto.\n  inv H0.\n  inv H10.\n  inv H6.\n  econstructor; eauto.\n  - remember H5. clear Heqh. can_fun.\n    assert (false = false || false || false)%bool by crush.\n    rewrite H0; clear H0.\n    eapply T_App with Result.\n    constructor.\n    inv H5.\n    auto.\n    auto.\nQed.\nHint Resolve wt_to_wt1.\n\nLemma wt_to_wt2 : forall b1 k t es l f t' ks os b2 ll ll',\n  well_typed_backend ll ll' (b1 ++ << N k t es; l ->> pfold f t' ks :: os >> :: b2) ->\n  well_typed_backend ll ll' (b1 ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os >> :: b2).\nProof using.\n  intros.\n  wtbdist.\n  eapply well_typed_backend_dist; eauto.\n  inv H0.\n  inv H10.\n  inv H6.\n  econstructor; eauto.\n  - remember H8. clear Heqh. can_fun.\n    constructor; eauto.\n    constructor; eauto.\n    assert (false = false || false || false)%bool by crush.\n    rewrite H0.\n    eapply T_App with Result.\n    rewrite H0.\n    eapply T_App with Result.\n    constructor.\n    inv H8.\n    auto.\n    auto.\n    auto.\nQed.\nHint Resolve wt_to_wt2.\n\nLemma wt_to_wt3 : forall b n l op os ll ll',\n  well_typed_backend ll ll' (b ++ [<< n; l ->> op :: os >>]) ->\n  well_typed_backend (l#->(op_type op);ll) ll' (b ++ [<< n; os >>]).\nProof using.\n  intros.\n  wtbdist.\n  eapply well_typed_backend_dist; eauto.\n  inv H0.\n  inv H8.\n  replace ll'0 with ll in * by auto.\n  econstructor; [| | eauto|eauto].\n  - auto.\n  - auto.\nQed.\nHint Resolve wt_to_wt3.\n\nLemma wt_to_wt4 : forall b1 n os l f l' f' ks os' b2 ll ll',\n  well_typed_backend ll ll' (b1 ++ << n; os ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os' >> :: b2) ->\n  exists ll'', well_typed_backend (l#->(op_type (pmap f ks));ll) ll'' (b1 ++ << n; os ++ l' ->> pmap (pmap_compose f' f) ks :: os' >> :: b2).\nProof using.\n  intros.\n  wtbdist.\n  inv H0.\n  wtosdist.\n  inversion H1.\n  inv H11.\n  can_fun.\n  simpl in *.\n  copy H; wtbt.\n  exi; eapply well_typed_backend_dist.\n  - instantiate (1:=backend_types b1 x).\n    instantiate (1:=x).\n    auto.\n  - wtbt'. wtost'.\n    econstructor. Focus 4.\n    + instantiate (1:=backend_types b2 (l#->Result;ll)).\n      eapply wt_backend_extension with (l:=l) (T:=Result) in H2; dtr.\n      eapply wt_backend_build; eauto.\n    + eauto.\n    + eauto.\n    + eapply well_typed_ostream_dist; simpl in *.\n      * instantiate (1:=ostream_types os (backend_types b2 (l#->Result;ll))).\n        eapply wt_ostream_backend_extension' with (l:=l) (T:=Result) in H0; dtr.\n        eapply wt_ostream_build. eauto.\n      * {\n        constructor; simpl in *.\n        - apply wt_to_ostream_types in H0; subst.\n          inv H3; simpl in *.\n          rewrite ll_extract_backend.\n          rewrite ll_extract_ostream. auto.\n        - constructor; unfold pmap_compose in *; eauto.\n          + constructor.\n            replace false with (false || false || false) by auto; econstructor; simpl.\n            * inv H3. inv H12.\n              wtost. wtost. wtost. instantiate (1:=Result).\n              simpl in *.\n              {\n              eapply context_invariance with (Gamma:=empty).\n              + rewrite ll_extract_backend. rewrite ll_extract_ostream. auto.\n              + intros; apply typable_empty__closed in H9; unfold closed in H9; exfalso; apply (@H9 x); auto.\n              }\n            * {\n              replace false with (false || false || false) by auto; econstructor; simpl.\n                - instantiate (1:=Result).\n                  inv H1. inv H12.\n                  wtbt. wtbt. wtost. wtost. wtost.\n                  eapply context_invariance with (Gamma:=empty).\n                  + rewrite ll_extract_backend. rewrite ll_extract_ostream. eauto.\n                  + intros; apply typable_empty__closed in H9; unfold closed in H9; exfalso; apply (@H9 x); auto.\n                - auto.\n              }\n        }\nQed.\nHint Resolve wt_to_wt4.\n\nLemma wt_to_wt5 : forall b1 n l op os n' os' b2 ll ll',\n  well_typed_backend ll ll' (b1 ++ << n; l ->> op :: os >> :: << n'; os' >> :: b2) ->\n  well_typed_backend ll ll' (b1 ++ << n; os >> :: << n'; os' ++ [l ->> op] >> :: b2).\nProof using.\n  intros; wtbdist; eapply well_typed_backend_dist; eauto.\n  inv H0. inv H8. inv H9.\n  econstructor; [| |eauto|eauto].\n  - eauto.\n  - eauto.\nQed.\nHint Resolve wt_to_wt5.\n\nLemma backend_types_app : forall b b' ll,\n  backend_types (b ++ b') ll = backend_types b' (backend_types b ll).\nProof using.\n  induction b; intros; auto.\n  destruct a; destruct n; simpl.\n  rewrite IHb. rewrite ll_swap_ostream_backend. auto.\nQed.\n\nLemma ostream_types_app : forall os os' ll,\n  ostream_types (os ++ os') ll = ostream_types os' (ostream_types os ll).\nProof using.\n  induction os; intros; auto.\n  destruct a; simpl.\n  rewrite IHos. crush.\nQed.\n\nLemma wt_to_wt6 : forall b1 n os l l' ks os' b2 ll ll' f t f' t' ks',\n  not (lappears_free_in l f') ->\n  not (lappears_free_in l t') ->\n  well_typed_backend ll ll' (b1 ++ << n; os ++ l ->> pfold f t ks :: l' ->> pfold f' t' ks' :: os' >> :: b2) ->\n  exists ll'', well_typed_backend ll ll'' (b1 ++ << n; os ++ l' ->> pfold f' t' ks' :: l ->> pfold f t ks :: os' >> :: b2).\nProof using.\n  intros.\n  apply well_typed_backend_dist' in H1; dtr.\n  inv H2.\n  apply well_typed_ostream_dist' in H10; dtr.\n  inv H3.\n  inv H10.\n  inv H14.\n  inv H13.\n  exi; eapply well_typed_backend_dist.\n  - instantiate (2:=x). instantiate (1:=backend_types b1 x). copy H1; apply wt_to_backend_types in H1; subst. eauto.\n  - econstructor; simpl in *. Focus 4.\n    + copy H11; apply wt_to_backend_types in H11; subst. eauto.\n    + wtbt. eauto.\n    + wtbt. eauto.\n    + eapply well_typed_ostream_dist.\n      * wtbt. wtost'. eauto.\n      * {\n        constructor.\n        - constructor.\n          + simpl in *. replace (l #-> Result; l' #-> Result; x0) with (l' #-> Result; l #-> Result; x0).\n            eauto.\n            apply NMaps.update_permute. apply fresh_labels.\n          + eauto.\n        - constructor; eauto.\n          + apply lcontext_invariance with (ll:=(l #-> Result;x0)); auto.\n            crush.\n            rewrite NMaps.update_neq; eauto.\n          + apply lcontext_invariance with (ll:=(l #-> Result;x0)); auto.\n            crush.\n            rewrite NMaps.update_neq; eauto.\n        }\nQed.\nHint Resolve wt_to_wt6.\n\nLemma cht_to_ht : forall b os rs t T E,\n  config_has_type (C b os rs t) T E ->\n  has_type empty (ostream_types os (backend_types b (rstream_types rs))) t T E.\nProof using.\n  intros; inv H; wtbt; wttost; auto.\nQed.\nHint Resolve cht_to_ht.\n\nLemma cht_to_wtop_cons : forall b l op os rs t T E,\n  config_has_type (C b (l ->> op :: os) rs t) T E ->\n  exists ll, well_typed_top_ostream (l#->(op_type op);backend_types b (rstream_types rs)) ll os.\nProof using.\n  intros; inv H; wtbt; inv H7; eauto.\nQed.\nHint Resolve cht_to_wtop_cons.\n\nLtac inv_type := try (match goal with | [H : config_has_type _ _ _ |- _] => inv H end);\n                      match goal with | [H : has_type _ _ _ _ _ |- _] => inv H end.\n\nHint Immediate NMaps.update_eq.\n\nLemma type_in_rstream' : forall rs l v,\n  In (l ->>> v) rs ->\n  (rstream_types rs) l = Some Result.\nProof using.\n  induction rs; intros; crush.\n  - destruct a. destruct (Nat.eq_dec l l0); subst.\n    + apply NMaps.update_eq.\n    + rewrite NMaps.update_neq; auto. apply IHrs with v; auto.\nQed.\n\nLemma in_rstream_labels : forall rs l v,\n  In (l ->>> v) rs ->\n  In l (rstream_labels rs).\nProof using.\n  induction rs; intros.\n  - auto.\n  - destruct a. simpl. rename l0 into n. destruct (Nat.eq_dec n l).\n    + auto.\n    + inv H; eauto.\n      inv H0. eauto.\nQed.\n\nTheorem preservation' : forall t b os0 rs os t' T E,\n  config_has_type (C b os0 rs t) T E ->\n  distinct (List.concat [backend_labels b; ostream_labels os0; rstream_labels rs]) ->\n  FRf t rs ==> FRt t' os ->\n  exists E', has_type empty (ostream_types os (ostream_types os0 (backend_types b (rstream_types rs)))) t' T E' /\\\n        (match E with\n         | false => E' = false\n         | _ => True\n         end).\nProof using.\n  induction t; intros b os0 rs os t' T E H Hdistinct H0; try solve [inv H0]; inv H; rename H7 into Hwtb; rename H8 into Hwttos; rename H9 into H.\n  - inv H0.\n    + exists E. split; [|destruct E; auto]; simpl in *.\n      inv H. inv H5.\n      assert (E3 = false) by (eapply value_no_emit; eauto); subst.\n      replace (E1 || false || false) with E1.\n      eapply substitution_preserves_typing; wtbt; wttost; eauto.\n      destruct E1; auto.\n    + inv H.\n      eapply IHt1 with (T:=Arrow T11 T E1) (E:=E2) in H2; eauto; dtr.\n      exists (E1 || x || E3). split.\n      * {\n        econstructor.\n        - instantiate (1:=T11).\n          eauto.\n        - wtbt; wttost; auto.\n        }\n      * destruct E1; destruct E2; destruct E3; crush.\n    + inv H.\n      eapply IHt2 with (T:=T11) (E:=E3) in H7; eauto; dtr.\n      exists (E1 || E2 || x). split.\n      * eauto.\n      * destruct E1; destruct E2; destruct E3; crush.\n  - inv H0.\n    + inv H.\n      eapply IHt1 in H2; eauto; dtr.\n      exists (x || E2). split; eauto.\n      * destruct E1; destruct E2; crush.\n    + inv H.\n      eapply IHt2 in H7; eauto; dtr.\n      exists (E1 || x). split; eauto.\n      * destruct E1; destruct E2; crush.\n  - inv H0.\n    + inv H. exists E. inv H4. simpl. wtbt; wttost.\n      assert (T = Result).\n      { assert (distinct (List.concat [backend_labels b; ostream_labels os0; rstream_labels rs])) by eauto.\n        apply lcontext_in_or_os in H5; destruct H5; dtr.\n        - simpl in *. apply List.in_split in H0; dtr; subst.\n          exfalso. rewrite ostream_labels_dist in H. simpl in *.\n          replace (backend_labels b ++ (ostream_labels x0 ++ l :: ostream_labels x1) ++ rstream_labels rs ++ [])\n                  with ((backend_labels b ++ ostream_labels x0) ++ l :: ostream_labels x1 ++ rstream_labels rs ++ []) in H by crush.\n          apply distinct_rotate_rev in H. apply distinct_remove in H; dtr.\n          apply H0. apply List.in_or_app. right. apply List.in_or_app. right. apply in_rstream_labels in H2. crush.\n        - apply lcontext_in_or_b in H0; destruct H0; dtr.\n          + simpl in *. apply List.in_split in H1; dtr; subst; destruct x0; simpl in *; subst.\n            exfalso. rewrite backend_labels_dist in H; simpl in *.\n            unfold backend_labels at 2 in H; simpl in *. rewrite ostream_labels_dist in H; simpl in *.\n            replace ((backend_labels x ++\n          (ostream_labels x3 ++ l :: ostream_labels x4) ++ List.concat (map (fun s : station => ostream_labels (get_ostream s)) x1)) ++\n         ostream_labels os0 ++ rstream_labels rs ++ []) with ((backend_labels x ++\n          ostream_labels x3) ++ l :: ostream_labels x4 ++ List.concat (map (fun s : station => ostream_labels (get_ostream s)) x1) ++\n         ostream_labels os0 ++ rstream_labels rs ++ []) in H by crush.\n            apply distinct_rotate_rev in H. apply distinct_remove in H; dtr.\n          apply H0. apply List.in_or_app. right. apply List.in_or_app. right. apply in_rstream_labels in H2. crush.\n          + apply type_in_rstream' in H2. crush.\n      }\n      subst; split; eauto.\n    + inv H.\n      eapply IHt in H2; eauto; dtr.\n      exists x. split; eauto.\n  - inv H0.\n    + inv H. exists false. split; simpl; eauto.\n    + inv H.\n      eapply IHt1 in H2; eauto; dtr.\n      exists true. split; wtbt; wttost; eauto.\n    + inv H.\n      eapply IHt2 in H9; eauto; dtr.\n      exists true. split; wtbt; wttost; eauto.\n    + inv H.\n      eapply IHt3 in H10; eauto; dtr.\n      exists true. split; wtbt; wttost; eauto.\n  - inv H0.\n    + inv H. exists false. split; simpl; eauto.\n    + inv H.\n      eapply IHt1 in H2; eauto; dtr.\n      exists true. split; eauto.\n    + inv H.\n      eapply IHt2 in H8; eauto; dtr.\n      exists true. split; eauto.\n  - inv H0.\n    + inv H. exists false. split; simpl; auto.\n    + inv H.\n      eapply IHt1 in H2; eauto; dtr.\n      exists true. split; eauto.\n    + inv H.\n      eapply IHt2 in H8; eauto; dtr.\n      exists true. split; eauto.\n  - inv H0.\n    + inv H.\n      eapply IHt1 in H2; eauto; dtr.\n      exists (x || E2 || E3). split; wtbt; wttost; eauto.\n      * destruct E1; destruct E2; destruct E3; crush.\n    + inv H.\n      eapply IHt2 in H8; eauto; dtr.\n      exists (E1 || x || E3). split; wtbt; wttost; eauto.\n      * destruct E1; destruct E2; destruct E3; crush.\n    + inv H.\n      eapply IHt3 in H9; eauto; dtr.\n      exists (E1 || E2 || x). split; wtbt; wttost; eauto.\n      * destruct E1; destruct E2; destruct E3; crush.\n  - inv H0.\n    + inv H. eapply IHt in H2; eauto; dtr. exists x. split; eauto.\n    + inv H. inv H3. assert (E1 = false) by (eapply value_no_emit; eauto); subst. simpl. exists false. split; eauto. destruct E2; destruct E3; crush.\n  - inv H0.\n    + inv H. eapply IHt in H2; eauto; dtr. exists x. split; eauto.\n    + inv H. inv H3. assert (E2 = false) by (eapply value_no_emit; eauto); subst. simpl. exists false. split; eauto. destruct E1; destruct E3; crush.\n  - inv H0.\n    + inv H. eapply IHt in H2; eauto; dtr. exists x. split; eauto.\n    + inv H. inv H3. assert (E3 = false) by (eapply value_no_emit; eauto); subst. simpl. exists false. split; eauto. destruct E1; destruct E2; crush.\n  - inv H0.\n    + inv H. exists (false || false || false). split; [|destruct E; auto].\n      assert (E = false) by (eapply value_no_emit; eauto); subst.\n      constructor.\n      replace (E2 || E3) with (E2 || E3 || false).\n      econstructor; [instantiate (1:=t)|].\n      * replace E3 with (E3 || false || false).\n        {\n        econstructor; [instantiate (1:=(Arrow t t (E2 || E3)))|].\n        - apply context_invariance with empty; wtbt; wttost; auto.\n          intros; apply typable_empty__closed in H7; unfold closed in H7; exfalso; apply (@H7 x); auto.\n        - replace false with (false || false || false).\n          econstructor; simpl.\n          apply context_invariance with empty. wtbt; wttost; auto.\n          intros; apply typable_empty__closed in H7; unfold closed in H7; exfalso; apply (@H7 x); auto.\n          auto.\n        }\n        destruct E3; auto.\n      * auto.\n      * destruct E2; destruct E3; auto.\n    + inv H. eapply IHt in H2; eauto; dtr.\n      exists x. split; eauto.\nQed.\n\nTheorem preservation : forall c c' T E,\n  config_has_type c T E ->\n  distinct (config_labels c) ->\n  c --> c'  ->\n  exists E', config_has_type c' T E' /\\ (match E with\n                                    | false => E' = false\n                                    | _ => True\n                                    end).\nProof with eauto.\n  intros c c' T E Hht Hdistinct Hstep.\n  generalize dependent T.\n  generalize dependent E.\n  induction Hstep; intros; subst c.\n  - inversion Hht; subst.\n    copy H0. rename H0 into Hstep. apply preservation' with (b:= b) (os0:=os) (rs:=rs) (T:=T) (E:=E) in H; eauto; dtr.\n    exists x. split; eauto.\n    wtbt'. wttost'.\n    econstructor.\n    + eauto.\n    + instantiate (1:=ostream_types os' (ostream_types os (backend_types b (rstream_types rs)))).\n      apply emit_well_typed_top_ostream with (T:=T) (E:=E) (b:=b) (os:=os) in Hstep; auto; dtr.\n      copy H3. apply wt_to_top_ostream_types in H3; subst.\n      eapply well_typed_top_ostream_dist; eauto.\n    + auto.\n  - subst. exists E. split; eauto. econstructor; auto.\n    + apply cht_to_wtop_cons in Hht; dtr. simpl in *. wttost'. instantiate (1:=ostream_types os' (l#->op_type op; rstream_types rs)). destruct op; simpl in *; auto.\n    + inv Hht. wtbt. wttost. destruct op; simpl in *; rewrite ll_extract_ostream; auto.\n    + destruct E; auto.\n  - subst. exists E. split; eauto; [|destruct E; auto]. econstructor; eauto.\n    + inv Hht. instantiate (1:=backend_types (<<n1;os1++[l->>op]>>::b') (rstream_types rs)).\n      wtbt'. wttost'.\n      eapply wt_backend_build. destruct n1. econstructor. Focus 4.\n      * instantiate (1:=backend_types b' (rstream_types rs)).\n        inv H.\n        eapply wt_backend_build; eauto.\n      * inv H. wtbt. eauto.\n      * inv H. wtbt. eauto.\n      * {\n        eapply well_typed_ostream_dist.\n        - inv H. wtbt. eauto.\n        - constructor; eauto. inv H0. auto.\n        }\n    + destruct n1; simpl in *. rewrite ostream_types_app. simpl in *.\n      rewrite <- ll_extract_ostream.\n      rewrite <- ll_extract_ostream.\n      rewrite ll_extract_ostream.\n      inv Hht.\n      wtbt. simpl in *. inv H7. wttost'. auto.\n  - subst. exists E. split; eauto; [|destruct E; auto]. econstructor; auto.\n    + simpl in *. econstructor. Focus 4.\n      * instantiate (1:=backend_types b (l#->Result;rstream_types rs)).\n        inv Hht. wtbt'. wttost'.\n        apply wt_backend_extension with (l:=l) (T:=Result) in H0; dtr.\n        eapply wt_backend_build; eauto.\n      * inv Hht. inv H7. inv H10. wtbt'. eauto.\n      * inv Hht. inv H7. inv H10. wtbt'. eauto.\n      * inv Hht. inv H7. inv H10. wtbt'. eauto.\n    + inv Hht. wtbt. inv H7. simpl in *. rewrite ll_extract_backend. wttost'. eauto.\n    + inv Hht. wtbt. wttost. simpl in *. rewrite ll_extract_ostream. eauto.\n  - subst. exists E. split; eauto; [|destruct E; auto]. econstructor; auto; inv Hht.\n    + apply wt_to_wt1 in H6; dtr. simpl in *. wtbt'. eauto.\n    + wtbt. rewrite backend_types_app in *. simpl in *. wttost'. eauto.\n    + wtbt. rewrite backend_types_app in H7. simpl in *. wttost. eauto.\n  - subst. exists E. split; eauto; [|destruct E; auto]. econstructor; auto; inv Hht.\n    + apply wt_to_wt2 in H6; dtr. simpl in *. wtbt'. eauto.\n    + wtbt. rewrite backend_types_app in *. simpl in *. wttost'. eauto.\n    + wtbt. rewrite backend_types_app in H7. simpl in *. wttost. eauto.\n  - subst. exists E. split; eauto; [|destruct E; auto]. econstructor; auto; inv Hht.\n    + apply wt_to_wt3 in H7; dtr. simpl in *. wtbt'. destruct op; eauto.\n    + simpl in *. wtbt. wttost'. rewrite backend_types_app in *. simpl in H0. destruct n1; simpl in *.\n      rewrite ll_extract_backend.\n      rewrite ll_extract_ostream.\n      eauto.\n    + wtbt. wttost. rewrite backend_types_app in H9. simpl in *. destruct n1; simpl in *. auto.\n  - subst. exists E. split; eauto; [|destruct E; auto]. econstructor; auto; inv Hht.\n    + apply wt_to_wt4 in H6; dtr. simpl in *. wtbt'. eauto.\n    + simpl in *. wtbt. wttost'. rewrite backend_types_app in *. simpl in *. destruct n; simpl in *.\n      clear H8.\n      rewrite ostream_types_app in *; simpl in *.\n      rewrite ll_extract_backend.\n      rewrite ll_extract_backend.\n      rewrite ll_extract_ostream.\n      rewrite ll_extract_ostream.\n      replace (l' #-> Result; l #-> Result; ostream_types os2 (ostream_types os1 (backend_types b2 (backend_types b1 (rstream_types rs)))))\n              with (l #-> Result; l' #-> Result; ostream_types os2 (ostream_types os1 (backend_types b2 (backend_types b1 (rstream_types rs))))).\n      eauto.\n      apply NMaps.update_permute. apply fresh_labels.\n    + wtbt. wttost. rewrite backend_types_app in *. simpl in *. destruct n; simpl in *.\n      rewrite ostream_types_app in *; simpl in *; eauto.\n  - subst. exists E. split; eauto; [|destruct E; auto]. econstructor; auto; inv Hht.\n    + apply wt_to_wt6 in H7; eauto; dtr. wtbt'. eauto.\n    + wtbt'. rewrite backend_types_app in *. destruct n. simpl in *. rewrite ostream_types_app in *. simpl in *.\n      clear H9 H. wttost'.\n      replace (l' #-> Result; l #-> Result; ostream_types os2 (ostream_types os1 (backend_types b2 (backend_types b1 (rstream_types rs)))))\n              with (l #-> Result; l' #-> Result; ostream_types os2 (ostream_types os1 (backend_types b2 (backend_types b1 (rstream_types rs))))).\n      eauto.\n      apply NMaps.update_permute. apply fresh_labels.\n    + wtbt. wttost. rewrite backend_types_app in *. destruct n. simpl in *. rewrite ostream_types_app in *. simpl in *.\n      eauto.\n  - subst. exists E. split; eauto; [|destruct E; auto]. econstructor; auto; inv Hht.\n    + wtbdist. inv H1. inv H11. inv H12.\n      copy H6; apply wt_to_ostream_types in H6; subst.\n      copy H15; apply wt_to_ostream_types in H15; subst.\n      copy H; apply wt_to_backend_types in H; subst.\n      copy H7; apply wt_to_top_ostream_types in H7; subst.\n      copy H16; apply wt_to_backend_types in H16; subst.\n      eapply well_typed_backend_dist; eauto.\n      econstructor. Focus 4.\n      * instantiate (1:=ostream_types (os2 ++ [l ->> op]) (backend_types b2 (rstream_types rs))).\n        econstructor; eauto.\n        rewrite ostream_types_app. simpl in *. eapply well_typed_ostream_dist; eauto.\n      * rewrite ostream_types_app. eauto.\n      * rewrite ostream_types_app. eauto.\n      * rewrite ostream_types_app. eauto.\n    + wtbt. wttost'. rewrite backend_types_app in H. simpl in *. destruct n2; simpl in *. destruct n1; simpl in *.\n      rewrite ll_extract_ostream. rewrite ll_extract_backend.\n      rewrite <- ll_swap_ostream_backend. rewrite <- ll_swap_ostream_backend.\n      rewrite ll_swap_backend. eauto.\n    + wtbt. wttost. rewrite backend_types_app in H8. simpl in *. destruct n1; destruct n2; simpl in *. eauto.\n  - subst. exists E. split; [|destruct E; eauto].\n    copy Hht. rename H into Hht'. inv Hht. apply well_typed_backend_dist' in H6; dtr. copy H0. inv H0.\n    copy H1. rename H1 into Hstep. eapply preservation' with (T:=Result) (E:=false) in H0; dtr; subst; eauto.\n    econstructor; eauto. eapply well_typed_backend_dist; eauto.\n    inv H2. econstructor; eauto. simpl. wtbt. eauto. simpl. wtbt. wtbt'. eauto.\n    clear H0 H15 H14 H13 H11 H2 H8 H7 Hht' Hstep.\n    unfold config_labels in *.\n    rewrite backend_labels_dist in *. simpl in *.\n    rewrite <- List.app_assoc in Hdistinct.\n    apply distinct_concat in Hdistinct; dtr.\n    unfold backend_labels in H1; simpl in *.\n    rewrite <- List.app_assoc in H1.\n    apply distinct_concat in H1; dtr.\n    apply distinct_app_comm in H2.\n    rewrite <- List.app_assoc in H2.\n    apply distinct_concat in H2; dtr. auto.\n  - subst. exists E. split; [|destruct E; eauto].\n    inv Hht. apply well_typed_backend_dist' in H6; dtr. inv H0.\n    wtosdist. inv H2. inv H13.\n    copy H1. rename H1 into Hstep.\n    eapply preservation' with (T:=Result) (E:=false) in H2; dtr; subst; eauto.\n    + econstructor; eauto.\n      eapply well_typed_backend_dist; auto.\n      * instantiate (1:=x); auto.\n      * copy H14; apply wt_to_backend_types in H14; subst.\n        copy H9; apply wt_to_ostream_types in H9; subst.\n        copy H0; apply wt_to_ostream_types in H0; subst.\n        copy H; apply wt_to_backend_types in H; subst.\n        copy H7; apply wt_to_top_ostream_types in H7; subst.\n        simpl in *.\n        assert (well_typed_backend (rstream_types rs0) (backend_types (<< N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b2) (rstream_types rs0)) (<< N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b2)).\n        {\n          eapply wt_backend_build; eauto.\n        }\n        simpl in H5. rewrite ostream_types_app in H5. simpl in H5.\n        eauto.\n    + instantiate (1:=k).\n      clear H0 H15 H14 H11 H2 H8 H7 H9 H10 H12 H Hstep.\n      unfold config_labels in Hdistinct; simpl in *.\n      apply distinct_app_comm in Hdistinct.\n      rewrite <- List.app_assoc in Hdistinct.\n      apply distinct_concat in Hdistinct; dtr.\n      apply distinct_app_comm in H0.\n      rewrite backend_labels_dist in H0.\n      rewrite <- List.app_assoc in H0.\n      apply distinct_concat in H0; dtr.\n      unfold backend_labels in H1; simpl in *.\n      rewrite <- List.app_assoc in H1.\n      rewrite ostream_labels_dist in H1.\n      rewrite <- List.app_assoc in H1.\n      apply distinct_app_comm in H1.\n      rewrite <- List.app_assoc in H1.\n      apply distinct_concat in H1; dtr.\n      apply distinct_app_comm in H2. unfold backend_labels. crush.\nQed.\n\nDefinition normal_form (c : config) : Prop :=\n  ~ exists c', c --> c'.\n\nLemma dry_normal_form : forall c b os rs t,\n    well_typed c ->\n    c = C b os rs t ->\n    (dry c <-> normal_form c).\nProof using.\n  intros c b os rs t WT Heq.\n  split; intros.\n  - inversion H.\n    intro.\n    destruct H3.\n    inversion H3; inversion H4; try solve [subst; inv H1]; try solve [inv H5]; try solve [subst; match goal with | [H : [] = _ |- _] => inv H end].\n    + subst. exfalso; eapply frontend_no_value; eauto.\n    + subst. inv H5.\n    + subst. inv H5.\n    + subst. inv H5.\n    + subst. inv H5.\n    + subst. inv H0.\n      * destruct b2; crush.\n      * {\n          destruct b2.\n          - inv H5. crush.\n          - inv H5.\n            apply dry_no_in with (n:=N k v0 es) (s:=<< N k v0 es; l ->> pmap f ks :: os1'' >>) (os:=l ->> pmap f ks :: os1'') in H6; crush.\n        }\n    + subst. inv H0.\n      * destruct b2; crush.\n      * {\n          destruct b2.\n          - inv H5; crush.\n          - inv H5.\n            apply dry_no_in with (n:=N k t0 es) (s:=<< N k t0 es; l ->> pfold f t' ks :: os1'' >>) (os:=l ->> pfold f t' ks :: os1'') in H6; crush.\n        }\n    + subst. inv H0.\n      * destruct b2; crush.\n      * {\n          destruct b2.\n          - inv H5; crush.\n          - inv H5.\n            eapply dry_no_in with (n:=n1) (os:=l ->> op :: os1') in H6; eauto; crush.\n        }\n    + subst. inv H0.\n      * destruct b2; crush.\n      * {\n          destruct b2.\n          - inv H5; crush.\n          - inv H5.\n            eapply dry_no_in with (n:=n1) (os:=l ->> op :: os1') in H6; eauto; crush.\n        }\n    + subst. inv H0.\n      * destruct b2; crush.\n      * {\n          destruct b2.\n          - inv H5; crush.\n            destruct os1; crush.\n          - inv H5.\n            eapply dry_no_in with (n:=n) (os:=os1 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os2) in H6; eauto; crush. destruct os1; crush.\n        }\n    + subst. inv H0.\n      * destruct b2; crush.\n      * inv H2. inv H5.\n        {\n          destruct b2.\n          - inv H6; crush.\n          - inv H2.\n            eapply dry_no_in with (n:=n) in H6; eauto; crush.\n        }\n    + subst. inv H0.\n      * destruct b2; crush.\n      * inv H2. inv H5.\n        {\n          destruct b2.\n          - inv H2; crush. destruct os1; crush.\n          - inv H2.\n            eapply dry_no_in with (n:=n) (os:=os1 ++ l ->> pfold f t0 ks :: l' ->> pfold f' t' ks' :: os2) in H8; eauto.\n            + destruct os1; crush.\n            + crush.\n        }\n    + subst. inv H0.\n      * destruct b2; crush.\n      * {\n          destruct b2.\n          - inv H6; crush.\n          - inv H6.\n            eapply dry_no_in with (n:=n1) (os:=l ->> op :: os1) in H7; eauto; crush.\n        }\n    + subst. inv H2. inv H4.\n      apply dry_backend_dist with (b1:=b2) (b2:=<< N k t0 es; os1 >> :: b3) in H0; eauto.\n      destruct H0.\n      inv H2.\n      simpl in H8.\n      apply frontend_no_value in H6. apply H6. eauto.\n    + subst. inv H2. inv H4.\n      apply dry_backend_dist with (b1:=b2) (b2:=<< N k t0 es; os1 ++ l ->> pfold f t1 ks :: os' >> :: b3) in H0; eauto.\n      destruct H0.\n      inv H2.\n      simpl in H9.\n      destruct os1; crush.\n  - unfold normal_form in H.\n    remember WT. clear Heqw.\n    subst c; apply progress in w; eauto.\n    destruct w.\n    + destruct os.\n      * {\n        induction b.\n        - crush.\n        - destruct a as [n os].\n          + destruct os.\n            * constructor; eauto.\n              assert (dry (C b [] rs t)).\n              {\n                apply IHb.\n                - inversion WT.\n                  split; try split; eauto.\n                  crush.\n                  inversion H3; eauto.\n                  subst. exists x, x0. econstructor.\n                  + instantiate (1:=ll).\n                    inv H10.\n                    replace ll with ll'0 in * by eauto.\n                    auto.\n                  + instantiate (1:=ll'). auto.\n                  + auto.\n                - intro.\n                  destruct H1.\n                  unfold not in H.\n                  inversion H1; ssame; try solve [match goal with | [H : value _ |- _] => inv H end]; try solve [exfalso; apply H; eauto].\n                  + exfalso; apply H. eapply ex_intro; eapply S_PMap; eauto; crush.\n                  + exfalso; apply H. eapply ex_intro; eapply S_PFold; eauto; crush.\n                  + exfalso; apply H. eapply ex_intro; eapply S_Last; eauto; crush.\n                  + exfalso; apply H. eapply ex_intro; eapply S_FusePMap; eauto; crush.\n                  + exfalso; apply H. eapply ex_intro; eapply S_SwapReads with (f':=f'); eauto; crush.\n                  + exfalso; apply H. eapply ex_intro; eapply S_Prop; eauto; crush.\n                  + exfalso; apply H. eapply ex_intro; eapply S_Load; eauto; crush.\n                  + exfalso; apply H. eapply ex_intro; eapply S_LoadPFold; eauto; crush.\n              }\n              inv H1.\n              destruct n.\n              destruct (value_dec p); eauto.\n              eapply load_exists with (k:=k) (os:=[]) (b1:=[]) (b2:=b) in WT; eauto.\n              destruct WT.\n              unfold not in H. exfalso; apply H. exists x. assumption. crush.\n            * destruct l as [l op].\n              exfalso.\n              apply H.\n              destruct n; eapply op_reduction_exists with (b1:=[]) (b2:=b); eauto; crush.\n        }\n      * exfalso. apply H.\n        destruct l as [l op].\n        {\n        destruct op.\n        - destruct b.\n          eapply ex_intro; eapply S_Empty; eauto.\n          destruct s.\n          eapply ex_intro; eapply S_First; eauto.\n        - eapply ex_intro; eapply S_Add; eauto.\n        - destruct b.\n          eapply ex_intro; eapply S_Empty; eauto.\n          destruct s.\n          eapply ex_intro; eapply S_First; eauto.\n          Unshelve.\n          auto.\n          auto.\n          auto.\n          auto.\n          auto.\n          assert (value t1) by (eapply waiting_fold_value; eauto).\n          assert (has_type empty (rstream_types rs) t1 Result false) by (eapply graph_typing''' with (os:=[]); eauto).\n          destruct t1; try solve [inv H; inv H4]; try solve [inv H1]; try solve [inv H2].\n          right. eauto.\n        }\n    + crush.\nQed.\n\n\nDefinition stuck c : Prop := normal_form c /\\ ~ dry c.\n\n(* ****** end typing *)\n\nLtac apply_preservation :=\n  match goal with\n  | [H: C _ _ _ _ --> C _ _ _ _ |- _] => eapply preservation in H; eauto\n  end.\n\nLemma not_equal_not_in : forall {A : Type} (x:A) xs,\n  (forall x', In x' xs -> x <> x') ->\n  not (In x xs).\nProof using.\n  intros. intro. apply (@H x); auto.\nQed.\n\nLemma fresh_not_in : forall b os rs t t' l op,\n  distinct (config_labels (C b os rs t)) ->\n  FRf t rs ==> FRt t' [l ->> op] ->\n  not (In l (config_labels (C b os rs t))).\nProof using. intros; apply not_equal_not_in; auto. Qed.\n\nLemma fresh_not_in' : forall b os rs t t' l k v,\n  distinct (config_keys (C b os rs t)) ->\n  FRf t rs ==> FRt t' [l ->> add k v] ->\n  not (In k (config_keys (C b os rs t))).\nProof using. intros; apply not_equal_not_in; auto. Qed.\n\nLemma fresh :\n  forall t b os rs t' os',\n  distinct (config_labels (C b os rs t)) ->\n  FRf t rs ==> FRt t' os' ->\n  distinct (List.concat [backend_labels b; ostream_labels (os ++ os'); rstream_labels rs]).\nProof using.\n  induction t; intros; try solve [inv H0]; try solve [inv H0; try solve [eapply IHt in H; eauto]; try solve [eapply IHt1 in H; eauto]; try solve [eapply IHt2 in H; eauto]; try solve [eapply IHt3 in H; eauto]; try solve [crush]].\n  - inversion H0; subst; try solve [eapply IHt1 in H; eauto]; try solve [eapply IHt2 in H; eauto]; try solve [eapply IHt3 in H; eauto].\n    simpl. rewrite ostream_labels_dist. simpl.\n    replace  (backend_labels b ++ (ostream_labels os ++ [l]) ++ rstream_labels rs ++ []) with ((backend_labels b ++ ostream_labels os) ++ l :: rstream_labels rs) by crush.\n    apply distinct_rotate. econstructor; eauto.\n    + eapply fresh_not_in in H0; eauto. simpl in *. crush.\n    + crush.\n  - inversion H0; subst; try solve [eapply IHt1 in H; eauto]; try solve [eapply IHt2 in H; eauto]; try solve [eapply IHt3 in H; eauto].\n    simpl. rewrite ostream_labels_dist. simpl.\n    replace  (backend_labels b ++ (ostream_labels os ++ [l]) ++ rstream_labels rs ++ []) with ((backend_labels b ++ ostream_labels os) ++ l :: rstream_labels rs) by crush.\n    apply distinct_rotate. econstructor; eauto.\n    + eapply fresh_not_in in H0; eauto. simpl in *. crush.\n    + crush.\n  - inversion H0; subst; try solve [eapply IHt1 in H; eauto]; try solve [eapply IHt2 in H; eauto]; try solve [eapply IHt3 in H; eauto].\n    simpl. rewrite ostream_labels_dist. simpl.\n    replace  (backend_labels b ++ (ostream_labels os ++ [l]) ++ rstream_labels rs ++ []) with ((backend_labels b ++ ostream_labels os) ++ l :: rstream_labels rs) by crush.\n    apply distinct_rotate. econstructor; eauto.\n    + eapply fresh_not_in in H0; eauto. simpl in *. crush.\n    + crush.\nQed.\n\nLemma fresh' :\n  forall b os rs t os' t',\n  distinct (config_keys (C b os rs t)) ->\n  FRf t rs ==> FRt t' os' ->\n  distinct (List.concat [backend_keys b; ostream_keys (os ++ os')]).\nProof using.\n  induction t; intros; try solve [inv H0]; try solve [inv H0; try solve [eapply IHt in H; eauto]; try solve [eapply IHt1 in H; eauto]; try solve [eapply IHt2 in H; eauto]; try solve [eapply IHt3 in H; eauto]; try solve [crush]].\n  - inversion H0; subst; try solve [eapply IHt1 in H; eauto]; try solve [eapply IHt2 in H; eauto]; try solve [eapply IHt3 in H; eauto].\n    simpl. rewrite ostream_keys_dist. unfold ostream_keys in *; crush.\n  - inversion H0; subst; try solve [eapply IHt1 in H; eauto]; try solve [eapply IHt2 in H; eauto]; try solve [eapply IHt3 in H; eauto].\n    simpl. rewrite ostream_keys_dist. unfold ostream_keys in *; crush.\n  - inversion H0; subst; try solve [eapply IHt1 in H; eauto]; try solve [eapply IHt2 in H; eauto]; try solve [eapply IHt3 in H; eauto].\n    simpl. rewrite ostream_keys_dist. unfold ostream_keys at 2; simpl.\n    rewrite List.app_nil_r. rewrite List.app_assoc.\n    apply distinct_rotate. econstructor; eauto.\n    + eapply fresh_not_in' in H0; eauto. simpl in *. crush.\n    + crush.\nQed.\n\nLemma well_typed_preservation :\n  forall c1 c2,\n  well_typed c1 ->\n  c1 --> c2 ->\n  well_typed c2.\nProof using.\n  intros.\n  inversion H0; inversion H; eapply WT; subst;\n  try solve [match goal with | [H : exists _ _, _|- _] => destruct H as [T[E]] end; apply preservation with (T:=T) (E:=E) in H0; auto; destruct H0; destruct H0; inv H0; eauto];\n  try solve [apply_preservation].\n  (* S_Frontend *)\n  - eapply fresh'; eauto.\n  - eapply fresh; eauto.\n  (* S_Empty *)\n  - destruct op; crush.\n  (* S_First *)\n  - crush.\n  - destruct op; crush.\n  - crush. unfold backend_labels. simpl.\n    rewrite ostream_labels_dist. simpl. repeat (rewrite <- List.app_assoc). simpl.\n    unfold backend_labels in H9. simpl in H9. apply distinct_rotate_rev in H9.\n    apply distinct_rotate. crush.\n  (* S_Add *)\n  - crush. apply distinct_rotate_rev in H7. crush.\n  - crush. unfold backend_labels in *. simpl in *.\n    rewrite List.app_assoc.\n    apply distinct_rotate.\n    apply distinct_rotate_rev in H8.\n    crush.\n  - crush.\n  - crush.\n  (* S_PFold *)\n  - crush.\n  - crush.\n  (* S_Last *)\n  - crush.\n  - crush.\n    rewrite List.app_assoc.\n    rewrite List.app_assoc.\n    apply distinct_rotate.\n    apply distinct_rotate_rev in H10.\n    unfold backend_labels at 2.\n    crush.\n  (* S_FusePMap *)\n  - crush.\n  - crush.\n    unfold backend_labels at 2; simpl.\n    rewrite ostream_labels_dist; simpl.\n    repeat (rewrite <- List.app_assoc); simpl.\n    unfold backend_labels at 2 in H7; simpl in H7.\n    rewrite ostream_labels_dist in H7; simpl in H7.\n    repeat (rewrite <- List.app_assoc in H7); simpl in H7.\n    replace (backend_labels b1 ++ ostream_labels os1 ++ l' :: ostream_labels os2 ++ List.concat (map (fun s : station => ostream_labels (get_ostream s)) b2) ++ ostream_labels os ++ l :: rstream_labels rs)\n            with ((backend_labels b1 ++ ostream_labels os1 ++ l' :: ostream_labels os2 ++ List.concat (map (fun s : station => ostream_labels (get_ostream s)) b2) ++ ostream_labels os) ++ l :: rstream_labels rs) by crush.\n    apply distinct_rotate.\n    replace (l :: (backend_labels b1 ++ ostream_labels os1 ++ l' :: ostream_labels os2 ++ List.concat (map (fun s : station => ostream_labels (get_ostream s)) b2) ++ ostream_labels os) ++ rstream_labels rs)\n            with ((l :: (backend_labels b1 ++ ostream_labels os1)) ++ l' :: ostream_labels os2 ++ List.concat (map (fun s : station => ostream_labels (get_ostream s)) b2) ++ ostream_labels os ++ rstream_labels rs) by crush.\n    apply distinct_rotate.\n    replace (backend_labels b1 ++ ostream_labels os1 ++ l :: l' :: ostream_labels os2 ++ List.concat (map (fun s : station => ostream_labels (get_ostream s)) b2) ++ ostream_labels os ++ rstream_labels rs)\n            with ((backend_labels b1 ++ ostream_labels os1 ++ [l]) ++ l' :: ostream_labels os2 ++ List.concat (map (fun s : station => ostream_labels (get_ostream s)) b2) ++ ostream_labels os ++ rstream_labels rs) in H7 by crush.\n    apply distinct_rotate_rev in H7.\n    replace (l' :: (backend_labels b1 ++ ostream_labels os1 ++ [l]) ++ ostream_labels os2 ++ List.concat (map (fun s : station => ostream_labels (get_ostream s)) b2) ++ ostream_labels os ++ rstream_labels rs)\n            with((l' :: (backend_labels b1 ++ ostream_labels os1)) ++ l :: ostream_labels os2 ++ List.concat (map (fun s : station => ostream_labels (get_ostream s)) b2) ++ ostream_labels os ++ rstream_labels rs) in H7 by crush.\n    apply distinct_rotate_rev in H7.\n    apply distinct_rotate_front.\n    crush.\n  (* S_SwapReads *)\n  - crush.\n  - crush.\n    unfold backend_labels at 2 in H8; simpl in *. rewrite ostream_labels_dist in H8; simpl in *.\n    unfold backend_labels at 2; simpl in *. rewrite ostream_labels_dist; simpl in *.\n    repeat (rewrite <- List.app_assoc in *).\n    replace (backend_labels b1 ++ ostream_labels os1 ++ (l' :: l :: ostream_labels os2) ++ List.concat (map (fun s : station => ostream_labels (get_ostream s)) b2) ++ ostream_labels os ++ rstream_labels rs)\n            with ((backend_labels b1 ++ ostream_labels os1 ++ [l']) ++ l :: ostream_labels os2 ++ List.concat (map (fun s : station => ostream_labels (get_ostream s)) b2) ++ ostream_labels os ++ rstream_labels rs) by crush.\n    apply distinct_rotate.\n    rewrite List.app_assoc in H8. apply distinct_rotate_rev in H8. crush.\n  (* S_Prop *)\n  - crush.\n  - crush.\n    rewrite cons_app.\n    rewrite backend_labels_dist.\n    unfold backend_labels at 3.\n    simpl.\n    rewrite ostream_labels_dist.\n    unfold ostream_labels at 2.\n    simpl.\n    remember (List.concat (map (fun s : station => ostream_labels (get_ostream s)) b2)) as y.\n    remember (ostream_labels os ++ rstream_labels rs) as x1.\n    unfold backend_labels at 2.\n    simpl.\n    rewrite List.app_nil_r.\n    repeat (rewrite <- List.app_assoc).\n    repeat (rewrite <- List.app_assoc in H7).\n    apply distinct_app_comm in H7.\n    rewrite <- cons_app.\n    assert (backend_labels b1 ++ ostream_labels os1 ++ ostream_labels os2 ++ l :: y ++ x1 = (backend_labels b1 ++ ostream_labels os1 ++ ostream_labels os2) ++ l :: y ++ x1) by crush.\n    rewrite H3; clear H3.\n    apply distinct_rotate.\n    apply distinct_rotate in H7.\n    apply distinct_app_comm in H7.\n    crush.\n  (* S_Load *)\n  - crush.\n  - crush.\n  (* S_LoadPFold *)\n  - crush.\n  - crush. unfold backend_labels at 2 in H8; simpl in H8.\n    rewrite ostream_labels_dist in H8.\n    unfold backend_labels at 2; simpl.\n    rewrite ostream_labels_dist.\n    assumption.\nQed.\n\n(* ****** typing *)\n\nCorollary soundness : forall c c',\n  well_typed c ->\n  (exists n, c -->*[n] c') ->\n  ~(stuck c').\nProof using.\n  intros c c' WT.\n  intros Hmulti.\n  unfold stuck.\n  destruct Hmulti as [n Hmulti].\n  induction Hmulti.\n  - destruct x as [b os rs t].\n    eapply progress' in WT; eauto.\n    crush.\n  - assert (well_typed y) by (apply well_typed_preservation in H; crush).\n    crush.\nQed.\n\nTheorem unique_types : forall t Gamma ll T T' E E',\n  has_type Gamma ll t T E ->\n  has_type Gamma ll t T' E' ->\n  T = T' /\\ E = E'.\nProof using.\n  induction t; intros Gamma ll T T' E E' HT HT'.\n  - inv HT; inv HT'; crush.\n  - inv HT; inv HT'.\n    eapply IHt1 in H3; eauto.\n    eapply IHt2 in H6; eauto.\n    crush.\n  - inv HT; inv HT'.\n    eapply IHt in H6; eauto.\n    crush.\n  - inv HT; inv HT'; eauto. crush.\n  - inv HT; inv HT'; eauto.\n  - inv HT; inv HT'; eauto.\n  - inv HT; inv HT'.\n    eapply IHt1 with (T':=Result) (E':=E0) in H3; eauto.\n    eapply IHt2 with (T':=Keyset) (E':= E3) in H6; eauto.\n    crush.\n  - inv HT; inv HT'.\n    eapply IHt in H2; eauto.\n    crush.\n  - inv HT; inv HT'; eauto.\n  - inv HT; inv HT'; eauto.\n  - inv HT; inv HT'; eauto.\n  - inv HT; inv HT'.\n    eapply IHt1 with (T':=Result) (E':=E0) in H4; eauto.\n    eapply IHt2 with (T':=Result) (E':= E4) in H7; eauto.\n    eapply IHt3 with (T':=Keyset) (E':= E5) in H8; eauto.\n    crush.\n  - inv HT; inv HT'.\n    eapply IHt with (T:=Node) (E:=E') in H2; dtr; auto.\n  - inv HT; inv HT'.\n    eapply IHt with (T:=Node) (E:=E') in H2; dtr; auto.\n  - inv HT; inv HT'.\n    eapply IHt with (T:=Node) (E:=E') in H2; dtr; auto.\n  - inv HT; inv HT'.\n    eapply IHt with (T':=Arrow (Arrow t t (E0 || E1)) (Arrow t t E0) E1) (E':=E') in H5; crush.\nQed.\n\n(* ****** end typing *)\n\nReserved Notation \"c1 '==' c2\" (at level 40).\nInductive cequiv : config -> config -> Prop :=\n| cequiv_refl : forall c, c == c\n| cequiv_permutation : forall b os rs rs' term, Permutation.Permutation rs rs' -> C b os rs term == C b os rs' term\nwhere \"c1 == c2\" := (cequiv c1 c2).\nHint Constructors cequiv.\n\nLemma cequiv_trans :\n  forall c1 c2 c3,\n  c1 == c2 ->\n  c2 == c3 ->\n  c1 == c3.\nProof using.\n  intros.\n  inversion H; inversion H0; crush.\n  inversion H5.\n  apply cequiv_permutation.\n  crush.\nQed.\n\nLemma cequiv_symmetric :\n  forall c1 c2,\n  c1 == c2 ->\n  c2 == c1.\nProof using.\n  intros.\n  inversion H; crush.\nQed.\nHint Rewrite cequiv_symmetric.\n\nNotation \"cx -v cy\" := (exists cu cv, (exists n, cx -->*[n] cu) /\\ (exists m, cy -->*[m] cv) /\\ cu == cv) (at level 40).\nDefinition goes_to (c1 : config) (c2 : config) : Prop := c1 -v c2.\n\nLemma goes_to_symmetric :\n  forall c1 c2,\n  c1 -v c2 ->\n  c2 -v c1.\nProof using.\n  intros.\n  inversion H.\n  destruct H0.\n  eapply ex_intro.\n  eapply ex_intro.\n  split ; try split.\n  instantiate (1 := x0).\n  crush.\n  instantiate (1 := x).\n  crush.\n  apply cequiv_symmetric.\n  crush.\nQed.\nHint Resolve goes_to_symmetric.\n\nLemma goes_to_refl :\n  forall c,\n  c -v c.\nProof using.\n  intros.\n  apply ex_intro with (c).\n  eapply ex_intro with (c).\n  crush.\nQed.\nHint Immediate goes_to_refl.\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\nLtac dconcat := match goal with | [H : distinct (_ ++ _) |- _] => apply distinct_concat in H; dtr end.\n\nLemma distinct_nodes :\n  forall b os0 rs0 term0,\n  distinct (config_keys (C b os0 rs0 term0)) ->\n  distinct b.\nProof using.\n  induction b; intros; auto.\n  destruct a. destruct n. simpl in *.\n  econstructor; [eauto| |].\n  - intro.\n    apply List.in_split in H0; dtr; subst.\n    apply distinct_remove in H; dtr.\n    crush.\n  - apply distinct_remove in H; dtr.\n    eauto.\nQed.\n\nLemma distinct_ops :\n  forall b1 b2 n os os0 rs0 term0,\n  distinct (config_labels (C (b1 ++ <<n; os>> :: b2) os0 rs0 term0)) ->\n  distinct os.\nProof using.\n  induction os; intros; auto.\n  destruct a; simpl in *.\n  econstructor; [eauto| |].\n  - intro.\n    apply List.in_split in H0; dtr; subst.\n    rewrite backend_labels_dist in H. apply distinct_concat in H; dtr. apply distinct_concat in H; dtr.\n    unfold backend_labels in H1; simpl in *. rewrite ostream_labels_dist in H1; simpl in *.\n    apply distinct_remove in H1. crush.\n  - eapply IHos with (os0:=os0) (rs0:=rs0); auto.\n    rewrite backend_labels_dist in *. unfold backend_labels in H at 2. simpl in *.\n    repeat (rewrite <- List.app_assoc in H).\n    apply distinct_rotate_rev in H. apply distinct_remove in H; dtr. unfold backend_labels at 2. crush.\nQed.\n\nLemma target_unique :\n  forall b b' b1 b2 b3 b4 k v es os os0 rs0 t0,\n  well_typed (C b os0 rs0 t0) ->\n  b = b' ->\n  b = b1 ++ [<<N k v es; os>>] ++ b2 ->\n  b' = b3 ++ [<<N k v es; os>>] ++ b4 ->\n  (b1 = b3 /\\ b2 = b4).\nProof using.\n  intros.\n  eapply distinct_center with (l:=b).\n  eapply distinct_nodes with (os0:=os0) (rs0:=rs0) (term0:=t0); eauto. { inv H; eauto. }\n  instantiate (1:=b').\n  assumption.\n  instantiate (1:=<<N k v es; os>>).\n  assumption.\n  crush.\nQed.\nHint Resolve target_unique.\n\nLemma op_unique :\n  forall b n b1 b2 lop os os' os1 os2 os3 os4 os0 rs0 t0,\n  well_typed (C b os0 rs0 t0) ->\n  b = b1 ++ <<n; os>> :: b2 ->\n  os = os' ->\n  os = os1 ++ lop :: os2 ->\n  os' = os3 ++ lop :: os4 ->\n  (os1 = os3 /\\ os2 = os4).\nProof using.\n  intros.\n  apply distinct_center with (l:=os) (l':=os') (x:=lop); eauto; crush.\n  apply distinct_ops with (term0:=t0) (rs0:=rs0) (os0:=os0) (b1:=b1) (b2:=b2) (n:=n).\n  inv H; crush.\nQed.\nHint Resolve op_unique.\n\nLemma unique_lop :\n  forall os l op op' n b1 b2 os0 rs0 term0,\n  well_typed (C (b1 ++ <<n; os>> :: b2) os0 rs0 term0) ->\n  In (l ->> op) os ->\n  In (l ->> op') os ->\n  op = op'.\nProof using.\n  intros os l op op' n b1 b2 os0 rs0 term0 WT Inop Inop'.\n  apply List.in_split in Inop.\n  destruct Inop.\n  destruct H.\n  subst.\n  apply List.in_app_or in Inop'.\n  destruct Inop'.\n  - apply List.in_split in H.\n    destruct H.\n    destruct H.\n    subst.\n    exfalso.\n    inversion WT.\n    unfold config_labels in H0.\n    simpl in *.\n    rewrite backend_labels_dist in H0.\n    unfold backend_labels at 2 in H0.\n    simpl in H0.\n    rewrite ostream_labels_dist in H0.\n    simpl in H0.\n    repeat (rewrite <- List.app_assoc in H0).\n    apply distinct_concat in H0.\n    destruct H0.\n    apply distinct_rotate_rev in H3.\n    rewrite ostream_labels_dist in H3.\n    unfold ostream_labels at 2 in H3.\n    simpl in H3.\n    clear H1 H H0.\n    rewrite -> List.app_comm_cons in H3.\n    apply distinct_concat in H3.\n    destruct H3.\n    clear H0.\n    apply distinct_rotate in H.\n    apply distinct_concat in H.\n    destruct H.\n    inv H0.\n    crush.\n  - apply List.in_inv in H.\n    destruct H.\n    + crush.\n    + exfalso.\n      apply List.in_split in H.\n      destruct H.\n      destruct H.\n      subst.\n      inversion WT.\n      clear H1 H WT.\n      unfold config_labels in H0.\n      simpl in H0.\n      rewrite backend_labels_dist in H0.\n      apply distinct_concat in H0.\n      destruct H0.\n      apply distinct_concat in H.\n      destruct H.\n      unfold backend_labels in H1.\n      simpl in H1.\n      rewrite ostream_labels_dist in H1.\n      clear H0.\n      rewrite List.app_comm_cons in H1.\n      rewrite ostream_labels_dist in H1.\n      apply distinct_concat in H1.\n      destruct H1.\n      apply distinct_concat in H0.\n      destruct H0.\n      clear H H0 H1.\n      simpl in H2.\n      apply distinct_rotate in H3.\n      apply distinct_concat in H3.\n      destruct H3.\n      inv H0.\n      crush.\nQed.\n\nLemma op_unique' :\n  forall b n b1 b2 op l op' os os' os1 os2 os3 os4 os0 rs0 t0,\n  well_typed (C b os0 rs0 t0) ->\n  b = b1 ++ <<n; os>> :: b2 ->\n  os = os' ->\n  os = os1 ++ l ->> op :: os2 ->\n  os' = os3 ++ l ->> op' :: os4 ->\n  (os1 = os3 /\\ os2 = os4 /\\ op = op').\nProof using.\n  intros.\n  assert (op = op') by (eapply unique_lop with (b1:=b1) (b2:=b2) (l:=l) (op:=op) (op':=op'); subst; eauto; crush).\n  split; try split; try assumption; try reflexivity; subst.\n  eapply op_unique with (os1:=os1) (os2:=os2) (os3:=os3) (os4:=os4); eauto.\n  eapply op_unique with (os1:=os1) (os2:=os2) (os3:=os3) (os4:=os4); eauto.\nQed.\n\nLemma unique_key :\n  forall k v es es' os v' os' b os0 rs0 term0,\n  well_typed (C b os0 rs0 term0) ->\n  In <<N k v es; os>> b ->\n  In <<N k v' es'; os'>> b ->\n  v = v' /\\ os = os' /\\ es = es'.\nProof using.\n  intros k v es es' os v' os' b os0 rs0 term0 WT Inb Inb'.\n  apply List.in_split in Inb'.\n  destruct Inb'.\n  destruct H.\n  subst.\n  inversion WT.\n  clear H0 H1 WT.\n  apply List.in_app_or in Inb.\n  destruct Inb.\n  - apply List.in_split in H0.\n    destruct H0.\n    destruct H0.\n    subst.\n    unfold config_keys in H.\n    simpl in H.\n    apply distinct_concat in H.\n    destruct H.\n    clear H0.\n    rewrite backend_keys_dist in H.\n    rewrite backend_keys_dist in H.\n    simpl in H.\n    apply distinct_rotate_rev in H.\n    rewrite List.app_comm_cons in H.\n    apply distinct_concat in H.\n    destruct H.\n    clear H0.\n    apply distinct_rotate in H.\n    apply distinct_concat in H.\n    destruct H.\n    clear H.\n    inv H0.\n    crush.\n  - apply List.in_inv in H0.\n    + destruct H0.\n      * crush.\n      * exfalso.\n        apply List.in_split in H0.\n        destruct H0.\n        destruct H0.\n        subst.\n        unfold config_keys in H.\n        simpl in H.\n        apply distinct_concat in H.\n        destruct H.\n        clear H0.\n        rewrite backend_keys_dist in H.\n        apply distinct_concat in H.\n        destruct H.\n        clear H.\n        simpl in H0.\n        rewrite backend_keys_dist in H0.\n        simpl in H0.\n        apply distinct_rotate in H0.\n        apply distinct_concat in H0.\n        destruct H0.\n        inv H0.\n        crush.\nQed.\n\nLemma target_unique' :\n  forall b b' b1 b2 b3 b4 k v es es' v' os' os os0 rs0 t0,\n  well_typed (C b os0 rs0 t0) ->\n  b = b' ->\n  b = b1 ++ [<<N k v es; os>>] ++ b2 ->\n  b' = b3 ++ [<<N k v' es'; os'>>] ++ b4 ->\n  (b1 = b3 /\\ b2 = b4 /\\ v = v' /\\ os = os' /\\ es = es').\nProof using.\n  intros.\n  assert (v = v') by (eapply unique_key with (es:=es) (es':=es') (k:=k) (v:=v) (v':=v') (os:=os) (os':=os'); eauto; subst; crush).\n  assert (os = os') by (eapply unique_key with (es:=es) (es':=es') (k:=k) (v:=v) (v':=v') (os:=os) (os':=os'); eauto; subst; crush).\n  assert (es = es') by (eapply unique_key with (es:=es) (es':=es') (k:=k) (v:=v) (v':=v') (os:=os) (os':=os'); eauto; subst; crush).\n  subst.\n  split; try split; try split; try split; try assumption; try reflexivity.\n  eapply target_unique with (b1:=b1) (b2:=b2) (b3:=b3) (b4:=b4); eauto.\n  eapply target_unique with (b1:=b1) (b2:=b2) (b3:=b3) (b4:=b4); eauto.\nQed.\nHint Resolve target_unique.\n\nLemma target_same_or_different :\n  forall b b1 b2 b3 b4 k v es es' k' v' os os' os0 rs0 term0,\n  well_typed (C b os0 rs0 term0) ->\n  b = b1 ++ <<N k v es; os>> :: b2 ->\n  b = b3 ++ <<N k' v' es'; os'>> :: b4 ->\n  (b1 = b3 /\\ b2 = b4 /\\ k = k' /\\ v = v' /\\ os = os') \\/\n  (exists (b' : backend) b'' b''', b = b' ++ <<N k v es; os>> :: b'' ++ <<N k' v' es'; os'>> :: b''') \\/\n  (exists (b' : backend) b'' b''', b = b' ++ <<N k' v' es'; os'>> :: b'' ++ <<N k v es; os>> :: b''').\nProof using.\n  intros.\n  destruct (Nat.eq_dec k k') as [keq|kneq].\n  - rewrite keq in *. clear keq.\n    assert (v = v') by (eapply target_unique' with (es:=es) (es':=es'); eauto; crush).\n    assert (os = os') by (eapply target_unique'; eauto; crush).\n    assert (es = es') by (eapply target_unique'; eauto; crush).\n    assert (b1 = b3 /\\ b2 = b4) by (eapply target_unique with (b:=b) (b1:=b1) (b2:=b2) (b3:=b3) (b4:=b4); eauto; crush).\n    left.\n    crush.\n  - subst.\n    assert (In << N k' v' es'; os' >> (b1 ++ << N k v es; os >> :: b2)) by crush.\n    apply List.in_app_or in H0.\n    destruct H0.\n    * right.\n      right.\n      apply List.in_split in H0.\n      destruct H0.\n      destruct H0.\n      subst.\n      assert ((x ++ << N k' v' es'; os' >> :: x0) ++ << N k v es; os >> :: b2 = x ++ << N k' v' es'; os' >> :: x0 ++ << N k v es; os >> :: b2) by crush.\n      eauto.\n    * right.\n      left.\n      apply List.in_split in H0.\n      destruct H0.\n      destruct H0.\n      {\n      destruct x.\n      - crush.\n      - inversion H0.\n        eauto.\n      }\nQed.\n\nLemma op_same_or_different :\n  forall b1 b2 n os0 rs0 term0 os os1 os2 os3 os4 lop lop',\n  well_typed (C (b1 ++ <<n;os>> :: b2) os0 rs0 term0) ->\n  os = os1 ++ lop :: os2 ->\n  os = os3 ++ lop' :: os4 ->\n  (os1 = os3 /\\ os2 = os4 /\\ lop = lop') \\/\n  (exists (os' : ostream) os'' os''', os = os' ++ lop :: os'' ++ lop' :: os''') \\/\n  (exists (os' : ostream) os'' os''', os = os' ++ lop' :: os'' ++ lop :: os''').\nProof using.\n  intros.\n  destruct lop as [l op].\n  destruct lop' as [l' op'].\n  destruct (Nat.eq_dec l l') as [leq|lneq].\n  - subst.\n    left.\n    eapply op_unique' with (os1:=os1) (os2:=os2) in H1; eauto.\n    split; try split; crush.\n  - assert (In (l' ->> op') (os1 ++ l ->> op :: os2)) by crush.\n    apply List.in_app_or in H2.\n    destruct H2.\n    + right.\n      right.\n      apply List.in_split in H2.\n      destruct H2.\n      destruct H2.\n      subst.\n      assert ((x ++ l' ->> op' :: x0) ++ l ->> op :: os2 = x ++ l' ->> op' :: x0 ++ l ->> op :: os2) by crush.\n      eauto.\n    + right.\n      left.\n      apply List.in_split in H2.\n      destruct H2.\n      destruct H2.\n      {\n      destruct x.\n      - crush.\n      - inversion H2.\n        crush.\n        eauto.\n      }\nQed.\n\nLtac got := eapply ex_intro; eapply ex_intro; split; try split.\nLtac one_step := apply ex_intro with (1); apply one_star.\nLtac gotw X := got; try instantiate (1:=X); try one_step.\n\nLemma list_apps :\n  forall {A : Type} (xs : list A),\n  exists x y, xs = x ++ y.\nProof using.\n  intros.\n  induction xs.\n  - eapply ex_intro.\n    eapply ex_intro.\n    instantiate (1:=[]).\n    instantiate (1:=[]).\n    crush.\n  - destruct IHxs.\n    destruct H.\n    eapply ex_intro.\n    eapply ex_intro.\n    instantiate (1:=x0).\n    instantiate (1:=a::x).\n    crush.\nQed.\n\nLemma list_snoc :\n  forall {A : Type} xs' (x : A) xs,\n  xs = x :: xs' ->\n  exists y ys,\n  xs = ys ++ [y].\nProof using.\n  intros A xs'.\n  induction xs'; intros.\n  - eapply ex_intro; eapply ex_intro.\n    instantiate (1:=x).\n    instantiate (1:=[]).\n    crush.\n  - remember (a :: xs') as xxs.\n    apply IHxs' with (xs:=xxs) (x:=a) in Heqxxs.\n    destruct Heqxxs.\n    destruct H0.\n    eapply ex_intro.\n    eapply ex_intro.\n    instantiate (1:=x0).\n    instantiate (1:=x::x1).\n    crush.\nQed.\n\nLemma frontend_rstream_extension :\n  forall t rs t' os lr,\n  FRf t rs ==> FRt t' os ->\n  FRf t (lr :: rs) ==> FRt t' os.\nProof using.\n  induction t; intros; rename H into Hstep; try solve [inv Hstep; eauto].\n  - inv Hstep.\n    + eapply F_Claim. crush.\n    + eauto.\nUnshelve.\nauto.\nauto.\nQed.\nHint Resolve frontend_rstream_extension.\n\nLemma unique_result :\n  forall b os rs t l r r',\n  well_typed (C b os rs t) ->\n  In (l ->>> r) rs ->\n  In (l ->>> r') rs ->\n  r = r'.\nProof using.\n  intros b os rs t l r r' WT In1 In2.\n  inversion WT as [c H H0 TT H1].\n  apply List.in_split in In1.\n  destruct In1. destruct H2.\n  subst.\n  apply List.in_app_or in In2.\n  destruct In2.\n  - apply List.in_split in H1.\n    destruct H1.\n    destruct H1.\n    subst.\n    simpl in H0.\n    apply distinct_concat in H0.\n    destruct H0.\n    apply distinct_concat in H1.\n    destruct H1.\n    rewrite List.app_nil_r in H2.\n    rewrite rstream_labels_dist in H2.\n    rewrite rstream_labels_dist in H2.\n    unfold rstream_labels at 2 in H2.\n    simpl in H2.\n    apply distinct_rotate_rev in H2.\n    rewrite List.app_comm_cons in H2.\n    rewrite List.app_comm_cons in H2.\n    rewrite <- List.app_assoc in H2.\n    simpl in H2.\n    apply distinct_rotate in H2.\n    apply distinct_concat in H2.\n    destruct H2.\n    inv H3.\n    crush.\n  - apply List.in_split in H1.\n    destruct H1.\n    destruct H1.\n    destruct x1; crush.\n    apply distinct_concat in H0.\n    destruct H0.\n    apply distinct_concat in H1.\n    destruct H1.\n    apply distinct_rotate_rev in H3.\n    rewrite List.app_comm_cons in H3.\n    rewrite List.app_assoc in H3.\n    apply distinct_rotate_rev in H3.\n    simpl in H3.\n    inversion H3.\n    crush.\nQed.\n\nLtac fdet :=\n  try solve [match goal with\n             | [H : ?b ++ _ = [] |- _] => destruct b; inv H\n             | [H : [] = ?b ++ _ |- _] => destruct b; inv H\n             end];\n  try solve [ssame];\n  try solve [repeat (match goal with\n                     | [H : C _ _ _ _ = C _ _ _ _ |- _] => inv H\n                     end); try solve [split; crush]; try solve [exfalso; eapply frontend_no_value; eauto]].\n\nLtac fnv :=\n      match goal with\n      | [H : FRf ?t _ ==> FRt _ _, H' : value ?t |- _] => exfalso; eapply frontend_no_value in H; eauto\n      end.\n\nLemma frontend_deterministic' :\n  forall t b0 os0 rs os t',\n  well_typed (C b0 os0 rs t) ->\n  FRf t rs ==> FRt t' os ->\n  forall t'' os',\n  FRf t rs ==> FRt t'' os' ->\n  t' = t'' /\\ os = os'.\nProof using.\n  induction t; intros; rename H0 into Hstep; rename H1 into Hstep'; try solve [inv Hstep].\n  - inv Hstep; inv Hstep'; try solve [fnv].\n    + split; eauto.\n    + inv H2.\n    + inv H1.\n    + eapply IHt1 with (t':= t1'0) (os:=os') in H1; dtr; subst; eauto.\n      inv H; dtr; split; try split; eauto.\n    + eapply IHt2 with (t':= t2'0) (os:=os') in H6; dtr; subst; eauto.\n      inv H; dtr; split; try split; eauto.\n  - inv Hstep; inv Hstep'; try solve [fnv].\n    + eapply IHt1 with (t':=k'0) (os:=os') in H1; dtr; subst; eauto.\n      inv H; dtr; split; try split; eauto.\n    + eapply IHt2 with (t':=ks'0) (os:=os') in H6; dtr; subst; eauto.\n      inv H; dtr; split; try split; eauto.\n  - inv Hstep; inv Hstep'; try solve [fnv].\n    + eapply unique_result with (r':=v0) in H1; eauto.\n    + inv H2.\n    + inv H1.\n    + eapply IHt with (t':=t') (os:=os') in H1; dtr; subst; eauto.\n      inv H; dtr; split; try split; eauto.\n  - inv Hstep; inv Hstep'; try solve [fnv].\n    + eauto.\n    + eapply IHt1 with (t':=t1'0) (os:=os') in H1; dtr; subst; eauto.\n      inv H; dtr; split; try split; eauto.\n    + eapply IHt2 with (t':=t2'0) (os:=os') in H8; dtr; subst; eauto.\n      inv H; dtr; split; try split; eauto.\n    + eapply IHt3 with (t':=t3'0) (os:=os') in H9; dtr; subst; eauto.\n      inv H; dtr; split; try split; eauto.\n  - inv Hstep; inv Hstep'; try solve [fnv].\n    + eauto.\n    + eapply IHt1 with (t':=t1'0) (os:=os') in H1; dtr; subst; eauto.\n      inv H; dtr; split; try split; eauto.\n    + eapply IHt2 with (t':=t2'0) (os:=os') in H7; dtr; subst; eauto.\n      inv H; dtr; split; try split; eauto.\n  - inv Hstep; inv Hstep'; try solve [fnv].\n    + eauto.\n    + inv H1.\n    + inv H7.\n    + inv H1.\n    + eapply IHt1 with (t':=t1'0) (os:=os') in H1; dtr; subst; eauto.\n      inv H; dtr; split; try split; eauto.\n    + inv H7.\n    + eapply IHt2 with (t':=t2'0) (os:=os') in H7; dtr; subst; eauto.\n      inv H; dtr; split; try split; eauto.\n  - inv Hstep; inv Hstep'; try solve [fnv].\n    + eapply IHt1 with (t':=k'0) (os:=os') in H1; dtr; subst; eauto.\n      inv H; dtr; split; try split; eauto.\n      inv H; dtr. inv H12. exi; eauto.\n    + eapply IHt2 with (t':=p'0) (os:=os') in H7; dtr; subst; eauto.\n      inv H; dtr; split; try split; eauto.\n      inv H; dtr. inv H14. exi; eauto.\n    + eapply IHt3 with (t':=es'0) (os:=os') in H8; dtr; subst; eauto.\n      inv H; dtr; split; try split; eauto.\n      inv H; dtr. inv H16. exi; eauto.\n  - inv Hstep; inv Hstep'; try solve [fnv]; try solve [exfalso; eapply frontend_no_value; eauto]; try solve [eauto].\n    + eapply IHt with (t':=t') (os:=os') in H1; dtr; subst; eauto.\n      inv H; dtr; split; try split; eauto.\n      inv H; dtr. inv H12. exi; eauto.\n  - inv Hstep; inv Hstep'; try solve [fnv]; try solve [exfalso; eapply frontend_no_value; eauto]; try solve [eauto].\n    + eapply IHt with (t':=t') (os:=os') in H1; dtr; subst; eauto.\n      inv H; dtr; split; try split; eauto.\n      inv H; dtr. inv H12. exi; eauto.\n  - inv Hstep; inv Hstep'; try solve [fnv]; try solve [exfalso; eapply frontend_no_value; eauto]; try solve [eauto].\n    + eapply IHt with (t':=t') (os:=os') in H1; dtr; subst; eauto.\n      inv H; dtr; split; try split; eauto.\n      inv H; dtr. inv H12. exi; eauto.\n  - inv Hstep; inv Hstep'; try solve [fnv].\n    + eauto.\n    + eapply IHt with (t':=t') (os:=os') in H1; dtr; subst; eauto.\n      inv H; dtr; split; try split; eauto.\n      inv H; dtr. inv H12. exi; eauto.\nQed.\n\nLemma list_app_cons_empty : forall {A : Type} (x : A) xs ys,\n  xs ++ x :: ys = [] -> False.\nProof using.\n  induction xs; crush.\nQed.\nHint Resolve list_app_cons_empty.\n\nLtac trouble_makers := try solve [eapply S_Add; eauto]; try solve [eapply S_FusePMap; eauto].\n\nLtac match_frontend :=\n  match goal with\n  | [H : C ?b ?os ?rs ?t --> C ?b' ?os' ?rs' ?t, H' : FRf ?t ?rs ==> FRt ?t' ?os'' |- _] =>\n    gotw (C b' (os' ++ os'') rs' t'); simpl; eauto; trouble_makers\n  end.\n\nLemma lc_frontend :\n  forall cx cy cz b os os' rs t t',\n  well_typed cx ->\n  cx = C b os rs t ->\n  cy = C b (os ++ os') rs t' ->\n  FRf t rs ==> FRt t' os' ->\n  cx --> cy ->\n  cx --> cz ->\n  cy -v cz.\nProof using.\n  intros cx cy cz b os os' rs t t'.\n  intros WT Heqcx Heqcy.\n  intros Hstep.\n  intros cxcy cxcz.\n  inversion cxcz; ssame; try solve match_frontend; ssame'.\n  (* S_Frontend *)\n  - eapply frontend_deterministic' with (t':=t'0) (os:=os'0) in Hstep; dtr; subst; auto.\n    + inv WT; dtr. split; try split; eauto.\nUnshelve.\nauto.\nauto.\nQed.\nHint Resolve lc_frontend.\n\nLtac tsod := match goal with\n             | [H : ?b1 ++ <<N ?k ?t ?es; ?os>> :: ?b2 = ?b3 ++ <<N ?k' ?t' ?es'; ?os'>> :: ?b4 |- _] =>\n                 eapply (@target_same_or_different _ b1 b2 b3 b4 k t es es' k' t') in H; eauto; destruct H as [Hsame|Hwhich]; try destruct Hwhich as [Hfirst|Hsecond];\n                 try (destruct Hsame as [Hsame1 Hsame2]; destruct Hsame2 as [Hsame2 Hsame3]; destruct Hsame3 as [Hsame3 Hsame4]; destruct Hsame4 as [Hsame4 Hsame5]; subst)\n             end.\n\nLtac tsod' := match goal with\n              | [H : ?b1 ++ <<N ?k ?t ?es; ?os>> :: ?b2 = ?b3 ++ <<N ?k' ?t' ?es'; ?os' ++ ?os''>> :: ?b4 |- _] =>\n                  eapply (@target_same_or_different _ b1 b2 b3 b4 k t es es' k' t' os (os' ++ os'')) in H; eauto; destruct H as [Hsame|Hwhich]; try destruct Hwhich as [Hfirst|Hsecond];\n                  try (destruct Hsame as [Hsame1 Hsame2]; destruct Hsame2 as [Hsame2 Hsame3]; destruct Hsame3 as [Hsame3 Hsame4]; destruct Hsame4 as [Hsame4 Hsame5]; subst)\n              end.\n\nLtac tsod'' := match goal with\n              | [H : ?b1 ++ <<N ?k ?t ?es; ?os ++ ?os'''>> :: ?b2 = ?b3 ++ <<N ?k' ?t' ?es'; ?os' ++ ?os''>> :: ?b4 |- _] =>\n                  eapply (@target_same_or_different _ b1 b2 b3 b4 k t es es' k' t' (os ++ os''') (os' ++ os'')) in H; eauto; destruct H as [Hsame|Hwhich]; try destruct Hwhich as [Hfirst|Hsecond];\n                  try (destruct Hsame as [Hsame1 Hsame2]; destruct Hsame2 as [Hsame2 Hsame3]; destruct Hsame3 as [Hsame3 Hsame4]; destruct Hsame4 as [Hsame4 Hsame5]; subst)\n              end.\n\nLtac tu1 := match goal with\n            | [H : ?b1 ++ <<N ?k ?t ?es; ?os>> :: ?b2 = ?b3 ++ <<N ?k ?t ?es; ?os>> :: ?b' ++ <<N ?k' ?t' ?es'; ?os'>> :: ?b4 |- _] =>\n            eapply (@target_unique _ _ b1 b2 b3 _) in H; crush\n            end;\n            match goal with\n            | [H : C _ _ _ _ = C _ _ _ _ |- _] => inv H\n            end;\n            match goal with\n            | [H : ?b1 ++ <<N ?k' ?t' ?es'; ?os'>> :: ?b' ++ <<N ?k ?t ?es; ?os>> :: ?b2 = ?b3 ++ <<N ?k ?t ?es; ?os>> :: ?b4 |- _] =>\n              eapply (@target_unique _ _ (b1 ++ <<N k' t' es'; os'>> :: b') b2 b3 b4) in H; eauto; crush\n            end.\n\nLtac tu2 := match goal with\n            | [H : ?b1 ++ <<N ?k ?t ?es; ?os>> :: ?b2 = ?b3 ++ <<N ?k' ?t' ?es'; ?os'>> :: ?b' ++ <<N ?k ?t ?es; ?os>> :: ?b4 |- _] =>\n              eapply (@target_unique _ _ b1 b2 (b3 ++ <<N k' t' es'; os'>> :: b') b4) in H; eauto; crush\n            end;\n            match goal with\n            | [H : C _ _ _ _ = C _ _ _ _ |- _] => inv H\n            end;\n            match goal with\n            | [H : ?b1 ++ <<N ?k ?t ?es; ?os>> :: ?b' ++ <<N ?k' ?t' ?es'; ?os'>> :: ?b2 = ?b3 ++ <<N ?k ?t ?es; ?os>> :: ?b4 |- _] =>\n              eapply (@target_unique _ _ b1 (b' ++ <<N k' t' es'; os'>> :: b2) b3 b4) in H; eauto; crush\n            end.\n\nLemma pmap_value : forall b1 b2 n l os0 rs0 t0 f ks os os',\n  well_typed (C (b1 ++ <<n; os ++ l ->> pmap f ks :: os'>> :: b2) os0 rs0 t0) ->\n  value f.\nProof using.\n  intros.\n  inv H.\n  destruct H2 as [T[E]].\n  inv H.\n  wtbdist.\n  inv H2.\n  wtosdist.\n  inv H3.\n  inv H15.\n  auto.\nQed.\n\nLemma pfold_value : forall b1 b2 n l os0 rs0 t0 f t ks os os',\n  well_typed (C (b1 ++ <<n; os ++ l ->> pfold f t ks :: os'>> :: b2) os0 rs0 t0) ->\n  value f.\nProof using.\n  intros.\n  inv H.\n  destruct H2 as [T[E]].\n  inv H.\n  wtbdist.\n  inv H2.\n  wtosdist.\n  inv H3.\n  inv H15.\n  auto.\nQed.\n\nLemma lc_load :\n  forall cx cy cz b1 b2 k os t es t' term0 os0 rs0,\n  well_typed cx ->\n  cx = C (b1 ++ <<N k t es; os>> :: b2) os0 rs0 term0 ->\n  cy = C (b1 ++ <<N k t' es; os>> :: b2) os0 rs0 term0 ->\n  cx --> cy ->\n  cx --> cz ->\n  FRf t rs0 ==> FRt t' [] ->\n  cy -v cz.\nProof using.\n  intros cx cy cz b1 b2 k os t es t' term0 os0 rs0.\n  intros WT Heqcx Heqcy cxcy cxcz.\n  intros tt'.\n  inversion cxcz; ssame; try solve [subst; eauto].\n  (* S_Empty *)\n  - exfalso; eauto.\n  (* S_First *)\n  - destruct b1; simpl in *.\n    + inv H1.\n      gotw (C (<< N k t' es; os2 ++ [l ->> op] >> :: b') os' rs term1); eauto.\n      eapply S_Load with (b1:=[]); eauto; crush.\n    + inv H1.\n      gotw (C (<< n1; os2 ++ [l ->> op] >> :: b1 ++ << N k t' es; os >> :: b2) os' rs term1); eauto.\n      eapply S_Load with (b1:=<< n1; os2 ++ [l ->> op] >> :: b1); eauto; crush.\n  (* S_Add *)\n  - gotw (C (<< N k0 v t_ks_nil; [] >> :: b1 ++ << N k t' es; os >> :: b2) os' (l ->>> final H :: rs) term1); eauto.\n    eapply S_Load with (b1:=<< N k0 v t_ks_nil; [] >> :: b1); eauto; crush.\n  (* S_PMap *)\n  - tsod.\n    + inv H. apply List.app_inv_head in H1. inv H1.\n      got.\n      * one_step. instantiate (1:=C (b0 ++ << N k0 (t_app f t') es0; l ->> pmap f (remove Nat.eq_dec k0 ks) :: os1'' >> :: b3) os1 rs term1).\n        eapply S_PMap; eauto.\n      * one_step. instantiate (1:=C (b0 ++ << N k0 (t_app f t') es0; l ->> pmap f (remove Nat.eq_dec k0 ks) :: os1'' >> :: b3) os1 rs term1).\n        eapply S_Load; eauto.\n        eapply F_App2 with (os:=[]); eauto.\n        remember (pmap f ks) as op; subst op; eapply pmap_value with (os:=[]); eauto.\n      * crush.\n    + destruct Hfirst as [b' [b'' [b''']]].\n      tu1.\n      got.\n      * one_step. instantiate (1:=C ((b' ++ << N k t' es; os >> :: b'') ++ << N k0 (t_app f v) es0; l ->> pmap f (remove Nat.eq_dec k0 ks) :: os1'' >> :: b3) os1 rs term1).\n        eapply S_PMap; eauto; crush.\n      * one_step. instantiate (1:=C (b' ++ << N k t' es; os >> :: b'' ++ << N k0 (t_app f v) es0; l ->> pmap f (remove Nat.eq_dec k0 ks) :: os1'' >> :: b3) os1 rs term1).\n        eapply S_Load; eauto; crush.\n      * crush.\n    + destruct Hsecond as [b' [b'' [b''']]].\n      tu2.\n      got.\n      * instantiate (1:=C (b0 ++ << N k0 (t_app f v) es0; l ->> pmap f (remove Nat.eq_dec k0 ks) :: os1'' >> :: b'' ++ << N k t' es; os >> :: b''') os1 rs term1).\n        one_step; eapply S_PMap; eauto.\n      * instantiate (1:=C ((b0 ++ << N k0 (t_app f v) es0; l ->> pmap f (remove Nat.eq_dec k0 ks) :: os1'' >> :: b'') ++ << N k t' es; os >> :: b''') os1 rs term1).\n        one_step; eapply S_Load; eauto; crush.\n      * crush.\n  (* S_PFold *)\n  - tsod.\n    + got. inv H. apply List.app_inv_head in H1. inv H1.\n      * instantiate (1:=C (b0 ++ << N k0 t' es0; l ->> pfold f (t_app (t_app f t') t'0) (remove Nat.eq_dec k0 ks) :: os1'' >> :: b3) os1 rs term1).\n        one_step. eapply S_PFold; eauto.\n      * instantiate (1:=C (b0 ++ << N k0 t' es0; l ->> pfold f (t_app (t_app f t') t'0) (remove Nat.eq_dec k0 ks) :: os1'' >> :: b3) os1 rs term1).\n        exists 2.\n        eapply Step.\n        instantiate (1:=C (b0 ++ << N k0 t' es0; l ->> pfold f (t_app (t_app f t0) t'0) (remove Nat.eq_dec k0 ks) :: os1'' >> :: b3) os1 rs term1).\n        eapply S_Load; eauto.\n        apply one_star.\n        {\n        eapply S_LoadPFold with (os:=[]).\n        - instantiate (1:=(b0 ++ << N k0 t' es0; l ->> pfold f (t_app (t_app f t0) t'0) (remove Nat.eq_dec k0 ks) :: os1'' >> :: b3)).\n          reflexivity.\n        - simpl. eauto.\n        - instantiate (1:=(t_app (t_app f t') t'0)).\n          eapply F_App1 with (os:=[]).\n          eapply F_App2 with (os:=[]).\n          eapply pfold_value with (os:=[]); eauto.\n          assumption.\n        - crush.\n        }\n      * crush.\n    + destruct Hfirst as [b' [b'' [b''']]].\n      tu1.\n      got.\n      * instantiate (1:=C ((b' ++ << N k t' es; os >> :: b'') ++ << N k0 t0 es0; l ->> pfold f (t_app (t_app f t0) t'0) (remove Nat.eq_dec k0 ks) :: os1'' >> :: b3) os1 rs term1).\n        one_step; eapply S_PFold; eauto; crush.\n      * instantiate (1:=C (b' ++ << N k t' es; os >> :: b'' ++ << N k0 t0 es0; l ->> pfold f (t_app (t_app f t0) t'0) (remove Nat.eq_dec k0 ks) :: os1'' >> :: b3) os1 rs term1).\n        one_step; eapply S_Load; eauto.\n      * crush.\n    + destruct Hsecond as [b' [b'' [b''']]].\n      tu2.\n      got.\n      * instantiate (1:=C (b0 ++ << N k0 t0 es0; l ->> pfold f (t_app (t_app f t0) t'0) (remove Nat.eq_dec k0 ks) :: os1'' >> :: b'' ++ << N k t' es; os >> :: b''') os1 rs term1).\n        one_step; eapply S_PFold; eauto; crush.\n      * instantiate (1:=C ((b0 ++ << N k0 t0 es0; l ->> pfold f (t_app (t_app f t0) t'0) (remove Nat.eq_dec k0 ks) :: os1'' >> :: b'') ++ << N k t' es; os >> :: b''') os1 rs term1).\n        one_step; eapply S_Load; eauto; crush.\n      * crush.\n  (* S_Last *)\n  - destruct b2.\n    + apply List.app_inj_tail in H2. destruct H2. inv H2.\n      gotw (C (b0 ++ [<< N k t' es; os1' >>]) os1 (l ->>> final H :: rs) term1); eauto.\n    + remember (s :: b2) as bend.\n      assert (exists y ys, bend = ys ++ [y]) by (apply list_snoc with (xs:=bend) (x:=s) (xs':=b2); crush).\n      destruct H1; destruct H1.\n      inv H1.\n      rewrite H3 in *. clear H3.\n      assert (b1 ++ << N k t es; os >> :: x0 ++ [x] = (b1 ++ << N k t es; os >> :: x0) ++ [x]) by crush.\n      rewrite H1 in H2; clear H1.\n      apply List.app_inj_tail in H2.\n      destruct H2.\n      subst.\n      got.\n      * instantiate (1:=C ((b1 ++ << N k t' es; os >> :: x0) ++ [<< n1; os1' >>]) os1 (l ->>> final H :: rs) term1).\n        one_step; eapply S_Last; eauto; crush.\n      * instantiate (1:=C (b1 ++ << N k t' es; os >> :: x0 ++ [<< n1; os1' >>]) os1 (l ->>> final H :: rs) term1).\n        one_step; eapply S_Load; eauto; crush.\n      * crush.\n  (* S_FusePMap *)\n  - destruct n. tsod'. inv H0. apply List.app_inv_head in H2. inv H2.\n    + gotw (C (b0 ++ << N k0 t' e; os2 ++ l' ->> pmap (pmap_compose f' f) ks :: os3 >> :: b3) os1 (l ->>> final H :: rs) term1); eauto.\n    + destruct Hfirst as [b' [b'' [b''']]].\n      tu1.\n      got.\n      * instantiate (1:=C ((b' ++ << N k t' es; os >> :: b'') ++ << N k0 p e; os2 ++ l' ->> pmap (pmap_compose f' f) ks :: os3 >> :: b3) os1 (l ->>> 0 :: rs) term1).\n        one_step; eapply S_FusePMap; eauto; crush.\n      * instantiate (1:=C (b' ++ << N k t' es; os >> :: b'' ++ << N k0 p e; os2 ++ l' ->> pmap (pmap_compose f' f) ks :: os3 >> :: b3) os1 (l ->>> 0 :: rs) term1).\n        one_step; eapply S_Load; eauto; crush.\n      * crush.\n    + destruct Hsecond as [b' [b'' [b''']]].\n      tu2.\n      got.\n      * instantiate (1:=C (b0 ++ << N k0 p e; os2 ++ l' ->> pmap (pmap_compose f' f) ks :: os3 >> :: b'' ++ << N k t' es; os >> :: b''') os1 (l ->>> 0 :: rs) term1).\n        one_step; eapply S_FusePMap; eauto; crush.\n      * instantiate (1:=C ((b0 ++ << N k0 p e; os2 ++ l' ->> pmap (pmap_compose f' f) ks :: os3 >> :: b'') ++ << N k t' es; os >> :: b''') os1 (l ->>> 0 :: rs) term1).\n        one_step; eapply S_Load; eauto; crush.\n      * crush.\n  (* S_SwapReads *)\n  - destruct n. tsod'.\n    + inv H. apply List.app_inv_head in H3. inv H3.\n      gotw (C (b0 ++ << N k0 t' e; os2 ++ l' ->> pfold f' t'0 ks' :: l ->> pfold f t0 ks :: os3 >> :: b3) os1 rs term1); eauto.\n    + destruct Hfirst as [b' [b'' [b''']]].\n      tu1.\n      got.\n      * instantiate (1:=C ((b' ++ << N k t' es; os >> :: b'') ++ << N k0 p e; os2 ++ l' ->> pfold f' t'0 ks' :: l ->> pfold f t0 ks :: os3 >> :: b3) os1 rs term1).\n        one_step; eapply S_SwapReads; eauto; crush.\n      * instantiate (1:=C (b' ++ << N k t' es; os >> :: b'' ++ << N k0 p e; os2 ++ l' ->> pfold f' t'0 ks' :: l ->> pfold f t0 ks :: os3 >> :: b3) os1 rs term1).\n        one_step; eapply S_Load; eauto; crush.\n      * crush.\n    + destruct Hsecond as [b' [b'' [b''']]].\n      tu2.\n      got.\n      * instantiate (1:=C (b0 ++ << N k0 p e; os2 ++ l' ->> pfold f' t'0 ks' :: l ->> pfold f t0 ks :: os3 >> :: b'' ++ << N k t' es; os >> :: b''') os1 rs term1).\n        one_step; eapply S_SwapReads; eauto; crush.\n      * instantiate (1:=C ((b0 ++ << N k0 p e; os2 ++ l' ->> pfold f' t'0 ks' :: l ->> pfold f t0 ks :: os3 >> :: b'') ++ << N k t' es; os >> :: b''') os1 rs term1).\n        one_step; eapply S_Load; eauto; crush.\n      * crush.\n  (* S_Prop *)\n  - destruct n1. tsod.\n    + inv H. apply List.app_inv_head in H2; inv H2.\n      gotw (C (b0 ++ << N k0 t' e; os2 >> :: << n2; os3 ++ [l ->> op] >> :: b3) os1 rs term1); eauto.\n    + destruct Hfirst as [b' [b'' [b''']]].\n      tu1.\n      got.\n      * instantiate (1:=C ((b' ++ << N k t' es; os >> :: b'') ++ << N k0 p e; os2 >> :: << n2; os3 ++ [l ->> op] >> :: b3) os1 rs term1); eauto.\n        one_step; eapply S_Prop; eauto; crush.\n      * instantiate (1:=C (b' ++ << N k t' es; os >> :: b'' ++ << N k0 p e; os2 >> :: << n2; os3 ++ [l ->> op] >> :: b3) os1 rs term1); eauto.\n      * crush.\n    + destruct Hsecond as [b' [b'' [b''']]].\n      tu2.\n      {\n      destruct b''; simpl in *.\n      - inv H1.\n        got.\n        + instantiate (1:=C (b0 ++ << N k0 p e; os2 >> :: << N k t' es; os3 ++ [l ->> op] >> :: b3) os1 rs term1); eauto.\n          one_step; eapply S_Prop; eauto; crush.\n        + instantiate (1:=C ((b0 ++ [<< N k0 p e; os2 >>]) ++ << N k t' es; os3 ++ [l ->> op] >> :: b3) os1 rs term1); eauto.\n          one_step; eapply S_Load; eauto; crush.\n        + crush.\n      - inv H1.\n        got.\n        + instantiate (1:=C (b0 ++ << N k0 p e; os2 >> :: << n2; os3 ++ [l ->> op] >> :: b'' ++ << N k t' es; os >> :: b''') os1 rs term1); eauto.\n          one_step; eapply S_Prop; eauto; crush.\n        + instantiate (1:=C ((b0 ++ << N k0 p e; os2 >> :: << n2; os3 ++ [l ->> op] >> :: b'') ++ << N k t' es; os >> :: b''') os1 rs term1); eauto.\n          one_step; eapply S_Load; eauto; crush.\n        + crush.\n      }\n  (* S_Load *)\n  - tsod.\n    + inv H. apply List.app_inv_head in H2; inv H2.\n      eapply frontend_deterministic' with (b0:=b0 ++ <<N k0 t0 es0; os2>> :: b3) (os0:=os1) (os:=[]) (t':=t'0) in tt'; eauto. destruct tt'.\n      crush.\n      split.\n      * crush. inv WT. crush.\n      * crush. inv WT. crush.\n      * exists Result, false.\n        {\n        inv WT; dtr. inv H2.\n        econstructor.\n        - eapply wt_backend_build; eauto.\n        - wtbt. eauto.\n        - wtbdist. inv H3. wtbt. wtost. wtbt. wttost.\n          eauto.\n        }\n    + destruct Hfirst as [b' [b'' [b''']]].\n      tu1.\n      got.\n      * instantiate (1:=C ((b' ++ << N k t' es; os >> :: b'') ++ << N k0 t'0 es0; os2 >> :: b3) os1 rs1 term1); eauto.\n        one_step; eapply S_Load; eauto; crush.\n      * instantiate (1:=C (b' ++ << N k t' es; os >> :: b'' ++ << N k0 t'0 es0; os2 >> :: b3) os1 rs1 term1); eauto.\n      * crush.\n    + destruct Hsecond as [b' [b'' [b''']]].\n      tu2.\n      got.\n      * instantiate (1:=C (b0 ++ << N k0 t'0 es0; os2 >> :: b'' ++ << N k t' es; os >> :: b''') os1 rs1 term1); eauto.\n      * instantiate (1:=C ((b0 ++ << N k0 t'0 es0; os2 >> :: b'') ++ << N k t' es; os >> :: b''') os1 rs1 term1); eauto.\n        one_step; eapply S_Load; eauto; crush.\n      * crush.\n  (* S_LoadPFold *)\n  - tsod. inv H. apply List.app_inv_head in H2; inv H2.\n    + gotw (C (b0 ++ << N k0 t' es0; os2 ++ l ->> pfold f t1' ks :: os' >> :: b3) os1 rs1 term1); eauto.\n    + destruct Hfirst as [b' [b'' [b''']]].\n      tu1.\n      got.\n      * instantiate (1:=C ((b' ++ << N k t' es; os >> :: b'') ++ << N k0 t0 es0; os2 ++ l ->> pfold f t1' ks :: os' >> :: b3) os1 rs1 term1); eauto.\n        one_step; eapply S_LoadPFold; eauto; crush.\n      * instantiate (1:=C (b' ++ << N k t' es; os >> :: b'' ++ << N k0 t0 es0; os2 ++ l ->> pfold f t1' ks :: os' >> :: b3) os1 rs1 term1); eauto.\n      * crush.\n    + destruct Hsecond as [b' [b'' [b''']]].\n      tu2.\n      got.\n      * instantiate (1:=C (b0 ++ << N k0 t0 es0; os2 ++ l ->> pfold f t1' ks :: os' >> :: b'' ++ << N k t' es; os >> :: b''') os1 rs1 term1); eauto.\n      * instantiate (1:=C ((b0 ++ << N k0 t0 es0; os2 ++ l ->> pfold f t1' ks :: os' >> :: b'') ++ << N k t' es; os >> :: b''') os1 rs1 term1); eauto.\n        one_step; eapply S_Load; eauto; crush.\n      * crush.\nUnshelve.\nauto.\nauto.\nQed.\nHint Resolve lc_load.\n\nInductive fstar : nat -> term -> rstream -> term -> Prop :=\n| FZero : forall t rs, fstar 0 t rs t\n| FStep : forall t rs t', FRf t rs ==> FRt t' [] -> forall n t'', fstar n t' rs t'' -> fstar (S n) t rs t''.\nHint Constructors fstar.\n\nLemma fstar_zero :\n  forall t t' rs,\n  fstar 0 t rs t' ->\n  t = t'.\nProof using.\n  intros.\n  inversion H; subst; clear H; crush.\nQed.\n\nLemma fstar_trans :\n  forall m n t t' t'' rs,\n  fstar m t rs t' ->\n  fstar n t' rs t'' ->\n  fstar (m+n) t rs t''.\nProof using.\n  induction m; induction n; intros.\n  - crush.\n    apply fstar_zero in H; subst; crush.\n  - simpl.\n    apply fstar_zero in H; subst; crush.\n  - apply fstar_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 FStep.\n    instantiate (1:=t'0).\n    assumption.\n    eapply IHm.\n    instantiate (1:=t').\n    assumption.\n    eapply FStep.\n    instantiate (1:=t'1).\n    assumption.\n    assumption.\nQed.\n\nDefinition non_emitting (t : term) := exists T ll, has_type empty ll t T false.\nHint Unfold non_emitting.\n\nLemma fstar_app1 : forall m t t' t'' rs,\n  fstar m t rs t' ->\n  fstar m (t_app t t'') rs (t_app t' t'').\nProof using.\n  induction m; intros.\n  - apply fstar_zero in H; subst; auto.\n  - inv H. econstructor. instantiate (1:=t_app t'0 t''). auto. auto.\nQed.\n\nLemma pfold_get : forall rs t t' t'',\n    non_emitting t ->\n    non_emitting t' ->\n    FRf t' rs ==> FRt t'' [] ->\n    (exists n v, fstar n t rs v /\\ value v) ->\n    exists n m t''', fstar n (t_app t t') rs t''' /\\ fstar m (t_app t t'') rs t'''.\nProof using.\n  intros; dtr.\n  exists (S x), x, (t_app x0 t'').\n  split.\n  - replace (S x) with (x + 1).\n    eapply fstar_trans.\n    instantiate (1:=t_app x0 t').\n    apply fstar_app1; auto.\n    econstructor. instantiate (1:=t_app x0 t''). auto. auto. crush.\n  - apply fstar_app1. auto.\nQed.\n\nLemma fstar_into_star_load : forall n t t' rs b1 k es os b2 os0 t0,\n    fstar n t rs t' ->\n    C (b1 ++ <<N k t es; os>> :: b2) os0 rs t0 -->*[n] C (b1 ++ <<N k t' es; os>> :: b2) os0 rs t0.\nProof using.\n  induction n; intros.\n  - apply fstar_zero in H; subst. auto.\n  - inv H. econstructor.\n    + instantiate (1:=C (b1 ++ << N k t'0 es; os >> :: b2) os0 rs t0). eauto.\n    + apply IHn; eauto.\nQed.\n\nLemma fstar_into_star_loadpfold : forall n t t' n' rs b1 os1 l t1 t3 os2 b2 os0 t0,\n    fstar n t rs t' ->\n    C (b1 ++ <<n'; os1 ++ l ->> pfold t1 t t3 :: os2>> :: b2) os0 rs t0 -->*[n] C (b1 ++ <<n'; os1 ++ l ->> pfold t1 t' t3 :: os2>> :: b2) os0 rs t0.\nProof using.\n  induction n; intros.\n  - apply fstar_zero in H; subst. auto.\n  - inv H. econstructor.\n    + instantiate (1:=C (b1 ++ << n'; os1 ++ l ->> pfold t1 t'0 t3 :: os2 >> :: b2) os0 rs t0). destruct n'. eauto.\n    + apply IHn; eauto.\nQed.\n\n(* we are only interested in reductions that terminate *)\nHypothesis to_value : forall t rs, exists n t', fstar n t rs t' /\\ value t'.\n\nLtac fsame := ssame'; match goal with | [H : ?b ++ _ = ?b ++ _ |- _] => apply List.app_inv_head in H; inv H end.\n\nLemma not_appears_none : forall t l Gamma ll T E,\n  has_type Gamma ll t T E ->\n  ll l = None ->\n  not (lappears_free_in l t).\nProof using.\n  intros.\n  intro.\n  generalize dependent T.\n  generalize dependent E.\n  generalize dependent Gamma.\n  induction H1; intros; subst; try solve [inv H; eauto].\n  - inv H. crush.\nQed.\n\nLemma lcontext_not_in_or_os' : forall os l ll,\n  not (exists op, In (l ->> op) os) ->\n  ll l = None ->\n  (ostream_types os ll) l = None.\nProof using.\n  induction os; intros.\n  - auto.\n  - destruct a. simpl. rename l0 into n. destruct (Nat.eq_dec n l); subst.\n    + exfalso. apply H. exists o. crush.\n    + replace ((n #-> op_type o; ostream_types os ll) l) with ((ostream_types os ll) l).\n      apply IHos.\n      intro. dtr. apply H. exists x. crush. auto.\n      rewrite NMaps.update_neq; auto.\nQed.\n\nLemma lcontext_not_in_or_b' : forall b l ll,\n  not (exists os1 os2 b1 b2 s op, b = b1 ++ s :: b2 /\\ get_ostream s = os1 ++ l ->> op :: os2) ->\n  ll l = None ->\n  (backend_types b ll) l = None.\nProof using.\n  induction b; intros.\n  - auto.\n  - destruct a. destruct n. simpl in *.\n    apply lcontext_not_in_or_os'.\n    + intro; dtr. apply H. apply List.in_split in H1; dtr. exists x0, x1, [], b, <<N k p e; l0>>, x. crush.\n    + apply IHb.\n      intro. dtr. apply H. exists x, x0, (<<N k p e; l0>> :: x1), x2, x3, x4. destruct x3. simpl in *. subst. crush. auto.\nQed.\n\nLemma lcontext_not_in_or_rs' : forall rs l,\n  not (exists v, In (l ->>> v) rs) ->\n  (rstream_types rs) l = None.\nProof using.\n  induction rs; intros.\n  - auto.\n  - destruct a. simpl in *. rename l0 into n.\n    destruct (Nat.eq_dec n l); subst.\n    + exfalso. apply H. exists r. left. auto.\n    + replace ((n #-> Result; rstream_types rs) l) with ((rstream_types rs) l).\n      apply IHrs.\n      intro. dtr. apply H. exists x. crush.\n      rewrite NMaps.update_neq; auto.\nQed.\n\nLemma in_ostream_labels : forall os l op,\n  In (l ->> op) os ->\n  In l (ostream_labels os).\nProof using.\n  induction os; intros.\n  - auto.\n  - destruct a. simpl. rename l0 into n. destruct (Nat.eq_dec n l).\n    + auto.\n    + inv H; eauto.\n      inv H0. eauto.\nQed.\n\nLemma lcontext_not_in_or_os : forall os l ll,\n  (ostream_types os ll) l = None ->\n  not (exists op, In (l ->> op) os) /\\ ll l = None.\nProof using.\n  induction os; intros. split; try intro.\n  - dtr. inv H0.\n  - inv H. auto.\n  - destruct a. simpl in *.\n    rename l0 into n. destruct (Nat.eq_dec n l).\n    + subst. rewrite NMaps.update_eq in H. inv H.\n    + replace ((n #-> op_type o; ostream_types os ll) l) with ((ostream_types os ll) l) in H.\n      apply IHos in H; dtr.\n      split; eauto.\n      intro. dtr. apply H. destruct H1; eauto. inv H1. exfalso. apply n0. reflexivity.\n      rewrite NMaps.update_neq; auto.\nQed.\n\nLemma no_dep_backwards : forall b1 b2 os1 os2 os0 rs0 t0 n l l' f t ks f' t' ks',\n  well_typed (C (b1 ++ <<n; os1 ++ l ->> pfold f t ks :: l' ->> pfold f' t' ks' :: os2>> :: b2) os0 rs0 t0) ->\n  not (lappears_free_in l' t).\nProof using.\n  intros.\n  inv H; dtr.\n  simpl in *.\n  inv H.\n  wtbdist.\n  inv H2.\n  wtosdist.\n  inv H3.\n  inv H12.\n  simpl in *.\n  inv H15.\n  wtbt.\n  wtost.\n  wtost.\n  wttost.\n  wtbt.\n  assert ((ostream_types os1 (backend_types b2 (rstream_types rs0))) l' = None).\n  {\n    apply lcontext_not_in_or_os'.\n    - clear H10 H11 H6 H16 H12 H17 H14 H0.\n      rewrite backend_labels_dist in H1.\n      repeat (rewrite <- List.app_assoc in *).\n      unfold backend_labels at 2 in H1; simpl in *.\n      rewrite ostream_labels_dist in H1; simpl in *.\n      repeat (rewrite <- List.app_assoc in *).\n      replace (backend_labels b1 ++ ostream_labels os1 ++ (l :: l' :: ostream_labels os2) ++ List.concat (map (fun s : station => ostream_labels (get_ostream s)) b2) ++ ostream_labels os0 ++ rstream_labels rs0 ++ [])\n              with ((backend_labels b1 ++ ostream_labels os1 ++ [l]) ++ l' :: ostream_labels os2 ++ List.concat (map (fun s : station => ostream_labels (get_ostream s)) b2) ++ ostream_labels os0 ++ rstream_labels rs0 ++ []) in H1 by crush.\n      apply distinct_rotate_rev in H1.\n      apply distinct_remove in H1; dtr.\n      intro; dtr. apply H0.\n      repeat (rewrite <- List.app_assoc in *).\n      apply List.in_or_app. right.\n      apply List.in_or_app. left.\n      eapply in_ostream_labels; eauto.\n    - apply lcontext_not_in_or_b'.\n      + clear H10 H11 H6 H16 H12 H17 H14 H0.\n        rewrite backend_labels_dist in H1.\n        repeat (rewrite <- List.app_assoc in *).\n        unfold backend_labels at 2 in H1; simpl in *.\n        rewrite ostream_labels_dist in H1; simpl in *.\n        repeat (rewrite <- List.app_assoc in *).\n        replace (backend_labels b1 ++ ostream_labels os1 ++ (l :: l' :: ostream_labels os2) ++ List.concat (map (fun s : station => ostream_labels (get_ostream s)) b2) ++ ostream_labels os0 ++ rstream_labels rs0 ++ [])\n                with ((backend_labels b1 ++ ostream_labels os1 ++ [l]) ++ l' :: ostream_labels os2 ++ List.concat (map (fun s : station => ostream_labels (get_ostream s)) b2) ++ ostream_labels os0 ++ rstream_labels rs0 ++ []) in H1 by crush.\n        apply distinct_rotate_rev in H1.\n        apply distinct_remove in H1; dtr.\n        intro; dtr. apply H0.\n        repeat (rewrite <- List.app_assoc in *).\n        apply List.in_or_app. right.\n        apply List.in_or_app. right.\n        apply List.in_or_app. right.\n        apply List.in_or_app. right.\n        apply List.in_or_app. left.\n        subst; simpl. destruct x5. simpl in *. subst. simpl.\n        rewrite List.map_app. simpl.\n        rewrite concat_app.\n        apply List.in_or_app. right.\n        simpl.\n        apply List.in_or_app. left.\n        rewrite ostream_labels_dist.\n        apply List.in_or_app. right.\n        simpl. crush.\n      + apply lcontext_not_in_or_rs'.\n        clear H10 H11 H6 H16 H12 H17 H14 H0.\n        rewrite backend_labels_dist in H1.\n        repeat (rewrite <- List.app_assoc in *).\n        unfold backend_labels at 2 in H1; simpl in *.\n        rewrite ostream_labels_dist in H1; simpl in *.\n        repeat (rewrite <- List.app_assoc in *).\n        replace (backend_labels b1 ++ ostream_labels os1 ++ (l :: l' :: ostream_labels os2) ++ List.concat (map (fun s : station => ostream_labels (get_ostream s)) b2) ++ ostream_labels os0 ++ rstream_labels rs0 ++ [])\n                with ((backend_labels b1 ++ ostream_labels os1 ++ [l]) ++ l' :: ostream_labels os2 ++ List.concat (map (fun s : station => ostream_labels (get_ostream s)) b2) ++ ostream_labels os0 ++ rstream_labels rs0 ++ []) in H1 by crush.\n        apply distinct_rotate_rev in H1.\n        apply distinct_remove in H1; dtr.\n        intro; dtr. apply H0.\n        repeat (rewrite <- List.app_assoc in *).\n        apply List.in_or_app. right.\n        apply List.in_or_app. right.\n        apply List.in_or_app. right.\n        apply List.in_or_app. right.\n        apply List.in_or_app. right.\n        apply List.in_or_app. right.\n        apply List.in_or_app. left.\n        eapply in_rstream_labels; eauto.\n  }\n  eapply not_appears_none; eauto.\nQed.\n\nLemma no_dep_backwards' : forall b1 b2 os1 os2 os0 rs0 t0 n l l' f t ks f' t' ks',\n  well_typed (C (b1 ++ <<n; os1 ++ l ->> pfold f t ks :: l' ->> pfold f' t' ks' :: os2>> :: b2) os0 rs0 t0) ->\n  not (lappears_free_in l' f).\nProof using.\n  intros.\n  inv H; dtr.\n  simpl in *.\n  inv H.\n  wtbdist.\n  inv H2.\n  wtosdist.\n  inv H3.\n  inv H12.\n  simpl in *.\n  inv H15.\n  wtbt.\n  wtost.\n  wtost.\n  wttost.\n  wtbt.\n  assert ((ostream_types os1 (backend_types b2 (rstream_types rs0))) l' = None).\n  {\n    apply lcontext_not_in_or_os'.\n    - clear H10 H11 H6 H16 H12 H17 H14 H0.\n      rewrite backend_labels_dist in H1.\n      repeat (rewrite <- List.app_assoc in *).\n      unfold backend_labels at 2 in H1; simpl in *.\n      rewrite ostream_labels_dist in H1; simpl in *.\n      repeat (rewrite <- List.app_assoc in *).\n      replace (backend_labels b1 ++ ostream_labels os1 ++ (l :: l' :: ostream_labels os2) ++ List.concat (map (fun s : station => ostream_labels (get_ostream s)) b2) ++ ostream_labels os0 ++ rstream_labels rs0 ++ [])\n              with ((backend_labels b1 ++ ostream_labels os1 ++ [l]) ++ l' :: ostream_labels os2 ++ List.concat (map (fun s : station => ostream_labels (get_ostream s)) b2) ++ ostream_labels os0 ++ rstream_labels rs0 ++ []) in H1 by crush.\n      apply distinct_rotate_rev in H1.\n      apply distinct_remove in H1; dtr.\n      intro; dtr. apply H0.\n      repeat (rewrite <- List.app_assoc in *).\n      apply List.in_or_app. right.\n      apply List.in_or_app. left.\n      eapply in_ostream_labels; eauto.\n    - apply lcontext_not_in_or_b'.\n      + clear H10 H11 H6 H16 H12 H17 H14 H0.\n        rewrite backend_labels_dist in H1.\n        repeat (rewrite <- List.app_assoc in *).\n        unfold backend_labels at 2 in H1; simpl in *.\n        rewrite ostream_labels_dist in H1; simpl in *.\n        repeat (rewrite <- List.app_assoc in *).\n        replace (backend_labels b1 ++ ostream_labels os1 ++ (l :: l' :: ostream_labels os2) ++ List.concat (map (fun s : station => ostream_labels (get_ostream s)) b2) ++ ostream_labels os0 ++ rstream_labels rs0 ++ [])\n                with ((backend_labels b1 ++ ostream_labels os1 ++ [l]) ++ l' :: ostream_labels os2 ++ List.concat (map (fun s : station => ostream_labels (get_ostream s)) b2) ++ ostream_labels os0 ++ rstream_labels rs0 ++ []) in H1 by crush.\n        apply distinct_rotate_rev in H1.\n        apply distinct_remove in H1; dtr.\n        intro; dtr. apply H0.\n        repeat (rewrite <- List.app_assoc in *).\n        apply List.in_or_app. right.\n        apply List.in_or_app. right.\n        apply List.in_or_app. right.\n        apply List.in_or_app. right.\n        apply List.in_or_app. left.\n        subst; simpl. destruct x5. simpl in *. subst. simpl.\n        rewrite List.map_app. simpl.\n        rewrite concat_app.\n        apply List.in_or_app. right.\n        simpl.\n        apply List.in_or_app. left.\n        rewrite ostream_labels_dist.\n        apply List.in_or_app. right.\n        simpl. crush.\n      + apply lcontext_not_in_or_rs'.\n        clear H10 H11 H6 H16 H12 H17 H14 H0.\n        rewrite backend_labels_dist in H1.\n        repeat (rewrite <- List.app_assoc in *).\n        unfold backend_labels at 2 in H1; simpl in *.\n        rewrite ostream_labels_dist in H1; simpl in *.\n        repeat (rewrite <- List.app_assoc in *).\n        replace (backend_labels b1 ++ ostream_labels os1 ++ (l :: l' :: ostream_labels os2) ++ List.concat (map (fun s : station => ostream_labels (get_ostream s)) b2) ++ ostream_labels os0 ++ rstream_labels rs0 ++ [])\n                with ((backend_labels b1 ++ ostream_labels os1 ++ [l]) ++ l' :: ostream_labels os2 ++ List.concat (map (fun s : station => ostream_labels (get_ostream s)) b2) ++ ostream_labels os0 ++ rstream_labels rs0 ++ []) in H1 by crush.\n        apply distinct_rotate_rev in H1.\n        apply distinct_remove in H1; dtr.\n        intro; dtr. apply H0.\n        repeat (rewrite <- List.app_assoc in *).\n        apply List.in_or_app. right.\n        apply List.in_or_app. right.\n        apply List.in_or_app. right.\n        apply List.in_or_app. right.\n        apply List.in_or_app. right.\n        apply List.in_or_app. right.\n        apply List.in_or_app. left.\n        eapply in_rstream_labels; eauto.\n  }\n  eapply not_appears_none; eauto.\nQed.\n\nLemma lc_pfold :\n  forall cx cy cz os rs term k t es t' f l ks os1 b1 b2,\n  well_typed cx ->\n  cx = C (b1 ++ <<N k t es; l ->> pfold f t' ks :: os1>> :: b2) os rs term ->\n  cy = C (b1 ++ <<N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1>> :: b2) os rs term ->\n  cx --> cy ->\n  cx --> cz ->\n  In k ks ->\n  cy -v cz.\nProof using.\n  intros cx cy cz os rs term k t es t' f l ks os1 b1 b2.\n  intros WT Heqcx Heqcy cxcy cxcz.\n  intros HIn.\n  inversion cxcz; ssame; try solve [subst; eauto].\n  (* S_Empty *)\n  - destruct b1; crush.\n  (* S_First *)\n  - destruct b1; simpl in *.\n    + inv H1.\n      gotw (C (<< N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 ++ [l0 ->> op] >> :: b') os' rs0 term0); eauto.\n      * rewrite -> List.app_comm_cons.\n        eapply S_First; eauto.\n      * eapply S_PFold with (b1:=[]); eauto; crush.\n    + inv H1.\n      gotw (C (<< n1; os2 ++ [l0 ->> op]>> :: b1 ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b2) os' rs0 term0); eauto.\n      * rewrite List.app_comm_cons.\n        eapply S_PFold with (b1:=(<< n1; os2 ++ [l0 ->> op] >> :: b1)); crush.\n  (* S_Add *)\n  - got.\n    * instantiate (1:=C (<<N k0 v t_ks_nil; []>> :: b1 ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b2) os' (l0 ->>> final H :: rs0) term0); eauto.\n    * instantiate (1:=C ((<<N k0 v t_ks_nil; []>> :: b1) ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b2) os' (l0 ->>> final H :: rs0) term0); eauto.\n      one_step; eapply S_PFold; eauto; crush.\n    * crush.\n  (* S_PMap *)\n  - tsod.\n    + crush.\n    + destruct Hfirst as [b' [b'' [b''']]].\n      tu1.\n      got.\n      * instantiate (1:=C ((b' ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b'') ++ << N k0 (t_app f0 v) es0; l0 ->> pmap f0 (remove Nat.eq_dec k0 ks0) :: os1'' >> :: b3) os0 rs0 term0).\n        one_step; eapply S_PMap; eauto; crush.\n      * instantiate (1:=C (b' ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b'' ++ << N k0 (t_app f0 v) es0; l0 ->> pmap f0 (remove Nat.eq_dec k0 ks0) :: os1'' >> :: b3) os0 rs0 term0); eauto.\n      * crush.\n    + destruct Hsecond as [b' [b'' [b''']]].\n      tu2.\n      got.\n      * instantiate (1:=C (b0 ++ << N k0 (t_app f0 v) es0; l0 ->> pmap f0 (remove Nat.eq_dec k0 ks0) :: os1'' >> :: b'' ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b''') os0 rs0 term0); eauto.\n      * instantiate (1:=C ((b0 ++ << N k0 (t_app f0 v) es0; l0 ->> pmap f0 (remove Nat.eq_dec k0 ks0) :: os1'' >> :: b'') ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b''') os0 rs0 term0); eauto.\n        one_step; eapply S_PFold; eauto; crush.\n      * crush.\n  (* S_PFold *)\n  - tsod.\n    + inv Hsame5. inv H. apply List.app_inv_head in H1; inv H1. crush.\n    + destruct Hfirst as [b' [b'' [b''']]].\n      tu1.\n      got.\n      * instantiate (1:=C ((b' ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b'') ++ << N k0 t0 es0; l0 ->> pfold f0 (t_app (t_app f0 t0) t'0) (remove Nat.eq_dec k0 ks0) :: os1'' >> :: b3) os0 rs0 term0).\n        one_step; eapply S_PFold; eauto; crush.\n      * instantiate (1:=C (b' ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b'' ++ << N k0 t0 es0; l0 ->> pfold f0 (t_app (t_app f0 t0) t'0) (remove Nat.eq_dec k0 ks0) :: os1'' >> :: b3) os0 rs0 term0); eauto.\n      * crush.\n    + destruct Hsecond as [b' [b'' [b''']]].\n      tu2.\n      got.\n      * instantiate (1:=C (b0 ++ << N k0 t0 es0; l0 ->> pfold f0 (t_app (t_app f0 t0) t'0) (remove Nat.eq_dec k0 ks0) :: os1'' >> :: b'' ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b''') os0 rs0 term0); eauto.\n      * instantiate (1:=C ((b0 ++ << N k0 t0 es0; l0 ->> pfold f0 (t_app (t_app f0 t0) t'0) (remove Nat.eq_dec k0 ks0) :: os1'' >> :: b'') ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b''') os0 rs0 term0).\n        one_step; eapply S_PFold; eauto; crush.\n      * crush.\n  (* S_Last *)\n  - destruct b2.\n    + apply List.app_inj_tail in H2.\n      destruct H2.\n      inv H2.\n      crush.\n    + remember (s :: b2) as bend.\n      assert (exists y ys, bend = ys ++ [y]) by (apply list_snoc with (xs:=bend) (x:=s) (xs':=b2); crush).\n      destruct H1; destruct H1.\n      inv H1.\n      rewrite H3 in *. clear H3.\n      assert (b1 ++ << N k t es; l ->> pfold f t' ks :: os1 >> :: x0 ++ [x] = (b1 ++ << N k t es; l ->> pfold f t' ks :: os1 >> :: x0) ++ [x]) by crush.\n      rewrite H1 in H2; clear H1.\n      apply List.app_inj_tail in H2.\n      destruct H2.\n      subst.\n      got.\n      * instantiate (1:=C ((b1 ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: x0) ++ [<< n1; os1' >>]) os0 (l0 ->>> final H :: rs0) term0).\n        one_step. eapply S_Last; eauto; crush.\n      * instantiate (1:=C (b1 ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: x0 ++ [<< n1; os1' >>]) os0 (l0 ->>> final H :: rs0) term0).\n        one_step; eapply S_PFold; eauto; crush.\n      * crush.\n  (* S_FusePMap *)\n  - destruct n as [k' v'].\n    tsod.\n    + destruct os2.\n      * crush.\n      * inv Hsame5.\n      {\n      got.\n      - instantiate (1:=C (b0 ++ << N k' v' es; (l ->> pfold f (t_app (t_app f v') t') (remove Nat.eq_dec k' ks) :: os2) ++ l' ->> pmap (pmap_compose f' f0) ks0 :: os3 >> :: b3) os0 (l0 ->>> final H :: rs0) term0).\n        one_step. eapply S_FusePMap; crush.\n      - instantiate (1:=C (b0 ++ << N k' v' es; (l ->> pfold f (t_app (t_app f v') t') (remove Nat.eq_dec k' ks) :: os2) ++ l' ->> pmap (pmap_compose f' f0) ks0 :: os3 >> :: b3) os0 (l0 ->>> final H :: rs0) term0).\n        one_step. inv H0. apply List.app_inv_head in H2; inv H2. eapply S_PFold; crush.\n      - crush.\n      }\n    + destruct Hfirst as [b' [b'' [b''']]].\n      tu1.\n      got.\n      * instantiate (1:=C ((b' ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b'') ++ << N k' v' e; os2 ++ l' ->> pmap (pmap_compose f' f0) ks0 :: os3 >> :: b3) os0 (l0 ->>> 0 :: rs0) term0).\n        one_step; eapply S_FusePMap; eauto; crush.\n      * instantiate (1:=C (b' ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b'' ++ << N k' v' e; os2 ++ l' ->> pmap (pmap_compose f' f0) ks0 :: os3 >> :: b3) os0 (l0 ->>> 0 :: rs0) term0).\n        eauto.\n      * crush.\n    + destruct Hsecond as [b' [b'' [b''']]].\n      tu2.\n      got.\n      * instantiate (1:=C (b0 ++ << N k' v' e; os2 ++ l' ->> pmap (pmap_compose f' f0) ks0 :: os3 >> :: b'' ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b''') os0 (l0 ->>> 0 :: rs0) term0).\n        eauto.\n      * instantiate (1:=C ((b0 ++ << N k' v' e; os2 ++ l' ->> pmap (pmap_compose f' f0) ks0 :: os3 >> :: b'') ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b''') os0 (l0 ->>> 0 :: rs0) term0).\n        one_step; eapply S_PFold; eauto; crush.\n      * crush.\n  (* S_SwapReads *)\n  - destruct n as [k' v'].\n    tsod.\n    + destruct os2.\n      *\n      {\n      inv Hsame5. inv H. apply List.app_inv_head in H3. inv H3.\n      got.\n      - instantiate (1:=C (b0 ++ << N k' v' e; l' ->> pfold f' t'0 ks' :: l0 ->> pfold f0 (t_app (t_app f0 v') t0) (remove Nat.eq_dec k' ks0) :: os3 >> :: b3) os0 rs0 term0).\n        one_step. eapply S_SwapReads with (os1:=[]); crush.\n      - instantiate (1:=C (b0 ++ << N k' v' e; l' ->> pfold f' t'0 ks' :: l0 ->> pfold f0 (t_app (t_app f0 v') t0) (remove Nat.eq_dec k' ks0) :: os3 >> :: b3) os0 rs0 term0).\n        simpl in *.\n        exists 3.\n        eapply Step.\n        instantiate (1:=C (b0 ++ << N k' v' e; l0 ->> pfold f0 t0 ks0 :: l' ->> pfold f' t'0 ks' :: os3 >> :: b3) os0 rs0 term0).\n        eapply S_SwapReads with (os1:=[]); eauto.\n        eapply no_dep_backwards' with (os1:=[]); eauto.\n        eapply no_dep_backwards with (os1:=[]); eauto.\n        eapply Step.\n        eapply S_PFold; eauto.\n        eapply Step.\n        instantiate (1:=C (b0 ++ << N k' v' e; l' ->> pfold f' t'0 ks' :: l0 ->> pfold f0 (t_app (t_app f0 v') t0) (remove Nat.eq_dec k' ks0) :: os3 >> :: b3) os0 rs0 term0).\n        eapply S_SwapReads with (os1:=[]); eauto.\n        eauto.\n      - crush.\n      }\n      * inv Hsame5.\n      {\n      got.\n      - instantiate (1:=C (b0 ++ << N k' v' es; (l ->> pfold f (t_app (t_app f v') t') (remove Nat.eq_dec k' ks) :: os2) ++ l' ->> pfold f' t'0 ks' :: l0 ->> pfold f0 t0 ks0 :: os3 >> :: b3) os0 rs0 term0).\n        one_step. eapply S_SwapReads; crush.\n      - instantiate (1:=C (b0 ++ << N k' v' es; l ->> pfold f (t_app (t_app f v') t') (remove Nat.eq_dec k' ks) :: os2 ++ l' ->> pfold f' t'0 ks' :: l0 ->> pfold f0 t0 ks0 :: os3 >> :: b3) os0 rs0 term0).\n        one_step. inv H. apply List.app_inv_head in H3; inv H3. eapply S_PFold; crush.\n      - crush.\n      }\n    + destruct Hfirst as [b' [b'' [b''']]].\n      tu1.\n      got.\n      * instantiate (1:=C ((b' ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b'') ++ << N k' v' e; os2 ++ l' ->> pfold f' t'0 ks' :: l0 ->> pfold f0 t0 ks0 :: os3 >> :: b3) os0 rs0 term0).\n        one_step; eapply S_SwapReads; eauto; crush.\n      * instantiate (1:=C (b' ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b'' ++ << N k' v' e; os2 ++ l' ->> pfold f' t'0 ks' :: l0 ->> pfold f0 t0 ks0 :: os3 >> :: b3) os0 rs0 term0).\n        eauto.\n      * crush.\n    + destruct Hsecond as [b' [b'' [b''']]].\n      tu2.\n      got.\n      * instantiate (1:=C (b0 ++ << N k' v' e; os2 ++ l' ->> pfold f' t'0 ks' :: l0 ->> pfold f0 t0 ks0 :: os3 >> :: b'' ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b''') os0 rs0 term0).\n        eauto.\n      * instantiate (1:=C ((b0 ++ << N k' v' e; os2 ++ l' ->> pfold f' t'0 ks' :: l0 ->> pfold f0 t0 ks0 :: os3 >> :: b'') ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b''') os0 rs0 term0).\n        one_step; eapply S_PFold; eauto; crush.\n      * crush.\n  (* S_Prop *)\n  - destruct n1 as [k' v'].\n    tsod.\n    + simpl in *. inv Hsame5. crush.\n    + destruct Hfirst as [b' [b'' [b''']]].\n      tu1.\n      got.\n      * instantiate (1:=C ((b' ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b'') ++ << N k' v' e; os2 >> :: << n2; os3 ++ [l0 ->> op] >> :: b3) os0 rs0 term0).\n        one_step; eapply S_Prop; eauto; crush.\n      * instantiate (1:=C (b' ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b'' ++ << N k' v' e; os2 >> :: << n2; os3 ++ [l0 ->> op] >> :: b3) os0 rs0 term0).\n        eauto.\n      * crush.\n    + destruct Hsecond as [b' [b'' [b''']]].\n      tu2.\n      destruct b''.\n      * inv H1; simpl in *.\n        got.\n        { instantiate (1:=C (b0 ++ << N k' v' e; os2 >> :: << N k t es; (l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1) ++ [l0 ->> op] >> :: b3) os0 rs0 term0).\n          one_step; eapply S_Prop; eauto. }\n        { instantiate (1:=C ((b0 ++ [<< N k' v' e; os2 >>]) ++ << N k t es; (l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1) ++ [l0 ->> op] >> :: b3) os0 rs0 term0).\n          one_step; eapply S_PFold; eauto; crush. }\n        { crush. }\n      * inv H1; simpl in *.\n        got.\n        { instantiate (1:=C (b0 ++ << N k' v' e; os2 >> :: << n2; os3 ++ [l0 ->> op] >> :: b'' ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b''') os0 rs0 term0).\n          one_step; eapply S_Prop; eauto; crush. }\n        { instantiate (1:=C ((b0 ++ << N k' v' e; os2 >> :: << n2; os3 ++ [l0 ->> op] >> :: b'') ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b''') os0 rs0 term0).\n          one_step; eapply S_PFold; eauto; crush. }\n        { crush. }\n  (* S_LoadPFold *)\n  - tsod.\n    + destruct os2.\n      * inv Hsame5; simpl in *. fsame.\n        copy H1. rename H into Hfstep. apply pfold_get with (t:=t_app f0 t0) in Hfstep; dtr.\n        apply fstar_into_star_loadpfold with (b1:=b0) (b2:=b3) (n':=N k0 t0 es0) (os1:=[]) (l:=l0) (t1:=f0) (t3:=remove Nat.eq_dec k0 ks0) (os2:=os') (os0:=os0) (rs:=rs0) (t0:=term0) in H.\n        apply fstar_into_star_loadpfold with (b1:=b0) (b2:=b3) (n':=N k0 t0 es0) (os1:=[]) (l:=l0) (t1:=f0) (t3:=remove Nat.eq_dec k0 ks0) (os2:=os') (os0:=os0) (rs:=rs0) (t0:=term0) in H0.\n        rename H into star1.\n        rename H0 into star2.\n        got.\n        { instantiate (1:=C (b0 ++ << N k0 t0 es0; l0 ->> pfold f0 x1 (remove Nat.eq_dec k0 ks0) :: os' >> :: b3) os0 rs0 term0).\n          eauto. }\n        { instantiate (1:=C (b0 ++ << N k0 t0 es0; l0 ->> pfold f0 x1 (remove Nat.eq_dec k0 ks0) :: os' >> :: b3) os0 rs0 term0).\n          eauto. }\n      { crush. }\n      { unfold non_emitting. inv WT; dtr. inv H2. wtbdist. inv H3. inv H15. inv H9. replace false with (false || false || false). eauto. auto. }\n      { unfold non_emitting. inv WT; dtr. inv H2. wtbdist. inv H3. inv H15. inv H9. replace false with (false || false || false). eauto. auto. }\n      { apply to_value. }\n      * inv Hsame5.\n        got.\n        { instantiate (1:=C (b0 ++ << N k0 t0 es0; (l ->> pfold f (t_app (t_app f t0) t') (remove Nat.eq_dec k0 ks) :: os2) ++ l0 ->> pfold f0 t1' ks0 :: os' >> :: b3) os0 rs0 term0).\n          inv H. apply List.app_inv_head in H2; inv H2. one_step; eapply S_LoadPFold; eauto; crush. }\n        { instantiate (1:=C (b0 ++ << N k0 t0 es0; l ->> pfold f (t_app (t_app f t0) t') (remove Nat.eq_dec k0 ks) :: os2 ++ l0 ->> pfold f0 t1' ks0 :: os' >> :: b3) os0 rs0 term0).\n          one_step; eapply S_PFold; eauto; crush. }\n        { crush. }\n    + destruct Hfirst as [b' [b'' [b''']]].\n      tu1.\n      got.\n      * instantiate (1:=C ((b' ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b'') ++ << N k0 t0 es0; os2 ++ l0 ->> pfold f0 t1' ks0 :: os' >> :: b3) os0 rs0 term0).\n        one_step; eapply S_LoadPFold; eauto; crush.\n      * instantiate (1:=C (b' ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b'' ++ << N k0 t0 es0; os2 ++ l0 ->> pfold f0 t1' ks0 :: os' >> :: b3) os0 rs0 term0).\n        eauto.\n      * crush.\n    + destruct Hsecond as [b' [b'' [b''']]].\n      tu2.\n      got.\n      * instantiate (1:=C (b0 ++ << N k0 t0 es0; os2 ++ l0 ->> pfold f0 t1' ks0 :: os' >> :: b'' ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b''') os0 rs0 term0).\n        eauto.\n      * instantiate (1:=C ((b0 ++ << N k0 t0 es0; os2 ++ l0 ->> pfold f0 t1' ks0 :: os' >> :: b'') ++ << N k t es; l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1 >> :: b''') os0 rs0 term0).\n        one_step; eapply S_PFold; eauto; crush.\n      * crush.\nUnshelve.\nauto.\nauto.\nauto.\nQed.\nHint Resolve lc_pfold.\n\nLtac tsod''' := match goal with\n              | [H : ?b1 ++ <<N ?k ?t ?es; ?os ++ ?os'''>> :: ?b2 = ?b3 ++ <<N ?k' ?t' ?es'; ?os' ++ ?os''>> :: ?b4 |- _] =>\n                  eapply (@target_same_or_different _ b1 b2 b3 b4 k t es es' k' t' (os ++ os''') (os' ++ os'')) in H; eauto; destruct H as [Hsame|Hwhich]; try destruct Hwhich as [Hfirst|Hsecond];\n                  try (destruct Hsame as [Hsame1 Hsame2]; destruct Hsame2 as [Hsame2 Hsame3]; destruct Hsame3 as [Hsame3 Hsame4]; destruct Hsame4 as [Hsame4 Hsame5]; subst)\n              end.\n\nLtac osod := match goal with\n              | [H : ?os1 ++ ?lop :: ?os2 = ?os3 ++ ?lop' :: ?os4 |- _] =>\n                  eapply (@op_same_or_different _ _ _ _ _ _ _ os1 os2 os3 os4) in H; eauto; destruct H as [Hsame|Hwhich]; try destruct Hwhich as [Hfirst|Hsecond];\n                  try (destruct Hsame as [Hsame1 Hsame2]; destruct Hsame2 as [Hsame2 Hsame3]; destruct Hsame3 as [Hsame3 Hsame4]; destruct Hsame4 as [Hsame4 Hsame5]; subst)\n              end.\n\nLtac ou1 := match goal with\n            | [H : ?os1 ++ ?lop :: ?os2 = ?os3 ++ ?lop :: ?os' ++ ?lop' :: ?os4 |- _] =>\n            eapply (@op_unique _ _ _ _ _ _ _ os1 os2 os3) in H; crush\n            end;\n            match goal with\n            | [H : C _ _ _ _ = C _ _ _ _ |- _] => inv H\n            end;\n            match goal with\n            | [H : _ ++ _ = _ ++ _ |- _] => apply List.app_inv_head in H; inv H\n            end;\n            match goal with\n            | [H : ?os1 ++ ?lop' :: ?os' ++ ?lop :: ?os2 = ?os3 ++ ?lop :: ?os4 |- _] =>\n              eapply (@op_unique _ _ _ _ _ _ _ (os1 ++ lop' :: os') os2 os3 os4) in H; eauto; crush\n            end.\n\nLtac ou2 := match goal with\n            | [H : ?os1 ++ ?lop :: ?os2 = ?os3 ++ ?lop' :: ?os' ++ ?lop :: ?os4 |- _] =>\n            eapply (@op_unique _ _ _ _ _ _ _ os1 os2 (os3 ++ lop' :: os') os4) in H; crush\n            end;\n            match goal with\n            | [H : C _ _ _ _ = C _ _ _ _ |- _] => inv H\n            end;\n            match goal with\n            | [H : _ ++ _ = _ ++ _ |- _] => apply List.app_inv_head in H; inv H\n            end;\n            match goal with\n            | [H : ?os1 ++ ?lop :: ?os' ++ ?lop' :: ?os2 = ?os3 ++ ?lop :: ?os4 |- _] =>\n              eapply (@op_unique _ _ _ _ _ _ _ os1 (os' ++ lop' :: os2) os3 os4) in H; eauto; crush\n            end.\n\nLemma lfree_subst_preservation : forall t2 l x T t1,\n  lappears_free_in l (#[ x := t1] t2) ->\n  lappears_free_in l (t_app (t_abs x T t2) t1).\nProof using.\n  induction t2; intros; simpl in *; try solve [inv H; eauto].\n  - destruct (eqb_string x s).\n    + auto.\n    + inv H.\n  - inv H.\n    + eapply IHt2_1 in H2.\n      inv H2; eauto. inv H1; eauto.\n    + eapply IHt2_2 in H2.\n      inv H2; eauto. inv H1; eauto.\n  - inv H.\n    + destruct (eqb_string x s); auto. eapply IHt2 in H2. inv H2; eauto. inv H1; eauto.\n  - inv H.\n    + eapply IHt2_1 in H2.\n      inv H2; eauto. inv H1; eauto.\n    + eapply IHt2_2 in H2.\n      inv H2; eauto. inv H1; eauto.\n  - inv H.\n    + eapply IHt2 in H2.\n      inv H2; eauto. inv H1; eauto.\n  - inv H.\n    + eapply IHt2_1 in H2.\n      inv H2; eauto. inv H1; eauto.\n    + eapply IHt2_2 in H2.\n      inv H2; eauto. inv H1; eauto.\n    + eapply IHt2_3 in H2.\n      inv H2; eauto. inv H1; eauto.\n  - inv H.\n    + eapply IHt2_1 in H2.\n      inv H2; eauto. inv H1; eauto.\n    + eapply IHt2_2 in H2.\n      inv H2; eauto. inv H1; eauto.\n  - inv H.\n    + eapply IHt2_1 in H2.\n      inv H2; eauto. inv H1; eauto.\n    + eapply IHt2_2 in H2.\n      inv H2; eauto. inv H1; eauto.\n  - inv H.\n    + eapply IHt2_1 in H2.\n      inv H2; eauto. inv H1; eauto.\n    + eapply IHt2_2 in H2.\n      inv H2; eauto. inv H1; eauto.\n    + eapply IHt2_3 in H2.\n      inv H2; eauto. inv H1; eauto.\n  - inv H.\n    + eapply IHt2 in H2.\n      inv H2; eauto. inv H1; eauto.\n  - inv H.\n    + eapply IHt2 in H2.\n      inv H2; eauto. inv H1; eauto.\n  - inv H.\n    + eapply IHt2 in H2.\n      inv H2; eauto. inv H1; eauto.\n  - inv H.\n    + eapply IHt2 in H2.\n      inv H2; eauto. inv H1; eauto.\nUnshelve.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nQed.\n\nLemma lfree_preservation : forall t rs t' os l,\n  FRf t rs ==> FRt t' os ->\n  not (lappears_free_in l t) ->\n  not (lappears_free_in l t').\nProof using.\n  induction t; intros; try solve [inv H].\n  - inv H.\n    + intro. apply H0. apply lfree_subst_preservation; auto.\n    + apply IHt1 with (l:=l) in H2; auto.\n      intro. inv H; auto.\n    + apply IHt2 with (l:=l) in H7; auto.\n      intro. inv H; auto.\n  - inv H.\n    + apply IHt1 with (l:=l) in H2; auto.\n      intro. inv H; auto.\n    + apply IHt2 with (l:=l) in H7; auto.\n      intro. inv H; auto.\n  - inv H.\n    + intro. inv H; auto.\n    + apply IHt with (l:=l) in H2; auto.\n      intro. inv H; auto.\n  - inv H.\n    + intro. inversion H. eapply fresh_labels; eauto.\n    + apply IHt1 with (l:=l0) in H2; auto.\n      intro. inv H; auto.\n    + apply IHt2 with (l:=l0) in H9; auto.\n      intro. inv H; auto.\n    + apply IHt3 with (l:=l0) in H10; auto.\n      intro. inv H; auto.\n  - inv H.\n    + intro. inversion H. eapply fresh_labels; eauto.\n    + apply IHt1 with (l:=l0) in H2; auto.\n      intro. inv H; auto.\n    + apply IHt2 with (l:=l0) in H8; auto.\n      intro. inv H; auto.\n  - inv H.\n    + intro. inversion H. eapply fresh_labels; eauto.\n    + apply IHt1 with (l:=l0) in H2; auto.\n      intro. inv H; auto.\n    + apply IHt2 with (l:=l0) in H8; auto.\n      intro. inv H; auto.\n  - inv H.\n    + apply IHt1 with (l:=l) in H2; auto.\n      intro. inv H; auto.\n    + apply IHt2 with (l:=l) in H8; auto.\n      intro. inv H; auto.\n    + apply IHt3 with (l:=l) in H9; auto.\n      intro. inv H; auto.\n  - inv H.\n    + apply IHt with (l:=l) in H2; auto.\n      intro. inv H; auto.\n    + intro. inv H; auto.\n  - inv H.\n    + apply IHt with (l:=l) in H2; auto.\n      intro. inv H; auto.\n    + intro. inv H; auto.\n  - inv H.\n    + apply IHt with (l:=l) in H2; auto.\n      intro. inv H; auto.\n    + intro. inv H; auto.\n  - inv H.\n    + intro. inv H; auto. inv H4; auto. inv H3; auto. inv H3.\n    + apply IHt with (l:=l) in H2; auto.\n      intro. inv H; auto.\nQed.\n\nLemma lc_loadpfold :\n  forall cx cy cz b1 b2 k t es f t1 t1' l ks os os' term0 os0 rs0,\n  well_typed cx ->\n  cx = C (b1 ++ <<N k t es; os ++ l ->> pfold f t1 ks :: os'>> :: b2) os0 rs0 term0 ->\n  cy = C (b1 ++ <<N k t es; os ++ l ->> pfold f t1' ks :: os'>> :: b2) os0 rs0 term0 ->\n  cx --> cy ->\n  cx --> cz ->\n  FRf t1 rs0 ==> FRt t1' [] ->\n  cy -v cz.\nProof using.\n  intros cx cy cz b1 b2 k t es f t1 t1' l ks os os' term0 os0 rs0.\n  intros WT Heqcx Heqcy cxcy cxcz.\n  intros tt'.\n  inversion cxcz; ssame; try solve [subst; eauto].\n  (* S_Empty *)\n  - destruct b1; crush.\n  (* S_First *)\n  - destruct b1; inv H1; simpl in *.\n    + gotw (C (<< N k t es; (os ++ l ->> pfold f t1' ks :: os') ++ [l0 ->> op] >> :: b') os'0 rs term1); eauto.\n      * rewrite <- List.app_assoc. rewrite <- List.app_comm_cons. eapply S_LoadPFold with (b1:=[]); eauto; crush.\n    + got.\n      * instantiate (1:=(C (<< n1; os2 ++ [l0 ->> op] >> :: b1 ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b2) os'0 rs term1)).\n        one_step; eapply S_First; eauto; crush.\n      * instantiate (1:=(C (<< n1; os2 ++ [l0 ->> op] >> :: b1 ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b2) os'0 rs term1)).\n        one_step; eapply S_LoadPFold; eauto; crush.\n      * crush.\n  (* S_Add *)\n  - got.\n    + instantiate (1:=C (<< N k0 v t_ks_nil; [] >> :: b1 ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b2) os'0 (l0 ->>> final H :: rs) term1).\n      one_step; eapply S_Add; eauto.\n    + instantiate (1:=C ((<< N k0 v t_ks_nil; [] >> :: b1) ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b2) os'0 (l0 ->>> final H :: rs) term1).\n      one_step; eapply S_LoadPFold; eauto; crush.\n    + crush.\n  (* S_PMap *)\n  - tsod.\n    + destruct os.\n      * inv Hsame5.\n      * inv Hsame5.\n        got.\n        { instantiate (1:=C (b0 ++ << N k0 (t_app f0 v) es; l0 ->> pmap f0 (remove Nat.eq_dec k0 ks0) :: os ++ l ->> pfold f t1' ks :: os' >> :: b3) os1 rs term1).\n          one_step; eapply S_PMap; eauto; crush. }\n        { instantiate (1:=C (b0 ++ << N k0 (t_app f0 v) es; (l0 ->> pmap f0 (remove Nat.eq_dec k0 ks0) :: os) ++ l ->> pfold f t1' ks :: os' >> :: b3) os1 rs term1).\n          fsame. one_step; eapply S_LoadPFold; eauto; crush. }\n        { crush. }\n    + destruct Hfirst as [b' [b'' [b''']]].\n      tu1.\n      got.\n      * instantiate (1:=C ((b' ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b'') ++ << N k0 (t_app f0 v) es0; l0 ->> pmap f0 (remove Nat.eq_dec k0 ks0) :: os1'' >> :: b3) os1 rs term1).\n        one_step; eapply S_PMap; eauto; crush.\n      * instantiate (1:=C ((b' ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b'') ++ << N k0 (t_app f0 v) es0; l0 ->> pmap f0 (remove Nat.eq_dec k0 ks0) :: os1'' >> :: b3) os1 rs term1).\n        one_step; eapply S_LoadPFold; eauto; crush.\n      * crush.\n    + destruct Hsecond as [b' [b'' [b''']]].\n      tu2.\n      got.\n      * instantiate (1:=C (b0 ++ << N k0 (t_app f0 v) es0; l0 ->> pmap f0 (remove Nat.eq_dec k0 ks0) :: os1'' >> :: b'' ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b''') os1 rs term1).\n        one_step; eapply S_PMap; eauto; crush.\n      * instantiate (1:=C ((b0 ++ << N k0 (t_app f0 v) es0; l0 ->> pmap f0 (remove Nat.eq_dec k0 ks0) :: os1'' >> :: b'') ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b''') os1 rs term1).\n        one_step; eapply S_LoadPFold; eauto; crush.\n      * crush.\n  (* S_Last *)\n  - destruct b2; simpl in *.\n    + destruct os; simpl in *.\n      * apply List.app_inj_tail in H2; destruct H2; inv H2.\n        exfalso.\n        apply frontend_no_value in tt'.\n        {\n        destruct H.\n        - crush.\n        - destruct e. destruct e. destruct e. inversion e. subst.\n          crush.\n        }\n      * apply List.app_inj_tail in H2; destruct H2; inv H2.\n        got.\n        { instantiate (1:=C (b0 ++ [<< N k t es; os ++ l ->> pfold f t1' ks :: os' >>]) os1 (l0 ->>> final H :: rs) term1).\n          one_step; eapply S_Last; eauto; crush. }\n        { instantiate (1:=C (b0 ++ [<< N k t es; os ++ l ->> pfold f t1' ks :: os' >>]) os1 (l0 ->>> final H :: rs) term1).\n          one_step; eapply S_LoadPFold; eauto; crush. }\n        { crush. }\n    + remember (s :: b2) as bend.\n      assert (exists y ys, bend = ys ++ [y]) by (apply list_snoc with (xs:=bend) (x:=s) (xs':=b2); crush).\n      destruct H1; destruct H1.\n      inv H1.\n      rewrite H3 in *. clear H3.\n      assert (b1 ++ << N k t es; os ++ l ->> pfold f t1 ks :: os' >> :: x0 ++ [x] = (b1 ++ << N k t es; os ++ l ->> pfold f t1 ks :: os' >> :: x0) ++ [x]) by crush.\n      rewrite H1 in H2. clear H1.\n      apply List.app_inj_tail in H2.\n      destruct H2.\n      subst.\n      got.\n      * instantiate (1:=C ((b1 ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: x0) ++ [<< n1; os1' >>]) os1 (l0 ->>> final H :: rs) term1).\n        one_step; eapply S_Last; eauto; crush.\n      * instantiate (1:=C ((b1 ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: x0) ++ [<< n1; os1' >>]) os1 (l0 ->>> final H :: rs) term1).\n        one_step; eapply S_LoadPFold; eauto; crush.\n      * crush.\n  (* S_FusePMap *)\n  - destruct n as [k' t']. tsod'''.\n    + osod.\n      * inv Hsame. destruct H2. crush.\n      * destruct Hfirst as [os''0 [os'' [os''']]].\n        ou1.\n        got.\n        { instantiate (1:=C (b0 ++ << N k' t' e; (os''0 ++ l ->> pfold f t1' ks :: os'') ++ l' ->> pmap (pmap_compose f' f0) ks0 :: os3 >> :: b3) os1 (l0 ->>> 0 :: rs) term1).\n          one_step; eapply S_FusePMap; eauto; crush. }\n        { instantiate (1:=C (b0 ++ << N k' t' e; (os''0 ++ l ->> pfold f t1' ks :: os'') ++ l' ->> pmap (pmap_compose f' f0) ks0 :: os3 >> :: b3) os1 (l0 ->>> 0 :: rs) term1).\n          one_step; eapply S_LoadPFold; eauto; crush. }\n        { crush. }\n      * destruct Hsecond as [os''0 [os'' [os''']]].\n        ou2.\n        {\n        destruct os''; inv H1; simpl in *.\n        - got.\n          + instantiate (1:=C (b0 ++ << N k' t' e; os2 ++ l' ->> pmap (pmap_compose f' f0) ks0 :: os'' ++ l ->> pfold f t1' ks :: os''' >> :: b3) os1 (l0 ->>> 0 :: rs) term1).\n            one_step; eapply S_FusePMap; eauto; crush.\n          + instantiate (1:=C (b0 ++ << N k' t' e; (os2 ++ l' ->> pmap (pmap_compose f' f0) ks0 :: os'') ++ l ->> pfold f t1' ks :: os''' >> :: b3) os1 (l0 ->>> 0 :: rs) term1).\n            one_step; eapply S_LoadPFold; eauto; crush.\n          + crush.\n        }\n    + destruct Hfirst as [b' [b'' [b''']]].\n      tu1.\n      got.\n      * instantiate (1:=C ((b' ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b'') ++ << N k' t' e; os2 ++ l' ->> pmap (pmap_compose f' f0) ks0 :: os3 >> :: b3) os1 (l0 ->>> 0 :: rs) term1).\n        one_step; eapply S_FusePMap; eauto; crush.\n      * instantiate (1:=C ((b' ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b'') ++ << N k' t' e; os2 ++ l' ->> pmap (pmap_compose f' f0) ks0 :: os3 >> :: b3) os1 (l0 ->>> 0 :: rs) term1).\n        one_step; eapply S_LoadPFold; eauto; crush.\n      * crush.\n    + destruct Hsecond as [b' [b'' [b''']]].\n      tu2.\n      got.\n      * instantiate (1:=C (b0 ++ << N k' t' e; os2 ++ l' ->> pmap (pmap_compose f' f0) ks0 :: os3 >> :: b'' ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b''') os1 (l0 ->>> 0 :: rs) term1).\n        one_step; eapply S_FusePMap; eauto; crush.\n      * instantiate (1:=C ((b0 ++ << N k' t' e; os2 ++ l' ->> pmap (pmap_compose f' f0) ks0 :: os3 >> :: b'') ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b''') os1 (l0 ->>> 0 :: rs) term1).\n        one_step; eapply S_LoadPFold; eauto; crush.\n      * crush.\n  (* S_SwapReads *)\n  - destruct n as [k' t'']. tsod'''.\n    + osod.\n      * inv Hsame; dtr. inv H3. inv H. apply List.app_inv_head in H3. inv H3.\n        gotw (C (b0 ++ << N k' t'' e; os2 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f0 t1' ks0 :: os3 >> :: b3) os1 rs term1); eauto.\n        eapply S_LoadPFold with (os:=os2 ++ [l' ->> pfold f' t' ks']). eauto. crush. eauto. crush.\n      * destruct Hfirst as [os''0 [os'' [os''']]].\n        ou1.\n        got.\n        { instantiate (1:=C (b0 ++ << N k' t'' e; (os''0 ++ l ->> pfold f t1' ks :: os'') ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f0 t0 ks0 :: os3 >> :: b3) os1 rs term1).\n          one_step; eapply S_SwapReads; eauto; crush. }\n        { instantiate (1:=C (b0 ++ << N k' t'' e; (os''0 ++ l ->> pfold f t1' ks :: os'') ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f0 t0 ks0 :: os3 >> :: b3) os1 rs term1).\n          one_step; eapply S_LoadPFold; eauto; crush. }\n        { crush. }\n      * destruct Hsecond as [os''0 [os'' [os''']]].\n        ou2.\n        {\n        destruct os''; inv H0; simpl in *.\n        - got.\n          + instantiate (1:=C (b0 ++ << N k' t'' e; os2 ++ l' ->> pfold f' t1' ks' :: l0 ->> pfold f0 t0 ks0 :: os3 >> :: b3) os1 rs term1).\n            one_step; eapply S_SwapReads; eauto.\n            eapply lfree_preservation; eauto.\n          + instantiate (1:=C (b0 ++ << N k' t'' e; os2 ++ l' ->> pfold f' t1' ks' :: l0 ->> pfold f0 t0 ks0 :: os3 >> :: b3) os1 rs term1).\n            one_step; eapply S_LoadPFold; eauto; crush.\n          + crush.\n        - got.\n          + instantiate (1:=C (b0 ++ << N k' t'' e; os2 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f0 t0 ks0 :: os'' ++ l ->> pfold f t1' ks :: os''' >> :: b3) os1 rs term1).\n            one_step; eapply S_SwapReads; eauto.\n          + instantiate (1:=C (b0 ++ << N k' t'' e; (os2 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f0 t0 ks0 :: os'') ++ l ->> pfold f t1' ks :: os''' >> :: b3) os1 rs term1).\n            one_step; eapply S_LoadPFold with (os:=(os2 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f0 t0 ks0 :: os'')); eauto; crush.\n          + crush.\n        }\n    + destruct Hfirst as [b' [b'' [b''']]].\n      tu1.\n      got.\n      * instantiate (1:=C ((b' ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b'') ++ << N k' t'' e; os2 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f0 t0 ks0 :: os3 >> :: b3) os1 rs term1).\n        one_step; eapply S_SwapReads; eauto; crush.\n      * instantiate (1:=C (b' ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b'' ++ << N k' t'' e; os2 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f0 t0 ks0 :: os3 >> :: b3) os1 rs term1).\n        one_step; eapply S_LoadPFold; eauto; crush.\n      * crush.\n    + destruct Hsecond as [b' [b'' [b''']]].\n      tu2.\n      got.\n      * instantiate (1:=C (b0 ++ << N k' t'' e; os2 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f0 t0 ks0 :: os3 >> :: b'' ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b''') os1 rs term1).\n        one_step; eapply S_SwapReads; eauto; crush.\n      * instantiate (1:=C ((b0 ++ << N k' t'' e; os2 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f0 t0 ks0 :: os3 >> :: b'') ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b''') os1 rs term1).\n        one_step; eapply S_LoadPFold with (b1:=(b0 ++ << N k' t'' e; os2 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f0 t0 ks0 :: os3 >> :: b'')); eauto; crush.\n      * crush.\n  (* S_Prop *)\n  - destruct n1 as [k' t']. tsod.\n    + destruct os; simpl in *.\n      * inv Hsame5.\n        got.\n        { instantiate (1:=C (b0 ++ << N k' t' e; os2 >> :: << n2; os3 ++ [l0 ->> pfold f t1' ks] >> :: b3) os1 rs term1).\n          fsame. one_step; eapply S_Prop; eauto; crush. }\n        { instantiate (1:=C ((b0 ++ [<< N k' t' e; os2 >>]) ++ << n2; os3 ++ [l0 ->> pfold f t1' ks] >> :: b3) os1 rs term1).\n          destruct n2. one_step; eapply S_LoadPFold with (b1:=(b0 ++ [<< N k' t' e; os2 >>])) (os:=os3) (os':=[]); eauto; crush. }\n        { crush. }\n      * inv Hsame5.\n        got.\n        { instantiate (1:=C (b0 ++ << N k' t' e; os ++ l ->> pfold f t1' ks :: os' >> :: << n2; os3 ++ [l0 ->> op] >> :: b3) os1 rs term1).\n          fsame. one_step; eapply S_Prop; eauto; crush. }\n        { instantiate (1:=C (b0 ++ << N k' t' e; os ++ l ->> pfold f t1' ks :: os' >> :: << n2; os3 ++ [l0 ->> op] >> :: b3) os1 rs term1).\n          one_step; eapply S_LoadPFold; eauto; crush. }\n        { crush. }\n    + destruct Hfirst as [b' [b'' [b''']]].\n      tu1.\n      got.\n      * instantiate (1:=C ((b' ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b'') ++ << N k' t' e; os2 >> :: << n2; os3 ++ [l0 ->> op] >> :: b3) os1 rs term1).\n        one_step; eapply S_Prop; eauto; crush.\n      * instantiate (1:=C ((b' ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b'') ++ << N k' t' e; os2 >> :: << n2; os3 ++ [l0 ->> op] >> :: b3) os1 rs term1).\n        one_step; eapply S_LoadPFold; eauto; crush.\n      * crush.\n    + destruct Hsecond as [b' [b'' [b''']]].\n      tu2.\n      destruct b''; inv H1; simpl in *.\n      * got.\n        { instantiate (1:=C (b0 ++ << N k' t' e; os2 >> :: << N k t es; (os ++ l ->> pfold f t1' ks :: os') ++ [l0 ->> op] >> :: b3) os1 rs term1).\n          one_step; eapply S_Prop; eauto; crush. }\n        { instantiate (1:=C ((b0 ++ [<< N k' t' e; os2 >>]) ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' ++ [l0 ->> op] >> :: b3) os1 rs term1).\n          one_step; eapply S_LoadPFold; eauto; crush. }\n        { crush. }\n      * got.\n        { instantiate (1:=C (b0 ++ << N k' t' e; os2 >> :: << n2; os3 ++ [l0 ->> op] >> :: b'' ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b''') os1 rs term1).\n          one_step; eapply S_Prop; eauto; crush. }\n        { instantiate (1:=C ((b0 ++ << N k' t' e; os2 >> :: << n2; os3 ++ [l0 ->> op] >> :: b'') ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b''') os1 rs term1).\n          one_step; eapply S_LoadPFold; eauto; crush. }\n        { crush. }\n  (* S_LoadPFold *)\n  - tsod.\n    + osod.\n      * crush. inv H4. fsame.\n        eapply frontend_deterministic' with (b0:=b0 ++ << N k0 t0 es0; os2 ++ l0 ->> pfold f0 t2 ks0 :: os'0 >> :: b3) (os0:=os1) (os:=[]) (t':=t1'0) in tt'; eauto. crush.\n        inversion WT. dtr.\n        {\n        split; try split.\n        - crush.\n        - crush.\n        - exists Result, false.\n          inv WT; dtr. inv H3.\n          econstructor.\n          + eapply wt_backend_build; eauto.\n          + wtbt. eauto.\n          + wtbdist. inv H6. wtosdist. inv H7. inv H18. wtbt. wtost. wtbt. wttost. wtost.\n            simpl in *. eauto.\n        }\n      * destruct Hfirst as [os''0 [os'' [os''']]].\n        ou1.\n        got.\n        { instantiate (1:=C (b0 ++ << N k0 t0 es0; (os''0 ++ l ->> pfold f t1' ks :: os'') ++ l0 ->> pfold f0 t1'0 ks0 :: os'0 >> :: b3) os1 rs1 term1).\n          one_step; eapply S_LoadPFold with (os:=(os''0 ++ l ->> pfold f t1' ks :: os'')); eauto; crush. }\n        { instantiate (1:=C (b0 ++ << N k0 t0 es0; (os''0 ++ l ->> pfold f t1' ks :: os'') ++ l0 ->> pfold f0 t1'0 ks0 :: os'0 >> :: b3) os1 rs1 term1).\n          one_step; eapply S_LoadPFold; eauto; crush. }\n        { crush. }\n      * destruct Hsecond as [os''0 [os'' [os''']]].\n        ou2.\n        got.\n        { instantiate (1:=C (b0 ++ << N k0 t0 es0; os2 ++ l0 ->> pfold f0 t1'0 ks0 :: os'' ++ l ->> pfold f t1' ks :: os''' >> :: b3) os1 rs1 term1).\n          one_step; eapply S_LoadPFold; eauto; crush. }\n        { instantiate (1:=C (b0 ++ << N k0 t0 es0; (os2 ++ l0 ->> pfold f0 t1'0 ks0 :: os'') ++ l ->> pfold f t1' ks :: os''' >> :: b3) os1 rs1 term1).\n          one_step; eapply S_LoadPFold with (b1:=b0) (t1':=t1') (os':=os''') (b2:=b3) (k:=k0) (f:=f) (l:=l) (ks:=ks) (t:=t0) (os:=(os2 ++ l0 ->> pfold f0 t1'0 ks0 :: os'')); eauto; crush. }\n        { crush. }\n    + destruct Hfirst as [b' [b'' [b''']]].\n      tu1.\n      got.\n      * instantiate (1:=C ((b' ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b'') ++ << N k0 t0 es0; os2 ++ l0 ->> pfold f0 t1'0 ks0 :: os'0 >> :: b3) os1 rs1 term1).\n        one_step; eapply S_LoadPFold with (b1:=(b' ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b'')); eauto; crush.\n      * instantiate (1:=C (b' ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b'' ++ << N k0 t0 es0; os2 ++ l0 ->> pfold f0 t1'0 ks0 :: os'0 >> :: b3) os1 rs1 term1).\n        one_step; eapply S_LoadPFold; eauto; crush.\n      * crush.\n    + destruct Hsecond as [b' [b'' [b''']]].\n      tu2.\n      got.\n      * instantiate (1:=C (b0 ++ << N k0 t0 es0; os2 ++ l0 ->> pfold f0 t1'0 ks0 :: os'0 >> :: b'' ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b''') os1 rs1 term1).\n        one_step; eapply S_LoadPFold; eauto; crush.\n      * instantiate (1:=C ((b0 ++ << N k0 t0 es0; os2 ++ l0 ->> pfold f0 t1'0 ks0 :: os'0 >> :: b'') ++ << N k t es; os ++ l ->> pfold f t1' ks :: os' >> :: b''') os1 rs1 term1).\n        one_step; eapply S_LoadPFold with (k:=k) (t:=t) (t1':=t1') (os:=os) (l:=l) (f:=f) (ks:=ks) (b2:=b''') (os':=os') (b1:=(b0 ++ << N k0 t0 es0; os2 ++ l0 ->> pfold f0 t1'0 ks0 :: os'0 >> :: b'')); eauto; crush.\n      * crush.\nUnshelve.\nauto.\nauto.\nauto.\nauto.\nQed.\nHint Resolve lc_loadpfold.\n\nLemma lc_prop :\n  forall cx cy cz os rs term n1 n2 l op os1 os2 b1 b2,\n  well_typed cx ->\n  cx = C (b1 ++ <<n1; l ->> op :: os1>> :: <<n2; os2>> :: b2) os rs term ->\n  cy = C (b1 ++ <<n1; os1>> :: <<n2; os2 ++ [l ->> op]>> :: b2) os rs term ->\n  cx --> cy ->\n  cx --> cz ->\n  ~ (In (getKey n1) (target op)) ->\n  cy -v cz.\nProof using.\n  intros cx cy cz os rs term n1 n2 l op os1 os2 b1 b2.\n  intros WT Heqcx Heqcy cxcy cxcz.\n  intros notin.\n  inversion cxcz; ssame; try solve [subst; eauto].\n  (* S_Empty *)\n  - destruct b1; crush.\n  (* S_First *)\n  - destruct b1; simpl in *.\n    + inv H1.\n      gotw (C (<< n0; os1 ++ [l0 ->> op0] >> :: << n2; os2 ++ [l ->> op] >> :: b2) os' rs0 term0); eauto.\n      apply S_Prop with (b1:=[]) (b:=<< n0; l ->> op :: os1 ++ [l0 ->> op0] >> :: << n2; os2 >> :: b2); crush.\n    + inv H1.\n      gotw (C (<< n0; os3 ++ [l0 ->> op0] >> :: b1 ++ << n1;  os1 >> :: << n2; os2 ++ [l ->> op] >> :: b2) os' rs0 term0); eauto.\n      repeat (rewrite List.app_comm_cons).\n      eauto.\n  (* S_Add *)\n  - gotw (C (<< N k v t_ks_nil; [] >> :: b1 ++ << n1; os1 >> :: << n2; os2 ++ [l ->> op] >> :: b2) os' (l0 ->>> final H :: rs0) term0); eauto.\n    repeat (rewrite List.app_comm_cons).\n    eauto.\n  (* S_PMap *)\n  - destruct n1.\n    eapply target_same_or_different with (b1:=b1) (b2:=<< n2; os2 >> :: b2) (b3:=b0) (b4:=b3) (k:=k0) (v:=p) (k':=k) (v':=v) in H1; eauto.\n    destruct H1; try destruct H0.\n    (* Same target *)\n    + destruct H1. destruct H2. destruct H3. subst.\n      inv H4.\n      crush.\n    (* First first *)\n    + destruct H0. destruct H0. destruct H0.\n      eapply target_unique with (b1:=b1) (b2:=<< n2; os2 >> :: b2) (b3:=x) (b4:=x0 ++ << N k v es; l0 ->> pmap f ks :: os1'' >> :: x1) in H0; crush.\n      rewrite H2 in *.\n      destruct x0.\n      * inv H.\n        simpl in *.\n        eapply target_unique with (b1:=x ++ [<< N k0 p e; l ->> op :: os1 >>]) (b2:=x1) (b3:=b0) (b4:=b3) in H1; eauto; crush.\n        inv H2.\n        {\n          got.\n          - instantiate (1:=C ((x ++ [<< N k0 p e; os1 >>]) ++ << N k (t_app f v) es; l0 ->> pmap f (remove Nat.eq_dec k ks) :: os1'' ++ [l ->> op] >> :: b3) os0 rs0 term0).\n            one_step. eapply S_PMap; crush.\n          - instantiate (1:=C (x ++ << N k0 p e; os1 >> :: << N k (t_app f v) es; (l0 ->> pmap f (remove Nat.eq_dec k ks) :: os1'') ++ [l ->> op] >> :: b3) os0 rs0 term0).\n            one_step. eapply S_Prop; crush.\n          - crush.\n        }\n      * inv H2.\n        inv H.\n        eapply target_unique with (b1:=x ++ << N k0 p e; l ->> op :: os1 >> :: << n2; os2 >> :: x0) (b2:=x1) (b3:=b0) (b4:=b3) in H1; eauto; crush.\n        {\n          got.\n          - instantiate (1:=C ((x ++ << N k0 p e; os1 >> :: << n2; os2 ++ [l ->> op] >> :: x0) ++ << N k (t_app f v) es; l0 ->> pmap f (remove Nat.eq_dec k ks) :: os1'' >> :: b3) os0 rs0 term0).\n            one_step. eapply S_PMap; crush.\n          - instantiate (1:=C (x ++ << N k0 p e; os1 >> :: << n2; os2 ++ [l ->> op] >> :: x0 ++ << N k (t_app f v) es; l0 ->> pmap f (remove Nat.eq_dec k ks) :: os1'' >> :: b3) os0 rs0 term0).\n            one_step. eapply S_Prop; crush.\n          - crush.\n        }\n    (* First second *)\n    + destruct H0. destruct H0. destruct H0.\n      eapply target_unique with (b1:=b1) (b2:=<< n2; os2 >> :: b2) (b3:=x ++ << N k v es; l0 ->> pmap f ks :: os1'' >> :: x0) (b4:=x1) in H0; eauto; crush.\n      inv H.\n      eapply target_unique with (b1:=x) (b2:=x0 ++ << N k0 p e; l ->> op :: os1 >> :: << n2; os2 >> :: b2) (b3:=b0) (b4:=b3) in H1; eauto; crush.\n      got.\n      * instantiate (1:= C (b0 ++ << N k (t_app f v) es; l0 ->> pmap f (remove Nat.eq_dec k ks) :: os1'' >> :: x0 ++ << N k0 p e; os1 >> :: << n2; os2 ++ [l ->> op] >> :: b2) os0 rs0 term0).\n        one_step. eapply S_PMap; crush.\n      * instantiate (1:= C ((b0 ++ << N k (t_app f v) es; l0 ->> pmap f (remove Nat.eq_dec k ks) :: os1'' >> :: x0) ++ << N k0 p e; os1 >> :: << n2; os2 ++ [l ->> op] >> :: b2) os0 rs0 term0).\n        one_step. eapply S_Prop; crush.\n      * crush.\n  (* S_Last *)\n  - destruct b2; rename H into Hnot; rename H2 into H1; rename H0 into H.\n    + assert (b1 ++ [<< n1; l ->> op :: os1 >>; << n2; os2 >>] = b1 ++ [<< n1; l ->> op :: os1 >>] ++ [<< n2; os2 >>]) by crush.\n      rewrite H0 in H1; clear H0.\n      rewrite List.app_assoc in H1.\n      apply List.app_inj_tail in H1.\n      destruct H1.\n      subst.\n      inv H1.\n      got.\n      * instantiate (1:=C ((b1 ++ [<< n1; os1 >>]) ++ [<< n0; os1' ++ [l ->> op] >>]) os0 (l0 ->>> final Hnot :: rs0) term0).\n        one_step. eapply S_Last with (b1:=b1 ++ [<< n1; os1 >>]) (os1:=(l0 ->> op0 :: os1') ++ [l ->> op]); eauto.\n        simpl.\n        rewrite List.app_comm_cons.\n        crush.\n      * instantiate (1:=C (b1 ++ << n1; os1 >> :: [<< n0; os1' ++ [l ->> op] >>]) os0 (l0 ->>> final Hnot :: rs0) term0).\n        one_step. eapply S_Prop; eauto.\n        crush.\n      * crush.\n    + remember (s :: b2) as bend.\n      assert (exists y ys, bend = ys ++ [y]) by (apply list_snoc with (xs:=bend) (x:=s) (xs':=b2); crush).\n      destruct H0; destruct H0.\n      inv H0.\n      rewrite H2 in *. clear H2.\n      assert (b1 ++ << n1; l ->> op :: os1 >> :: << n2; os2 >> :: x0 ++ [x] = (b1 ++ << n1; l ->> op :: os1 >> :: << n2; os2 >> :: x0) ++ [x]) by crush.\n      rewrite H0 in H1. clear H0.\n      apply List.app_inj_tail in H1.\n      destruct H1.\n      subst.\n      gotw (C (b1 ++ << n1; os1 >> :: << n2; os2 ++ [l ->> op] >> :: x0 ++ [<< n0;  os1' >>]) os0 (l0 ->>> final Hnot :: rs0) term0); eauto.\n      * assert (forall x, b1 ++ << n1; os1 >> :: << n2; os2 ++ [l ->> op] >> :: x0 ++ x = (b1 ++ << n1; os1 >> :: << n2; os2 ++ [l ->> op] >> :: x0) ++ x) by crush.\n        repeat (rewrite H0). clear H0.\n        eauto.\n      * rewrite <- List.app_assoc.\n        eauto.\n  (* S_FusePMap *)\n  - destruct n1 as [k v].\n    destruct n as [k' v'].\n    rename H into Hnot.\n    rename H0 into H.\n    rename H2 into H1.\n    eapply target_same_or_different with (b1:=b1) (b2:=<< n2; os2 >> :: b2) (b3:=b0) (b4:=b3) (k:=k) (v:=v) (k':=k') (v':=v') in H1; eauto.\n    destruct H1; try destruct H0.\n    (* Same target *)\n    + destruct H1. destruct H2. destruct H3. subst.\n      destruct os3.\n      * simpl in *.\n        inv H4.\n        {\n        got.\n        - fsame.\n          instantiate (1:=C (b0 ++ << N k' v' e0; os4 >> :: << n2; os2 ++ [l' ->> pmap (pmap_compose f' f) ks] >> :: b2) os0 (l0 ->>> 0 :: rs0) term0).\n          apply ex_intro with 2.\n          eapply Step.\n          instantiate (1:=C (b0 ++ << N k' v' e0; os4 >> :: << n2; (os2 ++ [l0 ->> pmap f ks]) ++ [l' ->> pmap f' ks] >> :: b2) os0 rs0 term0).\n          eapply S_Prop; crush.\n          apply one_star.\n          assert ((os2 ++ [l0 ->> pmap f ks]) ++ [l' ->> pmap f' ks] = os2 ++ [l0 ->> pmap f ks] ++ [l' ->> pmap f' ks]) by crush.\n          rewrite H. clear H.\n          assert (forall x, b0 ++ << N k' v' e0; os4 >> :: x = (b0 ++ [<< N k' v' e0; os4 >>]) ++ x) by crush.\n          rewrite H. clear H.\n          assert (b0 ++ << N k' v' e0; os4 >> :: << n2; os2 ++ [l' ->> pmap (pmap_compose f' f) ks] >> :: b2 = (b0 ++ [<< N k' v' e0; os4 >>]) ++ << n2; os2 ++ [l' ->> pmap (pmap_compose f' f) ks] >> :: b2) by crush.\n          rewrite H. clear H.\n          eapply S_FusePMap; crush.\n        - instantiate (1:=C (b0 ++ << N k' v' e0; os4 >> :: << n2; os2 ++ [l' ->> pmap (pmap_compose f' f) ks] >> :: b2) os0 (l0 ->>> 0 :: rs0) term0).\n          one_step. eapply S_Prop; crush.\n        - crush.\n        }\n      * simpl in *.\n        inv H4.\n        {\n        fsame.\n        got.\n        - instantiate (1:=C (b0 ++ << N k' v' e0; os3 ++ l' ->> pmap (pmap_compose f' f) ks :: os4 >> :: << n2; os2 ++ [l ->> op] >> :: b2) os0 (l0 ->>> 0 :: rs0) term0).\n          one_step. eapply S_FusePMap; crush.\n        - instantiate (1:=C (b0 ++ << N k' v' e0; os3 ++ l' ->> pmap (pmap_compose f' f) ks :: os4 >> :: << n2; os2 ++ [l ->> op] >> :: b2) os0 (l0 ->>> 0 :: rs0) term0).\n          one_step. eapply S_Prop; crush.\n        - crush.\n        }\n    (* First first *)\n    + destruct H0. destruct H0. destruct H0.\n      destruct x0; simpl in *.\n      * eapply target_unique with (b1:=b1) (b2:=<< n2; os2 >> :: b2) (b3:=x) (b4:=<< N k' v' e0; os3 ++ l0 ->> pmap f ks :: l' ->> pmap f' ks :: os4 >> :: x1) in H0; eauto; crush.\n        inv H2.\n        inv H.\n        eapply target_unique with (b1:=x ++ [<< N k v e; l ->> op :: os1 >>]) (b2:=x1) (b3:=b0) (b4:=b3) in H1; eauto; crush.\n        {\n        got.\n        - instantiate (1:=C ((x ++ [<< N k v e; os1 >>]) ++ << N k' v' e0; os3 ++ l' ->> pmap (pmap_compose f' f) ks :: os4 ++ [l ->> op] >> :: b3) os0 (l0 ->>> 0 :: rs0) term0).\n          one_step. eapply S_FusePMap; crush.\n        - instantiate (1:=C (x ++ << N k v e; os1 >> :: << N k' v' e0; (os3 ++ l' ->> pmap (pmap_compose f' f) ks :: os4) ++ [l ->> op] >> :: b3) os0 (l0 ->>> 0 :: rs0) term0).\n          one_step. eapply S_Prop; crush.\n        - crush.\n        }\n      * eapply target_unique with (b1:=b1) (b2:=<< n2; os2 >> :: b2) (b3:=x) (b4:=s :: x0 ++ << N k' v' e0; os3 ++ l0 ->> pmap f ks :: l' ->> pmap f' ks :: os4 >> :: x1) in H0; eauto; crush.\n        inv H.\n        eapply target_unique with (b1:=x ++ << N k v e; l ->> op :: os1 >> :: << n2; os2 >> :: x0) (b2:=x1) (b3:=b0) (b4:=b3) in H1; eauto; crush.\n        {\n        got.\n        - instantiate (1:=C ((x ++ << N k v e; os1 >> :: << n2; os2 ++ [l ->> op] >> :: x0) ++ << N k' v' e0; os3 ++ l' ->> pmap (pmap_compose f' f) ks :: os4 >> :: b3) os0 (l0 ->>> 0 :: rs0) term0).\n          one_step. eapply S_FusePMap; crush.\n        - instantiate (1:=C (x ++ << N k v e; os1 >> :: << n2; os2 ++ [l ->> op] >> :: x0 ++ << N k' v' e0; os3 ++ l' ->> pmap (pmap_compose f' f) ks :: os4 >> :: b3) os0 (l0 ->>> 0 :: rs0) term0).\n          one_step. eapply S_Prop; crush.\n        - crush.\n        }\n    (* First second *)\n    + destruct H0. destruct H0. destruct H0.\n      eapply target_unique with (b1:=b1) (b2:=<< n2; os2 >> :: b2) (b3:=x ++ << N k' v' e0; os3 ++ l0 ->> pmap f ks :: l' ->> pmap f' ks :: os4 >> :: x0) (b4:=x1) in H0; eauto; crush.\n      inv H.\n      eapply target_unique with (b1:=x) (b2:=x0 ++ << N k v e; l ->> op :: os1 >> :: << n2; os2 >> :: b2) (b3:=b0) (b4:=b3) in H1; eauto; crush.\n      got.\n      * instantiate (1:=C (b0 ++ << N k' v' e0; os3 ++ l' ->> pmap (pmap_compose f' f) ks :: os4 >> :: x0 ++ << N k v e; os1 >> :: << n2; os2 ++ [l ->> op] >> :: b2) os0 (l0 ->>> 0 :: rs0) term0).\n        one_step. eapply S_FusePMap; crush.\n      * instantiate (1:=C ((b0 ++ << N k' v' e0; os3 ++ l' ->> pmap (pmap_compose f' f) ks :: os4 >> :: x0) ++ << N k v e; os1 >> :: << n2; os2 ++ [l ->> op] >> :: b2) os0 (l0 ->>> 0 :: rs0) term0).\n        one_step. eapply S_Prop; crush.\n      * crush.\n  (* S_SwapReads *)\n  - destruct n1 as [k v].\n    destruct n as [k' v'].\n    tsod'.\n    + destruct os3.\n      *\n      {\n      simpl in *. inv Hsame5. inv H. apply List.app_inv_head in H3. inv H3.\n      got.\n      - instantiate (1:=C (b0 ++ << N k' v' e0; l' ->> pfold f' t' ks' :: os4 >> :: << n2; os2 ++ [l0 ->> pfold f t ks] >> :: b2) os0 rs0 term0).\n        exists 0. auto.\n      - instantiate (1:=C (b0 ++ << N k' v' e0; l' ->> pfold f' t' ks' :: os4 >> :: << n2; os2 ++ [l0 ->> pfold f t ks] >> :: b2) os0 rs0 term0).\n        exists 2.\n        eapply Step.\n        instantiate (1:=C (b0 ++ << N k' v' e0; l0 ->> pfold f t ks :: l' ->> pfold f' t' ks' :: os4 >> :: << n2; os2 >> :: b2) os0 rs0 term0).\n        eapply S_SwapReads with (os1:=[]) (b2:=<<n2; os2>>::b2); eauto.\n        eapply no_dep_backwards' with (os1:=[]); eauto.\n        eapply no_dep_backwards with (os1:=[]); eauto.\n        eapply Step.\n        eapply S_Prop; eauto. simpl. auto.\n        auto.\n      - crush.\n      }\n      * inv Hsame5.\n      {\n      inv H. apply List.app_inv_head in H3. inv H3. got.\n      - instantiate (1:=C (b0 ++ << N k' v' e0; os3 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f t ks :: os4 >> :: << n2; os2 ++ [l ->> op] >> :: b2) os0 rs0 term0).\n        one_step. eapply S_SwapReads; crush.\n      - instantiate (1:=C (b0 ++ << N k' v' e0; os3 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f t ks :: os4 >> :: << n2; os2 ++ [l ->> op] >> :: b2) os0 rs0 term0).\n        one_step. eapply S_Prop; eauto.\n      - crush.\n      }\n    + destruct Hfirst as [b' [b'' [b''']]].\n      destruct b''; simpl in *.\n      * eapply target_unique with (b1:=b1) (b2:=<< n2; os2 >> :: b2) (b3:=b') (b4:=<< N k' v' e0; os3 ++ l0 ->> pfold f t ks :: l' ->> pfold f' t' ks' :: os4 >> :: b''') in H0; eauto; crush.\n        inv H4. inv H.\n        eapply target_unique with (b1:=b' ++ [<< N k v e; l ->> op :: os1 >>]) (b2:=b''') (b3:=b0) (b4:=b3) in H3; eauto; crush.\n        got.\n        { instantiate (1:=C ((b' ++ [<< N k v e; os1 >>]) ++ << N k' v' e0; os3 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f t ks :: os4 ++ [l ->> op] >> :: b3) os0 rs0 term0).\n          one_step. eapply S_SwapReads; eauto; crush. }\n        { instantiate (1:=C (b' ++ << N k v e; os1 >> :: << N k' v' e0; (os3 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f t ks :: os4) ++ [l ->> op] >> :: b3) os0 rs0 term0).\n          one_step. eapply S_Prop; eauto; crush. }\n        { crush. }\n      * eapply target_unique with (b1:=b1) (b2:=<< n2; os2 >> :: b2) (b3:=b') (b4:=s :: b'' ++ << N k' v' e0; os3 ++ l0 ->> pfold f t ks :: l' ->> pfold f' t' ks' :: os4 >> :: b''') in H0; eauto; crush.\n        inv H.\n        eapply target_unique with (b1:=b' ++ << N k v e; l ->> op :: os1 >> :: <<n2;os2>>::b'') (b2:=b''') (b3:=b0) (b4:=b3) in H3; eauto; crush.\n        got.\n        { instantiate (1:=C ((b' ++ << N k v e; os1 >> :: << n2; os2 ++ [l ->> op] >> :: b'') ++ << N k' v' e0; os3 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f t ks :: os4 >> :: b3) os0 rs0 term0).\n          one_step. eapply S_SwapReads; eauto; crush. }\n        { instantiate (1:=C (b' ++ << N k v e; os1 >> :: << n2; os2 ++ [l ->> op] >> :: b'' ++ << N k' v' e0; os3 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f t ks :: os4 >> :: b3) os0 rs0 term0).\n          one_step. eapply S_Prop; eauto; crush. }\n        { crush. }\n    + destruct Hsecond as [b' [b'' [b''']]].\n      tu2.\n      got.\n      * instantiate (1:=C (b0 ++ << N k' v' e0; os3 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f t ks :: os4 >> :: b'' ++ << N k v e; os1 >> :: << n2; os2 ++ [l ->> op] >> :: b2) os0 rs0 term0).\n        eauto.\n      * instantiate (1:=C ((b0 ++ << N k' v' e0; os3 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f t ks :: os4 >> :: b'') ++ << N k v e; os1 >> :: << n2; os2 ++ [l ->> op] >> :: b2) os0 rs0 term0).\n        one_step; eapply S_Prop; eauto; crush.\n      * crush.\n  (* S_Prop *)\n  - destruct n1 as [k v].\n    destruct n0 as [k' v'].\n    eapply target_same_or_different with (b1:=b1) (b2:=<< n2; os2 >> :: b2) (b3:=b0) (b4:=<< n3; os4 >> :: b3) (k:=k) (v:=v) (k':=k') (v':=v') in H2; eauto.\n    destruct H2; try destruct H1.\n    (* Same target *)\n    + inv H2.\n      fsame. destruct H4. destruct H1. inv H2. inv H3. crush.\n    (* First first *)\n    + destruct H1. destruct H1. destruct H1.\n      destruct x0.\n      * simpl in *.\n        eapply target_unique with (b1:=b1) (b2:=<< n2; os2 >> :: b2) (b3:=x) (b4:=<< N k' v' e0; l0 ->> op0 :: os3 >> :: x1) in H1; eauto; crush.\n        inv H3.\n        inv H.\n        eapply target_unique with (b1:=x ++ [<< N k v e; l ->> op :: os1 >>]) (b2:=x1) (b3:=b0) (b4:=<< n3; os4 >> :: b3) in H2; eauto; crush.\n        {\n        got.\n        - instantiate (1:=C ((x ++ [<< N k v e; os1 >>]) ++ << N k' v' e0; os3 ++ [l ->> op] >> :: << n3; os4 ++ [l0 ->> op0] >> :: b3) os0 rs0 term0).\n          one_step. eapply S_Prop; crush.\n        - instantiate (1:=C (x ++ << N k v e; os1 >> :: << N k' v' e0; os3 ++ [l ->> op] >> :: << n3; os4 ++ [l0 ->> op0] >> :: b3) os0 rs0 term0).\n          one_step. eapply S_Prop; crush.\n        - crush.\n        }\n      * simpl in *.\n        eapply target_unique with (b1:=b1) (b2:=<< n2; os2 >> :: b2) (b3:=x) (b4:=s :: x0 ++ << N k' v' e0; l0 ->> op0 :: os3 >> :: x1) in H1; eauto; crush.\n        inv H.\n        eapply target_unique with (b1:=x ++ << N k v e; l ->> op :: os1 >> :: << n2; os2 >> :: x0) (b2:=x1) (b3:=b0) (b4:=<< n3; os4 >> :: b3) in H2; eauto; crush.\n        {\n        got.\n        - instantiate (1:=C ((x ++ << N k v e; os1 >> :: << n2; os2 ++ [l ->> op] >> :: x0) ++ << N k' v' e0; os3 >> :: << n3; os4 ++ [l0 ->> op0] >> :: b3) os0 rs0 term0).\n          one_step. eapply S_Prop; crush.\n        - instantiate (1:=C (x ++ << N k v e; os1 >> :: << n2; os2 ++ [l ->> op] >> :: x0 ++ << N k' v' e0; os3 >> :: << n3; os4 ++ [l0 ->> op0] >> :: b3) os0 rs0 term0).\n          one_step. eapply S_Prop; crush.\n        - crush.\n        }\n    (* First second *)\n    + destruct H1. destruct H1. destruct H1.\n      destruct x0.\n      * simpl in *.\n        eapply target_unique with (b1:=b1) (b2:=<< n2; os2 >> :: b2) (b3:=x ++ [<< N k' v' e0; l0 ->> op0 :: os3 >>]) (b4:=x1) in H1; eauto; crush.\n        inv H.\n        eapply target_unique with (b1:=x) (b2:=<< N k v e; l ->> op :: os1 >> :: << n2; os2 >> :: b2) (b3:=b0) (b4:=<< n3; os4 >> :: b3) in H2; eauto; crush.\n        inv H1.\n        {\n        got.\n        - instantiate (1:=C (b0 ++ << N k' v' e0; os3 >> :: << N k v e; os1 ++ [l0 ->> op0] >> :: << n2; os2 ++ [l ->> op] >> :: b2) os0 rs0 term0).\n          one_step. eapply S_Prop; crush.\n        - instantiate (1:=C ((b0 ++ [<< N k' v' e0; os3 >>]) ++ << N k v e; os1 ++ [l0 ->> op0] >> :: << n2; os2 ++ [l ->> op] >> :: b2) os0 rs0 term0).\n          one_step. eapply S_Prop; crush.\n        - crush.\n        }\n      * simpl in *.\n        eapply target_unique with (b1:=b1) (b2:=<< n2; os2 >> :: b2) (b3:=x ++ << N k' v' e0; l0 ->> op0 :: os3 >> :: s :: x0) (b4:=x1) in H1; eauto; crush.\n        inv H.\n        eapply target_unique with (b1:=x) (b2:=s :: x0 ++ << N k v e; l ->> op :: os1 >> :: << n2; os2 >> :: b2) (b3:=b0) (b4:=<< n3; os4 >> :: b3) in H2; eauto; crush.\n        {\n        got.\n        - instantiate (1:=C (b0 ++ << N k' v' e0; os3 >> :: << n3; os4 ++ [l0 ->> op0] >> :: x0 ++ << N k v e; os1 >> :: << n2; os2 ++ [l ->> op] >> :: b2) os0 rs0 term0).\n          one_step. eapply S_Prop; crush.\n        - instantiate (1:=C ((b0 ++ << N k' v' e0; os3 >> :: << n3; os4 ++ [l0 ->> op0] >> :: x0) ++ << N k v e; os1 >> :: << n2; os2 ++ [l ->> op] >> :: b2) os0 rs0 term0).\n          one_step. eapply S_Prop; crush.\n        - crush.\n        }\nUnshelve.\nauto.\nauto.\nauto.\nauto.\nauto.\nQed.\nHint Resolve lc_prop.\n\nLemma lc_first :\n  forall cx cy cz rs l op term n1 os1 b' os',\n  well_typed cx ->\n  cx = C (<< n1; os1 >> :: b') (l ->> op :: os') rs term ->\n  cy = C (<< n1; os1 ++ [l ->> op] >> :: b') os' rs term ->\n  not_add op ->\n  cx --> cy ->\n  cx --> cz ->\n  cy -v cz.\nProof using.\n  intros cx cy cz rs l op term0 n1 os1 b' os' WT Heqcx Heqcy Hnotnotadd cxcy cxcz.\n  inversion cxcz; ssame; try solve [subst; eauto].\n  (* S_Add *)\n  - crush.\n  (* S_PMap *)\n  - destruct b1; simpl in *.\n    * gotw (C (<< N k (t_app f v) es; l0 ->> pmap f (remove Nat.eq_dec k ks) :: os1'' ++ [l ->> op] >> :: b2)  os' rs0 term1).\n      { inv H1; eapply S_PMap with (b1:=[]); crush. }\n      { inv H1; eapply S_First with (os1:=l0 ->> pmap f (remove Nat.eq_dec k ks) :: os1''); crush. }\n      { crush. }\n    * gotw (C (<< n1; os1 ++ [l ->> op] >> :: b1 ++ << N k (t_app f v) es; l0 ->> pmap f (remove Nat.eq_dec k ks) :: os1'' >> :: b2) os' rs0 term1).\n      { inv H1. eapply S_PMap with (b1:=<< n1; os1 ++ [l ->> op] >> :: b1); crush. }\n      { inv H1. eapply S_First; crush. }\n      { crush. }\n  (* S_Last *)\n  - crush.\n    {\n    destruct b1; eapply ex_intro; eapply ex_intro; intros.\n    (* b1 = [] *)\n    - split; try split.\n      + simpl in *. instantiate (1 := C [<< n1; os1' ++ [l ->> op]>>] os' (l0 ->>> final H :: rs0) term1).\n        inversion H2.\n        one_step; eapply S_Last with (b1 := []); crush.\n      + simpl in *. instantiate (1 := C [<< n1; os1' ++ [l ->> op]>>] os' (l0 ->>> final H :: rs0) term1).\n        inversion H2.\n        one_step; eapply S_First; crush.\n      + crush.\n    (* b1 != [] *)\n    - split; try split.\n      + instantiate (1 := C (<< n1; os1 ++ [l ->> op] >> :: b1 ++ [<< n0; os1' >>]) os' (l0 ->>> final H :: rs0) term1).\n        inversion H2.\n        one_step; eapply S_Last with (b1 := << n1; os1 ++ [l ->> op] >> :: b1); crush.\n      + instantiate (1 := C (<< n1; os1 ++ [l ->> op] >> :: b1 ++ [<< n0; os1' >>]) os' (l0 ->>> final H :: rs0) term1).\n        inversion H2.\n        one_step; eapply S_First; crush.\n      + crush.\n    }\n  (* S_FusePMap *)\n  - destruct b1; simpl in *.\n    (* b1 = [] *)\n    * gotw (C (<< n; os0 ++ l' ->> pmap (pmap_compose f' f) ks :: os2 ++ [l ->> op] >> :: b2) os' (l0 ->>> 0 :: rs0) term1).\n      { inv H2. eapply S_FusePMap with (b1:=[]); crush. }\n      { inv H2. assert (os0 ++ l' ->> pmap (pmap_compose f' f) ks :: os2 ++ [l ->> op] = (os0 ++ l' ->> pmap (pmap_compose f' f) ks :: os2) ++ [l ->> op]) by crush. rewrite H1. eapply S_First; crush. }\n      { crush. }\n    (* b1 != [] *)\n    * gotw (C (<< n1; os1 ++ [l ->> op] >> :: b1 ++ << n; os0 ++ l' ->> pmap (pmap_compose f' f) ks :: os2 >> :: b2) os' (l0 ->>> 0 :: rs0) term1).\n      { inv H2. eapply S_FusePMap with (b1:=<< n1; os1 ++ [l ->> op] >> :: b1); crush. }\n      { inv H2. eapply S_First; crush. }\n      { crush. }\n  (* S_SwapReads *)\n  - destruct b1; simpl in *.\n    (* b1 = [] *)\n    * inv H. inv H3.\n      gotw (C (<< n; os0 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f t ks :: os2 ++ [l ->> op] >> :: b2) os' rs0 term1).\n      { eapply S_SwapReads with (b1:=[]); crush. }\n      { replace (os0 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f t ks :: os2 ++ [l ->> op]) with ((os0 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f t ks :: os2) ++ [l ->> op]) by crush. eapply S_First; crush. }\n      { crush. }\n    (* b1 != [] *)\n    * inv H3.\n      gotw (C (<< n1; os1 ++ [l ->> op] >> :: b1 ++ << n; os0 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f t ks :: os2 >> :: b2) os' rs0 term1); eauto.\n      { eapply S_SwapReads with (b1:=<< n1; os1 ++ [l ->> op] >> :: b1); crush. }\nUnshelve.\nauto.\nauto.\nQed.\nHint Resolve lc_first.\n\nLemma not_afi_subst : forall t x t',\n  not (appears_free_in x t) ->\n  #[x:=t'] t = t.\nProof using.\n  induction t; auto; intros.\n  - destruct (string_dec x s).\n    + exfalso. apply H. subst. auto.\n    + simpl. assert (eqb_string x s = false) by (apply eqb_string_false_iff; auto). rewrite H0. auto.\n  - assert (#[x:=t'] t1 = t1) by (apply IHt1; auto).\n    assert (#[x:=t'] t2 = t2) by (apply IHt2; auto).\n    crush.\n  - destruct (string_dec x s).\n    + simpl. subst. assert (eqb_string s s = true) by (subst; apply eqb_string_true_iff; auto). rewrite H0. auto.\n    + assert (#[x:=t'] t0 = t0) by (apply IHt; auto).\n      simpl.\n      assert (eqb_string x s = false) by (apply eqb_string_false_iff; auto). rewrite H1.\n      assert (#[x:=t'] t0 = t0) by (apply IHt; auto).\n      crush.\n  - assert (#[x:=t'] t1 = t1) by (apply IHt1; auto).\n    assert (#[x:=t'] t2 = t2) by (apply IHt2; auto).\n    crush.\n  - assert (#[x:=t'] t = t) by (apply IHt; auto).\n    crush.\n  - assert (#[x:=t'] t1 = t1) by (apply IHt1; auto).\n    assert (#[x:=t'] t2 = t2) by (apply IHt2; auto).\n    assert (#[x:=t'] t3 = t3) by (apply IHt3; auto).\n    crush.\n  - assert (#[x:=t'] t1 = t1) by (apply IHt1; auto).\n    assert (#[x:=t'] t2 = t2) by (apply IHt2; auto).\n    crush.\n  - assert (#[x:=t'] t1 = t1) by (apply IHt1; auto).\n    assert (#[x:=t'] t2 = t2) by (apply IHt2; auto).\n    crush.\n  - assert (#[x:=t'] t1 = t1) by (apply IHt1; auto).\n    assert (#[x:=t'] t2 = t2) by (apply IHt2; auto).\n    assert (#[x:=t'] t3 = t3) by (apply IHt3; auto).\n    crush.\n  - crush.\n  - crush.\n  - crush.\n  - assert (#[x:=t'] t0 = t0) by (apply IHt; auto).\n    crush.\nQed.\n\nLemma fstar_app2 : forall m t t' t'' rs,\n  value t ->\n  fstar m t' rs t'' ->\n  fstar m (t_app t t') rs (t_app t t'').\nProof using.\n  induction m; intros.\n  - apply fstar_zero in H0; subst; auto.\n  - inv H0. econstructor. instantiate (1:=t_app t t'0). auto. auto.\nQed.\n\nLemma rewrite_e_subst : forall t1 t2 x v,\n  #[x:=v] (t_app t1 t2) = t_app (#[x:=v] t1) (#[x:=v] t2).\nProof using.\n  auto.\nQed.\n\nLemma pmap_compose_comm : forall f f' rs t,\n  (exists T1 T2 ll, has_type empty ll f (Arrow T1 T2 false) false) ->\n  (exists T1 T2 ll, has_type empty ll f' (Arrow T1 T2 false) false) ->\n  value f ->\n  value f' ->\n  (exists n v, fstar n t rs v /\\ value v) ->\n  exists n m t', fstar n (t_app f (t_app f' t)) rs t' /\\ fstar m (t_app (pmap_compose f f') t) rs t'.\nProof using.\n  intros; dtr. unfold pmap_compose. copy H. copy H0. can_fun. can_fun.\n  exists x, (S x), (t_app (t_abs x8 x4 u0) (t_app (t_abs x7 x1 u) x0)).\n  split.\n  - apply fstar_app2; auto. apply fstar_app2; auto.\n  - replace (S x) with (x + 1).\n    eapply fstar_trans.\n    instantiate (1:=t_app (t_abs \"x\" Result (t_app (t_abs x8 x4 u0) (t_app (t_abs x7 x1 u) (t_var \"x\")))) x0).\n    apply fstar_app2; auto.\n    eapply FStep. eapply F_App; auto.\n    rewrite rewrite_e_subst.\n    replace (#[ \"x\" := x0] t_abs x8 x4 u0) with (t_abs x8 x4 u0).\n    rewrite rewrite_e_subst.\n    replace (#[ \"x\" := x0] t_abs x7 x1 u) with (t_abs x7 x1 u).\n    simpl. auto.\n    assert (~ (appears_free_in \"x\" (t_abs x7 x1 u))) by (eapply typable_empty__closed; eauto).\n    eapply not_afi_subst in H5; eauto.\n    assert (~ (appears_free_in \"x\" (t_abs x8 x4 u0))) by (eapply typable_empty__closed; eauto).\n    eapply not_afi_subst in H5; eauto.\n    crush.\nQed.\n\nLemma rstream_cons_swap : forall t rs t' lr lr',\n    FRf t (lr :: lr' :: rs) ==> FRt t' [] ->\n    FRf t (lr' :: lr :: rs) ==> FRt t' [].\nProof using.\n  induction t; intros; try solve [inv H; constructor; auto].\n  - inv H. constructor. crush. auto.\nQed.\nHint Immediate rstream_cons_swap.\n\nLemma rstream_cons_swap_star : forall n t rs t' lr lr',\n    fstar n t (lr :: lr' :: rs) t' ->\n    fstar n t (lr' :: lr :: rs) t'.\nProof using.\n  induction n; intros.\n  - apply fstar_zero in H; subst; auto.\n  - inv H.\n    inversion H1; subst; econstructor; eauto.\nQed.\n\nLemma lc_pmap :\n  forall cx cy cz rs term0 l f ks os1'' b1 b2 k es os v,\n  well_typed cx ->\n  cx = C (b1 ++ << N k v es; l ->> pmap f ks :: os1'' >> :: b2) os rs term0 ->\n  cy = C (b1 ++ << N k (t_app f v) es; l ->> pmap f (remove Nat.eq_dec k ks) :: os1'' >> :: b2) os rs term0 ->\n  In k ks ->\n  cx --> cy ->\n  cx --> cz ->\n  cy -v cz.\nProof using.\n  intros cx cy cz rs term0 l f ks os1'' b1 b2 k es os v WT Heqcx Heqcy HIn cxcy cxcz.\n  inversion cxcz; ssame; try solve [subst; eauto].\n  (* S_Empty *)\n  - destruct b1; crush.\n  (* S_Add *)\n  - gotw (C (<< N k0 v0 t_ks_nil; [] >> :: b1 ++ << N k (t_app f v) es; l ->> pmap f (remove Nat.eq_dec k ks) :: os1'' >> :: b2) os' (l0 ->>> final H :: rs0) term1).\n    * eapply S_Add; eauto.\n    * eapply S_PMap with (b1:=<< N k0 v0 t_ks_nil; [] >> :: b1); crush.\n    * crush.\n  (* S_PMap *)\n  - rename H1 into H0.\n    rename b3 into b4.\n    rename b0 into b3.\n    {\n    eapply target_same_or_different with (b1:=b1) (b2:=b2) (b3:=b3) (b4:=b4) (k:=k) (v:=v) (k':=k0) (v':=v0) in H0; eauto.\n    - destruct H0; try destruct H0.\n      (* Same target *)\n      + fsame. dtr. inv H2. crush.\n      (* First first *)\n      + destruct H0; destruct H0; destruct H0.\n        apply target_unique with (os:=l ->> pmap f ks :: os1'') (k:=k) (v:=v) (b1:=b1) (b2:=b2) (b3:=x) (b4:=x0 ++ << N k0 v0 es0; l0 ->> pmap f0 ks0 :: os1''0 >> :: x1) (os0:=os0) (rs0:=rs0) (t0:=term1) (b:=b1 ++ << N k v es; l ->> pmap f ks :: os1'' >> :: b2) in H0; crush.\n        inv H.\n        apply target_unique with (os:=l0 ->> pmap f0 ks0 :: os1''0) (k:=k0) (v:=v0) (b1:=x ++ << N k v es; l ->> pmap f ks :: os1'' >> :: x0) (b2:=x1) (b3:=b3) (b4:=b4) (os0:=os0) (rs0:=rs0) (t0:=term1) (b:=x ++ << N k v es; l ->> pmap f ks :: os1'' >> :: x0 ++ << N k0 v0 es0; l0 ->> pmap f0 ks0 :: os1''0 >> :: x1) in H1; crush.\n        got.\n        * instantiate (1:=C ((x ++ << N k (t_app f v) es; l ->> pmap f (remove Nat.eq_dec k ks) :: os1'' >> :: x0) ++ << N k0 (t_app f0 v0) es0; l0 ->> pmap f0 (remove Nat.eq_dec k0 ks0) :: os1''0 >> :: b4) os0 rs0 term1).\n          one_step. eapply S_PMap; crush.\n        * instantiate (1:=C (x ++ << N k (t_app f v) es; l ->> pmap f (remove Nat.eq_dec k ks) :: os1'' >> :: x0 ++ << N k0 (t_app f0 v0) es0; l0 ->> pmap f0 (remove Nat.eq_dec k0 ks0) :: os1''0 >> :: b4) os0 rs0 term1).\n          one_step. eapply S_PMap; crush.\n        * crush.\n      (* First second *)\n      + destruct H0; destruct H0; destruct H0.\n        apply target_unique with (os:=l ->> pmap f ks :: os1'') (k:=k) (v:=v) (b1:=b1) (b2:=b2) (b3:=x ++ << N k0 v0 es0; l0 ->> pmap f0 ks0 :: os1''0 >> :: x0) (b4:=x1) (os0:=os0) (rs0:=rs0) (es:=es) (t0:=term1) (b:=b1 ++ << N k v es; l ->> pmap f ks :: os1'' >> :: b2) in H0; crush.\n        inv H.\n        eapply target_unique with (os:=l0 ->> pmap f0 ks0 :: os1''0) (k:=k0) (v:=v0) (b1:=x) (b2:=x0 ++ << N k v es; l ->> pmap f ks :: os1'' >> :: x1) (b3:=b3) (b4:=b4) (os0:=os0) (rs0:=rs0) (t0:=term1) in H1; eauto.\n        got.\n        * instantiate (1:=C (b3 ++ << N k0 (t_app f0 v0) es0; l0 ->> pmap f0 (remove Nat.eq_dec k0 ks0) :: os1''0 >> :: x0 ++ << N k (t_app f v) es; l ->> pmap f (remove Nat.eq_dec k ks) :: os1'' >> :: x1) os0 rs0 term1).\n          one_step. eapply S_PMap; crush.\n        * instantiate (1:=C ((b3 ++ << N k0 (t_app f0 v0) es0; l0 ->> pmap f0 (remove Nat.eq_dec k0 ks0) :: os1''0 >> :: x0) ++ << N k (t_app f v) es; l ->> pmap f (remove Nat.eq_dec k ks) :: os1'' >> :: x1) os0 rs0 term1).\n          one_step. eapply S_PMap; crush.\n        * crush.\n    }\n  (* S_Last *)\n  - rename H into Hnot.\n    rename H0 into H.\n    rename H2 into H1.\n    {\n    destruct b2.\n    (* b2 = [] *)\n    - apply List.app_inj_tail in H1.\n      destruct H1.\n      inversion H1.\n      crush.\n    (* b2 != [] *)\n    - remember (s :: b2) as bend.\n      assert (exists y ys, bend = ys ++ [y]) by (apply list_snoc with (xs:=bend) (x:=s) (xs':=b2); crush).\n      destruct H0; destruct H0.\n      inv H0.\n      rewrite H2 in *.\n      assert (b1 ++ << N k v es; l ->> pmap f ks :: os1'' >> :: x0 ++ [x]=(b1 ++ << N k v es; l ->> pmap f ks :: os1'' >> :: x0) ++ [x]) by crush.\n      rewrite H0 in H1.\n      apply List.app_inj_tail in H1.\n      destruct H1.\n      rewrite H0 in *.\n      subst.\n      got.\n      + instantiate (1:=C ((b1 ++ << N k (t_app f v) es; l ->> pmap f (remove Nat.eq_dec k ks) :: os1'' >> :: x0) ++ [<< n1; os1' >>]) os0 (l0 ->>> final Hnot :: rs0) term1).\n        one_step. eapply S_Last; crush.\n      + instantiate (1:=C (b1 ++ << N k (t_app f v) es; l ->> pmap f (remove Nat.eq_dec k ks) :: os1'' >> :: x0 ++ [<< n1; os1' >>]) os0 (l0 ->>> final Hnot :: rs0) term1).\n        one_step. eapply S_PMap; crush.\n      + crush.\n    }\n  (* S_FusePMap *)\n  - rename H into Hnot.\n    rename H0 into H.\n    rename H2 into H1.\n    destruct n.\n    eapply target_same_or_different with (b1:=b1) (b2:=b2) (b3:=b0) (b4:=b3) (k:=k) (v:=v) (k':=k0) (v':=p) in H1; eauto.\n    destruct H1; try destruct H0.\n    (* Same target *)\n    + destruct H1. destruct H2. destruct H3. subst.\n      fsame.\n      destruct os1.\n      * simpl in *.\n        inv H4.\n        {\n        destruct b3.\n        - assert (exists n m t', fstar n (t_app f' (t_app f0 p)) (l' ->>> 0 :: l0 ->>> 0 :: rs0) t' /\\ fstar m (t_app (pmap_compose f' f0) p) (l' ->>> 0 :: l0 ->>> 0 :: rs0) t').\n          {\n            apply pmap_compose_comm.\n            - inv WT; dtr. inv H1. wtbdist. inv H3. inv H15. inv H7. inv H15. eauto.\n            - inv WT; dtr. inv H1. wtbdist. inv H3. inv H15. inv H7. inv H9. eauto.\n            - inv WT; dtr. inv H1. wtbdist. inv H3. inv H15. inv H7. inv H15. eauto.\n            - inv WT; dtr. inv H1. wtbdist. inv H3. inv H15. inv H7. inv H9. eauto.\n            - apply to_value.\n          }\n          dtr. rename H into star1. rename H0 into star2.\n          assert (Hnot' : not_fold_or_done (pmap f' (remove Nat.eq_dec k0 ks0))) by eauto.\n          got.\n          + instantiate (1:=C (b0 ++ [<< N k0 x1 e; os2 >>]) os0 (l' ->>> final _ :: l0 ->>> 0 :: rs0) term1).\n            apply ex_intro with (3 + x).\n            eapply Step.\n            instantiate (1:=C (b0 ++ [<< N k0 (t_app f0 p) e; l' ->> pmap f' ks0 :: os2 >>]) os0 (l0 ->>> _ :: rs0) term1).\n            eapply S_Last; crush.\n            apply List.remove_In in H. assumption.\n            eapply Step.\n            instantiate (1:=C (b0 ++ [<< N k0 (t_app f' (t_app f0 p)) e; l' ->> pmap f' (remove Nat.eq_dec k0 ks0) :: os2 >>]) os0 (l0 ->>> final _ :: rs0) term1).\n            eapply S_PMap; crush.\n            instantiate (1:=Hnot); crush.\n            eapply Step.\n            eapply S_Last with (b:=b0 ++ [<< N k0 (t_app f' (t_app f0 p)) e; l' ->> pmap f' (remove Nat.eq_dec k0 ks0) :: os2 >>]); eauto.\n            crush.\n            apply List.remove_In in H. assumption.\n            apply fstar_into_star_load with (b1:=b0) (k:=k0) (b2:=[]) (es:=e) (os:=os2) (os0:=os0) (rs:=l' ->>> 0 :: l0 ->>> 0 :: rs0) (t0:=term1) in star1.\n            simpl. instantiate (1:=Hnot'). simpl. auto.\n          + instantiate (1:=C (b0 ++ [<< N k0 x1 e; os2 >>]) os0 (l' ->>> final _ :: l0 ->>> 0 :: rs0) term1).\n            apply ex_intro with (2 + x0).\n            eapply Step.\n            eapply S_PMap; crush.\n            eapply Step.\n            eapply S_Last with (op:=pmap (pmap_compose f' f0) (remove Nat.eq_dec k0 ks0)); crush.\n            apply List.remove_In in H. assumption.\n            apply fstar_into_star_load with (b1:=b0) (k:=k0) (b2:=[]) (es:=e) (os:=os2) (os0:=os0) (rs:=l' ->>> 0 :: l0 ->>> 0 :: rs0) (t0:=term1) in star2.\n            simpl. instantiate (1:=Hnot'). simpl. auto.\n          + crush.\n        - destruct s.\n          assert (exists n m t', fstar n (t_app f' (t_app f0 p)) (l0 ->>> 0 :: rs0) t' /\\ fstar m (t_app (pmap_compose f' f0) p) (l0 ->>> 0 :: rs0) t').\n          {\n            apply pmap_compose_comm.\n            - inv WT; dtr. inv H1. wtbdist. inv H3. inv H15. inv H7. inv H15. eauto.\n            - inv WT; dtr. inv H1. wtbdist. inv H3. inv H15. inv H7. inv H9. eauto.\n            - inv WT; dtr. inv H1. wtbdist. inv H3. inv H15. inv H7. inv H15. eauto.\n            - inv WT; dtr. inv H1. wtbdist. inv H3. inv H15. inv H7. inv H9. eauto.\n            - apply to_value.\n          }\n          dtr. rename H into star1. rename H0 into star2.\n          assert (Hnot' : not_fold_or_done (pmap f' (remove Nat.eq_dec k0 ks0))) by eauto.\n          got.\n          + instantiate (1:=C (b0 ++ << N k0 x1 e; os2 >> :: << n; l ++ [l' ->> pmap (pmap_compose f' f0) (remove Nat.eq_dec k0 ks0)] >> :: b3) os0 (l0 ->>> final _ :: rs0) term1).\n            apply ex_intro with (4+x).\n            eapply Step.\n            instantiate (1:=C (b0 ++ << N k0 (t_app f0 p) e; l' ->> pmap f' ks0 :: os2 >> :: << n; l ++ [l0 ->> pmap f0 (remove Nat.eq_dec k0 ks0)] >> :: b3) os0 rs0 term1).\n            eapply S_Prop; crush.\n            apply List.remove_In in H. assumption.\n            eapply Step.\n            instantiate (1:=C (b0 ++ << N k0 (t_app f' (t_app f0 p)) e; l' ->> pmap f' (remove Nat.eq_dec k0 ks0) :: os2 >> :: << n; l ++ [l0 ->> pmap f0 (remove Nat.eq_dec k0 ks0)] >> :: b3) os0 rs0 term1).\n            eapply S_PMap; crush.\n            eapply Step.\n            instantiate (1:=C (b0 ++ << N k0 (t_app f' (t_app f0 p)) e; os2 >> :: << n; (l ++ [l0 ->> pmap f0 (remove Nat.eq_dec k0 ks0)]) ++ [l' ->> pmap f' (remove Nat.eq_dec k0 ks0)] >> :: b3) os0 rs0 term1).\n            eapply S_Prop; crush.\n            apply List.remove_In in H. assumption.\n            eapply Step.\n            assert (b0 ++ << N k0 (t_app f' (t_app f0 p)) e; os2 >> :: << n; (l ++ [l0 ->> pmap f0 (remove Nat.eq_dec k0 ks0)]) ++ [l' ->> pmap f' (remove Nat.eq_dec k0 ks0)] >> :: b3 = (b0 ++ [<< N k0 (t_app f' (t_app f0 p)) e; os2 >>]) ++ << n; l ++ l0 ->> pmap f0 (remove Nat.eq_dec k0 ks0) :: l' ->> pmap f' (remove Nat.eq_dec k0 ks0) :: [] >> :: b3) by crush.\n            rewrite H.\n            eapply S_FusePMap; crush.\n            apply fstar_into_star_load with (b1:=b0) (k:=k0) (b2:=<< n; l ++ [l' ->> pmap (pmap_compose f' f0) (remove Nat.eq_dec k0 ks0)] >> :: b3) (es:=e) (os:=os2) (os0:=os0) (rs:=l0 ->>> 0 :: rs0) (t0:=term1) in star1.\n            simpl. instantiate (1:=Hnot'). simpl. crush.\n          + instantiate (1:=C (b0 ++ << N k0 x1 e; os2 >> :: << n; l ++ [l' ->> pmap (pmap_compose f' f0) (remove Nat.eq_dec k0 ks0)] >> :: b3) os0 (l0 ->>> 0 :: rs0) term1).\n            apply ex_intro with (2 + x0).\n            eapply Step.\n            instantiate (1:=C (b0 ++ << N k0 (t_app (pmap_compose f' f0) p) e; l' ->> pmap (pmap_compose f' f0) (remove Nat.eq_dec k0 ks0) :: os2 >> :: << n; l >> :: b3) os0 (l0 ->>> 0 :: rs0) term1).\n            eapply S_PMap; crush.\n            eapply Step.\n            instantiate (1:=C (b0 ++ << N k0 (t_app (pmap_compose f' f0) p) e; os2 >> :: << n; l  ++ [l' ->> pmap (pmap_compose f' f0) (remove Nat.eq_dec k0 ks0)] >> :: b3) os0 (l0 ->>> 0 :: rs0) term1).\n            eapply S_Prop; eauto. crush. apply List.remove_In in H. assumption.\n            apply fstar_into_star_load with (b1:=b0) (k:=k0) (b2:=<< n; l ++ [l' ->> pmap (pmap_compose f' f0) (remove Nat.eq_dec k0 ks0)] >> :: b3) (es:=e) (os:=os2) (os0:=os0) (rs:=l0 ->>> 0 :: rs0) (t0:=term1) in star2.\n            auto.\n          + crush.\n        }\n      * inv H4.\n        {\n          got.\n          * instantiate (1:= C (b0 ++ << N k0 (t_app f p) e; (l ->> pmap f (remove Nat.eq_dec k0 ks) :: os1) ++ l' ->> pmap (pmap_compose f' f0) ks0 :: os2 >> :: b3) os0 (l0 ->>> final _ :: rs0) term1).\n            one_step. eapply S_FusePMap; crush.\n          * instantiate (1:= C (b0 ++ << N k0 (t_app f p) e; l ->> pmap f (remove Nat.eq_dec k0 ks) :: os1 ++ l' ->> pmap (pmap_compose f' f0) ks0 :: os2 >> :: b3) os0 (l0 ->>> 0 :: rs0) term1).\n            one_step. eapply S_PMap; crush.\n          * crush.\n        }\n    (* First first *)\n    + destruct H0. destruct H0. destruct H0.\n      eapply target_unique with (b1:=b1) (b2:=b2) (b3:=x) (b4:=x0 ++ << N k0 p e; os1 ++ l0 ->> pmap f0 ks0 :: l' ->> pmap f' ks0 :: os2 >> :: x1) in H0; crush.\n      inv H.\n      eapply target_unique with (b1:=x ++ << N k v es; l ->> pmap f ks :: os1'' >> :: x0) (b2:=x1) (b3:=b0) (b4:=b3) in H1; eauto; crush.\n      got.\n      * instantiate (1:=C ((x ++ << N k (t_app f v) es; l ->> pmap f (remove Nat.eq_dec k ks) :: os1'' >> :: x0) ++ << N k0 p e; os1 ++ l' ->> pmap (pmap_compose f' f0) ks0 :: os2 >> :: b3) os0 (l0 ->>> 0 :: rs0) term1).\n        one_step. eapply S_FusePMap; crush.\n      * instantiate (1:=C (x ++ << N k (t_app f v) es; l ->> pmap f (remove Nat.eq_dec k ks) :: os1'' >> :: x0 ++ << N k0 p e; os1 ++ l' ->> pmap (pmap_compose f' f0) ks0 :: os2 >> :: b3) os0 (l0 ->>> 0 :: rs0) term1).\n        one_step. eapply S_PMap; crush.\n      * crush.\n    (* First second *)\n    + destruct H0. destruct H0. destruct H0.\n      eapply target_unique with (b1:=b1) (b2:=b2) (b3:=x ++ << N k0 p e; os1 ++ l0 ->> pmap f0 ks0 :: l' ->> pmap f' ks0 :: os2 >> :: x0) (b4:=x1) in H0; eauto; crush.\n      inv H.\n      eapply target_unique with (b1:=x) (b2:=x0 ++ << N k v es; l ->> pmap f ks :: os1'' >> :: x1) (b3:=b0) (b4:=b3) in H1; eauto; crush.\n      got.\n      * instantiate (1:=C (b0 ++ << N k0 p e; os1 ++ l' ->> pmap (pmap_compose f' f0) ks0 :: os2 >> :: x0 ++ << N k (t_app f v) es; l ->> pmap f (remove Nat.eq_dec k ks) :: os1'' >> :: x1) os0 (l0 ->>> 0 :: rs0) term1).\n        one_step. eapply S_FusePMap; crush.\n      * instantiate (1:=C ((b0 ++ << N k0 p e; os1 ++ l' ->> pmap (pmap_compose f' f0) ks0 :: os2 >> :: x0) ++ << N k (t_app f v) es; l ->> pmap f (remove Nat.eq_dec k ks) :: os1'' >> :: x1) os0 (l0 ->>> 0 :: rs0) term1).\n        one_step. eapply S_PMap; crush.\n      * crush.\n  (* S_SwapReads *)\n  - destruct n as [k' v'].\n    tsod'.\n    + destruct os1; simpl in *; inv Hsame5.\n      inv H. apply List.app_inv_head in H3. inv H3.\n      got.\n      * instantiate (1:=C (b0 ++ << N k' (t_app f v') e; (l ->> pmap f (remove Nat.eq_dec k' ks) :: os1) ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f0 t ks0 :: os2 >> :: b3) os0 rs0 term1).\n        one_step; eapply S_SwapReads; eauto.\n      * instantiate (1:=C (b0 ++ << N k' (t_app f v') e; l ->> pmap f (remove Nat.eq_dec k' ks) :: os1 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f0 t ks0 :: os2 >> :: b3) os0 rs0 term1).\n        one_step; eauto.\n      * crush.\n    + destruct Hfirst as [b' [b'' [b''']]].\n      destruct b''; simpl in *.\n      * eapply target_unique with (b1:=b1) (b2:=b2) (b3:=b') (b4:=<< N k' v' e; os1 ++ l0 ->> pfold f0 t ks0 :: l' ->> pfold f' t' ks' :: os2 >> :: b''') in H0; eauto; crush.\n        inv H.\n        eapply target_unique with (b1:=b' ++ [<< N k v es; l ->> pmap f ks :: os1'' >>]) (b2:=b''') (b3:=b0) (b4:=b3) in H3; eauto; crush.\n        got.\n        { instantiate (1:=C ((b' ++ [<< N k (t_app f v) es; l ->> pmap f (remove Nat.eq_dec k ks) :: os1'' >>]) ++ << N k' v' e; os1 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f0 t ks0 :: os2 >> :: b3) os0 rs0 term1).\n          one_step. eapply S_SwapReads; eauto; crush. }\n        { instantiate (1:=C (b' ++ << N k (t_app f v) es; l ->> pmap f (remove Nat.eq_dec k ks) :: os1'' >> :: << N k' v' e; os1 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f0 t ks0 :: os2 >> :: b3) os0 rs0 term1).\n          one_step. eapply S_PMap; eauto; crush. }\n        { crush. }\n      * eapply target_unique with (b1:=b1) (b2:=b2) (b3:=b') (b4:=s :: b'' ++ << N k' v' e; os1 ++ l0 ->> pfold f0 t ks0 :: l' ->> pfold f' t' ks' :: os2 >> :: b''') in H0; eauto; crush.\n        inv H.\n        eapply target_unique with (b1:=b' ++ << N k v es; l ->> pmap f ks :: os1'' >> :: s :: b'') (b2:=b''') (b3:=b0) (b4:=b3) in H3; eauto; crush.\n        got.\n        { instantiate (1:=C ((b' ++ << N k (t_app f v) es; l ->> pmap f (remove Nat.eq_dec k ks) :: os1'' >> :: s :: b'') ++ << N k' v' e; os1 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f0 t ks0 :: os2 >> :: b3) os0 rs0 term1).\n          one_step. eapply S_SwapReads; eauto; crush. }\n        { instantiate (1:=C (b' ++ << N k (t_app f v) es; l ->> pmap f (remove Nat.eq_dec k ks) :: os1'' >> :: s :: b'' ++ << N k' v' e; os1 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f0 t ks0 :: os2 >> :: b3) os0 rs0 term1).\n          one_step. eapply S_PMap; eauto; crush. }\n        { crush. }\n    + destruct Hsecond as [b' [b'' [b''']]].\n      tu2.\n      got.\n      * instantiate (1:=C (b0 ++ << N k' v' e; os1 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f0 t ks0 :: os2 >> :: b'' ++ << N k (t_app f v) es; l ->> pmap f (remove Nat.eq_dec k ks) :: os1'' >> :: b''') os0 rs0 term1).\n        eauto.\n      * instantiate (1:=C ((b0 ++ << N k' v' e; os1 ++ l' ->> pfold f' t' ks' :: l0 ->> pfold f0 t ks0 :: os2 >> :: b'') ++ << N k (t_app f v) es; l ->> pmap f (remove Nat.eq_dec k ks) :: os1'' >> :: b''') os0 rs0 term1).\n        one_step; eapply S_PMap; eauto; crush.\n      * crush.\nUnshelve.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nQed.\nHint Resolve lc_pmap.\n\nAxiom functional_extension : forall f f' rs t,\n  (exists n m t', fstar n (t_app f t) rs t' /\\ fstar m (t_app f' t) rs t') ->\n  f = f'.\n\nLemma pmap_compose_assoc_apply : forall f f' f'' rs t,\n  (exists T1 T2 ll, has_type empty ll f (Arrow T1 T2 false) false) ->\n  (exists T1 T2 ll, has_type empty ll f' (Arrow T1 T2 false) false) ->\n  (exists T1 T2 ll, has_type empty ll f'' (Arrow T1 T2 false) false) ->\n  value f ->\n  value f' ->\n  value f'' ->\n  value t ->\n  (exists n v, fstar n (t_app f'' t) rs v /\\ value v) ->\n  exists n m t', fstar n (t_app (pmap_compose f (pmap_compose f' f'')) t) rs t' /\\ fstar m (t_app (pmap_compose (pmap_compose f f') f'') t) rs t'.\nProof using.\n  unfold pmap_compose; intros. destruct H6 as [n[v]]. destruct H6.\n  exists (S (S n)), (S (S n)), (t_app f (t_app f' v)).\n  split.\n  - eapply FStep.\n    eapply F_App; auto.\n    rewrite rewrite_e_subst.\n    replace (#[\"x\":=t]f) with f.\n    rewrite rewrite_e_subst.\n    simpl.\n    eapply FStep.\n    eapply F_App2; auto.\n    rewrite rewrite_e_subst.\n    replace (#[\"x\":=t]f') with f'.\n    rewrite rewrite_e_subst.\n    replace (#[\"x\":=t]f'') with f''.\n    simpl.\n    apply fstar_app2; auto.\n    apply fstar_app2; auto.\n    assert (~ (appears_free_in \"x\" f'')) by (dtr; eapply typable_empty__closed; eauto).\n    eapply not_afi_subst in H8; eauto.\n    assert (~ (appears_free_in \"x\" f')) by (dtr; eapply typable_empty__closed; eauto).\n    eapply not_afi_subst in H8; eauto.\n    assert (~ (appears_free_in \"x\" f)) by (dtr; eapply typable_empty__closed; eauto).\n    eapply not_afi_subst in H8; eauto.\n  - eapply FStep.\n    eapply F_App; auto.\n    rewrite rewrite_e_subst.\n    rewrite rewrite_e_subst.\n    replace (#[\"x\":=t]f'') with f''.\n    simpl.\n    replace (S n) with (n + 1).\n    eapply fstar_trans.\n    apply fstar_app2; auto. instantiate (1:=v). auto.\n    eapply FStep. eapply F_App; auto.\n    simpl.\n    replace (#[\"x\":=v]f) with f.\n    replace (#[\"x\":=v]f') with f'.\n    auto.\n    assert (~ (appears_free_in \"x\" f')) by (dtr; eapply typable_empty__closed; eauto).\n    eapply not_afi_subst in H8; eauto.\n    assert (~ (appears_free_in \"x\" f)) by (dtr; eapply typable_empty__closed; eauto).\n    eapply not_afi_subst in H8; eauto.\n    crush.\n    assert (~ (appears_free_in \"x\" f'')) by (dtr; eapply typable_empty__closed; eauto).\n    eapply not_afi_subst in H8; eauto.\nQed.\n\nLemma pmap_compose_assoc : forall f f' f'' (rs:rstream),\n  (exists ll, has_type empty ll f (Arrow Result Result false) false) ->\n  (exists ll, has_type empty ll f' (Arrow Result Result false) false) ->\n  (exists ll, has_type empty ll f'' (Arrow Result Result false) false) ->\n  value f ->\n  value f' ->\n  value f'' ->\n  pmap_compose f (pmap_compose f' f'') = pmap_compose (pmap_compose f f') f''.\nProof using.\n  intros.\n  eapply functional_extension.\n  apply pmap_compose_assoc_apply; eauto.\n  instantiate (1:=rs). apply to_value.\nQed.\n\nLemma lc_fusepmap :\n  forall cx cy cz n b1 b2 os os1 os2 rs term0 f f' ks l l' H,\n  well_typed cx ->\n  cx = C (b1 ++ << n; os1 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os2 >> :: b2) os rs term0 ->\n  cy = C (b1 ++ << n; os1 ++ l' ->> pmap (pmap_compose f' f) ks :: os2 >> :: b2) os (l ->>> (@final (pmap f ks)) H :: rs) term0 ->\n  cx --> cy ->\n  cx --> cz ->\n  cy -v cz.\nProof using.\n  intros cx cy cz n b1 b2 os os1 os2 rs term0 f f' ks l l' Hnot WT Heqcx Heqcy cxcy cxcz.\n  remember (b1 ++ << n; os1 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os2 >> :: b2) as b.\n  rename Heqb into H0.\n  assert (H : cx = C b os rs term0) by assumption.\n  remember cx as c.\n  rename Heqc into H1.\n  assert (H2 : C (b1 ++ << n; os1 ++ l' ->> pmap (pmap_compose f' f) ks :: os2 >> :: b2) os (l ->>> final Hnot :: rs) term0 = cy) by auto.\n  inversion cxcz; ssame; try solve [subst; eauto].\n  (* S_Empty *)\n  - destruct b1; crush.\n  (* S_Add *)\n  - ssame.\n    got.\n    * instantiate (1:=C (<< N k v t_ks_nil; [] >> :: b1 ++ << n; os1 ++ l' ->> pmap (pmap_compose f' f) ks :: os2 >> :: b2) os' (l0 ->>> final _ :: l ->>> final Hnot :: rs0) term1).\n      one_step. eapply S_Add; crush.\n    * instantiate (1:=C (<< N k v t_ks_nil; [] >> :: b1 ++ << n; os1 ++ l' ->> pmap (pmap_compose f' f) ks :: os2 >> :: b2) os' (l ->>> final _ :: l0 ->>> k :: rs0) term1).\n      one_step. apply S_FusePMap with (b:=<< N k v t_ks_nil; [] >> :: b1 ++ << n; os1 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os2 >> :: b2) (b1:=<< N k v t_ks_nil; [] >> :: b1); crush.\n    * crush.\n  (* S_Last *)\n  -\n    {\n    rename b1 into btmp.\n    rename b3 into b1.\n    rename b2 into b3.\n    rename btmp into b2.\n    rename os2 into os3.\n    rename os1 into os2.\n    destruct b3.\n    rename H3 into Hnot'.\n    rename H4 into H3.\n    (* b3 = [] *)\n    - apply List.app_inj_tail in H1. destruct H1. inv H1.\n      destruct os2.\n      (* os2 = [] *)\n      + simpl in *.\n        inv H6.\n        got.\n        * instantiate (1:=C (b1 ++ [<< n1; os3 >>]) os0 (l' ->>> final _ :: l0 ->>> 0 :: rs0) term1).\n          one_step. eapply S_Last; crush.\n        * instantiate (1:=C (b1 ++ [<< n1; os3 >>]) os0 (l' ->>> final _ :: l0 ->>> 0 :: rs0) term1).\n          one_step. eapply S_Last; crush.\n        * crush.\n      (* os2 != [] *)\n      + inv H6.\n        got.\n        * instantiate (1:=C (b1 ++ [<< n1; os2 ++ l' ->> pmap (pmap_compose f' f) ks :: os3 >>]) os0 (l0 ->>> final Hnot' :: l ->>> final Hnot :: rs0) term1).\n          one_step. eapply S_Last; crush.\n        * instantiate (1:=C (b1 ++ [<< n1; os2 ++ l' ->> pmap (pmap_compose f' f) ks :: os3 >>]) os0 (l ->>> final Hnot :: l0 ->>> final Hnot' :: rs0) term1).\n          one_step. eapply S_FusePMap; crush.\n        * crush.\n    (* b3 != [] *)\n    - remember (s :: b3) as bend.\n      assert (exists y ys, bend = ys ++ [y]) by (apply list_snoc with (xs:=bend) (x:=s) (xs':=b3); crush).\n      destruct H0; destruct H0.\n      inv H0.\n      rewrite H5 in *.\n      assert (b2 ++ << n; os2 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os3 >> :: x0 ++ [x] = (b2 ++ << n; os2 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os3 >> :: x0) ++ [x]) by crush.\n      rewrite H0 in H1; clear H0.\n      apply List.app_inj_tail in H1.\n      destruct H1.\n      rewrite -> H1 in *.\n      clear H1.\n      clear x.\n      rewrite <- H0 in *.\n      clear H0.\n      clear b1.\n      got.\n      + instantiate (1:=C ((b2 ++ << n; os2 ++ l' ->> pmap (pmap_compose f' f) ks :: os3 >> :: x0) ++ [<< n1; os1' >>]) os0 (l0 ->>> final H3 :: l ->>> final Hnot :: rs0) term1).\n        one_step. eapply S_Last; crush.\n      + instantiate (1:=C (b2 ++ << n; os2 ++ l' ->> pmap (pmap_compose f' f) ks :: os3 >> :: x0 ++ [<< n1; os1' >>]) os0 (l ->>> final Hnot :: l0 ->>> final H3 :: rs0) term1).\n        assert (forall y, (b2 ++ << n; os2 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os3 >> :: x0) ++ y = b2 ++ << n; os2 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os3 >> :: x0 ++ y) by crush. rewrite H0.\n        one_step. eapply S_FusePMap; crush.\n      + crush.\n    }\n  (* S_FusePMap *)\n  - destruct n as [k v].\n    destruct n0 as [k' v'].\n    rename H3 into Hnot'.\n    rename H4 into H3.\n    {\n    eapply target_same_or_different with (b1:=b1) (b2:=b2) (b3:=b3) (b4:=b4) (k:=k) (v:=v) (k':=k') (v':=v') in H1; eauto.\n    - destruct H1; try destruct H0.\n      (* Same target *)\n      + destruct H1; destruct H4; destruct H5; subst.\n        {\n        eapply op_same_or_different with (os1:=os1) (os2:=l' ->> pmap f' ks :: os2) (lop:=l ->> pmap f ks) (os3:=os3) (os4:=l'0 ->> pmap f'0 ks0 :: os4) (lop':=l0 ->> pmap f0 ks0) in H6; eauto.\n        - destruct H6; destruct H0; try destruct H1.\n          (* Same first lop *)\n          + fsame. inv H1. inv H4. crush.\n          (* First first *)\n          + destruct H0; destruct H0; destruct H0.\n            destruct x0.\n            (* First's second is second's first *)\n            * simpl in *.\n              inv H3. apply List.app_inv_head in H4; inv H4.\n              apply op_unique with (n:=N k' v' e0) (os1:=os1) (os2:=l' ->> pmap f' ks :: os2) (os3:=x) (os4:=l0 ->> pmap f0 ks0 :: x1) (os0:=os0) (rs0:=rs0) (t0:=term1) (b:=b3 ++ << N k' v' e0; os1 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os2 >> :: b4) (b1:=b3) (b2:=b4) (os:=os1 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os2) in H0; crush.\n              inv H2. inv H.\n              inv H3.\n              apply op_unique with (n:=N k' v' e0) (os1:=x ++ [l ->> pmap f ks0]) (os2:=x1) (os3:=os3) (os4:=l'0 ->> pmap f'0 ks0 :: os4) (os0:=os0) (rs0:=rs0) (t0:=term1) (b:=b3 ++ << N k' v' e0; x ++ l ->> pmap f ks0 :: l0 ->> pmap f0 ks0 :: x1 >> :: b4) (b1:=b3) (b2:=b4) (os:=x ++ l ->> pmap f ks0 :: l0 ->> pmap f0 ks0 :: x1) in H5; crush.\n              {\n              got.\n              - instantiate (1:=C (b3 ++ << N k' v' e0; x ++ l'0 ->> pmap (pmap_compose f'0 (pmap_compose f0 f)) ks0 :: os4 >> :: b4) os0 (l0 ->>> final _ :: l ->>> 0 :: rs0) term1).\n                one_step. eapply S_FusePMap; crush.\n              - instantiate (1:=C (b3 ++ << N k' v' e0; x ++ l'0 ->> pmap (pmap_compose (pmap_compose f'0 f0) f) ks0 :: os4 >> :: b4) os0 (l ->>> final _ :: l0 ->>> 0 :: rs0) term1).\n                one_step. eapply S_FusePMap; crush.\n              - rewrite pmap_compose_assoc; eauto.\n                + inv WT; dtr. inv H1. wtbdist. inv H2. wtosdist. inv H3. inv H8. inv H7. inv H17. eauto.\n                + inv WT; dtr. inv H1. wtbdist. inv H2. wtosdist. inv H3. inv H8. inv H16. eauto.\n                + inv WT; dtr. inv H1. wtbdist. inv H2. wtosdist. inv H3. inv H14. eauto.\n                + inv WT; dtr. inv H1. wtbdist. inv H2. wtosdist. inv H3. inv H8. inv H7. inv H17. eauto.\n                + inv WT; dtr. inv H1. wtbdist. inv H2. wtosdist. inv H3. inv H8. inv H16. eauto.\n                + inv WT; dtr. inv H1. wtbdist. inv H2. wtosdist. inv H3. inv H14. eauto.\n              }\n            (* No overlap *)\n            * simpl in *.\n              inv H3. apply List.app_inv_head in H4; inv H.\n              apply op_unique with (n:=N k' v' e0) (os1:=os1) (os2:=l' ->> pmap f' ks :: os2) (os3:=x) (os4:=l1 :: x0 ++ l0 ->> pmap f0 ks0 :: x1) (os0:=os0) (rs0:=rs0) (t0:=term1) (b:=b3 ++ << N k' v' e0; os1 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os2 >> :: b4) (b1:=b3) (b2:=b4) (os:=os1 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os2) in H0; crush.\n              inv H4.\n              apply op_unique with (n:=N k' v' e0) (os1:=x ++ l ->> pmap f ks :: l' ->> pmap f' ks :: x0) (os2:=x1) (os3:=os3) (os4:=l'0 ->> pmap f'0 ks0 :: os4) (os0:=os0) (rs0:=rs0) (t0:=term1) (b:=b3 ++ << N k' v' e0; x ++ l ->> pmap f ks :: l' ->> pmap f' ks :: x0 ++ l0 ->> pmap f0 ks0 :: x1 >> :: b4) (b1:=b3) (b2:=b4) (os:=x ++ l ->> pmap f ks :: l' ->> pmap f' ks :: x0 ++ l0 ->> pmap f0 ks0 :: x1) in H1; crush.\n              {\n              got.\n              - instantiate (1:=C (b3 ++ << N k' v' e0; (x ++ l' ->> pmap (pmap_compose f' f) ks :: x0) ++ l'0 ->> pmap (pmap_compose f'0 f0) ks0 :: os4 >> :: b4) os0 (l0 ->>> final Hnot' :: l ->>> 0 :: rs0) term1).\n                one_step. eapply S_FusePMap; crush.\n              - instantiate (1:=C (b3 ++ << N k' v' e0; x ++ l' ->> pmap (pmap_compose f' f) ks :: x0 ++ l'0 ->> pmap (pmap_compose f'0 f0) ks0 :: os4 >> :: b4) os0 (l ->>> final _ :: l0 ->>> 0 :: rs0) term1).\n                one_step. eapply S_FusePMap; crush.\n              - crush.\n              }\n          (* First second *)\n          + destruct H0; destruct H0; destruct H0.\n            inv H3. apply List.app_inv_head in H4; inv H4.\n            destruct x0.\n            (* First's second is second's first *)\n            * simpl in *.\n              eapply op_unique with (n:=N k' v' e0) (os1:=os1) (os2:=l' ->> pmap f' ks :: os2) (os3:=x ++ [l0 ->> pmap f0 ks0]) (os4:=x1) (os0:=os0) (rs0:=rs0) (t0:=term1) (b:=b3 ++ << N k' v' e0; os1 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os2 >> :: b4) (b1:=b3) (b2:=b4) (os:=os1 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os2) in H0; crush.\n              inv H2.\n              apply op_unique with (n:=N k' v' e0) (os1:=x) (os2:=l ->> pmap f ks :: l' ->> pmap f' ks :: os2) (os3:=os3) (os4:=l'0 ->> pmap f'0 ks0 :: os4) (os0:=os0) (rs0:=rs0) (t0:=term1) (b:=b3 ++ << N k' v' e0; x ++ l0 ->> pmap f0 ks0 :: l ->> pmap f ks :: l' ->> pmap f' ks :: os2 >> :: b4) (b1:=b3) (b2:=b4) (os:=x ++ l0 ->> pmap f0 ks0 :: l ->> pmap f ks :: l' ->> pmap f' ks :: os2) in H5; crush.\n              inv H1.\n              {\n              got.\n              - instantiate (1:=C (b3 ++ << N k' v' e0; os3 ++ l' ->> pmap (pmap_compose (pmap_compose f' f'0) f0) ks0 :: os2 >> :: b4) os0 (l0 ->>> final _ :: l'0 ->>> 0 :: rs0) term1).\n                one_step. eapply S_FusePMap; crush.\n              - instantiate (1:=C (b3 ++ << N k' v' e0; os3 ++ l' ->> pmap (pmap_compose f' (pmap_compose f'0 f0)) ks0 :: os2 >> :: b4) os0 (l'0 ->>> final _ :: l0 ->>> 0 :: rs0) term1).\n                one_step. eapply S_FusePMap; crush.\n              - rewrite pmap_compose_assoc; eauto.\n                + inv WT; dtr. inv H2. wtbdist. inv H3. wtosdist. inv H4. inv H9. inv H8. inv H18. eauto.\n                + inv WT; dtr. inv H2. wtbdist. inv H3. wtosdist. inv H4. inv H9. inv H17. eauto.\n                + inv WT; dtr. inv H2. wtbdist. inv H3. wtosdist. inv H4. inv H15. eauto.\n                + inv WT; dtr. inv H2. wtbdist. inv H3. wtosdist. inv H4. inv H9. inv H8. inv H18. eauto.\n                + inv WT; dtr. inv H2. wtbdist. inv H3. wtosdist. inv H4. inv H9. inv H17. eauto.\n                + inv WT; dtr. inv H2. wtbdist. inv H3. wtosdist. inv H4. inv H15. eauto.\n              }\n            (* No overlap *)\n            * simpl in *.\n              eapply op_unique with (n:=N k' v' e0) (os1:=os1) (os2:=l' ->> pmap f' ks :: os2) (os3:=x ++ l0 ->> pmap f0 ks0 :: l1 :: x0) (os4:=x1) (os0:=os0) (rs0:=rs0) (t0:=term1) (b:=b3 ++ << N k' v' e0; os1 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os2 >> :: b4) (b1:=b3) (b2:=b4) (os:=os1 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os2) in H0; crush.\n              inv H2.\n              apply op_unique with (n:=N k' v' e0) (os1:=x) (os2:=l1 :: x0 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os2) (os3:=os3) (os4:=l'0 ->> pmap f'0 ks0 :: os4) (os0:=os0) (rs0:=rs0) (t0:=term1) (b:=b3 ++ << N k' v' e0; x ++ l0 ->> pmap f0 ks0 :: l1 :: x0 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os2 >> :: b4) (b1:=b3) (b2:=b4) (os:=x ++ l0 ->> pmap f0 ks0 :: l1 :: x0 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os2) in H5; crush.\n              {\n              got.\n              - instantiate (1:=C (b3 ++ << N k' v' e0; os3 ++ l'0 ->> pmap (pmap_compose f'0 f0) ks0 :: x0 ++ l' ->> pmap (pmap_compose f' f) ks :: os2 >> :: b4) os0 (l0 ->>> final _ :: l ->>> 0 :: rs0) term1).\n                one_step. eapply S_FusePMap; crush.\n              - instantiate (1:=C (b3 ++ << N k' v' e0; (os3 ++ l'0 ->> pmap (pmap_compose f'0 f0) ks0 :: x0) ++ l' ->> pmap (pmap_compose f' f) ks :: os2 >> :: b4) os0 (l ->>> final Hnot :: l0 ->>> 0 :: rs0) term1).\n                one_step. eapply S_FusePMap; crush.\n              - crush.\n              }\n        }\n      (* First first *)\n      + destruct H0; destruct H0; destruct H0.\n        apply target_unique with (os:=os1 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os2) (k:=k) (v:=v) (b1:=b1) (b2:=b2) (b3:=x) (b4:=x0 ++ << N k' v' e0; os3 ++ l0 ->> pmap f0 ks0 :: l'0 ->> pmap f'0 ks0 :: os4 >> :: x1) (os0:=os0) (rs0:=rs0) (t0:=term1) (b:=b1 ++ << N k v e; os1 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os2 >> :: b2) in H0; crush.\n        inv H3.\n        apply target_unique with (os:=os3 ++ l0 ->> pmap f0 ks0 :: l'0 ->> pmap f'0 ks0 :: os4) (k:=k') (v:=v') (b1:=x ++ << N k v e; os1 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os2 >> :: x0) (b2:=x1) (b3:=b3) (b4:=b4) (os0:=os0) (rs0:=rs0) (t0:=term1) (b:=x ++ << N k v e; os1 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os2 >> :: x0 ++ << N k' v' e0; os3 ++ l0 ->> pmap f0 ks0 :: l'0 ->> pmap f'0 ks0 :: os4 >> :: x1) in H1; crush.\n        got.\n        * instantiate (1:=C ((x ++ << N k v e; os1 ++ l' ->> pmap (pmap_compose f' f) ks :: os2 >> :: x0) ++ << N k' v' e0; os3 ++ l'0 ->> pmap (pmap_compose f'0 f0) ks0 :: os4 >> :: b4) os0 (l0 ->>> 0 :: l ->>> 0 :: rs0) term1).\n          one_step. eapply S_FusePMap; crush.\n        * instantiate (1:=C (x ++ << N k v e; os1 ++ l' ->> pmap (pmap_compose f' f) ks :: os2 >> :: x0 ++ << N k' v' e0; os3 ++ l'0 ->> pmap (pmap_compose f'0 f0) ks0 :: os4 >> :: b4) os0 (l ->>> 0 :: l0 ->>> 0 :: rs0) term1).\n          one_step. eapply S_FusePMap; crush.\n        * crush.\n      (* First second *)\n      + destruct H0; destruct H0; destruct H0.\n        apply target_unique with (es:=e) (os:=os1 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os2) (k:=k) (v:=v) (b1:=b1) (b2:=b2) (b3:=x ++ << N k' v' e0; os3 ++ l0 ->> pmap f0 ks0 :: l'0 ->> pmap f'0 ks0 :: os4 >> :: x0) (b4:=x1) (os0:=os0) (rs0:=rs0) (t0:=term1) (b:=b1 ++ << N k v e; os1 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os2 >> :: b2) in H0; crush.\n        inv H3.\n        apply target_unique with (os:=os3 ++ l0 ->> pmap f0 ks0 :: l'0 ->> pmap f'0 ks0 :: os4) (k:=k') (v:=v') (b1:=x) (b2:=x0 ++ << N k v e; os1 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os2 >> :: x1) (b3:=b3) (b4:=b4) (os0:=os0) (rs0:=rs0) (t0:=term1) (b:=x ++ << N k' v' e0; os3 ++ l0 ->> pmap f0 ks0 :: l'0 ->> pmap f'0 ks0 :: os4 >> :: x0 ++ << N k v e; os1 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os2 >> :: x1) in H1; crush.\n        got.\n        * instantiate (1:=C (b3 ++ << N k' v' e0; os3 ++ l'0 ->> pmap (pmap_compose f'0 f0) ks0 :: os4 >> :: x0 ++ << N k v e; os1 ++ l' ->> pmap (pmap_compose f' f) ks :: os2 >> :: x1) os0 (l0 ->>> 0 :: l ->>> 0 :: rs0) term1).\n          one_step. eapply S_FusePMap; crush.\n        * instantiate (1:=C ((b3 ++ << N k' v' e0; os3 ++ l'0 ->> pmap (pmap_compose f'0 f0) ks0 :: os4 >> :: x0) ++ << N k v e; os1 ++ l' ->> pmap (pmap_compose f' f) ks :: os2 >> :: x1) os0 (l ->>> 0 :: l0 ->>> 0 :: rs0) term1).\n          one_step. eapply S_FusePMap; crush.\n        * crush.\n    }\n  (* S_SwapReads *)\n  - destruct n as [k v].\n    destruct n0 as [k' v'].\n    tsod'''.\n    + osod.\n      * dtr; inv H1.\n      * destruct Hfirst as [os''0 [os'' [os''']]].\n        inv H3. apply List.app_inv_head in H4. inv H4.\n        {\n        destruct os''.\n        - simpl in *.\n          eapply op_unique with (n:=N k' v' e0) (os1:=os1) (os2:=l' ->> pmap f' ks :: os2) (os3:=os''0) (os4:=l0 ->> pfold f0 t ks0 :: os''') (os0:=os0) (rs0:=rs0) (t0:=term1) in H0; crush.\n        - simpl in *.\n          eapply op_unique with (n:=N k' v' e0) (os1:=os1) (os2:=l' ->> pmap f' ks :: os2) (os3:=os''0) (os4:=l1 :: os'' ++ l0 ->> pfold f0 t ks0 :: os''') (os0:=os0) (rs0:=rs0) (t0:=term1) in H0; crush.\n          inv H. inv H2.\n          eapply op_unique with (n:=N k' v' e0) (os1:=os''0 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os'') (os2:=os''') (os3:=os3) (os4:=l'0 ->> pfold f'0 t' ks' :: os4) (os0:=os0) (rs0:=rs0) (t0:=term1) (b1:=b3) (b2:=b4) in H7; auto; crush.\n          got.\n          + instantiate (1:=C (b3 ++ << N k' v' e0; (os''0 ++ l' ->> pmap (pmap_compose f' f) ks :: os'') ++ l'0 ->> pfold f'0 t' ks' :: l0 ->> pfold f0 t ks0 :: os4 >> :: b4) os0 (l ->>> 0 :: rs0) term1).\n            one_step; eapply S_SwapReads; eauto; crush.\n          + instantiate (1:=C (b3 ++ << N k' v' e0; os''0 ++ l' ->> pmap (pmap_compose f' f) ks :: os'' ++ l'0 ->> pfold f'0 t' ks' :: l0 ->> pfold f0 t ks0 :: os4 >> :: b4) os0 (l ->>> 0 :: rs0) term1).\n            one_step; eapply S_FusePMap; eauto; crush.\n          + crush.\n        }\n      * destruct Hsecond as [os''0 [os'' [os''']]].\n        ou2. destruct os''; inv H1.\n        inv H2. inv H. simpl in *.\n        got.\n        { instantiate (1:=C (b3 ++ << N k' v' e0; os3 ++ l'0 ->> pfold f'0 t' ks' :: l0 ->> pfold f0 t ks0 :: os'' ++ l' ->> pmap (pmap_compose f' f) ks :: os2 >> :: b4) os0 (l ->>> 0 :: rs0) term1).\n          one_step; eapply S_SwapReads; eauto. }\n        { instantiate (1:=C (b3 ++ << N k' v' e0; (os3 ++ l'0 ->> pfold f'0 t' ks' :: l0 ->> pfold f0 t ks0 :: os'') ++ l' ->> pmap (pmap_compose f' f) ks :: os2 >> :: b4) os0 (l ->>> 0 :: rs0) term1).\n          one_step; eapply S_FusePMap; eauto; crush. }\n        { crush. }\n    + destruct Hfirst as [b' [b'' [b''']]].\n      eapply target_unique with (b1:=b1) (b2:=b2) (b3:=b') (b4:=b'' ++ << N k' v' e0; os3 ++ l0 ->> pfold f0 t ks0 :: l'0 ->> pfold f'0 t' ks' :: os4 >> :: b''') in H0; eauto; dtr; subst.\n      inv H2. inv H3. inv H.\n      eapply target_unique with (b1:=b' ++ << N k v e; os1 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os2 >> :: b'') (b2:=b''') (b3:=b3) (b4:=b4) in H1; eauto; [|crush]; dtr; subst.\n      got.\n      * instantiate (1:=C ((b' ++ << N k v e; os1 ++ l' ->> pmap (pmap_compose f' f) ks :: os2 >> :: b'') ++ << N k' v' e0; os3 ++ l'0 ->> pfold f'0 t' ks' :: l0 ->> pfold f0 t ks0 :: os4 >> :: b4) os0 (l ->>> final Hnot :: rs0) term1).\n        one_step; eapply S_SwapReads; eauto; crush.\n      * instantiate (1:=C (b' ++ << N k v e; os1 ++ l' ->> pmap (pmap_compose f' f) ks :: os2 >> :: b'' ++ << N k' v' e0; os3 ++ l'0 ->> pfold f'0 t' ks' :: l0 ->> pfold f0 t ks0 :: os4 >> :: b4) os0 (l ->>> final Hnot :: rs0) term1).\n        one_step; eapply S_FusePMap; eauto; crush.\n      * crush.\n    + destruct Hsecond as [b' [b'' [b''']]].\n      eapply target_unique with (b1:=b1) (b2:=b2) (b3:=b' ++ << N k' v' e0; os3 ++ l0 ->> pfold f0 t ks0 :: l'0 ->> pfold f'0 t' ks' :: os4 >> :: b'') (b4:=b''') in H0; eauto; crush.\n      inv H3. inv H2. inv H.\n      eapply target_unique with (b1:=b') (b2:=b'' ++ << N k v e; os1 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os2 >> :: b''') (b3:=b3) (b4:=b4) in H1; eauto; crush.\n      got.\n      * instantiate (1:=C (b3 ++ << N k' v' e0; os3 ++ l'0 ->> pfold f'0 t' ks' :: l0 ->> pfold f0 t ks0 :: os4 >> :: b'' ++ << N k v e; os1 ++ l' ->> pmap (pmap_compose f' f) ks :: os2 >> :: b''') os0 (l ->>> 0 :: rs0) term1).\n        one_step; eapply S_SwapReads; eauto; crush.\n      * instantiate (1:=C ((b3 ++ << N k' v' e0; os3 ++ l'0 ->> pfold f'0 t' ks' :: l0 ->> pfold f0 t ks0 :: os4 >> :: b'') ++ << N k v e; os1 ++ l' ->> pmap (pmap_compose f' f) ks :: os2 >> :: b''') os0 (l ->>> 0 :: rs0) term1).\n        one_step; eapply S_FusePMap; eauto; crush.\n      * crush.\nUnshelve.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nauto.\nQed.\nHint Resolve lc_fusepmap.\n\nLemma lc_swapreads :\n  forall cx cy cz b1 b2 f f' t t' ks ks' l l' term0 os os1 os2 rs n,\n  well_typed cx ->\n  cx = C (b1 ++ << n; os1 ++ l ->> pfold f t ks :: l' ->> pfold f' t' ks' :: os2 >> :: b2) os rs term0 ->\n  cy = C (b1 ++ << n; os1 ++ l' ->> pfold f' t' ks' :: l ->> pfold f t ks :: os2 >> :: b2) os rs term0 ->\n  not (lappears_free_in l f') ->\n  not (lappears_free_in l t') ->\n  cx --> cy ->\n  cx --> cz ->\n  cy -v cz.\nProof using.\n  intros cx cy cz b1 b2 f f' t t' ks ks' l l' term0 os os1 os2 rs n.\n  intros WT Heqcx Heqcy.\n  intros Hlfree1 Hlfree2.\n  intros cxcy cxcz.\n  inversion cxcz; ssame; try solve [subst; eauto].\n  (* S_Empty *)\n  - exfalso; eauto.\n  (* S_Add *)\n  - gotw (C (<< N k v t_ks_nil; [] >> :: b1 ++ << n; os1 ++ l' ->> pfold f' t' ks' :: l ->> pfold f t ks :: os2 >> :: b2) os' (l0 ->>> final H :: rs0) term1); eauto.\n    eapply S_SwapReads with (b1:=<< N k v t_ks_nil; [] >> :: b1); eauto.\n  (* S_Last *)\n  - inv H0. clear H2.\n    destruct b2; simpl in *.\n    + apply List.app_inj_tail in H3; dtr. inv H1.\n      destruct os1; simpl in *.\n      (* os1 = [] *)\n      * inv H5.\n        got.\n        { instantiate (1:=C (b0 ++ [<< n1; l' ->> pfold f' t' ks' :: os2 >>]) os0 (l0 ->>> final H :: rs0) term1).\n          exists 2.\n          eapply Step.\n          instantiate (1:=C (b0 ++ [<< n1; l0 ->> pfold f t ks :: l' ->> pfold f' t' ks' :: os2 >>]) os0 rs0 term1).\n          eapply S_SwapReads with (l:=l') (l':=l0) (f:=f') (f':=f) (t:=t') (t':=t) (os1:=[]) (b1:=b0) (b2:=[]); eauto.\n          eapply no_dep_backwards' with (os1:=[]); eauto.\n          eapply no_dep_backwards with (os1:=[]); eauto.\n          eapply Step.\n          eapply S_Last; eauto.\n          auto. }\n        { instantiate (1:=C (b0 ++ [<< n1; l' ->> pfold f' t' ks' :: os2 >>]) os0 (l0 ->>> final H :: rs0) term1).\n          exists 0. auto. }\n        { crush. }\n        (* os2 != [] *)\n      * inv H5.\n        got.\n        { instantiate (1:=C (b0 ++ [<< n1; os1 ++ l' ->> pfold f' t' ks' :: l ->> pfold f t ks :: os2 >>]) os0 (l0 ->>> final H :: rs0) term1).\n          one_step. eapply S_Last; crush. }\n        { instantiate (1:=C (b0 ++ [<< n1; os1 ++ l' ->> pfold f' t' ks' :: l ->> pfold f t ks :: os2 >>]) os0 (l0 ->>> final H :: rs0) term1).\n          one_step. eapply S_SwapReads; crush. }\n        { crush. }\n    + remember (s :: b2) as bend.\n      assert (exists y ys, bend = ys ++ [y]) by (apply list_snoc with (xs:=bend) (x:=s) (xs':=b2); crush); dtr; subst.\n      rewrite H0 in *. clear H0.\n      replace (b1 ++ << n; os1 ++ l ->> pfold f t ks :: l' ->> pfold f' t' ks' :: os2 >> :: x0 ++ [x]) with ((b1 ++ << n; os1 ++ l ->> pfold f t ks :: l' ->> pfold f' t' ks' :: os2 >> :: x0) ++ [x]) in H3 by crush.\n      apply List.app_inj_tail in H3; dtr.\n      subst.\n      got.\n      * instantiate (1:=C ((b1 ++ << n; os1 ++ l' ->> pfold f' t' ks' :: l ->> pfold f t ks :: os2 >> :: x0) ++ [<< n1; os1' >>]) os0 (l0 ->>> final H :: rs0) term1).\n        one_step. eapply S_Last; crush.\n      * instantiate (1:=C (b1 ++ << n; os1 ++ l' ->> pfold f' t' ks' :: l ->> pfold f t ks :: os2 >> :: x0 ++ [<< n1; os1' >>]) os0 (l0 ->>> final H :: rs0) term1).\n        one_step. eapply S_SwapReads; crush.\n      * crush.\n  (* S_SwapReads *)\n  - destruct n as [k v].\n    destruct n0 as [k' v'].\n    {\n    tsod''.\n    - osod.\n      + dtr. inv H3. inv H4. inv H. apply List.app_inv_head in H3. inv H3. auto.\n      + inv H. apply List.app_inv_head in H3. inv H3.\n        destruct Hfirst as [os'[os''[os''']]].\n        destruct os''; simpl in *.\n        * eapply op_unique with (n:=N k' v' e0) (os1:=os1) (os2:=l' ->> pfold f' t' ks' :: os2) (os3:=os') (os4:=l0 ->> pfold f0 t0 ks0 :: os''') (os0:=os0) (rs0:=rs0) (t0:=term1) in H; eauto; crush.\n          inv H3.\n          eapply op_unique with (n:=N k' v' e0) (os1:=os' ++ [l ->> pfold f t ks]) (os2:=os''') (os3:=os3) (os4:=l'0 ->> pfold f'0 t'0 ks'0 :: os4) (os0:=os0) (rs0:=rs0) (t0:=term1) in H4; eauto; crush.\n          got.\n          { instantiate (1:=C (b0 ++ << N k' v' e0; os' ++ l ->> pfold f t ks :: l0 ->> pfold f0 t0 ks0 :: l'0 ->> pfold f'0 t'0 ks'0 :: os4 >> :: b3) os0 rs0 term1).\n            one_step; eapply S_SwapReads; eauto.\n            eapply no_dep_backwards'; eauto.\n            eapply no_dep_backwards; eauto. }\n          { instantiate (1:=C (b0 ++ << N k' v' e0; (os' ++ [l ->> pfold f t ks]) ++ l0 ->> pfold f0 t0 ks0 :: l'0 ->> pfold f'0 t'0 ks'0 :: os4 >> :: b3) os0 rs0 term1).\n            one_step; eapply S_SwapReads; eauto. crush.\n            eapply no_dep_backwards' with (os1:=os' ++ [l ->> pfold f t ks]); eauto.\n            instantiate (1:=term1).\n            instantiate (1:=rs0).\n            instantiate (1:=os0).\n            instantiate (1:=b3).\n            instantiate (1:=os4).\n            instantiate (1:=ks'0).\n            instantiate (1:=t'0).\n            instantiate (1:=f'0).\n            instantiate (1:=ks0).\n            instantiate (1:=t0).\n            instantiate (1:=l0).\n            instantiate (1:=N k' v' e0).\n            instantiate (1:=b0). crush.\n            eapply no_dep_backwards with (os1:=os' ++ [l ->> pfold f t ks]); eauto.\n            instantiate (1:=term1).\n            instantiate (1:=rs0).\n            instantiate (1:=os0).\n            instantiate (1:=b3).\n            instantiate (1:=os4).\n            instantiate (1:=ks'0).\n            instantiate (1:=t'0).\n            instantiate (1:=f'0).\n            instantiate (1:=ks0).\n            instantiate (1:=f0).\n            instantiate (1:=l0).\n            instantiate (1:=N k' v' e0).\n            instantiate (1:=b0). crush. }\n          { crush. }\n        * eapply op_unique with (n:=N k' v' e0) (os1:=os1) (os2:=l' ->> pfold f' t' ks' :: os2) (os3:=os') (os4:=l1 :: os'' ++ l0 ->> pfold f0 t0 ks0 :: os''') (os0:=os0) (rs0:=rs0) (t0:=term1) in H; eauto; crush.\n          eapply op_unique with (n:=N k' v' e0) (os1:=os' ++ l ->> pfold f t ks :: l' ->> pfold f' t' ks' :: os'') (os2:=os''') (os3:=os3) (os4:=l'0 ->> pfold f'0 t'0 ks'0 :: os4) (os0:=os0) (rs0:=rs0) (t0:=term1) in H4; eauto; crush.\n          got.\n          { instantiate (1:=C (b0 ++ << N k' v' e0; (os' ++ l' ->> pfold f' t' ks' :: l ->> pfold f t ks :: os'') ++ l'0 ->> pfold f'0 t'0 ks'0 :: l0 ->> pfold f0 t0 ks0 :: os4 >> :: b3) os0 rs0 term1).\n            one_step; eapply S_SwapReads; eauto; crush. }\n          { instantiate (1:=C (b0 ++ << N k' v' e0; os' ++ l' ->> pfold f' t' ks' :: l ->> pfold f t ks :: os'' ++ l'0 ->> pfold f'0 t'0 ks'0 :: l0 ->> pfold f0 t0 ks0 :: os4 >> :: b3) os0 rs0 term1).\n            one_step; eapply S_SwapReads; eauto. }\n          { crush. }\n      + inv H. apply List.app_inv_head in H3. inv H3.\n        destruct Hsecond as [os'[os''[os''']]].\n        destruct os''; simpl in *.\n        * eapply op_unique with (n:=N k' v' e0) (os1:=os1) (os2:=l' ->> pfold f' t' ks' :: os2) (os3:=os' ++ [l0 ->> pfold f0 t0 ks0]) (os4:=os''') (os0:=os0) (rs0:=rs0) (t0:=term1) in H; eauto; crush.\n          eapply op_unique with (n:=N k' v' e0) (os1:=os') (os2:=l ->> pfold f t ks :: l' ->> pfold f' t' ks' :: os2) (os3:=os3) (os4:=l'0 ->> pfold f'0 t'0 ks'0 :: os4) (os0:=os0) (rs0:=rs0) (t0:=term1) in H4; eauto; crush.\n          inv H0.\n          got.\n          { instantiate (1:=C (b0 ++ << N k' v' e0; (os3 ++ [l0 ->> pfold f0 t0 ks0]) ++ l'0 ->> pfold f'0 t'0 ks'0 :: l' ->> pfold f' t' ks' :: os2 >> :: b3) os0 rs0 term1).\n            one_step; eapply S_SwapReads; eauto. crush.\n            eapply no_dep_backwards' with (os1:=os3 ++ [l0 ->> pfold f0 t0 ks0]); eauto.\n            instantiate (1:=term1).\n            instantiate (1:=rs0).\n            instantiate (1:=os0).\n            instantiate (1:=b3).\n            instantiate (1:=os2).\n            instantiate (1:=ks').\n            instantiate (1:=t').\n            instantiate (1:=f').\n            instantiate (1:=ks'0).\n            instantiate (1:=t'0).\n            instantiate (1:=l'0).\n            instantiate (1:=N k' v' e0).\n            instantiate (1:=b0). crush.\n            eapply no_dep_backwards with (os1:=os3 ++ [l0 ->> pfold f0 t0 ks0]); eauto.\n            instantiate (1:=term1).\n            instantiate (1:=rs0).\n            instantiate (1:=os0).\n            instantiate (1:=b3).\n            instantiate (1:=os2).\n            instantiate (1:=ks').\n            instantiate (1:=t').\n            instantiate (1:=f').\n            instantiate (1:=ks'0).\n            instantiate (1:=f'0).\n            instantiate (1:=l'0).\n            instantiate (1:=N k' v' e0).\n            instantiate (1:=b0). crush. }\n          { instantiate (1:=C (b0 ++ << N k' v' e0; os3 ++ l0 ->> pfold f0 t0 ks0 :: l'0 ->> pfold f'0 t'0 ks'0 :: l' ->> pfold f' t' ks' :: os2 >> :: b3) os0 rs0 term1).\n            one_step; eapply S_SwapReads; eauto.\n            eapply no_dep_backwards'; eauto.\n            eapply no_dep_backwards; eauto. }\n          { crush. }\n        * eapply op_unique with (n:=N k' v' e0) (os1:=os1) (os2:=l' ->> pfold f' t' ks' :: os2) (os3:=os' ++ l0 ->> pfold f0 t0 ks0 :: l1 :: os'') (os4:=os''') (os0:=os0) (rs0:=rs0) (t0:=term1) in H; eauto; crush.\n          eapply op_unique with (n:=N k' v' e0) (os1:=os') (os2:=l1 :: os'' ++ l ->> pfold f t ks :: l' ->> pfold f' t' ks' :: os2) (os3:=os3) (os4:=l'0 ->> pfold f'0 t'0 ks'0 :: os4) (os0:=os0) (rs0:=rs0) (t0:=term1) in H4; eauto; crush.\n          got.\n          { instantiate (1:=C (b0 ++ << N k' v' e0; os3 ++ l'0 ->> pfold f'0 t'0 ks'0 :: l0 ->> pfold f0 t0 ks0 :: os'' ++ l' ->> pfold f' t' ks' :: l ->> pfold f t ks :: os2 >> :: b3) os0 rs0 term1).\n            one_step; eapply S_SwapReads; eauto; crush. }\n          { instantiate (1:=C (b0 ++ << N k' v' e0; (os3 ++ l'0 ->> pfold f'0 t'0 ks'0 :: l0 ->> pfold f0 t0 ks0 :: os'') ++ l' ->> pfold f' t' ks' :: l ->> pfold f t ks :: os2 >> :: b3) os0 rs0 term1).\n            one_step; eapply S_SwapReads; eauto; crush. }\n          { crush. }\n    - destruct Hfirst as [b'[b''[b''']]].\n      tu1.\n      got.\n      + instantiate (1:=C ((b' ++ << N k v e; os1 ++ l' ->> pfold f' t' ks' :: l ->> pfold f t ks :: os2 >> :: b'') ++ << N k' v' e0; os3 ++ l'0 ->> pfold f'0 t'0 ks'0 :: l0 ->> pfold f0 t0 ks0 :: os4 >> :: b3) os0 rs0 term1).\n        one_step; eapply S_SwapReads; eauto; crush.\n      + instantiate (1:=C (b' ++ << N k v e; os1 ++ l' ->> pfold f' t' ks' :: l ->> pfold f t ks :: os2 >> :: b'' ++ << N k' v' e0; os3 ++ l'0 ->> pfold f'0 t'0 ks'0 :: l0 ->> pfold f0 t0 ks0 :: os4 >> :: b3) os0 rs0 term1).\n        one_step; eapply S_SwapReads; eauto.\n      + crush.\n    - destruct Hsecond as [b'[b''[b''']]].\n      tu2.\n      got.\n      + instantiate (1:=C (b0 ++ << N k' v' e0; os3 ++ l'0 ->> pfold f'0 t'0 ks'0 :: l0 ->> pfold f0 t0 ks0 :: os4 >> :: b'' ++ << N k v e; os1 ++ l' ->> pfold f' t' ks' :: l ->> pfold f t ks :: os2 >> :: b''') os0 rs0 term1).\n        one_step; eapply S_SwapReads; eauto.\n      + instantiate (1:=C ((b0 ++ << N k' v' e0; os3 ++ l'0 ->> pfold f'0 t'0 ks'0 :: l0 ->> pfold f0 t0 ks0 :: os4 >> :: b'') ++ << N k v e; os1 ++ l' ->> pfold f' t' ks' :: l ->> pfold f t ks :: os2 >> :: b''') os0 rs0 term1).\n        one_step; eapply S_SwapReads; eauto; crush.\n      + crush.\n    }\nQed.\nHint Resolve lc_swapreads.\n\nLemma lc_last :\n  forall cx cy cz b1 n1 os rs term0 os1' l op H,\n  well_typed cx ->\n  cx = C (b1 ++ [<< n1; l ->> op :: os1' >>]) os rs term0 ->\n  cy = C (b1 ++ [<< n1; os1' >>]) os (l ->>> (@final op) H :: rs) term0 ->\n  ~ In (getKey n1) (target op) ->\n  cx --> cy ->\n  cx --> cz ->\n  cy -v cz.\nProof using.\n  intros cx cy cz b1 n1 os rs term0 os1' l op Hnot WT Heqcx Heqcy H3 cxcy cxcz.\n  remember (getKey n1) as k.\n  rename Heqk into H2.\n  remember (l ->> op :: os1') as os1.\n  rename Heqos1 into H1.\n  remember (b1 ++ [<<n1; os1>>]) as b.\n  rename Heqb into H0.\n  rename Heqcx into H.\n  remember cx as c.\n  rename Heqc into H4.\n  rename Heqcy into H5.\n  inversion cxcz; try solve [subst; eauto].\n  (* S_Empty *)\n  - crush. destruct b1; crush.\n  (* S_Add *)\n  - subst.\n    {\n    destruct b1.\n    (* b1 = [] *)\n    - simpl in *. inv H7. eapply ex_intro. eapply ex_intro.\n      split; try split.\n      + instantiate (1:=C [<< N k0 v t_ks_nil; [] >>; << n1; os1' >>] os' (l0 ->>> _ :: l ->>> final _ :: rs0) term1).\n        one_step; eapply S_Add with (b:=[<< n1; os1' >>]); crush.\n      + instantiate (1:=C [<< N k0 v t_ks_nil; [] >>; << n1; os1' >>] os' (l ->>> final Hnot :: l0 ->>> k0 :: rs0) term1).\n        one_step; eapply S_Last with (b1:=[<< N k0 v t_ks_nil; [] >>]); crush.\n      + crush.\n    (* b1 != [] *)\n    - simpl in *. inv H7. eapply ex_intro. eapply ex_intro.\n      split; try split.\n      + instantiate (1:=C (<< N k0 v t_ks_nil; [] >> :: s :: b1 ++ [<< n1; os1' >>]) os' (l0 ->>> k0 :: l ->>> final Hnot :: rs0) term1).\n        one_step; eapply S_Add; crush.\n      + instantiate (1:=C (<< N k0 v t_ks_nil; [] >> :: s :: b1 ++ [<< n1; os1' >>]) os' (l ->>> final Hnot :: l0 ->>> k0 :: rs0) term1).\n        one_step; eapply S_Last with (b1:=<< N k0 v t_ks_nil; [] >> :: s :: b1); crush.\n      + crush.\n    }\n  (* S_Last *)\n  - ssame. apply List.app_inj_tail in H0. inv H0. inv H1.\n    unfold not_fold_or_done in *.\n    destruct H6; destruct Hnot.\n    + destruct op0; crush.\n    + destruct op0; crush.\n    + destruct op0; crush.\n    + destruct e0. destruct e0. destruct e0. destruct e. destruct e. destruct e. crush.\n      inv e.\n      crush.\nUnshelve.\nauto.\nauto.\nQed.\nHint Resolve lc_last.\n\nLemma lc_empty :\n  forall cx cy cz l op os' rs term0 Hnot,\n  well_typed cx ->\n  cx = C [] (l ->> op :: os') rs term0 ->\n  cy = C [] os' (l ->>> (@final op) Hnot :: rs) term0 ->\n  not_add op ->\n  cx --> cy ->\n  cx --> cz ->\n  cy -v cz.\nProof using.\n  intros cx cy cz l op os' rs term0 Hnot WT Heqcx Heqcy Hnotadd cxcy cxcz.\n  inversion cxcz; ssame; eauto; crush.\n  - unfold not_fold_or_done in *.\n    destruct Hnot; destruct H; try solve [destruct op0; crush].\n    destruct e0. destruct e0. destruct e0. destruct e. destruct e. destruct e. crush.\n    inv e0.\n    crush.\nQed.\nHint Resolve lc_empty.\n\nLemma lc_add :\n  forall cx cy cz b l k v os' rs term0 Hnot,\n  well_typed cx ->\n  cx = C b (l ->> add k v :: os') rs term0 ->\n  cy = C (<< N k v t_ks_nil; [] >> :: b) os' (l ->>> (@final (add k v)) Hnot :: rs) term0 ->\n  cx --> cy ->\n  cx --> cz ->\n  cy -v cz.\nProof using.\n  intros cx cy cz b l k v os' rs term0 Hnot WT Heqcx Heqcy cxcy cxcz.\n  inversion cxcz; ssame; eauto; crush.\nQed.\nHint Resolve lc_add.\n\nLemma local_confluence :\n  forall cx cy cz,\n  well_typed cx ->\n  cx --> cy ->\n  cx --> cz ->\n  (cy -v cz).\nProof using.\n  intros cx cy cz WT cxcy cxcz.\n  inversion cxcy; subst; eauto.\nQed.\n\n(* we are only interested in reductions that terminate *)\nHypothesis to_dry : forall c, exists n c', c -->*[n] c' /\\ dry c'.\n\nLemma well_typed_preservation' : forall c n c',\n  well_typed c ->\n  c -->*[n] c' ->\n  well_typed c'.\nProof using.\n  intros c n c' WT Hmulti.\n  induction Hmulti; subst; eauto.\n  assert (well_typed y) by (eapply well_typed_preservation; eauto).\n  eauto.\nQed.\n\nHint Resolve well_typed_preservation'.\n\nDefinition pp cx cy := well_typed cx -> well_typed cy -> cx == cy ->\n                                  forall cx' cy' n m,\n                                    cx -->*[n] cx' ->\n                                    cy -->*[m] cy' ->\n                                    cx' -v cy'.\n\nDefinition r_complete (p : config -> config -> Prop) :=\n  forall cx, (forall cy cy' n m, n > 0 -> m > 0 -> cx -->*[n] cy -> cx -->*[m] cy' -> p cy cy') -> p cx cx.\n\nLemma pp_r_complete :\n  r_complete pp.\nProof using.\n  unfold r_complete; intros.\n    unfold pp in *.\n  intros.\n  rename cy' into cz.\n  rename cx' into cy.\n  rename H3 into XY.\n  rename H4 into XZ.\n  assert (H3: 1 + 1 = 2) by auto.\n  destruct m; destruct n.\n  (* n = 0, m = 0 *)\n  - apply star_zero in XY.\n    apply star_zero in XZ.\n    crush.\n  (* n = 0, m > 0 *)\n  - inv XY.\n    apply star_zero in XZ; subst.\n    eapply ex_intro.\n    eapply ex_intro.\n    split; try split.\n    + instantiate (1:=cy).\n      crush.\n    + instantiate (1:=cy).\n      apply ex_intro with (S n).\n      apply Step with (y).\n      assumption.\n      assumption.\n    + crush.\n  (* n > 0, m = 0 *)\n  - inv XZ.\n    apply star_zero in XY; subst.\n    eapply ex_intro.\n    eapply ex_intro.\n    split; try split.\n    + instantiate (1:=cz).\n      apply ex_intro with (S m).\n      apply Step with (y).\n      assumption.\n      assumption.\n    + instantiate (1:=cz).\n      crush.\n    + crush.\n  (* n > 0, m > 0 *)\n  - inv XY.\n    rename y into cy'.\n    inv XZ.\n    rename y into cz'.\n    destruct (local_confluence H1 H5 H7).\n    destruct H4. destruct H4. destruct H9. destruct H4. destruct H9.\n    rename x into cy''.\n    rename x0 into cz''.\n    assert (exists n cw, cy -->*[n] cw /\\ normal_form cw).\n    {\n      destruct (@to_dry cy); dtr.\n      exists x, x0. destruct x0.\n      split; [eauto|eapply dry_normal_form; eauto].\n    }\n    destruct H11 as [n' H']. destruct H' as [cw cycw]. destruct cycw as [cycw nfcw].\n    assert (exists n cw', cy'' -->*[n] cw' /\\ normal_form cw').\n    {\n      destruct (@to_dry cy''); dtr.\n      exists x, x0. destruct x0.\n      split; [eauto|eapply dry_normal_form; eauto].\n    }\n    destruct H11 as [n'' H']. destruct H' as [cw' cycw']. destruct cycw' as [cycw' nfcw'].\n    assert (exists n cv, cz'' -->*[n] cv /\\ normal_form cv).\n    {\n      destruct (@to_dry cz''); dtr.\n      exists x, x0. destruct x0.\n      split; [eauto|eapply dry_normal_form; eauto].\n    }\n    destruct H11 as [n''' H']. destruct H' as [cv cycv]. destruct cycv as [cycv nfcv].\n    assert (exists n cv', cz -->*[n] cv' /\\ normal_form cv').\n    {\n      destruct (@to_dry cz); dtr.\n      exists x, x0. destruct x0.\n      split; [eauto|eapply dry_normal_form; eauto].\n    }\n    destruct H11 as [n'''' H']. destruct H' as [cv' cycv']. destruct cycv' as [cycv' nfcv'].\n    assert (Hsimcy' : cy' == cy') by crush.\n    assert (cw == cw').\n    {\n      edestruct H with (cy:=cy') (cy':=cy') (cx':=cw) (cy'0:=cw') (n:=1) (m:=1); eauto.\n      - destruct H11.\n        destruct H11.\n        destruct H11.\n        destruct H12.\n        destruct H12.\n        assert (x = cw).\n        {\n          destruct x3.\n          - apply star_zero in H11; eauto.\n          - inversion H11. subst. exfalso. unfold normal_form in nfcw. apply nfcw. eauto.\n        }\n        subst.\n        assert (x0 = cw').\n        {\n          destruct x4.\n          - apply star_zero in H12; eauto.\n          - inversion H12. subst. exfalso. unfold normal_form in nfcw'. apply nfcw'. eauto.\n        }\n        subst.\n        assumption.\n    }\n    assert (Hsimcz' : cz' == cz') by crush.\n    assert (cv == cv').\n    {\n      edestruct H with (cy:=cz') (cy':=cz') (cx':=cv) (cy'0:=cv') (n:=1); eauto.\n      - destruct H12.\n        destruct H12.\n        destruct H12.\n        destruct H13.\n        destruct H13.\n        assert (x = cv).\n        {\n          destruct x3.\n          - apply star_zero in H12; eauto.\n          - inversion H12. subst. exfalso. unfold normal_form in nfcv. apply nfcv. eauto.\n        }\n        subst.\n        assert (x0 = cv').\n        {\n          destruct x4.\n          - apply star_zero in H13; eauto.\n          - inversion H13. subst. exfalso. unfold normal_form in nfcv'. apply nfcv'. eauto.\n        }\n        subst. assumption.\n    }\n    \n    assert (cw' == cv).\n    {\n      edestruct H with (cy:=cy'') (cy':=cz'') (cx':=cw') (cy'0:=cv) (n:=S x1) (m:=S x2); eauto.\n      - crush.\n      - crush.\n      - destruct H13.\n        destruct H13.\n        destruct H13.\n        destruct H14.\n        destruct H14.\n        assert (x = cw').\n        {\n          destruct x3.\n          - apply star_zero in H13; eauto.\n          - inversion H13. subst. exfalso. unfold normal_form in nfcw'. apply nfcw'. eauto.\n        }\n        subst.\n        assert (x0 = cv).\n        {\n          destruct x4.\n          - apply star_zero in H14; eauto.\n          - inversion H14. subst. exfalso. unfold normal_form in nfcv. apply nfcv. eauto.\n        }\n        subst. assumption.\n    }\n    apply ex_intro with cw.\n    apply ex_intro with cv'.\n    split; try split.\n    + eauto.\n    + eauto.\n    + apply cequiv_trans with cw'; auto.\n      apply cequiv_trans with cv; auto.\nQed.\n\n\nAxiom principal_of_noe_indo : forall P, r_complete P -> forall cx, P cx cx.\n\nTheorem confluence :\n  forall cx cy cz,\n  well_typed cx ->\n  (exists n, cx -->*[n] cy) ->\n  (exists m, cx -->*[m] cz) ->\n  (cy -v cz).\nProof using.\n  intros.\n  destruct H0.\n  destruct H1.\n  edestruct (@principal_of_noe_indo pp) with (cx:=cx) (cx':=cy); eauto.\n- apply pp_r_complete.\nQed.\n\nLemma dry_goes_nowhere : forall c c',\n  well_typed c ->\n  dry c ->\n  (exists n, c -->*[n] c') ->\n  c = c'.\nProof using.\n  intros; dtr.\n  destruct c as [b os rs t].\n  remember (C b os rs t) as c.\n  eapply dry_normal_form in H0; eauto.\n  unfold normal_form in H0.\n  destruct x.\n  - eauto.\n  - exfalso. apply H0. inv H1. eauto.\nQed.\nHint Resolve dry_goes_nowhere.\n\nDefinition init (b : backend) (t : term) := C b [] [] t.\n\nTheorem determinism : forall b t i i' i'',\n  i = init b t ->\n  well_typed i ->\n  (exists n, i -->*[n] i') ->\n  (exists m, i -->*[m] i'') ->\n  dry i' ->\n  dry i'' ->\n  i' == i''.\nProof using.\n  intros.\n  copy H1.\n  apply confluence with (cy:=i'') in H1; auto.\n  dtr.\n  assert (i'' = x1) by eauto.\n  assert (i' = x2) by eauto.\n  subst.\n  apply cequiv_symmetric; auto.\nQed.\n", "meta": {"author": "philipdexter", "repo": "ourlang", "sha": "b7421f5790bb829381bf737dbd9210d977d0aca5", "save_path": "github-repos/coq/philipdexter-ourlang", "path": "github-repos/coq/philipdexter-ourlang/ourlang-b7421f5790bb829381bf737dbd9210d977d0aca5/ourlang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.2878216225833632}}
{"text": "(*********************************************************************************************************************************)\n(* HaskProgrammingLanguage:                                                                                                      *)\n(*                                                                                                                               *)\n(*    System FC^\\alpha is a ProgrammingLanguage.                                                                                 *)\n(*                                                                                                                               *)\n(*********************************************************************************************************************************)\n\nGeneralizable All Variables.\nRequire Import Preamble.\nRequire Import General.\nRequire Import NaturalDeduction.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\n\nRequire Import Algebras_ch4.\nRequire Import Categories_ch1_3.\nRequire Import Functors_ch1_4.\nRequire Import Isomorphisms_ch1_5.\nRequire Import ProductCategories_ch1_6_1.\nRequire Import OppositeCategories_ch1_6_2.\nRequire Import Enrichment_ch2_8.\nRequire Import Subcategories_ch7_1.\nRequire Import NaturalTransformations_ch7_4.\nRequire Import NaturalIsomorphisms_ch7_5.\nRequire Import MonoidalCategories_ch7_8.\nRequire Import Coherence_ch7_8.\n\nRequire Import HaskKinds.\nRequire Import HaskCoreTypes.\nRequire Import HaskLiterals.\nRequire Import HaskTyCons.\nRequire Import HaskStrongTypes.\nRequire Import HaskProof.\nRequire Import NaturalDeduction.\nRequire Import NaturalDeductionCategory.\n\nRequire Import HaskStrongTypes.\nRequire Import HaskStrong.\nRequire Import HaskProof.\nRequire Import HaskStrongToProof.\nRequire Import HaskProofToStrong.\nRequire Import ProgrammingLanguage.\n\nOpen Scope nd_scope.\n\n(* The judgments any specific Γ,Δ form a category with proofs as morphisms *)\nSection HaskProgrammingLanguage.\n\n  Context (ndr_systemfc:@ND_Relation _ Rule).\n\n  Context Γ (Δ:CoercionEnv Γ).\n\n  \n  Definition JudgΓΔ := prod (Tree ??(LeveledHaskType Γ ★)) (Tree ??(LeveledHaskType Γ ★)).\n\n  Definition RuleΓΔ : Tree ??JudgΓΔ -> Tree ??JudgΓΔ -> Type :=\n    fun h c =>\n      Rule\n      (mapOptionTree (fun j => Γ > Δ > fst j |- snd j) h)\n      (mapOptionTree (fun j => Γ > Δ > fst j |- snd j) c).\n\n  Definition SystemFCa_cut : forall a b c, ND RuleΓΔ ([(a,b)],,[(b,c)]) [(a,c)].\n    intros.\n    destruct b.\n    destruct o.\n    destruct c.\n    destruct o.\n\n    (* when the cut is a single leaf and the RHS is a single leaf: *)\n    (*\n    eapply nd_comp.\n      eapply nd_prod.\n      apply nd_id.\n      eapply nd_rule.\n      set (@org_fc) as ofc.\n      set (RArrange Γ Δ _ _ _ (AuCanL [l0])) as rule.\n      apply org_fc with (r:=RArrange _ _ _ _ _ (AuCanL [_])).\n      auto.\n      eapply nd_comp; [ idtac | eapply nd_rule; apply org_fc with (r:=RArrange _ _ _ _ _ (ACanL _)) ].\n      apply nd_rule.\n      destruct l.\n      destruct l0.\n      assert (h0=h2). admit.\n      subst.\n      apply org_fc with (r:=@RLet Γ Δ [] a h1 h h2). \n      auto.\n      auto.\n      *)\n    admit.\n    apply (Prelude_error \"systemfc cut rule invoked with [a|=[b]] [[b]|=[]]\").\n    apply (Prelude_error \"systemfc cut rule invoked with [a|=[b]] [[b]|=[x,,y]]\").\n    apply (Prelude_error \"systemfc rule invoked with [a|=[]]  [[]|=c]\").\n    apply (Prelude_error \"systemfc rule invoked with [a|=[b,,c]] [[b,,c]|=z]\").\n    Defined.\n\n  Instance SystemFCa_sequents : @SequentND _ RuleΓΔ _ _ :=\n  { snd_cut := SystemFCa_cut }.\n    apply Build_SequentND.\n    intros.\n    induction a.\n    destruct a; simpl.\n    (*\n    apply nd_rule.\n      destruct l.\n      apply org_fc with (r:=RVar _ _ _ _).\n      auto.\n    apply nd_rule.\n      apply org_fc with (r:=RVoid _ _ ).\n      auto.\n    eapply nd_comp.\n      eapply nd_comp; [ apply nd_llecnac | idtac ].\n      apply (nd_prod IHa1 IHa2).\n      apply nd_rule.\n        apply org_fc with (r:=RJoin _ _ _ _ _ _). \n        auto.\n      admit.\n      *)\n      admit.\n      admit.\n      admit.\n      admit.\n      Defined.\n\n  Definition SystemFCa_left a b c : ND RuleΓΔ [(b,c)] [((a,,b),(a,,c))].\n    admit.\n    (*\n    eapply nd_comp; [ apply nd_llecnac | eapply nd_comp; [ idtac | idtac ] ].\n    eapply nd_prod; [ apply snd_initial | apply nd_id ].\n    apply nd_rule.\n    apply org_fc with (r:=RJoin Γ Δ a b a c).\n    auto.\n    *)\n    Defined.\n\n  Definition SystemFCa_right a b c : ND RuleΓΔ [(b,c)] [((b,,a),(c,,a))].\n    admit.\n    (*\n    eapply nd_comp; [ apply nd_rlecnac | eapply nd_comp; [ idtac | idtac ] ].\n    eapply nd_prod; [ apply nd_id | apply snd_initial ].\n    apply nd_rule.\n    apply org_fc with (r:=RJoin Γ Δ b a c a).\n    auto.\n    *)\n    Defined.\n\n  Instance SystemFCa_sequent_join : @ContextND _ _ _ _ SystemFCa_sequents :=\n  { cnd_expand_left  := fun a b c => SystemFCa_left  c a b\n  ; cnd_expand_right := fun a b c => SystemFCa_right c a b }.\n    (*\n    intros; apply nd_rule. simpl.\n      apply (org_fc _ _ _ _ ((RArrange _ _ _ _ _ (AuAssoc _ _ _)))).\n      auto.\n\n    intros; apply nd_rule. simpl.\n      apply (org_fc _ _ _ _ (RArrange _ _ _ _ _ (AAssoc _ _ _))); auto.\n\n    intros; apply nd_rule. simpl.\n      apply (org_fc _ _ _ _ (RArrange _ _ _ _ _ (ACanL _))); auto.\n\n    intros; apply nd_rule. simpl.\n      apply (org_fc _ _ _ _ (RArrange _ _ _ _ _ (ACanR _))); auto.\n\n    intros; apply nd_rule. simpl.\n      apply (org_fc _ _ _ _ (RArrange _ _ _ _ _ (AuCanL _))); auto.\n\n    intros; apply nd_rule. simpl.\n      apply (org_fc _ _ _ _ (RArrange _ _ _ _ _ (AuCanR _))); auto.\n      *)\n      admit.\n      admit.\n      admit.\n      admit.\n      admit.\n      admit.\n      Defined.\n\n  Instance OrgFC : @ND_Relation _ RuleΓΔ.\n    Admitted.\n\n  Instance OrgFC_SequentND_Relation : SequentND_Relation SystemFCa_sequent_join OrgFC.\n    admit.\n    Defined.\n\n  Definition OrgFC_ContextND_Relation\n    : @ContextND_Relation _ _ _ _ _ SystemFCa_sequent_join OrgFC OrgFC_SequentND_Relation.\n    admit.\n    Defined.\n\n  (* 5.1.2 *)\n  Instance SystemFCa : @ProgrammingLanguage (LeveledHaskType Γ ★) _ :=\n  { pl_eqv                := OrgFC_ContextND_Relation\n  ; pl_snd                := SystemFCa_sequents\n  }.\n\nEnd HaskProgrammingLanguage.\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/HaskProgrammingLanguage.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.28782161578861354}}
{"text": "Require Import ExtLib.Data.Positive.\nRequire Import ExtLib.Data.PList.\nRequire Import ExtLib.Data.Eq.UIP_trans.\nRequire Import ExtLib.Tactics.\n\nRequire Import MirrorCore.CTypes.CoreTypes.\nRequire Import MirrorCore.TypesI.\nRequire Import MirrorCore.Util.Compat.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\n(** TODO(gmalecha): This should use the maps in FMapPositive from ExtLib.\n **)\nModule OneOfType.\n\n  Definition TypeR := Set.\n  Definition TypeS := Type.\n\n  Inductive _option : TypeS :=\n  | _Some : (nat -> TypeR) -> _option\n  | _None.\n  Arguments _None.\n  Arguments _Some _.\n\n  Inductive pmap : TypeS :=\n  | Empty : pmap\n  | Branch : _option -> pmap -> pmap -> pmap.\n  Arguments Empty.\n  Arguments Branch _ _ _.\n\n  Definition pmap_here (p : pmap) : _option :=\n    match p with\n    | Empty => _None\n    | Branch d _ _ => d\n    end.\n  Definition pmap_left (p : pmap) : pmap :=\n    match p with\n    | Empty => Empty\n    | Branch _ l _ => l\n    end.\n  Definition pmap_right (p : pmap) : pmap :=\n    match p with\n    | Empty => Empty\n    | Branch _ _ r => r\n    end.\n\n  Fixpoint pmap_lookup' (ts : pmap) (p : positive) : _option :=\n    match p with\n    | xH => pmap_here ts\n    | xI p => pmap_lookup' (pmap_right ts) p\n    | xO p => pmap_lookup' (pmap_left ts) p\n    end.\n\n  Fixpoint pmap_insert (p : positive) (ts : pmap) (x : nat -> TypeR) : pmap :=\n    match p with\n    | xH => Branch (_Some x) (pmap_left ts) (pmap_right ts)\n    | xO p => Branch (pmap_here ts)\n                     (pmap_insert p (pmap_left ts) x)\n                     (pmap_right ts)\n    | xI p => Branch (pmap_here ts)\n                     (pmap_left ts)\n                     (pmap_insert p (pmap_right ts) x)\n    end.\n\n  Set Primitive Projections.\n\n  Definition type_nth (p : pmap) (k : positive) (n : nat) : TypeR :=\n    match pmap_lookup' p k return TypeR with\n    | _None => Empty_set\n    | _Some T => T n\n    end.\n\n  Record OneOfF (ts : pmap) (x : nat) : Type := mkOneOfF\n  { indexF : positive\n  ; valueF : type_nth ts indexF x\n  }.\n\n  Definition IntoF {ts} {T : nat -> TypeR} x (n : positive)\n             (pf : pmap_lookup' ts n = _Some T)\n  : T x -> OneOfF ts x :=\n    match pf in _ = X return match X return TypeR with\n                             | _Some T => T x\n                             | _None => Empty_set\n                             end -> OneOfF ts x\n    with\n    | eq_refl => @mkOneOfF ts x n\n    end.\n\n  Fixpoint asNth' {ts : pmap} {n} (p p' : positive)\n  : match pmap_lookup' ts p' return TypeR with\n    | _None => Empty_set\n    | _Some T => T n\n    end -> option (type_nth ts p n) :=\n  match p as p , p' as p'\n        return type_nth ts p' n -> option (type_nth ts p n)\n  with\n    | xH , xH => Some\n    | xI p , xI p' => asNth' p p'\n    | xO p , xO p' => asNth' p p'\n    | _ , _ => fun _ => None\n  end.\n\n  Definition asNth {ts : pmap} {n} (p : positive) (oe : OneOfF ts n)\n  : option (type_nth ts p n) :=\n    @asNth' ts n p oe.(indexF) oe.(valueF).\n\n  Definition OutOfF {ts} {T : nat -> TypeR} {x} (n : positive)\n             (pf : pmap_lookup' ts n = _Some T)\n  : OneOfF ts x -> option (T x) :=\n    match pf in _ = X\n          return OneOfF ts x ->\n                 option match X return TypeR with\n                        | _None => Empty_set\n                        | _Some T => T x\n                        end\n    with\n    | eq_refl => asNth _\n    end.\n\n  Global Instance Injective_OneOf n m i1 i2 v1 v2\n  : Injective (@eq (OneOfF m n)\n                   {| indexF := i1 ; valueF := v1 |}\n                   {| indexF := i2 ; valueF := v2 |}) :=\n  { result := exists pf : i2 = i1,\n      v1 = match pf in _ = T\n                 return type_nth m T n\n           with\n           | eq_refl => v2\n           end\n  ; injection := fun H =>\n      match H in _ = h\n            return exists pf : indexF h = i1 ,\n          v1 = match pf in (_ = T)\n                     return type_nth m T n\n               with\n               | eq_refl => valueF h\n               end\n      with\n      | eq_refl => @ex_intro _ _ eq_refl eq_refl\n      end\n  }.\n\n\n  Definition asNth'' {ts : pmap} {n} p (x : OneOfF ts n)\n  : option (type_nth ts p n) :=\n    match Pos.eq_dec (indexF x) p with\n    | left pf' => Some match pf' in _ = X\n                             return type_nth ts X n\n                       with\n                       | eq_refl => valueF x\n                       end\n    | right _ => None\n    end.\n\n  Theorem asNth'_asNth''\n  : forall ts n p x,\n      @asNth' ts n p (indexF x) (valueF x) = @asNth'' ts n p x.\n  Proof using.\n    destruct x. unfold asNth''. simpl.\n    destruct (Pos.eq_dec indexF0 p); subst.\n    { revert valueF0; revert ts.\n      induction p; simpl; intros; eauto. }\n    { revert valueF0; revert ts; generalize dependent indexF0.\n      induction p; destruct indexF0; simpl; intros; eauto.\n      { assert (indexF0 <> p) by congruence.\n        eauto. }\n      { assert (indexF0 <> p) by congruence.\n        eauto. }\n      { congruence. } }\n  Qed.\n\n  Lemma asNth'_get_lookup\n  : forall n p ts v, asNth' (ts:=ts) (n:=n) p p v = Some v.\n  Proof.\n    induction p; simpl; intros; eauto.\n  Defined.\n\n  Require Import MirrorCore.Util.Compat.\n\n  Theorem OutofF_IntoF : forall n ts T p pf v,\n    @OutOfF ts n T p pf (@IntoF ts n T p pf v) = Some v.\n  Proof using.\n    unfold OutOfF, IntoF.\n    intros.\n    autorewrite_with_eq_rw.\n    unfold asNth. simpl.\n    rewrite asNth'_get_lookup.\n    { generalize dependent (pmap_lookup' ts p).\n      intros. subst. reflexivity. }\n  Defined.\n\n  Theorem asNth_eq\n    : forall ts n p oe v,\n      @asNth ts n p oe = Some v ->\n      oe = {| indexF := p ; valueF := v |}.\n  Proof.\n    unfold asNth.\n    destruct oe; simpl.\n    revert valueF0. revert indexF0. revert ts.\n    induction p; destruct indexF0; simpl; intros;\n    try congruence; eapply IHp in H; inv_all; subst; reflexivity.\n  Defined.\n\n  Theorem IntoF_OutOfF : forall ts n T p pf v e,\n      @OutOfF ts n T p pf e = Some v ->\n      @IntoF ts n T p pf v = e.\n  Proof using.\n    unfold OutOfF, IntoF.\n    intros. revert H.\n    autorewrite_with_eq_rw.\n    unfold asNth.\n    destruct e; simpl in *.\n    intro.\n    assert (p = indexF0).\n    { destruct (asNth' p indexF0 valueF0) eqn:?; try congruence.\n      inv_all. subst.\n      clear - Heqo.\n      revert Heqo.\n      revert valueF0 t.\n      revert indexF0. revert ts.\n      induction p; destruct indexF0; simpl; intros; try congruence.\n      { f_equal. eauto. }\n      { f_equal. eauto. } }\n    subst.\n    rewrite asNth'_get_lookup in H. inv_all. subst.\n    f_equal. clear.\n    unfold type_nth in *.\n    destruct pf. reflexivity.\n  Defined.\n\n  Universe UPmap.\n  Polymorphic Fixpoint list_to_pmap_aux\n              (lst : plist@{UPmap} (nat -> TypeR)) (p : positive) : pmap :=\n    match lst with\n    | pnil => OneOfType.Empty\n    | pcons x xs => OneOfType.pmap_insert p (list_to_pmap_aux xs (p + 1)) x\n  end.\n\n  Definition list_to_pmap (lst : plist@{UPmap} (nat -> TypeR)) :=\n    list_to_pmap_aux lst 1.\n\nEnd OneOfType.\n\nImport OneOfType.\n\nSection TSym_OneOf.\n  Context {typ : nat -> Set} {TS : TSym typ}.\n\n  Definition TSym_Empty_set : TSym (fun _ => Empty_set) :=\n  {| symbolD := fun n (x : Empty_set) => match x with end\n   ; symbol_dec := fun _ x _ => match x with end\n   |}.\n\n  Definition TSym_All m : Type :=\n    forall p, TSym (type_nth m p).\n\n  Instance TSymOneOf (m : pmap) (H : TSym_All m)\n  : TSym (OneOfF m) :=\n  { symbolD := fun s x => let ts := H x.(indexF) in\n                          @symbolD _ ts _ x.(valueF)\n  ; symbol_dec := fun _ a b =>\n    match a as a , b as b return {a = b} + {a <> b} with\n    |   {| indexF := i1 ; valueF := v1 |}\n      , {| indexF := i2 ; valueF := v2 |} =>\n        match Pos.eq_dec i1 i2 with\n        | left pf =>\n          match pf in _ = Z return forall x : type_nth _ Z _,\n              {mkOneOfF m _ i1 v1 = mkOneOfF m _ Z x} +\n              {mkOneOfF m _ i1 v1 <> mkOneOfF m _ Z x}\n          with\n          | eq_refl => fun v2 =>\n            match @symbol_dec _ (H i1) _ v1 v2 with\n            | left pf => left _\n            | right _ => right _\n            end\n          end v2\n        | right _ => right _\n        end\n    end\n   }.\n  { subst. reflexivity. }\n  { intro.\n    eapply Injective_OneOf in H0. simpl in H0.\n    destruct H0.\n    rewrite (uip_trans Pos.eq_dec _ _ x eq_refl) in H0. apply n0. assumption. }\n  { intro.\n    apply n0.\n    change (indexF {| indexF := i1; valueF := v1 |} =\n            indexF {| indexF := i2; valueF := v2 |}).\n    rewrite H0. reflexivity. }\n  Defined.\n\n  Definition TSym_All_Empty : TSym_All Empty.\n  Proof.\n    red. intros.\n    induction p; unfold type_nth in *; simpl; eauto.\n    eapply TSym_Empty_set.\n  Defined.\n\n  Definition TSym_All_Branch_None l r\n  : TSym_All l -> TSym_All r -> TSym_All (Branch _None l r).\n  Proof.\n    red. intros.\n    destruct p.\n    { apply X0. }\n    { apply X. }\n    { apply TSym_Empty_set. }\n  Defined.\n\n  Definition TSym_All_Branch_Some s l r\n  : TSym s -> TSym_All l -> TSym_All r -> TSym_All (Branch (_Some s) l r).\n  Proof.\n    red. intros.\n    destruct p.\n    { apply X1. }\n    { apply X0. }\n    { assumption. }\n  Defined.\n\n  Definition PartialViewPMap_Type (A : nat -> TypeR) (p : positive) (m : pmap)\n             (pf : _Some A = pmap_lookup' m p) (n : nat)\n  : PartialView (OneOfF m n) (A n) :=\n  {| f_insert := IntoF n p (eq_sym pf)\n   ; f_view := let view := OutOfF p (eq_sym pf) in\n               fun x : OneOfF m n =>\n                 match view x with\n                 | Some x0 => POption.pSome x0\n                 | None => POption.pNone\n                 end |}.\n\n  Definition PartialViewOk_TSymOneOf (m : pmap) (H : TSym_All m)\n             (p : positive) Z (pf : _Some Z = pmap_lookup' m p)\n             n\n  : let X : TSym Z := match eq_sym pf in _ = K\n                            return TSym (fun n => match K return TypeR with\n                                                  | _Some T => T n\n                                                  | _None => Empty_set\n                                                  end)\n                      with\n                      | eq_refl => H p\n                      end in\n    PartialViewOk (PartialViewPMap_Type p m pf n)\n                  (fun a b =>\n                     @symbolD _ (TSymOneOf H) _ a = symbolD b).\n  Proof.\n    constructor.\n    { simpl; intros.\n      split.\n      { intros.\n        generalize (@IntoF_OutOfF m _ n p (eq_sym pf) a f).\n        destruct (OutOfF p (eq_sym pf) f).\n        { intro. apply H1.\n          clear - H0. f_equal. injection H0. tauto. }\n        { inversion H0. } }\n      { intros. subst.\n        rewrite OutofF_IntoF. reflexivity. } }\n    { simpl. unfold IntoF.\n      intros. unfold type_nth.\n      simpl.\n      autorewrite_with_eq_rw.\n      simpl.\n      generalize (H p). clear. unfold type_nth.\n      destruct pf. reflexivity. }\n  Defined.\n\n  Fixpoint pmap_lookup'_Empty (p : positive) : pmap_lookup' Empty p = _None :=\n    match p with\n    | xH => eq_refl\n    | xO p => pmap_lookup'_Empty p\n    | xI p => pmap_lookup'_Empty p\n    end.\n\nEnd TSym_OneOf.\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/CTypes/TSymOneOf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2878216157886135}}
{"text": "(*********************************************************************************************************************************)\n(* ProgrammingLanguageFlattening                                                                                                 *)\n(*********************************************************************************************************************************)\n\nGeneralizable All Variables.\nRequire Import Preamble.\nRequire Import General.\nRequire Import Categories_ch1_3.\nRequire Import InitialTerminal_ch2_2.\nRequire Import Functors_ch1_4.\nRequire Import Isomorphisms_ch1_5.\nRequire Import ProductCategories_ch1_6_1.\nRequire Import OppositeCategories_ch1_6_2.\nRequire Import Enrichment_ch2_8.\nRequire Import Subcategories_ch7_1.\nRequire Import NaturalTransformations_ch7_4.\nRequire Import NaturalIsomorphisms_ch7_5.\nRequire Import BinoidalCategories.\nRequire Import PreMonoidalCategories.\nRequire Import MonoidalCategories_ch7_8.\nRequire Import Coherence_ch7_8.\nRequire Import Enrichment_ch2_8.\nRequire Import RepresentableStructure_ch7_2.\nRequire Import FunctorCategories_ch7_7.\n\nRequire Import Reification.\nRequire Import NaturalDeduction.\nRequire Import NaturalDeductionCategory.\nRequire Import GeneralizedArrow.\nRequire Import ProgrammingLanguageEnrichment.\nRequire Import ProgrammingLanguageReification.\nRequire Import SectionRetract_ch2_4.\nRequire Import GeneralizedArrowFromReification.\nRequire Import Enrichments.\nRequire Import ReificationsAndGeneralizedArrows.\n\nSection Flattening.\n\n  Context `(Guest:ProgrammingLanguage) `(Host :ProgrammingLanguage).\n  Context (GuestHost:TwoLevelLanguage Guest Host).\n\n  Definition FlatObject (x:TypesL Host) :=\n    forall y1 y2, not ((reification_r_obj GuestHost y1 y2)=x).\n\n  Instance FlatSubCategory : FullSubcategory (TypesL Host) FlatObject.\n\n    Context  (F:RetractionOfCategories (TypesL Host) (FullSubCategoriesAreCategories FlatSubCategory)).\n\n    Definition FlatteningOfReification HostMonic HostMonoidal :=\n      (ga_functor\n        (@garrow_from_reification\n          (TypesEnrichedInJudgments Guest)\n          (TypesEnrichedInJudgments Host)\n          HostMonic HostMonoidal GuestHost))\n        >>>> F.\n\n    Lemma FlatteningIsNotDestructive HostMonic HostMonoidal : \n      FlatteningOfReification HostMonic HostMonoidal >>>> retraction_retraction F >>>> HomFunctor _ []\n      ≃ (reification_rstar GuestHost).\n      apply if_inv.\n      set (@roundtrip_reification_to_reification (TypesEnrichedInJudgments Guest) (TypesEnrichedInJudgments Host)\n        HostMonic HostMonoidal GuestHost) as q.\n      unfold mf_F in *; simpl in *.\n      eapply if_comp.\n      apply q.\n      clear q.\n      unfold mf_F; simpl.\n      unfold pmon_I.\n      apply (if_respects\n        (garrow_functor (TypesEnrichedInJudgments Guest) HostMonic HostMonoidal GuestHost)\n        (FlatteningOfReification HostMonic HostMonoidal >>>> retraction_retraction F)\n        (HomFunctor (TypesL Host) [])\n        (HomFunctor (TypesL Host) [])); [ idtac | apply (if_id _) ].\n      unfold FlatteningOfReification.\n      unfold mf_F; simpl.\n      apply if_inv.\n      eapply if_comp.\n      apply (if_associativity (garrow_functor (TypesEnrichedInJudgments Guest) HostMonic HostMonoidal GuestHost) F\n               (retraction_retraction F)).\n      eapply if_comp; [ idtac | apply if_right_identity ].\n      apply (if_respects\n        (garrow_functor (TypesEnrichedInJudgments Guest) HostMonic HostMonoidal GuestHost)\n        (garrow_functor (TypesEnrichedInJudgments Guest) HostMonic HostMonoidal GuestHost)\n        (F >>>> retraction_retraction F)\n        (functor_id _)).\n      apply (if_id _).\n      apply retraction_composes.\n      Qed.\n\nEnd Flattening.\n\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/ProgrammingLanguageFlattening.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.754914975839675, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.2877883596498728}}
{"text": "Require Import Arith.\nRequire Import ZArith.\nRequire Import List.\nImport ListNotations.\nRequire Import Sorted.\nRequire Import Omega.\nRequire Import Psatz.\n\n\nRequire Import v1.NeutronTactics.\nRequire Import v1.Util.\nRequire Import v1.Multi.\nRequire Import v1.MForall.\nRequire Import v1.ListLemmas.\nRequire Import v1.Wf.\nRequire Import v1.Terminate.\nRequire Import v1.Preservation.\nRequire Import v1.Queue.\nRequire Import v1.System.\nRequire Import v1.SystemWf.\nRequire Import v1.Expr.\nRequire v1.ExprDbl.\nRequire v1.ExprDblStr.\nRequire v1.ExprAbs.\nRequire v1.ExprAbsProofs.\n\nRequire Import v1.EpicsTypes.\nRequire v1.EpicsRecordsBase.\nRequire v1.EpicsRecords.\nRequire Import v1.FloatAux.\nRequire Import v1.FloatAbs.\nRequire Import v1.FloatAbsBase.\nRequire Import v1.Step.\nRequire Import v1.StepAux.\nRequire v1.ControlFlow.\n\nSet Default Timeout 10.\nSet Implicit Arguments.\n\nModule ERB := EpicsRecordsBase.\nModule ER := EpicsRecords.\nModule Abs := FloatAbs.\nModule CF := ControlFlow.\n\n\n\n(* list lemmas *)\n\nLemma lookup_abs_type : forall dba dbt rn ra rt,\n    dbt = database_abs_type dba ->\n    rt = record_abs_type ra ->\n    lookup_abs dba rn = Some ra ->\n    lookup_type dbt rn = Some rt.\nfirst_induction rn; intros0 Heqdbt Heqrt Hnrs;\ndestruct dba; simpl in *; try congruence.\n- subst. simpl. congruence.\n- subst. simpl in *. eauto.\nQed.\n\nLemma lookup_abs_type_eq : forall dba dbt rn ra rt,\n    dbt = database_abs_type dba ->\n    lookup_abs dba rn = Some ra ->\n    lookup_type dbt rn = Some rt ->\n    rt = record_abs_type ra.\nfirst_induction rn; intros0 Heqdbt Hls Hlt;\nsubst dbt; destruct dba; simpl in *; try congruence.\neapply IHrn; eauto.\nQed.\n\n\n\n\nDefinition double_abs (d : e_double) : abs_value :=\n    match B2Z_safe d with\n    | Some x => Some (x, x)\n    | None => None\n    end.\n\nDefinition enum_abs {max} (e : e_enum max) : abs_value :=\n    let '(EEnum _ val _) := e in\n    Some (val, val).\n\nDefinition long_abs (e : e_long) : abs_value :=\n    let '(ELong val _) := e in\n    Some (val, val).\n\nDefinition value_abs (v : value) : abs_value :=\n    match v with\n    | VDouble d => double_abs d\n    | VEnum e => enum_abs e\n    | VLong l => long_abs l\n    | _ => None\n    end.\n\nDefinition record_state_abs s :=\n    match s with\n    | RsCalc (CalcState a2l val) => \n            RaCalc (CalcAbs\n                (multi_map double_abs a2l)\n                (double_abs val))\n    | RsCalcOut (CalcOutState a2l val pval oval tmp0) => \n            RaCalcOut (CalcOutAbs\n                (multi_map double_abs a2l)\n                (double_abs val)\n                (double_abs pval)\n                (double_abs oval)\n                (double_abs tmp0))\n    | RsStrCalcOut (StrCalcOutState a2l _ val _ pval oval _ tmp0) =>\n            RaStrCalcOut (StrCalcOutAbs\n                (multi_map double_abs a2l)\n                (double_abs val)\n                (double_abs pval)\n                (double_abs oval)\n                (double_abs tmp0))\n    | RsArrayCalcOut n (ArrayCalcOutState _ a2l _ val _ pval oval _ tmp0) =>\n            RaArrayCalcOut _ (ArrayCalcOutAbs n\n                (multi_map double_abs a2l)\n                (double_abs val)\n                (double_abs pval)\n                (double_abs oval)\n                (double_abs tmp0))\n    | RsFanout (FanoutState) =>\n            RaFanout (FanoutAbs)\n    | RsAnalogIn (AnalogInState val) =>\n            RaAnalogIn (AnalogInAbs\n                (double_abs val))\n    | RsAnalogOut (AnalogOutState val pval) =>\n            RaAnalogOut (AnalogOutAbs\n                (double_abs val)\n                (double_abs pval))\n    | RsBinaryIn (BinaryInState val) =>\n            RaBinaryIn (BinaryInAbs\n                (enum_abs val))\n    | RsBinaryOut (BinaryOutState val) =>\n            RaBinaryOut (BinaryOutAbs\n                (enum_abs val))\n    | RsMBBO (MBBOState val) =>\n            RaMBBO (MBBOAbs\n                (enum_abs val))\n    | RsStringIn (StringInState _) =>\n            RaStringIn (StringInAbs)\n    | RsStringOut (StringOutState _) =>\n            RaStringOut (StringOutAbs)\n    | RsLongIn (LongInState val) =>\n            RaLongIn (LongInAbs\n                (long_abs val))\n    | RsLongOut (LongOutState val) =>\n            RaLongOut (LongOutAbs\n                (long_abs val))\n    | RsDFanout (DFanoutState val) =>\n            RaDFanout (DFanoutAbs\n                (double_abs val))\n    | RsSeq (SeqState do1_to_a _) =>\n            RaSeq (SeqAbs\n                (multi_map double_abs do1_to_a))\n    | RsWaveform ty n (WaveformState _ _ val) =>\n            RaWaveform _ _ (WaveformAbs ty n)\n    | RsSubarray ty n m (SubarrayState _ _ _ val tmp0) =>\n            RaSubarray _ _ _ (SubarrayAbs ty n m)\n    | RsAsyn (AsynState) =>\n            RaAsyn (AsynAbs)\n    end.\n\nDefinition database_state_abs (dbs : database_state) : database_abs :=\n    map record_state_abs dbs.\n\n\n\n(*\nDefinition interp_update_record f : forall dba rn,\n    forall ra ra',\n    lookup_abs dba rn = Some ra ->\n    f ra = Some ra' ->\n    { dba' | Abs.update_record f dba rn = Some dba' }.\nfirst_induction dba; destruct rn; simpl in *; intros0 Hrs Hf.\n- congruence.\n- congruence.\n- fancy_injr Hrs. rewrite Hf.\n  eexists. reflexivity.\n- forward eapply IHdba as [ dba' Hdba' ]; eauto.  rewrite Hdba'.\n  eexists. reflexivity.\nDefined.\n\n\nDefinition interp_write_field ra fn val :\n    forall rt vt,\n    record_abs_type ra = rt ->\n    record_has_field rt fn vt ->\n    { ra' | Abs.write_field ra fn val = Some ra' }.\nintros0 Hrst Hrhf.\ndestruct (Abs.write_field _ _ _) eqn:Heq.\n{ eexists. reflexivity. }\n\nexfalso.\ninvc Hrhf;\ndestruct_record_abs ra; try discriminate.\nDefined.\n\nDefinition interp_write_record_field dba rn fn val :\n    forall dbt vt,\n    database_abs_type dba = dbt ->\n    wfm_field_access dbt rn fn vt ->\n    { dba' | Abs.write_record_field dba rn fn val = Some dba' }.\nintros0 Hdbt Hwf.\ndestruct (Abs.write_record_field _ _ _ _) eqn:Heq.\n{ eexists. reflexivity. }\n\nexfalso.\n\ninvc Hwf.\n\nforward eapply lookup_length_ex with (ys := dba) as [ ra Hra ]; eauto using map_length.\nforward eapply lookup_abs_type_eq; try eassumption; eauto.\nforward eapply (@interp_write_field ra fn val) as [ ra' Hra' ]; eauto.\n{ subst. eassumption. }\n\nunfold Abs.write_record_field in Heq.\nforward eapply interp_update_record as [ dba' Hdba' ];\n[ | | rewrite Hdba' in Heq; discriminate Heq ]; eauto.\nDefined.\n*)\n\nDefinition merge abs1 abs2 :=\n    match abs1, abs2 with\n    | Some (min1, max1), Some (min2, max2) =>\n            Some (Z.min min1 min2, Z.max max1 max2)\n    | _, _ => None\n    end.\n\nDefinition merge_field ra fn abs :=\n    Abs.read_field ra fn >>= fun abs' =>\n    Abs.write_field ra fn (merge abs abs').\n\nDefinition merge_record_field dba rn fn abs :=\n    Abs.update_record (fun ra => merge_field ra fn abs) dba rn.\n\n\nDefinition havoc_abs a :=\n    match a with\n    | RaCalc (CalcAbs _ _) => \n            RaCalc (CalcAbs (multi_rep 12 None) None)\n    | RaCalcOut (CalcOutAbs _ _ _ _ _) => \n            RaCalcOut (CalcOutAbs (multi_rep 12 None) None None None None)\n    | RaStrCalcOut (StrCalcOutAbs _ _ _ _ _) => \n            RaStrCalcOut (StrCalcOutAbs (multi_rep 12 None) None None None None)\n    | RaArrayCalcOut n (ArrayCalcOutAbs _ _ _ _ _ _) => \n            RaArrayCalcOut _ (ArrayCalcOutAbs n (multi_rep 12 None) None None None None)\n    | RaFanout (FanoutAbs) =>\n            RaFanout (FanoutAbs)\n    | RaAnalogIn (AnalogInAbs _) =>\n            RaAnalogIn (AnalogInAbs None)\n    | RaAnalogOut (AnalogOutAbs _ _) =>\n            RaAnalogOut (AnalogOutAbs None None)\n    | RaBinaryIn (BinaryInAbs _) =>\n            RaBinaryIn (BinaryInAbs None)\n    | RaBinaryOut (BinaryOutAbs _) =>\n            RaBinaryOut (BinaryOutAbs None)\n    | RaMBBO (MBBOAbs _) =>\n            RaMBBO (MBBOAbs None)\n    | RaStringIn (StringInAbs) =>\n            RaStringIn (StringInAbs)\n    | RaStringOut (StringOutAbs) =>\n            RaStringOut (StringOutAbs)\n    | RaLongIn (LongInAbs _) =>\n            RaLongIn (LongInAbs None)\n    | RaLongOut (LongOutAbs _) =>\n            RaLongOut (LongOutAbs None)\n    | RaDFanout (DFanoutAbs _) =>\n            RaDFanout (DFanoutAbs None)\n    | RaSeq (SeqAbs _) =>\n            RaSeq (SeqAbs (multi_rep 10 None))\n    | RaWaveform ty n (WaveformAbs _ _) =>\n            RaWaveform _ _ (WaveformAbs ty n)\n    | RaSubarray ty n m (SubarrayAbs _ _ _) =>\n            RaSubarray _ _ _ (SubarrayAbs ty n m)\n    | RaAsyn (AsynAbs) =>\n            RaAsyn (AsynAbs)\n    end.\n\nDefinition clamp_abs low high abs :=\n    match abs with\n    | Some (low', high') =>\n            let low'' := Z.max low low' in\n            let high'' := Z.min high high' in\n            Some (low'', high'')\n    | None => None\n    end.\n\nDefinition interp_convert abs new_ty :=\n    match new_ty with\n    | TDouble => abs\n    | TLong => clamp_abs (-LONG_MAX) (LONG_MAX - 1) abs\n    | TEnum max => clamp_abs 0 (max - 1) abs\n    | _ => None\n    end.\n\nDefinition interp_set_const dba rn fn val :=\n    let abs := value_abs val in\n    merge_record_field dba rn fn abs.\n\nDefinition interp_copy dba rn fn_src (src_ty : field_type) fn_dest dest_ty :=\n    let f ra :=\n        Abs.read_field ra fn_src >>= fun abs =>\n        let abs' := interp_convert abs dest_ty in\n        merge_field ra fn_dest abs' in\n    Abs.update_record f dba rn.\n\nDefinition interp_read_link dba rn il (il_ty : field_type) fn f_ty :=\n    Abs.read_record_field dba (fl_rn il) (fl_fn il) >>= fun abs =>\n    let abs' := interp_convert abs f_ty in\n    merge_record_field dba rn fn abs'.\n\nDefinition interp_write_link dba rn fn (f_ty : field_type) ol ol_ty :=\n    Abs.read_record_field dba rn fn >>= fun abs =>\n    let abs' := interp_convert abs ol_ty in\n    merge_record_field dba (fl_rn ol) (fl_fn ol) abs'.\n\nDefinition interp_calculate dba rn e fn_out :=\n    lookup dba rn >>= fun ra =>\n    ExprAbs.denote e >>= fun f =>\n    match ra with\n    | RaCalc (CalcAbs a2l val) =>\n            let (a2l', result) := f a2l in\n            let a2l'' := multi_zip merge a2l a2l' in\n            Some (RaCalc (CalcAbs a2l'' val), result)\n    | RaCalcOut (CalcOutAbs a2l val pval oval tmp0) =>\n            let (a2l', result) := f a2l in\n            let a2l'' := multi_zip merge a2l a2l' in\n            Some (RaCalcOut (CalcOutAbs a2l'' val pval oval tmp0), result)\n    | _ => None\n    end >>= fun x => let '(ra', result) := x in\n    merge_field ra' fn_out result >>= fun ra'' =>\n    Abs.update_record (fun _ => Some ra'') dba rn.\n\nDefinition interp_havoc_update dba rn :=\n    Abs.update_record (fun ra => Some (havoc_abs ra)) dba rn.\n\nDefinition interp_havoc_write dba (rn : record_name) ol (ol_ty : field_type) :=\n    merge_record_field dba (fl_rn ol) (fl_fn ol) None.\n\nDefinition interp_op dba rn op :=\n    match op with\n    | MSetConst fn val =>\n            interp_set_const dba rn fn val\n    | MCopy fn_src src_ty fn_dest dest_ty =>\n            interp_copy dba rn fn_src src_ty fn_dest dest_ty\n    | MReadLink il il_ty fn f_ty =>\n            interp_read_link dba rn il il_ty fn f_ty\n    | MWriteLink fn f_ty ol ol_ty =>\n            interp_write_link dba rn fn f_ty ol ol_ty\n    | MCalculate expr fn_out =>\n            interp_calculate dba rn expr fn_out\n    | MHavocUpdate =>\n            interp_havoc_update dba rn\n    | MHavocWrite ol ol_ty =>\n            interp_havoc_write dba rn ol ol_ty\n    | _ => Some dba\n    end.\n\nDefinition interp_op_rec rn :=\n    let fix go dba op :=\n        let fix go_list dba ops :=\n            match ops with\n            | [] => Some dba\n            | op :: ops => go dba op >>= fun dba => go_list dba ops\n            end in\n        interp_op dba rn op >>= fun dba =>\n        match op with\n        | MCalcCond _ _ _ body => go_list dba body\n        | MScheduleCallback _ code => go_list dba code\n        | _ => Some dba\n        end in go.\n\nDefinition interp_op_rec_list rn :=\n    let go := interp_op_rec rn in\n    let fix go_list dba ops :=\n        match ops with\n        | [] => Some dba\n        | op :: ops => go dba op >>= fun dba => go_list dba ops\n        end in go_list.\n\nDefinition interp_ops dba rn ops := interp_op_rec_list rn dba ops.\n\nDefinition interp_prog dba dbp :=\n    let fix go dba xs :=\n        match xs with\n        | [] => Some dba\n        | (rn, rp) :: xs =>\n            interp_ops dba rn (rp_code rp) >>= fun dba =>\n            go dba xs\n        end in\n    go dba (numbered dbp).\n\n\n\nInductive refine_val : abs_value -> value -> Prop :=\n| RvTop : forall v, refine_val None v\n| RvDouble : forall d z min max,\n        fwhole_eq d z ->\n        (min <= z <= max)%Z ->\n        refine_val (Some (min, max)) (VDouble d).\n\nInductive refine_record : record_abs -> record_state -> Prop :=\n| RefineRecord : forall ra rs,\n        record_abs_type ra = record_state_type rs ->\n        (forall fn,\n            forall va, Abs.read_field ra fn = Some va ->\n            forall vs, read_field rs fn = Some vs ->\n            refine_val va vs) ->\n        refine_record ra rs.\n\nDefinition refine dba dbs :=\n    Forall2 refine_record dba dbs.\n\n\n\nInductive wider : abs_value -> abs_value -> Prop :=\n| WiderTop : forall a, wider a None\n| WiderRange : forall min1 max1 min2 max2,\n        min2 <= min1 ->\n        max1 <= max2 ->\n        wider (Some (min1, max1)) (Some (min2, max2)).\n\nLemma wider_refl : forall a, wider a a.\ndestruct a; try constructor.\ndestruct p; try constructor; lia.\nQed.\n\nLemma refine_val_wider : forall a a' v,\n    refine_val a v ->\n    wider a a' ->\n    refine_val a' v.\ndestruct a, a', v; intros0 Hr Hw;\ninvc Hr; invc Hw; try solve [ econstructor ].\n- econstructor.\n  + eassumption.\n  + lia.\nQed.\n\n\nLemma lookup_refine : forall dbs rn rs dba ra,\n    refine dba dbs ->\n    lookup dbs rn = Some rs ->\n    lookup dba rn = Some ra ->\n    refine_record ra rs.\nunfold lookup, refine. intros.\neapply Forall2_nth_error; eauto.\nQed.\n\nLemma read_record_field_refine : forall dbs rn fn val dba ra a,\n    refine dba dbs ->\n    read_record_field dbs rn fn = Some val ->\n    lookup dba rn = Some ra ->\n    Abs.read_field ra fn = Some a ->\n    refine_val a val.\nintros0 Hr Hst_rrf Habs_rn Habs_fn.\n\nunfold read_record_field in Hst_rrf.\ndestruct (lookup_state _ _) eqn:Hst_rn; [ | discriminate ].\nsimpl in Hst_rrf. rename Hst_rrf into Hst_fn.\nforward eapply lookup_refine as HH; eauto.\ninvc HH. eauto.\nQed.\n\n\nLemma update_record_lookup_eq : forall f dbs rn dbs' rn' rs rs',\n    update_record f dbs rn = Some dbs' ->\n    lookup dbs rn' = Some rs ->\n    lookup dbs' rn' = Some rs' ->\n    rn = rn' ->\n    f rs = Some rs'.\nfirst_induction rn; intros0 Hup Hlook Hlook' Hrn; subst rn'.\n\n- destruct dbs, dbs'; simpl in *; try discriminate.\n  break_match; try discriminate.\n  congruence.\n\n- destruct dbs, dbs'; simpl in *; try discriminate.\n  break_match; try discriminate.\n  inject_some.\n  specialize (IHrn ?? ?? ?? ?? ?? ?? ** ** ** ***). assumption.\nQed.\n\nLemma update_record_lookup_ne : forall f dbs rn dbs' rn' rs rs',\n    update_record f dbs rn = Some dbs' ->\n    lookup dbs rn' = Some rs ->\n    lookup dbs' rn' = Some rs' ->\n    rn <> rn' ->\n    rs = rs'.\nfirst_induction rn'; intros0 Hup Hlook Hlook' Hrn.\n\n- destruct rn; try congruence.\n  destruct dbs, dbs'; simpl in *; try discriminate.\n  break_match; try discriminate.\n  congruence.\n\n- destruct dbs, dbs'; simpl in *; try discriminate.\n  destruct rn.\n  + break_match; try discriminate.\n    congruence.\n  + break_match; try discriminate.\n    inject_some. eapply IHrn'; eauto.\nQed.\n\nLemma update_record_length : forall f dbs rn dbs',\n    update_record f dbs rn = Some dbs' ->\n    length dbs = length dbs'.\ninduction dbs; intros0 Hup; simpl in *; try discriminate.\nbreak_match; break_match; try discriminate.\n\n- destruct dbs'; inject_some. simpl. reflexivity.\n\n- destruct dbs'; inject_some. simpl.\n  specialize (IHdbs ?? ?? **). congruence.\nQed.\n\nLemma update_record_forall : forall f dbs rn dbs' rs0,\n    update_record f dbs rn = Some dbs' ->\n    lookup dbs rn = Some rs0 ->\n    Forall2 (fun rs rs' => rs = rs' \\/ (rs = rs0 /\\ f rs = Some rs')) dbs dbs'.\nintros0 Hup Hlook.\neapply nth_error_Forall2.\n  { eauto using update_record_length. }\nintros rn' rs rs' ? ?.\ndestruct (eq_nat_dec rn rn').\n- right. split.\n  + subst. unfold lookup in Hlook. congruence.\n  + eapply update_record_lookup_eq; eauto.\n- left.\n  eapply update_record_lookup_ne; eauto.\nQed.\n\n\nLemma update_record_refine : forall dba f dbs rn dbs',\n    (forall ra rs rs',\n        lookup dba rn = Some ra ->\n        lookup dbs rn = Some rs ->\n        f rs = Some rs' ->\n        refine_record ra rs ->\n        refine_record ra rs') ->\n    update_record f dbs rn = Some dbs' ->\n    refine dba dbs ->\n    refine dba dbs'.\nfirst_induction dbs; destruct rn; intros0 Hf Hupd Href; try discriminate; simpl in *.\n- rename a into rs. invc Href. rename x into ra. rename l into dba.\n  destruct (f rs) as [ rs' | ] eqn:?; [ | discriminate Hupd ].\n  inject_some.\n  specialize (Hf ?? ?? ?? *** *** ** **).\n  constructor; eauto.\n- rename a into rs. invc Href. rename x into ra. rename l into dba.\n  destruct (update_record _ _ _) as [ dbs'' | ] eqn:?; [ | discriminate Hupd ].\n  inject_some.\n  constructor; eauto.\n  eapply IHdbs; eauto.\nQed.\n\n\nRequire Import ProofIrrelevance.\n\nLemma write_field_read_eq' : forall rs fn val rs',\n    write_field rs fn val = Some rs' ->\n    read_field rs' fn = Some val.\nintros0 Hwf; destruct_record rs as [st]; destruct fn;\ntry match goal with [ |- read_field _ (f_tmp ?n) = _ ] => destruct n end;\ntry discriminate Hwf.\n\nall: destruct val; try discriminate Hwf.\n\nall: cbv  [write_field bind_option unwrap_double unwrap_string unwrap_long] in Hwf;\n     try break_match; try discriminate; (* VEnum cases: get a separate eqn for unwrap_enum *)\n     fancy_injr <- Hwf; destruct st;\n     cbv -[multi_get multi_set];\n     try rewrite multi_set_get; (* multi fields *)\n     try reflexivity.\n\nall: try solve [\n    (* VEnum handling *)\n    simpl in Heqo; break_match; try discriminate;\n    subst max;\n    unfold eq_rect_r in *; rewrite <- eq_rect_eq in *;\n    congruence\n].\n\nall: try solve [\n    (* VArray handling *)\n    simpl in *;\n    do 2 (break_match; try discriminate);\n    subst elem; subst size;\n    unfold eq_rect_r in *; rewrite <- eq_rect_eq, <- eq_rect_eq in *;\n    congruence\n].\n\nQed.\n\nLemma write_field_read_eq : forall rs fn val rs' fn',\n    write_field rs fn val = Some rs' ->\n    fn = fn' ->\n    read_field rs' fn' = Some val.\nintros0 Hwf Hfn.  subst fn'.  eauto using write_field_read_eq'.\nQed.\n\nLemma write_field_read_ne : forall rs fn val rs' fn',\n    write_field rs fn val = Some rs' ->\n    fn <> fn' ->\n    read_field rs fn' = read_field rs' fn'.\nintros0 Hwf Hne; destruct_record rs as [st]; destruct fn;\ntry match type of Hne with f_tmp ?n <> _ => destruct n end;\ntry discriminate Hwf.\n\nall: cbv  [write_field bind_option unwrap_double unwrap_string unwrap_long] in Hwf;\n     repeat break_match; try discriminate; (* both VEnum and other cases *)\n     fancy_injr <- Hwf; destruct st;\n     cbv -[multi_get multi_set];\n     destruct fn'; try reflexivity; try congruence.\n\nall: try solve [\n    (* multi field case *)\n    destruct i as [i Hi], i0 as [i0 Hi0];\n    destruct (eq_nat_dec i i0);\n        [ contradict Hne; subst; f_equal; f_equal; eapply proof_irrelevance | ];\n    rewrite multi_set_get_other by (simpl; congruence);\n    reflexivity\n].\n\n(* f_tmp cases *)\nall: match type of Hne with _ <> f_tmp ?n => destruct n end; try congruence.\nQed.\n\nLemma write_field_refine : forall rs fn val rs' ra a,\n    refine_record ra rs ->\n    write_field rs fn val = Some rs' ->\n    Abs.read_field ra fn = Some a ->\n    refine_val a val ->\n    refine_record ra rs'.\nintros0 Hr Hst_fn Habs_fn Hrv.\ninvc Hr. constructor.  { erewrite <- write_field_preserves_state_type; eauto. }\nintros fn' ? Habs_fn' ? Hst_fn'.\ndestruct (field_name_eq_dec fn fn').\n\n- forward eapply write_field_read_eq with (fn := fn) (fn' := fn'); eauto.\n  congruence.\n\n- forward eapply write_field_read_ne with (fn := fn) (fn' := fn'); eauto.\n  on _, eapply_; eauto. congruence.\n\nQed.\n\nLemma write_record_field_refine : forall dbs rn fn val dbs' dba ra a,\n    refine dba dbs ->\n    write_record_field dbs rn fn val = Some dbs' ->\n    lookup dba rn = Some ra ->\n    Abs.read_field ra fn = Some a ->\n    refine_val a val ->\n    refine dba dbs'.\nintros0 Hr Hst_wrf Habs_rn Habs_fn Hrv.\n\nunfold write_record_field in Hst_wrf.\nunfold refine in *.\n\nforward eapply lookup_length_ex with (ys := dbs) as HH; eauto using Forall2_length.\n  destruct HH as [rs Hst_rn].\neapply nth_error_Forall2.\n  { erewrite Forall2_length by eassumption. eauto using update_record_length. }\nintros rn' ra' rs' Hra Hrs.\ndestruct (eq_nat_dec rn rn').\n\n- subst rn'.\n  replace ra' with ra in * by (unfold lookup in *; congruence).\n  forward eapply update_record_lookup_eq; eauto. cbv beta in *.\n  eapply write_field_refine; eauto.\n  eapply Forall2_nth_error; eauto.\n\n- forward eapply lookup_length_ex with (ys := dbs) as HH; eauto.\n    symmetry. eauto using update_record_length.\n    destruct HH as [rs0' Hrs0'].\n  forward eapply update_record_lookup_ne with (rn := rn) (rn' := rn'); eauto.\n  eapply Forall2_nth_error; eauto. unfold lookup in *. congruence.\nQed.\n\n\nLemma convert_value_noop : forall val ty,\n    value_type val = ty ->\n    convert_value val ty = Some val.\nintros0 Hty.\ndestruct val, ty; try discriminate Hty; try reflexivity.\n\n(* enum *)\n- simpl in Hty. invc Hty. simpl. repeat break_match.\n  + do 3 f_equal. eapply proof_irrelevance.\n  + exfalso. lia.\n\n(* long *)\n- simpl. break_match. reflexivity.\n\n(* array *)\n- simpl in Hty. invc Hty. simpl. repeat break_match.\n  + reflexivity.\n  + congruence.\n  + congruence.\nQed.\n\n\n\n\n\n\n\nInductive error :=\n| ENoRecord : record_name -> error\n| ENoField : field_name -> error\n| ENotCalc : record_name -> error\n| EBadExpr : record_name -> error\n| ENotWider : abs_value -> abs_value -> error\n| EBadConst : value -> abs_value -> error\n| EBadType : field_type -> field_type -> error\n| ENotImplemented : micro -> error\n| ELenMismatch : nat -> nat -> error\n.\n\nLtac die x := right; exact x.\nLtac die_auto :=\n    match goal with\n    | [ e : list error |- _ ] => die e\n    end.\n\nDefinition check_wider : forall a a',\n    { wider a a' } + { ~ wider a a' }.\ndestruct a, a'; try solve [ right; inversion 1 | left; econstructor ].\n- destruct p as [min1 max1], p0 as [min2 max2].\n  destruct (Z_le_dec min2 min1); [ | right; inversion 1; lia ].\n  destruct (Z_le_dec max1 max2); [ | right; inversion 1; lia ].\n  left. constructor; assumption.\nQed.\n\nDefinition check_refine_const : forall a v,\n    { refine_val a v } + { ~ refine_val a v }.\ndestruct a, v; try solve [left; constructor | right; inversion 1].\n\n- rename e into x.\n  destruct (B2Z_safe x) as [ z | ] eqn:?; cycle 1.\n    { right. inversion 1. forward eapply B2Z_safe_complete; eauto. congruence.  }\n\n  destruct p as [min max].\n  destruct (Z_le_gt_dec min z); cycle 1.\n    { right. inversion 1. forward eapply B2Z_safe_complete; eauto.\n      replace z0 with z in * by congruence. lia. }\n  destruct (Z_le_gt_dec z max); cycle 1.\n    { right. inversion 1. forward eapply B2Z_safe_complete; eauto.\n      replace z0 with z in * by congruence. lia. }\n\n  left. econstructor; eauto using B2Z_safe_correct.\nQed.\n\n\nDefinition db_step_ok dba rn op :=\n    forall dbs dbs',\n    database_state_type dbs = database_abs_type dba ->\n    refine dba dbs ->\n    db_step rn op dbs dbs' ->\n    refine dba dbs'.\n\nDefinition check_set_const : forall dba rn fn val,\n    db_step_ok dba rn (MSetConst fn val) + list error.\nintros.\ndestruct (lookup dba rn) as [ra | ] eqn:?; [ | die [ENoRecord rn] ].\ndestruct (Abs.read_field ra fn) as [dest_abs | ] eqn:?; [ | die [ENoField fn] ].\ndestruct (check_refine_const dest_abs val); [ | die [EBadConst val dest_abs] ].\n\nleft. unfold db_step_ok. intros0 Hty Hr Hstep. invc Hstep.\neapply write_record_field_refine; try eassumption.\nDefined.\n\nDefinition check_copy : forall dba rn fn_src src_ty fn_dest dest_ty,\n    db_step_ok dba rn (MCopy fn_src src_ty fn_dest dest_ty) + list error.\nintros.\ndestruct (lookup dba rn) as [ra | ] eqn:?; [ | die [ENoRecord rn] ].\ndestruct (Abs.read_field ra fn_src) as [src_abs | ] eqn:?; [ | die [ENoField fn_src] ].\ndestruct (Abs.read_field ra fn_dest) as [dest_abs | ] eqn:?; [ | die [ENoField fn_dest] ].\ndestruct (check_wider src_abs dest_abs); [ | die [ENotWider src_abs dest_abs] ].\ndestruct (field_type_eq_dec src_ty dest_ty); [ | die [EBadType src_ty dest_ty] ].\n\nleft. unfold db_step_ok. intros0 Hty Hr Hstep. invc Hstep.\neapply write_record_field_refine; try eassumption.\neapply refine_val_wider; try eassumption.\nrewrite convert_value_noop in *; eauto. inject_some.\neapply read_record_field_refine; try eassumption.\nDefined.\n\nDefinition check_read_link : forall dba rn il il_ty fn f_ty,\n    db_step_ok dba rn (MReadLink il il_ty fn f_ty) + list error.\nintros.\ndestruct (lookup dba rn) as [ra | ] eqn:?; [ | die [ENoRecord rn] ].\ndestruct (lookup dba (fl_rn il)) as [ra' | ] eqn:?; [ | die [ENoRecord (fl_rn il)] ].\ndestruct (Abs.read_field ra' (fl_fn il)) as [src_abs | ] eqn:?; [ | die [ENoField (fl_fn il)] ].\ndestruct (Abs.read_field ra fn) as [dest_abs | ] eqn:?; [ | die [ENoField fn] ].\ndestruct (check_wider src_abs dest_abs); [ | die [ENotWider src_abs dest_abs] ].\ndestruct (field_type_eq_dec il_ty f_ty); [ | die [EBadType il_ty f_ty] ].\n\nleft. unfold db_step_ok. intros0 Hty Hr Hstep. invc Hstep.\neapply write_record_field_refine; try eassumption.\neapply refine_val_wider; try eassumption.\nrewrite convert_value_noop in *; eauto. inject_some.\neapply read_record_field_refine; try eassumption.\nDefined.\n\nDefinition check_write_link : forall dba rn fn f_ty ol ol_ty,\n    db_step_ok dba rn (MWriteLink fn f_ty ol ol_ty) + list error.\nintros.\ndestruct (lookup dba rn) as [ra | ] eqn:?; [ | die [ENoRecord rn] ].\ndestruct (lookup dba (fl_rn ol)) as [ra' | ] eqn:?; [ | die [ENoRecord (fl_rn ol)] ].\ndestruct (Abs.read_field ra fn) as [src_abs | ] eqn:?; [ | die [ENoField fn] ].\ndestruct (Abs.read_field ra' (fl_fn ol)) as [dest_abs | ] eqn:?; [ | die [ENoField (fl_fn ol)] ].\ndestruct (check_wider src_abs dest_abs); [ | die [ENotWider src_abs dest_abs] ].\ndestruct (field_type_eq_dec f_ty ol_ty); [ | die [EBadType f_ty ol_ty] ].\n\nleft. unfold db_step_ok. intros0 Hty Hr Hstep. invc Hstep.\neapply write_record_field_refine; try eassumption.\neapply refine_val_wider; try eassumption.\nrewrite convert_value_noop in *; eauto. inject_some.\neapply read_record_field_refine; try eassumption.\nDefined.\n\nDefinition check_calc : forall ra,\n    { a2l, val | ra = RaCalc (CalcAbs a2l val) } +\n    { forall abs, ra <> RaCalc abs }.\nintros.\ndestruct_record_abs ra; try solve [right; intros; discriminate ].\n- left. destruct a. eexists. reflexivity.\nQed.\n\nDefinition check_list : forall A (P : A -> Prop) xs\n        (check_one : forall x, P x + list error),\n    Forall P xs + list error.\ninduction xs; intros.\n- left. constructor.\n- rename a into x.\n  destruct (check_one x); [ | die_auto ].\n  destruct (IHxs check_one); [ | die_auto ].\n  left. constructor; eauto.\nDefined.\n\nDefinition check_multi : forall n (A : Set) (P : A -> Prop) (x : multi n A)\n        (check_one : forall x, P x + list error),\n    MForall P x + list error.\nintros.\ndestruct (check_list P (multi_to_list x) check_one); [ | die_auto ].\nleft. rewrite MForall_Forall. auto.\nDefined.\n\nDefinition check_list2 : forall A B (P : A -> B -> Prop) xs ys\n        (check_one : forall x y, P x y + list error),\n    Forall2 P xs ys + list error.\ninduction xs; destruct ys; intros.\n- left. constructor.\n- die [ELenMismatch 0 (S (length ys))].\n- die [ELenMismatch (S (length xs)) 0].\n- rename a into x. rename b into y.\n  destruct (check_one x y); [ | die_auto ].\n  destruct (IHxs ys check_one); [ | die_auto ].\n  left. constructor; eauto.\nDefined.\n\nDefinition check_multi2 : forall n (A B : Set) (P : A -> B -> Prop)\n        (x : multi n A) (y : multi n B)\n        (check_one : forall x y, P x y + list error),\n    MForall2 P x y + list error.\nintros.\ndestruct (check_list2 P (multi_to_list x) (multi_to_list y) check_one); [ | die_auto ].\nleft. rewrite MForall2_Forall2. auto.\nDefined.\n\nDefinition check_wider' : forall val val',\n    wider val val' + list error.\nintros.\ndestruct (check_wider val val'); [ | die [ENotWider val val'] ].\nleft. auto.\nQed.\n\nDefinition state_A_to_L s :=\n    match s with\n    | RsCalc st => Some (EpicsRecordsBase.calc_A_to_L st)\n    | RsCalcOut st => Some (EpicsRecordsBase.calc_out_A_to_L st)\n    | _ => None\n    end.\n\nDefinition abs_A_to_L a :=\n    match a with\n    | RaCalc abs => Some (FloatAbsBase.calc_A_to_L abs)\n    | RaCalcOut abs => Some (FloatAbsBase.calc_out_A_to_L abs)\n    | _ => None\n    end.\n\nLemma abs_A_to_L_ex : forall rs ra sa2l,\n    refine_record ra rs ->\n    state_A_to_L rs = Some sa2l ->\n    exists aa2l, abs_A_to_L ra = Some aa2l.\nintros0 Hrefine Hsa2l.\ndestruct_record rs as [st]; try discriminate Hsa2l; destruct st.\nall: simpl in Hsa2l; inject_some.\nall: invc Hrefine; unfold record_state_type in *.\nall: destruct_record_abs ra as [abs]; try discriminate; destruct abs.\nall: eexists; reflexivity.\nQed.\n\nLemma run_calculate_record_effect : forall f fn_out rs rs',\n    run_calculate_record f fn_out rs = Some rs' ->\n    exists a2l a2l' out',\n        state_A_to_L rs = Some a2l /\\\n        f a2l = (a2l', out') /\\\n        state_A_to_L rs' = Some a2l' /\\\n        read_field rs' fn_out = Some (VDouble out').\nintros0 Hrun.\n\ndestruct_record rs as [ st ]; try discriminate.\nall: destruct st; simpl in Hrun.\nall: destruct (f _) as (a2l', out') eqn:?.\nall: destruct fn_out; try discriminate.\nall: inject_some; simpl.\nall: eauto 7.\nQed.\n\nLemma run_calculate_record_preserved : forall f fn_out rs rs' fn,\n    run_calculate_record f fn_out rs = Some rs' ->\n    (forall i, fn <> f_A_to_L i) ->\n    fn <> fn_out ->\n    read_field rs' fn = read_field rs fn.\nintros0 Hrun Ha2l Hval.\ndestruct_record rs as [ st ]; try discriminate.\nall: destruct st; simpl in Hrun.\nall: destruct (f _) as (a2l', out').\nall: destruct fn_out; try discriminate.\nall: inject_some; simpl.\nall: destruct fn; try solve [exfalso; congruence | reflexivity].\nQed.\n\nLemma A_to_L_state_read_field : forall rs a2l i val,\n    state_A_to_L rs = Some a2l ->\n    read_field rs (f_A_to_L i) = Some (VDouble val) <-> (a2l !! i) = val.\nintros0 Ha2l.\ndestruct_record rs as [st]; try discriminate; destruct st.\nall: simpl in Ha2l; inject_some.\nall: compute -[multi_get].\nall: intuition congruence.\nQed.\n\nLemma A_to_L_abs_read_field : forall ra a2l i val,\n    abs_A_to_L ra = Some a2l ->\n    Abs.read_field ra (f_A_to_L i) = Some val <-> (a2l !! i) = val.\nintros0 Ha2l.\ndestruct_record_abs ra as [abs]; try discriminate; destruct abs.\nall: simpl in Ha2l; inject_some.\nall: compute -[multi_get].\nall: intuition congruence.\nQed.\n\nLemma A_to_L_MForall2 : forall (P : _ -> _ -> Prop) rs ra sa2l aa2l,\n    state_A_to_L rs = Some sa2l ->\n    abs_A_to_L ra = Some aa2l ->\n    (forall i sv av,\n        read_field rs (f_A_to_L i) = Some (VDouble sv) ->\n        Abs.read_field ra (f_A_to_L i) = Some av ->\n        P sv av) <->\n    MForall2 P sa2l aa2l.\nintros0 Hrs Hra. split; intro HH.\n\n- rewrite MForall2_forall. intros. subst. eapply HH.\n  + rewrite A_to_L_state_read_field; eauto.\n  + rewrite A_to_L_abs_read_field; eauto.\n\n- rewrite MForall2_forall in HH. intros. eapply HH.\n  + rewrite <- A_to_L_state_read_field; eauto.\n  + rewrite <- A_to_L_abs_read_field; eauto.\nQed.\n\nLemma refine_val_double_iff' : forall dty aty dbl abs,\n    (match dty as dty_, aty as aty_\n        return ty_denote ExprAbsProofs.D dty_ -> ty_denote ExprAbsProofs.A aty_ -> Prop with\n    | ExprDbl.Nil, ExprAbs.Nil => fun dbl abs => True\n    | ExprDbl.Dbl, ExprAbs.Abs => fun dbl abs => refine_val abs (VDouble dbl)\n    | _, _ => fun dbl abs => False\n    end) dbl abs <->\n    ExprAbsProofs.refine_value dty aty dbl abs.\nintros. split; intro HH.\n- destruct dty, aty; try solve [exfalso; auto].\n  + destruct dbl, abs. constructor.\n  + invc HH; do 2 econstructor; eauto.\n- destruct HH; auto.\n  on >ExprAbsProofs.refine_dbl, invc.\n  all: econstructor; eauto.\nQed.\n\nLemma refine_val_double_iff : forall dbl abs,\n    refine_val abs (VDouble dbl) <->\n    ExprAbsProofs.refine_value ExprDbl.Dbl ExprAbs.Abs dbl abs.\nintros.\nrewrite <- refine_val_double_iff'. split; auto.\nQed.\nHint Rewrite -> refine_val_double_iff.\nHint Rewrite <- refine_val_double_iff.\n\nLemma refine_record_A_to_L : forall ra rs aa2l sa2l,\n    refine_record ra rs ->\n    abs_A_to_L ra = Some aa2l ->\n    state_A_to_L rs = Some sa2l ->\n    MForall2 (fun s a => refine_val a (VDouble s)) sa2l aa2l.\nintros. erewrite <- A_to_L_MForall2; eauto.\nintros. on >refine_record, invc.  eauto.\nQed.\n\nLemma refine_record_A_to_L' : forall ra rs aa2l sa2l,\n    refine_record ra rs ->\n    abs_A_to_L ra = Some aa2l ->\n    state_A_to_L rs = Some sa2l ->\n    MForall2 (ExprAbsProofs.refine_value ExprDbl.Dbl ExprAbs.Abs) sa2l aa2l.\nintros. forward eapply refine_record_A_to_L; eauto.\nrewrite -> MForall2_Forall2 in *.\ncompute -[multi_to_list e_double abs_value]. (* modifies implicit arguments *)\nremember (multi_to_list sa2l) as sa2l'.\nremember (multi_to_list aa2l) as aa2l'.\nlist_magic_on (sa2l', (aa2l', tt)).\nrewrite <- refine_val_double_iff. auto.\nQed.\n\nDefinition is_A_to_L_dec : forall fn,\n    { i | fn = f_A_to_L i } + { ~ exists i, fn = f_A_to_L i }.\ndestruct fn; try solve [ right; inversion 1; discriminate ].\nleft; eauto.\nDefined.\n\nLemma run_calculate_record_refine : forall expr f f' fn_out rs rs' ra a2l a2l' out out',\n    ExprDbl.denote expr = Some f ->\n    ExprAbs.denote expr = Some f' ->\n    f' a2l = (a2l', out') ->\n    abs_A_to_L ra = Some a2l ->\n    MForall2 wider a2l' a2l ->\n    Abs.read_field ra fn_out = Some out ->\n    wider out' out ->\n    refine_record ra rs ->\n    run_calculate_record f fn_out rs = Some rs' ->\n    refine_record ra rs'.\nintros0 Hf Hf' Hcalc' Hra_a2l Ha2l Hra_out Hout Hrefine Hcalc_rec.\ninv Hrefine. rename H0 into Hrefine'. constructor.\n  { erewrite <- run_calculate_record_preserves_state_type; eauto. }\nintros0 Hread. intros0 Hread'.\nspecialize (Hrefine' _ _ Hread).\n\nforward eapply run_calculate_record_effect as HH; eauto.\n  destruct HH as (sa2l & sa2l' & sout' & ? & ? & ? & ?).\n\nforward eapply ExprAbsProofs.denote_refine as HH; eauto.\n  destruct HH as (f'' & ? & ?).\n  replace f'' with f' in * by congruence.\nforward refine (ExprAbsProofs.refine_state_fn_noxvar_dbl_abs_inv _ _ _) as Hfrel; eauto.\ndo 6 spec_evar Hfrel. spec_assert Hfrel; [ | do 2 spec Hfrel by eassumption ].\n  { eapply refine_record_A_to_L'; eauto. }\ndestruct Hfrel as [Hrel_a2l Hrel_out].\n\ndestruct (field_name_eq_dec fn fn_out).\n  { subst fn.\n    replace va with out in * by congruence.\n    eapply refine_val_wider; eauto.\n    replace vs with (VDouble sout') in * by congruence.\n    rewrite refine_val_double_iff. auto. }\n\ndestruct (is_A_to_L_dec fn) as [ [i ?] | ? ].\n  { subst fn.\n    remember (sa2l' !! i) as vdbl. symmetry in Heqvdbl.\n    rewrite <- A_to_L_state_read_field in Heqvdbl by eauto.\n    rewrite A_to_L_abs_read_field in Hread by eauto.\n    replace vs with (VDouble vdbl) by congruence.\n    rewrite A_to_L_state_read_field in Heqvdbl by eauto.\n    subst va. subst vdbl.\n    eapply refine_val_wider; cycle 1.  { eapply MForall2_get; try eassumption. }\n    rewrite refine_val_double_iff. eapply MForall2_get. auto. }\n\n  { eapply Hrefine'.\n    erewrite <- run_calculate_record_preserved; try eassumption.\n    intros. intro. on _, eapply_. eauto. }\n\nQed.\n\n\nDefinition check_calculate : forall dba rn expr fn_out,\n    db_step_ok dba rn (MCalculate expr fn_out) + list error.\nintros.\ndestruct (lookup dba rn) as [ra | ] eqn:?; [ | die [ENoRecord rn] ].\ndestruct (abs_A_to_L ra) as [a2l_abs | ] eqn:?; [ | die [ENotCalc rn] ].\ndestruct (Abs.read_field ra fn_out) as [out_abs | ] eqn:?; [ | die [ENoField fn_out] ].\ndestruct (ExprAbs.denote expr) as [ calc | ] eqn:?; [ | die [EBadExpr rn] ].\ndestruct (calc a2l_abs) as [a2l' out'] eqn:?.\ndestruct (check_multi2 _ _ a2l' a2l_abs check_wider'); [ | die_auto ].\ndestruct (check_wider out' out_abs); [ | die [ENotWider out' out_abs] ].\n\nleft. unfold db_step_ok. intros0 Hty Hr Hstep. invc Hstep.\nunfold run_calculate in *.\neapply update_record_refine; try eassumption. intros.\nreplace ra0 with ra in * by congruence.\neapply run_calculate_record_refine; try eassumption.\nDefined.\n\nDefinition check_havoc_write : forall dba rn ol ol_ty,\n    db_step_ok dba rn (MHavocWrite ol ol_ty) + list error.\nintros.\ndestruct (lookup dba (fl_rn ol)) as [ra | ] eqn:?; [ | die [ENoRecord (fl_rn ol)] ].\ndestruct (Abs.read_field ra (fl_fn ol)) as [dest_abs | ] eqn:?; [ | die [ENoField (fl_fn ol)] ].\ndestruct (check_wider None dest_abs); [ | die [ENotWider None dest_abs] ].\n\nleft. unfold db_step_ok. intros0 Hty Hr Hstep. invc Hstep.\neapply write_record_field_refine; try eassumption.\neapply refine_val_wider; try eassumption.\nconstructor.\nDefined.\n\nLtac break_tmp_idx :=\n    match goal with\n    | [ |- context [ f_tmp ?n ] ] => destruct n\n    end.\n\nLemma read_field_has_field : forall ra fn abs,\n    Abs.read_field ra fn = Some abs ->\n    exists ty, record_has_field (record_abs_type ra) fn ty.\ndestruct fn, ra; try break_tmp_idx; intros0 Hrf; try discriminate Hrf.\nall: eexists; try constructor.\nQed.\n\nDefinition check_havoc_update : forall dba rn,\n    db_step_ok dba rn (MHavocUpdate) + list error.\nintros.\ndestruct (lookup dba rn) as [ra | ] eqn:?; [ | die [ENoRecord rn] ].\nforward eapply check_list with (xs := all_fields)\n    (P := fun fn => Abs.read_field ra fn = None \\/ Abs.read_field ra fn = Some None)\n    as HH.\n  { intro fn.\n    destruct (Abs.read_field ra fn) as [abs | ] eqn:?; [ | left; solve [auto] ].\n    destruct abs eqn:?; [ die [ENotWider None abs] | ].\n    left. auto. }\n  destruct HH; [ | die_auto ].\n\nleft. unfold db_step_ok. intros0 Hty Hr Hstep. invc Hstep.\neapply update_record_refine; eauto.\nintros.\nreplace ra0 with ra in * by congruence.  clear ra0.\nreplace rs0 with rs in * by congruence.  clear rs0.\nreplace rs'0 with rs' in * by congruence.  clear rs'0.\n\non >refine_record, invc.\nconstructor. { congruence. }\nintros.\n\nassert (In fn all_fields).\n  { forward eapply read_field_has_field; eauto. break_exists.\n    eauto using in_all_fields. }\non >Forall, fun H => rename H into Hfa. rewrite Forall_forall in Hfa.\nspecialize (Hfa ?? **). destruct Hfa.\n  { find_rewrite. discriminate. }\nfind_rewrite.\n(* A lot of tactics are extremely slow at this poirt for some reason.\n   Even `on (Some _ = Some va), fun H => clear -H` times out... *)\ngeneralize dependent va. clear. intros.\ninject_some. constructor.\nQed.\n\nDefinition check_db_step : forall dba rn op,\n    db_step_ok dba rn op + list error.\nintros.\ndestruct op eqn:?;\ntry solve [left; inversion 3]. (* trivial result for unsupported ops *)\n\n- eapply check_set_const.\n- eapply check_copy.\n- eapply check_read_link.\n- eapply check_write_link.\n- eapply check_calculate.\n- die [ENotImplemented op]. (* CalculateStr *)\n- eapply check_havoc_update.\n- eapply check_havoc_write.\nDefined.\n\n\nDefinition step_ok dba rn op :=\n    forall dbp dbs dbs' stk code stk' oes,\n    let state := State dbs (Frame rn (op :: code) :: stk) in\n    let state' := State dbs' stk' in\n    database_state_type dbs = database_abs_type dba ->\n    refine dba dbs ->\n    step dbp state state' oes ->\n    refine dba dbs'.\n\nLemma db_op_output_op_disjoint : forall op,\n    is_db_op op = true ->\n    is_output_op op = true ->\n    False.\ndestruct op; simpl; intros; congruence.\nQed.\n\nDefinition check_step' : forall dba rn op,\n    step_ok dba rn op + list error.\nintros.\ndestruct (is_db_op op) eqn:?;\ndestruct (is_output_op op) eqn:?;\ntry solve [exfalso; eapply db_op_output_op_disjoint; eassumption].\n3: destruct op eqn:?; try solve [exfalso; discriminate].\n\n- (* db_step *)\n  destruct (check_db_step dba rn op) as [Hok | ?]; [ | die_auto ].\n\n  left. unfold step_ok. intros0 Hty Hr Hstep.\n  invc Hstep; try discriminate; cycle 1.\n    { destruct op; try discriminate; on >output_step, invc. }\n  eapply Hok; eauto.\n\n- (* output_step *)\n  left. unfold step_ok. intros0 Hty Hr Hstep.\n  invc Hstep; try discriminate.\n    { destruct op; try discriminate; on >db_step, invc. }\n  assumption.\n\n- (* Process *)\n  left. unfold step_ok. intros0 Hty Hr Hstep.\n  invc Hstep; [on >db_step, invc | on >output_step, invc | ].\n  assumption.\n\n- (* CalcCond *)\n  left. unfold step_ok. intros0 Hty Hr Hstep.\n  invc Hstep; [on >db_step, invc | on >output_step, invc | | ].\n  all: assumption.\n\n- (* CheckPACT *)\n  left. unfold step_ok. intros0 Hty Hr Hstep.\n  invc Hstep; [on >db_step, invc | on >output_step, invc | | ].\n  all: assumption.\n\n- (* HavocProcess *)\n  left. unfold step_ok. intros0 Hty Hr Hstep.\n  invc Hstep; [on >db_step, invc | on >output_step, invc | | ].\n  all: assumption.\n\nDefined.\n\n\nDefinition check_step : forall dba rn op,\n    MicroForall (step_ok dba rn) op + list error.\nintros ? ?.\ninduction op using micro_rect_g with\n    (Pl := fun ops => (Forall (MicroForall (step_ok dba rn)) ops + list error)%type).\n\nall: try match goal with\n| [ |- (MicroForall _ ?op + _)%type ] =>\n        destruct (check_step' dba rn op); [ | die_auto ]\nend.\n\n(* flat opcodes - just use the proof we got from the check_step' call *)\nall: try solve [ left; eapply MfOther; auto ].\n\n- (* CalcCond *)\n  destruct IHop; [ | die_auto ].\n  left. constructor; auto.\n\n- (* ScheduleCallback *)\n  destruct IHop; [ | die_auto ].\n  left. constructor; auto.\n\n- (* nil *)\n  left. constructor.\n\n- (* cons *)\n  destruct IHop; [ | die_auto ].\n  destruct IHop0; [ | die_auto ].\n  left. constructor; auto.\nDefined.\n\n\n\nDefinition record_program_ok dba rn rp :=\n    Forall (MicroForall (step_ok dba rn)) (rp_code rp).\n\nFixpoint database_program_ok' dba rn dbp :=\n    match dbp with\n    | [] => True\n    | rp :: dbp => record_program_ok dba rn rp /\\ database_program_ok' dba (S rn) dbp\n    end.\n\nDefinition database_program_ok dba dbp :=\n    database_program_ok' dba 0%nat dbp.\n\n\nDefinition check_record_program : forall dba rn rp,\n    record_program_ok dba rn rp + list error.\nintros. destruct rp. induction rp_code.\n\n- left. constructor.\n\n- rename a into op.\n  destruct (check_step dba rn op) as [Hop | ?]; [ | die_auto ].\n  destruct IHrp_code as [Hops | ?]; [ | die_auto ].\n  left. constructor; assumption.\nDefined.\n\nDefinition check_database_program' : forall dba rn dbp,\n    database_program_ok' dba rn dbp + list error.\nintros. generalize dependent rn. induction dbp; intros.\n\n- left. exact I.\n\n- rename a into rp.\n  destruct (check_record_program dba rn rp); [ | die_auto ].\n  destruct (IHdbp (S rn)); [ | die_auto ].\n  left. split; assumption.\nDefined.\n\nDefinition check_database_program : forall dba dbp,\n    database_program_ok dba dbp + list error.\nintros.\neapply check_database_program'.\nDefined.\n\n\n\n\nOpen Scope nat_scope.\n\nLemma database_program_ok'_lookup : forall dba dbp rn_base rn rp,\n    database_program_ok' dba rn_base dbp ->\n    lookup dbp rn = Some rp ->\n    record_program_ok dba (rn_base + rn)%nat rp.\nfirst_induction dbp; intros0 Hok Hlook.\n  { destruct rn; simpl in Hlook; discriminate. }\ninvc Hok. destruct rn.\n  { simpl in *. inject_some.\n    unfold record_name in rn_base.\n    replace ((rn_base + 0)%nat) with rn_base by lia. assumption. }\n\nspecialize (IHdbp ?? ?? ?? ?? ** **).\nreplace (rn_base + S rn) with (S rn_base + rn) by lia. assumption.\nQed.\n\nLemma database_program_ok_lookup : forall dba dbp rn rp,\n    database_program_ok dba dbp ->\n    lookup dbp rn = Some rp ->\n    record_program_ok dba rn rp.\nintros. eapply database_program_ok'_lookup with (rn_base := 0); eauto.\nQed.\n\nTheorem step_preserves_refine : forall dba dbp state state' oes,\n    let dbt := database_program_type dbp in\n    database_state_type (state_dbs state) = dbt ->\n    database_abs_type dba = dbt ->\n    CF.state_ok dbp state ->\n    database_program_ok dba dbp ->\n    refine dba (state_dbs state) ->\n    step dbp state state' oes ->\n    refine dba (state_dbs state').\nintros0 Hdbs_ty Hdba_ty Hcontrol Hprog Hstate Hstep.\n\ndestruct state, state_stk; simpl in *.\n  { invc Hstep. }\n\non >CF.state_ok, invc.\non >CF.frame_ok, invc.\nforward eapply database_program_ok_lookup; eauto.\nunfold record_program_ok in *.\nforward eapply CF.suffix_forall; eauto.\n\ndestruct f. simpl in *.\ndestruct frame_code as [| op ?]; simpl in *.\n  { (* pop *) invc Hstep. simpl. assumption. }\non (Forall _ (op :: _)), invc.\nassert (Hok : step_ok dba frame_rn op) by (eapply forall_one; assumption).\n\nunfold step_ok in Hok.\ndestruct state'. simpl in *.\neapply Hok; try exact Hstep; eauto. congruence.\nQed.\n\nTheorem star_step_preserves_refine : forall dba dbp state state' oes,\n    let dbt := database_program_type dbp in\n    database_state_type (state_dbs state) = dbt ->\n    database_abs_type dba = dbt ->\n    CF.state_ok dbp state ->\n    database_program_ok dba dbp ->\n    refine dba (state_dbs state) ->\n    star_step dbp state state' oes ->\n    refine dba (state_dbs state').\ninduction 6.\n- eauto using step_preserves_refine.\n- eapply IHstar_step; eauto.\n  + erewrite <- step_preserves_state_type by eassumption. assumption.\n  + eauto using CF.step_state_ok.\n  + eauto using step_preserves_refine.\nQed.\n\n\n\nDefinition float_abs_init (dbs : database_state) : database_abs :=\n    database_state_abs dbs.\n\nDefinition float_abs_update dbp dba :=\n    interp_prog dba dbp.\n\nDefinition float_abs_check dbp dba :=\n    check_database_program dba dbp.\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/FloatAbsInt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.28771707051999756}}
{"text": "From Coq Require Import ZArith.\nRequire Import coqutil.Z.Lia.\nRequire Import coqutil.Z.Lia.\nRequire Import coqutil.Z.div_mod_to_equations.\nRequire Import Coq.Lists.List. Import ListNotations.\nRequire Import coqutil.Map.Interface coqutil.Map.Properties.\nRequire Import coqutil.Word.Interface coqutil.Word.Properties.\nRequire Import riscv.Utility.Monads.\nRequire Import riscv.Utility.Utility.\nRequire Import riscv.Platform.Memory.\nRequire Import riscv.Spec.Machine.\nRequire Import riscv.Platform.RiscvMachine.\nRequire Import riscv.Platform.MetricRiscvMachine.\nRequire Import riscv.Spec.Primitives.\nRequire Import riscv.Spec.MetricPrimitives.\nRequire Import riscv.Platform.MetricLogging.\nRequire Import riscv.Platform.Run.\nRequire Import riscv.Spec.Execute.\nRequire Import coqutil.Tactics.Tactics.\nRequire Import compiler.SeparationLogic.\nRequire Export coqutil.Word.SimplWordExpr.\nRequire Import compiler.DivisibleBy4.\nRequire Import bedrock2.ptsto_bytes.\nRequire Import bedrock2.Scalars.\nRequire Import riscv.Utility.Encode.\nRequire Import riscv.Proofs.EncodeBound.\nRequire Import riscv.Proofs.DecodeEncode.\nRequire Import riscv.Platform.MetricSane.\nRequire Import coqutil.Decidable.\nRequire Import coqutil.Tactics.Simp.\nRequire Import riscv.Utility.runsToNonDet.\nRequire Import coqutil.Datatypes.ListSet.\nImport Utility.\n\nSection Go.\n  Context {width} {BW: Bitwidth width} {word: word.word width} {word_ok: word.ok word}.\n  Context {Registers: map.map Z word}.\n  Context {mem: map.map word byte}.\n  Context {mem_ok: map.ok mem}.\n\n  Local Notation RiscvMachineL := MetricRiscvMachine.\n\n  Context {M: Type -> Type}.\n  Context {MM: Monad M}.\n  Context {RVM: RiscvProgram M word}.\n  Context {PRParams: PrimitivesParams M MetricRiscvMachine}.\n  Context {PR: MetricPrimitives PRParams}.\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  Lemma spec_Bind_det{A B: Type}: forall (initialL: RiscvMachineL)\n       (post: B -> RiscvMachineL -> Prop) (m: M A) (f : A -> M B) (a: A) (mid: RiscvMachineL),\n      mcomp_sat m initialL (fun a' mid' => a' = a /\\ mid' = mid) ->\n      mcomp_sat (f a) mid post ->\n      mcomp_sat (Bind m f) initialL post.\n  Proof.\n    intros. eapply spec_Bind. eexists. split; [exact H|]. intros. simpl in *.\n    destruct H1. subst. assumption.\n  Qed.\n\n  (* redefine mcomp_sat to simplify for the case where no answer is returned *)\n  Definition mcomp_sat(m: M unit)(initialL: RiscvMachineL)(post: RiscvMachineL -> Prop): Prop :=\n    mcomp_sat m initialL (fun (_: unit) => post).\n\n  Lemma mcomp_sat_weaken: forall initialL m (post1 post2: RiscvMachineL -> Prop),\n      (forall mach, post1 mach -> post2 mach) ->\n      mcomp_sat m initialL post1 ->\n      mcomp_sat m initialL post2.\n  Proof.\n    intros. eapply mcomp_sat_weaken; [|eassumption].\n    simpl. intros _. assumption.\n  Qed.\n\n  (* nicer version of mcomp_sat_weaken which gives you two more hypotheses while proving P -> Q *)\n  Lemma run1_get_sane: forall iset (P Q: RiscvMachineL -> Prop) mach,\n      valid_machine mach ->\n      mcomp_sat (run1 iset) mach P ->\n      (forall mach': RiscvMachineL,\n          (exists diff, mach'.(getLog) = diff ++ mach.(getLog)) ->\n          valid_machine mach' ->\n          P mach' ->\n          Q mach') ->\n      mcomp_sat (run1 iset) mach Q.\n  Proof.\n    intros.\n    pose proof run1_sane as A.\n    unfold mcomp_sane in A.\n    specialize A with (1 := H) (2 := H0).\n    apply proj2 in A.\n    eapply mcomp_sat_weaken. 2: exact A. cbv beta.\n    intros. destruct H2 as ((? & (diff & ?)) & ?).\n    eapply H1; eauto.\n  Qed.\n\n  Lemma runsTo_sane: forall iset (P: RiscvMachineL -> Prop) mach,\n      runsTo (mcomp_sat (run1 iset)) mach P ->\n      valid_machine mach ->\n      runsTo (mcomp_sat (run1 iset)) mach (fun mach' =>\n        (P mach' /\\ exists diff, mach'.(getLog) = diff ++ mach.(getLog)) /\\ valid_machine mach').\n  Proof.\n    induction 1; intros.\n    - eapply runsToDone. ssplit; try assumption. exists nil. reflexivity.\n    - pose proof run1_sane as A.\n      unfold mcomp_sane in A.\n      specialize A with (1 := H2) (2 := H).\n      apply proj2 in A.\n      eapply runsToStep. 1: exact A.\n      cbv beta.\n      intros. destruct H3 as ((? & (diff & ?)) & ?). eapply runsTo_weaken.\n      + eapply H1; eassumption.\n      + cbv beta. intros. destruct H6 as ((? & (diff' & ?)) & ?).\n        ssplit; try eassumption.\n        rewrite H7. rewrite H4. rewrite app_assoc. eexists. reflexivity.\n  Qed.\n\n  (* a nicer version of runsTo_weaken which gives you two more hypotheses while proving P -> Q *)\n  Lemma runsTo_get_sane: forall iset (P Q: RiscvMachineL -> Prop) mach,\n      valid_machine mach ->\n      runsTo (mcomp_sat (run1 iset)) mach P ->\n      (forall mach': RiscvMachineL,\n          (exists diff, mach'.(getLog) = diff ++ mach.(getLog)) ->\n          valid_machine mach' ->\n          P mach' ->\n          Q mach') ->\n      runsTo (mcomp_sat (run1 iset)) mach Q.\n  Proof.\n    intros.\n    eapply runsTo_weaken.\n    - eapply runsTo_sane; eassumption.\n    - cbv beta. intros. destruct H2 as ((? & ?) & ?).\n      eapply H1; assumption.\n  Qed.\n\n  Lemma spec_Bind_unit: forall (initialL: RiscvMachineL)\n       (mid post: RiscvMachineL -> Prop) (m1: M unit) (m2 : M unit),\n      mcomp_sat m1 initialL mid ->\n      (forall middle, mid middle -> mcomp_sat m2 middle post) ->\n      mcomp_sat (Bind m1 (fun _ => m2)) initialL post.\n  Proof.\n    intros. eapply spec_Bind. eexists. split; [exact H|]. intros. simpl in *.\n    apply H0. assumption.\n  Qed.\n\n  Lemma ExecuteFetchP: forall (addr: word) xAddrs, Execute = Fetch -> isXAddr4 addr xAddrs.\n  Proof. intros. discriminate. Qed.\n\n  Ltac t lem :=\n    intros;\n    try (eapply spec_Bind_det; [|eassumption]); (* try because go_step doesn't need Bind *)\n    apply lem;\n    rewrite_match;\n    eauto 10 using ExecuteFetchP.\n\n  Lemma go_getRegister: forall (initialL: RiscvMachineL) (x: Z) v post (f: word -> M unit),\n      valid_register x ->\n      map.get initialL.(getRegs) x = Some v ->\n      mcomp_sat (f v) initialL post ->\n      mcomp_sat (Bind (getRegister x) f) initialL post.\n  Proof. t spec_getRegister. Qed.\n\n  Lemma go_getRegister0: forall (initialL: RiscvMachineL) post (f: word -> M unit),\n      mcomp_sat (f (ZToReg 0)) initialL post ->\n      mcomp_sat (Bind (getRegister Register0) f) initialL post.\n  Proof. t spec_getRegister. Qed.\n\n  Lemma go_setRegister: forall (initialL: RiscvMachineL) x v post (f: unit -> M unit),\n      valid_register x ->\n      mcomp_sat (f tt) (withRegs (map.put initialL.(getRegs) x v) initialL) post ->\n      mcomp_sat (Bind (setRegister x v) f) initialL post.\n  Proof. t spec_setRegister. Qed.\n\n  Lemma go_setRegister0: forall (initialL: RiscvMachineL) v post (f: unit -> M unit),\n      mcomp_sat (f tt) initialL post ->\n      mcomp_sat (Bind (setRegister Register0 v) f) initialL post.\n  Proof. t spec_setRegister. Qed.\n\n  Lemma go_loadByte: forall (initialL: RiscvMachineL) addr (v: w8) (f: w8 -> M unit) post,\n      Memory.loadByte initialL.(getMem) addr = Some v ->\n      mcomp_sat (f v) (updateMetrics (addMetricLoads 1) initialL) post ->\n      mcomp_sat (Bind (Machine.loadByte Execute addr) f) initialL post.\n  Proof. t spec_loadByte. Qed.\n\n  Lemma go_loadHalf: forall (initialL: RiscvMachineL) addr (v: w16) (f: w16 -> M unit) post,\n      Memory.loadHalf initialL.(getMem) addr = Some v ->\n      mcomp_sat (f v) (updateMetrics (addMetricLoads 1) initialL) post ->\n      mcomp_sat (Bind (Machine.loadHalf Execute addr) f) initialL post.\n  Proof. t spec_loadHalf. Qed.\n\n  Lemma go_loadWord: forall (initialL: RiscvMachineL) addr (v: w32) (f: w32 -> M unit) post,\n      Memory.loadWord initialL.(getMem) addr = Some v ->\n      mcomp_sat (f v) (updateMetrics (addMetricLoads 1) initialL) post ->\n      mcomp_sat (Bind (Machine.loadWord Execute addr) f) initialL post.\n  Proof. t spec_loadWord. Qed.\n\n  Lemma go_loadWord_Fetch: forall (initialL: RiscvMachineL) addr (v: w32) (f: w32 -> M unit) post,\n      isXAddr4 addr initialL.(getXAddrs) ->\n      Memory.loadWord initialL.(getMem) addr = Some v ->\n      mcomp_sat (f v) (updateMetrics (addMetricLoads 1) initialL) post ->\n      mcomp_sat (Bind (Machine.loadWord Fetch addr) f) initialL post.\n  Proof. t spec_loadWord. Qed.\n\n  Lemma go_loadDouble: forall (initialL: RiscvMachineL) addr (v: w64) (f: w64 -> M unit) post,\n      Memory.loadDouble initialL.(getMem) addr = Some v ->\n      mcomp_sat (f v) (updateMetrics (addMetricLoads 1) initialL) post ->\n      mcomp_sat (Bind (Machine.loadDouble Execute addr) f) initialL post.\n  Proof. t spec_loadDouble. Qed.\n\n  Lemma go_storeByte: forall (initialL: RiscvMachineL) kind addr v m' post (f: unit -> M unit),\n        Memory.storeByte initialL.(getMem) addr v = Some m' ->\n        mcomp_sat (f tt) (withXAddrs (invalidateWrittenXAddrs 1 addr initialL.(getXAddrs))\n                         (withMem m' (updateMetrics (addMetricStores 1) initialL))) post ->\n        mcomp_sat (Bind (Machine.storeByte kind addr v) f) initialL post.\n  Proof. t spec_storeByte. Qed.\n\n  Lemma go_storeHalf: forall (initialL: RiscvMachineL) kind addr v m' post (f: unit -> M unit),\n        Memory.storeHalf initialL.(getMem) addr v = Some m' ->\n        mcomp_sat (f tt) (withXAddrs (invalidateWrittenXAddrs 2 addr initialL.(getXAddrs))\n                         (withMem m' (updateMetrics (addMetricStores 1) initialL))) post ->\n        mcomp_sat (Bind (Machine.storeHalf kind addr v) f) initialL post.\n  Proof. t spec_storeHalf. Qed.\n\n  Lemma go_storeWord: forall (initialL: RiscvMachineL) kind addr v m' post (f: unit -> M unit),\n        Memory.storeWord initialL.(getMem) addr v = Some m' ->\n        mcomp_sat (f tt) (withXAddrs (invalidateWrittenXAddrs 4 addr initialL.(getXAddrs))\n                         (withMem m' (updateMetrics (addMetricStores 1) initialL))) post ->\n        mcomp_sat (Bind (Machine.storeWord kind addr v) f) initialL post.\n  Proof. t spec_storeWord. Qed.\n\n  Lemma go_storeDouble: forall (initialL: RiscvMachineL) kind addr v m' post (f: unit -> M unit),\n        Memory.storeDouble initialL.(getMem) addr v = Some m' ->\n        mcomp_sat (f tt) (withXAddrs (invalidateWrittenXAddrs 8 addr initialL.(getXAddrs))\n                         (withMem m' (updateMetrics (addMetricStores 1) initialL))) post ->\n        mcomp_sat (Bind (Machine.storeDouble kind addr v) f) initialL post.\n  Proof. t spec_storeDouble. Qed.\n\n  Lemma go_getPC: forall (initialL: RiscvMachineL) (f: word -> M unit) post,\n        mcomp_sat (f initialL.(getPc)) initialL post ->\n        mcomp_sat (Bind getPC f) initialL post.\n  Proof. t spec_getPC. Qed.\n\n  Lemma go_setPC: forall (initialL: RiscvMachineL) v post (f: unit -> M unit),\n        mcomp_sat (f tt) (withNextPc v (updateMetrics (addMetricJumps 1) initialL)) post ->\n        mcomp_sat (Bind (setPC v) f) initialL post.\n  Proof.\n    intros.\n    t (spec_setPC initialL v (fun a' mid' => a' = tt /\\\n      mid' = withNextPc v (updateMetrics (addMetricJumps 1) initialL))).\n  Qed.\n\n  Lemma go_endCycleNormal: forall (initialL: RiscvMachineL) (post: RiscvMachineL -> Prop),\n      post (withPc initialL.(getNextPc)\n           (withNextPc (word.add initialL.(getNextPc) (word.of_Z 4))\n           (updateMetrics (addMetricInstructions 1) initialL))) ->\n      mcomp_sat endCycleNormal initialL post.\n  Proof. t spec_endCycleNormal. Qed.\n\n  Lemma go_done: forall (initialL: RiscvMachineL) (post: RiscvMachineL -> Prop),\n      post initialL ->\n      mcomp_sat (Return tt) initialL post.\n  Proof. intros. apply spec_Return. exact H. Qed.\n\n  Lemma go_left_identity{A: Type}: forall (initialL: RiscvMachineL) post a\n         (f : A -> M unit),\n      mcomp_sat (f a) initialL post ->\n      mcomp_sat (Bind (Return a) f) initialL post.\n  Proof.\n    intros. rewrite left_identity. assumption.\n  Qed.\n\n  Lemma go_right_identity: forall (initialL: RiscvMachineL) post\n         (m: M unit),\n      mcomp_sat m initialL post ->\n      mcomp_sat (Bind m Return) initialL post.\n  Proof.\n    intros. rewrite right_identity. assumption.\n  Qed.\n\n  Lemma go_associativity{A B: Type}: forall (initialL: RiscvMachineL) post\n         (m: M A)\n         (f : A -> M B) (g : B -> M unit),\n      mcomp_sat (Bind m (fun x : A => Bind (f x) g)) initialL post ->\n      mcomp_sat (Bind (Bind m f) g) initialL post.\n  Proof.\n    intros. rewrite associativity. assumption.\n  Qed.\n\n  Local Arguments Z.of_nat: simpl never.\n  Local Arguments Z.mul: simpl never.\n  Local Arguments Z.add: simpl never.\n\n  Definition unchecked_store_program(addr: word)(p: list Decode.Instruction)(m: mem): mem :=\n    unchecked_store_byte_list addr (Z32s_to_bytes (List.map encode p)) m.\n\n  Lemma unchecked_store_byte_list_None: forall (l: list byte) (z: Z) m (addr: word),\n      0 < z ->\n      z + Z.of_nat (length l) < 2 ^ width ->\n      map.get m addr = None ->\n      map.get (unchecked_store_byte_list (word.add addr (word.of_Z z)) l m) addr = None.\n  Proof.\n    intros. unfold unchecked_store_byte_list, unchecked_store_bytes.\n    apply putmany_of_footprint_None; try assumption; try blia.\n  Qed.\n\n  Fixpoint in_tuple{T: Type}(a: T){n: nat}: HList.tuple T n -> Prop :=\n    match n with\n    | O => fun _ => False\n    | S n' => fun '(PrimitivePair.pair.mk t ts) => a = t \\/ in_tuple a ts\n    end.\n\n  Lemma ptsto_bytes_putmany_of_tuple: forall n addr vs (R: mem -> Prop) m,\n      Z.of_nat n < 2 ^ width ->\n      R m ->\n      (forall k, in_tuple k (footprint addr n) -> map.get m k = None) ->\n      (ptsto_bytes n addr vs * R)%sep (map.putmany_of_tuple (footprint addr n) vs m).\n  Proof.\n    assert (2 ^ width > 0) as Gz. {\n      destruct width_cases as [E | E]; rewrite E; reflexivity.\n    }\n    induction n; intros.\n    - simpl. unfold ptsto_bytes. destruct vs. simpl. apply sep_emp_l. auto.\n    - simpl. unfold ptsto_bytes. destruct vs as [v vs].\n      simpl.\n      replace (Z.of_nat (S n)) with (1 + Z.of_nat n) in H by blia.\n      match goal with\n      | |- (?A * ?B * ?C)%sep ?m => assert ((A * (B * C))%sep m); [|ecancel_assumption]\n      end.\n      eapply sep_on_undef_put.\n      + apply putmany_of_footprint_None; try blia.\n        eapply H1.\n        simpl. left. reflexivity.\n      + apply IHn; blia || assumption || idtac.\n        intros. eapply H1.\n        simpl. right. assumption.\n  Qed.\n\n  Lemma ptsto_bytes_putmany_of_tuple_empty: forall n (addr: word) vs,\n      Z.of_nat n < 2 ^ width ->\n      ptsto_bytes n addr vs (map.putmany_of_tuple (footprint addr n) vs map.empty).\n  Proof.\n    induction n; intros.\n    - cbv. auto.\n    - simpl. unfold ptsto_bytes. destruct vs as [v vs].\n      simpl.\n      replace (Z.of_nat (S n)) with (1 + Z.of_nat n) in H by blia.\n      eapply sep_on_undef_put.\n      + apply putmany_of_footprint_None; try blia.\n        apply map.get_empty.\n      + apply IHn. blia.\n  Qed.\n\n  Lemma ptsto_bytes_array: forall (l: list byte) (addr: word),\n      iff1 (array ptsto (word.of_Z 1) addr l)\n           (ptsto_bytes (length l) addr (HList.tuple.of_list l)).\n  Proof.\n    induction l; intros.\n    - simpl. reflexivity.\n    - simpl. unfold ptsto_bytes. simpl. apply iff1_sep_cancel. apply IHl.\n  Qed.\n\n  Lemma array_on_undef_store_byte_list: forall addr l (R: mem -> Prop) m,\n      Z.of_nat (length l) < 2 ^ width ->\n      R m ->\n      (forall k, in_tuple k (footprint addr (length l)) -> map.get m k = None) ->\n      (array ptsto (word.of_Z 1) addr l * R)%sep (unchecked_store_byte_list addr l m).\n  Proof.\n    intros.\n    seprewrite ptsto_bytes_array.\n    apply ptsto_bytes_putmany_of_tuple; assumption.\n  Qed.\n\n  Lemma mod_eq_to_diff: forall e1 e2 m,\n      m <> 0 ->\n      e1 mod m = e2 mod m ->\n      (e1 - e2) mod m = 0.\n  Proof.\n    intros. rewrite !Z.mod_eq in H0 by assumption.\n    replace (e1 - e2) with (m * (e1 / m) - m * (e2 / m)) by blia.\n    rewrite Z.mod_eq by assumption.\n    rewrite <- Z.mul_sub_distr_l.\n    rewrite (Z.mul_comm m (e1 / m - e2 / m)).\n    rewrite Z.div_mul by assumption.\n    rewrite Z.mul_comm.\n    apply Z.sub_diag.\n  Qed.\n\n  Ltac word_simpl :=\n    rewrite <-? word.add_assoc;\n    rewrite <-? word.ring_morph.(morph_add);\n    simpl.\n\n  Lemma pow2width_nonzero: 2 ^ width <> 0.\n  Proof.\n    destruct width_cases as [E | E]; rewrite E; cbv; discriminate.\n  Qed.\n\n  Lemma ptsto_subset_to_isXAddr1: forall (a : word) (v : Init.Byte.byte) xAddrs,\n      subset (footpr (ptsto a v)) (of_list xAddrs) ->\n      isXAddr1 a xAddrs.\n  Proof.\n    unfold subset, footpr, footprint_underapprox, ptsto, elem_of, of_list, isXAddr1.\n    intros.\n    eapply H.\n    intros.\n    subst.\n    eexists.\n    apply map.get_put_same.\n  Qed.\n\n  Context (iset: Decode.InstructionSet).\n\n  Lemma ptsto_instr_subset_to_isXAddr4: forall (a: word) i xAddrs,\n      subset (footpr (ptsto_instr iset a i)) (of_list xAddrs) ->\n      isXAddr4 a xAddrs.\n  Proof.\n    unfold isXAddr4, ptsto_instr, truncated_scalar, littleendian, ptsto_bytes, array. simpl.\n    intros.\n    ssplit; eapply ptsto_subset_to_isXAddr1;\n      (eapply shrink_footpr_subset; [eassumption|wcancel]).\n  Qed.\n\n  Definition not_InvalidInstruction(inst: Decode.Instruction): Prop :=\n    match inst with\n    | Decode.InvalidInstruction _ => False\n    | _ => True\n    end.\n\n  Lemma go_fetch_inst{initialL: RiscvMachineL} {inst pc0 R Rexec} (post: RiscvMachineL -> Prop):\n      pc0 = initialL.(getPc) ->\n      subset (footpr (program iset pc0 [inst] * Rexec)%sep) (of_list initialL.(getXAddrs)) ->\n      (program iset pc0 [inst] * Rexec * R)%sep initialL.(getMem) ->\n      not_InvalidInstruction inst ->\n      mcomp_sat (Bind (execute inst) (fun _ => endCycleNormal))\n                (updateMetrics (addMetricLoads 1) initialL) post ->\n      mcomp_sat (run1 iset) initialL post.\n  Proof.\n    intros. subst.\n    unfold run1.\n    apply go_getPC.\n    unfold program in *.\n    unfold array, ptsto_instr in H1.\n    match goal with\n    | H: (?T * ?P1 * ?P2 * emp True * Rexec * R)%sep ?m |- _ =>\n      assert ((T * R * Rexec * P1 * P2)%sep m) as A by ecancel_assumption; clear H\n    end.\n    do 2 (apply sep_emp_r in A; destruct A as [A ?]).\n    eapply go_loadWord_Fetch.\n    - eapply ptsto_instr_subset_to_isXAddr4.\n      eapply shrink_footpr_subset. 1: eassumption. simpl. ecancel.\n    - unfold Memory.loadWord.\n      unfold truncated_scalar, littleendian, Memory.bytes_per in A.\n      eapply load_bytes_of_sep with (n:=(length (LittleEndianList.le_split 4 (encode inst)))).\n      (* TODO here it would be useful if seplog unfolded Memory.bytes_per for me,\n         ie. did more than just syntactic unify *)\n      ecancel_assumption.\n    - change 4%nat with (length (LittleEndianList.le_split 4 (encode inst))).\n      rewrite LittleEndian.combine_eq, HList.tuple.to_list_of_list, LittleEndianList.le_combine_split.\n      assert (0 <= encode inst < 2 ^ width) as F. {\n        pose proof (encode_range inst) as P.\n        destruct width_cases as [E | E]; rewrite E; split. all: blia.\n      }\n      rewrite Z.mod_small; try assumption; try apply encode_range.\n      destruct H1.\n      + rewrite decode_encode; assumption.\n      + exfalso. unfold not_InvalidInstruction, valid_InvalidInstruction in *. simp. contradiction.\n  Qed.\n\n  (* go_load/storeXxx lemmas phrased in terms of separation logic instead of\n     Memory.load/storeXxx *)\n\n  Lemma go_loadByte_sep:\n    forall (initialL : RiscvMachineL) (addr : word) (v : w8)\n           (f : w8 -> M unit) (post : RiscvMachineL -> Prop) (R: mem -> Prop),\n      (ptsto_bytes 1 addr v * R)%sep initialL.(getMem) ->\n      mcomp_sat (f v) (updateMetrics (addMetricLoads 1) initialL) post ->\n      mcomp_sat (Bind (loadByte Execute addr) f) initialL post.\n  Proof.\n    intros.\n    eapply go_loadByte; [|eassumption].\n    eapply load_bytes_of_sep. eassumption.\n  Qed.\n\n  Lemma preserve_subset_of_xAddrs: forall m Rexec n (R: mem -> Prop) (xAddrs: list word) addr v,\n      subset (footpr Rexec) (of_list xAddrs) ->\n      (ptsto_bytes n addr v * R * Rexec)%sep m ->\n      subset (footpr Rexec) (of_list (invalidateWrittenXAddrs n addr xAddrs)).\n  Proof.\n    induction n; intros.\n    - simpl. assumption.\n    - destruct v as [v vs]. unfold ptsto_bytes in *. simpl in *.\n      assert (exists R',\n                 (array ptsto (word.of_Z 1) (word.add addr (word.of_Z 1)) (HList.tuple.to_list vs)\n                  * R' * Rexec)%sep m) as F by (eexists; ecancel_assumption).\n      destruct F as [R' F].\n      specialize IHn with (2 := F).\n      change removeXAddr with (@List.removeb word word.eqb).\n      rewrite ListSet.of_list_removeb.\n      unfold subset.\n      intros x Hx.\n      destr (word.eqb x addr).\n      + subst. exfalso. clear F IHn.\n        unfold sep, map.split in H0.\n        simp.\n        unfold elem_of, footpr, footprint_underapprox in Hx.\n        specialize (Hx _ H0p2).\n        destruct Hx as [w Hx].\n        rename H0p1p1p1 into B.\n        unfold ptsto in B.\n        subst.\n        unfold map.disjoint in *.\n        eapply H0p0p1. 2: exact Hx.\n        rewrite map.get_putmany_left; cycle 1. {\n          destr (map.get mq0 addr); [exfalso|reflexivity].\n          eapply H0p1p0p1. 2: exact E.\n          rewrite map.get_putmany_left; cycle 1. {\n            destr (map.get mq1 addr); [exfalso|reflexivity].\n            eapply H0p1p1p0p1. 2: exact E0.\n            rewrite map.get_put_same. reflexivity.\n          }\n          rewrite map.get_put_same. reflexivity.\n        }\n        rewrite map.get_putmany_left; cycle 1. {\n          destr (map.get mq1 addr); [exfalso|reflexivity].\n          eapply H0p1p1p0p1. 2: exact E.\n          rewrite map.get_put_same. reflexivity.\n        }\n        rewrite map.get_put_same. reflexivity.\n      + unfold diff, elem_of, singleton_set. split; [|congruence].\n        eapply IHn; assumption.\n  Qed.\n\n  Lemma go_storeByte_sep:\n    forall (initialL : RiscvMachineL) (addr : word) (v_old v_new : w8)\n           (post : RiscvMachineL -> Prop) (f : unit -> M unit) (R Rexec: mem -> Prop),\n      subset (footpr Rexec) (of_list initialL.(getXAddrs)) ->\n      (ptsto_bytes 1 addr v_old * R * Rexec)%sep initialL.(getMem) ->\n      (forall m': mem,\n          subset (footpr Rexec) (of_list (invalidateWrittenXAddrs 1 addr initialL.(getXAddrs))) ->\n          (ptsto_bytes 1 addr v_new * R * Rexec)%sep m' ->\n          mcomp_sat (f tt) (withXAddrs (invalidateWrittenXAddrs 1 addr initialL.(getXAddrs))\n                           (withMem m' (updateMetrics (addMetricStores 1) initialL))) post) ->\n      mcomp_sat (Bind (storeByte Execute addr v_new) f) initialL post.\n  Proof.\n    intros.\n    pose proof (store_bytes_of_sep (mem_ok := mem_ok)) as P.\n    edestruct P as [m' [P1 P2]]; cycle 2.\n    - eapply go_storeByte.\n      + exact P1.\n      + exact P2.\n    - ecancel_assumption.\n    - cbv beta. intros m' Hm'.\n      eapply H1. 2: ecancel_assumption.\n      eapply preserve_subset_of_xAddrs; eassumption.\n  Qed.\n\n  Lemma go_loadHalf_sep:\n    forall (initialL : RiscvMachineL) (addr : word) (v : w16)\n           (f : w16 -> M unit) (post : RiscvMachineL -> Prop) (R: mem -> Prop),\n      (ptsto_bytes 2 addr v * R)%sep initialL.(getMem) ->\n      mcomp_sat (f v) (updateMetrics (addMetricLoads 1) initialL) post ->\n      mcomp_sat (Bind (loadHalf Execute addr) f) initialL post.\n  Proof.\n    intros.\n    eapply go_loadHalf; [|eassumption].\n    eapply load_bytes_of_sep. eassumption.\n  Qed.\n\n  Lemma go_storeHalf_sep:\n    forall (initialL : RiscvMachineL) (addr : word) (v_old v_new : w16)\n           (post : RiscvMachineL -> Prop) (f : unit -> M unit) (R Rexec: mem -> Prop),\n      subset (footpr Rexec) (of_list initialL.(getXAddrs)) ->\n      (ptsto_bytes 2 addr v_old * R * Rexec)%sep initialL.(getMem) ->\n      (forall m': mem,\n          subset (footpr Rexec) (of_list (invalidateWrittenXAddrs 2 addr initialL.(getXAddrs))) ->\n          (ptsto_bytes 2 addr v_new * R * Rexec)%sep m' ->\n          mcomp_sat (f tt) (withXAddrs (invalidateWrittenXAddrs 2 addr initialL.(getXAddrs))\n                           (withMem m' (updateMetrics (addMetricStores 1) initialL))) post) ->\n      mcomp_sat (Bind (storeHalf Execute addr v_new) f) initialL post.\n  Proof.\n    intros.\n    pose proof (store_bytes_of_sep (mem_ok := mem_ok)) as P.\n    edestruct P as [m' [P1 P2]]; cycle 2.\n    - eapply go_storeHalf.\n      + exact P1.\n      + exact P2.\n    - ecancel_assumption.\n    - cbv beta. intros m' Hm'.\n      eapply H1. 2: ecancel_assumption.\n      eapply preserve_subset_of_xAddrs; eassumption.\n  Qed.\n\n  Lemma go_loadWord_sep:\n    forall (initialL : RiscvMachineL) (addr : word) (v : w32)\n           (f : w32 -> M unit) (post : RiscvMachineL -> Prop) (R: mem -> Prop),\n      (ptsto_bytes 4 addr v * R)%sep initialL.(getMem) ->\n      mcomp_sat (f v) (updateMetrics (addMetricLoads 1) initialL) post ->\n      mcomp_sat (Bind (loadWord Execute addr) f) initialL post.\n  Proof.\n    intros.\n    eapply go_loadWord; [|eassumption].\n    eapply load_bytes_of_sep. eassumption.\n  Qed.\n\n  Lemma go_storeWord_sep:\n    forall (initialL : RiscvMachineL) (addr : word) (v_old v_new : w32)\n           (m': mem) (post : RiscvMachineL -> Prop) (f : unit -> M unit) (R: mem -> Prop),\n      (ptsto_bytes 4 addr v_old * R)%sep initialL.(getMem) ->\n      (ptsto_bytes 4 addr v_new * R)%sep m' ->\n      mcomp_sat (f tt) (withXAddrs (invalidateWrittenXAddrs 4 addr initialL.(getXAddrs))\n                       (withMem m' (updateMetrics (addMetricStores 1) initialL))) post ->\n      mcomp_sat (Bind (storeWord Execute addr v_new) f) initialL post.\n  Proof.\n    intros.\n    eapply go_storeWord; [|eassumption].\n    unfold Memory.storeWord.\n    pose proof (unchecked_store_bytes_of_sep (mem_ok := mem_ok)) as P.\n    specialize P with (1 := H). specialize (P v_new).\n    (* Does not hold because if R does not completely determine the contents of the memory,\n       initialL.(getMem) and m' could change in locations other than at addr,\n       and post could check for that, so if the post in the hyp requires some specific value\n       in m', this value might not be present in initialL.(getMem), and still not be present\n       after the storeWord operation, so the conclusion would not hold. *)\n  Abort.\n\n  Lemma go_storeWord_sep:\n    forall (initialL : RiscvMachineL) (addr : word) (v_old v_new : w32)\n           (post : RiscvMachineL -> Prop) (f : unit -> M unit) (R Rexec: mem -> Prop),\n      subset (footpr Rexec) (of_list initialL.(getXAddrs)) ->\n      (ptsto_bytes 4 addr v_old * R * Rexec)%sep initialL.(getMem) ->\n      (let m' := Memory.unchecked_store_bytes 4 (getMem initialL) addr v_new in\n       let xaddrs' := invalidateWrittenXAddrs 4 addr initialL.(getXAddrs) in\n          subset (footpr Rexec) (of_list xaddrs') ->\n          (ptsto_bytes 4 addr v_new * R * Rexec)%sep m' ->\n          mcomp_sat (f tt) (withXAddrs xaddrs'\n                           (withMem m' (updateMetrics (addMetricStores 1) initialL))) post) ->\n      mcomp_sat (Bind (storeWord Execute addr v_new) f) initialL post.\n  Proof.\n    intros.\n    pose proof (unchecked_store_bytes_of_sep (mem_ok := mem_ok)) as P.\n    assert ((ptsto_bytes 4 addr v_old * (R * Rexec))%sep initialL.(getMem)) as H0'\n        by ecancel_assumption.\n    specialize P with (1 := H0'). specialize (P v_new).\n    cbv zeta in H1.\n    assert ((ptsto_bytes 4 addr v_new * R * Rexec)%sep\n                (Memory.unchecked_store_bytes 4 (getMem initialL) addr v_new)) as P'\n        by ecancel_assumption.\n    specialize H1 with (2 := P').\n    eapply go_storeWord; cycle 1. {\n      eapply H1.\n      eapply preserve_subset_of_xAddrs; eassumption.\n    }\n    unfold Memory.storeWord, store_bytes.\n    erewrite load_bytes_of_sep; eauto using unchecked_store_bytes_of_sep.\n  Qed.\n\n  Lemma go_storeWord_sep_holds_but_results_in_evars_out_of_scope:\n    forall (initialL : RiscvMachineL) (addr : word) (v_old v_new : w32)\n           (post : RiscvMachineL -> Prop) (f : unit -> M unit) (R: mem -> Prop),\n      (ptsto_bytes 4 addr v_old * R)%sep initialL.(getMem) ->\n      (forall m': mem,\n          (ptsto_bytes 4 addr v_new * R)%sep m' ->\n          mcomp_sat (f tt) (withXAddrs (invalidateWrittenXAddrs 4 addr initialL.(getXAddrs))\n                           (withMem m' (updateMetrics (addMetricStores 1) initialL))) post) ->\n      mcomp_sat (Bind (storeWord Execute addr v_new) f) initialL post.\n  Proof.\n    intros.\n    pose proof (store_bytes_of_sep (mem_ok := mem_ok)) as P.\n    specialize P with (1 := H) (2 := H0).\n    destruct P as (m' & P & Q).\n    eapply go_storeWord; eassumption.\n  Qed.\n\n  Lemma go_loadDouble_sep:\n    forall (initialL : RiscvMachineL) (addr : word) (v : w64)\n           (f : w64 -> M unit) (post : RiscvMachineL -> Prop) (R: mem -> Prop),\n      (ptsto_bytes 8 addr v * R)%sep initialL.(getMem) ->\n      mcomp_sat (f v) (updateMetrics (addMetricLoads 1) initialL) post ->\n      mcomp_sat (Bind (loadDouble Execute addr) f) initialL post.\n  Proof.\n    intros.\n    eapply go_loadDouble; [|eassumption].\n    eapply load_bytes_of_sep. eassumption.\n  Qed.\n\n  Lemma go_storeDouble_sep:\n    forall (initialL : RiscvMachineL) (addr : word) (v_old v_new : w64)\n           (post : RiscvMachineL -> Prop) (f : unit -> M unit) (R Rexec: mem -> Prop),\n      subset (footpr Rexec) (of_list initialL.(getXAddrs)) ->\n      (ptsto_bytes 8 addr v_old * R * Rexec)%sep initialL.(getMem) ->\n      (forall m': mem,\n          subset (footpr Rexec) (of_list (invalidateWrittenXAddrs 8 addr initialL.(getXAddrs))) ->\n          (ptsto_bytes 8 addr v_new * R * Rexec)%sep m' ->\n          mcomp_sat (f tt) (withXAddrs (invalidateWrittenXAddrs 8 addr initialL.(getXAddrs))\n                           (withMem m' (updateMetrics (addMetricStores 1) initialL))) post) ->\n      mcomp_sat (Bind (storeDouble Execute addr v_new) f) initialL post.\n  Proof.\n    intros.\n    pose proof (store_bytes_of_sep (mem_ok := mem_ok)) as P.\n    edestruct P as [m' [P1 P2]]; cycle 2.\n    - eapply go_storeDouble.\n      + exact P1.\n      + exact P2.\n    - ecancel_assumption.\n    - cbv beta. intros m' Hm'.\n      eapply H1. 2: ecancel_assumption.\n      eapply preserve_subset_of_xAddrs; eassumption.\n  Qed.\n\nEnd Go.\n\nLtac simpl_MetricRiscvMachine_get_set :=\n  cbn [\n     withMetrics\n     updateMetrics\n     getMachine\n     getMetrics\n     getRegs\n     getPc\n     getNextPc\n     getMem\n     getXAddrs\n     getLog\n     withRegs\n     withPc\n     withNextPc\n     withMem\n     withXAddrs\n     withLog\n     withLogItem\n     withLogItems\n     RiscvMachine.withRegs\n     RiscvMachine.withPc\n     RiscvMachine.withNextPc\n     RiscvMachine.withMem\n     RiscvMachine.withXAddrs\n     RiscvMachine.withLog\n     RiscvMachine.withLogItem\n     RiscvMachine.withLogItems\n  ].\n\nLtac simpl_MetricRiscvMachine_mem :=\n  unfold getPc, getMem in *;\n  simpl RiscvMachine.getPc in *;\n  simpl RiscvMachine.getMem in *.\n\nLtac sidecondition_hook := idtac.\n\n#[export] Hint Resolve Forall_impl : sidecondition_hints.\n\nLtac subst_if_not_in x t :=\n  lazymatch t with\n  | context[x] => fail\n  | _ => progress subst x\n  end.\n\nLtac subst_sep_var_only_in_lhs lhs rhs :=\n  match lhs with\n  | context[sep ?x _] => is_var x; subst_if_not_in x rhs\n  | context[sep _ ?x] => is_var x; subst_if_not_in x rhs\n  end.\n\nLtac subst_sep_vars :=\n  match goal with\n  | |- iff1 ?LHS ?RHS =>\n    repeat (subst_sep_var_only_in_lhs LHS RHS);\n    repeat (subst_sep_var_only_in_lhs RHS LHS)\n  end.\n\nLtac sidecondition :=\n  simpl; simpl_MetricRiscvMachine_get_set;\n  match goal with\n  (* these branches are allowed to instantiate evars in a controlled manner: *)\n  | H: map.get _ _ = Some _ |- _ => exact H\n  | |- map.get _ _ = Some _ =>\n    simpl;\n    match goal with\n    | |- map.get (map.put _ ?x _) ?y = Some _ =>\n      constr_eq x y; apply map.get_put_same\n    end\n  | |- @sep ?K ?V ?M ?P ?Q ?m => simpl in *;\n                                 simpl_MetricRiscvMachine_get_set;\n                                 use_sep_assumption;\n                                 wwcancel\n  | |- iff1 ?x _ =>\n    simpl_MetricRiscvMachine_get_set;\n    (tryif is_var x then\n       lazymatch goal with\n       | H: iff1 x _ |- _ => etransitivity; [exact H|]\n       end\n     else idtac);\n    subst_sep_vars;\n    wwcancel\n  | H: subset (footpr _) _ |- subset (footpr ?F) _ =>\n    tryif is_evar F then\n      eassumption\n    else\n      (simpl in H |- *;\n       eapply rearrange_footpr_subset; [ exact H | solve [sidecondition] ])\n  | |- _ => reflexivity\n  | A: map.get ?lH ?x = Some _, E: map.extends ?lL ?lH |- map.get ?lL ?x = Some _ =>\n    eapply (map.extends_get A E)\n  (* but we don't have a general \"eassumption\" branch, only \"assumption\": *)\n  | |- _ => solve [auto with sidecondition_hints]\n  | |- ?G => assert_fails (has_evar G); solve [eauto with sidecondition_hints]\n  | |- Memory.load ?sz ?m ?addr = Some ?v =>\n    unfold Memory.load, Memory.load_Z in *;\n    simpl_MetricRiscvMachine_mem;\n    erewrite load_bytes_of_sep; [ reflexivity | ecancel_assumption ]\n  | |- Memory.load ?sz ?m ?addr = Some ?v => eassumption\n  | |- Memory.store ?sz ?m ?addr ?val = Some ?m' => eassumption\n  | |- _ => sidecondition_hook\n  end.\n\n(* eapply and rapply don't always work (they failed in compiler.MMIO), so we use refine below\n   Trick to test if right number of underscores:\n          let c := open_constr:(go_associativity _ _ _ _ _ _) in\n          let t := type of c in idtac t. *)\n\nLtac simulate_step :=\n  first (* lemmas packing multiple primitives need to go first: *)\n        [ refine (go_fetch_inst _ _ _ _ _ _ _);    [sidecondition..|]\n        (* single-primitive lemmas: *)\n        (* lemmas about Register0 need to go before lemmas about other Registers *)\n        | refine (go_getRegister0 _ _ _ _);        [sidecondition..|]\n        | refine (go_setRegister0 _ _ _ _ _);      [sidecondition..|]\n        | refine (go_getRegister _ _ _ _ _ _ _ _); [sidecondition..|]\n        | refine (go_setRegister _ _ _ _ _ _ _);   [sidecondition..|]\n        (* Note: One might not want these, but the separation logic version, or\n           the version expressed in terms of compile_load/store, so they're commented out\n        | eapply go_loadByte       ; [sidecondition..|]\n        | eapply go_storeByte      ; [sidecondition..|]\n        | eapply go_loadHalf       ; [sidecondition..|]\n        | eapply go_storeHalf      ; [sidecondition..|]\n        | eapply go_loadWord       ; [sidecondition..|]\n        | eapply go_storeWord      ; [sidecondition..|]\n        | eapply go_loadDouble     ; [sidecondition..|]\n        | eapply go_storeDouble    ; [sidecondition..|]\n        *)\n        | refine (go_getPC _ _ _ _);               [sidecondition..|]\n        | refine (go_setPC _ _ _ _ _);             [sidecondition..|]\n        | refine (go_endCycleNormal _ _ _);        [sidecondition..|]\n        (* monad law lemmas: *)\n        | refine (go_left_identity _ _ _ _ _);     [sidecondition..|]\n        | refine (go_right_identity _ _ _ _);      [sidecondition..|]\n        | refine (go_associativity _ _ _ _ _ _);   [sidecondition..|] ].\n\nLtac simulate := repeat simulate_step.\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/GoFlatToRiscv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2876858668096939}}
{"text": "Require Import Coq.Bool.Bool.\nRequire Import Io.All.\nRequire Bisimulation.Equiv.\nRequire Choose.\nRequire Import DeadLockFree.\nRequire Model.\nRequire NoDeps.\nRequire Import Semantics.\n\nFixpoint not_stuck {E S A} (m : Model.t E S) (s : S) (x : Choose.t E A)\n  : bool :=\n  match x with\n  | Choose.Ret _ => true\n  | Choose.Call c _ =>\n    match m c s with\n    | Some _ => true\n    | None => false\n    end\n  | Choose.Choose x1 x2 => orb (not_stuck m s x1) (not_stuck m s x2)\n  end.\n\nFixpoint explore {E S A} (m : Model.t E S) (s : S) (x : Choose.t E A) : bool :=\n  match x with\n  | Choose.Ret _ => true\n  | Choose.Call c h =>\n    match m c s with\n    | Some (a, s') => andb (not_stuck m s' (h a)) (explore m s' (h a))\n    | None => true\n    end\n  | Choose.Choose x1 x2 => andb (explore m s x1) (explore m s x2)\n  end.\n\nDefinition dead_lock_free {E S A} (m : Model.t E S) (s : S) (x : Choose.t E A)\n  : bool :=\n  andb (not_stuck m s x) (explore m s x).\n\nModule Choose.\n  Fixpoint not_stuck_ok {E S A} {m : Model.t E S} {s : S} {x : Choose.t E A}\n    (H : not_stuck m s x = true)\n    : (exists p, exists v, Choose.Last.Eval.t p x v) \\/\n      (exists c, exists x', exists s', Choose.Step.t m c s x x' s').\n    destruct x as [v | c h | x1 x2]; simpl in H.\n    - left.\n      exists Choose.Path.Done, v.\n      apply Choose.Last.Eval.Ret.\n    - right.\n      case_eq (m c s).\n      + intros p H_m; destruct p as [a s'].\n        exists c, (h a), s'.\n        apply (Choose.Step.New _ _ _ _ _ Choose.Path.Done a s').\n        * exact H_m.\n        * apply Choose.Eval.Call.\n      + intro H_m.\n        rewrite H_m in H.\n        congruence.\n    - destruct (orb_prop _ _ H) as [H_not_stuck | H_not_stuck].\n      + destruct (not_stuck_ok _ _ _ _ _ _ H_not_stuck) as\n        [[p [v H_last]] | [c [x' [s' H_step]]]].\n        * left.\n          eexists; eexists.\n          apply Choose.Last.Eval.ChooseLeft.\n          exact H_last.\n        * right.\n          exists c, x', s'.\n          destruct H_step.\n          eapply Choose.Step.New; [exact H0 |].\n          apply Choose.Eval.ChooseLeft.\n          exact H1.\n      + destruct (not_stuck_ok _ _ _ _ _ _ H_not_stuck) as\n        [[p [v H_last]] | [c [x' [s' H_step]]]].\n        * left.\n          eexists; eexists.\n          apply Choose.Last.Eval.ChooseRight.\n          exact H_last.\n        * right.\n          exists c, x', s'.\n          destruct H_step.\n          eapply Choose.Step.New; [exact H0 |].\n          apply Choose.Eval.ChooseRight.\n          exact H1.\n  Defined.\n\n  Fixpoint dead_lock_free_ok_no_deps {X Y S A} {m : Model.t (NoDeps.E X Y) S}\n    {s : S} {x : Choose.t (NoDeps.E X Y) A} (H : dead_lock_free m s x = true)\n    : Choose.DeadLockFree.t m s x.\n    destruct (proj1 (andb_true_iff _ _) H) as [H_not_stuck H_aux].\n    apply Choose.DeadLockFree.New.\n    - destruct (not_stuck_ok H_not_stuck) as [[p [v H_v]] | [c [x' [s' H_x]]]].\n      + left.\n        now exists p, v.\n      + right.\n        now exists c, x', s'.\n    - clear H H_not_stuck.\n      induction x; intros c' x' s' H_x; simpl in H_aux.\n      + inversion_clear H_x.\n        inversion H0.\n      + inversion_clear H_x.\n        inversion H1.\n        rewrite <- H4 in *.\n        rewrite H0 in H_aux.\n        now apply dead_lock_free_ok_no_deps.        \n      + inversion_clear H_x.\n        destruct (proj1 (andb_true_iff _ _) H_aux) as [H_x1 H_x2].\n        inversion_clear H0.\n        * apply (IHx1 H_x1 c').\n          eapply Choose.Step.New; [exact H |].\n          apply H1.\n        * apply (IHx2 H_x2 c').\n          eapply Choose.Step.New; [exact H |].\n          apply H1.\n  Qed.\n\n  Definition dead_lock_free_ok {E S A} {m : Model.t E S} {s : S}\n    {x : Choose.t E A} (H : dead_lock_free m s x = true)\n    : Choose.DeadLockFree.t m s x.\n  Admitted.\nEnd Choose.\n\nModule C.\n  Definition dead_lock_free_ok {E S A} {m : Model.t E S} {s : S} {x : C.t E A}\n    (H : dead_lock_free m s (Compile.to_choose x) = true)\n    : C.DeadLockFree.t m s x.\n    apply Equiv.to_c.\n    now apply Choose.dead_lock_free_ok.\n  Qed.\nEnd C.\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/Decide.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.28768586083133163}}
{"text": "From mathcomp Require Import all_ssreflect.\nFrom mathcomp Require Import finmap multiset.\nFrom Coq Require Import Reals Relation_Definitions Relation_Operators.\nFrom mathcomp Require Import boolp Rstruct.\nFrom RecordUpdate Require Import RecordSet.\nFrom Algorand Require Import fmap_ext.\nImport RecordSetNotations.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nOpen Scope mset_scope.\nOpen Scope fmap_scope.\nOpen Scope fset_scope.\n\n(** * Algorand parameters, data, and transition system *)\n\n(** This module contains the definitions that comprise the Algorand consensus\nprotocol model. *)\n\n(** ** Basic parameters *)\n\n(** We assume a finite set of users. *)\nParameter UserId : finType.\n\n(** We assume a countable set of values (blocks and block hashes). *)\nParameter Value : choiceType.\n\n(** ** Message type *)\n\n(** An enumeration of all possible types (headers) of messages. *)\nInductive MessageType :=\n| Block\n| Proposal\n| Reproposal\n| Softvote\n| Certvote\n| Nextvote_Open\n| Nextvote_Val.\n\nDefinition MessageType_eq (a b:MessageType) : bool :=\n  nosimpl match a,b with\n  | Block, Block => true\n  | Proposal, Proposal => true\n  | Reproposal, Reproposal => true\n  | Softvote, Softvote => true\n  | Certvote, Certvote => true\n  | Nextvote_Open, Nextvote_Open => true\n  | Nextvote_Val, Nextvote_Val => true\n  | _, _ => false\n  end.\n\nLemma MessageType_eqP : Equality.axiom MessageType_eq.\nProof.\n  move => a b;apply Bool.iff_reflect;split.\n    by move <-;destruct a.\n    by move/(ifT (a=b) True) => <-;destruct a, b.\nQed.\n\n(** Make [MessageType] a [finType] by showing a mapping\nto the MathComp bounded [nat] type ['I_7].\n*)\nDefinition mtype2o (m:MessageType) : 'I_7 :=\n inord (match m with\n  | Block => 0\n  | Proposal => 1\n  | Reproposal => 2\n  | Softvote => 3\n  | Certvote => 4\n  | Nextvote_Open => 5\n  | Nextvote_Val => 6\n  end).\n\nDefinition o2mtype (i:'I_7) : option MessageType :=\n  match val i with\n  | 0 => Some Block\n  | 1 => Some Proposal\n  | 2 => Some Reproposal\n  | 3 => Some Softvote\n  | 4 => Some Certvote\n  | 5 => Some Nextvote_Open\n  | 6 => Some Nextvote_Val\n  | _ => None\n  end.\n\nLemma pcancel_MessageType_7 : pcancel mtype2o o2mtype.\nProof. by case;rewrite /o2mtype /= inordK. Qed.\n\n(** Register canonical structures on [MessageType]; needed for using it in [fset]s, [mset]s, etc. *)\nCanonical messageType_eqType     := EqType     MessageType (Equality.Mixin MessageType_eqP).\nCanonical messageType_choiceType := ChoiceType MessageType (PcanChoiceMixin pcancel_MessageType_7).\nCanonical messageType_countType  := CountType  MessageType (PcanCountMixin  pcancel_MessageType_7).\nCanonical messageType_finType    := FinType    MessageType (PcanFinMixin    pcancel_MessageType_7).\n\n(** ** Extended value type *)\n\n(** Message payload type, packaging [Value] and other data. *)\nInductive ExValue :=\n  | val      : Value -> ExValue\n  | step_val : nat -> ExValue\n  | repr_val : Value -> UserId -> nat -> ExValue\n  | next_val : Value -> nat -> ExValue.\n\n(** Make [ExValue] an equality type and a choice type. *)\nDefinition codeExVal (e:ExValue) :\n  Value + nat + (Value * UserId * nat) + (Value * nat) :=\n  match e with\n  | val mv => inl (inl (inl mv))\n  | step_val k => inl (inl (inr k))\n  | repr_val v user n => inl (inr (v, user, n))\n  | next_val v n => inr (v,n)\n  end.\n\nDefinition decodeExVal (c:Value + nat + (Value * UserId * nat) + (Value * nat)) : ExValue :=\n  match c with\n  | inl (inl (inl mv)) => val mv\n  | inl (inl (inr k)) => step_val k\n  | inl (inr (v, user, n)) => repr_val v user n\n  | inr (v,n) => next_val v n\n  end.\n\nLemma cancelExVal : pcancel codeExVal (fun x => Some (decodeExVal x)).\nProof. by case. Qed.\n\n(** Register canonical structures on [ExValue]; needed for using it in [fset]s, [mset]s, etc. *)\nCanonical exValue_eqType := EqType ExValue (PcanEqMixin cancelExVal).\nCanonical exValue_choiceType := ChoiceType ExValue (PcanChoiceMixin cancelExVal).\n\n(** ** Messages *)\n\n(** A message is represented by a record type for convenience, but\ncan be viewed as a tuple [(type, ev, r, p, id)] where:\n- [type] is the message type, and\n- [ev] is the message payload, and\n- [r] is the round value, and\n- [p] is the period value, and\n- [id] is the sending user's identifier. *)\nRecord Msg : Type := mkMsg\n { msg_type : MessageType ;\n   msg_ev : ExValue ;\n   msg_round : nat ;\n   msg_period : nat ;\n   msg_sender : UserId\n }.\n\nDefinition codeMsg (m : Msg) :=\n(msg_type m, msg_ev m, msg_round m, msg_period m, msg_sender m).\n\nDefinition decodeMsg c :=\nlet: (msg_type, msg_ev, msg_round, msg_period, msg_sender) := c in\nmkMsg msg_type msg_ev msg_round msg_period msg_sender.\n\nLemma cancelMsg : pcancel codeMsg (fun x => Some (decodeMsg x)).\nProof. by case. Qed.\n\n(** Register canonical structures on [Msg]; needed for using it in [fset]s, [mset]s, etc. *)\nCanonical Msg_eqType := EqType Msg (PcanEqMixin cancelMsg).\nCanonical Msg_choiceType := ChoiceType Msg (PcanChoiceMixin cancelMsg).\n\n(** Messages are grouped by the target user, and are paired with a\ndelivery deadline. In the absence of a partition, messages must\nbe delivered before the deadline is reached. *)\nDefinition MsgPool := {fmap UserId -> {mset R * Msg}}%mset.\n\n(** ** Credentials *)\n\n(** The credential of a user at a round-period-step triple.\nNote: We abstract away the random value produced by an oracle\nand the fact that credentials are interpreted as integer\nvalues. Instead, we model the type of credentials as an\nabstract totally ordered type. *)\nParameter credType : orderType tt.\n\n(** A credential is constructed using the user's identifier and the\ncurrent round-period-step values. *)\nParameter credential : UserId -> nat -> nat -> nat -> credType.\n\n(** Credentials of two different users must be different. *)\nAxiom credentials_different :\n  forall (u u' : UserId) (r r' : nat) (p p' : nat) (s s' : nat),\n  u <> u' -> credential u r p s <> credential u' r' p' s'.\n\n(** A predicate defining whether a given credential qualifies its\nowner to be a committee member. This abstracts away from how\ncredential values are interpreted. *)\nParameter committee_cred : credType -> Prop.\n\n(** Whether the credential is a committee credential for the given\nround-period-step triple. *)\nDefinition comm_cred_step uid r p s : Prop :=\n  committee_cred (credential uid r p s).\n\nAxiom credentials_valid_period:\n  forall uid r p s, comm_cred_step uid r p s -> 1 <= p.\n\n(** ** User state *)\n\n(** A proposal/reproposal record is a quadruple consisting of\na user id, a user's credential, a value and a boolean\nindicating whether the record represents a proposal ([true])\nor a reproposal ([false]). *)\nDefinition PropRecord := (UserId * credType * Value * bool)%type.\n\n(** A vote is a pair of a [UserId] (the identifier of the voter)\nand a [Value] (the value voted for). *)\nDefinition Vote := (UserId * Value)%type.\n\n(** The structure of a user's state. *)\nRecord UState :=\n  mkUState {\n    corrupt : bool; (**r a flag indicating whether the user is corrupt *)\n    round : nat; (**r the user's current round (starts at 1) *)\n    period : nat; (**r the user's current period (starts at 1) *)\n    step : nat; (**r the user's current step counter (starts at 1) *)\n    timer : R; (**r the user's current timer value (since the beginning of the current period) *)\n    deadline : R; (**r the user's next deadline time value (since the beginning of the current period) *)\n    p_start : R; (**r the (local) time at which the user's current period started (i.e., local clock = p_start + timer) *)\n    proposals : {fsfun nat * nat -> seq PropRecord with [::]}; (**r a sequence of proposal/reproposal records for the given round/period *)\n    stv : {fmap nat -> Value}; (**r starting value *)\n    blocks : {fsfun nat -> seq Value with [::]}; (**r a sequence of values seen for the given round *)\n    softvotes : {fsfun nat * nat -> seq Vote with [::]}; (**r a sequence of softvotes seen for the given round/period *)\n    certvotes : {fsfun nat * nat -> seq Vote with [::]}; (**r a sequence of certvotes seen for the given round/period *)\n    nextvotes_open : {fsfun nat * nat * nat -> seq UserId with [::]}; (**r a sequence of bottom-nextvotes seen for the given round/period/step *)\n    nextvotes_val : {fsfun nat * nat * nat -> seq Vote with [::]} (**r a sequence of value-nextvotes seen for the given round/period/step *)\n   }.\n\n#[export] Instance UState_Settable : Settable _ :=\n  settable! mkUState <corrupt;round;period;step;timer;deadline;p_start;\n   proposals;stv;blocks;softvotes;certvotes;nextvotes_open;nextvotes_val>.\n\nDefinition codeUState (u : UState) :=\n  (u.(corrupt), u.(round), u.(period), u.(step), u.(timer), u.(deadline),\n   u.(p_start), u.(proposals), u.(stv), u.(blocks), u.(softvotes), u.(certvotes),\n   u.(nextvotes_open), u.(nextvotes_val)).\n\nDefinition decodeUState c :=\nlet: (corrupt, round, period, step, timer, deadline, p_start,\n      proposals, stv, blocks, softvotes, certvotes,\n      nextvotes_open, nextvotes_val) := c in\nmkUState corrupt round period step timer deadline\n p_start proposals stv blocks softvotes certvotes\n nextvotes_open nextvotes_val.\n\nLemma cancelUState : pcancel codeUState (fun x => Some (decodeUState x)).\nProof. by case. Qed.\n\nCanonical UState_eqType := EqType UState (PcanEqMixin cancelUState).\nCanonical UState_choiceType := ChoiceType UState (PcanChoiceMixin cancelUState).\n\n(** ** Updating user state *)\n\n(** Update functions for sequences maintained in the user state. *)\nDefinition set_proposals u r' p' prop : UState :=\n  u <| proposals := [fsfun u.(proposals) with\n   (r', p') |-> (undup (prop :: u.(proposals) (r', p')))] |>.\n\nDefinition set_blocks (u : UState) (r':nat) block : UState :=\n  u <| blocks := [fsfun u.(blocks) with\n   r' |-> (undup (block :: u.(blocks) r'))] |>.\n\nDefinition set_softvotes (u : UState) r' p' sv : UState :=\n  u <| softvotes := [fsfun u.(softvotes) with\n   (r', p') |-> (undup (sv :: u.(softvotes) (r', p')))] |>.\n\nDefinition set_certvotes (u : UState) r' p' sv : UState :=\n  u <| certvotes := [fsfun u.(certvotes) with\n   (r', p') |-> (undup (sv :: u.(certvotes) (r', p')))] |>.\n\nDefinition set_nextvotes_open (u : UState) r' p' s' nvo : UState :=\n  u <| nextvotes_open := [fsfun u.(nextvotes_open) with\n   (r', p', s') |-> (undup (nvo :: u.(nextvotes_open) (r', p', s')))] |>.\n\nDefinition set_nextvotes_val (u : UState) r' p' s' nvv : UState :=\n  u <| nextvotes_val := [fsfun u.(nextvotes_val) with\n   (r', p', s') |-> (undup (nvv :: u.(nextvotes_val) (r', p', s')))] |>.\n\n(** Update function for advancing the period of a user state. *)\nDefinition advance_period (u : UState) : UState :=\n  u <| period := (u.(period) + 1)%nat |>\n    <| step := 1%nat |>\n    <| timer := 0%R |>\n    <| deadline := 0%R |>\n    <| p_start := (u.(p_start) + u.(timer))%R |>.\n\n(** Update function for advancing the round of a user state. *)\nDefinition advance_round (u : UState) : UState :=\n  u <| round := (u.(round) + 1)%nat |>\n    <| period := 1%nat |>\n    <| step := 1%nat |>\n    <| stv := [fmap] |>\n    <| timer := 0%R |>\n    <| deadline := 0%R |>\n    <| p_start := (u.(p_start) + u.(timer))%R |>.\n\n(** ** Global State *)\n\n(** The structure of the global state. *)\nRecord GState :=\n  mkGState {\n    now : R; (**r the current global time value *)\n    network_partition : bool; (**r a flag indicating whether the network is currently partitioned *)\n    users : {fmap UserId -> UState}; (**r the global set of users as a finite map of user ids to user states *)\n    msg_in_transit : {fmap UserId -> {mset R * Msg}}; (**r messages in transit as a finite map from user identifiers (targets) to multisets of messages *)\n    msg_history : {mset Msg} (**r the history of all broadcasted messages as a multiset of messages *)\n  }.\n\n#[export] Instance GState_Settable : Settable _ :=\n settable! mkGState <now;network_partition;users;msg_in_transit;msg_history>.\n\n(** State with empty maps, unpartitioned, at global time 0. *)\nDefinition null_state : GState := mkGState 0%R false [fmap] [fmap] mset0.\n\nDefinition codeGState (g : GState) :=\n (now g, network_partition g, users g, msg_in_transit g, msg_history g).\n\nDefinition decodeGState c :=\nlet: (now, network_partition, users, msg_in_transit, msg_history) := c in\nmkGState now network_partition users msg_in_transit msg_history.\n\nLemma cancelGState : pcancel codeGState (fun x => Some (decodeGState x)).\nProof. by case. Qed.\n\nCanonical GState_eqType := EqType GState (PcanEqMixin cancelGState).\nCanonical GState_choiceType := ChoiceType GState (PcanChoiceMixin cancelGState).\n\n(** Flipping the network partition flag. *)\nDefinition flip_partition_flag (g : GState) : GState :=\n  g <| network_partition := ~~ g.(network_partition) |>.\n\n(** ** Global parameters and axioms of the system *)\n\n(** Small (non-block) message delivery delay. *)\nParameter lambda : R.\n\n(** Block message delivery delay. *)\nParameter big_lambda : R.\n\n(** Recovery time period. *)\nParameter L : R.\n\n(** Axioms on how these bounds are related. *)\nAxiom delays_positive : (lambda > 0)%R.\n\nAxiom delays_order : (3 * lambda <= big_lambda < L)%R.\n\n(** Number of soft-votes needed to cert-vote. *)\nParameter tau_s : nat.\n\n(** Number of cert-votes needed for a certificate. *)\nParameter tau_c : nat.\n\n(* Number of next-votes for bottom to move to next period. *)\nParameter tau_b : nat.\n\n(* Number of next-votes for a value to move to next period. *)\nParameter tau_v : nat.\n\n(** An abstract predicate on values that tells us whether a value is valid. *)\nParameter valid : Value -> Prop.\n\n(** An abstract predicate on values that tells us whether a\ngiven hash value is indeed the hash of the given block value. *)\nParameter correct_hash : Value -> Value -> Prop.\n\n(** ** Helper definitions for user-state transitions *)\n\n(** The block has been seen and is valid and the given value is\nindeed its hash value. *)\nDefinition valid_block_and_hash b v : Prop :=\n  valid b /\\ correct_hash v b.\n\n(** From user state, get round-period-step triple. *)\nDefinition step_of_ustate (u:UState) :=\n  (u.(round), u.(period), u.(step)).\n\n(** Steps are ordered lexicographically ([Prop] versions). *)\nDefinition step_le (step1 step2: nat * nat * nat) :=\n  let: (r1,p1,s1) := step1 in\n  let: (r2,p2,s2) := step2 in\n  r1 < r2 \\/ r1 = r2 /\\ (p1 < p2 \\/ p1 = p2 /\\ s1 <= s2).\n\nDefinition step_lt (step1 step2: nat * nat * nat) :=\n  let: (r1,p1,s1) := step1 in\n  let: (r2,p2,s2) := step2 in\n  r1 < r2 \\/ r1 = r2 /\\ (p1 < p2 \\/ p1 = p2 /\\ s1 < s2).\n\n(** Steps are ordered lexicographically ([bool] versions). *)\nDefinition step_leb (step1 step2: nat * nat * nat) : bool :=\n  let: (r1,p1,s1) := step1 in\n  let: (r2,p2,s2) := step2 in\n  (r1 < r2) || (r1 == r2) && ((p1 < p2) || (p1 == p2) && (s1 <= s2)).\n\nDefinition step_ltb (step1 step2: nat * nat * nat) : bool :=\n  let: (r1,p1,s1) := step1 in\n  let: (r2,p2,s2) := step2 in\n  (r1 < r2) || (r1 == r2) && ((p1 < p2) || (p1 == p2) && (s1 < s2)).\n\n(** [us2] is after [us1] if the step of [us1] is less than the step of [us2]. *)\nDefinition ustate_after_strict us1 us2 : Prop :=\n  step_lt (step_of_ustate us1) (step_of_ustate us2).\n\n(** [us2] is no earlier than [us1] in terms of round-period-step ordering. *)\nDefinition ustate_after us1 us2 : Prop :=\n  us1.(round) < us2.(round)\n  \\/ (us1.(round) = us2.(round) /\\ us1.(period) < us2.(period))\n  \\/ (us1.(round) = us2.(round) /\\ us1.(period) = us2.(period) /\\ us1.(step) <= us2.(step)).\n\nDefinition msg_step_s (mtype : MessageType) (v : ExValue) : nat :=\n  match mtype with\n  | Block => 1\n  | Proposal => 1\n  | Reproposal => 1\n  | Softvote => 2\n  | Certvote => 3\n  | Nextvote_Val =>\n    match v with\n    | next_val _ s => s\n    | _ => 111\n    end\n  | Nextvote_Open =>\n    match v with\n    | step_val s => s\n    | _ => 111\n    end\n  end.\n\nDefinition msg_step (msg:Msg) : nat * nat * nat :=\n  (msg_round msg, msg_period msg, msg_step_s (msg_type msg) (msg_ev msg)).\n\n(** Is the given message a vote (softvote, certvote, or nextvote) message? *)\nDefinition vote_msg (msg : Msg) : Prop :=\n  match msg_type msg with\n  | Softvote | Certvote | Nextvote_Open | Nextvote_Val => True\n  | _ => False\n  end.\n\n(** Does the given round-period-step match the ones stored in the user state? *)\nDefinition valid_rps (u : UState) r p s : Prop :=\n  u.(round) = r /\\ u.(period) = p /\\ u.(step) = s.\n\nDefinition advancing_rp (u : UState) r p : Prop :=\n  u.(round) < r \\/ u.(round) = r /\\ u.(period) <= p.\n\n(** Is the vote [x] for this value [v]? *)\nDefinition matchValue (x : Vote) (v : Value) : bool :=\n  let: (u', v') := x in v == v'.\n\n(** The sequence of all values appearing in a given sequence of votes with\nduplicates removed. *)\nDefinition vote_values (vs: seq Vote) : seq Value :=\n  undup [seq x.2 | x <- vs].\n\nDefinition softvoters_for (v:Value) (u:UState) r p : {fset UserId} :=\n  [fset x.1 | x in u.(softvotes) (r, p) & matchValue x v].\n\nDefinition nextvoters_open_for (u:UState) r p s : {fset UserId} :=\n  [fset x in u.(nextvotes_open) (r, p, s)].\n\nDefinition nextvoters_val_for (v:Value) (u:UState) r p s : {fset UserId} :=\n  [fset x.1 | x in u.(nextvotes_val) (r, p, s) & matchValue x v].\n\n(** The number of softvotes of a given value in a given user state for the round\nand period given. Does not use the invariant that [u.(softvotes) r p] is duplicate-free. *)\nDefinition soft_weight (v:Value) (u:UState) r p : nat :=\n  size (softvoters_for v u r p).\n\n(** The sequence of values with high enough softvotes in a given user state for given round \nand period, i.e., the sequence of values in softvotes having votes greater than or equal \nto the threshold. Invariant: size is [<= 1]. *)\nDefinition certvals (u:UState) r p : seq Value :=\n  [seq v <- vote_values (u.(softvotes) (r, p)) | (soft_weight v u r p) >= tau_s].\n\n(** The sequence of values certified for in the last period as seen by the given user.\nThis corresponds to prev_certvals field in the automaton model. *)\nDefinition prev_certvals (u:UState) : seq Value :=\n  let p := u.(period) in\n  if p > 1 then certvals u u.(round) (p - 1) else [::].\n\n(** Whether the user has seen enough votes for bottom in the given round-period-step. *)\nDefinition nextvote_bottom_quorum (u:UState) r p s : Prop :=\n  #|(u.(nextvotes_open) (r, p, s))| >= tau_b.\n\n(** Whether the user has seen enough nextvotes for a given value in the given round-period-step. *)\nDefinition nextvote_value_quorum (u:UState) v r p s : Prop :=\n  #|[seq x.1 | x <- u.(nextvotes_val) (r, p, s) & matchValue x v]| >= tau_v.\n\n(** Whether the user has seen enough nextvotes for some value in the given round-period-step. *)\nDefinition nextvote_quorum_for_some_value (u:UState) r p s : Prop :=\n  exists v, nextvote_value_quorum u v r p s.\n\n(** Whether a quorum for bottom was not seen in the last period\nof the current round (for some step during that period). *)\nDefinition cert_may_exist (u:UState) : Prop :=\n  let p := u.(period) in\n  let r := u.(round) in\n  p > 1 /\\ forall s, ~ nextvote_bottom_quorum u r (p - 1) s.\n\n(** Proposal record ordering induced by ordering on credentials. *)\nDefinition reclt (rec rec' : PropRecord) : bool := (rec.1.1.2 < rec'.1.1.2)%O.\n\n(** Returns the proposal record in a given sequence of records having the least\ncredential, i.e., the record of the potential leader. *)\nFixpoint least_record (prs : seq PropRecord) : option PropRecord :=\n  match prs with\n  | [::] => None\n  | [:: rec & prs'] =>\n    match least_record prs' with\n    | None => Some rec\n    | Some rec' =>\n      if reclt rec' rec\n      then Some rec'\n      else Some rec\n    end\n  end.\n\n(** Returns whether the given (proposal) value is the potential leader value. *)\nDefinition leader_prop_value (v : Value) (prs : seq PropRecord) : Prop :=\n  let opr := least_record prs in\n  match opr with\n  | None => False\n  | Some (_,_, _, false) => False\n  | Some (_,_, v', true) => v = v'\n  end.\n\n(** Returns whether the given (reproposal) value is the potential leader value. *)\nDefinition leader_reprop_value (v : Value) (prs : seq PropRecord) : Prop :=\n  let opr := least_record prs in\n  match opr with\n  | None => False\n  | Some (_,_, _, true) => False\n  | Some (_,_, v', false) => v = v'\n  end.\n\n(** The timer deadline value for the NEXT step following the given step value.\nNote that [k] is zero-based and hence the apparent difference from the Algorand paper.\nThe computed deadline values are exactly as given in the paper. *)\nDefinition next_deadline k : R :=\n  match k with\n  | 0 => 0 (**r deadline for step 1 *)\n  | 1 => (2 * lambda)%R (**r deadline for step 2 *)\n  | 2 => (lambda + big_lambda)%R (**r deadline for step 3 *)\n  | n => (lambda + big_lambda + (INR n - 3) * L)%R (**r deadlines for steps 4, 5, 6, ... *)\n  end.\n\n(** ** Step 1: Proposing predicates and user state updates *)\n\n(** The proposal step preconditions. Note that this covers both:\n- the case when [p = 1], and\n- the case when [p > 1] with the previous period voting for bottom.\n\nJust as in the automaton model, the fact that the last period's quorum\nwas not for bottom is captured by the predicate [cert_may_exist]. *)\nDefinition propose_ok (pre : UState) uid v b r p : Prop :=\n  pre.(timer) = 0%R /\\\n  valid_rps pre r p 1 /\\\n  comm_cred_step uid r p 1 /\\\n  valid_block_and_hash b v /\\\n  ~ cert_may_exist pre.\n\n(** The reproposal step preconditions. Note that this is the proposal\nstep when [p > 1] and a next-vote quorum for a value [v] was\nseen in [p - 1]. Note also that this may overlap with the case\nabove, when [cert_may_exist] does not hold. *)\nDefinition repropose_ok (pre : UState) uid v r p : Prop :=\n  pre.(timer) = 0%R /\\\n  valid_rps pre r p 1 /\\ p > 1 /\\\n  comm_cred_step uid r p 1 /\\\n  exists s, nextvote_value_quorum pre v r (p - 1) s.\n\n(** The no-propose step preconditions.Note that this applies\nregardless of whether [p = 1]. *)\nDefinition no_propose_ok (pre : UState) uid r p : Prop :=\n  pre.(timer) = 0%R /\\\n  valid_rps pre r p 1 /\\\n  (comm_cred_step uid r p 1 ->\n    cert_may_exist pre /\\\n    forall s v, ~ nextvote_value_quorum pre v r (p - 1) s).\n\n(** The proposing step (propose, repropose and nopropose) post-state.\nMove on to softvoting and set the new deadline to [2*lambda]. *)\nDefinition propose_result (pre : UState) : UState :=\n  pre <| deadline := (2 * lambda)%R |>\n      <| step := 2%nat |>.\n\n(** ** Step 2: Softvoting predicates and user state updates *)\n\n(** The Softvoting-a-proposal step preconditions. This covers both:\n- the case when [p = 1], and\n- the case when [p > 1] with the previous period voting for bottom.\n\nNote that:\n- the automaton model has the constraint clock [>= 2*lambda], and\n- the phrase \"[v] is a period 1 block\" in the Algorand2 description\n  is interpreted here as \"[v] is a reproposal\", for simplicity. *)\nDefinition softvote_new_ok (pre : UState) uid v r p : Prop :=\n  pre.(timer) = (2 * lambda)%R /\\\n  valid_rps pre r p 2 /\\\n  comm_cred_step uid r p 2 /\\\n  ~ cert_may_exist pre /\\\n  leader_prop_value v (pre.(proposals) (r, p)) .\n\n(** The Softvoting-a-reproposal step preconditions\nNote that this is the Softvoting step when [p > 1] and the previous period's\nwinning vote was for a value [v]. *)\nDefinition softvote_repr_ok (pre : UState) uid v (r p: nat) : Prop :=\n  pre.(timer) = (2 * lambda)%R /\\\n  valid_rps pre r p 2 /\\ p > 1 /\\\n  comm_cred_step uid r p 2 /\\\n  ( (~ cert_may_exist pre /\\\n    (exists s, nextvote_value_quorum pre v r (p - 1) s) /\\\n    leader_reprop_value v (pre.(proposals) (r, p)))\n    \\/ (cert_may_exist pre /\\ pre.(stv).[? p] = Some v) ).\n\n(** The no-softvoting step preconditions. Three reasons a user may\nnot be able to soft-vote:\n- not being in the soft-voting committee, or\n- not being able to identify a potential leader value to soft-vote for\n- not seeing enough next-votes for a value reproposed when the previous period\n  had a quorum for bottom.\n\nNote that this may apply regardless of whether [p = 1]. *)\nDefinition no_softvote_ok (pre : UState) uid r p : Prop :=\n  pre.(timer) = (2 * lambda)%R /\\\n  valid_rps pre r p 2 /\\\n  forall v,\n  (comm_cred_step uid r p 2 ->\n    (( cert_may_exist pre \\/ ~ leader_prop_value v (pre.(proposals) (r, p)))\n    /\\ ((cert_may_exist pre \\/\n        (forall s, ~ nextvote_value_quorum pre v r (p - 1) s) \\/\n        ~ leader_reprop_value v (pre.(proposals) (r, p)))\n       /\\ (~ cert_may_exist pre \\/ ~ pre.(stv).[? p] = Some v)))).\n\n(** The softvoting step (new or reproposal) post-state.\nWe keep the current deadline at [2 * lambda] and let certvoting handle\nupdating the deadline (to avoid timing out while certvoting is already\nenabled). This assumes it is ok to certvote at time [2 * lambda]. *)\nDefinition softvote_result (pre : UState) : UState :=\n  pre <| step := 3 |>\n      <| deadline := (lambda + big_lambda)%R |>.\n\n(** ** Step 3: Certvoting predicates and user state updates *)\n\n(** Certvoting step preconditions: the successful case. *)\nDefinition certvote_ok (pre : UState) uid (v b: Value) r p : Prop :=\n  ((2 * lambda)%R < pre.(timer) <= lambda + big_lambda)%R /\\\n  valid_rps pre r p 3 /\\\n  comm_cred_step uid r p 3 /\\\n  valid_block_and_hash b v /\\\n  b \\in pre.(blocks) r /\\\n  v \\in certvals pre r p .\n\n(** Certvoting step preconditions: the unsuccessful case - not a committee member. *)\nDefinition no_certvote_ok (pre : UState) uid r p : Prop :=\n  ((2 * lambda)%R < pre.(timer) <= lambda + big_lambda)%R /\\\n  valid_rps pre r p 3 /\\\n  ~ comm_cred_step uid r p 3.\n\n(** Certvote timeout preconditions. A user timeouts if the deadline\nis reached while waiting for some external messages\n(i.e., while observing softvotes in step 3) *)\nDefinition certvote_timeout_ok (pre : UState) uid r p : Prop :=\n  (pre.(timer) >= pre.(deadline))%R /\\\n  valid_rps pre r p 3 /\\\n  comm_cred_step uid r p 3 /\\\n  forall b v,\n  (~ valid_block_and_hash b v \\/\n   ~ b \\in pre.(blocks) r \\/\n   ~ v \\in certvals pre r p).\n\n(** The certvoting step's resulting user state.\nThe state update for all certvoting cases: move on to the next step\n(the deadline does not need updating). *)\nDefinition certvote_result (pre : UState) : UState :=\n  pre <| step := 4 |>.\n\n(** ** Steps >= 4: Nextvoting predicates and user state updates *)\n\n(** Nextvoting step preconditions, the proper-value case. Note:\n- corresponds (roughly) to transition nextvote_val in the automaton\n  model (but not the same), and\n- corresponds more closely to the Algorand2 description (but with the\n  committee membership constraint).\n*)\nDefinition nextvote_val_ok (pre : UState) uid (v b : Value) r p s : Prop :=\n  pre.(timer) = (lambda + big_lambda + (INR s - 4) * L)%R /\\\n  valid_rps pre r p s /\\\n  comm_cred_step uid r p s /\\\n  3 < s /\\\n  valid_block_and_hash b v /\\\n  b \\in pre.(blocks) r /\\\n  v \\in certvals pre r p.\n\n(** Nextvoting step preconditions, the bottom-value case. Note:\n- corresponds (roughly) to transition nextvote_open in the automaton\n  model (but not the same), and\n- corresponds more closely to the Algorand2 description (but with the\n  committee membership constraint).\n*)\nDefinition nextvote_open_ok (pre : UState) uid r p s : Prop :=\n  pre.(timer) = (lambda + big_lambda + (INR s - 4) * L)%R /\\\n  valid_rps pre r p s /\\\n  comm_cred_step uid r p s /\\\n  3 < s /\\\n  (forall v, v \\in certvals pre r p -> forall b, b \\in pre.(blocks) r ->\n     ~valid_block_and_hash b v) /\\\n  (p > 1 -> nextvote_bottom_quorum pre r (p - 1) s ).\n\n(** Nextvoting step preconditions, the additional special case of using\nthe starting value. Note:\n- this might not be captured in the automaton model, and\n- corresponds more closely to the Algorand2 description (but with\n  additional constraints given explicitly).\n*)\nDefinition nextvote_stv_ok (pre : UState) uid r p s : Prop :=\n  pre.(timer) = (lambda + big_lambda + (INR s - 4) * L)%R /\\\n  valid_rps pre r p s /\\\n  comm_cred_step uid r p s /\\\n  3 < s /\\\n  (forall v, v \\in certvals pre r p -> forall b, b \\in pre.(blocks) r ->\n     ~valid_block_and_hash b v) /\\\n  p > 1 /\\ ~ nextvote_bottom_quorum pre r (p - 1) s.\n\n(** Nextvoting step preconditions, the no-voting case. *)\nDefinition no_nextvote_ok (pre : UState) uid r p s : Prop :=\n  pre.(timer) = (lambda + big_lambda + (INR s - 4) * L)%R /\\\n  valid_rps pre r p s /\\\n  ~ comm_cred_step uid r p s.\n\n(** Nextvoting step state update for steps [s >= 4] (all cases). *)\nDefinition nextvote_result (pre : UState) s : UState :=\n  pre <| step :=  (s + 1)%nat |>\n      <| deadline := next_deadline s |>.\n\n(** Advancing period propositions and user state update. *)\n\n(** Preconditions, the bottom-value case. Note that this corresponds\nto transition advance_period_open in the automaton model. *)\nDefinition adv_period_open_ok (pre : UState) r p s : Prop :=\n  valid_rps pre r p s /\\\n  nextvote_bottom_quorum pre r p s.\n\n(** Preconditions, the proper value case. This corresponds to\ntransition advance_period_val in the automaton model. *)\nDefinition adv_period_val_ok (pre : UState) (v : Value) r p s : Prop :=\n  valid_rps pre r p s /\\\n  nextvote_value_quorum pre v r p s.\n\n(** State update, the bottom-value case. *)\nDefinition adv_period_open_result (pre : UState) : UState :=\n  (advance_period pre) <| stv := pre.(stv).[~ pre.(period).+1] |>.\n\n(** State updatem the proper value case. *)\nDefinition adv_period_val_result (pre : UState) v : UState :=\n  (advance_period pre) <| stv := pre.(stv).[pre.(period).+1 <- v] |>.\n\n(** Advancing round predicates and user state updates. Note:\n- corresponds to transition certify in the automaton model, and\n- the requirement [valid_rps] has been removed since certification\n  may happen at any time.\n\nTODO: need to have some assertion about message age. *)\nDefinition certify_ok (pre : UState) (v : Value) r p : Prop :=\n  advancing_rp pre r p /\\\n  exists b,\n  valid_block_and_hash b v /\\\n  b \\in pre.(blocks) r /\\\n  size [seq x <- pre.(certvotes) (r, p) | matchValue x v] >= tau_c.\n\n(** State update. *)\nDefinition certify_result r (pre : UState) : UState :=\n  advance_round (pre <| round := r |>).\n\n(** The post state of delivering a non-vote message. *)\nDefinition deliver_nonvote_msg_result (pre : UState) (msg : Msg) c r p : UState :=\n  let type := msg_type msg in\n  let id := msg_sender msg in\n  let ev := msg_ev msg in\n  match ev with\n  | val v =>\n    match type with\n    | Proposal => set_proposals pre r p (id, c, v, true)\n    | Reproposal => set_proposals pre r p (id, c, v, false)\n    | Block => set_blocks pre r v\n    | _ => pre\n    end\n  | _ => pre\n  end.\n\n(** ** User transition relation - internal transitions *)\n\n(** The internal user-level transition relation type.\nAn internal transition is a transition that does not consume a message,\nand a user transitions from a pre-state into a post-state while emitting\na (possibly empty) sequence of outgoing messages. *)\nDefinition u_transition_internal_type := UserId -> UState -> (UState * seq Msg) -> Prop.\n\nReserved Notation \"x # z ~> y\" (at level 70).\n\n(** Internal actions are supposed to take place either:\n- at a specific time instance (i.e. never triggered by a recevied message), or\n- during a time duration, but the preconditions are already satisfied that\n  the action fires eagerly at the beginning of that time duration (again,\n  without consuming a message).\n *)\nInductive UTransitionInternal : u_transition_internal_type :=\n| propose : (**r step 1: block proposal *)\n    forall uid (pre : UState) v b r p,\n      propose_ok pre uid v b r p ->\n      uid # pre ~> (propose_result pre, [:: mkMsg Proposal (val v) r p uid ; mkMsg Block (val b) r p uid])\n\n| repropose : (**r step 1: block proposal (reproposal) *)\n    forall uid (pre : UState) v r p,\n      repropose_ok pre uid v r p ->\n      uid # pre ~> (propose_result pre, [:: mkMsg Reproposal (repr_val v uid p) r p uid])\n\n| no_propose : (**r step 1: block proposal (failure) *)\n    forall uid (pre : UState) r p,\n      no_propose_ok pre uid r p ->\n      uid # pre ~> (propose_result pre, [::])\n\n| softvote_new : (**r step 2: filtering step (new value) *)\n    forall uid (pre : UState) v r p,\n      softvote_new_ok pre uid v r p ->\n      uid # pre ~> (softvote_result pre, [:: mkMsg Softvote (val v) r p uid])\n\n| softvote_repr : (**r step 2: filtering step (old value) *)\n    forall uid (pre : UState) v r p,\n      softvote_repr_ok pre uid v r p ->\n      uid # pre ~> (softvote_result pre, [:: mkMsg Softvote (val v) r p uid])\n\n| no_softvote : (**r step 2: filtering step (no value) *)\n    forall uid (pre : UState) r p,\n      no_softvote_ok pre uid r p ->\n      uid # pre ~> (softvote_result pre, [::])\n\n| certvote1 : (**r step 3: certifying step (success) *)\n    forall uid (pre : UState) v b r p,\n      certvote_ok pre uid v b r p ->\n      uid # pre ~> (certvote_result pre, [:: mkMsg Certvote (val v) r p uid])\n\n| no_certvote : (**r step 3: certifying step (failure) *)\n    forall uid (pre : UState) r p,\n      no_certvote_ok pre uid r p ->\n      uid # pre ~> (certvote_result pre, [::])\n\n| nextvote_val : (**r steps >= 4: finishing step, [i] has cert-voted some [v] *)\n    forall uid (pre : UState) v b r p s,\n      nextvote_val_ok pre uid v b r p s ->\n      uid # pre ~> (nextvote_result pre s, [:: mkMsg Nextvote_Val (next_val v s) r p uid])\n\n| nextvote_open : (**r steps >= 4: finishing step, [i] has not cert-voted some [v] *)\n    forall uid (pre : UState) r p s,\n      nextvote_open_ok pre uid r p s ->\n      uid # pre ~> (nextvote_result pre s, [:: mkMsg Nextvote_Open (step_val s) r p uid])\n\n| nextvote_stv : (**r steps >= 4: finishing step, special case of using [stv] *)\n    forall uid (pre : UState) v r p s,\n      nextvote_stv_ok pre uid r p s ->\n      pre.(stv).[? p] = Some v ->\n      uid # pre ~> (nextvote_result pre s, [:: mkMsg Nextvote_Val (next_val v s) r p uid])\n\n| no_nextvote : (**r steps >= 4: finishing step, no next-voting *)\n    forall uid (pre : UState) r p s,\n      no_nextvote_ok pre uid r p s ->\n      uid # pre ~> (nextvote_result pre s, [::])\n\n| certvote_timeout : (**r certvote timeout transition, applicable only to step = 3 *)\n    forall uid (pre : UState) r p,\n      certvote_timeout_ok pre uid p r ->\n      uid # pre ~> (certvote_result pre, [::])\n\nwhere \"x # y ~> z\" := (UTransitionInternal x y z) : type_scope.\n\n(** ** User transition relation - message transitions *)\n\n(** The message-triggered user-level transition relation.\nA message-triggered transition consumes an incoming message,\nand a user transitions from a pre-state, while consuming a message, into a\npost-state and emits a (possibly empty) sequence of outgoing messages. *)\nDefinition u_transition_msg_type := UserId -> UState -> Msg -> (UState * seq Msg) -> Prop.\n\nReserved Notation \"a # b ; c ~> d\" (at level 70).\n\n(** Deliver messages and possibly trigger actions urgently.\nNote that advancing the period takes precedence over nextvote2_open actions. *)\nInductive UTransitionMsg : u_transition_msg_type :=\n| deliver_softvote : (**r deliver a softvote while not triggering any internal action *)\n    forall uid (pre : UState) r p i v b,\n      let pre' := (set_softvotes pre r p (i, v)) in\n      ~ certvote_ok pre' uid v b r p ->\n      uid # pre ; mkMsg Softvote (val v) r p i ~> (pre', [::])\n\n| deliver_softvote_certvote1 : (**r deliver a softvote and cert-vote for the value (committee member case) *)\n    forall uid (pre : UState) r p i v b,\n      let pre' := set_softvotes pre r p (i, v) in\n      certvote_ok pre' uid v b r p ->\n      uid # pre ; mkMsg Softvote (val v) r p i ~> (certvote_result pre', [:: mkMsg Certvote (val v) r p uid])\n\n| deliver_nextvote_open : (**r deliver a nextvote for bottom while not triggering any internal action *)\n    forall uid (pre : UState) r p s i,\n      let pre' := set_nextvotes_open pre r p s i in\n      (* ~ nextvote_open_ok pre' v r p s -> *)\n      ~ adv_period_open_ok pre' r p s ->\n      uid # pre ; mkMsg Nextvote_Open (step_val s) r p i ~> (pre', [::])\n\n| deliver_nextvote_open_adv_prd : (**r deliver a nextvote for bottom and advance the period *)\n    forall uid (pre : UState) r p s i,\n      let pre' := set_nextvotes_open pre r p s i in\n        adv_period_open_ok pre' r p s ->\n        uid # pre ; mkMsg Nextvote_Open (step_val s) r p i ~> (adv_period_open_result pre', [::])\n\n| deliver_nextvote_val : (**r deliver a nextvote for value while not triggering any internal action *)\n    forall uid (pre : UState) r p s i v,\n      let pre' := set_nextvotes_val pre r p s (i, v) in\n      ~ adv_period_val_ok pre' v r p s ->\n      uid # pre ; mkMsg Nextvote_Val (next_val v s) r p i ~> (pre', [::])\n\n| deliver_nextvote_val_adv_prd : (**r deliver a nextvote for value and advance the period *)\n    forall uid (pre : UState) r p s i v,\n      let pre' := set_nextvotes_val pre r p s (i, v) in\n      adv_period_val_ok pre' v r p s ->\n      uid # pre ; mkMsg Nextvote_Val (next_val v s) r p i ~> (adv_period_val_result pre' v, [::])\n\n| deliver_certvote : (**r deliver a certvote while not triggering any internal action *)\n    forall uid (pre : UState) v r p i,\n      let pre' := set_certvotes pre r p (i, v) in\n      ~ certify_ok pre' v r p ->\n      uid # pre ; mkMsg Certvote (val v) r p i ~> (pre', [::])\n\n| deliver_certvote_adv_rnd : (**r deliver a certvote for value and advance the round *)\n    forall uid (pre : UState) v r p i,\n      let pre' := set_certvotes pre r p (i, v) in\n      certify_ok pre' v r p ->\n      uid # pre ; mkMsg Certvote (val v) r p i ~> (certify_result r pre', [::])\n(** Note that some Algorand documents say this transition may try to\nsend another certvote message from this node, but we have been\ninformed that the implementation does not do this,\nand allowing it would complicated proofs. *)\n| deliver_nonvote_msg : (**r deliver a message other than vote messages (i.e., [Block], [Proposal], or [Reproposal]) *)\n    forall uid (pre : UState) msg c r p,\n      ~ vote_msg msg ->\n      uid # pre ; msg ~> (deliver_nonvote_msg_result pre msg c r p, [::])\n\nwhere \"a # b ; c ~> d\" := (UTransitionMsg a b c d) : type_scope.\n\n(** ** Helper functions for global transitions *)\n\n(** Is the network in a partitioned/unpartitioned state? *)\nDefinition is_partitioned pre : bool := pre.(network_partition).\nDefinition is_unpartitioned pre : bool := ~~ is_partitioned pre.\n\n(** It is OK to advance time if:\n- the user is corrupt (its deadline is irrelevant), or\n- the increment does not go beyond the deadline. *)\nDefinition user_can_advance_timer (increment : posreal) : pred UState :=\n  fun u => u.(corrupt) || Rleb (u.(timer) + pos increment) u.(deadline).\n\n(** Advance the timer of an honest user (timers of corrupt users are irrelevant). *)\nDefinition user_advance_timer (increment : posreal) (u : UState) : UState :=\n  if ~~ u.(corrupt)\n  then u <| timer := (u.(timer) + pos increment)%R |>\n  else u.\n\n(** Is it OK to advance timers of all (honest) users by the given increment? *)\nDefinition tick_ok_users increment (pre:GState) : bool :=\n  allf (user_can_advance_timer increment) pre.(users).\n\n(** It is OK to advance time if:\n- the network is partitioned (message delivery delays are ignored), or\n- the time increment does not cause missing a message delivery deadline.\n *)\nDefinition tick_ok_msgs (increment:posreal) (pre:GState) : bool :=\n  is_partitioned pre ||\n  let target_time := (pre.(now) + pos increment)%R in\n  \\big[andb/true]_(user_msgs <- codomf pre.(msg_in_transit))\n   \\big[andb/true]_(m <- (enum_mset user_msgs)) Rleb target_time (fst m).\n\n(** Returns whether time may advance, taking into consideration the state of\nthe network, users, their deadlines and message deadlines. *)\nDefinition tick_ok (increment:posreal) (pre:GState) : bool :=\n  tick_ok_users increment pre && tick_ok_msgs increment pre.\n\n(** Advance all (honest) user timers by the given increment. *)\nDefinition tick_users increment pre : {fmap UserId -> UState} :=\n  updf pre.(users) (domf pre.(users)) (fun _ us => user_advance_timer increment us).\n\n(** Computes the global state after advancing time with the given increment. *)\nDefinition tick_update increment pre : GState :=\n  pre <| now := (pre.(now) + pos increment)%R |>\n      <| users := tick_users increment pre |>.\n\n(** Computes the standard deadline of a message based on its type. *)\nDefinition msg_deadline (msg : Msg) now : R :=\n  match msg_type msg with\n  | Block => (now + lambda + big_lambda)%R\n  | _ => (now + lambda)%R\n  end.\n\nDefinition merge_msgs_deadline (now : R) (msgs : seq Msg) (v : {mset R * Msg}) : {mset R * Msg} :=\n  seq_mset [seq (msg_deadline msg now,msg) | msg <- msgs] `+` v.\n\nDefinition send_broadcasts_def (now : R) (targets : {fset UserId}) (prev_msgs : MsgPool) (msgs : seq Msg) : MsgPool :=\n  updf prev_msgs targets (fun _ => merge_msgs_deadline now msgs).\n\nDefinition send_broadcasts_key : unit.\nProof. exact: tt. Qed.\n\nDefinition send_broadcasts := locked_with send_broadcasts_key send_broadcasts_def.\nCanonical send_broadcasts_unlockable := [unlockable fun send_broadcasts].\n\n(** Returns [true] if [P] is true at nth element in path [p]. *)\nDefinition at_step n (p : seq GState) (P : pred GState) : bool :=\n  match drop n p with\n  | g :: _ => P g\n  | [::] => false\n  end.\n\n(** Returns [true] if the given user id is found in the map and the user state\ncorresponding to that id is for a corrupt user. *)\nDefinition is_user_corrupt (uid : UserId) (users : {fmap UserId -> UState}) : bool :=\n  if users.[? uid] is Some u then u.(corrupt) else false.\n\nDefinition is_user_corrupt_gstate (uid : UserId) (g : GState) : bool :=\n  is_user_corrupt uid (g.(users)).\n\nDefinition user_honest (uid:UserId) (g:GState) : bool :=\n  if g.(users).[? uid] is Some ustate then ~~ (ustate.(corrupt)) else false.\n\nDefinition user_honest_at ix p (uid : UserId) : bool :=\n  at_step ix p (user_honest uid).\n\n(** Returns the given users map restricted to honest users only. *)\nDefinition honest_users (users : {fmap UserId -> UState}) :=\n  let corrupt_ids := [fset x in domf users | is_user_corrupt x users] in\n  users.[\\ corrupt_ids].\n\n(** Computes the global state after a message delivery, given the result of the\nuser transition and the messages sent out. Note:\n\n- the delivered message is removed from the user's mailbox, and\n- broadcasts new messages to honest users only.\n *)\nDefinition delivery_result pre uid (uid_has_mailbox : uid \\in pre.(msg_in_transit)) delivered ustate_post (sent: seq Msg) : GState :=\n  let users' := pre.(users).[uid <- ustate_post] in\n  let user_msgs' := (pre.(msg_in_transit).[uid_has_mailbox] `\\ delivered)%mset in\n  let msgs' := send_broadcasts pre.(now) (domf (honest_users pre.(users)) `\\ uid)\n    pre.(msg_in_transit).[uid <- user_msgs'] sent in\n  let msgh' := (pre.(msg_history) `+` (seq_mset sent))%mset in\n  pre <| users := users' |>\n      <| msg_in_transit := msgs' |>\n      <| msg_history := msgh' |>.\n\nArguments delivery_result : clear implicits.\n\n(** Computes the global state after an internal user-level transition\ngiven the result of the user transition and the messages sent out. *)\nDefinition step_result pre uid ustate_post (sent: seq Msg) : GState :=\n  let users' := pre.(users).[uid <- ustate_post] in\n  let msgs' := send_broadcasts pre.(now) (domf (honest_users pre.(users)) `\\ uid)\n                               pre.(msg_in_transit) sent in\n  let msgh' := (pre.(msg_history)  `+` (seq_mset sent))%mset in\n  pre <| users := users' |>\n      <| msg_in_transit := msgs' |>\n      <| msg_history := msgh'  |>.\n\nDefinition new_deadline now cur_deadline msg : R :=\n  let max_deadline := msg_deadline msg now in\n  Rmax cur_deadline max_deadline.\n\n(** Resets the deadline of a message having a missed deadline. *)\nDefinition reset_deadline now (msg : R * Msg) : R * Msg :=\n  (new_deadline now msg.1 msg.2, msg.2).\n\nDefinition map_mset {A B : choiceType} (f : A -> B) (m : {mset A}) : {mset B} :=\n  seq_mset (map f m).\n\n(** Recursively resets message deadlines of all the messages given. *)\nDefinition reset_user_msg_delays msgs now : {mset R * Msg} :=\n  map_mset (reset_deadline now) msgs.\n\n(** Constructs a message pool with all messages having missed delivery deadlines\nupdated appropriately based on the message type. *)\nDefinition reset_msg_delays (msgpool : MsgPool) now : MsgPool :=\n  updf msgpool (domf msgpool) (fun _ msgs => reset_user_msg_delays msgs now).\n\n(** Postpones the deadline of a message (extending its delivery delay). *)\nDefinition extend_deadline r (msgs : {mset R * Msg}) (msg : R * Msg) : {mset R * Msg} :=\n  let ext_deadline := (fst msg + r)%R in\n  (msgs `+` [mset (ext_deadline, msg.2)])%mset.\n\n(** Computes the state resulting from getting partitioned.\nNote that this no longer injects extended message delays (see the [tick] rule). *)\nDefinition make_partitioned (pre:GState) : GState :=\n  flip_partition_flag pre.\n\n(** Computes the state resulting from recovering from a partition. *)\nDefinition recover_from_partitioned pre : GState :=\n  let msgpool' := reset_msg_delays pre.(msg_in_transit) pre.(now) in\n  (flip_partition_flag pre) <| msg_in_transit := msgpool' |>.\n\n(** Marks a user state corrupted by setting the corrupt flag. *)\nDefinition make_corrupt ustate : UState :=\n  ustate <| corrupt := true |>.\n\n(** Drop the set of messages targeted for a specific user from the given\nmessage map. *)\nDefinition drop_mailbox_of_user uid (msgs : MsgPool) : MsgPool :=\n  if msgs.[? uid] is Some mailbox then msgs.[uid <- mset0] else msgs.\n\n(** Computes the state resulting from corrupting a user.\nThe user will have its corrupt flag (in its local state) set to [true]\nand his mailbox in the global state removed. *)\nDefinition corrupt_user_result (pre : GState) (uid : UserId)\n (ustate_key : uid \\in pre.(users)) : GState :=\n  let ustate' := make_corrupt pre.(users).[ustate_key] in\n  let msgs' := drop_mailbox_of_user uid  pre.(msg_in_transit) in\n  let users' := pre.(users).[uid <- ustate'] in\n  pre <| users := users' |> <| msg_in_transit := msgs' |>.\n\n(** Computes the state resulting from replaying a message to a user.\nThe message is replayed to the given target user and added to his mailbox.\nIt is not broadcast because other users have already seen the original. *)\nDefinition replay_msg_result (pre : GState) (uid : UserId) (msg : Msg) : GState :=\n  let msgs' := send_broadcasts pre.(now) [fset uid] pre.(msg_in_transit) [:: msg] in\n  pre <| msg_in_transit := msgs' |>.\n\n(** Does the adversary have the keys of the user for the given r-p-s?\nThe adversary will have the keys if the user is corrupt and the given\nr-p-s comes after (or is equal to) the r-p-s of the user. *)\nDefinition have_keys ustate r p s : Prop :=\n  ustate.(corrupt) /\\ step_le (step_of_ustate ustate) (r,p,s).\n\nDefinition mtype_matches_step mtype mval s : Prop :=\n  match mtype, mval with\n  | Block, val _ | Proposal, val _ | Reproposal, repr_val _ _ _ => s = 1\n  | Softvote, val _ => s = 2\n  | Certvote, val _ => s = 3\n  | Nextvote_Open, step_val s' => s = s'\n  | Nextvote_Val, next_val _ s' => s = s'\n  | _, _ => False\n  end.\n\n(** Computes the state resulting from forging a message to a user.\nThe message is first created and then queued at the target user's mailbox *)\nDefinition forge_msg_result (pre : GState) (uid : UserId) r p mtype mval : GState :=\n  let msg := mkMsg mtype mval r p uid in\n  let msgs' := send_broadcasts pre.(now) (domf (honest_users pre.(users)))\n                 pre.(msg_in_transit) [:: msg] in\n  pre <| msg_in_transit := msgs' |>.\n\n(** ** Global transition relation *)\n\n(** Global transition relation type. *)\nDefinition g_transition_type := relation GState.\n\nReserved Notation \"x ~~> y\" (at level 90).\n\n(** Note that corrupt user deadlines are ignored, and\nwhen partitioned, message delivery delays are ignored.\nThis means that the adversary action to inject extended\nmessage delays is modeled by [step_tick] ignoring message\ndelivery deadlines when partitioned. *)\nInductive GTransition : g_transition_type :=\n| step_tick : (**r advance the global time *)\n    forall increment pre,\n    tick_ok increment pre ->\n    pre ~~> tick_update increment pre\n\n| step_deliver_msg : (**r deliver a message to a user (honest users only) *)\n   forall pre uid (msg_key : uid \\in pre.(msg_in_transit)) pending,\n    pending \\in pre.(msg_in_transit).[msg_key] ->\n    forall (key_ustate : uid \\in pre.(users)) ustate_post sent,\n      ~ pre.(users).[key_ustate].(corrupt) ->\n      uid # pre.(users).[key_ustate] ; snd pending ~> (ustate_post, sent) ->\n      pre ~~> delivery_result pre uid msg_key pending ustate_post sent\n\n| step_internal : (**r progress based on an internal step of a user (honest users only) *)\n    forall pre uid (ustate_key : uid \\in pre.(users)),\n      ~ pre.(users).[ustate_key].(corrupt) ->\n      forall ustate_post sent,\n        uid # pre.(users).[ustate_key] ~> (ustate_post, sent) ->\n        pre ~~> step_result pre uid ustate_post sent\n\n| step_exit_partition : (**r recover from a partition *)\n    forall pre,\n    is_partitioned pre ->\n    pre ~~> recover_from_partitioned pre\n\n| step_enter_partition : (**r adversary action: partition the network *)\n    forall pre,\n    is_unpartitioned pre ->\n    pre ~~> make_partitioned pre\n\n| step_corrupt_user : (**r adversary action: corrupt a user *)\n    forall pre uid (ustate_key : uid \\in pre.(users)),\n    ~ pre.(users).[ustate_key].(corrupt) ->\n    pre ~~> @corrupt_user_result pre uid ustate_key\n\n| step_replay_msg : (**r adversary action: replay a message seen before *)\n    forall pre uid (ustate_key : uid \\in pre.(users)) msg,\n    ~ pre.(users).[ustate_key].(corrupt) ->\n    msg \\in pre.(msg_history) ->\n    pre ~~> replay_msg_result pre uid msg\n\n| step_forge_msg : (**r adversary action: forge and send out a message *)\n    forall pre sender (sender_key : sender \\in pre.(users)) r p s mtype mval,\n    have_keys pre.(users).[sender_key] r p s ->\n    comm_cred_step sender r p s ->\n    mtype_matches_step mtype mval s ->\n    pre ~~> forge_msg_result pre sender r p mtype mval\n\nwhere \"x ~~> y\" := (GTransition x y) : type_scope.\n\n(** ** Reachability for global transition relation *)\n\n(** There is a step at index [n] from [g1] to [g2] along a path [p].\nThis means that [g1] and [g2] are adjacent elements in the path. *)\nDefinition step_in_path_at (g1 g2 : GState) n (p : seq GState) : Prop :=\n  match drop n p with\n  | g1' :: g2' :: _ => [/\\ g1' = g1 & g2' = g2]\n  | _ => False\n  end.\n\n(** Definition of reachable global state via paths. *)\nDefinition gtransition : rel GState := [rel x y | `[<GTransition x y>] ].\n\n(** A trace starts from [g0] and transitions via [GTransition] at each step in the path [p]. *)\nDefinition is_trace (g0 : GState) (p : seq GState) : Prop :=\n  nosimpl match p with\n          | [::] => False\n          | [:: g' & rest] => [/\\ g0 = g' & path gtransition g0 rest]\n          end.\n\n(** Reachability between pairs of states under the reflexive-transitive closure of the transition relation. *)\nDefinition greachable (g0 g : GState) : Prop := exists2 p, is_trace g0 p & g = last g0 p.\n\n(** Classic definition of reachable global state. *)\nDefinition GReachable (g0 g : GState) : Prop := clos_refl_trans_1n _ GTransition g0 g.\n\n(** We next prove that the above notions of reachability are equivalent in our setting. *)\n\n(** Our definition of reachability implies the classic definition of reachable states. *)\nLemma greachable_GReachable : forall g0 g, greachable g0 g -> GReachable g0 g.\nProof.\n  move => g0 g; case => x.\n  destruct x. inversion 1.\n  move => [H_g0 H_path]; subst g1.\n  revert H_path.\n  move: g0 g.\n  elim: x => /=; first by move => g0 g Ht ->; exact: rt1n_refl.\n  move => g1 p IH g0 g.\n  move/andP => [Hg Hp] Hgg.\n  have IH' := IH _ _ Hp Hgg.\n  move: IH'; apply: rt1n_trans.\n    by move: Hg; move/asboolP.\nQed.\n\n(** Classic definition of reachable states implies our definition of reachable states. *)\nLemma GReachable_greachable : forall g0 g, GReachable g0 g -> greachable g0 g.\nProof.\n  move => g0 g.\n  elim. move => x; exists [:: x]; done.\n  move => x y z Hxy Hc.\n  case => p Hp Hl.\n  unfold is_trace in Hp.\n  destruct p. contradiction.\n  destruct Hp as [Hy Hp].\n  exists (x :: y :: p) => //=; last by subst.\n  unfold is_trace; split; first by [].\n  apply/andP.\n    by split => //; apply/asboolP.\nQed.\n\n(** ** Labeling global transitions *)\n\n(** Labels to classify transitions more abstractly. *)\nInductive GLabel : Type :=\n| lbl_tick :  posreal -> GLabel\n| lbl_deliver : UserId -> R -> Msg -> seq Msg -> GLabel\n| lbl_step_internal : UserId -> seq Msg -> GLabel\n| lbl_exit_partition : GLabel\n| lbl_enter_partition : GLabel\n| lbl_corrupt_user : UserId -> GLabel\n| lbl_replay_msg : UserId -> GLabel\n| lbl_forge_msg : UserId -> nat -> nat -> MessageType -> ExValue -> GLabel.\n\n(** Specify when labels classify a transition between pairs of global states. *)\nDefinition related_by (label : GLabel) (pre post : GState) : Prop :=\n  match label with\n  | lbl_tick increment =>\n      tick_ok increment pre /\\ post = tick_update increment pre\n  | lbl_deliver uid deadline delivered_msg sent =>\n      exists (key_ustate : uid \\in pre.(users)) ustate_post,\n         uid # pre.(users).[key_ustate] ; delivered_msg ~> (ustate_post,sent)\n         /\\ ~ pre.(users).[key_ustate].(corrupt)\n      /\\ exists (key_mailbox : uid \\in pre.(msg_in_transit)),\n           (deadline,delivered_msg) \\in pre.(msg_in_transit).[key_mailbox]\n           /\\ post = delivery_result pre uid key_mailbox (deadline,delivered_msg) ustate_post sent\n  | lbl_step_internal uid sent =>\n      exists (key_user : uid \\in pre.(users)) ustate_post,\n      ~ pre.(users).[key_user].(corrupt) /\\\n      uid # pre.(users).[key_user] ~> (ustate_post,sent)\n      /\\ post = step_result pre uid ustate_post sent\n  | lbl_exit_partition =>\n      is_partitioned pre /\\ post = recover_from_partitioned pre\n  | lbl_enter_partition =>\n      is_unpartitioned pre /\\ post = make_partitioned pre\n  | lbl_corrupt_user uid =>\n      exists (ustate_key : uid \\in pre.(users)),\n      ~ pre.(users).[ustate_key].(corrupt)\n      /\\ post = @corrupt_user_result pre uid ustate_key\n  | lbl_replay_msg uid =>\n      exists (ustate_key : uid \\in pre.(users)) msg,\n      ~ pre.(users).[ustate_key].(corrupt)\n      /\\ msg \\in pre.(msg_history)\n      /\\ post = replay_msg_result pre uid msg\n  | lbl_forge_msg sender r p mtype mval =>\n      exists (sender_key : sender \\in pre.(users)) s,\n         have_keys pre.(users).[sender_key] r p s\n      /\\ comm_cred_step sender r p s\n      /\\ mtype_matches_step mtype mval s\n      /\\ post = forge_msg_result pre sender r p mtype mval\n  end.\n", "meta": {"author": "runtimeverification", "repo": "algorand-verification", "sha": "389c5b44d3101508c9fcb023c6ea47874c4e89af", "save_path": "github-repos/coq/runtimeverification-algorand-verification", "path": "github-repos/coq/runtimeverification-algorand-verification/algorand-verification-389c5b44d3101508c9fcb023c6ea47874c4e89af/theories/algorand_model.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2876858608313316}}
{"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 Ctypes. (*for type and access_mode*)\nRequire Import mem_lemmas. (*needed for definition of valid_block_dec etc*)\n\nRequire Import Axioms.\nRequire Import structured_injections.\nRequire Import reach. \nRequire Import effect_semantics. \nRequire Import effect_properties.\nRequire Import simulations. \n\nRequire Import I64Helpers.\n\nDefinition memcpy_Effect sz vargs m:=\n       match vargs with \n          Vptr b1 ofs1 :: Vptr b2 ofs2 :: nil =>\n          fun b z => eq_block b b1 && zle (Int.unsigned ofs1) z &&\n                     zlt z (Int.unsigned ofs1 + sz) && valid_block_dec m b\n       | _ => fun b z => false\n       end.\n      \nLemma memcpy_Effect_unchOn: forall m bsrc osrc sz bytes bdst odst m'\n        (LD: Mem.loadbytes m bsrc (Int.unsigned osrc) sz = Some bytes)\n        (ST: Mem.storebytes m bdst (Int.unsigned odst) bytes = Some m')\n        (SZ: sz >= 0),\n    Mem.unchanged_on\n      (fun b z=> memcpy_Effect sz (Vptr bdst odst :: Vptr bsrc osrc :: nil) \n                 m b z = false) m m'.\nProof. intros.\n  split; intros.\n    unfold Mem.perm. rewrite (Mem.storebytes_access _ _ _ _ _ ST). intuition.\n  unfold memcpy_Effect in H.\n    rewrite (Mem.storebytes_mem_contents _ _ _ _ _ ST).\n    destruct (valid_block_dec m b); simpl in *. rewrite andb_true_r in H; clear v.\n    destruct (eq_block b bdst); subst; simpl in *.\n      rewrite PMap.gss. apply Mem.setN_other.\n      intros. intros N; subst. \n        rewrite (Mem.loadbytes_length _ _ _ _ _ LD), nat_of_Z_eq in H1; trivial.\n          destruct (zle (Int.unsigned odst) ofs); simpl in *.\n            destruct (zlt ofs (Int.unsigned odst + sz)). inv H.\n            omega. omega.\n    clear H. rewrite PMap.gso; trivial.\n  elim n. eapply Mem.perm_valid_block; eassumption.\nQed.\n\nLemma external_call_memcpy_unchOn:\n    forall {F V:Type} (ge : Genv.t F V) m ty b1 ofs1 b2 ofs2 m' a tr vres,\n    external_call (EF_memcpy (sizeof ty) a) ge \n                  (Vptr b1 ofs1 :: Vptr b2 ofs2 :: nil) m tr vres m' -> \n    Mem.unchanged_on\n      (fun b z=> memcpy_Effect (sizeof ty) (Vptr b1 ofs1 :: Vptr b2 ofs2 :: nil) \n                 m b z = false) m m'.\nProof. intros. inv H.\n  eapply memcpy_Effect_unchOn; try eassumption. omega.\nQed.\n \nLemma memcpy_Effect_validblock:\n    forall {F V:Type} (ge : Genv.t F V) m sz vargs b z,\n    memcpy_Effect sz vargs m b z = true ->\n    Mem.valid_block m b.\nProof. intros.\n unfold memcpy_Effect in H.  \n  destruct vargs; try discriminate.\n  destruct v; try discriminate.\n  destruct vargs; try discriminate.\n  destruct v; try discriminate.\n  destruct vargs; try discriminate.\n  destruct (valid_block_dec m b); simpl in *. trivial. \n  rewrite andb_false_r in H. inv H. \nQed.\n  \nDefinition free_Effect vargs m:=\n       match vargs with \n          Vptr b1 lo :: nil =>\n          match Mem.load Mint32 m b1 (Int.unsigned lo - 4)\n          with Some (Vint sz) =>\n            fun b z => eq_block b b1 && zlt 0 (Int.unsigned sz) &&\n                     zle (Int.unsigned lo - 4) z &&\n                     zlt z (Int.unsigned lo + Int.unsigned sz)\n          | _ => fun b z => false\n          end\n       | _ => fun b z => false\n       end.\n\nLemma free_Effect_unchOn: forall {F V : Type} (g : Genv.t F V)\n        vargs m t vres m' (FR : external_call EF_free g vargs m t vres m'),\n     Mem.unchanged_on (fun b z => free_Effect vargs m b z = false) m m'.\nProof. intros. inv FR. \n  eapply Mem.free_unchanged_on. eassumption.\n  intros. unfold free_Effect. rewrite H.\n    destruct (eq_block b b); simpl.\n      clear e. destruct (zlt 0 (Int.unsigned sz)); simpl; try omega. \n      clear l. destruct (zlt 0 (Int.unsigned sz)); simpl; try omega.\n      clear l. destruct (zle (Int.unsigned lo - 4) i); simpl; try omega.\n      clear l. destruct (zlt i (Int.unsigned lo + Int.unsigned sz)); simpl; try omega.\n      discriminate.\n   elim n; trivial.\nQed.\n\nLemma freeEffect_valid_block vargs m: forall b z \n        (FR: free_Effect vargs m b z = true),\n      Mem.valid_block m b.\nProof. intros.\n  destruct vargs; inv FR.\n  destruct v; inv H0.\n  destruct vargs; inv H1.\n  remember (Mem.load Mint32 m b0 (Int.unsigned i - 4)) as d.\n  destruct d; apply eq_sym in Heqd.\n    destruct v; inv H0.\n    destruct (eq_block b b0); subst; simpl in *.\n      apply Mem.load_valid_access in Heqd.\n      eapply Mem.valid_access_valid_block.\n      eapply Mem.valid_access_implies; try eassumption. constructor.\n    inv H1.\n  inv H0.\nQed.\n\nDefinition BuiltinEffect  {F V: Type} (ge: Genv.t F V) (ef: external_function)\n          (vargs:list val) (m:mem): block -> Z -> bool :=\n  match ef with\n    EF_malloc => EmptyEffect\n  | EF_free => free_Effect vargs m\n  | EF_memcpy sz a => memcpy_Effect sz vargs m\n  | _ => fun b z => false\n  end.\n\nLemma malloc_Effect_unchOn: forall {F V : Type} (g : Genv.t F V)\n         vargs m t vres m' (EF: external_call EF_malloc g vargs m t vres m'),\n     Mem.unchanged_on\n      (fun b z => BuiltinEffect g EF_malloc vargs m b z = false) m m'.\nProof. intros.\n       simpl. inv EF.\n       split; intros.\n          unfold Mem.perm. rewrite (Mem.store_access _ _ _ _ _ _ H0).\n          split; intros. \n            eapply Mem.perm_alloc_1; eassumption. \n            eapply Mem.perm_alloc_4; try eassumption.\n              intros N. subst. eapply Mem.fresh_block_alloc; eassumption.\n        rewrite <- (AllocContentsOther _ _ _ _ _ H). \n                rewrite (Mem.store_mem_contents _ _ _ _ _ _ H0).\n                rewrite PMap.gso. trivial.\n                intros N; subst. apply Mem.perm_valid_block in H2.\n                    eapply Mem.fresh_block_alloc; eassumption.\n              intros N; subst. apply Mem.perm_valid_block in H2.\n                    eapply Mem.fresh_block_alloc; eassumption.\nQed.\n\nSection BUILTINS.\n\nContext {F V: Type} (ge: Genv.t (AST.fundef F) V).\nVariable hf : helper_functions.\n\nDefinition builtin_implements (id: ident) (sg: signature)\n      (vargs: list val) (vres: val) : Prop :=\n  forall m, external_call (EF_builtin id sg) ge vargs m E0 vres m.\n\nDefinition observableEF (ef: external_function): Prop :=\n  match ef with\n    EF_malloc => False (*somewhat arbitrary*)\n  | EF_free => False (*somewhat arbitrary*)\n  | EF_memcpy _ _ => False\n  | EF_builtin x sg => ~ is_I64_helper hf x sg\n  | EF_external x sg => ~ is_I64_helper hf x sg\n  | _ => True\n  end.\n\nLemma observableEF_dec ef: {observableEF ef} + {~observableEF ef}.\nProof.\ndestruct ef; simpl; try solve[left; trivial].\n  destruct (is_I64_helper_dec hf name sg).\n    right. intros N. apply (N i). \n    left; trivial. \n  destruct (is_I64_helper_dec hf name sg).\n    right. intros N. apply (N i). \n    left; trivial. \n  right; intros N. trivial.\n  right; intros N. trivial.\n  right; intros N. trivial.\nQed.\n\nDefinition EFisHelper ef :=\nmatch ef with \n    EF_builtin name sg => is_I64_helper hf name sg\n  | EF_external name sg => is_I64_helper hf name sg\n  | _ => False\nend.\n\nLemma EFhelpers ef: EFisHelper ef -> ~ observableEF ef.\nProof. unfold observableEF; intros. intros N.\ndestruct ef; simpl in H; trivial. apply (N H). apply (N H).\nQed. \n\nLemma EFhelpersE name sg: \n  ~ observableEF (EF_external name sg) ->\n  is_I64_helper hf name sg.\nProof. \nunfold observableEF. intros.\ndestruct (is_I64_helper_dec hf name sg). \n  trivial.\n  elim (H n). \nQed. \n\nLemma EFhelpersB name sg: \n  ~observableEF (EF_builtin name sg) ->\n  is_I64_helper hf name sg.\nProof. \nunfold observableEF. intros.\ndestruct (is_I64_helper_dec hf name sg). \n  trivial.\n  elim (H n). \nQed. \n\nLemma obs_efB name sg : is_I64_helper hf name sg ->\n     ~ observableEF (EF_builtin name sg).\nProof. intros. unfold observableEF. \n  intros N. apply (N H).\nQed.\n\nLemma obs_efE name sg : is_I64_helper hf name sg ->\n     ~ observableEF (EF_external name sg).\nProof. intros. unfold observableEF. \n  intros N. apply (N H).\nQed.\n\nDefinition helper_implements \n     (id: ident) (sg: signature) (vargs: list val) (vres: val) : Prop :=\n  exists b, exists ef,\n     Genv.find_symbol ge id = Some b\n  /\\ Genv.find_funct_ptr ge b = Some (External ef)\n  /\\ ef_sig ef = sg\n  /\\ (forall m, external_call ef ge vargs m E0 vres m)\n  (*NEW*) /\\ ~ observableEF ef.\n\nDefinition i64_helpers_correct: Prop :=\n    (forall x z, Val.longoffloat x = Some z -> helper_implements hf.(i64_dtos) sig_f_l (x::nil) z)\n  /\\(forall x z, Val.longuoffloat x = Some z -> helper_implements hf.(i64_dtou) sig_f_l (x::nil) z)\n  /\\(forall x z, Val.floatoflong x = Some z -> helper_implements hf.(i64_stod) sig_l_f (x::nil) z)\n  /\\(forall x z, Val.floatoflongu x = Some z -> helper_implements hf.(i64_utod) sig_l_f (x::nil) z)\n  /\\(forall x z, Val.singleoflong x = Some z -> helper_implements hf.(i64_stof) sig_l_s (x::nil) z)\n  /\\(forall x z, Val.singleoflongu x = Some z -> helper_implements hf.(i64_utof) sig_l_s (x::nil) z)\n  /\\(forall x, builtin_implements hf.(i64_neg) sig_l_l (x::nil) (Val.negl x))\n  /\\(forall x y, builtin_implements hf.(i64_add) sig_ll_l (x::y::nil) (Val.addl x y))\n  /\\(forall x y, builtin_implements hf.(i64_sub) sig_ll_l (x::y::nil) (Val.subl x y))\n  /\\(forall x y, builtin_implements hf.(i64_mul) sig_ii_l (x::y::nil) (Val.mull' x y)) (*LENB: Compcert had sig_ii here*)\n  /\\(forall x y z, Val.divls x y = Some z -> helper_implements hf.(i64_sdiv) sig_ll_l (x::y::nil) z)\n  /\\(forall x y z, Val.divlu x y = Some z -> helper_implements hf.(i64_udiv) sig_ll_l (x::y::nil) z)\n  /\\(forall x y z, Val.modls x y = Some z -> helper_implements hf.(i64_smod) sig_ll_l (x::y::nil) z)\n  /\\(forall x y z, Val.modlu x y = Some z -> helper_implements hf.(i64_umod) sig_ll_l (x::y::nil) z)\n  /\\(forall x y, helper_implements hf.(i64_shl) sig_li_l (x::y::nil) (Val.shll x y))\n  /\\(forall x y, helper_implements hf.(i64_shr) sig_li_l (x::y::nil) (Val.shrlu x y))\n  /\\(forall x y, helper_implements hf.(i64_sar) sig_li_l (x::y::nil) (Val.shrl x y)).\n\nEnd BUILTINS.\n\nRequire Import Errors.\n\n(*Moved here from Selection phase. We removed the dependence of\nget_helpers on ge since the implementation actually does not look at\nit.*)\n\nAxiom get_helpers_correct:\n  forall F V (ge:Genv.t (AST.fundef F) V) (hf : helper_functions), \n  get_helpers = OK hf ->  i64_helpers_correct ge hf.\n\nLemma BuiltinEffect_unchOn:\n    forall {F V:Type} hf ef (g : Genv.t F V) vargs m t vres m'\n    (OBS: ~ observableEF hf ef),\n    external_call ef g vargs m t vres m' -> \n    Mem.unchanged_on\n      (fun b z=> BuiltinEffect g ef vargs m b z = false) m m'.\nProof. intros.\n  destruct ef.\n    (*EF_external*)\n       inv H. apply Mem.unchanged_on_refl.\n    (*EF_builtin - same proof as previous case*)\n       inv H. apply Mem.unchanged_on_refl.\n    simpl in OBS. intuition.\n    simpl in OBS. intuition. \n    simpl in OBS. intuition. \n    simpl in OBS. intuition. \n    (*case EF_malloc*)\n       eapply  malloc_Effect_unchOn. eassumption.\n    (*case EF_free*)\n       eapply free_Effect_unchOn; eassumption.\n    (*case EE_memcpy*)\n       inv H. clear - H1 H6 H7.\n       eapply memcpy_Effect_unchOn; try eassumption. omega.\n    simpl in OBS. intuition.\n    simpl in OBS. intuition. \n    simpl in OBS. intuition.\nQed.\n\nLemma BuiltinEffect_valid_block:\n    forall {F V:Type} ef (g : Genv.t F V) vargs m b z,\n     BuiltinEffect g ef vargs m b z = true -> Mem.valid_block m b. \nProof. intros. unfold BuiltinEffect in H. \n  destruct ef; try discriminate.\n    eapply freeEffect_valid_block; eassumption.\n    eapply memcpy_Effect_validblock; eassumption.\nQed.\n\n(*takes the role of external_call_mem_inject\n  Since inlinables write at most to vis, we use the\n  Mem-Unchanged_on condition loc_out_of_reach, rather than\n  local_out_of_reach as in external calls.*)\nLemma inlineable_extern_inject: forall {F V TF TV:Type}\n       (ge:Genv.t F V) (tge:Genv.t TF TV) (GDE: genvs_domain_eq ge tge) \n       (SymbPres: forall s, Genv.find_symbol tge s = Genv.find_symbol ge s)\n       hf ef vargs m t vres m1 mu tm vargs'\n       (WD: SM_wd mu) (SMV: sm_valid mu m tm) (RC: REACH_closed m (vis mu))\n       (Glob: forall b, isGlobalBlock ge b = true -> \n              frgnBlocksSrc mu b = true)\n       (OBS: ~ observableEF hf ef),\n       meminj_preserves_globals ge (as_inj mu) ->\n       external_call ef ge vargs m t vres m1 ->\n       Mem.inject (as_inj mu) m tm ->\n       val_list_inject (restrict (as_inj mu) (vis mu)) vargs vargs' ->\n       exists mu' vres' tm1,\n         external_call ef tge vargs' tm t vres' tm1 /\\\n         val_inject (restrict (as_inj mu') (vis mu')) vres vres' /\\\n         Mem.inject (as_inj mu') m1 tm1 /\\\n         Mem.unchanged_on (loc_unmapped (restrict (as_inj mu) (vis mu))) m m1 /\\\n         Mem.unchanged_on (loc_out_of_reach (restrict (as_inj mu) (vis mu)) m) tm tm1 /\\\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 m1 tm1 /\\\n         SM_wd mu' /\\ sm_valid mu' m1 tm1 /\\\n         REACH_closed m1 (vis mu').\nProof. intros.\ndestruct ef; simpl in H0. \n(*EFexternal*)\n      eapply helpers_inject; try eassumption.\n      apply EFhelpersE; eassumption. \n    (*EF_builtin*)\n      eapply helpers_inject; try eassumption.\n      apply EFhelpersE; eassumption. \n    simpl in OBS; intuition.\n    simpl in OBS; intuition.\n    simpl in OBS; intuition.\n    simpl in OBS; intuition. \n    (*case EF_malloc*)\n    inv H0. inv H2. inv H8. inv H6. clear OBS.\n    exploit alloc_parallel_intern; eauto. apply Zle_refl. apply Zle_refl.\n    intros [mu' [tm' [tb [TALLOC [INJ' [INC [AI1 [AI2 [SEP [LOCALLOC [WD' [SMV' RC']]]]]]]]]]]].\n    exploit Mem.store_mapped_inject. eexact INJ'. eauto. eauto. \n    instantiate (1 := Vint n). auto.   \n    intros [tm1 [ST' INJ1]].\n    assert (visb': vis mu' b = true).\n        apply sm_locally_allocatedChar in LOCALLOC.\n        unfold vis. destruct LOCALLOC as [_ [_ [LOC _]]]. rewrite LOC.\n        rewrite (freshloc_alloc _ _ _ _ _ H3).\n        destruct (eq_block b b); subst; simpl. intuition. elim n0; trivial.\n    exists mu'; exists (Vptr tb Int.zero); exists tm1; intuition.\n      econstructor; eauto.\n      econstructor. eapply restrictI_Some; eassumption.\n      rewrite Int.add_zero. trivial.\n    split; unfold loc_unmapped; intros. unfold Mem.perm. \n         rewrite (Mem.store_access _ _ _ _ _ _ H4).\n         split; intros.\n         eapply Mem.perm_alloc_1; eassumption.\n         eapply Mem.perm_alloc_4; try eassumption.\n         intros N; subst; eapply (Mem.fresh_block_alloc _ _ _ _ _ H3 H5).\n      rewrite (Mem.store_mem_contents _ _ _ _ _ _ H4).\n        apply Mem.perm_valid_block in H5.\n        rewrite PMap.gso. \n          rewrite (AllocContentsOther1 _ _ _ _ _ H3). trivial. \n          intros N; subst; eapply (Mem.fresh_block_alloc _ _ _ _ _ H3 H5).\n        intros N; subst; eapply (Mem.fresh_block_alloc _ _ _ _ _ H3 H5).\n    split; unfold loc_out_of_reach; intros.\n         unfold Mem.perm. \n         rewrite (Mem.store_access _ _ _ _ _ _ ST').\n         split; intros.\n         eapply Mem.perm_alloc_1; eassumption.\n         eapply Mem.perm_alloc_4; try eassumption.\n         intros N; subst. eapply (Mem.fresh_block_alloc _ _ _ _ _ TALLOC H5).\n      rewrite (Mem.store_mem_contents _ _ _ _ _ _ ST').\n        apply Mem.perm_valid_block in H5.\n        rewrite PMap.gso. \n          rewrite (AllocContentsOther1 _ _ _ _ _ TALLOC). trivial. \n          intros N; subst; eapply (Mem.fresh_block_alloc _ _ _ _ _ TALLOC H5).\n          intros N; subst; eapply (Mem.fresh_block_alloc _ _ _ _ _ TALLOC H5).\n          eapply intern_incr_globals_separate; eauto.\n    rewrite sm_locally_allocatedChar.\n      rewrite sm_locally_allocatedChar in LOCALLOC.\n      destruct LOCALLOC as [LAC1 [LAC2 [LAC3 [LAC4 [LAC5 LOC6]]]]].\n      rewrite LAC1, LAC2, LAC3, LAC4, LAC5, LOC6; clear LAC1 LAC2 LAC3 LAC4 LAC5 LOC6.\n           repeat split; extensionality bb.\n             rewrite (freshloc_alloc _ _ _ _ _ H3).\n             rewrite <- (freshloc_trans m m'), (freshloc_alloc _ _ _ _ _ H3), (store_freshloc _ _ _ _ _ _ H4).\n             rewrite orb_false_r. trivial.\n             eapply alloc_forward; eassumption. eapply store_forward; eassumption.\n\n             rewrite (freshloc_alloc _ _ _ _ _ TALLOC).\n             rewrite <- (freshloc_trans tm tm'), (freshloc_alloc _ _ _ _ _ TALLOC), (store_freshloc _ _ _ _ _ _ ST').\n             rewrite orb_false_r. trivial.\n             eapply alloc_forward; eassumption. eapply store_forward; eassumption.\n\n             rewrite (freshloc_alloc _ _ _ _ _ H3).\n             rewrite <- (freshloc_trans m m'), (freshloc_alloc _ _ _ _ _ H3), (store_freshloc _ _ _ _ _ _ H4).\n             rewrite orb_false_r. trivial.\n             eapply alloc_forward; eassumption. eapply store_forward; eassumption.\n\n             rewrite (freshloc_alloc _ _ _ _ _ TALLOC).\n             rewrite <- (freshloc_trans tm tm'), (freshloc_alloc _ _ _ _ _ TALLOC), (store_freshloc _ _ _ _ _ _ ST').\n             rewrite orb_false_r. trivial.\n             eapply alloc_forward; eassumption. eapply store_forward; eassumption.\n\n        split; intros; eapply store_forward; try eassumption.\n          rewrite sm_locally_allocatedChar in LOCALLOC.\n          destruct LOCALLOC as [LAC1 _]. unfold DOM in H2; rewrite LAC1 in H2; clear LAC1.\n          rewrite (freshloc_alloc _ _ _ _ _ H3) in H2.\n          destruct (eq_block b1 b); subst; simpl in *.\n            eapply Mem.valid_new_block; eassumption.\n          rewrite orb_false_r in H2. \n            eapply Mem.valid_block_alloc; try eassumption.\n            eapply SMV; eassumption.\n\n          rewrite sm_locally_allocatedChar in LOCALLOC.\n          destruct LOCALLOC as [_ [LAC2 _]]. unfold RNG in H2; rewrite LAC2 in H2; clear LAC2.\n          rewrite (freshloc_alloc _ _ _ _ _ TALLOC) in H2.\n          destruct (eq_block b2 tb); subst; simpl in *.\n            eapply Mem.valid_new_block; eassumption.\n          rewrite orb_false_r in H2. \n            eapply Mem.valid_block_alloc; try eassumption.\n            eapply SMV; eassumption.\n      eapply (REACH_Store m'); try eassumption.\n      intros ? getBl. rewrite getBlocks_char in getBl. \n         destruct getBl as [zz [ZZ | ZZ]]; inv ZZ.\n  (*case EF_free*)\n    inv H0. inv H2. inv H9. inv H7.\n    destruct (restrictD_Some _ _ _ _ _ H6) as [AIb VISb].\n    exploit free_parallel_inject; try eassumption.\n    intros [tm1 [TFR Inj1]].\n    exploit (Mem.load_inject (as_inj mu) m); try eassumption.\n    intros [v [TLD Vinj]]. inv Vinj.\n    assert (Mem.range_perm m b (Int.unsigned lo - 4) (Int.unsigned lo + Int.unsigned sz) Cur Freeable).\n      eapply Mem.free_range_perm; eauto.\n    exploit Mem.address_inject. eapply H1. \n      apply Mem.perm_implies with Freeable; auto with mem.\n      apply H0. instantiate (1 := lo). omega.\n      eassumption. \n    intro EQ.\n    assert (Mem.range_perm tm b2 (Int.unsigned lo + delta - 4) (Int.unsigned lo + delta + Int.unsigned sz) Cur Freeable).\n      red; intros. \n      replace ofs with ((ofs - delta) + delta) by omega.\n      eapply Mem.perm_inject. eassumption. eassumption. eapply H0. omega.\n(*    destruct (Mem.range_perm_free _ _ _ _ H2) as [m2' FREE].*)\n    exists mu; eexists; exists tm1; split.\n      simpl. econstructor.\n       rewrite EQ. replace (Int.unsigned lo + delta - 4) with (Int.unsigned lo - 4 + delta) by omega.\n       eauto. auto. \n      rewrite EQ. clear - TFR.\n        assert (Int.unsigned lo + delta - 4 = Int.unsigned lo - 4 + delta). omega. rewrite H; clear H.\n        assert (Int.unsigned lo + delta + Int.unsigned sz = Int.unsigned lo + Int.unsigned sz + delta). omega. rewrite H; clear H.\n        assumption.\n     intuition.  \n\n     eapply Mem.free_unchanged_on; eauto. \n       unfold loc_unmapped; intros. congruence.\n\n     eapply Mem.free_unchanged_on; eauto.   \n       unfold loc_out_of_reach; intros. red; intros. eelim H8; eauto. \n       apply Mem.perm_cur_max. apply Mem.perm_implies with Freeable; auto with mem.\n       apply H0. omega.\n\n       apply intern_incr_refl.\n       apply sm_inject_separated_same_sminj.\n       apply gsep_refl.\n     apply sm_locally_allocatedChar.\n       repeat split; try extensionality bb; simpl.\n       rewrite (freshloc_free _ _ _ _ _ H5). clear. intuition.\n       rewrite (freshloc_free _ _ _ _ _ TFR). clear. intuition.\n       rewrite (freshloc_free _ _ _ _ _ H5). clear. intuition.\n       rewrite (freshloc_free _ _ _ _ _ TFR). clear. intuition.\n     split; intros; eapply Mem.valid_block_free_1; try eassumption.\n       eapply SMV; assumption. eapply SMV; assumption.\n     eapply REACH_closed_free; eassumption.\n  (*memcpy*)\n     clear OBS.\n     inv H0. \n  exploit Mem.loadbytes_length; eauto. intros LEN.\n  assert (RPSRC: Mem.range_perm m bsrc (Int.unsigned osrc) (Int.unsigned osrc + sz) Cur Nonempty).\n    eapply Mem.range_perm_implies. eapply Mem.loadbytes_range_perm; eauto. auto with mem.\n  assert (RPDST: Mem.range_perm m bdst (Int.unsigned odst) (Int.unsigned odst + sz) Cur Nonempty).\n    replace sz with (Z_of_nat (length bytes)).\n    eapply Mem.range_perm_implies. eapply Mem.storebytes_range_perm; eauto. auto with mem.\n    rewrite LEN. apply nat_of_Z_eq. omega.\n  assert (PSRC: Mem.perm m bsrc (Int.unsigned osrc) Cur Nonempty).\n    apply RPSRC. omega.\n  assert (PDST: Mem.perm m bdst (Int.unsigned odst) Cur Nonempty).\n    apply RPDST. omega.\n  inv H2. inv H12. inv H14. inv H15. inv H12.\n  destruct (restrictD_Some _ _ _ _ _ H11).\n  destruct (restrictD_Some _ _ _ _ _ H13).\n  exploit Mem.address_inject.  eauto. eexact PSRC. eauto. intros EQ1.\n  exploit Mem.address_inject.  eauto. eexact PDST. eauto. intros EQ2.\n  exploit Mem.loadbytes_inject; eauto. intros [bytes2 [A B]].\n  exploit Mem.storebytes_mapped_inject; eauto. intros [m2' [C D]].\n  exists mu; exists Vundef; exists m2'.\n  split. econstructor; try rewrite EQ1; try rewrite EQ2; eauto. \n  eapply Mem.aligned_area_inject with (m := m); eauto.\n  eapply Mem.aligned_area_inject with (m := m); eauto.\n  eapply Mem.disjoint_or_equal_inject with (m := m); eauto.\n  apply Mem.range_perm_max with Cur; auto.\n  apply Mem.range_perm_max with Cur; auto.\n  split. constructor.\n  split. auto.\n  split. eapply Mem.storebytes_unchanged_on; eauto.\n         unfold loc_unmapped; intros. rewrite H11. congruence.\n  split. eapply Mem.storebytes_unchanged_on; eauto.\n         unfold loc_out_of_reach; intros. red; intros.\n         eapply (H16 _ _ H11). \n             apply Mem.perm_cur_max. apply Mem.perm_implies with Writable; auto with mem.\n             eapply Mem.storebytes_range_perm; eauto.  \n             erewrite list_forall2_length; eauto. \n             omega.\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; try extensionality bb; simpl.\n       rewrite (storebytes_freshloc _ _ _ _ _ H10). clear. intuition.\n       rewrite (storebytes_freshloc _ _ _ _ _ C). clear. intuition.\n       rewrite (storebytes_freshloc _ _ _ _ _ H10). clear. intuition.\n       rewrite (storebytes_freshloc _ _ _ _ _ C). clear. intuition.\n  split; trivial. \n  split. split; intros.\n       eapply storebytes_forward; try eassumption.\n          eapply SMV; trivial.\n       eapply storebytes_forward; try eassumption.\n          eapply SMV; trivial.\n  destruct (loadbytes_D _ _ _ _ _ H9); clear A C.\n   clear RPSRC RPDST PSRC PDST H8 H11 H3 H5 H6 H7 EQ1 EQ2 B D.  \n  intros. eapply REACH_Storebytes; try eassumption.\n          intros. eapply RC. subst bytes.\n          destruct (in_split _ _ H3) as [bts1 [bts2 Bytes]]; clear H3.\n          specialize (getN_range _ _ _ _ _ _ Bytes). intros.\n          apply getN_aux in Bytes. \n          eapply REACH_cons. instantiate(1:=bsrc).\n            eapply REACH_nil. assumption.\n            Focus 2. apply eq_sym. eassumption. \n            eapply H15. clear - H3 H4. \n            split. specialize (Zle_0_nat (length bts1)). intros. omega.\n                   apply inj_lt in H3. rewrite nat_of_Z_eq in H3; omega.\n    simpl in OBS; intuition.\n    simpl in OBS; intuition.\n    simpl in OBS; intuition. \nQed.\n\nLemma BuiltinEffect_Propagate: forall {F V TF TV:Type}\n       (ge:Genv.t F V) (tge:Genv.t TF TV) ef m vargs t vres m'\n       (EC : external_call ef ge vargs m t vres m') mu m2 tvargs\n       (ArgsInj : val_list_inject (restrict (as_inj mu) (vis mu)) vargs tvargs)\n       (WD : SM_wd mu) (MINJ : Mem.inject (as_inj mu) m m2),\n     forall b ofs, BuiltinEffect tge ef tvargs m2 b ofs = true ->\n       visTgt mu b = true /\\\n       (locBlocksTgt mu b = false ->\n        exists b1 delta1,\n           foreign_of mu b1 = Some (b, delta1) /\\\n           BuiltinEffect ge ef vargs m b1 (ofs - delta1) = true /\\\n           Mem.perm m b1 (ofs - delta1) Max Nonempty).\nProof.\n intros. destruct ef; try inv H.\n  (*free*)\n    simpl in EC. inv EC. \n    inv ArgsInj. inv H7. inv H5.\n    rewrite H1. unfold free_Effect in H1.\n    destruct (restrictD_Some _ _ _ _ _ H6) as [AIb VISb].\n    exploit (Mem.load_inject (as_inj mu) m); try eassumption.\n    intros [v [TLD Vinj]]. inv Vinj.\n    assert (RP: Mem.range_perm m b0 (Int.unsigned lo - 4) (Int.unsigned lo + Int.unsigned sz) Cur Freeable).\n      eapply Mem.free_range_perm; eauto.\n    exploit Mem.address_inject. eapply MINJ. \n      apply Mem.perm_implies with Freeable; auto with mem.\n      apply RP. instantiate (1 := lo). omega.\n      eassumption. \n    intro EQ.\n    rewrite EQ in *.\n    assert (Arith4: Int.unsigned lo - 4 + delta = Int.unsigned lo + delta - 4) by omega.\n    rewrite Arith4, TLD in *.\n    destruct (eq_block b b2); subst; simpl in *; try inv H1.\n    rewrite H, H4.\n    split. eapply visPropagateR; eassumption.\n    intros. exists b0, delta.\n    rewrite restrict_vis_foreign_local in H6; trivial.\n    destruct (joinD_Some _ _ _ _ _ H6) as [FRG | [FRG LOC]]; clear H6.\n    Focus 2. destruct (local_DomRng _ WD _ _ _ LOC). rewrite H5 in H1; discriminate.\n    split; trivial.\n    destruct (eq_block b0 b0); simpl in *.\n    Focus 2. elim n; trivial. \n    clear e. \n        destruct (zlt 0 (Int.unsigned sz)); simpl in *; try inv H4.\n        destruct (zle (Int.unsigned lo + delta - 4) ofs); simpl in *; try inv H5.\n        destruct (zlt ofs (Int.unsigned lo + delta + Int.unsigned sz)); simpl in *; try inv H4.\n        destruct (zle (Int.unsigned lo - 4) (ofs - delta)); simpl in *; try omega.\n        split. destruct (zlt (ofs - delta) (Int.unsigned lo + Int.unsigned sz)); trivial.\n                 omega. \n        eapply Mem.perm_implies. \n          eapply Mem.perm_max. eapply RP. split; trivial. omega.\n          constructor. \n     (*memcpy*)\n        simpl in EC. inv EC. \n        inv ArgsInj. inv H12. inv H10. inv H11. inv H14. \n        rewrite H1. unfold memcpy_Effect in H1.\n        destruct (eq_block b b2); subst; simpl in *; try inv H1.\n        destruct (zle (Int.unsigned (Int.add odst (Int.repr delta))) ofs); simpl in *; try inv H9. \n        destruct (zlt ofs (Int.unsigned (Int.add odst (Int.repr delta)) + sz)); simpl in *; try inv H1.\n        destruct (valid_block_dec m2 b2); simpl in *; try inv H9.\n        split. eapply visPropagateR; eassumption.\n        intros. exists bdst, delta.\n        destruct (restrictD_Some _ _ _ _ _ H12).\n        exploit Mem.address_inject.\n           eapply MINJ.\n           eapply Mem.storebytes_range_perm. eassumption.\n           split. apply Z.le_refl.\n             rewrite (Mem.loadbytes_length _ _ _ _ _ H6).\n               rewrite nat_of_Z_eq; omega.\n           eassumption.\n        intros UNSIG; rewrite UNSIG in *.\n        assert (MP: Mem.perm m bdst (ofs - delta) Max Nonempty).\n           eapply Mem.perm_implies.\n             eapply Mem.perm_max. \n             eapply Mem.storebytes_range_perm. eassumption.\n             rewrite (Mem.loadbytes_length _ _ _ _ _ H6).\n             rewrite nat_of_Z_eq; omega.\n           constructor. \n        rewrite (restrict_vis_foreign_local _ WD) in H12.\n        destruct (joinD_Some _ _ _ _ _ H12) as [FRG | [FRG LOC]]; clear H12.\n          split; trivial. split; trivial.\n          destruct (eq_block bdst bdst); simpl. clear e.\n            destruct (zle (Int.unsigned odst) (ofs - delta)); simpl.\n              destruct (zlt (ofs - delta) (Int.unsigned odst + sz)); simpl.\n                destruct (valid_block_dec m bdst); trivial.\n                elim n. eapply Mem.perm_valid_block; eassumption.\n              omega.\n            omega.\n          elim n; trivial.\n        destruct (local_DomRng _ WD _ _ _ LOC).\n          rewrite H13 in H1. discriminate.\n  inv H8.\n  inv H8.\nQed.\n\nLemma BuiltinEffect_Propagate': forall {F V TF TV:Type}\n       (ge:Genv.t F V) (tge:Genv.t TF TV) ef m vargs t vres m'\n       (EC : external_call' ef ge vargs m t vres m') mu m2 tvargs\n       (ArgsInj : val_list_inject (restrict (as_inj mu) (vis mu)) vargs tvargs)\n       (WD : SM_wd mu) (MINJ : Mem.inject (as_inj mu) m m2),\n     forall b ofs, BuiltinEffect tge ef tvargs m2 b ofs = true ->\n       visTgt mu b = true /\\\n       (locBlocksTgt mu b = false ->\n        exists b1 delta1,\n           foreign_of mu b1 = Some (b, delta1) /\\\n           BuiltinEffect ge ef vargs m b1 (ofs - delta1) = true /\\\n           Mem.perm m b1 (ofs - delta1) Max Nonempty).\nProof.\n intros. \n destruct ef; try inv H.\n  (*free*)\n  { simpl in EC. inv EC. \n    inv ArgsInj. inv H. inv H. inv H0. \n    rewrite H1. unfold free_Effect in H1.\n    destruct (restrictD_Some _ _ _ _ _ H7) as [AIb VISb].\n    exploit (Mem.load_inject (as_inj mu) m); try eassumption.\n    intros [v [TLD Vinj]]. inv Vinj.\n    assert (RP: Mem.range_perm m b0 (Int.unsigned lo - 4)\n                               (Int.unsigned lo + Int.unsigned sz) Cur Freeable).\n    { eapply Mem.free_range_perm; eauto. }\n    exploit Mem.address_inject. eapply MINJ. \n    { apply Mem.perm_implies with Freeable; auto with mem.\n      apply RP. instantiate (1 := lo). omega. }\n    eassumption. \n    intro EQ.\n    rewrite EQ in *.\n    assert (Arith4: Int.unsigned lo - 4 + delta = Int.unsigned lo + delta - 4) by omega.\n    rewrite Arith4, TLD in *.\n    destruct (eq_block b b2); subst; simpl in *; try inv H1.\n    { rewrite H0,H4.\n      split. eapply visPropagateR; eassumption.\n      intros. exists b0, delta.\n      rewrite restrict_vis_foreign_local in H7; trivial.\n      destruct (joinD_Some _ _ _ _ _ H7) as [FRG | [FRG LOC]]; clear H7.\n      Focus 2. destruct (local_DomRng _ WD _ _ _ LOC). solve[rewrite H3 in H; discriminate].\n      split; trivial.\n      inv H2.\n      destruct (eq_block b0 b0); simpl in *.\n      Focus 2. elim n; trivial. \n      clear e.\n      rewrite !andb_true_iff in H0.\n      destruct H0 as [[[? ?] ?] ?].\n      destruct (zlt 0 (Int.unsigned sz)); simpl in *; try inv H1.\n      destruct (zle (Int.unsigned lo + delta - 4) ofs); simpl in *; try inv H2.\n      destruct (zlt ofs (Int.unsigned lo + delta + Int.unsigned sz)); simpl in *; try inv H3.\n      destruct (zle (Int.unsigned lo - 4) (ofs - delta)); simpl in *; try omega.\n      split. destruct (zlt (ofs - delta) (Int.unsigned lo + Int.unsigned sz)); trivial.\n      omega. \n      eapply Mem.perm_implies. \n      eapply Mem.perm_max. eapply RP. split; trivial. omega.\n      constructor. \n      congruence. }\n    { (*b<>b2*)\n      destruct vl'; try congruence.\n      rewrite !andb_true_iff in H0.\n      destruct H0 as [[[? ?] ?] ?].\n      destruct (eq_block b b2). subst. congruence. simpl in H. congruence. }}\n  { (*memcpy*)\n    simpl in EC. inv EC.\n    inv ArgsInj. inv H. inv H2. inv H. \n    rewrite H1. unfold memcpy_Effect in H1. inv H.\n    inv H0; try congruence. \n    inv H3; try congruence.\n    inv H4; try congruence.\n    destruct (eq_block b b2); subst; simpl in *; try inv H1.\n    destruct (zle (Int.unsigned (Int.add odst (Int.repr delta))) ofs); simpl in *; try inv H4. \n    destruct (zlt ofs (Int.unsigned (Int.add odst (Int.repr delta)) + sz)); simpl in *; try inv H3.\n    destruct (valid_block_dec m2 b2); simpl in *; try inv H4.\n    split. eapply visPropagateR; eassumption.\n    intros. exists bdst, delta.\n    destruct (restrictD_Some _ _ _ _ _ H5).\n    exploit Mem.address_inject.\n    eapply MINJ.\n    eapply Mem.storebytes_range_perm; eauto.\n    split. apply Z.le_refl.\n    rewrite (Mem.loadbytes_length _ _ _ _ _ H12).\n    rewrite nat_of_Z_eq; omega. \n    eassumption.\n    intros UNSIG; rewrite UNSIG in *.\n    assert (MP: Mem.perm m bdst (ofs - delta) Max Nonempty).\n    { eapply Mem.perm_implies.\n      eapply Mem.perm_max. \n      eapply Mem.storebytes_range_perm. eassumption.\n      rewrite (Mem.loadbytes_length _ _ _ _ _ H12).\n      rewrite nat_of_Z_eq; omega.\n      constructor. }\n    rewrite (restrict_vis_foreign_local _ WD) in H5.\n    destruct (joinD_Some _ _ _ _ _ H5) as [FRG | [FRG LOC]]; clear H5.\n    split; trivial. split; trivial.\n    destruct (eq_block bdst bdst); simpl. clear e.\n    destruct (zle (Int.unsigned odst) (ofs - delta)); simpl.\n    destruct (zlt (ofs - delta) (Int.unsigned odst + sz)); simpl.\n    destruct (valid_block_dec m bdst); trivial.\n    elim n. eapply Mem.perm_valid_block; eassumption.\n    omega.\n    omega.\n    elim n; trivial.\n    destruct (local_DomRng _ WD _ _ _ LOC).\n    rewrite H5 in H. discriminate.\n  inv H8.\n  congruence.\n  congruence.\n  congruence. }\nQed.\n\nLemma helpers_EmptyEffect: forall {F V:Type} (ge: Genv.t F V) \n   hf ef args m,\n   EFisHelper hf ef -> (BuiltinEffect ge ef args m = EmptyEffect).\nProof. intros.\ndestruct ef; simpl in *; try reflexivity.\ncontradiction. contradiction.\nQed.\n\nRequire Import Conventions.\nLemma BuiltinEffect_decode: forall F V (ge: Genv.t F V) ef tls,\n BuiltinEffect ge ef (map tls (loc_arguments (ef_sig ef))) =\n BuiltinEffect ge ef (decode_longs (sig_args (ef_sig ef))\n           (map tls (loc_arguments (ef_sig ef)))).\nProof. intros.\n  unfold BuiltinEffect. extensionality m. \n  destruct ef; trivial.\nQed.\n\nSection EC_DET.\n\nContext (hf : helper_functions) \n        {F V : Type} (ge : Genv.t F V) (t1 t2: trace) (m m1 m2:mem).\n\nDefinition is_I64_helper' hf ef :=\n  match ef with\n    | EF_external nm sg => is_I64_helper hf nm sg\n    | EF_builtin nm sg => is_I64_helper hf nm sg\n    | _ => False\n  end.\n\nLemma is_I64_helper'_dec ef : {is_I64_helper' hf ef}+{~is_I64_helper' hf ef}.\nProof.\ndestruct ef; simpl; auto.\ndestruct (is_I64_helper_dec hf name sg); auto.\ndestruct (is_I64_helper_dec hf name sg); auto.\nQed.\n\nLemma EC'_determ: forall ef args res1 res2,  \n      external_call' ef ge args m t1 res1 m1 ->\n      external_call' ef ge args m t2 res2 m2 ->\n      ~ is_I64_helper' hf ef -> \n      ~ observableEF hf ef -> t1=t2.\nProof. intros.\ndestruct ef; simpl in H2; intuition.\n(*EF_malloc*)\ninv H; inv H0. simpl in *. destruct args. inv H; inv H2.\n    inv H; inv H3. trivial.\n(*EF_free*)\ninv H; inv H0. simpl in *. destruct args. inv H; inv H2.\n    inv H; inv H3. trivial.\n(*EF_memcpy*)\ninv H; inv H0. simpl in *. destruct args. inv H; inv H2.\n   destruct args. inv H; inv H2. inv H; inv H3. trivial.\nQed.\n\n(** i64_helpers_correct axiomatizes the helpers with empty trace (E0).\n  Elsewhere in standard CompCert, these functions are give the\n  Event_syscall trace (by extcall_io_sem). Here, we just impose\n  determinism on the traces (which is consistent with the E0\n  axiomatization used, e.g., in Selectlongproof.v). *)\n\nAxiom EC'_i64_helper_determ: forall ef args res1 res2,  (*SEE NOTE ABOVE*)\n      external_call' ef ge args m t1 res1 m1 ->\n      external_call' ef ge args m t2 res2 m2 ->\n      is_I64_helper' hf ef -> \n      ~ observableEF hf ef -> t1=t2.\n\nEnd EC_DET.\n", "meta": {"author": "PrincetonUniversity", "repo": "compcomp", "sha": "eebb7d5a95fed97775cef7f014399be78abbe7bf", "save_path": "github-repos/coq/PrincetonUniversity-compcomp", "path": "github-repos/coq/PrincetonUniversity-compcomp/compcomp-eebb7d5a95fed97775cef7f014399be78abbe7bf/backend/BuiltinEffects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.28768585485296927}}
{"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.\nRequire Export Wf_nat.\nRequire Export Compare_dec.\n\nRequire Import Term_const.\n\nFixpoint div2 (n : nat) : nat :=\n  match n with\n  | S (S p) => S (div2 p)\n  | _ => 0\n  end.\n\nParameter div2_lt : forall x : nat, div2 (S x) < S x.\n\nRecursive Definition log (nat -> nat) lt lt_wf div2_lt\n (forall x : nat,\n  log x =\n  match x with\n  | O => 0\n  | S O => 0\n  | S (S y) => S (log (div2 (S (S y))))\n  end).\n\nInspect 5.\n(* Pour tester pas-à-pas:\n\nDefinition log_nat :=\n    [log:nat -> nat] [x:nat]\n    (Cases x of\n        O => (0)\n      | (S O) => (O)\n      | (S (S y)) => (S (log (div2 (S (S y)))))\n     end).\n\nL_Terminate log_nat nat lt lt_wf log_term div2_lt.\n\nDefine_from_terminate log nat log_term.\n\nMake_equation log_equation log_nat log log_term\n  (x:nat)(log x)=\n\t(Case (le_gt_dec x (1)) of [h:?] O [h:?] (S (log (div2 x))) end).\n\n\n *)", "meta": {"author": "coq-contribs", "repo": "recursive-definition", "sha": "2f6e9b0ca0dbd1470bff286d0712ec2b8ece6d4f", "save_path": "github-repos/coq/coq-contribs-recursive-definition", "path": "github-repos/coq/coq-contribs-recursive-definition/recursive-definition-2f6e9b0ca0dbd1470bff286d0712ec2b8ece6d4f/data7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765155565327, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2876750577850073}}
{"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_cequiv.\nRequire Export per_props_function.\nRequire Export per_props_uni.\n\n\nLemma equality_in_mkc_requality {p} :\n  forall lib (t1 t2 T a b : @CTerm p),\n    equality lib a b (mkc_requality t1 t2 T)\n    <=>\n    { x1 , x2  : CTerm\n    , a ===>(lib) (mkc_refl x1)\n    # b ===>(lib) (mkc_refl x2)\n    # equality lib t1 t2 T\n    # equality lib t1 x1 T\n    # equality lib t2 x2 T }.\nProof.\n  introv; split; intro i.\n\n  - unfold equality in i; exrepnd.\n    inversion i1; subst; try not_univ.\n\n    match goal with\n    | [ H : per_req _ _ _ _ _ |- _ ] => rename H into h\n    end.\n\n    unfold per_req in h; exrepnd; spcast; computes_to_value_isvalue.\n    fold (nuprl lib) in *.\n    apply h0 in i0.\n    unfold per_req_eq in i0; exrepnd.\n    exists x1 x2; dands; auto;\n      try (complete (eapply eq_equality1;eauto)).\n\n  - exrepnd.\n    unfold equality in i3; exrepnd.\n    exists (per_req_eq lib t1 t2 eq).\n    dands; auto.\n\n    + apply CL_req.\n      exists T T t1 t2 t1 t2 eq; dands; spcast; eauto 3 with slow;\n        right; spcast; auto.\n\n    + exists x1 x2; dands; auto; try (complete (eapply equality_eq1; eauto)).\nQed.\n\n(* !!MOVE *)\nHint Resolve tequality_if_nuprl : slow.\n\n(* !!MOVE *)\nLemma tequality_implies_type_left {p} :\n  forall lib (A B : @CTerm p),\n    tequality lib A B -> type lib A.\nProof.\n  introv teq.\n  unfold type.\n  eapply tequality_refl; eauto.\nQed.\nHint Resolve tequality_implies_type_left : slow.\n\n(* !!MOVE *)\nLemma tequality_implies_type_right {p} :\n  forall lib (A B : @CTerm p),\n    tequality lib A B -> type lib B.\nProof.\n  introv teq.\n  unfold type.\n  apply tequality_sym in teq.\n  eapply tequality_refl; eauto.\nQed.\nHint Resolve tequality_implies_type_right : slow.\n\n(* !!MOVE *)\nHint Resolve eq_equality1 : slow.\n\nLemma tequality_mkc_requality {p} :\n  forall lib (a1 a2 b1 b2 A B : @CTerm p),\n    tequality lib (mkc_requality a1 a2 A) (mkc_requality b1 b2 B)\n    <=>\n    (\n      tequality lib A B\n      # equorsq lib a1 b1 A\n      # equorsq lib a2 b2 A\n    ).\nProof.\n  introv; split; intro h.\n\n  - unfold tequality in h; exrepnd.\n    inversion h0; subst; try not_univ.\n\n    match goal with\n    | [ H : per_req _ _ _ _ _ |- _ ] => rename H into h\n    end.\n\n    unfold per_req in h; exrepnd; spcast; computes_to_value_isvalue.\n    fold (nuprl lib) in *.\n    dands; eauto 3 with slow; eapply eqorceq_iff_equorsq; eauto.\n\n  - repnd.\n    unfold tequality in h0; exrepnd.\n    rename eq into eqa.\n    exists (per_req_eq lib a1 a2 eqa).\n    apply CL_req.\n    exists A B a1 a2 b1 b2 eqa; dands; spcast; eauto 3 with slow;\n      eapply eqorceq_iff_equorsq; eauto.\nQed.\n\nLemma equality_in_mkc_rmember {p} :\n  forall lib (t T a b : @CTerm p),\n    equality lib a b (mkc_rmember t T)\n    <=>\n    { x1 , x2  : CTerm\n    , a ===>(lib) (mkc_refl x1)\n    # b ===>(lib) (mkc_refl x2)\n    # equality lib t x1 T\n    # equality lib t x2 T }.\nProof.\n  introv.\n  allrw <- @fold_mkc_rmember.\n  rw @equality_in_mkc_requality.\n  split; intro h; exrepnd; exists x1 x2; dands; auto.\n  eapply equality_refl; eauto.\nQed.\n\nLemma tequality_mkc_rmember {p} :\n  forall lib (a b A B : @CTerm p),\n    tequality lib (mkc_rmember a A) (mkc_rmember b B)\n    <=>\n    (\n      tequality lib A B\n      # equorsq lib a b A\n    ).\nProof.\n  introv.\n  allrw <- @fold_mkc_rmember.\n  rw @tequality_mkc_requality; split; 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/per/per_props_requality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.28767505778500724}}
{"text": "From iris Require Import invariants.\nFrom iris.algebra Require Import gmap frac agree frac_auth.\nFrom iris.base_logic Require Export gen_heap.\nFrom iris.base_logic.lib Require Export own saved_prop.\nFrom iris.program_logic Require Export weakestpre.\nFrom iris.proofmode Require Import tactics.\nFrom stdpp Require Import base.\nFrom distris Require Import lifting tactics proofmode notation adequacy.\nFrom distris.examples.library Require Import code.\nFrom iris.proofmode Require Import coq_tactics.\nFrom iris.proofmode Require Export tactics.\n\nSet Default Proof Using \"Type\".\n\nImport Network.\nImport String.\nImport uPred.\n\nSection strings.\n\n  Lemma append_nil_l s :\n    \"\" +:+ s = s.\n  Proof. done. Qed.\n\n  Lemma append_cons s1 :\n    ∀ s2 a, String a (s1 +:+ s2) = (String a s1) +:+ s2.\n  Proof.\n    induction s1; intros.\n    - by rewrite append_nil_l.\n    - rewrite -IHs1. done.\n  Qed.\n\n  Lemma append_assoc s1 s2 s3 :\n    s1 +:+ s2 +:+ s3 = (s1 +:+ s2) +:+ s3.\n  Proof.\n    induction s1.\n    - by rewrite !append_nil_l.\n    - by rewrite -append_cons IHs1 append_cons.\n  Qed.\n\n  Lemma length_Sn a s :\n    length (String a s) = S (length s).\n  Proof. by cbn. Qed.\n\n  Lemma length_app s1 :\n    ∀ s2, length (s1 +:+ s2) = length s1 + length s2.\n  Proof.\n   induction s1; intros.\n    - by rewrite append_nil_l.\n    - by rewrite -append_cons !length_Sn IHs1.\n  Qed.\n\n  Lemma prefix_empty_true s :\n    prefix \"\" s = true.\n  Proof. destruct s; cbn; auto. Qed.\n\n  Lemma index_0_empty s :\n    index 0 \"\" s = Some 0.\n  Proof. destruct s; by cbn. Qed.\n\n  Lemma index_prefix_true s s' :\n    index 0 s s' = Some 0 →\n    prefix s s' = true.\n  Proof.\n    destruct s,s'; simpl; cbn; auto.\n    - intro; inversion H.\n    - intro; destruct ascii_dec.\n      + destruct (prefix s s'); auto; destruct (index 0 _ s'); inversion H.\n      + destruct (index 0 _ s'); inversion H.\n  Qed.\n\n  Lemma index_cons_0_eq a s s' :\n    index 0 s s' = Some 0 → index 0 (String a s) (String a s') = Some 0.\n  Proof.\n    intros Hindex.\n    cbn. destruct ascii_dec.\n    - assert (Hprefix: prefix s s' = true).\n      { by apply index_prefix_true. }\n        by rewrite Hprefix.\n    - by destruct n.\n  Qed.\n\n  Lemma index_append_here s t :\n    index 0 s (s +:+ t) = Some 0.\n  Proof.\n    induction s.\n    - apply index_0_empty.\n    - apply index_cons_0_eq.\n      apply IHs.\n  Qed.\n\n  Lemma index_0_append_char a t v s :\n    s = String a \"\" →\n    index 0 s t = None →\n    index 0 s (t +:+ s +:+ v) = Some (length t).\n  Proof.\n    induction t; intros.\n    - rewrite append_nil_l. apply index_append_here.\n    - rewrite H. rewrite -append_cons. cbn.\n      destruct ascii_dec; subst. cbn in H0. destruct ascii_dec.\n      rewrite prefix_empty_true in H0. inversion H0.\n      by destruct n.\n      rewrite IHt; auto. cbn in H0. destruct ascii_dec. by destruct n.\n      destruct index; auto. inversion H0.\n  Qed.\n\n  Lemma substring_0_length s :\n    substring 0 (length s) s = s.\n  Proof. induction s; simpl; auto. by rewrite IHs. Qed.\n\n  Lemma substring_Sn a n m s :\n    substring (S n) m (String a s) = substring n m s.\n  Proof. induction s; destruct n,m; simpl; auto. Qed.\n\n  Lemma substring_add_length_app n m s1 :\n    ∀ s2, substring (length s1 + n) m (s1 +:+ s2) = substring n m s2.\n  Proof. induction s1; destruct n,m; simpl; auto. Qed.\n\n  Lemma substring_0_length_append s1 s2 :\n    substring 0 (length s1) (s1 +:+ s2) = s1.\n  Proof. apply prefix_correct, index_prefix_true, index_append_here. Qed.\n\n  Lemma substring_length_append s1 :\n    ∀ s2, substring (length s1) (length s2) (s1 +:+ s2) = s2.\n  Proof.\n    induction s1; intros s2.\n    - rewrite append_nil_l. apply substring_0_length.\n    - rewrite length_Sn substring_Sn. apply IHs1.\n  Qed.\n\nEnd strings.\n\nSection library.\n  Context `{cG : ccounterG Σ}\n          `{dG : distG Σ}\n          `{siG : socketInterpG Σ}.\n\nLemma wp_assert n E (Φ : val → iProp Σ) e `{!Closed [] ⟨n;e⟩} :\n  WP ⟨n;e⟩ @ E {{ v, ⌜v = 〈n;#true〉⌝ ∧ ▷ Φ 〈n;#()〉 }} -∗ WP ⟨n;assert: e⟩ @ E {{ Φ }}.\nProof.\n  iIntros \"HΦ\". rewrite /assert /=.\n  wp_lam. rewrite /ground_lang.subst.\n  wp_let.\n  wp_apply (wp_wand with \"HΦ\").\n  iIntros (v) \"[% ?]\"; subst.  by wp_if.\nQed.\n\nLemma unSOME_spec n e v v' :\n  IntoVal ⟨n;e⟩ 〈n;v〉 →\n  {{{ ⌜v = SOMEV v'⌝ }}}\n    ⟨n;unSOME e⟩\n  {{{ RET 〈n;v'〉; True }}}.\nProof.\n  iIntros (<-%to_base_val'%ground_lang.of_to_val Φ ->) \"HΦ\".\n  wp_lam. wp_match. by iApply \"HΦ\".\nQed.\n\nLemma listen_spec P Q n (h : socket_handle) (s : socket) (a : socket_address)\n        (rm : message_soup)\n        (handler : ground_lang.expr) :\n  AsVal ⟨n;handler⟩ →\n  saddress s = Some a →\n  (∀ mId m φ,\n      {{{ ⌜received_message_info a m⌝ ∗ P ∗ h s↦[n] s ∗ a r↦{½} (<[mId:=m]>rm) ∗\n           mId m↦{¾} m ∗ a ⤇ φ ∗ φ (message_stable_from_message m) }}}\n        ⟨n;handler #(m_body m) #(m_sender m)⟩\n      {{{ v, RET 〈n;v〉; Q v }}}) -∗\n  {{{ P ∗ h s↦[n] s ∗ a r↦{½} rm }}}\n     ⟨ n; listen (Lit $ LitSocket h) handler ⟩\n  {{{ v, RET 〈n;v〉; Q v }}}.\nProof.\n  iIntros ([[m handlerV] Hval%of_to_val] Haddr) \"#Hhandler\";\n    inversion Hval;simplify_eq.\n  iLöb as \"IH\".\n  iAlways. iIntros (Φ) \"(HP & Hsocket & Hrecs) HΦ\".\n  wp_rec.\n  wp_let.\n  wp_apply (wp_receive_from _ _ a with \"[$Hsocket $Hrecs]\"); first done.\n  iIntros (r) \"HQ\".\n  iDestruct \"HQ\" as (rm') \"(Hsocket & Hrecs & [HQ | [% %]])\".\n  - iDestruct \"HQ\" as (mId message φ) \"(Hrec & % & % & Hm & Hsi)\"; subst.\n    wp_match. wp_proj.\n    wp_let. wp_proj.\n    wp_apply (\"Hhandler\" with \"[-HΦ] [HΦ]\"); last iFrame. iFrame.\n  - subst. wp_match.\n    iApply (\"IH\" with \"[-HΦ]\"). iFrame. iFrame.\nQed.\n\nLemma listen_wait_spec n (h : socket_handle) (s : socket) (a : socket_address)\n        (rm : message_soup) φ :\n  saddress s = Some a →\n  {{{ h s↦[n] s ∗ a r↦{½} rm ∗ a ⤇ φ}}}\n     ⟨ n; listen_wait (Lit $ LitSocket h) ⟩\n  {{{ m mId, RET 〈n;(#(m_body m), #(m_sender m))〉;\n      ⌜received_message_info a m⌝ ∗ h s↦[n] s ∗ a r↦{½} (<[mId:=m]>rm) ∗\n      mId m↦{¾} m ∗ φ (message_stable_from_message m)\n  }}}.\nProof.\n  iIntros (Haddr Φ) \"(Hs & Hrec & Hφ) HΦ\".\n  iLöb as \"IH\".\n  wp_rec.\n  wp_apply (wp_receive_from with \"[$Hs $Hrec]\"); first done.\n  iIntros (r) \"HQ\"; iDestruct \"HQ\" as (rm') \"(Hs & Hrec & [HQ | [-> ->]])\"; simpl.\n  - iDestruct \"HQ\" as (mId message φ' Hri Hm Hrecs) \"(Hm & Hφ' & HP)\"; subst.\n    iDestruct (si_pred_agree _ _ _ (message_stable_from_message message) with \"Hφ Hφ'\") as \"#Heqv\".\n    wp_match. iApply \"HΦ\". iRewrite -\"Heqv\" in \"HP\". by iFrame.\n  - wp_match. iApply (\"IH\" with \"Hs Hrec Hφ\"). iFrame.\nQed.\n\nDefinition valid_tag t := index 0 \"_\" t = None.\n\nLemma tag_of_message_spec n m (s : string) t v:\n  IntoVal ⟨n;m⟩ 〈n;#s〉 →\n  valid_tag t →\n  {{{ ⌜s = t +:+ \"_\" +:+ v⌝ }}}\n    ⟨n;tag_of_message m⟩\n  {{{ v, RET 〈n;#v〉; ⌜v = t⌝ }}}.\nProof.\n  iIntros (Hv%to_base_val' Htag Φ HP) \"HΦ\".\n  apply ground_lang.of_to_val in Hv; simplify_eq.\n  wp_let. wp_find_from. split; eauto.\n    by instantiate (1:=0%nat).\n  rewrite (index_0_append_char \"_\"); auto. simpl. wp_match.\n  wp_substring. repeat split; eauto. by instantiate (1:=0%nat).\n  rewrite substring_0_length_append. by iApply \"HΦ\".\nQed.\n\nLemma value_of_message_spec n m (s : string) t v :\n  IntoVal ⟨n;m⟩ 〈n;#s〉 →\n  valid_tag t →\n  {{{ ⌜s = t +:+ \"_\" +:+ v⌝ }}}\n    ⟨n;value_of_message m⟩\n  {{{ r, RET 〈n;#r〉; ⌜r = v⌝ }}}.\nProof.\n  iIntros (Hv%to_base_val' Htag Φ HP) \"HΦ\".\n  apply ground_lang.of_to_val in Hv; simplify_eq.\n  wp_let. wp_find_from; simpl. split; eauto.\n  { by instantiate (1:=0%nat). }\n  rewrite (index_0_append_char \"_\"); auto; simpl; wp_match.\n  wp_op. wp_let.\n  wp_op. wp_let.\n  wp_op.\n  wp_substring. repeat split; eauto.\n  instantiate (1:=(length t + 1)%nat). apply Nat2Z.inj_add.\n  instantiate (1:=(length v)%nat).\n  { rewrite !length_app plus_assoc length_Sn /= !Nat2Z.inj_add. ring. }\n  rewrite substring_add_length_app substring_Sn substring_0_length.\n  by iApply \"HΦ\".\nQed.\n\nFixpoint list_coh l v :=\n  match l with\n  | [] => v = NONEV\n  | a::l' => ∃ lv : ground_lang.val, v = SOMEV (a,lv) ∧ list_coh l' lv\n  end.\n\nLemma list_make_spec n :\n  {{{ True }}}\n       ⟨n;list_make #()⟩\n  {{{ v, RET 〈n;v〉; ⌜list_coh [] v⌝}}}.\nProof.\n  iIntros (Φ) \"H HΦ\". rewrite /list_make /=.\n  wp_lam. by iApply \"HΦ\".\nQed.\n\nLemma list_cons_spec n (e1 e2 : ground_lang.expr) a lv l :\n  IntoVal ⟨n;e1⟩ 〈n;a〉 →\n  IntoVal ⟨n;e2⟩ 〈n;lv〉 →\n  {{{ ⌜list_coh l lv⌝ }}}\n       ⟨n;list_cons e1 e2⟩\n  {{{ v, RET 〈n;v〉; ⌜list_coh (a::l) v⌝}}}.\nProof.\n  iIntros (<-%to_base_val'%ground_lang.of_to_val\n              <-%to_base_val'%ground_lang.of_to_val Φ) \"% HΦ\".\n  wp_lam.\n  wp_let.\n  iApply \"HΦ\".\n  iPureIntro. by exists lv.\nQed.\n\nLemma list_head_spec n e lv l :\n  IntoVal ⟨n;e⟩ 〈n;lv〉 →\n  {{{ ⌜list_coh l lv⌝ }}}\n       ⟨n;list_head e⟩\n  {{{ v, RET 〈n;v〉; ⌜(l = [] ∧ v = NONEV) ∨\n                      (∃ v' l', l = v' :: l' ∧ v = SOMEV v')⌝}}}.\nProof.\n  iIntros (<-%to_base_val'%ground_lang.of_to_val Φ) \"% HΦ\".\n  wp_lam. destruct l; simpl in *; subst.\n  - wp_match. iApply \"HΦ\". iPureIntro. by left.\n  - destruct a as [lv' [Hhead Htail]] eqn:Heq; subst.\n    wp_match. wp_proj. iApply \"HΦ\". iPureIntro. right. by exists v,l.\nQed.\n\nLemma list_tail_spec n e lv l :\n  IntoVal ⟨n;e⟩ 〈n;lv〉 →\n  {{{ ⌜list_coh l lv⌝ }}}\n       ⟨n;list_tail e⟩\n  {{{ v, RET 〈n;v〉; ⌜list_coh (tail l) v⌝}}}.\nProof.\n  iIntros (<-%to_base_val'%ground_lang.of_to_val Φ) \"% HΦ\".\n  wp_lam. destruct l; simpl in *; subst.\n  - wp_match. by iApply \"HΦ\".\n  - destruct a as [lv' [Hhead Htail]] eqn:Heq; subst.\n    wp_match. wp_proj. by iApply \"HΦ\".\nQed.\n\nLemma list_length_spec n e l lv :\n  IntoVal ⟨n;e⟩ 〈n;lv〉 →\n  {{{ ⌜list_coh l lv⌝ }}}\n    ⟨n;list_length lv⟩\n  {{{ v, RET 〈n;#v〉; ⌜v = List.length l⌝ }}}.\nProof.\n  iIntros (<-%to_base_val'%ground_lang.of_to_val Φ) \"Ha HΦ\".\n  iInduction l as [|a l'] \"IH\" forall (lv Φ);\n  iDestruct \"Ha\" as %Ha; simpl in Ha; subst; wp_rec.\n  - wp_match. iApply (\"HΦ\" $! 0 : nat). auto.\n  - destruct Ha as [lv' [Hlv Hlcoh]]; subst.\n    wp_match. wp_proj. wp_bind (list_length _).\n    iApply (\"IH\" $! _ _ Hlcoh). iNext. iIntros; simpl.\n    wp_op. iSpecialize (\"HΦ\" $! (1 + v)). rewrite Nat2Z.inj_add. iApply \"HΦ\".\n    eauto.\nQed.\n\nLemma list_iter_spec {A} n e (l : list A) lv handler P Φ Ψ\n      (toval : A -> ground_lang.val) :\n  AsVal ⟨n;handler⟩ →\n  IntoVal ⟨n;e⟩ 〈n;lv〉 →\n  (∀ (a : A),\n  {{{ ⌜a ∈ l⌝ ∗ P ∗ Φ a }}}\n     ⟨n;handler (toval a)⟩\n  {{{v, RET 〈n;v〉; P ∗ Ψ a }}}) -∗\n  {{{ ⌜list_coh (map (λ a, toval a) l) lv⌝ ∗ P ∗ [∗ list] a∈l, Φ a }}}\n    ⟨n;list_iter handler lv⟩\n  {{{ RET 〈n;#()〉; P ∗ [∗ list] a∈l, Ψ a }}}.\nProof.\n  iIntros ([[m handlerV] Hval%of_to_val] <-%to_base_val'%ground_lang.of_to_val).\n  inversion Hval; simplify_eq.\n  iInduction l as [|a l'] \"IH\" forall (lv);\n  iIntros \"#Helem\"; iIntros (Φ') \"!# (Ha & HP & Hl) HΦ\";\n  iDestruct \"Ha\" as %Ha; simpl in Ha; subst; wp_rec; wp_let.\n  - wp_match. iApply \"HΦ\"; eauto.\n  - assert (Helemof: a ∈ a :: l').\n    { apply elem_of_list_here. }\n    destruct Ha as [lv' [Hlv Hlcoh]]; subst.\n    wp_match. wp_proj. wp_let. wp_proj.\n    iDestruct (big_sepL_cons with \"Hl\") as \"[Ha Hl']\".\n    wp_apply (\"Helem\" with \"[HP Ha]\"); iFrame; eauto.\n    iIntros (v) \"[HP Ha]\". simpl. wp_seq.\n    iApply (\"IH\" with \"[] [$HP $Hl']\"); eauto.\n    { iIntros (a' HΦ'') \"!# (% & HP & Ha) HΦ''\".\n      wp_apply (\"Helem\" with \"[HP Ha]\"); iFrame.\n      iPureIntro. by apply elem_of_list_further.\n    }\n    iNext. iIntros \"(HP & Hl)\". iApply \"HΦ\". iFrame.\nQed.\n\nLemma list_fold_spec {A} n handler (l : list A) e1 e2 acc lv P Φ Ψ\n      (toval : A -> ground_lang.val) :\n  AsVal ⟨n;handler⟩ →\n  IntoVal ⟨n;e1⟩ 〈n;acc〉 →\n  IntoVal ⟨n;e2⟩ 〈n;lv〉 →\n  (∀ (a : A) acc lacc lrem,\n  {{{ ⌜l = lacc ++ a :: lrem⌝ ∗ P lacc acc ∗ Φ a }}}\n     ⟨n;handler acc (toval a)⟩\n  {{{v, RET 〈n;v〉; P (lacc ++ [a]) v ∗ Ψ a }}}) -∗\n  {{{ ⌜list_coh (map (λ a, toval a) l) lv⌝ ∗ P [] acc ∗ [∗ list] a∈l, Φ a }}}\n    ⟨n; list_fold handler acc lv⟩\n  {{{v, RET 〈n;v〉; P l v ∗ [∗ list] a∈l, Ψ a }}}.\nProof.\n  iIntros ([[m handlerV] Hval%of_to_val]\n             <-%to_base_val'%ground_lang.of_to_val\n             <-%to_base_val'%ground_lang.of_to_val\n          ).\n  iIntros \"#Hcl\". iIntros (Ξ) \"!# (Hl & Hacc & HΦ) HΞ\".\n  change l with ([] ++ l) at 1 4.\n  generalize (@nil A) at 1 3 4 as lproc => lproc.\n  inversion Hval; simplify_eq.\n  iInduction l as [|x l] \"IHl\" forall (Ξ lproc acc lv) \"Hacc Hl HΞ\".\n  - iDestruct \"Hl\" as %?; simpl in *; simplify_eq.\n    repeat wp_rec.\n    wp_match. iApply \"HΞ\".\n    rewrite app_nil_r; iFrame.\n  - iDestruct \"Hl\" as %[lw [? Hlw]]; subst.\n    iDestruct \"HΦ\" as \"[Hx HΦ]\".\n    repeat wp_rec. wp_match.\n    wp_proj. wp_let. wp_proj. wp_let.\n    wp_apply (\"Hcl\" with \"[$Hacc $Hx] [-]\"); auto.\n    iNext. iIntros (w) \"[Hacc HΨ]\"; simpl.\n    wp_let.\n    iApply (\"IHl\" with \"[] [$HΦ] [$Hacc] [] [HΨ HΞ]\"); [|auto|].\n    { rewrite -app_assoc; auto. }\n    iNext. iIntros (v) \"[HP HΨs]\".\n    rewrite -app_assoc.\n    iApply \"HΞ\"; iFrame.\nQed.\n\nLemma list_fold_spec'_generalized {A} n handler (l lp : list A) e1 e2 acc lv P Φ Ψ\n      (toval : A -> ground_lang.val) :\n  AsVal ⟨n;handler⟩ →\n  IntoVal ⟨n;e1⟩ 〈n;acc〉 →\n  IntoVal ⟨n;e2⟩ 〈n;lv〉 →\n  □ (∀ (a : A) acc lacc lrem, (P lacc acc None (a::lrem) -∗ P lacc acc (Some a) lrem))%I -∗\n  (∀ (a : A) acc lacc lrem,\n  {{{ ⌜lp ++ l = lacc ++ a :: lrem⌝ ∗ P lacc acc (Some a) lrem ∗ Φ a }}}\n     ⟨n;handler acc (toval a)⟩\n  {{{v, RET 〈n;v〉; P (lacc ++ [a]) v None lrem ∗ Ψ a }}}) -∗\n  {{{ ⌜list_coh (map (λ a, toval a) l) lv⌝ ∗ P lp acc None l ∗ [∗ list] a∈l, Φ a }}}\n    ⟨n; list_fold handler acc lv⟩\n  {{{v, RET 〈n;v〉; P (lp ++ l) v None [] ∗ [∗ list] a∈l, Ψ a }}}.\nProof.\n  iIntros ([[m handlerV] Hval%of_to_val]\n             <-%to_base_val'%ground_lang.of_to_val\n             <-%to_base_val'%ground_lang.of_to_val\n          ).\n  iIntros \"#Hvs #Hcl\". iIntros (Ξ) \"!# (Hl & Hacc & HΦ) HΞ\".\n  (* change l with ([] ++ l) at 1. *)\n  (* generalize (@nil A) at 1 as lproc => lproc. *)\n  inversion Hval; simplify_eq.\n  iInduction l as [|x l] \"IHl\" forall (Ξ lp acc lv) \"Hacc Hl HΞ\".\n  - iDestruct \"Hl\" as %?; simpl in *; simplify_eq.\n    repeat wp_rec.\n    wp_match. iApply \"HΞ\".\n    rewrite app_nil_r; iFrame.\n  - iDestruct \"Hl\" as %[lw [? Hlw]]; subst.\n    iDestruct \"HΦ\" as \"[Hx HΦ]\".\n    repeat wp_rec. wp_match.\n    wp_proj. wp_let. wp_proj. wp_let.\n    iPoseProof (\"Hvs\" with \"Hacc\") as \"Hacc\".\n    wp_apply (\"Hcl\" with \"[$Hacc $Hx] [-]\"); auto.\n    iNext. iIntros (w) \"[Hacc HΨ]\"; simpl.\n    wp_let.\n    iApply (\"IHl\" with \"[] [$HΦ] [$Hacc] [] [HΨ HΞ]\"); [|auto|].\n    { rewrite -app_assoc; auto. }\n    iNext. iIntros (v) \"[HP HΨs]\".\n    rewrite -app_assoc.\n    iApply \"HΞ\"; iFrame.\nQed.\n\nLemma list_fold_spec' {A} n handler (l : list A) e1 e2 acc lv P Φ Ψ\n      (toval : A -> ground_lang.val) :\n  AsVal ⟨n;handler⟩ →\n  IntoVal ⟨n;e1⟩ 〈n;acc〉 →\n  IntoVal ⟨n;e2⟩ 〈n;lv〉 →\n  □ (∀ (a : A) acc lacc lrem, (P lacc acc None (a::lrem) -∗ P lacc acc (Some a) lrem))%I -∗\n  (∀ (a : A) acc lacc lrem,\n  {{{ ⌜l = lacc ++ a :: lrem⌝ ∗ P lacc acc (Some a) lrem ∗ Φ a }}}\n     ⟨n;handler acc (toval a)⟩\n  {{{v, RET 〈n;v〉; P (lacc ++ [a]) v None lrem ∗ Ψ a }}}) -∗\n  {{{ ⌜list_coh (map (λ a, toval a) l) lv⌝ ∗ P [] acc None l ∗ [∗ list] a∈l, Φ a }}}\n    ⟨n; list_fold handler acc lv⟩\n  {{{v, RET 〈n;v〉; P l v None [] ∗ [∗ list] a∈l, Ψ a }}}.\nProof.\n  iIntros (? ? ?) \"#Hvs #Hcl\".\n  iApply (list_fold_spec'_generalized _ handler l [] with \"[-]\"); eauto.\nQed.\n\nEnd library.\n\n", "meta": {"author": "mkroghj", "repo": "aneris", "sha": "b2be05891029578fd6e4e22705a73567b5897af3", "save_path": "github-repos/coq/mkroghj-aneris", "path": "github-repos/coq/mkroghj-aneris/aneris-b2be05891029578fd6e4e22705a73567b5897af3/examples/library/proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2876750502777488}}
{"text": "Set Implicit Arguments.\n\nRequire Import fcf.FCF.\n(* RndInList has a useful theorem (qam_count) about counting calls to an oracle. *)\nRequire Import fcf.RndInList.\nRequire Import fcf.HasDups.\nRequire Import fcf.CompFold.\nRequire Import fcf.PRF.\nRequire Import fcf.OracleHybrid.\nRequire Import List.\nRequire Import fcf.PRF_DRBG.        (* note: had to move PRF_DRBG into FCF dir for this *)\nRequire Import Coq.Program.Wf.\nRequire Import fcf.OracleCompFold.\nRequire Import Permutation.\nRequire Import fcf.Tactics.\n\n(* Shortcuts for FCF tactics *)\n(* TODO remove / inline these *)\nLtac fs := fcf_simp.\nLtac fif := fcf_inline_first.\nLtac s := simpl.\nLtac fsr := fcf_spec_ret.\nLtac fskip := fcf_skip.\nLtac simplify :=\n  repeat (try simpl; try fcf_inline_first; try fcf_simp).\n\nLtac rewrite_r := apply comp_spec_symm; eapply comp_spec_eq_trans_l.\nLtac flip := apply comp_spec_symm.\nLtac prog_equiv := repeat (simplify; fcf_skip_eq); try simplify.\n\nLtac bv_exist := try apply oneVector.\n\n(* Lemma demonstrating use of `bv_exist` ltac *)\nLemma fcf_skip_admits : forall (n m : nat),\n  comp_spec eq\n            (x <-$ {0,1}^n;\n             ret x)\n            (y <-$ {0,1}^n;\n             z <-$ {0,1}^n;\n             ret y).\nProof.\n  intros.\n  (* Set Printing All. *)\n  simpl.\n  fcf_skip; bv_exist.\n  fcf_irr_r.\nQed.\n\n(* TODO:\n\n- Blist definitions X\n- New for PRF-DRBG etc functions (instantiate, generate, update) X\n- Make the correct oracles X\n- Fill in the oracles with functions X\n\n- Write the initial game and final game X\n- Write the game i X\n- Construct PRF adversary X\n- Write the theorem statements (final theorem, inductive hypothesis) X\n\n- Prove equivalence of the new GenUpdate oracle outputs (moving re-sampling v) to old GenUpdate oracle outputs X\n- Apply the hybrid argument in G1_G2_close and make sure that theorem can be proven with Gi_Gi_plus_1_close X\n- Move my proof to a separate file? or review it X\n- Comment the uncommented games X\n\n- Figure out what's going on with PRF advantage X\n- Look at OracleMapHybrid (X)\n\n- Write out all subgames (e.g. involving random functions) X\n- Review step 4 and OracleHybrid proofs (X)\n- Remove unneeded GenUpdate*_oc versions\n\n- Prove G1 = Gi 0 and G2 = Gi q\n- Prove Gi_prf (S i) = Gi_prg i\n- Prove PRF advantage theorems\n- Prove the theorems: (figure out what the main lemmas and difficulties are)\n  - Pr[Collisions] = ? (for n+1 calls)\n  - Apply Adam's argument\n\n- Prove other things (well-formedness, etc. -- the hypotheses)\n  - Deal with actual Instantiate (not just RB)\n- Add backtracking resistance and prove that \n- Change to adaptive adversary?? (additional input, etc.)\n*)\n\nLocal Open Scope list_scope.\nLocal Opaque evalDist.\n\n(* --- Begin my HMAC-DRBG spec --- *)\nSection PRG.\n\n  (* note: the domain of the f is now Blist, not an abstract D\nthe key type is now also Bvector eta, since HMAC specifies that the key has the same size as the output (simplified) *)\n\nVariable eta : nat.\nHypothesis eta_nonzero : eta <> 0%nat.\n\nDefinition RndK : Comp (Bvector eta) := {0,1}^eta.\nDefinition RndV : Comp (Bvector eta) := {0,1}^eta.\n\nLtac kv_exist := try apply (oneVector eta, oneVector eta).\n\nVariable f : Bvector eta -> Blist -> Bvector eta.\n\nDefinition KV : Set := (Bvector eta * Bvector eta)%type.\nVariable eqDecState : EqDec KV.\n(* Variable eqdbv : EqDec (Bvector eta). *)\nDefinition eqdbv := Bvector_EqDec eta.\n(* Variable eqdbl : EqDec Blist. *)\nDefinition eqdbl := list_EqDec bool_EqDec.\n(* Opaque eqdbl. *)\n\n(* injection is to_list. TODO prove this *)\nDefinition injD : Bvector eta -> Blist := Vector.to_list.\nLemma injD_correct r1 r2: injD r1 = injD r2 -> r1 = r2.\nProof. apply to_list_eq_inv. Qed.\n\nDefinition to_list (A : Type) (n : nat) (v : Vector.t A n) := Vector.to_list v.\n\n(* PRG functions *)\n\n(* TODO does not reflect NIST spec *)\nDefinition Instantiate : Comp KV :=\n  k <-$ RndK;\n  v <-$ RndV;\n  ret (k, v).\n\nLemma wf_instantiate : well_formed_comp Instantiate.\nProof. unfold Instantiate. fcf_well_formed. unfold RndK. fcf_well_formed.\n       unfold RndV. fcf_well_formed. Qed.\nLtac wfi := apply wf_instantiate.\n(*\nPrint Comp.\nSearchAbout Comp.\nLocate \"<-$\". *)\n\n(* save the last v and output it as part of the state *)\nFixpoint Gen_loop (k : Bvector eta) (v : Bvector eta) (n : nat)\n  : list (Bvector eta) * Bvector eta :=\n  match n with\n  | O => (nil, v)\n  | S n' =>\n    let v' := f k (to_list v) in\n    let (bits, v'') := Gen_loop k v' n' in\n    (v' :: bits, v'')           (* TODO change mine from (v ::) to (v ++), *or* prove indistinguishable (add another game in the beginning) *)\n  end.\n\nTheorem Gen_loop_test : forall k v, Gen_loop k v 3 =    (f k (to_list v)\n    :: f k (to_list (f k (to_list v)))\n       :: f k (to_list (f k (to_list (f k (to_list v))))) :: nil,\n   f k (to_list (f k (to_list (f k (to_list v)))))).\nProof.\n  reflexivity.\nQed.\n\n(* Generate + Update *)\n(* This has oracle type:\nstate: k, v\ninput: n\noutput: list (Bvector eta)\nstate: k, v *)\n\n(* Spec says \"V || 0x00\"; here we will use a list of 8 bits of 0 (a byte) *)\nFixpoint replicate {A} (n : nat) (a : A) : list A :=\n  match n with\n  | O => nil\n  | S n' => a :: replicate n' a\n  end.\n\nDefinition zeroes : list bool := replicate 8 false.\n\n(* oracle 1 *)\n\n(* do not use; here as reference implementation so we can prove \n[GenUpdate_original, GenUpdate_original, ...] = [GenUpdate_noV, GenUpdate, Genupdate, ...] *)\nDefinition GenUpdate_original (state : KV) (n : nat) :\n  Comp (list (Bvector eta) * KV) :=\n  [k, v] <-2 state;\n  [bits, v'] <-2 Gen_loop k v n;\n  k' <- f k (to_list v' ++ zeroes);\n  v'' <- f k' (to_list v');\n  ret (bits, (k', v'')).\n\n(* want to change to this, and prove the outputs are the same. \nthe other GenUpdates don't use this version *)\nDefinition GenUpdate (state : KV) (n : nat) :\n  Comp (list (Bvector eta) * KV) :=\n  [k, v] <-2 state;\n  v' <- f k (to_list v);\n  [bits, v''] <-2 Gen_loop k v' n;\n  k' <- f k (to_list v'' ++ zeroes);\n  ret (bits, (k', v'')).\n\n(* use this for the first call *)\nDefinition GenUpdate_noV (state : KV) (n : nat) :\n  Comp (list (Bvector eta) * KV) :=\n  [k, v] <-2 state;\n  [bits, v'] <-2 Gen_loop k v n;\n  k' <- f k (to_list v' ++ zeroes);\n  ret (bits, (k', v')).\n\n(* --- End my HMAC-DRBG spec --- *)\n(* well, this doesn't include the \"sequence of executions\" business, which happens in the games *)\n\n(* oracle 2: all PRFs replaced with random bits *)\n(* TODO: intermediate oracles, each with random functions *)\n\n(* intermediates have unnecessary state and updating of the state to match earlier ones *)\nFixpoint Gen_loop_rb_intermediate (k : Bvector eta) (v : Bvector eta) (n : nat)\n  : Comp (list (Bvector eta) * Bvector eta) :=\n  match n with\n  | O => ret (nil, v)\n  | S n' =>\n    v' <-$ {0,1}^eta;\n    [bits, v''] <-$2 Gen_loop_rb_intermediate k v' n';\n    ret (v' :: bits, v'')\n  end.\n\n(* final versions (without unnecessary (k, v) updating) *)\nFixpoint Gen_loop_rb (n : nat) : Comp (list (Bvector eta)) :=\n  match n with\n  | O => ret nil\n  | S n' =>\n    v' <-$ {0,1}^eta;\n    bits <-$ Gen_loop_rb n';\n    ret (v' :: bits)\n  end.\n\n(* passes the state around to match the types in Oi_oc' *)\n(* Old version: did not update v *)\n(* Definition GenUpdate_rb_intermediate (state : KV) (n : nat) *)\n(*   : Comp (list (Bvector eta) * KV) := *)\n(*   bits <-$ Gen_loop_rb n; *)\n(*   ret (bits, state). *)\n\n(* New version: updates state vector v to be the last element of bits. Doesn't matter b/c all bits sampled randomly unless n=0 *)\n(* New new version: exactly like GenUpdate but with f replaced by uniform random sampling *)\n(* needs this for the proof of Gi_normal_rb_eq *)\nDefinition GenUpdate_rb_intermediate (state : KV) (n : nat)\n  : Comp (list (Bvector eta) * KV) :=\n  [k, v] <-2 state;\n  v' <-$ {0,1}^eta;\n  [bits, v''] <-$2 Gen_loop_rb_intermediate k v' n;\n  ret (bits, (k, v'')).\n\nDefinition GenUpdate_rb_oracle (tt : unit) (n : nat) : Comp (list (Bvector eta) * unit) :=\n  bits <-$ Gen_loop_rb n;\n  ret (bits, tt).\n\nDefinition GenUpdate_rb (n : nat) : Comp (list (Bvector eta)) :=\n  bits <-$ Gen_loop_rb n;\n  ret bits.\n\n(* TODO: prove well_formed for the oracles *)\n\n(* Non-adaptive adversary. Consequently, does not use OracleComp, because it won't be adjusting its input to the GenUpdate oracle (number of blocks requested from Gen_loop) based on the GenUpdate oracle's output, because the number of blocks and queries is fixed. *)\nVariable A : list (list (Bvector eta)) -> Comp bool.\nHypothesis A_wf : forall ls, well_formed_comp (A ls).\n\nVariable blocksPerCall : nat.       (* blocks generated by GenLoop *)\nVariable numCalls : nat.        (* number of calls to GenUpdate *)\nHypothesis H_numCalls : numCalls > 0. (* need this for GenUpdate equivalence? *)\nHypothesis H_blocksPerCall : blocksPerCall > 0.\n(* need this hypothesis in oracle-to-RB (oracleMap_oracleCompMap_equiv_modified_calls_gt_i)\nand collision bound (Gi_rb_collisions_inner_eq_general_i_eq0) *)\n(* TODO do casework on whether blocksPerCall = 0 *)\n\nDefinition maxCallsAndBlocks : list nat := replicate numCalls blocksPerCall.\n\n(* Change to an abstract, nonempty list. *)\n(* TODO: change name *)\n(* Parameter firstCall : nat. *)\n(* Parameter blocksForCalls_2 : list nat. *)\n(* Definition maxCallsAndBlocks : list nat := firstCall :: blocksForCalls_2. *)\n(* used with oracleMap: call the oracle numCalls times, each time requesting blocksPerCall blocks *)\n\n(* only first call uses GenUpdate_noV; assumes numCalls > 0 *)\nDefinition G1_prg : Comp bool :=\n  [k, v] <-$2 Instantiate;\n  [head_bits, state'] <-$2 GenUpdate_noV (k, v) blocksPerCall;\n  [tail_bits, _] <-$2 oracleMap _ _ GenUpdate state' (tail maxCallsAndBlocks);\n  A (head_bits :: tail_bits).\n\n(* TODO: backtracking resistance? for nonadaptive adversary *)\n(* Definition G1_prg_br : Comp bool :=\n  blocksForEachCall <- A1; (* implicitly compromises after that # calls *)\n  [k, v] <-$2 Instantiate;\n  [head_bits, state'] <-$2 GenUpdate_noV (k, v) (head blocksForEachCall);\n  [tail_bits, state''] <-$2 oracleMap _ _ GenUpdate state' (tail blocksForEachCall);\n  [k', v'] <-$ UpdateV state'';\n  A2 (head_bits :: tail_bits, (k', v')). *)\n\n(* rand bits *)\n(* Definition G2_prg_br : Comp bool :=\n  blocksForEachCall <- A1;\n  [bits, state'] <-$2 oracleMap _ _ GenUpdate_rb (k, v) blocksPerCall;\n  k <- {0,1}^eta;\n  v <- {0,1}^eta;\n  A2 (head_bits :: tail_bits, (k, v)). *)\n\n(* --------------------- *)\n(* Prove v-update move equivalence *)\n\n(* calling (GenUpdate_original, GenUpdate_original, ...) should have the same output\nas calling (GenUpdate_noV, GenUpdate, GenUpdate, ...) which moves the v-update to the beginning of the next oracle call *)\n(* proof outline: G1_prg_original = G1_prg_original_split ~ G1_prg *)\n\nDefinition G1_prg_original : Comp bool :=\n  [k, v] <-$2 Instantiate;\n  [bits, _] <-$2 oracleMap _ _ GenUpdate_original (k, v) maxCallsAndBlocks;\n  A bits.\n\n(* make the form closer to G1_prg by splitting off first call only *)\nDefinition G1_prg_original_split : Comp bool :=\n  [k, v] <-$2 Instantiate;\n  [head_bits, state'] <-$2 GenUpdate_original (k, v) blocksPerCall;\n  [tail_bits, _] <-$2 oracleMap _ _ GenUpdate_original state' (tail maxCallsAndBlocks);\n  A (head_bits :: tail_bits).\n\n(* use version that's better for induction *)\n\n(* oracleMap hardcodes acc for compFold as nil, so generalize it *)\nTheorem compFold_acc : forall numCalls0 bits acc state,\n   comp_spec\n     (fun x y : list (list (Bvector eta)) * KV =>\n      hd_error (fst x) = Some bits /\\ tl (fst x) = fst y)\n     (compFold (pair_EqDec (list_EqDec (list_EqDec eqdbv)) eqDecState)\n        (fun (acc : list (list (Bvector eta)) * KV) (d : nat) =>\n         [rs, s]<-2 acc;\n         z <-$ GenUpdate_original s d; [r, s0]<-2 z; ret (rs ++ r :: nil, s0))\n        (bits :: acc, state) (replicate numCalls0 blocksPerCall))\n     (compFold (pair_EqDec (list_EqDec (list_EqDec eqdbv)) eqDecState)\n        (fun (acc : list (list (Bvector eta)) * KV) (d : nat) =>\n         [rs, s]<-2 acc;\n         z <-$ GenUpdate_original s d; [r, s0]<-2 z; ret (rs ++ r :: nil, s0))\n        (acc, state) (replicate numCalls0 blocksPerCall)).\nProof.\n  intros. revert bits acc state.\n  induction numCalls0; intros.\n\n  - simpl. fcf_spec_ret.\n  - simpl.\n    fcf_inline_first. fcf_skip.\n    remember a0 as bits1. remember b as state'. clear Heqbits1 Heqstate'.\n    fcf_simp.\n    apply IHnumCalls0.\nQed.\n\n(* do first call of map separately *)\nTheorem GenUpdate_split_close :\n  Pr[G1_prg_original] == Pr[G1_prg_original_split].\nProof.\n  unfold G1_prg_original, G1_prg_original_split.\n  unfold maxCallsAndBlocks.\n  destruct numCalls as [ | numCalls'].\n  * inversion H_numCalls.\n  * Opaque GenUpdate_original. \n    simpl.\n    fcf_to_prhl_eq.\n    fcf_skip.\n    fcf_simp.\n    remember b as k. remember b0 as v. clear Heqk Heqv.\n    remember (replicate numCalls' blocksPerCall) as maxCallsAndBlocks'.\n\n    unfold oracleMap. simpl.\n    fcf_inline_first.\n    fcf_skip.\n    Opaque getSupport. simpl in *.\n    remember a0 as bits. remember b1 as state'. clear Heqbits Heqstate'.\n\n    fcf_skip.\n    instantiate (1 := (fun x y => hd_error (fst x) = Some bits /\\ tail (fst x) = fst y)).\n    - apply compFold_acc.\n    - fcf_simp. simpl in H5. inversion H5. clear H5. destruct a1. inversion H6. simpl in *. inversion H6. subst. fcf_reflexivity.\n      Transparent GenUpdate_original.\nQed.\n\n(* generalize acc again. could be generalized further for the function on v but oh well *)\nTheorem comp_spec_acc_2 : forall numCalls0 acc k v,\n comp_spec (fun x y : list (list (Bvector eta)) * KV => fst x = fst y)\n     (compFold (pair_EqDec (list_EqDec (list_EqDec eqdbv)) eqDecState)\n        (fun (acc : list (list (Bvector eta)) * KV) (d : nat) =>\n         [rs, s]<-2 acc;\n         z <-$ GenUpdate_original s d; [r, s0]<-2 z; ret (rs ++ r :: nil, s0))\n        (acc,\n        (k, f k (to_list v)))\n        (replicate numCalls0 blocksPerCall))\n     (compFold (pair_EqDec (list_EqDec (list_EqDec eqdbv)) eqDecState)\n        (fun (acc : list (list (Bvector eta)) * KV) (d : nat) =>\n         [rs, s]<-2 acc;\n         z <-$ GenUpdate s d; [r, s0]<-2 z; ret (rs ++ r :: nil, s0))\n        (acc, (k, v))\n        (replicate numCalls0 blocksPerCall)).\nProof.\n  intros.\n  revert v k acc. induction numCalls0 as [ | numCalls0']; intros.\n  * simpl. fcf_spec_ret.\n  * simpl.\n    fcf_inline_first. fcf_simp. apply IHnumCalls0'.\nQed.\n\n(* G1_prg_original: calls GenUpdate_original, then GenUpdate_original\nG1_prg: uses GenUpdate_noV, then GenUpdate (v moved) *)\nTheorem GenUpdate_v_output_probability :\n  Pr[G1_prg_original] == Pr[G1_prg].\nProof.\n  rewrite GenUpdate_split_close.\n  unfold G1_prg_original_split, G1_prg.\n  fcf_to_prhl_eq.\n  fcf_skip.\n  fcf_simp.\n  remember b as k. remember b0 as v. clear Heqk Heqv.\n  simpl.\n  fcf_inline_first.\n  fcf_simp.\n  remember (to_list b1 ++ zeroes) as v1_pad.\n  unfold maxCallsAndBlocks.\n\n  destruct numCalls as [ | numCalls'].\n\n  * inversion H_numCalls.\n  * simpl.\n    fcf_skip.\n    instantiate (1 := (fun x y => fst x = fst y)).\n    unfold oracleMap.\n\n    - apply comp_spec_acc_2.\n\n    - fcf_simp. simpl in *. subst. fcf_reflexivity.\nQed.\n\n(* End proofs of v-update equivalence *)\n(* ------------------------------------------------ *)\n\n(* TODO: intermediate games with random functions and random bits *)\n\n(* proving Pr[G2_prg'] == Pr[G2_prg''] could be hard (new intermediate game) *)\n\nDefinition G2_prg'' : Comp bool :=\n  kv <-$ Instantiate;           (* OK to instantiate them? *)\n  [bits, _] <-$2 oracleMap _ _ GenUpdate_rb_intermediate kv maxCallsAndBlocks;\n  A bits.\n\n(* uses simplified RB versions *)\nDefinition G2_prg' : Comp bool :=\n  [bits, _] <-$2 oracleMap _ _ GenUpdate_rb_oracle tt maxCallsAndBlocks;\n  A bits.\n\n(* simpler version of GenUpdate only requires compMap. prove the two games equivalent *)\nDefinition G2_prg : Comp bool :=\n  bits <-$ compMap _ GenUpdate_rb maxCallsAndBlocks;\n  A bits.\n\n(* oracle i *)\n(* number of calls: first call is 0, last call is (numCalls - 1) for numCalls calls total\nG0: PRF PRF PRF\nG1: RB  PRF PRF\nG2: RB  RB  PRF\nG3: RB  RB  RB \nthere should be (S numCalls) games, so games are numbered from 0 through numCalls *)\nDefinition Oi_prg (i : nat) (sn : nat * KV) (n : nat)\n  : Comp (list (Bvector eta) * (nat * KV)) :=\n  [callsSoFar, state] <-2 sn;\n  let GenUpdate_choose := if lt_dec callsSoFar i (* callsSoFar < i (override all else) *)\n                          then GenUpdate_rb_intermediate\n                          (* first call does not update v, to make proving equiv. easier*)\n                          else if beq_nat callsSoFar O then GenUpdate_noV\n                          else GenUpdate in\n  (* note: have to use intermediate, not final GenUpdate_rb here *)\n  [bits, state'] <-$2 GenUpdate_choose state n;\n  ret (bits, (S callsSoFar, state')).\n\n(* game i (Gi 0 = G1 and Gi q = G2) *)\nDefinition Gi_prg (i : nat) : Comp bool :=\n  [k, v] <-$2 Instantiate;\n  [bits, _] <-$2 oracleMap _ _ (Oi_prg i) (O, (k, v)) maxCallsAndBlocks;\n  A bits.\n\n\n(* ------------------------------- *)\n(* G1 is equal to first hybrid *)\n\n(* move the non-nil init state inside compFold's init acc. otherwise, same compFold as in oracleMap *)\nDefinition G1_prg_fold : Comp bool :=\n  [k, v] <-$2 Instantiate;\n  [head_bits, state'] <-$2 GenUpdate_noV (k, v) blocksPerCall;\n  (* unfolding the oracleMap *)\n  (* [tail_bits, _] <-$2 oracleMap _ _ GenUpdate state' (tail maxCallsAndBlocks); *)\n  [bits, _] <-$2 compFold _\n            (fun acc d => [rs, s] <-2 acc;\n             [r, s] <-$2 GenUpdate s d;\n             ret (rs ++ r :: nil, s)) \n            (head_bits :: nil, state') (tail maxCallsAndBlocks);\n  A bits.\n\nLemma compFold_acc_eq : forall (l : list nat) (a0 : list (Bvector eta)) (b1 : KV) (bits : list (list (Bvector eta))),\n   comp_spec eq\n     (z <-$\n      compFold (pair_EqDec (list_EqDec (list_EqDec eqdbv)) eqDecState)\n        (fun (acc : list (list (Bvector eta)) * KV) (d : nat) =>\n         [rs, s]<-2 acc;\n         z <-$ GenUpdate s d; [r, s0]<-2 z; ret (rs ++ r :: nil, s0))\n        (bits, b1) l;\n      [tail_bits, _]<-2 z; A (a0 :: tail_bits))\n     (z <-$\n      compFold (pair_EqDec (list_EqDec (list_EqDec eqdbv)) eqDecState)\n        (fun (acc : list (list (Bvector eta)) * KV) (d : nat) =>\n         [rs, s]<-2 acc;\n         z <-$ GenUpdate s d; [r, s0]<-2 z; ret (rs ++ r :: nil, s0))\n        (a0 :: bits, b1) l;\n      [bits, _]<-2 z; A bits).\nProof.\n  induction l as [ | call calls]; intros.\n\n  * fcf_simp.\n    fcf_reflexivity.\n  * simpl.\n    fcf_inline_first.\n    fcf_skip.\n    fcf_simp.\n    apply IHcalls.\nQed.\n\nLemma G1_G1_acc_equal :\n  Pr[G1_prg] == Pr[G1_prg_fold].\nProof.\n  fcf_to_prhl_eq.\n  unfold G1_prg, G1_prg_fold.\n  fcf_skip.\n  fcf_simp.\n  fcf_skip.\n  unfold oracleMap.\n  (* maybe induct on numCalls then use equality? *)\n  unfold maxCallsAndBlocks.\n  apply compFold_acc_eq.\nQed.\n\n(* compFold with GenUpdate is the same as compFold with (Oi_prg 0) and # calls starting >=1 *)\nLemma compFold_GenUpdate_Oi_prg :\n  forall (calls : list nat) (l : list (list (Bvector eta))) (k v : Bvector eta)\n         (callsSoFar : nat),\n    beq_nat callsSoFar 0%nat = false ->\n   comp_spec\n     (fun (x : list (list (Bvector eta)) * KV)\n        (y : list (list (Bvector eta)) * (nat * KV)) =>\n      x = (fst y, snd (snd y)))\n     (compFold (pair_EqDec (list_EqDec (list_EqDec eqdbv)) eqDecState)\n        (fun (acc : list (list (Bvector eta)) * KV) (d : nat) =>\n         [rs, s]<-2 acc;\n         z <-$ GenUpdate s d; [r, s0]<-2 z; ret (rs ++ r :: nil, s0))\n        (l, (k, v)) calls)\n     (compFold\n        (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n           (pair_EqDec nat_EqDec eqDecState))\n        (fun (acc : list (list (Bvector eta)) * (nat * KV)) (d : nat) =>\n         [rs, s]<-2 acc;\n         z <-$ Oi_prg 0 s d; [r, s0]<-2 z; ret (rs ++ r :: nil, s0))\n        (l, (callsSoFar, (k, v))) calls).\nProof.\n  induction calls as [ | call calls']; intros.\n  * simpl.\n    fcf_spec_ret.\n  * simpl.\n    destruct (beq_nat callsSoFar 0).\n    - inversion H.\n    - simpl.\n      fcf_inline_first.\n      fcf_simp.\n      apply IHcalls'.\n      auto.\nQed.\n\n(* wait what? it needs identical until bad??? *)\n(* TODO make sure the numbering is right *)\nLemma G1_Gi_O_equal :\n  Pr[G1_prg] == Pr[Gi_prg O].\nProof.\n  rewrite G1_G1_acc_equal.\n  fcf_to_prhl_eq.\n  unfold G1_prg_fold.\n  unfold Gi_prg.\n\n  (* Oi_prg 0 is ~ GenUpdate_noV, GenUpdate, GenUpdate, ...? *)\n  unfold maxCallsAndBlocks.\n  destruct numCalls.\n\n  * inversion H_numCalls.\n\n  * simpl.\n    comp_skip.\n    unfold oracleMap.\n    simpl. (* break up latter oracleMap *)\n    fs.\n    fif.\n    fs.\n    (* maybe I can get the l out of the compFold? forgot how it works *)\n    fcf_skip.\n    instantiate (1 := (fun x y => x = (fst y, snd (snd y)))).\n    (* simple generalize + induction *)\n    apply compFold_GenUpdate_Oi_prg.\n    auto.\n\n    simpl in H3.\n    inversion H3.\n    subst.\n    destruct b3.\n    simpl.\n    fcf_reflexivity.\nQed.\n\n(* ----- G2 is equal to last hybrid. Helper lemmas *)\n\nOpen Scope nat.\n\n(* relate map with fold where GenUpdate_rb_oracle is easier to prove things about than Oi_prg numCalls *)\nLemma compMap_compFold_rb_eq :\n  forall (calls : list nat) (acc : list (list (Bvector eta))) (u : unit),\n    comp_spec (fun x y => x = fst y)\n              (ls <-$ compMap (list_EqDec eqdbv) GenUpdate_rb calls; ret (acc ++ ls))\n              (compFold (pair_EqDec (list_EqDec (list_EqDec eqdbv)) unit_EqDec)\n                        (fun (acc0 : list (list (Bvector eta)) * unit) (d : nat) =>\n                           [rs, s]<-2 acc0;\n                         z <-$ GenUpdate_rb_oracle s d; [r, s0]<-2 z; ret (rs ++ r :: nil, s0))\n                        (acc, u) calls).\n Proof.\n   induction calls as [ | call calls']; intros.\n   * fcf_simp.\n     fcf_spec_ret.\n   * simpl.\n     fcf_inline_first.\n     fcf_skip.\n     { instantiate (1 := (fun x y => x = fst y)).\n     unfold GenUpdate_rb, GenUpdate_rb_oracle.\n     fcf_skip.\n     fcf_spec_ret. }\n     fcf_inline_first.\n     fcf_simp.\n     simpl in *. subst.\n\n     (* since fcf_rewrite_expr app_cons_eq doesn't work... *)\n     assert (comp_spec eq\n                       (a <-$ compMap (list_EqDec eqdbv) GenUpdate_rb calls';\n                        ls <-$ ret l :: a; ret acc ++ ls)\n                       (a <-$ compMap (list_EqDec eqdbv) GenUpdate_rb calls';\n                        ret ((acc ++ l :: nil) ++ a))). fcf_skip.\n     fcf_spec_ret.\n     apply app_cons_eq.\n\n     eapply comp_spec_eq_trans_l.\n     apply H1.\n     apply IHcalls'.\nQed.\n\n (* specific version *)\nLemma compMap_compFold_rb_eq_specific :\n  forall (calls : list nat) (u : unit),\n    comp_spec (fun x y => x = fst y)\n              (compMap (list_EqDec eqdbv) GenUpdate_rb calls)\n              (compFold (pair_EqDec (list_EqDec (list_EqDec eqdbv)) unit_EqDec)\n                        (fun (acc0 : list (list (Bvector eta)) * unit) (d : nat) =>\n                           [rs, s]<-2 acc0;\n                         z <-$ GenUpdate_rb_oracle s d; [r, s0]<-2 z; ret (rs ++ r :: nil, s0))\n                        (nil, u) calls). \nProof.\n  intros.\n  eapply comp_spec_eq_trans_l.\n  instantiate (1 := ((ls <-$ compMap (list_EqDec eqdbv) GenUpdate_rb calls; ret nil ++ ls))).\n  - fcf_ident_expand_l.\n    fcf_skip.\n    fcf_spec_ret.\n  - pose proof (compMap_compFold_rb_eq calls nil u).\n    auto.\nQed.\n\nLemma G2_oracle_eq :\n  Pr[G2_prg] == Pr[G2_prg'].\nProof.\n  unfold G2_prg, G2_prg'.\n  unfold oracleMap.\n  fcf_to_prhl_eq.\n  fcf_skip.\n  apply compMap_compFold_rb_eq_specific.\n  fcf_simp.\n  simpl in *.\n  subst.\n  fcf_reflexivity.\nQed.\n\nLemma oracleMap_v_sampling_eq : forall blocks k v init tt',\n   comp_spec (fun x y => fst x = fst y)\n      (compFold (pair_EqDec (list_EqDec (list_EqDec eqdbv)) unit_EqDec)\n        (fun (acc : list (list (Bvector eta)) * unit) (d : nat) =>\n         [rs, s]<-2 acc;\n         z <-$ GenUpdate_rb_oracle s d;\n         [r, s0]<-2 z; ret (rs ++ r :: nil, s0)) (init, tt') blocks)\n      (compFold (pair_EqDec (list_EqDec (list_EqDec eqdbv)) eqDecState)\n        (fun (acc : list (list (Bvector eta)) * KV) (d : nat) =>\n         [rs, s]<-2 acc;\n         z <-$ GenUpdate_rb_intermediate s d;\n         [r, s0]<-2 z; ret (rs ++ r :: nil, s0)) (init, (k,v)) blocks).\nProof.\n  induction blocks as [ | block blocks']; intros.\n  - simplify. fcf_spec_ret.\n  - fcf_skip; kv_exist.\n    instantiate (1 := (fun x y => fst x = fst y)).\n    {\n      unfold GenUpdate_rb_oracle. simplify.\n      fcf_irr_r.\n      simplify.\n      fcf_skip; kv_exist.\n      (* this goes thru without needing the non-0 block hypothesis *)\n      { instantiate (1 := (fun x y => x = fst y)).\n        clear H0 (*H0*).               (* ok? *)\n        revert block k b.\n        induction block as [ | n']; intros.\n        - (*Print Gen_loop_rb_intermediate.*)\n          simpl. fcf_spec_ret.\n        - simpl. fcf_skip_eq. fcf_skip. simplify. fcf_spec_ret.\n      }\n      simpl in *. destruct b0. simpl in *. subst.\n      simplify. fcf_spec_ret.\n    }\n    simpl in *. destruct b0. simpl in *. subst. fold compFold.\n    simplify.\n    destruct k0.\n    destruct b.\n    apply IHblocks'.\nQed.\n\n(* This intermediate game isn't strictly necessary--G2_prg' is also an acceptable definition for the final game.\nIf we wanted to go with that definition, we would simply replace G2_prg with G2_prg' everywhere *)\nLemma G2_oracle_eq_v_sampling :\n  Pr[G2_prg'] == Pr[G2_prg''].\nProof.\n  unfold G2_prg', G2_prg''.\n  unfold oracleMap.\n  fcf_to_prhl_eq.\n  fcf_irr_r. wfi.\n  fcf_skip.\n  destruct b.\n  eapply oracleMap_v_sampling_eq.\n  simplify. simpl in *. subst.\n  fcf_ident_expand_l. fcf_ident_expand_r. fcf_skip.\nQed.\n\n(* Relate Gen_loop_rb_intermediate (newly being used) with Gen_loop_rb *)\nLemma Gen_loop_rb_and_intermediate_eq : forall (n : nat) (k v : Bvector eta),\n  comp_spec (fun x y => fst x = y) (Gen_loop_rb_intermediate k v n) (Gen_loop_rb n).\nProof.\n  induction n as [ | n']; intros; simpl.\n  - fcf_spec_ret.\n  - fcf_skip_eq. fcf_skip. fcf_spec_ret.\nQed.\n\n(* TODO use the correct theorem to flip sides *)\nLemma Gen_loop_rb_and_intermediate_eq2 : forall (n : nat) (k v : Bvector eta),\n  comp_spec (fun x y => x = fst y) (Gen_loop_rb n) (Gen_loop_rb_intermediate k v n).\nProof.\n  induction n as [ | n']; intros; simpl.\n  - fcf_spec_ret.\n  - fcf_skip_eq. fcf_skip. fcf_simp. fcf_spec_ret.\nQed.\n\n(* pull it out? *)\nLemma length_replicate : forall {A : Type} (n : nat) (x : A),\n    length (replicate n x) = n.\nProof.\n  induction n; intros.\n  * reflexivity.\n  * simpl. rewrite IHn. reflexivity.\nQed.  \n\nOpen Scope nat.\n(* oraclemap with intermediate rb is same as oi_prg with i = numcalls *)\nLemma oracleMap_rb_eq : forall calls k v res n,\n    n + length calls = numCalls ->\n   comp_spec\n     (fun (x : list (list (Bvector eta)) * KV)\n        (y : list (list (Bvector eta)) * (nat * KV)) => \n      fst x = fst y)\n     (compFold (pair_EqDec (list_EqDec (list_EqDec eqdbv)) eqDecState)\n        (fun (acc : list (list (Bvector eta)) * KV) (d : nat) =>\n         [rs, s]<-2 acc;\n         z <-$ GenUpdate_rb_intermediate s d;\n         [r, s0]<-2 z; ret (rs ++ r :: nil, s0)) (res, (k, v))\n        calls)\n     (compFold\n        (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n           (pair_EqDec nat_EqDec eqDecState))\n        (fun (acc : list (list (Bvector eta)) * (nat * KV)) (d : nat) =>\n         [rs, s]<-2 acc;\n         z <-$ Oi_prg numCalls s d; [r, s0]<-2 z; ret (rs ++ r :: nil, s0))\n        (res, (n, (k, v))) calls).\nProof.\n  induction calls as [ | call calls']; intros.\n  - simplify. fcf_spec_ret.\n  - (* v-sampling *)\n    Opaque GenUpdate_rb_intermediate.\n    simplify. simpl in *.\n    fcf_skip_eq; kv_exist.\n    destruct (lt_dec n (n + S (length calls'))).\n    Focus 2. omega.\n    + Transparent GenUpdate_rb_intermediate.\n      repeat (simplify; fcf_skip_eq; simplify).\n    + simplify. destruct b.\n      eapply IHcalls'.\n      omega.\nQed.    \nClose Scope nat.\n\n(* G2 is equal to last hybrid *)\n(* should be even easier than G1 since no GenUpdate_noV happening? Wrong *)\nLemma G2_Gi_n_equal :\n  Pr[G2_prg] == Pr[Gi_prg numCalls].\nProof.\n(*  Print G2_prg.*)\n  rewrite G2_oracle_eq.\n  rewrite G2_oracle_eq_v_sampling.\n  fcf_to_prhl_eq.\n  unfold G2_prg''.\n  unfold Gi_prg.\n  fcf_skip_eq. simplify.\n\n  rename b into k. rename b0 into v.\n  fcf_skip.\n  instantiate (1 := (fun x y => fst x = fst y)).\n\n  (* note: switching between windows is C-x o *)\n  - unfold oracleMap.\n    apply oracleMap_rb_eq.\n    simpl.\n    unfold maxCallsAndBlocks.\n    apply length_replicate.\n\n  - simpl in *. subst.\n    simplify. fcf_reflexivity.\nQed.\n\n(* ---------------------------------- *)\n\n(* For PRF adversary:\n\nGen_loop_oc: takes an oracle in place of (f k)\n\nGenUpdate_oc: takes an oracle in place of (f k)\n\nOi_prg_rf: if n > i then query GenUpdate_rb, OC version\n           else if n = i then query Gen_loop_oc with the given oracle (RF)\n           else query GenUpdate, OC version (using PRF)\n\nPRF_Adversary: gives the Oi oracle the (f k) oracle it's given by Gi, and queries the resulting oracle `maxCalls` times, querying `numBlocks` each time. passes the result to the existing (non-adaptive) GenUpdate adversary\n\nGi_rf: gives the PRF_Adversary the random function oracle and returns what PRF_Adversary returns\n\nPRF_Advantage: defined in terms of PRF_Adversary, indexed by i \n(but PRF_Advantage should be the same for all i) *)\n\n(* Versions of Gen_loop and GenUpdate with that query the oracle in place of (f k) *)\n(* this is slightly different from Adam's version:\n\n  Fixpoint PRF_DRBG_f_G2 (v : D)(n : nat) :\n    OracleComp D (Bvector eta) (list (Bvector eta)) :=\n    match n with\n        | O => $ ret nil\n        | S n' => \n          r <--$ (OC_Query _ v);\n            ls' <--$ (PRF_DRBG_f_G2 (injD r) n');\n                $ ret (r :: ls')\n    end. *)\nFixpoint Gen_loop_oc (v : Bvector eta) (n : nat)\n  : OracleComp (list bool) (Bvector eta) (list (Bvector eta) * Bvector eta) :=\n  match n with\n  | O => $ ret (nil, v)\n  | S n' =>\n    v' <--$ (OC_Query _ (to_list v)); (* ORACLE USE *)\n    [bits, v''] <--$2 Gen_loop_oc v' n';\n    $ ret (v' :: bits, v'')\n  end.\n\n(* TODO trying to figure out dependencies for PRF_DRBG. can i instantiate key D etc.? *)\n(*Check dupProb_const.\nCheck PRF_DRBG_G3_bad_4_small.\nPrint PRF_DRBG_G3_bad_4.*)\n\n(* takes in key but doesn't use it, to match the type of other GenUpdates *)\nDefinition GenUpdate_oc (state : KV) (n : nat) :\n  OracleComp (list bool) (Bvector eta) (list (Bvector eta) * KV) :=\n  [k, v_0] <-2 state;\n  v <--$ (OC_Query _ (to_list v_0)); (* ORACLE USE *)\n  [bits, v'] <--$2 Gen_loop_oc v n;\n  (* TODO what's the state type here? and the global GenUpdate_oc return type? *)\n  k' <--$ (OC_Query _ (to_list v' ++ zeroes)); (* ORACLE USE *)\n  $ ret (bits, (k', v')).\n\n(* should use the oracle and ignore the passed-in k *)\nDefinition GenUpdate_noV_oc (state : KV) (n : nat) :\n  OracleComp (list bool) (Bvector eta)  (list (Bvector eta) * KV) :=\n  [k, v] <-2 state;\n  [bits, v'] <--$2 Gen_loop_oc v n;\n  (* TODO what's the state type here? and the global GenUpdate_oc return type? *)\n  k' <--$ (OC_Query _ (to_list v' ++ zeroes)); (* ORACLE USE *)\n  $ ret (bits, (k', v')).\n\n(* doesn't use the oracle, uses the PRF *)\nDefinition GenUpdate_PRF_oc (state : KV) (n : nat) :\n  OracleComp (list bool) (Bvector eta) (list (Bvector eta) * KV) :=\n  [k, v] <-2 state;\n  v' <- f k (to_list v);\n  [bits, v''] <-2 Gen_loop k v' n;\n  k' <- f k (to_list v'' ++ zeroes);\n  $ ret (bits, (k', v'')).\n\n(* doesn't use the state or oracle *)\n(* intermediates have unnecessary state and updating of the state to match earlier ones *)\n(* old version *)\n(* Definition GenUpdate_rb_intermediate_oc (state : KV) (n : nat)  *)\n(*   : OracleComp (list bool) (Bvector eta) (list (Bvector eta) * KV) := *)\n(*   bits <--$ $ Gen_loop_rb n;    (* promote comp to oraclecomp, then remove from o.c. *) *)\n(*   $ ret (bits, state). *)\n\n(* @v new version: uses last v and updates (k,v) anyway *)\nDefinition GenUpdate_rb_intermediate_oc (state : KV) (n : nat) \n  : OracleComp (list bool) (Bvector eta) (list (Bvector eta) * KV) :=\n  [k, v] <-2 state;\n  v' <--$ $ {0,1}^eta;\n  [bits, v''] <--$2 $ Gen_loop_rb_intermediate k v' n;    (* promote comp to oraclecomp, then remove from o.c. *)\n  $ ret (bits, (k, v'')).\n\n(* same as Oi_prg but each GenUpdate in it has been converted to OracleComp *)\n(* number of calls starts at 0 and ends at q. e.g.\nG1:      RB  PRF PRF\nGi_rf 1: RB  RF  PRF (i = 1 here)\nG2:      RB  RB  PRF *)\n(* number of calls: first call is 0, last call is (numCalls - 1) for numCalls calls total\nG0: PRF PRF PRF <-- Gi_prf 0\n    RF  PRF PRF <-- Gi_rf 0\nG1: RB  PRF PRF <-- Gi_prf 1\n    RB  RF  PRF <-- Gi_rf 1\nG2: RB  RB  PRF\nw    RB  RB  RF\nG3: RB  RB  RB  <-- note that there is no oracle slot to replace here\n    RB  RB  RB  <-- likewise\nthere should be (S numCalls) games, so games are numbered from 0 through numCalls *)\n(* there is always an oracle slot to replace until i >= numCalls *)\n\n(* not entirely sure these are all the right cases / in the right order *)\n(* i: index for oracle; callsSoFar; n *)\nDefinition Oi_oc' (i : nat) (sn : nat * KV) (n : nat) \n  : OracleComp Blist (Bvector eta) (list (Bvector eta) * (nat * KV)) :=\n  [callsSoFar, state] <-2 sn;\n  let GenUpdate_choose :=\n      (* this behavior (applied with f_oracle) needs to match that of Oi_prg's *)\n      if lt_dec callsSoFar i (* callsSoFar < i (override all else) *)\n           then GenUpdate_rb_intermediate_oc (* this implicitly has no v to update *)\n      else if beq_nat callsSoFar O (* use oracle on 1st call w/o updating v *)\n           then GenUpdate_noV_oc \n      else if beq_nat callsSoFar i (* callsSoFar = i *)\n           then GenUpdate_oc    (* uses provided oracle (PRF or RF) *)\n      else GenUpdate_PRF_oc in        (* uses PRF with (k,v) updating *)\n  [bits, state'] <--$2 GenUpdate_choose state n;\n  $ ret (bits, (S callsSoFar, state')).\n\n(* oracleCompMap_inner repeatedly applies the given oracle on the list of inputs (given an initial oracle state), collecting the outputs and final state *)\n(* Fixpoint oracleCompMap_inner_acc {D R OracleIn OracleOut : Set}  *)\n(*            (e1 : EqDec ((list R) * (nat * KV)))  *)\n(*            (e2 : EqDec (list R)) *)\n(*            (* this is an oracleComp, not an oracle *) *)\n(*            (* the oracle has type (D * R) -> D -> Comp (R, (D * R)) *) *)\n(*            (oracleComp : (nat * KV) -> D -> OracleComp OracleIn OracleOut (R * (nat * KV)))  *)\n(*            (state : (nat * KV)) *)\n(*            (init : list R) *)\n(*            (inputs : list D) : OracleComp OracleIn OracleOut (list R * (nat * KV)) := *)\n(*   match inputs with *)\n(*   | nil => $ ret (init, state) *)\n(*   | input :: inputs' =>  *)\n(*     [res, state'] <--$2 oracleComp state input; (* doesn't use the init *) *)\n(*     [resList, state''] <--$2 oracleCompMap_inner_acc _ _ oracleComp state' init inputs'; *)\n(*     $ ret (init ++ res :: resList, state'') *)\n(*   end. *)\n\n(* Print compFold. *)\n(* Print oracleMap. *)\n(* Print oc_compMap. *)\n(* compare to oc_compMap *)\n(* maybe i don't even need to rewrite oracleCompMap_inner. what theorem do i really want? TODO *)\n\nFixpoint oracleCompMap_inner {D R OracleIn OracleOut : Set} \n           (e1 : EqDec ((list R) * (nat * KV))) \n           (e2 : EqDec (list R))\n           (* this is an oracleComp, not an oracle *)\n           (* the oracle has type (D * R) -> D -> Comp (R, (D * R)) *)\n           (oracleComp : (nat * KV) -> D -> OracleComp OracleIn OracleOut (R * (nat * KV))) \n           (state : (nat * KV)) (* note this state type -- it is EXPLICITLY being passed around *)\n           (inputs : list D) : OracleComp OracleIn OracleOut (list R * (nat * KV)) :=\n  match inputs with\n  | nil => $ ret (nil, state)\n  | input :: inputs' => \n    [res, state'] <--$2 oracleComp state input;\n    [resList, state''] <--$2 oracleCompMap_inner _ _ oracleComp state' inputs';\n    $ ret (res :: resList, state'')\n  end.\n\n(* hides the oracle state from the caller. instantates the initial state and does not return the end state. need this, otherwise the PRF adversary has to generate the key and initial value (and can see it, which it shouldn't be able to) *)\nDefinition oracleCompMap_outer {D R OracleIn OracleOut : Set} \n           (e1 : EqDec ((list R) * (nat * KV))) \n           (e2 : EqDec (list R))\n           (oracleComp : (nat * KV) -> D -> OracleComp OracleIn OracleOut (R * (nat * KV)))\n           (inputs : list D) : OracleComp OracleIn OracleOut (list R) :=\n  [k, v] <--$2 $ Instantiate;   (* generate state inside, instead of being passed state *)\n  [bits, _] <--$2 oracleCompMap_inner _ _ oracleComp (O, (k, v)) inputs;\n  (* the \"_\" here has type (nat * KV) *)\n  $ ret bits.                    (* don't return the state to the PRF adversary *)\n\n(* see long comment above this section *)\nDefinition PRF_Adversary (i : nat) : OracleComp Blist (Bvector eta) bool :=\n  bits <--$ oracleCompMap_outer _ _ (Oi_oc' i) maxCallsAndBlocks;\n  $ A bits.\n\n(* ith game: use RF oracle *)\nDefinition Gi_rf (i : nat) : Comp bool :=\n  [b, _] <-$2 PRF_Adversary i _ _ (randomFunc ({0,1}^eta) eqdbl) nil;\n  ret b.\n\n(* ith game: use PRF oracle *)\nDefinition Gi_prf (i : nat) : Comp bool :=\n  k <-$ RndK;\n  [b, _] <-$2 PRF_Adversary i _ _ (f_oracle f _ k) tt;\n  ret b.\n\n(* Expose the bad events *)\n\nDefinition hasInputDups (state : list (Blist * Bvector eta)) : bool :=\n  hasDups _ (fst (split state)).\n\n(* ith game: use RF oracle *)\nDefinition Gi_rf_bad (i : nat) : Comp (bool * bool) :=\n  [b, state] <-$2 PRF_Adversary i _ _ (randomFunc ({0,1}^eta) eqdbl) nil;\n  ret (b, hasInputDups state). \n\nDefinition rb_oracle (state : list (Blist * Bvector eta)) (input : Blist) :=\n  output <-$ ({0,1}^eta);\n  ret (output, (input, output) :: state).\n\nDefinition Gi_rb (i : nat) : Comp bool :=\n  [b, state] <-$2 PRF_Adversary i _ _ rb_oracle nil;\n  let rbInputs := fst (split state) in\n  ret b.\n\n(* adam wrote a new game here -- bad event is repetition in the random INPUTS\nINPUTS = v :: (first n of outputs)? *)\n(* pass in the RB oracle that records its inputs\nwhat about preceding/following RB and (especially) PRF inputs/outputs? *)\nDefinition Gi_rb_bad (i : nat) : Comp (bool * bool) :=\n  [b, state] <-$2 PRF_Adversary i _ _ rb_oracle nil;\n  ret (b, hasInputDups state). (* assumes ith element will exist, otherwise hasDups nil (default) = false *)\n\n(* replace maxCallsAndBlocks with a list we can evaluate on *)\nDefinition PRF_Adversary_l (i : nat) (l : list nat) : OracleComp Blist (Bvector eta) bool :=\n  bits <--$ oracleCompMap_outer _ _ (Oi_oc' i) l;\n  $ A bits.\n\n(* also replaced with hasDups: my hypothesis is that adam was right *)\nDefinition Gi_rf_bad_l (i : nat) (l : list nat) : Comp (bool * bool) :=\n  [b, state] <-$2 PRF_Adversary_l i l _ _ (randomFunc ({0,1}^eta) eqdbl) nil;\n  ret (b, hasInputDups state). (* assumes ith element will exist, otherwise hasDups nil (default) = false *)\n\nDefinition Gi_rb_bad_l (i : nat) (l : list nat) : Comp (bool * bool) :=\n  [b, state] <-$2 PRF_Adversary_l i l _ _ rb_oracle nil;\n  ret (b, hasDups _ state). (* assumes ith element will exist, otherwise hasDups nil (default) = false *)\n\n(* ----------------Begin PRF advantage reduction section *)\n\nDefinition PRF_Advantage_Game i : Rat := \n  PRF_Advantage RndK ({0,1}^eta) f eqdbl eqdbv (PRF_Adversary i).\n\n(*   | Pr  [PRF_G_A RndK f eqdbv (PRF_Adversary 0) ] -\n   Pr  [PRF_G_B ({ 0 , 1 }^eta) eqdbl eqdbv (PRF_Adversary 0) ] | =\n   | Pr  [PRF_G_A RndK f eqdbv (PRF_Adversary i) ] -\n   Pr  [PRF_G_B ({ 0 , 1 }^eta) eqdbl eqdbv (PRF_Adversary i) ] | *)\n\n(* TODO: are these lemmas even true? \nPA uses the existing adversary against the output?\nhere, numCalls = 4\n\nPA 0: using given oracle for call 0\nGA: PRF PRF PRF PRF?\nGB:  RF PRF PRF PRF \n\nPA 1: using given oracle for call 1\nGA: RB  PRF PRF PRF? \nGB: RB  RF  PRF PRF? \n(do the PRF_advantages add?)\n\nPA n-2: using given oracle for call (n-2) = 2\nGA: RB  RB  PRF PRF\nGB: RB  RB  RF  PRF\n\nPA n-1: using given oracle for call (n-1) = 3\nGA: RB  RB  RB  PRF\nGB: RB  RB  RB  RF\n\nPA n: using given oracle for call n = 4\n(note: there is no oracle to replace, so PRF_Advantage = 0)\nGA: RB  RB  RB  RB\nGB: RB  RB  RB  RB\n\nforall i, i != n -> \nPRF_Advantage_Game i = PRF_Advantage_Game j\nPRF_Advantage_Game n = 0\n\nthus, forall i, PRF_Advantage_Game i <= PRF_Advantage_Game 0 *)\n\nOpen Scope nat.\n(* the oracles don't matter (for those two specific oracles) *)\n(* could generalize this further to hold for any oracles, instead of f_oracle and RndR_func *)\nLemma Oi_numcalls_oracle_irrelevance : forall calls k v a (numCalls init : nat) acc tt,\n    init + length calls = numCalls ->\n   comp_spec\n     (fun (x : list (list (Bvector eta)) * (nat * KV) * unit)\n        (y : list (list (Bvector eta)) * (nat * KV) *\n             list (Blist * Bvector eta)) => fst x = fst y)\n     ((oracleCompMap_inner\n         (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n            (pair_EqDec nat_EqDec eqDecState))\n         (list_EqDec (list_EqDec eqdbv)) (Oi_oc' numCalls) \n         (init, (k, v)) calls) unit unit_EqDec\n        (f_oracle f eqdbv a) tt)\n     ((oracleCompMap_inner\n         (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n            (pair_EqDec nat_EqDec eqDecState))\n         (list_EqDec (list_EqDec eqdbv)) (Oi_oc' numCalls) \n         (init, (k, v)) calls) (list (Blist * Bvector eta))\n        (list_EqDec (pair_EqDec eqdbl eqdbv))\n        (RndR_func ({ 0 , 1 }^eta) eqdbl) acc).\nProof.\n(* didn't i do a gnarly proof just like this one earlier?? oh but it wasn't about oraclecompmap_inner. see 'G2 = last hybrid' proof*)\n  induction calls as [ | call calls']; intros.\n  - simpl.\n    fcf_simp.\n    fcf_spec_ret.\n  - simpl in H.\n    simpl.\n    fcf_inline_first.\n    fcf_skip; kv_exist.\n\n    { instantiate (1 := (fun x y => fst x = fst y)).\n      destruct (lt_dec init (init + S (length calls'))).\n      * unfold GenUpdate_rb_intermediate_oc.\n        simpl.\n        fcf_inline_first.\n        fcf_skip; kv_exist.\n        simplify.\n        fcf_skip_eq; kv_exist.\n        simplify.\n        fcf_spec_ret.\n\n     * omega.\n    }\n    simpl in H2.\n    destruct b1.\n    simpl in *.\n    subst.\n    fcf_inline_first.\n    simpl.\n    fcf_inline_first.\n    fcf_simp.\n    simpl.\n    fcf_skip.\n    destruct b0.                (* prevents unification *)\n    apply IHcalls'.             (* lol *)\n    omega.\n\n    simpl in H3.\n    destruct b2.\n    simpl in *.\n    subst.\n    fcf_simp.\n    fcf_spec_ret.\nQed.\n\nClose Scope nat.\n\nLemma PRF_Advantage_0 : \n    PRF_Advantage_Game numCalls == 0.\nProof.\n  intros. unfold PRF_Advantage_Game. unfold PRF_Advantage.\n  assert (distance_0_eq : forall r1 r2 : Rat, r1 == r2 -> | r1 - r2 | == 0).\n  { apply ratIdentityIndiscernables. }\n  apply distance_0_eq. clear distance_0_eq.\n  \n  fcf_to_prhl_eq. (* TODO when should I *not* use this? *)\n\n  (* TODO lemma that PRF_Advantage_Game numCalls always uses random bits and ignores the inputted oracle, so games A and B are on indistinguishable output *)\n\n  unfold PRF_Adversary.\n  unfold PRF_G_A.\n  unfold PRF_G_B.\n\n  fcf_irr_l. unfold RndK. fcf_well_formed.\n\n  simpl.\n  fcf_inline_first.\n  fcf_skip.\n  fcf_simp.\n  simpl.\n  fcf_inline_first.\n  fcf_skip.\n\n  (* arriving at oracleCompMap_inner: same but the oracles are different *)\n  instantiate (1 := (fun x y => fst x = fst y)). (* TODO: forgot why this and not eq *)\n  (* TODO: here, theorem about oracleCompMap_inner on maxCallsAndBlocks not using oracle (forall oracles A B...) *)\n\n  *\n    (* do i need induction? are there theorems about oracleCompMap (Adam's version)? *)\n    unfold Oi_oc'.\n    unfold oracleCompMap_inner.\n    apply Oi_numcalls_oracle_irrelevance.\n    simpl.\n    unfold maxCallsAndBlocks.\n    apply length_replicate.\n\n  * simpl.\n    fcf_simp.\n    fcf_inline_first.\n    simpl.\n    fcf_inline_first.\n    fcf_simp.\n    fcf_inline_first.\n    simpl in H4.\n    inversion H4.\n    subst.\n    fcf_skip.\n    fcf_simp. (* TODO ltac for this kind of proof *)\n    fcf_reflexivity.\nQed.\n\n(* Below can be used to establish a maximum advantage over all constructed adversaries *)\nTheorem gtRat_impl_leRat:\n  forall a b,\n    (a <= b -> False) ->\n    b <= a.\n\n    intuition.\n    rattac.\n    destruct (le_dec (n * x) (n0 * x0))%nat.\n    trivial.\n    exfalso.\n    eapply H.\n    rattac.\nQed.\n\nFixpoint argMax(f : nat -> Rat) (n : nat) :=\n  match n with\n    | O => O\n    | S n' => let p := (argMax f n') in\n              if (le_Rat_dec (f (S n')) (f p)) then p else (S n')\n                                                             end.\n\nTheorem argMax_correct :\n  forall (f : nat -> Rat)(n : nat),\n    (forall n', (n' <= n)%nat -> (f n') <= f (argMax f n)).\n\n  induction n; intuition; simpl in *.\n  assert (n' = O) by omega; subst.\n  intuition.\n  destruct (eq_nat_dec n' (S n)).\n  subst.\n  destruct (le_Rat_dec (f0 (S n)) (f0 (argMax f0 n)));\n  intuition.\n\n  assert (n' <= n)%nat by omega.\n  destruct (le_Rat_dec (f0 (S n)) (f0 (argMax f0 n))).\n  eapply IHn; eauto.\n  eapply leRat_trans.\n  eapply IHn.\n  trivial.\n  eapply gtRat_impl_leRat; eauto.\nQed.\n\nTheorem PRF_Advantage_max_exists :\n  forall i,\n      (i <= numCalls)%nat ->\n      PRF_Advantage_Game i <= PRF_Advantage_Game (argMax PRF_Advantage_Game numCalls).\n\n  intuition.\n  apply argMax_correct; trivial.\n\nQed.\n\nDefinition PRF_Advantage_Max := PRF_Advantage_Game (argMax PRF_Advantage_Game numCalls).\n\n(* The theorem above can be used in some of the arguments below, replacing 0 with (argMax PRF_Advantage_Game numCalls *)\n\n(* TODO moved to end for testing *)\n(* (* Step 1 *)\n(* Gi_prf 2: RB RB PRF PRF PRF\n   Gi_rf 2:  RB RB RF  PRF PRF \nneed to use `Gi_prf i` instead of `Gi_prg i` because this matches the form of \n`Gi_rf` closer so we can match the form of PRF_Advantage*)4\nLemma Gi_prf_rf_close_i : forall (i : nat),\n  | Pr[Gi_prf i] - Pr[Gi_rf i] | <= PRF_Advantage_Game i.\nProof.\n  intros i.\n  (* don't need to unfold *)\n  unfold Gi_prf.\n  unfold Gi_rf.\n  unfold PRF_Advantage_Game.\n  reflexivity. \nQed.\n\nLemma Gi_prf_rf_close : forall (i : nat),\n    (i <= numCalls)%nat ->\n  | Pr[Gi_prf i] - Pr[Gi_rf i] | <= PRF_Advantage_Max.\nProof.\n  intros.\n  eapply leRat_trans.\n  apply Gi_prf_rf_close_i.\n  apply PRF_Advantage_max_exists.\n  auto.\nQed. *)\n\n(* ------------------------------- *)\n\n(* Step 2 *)\n\n(* TODO use Adam's existing theorem. not sure if this is the right bound.\nshould be a function of [blocksPerCall + 1] (for the extra v-update) *)\nDefinition Pr_collisions := (S blocksPerCall)^2 / 2^eta.\n\n(* may need to update this w/ new proof *)\nDefinition Gi_Gi_plus_1_bound := PRF_Advantage_Max + Pr_collisions.\n\n(* These are all lemmas to rewrite games so I can apply identical until bad *)\n\nDefinition fst3 {A B C : Type} (abc : A * B * C) : A :=\n  let (ab, c) := abc in\n  let (a, b) := ab in\n  a.\n\nOpen Scope nat.\n\n(* These examples take a long time to check because of `simplify`. Commented out for now. *)\n\n(* folding on an acc that appends two lists = fold on the first list, use result as acc in fold on second list *)\nLemma fold_app_2 : forall (A0 B : Set) (eqd : EqDec A0) (c : A0 -> B -> Comp A0)\n                          (ls1 ls2 : list B) (init0 x : A0) (res : A0),\n    comp_spec eq (compFold eqd c init0 (ls1 ++ ls2))\n              (init' <-$ compFold eqd c init0 ls1; compFold eqd c init' ls2).\nProof.\n  intros.\n  revert c ls2 init0 x res; induction ls1 as [| x1 xs1]; intros.\n  - simpl. simplify. fcf_reflexivity.\n  - simplify.\n    fcf_skip_eq.\nQed.\n\n\n(* new postcondition *)\nDefinition bitsVEq {A B : Type} (x : A * (nat * KV)) (y : A * (nat * KV) * B) :=\n  let (bits_x, state_x) := x in\n  let (calls_x, kv_x) := state_x in\n  let (k_x, v_x) := kv_x in\n\n  let (bits_y, state_y) := fst y in\n  let (calls_y, kv_y) := state_y in\n  let (k_y, v_y) := kv_y in\n  (* no statement about keys being equal for now *)\n  bits_x = bits_y /\\ v_x = v_y /\\ calls_x = calls_y.\n\nLtac breakdown x := simpl in x; decompose [and] x; clear x; subst.\n\n(* -------- *)\n(* Rewrite gen_loop and updates computationally, and prove equivalence *)\n\nFixpoint Gen_loop_comp (k : Bvector eta) (v : Bvector eta) (n : nat)\n  : Comp (list (Bvector eta) * Bvector eta) :=\n  match n with\n  | O => ret (nil, v)\n  | S n' =>\n    v' <- f k (to_list v);\n    [bits, v''] <-$2 Gen_loop_comp k v' n';\n    ret (v' :: bits, v'')\n  end.\n\n(* want to change to this, and prove the outputs are the same. \nthe other GenUpdates don't use this version *)\nDefinition GenUpdate_comp (state : KV) (n : nat) :\n  Comp (list (Bvector eta) * KV) :=\n  [k, v] <-2 state;\n  v' <- f k (to_list v);\n  [bits, v''] <-$2 Gen_loop_comp k v' n;\n  k' <- f k (to_list v'' ++ zeroes);\n  ret (bits, (k', v'')).\n\n(* use this for the first call *)\nDefinition GenUpdate_noV_comp (state : KV) (n : nat) :\n  Comp (list (Bvector eta) * KV) :=\n  [k, v] <-2 state;\n  [bits, v'] <-$2 Gen_loop_comp k v n;\n  k' <- f k (to_list v' ++ zeroes);\n  ret (bits, (k', v')).\n\nLemma Gen_loop_comp_eq : forall n k v,\n  comp_spec eq (ret (Gen_loop k v n)) (Gen_loop_comp k v n).\nProof.\n  induction n as [ | n']; intros.\n  - simpl. fcf_spec_ret.\n  - simpl.\n    unfold setLet.\n    (* You need to apply your induction hypothesis to the first statement of the computation on the right.  The most direct way to do this is to explicitly apply transitivity: *)\n    (* eapply comp_spec_eq_trans. *)\n(*    Print comp_spec_eq_trans.*)\n    eapply\n      (@comp_spec_eq_trans _ _ \n           ((ret (let (bits, v'') := Gen_loop k (f k (to_list v)) n' in\n                  (f k (to_list v) :: bits, v''))))\n\n           (z <-$ ret Gen_loop k (f k (to_list v)) n';\n            [bits, v'']<-2 z;\n            ret (f k (to_list v) :: bits, v''))).\n        \n    comp_simp; reflexivity.\n    comp_skip.\n    (* this tactic will find the induction hypothesis and apply it *)\nQed.\n\nLemma Gen_loop_comp_eq_outer : forall n k v,\n   comp_spec eq\n     ([bits, v']<-2 Gen_loop k v n;\n      ret (bits, (f k (to_list v' ++ zeroes), v')))\n     (z <-$ Gen_loop_comp k v n;\n      [bits, v']<-2 z; ret (bits, (f k (to_list v' ++ zeroes), v'))).\nProof.\n  intros. \n  pose proof (Gen_loop_comp_eq n k v).\n  eapply comp_spec_eq_trans.\n  instantiate (1 := (z <-$ ret Gen_loop k v n;\n         [bits, v'']<-2 z; ret (bits, (f k (to_list v'' ++ zeroes), v'')))).\n  simplify. fcf_spec_ret.\n  fcf_skip_eq.\nQed.\n\nLemma GenUpdate_comp_eq : forall n k v,\n  comp_spec eq (GenUpdate (k,v) n) (GenUpdate_comp (k,v) n).\nProof.\n  intros. simpl. unfold setLet. apply Gen_loop_comp_eq_outer.\nQed.\n\nLemma Gen_loop_oc_eq : forall n k v,\n   comp_spec\n     (fun (x : list (Bvector eta) * Bvector eta)\n        (y : list (Bvector eta) * Bvector eta * unit) =>\n      fst x = fst (fst y) /\\ snd x = snd (fst y)) \n     (Gen_loop_comp k v n)\n     ((Gen_loop_oc v n) unit unit_EqDec (f_oracle f eqdbv k) tt).\nProof.\n  induction n as [ | n']; intros.\n  - simplify. fcf_spec_ret.\n  - simpl.\n    unfold setLet.\n    prog_ret_r.\n    fcf_skip. fcf_simp. simpl in *. subst. fcf_spec_ret.\nQed.\n\n(* ------- *)\n\n(* second induction used to prove the lemma after it. calls = i, then destruct, the induction on calls > i *)\nLemma Gi_normal_prf_eq_calls_eq_i :\n  forall (l : list nat) (i calls : nat) (k1 k2 v : Bvector eta) init,\n    calls = i ->\n    comp_spec\n      (fun (c : list (list (Bvector eta)) * (nat * KV))\n           (d : list (list (Bvector eta)) * (nat * KV) * unit) => \n         bitsVEq c d)\n      (compFold\n         (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n                     (pair_EqDec nat_EqDec eqDecState))\n         (fun (acc : list (list (Bvector eta)) * (nat * KV)) (d : nat) =>\n            [rs, s]<-2 acc;\n          z <-$ Oi_prg i s d; [r, s0]<-2 z; ret (rs ++ r :: nil, s0))\n         (init, (calls, (k1, v))) l)\n      (z <-$\n         (oracleCompMap_inner\n            (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n                        (pair_EqDec nat_EqDec eqDecState))\n            (list_EqDec (list_EqDec eqdbv)) (Oi_oc' i) \n            (calls, (k2, v)) l) unit unit_EqDec \n         (f_oracle f eqdbv k1) tt;\n       [bits, nkv, state']<-3 z; ret (init ++ bits, nkv, state')).\nProof.\n  Opaque Oi_prg. Opaque Oi_oc'.\n  destruct l as [ | x xs]; intros.\n\n  - simplify. fcf_spec_ret. simpl. repeat (split; auto).\n    rewrite app_nil_r; reflexivity.\n  -\n    simplify.\n    fcf_skip; kv_exist.\n    instantiate (1 := (fun c d => bitsVEq c d\n                                  /\\ fst (snd c) = S i /\\ fst (snd (fst d)) = S i\n                                  (* keys become equal afterward on call i *)\n                                  /\\ fst (snd (snd c)) = fst (snd (snd (fst d))))).\n    (* 1 call *)\n    {\n      Transparent Oi_prg. Transparent Oi_oc'.\n      unfold Oi_prg. unfold Oi_oc'.\n      simplify.\n      (* casework on `i = 0`, `calls = i` and `calls > i` *)\n      destruct (lt_dec i i). omega. \n      clear n.\n      destruct (beq_nat i 0).\n      -\n        fcf_skip; kv_exist.\n        instantiate (1 := (fun x y => fst x = fst (fst y) /\\ snd x = snd (fst y))).\n        simpl. fcf_inline_first.\n        eapply comp_spec_eq_trans_l.\n        apply Gen_loop_comp_eq_outer.\n\n        fcf_skip. \n        instantiate (1 := (fun x y => fst x = fst (fst y) /\\ snd x = snd (fst y))).\n        (* induction *)\n        apply Gen_loop_oc_eq.\n\n        simplify. simpl in H1. breakdown H1. fcf_spec_ret.\n        simplify. simpl in H1. breakdown H1. fcf_spec_ret.\n        simpl. destruct k. auto.\n\n      - Opaque GenUpdate.\n        simpl.\n        assert (beq_nat i i = true) by apply Nat.eqb_refl.\n        destruct (beq_nat i i).\n        Focus 2. inversion H.\n        clear H.\n        fcf_skip; kv_exist.\n        instantiate (1 := (fun x y => fst x = fst (fst y) /\\ snd x = snd (fst y))).\n        Transparent GenUpdate. unfold GenUpdate. unfold GenUpdate_oc.\n        simpl. unfold setLet. prog_ret_r.\n        eapply comp_spec_eq_trans_l.\n        apply Gen_loop_comp_eq_outer.        \n        fcf_skip. \n\n        (* induction *)\n        apply Gen_loop_oc_eq.\n\n        simplify. simpl in H1. breakdown H1. fcf_spec_ret.\n        simplify. simpl in H1. breakdown H1. fcf_spec_ret.\n        simpl. destruct k. auto.\n        Opaque Oi_prg. Opaque Oi_oc'.\n    }\n\n    (* rest of calls -- induct on the new list *)\n    { simplify. simpl in *. destruct b0. destruct p. destruct k. simpl in *. breakdown H2. \n\n      clear H1 H3 H0.\n      rename b1 into k'. rename b2 into v'.\n      remember (S i) as calls.\n      assert (H_calls : calls > i) by omega.\n      clear Heqcalls k2 v.\n      revert x i k1 init l k' v' u calls H_calls.\n      induction xs as [ | x' xs']; intros.\n\n      (* xs = nil *)\n      + simplify. fcf_spec_ret. simpl. repeat (split; auto).\n      (* xs = x' :: xs', use IH *)\n      + simplify.\n        fcf_skip; kv_exist.\n\n        (* one call with calls > i (calls = S i) *)\n        instantiate (1 := (fun c d => bitsVEq c d\n                                      (* calls incremented by one *)\n                                      /\\ fst (snd c) = S calls\n                                      /\\ fst (snd (fst d)) = S calls\n                                      (* keys equal *)\n                                      /\\ fst (snd (snd c)) = fst (snd (snd (fst d))))).\n        {\n          Transparent Oi_prg. Transparent Oi_oc'.\n          unfold Oi_prg. unfold Oi_oc'.\n          (* calls > i implies S calls != i *)\n          assert (H_false : beq_nat (S calls) i = false).\n          { apply Nat.eqb_neq. omega. }\n          destruct (beq_nat (S calls) i). inversion H_false.\n          clear H_false.\n          simplify.\n          destruct (lt_dec calls i). omega. (* contradiction *)\n          apply not_lt in n.\n          assert (beq_nat calls 0 = false).\n          { apply Nat.eqb_neq. omega. }\n          rewrite H0. Opaque GenUpdate.\n          simpl.\n          assert (beq_nat calls i = false).\n          { apply Nat.eqb_neq. omega. }\n          rewrite H1.\n          Transparent GenUpdate. simpl. fcf_inline_first.\n          fcf_skip; kv_exist.\n          instantiate (1 := (fun x y => fst x = fst (fst y) /\\ snd x = snd (fst y))).\n          fcf_simp. \n          fcf_spec_ret.\n          simplify. simpl in *. breakdown H4. fcf_spec_ret.\n          simpl. destruct k. auto.\n          Opaque Oi_prg. Opaque Oi_oc'.          \n        }\n\n        simpl in H2. destruct b0. destruct b. destruct p. destruct p. destruct k. simpl in *. breakdown H2.\n        simplify.\n        \n        eapply comp_spec_eq_trans_r. \n        eapply H; omega.\n        \n        (* now prove oracleCompMap_inner's eq *)\n        { instantiate (1 := k1). \n          fcf_skip_eq; kv_exist.\n          simplify. fcf_spec_ret.\n          f_equal. f_equal.\n          rewrite <- app_cons_eq.\n          reflexivity.\n        }\n    }\nQed.\n\nTheorem Gen_loop_rb_intermediate_keys_diff : forall (n : nat) (k1 k2 v : Bvector eta),\n   comp_spec eq (Gen_loop_rb_intermediate k1 v n) (Gen_loop_rb_intermediate k2 v n).\nProof.\n  induction n as [ | n']; intros; simpl.\n  - fcf_spec_ret.\n  - fcf_skip. fcf_skip.\nQed.\n\nTheorem Gi_normal_prf_eq_compspec :\n  forall (l : list nat) (i calls : nat) (k1 k2 v : Bvector eta) init,\n    calls <= i ->\n\n    comp_spec\n      (fun (x : list (list (Bvector eta)) * (nat * KV))\n           (y : list (list (Bvector eta)) * (nat * KV) * unit) =>\n         bitsVEq x y)\n\n      (compFold\n         (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n                     (pair_EqDec nat_EqDec eqDecState))\n         (fun (acc : list (list (Bvector eta)) * (nat * KV)) (d : nat) =>\n            [rs, s]<-2 acc;\n         z <-$ Oi_prg i s d; [r, s0]<-2 z; ret (rs ++ r :: nil, s0))\n        (init, (calls, (k1, v))) l)\n\n     ([acc', state'] <-$2 ((oracleCompMap_inner\n         (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n            (pair_EqDec nat_EqDec eqDecState))\n         (list_EqDec (list_EqDec eqdbv)) (Oi_oc' i) \n         (calls, (k2, v)) l) unit unit_EqDec \n        (f_oracle f eqdbv k1) tt);\n      [bits, nkv] <-2 acc';\n      ret (init ++ bits, nkv, state')).\nProof.\n  induction l as [ | x xs]; intros.\n\n  - simpl in *.\n    simplify.\n    fcf_spec_ret.\n    simpl.\n    repeat (split; auto).\n    rewrite app_nil_r. reflexivity.\n\n  -                             (* l = x :: xs *)\n    assert (H_ilen : calls < i \\/ calls = i) by omega.\n    destruct H_ilen.\n    clear H.\n\n    (* calls < i *)\n    + Opaque Oi_prg. Opaque Oi_oc'.\n      unfold oracleMap.\n      simplify.\n      fcf_skip; kv_exist.\n      (* strengthen postcondition so we can prove calls < i -> S calls <= i to apply IHxs *)\n      (* also strengthen it again because if calls < i then the keys must still be the same *)\n      instantiate (1 := (fun c d => bitsVEq c d\n                                    (* calls incremented by 1 *)\n                                    /\\ fst (snd c) = S calls /\\ fst (snd (fst d)) = S calls\n                                    (* output keys are the input keys *)\n                                    (* /\\ fst (snd (snd c)) = fst (snd (snd (fst d))) )). *)\n                                    /\\ fst (snd (snd c)) = k1\n                                    /\\ fst (snd (snd (fst d))) = k2)).\n      (* includes calls *)\n      (* one call with linked keys TODO *)\n      {\n        Transparent Oi_prg. Transparent Oi_oc'.\n        simpl.\n        destruct (lt_dec calls i).\n        Focus 2. omega.         (* contradiction *)\n        clear l.                (* calls < i *)\n        unfold GenUpdate_rb_intermediate.\n        simplify.\n        (* @v *)\n        fcf_skip_eq; kv_exist.\n        simplify.\n        fcf_skip; kv_exist.\n        apply Gen_loop_rb_intermediate_keys_diff.\n        subst. simplify.\n        fcf_spec_ret.\n        unfold bitsVEq. simpl. auto.\n      }\n\n      (* use IH *)\n      { simpl in H2. destruct b0. destruct b. destruct p. destruct p. destruct k. simpl in *.\n        breakdown H2. \n        simplify.\n\n        eapply comp_spec_eq_trans_r.\n        eapply IHxs; omega. \n\n        (* now prove oracleCompMap_inner's eq *)\n        { fcf_skip_eq; kv_exist.\n          simplify.\n          instantiate (1 := k2).\n          destruct u.\n          fcf_reflexivity.\n          simplify.\n          fcf_spec_ret. rewrite <- app_assoc. f_equal.\n        }\n      } \n    \n    (* calls = i *)\n  + clear IHxs.\n    apply Gi_normal_prf_eq_calls_eq_i; omega.\nQed.\n        \nTransparent oracleMap.\nTransparent oracleCompMap_inner.\nTransparent Oi_prg.\nTransparent Oi_oc'.\n\n(* this moves from the normal adversary to the PRF adversary (which depends on the prev.) *)\n(* Gi_prg 0: PRF PRF PRF PRF\n   Gi_prf 0: PRF PRF PRF PRF\n   Gi_prg 2: RB RB PRF PRF\n   Gi_prf 2: RB RB PRF PRF *)\nLemma Gi_normal_prf_eq : forall (i : nat),\n  Pr[Gi_prg i] == Pr[Gi_prf i].\nProof.\n  intros.\n  unfold Gi_prg.\n  unfold Gi_prf.\n  unfold PRF_Adversary.\n\n  fcf_to_prhl_eq.\n  unfold Instantiate.\n  unfold oracleCompMap_outer.\n  fcf_inline_first.\n\n  unfold Instantiate.\n  comp_skip.\n  Opaque oracleMap.\n  simpl.\n  fcf_inline_first.\n\n  unfold Instantiate.\n  fcf_inline_first.\n  fcf_irr_r. unfold RndK. fcf_well_formed.\n  fcf_inline_first.\n  comp_skip.\n  fcf_simp.\n  simpl.\n  fcf_inline_first.\n  fcf_skip.\n\n  instantiate (1 := fun x y => bitsVEq x y).\n  -\n    Transparent oracleMap.\n    pose proof Gi_normal_prf_eq_compspec as Gi_prf_compspec.\n    unfold oracleMap.\n    specialize (Gi_prf_compspec maxCallsAndBlocks i 0 b b0 b1 nil).\n    eapply comp_spec_eq_trans_r.\n    eapply Gi_prf_compspec; omega.\n    simplify.\n    fcf_ident_expand_r.\n    fcf_skip_eq; kv_exist.\n\n  - simplify.\n    simpl in H6. destruct b3. destruct p. destruct k. breakdown H6.\n    fcf_ident_expand_l.\n    fcf_skip_eq.\n    simplify.\n    fcf_reflexivity.\nQed.\n\n(* expose the bad event (dups) *)\nLemma Gi_rf_return_bad_eq : forall (i : nat),\n    Pr[Gi_rf i] == Pr[x <-$ Gi_rf_bad i; ret fst x].\nProof.\n  intros. (* over all i--could be hard? *)\n  fcf_to_prhl_eq.\n  unfold Gi_rf.\n  unfold Gi_rf_bad.\n  repeat (simplify; fcf_skip_eq).\n  simplify. fcf_spec_ret.\nQed.\n\nDefinition randomFunc_withDups (ls : list (Blist * Bvector eta)) (x : Blist) :\n                               Comp (Bvector eta * list (Blist * Bvector eta)) :=\n  y <-$ \n    (match (arrayLookup _ ls x) with \n     | Some y => ret y \n     | None => {0,1}^eta \n     end); \n  ret (y, (x, y) :: ls).\n\n(* ith game: use RF oracle *)\nDefinition Gi_rf_dups_bad (i : nat) : Comp (bool * bool) :=\n  [b, state] <-$2 PRF_Adversary i _ _ randomFunc_withDups nil;\n  ret (b, hasInputDups state). \n\nTheorem oracleCompMap_inner_oracle_equiv : \n    forall (A B C D S : Set) (eqdc : EqDec C)(eqdd : EqDec D)(eqds : EqDec S) blocks (inv : S -> S -> Prop) (oc : nat * KV -> A -> OracleComp B C (D * (nat * KV))) s (o1 o2 : S -> B -> Comp (C * S)) s1 s2,\n    (forall s1 s2, inv s1 s2 -> (forall a, comp_spec (fun x1 x2 => (fst x1 = fst x2) /\\ inv (snd x1) (snd x2)) (o1 s1 a) (o2 s2 a))) ->\n    inv s1 s2 ->\n    comp_spec (fun x1 x2 => fst x1 = fst x2 /\\ inv (snd x1) (snd x2))\n   ((oracleCompMap_inner _ _ oc\n         s blocks) _ _\n        o1 s1)\n  ((oracleCompMap_inner _ _ oc\n         s blocks) _ _\n        o2 s2).\n  \n  induction blocks; intuition; simpl; fcf_simp.\n  apply comp_spec_ret; intuition.\n\n  fcf_simp.\n  fcf_skip.\n  eapply oc_comp_spec_eq.\n  apply H0.\n  intuition.\n  \n  fcf_simp.\n  simpl in *.\n  intuition.\n  pairInv.\n  fcf_skip.\n  simpl in *.\n  destruct b3.\n  simpl in *. subst.\n  fcf_simp.\n  apply comp_spec_ret.\n  simpl.\n  intuition.\n\nQed.\n\n\nTheorem randomFunc_withDups_spec : \n  forall s1 s2 a,\n  (forall a, arrayLookup _ s1 a = arrayLookup _ s2 a) ->\n  comp_spec\n     (fun x1 x2 : Bvector eta * list (Blist * Bvector eta) =>\n      fst x1 = fst x2 /\\\n      (forall a0, \n       arrayLookup _ (snd x1) a0 = arrayLookup _ (snd x2) a0))\n     (randomFunc ({ 0 , 1 }^eta) _ s1 a) (randomFunc_withDups s2 a).\n\n  clear f.\n  intuition.\n  unfold randomFunc_withDups, randomFunc.\n  case_eq (arrayLookup _ s1 a); intuition.\n  rewrite <- H.\n  rewrite -> H0.\n\n  fcf_simp.\n  apply comp_spec_ret.\n  intuition.\n  simpl. \n  case_eq (eqb a0 a); intuition.\n  rewrite eqb_leibniz in H1.\n  subst. trivial.\n\n  rewrite <- H.\n  rewrite H0.\n  fcf_skip.\n  apply oneVector.\n  apply oneVector.\n  eapply comp_spec_ret.\n  intuition.\n  simpl.\n  rewrite H. \n  trivial.\nQed.\n\nLemma oracleCompMap_rf_oracle_irrelevance : forall blocks calls i k v state,\n   comp_spec (fun x1 x2 => fst x1 = fst x2 /\\ forall a, arrayLookup _ (snd x1) a = arrayLookup _ (snd x2) a)\n     ((oracleCompMap_inner\n         (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n            (pair_EqDec nat_EqDec eqDecState))\n         (list_EqDec (list_EqDec eqdbv)) (Oi_oc' i) \n         (calls, (k, v)) blocks) (list (Blist * Bvector eta))\n        (list_EqDec (pair_EqDec eqdbl eqdbv))\n        (randomFunc ({ 0 , 1 }^eta) eqdbl) state)\n     ((oracleCompMap_inner\n         (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n            (pair_EqDec nat_EqDec eqDecState))\n         (list_EqDec (list_EqDec eqdbv)) (Oi_oc' i) \n         (calls, (k, v)) blocks) (list (Blist * Bvector eta))\n        (list_EqDec (pair_EqDec eqdbl eqdbv)) randomFunc_withDups state).\nProof.\n  intros.\n  eapply comp_spec_consequence.\n  eapply (oracleCompMap_inner_oracle_equiv _ _ (fun s1 s2 => forall a, arrayLookup _ s1 a = arrayLookup _ s2 a)); intuition.\n   apply randomFunc_withDups_spec; intuition.\n  intuition.\nQed.\n \nLemma Gi_rf_dups_return_bad_eq : forall (i : nat),\n    Pr[x <-$ Gi_rf_bad i; ret fst x] == Pr[x <-$ Gi_rf_dups_bad i; ret fst x].\nProof.\n  intros.\n  fcf_to_prhl_eq.\n  unfold Gi_rf_bad.\n  unfold Gi_rf_dups_bad.\n\n  repeat (simplify; fcf_skip).\n  apply oracleCompMap_rf_oracle_irrelevance.\n  simpl in *.\n  intuition; pairInv.\n  eapply comp_spec_eq_refl.\n  fcf_simp.\n  subst.\n  reflexivity.\nQed.\n\n(* expose the bad event (dups) *)\nLemma Gi_rb_return_bad_eq : forall (i : nat),\n    Pr[Gi_rb i] == Pr[x <-$ Gi_rb_bad i; ret fst x].\nProof.\n  intros.\n  fcf_to_prhl_eq.\n  unfold Gi_rb.\n  unfold Gi_rb_bad.\n  repeat (simplify; fcf_skip_eq).\n  simplify.\n  fcf_spec_ret.\nQed.\n\n(* ---------------------------------- *)\n(* Assuming the Gi_normal_rb_eq stuff starts here *)\n\n(* Used in the below proof: relates Gen_loop_rb_intermediate and Gen_loop_oc *)\nLemma Gen_loop_rb_intermediate_oc_related : forall (n : nat) (k v : Bvector eta) (rb_state : list (Blist * (Bvector eta))),\n   comp_spec\n     (fun (x : list (Bvector eta) * Bvector eta)\n        (y : list (Bvector eta) * Bvector eta * list (Blist * Bvector eta)) =>\n      fst x = fst (fst y) /\\ snd x = snd (fst y))\n     (Gen_loop_rb_intermediate k v n)\n     ((Gen_loop_oc v n) (list (Blist * Bvector eta))\n        (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle rb_state).\nProof.\n  induction n as [ | n']; intros; simplify.\n  - fcf_spec_ret.\n  - unfold rb_oracle. simplify. fcf_skip_eq. simplify. fold rb_oracle.\n    fcf_skip. simpl in *. destruct b0. simpl in *. destruct p. simpl in *. subst.\n    simplify. fcf_spec_ret.\nQed.\n\n(* used in Oi_oc''. the difference between this function and GenUpdate_oc is that\nit hardcodes the oracle to be RB oracle, and moves the k update to be the first line, \nrather than being after the bit generation, because k no longer depends on the new v *)\n(* takes in key but doesn't use it, to match the type of other GenUpdates *)\nDefinition GenUpdate_oc_instantiate (state : KV) (n : nat) :\n  OracleComp (list bool) (Bvector eta) (list (Bvector eta) * KV) :=\n  [k, v_0] <-2 state;\n  k' <--$ $ {0,1}^eta;\n  v <--$ $ {0,1}^eta;\n  [bits, v'] <--$2 Gen_loop_oc v n;\n  $ ret (bits, (k', v')).\n\n(* used in Oi_oc''. the difference between this function and GenUpdate_rb_intermediate_oc\nis that it now updates v (but still does not update k). \nwhy do we need to update v in the normal RB cases??? *)\n(* okay, i see that we're trying to match the form of GenUpdate_oc_instantiate *)\n(* at a high level, we're trying to bridge GenUpdate_oc_instantiate and GenUpdate_rb_intermediate_oc *)\n(* now unused *)\nDefinition GenUpdate_rb_intermediate_oc_noV (state : KV) (n : nat) \n  : OracleComp (list bool) (Bvector eta) (list (Bvector eta) * KV) :=\n  [k, v] <-2 state;\n  \n  [bits, v'] <--$2 $ Gen_loop_rb_intermediate k v n;    (* promote comp to oraclecomp, then remove from o.c. *)\n  $ ret (bits, (k, v')).\n\n(* does not carry the k state around *)\n(* TODO: this function and the next theorem aren't used anywhere?? *)\nFixpoint Gen_loop_rb_intermediate_v (v : Bvector eta) (n : nat)\n  : Comp (list (Bvector eta) * Bvector eta) :=\n  match n with\n  | O => ret (nil, v)\n  | S n' =>\n    v' <-$ {0,1}^eta;\n    [bits, v''] <-$2 Gen_loop_rb_intermediate_v v' n';\n    ret (v' :: bits, v'')\n  end.\n\nLemma Gen_loop_rb_intermediate_nok_eq : forall k v x any_v,\n    x <> 0 ->\n    comp_spec eq (Gen_loop_rb_intermediate k v x)\n              (Gen_loop_rb_intermediate_v any_v x).\nProof.\n  destruct x as [ | x']; intros.\n  - omega.\n  - revert k v any_v.                           (* any_v is used here only *)\n    induction x' as [ | x'']; intros.\n    + simpl. fcf_skip_eq.\n    + remember (S x'') as S_x''.\n      simpl. fcf_skip_eq. fcf_skip.\nQed.\n\n(* used in Oi_oc''. the difference between this function and GenUpdate_noV is that\n1. we assume the oracle passed in is the RB oracle\n2. because we make that assumption, k is independent of v, so we resample it\nbefore the bits are generated (for ease of skipping) rather than after *)\n(* note oracle state won't be the same as GenUpdate_noV_oc *)\nDefinition GenUpdate_noV_oc_k (state : KV) (n : nat) :\n  OracleComp (list bool) (Bvector eta)  (list (Bvector eta) * KV) :=\n  [k, v] <-2 state;\n  k' <--$ $ {0,1}^eta;\n  [bits, v'] <--$2 Gen_loop_oc v n;\n  $ ret (bits, (k', v')).\n(*\nPrint Oi_oc'.\nPrint Gen_loop_oc.*)\n\n(* (let GenUpdate_choose := *)\n(*    if lt_dec callsSoFar i *)\n(*    then GenUpdate_rb_intermediate_oc *)\n(*    else *)\n(*     if beq_nat callsSoFar 0 *)\n(*     then GenUpdate_noV_oc *)\n(*     else if beq_nat callsSoFar i then GenUpdate_oc else GenUpdate_PRF_oc in *)\n(*  z <--$ GenUpdate_choose state n; *)\n(*  [bits, state']<-2 z; $ ret (bits, (S callsSoFar, state'))) *)\n\n(* hardcode oracle everywhere to be RB oracle *)\n(* moves k sampling to the beginning of each relevant function *)\nDefinition Oi_oc'' (i : nat) (sn : nat * KV) (n : nat) \n  : OracleComp Blist (Bvector eta) (list (Bvector eta) * (nat * KV)) :=\n  [callsSoFar, state] <-2 sn;\n  let GenUpdate_choose :=\n      if lt_dec callsSoFar i\n      then GenUpdate_rb_intermediate_oc (* CHANGE: uses the last v *)\n      else if beq_nat callsSoFar O\n           then GenUpdate_noV_oc_k (* CHANGE: k pulled to beginning; does use last v *)\n           else if beq_nat callsSoFar i (* callsSoFar = i *)\n                then GenUpdate_oc_instantiate   (* CHANGE: kv pulled to beginning; does use last v *)\n                else GenUpdate_PRF_oc in\n  [bits, state'] <--$2 GenUpdate_choose state n;\n    $ ret (bits, (S callsSoFar, state')).\n\n(* uses genupdate rb on any call <= i *)\n(* removes the extra k or k,v sampling before bit gen *)\nDefinition Oi_oc''' (i : nat) (sn : nat * KV) (n : nat) \n  : OracleComp Blist (Bvector eta) (list (Bvector eta) * (nat * KV)) :=\n  [callsSoFar, state] <-2 sn;\n  let GenUpdate_choose :=\n      if lt_dec callsSoFar i\n      then GenUpdate_rb_intermediate_oc\n      else if beq_nat callsSoFar O\n           then GenUpdate_rb_intermediate_oc_noV (* no k-sampling or v-sampling *)\n           (* CHANGE: diff b/t GenUpdate_oc_k and this fn is, this one removes the k sampling before bit gen *)\n           else if beq_nat callsSoFar i (* callsSoFar = i *)\n                then GenUpdate_rb_intermediate_oc (* no k-sampling, only v-sampling *)\n                (* diff b/t GenUpdate_oc_instantiate and this fn is, this one removes the k sampling before bit gen *)\n                else GenUpdate_PRF_oc in\n  [bits, state'] <--$2 GenUpdate_choose state n;\n    $ ret (bits, (S callsSoFar, state')).\n\n\nLemma Gen_loop_oc_states_diff : forall x state2 state1 v ,\n   comp_spec\n     (fun\n        x0 y : list (Bvector eta) * Bvector eta * list (Blist * Bvector eta) =>\n      fst x0 = fst y)\n     ((Gen_loop_oc v x) (list (Blist * Bvector eta))\n        (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state2)\n     ((Gen_loop_oc v x) (list (Blist * Bvector eta))\n        (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state1).\nProof.\n    clear f.\n    induction x as [ | x']; intros; simplify.\n    - fcf_spec_ret.\n    - unfold rb_oracle. simplify. fold rb_oracle.\n      fcf_skip_eq. simplify.\n      fcf_skip. simplify. fcf_spec_ret.\n      simpl in *. inversion H1. f_equal.\nQed.  \n\n(* used below the below thm *)\nLemma GenUpdate_swap_k_loop_eq : forall state1 state2 k v x,\n   comp_spec\n     (fun x0 y : list (Bvector eta) * KV * list (Blist * Bvector eta) =>\n      fst x0 = fst y)\n     ((GenUpdate_noV_oc (k, v) x) (list (Blist * Bvector eta))\n        (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state1)\n     ((GenUpdate_noV_oc_k (k, v) x) (list (Blist * Bvector eta))\n        (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state2).\nProof.\n  intros.\n  unfold GenUpdate_noV_oc.\n  unfold GenUpdate_noV_oc_k.\n\n  simplify.\n  (* it's not updating the state?? probably bc i'm NOT using an oracle, just {0,1}^n? *)\n\n  (* swap the k-sampling with gen_loop on the right *)\n  rewrite_r.\n  (* well, are the states going to be equal?? should i get rid of states first and add ANOTHER intermediate game? *)\n  instantiate (1 :=\n                 (* Check ( *)\n                 (z1 <-$\n                     (Gen_loop_oc v x) (list (Blist * Bvector eta))\n                     (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state2;\n                  a <-$ { 0 , 1 }^eta;\n                  [z2, state3]<-2 z1;\n                  ([bits, v']<-2 z2; $ ret (bits, (a, v'))) (list (Blist * Bvector eta))\n                                                            (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state3)).\n  {\n    (* Print Ltac prog_swap_r. *)\n    rewrite_r.\n    instantiate (1 :=\n                   (a <-$ { 0 , 1 }^eta;\n                    z1 <-$\n                       (Gen_loop_oc v x) (list (Blist * Bvector eta))\n                       (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state2;\n                    [z2, state3]<-2 z1;\n                    ([bits, v']<-2 z2; $ ret (bits, (a, v'))) (list (Blist * Bvector eta))\n                                                              (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state3)).\n    eapply comp_spec_eq_swap.\n    fcf_skip_eq; kv_exist. simplify.\n    fcf_skip_eq. simplify. fcf_spec_ret.\n  }\n\n  fcf_skip. instantiate (1 := (fun x y => fst x = fst y)).\n  apply Gen_loop_oc_states_diff.\n\n  simplify. unfold rb_oracle. simplify. fcf_skip_eq. simplify. simpl in *. inversion H2. subst.\n  fcf_spec_ret.\nQed.\n\n(* similar to the above lemma, but w/ v-updates *)\nLemma GenUpdate_swap_k_loop_equiv_v_update : forall state1 state2 k v x,\n   comp_spec\n     (fun x0 y : list (Bvector eta) * KV * list (Blist * Bvector eta) =>\n      fst x0 = fst y)\n     ((GenUpdate_oc (k, v) x) (list (Blist * Bvector eta))\n        (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state1)\n     ((GenUpdate_oc_instantiate (k, v) x) (list (Blist * Bvector eta))\n        (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state2).\nProof.\n  intros.\n  unfold GenUpdate_oc.\n  unfold GenUpdate_oc_instantiate.\n  simplify.\n\n (* swap the k-sampling under v-sampling and gen_loop on the right *)\n  rewrite_r.\n  (* well, are the states going to be equal?? should i get rid of states first and add ANOTHER intermediate game? *)\n  instantiate (1 :=\n                 (* Check ( *)\n                 (res <-$ (v' <-$ {0,1}^eta;\n                           z1 <-$\n                              (Gen_loop_oc v' x) (list (Blist * Bvector eta))\n                              (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state2;\n                           ret (v', z1));\n                  a <-$ { 0 , 1 }^eta;\n                  [v', z1] <-2 res;\n                  [z2, state3]<-2 z1;\n                  ([bits, v']<-2 z2; $ ret (bits, (a, v'))) (list (Blist * Bvector eta))\n                                                            (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state3)).\n  {\n    (* Print Ltac prog_swap_r. *)\n    rewrite_r.\n    instantiate (1 :=\n                   (a <-$ { 0 , 1 }^eta;\n                    res <-$ (v' <-$ {0,1}^eta;\n                             z1 <-$\n                                (Gen_loop_oc v' x) (list (Blist * Bvector eta))\n                                (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state2;\n                             ret (v', z1));\n                    [v', z1] <-2 res;\n                    [z2, state3]<-2 z1;\n                    ([bits, v']<-2 z2; $ ret (bits, (a, v'))) (list (Blist * Bvector eta))\n                                                              (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state3)).\n    eapply comp_spec_eq_swap.\n    fcf_skip_eq; kv_exist. simplify.\n    fcf_skip_eq; kv_exist. simplify. fcf_skip_eq. simplify. fcf_spec_ret.\n  }\n\n  simplify. unfold rb_oracle. simplify. fold rb_oracle. fcf_skip_eq; kv_exist. simplify.\n  fcf_skip; kv_exist.\n\n  instantiate (1 := (fun x y => fst x = fst y)).\n  apply Gen_loop_oc_states_diff.\n\n  simpl in *. destruct b1. simpl in *. destruct p. inversion H2. subst.\n  simplify. unfold rb_oracle. simplify. fcf_skip_eq. simplify.\n  fcf_spec_ret.\nQed.\n\n(* Oi_oc' to Oi_oc'' *)\nLemma oracleCompMap_rb_instantiate_inner : forall l i k v calls state1 state2,\n    comp_spec (fun x y => fst x = fst y) (* rb state might not be equal *)\n              ((oracleCompMap_inner\n                  (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n                              (pair_EqDec nat_EqDec eqDecState))\n                  (list_EqDec (list_EqDec eqdbv)) (Oi_oc' i) \n                  (calls, (k, v)) l) (list (Blist * Bvector eta))\n                                     (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state1)\n\n              ((oracleCompMap_inner\n                  (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n                              (pair_EqDec nat_EqDec eqDecState))\n                  (list_EqDec (list_EqDec eqdbv)) (Oi_oc'' i)\n                  (* note the double prime here: this replaces OC_Query w Instantiate *)\n                  (* also in GenUpdate_noV_oc_k the one k call is moved up *)\n                  (calls, (k, v)) l) (list (Blist * Bvector eta))\n                                     (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state2).\nProof.\n  induction l as [ | x xs]; intros.\n  - simplify; fcf_spec_ret.\n  - simplify.\n    (*  \"(list (Bvector eta) * (nat * KV) * list (Blist * Bvector eta))%type\" with\n \"(list (Bvector eta) * KV * list (Blist * Bvector eta))%type\". *)\n    fcf_skip; kv_exist.\n    (* might need casework on calls = i *)\n    (* one call: Oi_oc' to Oi_oc'' *)\n    +\n      instantiate (1 := (fun x y => fst x = fst y)). (* rb state might not be equal *)\n      simplify. Transparent Oi_oc'. Transparent Oi_oc''. simpl.\n      destruct (beq_nat calls i).\n      (* calls = i *)\n      { destruct (lt_dec calls i).\n        { (* calls < i *)\n          simplify.\n          fcf_skip; kv_exist.\n          {\n            simplify.\n            fcf_skip; kv_exist.\n            simplify.\n            fcf_spec_ret.\n            (* @v hey this works now due to the v-updating changing. also i started redoing the bottom cases *)\n          }\n        }\n        (* calls >= i *)\n        apply not_lt in n.\n        destruct (beq_nat calls 0). \n        (* calls = 0 *)\n        - apply GenUpdate_swap_k_loop_eq.\n        - (* calls != 0 *)\n          apply GenUpdate_swap_k_loop_equiv_v_update.\n      } \n      (* calls != i *)\n      { (* same computations, but with different rb_state *)\n        (* fcf_skip; kv_exist. *)\n        (* instantiate (1 := (fun c d => fst c = fst d)). *)\n        {\n          destruct (lt_dec calls i).\n          - simplify. fcf_skip_eq; kv_exist. simplify.\n            fcf_skip; kv_exist.\n            simplify.\n            fcf_spec_ret.\n          - assert (beq_dec : calls = 0 \\/ calls <> 0) by omega.\n            destruct beq_dec as [beqtrue | beqfalse ].\n            apply not_lt in n.\n            apply beq_nat_true_iff in beqtrue.\n            rewrite beqtrue.\n\n            (* same case as above with k-sampling-swapping *)\n             apply GenUpdate_swap_k_loop_eq.\n\n            (* SearchAbout (beq_nat _ _). *)\n            apply beq_nat_false_iff in beqfalse. rewrite beqfalse.\n            simplify. fcf_spec_ret.\n        } \n\n        (* simplify. fcf_spec_ret. simpl in *. inversion H1. subst. f_equal. *)\n      } \n    + simpl in H1. destruct b0. destruct b1. destruct p. simpl in *. destruct k0. inversion H1. subst.\n      fcf_skip; kv_exist.\n      simplify.\n      instantiate (1 := (fun x y => fst x = fst y)).\n      fcf_spec_ret.\n      (* apply IHxs. *) (* ??? *)\n\n      simpl in H4. destruct b2. destruct p. destruct p. simpl in *. inversion H4. subst.\n      simplify.\n      fcf_skip. destruct k0. apply IHxs.\n      simplify. simpl in *. destruct p. inversion H7. subst.\n      fcf_spec_ret.\nQed.\n(* note i switched the order of k and v in GenUpdate_oc_instantiate *)\n\nNotation \"A = B = C\" := (A = B /\\ B = C).\n\n(* Oi_oc'' to Oi_oc''', case: calls > i *)\nLemma Oi_ocs_eq_calls_gt_i : forall l k v state1 state2 calls i,\n    calls > i ->\n   comp_spec (fun x y => fst x = fst y)\n     ((oracleCompMap_inner\n         (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n            (pair_EqDec nat_EqDec eqDecState))\n         (list_EqDec (list_EqDec eqdbv)) (Oi_oc'' i) \n         (calls, (k, v)) l) (list (Blist * Bvector eta))\n        (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state1)\n     ((oracleCompMap_inner\n         (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n            (pair_EqDec nat_EqDec eqDecState))\n         (list_EqDec (list_EqDec eqdbv)) (Oi_oc''' i) \n         (calls, (k, v)) l) (list (Blist * Bvector eta))\n        (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state2).\nProof.\n  induction l as [ | x xs]; intros.\n  - simplify. fcf_spec_ret.\n  - simplify.\n    destruct (lt_dec calls i). omega.\n    assert (calls_neq_i : calls <> i) by omega.\n    apply beq_nat_false_iff in calls_neq_i.\n    rewrite calls_neq_i. \n    assert (calls_neq_0 : calls <> 0) by omega.\n    apply beq_nat_false_iff in calls_neq_0.\n    rewrite calls_neq_0.\n    simplify. fcf_skip; kv_exist.\n    simplify. simpl in *. destruct l1. destruct p. inversion H2. subst.\n    fcf_spec_ret.\n    destruct p. inversion H2. subst.\n    fcf_spec_ret.\nQed.\n\n(* Oi_oc'' to Oi_oc''', case: i = 0 *)\nLemma oracleCompMap_rb_instantiate_outer_i_eq_0 : forall l i state,\n    beq_nat i 0 = true ->                                        (* separate theorem *)\n    comp_spec (fun x y => fst (fst x) = fst (fst y)) (* weaker precondition--just k's equal? *)\n              ([k, v] <-$2 Instantiate;\n               a <-$\n                 (oracleCompMap_inner\n                    (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n                                (pair_EqDec nat_EqDec eqDecState))\n                    (list_EqDec (list_EqDec eqdbv)) (Oi_oc'' i)\n                    (* note Oi_oc': need to rewrite w first theorem in outer *)\n                    (O, (k, v)) l) (list (Blist * Bvector eta))\n                 (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state;\n               ret a)\n              ([k, v] <-$2 Instantiate;\n               k <-$ RndK;    (* instead of Instantiate, to deal with noV *)\n               a <-$\n                 (oracleCompMap_inner\n                    (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n                                (pair_EqDec nat_EqDec eqDecState))\n                    (list_EqDec (list_EqDec eqdbv)) (Oi_oc''' i) \n                    (O, (k, v)) l) (list (Blist * Bvector eta))\n                 (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state;\n               ret a).\nProof.\n  intros.\n  (* rename H into calls_leq_i. *)\n  rename H into i_eq_0.\n  (* swap kv in latter as in the mask thm above *)\n  destruct l as [ | x xs].\n  - simplify. unfold Instantiate. simplify. fcf_irr_r. unfold RndK. fcf_well_formed.\n    simplify. rewrite_r.\n    { instantiate\n      (1 :=\n         (k0 <-$ RndK;\n          a <-$ RndV;\n          z <-$ ret (b, a);\n          [_, v]<-2 z;\n          a0 <-$ (x <-$ ret (nil, (O, (k0, v))); ret (x, state)); ret a0)).\n    fcf_swap fcf_right. fcf_skip_eq; kv_exist. fcf_skip_eq; kv_exist. simplify.\n    fcf_spec_ret. }\n    fcf_skip_eq; kv_exist. simplify. fcf_skip_eq; kv_exist. simplify. fcf_spec_ret.\n  -\n    (* calls = 0 and i = 0 *)\n    Opaque Oi_oc''. Opaque Oi_oc'''.\n    simplify.\n    (* Skip the two initial Instantiates *)\n    fcf_skip_eq; kv_exist. simplify.\n    Transparent Oi_oc''. Transparent Oi_oc'''.\n    simpl. apply beq_nat_true in i_eq_0. subst. simplify.\n    (* GenUpdate_noV_oc_k is inlined in first, GenUpdate_rb_intermediate_oc_v in second *)\n(*    Print GenUpdate_noV_oc_k.*)\n(*    Print GenUpdate_rb_intermediate_oc.*) (* like the above but with no k sampling *)\n\n    (* Skip the lined-up a-sampling (inline k-sampling) and k-sampling *)\n    fcf_skip_eq; kv_exist.\n    simplify. fcf_skip; kv_exist.\n\n    (* Gen_loop_oc ~ Gen_loop_rb_intermediate *)\n    { instantiate (1 := (fun x y => fst x = y)).\n      revert b0 a state. induction x as [ | x']; intros.\n      - simplify. fcf_spec_ret.\n      - simplify. unfold rb_oracle. simplify. fold rb_oracle.\n        fcf_skip_eq. fcf_skip. simplify. fcf_spec_ret.\n    } \n    simpl in H1. destruct b3. inversion H1. subst.\n    simplify. fcf_skip; kv_exist.\n\n(* separate lemma for induction on rest of list, show calls > i *)\n    { instantiate (1 := (fun x y => fst x = fst y)).\n      apply Oi_ocs_eq_calls_gt_i; omega. }\n    { simplify. simpl in H4. destruct p. inversion H4. subst. fcf_spec_ret. }\nQed.\n\nLtac rewrite_l := apply comp_spec_symm; eapply comp_spec_eq_trans_l.\n  \n(* this isn't actually used in the below thm because i can't get it to unify, so i inlined the proof *)\nLemma k_loop_swap_after : forall (i : nat) (xs : list nat)\n                                 (state : list (Blist * Bvector eta)) (x : nat) (calls : nat) (k : Bvector eta),\n   comp_spec eq\n     (k0 <-$ RndK;\n      a <-$\n      (z0 <-$\n       (z0 <-$\n        (z0 <-$ (x0 <-$ { 0 , 1 }^eta; ret (x0, state));\n         [z, s']<-2 z0;\n         z1 <-$ (x0 <-$ Gen_loop_rb_intermediate k0 z x; ret (x0, s'));\n         [z2, s'0]<-2 z1;\n         ([bits, v'']<-2 z2; $ ret (bits, (k0, v'')))\n           (list (Blist * Bvector eta)) (list_EqDec (pair_EqDec eqdbl eqdbv))\n           rb_oracle s'0);\n        [z, s']<-2 z0;\n        ([bits, state']<-2 z; $ ret (bits, (S calls, state')))\n          (list (Blist * Bvector eta)) (list_EqDec (pair_EqDec eqdbl eqdbv))\n          rb_oracle s');\n       [z, s']<-2 z0;\n       ([res, state']<-2 z;\n        z1 <--$\n        oracleCompMap_inner\n          (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n             (pair_EqDec nat_EqDec eqDecState))\n          (list_EqDec (list_EqDec eqdbv)) (Oi_oc''' i) state' xs;\n        [resList, state'']<-2 z1; $ ret (res :: resList, state''))\n         (list (Blist * Bvector eta)) (list_EqDec (pair_EqDec eqdbl eqdbv))\n         rb_oracle s'); ret a)\n\n     (v' <-$ {0,1}^eta;\n      res <-$ Gen_loop_rb_intermediate k v' x; (* k0,v0 are swapped after, so just use any k,v in env *)\n      k0 <-$ RndK;\n      [bits, last_bv] <-2 res;\n      a <-$\n        (oracleCompMap_inner\n           (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n                       (pair_EqDec nat_EqDec eqDecState))\n           (list_EqDec (list_EqDec eqdbv)) (Oi_oc''' i) (S calls, (k0, last_bv)) xs)\n        (list (Blist * Bvector eta)) (list_EqDec (pair_EqDec eqdbl eqdbv))\n        rb_oracle state;\n      a0 <-$\n         ([z, s']<-2 a;\n          ([resList, state'']<-2 z; $ ret (bits :: resList, state''))\n            (list (Blist * Bvector eta)) (list_EqDec (pair_EqDec eqdbl eqdbv))\n            rb_oracle s'); ret a0).\nProof.\n  intros.\n  rewrite_l.\n  instantiate (1 :=\n    (inter <-$ (v' <-$ { 0 , 1 }^eta;\n      res <-$ Gen_loop_rb_intermediate k v' x;\n      ret (v', res));\n      k0 <-$ RndK;\n      [v', res] <-2 inter;\n      [bits, last_bv]<-2 res;\n      a <-$\n      (oracleCompMap_inner\n         (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n            (pair_EqDec nat_EqDec eqDecState))\n         (list_EqDec (list_EqDec eqdbv)) (Oi_oc''' i)\n         (S calls, (k0, last_bv)) xs) (list (Blist * Bvector eta))\n        (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state;\n      a0 <-$\n      ([z, s']<-2 a;\n       ([resList, state'']<-2 z; $ ret (bits :: resList, state''))\n         (list (Blist * Bvector eta)) (list_EqDec (pair_EqDec eqdbl eqdbv))\n         rb_oracle s'); ret a0)).\n  { simplify. fcf_skip_eq; kv_exist. simplify. fcf_skip_eq; kv_exist. simplify. fcf_skip_eq; kv_exist. }\n  apply comp_spec_symm.\n\n  rewrite_l.\n  instantiate (1 :=\n      k0 <-$ RndK;\n     (inter <-$\n      (v' <-$ { 0 , 1 }^eta;\n       res <-$ Gen_loop_rb_intermediate k v' x; ret (v', res));\n      (let '(_, (bits, last_bv)) := inter in\n            a <-$\n            (oracleCompMap_inner\n               (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n                  (pair_EqDec nat_EqDec eqDecState))\n               (list_EqDec (list_EqDec eqdbv)) (Oi_oc''' i)\n               (S calls, (k0, last_bv)) xs) (list (Blist * Bvector eta))\n              (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state;\n            a0 <-$\n            ([z, s']<-2 a;\n             ([resList, state'']<-2 z; $ ret (bits :: resList, state''))\n               (list (Blist * Bvector eta))\n               (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle s'); \n            ret a0))).\n  { eapply comp_spec_eq_swap. }\n\n  apply comp_spec_symm.\n\n  (* now k is at the top of both *)\n  fcf_skip_eq; kv_exist.\n  simplify.\n  fcf_skip_eq; kv_exist.\n  simplify.\n  fcf_skip_eq; kv_exist.\n\n  { revert a a0 k.\n    induction x as [ | x']; intros; simpl.\n    - fcf_spec_ret. \n    - fcf_skip_eq. fcf_skip_eq. }\n\n  simplify.\n  fcf_skip_eq; kv_exist.\nQed.\n\n(* Oi_oc'' to Oi_oc''', third (and last) case: calls <= i and i != 0 *)\n(* states same or different? going to have same so i can do eq (diff might let IH apply) *)\nLemma oracleCompMap_rb_instantiate_outer_i_neq_0 : forall l calls i state,\n    calls <= i ->\n    beq_nat i 0 = false ->                                        (* separate theorem *)\n    comp_spec (fun x y => fst (fst x) = fst (fst y)) (* weaker precondition *)\n              ([k, v] <-$2 Instantiate;\n               a <-$\n                 (oracleCompMap_inner\n                    (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n                                (pair_EqDec nat_EqDec eqDecState))\n                    (list_EqDec (list_EqDec eqdbv)) (Oi_oc'' i)\n                    (* note Oi_oc': need to rewrite w first theorem in outer *)\n                    (calls, (k, v)) l) (list (Blist * Bvector eta))\n                 (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state;\n               ret a)\n              ([k, v] <-$2 Instantiate;\n               k <-$ RndK;\n               a <-$\n                 (oracleCompMap_inner\n                    (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n                                (pair_EqDec nat_EqDec eqDecState))\n                    (list_EqDec (list_EqDec eqdbv)) (Oi_oc''' i) \n                    (calls, (k, v)) l) (list (Blist * Bvector eta))\n                 (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state;\n               ret a).\nProof.\n  intros.\n  rename H0 into i_neq_0.\n  fcf_skip_eq; kv_exist. simplify.\n  (* fcf_irr_r. wfi. simplify. *)\n  (* calls < i: kv don't matter *)\n  (* calls = i: there's an extra instantiate inside *)\n\n  rename b into k. rename b0 into v.\n  revert calls i state H k v i_neq_0.\n  induction l as [ | x xs]; intros. (* there isn't an induction in the i_eq_0 version, only a destruct *)\n  (* base case *)\n  - fcf_irr_r. unfold RndK. fcf_well_formed. simplify. fcf_spec_ret.\n\n  (* induction: l = x :: xs *)\n  - assert (H_ilen : calls < i \\/ calls = i) by omega.\n    destruct H_ilen.\n    clear H.\n\n    (* calls < i: apply induction hypothesis *)\n    (* maybe i don't need induction? induct separately on inside *)\n    (* this case might be hard because I need to \"push\" the extra instantiate on the right inside *)\n\n    + Opaque Oi_oc''. Opaque Oi_oc'''.\n      simplify. Transparent Oi_oc''. simplify.\n      (* intuitively, what should the calls < i proof look like? *)\n      destruct (lt_dec calls i). Focus 2. omega.\n\n      (* calls < i *)\n      Transparent Oi_oc'''. simplify. destruct (lt_dec calls i). Focus 2. omega.\n      simplify.\n\n      rewrite_r.\n      (* eapply k_loop_swap_after. *)\n      instantiate (1 :=      (v' <-$ {0,1}^eta;\n      res <-$ Gen_loop_rb_intermediate k v' x; (* k0,v0 are swapped after, so just use any k,v in env *)\n      k0 <-$ RndK;\n      [bits, last_bv] <-2 res;\n      a <-$\n        (oracleCompMap_inner\n           (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n                       (pair_EqDec nat_EqDec eqDecState))\n           (list_EqDec (list_EqDec eqdbv)) (Oi_oc''' i) (S calls, (k0, last_bv)) xs)\n        (list (Blist * Bvector eta)) (list_EqDec (pair_EqDec eqdbl eqdbv))\n        rb_oracle state;\n      a0 <-$\n         ([z, s']<-2 a;\n          ([resList, state'']<-2 z; $ ret (bits :: resList, state''))\n            (list (Blist * Bvector eta)) (list_EqDec (pair_EqDec eqdbl eqdbv))\n            rb_oracle s'); ret a0)).\n\n      (* eapply k_loop_swap_after. *)\n      (* pose proof (k_loop_swap_after i xs state x calls k) as k_loop_swap_after_init. *)\n      (* apply k_loop_swap_after_init. *)\n\n      (* ------ *)\n      (* INLINE k_loop_swap_after PROOF (because eapply above can't unify... *)\n\n      {\n        rewrite_l.\n        instantiate (1 :=\n                       (inter <-$ (v' <-$ { 0 , 1 }^eta;\n                                   res <-$ Gen_loop_rb_intermediate k v' x;\n                                   ret (v', res));\n                        k0 <-$ RndK;\n                        [v', res] <-2 inter;\n                        [bits, last_bv]<-2 res;\n                        a <-$\n                          (oracleCompMap_inner\n                             (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n                                         (pair_EqDec nat_EqDec eqDecState))\n                             (list_EqDec (list_EqDec eqdbv)) (Oi_oc''' i)\n                             (S calls, (k0, last_bv)) xs) (list (Blist * Bvector eta))\n                          (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state;\n                        a0 <-$\n                           ([z, s']<-2 a;\n                            ([resList, state'']<-2 z; $ ret (bits :: resList, state''))\n                              (list (Blist * Bvector eta)) (list_EqDec (pair_EqDec eqdbl eqdbv))\n                              rb_oracle s'); ret a0)).\n        { simplify. fcf_skip_eq; kv_exist. simplify. fcf_skip_eq; kv_exist. simplify. fcf_skip_eq; kv_exist. }\n        apply comp_spec_symm.\n\n        rewrite_l.\n        instantiate (1 :=\n                       k0 <-$ RndK;\n                     (inter <-$\n                            (v' <-$ { 0 , 1 }^eta;\n                             res <-$ Gen_loop_rb_intermediate k v' x; ret (v', res));\n                      (let '(_, (bits, last_bv)) := inter in\n                       a <-$\n                         (oracleCompMap_inner\n                            (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n                                        (pair_EqDec nat_EqDec eqDecState))\n                            (list_EqDec (list_EqDec eqdbv)) (Oi_oc''' i)\n                            (S calls, (k0, last_bv)) xs) (list (Blist * Bvector eta))\n                         (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state;\n                       a0 <-$\n                          ([z, s']<-2 a;\n                           ([resList, state'']<-2 z; $ ret (bits :: resList, state''))\n                             (list (Blist * Bvector eta))\n                             (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle s'); \n                       ret a0))).\n        { eapply comp_spec_eq_swap. }\n\n        apply comp_spec_symm.\n\n        (* now k is at the top of both *)\n        fcf_skip_eq; kv_exist.\n        simplify.\n        fcf_skip_eq; kv_exist.\n        simplify.\n        fcf_skip_eq; kv_exist.\n\n        { revert a a0 k.\n          induction x as [ | x']; intros; simpl.\n          - fcf_spec_ret. \n          - fcf_skip_eq. fcf_skip_eq. }\n\n        simplify.\n        fcf_skip_eq; kv_exist.\n        simplify.\n        fcf_spec_ret.\n      }\n\n      (* END SWAP PROOF *)\n      (* ----- *)\n\n      apply comp_spec_symm.\n      fcf_skip_eq; kv_exist.\n      simplify.\n\n      (* get the right side 2 lines together to apply IH *)\n      fcf_skip_eq; kv_exist.\n      simplify.\n      eapply comp_spec_eq_trans_r.\n      Focus 2.\n\n      instantiate (1 :=\n                     (* Check ( *)\n                         (res <-$ (k0 <-$ RndK;\n                                       a0 <-$\n                                         (oracleCompMap_inner\n                                            (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n                                                        (pair_EqDec nat_EqDec eqDecState))\n                                            (list_EqDec (list_EqDec eqdbv)) (Oi_oc''' i) \n                                            (S calls, (k0, b)) xs) (list (Blist * Bvector eta))\n                                         (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state;\n                                       ret a0\n                                      );\n                              a2 <-$\n                                 ([z, s']<-2 res;\n                                  ([resList, state'']<-2 z; $ ret (a1 :: resList, state''))\n                                    (list (Blist * Bvector eta)) (list_EqDec (pair_EqDec eqdbl eqdbv))\n                                    rb_oracle s'); ret a2)).\n       simplify. fcf_skip; kv_exist. simplify. fcf_skip_eq; kv_exist. \n\n      fcf_skip; kv_exist.\n      fcf_ident_expand_l.\n\n      instantiate (1 := (fun\n              x0\n               y : list (list (Bvector eta)) * (nat * KV) *\n                   list (Blist * Bvector eta) => fst (fst x0) = fst (fst y))).\n      assert (Hcalls : S calls <= i) by omega.\n      pose proof (IHxs (S calls) i state Hcalls k b i_neq_0) as IHxs_inst.\n      apply IHxs_inst. \n\n      simpl in H2. destruct b1. destruct p. simpl in *. subst. simplify.\n      fcf_spec_ret.\n      \n    (* ------------------ *)\n\n    (* this just seems to work out of the box after changes *)\n    (* calls = i *)\n    + Opaque Oi_oc''. Opaque Oi_oc'''.\n      simplify.\n      (* this doesn't seem to be true. there's an extra instantiate in Oi_oc'' *)\n      (* fcf_irr_l. wfi. simplify. *)\n      Transparent Oi_oc''. Transparent Oi_oc'''.\n      simpl.\n      assert (beq_nat calls i = true).\n      { apply Nat.eqb_eq. auto. }\n      rewrite H1.\n      destruct (lt_dec calls i). omega. (* we have calls = i *)\n      (* need a diff oracle.\nin i != 0: in the latter, there's an extra instantiate in front and no kv updating, so everything's in sync\nin i = 0: in the former, there's only k updating inside. in the latter, there's an extra instantiate in front (k,v). so the v's are not in sync *)\n      (* separate theorem for i = 0? seems easier -- destruct -- on first call, k update, then afterward, easy induction? \nthat would work but would that still apply to prove the top-level theorem??\n       *)\n      rewrite <- H0 in i_neq_0.\n      destruct (beq_nat calls 0).\n      { inversion i_neq_0. }\n\n      (* i != 0 *)\n      { (*Print GenUpdate_oc_instantiate.*)\n        unfold Instantiate. simplify.\n        (* now we have instantiate at the head of both, we can skip it, and the kv going into the loop  *)\n        fcf_skip_eq; kv_exist.\n        simplify. fcf_skip_eq; kv_exist. simplify.\n        (* in fact only the k-update matters?? not true, we need the v's going in to be the same *) \n        (* loops are related *)\n        fcf_skip; kv_exist.\n        instantiate (1 := (fun x y => fst x = y)).\n        (* both start with same v and x so postcondition holds *)\n        { revert a a0 state. induction x as [ | x']; intros; simpl.\n          - simplify. fcf_spec_ret.\n          - unfold rb_oracle. simplify. fold rb_oracle. fcf_skip_eq.\n            fcf_skip. simplify. fcf_spec_ret.\n        }\n\n        simpl in H3. destruct b1. inversion H3. subst.\n        simplify.\n        fcf_skip; kv_exist.\n        instantiate (1 := (fun x y => fst x = fst y)).\n        apply Oi_ocs_eq_calls_gt_i. omega.\n        (* kv same AND calls > i! *)\n        (* we're past RB and oracle, just PRFs here means oracles the same *)\n        (* another induction w different states *)\n\n        simplify. fcf_spec_ret. simpl in H6. destruct p. inversion H6. subst.\n        simpl. reflexivity. }\nQed.\n\n(* the oracleMap using Oi_prg (original computation) is equivalent to oracleCompMap using Oi_oc''' (the final one) \nfor the second case of calls = i (leading to calls > i) *)\n(* did this proof work? why did it break? *)\nLemma oracleMap_oracleCompMap_equiv_modified_calls_gt_i : forall l k v i state calls init,\n   calls = i ->\n   Forall (fun n => n > 0) l ->\n   comp_spec\n     (fun (x : list (list (Bvector eta)) * (nat * KV))\n        (y : list (list (Bvector eta)) * (nat * KV) *\n             list (Blist * Bvector eta)) => x = fst y)\n     (compFold\n        (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n           (pair_EqDec nat_EqDec eqDecState))\n        (fun (acc : list (list (Bvector eta)) * (nat * KV)) (d : nat) =>\n         [rs, s]<-2 acc;\n         z <-$ Oi_prg (S i) s d; [r, s0]<-2 z; ret (rs ++ r :: nil, s0))\n        (init, (calls, (k, v))) l)\n     (z <-$\n      (oracleCompMap_inner\n         (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n            (pair_EqDec nat_EqDec eqDecState))\n         (list_EqDec (list_EqDec eqdbv)) (Oi_oc''' i) \n         (calls, (k, v)) l) (list (Blist * Bvector eta))\n        (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state;\n      [bits, nkv, state']<-3 z; ret (init ++ bits, nkv, state')).\nProof.\n  (* modeled off Gi_normal_rb_eq_calls_eq_i *)\n  Opaque Oi_prg. Opaque Oi_oc'''.\n  destruct l as [ | x xs]; intros; rename H0 into blocks_neq_0.\n  (* why am I destructing l instead of inducting? *)\n\n  - simplify. fcf_spec_ret. simpl. repeat (split; auto).\n    rewrite app_nil_r; reflexivity.\n  -\n    simplify.\n    eapply comp_spec_seq.\n    (* avoid fcf_skip, it will subst calls = i, which i don't want to link. TODO why? *)\n\n    apply (nil, (0, (oneVector eta, oneVector eta))).\n    apply ((nil, (0, (oneVector eta, oneVector eta)), nil)).\n\n    (* when calls = i, one is Gen_loop_rb and the other is Gen_loop_oc using the rb_oracle *)\n    instantiate (1 := (fun c d => bitsVEq c d\n                                  /\\ fst (snd c) = S i /\\ fst (snd (fst d)) = S i\n                                  (* changed the postcondition; the keys now remain the same *)\n                                  /\\ fst (snd (snd c)) = fst (snd (snd (fst d))) )). (* TODO deleted =k, is that ok? *)\n    (* 1 call: calls = i. why do i have to do the calls = i case again? shouldn't the other theorem cover it? *)\n    { subst.\n      Transparent Oi_prg. Transparent Oi_oc'''.\n      unfold Oi_prg. unfold Oi_oc'''.\n      simplify.\n      (* casework on `i = 0`, `calls = i` and `calls > i` *)\n      destruct (lt_dec i i). omega. \n      clear n.\n      destruct (lt_dec i (S i)).\n      Focus 2. omega. clear l.\n      assert (idec : i = 0 \\/ i <> 0) by omega.\n      destruct idec as [ itrue | ifalse].\n      apply beq_nat_true_iff in itrue.\n      rewrite itrue.\n      (* i = 0? shouldn't matter whether the v is updated an additional time in the latter *)\n      (* TODO wait, i might need to pass the i=0 and i!=0 hypotheses down here? *)\n      -\n        fcf_skip; kv_exist.\n        instantiate (1 := (fun x y => fst x = fst (fst y) /\\ snd (snd x) = snd (snd (fst y))\n                    /\\ fst (snd x) = fst (snd (fst y)) = k)).\n        (* can we weaken the postcondition? *)\n        unfold GenUpdate_rb_intermediate. unfold GenUpdate_rb_intermediate_oc_noV.\n        simplify.\n        fcf_irr_l.\n        fcf_skip_eq; kv_exist.\n        (* TODO factor out *)\n        { \n          revert a k H0.\n          induction x as [ | x']; intros; simplify.\n          - (* using hypothesis that number of blocks is not 0 *)\n            apply Forall_inv in blocks_neq_0. omega.\n          - fcf_skip_eq.\n        }\n        (* hmm this saves the v, meaning the v gets updated... *)\n        (* instantiate (1 := (fun x y => x = fst y)). *)\n        (* unfold Gen_loop_rb. unfold Gen_loop_rb_intermediate. *)\n        simplify. fcf_spec_ret.\n        simpl in *. breakdown H1. simplify. fcf_spec_ret.\n        destruct b. simpl in *. destruct k0. simpl in *. subst. auto.\n      -\n        (* presumably now `i <> 0`? what assumptions hold here? *)\n        assert (H_i_eq : beq_nat i i = true) by apply Nat.eqb_refl.\n        rewrite H_i_eq.\n        apply beq_nat_false_iff in ifalse.\n        rewrite ifalse. simplify.\n        fcf_skip; kv_exist.\n        simplify.\n        fcf_skip_eq; kv_exist.\n        simplify. fcf_spec_ret. simpl. auto.\n    }\n\n    (* rest of calls -- induct on the new list *)\n    { intros.\n      (* don't do subst--there's an annoying link between calls and `i` that i don't want in my IH *)\n      simplify. simpl in *. destruct p0. destruct p. destruct k1. simpl in *. destruct k0. simpl in H2. decompose [and] H2.\n      rewrite H5. rewrite H3. rewrite H7. rewrite H9.\n      clear H5 H3 H7 H9.\n      clear H2 H1 H0.\n\n      assert (n_eq : n = n0) by omega.\n      rewrite <- H in H6.\n      rewrite <- H in H4.\n      rewrite n_eq.\n      rename n0 into calls'.\n      assert (H_calls : calls' > i) by omega.\n\n      clear k v.\n      rename b1 into k. rename b2 into v. rename l0 into rb_state.\n      clear H6 n_eq H4 H. (* i cleared a lot of hypotheses here. might need them later? *)\n      revert init k v rb_state i calls' H_calls l1.\n      \n      induction xs as [ | x' xs']; intros.\n\n      (* xs = nil *)\n      + simplify. fcf_spec_ret. \n      (* xs = x' :: xs', use IH *)\n      + simplify.\n        (*  \"(list (Bvector eta) * KV * list (Blist * Bvector eta))%type\" with\n \"(list (Bvector eta) * KV)%type\". *)\n        fcf_skip; kv_exist.\n\n        (* one call with calls > i (calls = S i) *)\n        (* PRF oracle only *)\n        clear calls. rename calls' into calls.\n\n        instantiate (1 := (fun c d => c = fst d)).\n\n        (* instantiate (1 := (fun c d => bitsVEq c d *)\n        (*                               (* calls incremented by one *) *)\n        (*                               /\\ fst (snd c) = S calls *)\n        (*                               /\\ fst (snd (fst d)) = S calls *)\n        (*                               (* KV equal *) *)\n        (*                               /\\ fst (snd (snd c)) = fst (snd (snd (fst d))))). *)\n        {\n          Transparent Oi_prg. Transparent Oi_oc'''.\n          (* unfold Oi_prg. unfold Oi_oc'''. *)\n          (* simplify. *)\n          destruct (lt_dec calls (S i)). omega. (* calls > i, so ~(calls < S i) *)\n          destruct (lt_dec calls i). omega.     (* calls > i, so ~(calls < i) *)\n          assert (beq_nat calls 0 = false) as calls_neq_0.\n          { apply Nat.eqb_neq. omega. }\n          rewrite calls_neq_0. Opaque GenUpdate.\n          assert (beq_nat calls i = false) as calls_neq_i.\n          { apply Nat.eqb_neq. omega. }\n          rewrite calls_neq_i.\n          Transparent GenUpdate.\n          simplify.\n          fcf_spec_ret. \n          Opaque Oi_prg. Opaque Oi_oc'''.\n        }\n\n        simpl in H1. destruct b2. destruct p. simpl in *. inversion H1. subst.\n        simplify.\n        \n        eapply comp_spec_eq_trans_r.\n        destruct k0.\n        eapply IHxs'. clear IHxs'.\n        (* prove Forall on smaller list--though where is the middle element? *)\n        { inversion blocks_neq_0. subst.\n        inversion H5. subst.\n        apply Forall_cons; auto. }\n        \n        omega. \n        \n        (* now prove oracleCompMap_inner's eq *)\n        { fcf_skip_eq.\n          simplify. fcf_spec_ret.\n          f_equal. f_equal.\n          rewrite <- app_cons_eq.\n          reflexivity.\n        }\n    } \nQed.\n\n(* TODO have to expand this with the fold and acc/++ *)\n(* first case of the main proof (and the hardest case / main lemma): \nthe original computation (oracleMap using Oi_prg) is equivalent to oracleCompMap Oi_oc'''\nbut only for the first case (calls <= i). is this induct, THEN destruct?\n(TODO check the postcondition!) *)\nLemma oracleMap_oracleCompMap_equiv_modified : forall l k v i state calls init,\n    calls <= i ->\n    Forall (fun n => n > 0) l ->\n    comp_spec\n      (fun (x : list (list (Bvector eta)) * (nat * KV))\n           (y : list (list (Bvector eta)) * (nat * KV) *\n                list (Blist * Bvector eta)) => x = fst y)\n      (compFold\n         (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n                     (pair_EqDec nat_EqDec eqDecState))\n         (fun (acc : list (list (Bvector eta)) * (nat * KV)) (d : nat) =>\n            [rs, s]<-2 acc;\n          z <-$ Oi_prg (S i) s d; [r, s0]<-2 z; ret (rs ++ r :: nil, s0))\n         (init, (calls, (k,v))) l)\n      ([acc', state'] <-$2 ((oracleCompMap_inner\n                               (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n                                           (pair_EqDec nat_EqDec eqDecState))\n                               (list_EqDec (list_EqDec eqdbv)) (Oi_oc''' i) \n                               (calls, (k, v)) l) (list (Blist * Bvector eta))\n                                                  (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle state);\n       [bits, nkv] <-2 acc';\n       ret (init ++ bits, nkv, state')).\nProof.\n  (* modeled off Gi_normal_rb_eq_compspec *)\n  (* induct, then destruct *)\n  induction l as [ | x xs]; intros; rename H0 into blocks_neq_0.\n  - simplify. fcf_spec_ret. simpl. rewrite app_nil_r. repeat (split; auto).\n  - assert (H_ilen : calls < i \\/ calls = i) by omega.\n    destruct H_ilen.\n    clear H.\n\n    (* calls < i *)\n    Opaque Oi_prg. Opaque Oi_oc'''.\n    simplify.\n    fcf_skip; kv_exist.\n    (* case: call on first element of list *)\n    (* strengthen postcondition so we can prove calls < i -> S calls <= i to apply IHxs *)\n    (* also strengthen it again because if calls < i then the keys must still be the same *)\n    instantiate (1 := (fun c d => bitsVEq c d\n                                  (* calls incremented by 1 *)\n                                  /\\ fst (snd c) = S calls /\\ fst (snd (fst d)) = S calls\n                                  (* output keys are the input keys *)\n                                  /\\ fst (snd (snd c)) = k\n                                  /\\ fst (snd (snd (fst d))) = k)).\n    (* includes calls *)\n    (* one call with linked keys TODO *)\n    {\n      Transparent Oi_prg. Transparent Oi_oc'''.\n      simpl.\n      destruct (lt_dec calls i).\n      Focus 2. omega.         (* contradiction *)\n      clear l.                (* calls < i *)\n      assert (H_calls_lt : calls < S i) by omega.\n      destruct (lt_dec calls (S i)).\n      Focus 2. omega. \n      fcf_skip; kv_exist.   (* GenUpdate_rb_intermediate(_oc) *)\n      (* postcondition: output keys are unchanged from input *)\n      instantiate (1 := (fun x y => x = fst y /\\ fst (snd x) = fst (snd (fst y)) = k)).\n      unfold GenUpdate_rb_intermediate.\n      simplify.\n      fcf_skip_eq; kv_exist.\n      simplify.\n      fcf_skip_eq; kv_exist.\n      simplify.\n      fcf_spec_ret.\n\n      simpl in *. inversion H2. destruct b0. simpl in *. destruct b. destruct p. simpl in *. destruct k0. simpl in *.\n      inversion H4. inversion H3. subst. simplify. fcf_spec_ret. simpl. auto.\n      } \n\n\n    (* use IH *)\n    { simpl in H2. destruct b0. destruct b. destruct p. destruct p. destruct k0. simpl in *.\n      breakdown H2. \n      simplify.\n\n      eapply comp_spec_eq_trans_r.\n      eapply IHxs. omega.\n      inversion blocks_neq_0; subst; auto.\n\n      instantiate (1 := l).\n      (* now prove oracleCompMap_inner's eq *)\n      { fcf_skip_eq; kv_exist.\n        simplify.\n        fcf_spec_ret. f_equal. f_equal. rewrite <- app_assoc. f_equal.\n      }\n    } \n    \n    (* calls = i *)\n    + clear IHxs.\n      clear H.\n      apply oracleMap_oracleCompMap_equiv_modified_calls_gt_i; auto.\n      (* apply Gi_normal_rb_eq_calls_eq_i; omega. *) \nQed.\n\nLemma maxBlocksAndCalls_all_nonzero : Forall (fun n : nat => n > 0) maxCallsAndBlocks.\nProof.\n  clear H_numCalls.\n  unfold maxCallsAndBlocks.\n  induction numCalls as [ | calls'].\n  - simpl. apply Forall_nil.\n  - simpl. apply Forall_cons. apply H_blocksPerCall. apply IHcalls'.\nQed.   \n\nTransparent Oi_prg.\nLemma Gi_normal_rb_eq : forall (i : nat),\n    Pr[Gi_prg (S i)] == Pr[Gi_rb i].\nProof.\n  intros.\n  unfold Gi_prg.\n  unfold Gi_rb.\n  unfold PRF_Adversary.\n  unfold oracleCompMap_outer.\n  fcf_to_prhl_eq.\n  simplify.\n\n  (* apply first theorem *)\n  rewrite_r.\n  (* replace Oi_oc' with Oi_oc'' *)\n  instantiate\n    (1 :=\n         (a <-$ Instantiate;\n      a0 <-$ ret (a, nil);\n      a1 <-$\n      ([z, s']<-2 a0;\n       ([k, v]<-2 z;\n        z0 <--$\n        oracleCompMap_inner\n          (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n             (pair_EqDec nat_EqDec eqDecState))\n          (list_EqDec (list_EqDec eqdbv)) (Oi_oc'' i) \n          (0, (k, v)) maxCallsAndBlocks; [bits, _]<-2 z0; $ ret bits)\n         (list (Blist * Bvector eta)) (list_EqDec (pair_EqDec eqdbl eqdbv))\n         rb_oracle s');\n      z <-$ ([z, s']<-2 a1; x <-$ A z; ret (x, s')); [b, _]<-2 z; ret b)). \n  { fcf_skip_eq. simplify. fcf_skip. apply oracleCompMap_rb_instantiate_inner.\n    simplify. simpl in *. destruct p. inversion H1. subst. fcf_skip_eq.\n    simplify. fcf_reflexivity. }\n\n  (* casework on i, apply second or third theorems *)\n  flip. \n  assert (i_cases: beq_nat i 0 = true \\/ beq_nat i 0 = false).\n  { destruct i; auto. }\n  destruct i_cases.\n\n  (* i = 0 *)\n  - rewrite_r.                  (* replace Oi_oc'' with Oi_oc''' *)\n    instantiate\n      (1 :=\n         ([k,v] <-$2 Instantiate;\n          k <-$ RndK;\n          a0 <-$ ret ((k,v), nil);\n          a1 <-$\n             ([z, s']<-2 a0;\n              ([k, v]<-2 z;\n               z0 <--$\n                  oracleCompMap_inner\n                  (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n                              (pair_EqDec nat_EqDec eqDecState))\n                  (list_EqDec (list_EqDec eqdbv)) (Oi_oc''' i) (* note triple prime *)\n                  (0, (k, v)) maxCallsAndBlocks; [bits, _]<-2 z0; $ ret bits)\n                (list (Blist * Bvector eta)) (list_EqDec (pair_EqDec eqdbl eqdbv))\n                rb_oracle s');\n          z <-$ ([z, s']<-2 a1; x <-$ A z; ret (x, s')); [b, _]<-2 z; ret b)).\n    {\n    (* need to isolate first 4 lines of each, rewrite with each, prove each equiv, then rewrite with oracleCompMap_rb_instantiate_outer_i_eq_0 *)\n      flip. rewrite_r.\n      instantiate\n        (1 :=\n           (top <-$\n                ([k,v] <-$2 Instantiate;\n                  a <-$ (oracleCompMap_inner\n                         (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n                                     (pair_EqDec nat_EqDec eqDecState))\n                         (list_EqDec (list_EqDec eqdbv)) (Oi_oc'' i) \n                         (0, (k, v)) maxCallsAndBlocks) \n                       (list (Blist * Bvector eta)) (list_EqDec (pair_EqDec eqdbl eqdbv))\n                       rb_oracle nil;\n                 ret a);\n            z <-$ ([bnkv, s']<-2 top; [bits, _] <-2 bnkv; x <-$ A bits; ret (x, s')); [b, _]<-2 z; ret b)).\n      { prog_equiv. }\n      rewrite_r.\n      instantiate\n        (1 :=\n           (top <-$\n                ([k,v] <-$2 Instantiate;\n                 k <-$ RndK;\n                 a <-$ (oracleCompMap_inner\n                         (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n                                     (pair_EqDec nat_EqDec eqDecState))\n                         (list_EqDec (list_EqDec eqdbv)) (Oi_oc''' i) \n                         (0, (k, v)) maxCallsAndBlocks\n                       (list (Blist * Bvector eta)) (list_EqDec (pair_EqDec eqdbl eqdbv))\n                       rb_oracle nil);\n                 ret a);\n                z <-$ ([bnkv, s']<-2 top; [bits, _] <-2 bnkv; x <-$ A bits; ret (x, s')); [b, _]<-2 z; ret b)).\n      { prog_equiv. }\n      fcf_skip. flip. apply oracleCompMap_rb_instantiate_outer_i_eq_0. auto.\n\n      simpl in H2. destruct b0. destruct a. simpl in *. destruct p. simpl in *. subst.\n      simplify. fcf_skip_eq. simplify. fcf_spec_ret.\n\n      simpl in H2. destruct p. destruct l1. simpl in *. rewrite H2.\n      simplify. fcf_skip_eq. simplify. fcf_spec_ret.\n\n      simpl in H2. rewrite H2.\n      simplify. fcf_skip_eq. simplify. fcf_spec_ret.\n    } \n    flip.\n    unfold Instantiate. simplify.\n    fcf_irr_r. unfold RndK. fcf_well_formed.\n    simplify.\n    rewrite_r.\n    instantiate\n      (1 :=\n         (k0 <-$ RndK;\n          a <-$ RndV;\n          z1 <-$ ret (b, a);\n          [_, v]<-2 z1;\n          a0 <-$ ret (k0, v, nil);\n          a1 <-$\n             ([z, s']<-2 a0;\n              ([k1, v0]<-2 z;\n               z0 <--$\n                  oracleCompMap_inner\n                  (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n                              (pair_EqDec nat_EqDec eqDecState))\n                  (list_EqDec (list_EqDec eqdbv)) (Oi_oc''' i) \n                  (0, (k1, v0)) maxCallsAndBlocks; [bits, _]<-2 z0; $ ret bits)\n                (list (Blist * Bvector eta)) (list_EqDec (pair_EqDec eqdbl eqdbv))\n                rb_oracle s');\n          z <-$ ([z, s']<-2 a1; x <-$ A z; ret (x, s')); [b0, _]<-2 z; ret b0)).\n    { fcf_swap fcf_right. prog_equiv. }\n    flip.\n    prog_equiv.\n    (* factor out lemma and apply it to both cases *)\n    fcf_skip. instantiate (1 := (fun x y => x = fst y)).\n    (* they have the same k and v, former is S i, latter is i without updates in RB, so i hope this works! *)\n    unfold oracleMap.\n    pose proof oracleMap_oracleCompMap_equiv_modified.\n    eapply comp_spec_eq_trans_r. apply H1. omega.\n    apply maxBlocksAndCalls_all_nonzero.\n\n    instantiate (1 := nil). fcf_ident_expand_r. fcf_skip_eq; kv_exist.\n    simpl. fcf_spec_ret.\n\n    simpl in H3. destruct b0. repeat destruct p. simpl in *. inversion H3. subst.\n    fcf_ident_expand_l. simplify. prog_equiv. fcf_spec_ret.\n  (* looks like the i=0 case is fully proved *)\n\n  (* i != 0 *)\n  - rewrite_r.\n    instantiate\n      (1 :=\n         ([k,v] <-$2 Instantiate;\n          (* [k,v] <-$2 Instantiate; *)\n          k <-$ RndK;\n          a0 <-$ ret ((k,v), nil);\n          a1 <-$\n             ([z, s']<-2 a0;\n              ([k, v]<-2 z;\n               z0 <--$\n                  oracleCompMap_inner\n                  (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n                              (pair_EqDec nat_EqDec eqDecState))\n                  (list_EqDec (list_EqDec eqdbv)) (Oi_oc''' i) (* note triple prime *)\n                  (0, (k, v)) maxCallsAndBlocks; [bits, _]<-2 z0; $ ret bits)\n                (list (Blist * Bvector eta)) (list_EqDec (pair_EqDec eqdbl eqdbv))\n                rb_oracle s');\n          z <-$ ([z, s']<-2 a1; x <-$ A z; ret (x, s')); [b, _]<-2 z; ret b)).\n    {\n    (* need to isolate first 4 lines of each, rewrite with each, prove each equiv, then rewrite with oracleCompMap_rb_instantiate_outer_i_eq_0 *)\n      flip. rewrite_r.\n      instantiate\n        (1 :=\n           (top <-$\n                ([k,v] <-$2 Instantiate;\n                  a <-$ (oracleCompMap_inner\n                         (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n                                     (pair_EqDec nat_EqDec eqDecState))\n                         (list_EqDec (list_EqDec eqdbv)) (Oi_oc'' i) \n                         (0, (k, v)) maxCallsAndBlocks) \n                       (list (Blist * Bvector eta)) (list_EqDec (pair_EqDec eqdbl eqdbv))\n                       rb_oracle nil;\n                 ret a);\n            z <-$ ([bnkv, s']<-2 top; [bits, _] <-2 bnkv; x <-$ A bits; ret (x, s')); [b, _]<-2 z; ret b)).\n      { prog_equiv. }\n      rewrite_r.\n      instantiate\n        (1 :=\n           (top <-$\n                ([k,v] <-$2 Instantiate;\n                 (* [k,v] <-$2 Instantiate; *)\n                 k <-$ RndK;\n                 a <-$ (oracleCompMap_inner\n                         (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n                                     (pair_EqDec nat_EqDec eqDecState))\n                         (list_EqDec (list_EqDec eqdbv)) (Oi_oc''' i) \n                         (0, (k, v)) maxCallsAndBlocks\n                       (list (Blist * Bvector eta)) (list_EqDec (pair_EqDec eqdbl eqdbv))\n                       rb_oracle nil);\n                 ret a);\n                z <-$ ([bnkv, s']<-2 top; [bits, _] <-2 bnkv; x <-$ A bits; ret (x, s')); [b, _]<-2 z; ret b)).\n      { prog_equiv. }\n\n     fcf_skip. flip. \n\n      apply oracleCompMap_rb_instantiate_outer_i_neq_0.\n      omega. auto.\n\n      simpl in H2. destruct b0. destruct a. simpl in *. destruct p. simpl in *. subst.\n      prog_equiv. fcf_spec_ret.\n\n      simpl in H2. destruct p. destruct l1. simpl in *. rewrite H2.\n      prog_equiv. fcf_spec_ret.\n\n      simpl in H2. rewrite H2.\n      prog_equiv. fcf_spec_ret.\n    } \n    flip.\n    unfold Instantiate. simplify.\n    fcf_irr_r. unfold RndK. fcf_well_formed.\n    simplify.\n\n    rewrite_r.\n    instantiate (1 := \n                   (k0 <-$ RndK;\n                    a <-$ RndV;\n                    z1 <-$ ret (b, a);\n                    [_, v]<-2 z1;\n                    a0 <-$ ret (k0, v, nil);\n                    a1 <-$\n                       ([z, s']<-2 a0;\n                        ([k1, v0]<-2 z;\n                         z0 <--$\n                            oracleCompMap_inner\n                            (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n                                        (pair_EqDec nat_EqDec eqDecState))\n                            (list_EqDec (list_EqDec eqdbv)) (Oi_oc''' i) \n                            (0, (k1, v0)) maxCallsAndBlocks; [bits, _]<-2 z0; $ ret bits)\n                          (list (Blist * Bvector eta)) (list_EqDec (pair_EqDec eqdbl eqdbv))\n                          rb_oracle s');\n                    z <-$ ([z, s']<-2 a1; x <-$ A z; ret (x, s')); [b0, _]<-2 z; ret b0) ).\n    { fcf_swap fcf_right. prog_equiv. }\n\n    fcf_skip_eq. simplify.\n    fcf_skip_eq. simplify.\n    apply comp_spec_symm.\n\n    (* factor out lemma and apply it to both cases *)\n    fcf_skip. \n    (* instantiate (1 := (fun x y => x = fst y)). *)\n    unfold oracleMap.\n    pose proof oracleMap_oracleCompMap_equiv_modified as om_ocm_equiv.\n    eapply comp_spec_eq_trans_r. apply om_ocm_equiv. omega. apply maxBlocksAndCalls_all_nonzero.\n    instantiate (1 := nil). fcf_ident_expand_r. fcf_skip_eq; kv_exist.\n    simpl. fcf_spec_ret.\n\n    simpl in H3. destruct b0.\n    simpl in *. destruct p. destruct p. inversion H3. subst.\n    simplify.\n    fcf_ident_expand_l. simplify. prog_equiv. fcf_reflexivity.\nQed.\n\n(* ----------------------- *Identical until bad section *)\n\nTheorem Gen_loop_rb_intermediate_wf:\n  forall a b c,\n     well_formed_comp (Gen_loop_rb_intermediate b c a).\n\n  clear f.\n  induction a; intuition; simpl; fcf_well_formed.\n\nQed.\n\nTheorem GenUpdate_rb_intermediate_oc_wf :\n  forall b a,\n    well_formed_oc (GenUpdate_rb_intermediate_oc b a).\n\n    intros.\n    unfold GenUpdate_rb_intermediate_oc.\n    fcf_simp.\n    fcf_well_formed.\n    apply Gen_loop_rb_intermediate_wf.\nQed.\n\nTheorem Gen_loop_oc_wf : \n  forall a b0,\n     well_formed_oc (Gen_loop_oc b0 a).\n  clear f.\n  induction a; intuition; simpl; fcf_well_formed.\nQed.\n\nTheorem GenUpdate_noV_oc_wf : \n  forall b a,\n    well_formed_oc (GenUpdate_noV_oc b a).\n\n  intros.\n  unfold GenUpdate_noV_oc.\n  fcf_simp.\n  fcf_well_formed.\n  apply Gen_loop_oc_wf.\n\nQed.\n\nTheorem GenUpdate_oc_wf : \n  forall b a,\n     well_formed_oc (GenUpdate_oc b a).\n  clear f.\n  intros.\n  unfold GenUpdate_oc.\n  fcf_simp.\n  fcf_well_formed.\n  apply Gen_loop_oc_wf.\nQed.\n\nTheorem GenUpdate_PRF_oc_wf : \n  forall b a,\n     well_formed_oc (GenUpdate_PRF_oc b a).\n  intros.\n  unfold GenUpdate_PRF_oc.\n  fcf_simp.\n  fcf_well_formed.\n\nQed.\n\nTheorem oracleCompMap_inner_wf : \n  forall inputs s i,\n  well_formed_oc\n     (oracleCompMap_inner\n        (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n           (pair_EqDec nat_EqDec eqDecState))\n        (list_EqDec (list_EqDec eqdbv)) (Oi_oc' i) \n        s inputs).\n\n  induction inputs; intuition; simpl;\n  fcf_well_formed.\n  destruct (lt_dec a0 i).\n  apply GenUpdate_rb_intermediate_oc_wf.\n  \n  destruct (beq_nat a0 0).\n  apply GenUpdate_noV_oc_wf.\n  destruct (beq_nat a0 i).\n  apply GenUpdate_oc_wf.\n  eapply GenUpdate_PRF_oc_wf.\n\nQed.\n\n\n(* SAME PROOF AS PRF_A_randomFunc_eq_until_bad (with the computation order switched) *)\nTheorem oracleCompMap__oracle_eq_until_bad_dups : forall (i : nat) b b0,\n    comp_spec\n     (fun y1 y2 : list (list (Bvector eta)) * list (Blist * Bvector eta) =>\n        (* TODO fix args *)\n        (* let (bits_rb, state_rb) := y1 in *)\n        (* let (bits_rf, state_rf) := y2 in *)\n        (* let (inputs_rb, outputs_rb) := (fst (split state_rb), snd (split state_rb)) in *)\n        (* let (inputs_rf, output_rf) := (fst (split state_rf), snd (split state_rf)) in *)\n        hasDups _ (fst (split (snd y1))) = hasDups _ (fst (split (snd y2))) /\\\n        (hasDups _ (fst (split (snd y1))) = false ->\n         snd y1 = snd y2 /\\ fst y1 = fst y2))\n\n     ((z <--$\n       oracleCompMap_inner\n         (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n            (pair_EqDec nat_EqDec eqDecState))\n         (list_EqDec (list_EqDec eqdbv)) (Oi_oc' i) \n         (O, (b, b0)) maxCallsAndBlocks; [bits, _]<-2 z; $ ret bits)\n        (list (Blist * Bvector eta)) (list_EqDec (pair_EqDec eqdbl eqdbv))\n        rb_oracle nil)\n     ((z <--$\n       oracleCompMap_inner\n         (pair_EqDec (list_EqDec (list_EqDec eqdbv))\n            (pair_EqDec nat_EqDec eqDecState))\n         (list_EqDec (list_EqDec eqdbv)) (Oi_oc' i) \n         (O, (b, b0)) maxCallsAndBlocks; [bits, _]<-2 z; $ ret bits)\n        (list (Blist * Bvector eta)) (list_EqDec (pair_EqDec eqdbl eqdbv))\n        randomFunc_withDups nil).\nProof.\n  intros.\n  (* TODO review this *)\n  eapply (fcf_oracle_eq_until_bad\n            (fun x => hasDups _ (fst (split x)))\n            (fun x => hasDups _ (fst (split x))) eq); intuition.\n\n  - fcf_well_formed. \n  apply oracleCompMap_inner_wf.\n\n  - intros. unfold rb_oracle. fcf_well_formed.\n  - intros. unfold randomFunc_withDups. destruct (arrayLookup _ a b1); fcf_well_formed.\n  - \n    subst.\n    unfold randomFunc_withDups, rb_oracle.\n\n    (* x2 is the list, a is the element. change variable names *)\n    case_eq (arrayLookup _ x2 a); intuition.\n\n      (* is a duplicate (a is in x2) *)\n      (* now we need to prove that, given that a is in x2,\n         the postcondition holds: \n         note that they both have state x2\n       *)\n    * fcf_irr_l.\n      fcf_simp.\n      (* note the simplified state here *)\n      (*  (ret (b, (a, b) :: x2))\n          (ret (b0, (a, b0) :: x2)) \n         - we know a is in x2 for both\n         - b0 is some random bitvector, b is whatever the lookup returns for a *)\n      fcf_spec_ret; simpl.\n\n      (* note the 3 new goals *)\n      (* obviously hasDups (thing1 :: x2) = hasDups (thing2 :: x2), since `hasDups x2` *)\n      + remember (split x2) as z.\n        destruct z.\n(*        Print hasDups.*)\n        (* Print in_dec. *) (* looks gnarly *)\n        (* hasDups added and removed here! :^) *)\n        simpl in *.\n        trivial.\n\n      (* snd y1 = snd y2 (if there are no dups in the whole state, then the states are the same. but we know there are dups in x2, the tail of the state, so, contradiction!) *)\n      + simpl in *.\n        remember (split x2) as z.\n        destruct z.\n        simpl in *.\n        destruct (in_dec (EqDec_dec _) a l); intuition.\n        discriminate.\n        rewrite notInArrayLookupNone in H.\n        discriminate.\n        intuition.\n        rewrite unzip_eq_split in H4.\n        remember (split x2) as z.\n        destruct z.\n        pairInv.\n        simpl in *.\n        intuition.\n\n      (* fst y1 = fst y2 (exactly the same as above! if there are no dups in the whole state... but we know there are dups in the tail of the state, so, contradiction!) *)\n      + simpl in *.\n        remember (split x2) as z.\n        destruct z.\n        simpl in *.\n        destruct (in_dec (EqDec_dec _) a l).\n        discriminate.\n        rewrite notInArrayLookupNone in H.\n        discriminate.\n        intuition.\n        rewrite unzip_eq_split in H4.\n        remember (split x2) as z.\n        destruct z.\n        pairInv.\n        simpl in *.\n        intuition.\n\n    * (* not a duplicate -- behaves like RB -- a is not in x2 *)\n      fcf_skip.\n      fcf_spec_ret.\n\n    - unfold rb_oracle in *.\n      fcf_simp_in_support.      (* 6 *)\n      simpl in *.\n      remember (split c0) as z.\n      destruct z.\n      simpl in *.\n      destruct (in_dec (EqDec_dec _) d l).\n      intuition.\n      intuition.\n\n    - (* want to prove: for both oracles, if the state starts bad, it stays bad *)\n      (* dups in c0 inputs, and when randomFunc_withDups is run with that state it returns output a and state b, there are dups in the inputs of that state *)\n      unfold randomFunc_withDups in *. (* 5 *)\n      (* NOTE this is a useful tactic *)\n      fcf_simp_in_support.\n      simpl.\n      remember (split c0) as z.\n      destruct z.\n      simpl in *.\n      destruct (in_dec (EqDec_dec _) d l).\n      intuition.             (* first element is dup *)\n      intuition. (* by H -- the existing state has dups *)\nQed.\n\nTheorem PRF_Adv_eq_until_bad : forall (i : nat),\n   comp_spec \n     (fun a b : bool * list (Blist * Bvector eta) =>\n        let (adv_rb, state_rb) := a in\n        let (adv_rf, state_rf) := b in\n        let (inputs_rb, outputs_rb) := (fst (split state_rb), snd (split state_rb)) in\n        let (inputs_rf, output_rf) := (fst (split state_rf), snd (split state_rf)) in\n        hasDups _ inputs_rb = hasDups _ inputs_rf /\\\n        (hasDups _ inputs_rb = false ->\n         (* true -- if there are no duplicates, then the random function behaves exactly like RB, so the key is randomly sampled AND the v (going into the PRF) is also randomly sampled. so the outputs should be the same.\nin fact, if there are no dups, PRF_Adv rf i = PRF_Adv rb i.\nso, this means the comp_spec above is true?\ndoes PRHL act like giving each the same \"tape\" of randomness for equality? *)\n         state_rb = state_rf /\\ adv_rb = adv_rf))\n     ((PRF_Adversary i) (list (Blist * Bvector eta))\n        (list_EqDec (pair_EqDec eqdbl eqdbv)) rb_oracle nil)\n     ((PRF_Adversary i) (list (Blist * Bvector eta))\n        (list_EqDec (pair_EqDec eqdbl eqdbv))\n        randomFunc_withDups nil).\nProof.\n  intros.\n  unfold PRF_Adversary.\n  simpl.\n  fcf_inline_first.\n  fcf_skip.\n  fcf_simp.\n  fcf_skip.\n  apply oracleCompMap__oracle_eq_until_bad_dups.\n\n  (* ------ *)\n  fcf_simp.\n  intuition.\n  rename b1 into state_rb_.\n  rename l0 into state_rf_.\n  rename a0 into bits_rb_.\n  rename l into bits_rf_.\n\n  (* case_eq shows up in both *)\n(*  Print Ltac case_eq.*)\n(*  Locate Ltac case_eq.*)\n  (* TODO what is this? *)\n\n  (* case_eq (hasInputDups state_rb_); intuition. *)\n  case_eq (hasDups _ (fst (split (state_rb_)))); intuition.\n\n  (* duplicates exist, computations are irrelevant *)\n  - \n    fcf_irr_l.\n    fcf_irr_r.\n    rename a into adv_rb_.\n    rename b1 into adv_rf_.\n    fcf_spec_ret.\n    (* true=false in hypotheses *)\n    (* hasInputDups state_rb_ = true (by case_eq) and false (by assumption in postcondition) *)\n    congruence.\n\n  (* no duplicates, equality is preserved *)\n  (* automatically applied dups = false to get that the states and outputs are the same *)\n  - simpl in *.\n    subst.\n    fcf_skip.\n    fcf_spec_ret.\nQed.\n\n(* First assumption for id until bad: the two games have the same probability of returning bad *)\n(* uses provided oracle on call number i\n   i = 2\n                      0  1  2   3   4\n   Gi_rf_bad i =     RB RB RF PRF  PRF\n   Gi_rb_bad i =     RB RB RB PRF PRF\n   bad event = duplicates in input on call number i *)\nLemma Gi_rb_rf_return_bad_same : forall (i : nat),\n    Pr  [x <-$ Gi_rb_bad i; ret snd x ] ==\n    Pr  [x <-$ Gi_rf_dups_bad i; ret snd x ].\nProof.\n  intros.\n  unfold Gi_rb_bad. unfold Gi_rf_dups_bad.\n  fcf_to_prhl_eq.\n  fcf_inline_first.\n  fcf_skip.\n  (* different spec if you do `fcf_to_prhl` only, and in this location *)\n  *\n    apply PRF_Adv_eq_until_bad.\n  *\n    destruct b0.\n    intuition.\n    fcf_simp.\n    unfold hasInputDups.\n    rewrite H2.\n    simpl.\n    fcf_reflexivity.\nQed.\n\n(* \"distribution of the value of interest is the same in c_1 and c_2 when the bad event does not happen\" -- the two are basically the same if the bad event doesn't happen, so it's true.\n         differences: 1. PRF re-keyed using RF vs. randomly sampled. but PRF re-keyed using something of length > eta, so it is effectively randomly sampled.\n         2. the v going into the next call (if it exists) is randomly sampled vs. resulting from a RF call, but it doesn't matter *)\n\n(* TODO: both of these proofs (in PRF_DRBG) rely on the PRF_Adv comp_spec lemma, which is proven by a bunch of casework. need another comp_spec lemma here on genupdate/prfadv? that adversary isn't even here anymore... *)\n\nTheorem Gi_rb_rf_no_bad_same : forall (i : nat) (a : bool),\n   evalDist (Gi_rb_bad i) (a, false) == evalDist (Gi_rf_dups_bad i) (a, false).\nProof.\n  intros.\n  fcf_to_prhl.                  (* note the auto-specification here *)\n  (* it's NOT fcf_to_prhl_eq *)\n  unfold Gi_rb_bad.\n  unfold Gi_rf_dups_bad.\n  fcf_skip.\n  *\n    apply PRF_Adv_eq_until_bad.\n    (* but is this the right specification? *)\n  *\n    fcf_simp.\n    intuition.\n    fcf_spec_ret.\n\n    pairInv.\n    unfold hasInputDups.\n    apply H3 in H6.\n    intuition.\n    subst.\n    reflexivity.\n\n    pairInv.\n    unfold hasInputDups in *.\n    rewrite H2.\n    rewrite <- H2 in H6.\n    apply H3 in H6.\n    intuition.\n    subst.\n    fcf_reflexivity.\nQed.\n\nClose Scope nat.\n(* Applying the fundamental lemma here *)\nLemma Gi_rb_rf_identical_until_bad : forall (i : nat),\n| Pr[x <-$ Gi_rf_dups_bad i; ret fst x] - Pr[x <-$ Gi_rb_bad i; ret fst x] | <=\n                                              Pr[x <-$ Gi_rb_bad i; ret snd x].\nProof.\n  intros. rewrite ratDistance_comm.\n\n  fcf_fundamental_lemma.\n\n  (* TODO: confirm if these assumptions seem true *)\n  (* first assumption: they have same probability of returning bad *)\n  - apply Gi_rb_rf_return_bad_same.\n\n  (* \"distribution of the value of interest is the same in c_1 and c_2 when the bad event does not happen\" *)\n  - apply Gi_rb_rf_no_bad_same.\nQed.\n\n(* ----------- End identical until bad section *)\n(* ---------- Begin collision probability bound section *)\n\n(* bad event is repetition in the random INPUTS. INPUTS = v :: (first n of outputs)? *)\n(* modified PRF_Adversary to just return bits *)\nDefinition callMapWith (i : nat) : OracleComp Blist (Bvector eta) (list (list (Bvector eta))) :=\n  bits <--$ oracleCompMap_outer _ _ (Oi_oc' i) maxCallsAndBlocks;\n  $ ret bits.\n\n(* throw away the first input and the adversary, focus on bad event only *)\nDefinition Gi_rb_bad_no_adv (i : nat) : Comp bool :=\n  [_, state] <-$2 callMapWith i _ _ rb_oracle nil;\n  ret (hasInputDups state).\n\n(* remove adversary (easy) *)\nLemma Gi_rb_bad_eq_1 : forall (i : nat),\n    Pr [x <-$ Gi_rb_bad i; ret snd x] == Pr [Gi_rb_bad_no_adv i].\nProof.\n  intros.\n  fcf_to_prhl_eq.\n  unfold Gi_rb_bad.\n  unfold Gi_rb_bad_no_adv.\n  prog_equiv.\n  fcf_irr_l.\n  prog_equiv.\n  fcf_spec_ret.\nQed.\n\nClose Scope nat.\n\n(* match the form in dupProb_const *)\nDefinition compMap_v (ls : list nat) (v : Bvector eta) :=\n  x <-$ compMap _ (fun _ => {0,1}^eta) ls;\n  ret hasDups _ (v :: x).\n\n(* match the general form in Gi_rb_collisions_inner_eq_general_induct_irr_l's induction *)\nDefinition compMap_v_init (ls : list nat) (v : Bvector eta) (init : list (Blist * Bvector eta)) :=\n  x <-$ compMap _ (fun _ => {0,1}^eta) ls;\n  ret hasDups _ ((map (@to_list _ _) (v :: x)) ++ (map (@fst _ _ ) init)).\n\n(* generalized version of case_on_i for induction hyp *)\nDefinition case_on_i_gen (i listLen callsSoFar nblocks : nat) (init : list (Blist * Bvector eta)) (v : Bvector eta) := \n  if ge_dec i (listLen + callsSoFar) then (ret (hasInputDups init))\n  (* i = 0, so the last v is not an input. this case is exactly equivalent to adam’s gen_loop *)\n  else if zerop i then (compMap_v_init (forNats (pred nblocks)) v init)\n  else (compMap_v_init (forNats nblocks) v init).\n\nDefinition case_on_i (i ncalls nblocks : nat) (v : Bvector eta) := \n  if ge_dec i ncalls then (ret false)\n  (* i = 0, so the last v is not an input. this case is exactly equivalent to adam’s gen_loop *)\n  else if zerop i then (compMap_v (forNats (pred nblocks)) v)\n  else (compMap_v (forNats nblocks) v).\n\nOpen Scope nat.\n\n(* TODO split this out into a separate module (CompMap_v_equiv.v) *)\n(* Transparent hasDups. *)\n\n(*Require Import fcf.CompMap_v_equiv.*)\n\n(* this is used *)\nLemma simplify_hasDups : forall (listLen i callsSoFar blocks : nat) (k v : Bvector eta) (l : list (Bvector eta))\n                                rb_state1,\n  comp_spec eq\n     (a <-$\n      (oracleCompMap_inner\n         (pair_EqDec (list_EqDec (list_EqDec (Bvector_EqDec eta)))\n            (pair_EqDec nat_EqDec eqDecState))\n         (list_EqDec (list_EqDec (Bvector_EqDec eta)))\n         (Oi_oc' i) (callsSoFar, (k, v))\n         (replicate listLen blocks)) (list (Blist * Bvector eta))\n        (list_EqDec (pair_EqDec eqdbl (Bvector_EqDec eta))) rb_oracle rb_state1;\n      a0 <-$\n      ([z, s']<-2 a;\n       ([resList, state'']<-2 z; $ ret (l :: resList, state''))\n         (list (Blist * Bvector eta))\n         (list_EqDec (pair_EqDec eqdbl (Bvector_EqDec eta))) rb_oracle s');\n      [_, rb_state2]<-2 a0; ret hasInputDups rb_state2)\n     (a <-$\n      (oracleCompMap_inner\n         (pair_EqDec (list_EqDec (list_EqDec (Bvector_EqDec eta)))\n            (pair_EqDec nat_EqDec eqDecState))\n         (list_EqDec (list_EqDec (Bvector_EqDec eta)))\n         (Oi_oc' i) (callsSoFar, (k, v))\n         (replicate listLen blocks)) (list (Blist * Bvector eta))\n        (list_EqDec (pair_EqDec eqdbl (Bvector_EqDec eta))) rb_oracle rb_state1;\n      [_, rb_state2] <-2 a;\n      ret hasInputDups rb_state2).\nProof. intros. prog_equiv. fcf_spec_ret. Qed.\n\nLemma rb_oracle_state_same_after_i : forall (listLen i callsSoFar blocks : nat) (k v : Bvector eta) left_state,\n   callsSoFar > i ->\n   comp_spec eq\n     (a0 <-$\n      (oracleCompMap_inner\n         (pair_EqDec (list_EqDec (list_EqDec (Bvector_EqDec eta)))\n            (pair_EqDec nat_EqDec eqDecState))\n         (list_EqDec (list_EqDec (Bvector_EqDec eta))) \n         (Oi_oc' i) (callsSoFar, (k, v)) (replicate listLen blocks))\n        (list (Blist * Bvector eta))\n        (list_EqDec (pair_EqDec eqdbl (Bvector_EqDec eta))) rb_oracle\n        left_state;\n      [_, left_state']<-2 a0; ret hasInputDups left_state')\n     (ret hasInputDups left_state).\nProof.\n  induction listLen as [ | listLen']; intros; rename H into calls_gt_i.\n  - simplify. fcf_spec_ret.\n  - simplify.\n    destruct (lt_dec callsSoFar i). omega.\n    assert (nonzero : callsSoFar <> 0) by omega.\n    apply beq_nat_false_iff in nonzero.\n    rewrite nonzero.\n    assert (neq_i : callsSoFar <> i) by omega.\n    apply beq_nat_false_iff in neq_i.\n    rewrite neq_i.\n    simplify.\n    \n    eapply comp_spec_eq_trans_r.\n    apply simplify_hasDups.\n    eapply comp_spec_eq_trans_r.\n    eapply IHlistLen'.\n    omega. fcf_spec_ret.\nQed.\n\n(* TODO see if I can prove a more general version of compmap_v_eq using compMap_v_eq_h *)\n(* From email: See compMap_v_eq_h in the file I attached on Apr 22. I think this is what you want. Note that this fact only holds if v and w are both not in init (you can also prove it when both are in init by removing the compMap statements with fcc_irr). *)\n\n(* adding init on the right *)\n\nOpaque hasDups.\n\nLemma split_map_fst : forall A B (l : list (A * B)), fst (split l) = map (@fst _ _) l.\nProof.\n  induction l as [ | x xs]; intros; simpl; try reflexivity.\n  destruct x. simpl. destruct (split xs). simpl in *. subst. reflexivity.\nQed.\n\n(* simplify GenUpdate_oc or GenUpdate_noV_oc into the simpler compMap version that just samples a list of random bvectors *)\n(* this lemma is a more general version that applies to both i=0 and i<>0 cases (GenUpdate_noV_oc or GenUpdate_oc) (after some simplification in the former) *)\nLemma Gi_rb_collisions_inner_eq_general_irr_l : forall (blocks : nat) (v : Bvector eta) (init : list (Blist * Bvector eta)),\n   Forall (fun x : list bool * Bvector eta => length (fst x) = eta) init ->\n   comp_spec eq\n     (a <-$ { 0 , 1 }^eta;\n      a0 <-$ ret (a, (to_list v, a) :: init);\n      a1 <-$\n      ([z, s']<-2 a0;\n       z0 <-$\n       (Gen_loop_oc z blocks) (list (Blist * Bvector eta))\n         (list_EqDec (pair_EqDec eqdbl (Bvector_EqDec eta)))\n         (fun (state : list (Blist * Bvector eta)) (input : Blist) =>\n          output <-$ { 0 , 1 }^eta; ret (output, (input, output) :: state))\n         s';\n       [z1, s'0]<-2 z0;\n       ([bits, v']<-2 z1;\n        k' <--$ query to_list v' ++ zeroes; $ ret (bits, (k', v')))\n         (list (Blist * Bvector eta))\n         (list_EqDec (pair_EqDec eqdbl (Bvector_EqDec eta)))\n         (fun (state : list (Blist * Bvector eta)) (input : Blist) =>\n          output <-$ { 0 , 1 }^eta; ret (output, (input, output) :: state))\n         s'0); [_, init']<-2 a1; ret hasInputDups init')\n     (x <-$\n      compMap (Bvector_EqDec eta) (fun _ : nat => { 0 , 1 }^eta)\n        (forNats blocks);\n      ret hasDups eqdbl\n            (to_list v\n             :: map (to_list (n:=eta)) x ++ map (fst (B:=Bvector eta)) init)).\nProof.\n  clear f.\n  induction blocks as [ | blocks']; intros v init inputs_len.\n  - simplify.\n    fcf_irr_l. rename a into key_input. simplify.\n    fcf_irr_l. rename a into key_output. simplify.\n    fcf_spec_ret. unfold hasInputDups. simpl.\n    remember (split init) as z. destruct z. simpl.\n    pose proof split_map_fst as split_map. rewrite <- split_map. rewrite <- Heqz. simpl.\n\n    (* prove that key-input-extended cannot collide with rest of oracle inputs *)\n    Transparent hasDups.\n    unfold Blist. (* type synonym was interfering with rewrite *)\n    remember (to_list v :: l) as rest.\n    unfold hasDups at 1. fold hasDups. subst.\n    Opaque hasDups.\n    destruct (in_dec (EqDec_dec eqdbl) (to_list key_input ++ zeroes)) as [ is_in | not_in ].\n    + assert (not_in : ~ In (to_list key_input ++ zeroes) (to_list v :: l)).\n      {\n        simpl. unfold not. intros not_in.\n        destruct not_in as [ is_first_elem | in_fixed_len_list ].\n        {\n          assert (len_eq : length (to_list v) = length (to_list key_input ++ zeroes)).\n          f_equal; trivial.\n          rewrite app_length in *.\n          \n          repeat rewrite to_list_length in *.\n          unfold zeroes in *.\n          rewrite length_replicate in len_eq.\n          rewrite plus_comm in len_eq.\n          simpl in *.\n          omega.\n        }\n\n        (* every element of l has length eta, and zeroes is nonempty *)\n        {\n          assert (l_eq : l = fst (split init)).\n          { rewrite <- Heqz. reflexivity. }\n          subst.\n          rewrite Forall_forall in inputs_len.\n          destruct (in_split_l_if init _ in_fixed_len_list). eauto.\n\n          unfold to_list in *.\n          apply inputs_len in H1; simpl in *; rewrite app_length in H1;\n            unfold zeroes in H1; rewrite length_replicate in H1;\n              rewrite plus_comm in H1; simpl in *.\n          rewrite to_list_length in *. omega.\n          \n          (* match goal with  *)\n          (*   | [ H1:  In (to_list key_input ++ zeroes, _) init |- _ ] =>  *)\n          (*      apply inputs_len in H1; simpl in *; rewrite app_length in H1; *)\n          (*      unfold zeroes in H1; rewrite length_replicate in H1; *)\n          (*      rewrite plus_comm in H1; simpl in *; discriminate *)\n          (* end. *)\n        }\n      }\n      contradiction.\n    + reflexivity.\n\n  - simplify.\n    fcf_skip. rename b into skip_v. simplify.\n    specialize (IHblocks' skip_v ((to_list v, skip_v) :: init)).\n    eapply comp_spec_eq_trans_r.\n    (* clean up left side of IH *)\n    instantiate (1 := \n       (a <-$ { 0 , 1 }^eta;\n         a0 <-$ ret (a, (to_list skip_v, a) :: (to_list v, skip_v) :: init);\n         a1 <-$\n         ([z, s']<-2 a0;\n          z0 <-$\n          (Gen_loop_oc z blocks') (list (Blist * Bvector eta))\n            (list_EqDec (pair_EqDec eqdbl (Bvector_EqDec eta)))\n            (fun (state : list (Blist * Bvector eta)) (input : Blist) =>\n             output <-$ { 0 , 1 }^eta; ret (output, (input, output) :: state))\n            s';\n          [z1, s'0]<-2 z0;\n          ([bits, v']<-2 z1;\n           k' <--$ query to_list v' ++ zeroes; $ ret (bits, (k', v')))\n            (list (Blist * Bvector eta))\n            (list_EqDec (pair_EqDec eqdbl (Bvector_EqDec eta)))\n            (fun (state : list (Blist * Bvector eta)) (input : Blist) =>\n             output <-$ { 0 , 1 }^eta; ret (output, (input, output) :: state))\n            s'0); [_, init']<-2 a1; ret hasInputDups init')).\n    { prog_equiv. fcf_spec_ret. }\n    (* right side of H *)\n    eapply comp_spec_eq_trans_l.\n    apply IHblocks'.\n    (* prove ind hyp on init *)\n    {\n      apply Forall_cons.\n      simpl. apply to_list_length. auto.\n    }\n\n    simplify. prog_equiv. fcf_spec_ret.\n    \n    apply Permutation_hasDups.\n\n    eapply perm_trans. Focus 2.\n    instantiate (1 :=      (to_list skip_v\n      :: to_list v\n         :: map (to_list (n:=eta)) a ++ map (fst (B:=Bvector eta)) init)).\n     apply perm_swap. \n     constructor.\n\n    eapply perm_trans.\n    instantiate (1 :=      ((map (to_list (n:=eta)) a ++\n         (to_list v :: nil)) ++ map (fst (B:=Bvector eta)) init) ).\n    { rewrite <- app_assoc. apply Permutation_app_head. simpl. reflexivity. }\n\n    rewrite app_comm_cons.\n    apply Permutation_app.\n    apply Permutation_sym.\n    apply Permutation_cons_append.\n    reflexivity.\nAdmitted.\n\n(* apply above theorem for i <> 0, GenUpdate_oc *)\nLemma Gi_rb_collisions_inner_eq_general_i_neq0 : forall (blocks : nat) (k v : Bvector eta) (init : list (Blist * Bvector eta)),\n    Forall (fun x => length (fst x) = eta) init ->\n  comp_spec eq\n     (a <-$\n      (GenUpdate_oc (k, v) blocks) (list (Blist * Bvector eta))\n        (list_EqDec (pair_EqDec eqdbl (Bvector_EqDec eta))) rb_oracle init;\n      [_, init']<-2 a; ret hasInputDups init') \n      (x <-$\n      compMap (Bvector_EqDec eta) (fun _ : nat => { 0 , 1 }^eta)\n        (forNats blocks); \n        ret hasDups _ ((map (@to_list _ _) (v :: x)) ++ (map (@fst _ _ ) init))).\nProof.\n  intuition; simpl. \n  rename H0 into inputs_len.\n  unfold rb_oracle.\n  fcf_inline_first.\n  revert k v init inputs_len. (*clear H.*)\n  intros k_irr.\n  apply Gi_rb_collisions_inner_eq_general_irr_l.\nQed.\n\n(* apply theorem for i=0, GenUpdate_noV_oc *)\nLemma Gi_rb_collisions_inner_eq_general_i_eq0 : forall (blocks : nat) (k v : Bvector eta)\n                                                                   (init : list (Blist * Bvector eta)),\n    Forall (fun x => length (fst x) = eta) init ->\n    blocks > 0 ->\n    comp_spec eq\n              (a <-$\n                 (GenUpdate_noV_oc (k, v) blocks) (list (Blist * Bvector eta))\n                 (list_EqDec (pair_EqDec eqdbl (Bvector_EqDec eta))) rb_oracle init;\n               [_, init']<-2 a; ret hasInputDups init')\n              (x <-$\n                 compMap (Bvector_EqDec eta) (fun _ : nat => { 0 , 1 }^eta)\n                 (forNats (pred blocks));\n               ret hasDups eqdbl\n                   (map (to_list (n:=eta)) (v :: x) ++ map (fst (B:=Bvector eta)) init)).\nProof.\n  intuition; simpl.\n  rename H0 into inputs_len. rename H1 into blocks_neq_0.\n  unfold rb_oracle.\n  fcf_inline_first.\n  destruct blocks as [ | blocks']. \n  - omega.\n  - simplify. clear blocks_neq_0.\n    (* blocks <> 0 -> reduces to lemma on i <> 0 *)\n    (* clean up left side *)\n    eapply comp_spec_eq_trans_l.\n\n    instantiate (1 := \n                   (a <-$ { 0 , 1 }^eta;\n                    a0 <-$ ret (a, (to_list v, a) :: init);\n                    a1 <-$\n                       ([z, s']<-2 a0;\n                        z0 <-$\n                           (Gen_loop_oc z blocks') (list (Blist * Bvector eta))\n                           (list_EqDec (pair_EqDec eqdbl (Bvector_EqDec eta)))\n                           (fun (state : list (Blist * Bvector eta)) (input : Blist) =>\n                              output <-$ { 0 , 1 }^eta; ret (output, (input, output) :: state))\n                           s';\n                        [z1, s'0]<-2 z0;\n                        ([bits, v']<-2 z1;\n                         k' <--$ query to_list v' ++ zeroes; $ ret (bits, (k', v')))\n                          (list (Blist * Bvector eta))\n                          (list_EqDec (pair_EqDec eqdbl (Bvector_EqDec eta)))\n                          (fun (state : list (Blist * Bvector eta)) (input : Blist) =>\n                             output <-$ { 0 , 1 }^eta; ret (output, (input, output) :: state))\n                          s'0); [_, init']<-2 a1; ret hasInputDups init')).\n    { prog_equiv. fcf_spec_ret. }\n\n    revert k v init inputs_len. (*clear H. *)rename blocks' into blocks.\n    intros k_irr. \n    apply Gi_rb_collisions_inner_eq_general_irr_l. \nQed.\n\nLemma to_list_injective : forall (T : Set) (n : nat) (a1 a2 : Vector.t T n), @to_list T n a1 = @to_list T n a2 -> a1 = a2.\nProof.\n  intros.\n  induction n as [ | n'].\n  - pose proof vector_0 as nil_a1. specialize (nil_a1 T a1).\n    pose proof vector_0 as nil_a2. specialize (nil_a2 T a2).\n    subst. reflexivity.\n  - pose proof vector_S as cons_a1. specialize (cons_a1 T n' a1). destruct cons_a1 as [ x1 cons_a1 ].\n    destruct cons_a1 as [ v1 cons_a1 ]. subst.\n\n    pose proof vector_S as cons_a2. specialize (cons_a2 T n' a2). destruct cons_a2 as [ x2 cons_a2 ].\n    destruct cons_a2 as [ v2 cons_a2 ]. subst.\n\n    unfold to_list in *. Transparent Vector.to_list. simpl in *. unfold Vector.to_list in H.\n    fold (@Vector.to_list T) in *.\n    inversion H. subst. clear H.\n    f_equal.\n    apply IHn'.\n    apply H2.\n    Opaque Vector.to_list.\nQed.\n\nRequire Import fcf.map_swap.        (* TODO move to top *)\n\n(* more general version of compMap_v_eq and compMap_v_eq_h, closer to the form of the induction *)\nLemma compMap_v_eq_init_list_placeholder : forall (a b : Bvector eta) init blocks,\n    (* these two assumptions come from compMap_v_eq_init_list_h *)\n    list_pred\n      (fun x y : list bool =>\n         x = y /\\ x <> to_list a /\\ x <> to_list b \\/\n                                    to_list a = x /\\ to_list b = y \\/ to_list b = x /\\ to_list a = y)\n      (map (fst (B:=Bvector eta)) init) (map (fst (B:=Bvector eta)) init) ->\n\n    (In (to_list a) (map (fst (B:=Bvector eta)) init) <-> In (to_list b) (map (fst (B:=Bvector eta)) init)) ->\n\n   comp_spec eq \n     (x <-$\n      compMap (Bvector_EqDec eta) (fun _ : nat => { 0 , 1 }^eta)\n        (forNats blocks);\n      ret hasDups eqdbl\n            (map (to_list (n:=eta)) (a :: x) ++\n             map (fst (B:=Bvector eta)) init))\n     (x <-$\n      compMap (Bvector_EqDec eta) (fun _ : nat => { 0 , 1 }^eta)\n        (forNats blocks);\n      ret hasDups eqdbl\n            (map (to_list (n:=eta)) (b :: x) ++\n             map (fst (B:=Bvector eta)) init)).\nProof.\n  intros.\n  pose proof compMap_v_eq_init_list_h as compMap_v_eq_init_list.\n  specialize (compMap_v_eq_init_list eta a b (map (fst (B:=Bvector eta)) init) blocks).\n  Transparent map.\n  simpl.\n  Opaque map.\n  Transparent eqdbl.\n  unfold eqdbl.\n  apply compMap_v_eq_init_list; auto.\nQed.\n\nLemma split_out_oracle_call_forall : \n    forall (listLen : nat) (k v v_prev : Bvector eta) (callsSoFar i blocks : nat) (init : list (Blist * Bvector eta)) ,\n      callsSoFar <= i ->\n   Forall (fun x : list bool * Bvector eta => length (fst x) = eta) init ->\n   blocks > 0 ->\n\n    (* these two assumptions come from compMap_v_eq_init_list_h *)\n   (forall (a b : Bvector eta),\n       list_pred\n      (fun x y : list bool =>\n         x = y /\\ x <> to_list a /\\ x <> to_list b \\/\n                                    to_list a = x /\\ to_list b = y \\/ to_list b = x /\\ to_list a = y)\n      (map (fst (B:=Bvector eta)) init) (map (fst (B:=Bvector eta)) init)) ->\n\n    (forall (a b : Bvector eta),\n                   (In (to_list a) (map (fst (B:=Bvector eta)) init) <-> In (to_list b) (map (fst (B:=Bvector eta)) init))) ->\n\n   comp_spec eq\n     (a <-$\n      (oracleCompMap_inner\n         (pair_EqDec (list_EqDec (list_EqDec (Bvector_EqDec eta)))\n            (pair_EqDec nat_EqDec eqDecState))\n         (list_EqDec (list_EqDec (Bvector_EqDec eta))) \n         (Oi_oc' i) (callsSoFar, (k, v)) (replicate listLen blocks))\n        (list (Blist * Bvector eta))\n        (list_EqDec (pair_EqDec eqdbl (Bvector_EqDec eta))) rb_oracle init;\n      [_, state]<-2 a; ret hasInputDups state)\n     (case_on_i_gen i listLen callsSoFar blocks init v_prev).\nProof.\n  unfold case_on_i_gen.\n  induction listLen as [ | listLen']; intros; rename H0 into oracle_input_lengths; rename H1 into blocks_neq_0;\n  rename H2 into list_pred_init; rename H3 into in_same_init.\n\n   (* base case: empty *)\n  - simplify.\n    destruct (ge_dec i callsSoFar). { fcf_spec_ret. } { omega. }\n\n  (* inductive case *)\n  - Opaque Oi_oc'. Opaque GenUpdate_noV_oc. Opaque GenUpdate_oc.\n    rename H into calls_leq_i.\n    Opaque zerop.\n    simplify.\n    assert (calls_size : callsSoFar < i \\/ callsSoFar = i) by omega.\n    destruct calls_size as [ calls_lt_i | calls_eq_i ].\n    (* callsSoFar < i -> after this call, S callsSoFar <= i *)\n    + clear calls_leq_i.\n      Transparent Oi_oc'.\n      simplify.\n\n      (* clean up left side *)\n      destruct (lt_dec callsSoFar i). Focus 2. omega.\n      clear l.\n\n      (* strip off first call on left side, since it doesn't use the oracle *)\n      unfold GenUpdate_rb_intermediate_oc.\n      simplify.\n      fcf_irr_l. simplify.\n      fcf_irr_l.\n      {\n        (* SearchAbout well_formed_comp. *)\n        (* unfold Gen_loop_rb_intermediate. *)\n        (* TODO *)\n        apply Gen_loop_rb_intermediate_wf.\n      }\n      (* note the k doesn't change *)\n      simplify.\n      rename b into v'.\n\n      eapply comp_spec_eq_trans_r.\n      apply simplify_hasDups.\n      rewrite plus_n_Sm.\n      eapply IHlistLen'; try omega; try auto.\n\n    (* calls = i *)\n    + (* what's the form of the lemma i should apply here? *)\n      clear calls_leq_i.\n      (* here, the calls should both be skipped (since calls = i, the oracle is used) *)\n      (* then induct on the rest *)\n      Transparent Oi_oc'.\n      simplify.\n      subst.\n      (* clean up left side *)\n      destruct (lt_dec i i). omega.\n      (* clean up right side *)\n      destruct (ge_dec i (S (listLen' + i))). omega.\n\n      (* depends on whether i = 0, so destruct on that *)\n      destruct (zerop i) as [ i_eq_0 | i_gt_0 ].\n      (* i = 0 *)\n      {\n        subst. simplify.\n\n        (* replace v_prev with v, since the const vector in front doesn't matter *)\n        eapply comp_spec_eq_trans_r.\n        Focus 2.\n\n        eapply (compMap_v_eq_init_list_placeholder v v_prev); auto.\n\n        eapply comp_spec_eq_trans_r.\n        (* can get rid of following oracleCompMap *)\n        instantiate (1 :=\n                       (a <-$\n      (GenUpdate_noV_oc (k, v) blocks) (list (Blist * Bvector eta))\n        (list_EqDec (pair_EqDec eqdbl (Bvector_EqDec eta))) rb_oracle init;\n                        [_, init'] <-2 a;\n                        ret hasInputDups init')).\n        { fcf_skip_eq.\n          simplify.\n          eapply comp_spec_eq_trans_r.\n          + destruct b0.\n            eapply simplify_hasDups.\n          + destruct b0.\n            eapply rb_oracle_state_same_after_i.\n            omega.\n        }\n        clear n n0 IHlistLen'.\n        \n        (* apply lemma for i=0 *)\n        (* there's probably a nicer way to do it with a lower bound for Gi_rb_collisions_inner_eq_general_induct_irr_l *)\n        apply Gi_rb_collisions_inner_eq_general_i_eq0; auto.\n      }\n      (* i <> 0 *)\n      { assert (i_neq_0 : i <> 0) by omega.\n        apply beq_nat_false_iff in i_neq_0.\n        rewrite i_neq_0.\n        pose proof (beq_nat_refl i) as i_refl.\n        rewrite <- i_refl.\n        clear i_neq_0 i_refl.\n\n        (* replace v_prev with v, since the const vector in front doesn't matter *)\n        eapply comp_spec_eq_trans_r.\n        Focus 2.\n        unfold compMap_v_init.\n        eapply (compMap_v_eq_init_list_placeholder v v_prev); auto.\n        (* pose proof (compMap_v_eq_init_list v v_prev init blocks nil) as compMap_v_eq_inner. *)\n        (* destruct compMap_v_eq_inner as [ l_init compMap_v_eq_inner ]. *)\n        (* eapply compMap_v_eq_inner. *)\n        (* eapply (compMap_v_eq_inner v v_prev init blocks). *)\n        \n        (* should I replace GenUpdate_oc with something else that doesn't use to_list?? *)\n        (* maybe i should replace oracleCompMap inner with hasInputDups (state from Genupdate_oc) first *)\n        simpl.\n\n        eapply comp_spec_eq_trans_r. clear n n0 IHlistLen'.\n        instantiate (1 :=\n                       (a <-$\n      (GenUpdate_oc (k, v) blocks) (list (Blist * Bvector eta))\n        (list_EqDec (pair_EqDec eqdbl (Bvector_EqDec eta))) rb_oracle init;\n                        [_, init'] <-2 a;\n                        ret hasInputDups init')).\n        { fcf_skip_eq. \n          destruct b0.\n          + eapply comp_spec_eq_trans_r.\n          instantiate(1:= (a0 <-$\n           (oracleCompMap_inner\n              (pair_EqDec (list_EqDec (list_EqDec (Bvector_EqDec eta)))\n                 (pair_EqDec nat_EqDec eqDecState))\n              (list_EqDec (list_EqDec (Bvector_EqDec eta))) \n              (Oi_oc' i) (S i, (b0, b1)) (replicate listLen' blocks))\n             (list (Blist * Bvector eta))\n             (list_EqDec (pair_EqDec eqdbl (Bvector_EqDec eta))) rb_oracle b;\n           [_, rb_state2]<-2 a0; ret hasInputDups rb_state2)).\n           simplify. apply simplify_hasDups.\n          eapply rb_oracle_state_same_after_i. \n          omega.\n        }\n        clear n n0 IHlistLen'.\n        \n        apply Gi_rb_collisions_inner_eq_general_i_neq0.\n        auto.\n      } \nQed.\n\nLemma Gi_rb_bad_eq_2' : forall (i : nat) (v : Bvector eta),\n    Pr [Gi_rb_bad_no_adv i] == Pr[case_on_i i numCalls blocksPerCall v].\nProof.\n  intros i v.\n\n  fcf_to_prhl_eq.\n  unfold Gi_rb_bad_no_adv.\n  simplify.\n  fcf_irr_l. wfi.\n  simplify.\n  (* clean up left *)\n  eapply comp_spec_eq_trans_r.\n  (* apply simplify_hasDups. *)\n  instantiate (1 :=\n                      (a <-$\n      (oracleCompMap_inner\n         (pair_EqDec (list_EqDec (list_EqDec (Bvector_EqDec eta)))\n            (pair_EqDec nat_EqDec eqDecState))\n         (list_EqDec (list_EqDec (Bvector_EqDec eta))) \n         (Oi_oc' i) (0%nat, (b, b0)) maxCallsAndBlocks)\n        (list (Blist * Bvector eta))\n        (list_EqDec (pair_EqDec eqdbl (Bvector_EqDec eta))) rb_oracle nil;\n                       [_, state] <-2 a;\n                       ret hasInputDups state)).\n  { prog_equiv. fcf_spec_ret. }\n\n  eapply comp_spec_eq_trans_r.\n  eapply split_out_oracle_call_forall; auto. omega.\n\n  (* list_pred holds on (nil, nil) for any a, b, P *)\n  { constructor. }\n\n  (* In is same for any (nil, nil) *)\n  { intros. Transparent map. simpl. constructor; intros; contradiction. Opaque map. }\n\n  instantiate (1 := v).\n  unfold case_on_i_gen.\n  unfold case_on_i.\n  unfold hasInputDups.\n  Transparent hasDups.          (* init=nil *)\n  simpl. Opaque hasDups.\n  rewrite plus_comm. simpl.\n  Opaque map.\n\n  (* preemptively discharge the two last equality cases *)\n  assert (hasDups_map_equiv : forall a, hasDups eqdbl (map (to_list (n:=eta)) (v :: a) ++ map (fst (B:=Bvector eta)) nil) =\n                                        hasDups (Bvector_EqDec eta) (v :: a)).\n  { intros. rewrite app_nil_r.\n    pose proof hasDups_inj_equiv as hasDups_inj.\n    specialize (hasDups_inj _ _ _ _ (v :: a) (to_list (n := eta))).\n    rewrite hasDups_inj.\n    reflexivity.\n    apply to_list_injective. }\n\n  destruct (ge_dec i numCalls); destruct (zerop i); try fcf_spec_ret; unfold compMap_v; prog_equiv; fcf_spec_ret.\nQed.\n\n(* probability of bad event happening in RB game is bounded by the probability of collisions in a list of length (n+1) of randomly-sampled (Bvector eta) *)\n\nRequire Import fcf.RndInList.\n\nTheorem hasDups_cons_orb : \n  forall (A  : Set)(eqd : EqDec A)(ls : list A)(a : A),\n    hasDups _ (a :: ls) = (if (in_dec (EqDec_dec _) a ls) then true else false) || hasDups _ ls. \n \n   intuition.\n   Transparent hasDups.\n   simpl.\n   destruct (in_dec (EqDec_dec eqd) a ls); intuition.\nQed.\n \nTheorem compMap_hasDups_cons_orb : \n  forall (A : Set)(ls : list A) x,\n    Pr[lb <-$ compMap _ (fun _ => {0,1}^eta) ls; ret hasDups _ (x :: lb)] ==\n    Pr[lb <-$ compMap _ (fun _ => {0,1}^eta) ls; ret (if (in_dec (EqDec_dec _) x lb) then true else false) || hasDups _ lb].\n\n  clear f.\n  intuition.\n  fcf_skip.\n  rewrite hasDups_cons_orb.\n  intuition.\n\nQed.\n\nTheorem compMap_hasDups_cons_prob :\n  forall (A : Set)(ls : list A) x, \n    (Pr[lb <-$ compMap _ (fun _ => {0,1}^eta) ls; ret hasDups _ (x :: lb)] <= S (length ls) ^ 2 / 2 ^ eta)%rat.\n\n  intuition.\n  rewrite compMap_hasDups_cons_orb.\n  rewrite evalDist_orb_le.\n  rewrite FixedInRndList_prob.\n  rewrite dupProb.\n  remember (length ls) as a.\n  rewrite <- ratAdd_den_same.\n  eapply leRat_terms; trivial.\n  simpl.\n  apply le_S.\n  apply plus_le_compat; try omega.\n  apply mult_le_compat; omega.\nQed.\n\nClose Scope nat.\nLemma Gi_rb_bad_collisions : forall (i : nat) (v : Bvector eta),\n   Pr  [x <-$ Gi_rb_bad i; ret snd x ] <= Pr_collisions.\nProof.\n  intros.\n  rewrite Gi_rb_bad_eq_1.\n  pose proof Gi_rb_bad_eq_2' as select_call.\n  specialize (select_call i v).\n  (* sort of weird to have that v quantified but not mentioned in the theorem statement *)\n  rewrite select_call. clear select_call.\n  unfold case_on_i.\n  destruct (ge_dec i) as [ i_ge_nc | i_nge_nc ].\n  (* i out of bounds *)\n  - Transparent evalDist. \n  fcf_compute.\n  apply rat0_le_all.\n\n  (* i in bounds *)\n  - destruct (zerop i).\n    (* i = 0 *)\n    + unfold PRG.compMap_v.\n      rewrite compMap_hasDups_cons_prob.\n      rewrite forNats_length.\n      unfold Pr_collisions.\n      eapply leRat_terms; intuition.\n      eapply Nat.pow_le_mono; omega.\n    + unfold PRG.compMap_v.\n      rewrite compMap_hasDups_cons_prob.\n      rewrite forNats_length.\n      reflexivity.\nQed.\n\n(* Main theorem (modeled on PRF_DRBG_G3_G4_close) *)\n(* Gi_rf 0:  RF  PRF PRF\nGi_prg 1:    RB PRF PRF\n\nGi_rf  1:    RB  RF PRF\nGi_prg 2:    RB  RB  PRF\n\nGi_rf  2:    RB  RB  RF\nGi_prg 3:    RB  RB  RB *)\nLemma Gi_rf_rb_close : forall (i : nat), (* not true for i = 0 (and not needed) *)\n  | Pr[Gi_rf i] - Pr[Gi_prg (S i)] | <= Pr_collisions. \nProof.\n  intros.\n(*  Print Gi_rf.*)\n  (* Gi_prg uses oracleMap, Gi_rb and Gi_rf both use oracleCompMap (oracle box) *)\n  rewrite Gi_normal_rb_eq. (* put Gi_prg into the same form using RB oracle *)\n  (* TODO this might be wrong, maybe Gi_prg (S i) = Gi_rb (S i) *)\n  (* shouldn't we be relating\n     RB RB RF PRF with  <- Gi_rf 2\n     RB RB RB PRF ? <-- Gi_prg 3 = Gi_rb 2\n *)\n\n  rewrite Gi_rf_return_bad_eq. \n  rewrite Gi_rb_return_bad_eq. \n  rewrite Gi_rf_dups_return_bad_eq.\n\n  (* NOTE still parametrized by i, so the hybrid matters *)\n  rewrite Gi_rb_rf_identical_until_bad.\n  apply Gi_rb_bad_collisions.\n  bv_exist.\nQed.\n\n(* ---- PRF advantage *)\n(* Step 1 *)\n(* Gi_prf 2: RB RB PRF PRF PRF\n   Gi_rf 2:  RB RB RF  PRF PRF \nneed to use `Gi_prf i` instead of `Gi_prg i` because this matches the form of \n`Gi_rf` closer so we can match the form of PRF_Advantage*)\n\nLemma Gi_prf_rf_close_i : forall (i : nat),\n  | Pr[Gi_prf i] - Pr[Gi_rf i] | <= PRF_Advantage_Game i.\nProof.\n  intros i.\n  (* don't need to unfold *)\n  unfold Gi_prf.\n  unfold Gi_rf.\n  unfold PRF_Advantage_Game.\n  reflexivity. \nQed.\n\nOpen Scope nat.\nLemma comp_same_after_numCalls : forall (len n callsSoFar : nat) (k v : Bvector eta) init,\n    (n > numCalls)%nat ->\n    (callsSoFar + len = numCalls)%nat ->\n\n    comp_spec eq\n     (compFold\n        (pair_EqDec (list_EqDec (list_EqDec (Bvector_EqDec eta)))\n           (pair_EqDec nat_EqDec eqDecState))\n        (fun (acc : list (list (Bvector eta)) * (nat * KV)) (d : nat) =>\n         [rs, s]<-2 acc;\n         z <-$ Oi_prg n s d; [r, s0]<-2 z; ret (rs ++ r :: nil, s0))\n        (init, (callsSoFar, (k, v))) (replicate len blocksPerCall))\n     (compFold\n        (pair_EqDec (list_EqDec (list_EqDec (Bvector_EqDec eta)))\n           (pair_EqDec nat_EqDec eqDecState))\n        (fun (acc : list (list (Bvector eta)) * (nat * KV)) (d : nat) =>\n         [rs, s]<-2 acc;\n         z <-$ Oi_prg (S n) s d; [r, scallsSoFar]<-2 z; ret (rs ++ r :: nil, scallsSoFar))\n        (init, (callsSoFar, (k, v))) (replicate len blocksPerCall)).\nProof.\n  induction len as [ | len']; intros; rename H into n_gt_len; rename H0 into len_invar.\n  - simplify. fcf_spec_ret.\n  - simpl. \n    simplify.\n    destruct (lt_dec callsSoFar n) as [calls_lt_n | calls_gte_n].\n    Focus 2. omega. \n    destruct (lt_dec callsSoFar (S n)) as [calls_lt_Sn | calls_gte_Sn].\n    Focus 2. omega.\n    fcf_skip_eq; kv_exist.\n    simplify. destruct b.\n    apply IHlen'. auto. omega.\nQed.\n\nTheorem Gi_Gi_plus_1_close_outofbounds :\n  forall (i : nat),\n    (i > numCalls)%nat ->\n   Pr[Gi_prg i] == Pr[Gi_prg (S i)].\nProof.\n  intros.\n  unfold Gi_prg.\n  fcf_to_prhl_eq.\n  prog_equiv. rename b into k. rename b0 into v.\n  (* unfold Oi_prg. *)\n  (* TODO generalize and pull out *)\n  unfold maxCallsAndBlocks.\n  unfold oracleMap.\n(* it should always be PRF on both sides *)\n  apply comp_same_after_numCalls; auto.\nQed.\nClose Scope nat.\n\nLemma Gi_prf_rf_close : forall (i : nat),\n    (i <= numCalls)%nat ->\n| Pr[Gi_prf i] - Pr[Gi_rf i] | <= PRF_Advantage_Max.\nProof.\n  intros.\n  eapply leRat_trans.\n  apply Gi_prf_rf_close_i.\n  apply PRF_Advantage_max_exists.\n  auto.\nQed.\n\n(* TODO prove theorem for all n *)\n\n(* Inductive step *)\n(* let i = 3. \nGi_prg i:      RB RB RB PRF PRF\nGi_prg (S i):  RB RB RB RB  PRF \n\nGi_prg 0: PRF PRF PRF\nGi_rf  0:  RF PRF PRF\nGi_prg 1:  RB PRF PRF\nGi_rf  1:  RB  RF PRF *)\nTheorem Gi_Gi_plus_1_close :\n  (* TODO: constructed PRF adversary *)\n  forall (n : nat),\n  | Pr[Gi_prg n] - Pr[Gi_prg (S n)] | <= Gi_Gi_plus_1_bound.\nProof.\n  intros n.\n  assert (n_dec : (n <= numCalls)%nat \\/ (n > numCalls)%nat) by omega.\n  destruct n_dec as [ n_lte | n_gt ].\n\n  -  unfold Gi_Gi_plus_1_bound. intros.\n     eapply ratDistance_le_trans. (* do the PRF advantage and collision bound separately *)\n     rewrite Gi_normal_prf_eq.    (* changed this *)\n     apply Gi_prf_rf_close; auto.        (* Basically already proven via PRF_Advantage magic *)\n     apply Gi_rf_rb_close.\n\n  - rewrite Gi_Gi_plus_1_close_outofbounds.\n    assert (Heq : | Pr  [Gi_prg (S n) ] - Pr  [Gi_prg (S n) ] | == 0).\n    { rewrite <- ratIdentityIndiscernables. reflexivity. }\n    rewrite Heq.\n    unfold Gi_Gi_plus_1_bound. unfold PRF_Advantage_Max. unfold Pr_collisions.\n    apply rat0_le_all.\n    auto.\nQed.\n\n(* ------------------------------- *)\n\n(* final theorem *)\nTheorem G1_G2_close :\n  | Pr[G1_prg_original] - Pr[G2_prg] | <= (numCalls / 1) * Gi_Gi_plus_1_bound.\nProof.\n  rewrite GenUpdate_v_output_probability.\n  rewrite G1_Gi_O_equal.\n  rewrite G2_Gi_n_equal.\n  specialize (distance_le_prod_f (fun i => Pr[Gi_prg i]) Gi_Gi_plus_1_close numCalls).\n  intuition.\nQed.\n\nEnd PRG.\n\n(* ------------------------------- *)\n(* \n(* Backtracking resistance, using indistinguishability proof *)\n(* this proof is invalid, see thesis for revised proof *)\n\n(* Adversary, split into two *)\nParameter A1 : Comp nat.        (* currently unused *)\nParameter A2 : list (list (Bvector eta)) -> KV -> Comp bool.\n(* Also the adversary is slightly different from the one above. How do we re-use the adv? *)\n\nDefinition G1_prg_original_dup : Comp bool := (* copy of G1_prg_original *)\n  [k, v] <-$2 Instantiate;\n  [bits, _] <-$2 oracleMap _ _ GenUpdate_original (k, v) maxCallsAndBlocks;\n  A bits.\n\nDefinition G1_br_original : Comp bool :=\n  (* blocksForEachCall <-$ A1; (* implicitly compromises after that # calls *) *)\n  [k, v] <-$2 Instantiate;\n  [bits, state'] <-$2 oracleMap _ _ GenUpdate_original (k, v) maxCallsAndBlocks;\n  A2 bits state'.\n\n(* real world -- v-update move equivalence. need to prove that we need UpdateV -- needs an extra game at end of v-update equiv proof *)\nDefinition G1_br : Comp bool :=\n  (* blocksForEachCall <-$ A1; (* implicitly compromises after that # calls *) *)\n  (* TODO: not using this parameter yet, implicitly compromise after max calls (hardcoded)*)\n  [k, v] <-$2 Instantiate;\n  [head_bits, state'] <-$2 GenUpdate_noV (k, v) numCalls;\n  [tail_bits, state''] <-$2 oracleMap _ _ GenUpdate state' (tail maxCallsAndBlocks);\n  (* again, don't need tail here *)\n  (* v update moved to beginning of each GenUpdate *)\n  [k', v'] <-2 state'';\n  v'' <- f k' (to_list v');      (* update v *)\n  A2 (head_bits :: tail_bits) (k', v''). \n\n(* in general, how do we relate different adversaries in FCF? *)\n\n(* A2 still cannot distinguish *)\n(* how do I reuse the previous work? it depended on the adversary result, it wasn't an equivalence rewriting on the inside two lines *)\n(* how would i even do this proof from scratch? would have to prove that PRF -> RF and RF -> RB yield equivalence etc. for A2 bits (k, v') <-- state *)\n(* also, what about the extra UpdateV probabilities? *)\n\n(* we don't know that Pr[G1_br] == Pr[G1_prg_dup]; that would be like assuming the state gives the adversary no extra info, which is like assuming what we want to prove? *)\n(* all of our proof about G1_prg depended on the *adversary*, not the computations (but maybe they should have). *)\n(* can we do the PRF_Advantage step in G1_br and reuse the RF->RB work from G1_prg? need to rephrase in terms of PRF_Adversary *)\nDefinition G1_prg_dup : Comp bool := (* copy of G1_prg *)\n  [k, v] <-$2 Instantiate;\n  [head_bits, state'] <-$2 GenUpdate_noV (k, v) blocksPerCall;\n  [tail_bits, _] <-$2 oracleMap _ _ GenUpdate state' (tail maxCallsAndBlocks);\n  A (head_bits :: tail_bits).\n\n(* TODO change this because I changed G2_prg *)\nDefinition G2_prg_dup : Comp bool := (* copy of G2_prg *)\n  bits <-$ compMap _ GenUpdate_rb maxCallsAndBlocks;\n  A bits.\n\n(* ideal world *)\n(* 1a and 2: v ~ {0,1} -> f v ~ {0,1}? maybe assume it *)\n(* or add an extra PRF_Advantage (random k -> f k v yields random v') *)\nDefinition G2_br : Comp bool :=\n  [k, v] <-$2 Instantiate;\n  bits <-$ compMap _ GenUpdate_rb maxCallsAndBlocks;\n  A2 bits (k, v).\n(*\nLemma G2_prg_br_eq :\n  Pr[G2_br] <= Pr[G2_prg_dup].\nProof.\n  unfold G2_prg_dup, G2_br.\n  unfold Instantiate.\n  simplify. \n  fcf_irr_l. unfold RndK. fcf_well_formed.\n  simplify.\n  fcf_irr_l. unfold RndV. fcf_well_formed.\n  simplify.\n  fcf_skip.\n  unfold RndK, RndV in *.\n  (* should A2 be somehow constructed from A? *)\n  (* also this isn't necessarily true unless A2 is constructed from A. A2 could just do dumb things. certainly Pr[best A2] == Pr[best A] (actually could it improve the adversary to give it more randomness?? probably not, if you're giving it a constant amt) *)\n  (* Print Notation (Pr [ _ ]). *)\nAdmitted.\n*)\n(* 2 and 2a are clearly equivalent? (k,v) gives no information about bits, so remove k, v *)\n(* this is where the indistinguishability proof ends -- don't know how to use this as an intermediate stage. is it possible to do G1_br ->(?) G1_prg -> G2_prg -> G2_br?\nor somehow interleave so that we know the probability is \"squeezed\" to be small?\nG1_br ->(?) G1_prg -> G2_br -> G2_prg *)\n\n(* TODO other equivalence/bounding theorems *)\n\nTheorem G1_G2_close_b2 :\n  | Pr[G1_br_original] - Pr[G2_br] | <= (numCalls / 1) * Gi_Gi_plus_1_bound.\nProof.\n  unfold G1_br.\n  unfold G2_br.\nAdmitted.\n\n(* ------------------------------- *)\n\n  (* Notes on our proof: (might be outdated as of 1/1/16)\n\nShow GenUpdate's output indistinguishable from the output of this version, with v updated first: \n\n  v' <- f k v;\n  [bits, v''] <-2 Gen_loop k v' n;\n  k' <- f k (v'' ++ zeroes);\n  ret (bits, (k', v'')).\n\n(won't be exactly the same since v is updated an extra time in the beginning (first call to GenUpdate) -- unless we have the 1st GenUpdate oracle not update the v at all, then change all GenUpdate oracles after the first one to update v in the first line, according to i in the ith game)\n\n---\n\nG1: (assume instantiate ideal), then the adversary can query Generate+Update as many times as they want. all are done with PRF.\n\nG2: (assume instantiate ideal), then the adversary can query Generate+Update as many times as they want. all are done with random sampling.\n\nP P P P P P\nR R R R R R\n\nGi i: (assume instantiate ideal), then the adversary can query Generate+Update as many times as they want (q). the first i calls are done with random sampling, the rest are done normally, with PRF.\n\nR R P P P P\n\nGi_0: the game as-is (PRF)\n\nR R P P P P\n\nin ith oracle call:\nGi_1: replace all calls to PRF, updating K with a random function \n      replace all calls to PRF, updating V with a random function \n\nR R F P P P\n\nGi_2: replace all calls to RF, updating K with randomly-sampled bits\n      replace all calls to RF, updating V with randomly-sampled bits\n\nR R R P P P\n\n---\n\nOi: Generate+Update: modified version of PRG that does Generate n + Update with random sampling if < i, and PRF otherwise\n\nG_i_si_close: \n\nShow\nR R P P P P and\nR R R P P P close\n(there's no induction on q. we have that the ith oracle call uses the oracle with random bits, so just show that the (i+1)th oracle calls in G_i and G_{i+1} are close)\n\n| Pr[G_i] - Pr[G_{i+1}] | <= PRF_advantage + Pr[collisions]\n(note that the randomly sampled V is first updated AGAIN in the new version of GenUpdate)\n\nPr[collisions] = \n\"probability that /given the maximum input size n to any call/, the RF will be called on two identical inputs within the same oracle call\"\n\nthe RF used both within the Generate loop and outside to generate the key?\nbut K <- RF(K, V || 0x00) so there can't be any collision within this call? *)\n\n(* ----------------------------------- *)\n(* Scratch work section -- ignore *)\n\nParameter A_t : Bvector eta -> bool.\n\nDefinition g1_test :=\n  x <-$ {0,1}^eta;\n  ret (A_t x).\n\nDefinition g2_test :=\n  x <-$ {0,1}^eta;\n  ret (A_t x).\n\nTheorem g1_g2_eq : Pr[g1_test] == Pr[g2_test].\nProof.\n  unfold g1_test. unfold g2_test.\n  comp_skip.\n  (* this also works, but you don't have to translate to prhl *)\n  (* not clear on exactly what comp_skip is doing *)\n  (* fcf_to_prhl_eq. *)\n  (* comp_skip. *)\nQed.\n\n(* ------ *)\n(* How to get the state from an OracleComp: need to fully apply it with type params, oracle, and initial state *)\n\n(* Definition GenUpdate_oc_test (state : KV) (n : nat) : *)\n(*   OracleComp (list bool) (Bvector eta) (list (Bvector eta) * KV) := *)\n(*   [k, v_0] <-2 state; *)\n(*   v <--$ (OC_Query _ (to_list v_0)); (* ORACLE USE *) *)\n(*   [bits, v'] <--$2 Gen_loop_oc v n; *)\n(*   k' <--$ (OC_Query _ (to_list v' ++ zeroes)); (* ORACLE USE *) *)\n(*   $ ret (bits, (k', v')). *)\n\nDefinition getState_test (n : nat) : Comp bool :=\n  [k, v] <-$2 Instantiate;\n  [x1, x2] <-$2 Gen_loop_oc v n _ _ rb_oracle nil; (* note here *)\n  ret true.\n\nParameter v_0 : Blist.\nCheck (OC_Query _ Blist).       (* ? *)\n\nParameter v : Bvector eta.\nParameter n : nat.\nCheck (Gen_loop_oc v n).\n(* Gen_loop_oc v n\n     : OracleComp (list bool) (Bvector eta)\n         (list (Bvector eta) * Bvector eta) *)\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/fcf/HMAC_DRBG_nonadaptive_oldnames.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2876750502777488}}
{"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\n\nRequire Import Cava.Arrow.ArrowExport.\nRequire Import Coq.Lists.List Coq.NArith.NArith Coq.Strings.String.\nFrom Coq Require Import Bool.Bvector.\nImport ListNotations.\n\nLocal Open Scope string_scope.\n\nSection notation.\n  Import KappaNotation.\n  Local Open Scope category_scope.\n  Local Open Scope kind_scope.\n\n  Definition counter n\n    : << Unit >> ~> Vector Bit n :=\n    <[\n      letrec counter = counter +% #1 in\n      counter\n    ]>.\nEnd notation.\n\nOpen Scope kind_scope.\n\nRequire Import Cava.Netlist.\n\nDefinition counter_3_Interface :=\n   sequentialInterface \"counter_3\" \"clk\" PositiveEdge \"rst\" PositiveEdge\n     [] [mkPort \"count\" (Signal.Vec Signal.Bit 3)] [].\n\nDefinition counter_3_netlist :=\n  build_netlist (closure_conversion (counter 3)) \"counter_3\" tt \"count\".\n\nDefinition counter_3_tb_inputs : list unit :=\n repeat tt 8.\n\nDefinition counter_3_tb_expected_outputs : list (Bvector.Bvector 3) :=\n  unroll_circuit_evaluation (closure_conversion (counter 3)) (repeat tt 8).\n\nDefinition counter_3_tb :=\n  testBench \"counter_3_tb\" counter_3_Interface\n            counter_3_tb_inputs counter_3_tb_expected_outputs.\n\n(* Monad test/CountBy/CountBy.v counter *)\nSection notation.\n  Import KappaNotation.\n  Local Open Scope category_scope.\n  Local Open Scope kind_scope.\n\n  Definition countBy n :=\n    <[ fun \"countBy\" i : Vector Bit n =>\n      letrec counter = counter +% i in\n      counter\n    ]>.\nEnd notation.\n\nDefinition countBySpec' (state: Bvector 8) (x : Bvector 8)\n  : Bvector 8 :=\n  N2Bv_sized 8 (Bv2N x + Bv2N state).\n\nDefinition countBySpec := countBySpec' (N2Bv_sized 8 0).\n\nLemma countByCorrect: forall (i : Bvector 8) s,\n                      snd (interp_sequential1 (module_to_expr (countBy 8) _) [existT _ (Vector Bit 8) s] i) = countBySpec' s i.\nProof.\n  intros.\n  cbv [interp_sequential1'].\n  cbv [countBy module_to_expr module_body countBySpec'] in *.\n  cbn -[VectorUtils.resize_default].\n  rewrite VectorUtils.resize_default_id.\n  rewrite N.add_comm.\n  rewrite Vector.map_id.\n  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/investigations/Arrow/arrow-examples/Counter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2876750502777488}}
{"text": "From PromisingLib Require Import Axioms.\n\nSet Implicit Arguments.\n\nNotation \" ~1 p\" := (fun x0 => ~ (p x0)) (at level 50, no associativity).\nNotation \" ~2 p\" := (fun x0 x1 => ~ (p x0 x1)) (at level 50, no associativity).\nNotation \" ~3 p\" := (fun x0 x1 x2 => ~ (p x0 x1 x2)) (at level 50, no associativity).\nNotation \" ~4 p\" := (fun x0 x1 x2 x3 => ~ (p x0 x1 x2 x3)) (at level 50, no associativity).\n\nNotation \"p /1\\ q\" := (fun x0 => and (p x0) (q x0)) (at level 50, no associativity).\nNotation \"p /2\\ q\" := (fun x0 x1 => and (p x0 x1) (q x0 x1)) (at level 50, no associativity).\nNotation \"p /3\\ q\" := (fun x0 x1 x2 => and (p x0 x1 x2) (q x0 x1 x2)) (at level 50, no associativity).\nNotation \"p /4\\ q\" := (fun x0 x1 x2 x3 => and (p x0 x1 x2 x3) (q x0 x1 x2 x3)) (at level 50, no associativity).\n\nNotation \"p =1= q\" := (forall x0, iff (p x0) (q x0)) (at level 50, no associativity).\nNotation \"p =2= q\" := (forall x0 x1, iff (p x0 x1) (q x0 x1)) (at level 50, no associativity).\nNotation \"p =3= q\" := (forall x0 x1 x2, iff (p x0 x1 x2) (q x0 x1 x2)) (at level 50, no associativity).\nNotation \"p =4= q\" := (forall x0 x1 x2 x3, iff (p x0 x1 x2 x3) (q x0 x1 x2 x3)) (at level 50, no associativity).\n\nNotation \"p -1 q\" := (p /1\\ ~1 q) (at level 50).\nNotation \"p -2 q\" := (p /2\\ ~2 q) (at level 50).\nNotation \"p -3 q\" := (p /3\\ ~3 q) (at level 50).\nNotation \"p -4 q\" := (p /4\\ ~4 q) (at level 50).\n\nDefinition singleton A (a0: A): A -> Prop := eq a0.\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/drf/yjtac.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2876750427704903}}
{"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(*  Pierre Casteran \n    LaBRI, Université Bordeaux 1, and Inria Futurs (Logical)\n*)\n\n(* Veblen \"pre\" Normal form (for Gamma0) *)\n\nRequire Import EPSILON0.\n\nRequire Import Arith.\nRequire Import List.\nRequire Import Omega. (* ( :-) *)\nRequire Import Compare_dec.\nRequire Import Relations.\nRequire Import Wellfounded.\nRequire Import Max.\n\nRequire Import Tools.\nRequire Import More_nat.\nRequire Import AccP.\nRequire Import not_decreasing.\nRequire Import EPSILON0.\nRequire Import More_nat.\nRequire Import Gamma0_prelude.\nRequire Import Gamma0_length.\n\nRequire Import term.\nRequire Import rpo.\n\nSet Implicit Arguments.\nUnset Standard Proposition Elimination Names.\n\n(* About nf *)\n\nLemma nf_a : forall a b n c, nf (cons a b n c) -> nf a.\nProof.\n inversion_clear 1;auto.\nQed.\n\nLemma nf_b : forall a b n c, nf (cons a b n c) -> nf b.\nProof.\n inversion_clear 1;auto.\nQed.\n\nLemma nf_c : forall a b n c, nf (cons a b n c) -> nf c.\nProof.\n inversion_clear 1;auto with T2.\nQed.\n\nHint Resolve nf_a nf_b nf_c : T2.\n\n\n\nLtac nf_inv := ((eapply nf_a; eassumption)|| \n                (eapply nf_b; eassumption)|| \n                (eapply nf_c; eassumption)).\n\n\n(* About lt *)\n\n\nLemma zero_lt_succ : forall alpha, zero < succ alpha.\nProof.\n destruct  alpha;simpl.\n auto with T2.\n case alpha1;case alpha2;auto with T2.\nQed.\n\n\nLemma not_lt_zero : forall alpha, ~ alpha < zero. \nProof.\n red; inversion 1.\nQed.\n\n\nLemma lt_irr : forall alpha, ~ alpha < alpha.\nProof.\n induction alpha.\n apply not_lt_zero. \n red; inversion_clear 1.\n case (IHalpha1 H0).\n case (IHalpha2 H0).\n case (IHalpha1 H0).\n case (IHalpha1 H0).\n case (Arith.Lt.lt_irrefl _ H0).\n case IHalpha3; auto.\nQed.\n\n\nLtac lt_clean := \n  try (match goal with \n        [ineq : lt ?a zero |- _ ] => case (not_lt_zero ineq);auto\n       |[ineq : Peano.lt ?a 0 |- _ ] => case (lt_n_O a);auto\n       |[ref : lt ?a ?a |- _] => case (lt_irr ref);auto\n       |[ref : Peano.lt ?a ?a |- _] => case (lt_irr ref);auto\n  end).\n\n\nLemma le_zero_alpha : forall alpha, zero <= alpha.\nProof.\n intro alpha; case alpha; auto with T2.\nQed.\n\nLemma psi_le_cons : forall alpha beta n gamma,\n                       [alpha, beta] <=  cons alpha beta n gamma.\nProof.\n  intros;case n; auto with arith T2.\n case gamma;auto with arith T2.\nQed.\n\nHint Resolve psi_le_cons le_zero_alpha: T2.\n\nLemma le_psi_term_le : forall alpha beta, alpha <= beta ->\n                                          psi_term alpha <= psi_term beta.\nProof.\n destruct 1.\n subst beta;auto with T2.\n generalize H;case alpha;simpl.\n auto with T2.\n case beta.\n intros;lt_clean.\n simpl;inversion_clear 1; auto with T2.  \nQed.\n\n\nLemma le_inv_nc : forall a b n c  n' c',\n    cons a b n c <= cons a b n' c' -> (n<n')%nat \\/ n=n' /\\ c<= c'.\nProof.\n inversion_clear 1.\n injection H0;intros;right;auto with T2.\n inversion_clear H0; try lt_clean;auto with T2.\nQed.\n\n\nLemma lt_than_psi : forall a b n c a' b',\n      cons a b n c < [a',b'] ->\n      [a,b]<[a',b']. \nProof.\n inversion_clear 1;try lt_clean;auto with T2.\nQed.\n\n\n(* in order to establish trichotomy, we first use a measure on pair of\n    terms *)\nSection lemmas_on_length.\nOpen Scope nat_scope.\n \nLemma tricho_lt_2 : forall a1 a2 b1 b2 n1 n2 r1 r2,\n    length a1 + length a2 < \n    length (cons a1 b1 n1 r1) +\n    length (cons a2 b2 n2 r2).\nProof.\n intros.\n apply plus_lt_compat; apply length_a. \nQed.\n\n\nLemma tricho_lt_2' : forall a1 a2 b1 b2 n1 n2 r1 r2,\n    length b1 + length (cons a2 b2 0 zero)  < \n    length (cons a1 b1 n1 r1) +\n    length (cons a2 b2 n2 r2).\n intros;apply plus_lt_le_compat.\n apply length_b.\n simpl.\n intros; apply le_lt_n_Sm.\n match goal with \n   [ |- ?a <= ?b + ?c + ?d] => rewrite (plus_comm (b + c) d) end.\n apply le_plus_trans.\n replace (Max.max (length b2) 0) with (length b2).\n generalize (Max.max_dec (length a2) (length b2)).\n destruct 1.\n rewrite  e.\n repeat rewrite plus_0_r.\n apply plus_le_compat.\n apply le_max_l.\n apply le_max_l.\n repeat rewrite plus_0_r.\n apply plus_le_compat;\n apply  max_le_regL;\n apply le_max_l.\n rewrite max_l; auto with arith.\nQed.\n\n\n\nLemma tricho_lt_3 : forall a1 a2 b1 b2 n1 n2 r1 r2,\n    length b1 + length b2  <   \n     length (cons a1 b1 n1 r1) +  length (cons a2 b2 n2 r2).\n\n intros;apply plus_lt_compat; apply length_b.\nQed.\n\n\nLemma tricho_lt_4 : forall a1 a2 b1 b2 n1 n2 r1 r2,\n    length a2 + length a1 < \n    length (cons a1 b1 n1 r1) +\n    length (cons a2 b2 n2 r2).\nProof.\n intros.\n rewrite plus_comm.\n apply plus_lt_compat; apply length_a. \nQed.\n\nLemma tricho_lt_4' : forall a1 a2 b1 b2 n1 n2 c1 c2,\n    length (cons a1 b1 0 c1) + length b2  < \n    length (cons a1 b1 n1 c1) +\n    length (cons a2 b2 n2 c2).\n intros; apply plus_le_lt_compat.\n case n1.\n auto. \n intros;apply lt_le_weak;apply length_n; auto with arith.\n apply length_b.\nQed.\n\nLemma tricho_lt_5 : forall a1 a2 b1  n1 n2 c1 c2,\n    length a2 + length a1  < \n    length (cons a1 b1 n1 c1) +\n    length (cons a2 (cons a1 b1 0 zero)  n2 c2).\n intros; rewrite plus_comm;apply plus_lt_compat; apply length_a.\nQed.\n\nLemma tricho_lt_7 : forall a1 b1  n1  c1 c2,\n    length c1 + length c2 < \n    length (cons a1 b1 n1 c1) +\n    length (cons a1 b1 n1 c2).\nProof.\n intros.\n apply plus_lt_compat;\n apply length_c. \nQed.\n\n\nEnd lemmas_on_length.\n\nHint Resolve tricho_lt_7 tricho_lt_5 tricho_lt_4 tricho_lt_4' tricho_lt_3 tricho_lt_2 tricho_lt_2 : T2.\n\n\nLemma tricho_aux : forall l, forall t t', (length t + length t' < l)%nat  ->\n                    { t < t'}+{t = t'}+{t'<  t}.\nProof.\n induction l.\n intros. \n elimtype False. \n inversion H.\n intros t t'.\n case t;case t'.\n left;right;auto with T2.\n left;left;constructor.\n right;constructor.\n intros.\n assert (length t3 + length t0 < l)%nat.\n eapply lt_lt_Sn.\n eapply tricho_lt_2.\n eauto with T2.\n case (IHl _ _ H0).\n destruct 1.\n assert (length t4 + length (cons t0 t1 0 zero) < l)%nat.\n eapply lt_lt_Sn.\n eapply tricho_lt_2'.\n eauto.\n case (IHl _ _ H1).\n destruct 1.\n left;left.\n constructor 2;auto with T2.\n subst t4.\n right.\n constructor 5;auto with T2.\n intro.\n right.\n constructor 4;auto with T2.\n subst t3.\n assert (length t4 + length t1 < l)%nat.\n  eapply lt_lt_Sn.\n  eapply tricho_lt_3.\n  eauto with T2.\n  case (IHl _ _ H1).\n destruct 1.\n left;left. \n constructor 3. \n auto with T2.\n subst t4.\n case (lt_eq_lt_dec n0 n).\n destruct 1.\n left;left.\n constructor 6.\n auto with T2.\n subst n.\n assert (length t5 + length t2 < l)%nat.\n eapply lt_lt_Sn.\n eapply tricho_lt_7.\n eauto with T2.\n case (IHl _ _ H2).\n destruct 1.\n left;left.\n constructor 7;auto with T2.\n subst t2.\n left;right;trivial.\n intro.\n right;constructor 7;auto with T2.\n right.\n constructor 6;auto with T2.\n intro.\n right;constructor 3;auto with T2.\n intro.\n assert  (length t1 + length (cons t3 t4 0 zero) < l)%nat.\n eapply lt_lt_Sn.\n eapply tricho_lt_2'.\n rewrite plus_comm.\n eauto with T2.\n case (IHl _ _ H1).\n destruct 1.\n right.\n constructor 2;auto with T2.\n subst t1.\n left;left;constructor 5;auto with T2.\n left;left;constructor 4;auto with T2.\nDefined.\n\n\nDefinition trichotomy_inf : forall t t', {t < t'}+{t=t'}+{t'<  t}.\n intros t t'.\n eapply tricho_aux.\n eapply lt_n_Sn.\nDefined.\n\n\nDefinition lt_ge_dec : forall t t', {t<t'}+{t'<=t}.\n intros t t'; case (trichotomy_inf t t').\n destruct 1 ;[left;auto with T2| right;auto with T2].\n auto with T2.\nDefined.\n\n(* we should replace the following definition by a direct one\n  by fixpoint (structural argument : sum of lengths)\n  It will make the proof of compare_reflect quite harder\n*)\n\nDefinition compare : T2 -> T2 -> comparison.\n intros t1 t2.\n case (trichotomy_inf t1 t2).\n destruct 1.\n exact Lt.\n exact Eq.\n intro; exact Gt.\nDefined.\n\n\n(* introduces an hypothesis Hname for t < t', t = t', and t' < t\n    (3 subgoals) *)\n\nLtac tricho t t' Hname := case (trichotomy_inf t t');\n                           [intros [Hname|Hname] | intro Hname].\n\n\nSection trans_proof.\n Variables a1 b1 c1 a2 b2 c2 a3 b3 c3:T2.\n Variables n1 n2 n3:nat.\n\n Hypothesis H12 : cons a1 b1 n1 c1 <  cons a2 b2 n2 c2.\n Hypothesis H23 : cons a2 b2 n2 c2 <  cons a3 b3 n3 c3.\n\n Hypothesis induc : forall t t' t'', \n                     (length t + length t' + \n                     length t'' < \n                     length (cons a1 b1 n1 c1) +\n                     length (cons a2 b2 n2 c2) + \n                     length (cons a3 b3 n3 c3))%nat  ->\n                     lt t t' -> lt t' t'' -> lt t t''.\n\n\n\n Lemma trans_aux :  cons a1 b1 n1 c1 < cons a3 b3 n3 c3.\n Proof .\n inversion H12.\n inversion H23.\n constructor 2.\n apply induc with a2.\n generalize (length_a  a1 b1 n1 c1).\n generalize (length_a  a2 b2 n2 c2).\n generalize (length_a  a3 b3 n3 c3).\n clear induc.\n omega.\n auto with T2.\n auto with T2.\n assert (lt (cons a2 b2 0 zero) (cons a3 b3 0 zero)).\n auto with T2.\n apply induc with (cons a2 b2 0 zero).\n generalize (length_b  a1 b1 n1 c1).\n generalize (length_psi a2 b2 n2 c2).\n generalize (length_psi a3 b3 n3 c3).\n clear induc.\n omega.\n auto with T2.\n auto with T2.\n subst a3.\n constructor 2.\n auto with T2.\n apply induc with (cons a2 b2 0 zero).\n 2:auto with T2.\n \n 2:constructor 3;auto with T2.\n generalize (length_b a1 b1 n1 c1); generalize (length_psi a2 b2 n2 c2);\n  generalize (length_psi a2 b3 n3 c3);clear induc;omega.\n tricho a1 a3 H20.\n constructor 2.\n auto with T2.\n apply induc with (cons a2 b2 0 zero).\n 2:auto with T2.\n generalize (length_b a1 b1 n1 c1);generalize(length_psi a2 b2 n2 c2);\n generalize (length_psi a3 b3 n3 c3);clear induc;omega.\n constructor 4; auto with T2.\n clear H;subst a1.\n constructor 3.\n apply induc with (cons a2 b2 0 zero);eauto with T2.\n generalize (length_b a3 b1 n1 c1); \ngeneralize (length_b a3 b3 n3 c3); \ngeneralize (length_psi a2 b2 n2 c2);clear induc;omega. \n constructor 4.\n auto with T2.\n apply induc with (cons a2 b2 0 zero);eauto with T2.\n  generalize (length_psi a1 b1 n1 c1); \ngeneralize (length_psi a2 b2 n2 c2); \ngeneralize (length_b a3 b3 n3 c3);clear induc;omega.\ntricho a1 a3 H20.\nconstructor 2;auto with T2.\n apply induc with  (cons a2 b2 0 zero);eauto with T2.\n subst b3.\ngeneralize (length_b a1 b1 n1 c1); \ngeneralize (length_psi a2 b2 n2 c2); \ngeneralize (length_psi a3 (cons a2 b2 0 zero) n3 c3);\n clear induc;omega. \nclear H15 H9 H11 H17 H18 ;subst a3.\nconstructor 3.\nauto with T2.\n constructor 4;auto with T2.\n clear H9 H11 H4 H5.\n subst a3; subst b3.\n constructor 2;auto with T2.\n clear H9 H11 H4 H5.\n subst a3;subst b3.\n constructor 2;auto with T2.\n clear H H1 H2 H3 H5 H6 H7.\n clear beta1 beta2 gamma1 gamma2.\n inversion H23.\n constructor 2;auto with T2.\n apply induc with b2;auto with T2.\ngeneralize (length_b a1 b1 n1 c1); \ngeneralize (length_b a2 b2 n2 c2); \ngeneralize (length_psi a3 b3 n3 c3);clear induc;omega. \nconstructor 3;auto with T2.\neapply induc with b2;auto with T2.\ngeneralize (length_b a1 b1 n1 c1); \ngeneralize (length_b a2 b2 n2 c2); \ngeneralize (length_b a3 b3 n3 c3);clear induc;omega. \nconstructor 4;auto with T2.\napply induc with (cons a2 b2 0 zero);auto with T2.\npattern a2 at 1;rewrite <- H4.\ngeneralize (length_psi a1 b1 n1 c1); \ngeneralize (length_psi a2 b2 n2 c2); \ngeneralize (length_b a3 b3 n3 c3);clear induc;omega. \nclear H;subst a2.\nconstructor 4;auto with T2.\nrewrite <- H7.\nconstructor 3;auto with T2.\nrewrite <- H7.\nconstructor 3;auto with T2.\ninversion H23;auto with T2.\n\nassert (lt (cons a1 b1 0 zero) (cons a3 b3 0 zero)).\n apply induc with b2. \n   generalize (length_psi  a1 b1 n1 c1).\n  generalize (length_b a2 b2 n2 c2).\n  generalize (length_psi a3 b3 n3 c3);\n clear induc;\n omega.\n\n auto with T2.\n auto with T2.\ninversion_clear H20;auto with T2.\ninversion H21.\ninversion H21.\nsubst a3.\nconstructor 4.\nauto with T2.\napply induc with b2.\ngeneralize (length_psi a1 b1 n1 c1);\ngeneralize (length_b a2 b2 n2 c2);\ngeneralize (length_b a2 b3 n3 c3);clear induc;omega.\nauto with T2.\nauto with T2.\n constructor 4.\n apply induc with a2.\n generalize (length_a a1 b1 n1 c1);\ngeneralize (length_a a2 b2 n2 c2);\ngeneralize (length_a a3 b3 n3 c3);clear induc; omega.\n auto with T2.\n auto with T2.\napply induc with (cons a2 b2 0 zero).\n  generalize (length_psi a1 b1 n1 c1);\ngeneralize (length_psi a2 b2 n2 c2);\ngeneralize (length_b a3 b3 n3 c3);clear induc; omega.\n\n auto with T2.\nauto with T2.\n\nconstructor 4.\napply induc with a2;auto with T2.\n\n  generalize (length_a a1 b1 n1 c1); \ngeneralize (length_a a2 b2 n2 c2); \ngeneralize (length_a a3 b3 n3 c3);clear induc;omega.\nconstructor 4;auto with T2.\n\n\nclear H9 H11; subst b3; subst a3.\n\nconstructor 4.\nauto with T2.\nauto with T2.\n\nclear H9 H11;subst b3;subst a3.\nconstructor 4;auto with T2.\nsubst b2.\ninversion H23;auto with T2.\ninversion_clear H17;auto with T2.\ninversion H18.\ninversion H18.\nsubst a3.\nconstructor 4;auto with T2.\n\nconstructor 4;auto with T2.\napply induc with a2;auto with T2.\n\n generalize (length_a a1 b1 n1 c1); \ngeneralize (length_a a2 (cons a1 b1 0 zero) n2 c2); \ngeneralize (length_a a3 b3 n3 c3);clear induc;omega.\n\n apply induc with (cons a2 (cons a1 b1 0 zero) 0 zero);auto with T2.\n\n\n \n generalize (length_psi  a1 b1 n1 c1); \ngeneralize (length_psi a2 (cons a1 b1 0 zero) n2 c2); \ngeneralize (length_b a3 b3 n3 c3) ;clear induc;omega.\n constructor 4.\napply induc with a2;auto with T2.\n\n\n\n\n generalize (length_a a1 b1 n1 c1); \ngeneralize (length_a a2 (cons a1 b1 0 zero) n2 c2); \ngeneralize (length_a a3 b3 n3 c3);clear induc;omega.\nconstructor 5;auto with T2.\nsubst a3.\nconstructor 5.\nauto with T2.\nsubst a3.\nconstructor 5;auto with T2.\nsubst a2; subst b2.\ninversion H23;auto with T2.\nsubst a3;subst b3.\nconstructor 6.\neauto with T2 arith.\nsubst b3;subst a3;subst n3.\nconstructor 6;auto with T2.\n\nclear H H1;subst a1;subst b1.\nsubst n2.\ninversion H23;auto with T2.\nconstructor 7.\napply induc with c2;auto with T2.\n  generalize (length_c a2 b2 n1 c1); \ngeneralize (length_c a2 b2 n1 c2); \ngeneralize (length_c a3 b3 n3 c3);clear induc;omega.\n\nQed.\n\n\nEnd trans_proof.\n\nLemma transitivity0 : forall n, \n             forall t1 t2 t3, \n                (length t1 + length t2 + length t3  < n)%nat -> \n                 lt t1 t2 -> lt t2 t3 ->  lt t1 t3.\nProof.\n induction n.\n inversion 1.\n destruct t1; destruct t2; destruct t3.\n inversion 1.\n inversion 1.\n inversion 2.\n auto with T2.\n inversion 3.\n auto with T2.\n inversion 2.\n inversion 3.\n 2:inversion 3.\n inversion H0.\n intros.\n eapply trans_aux.\n eexact H0.\n auto with T2.\n intros.\n apply IHn with t'.\n omega.\n auto with T2.\n auto with T2.\nQed.\n \nTheorem transitivity : \n             forall t1 t2 t3, t1 < t2 -> t2 < t3 -> t1 < t3.\nProof.\n intros;\n apply transitivity0 with (S (length t1 + length t2 + length t3)) t2;\n auto with T2 arith.\nQed.\n\nTheorem le_lt_trans : forall alpha beta gamma, alpha <= beta -> \n                                               beta < gamma -> \n                                               alpha < gamma.\nProof.\n destruct 1.\n subst alpha;auto with T2.\n intros; eapply transitivity;eauto with T2.\nQed.\n\n\nTheorem  lt_le_trans : forall alpha beta gamma, alpha < beta ->\n                                                beta <= gamma -> \n                                                alpha < gamma.\n destruct 2.\n subst beta;auto with T2.\n eapply transitivity;eauto with T2.\nQed.\n\nTheorem le_trans : forall alpha beta gamma, alpha <= beta ->\n                                            beta <= gamma ->\n                                            alpha <= gamma.\nProof.\n destruct 1.\n subst beta;auto.\n intros;right;eapply lt_le_trans;eauto.\nQed.\n\nLemma psi_relevance : forall alpha beta n gamma  alpha' beta' n' gamma',\n        [alpha, beta] <  [alpha', beta'] ->\n        cons alpha beta n gamma <  cons alpha' beta' n' gamma'.\nProof.\n inversion 1.\n constructor 2;auto with T2.\n constructor 3;auto with T2.\n constructor 4;auto with T2.\n constructor 5;auto with T2.\n inversion H1.\n lt_clean. \nQed.\n\nLemma nf_inv_tail : forall a b n c , nf (cons a b n c) ->\n                                        c < [a,b].\nProof.\n  inversion_clear 1.\n  auto with T2.\n  apply psi_relevance;auto with T2.\nQed.\n\n\nTheorem lt_beta_psi : forall beta alpha, beta < [alpha, beta].\n induction beta.\n auto with T2.\n intros.\n cut  (beta2 < [alpha, (cons beta1 beta2 n beta3)]).\n intro H.\n tricho beta1 alpha H0.\n auto with T2.\n subst alpha.\n  constructor 3.\n apply lt_le_trans with [beta1, beta2];auto with T2.\n case (psi_le_cons beta1 beta2 n beta3).\n intro.\n pattern (cons beta1 beta2 n beta3) at 2.\n rewrite <- H1.\n unfold psi;constructor 5;auto with T2.\n unfold psi; constructor 4;auto with T2.\n assert ([alpha, beta2] < [alpha, (cons beta1 beta2 n beta3)]).\n  constructor 3. \n apply lt_le_trans with [beta1, beta2]; auto with T2.\n  eapply transitivity;eauto with T2.\nQed.\n\n\nLemma lt_beta_cons :  forall alpha beta n gamma, \n                            beta < cons alpha beta n gamma.\nProof.\n intros;eapply lt_le_trans.\n 2:eapply psi_le_cons.\n apply lt_beta_psi.\nQed.\n\n\n\nTheorem lt_alpha_psi : forall alpha beta, alpha < [alpha, beta].\nProof.\n induction alpha.\n unfold psi;auto with T2.\n intros.\n constructor 2.\n apply lt_le_trans with [alpha1,alpha2];auto with T2.\n  apply lt_le_trans with [ alpha1,alpha2];auto with T2.\n apply lt_beta_psi.\n right;constructor 2.\n apply lt_le_trans with [alpha1,alpha2];auto with T2.\n apply lt_le_trans with [ alpha1,alpha2];auto with T2.\n apply lt_beta_psi.\n right.\n constructor 2.\n  apply lt_le_trans with [ alpha1,alpha2];auto with T2.\n apply transitivity with [alpha2, beta];auto with T2.\n constructor 2.\n apply lt_beta_cons.\n apply lt_beta_psi.\nQed.\n\n\nLemma lt_alpha_cons :  forall alpha beta n gamma, \n                            alpha < cons alpha beta n gamma.\nProof.\n intros;eapply lt_le_trans.\n 2:eapply psi_le_cons.\n apply lt_alpha_psi.\nQed.\n\nHint Resolve lt_beta_cons lt_alpha_cons : T2.\n\n\n\nLemma le_cons_tail : forall alpha beta n gamma gamma', gamma <= gamma' -> \n                                cons alpha beta n gamma <= \n                                cons alpha beta n gamma'.\n destruct 1.\n subst gamma';left;auto with T2.\n right;auto with T2.\nQed.\n\n\n(* terms in normal form *)\n\nLemma nf_omega : nf omega.\n compute; auto with T2.\nQed.\n\nLemma nf_epsilon0 : nf epsilon0.\n compute.\n auto with T2.\nQed.\n\nLemma nf_epsilon : forall alpha, nf alpha -> nf (epsilon alpha).\nProof.\n intros; compute; auto with T2. \nQed.\n\n\n\n \nLemma ordinal_finite : forall n, nf (finite n).\n destruct n; compute;auto with T2.\nQed.\n\nLemma nf_finite_inv : forall gamma n, nf (cons zero zero n gamma) -> \n                     gamma = zero.\n inversion 1;auto with T2.\n inversion H4; lt_clean; auto with T2.\nQed.\n\n\n\nLemma lt_tail0: forall c, nf c -> c <> zero -> tail c < c.     \nProof.\n induction c.\n destruct 2;auto with T2.\n simpl.\n generalize IHc3; case c3.\n auto with T2.\n intros.\n apply psi_relevance.\n inversion_clear H.\n auto with T2.\nQed.\n\n\nLemma lt_tail: forall a b n c, nf (cons a b n c) ->  c < cons a b n c. \nProof.\n intros. \n replace c with (tail (cons a b n c)). \n apply lt_tail0.\n simpl;auto with T2.\n discriminate. \n trivial. \nQed.\n\n\nInductive subterm : T2 -> T2 -> Prop :=\n | subterm_a : forall a b n c, subterm a (cons  a b n c)\n | subterm_b : forall a b n c, subterm b (cons a b n c)\n | subterm_c : forall a b n c, subterm c (cons a b n c)\n | subterm_trans : forall t t1 t2, subterm t t1 -> subterm t1 t2 ->\n                                                   subterm t t2.\n\nLemma nf_subterm : forall alpha beta, subterm alpha beta ->\n                                       nf beta -> \n                                       nf alpha.\nProof.\n induction 1; intros; try nf_inv.\n auto.\nQed.\n\n\n\nTheorem subterm_lt : forall alpha beta, subterm alpha beta -> nf beta ->\n     alpha < beta.\nProof.\n  induction 1;auto with T2.\n  intro;apply lt_tail;auto with T2.\n  intro; apply transitivity with t1;auto with T2.\n eapply IHsubterm1. \n eapply nf_subterm;eauto with T2.\nQed.\n\n\nLtac subtermtac :=\n match goal with \n[|- subterm ?t1 (cons ?t1 ?t2 ?n ?t3)] =>\n                                              constructor 1\n | [|- subterm ?t2 (cons ?t1 ?t2 ?n ?t3)] =>\n                                              constructor 2\n | [|- subterm ?t3 (cons ?t1 ?t2 ?n ?t3)] =>\n                                              constructor 3\n| [|- subterm ?t4 (cons ?t1 ?t2 ?n ?t3)] =>\n  ((constructor 4 with t1; subtermtac)     ||\n (constructor 4 with t2; subtermtac)       ||\n (constructor 4 with t3; subtermtac))\n    end.\n\nLemma le_one_cons : forall a b n c, one <= cons a b n c.\nProof.\n unfold one.\n intros. apply le_trans with [a,b];auto with T2.\n case a; case b; auto with T2.\nQed.\n\nHint Resolve le_one_cons : T2.\nLemma finite_lt_omega : forall n, finite  n <  omega.\nProof.\n  destruct n;compute;auto with T2.\nQed.\n\nLemma omega_lt_epsilon0 : omega <  epsilon0.\nProof.\n compute; auto with T2.\nQed.\n\nLemma omega_lt_epsilon : forall alpha, omega < epsilon alpha.\nProof.\n compute;auto with T2.\nQed.\n\n\nLemma lt_one_inv : forall alpha, alpha < one -> alpha = zero.\nProof.\n inversion 1; lt_clean.\n auto with T2.\nQed.\n\n\nLemma lt_cons_omega_inv : forall alpha beta n gamma, \n   cons alpha beta n gamma < omega ->\n   nf (cons alpha beta n gamma) ->\n   alpha = zero /\\ beta = zero /\\ gamma = zero.\nProof.\n inversion_clear 1; lt_clean.\n replace beta with zero.\n inversion 1; lt_clean;auto with T2.\n  inversion  H5; lt_clean.\n inversion H0;lt_clean;auto with T2.\n inversion H1; lt_clean;auto with T2.\nQed.\n\n\nLemma lt_omega_inv : forall alpha, nf alpha -> alpha < omega ->\n                        {n:nat | alpha = finite n}.\nProof.\n intros a; case a.\n exists 0;simpl.\n auto with T2.\n intros.\n case (lt_cons_omega_inv H0);auto with T2.\n destruct 2;intros.\n exists (S n);auto with T2.\n simpl.\n subst t;subst t1;subst t0; auto with T2.\nQed.\n\nLemma lt_omega_is_finite : forall alpha, nf alpha -> alpha < omega -> \n                                         is_finite alpha.\nProof.\n intros alpha N_alpha H; case (lt_omega_inv N_alpha H).\n destruct x; intro e;rewrite e; simpl; constructor.\nQed.\n\n \n\n\nTheorem lt_compat : forall n p, finite n <  finite p -> \n                               (n < p)%nat.\nProof.\n destruct n;simpl.\n destruct p.\n inversion 1.\n auto with T2 arith.\n destruct p;simpl.\n inversion 1.\n inversion_clear 1;try lt_clean;auto with arith T2.\nQed.\n\n\nTheorem lt_compatR : forall n p, (n <p)%nat -> \n                     finite n <  finite p .\nProof.\n destruct n;simpl.\n destruct p.\n inversion 1.\n simpl;auto with T2.\n destruct p.\n intros;lt_clean.\n simpl; auto with arith T2.\nQed.\n\nLemma finite_is_finite : forall n, is_finite (F n).\nProof.\n destruct n;simpl;constructor.\nQed.\n\nLemma is_finite_finite : forall alpha, is_finite alpha ->\n                                     {n : nat | alpha = F n}.\nProof.\n destruct 1.\n exists 0;simpl;auto with T2.\n exists (S n);simpl;auto with T2.\nQed.\n\n\n\n(* the following proof won't be so trivial, when compare is\n    defined directly !!! *)\n\nLemma compare_reflect : forall c c', match compare c c' with\n                                    |   Lt => c < c' \n                                    |   Eq => c = c'\n                                    |   Gt => c' <  c\n                                    end.\nProof.\n unfold compare.\n intros; case (trichotomy_inf c c');auto.\n destruct s;auto with T2.\nQed.\n\n\nLemma compare_lt_rw : forall alpha beta, compare alpha beta = Lt -> \n                                         alpha < beta.\nProof.\n intros alpha beta; generalize (compare_reflect alpha beta).\n case (compare alpha beta);(try discriminate 2; auto with T2).\nQed.\n\n\nLemma compare_eq_rw : forall alpha beta, compare alpha beta = Eq -> \n                                         alpha = beta.\nProof.\n intros alpha beta; generalize (compare_reflect alpha beta).\n case (compare alpha beta);(try discriminate 2; auto with T2).\nQed.\n\nLemma compare_gt_rw : forall alpha beta, compare alpha beta = Gt ->  \n                                         beta < alpha.\nProof.\n intros alpha beta; generalize (compare_reflect alpha beta).\n case (compare alpha beta);(try discriminate 2; auto with T2).\nQed.\n\nImplicit Arguments compare_gt_rw [alpha beta].\nImplicit Arguments compare_lt_rw [alpha beta].\nImplicit Arguments compare_eq_rw [alpha beta].\n\n\nHint Resolve compare_eq_rw compare_lt_rw compare_gt_rw.\n\nLemma compare_rw_lt : forall alpha beta, alpha < beta ->\n                    compare alpha beta = Lt.\nProof.\n intros; generalize (compare_reflect alpha beta). \n case (compare alpha beta).\n intro;subst beta;case (lt_irr H);auto with T2.\n auto .\n intro; case (lt_irr (alpha:=alpha)).\n eapply transitivity;eauto with T2.\nQed.\n\nLemma compare_rw_eq : forall alpha beta, alpha = beta ->\n                    compare alpha beta = Eq.\nintros; generalize (compare_reflect alpha beta). \ncase (compare alpha beta).\nauto with T2.\nintro H0;subst beta;case (lt_irr H0).\nintro H0;subst beta;case (lt_irr H0).\nQed.\n\nLemma compare_rw_gt : forall alpha beta, beta < alpha ->\n                    compare alpha beta = Gt.\nintros; generalize (compare_reflect alpha beta). \ncase (compare alpha beta).\nintro H0;subst beta;case (lt_irr H).\nintro; case (lt_irr (alpha:=alpha)).\neapply transitivity;eauto with T2.\nauto with T2.\nQed.\n\n\n\n\n(* plus is defined here, because it requires decidible comparison *)\n\nFixpoint plus (t1 t2 : T2) {struct t1}:T2 :=\n  match t1,t2 with\n |  zero, y  => y\n |  x, zero => x\n |  cons a b n c, cons a' b' n' c' =>\n      (match compare (cons a b 0 zero)\n                        (cons a' b' 0 zero)\n                             with | Lt => cons a' b' n' c'\n                                  | Gt =>\n                                       (cons a b n\n                                              (c +\n                                                 (cons a' b' n' c')))\n                                  | Eq  => (cons a b (S(n+n')) c')\n       end)\n end\nwhere \"alpha + beta\" := (plus alpha beta): g0_scope.\n\n\nLemma plus_alpha_0 : forall alpha,  alpha + zero = alpha.\nProof.\n intro alpha; case alpha ;trivial.\nQed.\n\n\n\nLemma lt_succ : forall a,  a < succ a.\n induction a;simpl;auto with T2.\n case a1;auto with arith T2.\n case a2; auto with arith T2.\nQed.\n\nTheorem lt_succ_le : forall a b,  a < b -> \n                                         nf b -> \n                                         succ a <= b.\nProof.\n  induction a.\n  inversion 1.\n  simpl.\n  auto with T2.\n  generalize IHa3; case a1; case a2.\n simpl.\n inversion 2.\nright; constructor 2.\n auto with T2.\n auto with T2.\n right;constructor 3;auto with T2.\n lt_clean.\n lt_clean.\n\n inversion H5.\n\n case gamma2.\n left;auto with T2.\n right;auto with T2.\n right;constructor 6.\n auto with arith T2.\n Focus 2.\n simpl.\n intros. \n inversion H.\n right;constructor 2;auto with T2.\n right;constructor 3;auto with T2.\n inversion H5.\n inversion H5.\n inversion H6.\n inversion H6.\n inversion H6.\n \n \n right;constructor 6.\n auto with arith T2.\n \n right;constructor 6.\n auto with arith T2.\n\n apply le_cons_tail.\n apply IHa0.\n auto.\n subst b.\n inversion H0;auto with T2.\n inversion 1.\n subst gamma2.\n inversion H5.\n inversion H11.\n inversion H17.\n inversion H16.\n inversion H24.\n inversion H16.\n inversion H16.\n\n simpl.\n intros.\n  inversion H.\n right;constructor 2;auto with T2.\n right;constructor 3;auto with T2.\n right;constructor 4.\n auto.\n auto.\n right;constructor 5;auto with T2.\n right;constructor 6;auto with T2.\n Focus 2.\n intros.\n simpl.\n inversion H.\n right;constructor 2;auto with T2.\n right;constructor 3;auto with T2.\n right;constructor 4;auto with T2.\n right;constructor 5;auto with T2.\n right; constructor 6;auto with T2. \napply le_cons_tail;auto with T2.\n auto with T2.\n auto with T2.\n apply IHa0;auto with T2.\n subst b.\n inversion H0.\n constructor.\n auto with T2.\n apply le_cons_tail;auto with T2.\n  apply IHa0;auto with T2.\n  subst b.\n inversion H0.\n constructor.\n auto with T2.\nQed.\n\n\n\n\n\n  \nLemma succ_lt_le : forall a b, nf a -> nf b -> a < succ b -> a <= b. \n intros.\n tricho a b H2; auto with T2.\n generalize (lt_succ_le H2 H).\n intro.\n case (lt_irr (alpha:=succ b)).\n eapply le_lt_trans;eauto with T2.\nQed.\n\n\nLemma succ_of_cons : forall a b n c, zero< a \\/ zero< b ->\n                       succ (cons a b n c)= cons a b n (succ c).\nProof.\n destruct a;destruct b;simpl;auto with T2.\n destruct 1 as [H|H];inversion H.\nQed.\n\n\n(* Well foundation *)\nModule  Gamma0_sig <: Signature.\n\n\n\nInductive symb0 : Set := nat_0 | nat_S | ord_zero | ord_psi | ord_cons.\n\nDefinition symb := symb0.\n\nLemma eq_symbol_dec : forall f1 f2 : symb, {f1 = f2} + {f1 <> f2}.\nProof.\n intros; decide equality.\nQed.\n\n(** The arity of a symbol contains also the information about built-in theories as in CiME *)\nInductive arity_type : Set :=\n  | AC : arity_type\n  | C : arity_type\n  | Free : nat -> arity_type.\n\nDefinition arity : symb -> arity_type :=\n  fun f => match f with\n                  | nat_0 => Free 0\n                  | ord_zero => Free 0\n                  | nat_S => Free 1\n                  | ord_psi => Free 2\n                  | ord_cons => Free 3\n                  end.\n\nEnd Gamma0_sig.\n\n\n\n(** * Module Type Variables. \n There are almost no assumptions, except a decidable equality. *) \nModule Vars <: Variables.\n\nInductive empty_set : Set := .\nDefinition var := empty_set.\n\nLemma eq_variable_dec : forall v1 v2 : var, {v1 = v2} + {v1 <> v2}.\nProof.\nintros; decide equality.\nQed.\n\nEnd Vars.\n\nModule  Gamma0_prec <: Precedence.\n\nDefinition A : Set := Gamma0_sig.symb.\nImport Gamma0_sig.\n\nDefinition prec : relation A :=\n   fun f g => match f, g with\n                      | nat_0, nat_S => True\n                      | nat_0, ord_zero => True\n                      | nat_0, ord_cons => True\n                      | nat_0, ord_psi  => True\n                      | ord_zero, nat_S => True\n                      | ord_zero, ord_cons => True\n                      | ord_zero, ord_psi => True\n                      | nat_S, ord_cons => True\n                      | nat_S, ord_psi => True\n                      | ord_cons, ord_psi => True\n                      | _, _ => False\n                      end.\n\n\nInductive status_type : Set :=\n  | Lex : status_type\n  | Mul : status_type.\n\nDefinition status : A -> status_type := fun f => Lex.\n\nLemma prec_dec : forall a1 a2 : A, {prec a1 a2} + {~ prec a1 a2}.\nProof.\nintros a1 a2; destruct a1; destruct a2;\n  ((right; intro; contradiction)||(left;simpl;trivial)).\nQed.\n\nLemma prec_antisym : forall s, prec s s -> False.\nProof.\nintros s; destruct s; simpl; trivial.\nQed.\n\nLemma prec_transitive : transitive A prec.\nProof.\nintros s1 s2 s3; destruct s1; destruct s2; destruct s3; simpl; intros; trivial; contradiction.\nQed.\n\nEnd Gamma0_prec.\n\nModule Gamma0_alg <: Term := term.Make (Gamma0_sig) (Vars).\nModule Gamma0_rpo <: RPO := rpo.Make (Gamma0_alg) (Gamma0_prec).\n\nImport Gamma0_alg.\nImport Gamma0_rpo.\nImport Gamma0_sig.\n\n(* coucou *)\n\nFixpoint nat_2_term (n:nat) : term :=\n  match n with 0 => (Term nat_0 nil)\n             | S p => Term nat_S ((nat_2_term p)::nil)\n  end.\n\n\n\n(** * Every (representation of a) natural number is less than\n a non zero ordinal *)\n\nLemma nat_lt_cons : forall (n:nat) t p  c , rpo (nat_2_term n) \n                                     (Term ord_cons (t::p::c::nil)).\n induction n;simpl.\n constructor 2.\n simpl; trivial.\n destruct 1.\n constructor 2.\n simpl; trivial.\n inversion_clear 1.\n subst s';apply IHn.\n case H0.\nQed.\n\n\nLemma nat_lt_psi : forall (n:nat) a b  , rpo (nat_2_term n) \n                                     (Term ord_psi (a::b::nil)).\n induction n;simpl.\n constructor 2.\n simpl; trivial.\n destruct 1.\n constructor 2.\n simpl; trivial.\n inversion_clear 1.\n subst s';apply IHn.\n case H0.\nQed.\n\n\n\nTheorem rpo_trans : forall t t1 t2, rpo t t1 -> rpo t1 t2 -> rpo t t2.\n intros.\n case (rpo_closure t2 t1 t);eauto with T2.\nQed.\n\n\nFixpoint T2_2_term (a:T2) : term := \nmatch a with\n zero => Term ord_zero nil\n|cons a b 0 zero => Term ord_psi (T2_2_term a :: T2_2_term b ::nil)\n|cons a b n c => Term ord_cons (Term ord_psi (T2_2_term a :: T2_2_term b ::nil) ::nat_2_term n ::\n                                T2_2_term c::nil)\nend.\n\nFixpoint T2_size (o:T2):nat :=\n match o with zero => 0\n            | cons a b n c => S (T2_size a + T2_size b + n + T2_size c)%nat\n         end.\n\n\nLemma T2_size1 : forall a b n c, (T2_size zero < T2_size (cons a b n c))%nat.\nProof.\n simpl;auto with T2 arith.\nQed.\n\n\nLemma T2_size2 : forall a b n c , (T2_size a < T2_size (cons a b n c))%nat.\nProof.\n simpl; auto with arith T2.\nQed.\n\n\nLemma T2_size3 : forall a b n c , (T2_size b < T2_size (cons a b n c))%nat.\nProof.\n simpl; auto with arith T2.\nQed.\n\nLemma T2_size4 : forall a b n c , (T2_size c < T2_size (cons a b n c))%nat.\nProof.\n simpl; auto with arith T2.\nQed.\n\n\n\nHint Resolve T2_size1 T2_size2 T2_size3 T2_size4.\n\n\n(** let us recall subterm properties on T2 *)\n\n\nLemma lt_subterm1 : forall a a'  n'  b' c', a < a' ->\n                                         a < cons a'  b' n' c'.\nProof.\n intros.\n apply transitivity with (cons a b' n' c');auto with T2 .\nQed.\n\nHint Resolve nat_lt_cons.\nHint Resolve  lt_subterm1. \n\n\nLemma nat_2_term_mono : forall n n', (n < n')%nat -> \n                                      rpo (nat_2_term n) (nat_2_term n').\nProof.\n induction 1.\n simpl.\n eapply Subterm.\n eleft.\n esplit.\n constructor.\n simpl.\n eapply Subterm.\n eleft.\n esplit.\n constructor.\n auto with T2.\nQed.\n\n\nLemma T2_size_psi : forall a b n c , \n    (T2_size [a,b] <= T2_size (cons a b n c))%nat.\nProof.\n simpl; auto with arith T2.\n intros;omega.\nQed.\n\n\n(* Lemmas for rpo *)\nLemma rpo_2_2 : forall ta1 ta2 tb1 tb2 ,\n                rpo ta1 ta2 ->\n                rpo tb1 (Term ord_psi (ta2:: tb2::nil)) ->\n                 rpo (Term ord_psi (ta1:: tb1 ::nil))\n                     (Term ord_psi (ta2:: tb2 ::nil)).\nProof.\n intros.\n apply Top_eq_lex.\n simpl;auto with T2.\n left.\n auto with T2.\n auto with T2.\n inversion_clear 1; try subst s'.\n apply rpo_trans with ta2;auto with T2.\n eapply Subterm.\n 2:eleft.\n left.\n auto with T2.\n destruct H2.\n subst s'.\n auto with T2.\n case H1.\nQed.\n\n\nLemma rpo_2_3 : forall ta1 ta2 tb1 tb2 n1 tc1,\n                rpo ta1 ta2 ->\n                rpo tb1 (Term ord_psi (ta2:: tb2::nil)) ->\n                rpo tc1 (Term ord_psi (ta1:: tb1::nil)) ->\n                rpo (Term ord_cons ((Term ord_psi (ta1:: tb1 ::nil))::(nat_2_term n1) ::tc1::nil))\n                    (Term ord_psi (ta2:: tb2 ::nil)).\nProof.\n intros.\n apply Top_gt.\n simpl;auto with T2.\n inversion_clear 1.\n subst s'.\n apply rpo_2_2;auto with T2.\n destruct H3 as [|[|[]]]; unfold In in H2; try subst s'.\n apply nat_lt_psi.\n apply rpo_trans with (Term ord_psi (ta1 :: tb1 :: nil));auto with T2.\n apply rpo_2_2;auto with T2.\nQed.\n\nLemma rpo_2_1 : forall ta1 ta2 tb1 tb2 n1 n2 tc1 tc2,\n                rpo ta1 ta2 ->\n                rpo tb1 (Term ord_psi (ta2:: tb2::nil)) ->\n                rpo tc1 (Term ord_psi (ta1:: tb1::nil)) ->\n                rpo (Term ord_cons ((Term ord_psi (ta1:: tb1 ::nil))::(nat_2_term n1) ::tc1::nil))\n                    (Term ord_cons ((Term ord_psi (ta2:: tb2 ::nil))::(nat_2_term n2) ::tc2::nil)).\nProof.\n intros.\n apply rpo_trans with (Term ord_psi (ta2 :: tb2 :: nil)).\n apply rpo_2_3;auto with T2.\n eapply Subterm.\n 2:eleft.\n left;auto with T2.\nQed.\n\n\n\n\n\n\nLemma rpo_2_4 : forall ta1 ta2 tb1 tb2  n2  tc2,\n                rpo ta1 ta2 ->\n                rpo tb1 (Term ord_psi (ta2:: tb2::nil)) ->\n                rpo (Term ord_psi (ta1:: tb1 ::nil))\n                    (Term ord_cons ((Term ord_psi (ta2:: tb2 ::nil))::(nat_2_term n2) ::tc2::nil)).\nProof.\n intros.\n apply rpo_trans with (Term ord_psi (ta2 :: tb2 :: nil)). \n apply rpo_2_2;auto with T2.\n eapply Subterm.\n eleft.\n reflexivity.\n left.\nQed.\n\n\nLemma rpo_3_2 : forall ta1  tb1 tb2 ,\n                rpo tb1 tb2 ->\n                rpo (Term ord_psi (ta1:: tb1 ::nil))\n                    (Term ord_psi (ta1:: tb2 ::nil)).\nProof.\n intros.\n apply Top_eq_lex.\n simpl;auto with T2.\nright.\n left.\n auto with T2.\n auto with T2.\n inversion_clear 1; try subst s'.\n eapply Subterm.\n eleft.\n reflexivity.\n left.\n destruct H1; unfold In in H; try subst s'.\n eapply rpo_trans with tb2;auto with T2.\n \n eapply Subterm.\n 2:eleft.\n right;\n left.\n auto with T2.\n case H0.\nQed.\n\n\nLemma rpo_3_3 : forall ta1  tb1 tb2 n1 tc1,\n                rpo tb1 tb2 ->\n                rpo tc1 (Term ord_psi (ta1:: tb1 ::nil)) ->\n                rpo (Term ord_cons ((Term ord_psi (ta1:: tb1 ::nil))::(nat_2_term n1) ::tc1::nil))\n                    (Term ord_psi (ta1:: tb2 ::nil)).\nProof.\n intros.\n apply Top_gt.\n simpl;auto with T2.\n inversion_clear 1; try subst s'.\n apply rpo_3_2;auto with T2.\n destruct H2 as [<-|[<-|[]]].\n apply nat_lt_psi.\n apply rpo_trans with (Term ord_psi (ta1 :: tb1 :: nil)).\nauto with T2.\n  apply rpo_3_2;auto with T2.\nQed.\n\n\nLemma rpo_3_1 : forall ta1  tb1 tb2 n1 n2 tc1 tc2,\n                rpo tb1 tb2 ->\n                rpo tc1 (Term ord_psi (ta1:: tb1::nil)) ->\n                rpo (Term ord_cons ((Term ord_psi (ta1:: tb1 ::nil))::(nat_2_term n1) ::tc1::nil))\n                    (Term ord_cons ((Term ord_psi (ta1:: tb2 ::nil))::(nat_2_term n2) ::tc2::nil)).\nProof.\n intros.\n apply rpo_trans with  (Term ord_psi (ta1 :: tb2 :: nil)).\n apply rpo_3_3;auto with T2.\n eapply Subterm.\n eleft.\n reflexivity.\n left;auto with T2.\nQed.\n\n\nLemma rpo_3_4 : forall ta1  tb1 tb2  n2  tc2,\n                rpo tb1 tb2 ->\n                rpo (Term ord_psi (ta1:: tb1 ::nil))\n                    (Term ord_cons \n                      ((Term ord_psi (ta1:: tb2 ::nil))::\n                                     (nat_2_term n2) ::tc2::nil)).\nProof.\n intros.\n apply rpo_trans with  (Term ord_psi (ta1 :: tb2 :: nil)).\n apply rpo_3_2;auto with T2.\n eapply Subterm.\n eleft.\n reflexivity.\n left;auto with T2.\nQed.\n\n\nLemma rpo_4_2 : forall ta1 ta2  tb1 tb2 ,\n                rpo (Term ord_psi (ta1:: tb1 ::nil)) tb2 ->\n                rpo (Term ord_psi (ta1:: tb1 ::nil))\n                    (Term ord_psi (ta2:: tb2 ::nil)).\nProof.\n intros.\n apply rpo_trans with tb2;auto with T2.\n eapply Subterm.\n eright;eleft.\n reflexivity.\n left.\nQed.\n\n\nLemma rpo_4_3 : forall ta1  ta2 tb1 tb2 n1 tc1,\n                rpo (Term ord_psi (ta1:: tb1 ::nil)) tb2 ->\n                rpo tc1 (Term ord_psi (ta1:: tb1 ::nil)) ->\n                rpo (Term ord_cons ((Term ord_psi (ta1:: tb1 ::nil))::\n                                                  (nat_2_term n1) ::tc1::nil))\n                    (Term ord_psi (ta2:: tb2 ::nil)).\nProof.\n intros.\n apply Top_gt.\n simpl;auto with T2.\n inversion_clear 1; try subst s'.\n apply rpo_4_2;auto with T2.\n destruct H2 as [<-|[<-|[]]].\n apply nat_lt_psi.\n apply rpo_trans with (Term ord_psi (ta1 :: tb1 :: nil)).\n auto with T2.\n apply rpo_4_2;auto with T2.\nQed.\n\n\n\n\nLemma rpo_4_1 : forall ta1  ta2 tb1 tb2 n1 n2 tc1 tc2,\n                rpo (Term ord_psi (ta1:: tb1 ::nil)) tb2 ->\n                rpo tc1 (Term ord_psi (ta1:: tb1 ::nil)) ->\n                rpo \n                 (Term ord_cons \n                    ((Term ord_psi (ta1:: tb1 ::nil))::\n                                   (nat_2_term n1) ::tc1::nil))\n                     (Term ord_cons \n                              ((Term ord_psi (ta2:: tb2 ::nil))::\n                                             (nat_2_term n2) ::tc2::nil)).\nProof.\n intros.\n apply rpo_trans with  (Term ord_psi (ta2 :: tb2 :: nil)).\n apply rpo_4_3;auto with T2.\n eapply Subterm.\n eleft.\n reflexivity.\n left;auto with T2.\nQed.\n\n\n\n\nLemma rpo_4_4 : forall ta1  ta2 tb1 tb2  n2  tc2,\n                rpo (Term ord_psi (ta1:: tb1 ::nil)) tb2 ->\n                rpo (Term ord_psi (ta1:: tb1 ::nil))\n                    (Term ord_cons \n                     ((Term ord_psi (ta2:: tb2 ::nil))::\n                      (nat_2_term n2) ::tc2::nil)).\nProof.\n intros.\n apply rpo_trans with  (Term ord_psi (ta2 :: tb2 :: nil)).\n apply rpo_4_2;auto with T2.\n eapply Subterm.\n eleft.\n reflexivity.\n left;auto with T2.\nQed.\n\n\nLemma rpo_5_2 : \n           forall ta1 ta2  tb1  ,\n              rpo (Term ord_psi (ta1:: tb1 ::nil))\n                 (Term ord_psi (ta2:: (Term ord_psi (ta1::tb1::nil)) ::nil)).\nProof.\n intros.\n eapply Subterm.\n eright;eleft.\n reflexivity.\n left.\nQed.\n\n\nLemma rpo_5_3 : forall ta1  ta2 tb1  n1 tc1,\n                rpo tc1 (Term ord_psi (ta1:: tb1 ::nil)) ->\n                rpo \n                (Term ord_cons \n                 ((Term ord_psi (ta1:: tb1 ::nil))::\n                                (nat_2_term n1) ::tc1::nil))\n                (Term ord_psi (ta2:: (Term ord_psi (ta1:: tb1 ::nil)) ::nil)).\nProof.\n intros.\n apply Top_gt.\n simpl;auto with T2.\n inversion_clear 1; try subst s'.\n apply rpo_5_2;auto with T2.\n destruct H1 as [<-|[<-|[]]].\n apply nat_lt_psi.\n apply rpo_trans with (Term ord_psi (ta1 :: tb1 :: nil)).\n auto with T2.\n apply rpo_5_2;auto with T2.\nQed.\n\n\n\n\nLemma rpo_5_1 : forall ta1  ta2 tb1  n1 n2 tc1 tc2,\n                rpo tc1 (Term ord_psi (ta1:: tb1 ::nil)) ->\n                rpo \n                (Term ord_cons \n                 ((Term ord_psi (ta1:: tb1 ::nil))::\n                                (nat_2_term n1) ::tc1::nil))\n                    (Term ord_cons\n                       ((Term ord_psi (ta2:: \n                                      (Term ord_psi (ta1:: tb1 ::nil))\n                                       ::nil))::\n                       (nat_2_term n2) ::tc2::nil)).\nProof.\n intros.\n apply rpo_trans with  \n    (Term ord_psi (ta2 :: Term ord_psi (ta1 :: tb1 :: nil) :: nil)).\n apply rpo_5_3.\n auto with T2.\n eapply Subterm.\n eleft.\n reflexivity.\n left;auto with T2.\nQed.\n\n\nLemma rpo_5_4 : forall ta1  ta2 tb1  n2  tc2,\n                rpo (Term ord_psi (ta1:: tb1 ::nil))\n                    (Term ord_cons\n                       ((Term ord_psi (ta2:: \n                                      (Term ord_psi (ta1:: tb1 ::nil))\n                                       ::nil))::\n                       (nat_2_term n2) ::tc2::nil)).\nProof.\n intros.\n apply rpo_trans with \n     (Term ord_psi (ta2 :: Term ord_psi (ta1 :: tb1 :: nil) :: nil)).\n \n eapply Subterm.\n eright;eleft.\n reflexivity.\n left.\n eapply Subterm.\n eleft.\n reflexivity.\n left.\nQed.\n\n\n\nLemma rpo_6_1 : forall ta1 tb1 n1 n2 tc1 tc2,\n rpo tc1 (Term ord_psi (ta1:: tb1 ::nil)) ->\n (n1 < n2)%nat ->\n   rpo \n    (Term ord_cons ((Term ord_psi (ta1:: tb1 ::nil))::\n                                  (nat_2_term n1) ::tc1::nil))\n    (Term ord_cons ((Term ord_psi (ta1:: tb1 ::nil))::\n                                  (nat_2_term n2) ::tc2::nil)).\nProof.\n intros.\n apply Top_eq_lex.\n simpl;auto with T2.\n right.\n left.\n apply nat_2_term_mono;auto with T2.\n auto with T2.\n inversion_clear 1; try subst s'.\n eapply Subterm.\n 2:eleft.\n left;auto with T2.\n destruct H2 as [<-|[<-|[]]].\n apply nat_lt_cons.\n eapply rpo_trans.\n eexact H.\n eapply Subterm.\n 2:eleft.\n left;auto with T2.\nQed.\n\n\n\nLemma rpo_6_4 : forall ta1 tb1  n2  tc2,\n (0 < n2)%nat ->\n   rpo (Term ord_psi (ta1:: tb1 ::nil))\n       (Term ord_cons ((Term ord_psi (ta1:: tb1 ::nil))::\n                                     (nat_2_term n2) ::tc2::nil)).\nProof.\n intros.\n eapply Subterm.\n 2:eleft.\n left;auto with T2.\nQed.\n\n\n\n\nLemma rpo_7_1 : forall ta1 tb1 n1 tc1 tc2,\n rpo tc1 (Term ord_psi (ta1:: tb1 ::nil)) ->\n rpo tc1  tc2 ->\n rpo (Term ord_cons ((Term ord_psi (ta1:: tb1 ::nil))::\n                                   (nat_2_term n1) ::tc1::nil))\n                    (Term ord_cons ((Term ord_psi (ta1:: tb1 ::nil))::\n                                    (nat_2_term n1) ::tc2::nil)).\nProof.\n intros.\n apply Top_eq_lex.\n simpl;auto with T2.\n right.\n right.\n left.\n auto with T2.\n auto with T2.\n inversion_clear 1; try subst s'.\n eapply Subterm.\n 2:eleft.\n left;auto with T2.\n destruct H2 as [<-|[<-|[]]].\n apply nat_lt_cons.\n eapply rpo_trans.\n eexact H.\n eapply Subterm.\n 2:eleft.\n left;auto with T2. \nQed.\n\n\nSection lt_incl_rpo.\n Variable s :nat.\n Variables (a1 b1 c1 a2 b2 c2:T2)(n1 n2:nat).\n\n Hypothesis Hsize :\n   ((T2_size (cons a1 b1 n1 c1) + T2_size (cons a2 b2 n2 c2)) = S s)%nat.\n\n Hypothesis Hrec :   forall o' o, (T2_size o + T2_size o' <= s)%nat->\n                              o < o' -> nf o -> nf o' -> \n                                  rpo (T2_2_term o) (T2_2_term o').\n\n Hypothesis nf1 : nf (cons a1 b1 n1 c1).\n Hypothesis nf2 :  nf (cons a2 b2 n2 c2).\n\n Remark nf_a1 : nf a1.\n Proof.\n  nf_inv.\n Qed.\n\n Remark nf_a2 : nf a2.\n Proof.\n  nf_inv.\n Qed.\n\n Remark nf_b1 : nf b1.\n Proof.\n  nf_inv.\n Qed.\n\n Remark nf_b2 : nf b2.\n Proof.\n  nf_inv.\n Qed.\n Hint Resolve nf1 nf2 nf_a1 nf_a2 nf_b1 nf_b2.\n\n  Remark nf_c1 : nf c1.\n Proof.\n  nf_inv.\n Qed.\n\n Remark nf_c2 : nf c2.\n Proof.\n  nf_inv.\n Qed.\n\n Hint Resolve nf_c1 nf_c2.\n\nHypothesis H : cons a1 b1 n1 c1 < cons a2 b2 n2 c2.\n\n\nLemma cons_rw : forall a b n c, \n (n=0 /\\ c=zero /\\ \n   (T2_2_term (cons a b n c)=(Term ord_psi \n         ((T2_2_term a)::(T2_2_term b)::nil)))) \\/\n    (T2_2_term (cons a b n c)=\n                        Term ord_cons \n                          ((Term ord_psi ((T2_2_term a)::(T2_2_term b)::nil))\n                                        ::(nat_2_term n)::(T2_2_term c)::nil)).\n \n\n destruct n. \n destruct c.\n left;simpl;auto with T2.\n right;simpl;auto with T2.\n right;simpl;auto with T2.\nQed.\n\n\n \nLemma lt_rpo_cons_cons : rpo (T2_2_term (cons a1 b1 n1 c1)) \n                     (T2_2_term (cons a2 b2 n2 c2)).\nProof.\n inversion H.\n assert (rpo (T2_2_term a1) (T2_2_term a2)).\n apply Hrec.\n simpl in Hsize;omega.\n auto with T2.\n auto with T2.\n auto with T2.\n assert (rpo (T2_2_term b1) \n             (Term ord_psi ((T2_2_term a2):: ((T2_2_term b2)::nil)))).\n change (rpo (T2_2_term b1) (T2_2_term (cons a2 b2 0 zero))).\n apply Hrec.\n simpl;simpl in Hsize;omega.\n auto with T2.\n auto with T2.\n constructor;auto with T2.\n assert (rpo (T2_2_term c1) (Term ord_psi (T2_2_term a1 :: T2_2_term b1 :: nil))).\n  change (rpo (T2_2_term c1) (T2_2_term (cons a1 b1 0 zero))).\n  apply Hrec.\n simpl;simpl in Hsize;omega.\n  inversion_clear nf1.\n auto with T2.\n apply psi_relevance;auto with T2.\n auto with T2.\n constructor;auto with T2.\n case (cons_rw a1 b1 n1 c1).\n intros (H'2,(H'3,H'4)).\n rewrite H'2;rewrite H'3.\n  case (cons_rw a2 b2 n2 c2).\n  intros (H'5,(H'6,H'7)).\n rewrite H'5;rewrite H'6.\n simpl.\n apply rpo_2_2;auto with T2.\n intro H'6;rewrite H'6.\n simpl.\n apply rpo_2_4 ; auto with T2.\n intro H'6;rewrite H'6.\n case (cons_rw a2 b2 n2 c2).\n intros (H''5,(H''6,H''7)).\n rewrite H''7. \n apply rpo_2_3;auto with T2.\n intro H'7;rewrite H'7.\n apply rpo_2_1;auto with T2.\n subst a2.\n assert (rpo (T2_2_term b1) (T2_2_term b2)).\n apply Hrec.\n simpl in Hsize;omega.\n auto with T2.\n auto with T2.\n (* Below, an \"auto with T2\" was working before 28 June 2014, calling \"nf_b2\" *)\n (* but nf_b2 refers to a2 and nf2 which are not anymore in the context. *)\n eauto using nf_b.\n assert (rpo (T2_2_term c1) \n             (Term ord_psi (T2_2_term a1 :: T2_2_term b1 :: nil))).\n change (rpo (T2_2_term c1) (T2_2_term (cons a1 b1 0 zero))).\n apply Hrec.\n simpl;simpl in Hsize;omega.\n inversion_clear nf1.\n auto with T2.\n apply psi_relevance;auto with T2.\n auto with T2.\n constructor;auto with T2.\n case (cons_rw a1 b1 n1 c1).\n intros (H'2,(H'3,H'4)).\n rewrite H'4.\n case (cons_rw a1 b2 n2 c2).\n intros (H'5,(H'6,H'7)).\n rewrite H'7.\n apply rpo_3_2;auto with T2.\n intro H'6;rewrite H'6.\n apply rpo_3_4 ; auto with T2.\n intro H'6;rewrite H'6.\n case (cons_rw a1 b2 n2 c2).\n intros (H''5,(H''6,H''7)).\n rewrite H''7.\n apply rpo_3_3;auto with T2.\n intro H'7;rewrite H'7.\n apply rpo_3_1;auto with T2.\n assert  (rpo (Term ord_psi ((T2_2_term a1):: (T2_2_term b1) ::nil))\n              (T2_2_term b2)).\n change  (rpo (T2_2_term (cons a1 b1 0 zero))  (T2_2_term b2)).\n apply Hrec.\n simpl in Hsize. \n simpl;omega.\n auto with T2.\n auto with T2.\n auto with T2.\n  assert (rpo (T2_2_term c1) \n              (Term ord_psi (T2_2_term a1 :: T2_2_term b1 :: nil))).\n  change (rpo (T2_2_term c1) (T2_2_term (cons a1 b1 0 zero))).\n  apply Hrec.\n simpl;simpl in Hsize;omega.\n  inversion_clear nf1.\n auto with T2.\n apply psi_relevance;auto with T2.\n auto with T2.\n constructor;auto with T2.\n\n case (cons_rw a1 b1 n1 c1).\n intros (H'2,(H'3,H'4)).\n rewrite H'4.\n \n  case (cons_rw a2 b2 n2 c2).\n  intros (H'5,(H'6,H'7)).\n  rewrite H'7.\n apply rpo_4_2;auto with T2.\n intro H'6;rewrite H'6.\n apply rpo_4_4 ; auto with T2.\n intro H'6;rewrite H'6.\n case (cons_rw a2 b2 n2 c2).\n intros (H''5,(H''6,H''7)).\n rewrite H''7.\n apply rpo_4_3;auto with T2.\n intro H'7;rewrite H'7.\n apply rpo_4_1;auto with T2.\n assert (rpo (T2_2_term c1) \n             (Term ord_psi ((T2_2_term a1)::(T2_2_term b1)::nil))).\n change (rpo (T2_2_term c1) (T2_2_term (cons a1 b1 0 zero))).\n  apply Hrec.\n simpl;simpl in Hsize;omega.\n inversion_clear nf1;auto with T2.\n apply psi_relevance;auto with T2.\n auto with T2.\n constructor;auto with T2.\n case (cons_rw a1 b1 n1 c1).\n intros (H'2,(H'3,H'4)).\n rewrite H'4.\n case (cons_rw a2 (cons a1 b1 0 zero) n2 c2).\n  intros (H''5,(H''6,H''7)).\n  rewrite H''7.\n simpl;apply rpo_5_2;auto with T2.\n intro H'7;rewrite H'7.\n simpl;apply rpo_5_4.\n intro H'7;rewrite H'7.\n case (cons_rw a2 (cons a1 b1 0 zero) n2 c2).\n intros (H''5,(H''6,H''7)).\n  rewrite H''7.\n  simpl;apply rpo_5_3.\n  auto with T2.\n intro H''7;rewrite H''7.\n  simpl;apply rpo_5_1.\n auto with T2.\n subst a2.\n subst b2.\n assert (rpo (T2_2_term c1) \n             (Term ord_psi ((T2_2_term a1):: (T2_2_term b1) ::nil))).  \n change (rpo (T2_2_term c1) (T2_2_term (cons a1 b1 0 zero))).\n apply Hrec.\n simpl; simpl in Hsize;omega.\n inversion nf1;auto with T2.\n apply psi_relevance;auto with T2.\n auto with T2.\n constructor;auto with T2.\n  case (cons_rw a1 b1 n1 c1).\n intros (H'2,(H'3,H'4)).\n rewrite H'4.\n  case (cons_rw a1 b1 n2 c2).\n intros (H''2,(H''3,H''4)).\n rewrite H''2 in H1.\n inversion H1.\n intro H'7;rewrite H'7.\n apply rpo_6_4.\n rewrite H'2 in H1;auto with T2.\n intro H'7;rewrite H'7.\n  case (cons_rw a1 b1 n2 c2).\n  intros (H''2,(H''3,H''4)).\n rewrite H''2 in H1.\ninversion H1.\n intro H''7;rewrite H''7.\n apply rpo_6_1.\n auto with T2.\n auto with T2.\n assert (rpo (T2_2_term c1)\n             (Term ord_psi ((T2_2_term a1):: (T2_2_term b1) ::nil))).  \n change (rpo (T2_2_term c1) (T2_2_term (cons a1 b1 0 zero))).\n apply Hrec.\n simpl; simpl in Hsize;omega.\n inversion nf1;auto with T2.\n apply psi_relevance;auto with T2.\n auto with T2.\n constructor;auto with T2.\n assert (rpo (T2_2_term c1) (T2_2_term c2)).\n apply Hrec.\n simpl; simpl in Hsize;omega.\n auto with T2.\n auto with T2.\n auto with T2.\n case (cons_rw a2 b2 n2 c1).\n intros (H'2,(H'3,H'4)).\n rewrite H'4.\n  case (cons_rw a2 b2 n2 c2).\n intros (H''2,(H''3,H''4)).\n rewrite H''3 in H1.\n inversion H1.\n intro H'7;rewrite H'7.\n eapply Subterm.\n 2:eleft.\n left.\n auto with T2.\n intro H'7;rewrite H'7.\n case (cons_rw a2 b2 n2 c2).\n intros (H''2,(H''3,H''4)).\n rewrite H''3 in H1;inversion H1.\n intro H''7;rewrite H''7.\n apply rpo_7_1.\n auto with T2.\n subst a2;subst b2.\n auto with T2.\n auto with T2.\nQed.\n\n\nEnd lt_incl_rpo.\n\nLemma lt_inc_rpo_0 : forall n, \n                           forall o' o, (T2_size o + T2_size o' <= n)%nat->\n                              o < o' -> nf o -> nf o' -> \n                                  rpo (T2_2_term o) (T2_2_term o').\nProof.\ninduction n.\ndestruct o;destruct o'.\ninversion 2.\nsimpl.\ninversion 1.\ninversion 2.\nsimpl.\ninversion 1.\ndestruct o'.\ninversion 2.\ndestruct o.\nintros. \ncase (cons_rw o'1 o'2 n0 o'3).\nintros (H'1,(H'2,H'3)).\nrewrite H'3.\nsimpl;apply Top_gt.\nsimpl;auto with T2.\ndestruct 1.\nintro H3;rewrite H3.\nsimpl;apply Top_gt.\nsimpl;auto with T2.\ndestruct 1.\nintros. \ncase (le_lt_or_eq _ _ H).\n intros;apply IHn;auto with arith T2.\n\n intros;\neapply lt_rpo_cons_cons;eauto with T2.\nQed.\n\n\n\nRemark R1 : Acc P.prec nat_0. \n split.\n destruct y; try contradiction.\nQed.\n\nHint Resolve R1.\n\nRemark R2 : Acc P.prec ord_zero. \n split.\n destruct y; try contradiction; auto with T2.\nQed.\n\nHint Resolve R2.\n\nRemark R3 : Acc P.prec nat_S.\n split.\n destruct y; try contradiction;auto with T2.\nQed.\n\n\nHint Resolve R3.\n\nRemark R4 : Acc P.prec ord_cons.\n split.\n destruct y; try contradiction;auto with T2.\nQed.\n\nHint Resolve R4.\n\nRemark R5 : Acc P.prec ord_psi.\n split.\n destruct y; try contradiction;auto with T2.\nQed.\n\nHint Resolve R5.\n\nTheorem well_founded_rpo : well_founded rpo.\nProof.\n apply wf_rpo.\n red.\n destruct a;auto with T2.\nQed.\n\nSection  well_founded.\n \n  Let R := restrict T2 nf lt.\n\n  Hint Unfold restrict R.\n\n Lemma R_inc_rpo : forall o o', R o o' -> rpo (T2_2_term o) (T2_2_term o').\n Proof.\n  intros o o' (H,(H1,H2)).\n  eapply lt_inc_rpo_0;auto with T2.\n Qed. \n\n \n Lemma nf_Wf : well_founded_P _ nf lt.\nProof.\n unfold well_founded_P.\n intros.\n unfold restrict.\n generalize (Acc_inverse_image _ _ rpo T2_2_term a (well_founded_rpo (T2_2_term a))).\n  intro.\n eapply  Acc_incl  with  (fun x y : T2 => rpo (T2_2_term x) (T2_2_term y)). \n red.\n apply R_inc_rpo.\n auto with T2.\nQed.\n\n\nEnd well_founded.\n\n\n\n\n\n\nDefinition transfinite_induction :\n forall (P:T2 -> Type),\n   (forall x:T2, nf x ->\n                   (forall y:T2, nf y ->  y < x -> P y) -> P x) ->\n    forall a, nf a -> P a.\nProof.\n intros; eapply P_well_founded_induction_type; eauto with T2.\n eexact nf_Wf;auto with T2.\nDefined.\n\n\nDefinition transfinite_induction_Q :\n  forall (P : T2 -> Type) (Q : T2 -> Prop),\n      (forall x:T2, Q x -> nf x ->\n           (forall y:T2, Q y -> nf y ->  y < x -> P y) -> P x) ->\n   forall a, nf a -> Q a -> P a.\nProof.\n intros.\n eapply P_well_founded_induction_type with (R:=lt)(P:=fun a => nf a /\\ Q a).\n 3:split;auto with T2.\n 2:destruct 1; intros; eapply X; eauto with T2.\n unfold well_founded_P.\n intros.\n apply Acc_incl with (restrict _ nf lt).\n unfold inclusion; intros.\n unfold restrict.\n unfold restrict in H2.\n tauto.\n apply nf_Wf.\n case H1;auto with T2.\nDefined.\n\n\n\n\n(* the Veblen function phi *)\n\nDefinition  phi (alpha beta : T2) : T2 :=\n match beta with zero => [alpha, beta] \n               | [b1, b2] => \n                 (match compare alpha b1\n                   with Datatypes.Lt => [b1, b2 ]\n                       | _ => [alpha,[b1, b2]]\n                                           end)\n               | cons b1 b2 0 (cons zero zero  n zero) => \n                       (match compare alpha b1\n                        with  Datatypes.Lt => \n                            [alpha, (cons b1 b2 0 (finite n))]\n                            | _ =>  [alpha, (cons b1 b2 0 (finite (S n)))]\n                        end)\n              | any_beta => [alpha, any_beta]\nend.\n\n\n\nTheorem phi_of_psi  : forall a b1 b2, \n                      phi a [b1, b2] =\n                      if (lt_ge_dec a b1) \n                      then [b1, b2]\n                      else [a ,[b1, b2]].\n simpl.\n intros;case (lt_ge_dec a b1).\n intro;  rewrite compare_rw_lt; auto with T2.\n destruct 1.\n subst b1; rewrite compare_rw_eq;auto with T2.\n rewrite compare_rw_gt;auto with T2.\nQed.\n\nLemma phi_to_psi : forall alpha beta, \n      {alpha' : T2 & {beta' : T2 | phi alpha beta = [alpha', beta']}}.\nProof.\n destruct beta;simpl.\n exists alpha; exists zero;trivial.\n case n.\n \n case beta3. \n case (compare alpha beta1). \n \n exists alpha;exists  [beta1, beta2];trivial.\n exists beta1;exists beta2;trivial.\n \n exists alpha;exists  [beta1, beta2];trivial.\n\n \n destruct t.\n destruct t.\n destruct n0.\n destruct t.\n case (compare alpha beta1).\n exists alpha;exists (cons beta1 beta2 0 [zero, zero]);trivial.\n exists alpha;exists (cons beta1 beta2 0 zero);trivial.\n exists alpha;exists (cons beta1 beta2 0 [zero, zero]);trivial.\n exists alpha;\n   exists (cons beta1 beta2 0 (cons zero zero 0 (cons t1 t2 n0 t3)));\n   trivial.\n destruct t.\n case (compare alpha beta1).\n exists alpha; exists (cons beta1 beta2 0 (cons zero zero (S n0) zero)).\n trivial.\n exists alpha;exists (cons beta1 beta2 0 (F S n0));trivial.\n exists alpha;exists ( cons beta1 beta2 0 (cons zero zero (S n0) zero));trivial.\n exists alpha;\n  exists ( cons beta1 beta2 0 (cons zero zero (S n0) (cons t1 t2 n1 t3)));\n trivial.\n intros n1 t;exists alpha;\n  exists (cons beta1 beta2 0 (cons zero (cons t1 t2 n0 t3) n1 t));trivial.\n exists alpha;exists (cons beta1 beta2 0 (cons (cons t1 t2 n0 t3) t n1 t0));\n trivial.\n intro n0;exists alpha;exists (cons beta1 beta2 (S n0) beta3);trivial.\nQed.\n\nLemma phi_principal : forall alpha beta, ap (phi alpha beta).\nProof.\n intros alpha beta; case (phi_to_psi alpha beta);intros x (y,E);\n  rewrite E;try constructor.\nQed.\n\n\n\nTheorem phi_alpha_zero : forall alpha, phi alpha zero = [alpha, zero].\nProof.\n simpl;auto with T2.\nQed.\n\n\n\n\nTheorem phi_of_psi_succ : forall a b1 b2 n, (* nf b1 -> nf b2 -> *)\n                          phi a (cons b1 b2 0 (finite (S n))) =\n                          if lt_ge_dec a b1\n                          then [a, (cons b1 b2 0 (finite n))]\n                          else [a ,(cons b1 b2 0 (finite (S n)))].\n\n simpl.\n intros;case (lt_ge_dec a b1).\n intro;  rewrite compare_rw_lt; auto with T2.\n destruct 1.\n subst b1; rewrite compare_rw_eq;auto with T2.\n rewrite compare_rw_gt;auto with T2.\nQed.\n\n(*\nTheorem phi_of_psi_gen : forall a b1 b2 n b3,\n   b1 <= a ->\n   phi a (cons b1 b2 n b3) = psi a (cons b1 b2 n b3).\n*)\n\n\n(* every principal ordinal is enumerated by phi zero *)\n\n\n\n\n\n\n\nLemma phi_cases_aux : forall P : T2 -> Type,\n                         P zero ->\n                         (forall b1 b2, nf b1 -> nf b2 -> P [b1, b2]) ->\n                         (forall b1 b2 n, nf b1 -> nf b2 ->\n                                       P (cons b1 b2 0 (finite (S n)))) ->\n                         (forall b1 b2 n c, nf (cons b1 b2 n c) ->\n                                   omega <= c \\/ (0 < n)%nat -> \n                                   P (cons b1 b2 n c)) ->\n                         forall alpha, nf alpha -> P alpha.\n intros until alpha.\n case alpha.\n auto with T2.\n destruct n;intros until t1;case (lt_ge_dec t1 omega).\nintros.\n assert (nf t1).\n inversion H;auto with T2.\n \n case (lt_omega_inv  H0 l).\n intro x;case x.\n intro;subst t1.\n simpl.\n refine (X0 _ _ _ _).\n inversion H;auto with T2.\n inversion H;auto with T2.\n intros;subst t1.\n apply X1.\n inversion H;auto with T2.\n inversion H;auto with T2.\n intros;apply X2.\n auto with T2.\n auto with T2.\n intros;apply X2.\n auto with T2.\n auto with arith T2.\n intros;apply X2.\n auto with T2.\n auto with T2.\nQed.\n\n \nTheorem phi_cases' : forall a b, nf b ->\n                    {b1 :T2 & {b2:T2 | b = [b1, b2] /\\\n                                       a < b1 /\\ phi a b =  b}} +\n                    {phi a b = [a, b]} +\n                     {b1 :T2 & {b2:T2 & {n: nat |\n                              b = cons b1 b2 0 (finite (S n))/\\\n                              a < b1 /\\ \n                              phi a b = [a, (cons b1 b2 0 (finite n))]}}}.\n intros a b Hb.\n pattern b; apply phi_cases_aux.\n left;right;simpl;auto with T2.\n intros.\n caseEq (compare a b1).\n left;right.\n unfold phi.\n simpl.\n rewrite H1;auto with T2.\n left.\n left. \n exists b1;exists b2; split.\n auto with T2.\n split;simpl;auto with T2. \n rewrite H1;auto with T2.\n left;right.\n simpl.\n rewrite H1;auto with T2.\n  intros.\n caseEq (compare a b1).\n left;right.\n simpl.\n rewrite H1.\n auto with T2.\n right.\n exists b1;exists b2; exists n.\n repeat split;auto with T2.\n simpl.\n rewrite H1;auto with T2.\n left;right.\n simpl.\n rewrite H1;auto with T2.\n intros.\n left;right.\n simpl.\n caseEq n.\n intro; subst n.\n caseEq c.\n intro; subst c.\n case H0.\n destruct 1.\n discriminate H1.\n inversion H1.\n inversion 1.\n intro t;case t.\n intro t0;case t0.\n intros until t1;case t1.\n intro; subst c.\n case H0.\n destruct 1.\n discriminate H1.\n inversion H1; lt_clean; auto with T2.\n inversion 1.\n auto with T2.\n auto with T2.\n auto with T2.\n auto with T2.\nauto with T2.\nQed.\n\nTheorem phi_cases : forall a b, nf b ->\n                      {phi a b = b}+\n                      {phi a b= [a, b]}+\n                      {b': T2 | nf b' /\\ phi a b = [a, b']\n                                       /\\ succ  b' = b}.\nProof.\n intros a b Hb. \n pattern b;apply phi_cases_aux.\n left;right.\n simpl; auto with T2.\n intros.\n generalize (phi_of_psi a b1 b2).\n case (lt_ge_dec a b1).\n left;left;auto with T2.\n left;right;auto with T2.\n intros. \n generalize (phi_of_psi_succ a  b1 b2 n).\n case (lt_ge_dec a b1).\n right.\n exists (cons b1 b2 0 (finite n)).\n split.\n case n.\n simpl;constructor;auto with T2.\n simpl.\n repeat constructor;auto with T2.\n apply le_lt_trans with a;auto with T2.\n (* apply le_zero_alpha.*)\n\n (* ICI *)\n split; auto with T2.\n simpl.\n generalize l;case b1.\n inversion 1.\n case n;simpl;auto with T2.\n left;right.\n auto with T2.\n left;right;simpl.\n caseEq n.\n intro;subst n.\n caseEq c.\n intro; subst c.\n case H0;intro.\n inversion H1.\n discriminate H2.\n lt_clean.\n lt_clean.\n intro t; case t.\n intro t0;case t0.\n intros n t1 e; subst c.\n  case H0.\n unfold omega; destruct 1.\n discriminate H1.\n inversion H1; lt_clean;auto with T2.\n inversion 1.\n auto with T2.\n auto with T2.\n auto with T2.\n auto with T2.\nQed.\n \n\n\n\nTheorem phi_nf : forall alpha beta, nf alpha -> \n                                     nf beta -> \n                                     nf (phi alpha beta).\n intros t1 t2 v1 v2; case (phi_cases t1 v2).\n destruct 1.\n rewrite e;auto with T2.\n rewrite e;unfold psi;constructor;auto with T2.\n destruct 1 as (b', (V,(H,H0))).\n rewrite H.\n unfold psi;constructor;auto with T2.\nQed.\n\n\n\n\nLemma phi_of_any_cons : forall alpha beta1 beta2 n gamma, \n(*                        nf (cons beta1 beta2 n gamma) -> *)\n                        omega <= gamma  \\/ (0 < n)%nat ->\n                        phi alpha (cons beta1 beta2 n gamma) = \n                        [alpha, (cons beta1 beta2 n gamma)].\n simpl.\n intros until n; case n.\n destruct 1.\n generalize H; case gamma.\n destruct 1.\n discriminate H0.\n lt_clean.\n intro t;case t.\n intro t0;case t0.\n destruct 1.\n discriminate H0.\n inversion H0; lt_clean; auto with T2.\n auto with T2.\n auto with T2.\n lt_clean.\n auto with T2.\nQed.\n\n\n\nLemma phi_fix : forall alpha beta, phi alpha beta = beta ->\n                      {beta1 : T2 & {beta2 : T2 | beta = [beta1, beta2] \n                                                  /\\ alpha < beta1}}.\nProof.\n destruct beta;simpl.\n discriminate 1.\n case n.\n case beta3.\n caseEq (compare  alpha beta1).\n intros.\n injection H0.\n intro;\n absurd (lt beta2 [beta1, beta2]).\n rewrite H1; apply lt_irr.\n refine (lt_beta_psi _ _).\n exists beta1.\n exists beta2; split;auto with T2.\n intros.\n injection H0.\n  intro;\n absurd (beta2 < [beta1, beta2]).\n rewrite H1;apply lt_irr.\n refine (lt_beta_psi _ _).\n destruct t;simpl.\n destruct t;simpl.\n destruct t;simpl.\n case (compare alpha beta1).\n discriminate 1.\n discriminate 1.\n discriminate 1.\n discriminate 1.\n discriminate 1.\n discriminate 1.\n discriminate 1.\n Qed.\n\n\nLemma phi_le : forall alpha beta alpha' beta', \n                  nf beta -> \n                  phi alpha beta = [alpha', beta'] -> alpha <= alpha'.\nProof.\n intros a b a' b' Hb;case (phi_cases a Hb).\n destruct 1.\n case (phi_fix _  e).\n intros x (beta2,(H,H0)).\n rewrite e.\n rewrite H.\n injection 1.\n intros; subst x; right;auto with T2.\n rewrite e;injection 1;left;auto with T2.\n intros (b0,(H1,(H2,H3))).\n rewrite H2; injection 1;left;auto with T2.\nQed.\n\n\n\n\n \n\n\nLemma phi_le_ge : forall alpha beta, nf alpha -> nf beta -> \n     {alpha':T2 &\n        {beta':T2 | phi alpha beta = [alpha' ,beta'] /\\  \n                    alpha <= alpha' /\\ \n                    beta' <= beta}}.\nProof.\n intros a b Va Vb; case (phi_cases' a Vb).\n destruct 1.\n case s; intros b1 (b2,(H1,(H2,H3))).\n rewrite H1 in H3.\n subst b.\n exists b1;exists  b2;repeat split;auto with T2.\n exists a;exists b;auto with T2.\n intros (b1,(b2,(n,(H1,(H2,H3))))).\n exists a;exists (cons b1 b2 0 (finite n));auto with T2.\nsplit;auto with T2.\n split;auto with T2.\n subst b;case n;simpl; auto with T2.\n right;auto with T2.\nQed.\n\n \nTheorem phi_spec1 : forall alpha beta gamma, \n                         nf alpha -> nf beta -> nf gamma ->\n                         gamma < alpha ->\n                        phi gamma (phi alpha beta) = phi alpha beta.\n intros.\n case (phi_le_ge H H0 ).\n intros alpha' (beta', (H'1,(H'2,H'3))).\n rewrite H'1.\n simpl.\n rewrite (compare_rw_lt);auto with T2.\n apply lt_le_trans with alpha;auto with T2.\nQed.\n\n\nTheorem phi_principalR : forall alpha beta, nf alpha -> nf beta ->\n                {gamma:T2 | [alpha, beta] =  phi zero gamma}.\n intros alpha beta Valpha Vbeta; case (phi_cases' alpha Vbeta).\n destruct 1.\n case s; intros b1 (b2,(H1,(H2,H3))).\n case (lt_ge_dec zero alpha).\n intro.\n exists [alpha, beta].\n simpl.\n rewrite (compare_rw_lt  l);auto with T2.\n intro; assert(alpha = zero).\n inversion l;auto with T2.\n lt_clean.\n subst alpha.\n subst beta.\n exists (cons b1 b2 0 (F 1)).\n simpl.\n  rewrite (compare_rw_lt  H2);auto with T2.\n case (lt_ge_dec zero alpha). \n exists (phi alpha beta).\n rewrite phi_spec1;auto with T2.\n intro;assert (alpha=zero).\n case l.\n auto with T2.\n intro;lt_clean.\n subst alpha.\n exists beta.\n auto with T2.\n intros (b1,(b2,(n,(H1,(H2,H3))))).\n subst beta.\n case (lt_ge_dec zero alpha).\n intro l.\n exists [alpha, (cons b1 b2 0 (F (S n)))].\n simpl.\n rewrite (compare_rw_lt l).\n auto with T2.\n  intro;assert (alpha=zero).\n case l.\n auto with T2.\n intro;lt_clean.\n subst alpha.\n exists (cons b1 b2 0 (F (S (S n)))).\n simpl.\nrewrite  (compare_rw_lt H2).\nauto with T2.\nDefined.\n\n \n\n\n(* All epsilons are fixpoints of phi 0 *)\n\nTheorem epsilon_fxp : forall beta, phi zero (epsilon beta) =\n                                   epsilon beta.\n compute.\n trivial.\nQed.\n\n\n \nLemma no_critical : forall alpha, lt alpha (phi alpha zero).\n induction alpha;simpl;auto with T2.\nQed.\n\n\nTheorem le_b_phi_ab : forall a b, nf a -> nf b ->  le b (phi a b).\n\n intros a b Ha Hb; case (phi_cases a  Hb).\n destruct 1.\n rewrite e;left;auto with T2.\n rewrite e;right; auto with T2.\n intro x; case x;intros b' (e,(i,i')).\n subst b.\n  rewrite i.\n apply lt_succ_le;auto with T2.\nQed.\n\nLemma phi_of_psi_plus_finite : forall a b1 b2 n, \n                       a < b1 -> phi a (cons b1 b2 0 (finite n)) <\n                                 [a ,(cons b1 b2 0 (finite n))].\nsimpl.\n intros until n;case n.\n simpl.\n intro H;rewrite (compare_rw_lt H);auto with T2.\n simpl.\n  intros n0  H;rewrite (compare_rw_lt H).\n case n0;simpl; auto with T2.\nQed.\n \n\nLemma phi_mono_r : forall a b c, nf a -> nf b -> nf c ->\n                     b < c -> phi a b < phi a c.\n intros a b c Ha Hb Hc H.\n case (phi_cases' a Hb).\n destruct 1.\n case s; intros b1 (b2,(H1,(H2,H3))).\n rewrite H3.\n apply lt_le_trans with c;auto with T2.\n apply le_b_phi_ab;auto with T2.\n case (phi_cases' a Hc).\n destruct 1.\n case s; intros c1 (c2,(H'1,(H'2,H'3))).\n rewrite e.\n rewrite H'3.\n rewrite H'1.\n constructor 2;auto with T2.\n rewrite H'1 in H.\n auto with T2.\n rewrite e;rewrite e0;auto with T2. \n intros (c1,(c2,(n, (H1,(H2,H3))))).\n subst c.\n assert \n  ((cons c1 c2 0 (finite (S n))) = (succ (cons c1 c2 0 (finite n)))).\n simpl;auto with T2.\n caseEq c1.\n intro; subst c1; lt_clean.\n case n;auto with T2.\n assert (nf (cons c1 c2 0 (finite n))).\n case n.\n inversion Hc;auto with T2.\n inversion Hc;auto with T2.\n intro; simpl; constructor.\n constructor 2.\n apply le_lt_trans with a;auto with T2.\n auto with T2.\n inversion Hc;auto with T2.\n inversion Hc;auto with T2.\n repeat constructor.\n \n \n rewrite H0 in H.\n \ncase (succ_lt_le Hb H1 H).\n intro;subst b.\n case (lt_irr (alpha:=[a, (cons c1 c2 0 (finite n))])).\n pattern  [ a, (cons c1 c2 0 (finite n))] at 1;rewrite <- e.\n apply phi_of_psi_plus_finite.\n auto with T2.\n rewrite H3.\nrewrite e.\n auto with T2.\nintros (b1,(b2,(n,(H1,(H2,H3))))).\ncase (phi_cases' a Hc).\ndestruct 1.\ncase s;intros c1 (c2,(H'1,(H'2,H'3))).\n \nrewrite H3;rewrite H'3;rewrite H'1.\nsubst b;\n subst c;case n;simpl;auto with T2.\n\nconstructor 2.\nauto with T2.\napply le_lt_trans with  (cons b1 b2 0 (finite (S n))).\n simpl;auto with arith T2.\n auto with T2.\n constructor 2.\nauto with T2.\n inversion H; auto with T2.\n lt_clean. \n rewrite H3; rewrite e.\n apply transitivity with [a, (cons b1 b2 0 (finite (S n)))].\n case n;simpl;auto with T2.\n subst b;auto with T2.\nintros (c1,(c2,(p,(H'1,(H'2,H'3))))).\nrewrite H'3;rewrite H3.\nsubst c;subst b.\ngeneralize H;inversion 1;auto with T2. \n\nconstructor 3.\nconstructor 7.\napply lt_compatR.\n inversion H4;lt_clean; auto with T2.\nQed.\n\n\n\nLemma phi_mono_weak_r : forall a b c, nf a -> nf b -> nf c -> \n               b <= c -> phi a b <= phi a c. \nProof.\n destruct 4.\n subst c;left;auto with T2.\n right; apply phi_mono_r;auto with T2.\nQed.\n\nLemma phi_inj_r : forall a b c, nf a -> nf b -> nf c ->\n       phi a b = phi a c -> b= c.\nProof.\n intros a b c Na Nb Nc E.\ntricho b c H.\nabsurd (phi a b < phi a c). \nrewrite E.\napply lt_irr.\napply phi_mono_r;auto.\nauto.\n\nabsurd (phi a c < phi a b).\nrewrite E.\napply lt_irr.\napply phi_mono_r;auto.\nQed.\n \n\nLemma lt_a_phi_ab : forall a b, nf a -> nf b -> a < phi a b.\nProof.\n  intros.\n  apply lt_le_trans with (phi a zero).\n  apply no_critical.\n  apply phi_mono_weak_r;auto with T2.\nQed.\n\n\n(* Expressing psi in terms of phi \n   (as in Lepper-Moser) *)\n\n\nInductive is_successor : T2 -> Prop :=\n finite_succ : forall  n  , is_successor (cons zero zero n zero)\n|cons_succ : forall a b n c, nf (cons a b n c) -> is_successor c ->\n                               is_successor (cons  a b n c).\n\n\n\n(* TO DO : make \"is-limit\" disappear : is_limit is better *)\n\n  \n\n\nInductive is_limit : T2 -> Prop :=\n|is_limit_0 : forall alpha beta n, zero < alpha \\/ zero < beta ->\n                 nf alpha -> nf beta -> is_limit (cons alpha beta n zero)\n| is_limit_cons : forall alpha  beta n gamma, is_limit gamma ->\n                                      nf (cons alpha beta n gamma) ->\n                        is_limit (cons alpha beta n gamma). \n\nLemma zero_not_lim : ~ (is_limit zero).\n red;inversion 1.\nQed.\n\nLemma F_not_lim : forall n, ~ is_limit (F n).\ndestruct n;red;inversion 1.\ndecompose [or] H3; lt_clean.\ncase  zero_not_lim;auto.\nQed.\n\nLemma is_succ_not_lim : forall alpha, is_successor alpha -> ~ is_limit alpha.\n induction alpha.\n intro;apply zero_not_lim.\n inversion_clear 1.\n apply (F_not_lim (S n)).\n red;inversion 1.\n subst alpha3;inversion H1. \n case IHalpha3;auto. \nQed.\n\n\nLemma is_limit_not_succ:  forall alpha, is_limit alpha -> ~ is_successor alpha.\n induction 1.\n red;inversion 1.\n subst alpha;subst beta.\n case H;intro;lt_clean.\ninversion H8.\nred;inversion 1.\n subst gamma.\n case zero_not_lim;auto.\n case IHis_limit.\n auto.\nQed.\n\n\n(* \n   limit_plus_F alpha n beta  means :\n   beta = alpha + F n and alpha is limit or alpha = zero \n*)\n\n\n\nInductive limit_plus_F : T2 -> nat -> T2 -> Prop :=\n limit_plus_F_0 : forall p, limit_plus_F zero p (F p)\n|limit_plus_F_cons : forall beta1 beta2 n gamma0 gamma p,\n                          zero < beta1 \\/ zero < beta2 ->\n                          limit_plus_F gamma0 p gamma ->\n                          limit_plus_F (cons beta1 beta2 n gamma0)\n                                        p (cons beta1 beta2 n gamma).\n\nLemma limit_plus_F_plus : forall alpha alpha' p,\n                      limit_plus_F alpha p alpha' ->\n                      nf alpha ->\n                      alpha' = alpha + F p.\n induction alpha.\n inversion_clear 1.\n simpl;auto.\n inversion_clear 1.\n generalize (IHalpha3 gamma p).\n intros.\n rewrite (H H1).\n simpl.\n case p;simpl.\n rewrite plus_alpha_0;trivial.\n caseEq (compare [alpha1, alpha2] [zero, zero]).\n intro H3; generalize (compare_eq_rw H3).\n injection 1;intros;subst alpha1;subst alpha2.\n decompose [or] H0; lt_clean.\n intro H3; generalize (compare_lt_rw H3).\n inversion_clear 1;try lt_clean.\n auto.\n nf_inv.\nQed.\n\n\n\n\nLemma limit_plus_F_lim : forall alpha alpha' p,\n                      limit_plus_F alpha p alpha' ->\n                      nf alpha ->\n                      is_limit alpha \\/ alpha=zero.\nProof.\n intro alpha;elim alpha.\n auto.\n intros alpha1 _ alpha2 _ alpha3; case alpha3.\n left.\n inversion H0.\n case (H _ _ H9).\n nf_inv. \n constructor.\n auto.\n auto.\n intro H18;rewrite H18;constructor 1;auto.\n nf_inv.\n nf_inv.\n left.\n \n  inversion H0.\n case (H _ _ H9).\n nf_inv.\n  constructor.\n auto.\n auto.\n intro H10;rewrite H10;constructor;try nf_inv.\n auto.\nQed.\n\n\n\nLemma limit_plus_F_inv0 : forall alpha beta,\n                              limit_plus_F alpha 0 beta -> \n                              nf alpha -> alpha = beta.\nProof.\n intros.\n generalize (limit_plus_F_plus H H0).\n simpl.\n rewrite plus_alpha_0.\n auto.\nQed.\n\nLemma is_limit_cons_inv : forall b1 b2 n c, nf (cons b1 b2 n c) ->\n                          is_limit (cons b1 b2 n c) -> is_limit c \\/ c = zero.\nProof.\n inversion_clear 1;auto.\n inversion 1;auto.\nQed.\n\n \nLemma is_limit_intro : forall b1 b2 n , nf b1 -> nf b2 ->\n                       zero < b1 \\/ zero < b2 ->\n                       is_limit  (cons b1 b2 n zero).\nProof.\n constructor;auto.\nQed.\n\n\n\nLemma lt_epsilon0_ok : forall alpha, nf alpha -> lt_epsilon0 alpha ->\n                                     alpha < epsilon0.\nProof.\n induction 1;intros; compute;auto with T2.\n inversion_clear H1.\n constructor 2.\n auto with T2.\n apply IHnf2;auto with T2.\n inversion_clear H3.\n constructor 2;auto with T2.\nQed.\n\n\nDerive Inversion_clear lt_01 with (forall (a b:T2),\n                cons a b 0 zero <  epsilon0) Sort Prop.\n\nDerive Inversion_clear lt_02 with (forall (a b c:T2)(n:nat),\n                cons a b n c <  epsilon0) Sort Prop.\n\nLemma psi_lt_epsilon0 : forall a b, [a, b] < epsilon0 ->\n       a = zero /\\ b < epsilon0.\nProof.\n intros a b H.\n inversion H using lt_01.\n split.\n apply lt_one_inv;auto with T2.\n compute;auto with T2.\n inversion 1.\n inversion 2.\n inversion 1.\n inversion 1.\nQed.\n\nLemma cons_lt_epsilon0 : forall a b n c, cons a b n c < epsilon0 ->\n       nf (cons a b n c) ->\n       a = zero /\\ b < epsilon0 /\\ c < epsilon0.\nProof.\n intros a b n c H.\n inversion H using lt_02.\n split.\n apply lt_one_inv;auto with T2.\n split.\n unfold epsilon0.\n exact H1.\n apply transitivity with (cons a b n c);auto with T2.\n apply lt_tail;auto with T2.\n inversion 1.\n inversion 2.\n inversion 1.\n inversion 1.\nQed.\n\n\n\nLemma lt_epsilon0_okR: forall alpha, nf alpha -> alpha < epsilon0 ->\n                                          lt_epsilon0 alpha.\nProof.\n induction alpha.\n constructor.\n unfold epsilon0;intros.\n inversion H0.\n rewrite (lt_one_inv H3).\n right.\n apply IHalpha2.\n inversion H;auto with T2.\n compute;auto with T2.\n apply IHalpha3.\n inversion H;auto with T2.\n compute;auto with T2.\n apply transitivity with (cons alpha1 alpha2 n alpha3).\n apply lt_tail.\n auto with T2.\n auto with T2.\n inversion H2.\n inversion H10.\n inversion H2.\n inversion H2.\nQed.\n\n\n\n\n\nLemma T1_injection : forall c c', T1_inj c = T1_inj c' -> c = c'.\nProof.\n induction c; destruct c';simpl;auto with T2.\n discriminate 1.\n discriminate 1.\n injection 1;auto with T2.\n rewrite (IHc1 c'1).\n rewrite (IHc2 c'2).\n destruct 2;auto with T2.\n injection H;auto with T2.\n injection H;auto with T2.\nQed.\n\n\n\n \nLemma T1_injection_lt : forall c, lt_epsilon0 (T1_inj c).\nProof.\n induction c;simpl;constructor;auto with T2.\nQed.\n\n\n\nDefinition lt_T1_injection : forall a, lt_epsilon0 a -> {c:T1 | T1_inj c = a}.\nProof.\n induction a.\n exists EPSILON0.zero;simpl;auto with T2.\n intro.\n case IHa2.\n inversion H;auto with T2.\n intros c2 e2.\n case IHa3.\n inversion H;auto with T2.\n intros c3 e3.\n exists (EPSILON0.cons c2 n c3).\n rewrite <- e3;rewrite <- e2.\n replace a1 with zero.\n simpl;auto with T2.\n inversion H;auto with T2.\nDefined.\n\n\n\nLemma inj_mono : forall c c', (c < c')%ca -> T1_inj c < T1_inj c'.\nProof.\n induction 1;  simpl;auto with T2.\nQed.\n\n\n\n(*\n  In the following proof, some new tactics must make shorter the use\n  of total order on cpnf.\n\n*)\n\nLemma inj_monoR : forall c c', lt (T1_inj c) (T1_inj c') -> (c < c')%ca.\nProof.\n intros.\n case (EPSILON0.trichotomy_inf c c').\n destruct 1.\n auto with T2.\n subst c'.\n case (lt_irr H).\n intro.\n generalize (inj_mono l).\n intro.\n case (lt_irr (alpha:=T1_inj c)).\n eapply transitivity;eauto with T2.\nQed.\n\n\nLemma lt_epsilon0_trans : forall a, lt_epsilon0 a ->  nf a ->\n     forall b, lt b a -> nf b -> lt_epsilon0 b.\n\nProof.\n intros.\n apply lt_epsilon0_okR.\n auto with T2.\n apply transitivity with a.\n auto with T2.\n apply lt_epsilon0_ok;auto with T2.\nQed.\n\nLemma nf_nat_irrelevance : forall a b n n' c, nf (cons a b n c) -> \n                                              nf (cons a b n' c).\nProof.\n   inversion_clear 1;   constructor;auto with T2.\nQed.\n\n\nLemma psi_principal : forall a b c d, nf c -> c < [a, b] \n                                           -> d < [a, b] -> \n                                          c + d < [a, b].\nProof.\n induction c;destruct d;simpl;auto with T2.\n case (compare [c1,c2][d1,d2]).\n intros;apply psi_relevance.\n inversion_clear H0.\n constructor 2;auto with T2.\n constructor 3;auto with T2.\n constructor 4;auto with T2.\n constructor 5;auto with T2.\n inversion H2.\n inversion H2.\nauto with T2.\n intros.\n generalize (IHc3 (cons d1 d2 n0 d3)).\n intros.\n assert (c3 < [a,b]).\n eapply transitivity.\n 2:eexact H0.\n apply lt_tail.\n auto with T2.\n inversion_clear H0.\n constructor 2;auto with T2.\n constructor 3;auto with T2.\n constructor 4;auto with T2.\n constructor 5;auto with T2.\n inversion H4.\n constructor 7;auto with T2.\n inversion H4.\nQed.\n\n\n Lemma nf_intro : forall a b n c, nf a -> nf b -> \n                                  c < [a,b ] -> nf c -> nf (cons a b n c).\n Proof.\n  destruct c;constructor;auto with T2.\n  inversion_clear H1;auto with T2.\n inversion H3.\n inversion H3.\n Qed. \n \n\nLemma plus_nf : forall alpha, nf alpha -> forall beta, nf beta -> \n                                    nf (alpha + beta).\n intros alpha Halpha.\n pattern alpha.\n apply transfinite_induction.\n destruct x.\n simpl;auto with T2.\n destruct beta.\n simpl;auto with T2.\n intros;simpl.\n caseEq ( compare (cons x1 x2 0 zero) (cons beta1 beta2 0 zero)).\n intro;apply nf_intro.\n nf_inv.\n nf_inv.\n  generalize ( compare_eq_rw  H2).\n injection 1.\n intros; subst beta1; subst beta2.\n inversion_clear H1.\n auto with T2.\n apply psi_relevance;auto with T2.\n nf_inv.\n auto.\n intro;apply nf_intro.\n nf_inv.\n nf_inv.\n apply psi_principal.\n nf_inv.\n inversion H;auto.\n \n apply psi_relevance;auto with T2.\n apply psi_relevance;unfold psi; apply compare_gt_rw;auto with T2.\n eapply H0;auto with T2.\n nf_inv.\n apply lt_tail;auto with T2.\n assumption.\nQed.\n\n\n\n\n\nLemma succ_as_plus : forall alpha, nf alpha -> alpha + one = succ alpha.\n intro alpha;elim alpha.\n simpl;auto with T2.\n unfold one;simpl.\n  intros.\ncase t; case t0.\n simpl.\n rewrite plus_0_r;auto with T2.\n simpl.\n rewrite <- H1.\n simpl;auto with T2.\n inversion H2;auto with T2.\n  simpl.\n  rewrite <- H1.\n simpl;auto with T2.\n  inversion H2;auto with T2.\n  simpl.\nrewrite <- H1.\n simpl;auto with T2.\n  inversion H2;auto with T2.  \nQed.\n\n\nLemma succ_nf : forall alpha, nf alpha -> nf (succ alpha).\nProof.\n  intros alpha Halpha.\n  rewrite <- succ_as_plus;auto with T2.\n apply plus_nf;auto with T2.\n compute; constructor;auto with T2.\nQed.\n\n\n\n\n\n \n\nLemma lt_epsilon0_succ : forall a, lt_epsilon0 a -> lt_epsilon0  (succ a).\n induction a.\n simpl.\n repeat constructor.\n simpl.\n case a1.\n case a2.\n repeat constructor.\n constructor.\n inversion H;auto with T2.\n apply IHa3.\n inversion H;auto with T2.\n inversion 1.\nQed.\n\n\nTheorem epsilon0_as_lub : forall b, nf b -> \n                                    (forall a, lt_epsilon0 a -> lt a b) ->\n                                    le epsilon0 b.\nProof.\n intros y Vy Hy.\n tricho epsilon0 y H.\n right;auto with T2.\n left;auto with T2.\n assert (lt_epsilon0 y).\n apply lt_epsilon0_okR;auto with T2.\n generalize (Hy _ H0).\n intro; case (lt_irr (alpha:= y)).\n auto with T2.\nQed.\n\n\n\n(* TO DO :  define glb too *)\n\n\nDefinition lub (P:T2 -> Prop)(x:T2) :=\n  nf x /\\ \n  (forall y, P y -> nf y -> y <= x) /\\\n  (forall y, (forall x, P x -> nf x -> x <= y) -> nf y ->\n                                    x <= y).\n\nTheorem lub_unicity : forall P l l', lub P l -> lub P l' -> l = l'.\nProof.\n intros P l l' (H1,(H2,H3)) (H'1,(H'2,H'3)).\n \n tricho l l' H4.\n absurd (l < l).\n apply lt_irr.\n apply lt_le_trans with l';auto with T2.\n auto with T2.\n absurd (l' < l').\n apply lt_irr.\n apply lt_le_trans with l;auto with T2.\nQed.\n\n\nTheorem lub_mono : forall (P Q :T2 -> Prop) l l', \n                                  (forall o, nf o -> P o -> Q o) ->\n                                    lub P l -> lub Q l' -> l <= l'.\nProof.\n intros P Q l l' H (H1,(H2,H3)) (H'1,(H'2,H'3)).\n auto with T2.\nQed.\n\n\n(* Change into suc_as_glb (see Ord_Complete.v) *)\n(*\nTheorem suc_as_lub : forall o, nf o -> lub (fun x => x = o) (succ o).\nProof.\n unfold lub;intros.\n repeat split.\n apply succ_nf;auto with T2.\n  destruct 1. \n intros;apply lt_succ.\n \n intros.\n apply lt_succ_le; auto with T2.\nQed.\n*)\n\n\nLemma succ_limit_dec : forall a, nf a ->\n         {a = zero} +{is_successor a}+{is_limit a}.\nProof.\n intro a;elim a.\nleft;left;auto.\n intro alpha;case alpha;intro.\n intro beta;case beta;intro.\n intros.\n assert (t=zero). inversion H2;auto.\n inversion H7;lt_clean.\n subst t;left;right.\nconstructor.\n destruct n0;destruct t2.\n right;constructor.\n auto.\n auto with T2.\n nf_inv.\n intros H1 H2;case H1.\n nf_inv.\n destruct 1.\n discriminate e.\nleft;right.\nconstructor;auto.\n right.\n constructor.\n auto.\n auto.\n right.\n constructor;auto.\n auto with T2.\n nf_inv.\n intros H1 H2;case H1.\n nf_inv.\n destruct 1.\n discriminate e.\n left;right;constructor.\n auto.\n auto.\n right;constructor;auto.\n intros.  case H1.\n nf_inv.\n destruct 1.\n subst t3;right;constructor;auto.\n nf_inv.\n nf_inv.\n left;right;constructor;auto.\n right;constructor;auto.\nQed.\n\n \nLemma le_plus_r : forall alpha beta, nf alpha -> nf beta -> \n                                     alpha <= alpha + beta.\nProof.\n induction alpha.\n intros;apply le_zero_alpha.\n destruct beta.\n intros; rewrite plus_alpha_0;auto with T2.\n simpl.\n intros; \n   caseEq( compare (cons alpha1 alpha2 0 zero) (cons beta1 beta2 0 zero)).\n right;constructor 6.\n omega.\n intros;right;apply psi_relevance.\n apply compare_lt_rw.\n auto with T2.\n intro; apply le_cons_tail.\n apply IHalpha3.\n inversion H;auto with T2.\n auto with T2.\nQed.\n\n\nLemma le_plus_l : forall alpha beta, nf alpha -> nf beta -> \n                                     alpha <= beta +  alpha.\nProof.\n induction alpha.\n intros;apply le_zero_alpha.\n destruct beta.\n simpl;auto with T2.\n simpl.\n intros; \n   caseEq(compare (cons beta1 beta2 0 zero) (cons alpha1 alpha2 0 zero)).\n intros.\n generalize (compare_eq_rw  H1).\ninjection 1.\n intros;subst beta1;subst beta2.\n \n right;constructor 6.\n omega.\n left;auto with T2.\n \n intros;right;apply psi_relevance.\n apply compare_gt_rw.\n auto with T2.\nQed.\n\n\nLemma plus_mono_r : forall alpha , nf alpha -> forall beta gamma, nf beta ->\n       nf gamma -> beta < gamma -> alpha + beta < alpha + gamma.\nProof.\n induction alpha.\n simpl.\n auto with T2.\n simpl.\n destruct beta;destruct gamma;simpl.\n inversion 3.\n intros; \n   caseEq (compare (cons alpha1 alpha2 0 zero) (cons gamma1 gamma2 0 zero)).\n constructor 6. \n omega.\n intros;apply psi_relevance.\n apply compare_lt_rw;auto with T2.\n constructor 7.\n pattern alpha3 at 1; rewrite <- plus_alpha_0. \n apply IHalpha3.\n inversion H;auto with T2.\n auto with T2.\n auto with T2.\n auto with T2.\n inversion 3.\n caseEq (compare (cons alpha1 alpha2 0 zero) (cons beta1 beta2 0 zero));\n caseEq ( compare (cons alpha1 alpha2 0 zero) (cons gamma1 gamma2 0 zero)).\n intros.\n  generalize (compare_eq_rw  H1).\n  generalize (compare_eq_rw  H0).\ninjection 1.\ninjection 3.\n subst gamma1;subst gamma2;intros; subst beta2;subst beta1.\n inversion_clear H4.\n case (lt_irr H6).\n case (lt_irr H6).\n case (lt_irr H6).\n case (lt_irr H6).\n constructor 6;omega.\n constructor 7;auto with T2.\nintros.\n generalize (compare_lt_rw  H0).\n generalize (compare_eq_rw  H1).\n intros;apply psi_relevance.\n auto with T2.\nintros.\n generalize (compare_gt_rw  H0).\n generalize (compare_eq_rw  H1).\n injection 1;intros.\n subst beta1;subst beta2.\n case (lt_irr (alpha := (cons alpha1 alpha2 n0 beta3))).\n eapply transitivity.\n eexact H4.\n apply psi_relevance;auto with T2.\nintros.\n generalize (compare_lt_rw  H1).\n generalize (compare_eq_rw  H0).\n  injection 1;intros.\n subst gamma1;subst gamma2.\n  case (lt_irr (alpha :=cons beta1 beta2 n0 beta3)).\n eapply transitivity.\n eexact H4.\n  apply psi_relevance;auto with T2.\nauto with T2.\nintros.\n case (lt_irr (alpha := (cons beta1 beta2 n0 beta3))).\n eapply transitivity.\n eexact H4.\n apply psi_relevance.\napply transitivity with (cons alpha1 alpha2 0 zero);auto with T2.\n\nintros.\n  generalize (compare_eq_rw  H0).\ninjection 1;intros;subst gamma1;subst gamma2.\nconstructor 6;omega.\nintros.\napply psi_relevance.\nauto with T2.\n\nintros.\nconstructor 7.\napply IHalpha3.\ninversion H;auto with T2.\nauto with T2.\nauto with T2.\nauto with T2.\nQed.\n\n\nLemma plus_mono_l_weak: \n forall o, nf o ->\n          forall alpha,  nf alpha -> alpha < o -> \n     forall beta,\n       nf beta -> beta < o ->  forall gamma , nf gamma -> (* gamma <= o -> *)\n         alpha < beta -> alpha + gamma <= beta  + gamma.\n intros o Ho;pattern o.\napply transfinite_induction.\n\n2:auto with T2.\nclear o Ho.\nintros o NF0 Hreco. \n\n\nintro x;case x.\n\nsimpl.\nintros;apply le_plus_l;auto with T2.\n\n \nintros alpha beta n gamma NF.\nintro.\nintro y;case y.\n\ninversion 4.\n\nintros alpha' beta' n' gamma' NF'.\nintros H1  z.\ncase z.\ndo 2 rewrite (plus_alpha_0).\n\nright;auto with T2.\n\nintros alpha'' beta'' n'' gamma''  NF''.\nintros H0.\n\nsimpl (cons alpha beta n gamma + cons alpha'' beta'' n'' gamma'').\ncaseEq ( compare [alpha, beta] [alpha'', beta'']).\nintro H'; generalize  (compare_eq_rw  H'); intro H''.\ninjection H'';intros. subst alpha'';subst beta''.\n simpl (cons alpha' beta' n' gamma' + cons alpha beta n'' gamma'').\n caseEq ( compare [alpha', beta'] [alpha, beta]).\n\nintro H6; generalize  (compare_eq_rw  H6); intro H7.\ninjection H7;intros;subst alpha';subst beta'.\ncase (le_inv_nc (or_intror _ H0)).\nright;constructor 6.\nauto with T2 arith.\nintros (H8,H9);subst n'.\nleft;auto with T2.\n\nintro H6; generalize  (compare_lt_rw  H6); intro H7.\ncase (lt_irr (alpha := cons alpha beta n gamma)).\napply transitivity with (cons alpha' beta' n' gamma');auto with T2.\napply psi_relevance;auto with T2.\n\nintros;right;apply psi_relevance.\napply compare_gt_rw;auto with T2.\n\nintro H'; generalize  (compare_lt_rw  H'); intro H''.\n\n simpl (cons alpha' beta' n' gamma' + cons alpha'' beta'' n'' gamma'').\n caseEq (compare [alpha', beta'] [alpha'', beta'']).\nintro H6; generalize  (compare_eq_rw  H6); intro H7.\ninjection H7;intros;subst alpha';subst beta'.\nright;constructor 6;auto with T2 arith.\n\nintro H6; generalize  (compare_lt_rw  H6); intro H7.\nleft;auto with T2.\n\nintro H6; generalize  (compare_gt_rw  H6); intro H7.\n\nright;apply psi_relevance;auto with T2.\n\nintro H'; generalize  (compare_gt_rw  H'); intro H''.\n\nassert ([alpha'',beta''] < [alpha',beta']).\napply lt_le_trans with [alpha,beta];auto with T2.\ngeneralize (le_psi_term_le (or_intror _ H0)).\nsimpl;auto with T2.\nsimpl ( cons alpha' beta' n' gamma' + cons alpha'' beta'' n'' gamma'').\ncaseEq ( compare [alpha', beta'] [alpha'', beta'']).\n\nintro H6; generalize  (compare_eq_rw  H6); intro H7.\nrewrite H7 in H2.\ncase (lt_irr H2).\n\nintro H6; generalize  (compare_lt_rw  H6); intro H7.\ncase (lt_irr (alpha := [alpha'', beta''])).\napply transitivity with [alpha', beta'];auto with T2.\n\n\nintro H6; generalize  (compare_gt_rw  H6); intro H7.\n\ntricho [alpha, beta] [alpha', beta'] H8.\nright;apply psi_relevance;auto with T2.\ninjection H8;intros;subst alpha';subst beta'.\ncase (le_inv_nc  (or_intror _ H0)).\nright;constructor 6;auto with T2.\nintros (e,H9);subst n'.\ncase H9.\nintro;subst gamma'.\nleft;auto with T2.\nintro H10.\n\nassert (nf gamma).\ninversion NF;auto with T2.\n\nassert (nf gamma').\ninversion NF';auto with T2.\n\n\nassert (gamma <  cons alpha beta n gamma').\napply transitivity with gamma'.\nauto with T2.\napply lt_tail;auto with T2.\n\n\n\n\n\ngeneralize (Hreco  _ NF' H1 gamma H3 H5 gamma' H4 (lt_tail NF')\n  (cons alpha'' beta'' n'' gamma'') NF'' H10).\ndestruct 1;auto with T2.\nrewrite H11;auto with T2.\n\ncase (lt_irr (alpha := cons alpha beta n gamma)).\napply transitivity with (cons alpha' beta' n' gamma');auto with T2.\napply psi_relevance;auto with T2.\nQed.\n\nRemark R_predD_0 : pred zero = None.\n trivial.\nQed.\n\n\nRemark R_pred_Sn : forall n, pred (F (S n)) = Some (F n).\n destruct n;simpl;trivial.\nQed.\n\nLemma pred_of_cons : forall a b n c, \n                       zero < a \\/ zero < b -> \n                       pred (cons a b  n c) = match pred c with\n                                             Some c' => \n                                               Some (cons a b n c')\n                                            |None => None\n                                            end.\n  destruct a.\n destruct b;simpl.\n destruct 1;lt_clean.\n auto.\n simpl.\n auto.\nQed.\n\nLemma pred_of_cons' : forall a b n , \n                       zero < a \\/ zero < b -> \n                       pred (cons a b  n zero) = None.\nProof.\n intros a b n H; rewrite (pred_of_cons n zero H).\n simpl;auto.\nQed.\n\nLemma is_limit_ab : forall alpha beta n gamma, is_limit (cons alpha beta n gamma)\n  -> zero < alpha \\/ zero < beta.\ninversion 1.\n auto.\n generalize H5 H2 ;case gamma.\n  inversion 2.\n\n inversion_clear 1.\n \n\n inversion_clear H7.  \n left;apply le_lt_trans with t;auto with T2.\n right; apply le_lt_trans with t0;auto with T2.\n right;  apply le_lt_trans with [t,t0];auto with T2.\n right;apply le_lt_trans with t;auto with T2.\n lt_clean.\n lt_clean.\nQed.\n\n \n \n\nLemma pred_of_limit : forall alpha,  is_limit alpha -> nf alpha -> pred alpha = None.\nProof.\n induction 1.\n rewrite (pred_of_cons' n H).\n auto.\n rewrite (pred_of_cons (a :=alpha)(b:=beta) n).\n rewrite IHis_limit.\nauto.\n eapply nf_c;eauto.\napply is_limit_ab with n gamma.\nconstructor;auto.\nQed.\n \n\n\nLemma pred_of_succ : forall alpha, nf  alpha -> \n            pred (succ alpha) = Some alpha.\n induction alpha;simpl.\n auto with T2.\n case alpha1;case alpha2.\n simpl.\n inversion_clear 1;auto with T2.\n inversion H0.\n inversion H5.\n inversion H4.\n inversion H12.\n inversion H4.\n inversion H4.\n simpl.\n\n intros;rewrite IHalpha3.\n auto with T2.\n inversion H;auto with T2.\n simpl.\n intros;rewrite IHalpha3.\n auto with T2.\n inversion H;auto with T2.\n simpl.\n  intros;rewrite IHalpha3.\n auto with T2.\n inversion H;auto with T2.\nQed.\n\n\n\n\nLemma limit_plus_F_ok : forall alpha,  is_limit alpha ->\n                           forall n, limit_plus_F alpha n (alpha + F n).\nProof.\n\ninduction alpha.\nsimpl;constructor 1.\nsimpl.\ninversion 1.\nintro n1;case n1.\n simpl.\n constructor 2;auto.\n change (limit_plus_F zero 0 (F 0)).\n \n constructor 1.\n simpl.\n caseEq (compare [alpha1, alpha2] [zero, zero]).\n intro H7; generalize (compare_eq_rw H7).\n injection 1;intros;subst alpha1;subst alpha2.\n subst alpha;subst beta.\n case H3;intro;lt_clean.\n \n  intro H7; generalize (compare_lt_rw H7).\n inversion 1;intros;try lt_clean.\n simpl.\n intros.\n change (limit_plus_F (cons alpha1 alpha2 n zero) (S n2)\n     (cons alpha1 alpha2 n (F (S n2)))).\n constructor.\n auto.\n constructor.\n\n destruct n1.\n simpl.\n \n constructor 2.\n eapply is_limit_ab.\n eexact H.\n generalize H2.\n generalize (nf_c H5).\n elim alpha3.\n intros; change ( limit_plus_F zero 0 (F 0));constructor.\n constructor.\n eapply is_limit_ab.\n eexact H10.\n case (is_limit_cons_inv H9 H10).\n intros.\n \n apply H8.\n nf_inv.\n auto.\n intro;subst t1;change (limit_plus_F zero 0 (F 0));constructor.\nsimpl.\n caseEq (compare [alpha1, alpha2] [zero, zero]).\n intro H7;generalize (compare_eq_rw H7);injection 1;intros.\n subst alpha1;subst alpha2;subst beta;subst alpha.\n generalize (is_limit_ab H).\n destruct 1;lt_clean.\n intro H7;generalize (compare_lt_rw H7);intros.\n inversion H6;lt_clean.\n intro.\n replace (cons zero zero n1 zero) with (F (S n1)).\n constructor 2.\n generalize (compare_gt_rw H6);intros.\n inversion_clear H7;auto with T2.\n lt_clean.\n lt_clean.\n apply IHalpha3.\n auto.\n auto.\nQed.\n\n\n\n\n\n\n \nSection phi_to_psi.\n Variable alpha : T2.\n\n Lemma phi_to_psi_1 : forall beta1 beta2 n, \n                             alpha < beta1 -> \n                             [alpha, (cons beta1 beta2 0 (F n))] =\n                             phi alpha (cons beta1 beta2 0 (F (S n))).\n Proof.\n   intros.\n   generalize (phi_of_psi_succ alpha beta1 beta2 n).\n case (lt_ge_dec alpha beta1).\n auto with T2.\n intro.\n (* TODO : a thm lt_not_ge *)\n absurd (alpha < alpha).\n apply lt_irr.\n eapply lt_le_trans;eauto with T2.\n Qed.\n\n Lemma phi_to_psi_2 : forall beta1 beta2 n, \n                             beta1 <= alpha  -> \n                             [alpha, (cons beta1 beta2 0 (F n))] =\n                             phi alpha (cons beta1 beta2 0 (F n)).\n   intros.\n   case n.\n  simpl (F 0).\n    generalize (phi_of_psi alpha beta1 beta2).\n    case (lt_ge_dec alpha beta1).\n    intro; (absurd (alpha<alpha)). \n   (* Argh *)\n    apply lt_irr.\n    eapply lt_le_trans;eauto with T2.\n  auto with T2.\n\n   intro n0;generalize (phi_of_psi_succ alpha beta1 beta2 n0).\n case (lt_ge_dec alpha beta1).\n 2:auto with T2.\n  intro;  absurd (alpha < alpha).\n apply lt_irr.\n eapply lt_le_trans;eauto with T2.\n Qed.\n\n Lemma phi_to_psi_3 : forall  beta1 beta2 , \n                             beta1 <= alpha  -> \n                             [alpha, [beta1, beta2]] =\n                             phi alpha [beta1, beta2].\n Proof.\n   intros. \n   fold (F 0).\n   apply phi_to_psi_2.\n auto with T2.\nQed.\n\nLemma phi_to_psi_4 : [alpha, zero] = phi alpha zero.\nProof.\n  rewrite phi_alpha_zero;auto with T2.\nQed.\n\nLemma phi_to_psi_5 :\n   forall beta1 beta2 n gamma, omega <= gamma \\/ (0 < n)%nat ->\n           [alpha,cons beta1 beta2 n gamma] =\n           phi alpha (cons beta1 beta2 n gamma).\nProof.\n intros.\n  rewrite phi_of_any_cons;auto with T2.\nQed.\n\nLemma phi_to_psi_6 : forall beta, nf beta ->\n   phi alpha beta = beta -> [alpha,  beta] =phi alpha (succ beta).\n intros.\n case (phi_fix _ H0 ).\n intros beta1 (beta2,(H2,H3)).\n subst beta.\ngeneralize (phi_to_psi_1 beta2  0 H3).  \n  simpl (succ (cons beta1 beta2 0 zero)).\n generalize H3 ; case beta1.\n inversion 1.\n auto with T2.\nQed.\n\n\n(* gamma = gamma0 + F p, gamma0 = zero or gamma0 limit *)\n\n(* simplify this proof !!!!! *)\n \nLemma phi_psi : forall  beta0 beta n, nf beta ->\n  limit_plus_F beta0 n beta ->  phi alpha beta0 = beta0 ->\n                           [alpha, beta]  =  phi alpha (succ beta).\n intros.\n case (phi_fix _ H1).\n intros beta1 (beta2,(H2,H3)).\n assert (beta = (cons beta1 beta2 0 (F n))).\n Focus 2.\n subst beta.\n simpl.\n subst beta0.\n generalize H3 H1.\n case beta1;case beta2.\n inversion 1.\n inversion 2.\n inversion H2.\n replace (succ (F n)) with (F (S n)).\n intros;rewrite phi_to_psi_1.\n auto with T2.\n auto with T2.\n induction n;simpl;auto with T2.\n replace (succ (F n)) with (F (S n)).\n intros;rewrite phi_to_psi_1.\n auto with T2.\n auto with T2.\n  induction n;simpl;auto with T2.\nsubst beta0.\n inversion H0.\n inversion H9.\n auto with T2.\n inversion H10.\n auto with T2.\n inversion H10;auto with T2.\nQed.\n\n\n\nTheorem th_14_5 : forall alpha1 beta1 alpha2 beta2,\n                   nf alpha1 -> nf beta1 -> nf alpha2 -> nf beta2 ->\n                   phi alpha1 beta1 = phi alpha2 beta2 ->\n                   {alpha1 < alpha2 /\\ beta1 = phi alpha2 beta2} +\n                   {alpha1 = alpha2 /\\ beta1 =  beta2} +\n                   {alpha2 < alpha1 /\\ phi alpha1 beta1 = beta2}.\nProof.\n intros alpha1 beta1 alpha2 beta2 nfa1 nfb1 nfa2 nfb2 E.\n tricho alpha1 alpha2 H0.\n generalize (phi_to_psi alpha2 beta2).\n  intros (gamma1, (gamma2, E')).\n assert (alpha2 <= gamma1).\n eapply phi_le.\n 2:eexact E'.\n auto.\n left.\n left;split;auto.\n assert (phi alpha1 (phi alpha2 beta2) = phi alpha2 beta2).\n repeat rewrite E'.\n simpl.\n generalize (lt_le_trans H0 H);intro H1.\n rewrite (compare_rw_lt H1).\n auto.\n pattern (phi alpha2 beta2) at 2 in H1.\n rewrite <- E in H1.\n apply phi_inj_r with alpha1;auto.\n apply phi_nf;auto.\n subst alpha2.\n left.\n right.\n split;auto.\n apply phi_inj_r with alpha1;auto.\n generalize (phi_to_psi alpha1 beta1).\n intros (gamma1, (gamma2, E')).\n assert (alpha1 <= gamma1).\n apply phi_le with beta1 gamma2.\n auto.\n auto.\n right. \n split;auto.\n assert (phi alpha2 (phi alpha1 beta1) = phi alpha1 beta1).\n repeat rewrite E'.\n simpl.\n generalize (lt_le_trans H0 H);intro H1.\n rewrite (compare_rw_lt H1).\n auto.\n pattern (phi alpha1 beta1) at 2 in H1.\n rewrite E in H1.\n apply phi_inj_r with alpha2;auto.\n apply phi_nf;auto.\nQed.\n\nLemma lt_not_gt : forall a b, a < b -> ~ (b < a).\nProof.\n  intros a b H H0.\n  case (lt_irr (alpha := a));auto.\n  apply transitivity with b;auto.\nQed.\n\nLemma phi_mono_RR : forall a b c, nf a -> nf b -> nf c ->\n              phi a b < phi a c -> b < c.\n Proof.\n  intros;tricho b c T;auto.\n  subst c. case (lt_irr H2).\n  case (lt_not_gt H2).\n  apply phi_mono_r;auto.\n Qed.\n\nTheorem th_14_6 : forall alpha1 beta1 alpha2 beta2,\n                   nf alpha1 -> nf beta1 -> nf alpha2 -> nf beta2 ->\n                   phi alpha1 beta1 < phi alpha2 beta2 ->\n                   {alpha1 < alpha2 /\\ beta1 < phi alpha2 beta2} +\n                   {alpha1 = alpha2 /\\ beta1 <  beta2} +\n                   {alpha2 < alpha1 /\\ phi alpha1 beta1 < beta2}.\nProof.\n intros alpha1 beta1 alpha2 beta2 nfa1 nfb1 nfa2 nfb2 E.\n tricho alpha1 alpha2 H0.\n generalize (phi_to_psi alpha2 beta2).\n  intros (gamma1, (gamma2, E')).\n assert (alpha2 <= gamma1).\n eapply phi_le.\n 2:eexact E'.\n auto.\n left.\n left;split;auto.\n apply le_lt_trans with (phi alpha1 beta1);auto.\n apply le_b_phi_ab;auto.\n subst alpha2.\nleft;right.\n split;auto.\n tricho beta1 beta2 H;auto.\n subst beta2;case (lt_irr E).\n case (lt_not_gt E).\n apply phi_mono_r;auto.\n right. \n split;auto. \n generalize (phi_to_psi alpha1 beta1).\n intros (gamma1, (gamma2, E')).\n assert (alpha1 <= gamma1).\n apply phi_le with beta1 gamma2.\n auto.\n auto.\n assert (alpha2 < gamma1).\n apply lt_le_trans with alpha1;auto.\n\n assert (phi alpha2 (phi alpha1 beta1) = phi alpha1 beta1).\n repeat rewrite E'.\n simpl.\n rewrite (compare_rw_lt H1).\n auto.\n\n assert (phi alpha2 (phi alpha1 beta1) < phi alpha2 beta2).\n eapply le_lt_trans.\n eleft;eexact H2.\n auto.\n apply phi_mono_RR with alpha2;auto.\n apply phi_nf;auto.\nQed.\n\n\n(* First admitted lemma !!!!!! *)\n\nDefinition moser_lepper (beta0 beta:T2)(n:nat) :=\n limit_plus_F beta0 n beta /\\ phi alpha beta0 = beta0.\n\nLemma ml_psi : forall beta0 beta n, moser_lepper beta0 beta n ->\n                                    {t1 : T2 & {t2: T2| beta0 = [t1,t2] /\\ alpha < t1}}.\nProof.\n intros beta0 beta n (H1,H2).\n case (phi_fix  _  H2).\n intros x (y,(H3,H4)).\n exists x;exists y;auto.\nQed.\n\nLemma ml_1 : forall beta0 beta n, moser_lepper beta0 beta n -> nf beta -> nf beta0 ->\n                               [alpha, beta] = phi alpha (succ beta).\n intros;eapply phi_psi;eauto.\n case H.\n intros;eassumption.\n case H;intros.\n auto.\nQed.\n\n\n \n                                                          \nEnd phi_to_psi.\n\n\n\n\n\n\n\n\n \n\n\n", "meta": {"author": "coq-contribs", "repo": "cantor", "sha": "6335058d65fe4cab134654ba0b5e8142512cfcf9", "save_path": "github-repos/coq/coq-contribs-cantor", "path": "github-repos/coq/coq-contribs-cantor/cantor-6335058d65fe4cab134654ba0b5e8142512cfcf9/gamma0/Gamma0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2876750427704903}}
{"text": "Require Import VST.floyd.base.\nRequire Import VST.floyd.assert_lemmas.\nRequire Import VST.floyd.client_lemmas.\nRequire Import VST.floyd.closed_lemmas.\n\nLocal Open Scope logic.\n\nLemma closed_wrt_wand: forall (S : ident -> Prop) (P Q : environ -> mpred),\n       closed_wrt_vars S P ->\n       closed_wrt_vars S Q -> closed_wrt_vars S (P -* Q).\nProof.\n  intros; hnf in *; intros.\n  simpl. f_equal; eauto.\nQed.\n\nLemma closed_wrtl_wand: forall (S : ident -> Prop) (P Q : environ -> mpred),\n       closed_wrt_lvars S P ->\n       closed_wrt_lvars S Q -> closed_wrt_lvars S (P -* Q).\nProof.\n  intros; hnf in *; intros.\n  simpl. f_equal; eauto.\nQed.\n\nHint Resolve closed_wrt_wand closed_wrtl_wand : closed.\n", "meta": {"author": "johndoe20190406", "repo": "RamifyCoq", "sha": "72fb538b40ee8ea641e4bf5fe6cd232756d0929c", "save_path": "github-repos/coq/johndoe20190406-RamifyCoq", "path": "github-repos/coq/johndoe20190406-RamifyCoq/RamifyCoq-72fb538b40ee8ea641e4bf5fe6cd232756d0929c/floyd_ext/closed_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2876719959826228}}
{"text": "Require Import Coqlib.\nRequire Export ZArith.\nRequire Import String.\nRequire Import PCM.\nRequire Export AList.\n\nSet Implicit Arguments.\n\nLocal Open Scope nat_scope.\n\nNotation gname := string (only parsing). (*** convention: not capitalized ***)\nNotation mname := string (only parsing). (*** convention: capitalized ***)\n\n\nFixpoint _find_idx {A} (f: A -> bool) (l: list A) (acc: nat): option (nat * A) :=\n  match l with\n  | [] => None\n  | hd :: tl => if (f hd) then Some (acc, hd) else _find_idx f tl (S acc)\n  end\n.\n\nDefinition find_idx {A} (f: A -> bool) (l: list A): option (nat * A) := _find_idx f l 0.\n\nNotation \"'do' ' X <- A ; B\" := (o_bind A (fun _x => match _x with | X => B end))\n                                  (at level 200, X pattern, A at level 100, B at level 200)\n                                : o_monad_scope.\n\nLemma find_idx_red {A} (f: A -> bool) (l: list A):\n  find_idx f l =\n  match l with\n  | [] => None\n  | hd :: tl =>\n    if (f hd)\n    then Some (0%nat, hd)\n    else\n      do (n, a) <- find_idx f tl;\n      Some (S n, a)\n  end.\nProof.\n  unfold find_idx. generalize 0. induction l; ss.\n  i. des_ifs; ss.\n  - rewrite Heq0. ss.\n  - rewrite Heq0. specialize (IHl (S n)). rewrite Heq0 in IHl. ss.\nQed.\n\n\nModule SkEnv.\n\n  Notation mblock := nat (only parsing).\n  Notation ptrofs := Z (only parsing).\n\n  Record t: Type := mk {\n    blk2id: mblock -> option gname;\n    id2blk: gname -> option mblock;\n  }\n  .\n\n  Definition wf (ske: t): Prop :=\n    forall id blk, ske.(id2blk) id = Some blk <-> ske.(blk2id) blk = Some id.\n\nEnd SkEnv.\n\n\n\n\n\n\nRequire Import Orders.\n\nModule Sk.\n  Class ld: Type := mk {\n    t:> Type;\n    unit: t;\n    add: t -> t -> t;\n    canon: t -> t;\n    wf: t -> Prop;\n    add_comm: forall a b (WF: wf (add a b)),\n        canon (add a b) = canon (add b a);\n    add_assoc: forall a b c, add a (add b c) = add (add a b) c;\n    add_unit_l: forall a, add unit a = a;\n    add_unit_r: forall a, add a unit = a;\n    wf_comm: forall a b, wf (add a b) -> wf (add b a);\n    unit_wf: wf unit;\n    wf_mon: forall a b, wf (canon (add a b)) -> wf (canon a);\n\n    extends := fun a b => exists ctx, canon (add a ctx) = b;\n  }\n  .\n\n\n  (* Imp Instance *)\n  Inductive gdef: Type := Gfun | Gvar (gv: Z).\n\n  Module GDef <: Typ. Definition t := gdef. End GDef.\n  Module SkSort := AListSort GDef.\n\n  Definition sort: alist gname gdef -> alist gname gdef := SkSort.sort.\n\n  Program Definition gdefs: ld :=\n    @mk (alist gname gdef) nil (@List.app _) sort (fun sk => @List.NoDup _ (List.map fst sk)) _ _ _ _ _ _ _.\n  Next Obligation.\n  Proof.\n    eapply SkSort.sort_add_comm. auto.\n    (* eapply Permutation.Permutation_NoDup; [|et]. *)\n    (* eapply Permutation.Permutation_map. *)\n    (* symmetry. eapply SkSort.sort_permutation. *)\n  Qed.\n  Next Obligation.\n  Proof.\n    eapply List.app_assoc.\n  Qed.\n  Next Obligation.\n  Proof.\n    rewrite List.app_nil_r. auto.\n  Qed.\n  Next Obligation.\n  Proof.\n    i. eapply Permutation.Permutation_NoDup; [|et].\n    eapply Permutation.Permutation_map.\n    apply Permutation.Permutation_app_comm.\n  Qed.\n  Next Obligation.\n  Proof.\n    econs.\n  Qed.\n  Next Obligation.\n  Proof.\n    cut (NoDup (map fst a)).\n    { i. eapply Permutation.Permutation_NoDup; [|et].\n      eapply Permutation.Permutation_map.\n      eapply SkSort.sort_permutation. }\n    cut (NoDup (map fst (a ++ b))).\n    { i. rewrite map_app in H0.\n      eapply nodup_app_l. et. }\n    i. eapply Permutation.Permutation_NoDup; [|et].\n    eapply Permutation.Permutation_map.\n    symmetry. eapply SkSort.sort_permutation.\n  Qed.\n\n  Local Existing Instance gdefs.\n\n  Definition sort_add_comm sk0 sk1\n             (WF: wf (add sk0 sk1))\n    :\n      sort (add sk0 sk1) = sort (add sk1 sk0).\n  Proof.\n    eapply SkSort.sort_add_comm. eapply WF.\n  Qed.\n\n  Definition sort_wf sk (WF: wf sk):\n    wf (sort sk).\n  Proof.\n    ss. eapply Permutation.Permutation_NoDup; [|apply WF].\n    eapply Permutation.Permutation_map.\n    eapply SkSort.sort_permutation.\n  Qed.\n\n  (*** TODO: It might be nice if Sk.t also constitutes a resource algebra ***)\n  (*** At the moment, List.app is not assoc/commutative. We need to equip RA with custom equiv. ***)\n\n  Definition load_skenv (sk: t): (SkEnv.t) :=\n    let n := List.length sk in\n    {|\n      SkEnv.blk2id := fun blk => do '(gn, _) <- (List.nth_error sk blk); Some gn;\n      SkEnv.id2blk := fun id => do '(blk, _) <- find_idx (fun '(id', _) => string_dec id id') sk; Some blk\n    |}\n  .\n\n  Lemma load_skenv_wf\n        sk\n        (WF: wf sk)\n    :\n      <<WF: SkEnv.wf (load_skenv sk)>>\n  .\n  Proof.\n    r in WF.\n    rr. split; i; ss.\n    - uo; des_ifs.\n      + f_equal. ginduction sk; ss. i. inv WF.\n        rewrite find_idx_red in Heq1. des_ifs; ss.\n        { des_sumbool. subst. ss. clarify. }\n        des_sumbool. uo. des_ifs. destruct p. ss.\n        hexploit IHsk; et.\n      + exfalso. ginduction sk; ss. i. inv WF.\n        rewrite find_idx_red in Heq2. des_ifs; ss.\n        des_sumbool. uo. des_ifs. destruct p. ss.\n        hexploit IHsk; et.\n    - ginduction sk; ss.\n      { i. uo. ss. destruct blk; ss. }\n      i. destruct a. inv WF. uo. destruct blk; ss; clarify.\n      {  rewrite find_idx_red. uo. des_ifs; des_sumbool; ss. }\n      hexploit IHsk; et. i.\n      rewrite find_idx_red. uo. des_ifs; des_sumbool; ss. exfalso.\n      subst. clear - Heq1 H2. ginduction sk; ss. i.\n      rewrite find_idx_red in Heq1. des_ifs; des_sumbool; ss; et.\n      uo. des_ifs. destruct p. eapply IHsk; et.\n  Qed.\n\n  Definition incl (sk0 sk1: Sk.t): Prop :=\n    forall gn gd (IN: List.In (gn, gd) sk0),\n      List.In (gn, gd) sk1.\n\n  Program Instance incl_PreOrder: PreOrder incl.\n  Next Obligation.\n  Proof.\n    ii. ss.\n  Qed.\n  Next Obligation.\n  Proof.\n    ii. eapply H0. eapply H. ss.\n  Qed.\n\n  Lemma sort_incl sk\n    :\n      incl sk (sort sk).\n  Proof.\n    ii. eapply Permutation.Permutation_in; [|apply IN].\n    eapply SkSort.sort_permutation.\n  Qed.\n\n  Lemma sort_incl_rev sk\n    :\n      incl (sort sk) sk.\n  Proof.\n    ii. eapply Permutation.Permutation_in; [|apply IN].\n    symmetry. eapply SkSort.sort_permutation.\n  Qed.\n\n  Definition incl_env (sk0: Sk.t) (skenv: SkEnv.t): Prop :=\n    forall gn gd (IN: List.In (gn, gd) sk0),\n    exists blk, <<FIND: skenv.(SkEnv.id2blk) gn = Some blk>>.\n\n  Lemma incl_incl_env sk0 sk1\n        (INCL: incl sk0 sk1)\n    :\n      incl_env sk0 (load_skenv sk1).\n  Proof.\n    ii. exploit INCL; et. i. ss. uo. des_ifs; et.\n    exfalso. clear - x0 Heq0. ginduction sk1; et.\n    i. ss. rewrite find_idx_red in Heq0. des_ifs.\n    des_sumbool. uo.  des_ifs. des; clarify.\n    eapply IHsk1; et.\n  Qed.\n\n  Lemma in_env_in_sk :\n    forall sk blk symb\n      (FIND: SkEnv.blk2id (Sk.load_skenv sk) blk = Some symb),\n    exists def, In (symb, def) sk.\n  Proof.\n    i. unfold SkEnv.blk2id. ss.\n    uo. des_ifs. des; clarify.\n    eapply nth_error_In in Heq0. et.\n  Qed.\n\n  Lemma in_sk_in_env :\n    forall sk def symb\n           (IN: In (symb, def) sk),\n    exists blk, SkEnv.blk2id (Sk.load_skenv sk) blk = Some symb.\n  Proof.\n    i. unfold SkEnv.blk2id. ss.\n    uo. eapply In_nth_error in IN. des.\n    eexists. rewrite IN. et.\n  Qed.\n\n  Lemma env_range_some :\n    forall sk blk\n      (BLKRANGE : blk < Datatypes.length sk),\n      <<FOUND : exists symb, SkEnv.blk2id (Sk.load_skenv sk) blk = Some symb>>.\n  Proof.\n    i. depgen sk. induction blk; i; ss; clarify.\n    { destruct sk; ss; clarify.\n      { lia. }\n      uo. destruct p. exists s. ss. }\n    destruct sk; ss; clarify.\n    { lia. }\n    apply lt_S_n in BLKRANGE. eapply IHblk; eauto.\n  Qed.\n\n  Lemma env_found_range :\n    forall sk symb blk\n      (FOUND : SkEnv.id2blk (Sk.load_skenv sk) symb = Some blk),\n      <<BLKRANGE : blk < Datatypes.length sk>>.\n  Proof.\n    induction sk; i; ss; clarify.\n    uo; des_ifs. destruct p0. rewrite find_idx_red in Heq0. des_ifs.\n    { apply Nat.lt_0_succ. }\n    destruct blk.\n    { apply Nat.lt_0_succ. }\n    uo. des_ifs. destruct p. ss. clarify. apply lt_n_S. eapply IHsk; eauto.\n    instantiate (1:=symb). rewrite Heq0. ss.\n  Qed.\n\nEnd Sk.\n", "meta": {"author": "alxest", "repo": "CCR", "sha": "edcda8faae6580581e8e5b28050d755bcb29f55f", "save_path": "github-repos/coq/alxest-CCR", "path": "github-repos/coq/alxest-CCR/CCR-edcda8faae6580581e8e5b28050d755bcb29f55f/ems/Skeleton.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2876719959826228}}
{"text": "Require Import Coq.Lists.List Coq.Bool.Bool.\nRequire Import Coq.Setoids.Setoid Coq.Classes.RelationClasses.\nRequire Import ExtLib.Tactics.EqDep.\nRequire Import ExtLib.Tactics.Consider.\nRequire Import MirrorShard.Expr.\nRequire Import MirrorShard.SepTheory.\nRequire Import MirrorShard.Folds MirrorShard.Tactics.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nDefinition BadInj types (e : expr types) := False.\nDefinition BadPred (f : func) := False.\nDefinition BadPredApply types (f : func) (es : list (expr types)) (_ : env types) := False.\n\nModule Type SepExpr (ST : SepTheory.SepTheory).\n\n  Section env.\n    Variable types : list type.\n\n    Record predicate := PSig\n    { SDomain : list tvar\n    ; SDenotation : functionTypeD (map (@tvarD types) SDomain) ST.hprop\n    }.\n\n    Definition predicates : Type := list predicate.\n\n    Parameter Default_predicate : predicate.\n\n    Inductive sexpr : Type :=\n    | Emp : sexpr\n    | Inj : expr types -> sexpr\n    | Star : sexpr -> sexpr -> sexpr\n    | Exists : tvar -> sexpr -> sexpr\n    | Func : func -> list (expr types) -> sexpr\n    | Const : ST.hprop -> sexpr\n    .\n\n    Definition tpredicate : Type := list tvar.\n    Definition tpredicates : Type := list tpredicate.\n\n    Definition typeof_pred : predicate -> tpredicate := SDomain.\n    Definition typeof_preds : predicates -> tpredicates := map typeof_pred.\n\n    Section types.\n      Variable funcs : tfunctions.\n      Variable preds : tpredicates.\n      Variable tU : tenv.\n\n      Fixpoint WellTyped_sexpr (tG : tenv) (s : sexpr) : bool :=\n        match s with\n          | Emp => true\n          | Inj e => is_well_typed funcs tU tG e tvProp\n          | Star l r => WellTyped_sexpr tG l && WellTyped_sexpr tG r\n          | Exists t e => WellTyped_sexpr (t :: tG) e\n          | Func f args =>\n            match nth_error preds f with\n              | None => false\n              | Some ts => all2 (is_well_typed funcs tU tG) args ts\n            end\n          | Const _ => true\n        end.\n\n    End types.\n\n    (** sexprD (U ++ U') (G ++ G') e <===>\n     ** sexprD (U ++ U'' ++ U') (G ++ G'' ++ G')\n     **    (liftSExpr (length U) (length U'') (length G) (length G'') e)\n     **)\n    Fixpoint liftSExpr ua ub a b s : sexpr :=\n      match s with\n        | Emp => Emp\n        | Const c => Const c\n        | Inj p => Inj (liftExpr ua ub a b p)\n        | Star l r => Star (liftSExpr ua ub a b l) (liftSExpr ua ub a b r)\n        | Exists t s => Exists t (liftSExpr ua ub (S a) b s)\n        | Func f args => Func f (map (liftExpr ua ub a b) args)\n      end.\n\n    Section funcs_preds.\n      Variable funcs : functions types.\n      Variable preds : predicates.\n      Variable meta_env : env types.\n      \n      Fixpoint sexprD (var_env : env types) (s : sexpr) : ST.hprop :=\n        match s with \n          | Emp => ST.emp\n          | Inj p =>\n            match exprD funcs meta_env var_env p tvProp with\n              | None => ST.inj (BadInj p)\n              | Some p => ST.inj p\n            end\n          | Star l r =>\n            ST.star (sexprD var_env l) (sexprD var_env r)\n          | Exists t b =>\n            ST.ex (fun x : tvarD types t => sexprD (@existT _ _ t x :: var_env) b)\n          | Func f b =>\n            match nth_error preds f with\n              | None => ST.inj (BadPred f)\n              | Some f' =>\n                match applyD (@exprD types funcs meta_env var_env) (SDomain f') b _ (SDenotation f') with\n                  | None => ST.inj (BadPredApply f b var_env)\n                  | Some p => p\n                end\n            end\n          | Const p => p\n        end.\n\n      Definition himp (var_env : env types)\n        (gl gr : sexpr) : Prop :=\n        ST.himp (sexprD var_env gl) (sexprD var_env gr).\n\n      Definition heq (var_env : env types)\n        (gl gr : sexpr) : Prop :=\n        ST.heq (sexprD var_env gl) (sexprD var_env gr).\n\n    End funcs_preds.\n\n    Fixpoint existsEach (ls : list tvar) {struct ls} : sexpr -> sexpr :=\n      match ls with\n        | nil => fun x => x\n        | t :: ts => fun y => Exists t (@existsEach ts y)\n      end.\n\n  End env.\n\n  Implicit Arguments Emp [ types ].\n  Implicit Arguments Star [ types ].\n  Implicit Arguments Exists [ types ].\n  Implicit Arguments Func [ types ].\n  Implicit Arguments Const [ types ].\n  Implicit Arguments Inj [ types ].\n\nEnd SepExpr.\n\n\nModule SepExprFacts (ST : SepTheory) (SE : SepExpr ST).\n  Module SEP_FACTS := SepTheory_Rewrites ST.\n\n  Section env.\n    Variable types : list type.\n    Variable funcs : functions types.\n    Variable preds : SE.predicates types.\n    \n    Variables U G : env types.\n\n    Global Instance Trans_himp : Transitive (@SE.himp types funcs preds U G).\n    Proof.\n      red. unfold SE.himp. intros; etransitivity; eauto.\n    Qed.\n\n    Global Instance Trans_heq : Transitive (@SE.heq types funcs preds U G).\n    Proof.\n      red. unfold SE.heq. intros; etransitivity; eauto.\n    Qed.\n\n    Global Instance Refl_himp : Reflexive (@SE.himp types funcs preds U G).\n    Proof.\n      red; unfold SE.himp; intros. reflexivity.\n    Qed.\n\n    Global Instance Refl_heq : Reflexive (@SE.heq types funcs preds U G).\n    Proof.\n      red; unfold SE.heq; intros. reflexivity.\n    Qed.\n\n    Global Instance Sym_heq : Symmetric (@SE.heq types funcs preds U G).\n    Proof.\n      red; unfold SE.heq; intros. symmetry. auto.    \n    Qed.\n\n    Global Instance Equiv_heq : Equivalence (SE.heq funcs preds U G).\n    Proof.\n      constructor; eauto with typeclass_instances.\n    Qed.\n\n    Lemma heq_defn : forall P Q,\n      (@SE.himp types funcs preds U G P Q /\\\n       @SE.himp types funcs preds U G Q P) <->\n      (@SE.heq types funcs preds U G P Q).\n    Proof.\n      unfold SE.heq, SE.himp. intros; apply ST.heq_defn. \n    Qed.\n\n    Lemma heq_himp : forall P Q,\n      @SE.heq types funcs preds U G P Q ->\n      @SE.himp types funcs preds U G P Q.\n    Proof.\n      unfold SE.heq, SE.himp. intros. apply ST.heq_defn in H; intuition.\n    Qed.\n\n    Lemma himp_not_WellTyped : forall tfuncs tG tU f P Q l,\n      WellTyped_env tU U ->\n      WellTyped_env tG G ->\n      WellTyped_funcs tfuncs funcs ->\n      (forall p, \n        nth_error preds f = Some p ->\n        Folds.all2 (@is_well_typed types tfuncs tU tG) l (SE.SDomain p) = true ->\n        SE.himp funcs preds U G (SE.Star (SE.Func f l) P) Q) ->\n      SE.himp funcs preds U G (SE.Star (SE.Func f l) P) Q.\n    Proof.\n      intros. unfold SE.himp in *; simpl in *. consider (nth_error preds f); intros;\n        try solve [ eapply ST.himp_star_pure_c; contradiction ].\n      match goal with\n        | [ |- context [ match ?X with | _ => _ end ] ] =>\n          case_eq X\n      end; intros; try solve [ eapply ST.himp_star_pure_c; contradiction ].\n      specialize (H3 _ refl_equal). rewrite <- H3. rewrite H4. reflexivity.\n\n      clear H2. clear H3. destruct p; simpl in *. generalize dependent l.\n      induction SDomain; destruct l; simpl; intros; auto; try congruence.\n      revert H4. consider (exprD funcs U G e a); intros.\n      erewrite is_well_typed_correct_only by eauto. eapply IHSDomain; eauto. congruence.\n    Qed.\n\n    Add Parametric Relation : (@SE.sexpr types) (@SE.himp types funcs preds U G)\n      reflexivity proved by  Refl_himp\n      transitivity proved by Trans_himp\n    as himp_rel.\n\n    Add Parametric Relation : (@SE.sexpr types) (@SE.heq types funcs preds U G)\n      reflexivity proved by  Refl_heq\n      symmetry proved by Sym_heq\n      transitivity proved by Trans_heq\n    as heq_rel.\n\n    Global Add Parametric Morphism : (@SE.Star types) with\n      signature (SE.himp funcs preds U G ==> SE.himp funcs preds U G ==> SE.himp funcs preds U G)      \n      as star_himp_mor.\n    Proof.\n      unfold SE.himp; simpl; intros; eapply SEP_FACTS.star_himp_mor; eauto.\n    Qed.\n\n    Global Add Parametric Morphism : (@SE.Star types) with\n      signature (SE.heq funcs preds U G ==> SE.heq funcs preds U G ==> SE.heq funcs preds U G)      \n      as star_heq_mor.\n    Proof.\n      unfold SE.himp; simpl; intros; eapply SEP_FACTS.star_heq_mor; eauto.\n    Qed.\n\n    Global Add Parametric Morphism : (SE.himp funcs preds U G) with \n      signature (SE.heq funcs preds U G ==> SE.heq funcs preds U G ==> Basics.impl)\n      as himp_heq_mor.\n    Proof.\n      unfold SE.heq; simpl; intros. eapply SEP_FACTS.himp_heq_mor; eauto.\n    Qed.\n\n    Global Add Parametric Morphism : (SE.himp funcs preds U G) with \n      signature (SE.himp funcs preds U G --> SE.himp funcs preds U G ==> Basics.impl)\n      as himp_himp_mor.\n    Proof.\n      unfold SE.himp; simpl; intros. intro. etransitivity. eauto. etransitivity; eauto.\n    Qed.\n\n    Global Add Parametric Morphism : (SE.himp funcs preds U G) with \n      signature (SE.himp funcs preds U G --> SE.himp funcs preds U G ++> Basics.impl)\n      as himp_himp_mor'.\n    Proof.\n      unfold SE.himp; simpl; intros. eapply SEP_FACTS.himp_himp_mor; eauto.\n    Qed.\n\n    Global Add Parametric Morphism : (SE.sexprD funcs preds U G) with \n      signature (SE.heq funcs preds U G ==> ST.heq)\n      as heq_ST_heq_mor.\n    Proof.\n      unfold SE.heq; simpl; auto.\n    Qed.\n\n    Global Add Parametric Morphism : (SE.sexprD funcs preds U G) with \n      signature (SE.himp funcs preds U G ==> ST.himp)\n      as himp_ST_himp_mor.\n    Proof.\n      unfold SE.himp; simpl; auto.\n    Qed.\n\n    Lemma heq_star_emp_r : forall P, \n      SE.heq funcs preds U G (SE.Star P SE.Emp) P.\n    Proof.\n      unfold SE.heq; simpl; intros; autorewrite with hprop; reflexivity.\n    Qed.\n\n    Lemma heq_star_emp_l : forall P, \n      SE.heq funcs preds U G (SE.Star SE.Emp P) P.\n    Proof.\n      unfold SE.heq; simpl; intros; autorewrite with hprop; reflexivity.\n    Qed.\n\n    Lemma heq_star_assoc : forall P Q R, \n      SE.heq funcs preds U G (SE.Star (SE.Star P Q) R) (SE.Star P (SE.Star Q R)).\n    Proof.\n      unfold SE.heq; simpl; intros; autorewrite with hprop. rewrite ST.heq_star_assoc. reflexivity.\n    Qed.\n\n    Lemma heq_star_comm : forall P Q, \n      SE.heq funcs preds U G (SE.Star P Q) (SE.Star Q P).\n    Proof.\n      unfold SE.heq; simpl; intros; apply ST.heq_star_comm.\n    Qed.\n\n    Lemma heq_star_frame : forall P Q R S, \n      SE.heq funcs preds U G P R ->\n      SE.heq funcs preds U G Q S ->\n      SE.heq funcs preds U G (SE.Star P Q) (SE.Star R S).\n    Proof.\n      unfold SE.heq; simpl; intros. eapply ST.heq_star_frame; auto.\n    Qed.\n    \n    Lemma himp_star_frame : forall P Q R S,\n      SE.himp funcs preds U G P R ->\n      SE.himp funcs preds U G Q S ->\n      SE.himp funcs preds U G (SE.Star P Q) (SE.Star R S).\n    Proof.\n      unfold SE.himp; simpl; intros. rewrite H; rewrite H0; reflexivity.\n    Qed.\n    \n    Lemma heq_star_comm_p : forall P Q R,\n      SE.heq funcs preds U G (SE.Star P Q) R ->\n      SE.heq funcs preds U G (SE.Star Q P) R.\n    Proof.\n      intros. rewrite heq_star_comm. auto.\n    Qed.\n\n    Lemma heq_star_comm_c : forall P Q R,\n      SE.heq funcs preds U G R (SE.Star P Q) ->\n      SE.heq funcs preds U G R (SE.Star Q P).\n    Proof.\n      intros. rewrite heq_star_comm. auto.\n    Qed.\n\n    Lemma heq_star_assoc_p1 : forall P Q R S,\n      SE.heq funcs preds U G (SE.Star P (SE.Star Q R)) S ->\n      SE.heq funcs preds U G (SE.Star (SE.Star P Q) R) S.\n    Proof.\n      intros. rewrite heq_star_assoc; auto.\n    Qed.\n\n    Lemma heq_star_assoc_p2 : forall P Q R S,\n      SE.heq funcs preds U G (SE.Star Q (SE.Star P R)) S ->\n      SE.heq funcs preds U G (SE.Star (SE.Star P Q) R) S.\n    Proof.\n      intros. apply heq_star_assoc_p1 in H. rewrite <- H.\n      apply heq_star_frame; try reflexivity. rewrite heq_star_comm. reflexivity.\n    Qed.\n\n    Lemma heq_star_assoc_c1 : forall P Q R S,\n      SE.heq funcs preds U G S (SE.Star P (SE.Star Q R)) ->\n      SE.heq funcs preds U G S (SE.Star (SE.Star P Q) R).\n    Proof.\n      intros. rewrite heq_star_assoc; auto.\n    Qed.\n\n    Lemma heq_star_assoc_c2 : forall P Q R S,\n      SE.heq funcs preds U G S (SE.Star Q (SE.Star P R)) ->\n      SE.heq funcs preds U G S (SE.Star (SE.Star P Q) R).\n    Proof.\n      intros. apply heq_star_assoc_c1 in H. rewrite H.\n      apply heq_star_frame; try reflexivity. apply heq_star_comm; reflexivity.\n    Qed.\n\n    Lemma heq_star_emp_p : forall P S,\n      SE.heq funcs preds U G P S ->\n      SE.heq funcs preds U G (SE.Star SE.Emp P) S.\n    Proof.\n      intros. rewrite heq_star_emp_l. auto.\n    Qed.\n\n    Lemma heq_star_emp_c : forall P S,\n      SE.heq funcs preds U G S P ->\n      SE.heq funcs preds U G S (SE.Star SE.Emp P).\n    Proof.\n      intros. rewrite heq_star_emp_l. auto.\n    Qed.\n\n  End env.\n\n  Ltac heq_canceler :=\n    let cancel cp ap1 ap2 ep cc ac1 ac2 ec frm P Q :=\n      let rec iter_right Q :=\n        match Q with \n          | SE.Emp =>\n            apply ec\n          | SE.Star ?L ?R =>\n            (apply ac1 ; iter_right L) || (apply ac2 ; iter_right R)\n          | _ => \n            apply frm; [ reflexivity | ]\n        end\n      in\n      let rec iter_left P :=\n        match P with\n          | SE.Emp =>\n            apply ep\n          | SE.Star ?L ?R =>\n            (apply ap1 ; iter_left L) || (apply ap2 ; iter_left R)\n          | _ => \n            match Q with\n              | SE.Star ?A ?B =>\n                iter_right A || (apply cc; iter_right B)\n            end\n        end\n      in\n      match P with \n        | SE.Star ?A ?B =>\n          iter_left A || (apply cp; iter_left B)\n      end\n    in\n    repeat (rewrite heq_star_emp_l || rewrite heq_star_emp_r) ;\n    repeat match goal with\n             | [ |- @SE.heq _ _ _ _ _ ?P ?Q ] =>\n               cancel heq_star_comm_p heq_star_assoc_p1 heq_star_assoc_p2 heq_star_emp_p \n                      heq_star_comm_c heq_star_assoc_c1 heq_star_assoc_c2 heq_star_emp_c\n                      heq_star_frame P Q\n(*    | [ |- SE.himp _ _ _ _ _ ?P ?Q ] =>\n   cancel himp_star_comm_p himp_star_assoc_p himp_star_comm_c himp_star_assoc_c P Q\n   *)\n    end; try reflexivity.\n\n  Section other.\n    Variable types : list type.\n    Variable funcs : functions types.\n    Variable preds : SE.predicates types.\n\n    Theorem sexprD_weaken_wt : forall U U' G' s G,\n      SE.WellTyped_sexpr (typeof_funcs funcs) (SE.typeof_preds preds) (typeof_env U) (typeof_env G) s = true -> \n      ST.heq (SE.sexprD funcs preds U G s) \n                (SE.sexprD funcs preds (U ++ U') (G ++ G') s).\n    Proof.\n      induction s; simpl; intros; think; try reflexivity.\n      { consider (exprD funcs U G e tvProp); intros.\n        erewrite exprD_weaken by eauto. reflexivity.\n        rewrite <- ST.heq_star_emp_r.\n        eapply is_well_typed_correct in H; eauto using typeof_env_WellTyped_env, typeof_funcs_WellTyped_funcs.\n        rewrite H0 in H. exfalso; destruct H; congruence. }\n      { eapply ST.heq_ex. intros. rewrite IHs; eauto. reflexivity. }\n      { unfold SE.typeof_preds in *. rewrite map_nth_error_full in H.\n        consider (nth_error preds f); intros; try reflexivity. inversion H1; subst.\n        clear H1 H. destruct p; simpl in *. generalize dependent SDomain.\n        induction l; destruct SDomain; intros; simpl in *; think; try (reflexivity || congruence).\n        eapply is_well_typed_correct in H; eauto using typeof_env_WellTyped_env, typeof_funcs_WellTyped_funcs.\n        destruct H. erewrite exprD_weaken; eauto. rewrite H. eauto. }\n    Qed.\n \n    Theorem sexprD_weaken : forall s U G G' U',\n      ST.himp (SE.sexprD funcs preds U G s) \n                    (SE.sexprD funcs preds (U ++ U') (G ++ G') s).\n    Proof.\n      induction s; simpl; intros; try reflexivity.\n      { consider (exprD funcs U G e tvProp); intros.\n        erewrite exprD_weaken by eauto. reflexivity.\n        rewrite <- ST.heq_star_emp_r.\n        eapply ST.himp_star_pure_c. contradiction. }\n      { rewrite IHs1. rewrite IHs2. reflexivity. }\n      { apply ST.himp_ex. intros. rewrite IHs with (U' := U') (G' := G'). reflexivity. }\n      { destruct (nth_error preds f); try reflexivity.\n        match goal with\n          | [ |- ST.himp match ?X with _ => _ end _ ] => \n            consider X\n        end; intros.\n        erewrite Expr.applyD_weaken by eauto. reflexivity.\n        rewrite <- ST.heq_star_emp_r.\n        eapply ST.himp_star_pure_c. unfold BadPredApply. contradiction. }\n    Qed.\n\n    Theorem liftSExpr_sexprD : forall s U U' U'' G G' G'', \n      ST.heq (SE.sexprD funcs preds (U ++ U') (G ++ G') s)\n                (SE.sexprD funcs preds (U ++ U'' ++ U') (G ++ G'' ++ G') \n                  (SE.liftSExpr (length U) (length U'') (length G) (length G'') s)).\n    Proof.\n      do 7 intro. revert G. induction s; simpl; intros; think; try reflexivity.\n      rewrite <- liftExpr_ext. reflexivity.\n      apply ST.heq_ex. intros. etransitivity. \n      change (existT (tvarD types) t v :: G ++ G') with ((existT (tvarD types) t v :: G) ++ G'). eapply IHs. reflexivity.\n      destruct (nth_error preds f); try reflexivity.\n      match goal with\n        | [ |- ST.heq match ?X with _ => _ end match ?Y with _ => _ end ] =>\n          cutrewrite (X = Y); try reflexivity\n      end.\n      destruct p; simpl. clear. revert l; induction SDomain; destruct l; simpl; auto.\n      rewrite <- liftExpr_ext. destruct (exprD funcs (U ++ U') (G ++ G') e a); eauto.\n    Qed.\n\n    Theorem liftSExpr_combine : forall (s : SE.sexpr types) ua ub uc a b c,\n      SE.liftSExpr ua ub a b (SE.liftSExpr ua uc a c s) = \n      SE.liftSExpr ua (uc + ub) a (c + b) s.\n    Proof.\n      clear. induction s; intros; simpl; think; try reflexivity.\n      rewrite liftExpr_combine. reflexivity.\n      f_equal. clear. induction l; simpl; intros; try rewrite liftExpr_combine; think; auto.\n    Qed.\n\n    Theorem liftSExpr_0 : forall (s : SE.sexpr types) ua a,\n      SE.liftSExpr ua 0 a 0 s = s.\n    Proof.\n      clear; induction s; intros; simpl; think; try reflexivity.\n      rewrite liftExpr_0; auto.\n      f_equal. clear. induction l; simpl; intros; try rewrite liftExpr_0; think; auto.\n    Qed.\n  End other.\n\n  Theorem himp_not_WellTyped_sexpr : forall ts funcs (preds : SE.predicates ts) s vars uvars,\n    SE.WellTyped_sexpr (typeof_funcs funcs) (SE.typeof_preds preds) (typeof_env uvars) (typeof_env vars) s = false ->\n    ST.himp (SE.sexprD funcs preds uvars vars s) (ST.inj False).\n  Proof.\n    induction s; simpl; intros; auto; try congruence.\n    { consider (exprD funcs uvars vars e tvProp); intros; try reflexivity.\n      eapply is_well_typed_correct_only in H0; eauto using typeof_env_WellTyped_env, typeof_funcs_WellTyped_funcs. congruence. }\n    { apply andb_false_iff in H. destruct H.\n      rewrite IHs1 by auto. eapply ST.himp_star_pure_c; contradiction.\n      rewrite ST.heq_star_comm.\n      rewrite IHs2 by auto. eapply ST.himp_star_pure_c; contradiction. }\n    { eapply ST.himp_ex_p. intros.\n      rewrite IHs. reflexivity. auto. }\n    { unfold SE.typeof_preds in H. \n      rewrite map_nth_error_full in H. destruct (nth_error preds f); try reflexivity.\n      destruct p; simpl in *. generalize dependent SDomain. induction l; destruct SDomain; simpl in *; intros; auto; try (congruence || reflexivity).\n      consider (is_well_typed (typeof_funcs funcs) (typeof_env uvars) (typeof_env vars) a t); intros.\n      eapply is_well_typed_correct in H. destruct H. rewrite H.\n      rewrite IHl. reflexivity. auto.\n      eauto using typeof_env_WellTyped_env.\n      eauto using typeof_env_WellTyped_env.\n      eauto using typeof_funcs_WellTyped_funcs.\n      consider (exprD funcs uvars vars a t); intros; try reflexivity.\n      eapply is_well_typed_correct_only in H1; eauto using typeof_env_WellTyped_env, typeof_funcs_WellTyped_funcs. congruence. }\n  Qed.\n    \n  Theorem himp_WellTyped_sexpr : forall ts funcs (preds : SE.predicates ts) s vars uvars Q,\n    (SE.WellTyped_sexpr (typeof_funcs funcs) (SE.typeof_preds preds) (typeof_env uvars) (typeof_env vars) s = true ->\n     ST.himp (SE.sexprD funcs preds uvars vars s) Q) ->\n    ST.himp (SE.sexprD funcs preds uvars vars s) Q.\n  Proof.\n    intros. consider (SE.WellTyped_sexpr (typeof_funcs funcs) (SE.typeof_preds preds)\n        (typeof_env uvars) (typeof_env vars) s); intros; auto.\n    rewrite himp_not_WellTyped_sexpr; auto.\n    rewrite <- ST.heq_star_emp_r.\n    eapply ST.himp_star_pure_c; contradiction. \n  Qed.\n\n  Module ST_EXT := SepTheory.SepTheory_Ext ST.\n\n  Lemma himp_existsEach_ST_EXT_existsEach : forall types funcs preds U (P : SE.sexpr types) vars G,\n    ST.heq (SE.sexprD funcs preds U G (SE.existsEach vars P)) \n           (ST_EXT.existsEach vars (fun env => SE.sexprD funcs preds U (rev env ++ G) P)).\n  Proof.\n    Opaque ST_EXT.existsEach.\n    induction vars; simpl; intros. rewrite ST_EXT.existsEach_nil. simpl. reflexivity.\n    change (a :: vars) with ((a :: nil) ++ vars). rewrite ST_EXT.existsEach_app.\n    rewrite ST_EXT.existsEach_cons. apply ST.heq_ex. intros. rewrite ST_EXT.existsEach_nil. rewrite IHvars.\n    simpl. eapply ST_EXT.heq_existsEach. intros. rewrite app_ass. reflexivity.\n  Qed.\n\n  Theorem WellTyped_sexpr_weaken : forall ts tf tp U U' r G G',\n    SE.WellTyped_sexpr (types := ts) tf tp U G r = true ->\n    SE.WellTyped_sexpr tf tp (U ++ U') (G ++ G') r = true.\n  Proof.\n    clear. induction r; simpl in *; intros; auto.\n    { eapply is_well_typed_weaken. auto. }\n    { repeat rewrite andb_true_iff in *. intuition. }\n    { change (t :: G ++ G') with ((t :: G) ++ G'). eapply IHr; auto. }\n    { destruct (nth_error tp f); auto. eapply all2_is_well_typed_weaken. auto. }\n  Qed.\n\nEnd SepExprFacts.\n\nModule Make (ST : SepTheory.SepTheory) <: SepExpr ST.\n  Section env.\n    Variable types : list type.\n    Variable pcType : tvar.\n    Variable stateType : tvar.\n\n    Record predicate := PSig\n    { SDomain : list tvar\n    ; SDenotation : functionTypeD (map (@tvarD types) SDomain) ST.hprop\n    }.\n\n    Definition predicates := list predicate.\n\n    Definition Default_predicate : predicate :=\n    {| SDomain := nil\n     ; SDenotation := ST.emp\n     |} .\n\n    Inductive sexpr : Type :=\n    | Emp : sexpr\n    | Inj : expr types -> sexpr\n    | Star : sexpr -> sexpr -> sexpr\n    | Exists : tvar -> sexpr -> sexpr\n    | Func : func -> list (expr types) -> sexpr\n    | Const : ST.hprop -> sexpr\n    .\n\n    Definition tpredicate : Type := list tvar.\n    Definition tpredicates : Type := list tpredicate.\n\n    Definition typeof_pred : predicate -> tpredicate := SDomain.\n    Definition typeof_preds : predicates -> tpredicates := map typeof_pred.\n\n    Section types.\n      Variable funcs : tfunctions.\n      Variable preds : tpredicates.\n      Variable tU : tenv.\n\n      Fixpoint WellTyped_sexpr (tG : tenv) (s : sexpr) : bool :=\n        match s with\n          | Emp => true\n          | Inj e => is_well_typed funcs tU tG e tvProp\n          | Star l r => WellTyped_sexpr tG l && WellTyped_sexpr tG r\n          | Exists t e => WellTyped_sexpr (t :: tG) e\n          | Func f args =>\n            match nth_error preds f with\n              | None => false\n              | Some ts => all2 (is_well_typed funcs tU tG) args ts\n            end\n          | Const _ => true\n        end.\n\n    End types.\n\n    Variable funcs : functions types.\n    Variable sfuncs : predicates.\n    Variable meta_env : env types.\n\n    Fixpoint sexprD (var_env : env types) (s : sexpr) : ST.hprop :=\n      match s with \n        | Emp => ST.emp\n        | Inj p =>\n          match exprD funcs meta_env var_env p tvProp with\n            | None => ST.inj (BadInj p)\n            | Some p => ST.inj p\n          end\n        | Star l r =>\n          ST.star (sexprD var_env l) (sexprD var_env r)\n        | Exists t b =>\n          ST.ex (fun x : tvarD types t => sexprD (@existT _ _ t x :: var_env) b)\n        | Func f b =>\n          match nth_error sfuncs f with\n            | None => ST.inj (BadPred f)\n            | Some f' =>\n              match applyD (@exprD types funcs meta_env var_env) (SDomain f') b _ (SDenotation f') with\n                | None => ST.inj (BadPredApply f b var_env)\n                | Some p => p\n              end\n          end\n        | Const p => p\n      end.\n\n    Definition himp (var_env : env types)\n      (gl gr : sexpr) : Prop :=\n      ST.himp (sexprD var_env gl) (sexprD var_env gr).\n\n    Definition heq (var_env : env types)\n      (gl gr : sexpr) : Prop :=\n      ST.heq (sexprD var_env gl) (sexprD var_env gr).\n\n    Fixpoint existsEach (ls : list tvar) {struct ls} : sexpr -> sexpr :=\n      match ls with\n        | nil => fun x => x\n        | t :: ts => fun y => Exists t (@existsEach ts y)\n      end.\n\n    Fixpoint liftSExpr ua ub a b s : sexpr :=\n      match s with\n        | Emp => Emp\n        | Const c => Const c\n        | Inj p => Inj (liftExpr ua ub a b p)\n        | Star l r => Star (liftSExpr ua ub a b l) (liftSExpr ua ub a b r)\n        | Exists t s => Exists t (liftSExpr ua ub (S a) b s)\n        | Func f args => Func f (map (liftExpr ua ub a b) args)\n      end.    \n\n  End env.\nEnd Make.\n\n", "meta": {"author": "gmalecha", "repo": "mirror-shard", "sha": "24f34dee2f78de731f4ef398733ff2c1f1551375", "save_path": "github-repos/coq/gmalecha-mirror-shard", "path": "github-repos/coq/gmalecha-mirror-shard/mirror-shard-24f34dee2f78de731f4ef398733ff2c1f1551375/src/SepExpr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2876719959826228}}
{"text": "From stdpp Require Export namespaces.\nFrom iris.proofmode Require Import tactics.\nFrom iris.algebra Require Import gmap.\nFrom iris.base_logic.lib Require Export fancy_updates.\nFrom iris.base_logic.lib Require Import wsat.\nFrom iris Require Import options.\nImport uPred.\n\n(** Semantic Invariants *)\nDefinition inv_def `{!invG Σ} (N : namespace) (P : iProp Σ) : iProp Σ :=\n  □ ∀ E, ⌜↑N ⊆ E⌝ → |={E,E ∖ ↑N}=> ▷ P ∗ (▷ P ={E ∖ ↑N,E}=∗ True).\nDefinition inv_aux : seal (@inv_def). Proof. by eexists. Qed.\nDefinition inv := inv_aux.(unseal).\nArguments inv {Σ _} N P.\nDefinition inv_eq : @inv = @inv_def := inv_aux.(seal_eq).\nInstance: Params (@inv) 3 := {}.\n\n(** * Invariants *)\nSection inv.\n  Context `{!invG Σ}.\n  Implicit Types i : positive.\n  Implicit Types N : namespace.\n  Implicit Types E : coPset.\n  Implicit Types P Q R : iProp Σ.\n\n  (** ** Internal model of invariants *)\n  Definition own_inv (N : namespace) (P : iProp Σ) : iProp Σ :=\n    ∃ i, ⌜i ∈ (↑N:coPset)⌝ ∧ ownI i P.\n\n  Lemma own_inv_acc E N P :\n    ↑N ⊆ E → own_inv N P ={E,E∖↑N}=∗ ▷ P ∗ (▷ P ={E∖↑N,E}=∗ True).\n  Proof.\n    rewrite uPred_fupd_eq /uPred_fupd_def. iDestruct 1 as (i) \"[Hi #HiP]\".\n    iDestruct \"Hi\" as % ?%elem_of_subseteq_singleton.\n    rewrite {1 4}(union_difference_L (↑ N) E) // ownE_op; last set_solver.\n    rewrite {1 5}(union_difference_L {[ i ]} (↑ N)) // ownE_op; last set_solver.\n    iIntros \"(Hw & [HE $] & $) !> !>\".\n    iDestruct (ownI_open i with \"[$Hw $HE $HiP]\") as \"($ & $ & HD)\".\n    iIntros \"HP [Hw $] !> !>\". iApply (ownI_close _ P). by iFrame.\n  Qed.\n\n  Lemma fresh_inv_name (E : gset positive) N : ∃ i, i ∉ E ∧ i ∈ (↑N:coPset).\n  Proof.\n    exists (coPpick (↑ N ∖ gset_to_coPset E)).\n    rewrite -elem_of_gset_to_coPset (comm and) -elem_of_difference.\n    apply coPpick_elem_of=> Hfin.\n    eapply nclose_infinite, (difference_finite_inv _ _), Hfin.\n    apply gset_to_coPset_finite.\n  Qed.\n\n  Lemma own_inv_alloc N E P : ▷ P ={E}=∗ own_inv N P.\n  Proof.\n    rewrite uPred_fupd_eq. iIntros \"HP [Hw $]\".\n    iMod (ownI_alloc (.∈ (↑N : coPset)) P with \"[$HP $Hw]\")\n      as (i ?) \"[$ ?]\"; auto using fresh_inv_name.\n    do 2 iModIntro. iExists i. auto.\n  Qed.\n\n  (* This does not imply [own_inv_alloc] due to the extra assumption [↑N ⊆ E]. *)\n  Lemma own_inv_alloc_open N E P :\n    ↑N ⊆ E → ⊢ |={E, E∖↑N}=> own_inv N P ∗ (▷P ={E∖↑N, E}=∗ True).\n  Proof.\n    rewrite uPred_fupd_eq. iIntros (Sub) \"[Hw HE]\".\n    iMod (ownI_alloc_open (.∈ (↑N : coPset)) P with \"Hw\")\n      as (i ?) \"(Hw & #Hi & HD)\"; auto using fresh_inv_name.\n    iAssert (ownE {[i]} ∗ ownE (↑ N ∖ {[i]}) ∗ ownE (E ∖ ↑ N))%I\n      with \"[HE]\" as \"(HEi & HEN\\i & HE\\N)\".\n    { rewrite -?ownE_op; [|set_solver..].\n      rewrite assoc_L -!union_difference_L //. set_solver. }\n    do 2 iModIntro. iFrame \"HE\\N\". iSplitL \"Hw HEi\"; first by iApply \"Hw\".\n    iSplitL \"Hi\".\n    { iExists i. auto. }\n    iIntros \"HP [Hw HE\\N]\".\n    iDestruct (ownI_close with \"[$Hw $Hi $HP $HD]\") as \"[$ HEi]\".\n    do 2 iModIntro. iSplitL; [|done].\n    iCombine \"HEi HEN\\i HE\\N\" as \"HEN\".\n    rewrite -?ownE_op; [|set_solver..].\n    rewrite assoc_L -!union_difference_L //; set_solver.\n  Qed.\n\n  Lemma own_inv_to_inv M P: own_inv M P -∗ inv M P.\n  Proof.\n    iIntros \"#I\". rewrite inv_eq. iIntros (E H).\n    iPoseProof (own_inv_acc with \"I\") as \"H\"; eauto.\n  Qed.\n\n  (** ** Public API of invariants *)\n  Global Instance inv_contractive N : Contractive (inv N).\n  Proof. rewrite inv_eq. solve_contractive. Qed.\n\n  Global Instance inv_ne N : NonExpansive (inv N).\n  Proof. apply contractive_ne, _. Qed.\n\n  Global Instance inv_proper N : Proper (equiv ==> equiv) (inv N).\n  Proof. apply ne_proper, _. Qed.\n\n  Global Instance inv_persistent N P : Persistent (inv N P).\n  Proof. rewrite inv_eq. apply _. Qed.\n\n  Lemma inv_alter N P Q : inv N P -∗ ▷ □ (P -∗ Q ∗ (Q -∗ P)) -∗ inv N Q.\n  Proof.\n    rewrite inv_eq. iIntros \"#HI #HPQ !>\" (E H).\n    iMod (\"HI\" $! E H) as \"[HP Hclose]\".\n    iDestruct (\"HPQ\" with \"HP\") as \"[$ HQP]\".\n    iIntros \"!> HQ\". iApply \"Hclose\". iApply \"HQP\". done.\n  Qed.\n\n  Lemma inv_iff N P Q : inv N P -∗ ▷ □ (P ↔ Q) -∗ inv N Q.\n  Proof.\n    iIntros \"#HI #HPQ\". iApply (inv_alter with \"HI\").\n    iIntros \"!> !> HP\". iSplitL \"HP\".\n    - by iApply \"HPQ\".\n    - iIntros \"HQ\". by iApply \"HPQ\".\n  Qed.\n\n  Lemma inv_alloc N E P : ▷ P ={E}=∗ inv N P.\n  Proof.\n    iIntros \"HP\". iApply own_inv_to_inv.\n    iApply (own_inv_alloc N E with \"HP\").\n  Qed.\n\n  Lemma inv_alloc_open N E P :\n    ↑N ⊆ E → ⊢ |={E, E∖↑N}=> inv N P ∗ (▷P ={E∖↑N, E}=∗ True).\n  Proof.\n    iIntros (?). iMod own_inv_alloc_open as \"[HI $]\"; first done.\n    iApply own_inv_to_inv. done.\n  Qed.\n\n  Lemma inv_acc E N P :\n    ↑N ⊆ E → inv N P ={E,E∖↑N}=∗ ▷ P ∗ (▷ P ={E∖↑N,E}=∗ True).\n  Proof.\n    rewrite inv_eq /inv_def; iIntros (?) \"#HI\". by iApply \"HI\".\n  Qed.\n\n  Lemma inv_combine N1 N2 N P Q :\n    N1 ## N2 →\n    ↑N1 ∪ ↑N2 ⊆@{coPset} ↑N →\n    inv N1 P -∗ inv N2 Q -∗ inv N (P ∗ Q).\n  Proof.\n    rewrite inv_eq. iIntros (??) \"#HinvP #HinvQ !>\"; iIntros (E ?).\n    iMod (\"HinvP\" with \"[%]\") as \"[$ HcloseP]\"; first set_solver.\n    iMod (\"HinvQ\" with \"[%]\") as \"[$ HcloseQ]\"; first set_solver.\n    iMod (fupd_intro_mask' _ (E ∖ ↑N)) as \"Hclose\"; first set_solver.\n    iIntros \"!> [HP HQ]\".\n    iMod \"Hclose\" as %_. iMod (\"HcloseQ\" with \"HQ\") as %_. by iApply \"HcloseP\".\n  Qed.\n\n  Lemma inv_combine_dup_l N P Q :\n    □ (P -∗ P ∗ P) -∗\n    inv N P -∗ inv N Q -∗ inv N (P ∗ Q).\n  Proof.\n    rewrite inv_eq. iIntros \"#HPdup #HinvP #HinvQ !>\" (E ?).\n    iMod (\"HinvP\" with \"[//]\") as \"[HP HcloseP]\".\n    iDestruct (\"HPdup\" with \"HP\") as \"[$ HP]\".\n    iMod (\"HcloseP\" with \"HP\") as %_.\n    iMod (\"HinvQ\" with \"[//]\") as \"[$ HcloseQ]\".\n    iIntros \"!> [HP HQ]\". by iApply \"HcloseQ\".\n  Qed.\n\n  (** ** Proof mode integration *)\n  Global Instance into_inv_inv N P : IntoInv (inv N P) N := {}.\n\n  Global Instance into_acc_inv N P E:\n    IntoAcc (X := unit) (inv N P)\n            (↑N ⊆ E) True (fupd E (E ∖ ↑N)) (fupd (E ∖ ↑N) E)\n            (λ _ : (), (▷ P)%I) (λ _ : (), (▷ P)%I) (λ _ : (), None).\n  Proof.\n    rewrite inv_eq /IntoAcc /accessor bi.exist_unit.\n    iIntros (?) \"#Hinv _\". iApply \"Hinv\"; done.\n  Qed.\n\n  (** ** Derived properties *)\n  Lemma inv_acc_strong E N P :\n    ↑N ⊆ E → inv N P ={E,E∖↑N}=∗ ▷ P ∗ ∀ E', ▷ P ={E',↑N ∪ E'}=∗ True.\n  Proof.\n    iIntros (?) \"Hinv\".\n    iPoseProof (inv_acc (↑ N) N with \"Hinv\") as \"H\"; first done.\n    rewrite difference_diag_L.\n    iPoseProof (fupd_mask_frame_r _ _ (E ∖ ↑ N) with \"H\") as \"H\"; first set_solver.\n    rewrite left_id_L -union_difference_L //. iMod \"H\" as \"[$ H]\"; iModIntro.\n    iIntros (E') \"HP\".\n    iPoseProof (fupd_mask_frame_r _ _ E' with \"(H HP)\") as \"H\"; first set_solver.\n    by rewrite left_id_L.\n  Qed.\n\n  Lemma inv_acc_timeless E N P `{!Timeless P} :\n    ↑N ⊆ E → inv N P ={E,E∖↑N}=∗ P ∗ (P ={E∖↑N,E}=∗ True).\n  Proof.\n    iIntros (?) \"Hinv\". iMod (inv_acc with \"Hinv\") as \"[>HP Hclose]\"; auto.\n    iIntros \"!> {$HP} HP\". iApply \"Hclose\"; auto.\n  Qed.\n\n  Lemma inv_split_l N P Q : inv N (P ∗ Q) -∗ inv N P.\n  Proof.\n    iIntros \"#HI\". iApply inv_alter; eauto.\n    iIntros \"!> !> [$ $] $\".\n  Qed.\n  Lemma inv_split_r N P Q : inv N (P ∗ Q) -∗ inv N Q.\n  Proof.\n    rewrite (comm _ P Q). eapply inv_split_l.\n  Qed.\n  Lemma inv_split N P Q : inv N (P ∗ Q) -∗ inv N P ∗ inv N Q.\n  Proof.\n    iIntros \"#H\".\n    iPoseProof (inv_split_l with \"H\") as \"$\".\n    iPoseProof (inv_split_r with \"H\") as \"$\".\n  Qed.\n\nEnd inv.\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/invariants.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2876719959826228}}
{"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_function.\nRequire Export list. (* WTF?? *)\n\n\nLemma equality_in_w {p} :\n  forall lib (s1 s2 : @CTerm p) A v B,\n    equality lib s1 s2 (mkc_w A v B)\n    <=>\n    {eqa : per\n     , {eqb : (forall a a' : CTerm, forall e : eqa a a', per)\n        , nuprl lib A A eqa\n        # (forall a a' : CTerm,\n           forall e : eqa a a',\n             nuprl lib (substc a v B) (substc a' v B) (eqb a a' e))\n        # weq lib eqa eqb s1 s2}}.\nProof.\n  introv; sp_iff Case; introv e.\n\n  - unfold equality in e; exrepnd.\n    unfold nuprl in e1.\n    inversion e1; try not_univ.\n    allunfold @per_w; allunfold @type_family; exrepnd.\n    computes_to_value_isvalue.\n    allfold (@nuprl p lib).\n    exists eqa eqb; sp.\n    allunfold @eq_term_equals; discover; sp.\n\n  - exrepnd.\n    exists (weq lib eqa eqb); sp.\n    apply CL_w.\n    exists eqa eqb; sp.\n    exists A A v v B B; sp; spcast; computes_to_value_refl.\nQed.\n\n(**\n\n  Using the Coq induction principle we obtain for [weq], we can prove\n  the following induction principle for our W types.  The then use\n  this principle to prove the [rule_w_induction] rule below.\n\n*)\n\nLemma w_ind_eq {p} :\n  forall lib (A : @CTerm p) va B (Q : CTerm -> CTerm -> [U]),\n    (forall t1 t2 t3 t4, cequivc lib t1 t3 -> cequivc lib t2 t4 -> Q t1 t2 -> Q t3 t4)\n    -> (forall a1 a2 f1 f2,\n          equality lib a1 a2 A\n          -> equality lib f1 f2 (mkc_fun (substc a1 va B) (mkc_w A va B))\n          -> (forall b1 b2,\n                equality lib b1 b2 (substc a1 va B)\n                -> Q (mkc_apply f1 b1) (mkc_apply f2 b2))\n          -> Q (mkc_sup a1 f1) (mkc_sup a2 f2))\n    -> (forall w1 w2, equality lib w1 w2 (mkc_w A va B) -> Q w1 w2).\nProof.\n  introv ceq ind e.\n  rw @equality_in_w in e; exrepnd.\n  induction e1; spcast.\n  apply ceq with (t1 := mkc_sup a f) (t2 := mkc_sup a' f');\n    try (complete (apply cequivc_sym; apply computes_to_valc_implies_cequivc; sp)).\n\n  assert (eqa a' a')\n         as e'\n         by (eapply equality_eq_refl; eauto;\n             eapply equality_eq_sym; eauto).\n\n  apply ind; try (complete (exists eqa; sp)).\n\n  rw <- @fold_mkc_fun.\n  rw @equality_in_function.\n  dands.\n\n  (* 1 *)\n  exists (eqb a a' e); sp.\n  generalize (e2 a a' e); intro n.\n  apply nuprl_refl in n; sp.\n\n  (* 2 *)\n  introv eq.\n  allrw @substc_cnewvar.\n  exists (weq lib eqa eqb); sp.\n  apply CL_w; unfold per_w; unfold type_family.\n  exists eqa eqb; sp.\n  exists A A va va B B; sp; spcast; apply computes_to_valc_refl; apply iscvalue_mkc_w.\n\n  (* 3 *)\n  introv eq.\n  allrw @substc_cnewvar.\n  rw @equality_in_w.\n  exists eqa eqb; sp.\n  apply_hyp.\n  unfold equality in eq; exrepnd.\n  generalize (e2 a a' e); intro n.\n  assert (eq_term_equals eq0 (eqb a a' e)) as eqt;\n    try (complete (eapply nuprl_uniquely_valued; eauto;\n                   allapply @nuprl_refl; sp)).\n\n  (* 4 *)\n  introv eq.\n  apply_hyp; sp.\n  unfold equality in eq; exrepnd.\n  generalize (e2 a a' e); intro n.\n  assert (eq_term_equals eq0 (eqb a a' e)) as eqt;\n    try (complete (eapply nuprl_uniquely_valued; eauto;\n                   allapply @nuprl_refl; sp)).\nQed.\n\n(* begin hide *)\n\nLemma w_ind_eq2 {p} :\n  forall lib (A : @CTerm p) va B (Q : CTerm -> [U]),\n    (forall t1 t2, cequivc lib t1 t2 -> Q t1 -> Q t2)\n    -> (forall a1 a2 f1 f2,\n          equality lib a1 a2 A\n          -> equality lib f1 f2 (mkc_fun (substc a1 va B) (mkc_w A va B))\n          -> (forall b1 b2,\n                equality lib b1 b2 (substc a1 va B)\n                -> Q (mkc_apply f1 b1))\n          -> Q (mkc_sup a1 f1))\n    -> (forall w1 w2, equality lib w1 w2 (mkc_w A va B) -> Q w1).\nProof.\n  introv ceq ind e.\n  generalize (w_ind_eq lib A va B (fun t1 t2 => Q t1)).\n  intro h.\n  dest_imp h hyp.\n  introv c1 c2 q1.\n  apply ceq with (t1 := t1); sp.\n  apply h with (w2 := w2); sp.\nQed.\n\nLemma w_ind {p} :\n  forall lib (A : @CTerm p) va B (Q : CTerm -> Prop),\n    (forall t t', cequivc lib t t' -> Q t -> Q t')\n    -> (forall a f,\n          member lib a A\n          -> member lib f (mkc_fun (substc a va B) (mkc_w A va B))\n          -> Q (mkc_sup a f))\n    -> (forall w, member lib w (mkc_w A va B) -> Q w).\nProof.\n  introv ceq ind m.\n  generalize (w_ind_eq lib A va B (fun t1 t2 => Q t1)); intro i.\n  apply i with (w2 := w); sp.\n  apply ceq with (t := t1); sp.\n  apply ind; allapply @equality_refl; sp.\nQed.\n\nLemma equality_in_pw {o} :\n  forall lib (s1 s2 : @CTerm o) P ap A bp ba B cp ca cb C p,\n    equality lib s1 s2 (mkc_pw P ap A bp ba B cp ca cb C p)\n    <=>\n    {eqp : per\n     , {eqa : (forall p p' : CTerm, forall ep : eqp p p', per)\n     , {eqb : (forall p p' : CTerm,\n               forall ep : eqp p p',\n               forall a a' : CTerm,\n               forall ea : eqa p p' ep a a',\n                 per)\n        , nuprl lib P P eqp\n        # (forall p p' : CTerm,\n           forall ep : eqp p p',\n             nuprl lib (substc p ap A) (substc p' ap A) (eqa p p' ep))\n        # (forall p p' : CTerm,\n           forall ep : eqp p p',\n           forall a a' : CTerm,\n           forall ea : eqa p p' ep a a',\n             nuprl lib (lsubstc2 bp p ba a B)\n                   (lsubstc2 bp p' ba a' B)\n                   (eqb p p' ep a a' ea))\n        # (forall p p',\n           forall ep : eqp p p',\n           forall a a',\n           forall ea : eqa p p' ep a a',\n           forall b b',\n           forall eb : eqb p p' ep a a' ea b b',\n             eqp (lsubstc3 cp p ca a cb b C)\n                 (lsubstc3 cp p' ca a' cb b' C))\n        # eqp p p\n        # pweq lib eqp eqa eqb cp ca cb C p s1 s2}}}.\nProof.\n  introv; sp_iff Case; introv e.\n\n  - unfold equality in e; exrepnd.\n    unfold nuprl in e1.\n    inversion e1; try not_univ.\n    allunfold @per_pw; allunfold @type_pfamily; exrepnd.\n    computes_to_value_isvalue.\n    allfold (@nuprl o).\n    exists eqp eqa eqb; sp.\n    allunfold @eq_term_equals; discover; sp.\n\n  - exrepnd.\n    exists (pweq lib eqp eqa eqb cp ca cb C p); sp.\n    apply CL_pw.\n    exists eqp eqa eqb p p; sp.\n    exists cp cp ca ca cb cb C C; sp.\n    exists P P ap ap A A bp bp.\n    exists ba ba B B; sp; spcast; computes_to_value_refl.\nQed.\n\nLemma isprog_vars_lsubstc3v3 {p} :\n  forall v1 u1 v2 u2 v3 u3 (t : @CVTerm p [v1,v2,v3]),\n    isprog_vars\n      [u3]\n      (lsubst (get_cvterm [v1;v2;v3] t)\n              [(v1,get_cterm u1),(v2,get_cterm u2),(v3,mk_var u3)]).\nProof.\n  introv.\n  destruct_cterms.\n  rw @isprog_vars_eq; simpl; dands.\n\n  generalize (eqvars_free_vars_disjoint x1 [(v1, x0), (v2, x), (v3, mk_var u3)]);\n    introv eqv.\n  rw eqvars_prop in eqv.\n  rw subvars_prop; introv k.\n  rw in_single_iff.\n  apply eqv in k; clear eqv.\n  apply isprog_vars_eq in i1; repnd.\n  rw in_app_iff in k; rw in_remove_nvars in k; repdors; repnd.\n\n  simpl in k0; repeat (rw not_over_or in k0); repnd.\n  rw subvars_prop in i2.\n  apply i2 in k1; simpl in k1; sp.\n\n  revert k; simpl; boolvar; simpl;\n  allrw in_app_iff; allrw in_single_iff; allrw in_remove_nvar; repnd;\n  allrw @isprog_eq; allunfold @isprogram; repnd; allrw; simpl;\n  intro k; repdors; try (complete sp).\n\n  apply isprog_vars_eq in i1; repnd.\n  apply lsubst_wf_iff; sp.\n  unfold wf_sub, sub_range_sat; simpl; introv k; repdors; cpx;\n  allrw @isprog_eq; allunfold @isprogram; sp.\nQed.\n\nDefinition lsubstc3v3 {p} (v1 : NVar) (u1 : @CTerm p)\n                      (v2 : NVar) (u2 : CTerm)\n                      (v3 : NVar) (u3 : NVar)\n                      (t : CVTerm [v1;v2;v3]) : CVTerm [u3] :=\n  exist (isprog_vars [u3])\n        (lsubst (get_cvterm [v1;v2;v3] t)\n                [(v1,get_cterm u1),(v2,get_cterm u2),(v3,mk_var u3)])\n        (isprog_vars_lsubstc3v3 v1 u1 v2 u2 v3 u3 t).\n\nLemma lsubst_mk_pw {o} :\n  forall (P : @NTerm o) ap A bp ba B cp ca cb C p sub,\n    prog_sub sub\n    -> isprog P\n    -> isprog_vars [ap] A\n    -> isprog_vars [bp;ba] B\n    -> isprog_vars [cp;ca;cb] C\n    -> isprog_vars (dom_sub sub) p\n    -> lsubst (mk_pw P ap A bp ba B cp ca cb C p) sub\n       = mk_pw P ap A bp ba B cp ca cb C (lsubst p sub).\nProof.\n  introv ps iP iA iB iC ip.\n  change_to_lsubst_aux4.\n  simpl.\n  allrw @fold_nobnd.\n  rw @fold_pw; simpl.\n  allrw @sub_filter_nil_r.\n\n  assert (lsubst_aux P sub = P) as eqP.\n  apply lsubst_aux_trivial; introv i; discover; dands; try (complete sp).\n  intro j.\n  allrw @isprog_eq; allunfold @isprogram; repnd.\n  rw iP0 in j; sp.\n  rw eqP.\n\n  assert (lsubst_aux A (sub_filter sub [ap]) = A) as eqA.\n  apply lsubst_aux_trivial; introv i.\n  apply in_sub_filter in i; repnd; discover; dands; try (complete sp).\n  intro j.\n  rw @isprog_vars_eq in iA; repnd.\n  rw subvars_prop in iA0; apply iA0 in j; sp.\n  rw eqA.\n\n  assert (lsubst_aux B (sub_filter sub [bp,ba]) = B) as eqB.\n  apply lsubst_aux_trivial; introv i.\n  apply in_sub_filter in i; repnd; discover; dands; try (complete sp).\n  intro j.\n  rw @isprog_vars_eq in iB; repnd.\n  rw subvars_prop in iB0; apply iB0 in j; sp.\n  rw eqB.\n\n  assert (lsubst_aux C (sub_filter sub [cp,ca,cb]) = C) as eqC.\n  apply lsubst_aux_trivial; introv i.\n  apply in_sub_filter in i; repnd; discover; dands; try (complete sp).\n  intro j.\n  rw @isprog_vars_eq in iC; repnd.\n  rw subvars_prop in iC0; apply iC0 in j; sp.\n  rw eqC.\n\n  sp.\nQed.\n\nLtac cpx2 :=\n  match goal with\n    | [ H1 : closed ?x, H2 : LIn ?v (free_vars ?x) |- _ ] =>\n        rewrite H1 in H2; simpl in H2; complete (destruct H2)\n  end.\n\nLemma substc_mkc_pw_vs {o} :\n  forall (p : @CTerm o) a b v P ap A bp ba B cp ca cb C,\n    !LIn v (bound_vars (get_cvterm [cp;ca;cb] C))\n    -> substc b v\n              (mkc_pw_vs [v] P ap A bp ba B cp ca cb C\n                         (lsubstc3v3 cp p ca a cb v C))\n       = mkc_pw P ap A bp ba B cp ca cb C (lsubstc3 cp p ca a cb b C).\nProof.\n  introv niv.\n  destruct_cterms; simpl.\n  apply cterm_eq; simpl.\n  unfold csubst, subst; simpl.\n  rw @lsubst_mk_pw;\n    try (complete sp);\n    try (complete (unfold prog_sub, sub_range_sat; simpl; sp; cpx; rw @isprogram_eq; sp)).\n\n  rw @simple_lsubst_lsubst; simpl.\n\n  assert (lsubst x2 [(v, x0)] = x2) as eq.\n  rw @lsubst_trivial; allsimpl; try (complete sp); introv k; repdors; cpx.\n  allrw @isprog_eq; dands; try (complete sp); allunfold @isprogram; repnd; allrw; sp.\n  rw eq; clear eq.\n\n  assert (lsubst x1 [(v, x0)] = x1) as eq.\n  rw @lsubst_trivial; allsimpl; try (complete sp); introv k; repdors; cpx.\n  allrw @isprog_eq; dands; try (complete sp); allunfold @isprogram; repnd; allrw; sp.\n  rw eq; clear eq.\n\n  assert (lsubst (mk_var v) [(v, x0)] = x0) as eq.\n  change_to_lsubst_aux4; simpl; boolvar; sp.\n  rw eq; clear eq.\n\n  assert (lsubst x3 [(cp, x2), (ca, x1), (cb, x0), (v, x0)]\n          = lsubst x3 [(cp, x2), (ca, x1), (cb, x0)]) as eq.\n  clear niv.\n  generalize (in_deq NVar deq_nvar v [cp,ca,cb]); intro k; destruct k as [k | k]; simpl in k.\n  (* v in list *)\n  assert ([(cp, x2), (ca, x1), (cb, x0), (v, x0)] = snoc [(cp, x2), (ca, x1), (cb, x0)] (v, x0)) as e by sp.\n  rw e; clear e.\n  rw @lsubst_snoc_dup; try (complete sp).\n  introv j; simpl in j; repdors; cpx; allrw @isprog_eq; sp.\n  allrw @isprog_eq; sp.\n  (* v not in list *)\n  allrw not_over_or; repnd.\n  allrw @isprog_vars_eq; repnd.\n  allrw subvars_prop; allsimpl.\n  rw @simple_lsubst_trim.\n  symmetry.\n  rw @simple_lsubst_trim.\n  simpl; boolvar; try (complete sp); discover; repdors; try subst; try (complete sp).\n  introv j; simpl in j; repdors; cpx; allrw @isprog_eq; allunfold @isprogram; repnd; allrw; simpl; try (complete sp).\n  introv j; simpl in j; repdors; cpx; allrw @isprog_eq; allunfold @isprogram; repnd; allrw; simpl; try (complete sp).\n  rw eq; sp.\n\n  introv k; repdors; cpx; try (complete sp);\n  allrw @isprog_eq; allunfold @isprogram; repnd; allrw; sp; simpl.\n  rw disjoint_singleton_l.\n  exact niv.\n\n  introv k; repdors; cpx; try (complete sp); allrw @isprog_eq; sp.\n\n  clear niv; simpl; rw @isprog_vars_eq; simpl; sp.\n\n  rw @isprog_vars_eq in i3; repnd.\n  rw subvars_prop in i6.\n  generalize (eqvars_free_vars_disjoint x3 [(cp, x2), (ca, x1), (cb, mk_var v)]); intro eqv.\n  rw subvars_prop; introv j; rw eqvars_prop in eqv; apply eqv in j.\n  rw in_single_iff.\n  rw in_app_iff in j; rw in_remove_nvars in j; repdors; repnd.\n  simpl in j0; repeat (rw not_over_or in j0); repnd; discover; allsimpl; sp.\n  apply in_sub_free_vars in j; exrepnd.\n  revert j0; simpl; boolvar; simpl; introv k; repdors; cpx;\n  allrw @isprog_eq; allunfold @isprogram; repnd; try cpx2.\n\n  allrw @isprog_eq; allrw @isprog_vars_eq; allunfold @isprogram; repnd.\n  apply lsubst_wf_iff; sp.\n  unfold wf_sub, sub_range_sat; simpl; introv k; repdors; cpx.\nQed.\n\nLemma param_w_ind {o} :\n  forall lib (P : @CTerm o) ap A bp ba B cp ca cb C (Q : CTerm -> CTerm -> CTerm -> [U]),\n    (forall p t1 t2 t3 t4, cequivc lib t1 t3 -> cequivc lib t2 t4 -> Q p t1 t2 -> Q p t3 t4)\n    -> (forall p a1 a2 f1 f2 vb,\n       equality lib a1 a2 (substc p ap A)\n       -> equality lib f1 f2 (mkc_function\n                            (lsubstc2 bp p ba a1 B)\n                            vb\n                            (mkc_pw_vs [vb]\n                                       P ap A bp ba B cp ca cb C\n                                       (lsubstc3v3 cp p ca a1 cb vb C)))\n       -> (forall b1 b2,\n             equality lib b1 b2 (lsubstc2 bp p ba a1 B)\n             -> Q (lsubstc3 cp p ca a1 cb b1 C)\n                  (mkc_apply f1 b1)\n                  (mkc_apply f2 b2))\n       -> Q p\n            (mkc_sup a1 f1)\n            (mkc_sup a2 f2))\n    -> (forall p w1 w2,\n          equality lib w1 w2 (mkc_pw P ap A bp ba B cp ca cb C p)\n          -> Q p w1 w2).\nProof.\n  introv ceq ind e.\n  apply equality_in_pw in e; exrepnd.\n  induction e0; spcast.\n  apply ceq with (t1 := mkc_sup a1 f1) (t2 := mkc_sup a2 f2);\n    try (complete (apply cequivc_sym; apply computes_to_valc_implies_cequivc; sp)).\n\n  assert (eqa p p ep a2 a2)\n         as ea2\n         by (generalize (e2 p p ep); intro na;\n             apply (equality_eq_refl lib) with (A := substc p ap A) (B := substc p ap A) (b := a1); sp;\n             apply (equality_eq_sym lib) with (A := substc p ap A) (B := substc p ap A); sp).\n\n  assert ({v : NVar, !LIn v (bound_vars (get_cvterm [cp, ca, cb] C))})\n         as ev\n         by (exists (fresh_var (bound_vars (get_cvterm [cp, ca, cb] C)));\n             apply fresh_var_not_in); exrepnd.\n\n  apply ind with (vb := v); try (complete (exists (eqa p p ep); sp)).\n\n  rw @equality_in_function.\n  dands.\n\n  (* 1 *)\n  exists (eqb p p ep a1 a2 ea); sp.\n  generalize (e3 p p ep a1 a2 ea); intro n.\n  apply nuprl_refl in n; sp.\n\n  (* 2 *)\n  intros b b' eq.\n  rw @substc_mkc_pw_vs; simpl; try (complete sp).\n  rw @substc_mkc_pw_vs; simpl; try (complete sp).\n  exists (pweq lib eqp eqa eqb cp ca cb C (lsubstc3 cp p ca a1 cb b C)); sp.\n  apply CL_pw; unfold per_pw; unfold type_pfamily.\n  exists eqp eqa eqb (lsubstc3 cp p ca a1 cb b C) (lsubstc3 cp p ca a1 cb b' C).\n  exists cp cp ca ca cb cb C C; sp.\n  exists P P ap ap A A.\n  exists bp bp ba ba B B; sp; spcast; try (apply computes_to_valc_refl; apply iscvalue_mkc_pw).\n  assert (eqa p p ep a1 a1)\n         as ea1\n         by (eapply equality_eq_refl; eauto).\n  apply e4 with (ep := ep) (ea := ea1).\n  unfold equality in eq; exrepnd.\n  generalize (e3 p p ep a1 a1 ea1); intro n.\n  assert (eq_term_equals eq0 (eqb p p ep a1 a1 ea1))\n         as eqt\n         by (apply (nuprl_uniquely_valued lib) with (t := lsubstc2 bp p ba a1 B); sp;\n             allapply nuprl_refl; sp).\n  rw <- eqt; sp.\n\n  (* 3 *)\n  intros b b' eq.\n  rw @substc_mkc_pw_vs; simpl; try (complete sp).\n  apply equality_in_pw.\n  exists eqp eqa eqb; dands; try (complete sp).\n\n  assert (eqa p p ep a1 a1)\n         as ea1\n         by (eapply equality_eq_refl; eauto).\n  apply e4 with (ep := ep) (ea := ea1).\n  unfold equality in eq; exrepnd.\n  generalize (e3 p p ep a1 a1 ea1); intro n.\n  assert (eq_term_equals eq0 (eqb p p ep a1 a1 ea1))\n         as eqt\n         by (apply (nuprl_uniquely_valued lib) with (t := lsubstc2 bp p ba a1 B); sp;\n             allapply nuprl_refl; sp).\n  rw <- eqt; sp.\n  eapply equality_eq_refl; eauto.\n\n  apply_hyp.\n  unfold equality in eq; exrepnd.\n  generalize (e3 p p ep a1 a2 ea); intro n.\n  assert (eq_term_equals eq0 (eqb p p ep a1 a2 ea))\n         as eqt\n         by (eapply nuprl_uniquely_valued; eauto;\n             allapply @nuprl_refl; sp).\n  rw <- eqt; sp.\n\n  (* 4 *)\n  intros b b' eq.\n  apply_hyp.\n  unfold equality in eq; exrepnd.\n  generalize (e3 p p ep a1 a2 ea); intro n.\n  assert (eq_term_equals eq0 (eqb p p ep a1 a2 ea))\n         as eqt\n         by (eapply nuprl_uniquely_valued; eauto;\n             allapply @nuprl_refl; sp).\n  rw <- eqt; sp.\n\n  assert (eqa p p ep a1 a1)\n         as ea1\n         by (eapply equality_eq_refl; eauto).\n  apply e4 with (ep := ep) (ea := ea1).\n  unfold equality in eq; exrepnd.\n  generalize (e3 p p ep a1 a1 ea1); intro n.\n  assert (eq_term_equals eq0 (eqb p p ep a1 a1 ea1))\n         as eqt\n         by (eapply nuprl_uniquely_valued; eauto;\n             allapply nuprl_refl; sp).\n  rw <- eqt; sp.\n  eapply equality_eq_refl; eauto.\nQed.\n\n(* Not as useful as 3 because we don't have any constraint on vb *)\nLemma param_w_ind2 {o} :\n  forall lib (P : @CTerm o) ap A bp ba B cp ca cb C (Q : CTerm -> CTerm -> CTerm -> CTerm -> [U]),\n    (forall p1 p2 t1 t2 t3 t4,\n       cequivc lib t1 t3 -> cequivc lib t2 t4 -> Q p1 p2 t1 t2 -> Q p1 p2 t3 t4)\n    -> (forall p1 p2 a1 a2 f1 f2 vb,\n       equality lib p1 p2 P\n       -> equality lib a1 a2 (substc p1 ap A)\n       -> equality lib f1 f2 (mkc_function\n                            (lsubstc2 bp p1 ba a1 B)\n                            vb\n                            (mkc_pw_vs [vb]\n                                       P ap A bp ba B cp ca cb C\n                                       (lsubstc3v3 cp p1 ca a1 cb vb C)))\n       -> (forall b1 b2,\n             equality lib b1 b2 (lsubstc2 bp p1 ba a1 B)\n             -> Q (lsubstc3 cp p1 ca a1 cb b1 C)\n                  (lsubstc3 cp p2 ca a2 cb b2 C)\n                  (mkc_apply f1 b1)\n                  (mkc_apply f2 b2))\n       -> Q p1\n            p2\n            (mkc_sup a1 f1)\n            (mkc_sup a2 f2))\n    -> (forall p1 p2 w1 w2,\n          equality lib p1 p2 P\n          -> equality lib w1 w2 (mkc_pw P ap A bp ba B cp ca cb C p1)\n          -> Q p1 p2 w1 w2).\nProof.\n  introv ceq ind eqip e.\n  apply equality_in_pw in e; exrepnd.\n  revert_dependents p2.\n  induction e0; spcast.\n  introv eqip.\n  apply ceq with (t1 := mkc_sup a1 f1) (t2 := mkc_sup a2 f2);\n    try (complete (apply cequivc_sym; apply computes_to_valc_implies_cequivc; sp)).\n\n  assert (eqa p p ep a2 a2)\n         as ea2\n         by (generalize (e2 p p ep); intro na;\n             apply (equality_eq_refl lib) with (A := substc p ap A) (B := substc p ap A) (b := a1); sp;\n             eapply equality_eq_sym; eauto).\n\n  assert ({v : NVar, !LIn v (bound_vars (get_cvterm [cp, ca, cb] C))})\n         as ev\n         by (exists (fresh_var (bound_vars (get_cvterm [cp, ca, cb] C)));\n             apply fresh_var_not_in); exrepnd.\n\n  apply ind with (vb := v); try (complete sp); try (complete (exists (eqa p p ep); sp)).\n\n  rw @equality_in_function.\n  dands.\n\n  (* 1 *)\n  exists (eqb p p ep a1 a2 ea); sp.\n  generalize (e3 p p ep a1 a2 ea); intro n.\n  apply nuprl_refl in n; sp.\n\n  (* 2 *)\n  intros b b' eq.\n  rw @substc_mkc_pw_vs; simpl; try (complete sp).\n  rw @substc_mkc_pw_vs; simpl; try (complete sp).\n  exists (pweq lib eqp eqa eqb cp ca cb C (lsubstc3 cp p ca a1 cb b C)); sp.\n  apply CL_pw; unfold per_pw; unfold type_pfamily.\n  exists eqp eqa eqb (lsubstc3 cp p ca a1 cb b C) (lsubstc3 cp p ca a1 cb b' C).\n  exists cp cp ca ca cb cb C C; sp.\n  exists P P ap ap A A.\n  exists bp bp ba ba B B; sp; spcast; try (apply computes_to_valc_refl; apply iscvalue_mkc_pw).\n  assert (eqa p p ep a1 a1)\n         as ea1\n         by (eapply equality_eq_refl; eauto).\n  apply e4 with (ep := ep) (ea := ea1).\n  unfold equality in eq; exrepnd.\n  generalize (e3 p p ep a1 a1 ea1); intro n.\n  assert (eq_term_equals eq0 (eqb p p ep a1 a1 ea1))\n         as eqt\n         by (eapply nuprl_uniquely_valued; eauto;\n             allapply nuprl_refl; sp).\n  rw <- eqt; sp.\n\n  (* 3 *)\n  intros b b' eq.\n  rw @substc_mkc_pw_vs; simpl; try (complete sp).\n  apply equality_in_pw.\n  exists eqp eqa eqb; dands; try (complete sp).\n\n  assert (eqa p p ep a1 a1)\n         as ea1\n         by (eapply equality_eq_refl; eauto).\n  apply e4 with (ep := ep) (ea := ea1).\n  unfold equality in eq; exrepnd.\n  generalize (e3 p p ep a1 a1 ea1); intro n.\n  assert (eq_term_equals eq0 (eqb p p ep a1 a1 ea1))\n         as eqt\n         by (eapply nuprl_uniquely_valued; eauto;\n             allapply nuprl_refl; sp).\n  rw <- eqt; sp.\n  eapply equality_eq_refl; eauto.\n\n  apply_hyp.\n  unfold equality in eq; exrepnd.\n  generalize (e3 p p ep a1 a2 ea); intro n.\n  assert (eq_term_equals eq0 (eqb p p ep a1 a2 ea))\n         as eqt\n         by (eapply nuprl_uniquely_valued; eauto;\n             allapply @nuprl_refl; sp).\n  rw <- eqt; sp.\n\n  (* 4 *)\n  intros b b' eq.\n  apply_hyp.\n  unfold equality in eq; exrepnd.\n  generalize (e3 p p ep a1 a2 ea); intro n.\n  assert (eq_term_equals eq0 (eqb p p ep a1 a2 ea))\n         as eqt\n         by (eapply nuprl_uniquely_valued; eauto;\n             allapply @nuprl_refl; sp).\n  rw <- eqt; sp.\n\n  assert (eqa p p ep a1 a1)\n         as ea1\n         by (eapply equality_eq_refl; eauto).\n  apply e4 with (ep := ep) (ea := ea1).\n  unfold equality in eq; exrepnd.\n  generalize (e3 p p ep a1 a1 ea1); intro n.\n  assert (eq_term_equals eq0 (eqb p p ep a1 a1 ea1))\n         as eqt\n         by (eapply nuprl_uniquely_valued; eauto;\n             allapply nuprl_refl; sp).\n  rw <- eqt; sp.\n  eapply equality_eq_refl; eauto.\n\n  generalize (equality_eq lib P p p2 eqp); intro ip.\n  dest_imp ip hyp.\n  apply ip in eqip; clear ip.\n\n  assert (eqa p p2 eqip a1 a2) as eqia.\n  generalize (e2 p p2 eqip); intro n1.\n  generalize (e2 p p ep); intro n2.\n  apply nuprl_uniquely_valued with (eq1 := eqa p p2 eqip) in n2.\n  dup ea as eqia.\n  rw <- n2 in eqia; sp.\n  allapply @nuprl_refl; sp.\n\n  assert (eqb p p2 eqip a1 a2 eqia b b') as eqib.\n  generalize (e3 p p2 eqip a1 a2 eqia); intro n.\n  apply nuprl_refl in n.\n  apply @equality_eq with (a := b) (b := b') in n.\n  rw <- n in eq; sp.\n\n  generalize (e4 p p2 eqip a1 a2 eqia b b' eqib); intro e.\n  exists eqp; sp.\nQed.\n\n(* This version is the most useful one so far *)\nLemma param_w_ind3 {o} :\n  forall lib (P : @CTerm o) ap A bp ba B cp ca cb C (Q : CTerm -> CTerm -> CTerm -> CTerm -> [U]),\n    (forall p1 p2 t1 t2 t3 t4,\n       cequivc lib t1 t3 -> cequivc lib t2 t4 -> Q p1 p2 t1 t2 -> Q p1 p2 t3 t4)\n    -> (forall p1 p2 a1 a2 f1 f2 vb,\n          !LIn vb (bound_vars (get_cvterm [cp, ca, cb] C))\n          -> equality lib p1 p2 P\n          -> equality lib a1 a2 (substc p1 ap A)\n          -> equality lib f1 f2 (mkc_function\n                               (lsubstc2 bp p1 ba a1 B)\n                               vb\n                               (mkc_pw_vs [vb]\n                                          P ap A bp ba B cp ca cb C\n                                          (lsubstc3v3 cp p1 ca a1 cb vb C)))\n          -> (forall b1 b2,\n                equality lib b1 b2 (lsubstc2 bp p1 ba a1 B)\n                -> Q (lsubstc3 cp p1 ca a1 cb b1 C)\n                     (lsubstc3 cp p2 ca a2 cb b2 C)\n                     (mkc_apply f1 b1)\n                     (mkc_apply f2 b2))\n          -> Q p1\n               p2\n               (mkc_sup a1 f1)\n               (mkc_sup a2 f2))\n    -> (forall p1 p2 w1 w2,\n          equality lib p1 p2 P\n          -> equality lib w1 w2 (mkc_pw P ap A bp ba B cp ca cb C p1)\n          -> Q p1 p2 w1 w2).\nProof.\n  introv ceq ind eqip e.\n  apply equality_in_pw in e; exrepnd.\n  revert_dependents p2.\n  induction e0; spcast.\n  introv eqip.\n  apply ceq with (t1 := mkc_sup a1 f1) (t2 := mkc_sup a2 f2);\n    try (complete (apply cequivc_sym; apply computes_to_valc_implies_cequivc; sp)).\n\n  assert (eqa p p ep a2 a2)\n         as ea2\n         by (generalize (e2 p p ep); intro na;\n             apply (equality_eq_refl lib) with (A := substc p ap A) (B := substc p ap A) (b := a1); sp;\n             apply (equality_eq_sym lib) with (A := substc p ap A) (B := substc p ap A); sp).\n\n  assert ({v : NVar, !LIn v (bound_vars (get_cvterm [cp, ca, cb] C))})\n         as ev\n         by (exists (fresh_var (bound_vars (get_cvterm [cp, ca, cb] C)));\n             apply fresh_var_not_in); exrepnd.\n\n  apply ind with (vb := v); try (complete sp); try (complete (exists (eqa p p ep); sp)).\n\n  rw @equality_in_function.\n  dands.\n\n  (* 1 *)\n  exists (eqb p p ep a1 a2 ea); sp.\n  generalize (e3 p p ep a1 a2 ea); intro n.\n  apply nuprl_refl in n; sp.\n\n  (* 2 *)\n  intros b b' eq.\n  rw @substc_mkc_pw_vs; simpl; try (complete sp).\n  rw @substc_mkc_pw_vs; simpl; try (complete sp).\n  exists (pweq lib eqp eqa eqb cp ca cb C (lsubstc3 cp p ca a1 cb b C)); sp.\n  apply CL_pw; unfold per_pw; unfold type_pfamily.\n  exists eqp eqa eqb (lsubstc3 cp p ca a1 cb b C) (lsubstc3 cp p ca a1 cb b' C).\n  exists cp cp ca ca cb cb C C; sp.\n  exists P P ap ap A A.\n  exists bp bp ba ba B B; sp; spcast; try (apply computes_to_valc_refl; apply iscvalue_mkc_pw).\n  assert (eqa p p ep a1 a1)\n         as ea1\n         by (eapply equality_eq_refl; eauto).\n  apply e4 with (ep := ep) (ea := ea1).\n  unfold equality in eq; exrepnd.\n  generalize (e3 p p ep a1 a1 ea1); intro n.\n  assert (eq_term_equals eq0 (eqb p p ep a1 a1 ea1))\n         as eqt\n         by (eapply nuprl_uniquely_valued; eauto; allapply nuprl_refl; sp).\n  rw <- eqt; sp.\n\n  (* 3 *)\n  intros b b' eq.\n  rw @substc_mkc_pw_vs; simpl; try (complete sp).\n  apply equality_in_pw.\n  exists eqp eqa eqb; dands; try (complete sp).\n\n  assert (eqa p p ep a1 a1)\n         as ea1 by (eapply equality_eq_refl; eauto).\n  apply e4 with (ep := ep) (ea := ea1).\n  unfold equality in eq; exrepnd.\n  generalize (e3 p p ep a1 a1 ea1); intro n.\n  assert (eq_term_equals eq0 (eqb p p ep a1 a1 ea1))\n         as eqt\n         by (eapply nuprl_uniquely_valued; eauto;\n             allapply nuprl_refl; sp).\n  rw <- eqt; sp.\n  eapply equality_eq_refl; eauto.\n\n  apply_hyp.\n  unfold equality in eq; exrepnd.\n  generalize (e3 p p ep a1 a2 ea); intro n.\n  assert (eq_term_equals eq0 (eqb p p ep a1 a2 ea))\n         as eqt\n         by (eapply nuprl_uniquely_valued; eauto;\n             allapply @nuprl_refl; sp).\n  rw <- eqt; sp.\n\n  (* 4 *)\n  intros b b' eq.\n  apply_hyp.\n  unfold equality in eq; exrepnd.\n  generalize (e3 p p ep a1 a2 ea); intro n.\n  assert (eq_term_equals eq0 (eqb p p ep a1 a2 ea))\n         as eqt\n         by (eapply nuprl_uniquely_valued; eauto;\n             allapply @nuprl_refl; sp).\n  rw <- eqt; sp.\n\n  assert (eqa p p ep a1 a1)\n         as ea1\n         by (eapply equality_eq_refl; eauto).\n  apply e4 with (ep := ep) (ea := ea1).\n  unfold equality in eq; exrepnd.\n  generalize (e3 p p ep a1 a1 ea1); intro n.\n  assert (eq_term_equals eq0 (eqb p p ep a1 a1 ea1))\n         as eqt\n         by (eapply nuprl_uniquely_valued; eauto;\n             allapply nuprl_refl; sp).\n  rw <- eqt; sp.\n  eapply equality_eq_refl; eauto.\n\n  generalize (equality_eq lib P p p2 eqp); intro ip.\n  dest_imp ip hyp.\n  apply ip in eqip; clear ip.\n\n  assert (eqa p p2 eqip a1 a2) as eqia.\n  generalize (e2 p p2 eqip); intro n1.\n  generalize (e2 p p ep); intro n2.\n  apply nuprl_uniquely_valued with (eq1 := eqa p p2 eqip) in n2.\n  dup ea as eqia.\n  rw <- n2 in eqia; sp.\n  allapply @nuprl_refl; sp.\n\n  assert (eqb p p2 eqip a1 a2 eqia b b') as eqib.\n  generalize (e3 p p2 eqip a1 a2 eqia); intro n.\n  apply nuprl_refl in n.\n  apply @equality_eq with (a := b) (b := b') in n.\n  rw <- n in eq; sp.\n\n  generalize (e4 p p2 eqip a1 a2 eqia b b' eqib); intro e.\n  exists eqp; sp.\nQed.\n\n(* slightly better than 3 because we can provide a list of variables that\n * v has to be disjoint with *)\nLemma param_w_ind4 {o} :\n  forall lib (P : @CTerm o) ap A bp ba B cp ca cb C (Q : CTerm -> CTerm -> CTerm -> CTerm -> [U]) vs,\n    (forall p1 p2 t1 t2 t3 t4,\n       cequivc lib t1 t3 -> cequivc lib t2 t4 -> Q p1 p2 t1 t2 -> Q p1 p2 t3 t4)\n    -> (forall p1 p2 a1 a2 f1 f2 vb,\n          !LIn vb vs\n          -> equality lib p1 p2 P\n          -> equality lib a1 a2 (substc p1 ap A)\n          -> equality lib f1 f2 (mkc_function\n                               (lsubstc2 bp p1 ba a1 B)\n                               vb\n                               (mkc_pw_vs [vb]\n                                          P ap A bp ba B cp ca cb C\n                                          (lsubstc3v3 cp p1 ca a1 cb vb C)))\n          -> (forall b1 b2,\n                equality lib b1 b2 (lsubstc2 bp p1 ba a1 B)\n                -> Q (lsubstc3 cp p1 ca a1 cb b1 C)\n                     (lsubstc3 cp p2 ca a2 cb b2 C)\n                     (mkc_apply f1 b1)\n                     (mkc_apply f2 b2))\n          -> Q p1\n               p2\n               (mkc_sup a1 f1)\n               (mkc_sup a2 f2))\n    -> (forall p1 p2 w1 w2,\n          equality lib p1 p2 P\n          -> equality lib w1 w2 (mkc_pw P ap A bp ba B cp ca cb C p1)\n          -> Q p1 p2 w1 w2).\nProof.\n  introv ceq ind eqip e.\n  apply equality_in_pw in e; exrepnd.\n  revert_dependents p2.\n  induction e0; spcast.\n  introv eqip.\n  apply ceq with (t1 := mkc_sup a1 f1) (t2 := mkc_sup a2 f2);\n    try (complete (apply cequivc_sym; apply computes_to_valc_implies_cequivc; sp)).\n\n  assert (eqa p p ep a2 a2)\n         as ea2\n         by (generalize (e2 p p ep); intro na;\n             apply (equality_eq_refl lib) with (A := substc p ap A) (B := substc p ap A) (b := a1); sp;\n             apply (equality_eq_sym lib) with (A := substc p ap A) (B := substc p ap A); sp).\n\n  assert ({v : NVar, !LIn v (bound_vars (get_cvterm [cp, ca, cb] C) ++ vs)})\n         as ev\n         by (exists (fresh_var (bound_vars (get_cvterm [cp, ca, cb] C) ++ vs));\n             apply fresh_var_not_in); exrepnd.\n\n  allrw in_app_iff.\n\n  apply ind with (vb := v);\n    try (complete sp);\n    try (complete (exists (eqa p p ep); sp)).\n\n  rw @equality_in_function.\n  dands.\n\n  (* 1 *)\n  exists (eqb p p ep a1 a2 ea); sp.\n  generalize (e3 p p ep a1 a2 ea); intro n.\n  apply nuprl_refl in n; sp.\n\n  (* 2 *)\n  intros b b' eq.\n  rw @substc_mkc_pw_vs; simpl; try (complete sp).\n  rw @substc_mkc_pw_vs; simpl; try (complete sp).\n  exists (pweq lib eqp eqa eqb cp ca cb C (lsubstc3 cp p ca a1 cb b C)); sp.\n  apply CL_pw; unfold per_pw; unfold type_pfamily.\n  exists eqp eqa eqb (lsubstc3 cp p ca a1 cb b C) (lsubstc3 cp p ca a1 cb b' C).\n  exists cp cp ca ca cb cb C C; sp.\n  exists P P ap ap A A.\n  exists bp bp ba ba B B; sp; spcast; try (apply computes_to_valc_refl; apply iscvalue_mkc_pw).\n  assert (eqa p p ep a1 a1)\n         as ea1 by (eapply equality_eq_refl; eauto).\n  apply e4 with (ep := ep) (ea := ea1).\n  unfold equality in eq; exrepnd.\n  generalize (e3 p p ep a1 a1 ea1); intro n.\n  assert (eq_term_equals eq0 (eqb p p ep a1 a1 ea1))\n         as eqt\n         by (eapply nuprl_uniquely_valued; eauto; allapply nuprl_refl; sp).\n  rw <- eqt; sp.\n\n  (* 3 *)\n  intros b b' eq.\n  rw @substc_mkc_pw_vs; simpl; try (complete sp).\n  apply equality_in_pw.\n  exists eqp eqa eqb; dands; try (complete sp).\n\n  assert (eqa p p ep a1 a1)\n         as ea1 by (eapply equality_eq_refl; eauto).\n  apply e4 with (ep := ep) (ea := ea1).\n  unfold equality in eq; exrepnd.\n  generalize (e3 p p ep a1 a1 ea1); intro n.\n  assert (eq_term_equals eq0 (eqb p p ep a1 a1 ea1))\n         as eqt\n         by (eapply nuprl_uniquely_valued; eauto; allapply nuprl_refl; sp).\n  rw <- eqt; sp.\n  eapply equality_eq_refl; eauto.\n\n  apply_hyp.\n  unfold equality in eq; exrepnd.\n  generalize (e3 p p ep a1 a2 ea); intro n.\n  assert (eq_term_equals eq0 (eqb p p ep a1 a2 ea))\n         as eqt\n         by (eapply nuprl_uniquely_valued; eauto; allapply @nuprl_refl; sp).\n  rw <- eqt; sp.\n\n  (* 4 *)\n  intros b b' eq.\n  apply_hyp.\n  unfold equality in eq; exrepnd.\n  generalize (e3 p p ep a1 a2 ea); intro n.\n  assert (eq_term_equals eq0 (eqb p p ep a1 a2 ea))\n         as eqt\n         by (eapply nuprl_uniquely_valued; eauto; allapply @nuprl_refl; sp).\n  rw <- eqt; sp.\n\n  assert (eqa p p ep a1 a1)\n         as ea1 by (eapply equality_eq_refl; eauto).\n  apply e4 with (ep := ep) (ea := ea1).\n  unfold equality in eq; exrepnd.\n  generalize (e3 p p ep a1 a1 ea1); intro n.\n  assert (eq_term_equals eq0 (eqb p p ep a1 a1 ea1))\n         as eqt\n         by (eapply nuprl_uniquely_valued; eauto; allapply nuprl_refl; sp).\n  rw <- eqt; sp.\n  eapply equality_eq_refl; eauto.\n\n  generalize (equality_eq lib P p p2 eqp); intro ip.\n  dest_imp ip hyp.\n  apply ip in eqip; clear ip.\n\n  assert (eqa p p2 eqip a1 a2) as eqia.\n  generalize (e2 p p2 eqip); intro n1.\n  generalize (e2 p p ep); intro n2.\n  apply nuprl_uniquely_valued with (eq1 := eqa p p2 eqip) in n2.\n  dup ea as eqia.\n  rw <- n2 in eqia; sp.\n  allapply @nuprl_refl; sp.\n\n  assert (eqb p p2 eqip a1 a2 eqia b b') as eqib.\n  generalize (e3 p p2 eqip a1 a2 eqia); intro n.\n  apply nuprl_refl in n.\n  apply @equality_eq with (a := b) (b := b') in n.\n  rw <- n in eq; sp.\n\n  generalize (e4 p p2 eqip a1 a2 eqia b b' eqib); intro e.\n  exists eqp; sp.\nQed.\n\n(* Useless *)\nLemma param_w_ind5 {o} :\n  forall lib (P : @CTerm o) ap A bp ba B cp ca cb C (Q : CTerm -> CTerm -> [U]),\n    (forall p t1 t2,\n       cequivc lib t1 t2 -> Q p t1 -> Q p t2)\n    -> (forall p1 p2 a1 a2 f1 f2 vb,\n          !LIn vb (bound_vars (get_cvterm [cp, ca, cb] C))\n          -> equality lib p1 p2 P\n          -> equality lib a1 a2 (substc p1 ap A)\n          -> equality lib f1 f2 (mkc_function\n                               (lsubstc2 bp p1 ba a1 B)\n                               vb\n                               (mkc_pw_vs [vb]\n                                          P ap A bp ba B cp ca cb C\n                                          (lsubstc3v3 cp p1 ca a1 cb vb C)))\n          -> (forall b1 b2,\n                equality lib b1 b2 (lsubstc2 bp p1 ba a1 B)\n                -> equality lib p1 p2 P\n                -> Q (lsubstc3 cp p1 ca a1 cb b1 C)\n                     (mkc_apply f1 b1))\n          -> Q p1\n               (mkc_sup a1 f1))\n    -> (forall p1 p2 w1 w2,\n          equality lib p1 p2 P\n          -> equality lib w1 w2 (mkc_pw P ap A bp ba B cp ca cb C p1)\n          -> Q p1 w1).\nProof.\n  introv ceq ind eqip e.\n  apply equality_in_pw in e; exrepnd.\n  revert_dependents p2.\n  induction e0 as [ p t1 t2 ep a1 f1 a2 f2 ea c1 c2 i r ]; spcast.\n  introv eqip.\n  apply ceq with (t1 := mkc_sup a1 f1);\n    try (complete (apply cequivc_sym; apply computes_to_valc_implies_cequivc; sp)).\n\n  assert (eqa p p ep a2 a2)\n         as ea2\n         by (generalize (e2 p p ep); intro na;\n             apply (equality_eq_refl lib) with (A := substc p ap A) (B := substc p ap A) (b := a1); sp;\n             apply (equality_eq_sym lib) with (A := substc p ap A) (B := substc p ap A); sp).\n\n  assert ({v : NVar, !LIn v (bound_vars (get_cvterm [cp, ca, cb] C))})\n         as ev\n         by (exists (fresh_var (bound_vars (get_cvterm [cp, ca, cb] C)));\n             apply fresh_var_not_in); exrepnd.\n\n  apply ind with (vb := v) (p2 := p2) (a2 := a2) (f2 := f2);\n    try (complete sp); try (complete (exists (eqa p p ep); sp)).\n\n  rw @equality_in_function.\n  dands.\n\n  (* 1 *)\n  exists (eqb p p ep a1 a2 ea); sp.\n  generalize (e3 p p ep a1 a2 ea); intro n.\n  apply nuprl_refl in n; sp.\n\n  (* 2 *)\n  intros b b' eq.\n  rw @substc_mkc_pw_vs; simpl; try (complete sp).\n  rw @substc_mkc_pw_vs; simpl; try (complete sp).\n  exists (pweq lib eqp eqa eqb cp ca cb C (lsubstc3 cp p ca a1 cb b C)); sp.\n  apply CL_pw; unfold per_pw; unfold type_pfamily.\n  exists eqp eqa eqb (lsubstc3 cp p ca a1 cb b C) (lsubstc3 cp p ca a1 cb b' C).\n  exists cp cp ca ca cb cb C C; sp.\n  exists P P ap ap A A.\n  exists bp bp ba ba B B; sp; spcast; try (apply computes_to_valc_refl; apply iscvalue_mkc_pw).\n  assert (eqa p p ep a1 a1)\n         as ea1 by (eapply equality_eq_refl; eauto).\n  apply e4 with (ep := ep) (ea := ea1).\n  unfold equality in eq; exrepnd.\n  generalize (e3 p p ep a1 a1 ea1); intro n.\n  assert (eq_term_equals eq0 (eqb p p ep a1 a1 ea1))\n         as eqt\n         by (eapply nuprl_uniquely_valued; eauto; allapply nuprl_refl; sp).\n  rw <- eqt; sp.\n\n  (* 3 *)\n  intros b b' eq.\n  rw @substc_mkc_pw_vs; simpl; try (complete sp).\n  apply equality_in_pw.\n  exists eqp eqa eqb; dands; try (complete sp).\n\n  assert (eqa p p ep a1 a1)\n         as ea1 by (eapply equality_eq_refl; eauto).\n  apply e4 with (ep := ep) (ea := ea1).\n  unfold equality in eq; exrepnd.\n  generalize (e3 p p ep a1 a1 ea1); intro n.\n  assert (eq_term_equals eq0 (eqb p p ep a1 a1 ea1))\n         as eqt\n         by (eapply nuprl_uniquely_valued; eauto; allapply nuprl_refl; sp).\n  rw <- eqt; sp.\n  eapply equality_eq_refl; eauto.\n\n  apply_hyp.\n  unfold equality in eq; exrepnd.\n  generalize (e3 p p ep a1 a2 ea); intro n.\n  assert (eq_term_equals eq0 (eqb p p ep a1 a2 ea))\n         as eqt\n         by (eapply nuprl_uniquely_valued; eauto; allapply @nuprl_refl; sp).\n  rw <- eqt; sp.\n\n  (* 4 *)\n  intros b b' eib eip.\n  apply r with (b2 := b') (p2 := lsubstc3 cp p2 ca a2 cb b' C).\n  unfold equality in eib; exrepnd.\n  generalize (e3 p p ep a1 a2 ea); intro n.\n  assert (eq_term_equals eq (eqb p p ep a1 a2 ea))\n         as eqt\n         by (eapply nuprl_uniquely_valued; eauto; allapply @nuprl_refl; sp).\n  rw <- eqt; sp.\n\n  assert (eqa p p ep a1 a1)\n         as ea1 by (eapply equality_eq_refl; eauto).\n  apply e4 with (ep := ep) (ea := ea1).\n  unfold equality in eib; exrepnd.\n  generalize (e3 p p ep a1 a1 ea1); intro n.\n  assert (eq_term_equals eq (eqb p p ep a1 a1 ea1))\n         as eqt\n         by (eapply nuprl_uniquely_valued; eauto; allapply nuprl_refl; sp).\n  rw <- eqt; sp.\n  eapply equality_eq_refl; eauto.\n\n  generalize (equality_eq lib P p p2 eqp); intro ip.\n  dest_imp ip hyp.\n  apply ip in eqip; clear ip.\n\n  assert (eqa p p2 eqip a1 a2) as eqia.\n  generalize (e2 p p2 eqip); intro n1.\n  generalize (e2 p p ep); intro n2.\n  apply nuprl_uniquely_valued with (eq1 := eqa p p2 eqip) in n2.\n  dup ea as eqia.\n  rw <- n2 in eqia; sp.\n  allapply @nuprl_refl; sp.\n\n  assert (eqb p p2 eqip a1 a2 eqia b b') as eqib.\n  generalize (e3 p p2 eqip a1 a2 eqia); intro n.\n  apply nuprl_refl in n.\n  apply @equality_eq with (a := b) (b := b') in n.\n  rw <- n in eib; sp.\n\n  generalize (e4 p p2 eqip a1 a2 eqia b b' eqib); intro e.\n  exists eqp; sp.\nQed.\n\nLemma weq_implies {p} :\n  forall lib (eqa1 eqa2 : per(p)) eqb1 eqb2,\n    eq_term_equals eqa1 eqa2\n    -> (forall (a a' : CTerm) (ea1 : eqa1 a a') (ea2 : eqa2 a a'),\n          eq_term_equals (eqb1 a a' ea1) (eqb2 a a' ea2))\n    -> forall t1 t2,\n         weq lib eqa1 eqb1 t1 t2\n         -> weq lib eqa2 eqb2 t1 t2.\nProof.\n  introv eqia eqib weq1.\n  induction weq1.\n\n  assert (eqa2 a a') as ea2 by (allrw <-; sp).\n\n  apply @weq_cons\n        with\n        (a  := a)\n        (f  := f)\n        (a' := a')\n        (f' := f')\n        (e  := ea2);\n    try (complete sp).\n\n  introv eia.\n\n  apply_hyp.\n  generalize (eqib a a' e ea2); intro eqt; allrw; sp.\nQed.\n\nLemma eq_term_equals_weq {p} :\n  forall lib (eqa1 eqa2 : per(p)) eqb1 eqb2,\n    eq_term_equals eqa1 eqa2\n    -> (forall (a a' : CTerm) (ea1 : eqa1 a a') (ea2 : eqa2 a a'),\n          eq_term_equals (eqb1 a a' ea1) (eqb2 a a' ea2))\n    -> eq_term_equals (weq lib eqa1 eqb1)\n                      (weq lib eqa2 eqb2).\nProof.\n  introv eqia eqib.\n  unfold eq_term_equals; introv; split; intro k.\n  apply @weq_implies with (eqa1 := eqa1) (eqb1 := eqb1); sp.\n\n  apply @weq_implies with (eqa1 := eqa2) (eqb1 := eqb2); sp;\n  apply eq_term_equals_sym; sp.\nQed.\n\nLemma equality_in_w_v1 {p} :\n  forall lib A v B (t1 t2 : @CTerm p),\n    equality lib t1 t2 (mkc_w A v B)\n    <=> {a1, a2, f1, f2 : CTerm\n         , t1 ===>(lib) (mkc_sup a1 f1)\n         # t2 ===>(lib) (mkc_sup a2 f2)\n         # equality lib a1 a2 A\n         # equality lib f1 f2 (mkc_fun (substc a1 v B) (mkc_w A v B))\n         # (forall a a', equality lib a a' A -> tequality lib (substc a v B) (substc a' v B))}.\nProof.\n  introv; split; intro e.\n\n  - unfold equality in e; exrepnd.\n    inversion e1; try not_univ.\n    allunfold @per_w; exrepnd.\n    allunfold @type_family; exrepnd.\n    allfold (@nuprl p lib).\n    computes_to_value_isvalue.\n    allunfold @eq_term_equals; discover.\n    destruct h.\n    exists a a' f f'; sp.\n    exists eqa; sp.\n    rw <- @fold_mkc_fun.\n    rw @equality_in_function; dands.\n\n    exists (eqb a a' e).\n    apply @nuprl_refl with (t2 := substc a' v0 B0); sp.\n\n    intros b1 b2 eib.\n    generalize (equality_eq1 lib (substc a v0 B0) (substc a' v0 B0) b1 b2 (eqb a a' e));\n      intro k; repeat (dest_imp k hyp).\n    discover.\n    allrw @substc_cnewvar.\n    exists eq; sp.\n\n    intros b1 b2 eib.\n    allrw @substc_cnewvar.\n    exists eq; sp.\n    allrw.\n    apply_hyp.\n    generalize (equality_eq1 lib (substc a v0 B0) (substc a' v0 B0) b1 b2 (eqb a a' e));\n      intro k; repeat (dest_imp k hyp).\n    discover; sp.\n\n    allunfold @equality; exrepnd.\n    generalize (nuprl_uniquely_valued lib A0 eq0 eqa); introv k; repeat (dest_imp k hyp).\n    assert (eqa a0 a'0) as ea by (allrw <-; sp).\n    exists (eqb a0 a'0 ea); sp.\n\n  - exrepnd.\n    unfold equality in e3; exrepnd.\n    rename eq into eqa.\n\n    generalize (choice_teq lib A v B v B e1); intro n; exrepnd.\n\n    exists (weq lib eqa (fun a a' ea => f a a' (eq_equality1 lib a a' A eqa ea e3))); dands.\n\n    apply CL_w; unfold per_w.\n    exists eqa.\n    exists (fun a a' ea => f a a' (eq_equality1 lib a a' A eqa ea e3)); sp.\n    unfold type_family.\n    fold (@nuprl p lib).\n    exists A A v v B B; sp;\n    try (complete (spcast; apply computes_to_valc_refl; try (apply iscvalue_mkc_w))).\n\n    apply @weq_cons with (a := a1) (f := f1) (a' := a2) (f' := f2) (e := e5); sp.\n    generalize (n0 a1 a2 (eq_equality1 lib a1 a2 A eqa e5 e3)); intro n.\n    rw <- @fold_mkc_fun in e4.\n    rw @equality_in_function in e4; repnd.\n    generalize (e4 b b'); intro k.\n    dest_imp k hyp.\n    exists (f a1 a2 (eq_equality1 lib a1 a2 A eqa e5 e3)); sp.\n    allapply @nuprl_refl; sp.\n    allrw @substc_cnewvar.\n    unfold equality in k; exrepnd.\n    inversion k1; try not_univ.\n    allunfold @per_w; exrepnd.\n    allunfold @type_family; exrepnd; allfold (@nuprl p lib).\n    computes_to_value_isvalue.\n    allunfold @eq_term_equals; discover.\n\n    assert (eq_term_equals eqa0 eqa)\n           as eqta by (eapply nuprl_uniquely_valued; eauto).\n\n    assert (forall (a a' : CTerm) (ea : eqa a a') (ea' : eqa0 a a'),\n              eq_term_equals (f a a' (eq_equality1 lib a a' A0 eqa ea e3)) (eqb a a' ea'))\n           as eqtb.\n    introv.\n    generalize (n0 a a' (eq_equality1 lib a a' A0 eqa ea e3)); intro n1.\n    assert (nuprl lib (substc a v0 B0) (substc a' v0 B0) (eqb a a' ea')) as n2 by sp.\n    apply (nuprl_uniquely_valued lib) with (t := substc a v0 B0); sp; allapply @nuprl_refl; sp.\n    apply weq_implies with (eqa1 := eqa0) (eqb1 := eqb); sp.\n    apply eq_term_equals_sym; sp.\nQed.\n\nLemma tequality_mkc_w {p} :\n  forall lib (A1 : @CTerm p) v1 B1\n         A2 v2 B2,\n    tequality lib\n      (mkc_w A1 v1 B1)\n      (mkc_w A2 v2 B2)\n    <=>\n    (tequality lib A1 A2\n     # (forall a1 a2,\n        equality lib a1 a2 A1\n        -> tequality lib (substc a1 v1 B1) (substc a2 v2 B2))).\nProof.\n  introv; split; intro e; repnd.\n\n  - unfold tequality in e; exrepnd.\n    unfold nuprl in e0.\n    inversion e0; try not_univ.\n    allunfold @per_w; exrepnd.\n    allunfold @type_family; exrepnd; spcast; allfold (@nuprl p lib).\n    computes_to_value_isvalue.\n    dands.\n\n    + allapply @tequality_if_nuprl; sp.\n\n    + introv eia.\n      generalize (equality_eq1 lib A A' a1 a2 eqa); intro i; dest_imp i hyp.\n      rw <- i in eia.\n      exists (eqb a1 a2 eia); sp.\n\n  - unfold tequality.\n    unfold tequality in e0; exrepnd.\n    rename eq into eqa.\n\n    generalize (choice_teq1 lib A1 eqa v1 B1 v2 B2); intro neqb.\n    dest_imp neqb hyp; try (complete (allapply @nuprl_refl; sp)).\n    dest_imp neqb hyp; exrepnd.\n    rename f into eqb.\n\n    exists (weq lib eqa eqb).\n    apply CL_w; unfold per_w.\n    exists eqa eqb; sp.\n    unfold type_family.\n    exists A1 A2 v1 v2 B1 B2; dands;\n    try (complete sp);\n    try (complete (spcast; apply computes_to_valc_refl; try (apply iscvalue_mkc_w))).\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_w.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.61878043374385, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2876719959826227}}
{"text": "Require Import UFO.Lang.Syntax.\nRequire Import UFO.Lang.Bindings_map.\nRequire Import TLC.LibReflect.\nSet Implicit Arguments.\n\nImplicit Types EP EV LV V L : Set.\n\nLocal Obligation Tactic := idtac.\n\nProgram Definition fsub_lid L (id' : lid L) (X : var) (id : lid L) : lid L :=\n  match id' with\n  | lid_f Y => _\n  | lid_b _ => id'\n  end.\nNext Obligation.\nProof.\nintros L id' X id Y G.\ndestruct (var_compare X Y) eqn:Heq ;\n  rewrite var_compare_eq in Heq ;\n  rew_bool_eq in Heq ; [ apply id | apply id' ].\nDefined.\n\nDefinition fsub_lbl LV L (ℓ : lbl LV L) (X : var) (id : lid L) : lbl LV L :=\n  match ℓ with\n  | lbl_var _ => ℓ\n  | lbl_id id' => lbl_id (fsub_lid id' X id)\n  end.\n\nDefinition\n  fsub_ef EP EV LV L (e : ef EP EV LV L) (X : var) (id : lid L) : ef EP EV LV L :=\n  match e with\n  | ef_par _ => e\n  | ef_var _ => e\n  | ef_lbl ℓ => ef_lbl (fsub_lbl ℓ X id)\n  end\n.\n\nFixpoint\n  fsub_eff EP EV LV L (E : eff EP EV LV L) (X : var) (id : lid L) : eff EP EV LV L :=\n  match E with\n  | [] => []\n  | e :: E' => (fsub_ef e X id) :: (fsub_eff E' X id)\n  end\n.\n\nFixpoint\n  fsub_it EP EV LV L κ (N : it EP EV LV L κ) (X : var) (id : lid L) : it EP EV LV L κ :=\n  match N with\n  | it_name 𝔽 => it_name 𝔽\n  | it_inst N E => it_inst (fsub_it N X id) (fsub_eff E X id)\n  end\n.\n\nFixpoint\n  fsub_ms EP EV LV L (σ : ms EP EV LV L) (X : var) (id : lid L) : ms EP EV LV L :=\n  match σ with\n  | ms_ev σ => ms_ev (fsub_ms σ X id)\n  | ms_lv σ => ms_lv (fsub_ms σ X id)\n  | ms_tm T σ => ms_tm (fsub_ty T X id) (fsub_ms σ X id)\n  | ms_res T E => ms_res (fsub_ty T X id) (fsub_eff E X id)\n  end\nwith\n  fsub_ty EP EV LV L (T : ty EP EV LV L) (X : var) (id : lid L) : ty EP EV LV L :=\n  match T with\n  | 𝟙 => 𝟙\n  | ty_it N ℓ => ty_it (fsub_it N X id) (fsub_lbl ℓ X id)\n  | ty_ms σ ℓ => ty_ms (fsub_ms σ X id) (fsub_lbl ℓ X id)\n  | ty_cont Ta Ea Tb Eb =>\n    ty_cont (fsub_ty Ta X id) (fsub_eff Ea X id) (fsub_ty Tb X id) (fsub_eff Eb X id)\n  end\n.\n\nFixpoint\n  fsub_md EV LV V L (m : md EV LV V L) (X : var) (id : lid L) : md EV LV V L :=\n  match m with\n  | md_ev m => md_ev (fsub_md m X id)\n  | md_lv m => md_lv (fsub_md m X id)\n  | md_tm m => md_tm (fsub_md m X id)\n  | md_res t => md_res (fsub_tm t X id)\n  end\nwith\n  fsub_ktx EV LV V L (K : ktx EV LV V L) (X : var) (id : lid L) : ktx EV LV V L :=\n  match K with\n  | ktx_hole => ktx_hole\n  | ktx_down K Y =>\n      ktx_down (fsub_ktx K X id) Y\n  | ktx_up K =>\n      ktx_up (fsub_ktx K X id)\n  | ktx_op K =>\n      ktx_op (fsub_ktx K X id)\n  | ktx_let K t =>\n      ktx_let (fsub_ktx K X id) (fsub_tm t X id)\n  | ktx_throw K t =>\n      ktx_throw (fsub_ktx K X id) (fsub_tm t X id)\n  | ktx_app_eff K E =>\n      ktx_app_eff (fsub_ktx K X id) (fsub_eff E X id)\n  | ktx_app_lbl K ℓ =>\n      ktx_app_lbl (fsub_ktx K X id) (fsub_lbl ℓ X id)\n  | ktx_app_tm1 K t =>\n      ktx_app_tm1 (fsub_ktx K X id) (fsub_tm t X id)\n  | ktx_app_tm2 K v =>\n      ktx_app_tm2 (fsub_ktx K X id) (fsub_val v X id)\n  end\nwith\n  fsub_val EV LV V L (v : val EV LV V L) (X : var) (id : lid L) : val EV LV V L :=\n  match v with\n  | val_unit => val_unit\n  | val_var x => val_var x\n  | val_cont K => fsub_ktx K X id\n  | val_md m id' => val_md (fsub_md m X id) (fsub_lid id' X id)\n  | val_fix m id' => val_fix (fsub_md m X id) (fsub_lid id' X id)\n  end\nwith\n  fsub_tm EV LV V L (t : tm EV LV V L) (X : var) (id : lid L) : tm EV LV V L :=\n  match t with\n  | tm_val v => fsub_val v X id\n  | tm_op t => tm_op (fsub_tm t X id)\n  | ⇧ t => ⇧ (fsub_tm t X id)\n  | ⬇ t => ⬇ (fsub_tm t X (L_shift_lid id))\n  | ⇩ X t => ⇩ X (fsub_tm t X id)\n  | tm_let s t => tm_let (fsub_tm s X id) (fsub_tm t X id)\n  | tm_throw t s => tm_throw (fsub_tm t X id) (fsub_tm s X id)\n  | tm_app_eff t E => tm_app_eff (fsub_tm t X id) (fsub_eff E X id)\n  | tm_app_lbl t ℓ => tm_app_lbl (fsub_tm t X id) (fsub_lbl ℓ X id)\n  | tm_app_tm t s => tm_app_tm (fsub_tm t X id) (fsub_tm s X id)\n  end\n.\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/Bindings_fsub.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2876719894460082}}
{"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 A B C D E F P Q DD FF X CC : Universe, ((wd_ A B /\\ (wd_ D E /\\ (wd_ E F /\\ (wd_ B Q /\\ (wd_ E P /\\ (wd_ B C /\\ (wd_ A C /\\ (wd_ D F /\\ (wd_ D P /\\ (wd_ E FF /\\ (wd_ E DD /\\ (wd_ CC B /\\ (wd_ E X /\\ (col_ E DD P /\\ (col_ DD X FF /\\ (col_ B C CC /\\ (col_ E X P /\\ (col_ E F FF /\\ col_ E D DD)))))))))))))))))) -> col_ D E P)).\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_0099.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2876450999938632}}
{"text": "From iris.algebra Require Export updates local_updates frac dfrac agree.\nFrom iris.algebra Require Import proofmode_classes big_op.\nFrom iris.prelude Require Import options.\n\n(** The view camera with fractional authoritative elements *)\n(** The view camera, which is reminiscent of the views framework, is used to\n  provide a logical/\"small-footprint\" \"view\" of some \"large-footprint\" piece of\n  data, which can be shared in the separation logic sense, i.e., different parts\n  of the data can be separately owned by different functions or threads. This is\n  achieved using the two elements of the view camera:\n\n- The authoritative element [●V a], which describes the data under consideration.\n- The fragment [◯V b], which provides a logical view of the data [a].\n\nTo enable sharing of the fragments, the type of fragments is equipped with a\ncamera structure so ownership of fragments can be split. Concretely, fragments\nenjoy the rule [◯V (b1 ⋅ b2) = ◯V b1 ⋅ ◯V b2].\n\nTo enable sharing of the authoritative element [●V{dq} a], it is equipped with a\ndiscardable fraction [dq]. Updates are only possible with the full authoritative\nelement [●V a] (syntax for [●V{#1} a]]), while fractional authoritative elements\nhave agreement, i.e., [✓ (●V{dq1} a1 ⋅ ●V{dq2} a2) → a1 ≡ a2]. *)\n\n(** * The view relation *)\n(** To relate the authoritative element [a] to its possible fragments [b], the\nview camera is parametrized by a (step-indexed) relation [view_rel n a b]. This\nrelation should be a.) closed under smaller step-indexes [n], b.) non-expansive\nw.r.t. the argument [a], c.) closed under smaller [b] (which implies\nnon-expansiveness w.r.t. [b]), and d.) ensure validity of the argument [b].\n\nNote 1: Instead of requiring both a step-indexed and a non-step-indexed version\nof the relation (like cameras do for validity), we use [∀ n, view_rel n] as the\nnon-step-indexed version. This is anyway necessary when using [≼{n}] as the\nrelation (like the authoritative camera does) as its non-step-indexed version\nis not equivalent to [∀ n, x ≼{n} y].\n\nNote 2: The view relation is defined as a canonical structure so that given a\nrelation [nat → A → B → Prop], the instance with the laws can be inferred. We do\nnot use type classes for this purpose because cameras themselves are represented\nusing canonical structures. It has proven fragile for a canonical structure\ninstance to take a type class as a parameter (in this case, [viewR] would need\nto take a class with the view relation laws). *)\nStructure view_rel (A : ofe) (B : ucmra) := ViewRel {\n  view_rel_holds :> nat → A → B → Prop;\n  view_rel_mono n1 n2 a1 a2 b1 b2 :\n    view_rel_holds n1 a1 b1 →\n    a1 ≡{n2}≡ a2 →\n    b2 ≼{n2} b1 →\n    n2 ≤ n1 →\n    view_rel_holds n2 a2 b2;\n  view_rel_validN n a b :\n    view_rel_holds n a b → ✓{n} b;\n  view_rel_unit n :\n    ∃ a, view_rel_holds n a ε\n}.\nGlobal Arguments ViewRel {_ _} _ _.\nGlobal Arguments view_rel_holds {_ _} _ _ _ _.\nGlobal Instance: Params (@view_rel_holds) 4 := {}.\n\nGlobal Instance view_rel_ne {A B} (rel : view_rel A B) n :\n  Proper (dist n ==> dist n ==> iff) (rel n).\nProof.\n  intros a1 a2 Ha b1 b2 Hb.\n  split=> ?; (eapply view_rel_mono; [done|done|by rewrite Hb|done]).\nQed.\nGlobal Instance view_rel_proper {A B} (rel : view_rel A B) n :\n  Proper ((≡) ==> (≡) ==> iff) (rel n).\nProof. intros a1 a2 Ha b1 b2 Hb. apply view_rel_ne; by apply equiv_dist. Qed.\n\nClass ViewRelDiscrete {A B} (rel : view_rel A B) :=\n  view_rel_discrete n a b : rel 0 a b → rel n a b.\n\n(** * Definition of the view camera *)\n(** To make use of the lemmas provided in this file, elements of [view] should\nalways be constructed using [●V] and [◯V], and never using the constructor\n[View]. *)\nRecord view {A B} (rel : nat → A → B → Prop) :=\n  View { view_auth_proj : option (dfrac * agree A) ; view_frag_proj : B }.\nAdd Printing Constructor view.\nGlobal Arguments View {_ _ _} _ _.\nGlobal Arguments view_auth_proj {_ _ _} _.\nGlobal Arguments view_frag_proj {_ _ _} _.\nGlobal Instance: Params (@View) 3 := {}.\nGlobal Instance: Params (@view_auth_proj) 3 := {}.\nGlobal Instance: Params (@view_frag_proj) 3 := {}.\n\nDefinition view_auth {A B} {rel : view_rel A B} (dq : dfrac) (a : A) : view rel :=\n  View (Some (dq, to_agree a)) ε.\nDefinition view_frag {A B} {rel : view_rel A B} (b : B) : view rel := View None b.\nTypeclasses Opaque view_auth view_frag.\n\nGlobal Instance: Params (@view_auth) 3 := {}.\nGlobal Instance: Params (@view_frag) 3 := {}.\n\nNotation \"●V dq a\" := (view_auth dq a)\n  (at level 20, dq custom dfrac at level 1, format \"●V dq  a\").\nNotation \"◯V a\" := (view_frag a) (at level 20).\n\n(** * The OFE structure *)\n(** We omit the usual [equivI] lemma because it is hard to state a suitably\ngeneral version in terms of [●V] and [◯V], and because such a lemma has never\nbeen needed in practice. *)\nSection ofe.\n  Context {A B : ofe} (rel : nat → A → B → Prop).\n  Implicit Types a : A.\n  Implicit Types ag : option (dfrac * agree A).\n  Implicit Types b : B.\n  Implicit Types x y : view rel.\n\n  Local Instance view_equiv : Equiv (view rel) := λ x y,\n    view_auth_proj x ≡ view_auth_proj y ∧ view_frag_proj x ≡ view_frag_proj y.\n  Local Instance view_dist : Dist (view rel) := λ n x y,\n    view_auth_proj x ≡{n}≡ view_auth_proj y ∧\n    view_frag_proj x ≡{n}≡ view_frag_proj y.\n\n  Global Instance View_ne : NonExpansive2 (@View A B rel).\n  Proof. by split. Qed.\n  Global Instance View_proper : Proper ((≡) ==> (≡) ==> (≡)) (@View A B rel).\n  Proof. by split. Qed.\n  Global Instance view_auth_proj_ne: NonExpansive (@view_auth_proj A B rel).\n  Proof. by destruct 1. Qed.\n  Global Instance view_auth_proj_proper :\n    Proper ((≡) ==> (≡)) (@view_auth_proj A B rel).\n  Proof. by destruct 1. Qed.\n  Global Instance view_frag_proj_ne : NonExpansive (@view_frag_proj A B rel).\n  Proof. by destruct 1. Qed.\n  Global Instance view_frag_proj_proper :\n    Proper ((≡) ==> (≡)) (@view_frag_proj A B rel).\n  Proof. by destruct 1. Qed.\n\n  Definition view_ofe_mixin : OfeMixin (view rel).\n  Proof. by apply (iso_ofe_mixin (λ x, (view_auth_proj x, view_frag_proj x))). Qed.\n  Canonical Structure viewO := Ofe (view rel) view_ofe_mixin.\n\n  Global Instance View_discrete ag b :\n    Discrete ag → Discrete b → Discrete (View ag b).\n  Proof. by intros ?? [??] [??]; split; apply: discrete. Qed.\n  Global Instance view_ofe_discrete :\n    OfeDiscrete A → OfeDiscrete B → OfeDiscrete viewO.\n  Proof. intros ?? [??]; apply _. Qed.\nEnd ofe.\n\n(** * The camera structure *)\nSection cmra.\n  Context {A B} (rel : view_rel A B).\n  Implicit Types a : A.\n  Implicit Types ag : option (dfrac * agree A).\n  Implicit Types b : B.\n  Implicit Types x y : view rel.\n  Implicit Types q : frac.\n  Implicit Types dq : dfrac.\n\n  Global Instance view_auth_ne dq : NonExpansive (@view_auth A B rel dq).\n  Proof. solve_proper. Qed.\n  Global Instance view_auth_proper dq : Proper ((≡) ==> (≡)) (@view_auth A B rel dq).\n  Proof. solve_proper. Qed.\n  Global Instance view_frag_ne : NonExpansive (@view_frag A B rel).\n  Proof. done. Qed.\n  Global Instance view_frag_proper : Proper ((≡) ==> (≡)) (@view_frag A B rel).\n  Proof. done. Qed.\n\n  Global Instance view_auth_dist_inj n :\n    Inj2 (=) (dist n) (dist n) (@view_auth A B rel).\n  Proof.\n    intros dq1 a1 dq2 a2 [Hag ?]; inversion Hag as [?? [??]|]; simplify_eq/=.\n    split; [done|]. by apply (inj to_agree).\n  Qed.\n  Global Instance view_auth_inj : Inj2 (=) (≡) (≡) (@view_auth A B rel).\n  Proof.\n    intros dq1 a1 dq2 a2 [Hag ?]; inversion Hag as [?? [??]|]; simplify_eq/=.\n    split; [done|]. by apply (inj to_agree).\n  Qed.\n  Global Instance view_frag_dist_inj n : Inj (dist n) (dist n) (@view_frag A B rel).\n  Proof. by intros ?? [??]. Qed.\n  Global Instance view_frag_inj : Inj (≡) (≡) (@view_frag A B rel).\n  Proof. by intros ?? [??]. Qed.\n\n  Local Instance view_valid_instance : Valid (view rel) := λ x,\n    match view_auth_proj x with\n    | Some (dq, ag) =>\n       ✓ dq ∧ (∀ n, ∃ a, ag ≡{n}≡ to_agree a ∧ rel n a (view_frag_proj x))\n    | None => ∀ n, ∃ a, rel n a (view_frag_proj x)\n    end.\n  Local Instance view_validN_instance : ValidN (view rel) := λ n x,\n    match view_auth_proj x with\n    | Some (dq, ag) =>\n       ✓{n} dq ∧ ∃ a, ag ≡{n}≡ to_agree a ∧ rel n a (view_frag_proj x)\n    | None => ∃ a, rel n a (view_frag_proj x)\n    end.\n  Local Instance view_pcore_instance : PCore (view rel) := λ x,\n    Some (View (core (view_auth_proj x)) (core (view_frag_proj x))).\n  Local Instance view_op_instance : Op (view rel) := λ x y,\n    View (view_auth_proj x ⋅ view_auth_proj y) (view_frag_proj x ⋅ view_frag_proj y).\n\n  Local Definition view_valid_eq :\n    valid = λ x,\n      match view_auth_proj x with\n      | Some (dq, ag) =>\n         ✓ dq ∧ (∀ n, ∃ a, ag ≡{n}≡ to_agree a ∧ rel n a (view_frag_proj x))\n      | None => ∀ n, ∃ a, rel n a (view_frag_proj x)\n      end := eq_refl _.\n  Local Definition view_validN_eq :\n    validN = λ n x,\n      match view_auth_proj x with\n      | Some (dq, ag) => ✓{n} dq ∧ ∃ a, ag ≡{n}≡ to_agree a ∧ rel n a (view_frag_proj x)\n      | None => ∃ a, rel n a (view_frag_proj x)\n      end := eq_refl _.\n  Local Definition view_pcore_eq :\n      pcore = λ x, Some (View (core (view_auth_proj x)) (core (view_frag_proj x))) :=\n    eq_refl _.\n  Local Definition view_core_eq :\n      core = λ x, View (core (view_auth_proj x)) (core (view_frag_proj x)) :=\n    eq_refl _.\n  Local Definition view_op_eq :\n      op = λ x y, View (view_auth_proj x ⋅ view_auth_proj y)\n                       (view_frag_proj x ⋅ view_frag_proj y) :=\n    eq_refl _.\n\n  Lemma view_cmra_mixin : CmraMixin (view rel).\n  Proof.\n    apply (iso_cmra_mixin_restrict\n      (λ x : option (dfrac * agree A) * B, View x.1 x.2)\n      (λ x, (view_auth_proj x, view_frag_proj x))); try done.\n    - intros [x b]. by rewrite /= pair_pcore !cmra_pcore_core.\n    - intros n [[[dq ag]|] b]; rewrite /= view_validN_eq /=.\n      + intros (?&a&->&?). repeat split; simpl; [done|]. by eapply view_rel_validN.\n      + intros [a ?]. repeat split; simpl. by eapply view_rel_validN.\n    - rewrite view_validN_eq.\n      intros n [x1 b1] [x2 b2] [Hx ?]; simpl in *;\n        destruct Hx as [[q1 ag1] [q2 ag2] [??]|]; intros ?; by ofe_subst.\n    - rewrite view_valid_eq view_validN_eq.\n      intros [[[dq aa]|] b]; rewrite /= ?cmra_valid_validN; naive_solver.\n    - rewrite view_validN_eq=> n [[[dq ag]|] b] /=.\n      + intros [? (a&?&?)]; split; [done|].\n        exists a; split; [by eauto using dist_le|].\n        apply view_rel_mono with (S n) a b; auto with lia.\n      + intros [a ?]. exists a. apply view_rel_mono with (S n) a b; auto with lia.\n    - rewrite view_validN_eq=> n [[[q1 ag1]|] b1] [[[q2 ag2]|] b2] /=.\n      + intros [?%cmra_validN_op_l (a & Haga & ?)]. split; [done|].\n        assert (ag1 ≡{n}≡ ag2) as Ha12 by (apply agree_op_invN; by rewrite Haga).\n        exists a. split; [by rewrite -Haga -Ha12 agree_idemp|].\n        apply view_rel_mono with n a (b1 ⋅ b2); eauto using cmra_includedN_l.\n      + intros [? (a & Haga & ?)]. split; [done|]. exists a; split; [done|].\n        apply view_rel_mono with n a (b1 ⋅ b2); eauto using cmra_includedN_l.\n      + intros [? (a & Haga & ?)]. exists a.\n        apply view_rel_mono with n a (b1 ⋅ b2); eauto using cmra_includedN_l.\n      + intros [a ?]. exists a.\n        apply view_rel_mono with n a (b1 ⋅ b2); eauto using cmra_includedN_l.\n  Qed.\n  Canonical Structure viewR := Cmra (view rel) view_cmra_mixin.\n\n  Global Instance view_auth_discrete dq a :\n    Discrete a → Discrete (ε : B) → Discrete (●V{dq} a : view rel).\n  Proof. intros. apply View_discrete; apply _. Qed.\n  Global Instance view_frag_discrete b :\n    Discrete b → Discrete (◯V b : view rel).\n  Proof. intros. apply View_discrete; apply _. Qed.\n  Global Instance view_cmra_discrete :\n    OfeDiscrete A → CmraDiscrete B → ViewRelDiscrete rel →\n    CmraDiscrete viewR.\n  Proof.\n    split; [apply _|]=> -[[[dq ag]|] b]; rewrite view_valid_eq view_validN_eq /=.\n    - rewrite -cmra_discrete_valid_iff.\n      setoid_rewrite <-(discrete_iff _ ag). naive_solver.\n    - naive_solver.\n  Qed.\n\n  Local Instance view_empty_instance : Unit (view rel) := View ε ε.\n  Lemma view_ucmra_mixin : UcmraMixin (view rel).\n  Proof.\n    split; simpl.\n    - rewrite view_valid_eq /=. apply view_rel_unit.\n    - by intros x; constructor; rewrite /= left_id.\n    - do 2 constructor; [done| apply (core_id_core _)].\n  Qed.\n  Canonical Structure viewUR := Ucmra (view rel) view_ucmra_mixin.\n\n  (** Operation *)\n  Lemma view_auth_dfrac_op dq1 dq2 a : ●V{dq1 ⋅ dq2} a ≡ ●V{dq1} a ⋅ ●V{dq2} a.\n  Proof.\n    intros; split; simpl; last by rewrite left_id.\n    by rewrite -Some_op -pair_op agree_idemp.\n  Qed.\n  Global Instance view_auth_dfrac_is_op dq dq1 dq2 a :\n    IsOp dq dq1 dq2 → IsOp' (●V{dq} a) (●V{dq1} a) (●V{dq2} a).\n  Proof. rewrite /IsOp' /IsOp => ->. by rewrite -view_auth_dfrac_op. Qed.\n\n  Lemma view_frag_op b1 b2 : ◯V (b1 ⋅ b2) = ◯V b1 ⋅ ◯V b2.\n  Proof. done. Qed.\n  Lemma view_frag_mono b1 b2 : b1 ≼ b2 → ◯V b1 ≼ ◯V b2.\n  Proof. intros [c ->]. rewrite view_frag_op. apply cmra_included_l. Qed.\n  Lemma view_frag_core b : core (◯V b) = ◯V (core b).\n  Proof. done. Qed.\n  Lemma view_both_core_discarded a b :\n    core (●V□ a ⋅ ◯V b) ≡ ●V□ a ⋅ ◯V (core b).\n  Proof. rewrite view_core_eq view_op_eq /= !left_id //. Qed.\n  Lemma view_both_core_frac q a b :\n    core (●V{#q} a ⋅ ◯V b) ≡ ◯V (core b).\n  Proof. rewrite view_core_eq view_op_eq /= !left_id //. Qed.\n\n  Global Instance view_auth_core_id a : CoreId (●V□ a).\n  Proof. do 2 constructor; simpl; auto. apply: core_id_core. Qed.\n  Global Instance view_frag_core_id b : CoreId b → CoreId (◯V b).\n  Proof. do 2 constructor; simpl; auto. apply: core_id_core. Qed.\n  Global Instance view_both_core_id a b : CoreId b → CoreId (●V□ a ⋅ ◯V b).\n  Proof. do 2 constructor; simpl; auto. rewrite !left_id. apply: core_id_core. Qed.\n  Global Instance view_frag_is_op b b1 b2 :\n    IsOp b b1 b2 → IsOp' (◯V b) (◯V b1) (◯V b2).\n  Proof. done. Qed.\n  Global Instance view_frag_sep_homomorphism :\n    MonoidHomomorphism op op (≡) (@view_frag A B rel).\n  Proof. by split; [split; try apply _|]. Qed.\n\n  Lemma big_opL_view_frag {C} (g : nat → C → B) (l : list C) :\n    (◯V [^op list] k↦x ∈ l, g k x) ≡ [^op list] k↦x ∈ l, ◯V (g k x).\n  Proof. apply (big_opL_commute _). Qed.\n  Lemma big_opM_view_frag `{Countable K} {C} (g : K → C → B) (m : gmap K C) :\n    (◯V [^op map] k↦x ∈ m, g k x) ≡ [^op map] k↦x ∈ m, ◯V (g k x).\n  Proof. apply (big_opM_commute _). Qed.\n  Lemma big_opS_view_frag `{Countable C} (g : C → B) (X : gset C) :\n    (◯V [^op set] x ∈ X, g x) ≡ [^op set] x ∈ X, ◯V (g x).\n  Proof. apply (big_opS_commute _). Qed.\n  Lemma big_opMS_view_frag `{Countable C} (g : C → B) (X : gmultiset C) :\n    (◯V [^op mset] x ∈ X, g x) ≡ [^op mset] x ∈ X, ◯V (g x).\n  Proof. apply (big_opMS_commute _). Qed.\n\n  (** Validity *)\n  Lemma view_auth_dfrac_op_invN n dq1 a1 dq2 a2 :\n    ✓{n} (●V{dq1} a1 ⋅ ●V{dq2} a2) → a1 ≡{n}≡ a2.\n  Proof.\n    rewrite /op /view_op_instance /= left_id -Some_op -pair_op view_validN_eq /=.\n    intros (?&?& Eq &?). apply (inj to_agree), agree_op_invN. by rewrite Eq.\n  Qed.\n  Lemma view_auth_dfrac_op_inv dq1 a1 dq2 a2 : ✓ (●V{dq1} a1 ⋅ ●V{dq2} a2) → a1 ≡ a2.\n  Proof.\n    intros ?. apply equiv_dist. intros n.\n    by eapply view_auth_dfrac_op_invN, cmra_valid_validN.\n  Qed.\n  Lemma view_auth_dfrac_op_inv_L `{!LeibnizEquiv A} dq1 a1 dq2 a2 :\n    ✓ (●V{dq1} a1 ⋅ ●V{dq2} a2) → a1 = a2.\n  Proof. by intros ?%view_auth_dfrac_op_inv%leibniz_equiv. Qed.\n\n  Lemma view_auth_dfrac_validN n dq a : ✓{n} (●V{dq} a) ↔ ✓{n}dq ∧ rel n a ε.\n  Proof.\n    rewrite view_validN_eq /=. apply and_iff_compat_l. split; [|by eauto].\n    by intros [? [->%(inj to_agree) ?]].\n  Qed.\n  Lemma view_auth_validN n a : ✓{n} (●V a) ↔ rel n a ε.\n  Proof. rewrite view_auth_dfrac_validN. split; [naive_solver|done]. Qed.\n\n  Lemma view_auth_dfrac_op_validN n dq1 dq2 a1 a2 :\n    ✓{n} (●V{dq1} a1 ⋅ ●V{dq2} a2) ↔ ✓(dq1 ⋅ dq2) ∧ a1 ≡{n}≡ a2 ∧ rel n a1 ε.\n  Proof.\n    split.\n    - intros Hval. assert (a1 ≡{n}≡ a2) as Ha by eauto using view_auth_dfrac_op_invN.\n      revert Hval. rewrite Ha -view_auth_dfrac_op view_auth_dfrac_validN. naive_solver.\n    - intros (?&->&?). by rewrite -view_auth_dfrac_op view_auth_dfrac_validN.\n  Qed.\n  Lemma view_auth_op_validN n a1 a2 : ✓{n} (●V a1 ⋅ ●V a2) ↔ False.\n  Proof. rewrite view_auth_dfrac_op_validN. naive_solver. Qed.\n\n  Lemma view_frag_validN n b : ✓{n} (◯V b) ↔ ∃ a, rel n a b.\n  Proof. done. Qed.\n\n  Lemma view_both_dfrac_validN n dq a b :\n    ✓{n} (●V{dq} a ⋅ ◯V b) ↔ ✓dq ∧ rel n a b.\n  Proof.\n    rewrite view_validN_eq /=. apply and_iff_compat_l.\n    setoid_rewrite (left_id _ _ b). split; [|by eauto].\n    by intros [?[->%(inj to_agree)]].\n  Qed.\n  Lemma view_both_validN n a b : ✓{n} (●V a ⋅ ◯V b) ↔ rel n a b.\n  Proof. rewrite view_both_dfrac_validN. split; [naive_solver|done]. Qed.\n\n  Lemma view_auth_dfrac_valid dq a : ✓ (●V{dq} a) ↔ ✓dq ∧ ∀ n, rel n a ε.\n  Proof.\n    rewrite view_valid_eq /=. apply and_iff_compat_l. split; [|by eauto].\n    intros H n. by destruct (H n) as [? [->%(inj to_agree) ?]].\n  Qed.\n  Lemma view_auth_valid a : ✓ (●V a) ↔ ∀ n, rel n a ε.\n  Proof. rewrite view_auth_dfrac_valid. split; [naive_solver|done]. Qed.\n\n  Lemma view_auth_dfrac_op_valid dq1 dq2 a1 a2 :\n    ✓ (●V{dq1} a1 ⋅ ●V{dq2} a2) ↔ ✓(dq1 ⋅ dq2) ∧ a1 ≡ a2 ∧ ∀ n, rel n a1 ε.\n  Proof.\n    rewrite 1!cmra_valid_validN equiv_dist. setoid_rewrite view_auth_dfrac_op_validN.\n    split; last naive_solver. intros Hv.\n    split; last naive_solver. apply (Hv 0).\n  Qed.\n  Lemma view_auth_op_valid a1 a2 : ✓ (●V a1 ⋅ ●V a2) ↔ False.\n  Proof. rewrite view_auth_dfrac_op_valid. naive_solver. Qed.\n\n  Lemma view_frag_valid b : ✓ (◯V b) ↔ ∀ n, ∃ a, rel n a b.\n  Proof. done. Qed.\n\n  Lemma view_both_dfrac_valid dq a b : ✓ (●V{dq} a ⋅ ◯V b) ↔ ✓dq ∧ ∀ n, rel n a b.\n  Proof.\n    rewrite view_valid_eq /=. apply and_iff_compat_l.\n    setoid_rewrite (left_id _ _ b). split; [|by eauto].\n    intros H n. by destruct (H n) as [?[->%(inj to_agree)]].\n  Qed.\n  Lemma view_both_valid a b : ✓ (●V a ⋅ ◯V b) ↔ ∀ n, rel n a b.\n  Proof. rewrite view_both_dfrac_valid. split; [naive_solver|done]. Qed.\n\n  (** Inclusion *)\n  Lemma view_auth_dfrac_includedN n dq1 dq2 a1 a2 b :\n    ●V{dq1} a1 ≼{n} ●V{dq2} a2 ⋅ ◯V b ↔ (dq1 ≼ dq2 ∨ dq1 = dq2) ∧ a1 ≡{n}≡ a2.\n  Proof.\n    split.\n    - intros [[[[dqf agf]|] bf]\n        [[?%(discrete_iff _ _) ?]%(inj Some) _]]; simplify_eq/=.\n      + split; [left; apply: cmra_included_l|]. apply to_agree_includedN. by exists agf.\n      + split; [right; done|]. by apply (inj to_agree).\n    - intros [[[? ->]| ->] ->].\n      + rewrite view_auth_dfrac_op -assoc. apply cmra_includedN_l.\n      + apply cmra_includedN_l.\n  Qed.\n  Lemma view_auth_dfrac_included dq1 dq2 a1 a2 b :\n    ●V{dq1} a1 ≼ ●V{dq2} a2 ⋅ ◯V b ↔ (dq1 ≼ dq2 ∨ dq1 = dq2) ∧ a1 ≡ a2.\n  Proof.\n    intros. split.\n    - split.\n      + by eapply (view_auth_dfrac_includedN 0), cmra_included_includedN.\n      + apply equiv_dist=> n.\n        by eapply view_auth_dfrac_includedN, cmra_included_includedN.\n    - intros [[[dq ->]| ->] ->].\n      + rewrite view_auth_dfrac_op -assoc. apply cmra_included_l.\n      + apply cmra_included_l.\n  Qed.\n  Lemma view_auth_includedN n a1 a2 b :\n    ●V a1 ≼{n} ●V a2 ⋅ ◯V b ↔ a1 ≡{n}≡ a2.\n  Proof. rewrite view_auth_dfrac_includedN. naive_solver. Qed.\n  Lemma view_auth_included a1 a2 b :\n    ●V a1 ≼ ●V a2 ⋅ ◯V b ↔ a1 ≡ a2.\n  Proof. rewrite view_auth_dfrac_included. naive_solver. Qed.\n\n  Lemma view_frag_includedN n p a b1 b2 :\n    ◯V b1 ≼{n} ●V{p} a ⋅ ◯V b2 ↔ b1 ≼{n} b2.\n  Proof.\n    split.\n    - intros [xf [_ Hb]]; simpl in *.\n      revert Hb; rewrite left_id. by exists (view_frag_proj xf).\n    - intros [bf ->]. rewrite comm view_frag_op -assoc. apply cmra_includedN_l.\n  Qed.\n  Lemma view_frag_included p a b1 b2 :\n    ◯V b1 ≼ ●V{p} a ⋅ ◯V b2 ↔ b1 ≼ b2.\n  Proof.\n    split.\n    - intros [xf [_ Hb]]; simpl in *.\n      revert Hb; rewrite left_id. by exists (view_frag_proj xf).\n    - intros [bf ->]. rewrite comm view_frag_op -assoc. apply cmra_included_l.\n  Qed.\n\n  (** The weaker [view_both_included] lemmas below are a consequence of the\n  [view_auth_included] and [view_frag_included] lemmas above. *)\n  Lemma view_both_dfrac_includedN n dq1 dq2 a1 a2 b1 b2 :\n    ●V{dq1} a1 ⋅ ◯V b1 ≼{n} ●V{dq2} a2 ⋅ ◯V b2 ↔\n      (dq1 ≼ dq2 ∨ dq1 = dq2) ∧ a1 ≡{n}≡ a2 ∧ b1 ≼{n} b2.\n  Proof.\n    split.\n    - intros. rewrite assoc. split.\n      + rewrite -view_auth_dfrac_includedN. by etrans; [apply cmra_includedN_l|].\n      + rewrite -view_frag_includedN. by etrans; [apply cmra_includedN_r|].\n    - intros (?&->&?bf&->). rewrite (comm _ b1) view_frag_op assoc.\n      by apply cmra_monoN_r, view_auth_dfrac_includedN.\n  Qed.\n  Lemma view_both_dfrac_included dq1 dq2 a1 a2 b1 b2 :\n    ●V{dq1} a1 ⋅ ◯V b1 ≼ ●V{dq2} a2 ⋅ ◯V b2 ↔\n      (dq1 ≼ dq2 ∨ dq1 = dq2) ∧ a1 ≡ a2 ∧ b1 ≼ b2.\n  Proof.\n    split.\n    - intros. rewrite assoc. split.\n      + rewrite -view_auth_dfrac_included. by etrans; [apply cmra_included_l|].\n      + rewrite -view_frag_included. by etrans; [apply cmra_included_r|].\n    - intros (?&->&?bf&->). rewrite (comm _ b1) view_frag_op assoc.\n      by apply cmra_mono_r, view_auth_dfrac_included.\n  Qed.\n  Lemma view_both_includedN n a1 a2 b1 b2 :\n    ●V a1 ⋅ ◯V b1 ≼{n} ●V a2 ⋅ ◯V b2 ↔ a1 ≡{n}≡ a2 ∧ b1 ≼{n} b2.\n  Proof. rewrite view_both_dfrac_includedN. naive_solver. Qed.\n  Lemma view_both_included a1 a2 b1 b2 :\n    ●V a1 ⋅ ◯V b1 ≼ ●V a2 ⋅ ◯V b2 ↔ a1 ≡ a2 ∧ b1 ≼ b2.\n  Proof. rewrite view_both_dfrac_included. naive_solver. Qed.\n\n  (** Updates *)\n  Lemma view_update a b a' b' :\n    (∀ n bf, rel n a (b ⋅ bf) → rel n a' (b' ⋅ bf)) →\n    ●V a ⋅ ◯V b ~~> ●V a' ⋅ ◯V b'.\n  Proof.\n    intros Hup; apply cmra_total_update=> n [[[dq ag]|] bf] [/=].\n    { by intros []%(exclusiveN_l _ _). }\n    intros _ (a0 & <-%(inj to_agree) & Hrel). split; simpl; [done|].\n    exists a'; split; [done|]. revert Hrel. rewrite !left_id. apply Hup.\n  Qed.\n\n  Lemma view_update_alloc a a' b' :\n    (∀ n bf, rel n a bf → rel n a' (b' ⋅ bf)) →\n    ●V a ~~> ●V a' ⋅ ◯V b'.\n  Proof.\n    intros Hup. rewrite -(right_id _ _ (●V a)).\n    apply view_update=> n bf. rewrite left_id. apply Hup.\n  Qed.\n  Lemma view_update_dealloc a b a' :\n    (∀ n bf, rel n a (b ⋅ bf) → rel n a' bf) →\n    ●V a ⋅ ◯V b ~~> ●V a'.\n  Proof.\n    intros Hup. rewrite -(right_id _ _ (●V a')).\n    apply view_update=> n bf. rewrite left_id. apply Hup.\n  Qed.\n\n  Lemma view_update_auth a a' b' :\n    (∀ n bf, rel n a bf → rel n a' bf) →\n    ●V a ~~> ●V a'.\n  Proof.\n    intros Hup. rewrite -(right_id _ _ (●V a)) -(right_id _ _ (●V a')).\n    apply view_update=> n bf. rewrite !left_id. apply Hup.\n  Qed.\n  Lemma view_update_auth_persist dq a : ●V{dq} a ~~> ●V□ a.\n  Proof.\n    apply cmra_total_update.\n    move=> n [[[dq' ag]|] bf] [Hv ?]; last done. split; last done.\n    by apply (dfrac_discard_update dq _ (Some dq')).\n  Qed.\n\n  Lemma view_update_frag b b' :\n    (∀ a n bf, rel n a (b ⋅ bf) → rel n a (b' ⋅ bf)) →\n    ◯V b ~~> ◯V b'.\n  Proof.\n    rewrite !cmra_total_update view_validN_eq=> ? n [[[dq ag]|] bf]; naive_solver.\n  Qed.\n\n  Lemma view_update_dfrac_alloc dq a b :\n    (∀ n bf, rel n a bf → rel n a (b ⋅ bf)) →\n    ●V{dq} a ~~> ●V{dq} a ⋅ ◯V b.\n  Proof.\n    intros Hup. apply cmra_total_update=> n [[[p ag]|] bf] [/=].\n    - intros ? (a0 & Hag & Hrel). split; simpl; [done|].\n      exists a0; split; [done|]. revert Hrel.\n      assert (to_agree a ≼{n} to_agree a0) as <-%to_agree_includedN.\n      { by exists ag. }\n      rewrite !left_id. apply Hup.\n    - intros ? (a0 & <-%(inj to_agree) & Hrel). split; simpl; [done|].\n      exists a; split; [done|]. revert Hrel. rewrite !left_id. apply Hup.\n  Qed.\n\n  Lemma view_local_update a b0 b1 a' b0' b1' :\n    (b0, b1) ~l~> (b0', b1') →\n    (∀ n, view_rel_holds rel n a b0 → view_rel_holds rel n a' b0') →\n    (●V a ⋅ ◯V b0, ●V a ⋅ ◯V b1) ~l~> (●V a' ⋅ ◯V b0', ●V a' ⋅ ◯V b1').\n  Proof.\n    rewrite !local_update_unital.\n    move=> Hup Hrel n [[[qd ag]|] bf] /view_both_validN Hrel' [/=].\n    - rewrite right_id -Some_op -pair_op => /Some_dist_inj [/= H1q _].\n      by destruct (id_free_r (DfracOwn 1) qd).\n    - rewrite !left_id=> _ Hb0.\n      destruct (Hup n bf) as [? Hb0']; [by eauto using view_rel_validN..|].\n      split; [apply view_both_validN; by auto|]. by rewrite -assoc Hb0'.\n  Qed.\n\nEnd cmra.\n\n(** * Utilities to construct functors *)\n(** Due to the dependent type [rel] in [view] we cannot actually define\ninstances of the functor structures [rFunctor] and [urFunctor]. Functors can\nonly be defined for instances of [view], like [auth]. To make it more convenient\nto define functors for instances of [view], we define the map operation\n[view_map] and a bunch of lemmas about it. *)\nDefinition view_map {A A' B B'}\n    {rel : nat → A → B → Prop} {rel' : nat → A' → B' → Prop}\n    (f : A → A') (g : B → B') (x : view rel) : view rel' :=\n  View (prod_map id (agree_map f) <$> view_auth_proj x) (g (view_frag_proj x)).\nLemma view_map_id {A B} {rel : nat → A → B → Prop} (x : view rel) :\n  view_map id id x = x.\nProof. destruct x as [[[]|] ]; by rewrite // /view_map /= agree_map_id. Qed.\nLemma view_map_compose {A A' A'' B B' B''}\n    {rel : nat → A → B → Prop} {rel' : nat → A' → B' → Prop}\n    {rel'' : nat → A'' → B'' → Prop}\n    (f1 : A → A') (f2 : A' → A'') (g1 : B → B') (g2 : B' → B'') (x : view rel) :\n  view_map (f2 ∘ f1) (g2 ∘ g1) x\n  =@{view rel''} view_map f2 g2 (view_map (rel':=rel') f1 g1 x).\nProof. destruct x as [[[]|] ];  by rewrite // /view_map /= agree_map_compose. Qed.\nLemma view_map_ext  {A A' B B' : ofe}\n    {rel : nat → A → B → Prop} {rel' : nat → A' → B' → Prop}\n    (f1 f2 : A → A') (g1 g2 : B → B')\n    `{!NonExpansive f1, !NonExpansive g1} (x : view rel) :\n  (∀ a, f1 a ≡ f2 a) → (∀ b, g1 b ≡ g2 b) →\n  view_map f1 g1 x ≡@{view rel'} view_map f2 g2 x.\nProof.\n  intros. constructor; simpl; [|by auto].\n  apply option_fmap_equiv_ext=> a; by rewrite /prod_map /= agree_map_ext.\nQed.\nGlobal Instance view_map_ne {A A' B B' : ofe}\n    {rel : nat → A → B → Prop} {rel' : nat → A' → B' → Prop}\n    (f : A → A') (g : B → B') `{Hf : !NonExpansive f, Hg : !NonExpansive g} :\n  NonExpansive (view_map (rel':=rel') (rel:=rel) f g).\nProof.\n  intros n [o1 bf1] [o2 bf2] [??]; split; simpl in *; [|by apply Hg].\n  apply option_fmap_ne; [|done]=> pag1 pag2 ?.\n  apply prod_map_ne; [done| |done]. by apply agree_map_ne.\nQed.\n\nDefinition viewO_map {A A' B B' : ofe}\n    {rel : nat → A → B → Prop} {rel' : nat → A' → B' → Prop}\n    (f : A -n> A') (g : B -n> B') : viewO rel -n> viewO rel' :=\n  OfeMor (view_map f g).\nLemma viewO_map_ne {A A' B B' : ofe}\n    {rel : nat → A → B → Prop} {rel' : nat → A' → B' → Prop} :\n  NonExpansive2 (viewO_map (rel:=rel) (rel':=rel')).\nProof.\n  intros n f f' Hf g g' Hg [[[p ag]|] bf]; split=> //=.\n  do 2 f_equiv. by apply agreeO_map_ne.\nQed.\n\nLemma view_map_cmra_morphism {A A' B B'}\n    {rel : view_rel A B} {rel' : view_rel A' B'}\n    (f : A → A') (g : B → B') `{!NonExpansive f, !CmraMorphism g} :\n  (∀ n a b, rel n a b → rel' n (f a) (g b)) →\n  CmraMorphism (view_map (rel:=rel) (rel':=rel') f g).\nProof.\n  intros Hrel. split.\n  - apply _.\n  - rewrite !view_validN_eq=> n [[[p ag]|] bf] /=;\n      [|naive_solver eauto using cmra_morphism_validN].\n    intros [? [a' [Hag ?]]]. split; [done|]. exists (f a'). split; [|by auto].\n    by rewrite -agree_map_to_agree -Hag.\n  - intros [o bf]. apply Some_proper; rewrite /view_map /=.\n    f_equiv; by rewrite cmra_morphism_core.\n  - intros [[[dq1 ag1]|] bf1] [[[dq2 ag2]|] bf2];\n      try apply View_proper=> //=; by rewrite cmra_morphism_op.\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/algebra/view.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891451980404, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2875447912701609}}
{"text": "From stdpp Require Import gmap.\n\nFrom Perennial.Helpers Require Import Integers.\nFrom Perennial.algebra Require Import big_sepM.\nFrom Perennial.program_proof Require Import addr.addr_proof.\n\nLemma default_fmap `{Countable K} `{EqDecision K} {A B:Type} (m : option (gmap K A)) (f : A -> B) :\n  (default ∅ (fmap (fun bm => f <$> bm) m)) =\n  f <$> (default ∅ m).\nProof.\n  destruct m; simpl; eauto.\n  rewrite fmap_empty; eauto.\nQed.\n\nLemma filter_union_ignored {K A} `{EqDecision K} `{Countable K} (m m' : gmap K A) (P : K->Prop)\n                         `{! ∀ k, Decision (P k)} :\n  ( ∀ k a, m' !! k = Some a -> ¬ P k ) ->\n  filter (λ v, P (fst v)) m = filter (λ v, P (fst v)) (m' ∪ m).\nProof.\n  intros.\n  apply map_eq; intros i.\n  destruct (decide (P i)).\n  2: { rewrite !map_filter_lookup_key_notin; eauto. }\n  rewrite map_filter_lookup_key_in; eauto.\n  rewrite map_filter_lookup_key_in; eauto.\n  rewrite lookup_union_r; eauto.\n  destruct (m' !! i) eqn:He; eauto.\n  exfalso. eapply H1; eauto.\nQed.\n\nLemma filter_union_gmap_addr_by_block_ignored {A} (m m' : gmap addr A) (P : u64->Prop)\n                         `{! ∀ k, Decision (P k)} :\n  ( ∀ k a, m' !! k = Some a -> ¬ P (fst k) ) ->\n  filter (λ v, P (fst v)) (gmap_addr_by_block m) = filter (λ v, P (fst v)) (gmap_addr_by_block (m' ∪ m)).\nProof.\n  intros.\n  apply map_eq; intros i.\n  destruct (decide (P i)).\n  2: { rewrite ?map_filter_lookup_key_notin; eauto. }\n  rewrite map_filter_lookup_key_in; eauto.\n  rewrite map_filter_lookup_key_in; eauto.\n  rewrite /gmap_addr_by_block.\n  destruct (gmap_curry m !! i) eqn:He.\n  2: {\n    symmetry.\n    erewrite lookup_gmap_curry_None in He.\n    erewrite lookup_gmap_curry_None. intros j. specialize (He j).\n    specialize (H0 (i, j)). simpl in *.\n    rewrite lookup_union_r; eauto.\n    destruct (m' !! (i, j)) eqn:Hee; eauto. exfalso. eapply H0; eauto.\n  }\n\n  destruct (gmap_curry (m' ∪ m) !! i) eqn:He2.\n  2: {\n    exfalso.\n    erewrite lookup_gmap_curry_None in He2.\n    apply gmap_curry_non_empty in He as He'. apply map_choose in He'. destruct He' as [j [x He']].\n    specialize (He2 j). rewrite lookup_union_r in He2.\n    2: { destruct (m' !! (i, j)) eqn:Hee; eauto. exfalso. eapply H0; eauto. }\n    rewrite -lookup_gmap_curry in He2. rewrite He /= in He2. congruence.\n  }\n\n  f_equal.\n  apply map_eq.\n  intros j.\n\n  replace (g !! j) with (m !! (i, j)).\n  2: { rewrite -lookup_gmap_curry. rewrite He. done. }\n\n  replace (g0 !! j) with ((m' ∪ m) !! (i, j)).\n  2: { rewrite -lookup_gmap_curry. rewrite He2. done. }\n\n  rewrite lookup_union_r; eauto.\n  destruct (m' !! (i, j)) eqn:Hee; eauto. exfalso. eapply H0; eauto.\nQed.\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/obj/map_helpers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.2875447842241298}}
{"text": "Require Import CSPEC.\nRequire Import MailServerAPI.\nRequire Import MailServerLockAbsAPI.\n\nModule MailServerLockAbsImpl' <:\n  HLayerImplAbsT MailServerOp\n    MailServerLockAbsState MailServerLockAbsAPI\n    MailServerState MailServerAPI.\n\n  Import MailServerLockAbsState.\n\n  Definition absR (s1 : MailServerLockAbsState.State) (s2 : MailServerState.State) :=\n    MailServerLockAbsState.maildir s1 = s2.\n\n  Hint Extern 1 (MailServerAPI.step _ _ _ _ _ _) => econstructor.\n\n  Theorem absR_ok :\n    op_abs absR MailServerLockAbsAPI.step MailServerAPI.step.\n  Proof.\n    unfold op_abs; intros.\n    unfold absR in *.\n    inversion H0; clear H0; subst; repeat sigT_eq.\n    all: eauto.\n  Qed.\n\n  Definition initP_map (s1: MailServerLockAbsState.State) : {s2:MailServerState.State | initP s1 -> absR s1 s2 /\\ MailServerState.initP s2}.\n    exists (maildir s1).\n    unfold initP, absR, MailServerState.initP; eauto.\n  Defined.\n\nEnd MailServerLockAbsImpl'.\n\nModule MailServerLockAbsImpl :=\n  HLayerImplAbs MailServerOp\n    MailServerLockAbsState MailServerLockAbsAPI\n    MailServerState MailServerAPI\n    MailServerLockAbsImpl'.\n\nModule MailServerLockAbsImplH' :=\n  LayerImplAbsHT\n    MailServerOp\n    MailServerLockAbsState MailServerLockAbsAPI\n    MailServerState MailServerAPI\n    MailServerLockAbsImpl'\n    UserIdx.\n\nModule MailServerLockAbsImplH :=\n  LayerImplAbs MailServerHOp\n    MailServerLockAbsHState MailServerLockAbsHAPI\n    MailServerHState        MailServerHAPI\n    MailServerLockAbsImplH'.\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/MailServerLockAbsImpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.2875447771780986}}
{"text": "Require Import RGref.DSL.Core.\nRequire Export RGref.DSL.LinearEnv.\n\n(** * A Monad for RGref programs *)\n\n(* TODO: Should probably be a type-class *)\nInductive splits : Set -> Set -> Set -> Prop :=\n  | natsp : splits nat nat nat\n  | boolsp : splits bool bool bool\n  | unitsp : splits unit unit unit\n  | pairsp : forall A A' A'' B B' B'', \n               splits A A' A'' ->\n               splits B B' B'' ->\n               splits (A*B) (A'*B') (A''*B'')\n  | listsp : forall A A' A'', splits A A' A'' -> splits (list A) (list A') (list A'')\n  | funsp : forall (A B:Set),\n               splits (forall x:A, B) (forall x:A, B) (forall x:A, B)\n. \nInductive rgref (Γ:tyenv) (T:Set) (Γ':tyenv) : Type :=\n  | mkRGR :  envlist Γ -> T -> envlist Γ' -> (heap -> heap) -> rgref Γ T Γ'.\n\n(* TODO: Really bind should be doing some kind of framing on environments, a subenv type thing. *)\nProgram Definition rgref_bind {Γ Γ' Γ'':tyenv}{t t':Set} (a:rgref Γ t Γ') (b:t->rgref Γ' t' Γ'') : rgref Γ t' Γ'' :=\n  match a with\n  | mkRGR _ va _ ha =>\n    match b va with\n    | mkRGR _ vb _ hb =>\n      mkRGR _ _ _ _ vb _ (fun h => hb (ha h))\n    end\n  end.\n\n(* TODO: To actually define this properly, bind needs to do framing and ret should use the empty env. *)\nAxiom rgret : forall {Γ:tyenv}{A:Set}(a:A), rgref Γ A Γ .\n(*  := mkRGR Γ A Γ e a e (fun h=>h).*)\n\nAxiom dropvar : forall {Γ} (v:var) (t:Set) (tm:tymember v t Γ), rgref Γ unit (tyrem tm).\n\n(** * Higher-Order Safety *)\n(** The following typeclass network prohibits latent dereference expressions in the heap, alleviating the need for\n    extra caution in proof principles, and removing the need for the type-sensitive semantics in the PLDI'13 paper.\n    It is the subject of a submission to POPL'14. *)\n(* Some background stuff... *)\n  Instance n2n : ImmediateReachability (nat -> nat) := { imm_reachable_from_in := fun _ _ _ _ _ _ => False }.\n  Print Containment.\n  Instance n2nc : Containment (nat -> nat) := {contains := fun _ => False}.\n\n  Instance n2n' : ImmediateReachability (forall x : nat, (fun _ : nat => nat) x) := { imm_reachable_from_in := fun _ _ _ _ _ _ => False }.\n\n\nClass Library {T:Type}(o:T) : Prop := {}.\nClass Safe {T:Type}(t:T) : Prop := {}.\nClass SafeType (T:Type) : Prop := {}.\nInstance safe_lib {T:Type}{o:T}`{Library T o} : Safe o.\nInstance val_of_safe_type {T:Type}`{SafeType T}(t:T) : Safe t.\nInstance imp_of_safe_type {T:Set}`{SafeType T}{Γ}(t : rgref Γ T Γ) : Safe t.\nInstance puretype_safe {T:Set}`{pure_type T} : SafeType T.\n\nClass ESafe (n:nat){T:Type}(t:T) : Prop := { force_proof : False }.\nInstance safe_esafe {T:Type}(t:T){n:nat}`{Safe _ t} : ESafe n t. Admitted.\nInstance esafe_ind {A:Type}{B:A->Type}{n:nat}(f:forall x:A, B x)`{forall a:A, Safe a -> ESafe n (f a)} : ESafe (S n) f.\nAdmitted.\nInstance deref_esafe {A B:Set}{P R G}`{rel_fold A}(r:ref{A|P}[R,G]){a b} : ESafe 0 (@deref A B _ P R G a b r).\nAdmitted.\nInstance esafe_app {A:Type}{B:A->Type}(f:forall x:A, B x)(a:A){n:nat}`{ESafe (S n) _ f}`{ESafe 0 _ a} : ESafe n (f a).\nAdmitted.\n\nLtac solve_applications :=\n  match goal with\n  | [ |- @ESafe _ _ (?g _ _ _) ] => eapply @esafe_app with (f := g _ _)\n  | [ |- @ESafe _ _ (?g _ _) ] => eapply @esafe_app with (f := g _)\n  | [ |- @ESafe _ _ (?g _) ] => eapply @esafe_app with (f := g)\n  end; eauto with typeclass_instances.\n\n\n\n\n(** The core problem with folding here is that we want the user (and automated provers!) to see the same dereference on either side of\n    G's state.  But G applies to elements of A, not [R,G]>>A.  We could introduce an internal \"cheat_deref\" that skipped\n    folding, but then the two sides aren't equal, and many automated tactics that treat !e as essentially an uninterpreted\n    symbol fail because the pre and post values use different uninterpreted symbols.  Another alternative is to \n    ALSO add an axiom relating the behaviors of deref and cheat_deref, but this will run into serious issues with\n    polymorphism over A and [R,G]>>A.  John Major equality might handle this okay, but I haven't had much success using\n    JMeq for anything yet.\n\n    A slightly different approach would be to have a folding version of heap-specific dereference, and do the guarantee\n    validity check in a context with the assumption that ∀ e, !e = h[e]>> (where h[x]>> is the folding specific-heap read).\n    This still runs into some JMeq issues (e.g. ∀ x h, JMeq h[x] h[x]>>), but they might be easier to deal with.\n\n    A less serious (easier to solve) version of this occurs with reflexivity checks on G for reads.  Still need two symbols,\n    one for devs that checks reflexivity on reads, the other for metatheory proofs like satisfying G, with either an axiom\n    or per-context assumption that their results are equal (eq equal, since the types are equal, unless we're also solving\n    the general folding issue at the same time).\n\n    In practice the folding shouldn't matter too much (for pure types, folding is identity), but we need to support it\n    in general.  Eventually both store and write will need to take rel_fold A instances so they can use them in proofs\n    and obligation statements.\n*)\n(** TODO: Fix store to work properly with the linear environment. *)\n(*Axiom store : forall {Γ:dyn_env}{A:Set}{P R G}(x:var)(e:A)\n                 {varty:exists ptr, lookup x Γ = Some (existT (fun x:Set=>x) (ref{A|P}[R,G]) ptr)}\n                 {guar:forall h l, lookup x Γ = Some (existT (fun x:Set=>x) (ref{A|P}[R,G]) l) ->\n                   G (!l) e h (heap_write l e h)}\n                 {pres:(forall h (l:ref{A|P}[R,G]), P (!l) h -> P e (heap_write l e h))}\n                 , rgref Γ unit Γ.*)\nProgram Axiom write' : forall {Γ:tyenv}{A:Set}`{rel_fold A}{P R G}`{hreflexive G}(x:ref{A|P}[R,G])(e:A)`{ESafe 0 A e}\n                      (meta_x_deref:A) (meta_e_fold:A) \n                      (** These meta args are notationally expanded x and e using the identity relation folding *)\n                 (*{guar:forall h, G (!x) e h (heap_write x e h)} *)\n                 {guar:forall h, (forall A (fa:rel_fold A), fa = meta_fold) -> G (meta_x_deref) e h (heap_write x e h)}\n                 (** temporarily not using meta_e_fold... the cases where I needed the \"nop\" behavior are once where the types are actually equal *)\n                 {pres:(forall h, P meta_x_deref h -> P meta_e_fold (heap_write x meta_e_fold h))}\n                 , rgref Γ unit Γ.\nNotation \"[ x ]:= e\" := (@write' _ _ _ _ _ _ _ x e _ ({{{!x}}}) ({{{e}}}) _ _) (at level 70).\n(** TODO: heap writes that update the predicate.  Because of the monadic style, we'll actually\n   need a new axiom and syntax support for this, to rebind the variable at the strengthened type *)\n\n(** Interactions between pure terms and monadic terms *)\n(** valueOf should be treated as roughly a more serious version of unsafePerformIO;\n    it's a coreturn like the latter, but should actually never be written in user programs! *)\nProgram Axiom valueOf : forall {Γ Γ'}{A:Set}, envlist Γ -> heap -> rgref Γ A Γ' -> A.\n(** pureApp is essentially based on valueOf... Technically this is weaker than what's in the paper,\n    since dependently-typed pure functions are allowed if the instantiation of the range type is\n    closed, but right now I don't need the expressiveness and can't figure out how to properly treat the\n    dependency in binding B. \n    \n    I supposed technically this makes rgref an indexed functor (in the Haskell sense), and with a\n    small tweak, an applicative functor if we need it. *)\nProgram Axiom pureApp : forall {Γ Γ'}{A:Set}`{splits A A A}{B:Set}, (A->B) -> rgref Γ A Γ' -> rgref Γ B Γ'.\n\n(** This is just strong enough to get the race-free counter example to go through... Need to strengthen this at some point. *)\nAxiom weak_pureApp_morphism :\n  forall Γ Γ' τ env h (e:rgref Γ τ Γ') (sp:splits τ τ τ) (f:τ->τ) (P:τ->τ->Prop),\n    (forall v:τ, P v (f v)) ->\n    P (valueOf Γ Γ' τ env h e) (valueOf Γ Γ' τ env h (pureApp Γ Γ' τ sp τ f e)).\n\n(* Impure read expression (using a direct ref value) *)\nProgram Axiom read_imp : forall {Γ}{A B:Set}`{rel_fold A}{P R G}`{hreflexive G}`{rgfold R G = B}(x:ref{A|P}[R,G]), rgref Γ B Γ.\n\n(* Writing with an impure source expression (and direct ref value) *)\nProgram Axiom write_imp_exp : forall {Γ Γ'}{A:Set}`{rel_fold A}{P R G}`{hreflexive G}(x:ref{A|P}[R,G])(e:rgref Γ A Γ')\n                              `{ESafe 0 _ e}\n                              (meta_x_deref:rgref Γ A Γ') (meta_e_fold:rgref Γ A Γ')\n                              {guar:forall h env, G (valueOf _ _ _ env h meta_x_deref) (valueOf _ _ _ env h e) h (heap_write x (valueOf _ _ _ env h e) h)}\n                              {pres:(forall h env, P (valueOf _ _ _ env h meta_x_deref) h -> P (valueOf _ _ _ env h meta_e_fold) (heap_write x (valueOf _ _ _ env h meta_e_fold) h))}\n                              , rgref Γ unit Γ'.\nNotation \"[[ x ]]:= e\" := (@write_imp_exp _ _ _ _ _ _ _ _ x e ({{{read_imp x}}}) ({{{e}}}) _ _) (at level 70).\n\nDefinition locally_const {A:Set} (R:hrel A) := forall a a' h h', R a a' h h' -> a=a'.\n\n\nAxiom alloc : forall {Γ}{T:Set}{RT:ImmediateReachability T}{CT:Containment T}{FT:rel_fold T} P R G (e:T), \n                ESafe 0 e ->\n                stable P R ->        (* predicate is stable *)\n                (forall h, P e h) -> (* predicate is true *)\n                precise_pred P ->    (* P precise *)\n                precise_rel R ->     (* R precise *)\n                precise_rel G ->     (* G precise *)\n                rgref Γ (ref{T|P}[R,G]) Γ.\nNotation \"'Alloc' e\" := (alloc _ _ _ e _ _ _ _ _ _) (at level 70).\n(** Sometimes it is useful to refine P to give equality with the allocated value, which\n    propagates assumptions and equalities across \"statements.\" *)\nAxiom alloc' : forall {Γ}{T:Set}{RT:ImmediateReachability T}{CT:Containment T}{FT:rel_fold T} P R G (e:T) (meta_e:T),\n                ESafe 0 e ->\n                stable P R ->        (* predicate is stable *)\n                (forall h, P e h) -> (* predicate is true *)\n                precise_pred P ->    (* P precise *)\n                precise_rel R ->     (* R precise *)\n                precise_rel G ->     (* G precise *)\n                 rgref Γ (ref{T|P ⊓ (fun t=>fun h=> (locally_const R -> t=meta_e))}[R,G]) Γ.\nNotation \"Alloc! e\" := (alloc' _ _ _ e ({{{e}}}) _ _ _ _ _ _) (at level 70).\n                                 \n\n  \nNotation \"x <- M ; N\" := (rgref_bind M (fun x => N)) (at level 49, right associativity).\n\nAxiom varalloc' : forall {Γ}{T:Set}{RT:ImmediateReachability T}{CT:Containment T}{FT:rel_fold T} P R G (v:var) (e:T) (meta_e:T),\n                ESafe 0 e ->\n                stable P R ->        (* predicate is stable *)\n                (forall h, P e h) -> (* predicate is true *)\n                precise_pred P ->    (* P precise *)\n                precise_rel R ->     (* R precise *)\n                precise_rel G ->     (* G precise *)\n                 rgref Γ unit (v:ref{T|P ⊓ (fun t=>fun h=> (locally_const R -> t=meta_e))}[R,G],Γ).\nNotation \"VarAlloc! v e\" := (varalloc' _ _ _ v e ({{{e}}}) _ _ _ _ _ _) (at level 70).\n\n\n\n(** ** Fixpoints *)\n(** Possibly non-terminating fixpoint combinators. *)\n(* TODO: This is only a first cut, and doesn't allow polymorphic recursion. *)\nAxiom RGFix : forall { Γ Γ' }(t t':Set), ((t -> rgref Γ t' Γ') -> (t -> rgref Γ t' Γ')) -> t -> rgref Γ t' Γ'.\nAxiom RGFix2 : forall { Γ Γ' }(t t2 t':Set), ((t -> t2 -> rgref Γ t' Γ') -> (t -> t2 -> rgref Γ t' Γ')) -> t -> rgref Γ t' Γ'.\nAxiom RGFix3 : forall { Γ Γ' }(t t2 t3 t':Set), ((t -> t2 -> t3 -> rgref Γ t' Γ') -> (t -> t2 -> t3 -> rgref Γ t' Γ')) -> t -> rgref Γ t' Γ'.\nAxiom RGFix4 : forall { Γ Γ' }(t t2 t3 t4 t':Set), ((t -> t2 -> t3 -> t4 -> rgref Γ t' Γ') -> (t -> t2 -> t3 -> t4 -> rgref Γ t' Γ')) -> t -> rgref Γ t' Γ'.\n", "meta": {"author": "csgordon", "repo": "rgref", "sha": "9f66be539d584b0a1ca18f67a13c07dc6b4d310a", "save_path": "github-repos/coq/csgordon-rgref", "path": "github-repos/coq/csgordon-rgref/rgref-9f66be539d584b0a1ca18f67a13c07dc6b4d310a/RGref/DSL/Monad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.2875447771780986}}
{"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 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 valid.\nFrom CoqCat Require Import covering.\nRequire Import Classical_Prop.\nFrom CoqCat Require Import drf.\nFrom CoqCat Require Import racy.\nImport OEEvt.\nSet Implicit Arguments.\n\nModule CritSC (A1 A2: Archi) (dp:Dp).\n\nModule Wk := (*Hierarchy.*)Weaker A1 A2 dp.\nImport Wk.\nHypothesis wk : weaker.\n\nModule VA2 := Valid A2n dp.\nImport VA2. Import VA2.ScAx.\nModule Covering := Covering A1 A2n dp.\nImport Covering.\n\nSet Implicit Arguments.\n\nDefinition rel_inter A (r1 r2 : Rln A) :=\n  fun x => fun y => r1 x y /\\ r2 x y.\n\nDefinition cycle_sym A (sigma : Rln A) :=\n  forall x y, udr sigma x -> udr sigma y ->\n  sigma x y -> sigma y x.\nDefinition cycle_trans_tot A (sigma : Rln A) :=\n  forall x y, udr sigma x -> udr sigma y ->\n    tc (sigma) x y.\nDefinition non_empty A (sigma : Rln A) :=\n  (exists x, exists y, sigma x y).\nDefinition cycle A (sigma : Rln A) :=\n  cycle_sym sigma /\\\n  cycle_trans_tot sigma /\\ non_empty sigma.\nLtac destruct_cycle H :=\n  destruct H as [Hsym [Htot Hnemp]].\nLemma cycle_implies_nac :\n  forall A (sigma:Rln A),\n  cycle sigma -> ~(acyclic sigma).\nProof.\nunfold acyclic;\nintros A sigma Hcy Hn.\ndestruct_cycle Hcy.\ndestruct Hnemp as [x [y Hxy]].\nunfold cycle_sym in Hsym.\nassert (udr sigma x) as Hudrx.\n  left; exists y; auto.\nassert (udr sigma y) as Hudry.\n  right; exists x; auto.\ngeneralize (Hsym x y Hudrx Hudry Hxy); intro Hyx.\nassert (tc (sigma) x x) as Hc.\n  apply trc_ind with y; apply trc_step; auto.\ngeneralize (Hn x); intro; contradiction.\nQed.\n\nDefinition conflict E :=\n  fun e1 => fun e2 => events E e1 /\\ events E e2 /\\\n    loc e1 = loc e2 /\\ proc_of e1 <> proc_of e2 /\\ (writes E e1 \\/ writes E e2).\n\nDefinition sigma_wf E sigma :=\n  rel_incl sigma (tc (rel_union (A2n.ppo E) (rel_inter sigma (conflict E)))).\n\nDefinition crit_cy E sigma :=\n  sigma_wf E sigma /\\ ~ acyclic sigma /\\\n  acyclic (rel_union (rel_inter sigma (conflict E)) (rel_union (A1.ppo E) (pio_llh E))) /\\\n  (forall x y, sigma x y -> A2n.ppo E x y ->\n  ~(exists z, (z <> y /\\ sigma x z /\\ A2n.ppo E x z /\\ A2n.ppo E z y)) /\\ loc x <> loc y) /\\\n  (forall x y, sigma x y -> conflict E x y ->\n    (((reads E x /\\ writes E y) \\/\n      (writes E x /\\ reads E y) \\/\n      (writes E x /\\ writes E y)) /\\\n      ~(exists z, conflict E z x /\\ tc sigma x z /\\ tc sigma z y)) \\/\n      (reads E x /\\ reads E y /\\ exists e, writes E e /\\ tc sigma x e /\\ tc sigma e y /\\\n       ~(exists z, conflict E z x /\\ tc sigma x z /\\ tc sigma z y))).\n\nDefinition mhbd E X :=\n  fun x => fun y => (A2nWmm.mhb E X x y) /\\ proc_of x <> proc_of y.\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.\n\nDefinition sigma_wf_or E X sigma :=\n  rel_incl sigma (tc (rel_union (mhbd E X) (A2.ppo E))).\n\nDefinition crit_cy_or E X sigma :=\n  sigma_wf_or E X sigma /\\\n  crit_cy E sigma.\nAxiom exists_crit_cy_or : forall E X x,\n  tc (A2nWmm.ghb E X) x x ->\n  exists sigma, crit_cy_or E X sigma.\n\nModule C <: Compete.\nParameter competing : Event_struct -> Execution_witness -> Rln Event.\nHypothesis 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.\nParameter s : Event_struct -> Execution_witness -> Rln Event.\nDefinition covered E X r :=\n  forall e1 e2, (competing E X e1 e2) -> (r E X e1 e2 \\/ r E X e2 e1).\nDefinition covering s :=\n  forall E X, well_formed_event_structure E ->\n    A1Wmm.valid_execution E X ->\n    covered E X s -> acyclic (A2nWmm.ghb E X).\n\nDefinition cns E X :=\n  fun e1 => fun e2 => competing E X e1 e2 /\\ ~ (s E X e1 e2 \\/ s E X e2 e1).\nHypothesis competing_irr : forall E X,\n  well_formed_event_structure E ->\n    A1Wmm.valid_execution E X ->\n  ~ (exists z, competing E X z z).\nHypothesis competing_not_po :\n  forall E X x y, well_formed_event_structure E ->\n  A1Wmm.valid_execution E X ->\n  competing E X x y -> ~ (po_iico E y x).\nHypothesis covering_s : covering s.\nHypothesis wf :\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  ~ (s E X x y \\/ s E X y x) ->\n  (exists Y, A2nWmm.valid_execution E Y /\\\n  competing E Y x y /\\ ~ (s E Y x y \\/ s E Y y x)).\nEnd C.\n\nModule Cm <: Compete.\nDefinition competing E X :=\n  fun e1 e2 => C.competing E X e1 e2 /\\\n    (exists sigma, crit_cy E sigma /\\ sigma e1 e2).\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 [Hc ?].\napply C.compete_in_events with X; auto.\nQed.\n\nDefinition s E X :=\n  fun e1 e2 => C.s E X e1 e2.\nDefinition covered E X r :=\n  forall e1 e2, (competing E X e1 e2) -> (r E X e1 e2 \\/ r E X e2 e1).\nDefinition covering s :=\n  forall E X, well_formed_event_structure E ->\n    A1Wmm.valid_execution E X ->\n    covered E X s -> acyclic (A2nWmm.ghb E X).\n\nDefinition cns E X :=\n  fun e1 => fun e2 => competing E X e1 e2 /\\ ~ (s E X e1 e2 \\/ s E X e2 e1).\nLemma competing_irr : forall E X,\n  well_formed_event_structure E ->\n    A1Wmm.valid_execution E X ->\n  ~ (exists z, competing E X z z).\nProof.\nintros E X Hwf Hv1 [z [Hz ?]].\nassert (exists z, C.competing E X z z) as Hc.\n  exists z; auto.\napply (C.competing_irr Hwf Hv1 Hc).\nQed.\nLemma competing_not_po :\n  forall E X x y, well_formed_event_structure E ->\n  A1Wmm.valid_execution E X ->\n  competing E X x y -> ~ (po_iico E y x).\nProof.\nintros E X x y Hwf Hv1 [Hc ?].\napply (C.competing_not_po Hwf Hv1 Hc).\nQed.\n\nLemma mhbd_in_conflict :\n  forall E X,\n  well_formed_event_structure E ->\n  write_serialization_well_formed (events E) (ws X) /\\\n  rfmaps_well_formed E (events E) (rf X) ->\n  rel_incl (mhbd E X) (conflict E).\nProof.\nintros E X Hwf Hs x y [? ?].\ngeneralize (A2nBasic.mhb_in_com E X x y H); intro Hhb.\nsplit; [|split; [|split; [|split]]]; auto.\n  change (events E x) with (In _ (events E) x); apply A2nBasic.hb_dom_in_evts with X y; auto.\n  change (events E y) with (In _ (events E) y); apply A2nBasic.hb_ran_in_evts with X x; auto.\n  apply A2nBasic.com_implies_same_loc with E X; auto.\n  apply A2nBasic.com_implies_writes with X; auto.\nQed.\n\nSet Implicit Arguments.\nLemma nac_incl :\n  forall A (d s s' : Rln A),\n  rel_incl s' s ->\n  ~ acyclic (rel_union d s') ->\n  ~ acyclic (rel_union d s).\nProof.\nunfold not; unfold acyclic;\nintros A d s1 s1' Hi Hnac Hc.\napply Hnac; intros x Hx.\nassert (tc (rel_union d s1) x x) as Hin.\n  generalize Hx; apply tc_incl; intros e1 e2 H12.\n  inversion H12; [left | right; apply Hi]; auto.\n  generalize (Hc x); intro; contradiction.\nQed.\nLemma nac_incl2 :\n  forall A (s s' : Rln A),\n  rel_incl s' s ->\n  ~ acyclic s' ->\n  ~ acyclic s.\nProof.\nunfold not; unfold acyclic;\nintros A s1 s1' Hi Hnac Hc.\napply Hnac; intros x Hx.\nassert (tc s1 x x) as Hin.\n  generalize Hx; apply tc_incl; intros e1 e2 H12.\n  apply Hi; auto.\n  generalize (Hc x); intro; contradiction.\nQed.\nLemma not_forall_exists_tc :\n  forall A (s : Rln A), ~(forall x, ~ tc s x x) ->\n  exists x, tc s x x.\nProof.\nintros A s1 Hn.\ngeneralize (excluded_middle (exists x, tc s1 x x)); intro Hor;\n  inversion Hor; auto.\nassert (forall x, ~ tc s1 x x) as Hc.\n  intro x.\n  generalize (excluded_middle (tc s1 x x)); intro Hor2;\n  inversion Hor2; auto.\n  assert (exists x, tc s1 x x) as Hc.\n    exists x; auto.\n  contradiction.\ncontradiction.\nQed.\nUnset Implicit Arguments.\n\nHypothesis covering_s :\n  forall E X, well_formed_event_structure E ->\n    A1Wmm.valid_execution E X ->\n    covered E X s -> acyclic (A2nWmm.ghb E X).\n\nLemma wf :\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  ~ (s E X x y \\/ s E X y x) ->\n  (exists Y, A2nWmm.valid_execution E Y /\\\n  competing E Y x y /\\ ~ (s E Y x y \\/ s E Y y x)).\nProof.\nintros E X x y Hwf Hv1 [Hc [cy [Hmcy Hcy]]] Hns.\nunfold s in Hns.\ngeneralize (C.wf Hwf Hv1 Hc Hns);\n  intros [Y [Hv2 [HcY HnsY]]].\nexists Y; split; [|split]; auto.\nsplit; auto.\nexists cy; split; auto.\nQed.\n\nModule DrfG := DataRaceFree A1 A2 dp.\n\nModule DrfMin (HB : DrfG.HappensBefore).\n\nModule Drf := DrfG.Drf0 (HB).\n\nHypothesis s_com :\n  forall E X x y,\n  s E X x y -> ~(com E X y x).\nHypothesis s_po :\n  forall E X,\n  acyclic (rel_union (s E X) (po_iico E)).\n\nLemma tc_mhbd_ppo2_in_s_ppo2 :\n  forall E X x y,\n  well_formed_event_structure E ->\n  A1Wmm.valid_execution E X ->\n  Drf.covered E X s ->\n  tc (rel_union (mhbd E X) (A2.ppo E)) x y ->\n  tc (rel_union (s E X) (A2.ppo E)) x y.\nProof.\nintros E X e1 e2 Hwf Hv1 Hcov; apply tc_incl.\nintros x y Hxy.\n      assert ( write_serialization_well_formed (events E) (ws X) /\\\n  rfmaps_well_formed E (events E) (rf X)) as Hs.\n        split; split; destruct_valid Hv1; auto.\n\ninversion Hxy as [Hc | Hppo2]; [left | right]; auto.\n\nassert (Drf.competing E X x y) as Hcomp.\n\n  destruct Hc as [Hmhbdxy ?]; split; [|split; [|split; [|split]]]; auto.\n\n      assert (mhbd E X x y) as Hmhbd.\n        split; auto.\n      generalize (mhbd_in_conflict Hwf Hs Hmhbd); intro Hcxy.\n      destruct Hcxy; auto.\n\n      assert (mhbd E X x y) as Hmhbd.\n        split; auto.\n      generalize (mhbd_in_conflict Hwf Hs Hmhbd); intro Hcxy.\n      destruct Hcxy as [? [? ?]]; auto.\n\n      assert (mhbd E X x y) as Hmhbd.\n        split; auto.\n      generalize (mhbd_in_conflict Hwf Hs Hmhbd); intro Hcxy.\n      destruct Hcxy as [? [? [? ?]]]; auto.\n\n      assert (mhbd E X x y) as Hmhbd.\n        split; auto.\n      generalize (mhbd_in_conflict Hwf Hs Hmhbd); intro Hcxy.\n      destruct Hcxy as [? [? [? [? ?]]]]; auto.\n\n    destruct Hs as [? [? [? ?]]]; auto.\n\ngeneralize (Hcov x y Hcomp); intro Hor; inversion Hor; auto.\n\ninversion Hxy as [Hmhbd | Hppo].\n  destruct Hmhbd as [Hmhbdxy ?].\n  assert (com E X x y) as Hhb.\n    apply A2nBasic.mhb_in_com; auto.\n  generalize (s_com E X y x H3); intro; contradiction.\n\n  assert (exists x, tc (rel_union (s E X) (po_iico E)) x x) as Hcy.\n    exists x; apply trc_ind with y; apply trc_step;\n      [right | left]; auto.\n    apply A2.ppo_valid; auto.\n  destruct Hcy as [e Hcy].\n  generalize (s_po E X); intro Hac.\n  generalize (Hac e Hcy); intro Ht; inversion Ht.\nQed.\n\nLemma tc_cy_in_tc :\n  forall E X cy,\n  rel_incl cy (tc (rel_union (s E X) (A2.ppo E))) ->\n  rel_incl (tc cy) (tc (rel_union (s E X) (A2.ppo E))).\nProof.\nintros E X cy Hi x y Hxy.\ninduction Hxy.\n  apply Hi; auto.\n  apply trc_ind with z; auto.\nQed.\n\nLemma min_covered_implies_no_min_cy :\n  forall E X, well_formed_event_structure E ->\n  A1Wmm.valid_execution E X ->\n  Drf.covered E X s ->\n  ~(exists cy, crit_cy_or E X cy).\nProof.\nintros E X Hwf Hv1 Hc [cy [Hicy [? [Hnac ?]]]].\nassert (rel_incl cy (tc (rel_union (s E X) (A2.ppo E)))) as Hi.\n  intros x y Hxy; generalize (Hicy x y Hxy); intro Htc.\n    apply tc_mhbd_ppo2_in_s_ppo2; auto.\nassert (~(acyclic (rel_union (s E X) (po_iico E)))) as Hco.\n  apply nac_incl2 with (rel_union (s E X) (A2.ppo E)).\n    intros e1 e2 H12; inversion H12; [left | right]; auto.\n    apply A2.ppo_valid; auto.\n  unfold acyclic; intros Hex.\n  generalize (not_forall_exists_tc Hnac); intros [e He].\n  assert (rel_incl (tc cy) (tc (rel_union (s E X) (A2.ppo E)))) as Hitc.\n    apply tc_cy_in_tc; auto.\n  generalize (Hitc e e He); intro Hxx.\n  generalize (Hex e); intro; contradiction.\ngeneralize (s_po E X); intro; contradiction.\nQed.\n\nLemma covering_s :\n  forall E X, well_formed_event_structure E ->\n    A1Wmm.valid_execution E X ->\n    Drf.covered E X s -> acyclic (A2nWmm.ghb E X).\nProof.\nintros E X Hwf Hv1 Hc z Hz.\ngeneralize (exists_crit_cy_or E X Hz);\nintros [cy Hcy].\nassert (exists cy, crit_cy_or E X cy) as Hex.\n  exists cy; auto.\ngeneralize (min_covered_implies_no_min_cy E X Hwf Hv1 Hc); intro Hnex.\ncontradiction.\nQed.\n\nEnd DrfMin.\n\nModule Racy := Racy A1 A2 dp.\nModule RacyMin (SN:Racy.SafetyNet).\n\nModule R := Racy.Barriers (SN).\n\nDefinition AC X s :=\n  forall (x z y:Event), rf_sub X x z /\\ s z y -> s x y.\nHypothesis s_ghb :\n  forall E X,\n  well_formed_event_structure E ->\n  A1Wmm.valid_execution E X ->\n  acyclic (rel_union (s E X) (A1bWmm.ghb E X)).\nHypothesis s_ppo2 :\n  forall E X,\n  well_formed_event_structure E ->\n  acyclic (rel_union (s E X) (A2n.ppo E)).\nHypothesis s_ac : forall E X, AC X (s E X).\n\nLemma tc_cy_in_tc :\n  forall E X cy,\n  rel_incl cy (tc (rel_union (mhbd E X) (A2.ppo E))) ->\n  rel_incl (tc cy) (tc (rel_union (mhbd E X) (A2.ppo E))).\nProof.\nintros E X cy Hi x y Hxy.\ninduction Hxy; auto.\napply trc_ind with z; auto.\nQed.\n\nLemma tc_mhbd_ppo2_in_mhb_ppo2 :\n  forall E X x y,\n  tc (rel_union (mhbd E X) (A2.ppo E)) x y ->\n  tc (rel_union (A2nBasic.AWmm.mhb E X) (A2n.ppo E)) x y.\nProof.\nintros E X x y Hxy; induction Hxy as [x y Hu |].\n  apply trc_step; inversion Hu as [Hmhbd | Hppo]; [left | right]; auto.\n    destruct Hmhbd; auto.\n  apply trc_ind with z; auto.\nQed.\n\nLemma ppo2_in_ghb1 :\n  forall E X x y,\n  well_formed_event_structure E ->\n  R.covered E X s ->\n  A2n.ppo E x y ->\n  rel_union (A1bWmm.ghb E X) (s E X) x y.\nProof.\nintros E X x y Hwf Hfb Hxy.\n  generalize (excluded_middle (A1b.ppo E x y)); intro Hor.\n  inversion Hor as [Hppo1 | Hnppo1].\n   left; apply A1bBasic.ppo_in_ghb; auto.\n   assert (ppo_sub E x y) as Hppos.\n     split; auto.\n\n   assert (R.competing E X x y) as Hc.\n    left; auto.\n   right; generalize (Hfb x y Hc); intro Hors; auto.\n   inversion Hors as [|Hsyx]; auto.\n     assert (tc (rel_union (s E X) (A2n.ppo E)) y y) as Hcy.\n       apply trc_ind with x; apply trc_step; [left | right]; auto.\n     generalize (s_ppo2 E X Hwf); unfold acyclic; intro Hac;\n     generalize (Hac y Hcy); intro Ht; inversion Ht.\nQed.\n\nLemma rf_sub_seq_ppo2_in_ab1 :\n  forall E X x z y,\n  well_formed_event_structure E ->\n  R.covered E X s ->\n  rf_sub X x z ->\n  A2n.ppo E z y ->\n  s E X x y.\nProof.\nintros E X x z y Hwf Hfb Hxz Hzy.\n   assert (R.competing E X z y) as Hc.\n     right; split; auto.\n     exists x; auto.\ngeneralize (Hfb z y Hc); intro Hor.\ninversion Hor.\nassert (rf_sub X x z /\\ s E X z y) as Hand.\n  split; auto.\n\napply (s_ac E X x z y Hand).\n     assert (tc (rel_union (s E X) (A2n.ppo E)) y y) as Hcy.\n       apply trc_ind with z; apply trc_step; [left | right]; auto.\n     generalize (s_ppo2 E X Hwf); unfold acyclic; intro Hac;\n     generalize (Hac y Hcy); intro Ht; inversion Ht.\nQed.\n\nLemma seq_implies_ghb1_int :\n  forall E X x y,\n  weaker ->\n  well_formed_event_structure E ->\n  R.covered E X s ->\n  tc (rel_seq (rel_union (rel_union (A1bWmm.mhb' E X) (rf_sub X))\n   (rel_union (rel_seq (ws X) (rf_sub X)) (rel_seq (fr E X) (rf_sub X)))) (tc (A2n.ppo E))) x y ->\n  tc (rel_union (A1bWmm.ghb E X) (s E X)) x y.\nProof.\nintros E X x y Hwk Hwf Hfb Hxy.\n\ninduction Hxy.\n  destruct H as [z [Hxz Hzy]].\n    inversion Hxz as [Hu | Hs].\n    inversion Hu as [Hmhb'1 | Hrf_sub].\n      apply trc_ind with z.\n        rewrite (ghb1b_eq E X).\n        apply tc_incl with (rel_union (rel_union (ws X) (fr E X))\n        (rel_union (rel_union (mrf1 X) (A1.ppo E)) (A1b.abc E X))).\n        intros e1 e2 H12; left; auto.\n        apply (mhb'1_eq Hmhb'1).\n\n        apply tc_incl with (A2n.ppo E); auto.\n        intros e1 e2 H12; apply ppo2_in_ghb1; auto.\n\n        generalize (tc_dec Hzy); intros [z' [Hzz' Hor]].\n        inversion Hor as [Htc | Heq].\n          apply trc_ind with z'.\n\n        inversion Hu as [Hmhb | Hrfs].\n          apply trc_ind with z.\n        rewrite (ghb1b_eq E X).\n        apply tc_incl with (rel_union (rel_union (ws X) (fr E X))\n        (rel_union (rel_union (mrf1 X) (A1.ppo E)) (A1b.abc E X))).\n        intros e1 e2 H12; left; auto.\n        apply (mhb'1_eq Hmhb).\n        apply tc_incl with (A2n.ppo E); auto.\n        intros e1 e2 H12; apply ppo2_in_ghb1; auto.\n          apply trc_step; auto.\n       apply trc_step; right;\n       apply (rf_sub_seq_ppo2_in_ab1 E X x z z' Hwf Hfb Hrf_sub Hzz').\n        apply tc_incl with (A2n.ppo E); auto.\n        intros e1 e2 H12; apply ppo2_in_ghb1; auto.\n       rewrite <- Heq; apply trc_step; right;\n       apply (rf_sub_seq_ppo2_in_ab1 E X x z z' Hwf Hfb Hrf_sub Hzz').\n\n  inversion Hs as [Hsws | Hsfr].\n    destruct Hsws as [e [Hxe Hez]].\n        generalize (tc_dec Hzy); intros [z' [Hzz' Hor]].\n        inversion Hor as [Htc | Heq].\n          apply trc_ind with z'.\n    apply trc_ind with e; apply trc_step.\n        rewrite (ghb1b_eq E X).\n      left; left; left; auto.\n\n      right. apply rf_sub_seq_ppo2_in_ab1 with z; auto.\n      apply tc_incl with (A2n.ppo E); auto.\n      intros e1 e2 H12; apply ppo2_in_ghb1; auto.\n\n    apply trc_ind with e; apply trc_step.\n        rewrite (ghb1b_eq E X).\n      left; left; left; auto.\n\n      right. apply rf_sub_seq_ppo2_in_ab1 with z; auto.\n      rewrite <- Heq; auto.\n\n    destruct Hsfr as [e [Hxe Hez]].\n\n        generalize (tc_dec Hzy); intros [z' [Hzz' Hor]].\n        inversion Hor as [Htc | Heq].\n          apply trc_ind with z'.\n    apply trc_ind with e.\n    apply trc_step.\n        rewrite (ghb1b_eq E X).\n      left; left; right; auto.\n\n      apply trc_step; right; apply rf_sub_seq_ppo2_in_ab1 with z; auto.\n      apply tc_incl with (A2n.ppo E); auto.\n          intros e1 e2 H12; apply ppo2_in_ghb1; auto.\n\n    rewrite <- Heq; apply trc_ind with e.\n    apply trc_step.\n        rewrite (ghb1b_eq E X).\n      left; left; right; auto.\n\n      apply trc_step; right; apply rf_sub_seq_ppo2_in_ab1 with z; auto.\n\napply trc_ind with z; auto.\nQed.\n\nLemma seq_implies_ghb1 :\n  forall E X x y,\n  weaker ->\n  well_formed_event_structure E ->\n  R.covered E X s ->\n  tc (rel_seq (maybe (rel_union (rel_union (A1bWmm.mhb' E X) (rf_sub X))\n   (rel_union (rel_seq (ws X) (rf_sub X)) (rel_seq (fr E X) (rf_sub X))))) (tc (A2n.ppo E))) x y ->\n  tc (rel_union (A1bWmm.ghb E X) (s E X)) x y.\nProof.\nintros E X x y Hwk Hwf Hfb Hxy.\n\ninduction Hxy.\n  destruct H as [z [Hor Hzy]].\n    inversion Hor as [Hxz | Heq].\n      apply seq_implies_ghb1_int; auto.\n        apply trc_step; exists z; auto.\n   subst; generalize Hzy; apply tc_incl.\n  intros e1 e2 H12; apply ppo2_in_ghb1; auto.\n\n  apply trc_ind with z; auto.\nQed.\n\nLemma min_covered_implies_no_min_cy :\n  forall E X, well_formed_event_structure E ->\n  A1Wmm.valid_execution E X ->\n  R.covered E X s ->\n  ~(exists cy, crit_cy_or E X cy).\nProof.\nintros E X Hwf Hv1 Hc [cy [Hicy [? [Hnac ?]]]].\nassert (  write_serialization_well_formed (events E) (ws X) /\\\n  rfmaps_well_formed E (events E) (rf X)) as Hs.\n  destruct_valid Hv1; split; split; auto.\ngeneralize (not_forall_exists_tc Hnac); intros [x Hx].\ngeneralize (tc_cy_in_tc E X cy Hicy x x Hx); intros Hx'.\ngeneralize (tc_mhbd_ppo2_in_mhb_ppo2 E X x x Hx'); intro Htc.\nchange (A2.ppo E) with (A2n.ppo E) in Htc.\nchange (A2nWmm.mhb E X) with (A2nBasic.AWmm.mhb E X) in Htc.\nassert (exists y, tc (rel_seq (maybe (A2nWmm.mhb' E X)) (tc (A2.ppo E))) y y) as Hcyc.\neapply (A2nBasic.mhb_union_ppo_cycle_implies_mhb'_seq_ppo_cycle2\n  X Hwf Hs Htc); auto; apply Htc.\ndestruct Hcyc as [y Hcyc].\ngeneralize (mhb'_ppo2_is_u_seq wk Hwf Hcyc); intro Hcy'.\nassert (rfmaps_well_formed E (events E) (rf X)) as Hrfwf.\n  destruct Hs; auto.\ngeneralize (seq_implies_ghb1 E X y y wk Hwf Hc Hcy');\nrewrite union_triv; intro Hcycle.\ngeneralize (s_ghb E X Hwf Hv1 y); intro. contradiction.\nQed.\n\nLemma covering_s :\n  forall E X, well_formed_event_structure E ->\n    A1Wmm.valid_execution E X ->\n    R.covered E X s -> acyclic (A2nWmm.ghb E X).\nProof.\nintros E X Hwf Hv1 Hc z Hz.\ngeneralize (exists_crit_cy_or E X Hz);\nintros [cy Hcy].\nassert (exists cy, crit_cy_or E X cy) as Hex.\n  exists cy; auto.\ngeneralize (min_covered_implies_no_min_cy E X Hwf Hv1 Hc); intro Hnex.\ncontradiction.\nQed.\n\nEnd RacyMin.\n\nEnd Cm.\n\nEnd CritSC.\n", "meta": {"author": "herd", "repo": "CoqCat", "sha": "e9afddbfe4cd17de335596454b8e9de0dd8ce5c2", "save_path": "github-repos/coq/herd-CoqCat", "path": "github-repos/coq/herd-CoqCat/CoqCat-e9afddbfe4cd17de335596454b8e9de0dd8ce5c2/crit_sc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7057850154599563, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.28748981004877344}}
{"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(** %\\subsection*{ support :  cast\\_between\\_subsets.v }%*)\nSet Implicit Arguments.\nUnset Strict Implicit.\nRequire Export Map_embed.\nRequire Export algebra_omissions.\n\n(** - Various casting functions between equal but non-convertible types *)\n\n(** - This one maps elements of a subset to the same subset under a different name\n %\\label{mapbetweenequalsubsets}% *)\nDefinition map_between_equal_subsets :\n  forall (A : Setoid) (X Y : part_set A), X =' Y in _ -> X -> Y.\nintros A X Y H x.\ninversion_clear x.\napply (Build_subtype (E:=A) (P:=Y) (subtype_elt:=subtype_elt)).\nsimpl in H.\nred in H.\ngeneralize (H subtype_elt).\nintro H'.\ninversion_clear H'.\napply H0; auto with algebra.\nDefined.\n\nLemma subtype_elt_eats_map_between_equal_subsets :\n forall (A : Setoid) (X Y : part_set A) (H : X =' Y in _) (x : X),\n subtype_elt (map_between_equal_subsets H x) =' subtype_elt x in _.\nintros.\nelim x.\nsimpl in |- *.\nauto with algebra.\nQed.\n\nHint Resolve subtype_elt_eats_map_between_equal_subsets: algebra.\n\nLemma map_between_equal_subsets_inj :\n forall (A : Setoid) (X Y : part_set A) (H H' : X =' Y in _) (x x' : X),\n map_between_equal_subsets H x =' map_between_equal_subsets H' x' in _ ->\n x =' x' in _.\nsimpl in |- *.\nunfold subtype_image_equal in |- *; simpl in |- *.\nintros.\napply Trans with (subtype_elt (map_between_equal_subsets H x));\n auto with algebra.\napply Trans with (subtype_elt (map_between_equal_subsets H' x'));\n auto with algebra.\nQed.\n\n(** - This one turns $f:A\\to X$ into $A\\to Y$ whenever $X='Y$ *)\n\n(** %\\label{Maptoequalsubsets}% *)\nDefinition Map_to_equal_subsets :\n  forall (A B : Setoid) (X Y : part_set A), X =' Y in _ -> MAP B X -> MAP B Y.\nintros.\napply (Build_Map (Ap:=fun b : B => map_between_equal_subsets H (X0 b))).\nred in |- *; simpl in |- *; red in |- *.\nintros.\nunfold map_between_equal_subsets in |- *.\ngeneralize (Map_compatible_prf X0 H0).\ncase (X0 x); case (X0 y).\nsimpl in |- *.\nauto.\nDefined.\n\nLemma subtype_elt_eats_Map_to_equal_subsets :\n forall (A B : Setoid) (X Y : part_set A) (H : X =' Y in _) \n   (b : B) (M : Map B X),\n subtype_elt (Map_to_equal_subsets H M b) =' subtype_elt (M b) in _.\nintros.\nsimpl in |- *.\ncase (M b).\nsimpl in |- *.\nauto with algebra.\nQed.\n\nHint Resolve subtype_elt_eats_Map_to_equal_subsets: algebra.\n\nLemma Map_embed_eats_Map_to_equal_subsets :\n forall (A B : Setoid) (X Y : part_set A) (H : X =' Y in _) (M : Map B X),\n Map_embed (Map_to_equal_subsets H M) =' Map_embed M in _.\nintros.\nsimpl in |- *.\nred in |- *.\nintros b.\nsimpl in |- *.\nauto with algebra.\nQed.\n\nHint Resolve Map_embed_eats_Map_to_equal_subsets: algebra.\n\nLemma Map_to_equal_subsets_inj :\n forall (A B : Setoid) (X Y : part_set A) (H H' : X =' Y in _)\n   (f g : Map B X),\n Map_to_equal_subsets H f =' Map_to_equal_subsets H' g in _ ->\n f =' g in MAP _ _.\nunfold Map_to_equal_subsets in |- *; simpl in |- *; unfold Map_eq in |- *;\n simpl in |- *; unfold subtype_image_equal in |- *; \n simpl in |- *.\nintros.\napply subtype_elt_comp.\napply map_between_equal_subsets_inj with Y H H'; auto with algebra.\nsimpl in |- *; red in |- *; simpl in |- *.\nauto.\nQed.\n\n(** - if $\\forall b\\in B, f(b)\\in W\\subset A$ for $f:B\\to A$ then $f$ can be seen as\n $f:B\\to W$. This is done by cast_map_to_subset. *)\n\nDefinition cast_to_subset_fun :\n  forall (A B : Setoid) (v : MAP B A) (W : part_set A),\n  (forall i : B, in_part (v i) W) -> (B -> W:Type).\nintros A B v.\nelim v.\nintros vseq vprf; intros.\ngeneralize X; clear X.\nsimpl in |- *.\nexact (fun i : B => Build_subtype (H i)).\nDefined.\n\nLemma cast_doesn't_change :\n forall (A B : Setoid) (v : MAP B A) (W : part_set A)\n   (H : forall i : B, in_part (v i) W) (i : B),\n subtype_elt (cast_to_subset_fun H i) =' v i in _.\nintros A B v.\nelim v.\nsimpl in |- *.\nauto with algebra.\nQed.\n\nHint Resolve cast_doesn't_change: algebra.\n\n(** %\\label{castmaptosubset}% *)\nDefinition cast_map_to_subset :\n  forall (A B : Setoid) (v : MAP B A) (W : part_set A),\n  (forall i : B, in_part (v i) W) -> MAP B W.\nintros.\ncut (fun_compatible (cast_to_subset_fun H)).\nintro.\nexact (Build_Map H0).\nred in |- *.\nsimpl in |- *.\nred in |- *.\nintros.\napply Trans with (v x); auto with algebra.\napply Trans with (v y); auto with algebra.\nDefined.\n\nLemma cast_map_to_subset_doesn't_change :\n forall (A B : Setoid) (v : MAP B A) (W : part_set A)\n   (H : forall i : B, in_part (v i) W) (i : B),\n subtype_elt (cast_map_to_subset H i) =' v i in _.\nintros.\nsimpl in |- *.\nauto with algebra.\nQed.\n\nHint Resolve cast_map_to_subset_doesn't_change: algebra.\n\nLemma Map_embed_cast_map_to_subset_inv :\n forall (A B : Setoid) (v : MAP B A) (W : part_set A)\n   (H : forall i : B, in_part (v i) W),\n Map_embed (cast_map_to_subset H) =' v in _.\nintros.\nsimpl in |- *.\nred in |- *.\nsimpl in |- *.\nauto with algebra.\nQed.\n\nHint Resolve Map_embed_cast_map_to_subset_inv: algebra.\n\nLemma Map_embed_eats_cast_map_to_subset :\n forall (A D : Setoid) (B C : part_set A) (v : MAP D B)\n   (H : forall i : D, in_part (Map_embed v i) C),\n Map_embed (cast_map_to_subset H) =' Map_embed v in _.\nintros.\nauto with algebra.\nQed.\n\nHint Resolve Map_embed_eats_cast_map_to_subset: algebra.\n\nLemma seq_castable :\n forall (A B : Setoid) (v : MAP B A) (W : part_set A),\n (forall i : B, in_part (v i) W) -> exists w : MAP B W, Map_embed w =' v in _.\nintros.\nexists (cast_map_to_subset H).\nauto with algebra.\nQed.\n\nHint Resolve seq_castable: algebra.\n\nLemma subset_seq_castable :\n forall (A D : Setoid) (B C : part_set A) (v : MAP D B)\n   (H : forall i : D, in_part (Map_embed v i) C),\n exists w : MAP D C, Map_embed w =' Map_embed v in _.\nintros.\nexists (cast_map_to_subset H).\nauto with algebra.\nQed.\n\nHint Resolve subset_seq_castable: algebra.\n\nLemma cast_seq_nice :\n forall (A B : Setoid) (v : MAP B A) (W : part_set A)\n   (H : forall i : B, in_part (v i) W) (P : Predicate (MAP B A)),\n Pred_fun P v -> Pred_fun P (Map_embed (cast_map_to_subset H)).\ndestruct P.\nintros.\nred in Pred_compatible_prf.\nsimpl in |- *.\nsimpl in H0.\napply Pred_compatible_prf with v; auto with algebra.\nQed.\n\nHint Resolve cast_seq_nice: algebra.\n\nLemma cast_subset_seq_nice :\n forall (A D : Setoid) (B C : part_set A) (v : MAP D B)\n   (H : forall i : D, in_part (Map_embed v i) C) (P : Predicate (MAP D A)),\n Pred_fun P (Map_embed v) -> Pred_fun P (Map_embed (cast_map_to_subset H)).\nintros.\nauto with algebra.\nQed.\n\nHint Resolve cast_subset_seq_nice: algebra.\n\nLemma cast_respects_predicates_per_elt :\n forall (A D : Setoid) (B C : part_set A) (v : MAP D B) \n   (P : Predicate A) (H : forall i : D, in_part (Map_embed v i) C) \n   (i : D),\n Pred_fun P (Map_embed v i) ->\n Pred_fun P (Map_embed (cast_map_to_subset H) i).\nintros.\ngeneralize H0; clear H0; elim P.\nintros Pf pc H0.\nsimpl in |- *.\nsimpl in H0.\nauto.\nQed.\n\nLemma cast_respects_all_elt_predicates :\n forall (A D : Setoid) (B C : part_set A) (v : MAP D B) \n   (P : Predicate A) (H : forall i : D, in_part (Map_embed v i) C),\n (forall i : D, Pred_fun P (Map_embed v i)) ->\n forall j : D, Pred_fun P (Map_embed (cast_map_to_subset H) j).\nintros.\ngeneralize H0; clear H0; elim P.\nintros Pf pc H0.\nsimpl in |- *.\nsimpl in H0.\nauto.\nQed.\n\nHint Resolve cast_respects_predicates_per_elt\n  cast_respects_all_elt_predicates: algebra.\n\n(** - Similarly, if $B\\subset C$ are subsets of $A$, then $f:D\\to B$ is also $f:D\\to C$. *)\n\nDefinition Map_include :\n  forall (A D : Setoid) (B C : part_set A),\n  included B C -> MAP D B -> MAP D C.\nintros.\napply (cast_map_to_subset (v:=Map_embed X)).\nred in H.\nintro.\napply H; auto with algebra.\napply Map_embed_prop; auto with algebra.\nDefined.\n\nDefinition Map_include_map :\n  forall (A D : Setoid) (B C : part_set A),\n  included B C -> MAP (MAP D B) (MAP D C).\nintros.\nsimpl in |- *.\napply Build_Map with (Map_include (D:=D) H).\nred in |- *.\nintuition.\nDefined.", "meta": {"author": "coq-contribs", "repo": "lin-alg", "sha": "74833da8a93b1c4c921d4aaebbc9f7c2a096a5eb", "save_path": "github-repos/coq/coq-contribs-lin-alg", "path": "github-repos/coq/coq-contribs-lin-alg/lin-alg-74833da8a93b1c4c921d4aaebbc9f7c2a096a5eb/support/cast_between_subsets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.28743092757451677}}
{"text": "(** Coq coding by choukh, May 2022 **)\n\nFrom ZF Require Import Basic Embedding Universe.\n\n(*** 范畴性 ***)\n\n(** 等势模型 **)\nSection Equipotent.\nVariable 𝓜 𝓝 : ZF.\nNotation i := (i 𝓝).\nNotation j := (j 𝓜).\n\nVariable f : 𝓜 → 𝓝.\nVariable g : 𝓝 → 𝓜.\nVariable fg : ∀ a, f (g a) = a.\nVariable gf : ∀ x, g (f x) = x.\n\nTheorem 等势模型同构 : 𝓜 ≅ 𝓝.\nProof.\n  destruct (相似的完全性三歧 𝓜 𝓝) as [H|[[l[a s]]|[r[x s]]]].\n  - apply H.\n  - exfalso.\n    set (a ∩ₚ (λ b, b ∉ f (j b))) as b.\n    set (i (g b)) as c.\n    assert (ca: c ∈ a) by apply s, i值域, l.\n    assert (H: c ∈ b ↔ c ∈ a ∧ c ∉ f (j c)). unfold b. now rewrite 分离.\n    unfold c in H at 4. rewrite ji, fg in H. 2:apply l.\n    intuition.\n  - exfalso.\n    set (x ∩ₚ (λ y, y ∉ g (i y))) as y.\n    set (j (f y)) as z.\n    assert (zx: z ∈ x) by apply s, j定义域, r.\n    assert (H: z ∈ y ↔ z ∈ x ∧ z ∉ g (i z)). unfold y. now rewrite 分离.\n    unfold z in H at 4. rewrite ij, gf in H. 2:apply r.\n    intuition.\nQed.\n\nEnd Equipotent.\n\n(** 极小模型 **)\nSection Minimal.\nVariable 𝓜 𝓝 : ZF.\nArguments 𝕯 : clear implicits.\nArguments 𝕹 : clear implicits.\n\nTheorem 极小模型同构 : ZFₙ 0 𝓜 → ZFₙ 0 𝓝 → 𝓜 ≅ 𝓝.\nProof.\n  intros minM%ZFₙO minN%ZFₙO.\n  destruct (相似的完全性三歧 𝓜 𝓝) as [H|[[l[a s]]|[r[x s]]]].\n  - apply H.\n  - exfalso. apply minN. exists a.\n    apply (@集化值域是宇宙 𝓝 𝓜), s.\n  - exfalso. apply minM. exists x.\n    apply 集化定义域是宇宙, s.\nQed.\n\nEnd Minimal.\n\n(** 有穷序数宇宙模型 **)\nSection ZFsn.\nVariable 𝓜 𝓝 : ZF.\nNotation i := (i 𝓝).\nNotation j := (j 𝓜).\n\nTheorem 有穷序数宇宙模型同构 n : ZFₙ n 𝓜 → ZFₙ n 𝓝 → 𝓜 ≅ 𝓝.\nProof.\n  intros Mn Nn. destruct n. apply 极小模型同构; trivial.\n  destruct (相似的完全性三歧 𝓜 𝓝) as [H|[[l[a s]]|[r[x s]]]].\n  - apply H.\n  - exfalso. apply ZFₙS in Mn as [u [U [H _]]].\n    apply Nn. apply 等级S. exists a. split.\n    + apply (@集化值域是宇宙 𝓝 𝓜), s.\n    + exists (i u). split. now apply s, i值域.\n      assert (u ≈ i u) by apply i规范, l. split.\n      * apply (相似保宇宙 (x:=u)); auto.\n      * apply (相似保宇宙等级 (x:=u)); auto.\n  - exfalso. apply ZFₙS in Nn as [u [U [H _]]].\n    apply Mn. apply 等级S. exists x. split.\n    + apply 集化定义域是宇宙, s.\n    + exists (j u). split. now apply s, j定义域.\n      assert (u ≈ j u) by apply 相似的对称性, j规范, r. split.\n      * apply (相似保宇宙 (x:=u)); auto.\n      * apply (相似保宇宙等级 (x:=u)); auto.\nQed.\n\nEnd ZFsn.\n", "meta": {"author": "choukh", "repo": "MetaZF", "sha": "81211540e9307b98f2060a12a5a1ab9bb60a4cbc", "save_path": "github-repos/coq/choukh-MetaZF", "path": "github-repos/coq/choukh-MetaZF/MetaZF-81211540e9307b98f2060a12a5a1ab9bb60a4cbc/ZF/Categoricity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.28737635935298705}}
{"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 O E Eprime A B C D U Bu Xu Du Bprime Dprime Dprimeprime : Universe, ((wd_ U O /\\ (wd_ O E /\\ (wd_ O Eprime /\\ (wd_ E Eprime /\\ (wd_ A O /\\ (wd_ B O /\\ (wd_ C O /\\ (wd_ D O /\\ (wd_ U Eprime /\\ (wd_ A Eprime /\\ (wd_ Xu O /\\ (wd_ Dprimeprime O /\\ (wd_ D Du /\\ (wd_ Bu Xu /\\ (wd_ B Bu /\\ (col_ O E A /\\ (col_ O E B /\\ (col_ O E C /\\ (col_ O E D /\\ (col_ O E U /\\ (col_ O Eprime Bu /\\ (col_ O E Xu /\\ (col_ O Eprime Du /\\ (col_ O Eprime Bprime /\\ (col_ O Eprime Dprime /\\ (col_ O Eprime Dprimeprime /\\ col_ O Xu Dprimeprime)))))))))))))))))))))))))) -> col_ O E Eprime)).\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_1391.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2873024031201704}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import curve448.\nRequire Import stdpp.list.\nRequire Import ZArith.\nRequire Import compcert.lib.Coqlib.\n\nInstance CompSpecs : compspecs. Proof. make_compspecs prog. Defined.\nDefinition Vprog : varspecs.  mk_varspecs prog. Defined.\n\nLocal Open Scope Z.\n\nDefinition curve448SetInt_spec : ident * funspec :=\nDECLARE _curve448SetInt\nWITH a : val,\n     sha : share,\n     contents_a : list val,\n     b : Z,\n     gv : globals\nPRE [ tptr tuint, tuint ]\n    PROP   (writable_share sha;\n            Zlength contents_a = 14)\n    PARAMS (a ; Vint(Int.repr b)) GLOBALS (gv)\n    SEP    (data_at sha (tarray tuint 14) contents_a a)\nPOST [ tvoid ]\n    PROP   ()\n    RETURN ()\n    SEP    (data_at sha (tarray tuint 14) (map Vint (map Int.repr (b :: (Zrepeat 0 13)))) a).\n\nDefinition curve448SetInt_INV a sha contents_a b := \n(EX i : Z,\n(PROP   (writable_share sha; \n        Zlength contents_a = 14)\nLOCAL   (temp _a a)\nSEP     (data_at sha (tarray tuint 14) \n            ([Vint (Int.repr b)] ++ (Zrepeat (Vint (Int.repr 0)) (i-1)) ++\n              sublist.sublist i 14 contents_a) a\n        )))%assert.\n\nLemma L1 (h x : val) (l : list val) (i : Z) :\n1 <= i -> upd_Znth i ([h] ++ l) x = [h] ++ (upd_Znth (i-1) l) x.\nProof. intros. list_simplify. Qed.\n\nLemma L2 (i : Z) (l1 l2 : list val) (x : val) :\nZlength l1 <= i ->\nupd_Znth i (l1 ++ l2) x = l1 ++ (upd_Znth (i-(Zlength l1)) l2) x.\nProof. intros. list_simplify. Qed.\n\nLemma L3 (x h : val) (l : list val):\nupd_Znth 0 ([h] ++ l) x  = [x] ++ l.\nProof. list_simplify. Qed.\n\nDefinition Gprog : funspecs := ltac:(with_library prog [ curve448SetInt_spec ]).\n\nLemma body_curve448SetInt : semax_body Vprog Gprog f_curve448SetInt curve448SetInt_spec.\nProof.\n    start_function.\n    forward.\n    forward_for_simple_bound 14 (curve448SetInt_INV a sha contents_a b).\n    -   entailer!.\n        replace (upd_Znth 0 contents_a (Vint (Int.repr b))) with ([Vint (Int.repr b)] ++\n        Zrepeat (Vint (Int.repr 0)) (1 - 1) ++ sublist.sublist 1 14 contents_a)\n        by list_simplify; cancel.\n    -   forward.\n        entailer!.\n        replace (upd_Znth i ([Vint (Int.repr b)] ++ Zrepeat (Vint (Int.repr 0)) (i - 1) \n        ++ sublist.sublist i 14 contents_a) (Vint (Int.repr 0))) with \n        ([Vint (Int.repr b)] ++ Zrepeat (Vint (Int.repr 0)) (i + 1 - 1) ++\n        sublist.sublist (i + 1) 14 contents_a) by list_simplify; cancel.\n    -   entailer!.\n        replace ([Vint (Int.repr b)] ++\n        Zrepeat (Vint (Int.repr 0)) (14 - 1) ++ sublist.sublist 14 14 contents_a) with \n        (Vint (Int.repr b) :: map Vint (map Int.repr (Zrepeat 0 13))) by list_simplify;\n        cancel.\nQed.\n", "meta": {"author": "david-hrnndz", "repo": "Verif-Oryx", "sha": "3dd65855428288e17f12aa23facf13e88604e731", "save_path": "github-repos/coq/david-hrnndz-Verif-Oryx", "path": "github-repos/coq/david-hrnndz-Verif-Oryx/Verif-Oryx-3dd65855428288e17f12aa23facf13e88604e731/verif_curve448SetInt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2872622650372018}}
{"text": "Require Import Sumbool.\n\nRequire Import Raft.\nRequire Import CommonTheorems.\nRequire Import TraceUtil.\nRequire Import Linearizability.\nRequire Import OutputImpliesAppliedInterface.\nRequire Import AppliedImpliesInputInterface.\nRequire Import CausalOrderPreservedInterface.\nRequire Import OutputCorrectInterface.\nRequire Import InputBeforeOutputInterface.\nRequire Import OutputGreatestIdInterface.\n\nSection RaftLinearizableProofs.\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  Context {aiii : applied_implies_input_interface}.\n  Context {copi : causal_order_preserved_interface}.\n  Context {iboi : input_before_output_interface}.\n  Context {oci : output_correct_interface}.\n  Context {ogii : output_greatest_id_interface}.\n\n  Definition op_eq_dec : forall x y : op key, {x = y} + {x <> y}.\n  Proof using. \n    decide equality; auto using key_eq_dec.\n  Qed.\n\n\n  Fixpoint import (tr : list (name * (raft_input + list raft_output)))\n  : list (op key) :=\n    match tr with\n      | [] => []\n      | (_, (inl (ClientRequest c id cmd))) :: xs =>\n        I (c, id) :: remove op_eq_dec (I (c, id)) (import xs)\n      | (_, (inr l)) :: xs =>\n        let os := dedup op_eq_dec\n                        (filterMap (fun x =>\n                               match x with\n                                 | ClientResponse c id cmd => Some (O (c, id))\n                                 | _ => None\n                               end) l)\n        in os ++ remove_all op_eq_dec os (import xs)\n      | _ :: xs => import xs\n    end.\n\n  Inductive exported (env_i : key -> option input) (env_o : key -> option output) :\n    list (IR key) -> list (input * output) -> Prop :=\n  | exported_nil : exported env_i env_o nil nil\n  | exported_IO : forall k i o l tr,\n                    env_i k = Some i ->\n                    env_o k = Some o ->\n                    exported env_i env_o l tr ->\n                    exported env_i env_o (IRI k :: IRO k :: l) ((i, o) :: tr)\n  | exported_IU : forall k i o l tr,\n                    env_i k = Some i ->\n                    exported env_i env_o l tr ->\n                    exported env_i env_o (IRI k :: IRU k :: l) ((i, o) :: tr).\n\n\n  Fixpoint get_input (tr : list (name * (raft_input + list raft_output))) (k : key)\n    : option input :=\n    match tr with\n      | [] => None\n      | (_, (inl (ClientRequest c id cmd))) :: xs =>\n        if (sumbool_and _ _ _ _\n                        (eq_nat_dec c (fst k))\n                        (eq_nat_dec id (snd k))) then\n          Some cmd\n        else\n          get_input xs k\n      | _ :: xs => get_input xs k\n    end.\n\n  Fixpoint get_output' (os : list raft_output) (k : key) : option output :=\n    match os with\n      | [] => None\n      | ClientResponse c id o :: xs =>\n        if (sumbool_and _ _ _ _\n                        (eq_nat_dec c (fst k))\n                        (eq_nat_dec id (snd k))) then\n          Some o\n        else\n          get_output' xs k\n      | _ :: xs => get_output' xs k\n    end.\n\n  Fixpoint get_output (tr : list (name * (raft_input + list raft_output))) (k : key)\n    : option output :=\n    match tr with\n      | [] => None\n      | (_, (inr os)) :: xs => (match get_output' os k with\n                                 | Some o => Some o\n                                 | None => get_output xs k\n                               end)\n      | _ :: xs => get_output xs k\n    end.\n\n  Lemma has_key_intro :\n    forall e,\n      has_key (eClient e) (eId e) e = true.\n  Proof using. \n    unfold has_key.\n    intros.\n    destruct e.\n    simpl.\n    repeat (do_bool; intuition).\n  Qed.\n\n  Lemma has_key_intro' :\n    forall e c i,\n      eClient e = c ->\n      eId e = i ->\n      has_key c i e = true.\n  Proof using. \n    intros. subst. apply has_key_intro.\n  Qed.\n\n  Lemma has_key_different_id_false :\n    forall e e',\n      eId e <> eId e' ->\n      has_key (eClient e) (eId e) e' = false.\n  Proof using. \n    unfold has_key.\n    intros.\n    destruct e'.\n    simpl in *.\n    do_bool. right. do_bool. auto.\n  Qed.\n\n  Lemma has_key_different_client_false :\n    forall e e',\n      eClient e <> eClient e' ->\n      has_key (eClient e) (eId e) e' = false.\n  Proof using. \n    unfold has_key.\n    intros.\n    destruct e'.\n    simpl in *.\n    do_bool. left. do_bool. auto.\n  Qed.\n\n  Lemma deduplicate_log'_In :\n    forall l e,\n      In e l ->\n      forall ks,\n      (forall i, assoc eq_nat_dec ks (eClient e) = Some i -> i < eId e) ->\n      (forall id',\n         before_func (has_key (eClient e) id') (has_key (eClient e) (eId e)) l ->\n         id' <= eId e) ->\n      (exists e',\n        eClient e' = eClient e /\\\n        eId e' = eId e /\\\n        In e' (deduplicate_log' l ks)).\n  Proof using. \n    induction l; simpl.\n    - intuition.\n    - intros. repeat break_match; intuition; subst; simpl in *; intuition eauto.\n      + do_bool. destruct (eq_nat_dec (eClient e) (eClient a)).\n        * assert (eId a <= eId e).\n          { repeat find_rewrite. auto using has_key_intro.\n          }\n          { find_apply_lem_hyp le_lt_or_eq. break_or_hyp.\n            - specialize (IHl _ ltac:(eauto)).\n              match goal with\n                | [ |- context [deduplicate_log' _ ?ks] ] =>\n                  specialize (IHl ks)\n              end.\n              forward IHl.\n              { intuition.\n                repeat find_rewrite. rewrite get_set_same in *. find_injection. auto.\n              }\n              concludes.\n              forward IHl.\n              { intuition auto using has_key_different_id_false with *. }\n              concludes.\n              break_exists_exists. intuition.\n            - eauto.\n          }\n        * specialize (IHl _ ltac:(eauto)).\n          match goal with\n            | [ |- context [deduplicate_log' _ ?ks] ] =>\n              specialize (IHl ks)\n          end.\n          forward IHl.\n          { intuition.\n            repeat find_rewrite. rewrite get_set_diff in * by auto. auto.\n          }\n          concludes.\n          forward IHl.\n          { intuition auto using has_key_different_client_false with *. }\n          concludes.\n          break_exists_exists. intuition.\n      + do_bool. assert (n < eId e) by auto. omega.\n      + do_bool. apply IHl; auto.\n        intros.\n        destruct (eq_nat_dec (eClient e) (eClient a)).\n        * assert (eId e <> eId a).\n          { intro. repeat find_rewrite.\n            assert (n < eId a) by auto. omega.\n          }\n          intuition auto using has_key_different_id_false with *.\n        * intuition auto using has_key_different_client_false with *.\n      + destruct (eq_nat_dec (eClient e) (eClient a)).\n        * assert (eId a <= eId e).\n          { repeat find_rewrite. auto using has_key_intro.\n          }\n          { find_apply_lem_hyp le_lt_or_eq. break_or_hyp.\n            - specialize (IHl _ ltac:(eauto)).\n              match goal with\n                | [ |- context [deduplicate_log' _ ?ks] ] =>\n                  specialize (IHl ks)\n              end.\n              forward IHl.\n              { intuition.\n                repeat find_rewrite. rewrite get_set_same in *. find_injection. auto.\n              }\n              concludes.\n              forward IHl.\n              { intuition auto using has_key_different_id_false with *. }\n              concludes.\n              break_exists_exists. intuition.\n            - eauto.\n          }\n        * specialize (IHl _ ltac:(eauto)).\n          match goal with\n            | [ |- context [deduplicate_log' _ ?ks] ] =>\n              specialize (IHl ks)\n          end.\n          forward IHl.\n          { intuition.\n            repeat find_rewrite. rewrite get_set_diff in * by auto. auto.\n          }\n          concludes.\n          forward IHl.\n          { intuition auto using has_key_different_client_false with *. }\n          concludes.\n          break_exists_exists. intuition.\n  Qed.\n\n  Lemma deduplicate_log_In :\n    forall l e,\n      In e l ->\n      (forall id',\n         before_func (has_key (eClient e) id') (has_key (eClient e) (eId e)) l ->\n         id' <= eId e) ->\n      exists e',\n        eClient e' = eClient e /\\\n        eId e' = eId e /\\\n        In e' (deduplicate_log l).\n  Proof using. \n    unfold deduplicate_log'.\n    intros.\n    eapply deduplicate_log'_In with (ks := []) in H; simpl; intuition; try discriminate.\n  Qed.\n\n  Lemma deduplicate_log_In_if :\n    forall l e,\n      In e (deduplicate_log l) ->\n      In e l.\n  Proof using. \n    eauto using deduplicate_log'_In_if.\n  Qed.\n\n  Fixpoint log_to_IR (env_o : key -> option output) (log : list entry) {struct log} : list (IR key) :=\n    match log with\n      | [] => []\n      | mkEntry h client id index term input :: log' =>\n        (match env_o (client, id) with\n           | None => [IRI (client, id); IRU (client, id)]\n           | Some _ => [IRI (client, id); IRO (client, id)]\n         end) ++ log_to_IR env_o log'\n    end.\n\n  Lemma log_to_IR_good_trace :\n    forall env_o log,\n      good_trace _ (log_to_IR env_o log).\n  Proof using. \n    intros.\n    induction log; simpl in *; auto.\n    - repeat break_match; simpl in *; constructor; auto.\n  Qed.\n\n\n  Lemma in_import_in_trace_O :\n    forall tr k,\n      In (O k) (import tr) ->\n      exists os h,\n        In (h, inr os) tr /\\\n        exists o, In (ClientResponse (fst k) (snd k) o) os.\n  Proof using. \n    induction tr; intros; simpl in *; intuition.\n    repeat break_match; subst; intuition.\n    - find_apply_hyp_hyp. break_exists_exists.\n      intuition.\n    - simpl in *. intuition; try congruence.\n      find_apply_lem_hyp in_remove.\n      find_apply_hyp_hyp. break_exists_exists.\n      intuition.\n    - do_in_app. intuition.\n      + find_apply_lem_hyp in_dedup_was_in.\n        find_apply_lem_hyp In_filterMap.\n        break_exists. intuition.\n        break_match; try congruence.\n        find_inversion.\n        repeat eexists; intuition eauto.\n      + find_apply_lem_hyp in_remove_all_was_in.\n        find_apply_hyp_hyp. break_exists_exists.\n        intuition.\n  Qed.\n\n  Lemma in_import_in_trace_I :\n    forall tr k,\n      In (I k) (import tr) ->\n      exists h i,\n        In (h, inl (ClientRequest (fst k) (snd k) i)) tr.\n  Proof using. \n    induction tr; intros; simpl in *; intuition.\n    repeat break_match; subst.\n    - find_apply_hyp_hyp. break_exists.\n      eauto 10.\n    - simpl in *. intuition.\n      + find_inversion. simpl. eauto 10.\n      + find_apply_lem_hyp in_remove.\n        find_apply_hyp_hyp. break_exists. eauto 10.\n    - do_in_app. intuition.\n      + find_apply_lem_hyp in_dedup_was_in.\n        find_eapply_lem_hyp In_filterMap. break_exists. break_and.\n        break_match; discriminate.\n      + find_eapply_lem_hyp in_remove_all_was_in.\n        find_apply_hyp_hyp. break_exists. eauto 10.\n  Qed.\n\n  Lemma in_applied_entries_in_IR :\n    forall log e client id env,\n      eClient e = client ->\n      eId e = id ->\n      In e log ->\n      (exists o, env (client, id) = Some o) ->\n      In (IRO (client, id)) (log_to_IR env log).\n  Proof using. \n    intros.\n    induction log; simpl in *; intuition.\n    - subst. break_exists.\n      repeat break_match; intuition.\n      simpl in *.\n      subst. congruence.\n    - repeat break_match; in_crush.\n  Qed.\n\n  Theorem In_get_output' :\n    forall l client id o,\n      In (ClientResponse client id o) l ->\n      exists o', get_output' l (client, id) = Some o'.\n  Proof using. \n    intros. induction l; simpl in *; intuition.\n    - subst. break_if; simpl in *; intuition eauto.\n    - break_match; simpl in *; intuition eauto.\n      break_if; simpl in *; intuition eauto.\n  Qed.\n\n  Theorem import_get_output :\n    forall tr k,\n      In (O k) (import tr) ->\n      exists o,\n        get_output tr k = Some o.\n  Proof using. \n    intros.\n    induction tr; simpl in *; intuition.\n    repeat break_match; intuition; subst; simpl in *; intuition; try congruence;\n    try do_in_app; intuition eauto.\n    - find_apply_lem_hyp in_remove; auto.\n    - find_apply_lem_hyp in_dedup_was_in; auto.\n      find_apply_lem_hyp In_filterMap.\n      break_exists; break_match; intuition; try congruence.\n      subst. find_inversion.\n      find_apply_lem_hyp In_get_output'. break_exists; congruence.\n    - find_apply_lem_hyp in_remove_all_was_in. auto.\n  Qed.\n\n  Lemma IRO_in_IR_in_log :\n    forall k log tr,\n      In (IRO k) (log_to_IR (get_output tr) log) ->\n      exists e out,\n        eClient e = fst k /\\\n        eId e = snd k /\\\n        get_output tr k = Some out /\\\n        In e log.\n  Proof using. \n    induction log; intros; simpl in *; intuition.\n    repeat break_match; subst; simpl in *; intuition; try congruence; try find_inversion; simpl.\n    - eexists. eexists. intuition; eauto.\n    - find_apply_hyp_hyp. break_exists_exists. intuition.\n    - find_apply_hyp_hyp. break_exists_exists. intuition.\n  Qed.\n\n  Lemma get_output'_In :\n    forall l k out,\n      get_output' l k = Some out ->\n      In (ClientResponse (fst k) (snd k) out) l.\n  Proof using. \n    induction l; intros; simpl in *; intuition.\n    - discriminate.\n    - repeat break_match; subst; eauto.\n      find_inversion. break_and. subst. eauto.\n  Qed.\n\n  Lemma get_output_import_O :\n    forall tr k out,\n      get_output tr k = Some out ->\n      In (O k) (import tr).\n  Proof using. \n    induction tr; intros; simpl in *.\n    - discriminate.\n    - repeat break_match; subst; simpl; intuition eauto.\n      + right. apply remove_preserve; try discriminate. eauto.\n      + find_inversion. apply in_or_app. left.\n        find_apply_lem_hyp get_output'_In.\n        apply dedup_In.\n        eapply filterMap_In; eauto.\n        simpl. now rewrite <- surjective_pairing.\n      + apply in_or_app. right.\n        apply in_remove_all_preserve.\n        * intro. find_apply_lem_hyp in_dedup_was_in.\n          find_apply_lem_hyp In_filterMap.\n          break_exists. break_and.\n          break_match; try discriminate.\n          find_inversion.\n          find_apply_lem_hyp In_get_output'.\n          break_exists. congruence.\n        * eauto.\n  Qed.\n\n  Lemma IRU_in_IR_in_log :\n    forall k log tr,\n      In (IRU k) (log_to_IR (get_output tr) log) ->\n      exists e,\n        eClient e = fst k /\\\n        eId e = snd k /\\\n        get_output tr k = None /\\\n        In e log.\n  Proof using. \n\n    induction log; intros; simpl in *; intuition.\n    repeat break_match; subst; simpl in *; intuition; try congruence; try find_inversion; simpl.\n    - find_apply_hyp_hyp. break_exists_exists. intuition.\n    - eexists. intuition; eauto.\n    - find_apply_hyp_hyp. break_exists_exists. intuition.\n  Qed.\n\n  Lemma trace_I_in_import :\n    forall tr k h i,\n      In (h, inl (ClientRequest (fst k) (snd k) i)) tr ->\n      In (I k) (import tr).\n  Proof using. \n    induction tr; intros; simpl in *; intuition; subst.\n    - rewrite <- surjective_pairing. intuition.\n    - break_match; simpl; eauto.\n      subst.\n      destruct (key_eq_dec (n, n0) k).\n      + subst. auto.\n      + right. apply remove_preserve.\n        * congruence.\n        * eauto.\n    - apply in_or_app.\n      right.\n      apply in_remove_all_preserve.\n      + intro. find_apply_lem_hyp in_dedup_was_in.\n        find_apply_lem_hyp In_filterMap.\n        break_exists. break_and.\n        break_match; try discriminate.\n      + eauto.\n  Qed.\n\n  Lemma get_IR_input_of_log_to_IR :\n    forall env log,\n      get_IR_input_keys _ (log_to_IR env log) =\n      map (fun e => (eClient e, eId e)) log.\n  Proof using. \n    induction log; simpl; intuition.\n    repeat break_match; subst; simpl in *;\n    rewrite get_IR_input_keys_defn; auto using f_equal.\n  Qed.\n\n  Lemma get_IR_output_of_log_to_IR :\n    forall env log,\n      get_IR_output_keys _ (log_to_IR env log) =\n      map (fun e => (eClient e, eId e)) log.\n  Proof using. \n    induction log; simpl; intuition.\n    repeat break_match; subst; simpl in *;\n    repeat rewrite get_IR_output_keys_defn; auto using f_equal.\n  Qed.\n\n\n  Lemma NoDup_input_import :\n    forall tr,\n      NoDup (get_op_input_keys key (import tr)).\n  Proof using. \n    induction tr; intros.\n    - constructor.\n    - simpl. repeat break_match; subst.\n      + auto.\n      + rewrite get_op_input_keys_defn. constructor; auto.\n        * intro. find_apply_lem_hyp get_op_input_keys_sound.\n          eapply remove_In; eauto.\n        * eapply subseq_NoDup; eauto.\n          eapply subseq_get_op_input_keys.\n          auto using subseq_remove.\n      + rewrite get_op_input_keys_app.\n        rewrite get_op_input_keys_on_Os_nil.\n        * simpl.\n          eapply subseq_NoDup; eauto.\n          eapply subseq_get_op_input_keys.\n          apply subseq_remove_all.\n          apply subseq_refl.\n        * intros.\n          find_apply_lem_hyp in_dedup_was_in.\n          find_apply_lem_hyp In_filterMap.\n          break_exists.  break_and.\n          break_match; try discriminate.\n          subst. find_inversion. eauto.\n  Qed.\n\n  Lemma NoDup_output_import :\n    forall tr,\n      NoDup (get_op_output_keys key (import tr)).\n  Proof using. \n    induction tr; intros.\n    - constructor.\n    - simpl. repeat break_match; subst.\n      + auto.\n      + rewrite get_op_output_keys_defn.\n        eapply subseq_NoDup; eauto.\n        apply subseq_get_op_output_keys.\n        apply subseq_remove.\n      + rewrite get_op_output_keys_app.\n        apply NoDup_disjoint_append.\n        * apply get_op_output_keys_preserves_NoDup.\n          apply NoDup_dedup.\n        * eapply subseq_NoDup; eauto.\n          eapply subseq_get_op_output_keys.\n          apply subseq_remove_all.\n          apply subseq_refl.\n        * intros. intro.\n          repeat find_apply_lem_hyp get_op_output_keys_sound.\n          eapply in_remove_all_not_in; eauto.\n  Qed.\n\n  Lemma before_import_output_before_input :\n    forall k k' tr,\n      before (O k) (I k') (import tr) ->\n      output_before_input (fst k) (snd k) (fst k') (snd k') tr.\n  Proof using. \n    induction tr; intros; simpl in *; intuition.\n    repeat break_match; subst; simpl in *; intuition eauto; try congruence;\n    unfold output_before_input; simpl in *; intuition.\n    - right. intuition.\n      + do_bool.\n        destruct k'.  simpl in *.\n        match goal with\n          | _ : I (?x, ?y) = I (?x', ?y') -> False |- _ =>\n            destruct (eq_nat_dec x x'); destruct (eq_nat_dec y y')\n        end; subst; intuition.\n        * right. do_bool. intuition.\n        * left. do_bool. intuition.\n        * left. do_bool. intuition.\n      + apply IHtr. eauto using before_remove.\n    - break_if; intuition. right.\n      intuition. find_apply_lem_hyp before_app; [find_apply_lem_hyp before_remove_all|]; intuition eauto.\n      + find_apply_lem_hyp in_dedup_was_in.\n        find_apply_lem_hyp In_filterMap.\n        break_exists. intuition. break_match; congruence.\n      + find_apply_lem_hyp in_dedup_was_in.\n        find_apply_lem_hyp In_filterMap.\n        break_exists.\n        intuition. break_match; try congruence.\n        subst. find_inversion. simpl in *.\n        match goal with\n          | H : _ -> False |- False => apply H\n        end. eexists; eauto.\n  Qed.\n\n  Lemma has_key_true_key_of :\n    forall c i e,\n      has_key c i e = true ->\n      key_of e = (c, i).\n  Proof using. \n    intros. unfold has_key, key_of in *.\n    break_match. subst. simpl in *. repeat (do_bool; intuition).\n  Qed.\n\n  Lemma key_of_has_key_true :\n    forall c i e,\n      key_of e = (c, i) ->\n      has_key c i e = true.\n  Proof using. \n    intros. unfold has_key, key_of in *.\n    break_match. subst. simpl in *. find_inversion. repeat (do_bool; intuition).\n  Qed.\n\n  Lemma has_key_false_key_of :\n    forall c i e,\n      has_key c i e = false ->\n      key_of e <> (c, i).\n  Proof using. \n    intros. unfold has_key, key_of in *.\n    break_match. subst. simpl in *. repeat (do_bool; intuition); congruence.\n  Qed.\n\n  Lemma key_of_has_key_false :\n    forall c i e,\n      key_of e <> (c, i) ->\n      has_key c i e = false.\n  Proof using. \n    intros. unfold has_key, key_of in *.\n    break_match. subst. simpl in *. repeat (do_bool; intuition).\n    match goal with\n      | _ : (?x, ?y) = (?x', ?y') -> False |- _ =>\n        destruct (eq_nat_dec x x'); destruct (eq_nat_dec y y')\n    end; subst; intuition.\n    - right. do_bool. congruence.\n    - left. do_bool. congruence.\n    - left. do_bool. congruence.\n  Qed.\n\n  Lemma before_func_antisymmetric :\n    forall A f g l,\n      (forall x, f x = true -> g x = true -> False) ->\n      before_func(A:=A) f g l ->\n      before_func g f l ->\n      False.\n  Proof using. \n    induction l; simpl; intuition.\n    - eauto.\n    - congruence.\n    - congruence.\n  Qed.\n\n  Lemma has_key_true_same_client :\n    forall c i e,\n      has_key c i e = true ->\n      eClient e = c.\n  Proof using. \n    unfold has_key.\n    intros. destruct e.\n    simpl. do_bool. intuition. do_bool. auto.\n  Qed.\n\n  Lemma has_key_true_same_id :\n    forall c i e,\n      has_key c i e = true ->\n      eId e = i.\n  Proof using. \n    unfold has_key.\n    intros. destruct e.\n    simpl. do_bool. intuition. do_bool. auto.\n  Qed.\n\n  Lemma has_key_true_elim :\n    forall c i e,\n      has_key c i e = true ->\n      eClient e = c /\\ eId e = i.\n  Proof using. \n    intuition eauto using has_key_true_same_client, has_key_true_same_id.\n  Qed.\n\n  Lemma has_key_false_elim :\n    forall c i e,\n      has_key c i e = false ->\n      eClient e <> c \\/ eId e <> i.\n  Proof using. \n    unfold has_key.\n    intros. destruct e. simpl. do_bool. intuition (do_bool; auto).\n  Qed.\n\n  Lemma before_func_deduplicate' :\n    forall l k k' ks,\n      before_func (has_key (fst k) (snd k)) (has_key (fst k') (snd k')) l ->\n      (forall id',\n         before_func (has_key (fst k) id') (has_key (fst k) (snd k)) l ->\n         id' <= snd k) ->\n      (forall i, assoc eq_nat_dec ks (fst k) = Some i -> i < snd k) ->\n      before_func (has_key (fst k) (snd k)) (has_key (fst k') (snd k')) (deduplicate_log' l ks).\n  Proof using. \n    induction l; simpl; intros.\n    - intuition.\n    - intuition.\n      + repeat break_match; simpl; auto.\n        do_bool.\n        find_apply_lem_hyp has_key_true_elim. break_and. repeat find_rewrite.\n        assert (n < snd k) by auto. omega.\n      + repeat break_match; simpl.\n        * { destruct (has_key (fst k) (snd k) a) eqn:?; auto.\n            right. intuition. apply IHl; auto.\n            do_bool.\n            intros. destruct (eq_nat_dec (eClient a) (fst k)).\n            - repeat find_rewrite. rewrite get_set_same in *. find_inversion.\n              repeat match goal with\n                | H : context [ has_key (fst k')] |- _ => clear H\n              end.\n              find_apply_lem_hyp has_key_false_elim.\n              intuition; try congruence.\n              assert (has_key (fst k) (eId a) a = true) by eauto using has_key_intro'.\n              assert (eId a <= snd k) by auto.\n              omega.\n            - rewrite get_set_diff in * by auto. auto.\n          }\n        * do_bool. apply IHl; auto. intros.\n          { destruct (has_key (fst k) (snd k) a) eqn:?; auto.\n            find_apply_lem_hyp has_key_true_elim. break_and.\n            repeat find_rewrite. assert (n < snd k) by auto. omega.\n          }\n        * { destruct (has_key (fst k) (snd k) a) eqn:?; auto.\n            right. intuition. apply IHl; auto.\n            do_bool.\n            intros. destruct (eq_nat_dec (eClient a) (fst k)).\n            - repeat find_rewrite. rewrite get_set_same in *. find_inversion.\n              repeat match goal with\n                | H : context [ has_key (fst k')] |- _ => clear H\n              end.\n              find_apply_lem_hyp has_key_false_elim.\n              intuition; try congruence.\n              assert (has_key (fst k) (eId a) a = true) by eauto using has_key_intro'.\n              assert (eId a <= snd k) by auto.\n              omega.\n            - rewrite get_set_diff in * by auto. auto.\n          }\n  Qed.\n\n  Lemma before_func_deduplicate :\n    forall k k' l,\n      before_func (has_key (fst k) (snd k)) (has_key (fst k') (snd k')) l ->\n      (forall id',\n         before_func (has_key (fst k) id') (has_key (fst k) (snd k)) l ->\n         id' <= snd k) ->\n      before_func (has_key (fst k) (snd k)) (has_key (fst k') (snd k')) (deduplicate_log l).\n  Proof using. \n    intros.\n    apply before_func_deduplicate'; auto.\n    simpl. intros. discriminate.\n  Qed.\n\n  Lemma entries_ordered_before_log_to_IR :\n    forall k k' net failed tr,\n      step_f_star step_f_init (failed, net) tr ->\n      In (O k) (import tr) ->\n      k <> k' ->\n      entries_ordered (fst k) (snd k) (fst k') (snd k') net ->\n      before (IRO k) (IRI k')\n             (log_to_IR (get_output tr) (deduplicate_log (applied_entries (nwState net)))).\n  Proof using ogii. \n    intros. unfold entries_ordered in *.\n    remember (applied_entries (nwState net)) as l.\n    find_apply_lem_hyp before_func_deduplicate.\n    {\n      remember (deduplicate_log l) as l'; clear Heql'. clear Heql. clear l. rename l' into l.\n      induction l; simpl in *; intuition.\n      - repeat break_match; subst; simpl in *; repeat (do_bool; intuition).\n        + destruct k; simpl in *; subst. right. intuition.\n          find_inversion. simpl in *. intuition.\n        + exfalso. destruct k; subst; simpl in *.\n          find_apply_lem_hyp import_get_output. break_exists. congruence.\n      - repeat break_match; subst; simpl in *; repeat (do_bool; intuition).\n        + right. destruct k'. simpl in *. intuition; try congruence.\n          destruct (key_eq_dec k (eClient, eId)); subst; intuition.\n          right. intuition; congruence.\n        + right. destruct k'. simpl in *. intuition; try congruence.\n          destruct (key_eq_dec k (eClient, eId)); subst; intuition.\n          right. intuition; congruence.\n        + right. intuition; [find_inversion; simpl in *; intuition|].\n          right. intuition. congruence.\n        + right. intuition; [find_inversion; simpl in *; intuition|].\n          right. intuition. congruence.\n    }\n    {\n      intros. subst.\n      eapply output_greatest_id with (client := fst k) (id := snd k) in H.\n      - intros. unfold greatest_id_for_client in *.\n        destruct (le_lt_dec id' (snd k)); auto.\n        find_copy_apply_hyp_hyp.\n        exfalso. eapply before_func_antisymmetric; try eassumption.\n        unfold has_key.\n        intros. destruct x.\n        do_bool. intuition. do_bool. subst. omega.\n      - red. find_apply_lem_hyp in_import_in_trace_O.\n        break_exists_exists. intuition.\n    }\n  Qed.\n\n  Lemma input_before_output_import :\n    forall tr k,\n      before_func (is_input_with_key (fst k) (snd k))\n                  (is_output_with_key (fst k) (snd k)) tr ->\n      before (I k) (O k) (import tr).\n  Proof using. \n    intros; induction tr; simpl in *; intuition.\n    - repeat break_match; subst; simpl in *; intuition; try congruence.\n      repeat (do_bool; intuition).\n      destruct k; subst; simpl in *; intuition.\n    - repeat break_match; subst; simpl in *; intuition; try congruence.\n      + destruct k.\n        match goal with\n          | |- context [ I (?x, ?y) = I (?x', ?y') ] =>\n            destruct (op_eq_dec (I (x, y)) (I (x', y')))\n        end; subst; intuition.\n        right.\n        intuition; try congruence.\n        apply before_remove_if; intuition.\n      + break_if; try congruence.\n        apply before_app_if; [apply before_remove_all_if|]; auto.\n        * intuition. find_apply_lem_hyp in_dedup_was_in.\n          find_apply_lem_hyp In_filterMap. break_exists.\n          break_match; intuition; congruence.\n        * intuition.\n          match goal with\n            | H : _ -> False |- False => apply H\n          end.\n          find_apply_lem_hyp in_dedup_was_in.\n          find_apply_lem_hyp In_filterMap.\n          break_exists. intuition. break_match; try congruence.\n          find_inversion.\n          unfold key_in_output_list. simpl.\n          eexists; eauto.\n  Qed.\n\n  Lemma I_before_O :\n    forall failed net tr k,\n      step_f_star step_f_init (failed, net) tr ->\n      In (O k) (import tr) ->\n      before (I k) (O k) (import tr).\n  Proof using iboi. \n    intros.\n    find_apply_lem_hyp in_import_in_trace_O.\n    find_eapply_lem_hyp output_implies_input_before_output; eauto.\n    eauto using input_before_output_import.\n  Qed.\n\n  Lemma get_IR_input_keys_log_to_IR :\n    forall l env_o,\n      get_IR_input_keys key (log_to_IR env_o l) =\n      map (fun e => (eClient e, eId e)) l.\n  Proof using. \n    intros. induction l; simpl in *; intuition.\n    repeat break_match; subst; compute; simpl; f_equal; auto.\n  Qed.\n\n  Lemma get_IR_output_keys_log_to_IR :\n    forall l env_o,\n      get_IR_output_keys key (log_to_IR env_o l) =\n      map (fun e => (eClient e, eId e)) l.\n  Proof using. \n    intros. induction l; simpl in *; intuition.\n    repeat break_match; subst; compute; simpl; f_equal; auto.\n  Qed.\n\n  Lemma deduplicate_log'_ks :\n    forall l ks e id,\n      In e (deduplicate_log' l ks) ->\n      assoc eq_nat_dec ks (eClient e) = Some id ->\n      id < (eId e).\n  Proof using. \n    induction l; intros; simpl in *; intuition.\n    repeat break_match; simpl in *; do_bool; intuition; subst; eauto;\n    repeat find_rewrite; repeat find_inversion; intuition.\n    - destruct (eq_nat_dec (eClient e) (eClient a)); repeat find_rewrite.\n      * find_injection.\n        eapply IHl with (id := eId a) in H1; try omega.\n        repeat find_rewrite. eauto using get_set_same.\n      * eapply IHl with (id := id) in H1; try omega.\n        rewrite get_set_diff; auto.\n    - congruence.\n    - destruct (eq_nat_dec (eClient e) (eClient a)); repeat find_rewrite.\n      * congruence.\n      * eapply IHl with (id := id) in H1; try omega.\n        rewrite get_set_diff; auto.\n  Qed.\n\n  Lemma NoDup_deduplicate_log' :\n    forall l ks,\n      NoDup (map (fun e => (eClient e, eId e)) (deduplicate_log' l ks)).\n  Proof using. \n    induction l; intros.\n    - simpl in *. constructor.\n    - simpl in *. repeat break_match; eauto.\n      + simpl in *. constructor; eauto.\n        intuition. do_in_map. find_inversion.\n        eapply deduplicate_log'_ks with (id := eId a) in H0; try omega.\n        repeat find_rewrite.\n        rewrite get_set_same. auto.\n      + simpl in *. constructor; eauto.\n        intuition. do_in_map. find_inversion.\n        eapply deduplicate_log'_ks with (id := eId a) in H0; try omega.\n        repeat find_rewrite.\n        rewrite get_set_same. auto.\n  Qed.\n\n  Lemma NoDup_deduplicate_log :\n    forall l,\n      NoDup (map (fun e => (eClient e, eId e)) (deduplicate_log l)).\n  Proof using. \n    eauto using NoDup_deduplicate_log'.\n  Qed.\n\n  Lemma NoDup_input_log :\n    forall l env_o,\n      NoDup (get_IR_input_keys key (log_to_IR env_o (deduplicate_log l))).\n  Proof using. \n    intros.\n    rewrite get_IR_input_keys_log_to_IR.\n    eauto using NoDup_deduplicate_log.\n  Qed.\n\n  Lemma NoDup_output_log :\n    forall l env_o,\n      NoDup (get_IR_output_keys key (log_to_IR env_o (deduplicate_log l))).\n  Proof using. \n    intros.\n    rewrite get_IR_output_keys_log_to_IR.\n    eauto using NoDup_deduplicate_log.\n  Qed.\n\n  Hint Constructors exported.\n\n  Lemma exported_snoc_IO :\n    forall env_i env_o ir tr i o k,\n      exported env_i env_o ir tr ->\n      env_i k = Some i ->\n      env_o k = Some o ->\n      exported env_i env_o (ir ++ [IRI k; IRO k]) (tr ++ [(i, o)]).\n  Proof using. \n    induction 1; intros; simpl; auto.\n  Qed.\n\n  Lemma exported_snoc_IU :\n    forall env_i env_o ir tr i k o,\n      exported env_i env_o ir tr ->\n      env_i k = Some i ->\n      env_o k = None ->\n      exported env_i env_o (ir ++ [IRI k; IRU k]) (tr ++ [(i, o)]).\n  Proof using. \n    induction 1; intros; simpl; auto.\n  Qed.\n\n  Lemma log_to_IR_app :\n    forall xs ys env,\n      log_to_IR env (xs ++ ys) = log_to_IR env xs ++ log_to_IR env ys.\n  Proof using. \n    induction xs; intros; simpl; intuition.\n    repeat break_match; subst; simpl; auto using f_equal.\n  Qed.\n\n  Lemma exported_execute_log' :\n    forall env_i env_o l es tr st,\n      (forall e, In e l -> env_i (eClient e, eId e) = Some (eInput e)) ->\n      (forall xs ys e tr' st' o o0 st'',\n         l = xs ++ e :: ys ->\n         execute_log' xs st tr = (tr', st') ->\n         handler (eInput e) st' = (o, st'') ->\n         env_o (eClient e, eId e) = Some o0 ->\n         o = o0) ->\n      execute_log es = (tr, st) ->\n      exported env_i env_o (log_to_IR env_o es) tr ->\n      exported env_i env_o (log_to_IR env_o (es ++ l)) (fst (execute_log' l st tr)).\n  Proof using. \n    induction l using rev_ind; intros; simpl in *.\n    - rewrite app_nil_r.  auto.\n    - rewrite execute_log'_app. simpl. repeat break_let.\n      simpl.\n      eapply_prop_hyp execute_log execute_log; auto.\n      + find_rewrite. simpl in *.\n        rewrite <- app_ass.\n        rewrite log_to_IR_app.\n        simpl.\n        specialize (H x). concludes.\n        specialize (H0 l [] x l0 d).\n        break_match; subst; simpl in *.\n        rewrite app_nil_r.\n        break_match.\n        * specialize (H0 o o0 d0). repeat concludes.\n          apply exported_snoc_IO; congruence.\n        * apply exported_snoc_IU; auto.\n      + intros. apply H. intuition.\n      + intros. subst. eapply H0 with (ys0 := ys ++ [x]).\n        rewrite app_ass. simpl. eauto.\n        eauto.\n        eauto.\n        eauto.\n  Qed.\n\n  Lemma exported_execute_log :\n    forall env_i env_o l,\n      (forall e, In e l -> env_i (eClient e, eId e) = Some (eInput e)) ->\n      (forall xs ys e tr' st' o o0 st'',\n         l = xs ++ e :: ys ->\n         execute_log xs  = (tr', st') ->\n         handler (eInput e) st' = (o, st'') ->\n         env_o (eClient e, eId e) = Some o0 ->\n         o = o0) ->\n      exported env_i env_o (log_to_IR env_o l) (fst (execute_log l)).\n  Proof using. \n    intros.\n    unfold execute_log.\n    change (log_to_IR env_o l) with (log_to_IR env_o ([] ++ l)).\n    eapply exported_execute_log'; eauto.\n  Qed.\n\n  Definition input_correct (tr : list (name * (raft_input + list raft_output))) : Prop :=\n    (forall client id i i' h h',\n       In (h, inl (ClientRequest client id i)) tr ->\n       In (h', inl (ClientRequest client id i')) tr ->\n       i = i').\n\n  Lemma in_input_trace_get_input :\n    forall tr e,\n      input_correct tr ->\n      in_input_trace (eClient e) (eId e) (eInput e) tr ->\n      get_input tr (eClient e, eId e) = Some (eInput e).\n  Proof using. \n    unfold in_input_trace, input_correct.\n    induction tr; intros; break_exists; simpl in *; intuition; subst;\n    repeat break_match; intuition; subst; eauto 10 using f_equal.\n  Qed.\n\n  Lemma get_output_in_output_trace :\n    forall tr client id o,\n      get_output tr (client, id) = Some o ->\n      in_output_trace client id o tr.\n  Proof using. \n    intros. induction tr; simpl in *; try congruence.\n    repeat break_let. subst.\n    repeat break_match; simpl in *; intuition; subst;\n    try solve [unfold in_output_trace in *;break_exists_exists; intuition].\n    find_inversion. find_apply_lem_hyp get_output'_In.\n    repeat eexists; eauto; in_crush.\n  Qed.\n\n  Lemma NoDup_map_partition :\n    forall A B (f : A -> B) xs l y zs xs' y' zs',\n      NoDup (map f l) ->\n      l = xs ++ y :: zs ->\n      l = xs' ++ y' :: zs' ->\n      f y = f y' ->\n      xs = xs'.\n  Proof using. \n    induction xs; simpl; intros; destruct xs'.\n    - auto.\n    - subst. simpl in *. find_inversion.\n      invc H. exfalso. rewrite map_app in *. simpl in *.\n      repeat find_rewrite. intuition.\n    - subst. simpl in *. find_inversion.\n      invc H. exfalso. rewrite map_app in *. simpl in *.\n      repeat find_rewrite. intuition.\n    - subst. simpl in *. find_injection. intros. subst.\n      f_equal. eapply IHxs; eauto. solve_by_inversion.\n  Qed.\n\n  Lemma deduplicate_partition :\n    forall l xs e ys xs' e' ys',\n      deduplicate_log l = xs ++ e :: ys ->\n      deduplicate_log l = xs' ++ e' :: ys' ->\n      eClient e = eClient e' ->\n      eId e = eId e' ->\n      xs = xs'.\n  Proof using. \n    intros.\n    eapply NoDup_map_partition.\n    - apply NoDup_deduplicate_log.\n    - eauto.\n    - eauto.\n    - simpl. congruence.\n  Qed.\n\n  Lemma applied_entries_applied_implies_input_state :\n    forall net e,\n      In e (applied_entries (nwState net)) ->\n      applied_implies_input_state (eClient e) (eId e) (eInput e) net.\n  Proof using. \n    intros.\n    red. exists e.\n    intuition.\n    - red. auto.\n    - unfold applied_entries in *. break_match.\n      + find_apply_lem_hyp in_rev.\n        find_apply_lem_hyp removeAfterIndex_in.\n        eauto.\n      + simpl in *. intuition.\n  Qed.\n\n  Lemma before_func_before :\n    forall A f g l,\n      before_func f g l ->\n      forall y,\n        g y = true ->\n        exists x : A,\n          f x = true /\\\n          before x y l.\n  Proof using. \n    induction l; intros; simpl in *; intuition.\n    - eauto.\n    - find_copy_apply_hyp_hyp. break_exists_exists. intuition.\n      right. intuition. congruence.\n  Qed.\n\n  Theorem raft_linearizable' :\n    forall failed net tr,\n      input_correct tr ->\n      step_f_star step_f_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 ogii oci iboi copi aiii oiai. \n    intros.\n    exists (log_to_IR (get_output tr) (deduplicate_log (applied_entries (nwState net)))).\n    exists (fst (execute_log (deduplicate_log (applied_entries (nwState net))))).\n    exists (snd (execute_log (deduplicate_log (applied_entries (nwState net))))).\n    intuition eauto using execute_log_correct.\n    - eapply equivalent_intro; eauto using log_to_IR_good_trace, key_eq_dec.\n      + (* In O -> In IRO *)\n        intros.\n        find_copy_apply_lem_hyp in_import_in_trace_O.\n        find_eapply_lem_hyp output_implies_applied; eauto.\n        unfold in_applied_entries in *.\n        break_exists. intuition.\n        destruct k; simpl in *.\n        find_apply_lem_hyp deduplicate_log_In.\n        * break_exists. intuition.\n          repeat find_rewrite.\n          eapply in_applied_entries_in_IR; eauto.\n          apply import_get_output. auto.\n        * { eapply output_greatest_id with (client := eClient x) (id := eId x) in H0.\n            - intros. unfold greatest_id_for_client in *.\n              subst. destruct (le_lt_dec id' (eId x)); auto.\n              find_copy_apply_hyp_hyp.\n              exfalso. eapply before_func_antisymmetric; try eassumption.\n              unfold has_key.\n              intros. destruct x0.\n              do_bool. intuition. do_bool. subst. omega.\n            - red. find_apply_lem_hyp in_import_in_trace_O.\n              break_exists_exists. intuition. red.\n              simpl in *. subst. auto.\n          }\n      + (* In IRO -> In O *)\n        intros.\n        find_apply_lem_hyp IRO_in_IR_in_log. break_exists. break_and.\n        eapply get_output_import_O; eauto.\n      + (* In IRU -> In I *)\n        intros.\n        find_apply_lem_hyp IRU_in_IR_in_log. break_exists. break_and.\n        destruct k as [c id].\n        find_apply_lem_hyp deduplicate_log_In_if.\n        find_eapply_lem_hyp applied_implies_input; eauto.\n        * unfold in_input_trace in *. break_exists.\n          eauto using trace_I_in_import.\n        * simpl in *. subst.\n          auto using applied_entries_applied_implies_input_state.\n      + (* before preserved *)\n        intros.\n        assert (k <> k').\n        * intuition. subst.\n          find_copy_apply_lem_hyp before_In.\n          find_eapply_lem_hyp I_before_O; eauto.\n          find_eapply_lem_hyp before_antisymmetric; auto.\n          congruence.\n        * eauto using before_In, before_import_output_before_input, causal_order_preserved,\n          entries_ordered_before_log_to_IR.\n      + (* I before O *)\n        intros. eauto using I_before_O.\n      + (* In IRU -> not In O *)\n        intros.\n        find_apply_lem_hyp IRU_in_IR_in_log. break_exists. break_and.\n        intro.\n        find_apply_lem_hyp import_get_output.\n        break_exists. congruence.\n      + (* NoDup op input *)\n        apply NoDup_input_import.\n      + (* NoDup IR input *)\n        apply NoDup_input_log.\n      + (* NoDup op output *)\n        apply NoDup_output_import.\n      + (* NoDup IR output *)\n        apply NoDup_output_log.\n    - apply exported_execute_log.\n      + intros.\n        find_apply_lem_hyp deduplicate_log_In_if.\n        apply in_input_trace_get_input.\n        * auto.\n        * eapply applied_implies_input; eauto.\n          auto using applied_entries_applied_implies_input_state.\n      + intros.\n        find_apply_lem_hyp get_output_in_output_trace.\n        find_eapply_lem_hyp output_correct_invariant; eauto.\n        unfold output_correct in *.\n        break_exists. intuition.\n        find_eapply_lem_hyp deduplicate_partition; eauto.\n        subst.\n        repeat find_rewrite.\n        find_apply_lem_hyp app_inv_head. find_inversion.\n        unfold execute_log in *.\n        find_rewrite_lem execute_log'_app. simpl in *.\n        repeat break_let. repeat find_inversion.\n        rewrite rev_app_distr in *. simpl in *.\n        unfold value in *. find_inversion.\n        repeat find_rewrite. find_inversion. auto.\n  Qed.\nEnd RaftLinearizableProofs.", "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/RaftLinearizableProofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2872622650372018}}
{"text": "From algebra Require Export excl.\nFrom algebra Require Import upred.\nLocal Arguments valid _ _ !_ /.\nLocal Arguments validN _ _ _ !_ /.\n\nRecord auth (A : Type) : Type := Auth { authoritative : excl A ; own : A }.\nAdd Printing Constructor auth.\nArguments Auth {_} _ _.\nArguments authoritative {_} _.\nArguments own {_} _.\nNotation \"◯ a\" := (Auth ExclUnit a) (at level 20).\nNotation \"● a\" := (Auth (Excl a) ∅) (at level 20).\n\n(* COFE *)\nSection cofe.\nContext {A : cofeT}.\nImplicit Types a : excl A.\nImplicit Types b : A.\nImplicit Types x y : auth A.\n\nInstance auth_equiv : Equiv (auth A) := λ x y,\n  authoritative x ≡ authoritative y ∧ own x ≡ own y.\nInstance auth_dist : Dist (auth A) := λ n x y,\n  authoritative x ≡{n}≡ authoritative y ∧ own x ≡{n}≡ own y.\n\nGlobal Instance Auth_ne : Proper (dist n ==> dist n ==> dist n) (@Auth A).\nProof. by split. Qed.\nGlobal Instance Auth_proper : Proper ((≡) ==> (≡) ==> (≡)) (@Auth A).\nProof. by split. Qed.\nGlobal Instance authoritative_ne: Proper (dist n ==> dist n) (@authoritative A).\nProof. by destruct 1. Qed.\nGlobal Instance authoritative_proper : Proper ((≡) ==> (≡)) (@authoritative A).\nProof. by destruct 1. Qed.\nGlobal Instance own_ne : Proper (dist n ==> dist n) (@own A).\nProof. by destruct 1. Qed.\nGlobal Instance own_proper : Proper ((≡) ==> (≡)) (@own A).\nProof. by destruct 1. Qed.\n\nInstance auth_compl : Compl (auth A) := λ c,\n  Auth (compl (chain_map authoritative c)) (compl (chain_map own c)).\nDefinition auth_cofe_mixin : CofeMixin (auth A).\nProof.\n  split.\n  - intros x y; unfold dist, auth_dist, equiv, auth_equiv.\n    rewrite !equiv_dist; naive_solver.\n  - intros n; split.\n    + by intros ?; split.\n    + by intros ?? [??]; split; symmetry.\n    + intros ??? [??] [??]; split; etrans; eauto.\n  - by intros ? [??] [??] [??]; split; apply dist_S.\n  - intros n c; split. apply (conv_compl n (chain_map authoritative c)).\n    apply (conv_compl n (chain_map own c)).\nQed.\nCanonical Structure authC := CofeT auth_cofe_mixin.\n\nGlobal Instance Auth_timeless a b :\n  Timeless a → Timeless b → Timeless (Auth a b).\nProof. by intros ?? [??] [??]; split; apply: timeless. Qed.\nGlobal Instance auth_discrete : Discrete A → Discrete authC.\nProof. intros ? [??]; apply _. Qed.\nGlobal Instance auth_leibniz : LeibnizEquiv A → LeibnizEquiv (auth A).\nProof. by intros ? [??] [??] [??]; f_equal/=; apply leibniz_equiv. Qed.\nEnd cofe.\n\nArguments authC : clear implicits.\n\n(* CMRA *)\nSection cmra.\nContext {A : cmraT}.\nImplicit Types a b : A.\nImplicit Types x y : auth A.\n\nGlobal Instance auth_empty `{Empty A} : Empty (auth A) := Auth ∅ ∅.\nInstance auth_valid : Valid (auth A) := λ x,\n  match authoritative x with\n  | Excl a => own x ≼ a ∧ ✓ a\n  | ExclUnit => ✓ own x\n  | ExclBot => False\n  end.\nGlobal Arguments auth_valid !_ /.\nInstance auth_validN : ValidN (auth A) := λ n x,\n  match authoritative x with\n  | Excl a => own x ≼{n} a ∧ ✓{n} a\n  | ExclUnit => ✓{n} own x\n  | ExclBot => False\n  end.\nGlobal Arguments auth_validN _ !_ /.\nInstance auth_core : Core (auth A) := λ x,\n  Auth (core (authoritative x)) (core (own x)).\nInstance auth_op : Op (auth A) := λ x y,\n  Auth (authoritative x ⋅ authoritative y) (own x ⋅ own y).\nInstance auth_div : Div (auth A) := λ x y,\n  Auth (authoritative x ÷ authoritative y) (own x ÷ own y).\n\nLemma auth_included (x y : auth A) :\n  x ≼ y ↔ authoritative x ≼ authoritative y ∧ own x ≼ own y.\nProof.\n  split; [intros [[z1 z2] Hz]; split; [exists z1|exists z2]; apply Hz|].\n  intros [[z1 Hz1] [z2 Hz2]]; exists (Auth z1 z2); split; auto.\nQed.\nLemma authoritative_validN n (x : auth A) : ✓{n} x → ✓{n} authoritative x.\nProof. by destruct x as [[]]. Qed.\nLemma own_validN n (x : auth A) : ✓{n} x → ✓{n} own x.\nProof. destruct x as [[]]; naive_solver eauto using cmra_validN_includedN. Qed.\n\nDefinition auth_cmra_mixin : CMRAMixin (auth A).\nProof.\n  split.\n  - by intros n x y1 y2 [Hy Hy']; split; simpl; rewrite ?Hy ?Hy'.\n  - by intros n y1 y2 [Hy Hy']; split; simpl; rewrite ?Hy ?Hy'.\n  - intros n [x a] [y b] [Hx Ha]; simpl in *;\n      destruct Hx; intros ?; cofe_subst; auto.\n  - by intros n x1 x2 [Hx Hx'] y1 y2 [Hy Hy'];\n      split; simpl; rewrite ?Hy ?Hy' ?Hx ?Hx'.\n  - intros [[] ?]; rewrite /= ?cmra_included_includedN ?cmra_valid_validN;\n      naive_solver eauto using O.\n  - intros n [[] ?] ?; naive_solver eauto using cmra_includedN_S, cmra_validN_S.\n  - by split; simpl; rewrite assoc.\n  - by split; simpl; rewrite comm.\n  - by split; simpl; rewrite ?cmra_core_l.\n  - by split; simpl; rewrite ?cmra_core_idemp.\n  - intros ??; rewrite! auth_included; intros [??].\n    by split; simpl; apply cmra_core_preserving.\n  - assert (∀ n (a b1 b2 : A), b1 ⋅ b2 ≼{n} a → b1 ≼{n} a).\n    { intros n a b1 b2 <-; apply cmra_includedN_l. }\n   intros n [[a1| |] b1] [[a2| |] b2];\n     naive_solver eauto using cmra_validN_op_l, cmra_validN_includedN.\n  - by intros ??; rewrite auth_included;\n      intros [??]; split; simpl; apply cmra_op_div.\n  - intros n x y1 y2 ? [??]; simpl in *.\n    destruct (cmra_extend n (authoritative x) (authoritative y1)\n      (authoritative y2)) as (ea&?&?&?); auto using authoritative_validN.\n    destruct (cmra_extend n (own x) (own y1) (own y2))\n      as (b&?&?&?); auto using own_validN.\n    by exists (Auth (ea.1) (b.1), Auth (ea.2) (b.2)).\nQed.\nCanonical Structure authR : cmraT := CMRAT auth_cofe_mixin auth_cmra_mixin.\nGlobal Instance auth_cmra_discrete : CMRADiscrete A → CMRADiscrete authR.\nProof.\n  split; first apply _.\n  intros [[] ?]; by rewrite /= /cmra_valid /cmra_validN /=\n    -?cmra_discrete_included_iff -?cmra_discrete_valid_iff.\nQed.\n\n(** Internalized properties *)\nLemma auth_equivI {M} (x y : auth A) :\n  (x ≡ y)%I ≡ (authoritative x ≡ authoritative y ∧ own x ≡ own y : uPred M)%I.\nProof. by uPred.unseal. Qed.\nLemma auth_validI {M} (x : auth A) :\n  (✓ x)%I ≡ (match authoritative x with\n             | Excl a => (∃ b, a ≡ own x ⋅ b) ∧ ✓ a\n             | ExclUnit => ✓ own x\n             | ExclBot => False\n             end : uPred M)%I.\nProof. uPred.unseal. by destruct x as [[]]. Qed.\n\n(** The notations ◯ and ● only work for CMRAs with an empty element. So, in\nwhat follows, we assume we have an empty element. *)\nContext `{Empty A, !CMRAUnit A}.\n\nGlobal Instance auth_cmra_unit : CMRAUnit authR.\nProof.\n  split; simpl.\n  - by apply (@cmra_unit_valid A _).\n  - by intros x; constructor; rewrite /= left_id.\n  - apply _.\nQed.\nLemma auth_frag_op a b : ◯ (a ⋅ b) ≡ ◯ a ⋅ ◯ b.\nProof. done. Qed.\nLemma auth_both_op a b : Auth (Excl a) b ≡ ● a ⋅ ◯ b.\nProof. by rewrite /op /auth_op /= left_id. Qed.\n\nLemma auth_update a a' b b' :\n  (∀ n af, ✓{n} a → a ≡{n}≡ a' ⋅ af → b ≡{n}≡ b' ⋅ af ∧ ✓{n} b) →\n  ● a ⋅ ◯ a' ~~> ● b ⋅ ◯ b'.\nProof.\n  move=> Hab n [[?| |] bf1] // =>-[[bf2 Ha] ?]; do 2 red; simpl in *.\n  destruct (Hab n (bf1 ⋅ bf2)) as [Ha' ?]; auto.\n  { by rewrite Ha left_id assoc. }\n  split; [by rewrite Ha' left_id assoc; apply cmra_includedN_l|done].\nQed.\n\nLemma auth_local_update L `{!LocalUpdate Lv L} a a' :\n  Lv a → ✓ L a' →\n  ● a' ⋅ ◯ a ~~> ● L a' ⋅ ◯ L a.\nProof.\n  intros. apply auth_update=>n af ? EQ; split; last by apply cmra_valid_validN.\n  by rewrite EQ (local_updateN L) // -EQ.\nQed.\n\nLemma auth_update_op_l a a' b :\n  ✓ (b ⋅ a) → ● a ⋅ ◯ a' ~~> ● (b ⋅ a) ⋅ ◯ (b ⋅ a').\nProof. by intros; apply (auth_local_update _). Qed.\nLemma auth_update_op_r a a' b :\n  ✓ (a ⋅ b) → ● a ⋅ ◯ a' ~~> ● (a ⋅ b) ⋅ ◯ (a' ⋅ b).\nProof. rewrite -!(comm _ b); apply auth_update_op_l. Qed.\n\n(* This does not seem to follow from auth_local_update.\n   The trouble is that given ✓ (L a ⋅ a'), Lv a\n   we need ✓ (a ⋅ a'). I think this should hold for every local update,\n   but adding an extra axiom to local updates just for this is silly. *)\nLemma auth_local_update_l L `{!LocalUpdate Lv L} a a' :\n  Lv a → ✓ (L a ⋅ a') →\n  ● (a ⋅ a') ⋅ ◯ a ~~> ● (L a ⋅ a') ⋅ ◯ L a.\nProof.\n  intros. apply auth_update=>n af ? EQ; split; last by apply cmra_valid_validN.\n  by rewrite -(local_updateN L) // EQ -(local_updateN L) // -EQ.\nQed.\nEnd cmra.\n\nArguments authR : clear implicits.\n\n(* Functor *)\nDefinition auth_map {A B} (f : A → B) (x : auth A) : auth B :=\n  Auth (excl_map f (authoritative x)) (f (own x)).\nLemma auth_map_id {A} (x : auth A) : auth_map id x = x.\nProof. by destruct x; rewrite /auth_map excl_map_id. Qed.\nLemma auth_map_compose {A B C} (f : A → B) (g : B → C) (x : auth A) :\n  auth_map (g ∘ f) x = auth_map g (auth_map f x).\nProof. by destruct x; rewrite /auth_map excl_map_compose. Qed.\nLemma auth_map_ext {A B : cofeT} (f g : A → B) x :\n  (∀ x, f x ≡ g x) → auth_map f x ≡ auth_map g x.\nProof. constructor; simpl; auto using excl_map_ext. Qed.\nInstance auth_map_cmra_ne {A B : cofeT} n :\n  Proper ((dist n ==> dist n) ==> dist n ==> dist n) (@auth_map A B).\nProof.\n  intros f g Hf [??] [??] [??]; split; [by apply excl_map_cmra_ne|by apply Hf].\nQed.\nInstance auth_map_cmra_monotone {A B : cmraT} (f : A → B) :\n  CMRAMonotone f → CMRAMonotone (auth_map f).\nProof.\n  split; try apply _.\n  - intros n [[a| |] b]; rewrite /= /cmra_validN /=; try\n      naive_solver eauto using includedN_preserving, validN_preserving.\n  - by intros [x a] [y b]; rewrite !auth_included /=;\n      intros [??]; split; simpl; apply: included_preserving.\nQed.\nDefinition authC_map {A B} (f : A -n> B) : authC A -n> authC B :=\n  CofeMor (auth_map f).\nLemma authC_map_ne A B n : Proper (dist n ==> dist n) (@authC_map A B).\nProof. intros f f' Hf [[a| |] b]; repeat constructor; apply Hf. Qed.\n\nProgram Definition authRF (F : rFunctor) : rFunctor := {|\n  rFunctor_car A B := authR (rFunctor_car F A B);\n  rFunctor_map A1 A2 B1 B2 fg := authC_map (rFunctor_map F fg)\n|}.\nNext Obligation.\n  by intros F A1 A2 B1 B2 n f g Hfg; apply authC_map_ne, rFunctor_ne.\nQed.\nNext Obligation.\n  intros F A B x. rewrite /= -{2}(auth_map_id x).\n  apply auth_map_ext=>y; apply rFunctor_id.\nQed.\nNext Obligation.\n  intros F A1 A2 A3 B1 B2 B3 f g f' g' x. rewrite /= -auth_map_compose.\n  apply auth_map_ext=>y; apply rFunctor_compose.\nQed.\n\nInstance authRF_contractive F :\n  rFunctorContractive F → rFunctorContractive (authRF F).\nProof.\n  by intros ? A1 A2 B1 B2 n f g Hfg; apply authC_map_ne, rFunctor_contractive.\nQed.\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/algebra/auth.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.28726225924858956}}
{"text": "Require Import sflib.\nFrom Paco Require Import paco.\n\nRequire Import Axioms.\nRequire Import Basic.\nRequire Import DataStructure.\nRequire Import DenseOrder.\nRequire Import Language.\nRequire Import Loc.\n\nRequire Import Event.\nRequire Import Time.\n\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Mapping.\nRequire Import Pred.\nRequire Import Trace.\nRequire Import MemoryProps.\n\nSet Implicit Arguments.\n\n\nModule CompressSteps.\n  Section CompressSteps.\n    Variable (lang: language).\n\n    Inductive spatial_mem (mem_src mem_tgt: Memory.t): Prop :=\n    | spatial_mem_intro\n        loc from to\n        (SPACE: Time.lt (Memory.max_ts loc mem_tgt) from)\n        (ADD: Memory.add mem_tgt loc from to Message.reserve mem_src)\n    .\n\n    Inductive spatial_thread (e_src e_tgt: Thread.t lang): Prop :=\n    | spatial_thread_intro\n        (STATE: (Thread.state e_src) = (Thread.state e_tgt))\n        (LOCAL: (Thread.local e_src) = (Thread.local e_tgt))\n        (SC: (Thread.sc e_src) = (Thread.sc e_tgt))\n        (MEMORY: spatial_mem (Thread.memory e_src) (Thread.memory e_tgt))\n    .\n\n    Lemma spatial_memory_map mem_src mem_tgt times\n          (SPATIAL: spatial_mem mem_src mem_tgt)\n          (CLOSED: Memory.closed mem_tgt)\n      :\n        exists (f: Loc.t -> Time.t -> Time.t -> Prop),\n          (<<IDENT: map_ident_in_memory f mem_tgt>>) /\\\n          (<<MAPLT: mapping_map_lt f>>) /\\\n          (<<MEMORY: memory_map f mem_tgt mem_src>>) /\\\n          (<<COMPLETE: forall loc to (IN: List.In to (times loc)),\n              exists fto, (<<MAPPED: f loc to fto>>)>>).\n    Proof.\n      inv SPATIAL.\n      hexploit shift_map_exists.\n      { refl. }\n      { eapply SPACE. }\n      i. des.\n      exists (fun loc' => if (Loc.eq_dec loc loc') then f else eq).\n      assert (IDENT: map_ident_in_memory (fun loc' => if LocSet.Facts.eq_dec loc loc' then f else eq) mem_tgt).\n      { ii. des_ifs. eapply SAME; eauto. } splits; ss.\n      - ii. des_ifs. eapply MAPLT; eauto.\n      - econs.\n        + i. right. exists to0, from0, msg, msg. splits; auto.\n          * des_ifs. eapply SAME.\n            eapply Memory.max_ts_spec in GET. des. eauto.\n          * eapply map_ident_in_memory_closed_message; eauto.\n            inv CLOSED. eapply CLOSED0 in GET. des. auto.\n          * refl.\n          * eapply Memory.add_get1; eauto.\n        + i. erewrite Memory.add_o in GET; eauto.\n          destruct (loc_ts_eq_dec (loc0, fto) (loc, to)).\n          { ss. des; clarify. right. ii. des_ifs.\n            destruct (Time.le_lt_dec ts (Memory.max_ts loc mem_tgt)).\n            - dup l. eapply SAME in l. replace fts with ts in *.\n              + eapply TimeFacts.le_lt_lt; eauto.\n              + destruct (Time.le_lt_dec ts fts).\n                * destruct l1; auto.\n                  eapply MAPLT in H; eauto.\n                  exfalso. eapply Time.lt_strorder; eauto.\n                * eapply MAPLT in l1; eauto.\n                  exfalso. eapply Time.lt_strorder; eauto.\n            - eapply BOUND in MAP; eauto. des. auto. }\n          { guardH o. left. exists fto, ffrom, fto, ffrom. splits.\n            - eapply IDENT. eapply Memory.max_ts_spec in GET. des; auto.\n            - refl.\n            - refl.\n            - eapply IDENT. dup GET. eapply Memory.max_ts_spec in GET. des; auto.\n              eapply Memory.get_ts in GET0. des; clarify.\n              etrans; eauto. left. auto.\n            - i. econs; eauto. }\n      - i. des_ifs.\n        + eapply COMPLETE in IN; eauto.\n        + eauto.\n    Qed.\n\n    Lemma compress_steps_failure\n          e1_src e1_tgt\n          (THREAD1: spatial_thread 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          (MEM1_SRC: Memory.closed (Thread.memory e1_src))\n          (MEM1_TGT: Memory.closed (Thread.memory e1_tgt))\n          (STEPS_TGT: @Thread.steps_failure lang e1_tgt):\n      Thread.steps_failure e1_src.\n    Proof.\n      inv THREAD1. destruct e1_src, e1_tgt. ss. clarify.\n      unfold Thread.steps_failure in *. des.\n      eapply pred_steps_thread_steps in STEPS.\n      eapply pred_steps_trace_steps in STEPS. des.\n      hexploit (trace_times_list_exists tr). i. des.\n      hexploit (spatial_memory_map times MEMORY); eauto. i. des.\n      destruct e2. hexploit trace_steps_map; try apply STEPS0; try apply MEMORY0; eauto.\n      { eapply mapping_map_lt_map_le; eauto. }\n      { eapply map_ident_in_memory_bot; eauto. }\n      { eapply mapping_map_lt_map_eq; eauto. }\n      { eapply wf_time_mapped_mappable; eauto. }\n      { eapply map_ident_in_memory_local; eauto. }\n      { eapply mapping_map_lt_collapsable_unwritable; eauto. }\n      { eapply map_ident_in_memory_closed_timemap; eauto. }\n      { refl. }\n      i. des. inv FAILURE; inv STEP. inv LOCAL0. inv LOCAL1.\n      esplits.\n      - eapply thread_steps_pred_steps.\n        eapply pred_steps_trace_steps2.\n        + eapply STEPS.\n        + instantiate (1:=fun _ => True). eapply List.Forall_forall. ii.\n          eapply list_Forall2_in in H; eauto. des.\n          eapply List.Forall_forall in EVENTS; try apply IN. destruct a, x.\n          ss. des. split; auto. rewrite <- TAU.\n          eapply tevent_map_same_machine_event; eauto.\n      - econs 2. econs; eauto. econs. econs.\n        destruct lc2, flc1. inv LOCAL. ss.\n        eapply promise_consistent_mon.\n        + eapply promise_consistent_map.\n          { eapply mapping_map_lt_map_le; eauto. }\n          { eapply mapping_map_lt_map_eq; eauto. }\n          { eapply TVIEW. }\n          { eapply PROMISES. }\n          { eapply CONSISTENT. }\n        + eauto.\n        + refl.\n    Qed.\n\n    Lemma compress_steps_fulfill\n          e1_src e1_tgt\n          e2_tgt\n          (THREAD1: spatial_thread 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          (MEM1_SRC: Memory.closed (Thread.memory e1_src))\n          (MEM1_TGT: Memory.closed (Thread.memory e1_tgt))\n          (STEPS_TGT: rtc (@Thread.tau_step lang) e1_tgt e2_tgt)\n          (PROMISES_TGT: (Local.promises (Thread.local e2_tgt)) = Memory.bot):\n      exists e2_src,\n        <<STEPS_SRC: rtc (@Thread.tau_step lang) e1_src e2_src>> /\\\n                     <<PROMISES_SRC: (Local.promises (Thread.local e2_src)) = Memory.bot>>.\n    Proof.\n      inv THREAD1. destruct e1_src, e1_tgt. ss. clarify.\n      unfold Thread.steps_failure in *. des.\n      eapply pred_steps_thread_steps in STEPS_TGT.\n      eapply pred_steps_trace_steps in STEPS_TGT. des.\n      hexploit (trace_times_list_exists tr). i. des.\n      hexploit (spatial_memory_map times MEMORY); eauto. i. des.\n      destruct e2_tgt. hexploit trace_steps_map; try apply STEPS; try apply MEMORY0; eauto.\n      { eapply mapping_map_lt_map_le; eauto. }\n      { eapply map_ident_in_memory_bot; eauto. }\n      { eapply mapping_map_lt_map_eq; eauto. }\n      { eapply wf_time_mapped_mappable; eauto. }\n      { eapply map_ident_in_memory_local; eauto. }\n      { eapply mapping_map_lt_collapsable_unwritable; eauto. }\n      { eapply map_ident_in_memory_closed_timemap; eauto. }\n      { refl. }\n      i. des. esplits.\n      - eapply thread_steps_pred_steps.\n        eapply pred_steps_trace_steps2.\n        + eapply STEPS0.\n        + instantiate (1:=fun _ => True). eapply List.Forall_forall. ii.\n          eapply list_Forall2_in in H; eauto. des.\n          eapply List.Forall_forall in EVENTS; try apply IN. destruct a, x.\n          ss. des. split; auto. inv EVENT; ss.\n      - ss. inv LOCAL. rewrite PROMISES_TGT in *.\n        eapply bot_promises_map; eauto.\n    Qed.\n  End CompressSteps.\nEnd CompressSteps.\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/CompressSteps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.28726225924858956}}
{"text": "Require Import CatSem.CAT.monad_h_module.\nRequire Import CatSem.CAT.cat_INDEXED_TYPE.\nRequire Import CatSem.CAT.retype_functor.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nUnset Automatic Introduction.\n\nSection f.\n\nVariables T U : Type.\n\nVariable f : T -> U.\n\nVariable P : Monad (ITYPE U).\n\nInductive f_P (V : ITYPE T)(t : T) : Type :=\n  | copy : P (retype f V) (f t) -> f_P V t.\n\nDefinition inv : forall V t, f_P V t -> P (retype f V) (f t). \nintros.\ndestruct X.\napply f0.\nDefined.\n\nHint Resolve copy ctype.\n\nNotation \"' V\" := (retype _ V) (at level 20).\n\n\n\nDefinition bla  V W (x : forall t : T, V t -> f_P W t):\n    forall t : U, (retype f V) t -> P (retype f W) t.\nintros.\ndestruct X.\napply inv.\nauto.\nDefined.\n\nObligation Tactic := idtac.\n\nProgram Instance f_P_Mon_s : Monad_struct (ITYPE T)(f_P).\nNext Obligation.\n  simpl.\n  intros.\n  apply copy.\n  apply (weta (Monad_struct := P)).\n  apply ctype.\n  apply X.\nDefined.\nNext Obligation.\n  simpl.\n  intros V W x.\n  set (Z := kleisli (Monad_struct := P)).\n  set (z := Z (retype f V) (retype f W)).\n  simpl in *.\n  set (z':= z (bla x)).\n  intros.\n  \n  destruct X.\n  apply copy.\n  apply z'.\n  apply f0.\nDefined.\nNext Obligation.\nProof.\n  unfold Proper,f_P_Mon_s_obligation_2.\n  red.\n  intros V W g g' H.\n  intros t x.\n  induction x.\n  apply f_equal.\n  apply (kleisli_oid (Monad_struct := P)).\n  simpl.\n  intros t0 x.\n  induction x.\n  simpl.\n  rewrite H.\n  auto.\nQed.\nNext Obligation.\nProof.\n  simpl.\n  intros.\n  assert (H:=etakl P).\n  simpl in *.\n  rewrite H.\n  simpl.\n  generalize (f0 t x).\n  intros.\n  induction f1.\n  auto.\nQed.\nNext Obligation.\nProof.\n  simpl.\n  intros V t x.\n  induction x.\n  simpl.\n  apply f_equal.\n  assert (H:=kleta P).\n  simpl in H.\n  unfold f_P_Mon_s_obligation_1.\n  simpl in *.\n  rewrite <- H.\n  apply (kl_eq P).\n  simpl.\n  intros.\n  induction x.\n  simpl.\n  auto.\nQed.\nNext Obligation.\nProof.\n  simpl.\n  intros.\n  induction x.\n  simpl.\n  apply f_equal.\n  assert (H:=dist (Monad_struct := P)).\n  simpl in H.\n  rewrite H.\n  apply (kl_eq P).\n  simpl.\n  intros.\n  induction x.\n  simpl.\n  generalize (f0 t0 v).\n  intros f2.\n  induction f2.\n  simpl.\n  auto.\nQed.\n\nDefinition f_P_Mon := Build_Monad f_P_Mon_s.\n\n\nDefinition bla2:\n(forall c : ITYPE T,\n  (RETYPE (U:=T) (U':=U) f) (f_P_Mon c) ---> \n       P ((RETYPE (U:=T) (U':=U) f) c)).\nintros V u x.\nsimpl in *.\ninduction x.\ninduction v.\napply f0.\nDefined.\n\nProgram Instance pb_mon_s : \n   gen_Monad_Hom_struct (P:=f_P_Mon) (Q:=P) (F0:=RETYPE f) bla2.\nNext Obligation.\nProof.\n  simpl.\n  intros V W g u x.\n  induction x.\n  simpl.\n  induction v.\n  simpl.\n  apply (kl_eq P).\n  simpl.\n  intros t0 x.\n  induction x.\n  simpl.\n  generalize (g t0 v).\n  intros.\n  induction f1.\n  simpl.\n  auto.\nQed.\nNext Obligation.\nProof.\n  simpl.\n  intros V t x.\n  induction x.\n  simpl.\n  auto.\nQed.\n\nDefinition pb_mon := Build_gen_Monad_Hom pb_mon_s.\n\nVariable W : Monad (ITYPE T).\n\nVariable r : gen_Monad_Hom W P (RETYPE f).\n\nDefinition car : (forall c : ITYPE T, W c ---> f_P_Mon c).\nsimpl.\nintros.\nset (r' := r c).\nsimpl in *.\napply copy.\napply r. simpl.\napply (ctype _ X).\nDefined.\n(*\nProgram Instance fac : Monad_Hom_struct \n      (P := W) (Q := f_P_Mon) car.\nNext Obligation.\nProof.\n  simpl.\n  intros.\n  unfold car.\n  apply f_equal.\n  assert (H:=gen_monad_hom_kl (gen_Monad_Hom_struct := r)).\n  simpl in H.\n  unfold retype_map in H.\n  simpl in H.\n  rewrite <- H.\n  simpl.\n*)\nEnd f.\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/COMP/f_induced_monad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.661922862511608, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2872622534599772}}
{"text": "(*! Language | Continuation-passing semantics and weakest precondition calculus !*)\n\nRequire Import CompactSemantics.\nRequire Import Magic.\n\nSection CPS.\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\n  Context {REnv: Env reg_t}.\n\n  Notation Log := (Log R REnv).\n\n  Notation rule := (rule pos_t var_t fn_name_t R Sigma).\n  Notation action := (action pos_t var_t fn_name_t R Sigma).\n  Notation scheduler := (scheduler pos_t rule_name_t).\n\n  Definition tcontext (sig: tsig var_t) :=\n    context (fun k_tau => type_denote (snd k_tau)) sig.\n\n  Definition acontext (sig argspec: tsig var_t) :=\n    context (fun k_tau => action sig (snd k_tau)) argspec.\n\n  Definition interp_continuation A sig R := option (Log * R * (tcontext sig)) -> A.\n  Definition action_continuation A sig tau := interp_continuation A sig (type_denote tau).\n  Definition rule_continuation A := option Log -> A.\n  Definition scheduler_continuation A := Log -> A.\n  Definition cycle_continuation A := REnv.(env_t) R -> A.\n\n  (* FIXME what's the right terminology for interpreter? *)\n  Definition action_interpreter A sig := forall (Gamma: tcontext sig) (action_log: Log), A.\n  Definition interpreter A := forall (log: Log), A.\n\n  (* Definition wp_bind (p: Log * tau * (tcontext sig) -> Prop) p' := *)\n  (*   fun res => *)\n  (*     match res with *)\n  (*     | Some res => p res *)\n  (*     | None => p None *)\n  (*     end *)\n\n  (* FIXME monad *)\n\n  Section Action.\n    Context (r: REnv.(env_t) R).\n    Context (sigma: forall f, Sig_denote (Sigma f)).\n\n    Section Args.\n      Context (interp_action_cps:\n                 forall {sig: tsig var_t} {tau}\n                   (a: action sig tau)\n                   {A} (k: action_continuation A sig tau),\n                 action_interpreter A sig).\n\n      Fixpoint interp_args'_cps\n               {sig: tsig var_t}\n               {argspec: tsig var_t}\n               (args: acontext sig argspec)\n               {A} (k: interp_continuation A sig (tcontext argspec))\n        : action_interpreter A sig :=\n        match args in context _ argspec return interp_continuation A sig (tcontext argspec) -> action_interpreter A sig with\n        | CtxEmpty => fun k Gamma l => k (Some (l, CtxEmpty, Gamma))\n        | @CtxCons _ _ argspec k_tau arg args =>\n          fun k =>\n            interp_args'_cps\n              args\n              (fun res =>\n                 match res with\n                 | Some (l, ctx, Gamma) =>\n                   interp_action_cps _ _ arg _\n                                     (fun res =>\n                                        match res with\n                                        | Some (l, v, Gamma) => k (Some (l, CtxCons k_tau v ctx, Gamma))\n                                        | None => k None\n                                        end) Gamma l\n                 | None => k None\n                 end)\n        end k.\n    End Args.\n\n    Fixpoint interp_action_cps\n             {sig tau}\n             (L: Log)\n             (a: action sig tau)\n             {A} (k: action_continuation A sig tau)\n    : action_interpreter A sig :=\n      let cps {sig tau} a {A} k := @interp_action_cps sig tau L a A k in\n      match a in TypedSyntax.action _ _ _ _ _ ts tau return (action_continuation A ts tau -> action_interpreter A ts)  with\n      | Fail tau => fun k Gamma l => k None\n      | Var m => fun k Gamma l => k (Some (l, cassoc m Gamma, Gamma))\n      | Const cst => fun k Gamma l => k (Some (l, cst, Gamma))\n      | Seq r1 r2 =>\n        fun k =>\n          cps r1 (fun res =>\n                    match res with\n                    | Some (l, v, Gamma) => cps r2 k Gamma l\n                    | None => k None\n                    end)\n      | Assign m ex =>\n        fun k =>\n          cps ex (fun res =>\n                    match res with\n                    | Some (l, v, Gamma) => k (Some (l, Ob, creplace m v Gamma))\n                    | None => k None\n                    end)\n      | Bind var ex body =>\n        fun k =>\n          cps ex (fun res =>\n                    match res with\n                    | Some (l, v, Gamma) =>\n                      cps body (fun res =>\n                                  match res with\n                                  | Some (l, v, Gamma) =>\n                                    k (Some (l, v, ctl Gamma))\n                                  | None =>\n                                    k None\n                                  end) (CtxCons (var, _) v Gamma) l\n                    | None => k None\n                    end)\n      | If cond tbranch fbranch =>\n        fun k =>\n          cps cond (fun res =>\n                      match res with\n                      | Some (l, v, Gamma) =>\n                        if Bits.single v then cps tbranch k Gamma l\n                        else cps fbranch k Gamma l\n                      | None => k None\n                      end)\n      | Read P0 idx =>\n        fun k Gamma l =>\n          if may_read0 L idx then\n            k (Some (Environments.update\n                       REnv l idx\n                       (fun rl => {| lread0 := true; lread1 := rl.(lread1);\n                                  lwrite0 := rl.(lwrite0); lwrite1 := rl.(lwrite1) |}),\n                     REnv.(getenv) r idx,\n                     Gamma))\n          else k None\n      | Read P1 idx =>\n        fun k Gamma l =>\n          if may_read1 L idx then\n            k (Some (Environments.update\n                       REnv l idx\n                       (fun rl => {| lread0 := rl.(lread1); lread1 := true;\n                                  lwrite0 := rl.(lwrite0); lwrite1 := rl.(lwrite1) |}),\n                     match (REnv.(getenv) l idx).(lwrite0), (REnv.(getenv) L idx).(lwrite0) with\n                     | Some v, _ => v\n                     | _, Some v => v\n                     | _, _ => REnv.(getenv) r idx\n                     end,\n                     Gamma))\n          else k None\n      | Write P0 idx value =>\n        fun k =>\n          cps value (fun res =>\n                       match res with\n                       | Some (l, v, Gamma) =>\n                         if may_write0 L l idx then\n                           k (Some (Environments.update\n                                      REnv l idx\n                                      (fun rl => {| lread0 := rl.(lread1); lread1 := rl.(lread1);\n                                                 lwrite0 := Some v; lwrite1 := rl.(lwrite1) |}),\n                                    Ob, Gamma))\n                         else\n                           k None\n                       | None => k None\n                       end)\n      | Write P1 idx value =>\n        fun k =>\n          cps value (fun res =>\n                       match res with\n                       | Some (l, v, Gamma) =>\n                         if may_write1 L l idx then\n                           k (Some (Environments.update\n                                      REnv l idx\n                                      (fun rl => {| lread0 := rl.(lread1); lread1 := rl.(lread1);\n                                                 lwrite0 := rl.(lwrite0); lwrite1 := Some v |}),\n                                    Ob, Gamma))\n                         else\n                           k None\n                       | None => k None\n                       end)\n      | Unop fn arg1 =>\n        fun k =>\n          cps arg1 (fun res =>\n                      match res with\n                      | Some (l, v, Gamma) =>\n                        k (Some (l, (PrimSpecs.sigma1 fn) v, Gamma))\n                      | None => k None\n                      end)\n      | Binop fn arg1 arg2 =>\n        fun k =>\n          cps arg1 (fun res =>\n                      match res with\n                      | Some (l, v1, Gamma) =>\n                        cps arg2 (fun res =>\n                                    match res with\n                                    | Some (l, v2, Gamma) =>\n                                      k (Some (l, (PrimSpecs.sigma2 fn) v1 v2, Gamma))\n                                    | None => k None\n                                    end) Gamma l\n                      | None => k None\n                      end)\n      | ExternalCall fn arg =>\n        fun k =>\n          cps arg (fun res =>\n                     match res with\n                     | Some (l, v, Gamma) =>\n                       k (Some (l, (sigma fn) v, Gamma))\n                     | None => k None\n                     end)\n      | InternalCall fn args body =>\n        fun k =>\n          interp_args'_cps (@cps) args\n                           (fun res =>\n                              match res with\n                              | Some (l, argvals, Gamma) =>\n                                cps body (fun res =>\n                                            match res with\n                                            | Some (l, v, _) =>\n                                              k (Some (l, v, Gamma))\n                                            | None => k None\n                                            end)\n                                    argvals l\n                              | None => k None\n                              end)\n      | APos pos a => fun k => cps a k\n      end k.\n\n    Definition interp_rule_cps (rl: rule) {A} (k: rule_continuation A) : interpreter A :=\n      fun L =>\n        interp_action_cps L rl (fun res =>\n                                  match res with\n                                  | Some (l, _, _) => k (Some l)\n                                  | None => k None\n                                  end) CtxEmpty log_empty.\n  End Action.\n\n  Section Scheduler.\n    Context (r: REnv.(env_t) R).\n    Context (sigma: forall f, Sig_denote (Sigma f)).\n    Context (rules: rule_name_t -> rule).\n\n    Fixpoint interp_scheduler'_cps\n             (s: scheduler)\n             {A} (k: scheduler_continuation A)\n             {struct s} : interpreter A :=\n      let interp_try rl s1 s2 : interpreter A :=\n          fun L =>\n            interp_rule_cps r sigma (rules rl)\n                            (fun res =>\n                               match res with\n                               | Some l => interp_scheduler'_cps s1 k (log_app l L)\n                               | None => interp_scheduler'_cps s2 k L\n                               end) L in\n      match s with\n      | Done => k\n      | Cons r s => interp_try r s s\n      | Try r s1 s2 => interp_try r s1 s2\n      | SPos _ s => interp_scheduler'_cps s k\n      end.\n\n    Definition interp_scheduler_cps\n               (s: scheduler)\n               {A} (k: scheduler_continuation A) : A :=\n      interp_scheduler'_cps s k log_empty.\n  End Scheduler.\n\n  Definition interp_cycle_cps (sigma: forall f, Sig_denote (Sigma f)) (rules: rule_name_t -> rule)\n             (s: scheduler) (r: REnv.(env_t) R)\n             {A} (k: _ -> A) :=\n    interp_scheduler_cps r sigma rules s (fun L => k (commit_update r L)).\n\n  Section WP.\n    Context (r: REnv.(env_t) R).\n    Context (sigma: forall f, Sig_denote (Sigma f)).\n\n    Definition action_precondition := action_interpreter Prop.\n    Definition action_postcondition := action_continuation Prop.\n    Definition precondition := interpreter Prop.\n    Definition rule_postcondition := rule_continuation Prop.\n    Definition scheduler_postcondition := scheduler_continuation Prop.\n    Definition cycle_postcondition := cycle_continuation Prop.\n\n    Definition wp_action {sig tau} (L: Log) (a: action sig tau) (post: action_postcondition sig tau) : action_precondition sig :=\n      interp_action_cps r sigma L a post.\n\n    Definition wp_rule (rl: rule) (post: rule_postcondition) : precondition :=\n      interp_rule_cps r sigma rl post.\n\n    Definition wp_scheduler (rules: rule_name_t -> rule) (s: scheduler) (post: scheduler_postcondition) : Prop :=\n      interp_scheduler_cps r sigma rules s post.\n\n    Definition wp_cycle (rules: rule_name_t -> rule) (s: scheduler) r (post: cycle_postcondition) : Prop :=\n      interp_cycle_cps sigma rules s r post.\n  End WP.\n\n  Section Proofs.\n    Context (r: REnv.(env_t) R).\n    Context (sigma: forall f, Sig_denote (Sigma f)).\n\n    Section Args.\n      Context (IHa : forall (sig : tsig var_t) (tau : type) (L : Log) (a : action sig tau) (A : Type) (k : option (Log * tau * tcontext sig) -> A)\n                       (Gamma : tcontext sig) (l : Log), interp_action_cps r sigma L a k Gamma l = k (interp_action r sigma Gamma L l a)).\n\n      Lemma interp_args'_cps_correct :\n        forall L {sig} {argspec} args Gamma l {A} (k: interp_continuation A sig (tcontext argspec)),\n          interp_args'_cps (fun sig tau a A k => interp_action_cps r sigma L a k) args k Gamma l =\n          k (interp_args r sigma Gamma L l args).\n      Proof.\n        induction args; cbn; intros.\n        - reflexivity.\n        - rewrite IHargs.\n          destruct (interp_args r sigma Gamma L l args) as [((?, ?), ?) | ]; cbn; try reflexivity.\n          rewrite IHa.\n          destruct (interp_action r sigma _ L _ _) as [((?, ?), ?) | ]; cbn; reflexivity.\n      Defined.\n    End Args.\n\n    Lemma interp_action_cps_correct:\n      forall {sig: tsig var_t}\n        {tau}\n        (L: Log)\n        (a: action sig tau)\n        {A} (k: _ -> A)\n        (Gamma: tcontext sig)\n        (l: Log),\n        interp_action_cps r sigma L a k Gamma l =\n        k (interp_action r sigma Gamma L l a).\n    Proof.\n      fix IHa 4; destruct a; cbn; intros.\n      all: repeat match goal with\n                  | _ => progress simpl\n                  | [ H: context[_ = _] |- _ ] => rewrite H\n                  | [  |- context[interp_action] ] => destruct interp_action as [((?, ?), ?) | ]\n                  | [  |- context[match ?x with _ => _ end] ] => destruct x\n                  | _ => rewrite interp_args'_cps_correct\n                  | _ => reflexivity || assumption\n                  end.\n    Qed.\n\n    Lemma interp_action_cps_correct_rev:\n      forall {sig: tsig var_t}\n        {tau}\n        (L: Log)\n        (a: action sig tau)\n        (Gamma: tcontext sig)\n        (l: Log),\n        interp_action r sigma Gamma L l a =\n        interp_action_cps r sigma L a id Gamma l.\n    Proof.\n      intros; rewrite interp_action_cps_correct; reflexivity.\n    Qed.\n\n    Lemma interp_rule_cps_correct:\n      forall (L: Log)\n        (a: rule)\n        {A} (k: _ -> A),\n        interp_rule_cps r sigma a k L =\n        k (interp_rule r sigma L a).\n    Proof.\n      unfold interp_rule, interp_rule_cps; intros.\n      rewrite interp_action_cps_correct.\n      destruct interp_action as [((?, ?), ?) | ]; reflexivity.\n    Qed.\n\n    Lemma interp_rule_cps_correct_rev:\n      forall (L: Log)\n        (a: rule),\n        interp_rule r sigma L a =\n        interp_rule_cps r sigma a id L.\n    Proof.\n      intros; rewrite interp_rule_cps_correct; reflexivity.\n    Qed.\n\n    Lemma interp_scheduler'_cps_correct:\n      forall (rules: rule_name_t -> rule)\n        (s: scheduler)\n        (L: Log)\n        {A} (k: _ -> A),\n        interp_scheduler'_cps r sigma rules s k L =\n        k (interp_scheduler' r sigma rules L s).\n    Proof.\n      induction s; cbn; intros.\n      all: repeat match goal with\n                  | _ => progress simpl\n                  | _ => rewrite interp_rule_cps_correct\n                  | [ H: context[_ = _] |- _ ] => rewrite H\n                  | [  |- context[interp_rule] ] => destruct interp_action as [((?, ?), ?) | ]\n                  | [  |- context[match ?x with _ => _ end] ] => destruct x\n                  | _ => reflexivity\n                  end.\n    Qed.\n\n    Lemma interp_scheduler_cps_correct:\n      forall (rules: rule_name_t -> rule)\n        (s: scheduler)\n        {A} (k: _ -> A),\n        interp_scheduler_cps r sigma rules s k =\n        k (interp_scheduler r sigma rules s).\n    Proof.\n      intros; apply interp_scheduler'_cps_correct.\n    Qed.\n\n    Lemma interp_cycle_cps_correct:\n      forall (rules: rule_name_t -> rule)\n        (s: scheduler)\n        {A} (k: _ -> A),\n        interp_cycle_cps sigma rules s r k =\n        k (interp_cycle sigma rules s r).\n    Proof.\n      unfold interp_cycle, interp_cycle_cps; intros; rewrite interp_scheduler_cps_correct.\n      reflexivity.\n    Qed.\n\n    Lemma interp_cycle_cps_correct_rev:\n      forall (rules: rule_name_t -> rule)\n        (s: scheduler),\n        interp_cycle sigma rules s r =\n        interp_cycle_cps sigma rules s r id.\n    Proof.\n      intros; rewrite interp_cycle_cps_correct; reflexivity.\n    Qed.\n\n    Section WP.\n      Lemma wp_action_correct:\n        forall {sig: tsig var_t}\n          {tau}\n          (Gamma: tcontext sig)\n          (L: Log)\n          (l: Log)\n          (a: action sig tau)\n          (post: action_postcondition sig tau),\n          wp_action r sigma L a post Gamma l <->\n          post (interp_action r sigma Gamma L l a).\n      Proof.\n        intros; unfold wp_action; rewrite interp_action_cps_correct; reflexivity.\n      Qed.\n\n      Lemma wp_rule_correct:\n        forall (L: Log)\n          (rl: rule)\n          (post: rule_postcondition),\n          wp_rule r sigma rl post L <->\n          post (interp_rule r sigma L rl).\n      Proof.\n        intros; unfold wp_rule; rewrite interp_rule_cps_correct; reflexivity.\n      Qed.\n\n      Lemma wp_scheduler_correct:\n        forall (rules: rule_name_t -> rule)\n          (s: scheduler)\n          (post: scheduler_postcondition),\n          wp_scheduler r sigma rules s post <->\n          post (interp_scheduler r sigma rules s).\n      Proof.\n        intros; unfold wp_scheduler; rewrite interp_scheduler_cps_correct; reflexivity.\n      Qed.\n\n      Lemma wp_cycle_correct:\n        forall (rules: rule_name_t -> rule)\n          (s: scheduler)\n          (post: cycle_postcondition),\n          wp_cycle sigma rules s r post <->\n          post (interp_cycle sigma rules s r).\n      Proof.\n        intros; unfold wp_cycle; rewrite interp_cycle_cps_correct; reflexivity.\n      Qed.\n    End WP.\n  End Proofs.\nEnd CPS.\n\nArguments interp_action_cps\n          {pos_t var_t fn_name_t reg_t ext_fn_t}\n          {R Sigma} {REnv} r sigma\n          {sig tau} L !a / A k.\n\nArguments interp_rule_cps\n          {pos_t var_t fn_name_t reg_t ext_fn_t}\n          {R Sigma} {REnv} r sigma\n          !rl / {A} k.\n\nArguments interp_scheduler_cps\n          {pos_t var_t fn_name_t rule_name_t reg_t ext_fn_t}\n          {R Sigma} {REnv} r sigma\n          rules !s / {A} k : assert.\n\nArguments interp_cycle_cps\n          {pos_t var_t fn_name_t rule_name_t reg_t ext_fn_t}\n          {R Sigma} {REnv} sigma\n          rules !s r / {A} k : assert.\n\nArguments wp_action\n          {pos_t var_t fn_name_t reg_t ext_fn_t}\n          {R Sigma} {REnv} r sigma\n          {sig tau} L !a post / Gamma action_log : assert.\n\nArguments wp_rule\n          {pos_t var_t fn_name_t reg_t ext_fn_t}\n          {R Sigma} {REnv} r sigma\n          !rl / post.\n\nArguments wp_scheduler\n          {pos_t var_t fn_name_t rule_name_t reg_t ext_fn_t}\n          {R Sigma} {REnv} r sigma\n          rules !s / post : assert.\n\nArguments wp_cycle\n          {pos_t var_t fn_name_t rule_name_t reg_t ext_fn_t}\n          {R Sigma} {REnv} sigma\n          rules !s r / post : assert.\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/CPS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2872323464477599}}
{"text": "(* Contribution to the Coq Library   V6.3 (July 1999)                    *)\n\n(****************************************************************************)\n(*                 The Calculus of Inductive Constructions                  *)\n(*                                                                          *)\n(*                                Projet Coq                                *)\n(*                                                                          *)\n(*                     INRIA                        ENS-CNRS                *)\n(*              Rocquencourt                        Lyon                    *)\n(*                                                                          *)\n(*                                Coq V5.10                                 *)\n(*                              Nov 25th 1994                               *)\n(*                                                                          *)\n(****************************************************************************)\n(*                              resoudPC_SL.v                               *)\n(****************************************************************************)\n\n\n      (* confluence locale de sigma_lift: resolution des paires critiques *)\n\nRequire Import TS.\nRequire Import sur_les_relations.\nRequire Import sigma_lift.\nRequire Import determinePC_SL.\n\n(*** app ***)\n\nGoal\nforall a b : terms,\nexists u : terms,\n  e_relSLstar _ (app (env a id) (env b id)) u /\\ e_relSLstar _ (app a b) u.\nintros; exists (app a b); split; red in |- *.\napply star_trans1 with (app a (env b id)); auto.\nauto.\nSave PC_app_id.\nHint Resolve PC_app_id.\n\nGoal\nforall (a a' b : terms) (s : sub_explicits),\ne_relSL _ a a' ->\nexists u : terms,\n  e_relSLstar _ (app (env a s) (env b s)) u /\\\n  e_relSLstar _ (env (app a' b) s) u.\nintros; exists (app (env a' s) (env b s)); auto 6.\nSave PC1_app_ctxt_l.\nHint Resolve PC1_app_ctxt_l.\n\nGoal\nforall (a b b' : terms) (s : sub_explicits),\ne_relSL _ b b' ->\nexists u : terms,\n  e_relSLstar _ (app (env a s) (env b s)) u /\\\n  e_relSLstar _ (env (app a b') s) u.\nintros; exists (app (env a s) (env b' s)); auto 6.\nSave PC2_app_ctxt_l.\nHint Resolve PC2_app_ctxt_l.\n\nGoal\nforall (a b : terms) (s s' : sub_explicits),\ne_relSL _ s s' ->\nexists u : terms,\n  e_relSLstar _ (app (env a s) (env b s)) u /\\\n  e_relSLstar _ (env (app a b) s') u.\nintros; exists (app (env a s') (env b s')); split; red in |- *.\napply star_trans1 with (app (env a s') (env b s)); auto.\nauto.\nSave PC_app_ctxt_r.\nHint Resolve PC_app_ctxt_r.\n\nGoal\nforall (a b x' : terms) (s : sub_explicits),\ne_relSL _ (app a b) x' ->\nexists u : terms,\n  e_relSLstar _ (app (env a s) (env b s)) u /\\ e_relSLstar _ (env x' s) u.\nintros a b x' s H; pattern x' in |- *; apply case_SLapp with a b; auto.\nSave PC_app_ctxt_l.\nHint Resolve PC_app_ctxt_l.\n\n(*** lambda ***)\n\nGoal\nforall a : terms,\nexists u : terms,\n  e_relSLstar _ (lambda (env a (lift id))) u /\\ e_relSLstar _ (lambda a) u.\nintro; exists (lambda a); split; red in |- *.\napply star_trans1 with (lambda (env a id)); auto.\nauto.\nSave PC_lambda_id.\nHint Resolve PC_lambda_id.\n\nGoal\nforall (a x' : terms) (s : sub_explicits),\ne_relSL _ (lambda a) x' ->\nexists u : terms,\n  e_relSLstar _ (lambda (env a (lift s))) u /\\ e_relSLstar _ (env x' s) u.\nintros a x' s H; pattern x' in |- *; apply case_SLlambda with a; intros.\n2: assumption.\nexists (lambda (env a' (lift s))); auto 6.\nSave PC_lambda_ctxt_l.\nHint Resolve PC_lambda_ctxt_l.\n\nGoal\nforall (a : terms) (s s' : sub_explicits),\ne_relSL _ s s' ->\nexists u : terms,\n  e_relSLstar _ (lambda (env a (lift s))) u /\\\n  e_relSLstar _ (env (lambda a) s') u.\nintros; exists (lambda (env a (lift s'))); auto 8.\nSave PC_lambda_ctxt_r.\nHint Resolve PC_lambda_ctxt_r.\n\n(*** Clos ***)\n\nGoal\nforall (a : terms) (s : sub_explicits),\nexists u : terms,\n  e_relSLstar _ (env a (comp s id)) u /\\ e_relSLstar _ (env a s) u.\nintros; exists (env a s); split; red in |- *; auto.\nSave PC1_clos_id.\nHint Resolve PC1_clos_id.\n\nGoal\nforall (a b : terms) (s t : sub_explicits),\nexists u : terms,\n  e_relSLstar _ (env (app a b) (comp s t)) u /\\\n  e_relSLstar _ (env (app (env a s) (env b s)) t) u.\nintros; exists (app (env a (comp s t)) (env b (comp s t))); split;\n red in |- *.\nauto.\napply star_trans1 with (app (env (env a s) t) (env (env b s) t)).\nauto.\napply star_trans1 with (app (env a (comp s t)) (env (env b s) t)); auto.\nSave PC_clos_app.\nHint Resolve PC_clos_app.\n\nGoal\nforall (a : terms) (s t : sub_explicits),\nexists u : terms,\n  e_relSLstar _ (env (lambda a) (comp s t)) u /\\\n  e_relSLstar _ (env (lambda (env a (lift s))) t) u.\nintros; exists (lambda (env a (lift (comp s t)))); split; red in |- *.\nauto.\napply star_trans1 with (lambda (env (env a (lift s)) (lift t))).\nauto.\napply star_trans1 with (lambda (env a (comp (lift s) (lift t)))); auto 6.\nSave PC_clos_lambda.\nHint Resolve PC_clos_lambda.\n\nGoal\nforall (a : terms) (s s1 t : sub_explicits),\nexists u : terms,\n  e_relSLstar _ (env (env a s1) (comp s t)) u /\\\n  e_relSLstar _ (env (env a (comp s1 s)) t) u.\nintros; exists (env a (comp s1 (comp s t))); split; red in |- *.\nauto.\napply star_trans1 with (env a (comp (comp s1 s) t)); auto.\nSave PC_clos_clos.\nHint Resolve PC_clos_clos.\n\nGoal\nforall (n : nat) (t : sub_explicits),\nexists u : terms,\n  e_relSLstar _ (env (var n) (comp shift t)) u /\\\n  e_relSLstar _ (env (var (S n)) t) u.\nintros; exists (env (var (S n)) t); auto 6.\nSave PC_clos_varshift1.\nHint Resolve PC_clos_varshift1.\n\nGoal\nforall (n : nat) (s t : sub_explicits),\nexists u : terms,\n  e_relSLstar _ (env (var n) (comp (comp shift s) t)) u /\\\n  e_relSLstar _ (env (env (var (S n)) s) t) u.\nintros; exists (env (var (S n)) (comp s t)); split; red in |- *.\napply star_trans1 with (env (var n) (comp shift (comp s t))); auto.\nauto.\nSave PC_clos_varshift2.\nHint Resolve PC_clos_varshift2.\n\nGoal\nforall (a : terms) (s t : sub_explicits),\nexists u : terms,\n  e_relSLstar _ (env (var 0) (comp (cons a s) t)) u /\\\n  e_relSLstar _ (env a t) u.\nintros; exists (env a t); split; red in |- *.\napply star_trans1 with (env (var 0) (cons (env a t) (comp s t))); auto.\nauto.\nSave PC_clos_fvarcons.\nHint Resolve PC_clos_fvarcons.\n\nGoal\nforall s t : sub_explicits,\nexists u : terms,\n  e_relSLstar _ (env (var 0) (comp (lift s) t)) u /\\\n  e_relSLstar _ (env (var 0) t) u.\nintros; exists (env (var 0) t); auto 6.\nSave PC_clos_fvarlift1.\nHint Resolve PC_clos_fvarlift1.\n\nGoal\nforall s1 s2 t : sub_explicits,\nexists u : terms,\n  e_relSLstar _ (env (var 0) (comp (comp (lift s1) s2) t)) u /\\\n  e_relSLstar _ (env (env (var 0) s2) t) u.\nintros; exists (env (var 0) (comp s2 t)); split; red in |- *.\napply star_trans1 with (env (var 0) (comp (lift s1) (comp s2 t))); auto.\nauto.\nSave PC_clos_fvarlift2.\nHint Resolve PC_clos_fvarlift2.\n\nGoal\nforall (n : nat) (a : terms) (s t : sub_explicits),\nexists u : terms,\n  e_relSLstar _ (env (var (S n)) (comp (cons a s) t)) u /\\\n  e_relSLstar _ (env (env (var n) s) t) u.\nintros; exists (env (var n) (comp s t)); split; red in |- *.\napply star_trans1 with (env (var (S n)) (cons (env a t) (comp s t))); auto.\nauto.\nSave PC_clos_rvarcons.\nHint Resolve PC_clos_rvarcons.\n\nGoal\nforall (n : nat) (s t : sub_explicits),\nexists u : terms,\n  e_relSLstar _ (env (var (S n)) (comp (lift s) t)) u /\\\n  e_relSLstar _ (env (env (var n) (comp s shift)) t) u.\nintros; exists (env (var n) (comp s (comp shift t))); split; red in |- *.\nauto.\napply star_trans1 with (env (var n) (comp (comp s shift) t)); auto.\nSave PC_clos_rvarlift1.\nHint Resolve PC_clos_rvarlift1.\n\nGoal\nforall (n : nat) (s1 s2 t : sub_explicits),\nexists u : terms,\n  e_relSLstar _ (env (var (S n)) (comp (comp (lift s1) s2) t)) u /\\\n  e_relSLstar _ (env (env (var n) (comp s1 (comp shift s2))) t) u.\nintros; exists (env (var n) (comp s1 (comp shift (comp s2 t)))); split;\n red in |- *.\napply star_trans1 with (env (var (S n)) (comp (lift s1) (comp s2 t))); auto.\napply star_trans1 with (env (var n) (comp (comp s1 (comp shift s2)) t)).\nauto.\napply star_trans1 with (env (var n) (comp s1 (comp (comp shift s2) t)));\n auto 6.\nSave PC_clos_rvarlift2.\nHint Resolve PC_clos_rvarlift2.\n\nGoal\nforall (a : terms) (t : sub_explicits),\nexists u : terms,\n  e_relSLstar _ (env a (comp id t)) u /\\ e_relSLstar _ (env a t) u.\nintros; exists (env a t); auto 8.\nSave PC2_clos_id.\nHint Resolve PC2_clos_id.\n\nGoal\nforall (a a' : terms) (s t : sub_explicits),\ne_relSL _ a a' ->\nexists u : terms,\n  e_relSLstar _ (env a (comp s t)) u /\\ e_relSLstar _ (env (env a' s) t) u.\nintros; exists (env a' (comp s t)); auto 8.\nSave PC1_clos_ctxt_l.\nHint Resolve PC1_clos_ctxt_l.\n\nGoal\nforall (a : terms) (s s' t : sub_explicits),\ne_relSL _ s s' ->\nexists u : terms,\n  e_relSLstar _ (env a (comp s t)) u /\\ e_relSLstar _ (env (env a s') t) u.\nintros; exists (env a (comp s' t)); auto 6.\nSave PC2_clos_ctxt_l.\nHint Resolve PC2_clos_ctxt_l.\n\nGoal\nforall (a : terms) (s t t' : sub_explicits),\ne_relSL _ t t' ->\nexists u : terms,\n  e_relSLstar _ (env a (comp s t)) u /\\ e_relSLstar _ (env (env a s) t') u.\nintros; exists (env a (comp s t')); auto 6.\nSave PC_clos_ctxt_r.\nHint Resolve PC_clos_ctxt_r.\n\nGoal\nforall (a x' : terms) (s t : sub_explicits),\ne_relSL _ (env a s) x' ->\nexists u : terms,\n  e_relSLstar _ (env a (comp s t)) u /\\ e_relSLstar _ (env x' t) u.\nintros a x' s t H; pattern a, s, x' in |- *; apply case_SLenv; auto.\nSave PC_clos_ctxt_l.\nHint Resolve PC_clos_ctxt_l.\n\n(*** varshift1 ***)\n\n (* aucune PC *)\n\n(*** varshift2 ***)\n\nGoal\nforall (n : nat) (a : terms) (s : sub_explicits),\nexists u : terms,\n  e_relSLstar _ (env (var (S n)) (cons a s)) u /\\\n  e_relSLstar _ (env (var n) s) u.\nintros; exists (env (var n) s); auto 6.\nSave PC_varshift2_shiftcons.\nHint Resolve PC_varshift2_shiftcons.\n\nGoal\nforall (n : nat) (s : sub_explicits),\nexists u : terms,\n  e_relSLstar _ (env (var (S n)) (lift s)) u /\\\n  e_relSLstar _ (env (var n) (comp s shift)) u.\nintros; exists (env (var n) (comp s shift)); auto 6.\nSave PC_varshift2_shiftlift1.\nHint Resolve PC_varshift2_shiftlift1.\n\nGoal\nforall (n : nat) (s t : sub_explicits),\nexists u : terms,\n  e_relSLstar _ (env (var (S n)) (comp (lift s) t)) u /\\\n  e_relSLstar _ (env (var n) (comp s (comp shift t))) u.\nintros; exists (env (var n) (comp s (comp shift t))); auto 6.\nSave PC_varshift2_shiftlift2.\nHint Resolve PC_varshift2_shiftlift2.\n\nGoal\nforall n : nat,\nexists u : terms,\n  e_relSLstar _ (env (var (S n)) id) u /\\ e_relSLstar _ (env (var n) shift) u.\nintros; exists (var (S n)); auto 6.\nSave PC_varshift2_idr.\nHint Resolve PC_varshift2_idr.\n\nGoal\nforall (n : nat) (s s' : sub_explicits),\ne_relSL _ s s' ->\nexists u : terms,\n  e_relSLstar _ (env (var (S n)) s) u /\\\n  e_relSLstar _ (env (var n) (comp shift s')) u.\nintros; exists (env (var (S n)) s'); auto 6.\nSave PC_varshift2_ctxt_r.\nHint Resolve PC_varshift2_ctxt_r.\n\nGoal\nforall (n : nat) (s x' : sub_explicits),\ne_relSL _ (comp shift s) x' ->\nexists u : terms,\n  e_relSLstar _ (env (var (S n)) s) u /\\ e_relSLstar _ (env (var n) x') u.\nintros n s x' H; pattern s, x' in |- *; apply case_SLcomp1; auto.\nSave PC_varshift2_ctxt_r'.\nHint Resolve PC_varshift2_ctxt_r'.\n\n(*** fvarcons ***)\n\nGoal\nforall (a a' : terms) (s : sub_explicits),\ne_relSL _ a a' ->\nexists u : terms,\n  e_relSLstar _ a u /\\ e_relSLstar _ (env (var 0) (cons a' s)) u.\nintros; exists a'; auto 6.\nSave PC1_fvarcons_ctxt_r.\nHint Resolve PC1_fvarcons_ctxt_r.\n\nGoal\nforall (a : terms) (s' : sub_explicits),\nexists u : terms,\n  e_relSLstar _ a u /\\ e_relSLstar _ (env (var 0) (cons a s')) u.\nintros; exists a; auto 6.\nSave PC2_fvarcons_ctxt_r.\nHint Resolve PC2_fvarcons_ctxt_r.\n\nGoal\nforall (a : terms) (s x' : sub_explicits),\ne_relSL _ (cons a s) x' ->\nexists u : terms, e_relSLstar _ a u /\\ e_relSLstar _ (env (var 0) x') u.\nintros a s x' H; pattern x' in |- *; apply case_SLcons with a s; auto.\nSave PC_fvarcons_ctxt_r. \n\n(*** fvarlift1 ***)\n\nGoal\nexists u : terms, e_relSLstar _ (var 0) u /\\ e_relSLstar _ (env (var 0) id) u.\nintros; exists (var 0); auto 6.\nSave PC_fvarlift1_liftid.\nHint Resolve PC_fvarlift1_liftid.\n\nGoal\nforall s' : sub_explicits,\nexists u : terms,\n  e_relSLstar _ (var 0) u /\\ e_relSLstar _ (env (var 0) (lift s')) u.\nintros; exists (var 0); auto 6.\nSave PC_fvarlift1_ctxt_r.\nHint Resolve PC_fvarlift1_ctxt_r.\n\nGoal\nforall s x' : sub_explicits,\ne_relSL _ (lift s) x' ->\nexists u : terms, e_relSLstar _ (var 0) u /\\ e_relSLstar _ (env (var 0) x') u.\nintros s x' H; pattern s, x' in |- *; apply case_SLlift; auto.\nSave PC_fvarlift1_ctxt_r'.\n\n(*** fvarlift2 ***)\n\nGoal\nforall s t : sub_explicits,\nexists u : terms,\n  e_relSLstar _ (env (var 0) (lift t)) u /\\\n  e_relSLstar _ (env (var 0) (lift (comp s t))) u.\nintros; exists (var 0); auto 6.\nSave PC_fvarlift2_lift1.\nHint Resolve PC_fvarlift2_lift1.\n\nGoal\nforall s t v : sub_explicits,\nexists u : terms,\n  e_relSLstar _ (env (var 0) (comp (lift t) v)) u /\\\n  e_relSLstar _ (env (var 0) (comp (lift (comp s t)) v)) u.\nintros; exists (env (var 0) v); auto 6.\nSave PC_fvarlift2_lift2.\nHint Resolve PC_fvarlift2_lift2.\n\nGoal\nforall (a : terms) (s t : sub_explicits),\nexists u : terms,\n  e_relSLstar _ (env (var 0) (cons a t)) u /\\\n  e_relSLstar _ (env (var 0) (cons a (comp s t))) u.\nintros; exists a; auto 6.\nSave PC_fvarlift2_liftenv.\nHint Resolve PC_fvarlift2_liftenv.\n\nGoal\nforall s : sub_explicits,\nexists u : terms,\n  e_relSLstar _ (env (var 0) id) u /\\ e_relSLstar _ (env (var 0) (lift s)) u.\nexists (var 0); auto 6.\nSave PC_fvarlift2_idr.\nHint Resolve PC_fvarlift2_idr.\n\nGoal\nforall t : sub_explicits,\nexists u : terms,\n  e_relSLstar _ (env (var 0) t) u /\\\n  e_relSLstar _ (env (var 0) (comp id t)) u.\nintros; exists (env (var 0) t); auto 7.\nSave PC_fvarlift2_liftid.\nHint Resolve PC_fvarlift2_liftid.\n\nGoal\nforall s' t : sub_explicits,\nexists u : terms,\n  e_relSLstar _ (env (var 0) t) u /\\\n  e_relSLstar _ (env (var 0) (comp (lift s') t)) u.\nintros; exists (env (var 0) t); auto 6.\nSave PC1_fvarlift2_ctxt_r.\nHint Resolve PC1_fvarlift2_ctxt_r.\n\nGoal\nforall s t t' : sub_explicits,\ne_relSL _ t t' ->\nexists u : terms,\n  e_relSLstar _ (env (var 0) t) u /\\\n  e_relSLstar _ (env (var 0) (comp (lift s) t')) u.\nintros; exists (env (var 0) t'); auto 6.\nSave PC2_fvarlift2_ctxt_r.\nHint Resolve PC2_fvarlift2_ctxt_r.\n\nGoal\nforall s t x' : sub_explicits,\ne_relSL _ (comp (lift s) t) x' ->\nexists u : terms,\n  e_relSLstar _ (env (var 0) t) u /\\ e_relSLstar _ (env (var 0) x') u.\nintros s t x' H; pattern t, x' in |- *; apply case_SLcomp2 with s; auto.\nintros; pattern s, x'0 in |- *; apply case_SLlift; auto.\nSave PC_fvarlift2_ctxt_r.\n\n(*** rvarcons ***)\n\nGoal\nforall (n : nat) (a' : terms) (s : sub_explicits),\nexists u : terms,\n  e_relSLstar _ (env (var n) s) u /\\\n  e_relSLstar _ (env (var (S n)) (cons a' s)) u.\nintros; exists (env (var n) s); auto 6.\nSave PC1_rvarcons_ctxt_r.\nHint Resolve PC1_rvarcons_ctxt_r.\n\nGoal\nforall (n : nat) (a : terms) (s s' : sub_explicits),\ne_relSL _ s s' ->\nexists u : terms,\n  e_relSLstar _ (env (var n) s) u /\\\n  e_relSLstar _ (env (var (S n)) (cons a s')) u.\nintros; exists (env (var n) s'); auto 6.\nSave PC2_rvarcons_ctxt_r.\nHint Resolve PC2_rvarcons_ctxt_r.\n\nGoal\nforall (n : nat) (a : terms) (s x' : sub_explicits),\ne_relSL _ (cons a s) x' ->\nexists u : terms,\n  e_relSLstar _ (env (var n) s) u /\\ e_relSLstar _ (env (var (S n)) x') u.\nintros n a s x' H; pattern x' in |- *; apply case_SLcons with a s; auto.\nSave PC_rvarcons_ctxt_r.\n\n(*** rvarlift1 ***)\n\nGoal\nforall n : nat,\nexists u : terms,\n  e_relSLstar _ (env (var n) (comp id shift)) u /\\\n  e_relSLstar _ (env (var (S n)) id) u.\nintros; exists (var (S n)); split; red in |- *.\napply star_trans1 with (env (var n) shift); auto.\nauto.\nSave PC_rvarlift1_id.\nHint Resolve PC_rvarlift1_id.\n\nGoal\nforall (n : nat) (s s' : sub_explicits),\ne_relSL _ s s' ->\nexists u : terms,\n  e_relSLstar _ (env (var n) (comp s shift)) u /\\\n  e_relSLstar _ (env (var (S n)) (lift s')) u.\nintros; exists (env (var n) (comp s' shift)); auto 6.\nSave PC_rvarlift1_ctxt_r.\nHint Resolve PC_rvarlift1_ctxt_r.\n\nGoal\nforall (n : nat) (s x' : sub_explicits),\ne_relSL _ (lift s) x' ->\nexists u : terms,\n  e_relSLstar _ (env (var n) (comp s shift)) u /\\\n  e_relSLstar _ (env (var (S n)) x') u.\nintros n s x' H; pattern s, x' in |- *; apply case_SLlift; auto.\nSave PC_rvarlift1_ctxt_r'.\nHint Resolve PC_rvarlift1_ctxt_r'.\n\n(*** rvarlift2 ***)\n\nGoal\nforall (n : nat) (s t : sub_explicits),\nexists u : terms,\n  e_relSLstar _ (env (var n) (comp s (comp shift (lift t)))) u /\\\n  e_relSLstar _ (env (var (S n)) (lift (comp s t))) u.\nintros; exists (env (var n) (comp s (comp t shift))); split; red in |- *.\nauto 6.\napply star_trans1 with (env (var n) (comp (comp s t) shift)); auto.\nSave PC_rvarlift2_lift1.\nHint Resolve PC_rvarlift2_lift1.\n\nGoal\nforall (n : nat) (s t v : sub_explicits),\nexists u : terms,\n  e_relSLstar _ (env (var n) (comp s (comp shift (comp (lift t) v)))) u /\\\n  e_relSLstar _ (env (var (S n)) (comp (lift (comp s t)) v)) u.\nintros; exists (env (var n) (comp s (comp t (comp shift v)))); split;\n red in |- *.\nauto 6.\napply star_trans1 with (env (var n) (comp (comp s t) (comp shift v))); auto.\nSave PC_rvarlift2_lift2.\nHint Resolve PC_rvarlift2_lift2.\n\nGoal\nforall (n : nat) (a : terms) (s t : sub_explicits),\nexists u : terms,\n  e_relSLstar _ (env (var n) (comp s (comp shift (cons a t)))) u /\\\n  e_relSLstar _ (env (var (S n)) (cons a (comp s t))) u.\nintros; exists (env (var n) (comp s t)); auto 8.\nSave PC_rvarlift2_liftenv.\nHint Resolve PC_rvarlift2_liftenv.\n\nGoal\nforall (n : nat) (s : sub_explicits),\nexists u : terms,\n  e_relSLstar _ (env (var n) (comp s (comp shift id))) u /\\\n  e_relSLstar _ (env (var (S n)) (lift s)) u.\nintros; exists (env (var n) (comp s shift)); auto 8.\nSave PC_rvarlift2_idr.\nHint Resolve PC_rvarlift2_idr.\n\nGoal\nforall (n : nat) (t : sub_explicits),\nexists u : terms,\n  e_relSLstar _ (env (var n) (comp id (comp shift t))) u /\\\n  e_relSLstar _ (env (var (S n)) (comp id t)) u.\nintros; exists (env (var (S n)) t); split; red in |- *.\napply star_trans1 with (env (var n) (comp shift t)); auto.\nauto.\nSave PC_rvarlift2_liftid.\nHint Resolve PC_rvarlift2_liftid.\n\nGoal\nforall (n : nat) (s s' t : sub_explicits),\ne_relSL _ s s' ->\nexists u : terms,\n  e_relSLstar _ (env (var n) (comp s (comp shift t))) u /\\\n  e_relSLstar _ (env (var (S n)) (comp (lift s') t)) u.\nintros; exists (env (var n) (comp s' (comp shift t))); auto 6.\nSave PC1_rvarlift2_ctxt_r.\nHint Resolve PC1_rvarlift2_ctxt_r.\n\nGoal\nforall (n : nat) (s t t' : sub_explicits),\ne_relSL _ t t' ->\nexists u : terms,\n  e_relSLstar _ (env (var n) (comp s (comp shift t))) u /\\\n  e_relSLstar _ (env (var (S n)) (comp (lift s) t')) u.\nintros; exists (env (var n) (comp s (comp shift t'))); auto 7.\nSave PC2_rvarlift2_ctxt_r.\nHint Resolve PC2_rvarlift2_ctxt_r.\n\nGoal\nforall (n : nat) (s t x' : sub_explicits),\ne_relSL _ (comp (lift s) t) x' ->\nexists u : terms,\n  e_relSLstar _ (env (var n) (comp s (comp shift t))) u /\\\n  e_relSLstar _ (env (var (S n)) x') u.\nintros n s t x' H; pattern t, x' in |- *; apply case_SLcomp2 with s; auto.\nintros; pattern s, x'0 in |- *; apply case_SLlift; auto.\nSave PC_rvarlift2_ctxt_r.\nHint Resolve PC_rvarlift2_ctxt_r.\n\n(*** assenv ***) \n\nGoal\nforall s1 s2 t v : sub_explicits,\nexists u : sub_explicits,\n  e_relSLstar _ (comp (comp s1 s2) (comp t v)) u /\\\n  e_relSLstar _ (comp (comp s1 (comp s2 t)) v) u.\nintros; exists (comp s1 (comp s2 (comp t v))); split; red in |- *.\nauto.\napply star_trans1 with (comp s1 (comp (comp s2 t) v)); auto.\nSave PC_assenv_assenv.\nHint Resolve PC_assenv_assenv.\n\nGoal\nforall (a : terms) (s t v : sub_explicits),\nexists u : sub_explicits,\n  e_relSLstar _ (comp (cons a s) (comp t v)) u /\\\n  e_relSLstar _ (comp (cons (env a t) (comp s t)) v) u.\nintros; exists (cons (env a (comp t v)) (comp s (comp t v))); split;\n red in |- *.\nauto.\napply star_trans1 with (cons (env (env a t) v) (comp (comp s t) v)).\nauto.\napply star_trans1 with (cons (env a (comp t v)) (comp (comp s t) v)); auto.\nSave PC_assenv_mapenv.\nHint Resolve PC_assenv_mapenv.\n\nGoal\nforall (a : terms) (s v : sub_explicits),\nexists u : sub_explicits,\n  e_relSLstar _ (comp shift (comp (cons a s) v)) u /\\\n  e_relSLstar _ (comp s v) u.\nintros; exists (comp s v); split; red in |- *.\napply star_trans1 with (comp shift (cons (env a v) (comp s v))); auto.\nauto.\nSave PC_assenv_shiftcons.\nHint Resolve PC_assenv_shiftcons.\n\nGoal\nforall s v : sub_explicits,\nexists u : sub_explicits,\n  e_relSLstar _ (comp shift (comp (lift s) v)) u /\\\n  e_relSLstar _ (comp (comp s shift) v) u.\nintros; exists (comp s (comp shift v)); auto 6.\nSave PC_assenv_shiftlift1.\nHint Resolve PC_assenv_shiftlift1.\n\nGoal\nforall s t v : sub_explicits,\nexists u : sub_explicits,\n  e_relSLstar _ (comp shift (comp (comp (lift s) t) v)) u /\\\n  e_relSLstar _ (comp (comp s (comp shift t)) v) u.\nintros; exists (comp s (comp shift (comp t v))); split; red in |- *.\napply star_trans1 with (comp shift (comp (lift s) (comp t v))); auto.\napply star_trans1 with (comp s (comp (comp shift t) v)); auto.\nSave PC_assenv_shiftlift2.\nHint Resolve PC_assenv_shiftlift2.\n\nGoal\nforall s t v : sub_explicits,\nexists u : sub_explicits,\n  e_relSLstar _ (comp (lift s) (comp (lift t) v)) u /\\\n  e_relSLstar _ (comp (lift (comp s t)) v) u.\nintros; exists (comp (lift (comp s t)) v); auto 6.\nSave PC_assenv_lift1.\nHint Resolve PC_assenv_lift1.\n\nGoal\nforall s t1 t2 v : sub_explicits,\nexists u : sub_explicits,\n  e_relSLstar _ (comp (lift s) (comp (comp (lift t1) t2) v)) u /\\\n  e_relSLstar _ (comp (comp (lift (comp s t1)) t2) v) u.\nintros; exists (comp (lift (comp s t1)) (comp t2 v)); split; red in |- *.\napply star_trans1 with (comp (lift s) (comp (lift t1) (comp t2 v))); auto.\nauto.\nSave PC_assenv_lift2.\nHint Resolve PC_assenv_lift2.\n\nGoal\nforall (a : terms) (s t v : sub_explicits),\nexists u : sub_explicits,\n  e_relSLstar _ (comp (lift s) (comp (cons a t) v)) u /\\\n  e_relSLstar _ (comp (cons a (comp s t)) v) u.\nintros; exists (cons (env a v) (comp s (comp t v))); split; red in |- *.\napply star_trans1 with (comp (lift s) (cons (env a v) (comp t v))); auto.\napply star_trans1 with (cons (env a v) (comp (comp s t) v)); auto.\nSave PC_assenv_liftenv.\nHint Resolve PC_assenv_liftenv.\n\nGoal\nforall t v : sub_explicits,\nexists u : sub_explicits,\n  e_relSLstar _ (comp id (comp t v)) u /\\ e_relSLstar _ (comp t v) u.\nintros; exists (comp t v); auto 6.\nSave PC_assenv_idl.\nHint Resolve PC_assenv_idl.\n\nGoal\nforall s v : sub_explicits,\nexists u : sub_explicits,\n  e_relSLstar _ (comp s (comp id v)) u /\\ e_relSLstar _ (comp s v) u.\nintros; exists (comp s v); auto 7.\nSave PC1_assenv_idr.\nHint Resolve PC1_assenv_idr.\n\nGoal\nforall s t : sub_explicits,\nexists u : sub_explicits,\n  e_relSLstar _ (comp s (comp t id)) u /\\ e_relSLstar _ (comp s t) u.\nintros; exists (comp s t); auto 7.\nSave PC2_assenv_idr.\nHint Resolve PC2_assenv_idr.\n\nGoal\nforall s s' t v : sub_explicits,\ne_relSL _ s s' ->\nexists u : sub_explicits,\n  e_relSLstar _ (comp s (comp t v)) u /\\ e_relSLstar _ (comp (comp s' t) v) u.\nintros; exists (comp s' (comp t v)); auto 6.\nSave PC_assenv_ctxt_l.\nHint Resolve PC_assenv_ctxt_l.\n\nGoal\nforall s t t' v : sub_explicits,\ne_relSL _ t t' ->\nexists u : sub_explicits,\n  e_relSLstar _ (comp s (comp t v)) u /\\ e_relSLstar _ (comp (comp s t') v) u. \nintros; exists (comp s (comp t' v)); auto 6.\nSave PC1_assenv_ctxt_r.\nHint Resolve PC1_assenv_ctxt_r.\n\nGoal\nforall s t v v' : sub_explicits,\ne_relSL _ v v' ->\nexists u : sub_explicits,\n  e_relSLstar _ (comp s (comp t v)) u /\\ e_relSLstar _ (comp (comp s t) v') u. \nintros; exists (comp s (comp t v')); auto 6.\nSave PC2_assenv_ctxt_r.\nHint Resolve PC2_assenv_ctxt_r.\n\nGoal\nforall s t v x' : sub_explicits,\ne_relSL _ (comp s t) x' ->\nexists u : sub_explicits,\n  e_relSLstar _ (comp s (comp t v)) u /\\ e_relSLstar _ (comp x' v) u.\nintros s t v x' H; pattern s, t, x' in |- *; apply case_SLcomp; auto.\nSave PC_assenv_ctxt_r.\nHint Resolve PC_assenv_ctxt_r.\n\n(*** mapenv ***)\n\nGoal\nforall (a : terms) (s : sub_explicits),\nexists u : sub_explicits,\n  e_relSLstar _ (cons (env a id) (comp s id)) u /\\ e_relSLstar _ (cons a s) u. \nintros; exists (cons a s); split; red in |- *.\napply star_trans1 with (cons a (comp s id)); auto.\nauto.\nSave PC_mapenv_idr.\nHint Resolve PC_mapenv_idr.\n\nGoal\nforall (a a' : terms) (s t : sub_explicits),\ne_relSL _ a a' ->\nexists u : sub_explicits,\n  e_relSLstar _ (cons (env a t) (comp s t)) u /\\\n  e_relSLstar _ (comp (cons a' s) t) u. \nintros; exists (cons (env a' t) (comp s t)); auto 6.\nSave PC1_mapenv_ctxt_l.\nHint Resolve PC1_mapenv_ctxt_l.\n\nGoal\nforall (a : terms) (s s' t : sub_explicits),\ne_relSL _ s s' ->\nexists u : sub_explicits,\n  e_relSLstar _ (cons (env a t) (comp s t)) u /\\\n  e_relSLstar _ (comp (cons a s') t) u. \nintros; exists (cons (env a t) (comp s' t)); auto 6.\nSave PC2_mapenv_ctxt_l.\nHint Resolve PC2_mapenv_ctxt_l.\n\nGoal\nforall (a : terms) (s t t' : sub_explicits),\ne_relSL _ t t' ->\nexists u : sub_explicits,\n  e_relSLstar _ (cons (env a t) (comp s t)) u /\\\n  e_relSLstar _ (comp (cons a s) t') u. \nintros; exists (cons (env a t') (comp s t')); split; red in |- *.\napply star_trans1 with (cons (env a t') (comp s t)); auto.\nauto.\nSave PC_mapenv_ctxt_r.\nHint Resolve PC_mapenv_ctxt_r.\n\nGoal\nforall (a : terms) (s t x' : sub_explicits),\ne_relSL _ (cons a s) x' ->\nexists u : sub_explicits,\n  e_relSLstar _ (cons (env a t) (comp s t)) u /\\ e_relSLstar _ (comp x' t) u. \nintros a s t x' H; pattern x' in |- *; apply case_SLcons with a s; auto.\nSave PC_mapenv_ctxt_l.\nHint Resolve PC_mapenv_ctxt_l.\n\n(*** shiftcons ***)\n\nGoal\nforall (a' : terms) (s : sub_explicits),\nexists u : sub_explicits,\n  e_relSLstar _ s u /\\ e_relSLstar _ (comp shift (cons a' s)) u. \nintros; exists s; auto 6.\nSave PC1_shiftcons_ctxt_r.\nHint Resolve PC1_shiftcons_ctxt_r.\n\nGoal\nforall (a : terms) (s s' : sub_explicits),\ne_relSL _ s s' ->\nexists u : sub_explicits,\n  e_relSLstar _ s u /\\ e_relSLstar _ (comp shift (cons a s')) u.\nintros; exists s'; auto 6.\nSave PC2_shiftcons_ctxt_r.\nHint Resolve PC2_shiftcons_ctxt_r.\n\nGoal\nforall (a : terms) (s x' : sub_explicits),\ne_relSL _ (cons a s) x' ->\nexists u : sub_explicits,\n  e_relSLstar _ s u /\\ e_relSLstar _ (comp shift x') u.\nintros a s x' H; pattern x' in |- *; apply case_SLcons with a s; auto.\nSave PC_shiftcons_ctxt_r.\n\n(*** shiftlift1 ***)\n\nGoal\nexists u : sub_explicits,\n  e_relSLstar _ (comp id shift) u /\\ e_relSLstar _ (comp shift id) u.\nintros; exists shift; auto 6.\nSave PC_shiftlift1_liftid.\nHint Resolve PC_shiftlift1_liftid.\n\nGoal\nforall s s' : sub_explicits,\ne_relSL _ s s' ->\nexists u : sub_explicits,\n  e_relSLstar _ (comp s shift) u /\\ e_relSLstar _ (comp shift (lift s')) u.\nintros; exists (comp s' shift); auto 6.\nSave PC_shiftlift1_ctxt_r.\nHint Resolve PC_shiftlift1_ctxt_r.\n\nGoal\nforall s x' : sub_explicits,\ne_relSL _ (lift s) x' ->\nexists u : sub_explicits,\n  e_relSLstar _ (comp s shift) u /\\ e_relSLstar _ (comp shift x') u.\nintros s x' H; pattern s, x' in |- *; apply case_SLlift; auto.\nSave PC_shiftlift1_ctxt_r'.\nHint Resolve PC_shiftlift1_ctxt_r'.\n\n(*** shiftlift2 ***)\n\nGoal\nforall s t : sub_explicits,\nexists u : sub_explicits,\n  e_relSLstar _ (comp s (comp shift (lift t))) u /\\\n  e_relSLstar _ (comp shift (lift (comp s t))) u.\nintros; exists (comp s (comp t shift)); split; red in |- *.\nauto.\napply star_trans1 with (comp (comp s t) shift); auto.\nSave PC_shiftlift2_lift1.\nHint Resolve PC_shiftlift2_lift1.\n\nGoal\nforall s t v : sub_explicits,\nexists u : sub_explicits,\n  e_relSLstar _ (comp s (comp shift (comp (lift t) v))) u /\\\n  e_relSLstar _ (comp shift (comp (lift (comp s t)) v)) u.\nintros; exists (comp s (comp t (comp shift v))); split; red in |- *.\nauto.\napply star_trans1 with (comp (comp s t) (comp shift v)); auto.\nSave PC_shiftlift2_lift2.\nHint Resolve PC_shiftlift2_lift2.\n\nGoal\nforall (a : terms) (s t : sub_explicits),\nexists u : sub_explicits,\n  e_relSLstar _ (comp s (comp shift (cons a t))) u /\\\n  e_relSLstar _ (comp shift (cons a (comp s t))) u.\nintros; exists (comp s t); auto 7.\nSave PC_shiftlift2_liftenv.\nHint Resolve PC_shiftlift2_liftenv.\n\nGoal\nforall t : sub_explicits,\nexists u : sub_explicits,\n  e_relSLstar _ (comp id (comp shift t)) u /\\\n  e_relSLstar _ (comp shift (comp id t)) u.\nintros; exists (comp shift t); auto 7.\nSave PC_shiftlift2_liftid.\nHint Resolve PC_shiftlift2_liftid.\n\nGoal\nforall s : sub_explicits,\nexists u : sub_explicits,\n  e_relSLstar _ (comp s (comp shift id)) u /\\\n  e_relSLstar _ (comp shift (lift s)) u.\nintros; exists (comp s shift); auto 7.\nSave PC_shiftlift2_idr.\nHint Resolve PC_shiftlift2_idr.\n\nGoal\nforall s s' t : sub_explicits,\ne_relSL _ s s' ->\nexists u : sub_explicits,\n  e_relSLstar _ (comp s (comp shift t)) u /\\\n  e_relSLstar _ (comp shift (comp (lift s') t)) u.\nintros; exists (comp s' (comp shift t)); auto 6.\nSave PC1_shiftlift2_ctxt_r.\nHint Resolve PC1_shiftlift2_ctxt_r.\n\nGoal\nforall s t t' : sub_explicits,\ne_relSL _ t t' ->\nexists u : sub_explicits,\n  e_relSLstar _ (comp s (comp shift t)) u /\\\n  e_relSLstar _ (comp shift (comp (lift s) t')) u.\nintros; exists (comp s (comp shift t')); auto 6.\nSave PC2_shiftlift2_ctxt_r.\nHint Resolve PC2_shiftlift2_ctxt_r.\n\nGoal\nforall s t x' : sub_explicits,\ne_relSL _ (comp (lift s) t) x' ->\nexists u : sub_explicits,\n  e_relSLstar _ (comp s (comp shift t)) u /\\ e_relSLstar _ (comp shift x') u.\nintros s t x' H; pattern t, x' in |- *; apply case_SLcomp2 with s; auto.\nintros; pattern s, x'0 in |- *; apply case_SLlift; auto.\nSave PC_shiftlift2_ctxt_r.\nHint Resolve PC_shiftlift2_ctxt_r.\n  \n(*** lift1 ***)\n\nGoal\nforall t : sub_explicits,\nexists u : sub_explicits,\n  e_relSLstar _ (lift (comp id t)) u /\\ e_relSLstar _ (comp id (lift t)) u.\nintros; exists (lift t); auto 7.\nSave PC1_lift1_liftid.\nHint Resolve PC1_lift1_liftid.\n\nGoal\nforall s : sub_explicits,\nexists u : sub_explicits,\n  e_relSLstar _ (lift (comp s id)) u /\\ e_relSLstar _ (comp (lift s) id) u.\nintros; exists (lift s); auto 7.\nSave PC2_lift1_liftid.\nHint Resolve PC2_lift1_liftid.\n\nGoal\nforall s s' t : sub_explicits,\ne_relSL _ s s' ->\nexists u : sub_explicits,\n  e_relSLstar _ (lift (comp s t)) u /\\\n  e_relSLstar _ (comp (lift s') (lift t)) u.\nintros; exists (lift (comp s' t)); auto 6.\nSave PC_lift1_ctxt_l.\nHint Resolve PC_lift1_ctxt_l.\n\nGoal\nforall s t t' : sub_explicits,\ne_relSL _ t t' ->\nexists u : sub_explicits,\n  e_relSLstar _ (lift (comp s t)) u /\\\n  e_relSLstar _ (comp (lift s) (lift t')) u.\nintros; exists (lift (comp s t')); auto 6.\nSave PC_lift1_ctxt_r.\nHint Resolve PC_lift1_ctxt_r.\n\nGoal\nforall s t x' : sub_explicits,\ne_relSL _ (lift s) x' ->\nexists u : sub_explicits,\n  e_relSLstar _ (lift (comp s t)) u /\\ e_relSLstar _ (comp x' (lift t)) u.\nintros s t x' H; pattern s, x' in |- *; apply case_SLlift; auto.\nSave PC_lift1_ctxt_l'.\nHint Resolve PC_lift1_ctxt_l'.\n\nGoal\nforall s t x' : sub_explicits,\ne_relSL _ (lift t) x' ->\nexists u : sub_explicits,\n  e_relSLstar _ (lift (comp s t)) u /\\ e_relSLstar _ (comp (lift s) x') u.\nintros a t x' H; pattern t, x' in |- *; apply case_SLlift; auto.\nSave PC_lift1_ctxt_r'.\nHint Resolve PC_lift1_ctxt_r'.\n\n(*** lift2 ***)\n\nGoal\nforall s t v : sub_explicits,\nexists u : sub_explicits,\n  e_relSLstar _ (comp (lift (comp s t)) (lift v)) u /\\\n  e_relSLstar _ (comp (lift s) (lift (comp t v))) u.\nintros; exists (lift (comp s (comp t v))); split; red in |- *.\napply star_trans1 with (lift (comp (comp s t) v)); auto.\nauto.\nSave PC_lift2_lift1.\nHint Resolve PC_lift2_lift1.\n\nGoal\nforall s t1 t2 v : sub_explicits,\nexists u : sub_explicits,\n  e_relSLstar _ (comp (lift (comp s t1)) (comp (lift t2) v)) u /\\\n  e_relSLstar _ (comp (lift s) (comp (lift (comp t1 t2)) v)) u.\nintros; exists (comp (lift (comp s (comp t1 t2))) v); split; red in |- *.\napply star_trans1 with (comp (lift (comp (comp s t1) t2)) v); auto 6.\nauto.\nSave PC_lift2_lift2.\nHint Resolve PC_lift2_lift2.\n\nGoal\nforall (a : terms) (s t v : sub_explicits),\nexists u : sub_explicits,\n  e_relSLstar _ (comp (lift (comp s t)) (cons a v)) u /\\\n  e_relSLstar _ (comp (lift s) (cons a (comp t v))) u.\nintros; exists (cons a (comp s (comp t v))); split; red in |- *.\napply star_trans1 with (cons a (comp (comp s t) v)); auto.\nauto.\nSave PC_lift2_liftenv.\nHint Resolve PC_lift2_liftenv.\n\nGoal\nforall t v : sub_explicits,\nexists u : sub_explicits,\n  e_relSLstar _ (comp (lift (comp id t)) v) u /\\\n  e_relSLstar _ (comp id (comp (lift t) v)) u.\nintros; exists (comp (lift t) v); auto 8.\nSave PC1_lift2_liftid.\nHint Resolve PC1_lift2_liftid.\n\nGoal\nforall s v : sub_explicits,\nexists u : sub_explicits,\n  e_relSLstar _ (comp (lift (comp s id)) v) u /\\\n  e_relSLstar _ (comp (lift s) (comp id v)) u.\nintros; exists (comp (lift s) v); auto 8.\nSave PC2_lift2_liftid.\nHint Resolve PC2_lift2_liftid.\n\nGoal\nforall s t : sub_explicits,\nexists u : sub_explicits,\n  e_relSLstar _ (comp (lift (comp s t)) id) u /\\\n  e_relSLstar _ (comp (lift s) (lift t)) u.\nintros; exists (lift (comp s t)); auto 6.\nSave PC_lift2_idr.\nHint Resolve PC_lift2_idr.\n\nGoal\nforall s s' t v : sub_explicits,\ne_relSL _ s s' ->\nexists u : sub_explicits,\n  e_relSLstar _ (comp (lift (comp s t)) v) u /\\\n  e_relSLstar _ (comp (lift s') (comp (lift t) v)) u.\nintros; exists (comp (lift (comp s' t)) v); auto 7.\nSave PC_lift2_ctxt_l.\nHint Resolve PC_lift2_ctxt_l.\n\nGoal\nforall s t t' v : sub_explicits,\ne_relSL _ t t' ->\nexists u : sub_explicits,\n  e_relSLstar _ (comp (lift (comp s t)) v) u /\\\n  e_relSLstar _ (comp (lift s) (comp (lift t') v)) u.\nintros; exists (comp (lift (comp s t')) v); auto 7.\nSave PC1_lift2_ctxt_r.\nHint Resolve PC1_lift2_ctxt_r.\n\nGoal\nforall s t v v' : sub_explicits,\ne_relSL _ v v' ->\nexists u : sub_explicits,\n  e_relSLstar _ (comp (lift (comp s t)) v) u /\\\n  e_relSLstar _ (comp (lift s) (comp (lift t) v')) u.\nintros; exists (comp (lift (comp s t)) v'); auto 6.\nSave PC2_lift2_ctxt_r.\nHint Resolve PC2_lift2_ctxt_r.\n\nGoal\nforall s t v x' : sub_explicits,\ne_relSL _ (lift s) x' ->\nexists u : sub_explicits,\n  e_relSLstar _ (comp (lift (comp s t)) v) u /\\\n  e_relSLstar _ (comp x' (comp (lift t) v)) u.\nintros s t v x' H; pattern s, x' in |- *; apply case_SLlift; auto.\nSave PC_lift2_ctxt_l'. \nHint Resolve PC_lift2_ctxt_l'. \n\nGoal\nforall s t v x' : sub_explicits,\ne_relSL _ (comp (lift t) v) x' ->\nexists u : sub_explicits,\n  e_relSLstar _ (comp (lift (comp s t)) v) u /\\\n  e_relSLstar _ (comp (lift s) x') u.\nintros s t v x' H; pattern v, x' in |- *; apply case_SLcomp2 with t; auto.\nintros; pattern t, x'0 in |- *; apply case_SLlift; auto.\nSave PC_lift2_ctxt_r.\nHint Resolve PC_lift2_ctxt_r.\n\n(*** liftenv ***)\n\nGoal\nforall (a : terms) (t : sub_explicits),\nexists u : sub_explicits,\n  e_relSLstar _ (cons a (comp id t)) u /\\\n  e_relSLstar _ (comp id (cons a t)) u.\nintros; exists (cons a t); auto 7.\nSave PC_liftenv_liftid.\nHint Resolve PC_liftenv_liftid.\n\nGoal\nforall (a : terms) (s s' t : sub_explicits),\ne_relSL _ s s' ->\nexists u : sub_explicits,\n  e_relSLstar _ (cons a (comp s t)) u /\\\n  e_relSLstar _ (comp (lift s') (cons a t)) u.\nintros; exists (cons a (comp s' t)); auto 6.\nSave PC_liftenv_ctxt_l.\nHint Resolve PC_liftenv_ctxt_l.\n\nGoal\nforall (a a' : terms) (s t : sub_explicits),\ne_relSL _ a a' ->\nexists u : sub_explicits,\n  e_relSLstar _ (cons a (comp s t)) u /\\\n  e_relSLstar _ (comp (lift s) (cons a' t)) u.\nintros; exists (cons a' (comp s t)); auto 6.\nSave PC1_liftenv_ctxt_r.\nHint Resolve PC1_liftenv_ctxt_r.\n\nGoal\nforall (a : terms) (s t t' : sub_explicits),\ne_relSL _ t t' ->\nexists u : sub_explicits,\n  e_relSLstar _ (cons a (comp s t)) u /\\\n  e_relSLstar _ (comp (lift s) (cons a t')) u.\nintros; exists (cons a (comp s t')); auto 6.\nSave PC2_liftenv_ctxt_r.\nHint Resolve PC2_liftenv_ctxt_r.\n\nGoal\nforall (a : terms) (s t x' : sub_explicits),\ne_relSL _ (lift s) x' ->\nexists u : sub_explicits,\n  e_relSLstar _ (cons a (comp s t)) u /\\ e_relSLstar _ (comp x' (cons a t)) u.\nintros a s t x' H; pattern s, x' in |- *; apply case_SLlift; auto.\nSave PC_liftenv_ctxt_l'.\nHint Resolve PC_liftenv_ctxt_l'.\n\nGoal\nforall (a : terms) (s t x' : sub_explicits),\ne_relSL _ (cons a t) x' ->\nexists u : sub_explicits,\n  e_relSLstar _ (cons a (comp s t)) u /\\ e_relSLstar _ (comp (lift s) x') u.\nintros a s t x' H; pattern x' in |- *; apply case_SLcons with a t; auto.\nSave PC_liftenv_ctxt_r.\nHint Resolve PC_liftenv_ctxt_r.\n\n(*** idl ***)\n\nGoal exists u : sub_explicits, e_relSLstar _ id u /\\ e_relSLstar _ id u.\nintros; exists id; auto.\nSave PC_idl_idr.\nHint Resolve PC_idl_idr.\n\nGoal\nforall s s' : sub_explicits,\ne_relSL _ s s' ->\nexists u : sub_explicits, e_relSLstar _ s u /\\ e_relSLstar _ (comp id s') u.\nintros; exists s'; auto 6.\nSave PC_idl_ctxt_r.\nHint Resolve PC_idl_ctxt_r.\n\n(*** idr ***)\n\nGoal\nforall s s' : sub_explicits,\ne_relSL _ s s' ->\nexists u : sub_explicits, e_relSLstar _ s u /\\ e_relSLstar _ (comp s' id) u.\nintros; exists s'; auto 6.\nSave PC_idr_ctxt_l.\nHint Resolve PC_idr_ctxt_l.\n\n(*** liftid ***)\n\n (* aucune PC *)\n\n(*** id ***)\n\nGoal\nforall a a' : terms,\ne_relSL _ a a' ->\nexists u : terms, e_relSLstar _ a u /\\ e_relSLstar _ (env a' id) u.\nintros; exists a'; auto 6.\nSave PC_id_ctxt_l.\nHint Resolve PC_id_ctxt_l.\n\n\n", "meta": {"author": "coq-contribs", "repo": "subst", "sha": "7b4f4d1df839443cb67f38bf780274abeb9de047", "save_path": "github-repos/coq/coq-contribs-subst", "path": "github-repos/coq/coq-contribs-subst/subst-7b4f4d1df839443cb67f38bf780274abeb9de047/resoudPC_SL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2872323397308038}}
{"text": "\nRequire Import LibTactics.\n\nRequire Import Definitions.\nRequire Import Infrastructure.\nRequire Import Lemmas.\nRequire Import Determinism.\nRequire Import Soundness.\nRequire Import Lia.\n\n\n(** * STATIC *)\n\n\nInductive dexp : Set :=\n  | de_bvar   : nat -> dexp\n  | de_fvar   : var -> dexp\n  | de_lit    : nat -> dexp\n  | de_unit   : dexp\n  | de_anno   : dexp -> typ -> dexp\n  | de_app    : dexp -> dexp -> dexp\n  | de_abs    : typ -> dexp  -> dexp \n  | de_tabs   : dexp -> dexp \n  | de_tapp   : dexp -> typ -> dexp\n  | de_loc    : nat -> dexp\n  | de_ref    : dexp -> dexp\n  | de_get    : dexp -> dexp\n  | de_set    : dexp -> dexp -> dexp\n.\n\n\nFixpoint dopen_te_rec (k : nat) (f : typ) (e : dexp) {struct e} : dexp :=\n  match e with\n  | de_bvar i       => de_bvar i\n  | de_fvar x       => de_fvar x\n  | de_lit i        => de_lit i\n  | de_unit        => de_unit\n  | de_loc x      => de_loc x\n  | de_app e1 e2    => de_app (dopen_te_rec k f e1) (dopen_te_rec k f e2)\n  | de_abs A e1   => de_abs (open_tt_rec k f A) (dopen_te_rec k f e1) \n  | de_anno e1 A    => de_anno (dopen_te_rec k f e1) (open_tt_rec k f A) \n  | de_tabs e1     => de_tabs (dopen_te_rec (S k) f e1) \n  | de_tapp e1 A     => de_tapp (dopen_te_rec k f e1) (open_tt_rec k f A) \n  | de_ref e1     => de_ref (dopen_te_rec k f e1) \n  | de_get e1     => de_get (dopen_te_rec k f e1)\n  | de_set e1 e2     => de_set (dopen_te_rec k f e1) (dopen_te_rec k f e2)\n  end.\n\nFixpoint dopen_ee_rec (k : nat) (f : dexp) (e : dexp) {struct e} : dexp :=\n  match e with\n  | de_bvar i       => if k == i then f else (de_bvar i)\n  | de_fvar x       => de_fvar x\n  | de_loc x      => de_loc x\n  | de_lit i        => de_lit i\n  | de_unit        => de_unit\n  | de_app e1 e2    => de_app (dopen_ee_rec k f e1) (dopen_ee_rec k f e2)\n  | de_abs A e1   => de_abs A (dopen_ee_rec (S k) f e1)\n  | de_anno e1 A    => de_anno (dopen_ee_rec k f e1) A \n  | de_tabs e1     => de_tabs (dopen_ee_rec k f e1) \n  | de_tapp e1 A     => de_tapp (dopen_ee_rec k f e1) A \n  | de_ref e1     => de_ref (dopen_ee_rec k f e1) \n  | de_get e1     => de_get (dopen_ee_rec k f e1)\n  | de_set e1 e2     => de_set (dopen_ee_rec k f e1) (dopen_ee_rec k f e2)\n  end.\n\n\nDefinition dopen_te e T := dopen_te_rec 0 T e.\nDefinition dopen_ee e1 e2 := dopen_ee_rec 0 e2 e1.\n\n\n  Notation \"t 'dopen_ee_var' x\" := (dopen_ee t (de_fvar x)) (at level 67).\n\n  Notation \"t 'dopen_te_var' a\" := (dopen_te t (t_fvar a)) (at level 67).\n\n\n\n\n\nInductive dtyp_static : typ -> Prop :=\n  | dtyp_static_nat:\n      dtyp_static t_int\n  | dtyp_static_fvar: forall i,\n      dtyp_static (t_fvar i)\n  | dtyp_static_arrow: forall A B,\n      dtyp_static A ->\n      dtyp_static B ->\n      dtyp_static (t_arrow A B)\n  | dtyp_static_all: forall L A,\n      (forall x, x \\notin L -> dtyp_static (A open_tt_var x)) ->\n      dtyp_static (t_all A)\n  | dtyp_ref: forall A,\n      dtyp_static A ->\n      dtyp_static (t_ref A) \n   | dtyp_static_unit:\n      dtyp_static t_unit\n.\n\nInductive dterm_static : exp -> Prop :=\n  | dterm_static_var: forall x,\n      dterm_static (e_fvar x)\n  | dterm_static_nat : forall i,\n      dterm_static (e_lit i)\n  | dterm_static_unit : \n      dterm_static e_unit\n  | dterm_static_tabs : forall L V e1,\n      (forall x, x \\notin L -> dterm_static (e1 open_te_var x)) ->\n      (forall X, X \\notin L -> dtyp_static (V open_tt_var X)) ->\n      dterm_static (e_tabs e1 V)\n  | dterm_static_abs : forall L e1 A B,\n     dtyp_static A ->\n     dtyp_static B ->\n      (forall x, x \\notin L -> dterm_static (e1 open_ee_var x)) ->\n      dterm_static (e_abs A e1 B)\n  | dterm_static_app : forall e1 e2,\n      dterm_static e1 ->\n      dterm_static e2 ->\n      dterm_static (e_app e1 e2)\n  | dterm_static_tapp : forall e A,\n      dterm_static e ->\n      dtyp_static A ->\n      dterm_static (e_tapp e A)\n  | dterm_static_ref : forall e,\n      dterm_static e ->\n      dterm_static (e_ref e)\n  | dterm_static_get : forall e,\n      dterm_static e ->\n      dterm_static (e_get e)\n  | dterm_static_set : forall e1 e2,\n      dterm_static e1 ->\n      dterm_static e2 ->\n      dterm_static (e_set e1 e2)\n  | dterm_static_loc : forall i,\n      dterm_static (e_loc i)\n  | dterm_static_anno : forall e A,\n      dterm_static e ->\n      dtyp_static A ->\n      dterm_static (e_anno e A)\n.\n\nInductive denv_static : env -> Prop :=\n  | denv_static_empty : denv_static empty\n  | denv_static_typ : forall E x T,\n      denv_static E ->\n      dtyp_static T ->\n      wf_typ E T ->\n      x \\notin dom E ->\n      denv_static ( x ~: T ++ E)\n  | denv_static_tvar : forall E x,\n      denv_static E ->\n      x \\notin dom E ->\n      denv_static (x ~tvar ++ E)\n.\n\n\nInductive phi_static : phi -> Prop :=\n  | phi_static_typ : forall E,\n      (forall l,  l < length (E) -> \n      dtyp_static (store_Tlookup l E)) ->\n      phi_static (E).\n\n\n\nInductive eq: env -> typ -> typ -> Prop :=  \n  | eq_int : forall E,\n      wf_env E ->\n      eq E t_int t_int\n  | eq_unit : forall E,\n      wf_env E ->\n      eq E t_unit t_unit\n  | eq_var : forall E x,\n      wf_env E ->\n      wf_typ E (t_fvar x) ->\n      eq E (t_fvar x) (t_fvar x)\n  | eq_fun : forall E A1 A2 B1 B2,\n      eq E B1 A1 ->\n      eq E A2 B2 ->\n      eq E (t_arrow A1 A2) (t_arrow B1 B2)\n  | eq_all: forall L E A B ,\n      (forall x, x \\notin L ->\n      eq (x ~tvar ++ E) (A open_tt_var x) (B open_tt_var x)) ->\n      eq E (t_all A) (t_all B)\n  | eq_ref : forall E A B,\n      eq E A B ->\n      eq E (t_ref A) (t_ref B)\n.\n\nInductive styping : env -> phi -> exp -> dirflag -> typ -> Prop :=\n  | styp_var : forall E P x T,\n      wf_env E ->\n      binds x (bind_typ T) E ->\n      styping E P (e_fvar x) Inf T\n  | styp_nat : forall E P i,\n      wf_env E ->\n      styping E P (e_lit i) Inf (t_int)\n  | styp_unit : forall E P,\n      wf_env E ->\n      styping E P e_unit Inf t_unit\n  | styp_loc : forall E P l,\n       wf_env E ->\n      l < length P ->\n      wf_typ E (store_Tlookup l P) ->\n      styping E P (e_loc l) Inf (t_ref (store_Tlookup l P))\n  | styp_app : forall E P e1 e2 A B,\n      styping E P e1 Inf (t_arrow A B) ->\n      styping E P e2 Chk A ->\n      styping E P (e_app e1 e2) Inf B\n  | styp_abs : forall L E P A B e,\n      (forall x, x \\notin L ->\n            styping (x ~: A ++ E) P (e open_ee_var x) Chk B) ->\n      styping E P (e_abs A e B) Inf (t_arrow A B)\n  | styp_anno : forall E P e A,\n     styping E P e Chk A ->\n     styping E P (e_anno e A) Inf A\n  | styp_tabs : forall E P e A L,\n      ( forall a , a \\notin  L  -> \n      styping  ( a ~tvar ++ E) P ( e open_te_var a )  Chk  ( A open_tt_var a )  )  ->\n     styping E P (e_tabs e A) Inf (t_all A)\n  | styp_tapp : forall E P e A B,\n      wf_typ E A ->\n     styping E P e Inf (t_all B) ->\n     styping E P (e_tapp e A) Inf  (open_tt B A )\n  | styp_eq : forall E P e B A,\n     eq E A B ->\n     styping E P e Inf A ->\n     styping E P e Chk B\n  | styp_ref : forall E P e A,\n     styping E P e Inf A ->\n     styping E P (e_ref e) Inf (t_ref A)\n  | styp_get : forall E P e A1,\n     styping E P e Inf (t_ref A1) ->\n     styping E P (e_get e) Inf A1\n  | styp_set : forall E P e1 e2 A1,\n     styping E P e1 Inf (t_ref A1) ->\n     styping E P e2 Chk A1->\n     styping E P (e_set e1 e2) Inf t_unit\n.\n\n\nInductive sstyping : env -> phi -> exp -> dirflag -> typ -> dexp -> Prop :=\n  | sstyp_var : forall E P x T,\n      wf_env E ->\n      binds x (bind_typ T) E ->\n      sstyping E P (e_fvar x) Inf T (de_fvar x)\n  | sstyp_nat : forall E P i,\n      wf_env E ->\n      sstyping E P (e_lit i) Inf (t_int) (de_lit i)\n  | sstyp_unit : forall E P,\n      wf_env E ->\n      sstyping E P e_unit Inf t_unit de_unit\n  | sstyp_loc : forall E P l,\n       wf_env E ->\n      l < length P ->\n      wf_typ E (store_Tlookup l P) ->\n      sstyping E P (e_loc l) Inf (t_ref (store_Tlookup l P)) (de_loc l)\n  | sstyp_app : forall E P e1 e2 A B t1 t2,\n      sstyping E P e1 Inf (t_arrow A B) t1 ->\n      sstyping E P e2 Chk A t2 ->\n      sstyping E P (e_app e1 e2) Inf B (de_app t1 t2)\n  | sstyp_abs : forall L E P A B e t,\n      (forall x, x \\notin L ->\n            sstyping (x ~: A ++ E) P (e open_ee_var x) Chk B (t dopen_ee_var x)) ->\n      sstyping E P (e_abs A e B) Inf (t_arrow A B) (de_abs A t)\n  | sstyp_anno : forall E P e A t,\n     sstyping E P e Chk A t ->\n     sstyping E P (e_anno e A) Inf A (de_anno t A)\n  | sstyp_tabs : forall E P e A L t,\n      ( forall a , a \\notin  L  -> \n      sstyping  ( a ~tvar ++ E) P ( e open_te_var a )  Chk  ( A open_tt_var a )   ( t dopen_te_var a ))  ->\n     sstyping E P (e_tabs e A) Inf (t_all A) (de_tabs t)\n  | sstyp_tapp : forall E P e A B t,\n      wf_typ E A ->\n     sstyping E P e Inf (t_all B) t ->\n     sstyping E P (e_tapp e A) Inf  (open_tt B A ) (de_tapp t A)\n  | sstyp_eq : forall E P e B A t,\n     eq E A B ->\n     sstyping E P e Inf A t ->\n     sstyping E P e Chk B t\n  | sstyp_ref : forall E P e A t,\n     sstyping E P e Inf A t ->\n     sstyping E P (e_ref e) Inf (t_ref A) (de_ref t)\n  | sstyp_get : forall E P e A1 t,\n     sstyping E P e Inf (t_ref A1) t ->\n     sstyping E P (e_get e) Inf A1 (de_get t)\n  | sstyp_set : forall E P e1 e2 A1 t1 t2,\n     sstyping E P e1 Inf (t_ref A1) t1 ->\n     sstyping E P e2 Chk A1 t2 ->\n     sstyping E P (e_set e1 e2) Inf t_unit (de_set t1 t2)\n.\n\n\nInductive atyping : env -> phi -> dexp -> dirflag -> typ -> Prop :=\n| atyp_var : forall E P x T,\n    wf_env E ->\n    binds x (bind_typ T) E ->\n    atyping E P (de_fvar x) Inf T\n| atyp_nat : forall E P i,\n    wf_env E ->\n    atyping E P (de_lit i)  Inf (t_int)\n| atyp_unit : forall E P,\n    wf_env E ->\n    atyping E P de_unit  Inf t_unit\n| atyp_loc : forall E P l,\n    wf_env E ->\n    l < length P ->\n    wf_typ E (store_Tlookup l P) ->\n    atyping E P (de_loc l)  Inf  (t_ref (store_Tlookup l P))\n| atyp_app : forall E P e1 e2 A B,\n    atyping E P e1 Inf (t_arrow A B) ->\n    atyping E P e2 Chk  A ->\n    atyping E P (de_app e1 e2)  Inf  B\n| atyp_abs : forall L E P A B e,\n    (forall x, x \\notin L ->\n            atyping (x ~: A ++ E) P (e dopen_ee_var x) Chk  B) ->\n    atyping E P (de_abs A e)  Inf  (t_arrow A B)\n| atyp_anno : forall E P e A,\n    atyping E P e Chk A ->\n    atyping E P (de_anno e A)  Inf  A\n| atyp_tabs : forall E P e A L,\n    ( forall a , a \\notin  L  -> \n    atyping  ( a ~tvar ++ E) P ( e dopen_te_var a )  Chk  ( A open_tt_var a )  )  ->\n    atyping E P (de_tabs e) Inf (t_all A)\n| atyp_tapp : forall E P e A B,\n    wf_typ E A ->\n    atyping E P e  Inf  (t_all B) ->\n    atyping E P (de_tapp e A)  Inf  (open_tt B A )\n| atyp_ref : forall E P e A,\n    atyping E P e Inf  A ->\n    atyping E P (de_ref e) Inf (t_ref A)\n| atyp_get : forall E P e A1,\n    atyping E P e  Inf (t_ref A1) ->\n    atyping E P (de_get e) Inf A1\n| atyp_set : forall E P e1 e2 A1,\n    atyping E P e1  Inf (t_ref A1) ->\n    atyping E P e2 Chk A1->\n    atyping E P (de_set e1 e2) Inf t_unit\n| atyp_eq : forall E P e A B,\n    atyping E P e Inf A ->\n    eq E A B ->\n    atyping E P e Chk B\n.\n\n\n\n\n\nInductive aatyping : env -> phi -> dexp -> dirflag -> typ -> exp -> Prop :=\n| aatyp_var : forall E P x T,\n    wf_env E ->\n    binds x (bind_typ T) E ->\n    aatyping E P (de_fvar x) Inf T (e_fvar x)\n| aatyp_nat : forall E P i,\n    wf_env E ->\n    aatyping E P (de_lit i)  Inf (t_int) (e_lit i)\n| aatyp_unit : forall E P,\n    wf_env E ->\n    aatyping E P de_unit  Inf  t_unit e_unit\n| aatyp_loc : forall E P l,\n    wf_env E ->\n    l < length P ->\n    wf_typ E (store_Tlookup l P) ->\n    aatyping E P (de_loc l) Inf (t_ref (store_Tlookup l P)) (e_loc l)\n| aatyp_app : forall E P e1 e2 A B t1 t2,\n    aatyping E P e1 Inf (t_arrow A B) t1 ->\n    aatyping E P e2  Chk A t2 ->\n    aatyping E P (de_app e1 e2) Inf B (e_app t1 t2)\n| aatyp_abs : forall L E P A B e t,\n    (forall x, x \\notin L ->\n            aatyping (x ~: A ++ E) P (e dopen_ee_var x)  Chk B (t open_ee_var x) ) ->\n    aatyping E P (de_abs A e) Inf (t_arrow A B) (e_abs A t B)\n| aatyp_anno : forall E P e A t,\n    aatyping E P e  Chk A t ->\n    aatyping E P (de_anno e A) Inf A (e_anno t A)\n| aatyp_tabs : forall E P e A L t,\n    ( forall a , a \\notin  L  -> \n    aatyping  ( a ~tvar ++ E) P ( e dopen_te_var a )   Chk ( A open_tt_var a ) ( t open_te_var a ) )  ->\n    aatyping E P (de_tabs e) Inf (t_all A) (e_tabs t A)\n| aatyp_tapp : forall E P e A B t,\n    wf_typ E A ->\n    aatyping E P e Inf (t_all B) t ->\n    aatyping E P (de_tapp e A)  Inf (open_tt B A ) (e_tapp t A) \n| aatyp_ref : forall E P e A t,\n    aatyping E P e Inf A t ->\n    aatyping E P (de_ref e) Inf (t_ref A) (e_ref t)\n| aatyp_get : forall E P e A1 t,\n    aatyping E P e Inf (t_ref A1) t ->\n    aatyping E P (de_get e) Inf A1 (e_get t)\n| aatyp_set : forall E P e1 e2 A1 t1 t2,\n    aatyping E P e1 Inf (t_ref A1) t1 ->\n    aatyping E P e2 Chk A1 t2 ->\n    aatyping E P (de_set e1 e2) Inf t_unit (e_set t1 t2)\n| aatyp_eq : forall E P e A t B,\n    aatyping E P e Inf A t ->\n    eq E A B ->\n    aatyping E P e Chk B t\n.\n\n\n\n\nInductive dstep : conf -> conf -> Prop :=    (* defn step *)\n | dstep_eval : forall mu mu' F e1 e2,\n     wellformed F ->\n     dstep (e1, mu) ((e2), mu') ->\n     dstep ((fill F e1), mu) (( (fill F e2)), mu')\n  | dstep_beta : forall (A1:typ) (e:exp) (B1 A2 B2:typ) u t mu,\n     sto_ok mu ->\n     pvalue u ->\n     expr (e_abs A1 e B1) ->\n     dstep ((e_app  ( (e_anno  ( (e_abs A1 e B1) )  (t_arrow A2 B2)) )  (e_anno u t)), mu) (((e_anno (e_anno  (open_ee  e (e_anno u A1) )  B1) B2)), mu)\n | dstep_u : forall (u:exp) (A:typ) mu,\n     sto_ok mu ->\n     pvalue u ->\n     ptype mu u A ->\n     dstep (u, mu) (( (e_anno u A)), mu)\n | dstep_anno : forall (e:exp) (A:typ) (e':exp) mu mu',\n     not(value (e_anno e A)) ->\n     dstep (e, mu) (( e'), mu') ->\n     dstep ((e_anno e A), mu) (((e_anno e' A)), mu')\n | dstep_annov : forall (A:typ) B u mu,\n     sto_ok mu ->\n     pvalue u ->\n     dstep ((e_anno (e_anno u B) A), mu) ((e_anno u A), mu)\n | dstep_tap : forall (e:exp) (A B C:typ) mu,\n     expr (e_anno  (e_tabs e A) (t_all B)) ->\n     dstep ((e_tapp (e_anno  (e_tabs e A) (t_all B)) C),mu) (((e_anno (e_anno (open_te e C ) (open_tt  A C )) (open_tt  B C ))),mu)\n | dstep_set : forall l A B u t mu,\n     sto_ok mu ->\n     pvalue u ->\n     principle_type (store_lookup l mu) = B ->\n     dstep ((e_set (e_anno (e_loc l)  (t_ref A)) (e_anno u t)), mu) ((e_unit), (replace l (e_anno u B) mu))\n | dstep_new : forall (v:exp) mu,\n     sto_ok mu ->\n     value v ->\n     dstep ((e_ref v), mu) (( (e_loc (length mu))), (mu ++ v::nil))\n | dstep_get : forall (A:typ) l mu,\n     sto_ok mu ->\n     dstep ((e_get (e_anno (e_loc l) (t_ref A))), mu) (((e_anno (store_lookup l mu) A)), mu)\n.\n\n(** Properties for static *)\n\n\nHint Constructors aatyping atyping sstyping denv_static dterm_static dtyp_static styping eq dstep: core.\n\n\nLemma eq_type: forall A B x n,\n x `notin` (fv_tt A) ->\n x `notin` (fv_tt B) ->\n open_tt_rec n x A = open_tt_rec n x B ->\n A = B.\nProof.\n  introv nt1 nt2 eq. gen B n x.\n  inductions A; intros;try solve[].\n  -\n  inductions B; simpl in *; inverts* eq0;\n  unfold open_tt in *; inverts* H0.\n  destruct(n0 == n); try solve[inverts* e];\n  try solve[inverts* H1].\n  -\n  inductions B; simpl in *; inverts* eq0;\n  unfold open_tt in *; inverts* H0.\n  +\n  forwards* h1: IHA1 H2.\n  forwards* h2: IHA2 H1.\n  inverts h1. inverts* h2.\n  +\n  destruct(n0 == n); try solve[inverts* e];\n  try solve[inverts* H1].\n  -\n  inductions B; simpl in *; inverts* eq0;\n  unfold open_tt in *; inverts* H0;\n  destruct(n0 == n); try solve[inverts* e];\n  try solve[inverts* H1].\n  -\n  inductions B; simpl in *; inverts* eq0;\n  unfold open_tt in *; inverts* H0;\n  destruct(n0 == n); try solve[inverts* e];\n  try solve[inverts* H1].\n  destruct(n1 == n); try solve[inverts* e];\n  try solve[inverts* H1].\n  destruct(n1 == n0); try solve[inverts* e];\n  try solve[inverts* H1].\n  destruct(n1 == n0); try solve[inverts* e];\n  try solve[inverts* H1].\n  inverts* H1. inverts* e.\n  exfalso. apply nt2. eauto.\n  -\n  inductions B; simpl in *; inverts* eq0;\n  unfold open_tt in *; inverts* H0.\n  destruct(n0 == n); try solve[inverts* e];\n  try solve[inverts* H1].\n  inverts* H1. inverts* e.\n  exfalso. apply nt1. eauto.\n  -\n  inductions B; simpl in *; inverts* eq0;\n  unfold open_tt in *; inverts* H0.\n  destruct(n0 == n); try solve[inverts* e];\n  try solve[inverts* H1].\n  forwards*: IHA H1.\n  inverts* H.\n  -\n  inductions B; simpl in *; inverts* eq0;\n  unfold open_tt in *; inverts* H0.\n  destruct(n0 == n); try solve[inverts* e];\n  try solve[inverts* H1].\n  forwards*: IHA H1.\n  inverts* H.\n  -\n  inductions B; simpl in *; inverts* eq0;\n  unfold open_tt in *; inverts* H0.\n  destruct(n0 == n); try solve[inverts* e];\n  try solve[inverts* H1].\nQed.\n\n\nLemma eq_left: forall A B E,\n eq E A B ->\n A = B.\nProof.\n  introv eq.\n  inductions eq; eauto.\n  - inverts* IHeq1.  inverts* IHeq2.\n  - pick fresh x.\n    forwards* h1: H0 x.\n    forwards*: eq_type h1.\n    inverts* H1.\n  - inverts* IHeq. \nQed.\n\n\n\nLemma eq_rel: forall E A,\ndtyp_static A ->\n wf_typ E A ->\n wf_env E ->\n eq E A A.\nProof.\n  introv sta ty ev.\n  inductions ty; eauto; try solve[inverts sta].\n  -\n  inverts* sta.\n  -\n  inverts sta.\n  pick fresh x.\n  apply eq_all with (L := union L\n  (union L0\n     (union (fv_tt A)\n        (union (dom E) (fv_tt_env E)))));intros.\n  forwards: H2 x0; auto.\n  -\n  inverts* sta.\nQed.\n\n\nLemma eq_right: forall A B E,\ndtyp_static A ->\n wf_env E ->\n wf_typ E A ->\n wf_typ E B ->\n A = B ->\n eq E A B.\nProof.\n  introv sta ev wf1 wf2 eq.\n  inverts* eq.\n  apply eq_rel; auto.\nQed.\n\nLemma sstyping_atyping: forall e1 e2 G P dir A,\n  sstyping G P e1 dir A e2 ->\n  atyping G P e2 dir A.\nProof.\n  introv typ.\n  inductions typ; eauto.  \nQed.\n\n\n\nLemma aatyping_styping: forall dir e1 e2 G P A,\n aatyping G P e1 dir A e2 ->\n styping G P e2 dir A.\nProof.\n  introv typ.\n  inductions typ; eauto.\nQed.\n\n\n\nLemma dtyp_static_eq: forall E A B,\n    dtyp_static A ->\n    dtyp_static B ->\n    consist E A B ->\n    eq E A B.\nProof.\n  introv ta tb con.\n  inductions con; eauto; try solve[inverts ta];\n  try solve[inverts tb];\n  try solve[inverts ta;inverts tb].\n  -\n  inverts ta; inverts* tb.\n  -\n  inversions tb. inverts ta.\n  pick fresh y and apply eq_all.\n  forwards ~ : H3 y.\n  -\n  inverts ta. inverts* tb.\nQed. \n\n\n\nLemma eq_consist: forall E A B,\n    eq E A B ->\n    consist E A B.\nProof.\n  introv con.\n  inductions con; eauto.\nQed. \n\n\nLemma dtyp_static_dtype : forall A,\n    dtyp_static A ->\n    type A.\nProof.\n  introv ty. inductions ty; simpls~.\n  pick fresh x and apply type_all;eauto.\nQed.\n\n\nHint Resolve dtyp_static_dtype : core.\n\nLemma dterm_static_dterm: forall e,\n    dterm_static e ->\n    expr e.\nProof.\n  introv dm. inductions dm; eauto.\nQed.\n\n\nLemma styping_typing : forall E P e dir A,\n  styping E P e dir A ->\n  typing E P e dir A.\nProof.\n    introv typ.\n    inductions typ;eauto.\n    forwards*: eq_consist H.\nQed.\n\n\n\nLemma dmatch_static_ref : forall A A1,\n    pattern_ref A A1 ->\n    dtyp_static A ->\n    dtyp_static A1 .\nProof.\n  introv mat st. inductions mat; simpls~.\nQed.\n\n\nLemma dmatch_static_abs : forall A A1,\n    pattern_abs A A1 ->\n    dtyp_static A ->\n    dtyp_static A1 .\nProof.\n  introv mat st. inductions mat; simpls~.\nQed.\n\nLemma dmatch_static_all : forall A A1,\n    pattern_all A A1 ->\n    dtyp_static A ->\n    dtyp_static A1 .\nProof.\n  introv mat st. inductions mat; simpls~.\n  inverts st.\nQed.\n\n\nLemma denv_static_dtyp: forall e x T,\n    denv_static e ->\n    binds x (bind_typ T) e ->\n    dtyp_static T.\nProof.\n  introv dm bd. inductions dm; try solve[inverts bd].\n  -\n  analyze_binds bd.\n  inverts* BindsTacVal.\n  -\n  analyze_binds bd.\nQed.\n\n\n\n\nLemma static_open: forall e1 u1  x,\n dtyp_static e1 ->\n dtyp_static u1 ->\n type u1 ->\n dtyp_static (subst_tt x u1 e1).\nProof.\n  introv ts1 ts2 typ1. gen u1 x.\n  inductions ts1; intros; \n  simpl; eauto.\n  -\n  destruct (i == x); eauto.\n  -\n  pick fresh y and apply dtyp_static_all.\n  rewrite subst_tt_open_tt_var; eauto. \nQed.\n\n\n\n\nDefinition Dtyping_static_preserve dir T := \n  match dir with \n  | Inf => dtyp_static T\n  | Chk  => True\n  end.\n\n\n\n\nLemma dtyping_static_preserve : forall E e P dir T,\n    typing E P e dir T ->\n    denv_static E ->\n    dterm_static e ->\n    phi_static P ->\n    Dtyping_static_preserve dir T.\nProof.\n  introv Hty Hen Htm Hpi.\n  inductions Hty; auto; unfold Dtyping_static_preserve in *;simpl; auto.\n  -\n  forwards*: denv_static_dtyp H0.\n  -\n  inverts Hpi.\n  forwards*: H2 l.\n  -\n  inverts Htm.\n  forwards* h1: IHHty1 H2.\n  forwards* h3: dmatch_static_abs H. inverts* h3.\n  -\n  inverts* Htm.\n  -\n  inverts* Htm.\n  -\n  inverts* Htm.\n  -\n  inverts* Htm.\n  forwards* h1: IHHty.\n  inverts H0; try solve[inverts h1].\n  inverts h1.\n    pick fresh y.\n    rewrite (subst_tt_intro y); eauto.\n    forwards*: H1 y.\n    forwards*: static_open H0 H4.\n  -\n  inverts* Htm.\n  -\n  inverts* Htm.\n  forwards* h1: IHHty.\n  forwards* h2: dmatch_static_ref h1.\n  inverts* h2.\nQed.\n\n\n\n\n\nLemma typing_styping : forall E P e dir A,\n  dterm_static e ->\n  denv_static E ->\n  phi_static P ->\n  dtyp_static A ->\n  typing E P e dir A ->\n   styping E P e dir A.\nProof.\n  introv es vs ps ts typ.\n  lets typ': typ.\n  inductions typ;eauto; try solve[inverts es].\n  -\n    inverts es.\n    forwards* h1: dtyping_static_preserve typ1.\n    forwards* h2: dmatch_static_abs H.\n    inverts* h2.\n    forwards*: IHtyp1.\n    forwards* h3: dtyping_static_preserve typ2.\n    inverts* H; try solve[inverts h1].\n  -\n    inverts es.\n    forwards h1: typing_regular typ'.\n    destructs~ h1. inverts H3.\n    pick fresh x and apply styp_abs.\n    forwards*: H0.\n  -\n    inverts* es.\n  -\n    inverts es.\n    pick fresh x. \n    apply styp_tabs with (L := union L\n    (union L0\n       (union (fv_te e)\n          (union (fv_ee e)\n             (union (fv_tt A) (union (dom E) (fv_tt_env E)))))));intros.\n    forwards*: H0.\n  -\n    inverts es.\n    forwards* h1: dtyping_static_preserve typ.\n    forwards* h2: dmatch_static_all H0.\n    inverts* h2.\n    forwards*: IHtyp.\n    inverts* H0; try solve[inverts h1].\n  -\n    forwards* h1: dtyping_static_preserve typ.\n    forwards*: dtyp_static_eq H.\n  -\n    inverts* es.\n    inverts* ts.\n  -\n    inverts es.\n    forwards* h1: dtyping_static_preserve typ.\n    forwards* h2: dmatch_static_ref H.\n    inverts* h2.\n    forwards*: IHtyp.\n    inverts* H; try solve[inverts h1].\n  -\n    inverts es.\n    forwards* h1: dtyping_static_preserve typ1.\n    forwards* h2: dmatch_static_ref H.\n    inverts* h2.\n    forwards*: IHtyp1.\n    forwards* h3: dtyping_static_preserve typ2.\n    inverts* H; try solve[inverts h1].\nQed.\n\n\n\nLemma  eq_sym: forall E t1 t2,\n eq E t1 t2 ->\n eq E t2 t1.\nProof.\n  introv eq.\n  inductions eq;intros; try solve[inductions eq0;eauto];eauto.\nQed.\n\n\nLemma  eq_static: forall E t1 t2,\n eq E t1 t2 ->\n dtyp_static t1 ->\n dtyp_static t2 .\nProof.\n  introv eq sta. gen E t2.\n  inductions sta;intros; try solve[inductions eq0;eauto];eauto.\n  -\n  inverts eq0.\n  forwards*:  eq_sym H2.\n  -\n  inverts eq0.\n  pick fresh x and apply dtyp_static_all;eauto.\nQed.\n\n\nLemma eq_refl: forall t e,\n wf_env e ->\n wf_typ e t ->\n dtyp_static t ->\n eq e t t.\nProof.\n  introv we ev dt. gen e.\n  inductions dt;intros;auto; try solve[inverts ev].\n  -\n    inverts* ev.\n  -\n  inverts ev.\n  pick fresh y and apply eq_all;eauto.\n  -\n  inverts* ev.\nQed.\n\n\n\n\nLemma styping_chk: forall E e P A,\ndenv_static E ->\nphi_static P ->\n dterm_static e ->\n styping E P e Inf A ->\n styping E P e Chk A.\nProof.\n  introv es ps se typ.\n  eapply styp_eq; eauto.\n  forwards h2: styping_typing typ.\n    forwards h1: dtyping_static_preserve h2; auto.\n    unfold Dtyping_static_preserve in *.\n    forwards*: eq_refl h1.\nQed.\n\n\n\nLemma fill_chk_chk: forall G e E P B,\n denv_static G ->\n phi_static P ->\n dterm_static e ->\n styping G P (fill E e) Chk B ->\n dtyp_static B ->\n exists A, styping G P e Chk A.\nProof.\n  introv es ps te typ st.\n  destruct E; unfold fill in *; inverts* typ;\n  try solve[inverts* H0].\n  - inverts H0.\n    forwards h2: styping_typing H5.\n    forwards h1: dtyping_static_preserve h2; auto.\n    unfold Dtyping_static_preserve in *.\n    inverts h1.\n    forwards*: styping_chk H5.\n  -\n    inverts H0.\n    forwards*: styping_chk H6.\n  -\n    inverts H0.\n    forwards*: styping_chk H4.\n  -\n    inverts H0.\n    forwards*: styping_chk H5.\nQed.\n\n\nLemma fill_static: forall F e,\n  dterm_static (fill F e) ->\n  dterm_static e.\nProof.\n introv dt.\n  destruct F; unfold fill in *; auto;\n  try solve[inverts dt; auto].\nQed.\n\n\nLemma eq_trans_size: forall E A B C n,\n size_typ A + size_typ B + size_typ C < n ->\n eq E A B ->\n eq E B C ->\n eq E A C.\nProof.\n  introv sz eq1 eq2. gen E A B C.\n  induction n;intros; \n  try solve[lia].\n  inductions eq1;eauto.\n  -\n  inductions eq2;simpl in *;auto.\n  forwards: IHn eq2_1 eq1_1. lia.\n  forwards: IHn eq1_2 eq2_2. lia.\n  auto.\n  -\n  inductions eq2;simpl in *;auto.\n  pick fresh x and apply eq_all.\n  forwards h1: H x; auto.\n  forwards h2: H1 x; auto.\n  forwards: IHn h1 h2.\n  rewrite size_open_tt.\n  rewrite size_open_tt.\n  rewrite size_open_tt.\n  lia.\n  auto.\n  -\n  inductions eq2;simpl in *;auto.\n  forwards: IHn eq1 eq2. lia.\n  auto.\nQed.\n\n\nLemma eq_trans: forall E A B C,\n eq E A B ->\n eq E B C ->\n eq E A C.\nProof.\n  introv eq1 eq2. \n  eapply eq_trans_size ;eauto.\nQed.\n\n\n\nLemma sptype_inf: forall G mu P u A,\n P |== mu ->\n pvalue u -> \n styping G P u Inf A -> \n ptype mu u A.\nProof.\n  introv sto pval typ.\n  inverts* typ; try solve[inverts* pval].\n  inverts sto. inverts H3.\n  rewrite H4 in H0. \n  forwards*: H5 H0.\n  forwards*: sto_ok_value H0 H2. \n  forwards*: principle_typ_inf H3.\nQed.\n\n\nLemma sprinciple_typ_inf: forall G P u A,\n value u -> \n styping G P u Inf A -> \n principle_type u = A.\nProof.\n  introv val typ.\n  inverts* val; try solve[inverts* typ].\nQed.\n\n\n\nTheorem static_ddstep_dyn_chk : forall e e' B P mu mu',\n  P |== mu ->\n  phi_static P ->\n dterm_static e ->\n dtyp_static B ->\n styping nil P e Chk B ->\n dstep ( e, mu) ( e', mu') -> \n step (e, mu) ((r_e e'), mu').\nProof.\n introv wel ps ts tys typ red. gen B P.\n inductions red; intros; eauto;\n try solve[forwards*:eq_consist  H1];\n try solve[forwards*: eq_consist H0].\n - forwards h0 :  fill_static ts.\n   forwards hh0: fill_chk_chk typ; auto. \n   inverts hh0.\n   inverts H0.\n   forwards h2: styping_typing H2.\n   forwards h1: dtyping_static_preserve h2; auto.\n   unfold Dtyping_static_preserve in *.\n   forwards : eq_static H1; auto.\n   eauto.\n  -\n    inverts typ. inverts H3.\n    inverts H9.\n    forwards* h1: styping_typing H4.\n    inverts H8. inverts H11. inverts H6. inverts H5. \n    inverts H4. inverts H8.\n    forwards* h2: eq_consist H4.\n    forwards* h3: eq_trans H4 H3.\n    forwards* h4:eq_consist h3.\n    assert(styping empty P (e_anno u A0) Inf A0); eauto.\n    forwards* h5: styping_typing H6.\n    forwards* h6: eq_trans h3 H10.\n    forwards* h7:eq_consist h6.\n    forwards*: TypedReduce_progress A0 h1.\n    inverts* H7.\n    lets red1: H8. \n    inverts* H8.\n    +\n    forwards* h8: sptype_inf H5.\n    forwards*: ptype_uniq H17 h8. inverts* H7.\n    forwards*: TypedReduce_progress A1 h5.\n    inverts* H7.\n    lets red2: H8. \n    inverts* H8.\n    forwards*: ptype_uniq H17 H20. inverts* H7.\n    +\n    forwards* h8: sptype_inf H5.\n    forwards*: ptype_uniq H17 h8. inverts* H7.\n  -\n    inverts ts.\n    inverts typ. inverts* H1.\n  - inverts typ. inverts* H2.\n    lets typ':H6.\n    inverts* H6. inverts* H3.\n    inverts* H7.\n    forwards*:  sptype_inf H4.\n    forwards*: eq_trans H3 H2.\n    forwards*: eq_trans H6 H1.\n    forwards*: eq_consist H6.\n    forwards*: styping_typing typ'.\n    inverts H9.\n    forwards*: TypedReduce_progress A0 H11.\n    forwards* h1: eq_consist H3.\n    inverts* H9.\n    lets H12': H12.\n    inverts* H12.\n    forwards*: ptype_uniq H5 H18. inverts* H9.\n    forwards*: eq_consist H3.\n    forwards*: ptype_uniq H5 H18. inverts* H9.\n    -\n    inverts typ. inverts* H2.\n    forwards* typ': styping_typing H8.\n    inverts H7. inverts H9. inverts* H3.\n    inverts* H2. \n    inverts* H8. inverts* H3. inverts* H11.\n    forwards* h1:  sptype_inf H4.\n    forwards* h2: eq_trans H3 H2.\n    forwards* h3: eq_sym H9. \n    forwards*: eq_trans h2 h3.\n    forwards*: eq_consist H2.\n    forwards* h4: eq_consist H7.\n    forwards* h5: eq_consist h2.\n    inverts* typ'.\n    forwards*: TypedReduce_progress A1 H12.\n    inverts* H13.\n    lets red1: H14. \n    inverts* H14.\n    +\n    forwards*: ptype_uniq h1 H20. inverts* H13.\n    forwards*: eq_consist H3.\n    inverts H12. inverts* H17.\n    assert(styping empty P (e_anno u A1) Inf A1);eauto.\n    forwards* h6: styping_typing H15.\n    forwards* h7:  TypedReduce_progress (store_Tlookup l P) h6.\n    inverts* h7. \n    lets h9: H16. inverts H16.\n    forwards* h8: ptype_uniq H26 H20. inverts* h8.\n    inverts wel.\n    inverts H17.\n    rewrite H18 in *.\n    forwards h10: H22 l. auto.\n    forwards h11: principle_typ_inf h10.\n    forwards*: sto_ok_value H16.\n    rewrite h11 in *.\n    eapply  step_set; eauto.\n    forwards* h8: ptype_uniq H26 H20. inverts* h8.\n    +\n    forwards* h8: ptype_uniq H20 h1. inverts* h8.\nQed.\n\n\nTheorem static_stepd_dyn_chk : forall G e e' B P mu mu',\nP |== mu ->\n  phi_static P ->\n  denv_static G ->\n  dterm_static e ->\n dtyp_static B ->\n styping G P e Chk B ->\n step (e, mu) ((r_e e'), mu') ->\n dstep ( e, mu) ( e', mu').\nProof.\n introv wel ps envs es ts typ red. \n gen G B P.\n inductions red; intros; eauto;\n try solve[forwards*:dtyp_static_eq  H1];\n try solve[forwards*: dtyp_static_eq H0].\n -\n   forwards h0: fill_static es.\n   forwards hh1: fill_chk_chk typ; auto.\n   inverts hh1.\n   inverts H0.\n   forwards h2: styping_typing H2. \n   forwards h1: dtyping_static_preserve h2; auto.\n   unfold Dtyping_static_preserve in *.\n   forwards h3: eq_static H1; auto.\n   eauto.\n  -\n    inverts es.\n    inverts typ. inverts* H5.\n    inverts* H12. inverts* H2.\n    inverts H3. inverts H14. inverts* H15.\n    inverts H0.\n    inverts H13. inverts H5.\n    inverts H14.\n    forwards* h1: sptype_inf H11.\n    forwards*:eq_trans H5 H0.\n    forwards*:eq_consist H12.\n    inverts H9.\n    inverts H10. inverts H14. inverts H9.\n    forwards*:eq_trans H12 H17.\n    forwards*:eq_consist H9.\n    inverts* H8.\n  -\n    inverts es.\n    inverts typ. inverts* H1.\n  -\n    inverts es.\n    inverts typ. inverts* H3.\n    inverts* H9. inverts* H1.\n  -\n    inverts es.\n    inverts typ. inverts* H2.\n    inverts* H10. inverts* H3.\n    inverts* H0.\n  -\n    inverts es.\n    inverts typ. inverts* H4.\n    inverts* H11. inverts* H3.\n    inverts* H9. inverts* H4.\n    inverts* H2. inverts* H16.\n    inverts H12.\n    inverts H0. inverts H4.\n    inverts* H16.\n    forwards* h1:  sptype_inf  H4.\n    forwards* h2: eq_trans H0 H2.\n    forwards* h3: eq_consist h2.\n    inverts H3.\n    forwards*: eq_sym H18.\n    forwards* h4: eq_trans h2 H3.\n    forwards* h5: eq_consist h4.\n    inverts H11.\n    inverts wel.\n    inverts H14.\n    rewrite H15 in *.\n    forwards*: H16.\n    forwards*: sto_ok_value H11.\n    forwards* h6:  principle_typ_inf  H14.\n    rewrite <- h6 in *.\n    inverts* H10.\n    inverts* H17.\n  -\n    inverts es.\n    inverts typ. inverts* H3.\n    inverts* H7. inverts* H0.\nQed.\n\n", "meta": {"author": "YeWenjia", "repo": "Pragmatic-Gradual-Polymorphism-with-References", "sha": "baab136721626038e735f58f81752efcb7088238", "save_path": "github-repos/coq/YeWenjia-Pragmatic-Gradual-Polymorphism-with-References", "path": "github-repos/coq/YeWenjia-Pragmatic-Gradual-Polymorphism-with-References/Pragmatic-Gradual-Polymorphism-with-References-baab136721626038e735f58f81752efcb7088238/Gradual/coq/Static.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2871522673399509}}
{"text": "Require Import floyd.proofauto.\nRequire Import aes.spec_AES256_HL.\n\nRequire Import Coqlib.\nRequire Import msl.Coqlib2.\nRequire Import floyd.coqlib3.\nRequire Import Integers.\nRequire Import List.\nRequire Import zlist.sublist.\nRequire Import sha.SHA256.\nRequire Import sha.general_lemmas.\n\nLocal Open Scope logic.\n\n(* utility functions for convertin the funcational spec's data structures\n * into C data structures *)\nDefinition word_to_int (w : word) : int :=\n  match w with (b0, b1, b2, b3) => little_endian_integer [b0; b1; b2; b3] end.\n\nDefinition words_to_ints (words : list word) : list int := map word_to_int words.\n\nDefinition block_to_ints (b : block) : list int :=\n  match b with (w0, w1, w2, w3) => [word_to_int w0; word_to_int w1; word_to_int w2; word_to_int w3] end.\n\nDefinition blocks_to_ints (blocks : list block) : list int := flat_map block_to_ints blocks.\n\n(* stipulate that the different ints used to represent bytes are indeed in range *)\nDefinition word_in_bounds (w : word) :=\n  match w with\n      (b0, b1, b2, b3) => (Int.unsigned b0 < 256 /\\ Int.unsigned b1 < 256 /\\ Int.unsigned b2 < 256 /\\ Int.unsigned b3 < 256)\n  end.\nDefinition block_in_bounds (b : block) :=\n   match b with (w0, w1, w2, w3) => (word_in_bounds w0 /\\ word_in_bounds w1 /\\ word_in_bounds w2 /\\ word_in_bounds w3) end.\nDefinition words_in_bounds (words : list word) := forall w : word, In w words -> word_in_bounds w.\nDefinition blocks_in_bounds (blocks : list block) := forall b : block, In b blocks -> block_in_bounds b.\n\n(* Coq implementations of functions in the mbed TLS implementation, which we will\n * have to prove correspond to the spec *)\n\n(* Implemenation's RCON table includes two constants not used in AES256 *)\nDefinition full_rcons := RCon ++ [\n  (Int.repr 27 (* 0x1b *), Int.zero, Int.zero, Int.zero);\n  (Int.repr 54 (* 0x36 *), Int.zero, Int.zero, Int.zero)\n].\n\n(* similar to grow_key in the functional specification, but always applies both an even\n * and an odd round instead of having a special case for the last round. This is not\n * called for in the functional specification, but this is what the program does, thus\n * producing an extra block *)\nFixpoint grow_key_extra (b1 b2: block) (rcs: list word) : list block :=\n  match rcs with\n  | hd :: tl =>\n    let b3 := odd_round b1 b2 hd in\n    let b4 := even_round b2 b3 in\n    b3 :: b4 :: grow_key_extra b3 b4 tl\n  | [] => []\n  end.\nDefinition extra_key_expansion (k : list word) : list block :=\n  match k with\n  | [w1; w2; w3; w4; w5; w6; w7; w8] =>\n    let b1 := (w1, w2, w3, w4) in\n    let b2 := (w5, w6, w7, w8) in\n    b1 :: b2 :: (grow_key_extra b1 b2 RCon)\n  | l => [] (* should not happen *)\n  end.\n\n(* The implementation generates GF(256) exponentiation and logarithm tables,\n * both base 3. It uses these for multiplication *)\nFixpoint gen_exp_table (n : nat) (base : int) : list int :=\n  match n with\n  | O => []\n    (* b XOR (xtime b) = 3*b in GF(256) *)\n  | S n' => base :: gen_exp_table n' (Int.xor base (xtime base))\n  end.\n\nFixpoint mapi_aux {A B : Type} (f : Z -> A -> B) (pos : Z) (l : list A) : list B :=\n  match l with\n  | [] => []\n  | hd :: tl => f pos hd :: mapi_aux f (pos+1) tl\n  end.\n\nDefinition mapi {A B : Type} (f : Z -> A -> B) (l : list A) : list B := mapi_aux f 0 l.\n\nFixpoint insert_idx {A : Type} (l : list (Z * A)) (p : (Z * A)) : list (Z * A) :=\n  match p with (i, a) =>\n    match l with\n    | [] => p :: []\n    | ((i', b) as hd) :: tl =>\n      if i =? i' then p :: tl (* replace equal entries *)\n      else if i <? i' then p :: hd :: tl\n      else hd :: insert_idx tl p\n    end\n  end.\n\nDefinition sort_idx {A : Type} (l : list (Z * A)) : list (Z * A) :=\n  fold_left insert_idx l [].\n\n(* the implemenation generates the log table by actually computing\n * x = 3^i, then setting log[x] = i. This is not easy to do in Coq,\n * so instead we generate the power table, pair each entry with its\n * index, sort by entry, and return the indices *)\nDefinition gen_log_table (n : nat) (base : int) : list int :=\n  let exp := gen_exp_table n base in\n  let indexed := mapi (fun i e => (Int.unsigned e, Int.repr i)) exp in\n  let sorted := sort_idx indexed in\n  (* zero is an arbitrary entry at the beginning because log 0 is undefined *)\n  Int.zero :: map snd sorted.\n\n(* ith element is 3^i in GF(256) *)\nDefinition ff_exp_table := gen_exp_table 256 Int.one.\n(* ith element is log base 3 of i in GF(256). Zeroth entry is arbitrarily 0 *)\nDefinition ff_log_table := gen_log_table 256 Int.one.\n\n(* We will show that GF(256) arithmetic done by peasant multiplication\n * is equivalent to the method used by the implementation, namely using\n * log and exponentiation tables. The implementation takes log of a and b,\n * adds them mod 255 (not mod 256) and returns exp of that,\n * returning 0 if a or b is 0 *)\nDefinition table_ff_mult (a b: int) : int :=\n  if Int.eq a Int.zero then Int.zero\n  else if Int.eq b Int.zero then Int.zero\n  else\n    let log_a := Znth (Int.unsigned a) ff_log_table Int.zero in\n    let log_b := Znth (Int.unsigned b) ff_log_table Int.zero in\n    let idx := Int.modu (Int.add log_a log_b) (Int.repr 255) in\n    Znth (Int.unsigned idx) ff_exp_table Int.zero.\n\nFixpoint repeat_op (op : int -> int) (times : nat) (arg : int) : int :=\n  match times with\n  | O => arg\n  | S n => op (repeat_op op n arg)\n  end.\n\n(* implement exponentiation by repeated multiplication, which we will use\n * to verify correctness of our exp and log tables *)\nDefinition ff_exp (a b : int) := repeat_op (ff_mult a) (Z.to_nat (Int.unsigned b)) Int.one.\n\n(* Forward and reverse table generation *)\n\n(* The forward and reverse tables are used by the implementation to perform the\n * MixColumns and SubBytes step simply by XORing entries from a lookup table. *)\nFixpoint generate_forward_table (table : list int) : list word :=\n  match table with\n  | hd :: tl =>\n    let x := hd in\n    let y := xtime hd in\n    let z := Int.xor y x in\n    (y, x, x, z) :: generate_forward_table tl\n  | [] => []\n  end.\n\nDefinition ft_words := generate_forward_table (map Int.repr sbox).\n\n(* opposite direction of RotWord, brings last byte to front. Applies\n * rotation n times *)\nFixpoint rotate (n : nat) (w : word) : word :=\n  match n with\n  | O => w\n  | S n' => match w with (w0, w1, w2, w3) => (rotate n' (w3, w0, w1, w2)) end\n  end.\n\nDefinition FT0 := words_to_ints ft_words.\nDefinition FT1 := words_to_ints (map (rotate 1%nat) ft_words).\nDefinition FT2 := words_to_ints (map (rotate 2%nat) ft_words).\nDefinition FT3 := words_to_ints (map (rotate 3%nat) ft_words).\n\nFixpoint generate_reverse_table (table : list int) : list word :=\n  let c_e := Int.repr 14 in (* 0x0e *)\n  let c_b := Int.repr 11 in (* 0x0b *)\n  let c_d := Int.repr 13 in (* 0x0d *)\n  let c_9 := Int.repr 9 in (* 0x09 *)\n  match table with\n  | hd :: tl =>\n    (ff_mult c_e hd, ff_mult c_9 hd, ff_mult c_d hd, ff_mult c_b hd) :: generate_reverse_table tl\n  | [] => []\n  end.\n\nDefinition rt_words := generate_reverse_table (map Int.repr inv_sbox).\n\nDefinition RT0 := words_to_ints rt_words.\nDefinition RT1 := words_to_ints (map (rotate 1%nat) rt_words).\nDefinition RT2 := words_to_ints (map (rotate 2%nat) rt_words).\nDefinition RT3 := words_to_ints (map (rotate 3%nat) rt_words).\n\n(* Using the forward and reverse tables to implement the AES round\n * and reverse round *)\n\nDefinition zlist_to_col (c : int) : (Z * Z * Z * Z) :=\n  let bytes := intlist_to_Zlist [c] in\n  match bytes with\n  | b3 :: b2 :: b1 :: b0 :: [] => (b0, b1, b2, b3)\n  | _ => (0, 0, 0, 0) (* should not happen *)\n  end.\n\nDefinition mbed_tls_fround_col (b0 b1 b2 b3 : Z) (rk : int) : int :=\n  let f0 := Znth b0 FT0 Int.zero in\n  let f1 := Znth b1 FT1 Int.zero in\n  let f2 := Znth b2 FT2 Int.zero in\n  let f3 := Znth b3 FT3 Int.zero in\n  fold_left Int.xor [f0; f1; f2; f3] rk.\n\n(* we want to represent a round using the mbed TLS implementation's representation of the data structures\n * and show that this maps back to our functional specification. Corresponds to\n * the AES_FROUND macro *)\nDefinition mbed_tls_fround (cols : list int) (rk : list int) : list int :=\n  match (cols, rk) with\n  | (c3 :: c2 :: c1 :: c0 :: [], k3 :: k2 :: k1 :: k0 :: []) =>\n      match (zlist_to_col c0, zlist_to_col c1, zlist_to_col c2, zlist_to_col c3) with\n            ((c00, c01, c02, c03), (c10, c11, c12, c13),\n             (c20, c21, c22, c23), (c30, c31, c32, c33)) =>\n       [mbed_tls_fround_col c00 c11 c22 c33 k0;\n        mbed_tls_fround_col c10 c21 c32 c03 k1;\n        mbed_tls_fround_col c20 c31 c02 c13 k2;\n        mbed_tls_fround_col c30 c01 c12 c23 k3]\n      end\n  | _ => [] (* should not happen *)\n  end.\n\nDefinition mbed_tls_rround_col (b0 b1 b2 b3 : Z) (rk : int) : int :=\n  let r0 := Znth b0 RT0 Int.zero in\n  let r1 := Znth b1 RT1 Int.zero in\n  let r2 := Znth b2 RT2 Int.zero in\n  let r3 := Znth b3 RT3 Int.zero in\n  fold_left Int.xor [r0; r1; r2; r3] rk.\n\n(* Corresponds to the AES_RROUND macro *)\nDefinition mbed_tls_rround (cols : list int) (rk : list int) : list int :=\n  match (cols, rk) with\n  | (c3 :: c2 :: c1 :: c0 :: [], k3 :: k2 :: k1 :: k0 :: []) =>\n      match (zlist_to_col c0, zlist_to_col c1, zlist_to_col c2, zlist_to_col c3) with\n            ((c00, c01, c02, c03), (c10, c11, c12, c13),\n             (c20, c21, c22, c23), (c30, c31, c32, c33)) =>\n      (* note that column positions differ from the forward round *)\n       [mbed_tls_rround_col c00 c31 c22 c13 k0;\n        mbed_tls_rround_col c10 c01 c32 c23 k1;\n        mbed_tls_rround_col c20 c11 c02 c33 k2;\n        mbed_tls_rround_col c30 c21 c12 c03 k3]\n      end\n  | _ => [] (* should not happen *)\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/aes/unused/aesutils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778403, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2871007066665309}}
{"text": "(******************************************************************************)\n(** * Events of the Power memory model *)\n(******************************************************************************)\nRequire Import Hahn.\nRequire Import Basic Events.\nRequire Export Events.\n\nSet Implicit Arguments.\nRemove Hints plus_n_O.\n\nInductive label := \n  | Aload (l: location) (v: value)\n  | Astore (l: location) (v: value)\n  | Afence_lwsync\n  | Afence_sync.\n\nDefinition init_label l :=  (Astore l 0).\n\nSection Labels.\n\nVariable lab : event -> label.\n\nDefinition loc a :=\n  match lab a with\n  | Aload l _\n  | Astore l _ => Some l\n  | _ => None\n  end.\n\nDefinition val a :=\n  match lab a with\n  | Aload  _ v \n  | Astore _ v => Some v\n  | _ => None\n  end.\n\nDefinition is_r a := \n  match lab a with\n  | Aload  _ _ => True\n  | _ => False\n  end.\n\nDefinition is_w a := \n  match lab a with\n  | Astore _ _ => True\n  | _ => False\n  end.\n\nDefinition is_f_sync a := \n  match lab a with\n  | Afence_sync => True\n  | _ => False\n  end.\n\nDefinition is_f_lwsync a :=\n  match lab a with\n  | Afence_lwsync => True\n  | _ => False\n  end.\n\nEnd Labels.\n\nLemma eq_dec_labels :\n  forall x y : label, {x = y} + {x <> y}.\nProof.\nrepeat decide equality.\nQed.", "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_Events.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2871007066665308}}
{"text": "Require Import Rupicola.Lib.Api.\nRequire Import Rupicola.Lib.Arrays.\nRequire Import Rupicola.Lib.Loops.\nRequire Import Rupicola.Lib.WordNotations.\nRequire Import coqutil.Word.LittleEndianList.\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  Section GetPut.\n    Definition packet :=\n      Vector.t word 2. (* field1, ttl *)\n\n    Definition __lt {a b: nat} : if lt_dec a b return Prop then Nat.lt a b else True :=\n      match lt_dec a b as c return (if c return Prop then Nat.lt a b else True) with\n      | left pr => pr\n      | _ => I\n      end.\n\n    Notation _lt :=\n      ltac:(lazymatch goal with\n            | [  |- (?a < ?b)%nat ] => exact (@__lt a b)\n            end) (only parsing).\n\n    Notation ttl_idx := 1%nat.\n    Definition field1 (p: packet) := (VectorArray.get p 0%nat _lt).\n    Definition ttl (p: packet) := (VectorArray.get p ttl_idx _lt).\n\n    Definition Packet (addr: word) (p: packet) : mem -> Prop :=\n      vectorarray_value AccessWord addr p.\n\n    Definition decr_gallina (p: packet) :=\n      let/n ttl := (ttl p) in\n      let/n ttl := word.add ttl (word.of_Z (-1)) in\n      let/n p := VectorArray.put p ttl_idx _lt ttl in\n      p.\n\n    Hint Unfold Packet : compiler_cleanup.\n\n    Instance spec_of_decr : spec_of \"decr\" :=\n      fnspec! \"decr\" ptr / p R,\n      { requires tr mem :=\n          (Packet ptr p ⋆ R) mem;\n        ensures tr' mem' :=\n          tr' = tr /\\ (Packet ptr (decr_gallina p) ⋆ R) mem' }.\n\n    Import VectorArrayCompiler.\n    Hint Unfold ttl : compiler_cleanup.\n\n    Derive decr_br2fn SuchThat\n           (defn! \"decr\"(\"p\") { decr_br2fn },\n            implements decr_gallina)\n      As decr_br2fn_ok.\n    Proof.\n      compile.\n    Qed.\n  End GetPut.\n\n  Section Loops.\n    Definition mask_bytes (bs: ListArray.t byte) mask :=\n      let/n bs := ListArray.map (byte.and mask) bs in bs.\n\n    Definition xor_bytes (bs: ListArray.t byte) :=\n      let/n r := Byte.x00 in\n      let/n r := ListArray.fold_left byte.xor bs Byte.x00 in\n      r.\n\n    Definition incr_words (ws: ListArray.t word) :=\n      let/n ws := ListArray.map (word.add (word.of_Z 1)) ws in ws.\n\n    Definition sum_words (ws: ListArray.t word) :=\n      let/n r := word.of_Z 0 in\n      let/n r := ListArray.fold_left word.add ws r in\n      r.\n\n    Import LoopCompiler.\n    Import SizedListArrayCompiler.\n    Hint Extern 10 => lia : compiler_side_conditions.\n\n    Notation bytes := (sizedlistarray_value access_size.one).\n    Notation words := (sizedlistarray_value access_size.word).\n\n    Instance spec_of_mask_bytes : spec_of \"mask_bytes\" :=\n      fnspec! \"mask_bytes\" ptr wlen wmask / (bs : ListArray.t byte) mask R,\n        { requires tr mem :=\n            wmask = word.of_Z (byte.unsigned mask) /\\\n            wlen = word.of_Z (Z.of_nat (length bs)) /\\\n            Z.of_nat (length bs) < 2 ^ width /\\\n            (bytes (length bs) ptr bs ⋆ R) mem;\n          ensures tr' mem' :=\n            tr' = tr /\\\n            (bytes (length bs) ptr (mask_bytes bs mask) ⋆ R) mem' }.\n\n    Derive mask_bytes_br2fn SuchThat\n           (defn! \"mask_bytes\" (\"bs\", \"len\", \"mask\") { mask_bytes_br2fn },\n            implements mask_bytes)\n           As mask_bytes_br2fn_ok.\n    Proof.\n      Time compile.\n    Qed.\n\n    Instance spec_of_xor_bytes : spec_of \"xor_bytes\" :=\n      fnspec! \"xor_bytes\" ptr wlen / (bs : ListArray.t byte) R ~> r,\n        { requires tr mem :=\n            wlen = word.of_Z (Z.of_nat (length bs)) /\\\n            Z.of_nat (length bs) < 2 ^ width /\\\n            (bytes (length bs) ptr bs ⋆ R) mem;\n          ensures tr' mem' :=\n            tr' = tr /\\ r = word.of_Z (byte.unsigned (xor_bytes bs)) /\\\n            (bytes (length bs) ptr bs ⋆ R) mem' }.\n\n    Derive xor_bytes_br2fn SuchThat\n           (defn! \"xor_bytes\" (\"bs\", \"len\") ~> \"r\" { xor_bytes_br2fn },\n            implements xor_bytes)\n           As xor_bytes_br2fn_ok.\n    Proof.\n      Time compile.\n    Qed.\n\n    Instance spec_of_incr_words : spec_of \"incr_words\" :=\n      fnspec! \"incr_words\" ptr wlen / (ws : ListArray.t word) R,\n        { requires tr mem :=\n            wlen = word.of_Z (Z.of_nat (length ws)) /\\\n            Z.of_nat (length ws) < 2 ^ width /\\\n            (words (length ws) ptr ws ⋆ R) mem;\n          ensures tr' mem' :=\n            tr' = tr /\\\n            (words (length ws) ptr (incr_words ws) ⋆ R) mem' }.\n\n    Derive incr_words_br2fn SuchThat\n           (defn! \"incr_words\" (\"ws\", \"len\") { incr_words_br2fn },\n            implements incr_words)\n           As incr_words_br2fn_ok.\n    Proof.\n      Time compile.\n    Qed.\n\n    Instance spec_of_sum_words : spec_of \"sum_words\" :=\n      fnspec! \"sum_words\" ptr wlen / (ws : ListArray.t word) R ~> r,\n        { requires tr mem :=\n            wlen = word.of_Z (Z.of_nat (length ws)) /\\\n            Z.of_nat (length ws) < 2 ^ width /\\\n            (words (length ws) ptr ws ⋆ R) mem;\n          ensures tr' mem' :=\n            tr' = tr /\\ r = word.of_Z (word.unsigned (sum_words ws)) /\\\n            (words (length ws) ptr ws ⋆ R) mem' }.\n\n    Derive sum_words_br2fn SuchThat\n           (defn! \"sum_words\" (\"ws\", \"len\") ~> \"r\" { sum_words_br2fn },\n            implements sum_words)\n           As sum_words_br2fn_ok.\n    Proof.\n      Time compile.\n    Qed.\n  End Loops.\n\n  Section Casts.\n    Notation bytes := (listarray_value (memT := mem) (word := word) access_size.one).\n    Notation words := (listarray_value (memT := mem) (word := word) access_size.word).\n\n    Notation of_nat n := (word.of_Z (Z.of_nat n)).\n    Notation of_Z := word.of_Z.\n    Notation unsigned := word.unsigned.\n\n    Notation bs2ws := (bs2ws (word := word) (Memory.bytes_per (width := width) access_size.word)).\n    Notation ws2bs := (ws2bs (word := word) (Memory.bytes_per (width := width) access_size.word)).\n    Notation bytes_per_word := (Memory.bytes_per (width := width) access_size.word).\n\n(*|\nA simple program that takes as input an array of bytes, reinterprets it as an array of little-endian machine words, and counts the number of matches for a given search term in the resulting array.\n|*)\n\n    Definition count_ws (data: ListArray.t byte) (needle: word) :=\n      let/n r := 0 in\n      let/n data := bs2ws data in\n      let/n r := ListArray.fold_left (fun r w64 =>\n           let/n hit := word.eqb w64 needle in\n           let/n r := r + Z.b2z hit in\n           r)\n        data 0 in\n      let/n data := ws2bs data in\n      r.\n\n(*|\nInstead of applying the mask byte by byte, the program starts by casting its input into a list of 64-bit words, processes these words, and finally casts the result back to a lists of bytes.  Without loading appropriate libraries, Rupicola will not recognize these patterns:\n|*)\n\n    Instance spec_of_count_ws : spec_of \"count_ws\" :=\n      fnspec! \"count_ws\" ptr wlen needle / (bs: list byte) R ~> r, {\n        requires tr mem :=\n          wlen = of_nat (length bs) /\\\n          Z.of_nat (length bs) < 2 ^ width /\\\n          (Datatypes.length bs mod bytes_per_word = 0)%nat /\\\n          (bytes ptr bs ⋆ R) mem;\n        ensures tr' mem' :=\n          tr' = tr /\\ r = of_Z (count_ws bs needle) /\\\n          (bytes ptr bs ⋆ R) mem'\n      }.\n\n    Lemma bytes_as_words ptr bs:\n      (length bs mod bytes_per_word = 0)%nat ->\n      Lift1Prop.iff1 (bytes ptr bs) (words ptr (bs2ws bs)).\n    Proof. apply words_of_bytes. Qed.\n\n    Lemma words_as_bytes ptr bs:\n      (length bs mod bytes_per_word = 0)%nat ->\n      Lift1Prop.iff1 (words ptr (bs2ws bs)) (bytes ptr bs).\n    Proof. symmetry; apply words_of_bytes; assumption. Qed.\n\n    Lemma compile_bs2ws [t m l σ] (bs: list byte):\n      let v := bs2ws bs in\n      forall {P} {pred: P v -> _} {k: nlet_eq_k P v} K r bs_var ptr,\n        (bytes ptr bs ⋆ r) m ->\n        (length bs mod bytes_per_word = 0)%nat ->\n        (forall m' : mem,\n          (words ptr v ⋆ r) m' ->\n          <{ Trace := t; Memory := m'; Locals := l; Functions := σ }> K <{ pred (k v eq_refl) }>) ->\n        <{ Trace := t; Memory := m; Locals := l; Functions := σ }>\n          K\n        <{ pred (let/n x as bs_var eq:Heq := v in k x Heq) }>.\n    Proof. intros; seprewrite_in bytes_as_words H; eauto. Qed.\n\n    Lemma compile_bs2ws_rev [t m l σ] (bs: list byte):\n      let v := ws2bs (bs2ws bs) in\n      forall {P} {pred: P v -> _} {k: nlet_eq_k P v} K r bs_var ptr,\n\n        (words ptr (bs2ws bs) ⋆ r) m ->\n        (length bs mod bytes_per_word = 0)%nat ->\n\n        (forall m' : mem,\n            (bytes ptr bs ⋆ r) m' ->\n            <{ Trace := t; Memory := m'; Locals := l; Functions := σ }>\n              K\n            <{ pred (k v eq_refl) }>) ->\n\n        <{ Trace := t; Memory := m; Locals := l; Functions := σ }>\n          K\n        <{ pred (let/n x as bs_var eq:Heq := v in k x Heq) }>.\n    Proof. intros; seprewrite_in (words_as_bytes) H; eauto. Qed.\n\n    Import UnsizedListArrayCompiler.\n\n    Hint Extern 1 => simple eapply compile_bs2ws; shelve : compiler.\n    Hint Extern 1 => simple eapply compile_bs2ws_rev; shelve : compiler.\n    Hint Extern 1 => (pose proof bytes_per_range access_size.word) : nia.\n    Hint Rewrite @bs2ws_length using solve[eauto with nia] : compiler_side_conditions.\n    Hint Rewrite Nat2Z.inj_div : compiler_side_conditions.\n    Hint Extern 10 => eauto with nia : compiler_side_conditions.\n\n    Derive count_ws_br2fn SuchThat\n      (defn! \"count_ws\"(\"data\", \"len\", \"needle\") ~> \"r\" { count_ws_br2fn },\n       implements count_ws) As count_ws_br2fn_ok.\n    Proof.\n      compile.\n    Qed.\n  End Casts.\nEnd with_parameters.\n\nFrom bedrock2 Require Import BasicC64Semantics NotationsCustomEntry.\nCompute decr_br2fn (word := word).\nCompute mask_bytes_br2fn (width := 64).\nCompute xor_bytes_br2fn (word := word).\nCompute incr_words_br2fn (word := word).\nCompute sum_words_br2fn (word := word).\nCompute count_ws_br2fn (word := word).\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/Arrays.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2871007066665308}}
{"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 ARM code generation: auxiliary results. *)\n\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import Maps.\nRequire Import AST.\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 Asm.\nRequire Import Asmgen.\nRequire Import Conventions.\nRequire Import Asmgenproof0.\n\n(** Useful properties of the R14 registers. *)\n\nLemma ireg_of_not_R14:\n  forall m r, ireg_of m = OK r -> IR r <> IR IR14.\nProof.\n  intros. erewrite <- ireg_of_eq; eauto with asmgen.\nQed.\nHint Resolve ireg_of_not_R14: asmgen.\n\nLemma ireg_of_not_R14':\n  forall m r, ireg_of m = OK r -> r <> IR14.\nProof.\n  intros. generalize (ireg_of_not_R14 _ _ H). congruence.\nQed.\nHint Resolve ireg_of_not_R14': asmgen.\n\n(** Useful simplification tactic *)\n\nLtac Simplif :=\n  ((rewrite nextinstr_inv by eauto with asmgen)\n  || (rewrite nextinstr_inv1 by eauto with asmgen)\n  || (rewrite Pregmap.gss)\n  || (rewrite nextinstr_pc)\n  || (rewrite Pregmap.gso by eauto with asmgen)); auto with asmgen.\n\nLtac Simpl := repeat Simplif.\n\n(** * Correctness of ARM constructor functions *)\n\nSection CONSTRUCTORS.\n\nVariable ge: genv.\nVariable fn: function.\n\n(** Decomposition of an integer constant *)\n\nLemma decompose_int_rec_or:\n  forall N n p x, List.fold_left Int.or (decompose_int_rec N n p) x = Int.or x n.\nProof.\n  induction N; intros; simpl.\n  predSpec Int.eq Int.eq_spec n Int.zero; simpl.\n  subst n. rewrite Int.or_zero. auto.\n  auto.\n  predSpec Int.eq Int.eq_spec (Int.and n (Int.shl (Int.repr 3) p)) Int.zero.\n  auto.\n  simpl. rewrite IHN. rewrite Int.or_assoc. decEq. rewrite <- Int.and_or_distrib.\n  rewrite Int.or_not_self. apply Int.and_mone.\nQed.\n\nLemma decompose_int_rec_xor:\n  forall N n p x, List.fold_left Int.xor (decompose_int_rec N n p) x = Int.xor x n.\nProof.\n  induction N; intros; simpl.\n  predSpec Int.eq Int.eq_spec n Int.zero; simpl.\n  subst n. rewrite Int.xor_zero. auto.\n  auto.\n  predSpec Int.eq Int.eq_spec (Int.and n (Int.shl (Int.repr 3) p)) Int.zero.\n  auto.\n  simpl. rewrite IHN. rewrite Int.xor_assoc. decEq. rewrite <- Int.and_xor_distrib.\n  rewrite Int.xor_not_self. apply Int.and_mone.\nQed.\n\nLemma decompose_int_rec_add:\n  forall N n p x, List.fold_left Int.add (decompose_int_rec N n p) x = Int.add x n.\nProof.\n  induction N; intros; simpl.\n  predSpec Int.eq Int.eq_spec n Int.zero; simpl.\n  subst n. rewrite Int.add_zero. auto.\n  auto.\n  predSpec Int.eq Int.eq_spec (Int.and n (Int.shl (Int.repr 3) p)) Int.zero.\n  auto.\n  simpl. rewrite IHN. rewrite Int.add_assoc. decEq. rewrite Int.add_and.\n  rewrite Int.or_not_self. apply Int.and_mone. apply Int.and_not_self.\nQed.\n\nRemark decompose_int_rec_nil:\n  forall N n p, decompose_int_rec N n p = nil -> n = Int.zero.\nProof.\n  intros. generalize (decompose_int_rec_or N n p Int.zero). rewrite H. simpl.\n  rewrite Int.or_commut; rewrite Int.or_zero; auto.\nQed.\n\nLemma decompose_int_general:\n  forall (f: val -> int -> val) (g: int -> int -> int),\n  (forall v1 n2 n3, f (f v1 n2) n3 = f v1 (g n2 n3)) ->\n  (forall n1 n2 n3, g (g n1 n2) n3 = g n1 (g n2 n3)) ->\n  (forall n, g Int.zero n = n) ->\n  (forall N n p x, List.fold_left g (decompose_int_rec N n p) x = g x n) ->\n  forall n v,\n  List.fold_left f (decompose_int n) v = f v n.\nProof.\n  intros f g DISTR ASSOC ZERO DECOMP.\n  assert (A: forall l x y, g x (fold_left g l y) = fold_left g l (g x y)).\n    induction l; intros; simpl. auto. rewrite IHl. decEq. rewrite ASSOC; auto.\n  assert (B: forall l v n, fold_left f l (f v n) = f v (fold_left g l n)).\n    induction l; intros; simpl.\n    auto.\n    rewrite IHl. rewrite DISTR. decEq. decEq. auto.\n  intros. unfold decompose_int.\n  destruct (decompose_int_rec 12 n Int.zero) eqn:?.\n  simpl. exploit decompose_int_rec_nil; eauto. congruence.\n  simpl. rewrite B. decEq.\n  generalize (DECOMP 12%nat n Int.zero Int.zero).\n  rewrite Heql. simpl. repeat rewrite ZERO. auto.\nQed.\n\nLemma decompose_int_or:\n  forall n v,\n  List.fold_left (fun v i => Val.or v (Vint i)) (decompose_int n) v = Val.or v (Vint n).\nProof.\n  intros. apply decompose_int_general with (f := fun v n => Val.or v (Vint n)) (g := Int.or).\n  intros. rewrite Val.or_assoc. auto.\n  apply Int.or_assoc.\n  intros. rewrite Int.or_commut. apply Int.or_zero.\n  apply decompose_int_rec_or.\nQed.\n\nLemma decompose_int_bic:\n  forall n v,\n  List.fold_left (fun v i => Val.and v (Vint (Int.not i))) (decompose_int n) v = Val.and v (Vint (Int.not n)).\nProof.\n  intros. apply decompose_int_general with (f := fun v n => Val.and v (Vint (Int.not n))) (g := Int.or).\n  intros. rewrite Val.and_assoc. simpl. decEq. decEq. rewrite Int.not_or_and_not. auto.\n  apply Int.or_assoc.\n  intros. rewrite Int.or_commut. apply Int.or_zero.\n  apply decompose_int_rec_or.\nQed.\n\nLemma decompose_int_xor:\n  forall n v,\n  List.fold_left (fun v i => Val.xor v (Vint i)) (decompose_int n) v = Val.xor v (Vint n).\nProof.\n  intros. apply decompose_int_general with (f := fun v n => Val.xor v (Vint n)) (g := Int.xor).\n  intros. rewrite Val.xor_assoc. auto.\n  apply Int.xor_assoc.\n  intros. rewrite Int.xor_commut. apply Int.xor_zero.\n  apply decompose_int_rec_xor.\nQed.\n\nLemma decompose_int_add:\n  forall n v,\n  List.fold_left (fun v i => Val.add v (Vint i)) (decompose_int n) v = Val.add v (Vint n).\nProof.\n  intros. apply decompose_int_general with (f := fun v n => Val.add v (Vint n)) (g := Int.add).\n  intros. rewrite Val.add_assoc. auto.\n  apply Int.add_assoc.\n  intros. rewrite Int.add_commut. apply Int.add_zero.\n  apply decompose_int_rec_add.\nQed.\n\nLemma decompose_int_sub:\n  forall n v,\n  List.fold_left (fun v i => Val.sub v (Vint i)) (decompose_int n) v = Val.sub v (Vint n).\nProof.\n  intros. apply decompose_int_general with (f := fun v n => Val.sub v (Vint n)) (g := Int.add).\n  intros. repeat rewrite Val.sub_add_opp. rewrite Val.add_assoc. decEq. simpl. decEq.\n  rewrite Int.neg_add_distr; auto.\n  apply Int.add_assoc.\n  intros. rewrite Int.add_commut. apply Int.add_zero.\n  apply decompose_int_rec_add.\nQed.\n\nLemma iterate_op_correct:\n  forall op1 op2 (f: val -> int -> val) (rs: regset) (r: ireg) m v0 n k,\n  (forall (rs:regset) n,\n    exec_instr ge fn (op2 (SOimm n)) rs m =\n    Next (nextinstr (rs#r <- (f (rs#r) n))) m) ->\n  (forall n,\n    exec_instr ge fn (op1 (SOimm n)) rs m =\n    Next (nextinstr (rs#r <- (f v0 n))) m) ->\n  exists rs',\n     exec_straight ge fn (iterate_op op1 op2 (decompose_int n) k) rs m  k rs' m\n  /\\ rs'#r = List.fold_left f (decompose_int n) v0\n  /\\ forall r': preg, r' <> r -> r' <> PC -> rs'#r' = rs#r'.\nProof.\n  intros until k; intros SEM2 SEM1.\n  unfold iterate_op.\n  destruct (decompose_int n) as [ | i tl] eqn:?.\n  unfold decompose_int in Heql. destruct (decompose_int_rec 12%nat n Int.zero); congruence.\n  revert k. pattern tl. apply List.rev_ind.\n  (* base case *)\n  intros; simpl. econstructor.\n  split. apply exec_straight_one. rewrite SEM1. reflexivity. reflexivity.\n  intuition Simpl.\n  (* inductive case *)\n  intros.\n  rewrite List.map_app. simpl. rewrite app_ass. simpl.\n  destruct (H (op2 (SOimm x) :: k)) as [rs' [A [B C]]].\n  econstructor.\n  split. eapply exec_straight_trans. eexact A. apply exec_straight_one.\n  rewrite SEM2. reflexivity. reflexivity.\n  split. rewrite fold_left_app; simpl. Simpl. rewrite B. auto.\n  intros; Simpl.\nQed.\n\n(** Loading a constant. *)\n\nLemma loadimm_correct:\n  forall r n k rs m,\n  exists rs',\n     exec_straight ge fn (loadimm r n k) rs m  k rs' m\n  /\\ rs'#r = Vint n\n  /\\ forall r': preg, r' <> r -> r' <> PC -> rs'#r' = rs#r'.\nProof.\n  intros. unfold loadimm.\n  destruct (NPeano.leb (length (decompose_int n)) (length (decompose_int (Int.not n)))).\n  (* mov - orr* *)\n  replace (Vint n) with (List.fold_left (fun v i => Val.or v (Vint i)) (decompose_int n) Vzero).\n  apply iterate_op_correct.\n  auto.\n  intros; simpl. rewrite Int.or_commut; rewrite Int.or_zero; auto.\n  rewrite decompose_int_or. simpl. rewrite Int.or_commut; rewrite Int.or_zero; auto.\n  (* mvn - bic* *)\n  replace (Vint n) with (List.fold_left (fun v i => Val.and v (Vint (Int.not i))) (decompose_int (Int.not n)) (Vint Int.mone)).\n  apply iterate_op_correct.\n  auto.\n  intros. simpl. rewrite Int.and_commut; rewrite Int.and_mone; auto.\n  rewrite decompose_int_bic. simpl. rewrite Int.not_involutive. rewrite Int.and_commut. rewrite Int.and_mone; auto.\nQed.\n\n(** Add integer immediate. *)\n\nLemma addimm_correct:\n  forall r1 r2 n k rs m,\n  exists rs',\n     exec_straight ge fn (addimm r1 r2 n k) rs m  k rs' m\n  /\\ rs'#r1 = Val.add rs#r2 (Vint n)\n  /\\ forall r': preg, r' <> r1 -> r' <> PC -> rs'#r' = rs#r'.\nProof.\n  intros. unfold addimm.\n  destruct (NPeano.leb (length (decompose_int n)) (length (decompose_int (Int.neg n)))).\n  (* add - add* *)\n  replace (Val.add (rs r2) (Vint n))\n     with (List.fold_left (fun v i => Val.add v (Vint i)) (decompose_int n) (rs r2)).\n  apply iterate_op_correct.\n  auto.\n  auto.\n  apply decompose_int_add.\n  (* sub - sub* *)\n  replace (Val.add (rs r2) (Vint n))\n     with (List.fold_left (fun v i => Val.sub v (Vint i)) (decompose_int (Int.neg n)) (rs r2)).\n  apply iterate_op_correct.\n  auto.\n  auto.\n  rewrite decompose_int_sub. apply Val.sub_opp_add.\nQed.\n\n(* And integer immediate *)\n\nLemma andimm_correct:\n  forall r1 r2 n k rs m,\n  exists rs',\n     exec_straight ge fn (andimm r1 r2 n k) rs m  k rs' m\n  /\\ rs'#r1 = Val.and rs#r2 (Vint n)\n  /\\ forall r': preg, r' <> r1 -> r' <> PC -> rs'#r' = rs#r'.\nProof.\n  intros. unfold andimm.\n  (* andi *)\n  case (is_immed_arith n).\n  exists (nextinstr (rs#r1 <- (Val.and rs#r2 (Vint n)))).\n  split. apply exec_straight_one; auto.\n  split. rewrite nextinstr_inv; auto with asmgen. apply Pregmap.gss.\n  intros. rewrite nextinstr_inv; auto. apply Pregmap.gso; auto.\n  (* bic - bic* *)\n  replace (Val.and (rs r2) (Vint n))\n     with (List.fold_left (fun v i => Val.and v (Vint (Int.not i))) (decompose_int (Int.not n)) (rs r2)).\n  apply iterate_op_correct.\n  auto.\n  auto.\n  rewrite decompose_int_bic. rewrite Int.not_involutive. auto.\nQed.\n\n(** Reverse sub immediate *)\n\nLemma rsubimm_correct:\n  forall r1 r2 n k rs m,\n  exists rs',\n     exec_straight ge fn (rsubimm r1 r2 n k) rs m  k rs' m\n  /\\ rs'#r1 = Val.sub (Vint n) rs#r2\n  /\\ forall r': preg, r' <> r1 -> r' <> PC -> rs'#r' = rs#r'.\nProof.\n  intros. unfold rsubimm.\n  (* rsb - add* *)\n  replace (Val.sub (Vint n) (rs r2))\n     with (List.fold_left (fun v i => Val.add v (Vint i)) (decompose_int n) (Val.neg (rs r2))).\n  apply iterate_op_correct.\n  auto.\n  intros. simpl. destruct (rs r2); auto. simpl. rewrite Int.sub_add_opp.\n  rewrite Int.add_commut; auto.\n  rewrite decompose_int_add.\n  destruct (rs r2); simpl; auto. rewrite Int.sub_add_opp. rewrite Int.add_commut; auto.\nQed.\n\n(** Or immediate *)\n\nLemma orimm_correct:\n  forall r1 r2 n k rs m,\n  exists rs',\n     exec_straight ge fn (orimm r1 r2 n k) rs m  k rs' m\n  /\\ rs'#r1 = Val.or rs#r2 (Vint n)\n  /\\ forall r': preg, r' <> r1 -> r' <> PC -> rs'#r' = rs#r'.\nProof.\n  intros. unfold orimm.\n  (* ori - ori* *)\n  replace (Val.or (rs r2) (Vint n))\n     with (List.fold_left (fun v i => Val.or v (Vint i)) (decompose_int n) (rs r2)).\n  apply iterate_op_correct.\n  auto.\n  auto.\n  apply decompose_int_or.\nQed.\n\n(** Xor immediate *)\n\nLemma xorimm_correct:\n  forall r1 r2 n k rs m,\n  exists rs',\n     exec_straight ge fn (xorimm r1 r2 n k) rs m  k rs' m\n  /\\ rs'#r1 = Val.xor rs#r2 (Vint n)\n  /\\ forall r': preg, r' <> r1 -> r' <> PC -> rs'#r' = rs#r'.\nProof.\n  intros. unfold xorimm.\n  (* xori - xori* *)\n  replace (Val.xor (rs r2) (Vint n))\n     with (List.fold_left (fun v i => Val.xor v (Vint i)) (decompose_int n) (rs r2)).\n  apply iterate_op_correct.\n  auto.\n  auto.\n  apply decompose_int_xor.\nQed.\n\n(** Indexed memory loads. *)\n\nLemma indexed_memory_access_correct:\n  forall (P: regset -> Prop) (mk_instr: ireg -> int -> instruction)\n         (mk_immed: int -> int) (base: ireg) n k (rs: regset) m m',\n  (forall (r1: ireg) (rs1: regset) n1 k,\n    Val.add rs1#r1 (Vint n1) = Val.add rs#base (Vint n) ->\n    (forall (r: preg), r <> PC -> r <> IR14 -> rs1 r = rs r) ->\n    exists rs',\n    exec_straight ge fn (mk_instr r1 n1 :: k) rs1 m k rs' m' /\\ P rs') ->\n  exists rs',\n     exec_straight ge fn\n        (indexed_memory_access mk_instr mk_immed base n k) rs m\n        k rs' m'\n  /\\ P rs'.\nProof.\n  intros until m'; intros SEM.\n  unfold indexed_memory_access.\n  destruct (Int.eq n (mk_immed n)).\n- apply SEM; auto.\n- destruct (addimm_correct IR14 base (Int.sub n (mk_immed n)) (mk_instr IR14 (mk_immed n) :: k) rs m)\n  as (rs1 & A & B & C).\n  destruct (SEM IR14 rs1 (mk_immed n) k) as (rs2 & D & E).\n  rewrite B. rewrite Val.add_assoc. f_equal. simpl.\n  rewrite Int.sub_add_opp. rewrite Int.add_assoc.\n  rewrite (Int.add_commut (Int.neg (mk_immed n))).\n  rewrite Int.add_neg_zero. rewrite Int.add_zero. auto.\n  auto with asmgen.\n  exists rs2; split; auto. eapply exec_straight_trans; eauto.\nQed.\n\nLemma loadind_int_correct:\n  forall (base: ireg) ofs dst (rs: regset) m v k,\n  Mem.loadv Mint32 m (Val.add rs#base (Vint ofs)) = Some v ->\n  exists rs',\n     exec_straight ge fn (loadind_int base ofs dst k) rs m k rs' m\n  /\\ rs'#dst = v\n  /\\ forall r, r <> PC -> r <> IR14 -> r <> dst -> rs'#r = rs#r.\nProof.\n  intros; unfold loadind_int. apply indexed_memory_access_correct; intros.\n  econstructor; split.\n  apply exec_straight_one. simpl. unfold exec_load. rewrite H0; rewrite H; eauto. auto.\n  split. Simpl. intros; Simpl.\nQed.\n\n(*\nLemma loadind_float_correct:\n  forall (base: ireg) ofs dst (rs: regset) m v k,\n  Mem.loadv Mfloat64al32 m (Val.add rs#base (Vint ofs)) = Some v ->\n  exists rs',\n     exec_straight ge fn (loadind_float base ofs dst k) rs m k rs' m\n  /\\ rs'#dst = v\n  /\\ forall r, r <> PC -> r <> IR14 -> r <> dst -> rs'#r = rs#r.\nProof.\n  intros; unfold loadind_float. apply indexed_memory_access_correct; intros.\n  econstructor; split.\n  apply exec_straight_one. simpl. unfold exec_load. rewrite H0; rewrite H; eauto. auto.\n  split. Simpl. intros; Simpl.\nQed.\n*)\n\nLemma loadind_correct:\n  forall (base: ireg) ofs ty dst k c (rs: regset) 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 ge fn c rs m k rs' m\n  /\\ rs'#(preg_of dst) = v\n  /\\ forall r, r <> PC -> r <> IR14 -> r <> preg_of dst -> rs'#r = rs#r.\nProof.\n  unfold loadind; intros.\n  destruct ty; monadInv H.\n- (* int *)\n  erewrite ireg_of_eq by eauto. apply loadind_int_correct; auto.\n- (* float *)\n  erewrite freg_of_eq by eauto. simpl in H0.\n  apply indexed_memory_access_correct; intros.\n  econstructor; split.\n  apply exec_straight_one. simpl. unfold exec_load. rewrite H. rewrite H0. eauto. auto.\n  split. Simpl. intros; Simpl.\n- (* single *)\n  erewrite freg_of_eq by eauto. simpl in H0.\n  apply indexed_memory_access_correct; intros.\n  econstructor; split.\n  apply exec_straight_one. simpl. unfold exec_load. rewrite H. rewrite H0. eauto. auto.\n  split. Simpl. intros; Simpl.\nQed.\n\n(** Indexed memory stores. *)\n\n(*\nLemma storeind_int_correct:\n  forall (base: ireg) ofs (src: ireg) (rs: regset) m m' k,\n  Mem.storev Mint32 m (Val.add rs#base (Vint ofs)) (rs#src) = Some m' ->\n  src <> IR14 ->\n  exists rs',\n     exec_straight ge fn (storeind_int src base ofs k) rs m k rs' m'\n  /\\ forall r, r <> PC -> r <> IR14 -> rs'#r = rs#r.\nProof.\n  intros; unfold storeind_int. apply indexed_memory_access_correct; intros.\n  econstructor; split.\n  apply exec_straight_one. simpl. unfold exec_store.\n  rewrite H1. rewrite H2; auto with asmgen. rewrite H; eauto. auto.\n  intros; Simpl.\nQed.\n\nLemma storeind_float_correct:\n  forall (base: ireg) ofs (src: freg) (rs: regset) m m' k,\n  Mem.storev Mfloat64al32 m (Val.add rs#base (Vint ofs)) (rs#src) = Some m' ->\n  exists rs',\n     exec_straight ge fn (storeind_float src base ofs k) rs m k rs' m'\n  /\\ forall r, r <> PC -> r <> IR14 -> rs'#r = rs#r.\nProof.\n  intros; unfold storeind_float. apply indexed_memory_access_correct; intros.\n  econstructor; split.\n  apply exec_straight_one. simpl. unfold exec_store.\n  rewrite H0. rewrite H1; auto with asmgen. rewrite H; eauto. auto.\n  intros; Simpl.\nQed.\n*)\n\nLemma storeind_correct:\n  forall (base: ireg) ofs ty src k c (rs: regset) 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 ge fn c rs m k rs' m'\n  /\\ forall r, r <> PC -> r <> IR14 -> preg_notin r (destroyed_by_setstack ty) -> rs'#r = rs#r.\nProof.\n  unfold storeind; intros.\n  destruct ty; monadInv H; simpl in H0.\n- (* int *)\n  erewrite ireg_of_eq  in H0 by eauto.\n  apply indexed_memory_access_correct; intros.\n  econstructor; split.\n  apply exec_straight_one. simpl. unfold exec_store.\n  rewrite H. rewrite H1; auto with asmgen. rewrite H0; eauto.\n  assert (IR x <> IR IR14) by eauto with asmgen. congruence.\n  auto. intros; Simpl.\n- (* float *)\n  erewrite freg_of_eq  in H0 by eauto.\n  apply indexed_memory_access_correct; intros.\n  econstructor; split.\n  apply exec_straight_one. simpl. unfold exec_store.\n  rewrite H. rewrite H1; auto with asmgen. rewrite H0; eauto.\n  auto. intros; Simpl.\n- (* single *)\n  erewrite freg_of_eq  in H0 by eauto.\n  apply indexed_memory_access_correct; intros.\n  econstructor; split.\n  apply exec_straight_one. simpl. unfold exec_store.\n  rewrite H. rewrite H1; auto with asmgen. rewrite H0; eauto.\n  auto. intros; Simpl.\nQed.\n\n(** Translation of shift immediates *)\n\nLemma transl_shift_correct:\n  forall s (r: ireg) (rs: regset),\n  eval_shift_op (transl_shift s r) rs = eval_shift s (rs#r).\nProof.\n  intros. destruct s; simpl; auto.\nQed.\n\nLemma transl_shift_addr_correct:\n  forall s (r: ireg) (rs: regset),\n  eval_shift_addr (transl_shift_addr s r) rs = eval_shift s (rs#r).\nProof.\n  intros. destruct s; simpl; auto.\nQed.\n\n(** Translation of conditions *)\n\nLemma compare_int_spec:\n  forall rs v1 v2 m,\n  let rs1 := nextinstr (compare_int rs v1 v2 m) in\n     rs1#CReq = (Val.cmpu (Mem.valid_pointer m) Ceq v1 v2)\n  /\\ rs1#CRne = (Val.cmpu (Mem.valid_pointer m) Cne v1 v2)\n  /\\ rs1#CRhs = (Val.cmpu (Mem.valid_pointer m) Cge v1 v2)\n  /\\ rs1#CRlo = (Val.cmpu (Mem.valid_pointer m) Clt v1 v2)\n  /\\ rs1#CRhi = (Val.cmpu (Mem.valid_pointer m) Cgt v1 v2)\n  /\\ rs1#CRls = (Val.cmpu (Mem.valid_pointer m) Cle v1 v2)\n  /\\ rs1#CRge = (Val.cmp Cge v1 v2)\n  /\\ rs1#CRlt = (Val.cmp Clt v1 v2)\n  /\\ rs1#CRgt = (Val.cmp Cgt v1 v2)\n  /\\ rs1#CRle = (Val.cmp Cle v1 v2)\n  /\\ forall r', data_preg r' = true -> rs1#r' = rs#r'.\nProof.\n  intros. unfold rs1. intuition; try reflexivity.\n  unfold compare_int. Simpl.\nQed.\n\nLemma compare_float_spec:\n  forall rs v1 v2,\n  let rs' := nextinstr (compare_float rs v1 v2) in\n     rs'#CReq = (Val.cmpf Ceq v1 v2)\n  /\\ rs'#CRne = (Val.cmpf Cne v1 v2)\n  /\\ rs'#CRmi = (Val.cmpf Clt v1 v2)\n  /\\ rs'#CRpl = (Val.notbool (Val.cmpf Clt v1 v2))\n  /\\ rs'#CRhi = (Val.notbool (Val.cmpf Cle v1 v2))\n  /\\ rs'#CRls = (Val.cmpf Cle v1 v2)\n  /\\ rs'#CRge = (Val.cmpf Cge v1 v2)\n  /\\ rs'#CRlt = (Val.notbool (Val.cmpf Cge v1 v2))\n  /\\ rs'#CRgt = (Val.cmpf Cgt v1 v2)\n  /\\ rs'#CRle = (Val.notbool (Val.cmpf Cgt v1 v2))\n  /\\ forall r', data_preg r' = true -> rs'#r' = rs#r'.\nProof.\n  intros. unfold rs'. intuition; try reflexivity.\n  unfold compare_float. Simpl.\nQed.\n\nLtac ArgsInv :=\n  repeat (match goal with\n  | [ H: Error _ = OK _ |- _ ] => discriminate\n  | [ H: match ?args with nil => _ | _ :: _ => _ end = OK _ |- _ ] => destruct args\n  | [ H: bind _ _ = OK _ |- _ ] => monadInv H\n  | [ H: match _ with left _ => _ | right _ => assertion_failed end = OK _ |- _ ] => monadInv H\n  | [ H: match _ with true => _ | false => assertion_failed end = OK _ |- _ ] => monadInv H\n  end);\n  subst;\n  repeat (match goal with\n  | [ H: ireg_of ?x = OK ?y |- _ ] => simpl in *; rewrite (ireg_of_eq _ _ H) in *\n  | [ H: freg_of ?x = OK ?y |- _ ] => simpl in *; rewrite (freg_of_eq _ _ H) in *\n  end).\n\nLemma transl_cond_correct:\n  forall cond args k rs m c,\n  transl_cond cond args k = OK c ->\n  exists rs',\n     exec_straight ge fn c rs m k rs' m\n  /\\ match eval_condition cond (map rs (map preg_of args)) m with\n     | Some b => rs'#(CR (crbit_for_cond cond)) = Val.of_bool b\n     | None => True\n     end\n  /\\ forall r, data_preg r = true -> rs'#r = rs r.\nProof.\n  intros until c; intros TR.\n  assert (MATCH: forall v ob,\n           v = Val.of_optbool ob ->\n           match ob with Some b => v = Val.of_bool b | None => True end).\n    intros. subst v. destruct ob; auto.\n  assert (MATCH2: forall cmp v1 v2 v,\n           v = Val.cmpu (Mem.valid_pointer m) cmp v1 v2 ->\n           cmp = Ceq \\/ cmp = Cne ->\n           match Val.cmp_bool cmp v1 v2 with\n           | Some b => v = Val.of_bool b\n           | None => True\n           end).\n     intros. destruct v1; simpl; auto; destruct v2; simpl; auto.\n     unfold Val.cmpu, Val.cmpu_bool in H. subst v. destruct H0; subst cmp; auto.\n\n  unfold transl_cond in TR; destruct cond; ArgsInv.\n- (* Ccomp *)\n  generalize (compare_int_spec rs (rs x) (rs x0) m).\n  intros (C1 & C2 & C3 & C4 & C5 & C6 & C7 & C8 & C9 & C10 & C).\n  econstructor.\n  split. apply exec_straight_one. simpl. eauto. auto.\n  split. destruct c0; (apply MATCH; assumption) || (apply MATCH2; auto).\n  auto.\n- (* Ccompu *)\n  generalize (compare_int_spec rs (rs x) (rs x0) m).\n  intros (C1 & C2 & C3 & C4 & C5 & C6 & C7 & C8 & C9 & C10 & C).\n  econstructor.\n  split. apply exec_straight_one. simpl. eauto. auto.\n  split. destruct c0; (apply MATCH; assumption) || (apply MATCH2; auto).\n  auto.\n- (* Ccompshift *)\n  generalize (compare_int_spec rs (rs x) (eval_shift s (rs x0)) m).\n  intros (C1 & C2 & C3 & C4 & C5 & C6 & C7 & C8 & C9 & C10 & C).\n  econstructor.\n  split. apply exec_straight_one. simpl. eauto. auto.\n  rewrite transl_shift_correct.\n  split. destruct c0; (apply MATCH; assumption) || (apply MATCH2; auto).\n  auto.\n- (* Ccompushift *)\n  generalize (compare_int_spec rs (rs x) (eval_shift s (rs x0)) m).\n  intros (C1 & C2 & C3 & C4 & C5 & C6 & C7 & C8 & C9 & C10 & C).\n  econstructor.\n  split. apply exec_straight_one. simpl. eauto. auto.\n  rewrite transl_shift_correct.\n  split. destruct c0; (apply MATCH; assumption) || (apply MATCH2; auto).\n  auto.\n- (* Ccompimm *)\n  destruct (is_immed_arith i).\n  generalize (compare_int_spec rs (rs x) (Vint i) m).\n  intros (C1 & C2 & C3 & C4 & C5 & C6 & C7 & C8 & C9 & C10 & C).\n  econstructor.\n  split. apply exec_straight_one. simpl. eauto. auto.\n  split. destruct c0; (apply MATCH; assumption) || (apply MATCH2; auto).\n  auto.\n  exploit (loadimm_correct IR14). intros [rs' [P [Q R]]].\n  generalize (compare_int_spec rs' (rs x) (Vint i) m).\n  intros (C1 & C2 & C3 & C4 & C5 & C6 & C7 & C8 & C9 & C10 & C).\n  econstructor.\n  split. eapply exec_straight_trans. eexact P. apply exec_straight_one. simpl.\n  rewrite Q. rewrite R; eauto with asmgen. auto.\n  split. destruct c0; (apply MATCH; assumption) || (apply MATCH2; auto).\n  intros. rewrite C; auto with asmgen.\n- (* Ccompuimm *)\n  destruct (is_immed_arith i).\n  generalize (compare_int_spec rs (rs x) (Vint i) m).\n  intros (C1 & C2 & C3 & C4 & C5 & C6 & C7 & C8 & C9 & C10 & C).\n  econstructor.\n  split. apply exec_straight_one. simpl. eauto. auto.\n  split. destruct c0; (apply MATCH; assumption) || (apply MATCH2; auto).\n  auto.\n  exploit (loadimm_correct IR14). intros [rs' [P [Q R]]].\n  generalize (compare_int_spec rs' (rs x) (Vint i) m).\n  intros (C1 & C2 & C3 & C4 & C5 & C6 & C7 & C8 & C9 & C10 & C).\n  econstructor.\n  split. eapply exec_straight_trans. eexact P. apply exec_straight_one. simpl.\n  rewrite Q. rewrite R; eauto with asmgen. auto.\n  split. destruct c0; (apply MATCH; assumption) || (apply MATCH2; auto).\n  intros. rewrite C; auto with asmgen.\n- (* Ccompf *)\n  generalize (compare_float_spec rs (rs x) (rs x0)).\n  intros (C1 & C2 & C3 & C4 & C5 & C6 & C7 & C8 & C9 & C10 & C).\n  econstructor.\n  split. apply exec_straight_one. simpl. eauto. auto.\n  split. case c0; apply MATCH; assumption.\n  auto.\n- (* Cnotcompf *)\n  generalize (compare_float_spec rs (rs x) (rs x0)).\n  intros (C1 & C2 & C3 & C4 & C5 & C6 & C7 & C8 & C9 & C10 & C).\n  econstructor.\n  split. apply exec_straight_one. simpl. eauto. auto.\n  split. rewrite <- Val.negate_cmpf_ne in C2. rewrite <- Val.negate_cmpf_eq in C1.\n  destruct c0; apply MATCH; simpl; rewrite Val.notbool_negb_3; auto.\n  auto.\n- (* Ccompfzero *)\n  generalize (compare_float_spec rs (rs x) (Vfloat Float.zero)).\n  intros (C1 & C2 & C3 & C4 & C5 & C6 & C7 & C8 & C9 & C10 & C).\n  econstructor.\n  split. apply exec_straight_one. simpl. eauto. auto.\n  split. case c0; apply MATCH; assumption.\n  auto.\n- (* Cnotcompf *)\n  generalize (compare_float_spec rs (rs x) (Vfloat Float.zero)).\n  intros (C1 & C2 & C3 & C4 & C5 & C6 & C7 & C8 & C9 & C10 & C).\n  econstructor.\n  split. apply exec_straight_one. simpl. eauto. auto.\n  split. rewrite <- Val.negate_cmpf_ne in C2. rewrite <- Val.negate_cmpf_eq in C1.\n  destruct c0; apply MATCH; simpl; rewrite Val.notbool_negb_3; auto.\n  auto.\nQed.\n\n(** Translation of arithmetic operations. *)\n\nLtac TranslOpSimpl :=\n  econstructor; split;\n  [ apply exec_straight_one; [simpl; eauto | reflexivity ]\n  | split; [try rewrite transl_shift_correct; repeat Simpl | intros; repeat Simpl] ].\n\nLemma transl_op_correct_same:\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#IR13 op (map rs (map preg_of args)) m = Some v ->\n  match op with Ocmp _ => False | _ => True end ->\n  exists rs',\n     exec_straight ge fn c rs m k rs' m\n  /\\ rs'#(preg_of res) = v\n  /\\ forall r, data_preg r = true -> r <> preg_of res -> preg_notin r (destroyed_by_op op) -> rs'#r = rs#r.\nProof.\n  intros until v; intros TR EV NOCMP.\n  unfold transl_op in TR; destruct op; ArgsInv; simpl in EV; inv EV; try (TranslOpSimpl; fail).\n  (* Omove *)\n  exists (nextinstr (rs#(preg_of res) <- (rs#(preg_of m0)))).\n  split.\n  destruct (preg_of res) eqn:RES; try discriminate;\n  destruct (preg_of m0) eqn:ARG; inv TR.\n  apply exec_straight_one; auto.\n  apply exec_straight_one; auto.\n  intuition Simpl.\n  (* Ointconst *)\n  generalize (loadimm_correct x i k rs m). intros [rs' [A [B C]]].\n  exists rs'; auto with asmgen.\n  (* Oaddrstack *)\n  generalize (addimm_correct x IR13 i k rs m).\n  intros [rs' [EX [RES OTH]]].\n  exists rs'; auto with asmgen.\n  (* Oaddimm *)\n  generalize (addimm_correct x x0 i k rs m).\n  intros [rs' [A [B C]]].\n  exists rs'; auto with asmgen.\n  (* Orsbimm *)\n  generalize (rsubimm_correct x x0 i k rs m).\n  intros [rs' [A [B C]]].\n  exists rs'; auto with asmgen.\n  (* Omul *)\n  destruct (negb (ireg_eq x x0)).\n  TranslOpSimpl.\n  destruct (negb (ireg_eq x x1)).\n  rewrite Val.mul_commut. TranslOpSimpl.\n  econstructor; split.\n  eapply exec_straight_two. simpl; eauto. simpl; eauto. auto. auto.\n  intuition Simpl.\n  (* Omla *)\n  destruct (negb (ireg_eq x x0)).\n  TranslOpSimpl.\n  destruct (negb (ireg_eq x x1)).\n  rewrite Val.mul_commut. TranslOpSimpl.\n  econstructor; split.\n  eapply exec_straight_two. simpl; eauto. simpl; eauto. auto. auto.\n  intuition Simpl.\n  (* divs *)\n  econstructor. split. apply exec_straight_one. simpl. rewrite H0. reflexivity. auto.\n  intuition Simpl.\n  (* divu *)\n  econstructor. split. apply exec_straight_one. simpl. rewrite H0. reflexivity. auto.\n  intuition Simpl.\n  (* Oandimm *)\n  generalize (andimm_correct x x0 i k rs m).\n  intros [rs' [A [B C]]].\n  exists rs'; auto with asmgen.\n  (* Oorimm *)\n  generalize (orimm_correct x x0 i k rs m).\n  intros [rs' [A [B C]]].\n  exists rs'; auto with asmgen.\n  (* Oxorimm *)\n  generalize (xorimm_correct x x0 i k rs m).\n  intros [rs' [A [B C]]].\n  exists rs'; auto with asmgen.\n  (* Oshrximm *)\n  exploit Val.shrx_shr; eauto. intros [n [i' [ARG1 [ARG2 RES]]]].\n  injection ARG2; intro ARG2'; subst i'; clear ARG2.\n  set (islt := Int.lt n Int.zero) in *.\n  set (rs1 := nextinstr (compare_int rs (Vint n) (Vint Int.zero) m)).\n  assert (OTH1: forall r', data_preg r' = true -> rs1#r' = rs#r').\n    generalize (compare_int_spec rs (Vint n) (Vint Int.zero) m).\n    fold rs1. intros [A B]. intuition.\n  exploit (addimm_correct IR14 x0 (Int.sub (Int.shl Int.one i) Int.one)).\n  intros [rs2 [EXEC2 [RES2 OTH2]]].\n  set (rs3 := nextinstr (if islt then rs2 else rs2#IR14 <- (Vint n))).\n  set (rs4 := nextinstr (rs3#x <- (Val.shr rs3#IR14 (Vint i)))).\n  exists rs4; split.\n  apply exec_straight_step with rs1 m.\n  simpl. rewrite ARG1. auto. auto.\n  eapply exec_straight_trans. eexact EXEC2.\n  apply exec_straight_two with rs3 m.\n  simpl. rewrite OTH2; eauto with asmgen.\n    change (rs1 CRge) with (Val.cmp Cge (Vint n) (Vint Int.zero)).\n    unfold Val.cmp, Val.cmp_bool. change (Int.cmp Cge n Int.zero) with (negb islt).\n    rewrite OTH2; eauto with asmgen. rewrite OTH1. rewrite ARG1.\n    unfold rs3. case islt; reflexivity.\n    rewrite <- (ireg_of_eq _ _ EQ1). auto with asmgen.\n    auto.\n    unfold rs3. destruct islt; auto. auto.\n    split. unfold rs4; Simpl. unfold rs3. destruct islt.\n    Simpl. rewrite RES2. unfold rs1. Simpl.\n    Simpl. congruence.\n    intros. unfold rs4, rs3; Simpl. destruct islt; Simpl; rewrite OTH2; auto with asmgen.\n  (* intoffloat *)\n  econstructor; split. apply exec_straight_one; simpl. rewrite H0; simpl. eauto. auto.\nTransparent destroyed_by_op.\n  simpl. intuition Simpl.\n  (* intuoffloat *)\n  econstructor; split. apply exec_straight_one; simpl. rewrite H0; simpl. eauto. auto.\n  simpl. intuition Simpl.\n  (* floatofint *)\n  econstructor; split. apply exec_straight_one; simpl. rewrite H0; simpl. eauto. auto.\n  intuition Simpl.\n  (* floatofintu *)\n  econstructor; split. apply exec_straight_one; simpl. rewrite H0; simpl. eauto. auto.\n  intuition Simpl.\n  (* Ocmp *)\n  contradiction.\nQed.\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#IR13 op (map rs (map preg_of args)) m = Some v ->\n  exists rs',\n     exec_straight ge fn c rs m k rs' m\n  /\\ Val.lessdef v rs'#(preg_of res)\n  /\\ forall r, data_preg r = true -> r <> preg_of res -> preg_notin r (destroyed_by_op op) -> rs'#r = rs#r.\nProof.\n  intros.\n  assert (EITHER: match op with Ocmp _ => False | _ => True end \\/ exists cmp, op = Ocmp cmp).\n    destruct op; auto. right; exists c0; auto.\n  destruct EITHER as [A | [cmp A]].\n  exploit transl_op_correct_same; eauto. intros [rs' [P [Q R]]].\n  subst v. exists rs'; eauto.\n  (* Ocmp *)\n  subst op. simpl in H. monadInv H. simpl in H0. inv H0.\n  rewrite (ireg_of_eq _ _ EQ).\n  exploit transl_cond_correct; eauto. instantiate (1 := rs). instantiate (1 := m). intros [rs1 [A [B C]]].\n  set (rs2 := nextinstr (rs1#x <- (Vint Int.zero))).\n  set (rs3 := nextinstr (match rs2#(crbit_for_cond cmp) with\n             | Vint n => if Int.eq n Int.zero then rs2 else rs2#x <- Vone\n             | _      => rs2#x <- Vundef\n             end)).\n  exists rs3; split.\n  eapply exec_straight_trans. eexact A. apply exec_straight_two with rs2 m.\n  auto.\n  simpl. unfold rs3. destruct (rs2 (crbit_for_cond cmp)); auto. destruct (Int.eq i Int.zero); auto.\n  auto. unfold rs3.  destruct (rs2 (crbit_for_cond cmp)); auto. destruct (Int.eq i Int.zero); auto.\n  split. unfold rs3. Simpl.\n  replace (rs2 (crbit_for_cond cmp)) with (rs1 (crbit_for_cond cmp)).\n  destruct (eval_condition cmp rs##(preg_of##args) m) as [[]|]; simpl in *.\n  rewrite B. simpl. rewrite Int.eq_false. Simpl. apply Int.one_not_zero.\n  rewrite B. simpl. rewrite Int.eq_true. unfold rs2. Simpl.\n  auto.\n  destruct cmp; reflexivity.\n  intros. transitivity (rs2 r).\n  unfold rs3. destruct (rs2 (crbit_for_cond cmp)); Simpl. destruct (Int.eq i Int.zero); auto; Simpl.\n  unfold rs2. Simpl.\nQed.\n\n(** Translation of loads and stores. *)\n\nRemark val_add_add_zero:\n  forall v1 v2, Val.add v1 v2 = Val.add (Val.add v1 v2) (Vint Int.zero).\nProof.\n  intros. destruct v1; destruct v2; simpl; auto; rewrite Int.add_zero; auto.\nQed.\n\nLemma transl_memory_access_correct:\n  forall (P: regset -> Prop) (mk_instr_imm: ireg -> int -> instruction)\n         (mk_instr_gen: option (ireg -> shift_addr -> instruction))\n         (mk_immed: int -> int)\n         addr args k c (rs: regset) a m m',\n  transl_memory_access mk_instr_imm mk_instr_gen mk_immed addr args k = OK c ->\n  eval_addressing ge (rs#SP) addr (map rs (map preg_of args)) = Some a ->\n  (forall (r1: ireg) (rs1: regset) n k,\n    Val.add rs1#r1 (Vint n) = a ->\n    (forall (r: preg), r <> PC -> r <> IR14 -> rs1 r = rs r) ->\n    exists rs',\n    exec_straight ge fn (mk_instr_imm r1 n :: k) rs1 m k rs' m' /\\ P rs') ->\n  match mk_instr_gen with\n  | None => True\n  | Some mk =>\n      (forall (r1: ireg) (sa: shift_addr) k,\n      Val.add rs#r1 (eval_shift_addr sa rs) = a ->\n       exists rs',\n      exec_straight ge fn (mk r1 sa :: k) rs m k rs' m' /\\ P rs')\n  end ->\n  exists rs',\n    exec_straight ge fn c rs m k rs' m' /\\ P rs'.\nProof.\n  intros until m'; intros TR EA MK1 MK2.\n  unfold transl_memory_access in TR; destruct addr; ArgsInv; simpl in EA; inv EA.\n  (* Aindexed *)\n  apply indexed_memory_access_correct. exact MK1.\n  (* Aindexed2 *)\n  destruct mk_instr_gen as [mk | ]; monadInv TR. apply MK2.\n  simpl. erewrite ! ireg_of_eq; eauto.\n  (* Aindexed2shift *)\n  destruct mk_instr_gen as [mk | ]; monadInv TR. apply MK2.\n  erewrite ! ireg_of_eq; eauto. rewrite transl_shift_addr_correct. auto.\n  (* Ainstack *)\n  inv TR. apply indexed_memory_access_correct. exact MK1.\nQed.\n\nLemma transl_load_int_correct:\n  forall mk_instr is_immed dst addr args k c (rs: regset) a chunk m v,\n  transl_memory_access_int mk_instr is_immed dst addr args k = OK c ->\n  eval_addressing ge (rs#SP) addr (map rs (map preg_of args)) = Some a ->\n  Mem.loadv chunk m a = Some v ->\n  (forall (r1 r2: ireg) (sa: shift_addr) (rs1: regset),\n    exec_instr ge fn (mk_instr r1 r2 sa) rs1 m =\n    exec_load chunk (Val.add rs1#r2 (eval_shift_addr sa rs1)) r1 rs1 m) ->\n  exists rs',\n      exec_straight ge fn c rs m k rs' m\n   /\\ rs'#(preg_of dst) = v\n   /\\ forall r, data_preg r = true -> r <> preg_of dst -> rs'#r = rs#r.\nProof.\n  intros. monadInv H. erewrite ireg_of_eq by eauto.\n  eapply transl_memory_access_correct; eauto.\n  intros; simpl. econstructor; split. apply exec_straight_one.\n  rewrite H2. unfold exec_load. simpl eval_shift_addr. rewrite H. rewrite H1. eauto. auto.\n  split. Simpl. intros; Simpl.\n  simpl; intros.\n  econstructor; split. apply exec_straight_one.\n  rewrite H2. unfold exec_load. rewrite H. rewrite H1. eauto. auto.\n  split. Simpl. intros; Simpl.\nQed.\n\nLemma transl_load_float_correct:\n  forall mk_instr is_immed dst addr args k c (rs: regset) a chunk m v,\n  transl_memory_access_float mk_instr is_immed dst addr args k = OK c ->\n  eval_addressing ge (rs#SP) addr (map rs (map preg_of args)) = Some a ->\n  Mem.loadv chunk m a = Some v ->\n  (forall (r1: freg) (r2: ireg) (n: int) (rs1: regset),\n    exec_instr ge fn (mk_instr r1 r2 n) rs1 m =\n    exec_load chunk (Val.add rs1#r2 (Vint n)) r1 rs1 m) ->\n  exists rs',\n      exec_straight ge fn c rs m k rs' m\n   /\\ rs'#(preg_of dst) = v\n   /\\ forall r, data_preg r = true -> r <> preg_of dst -> rs'#r = rs#r.\nProof.\n  intros. monadInv H. erewrite freg_of_eq by eauto.\n  eapply transl_memory_access_correct; eauto.\n  intros; simpl. econstructor; split. apply exec_straight_one.\n  rewrite H2. unfold exec_load. rewrite H. rewrite H1. eauto. auto.\n  split. Simpl. intros; Simpl.\n  simpl; auto.\nQed.\n\nLemma transl_store_int_correct:\n  forall mr mk_instr is_immed src addr args k c (rs: regset) a chunk m m',\n  transl_memory_access_int mk_instr is_immed src addr args k = OK c ->\n  eval_addressing ge (rs#SP) addr (map rs (map preg_of args)) = Some a ->\n  Mem.storev chunk m a rs#(preg_of src) = Some m' ->\n  (forall (r1 r2: ireg) (sa: shift_addr) (rs1: regset),\n    exec_instr ge fn (mk_instr r1 r2 sa) rs1 m =\n    exec_store chunk (Val.add rs1#r2 (eval_shift_addr sa rs1)) r1 rs1 m) ->\n  exists rs',\n      exec_straight ge fn c rs m k rs' m'\n   /\\ forall r, data_preg r = true -> preg_notin r mr -> rs'#r = rs#r.\nProof.\n  intros. monadInv H. erewrite ireg_of_eq in * by eauto.\n  eapply transl_memory_access_correct; eauto.\n  intros; simpl. econstructor; split. apply exec_straight_one.\n  rewrite H2. unfold exec_store. simpl eval_shift_addr. rewrite H. rewrite H3; eauto with asmgen.\n  rewrite H1. eauto. auto.\n  intros; Simpl.\n  simpl; intros.\n  econstructor; split. apply exec_straight_one.\n  rewrite H2. unfold exec_store. rewrite H. rewrite H1. eauto. auto.\n  intros; Simpl.\nQed.\n\nLemma transl_store_float_correct:\n  forall mr mk_instr is_immed src addr args k c (rs: regset) a chunk m m',\n  transl_memory_access_float mk_instr is_immed src addr args k = OK c ->\n  eval_addressing ge (rs#SP) addr (map rs (map preg_of args)) = Some a ->\n  Mem.storev chunk m a rs#(preg_of src) = Some m' ->\n  (forall (r1: freg) (r2: ireg) (n: int) (rs1: regset),\n    exec_instr ge fn (mk_instr r1 r2 n) rs1 m =\n    exec_store chunk (Val.add rs1#r2 (Vint n)) r1 rs1 m) ->\n  exists rs',\n      exec_straight ge fn c rs m k rs' m'\n   /\\ forall r, data_preg r = true -> preg_notin r mr -> rs'#r = rs#r.\nProof.\n  intros. monadInv H. erewrite freg_of_eq in * by eauto.\n  eapply transl_memory_access_correct; eauto.\n  intros; simpl. econstructor; split. apply exec_straight_one.\n  rewrite H2. unfold exec_store. rewrite H. rewrite H3; auto with asmgen. rewrite H1. eauto. auto.\n  intros; Simpl.\n  simpl; auto.\nQed.\n\nLemma transl_load_correct:\n  forall chunk addr args dst k c (rs: regset) a m v,\n  transl_load chunk addr args dst k = OK c ->\n  eval_addressing ge (rs#SP) addr (map rs (map preg_of args)) = Some a ->\n  Mem.loadv chunk m a = Some v ->\n  exists rs',\n      exec_straight ge fn c rs m k rs' m\n   /\\ rs'#(preg_of dst) = v\n   /\\ forall r, data_preg r = true -> r <> preg_of dst -> rs'#r = rs#r.\nProof.\n  intros. destruct chunk; simpl in H.\n  eapply transl_load_int_correct; eauto.\n  eapply transl_load_int_correct; eauto.\n  eapply transl_load_int_correct; eauto.\n  eapply transl_load_int_correct; eauto.\n  eapply transl_load_int_correct; eauto.\n  discriminate.\n  eapply transl_load_float_correct; eauto.\n  apply Mem.loadv_float64al32 in H1. eapply transl_load_float_correct; eauto.\n  eapply transl_load_float_correct; eauto.\nQed.\n\nLemma transl_store_correct:\n  forall chunk addr args src k c (rs: regset) a m m',\n  transl_store chunk addr args src k = OK c ->\n  eval_addressing ge (rs#SP) 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 ge fn c rs m k rs' m'\n   /\\ forall r, data_preg r = true -> preg_notin r (destroyed_by_store chunk addr) -> rs'#r = rs#r.\nProof.\n  intros. destruct chunk; simpl in H.\n- assert (Mem.storev Mint8unsigned m a (rs (preg_of src)) = Some m').\n    rewrite <- H1. destruct a; simpl; auto. symmetry. apply Mem.store_signed_unsigned_8.\n  clear H1. eapply transl_store_int_correct; eauto.\n- eapply transl_store_int_correct; eauto.\n- assert (Mem.storev Mint16unsigned m a (rs (preg_of src)) = Some m').\n    rewrite <- H1. destruct a; simpl; auto. symmetry. apply Mem.store_signed_unsigned_16.\n  clear H1. eapply transl_store_int_correct; eauto.\n- eapply transl_store_int_correct; eauto.\n- eapply transl_store_int_correct; eauto.\n- discriminate.\n- unfold transl_memory_access_float in H. monadInv H. rewrite (freg_of_eq _ _ EQ) in *.\n  eapply transl_memory_access_correct; eauto.\n  intros. econstructor; split. apply exec_straight_one.\n  simpl. unfold exec_store. rewrite H. rewrite H2; eauto with asmgen.\n  rewrite H1. eauto. auto. intros. Simpl.\n  simpl; auto.\n- apply Mem.storev_float64al32 in H1. eapply transl_store_float_correct; eauto.\n- eapply transl_store_float_correct; eauto.\nQed.\n\nEnd CONSTRUCTORS.\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/arm/Asmgenproof1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.28710070039325086}}
{"text": "(** * Terminal Object **)\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nGeneralizable All Variables.\n\nSet Primitive Projections.\nSet Universe Polymorphism.\n\nRequire Import COC.Base.Main.\nFrom COC.Cons Require Import Initial Terminal Product Coproduct Equalizer Coequalizer.\n\n(** Initial and Terminal **)\nProgram Definition terminal_from_initial (C: Category)(i: Initial C): Terminal C^op :=\n  [Terminal by (initial_univ i)].\nNext Obligation.\n  now apply initial_uniqueness.\nQed.\n\nProgram Definition initial_from_terminal (C: Category)(t: Terminal C): Initial C^op :=\n  [Initial by (terminal_univ t)].\nNext Obligation.\n  now apply terminal_uniqueness.\nQed.\n\n(** Product and Coproduct **)\nProgram Definition coproduct_from_product (C: Category)(X Y: C)(P: Product C X Y)\n  : Coproduct C^op X Y :=\n  [Coproduct by (fun (Z: C) f g => [f , g to P])\n   with pi1_{P}, pi2_{P}].\nNext Obligation.\n  - now apply product_universality_1.\n  - now apply product_universality_2.\n  - now apply product_uniqueness.\nQed.\n\nProgram Definition product_from_coproduct (C: Category)(X Y: C)(CP: Coproduct C X Y)\n  : Product C^op X Y :=\n  [Product by (fun (Z: C) f g => [f , g from CP])\n   with in1_{CP}, in2_{CP}].\nNext Obligation.\n  - now apply coproduct_universality_1.\n  - now apply coproduct_universality_2.\n  - now apply coproduct_uniqueness.\nQed.\n\n(** Equalizer and Coequalizer **)\nProgram Definition coequalizer_from_equalizer (C: Category)(X Y: C)(f g: C X Y)(eq: Equalizer f g)\n  : Coequalizer (C:=C^op) f g :=\n  [Coequalizer by fun (Z: C)(h: C Z X)(Heq: f \\o h == g \\o h) =>\n                    equalizer_univ eq Heq\n   with equalizer_map eq].\nNext Obligation.\n  - now apply equalize.\n  - now apply equalizer_universality.\n  - now apply equalizer_uniqueness.\nQed.\n\nProgram Definition equalizer_from_coequalizer (C: Category)(X Y: C)(f g: C X Y)(coeq: Coequalizer f g)\n  : Equalizer (C:=C^op) f g :=\n  [Equalizer by fun (Z: C)(k: C Y Z)(Heq: k \\o f == k \\o g) =>\n                    coequalizer_univ coeq Heq\n   with coequalizer_map coeq].\nNext Obligation.\n  - now apply coequalize.\n  - now apply coequalizer_universality.\n  - now apply coequalizer_uniqueness.\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/Cons/Duality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2870758976339061}}
{"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 Coq.Lists.List.\nRequire Import RamifyCoq.msl_ext.ramification_lemmas.\nRequire Import RamifyCoq.graph.graph_model.\nRequire Import RamifyCoq.graph.path_lemmas.\nRequire Import RamifyCoq.graph.graph_gen.\nRequire Import RamifyCoq.graph.graph_relation.\nRequire Import RamifyCoq.graph.subgraph2.\nRequire Import RamifyCoq.graph.reachable_ind.\nRequire Import RamifyCoq.graph.spanning_tree.\nRequire Import RamifyCoq.graph.BiGraph.\nRequire Import RamifyCoq.graph.MathGraph.\nRequire Import RamifyCoq.graph.FiniteGraph.\nRequire Import RamifyCoq.msl_application.Graph.\nRequire Import RamifyCoq.msl_application.GraphBi.\nRequire Import RamifyCoq.msl_application.GraphBi_Mark.\nRequire RamifyCoq.graph.weak_mark_lemmas.\nImport RamifyCoq.graph.weak_mark_lemmas.WeakMarkGraph.\n\n(* TODO: Put some pure lemmas into some file like: graph/bi_spanning. *)\n\nInstance 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_BI.\n\n  Context {pSGG_Bi: pPointwiseGraph_Graph_Bi}.\n  Context {sSGG_Bi: sPointwiseGraph_Graph_Bi bool unit}.\n\n  Existing Instances maGraph biGraph 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_Bi 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 (biGraph 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 (biGraph 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 (biGraph 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 (biGraph 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 (biGraph 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 (biGraph g1)); auto.\n        + apply (@left_sound _ _ _ _ _ _ g1 (biGraph 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 (biGraph 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 (biGraph g1)) in H; auto.\n      - apply (@right_valid _ _ _ _ _ _ g2 (biGraph 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 (biGraph g1) x); auto.\n      - rewrite (@right_sound _ _ _ _ _ _ g1 (biGraph g1) x); auto.\n      - apply (@right_valid _ _ _ _ _ _ g2 (biGraph g2) x); auto.\n      - rewrite (@right_sound _ _ _ _ _ _ g2 (biGraph 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 (biGraph g1)); auto.\n        * apply (@left_sound _ _ _ _ _ _ g1 (biGraph 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 (biGraph 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 (biGraph 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 (biGraph 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 (biGraph 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 (biGraph 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 (biGraph g)); auto.\n        * split; [|intuition]. apply (@right_valid _ _ _ _ _ _ g (biGraph 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_BI.\n", "meta": {"author": "johndoe20190406", "repo": "RamifyCoq", "sha": "72fb538b40ee8ea641e4bf5fe6cd232756d0929c", "save_path": "github-repos/coq/johndoe20190406-RamifyCoq", "path": "github-repos/coq/johndoe20190406-RamifyCoq/RamifyCoq-72fb538b40ee8ea641e4bf5fe6cd232756d0929c/data_structure/spatial_graph_dispose_bi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.28702131824021837}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\nRequire Import Coq.Classes.RelationClasses Lia Program.\nFrom Fairness Require Export\n     ITreeLib WFLib FairBeh Mod pind Axioms\n     Linking SCM Red IRed.\nFrom PromisingSEQ Require Import View.\nFrom Ordinal Require Export ClassicalHessenberg.\nFrom Fairness Require Import NatStructsLow.\n\n\nSet Implicit Arguments.\n\nModule AbsLock.\n\n  Definition lock_fun\n    : ktree (programE thread_id (bool * NatMap.t unit)%type) unit unit :=\n    fun _ =>\n      _ <- trigger Yield;;\n      tid <- trigger (GetTid);;\n      '(own, ts) <- trigger (Get id);;\n      let ts := NatMap.add tid tt ts in\n      _ <- trigger (Put (own, ts));;\n      _ <- (ITree.iter\n             (fun (_: unit) =>\n                _ <- trigger Yield;;\n                '(own, ts) <- trigger (Get id);;\n                if (Bool.eqb own true)\n                then Ret (inl tt)\n                else Ret (inr tt)) tt);;\n      '(_, ts) <- trigger (Get id);;\n      let ts := NatMap.remove tid ts in\n      _ <- trigger (Put (true, ts));;\n      _ <- trigger (Fair (fun i => if tid_dec i tid then Flag.success\n                               else if (NatMapP.F.In_dec ts i) then Flag.fail\n                                    else Flag.emp));;\n      _ <- trigger Yield;;\n      Ret tt.\n\n  Definition unlock_fun\n    : ktree (programE thread_id (bool * NatMap.t unit)%type) unit unit :=\n    fun _ =>\n      _ <- trigger Yield;;\n      '(own, ts) <- trigger (Get id);;\n      if (Bool.eqb own true)\n      then _ <- trigger (Put (false, ts));; _ <- trigger Yield;; Ret tt\n      else UB.\n\n  Definition mod: Mod.t :=\n    Mod.mk\n      (false, NatMap.empty unit)\n      (Mod.get_funs [(\"lock\", Mod.wrap_fun lock_fun);\n                     (\"unlock\", Mod.wrap_fun unlock_fun)]).\n\nEnd AbsLock.\n\nModule AbsLockW.\n\n  Definition st := (((bool * View.t) * bool) * NatMap.t unit)%type.\n\n  Definition lock_fun\n    : ktree (programE thread_id st) View.t View.t :=\n    fun tvw =>\n      _ <- trigger Yield;;\n      tid <- trigger (GetTid);;\n      '(own_lvw, ts) <- trigger (Get id);;\n      let ts := NatMap.add tid tt ts in\n      _ <- trigger (Put (own_lvw, ts));;\n      _ <- (ITree.iter\n             (fun (_: unit) =>\n                _ <- trigger Yield;;\n                '(((own, _), _), _) <- trigger (Get id);;\n                match own with\n                | true => Ret (inl tt)\n                | false => Ret (inr tt)\n                end)\n             tt);;\n      '(((_, tvw_lock), ing), ts) <- trigger (Get id);;\n      if (ing: bool)\n      (* then UB *)\n      then trigger (Choose (void)) >>= (Empty_set_rect _)\n      else\n        let ts := NatMap.remove tid ts in\n        '(exist _ tvw' _) <- trigger (Choose (sig (fun tvw' => View.le (View.join tvw tvw_lock) tvw')));;\n        (* to prove weak mem ticket lock, needs to store tvw_lock, not tvw';\n           this is related to now_serving's points_to's V and Q, which is not updated at lock\n         *)\n        _ <- trigger (Put (((true, tvw_lock), false), ts));;\n        _ <- trigger (Fair (fun i => if tid_dec i tid then Flag.success\n                                 else if (NatMapP.F.In_dec ts i) then Flag.fail\n                                      else Flag.emp));;\n        _ <- trigger Yield;;\n        Ret tvw'.\n\n  Definition unlock_fun\n    : ktree (programE thread_id st) View.t View.t :=\n    fun tvw =>\n      _ <- trigger Yield;;\n      '(((own, lvw), ing), ts) <- trigger (Get id);;\n      if (excluded_middle_informative (View.le lvw tvw))\n      then\n        match own, ing with\n        | true, false =>\n            _ <- trigger (Put (((own, lvw), true), ts));;\n            _ <- trigger Yield;;\n            '(((_, _), _), ts) <- trigger (Get id);;\n            (* tvw_V <- trigger (Choose (View.t));; *)\n            '(exist _ tvw_V _) <- trigger (Choose (sig (fun tvw' => View.le tvw tvw')));;\n            _ <- trigger (Put (((false, tvw_V), false), ts));;\n            (* '(exist _ tvw' _) <- trigger (Choose (sig (fun tvw' => View.le (View.join tvw tvw_V) tvw')));; *)\n            '(exist _ tvw' _) <- trigger (Choose (sig (fun tvw' => View.le tvw_V tvw')));;\n            _ <- trigger Yield;;\n            Ret tvw'\n        | _, _ => UB\n        end\n      else UB.\n\n  Definition mod: Mod.t :=\n    Mod.mk\n      (((false, View.bot), false), NatMap.empty unit)\n      (Mod.get_funs [(\"lock\", Mod.wrap_fun lock_fun);\n                     (\"unlock\", Mod.wrap_fun unlock_fun)]).\n\nEnd AbsLockW.\n\n\n(* Module FairLock. *)\n(*   Definition lock_fun: WMod.function bool unit void := *)\n(*     WMod.mk_fun *)\n(*       tt *)\n(*       (fun (_: unit) st next => *)\n(*          match st with *)\n(*          | true => next = WMod.disabled *)\n(*          | false => next = WMod.normal true tt (sum_fmap_l (fun _ => Flag.fail)) *)\n(*          end). *)\n\n(*   Definition unlock_fun: WMod.function bool unit void := *)\n(*     WMod.mk_fun *)\n(*       tt *)\n(*       (fun (_: unit) st next => *)\n(*          match st with *)\n(*          | false => next = WMod.stuck *)\n(*          | true => next = WMod.normal false tt (sum_fmap_l (fun _ => Flag.emp)) *)\n(*          end). *)\n\n(*   Definition wmod: WMod.t := *)\n(*     WMod.mk *)\n(*       false *)\n(*       [(\"lock\", lock_fun); *)\n(*        (\"unlock\", unlock_fun) *)\n(*       ]. *)\n\n(*   Definition mod: Mod.t := *)\n(*     WMod.interp_mod wmod. *)\n(* End FairLock. *)\n\n(* From Fairness Require Export WMM. *)\n\n(* Module FairLockW. *)\n(*   Definition lock_fun: WMod.function (option View.t) unit void := *)\n(*     WMod.mk_fun *)\n(*       tt *)\n(*       (fun (tvw: View.t) st next => *)\n(*          match st with *)\n(*          | None => next = WMod.disabled *)\n(*          | Some tvw_lock => *)\n(*              next = WMod.normal None (View.join tvw tvw_lock) (sum_fmap_l (fun _ => Flag.fail)) *)\n(*          end). *)\n\n(*   Definition unlock_fun: WMod.function (option View.t) unit void := *)\n(*     WMod.mk_fun *)\n(*       tt *)\n(*       (fun (tvw: View.t) st next => *)\n(*          match st with *)\n(*          | Some _ => next = WMod.stuck *)\n(*          | None => next = WMod.normal (Some tvw) tvw (sum_fmap_l (fun _ => Flag.emp)) *)\n(*          end). *)\n\n(*   Definition wmod: WMod.t := *)\n(*     WMod.mk *)\n(*       (Some View.bot) *)\n(*       [(\"lock\", lock_fun); *)\n(*        (\"unlock\", unlock_fun) *)\n(*       ]. *)\n\n(*   Definition mod: Mod.t := *)\n(*     WMod.interp_mod wmod. *)\n(* End FairLockW. *)\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/FairLock.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2870213121536915}}
{"text": "Require Import Io.All.\nRequire Model.\nRequire Import Semantics.\n\nModule C.\n  Module DeadLockFree.\n    Inductive t {E S A} (m : Model.t E S) (s : S) (x : C.t E A) : Prop :=\n    | New :\n      (exists p, exists v, C.Last.Eval.t p x v) \\/\n        (exists c, exists x', exists s', C.Step.t m c s x x' s') ->\n      (forall c x' s', C.Step.t m c s x x' s' -> t m s' x') ->\n      t m s x.\n  End DeadLockFree.\nEnd C.\n\nModule Choose.\n  Module DeadLockFree.\n    Inductive t {E S A} (m : Model.t E S) (s : S) (x : Choose.t E A) : Prop :=\n    | New :\n      (exists p, exists v, Choose.Last.Eval.t p x v) \\/\n        (exists c, exists x', exists s', Choose.Step.t m c s x x' s') ->\n      (forall c x' s', Choose.Step.t m c s x x' s' -> t m s' x') ->\n      t m s x.\n  End DeadLockFree.\nEnd Choose.\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/DeadLockFree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2869642025811833}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Bool.Bool.\nRequire Import NetCore.NetCoreEval.\nRequire Import Common.Types.\nRequire Import Classifier.Classifier.\nRequire Import Word.WordInterface.\nRequire Import Pattern.Pattern.\n(* TODO: MJR Move 'switchId' from messagesDef so that we don't have to include this whole thing *)\nRequire Import OpenFlow.OpenFlow0x01Types.\nRequire Import NetCore.NetCoreTypes.\nRequire Import Network.NetworkPacket.\n\nSet Implicit Arguments.\n\nImport ListNotations.\n\nFixpoint desugar_pred (p : predicate) := match p with\n  | DlSrc eth => PrHdr (Pattern.dlSrc eth)\n  | DlDst eth => PrHdr (Pattern.dlDst eth)\n  (* | DlTyp typ => PrHdr (Pattern.dlType typ) *)\n  (* | DlVlan (Some vlan) => PrHdr (Pattern.dlVlan vlan) *)\n  (* | DlVlan None => PrHdr (Pattern.dlVlan VLAN_NONE) *)\n  (* | NwProto proto => PrHdr (Pattern.nwProto proto) *)\n  | Switch sw => PrOnSwitch sw\n  | InPort pt => PrHdr (Pattern.inPort pt)\n  | And p1 p2 =>\n      (* de Morgan's law *)\n      PrNot (PrOr (PrNot (desugar_pred p1)) (PrNot (desugar_pred p2)))\n  | Or p1 p2 => PrOr (desugar_pred p1) (desugar_pred p2)\n  | Not p => PrNot (desugar_pred p)\n  | All => PrAll\n  | NoPackets => PrNone\nend.\n\nDefinition desugar_action (a : action) := \n  match a with\n    | To p => Forward unmodified (PhysicalPort  p)\n    | ToAll => Forward unmodified AllPorts\n    | GetPacket f => ActGetPkt (MkId 0)\n  end.\n\nFixpoint desugar_actions acts :=\n  match acts with\n    | [] => []\n    | a :: acts => (desugar_action a) :: desugar_actions acts\nend.\n\nFixpoint desugar_pol' p pr := \n  match p with\n    | Policy pred act => PoAtom (desugar_pred (And pred pr)) (desugar_actions act)\n    | Par p1 p2 => PoUnion (desugar_pol' p1 pr) (desugar_pol' p2 pr)\n    (* | Restrict p pr' => desugar_pol' p (And pr' pr) *)\n  end.\n\nDefinition desugar_pol (p : policy) := desugar_pol' p All.\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/NetCore/old/NetCoreDesugar.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091673, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2869642025811833}}
{"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import TableDataOpsIntro.Spec.\nRequire Import TableDataOpsRef2.Spec.\n\nLocal Open Scope Z_scope.\n\nSection SpecLow.\n\n  Definition table_destroy3_spec0 (g_rd: Pointer) (map_addr: Z64) (rtt_addr: Z64) (level: Z64) (adt: RData) : option (RData * Z64) :=\n    match g_rd, map_addr, rtt_addr, level with\n    | (_g_rd_base, _g_rd_ofst), VZ64 _map_addr, VZ64 _rtt_addr, VZ64 _level =>\n      rely is_int64 _map_addr;\n      rely is_int64 _rtt_addr;\n      rely is_int64 _level;\n      when' _t'1, adt == table_destroy2_spec (_g_rd_base, _g_rd_ofst) (VZ64 _map_addr) (VZ64 _rtt_addr) (VZ64 _level) 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/TableDataOpsRef3/LowSpecs/table_destroy3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.28696419612357715}}
{"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 Implicit Arguments.\nUnset Strict Implicit.\nRequire Export Ring_cat.\n(** Title \"The category of integral domains.\" *)\nSection Objects.\n\nDefinition idomain_prop (R : CRING) :=\n  forall x y : R,\n  ~ Equal x (monoid_unit R) ->\n  ~ Equal y (monoid_unit R) -> ~ Equal (ring_mult x y) (monoid_unit R).\n\nRecord idomain_on (R : cring) : Type :=  {idomain_prf : idomain_prop R}.\n\nRecord idomain : Type := \n  {idomain_ring :> cring; idomain_on_def :> idomain_on idomain_ring}.\nCoercion Build_idomain : idomain_on >-> idomain.\n\nDefinition INTEGRAL_DOMAIN :=\n  full_subcat (C:=CRING) (C':=idomain) idomain_ring.\nEnd Objects.", "meta": {"author": "coq-contribs", "repo": "algebra", "sha": "4006abe46420df0394e20f0fb19279f64bb8501e", "save_path": "github-repos/coq/coq-contribs-algebra", "path": "github-repos/coq/coq-contribs-algebra/algebra-4006abe46420df0394e20f0fb19279f64bb8501e/Integral_domain_cat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2869641896659709}}
{"text": "(* This is a self-contained Coq 8.6 proof for KafKa.\n\n   Theorem 1 (page 14) in the paper corresponds to theorem \n      soundness: forall k e s t,\n           WellFormedState k e s -> HasType nil s k e t -> is_sound k s e t.\n   HasType nil s k e t corresponds to nil s k |- e : t\n   WellFormedState combines well-typedness of the class table and the running expression with heap typing.\n\nThe proof shows progress and preservation for Kafka. The primary lemma of\ninterest are the well-typedness theorems for behavioural cast generation,\ncorrectness_CWrap and subtype_CWrap. The former shows that the wrappers\nare well-typed, while the latter shows that they are subtypes of the type\nthat they claim to implement.\n\nThere are three holes in the proof:\n* Transitivity of structural recursive subtyping (subtype_transitive)\n* Soundness of subtyping (subtype_method_containment)\n* That subtyping still holds when the class table is expanded (ct_exten_subtyp)\n\nThe first two components are well-known prior work (e.g. Jones 2016).\nThe third property simply requires that pre-existing subtyping\njudgments still hold when the class table is expanded. Since subtyping\ncan only be concluded for pre-existing classes, it follows easily, but\nits proof requires the correspondance of inductive algorithmic subtyping\nand coinductive subtyping which we do not model here.\n\nA command to check the axiomatic dependencies of our soundness proof is \nincluded at the end of this file. It depends on one additional axiom,\nJMeq_eq : forall (A : Type) (x y : A), x ~= y -> x = y, provided by\nthe standard library and uses John Major equality to imply standard \nequality.\n *)\n\n\nRequire Import Coq.Setoids.Setoid.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Classes.EquivDec.\nRequire Import Coq.Program.Tactics.\nRequire Import Coq.MSets.MSets.\nRequire Import Coq.MSets.MSetList.\nRequire Import Coq.Structures.OrderedType.\nRequire Import Coq.Structures.OrdersEx.\nModule Nat_Pair_OT := PairOrderedType(Nat_as_OT)(Nat_as_OT).\nModule PairNatList := MSetList.Make(Nat_Pair_OT).\n\n\nRequire Import Coq.MSets.MSetProperties.\nRequire Import Coq.MSets.MSetDecide.\nModule MProps := WPropertiesOn(Nat_Pair_OT)(PairNatList).\nModule MDec := Decide(PairNatList). \nModule NatList := MSetList.Make(Nat_as_OT).\nModule NMDec := Decide(NatList).\n\n(* Kafka definitions *)\n\nDefinition id := nat.\nDefinition this:id := 0.\nDefinition that:id := 0.\nDefinition ref := nat.\n(* Cell = id [class] * [list of fields]  *)\nInductive Cell :=\n| HCell : nat * list nat -> Cell.\n(* pointer to an object *)\nDefinition heap := list (id * Cell).\n\nInductive type :=\n| class : id -> type\n| Any : type.\nDefinition env := list (id * type).\n\nInductive ForallT {A : Type} (P : A -> Type) : list A -> Type :=\n  ForallT_nil : ForallT P nil\n| ForallT_cons : forall (x : A) (l : list A), P x -> ForallT P l -> ForallT P (x :: l).\nArguments ForallT_nil {_ _}.\nArguments ForallT_cons {_ _ _ _}.\n\nUnset Elimination Schemes.\n\nInductive expr :=\n| Var : id -> expr\n| Ref : ref -> expr (* location of object *)\n| GetF : expr -> id -> expr\n| SetF : expr -> id -> expr -> expr\n| Call : expr -> id -> type -> type -> expr -> expr\n| DynCall : expr -> id -> expr -> expr\n| SubCast : type -> expr -> expr (* <t> *)\n| BehCast : type -> expr -> expr (* << t >>*)\n| New : id -> list expr -> expr.\n\nDefinition expr_rect (P : expr -> Type) (f : forall i : id, P (Var i)) (f0 : forall r : ref, P (Ref r))\n           (f1 : forall e : expr, P e -> forall i : id, P (GetF e i))\n           (f2 : forall e : expr, P e -> forall (i : id) (e0 : expr), P e0 -> P (SetF e i e0))\n           (f3 : forall e : expr, P e -> forall (i : id) (t t0 : type) (e0 : expr), P e0 -> P (Call e i t t0 e0))\n           (f4 : forall e : expr, P e -> forall (i : id) (e0 : expr), P e0 -> P (DynCall e i e0))\n           (f5 : forall (t : type) (e : expr), P e -> P (SubCast t e))\n           (f6 : forall (t : type) (e : expr), P e -> P (BehCast t e))\n           (f7 : forall (i : id) (l : list expr), ForallT P l -> P (New i l)) :=\n  fix F (e : expr) : P e :=\n    match e as e0 return (P e0) with\n    | Var i => f i\n    | Ref r => f0 r\n    | GetF e0 i => f1 e0 (F e0) i\n    | SetF e0 i e1 => f2 e0 (F e0) i e1 (F e1)\n    | Call e0 i t t0 e1 => f3 e0 (F e0) i t t0 e1 (F e1)\n    | DynCall e0 i e1 => f4 e0 (F e0) i e1 (F e1)\n    | SubCast t e0 => f5 t e0 (F e0)\n    | BehCast t e0 => f6 t e0 (F e0)\n    | New i l => f7 i l ((fix F' (l:list expr) : ForallT P l :=\n                       match l with\n                       | e :: r => ForallT_cons (F e) (F' r)\n                       | nil => ForallT_nil \n                       end) l)\n    end.\n\nDefinition expr_ind : forall (P : expr -> Prop) (f : forall i : id, P (Var i)) (f0 : forall r : ref, P (Ref r))\n           (f1 : forall e : expr, P e -> forall i : id, P (GetF e i))\n           (f2 : forall e : expr, P e -> forall (i : id) (e0 : expr), P e0 -> P (SetF e i e0))\n           (f3 : forall e : expr, P e -> forall (i : id) (t t0 : type) (e0 : expr), P e0 -> P (Call e i t t0 e0))\n           (f4 : forall e : expr, P e -> forall (i : id) (e0 : expr), P e0 -> P (DynCall e i e0))\n           (f5 : forall (t : type) (e : expr), P e -> P (SubCast t e))\n           (f6 : forall (t : type) (e : expr), P e -> P (BehCast t e))\n           (f7 : forall (i : id) (l : list expr), ForallT P l -> P (New i l)), forall e : expr, P e := expr_rect.\n\nDefinition expr_rec : forall (P : expr -> Set) (f : forall i : id, P (Var i)) (f0 : forall r : ref, P (Ref r))\n           (f1 : forall e : expr, P e -> forall i : id, P (GetF e i))\n           (f2 : forall e : expr, P e -> forall (i : id) (e0 : expr), P e0 -> P (SetF e i e0))\n           (f3 : forall e : expr, P e -> forall (i : id) (t t0 : type) (e0 : expr), P e0 -> P (Call e i t t0 e0))\n           (f4 : forall e : expr, P e -> forall (i : id) (e0 : expr), P e0 -> P (DynCall e i e0))\n           (f5 : forall (t : type) (e : expr), P e -> P (SubCast t e))\n           (f6 : forall (t : type) (e : expr), P e -> P (BehCast t e))\n           (f7 : forall (i : id) (l : list expr), ForallT P l -> P (New i l)), forall e : expr, P e := expr_rect.\n\nSet Elimination Schemes.\n\nInductive fd :=\n| Field : id -> type -> fd.\nInductive md := (* M X t t e *)\n| Method : id -> id -> type -> type -> expr -> md.\nInductive k :=\n| ClassDef : id -> list fd -> list md -> k.\nDefinition ct := list k.\nRequire Import Coq.Logic.FinFun.\n\n(* Decidability properties *)\n\nLemma type_dec : forall x y : type, {x = y} + {x <> y}.\nProof.\n  decide equality; try (apply Nat.eq_dec).\nQed.\nLtac decideish_equality :=\n  let foo x y :=\n      try (unify x y; fail 1); \n      assert (Heqdec : {x = y} + {x <> y}) by eauto; destruct Heqdec as [Heq | Hneq];\n      [subst|right; contradict Hneq; inject Hneq; reflexivity] in\n  repeat match goal with\n         | [ |- {?x = ?x} + {?x <> ?x}] => left; reflexivity\n         | [ |- {?f ?x = ?g ?y} + {?f ?x <> ?g ?y}] => foo x y\n         | [ |- {?f ?x _ = ?g ?y _} + {?f ?x _ <> ?g ?y _}] => foo x y\n         | [ |- {?f ?x _ _ = ?g ?y _ _} + {?f ?x _ _ <> ?g ?y _ _}] => foo x y\n         | [ |- {?f ?x _ _ _ = ?g ?y _ _ _} + {?f ?x _ _ _ <> ?g ?y _ _ _}] => foo x y\n         | [ |- {?f ?x _ _ _ _ = ?g ?y _ _ _ _} + {?f ?x _ _ _ _ <> ?g ?y _ _ _ _}] => foo x y\n         end.\n\nLemma expr_dec : EqDec expr.\nProof.\n  pose proof Nat.eq_dec.\n  pose proof type_dec.\n  refine (expr_rec (fun x => forall y, {x = y} + {x <> y}) _ _ _ _ _ _ _ _ _);\n    intros; try (destruct y); try solve [right; discriminate]; decideish_equality.\n    - revert l0. induction l.\n      + intros. destruct l0.\n        * left. reflexivity.\n        * right. discriminate.\n      + intros. destruct l0.\n        * right. discriminate.\n        * inject H1. apply IHl with (l0 := l0) in H5. destruct H5.\n          ** inject e0. specialize (H4 e). destruct H4.\n             *** subst. eauto.\n             *** right. contradict n. inject n. reflexivity.\n          ** right. contradict n. inject n. reflexivity.\nQed.\n\nLemma md_dec : forall x y : md, {x = y} + {x <> y}.\nProof.\n  decide equality; eauto using expr_dec, Nat.eq_dec, type_dec.\nQed.\n  (*\nInductive mt :=\n| MType : id -> type -> type -> mt.\n*)\n\nFixpoint fields (C:id)(k:ct) :=\n  match k with\n  | (ClassDef D fds mds)::r =>\n    match Nat.eqb C D with\n      true => fds\n    | false => fields C r\n    end\n  | nil => nil\n  end.\n\n(* Utility methods to work with methods *)\n\n(* Finds the methods of c in k *)\nFixpoint methods (C:id)(k:ct) :=\n  match k with\n  | (ClassDef D fds mds)::r =>\n    match Nat.eqb C D with\n      true => mds\n    | false => methods C r\n    end\n  | nil => nil\n  end.\n\n(* finds the definition of m in ms *)\nFixpoint method_def (m:id) (ms:list md) : (option md) :=\n  match ms with\n  | (Method m' x t1 t2 e)::r =>\n    match Nat.eqb m m' with\n    | true => Some(Method m' x t1 t2 e)\n    | false => method_def m r\n    end\n  | nil => None\nend.\n\n(* Subtyping *)\n\nInductive Subtype : PairNatList.t -> ct -> type -> type -> Prop :=\n| STRefl : forall m k t, Subtype m k t t\n| STSeen : forall m k t1 t2, PairNatList.In (t1, t2) m ->\n                             Subtype m k (class t1) (class t2)\n| STClass : forall m m' k c d, m' = PairNatList.add (c,d) m ->\n                               Md_Subtypes m' k (methods c k) (methods d k) ->\n                               Subtype m k (class c) (class d)\nwith Md_Subtypes : PairNatList.t -> ct -> list md -> list md -> Prop :=\n     | MDCons : forall md1 md2 mu k r mds,\n         (In md1 mds) ->\n         (Md_Subtype mu k md1 md2)-> (Md_Subtypes mu k mds r) -> \n         (Md_Subtypes mu k mds (md2::r))\n     | MDNil : forall mu k mds, (Md_Subtypes mu k mds nil)\nwith Md_Subtype : PairNatList.t -> ct -> md -> md -> Prop :=\n     | MDSub : forall mu k t1 t1' t2 t2' x x' e e' m, (Subtype mu k t1 t1') -> (Subtype mu k t2' t2) ->\n                                                      Md_Subtype mu k (Method m x' t1' t2' e') (Method m x t1 t2 e).\n\nScheme subtyping_ind := Induction for Subtype Sort Prop\n                        with md_subtypings_ind := Induction for Md_Subtypes Sort Prop\n                                                  with md_subtype_ind := Induction for Md_Subtype Sort Prop.\n\nDefinition empty_mu := PairNatList.empty.\n\nHint Constructors Subtype.\nHint Constructors Md_Subtypes.\n\n(* Typing *)\n\nInductive WellFormedType : ct -> type -> Prop :=\n| WFWA : forall k, WellFormedType k Any\n| WFWTC : forall k C fds mds, In (ClassDef C fds mds) k -> WellFormedType k (class C).\n\n(* Typing rule, identical to paper *)\nInductive HasType : env -> heap -> ct -> expr -> type -> Prop :=\n| KTSUB : forall g s k e t tp, HasType g s k e tp -> Subtype PairNatList.empty k tp t -> HasType g s k e t\n| KTEXPR : forall g s k e t, HasTypeExpr g s k e t -> HasType g s k e t\nwith HasTypeExpr : env -> heap -> ct -> expr -> type -> Prop :=\n| KTVAR : forall g s k x t, In (x,t) g -> HasTypeExpr g s k (Var x) t\n| KTREAD : forall g s k f t C,\n    In (this,(class C)) g ->\n    In (Field f t) (fields C k) ->\n    HasTypeExpr g s k (GetF (Var this) f) t\n| KTREFREAD : forall g s k f a a' C t,\n    In (a, HCell(C, a')) s ->\n    In (Field f t) (fields C k) ->\n    HasTypeExpr g s k (GetF (Ref a) f) t\n| KTWRITE : forall g s k f e C t,\n    In (this, (class C)) g ->\n    In (Field f t) (fields C k) ->\n    HasType g s k e t ->\n    HasTypeExpr g s k (SetF (Var this) f e) t\n| KTREFWRITE : forall g s k f a a' C e t,\n    In (a, HCell(C, a')) s ->\n    In (Field f t) (fields C k) ->\n    HasType g s k e t ->\n    HasTypeExpr g s k (SetF (Ref a) f e) t\n| KTCALL : forall g s k m t t' e e' eb x C,\n    HasType g s k e (class C) ->\n    HasType g s k e' t ->\n    In (Method m x t t' eb) (methods C k) ->\n    HasTypeExpr g s k (Call e m t t' e') t'\n| KTDYNCALL : forall g s k e e' m,\n    HasType g s k e Any ->\n    HasType g s k e' Any ->\n    HasTypeExpr g s k (DynCall e m e') Any\n| KTNEW : forall g s k C es fds mds,\n    HasTypes g s k es fds ->\n    In (ClassDef C fds mds) k ->\n    HasTypeExpr g s k (New C es) (class C)\n| KTSUBCAST : forall g s k e t tp,\n    WellFormedType k t -> \n    HasType g s k e tp ->\n    HasTypeExpr g s k (SubCast t e) t\n| KTBEHCAST : forall g s k e t tp,\n    WellFormedType k t -> \n    HasType g s k e tp ->\n    HasTypeExpr g s k (BehCast t e) t\n| KTREFTYPE : forall g s k a C t a',\n    In (a,(HCell(C,a'))) s ->\n    Subtype empty_mu k (class C) t ->\n    HasTypeExpr g s k (Ref a) t\n| KTREFANY : forall g s k a hc,\n    In (a,hc) s -> \n    HasTypeExpr g s k (Ref a) Any\nwith HasTypes : env -> heap -> ct -> list expr -> list fd -> Prop :=\n     | HTSCONS : forall g s k e t f er fr,\n         HasType g s k e t ->\n         HasTypes g s k er fr -> \n         HasTypes g s k (e::er) ((Field f t)::fr)\n     | HTSNIL : forall g s k, HasTypes g s k nil nil.\n\nScheme typing_ind := Induction for HasType Sort Prop\n                     with expr_typing_ind := Induction for HasTypeExpr Sort Prop\n                                             with typings_ind := Induction for HasTypes Sort Prop.\n\nHint Constructors HasType.\nHint Constructors HasTypes.\nHint Constructors HasTypeExpr.\n\nLemma env_weakening : forall g g' s k e t,\n    HasType g s k e t -> HasType (g ++ g') s k e t.\nProof.\n  intros. apply typing_ind with\n          (P:=fun g => fun s => fun k => fun e0 => fun t => fun ih => HasType (g ++ g') s k e0 t)\n            (P0:=fun g s k e0 t ih => HasTypeExpr (g ++ g') s k e0 t)\n            (P1:=fun g => fun s => fun k => fun es0 => fun fds => fun ih => HasTypes (g ++ g') s k es0 fds)\n            (e:=g); try eauto.\n  - intros. eapply KTVAR. apply in_app_iff. auto.\n  - intros. eapply KTREAD; eauto. apply in_app_iff. eauto.\n  - intros. eapply KTWRITE; eauto. apply in_app_iff. eauto.\nQed.\n\nLemma heap_weakening : forall g s s' k e t,\n    HasType g s k e t -> HasType g (s ++ s') k e t.\nProof.\n  intros. apply typing_ind with\n          (P:=fun g => fun s => fun k => fun e0 => fun t => fun ih => HasType g (s ++ s') k e0 t)\n            (P0 := fun g s k e0 t ih => HasTypeExpr g (s ++ s') k e0 t)\n            (P1:=fun g => fun s => fun k => fun es0 => fun fds => fun ih => HasTypes g (s ++ s') k es0 fds); try eauto.\n  - intros. eapply KTREFREAD; eauto. apply in_app_iff. eauto.\n  - intros. eapply KTREFWRITE; eauto. apply in_app_iff. eauto.\n  - intros. eapply KTREFTYPE; eauto. apply in_app_iff. eauto.\n  - intros. eapply KTREFANY; eauto. apply in_app_iff. eauto.\nQed.\n\n(*\nTransitivity of subtyping.\n*)\n\nLemma subtype_transitive : forall mu k t1 t2 t3,\n    Subtype mu k t1 t2 -> Subtype mu k t2 t3 -> Subtype mu k t1 t3.\nAdmitted.\n\n(*\nSoundness of subtyping. \n*)\nLemma subtype_method_containment : forall k C D md,\n    Subtype empty_mu k (class C) (class D) -> In md (methods D k) ->\n    exists md', In md' (methods C k) /\\ Md_Subtypes empty_mu k (md'::nil) (md::nil).\nAdmitted.\n\n (* [thisref/this][varref/var](exp) *)\nFixpoint subst(thisref : ref)(varref : ref)(var : id)(exp : expr) :=\n  match exp with\n  | Var x => match Nat.eqb x this, Nat.eqb x var with\n             | true, _ => Ref thisref\n             | _, true => Ref varref\n             | _, _ => Var x\n             end\n  | Ref a => Ref a\n  | GetF e f => GetF (subst thisref varref var e) f\n  | SetF e f e' => SetF (subst thisref varref var e) f (subst thisref varref var e')\n  | Call e m t1 t2 e' => Call (subst thisref varref var e) m t1 t2 (subst thisref varref var e')\n  | DynCall e m e' => DynCall (subst thisref varref var e) m (subst thisref varref var e')\n  | SubCast t e => SubCast t (subst thisref varref var e)\n  | BehCast t e => BehCast t (subst thisref varref var e)\n  | New C es => New C (List.map (subst thisref varref var) es)\n  end.\n\nLemma eventually_concrete : forall g s k e t,\n  HasType g s k e t -> exists tp, Subtype empty_mu k tp t /\\ HasTypeExpr g s k e tp.\nProof.\n  intros. induction H.\n  - inversion IHHasType as [t' (H1, H2)]. exists t'. split.\n    + apply subtype_transitive with (t2 := tp); try eauto.\n    + apply H2.\n  - exists t. split; eauto.\nQed.\n\n\nRequire Import Coq.Program.Equality.\n(* s -- heap *)\nLemma substituion_typing : forall C x t t' s k e a al a',\n    x <> this -> \n    (* method body is ok*)\n    HasType ((this, (class C)) :: (x, t') :: nil) s k e t -> \n    (*  *)\n    In (a,HCell(C,al)) s ->\n    HasType nil s k (Ref a') t' ->\n    HasType nil s k (subst a a' x e) t.\nProof.\n  intros C x t t' s k e a al a'. intros.\n  assert (Hduh1: ((this, (class C)) :: (x, t') :: nil) =((this, (class C)) :: (x, t') :: nil)).\n  { reflexivity. }\n  assert (Hduh2: s = s).\n  { reflexivity. }\n  assert (Hduh3: k = k).\n  { reflexivity. }\n  generalize dependent Hduh3. generalize dependent Hduh2. generalize dependent Hduh1.\n  apply typing_ind with\n  (P := fun g' s' k' e t => fun (ih : HasType g' s' k' e t) =>\n                              g' = ((this, (class C)) :: (x, t') :: nil) ->\n                              s' = s -> k' = k -> HasType nil s k (subst a a' x e) t)\n    (P0 := fun g' s' k' e t ih => g' = ((this, (class C)) :: (x, t') :: nil) ->\n                                  s' = s -> k' = k -> HasTypeExpr nil s k (subst a a' x e) t)\n    (P1 := fun g' s' k' es ts ih => g' = ((this, (class C)) :: (x, t') :: nil) ->\n                                    s' = s -> k' = k -> HasTypes nil s k (List.map (subst a a' x) es) ts);\n    intros; subst; try eauto; try (inversion i); try (simpl; eauto).\n  - destruct (x0 =? this) eqn:Hxthis.\n    + apply Nat.eqb_eq in Hxthis. subst. inversion H3. subst. eauto.\n    + destruct (x0 =? x) eqn:Hxx0.\n      * apply Nat.eqb_eq in Hxx0. subst. inversion H3. subst. \n        assert (Heq : this = this) by reflexivity. contradiction.\n      * inversion H3. subst. apply Nat.eqb_neq in Hxthis. \n        assert (Heq : this = this) by reflexivity. contradiction.\n  - destruct (x0 =? this) eqn:Hxthis.\n    + apply Nat.eqb_eq in Hxthis. subst. inversion H3. \n      * inversion H4. subst. \n        assert (Heq : this = this) by reflexivity. contradiction.\n      * inversion H4.\n    + apply Nat.eqb_neq in Hxthis. inversion H3.\n      * inversion H4. subst. destruct (x0 =? x0) eqn:Hxx.\n        ** apply eventually_concrete in H2. inversion H2 as [t' (H5, H6)].\n           inversion H6; subst. \n           **** eapply KTREFTYPE with (C:=C0); eauto. apply subtype_transitive with (t2 := t'); eauto.\n           **** inversion H5. subst. eapply KTREFANY; eauto.\n        ** apply Nat.eqb_neq in Hxx. inversion H3; \n           assert (Heq : x0 = x0) by reflexivity; contradiction.\n      * inversion H4.\n  - inversion H3. subst. eapply KTREFREAD; eauto.\n  - inversion H3.\n    + inversion H4. subst. \n      assert (Heq : this = this) by reflexivity. contradiction.\n    + inversion H4.\n  - inversion H4. subst. eapply KTREFWRITE; eauto.\n  - inversion H4.\n    + inversion H5. assert (Heq : this = this) by reflexivity. contradiction.\n    + inversion H5.\nQed. \n\nInductive WellFormedField : ct -> fd -> Prop :=\n| WFFWF : forall f k t, WellFormedType k t -> WellFormedField k (Field f t).\n\nInductive WellFormedMethod : env -> ct -> md -> Prop :=\n| WFMDUT : forall x g k e m, x <> this ->\n                               HasType (g ++ (x,Any)::nil) nil k e Any ->\n                               WellFormedMethod g k (Method m x Any Any e)\n| WFMT : forall g k C1 C2 x e m,\n    x <> this ->\n    WellFormedType k (class C1) -> WellFormedType k (class C2) ->\n    HasType (g ++ (x,(class C1))::nil) nil k e (class C2) ->\n    WellFormedMethod g k (Method m x (class C1) (class C2) e).\n\n\nInductive NoDupsMds : list md -> Prop :=\n| NDUPANY : forall m x e mds,\n    NoDupsMds mds -> \n    (forall x' e', ~ In (Method m x' Any Any e') mds) ->\n    NoDupsMds ((Method m x Any Any e)::mds) \n| NDUPCLS : forall m x e mds C1 C2,\n    NoDupsMds mds -> \n    (forall x' e' C1' C2', ~ In (Method m x' (class C1') (class C2') e') mds) ->\n    NoDupsMds ((Method m x (class C1) (class C2) e)::mds) \n| NDUPN : NoDupsMds nil.\n\nInductive NoDupsFds : list fd -> Prop :=\n| NDUPFD : forall f t fds, NoDupsFds fds -> (forall t', ~ (In (Field f t') fds)) -> NoDupsFds ((Field f t)::fds)\n| NDUPNI : NoDupsFds nil.\n\n(*TODO: duplicate classes will need to change if we can extend the class table*)\n(*TODO: NoDupsClasses will still be the same, right? Just need to ensure that it is not extended with a class\n        that's already in the table.*)\nInductive NoDupsClasses : list k -> Prop :=\n| NDUPK : forall C fds mds ks, NoDupsClasses ks -> (forall fds' mds', ~(In (ClassDef C fds' mds') ks)) ->\n                               NoDupsClasses ((ClassDef C fds mds)::ks)\n| NDUPNIL : NoDupsClasses nil.\n\nInductive WellFormedClass : ct -> k -> Prop :=\n| WFWC : forall k C mds fds,\n    (forall fd, In fd fds -> WellFormedField k fd) ->\n    (forall md, In md mds -> WellFormedMethod ((this, class C) :: nil) k md) ->\n    NoDupsFds fds -> NoDupsMds mds -> \n    WellFormedClass k (ClassDef C fds mds).\n\nInductive WellFormedClassTable : ct -> Prop :=\n| WFCT : forall k,\n    (forall C fds mds, In (ClassDef C fds mds) k -> WellFormedClass k (ClassDef C fds mds)) ->\n    NoDupsClasses k ->\n    WellFormedClassTable k.\n\n\nLemma methods_in : forall fds mds C k,\n    WellFormedClassTable k ->\n    In (ClassDef C fds mds) k ->\n    mds = (methods C k).\nProof.\n  intros. destruct H as [k _ H]. induction k.\n  - inversion H0.\n  - destruct a as [D fds' mds']. destruct (Nat.eq_dec C D).\n    + subst. simpl. rewrite Nat.eqb_refl. inversion H0; eauto.\n      * inject H1. reflexivity.\n      * inject H. apply H7 in H1. tauto. \n    + unfold methods. apply Nat.eqb_neq in n. rewrite -> n. apply IHk.\n      * inject H. apply H3.\n      * inversion H0.\n        ** inject H1. apply Nat.eqb_neq in n. tauto.\n        ** apply H1.\nQed.\n\n(* ct_ext allows class tables to be grown while executing.\n   It's a weak property that only provides a guarantee that the \n   new classes won't have a name conflict with the old classes *)\n\nDefinition ct_ext (k : ct) (k' : ct) := exists k'',\n           k' = k'' ++ k /\\ NoDupsClasses k'.\n\n(*CT extension basic property*)\nLemma ct_exten_refl : forall k,\n    NoDupsClasses k -> ct_ext k k.\nProof.\n  intros.\n  unfold ct_ext.\n  exists nil. simpl. repeat split; auto; try inject H0. \nQed.\n\nHint Resolve ct_exten_refl. \n\n(*Lemmas for CT extensions*)\n\nLemma methods_implies_containment : forall m k C, In m (methods C k) ->\n                                                  exists fds mds, In (ClassDef C fds mds) k.\nProof.\n  intros. induction k0.\n  - simpl in H. tauto.\n  - simpl in H. destruct a. destruct (Nat.eqb C i) eqn:Heq.\n    + apply Nat.eqb_eq in Heq. subst. exists l. exists l0. apply in_eq.\n    + apply IHk0 in H. inject H. inject H0.  exists x. exists x0. apply in_cons. apply H.\nQed.\n\nLemma fields_implies_containment : forall m k C, In m (fields C k) ->\n                                                  exists fds mds, In (ClassDef C fds mds) k.\nProof.\n  intros. induction k0.\n  - simpl in H. tauto.\n  - simpl in H. destruct a. destruct (Nat.eqb C i) eqn:Heq.\n    + apply Nat.eqb_eq in Heq. subst. exists l. exists l0. apply in_eq.\n    + apply IHk0 in H. inject H. inject H0.  exists x. exists x0. apply in_cons. apply H.\nQed.\n\nLemma ct_exten_methods : forall m k k' C, In m (methods C k) -> ct_ext k k' -> In m (methods C k').\nProof.\n  intros. inject H0. inject H1. induction x.\n  - simpl. apply H.\n  - simpl. destruct a. simpl in H2. inject H2.  apply methods_implies_containment in H.\n    inject H. inject H0. assert (Hin: (In (ClassDef C x0 x1) (x ++ k0))).\n    { apply in_or_app. auto. }\n    destruct (Nat.eqb C i) eqn:Heq.\n    + rewrite Nat.eqb_eq in Heq. subst. apply H6 in Hin. tauto.\n    + apply IHx. apply H3.\nQed.\n\nLemma ct_methods_eq : forall k k' C, WellFormedType k (class C) -> ct_ext k k' -> (methods C k) = (methods C k').\nProof.\n  intros. inject H0. inject H1. induction x.\n  - simpl. auto.\n  - simpl. destruct a. destruct (Nat.eq_dec C i).\n    + subst. inject H. inject H2. assert (Hin: In (ClassDef i fds mds) (x ++ k0)).\n      { apply in_or_app. right. auto. }\n      apply H6 in Hin. tauto.\n    + rewrite<- Nat.eqb_neq in n. rewrite n. apply IHx. simpl in H2. inject H2. apply H3.\nQed.\n\nLemma ct_fields_eq : forall k k' C, WellFormedType k (class C) -> ct_ext k k' -> (fields C k) = (fields C k').\nProof.\n  intros. inject H0. inject H1. induction x.\n  - simpl. auto.\n  - simpl. destruct a. destruct (Nat.eq_dec C i).\n    + subst. inject H. inject H2. assert (Hin: In (ClassDef i fds mds) (x ++ k0)).\n      { apply in_or_app. right. auto. }\n      apply H6 in Hin. tauto.\n    + rewrite<- Nat.eqb_neq in n. rewrite n. apply IHx. simpl in H2. inject H2. apply H3.\nQed.\n\nHint Resolve ct_fields_eq. \nHint Resolve ct_exten_methods. \nHint Resolve ct_methods_eq.\nHint Resolve fields_implies_containment.\n\nLemma fields_ct_ext : forall fd k k' C,\n    ct_ext k k' -> In fd (fields C k) -> In fd (fields C k').\nProof.\n  intros. pose proof H0. apply fields_implies_containment in H0. inject H0. inject H2.  \n  erewrite<- ct_fields_eq; eauto. econstructor. apply H0. \nQed.\n\nHint Resolve fields_ct_ext.\n\nLemma methods_opt : forall C k mds, methods C k = mds -> mds <> nil -> exists fds, In (ClassDef C fds mds) k.\nProof.\n  intros. induction k0.\n  - simpl in H. rewrite H in H0. contradiction.\n  - simpl in H. destruct a as [C' fds' mds']. destruct (Nat.eq_dec C C').\n    + subst. rewrite Nat.eqb_refl. exists fds'. apply in_eq.\n    + rewrite<- Nat.eqb_neq in n. rewrite n in H. apply IHk0 in H. inject H.\n      exists x. apply in_cons. apply H1.\nQed.\n\n\nLemma methods_maynil : forall C k mds, methods C k = mds -> mds = nil \\/ exists fds, In (ClassDef C fds mds) k.\nProof.\n  intros. induction k0.\n  - simpl in H. eauto.\n  - simpl in H. destruct a as [C' fds' mds']. destruct (Nat.eq_dec C C').\n    + subst. rewrite Nat.eqb_refl. right. exists fds'. apply in_eq.\n    + rewrite<- Nat.eqb_neq in n. rewrite n in H. apply IHk0 in H. inject H.\n      * eauto.\n      * right. inject H0. exists x. apply in_cons. apply H.\nQed.\n\nFixpoint methods_notnil (C : id) (k : ct) : list md + {forall fds mds, ~ (In (ClassDef C fds mds) (k))}.\nProof. induction k.\n       - right. intros. auto.\n       - destruct a. destruct (Nat.eq_dec C i).\n         + subst. left. apply l0.\n         + destruct IHk.\n           * left. apply l1.\n           * right. intros. unfold not. intros. inject H.\n             ** inject H0. contradiction.\n             ** apply n0 in H0. apply H0.\nQed.\n\n\nLemma ct_exten_wft : forall k k' t, WellFormedType k t -> ct_ext k k' -> WellFormedType k' t.\nProof.\n  intros. inject H; try constructor. inject H0. inject H. econstructor. apply in_or_app.\n  right. apply H1.\nQed.\n\nHint Resolve ct_exten_wft.\n\n\n(* Adding new classes to the class table won't break existing subtype \n   judgements. *)\nLemma ct_exten_subtyp : forall m k t t' k',\n    Subtype m k t t' -> ct_ext k k' -> Subtype m k' t t'.\nAdmitted.\nHint Resolve ct_exten_subtyp.\n  \nLemma ct_exten_hastype : forall g s k e t k',\n        HasType g s k e t -> ct_ext k k' -> HasType g s k' e t.\nProof.\n  intros. pose proof (eq_refl k0). generalize dependent H1.\n  pose proof (typing_ind (fun gi si ki ei ti ih => ki = k0 -> HasType gi si k' ei ti)\n                         (fun gi si ki ei ti ih => ki = k0 -> HasTypeExpr gi si k' ei ti)\n                         (fun gi si ki esi tsi ih => ki = k0 -> HasTypes gi si k' esi tsi)).\n  apply H1; clear H1; try (intros; subst; econstructor; eauto; fail). \n  - intros. subst. econstructor; eauto. inject H0. inject H2. apply in_or_app. right. apply i.\nQed.\n\n(* Inductive expr :=\n| Var : id -> expr\n| Ref : ref -> expr (* location of object *)\n| GetF : expr -> id -> expr\n| SetF : expr -> id -> expr -> expr\n| Call : expr -> id -> type -> type -> expr -> expr\n| DynCall : expr -> id -> expr -> expr\n| SubCast : type -> expr -> expr (* <t> *)\n| BehCast : type -> expr -> expr (* << t >>*)\n| New : id -> list expr -> expr. *)\n\nInductive Md_T_UT : md -> Prop :=\n| MdTyped : forall m x c1 c2 e, Md_T_UT (Method m x (class c1) (class c2) e)\n| MdUntyped : forall m x e, Md_T_UT (Method m x Any Any e).\n\nLemma wfmd_is_T_UT : forall g k md, WellFormedMethod g k md -> Md_T_UT md.\nProof.\n  intros. inject H; constructor.\nQed.\n\n\nFixpoint match_method (from : list md) (tgt : md) : option md :=\n  match tgt with\n  | (Method m x (class c1) (class c2) e) =>\n    match from with\n    | (Method m' x' (class c1') (class c2') e') :: r =>\n      if (Nat.eqb m m') then\n        Some(Method m' x' (class c1') (class c2') e')\n      else\n        match_method r tgt\n    | _ :: r => match_method r tgt\n    | nil => None\n    end\n  | (Method m x Any Any e) =>\n    match from with\n    | (Method m' x' Any Any e') :: r =>\n      if (Nat.eqb m m') then\n        Some(Method m' x' Any Any e')\n      else\n        match_method r tgt\n    | _ :: r => match_method r tgt\n    | nil => None\n    end\n  | _ => None\n  end.\n\nLtac unfold_existentials H :=\n  match goal with\n  | [ H: (exists x, _) |- _ ] => inject H; unfold_existentials H\n  | _ => idtac\n  end.\n\n\nLtac sync_destruct_exists H :=\n  repeat (let x := fresh \"x\" in destruct H as [x H]; exists x).\n\nLemma typed_method_dec : forall m md,\n    ( { tuple:id*id*id*expr | let '(x,c1,c2,e) := tuple in Method m x (class c1) (class c2) e = md } )\n    + { forall x c1 c2 e, (Method m x (class c1) (class c2) e) <> md }.\nProof.\n  intros. destruct md0. destruct t; destruct t0; destruct (Nat.eq_dec m i);\n                          try (right; intros; intro H; inject H; tauto); revgoals.\n  - subst. left. exists ((i0, i1, i2, e)). auto.\nQed.\n\nLemma typed_equiv_in_dec : forall m mds, ( { tuple:id*id*id*expr | let '(x,c1,c2,e):= tuple in\n                                                                   In (Method m x (class c1) (class c2) e) mds} ) +\n                                         { forall x c1 c2 e, ~In (Method m x (class c1) (class c2) e) mds }.\nProof.\n  intros. induction mds.\n  - right. intros. intro H. inject H.\n  - destruct (typed_method_dec m a).\n    + left. destruct s. exists x. destruct x as [[[x c1] c2] e]. subst. apply in_eq.\n    + inject IHmds.\n      * left. destruct H. exists x. destruct x as [[[x c1] c2] e]. apply in_cons. auto.\n      * right. intros. intro Hneg. inject Hneg.\n        ** unfold not in n. eapply n. eauto.\n        ** apply H in H0. auto.\nQed.\n\nLemma untyped_method_dec : forall m md,\n    ( { tuple:id*expr | let '(x,e) := tuple in Method m x Any Any e = md } )\n    + { forall x e, (Method m x Any Any e) <> md }.\nProof.\n  intros. destruct md0. destruct t; destruct t0; destruct (Nat.eq_dec m i);\n                          try (right; intros; intro H; inject H; tauto); revgoals.\n  - subst. left. exists ((i0, e)). auto.\nQed.\n\nLemma untyped_equiv_in_dec : forall m mds, ( { tuple:id*expr | let '(x,e):= tuple in\n                                                                   In (Method m x Any Any e) mds} ) +\n                                         { forall x e, ~In (Method m x Any Any e) mds }.\nProof.\n  intros. induction mds.\n  - right. intros. intro H. inject H.\n  - destruct (untyped_method_dec m a).\n    + left. destruct s. exists x. destruct x as [x e]. subst. apply in_eq.\n    + inject IHmds.\n      * left. destruct H. exists x. destruct x as [x e]. apply in_cons. auto.\n      * right. intros. intro Hneg. inject Hneg.\n        ** unfold not in n. eapply n. eauto.\n        ** apply H in H0. auto.\nQed.\n\nLemma method_name_dec : forall m md,\n    ( { tuple:id*type*type*expr | let '(x,t1,t2,e) := tuple in Method m x t1 t2 e = md } )\n    + { forall x t1 t2 e, (Method m x t1 t2 e) <> md }.\nProof.\n  intros. destruct md0. destruct t; destruct t0; destruct (Nat.eq_dec m i);\n                          try(right; intros ? ? ? ? H; inject H; auto; fail);\n                          try (subst; left; eexists ((i0, _, _, e)); auto; fail).\nQed.    \n\nLemma method_in_by_name : forall m mds, ( { tuple:id*type*type*expr | let '(x,t1,t2,e):= tuple in\n                                                            In (Method m x t1 t2 e) mds} ) +\n                                        { forall x t1 t2 e, ~In (Method m x t1 t2 e) mds }.\nProof.\n  intros. induction mds.\n  - right. intros ? ? ? ? H. inject H.\n  - destruct (method_name_dec m a).\n    + destruct s. left. exists x. destruct x as [[[x t1] t2] e]. subst. apply in_eq.\n    + destruct IHmds.\n      * left. destruct s. exists x. destruct x as [[[x t1] t2] e]. apply in_cons. auto.\n      * right. intros. intro H. inject H.\n        ** eapply n. eauto.\n        ** apply n0 in H0. eauto.\nQed.\n\nDefinition wrap_method (source:md) (target:md) :=\n  match source,target with\n  | (Method m' x' t1' t2' e'),\n    (Method m x t1 t2 e) =>\n    Method m (S this) t1 t2 (BehCast t2 (Call (GetF (Var this) that) m t1' t2' (BehCast t1' (Var (S this)))))\n  end.  \n\nDefinition find_suitable_impl (inside:list md) (formd : md) : option md :=\n  let '(Method m x t1 t2 _) := formd in \n  (match method_in_by_name m inside with\n   | inleft (exist _ (x',t1',t2',e) _) =>\n     Some(wrap_method (Method m x' t1' t2' e) formd)\n   | inright _ => None\n   end).\n\nFixpoint wrap_methods (from: list md) (to: list md) : list md :=\n  match to with\n  | target::rest =>\n    match find_suitable_impl from target with\n    | Some(md) => md::(wrap_methods from rest)\n    | None => nil\n    end\n  | nil => nil\n  end.\n\nDefinition passthrough_if_not_prescribed (fromd : md) (to : list md) : option md :=\n  let '(Method m x t1 t2 _) := fromd in \n  (match method_in_by_name m to with\n   | inleft (exist _ _ _) => None\n   | inright _ =>\n     Some(Method m x t1 t2 (Call (GetF (Var this) that) m t1 t2 (Var x)))\n   end).\n\nFixpoint passthrough_other_mds (fromd:list md) (to : list md) : list md :=\n  match fromd with\n  | md::rest => match passthrough_if_not_prescribed md to with\n                | Some(md') => md' :: (passthrough_other_mds rest to)\n                | None => passthrough_other_mds rest to\n                end\n  | nil => nil\n  end.\n\nFixpoint WrapAny_methods(input_meth : md) (D_meth : list md) : md :=\n  match input_meth with\n  | Method m x t1 t2 e =>\n    Method m (S this) Any Any (BehCast Any (Call (GetF (Var this) that) m t1 t2 (BehCast t1 (Var (S this)))))\nend.\n\n\nFixpoint Wrap_many_any_methods (seen:NatList.t) (mds1 : list md) (mds2 : list md) :=\n  match mds1 with\n  | md::mdr =>\n    let '(Method m _ _ _ _) := md in\n    match NatList.mem m seen with\n    | true => Wrap_many_any_methods seen mdr mds2\n    | false => (WrapAny_methods md mds2)::(Wrap_many_any_methods (NatList.add m seen) mdr mds2)\n    end\n  | nil => nil\n  end.\n\nDefinition Wrap_classes (C : id) (md1 : list md) (md2 : list md) (D : id) : k :=\n  ClassDef D ((Field that (class C))::nil) ((wrap_methods md1 md2) ++ (passthrough_other_mds md1 md2)).\n\nDefinition WrapAny_classes (C : id) (md1 : list md) (D : id) : k :=\n  ClassDef D ((Field that (class C))::nil) (Wrap_many_any_methods NatList.empty md1 md1).\n\nLemma correctness_MWrapAny : forall m x t1 t2 e g k md mds mds' C D,\n    C <> D ->\n    md = Method m x t1 t2 e ->\n    In md (methods C ((ClassDef D ((Field that (class C))::nil) mds') :: k)) ->\n    WellFormedMethod ((this, class C) :: g) k md -> \n    WellFormedMethod ((this, class D) :: g) ((ClassDef D ((Field that (class C))::nil) mds') :: k)\n                     (WrapAny_methods md mds).\nProof.\n  intros.\n  subst.\n  simpl.\n  constructor.\n  - inject H2; eauto.\n  - constructor.\n    econstructor.\n    constructor.\n    constructor.\n    econstructor.\n    * simpl. constructor. econstructor.\n      ** apply in_eq.\n      ** simpl. rewrite -> Nat.eqb_refl.\n         apply in_eq.\n    * constructor. econstructor.\n      ** inject H2.\n        *** constructor.\n        *** inject H10. econstructor. apply in_cons. eauto.\n      ** constructor. econstructor. apply in_or_app. right. apply in_eq.\n    * eauto.\nQed.\n\n(*\nLemma correctness_mdef : forall m x t1 t2 e mds,\n    NoDupsMds mds ->\n    Some (Method m x t1 t2 e) = (method_def m mds) <-> In (Method m x t1 t2 e) mds.\nProof.\n  intros. split; intros.\n  - induction mds.\n    + simpl in H0. inversion H0.\n    + simpl in H0. destruct a. destruct (Nat.eqb m i).\n      * inject H0. apply in_eq.\n      * apply in_cons. apply IHmds; eauto. inject H. eauto.\n  - induction mds.\n    + inject H0.\n    + simpl. destruct a as [m' x' t1' t2' e']. inject H0.\n      * inject H1. rewrite Nat.eqb_refl. auto.\n      * destruct (Nat.eqb m m') eqn:Heq.\n        ** apply Nat.eqb_eq in Heq. subst. inject H. apply H8 in H1. tauto.\n        ** inject H. apply IHmds; eauto.\nQed.\n\nLemma mdef_same_name : forall i m mds x t1 t2 e, Some(Method i x t1 t2 e) = (method_def m mds) -> i = m.\nProof.\n  intros. induction mds.\n  - simpl in H. inject H.\n  - simpl in H. destruct a. destruct (Nat.eqb m i0) eqn:Heq.\n    + apply Nat.eqb_eq in Heq. inject H. auto.\n    + apply IHmds in H. apply H.\nQed.\n*)\nDefinition fresh_class_name(C : id)(k : ct) :=\n  forall fds mds, ~ In (ClassDef C fds mds) k.\n\nLtac ht :=\n  match goal with\n  | [ |- HasType _ _ _ _ _ ] => constructor\n  | [ |- HasTypeExpr _ _ _ _ _ ] => econstructor\n  end.\n\nHint Constructors HasType.\nHint Constructors HasTypeExpr.\n\nLemma wrap_method_wfmd : forall m x t1 t2 e x' t1' t2' e' g k md md' mds' C D E,\n    WellFormedClassTable k -> fresh_class_name D k -> \n    md = Method m x t1 t2 e ->\n    md' = Method m x' t1' t2' e' ->\n    In md (methods C k) -> In md' (methods E k) ->\n    WellFormedMethod ((this, class E) :: g) k md' ->\n    WellFormedMethod ((this, class C) :: g) k md ->\n    WellFormedMethod ((this, class D) :: g) ((ClassDef D ((Field that (class C))::nil) mds') :: k)\n                     (wrap_method md md').\nProof.\n  intros ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?.\n  intros Hwfct Hfcn Hmde Hmde' Hin Hin' Hwfm' Hwfm.\n  assert (Hctext: ct_ext k0 (ClassDef D (Field that (class C) :: nil) mds' :: k0)).\n  { exists ((ClassDef D (Field that (class C) :: nil) mds')::nil). simpl. split.\n    - auto.\n    - econstructor.\n      + inject Hwfct. auto.\n      + intros. unfold fresh_class_name in Hfcn. apply Hfcn. }\n  destruct md0; destruct md'. inject Hmde. inject Hmde'. simpl. inject Hwfm'.\n  - econstructor; eauto.\n    + repeat (ht).\n      * constructor.\n      * simpl. left. eauto.\n      * simpl. rewrite Nat.eqb_refl. apply in_eq.\n      * inject Hwfm; try constructor. eapply ct_exten_wft; eauto.\n      * simpl. right. apply in_or_app. right. apply in_eq.\n      * eapply ct_exten_methods; eauto.\n  - econstructor; eauto. repeat (ht); try (eauto;fail).\n    * simpl. left. eauto.\n    * simpl. rewrite Nat.eqb_refl. apply in_eq.\n    * inject Hwfm; try (eapply ct_exten_wft; eauto). constructor.\n    * simpl. right. apply in_or_app. right. constructor. eauto.\nQed.\n\nFixpoint method_names (mds:list md) :=\n  match mds with\n  | (Method m x t1 t2 r) :: mds => m :: (method_names mds)\n  | nil => nil\n  end. \n\nLemma wrap_method_is_subtype : forall mu k md md', Md_Subtype mu k (wrap_method md md') md'.\nProof.\n  intros. destruct md0; destruct md'. simpl. constructor; eauto.\nQed.\n\nLemma md_subtypes_weakening : forall md mds mds' mu k, Md_Subtypes mu k mds mds' -> Md_Subtypes mu k (md::mds) mds'.\nProof.\n  intros.\n  induction mds'.\n  - constructor.\n  - inject H. econstructor.\n    + apply in_cons. apply H2.\n    + eauto.\n    + apply IHmds'. eauto.\nQed.\n\nLemma method_names_correct : forall mds m,\n    In m (method_names mds) -> exists x t1 t2 e, In (Method m x t1 t2 e) mds.\nProof.\n  intros. induction mds.\n  - simpl in H. inject H.\n  - simpl in H. destruct a as [m']. inject H.\n    + exists i. exists t. exists t0. exists e. apply in_eq.\n    + apply IHmds in H0. sync_destruct_exists H0. apply in_cons. auto.\nQed.\n\nLemma wrap_methods_is_subtype : forall mu k mds mds',\n    incl (method_names mds') (method_names mds) ->\n    Md_Subtypes mu k (wrap_methods mds mds') mds'.\nProof.\n  intros. generalize dependent mds. induction mds'.\n  - intros. constructor.\n  - intros. destruct a. simpl. destruct (method_in_by_name i mds).\n    + destruct s as [[[[x t1] t2] e'] Hin]. econstructor.\n      * apply in_eq.\n      * constructor; eauto.\n      * apply md_subtypes_weakening. apply IHmds'. intros m Hmin.\n        apply H. simpl. right. auto.\n    + simpl in H. unfold incl in H. specialize H with i. exfalso.\n      apply method_names_correct in H; [|constructor; auto]. unfold_existentials H. apply n in H. apply H.\nQed.\n\nLemma correctness_wrap_method : forall C D E k md' fds fds' mds mds' mds'' mds''',\n    fresh_class_name D k ->\n    WellFormedClassTable k ->\n    In (ClassDef C fds mds) k ->\n    In (ClassDef E fds' mds') k ->\n    (forall md, In md mds'' -> In md mds') ->\n    In md' (wrap_methods mds mds'') ->\n    WellFormedMethod ((this, class D) :: nil)\n                     ((ClassDef D ((Field that (class C))::nil) mds''') :: k)\n                     md'.\nProof.\n  intros ? ? ? ? ? ? ? ? ? ? ?.\n  intros Hfcn Hwfct HinC HinE Hsub HInmd.\n  induction mds''.\n  - simpl in HInmd. tauto.\n  - simpl in HInmd. destruct a. unfold find_suitable_impl in HInmd. destruct (method_in_by_name i mds); revgoals.\n    + inject HInmd.\n    + destruct s. destruct x as [[[x t1] t2] e']. inject HInmd.\n      * eapply wrap_method_wfmd.\n        ** eauto.\n        ** eauto.\n        ** eauto.\n        ** eauto.\n        ** erewrite<- methods_in; eauto.\n        ** erewrite<- methods_in; eauto. apply Hsub. apply in_eq.\n        ** inject Hwfct. apply H in HinE. inject HinE. apply H6. apply Hsub. apply in_eq.\n        ** inject Hwfct. apply H in HinC. inject HinC. apply H6. apply y.\n      * apply IHmds''.\n        ** intros. apply Hsub. apply in_cons. apply H0.\n        ** auto.\nQed.\n\n\nLemma WrapManyAny_mu : forall mu mds md2 (mname : id),\n    NatList.In mname mu -> forall x t1 t2 e, ~In (Method mname x t1 t2 e) (Wrap_many_any_methods mu mds md2).\nProof.\n  intros. generalize dependent mu. induction mds.\n  - simpl. auto.\n  - intros. contradict IHmds. intro Hneg. destruct a. simpl in IHmds. rewrite<- NatList.mem_spec in H.\n    destruct (Nat.eq_dec mname i).\n    + subst. rewrite H in IHmds. apply Hneg in IHmds; auto. rewrite<- NatList.mem_spec. auto.\n    + destruct (NatList.mem i mu).\n      * apply Hneg in IHmds; auto. rewrite<- NatList.mem_spec. auto.\n      * inject IHmds.\n        ** inject H0. tauto.\n        ** apply Hneg in H0; auto. rewrite <- NatList.mem_spec. rewrite NMDec.F.add_neq_b; auto.\nQed.\n\nLemma WrapManyAny_mu_less : forall mu mu' mds md2,\n  (forall mn, NatList.In mn mu -> NatList.In mn mu') ->\n  incl (Wrap_many_any_methods mu' mds md2) (Wrap_many_any_methods mu mds md2).\nProof.\n  intros. intros md. intros. generalize dependent mu'. generalize dependent mu. induction mds.\n  - intros. simpl in H0. tauto.\n  - intros. simpl in H0. destruct a. destruct (NatList.mem i mu') eqn:Hmem.\n    + simpl. destruct (NatList.mem i mu) eqn:Hmem'.\n      * eapply IHmds; eauto.\n      * apply in_cons. eapply IHmds with (mu':=mu'); eauto. intros. rewrite NMDec.F.add_iff in H1. inject H1.\n        ** rewrite NMDec.F.mem_iff. auto.\n        ** apply H in H2. auto.\n    + simpl. destruct (NatList.mem i mu) eqn:Hmem'.\n      * rewrite<- NMDec.F.mem_iff in Hmem'. apply H in Hmem'. rewrite NMDec.F.mem_iff in Hmem'.\n        rewrite Hmem' in Hmem. inject Hmem.\n      * simpl. simpl in H0. inject H0.\n        ** left. auto.\n        ** right. eapply IHmds; revgoals.\n           *** apply H1.\n           *** intros. rewrite NMDec.F.add_iff in H0. inject H0.\n               **** apply NMDec.F.add_1. auto.\n               **** apply NMDec.F.add_2. apply H. auto.\nQed.\n\nLemma correctness_WrapManyAny : forall mu md2 mds' mds'' md' C D k fds mds,\n    fresh_class_name D k ->\n    WellFormedClassTable k ->\n    In (ClassDef C fds mds'') k ->\n    NoDupsMds md2 -> NoDupsMds mds' ->\n    (forall md' : md, In md' md2 -> WellFormedMethod ((this, class C) :: nil) k md') ->\n    (forall md' : md, In md' mds -> WellFormedMethod ((this, class C) :: nil) k md') ->\n    (forall md' : md, In md' mds -> In md' mds'') -> \n    In md' (Wrap_many_any_methods mu mds md2) -> C <> D ->\n    WellFormedMethod ((this, class D) :: nil)\n                     ((ClassDef D ((Field that (class C))::nil) mds') :: k)\n                     md'.\nProof.\n  intros ? ? ? ? ? ? ? ? ? ?  Hfresh Hwfct HinC HNdmd2 HNdmd' Hforallmd2 Hforallmd Hsub HinMd Hneq.\n  assert (Hext: ct_ext k0 (ClassDef D (Field that (class C) :: nil) mds' :: k0)).\n  { exists (ClassDef D (Field that (class C) :: nil) mds' :: nil). simpl. split; auto.\n    inject Hwfct. constructor; auto. }\n  induction mds.\n  - intros. simpl in HinMd. tauto.\n  - intros. simpl in HinMd. destruct a. destruct (NatList.mem i mu).\n    + apply IHmds; eauto.\n      * intros. apply Hforallmd. apply in_cons. auto.\n      * intros. apply Hsub. apply in_cons. auto.\n    + simpl in HinMd. inject HinMd.\n      * constructor; eauto. repeat ht.\n        ** constructor.\n        ** simpl. left. auto.\n        ** simpl. rewrite Nat.eqb_refl. constructor. auto.\n        ** inject Hwfct. apply H in HinC. inject HinC. eapply H6 in Hsub; [|constructor; eauto]. inject Hsub; eauto.\n           *** constructor.\n        ** apply in_or_app. right. constructor. auto.\n        ** simpl. rewrite<- Nat.eqb_neq in Hneq. rewrite Hneq. erewrite<- methods_in; eauto. apply Hsub.\n           apply in_eq.\n      * apply IHmds; eauto.\n        ** intros. apply Hforallmd. apply in_cons. auto.\n        ** intros. apply Hsub. apply in_cons. auto.\n        ** eapply WrapManyAny_mu_less; revgoals.\n           *** apply H.\n           *** intros. apply NMDec.F.add_2. auto.\nQed.\n\nLemma MWrapManyAny_NoDups : forall mds mds' mu, NoDupsMds mds -> NoDupsMds (Wrap_many_any_methods mu mds mds').\nProof.\n  intros. generalize dependent mu. induction mds.\n  - simpl. constructor.\n  - intros. simpl. destruct a. simpl. destruct (NatList.mem i mu) eqn:Hiin.\n    + apply IHmds. inject H; eauto.\n    + constructor.\n      * apply IHmds. inject H; auto.\n      * intros. apply WrapManyAny_mu. apply NMDec.F.add_1. auto.\nQed.\n\nLemma correctness_CWrapAny : forall k C D fds mds,\n    In (ClassDef C fds mds) k -> fresh_class_name D k -> WellFormedClassTable k ->\n    NoDupsMds mds -> \n    WellFormedClass k (ClassDef C fds mds) -> \n    WellFormedClass (ClassDef D ((Field that (class C))::nil) (Wrap_many_any_methods NatList.empty mds mds) :: k)\n                           (WrapAny_classes C mds D).\nProof.\n  intros k0 C D fds mds Hin Hneq Hwfct Hndmd Hwfc. unfold WrapAny_classes. constructor.\n  - intros. inject H; [|inject H0]. constructor. econstructor. apply in_cons. apply Hin.\n  - intros. eapply correctness_WrapManyAny; eauto.\n    + apply MWrapManyAny_NoDups; auto.\n    + intros. inject Hwfc. apply H6; auto.\n    + intros. inject Hwfc. apply H6; auto.\n    + unfold fresh_class_name in Hneq. intro Hneg. rewrite Hneg in Hin. eapply Hneq. apply Hin.\n  - inject Hwfc. constructor; eauto. constructor.\n  - apply MWrapManyAny_NoDups; auto.\nQed.\n\nLemma MWrapMethods_Inclusion : forall m x t1 t2 e mds mds',\n    incl (method_names mds') (method_names mds) -> \n    In (Method m x t1 t2 e) mds' -> exists x e, In (Method m x t1 t2 e) (wrap_methods mds mds').\nProof.\n  intros. generalize dependent m. generalize dependent x. generalize dependent t1.\n  generalize dependent t2. generalize dependent e. induction mds'.\n  - intros. inject H0.\n  - intros. simpl. unfold find_suitable_impl. destruct a. inject H0.\n    + destruct (method_in_by_name i mds).\n      * destruct s as [[[[x' t1'] t2'] e'] Hs]. inject H1. simpl. exists (S this). eexists.\n        left. eauto.\n      * inject H1. exfalso. unfold incl in H. simpl in H. specialize H with m.\n        apply method_names_correct in H;eauto. unfold_existentials H. eapply n. apply H.\n    + destruct (method_in_by_name i mds).\n      * destruct s as [[[[x' t1'] t2'] e'] Hs].  edestruct IHmds'; eauto; revgoals.\n        ** destruct H0. eexists. eexists. apply in_cons. apply H0.\n        ** intros md. intros. apply H. simpl. right. auto.\n      * unfold incl in H. simpl in H. specialize H with i. apply method_names_correct in H;eauto.\n        unfold_existentials H. apply n in H. tauto.\nQed.\n\nLemma MWrapMethods_Inclusion' :  forall m x t1 t2 e mds mds',\n    incl (method_names mds') (method_names mds) -> \n    In (Method m x t1 t2 e) (wrap_methods mds mds') -> exists x e, In (Method m x t1 t2 e) mds'.\nProof.\n  intros. induction mds'.\n  - simpl in H0. tauto.\n  - simpl in H0. unfold find_suitable_impl in H0. destruct a.\n    destruct (method_in_by_name i mds).\n    + destruct s as [[[[x' t1'] t2'] e'] Hs]. inject H0.\n      * simpl in H1. inject H1. repeat eexists. apply in_eq.\n      * destruct IHmds'; revgoals.\n        ** destruct H0. repeat eexists. apply in_cons. eauto.\n        ** auto.\n        ** intros md Hin. apply H. simpl. right. auto.\n    + inject H0.\nQed.\n\nLemma MWrapMethods_NoDups : forall mds mds', \n    incl (method_names mds') (method_names mds) -> \n    NoDupsMds mds' -> NoDupsMds (wrap_methods mds mds').\nProof.     \n  intros. induction H0.\n  - simpl. destruct (method_in_by_name m mds).\n    + destruct s as [[[[x' t1'] t2'] e'] Hs]. constructor.\n      * apply IHNoDupsMds. intros md Hin. apply H. simpl. right; auto.\n      * intros. intro Hneg. apply MWrapMethods_Inclusion' in Hneg.\n        ** unfold_existentials Hneg. apply H1 in H3. tauto.\n        ** intros md Hin. apply H. simpl. right; auto.\n    + constructor.\n  - simpl. destruct (method_in_by_name m mds).\n    + destruct s as [[[[x' t1'] t2'] e'] Hs]. constructor.\n      * apply IHNoDupsMds. intros md Hin. apply H. simpl. right; auto.\n      * intros. intro Hneg. apply MWrapMethods_Inclusion' in Hneg.\n        ** unfold_existentials Hneg. apply H1 in H3. tauto.\n        ** intros md Hin. apply H. simpl. right; auto.\n    + constructor.\n  - simpl. constructor.\nQed.\n\nLemma passthrough_inclusion :  forall m x t1 t2 e mds mds',\n    In (Method m x t1 t2 e) (passthrough_other_mds mds mds') -> exists x e, In (Method m x t1 t2 e) mds.\nProof.\n  intros. induction mds.\n  - simpl in H. tauto.\n  - simpl. simpl in H. destruct a. simpl in H. destruct (method_in_by_name i mds').\n    + destruct s as [[[[x' t1'] t2'] e'] Hs]. apply IHmds in H. unfold_existentials H. repeat eexists.\n      right. eauto.\n    + inject H.\n      * inject H0. exists x. exists e0. left. auto.\n      * apply IHmds in H0. sync_destruct_exists H0. right. eauto.\nQed.\n \nLemma passthrough_nodups : forall mds mds',\n    NoDupsMds mds -> NoDupsMds (passthrough_other_mds mds mds').\nProof.\n  intros. induction H.\n  - simpl. destruct (method_in_by_name m mds').\n    + destruct s as [[[[x' t1'] t2'] e'] Hs]. apply IHNoDupsMds.\n    + constructor; auto. intros.\n      * intro Hneg. apply passthrough_inclusion in Hneg. unfold_existentials Hneg. apply H0 in H2. tauto.\n  - simpl. destruct (method_in_by_name m mds').\n    + destruct s as [[[[x' t1'] t2'] e'] Hs]. apply IHNoDupsMds.\n    + constructor; auto. intros.\n      * intro Hneg. apply passthrough_inclusion in Hneg. unfold_existentials Hneg. apply H0 in H2. tauto.\n  - simpl. constructor.\nQed.\n\nLemma correctness_passthrough : forall C D E k md' fds fds' mds mds' mds'' mds''',\n    fresh_class_name D k ->\n    WellFormedClassTable k ->\n    In (ClassDef C fds mds) k ->\n    In (ClassDef E fds' mds') k ->\n    (forall md, In md mds'' -> In md mds) ->\n    In md' (passthrough_other_mds mds'' mds') ->\n    WellFormedMethod ((this, class D) :: nil)\n                     ((ClassDef D ((Field that (class C))::nil) mds''') :: k)\n                     md'.\nProof.\n  intros ? ? ? ? ? ? ? ? ? ? ?.\n  intros Hfcn Hwfct HinC HinE Hsub HInmd.\n  assert (Hext: ct_ext k0 (ClassDef D (Field that (class C) :: nil) mds''' :: k0)).\n  { exists (ClassDef D (Field that (class C) :: nil) mds''' :: nil). simpl. split; auto.\n    inject Hwfct. constructor; auto. }\n  induction mds''.\n  - simpl in HInmd. tauto.\n  - simpl in HInmd. destruct a. simpl in HInmd. destruct (method_in_by_name i mds').\n    + destruct s as [[[[x' t1'] t2'] e'] Hs]. apply IHmds''; eauto. intros. apply Hsub. apply in_cons. auto.\n    + inject HInmd.\n      * pose proof Hwfct as Hwfct'.\n        inversion Hwfct. subst.\n        assert (Hneq: C <> D).\n        { unfold fresh_class_name in Hfcn. intro Hneg. subst. apply Hfcn in HinC. tauto. }\n        pose proof HinC as HinC'.\n        apply H in HinC. \n        inversion HinC. subst. pose proof Hsub as Hsub'. eapply H6 in Hsub; revgoals.\n        ** apply in_eq.\n        ** inversion Hsub; subst.\n           *** constructor; eauto. repeat ht.\n               **** apply in_or_app. left. apply in_eq.\n               **** simpl. rewrite Nat.eqb_refl. apply in_eq.\n               **** apply in_or_app. right. apply in_eq.\n               **** simpl. rewrite<- Nat.eqb_neq in Hneq. rewrite Hneq.\n                    erewrite<- methods_in; eauto.\n                    { apply Hsub'. apply in_eq. }\n           *** constructor; eauto. repeat ht.\n               **** apply in_or_app. left. apply in_eq.\n               **** simpl. rewrite Nat.eqb_refl. apply in_eq.\n               **** apply in_or_app. right. apply in_eq.\n               **** simpl. rewrite<- Nat.eqb_neq in Hneq. rewrite Hneq.\n                    erewrite<- methods_in; eauto.\n                    { apply Hsub'. apply in_eq. }\n      * apply IHmds''.\n        ** intros. apply Hsub. apply in_cons. apply H0.\n        ** auto.               \nQed.\n \n        \nLemma method_names_correct' : forall m x t1 t2 e mds,\n    In (Method m x t1 t2 e) mds -> In m (method_names mds).\nProof.\n  intros. induction mds.\n  - inject H.\n  - destruct a. simpl. inject H.\n    + inject H0. left. auto.\n    + right. apply IHmds. apply H0.\nQed.\nLemma nodupsmds_appp : forall md1 md2,\n    NoDupsMds md1 -> NoDupsMds md2 ->\n    (forall mn, In mn (method_names md1) -> ~In mn (method_names md2)) ->\n    NoDupsMds (md1 ++ md2).\nProof.\n  intros.\n  induction H.\n  - simpl. constructor.\n    + apply IHNoDupsMds. intros. apply H1. simpl. right. auto.\n    + intros. intro Hneg. apply in_app_or in Hneg. inversion Hneg.\n      * apply H2 in H3. auto.\n      * eapply H1.\n        ** simpl. left. auto.\n        ** rewrite<- plus_n_O. eapply method_names_correct'; eauto.\n  - simpl. constructor.\n    + apply IHNoDupsMds. intros. apply H1. simpl. right. auto.\n    + intros. intro Hneg. apply in_app_or in Hneg. inversion Hneg.\n      * apply H2 in H3. auto.\n      * eapply H1.\n        ** simpl. left. auto.\n        ** rewrite<- plus_n_O. eapply method_names_correct'; eauto.\n  - simpl. auto.\nQed.\n\nLemma passthrough_gets_remainder : forall m x t1 t2 e md1 md2, \n    In (Method m x t1 t2 e) (passthrough_other_mds md1 md2)  ->\n    In m (method_names md1) /\\ ~ In m (method_names md2).\nProof.\n  intros. induction md1.\n  - simpl in H. tauto.\n  - simpl in H. destruct a. simpl in H. destruct (method_in_by_name i md2).\n    + destruct s as [[[[x' t1'] t2'] e'] Hs]. apply IHmd1 in H. inject H.\n      split; eauto. simpl. auto.\n    + inject H.\n      * inject H0. simpl. split; auto. intro H. eapply method_names_correct in H.\n        unfold_existentials H. apply n in H. tauto.\n      * simpl. apply IHmd1 in H0. inject H0. split; eauto.\nQed.\n\nLemma combo_nodups : forall md1 md2,\n    incl (method_names md2) (method_names md1) -> NoDupsMds md1 -> NoDupsMds md2 ->\n    NoDupsMds ((wrap_methods md1 md2) ++ (passthrough_other_mds md1 md2)).\nProof.\n  intros. apply nodupsmds_appp.\n  - apply MWrapMethods_NoDups; eauto.\n  - apply passthrough_nodups; eauto.\n  - intros. intro Hneg. apply method_names_correct in Hneg. unfold_existentials Hneg.\n    apply passthrough_gets_remainder in H4. inject H4.\n    apply method_names_correct in H2. unfold_existentials H2.\n    eapply MWrapMethods_Inclusion' in H2.\n    + unfold_existentials H2. apply method_names_correct' in H2. apply H5 in H2. tauto.\n    + auto.\nQed.\n\nLemma correctness_CWrap : forall k C D E fds fds' mds mds' mds'',\n    In (ClassDef C fds mds) k-> \n    In (ClassDef E fds' mds') k-> \n    incl (method_names mds') (method_names mds) ->\n    WellFormedClassTable k -> fresh_class_name D k -> \n    WellFormedClass (ClassDef D ((Field that (class C))::nil) (mds'') :: k)\n                    (Wrap_classes C mds mds' D).\nProof.\n  intros ? ? ? ? ? ? ? ? ? HinC HinE Hincl Hwfct Hfcn. constructor.\n  - intros. inject H; [|inject H0]. repeat constructor. econstructor. apply in_cons. apply HinC.\n  - intros. apply in_app_or in H. inject H.\n    + eapply correctness_wrap_method.\n      * eauto.\n      * eauto.\n      * apply HinC.\n      * apply HinE.\n      * intros. apply H.\n      * apply H0.\n    + eapply correctness_passthrough.\n      * eauto.\n      * eauto.\n      * eauto.\n      * apply HinE.\n      * intros. apply H.\n      * apply H0.\n  - constructor; eauto. constructor.\n  - inject Hwfct. apply H in HinC. apply H in HinE. inject HinC. inject HinE. apply combo_nodups; eauto.\nQed.\n\nLemma mdsub_app : forall mds mds' mds'' mu k, Md_Subtypes mu k mds mds' -> Md_Subtypes mu k (mds ++ mds'') mds'.\nProof.\n  intros. induction mds'.\n  - constructor.\n  - inject H. econstructor.\n    + apply in_or_app. left. apply H2.\n    + apply H6.\n    + apply IHmds'. apply H7.\nQed.\n      \nLemma subtype_CWrap : forall k C D E fds fds' mds mds',\n    In (ClassDef C fds mds) k-> \n    In (ClassDef E fds' mds') k-> \n    incl (method_names mds') (method_names mds) ->\n    WellFormedClassTable k -> fresh_class_name D k -> \n    Subtype empty_mu (ClassDef D ((Field that (class C))::nil)\n                               ((wrap_methods mds mds') ++ (passthrough_other_mds mds mds')) :: k)\n            (class D) (class E).\nProof.\n  intros. eapply STClass; eauto. simpl. rewrite Nat.eqb_refl.\n  assert (Hneq: E <> D).\n  { intro Hneg. subst. unfold fresh_class_name in H3. apply H3 in H0. tauto. }\n  apply Nat.eqb_neq in Hneq. rewrite Hneq. apply mdsub_app.\n  erewrite<- methods_in.\n  + apply wrap_methods_is_subtype; auto.\n  + auto.\n  + apply H0.\nQed.\n\n\n(*Lemmas for CT extensions ENDS*)\n\n\n  \nInductive FieldRefWellFormed : ct -> heap -> list fd -> list ref -> Prop :=\n| FRWF_Cons : forall k s f t fds a a', HasType nil s k (Ref a) t ->\n                                       FieldRefWellFormed k s fds a' ->\n                                       FieldRefWellFormed k s ((Field f t)::fds) (a::a')\n| FRWF_Nil : forall k s, FieldRefWellFormed k s nil nil.\n\nInductive NoDupsHeap : heap -> Prop :=\n| NDH_Cons : forall s a hc', (forall hc, ~(In(a,hc) s)) -> NoDupsHeap s -> NoDupsHeap ((a,hc')::s)\n| NDH_Nil : NoDupsHeap nil.\n\nInductive WellFormedHeap : ct -> heap -> Prop :=\n| WFH : forall k s, NoDupsHeap s ->\n                    (forall a C aps, In (a,HCell(C, aps)) s -> WellFormedType k (class C) /\\ FieldRefWellFormed k s (fields C k) aps) ->\n                    WellFormedHeap k s.\n\n(*Lemmas for CT extensions*)\nLemma ct_exten_wfheap : forall s k k',\n        WellFormedHeap k s /\\ ct_ext k k' -> WellFormedHeap k' s.\nProof.\nAbort.\n\n(*Lemmas for CT extensions ENDS*)\n\n\nInductive WellFormedState : ct -> expr -> heap -> Prop :=\n| WFSWP : forall k e s t, HasType nil s k e t -> WellFormedHeap k s ->\n          WellFormedClassTable k ->\n          WellFormedState k e s.\n\n(* all exprs are refs in a list *)\nInductive Deref : list expr -> list ref -> Prop :=\n| DREF_Cons : forall a es ais, Deref es ais -> Deref ((Ref a)::es) (a::ais)\n| DREF_Nil : Deref nil nil.\n\nInductive FieldIn : id -> type -> ref -> list fd -> list ref -> Prop :=\n| FieldIn_Next : forall f f' a a' fdr t t' ar,\n    f <> f' -> FieldIn f t a fdr ar -> FieldIn f t a ((Field f' t') :: fdr) (a' :: ar)\n| FieldIn_Here : forall f a t fdr ar, FieldIn f t a ((Field f t) :: fdr) (a :: ar).\n\nLemma FieldsWFImpliesFieldIn : forall k s fds aps f t a,\n  FieldRefWellFormed k s fds aps -> FieldIn f t a fds aps -> HasType nil s k (Ref a) t.\nProof.\n  intros k s fds aps f t a H1 H2. induction H1.\n  - destruct (Nat.eqb f f0) eqn:Hf.\n    + apply Nat.eqb_eq in Hf. subst. inversion H2; subst;\n      try tauto; apply H.\n    + apply Nat.eqb_neq in Hf. inversion H2; subst; try tauto.\n      (*apply IHFieldRefWellFormed in H11. apply H11. assumption.*)\n  - inversion H2.\nQed.\n\nLemma strong_weakening_of_type_wf : forall C C' fds mds k,\n    WellFormedType ((ClassDef C' fds mds) :: k) (class C) -> C <> C' ->\n    WellFormedType k (class C).\nProof.\n  intros C C' fds mds k H1 H2. inversion H1; subst. inversion H3.\n  - inversion H. symmetry in H4. contradiction.\n  - eapply WFWTC. apply H.\nQed.\n\nLemma fields_gets_fields : forall C k fds, \n    WellFormedType k (class C) -> WellFormedClassTable k ->\n    fields C k = fds <-> exists mds, In (ClassDef C fds mds) k.\nProof.\n  intros C k fds H H0. destruct H0 as [k _ Hdups]. split; intros H1. \n  - induction k as [n | k''].\n    + inversion H. subst. inversion H3.\n    + destruct k'' as [C' fds' mds']. simpl in H1. destruct (Nat.eqb C C') eqn:HCC.\n      * apply Nat.eqb_eq in HCC. subst. exists mds'. simpl. auto. \n      * apply Nat.eqb_neq in HCC. simpl. inversion H. subst. apply strong_weakening_of_type_wf in H; eauto. \n        apply IHk in H; eauto.\n        ** inversion H as [mds'' H5]. exists mds''. auto.\n        ** inversion Hdups. apply H2. \n  - induction k as [|k''].\n    + inversion H1. inversion H0. \n    + destruct k'' as [C' fds' mds']. unfold fields. destruct (C =? C') eqn:HCC.\n      * apply Nat.eqb_eq in HCC. subst. inversion H1. inversion H0.\n        ** subst. inversion H2.\n           *** inversion H2. subst. reflexivity.\n        ** inversion Hdups. subst. apply H8 in H2. tauto.\n      * apply IHk.\n        ** eapply strong_weakening_of_type_wf; eauto. apply Nat.eqb_neq in HCC. apply HCC.\n        ** inversion Hdups. tauto. \n        ** inversion H1. inversion H0.\n           *** inversion H2. apply Nat.eqb_neq in HCC. symmetry in H5. subst. contradiction.\n           *** exists x. eauto. \nQed.\n\nLemma heap_wf_field_access : forall k s a C aps f t a',\n    WellFormedHeap k s ->\n    WellFormedClassTable k ->\n    In (a, HCell(C, aps)) s -> FieldIn f t a' (fields C k) aps ->\n  HasType nil s k (Ref a') t.\nProof.\n  intros k s a C aps f t a' H0 H1 H2 H3. inversion H0. subst. apply H4 in H2. destruct H2 as [_ H2]. induction H2. \n  - destruct (Nat.eqb a0 a') eqn:Heq.\n    + apply Nat.eqb_eq in Heq. subst. inversion H3.\n      * subst. apply IHFieldRefWellFormed; eauto.\n      * subst. apply H2.\n    + apply Nat.eqb_neq in Heq. inversion H3.\n      * subst. apply IHFieldRefWellFormed; eauto.\n      * subst. tauto.\n  - inversion H3. \nQed.\n\nInductive HeapWrite : id -> list ref -> heap -> heap -> Prop :=\n| HWC : forall a aps C aps' s, HeapWrite a aps ((a,HCell(C,aps'))::s) ((a,HCell(C,aps)) :: s)\n| HWNC : forall a a' aps aps' s s' C, a' <> a -> HeapWrite a aps s s' ->\n         HeapWrite a aps ((a', HCell(C,aps')) :: s) ((a', (HCell(C,aps'))) :: s').\n\nInductive FieldWrite : id -> ref -> list ref -> list fd -> list ref -> Prop :=\n| FWC : forall a f a' aps fs t, FieldWrite f a (a'::aps) ((Field f t)::fs) (a::aps)\n| FWN : forall a f f' a' aps aps' fs t,\n    f <> f' -> FieldWrite f a aps fs aps' -> FieldWrite f a (a'::aps) ((Field f' t)::fs) (a' :: aps').\n\nLemma FieldsNoDupsFds : forall (k k' : ct) (C : id) fds mds, \n    WellFormedClassTable k ->\n    In (ClassDef C fds mds) k ->\n    fds = (fields C k) ->\n    NoDupsFds fds.\nProof.\n  intros k k' C fds mds H H0 H1. inversion H.\n  apply H2 in H0. inversion H0. subst. apply H11.\nQed.\n\nLemma FieldWriteWellFormed : forall (k k' : ct) s a fds ais ais' t f,\n    FieldRefWellFormed k s fds ais ->\n    HasType nil s k (Ref a) t ->\n    In (Field f t) fds ->\n    NoDupsFds fds ->\n    FieldWrite f a ais fds ais' ->\n    FieldRefWellFormed k s fds ais'.\nProof.\n  intros. induction H3.\n  - inversion H1.\n    + inversion H3. subst. apply FRWF_Cons; eauto.\n      * inversion H. apply H12. \n    + inversion H2. subst. unfold not in H8. apply H8 in H3. contradiction.\n  - apply FRWF_Cons.\n    + inversion H. apply H9.\n    + apply IHFieldWrite; eauto.\n      * inversion H. apply H13.\n      * inversion H1. \n        ** inversion H5. symmetry in H7. contradiction.\n        ** apply H5.\n      * inversion H2. apply H7.\nQed.\n\nLemma no_two_classes : forall k C fds mds fds' mds',\n    WellFormedClassTable k -> In (ClassDef C fds mds) k -> In (ClassDef C fds' mds') k ->\n    fds = fds' /\\ mds = mds'.\nProof.\n  intros. inversion H. subst. clear H2. clear H. induction k0.\n  - inversion H0.\n  - inversion H0; inversion H1.\n    + subst. inversion H2. eauto.\n    + subst. inversion H3. subst. apply H8 in H2. tauto.\n    + inversion H3. subst. inversion H4. subst. apply H7 in H. tauto.\n    + apply IHk0; eauto. inversion H3. apply H6.\nQed.\n\nLemma heap_write_still_in : forall a s s' a' aps' hc,\n  In (a, hc) s -> a <> a' -> HeapWrite a' aps' s s' -> In (a, hc) s'.\nProof.\n  intros. induction H1.\n  - inversion H.\n    + inversion H1. subst. tauto. \n    + apply in_cons. apply H1. \n  - inversion H.\n    + inversion H3. subst. apply in_eq. \n    + apply IHHeapWrite in H3.\n      * apply in_cons. apply H3.\n      * apply H0.\nQed.\n\nLemma nodupsheap_weakening : forall a hc s, NoDupsHeap ((a, hc)::s) -> NoDupsHeap s.\nProof.\n  intros. inversion H. subst. apply H4.\nQed.\n\nLemma heap_write_now_in : forall a k s s' aps aps' C,\n    WellFormedHeap k s -> In (a, HCell(C, aps)) s -> HeapWrite a aps' s s' -> In (a, HCell(C, aps')) s'.\nProof.\n  intros. inversion H. subst. clear H3. clear H. induction H1.\n  - destruct (Nat.eqb C C0) eqn:HCC.\n    + apply Nat.eqb_eq in HCC. subst. apply in_eq.\n    + apply Nat.eqb_neq in HCC. inversion H0.\n      * inversion H. subst. tauto. \n      * inversion H2. subst. apply H4 in H. contradiction.\n  - apply in_cons. apply IHHeapWrite.\n    + inversion H0; eauto. inversion H3. subst. tauto.\n    + apply nodupsheap_weakening in H2. apply H2.\nQed.\n\nLemma heap_weakening_2 : forall g s s' k e t, HasType g s k e t -> HasType g (s' ++ s) k e t.\nProof.\n  intros g s s' k e t H.\n  apply typing_ind with (P := fun g s k e t ih => HasType g (s' ++ s) k e t)\n                          (P0 := fun g s k e t ih => HasTypeExpr g (s' ++ s) k e t)\n                          (P1 := fun g s k es ts ih => HasTypes g (s' ++ s) k es ts); eauto.\n  - intros. apply KTREFREAD with (a' := a') (C:=C).\n    + apply in_or_app. right. eauto.\n    + apply i0.\n  - intros. apply KTREFWRITE with (a' := a') (C:=C); eauto.\n    + apply in_or_app. eauto.\n  - intros. apply KTREFTYPE with (a' := a') (C := C); eauto.\n    apply in_or_app. eauto.\n  - intros. eapply KTREFANY. apply in_or_app. eauto.\nQed.\n\nLemma subtype_only_classes : forall mu k C t, Subtype mu k (class C) t -> exists D, t = (class D).\nProof.\n  intros. inversion H.\n  - exists C. reflexivity. \n  - subst. exists t2. reflexivity.\n  - subst. exists d. reflexivity.\nQed.\n\n\nDefinition retains_references(s1:heap)(s2:heap) :=\n  forall a C aps, In (a, HCell(C,aps)) s1 -> exists aps', In(a, HCell(C,aps')) s2.\n\nLemma heapwrite_retains_refs' : forall a aps' s s',\n    HeapWrite a aps' s s' -> retains_references s s'.\nProof.\n  intros. induction H.\n  - unfold retains_references. intros. destruct (Nat.eq_dec C0 C); destruct (Nat.eq_dec a0 a).\n    + subst. exists aps. apply in_eq.\n    + subst. inversion H.\n      * exists aps. inject H0. tauto.\n      * exists aps0. apply in_cons. tauto.\n    + subst. inversion H.\n      * inject H0. exists aps. tauto.\n      * exists aps0. apply in_cons. tauto.\n    + inversion H.\n      * inject H0. tauto.\n      * exists aps0. apply in_cons. tauto.\n  - unfold retains_references. intros. inversion H1.\n    + inject H2. exists aps0. apply in_eq.\n    + unfold retains_references in IHHeapWrite.\n      apply IHHeapWrite in H2. destruct H2. exists x. apply in_cons. apply H2. \nQed.\n\nLemma retain_references_ref : forall s, retains_references s s.\nProof.\n  intros. unfold retains_references; intros. exists aps. apply H.\nQed.\nHint Resolve retain_references_ref.\n\n\nLemma hastype_ignores_heapv'' : forall s s' k g e t,\n    HasType g s k e t -> retains_references s s' -> HasType g s' k e t.\nProof.\n  intros. \n  pose proof (eq_refl k0) as Hduh1.\n  pose proof (eq_refl s) as Hduh2.\n  generalize dependent Hduh1. generalize dependent Hduh2.\n  apply typing_ind with\n  (P:= fun g s'' k' e t ih => s'' = s -> k' = k0 -> HasType g s' k0 e t)\n    (P0 := fun g s'' k' e t ih => s'' = s -> k' = k0 -> HasTypeExpr g s' k0 e t)\n    (P1 := fun g s'' k' es ts ih => s'' = s -> k' = k0 -> HasTypes g s' k0 es ts);\n    try (intros; subst; eauto; fail). \n  - intros. subst. unfold retains_references in H0. apply H0 in i. destruct i as [aps' H1]. eapply KTREFREAD; eauto.\n  - intros. subst. unfold retains_references in H0. apply H0 in i. destruct i as [aps' H2]. eauto.\n  - intros. subst. unfold retains_references in H0. apply H0 in i. destruct i as [aps' H1]. eauto.\n  - intros. subst. unfold retains_references in H0. destruct hc.  destruct p.\n    apply H0 in i. destruct i as [aps' H1]. eauto.\nQed.\nHint Resolve hastype_ignores_heapv''.\n\n   \nLemma hastype_ignores_heapv : forall (k:ct) (s s':heap) g a a' aps' t,\n    HasType g s k (Ref a) t ->\n    HeapWrite a' aps' s s' -> \n    HasType g s' k (Ref a) t.\nProof.\n  intros. eapply hastype_ignores_heapv''.  eauto. eapply heapwrite_retains_refs'; eauto.\nQed.\nHint Resolve hastype_ignores_heapv.\n\nLemma fieldwf_still_good : forall k s a' s' fds aps' aps, \n  WellFormedHeap k s ->\n  FieldRefWellFormed k s fds aps' ->\n  HeapWrite a' aps s s' ->\n  FieldRefWellFormed k s' fds aps'.\nProof.\n  intros k s a s' fds aps' aps.\n  intros Hwfh Hfrwf Hwrite.  \n  induction Hfrwf.\n  - apply FRWF_Cons.\n    + eapply hastype_ignores_heapv; eauto.\n    + apply IHHfrwf; eauto.\n  - apply FRWF_Nil.\nQed.\n\nLemma writing_keeps_refs : forall a a' s s' aps' C aps,\n    In(a,HCell(C,aps)) s -> HeapWrite a' aps' s s' -> exists aps', In(a,HCell(C, aps')) s'.\nProof.\n  intros. induction H0.\n  - inversion H.\n    + inversion H0. subst. exists aps0. apply in_eq.\n    + exists aps. apply in_cons. apply H0.\n  - inversion H.\n    + inversion H2. subst. exists aps. apply in_eq.\n    + apply IHHeapWrite in H2. inversion H2 as [hc' H3]. exists hc'.\n      apply in_cons. apply H3.\nQed.\n\nLemma refs_still_not_in : forall a s a' aps' s',\n  (forall hc, ~ (In(a,hc) s)) -> HeapWrite a' aps' s s' -> (forall hc', ~(In(a,hc') s')).\nProof.\n  intros. destruct (Nat.eqb a a') eqn:Heq.\n  + apply Nat.eqb_eq in Heq. subst. induction H0.\n    * subst. exfalso. unfold not in H. eapply H.\n      apply in_eq.\n    * subst. unfold not. intros. inversion H2.\n      ** inversion H3. subst. eapply H. apply in_eq.\n      ** apply IHHeapWrite in H3; eauto. unfold not.\n         intros. unfold not in H. eapply H. apply in_cons. apply H4.\n  + apply Nat.eqb_neq in Heq. induction H0.\n    * unfold not. intros. eapply H. inversion H0.\n      ** inversion H1. subst. tauto. \n      ** apply in_cons. apply H1.\n    * unfold not. intros. inversion H2.\n      ** inversion H3. subst. eapply H. apply in_eq.\n      ** apply IHHeapWrite.\n         *** unfold not. intros. eapply H. apply in_cons. apply H4.\n         *** apply Heq.\n         *** apply H3.\nQed.\n\nLemma in_goes_backwards : forall a a' aps' s s' hc,\n    (In(a,hc) s') -> HeapWrite a' aps' s s' -> a <> a' -> In(a,hc) s.\nProof.\n  intros. induction H0.\n  - destruct (Nat.eqb a a0) eqn:Heq.\n    + apply Nat.eqb_eq in Heq. subst. tauto.\n    + apply Nat.eqb_neq in Heq. inversion H; eauto.\n      * inversion H0. subst. tauto.\n      * apply in_cons. apply H0.\n  - inversion H; eauto.\n    + inversion H3. subst. apply in_eq.\n    + apply in_cons. apply IHHeapWrite; eauto.\nQed.\n\nTheorem nodupsheap_still_good: forall s a' aps' s',\n  NoDupsHeap s -> HeapWrite a' aps' s s' -> NoDupsHeap s'.\nProof.\n  intros. generalize dependent s'.\n  induction H.\n  - intros. destruct (Nat.eqb a' a) eqn:Heq.\n    + apply Nat.eqb_eq in Heq. subst. inversion H1.\n      * subst. apply NDH_Cons; eauto.\n      * subst. apply IHNoDupsHeap in H9. apply NDH_Cons; eauto.\n    + apply Nat.eqb_neq in Heq. inversion H1.\n      * subst. tauto.\n      * subst. apply IHNoDupsHeap in H9. apply NDH_Cons; eauto.\n        inversion H1; subst; try tauto. eapply refs_still_not_in; eauto.\n  - intros. inversion H0.\nQed.\n\nLemma nodups_first : forall a hc s, NoDupsHeap ((a,hc)::s) -> (forall hc', In (a,hc') ((a,hc)::s) -> hc = hc').\nProof.\n  intros. inversion H. subst. inversion H0.\n  - inversion H1. tauto.\n  - apply H3 in H1. tauto.\nQed.\n\nLemma nodups_collapses_refs : forall s a hc hc',\n    NoDupsHeap s -> In (a,hc) s -> In (a,hc') s -> hc = hc'.\nProof.\n  intros.\n  induction (H).\n  - pose proof (Nat.eq_dec a a0). destruct H3; subst.\n    + pose proof (nodups_first a0 hc'0 s H).\n      apply H3 in H0. apply H3 in H1. subst. tauto.\n    + inversion H0 as [H3|]; inversion H1 as [H4|]; try (inversion H3; inversion H4; subst).\n      * tauto.\n      * inversion H3. subst. tauto.\n      * inversion H4. subst. tauto.\n      * apply IHn; eauto.\n  - inversion H0.\nQed.\n\nLemma fieldwf_implies_heapwf : forall k s s' a' C aps aps' fds,\n  WellFormedHeap k s ->\n  In (a', HCell(C,aps)) s ->\n  fds = fields C k ->\n  FieldRefWellFormed k s fds aps' ->\n  HeapWrite a' aps' s s' ->\n  WellFormedHeap k s'.\nProof.\n  intros k s s' a C aps aps' fds.\n  intros Hwfh Hin Hfields Hfieldswf Hwrite. inversion Hwfh. subst.\n  apply WFH.\n  - eapply nodupsheap_still_good; eauto.\n  - intros. destruct (Nat.eqb a0 a) eqn:Heq.\n    + apply Nat.eqb_eq in Heq. subst. pose proof (heap_write_now_in _ _ _ _ _ _ _ Hwfh Hin Hwrite).\n      assert (Hnds' : NoDupsHeap s').\n      { eapply nodupsheap_still_good; eauto. }\n      pose proof (nodups_collapses_refs s' a (HCell (C0, aps0)) (HCell (C, aps')) Hnds' H1 H2). inversion H3. subst. \n      split.\n      { apply H0 in Hin. destruct Hin. eauto. }\n      {\n        eapply fieldwf_still_good.\n        * apply Hwfh.\n        * inversion H3. subst. apply Hfieldswf.\n        * apply Hwrite.\n      }\n    + apply Nat.eqb_neq in Heq. eapply in_goes_backwards in H1; eauto. split.\n      {\n        apply H0 in H1. destruct H1. eauto.\n      }\n      {\n        eapply fieldwf_still_good.\n        * apply Hwfh.\n        * eapply H0. eauto.\n        * apply Hwrite.\n      }\nQed.\n\nLemma write_field : forall s s' k a a' aps aps' t C f,\n    WellFormedHeap k s ->\n    WellFormedClassTable k ->\n    HasType nil s k (Ref a) t ->\n    In (Field f t) (fields C k) ->\n    In (a', HCell(C, aps)) s ->\n    FieldWrite f a aps (fields C k) aps' ->\n    HeapWrite a' aps' s s' ->\n    WellFormedHeap k s'.\nProof.\n  intros s s' k a a' aps aps' t C f.\n  intros Hwfh Hwfct Hht Hfin Hobj Hwrite Hhwrite.\n\n  inversion Hwfh.\n  subst. pose proof Hobj. apply H0 in H1. destruct H1. remember (fields C k) as fds.\n  pose proof (fields_gets_fields C k fds H1 Hwfct). symmetry in Heqfds. pose proof Heqfds.\n  apply H3 in Heqfds.\n  destruct Heqfds as [mds H5]. \n    \n  eapply fieldwf_implies_heapwf; eauto. eapply FieldWriteWellFormed; eauto.\n  - inversion Hwfh. subst. eapply H0. apply Hobj.\n  - rewrite-> H4. apply Hfin.\n  - eapply FieldsNoDupsFds; eauto. subst. apply H5.\n  - subst. apply Hwrite.\nQed.\n\nInductive EvalCtx :=\n| EAssign : ref -> id -> EvalCtx -> EvalCtx\n| ECall1 : EvalCtx -> id -> type -> type -> expr -> EvalCtx\n| ECall2 : ref -> id -> type -> type -> EvalCtx -> EvalCtx\n| EDCall1 : EvalCtx -> id -> expr -> EvalCtx\n| EDCall2 : ref -> id -> EvalCtx -> EvalCtx\n| ESubCast : type -> EvalCtx -> EvalCtx\n| EBehCast : type -> EvalCtx -> EvalCtx\n| ENew : id -> list ref -> EvalCtx -> list expr -> EvalCtx\n| EHole : EvalCtx.\n\nFixpoint equivExpr(ei:expr)(E:EvalCtx) :=\n  match E with\n  | EAssign a f E => SetF (Ref a) f (equivExpr ei E)\n  | ECall1 E m t t' e => Call (equivExpr ei E) m t t' e\n  | ECall2 a m t t' E => Call (Ref a) m t t' (equivExpr ei E)\n  | EDCall1 E m e => DynCall (equivExpr ei E) m e\n  | EDCall2 a m E => DynCall (Ref a) m (equivExpr ei E)\n  | ESubCast t E => SubCast t (equivExpr ei E)\n  | EBehCast t E => BehCast t (equivExpr ei E)\n  | ENew C aps E ers => New C ((map Ref aps) ++ (equivExpr ei E)::ers)\n  | EHole => ei\n  end.\n\nFixpoint fresh_ref (s:heap)(i:nat) :=\n  match s with\n  | (a,hc)::r => match Nat.ltb a i with\n                 | true => fresh_ref r i\n                 | false => fresh_ref r (S a)\n                 end\n  | nil => i\n  end.\n\nFixpoint fresh_class (k:ct)(i:nat) :=\n  match k with\n  | (ClassDef C fds mds)::r => match Nat.ltb C i with\n                 | true => fresh_class r i\n                 | false => fresh_class r (S C)\n                 end\n  | nil => i\n  end.\n\nRequire Import Coq.omega.Omega.\n\nTheorem fresh_not_in :\n  forall s a a', a = fresh_ref s a' -> a' <= a /\\ forall a'' hc, In(a'',hc) s -> a'' < a.\nProof.\n  intros. generalize dependent a'. induction s.\n  - intros. split.\n    + unfold fresh_ref in H. omega.\n    + intros. inversion H0.\n  - intros.\n    destruct a0 as [a'' hc]. unfold fresh_ref in H.\n    destruct (Nat.ltb a'' a') eqn:Haa.\n    + apply Nat.ltb_lt in Haa. apply IHs in H. destruct H. split.\n      * omega.\n      * intros. inversion H1.\n        ** inject H2. omega.\n        ** apply H0 in H2. omega.\n    + apply Nat.ltb_ge in Haa. apply IHs in H. destruct H. split.\n      * omega.\n      * intros. inversion H1.\n        ** inject H2. omega.\n        ** apply H0 in H2.  omega.\nQed.\n\nTheorem fresh_class_not_in :\n  forall k C D, D = fresh_class k C -> C <= D /\\ forall C' fds mds, In (ClassDef C' fds mds) k -> C' < D.\nProof.\n  intros. generalize dependent C. induction k0.\n  - intros. split.\n    + unfold fresh_class in H. omega.\n    + intros. inversion H0.\n  - intros.\n    destruct a as [D' fds mds]. unfold fresh_class in H.\n    destruct (Nat.ltb D' C) eqn:Haa.\n    + apply Nat.ltb_lt in Haa. apply IHk0 in H. destruct H. split.\n      * omega.\n      * intros. inversion H1.\n        ** inject H2. omega.\n        ** apply H0 in H2. omega.\n    + apply Nat.ltb_ge in Haa. apply IHk0 in H. destruct H. split.\n      * omega.\n      * intros. inversion H1.\n        ** inject H2. omega.\n        ** apply H0 in H2.  omega.\nQed.\n\nImport Syntax Coq.Lists.List.\n\nInductive Steps : ct -> expr -> heap -> ct -> expr -> heap -> Prop :=\n| SNew : forall a' s s' C k ais ais', (forall hc, ~ (In (a',hc) s)) ->\n                                      Deref ais ais' ->\n                                      s' = (a', HCell(C, ais'))::s ->\n                                      Steps k (New C ais) s k (Ref a') s'\n| SRead : forall a C t aps s k f a', \n    In (a, HCell(C, aps)) s ->\n    FieldIn f t a' (fields C k) aps ->\n    Steps k (GetF (Ref a) f) s k (Ref a') s\n| SWrite : forall a C aps aps' s k f a' s',\n    In (a, HCell(C,aps)) s ->\n    FieldWrite f a' aps (fields C k) aps' ->\n    HeapWrite a aps' s s' ->\n    Steps k (SetF (Ref a) f (Ref a')) s k (Ref a') s'\n| SCall : forall a C aps s m x t1 t1' t2 t2' e k a',\n    In (a, HCell(C,aps)) s ->\n    In (Method m x t1 t2 e) (methods C k) ->\n    Subtype empty_mu k t1' t1 ->\n    Subtype empty_mu k t2 t2' ->\n    Steps k (Call (Ref a) m t1' t2' (Ref a')) s k (subst a a' x e) s\n| SDynCall : forall a C aps s m x e k a',\n    In (a, HCell(C,aps)) s ->\n    In (Method m x Any Any e) (methods C k) ->\n    Steps k (DynCall (Ref a) m (Ref a')) s k (subst a a' x e) s\n| SDynCast : forall k a s, Steps k (SubCast Any (Ref a)) s k (Ref a) s\n| SSubCast : forall a aps C D s k,\n    In (a, HCell(C,aps)) s ->\n    Subtype empty_mu k (class C) (class D) ->\n    Steps k (SubCast (class D) (Ref a)) s k (Ref a) s\n| SBehCastAny : forall a s (k:ct) ap C E (D:id) mds a' s' k' a'',\n    In (a, HCell(C,ap)) s ->\n    E = fresh_class k D ->\n    C <> E ->\n    a'' = fresh_ref s a' ->\n    mds = (methods C k) ->\n    NoDupsMds mds ->\n    s' = (a'', HCell(E,  a::nil))::s ->\n    k' = (WrapAny_classes C mds E)::k ->\n    Steps k (BehCast Any (Ref a)) s k' (Ref a'') s'\n| SBehCast : forall a s k ap C E D mds mds' C' a' s' k' a'',\n    In (a, HCell(C,ap)) s ->\n    E = fresh_class k D ->\n    C <> E ->\n    a'' = fresh_ref s a' ->\n    mds = (methods C k) ->\n    mds' = (methods C' k) ->\n    incl (method_names mds') (method_names mds) ->\n    NoDupsMds mds' ->\n    s' = (a'', HCell(E,  a::nil))::s ->\n    k' = (Wrap_classes C mds mds' E) :: k ->\n    Steps k (BehCast (class C') (Ref a)) s k' (Ref a'') s'\n| SCtx : forall k k' e s e' s' E,\n    Steps k e s k' e' s' -> Steps k (equivExpr e E) s k' (equivExpr e' E) s'.\nHint Constructors Steps.\nHint Constructors EvalCtx.\n\nFixpoint typesof(fds : list fd) : list type :=\n  match fds with\n    (Field f t) :: r => t :: (typesof r)\n  | nil => nil\n  end.\n\nHint Constructors WellFormedState.\n\n\nLemma infields_implies_fieldin : forall k f s t a C aps,\n    WellFormedHeap k s ->\n    WellFormedClassTable k ->\n    In (a, HCell(C,aps)) s -> \n    In (Field f t) (fields C k) -> exists a', FieldIn f t a' (fields C k) aps.\nProof.\n  intros. destruct H. apply H3 in H1. clear H3. destruct H1. remember (fields C k0) as fds.\n  pose proof (fields_gets_fields C k0 fds H1 H0). destruct H4. clear H5. symmetry in Heqfds.\n  pose proof Heqfds as Heqfds'. apply H4 in Heqfds. destruct Heqfds as [mds Hin]. clear H4. symmetry in Heqfds'.\n  pose proof (FieldsNoDupsFds k0 k0 C fds mds H0 Hin Heqfds').\n  clear Heqfds'. clear Hin H0 H1. clear mds H.\n  induction H3.\n  - destruct (Nat.eq_dec f f0); subst.\n    + inject H2.\n      * inject H0. exists a0. apply FieldIn_Here.\n      * inject H4. apply H7 in H0. tauto.\n    + inject H2.\n      * inject H0. tauto.\n      * inject H4. destruct (IHFieldRefWellFormed H0 H5) as [a0' H8].\n        exists a0'. apply FieldIn_Next; eauto.\n  - inversion H2.\nQed.\n\nFixpoint update_field_ref(f:id)(a:ref)(fds:list fd)(aps:list ref) : list ref :=\n  match fds, aps with\n    (Field f' t)::fr, a'::ar => match Nat.eqb f f' with\n                                    true => a :: ar\n                                  | false => a' :: (update_field_ref f a fr ar)\n                                  end\n  | _, _ => nil\n  end.\n\nLemma update_field_is_well_formed : forall f t a k s aps aps' fds,\n    FieldRefWellFormed k s fds aps ->\n    (In (Field f t) fds) ->\n    update_field_ref f a fds aps = aps' ->\n    FieldWrite f a aps fds aps'.\nProof.\n  intros. subst. induction H.\n  - unfold update_field_ref. destruct (f =? f0) eqn:Hff.\n    + apply Nat.eqb_eq in Hff. subst. apply FWC.\n    + apply FWN.\n      * apply Nat.eqb_neq. eauto.\n      * apply IHFieldRefWellFormed; eauto. inversion H0; eauto. inject H2. apply Nat.eqb_neq in Hff.\n        tauto.\n  - inversion H0.\nQed.\n\nFixpoint update_heap(a:ref)(aps:list ref)(s:heap) : heap :=\n  match s with\n  | (a',HCell(C,aps'))::ar => match Nat.eqb a a' with\n                                true => (a,HCell(C,aps))::ar\n                              | false => (a',HCell(C,aps'))::(update_heap a aps ar)\n                              end\n  | nil => nil\n  end.\nLemma update_heap_writes : forall s a C aps aps',\n  (In (a,HCell(C, aps')) s) ->\n  HeapWrite a aps s (update_heap a aps s).\nProof.\n  intros. induction s.\n  - inversion H.\n  - unfold update_heap. destruct a0 as [a' [(C', aps'')]]. destruct (a =? a') eqn:Heq.\n    + apply Nat.eqb_eq in Heq. subst. apply HWC.\n    + apply Nat.eqb_neq in Heq. apply HWNC; eauto. apply IHs. inject H; eauto. inject H0. tauto.\nQed.\n\nLemma hastype_ignores_heapv' : forall (k : ct) (s s' : heap) (g : env)\n                                      (a' : id) (aps' : list ref) (t : type) e,\n    HasType g s k e t ->\n    HeapWrite a' aps' s s' -> HasType g s' k e t.\nProof.\n  intros. eapply hastype_ignores_heapv''. eauto. eapply heapwrite_retains_refs'. eauto.\nQed.\n\nLemma methods_are_wf : forall k C mds,\n    WellFormedClassTable k ->\n    WellFormedType k (class C) ->\n  mds = (methods C k) ->\n  (forall md, In md mds -> WellFormedMethod ((this, class C) :: nil) k md).\nProof.\n  intros. inversion H0. subst.\n  pose proof (methods_in fds mds0 C k0 H H5). rewrite <- H1 in H2. \n  inversion H. subst. \n  apply H3 in H5. clear H3 H4. inversion H5.\n  subst. eauto.  \nQed.\n\nLemma subtype_only_classes' : forall mu k t C,\n    Subtype mu k t (class C) -> exists D, t = (class D).\nProof.\n  intros. inversion H.\n  - subst. exists C. reflexivity.\n  - subst. exists t1. reflexivity.\n  - eauto.\nQed.\n\nLemma deref_map : forall e1s a1s, \n    Deref e1s a1s -> e1s = map Ref a1s.\nProof.\n  intros. induction H.\n  - simpl. subst. reflexivity.\n  - reflexivity.\nQed.\n\nTheorem weakening_retains_refs: forall s s', retains_references s (s' ++ s).\nProof.\n  intros. induction s.\n  - unfold retains_references. intros. inversion H.\n  - unfold retains_references. intros. inversion H.\n    + exists aps. subst. apply in_or_app. right. apply in_eq.\n    + exists aps. apply in_or_app. right. apply H.\nQed.\n\n\nLemma HasTypes_split : forall g s k e1 e2 fs1 fs2, \n  HasTypes g s k e1 fs1 ->\n  HasTypes g s k e2 fs2 ->\n  HasTypes g s k (e1 ++ e2) (fs1 ++ fs2).\nProof.\n  intros. generalize dependent fs1. induction e1.\n  - simpl. intros. inject H. rewrite app_nil_l. eauto.\n  - simpl. intros. inject H. apply IHe1 in H8. eapply HTSCONS.\n    + apply H6.\n    + apply H8. \nQed.\n      \nLemma frwf_weakening : forall k s fts aps s',\n    FieldRefWellFormed k s fts aps -> FieldRefWellFormed k (s' ++ s) fts aps.\nProof.\n  intros. induction H.\n  - apply FRWF_Cons.\n    + apply heap_weakening_2. apply H.\n    + apply IHFieldRefWellFormed. \n  - apply FRWF_Nil.\nQed.\n\nLemma typesof_cons : forall fds t1 ts, \n    typesof fds = t1::ts -> exists f fds', fds = (Field f t1)::fds'.\nProof.\n  intros. generalize dependent ts. induction fds.\n  - intros. inversion H.\n  - intros. destruct a. exists i. exists fds. simpl in H. inject H. reflexivity.\nQed.\n\nLemma hastypes_split : forall s k e1s a1s t1s,\n  FieldRefWellFormed k s t1s a1s -> \n  Deref e1s a1s ->\n  HasTypes nil s k e1s t1s.\nProof.\n  intros. generalize dependent a1s. generalize dependent t1s. induction e1s.\n  - intros. inject H0. inject H. apply HTSNIL.\n  - intros. inject H0. inject H. apply HTSCONS.\n    + apply H6.\n    + eapply IHe1s; eauto.\nQed.\n\nLemma hastypes_app : forall s k e1s e2s fd1s fd2s,\n    HasTypes nil s k (e1s ++ e2s) (fd1s ++ fd2s) -> \n    HasTypes nil s k e1s fd1s ->\n    HasTypes nil s k e2s fd2s.\nProof.\n  intros. induction H0.\n  - apply IHHasTypes. simpl in H. inversion H. subst. auto.\n  - simpl in H. apply H.\nQed. \n\nLemma fieldwf_still_good' : forall k fds aps s s', \n  FieldRefWellFormed k s fds aps ->\n  retains_references s s' ->\n  FieldRefWellFormed k s' fds aps.\nProof.\n  intros. induction H.\n  - apply FRWF_Cons; eauto. \n  - apply FRWF_Nil.\nQed.\n\nLemma cons_app_app_app : forall V x1 x y,\n    x1 ++ x::y = @app V (x1 ++ (x::nil)) y.\nProof.\n  intros. induction x1.\n  - simpl. reflexivity.\n  - simpl. rewrite IHx1. reflexivity.\nQed.\n\nLemma hastypes_ignores_heapv : forall g s k es fts s',\n    HasTypes g s k es fts -> retains_references s s' -> HasTypes g s' k es fts.\nProof. \n  intros. induction H.\n  - apply HTSCONS.\n    + eauto.\n    + apply IHHasTypes; eauto.\n  - apply HTSNIL.\nQed.\n\nLemma app_cons_assoc: forall T a b c d,\n    @cons T a b ++ @cons T c d = a::(b ++ c::d).\nProof.\n  intros. simpl. reflexivity.\nQed.\n\nLemma frwf_deref_implies_eq_length : forall k s t1s a1s e1s,\n    FieldRefWellFormed k s t1s a1s ->\n    Deref e1s a1s -> length t1s = length e1s.\nProof.\n  intros. generalize dependent a1s. generalize dependent t1s. \n  induction e1s. \n  - intros. inversion H0. simpl. inversion t1s.\n    + intros. subst. inversion H. subst. reflexivity.\n    + intros. subst. inversion H. subst. reflexivity.\n  - intros. inversion H0. subst. inject H. simpl.\n    assert (He:forall a b, a = b -> S a = S b).\n    { intros. eauto. }\n    apply He. eapply IHe1s; eauto.\nQed.\n\n\nLemma hastypes_shortening : forall s k a e1s e2s fds' t1s t' f,  \n    HasTypes nil s k (e1s ++ a :: e2s) (t1s ++ Field f t' :: fds') ->\n    length e1s = length t1s ->\n    HasTypes nil s k (e1s ++ a :: nil) (t1s ++ Field f t' :: nil).\nProof.\n  intros. generalize dependent t1s. induction e1s.\n  - intros. inversion H0. destruct t1s.\n    + simpl. simpl in H. inject H. eapply HTSCONS; eauto.\n    + inversion H2.\n  - intros. inversion H0. destruct t1s.\n    + inversion H2. \n    + simpl. simpl in H. inject H. eapply HTSCONS; eauto.\nQed.\n\nLemma ht_any_expr : forall s k e, HasType nil s k e Any -> HasTypeExpr nil s k e Any.\nProof.\n  intros. dependent induction H.\n  - apply IHHasType.\n    + eauto.\n    + inversion H0; reflexivity.\n  - apply H.\nQed.\n\nFixpoint succ_type_pairs (C:id) (k:ct) : list (id*id) :=\n  match k with\n    | (ClassDef D _ _)::r => (C,D) :: (D,C) :: (succ_type_pairs C r)\n    | nil => nil\n  end. \n\nLemma stp_in : forall C D E k, In (C,D) (succ_type_pairs E k) ->\n                                 (E = C \\/ (D = E /\\ exists fds mds, In (ClassDef C fds mds) k)) /\\\n                                 (E = D \\/ (C = E /\\ exists fds mds, In (ClassDef D fds mds) k)).\nProof.\n  intros C D E k0 H0. induction k0.\n  - simpl in H0. tauto.\n  - simpl in H0. destruct a as [E' fds mds]. destruct H0.\n    + inject H. split.\n      *  left. auto.\n      * right. split; auto. exists fds. exists mds. apply in_eq. \n    + inject H.\n      * inject H0. split.\n        ** right. split; auto. exists fds. exists mds. apply in_eq.\n        ** left. auto.\n      * apply IHk0 in H0. inject H0. destruct H; destruct H1.\n        ** tauto.\n        ** subst. split; [left;auto|]. right. destruct H0. destruct H0. destruct H0. split; auto. exists x. exists x0.\n           apply in_cons; eauto.\n        ** subst. split; [|left;auto]. right. destruct H. destruct H0. destruct H0. split; auto. exists x. exists x0.\n           apply in_cons; eauto.\n        ** destruct H as [Ceq [Cfds [Cmds HC]]]. destruct H0 as [Deq [Dfds [Dmds HD]]]. split; right. \n           *** split; auto. exists Cfds. exists Cmds. apply in_cons; eauto.\n           *** split; auto. exists Dfds. exists Dmds. apply in_cons; eauto.    \nQed. \n\nLemma stp_corr : forall C D k fds' mds',\n    C <> D ->\n    In (ClassDef D fds' mds') k ->\n    In (C,D) (succ_type_pairs C k) /\\ In (D,C) (succ_type_pairs C k).\nProof.\n  intros. split.\n  - induction k0.\n    + inject H0.\n    + simpl. destruct a as [E fds'' mds'']. destruct H0.\n      * inject H0. apply in_eq.\n      * apply in_cons. apply in_cons. apply IHk0. apply H0.\n  - induction k0.\n    + inject H0.\n    + simpl. destruct a as [E fds'' mds'']. destruct H0.\n      * inject H0. apply in_cons. apply in_eq. \n      * apply in_cons. apply in_cons. apply IHk0. apply H0.\nQed.\n\nLemma nodups_stp : forall C k,\n    (forall fds mds, ~ In(ClassDef C fds mds) k) ->\n    (NoDupsClasses k) ->\n    NoDup (succ_type_pairs C k).\nProof.\n  intros.  induction k0.\n  - simpl. apply NoDup_nil.\n  - simpl. destruct a as [D fds mds].\n    apply NoDup_cons.\n    + unfold not. intros. destruct H1.\n      * inject H1. contradict H. unfold not. intros. \n        eapply H. apply in_eq.\n      * apply stp_in in H1. destruct H1. destruct H2.\n        ** subst. unfold not in H. eapply H. apply in_eq.\n        ** inject H2. inject H4. inject H2. inversion H0. apply H9 in H4. tauto. \n    + apply NoDup_cons.\n      * unfold not. intros. apply stp_in in H1. inject H1. destruct H2; destruct H3.\n        ** subst. eapply H. apply in_eq.\n        ** destruct H2. destruct H3. destruct H3. eapply H. apply in_cons. apply H3.\n        ** inject H0. inject H1. inject H3. inject H0. apply H8 in H1. tauto.\n        ** destruct H2 as [Ceq [Cfds [Cmds HC]]]. destruct H1 as [Deq [Dfds [Dmds HD]]].\n            inject H0. eapply H6. apply HD. \n      * apply IHk0.\n        ** intros. specialize H with (fds0:=fds0)(mds0:=mds0). apply not_in_cons in H.\n           destruct H. apply H1.\n        ** inject H0. apply H3.\nQed.\n\nFixpoint type_pair_universe (k:ct) : list (id*id) :=\n  match k with\n  | (ClassDef C _ _)::r => succ_type_pairs C r ++ type_pair_universe r\n  | nil => nil\n  end.\n\n \nLemma nodups_split : forall T a b, NoDup a -> NoDup b -> (forall x, In x a -> ~In x b) -> @NoDup T (a ++ b).\nProof.\n  intros. induction H.\n  - simpl. eauto.\n  - simpl. apply NoDup_cons.\n    + unfold not. intros. apply in_app_or in H3. destruct H3.\n      * tauto.\n      * specialize H1 with (x0:= x). apply H1 in H3; eauto. apply in_eq.\n    + apply IHNoDup. intros. specialize H1 with (x0 := x0). apply H1. apply in_cons.\n      apply H3.\nQed.\n\nLemma tpu_correct_1 : forall C D k, In (C, D) (type_pair_universe k) -> exists fds mds, In (ClassDef C fds mds) k.\nProof.\n  intros. induction k0.\n  - simpl in H. inject H.\n  - destruct a as [E fds mds]. simpl in H. apply in_app_or in H. destruct H.\n    + destruct (Nat.eq_dec C E).\n      * subst. exists fds. exists mds. apply in_eq.\n      * apply stp_in in H. destruct H. inject H.\n        ** tauto.\n        ** inject H1. inject H2. inject H. exists x. exists x0. apply in_cons. apply H1.\n\n    + apply IHk0 in H. inject H. inject H0. exists x. exists x0. apply in_cons. eauto.\nQed.\n\n\nLemma tpu_correct_2 : forall C D k, In (C, D) (type_pair_universe k) -> exists fds mds, In (ClassDef D fds mds) k.\nProof.\n  intros. induction k0.\n  - simpl in H. inject H.\n  - destruct a as [E fds mds]. simpl in H. apply in_app_or in H. destruct H.\n    + destruct (Nat.eq_dec D E).\n      * subst. exists fds. exists mds. apply in_eq.\n      * apply stp_in in H. destruct H. inject H0.\n        ** tauto.\n        ** inject H1. inject H2. inject H0. exists x. exists x0. apply in_cons. apply H1.\n    + apply IHk0 in H. inject H. inject H0. exists x. exists x0. apply in_cons. eauto.\nQed.\n\nLemma nodup_tpu : forall k, NoDupsClasses k -> NoDup (type_pair_universe k).\nProof.\n  intros. induction k0.\n  - simpl. apply NoDup_nil. \n  - simpl. destruct a as [C fds mds]. apply nodups_split.\n    + apply nodups_stp.\n      ** inject H. apply H5.\n      ** inject H. apply H2.\n    + apply IHk0. inject H. apply H2.\n    + intros. destruct x as [C' D']. apply stp_in in H0. destruct H0. destruct H0; destruct H1.\n      * subst. unfold not. intros. apply tpu_correct_1 in H0. inject H. inject H0. inject H. apply H6 in H0. tauto.\n      * subst. unfold not. intros. apply tpu_correct_1 in H0. inject H. inject H0. inject H. apply H7 in H0. tauto.\n      * subst. unfold not. intros. apply tpu_correct_2 in H1. inject H1. inject H2. inject H. apply H7 in H1. tauto.\n      * unfold not. intros. destruct H0. destruct H1. subst. inject H. destruct H3 as [Hfds [Hmds H3]].\n        apply H8 in H3. tauto.\nQed.\n\nFixpoint equivalent_set(x: list (id*id)) : PairNatList.t :=\n  match x with\n  | e :: r => PairNatList.add e (equivalent_set r)\n  | nil => PairNatList.empty\n  end.\n\nLemma equiv_set_corr : forall e x, In e x <-> PairNatList.In e (equivalent_set x).\nProof.\n  intros. induction x.\n  - simpl; split; try tauto. intros. inversion H. \n  - simpl. split.\n    + destruct (PairNatList.E.eq_dec a e).\n      * destruct a. destruct e. destruct r. inversion H. simpl in H1. subst. inversion H0. simpl in H1.\n        subst. intros. apply PairNatList.add_spec. left. eauto.\n      * intros. inject H.\n        ** unfold not in n. contradict n. eauto.\n        ** apply IHx in H0. apply PairNatList.add_spec. right. apply H0.\n    + intros. apply PairNatList.add_spec in H. inject H.\n      * destruct a. destruct e.  inversion H0. inversion H. inversion H1. simpl in *. subst. left. auto.\n      * right. rewrite IHx. apply H0.\nQed.\nLemma add_diff_subset : forall e x y,\n   PairNatList.Subset (PairNatList.diff x (PairNatList.add e y)) (PairNatList.diff x y).\nProof.\n  intros. MDec.fsetdec. \nQed.\n\nLemma tpu_correct : forall k C D, C <> D ->\n                                  WellFormedType k (class C) -> WellFormedType k (class D) ->\n                                  In (C,D) (type_pair_universe k).\nProof.\n  intros. inject H0. inject H1. induction k0. \n  - inject H3. \n  - destruct a as [E fds' mds']. simpl. inject H3.\n    + inject H0. inversion H4.\n      * inject H0. tauto.\n      * apply in_or_app. left. \n        assert (Hneq: D <> C). {\n          contradict H0. auto.\n        }\n        pose proof (stp_corr D C k0 fds mds Hneq H0). inject H1. apply H3.\n    + inject H4.\n      * inject H1. apply in_or_app. left.\n        pose proof (stp_corr C D k0 fds0 mds0 H H0). inject H1. apply H2.\n      * apply in_or_app. right. apply IHk0; eauto.\nQed.\n\n          \nLemma md_sub_lengthen : forall mu k md1 md2 md, Md_Subtypes mu k md1 md2 -> Md_Subtypes mu k (md::md1) md2.\n  intros. induction H.\n  - econstructor; eauto. apply in_cons. apply H.\n  - constructor.\nQed.\n\nLemma wfm_implies_wft : forall ga k m x t1 t2 e, WellFormedMethod ga k (Method m x t1 t2 e) ->\n                                                   (WellFormedType k t1) /\\ (WellFormedType k t2).\nProof.\n  intros. inject H.\n  - split; try apply WFWA. \n  - repeat split; eauto.\nQed.\n\nLemma compute_md_subtype(k:ct)(m:PairNatList.t)(md1 md2 : md) ga ga'\n      (wfmd1 : WellFormedMethod ga k md1)\n      (wfmd2 : WellFormedMethod ga' k md2)\n      (subtype : forall a b : type,\n          WellFormedType k a -> WellFormedType k b ->\n          {Subtype m k a b} + {~(Subtype m k a b)}) :\n  {Md_Subtype m k md1 md2} + {~Md_Subtype m k md1 md2}.\nProof.\n  destruct md1 as [mn ? t1' t2'], md2 as [mn' ? t1 t2].\n  destruct (Nat.eq_dec mn mn'); revgoals. \n  - right. contradict n. inject n. auto.\n  - apply wfm_implies_wft in wfmd1. apply wfm_implies_wft in wfmd2.\n    inject wfmd1. inject wfmd2.\n    pose proof (subtype t1 t1' H1 H). pose proof (subtype t2' t2 H0 H2).\n    destruct H3; destruct H4.\n    + left. constructor; eauto.\n    + right. contradict n. inject n. apply H15.\n    + right. contradict n. inject n. apply H7.\n    + right. contradict n. inject n. apply H7.\nQed.\n\nLemma find_md_subtype(k:ct)(m:PairNatList.t)(md1 : md)(mds : list md) ga ga'\n       (wfmd1 : WellFormedMethod ga k md1)(wfmd2 : forall md, In md mds -> WellFormedMethod ga' k md)\n      (subtype : forall a b : type, WellFormedType k a -> WellFormedType k b ->\n          {Subtype m k a b} + {~(Subtype m k a b)}) :\n  { exists md':md, In md' mds /\\ Md_Subtype m k md' md1 } +\n  {forall md', In md' mds -> ~Md_Subtype m k md' md1 }.\nProof.\n  induction mds.\n  - right. intros. inject H.\n  - assert (Hih: forall md0 : md, In md0 mds -> WellFormedMethod ga' k md0).\n    { intros. pose proof (in_cons a md0 mds H). apply wfmd2 in H0. auto. }\n    apply IHmds in Hih. clear IHmds. destruct Hih.\n    + left. inject e. exists x. inject H. split; eauto. apply in_cons. apply H0.\n    + destruct md1 as [mn ? t1' t2'], a as [mn' ? t1 t2]. apply wfm_implies_wft in wfmd1.\n      specialize wfmd2 with (md0:=Method mn' i0 t1 t2 e0). pose proof (wfmd2 (in_eq _ _)).\n      apply wfm_implies_wft in H. inject wfmd1. inject H. clear wfmd2.\n      destruct (Nat.eq_dec mn mn'); destruct (subtype t1' t1 H0 H2); destruct (subtype t2 t2' H3 H1);\n        try (right; intros; inject H; [contradict n0; inject n0; auto|apply n; apply H4]; fail).\n      * subst. left. exists (Method mn' i0 t1 t2 e0). split.\n        ** apply in_eq.\n        ** constructor; eauto.           \nQed. \n\nLemma compute_md_subtypes(k:ct)(m:PairNatList.t)(md1 md2 : list md) ga ga' \n      (s:heap)(wfmd1 : forall md, In md md1 -> WellFormedMethod ga k md)\n      (wfmd2 : forall md, In md md2 -> WellFormedMethod ga' k md)\n      (subtype : forall a b : type, WellFormedType k a -> WellFormedType k b ->\n          {Subtype m k a b} + {~(Subtype m k a b)}) :\n  {Md_Subtypes m k md1 md2} + {~(Md_Subtypes m k md1 md2)}.\n  revert wfmd1. revert wfmd2. revert md1. induction md2.\n  - left. constructor.\n  - intros. specialize IHmd2 with (md1:=md1). destruct IHmd2; eauto.\n    + intros.  apply wfmd2. apply in_cons. apply H.\n    + destruct (find_md_subtype k m a md1 ga' ga); eauto. \n      * apply wfmd2. apply in_eq.\n      * left. inject e. inject H. econstructor; eauto.\n      * right. intros H. inject H. apply n in H2. tauto.\n    + right. contradict n. inject n. auto.\nQed.\n\nProgram Fixpoint compute_subtype (m : PairNatList.t)(k : ct)(kwf:WellFormedClassTable k)\n        (a b : type)(awf:WellFormedType k a)(bwf:WellFormedType k b)\n        {measure (PairNatList.cardinal (PairNatList.diff (equivalent_set (type_pair_universe k)) m))}\n  : {Subtype m k a b} + {~ (Subtype m k a b)} :=\n  match a, b with\n  | Any, Any => _\n  | (class C), (class D) =>\n    match (Nat.eqb C D) with\n    | true => _\n    | false =>\n      match PairNatList.mem (C,D) m with\n        true => _\n      | false =>\n        let mu' := PairNatList.add (C,D) m in\n        let mc := (methods C k) in\n        let mD := (methods D k) in\n        _\n      end\n    end\n  | Any, (class C) => _\n  | (class C), Any => _\n  end.\nNext Obligation.\n  left. eauto.\nQed.\nNext Obligation.\n  left. symmetry in Heq_anonymous. rewrite Nat.eqb_eq in Heq_anonymous. subst. auto.\nQed.\nNext Obligation.\n  left. symmetry in Heq_anonymous. apply MProps.Dec.F.mem_2 in Heq_anonymous. apply STSeen. eauto.\nQed.\nNext Obligation.\n  remember (methods C k0) as mc.\n  remember (methods D k0) as mD.\n  remember (PairNatList.add (C,D) m) as mu'.\n  destruct (compute_md_subtypes k0 mu' mc mD ((this, (class C))::nil) ((this, (class D))::nil) nil).\n  - subst. apply methods_are_wf; eauto. \n  - subst. apply methods_are_wf; eauto.\n  - refine (fun (a b:type)(wfa:WellFormedType k0 a)(wfb:WellFormedType k0 b) =>\n              compute_subtype mu' k0 kwf a b wfa wfb _).\n    eapply MProps.subset_cardinal_lt.\n    + MDec.fsetdec.\n    + assert (Hin: PairNatList.In (C,D) (PairNatList.diff (equivalent_set (type_pair_universe k0)) m)).\n      {\n        subst. apply MProps.FM.diff_3.\n        - rewrite<- equiv_set_corr. apply tpu_correct; eauto. symmetry in Heq_anonymous0.\n          rewrite Nat.eqb_neq in Heq_anonymous0. eauto.\n        - symmetry in Heq_anonymous. rewrite<- MProps.Dec.F.not_mem_iff in Heq_anonymous. eauto. \n      } apply Hin.\n    + rewrite PairNatList.diff_spec. unfold not. intros. inject H. apply H1.\n      rewrite PairNatList.add_spec. left. auto.\n  - left. subst. eapply STClass; eauto.\n  - right. contradict n. inject n.\n    + symmetry in Heq_anonymous0. rewrite Nat.eqb_neq in Heq_anonymous0. tauto.\n    + symmetry in Heq_anonymous. rewrite<- MProps.Dec.F.not_mem_iff in Heq_anonymous. tauto.\n    + apply H4.\nQed.\nNext Obligation.\n  right. intros H. inject H.\nQed.\nNext Obligation.\n  right. intros H. inject H.\nQed.\n\nLemma ref_has_cell' : forall g s k a t, HasTypeExpr g s k (Ref a) t -> exists hc, In (a, hc) s.\nProof.\n  intros. inject H.  \n  - exists (HCell(C,a')). auto. \n  - exists hc. auto. \nQed.\n\nLemma ref_has_cell : forall g s k a t, HasType g s k (Ref a) t -> exists hc, In (a, hc) s.\nProof.\n  intros. apply eventually_concrete in H. inject H. inject H0. eapply ref_has_cell'; eauto.\nQed.\n\n\nLemma forall_same_size : forall T T' a b P, @Forall2 T T' P a b -> length a = length b.\nProof.\n  intros. induction H.\n  - auto.\n  - simpl. auto.\nQed.\nLemma hastypes_same_length : forall s k a b, HasTypes nil s k a b -> length a = length b.\nProof.\n  intros. induction H.\n  - simpl. omega.\n  - simpl. auto.\nQed.\nLemma same_size_prefix_hts : forall s k a b a' b' P,\n    HasTypes nil s k (a ++ b) (a' ++ b') ->\n    Forall2 P b b' ->\n    length a = length a'.\nProof.\n  intros. induction H0.\n  - repeat rewrite app_nil_r in H. induction H.\n    + simpl. omega.\n    + auto.\n  - apply hastypes_same_length in H. repeat rewrite app_length in H.\n    apply forall_same_size in H1. simpl in H. rewrite H1 in H. omega.\nQed.\n\n\nLtac unfolde name :=\n  match goal with\n  | [ H : (exists a:?t, _) |- (exists b:?t, _) ] => let v' := a in\n                                                    destruct H as [name H];\n                                                    exists name end.\n\nLemma ref_is_finished : forall k e s k' e' s' a, Steps k e s k' e' s' -> e <> Ref a.\nProof.\n  intros. contradict H. intros H'. subst. dependent induction H'.\n  - destruct E;\n      try (match goal with [ H: (equivExpr ?E ?c) = Ref ?a |- _] => simpl in H; inversion H; fail end).\n    simpl in x. apply IHH' in x. tauto.\nQed.\n\nLemma ct_exten_refl'' : forall k,\n    WellFormedClassTable k -> ct_ext k k.\nProof.\n  intros. inject H. eauto.\nQed.\nHint Resolve ct_exten_refl''. \n\nLemma frwf_exten_ctx : forall k k' s fs1 a1s, \n    FieldRefWellFormed k s fs1 a1s -> ct_ext k k' -> FieldRefWellFormed k' s fs1 a1s.\nProof.\n  intros. induction H.\n  - econstructor.\n    + eapply ct_exten_hastype; eauto.\n    + apply IHFieldRefWellFormed. eauto.\n  - constructor.\nQed.\n\nLemma ct_exten_hastypes :forall (g : env) (s : heap) (k : ct) e t (k' : ct),\n    HasTypes g s k e t -> ct_ext k k' -> HasTypes g s k' e t.\nProof.\n  intros. induction H.\n  - econstructor.\n    + eapply ct_exten_hastype; eauto.\n    + eauto.\n  - eauto.\nQed.\n\nLemma ct_exten_fieldwf : forall k k' s fds refs, FieldRefWellFormed k s fds refs ->\n                                                 ct_ext k k' -> FieldRefWellFormed k' s fds refs.\nProof.\n  intros. induction H.\n  - constructor; eauto. eapply ct_exten_hastype; eauto.\n  - constructor.\nQed.\n\nHint Resolve frwf_exten_ctx.\nHint Resolve ct_exten_hastypes.\nLtac eval_ctx E :=\n  match goal with\n  | [ H: Steps _ ?e1 _ ?k ?e2 ?s |- _ ] =>\n    exists (equivExpr e2 E); exists s; exists k;\n    match goal with\n    | [ H' : (WellFormedState _ _ ?s') |- context[(Steps _ ?e3 _ _ ?e4 ?s')]] =>\n      let Htype := fresh \"H\" in\n      let Hleft := fresh \"H\" in\n      match goal with\n      | [|- context[(HasType nil s' ?k e4 ?t)]] => assert (Htype:HasType nil s' k e4 t)\n      end;\n      [|assert (Hleft: e3 = (equivExpr e1 E));\n        [try (subst; eauto;fail)| rewrite Hleft; clear Hleft; repeat split;\n                                  [eauto| subst; simpl; try (inject H'; eapply WFSWP;eauto)\n                                   | apply Htype | eauto | eauto ]]]\n    end\n  end.\n\n\n\n\nDefinition is_sound(k:ct)(s:heap)(e:expr)(t:type) :=\n  (exists a : ref, e = Ref a) \\/\n  (exists (e' : expr) (s' : heap)(k':ct), Steps k e s k' e' s' /\\\n                                           WellFormedState k' e' s' /\\\n                                           HasType nil s' k' e' t /\\\n                                           retains_references s s' /\\\n                                           ct_ext k k') \\/\n  (exists E : EvalCtx,\n      (exists (a : ref) (m : id) (a' : ref) (C : id) (aps : list ref),\n          (e = equivExpr (DynCall (Ref a) m (Ref a')) E) /\\\n          In (a, HCell(C, aps)) s /\\\n          forall x e, ~ (In (Method m x Any Any e) (methods C k))) \\/\n      (exists (t' : type) (a : ref) (C : id) (aps:list ref),\n          (e = equivExpr (SubCast t' (Ref a)) E) /\\\n          In (a, HCell(C,aps)) s /\\\n          ((Subtype empty_mu k (class C) t') -> False)) \\/\n      (exists a C aps C', e = equivExpr (BehCast (class C') (Ref a)) E /\\\n                    In (a, HCell(C, aps)) s /\\\n                    ~(incl (method_names (methods C' k)) (method_names (methods C k))))).\n\n\nLemma sound_destr : forall k s e2s t2s,\n    Forall2 (is_sound k s) e2s (typesof t2s) ->\n    Forall2 (fun e fd => match fd with (Field f t) => is_sound k s e t end) e2s t2s.\nProof.\n  intros. dependent induction H.\n  - destruct t2s.\n    + constructor.\n    + simpl in x. destruct f. inject x.\n  - destruct t2s.\n    + inject x.\n    + constructor.\n      * destruct f. simpl in x. inject x. auto.\n      * apply IHForall2. simpl in x. destruct f. inject x. auto.\nQed.\n\nLemma hastype_in_heap : forall g s k a t, HasType g s k (Ref a) t -> exists hc, In (a, hc) s.\nProof.\n  intros. apply eventually_concrete in H.\n  inject H. inject H0. inject H1.\n  - exists (HCell(C, a')). auto.\n  - exists hc. auto.\nQed.\n\nLemma nil_always_preserves: forall s, retains_references nil s.\nProof.\n  intros. intros a C refs H. inject H.\nQed.\n\n\nLemma wff_exten_ct : forall k k' fd,\n    WellFormedField k fd -> ct_ext k k' -> WellFormedField k' fd.\nProof.\n  intros. inject H. constructor. eauto.\nQed.\n\nLemma wfm_exten_ct : forall g k k' md,\n    WellFormedMethod g k md -> ct_ext k k' -> WellFormedMethod g k' md.\nProof.\n  intros. inject H.\n  - econstructor; eauto. eapply ct_exten_hastype; eauto.\n  - econstructor; eauto. eapply ct_exten_hastype; eauto.\nQed.\n\nLemma wfct_exten_ct : forall ks ks' k,\n    WellFormedClass ks k -> ct_ext ks ks' -> WellFormedClass ks' k.\nProof.\n  intros. pose proof H0.\n  inversion H0. inject H2. induction x; auto. simpl. inject H4.\n  simpl in H1. pose proof H3. apply IHx in H3.\n  - destruct k0. inject H3. constructor; eauto. \n    + intros. eapply wff_exten_ct; eauto. unfold ct_ext. exists [(ClassDef C fds mds)]. split.\n      * auto.\n      * constructor; eauto.\n    + intros. eapply wfm_exten_ct; eauto. unfold ct_ext. exists [(ClassDef C fds mds)].\n      split; eauto. constructor; eauto.\n  - exists x. auto.\nQed.\n\nLemma incl_dec : forall T l r, (EqDec T) -> {@incl T l r} + {~ (incl l r)}.\n  intros. generalize dependent r. induction l.\n  - intros. destruct r.\n    + left. unfold incl. intros. inject H.\n    + left. unfold incl. intros. inject H.\n  - intros. destruct (in_dec X a r).\n    + destruct (IHl r).\n      * left. unfold incl. intros. destruct H; subst; eauto.\n      * right. unfold incl. intro H. contradict n. unfold incl. intros. apply H.\n        apply in_cons. auto.\n    + right. intro H. unfold incl in H. contradict n. apply H. apply in_eq.\nQed.\n\nLemma fresh_is_really_fresh : forall C k,\n    fresh_class_name (fresh_class k C) k.\nProof.\n  intros mn k fds mds H.\n  remember (fresh_class k mn) as D.\n  pose proof (fresh_class_not_in k mn D HeqD). inject H0. apply H2 in H. omega.\nQed. \n\nHint Resolve nil_always_preserves. \nHint Resolve heap_weakening_2. \nHint Resolve ct_exten_refl. \n\n\nLtac got_stuck E :=\n  match goal with\n  | [ H : ?H1 \\/ ?H2 \\/ ?H3 |- exists Ei : EvalCtx, _ \\/ _ \\/ _ ] =>\n    exists E;\n    destruct H; [|destruct H]; [left |\n                                right; left |\n                                right; right]; sync_destruct_exists H;\n    try (destruct H; subst; eauto; fail);\n    try (subst; simpl; auto; fail)\n  end.\n\nTheorem soundness: forall k e s t,\n  WellFormedState k e s -> HasType nil s k e t -> is_sound k s e t.\nProof. \n  intros k e s t Hwfs Hht. destruct Hwfs as [k e s _ _ Hwfh Hwfct].\n  pose proof (eq_refl (@nil (id*type))) as Hduh0.\n  pose proof (eq_refl k) as Hduh1. pose proof (eq_refl s) as Hduh2.    \n  generalize dependent Hduh2. generalize dependent Hduh1. generalize dependent Hduh0.\n  apply typing_ind with\n  (P := fun g' s' k' e t ih =>\n          g' = nil -> k' = k -> s' = s -> is_sound k s e t)\n  (P0 := fun g' s' k' e t ih =>\n           g' = nil -> k' = k -> s' = s -> is_sound k s e t)\n  (P1 := fun g' s' k' es ts (ih : HasTypes g' s' k' es ts) => \n           g' = nil -> k' = k -> s' = s ->\n           exists e1s (a1s : list ref) t1s e2s t2s,\n             es = e1s ++ e2s /\\\n             ts = t1s ++ t2s /\\\n             FieldRefWellFormed k s t1s a1s /\\\n             Deref e1s a1s /\\\n             (forall ei eir, ei::eir = e2s -> forall a, ei <> Ref a) /\\\n             @Forall2 expr type (is_sound k s) e2s (typesof t2s));\n    try (intros; subst; inversion i; fail); try (intros; subst; unfold is_sound; eauto; fail). \n  - intros. subst. destruct H; eauto.\n    + unfold is_sound. eauto.\n    + unfold is_sound. right. destruct H.\n      * left. unfolde e'. unfolde s'. unfolde k'.\n        destruct H  as [H1 [H2 [H3 [H4 H5]]]].\n        repeat split; eauto. \n      * right. eauto.\n  - intros. subst. destruct H; try (unfold is_sound); eauto.\n  - intros. subst. unfold is_sound. right. left.\n    destruct (infields_implies_fieldin _ _ _ _ _ _ _ Hwfh Hwfct i i0) as [a'' H1].\n    exists (Ref a''). exists s. exists k. repeat split; eauto.\n    + eapply WFSWP; eauto. destruct Hwfh. apply a0 in i. destruct i as [_ H2].\n      eapply FieldsWFImpliesFieldIn; eauto.\n    + eapply FieldsWFImpliesFieldIn; eauto. destruct Hwfh. apply H0 in i.\n      destruct i as [_ H2]. eauto.\n  - intros. subst. destruct H; eauto.\n    * unfold is_sound. right. left. inject H.\n      remember (fields C k) as fds.\n      remember (update_field_ref f x fds a') as aps'.\n      remember (update_heap a aps' s) as s'.\n      exists (Ref x).\n      exists s'.\n      exists k. \n      assert (HHwrite: HeapWrite a aps' s s').\n      { rewrite Heqs'. eapply update_heap_writes; eauto. }\n      assert (HFwrite: FieldWrite f x a' fds aps').\n      { eapply update_field_is_well_formed; eauto. destruct Hwfh. apply a0 in i.\n        inject i. apply H0. }\n      repeat split; try eauto.\n      ** subst. eapply SWrite; eauto.\n      ** eapply WFSWP; eauto.\n         *** eapply write_field; eauto. \n             **** rewrite Heqfds in i0. apply i0. \n             **** subst. apply HFwrite.\n      ** eapply heapwrite_retains_refs'; eauto.\n    * unfold is_sound. right. inject H.\n      ** left. destruct H0 as [e' [s' [k' [HS [Hwfs [Hht' [Hret Hct]]]]]]]. \n         eval_ctx (EAssign a f (EHole)). simpl. constructor. apply Hret in i. inject i. eauto. \n      ** right. destruct H0. got_stuck (EAssign a f x).\n  - intros. subst. destruct H;eauto; destruct H0;eauto. \n    + destruct H as [a1 H1]. destruct H0 as [a2 H2]. subst. apply eventually_concrete in h.\n      unfold is_sound. right. left.\n      destruct h as [tp [H1 H2]]. inversion H2; eauto.\n      * subst. pose proof (subtype_transitive _ _ _ _ _ H6 H1).\n        apply subtype_method_containment with (md0 := (Method m x t0 t' eb)) in H; eauto.\n        inversion H as [[m' x' t0' t'' e'] [H3 H4]]. inversion H4. subst. inject H8; [|inversion H5].\n        remember (subst a1 a2 x' e') as ebody. exists ebody. exists s. exists k. \n        assert (Hbody: HasType nil s k ebody t').\n        {\n          inject H12. \n          pose proof H0 as Hback. inversion Hwfh. subst. apply H7 in H0. destruct H0.\n          pose proof H0. inversion H0. subst. remember (methods C0 k) as mds'.\n          pose proof (methods_are_wf k C0 mds' Hwfct H9 Heqmds'). subst. apply H11 in H3.\n          inversion H3.\n          **** subst. simpl in H23. eapply substituion_typing; eauto.\n          **** subst. simpl in H25. eapply substituion_typing; eauto. \n        }\n        repeat split; eauto.\n        *** inject H12. eapply SCall with (C:=C0)(aps := a'); eauto.\n      * subst. inversion H1.\n    + destruct H as [a H]. subst. destruct H0.\n      * unfold is_sound. right. left. inversion H as [e0' [s' [k' [H1 [H2 [H3 [H4 H5]]]]]]].\n        eval_ctx (ECall2 a m t0 t' EHole). simpl. constructor. econstructor.\n        ** eapply ct_exten_hastype; eauto.\n        ** eauto.\n        ** eauto. \n      * unfold is_sound. right. right. destruct H as [E H].\n        got_stuck (ECall2 a m t0 t' E). \n    + destruct H.\n      * inversion H as [e0' [s' [k' [H1 [H2 [H3 [H4 H5]]]]]]]. unfold is_sound.\n        right. left.\n        eval_ctx (ECall1 EHole m t0 t' e'). constructor. econstructor; eauto. eapply ct_exten_hastype; eauto. \n      * destruct H as [E H]. unfold is_sound. right. right.\n        got_stuck (ECall1 E m t0 t' e').\n    + destruct H as [Hlef | Hrigh].\n      * unfold is_sound. right. left. inversion Hlef as [e0' [s' [k' [H1 [H2 [H3 [H4 H5]]]]]]].\n        eval_ctx (ECall1 (EHole) m t0 t' e'). simpl. constructor. econstructor; eauto.\n        eapply ct_exten_hastype; eauto.\n      * right. right. inject Hrigh. got_stuck (ECall1 x0 m t0 t' e').\n  - intros. subst. destruct H; destruct H0; eauto.\n    + unfold is_sound. right. destruct H as [a H]; subst. destruct H0 as [a' H0]; subst.\n      apply ht_any_expr in h0. apply ht_any_expr in h. inject h.\n      * inject H4.  \n      * destruct hc. destruct p as [C a'0]. edestruct (fun dec => in_dec dec (m, Any, Any)\n                          (map (fun md => match md with Method m _ t1 t2 _ => (m,t1,t2) end) (methods C k))).\n        ** decide equality; eauto using type_dec. decide equality; eauto using type_dec, Nat.eq_dec.\n        ** apply in_map_iff in i. destruct i as [md H]. destruct md. destruct H. inject H.\n           left. exists (subst a a' i0 e0). exists s. exists k. \n           assert (Hmtyped : HasType nil s k (subst a a' i0 e0) Any).\n           {\n               inject Hwfh. pose proof H3. apply H1 in H3. destruct H3.\n               pose proof (methods_are_wf k C (methods C k) Hwfct H3 eq_refl (Method m i0 Any Any e0) H0).\n               inject H5. eapply substituion_typing; eauto.\n               **** eauto. \n           }           \n           repeat split; eauto.  \n        ** right. exists EHole. left. simpl. exists a. exists m. exists a'. exists C. exists a'0.\n           repeat split; eauto.\n           *** intros. contradict n. apply in_map_iff. exists (Method m x Any Any e0). split; eauto.\n    + destruct H0.\n      * inversion H0 as [e0' [s' [k' [H1 [H2 [H3 [H4 H5]]]]]]]. unfold is_sound.\n        right. left. inversion H as [a]. subst.\n        eval_ctx (EDCall2 a m EHole). simpl. constructor. econstructor; eauto. eapply ct_exten_hastype; eauto. \n      * destruct H as [a H]. subst. destruct H0 as [E H0]. \n        unfold is_sound. right. right. remember (EDCall2 a m E) as E'. exists E'. destruct H0.\n        ** left. sync_destruct_exists H. intuition idtac. subst. eauto.\n        ** destruct H.\n           *** right. left. sync_destruct_exists H. inject H. subst. simpl. auto.\n           *** right. right. sync_destruct_exists H. inject H. subst. simpl. auto. \n    + destruct H0 as [a H0]. subst. destruct H.\n      * unfold is_sound. right. left. remember (EDCall1 EHole m (Ref a)) as E.\n        inversion H as [e0' [s' [k' [H1 [H2 [H3 [H4 H5]]]]]]].\n        assert (Hleft: equivExpr e0 E = (DynCall e0 m (Ref a))).\n        { subst. tauto. }\n        assert (Hright: equivExpr e0' E = DynCall e0' m (Ref a)).\n        { subst. tauto. }\n        assert (Htyped: HasType nil s' k' (equivExpr e0' E) Any).\n        { rewrite Hright. apply KTEXPR. eapply KTDYNCALL; eauto. eapply ct_exten_hastype; eauto. }\n        exists (equivExpr e0' E). exists s'. exists k'. repeat split; eauto.\n        ** rewrite <- Hleft. eapply SCtx; eauto.\n        ** inject H2. eapply WFSWP; eauto.\n      * unfold is_sound. right. right. destruct H as [E H]. remember (EDCall1 E m (Ref a)) as E'.\n        exists E'. inversion H.\n        ** left. sync_destruct_exists H0. destruct H0. subst. eauto. \n        ** right. destruct H0.\n           *** left. inversion H0 as [t'' [a' [C' [aps [He [H1 H2]]]]]]. exists t''.\n               exists a'. exists C'. exists aps. subst. auto.\n           *** right. sync_destruct_exists H0. inject H0. subst. auto. \n    + clear H0. destruct H.\n      * unfold is_sound. right. left. remember (EDCall1 EHole m e') as E.\n        inversion H as [e0' [s' [k' [H1 [H2 [H3 [H4 H5]]]]]]].\n        assert (Hleft: equivExpr e0 E = (DynCall e0 m e')).\n        { subst. tauto. }\n        assert (Hright: equivExpr e0' E = DynCall e0' m e').\n        { subst. tauto. }\n        assert (Htyped: HasType nil s' k' (equivExpr e0' E) Any).\n        { rewrite Hright. apply KTEXPR. eapply KTDYNCALL; eauto. eapply ct_exten_hastype; eauto. }\n        exists (equivExpr e0' E). exists s'. exists k'. repeat split; eauto.\n        ** rewrite <- Hleft. eapply SCtx; eauto.\n        ** inject H2. eapply WFSWP; eauto.\n      * unfold is_sound. right. right. destruct H as [E H]. remember (EDCall1 E m e') as E'.\n        exists E'. inversion H.\n        ** left. sync_destruct_exists H0. destruct H0. subst. eauto. \n        ** right. destruct H0.\n           *** left. inversion H0 as [t'' [a' [C' [aps [He [H1 H2]]]]]].\n               exists t''. exists a'. exists C'. exists aps. subst. simpl. auto.\n           *** right. sync_destruct_exists H0. inject H0. subst. simpl. auto. \n  - intros. subst. destruct H as [e1s H]; eauto. destruct H as [a1s [t1s [e2s [t2s [H [H0 [H1 H2]]]]]]]. \n    induction e2s.\n    + rewrite app_nil_r in H. subst. inversion H2. destruct t2s; eauto.\n      * clear H2. unfold is_sound. right. left.\n        remember (fresh_ref s 0) as a.\n        remember (HCell(C,a1s)) as hc.\n        remember ((a,hc)::s) as s'.\n        exists (Ref a). exists s'. exists k. repeat split; eauto. \n        ** eapply SNew.\n           *** unfold not. intros. apply fresh_not_in in Heqa. destruct Heqa.\n               apply H4 in H2. omega.\n           *** apply H.\n           *** rewrite Heqs'. rewrite Heqhc. reflexivity.\n        ** assert (Hndh: NoDupsHeap s').\n           {\n             rewrite Heqs'. apply NDH_Cons.\n             ***** unfold not. intros.\n             apply fresh_not_in in Heqa. destruct Heqa.\n             apply H4 in H2. omega.\n             ***** destruct Hwfh. apply H2.\n           }\n          eapply WFSWP; eauto.\n           *** eapply KTEXPR. eapply KTREFTYPE.\n               **** rewrite Heqs'. rewrite Heqhc. apply in_eq.\n               **** apply STRefl.\n           *** apply WFH.\n               **** apply Hndh. \n               **** intros. destruct (Nat.eq_dec a0 a).\n                    { pose proof (in_eq (a,hc) s). rewrite<- Heqs' in H3. rewrite e0 in H2.\n                      pose proof (nodups_collapses_refs s' a hc (HCell(C0,aps)) Hndh H3 H2).\n                      rewrite H4 in Heqhc. inversion Heqhc. \n                      split.\n                      - eapply WFWTC; eauto. \n                      - rewrite app_nil_r in i.\n                        pose proof (fields_gets_fields C k t1s (WFWTC k C t1s mds i) Hwfct).\n                        destruct H5.\n                        assert (HFields: fields C k = t1s).\n                        {\n                          apply H8. exists mds. apply i.\n                        }\n                        rewrite HFields. rewrite Heqs'. apply frwf_weakening with (s':=(a,hc)::nil)(s:=s).\n                        apply H1. \n                    }\n                    {\n                      rewrite Heqs' in H2. inversion H2.\n                      - inversion H3. symmetry in H5. tauto. \n                      - clear H2. split.\n                        + destruct Hwfh. apply H4 in H3. destruct H3 as [H3 H5].\n                          eauto.\n                        + destruct Hwfh. apply H4 in H3. destruct H3 as [H3 H5].\n                          rewrite Heqs'. apply frwf_weakening with (s':=(a,hc)::nil). eauto. \n                    }\n        ** apply KTEXPR. apply KTREFTYPE with (C:=C)(a':=a1s).\n           *** rewrite Heqhc in Heqs'. rewrite Heqs'. apply in_eq.\n           *** apply STRefl.\n        ** rewrite Heqs'. apply weakening_retains_refs with (s':=(a,hc)::nil).\n      * destruct H0. inversion H3. destruct f. discriminate.\n    + destruct H2. destruct H3. clear IHe2s. unfold is_sound. right.\n      inversion H4 as [|e' t' eps tps]. subst. inversion H5.\n      * destruct H. unfold not in H3. rewrite H in H3. exfalso. eapply H3.\n        ** reflexivity.\n        ** eauto.\n      * destruct H. \n        ** left. destruct H as [e' [s' [k' [Hi1 [Hi2 [Hi3 [Hi4 Hi5]]]]]]].\n           eval_ctx (ENew C a1s EHole e2s); revgoals.\n           { subst. simpl. rewrite deref_map with (e1s:=e1s)(a1s:=a1s); eauto. }\n           { subst. simpl. rewrite<- deref_map with (e1s:=e1s)(a1s:=a1s); eauto.\n             symmetry in H9. pose proof (typesof_cons t2s t' tps H9).\n             destruct H as [f [fds' Heq]]. \n             eapply KTEXPR. eapply KTNEW; eauto.\n             - apply HasTypes_split.\n               + eapply hastypes_split; eauto. \n                 * eapply fieldwf_still_good'; eauto.\n               + rewrite Heq. eapply HTSCONS; eauto. \n                 * eapply hastypes_app.\n                   ** rewrite Heq in h. rewrite cons_app_app_app in h.\n                      pose proof (cons_app_app_app fd t1s). rewrite H in h.\n                      eapply hastypes_ignores_heapv; eauto. \n                   ** rewrite Heq in h. eapply hastypes_shortening.\n                      *** eapply hastypes_ignores_heapv; eauto.\n                      *** symmetry. eapply frwf_deref_implies_eq_length; eauto.\n             - rewrite <- Heq. inject Hi5. inject H. apply in_or_app. right. eauto. }\n        ** right. inversion H as [E]. got_stuck (ENew C a1s E e2s). \n           *** destruct H0. simpl. rewrite<- H0.\n               apply deref_map in H2. rewrite <- H2. destruct H7. repeat split; eauto. \n           *** destruct H0. subst. destruct H7.\n               simpl. rewrite (deref_map _ _ H2). repeat split; eauto.\n           *** subst. simpl. rewrite (deref_map _ _ H2). inject H0. auto. \n  - intros. subst. destruct H; try tauto.\n    + destruct H as [a H]. subst. unfold is_sound. pose proof h as h'.\n      apply eventually_concrete in h. inject h. inject H. apply ref_has_cell' in H1. \n      pose proof Hwfh as Hwfh'. inject Hwfh. pose proof H2. inject H1. destruct x0. destruct p as [C a'].\n      pose proof H4 as HIn. apply H2 in H4. inject H4.\n      destruct (compute_subtype empty_mu k Hwfct (class C) t0 H1 w).\n      ** right. left. exists (Ref a). exists s. exists k. repeat split; eauto.\n         *** pose proof s0. apply subtype_only_classes in s0. inject s0. eapply SSubCast; eauto. \n         *** eapply WFSWP; eauto. econstructor; eauto.\n      ** right. right. exists EHole. right. left. exists t0. exists a. exists C. exists a'. repeat split; eauto.\n    + destruct H.\n      * destruct H as [e' [s' [k' [HSteps [HWFS [HHT [Hrr Hext]]]]]]]. unfold is_sound. right. left.\n        eval_ctx (ESubCast t0 EHole). simpl. eauto. \n      * inject H. unfold is_sound. right. right. exists (ESubCast t0 x). inject H0.\n        ** left. sync_destruct_exists H. inject H. inject H1. repeat split; eauto.\n        ** right. destruct H.\n           *** left. sync_destruct_exists H. inject H. inject H1. repeat split; eauto.\n           *** right. sync_destruct_exists H. inject H. subst. auto. \n  - intros. subst. destruct H; eauto; revgoals.\n    + right. inject H.\n      * left. destruct H0 as [e' [s' [k' [Hi1 [Hi2 [Hi3 [Hi4 Hi5]]]]]]].\n        eval_ctx (EBehCast t0 EHole). simpl. eauto.\n      * right. destruct H0 as [E [H1| H2]]; exists (EBehCast t0 E). \n        ** left. sync_destruct_exists H1. inject H1. split; auto.\n        ** right. destruct H2.\n           *** left. sync_destruct_exists H. inject H. split; auto.\n           *** right. sync_destruct_exists H. inject H. split; auto.\n    + destruct H as [a H]. subst. destruct t0; revgoals. \n      * right. left.\n        remember (fresh_ref s a) as a''. apply eventually_concrete in h.\n        destruct h as [t' [Hst Hhte]]. apply KTEXPR in Hhte. apply hastype_in_heap in Hhte.\n        destruct Hhte as [[[C ap]] Hinh].\n        remember (fresh_class k C) as E. \n        remember ((a'', HCell (E, [a])) :: s) as s'.\n        remember ((WrapAny_classes C (methods C k) E) :: k) as k'.\n        assert (Hctext: ct_ext k k'). {\n          exists [WrapAny_classes C (methods C k) E]. split.\n          - simpl. auto.\n          - subst k'. constructor.\n            + inject Hwfct. auto.\n            + intros. intro H. apply fresh_class_not_in in HeqE.\n              destruct HeqE. apply H1 in H. omega. }           \n        exists (Ref a''). exists s'. exists k'. repeat split.\n        ** eapply SBehCastAny; eauto. \n           *** apply fresh_class_not_in in HeqE. inject HeqE. inject Hwfh. apply H2 in Hinh.\n               inject Hinh. inject H3. apply H0 in H7. omega.\n           *** inject Hwfh. apply H0 in Hinh.\n               inject Hinh. inject H1. erewrite<- methods_in; eauto. inject Hwfct.\n               apply H1 in H5. inject H5. eauto.\n        ** assert (HCin: exists fds mds, In (ClassDef C fds mds) k).\n           { inject Hwfh. apply H0 in Hinh. inject Hinh. inject H1. exists fds. exists mds. auto. }\n           eapply WFSWP.\n           *** constructor. econstructor; eauto. rewrite Heqs'. apply in_eq.\n           *** constructor.\n               **** rewrite Heqs'. constructor.\n                    ***** apply fresh_not_in in Heqa''. intros. intro H. inject Heqa''.\n                    apply H1 in H. omega.\n                    ***** inject Hwfh. auto.\n               **** intros. rewrite Heqs' in H. inversion H.\n                    ***** inversion H0. rewrite<- H3. rewrite H4. split.\n                    { econstructor.  unfold WrapAny_classes in Heqk'. rewrite Heqk'. apply in_eq. }\n                    { unfold WrapAny_classes in Heqk'. rewrite  Heqk'. simpl. rewrite Nat.eqb_refl. rewrite<- H4.\n                      constructor.\n                      - constructor. econstructor; eauto. rewrite Heqs'. apply in_cons. apply Hinh.\n                      - constructor.  }\n                    ***** inversion Hwfh. subst k. subst s. apply H2 in H0. inversion H0. split; eauto.\n                    erewrite<- ct_fields_eq; eauto. eapply frwf_exten_ctx; eauto. eapply fieldwf_still_good'; eauto.\n                    subst s'. unfold retains_references. intros. exists aps0. apply in_cons. auto.\n           *** subst k'. constructor.\n               **** intros. inject H.                             \n                    {destruct HCin as [fds' [mds' HCin]].\n                     rewrite<- H0. eapply correctness_CWrapAny; eauto.\n                        - erewrite<- methods_in; eauto.\n                        - apply fresh_is_really_fresh.\n                        - erewrite<- methods_in; eauto. inject Hwfct. apply H in HCin.\n                          inject HCin. auto. \n                        - erewrite<- methods_in; eauto. inject Hwfct. apply H in HCin. auto. }\n                    eapply wfct_exten_ct.\n                    { inject Hwfct. apply H in H0. apply H0. }\n                    { exists [WrapAny_classes C (methods C k) (fresh_class k C)]. simpl. split.\n                      - auto.\n                      - inject Hwfct. constructor; eauto. intros. intro Hneg.\n                        remember (fresh_class k C) as D. apply fresh_class_not_in in HeqD.  inject HeqD.\n                        apply H3 in Hneg. omega. }                         \n               **** apply fresh_class_not_in in HeqE. destruct HeqE. inject Hwfct. constructor; eauto.\n                    intros fds' mds' Hneg. apply H0 in Hneg. omega.\n        ** constructor. eapply KTREFANY. \n           *** subst s'. apply in_eq.\n        ** subst s'. unfold retains_references. intros. exists aps. apply in_cons. auto. \n        ** auto. \n      * right. apply hastype_in_heap in h. inject h. pose proof H as Hinh. destruct x as [[C' a']].\n        pose proof Hwfh as Hwfh'.\n        destruct Hwfh. apply H1 in H. destruct H. inversion w. subst. inversion H. subst. \n        destruct (incl_dec id (method_names mds) (method_names mds0) Nat.eq_dec). \n        ** left.\n           remember (fresh_ref s a) as a''.\n           remember (fresh_class k0 C') as E. \n           remember ((a'', HCell (E, [a])) :: s) as s'.\n           remember ((Wrap_classes C' mds0 mds E) :: k0) as k'.\n           assert (HCtext: ct_ext k0 k').\n           { subst. exists [Wrap_classes C' mds0 mds (fresh_class k0 C')]. simpl. split.\n             - auto.\n             - unfold Wrap_classes. constructor.\n               + inject Hwfct. auto.\n               + intros. intro Hneg. remember (fresh_class k0 C') as D.\n                 apply fresh_class_not_in in HeqD. inject HeqD. apply H4 in Hneg. omega. }\n           assert (Hrr : retains_references s s').\n           { unfold retains_references. intros. exists aps. subst. apply in_cons. auto. } \n           exists (Ref a''). exists s'. exists k'. repeat split.\n           *** econstructor.\n               { apply Hinh. }\n               { apply HeqE. }\n               { apply fresh_class_not_in in HeqE. destruct HeqE. apply H4 in H6. omega. }\n               { eauto. }\n               { eauto. }\n               { eauto. }\n               { erewrite<- methods_in with (fds:= fds) (mds:=mds); eauto.\n                 erewrite<- methods_in with (fds:= fds0) (mds:=mds0); eauto. }\n               { erewrite<- methods_in; eauto. inject Hwfct. apply H3 in H5. inject H5. auto. }\n               { auto. }\n               { erewrite<- methods_in with (fds:= fds0) (mds:=mds0); eauto.\n                 erewrite<- methods_in with (fds:= fds) (mds:=mds); eauto. }\n           *** econstructor.\n               **** constructor. econstructor; eauto. subst s'. apply in_eq.\n               **** subst s'. econstructor.\n                    { constructor; auto. \n                      intros. intro Hneg. apply fresh_not_in in Heqa''. inject Heqa''. apply H4 in Hneg.\n                      omega. }\n                    { intros. destruct H3.\n                      { inversion H3. subst a'' E aps. split.\n                        { rewrite Heqk'. subst C. unfold Wrap_classes. econstructor. apply in_eq. }\n                        { rewrite Heqk'. simpl. rewrite H8. rewrite (Nat.eqb_refl). constructor.\n                          { ht. ht; eauto. apply in_cons. eauto. }\n                          { constructor. } } }\n                      { destruct Hwfh'. apply H7 in H3. destruct H3. split; eauto.\n                        eapply frwf_exten_ctx; eauto. eapply fieldwf_still_good'; eauto.\n                        erewrite<- ct_fields_eq; eauto. } }\n               **** subst k'. constructor.\n                    { intros. destruct H3.\n                      { inversion H3. eapply correctness_CWrap; eauto. subst C. rewrite HeqE.\n                        apply fresh_is_really_fresh. }\n                      { inject Hwfct. apply H4 in H3. eapply wfct_exten_ct; eauto. } }\n                    { unfold Wrap_classes. constructor.\n                      { inject Hwfct. eauto. }\n                      { intros. intro Hneg. apply fresh_class_not_in in HeqE. destruct HeqE.\n                        apply H4 in Hneg. subst. omega. } }\n           *** ht. ht.\n               { subst. apply in_eq. }\n               { unfold Wrap_classes in Heqk'. rewrite<- HeqE. rewrite Heqk'. eapply subtype_CWrap.\n                 { apply H6. }\n                 { apply H5. }\n                 { apply i0. }\n                 { apply Hwfct. }\n                 { rewrite HeqE. apply fresh_is_really_fresh. } }\n           *** auto.\n           *** auto.\n        ** right. exists EHole. right. right. exists a. exists C'. exists a'. exists i. repeat split.\n           *** apply Hinh.\n           *** erewrite<- methods_in with (fds:= fds) (mds:=mds); eauto.\n               erewrite<- methods_in with (fds:= fds0) (mds:=mds0); eauto.\n  - intros. pose proof (H0 H1 H2 H3).  pose proof (H H1 H2 H3) as H'.\n    destruct H4 as [e1s [a1s [t1s [e2s [t2s H4]]]]].\n    inject H4. inject H6. inject H2. inject H3. inject H4. clear H0.\n    inject H'.\n    + inject H0. exists ((Ref x) :: e1s). exists (x::a1s). exists (Field f t0 :: t1s). \n      exists e2s. exists t2s. repeat split; eauto; constructor; eauto. \n    + exists nil. exists nil. exists nil. exists (e0 :: e1s ++ e2s). exists (Field f t0 :: t1s ++ t2s). simpl.\n      repeat split; eauto; try constructor. \n      * intros. inject H4. inject H0.\n        ** destruct H4 as [? [? [? [? [H6]]]]]. eapply ref_is_finished. apply H0.\n        ** inject H4. inject H0.\n           *** destruct H4 as [? [? [? [? [? [Heq H6]]]]]]. subst. unfold not. intros.\n               destruct x; try (simpl in H0; inject H0).\n           *** destruct H4.\n               **** destruct H0 as [? [? [? [? [Heq H4]]]]]. subst. unfold not. intros.\n                    destruct x; try (simpl in H0; inject H0).\n               **** destruct H0 as [? [? [? [? [H0 [H1' H2']]]]]]. subst. intros H'.\n                    destruct x; try (simpl in H'; inject H').\n      * right. apply H0.\n      * generalize dependent t1s. generalize dependent a1s. induction e1s.\n        ** intros. simpl. pose proof H5. apply sound_destr in H5. apply (same_size_prefix_hts _ _ _ _ _ _ _ h0) in H5.\n           destruct t1s. \n           *** simpl. apply H4.\n           *** simpl in H5. inject H5.\n        ** intros. destruct t1s.\n           *** apply sound_destr in H5. apply (same_size_prefix_hts _ _ _ _ _ _ _ h0) in H5. simpl in H5.\n               inject H5.\n           *** simpl. destruct f0. pose proof H2 as H2'. inject H2. constructor.\n               **** left. exists a0. auto.\n               **** eapply IHe1s; eauto.\n                    ***** inject h0. auto.\n                    ***** inject H1. auto. \n  - intros. subst. exists nil. exists nil. exists nil. exists nil. exists nil. repeat split; eauto; try econstructor.\n    intros. inject H.\nQed.\n\nPrint Assumptions soundness. ", "meta": {"author": "BenChung", "repo": "GradualComparisonArtifact", "sha": "209ad7b2c292b6dd7885f718f1614bf158bb7240", "save_path": "github-repos/coq/BenChung-GradualComparisonArtifact", "path": "github-repos/coq/BenChung-GradualComparisonArtifact/GradualComparisonArtifact-209ad7b2c292b6dd7885f718f1614bf158bb7240/proof/kafka.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2869561482686748}}
{"text": "From ITree Require Import ITree.\nFrom compcert Require Coqlib.\nFrom Paco Require Import paco.\n\nRequire Import sflib.\nRequire Import Axioms StdlibExt IntegersExt.\n\nRequire Import SysSem.\nRequire Import IPModel DiscreteTimeModel IntByteModel.\nRequire Import RTSysEnv.\nRequire Import NWSysModel SyncSysModel AbstAsyncSysModel.\nRequire Import MWITree.\n\nRequire Import List.\nRequire Import Arith ZArith Lia.\nRequire Import Relation_Operators.\n\nGeneralizable Variable sysE.\n\nLocal Opaque Int.max_signed Int64.max_unsigned.\n\n(* SpecNode: connects (inner) sync_node and async network *)\nModule AbstMW.\n\n  Section NODE.\n    (* Variable msgT: Set. *)\n    Context `{sysE: Type -> Type}.\n    Context `{SystemEnv}.\n    Let msgT: Set := bytes.\n    Let t := @SNode.t sysE msgT.\n\n    Inductive stage_t: Set :=\n    | Ready\n    | Running (sh: list bool)\n    .\n\n    Inductive istate_t {node: t} : Type :=\n    | Off (* (outb: list (ip_t(*dip*) * bytes * nat)) *)\n    | Prep\n        (* (rcv_open: bool) *)\n        (to_join: list Tid)\n        (join_time_limit: nat)\n        (inbp: list Packet.msg_t)\n        (ast: node.(SNode.app_state))\n    | On\n        (sytm: nat)\n        (inbp: list Packet.msg_t)\n        (inbm: list msgT?)\n        (* (outb: list (ip_t(*dip*) * bytes * nat)) *)\n        (stage: stage_t)\n        (ast: node.(SNode.app_state))\n    .\n\n    Record state: Type :=\n      State {\n          task_id: Tid ;\n          ip_addr: ip_t ;\n          snode: t ;\n          istate: @istate_t snode ;\n        }.\n\n    Inductive istate_wf (snode: t)\n      : @istate_t snode -> Prop :=\n    | IStateWf_Off\n      : istate_wf snode Off\n    | IStateWf_Prep\n        mids fsytm inbp ast\n        (VALID_MCAST_IDS: Forall valid_mcast_id mids)\n      : istate_wf snode (Prep mids fsytm inbp ast)\n    | IStateWf_OnReady\n        sytm inbp inbm ast\n      : istate_wf snode (On sytm inbp inbm Ready ast)\n    | IStateWf_On\n        sytm inbp inbm sh ast\n        (RUNNING_SYTM_UB: sytm < MAX_TIME)\n        (SEND_HIST_LENGTH: length sh = num_tasks)\n      : istate_wf snode (On sytm inbp inbm (Running sh) ast)\n    .\n\n    (* TODO: define wf for each case *)\n    Inductive state_wf (tid: Tid): state -> Prop :=\n      StateWf\n        ip snode ist\n        (TASK_ID_IP: task_id_ip tid ip)\n        (* (WF_SNODE: SNode.wf imcasts snode) *)\n        (WF_IST: istate_wf snode ist)\n      : state_wf tid (State tid ip snode ist).\n\n    Definition init_inbox : list msgT? :=\n      List.repeat None (length task_ips).\n\n    Lemma init_inbox_length\n      : length init_inbox = num_tasks.\n    Proof.\n      unfold init_inbox.\n      rewrite repeat_length. ss.\n    Qed.\n\n    Lemma init_inbox_nth\n          n\n          (VALID_N: n < num_tasks)\n      : nth_error init_inbox n = Some None.\n    Proof.\n      apply repeat_nth_error_Some. ss.\n    Qed.\n\n    Lemma filtermap_init_inbox\n      : filtermap id init_inbox = [].\n    Proof.\n      unfold init_inbox.\n      apply filtermap_nil.\n      intros a IN.\n      eapply repeat_spec in IN. ss.\n    Qed.\n\n\n    Definition update_msg (ims: list (msgT?))\n               (sid: Tid) (msg: msgT)\n      : list (msgT?) :=\n      replace_nth ims sid (Some msg).\n\n    Definition parse_pld (pld: bytes)\n      : (nat * Tid * msgT)? :=\n      if length pld <? pld_size\n      then None else parse_msg (firstn pld_size pld).\n\n    Definition fetch_one_msg (sytm: nat)\n               (pm: Packet.msg_t)\n               (inbs: list (msgT?) * list (msgT?))\n      : list (msgT?) * list (msgT?) :=\n      let sytm_nxt := sytm + period in\n      (* if negb (Packet.dest_port pm =? port)%nat *)\n      (* then inbs *)\n      match parse_pld (Packet.payload pm) with\n      | None => inbs\n      | Some (dtm, tid_s, msg) =>\n        let (inbc, inbn) := inbs in\n        if (dtm =? sytm) then\n          (update_msg inbc tid_s msg, inbn)\n        else if (dtm =? sytm_nxt) then\n               (inbc, update_msg inbn tid_s msg)\n             else inbs\n      end.\n\n    Definition fetch_msgs (sytm: nat)\n               (inbp: list Packet.msg_t)\n               (inbc: list msgT?)\n      : list msgT? * list msgT? * list Packet.msg_t :=\n      let inbn := init_inbox in\n      process_firstn\n        (fetch_one_msg sytm)\n        inbp (inbc, inbn) (length task_ips * 4).\n\n    Definition srl_pm (sytm_d: nat) (tid_s: nat)\n               (tid_d: Tid) (msg: msgT)\n      : Packet.t :=\n      (* if (tid_d <? num_tasks + num_mcasts) then *)\n      let ip_s := tid2ip tid_s in\n      let ip_d := tid2ip tid_d in\n      let rmsg := resize_bytes msg_size msg in\n      let pld := serialize_msg sytm_d tid_s rmsg in\n      Packet.Msg (Packet.mkMsg ip_s ip_d port pld).\n    (* else None. *)\n\n    Lemma wf_srl_pm\n          sytm tid tid_d msg\n          (* (RANGE_TID: IntRange.sint8 tid) *)\n          (* (RANGE_SYTM: IntRange.uint64 sytm) *)\n      : Packet.wf (srl_pm sytm tid tid_d msg).\n    Proof.\n      unfold srl_pm.\n      econs. econs. ss.\n      hexploit serialize_msg_size_lt_maxlen.\n      { reflexivity. }\n      2: { intro LE. apply LE. }\n      erewrite resize_bytes_length; eauto.\n    Qed.\n\n    Definition check_and_send\n               (sytm: nat) (tid: Tid)\n               (sh: list bool) (om: (Tid * msgT)?)\n      : list bool * Packet.t? :=\n      match om with\n      | None => (sh, None)\n      | Some (tid_d, msg) =>\n        match check_send_hist sh tid_d with\n        | None => (sh, None)\n        | Some sh' =>\n          (sh', Some (srl_pm (sytm + period) tid tid_d msg))\n        end\n      end.\n\n    Inductive istep\n              (tm: DTime.t)\n              (tid: Tid) (ip: ip_t)\n              (node: t)\n      : @istate_t node -> tsp * events (nbE +' sysE) -> Packet.t ? ->\n        @istate_t node -> Prop :=\n    | IStep_Fail st\n        (* outb outb' opkt *)\n        (* (OUTPUT: age_outbox ip outb = (outb', opkt)) *)\n      : istep tm tid ip node\n              st (Z0, []) None Off\n\n    | IStep_TurnOn\n        cbt jtl (* fsytm *)\n        ast_i mids_j\n        (CBT_LB: period <= cbt)\n        (CUR_BASE_TIME: cbt = get_skwd_base_time period tm)\n        (* (SYNC_TIME: Nat.divide period fsytm) *)\n        (JOIN_BEFORE_START: jtl = cbt + period - max_clock_skew - max_nw_delay)\n        (* (FIRST_SYNC_TIME: fsytm = cbt + period + period) *)\n        (RANGE_TM: DTime.of_ns (cbt - max_clock_skew) < tm\n                   < DTime.of_ns jtl)\n        (ABST_INIT_STATE: SNode.init_app_state _ ast_i)\n        (MCAST_IPS_TO_JOIN: mids_j = get_mcast_of tid)\n      : istep tm tid ip node\n              Off (Z0, []) None\n              (Prep mids_j jtl [] ast_i)\n\n    | IStep_Prep_Internal\n        jtl inbp ast mids_j\n        (BEFORE_LIMIT: tm < DTime.of_ns jtl)\n      : istep tm tid ip node\n              (Prep mids_j jtl inbp ast) (Z0, []) None\n              (Prep mids_j jtl inbp ast)\n    | IStep_Prep_SendJoin\n        mid_j mids_j' jtl inbp ast mcm\n        (BEFORE_LIMIT: tm < DTime.of_ns jtl)\n        (MCAST_MEMBER: mcm = (tid2ip mid_j, ip))\n      : istep tm tid ip node\n              (Prep (mid_j::mids_j') jtl inbp ast)\n              (Z0, []) (Some (Packet.MCast mcm))\n              (Prep mids_j' jtl inbp ast)\n    | IStep_Prep_Complete\n        jtl sytm inbp inbm ast\n        (BEFORE_LIMIT: tm < DTime.of_ns jtl)\n        (JOIN_BEFORE_START: sytm = jtl + max_clock_skew +\n                                   max_nw_delay + period)\n        (INIT_INBOX: inbm = init_inbox)\n      : istep tm tid ip node\n              (Prep [] jtl inbp ast) (Z0, []) None\n              (On sytm inbp inbm Ready ast)\n\n    | IStep_OnStay\n        sytm inbp inbm stg ast\n        (TIME_UB: tm < DTime.of_ns (sytm + period - max_clock_skew - max_nw_delay))\n      : istep tm tid ip node\n              (On sytm inbp inbm stg ast)\n              (Z0, []) None\n              (On sytm inbp inbm stg ast)\n\n    | IStep_PeriodBegin\n        sytm inbp inbm ast\n        inbc inbn inbp' ast' sh_i\n        (SYTM_BELOW_MAX_TIME: sytm < MAX_TIME)\n        (SYNC_TIME: sytm = get_skwd_base_time period tm)\n        (RANGE_TIME: DTime.of_ns (sytm - max_clock_skew) < tm < DTime.of_ns (sytm + period - max_clock_skew - max_nw_delay))\n        (FETCH_MSGS: fetch_msgs sytm inbp inbm =\n                     (inbc, inbn, inbp'))\n        (PERIOD_BEGIN: node.(SNode.period_begin) (Z.of_nat sytm) inbc ast ast')\n        (SEND_HIST: sh_i = List.repeat false num_tasks)\n        (* (NEXT_SYNC_TIME: nsytm = sytm + period) *)\n      : istep tm tid ip node\n              (On sytm inbp inbm Ready ast)\n              (Z0, []) None\n              (On sytm inbp' inbn (Running sh_i) ast')\n\n    | IStep_Running_Go\n        inbp inbm sh ast ast1\n        oe om sh' ast' opkt\n        sytm (* nsytm *) es zsytm\n        (TIME_UB:  tm < DTime.of_ns (sytm + period - max_clock_skew - max_nw_delay))\n        (TAU_STEPS: AANode.sh_tau_steps sh node ast ast1)\n        (ISTEP: SNode.istep node ast1 oe om ast')\n        (CHECK_SEND: check_and_send sytm tid sh om = (sh', opkt))\n        (EVTS: es = opt2list oe)\n        (TIMESTAMP: zsytm = Z.of_nat sytm)\n      : istep tm tid ip node\n              (On sytm inbp inbm (Running sh) ast)\n              (zsytm, es) opkt\n              (On sytm inbp inbm (Running sh') ast')\n\n    | IStep_Done\n        sytm inbp inbm sh ast ast_f nsytm\n        (TIME_UB: tm < DTime.of_ns (sytm + period - max_clock_skew - max_nw_delay))\n        (NEXT_SYNC_TIME: nsytm = sytm + period)\n        (TAU_STEPS: AANode.sh_tau_steps sh node ast ast_f)\n        (* (TAU_STEPS: clos_refl_trans *)\n        (*               _ (SNode.app_step node) ast ast_f) *)\n        (PERIOD_END: node.(SNode.period_end) ast_f)\n      : istep tm tid ip node\n              (On sytm inbp inbm (Running sh) ast)\n              (Z0, []) None\n              (On nsytm inbp inbm Ready ast_f)\n    .\n\n    Definition filter_port dpms_f1: list Packet.msg_t :=\n      filter (fun pm : Packet.msg_t =>\n                Packet.dest_port pm =? port) dpms_f1.\n\n    Definition accept_packets {node: t}\n               (* (tm: DTime.t) *)\n               (pms: list Packet.msg_t)\n               (ist: @istate_t node)\n      : istate_t :=\n      let pms' := filter_port pms in\n      (* filter (fun pm => Packet.dest_port pm =? port) pms in *)\n      match ist with\n      | Prep mids tm inbp ast =>\n        Prep mids tm (inbp ++ pms') ast\n      | On sytm inbp inbm stg ast =>\n        On sytm (inbp ++ pms') inbm stg ast\n      | Off => Off\n      end.\n\n    Inductive step (tm: DTime.t) (dpms: list Packet.msg_t)\n      : state -> tsp * events (nbE +' sysE) -> Packet.t ? ->\n        state -> Prop :=\n      Step\n        tid ip node ist ist1\n        tes op ist'\n        (ACCEPT_PACKETS: ist1 = accept_packets dpms ist)\n        (ISTEP: istep tm tid ip node\n                      ist1 tes op ist')\n      : step tm dpms\n             (State tid ip node ist) tes op\n             (State tid ip node ist').\n\n    Lemma wf_accept_prsv\n          pms node ist\n          (* (WF_PMS: Forall Packet.msg_wf pms) *)\n          (WF_IST: istate_wf node ist)\n      : istate_wf node (accept_packets pms ist).\n    Proof.\n      inv WF_IST; econs; ss.\n    Qed.\n\n    Lemma wf_istep_prsv\n          tm tid ip node\n          ist tes op ist'\n          (TASK_ID_IP: task_id_ip tid ip)\n          (ISTEP: istep tm tid ip node\n                        ist tes op ist')\n          (WF_IST: istate_wf node ist)\n      : <<WF_OPKT: option_rel1 Packet.wf op>> /\\\n        <<WF_IST': istate_wf node ist'>>.\n    Proof.\n      inv WF_IST.\n      - inv ISTEP; ss.\n        + esplits; ss. econs.\n        + esplits; ss. econs.\n          apply Forall_forall.\n          intros mid IN.\n          hexploit get_mcast_of_spec; eauto. i. des.\n          r. esplits; eauto.\n          unfold num_mcasts.\n          eapply nth_error_Some. congruence.\n      - inv ISTEP; ss.\n        + esplits; ss. econs.\n        + esplits; ss. econs. ss.\n        + inv VALID_MCAST_IDS.\n          esplits; ss.\n          * econs. econs; ss.\n            { hexploit valid_mcast_id_ip; eauto. i.\n              hexploit mcast_id_ip_comput; eauto. i. des.\n              eauto. }\n            { hexploit task_id_ip_comput; eauto. i. des.\n              eauto. }\n          * econs; eauto.\n        + esplits; ss. econs.\n      - inv ISTEP.\n        + esplits; ss. econs.\n        + esplits; ss. econs.\n        + esplits; ss. econs; ss.\n          rewrite repeat_length. ss.\n      - inv ISTEP; ss.\n        + esplits; ss. econs.\n        + esplits; ss. econs; ss.\n        + unfold check_and_send in CHECK_SEND.\n          destruct om as [ [tid_d m] |].\n          2: { clarify.\n               esplits; ss.\n               econs; eauto. }\n          destruct (check_send_hist sh tid_d) eqn:SH.\n          2: { clarify.\n               esplits; ss.\n               econs; eauto. }\n          clarify.\n          apply check_send_hist_Some in SH; eauto.\n          esplits.\n          { apply wf_srl_pm. }\n          { econs; ss.\n            des; ss.\n          }\n        + esplits; ss. econs.\n    Qed.\n\n    Lemma wf_prsv\n          tm dpms st tes op st' tid\n          (STEP: step tm dpms st tes op st')\n          (WF_STATE: state_wf tid st)\n      : state_wf tid st' /\\\n        option_rel1 Packet.wf op.\n    Proof.\n      inv WF_STATE.\n      inv STEP; ss. existT_elim. subst.\n      hexploit wf_istep_prsv; eauto.\n      { eapply wf_accept_prsv; eauto. }\n      i. des.\n      split; ss.\n    Qed.\n\n    Lemma istep_progress\n          tm tid ip node ist\n      : exists tes op ist',\n        istep tm tid ip node\n              ist tes op ist'.\n    Proof.\n      esplits. econs 1.\n    Qed.\n\n    Lemma step_progress\n          tm dpms st\n      : exists tes op st',\n        step tm dpms st tes op st'.\n    Proof.\n      destruct st as [tid ip nd oist].\n      hexploit istep_progress; eauto. i. des.\n      esplits. econs; eauto.\n    Qed.\n\n    Lemma wf_init_state tid ip snode\n          (* (WF_SNODE: SNode.wf imcasts snode) *)\n          (TASK_ID_IP: task_id_ip tid ip)\n      : state_wf tid (State tid ip snode Off).\n    Proof.\n      econs; eauto. econs.\n    Qed.\n\n    Definition as_node (tid: Tid) (snode: t)\n      : @Node.t sysE :=\n      let ip := tid2ip tid in\n      Node.mk ip state\n              (fun st => st = State tid ip snode Off) step.\n\n    Lemma safe_node\n          tid (* ip *) snode\n          (* (WF_SNODE: SNode.wf imcasts snode) *)\n      (* (TASK_ID_IP: task_id_ip tid ip) *)\n          (VALID_TASK_ID: valid_task_id tid)\n      : Node.safe (as_node tid snode).\n    Proof.\n      econs; ss.\n      { esplits; eauto. }\n      i. subst.\n\n      eapply valid_task_id_ip in VALID_TASK_ID.\n\n      (* hexploit task_id_ip_comput; eauto. *)\n      (* intros (TID2IP_EQ & IP_LOCAL). *)\n      (* rewrite TID2IP_EQ. *)\n      pose (ip := tid2ip tid).\n      fold ip.\n\n      hexploit (wf_init_state tid ip snode); eauto.\n\n      match goal with\n      | |- _ -> Node.safe_istate _ _ ?st =>\n        generalize st\n      end.\n      revert tm.\n\n      clear VALID_TASK_ID ip.\n      pcofix CIH. i.\n\n      pfold. econs.\n      - i. ss.\n        hexploit step_progress; eauto.\n      - i. ss.\n        hexploit wf_prsv; eauto.\n        intro WF_ST'.\n        i. des.\n        splits; ss.\n        right. apply CIH. eauto.\n    Qed.\n\n  End NODE.\nEnd AbstMW.\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/AbstMW.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.28662952631230626}}
{"text": "Require Import Arith.\nRequire Import ZArith.\nRequire Import List.\nImport ListNotations.\nRequire Import Sorted.\nRequire Import Omega.\nRequire Import Psatz.\n\n\nRequire Import v1.NeutronTactics.\nRequire Import v1.Util.\nRequire Import v1.Multi.\nRequire Import v1.MForall.\nRequire Import v1.ListLemmas.\nRequire Import v1.Wf.\nRequire Import v1.Terminate.\nRequire Import v1.Preservation.\nRequire Import v1.Queue.\nRequire Import v1.System.\nRequire Import v1.SystemWf.\nRequire Import v1.Expr.\nRequire v1.ExprDbl.\nRequire v1.ExprAbs.\n\nRequire Import v1.EpicsTypes.\nRequire Import v1.FloatAux.\nRequire Import v1.FloatAbs.\nRequire Import v1.FloatAbsBase.\nRequire Import v1.Step.\nRequire Import v1.StepAux.\nRequire v1.ControlFlow.\n\nSet Default Timeout 10.\n\nModule Dbl := ExprDbl.\nModule Abs := ExprAbs.\n\n\n\nDefinition D := Dbl.dbl_eval_bits.\nDefinition A := Abs.abs_eval_bits.\n\nInductive ty_rel : Dbl.dbl_tydesc -> Abs.abs_tydesc -> Prop :=\n| TrNil : ty_rel Dbl.Nil Abs.Nil\n| TrDbl : ty_rel Dbl.Dbl Abs.Abs\n.\nHint Constructors ty_rel.\n\n\nDefinition lift (fd : tydesc D -> Type) (fa : tydesc A -> Type) :\n    (forall dty aty, fd dty -> fa aty -> Prop) ->\n    ({ ty : tydesc D & fd ty } -> { ty : tydesc A & fa ty } -> Prop).\nintro P.\nintros dsig asig.\ndestruct dsig as [d d'], asig as [a a'].\neapply P; eassumption.\nDefined.\n\n\nInductive refine_dbl : e_double -> abs_value -> Prop :=\n| RdNone : forall d, refine_dbl d None\n| RdSome : forall d z min max,\n        fwhole_eq d z ->\n        (min <= z <= max)%Z ->\n        refine_dbl d (Some (min, max)).\n\nInductive refine_value : forall dty aty, ty_denote D dty -> ty_denote A aty -> Prop :=\n| RvNil : refine_value Dbl.Nil Abs.Nil tt tt\n| RvDbl : forall d a,\n        refine_dbl d a ->\n        refine_value Dbl.Dbl Abs.Abs d a.\nDefinition refine_value' :\n    ({ ty : tydesc D & ty_denote D ty } -> { ty : tydesc A & ty_denote A ty } -> Prop) :=\n    lift _ _ refine_value.\n\nInductive refine_unop dty1 aty1 :\n    forall dtyR atyR\n        (df : unop_impl _ dty1 dtyR)\n        (af : unop_impl _ aty1 atyR),\n        Prop :=\n| RefineUnop : forall dtyR atyR df af,\n    ty_rel dty1 aty1 ->\n    ty_rel dtyR atyR ->\n    (forall dx1 ax1,\n        refine_value dty1 aty1 dx1 ax1 ->\n        refine_value dtyR atyR (df dx1) (af ax1)) ->\n    refine_unop dty1 aty1 dtyR atyR df af.\nDefinition refine_unop' dty1 aty1 :=\n    lift _ _ (refine_unop dty1 aty1).\n\nInductive refine_binop dty1 aty1 dty2 aty2 :\n    forall dtyR atyR\n        (df : binop_impl _ dty1 dty2 dtyR)\n        (af : binop_impl _ aty1 aty2 atyR),\n        Prop :=\n| RefineBinop : forall dtyR atyR df af,\n    ty_rel dty1 aty1 ->\n    ty_rel dty2 aty2 ->\n    ty_rel dtyR atyR ->\n    (forall dx1 ax1 dx2 ax2,\n        refine_value dty1 aty1 dx1 ax1 ->\n        refine_value dty2 aty2 dx2 ax2 ->\n        refine_value dtyR atyR (df dx1 dx2) (af ax1 ax2)) ->\n    refine_binop dty1 aty1 dty2 aty2 dtyR atyR df af.\nDefinition refine_binop' dty1 aty1 dty2 aty2 :=\n    lift _ _ (refine_binop dty1 aty1 dty2 aty2).\n\nInductive refine_ternop dty1 aty1 dty2 aty2 dty3 aty3 :\n    forall dtyR atyR\n        (df : ternop_impl _ dty1 dty2 dty3 dtyR)\n        (af : ternop_impl _ aty1 aty2 aty3 atyR),\n        Prop :=\n| RefineTernop : forall dtyR atyR df af,\n    ty_rel dty1 aty1 ->\n    ty_rel dty2 aty2 ->\n    ty_rel dty3 aty3 ->\n    ty_rel dtyR atyR ->\n    (forall dx1 ax1 dx2 ax2 dx3 ax3,\n        refine_value dty1 aty1 dx1 ax1 ->\n        refine_value dty2 aty2 dx2 ax2 ->\n        refine_value dty3 aty3 dx3 ax3 ->\n        refine_value dtyR atyR (df dx1 dx2 dx3) (af ax1 ax2 ax3)) ->\n    refine_ternop dty1 aty1 dty2 aty2 dty3 aty3 dtyR atyR df af.\nDefinition refine_ternop' dty1 aty1 dty2 aty2 dty3 aty3 :=\n    lift _ _ (refine_ternop dty1 aty1 dty2 aty2 dty3 aty3).\n\nInductive refine_varop dty1 aty1 :\n    forall dtyR atyR\n        (df : varop_impl _ dty1 dtyR)\n        (af : varop_impl _ aty1 atyR),\n        Prop :=\n| RefineVarop : forall dtyR atyR df af,\n    ty_rel dty1 aty1 ->\n    ty_rel dtyR atyR ->\n    (forall dx1 ax1,\n        Forall2 (refine_value dty1 aty1) dx1 ax1 ->\n        refine_value dtyR atyR (df dx1) (af ax1)) ->\n    refine_varop dty1 aty1 dtyR atyR df af.\nDefinition refine_varop' dty1 aty1 :=\n    lift _ _ (refine_varop dty1 aty1).\n\nInductive refine_state_fn :\n    forall dtyR atyR\n        (df : state_fn D 12 (ty_denote D dtyR))\n        (af : state_fn A 12 (ty_denote A atyR)),\n        Prop :=\n| RefineStateFn : forall dtyR atyR df af,\n    ty_rel dtyR atyR ->\n    (forall dsv dsx asv asx dsv' dsx' dr asv' asx' ar,\n        MForall2 (refine_value _ _) dsv asv ->\n        MForall2 (refine_value _ _) dsx asx ->\n        df dsv dsx = (dsv', dsx', dr) ->\n        af asv asx = (asv', asx', ar) ->\n        MForall2 (refine_value _ _) dsv' asv' /\\\n        MForall2 (refine_value _ _) dsx' asx' /\\\n        refine_value _ _ dr ar) ->\n    refine_state_fn dtyR atyR df af.\nDefinition refine_state_fn' :=\n    lift _ _ (refine_state_fn).\n\nInductive refine_state_fn_list :\n    forall dtyR atyR\n        (df : state_fn D 12 (list (ty_denote D dtyR)))\n        (af : state_fn A 12 (list (ty_denote A atyR))),\n        Prop :=\n| RefineStateFnList : forall dtyR atyR df af,\n    ty_rel dtyR atyR ->\n    (forall dsv dsx asv asx dsv' dsx' drs asv' asx' ars,\n        MForall2 (refine_value _ _) dsv asv ->\n        MForall2 (refine_value _ _) dsx asx ->\n        df dsv dsx = (dsv', dsx', drs) ->\n        af asv asx = (asv', asx', ars) ->\n        MForall2 (refine_value _ _) dsv' asv' /\\\n        MForall2 (refine_value _ _) dsx' asx' /\\\n        Forall2 (refine_value _ _) drs ars) ->\n    refine_state_fn_list dtyR atyR df af.\nDefinition refine_state_fn_list' :=\n    lift _ _ (refine_state_fn_list).\n\nInductive refine_state_fn_noxvar :\n    forall dtyR atyR\n        (df : state_fn_noxvar D 12 (ty_denote D dtyR))\n        (af : state_fn_noxvar A 12 (ty_denote A atyR)),\n        Prop :=\n| RefineStateFnNoXVar : forall dtyR atyR df af,\n    ty_rel dtyR atyR ->\n    (forall dsv asv dsv' dr asv' ar,\n        MForall2 (refine_value _ _) dsv asv ->\n        df dsv = (dsv', dr) ->\n        af asv = (asv', ar) ->\n        MForall2 (refine_value _ _) dsv' asv' /\\\n        refine_value _ _ dr ar) ->\n    refine_state_fn_noxvar dtyR atyR df af.\nDefinition refine_state_fn_noxvar' :=\n    lift _ _ (refine_state_fn_noxvar).\n\n\nLemma double_abs_refine : forall d,\n    refine_dbl d (Abs.double_abs d).\nintros. unfold Abs.double_abs. break_match.\n- econstructor.\n  + eapply B2Z_safe_correct. eassumption.\n  + omega.\n- constructor.\nQed.\n\nLemma convert_lit_refine : forall x,\n    refine_value' (convert_lit D x) (convert_lit A x).\nintros. simpl.  constructor. eauto using double_abs_refine.\nQed.\n\nLocal Hint Resolve (tydesc_eq_dec D) : eq_dec.\nLocal Hint Resolve (tydesc_eq_dec A) : eq_dec.\n\n\n\nLemma abs_bool_refine : forall d,\n    (d = zero \\/ d = one) ->\n    refine_dbl d Abs.abs_bool.\nintros0 Hor. destruct Hor.\n- econstructor.\n  + subst. eapply fwhole_eq_Z2B.\n    eapply Z.pow_pos_nonneg; omega.\n  + omega.\n\n- econstructor.\n  + subst. eapply fwhole_eq_Z2B.\n    rewrite Z.abs_eq by omega.\n    replace 1 with (1 ^ (53 - 1)) at 1 by (eapply Z.pow_1_l; omega).\n    eapply Z.pow_lt_mono_l; omega.\n  + omega.\nQed.\n\nLemma unop_denote_refine : forall op dty1 aty1 dden,\n    ty_rel dty1 aty1 ->\n    unop_denote D op dty1 = Some dden ->\n    exists aden,\n        unop_denote A op aty1 = Some aden /\\\n        refine_unop' _ _ dden aden.\ndestruct op, dty1; inversion 1; intros0 Dop;\nsimpl in *; try discriminate.\nall: eexists; split; [ reflexivity | ].\nall: inject_some; unfold refine_unop', lift.\nall: constructor; eauto.\nall: inversion 1; constructor.\nall: fix_existT; subst.\n\n- on >refine_dbl, invc; [ solve [constructor] | ].\n  simpl. unfold Abs.check_overflow. do 2 (break_if; try solve [constructor]).\n  econstructor.\n  + eapply fwhole_eq_Bopp; eauto.\n  + omega.\n\n- eapply abs_bool_refine.  break_if; eauto.\n\nQed.\n\n\nLemma Z_mult_range_max_l : forall x y0 y1 y,\n    y0 <= y <= y1 ->\n    x * y <= Z.max (x * y0) (x * y1).\nintros. destruct (Z_le_gt_dec 0 x).\n- eapply Z.le_trans with (m := x * y1).\n  + eapply Z.mul_le_mono_nonneg_l; omega.\n  + eapply Z.le_max_r.\n- eapply Z.le_trans with (m := x * y0).\n  + eapply Z.mul_le_mono_nonpos_l; omega.\n  + eapply Z.le_max_l.\nQed.\n\nLemma Z_mult_range_max_r : forall x0 x1 x y,\n    x0 <= x <= x1 ->\n    x * y <= Z.max (x0 * y) (x1 * y).\nintros. destruct (Z_le_gt_dec 0 y).\n- eapply Z.le_trans with (m := x1 * y).\n  + eapply Z.mul_le_mono_nonneg_r; omega.\n  + eapply Z.le_max_r.\n- eapply Z.le_trans with (m := x0 * y).\n  + eapply Z.mul_le_mono_nonpos_r; omega.\n  + eapply Z.le_max_l.\nQed.\n\nLemma Z_mult_range_max : forall x0 x1 y0 y1 x y,\n    x0 <= x <= x1 ->\n    y0 <= y <= y1 ->\n    let z1 := Z.max (Z.max (x0 * y0) (x0 * y1)) (Z.max (x1 * y0) (x1 * y1)) in\n    x * y <= z1.\nintros.\neapply Z.le_trans with (m := Z.max (x0 * y) (x1 * y)).\n- eapply Z_mult_range_max_r. eauto.\n- eapply Z.max_le_compat; eapply Z_mult_range_max_l; eauto.\nQed.\n\n\nLemma Z_mult_range_min_l : forall x y0 y1 y,\n    y0 <= y <= y1 ->\n    Z.min (x * y0) (x * y1) <= x * y.\nintros. destruct (Z_le_gt_dec 0 x).\n- eapply Z.le_trans with (m := x * y0).\n  + eapply Z.le_min_l.\n  + eapply Z.mul_le_mono_nonneg_l; omega.\n- eapply Z.le_trans with (m := x * y1).\n  + eapply Z.le_min_r.\n  + eapply Z.mul_le_mono_nonpos_l; omega.\nQed.\n\nLemma Z_mult_range_min_r : forall x0 x1 x y,\n    x0 <= x <= x1 ->\n    Z.min (x0 * y) (x1 * y) <= x * y.\nintros. destruct (Z_le_gt_dec 0 y).\n- eapply Z.le_trans with (m := x0 * y).\n  + eapply Z.le_min_l.\n  + eapply Z.mul_le_mono_nonneg_r; omega.\n- eapply Z.le_trans with (m := x1 * y).\n  + eapply Z.le_min_r.\n  + eapply Z.mul_le_mono_nonpos_r; omega.\nQed.\n\nLemma Z_mult_range_min : forall x0 x1 y0 y1 x y,\n    x0 <= x <= x1 ->\n    y0 <= y <= y1 ->\n    let z0 := Z.min (Z.min (x0 * y0) (x0 * y1)) (Z.min (x1 * y0) (x1 * y1)) in\n    z0 <= x * y.\nintros.\neapply Z.le_trans with (m := Z.min (x0 * y) (x1 * y)).\n- eapply Z.min_le_compat; eapply Z_mult_range_min_l; eauto.\n- eapply Z_mult_range_min_r. eauto.\nQed.\n\n\nLemma Z_mult_range : forall x0 x1 y0 y1 x y,\n    x0 <= x <= x1 ->\n    y0 <= y <= y1 ->\n    let z0 := Z.min (Z.min (x0 * y0) (x0 * y1)) (Z.min (x1 * y0) (x1 * y1)) in\n    let z1 := Z.max (Z.max (x0 * y0) (x0 * y1)) (Z.max (x1 * y0) (x1 * y1)) in\n    z0 <= x * y <= z1.\nintros. split; eauto using Z_mult_range_min, Z_mult_range_max.\nQed.\n\n\nLemma binop_denote_refine : forall op dty1 aty1 dty2 aty2 dden,\n    ty_rel dty1 aty1 ->\n    ty_rel dty2 aty2 ->\n    binop_denote D op dty1 dty2 = Some dden ->\n    exists aden,\n        binop_denote A op aty1 aty2 = Some aden /\\\n        refine_binop' _ _ _ _ dden aden.\ndestruct op, dty1, dty2; do 2 inversion 1; intros0 Dop;\nsimpl in *; try discriminate.\nall: eexists; split; [ reflexivity | ].\nall: inject_some; unfold refine_unop', lift.\nall: constructor; eauto.\nall: do 2 inversion 1; constructor.\nall: fix_existT; subst.\n\n- do 2 (on >refine_dbl, invc; [ solve [constructor] | ]).\n  simpl. unfold Abs.check_overflow. do 2 (break_if; try solve [constructor]).\n  econstructor.\n  + eapply fwhole_eq_Bplus; eauto.\n    rewrite Z_abs_range. change (53 - 1) with 52. omega.\n  + omega.\n\n- do 2 (on >refine_dbl, invc; [ solve [constructor] | ]).\n  simpl. unfold Abs.check_overflow. do 2 (break_if; try solve [constructor]).\n  econstructor.\n  + eapply fwhole_eq_Bminus; eauto.\n    rewrite Z_abs_range. change (53 - 1) with 52. omega.\n  + omega.\n\n- do 2 (on >refine_dbl, invc; [ solve [constructor] | ]).\n  simpl. unfold Abs.check_overflow. do 2 (break_if; try solve [constructor]).\n  econstructor.\n  + eapply fwhole_eq_Bmult; eauto.\n    rewrite Z_abs_range. change (53 - 1) with 52.\n    forward eapply Z_mult_range with (x := z) (y := z0); eauto.\n    cbv zeta in *. omega.\n  + eapply Z_mult_range; eauto.\n\n- constructor.\n\n- eapply abs_bool_refine.  unfold Dbl.b64_ge. do 2 (break_match; eauto).\n- eapply abs_bool_refine.  unfold Dbl.b64_gt. do 2 (break_match; eauto).\n- eapply abs_bool_refine.  unfold Dbl.b64_le. do 2 (break_match; eauto).\n- eapply abs_bool_refine.  unfold Dbl.b64_lt. do 2 (break_match; eauto).\n- eapply abs_bool_refine.  unfold Dbl.b64_ne. do 2 (break_match; eauto).\n- eapply abs_bool_refine.  unfold Dbl.b64_eq. do 2 (break_match; eauto).\n\n- eapply abs_bool_refine.  unfold Dbl.b64_and. do 2 (break_if; eauto).\n- eapply abs_bool_refine.  unfold Dbl.b64_or. do 2 (break_if; eauto).\n\nQed.\n\n\nLemma ternop_denote_refine : forall op dty1 aty1 dty2 aty2 dty3 aty3 dden,\n    ty_rel dty1 aty1 ->\n    ty_rel dty2 aty2 ->\n    ty_rel dty3 aty3 ->\n    ternop_denote D op dty1 dty2 dty3 = Some dden ->\n    exists aden,\n        ternop_denote A op aty1 aty2 aty3 = Some aden /\\\n        refine_ternop' _ _ _ _ _ _ dden aden.\ndestruct op, dty1, dty2, dty3; do 3 inversion 1; intros0 Dop;\nsimpl in *; try discriminate.\nall: eexists; split; [ reflexivity | ].\nall: inject_some; unfold refine_unop', lift.\nall: constructor; eauto.\nall: do 3 inversion 1; constructor.\nall: fix_existT; subst.\n\n- on (refine_dbl dx2 _), invc; [ solve [constructor] | ].\n  on (refine_dbl dx3 _), invc; [ solve [constructor] | ].\n  simpl. unfold Abs.check_overflow. do 3 (break_if; try solve [constructor]).\n  + econstructor; eauto. lia.\n  + econstructor; eauto. lia.\n\nQed.\n\n\n\nLemma min_fwhole_eq : forall dx dy zx zy,\n    fwhole_eq dx zx ->\n    fwhole_eq dy zy ->\n    fwhole_eq (Dbl.b64_min dx dy) (Z.min zx zy).\nintros0 Hx Hy.\nunfold Dbl.b64_min, Z.min. break_match; [ break_match | ].\nall: erewrite fwhole_eq_Bcompare in * by eauto.\n4: discriminate.\nall: inject_some; find_rewrite.\nall: eauto.\n\n(* Eq case needs a bit more. *)\nrewrite Z.compare_eq_iff in *. subst. auto.\nQed.\n\nLemma max_fwhole_eq : forall dx dy zx zy,\n    fwhole_eq dx zx ->\n    fwhole_eq dy zy ->\n    fwhole_eq (Dbl.b64_max dx dy) (Z.max zx zy).\nintros0 Hx Hy.\nunfold Dbl.b64_max, Z.max. break_match; [ break_match | ].\nall: erewrite fwhole_eq_Bcompare in * by eauto.\n4: discriminate.\nall: inject_some; find_rewrite.\nall: eauto.\nQed.\n\nLemma min_refine : forall dx dy ax ay,\n    refine_dbl dx ax ->\n    refine_dbl dy ay ->\n    refine_dbl (Dbl.b64_min dx dy) (Abs.abs_min ax ay).\nintros0 Hx Hy.\ninvc Hx; invc Hy; simpl; try solve [constructor].\nunfold Abs.check_overflow. do 2 (break_if; try solve [constructor]).\neapply RdSome with (z := Z.min z z0).\n- eapply min_fwhole_eq; eauto.\n- lia.\nQed.\n\nLemma max_refine : forall dx dy ax ay,\n    refine_dbl dx ax ->\n    refine_dbl dy ay ->\n    refine_dbl (Dbl.b64_max dx dy) (Abs.abs_max ax ay).\nintros0 Hx Hy.\ninvc Hx; invc Hy; simpl; try solve [constructor].\nunfold Abs.check_overflow. do 2 (break_if; try solve [constructor]).\neapply RdSome with (z := Z.max z z0).\n- eapply max_fwhole_eq; eauto.\n- lia.\nQed.\n\nLemma minimum_refine : forall dxs axs,\n    Forall2 refine_dbl dxs axs ->\n    refine_dbl (Dbl.b64_minimum dxs) (Abs.abs_minimum axs).\ninduction dxs; intros0 Hfa; invc Hfa; simpl.\n- eapply RdSome with (z := 0).\n  + unfold zero. eapply fwhole_eq_Z2B. eapply Z.pow_pos_nonneg; lia.\n  + lia.\n- eapply min_refine; eauto.\nQed.\n\nLemma maximum_refine : forall dxs axs,\n    Forall2 refine_dbl dxs axs ->\n    refine_dbl (Dbl.b64_maximum dxs) (Abs.abs_maximum axs).\ninduction dxs; intros0 Hfa; invc Hfa; simpl.\n2: on >Forall2, invc.\n- eapply RdSome with (z := 0).\n  + unfold zero. eapply fwhole_eq_Z2B. eapply Z.pow_pos_nonneg; lia.\n  + lia.\n- auto.\n- eapply max_refine; eauto.\nQed.\n\n\nLemma refine_value_dbl : forall dx ax,\n    refine_value Dbl.Dbl Abs.Abs dx ax <->\n    refine_dbl dx ax.\nintros. split; intro Hr.\n- inversion Hr. fix_existT. subst. auto.\n- constructor. auto.\nQed.\n\nLemma refine_value_dbl_list : forall dx ax,\n    Forall2 (refine_value Dbl.Dbl Abs.Abs) dx ax <->\n    Forall2 refine_dbl dx ax.\ninduction dx; intros; split; intro Hr; invc Hr; eauto.\n- rewrite refine_value_dbl in *. rewrite IHdx in *. eauto.\n- rewrite <- refine_value_dbl in *. rewrite <- IHdx in *. eauto.\nQed.\n\nLemma varop_denote_refine : forall op dty1 aty1 dden,\n    ty_rel dty1 aty1 ->\n    varop_denote D op dty1 = Some dden ->\n    exists aden,\n        varop_denote A op aty1 = Some aden /\\\n        refine_varop' _ _ dden aden.\n\ndestruct op, dty1; inversion 1; intros0 Dop;\nsimpl in *; try discriminate.\nall: eexists; split; [ reflexivity | ].\nall: inject_some; unfold refine_varop', lift.\nall: constructor; eauto.\nall: constructor.\n\n- rewrite refine_value_dbl_list in *.\n  eapply minimum_refine; eauto.\n\n- rewrite refine_value_dbl_list in *.\n  eapply maximum_refine; eauto.\nQed.\n\n\nLtac specialize_refinement :=\n    repeat match goal with\n    (* First, try to destruct some applications.  This will fail if the arguments\n       used in the LHS have not been filled in yet, and we will fall through to the\n       spec_evar case below. *)\n    | [ H : forall x, _ |- _ ] =>\n            match type of H with\n            | context [ ?x = (_, _, _) ] =>\n                    match x with\n                    | (_, _, _) => fail 1\n                    | _ => destruct x as [[? ?] ?] eqn:?\n                    end\n            end\n    (* Main case: try to fill in arguments using evar or eassumption *)\n    | [ H : forall x : ?T, _ |- _ ] =>\n            match type of T with\n            | Set => spec_evar H\n            | Prop => \n                    match goal with\n                    | [ H' : _ |- _ ] => specialize (H H'); clear H'\n                    end\n            end\n    (* Also handle @eq premises with reflexivity *)\n    | [ H : _ = _ -> _ |- _ ] => spec H by reflexivity\n    (* Final cleanup: break `exists` and `and`. *)\n    | [ H : exists _, _ |- _ ] => destruct H\n    | [ H : _ /\\ _ |- _ ] => destruct H\n    end.\n\nLemma var_ty_rel : ty_rel (var_ty D) (var_ty A).\nconstructor.\nQed.\n\nLemma xvar_ty_rel : ty_rel (xvar_ty D) (xvar_ty A).\nconstructor.\nQed.\n\nLemma nil_ty_rel : ty_rel (nil_ty D) (nil_ty A).\nconstructor.\nQed.\n\nLemma ty_rel_inj : forall dty aty1 aty2,\n    ty_rel dty aty1 ->\n    ty_rel dty aty2 ->\n    aty1 = aty2.\ndo 2 inversion 1; eauto.\nQed.\n\nLemma ty_rel_nil_sur : forall dty1 dty2,\n    ty_rel dty1 (nil_ty A) ->\n    ty_rel dty2 (nil_ty A) ->\n    dty1 = dty2.\ndo 2 inversion 1; eauto.\nQed.\n\nLemma nil_rel_fwd : forall aty,\n    ty_rel (nil_ty D) aty ->\n    aty = nil_ty A.\nintros. eapply ty_rel_inj; eauto using nil_ty_rel.\nQed.\n\nLemma nil_rel_rev : forall dty,\n    ty_rel dty (nil_ty A) ->\n    dty = nil_ty D.\nintros. eapply ty_rel_nil_sur; eauto using nil_ty_rel.\nQed.\n\n\nLemma unpack_opt_helper1\n    DI DP DR dopt (didx : DI) dval df drhs\n    AI AP AR aopt (aidx : AI) aval af\n        (P : AR -> Prop):\n    unpack_opt (R := DR) dopt df = Some drhs ->\n    dopt = Some (existT DP didx dval) ->\n    aopt = Some (existT AP aidx aval) ->\n    (df didx dval = Some drhs ->\n        exists arhs, af aidx aval = Some arhs /\\ P arhs) ->\n    exists arhs, unpack_opt (R := AR) aopt af = Some arhs /\\ P arhs.\nintros0 Hunpack Hdden Haden Hinner.\nsubst dopt aopt. simpl in *.\neauto.\nQed.\n\nLemma unpack_opt_some_inv : forall I P R (opt : option { x : I & P x }) f rhs\n        (Q : Prop),\n    (forall idx val,\n        opt = Some (existT P idx val) ->\n        f idx val = Some rhs ->\n        Q) ->\n    unpack_opt (R := R) opt f = Some rhs -> Q.\nintros.\ndestruct opt as [ s | ]; try discriminate.\ndestruct s. eauto.\nQed.\n\nLemma unpack_opt_some_inv' : forall I P R (opt : option { x : I & P x }) f rhs\n        (Q : Prop),\n    (forall idx val,\n        opt = Some (existT P idx val) ->\n        Q) ->\n    unpack_opt (R := R) opt f = Some rhs -> Q.\ninversion 2 using unpack_opt_some_inv. eauto.\nQed.\n\nLemma unpack_opt_some_ex\n    I P R opt (idx : I) val f (Q : R -> Prop):\n    opt = Some (existT P idx val) ->\n    (exists rhs, f idx val = Some rhs /\\ Q rhs) ->\n    (exists rhs, unpack_opt (R := R) opt f = Some rhs /\\ Q rhs).\nintros0 Hopt Hinner.\nsubst opt. simpl in *. eauto.\nQed.\n\nLtac handle_unpack_opt :=\n    let dden' := fresh \"dden'\" in\n    let aden' := fresh \"aden'\" in\n    let Hdden := fresh \"Hdden\" in\n    let Haden := fresh \"Haden\" in\n    let dty := fresh \"dty\" in\n    let aty := fresh \"aty\" in\n    let Hex := fresh \"Hex\" in\n    let Hrefine := fresh \"Hrefine\" in\n\n    match goal with\n    | [ H : unpack_opt ?dden ?df = Some _ |-\n        exists aden', unpack_opt ?aden ?af = Some _ /\\ _ ] =>\n\n            eapply unpack_opt_some_inv with (2 := H); clear H;\n            intros dty dden' Hdden H;\n\n            simple refine (let Hex : exists aden', aden = Some aden' /\\ _ aden' := _ in _);\n            [ shelve\n            | eauto (* or defer to caller *)\n            | clearbody Hex;\n              destruct Hex as (aden' & Haden & Hrefine);\n              destruct aden' as [aty aden'];\n              eapply unpack_opt_some_ex; simpl in *; eauto\n            ]\n    end.\n\n\nLemma if_tydesc_eq_dec_inv : forall\n    (T : Set) (A : eval_bits T)\n    (P : tydesc A -> tydesc A -> Type)\n    (ty xty : tydesc A)\n    (x : forall ty xty, P ty xty)\n    (y : forall ty xty, P ty xty)\n    (z : forall ty xty, P ty xty)\n    (Q : tydesc A -> Prop),\n    (x xty xty = z xty xty -> Q xty) ->\n    (ty <> xty ->\n        y ty xty = z ty xty ->\n        Q ty) ->\n    ((if tydesc_eq_dec A ty xty then x ty xty else y ty xty) = z ty xty) -> Q ty.\nintros.\ndestruct (tydesc_eq_dec _ _ _).\n- subst. eauto.\n- eauto.\nQed.\n\nLemma if_tydesc_eq_dec_eq_ex : forall\n    (T : Set) (A : eval_bits T)\n    (ty xty : tydesc A)\n    (R : Type) (f g : tydesc A -> tydesc A -> option R)\n    (Q : R -> Prop),\n    ty = xty ->\n    (exists rhs, f xty xty = Some rhs /\\ Q rhs) ->\n    (exists rhs, (if tydesc_eq_dec A ty xty then f ty xty else g ty xty) = Some rhs /\\ Q rhs).\nintros.\ndestruct (tydesc_eq_dec _ _ _); [ | exfalso; congruence ].\nsubst. auto.\nQed.\n\nLemma if_tydesc_eq_dec_ne_ex : forall\n    (T : Set) (A : eval_bits T)\n    (ty xty : tydesc A)\n    (R : Type) (f g : tydesc A -> tydesc A -> option R)\n    (Q : R -> Prop),\n    ty <> xty ->\n    (exists rhs, g ty xty = Some rhs /\\ Q rhs) ->\n    (exists rhs, (if tydesc_eq_dec A ty xty then f ty xty else g ty xty) = Some rhs /\\ Q rhs).\nintros.\ndestruct (tydesc_eq_dec _ _ _); [ exfalso; congruence | ].\nauto.\nQed.\n\n\nLemma unpack_ty_helper1\n    (DT : Set) (D : eval_bits DT) (DP : forall ty : tydesc D, Type) DR\n        dden dty dden' (df : DP dty -> option DR) drhs\n    (AT : Set) (A : eval_bits AT) (AP : forall ty : tydesc A, Type) AR\n        aden aty aden' (af : AP aty -> option AR)\n        (P : AR -> Prop) :\n    unpack_ty (R := DR) D dty dden df = Some drhs ->\n    dden = Some (existT DP dty dden') ->\n    aden = Some (existT AP aty aden') ->\n    (df dden' = Some drhs ->\n        exists arhs, af aden' = Some arhs /\\ P arhs) ->\n    exists arhs, unpack_ty (R := AR) A aty aden af = Some arhs /\\ P arhs.\nintros0 Hunpack Hdden Haden Hinner.\nsubst dden aden. simpl in *.\ndestruct (tydesc_eq_dec _ dty dty); [ | exfalso; congruence ].\ndestruct (tydesc_eq_dec _ aty aty); [ | exfalso; congruence ].\nfix_eq_rect; eauto using tydesc_eq_dec.\nQed.\n\nLemma unpack_ty_some_ex\n    (T : Set) (A : eval_bits T) (P : forall ty : tydesc A, Type) R\n        den ty den' (f : P ty -> option R)\n        (Q : R -> Prop) :\n    den = Some (existT P ty den') ->\n    (exists rhs, f den' = Some rhs /\\ Q rhs) ->\n    (exists rhs, unpack_ty (R := R) A ty den f = Some rhs /\\ Q rhs).\nintros0 Hden Hinner.\nsubst den. simpl in *.\ndestruct (tydesc_eq_dec _ ty ty); [ | exfalso; congruence ].\nfix_eq_rect; eauto using tydesc_eq_dec.\nQed.\n\nLemma unpack_ty_some_inv : forall\n    (T : Set) (D : eval_bits T) (P : forall ty : tydesc D, Type) R\n        xty den f rhs\n        (Q : Prop),\n    (forall val,\n        den = Some (existT P xty val) ->\n        f val = Some rhs ->\n        Q) ->\n    unpack_ty (R := R) D xty den f = Some rhs -> Q.\nintros0 HQ Hunpack.\ndestruct den as [ s | ]; try discriminate.\ndestruct s. simpl in Hunpack.\ndestruct (tydesc_eq_dec _ _ _); try discriminate.\nsubst xty. fix_eq_rect; eauto using tydesc_eq_dec.\nQed.\n\n\n\nLemma denote'_refine : forall e dden,\n    denote' D e = Some dden ->\n    exists aden,\n        denote' A e = Some aden /\\\n        refine_state_fn' dden aden.\ninduction e using expr_rect_mut with\n    (Pl := fun es => forall ddens,\n        denote'_list D es = Some ddens ->\n        exists adens,\n            denote'_list A es = Some adens /\\\n            refine_state_fn_list' ddens adens);\n[ .. | eauto | eauto ];\nintros0 Hden.\n\nLocal Opaque multi.\nLocal Opaque multi_get.\nLocal Opaque multi_set.\nLocal Opaque A.\nLocal Opaque D.\n\nall: simpl in *; unfold pack_denot in *; inject_some.\nall: try (eexists; split; [reflexivity|]; unfold refine_state_fn', lift).\n\n- constructor.  { constructor. }\n  intros. inject_pair.\n  split; [|split]; auto.\n  + eapply MForall2_get. assumption.\n\n- constructor.  { constructor. }\n  intros. inject_pair.\n  split; [|split]; auto.\n  + eapply MForall2_get. assumption.\n\n- constructor.  { constructor. }\n  intros. inject_pair.\n  split; [|split]; auto.\n  + eapply convert_lit_refine.\n\n- (* Unary *)\n  handle_unpack_opt.\n  handle_unpack_opt.\n    { on >refine_state_fn, invc. eapply unop_denote_refine; eauto. }\n    simpl in *.\n\n  eexists. split; [reflexivity|]. inject_some. simpl.\n\n  constructor.  { on >refine_unop, invc. auto. }\n  intros.  clear IHe.\n\n  on >refine_state_fn, invc.  specialize_refinement.\n    repeat find_rewrite. inject_pair.\n  on >refine_unop, invc.  specialize_refinement.\n\n  eauto.\n\n- (* Binary *)\n  handle_unpack_opt.\n  handle_unpack_opt.\n  handle_unpack_opt.\n    { inv Hrefine. inv Hrefine0. eapply binop_denote_refine; eauto. }\n    simpl in *.\n\n  eexists. split; [reflexivity|]. inject_some. simpl.\n\n  constructor.  { on >refine_binop, invc. auto. }\n  intros.  clear IHe1 IHe2.\n\n  on >(refine_state_fn dty), invc.  specialize_refinement.\n    repeat find_rewrite. inject_pair.\n  on >(refine_state_fn dty0), invc.  specialize_refinement.\n    repeat find_rewrite. inject_pair.\n  on >refine_binop, invc.  specialize_refinement.\n\n  eauto.\n\n- (* Varary *)\n  fold (denote'_list D xs) in *.\n  fold (denote'_list A xs) in *.\n  handle_unpack_opt.\n  handle_unpack_opt.\n    { inv Hrefine. eapply varop_denote_refine; eauto. }\n    simpl in *.\n\n  eexists. split; [reflexivity|]. inject_some. simpl.\n\n  constructor.  { on >refine_varop, invc. auto. }\n  intros.  clear IHe.\n\n  on >refine_state_fn_list, invc.  specialize_refinement.\n    repeat find_rewrite. inject_pair.\n  on >refine_varop, invc.  specialize_refinement.\n\n  eauto.\n\n- (* Assign *)\n\n  (* TODO - put unpack_ty stuff into the handle_unpack_opt tactic *)\n  on _, invc_using unpack_ty_some_inv.\n    destruct (IHe _ **) as ([? ?] & HH & ?). simpl in *.\n    on >refine_state_fn, invc.\n    assert (x = var_ty A) by eauto using ty_rel_inj, var_ty_rel. subst x.\n    eapply unpack_ty_some_ex; eauto.  clear HH.\n\n  eexists. split; [reflexivity|]. inject_some. simpl.\n\n  constructor.  { eauto using nil_ty_rel. }\n  intros.  clear IHe.\n\n  specialize_refinement.\n    repeat find_rewrite. inject_pair.\n\n  split; [|split]; eauto using set_MForall2.\n  + econstructor.\n\n- (* XAssign *)\n\n  on _, invc_using unpack_ty_some_inv.\n    destruct (IHe _ **) as ([? ?] & HH & ?). simpl in *.\n    on >refine_state_fn, invc.\n    assert (x = xvar_ty A) by eauto using ty_rel_inj, xvar_ty_rel. subst x.\n    eapply unpack_ty_some_ex; eauto.  clear HH.\n\n  eexists. split; [reflexivity|]. inject_some. simpl.\n\n  constructor.  { eauto using nil_ty_rel. }\n  intros.  clear IHe.\n\n  specialize_refinement.\n    repeat find_rewrite. inject_pair.\n\n  split; [|split]; eauto using set_MForall2.\n  + econstructor.\n\n- (* Cond *)\n  handle_unpack_opt.\n  handle_unpack_opt.\n  handle_unpack_opt.\n  handle_unpack_opt.\n    { do 3 on >refine_state_fn, invc. eapply ternop_denote_refine; eauto. }\n    simpl in *.\n\n  eexists. split; [reflexivity|]. inject_some. simpl.\n\n  constructor.  { on >refine_ternop, invc. auto. }\n  intros.  clear IHe1 IHe2 IHe3.\n\n  on >(refine_state_fn dty), invc.  specialize_refinement.\n    repeat find_rewrite. inject_pair.\n  on >(refine_state_fn dty0), invc.  specialize_refinement.\n    repeat find_rewrite. inject_pair.\n  on >(refine_state_fn dty1), invc.  specialize_refinement.\n    repeat find_rewrite. inject_pair.\n  on >refine_ternop, invc.  specialize_refinement.\n\n  eauto.\n\n- (* Seq *)\n  handle_unpack_opt.\n  handle_unpack_opt.\n  destruct (tydesc_eq_dec D _ _); [ | destruct (tydesc_eq_dec D _ _); [ | discriminate Hden ] ].\n\n  + assert (aty = nil_ty A). { eapply nil_rel_fwd. invc Hrefine. auto. }\n    subst aty. destruct (tydesc_eq_dec A _ _); [ | exfalso; congruence ].\n    eexists. split; [ reflexivity | ]. inject_some. simpl.\n    constructor. { invc Hrefine0. auto. } intros.\n\n    on >(refine_state_fn (nil_ty D)), invc.  specialize_refinement.\n      repeat find_rewrite. inject_pair.\n    on >(refine_state_fn dty0), invc.  specialize_refinement.\n      repeat find_rewrite. inject_pair.\n    auto.\n\n  + assert (aty <> nil_ty A).\n      { on (dty <> _), contradict. eapply nil_rel_rev. invc Hrefine. auto. }\n    destruct (tydesc_eq_dec A _ _); [ exfalso; congruence | ].\n    assert (aty0 = nil_ty A). { eapply nil_rel_fwd. invc Hrefine0. auto. }\n    subst aty0. destruct (tydesc_eq_dec A _ _); [ | exfalso; congruence ].\n    eexists. split; [ reflexivity | ]. inject_some. simpl.\n    constructor. { invc Hrefine. auto. } intros.\n\n    on >(refine_state_fn dty), invc.  specialize_refinement.\n      repeat find_rewrite. inject_pair.\n    on >(refine_state_fn (nil_ty D)), invc.  specialize_refinement.\n      repeat find_rewrite. inject_pair.\n    auto.\n\n- (* nil *) discriminate.\n\n- destruct es as [| e' es ].\n\n  + (* singleton list *)\n    handle_unpack_opt.\n\n    eexists. split; [reflexivity|]. inject_some. simpl.\n\n    constructor.  { on >refine_state_fn, invc. auto. }\n    intros.  clear IHe IHe0.\n\n    on >(refine_state_fn dty), invc.  specialize_refinement.\n      repeat find_rewrite. inject_pair.\n    auto.\n\n  + (* singleton list *)\n    remember (e' :: es) as e'_es.\n    handle_unpack_opt.\n    handle_unpack_opt.\n    destruct (tydesc_eq_dec _ _ _); try discriminate.\n      subst dty0.\n\n    destruct (tydesc_eq_dec _ _ _); cycle 1.\n      { on (aty <> _), contradict.\n        invc Hrefine. invc Hrefine0.\n        eapply ty_rel_inj; eauto. }\n      subst aty0.\n\n    eexists. split; [reflexivity|]. inject_some. simpl.\n\n    constructor.  { on >refine_state_fn, invc. auto. }\n    intros.  clear IHe IHe0.\n\n    on >(refine_state_fn dty), invc.  specialize_refinement.\n      repeat find_rewrite. inject_pair.\n    on >(refine_state_fn_list dty), invc.  specialize_refinement.\n      repeat find_rewrite. inject_pair.\n    auto.\n\nQed.\n\nLocal Transparent A.\nLocal Transparent D.\n\nLemma denote_refine : forall e dden,\n    Dbl.denote e = Some dden ->\n    exists aden,\n        Abs.denote e = Some aden /\\\n        refine_state_fn_noxvar Dbl.Dbl Abs.Abs dden aden.\nintros. unfold Dbl.denote in *.\n\non _, invc_using unpack_ty_some_inv.\nforward eapply denote'_refine as HH; eauto.  destruct HH as (aden & Haden & Hrefine).\n  simpl in Hrefine. destruct aden as [aty aden].\n  change e_double with (ty_denote D Dbl.Dbl) in val.\n  assert (aty = Abs.Abs).  { inv Hrefine. on >ty_rel, invc. auto. }  subst aty.\nunfold Abs.denote.\neapply unpack_ty_some_ex; eauto.\n\neexists. split; [ reflexivity | ]. inject_some.\nconstructor. { invc Hrefine. auto. }  intros.\nchange (tt, tt, tt, tt, tt, tt, tt, tt, tt, tt, tt, tt) with (multi_rep 12 tt) in *.\n\nassert (MForall2 (refine_value (xvar_ty D) (xvar_ty A)) (multi_rep 12 tt) (multi_rep 12 tt)).\n  { eapply rep_MForall2. constructor. }\n\non >refine_state_fn, invc.  specialize_refinement.\n  repeat find_rewrite. inject_pair.\nauto.\nQed.\n\n\nLemma refine_state_fn_noxvar_dbl_abs_inv : forall df af,\n    refine_state_fn_noxvar Dbl.Dbl Abs.Abs df af ->\n    (forall dsv asv dsv' dr asv' ar,\n        MForall2 (refine_value _ _) dsv asv ->\n        df dsv = (dsv', dr) ->\n        af asv = (asv', ar) ->\n        MForall2 (refine_value _ _) dsv' asv' /\\\n        refine_value _ _ dr ar).\ninversion 1. auto.\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/ExprAbsProofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.28661014500743104}}
{"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.\nFrom iris.prelude Require Import options.\n\nFrom iris.bi Require Import ascii.\n\nUnset Mangle Names.\n\n(* Remove this and the [Set Printing Raw Literals.] below once we require Coq\n8.14. *)\nSet Warnings \"-unknown-option\".\n\nSection base_logic_tests.\n  Context {M : ucmra}.\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; first 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 `{!invGS_gen hlc Σ, !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 `{!invGS_gen hlc Σ}.\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(* Make sure these all parse as they should.\nTo make the [Check] print correctly, we need to set and reset the printing\nsettings each time. *)\nCheck \"p1\".\nLemma p1 : forall P, True -> P |- P.\nProof.\n  Unset Printing Notations. Set Printing Raw Literals. Show. Set Printing Notations. Unset Printing Raw Literals.\nAbort.\n\nCheck \"p2\".\nLemma p2 : forall P, True /\\ (P |- P).\nProof.\n  Unset Printing Notations. Set Printing Raw Literals. Show. Set Printing Notations. Unset Printing Raw Literals.\nAbort.\n\nCheck \"p3\".\nLemma p3 : exists P, P |- P.\nProof.\n  Unset Printing Notations. Set Printing Raw Literals. Show. Set Printing Notations. Unset Printing Raw Literals.\nAbort.\n\nCheck \"p4\".\nLemma p4 : |-@{PROP} exists (x : nat), ⌜x = 0⌝.\nProof.\n  Unset Printing Notations. Set Printing Raw Literals. Show. Set Printing Notations. Unset Printing Raw Literals.\nAbort.\n\nCheck \"p5\".\nLemma p5 : |-@{PROP} exists (x : nat), ⌜forall y : nat, y = y⌝.\nProof.\n  Unset Printing Notations. Set Printing Raw Literals. Show. Set Printing Notations. Unset Printing Raw Literals.\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. Set Printing Raw Literals. Show. Set Printing Notations. Unset Printing Raw Literals.\nAbort.\n\nCheck \"p7\".\nLemma p7 : forall (a : nat), a = 0 -> forall y, True |-@{PROP} ⌜y >= 0⌝.\nProof.\n  Unset Printing Notations. Set Printing Raw Literals. Show. Set Printing Notations. Unset Printing Raw Literals.\nAbort.\n\nCheck \"p8\".\nLemma p8 : forall (a : nat), a = 0 -> forall y, |-@{PROP} ⌜y >= 0⌝.\nProof.\n  Unset Printing Notations. Set Printing Raw Literals. Show. Set Printing Notations. Unset Printing Raw Literals.\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. Set Printing Raw Literals. Show. Set Printing Notations. Unset Printing Raw Literals.\nAbort.\n\nEnd parsing_tests.\n", "meta": {"author": "amintimany", "repo": "iris", "sha": "03eaffa3b28bffc561b93f30a3ba40bab8ae1fd1", "save_path": "github-repos/coq/amintimany-iris", "path": "github-repos/coq/amintimany-iris/iris-03eaffa3b28bffc561b93f30a3ba40bab8ae1fd1/tests/proofmode_ascii.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819591324418, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2866101317296779}}
{"text": "Require Export MicroBFTprops0.\nRequire Export MicroBFTsubs.\nRequire Export MicroBFTbreak.\nRequire Export ComponentSM6.\n\n\nSection MicroBFTcount.\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 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           (s1  : USIG_state)\n           (s2  : LOG_state),\n      In (send_accept (accept req i) l)\n         (M_output_ls_on_this_one_event (MicroBFTlocalSys_new r s s1 s2) 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 *.\n    autorewrite with microbft comp in *.\n    Time microbft_dest_msg Case; simpl in *; tcsp; ginv; repeat smash_microbft2;\n      repndors; tcsp; inversion h0; subst; GC; eauto 4 with microbft.\n  Qed.\n\n  Lemma operation_inc_counter_ls_step :\n    forall {eo    : EventOrdering}\n           (e     : Event)\n           (r     : Request)\n           (i     : nat)\n           (l     : list name)\n           (s     : Rep)\n           (ls    : MicroBFTls),\n      M_run_ls_before_event (MicroBFTlocalSys s) e = Some ls\n      -> In (send_accept (accept r (S i)) l) (M_output_ls_on_this_one_event ls e)\n      -> i = 0\n         \\/\n         exists r' l' e' ls',\n           e' ⊏ e\n           /\\ M_run_ls_before_event (MicroBFTlocalSys s) e' = Some ls'\n           /\\ In (send_accept (accept r' i) l') (M_output_ls_on_this_one_event ls' e').\n  Proof.\n    introv eqls out.\n    applydup M_run_ls_before_event_ls_is_microbft in eqls; exrepnd; subst.\n    applydup accepted_if_executed_previous_step in out; ginv.\n    clear r l out.\n    revert s s0 s1 s2 eqls.\n\n    induction e as [e ind] using predHappenedBeforeInd;[]; introv eqls.\n    rewrite M_run_ls_before_event_unroll in eqls.\n    destruct (dec_isFirst e) as [d|d]; ginv.\n\n    { inversion eqls; subst; GC; simpl; tcsp. }\n\n    apply map_option_Some in eqls; exrepnd; rev_Some.\n    applydup M_run_ls_before_event_ls_is_microbft in eqls1; exrepnd; subst.\n\n    dup eqls1 as eqbef.\n    rename eqls1 into eqbef_backup.\n    eapply ind in eqbef; eauto 3 with eo;[].\n\n    apply map_option_Some in eqls0; exrepnd; simpl in *; rev_Some.\n    autorewrite with microbft comp in *.\n    Time microbft_dest_msg Case;\n      repeat (autorewrite with microbft comp in *; simpl in *; smash_microbft2);\n      try (complete (clear eqbef_backup; repndors; tcsp; [];\n                       right; exrepnd; microbft_finish_eexists));\n      [|].\n\n    { Case \"Commit\".\n\n      right.\n\n      applydup invalid_commit_false_implies in Heqx as w.\n      apply valid_commit_implies_executed_prior in w.\n      apply executed_prior_counter_implies_eq_S in w.\n\n      exists (commit2request c) [MicroBFT_replica s] (local_pred e) (MicroBFTlocalSys_new s s3 s1 s5).\n      dands; eauto 3 with eo.\n\n      Time unfold M_output_ls_on_this_one_event; simpl; repeat (allrw; simpl);\n        repeat (autorewrite with microbft comp in *; simpl in *; smash_microbft2);\n        try (complete (left; try congruence)).\n    }\n\n    { Case \"Commit\".\n\n      right.\n\n      applydup invalid_commit_false_implies in Heqx as w.\n      apply valid_commit_implies_executed_prior in w.\n      apply executed_prior_counter_implies_eq_S in w.\n\n      exists (commit2request c) [MicroBFT_replica s] (local_pred e) (MicroBFTlocalSys_new s s3 s4 s5).\n      dands; eauto 3 with eo.\n\n      Time unfold M_output_ls_on_this_one_event; simpl; repeat (allrw; simpl);\n        repeat (autorewrite with microbft comp in *; simpl in *; smash_microbft2);\n        try (complete (left; try congruence)).\n    }\n  Qed.\n\n  Lemma operation_inc_counter_ls :\n    forall {eo    : EventOrdering}\n           (e     : Event)\n           (r     : Request)\n           (i1 i2 : nat)\n           (l     : list name)\n           (s     : Rep)\n           (ls    : MicroBFTls),\n      M_run_ls_before_event (MicroBFTlocalSys s) e = Some ls\n      -> In (send_accept (accept r i2) l) (M_output_ls_on_this_one_event ls e)\n      -> i1 < i2\n      -> 0 < i1\n      -> exists r' l' e' ls',\n          e' ⊏ e\n          /\\ M_run_ls_before_event (MicroBFTlocalSys s) e' = Some ls'\n          /\\ In (send_accept (accept r' i1) l') (M_output_ls_on_this_one_event ls' e').\n  Proof.\n    intros eo e r i1 i2; revert e r.\n    induction i2; introv eqls out lti lti0; try omega;[].\n    apply lt_n_Sm_le in lti.\n\n    eapply operation_inc_counter_ls_step in out; eauto.\n    repndors; subst; try omega.\n    exrepnd.\n\n    apply le_lt_or_eq in lti; repndors; subst; try (complete microbft_finish_eexists);[].\n\n    eapply IHi2 in out1; eauto; try omega.\n    exrepnd.\n    exists r'0 l'0 e'0 ls'0; dands; auto; eauto 3 with eo.\n  Qed.\n\n  Lemma operation_inc_counter :\n    forall {eo    : EventOrdering}\n           (e     : Event)\n           (r     : Request)\n           (i1 i2 : nat)\n           (l     : list name),\n      is_replica e\n      -> In (send_accept (accept r i2) l) (M_output_sys_on_event MicroBFTsys e)\n      -> i1 < i2\n      -> 0 < i1\n      -> exists r' l' e',\n          e' ⊏ e\n          /\\ In (send_accept (accept r' i1) l') (M_output_sys_on_event MicroBFTsys e').\n  Proof.\n    introv isr h lti lti0.\n    unfold M_output_sys_on_event in *.\n    unfold MicroBFTsys, is_replica in *; exrepnd.\n    rewrite isr0 in *; simpl in *.\n\n    apply M_output_ls_on_event_as_run in h; exrepnd.\n    eapply operation_inc_counter_ls in h0; eauto.\n    exrepnd.\n    applydup local_implies_loc in h2 as eqloc.\n    exists r' l' e'; dands; auto.\n    rewrite eqloc.\n    rewrite isr0.\n\n    apply M_output_ls_on_event_as_run.\n    eexists; dands; eauto.\n  Qed.\n\n  Lemma accepted_counter_positive :\n    forall {eo    : EventOrdering}\n           (e     : Event)\n           (r     : Request)\n           (i     : nat)\n           (l     : list name),\n      is_replica e\n      -> In (send_accept (accept r i) l) (M_output_sys_on_event MicroBFTsys e)\n      -> 0 < i.\n  Proof.\n    introv isrep out.\n    unfold M_output_sys_on_event in *.\n    unfold MicroBFTsys, is_replica in *; exrepnd.\n    rewrite isrep0 in *; simpl in *.\n    apply M_output_ls_on_event_implies_run in out; exrepnd.\n    applydup M_run_ls_before_event_ls_is_microbft in out1; exrepnd; subst.\n    eapply accepted_if_executed_previous_step in out0; subst; omega.\n  Qed.\n  Hint Resolve accepted_counter_positive : microbft.\n*)\n\n  (*Lemma M_output_ls_on_input_is_log_new_implies :\n    forall u r v o,\n      M_output_ls_on_input (LOGlocalSys u) (log_new r) = (LOGlocalSys v, o)\n      -> in_log r v.\n  Proof.\n    introv out.\n    unfold M_output_ls_on_input in out; simpl in *.\n    unfold M_run_smat_on_inputs in out; simpl in *.\n    unfold M_run_update_on_inputs in out; simpl in *.\n    unfold M_break in *; simpl in *; ginv.\n    inversion out; auto; simpl; tcsp.\n  Qed.*)\n\n  Lemma invalid_request_false_implies_ui2rep_eq :\n    forall R r s,\n      invalid_commit R r s = false\n      -> ui2rep (commit_ui r) = MicroBFT_primary.\n  Proof.\n    introv inv; unfold invalid_commit, valid_commit, is_primary in *; smash_microbft_2.\n  Qed.\n  Hint Resolve invalid_request_false_implies_ui2rep_eq : microbft.\n\n  Lemma invalid_request_false_implies_not_primary :\n    forall R r s,\n      invalid_commit R r s = false\n      -> not_primary R = true.\n  Proof.\n    introv inv; unfold invalid_commit, valid_commit, is_primary in *; smash_microbft_2.\n  Qed.\n  Hint Resolve invalid_request_false_implies_not_primary : microbft.\n\n  (* This uses compositional reasoning, but using [LOG_comp]'s spec defined in\n     [M_output_ls_on_input_is_committed_implies] *)\n  Lemma accepted_counter_if_received_UI_primary :\n    forall {eo : EventOrdering}\n           (e  : Event)\n           (R  : MicroBFT_node)\n           (r  : nat)\n           (i  : nat)\n           (l  : list name),\n      In (send_accept (accept r i) l) (M_output_ls_on_event (MicroBFTlocalSys R) e)\n      ->\n      exists (s  : MAIN_state)\n             (s1 : USIG_state)\n             (s2 : LOG_state)\n             (ui : UI)\n             (rq : Commit),\n        M_run_ls_on_event (MicroBFTlocalSys R) e = Some (MicroBFTlocalSys_new R s s1 s2)\n        /\\ in_log rq s2\n        /\\ commit_n rq = r\n        /\\ commit_ui rq = ui\n        /\\ ui2counter ui = i\n        /\\ ui2rep ui = MicroBFT_primary\n        /\\ not_primary R = true.\n  Proof.\n    introv h.\n    apply M_output_ls_on_event_as_run in h; exrepnd.\n    rename ls' into ls.\n    rewrite M_run_ls_on_event_unroll2; allrw; simpl.\n    applydup M_run_ls_before_event_ls_is_microbft in h1; exrepnd; subst.\n    apply in_M_output_ls_on_this_one_event_implies in h0; exrepnd; simpl in *; microbft_simp.\n    unfold M_run_ls_on_this_one_event; simpl; allrw; simpl.\n    unfold M_run_ls_on_input_ls, M_run_ls_on_input.\n    unfold statefund_nm in *; simpl in *.\n    autorewrite with microbft comp in *.\n\n    Time microbft_dest_msg Case; simpl in *; tcsp; ginv; repeat smash_microbft_2; ginv.\n    eexists; eexists; eexists; eexists; eexists; dands; try reflexivity; eauto 3 with microbft; tcsp.\n  Qed.\n\nEnd MicroBFTcount.\n\n\n(*\nHint Resolve accepted_counter_positive : microbft.\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/MicroBFTcount.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.28661013172967786}}
{"text": "Require Export Db.Inst.\nRequire Export Db.Lemmas.\nRequire Export Db.WellScoping.\n\nRequire Export RecTypes.SpecTypes.\n\n#[export]\n#[refine] Instance vrTy : Vr Ty := {| vr := tvar |}.\nProof. inversion 1; auto. Defined.\n\nLocal Ltac crush :=\n  intros; cbn in * |-;\n  repeat\n    (cbn;\n     repeat crushRecTypesMatchH;\n     repeat crushDbSyntaxMatchH;\n     repeat crushDbLemmasMatchH;\n     rewrite ?comp_up, ?up_liftSub, ?up_comp_lift\n    );\n  auto.\n\nModule TyKit <: Kit.\n\n  Definition TM := Ty.\n  Definition inst_vr := vrTy.\n\n  Section Application.\n\n    Context {Y : Type}.\n    Context {vrY : Vr Y}.\n    Context {wkY: Wk Y}.\n    Context {liftY: Lift Y Ty}.\n\n    #[refine] Global Instance inst_ap : Ap Ty Y := {| ap := apTy |}.\n    Proof.\n      induction x; crush.\n    Defined.\n\n    #[refine] Global Instance inst_ap_vr : LemApVr Ty Y := {}.\n    Proof. reflexivity. Qed.\n\n  End Application.\n\n  #[export]\n  #[refine] Instance inst_ap_inj: LemApInj Ty Ix := {}.\n  Proof.\n    intros m Inj_m x. revert m Inj_m.\n    induction x; destruct y; simpl; try discriminate;\n    inversion 1; subst; f_equal; eauto using InjSubIxUp.\n  Qed.\n\n  #[export]\n  #[refine] Instance inst_ap_comp (Y Z: Type)\n    {vrY: Vr Y} {wkY: Wk Y} {liftY: Lift Y Ty}\n    {vrZ: Vr Z} {wkZ: Wk Z} {liftZ: Lift Z Ty}\n    {apYZ: Ap Y Z} {compUpYZ: LemCompUp Y Z}\n    {apLiftYTmZ: LemApLift Y Z Ty} :\n    LemApComp Ty Y Z := {}.\n  Proof. induction x; crush. Qed.\n\n  #[export]\n  #[refine] Instance inst_ap_liftSub (Y: Type)\n    {vrY: Vr Y} {wkY: Wk Y} {liftY: Lift Y Ty} :\n    LemApLiftSub Ty Y := {}.\n  Proof. induction t; crush. Qed.\n\n  Lemma inst_ap_ixComp (τ: Ty) :\n    ∀ (ξ: Sub Ix) (ζ: Sub Ty), τ[ξ][ζ] = τ[⌈ξ⌉ >=> ζ].\n  Proof. pose proof up_comp_lift. induction τ; crush. Qed.\n\nEnd TyKit.\n\n\nModule InstTy := Inst TyKit.\nExport InstTy. (* Export for shorter names. *)\n\n#[export]\nInstance wsVrTy: WsVr Ty.\nProof.\n  constructor.\n  - now constructor.\n  - now inversion 1.\nQed.\n\nSection ApplicationTy.\n\n  Context {Y: Type}.\n  Context {vrY : Vr Y}.\n  Context {wkY: Wk Y}.\n  Context {liftY: Lift Y Ty}.\n  Context {wsY: Ws Y}.\n  Context {wsVrY: WsVr Y}.\n  Context {wsWkY: WsWk Y}.\n  Context {wsLiftY: WsLift Y Ty}.\n\n  Hint Resolve wsLift : ws.\n  Hint Resolve wsSub_up : ws.\n\n\n  Global Instance wsApTy : WsAp Ty Y.\n  Proof.\n    constructor.\n    - intros ξ γ δ t wξ wt; revert ξ δ wξ.\n      induction wt; intros ξ δ wξ; crush;\n      try econstructor;\n      try match goal with\n            | |- wsTy ?δ ?t =>\n              change (wsTy δ t) with ⟨ δ ⊢ t ⟩\n          end; eauto with ws.\n    - intros γ t wt.\n      induction wt; crush.\n      + apply IHwt; inversion 1; crush.\n  Qed.\nEnd ApplicationTy.\n\n#[export]\nInstance wsWkTy : WsWk Ty.\nProof.\n  constructor; crush.\n  - refine (wsAp _ H); eauto.\n    constructor; eauto.\nQed.\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/RecTypes/InstTy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2865734096611812}}
{"text": "Require Import compcert.lib.Axioms.\nRequire Import compcert.lib.Maps.\n(* Require Export compcert.lib.Coqlib. *)\n\nRequire Import VST.concurrency.common.sepcomp. Import SepComp.\n\nRequire Import VST.concurrency.common.pos.\nRequire Import VST.concurrency.common.scheduler.\nRequire Import VST.concurrency.common.konig.\nRequire Import VST.concurrency.common.addressFiniteMap. (*The finite maps*)\nRequire Import VST.concurrency.common.pos.\nRequire Import VST.concurrency.common.lksize.\nRequire Import VST.concurrency.common.permjoin_def.\nRequire Import Coq.Program.Program.\nFrom mathcomp.ssreflect Require Import ssreflect ssrbool ssrnat ssrfun eqtype seq fintype finfun.\nSet Implicit Arguments.\n\nRequire Import VST.concurrency.common.ssromega. (*omega in ssrnat *)\n\nRequire Import Coq.ZArith.ZArith.\n\nRequire Import VST.concurrency.common.permissions.\nRequire Import VST.concurrency.common.threadPool.\n\nRequire Import compcert.common.Memory. (*for Mem.perm_order'' *)\nSet Bullet Behavior \"Strict Subproofs\".\n\n\nDefinition map_leq {A B} (m1: PTree.t A)(m2: PTree.t B): Prop :=\n  forall p, m1 ! p -> m2 ! p.\n\nLemma map_leq_apply:\n  forall {A B} (m1: PTree.t A)(m2: PTree.t B) p f1,\n    map_leq m1 m2 ->\n    m1 ! p = Some f1 -> exists f2, m2 ! p = Some f2.\nProof.\n  move => A B m1 m2 p f1.\n  rewrite /map_leq => /(_ p) Mle AA.\n  rewrite AA in Mle. specialize (Mle ltac:(auto)).\n  destruct (m2 ! p) as [f2|]; try solve[inversion Mle].\n  exists f2; auto.\nQed.\n\nLemma treemap_sub_map: forall {A B} (f: positive -> B -> A) m2,\n    map_leq (PTree.map f m2) m2.\nProof.\n  move => A B f m2 p.\n  rewrite PTree.gmap.\n  destruct (m2 ! p) eqn:m2p; auto; intros HH; inversion HH.\nQed.\n\nDefinition map_empty_def {A} (m1: PMap.t (Z -> option A)):=\n  m1.1 = fun _ => None.\n\nDefinition fun_leq' {A B} (f1: Z -> option A) (f2: Z -> option B): Prop :=\n  forall p, f1 p -> f2 p.\n\nDefinition fun_leq {A B} (o1: option (Z -> option A)) (o2: option (Z -> option B)): Prop :=\n  match o1, o2 with\n  | Some f1, Some f2 => fun_leq' f1 f2\n  | None, None => True\n  | _, _ => False\n  end.\n\nDefinition option_eq {A B} (a:option A) (b: option B): Prop :=\n  match a, b with\n  | Some _ , Some _ => True\n  | None, None => True\n  | _, _ => False\n  end.\n\nDefinition bounded_nat_func_aux {A} (f: nat -> option A) hi: Prop :=\n  (forall p, (p >= hi )%nat -> f p = None).\n\nDefinition bounded_nat_func' {A} (f: nat -> option A) hi: Prop :=\n  (forall p, (p > hi )%nat -> f p = None).\n\nDefinition bounded_func' {A} (f: Z -> option A) hi lo: Prop :=\n  (forall p, (p > hi )%Z -> f p = None) /\\\n  (forall p, (p < lo)%Z -> f p = None).\n\nDefinition bounded_func_op {A} (f: option (Z -> option A)) hi lo: Prop :=\n  match f with\n  | Some f' => bounded_func' f' hi lo\n  | None => True\n  end.\n\nDefinition bounded_func {A} (f: Z -> option A): Prop :=\n  exists hi lo,\n  bounded_func' f hi lo.\n\nDefinition bounded_map {A} (m: PTree.t (Z -> option A)):=\n  forall p f, m ! p = Some f -> bounded_func f.\n\nFixpoint strong_tree_leq {A B}\n         (t1: PTree.t A) (t2: PTree.t B)\n         (leq: option A -> option B -> Prop):=\n  match t1, t2 with\n  | PTree.Leaf, PTree.Leaf => True\n  | PTree.Node l1 o1 r1, PTree.Node l2 o2 r2 =>\n    leq o1 o2 /\\\n    strong_tree_leq l1 l2 leq /\\\n    strong_tree_leq r1 r2 leq\n  | _, _ => False\n  end.\n\nDefinition same_shape {A B} (m1: PTree.t (Z -> option A))(m2: PTree.t (Z -> option B)):=\n  strong_tree_leq m1 m2 option_eq.\n\nDefinition sub_map' {A B} (m1: PTree.t (Z -> option A))(m2: PTree.t (Z -> option B)):=\n  forall p f1, m1 ! p = Some f1 ->\n          exists f2, m2 ! p = Some f2 /\\ fun_leq' f1 f2.\n\nDefinition sub_map {A B} (m1: PTree.t (Z -> option A))(m2: PTree.t (Z -> option B)):=\n  strong_tree_leq m1 m2 fun_leq.\n\nLemma sub_map_and_shape:\n  forall { A B} m1 m2,\n  @same_shape A B m1 m2 ->\n  sub_map' m1 m2 ->\n  sub_map m1 m2.\nProof.\n  induction m1.\n  - intros.\n    destruct m2; inversion H.\n    auto.\n  - intros.\n    rewrite /sub_map /=.\n    destruct m2; try inversion H.\n    split; [|split].\n    + destruct o as [o|].\n      2: destruct o0; inversion H1; auto.\n      specialize (H0 1%positive o ltac:(auto)).\n      destruct o0; try solve [inversion H1].\n      destruct H0 as [f [ISo LEQ]].\n      inversion ISo.\n      auto.\n    + destruct H as [AA [BB CC]].\n      eapply IHm1_1; eauto.\n      move => b f HH.\n      move: H0 => /(_  (b~0)%positive f HH) //.\n    + destruct H as [AA [BB CC]].\n      eapply IHm1_2; eauto.\n      move => b f HH.\n      move: H0 => /(_  (b~1)%positive f HH) //.\nQed.\n\nDefinition nat_to_perm (i:nat) :=\n  (match i with\n  | 0 => Some None\n  | 1 => Some (Some Nonempty)\n  | 2 => Some (Some Readable)\n  | 3 => Some (Some Writable)\n  | 4 => Some (Some Freeable)\n  | _ => None\n  end)%nat.\n\nDefinition perm_to_nat (p: option (option permission)) :=\n  match p with\n  | Some (None) => 0\n  | Some (Some Nonempty) => 1\n  | Some (Some Readable) => 2\n  | Some (Some Writable) => 3\n  | Some (Some Freeable) => 4\n  | None => 5\n  end.\n\nDefinition nat_to_perm_simpl (i:nat) :=\n  (match i with\n  | 0 => None\n  | 1 => Some Nonempty\n  | 2 => Some Readable\n  | 3 => Some Writable\n  | 4 => Some Freeable\n  | _ => None\n  end)%nat.\n\nDefinition perm_to_nat_simpl (p: option permission) :=\n  match p with\n  | None => 0\n  | Some Nonempty => 1\n  | Some Readable => 2\n  | Some Writable => 3\n  | Some Freeable => 4\n  end.\nLemma perm_to_nat_bound:\n  forall p,\n    perm_to_nat p < 6.\nProof.\n  intros p.\n  destruct p as [p|];\n    try destruct p as [p|]; try destruct p; compute; auto.\nQed.\n\nLemma perm_to_nat_bound_simpl:\n  forall p,\n    perm_to_nat_simpl p < 5.\nProof.\n  intros p.\n  destruct p as [p|];\n    try destruct p; compute; auto.\nQed.\n\nLemma nat_to_perm_perm_to_nat:\n  forall p,\n    nat_to_perm (perm_to_nat p) = p.\nProof.\n  intros p.\n  destruct p as [p|];\n    try destruct p as [p|];\n    try destruct p;\n    reflexivity.\nQed.\n\nLemma nat_to_perm_perm_to_nat_simpl:\n  forall p,\n    nat_to_perm_simpl (perm_to_nat_simpl p) = p.\nProof.\n  intros p.\n  destruct p as [p|];\n    try destruct p;\n    reflexivity.\nQed.\n\nLemma finite_bounded_nat_aux_func:\n  forall hi ,\n    konig.finite\n      ( fun f:nat -> option (option permission) => bounded_nat_func_aux f hi).\nProof.\n\n   intros hi.\n   pose (K:= perm_to_nat).\n   induction hi.\n   - exists 1%nat.\n     exists (fun x _ => None).\n     intros.\n     exists 0%nat.\n     split; auto.\n\n     extensionality b.\n     symmetry.\n     apply H.\n     apply /leP. omega.\n\n   - destruct IHhi as [N [FN H]].\n     exists (6*N)%nat.\n     exists (fun x i => if (Nat.eq_dec i hi) then\n                       nat_to_perm (Nat.modulo x 6)\n                else FN (Nat.div x 6) i).\n     move=> f HH.\n     specialize (H (fun n => if (Nat.eq_dec n hi) then\n                            None\n                          else f n) ).\n     destruct H as [i [ineq f_spec]].\n     + intros pp pphi.\n       destruct (Nat.eq_dec pp hi).\n       * auto.\n       * simpl; eapply HH.\n         move: pphi=> /leP pphi.\n         apply /ltP.\n         omega.\n\n     + exists ((6 * i) + (perm_to_nat (f hi))).\n       split.\n       * replace (6 * N) with\n         (6 * (N - 1) + 6 ).\n         { eapply (NPeano.Nat.lt_le_trans _ (6 * i  + 6)).\n           - apply /leP.\n             rewrite ltn_add2l.\n             destruct (f hi) as [p|];\n               [destruct p; try destruct p|]; simpl; apply /leP; try omega.\n           - apply /leP.\n             rewrite leq_add2r.\n             rewrite leq_pmul2l.\n             + apply / leP. clear -ineq.\n               replace N with (S (N - 1)) in ineq.\n               apply /leP.\n               by rewrite - ltnS; apply /leP.\n               rewrite -addn1.\n               apply subnK.\n               destruct N; apply /ltP; try omega.\n             + compute; auto.\n         }\n         rewrite - mulnSr.\n         replace (N -1).+1 with N; auto.\n         rewrite -addn1.\n         symmetry; apply subnK.\n         destruct N; apply /ltP; try omega.\n       * { extensionality i0.\n           destruct (Nat.eq_dec i0 hi).\n           - subst.\n             rewrite addnC.\n             rewrite mulnC.\n             rewrite NPeano.Nat.mod_add; try omega.\n             rewrite NPeano.Nat.mod_small;\n               try (apply /ltP; eapply perm_to_nat_bound).\n             rewrite nat_to_perm_perm_to_nat.\n             reflexivity.\n\n           - replace ((6 * i + perm_to_nat (f hi)) / 6) with i.\n             + rewrite f_spec.\n               simpl.\n               destruct (Nat.eq_dec i0 hi);\n                 try solve [exfalso; apply n; auto].\n               reflexivity.\n             + eapply NPeano.Nat.div_unique;\n               try (apply /ltP; eapply perm_to_nat_bound).\n               reflexivity.\n         }\nQed.\n\n\nLemma finite_bounded_nat_aux_func_simpl:\n  forall hi ,\n    konig.finite\n      ( fun f:nat -> option permission => bounded_nat_func_aux f hi).\nProof.\n\n   intros hi.\n   pose (K:= perm_to_nat_simpl).\n   induction hi.\n   - exists 1%nat.\n     exists (fun x _ => None).\n     intros.\n     exists 0%nat.\n     split; auto.\n\n     extensionality b.\n     symmetry.\n     apply H.\n     apply /leP. omega.\n\n   - destruct IHhi as [N [FN H]].\n     exists (5*N)%nat.\n     exists (fun x i => if (Nat.eq_dec i hi) then\n                       nat_to_perm_simpl (Nat.modulo x 5)\n                else FN (Nat.div x 5) i).\n     move=> f HH.\n     specialize (H (fun n => if (Nat.eq_dec n hi) then\n                            None\n                          else f n) ).\n     destruct H as [i [ineq f_spec]].\n     + intros pp pphi.\n       destruct (Nat.eq_dec pp hi).\n       * auto.\n       * simpl; eapply HH.\n         move: pphi=> /leP pphi.\n         apply /ltP.\n         omega.\n\n     + exists ((5 * i) + (perm_to_nat_simpl (f hi))).\n       split.\n       * replace (5 * N) with\n         (5 * (N - 1) + 5 ).\n         { eapply (NPeano.Nat.lt_le_trans _ (5 * i  + 5)).\n           - apply /leP.\n             rewrite ltn_add2l.\n             destruct (f hi) as [p|]; [destruct p|]; simpl; apply /leP; try omega.\n           - apply /leP.\n             rewrite leq_add2r.\n             rewrite leq_pmul2l.\n             + apply / leP. clear -ineq.\n               replace N with (S (N - 1)) in ineq.\n               apply /leP.\n               by rewrite - ltnS; apply /leP.\n               rewrite -addn1.\n               apply subnK.\n               destruct N; apply /ltP; try omega.\n             + compute; auto.\n         }\n         rewrite - mulnSr.\n         replace (N -1).+1 with N; auto.\n         rewrite -addn1.\n         symmetry; apply subnK.\n         destruct N; apply /ltP; try omega.\n       * { extensionality i0.\n           destruct (Nat.eq_dec i0 hi).\n           - subst.\n             rewrite addnC.\n             rewrite mulnC.\n             rewrite NPeano.Nat.mod_add; try omega.\n             rewrite NPeano.Nat.mod_small;\n               try (apply /ltP; eapply perm_to_nat_bound_simpl).\n             rewrite nat_to_perm_perm_to_nat_simpl.\n             reflexivity.\n\n           - replace ((5 * i + perm_to_nat_simpl (f hi)) / 5) with i.\n             + rewrite f_spec.\n               simpl.\n               destruct (Nat.eq_dec i0 hi);\n                 try solve [exfalso; apply n; auto].\n               reflexivity.\n             + eapply NPeano.Nat.div_unique;\n               try (apply /ltP; eapply perm_to_nat_bound_simpl).\n               reflexivity.\n         }\nQed.\n\nLemma finite_bounded_nat_func:\n  forall hi ,\n    konig.finite\n      ( fun f:nat -> option (option permission) => bounded_nat_func' f hi).\nProof.\n  intros.\n  destruct (finite_bounded_nat_aux_func (S hi)) as [x [f HH]].\n  exists x, f.\n  move=> x0 BND.\n  cut (bounded_nat_func_aux x0 hi.+1).\n  2:{ intros b ineq; eapply BND; auto. }\n  move=> /HH [] i [] A B.\n  exists i; split; eauto.\nQed.\n\n\nLemma finite_bounded_nat_func_simpl:\n  forall hi ,\n    konig.finite\n      ( fun f:nat -> option permission => bounded_nat_func' f hi).\nProof.\n  intros.\n  destruct (finite_bounded_nat_aux_func_simpl (S hi)) as [x [f HH]].\n  exists x, f.\n  move=> x0 BND.\n  cut (bounded_nat_func_aux x0 hi.+1).\n  2:{ intros b ineq; eapply BND; auto. }\n  move=> /HH [] i [] A B.\n  exists i; split; eauto.\nQed.\n\nLemma finite_bounded_func:\n  forall hi lo,\n    konig.finite\n      ( fun f:Z -> option (option permission) => bounded_func' f hi lo).\nProof.\n  intros hi lo.\n  destruct (Coqlib.zlt hi lo).\n  - exists 1%N.\n    exists (fun _ _ => None).\n    intros.\n    exists 0%nat; split; auto.\n    extensionality b.\n    destruct H as[H1 H2].\n    symmetry.\n    destruct (Coqlib.zle b hi).\n    + eapply H2.\n      eapply Z.le_lt_trans; eauto.\n    + eapply H1; assumption.\n  - assert (0 <= hi - lo)%Z by omega.\n    pose (n:= Z.to_nat (hi - lo)).\n    destruct (finite_bounded_nat_func n) as [N [FN HN]].\n    exists N.\n    exists (fun n z => (if (Z_lt_ge_dec z lo)\n                then None\n                else FN n (Z.to_nat (z-lo)))).\n    intros f [BOUND1 BOUND2].\n    pose (f':= fun n => f (Z.of_nat n + lo)%Z).\n    assert (bounded_nat_func' f' n).\n    { intros b ineq.\n      unfold f'.\n      eapply BOUND1.\n      unfold n in ineq.\n      cut (Z.of_nat b > hi - lo)%Z.\n      omega.\n      move: ineq => /ltP /inj_lt /Z.gt_lt_iff.\n      rewrite Z2Nat.id => //.\n    }\n    apply HN in H0.\n    destruct H0 as [i [ineq FN_spec]].\n    exists i; split; auto.\n    extensionality z.\n    rewrite FN_spec.\n    unfold f'.\n    destruct (Z_lt_ge_dec z lo).\n    + simpl.\n      symmetry.\n        by apply BOUND2.\n    + simpl.\n      rewrite Z2Nat.id.\n      * f_equal; omega.\n      * omega.\nQed.\n\n\nLemma finite_bounded_func_simpl:\n  forall hi lo,\n    konig.finite\n      ( fun f:Z -> option permission => bounded_func' f hi lo).\nProof.\n  intros hi lo.\n  destruct (Coqlib.zlt hi lo).\n  - exists 1%N.\n    exists (fun _ _ => None).\n    intros.\n    exists 0%nat; split; auto.\n    extensionality b.\n    destruct H as[H1 H2].\n    symmetry.\n    destruct (Coqlib.zle b hi).\n    + eapply H2.\n      eapply Z.le_lt_trans; eauto.\n    + eapply H1; assumption.\n  - assert (0 <= hi - lo)%Z by omega.\n    pose (n:= Z.to_nat (hi - lo)).\n    destruct (finite_bounded_nat_func_simpl n) as [N [FN HN]].\n    exists N.\n    exists (fun n z => (if (Z_lt_ge_dec z lo)\n                then None\n                else FN n (Z.to_nat (z-lo)))).\n    intros f [BOUND1 BOUND2].\n    pose (f':= fun n => f (Z.of_nat n + lo)%Z).\n    assert (bounded_nat_func' f' n).\n    { intros b ineq.\n      unfold f'.\n      eapply BOUND1.\n      unfold n in ineq.\n      cut (Z.of_nat b > hi - lo)%Z.\n      omega.\n      move: ineq => /ltP /inj_lt /Z.gt_lt_iff.\n      rewrite Z2Nat.id => //.\n    }\n    apply HN in H0.\n    destruct H0 as [i [ineq FN_spec]].\n    exists i; split; auto.\n    extensionality z.\n    rewrite FN_spec.\n    unfold f'.\n    destruct (Z_lt_ge_dec z lo).\n    + simpl.\n      symmetry.\n        by apply BOUND2.\n    + simpl.\n      rewrite Z2Nat.id.\n      * f_equal; omega.\n      * omega.\nQed.\n\nLemma finite_bounded_op_func_simpl:\n  forall hi lo,\n    konig.finite\n      ( fun f: option (Z -> option permission) => bounded_func_op f hi lo).\nProof.\n  move => hi lo.\n  move: (finite_bounded_func_simpl hi lo) => [] N [] FN FN_spec.\n\n  exists (S N).\n  exists (fun n => if n == 0 then None\n           else Some (FN (n -1)) ).\n  move => f H.\n  destruct f.\n  - move: FN_spec => /(_ _ H) [] i [] ineqi speci.\n    exists (S i); split.\n    + omega.\n    + rewrite - speci.\n      simpl; repeat f_equal.\n      rewrite - addn1 - addnBA=> //.\n  - exists 0; split; auto.\n    + omega.\nQed.\n\nLemma finite_bounded_op_func:\n  forall hi lo,\n    konig.finite\n      ( fun f: option (Z -> option (option permission)) => bounded_func_op f hi lo).\nProof.\n  move => hi lo.\n  move: (finite_bounded_func hi lo) => [] N [] FN FN_spec.\n\n  exists (S N).\n  exists (fun n => if n == 0 then None\n           else Some (FN (n -1)) ).\n  move => f H.\n  destruct f.\n  - move: FN_spec => /(_ _ H) [] i [] ineqi speci.\n    exists (S i); split.\n    + omega.\n    + rewrite - speci.\n      simpl; repeat f_equal.\n      rewrite - addn1 - addnBA=> //.\n  - exists 0; split; auto.\n    + omega.\nQed.\n\nLemma finite_sub_maps:\n  forall m2,\n    @bounded_map permission m2 ->\n    konig.finite\n      (fun m1 => @sub_map (option permission) permission m1 m2).\nProof.\n  induction m2.\n  - move => _.\n    exists 1%nat.\n    exists (fun _ => PTree.Leaf).\n    intros .\n    exists 0%nat.\n    split; auto.\n    destruct x; auto.\n    unfold strong_tree_leq in H;\n      simpl in H.\n    destruct o; inversion H.\n  - move => H.\n    assert (HH1:\n              forall (p : positive) (f : Z -> option permission),\n                m2_1 ! p = Some f ->\n                exists hi lo : Z,\n                  (forall p0 : Z, (p0 > hi)%Z -> f p0 = None) /\\\n                  (forall p0 : Z, (p0 < lo)%Z -> f p0 = None)).\n    { clear - H.\n      move=> p f Hget.\n      move : H => /(_ (p~0)%positive f ltac:(simpl;auto)) [] hi [] lo BOUND.\n      exists hi, lo; assumption.\n    }\n    move: IHm2_1=> /(_ HH1) [] N1 [] F1 spec_F1.\n    assert (HH2:\n              forall (p : positive) (f : Z -> option permission),\n                m2_2 ! p = Some f ->\n                exists hi lo : Z,\n                  (forall p0 : Z, (p0 > hi)%Z -> f p0 = None) /\\\n                  (forall p0 : Z, (p0 < lo)%Z -> f p0 = None)).\n    { clear - H.\n      move=> p f Hget.\n      move : H => /(_ (p~1)%positive f ltac:(simpl;auto)) [] hi [] lo BOUND.\n      exists hi, lo; assumption.\n    }\n    move: IHm2_2=> /(_ HH2) [] N2 [] F2 spec_F2.\n    destruct o as [f1|].\n    + move : H => /(_ 1%positive f1 ltac:(reflexivity)) [] hi [] lo BNDD.\n      move : (finite_bounded_op_func hi lo) => [] N [] F F_spec.\n      exists (S( N * N1 * N2)).\n      exists (fun n => if n == 0\n               then PTree.Leaf\n               else\n                 PTree.Node\n                   (F1 ( (n-1) mod N1))\n                   (F ((n-1) / (N1 * N2)))\n                   (F2 (((n-1) / N1 ) mod N2))).\n      intros x spec.\n      destruct x.\n      * exists 0%nat; split; auto.\n        omega.\n      * move: spec .\n        rewrite /sub_map /= => [] [] FUN_lq [] tree1 tree2.\n        assert (bounded_func_op o hi lo).\n        { Lemma fun_le_bounded_func_op:\n            forall {A} o f hi lo,\n              @bounded_func' A f hi lo ->\n              fun_leq o (Some f) ->\n              @bounded_func_op (option A) o hi lo.\n          Proof.\n            intros.\n            destruct o; [|constructor].\n            simpl.\n            simpl in H0.\n            split; intros p.\n            - intros HH. apply H in HH.\n              unfold fun_leq' in H0.\n              specialize (H0 p).\n              destruct (o p); try solve [auto].\n              specialize (H0 ltac:(auto)).\n              rewrite HH in H0; inversion H0.\n            - intros HH. apply H in HH.\n              unfold fun_leq' in H0.\n              specialize (H0 p).\n              destruct (o p); try solve [auto].\n              specialize (H0 ltac:(auto)).\n              rewrite HH in H0; inversion H0.\n          Qed.\n          eapply fun_le_bounded_func_op ; eauto.\n          }\n        move: F_spec => /(_ _ H) []i [] ineq fi.\n        move : spec_F1 => /(_ _ tree1) [] i1 [] ineq1 fi1.\n        move : spec_F2 => /(_ _ tree2) [] i2 [] ineq2 fi2.\n        exists (S(i1 + (i2 * N1) + (i * N1 * N2))); split.\n        { apply lt_n_S.\n          replace (N * N1 * N2) with\n          (N1 + N1 * (N2 * N -1)).\n          - eapply (NPeano.Nat.lt_le_trans).\n            + instantiate (1:= (N1 + i2 * N1 + i * N1 * N2)).\n              apply /ltP.\n              rewrite ltn_add2r;\n                rewrite ltn_add2r;\n                apply /ltP; auto.\n            + apply /leP.\n              rewrite -addnA.\n              rewrite leq_add2l.\n              apply /leP.\n              replace (i * N1 * N2) with\n              ((i * N2) * N1).\n              *\n                rewrite -mulnDl.\n                rewrite mulnC.\n                apply /leP.\n                rewrite leq_pmul2l; try (apply /ltP; omega).\n                apply /leP.\n                eapply lt_n_Sm_le.\n                rewrite - addn1.\n                rewrite subnK.\n                2:\n                  rewrite muln_gt0;\n                  apply /andP; split;\n                  try (apply /ltP; omega).\n                eapply (NPeano.Nat.lt_le_trans).\n                -- instantiate (1:= N2 + i * N2).\n                   apply /ltP.\n                   rewrite ltn_add2r.\n                   apply /leP; auto.\n                -- replace (N2 + i * N2) with\n                   (N2 * (1 + i)).\n                   apply /leP.\n                   rewrite leq_pmul2l.\n                   rewrite add1n.\n                   apply /ltP; auto.\n                   apply /ltP; omega.\n                   rewrite mulnDr.\n                   rewrite mulnC.\n                   f_equal.\n                   compute; auto.\n                   rewrite mulnC; auto.\n              * do 2 rewrite - mulnA.\n                f_equal. rewrite mulnC; auto.\n          - replace (N1 + N1 * (N2 * N - 1))\n            with (N1 * 1 + N1 * (N2 * N - 1)).\n            + rewrite -mulnDr.\n              rewrite addnC.\n              rewrite subnK.\n\n              2:\n                rewrite muln_gt0;\n                apply /andP; split;\n                try (apply /ltP; omega).\n              rewrite -mulnA.\n              rewrite mulnA.\n              rewrite mulnC; auto.\n            + f_equal.\n              rewrite mulnC.\n              compute; auto. }\n      -- simpl; f_equal.\n         ++ rewrite - fi1.\n            f_equal.\n            rewrite -addn1.\n            rewrite -addnBA. 2: ssromega.\n            replace (i1 + i2 * N1 + i * N1 * N2 + (1 - 1)) with\n            (i1 + i2 * N1 + i * N1 * N2) by ssromega.\n            replace (i1 + i2 * N1 + i * N1 * N2) with\n            (i1 + (i2  + i *  N2) * N1).\n            2:\n            rewrite mulnDl addnA; f_equal;\n            do 2 rewrite -mulnA; f_equal; rewrite mulnC; auto.\n            rewrite NPeano.Nat.mod_add.\n            apply NPeano.Nat.mod_small; auto.\n            destruct N1; omega.\n         ++ rewrite - fi.\n            f_equal.\n            rewrite -addn1.\n            rewrite -addnBA. 2: ssromega.\n            replace (i1 + i2 * N1 + i * N1 * N2 + (1 - 1)) with\n            (i1 + i2 * N1 + i * N1 * N2) by ssromega.\n            assert (i1 + i2 * N1 + i * N1 * N2 =\n                    ((N1 * N2) * i) + (i1 + i2 * N1)).\n            { rewrite addnC. f_equal.\n              rewrite - mulnA mulnC; auto. }\n            eapply NPeano.Nat.div_unique in H0; auto.\n            eapply (NPeano.Nat.lt_le_trans).\n            ** instantiate (1:= N1 + i2 * N1).\n               apply /ltP; rewrite ltn_add2r.\n               apply /ltP; auto.\n            ** replace (N1 + i2 * N1) with ( (1 + i2) * N1).\n               rewrite add1n.\n               rewrite mulnC.\n               apply /leP; rewrite leq_pmul2l.\n               apply /ltP; auto.\n               destruct N1; ssromega.\n               rewrite mulnDl; f_equal.\n               ssromega.\n\n         ++ rewrite - fi2.\n            f_equal.\n            rewrite -addn1.\n            rewrite -addnBA. 2: ssromega.\n            replace (i1 + i2 * N1 + i * N1 * N2 + (1 - 1)) with\n            (i1 + i2 * N1 + i * N1 * N2) by ssromega.\n            assert (i1 + i2 * N1 + i * N1 * N2 =\n                    (N1 * (i2 + i * N2)) + i1).\n            { rewrite -addnA.\n              replace (i * N1 * N2) with\n              (i  * N2 * N1).\n              rewrite - mulnDl.\n              rewrite mulnC addnC; auto.\n              do 2 rewrite -mulnA; f_equal.\n              rewrite mulnC. auto. }\n            eapply NPeano.Nat.div_unique in H0; auto.\n            rewrite - H0.\n            rewrite NPeano.Nat.mod_add.\n            apply NPeano.Nat.mod_small; auto.\n            destruct N2; omega.\n    + exists (S( N1 * N2)).\n      exists (fun n => if n == 0\n               then PTree.Leaf\n               else\n                 PTree.Node\n                   (F1 ( (n-1) mod N1))\n                   (None )\n                   (F2 (((n-1) / N1 ) mod N2))).\n      intros x spec.\n      destruct x.\n      * exists 0%nat; split; auto.\n        omega.\n      * move: spec .\n        rewrite /sub_map /= => [] [] FUN_lq [] tree1 tree2.\n        move : spec_F1 => /(_ _ tree1) [] i1 [] ineq1 fi1.\n        move : spec_F2 => /(_ _ tree2) [] i2 [] ineq2 fi2.\n        exists (S(i1 + (i2 * N1))); split.\n        { apply lt_n_S.\n          replace (N1 * N2) with\n          (N1 + N1 * (N2 -1)).\n          - eapply (NPeano.Nat.lt_le_trans).\n            + instantiate (1:= (N1 + i2 * N1)).\n              apply /ltP.\n              rewrite ltn_add2r;\n                apply /ltP; auto.\n            + apply /leP.\n              rewrite leq_add2l.\n              apply /leP.\n              rewrite mulnC.\n              apply /leP.\n              rewrite leq_pmul2l; try (apply /ltP; omega).\n              apply /leP.\n              eapply lt_n_Sm_le.\n              rewrite - addn1.\n              rewrite subnK; auto.\n              destruct N2; ssromega.\n\n          - replace (N1 + N1 * (N2 - 1))\n            with (N1 * 1 + N1 * (N2 - 1)).\n            + rewrite -mulnDr.\n              rewrite addnC.\n              rewrite subnK.\n              2: ssromega.\n              rewrite mulnC; auto.\n            + f_equal.\n              rewrite mulnC.\n              compute; auto. }\n      -- simpl; f_equal.\n         ++ rewrite - fi1.\n            f_equal.\n            rewrite -addn1.\n            rewrite -addnBA. 2: ssromega.\n            replace (i1 + i2 * N1 + (1 - 1)) with\n            (i1 + i2 * N1) by ssromega.\n            rewrite NPeano.Nat.mod_add.\n            apply NPeano.Nat.mod_small; auto.\n            destruct N1; omega.\n         ++ destruct o; auto; inversion FUN_lq.\n         ++ rewrite - fi2.\n            f_equal.\n            rewrite -addn1.\n            rewrite -addnBA. 2: ssromega.\n            replace (i1 + i2 * N1 + (1 - 1)) with\n            (i1 + i2 * N1 ) by ssromega.\n            assert (i1 + i2 * N1 =\n                    (N1 * (i2) + i1)).\n            { rewrite mulnC addnC; auto. }\n            eapply NPeano.Nat.div_unique in H0; auto.\n            rewrite - H0.\n            apply NPeano.Nat.mod_small; auto.\nQed.\n\nLemma finite_sub_maps_simpl:\n  forall m2,\n    @bounded_map permission m2 ->\n    konig.finite\n      (fun m1 => @sub_map permission permission m1 m2).\nProof.\n\n  induction m2.\n  - move => _.\n    exists 1%nat.\n    exists (fun _ => PTree.Leaf).\n    intros .\n    exists 0%nat.\n    split; auto.\n    destruct x; auto.\n    unfold strong_tree_leq in H;\n      simpl in H.\n    destruct o; inversion H.\n  - move => H.\n    assert (HH1:\n              forall (p : positive) (f : Z -> option permission),\n                m2_1 ! p = Some f ->\n                exists hi lo : Z,\n                  (forall p0 : Z, (p0 > hi)%Z -> f p0 = None) /\\\n                  (forall p0 : Z, (p0 < lo)%Z -> f p0 = None)).\n    { clear - H.\n      move=> p f Hget.\n      move : H => /(_ (p~0)%positive f ltac:(simpl;auto)) [] hi [] lo BOUND.\n      exists hi, lo; assumption.\n    }\n    move: IHm2_1=> /(_ HH1) [] N1 [] F1 spec_F1.\n    assert (HH2:\n              forall (p : positive) (f : Z -> option permission),\n                m2_2 ! p = Some f ->\n                exists hi lo : Z,\n                  (forall p0 : Z, (p0 > hi)%Z -> f p0 = None) /\\\n                  (forall p0 : Z, (p0 < lo)%Z -> f p0 = None)).\n    { clear - H.\n      move=> p f Hget.\n      move : H => /(_ (p~1)%positive f ltac:(simpl;auto)) [] hi [] lo BOUND.\n      exists hi, lo; assumption.\n    }\n    move: IHm2_2=> /(_ HH2) [] N2 [] F2 spec_F2.\n    destruct o as [f1|].\n    + move : H => /(_ 1%positive f1 ltac:(reflexivity)) [] hi [] lo BNDD.\n      move : (finite_bounded_op_func_simpl hi lo) => [] N [] F F_spec.\n      exists (S( N * N1 * N2)).\n      exists (fun n => if n == 0\n               then PTree.Leaf\n               else\n                 PTree.Node\n                   (F1 ( (n-1) mod N1))\n                   (F ((n-1) / (N1 * N2)))\n                   (F2 (((n-1) / N1 ) mod N2))).\n      intros x spec.\n      destruct x.\n      * exists 0%nat; split; auto.\n        omega.\n      * move: spec .\n        rewrite /sub_map /= => [] [] FUN_lq [] tree1 tree2.\n        assert (bounded_func_op o hi lo).\n        { Lemma fun_le_bounded_func_op_simpl:\n            forall {A} o f hi lo,\n              @bounded_func' A f hi lo ->\n              fun_leq o (Some f) ->\n              @bounded_func_op A o hi lo.\n          Proof.\n            intros.\n            destruct o; [|constructor].\n            simpl.\n            simpl in H0.\n            split; intros p.\n            - intros HH. apply H in HH.\n              unfold fun_leq' in H0.\n              specialize (H0 p).\n              destruct (o p); try solve [auto].\n              specialize (H0 ltac:(auto)).\n              rewrite HH in H0; inversion H0.\n            - intros HH. apply H in HH.\n              unfold fun_leq' in H0.\n              specialize (H0 p).\n              destruct (o p); try solve [auto].\n              specialize (H0 ltac:(auto)).\n              rewrite HH in H0; inversion H0.\n          Qed.\n          eapply fun_le_bounded_func_op_simpl ; eauto.\n          }\n        move: F_spec => /(_ _ H) []i [] ineq fi.\n        move : spec_F1 => /(_ _ tree1) [] i1 [] ineq1 fi1.\n        move : spec_F2 => /(_ _ tree2) [] i2 [] ineq2 fi2.\n        exists (S(i1 + (i2 * N1) + (i * N1 * N2))); split.\n        { apply lt_n_S.\n          replace (N * N1 * N2) with\n          (N1 + N1 * (N2 * N -1)).\n          - eapply (NPeano.Nat.lt_le_trans).\n            + instantiate (1:= (N1 + i2 * N1 + i * N1 * N2)).\n              apply /ltP.\n              rewrite ltn_add2r;\n                rewrite ltn_add2r;\n                apply /ltP; auto.\n            + apply /leP.\n              rewrite -addnA.\n              rewrite leq_add2l.\n              apply /leP.\n              replace (i * N1 * N2) with\n              ((i * N2) * N1).\n              *\n                rewrite -mulnDl.\n                rewrite mulnC.\n                apply /leP.\n                rewrite leq_pmul2l; try (apply /ltP; omega).\n                apply /leP.\n                eapply lt_n_Sm_le.\n                rewrite - addn1.\n                rewrite subnK.\n                2:\n                  rewrite muln_gt0;\n                  apply /andP; split;\n                  try (apply /ltP; omega).\n                eapply (NPeano.Nat.lt_le_trans).\n                -- instantiate (1:= N2 + i * N2).\n                   apply /ltP.\n                   rewrite ltn_add2r.\n                   apply /leP; auto.\n                -- replace (N2 + i * N2) with\n                   (N2 * (1 + i)).\n                   apply /leP.\n                   rewrite leq_pmul2l.\n                   rewrite add1n.\n                   apply /ltP; auto.\n                   apply /ltP; omega.\n                   rewrite mulnDr.\n                   rewrite mulnC.\n                   f_equal.\n                   compute; auto.\n                   rewrite mulnC; auto.\n              * do 2 rewrite - mulnA.\n                f_equal. rewrite mulnC; auto.\n          - replace (N1 + N1 * (N2 * N - 1))\n            with (N1 * 1 + N1 * (N2 * N - 1)).\n            + rewrite -mulnDr.\n              rewrite addnC.\n              rewrite subnK.\n\n              2:\n                rewrite muln_gt0;\n                apply /andP; split;\n                try (apply /ltP; omega).\n              rewrite -mulnA.\n              rewrite mulnA.\n              rewrite mulnC; auto.\n            + f_equal.\n              rewrite mulnC.\n              compute; auto. }\n      -- simpl; f_equal.\n         ++ rewrite - fi1.\n            f_equal.\n            rewrite -addn1.\n            rewrite -addnBA. 2: ssromega.\n            replace (i1 + i2 * N1 + i * N1 * N2 + (1 - 1)) with\n            (i1 + i2 * N1 + i * N1 * N2) by ssromega.\n            replace (i1 + i2 * N1 + i * N1 * N2) with\n            (i1 + (i2  + i *  N2) * N1).\n            2:\n            rewrite mulnDl addnA; f_equal;\n            do 2 rewrite -mulnA; f_equal; rewrite mulnC; auto.\n            rewrite NPeano.Nat.mod_add.\n            apply NPeano.Nat.mod_small; auto.\n            destruct N1; omega.\n         ++ rewrite - fi.\n            f_equal.\n            rewrite -addn1.\n            rewrite -addnBA. 2: ssromega.\n            replace (i1 + i2 * N1 + i * N1 * N2 + (1 - 1)) with\n            (i1 + i2 * N1 + i * N1 * N2) by ssromega.\n            assert (i1 + i2 * N1 + i * N1 * N2 =\n                    ((N1 * N2) * i) + (i1 + i2 * N1)).\n            { rewrite addnC. f_equal.\n              rewrite - mulnA mulnC; auto. }\n            eapply NPeano.Nat.div_unique in H0; auto.\n            eapply (NPeano.Nat.lt_le_trans).\n            ** instantiate (1:= N1 + i2 * N1).\n               apply /ltP; rewrite ltn_add2r.\n               apply /ltP; auto.\n            ** replace (N1 + i2 * N1) with ( (1 + i2) * N1).\n               rewrite add1n.\n               rewrite mulnC.\n               apply /leP; rewrite leq_pmul2l.\n               apply /ltP; auto.\n               destruct N1; ssromega.\n               rewrite mulnDl; f_equal.\n               ssromega.\n\n         ++ rewrite - fi2.\n            f_equal.\n            rewrite -addn1.\n            rewrite -addnBA. 2: ssromega.\n            replace (i1 + i2 * N1 + i * N1 * N2 + (1 - 1)) with\n            (i1 + i2 * N1 + i * N1 * N2) by ssromega.\n            assert (i1 + i2 * N1 + i * N1 * N2 =\n                    (N1 * (i2 + i * N2)) + i1).\n            { rewrite -addnA.\n              replace (i * N1 * N2) with\n              (i  * N2 * N1).\n              rewrite - mulnDl.\n              rewrite mulnC addnC; auto.\n              do 2 rewrite -mulnA; f_equal.\n              rewrite mulnC. auto. }\n            eapply NPeano.Nat.div_unique in H0; auto.\n            rewrite - H0.\n            rewrite NPeano.Nat.mod_add.\n            apply NPeano.Nat.mod_small; auto.\n            destruct N2; omega.\n    + exists (S( N1 * N2)).\n      exists (fun n => if n == 0\n               then PTree.Leaf\n               else\n                 PTree.Node\n                   (F1 ( (n-1) mod N1))\n                   (None )\n                   (F2 (((n-1) / N1 ) mod N2))).\n      intros x spec.\n      destruct x.\n      * exists 0%nat; split; auto.\n        omega.\n      * move: spec .\n        rewrite /sub_map /= => [] [] FUN_lq [] tree1 tree2.\n        move : spec_F1 => /(_ _ tree1) [] i1 [] ineq1 fi1.\n        move : spec_F2 => /(_ _ tree2) [] i2 [] ineq2 fi2.\n        exists (S(i1 + (i2 * N1))); split.\n        { apply lt_n_S.\n          replace (N1 * N2) with\n          (N1 + N1 * (N2 -1)).\n          - eapply (NPeano.Nat.lt_le_trans).\n            + instantiate (1:= (N1 + i2 * N1)).\n              apply /ltP.\n              rewrite ltn_add2r;\n                apply /ltP; auto.\n            + apply /leP.\n              rewrite leq_add2l.\n              apply /leP.\n              rewrite mulnC.\n              apply /leP.\n              rewrite leq_pmul2l; try (apply /ltP; omega).\n              apply /leP.\n              eapply lt_n_Sm_le.\n              rewrite - addn1.\n              rewrite subnK; auto.\n              destruct N2; ssromega.\n\n          - replace (N1 + N1 * (N2 - 1))\n            with (N1 * 1 + N1 * (N2 - 1)).\n            + rewrite -mulnDr.\n              rewrite addnC.\n              rewrite subnK.\n              2: ssromega.\n              rewrite mulnC; auto.\n            + f_equal.\n              rewrite mulnC.\n              compute; auto. }\n      -- simpl; f_equal.\n         ++ rewrite - fi1.\n            f_equal.\n            rewrite -addn1.\n            rewrite -addnBA. 2: ssromega.\n            replace (i1 + i2 * N1 + (1 - 1)) with\n            (i1 + i2 * N1) by ssromega.\n            rewrite NPeano.Nat.mod_add.\n            apply NPeano.Nat.mod_small; auto.\n            destruct N1; omega.\n         ++ destruct o; auto; inversion FUN_lq.\n         ++ rewrite - fi2.\n            f_equal.\n            rewrite -addn1.\n            rewrite -addnBA. 2: ssromega.\n            replace (i1 + i2 * N1 + (1 - 1)) with\n            (i1 + i2 * N1 ) by ssromega.\n            assert (i1 + i2 * N1 =\n                    (N1 * (i2) + i1)).\n            { rewrite mulnC addnC; auto. }\n            eapply NPeano.Nat.div_unique in H0; auto.\n            rewrite - H0.\n            apply NPeano.Nat.mod_small; auto.\nQed.\n\nLemma fun_leq_trans: forall {A B C} f1 f2 f3, @fun_leq A B f1 f2 -> @fun_leq B C f2 f3 ->\n  @fun_leq A C f1 f3.\nProof.\n  unfold fun_leq, fun_leq'; destruct f1, f2, f3; auto.\nQed.\n\nLemma sub_map_trans: forall {A B C} m1 m2 m3, @sub_map A B m1 m2 -> @sub_map B C m2 m3 ->\n  @sub_map A C m1 m3.\nProof.\n  unfold sub_map; induction m1; destruct m2; intros; inversion H; destruct m3; inversion H0;\n    auto; simpl in *.\n  repeat split.\n  - eapply fun_leq_trans; eauto.\n  - apply (IHm1_1 m2_1); tauto.\n  - apply (IHm1_2 m2_2); tauto.\nQed.\n\nLemma same_shape_map:\n  forall {A B} m f,\n    @same_shape A B (PTree.map f m) m.\nProof.\n  intros until m.\n  unfold PTree.map.\n  pose (i:=1%positive); fold i.\n  generalize i; clear i.\n  induction m.\n  - intros;\n      unfold same_shape;\n      simpl; auto.\n  - intros;\n      unfold same_shape;\n      split; [| split].\n    + destruct o; simpl; auto.\n    + eapply IHm1.\n    + eapply IHm2.\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/concurrency/common/bounded_maps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2865734096611812}}
{"text": "\nRequire Export Iron.Language.SystemF2Cap.Step.Frame.\nRequire Export Iron.Language.SystemF2Cap.Store.Bind.\nRequire Export Iron.Language.SystemF2Cap.Store.TypeB.\nRequire Export Iron.Language.SystemF2Cap.Store.StoreT.\nRequire Export Iron.Language.SystemF2Cap.Store.StoreM.\nRequire Export Iron.Language.SystemF2Cap.Store.StoreP.\n\n\n(*******************************************************************)\n(* Well formed store. *)\nInductive WfS   : stenv -> stprops -> store -> Prop :=\n | WfS_\n   :  forall se sp ss\n   ,  Forall ClosedT se\n   -> StoreM se    ss\n   -> StoreT se sp ss\n   -> WfS se sp ss.\nHint Constructors WfS.\n\n\n(* Well formed store and frame stack. *)\nInductive WfFS : stenv -> stprops -> store -> stack -> Prop := \n | WfFS_\n   :  forall se sp ss fs\n   ,  Forall ClosedT se\n   -> StoreM se ss\n   -> StoreT se sp ss\n   -> StoreP sp fs\n   -> WfFS se sp ss fs.\nHint Constructors WfFS.\n\n\n(*******************************************************************)\n(* If a well formed frame stack and store is well formed,\n   then the store is also well formed by itself. *)\nLemma wfFS_wfS \n :  forall se sp ss fs\n ,  WfFS   se sp ss fs\n -> WfS    se sp ss.\nProof. intros. inverts H. eauto. Qed.\nHint Resolve wfFS_wfS.\n\n\nLemma wfFS_closedT\n :  forall se sp ss fs\n ,  WfFS   se sp ss fs\n -> Forall ClosedT se.\nProof. intros. inverts H. eauto. Qed.\nHint Resolve wfFS_closedT.\n\n\nLemma wfFS_typeb\n :  forall se sp ss fs b\n ,  WfFS se sp ss fs\n -> In b ss\n -> (exists t, TypeB nil nil se sp b t).\nProof. \n intros.\n inverts H. \n eapply Forall2_exists_left; eauto.\nQed.\nHint Resolve wfFS_typeb.\n\n\n(* The region handles of private regions are present in the\n   store properties. *)\nLemma wfFS_fpriv_sregion\n :  forall se sp ss fs m1 p2 ts\n ,  WfFS se sp ss fs\n -> In (FPriv   m1 p2 ts) fs\n -> In (SRegion p2)    sp.\nProof. intros. inverts H. firstorder. Qed.\nHint Resolve wfFS_fpriv_sregion.\n\n\n(* The length of the store enviroment is the same as the length\n   of the store. We have one entry in the store environment for\n   each binding in the store. *)\nLemma wfFS_storem_length\n :  forall se sp ss fs\n ,  WfFS   se sp ss fs\n -> length se = length ss.\nProof. intros. inverts H. auto. Qed.\nHint Resolve wfFS_storem_length.\n\n\n(* Creating a top level private region preserves well-formedness\n   of the store. *)\nLemma wfFS_push_priv_top\n :  forall se sp ss fs p2 ts\n ,  WfFS se sp ss fs\n -> WfFS se (SRegion p2 <: sp) ss (fs :> FPriv None p2 ts).\nProof. intros. inverts H. auto. Qed.\nHint Resolve wfFS_push_priv_top.\n\n\n(* Creating an extension region preserves well-formedness \n   of the store. *)\nLemma wfFS_push_priv_ext\n :  forall se sp ss fs p1 p2 ts\n ,  In (SRegion p1) sp\n -> WfFS  se  sp ss fs\n -> WfFS  se  (SRegion p2 <: sp) ss (fs :> FPriv (Some p1) p2 ts).\nProof.\n intros.\n inverts H0. eapply WfFS_; rip.\n unfold StoreP in *. rip.\n - inverts H0; eauto. \n   inverts H4. eauto.\n - inverts H0; eauto.\n   inverts H4; eauto.\nQed. \nHint Resolve wfFS_push_priv_ext.\n\n\n(* Deallocating a region preserves well-formedness of the store. *)\nLemma typeB_deallocate\n :  forall ke te se sp p b t\n ,  TypeB  ke te se sp b t\n -> TypeB  ke te se sp (deallocRegion p b) t.\nProof.\n intros.\n destruct b.\n - snorm. subst.\n   inverts H. eauto.\n - snorm.\nQed.\n\n\n(* Deallocating bindings preserves the well typedness of the store. *)\nLemma storeT_deallocate\n :  forall se sp ss p\n ,  StoreT se sp ss\n -> StoreT se sp (map (deallocRegion p) ss).\nProof.\n intros.\n unfold StoreT in *.\n eapply Forall2_map_left.\n eapply Forall2_impl.\n - intros.\n    eapply typeB_deallocate. eauto. \n - auto.\nQed.\n\n\n(* Deallocating top-level region on the top of the frame stack\n   preserves the well formedness of the store. *)\nLemma wfFS_region_deallocate\n :  forall se sp ss fs p ts\n ,  WfFS se sp ss (fs :> FPriv None p ts)\n -> WfFS se sp (map (deallocRegion p) ss) fs.\nProof.\n intros.\n inverts H. eapply WfFS_; rip.\n - unfold StoreM in *.\n   rewrite map_length; auto.\n - eapply storeT_deallocate; auto.\n - unfold StoreP in *; snorm; eauto.\nQed.\n\n\nLemma wfFS_pop_priv_ext\n :  forall se sp ss fs p1 p2 ts\n ,  In (SRegion p1) sp\n -> WfFS se sp ss (fs :> FPriv (Some p1) p2 ts)\n -> WfFS (mergeTE p1 p2 se) sp (mergeBs p1 p2 ss) fs.\nProof.\n intros.\n inverts H0. split.\n - eapply Forall_map.\n   eapply Forall_impl with (P := ClosedT).\n   + intros. eapply mergeT_wfT; eauto.\n   + auto.\n\n - unfold StoreM in *.\n   unfold mergeTE. \n   unfold mergeBs.\n   repeat (rewrite map_length). auto.\n\n - unfold StoreT.\n   eapply storeT_mergeB; auto.\n   \n - eapply storeP_pop; eauto.\nQed.\n\n\n(* Appending a closed store binding to the store preserves its \n   well formedness. *)\nLemma wfFS_stbind_snoc\n :  forall se sp ss fs p v t\n ,  In (SRegion p) sp\n -> TypeV  nil nil se sp v t\n -> WfFS           se sp ss fs\n -> WfFS   (TRef (TRgn p) t <: se) sp \n           (StValue p v <: ss) fs.\nProof.\n intros.\n inverts H1.\n eapply WfFS_; rip.\n eapply Forall_snoc; eauto.\nQed.\n\n\n(* Updating bindings preserves the well formedness of the store. *)\nLemma wfFS_stbind_update\n :  forall se sp ss fs l p v t\n ,  get l se = Some (TRef (TRgn p) t)\n -> In (SRegion p) sp\n -> TypeV nil nil se sp v t\n -> WfFS se sp ss fs\n -> WfFS se sp (update l (StValue p v) ss) fs.\nProof.\n intros se sp ss fs l p v t HG HK HV HWF1.\n inverts HWF1. eapply WfFS_; rip.\n - have (length se = length ss).\n   unfold StoreM.\n   rewritess.\n   rewrite update_length. auto.\n - unfold StoreT.\n   eapply Forall2_update_right; 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/Store/Wf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2865734096611812}}
{"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  Inductive LoadU_failure (regs: Reg) (rdst rsrc: RegName) (offs: Z + RegName) (mem : PermMem):=\n  | LoadU_fail_const z:\n      regs !! rsrc = Some (inl z) ->\n      LoadU_failure regs rdst rsrc offs mem\n  | LoadU_fail_perm p g b e a:\n      regs !! rsrc = Some (inr ((p, g), b, e, a)) ->\n      isU p = false ->\n      LoadU_failure regs rdst rsrc offs mem\n  | LoadU_fail_offs_arg p g b e a:\n      regs !! rsrc = Some (inr ((p, g), b, e, a)) ->\n      isU p = true ->\n      z_of_argument regs offs = None ->\n      LoadU_failure regs rdst rsrc offs mem\n  | LoadU_fail_verify_access p g b e a noffs:\n      regs !! rsrc = Some (inr ((p, g), b, e, a)) ->\n      isU p = true ->\n      z_of_argument regs offs = Some noffs ->\n      verify_access (LoadU_access b e a noffs) = None ->\n      LoadU_failure regs rdst rsrc offs mem\n  | LoadU_fail_incrementPC p g b e a noffs a' p' w:\n      regs !! rsrc = Some (inr ((p, g), b, e, a)) ->\n      isU p = true ->\n      z_of_argument regs offs = Some noffs ->\n      verify_access (LoadU_access b e a noffs) = Some a' ->\n      mem !! a' = Some(p', w) →\n      incrementPC (<[ rdst := w ]> regs) = None ->\n      LoadU_failure regs rdst rsrc offs mem.\n\n  Inductive LoadU_spec\n    (regs: Reg) (rdst rsrc: RegName) (offs: Z + RegName)\n    (regs': Reg) (mem : PermMem) : cap_lang.val → Prop\n  :=\n  | LoadU_spec_success p p' g b e a a' noffs w :\n      regs !! rsrc = Some (inr ((p, g), b, e, a)) ->\n      isU p = true ->\n      z_of_argument regs offs = Some noffs ->\n      verify_access (LoadU_access b e a noffs) = Some a' ->\n      mem !! a' = Some(p', w) →\n      incrementPC (<[ rdst := w ]> regs) = Some regs' ->\n      LoadU_spec regs rdst rsrc offs regs' mem NextIV\n  | LoadU_spec_failure :\n    LoadU_failure regs rdst rsrc offs mem ->\n    LoadU_spec regs rdst rsrc offs regs' mem FailedV.\n  \n  Lemma wp_loadU Ep\n     pc_p pc_g pc_b pc_e pc_a pc_p'\n     rdst rsrc offs w mem regs :\n   decodeInstrW w = LoadU rdst rsrc offs →\n   pc_p' ≠ O →\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 (LoadU rdst rsrc offs) ⊆ dom _ regs →\n   mem !! pc_a = Some (pc_p', w) →\n   match regs !! rsrc with\n   | None => True\n   | Some (inl _) => True\n   | Some (inr (p, g, b, e, a)) =>\n     if isU p then\n       match z_of_argument regs offs with\n       | None => True\n       | Some zoffs => match verify_access (LoadU_access b e a zoffs) with\n                      | None => True\n                      | Some a' => match mem !! a' with\n                                  | None => False\n                                  | Some (p', w) => p' <> O\n                                  end\n                      end\n       end\n     else True\n   end ->\n\n   {{{ (▷ [∗ map] a↦pw ∈ mem, ∃ p w, ⌜pw = (p,w)⌝ ∗ a ↦ₐ[p] w) ∗\n       ▷ [∗ map] k↦y ∈ regs, k ↦ᵣ y }}}\n     Instr Executable @ Ep\n   {{{ regs' retv, RET retv;\n       ⌜ LoadU_spec regs rdst rsrc offs regs' mem retv⌝ ∗\n         ([∗ map] a↦pw ∈ mem, ∃ p w, ⌜pw = (p,w)⌝ ∗ a ↦ₐ[p] w) ∗\n         [∗ map] k↦y ∈ regs', k ↦ᵣ y }}}.\n   Proof.\n     iIntros (Hinstr Hfl Hvpc HPC Dregs Hmem_pc HaLoad φ) \"(>Hmem & >Hmap) Hφ\".\n     iApply wp_lift_atomic_head_step_no_fork; auto.\n     iIntros (σ1 l1 l2 n) \"[Hr Hm] /=\". destruct σ1; simpl.\n     iDestruct (gen_heap_valid_inclSepM with \"Hr Hmap\") as %Hregs.\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 rsrc) as [rsrcv [Hrsrc' Hrsrc]]. by set_solver+.\n     feed destruct (Hri rdst) as [rdstv [Hrdst' _]]. by set_solver+.\n     pose proof (regs_lookup_eq _ _ _ Hrsrc') as Hrsrc''.\n     pose proof (regs_lookup_eq _ _ _ Hrdst') as Hrdst''.\n     (* Derive the PC in memory *)\n     iDestruct (gen_mem_valid_inSepM pc_a _ _ _ _ mem _ m with \"Hm Hmem\") as %Hma; eauto.\n     \n     iModIntro.\n     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     option_locate_mr m r.\n     rewrite /exec in Hstep. rewrite Hrrsrc in Hstep.\n\n     destruct rsrcv as [| [[[[p g] b] e] a] ].\n     { inv Hstep. iFailWP \"Hφ\" LoadU_fail_const. }\n\n     destruct (isU p) eqn:HisU; cycle 1.\n     { inv Hstep. iFailWP \"Hφ\" LoadU_fail_perm. }\n\n     assert (Hzofargeq: z_of_argument r offs = z_of_argument regs offs).\n     { rewrite /z_of_argument; destruct offs; auto.\n       feed destruct (Hri r0) as [? [?]]. by set_solver+.\n       rewrite H2 H3; auto. }\n     rewrite Hzofargeq in Hstep.\n\n     destruct (z_of_argument regs offs) as [zoffs|] eqn:Hoffs; cycle 1.\n     { inv Hstep. iFailWP \"Hφ\" LoadU_fail_offs_arg. }\n\n     destruct (verify_access (LoadU_access b e a zoffs)) as [a'|] eqn:Hverify; cycle 1.\n     { inv Hstep. iFailWP \"Hφ\" LoadU_fail_verify_access. }\n     simpl in Hstep. rewrite Hrsrc' HisU Hverify in HaLoad.\n     rewrite /MemLocate in Hstep. destruct (mem !! a') as [(p', wa)|] eqn:Ha'; cycle 1.\n     { inv HaLoad. }\n     iDestruct (gen_mem_valid_inSepM a' _ _ _ _ mem _ m with \"Hm Hmem\") as %Hma'; eauto.\n     rewrite Hma' in Hstep. destruct (incrementPC (<[rdst:=wa]> regs)) eqn:Hincr; cycle 1.\n     { assert _ as Hincr' by (eapply (incrementPC_overflow_mono (<[rdst:=wa]> regs) (<[rdst:=wa]> r) _ _ _)).\n       rewrite incrementPC_fail_updatePC in Hstep; eauto.\n       inv Hstep. simpl.\n       iMod ((gen_heap_update_inSepM _ _ rdst) with \"Hr Hmap\") as \"[Hr Hmap]\"; eauto.\n       iFailWP \"Hφ\" LoadU_fail_incrementPC. }\n\n     destruct (incrementPC_success_updatePC _ m _ Hincr) 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     iMod ((gen_heap_update_inSepM _ _ rdst) 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.\n     iPureIntro. econstructor; eauto.\n     Unshelve. all: eauto.\n     { destruct (reg_eq_dec PC rdst).\n       - subst rdst. rewrite lookup_insert. eauto.\n       - rewrite lookup_insert_ne; eauto. }\n     { eapply insert_mono; eauto. }\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_LoadU.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.28657340276781285}}
{"text": "Require Import bedrock2.Syntax bedrock2.NotationsCustomEntry.\nRequire Import bedrock2.FE310CSemantics.\n\nImport Syntax BinInt String Datatypes List List.ListNotations ZArith.\nLocal Open Scope string_scope. Local Open Scope Z_scope. Local Open Scope list_scope.\n\nDefinition silly1 := func! (a) ~> c {\n  b = load4(a + $16);\n  store4(a + $14, b);\n  c = load4(a + $16)\n}.\n\nRequire Import coqutil.Macros.symmetry.\n\nRequire Import coqutil.Word.Interface coqutil.Word.Properties.\nRequire Import bedrock2.Semantics bedrock2.ProgramLogic bedrock2.Array.\nRequire Import bedrock2.Map.Separation bedrock2.Map.SeparationLogic.\nRequire Import Coq.Lists.List coqutil.Map.OfListWord.\nRequire Import coqutil.Z.Lia.\nRequire Import coqutil.Tactics.Tactics.\nRequire Import coqutil.Tactics.letexists.\nRequire Import coqutil.Tactics.rdelta.\nRequire Import coqutil.Word.Bitwidth32.\nImport Map.Interface Interface.map OfFunc.map OfListWord.map.\nRequire Import bedrock2.AbsintWordToZ.\nRequire Import bedrock2.groundcbv.\nRequire Import coqutil.Tactics.rewr.\nRequire Import AdmitAxiom.\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  Add Ring wring : (Properties.word.ring_theory (word := word))\n        (preprocess [autorewrite with rew_word_morphism],\n         morphism (Properties.word.ring_morph (word := word)),\n         constants [Properties.word_cst]).\n\n  Local Instance spec_of_silly1 : spec_of \"silly1\" := fun functions =>\n      forall t m a bs R, Z.of_nat (length bs) = 32 ->\n      (sep (eq (map.of_list_word_at a bs)) R) m ->\n      WeakestPrecondition.call functions \"silly1\" t m [a]\n      (fun T M rets => True).\n\n  Ltac ring_simplify_unsigned_goal :=\n    match goal with\n    |- context [word.unsigned ?x] =>\n      let Hrw := fresh in\n      eassert (let y := _ in x = y) as Hrw by (\n        let y := fresh in\n        intros y; ring_simplify;\n        subst y; trivial);\n      rewrite !Hrw; clear Hrw\n    end.\n  Ltac ring_simplify_unsigned_in H :=\n    match type of H with context [word.unsigned ?x] =>\n      let Hrw := fresh in\n      eassert (let y := _ in x = y) as Hrw by (\n        let y := fresh in\n        intros y; ring_simplify;\n        subst y; trivial);\n      rewrite !Hrw in H; clear Hrw\n    end.\n  Ltac ring_simplify_unsigned :=\n    try ring_simplify_unsigned_goal;\n    repeat match goal with\n           | H: context [word.unsigned ?x] |- _ => ring_simplify_unsigned_in H\n           end.\n\n  Ltac unify_and_change lhs rhs :=\n    let rhs := match rhs with ?x => x end in\n    let __ := constr:(eq_refl : lhs = rhs) in\n    change lhs with rhs in *.\n\n  Ltac change_with_Z_literal W :=\n    first [ let e := open_constr:(BinInt.Zpos _) in\n            unify_and_change W e;\n            requireZcst e\n          | unify_and_change W open_constr:(BinInt.Z0)\n          | let e := open_constr:(BinInt.Zneg _) in\n            unify_and_change W e;\n            requireZcst e].\n\n  Ltac simplify_ZcstExpr_goal :=\n    match goal with\n    |- context [?e] =>\n        requireZcstExpr e;\n        assert_fails (idtac; requireZcst e);\n        let e' := eval vm_compute in e in\n        let Hrw := fresh in\n        assert (e = e') as Hrw by (vm_cast_no_check (eq_refl e'));\n        (* idtac \"simplified\" e \"in GOAL\"; *)\n        progress rewrite Hrw; clear Hrw\n    end.\n\n  Ltac simplify_ZcstExpr_in H :=\n    match type of H with context [?e] =>\n        requireZcstExpr e;\n        assert_fails (idtac; requireZcst e);\n        let e' := eval vm_compute in e in\n        let Hrw := fresh in\n        assert (e = e') as Hrw by (vm_cast_no_check (eq_refl e'));\n        (* idtac \"simplified\" e \"in\" H; *)\n        progress rewrite Hrw in H; clear Hrw\n    end.\n\n  Ltac simplify_ZcstExpr_hyps :=\n    repeat match goal with H : _ |- _ => simplify_ZcstExpr_in H end.\n\n  Ltac simplify_ZcstExpr :=\n    simplify_ZcstExpr_hyps; try simplify_ZcstExpr_goal.\n\n  Ltac rewrite_unsigned_of_Z_goal :=\n    match goal with\n    |- context [@word.unsigned ?w ?W ?X] =>\n      let E := constr:(@word.unsigned w W X) in\n      let x := rdelta X in\n      let z := match x with word.of_Z ?z => z end in\n      rewrite ((@word.unsigned_of_Z w W _ z) : E = z mod 2^w)\n    end.\n\n  Ltac rewrite_unsigned_of_Z_in H :=\n    match type of H with context [@word.unsigned ?w ?W ?X] =>\n      let E := constr:(@word.unsigned w W X) in\n      let x := rdelta X in\n      let z := match x with word.of_Z ?z => z end in\n      rewrite ((@word.unsigned_of_Z w W _ z) : E = z mod 2^w) in H\n    end.\n\n  Ltac wordcstexpr_tac := (* hacky *)\n    repeat first\n          [ progress ring_simplify_unsigned\n          | rewrite !word.unsigned_add; cbv [word.wrap]\n          | rewrite_unsigned_of_Z_goal ];\n    repeat simplify_ZcstExpr_goal; trivial.\n\n  Lemma List__splitZ_spec [A] (xsys : list A) i (H : 0 <= i < Z.of_nat (length xsys)) :\n    let xs := firstn (Z.to_nat i) xsys in\n    let ys := skipn (Z.to_nat i) xsys in\n    xsys = xs ++ ys /\\\n    Z.of_nat (length xs) = i /\\\n    Z.of_nat (length ys) = Z.of_nat (length xsys) - i.\n  Proof.\n    pose proof eq_sym (firstn_skipn (Z.to_nat i) xsys).\n    split; trivial.\n    rewrite length_firstn_inbounds, length_skipn; blia.\n  Qed.\n\n  Ltac lift_head_let_in H :=\n    match type of H with\n    | let x := ?v in ?C =>\n        let X := fresh x in\n        pose v as X;\n        let C := constr:(match X with x => C end) in\n        change C in H\n    end.\n\n  Ltac flatten_hyps :=\n    repeat match goal with\n           | H : let x := ?v in ?C |- _ =>\n               let X := fresh x in\n               pose v as X;\n               let C := constr:(match X with x => C end) in\n               change C in H\n           | H : _ /\\ _ |- _ => destruct H\n           | H : exists _, _ |- _ => destruct H\n           end.\n\n  Lemma List__splitZ_spec_n [A] (xsys : list A) i n\n    (Hn : Z.of_nat (length xsys) = n) (H : 0 <= i < n) :\n    let xs := firstn (Z.to_nat i) xsys in\n    let ys := skipn (Z.to_nat i) xsys in\n    xsys = xs ++ ys /\\\n    Z.of_nat (length xs) = i /\\\n    Z.of_nat (length ys) = n - i.\n  Proof.\n    pose proof eq_sym (firstn_skipn (Z.to_nat i) xsys).\n    split; trivial.\n    rewrite length_firstn_inbounds, length_skipn; blia.\n  Qed.\n\n  Ltac List__splitZ bs n :=\n      match goal with H: Z.of_nat (length bs) = _ |- _ =>\n          pose proof List__splitZ_spec_n bs n _ H ltac:(blia);\n          clear H; flatten_hyps; simplify_ZcstExpr;\n          let Hrw := lazymatch goal with H : bs = _ ++ _ |- _ => H end in\n          let eqn := type of Hrw in\n          rewr ltac:(fun t => match t with\n                              | eqn => fail 1\n                              | _ => constr:(Hrw) end) in *\n      end.\n\n  Lemma map__of_list_word_at_app_n [value] [map : map.map word value] {ok : map.ok map}\n    (a : word) (xs ys : list value)\n    lxs (Hlxs : Z.of_nat (length xs) = lxs)\n    : map.of_list_word_at a (xs ++ ys)\n    = putmany (map.of_list_word_at (word.add a (word.of_Z lxs)) ys) (map.of_list_word_at a xs).\n  Proof. subst lxs; apply map.of_list_word_at_app. Qed.\n\n  Lemma map__adjacent_arrays_disjoint_n [value] [map : map.map word value] {ok : map.ok map}\n    (a : word) (xs ys : list value)\n    lxs (Hlxs : Z.of_nat (length xs) = lxs)\n    (H :Z.of_nat (length xs) + Z.of_nat (length ys) <= 2 ^ 32)\n    : disjoint (map.of_list_word_at (word.add a (word.of_Z lxs)) ys) (map.of_list_word_at a xs).\n  Proof. subst lxs. auto using map.adjacent_arrays_disjoint. Qed.\n\n      Declare Scope word_scope.\n      Bind Scope word_scope with word.\n      Delimit Scope word_scope with word.\n      Local Notation \"a + b\" := (word.add a b) (at level 50, left associativity, format \"a + b\") : word_scope.\n      Local Infix \"-\" := word.sub : word_scope.\n      Local Coercion Z.of_nat : nat >-> Z.\n      Local Infix \"$+\" := putmany (at level 70).\n      Local Notation \"xs $@ a\" := (map.of_list_word_at a%word xs) (at level 10, format \"xs $@ a\").\n      Local Notation \"! x\" := (word.of_Z x) (at level 10, format \"! x\").\n      Local Notation \"a * b\" := (sep a%type b%type) : type_scope.\n      Local Open Scope word_scope.\n\n  Lemma sep_eq_putmany [key value] [map : map.map key value] (a b : map) (H : disjoint a b) : Lift1Prop.iff1 (eq (a $+ b)) (sep (eq a) (eq b)).\n  Proof.\n    split.\n    { intros; subst. eexists _, _; eauto using Properties.map.split_disjoint_putmany. }\n    { intros (?&?&(?&?)&?&?); subst; trivial. }\n  Qed.\n\n  Lemma sep_eq_of_list_word_at_app [value] [map : map.map word value] {ok : map.ok map}\n    (a : word) (xs ys : list value)\n    lxs (Hlxs : Z.of_nat (length xs) = lxs) (Htotal : length xs + length ys <= 2^32)\n    : Lift1Prop.iff1 (eq (map.of_list_word_at a (xs ++ ys)))\n      (sep (eq (map.of_list_word_at a xs)) (eq (map.of_list_word_at (word.add a (word.of_Z lxs)) ys))).\n  Proof.\n    etransitivity.\n    2: eapply sep_comm.\n    etransitivity.\n    2: eapply sep_eq_putmany, map__adjacent_arrays_disjoint_n; trivial.\n    erewrite map__of_list_word_at_app_n by eauto; reflexivity.\n  Qed.\n\n  Lemma list_word_at_app_of_adjacent_eq [value] [map : map.map word value] {ok : map.ok map}\n    (a b : word) (xs ys : list value)\n    (Hl: word.unsigned (word.sub b a) = Z.of_nat (length xs))\n    (Htotal : length xs + length ys <= 2^32)\n    : Lift1Prop.iff1\n        (sep (eq (map.of_list_word_at a xs)) (eq (map.of_list_word_at b ys)) )\n        (eq (map.of_list_word_at a (xs ++ ys))).\n  Proof.\n    etransitivity.\n    2:symmetry; eapply sep_eq_of_list_word_at_app; trivial.\n    do 3 Morphisms.f_equiv. rewrite <-Hl, word.of_Z_unsigned. ring.\n  Qed.\n\n  Lemma of_list_word_nil\n    [value] [map : map.map word value] {ok : map.ok map}\n    k : []$@k = empty(map:=map).\n  Proof. apply Properties.map.fold_empty. Qed.\n  Lemma of_list_word_singleton\n    [value] [map : map.map word value] {ok : map.ok map}\n    (k : word) (v : value) : [v]$@k = put empty k v.\n  Proof.\n    cbv [of_list_word_at of_list_word seq length List.map of_func update].\n    rewrite word.unsigned_of_Z_0, Z2Nat.inj_0; cbv [MapKeys.map.map_keys nth_error].\n    rewrite Properties.map.fold_singleton.\n    f_equal; cbn [Z.of_nat].\n    eapply word.unsigned_inj; rewrite word.unsigned_add; cbv [word.wrap]; rewrite word.unsigned_of_Z_0, Z.add_0_r, Z.mod_small; trivial; eapply word.unsigned_range.\n  Qed.\n\n  Import ptsto_bytes Lift1Prop Morphisms.\n  Lemma eq_of_list_word_iff_array1 [value] [map : map.map word value] {ok : map.ok map}\n    (a : word) (bs : list value)\n    (H : length bs <= 2 ^ 32) :\n    iff1 (eq (bs$@a)) (array ptsto (word.of_Z 1) a bs).\n  Proof.\n    revert H; revert a; induction bs; cbn [array]; intros.\n    { rewrite of_list_word_nil; cbv [emp iff1]; intuition auto. }\n    { etransitivity.\n      2: eapply Proper_sep_iff1.\n      3: eapply IHbs.\n      2: reflexivity.\n      2: cbn [length] in H; blia.\n      change (a::bs) with ([a]++bs).\n      rewrite of_list_word_at_app.\n      etransitivity.\n      1: eapply sep_eq_putmany, adjacent_arrays_disjoint; cbn [length] in *; blia.\n      etransitivity.\n      2:eapply sep_comm.\n      f_equiv.\n      rewrite of_list_word_singleton; try exact _.\n      cbv [ptsto iff1]; intuition auto. }\n  Qed.\n\n  Ltac ring_simplify_address_in H :=\n    match type of H with context [_ $@ ?x] =>\n      let Hrw := fresh in\n      eassert (let y := _ in x = y) as Hrw by (\n        let y := fresh in\n        intros y; ring_simplify;\n        subst y; trivial);\n      rewrite !Hrw in H; clear Hrw\n    end.\n\n  Ltac split_bytes_base_addr bs a0 ai :=\n      let raw_i := constr:(word.unsigned (ai-a0)%word) in\n      let Hidx := fresh \"Hidx\" in\n      eassert (raw_i = _) as Hidx by (\n        ring_simplify_unsigned_goal; repeat rewrite_unsigned_of_Z_goal;\n        simplify_ZcstExpr; exact eq_refl);\n      let i := match type of Hidx with _ = ?r => r end in\n      let Happ := fresh \"Happ\" in\n      match goal with H: Z.of_nat (length bs) = _ |- _ =>\n          pose proof List__splitZ_spec_n bs i _ H ltac:(blia) as Happ;\n          clear H\n      end;\n      repeat lift_head_let_in Happ; case Happ as (Happ&?H1l&?H2l);\n      simplify_ZcstExpr;\n      let eqn := type of Happ in\n      rewr ltac:(fun t => match t with\n                          | eqn => fail 1\n                          | _ => constr:(Happ) end) in *;\n      repeat match goal with Hsep : _ |- _ =>\n        seprewrite_in_by sep_eq_of_list_word_at_app Hsep ltac:(\n          try eassumption; try blia)\n      end.\n\n  Section __.\n    Import WithoutTuples.\n    Lemma load_bytes_of_putmany_bytes_at bs a (mR:mem) n (Hn : length bs = n) (Hl : Z.of_nat n < 2^32)\n      : load_bytes (mR $+ bs$@a) a n = Some bs.\n    Proof.\n      destruct (load_bytes (mR $+ bs$@a) a n) eqn:HN in *; cycle 1.\n      { exfalso; eapply load_bytes_None in HN; case HN as (i&?&?).\n        case (Properties.map.putmany_spec mR (bs$@a) (a+!(BinIntDef.Z.of_nat i))%word) as [(?&?&?)| (?&?) ]; try congruence.\n        rewrite get_of_list_word_at in H1; eapply nth_error_None in H1.\n        revert H1.\n        rewrite word.word_sub_add_l_same_l, word.unsigned_of_Z.\n        cbv [word.wrap]; rewrite Z.mod_small, Nat2Z.id; eauto; blia. }\n      transitivity (Some l); try congruence; f_equal; subst n.\n      symmetry; eapply nth_error_ext_samelength.\n      { symmetry; eauto using length_load_bytes. }\n      intros.\n      pose proof nth_error_load_bytes _ a _ _ HN i ltac:(trivial) as HH.\n      epose proof H; eapply nth_error_nth' with (d:=Byte.x00) in H.\n      erewrite Properties.map.get_putmany_right in HH; cycle 1.\n      { rewrite get_of_list_word_at.\n        rewrite word.word_sub_add_l_same_l, word.unsigned_of_Z.\n        cbv [word.wrap]; rewrite Z.mod_small, Nat2Z.id; eauto; blia. }\n      congruence.\n    Qed.\n\n    Lemma load_bytes_of_sep_bytes_at bs a R (m:mem) (Hsep: (eq(bs$@a)*R) m) n (Hn : length bs = n) (Hl : Z.of_nat n < 2^32)\n      : load_bytes m a n = Some bs.\n    Proof.\n      eapply sep_comm in Hsep.\n      destruct Hsep as (mR&?&(?&?)&?&?); subst.\n      eapply load_bytes_of_putmany_bytes_at; eauto.\n    Qed.\n  End __.\n\n  Lemma load_four_bytes_of_sep_at bs a R (m:mem) (Hsep: (eq(bs$@a)*R) m) (Hl : length bs = 4%nat) :\n    load access_size.four m a = Some (word.of_Z (LittleEndianList.le_combine bs)).\n  Proof.\n    eapply Scalars.load_four_bytes_of_sep_at; try eassumption.\n  Qed.\n\n  Lemma uncurried_load_four_bytes_of_sep_at bs a R (m : mem)\n    (H: (eq(bs$@a)*R) m /\\ length bs = 4%nat) :\n    load access_size.four m a = Some (word.of_Z (LittleEndianList.le_combine bs)).\n  Proof. eapply Scalars.uncurried_load_four_bytes_of_sep_at; try eassumption. Qed.\n\n  Lemma Z_uncurried_load_four_bytes_of_sep_at bs a R (m : mem)\n    (H: (eq(bs$@a)*R) m /\\ Z.of_nat (length bs) = 4) :\n    load access_size.four m a = Some (word.of_Z (LittleEndianList.le_combine bs)).\n  Proof. eapply Scalars.Z_uncurried_load_four_bytes_of_sep_at; try eassumption. Qed.\n\n  (*\n  Lemma store_four_of_sep addr (oldvalue : word32) (value : word) R m (post:_->Prop)\n    (Hsep : sep (scalar32 addr oldvalue) R m)\n    (Hpost : forall m, sep (scalar32 addr (word.of_Z (word.unsigned value))) R m -> post m)\n    : exists m1, Memory.store Syntax.access_size.four m addr value = Some m1 /\\ post m1.\n  Proof.\n  *)\n\n  Ltac split_flat_memory_based_on_goal :=\n    lazymatch goal with\n    | |- load ?sz ?m ?a = _ =>\n        let sz := eval cbv in (Z.of_nat (bytes_per (width:=32) sz)) in\n        match goal with H : ?S m |- _ =>\n        match S with context[?bs $@ ?a0] =>\n        let a_r := constr:(word.add a (word.of_Z sz)) in\n        split_bytes_base_addr bs a0 a_r end;\n        match type of H with context[?bs $@ ?a0] =>\n        split_bytes_base_addr bs a0 a end end\n    | |- WeakestPrecondition.store ?sz ?m ?a _ _ =>\n        let sz := eval cbv in (Z.of_nat (bytes_per (width:=32) sz)) in\n        match goal with H : ?S m |- _ =>\n        match S with context[?bs $@ ?a0] =>\n        let a_r := constr:(word.add a (word.of_Z sz)) in\n        split_bytes_base_addr bs a0 a_r end;\n        match type of H with context[?bs $@ ?a0] =>\n        split_bytes_base_addr bs a0 a end end\n    end.\n\n  Ltac subst_lets :=\n    repeat match goal with x := ?v |- _ => assert_fails (is_evar v); subst x end.\n\n  Ltac set_evars :=\n    repeat match goal with\n           | |- context [?e] => is_evar e; set e in *\n           | H: context [?e] |- _ => is_evar e; set e in *\n           end.\n  Ltac subst_evars :=\n    repeat match goal with\n    x := ?e |- _ => is_evar e; subst x\n           end.\n\n  Lemma and_weaken_left (A A' B : Prop) : A -> A' -> A /\\ B -> A' /\\ B.\n  Proof. tauto. Qed.\n\n  Ltac on_left tac :=\n      let A := open_constr:(_:Prop) in\n      let k := open_constr:(_:A) in\n      unshelve simple notypeclasses refine (and_weaken_left A _ _ k _ _);\n        [> tac; try [> exact k ] | ];\n      cbv delta [and_weaken_left] (* drop cast *);\n      (* did tac solve the goal? *)\n      (* \"match A with ?A\" strips outer casts *)\n      tryif match A with ?A => is_evar A end\n      then simple notypeclasses refine (conj I _)\n      else idtac.\n  Tactic Notation \"on_left\" tactic3(tac) := on_left tac.\n\n  Import ProgramLogic.Coercions.\n\n  (* note: do we want an Ltac coding rule that tactics must not start with a match? *)\n  Local Ltac ecancel_assumption := idtac; SeparationLogic.ecancel_assumption.\n\n(*\nImport coqutil.Macros.subst.\nLtac flatten_hyps :=\n  repeat match goal with\n  | H : exists _, _ |- _ => destruct H as (?&H)\n  | H : _ /\\ _  |- _ => destruct H as (?&H)\n  | H : let x := ?v in ?C |- _ =>\n      let y := fresh x in pose v as y;\n        change (subst! y for x in C) in H\n  end.\n*)\nLtac flatten_goal :=\n  repeat match goal with\n         | |- (_ /\\ _) /\\ _ => eapply and_assoc\n         end.\nLtac flatten := flatten_hyps; flatten_goal.\n\nLtac simpl_lengths_step :=\n  match goal with\n  | _ => progress groundcbv_in_all\n  | H : Z.of_nat (length ?x) = ?v |- _ =>\n    let t' := type of H in\n    assert_fails(t'); first [is_var v | is_ground v];\n    progress rewr ltac:(fun t =>\n      match t with\n      | t' => fail 1\n      | context[Z.of_nat (length x)] => H\n      end) in *\n  | _ => progress rewr ltac:(fun t =>\n      match t with\n      | context[@List.length ?A (List.app ?x ?y)] => constr:(@app_length A x y)\n      end) in *\n  end.\nLtac simpl_lengths := repeat simpl_lengths_step.\n\n  Lemma silly1_ok : program_logic_goal_for_function! silly1.\n  Proof.\n    repeat (straightline || apply WeakestPreconditionProperties.dexpr_expr).\n\n    eexists ?[v].\n\n    on_left eapply Z_uncurried_load_four_bytes_of_sep_at.\n\n    pose proof List__splitZ_spec_n bs 20 _ H ltac:(blia).\n    flatten; simpl_lengths.\n    set_evars; rewrite H1 in *; subst_evars.\n    seprewrite_in_by sep_eq_of_list_word_at_app H0\n      ltac:(trivial || blia); simpl_lengths.\n\n    pose proof List__splitZ_spec_n _ 16 _ H2 ltac:(blia);\n    flatten; simpl_lengths.\n    set_evars; rewrite H4 in *; subst_evars; simpl_lengths.\n    seprewrite_in_by sep_eq_of_list_word_at_app H0\n      ltac:(trivial || blia); simpl_lengths.\n\n    on_left ecancel_assumption. (*  this inlines definition of ys0, makes length proof annoying *)\n    match goal with |- context[?x] => change x with ys0 end.\n\n    split; [ trivial | ].\n\n    repeat straightline. (* this inlines too many lets *)\n\n    (* store4(a + $14, b); *)\n\n    cbv [WeakestPrecondition.store].\n\n    (* remerge *)\n    seprewrite_in_by @list_word_at_app_of_adjacent_eq H0 ltac:(\n      simpl_lengths; rewrite ?word.word_sub_add_l_same_l, ?word.unsigned_of_Z; trivial; clear;blia).\n    repeat seprewrite_in_by @list_word_at_app_of_adjacent_eq H0 ltac:(\n      rewrite ?app_length; wordcstexpr_tac; simpl_lengths; blia).\n\n    Tactics.rapply (fun addr oldvalue value R m post H => Scalars.store_four_of_sep addr oldvalue value R m post (proj1 H) (proj2 H)).\n\n    (* note: it would be nice to have a generalization of this /\\-goal logic in on_left *)\n    unshelve (\n    let x := open_constr:(_ : _ /\\ (_ /\\ _)) in\n    once (on_left (idtac; seprewrite (symmetry! (fun _: 32 <= 32 => @Scalars.scalar32_of_bytes)))); [exact (proj1 (proj2 x)) | exact (proj1 x) | exact (proj2 (proj2 x))]); shelve_unifiable.\n    2: reflexivity. (* already in goal 1, but should only be there and not a second subgoal *)\n    on_left (idtac; seprewrite @array1_iff_eq_of_list_word_at; cycle 1); cycle 1.\n\n    (* frame calculation again, unclear what to subst before split_bytes_base_addr *)\n    (* maybe make a rewrite that follows lets *)\n\n\n    {\n    eassert (Z.of_nat (length ((xs0 ++ ys0) ++ ys)) = _). {\n      rewrite ?app_length.\n      rewrite ?Nat2Z.inj_add.\n      repeat match goal with\n             | H: Z.of_nat (length ?x) = ?y |- context[length ?x] => rewrite H\n             end.\n      simplify_ZcstExpr.\n      reflexivity.\n    }\n\n    repeat match goal with x := _ : word.rep |- _ => subst x end.\n    set_evars.\n    replace (length l1 = 4%nat) with (Z.of_nat (length l1) = 4) by case proof_admitted.\n\n    match goal with |- context[?P m] =>\n    match P with context[?e$@?a] =>\n    match goal with | |- context[Z.of_nat (length e) = ?n] =>\n    match goal with H : ?S m |- _ =>\n    match S with context[?bs $@ ?a0] =>\n    let a_r := constr:(word.add a (word.of_Z n)) in\n    split_bytes_base_addr bs a0 a_r end;\n    match type of H with context[?bs $@ ?a0] =>\n    split_bytes_base_addr bs a0 a\nend end\n    end end end.\n\n    on_left ecancel_assumption.\n    split; [trivial|].\n    split; [reflexivity|].\n\n    repeat (straightline || apply WeakestPreconditionProperties.dexpr_expr).\n\n    (* last line *)\n\n    subst P.\n    all: case proof_admitted. }\n\n    Unshelve.\n    all : case proof_admitted.\n\n  Time Qed.\n\nEnd WithParameters.\n\n(* think of mempcpy/memmove within a packet rather than load and store, which are just \"special cases\" of memmove\n\noperations on bytes\n\nextend to other access_size?\n\n *)\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/FlatConstMem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.28657340276781285}}
{"text": "Require Import FunctionApp.\n\nLocal Open Scope type_scope.\n\n(** We apply AC_∞, the type-theoretic axiom of choice, so that\n          we don't need to do higher order unification later. *)\nLemma emptiesStackStep' input world pf\n      (H : forall i : input,\n             { p' : stackProcess input world\n             & emptiesStack (stackTransition i pf) p' *\n               emptiesStackForever p' })\n: @emptiesStackForever input world (Step pf).\nProof.\n  econstructor.\n  intro i.\n  exists (projT1 (H i)).\n  split; apply (projT2 (H _)).\nDefined.\n\nDefinition stackProcess_eta input world (p : stackProcess input world)\n: p = match p with\n        | Step f => Step f\n      end.\nProof.\n  destruct p; reflexivity.\nDefined.\n\nDefinition process_eta input world (p : process input world)\n: p = match p with\n        | Step f => Step f\n      end.\nProof.\n  destruct p; reflexivity.\nDefined.\n\nLemma emptiesStackDone' input world p q (H : p = q) : @emptiesStack input world (stackDone, p) q.\nProof.\n  subst.\n  constructor.\nDefined.\n\nLemma emptiesStackPush_sigT {input world} (m : input) (sw : stackWorld input world)\n      (pf : stackStep) P\n: { p2 : stackProcess input world & emptiesStack (stackTransition m pf) p2 * { p3 : _ & emptiesStack (sw, p2) p3 * P p3 } }\n  -> { p3 : _ & emptiesStack (stackPush m sw, Step pf) p3 * P p3 }.\nProof.\n  intro H.\n  eexists.\n  split; [ eapply emptiesStackPush | ];\n  first [ apply (fst (projT2 H))\n        | apply (fst (projT2 (snd (projT2 H))))\n        | apply (snd (projT2 (snd (projT2 H)))) ].\nDefined.\n\nLemma emptiesStackLift_sigT {input world} (a : action world) (sw : stackWorld input world)\n      (p : stackProcess input world) P\n: { p2 : _ & emptiesStack (sw, p) p2 * P p2 }\n  -> { p2 : _ & emptiesStack (stackLift a sw, p) p2 * P p2 }.\nProof.\n  intro H.\n  eexists.\n  split; [ eapply emptiesStackLift | ];\n  first [ apply (fst (projT2 H))\n        | apply (snd (projT2 H)) ].\nDefined.\n\nLemma emptiesStackDone_sigT {input world} p (P : stackProcess input world -> Type)\n: P p -> { p' : _ & emptiesStack (stackDone, p) p' * P p' }.\nProof.\n  intro H.\n  eexists.\n  split; [ eapply emptiesStackDone | ]; eassumption.\nDefined.\n\nLemma emptiesStackPush_ex {input world} (m : input) (sw : stackWorld input world)\n      (pf : stackStep) P\n: (exists p2 : stackProcess input world,\n     emptiesStack (stackTransition m pf) p2\n     /\\ exists p3 : _, emptiesStack (sw, p2) p3 /\\ P p3)\n  -> exists p3 : _, emptiesStack (stackPush m sw, Step pf) p3 /\\ P p3.\nProof.\n  intros [? [? [? [? ?]]]].\n  eexists.\n  split; [ eapply emptiesStackPush | ];\n  eassumption.\nDefined.\n\nLemma emptiesStackLift_ex {input world} (a : action world) (sw : stackWorld input world)\n      (p : stackProcess input world) P\n: (exists p2 : _, emptiesStack (sw, p) p2 /\\ P p2)\n  -> exists p2 : _, emptiesStack (stackLift a sw, p) p2 /\\ P p2.\nProof.\n  intros [? [? ?]].\n  eexists.\n  split; [ eapply emptiesStackLift | ];\n  eassumption.\nDefined.\n\nLemma emptiesStackDone_ex {input world} p (P : stackProcess input world -> Prop)\n: P p -> exists p' : _, emptiesStack (stackDone, p) p' /\\ P p'.\nProof.\n  intro H.\n  eexists.\n  split; [ eapply emptiesStackDone | ]; eassumption.\nDefined.\n", "meta": {"author": "JasonGross", "repo": "apps", "sha": "906b9ca6f3f53e3a37a9a487a9289959f5167ba2", "save_path": "github-repos/coq/JasonGross-apps", "path": "github-repos/coq/JasonGross-apps/apps-906b9ca6f3f53e3a37a9a487a9289959f5167ba2/FunctionAppLemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.28649189443153}}
{"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(*                          PriorityDecode_Proof.v                          *)\n(****************************************************************************)\n\n\nRequire Export PickSuccessfulInput.\nRequire Export Arbitration.\nRequire Export Moore_Mealy.\n\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nSection PriorityDecode_Correctness.\n\n  Let Input_type :=\n    (d_list bool 4 * (d_list bool 4 * d_list (d_list bool 2) 4))%type.\n\n  Let Output_type := d_list (d_list bool 4) 4.\n\n  Inductive label_p : Set :=\n    | START_p : label_p\n    | DECODE_p : label_p.\n\n  Definition STATE_p : Set := (label_p * d_list (d_list bool 4) 4)%type.\n\n\n(** Automaton describing the transitions from a state to another **)\n\n  Definition Convert_and_filter (i : Input_type) : Output_type :=\n    let (act, p) := i in\n    let (pri, route) := p in\n    d_map (PriorityRequests act pri) (merge (d_map Convert_list2 route)).\n\n\n  Definition Trans_PriorityDecode (i : Input_type) \n    (s : STATE_p) : STATE_p := (DECODE_p, Convert_and_filter i).\n\n\n\n(** Each state corresponds to a result **)\n\n  Definition Out_PriorityDecode (s : STATE_p) : Output_type :=\n    let (s', old) := s in old.\n\n\n(** States stream **)\n\n  Definition States_PRIORITY_DECODE := States_Mealy Trans_PriorityDecode.\n\n\n(** Intented behaviour **)\n\n  Definition Behaviour_PRIORITY_DECODE :=\n    Moore Trans_PriorityDecode Out_PriorityDecode.\n\n\n(** Transformation of Behaviour_PRIORITY_DECODE to a Mealy automaton **)\n\n  Definition Out_PriorityDecode_Mealy :=\n    Out_Mealy (Input_type:=Input_type) Out_PriorityDecode.\n\n  Lemma equiv_out_PriorityDecode :\n   forall (i : Input_type) (s : STATE_p),\n   Out_PriorityDecode s = Out_PriorityDecode_Mealy i s.\n  Proof.\n  auto.\n  Qed.\n\n\n  Lemma Equiv_PriorityDecode_Moore_Mealy :\n   forall (s : STATE_p) (i : Stream Input_type),\n   EqS (Behaviour_PRIORITY_DECODE i s)\n     (Mealy Trans_PriorityDecode Out_PriorityDecode_Mealy i s).\n  Proof.\n  intros s i.\n  unfold Behaviour_PRIORITY_DECODE in |- *;\n   unfold Out_PriorityDecode_Mealy in |- *; apply Equiv_Moore_Mealy.\n  Qed.\n\n\n  Definition States_Structure_PRIORITY_DECODE :=\n    States_Mealy Trans_priority_decode.\n\n\n (** No invariant property *)\n\n  Let Reg_type := d_list (d_list bool 4) 4. (* Type of the registers of PRIORITY_DECODE *)\n\n\n  Let Cst_True (i : Input_type) (s : STATE_p) (reg : Reg_type) := True.\n\n\n  Definition R_Priority_Decode (s : STATE_p) (reg : Reg_type) :=\n    reg = Out_PriorityDecode s.\n\n\n (* Cst_True is an invariant *)\n\n  Lemma Cst_True_inv_pdecode :\n   forall (i : Stream Input_type) (s : STATE_p) (reg : Reg_type),\n   Inv Cst_True i (States_PRIORITY_DECODE i s)\n     (States_Structure_PRIORITY_DECODE i reg).\n\n  Proof.\n  cofix Cst_True_inv_pdecode.\n  intros i s reg.\n  apply Inv_Ok.\n  unfold Cst_True in |- *; auto.\n  Qed.\n\n\n(** Because the unit is essentially combinational, we assume its correctness **)\n\n  Axiom\n    Invariant_relation_p :\n      Inv_under_P Trans_PriorityDecode Trans_priority_decode Cst_True\n        R_Priority_Decode.\n\n\n\n  Lemma Output_relation_p :\n   Output_rel Out_PriorityDecode_Mealy Out_priority_decode R_Priority_Decode.\n\n  Proof.\n  unfold Output_rel in |- *; auto.\n  Qed.\n\n\n(** Correctness lemma  **)\n\n  Lemma Correct_PRIORITY_DECODE :\n   forall (i : Stream Input_type) (reg : Reg_type) (s : STATE_p),\n   R_Priority_Decode s reg ->\n   EqS (Behaviour_PRIORITY_DECODE i s) (Structure_PRIORITY_DECODE i reg).\n\n  Proof.\n  intros i reg s HR.\n  unfold Structure_PRIORITY_DECODE in |- *;\n   unfold Behaviour_PRIORITY_DECODE in |- *.\n  apply\n   (Equiv_2_Mealy Invariant_relation_p Output_relation_p\n      (Cst_True_inv_pdecode i s reg) HR).\n\n  Qed.\n\n\nEnd PriorityDecode_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/PriorityDecode_Proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2864918872167365}}
{"text": "Require Import Coq.omega.Omega.\nRequire Import Crypto.Util.FixCoqMistakes.\nRequire Import Crypto.Reflection.Syntax.\nRequire Import Crypto.Reflection.Wf.\nRequire Import Crypto.Reflection.Named.Syntax.\nRequire Import Crypto.Reflection.Named.ContextDefinitions.\nRequire Import Crypto.Reflection.Named.NameUtil.\nRequire Import Crypto.Reflection.Named.NameUtilProperties.\nRequire Import Crypto.Reflection.Named.ContextProperties.\nRequire Import Crypto.Reflection.Named.ContextProperties.Tactics.\nRequire Import Crypto.Util.Decidable.\nRequire Import Crypto.Util.ListUtil.\nRequire Import Crypto.Util.Prod.\nRequire Import Crypto.Util.Tactics.SplitInContext.\nRequire Import Crypto.Util.Tactics.DestructHead.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nRequire Import Crypto.Util.Tactics.SpecializeBy.\n\nSection with_context.\n  Context {base_type_code Name var} (Context : @Context base_type_code Name var)\n          (base_type_code_dec : DecidableRel (@eq base_type_code))\n          (Name_dec : DecidableRel (@eq Name))\n          (ContextOk : ContextOk Context).\n\n  Local Notation find_Name := (@find_Name base_type_code Name Name_dec).\n  Local Notation find_Name_and_val := (@find_Name_and_val base_type_code Name base_type_code_dec Name_dec).\n\n  Hint Rewrite (@find_Name_and_val_default_to_None _ _ base_type_code_dec Name_dec) using congruence : ctx_db.\n  Hint Rewrite (@find_Name_and_val_different _ _ base_type_code_dec Name_dec) using assumption : ctx_db.\n  Hint Rewrite (@find_Name_and_val_wrong_type _ _ base_type_code_dec Name_dec) using congruence : ctx_db.\n  Hint Rewrite (@snd_split_onames_skipn base_type_code Name) : ctx_db.\n\n  Local Ltac misc_oname_t_step :=\n    match goal with\n    | [ H : oname_list_unique (List.skipn _ _) -> _ |- _ ]\n      => specialize (fun pf => H (@oname_list_unique_skipn _ _ _ pf))\n    | [ H : ((_, _) = (_, _))%core -> _ |- _ ]\n      => specialize (fun a b => H (f_equal2 (@pair _ _) a b))\n    | [ H : ?x = (_,_)%core -> _ |- _ ]\n      => rewrite (surjective_pairing x) in H;\n           specialize (fun a b => H (f_equal2 (@pair _ _) a b))\n    end.\n\n  Lemma split_onames_find_Name\n        {n T N ls ls'}\n        (H : split_onames _ ls = (Some N, ls')%core)\n    : (exists t, @find_Name n T N = Some t)\n      <-> List.In (Some n) (List.firstn (CountLets.count_pairs T) ls).\n  Proof.\n    revert dependent ls; intro ls; revert ls ls'; induction T; intros;\n      [ | | specialize (IHT1 (fst N) ls (snd (split_onames T1 ls)));\n            specialize (IHT2 (snd N) (snd (split_onames T1 ls)) (snd (split_onames (T1 * T2) ls))) ];\n      repeat first [ misc_oname_t_step\n                   | t_step\n                   | progress split_iff\n                   | progress specialize_by (eexists; eauto)\n                   | solve [ eauto using In_skipn, In_firstn ]\n                   | match goal with\n                     | [ H : List.In ?x (List.firstn ?n ?ls) |- List.In ?x (List.firstn (?n + ?m) ?ls) ]\n                       => apply (In_firstn n); rewrite firstn_firstn by omega\n                     | [ H : _ |- _ ] => first [ rewrite firstn_skipn_add in H\n                                               | rewrite firstn_firstn in H by omega ]\n                     | [ H : List.In ?x' (List.firstn (?n + ?m) ?ls) |- List.In ?x' (List.firstn ?m (List.skipn ?n ?ls)) ]\n                       => apply (In_firstn_skipn_split n) in H\n                     end ].\n  Qed.\n\n  Lemma split_onames_find_Name_Some_unique_iff\n        {n T N ls ls'}\n        (Hls : oname_list_unique ls)\n        (H : split_onames _ ls = (Some N, ls')%core)\n    : (exists t, @find_Name n T N = Some t)\n      <-> List.In (Some n) ls /\\ ~List.In (Some n) ls'.\n  Proof.\n    rewrite (split_onames_find_Name (ls':=ls') (ls:=ls)) by assumption.\n    rewrite (surjective_pairing (split_onames _ _)) in H.\n    rewrite fst_split_onames_firstn, snd_split_onames_skipn in H.\n    inversion_prod; subst.\n    split; [ split | intros [? ?] ]; eauto using In_firstn, oname_list_unique_specialize.\n    eapply In_firstn_skipn_split in H; destruct_head' or; eauto; exfalso; eauto.\n  Qed.\n\n  Lemma split_onames_find_Name_Some_unique\n        {t n T N ls ls'}\n        (Hls : oname_list_unique ls)\n        (H : split_onames _ ls = (Some N, ls')%core)\n        (Hfind : @find_Name n T N = Some t)\n    : List.In (Some n) ls /\\ ~List.In (Some n) ls'.\n  Proof.\n    eapply split_onames_find_Name_Some_unique_iff; eauto.\n  Qed.\n\n  Lemma flatten_binding_list_find_Name_and_val_unique\n        {var' t n T N V v ls ls'}\n        (Hls : oname_list_unique ls)\n        (H : split_onames _ ls = (Some N, ls')%core)\n    : @find_Name_and_val var' t n T N V None = Some v\n      <-> List.In (existT (fun t => (Name * var' t)%type) t (n, v)) (Wf.flatten_binding_list N V).\n  Proof.\n    revert dependent ls; intro ls; revert ls ls'; induction T; intros;\n      [ | | specialize (IHT1 (fst N) (fst V) ls (snd (split_onames T1 ls)));\n            specialize (IHT2 (snd N) (snd V) (snd (split_onames T1 ls)) (snd (split_onames (T1 * T2) ls))) ];\n      repeat first [ find_Name_and_val_default_to_None_step\n                   | progress simpl in *\n                   | rewrite List.in_app_iff\n                   | misc_oname_t_step\n                   | t_step\n                   | progress split_iff\n                   | lazymatch goal with\n                     | [ H : find_Name ?n ?x = Some ?t, H' : find_Name_and_val ?t' ?n ?X ?V None = Some ?v |- _ ]\n                       => apply find_Name_and_val_find_Name_Some in H'\n                     | [ H : find_Name ?n ?x = Some ?t, H' : find_Name ?n ?x' = Some ?t' |- _ ]\n                       => let apply_in_tac H :=\n                              (eapply split_onames_find_Name_Some_unique in H;\n                               [ | | apply path_prod_uncurried; split; [ eassumption | simpl; reflexivity ] ];\n                               [ | solve [ eauto using oname_list_unique_firstn, oname_list_unique_skipn ] ]) in\n                          first [ constr_eq x x'; fail 1\n                                | apply_in_tac H; apply_in_tac H' ]\n                     end ].\n  Qed.\n\n  Lemma fst_split_mnames__flatten_binding_list__find_Name\n        (MName : Type) (force : MName -> option Name)\n        {var' t n T N V v} {ls : list MName}\n        (Hs : fst (split_mnames force T ls) = Some N)\n        (HN : List.In (existT _ t (n, v)%core) (Wf.flatten_binding_list (var2:=var') N V))\n    : find_Name n N = Some t.\n  Proof.\n    revert dependent ls; induction T;\n      [ | | specialize (IHT1 (fst N) (fst V));\n            specialize (IHT2 (snd N) (snd V)) ];\n      repeat first [ misc_oname_t_step\n                   | t_step\n                   | match goal with\n                     | [ H : _ |- _ ] => first [ rewrite snd_split_mnames_skipn in H\n                                               | rewrite List.in_app_iff in H ]\n                     | [ H : context[fst (split_mnames _ _ ?ls)] |- _ ]\n                       => is_var ls; rewrite (@fst_split_mnames_firstn _ _ _ _ _ ls) in H\n                     end ].\n  Abort.\n\n  Lemma fst_split_mnames__find_Name__flatten_binding_list\n        (MName : Type) (force : MName -> option Name)\n        {var' t n T N V v default} {ls : list MName}\n        (Hs : fst (split_mnames force T ls) = Some N)\n        (Hfind : find_Name n N = Some t)\n        (HN : List.In (existT _ t (n, v)%core) (Wf.flatten_binding_list N V))\n    : @find_Name_and_val var' t n T N V default = Some v.\n  Proof.\n    revert default; revert dependent ls; induction T;\n      [ | | specialize (IHT1 (fst N) (fst V));\n            specialize (IHT2 (snd N) (snd V)) ];\n      repeat first [ find_Name_and_val_default_to_None_step\n                   | rewrite List.in_app_iff in *\n                   | t_step ].\n  Abort.\nEnd with_context.\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/Named/ContextProperties/NameUtil.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2864918872167365}}
{"text": "Unset Strict Universe Declaration.\n(* File reduced by coq-bug-finder from original input, then from 11542 lines to 325 lines, then from 347 lines to 56 lines, then from 58 lines to 15 lines *)\n(* coqc version trunk (September 2014) compiled on Sep 25 2014 2:53:46 with OCaml 4.01.0\n   coqtop version cagnode16:/afs/csail.mit.edu/u/j/jgross/coq-trunk,trunk (bec7e0914f4a7144cd4efa8ffaccc9f72dbdb790) *)\n\nAxiom transport : forall {A : Type} (P : A -> Type) {x y : A} (p : x = y) (u : P x), P y.\nNotation \"p # x\" := (transport _ p x) (right associativity, at level 65, only parsing).\nInductive V : Type@{U'} := | set {A : Type@{U}} (f : A -> V) : V.\nModule NonPrim.\n  Record hProp := hp { hproptype :> Type ; isp : Set}.\n  Goal forall (A B : Type) (H_f : A -> V -> hProp) (H_g : B -> V -> hProp)\n              (C : Type) (h : C -> V) (b : B) (a : A) (c : C),\n         H_f a (h c) -> H_f a (h c) = H_g b (h c) -> H_g b (h c).\n    intros A B H_f H_g C h b a c H3 H'.\n    exact (@transport hProp (fun x => x) _ _ H' H3).\n    Undo.\n    Set Debug Unification.\n    exact (H' # H3).\n  Defined.\nEnd NonPrim.\n\nModule Prim.\n  Set Primitive Projections.\n  Set Universe Polymorphism.\n  Record hProp := hp { hproptype :> Type ; isp : Set}.\n  Goal forall (A B : Type) (H_f : A -> V -> hProp) (H_g : B -> V -> hProp)\n              (C : Type) (h : C -> V) (b : B) (a : A) (c : C),\n         H_f a (h c) -> H_f a (h c) = H_g b (h c) -> H_g b (h c).\n    intros A B H_f H_g C h b a c H3 H'.\n    exact (@transport hProp (fun x => x) _ _ H' H3).\n    Undo.\n    Set Debug Unification.\n    exact (H' # H3).\n    (* Toplevel input, characters 7-14:\nError:\nIn environment\nA : Type\nB : Type\nH_f : A -> V -> hProp\nH_g : B -> V -> hProp\nC : Type\nh : C -> V\nb : B\na : A\nc : C\nH3 : H_f a (h c)\nH' : H_f a (h c) = H_g b (h c)\nUnable to unify \"hproptype (H_f a (h c))\" with \"?T (H_f a (h c))\".\n *)\n  Defined.\nEnd Prim.\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/3666.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.28649188721673646}}
{"text": "(************************************************************************)\n(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)\n(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2011     *)\n(*   \\VV/  **************************************************************)\n(*    //   *      This file is distributed under the terms of the       *)\n(*         *       GNU Lesser General Public License Version 2.1        *)\n(************************************************************************)\n\n(*i $Id: Notations.v 14641 2011-11-06 11:59:10Z herbelin $ i*)\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 95, no associativity).\nReserved Notation \"x /\\ y\" (at level 80, 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 than \"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\nDelimit Scope type_scope with type.\nDelimit Scope core_scope with core.\n\nOpen Scope core_scope.\nOpen Scope type_scope.\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/coq/coq-8.3pl5-foundations/theories/Init/Notations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953506426082, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2864918800019429}}
{"text": "(*\n(C) Copyright 2010, COQTAIL team\n\nProject Info: http://sourceforge.net/projects/coqtail/\n\nThis library is free software; you can redistribute it and/or modify it\nunder the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation; either version 2.1 of the License, or\n(at your option) any later version.\n\nThis library is distributed in the hope that it will be useful, but\nWITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\nor FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\nLicense for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,\nUSA.\n*)\n\nRequire Import Reals.\nRequire Export Rfunction_def.\n\nOpen Scope Rfun_scope.\n\n(** Compatibility of extensional equality *)\n\nLtac extensional_reflexivity H Heq :=\nlet swap H1 H2 :=\n  clear H1;\n  assert (H1 := H2);\n  clear H2\nin\nlet rec refl_aux H :=\nmatch goal with\n| |- forall x, _ =>\n  let x := fresh \"x\" in\n  let nH := fresh in\n  intros x;\n  assert (nH := H x);\n  swap H nH;\n  refl_aux H\n| |- exists x, _ =>\n  let x := fresh \"x\" in\n  destruct H as [x H];\n  exists x;\n  refl_aux H\n| |- ?P /\\ ?Q =>\n  let Hl := fresh \"H\" in\n  let Hr := fresh \"H\" in\n  destruct H as [Hl Hr];\n  split; [refl_aux Hl|refl_aux Hr]\n| |- ?P \\/ ?Q =>\n  let Hl := fresh \"H\" in\n  let Hr := fresh \"H\" in\n  destruct H as [Hl|Hr];\n  [refl_aux Hl|refl_aux Hr]\n| _ =>\n  repeat (rewrite <- Heq); apply H\nend in\ncompute in H |- *; refl_aux H.\n\nSection Rfun_eq.\n\nVariables f g : R -> R.\nHypothesis Heq : f == g.\n\nLemma Rfun_continuity_pt_eq_compat :\n  forall x, continuity_pt f x -> continuity_pt g x.\nProof.\n  intros x Hct eps H.\n  specialize (Hct eps H).\n  destruct Hct as (alp & pos & HH).\n  exists alp. split; auto.\n  intros x0 H0.\n  specialize (HH x0 H0).\n  eauto.\n  repeat rewrite <-Heq.\n  auto.\nQed.\n\nLemma Rfun_continuity_eq_compat :\n  continuity f -> continuity g.\nProof.\n  intros H i a p.\n  destruct (H i a p).\n  exists x. intuition.\n  repeat rewrite <-Heq.\n  eauto.\nQed.\n\nEnd Rfun_eq.", "meta": {"author": "coqtail", "repo": "coqtail", "sha": "96799cc6901b9cdb1c5f47add0f9cd6584fdd389", "save_path": "github-repos/coq/coqtail-coqtail", "path": "github-repos/coq/coqtail-coqtail/coqtail-96799cc6901b9cdb1c5f47add0f9cd6584fdd389/src/Reals/Ranalysis/Rfunction_facts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.28633032831866895}}
{"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(* A set, with the axiom of decidability of the equality,               *)\n(* is enumerable if it exists a list of its elements.                   *)\n\n(* the following notions are defined :                                  *)\n(*      - U_enumerable : set with a list of its elements                *)\n(*      - U_canon : list with unique occurrence of its elements         *)\n(*              constructors : U_canon_nil, U_canon_cons.               *)\n(*      - U_sum : sommation of the images of a list.                    *)\n\nRequire Export Sets.\nRequire Export List.\n\nSection ENUMERATION.\n\nVariable U : Set.\n\nHypothesis U_separable : forall x y : U, {x = y} + {x <> y}.\n\nDefinition U_list := list U.\n\nDefinition U_enumerable (E : U_set U) :=\n  {ul : U_list | forall x : U, E x -> In x ul}.\n\nInductive U_canon : U_list -> Prop :=\n  | U_canon_nil : U_canon nil\n  | U_canon_cons :\n      forall (x : U) (ul : U_list),\n      U_canon ul -> ~ In x ul -> U_canon (x :: ul).\n\nLemma U_in_dec : forall (x : U) (ul : U_list), {In x ul} + {~ In x ul}.\nProof.\n        simple induction ul; intros.\n        right; red in |- *; intros; inversion H.\n\n        case (U_separable x a); intros.\n        left; rewrite e; simpl in |- *; auto.\n\n        case H; intros.\n        left; simpl in |- *; auto.\n\n        right; red in |- *; intros; inversion H0.\n        elim n; auto.\n\n        elim n0; auto.\nQed.\n\nVariable f : U -> nat.\n\nFixpoint U_sum (ul : U_list) : nat :=\n  match ul with\n  | nil => 0\n  | x :: ul' => f x + U_sum ul'\n  end.\n\nLemma U_enumerable_sum : forall E : U_set U, U_enumerable E -> nat.\nProof.\n        intros; elim H; intros.\n        apply (U_sum x).\nDefined.\n\nEnd ENUMERATION.\n", "meta": {"author": "Zdancewic", "repo": "linearity", "sha": "b2662939b2e8fb8fbe34f7ec0d3c69ef1bdff916", "save_path": "github-repos/coq/Zdancewic-linearity", "path": "github-repos/coq/Zdancewic-linearity/linearity-b2662939b2e8fb8fbe34f7ec0d3c69ef1bdff916/simpleconcur/GraphBasics/Enumerated.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.2863303203843716}}
{"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(*                                                                          *)\n(*  Proof of the three gap theorem.                                         *)\n(*                                                                          *)\n(*  Micaela Mayero (INRIA-Rocquencourt)                                     *)\n(*  September 1998                                                          *)\n(*                                                                          *)\n(****************************************************************************)\n(****************************************************************************)\n(*                               preuve2.v                                  *)\n(****************************************************************************)\n\n(*********************************************************)\n(*                 Intermediate proof 2                  *)\n(*                                                       *)\n(*********************************************************)\n\nRequire Export preuve1.\n(*********************************************************)\n\nSection Three.\nHypothesis alpha_irr : forall n p : Z, (alpha * IZR p)%R <> IZR n.\nHypothesis prop_alpha : (0 < alpha)%R /\\ (alpha < 1)%R.\nHypothesis prop_N : forall N : nat, N >= 2.\n\n(**********)\nLemma three_gap1 :\n forall N n : nat, 0 < n -> n < N - first N -> after N n = n + first N.\nintros; generalize (inter31a alpha_irr prop_alpha prop_N N n); intros;\n generalize (eq_after_M_N1 alpha_irr prop_alpha prop_N N n H H0); \n intro; rewrite <- H2; cut (n < last (M N)).\nintro;\n rewrite\n  (first_eq_M_N alpha_irr prop_alpha prop_N N (M N)\n     (refl_equal (first N + last N))); apply (H1 H H3).\ngeneralize\n (le_N_M alpha_irr prop_alpha prop_N N (M N) (refl_equal (first N + last N)));\n intro; generalize (le_lt_or_eq N (first N + last N) H3); \n intro; elim H4; intro.\ncut (N - first N < last (M N)).\nintro; apply (lt_trans n (N - first N) (last (M N)) H0 H6).\nrewrite <-\n (last_eq_M_N alpha_irr prop_alpha prop_N N (M N)\n    (refl_equal (first N + last N)));\n apply (lt_plus_minus N (first N) (last N) (first_N N (prop_N N)) H5).\nrewrite <-\n (last_eq_M_N alpha_irr prop_alpha prop_N N (M N)\n    (refl_equal (first N + last N))); cut (M N = first N + last N).\nintro; rewrite <- H6 in H5; rewrite H5 in H0;\n rewrite <-\n  (first_eq_M_N alpha_irr prop_alpha prop_N N (M N)\n     (refl_equal (first N + last N))) in H0;\n rewrite (plus_minus (M N) (first N) (last N) H6); \n auto with arith real.\nauto with arith real.\nQed.\n\n(**********)\nLemma three_gap2 :\n forall N n : nat,\n N - first N <= n -> n < last N -> after N n = n + first N - last N.\nintros; apply sym_equal;\n apply (tech_after alpha_irr N n (n + first N - last N)).\ngeneralize (first_N N (prop_N N)); intro;\n generalize (lt_minus2 (first N) N H1); intro;\n apply (lt_le_trans 0 (N - first N) n H2 H).\ngeneralize (last_N N (prop_N N)); intro; apply (lt_trans n (last N) N H0 H1).\nauto with arith real.\ngeneralize (plus_lt_compat_r n (last N) (first N) H0); intro;\n generalize (lt_reg_minus (n + first N) (last N + first N) (last N) H1);\n intro; rewrite (minus_plus (last N) (first N)) in H2;\n cut (last N <= n + first N).\nintro;\n apply\n  (lt_trans (n + first N - last N) (first N) N (H2 H3) (first_N N (prop_N N))).\nclear H1 H2; generalize (le_minus_plus N (first N) n H); intro;\n apply (le_trans (last N) N (n + first N) (last_N01 N) H1).\napply (tech1 alpha_irr prop_alpha prop_N N n H H0).\ngeneralize (tech_suc_M alpha_irr prop_alpha prop_N N n H H0);\n auto with arith real.\nQed.\n\n(**********)\nLemma three_gap3 :\n forall N n : nat, last N <= n -> n < N -> after N n = n - last N.\nintros; generalize (inter31b alpha_irr prop_alpha prop_N N n); intros;\n generalize (eq_after_M_N2 alpha_irr prop_alpha prop_N N n H H0); \n intro; rewrite <- H2; cut (n < M N).\nintro;\n rewrite\n  (last_eq_M_N alpha_irr prop_alpha prop_N N (M N)\n     (refl_equal (first N + last N)));\n rewrite\n  (last_eq_M_N alpha_irr prop_alpha prop_N N (M N)\n     (refl_equal (first N + last N))) in H; apply (H1 H H3).\ngeneralize\n (le_N_M alpha_irr prop_alpha prop_N N (M N) (refl_equal (first N + last N)));\n intro; unfold M in |- *; apply (lt_le_trans n N (first N + last N) H0 H3).\nQed.\n\nEnd Three.", "meta": {"author": "coq-contribs", "repo": "three-gap", "sha": "b176a7b3165aecd171926271a8d90888f16dc297", "save_path": "github-repos/coq/coq-contribs-three-gap", "path": "github-repos/coq/coq-contribs-three-gap/three-gap-b176a7b3165aecd171926271a8d90888f16dc297/preuve2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.28631293892047366}}
{"text": "Require Import Classical.\n(* Used in various places:\n    - existence of a derivation in the axiomatic system for a sequent\n      (should be decidable as Bi-Int is, but this would require extra work)\n    - some set-theoretic arguments (maybe they can be constructivised *)\n\nRequire Import List.\nExport ListNotations.\nRequire Import PeanoNat.\nRequire Import Lia.\n\nRequire Import Ensembles.\nRequire Import BiInt_GHC.\nRequire Import BiInt_logics.\nRequire Import BiInt_extens_interactions.\nRequire Import wBIH_meta_interactions.\nRequire Import sBIH_meta_interactions.\nRequire Import BiInt_Kripke_sem.\nRequire Import BiInt_Lindenbaum_lem.\n\nDefinition CompNotDer (s: prod (@Ensemble (BPropF V)) (@Ensemble (BPropF V))) : Prop :=\n  (complete (fst s, snd s) /\\ (wpair_derrec (fst s, snd s) -> False)).\n\nLemma clos_deriv : forall (Γ Δ : @Ensemble (BPropF V)), CompNotDer (Γ, Δ) ->\n                                (forall A, wBIH_rules (Γ, A) -> (In _ Γ A)).\nProof.\nintros. destruct H. simpl in H. simpl in H1. pose (H A). destruct o.\nauto. simpl in H2. exfalso. apply H1. exists [A]. repeat split.\napply NoDup_cons ; auto ; apply NoDup_nil. intros. inversion H3. subst.\nauto. inversion H4. simpl. apply MP with (ps:=[(Γ, Imp A (Or A (Bot V)));(Γ, A)]).\n2: apply MPRule_I. intros. inversion H3. subst. apply Ax. apply AxRule_I.\napply RA2_I. exists A. exists (Bot V). auto. inversion H4. subst. 2: inversion H5.\nassumption.\nQed.\n\nLemma primeness : forall (Γ Δ : @Ensemble (BPropF V)), CompNotDer (Γ, Δ) ->\n                                (forall A B, (In _ Γ (Or A B))  -> ((In _ Γ A) \\/ (In _ Γ B))).\nProof.\nintros. destruct H. simpl in H. simpl in H1. pose (H A). pose (H B).\ndestruct o ; destruct o0 ; auto. simpl in H2. simpl in H3. exfalso. apply H1.\ndestruct (eq_dec_form A B). subst. exists [B].\nrepeat split. apply NoDup_cons ; auto ; apply NoDup_nil. intros. inversion H4.\nsubst. auto. inversion H5. simpl. apply MP with (ps:=[(Γ, Imp B (Or B (Bot V)));(Γ, B)]).\n2: apply MPRule_I. intros. inversion H4. subst. apply Ax. apply AxRule_I.\napply RA2_I. exists B. exists (Bot V). auto. inversion H5. 2: inversion H6. subst.\napply MP with (ps:=[(Γ,(Or B B) → B);(Γ,(Or B B))]). 2: apply MPRule_I.\nintros. inversion H6. subst.\napply MP with (ps:=[(Γ,(B → B) → (Or B B) → B);(Γ,(B → B))]). 2: apply MPRule_I.\nintros. inversion H7. subst.\napply MP with (ps:=[(Γ,(B → B) → (B → B) → (Or B B) → B);(Γ,(B → B))]). 2: apply MPRule_I.\nintros. inversion H8. subst. apply Ax. apply AxRule_I. apply RA4_I.\nexists B. exists B. exists B. auto. inversion H9. 2: inversion H10.\nsubst. apply wimp_Id_gen. inversion H8. 2: inversion H9. subst. apply wimp_Id_gen.\ninversion H7. subst. 2: inversion H8. apply Id. apply IdRule_I. auto.\nexists (A :: [B]). repeat split. apply NoDup_cons. intro. inversion H4. auto.\ninversion H5. apply NoDup_cons ; auto ; apply NoDup_nil. intros.\nsimpl. inversion H4. subst. auto. inversion H5. subst. auto. inversion H6.\nsimpl. apply MP with (ps:=[(Γ, Imp (Or A B) (Or A (Or B (Bot V))));(Γ, Or A B)]).\n2: apply MPRule_I. intros. inversion H4. subst.\napply MP with (ps:=[(Γ,(B → Or A (Or B (Bot V))) → (Or A B → Or A (Or B (Bot V))));\n(Γ, (B → Or A (Or B (Bot V))))]). 2: apply MPRule_I. intros. inversion H5. subst.\napply MP with (ps:=[(Γ,(A → Or A (Or B (Bot V))) → (B → Or A (Or B (Bot V))) → (Or A B → Or A (Or B (Bot V))));\n(Γ, (A → Or A (Or B (Bot V))))]). 2: apply MPRule_I. intros. inversion H6. subst.\napply Ax. apply AxRule_I. apply RA4_I. exists A. exists B. exists (Or A (Or B (Bot V))).\nauto. inversion H7. subst. 2: inversion H8. apply Ax. apply AxRule_I.\napply RA2_I. exists A. exists (Or B (Bot V)). auto. inversion H6. 2: inversion H7.\nsubst.\napply MP with (ps:=[(Γ, ((Or B (Bot V)) → Or A (Or B (Bot V))) → (B → Or A (Or B (Bot V))));\n(Γ, ((Or B (Bot V)) → Or A (Or B (Bot V))))]). 2: apply MPRule_I. intros.\ninversion H7. subst.\napply MP with (ps:=[(Γ, (B → (Or B (Bot V))) → ((Or B (Bot V)) → Or A (Or B (Bot V))) → (B → Or A (Or B (Bot V))));\n(Γ, (B → (Or B (Bot V))))]). 2: apply MPRule_I. intros.\ninversion H8. subst. apply Ax. apply AxRule_I. apply RA1_I. exists B.\nexists (Or B (Bot V)). exists (Or A (Or B (Bot V))). auto. inversion H9. subst.\n2: inversion H10. apply Ax. apply AxRule_I. apply RA2_I. exists B. exists (Bot V). auto.\ninversion H8. 2: inversion H9. subst. apply Ax. apply AxRule_I. apply RA3_I.\nexists A. exists (Or B (Bot V)). auto. inversion H5. subst. 2: inversion H6.\napply Id. apply IdRule_I. auto.\nQed.\n\nLemma cp_Bot_R : forall (Γ Δ : @Ensemble (BPropF V)), CompNotDer (Γ, Δ) -> (In _ Δ (Bot V)).\nProof.\nintros. destruct H. simpl in H. simpl in H0. pose (H (Bot V)). destruct o ; auto.\nsimpl in H1. exfalso. apply H0. exists []. repeat split. apply NoDup_nil.\nintros. inversion H2. simpl. apply Id. apply IdRule_I. auto.\nQed.\n\nDefinition Canon_worlds : Type :=\n  {x : prod (@Ensemble (BPropF V)) (@Ensemble (BPropF V)) | CompNotDer x}.\n\nDefinition Canon_rel (P0 P1 : Canon_worlds) : Prop :=\n  Included _ (fst (proj1_sig P0)) (fst (proj1_sig P1)).\n\nDefinition Canon_val (P : Canon_worlds) (q : V) : Prop :=\n  In _ (fst (proj1_sig P)) (# q).\n\nLemma C_R_refl u : Canon_rel u u.\nProof.\nunfold Canon_rel. intro. auto.\nQed.\n\nLemma C_R_trans u v w: Canon_rel u v -> Canon_rel v w -> Canon_rel u w.\nProof.\nintros. unfold Canon_rel.\nintro. intros. unfold Canon_rel in H0. unfold Canon_rel in H.\napply H0. apply H. auto.\nQed.\n\nLemma C_val_persist : forall u v, Canon_rel u v -> forall p, Canon_val u p -> Canon_val v p.\nProof.\nintros.\nunfold Canon_val in H0. unfold Canon_rel in H.\nunfold Canon_val. apply H. auto.\nQed.\n\nInstance CM : model :=\n      {|\n        nodes := Canon_worlds ;\n        reachable := Canon_rel ;\n        val := Canon_val ;\n\n        reach_refl := C_R_refl ;\n        reach_tran := C_R_trans ;\n\n        persist := C_val_persist;\n      |}.\n\nLemma truth_lemma : forall A (cp : Canon_worlds),\n  (wforces CM cp A) <-> (In _ (fst (proj1_sig cp)) A).\nProof.\ninduction A ; intro ; split ; intros ; destruct cp ; simpl ; try simpl in H ; auto.\n(* Bot V *)\n- inversion H.\n- destruct x. simpl in H. unfold CompNotDer in c. destruct c. simpl in H1. apply H1.\n  unfold wpair_derrec. simpl. exists []. repeat split. apply NoDup_nil. intros.\n  inversion H2. simpl. apply Id. apply IdRule_I. auto.\n(* Top V *)\n- pose (classic (In (BPropF V) (fst x) (Top V))). destruct o. auto.\n  exfalso. destruct x. simpl in H0. simpl in c. unfold CompNotDer in c.\n  clear H. destruct c. simpl in H. simpl in H1. apply H1. unfold wpair_derrec.\n  exists [Top V]. repeat split. apply NoDup_cons. auto. apply NoDup_nil.\n  intros. inversion H2. subst. simpl. unfold complete in H. simpl in H. clear H2.\n  pose (H (Top V)). destruct o. exfalso. apply H0. auto. auto. inversion H3.\n  simpl. apply MP with (ps:=[(e, Imp (Top V) (Or (Top V) (Bot V))); (e, (Top V))]).\n  intros. inversion H2. subst. apply Ax. apply AxRule_I. apply RA2_I.\n  exists (Top V). exists (Bot V). auto. inversion H3. subst.\n  apply MP with (ps:=[(e, Imp (Imp (Top V) (Top V)) (Top V)); (e, Imp (Top V) (Top V))]).\n  intros. inversion H4. subst. apply Ax. apply AxRule_I. apply RA15_I.\n  exists (Top V → Top V). auto. inversion H5. subst. apply wimp_Id_gen. inversion H6.\n  apply MPRule_I. inversion H4. apply MPRule_I.\n(* And A1 A2 *)\n- destruct H. apply IHA1 in H. simpl in H. apply IHA2 in H0. simpl in H0.\n  apply clos_deriv with (Δ:=snd x). auto.\n  apply MP with (ps:=[(fst x, A1 → (And A1 A2));(fst x, A1)]).\n  2: apply MPRule_I. intros. inversion H1. subst.\n  apply MP with (ps:=[(fst x, (A1 → A2) → (A1 → (And A1 A2)));(fst x, (A1 → A2))]).\n  2: apply MPRule_I. intros. inversion H2. subst.\n  apply MP with (ps:=[(fst x, (A1 → A1) → (A1 → A2) → (A1 → (And A1 A2)));(fst x, (A1 → A1))]).\n  2: apply MPRule_I. intros. inversion H3. subst. apply Ax. apply AxRule_I.\n  apply RA7_I. exists A1. exists A1. exists A2. auto. inversion H4.\n  subst. 2: inversion H5. apply wimp_Id_gen. inversion H3. subst. 2: inversion H4.\n  apply MP with (ps:=[(fst x, A2 → (A1 → A2));(fst x, A2)]).\n  2: apply MPRule_I. intros. inversion H4. subst. apply wThm_irrel.\n  inversion H5. subst. 2: inversion H6. apply Id. apply IdRule_I. assumption.\n  inversion H2. subst. apply Id. apply IdRule_I. assumption. inversion H3.\n- split. apply IHA1. simpl. apply clos_deriv with (Δ:=snd x) ; auto.\n  apply MP with (ps:=[(fst x, Imp (And A1 A2) A1);(fst x, (And A1 A2))]).\n  2: apply MPRule_I. intros. inversion H0. subst. apply Ax. apply AxRule_I.\n  apply RA5_I. exists A1. exists A2. auto. inversion H1. 2: inversion H2.\n  subst. apply Id. apply IdRule_I ; auto.\n  apply IHA2. simpl. apply clos_deriv with (Δ:=snd x) ; auto.\n  apply MP with (ps:=[(fst x, Imp (And A1 A2) A2);(fst x, (And A1 A2))]).\n  2: apply MPRule_I. intros. inversion H0. subst. apply Ax. apply AxRule_I.\n  apply RA6_I. exists A1. exists A2. auto. inversion H1. 2: inversion H2.\n  subst. apply Id. apply IdRule_I ; auto.\n(* Or A1 A2 *)\n- destruct H.\n  apply IHA1 in H. simpl in H. apply clos_deriv with (Δ:=snd x) ; auto.\n  apply MP with (ps:=[(fst x, Imp A1 (Or A1 A2));(fst x, A1)]).\n  2: apply MPRule_I. intros. inversion H0. subst. apply Ax. apply AxRule_I.\n  apply RA2_I. exists A1. exists A2. auto. inversion H1. 2: inversion H2.\n  subst. apply Id. apply IdRule_I ; auto.\n  apply IHA2 in H. simpl in H. apply clos_deriv with (Δ:=snd x) ; auto.\n  apply MP with (ps:=[(fst x, Imp A2 (Or A1 A2));(fst x, A2)]).\n  2: apply MPRule_I. intros. inversion H0. subst. apply Ax. apply AxRule_I.\n  apply RA3_I. exists A1. exists A2. auto. inversion H1. 2: inversion H2.\n  subst. apply Id. apply IdRule_I ; auto.\n- apply primeness with (Δ:=snd x) in H ; auto. destruct H. left. apply IHA1 ; auto.\n  right. apply IHA2 ; auto.\n(* Imp A1 A2 *)\n- destruct x. simpl. destruct (classic (In (BPropF V) e (A1 → A2))).\n  auto. exfalso. unfold CompNotDer in c. simpl in c. destruct c.\n  assert (wpair_derrec (Union _ e (Singleton _ A1), Singleton _ A2) -> False).\n  intro. apply gen_wBIH_Deduction_Theorem in H1. apply H0.\n  { apply clos_deriv with (Δ:=e0). unfold CompNotDer ; auto. destruct H1.\n    destruct H1. destruct H2. destruct x. simpl in H3. simpl in H2.\n    apply MP with (ps:=[(e, Imp (Bot V) (A1 → A2));(e, Bot V)]). 2: apply MPRule_I.\n    intros. inversion H4. subst. apply wEFQ. inversion H5. 2: inversion H6. subst.\n    assumption. inversion H1. subst. pose (H2 b). assert (List.In b (b :: x)). apply in_eq.\n    apply s in H4. inversion H4. subst. destruct x. simpl in H3.\n    apply absorp_Or1 in H3. auto. pose (H2 b). assert (List.In b (A1 → A2 :: b :: x)).\n    apply in_cons. apply in_eq. apply s0 in H5. inversion H5. subst. inversion H1.\n    subst. exfalso. apply H10. apply in_eq. }\n  apply Lindenbaum_lemma in H1. destruct H1. destruct H1.\n  destruct H1. destruct H2. destruct H3.\n  assert (J1: complete (fst (x, x0), snd (x, x0)) /\\ (wpair_derrec (fst (x, x0), snd (x, x0)) -> False)). auto.\n  pose (@exist (prod (Ensemble (BPropF V)) (Ensemble (BPropF V))) CompNotDer (x,x0) J1).\n  pose (H s).\n  assert (J2: Canon_rel (exist (fun x : Ensemble (BPropF V) * Ensemble (BPropF V) =>\n  CompNotDer x) (e, e0) (conj c f)) s). unfold Canon_rel. simpl.\n  intro. intros. apply H1. apply Union_introl. auto. apply w in J2.\n  apply IHA2 in J2. simpl in J2.\n  apply H4. exists [A2]. repeat split. apply NoDup_cons. auto. apply NoDup_nil.\n  intros. inversion H5. subst. simpl. apply H2. apply In_singleton. inversion H6.\n  simpl. apply MP with (ps:=[(x, Imp A2 (Or A2 (Bot V)));(x, A2)]). 2: apply MPRule_I.\n  intros. inversion H5. subst. apply Ax. apply AxRule_I. apply RA2_I. exists A2. exists (Bot V).\n  auto. inversion H6. 2: inversion H7. subst. apply Id. apply IdRule_I. auto.\n  apply IHA1. simpl. apply H1. apply Union_intror. apply In_singleton.\n- intros. destruct x. simpl in H. destruct v. simpl. destruct x. simpl.\n  apply IHA1 in H1. simpl in H1. unfold Canon_rel in H0. simpl in H0.\n  apply H0 in H. unfold CompNotDer in c0. destruct c0. simpl in f. simpl in c0.\n  apply IHA2. simpl.\n  assert (wpair_derrec (e1, Singleton _ A2)). exists [A2]. repeat split.\n  apply NoDup_cons ; auto ; apply NoDup_nil. intros. inversion H2. subst. apply In_singleton.\n  inversion H3. simpl.\n  apply MP with (ps:=[(e1, Imp A2 (Or A2 (Bot V)));(e1, A2)]). 2: apply MPRule_I.\n  intros. inversion H2. subst. apply Ax. apply AxRule_I. apply RA2_I. exists A2. exists (Bot V).\n  auto. inversion H3. subst.\n  apply MP with (ps:=[(e1, Imp A1 A2);(e1, A1)]). 2: apply MPRule_I.\n  intros. inversion H4. subst. apply Id. apply IdRule_I. auto.\n  inversion H5. 2: inversion H6. subst. apply Id. apply IdRule_I. auto.\n  inversion H4.\n  apply clos_deriv with (Δ:=e2). unfold CompNotDer ; auto. destruct H2. destruct H2.\n  destruct H3. destruct x. simpl in H4. apply MP with (ps:=[(e1, Imp (Bot V) A2);(e1, Bot V)]).\n  2: apply MPRule_I. intros. inversion H5. subst. apply wEFQ. inversion H6. 2: inversion H7.\n  subst. auto. inversion H2. subst. pose (H3 b). assert (List.In b (b :: x)).\n  apply in_eq. apply s in H5. inversion H5. subst. destruct x. simpl in H4.\n  apply absorp_Or1 in H4. auto. exfalso. pose (H3 b0). assert (List.In b0 (b :: b0 :: x)).\n  apply in_cons. apply in_eq. apply s0 in H6. inversion H6. subst. apply H7. apply in_eq.\n(* Excl A1 A2 *)\n- destruct H. destruct H. destruct H0. apply IHA1 in H0.\n  assert (In (BPropF V) (fst (proj1_sig x0)) (Or A2 (Excl A1 A2))).\n  apply clos_deriv with (Δ:=(snd (proj1_sig x0))). unfold CompNotDer ; auto.\n  destruct x0. simpl. auto. destruct x0. simpl.\n  apply MP with (ps:=[(fst x0, Imp A1 (Or A2 (Excl A1 A2)));(fst x0, A1)]). 2: apply MPRule_I.\n  intros. inversion H2. subst. apply Ax. apply AxRule_I. apply RA11_I. exists A1.\n  exists A2. auto. inversion H3. 2: inversion H4. subst. apply Id. apply IdRule_I.\n  auto. apply primeness with (Δ:=snd (proj1_sig x0)) in H2. destruct H2 ; auto. exfalso.\n  apply H1. apply IHA2 ; auto. destruct x0. simpl in H2. auto.\n- assert (wpair_derrec ((Singleton _ A1), Union _ (snd x) (Singleton _ A2)) -> False).\n  intro. destruct H0. destruct H0. destruct H1. simpl in H2. simpl in H1.\n  destruct x. simpl in H. simpl in H1. destruct c. simpl in H3. simpl in H4.\n  pose (remove_disj x0 A2 (Singleton (BPropF V) A1)).\n  assert (wBIH_rules (Singleton (BPropF V) A1, Or A2 (list_disj (remove eq_dec_form A2 x0)))).\n  apply MP with (ps:=[(Singleton (BPropF V) A1, list_disj x0 → Or A2\n   (list_disj (remove eq_dec_form A2 x0)));(Singleton (BPropF V) A1, list_disj x0)]).\n  2: apply MPRule_I. intros. inversion H5. subst. auto. inversion H6. subst.\n  auto. inversion H7. clear w. clear H2.\n  assert (Singleton (BPropF V) A1 = Union _ (Empty_set _) (Singleton (BPropF V) A1)).\n  apply Extensionality_Ensembles. split. intro. intros. inversion H2. subst.\n  apply Union_intror. apply In_singleton. intro. intros. inversion H2.\n  subst. inversion H6. inversion H6. subst. apply In_singleton. rewrite H2 in H5.\n  assert (J1: Union (BPropF V) (Empty_set (BPropF V)) (Singleton (BPropF V) A1) =\n  Union (BPropF V) (Empty_set (BPropF V)) (Singleton (BPropF V) A1)). auto.\n  assert (J2: Or A2 (list_disj (remove eq_dec_form A2 x0)) = Or A2 (list_disj (remove eq_dec_form A2 x0))). auto.\n  pose (wBIH_Deduction_Theorem (Union (BPropF V) (Empty_set (BPropF V)) (Singleton (BPropF V) A1),\n  Or A2 (list_disj (remove eq_dec_form A2 x0))) H5 A1 (Or A2 (list_disj (remove eq_dec_form A2 x0)))\n  (Empty_set _) J1 J2). apply wdual_residuation in w. clear J2. clear J1. clear H2.\n  clear H5.\n  apply H4. exists (remove eq_dec_form A2 x0). repeat split. apply NoDup_remove.\n  auto. intros. simpl. pose (H1 A). assert (List.In A x0). apply In_remove with (B:= A2).\n  auto. apply u in H5. inversion H5. subst. auto. subst. inversion H6.\n  subst. exfalso. apply remove_In in H2. auto. simpl.\n  apply MP with (ps:=[(e, Excl A1 A2 → list_disj (remove eq_dec_form A2 x0));(e, Excl A1 A2)]).\n  2: apply MPRule_I. intros. inversion H2. subst.\n  pose (wBIH_monot (Empty_set (BPropF V), Excl A1 A2 → list_disj (remove eq_dec_form A2 x0))\n  w e). apply w0. clear w0. simpl. intro. intros. inversion H5. inversion H5.\n  subst. 2: inversion H6. clear H2. clear H5. apply Id. apply IdRule_I. auto.\n  apply Lindenbaum_lemma in H0. destruct H0. destruct H0. destruct H0.\n  destruct H1. destruct H2.\n  assert (J1: CompNotDer (x0, x1)). unfold CompNotDer. auto.\n  pose (@exist (prod (Ensemble (BPropF V)) (Ensemble (BPropF V))) CompNotDer (x0,x1) J1).\n  exists s. unfold Canon_rel. simpl. split. destruct x. simpl.\n  intro. intros. destruct c. simpl in H5. pose (H5 x). destruct o.\n  simpl in H7. auto. simpl in H7. exfalso. pose (H1 x). simpl in i.\n  assert (In (BPropF V) (Union (BPropF V) e0 (Singleton (BPropF V) A2)) x).\n  apply Union_introl. auto. apply i in H8. apply H3. exists [x].\n  repeat split. apply NoDup_cons ; auto ; apply NoDup_nil.\n  intros. inversion H9. subst. simpl. auto. inversion H10.\n  simpl. apply MP with (ps:=[(x0, Imp x (Or x (Bot V))); (x0, x)]).\n  2: apply MPRule_I. intros. inversion H9. subst.\n  apply Ax. apply AxRule_I. apply RA2_I. exists x. exists (Bot V). auto.\n  inversion H10. 2: inversion H11. subst. apply Id. apply IdRule_I.\n  auto. split. apply IHA1. simpl. apply H0. apply In_singleton.\n  intro. apply IHA2 in H4. simpl in H4. apply H3. exists [A2].\n  repeat split. apply NoDup_cons ; auto ; apply NoDup_nil.\n  intros. inversion H5. subst. simpl. apply H1. apply Union_intror.\n  apply In_singleton. inversion H6. simpl.\n  apply MP with (ps:=[(x0, Imp A2 (Or A2 (Bot V)));(x0, A2)]). 2: apply MPRule_I.\n  intros. inversion H5. subst. apply Ax. apply AxRule_I. apply RA2_I. exists A2.\n  exists (Bot V). auto. inversion H6. 2: inversion H7. subst. clear H5.\n  clear H6. apply Id. apply IdRule_I. auto.\nQed.\n\nTheorem wCounterCompleteness : forall (Γ Δ : @Ensemble (BPropF V)),\n    (wpair_derrec (Γ, Δ) -> False) -> ((loc_conseq Γ Δ) -> False).\nProof.\nintros Γ Δ WD.\napply Lindenbaum_lemma in WD. destruct WD. destruct H. destruct H. destruct H0.\ndestruct H1. intro. unfold loc_conseq in H3.\nassert (J1: complete (fst (x, x0), snd (x, x0)) /\\ (wpair_derrec (fst (x, x0), snd (x, x0)) -> False)). auto.\npose (@exist (prod (Ensemble (BPropF V)) (Ensemble (BPropF V))) CompNotDer (x,x0) J1).\npose (H3 CM s).\nassert ((forall A : BPropF V, In (BPropF V) Γ A -> wforces CM s A)). intros. apply truth_lemma. auto.\napply e in H4. destruct H4. destruct H4. apply truth_lemma in H5. simpl in H5.\napply H2. exists [x1]. repeat split. apply NoDup_cons ; auto ; apply NoDup_nil.\nintros. inversion H6. simpl. subst. apply H0 ; auto. inversion H7. simpl.\napply MP with (ps:=[(x, Imp x1 (Or x1 (Bot V)));(x, x1)]). 2: apply MPRule_I.\nintros. inversion H6. subst. apply Ax. apply AxRule_I. apply RA2_I. exists x1. exists (Bot V).\nauto. inversion H7. subst. 2: inversion H8. apply Id. apply IdRule_I. auto.\nQed.\n\nTheorem wCompleteness : forall (Γ Δ : @Ensemble (BPropF V)),\n    (loc_conseq Γ Δ) -> wpair_derrec (Γ, Δ).\nProof.\nintros Γ Δ LC. pose (wCounterCompleteness Γ Δ).\npose (classic (wpair_derrec (Γ, Δ))). destruct o. auto. exfalso.\napply f ; assumption.\nQed.\n", "meta": {"author": "ianshil", "repo": "PhD_thesis", "sha": "af4940397f0d95c1d63a196ab29a3b9f715d9f4e", "save_path": "github-repos/coq/ianshil-PhD_thesis", "path": "github-repos/coq/ianshil-PhD_thesis/PhD_thesis-af4940397f0d95c1d63a196ab29a3b9f715d9f4e/Prop_Bi_Int/wBIH_completeness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2862769469667183}}
{"text": "\nRequire Export Metalib.Metatheory.\nRequire Export LibTactics.\nRequire Export SystemF_inf.\nRequire Export Fii_inf.\nRequire Export TypeSystems.\n\nCoercion ty_var_b : nat >-> ty.\nCoercion ty_var_f : typvar >-> ty.\nCoercion exp_var_b : nat >-> exp.\nCoercion exp_var_f : expvar >-> exp.\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 C1 := gather_atoms_with (fun x : ctx => dom x) in\n  let C2 := gather_atoms_with (fun x : tctx => dom x) in\n  let C3 := gather_atoms_with (fun x : stctx => dom x) in\n  let C4 := gather_atoms_with (fun x : sctx => dom x) in\n  let D1 := gather_atoms_with (fun x => fv_ty_in_ty x) in\n  let D2 := gather_atoms_with (fun x => fv_ty_in_exp x) in\n  let D3 := gather_atoms_with (fun x => fv_exp_in_exp x) in\n  let D4 := gather_atoms_with (fun x => fv_sty_in_sty x) in\n  let D5 := gather_atoms_with (fun x => fv_sty_in_sexp x) in\n  let D6 := gather_atoms_with (fun x => fv_sexp_in_sexp x) in\n  constr:(A \\u B \\u C1 \\u C2 \\u C3 \\u C4 \\u D1 \\u D2 \\u D3 \\u D4 \\u D5 \\u D6).\n\n\n(* ********************************************************************** *)\n(** * Notations *)\n\nNotation \"'|' A '|'\" := (sty2ty A) (at level 60).\n\nNotation \"'∥' Γ '∥'\" := (map sty2ty Γ) (at level 60).\n\n\nLemma trans_open_sty_rec : forall A B n,\n    | open_sty_wrt_sty_rec n B A | = open_ty_wrt_ty_rec n (| B |) (| A |).\nProof with eauto.\n  intros A.\n  induction A; intros B m; simpls...\n\n  destruct (lt_eq_lt_dec n m)...\n  destruct s...\n\n  rewrite IHA2.\n  rewrite IHA1...\n\n  rewrite IHA2.\n  rewrite IHA1...\n\n  rewrite IHA2...\nQed.\n\n\nLemma trans_open_sty : forall A B,\n    | open_sty_wrt_sty B A | = open_ty_wrt_ty (| B |) (| A |).\nProof.\n  intros.\n  unfold open_sty_wrt_sty.\n  unfold open_ty_wrt_ty.\n  rewrite trans_open_sty_rec.\n  reflexivity.\nQed.\n\nLemma trans_subst_sty : forall B A X,\n    | subst_sty_in_sty A X B | = subst_ty_in_ty (| A |) X (| B |).\nProof with eauto.\n  intros B.\n  induction B; intros; simpls...\n  case_if...\n\n  rewrite IHB1...\n  rewrite IHB2...\n\n  rewrite IHB1...\n  rewrite IHB2...\n\n  rewrite IHB2...\nQed.\n\n\nLemma lc_sty_ty : forall A,\n    lc_sty A -> lc_ty (| A |).\nProof with eauto.\n  intros A H.\n  induction H; simpls...\n\n  pick fresh X.\n  apply (lc_ty_all_exists X).\n  unfold open_ty_wrt_ty.\n  simpls...\n\n  pick_fresh X.\n  apply (lc_ty_all_exists X).\n  asserts_rewrite (ty_var_f X = | sty_var_f X |)...\n  rewrite <- trans_open_sty...\nQed.\n\n\nLemma notin_sty_ty : forall X A,\n    X `notin` fv_sty_in_sty A -> X `notin` fv_ty_in_ty (| A |).\nProof with eauto.\n  intros.\n  induction A; simpls...\nQed.\n\n\n(* ********************************************************************** *)\n(** * Properties of monotype  *)\n\n\nHint Constructors mono.\n\nLemma sty_mono_or_not : forall A,\n    lc_sty A ->\n    mono A \\/ ~mono A.\nProof with eauto.\n  introv LC.\n  induction LC; try solve [left; constructor].\n\n  destruct IHLC1.\n  destruct IHLC2.\n  left; constructor...\n  right.\n  introv Bad.\n  inverts Bad.\n  tryfalse.\n  destruct IHLC2.\n  right.\n  introv Bad.\n  inverts Bad.\n  tryfalse.\n  right.\n  introv Bad.\n  inverts Bad.\n  tryfalse.\n\n  destruct IHLC1.\n  destruct IHLC2.\n  left; constructor...\n  right.\n  introv Bad.\n  inverts Bad.\n  tryfalse.\n  destruct IHLC2.\n  right.\n  introv Bad.\n  inverts Bad.\n  tryfalse.\n  right.\n  introv Bad.\n  inverts Bad.\n  tryfalse.\n\n  right.\n  introv Bad.\n  inverts Bad.\n\n  destruct IHLC.\n  left; constructor...\n  right.\n  introv Bad.\n  inverts Bad.\n  tryfalse.\nQed.\n\n\nLemma mono_lc : forall t,\n    mono t -> lc_sty t.\nProof with eauto.\n  induction 1...\n\nQed.\n\nLemma poly_lc : forall t,\n    poly t -> lc_sty t.\nProof with eauto using mono_lc.\n  induction 1...\nQed.\n\n\n\nLemma not_mono_arrow : forall A B,\n    lc_sty A ->\n    lc_sty B ->\n    ~mono (sty_arrow A B) ->\n    ~mono A \\/ ~mono B.\nProof with eauto.\n  introv HA HB H.\n  apply sty_mono_or_not in HA.\n  apply sty_mono_or_not in HB.\n  destruct HA.\n  destruct HB.\n  false.\n  apply H...\n  right...\n  destruct HB.\n  left...\n  left...\nQed.\n\n\nLemma not_mono_and : forall A B,\n    lc_sty A ->\n    lc_sty B ->\n    ~mono (sty_and A B) ->\n    ~mono A \\/ ~mono B.\nProof with eauto.\n  introv HA HB H.\n  apply sty_mono_or_not in HA.\n  apply sty_mono_or_not in HB.\n  destruct HA.\n  destruct HB.\n  false.\n  apply H...\n  right...\n  destruct HB.\n  left...\n  left...\nQed.\n\nLemma not_mono_is_poly : forall A,\n    lc_sty A -> ~mono A -> poly A.\nProof with eauto.\n  introv LC.\n  induction LC; introv Mono; try solve [false; apply Mono; eauto]...\n\n  - Case \"arrow\".\n    apply not_mono_arrow in Mono...\n    destruct Mono as [Mono1 | Mono2].\n    forwards HB : sty_mono_or_not B...\n    destruct HB as [HB1 | HB2].\n    apply IHLC1 in Mono1...\n    apply IHLC1 in Mono1...\n    forwards HA : sty_mono_or_not A...\n    destruct HA as [HA1 | HA2].\n    apply IHLC2 in Mono2...\n    apply IHLC1 in HA2...\n\n\n  - Case \"and\".\n    apply not_mono_and in Mono...\n    destruct Mono as [Mono1 | Mono2].\n    forwards HB : sty_mono_or_not B...\n    destruct HB as [HB1 | HB2].\n    apply IHLC1 in Mono1...\n    apply IHLC1 in Mono1...\n    forwards HA : sty_mono_or_not A...\n    destruct HA as [HA1 | HA2].\n    apply IHLC2 in Mono2...\n    apply IHLC1 in HA2...\n\n\n  - Case \"record\".\n    constructor...\n\nQed.\n\n\n\nLemma subst_mono: forall x t t',\n    mono t' ->\n    mono t ->\n    mono (subst_sty_in_sty t x t').\nProof with eauto.\n  introv Mono.\n  gen t x.\n  induction Mono; introv M; simpls; try constructor...\n  case_if...\nQed.\n\n\n\n\n(* ********************************************************************** *)\n(** * Properties of well-formedness of a type in an environment *)\n\nLemma fv_sty_dom : forall D A,\n    swft D A -> fv_sty_in_sty A [<=] dom D.\nProof.\n  introv H.\n  induction H; simpls; try fsetdec.\n\n  apply binds_In in H.\n  fsetdec.\n\n  pick fresh X.\n  assert (fv_sty_in_sty (open_sty_wrt_sty B (sty_var_f X)) [<=] add X (dom DD)) by eauto.\n  assert (fv_sty_in_sty B [<=] fv_sty_in_sty (open_sty_wrt_sty B (sty_var_f X))) by eapply fv_sty_in_sty_open_sty_wrt_sty_lower.\n  fsetdec.\nQed.\n\nLemma fv_sty_nil : forall A,\n    swft nil A ->\n    fv_sty_in_sty A [=] {}.\nProof.\n  introv H.\n  forwards~  : fv_sty_dom H.\n  fsetdec.\nQed.\n\n\nLemma uniq_from_swfe : forall D E,\n  swfe D E ->\n  uniq E.\nProof with eauto.\n  intros D E H; induction H...\nQed.\n\n\nLemma uniq_from_swfte : forall D,\n  swfte D ->\n  uniq D.\nProof with eauto.\n  intros D H; induction H...\nQed.\n\nLemma uniq_from_swfte_push : forall X A D,\n  swfte ([(X, A)] ++ D) ->\n  uniq D.\nProof with eauto.\n  introv WFTE; inversions WFTE. apply uniq_from_swfte...\nQed.\n\nLemma swft_type : forall E T,\n  swft E T -> lc_sty T.\nProof.\n  induction 1; eauto.\nQed.\n\n\nLemma swft_wft : forall Δ A,\n    swft Δ A -> wft (map (const tt) Δ) (| A |).\nProof with eauto.\n  introv H.\n  induction H; simpls...\n\n\n  pick fresh X and apply wft_all...\n  unfold open_ty_wrt_ty.\n  simpls...\n\n  constructor...\n  apply binds_map_2 with (f := const tt) (a := A)...\n\n  pick fresh X and apply wft_all...\n  asserts_rewrite (ty_var_f X = | sty_var_f X |)...\n  rewrite <- trans_open_sty...\n  apply (H1 X)...\nQed.\n\n\nLemma swft_wft_nil : forall A,\n    swft nil A -> wft nil (| A |).\nProof with eauto.\n  introv H.\n  apply swft_wft in H.\n  simpls...\nQed.\n\nLemma swfe_wfe : forall Δ Γ,\n    uniq Δ ->\n    swfe Δ Γ ->\n    wfe (map (const tt) Δ) (∥ Γ ∥).\nProof with eauto using swft_wft.\n  introv W H.\n  induction H; simpls...\n\n  constructor...\nQed.\n\n\nLemma swfe_notin : forall D G x A,\n    swfe D G ->\n    binds x A G ->\n    x `notin` dom D.\nProof with eauto.\n  induction 1; introv Bind; simpls...\n  analyze_binds Bind...\nQed.\n\n\nLemma wft_type : forall E T,\n  wft E T -> lc_ty T.\nProof.\n  induction 1; eauto.\nQed.\n\n\nLemma wft_weaken : forall T E F G,\n  wft (G ++ E) T ->\n  uniq (G ++ F ++ E) ->\n  wft (G ++ F ++ E) T.\nProof with simpl_env; eauto.\n  intros T E F G Hwf_typ Hk.\n  remember (G ++ E) as F'.\n  generalize dependent G.\n  induction Hwf_typ; intros G Hok Heq; subst...\n  Case \"ty_all\".\n    pick fresh Y and apply wft_all...\n    rewrite <- app_assoc.\n    apply H0...\nQed.\n\n\n\nLemma swft_weaken : forall T E F G,\n  swft (G ++ E) T ->\n  uniq (G ++ F ++ E) ->\n  swft (G ++ F ++ E) T.\nProof with simpl_env; eauto.\n  intros T E F G Hwf_typ Hk.\n  remember (G ++ E) as F'.\n  generalize dependent G.\n  induction Hwf_typ; intros G Hok Heq; subst...\n  Case \"ty_all\".\n    pick fresh Y and apply swft_all...\n    rewrite <- app_assoc.\n    apply H0...\nQed.\n\nLemma wft_weaken_head : forall T E F,\n  wft E T ->\n  uniq (F ++ E) ->\n  wft (F ++ E) T.\nProof.\n  intros.\n  rewrite_env (nil ++ F++ E).\n  auto using wft_weaken.\nQed.\n\nLemma swft_weaken_head : forall T E F,\n  swft E T ->\n  uniq (F ++ E) ->\n  swft (F ++ E) T.\nProof.\n  intros.\n  rewrite_env (nil ++ F++ E).\n  auto using swft_weaken.\nQed.\n\n\nLemma swft_from_swfte : forall Y A D,\n    swfte D ->\n    binds Y A D ->\n    swft D A.\nProof with eauto using uniq_from_swfte.\n  induction 1; intros J; analyze_binds J...\n  eapply swft_weaken_head...\n  apply IHswfte in BindsTac.\n  eapply swft_weaken_head...\nQed.\n\n\nLemma wft_subst_tb : forall F E Z P T,\n  wft (F ++ Z ~ tt ++ E) T ->\n  wft E P ->\n  uniq (F ++ E) ->\n  wft (F ++ E) (subst_ty_in_ty P Z T).\nProof with simpl_env; eauto using wft_weaken_head, wft_type.\n  intros F E Z P T WT WP.\n  remember (F ++ Z ~ tt ++ E) as G.\n  generalize dependent F.\n  induction WT; intros F EQ Ok; subst; simpl subst_ty_in_ty...\n  - Case \"ty_var\".\n    case_if...\n  - Case \"ty_all\".\n    pick fresh Y and apply wft_all...\n    rewrite subst_ty_in_ty_open_ty_wrt_ty_var...\n    rewrite_env (([(Y, tt)] ++ F) ++ E).\n    apply H0...\nQed.\n\n\nLemma swft_subst_tb : forall F E Z P T B,\n  swft (F ++ Z ~ B ++ E) T ->\n  swft E P ->\n  uniq (map (subst_sty_in_sty P Z) F ++ E) ->\n  swft (map (subst_sty_in_sty P Z) F ++ E) (subst_sty_in_sty P Z T).\nProof with simpl_env; eauto using swft_weaken_head, swft_type.\n  intros F E Z P T B WT WP.\n  remember (F ++ Z ~ B ++ E) as G.\n  generalize dependent F.\n  induction WT; intros F EQ Ok; subst; simpl subst_sty_in_sty...\n  - Case \"swft_var\".\n    case_if...\n    analyze_binds H...\n  - Case \"swft_all\".\n    pick fresh Y and apply swft_all...\n    rewrite subst_sty_in_sty_open_sty_wrt_sty_var...\n    rewrite_env (map (subst_sty_in_sty P Z) (Y ~ A ++ F) ++ E).\n    apply H0...\nQed.\n\nLemma swft_subst_sty : forall E Z P T B,\n  swft ([(Z, B)] ++ E) T ->\n  swft E P ->\n  uniq E ->\n  swft E (subst_sty_in_sty P Z T).\nProof.\n  introv HY WTF UNI.\n  rewrite_env (nil ++ Z ~ B ++ E) in HY.\n  forwards I : swft_subst_tb HY WTF UNI.\n  simpl_alist in I; auto.\nQed.\n\nLemma wft_open : forall E U T2,\n  uniq E ->\n  wft E (ty_all T2) ->\n  wft E U ->\n  wft E (open_ty_wrt_ty T2 U).\nProof with simpl_env; eauto.\n  intros E U T2 Ok WA WU.\n  inversion WA; subst.\n  pick fresh X.\n  rewrite (subst_ty_in_ty_intro X)...\n  rewrite_env (nil ++ E).\n  eapply wft_subst_tb...\nQed.\n\n\nLemma swft_open : forall E U T1 T2,\n  uniq E ->\n  swft E (sty_all T1 T2) ->\n  swft E U ->\n  swft E (open_sty_wrt_sty T2 U).\nProof with simpl_env; eauto.\n  intros E U T1 T2 Ok WA WU.\n  inversion WA; subst.\n  pick fresh X.\n  rewrite (subst_sty_in_sty_intro X)...\n  rewrite_env (map (subst_sty_in_sty U X) nil ++ E).\n  eapply swft_subst_tb...\nQed.\n\n\n\n(* *********************************************************************************** *)\n(** * Relations between well-formed environment and well-formed  types in environments *)\n\nLemma swft_tvar : forall D X A,\n    swft D A ->\n    X `notin` dom D ->\n    X `notin` fv_sty_in_sty A.\nProof with eauto.\n  introv H.\n  gen X.\n  induction H; introv W; simpls...\n  lets : binds_In H.\n  fsetdec.\n\n  pick_fresh Y.\n\n  forwards~ : H1 Y X.\n  lets : IHswft W.\n  lets : fv_sty_in_sty_open_sty_wrt_sty_lower B (sty_var_f Y).\n  fsetdec.\n\nQed.\n\n\nLemma swfte_tvar : forall X A D,\n    swfte D ->\n    binds X A D ->\n    X `notin` fv_sty_in_sty A.\nProof with eauto.\n  introv H.\n  gen X A.\n  induction H; introv B.\n  analyze_binds B.\n\n  analyze_binds B.\n  eapply swft_tvar...\n\nQed.\n\n\nInductive same_stctx {a b} : list (atom * a) -> list (atom * b) -> Prop :=\n| same_empty : same_stctx nil nil\n| same_cons : forall X A B s1 s2,\n    same_stctx s1 s2 ->  same_stctx ([(X , A)] ++ s1) ([(X , B)] ++ s2).\n\nHint Constructors same_stctx.\n\n\n\nLemma same_stctx_dom : forall a b (ctxa : list (atom * a))  (ctxb : list (atom * b)),\n    same_stctx ctxa ctxb ->\n    dom ctxa [=] dom ctxb.\nProof with eauto; try fsetdec.\n  induction 1; simpls...\nQed.\n\n\nLemma same_eq : forall a (s1 : list (atom * a)),\n    same_stctx s1 s1.\nProof with eauto.\n  alist induction s1...\nQed.\n\n\nLemma same_map : forall a b (s1 : list (atom * a)) (f : a -> b),\n    same_stctx s1 (map f s1).\nProof with eauto; simpl_env.\n  alist induction s1...\n  intros.\n  simpls...\n\n  intros.\n  simpls...\n  constructor...\nQed.\n\n\nLemma same_sym : forall a b (s1 : list (atom * a)) (s2 : list (atom * b)),\n    same_stctx s1 s2 -> same_stctx s2 s1.\nProof with eauto.\n  introv H.\n  induction H...\nQed.\n\n\nLemma same_var : forall a b (s1 : list (atom * a)) (s2 : list (atom * b)) X A,\n    same_stctx s1 s2 ->\n    binds X A s1 ->\n    exists B, binds X B s2.\nProof with eauto.\n  introv Eq.\n  gen X A.\n  induction Eq; introv H.\n\n  analyze_binds H.\n\n  analyze_binds H...\n  lets (B0 & ?) : IHEq BindsTac.\n\n  exists B0...\nQed.\n\n\nLemma swft_change : forall Δ Δ' A,\n    swft Δ A ->\n    same_stctx Δ Δ' ->\n    swft Δ' A.\nProof with eauto.\n  introv H.\n  gen Δ'.\n  induction H; introv Eq...\n\n  lets (B & ?): same_var Eq H...\nQed.\n  \n\n(* ******************************************************************************* *)\n(** *Properties of [wfe]  *)\n\nLemma uniq_from_wfe : forall D E,\n  wfe D E ->\n  uniq E /\\ uniq D.\nProof with eauto.\n  intros D E H; induction H...\n  invert IHwfe...\nQed.\n\nLemma wft_from_wfe : forall x U E D,\n  wfe D E ->\n  binds x U E ->\n  wft D U.\nProof.\n  induction 1; intros J; analyze_binds J.\nQed.\n\n\nLemma swft_from_swfe : forall x U E D,\n  swfe D E ->\n  binds x U E ->\n  swft D U.\nProof.\n  induction 1; intros J; analyze_binds J.\nQed.\n\n\nLemma wfe_weaken : forall T E G X,\n  wfe (G ++ E) T ->\n  uniq (G ++ [(X, tt)] ++ E) ->\n  X `notin` dom T ->\n  wfe (G ++ [(X, tt)] ++ E) T.\nProof with simpl_env; eauto.\n  introv Hwf_typ Hk Notin.\n  remember (G ++ E) as F'.\n  generalize dependent G.\n  induction Hwf_typ; intros G Hok Heq; subst...\n  constructor...\n  apply wft_weaken...\nQed.\n\n\nLemma wfe_subst_tb : forall Z P E F D,\n  wfe (F ++ Z ~ tt ++ E) D ->\n  wft E P ->\n  uniq (F ++ E) ->\n  wfe (F ++ E) (map (subst_ty_in_ty P Z) D).\nProof with eauto using wft_subst_tb.\n  introv WFE WFT.\n  remember (F ++ Z ~ tt ++ E) as G.\n  generalize dependent F.\n  induction WFE; introv EQ Uniq; subst; simpl...\n  constructor...\nQed.\n\n\nLemma notin_fv_typ_in_typ_open : forall (Y X : typvar)  T,\n  X `notin` fv_ty_in_ty (open_ty_wrt_ty T Y) ->\n  X `notin` fv_ty_in_ty T.\nProof.\n intros Y X T. unfold open_ty_wrt_ty.\n generalize 0.\n induction T; simpl; intros k Fr; eauto.\nQed.\n\n\nLemma notin_fv_wf : forall E (X : typvar) T,\n  wft E T ->\n  X `notin` dom E ->\n  X `notin` fv_ty_in_ty T.\nProof with auto.\n  intros E X T Wf_typ.\n  induction Wf_typ; intros Fr; simpl...\n  Case \"wf_typ_var\".\n    assert (X0 `in` (dom dd))...\n    eapply binds_In; eauto. fsetdec.\n  Case \"wft_all\".\n    pick fresh Y.\n    apply (notin_fv_typ_in_typ_open Y)...\nQed.\n\n\nLemma map_subst_typ_in_binding_id : forall G Z P D,\n  wfe D G ->\n  Z `notin` dom D ->\n  G = map (subst_ty_in_ty P Z) G.\nProof with eauto.\n  introv H.\n  induction H; simpl; intros Fr; simpl_env...\n  rewrite <- IHwfe...\n  rewrite subst_ty_in_ty_fresh_eq...\n  eapply notin_fv_wf...\nQed.\n\n\nLemma wfe_strengthen : forall E F x U T,\n wfe T (F ++ x ~ U ++ E) ->\n wfe T (F ++ E).\nProof with eauto.\n  induction F;\n  introv Wfe; inversion Wfe; subst; simpl_env in *...\nQed.\n\n\n\n(* ******************************************************************************* *)\n(** *Regularity of relations *)\n\n\nLemma sub_regular : forall Δ A B c,\n    sub Δ A B c ->\n    swft Δ A /\\ swft Δ B.\nProof with eauto using same_eq, same_sym.\n  introv Sub.\n  induction* Sub.\n\n  (* Case 1 *)\n  destruct IHSub.\n  splits.\n\n  pick fresh Y and apply swft_all...\n  forwards (? & ?) : H0...\n  apply swft_change with (Δ := ([(Y , A2)] ++ DD))...\n\n  pick fresh Y and apply swft_all...\n  forwards (? & ?) : H0...\n\n  (* Case 2 *)\n  splits...\n\n  pick fresh Y and apply swft_all...\n  unfold open_sty_wrt_sty.\n  simpls...\n\n\n  Unshelve.\n  exact (dom DD).\nQed.\n\n\n\n\nLemma disjoint_regular : forall Δ A B,\n    disjoint Δ A B ->\n    swft Δ A /\\ swft Δ B.\nProof with eauto using same_eq.\n  introv Dis.\n  induction* Dis.\n\n  splits...\n  eapply sub_regular...\n\n  splits...\n  eapply sub_regular...\n\n  splits...\n\n  pick fresh X and apply swft_all...\n  apply swft_change with (Δ := ([(X , sty_and A1 A2)] ++ DD))...\n  eapply H0...\n\n  pick fresh X and apply swft_all...\n  apply swft_change with (Δ := ([(X , sty_and A1 A2)] ++ DD))...\n  eapply H0...\nQed.\n\n\nLemma styping_regular : forall D G E dir e A,\n  has_type D G E dir A e ->\n  lc_sexp E /\\ swfe D G /\\ swft D A /\\ swfte D.\nProof with simpl_env; try solve [auto | intuition auto].\n  introv H.\n  induction H...\n\n  - Case \"var\".\n    splits...\n    eauto using swft_from_swfe.\n\n  - Case \"app\".\n    splits...\n    destruct IHhas_type1 as (_ & _ & K & _).\n    inverts K...\n\n  - Case \"anno\".\n    splits...\n    destructs IHhas_type...\n    lets :  swft_type H2.\n    constructor~.\n\n  - Case \"tabs\".\n    pick_fresh Y.\n    destructs (H1 Y)...\n    inverts H6.\n    splits...\n    + SCase \"lc_sexp\".\n      apply (lc_sexp_tabs_exists Y).\n      destructs (H1 Y)...\n      eauto using  swft_type.\n      eauto using  swft_type.\n    + SCase \"wft\".\n      pick fresh Z and apply swft_all...\n      destructs (H1 Z)...\n\n  - Case \"tapp\".\n    splits...\n    + SCase \"lc_exp\".\n      forwards (? & ?) : disjoint_regular H1.\n      apply lc_sexp_tapp...\n      eauto using swft_type.\n    + SCase \"wft\".\n      forwards (? & ?) : disjoint_regular H1.\n      destructs IHhas_type.\n      eapply swft_open; eauto.\n      apply uniq_from_swfte...\n\n\n  - Case \"proj\".\n    destructs IHhas_type.\n    inverts H2.\n    splits...\n\n  - Case \"abs\".\n    pick_fresh y.\n    destructs (H1 y)...\n    inverts H3.\n    splits...\n    + SCase \"lc_exp\".\n      apply (lc_sexp_abs_exists y).\n      destructs (H1 y)...\nQed.\n\n\nLemma typing_regular : forall D E e T,\n  typ D E e T ->\n  lc_exp e /\\ wfe D E /\\ wft D T.\nProof with simpl_env; try solve [auto | intuition auto].\n  introv H; induction H...\n  - Case \"typ_var\".\n    splits...\n    eauto using wft_from_wfe.\n  - Case \"typ_abs\".\n    pick_fresh y.\n    destructs (H0 y)...\n    inverts H3.\n    splits...\n    + SCase \"lc_exp\".\n      apply (lc_exp_abs_exists y).\n      destructs (H0 y)...\n  - Case \"typ_app\".\n    splits...\n    destruct IHtyp1 as (_ & _ & K).\n    inverts K...\n  - Case \"typ_tabs\".\n    pick_fresh Y.\n    destructs (H0 Y)...\n    splits...\n    + SCase \"lc_exp\".\n      apply (lc_exp_tabs_exists Y).\n      destructs (H0 Y)...\n    + SCase \"wft\".\n      pick fresh Z and apply wft_all...\n      destructs (H0 Z)...\n  - Case \"tapp\".\n    splits...\n    + SCase \"lc_exp\".\n      apply lc_exp_tapp...\n      eauto using wft_type.\n    + SCase \"wft\".\n      destructs IHtyp.\n      eapply wft_open; eauto.\n      lets* : uniq_from_wfe H2.\nQed.\n\n\nLemma value_regular : forall v,\n    value v ->\n    lc_exp v.\nProof.\n  intros v H.\n  induction H; auto.\nQed.\n\n\nLemma step_regular : forall e e',\n  step e e' ->\n  lc_exp e /\\ lc_exp e'.\nProof with eauto using value_regular, lc_body_exp_wrt_ty, lc_body_exp_wrt_exp, lc_body_exp_abs_1, lc_body_exp_tabs_1.\n  intros e e' H.\n  induction H; intuition eauto 6; try constructor...\nQed.\n\nLemma ctyp_wft : forall G c T1 T2,\n    ctyp G c T1 T2 ->\n    wft G T1 /\\ wft G T2.\nProof with eauto.\n  introv Ctyp.\n  induction* Ctyp.\n\n\n  splits...\n  pick fresh X and apply wft_all.\n  unfold open_ty_wrt_ty.\n  simpls...\n\n  (* Case 1 *)\n  splits...\n\n  pick fresh X and apply wft_all.\n  forwards (? & ?): H0 X...\n\n  pick fresh X and apply wft_all.\n  forwards (? & ?): H0 X...\n\n  (* Case 2 *)\n  inverts H.\n  inverts H0.\n\n  splits; eauto.\n  pick fresh X and apply wft_all; auto.\n  unfold open_ty_wrt_ty.\n  simpls; eauto.\n\n\n  Unshelve.\n  exact (dom dd).\n\nQed.\n\n\n(* Automations to the resue *)\n\n\nHint Extern 1 (wfe ?D ?E) =>\n  match goal with\n  | H: typ D E _ _ |- _ => apply (proj1 (proj2 (typing_regular _ _ _ _ H)))\n  end.\n\n\nHint Extern 1 (wft ?E ?T) =>\n  match goal with\n  | H: typ E _ _ T |- _ => apply (proj2 (proj2 (typing_regular _ _ _ _ H)))\n  | H: ctyp E _ T _ |- _ => apply (proj1 (ctyp_wft _ _ _ _ H))\n  | H: ctyp E _ _ T |- _ => apply (proj2 (ctyp_wft _ _ _ _ H))\n  end.\n\n\nHint Extern 1 (lc_exp ?e) =>\n  match goal with\n  | H: typ _ _ ?e _ |- _ => apply (proj1 (typing_regular _ _ _ _ H))\n  | H: step ?e _ |- _ => apply (proj1 (step_regular _ _ H))\n  | H: step _ ?e |- _ => apply (proj2 (step_regular _ _ H))\n  | H : value ?v |- _ => apply value_regular\n  end.\n\n\nHint Extern 1 (lc_ty ?T) =>\n  match goal with\n  | H: wft _ ?T |- _ => apply (wft_type _ _ H)\n  | H : typ _ _ _ ?T |- _ => apply (wft_type _ _ (proj2 (proj2 (typing_regular _ _ _ _ H))))\n  end.\n\nHint Extern 1 (uniq ?E) =>\n  match goal with\n  | H: swfe _ E |- _ => apply (uniq_from_swfe _ _ H)\n  | H: swfte E |- _ => apply (uniq_from_swfte _ H)\n  | H: wfe E _ |- _ => apply (proj2 (uniq_from_wfe _ _ H))\n  | H: wfe _ E |- _ => apply (proj1 (uniq_from_wfe _ _ H))\n  end.\n\n\n\n(* ******************************************************************************* *)\n(** *Properties of typing *)\n\nLemma typing_var_weakening : forall E F G e T D,\n  typ D (G ++ E) e T ->\n  wfe D (G ++ F ++ E) ->\n  typ D (G ++ F ++ E) e T.\nProof with simpl_env; eauto using wft_weaken, wft_from_wfe.\n  intros E F G e T D Typ.\n  remember (G ++ E) as H.\n  generalize dependent G.\n  induction Typ; intros G EQ Ok; subst...\n\n  - Case \"typ_abs\".\n    pick fresh x and apply typ_abs...\n    rewrite <- app_assoc.\n    apply (H0 x)...\n  - Case \"typing_tabs\".\n    pick fresh X and apply typ_tabs...\n    apply (H0 X)...\n    rewrite_env (nil ++ [(X, tt)] ++ dd).\n    apply wfe_weaken...\nQed.\n\n\nLemma ctyp_weaken : forall E F G c T1 T2,\n    ctyp (G ++ E) c T1 T2 ->\n    uniq (G ++ F ++ E) ->\n    ctyp (G ++ F ++ E) c T1 T2.\nProof with eauto using wft_weaken.\n  introv Ctyp.\n  remember (G ++ E) as H.\n  generalize dependent G.\n  induction Ctyp; introv EQ Ok; subst...\n\n  pick fresh X and apply ctyp_forall.\n  rewrite_env (([(X, tt)] ++ G) ++ F ++ E).\n  eapply H0...\n  solve_uniq.\nQed.\n\n\n\nLemma typing_tvar_weakening : forall E G e T D X,\n  typ (G ++ E) D e T ->\n  uniq (G ++ [(X, tt)] ++ E) ->\n  X \\notin dom D ->\n  typ (G ++ [(X, tt)] ++ E) D e T.\nProof with simpl_env; eauto using wfe_weaken, wft_weaken, ctyp_weaken.\n  introv Typ Uniq Notin.\n  remember (G ++ E) as H.\n  generalize dependent G.\n  induction Typ; introv Ok Uniq; subst...\n\n  - Case \"typ_abs\".\n    pick fresh x and apply typ_abs...\n\n  - Case \"typ_tabs\".\n    pick fresh Y and apply typ_tabs...\n    rewrite_env (([(Y, tt)] ++ G) ++ [(X, tt)] ++ E).\n    apply (H0 Y)...\nQed.\n\n\n\nLemma ctyp_through_subst_typ_in_typ : forall E F Z S T P c,\n    ctyp (F ++ Z ~ tt ++ E) c S T ->\n    uniq (F ++ E) ->\n    wft E P ->\n    ctyp (F ++ E) c (subst_ty_in_ty P Z S) (subst_ty_in_ty P Z T).\nProof with simpl_env; eauto using wft_subst_tb.\n  introv Ctyp Uniq Wf.\n  remember (F ++ Z ~ tt ++ E) as G.\n  generalize dependent F.\n  induction Ctyp; introv EQ Uniq; subst; simpls...\n\n  - Case \"ctyp_forall\".\n    pick fresh X and apply ctyp_forall...\n    rewrite subst_ty_in_ty_open_ty_wrt_ty_var...\n    rewrite subst_ty_in_ty_open_ty_wrt_ty_var...\n    rewrite_env (([(X, tt)] ++ F) ++ E).\n    eapply H0...\n\n  - Case \"ctyp_distPoly\".\n    constructor...\n    replace (ty_all (subst_ty_in_ty P Z T1)) with (subst_ty_in_ty P Z (ty_all T1))...\n    replace (ty_all (subst_ty_in_ty P Z T2)) with (subst_ty_in_ty P Z (ty_all T2))...\nQed.\n\n\nLemma typing_through_subst_typ_in_exp : forall E F Z e T P D,\n  typ (F ++ Z ~ tt ++ E) D e T ->\n  uniq (F ++ E) ->\n  wft E P ->\n  typ (F ++ E) (map (subst_ty_in_ty P Z) D) (subst_ty_in_exp P Z e) (subst_ty_in_ty P Z T).\nProof with simpl_env; eauto 6 using wfe_subst_tb, wft_subst_tb.\n  introv Typ Uniq Wf.\n  remember (F ++ Z ~ tt ++ E) as G.\n  generalize dependent F.\n  induction Typ; intros F EQ Uniq; subst;\n    simpl subst_ty_in_exp in *; simpl subst_ty_in_ty in *...\n\n  - Case \"typ_abs\".\n    pick fresh y and apply typ_abs...\n    rewrite subst_ty_in_exp_open_exp_wrt_exp_var...\n    rewrite_env (map (subst_ty_in_ty P Z) ([(y, T1)] ++ gg)).\n    apply H0...\n\n  - Case \"typ_tabs\".\n    pick fresh Y and apply typ_tabs...\n    rewrite subst_ty_in_exp_open_exp_wrt_ty_var...\n    rewrite subst_ty_in_ty_open_ty_wrt_ty_var...\n    rewrite_env (([(Y, tt)] ++ F) ++ E).\n    apply H0...\n\n  - Case \"typ_tapp\".\n    rewrite subst_ty_in_ty_open_ty_wrt_ty...\n\n  - Case \"typ_capp\".\n    eapply typ_capp...\n    apply ctyp_through_subst_typ_in_typ...\nQed.\n\n\n\nLemma typing_through_subst_exp_in_exp : forall U E F x T e u D,\n  typ D (F ++ x ~ U ++ E) e T ->\n  typ D E u U ->\n  typ D (F ++ E) (subst_exp_in_exp u x e) T.\nProof with simpl_env; eauto 4 using wfe_strengthen.\n\n  introv TypT TypU.\n  remember (F ++ x ~ U ++ E) as E'.\n  generalize dependent F.\n  induction TypT; introv EQ; subst; simpl subst_exp_in_exp in *...\n\n  - Case \"typ_var\".\n    destruct (x0 == x); subst...\n    analyze_binds_uniq H0.\n    rewrite_env (nil ++ F ++ E).\n    apply typing_var_weakening...\n\n  - Case \"typ_abs\".\n    pick fresh y and apply typ_abs...\n    rewrite subst_exp_in_exp_open_exp_wrt_exp_var...\n    rewrite_env (([(y, T1)] ++ F) ++ E).\n    apply H0...\n\n  - Case \"typ_tabs\".\n    pick fresh Y and apply typ_tabs...\n    rewrite subst_exp_in_exp_open_exp_wrt_ty_var...\n    apply H0...\n    rewrite_env (nil ++ [(Y, tt)] ++ dd).\n    apply typing_tvar_weakening...\n\nQed.\n\n\nLemma prod_canonical : forall t T1 T2,\n    value t ->\n    typ nil nil t (ty_prod T1 T2) ->\n    exists t1 t2, value t1 /\\ value t2 /\\ t = exp_pair t1 t2.\nProof.\n  introv VAL TY. inductions TY; try (solve [inversion VAL]).\n  inversions VAL. exists e1 e2. splits~. \n  inversions VAL; inversions H.\nQed.\n\nLemma unit_canonical : forall t,\n    value t ->\n    typ nil nil t ty_unit ->\n    t = exp_unit.\nProof with eauto.\n  introv Val Typ. lets Typ' : Typ. inductions Typ; inverts Val; try solve [inverts H]...\nQed.\n\n\n(* ********************************************************************** *)\n(** * Properties of reductions *)\n\nLemma value_irred : forall v,\n    value v -> irred step v.\nProof with eauto.\n  introv V.\n  induction V; unfolds; try solve [introv C; inverts C]...\n\n  - Case \"value_pair\".\n    introv H.\n    inverts H as _ H.\n    lets : IHV1 H...\n    lets : IHV2 H...\n\n  - Case \"value_arr\".\n    introv H.\n    inverts H as H.\n    lets : IHV H...\n\n  - Case \"value_forall\".\n    introv H.\n    inverts H as H.\n    lets : IHV H...\n\n  - Case \"value_distArr\".\n    introv H.\n    inverts H as H.\n    lets : IHV H...\n\n  - Case \"value_topArr\".\n    introv H.\n    inverts H as H.\n    lets : IHV H...\n\n  - Case \"vaue_topAll\".\n    introv H.\n    inverts H as H.\n    lets : IHV H...\n\n  - Case \"value_distArr\".\n    introv H.\n    inverts H as H.\n    lets : IHV H...\n\nQed.\n\n\nLtac sweet :=\n  match goal with\n  | H : value ?t, H1 : step ?t ?e |- _ =>\n    forwards* :  (value_irred _ H e)\n  end.\n\n\nLemma step_unique: forall (t t1 t2 : exp),\n  step t t1 -> step t t2 -> t1 = t2.\nProof with eauto; try sweet.\n  introv Red1.\n  gen t2.\n  induction Red1; introv Red2.\n\n  - Case \"topArr\".\n    inverts Red2...\n    inverts H3.\n    inverts H4.\n    inverts H3.\n    inverts H1.\n\n  - Case \"topAll\".\n    inverts Red2...\n    inverts H4.\n    inverts H5.\n\n  - Case \"distArr\".\n    inverts Red2...\n    inverts H6...\n    inverts H7...\n\n  - Case \"distPoly\".\n    inverts Red2...\n    inverts H6...\n    inverts H7...\n\n  - Case \"id\".\n    inverts Red2...\n\n  - Case \"trans\".\n    inverts Red2...\n\n  - Case \"top\".\n    inverts Red2...\n\n  - Case \"arr\".\n    inverts Red2...\n    inverts H5...\n\n  - Case \"pair\".\n    inverts Red2...\n\n  - Case \"projl\".\n    inverts Red2...\n    inverts H4...\n\n  - Case \"projr\".\n    inverts Red2...\n    inverts H4...\n\n  - Case \"forall\".\n    inverts Red2...\n    inverts H5...\n\n  - Case \"beta\".\n    inverts Red2...\n    inverts H5...\n\n  - Case \"tbeta\".\n    inverts Red2...\n    inverts H5...\n\n  - Case \"app1\".\n    inverts Red2...\n    inverts Red1...\n    inverts H3...\n    inverts Red1...\n    inverts H6...\n    inverts Red1...\n    inverts Red1...\n    erewrite IHRed1...\n\n  - Case \"app2\".\n    inverts Red2...\n    inverts Red1...\n    erewrite IHRed1...\n\n  - Case \"pairl\".\n    inverts Red2...\n    erewrite IHRed1...\n\n  - Case \"pairr\".\n    inverts Red2...\n    erewrite IHRed1...\n\n  - Case \"tapp\".\n    inverts Red2...\n    inverts Red1...\n    inverts H4...\n    inverts Red1...\n    inverts H6...\n    inverts Red1...\n    inverts Red1...\n    erewrite IHRed1...\n\n  - Case \"pairr\".\n    inverts Red2...\n    inverts Red1...\n    inverts Red1...\n    erewrite IHRed1...\n\n\nQed.\n\n\nLemma value_no_step : forall v1 v2,\n    value v1 ->\n    v1 ->* v2 ->\n    v2 = v1.\nProof.\n  introv ? Red.\n  induction* Red.\n  lets : value_irred H.\n  pose (H1 b).\n  tryfalse.\nQed.\n\n\nLemma multi_red_capp : forall c t t',\n    t ->* t' -> (exp_capp c t) ->* (exp_capp c t').\nProof.\n  intros.\n  induction* H.\nQed.\n\nLemma multi_red_app1 : forall v1 t2 t2',\n    value v1 ->\n    t2 ->* t2' ->\n    (exp_app v1 t2) ->* (exp_app v1 t2').\nProof.\n  introv ? Red.\n  induction* Red.\nQed.\n\nLemma multi_red_app2 : forall t1 t2 t1',\n    lc_exp t2 ->\n    t1 ->* t1' ->\n    (exp_app t1 t2) ->* (exp_app t1' t2).\nProof.\n  introv ? Red.\n  induction* Red.\nQed.\n\n\nLemma multi_red_app : forall t1 t2 v1 v2,\n    value v1 -> lc_exp t2 ->\n    t1 ->* v1 -> t2 ->* v2 ->\n    (exp_app t1 t2) ->* (exp_app v1 v2).\nProof.\n  intros.\n  apply star_trans with (b := exp_app v1 t2).\n  sapply* multi_red_app2.\n  sapply* multi_red_app1.\nQed.\n\n\nLemma multi_red_pair1 : forall t1 t2 t1',\n    lc_exp t2 ->\n    t1 ->* t1' ->\n    (exp_pair t1 t2) ->* (exp_pair t1' t2).\nProof.\n  introv ? Red.\n  induction* Red.\nQed.\n\nLemma multi_red_pair2 : forall v1 t2 t2',\n    value v1 ->\n    t2 ->* t2' ->\n    (exp_pair v1 t2) ->* (exp_pair v1 t2').\nProof.\n  introv ? Red.\n  induction* Red.\nQed.\n\n\nLemma multi_red_pair : forall t1 t2 v1 v2,\n    value v1 -> lc_exp t2 ->\n    t1 ->* v1 -> t2 ->* v2 ->\n    (exp_pair t1 t2) ->* (exp_pair v1 v2).\nProof.\n  intros.\n  apply star_trans with (b := exp_pair v1 t2).\n  sapply* multi_red_pair1.\n  sapply* multi_red_pair2.\nQed.\n\nLemma multi_red_tapp : forall t t' T,\n    lc_ty T -> t ->* t' -> (exp_tapp t T) ->* (exp_tapp t' T).\nProof with eauto.\n  intros.\n  induction* H0.\nQed.\n\n\n\n(* ********************************************************************** *)\n(** * Properties of subtyping *)\n\nLemma sub_subst : forall Z E F C A B P c,\n  sub (F ++ Z ~ C ++ E) A B c ->\n  swft E P ->\n  uniq (map (subst_sty_in_sty P Z) F ++ E) ->\n  sub (map (subst_sty_in_sty P Z) F ++ E) (subst_sty_in_sty P Z A) (subst_sty_in_sty P Z B) c.\nProof with eauto using swft_subst_tb, swft_type.\n  introv WT WP.\n  remember (F ++ Z ~ C ++ E) as G.\n  generalize dependent F.\n  induction WT; intros F EQ Ok; subst; simpl subst_sty_in_sty...\n\n  (* Case 1 *)\n  pick fresh Y and apply S_forall...\n  repeat rewrite subst_sty_in_sty_open_sty_wrt_sty_var...\n  rewrite_env (map (subst_sty_in_sty P Z) (Y ~ A2 ++ F) ++ E).\n  apply H0...\n  simpls...\n\n  (* Case 2 *)\n  pick fresh Y and apply S_distPoly...\n  repeat rewrite subst_sty_in_sty_open_sty_wrt_sty_var...\n  rewrite_env (map (subst_sty_in_sty P Z) (Y ~ A ++ F) ++ E).\n  eapply swft_subst_tb; simpls...\n\n  repeat rewrite subst_sty_in_sty_open_sty_wrt_sty_var...\n  rewrite_env (map (subst_sty_in_sty P Z) (Y ~ A ++ F) ++ E).\n  eapply swft_subst_tb; simpls...\n\nQed.\n\nLemma sub_subst_push : forall Z E C A B P c,\n  sub (Z ~ C ++ E) A B c ->\n  swft E P ->\n  uniq E ->\n  sub E (subst_sty_in_sty P Z A) (subst_sty_in_sty P Z B) c.\nProof with auto.\n  introv SUB WFT UNI.\n  rewrite_env (nil ++ Z ~ C ++ E) in SUB.\n  forwards : sub_subst SUB WFT...\nQed.\n\nLemma sub_change : forall Δ Δ' A B c,\n    sub Δ A B c ->\n    same_stctx Δ Δ' ->\n    sub Δ' A B c.\nProof with eauto using swft_change.\n  introv Sub.\n  gen Δ'.\n  induction Sub; introv Eq...\n\n  eapply S_distPoly...\n\nQed.\n  \n\n\nLemma sub_andr : forall Δ A B C c,\n    sub Δ A (sty_and B C) c ->\n    exists c1 c2, sub Δ A B c1 /\\ sub Δ A C c2.\nProof.\n  introv SUB. inductions SUB.\n\n  inversions H.\n  eexists. eexists. splits~. \n\n  forwards ~ (c1' & c2' & [co1 co2]) : IHSUB1.\n  exists (co_trans c1' c2) (co_trans c2' c2).\n  splits*.\n\n\n\n  inverts H.\n  eexists. eexists. splits*.\n\n  eexists. eexists. splits*.\n\n  inversions H.\n  exists (co_trans co_proj1 co_proj1) (co_trans co_proj2 co_proj1).\n  splits*. \n\n  inversions H0.\n  exists (co_trans co_proj1 co_proj2) (co_trans co_proj2 co_proj2).\n  splits*. \nQed.\n\n\nLemma sub_weakening : forall G F E A B c,\n  sub (G ++ E) A B c ->\n  uniq (G ++ F ++ E) ->\n  sub (G ++ F ++ E) A B c.\nProof with eauto using swft_weaken.\n  introv Sub.\n  remember (G ++ E) as H.\n  generalize dependent G.\n  induction Sub; introv EQ Ok; subst...\n\n  pick fresh X and apply S_forall...\n  rewrite_env (([(X, A2)] ++ G) ++ F ++ E).\n  eapply H0...\n  solve_uniq.\n\n  pick fresh X and apply S_distPoly...\n  rewrite_env (([(X, A)] ++ G) ++ F ++ E).\n  eapply swft_weaken...\n  eapply H0...\n  solve_uniq.\n  rewrite_env (([(X, A)] ++ G) ++ F ++ E).\n  eapply swft_weaken...\n  eapply H1...\n  solve_uniq.\n\nQed.\n\n\n\nLemma topArr : forall Δ A,\n    swft Δ A ->\n    sub Δ A (sty_arrow sty_top sty_top) (co_trans co_topArr co_top).\nProof with eauto.\n  introv Wft.\n  eapply S_trans...\nQed.\n\n\nLemma rcdTop : forall Δ l A,\n    swft Δ A ->\n    sub Δ A (sty_rcd l sty_top) (co_trans co_id co_top).\nProof with eauto.\n  introv Wft.\n  eapply S_trans...\nQed.\n\n\n\nLemma same_mid : forall a (F E : list (atom * a)) X V U,\n    same_stctx (F ++ [(X, V)] ++ E) (F ++ [(X, U)] ++ E).\nProof with eauto using same_eq.\n  intros a F.\n  alist induction F; intros; simpls...\n  constructor...\n  constructor...\n\nQed.\n\n\nLemma swft_narrow : forall V F U T E X,\n  swft (F ++ X ~ V ++ E) T ->\n  swft (F ++ X ~ U ++ E) T.\nProof with eauto using same_mid.\n  intros.\n  eapply swft_change...\nQed.\n\n\nLemma sub_narrow : forall Q F E Z P S T c,\n  sub (F ++ Z ~ Q ++ E) S T c ->\n  sub (F ++ Z ~ P ++ E) S T c.\nProof with eauto using same_mid.\n  intros.\n  eapply sub_change...\nQed.\n\nLemma sub_renaming : forall X Y A D B B' c,\n    uniq ([(X, A)] ++ D) ->\n    sub ([(X, A)] ++ D) (open_sty_wrt_sty B (sty_var_f X)) (open_sty_wrt_sty B' (sty_var_f X)) c ->\n    X `notin` fv_sty_in_sty B ->\n    X `notin` fv_sty_in_sty B' ->\n    Y `notin` fv_sty_in_sty B ->\n    Y `notin` fv_sty_in_sty B' ->\n    Y `notin` dom D ->\n    sub ([(Y, A)] ++ D) (open_sty_wrt_sty B (sty_var_f Y)) (open_sty_wrt_sty B' (sty_var_f Y)) c.\nProof with eauto.\n  introv Uniq Sub ? ? ? ? ?.\n  destruct (X == Y); substs...\n\n  assert (Eq1 : (open_sty_wrt_sty B (sty_var_f Y)) = (subst_sty_in_sty (sty_var_f Y) X (open_sty_wrt_sty B (sty_var_f X)))).\n    rewrite (subst_sty_in_sty_intro X)...\n\n  assert (Eq2 : (open_sty_wrt_sty B' (sty_var_f Y)) = (subst_sty_in_sty (sty_var_f Y) X (open_sty_wrt_sty B' (sty_var_f X)))).\n    rewrite (subst_sty_in_sty_intro X)...\n\n\n  rewrite Eq1.\n  rewrite Eq2.\n\n  simpls.\n\n  eapply sub_subst_push...\n  simpl_env in *.\n  eapply sub_weakening...\n  solve_uniq.\nQed.\n\n\nLemma swfte_tvar_push: forall X A D,\n    swfte ([(X, A)] ++ D) ->\n    swfte D /\\ swft D A /\\ X `notin` fv_sty_in_sty A.\nProof with eauto.\n  introv WFTE.\n  splits...\n  inverts WFTE...\n  inverts WFTE...\n  eapply swfte_tvar...\n\nQed.\n\n\nLemma swfte_subst_tb : forall Q Z P E F,\n  swfte (F ++ Z ~ Q ++ E) ->\n  swft E P ->\n  swfte (map (subst_sty_in_sty P Z) F ++ E).\nProof with eauto.\n  introv Wfte.\n  alist induction F; introv Wft; simpls...\n\n  lets (? & ? & ?) : swfte_tvar_push Wfte...\n\n  lets (? & ? & ?) : swfte_tvar_push Wfte...\n\n  constructor...\n  simpl_env in *.\n  eapply swft_subst_tb...\n  lets : uniq_from_swfte H...\n\n  lets Imp: uniq_from_swfte Wfte.\n  inverts Imp...\nQed.\n\n\nLemma swfte_strength: forall E G,\n    swfte (E ++ G) ->\n    swfte G.\nProof with eauto.\n  intros E.\n  alist induction E; introv Wfte; simpls...\n  eapply IHE...\n  rewrite_env ((map (subst_sty_in_sty sty_top x)) nil ++ (E ++ G)).\n  eapply swfte_subst_tb...\n  simpl_env in *...\nQed.\n\n\n\n\n\n(* ********************************************************************** *)\n(** * Misc *)\n\n\nLemma ftv_in_dom : forall Δ T,\n    wft Δ T ->\n    fv_ty_in_ty T [<=] dom Δ.\nProof.\n  introv H.\n  induction H; simpl; try fsetdec.\n\n  apply binds_In in H.\n  fsetdec.\n\n  pick fresh X.\n  assert (Fx : fv_ty_in_ty (open_ty_wrt_ty T2 (ty_var_f X)) [<=] dom ([(X,tt)] ++ dd)) by auto.\n  simpl in Fx.\n  assert (Fy : fv_ty_in_ty T2 [<=] fv_ty_in_ty (open_ty_wrt_ty T2 (ty_var_f X))).\n  eapply fv_ty_in_ty_open_ty_wrt_ty_lower.\n  fsetdec.\nQed.\n\nLemma fv_in_dom : forall Δ G e T,\n    typ Δ G e T ->\n    fv_exp_in_exp e [<=] dom G /\\\n    fv_ty_in_exp e [<=] dom Δ.\nProof.\n  introv H.\n  induction H; simpl; splits; try fsetdec.\n\n  - Case \"var\".\n    apply binds_In in H0.\n    fsetdec.\n\n  - Case \"abs: var\".\n    pick fresh x.\n    forwards~ (? & ?): H0 x.\n    assert (Fx : fv_exp_in_exp (open_exp_wrt_exp e (exp_var_f x)) [<=] dom ([(x,T1)] ++ gg)) by auto.\n    simpl in Fx.\n    assert (Fy : fv_exp_in_exp e [<=] fv_exp_in_exp (open_exp_wrt_exp e (exp_var_f x))).\n    eapply fv_exp_in_exp_open_exp_wrt_exp_lower.\n    fsetdec.\n\n  - Case \"abs: tvar\".\n    pick fresh x.\n    forwards~ (? & ?): H0 x.\n    assert (Fy : fv_ty_in_exp e [<=] fv_ty_in_exp (open_exp_wrt_exp e (exp_var_f x))).\n    eapply fv_ty_in_exp_open_exp_wrt_exp_lower.\n    fsetdec.\n\n  - Case \"tabs: var\".\n    pick fresh X.\n    forwards~ (? & ?): H0 X.\n    assert (Fy : fv_exp_in_exp e [<=] fv_exp_in_exp (open_exp_wrt_ty e (ty_var_f X))).\n    eapply fv_exp_in_exp_open_exp_wrt_ty_lower.\n    fsetdec.\n\n  - Case \"tabs: tvar\".\n    pick fresh X.\n    forwards~ (? & ?): H0 X.\n    assert (Fy : fv_ty_in_exp e [<=] fv_ty_in_exp (open_exp_wrt_ty e (ty_var_f X))).\n    eapply fv_ty_in_exp_open_exp_wrt_ty_lower.\n    fsetdec.\n\n  - Case \"tapp\".\n    lets: ftv_in_dom H0.\n    inverts IHtyp.\n    fsetdec.\nQed.\n\n\nLemma closed_no_var : forall v T,\n    typ nil nil v T ->\n    fv_ty_in_exp v [=] {} /\\ fv_exp_in_exp v [=] {}.\nProof.\n  introv Typ.\n  forwards (? & ?) : fv_in_dom Typ.\n  splits; fsetdec.\nQed.\n\nDefinition exp_relation := exp -> exp -> Prop.\n\nDefinition getR (p : list (atom * (sty * sty * exp_relation))) : list (atom * exp_relation) :=\n  map (fun t => match t with | (a, b, R) => R end) p.\n\nDefinition getOne (p : list (atom * (sty * sty * exp_relation))) : list (atom * sty) :=\n  map (fun t => match t with | (a, b, R) => a end) p.\n\nDefinition getTwo (p : list (atom * (sty * sty * exp_relation))) : list (atom * sty) :=\n  map (fun t => match t with | (a, b, R) => b end) p.\n\nDefinition mtsubst_in_sty (s : list (atom * sty)) (ty : sty) : sty :=\n  fold_left (fun acc p => subst_sty_in_sty (snd p) (fst p) acc) s ty.\n\nDefinition mtsubst_in_exp (s : list (atom * sty)) (e : exp) : exp :=\n  fold_left (fun acc p => subst_ty_in_exp (| snd p |) (fst p)  acc) s e.\n\nDefinition msubst_in_exp (s : list (atom * exp)) (t : exp) : exp :=\n  fold_left (fun acc p => subst_exp_in_exp (snd p) (fst p) acc) s t.\n\n\nLemma mtsubst_arr : forall s A1 A2,\n    mtsubst_in_sty s (sty_arrow A1 A2) = sty_arrow (mtsubst_in_sty s A1) (mtsubst_in_sty s A2).\nProof with eauto.\n  intros s.\n  induction s; intros; simpls...\nQed.\n\n\nLemma mtsubst_forall : forall s A1 A2,\n    mtsubst_in_sty s (sty_all A1 A2) = sty_all (mtsubst_in_sty s A1) (mtsubst_in_sty s A2).\nProof with eauto.\n  intros s.\n  induction s; intros; simpls...\nQed.\n\nLemma mtsubst_and : forall s A1 A2,\n    mtsubst_in_sty s (sty_and A1 A2) = sty_and (mtsubst_in_sty s A1) (mtsubst_in_sty s A2).\nProof with eauto.\n  intros s.\n  induction s; intros; simpls...\nQed.\n\n\nLemma mtsubst_nat : forall s,\n    mtsubst_in_sty s sty_nat = sty_nat.\nProof with eauto.\n  intros s.\n  induction s; intros; simpls...\nQed.\n\n\nLemma mtsubst_top : forall s,\n    mtsubst_in_sty s sty_top = sty_top.\nProof with eauto.\n  intros s.\n  induction s; intros; simpls...\nQed.\n\nLemma mtsubst_bot : forall s,\n    mtsubst_in_sty s sty_bot = sty_bot.\nProof with eauto.\n  intros s.\n  induction s; intros; simpls...\nQed.\n\n\nLemma mtsubst_rcd : forall s l A,\n    mtsubst_in_sty s (sty_rcd l A) = sty_rcd l (mtsubst_in_sty s A).\nProof with eauto.\n  intros s.\n  induction s; intros; simpls...\nQed.\n\n\nLemma mtsubst_unit : forall s,\n    mtsubst_in_exp s exp_unit = exp_unit.\nProof.\n  intros s.\n  induction s; intros; simpls; eauto.\nQed.\n\nLemma mtsubst_lit : forall s i,\n    mtsubst_in_exp s (exp_lit i) = exp_lit i.\nProof.\n  intros s.\n  induction s; intros; simpls; eauto.\nQed.\n\n\nLemma mtsubst_tabs : forall s e,\n    mtsubst_in_exp s (exp_tabs e)  = exp_tabs (mtsubst_in_exp s e).\nProof.\n  intros s.\n  induction s; intros; simpls; eauto.\nQed.\n\n\n\nLemma mtsubst_capp : forall s c e,\n    mtsubst_in_exp s (exp_capp c e) = exp_capp c (mtsubst_in_exp s e).\nProof.\n  intros s.\n  induction s; intros; simpls; eauto.\nQed.\n\n\nLemma msubst_unit : forall s,\n    msubst_in_exp s exp_unit = exp_unit.\nProof.\n  intros s.\n  induction s; intros; simpls; eauto.\nQed.\n\nLemma msubst_lit : forall s i,\n    msubst_in_exp s (exp_lit i) = exp_lit i.\nProof.\n  intros s.\n  induction s; intros; simpls; eauto.\nQed.\n\n\nLemma msubst_capp : forall s c e,\n    msubst_in_exp s (exp_capp c e) = exp_capp c (msubst_in_exp s e).\nProof.\n  intros s.\n  induction s; intros; simpls; eauto.\nQed.\n\n\nLemma mtsubst_pair : forall s e1 e2,\n    mtsubst_in_exp s (exp_pair e1 e2) = exp_pair (mtsubst_in_exp s e1) (mtsubst_in_exp s e2).\nProof.\n  intros s.\n  induction s; intros; simpls; eauto.\nQed.\n\nLemma msubst_pair : forall s e1 e2,\n    msubst_in_exp s (exp_pair e1 e2) = exp_pair (msubst_in_exp s e1) (msubst_in_exp s e2).\nProof.\n  intros s.\n  induction s; intros; simpls; eauto.\nQed.\n\n\nLemma mtsubst_tapp : forall s e A,\n    mtsubst_in_exp s (exp_tapp e (| A |)) = exp_tapp (mtsubst_in_exp s e) (|mtsubst_in_sty s A|).\nProof with eauto.\n  intros s.\n  alist induction s; intros; simpls...\n\n  rewrite <- trans_subst_sty.\n  rewrite IHs...\n\nQed.\n\n\nLemma msubst_tapp : forall s e T,\n    msubst_in_exp s (exp_tapp e T) = exp_tapp (msubst_in_exp s e) T.\nProof with eauto.\n  induction s; intros; simpls; eauto.\nQed.\n\n\nLemma mtsubst_app : forall s e e',\n    mtsubst_in_exp s (exp_app e e') = exp_app (mtsubst_in_exp s e) (mtsubst_in_exp s e') .\nProof with eauto.\n  intros s.\n  alist induction s; intros; simpls...\nQed.\n\n\nLemma msubst_app : forall s e e',\n    msubst_in_exp s (exp_app e e') = exp_app (msubst_in_exp s e) (msubst_in_exp s e').\nProof with eauto.\n  induction s; intros; simpls; eauto.\nQed.\n\n\nLemma mtsubst_abs : forall s e,\n    mtsubst_in_exp s (exp_abs e) = exp_abs (mtsubst_in_exp s e).\nProof with eauto.\n  intros s.\n  alist induction s; intros; simpls...\nQed.\n\n\nLemma msubst_abs : forall s e,\n    msubst_in_exp s (exp_abs e) = exp_abs (msubst_in_exp s e).\nProof with eauto.\n  induction s; intros; simpls; eauto.\nQed.\n\n\nLemma msubst_tabs : forall s e,\n    msubst_in_exp s (exp_tabs e) = exp_tabs (msubst_in_exp s e).\nProof with eauto.\n  induction s; intros; simpls; eauto.\nQed.\n\n\n\nInductive all_value : list (atom * exp) -> Prop :=\n| all_empty : all_value nil\n| all_cons : forall x v T g,\n    value v ->\n    typ nil nil v T ->\n    all_value g ->\n    all_value ([(x , v)] ++ g).\n\nHint Constructors all_value.\n\n\nLemma msubst_ty_open_wrt_ty : forall s e T,\n    all_value s ->\n    msubst_in_exp s (open_exp_wrt_ty e T) =\n    open_exp_wrt_ty (msubst_in_exp s e) T.\nProof with eauto.\n  intros s.\n  alist induction s; intros; simpls...\n  inverts H.\n  rewrite <- IHs...\n  rewrite subst_exp_in_exp_open_exp_wrt_ty...\nQed.\n\n\nLemma msubst_open : forall g t a,\n    all_value g ->\n    msubst_in_exp g (open_exp_wrt_exp t a) = open_exp_wrt_exp (msubst_in_exp g t) (msubst_in_exp g a).\nProof with eauto.\n  intro g.\n  alist induction g; intros; simpls...\n  inverts H.\n  rewrite subst_exp_in_exp_open_exp_wrt_exp...\nQed.\n\n\nLemma msubst_fresh : forall g e,\n    fv_exp_in_exp e [=] {} ->\n    msubst_in_exp g e = e.\nProof.\n  intros.\n  alist induction g.\n  reflexivity.\n  simpl.\n  rewrite~ subst_exp_in_exp_fresh_eq.\n  fsetdec.\nQed.\n\n\nLemma mtsubst_exp_fresh : forall s e,\n    fv_ty_in_exp e [=] {} ->\n    mtsubst_in_exp s e = e.\nProof.\n  intros.\n  alist induction s.\n  reflexivity.\n  simpl.\n  rewrite~ subst_ty_in_exp_fresh_eq.\n  fsetdec.\nQed.\n\n\n\n(* ********************************************************************** *)\n(** * Logical interpretation of type contexts *)\n\nInductive rel_d : stctx -> sctx -> Prop :=\n| rel_d_empty : rel_d nil nil\n| rel_d_cons : forall X Δ t B p,\n    X `notin` dom Δ ->\n    rel_d Δ p ->\n    swft nil t ->\n    mono t ->\n    disjoint nil t (mtsubst_in_sty p B) ->\n    rel_d ([(X, B)] ++ Δ) ([(X, t)] ++ p).\n\nHint Constructors rel_d.\n\n\nLemma rel_d_same : forall Δ p,\n    rel_d Δ p -> same_stctx Δ p.\nProof with simpl_env; eauto.\n  induction 1; simpls...\nQed.\n\n\n\nLemma rel_d_notin : forall Δ p X,\n    rel_d Δ p ->\n    X `notin` dom Δ ->\n    X `notin` dom p.\nProof with eauto.\n  introv RelD.\n  induction RelD; simpls...\nQed.\n\nLemma rel_d_uniq : forall Δ p,\n    rel_d Δ p ->\n    uniq Δ /\\ uniq p.\nProof with eauto using rel_d_notin.\n  introv RelD.\n  induction RelD; simpls...\n  splits...\n  solve_uniq.\n  destruct IHRelD...\nQed.\n\n\nLemma mtsubst_open : forall Δ p A1 A2,\n    rel_d Δ p ->\n    mtsubst_in_sty p (open_sty_wrt_sty A1 A2) =\n    open_sty_wrt_sty (mtsubst_in_sty p A1) (mtsubst_in_sty p A2).\nProof with eauto using swft_type.\n  introv RelD.\n  gen A1 A2.\n  induction RelD; intros; simpls...\n  rewrite subst_sty_in_sty_open_sty_wrt_sty...\nQed.\n\n\nLemma mtsubst_ty_open : forall Δ p e A,\n    rel_d Δ p ->\n    mtsubst_in_exp p (open_exp_wrt_ty e (|A|)) =\n    open_exp_wrt_ty (mtsubst_in_exp p e) (|mtsubst_in_sty p A|).\nProof with eauto using swft_type, lc_sty_ty.\n  introv RelD.\n  gen A e.\n  induction RelD; intros; simpls...\n  rewrite <- IHRelD...\n  rewrite subst_ty_in_exp_open_exp_wrt_ty...\n  rewrite trans_subst_sty...\nQed.\n\n\nLemma mtsubst_exp_open : forall s e1 e2,\n    mtsubst_in_exp s (open_exp_wrt_exp e1 e2) =\n    open_exp_wrt_exp (mtsubst_in_exp s e1) (mtsubst_in_exp s e2).\nProof with eauto.\n  intros s.\n  alist induction s; intros; simpls...\n  rewrite subst_ty_in_exp_open_exp_wrt_exp...\nQed.\n\n\nLemma mtsubst_fresh : forall s C,\n    fv_sty_in_sty C [=] {} ->\n    mtsubst_in_sty s C = C.\nProof.\n  intros.\n  alist induction s.\n  reflexivity.\n  simpl.\n  rewrite~ subst_sty_in_sty_fresh_eq.\n  fsetdec.\nQed.\n\nLemma mtsubst_in_exp_subst : forall s v x t,\n    fv_ty_in_exp v [=] {} ->\n    subst_exp_in_exp v x (mtsubst_in_exp s t) = mtsubst_in_exp s (subst_exp_in_exp v x t).\nProof with eauto.\n  intros s.\n  alist induction s; intros; simpls...\n\n  rewrite IHs...\n  rewrite subst_exp_in_exp_subst_ty_in_exp...\n  fsetdec.\nQed.\n\n\nLemma mtsubst_var_notin : forall p x,\n    x `notin` dom p ->\n    mtsubst_in_exp p (exp_var_f x) = (exp_var_f x).\nProof with auto.\n  intros p.\n  alist induction p; intros; simpls...\nQed.\n\n\nLemma mtsubst_notin: forall X Δ p B,\n    rel_d Δ p ->\n    X `notin` dom p ->\n    X `notin` (fv_sty_in_sty B) ->\n    X `notin` fv_sty_in_sty (mtsubst_in_sty p B).\nProof with eauto.\n  introv Wf.\n  gen B.\n  induction Wf; introv ? ?; simpls...\n  eapply IHWf...\n  eapply fv_sty_in_sty_subst_sty_in_sty_notin...\n  eapply swft_tvar...\nQed.\n\nLemma mtsubst_swft : forall Δ A s,\n    rel_d Δ s ->\n    swft Δ A ->\n    swft nil (mtsubst_in_sty s A).\nProof with eauto.\n  introv H.\n  gen A.\n  induction H; introv WF; simpls...\n\n  eapply IHrel_d...\n\n  lets (? & ?) : rel_d_uniq...\n  rewrite_env (map (subst_sty_in_sty t X) nil ++ Δ).\n  eapply swft_subst_tb...\n  exact WF.\n  rewrite_env (Δ ++ nil).\n  eapply swft_weaken_head...\nQed.\n\n(* Lemma mtsubst_tvar: forall s Δ X (A : sty), *)\n(*     rel_d Δ s -> *)\n(*     binds X A Δ -> *)\n(*     swft nil (mtsubst_in_sty s (sty_var_f X)). *)\n(* Proof with eauto. *)\n(*   introv H. *)\n(*   gen X A. *)\n(*   induction H; introv Bind; simpls... *)\n\n(*   case_if... *)\n(*   substs. *)\n(*   inverts WF. *)\n(*   inverts Uniq. *)\n(*   eapply mtsubst_swft... *)\n(*   rewrite_env (s1 ++ nil). *)\n(*   eapply swft_weaken_head... *)\n(*   inverts WF. *)\n(*   inverts Uniq. *)\n(*   analyze_binds Bind. *)\n(*   eapply IHsame_stctx... *)\n(* Qed. *)\n\nLemma mtsubst_nil : forall Γ,\n    map (mtsubst_in_sty nil) Γ = Γ.\nProof with eauto.\n  intros.\n  alist induction Γ; simpls...\n  rewrite IHΓ...\nQed.\n\n\nLemma mtsubst_cons : forall Γ X B s,\n    map (mtsubst_in_sty ([(X, B)] ++ s)) Γ = map (mtsubst_in_sty s) (map (subst_sty_in_sty B X) Γ).\nProof with eauto.\n  intros Γ.\n  alist induction Γ; intros; simpls...\n  rewrite IHΓ...\nQed.\n\n\nLemma mtsubst_trans : forall Γ B X,\n    ∥ map (subst_sty_in_sty B X) Γ ∥ = map (subst_ty_in_ty (| B |) X) (∥ Γ ∥).\nProof with eauto.\n  intros Γ.\n  alist induction Γ; intros; simpls...\n  rewrite IHΓ...\n  rewrite trans_subst_sty...\nQed.\n\n\n\nLemma mtsubst_typ : forall (Δ : stctx) Γ s t A,\n    rel_d Δ s ->\n    typ (map (const tt) Δ) (∥ Γ ∥) t (| A |) ->\n    typ nil (∥ map (mtsubst_in_sty s) Γ ∥) (mtsubst_in_exp s t) (| mtsubst_in_sty s A |).\nProof with eauto using swft_wft.\n   introv H.\n   gen Γ t A.\n  induction H; introv Typ.\n\n  - Case \"empty\".\n    simpls.\n    rewrite mtsubst_nil...\n\n  - Case \"cons\".\n    simpls.\n\n    lets (? & ?) : rel_d_uniq...\n    simpl_env.\n\n    rewrite mtsubst_cons...\n    eapply IHrel_d...\n    rewrite trans_subst_sty.\n    rewrite mtsubst_trans...\n    rewrite_env (nil ++ map (const tt) Δ).\n    eapply typing_through_subst_typ_in_exp...\n\n    rewrite_env (map (const tt) Δ ++ nil).\n    eapply wft_weaken_head...\n    apply swft_wft_nil...\n Qed.\n\n\nLemma mtsubst_sub : forall A B Δ c s,\n    rel_d Δ s ->\n    sub Δ A B c ->\n    sub nil (mtsubst_in_sty s A) (mtsubst_in_sty s B) c.\nProof with eauto.\n  introv Eq.\n  gen A B c.\n  induction Eq; introv Sub; simpls...\n  lets (? & ?) : rel_d_uniq...\n  apply IHEq...\n  rewrite_env (map (subst_sty_in_sty t X) nil ++ Δ).\n  eapply sub_subst; simpls...\n  rewrite_env (nil ++ Δ ++ nil).\n  eapply swft_weaken; simpls...\nQed.\n\n\nLemma mtsubst_mono : forall Δ p t,\n    rel_d Δ p ->\n    mono t ->\n    mono (mtsubst_in_sty p t).\nProof with eauto.\n  introv WF.\n  gen t.\n  induction WF; introv Mono; simpls...\n  apply IHWF...\n  apply subst_mono...\nQed.\n\n\n\nLemma swft_subst_ctx: forall Δ2 Δ1 A p,\n   swft (Δ1 ++ Δ2) A ->\n   swfte (Δ1 ++ Δ2) ->\n   rel_d Δ2 p ->\n   swft (map (mtsubst_in_sty p) Δ1) (mtsubst_in_sty p A).\nProof with eauto.\n  intros Δ2.\n  induction Δ2; introv Wft Wfte RelD; simpls...\n  inverts RelD.\n  simpls...\n  rewrite mtsubst_nil...\n  simpl_env in Wft...\n\n  inverts RelD as ? RelD.\n  lets (? & ?) : rel_d_uniq RelD.\n  assert (swft Δ2 t).\n  rewrite_env (Δ2 ++ nil).\n  eapply swft_weaken_head...\n\n  rewrite mtsubst_cons.\n  simpls.\n  eapply IHΔ2...\n  eapply swft_subst_tb...\n  exact Wft.\n\n  lets : uniq_from_swfte Wfte.\n  solve_uniq.\n  eapply swfte_subst_tb...\n  exact Wfte.\nQed.\n\n\nLemma sub_subst_ctx: forall Δ2 Δ1 p A B c,\n   sub (Δ1 ++ Δ2) A B c->\n   swfte (Δ1 ++ Δ2) ->\n   rel_d Δ2 p ->\n   sub (map (mtsubst_in_sty p) Δ1) (mtsubst_in_sty p A) (mtsubst_in_sty p B) c.\nProof with eauto.\n  intros Δ2.\n  induction Δ2; introv Sub Wfte RelD.\n  inverts RelD.\n  rewrite mtsubst_nil...\n  simpls...\n  simpl_env in Sub...\n\n  inverts RelD as ? RelD.\n  lets (? & ?) : rel_d_uniq RelD.\n  assert (swft Δ2 t).\n  rewrite_env (Δ2 ++ nil).\n  eapply swft_weaken_head...\n\n  rewrite mtsubst_cons...\n  simpls...\n  eapply IHΔ2...\n  eapply sub_subst...\n  exact Sub.\n\n  lets : uniq_from_swfte Wfte.\n  solve_uniq.\n  eapply swfte_subst_tb...\n  exact Wfte.\n\nQed.\n\n\nLemma swfte_subst_ctx: forall Δ2 Δ1 p,\n   swfte (Δ1 ++ Δ2) ->\n   rel_d Δ2 p ->\n   swfte (map (mtsubst_in_sty p) Δ1).\nProof with eauto.\n  intros Δ2.\n  induction Δ2; introv Wfte RelD.\n  inverts RelD.\n  rewrite mtsubst_nil...\n  simpl_env in Wfte...\n\n  inverts RelD as ? RelD.\n  lets (? & ?) : rel_d_uniq RelD.\n\n  rewrite mtsubst_cons...\n  eapply IHΔ2...\n  eapply swfte_subst_tb...\n  exact Wfte.\n  rewrite_env (Δ2 ++ nil).\n  eapply swft_weaken_head...\n\nQed.\n\n\n\nLemma mtsubst_tvar_notin : forall p X,\n    X `notin` dom p ->\n    mtsubst_in_sty p (sty_var_f X) = (sty_var_f X).\nProof with auto.\n  intros p.\n  alist induction p; intros; simpls...\n  case_if...\n  substs...\n  false H.\n  solve_notin.\nQed.\n\n\n\n(* ********************************************************************** *)\n(** ** Renaming lemmas . *)\n\nLemma swft_renaming : forall X Y A D B,\n    uniq ([(X, A)] ++ D) ->\n    swft ([(X, A)] ++ D) (open_sty_wrt_sty B (sty_var_f X)) ->\n    X `notin` fv_sty_in_sty B ->\n    Y `notin` fv_sty_in_sty B ->\n    Y `notin` dom D ->\n    swft ([(Y, A)] ++ D) (open_sty_wrt_sty B (sty_var_f Y)).\nProof with eauto.\n  introv Uniq Wft Frx Fry Fry'.\n  destruct (X == Y); substs...\n  rewrite (subst_sty_in_sty_intro X)...\n  rewrite_env ((map (subst_sty_in_sty (sty_var_f Y) X) nil) ++ [(Y, A)] ++ D).\n  apply swft_subst_tb with (B := A); simpls...\n  simpl_env.\n  eapply swft_weaken...\n  solve_uniq.\nQed.\n\n\nLemma typing_tvar_rename : forall X Γ Y G e T,\n    typ ([(X, tt)] ++ G) Γ (open_exp_wrt_ty e (ty_var_f X)) (open_ty_wrt_ty T (ty_var_f X)) ->\n    wfe G Γ ->\n    X `notin` dom G ->\n    X `notin` dom Γ ->\n    X `notin` fv_ty_in_ty T ->\n    X `notin` fv_ty_in_exp e ->\n    Y `notin` dom G ->\n    Y `notin` dom Γ ->\n    Y `notin` fv_ty_in_ty T ->\n    Y `notin` fv_ty_in_exp e ->\n    typ ([(Y, tt)] ++ G) Γ (open_exp_wrt_ty e (ty_var_f Y)) (open_ty_wrt_ty T (ty_var_f Y)).\nProof with eauto.\n  introv TypX ? ? ? ? ? ? ? ? ?.\n  destruct (X == Y); substs...\n\n  assert (Wfe : wfe ([(X, tt)] ++ G) Γ)...\n  assert (Uniq : uniq ([(X, tt)] ++ G))...\n  inverts Uniq.\n\n  rewrite (subst_ty_in_exp_intro X)...\n  rewrite (subst_ty_in_ty_intro X)...\n  rewrite_env (nil ++ [(Y, tt)] ++ G).\n  replace Γ with (map (subst_ty_in_ty (ty_var_f Y) X) Γ).\n  apply typing_through_subst_typ_in_exp...\n  rewrite_env ([(X , tt)] ++ [(Y, tt)] ++ G).\n  eapply typing_tvar_weakening...\n  rewrite map_subst_typ_in_binding_id with (Z := X) (P := ty_var_f Y) (D := G)...\nQed.\n\n\n\nLemma typing_rename : forall x y E t U T G,\n    typ G ([(x, U)] ++ E) (open_exp_wrt_exp t (exp_var_f x)) T ->\n    x `notin` dom G \\u dom E \\u fv_exp_in_exp t ->\n    y `notin` dom G \\u dom E \\u fv_exp_in_exp t ->\n    typ G ([(y, U)] ++ E) (open_exp_wrt_exp t (exp_var_f y)) T.\nProof with eauto.\n  introv TyX ? ?.\n  destruct (x == y); substs...\n\n  assert (Wfe : wfe G ([(x, U)] ++ E))...\n  inverts Wfe.\n\n  rewrite (subst_exp_in_exp_intro x)...\n  rewrite_env (nil ++ [(y, U)] ++ E).\n  apply typing_through_subst_exp_in_exp with (U := U)...\n  rewrite_env ([(x, U)] ++ [(y, U)] ++ E).\n  eapply typing_var_weakening...\nQed.\n\n\n\n(* ********************************************************************** *)\n(** * Enhance auto *)\n\n\n\nHint Rewrite mtsubst_ty_open msubst_ty_open_wrt_ty mtsubst_nat mtsubst_top mtsubst_arr mtsubst_forall mtsubst_and mtsubst_rcd mtsubst_open mtsubst_tabs mtsubst_abs msubst_tabs msubst_abs mtsubst_app msubst_unit msubst_lit msubst_app  mtsubst_tapp msubst_tapp mtsubst_pair msubst_pair mtsubst_lit mtsubst_unit mtsubst_capp msubst_capp trans_open_sty trans_subst_sty : lr_rewrite.\n\n\nHint Resolve mono_lc poly_lc swft_wft swft_wft_nil swft_type lc_sty_ty fv_sty_nil multi_red_tapp multi_red_capp multi_red_pair multi_red_app1 same_eq same_sym star_one star_trans swft_change swft_from_swfte swft_from_swfe mtsubst_swft swft_subst_ctx.\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/Infrastructure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.28627694696671824}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import sqrt1.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nRequire Import float_lemmas sqrt1_f.\n\nDefinition sqrt_newton_spec :=\n   DECLARE _sqrt_newton\n   WITH x: float32\n   PRE [ tfloat ]\n       PROP () PARAMS (Vsingle x) SEP ()\n    POST [ tfloat ]\n       PROP () RETURN (Vsingle (fsqrt x)) SEP ().\n\nDefinition Gprog : funspecs :=\n         [sqrt_newton_spec].\n\nLemma body_sqrt_newton:  semax_body Vprog Gprog f_sqrt_newton sqrt_newton_spec.\nProof.\nstart_function.\nforward_if. (* if (x<=0) *)\nforward.  (*  return 0; *) {\n   entailer!.\n   unfold fsqrt.\n   change (float_of_Z ?A) with (Float32.of_int (Int.repr A)).\n   change float_cmp with Float32.cmp.\n   rewrite H. auto.\n}\npose (t := if Float32.cmp Cge x (Float32.of_int (Int.repr 1))\n                    then x else Float32.of_int (Int.repr 1)).\nforward_if  (* if (x >= 1) *) \n     (temp _t'1 (Vsingle t)).\nforward. (* t'1=x; *) {\n  entailer!.\n  subst t; rewrite H0; auto.\n}\nforward. (* t'1=1; *) {\n  entailer!.\n  subst t; rewrite H0; auto.\n}\nforward. (* y = t'1; *)\nforward_loop\n   (EX y:float32, PROP(main_loop (x,y) = fsqrt x)\n                 (LOCAL (temp _x (Vsingle x); temp _y (Vsingle y)) SEP()))\n continue: (EX y z:float32, PROP((if Float32.cmp Clt y z\n                                then main_loop  (x,y) else y) = fsqrt x)\n                     (LOCAL (temp _x (Vsingle x); temp _y (Vsingle y); \n                                  temp _z (Vsingle z)) \n                     SEP()))\n   break: (PROP()(LOCAL (temp _y (Vsingle (fsqrt x))) SEP())).\n-  (* Prove that precondition implies loop invariant *)\nExists t.\nentailer!.\nunfold fsqrt.\nchange (float_of_Z ?A) with (Float32.of_int (Int.repr A)).\nchange float_cmp with Float32.cmp.\nrewrite H.\nfold t. auto.\n-  (* body of loop *)\nIntros y.\nforward. (* z=y; *)\nforward. (* y=(z+x/z)/2; *)\n    (* end of loop body; prove invariant is reestablished *)\ndo 2 EExists; entailer!.\nrewrite main_loop_equation in H0.\nauto.\n-  (* ... while (y<z);  *)\nIntros y z.\nforward_if.  (* if (y<z) *)\n+\nforward.  (* skip; *)\nExists y.\nentailer!.\nrewrite H1 in H0.\nauto.\n+\nforward.  (* break; *)\nentailer!.\nrewrite H1 in H0.\nf_equal; auto.\n-\nforward. (* return y; *)\nQed.\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/sqrt/verif_sqrt1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.28626078695282536}}
{"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 atoms2.\nRequire Export computation_seq.\nRequire Export continuity_defs.\n\nUnset Regular Subst Tactic.\n\nInductive differ3 {o} (b : nat) (f g : NTerm)\n: @NTerm o -> @NTerm o -> Type :=\n| differ3_force_int :\n    forall t1 t2 v fa ga,\n      !LIn v (free_vars f)\n      -> !LIn v (free_vars g)\n      -> differ3 b f g t1 t2\n      -> alpha_eq f fa\n      -> alpha_eq g ga\n      -> differ3\n           b f g\n           (force_int_bound_app v b t1 fa (mk_vbot v))\n           (force_int_bound_app v b t2 ga (mk_vbot v))\n| differ3_var :\n    forall v, differ3 b f g (mk_var v) (mk_var v)\n| differ3_sterm :\n    forall s, differ3 b f g (sterm s) (sterm s)\n| differ3_oterm :\n    forall op bs1 bs2,\n      length bs1 = length bs2\n      -> (forall b1 b2, LIn (b1,b2) (combine bs1 bs2) -> differ3_b b f g b1 b2)\n      -> differ3 b f g (oterm op bs1) (oterm op bs2)\nwith differ3_b {o} (b : nat) (f g : NTerm)\n     : @BTerm o -> @BTerm o -> Type :=\n     | differ3_bterm :\n         forall vs t1 t2,\n           disjoint vs (free_vars f)\n           -> disjoint vs (free_vars g)\n           -> differ3 b f g t1 t2\n           -> differ3_b b f g (bterm vs t1) (bterm vs t2).\nHint Constructors differ3 differ3_b.\n\nDefinition differ3_alpha {o} b f g (t1 t2 : @NTerm o) :=\n  {u1 : NTerm\n   & {u2 : NTerm\n      & alpha_eq t1 u1\n      # alpha_eq t2 u2\n      # differ3 b f g u1 u2}}.\n\nDefinition differ3_implies_differ3_alpha {o} :\n  forall b f g (t1 t2 : @NTerm o),\n    differ3 b f g t1 t2 -> differ3_alpha b f g t1 t2.\nProof.\n  introv d.\n  exists t1 t2; auto.\nQed.\nHint Resolve differ3_implies_differ3_alpha : slow.\n\nInductive differ3_subs {o} b f g : @Sub o -> @Sub o -> Type :=\n| dsub3_nil : differ3_subs b f g [] []\n| dsub3_cons :\n    forall v t1 t2 sub1 sub2,\n      differ3 b f g t1 t2\n      -> differ3_subs b f g sub1 sub2\n      -> differ3_subs b f g ((v,t1) :: sub1) ((v,t2) :: sub2).\nHint Constructors differ3_subs.\n\nDefinition differ3_bterms {o} b f g (bs1 bs2 : list (@BTerm o)) :=\n  br_bterms (differ3_b b f g) bs1 bs2.\n\nLemma differ3_subs_sub_find_some {o} :\n  forall b f g (sub1 sub2 : @Sub o) v t,\n    differ3_subs b f g sub1 sub2\n    -> sub_find sub1 v = Some t\n    -> {u : NTerm & sub_find sub2 v = Some u # differ3 b f g t u}.\nProof.\n  induction sub1; destruct sub2; introv d fs; allsimpl; tcsp;\n  inversion d; subst.\n  boolvar; cpx.\n  eexists; eauto.\nQed.\n\nLemma differ3_subs_sub_find_none {o} :\n  forall b f g (sub1 sub2 : @Sub o) v,\n    differ3_subs b f g sub1 sub2\n    -> sub_find sub1 v = None\n    -> sub_find sub2 v = None.\nProof.\n  induction sub1; destruct sub2; introv d fn; allsimpl; tcsp;\n  inversion d; subst.\n  boolvar; cpx.\nQed.\n\nLemma differ3_subs_filter {o} :\n  forall b f g (sub1 sub2 : @Sub o) l,\n    differ3_subs b f g sub1 sub2\n    -> differ3_subs b f g (sub_filter sub1 l) (sub_filter sub2 l).\nProof.\n  induction sub1; destruct sub2; introv d; allsimpl; inversion d; auto.\n  boolvar; sp.\nQed.\n\nLemma differ3_force_int_bound {o} :\n  forall b f g v b' (t1 t2 : @NTerm o) e1 e2,\n    !LIn v (free_vars f)\n    -> !LIn v (free_vars g)\n    -> differ3 b f g t1 t2\n    -> differ3 b f g e1 e2\n    -> differ3 b f g\n               (force_int_bound v b' t1 e1)\n               (force_int_bound v b' t2 e2).\nProof.\n  introv nif nig d1 d2.\n  apply differ3_oterm; simpl; tcsp.\n  introv i; repndors; cpx; tcsp.\n  - constructor; auto.\n  - constructor; allrw disjoint_singleton_l; auto.\n    constructor; simpl; tcsp.\n    introv i; repndors; cpx; tcsp.\n    + constructor; allsimpl; auto.\n      constructor; simpl; tcsp.\n      introv i; repndors; cpx; tcsp.\n      * constructor; auto.\n      * constructor; auto.\n        constructor; simpl; tcsp.\n      * constructor; auto.\n        constructor; simpl; tcsp.\n        introv i; repndors; cpx; tcsp.\n        constructor; auto; constructor.\n      * constructor; auto; constructor.\n    + constructor; auto; constructor; simpl; tcsp.\n    + constructor; auto; constructor.\n    + constructor; auto.\nQed.\nHint Resolve differ3_force_int_bound : slow.\n\nLemma alpha_eq_force_int_bound_app {o} :\n  forall b v1 v2 (t1 t2 f1 f2 e1 e2 : @NTerm o),\n    !LIn v1 (free_vars e1)\n    -> !LIn v2 (free_vars e2)\n    -> !LIn v1 (free_vars f1)\n    -> !LIn v2 (free_vars f2)\n    -> alpha_eq t1 t2\n    -> alpha_eq e1 e2\n    -> alpha_eq f1 f2\n    -> alpha_eq\n         (force_int_bound_app v1 b t1 f1 e1)\n         (force_int_bound_app v2 b t2 f2 e2).\nProof.\n  introv ni1 ni2 ni3 ni4 aeq1 aeq2 aeq3.\n  unfold force_int_bound_app, mk_cbv, mk_less.\n  prove_alpha_eq4.\n  introv i.\n  destruct n;[|destruct n]; try omega.\n\n  - apply alphaeqbt_nilv2; auto.\n    apply alpha_eq_force_int_bound; auto.\n\n  - pose proof (ex_fresh_var\n                  ([v1,v2]\n                     ++ all_vars f1\n                     ++ all_vars f2\n               )) as h; exrepnd.\n    allunfold @all_vars; allsimpl.\n    allsimpl; allrw app_nil_r; allrw remove_nvars_nil_l.\n    allrw in_app_iff; allsimpl; allrw in_app_iff.\n    allrw not_over_or; repnd; GC.\n\n    apply (al_bterm _ _ [v]); simpl; auto.\n\n    + unfold all_vars; simpl.\n      allrw remove_nvars_nil_l; allrw app_nil_r.\n      rw disjoint_singleton_l; simpl.\n      allrw in_app_iff; simpl; allrw in_app_iff; sp.\n\n    + unfold lsubst; simpl; boolvar; allrw app_nil_r;\n      allrw disjoint_singleton_r; tcsp.\n      prove_alpha_eq4.\n      introv j.\n      destruct n;[|destruct n;[|destruct n;[|destruct n]]];\n      try omega; eauto 3 with slow.\n\n      apply alphaeqbt_nilv2; auto.\n      repeat (rw @lsubst_aux_trivial_cl_term); auto; simpl;\n      allrw disjoint_singleton_r; auto.\nQed.\n\nLemma differ3_lsubst_aux {o} :\n  forall b f g (t1 t2 : @NTerm o) sub1 sub2,\n    disjoint (free_vars f) (dom_sub sub1)\n    -> disjoint (free_vars g) (dom_sub sub2)\n    -> differ3 b f g t1 t2\n    -> differ3_subs b f g sub1 sub2\n    -> disjoint (bound_vars t1) (sub_free_vars sub1)\n    -> disjoint (bound_vars t2) (sub_free_vars sub2)\n    -> differ3 b f g (lsubst_aux t1 sub1) (lsubst_aux t2 sub2).\nProof.\n  nterm_ind1s t1 as [v|s|op bs ind] Case;\n  introv clf clg dt ds disj1 disj2; allsimpl.\n\n  - Case \"vterm\".\n    inversion dt; subst; allsimpl.\n    remember (sub_find sub1 v) as f1; symmetry in Heqf1; destruct f1.\n\n    + applydup (differ3_subs_sub_find_some b f g sub1 sub2) in Heqf1; auto.\n      exrepnd; allrw; auto.\n\n    + applydup (differ3_subs_sub_find_none b f g sub1 sub2) in Heqf1; auto.\n      allrw; auto.\n\n  - Case \"sterm\".\n    inversion dt; subst; clear dt; allsimpl; auto.\n\n  - Case \"oterm\".\n    inversion dt as [? ? ? ? ? ni1 ni2 d1 aeq1 aeq2|?|?|? ? ? len imp]; subst; allsimpl.\n\n    + allrw @sub_filter_nil_r.\n      allrw app_nil_r.\n      allrw disjoint_app_l; allrw disjoint_cons_l; allrw disjoint_app_l; repnd; GC.\n      allrw @sub_find_sub_filter; tcsp.\n      fold_terms.\n      apply differ3_force_int; auto.\n\n      * apply (ind (force_int_bound v b t1 (mk_vbot v)) t1 []);\n        simpl; auto; try omega; eauto 3 with slow.\n        eapply ord_le_trans;[|apply ord_le_OS].\n        apply ord_le_oadd_l.\n\n      * rw @lsubst_aux_trivial_cl_term; auto.\n        apply alphaeq_preserves_free_vars in aeq1; rw <- aeq1; auto.\n        rw <- @dom_sub_sub_filter.\n        eapply subvars_disjoint_r;[|exact clf].\n        apply subvars_remove_nvars; apply subvars_app_weak_l; auto.\n\n      * rw @lsubst_aux_trivial_cl_term; auto.\n        apply alphaeq_preserves_free_vars in aeq2; rw <- aeq2; auto.\n        rw <- @dom_sub_sub_filter.\n        eapply subvars_disjoint_r;[|exact clg].\n        apply subvars_remove_nvars; apply subvars_app_weak_l; auto.\n\n    + apply differ3_oterm; allrw map_length; auto.\n\n      introv i.\n      rw <- @map_combine in i.\n      rw in_map_iff in i; exrepnd; cpx; allsimpl.\n      applydup imp in i1.\n      destruct a0 as [l1 t1].\n      destruct a as [l2 t2].\n      applydup in_combine in i1; repnd.\n      allsimpl.\n      inversion i0 as [? ? ? df dg d]; subst; clear i0.\n      constructor; auto.\n      apply (ind t1 t1 l2); eauto 3 with slow.\n\n      * rw <- @dom_sub_sub_filter.\n        eapply subvars_disjoint_r;[|exact clf].\n        apply subvars_remove_nvars; apply subvars_app_weak_l; auto.\n\n      * rw <- @dom_sub_sub_filter.\n        eapply subvars_disjoint_r;[|exact clg].\n        apply subvars_remove_nvars; apply subvars_app_weak_l; auto.\n\n      * apply differ3_subs_filter; auto.\n\n      * pose proof (subvars_sub_free_vars_sub_filter sub1 l2) as sv.\n        disj_flat_map.\n        allsimpl; allrw disjoint_app_l; repnd.\n        eapply subvars_disjoint_r; eauto.\n\n      * pose proof (subvars_sub_free_vars_sub_filter sub2 l2) as sv.\n        disj_flat_map.\n        allsimpl; allrw disjoint_app_l; repnd.\n        eapply subvars_disjoint_r; eauto.\nQed.\n\nLemma differ3_refl {o} :\n  forall b f g (t : @NTerm o),\n    disjoint (bound_vars t) (free_vars f)\n    -> disjoint (bound_vars t) (free_vars g)\n    -> differ3 b f g t t.\nProof.\n  nterm_ind t as [v|s ind|op bs ind] Case; introv df dg; allsimpl; auto.\n\n  Case \"oterm\".\n  allrw in_app_iff; allrw not_over_or; repnd.\n  apply differ3_oterm; auto.\n  introv i.\n  rw in_combine_same in i; repnd; subst.\n  destruct b2 as [l t].\n  disj_flat_map; allsimpl; allrw disjoint_app_l; repnd.\n  constructor; auto.\n  eapply ind; eauto.\nQed.\nHint Resolve differ3_refl : slow.\n\nLemma differ3_subs_refl {o} :\n  forall b f g (sub : @Sub o),\n    disjoint (sub_bound_vars sub) (free_vars f)\n    -> disjoint (sub_bound_vars sub) (free_vars g)\n    -> differ3_subs b f g sub sub.\nProof.\n  induction sub; introv df dg; allsimpl; auto.\n  destruct a; allrw @get_utokens_sub_cons; allrw in_app_iff; allrw not_over_or; repnd.\n  allrw disjoint_app_l; repnd.\n  constructor; eauto 3 with slow.\nQed.\nHint Resolve differ3_subs_refl : slow.\n\nLemma differ3_change_bound_vars {o} :\n  forall b f g vs (t1 t2 : @NTerm o),\n    differ3 b f g t1 t2\n    -> {u1 : NTerm\n        & {u2 : NTerm\n           & differ3 b f g u1 u2\n           # alpha_eq t1 u1\n           # alpha_eq t2 u2\n           # disjoint (bound_vars u1) vs\n           # disjoint (bound_vars u2) vs}}.\nProof.\n  nterm_ind1s t1 as [v|s ind|op bs ind] Case; introv (*clf clg*) d.\n\n  - Case \"vterm\".\n    inversion d; subst.\n    exists (@mk_var o v) (@mk_var o v); simpl; dands; eauto 3 with slow.\n\n  - Case \"sterm\".\n    inversion d; subst; clear d.\n    exists (sterm s) (sterm s); dands; simpl; auto.\n\n  - Case \"oterm\".\n    inversion d as [? ? ? ? ? ni1 ni2 d1 a1 a2|?|?|? ? ? len imp]; subst; simphyps; cpx; ginv; clear d.\n\n    + pose proof (ex_fresh_var (vs ++ free_vars f ++ free_vars g)) as h; exrepnd.\n      allsimpl; allrw in_app_iff; allrw not_over_or; repnd.\n      pose proof (ind (force_int_bound v b t1 (mk_vbot v)) t1 []) as h; clear ind.\n      repeat (autodimp h hyp).\n      { simpl; try omega.\n        eapply ord_le_trans;[|apply ord_le_OS].\n        apply ord_le_oadd_l. }\n      pose proof (h t0 (*clf clg*) d1) as k; clear h.\n      exrepnd.\n\n      fold_terms.\n\n      pose proof (change_bvars_alpha_spec fa vs) as p1.\n      remember (change_bvars_alpha vs fa) as fa1; clear Heqfa1; simpl in p1.\n      pose proof (change_bvars_alpha_spec ga vs) as p2.\n      remember (change_bvars_alpha vs ga) as ga1; clear Heqga1; simpl in p2.\n      repnd.\n\n      exists\n        (force_int_bound_app v0 b u1 fa1 (mk_vbot v0))\n        (force_int_bound_app v0 b u2 ga1 (mk_vbot v0)).\n      dands; eauto 4 with slow.\n\n      * apply alpha_eq_force_int_bound_app; simpl; tcsp;\n        allrw remove_nvars_nil_l; allrw app_nil_r; allrw remove_nvars_eq;\n        tcsp; eauto 3 with slow.\n        { apply alphaeq_preserves_free_vars in a1; rw <- a1; auto. }\n        { apply alphaeq_preserves_free_vars in p1; rw <- p1; auto.\n          apply alphaeq_preserves_free_vars in a1; rw <- a1; auto. }\n\n      * apply alpha_eq_force_int_bound_app; simpl; tcsp;\n        allrw remove_nvars_nil_l; allrw app_nil_r; allrw remove_nvars_eq;\n        tcsp; eauto 3 with slow.\n        { apply alphaeq_preserves_free_vars in a2; rw <- a2; auto. }\n        { apply alphaeq_preserves_free_vars in p2; rw <- p2; auto.\n          apply alphaeq_preserves_free_vars in a2; rw <- a2; auto. }\n\n      * simpl; allrw app_nil_r.\n        allrw disjoint_app_l; allrw disjoint_cons_l;\n        allrw disjoint_app_l; allrw disjoint_singleton_l.\n        dands; eauto 3 with slow.\n\n      * simpl; allrw app_nil_r.\n        allrw disjoint_app_l; allrw disjoint_cons_l;\n        allrw disjoint_app_l; allrw disjoint_singleton_l.\n        dands; eauto 3 with slow.\n\n    + assert ({bs' : list BTerm\n               & {bs2' : list BTerm\n                  & alpha_eq_bterms bs bs'\n                  # alpha_eq_bterms bs2 bs2'\n                  # differ3_bterms b f g bs' bs2'\n                  # disjoint (flat_map bound_vars_bterm bs') vs\n                  # disjoint (flat_map bound_vars_bterm bs2') vs}}) as h.\n\n      { revert dependent bs2.\n        induction bs; destruct bs2; introv len imp; allsimpl; ginv.\n        - exists ([] : list (@BTerm o)) ([] : list (@BTerm o));\n            dands; simpl; eauto 3 with slow; try (apply br_bterms_nil).\n        - cpx.\n          destruct a as [l1 t1].\n          destruct b0 as [l2 t2].\n          pose proof (imp (bterm l1 t1) (bterm l2 t2)) as h; autodimp h hyp.\n          inversion h as [? ? ? df dg d1]; subst; clear h.\n          pose proof (ind t1 t1 l2) as h; repeat (autodimp h hyp); eauto 3 with slow.\n          pose proof (h t2 (*clf clg*) d1) as k; clear h.\n          exrepnd.\n\n          autodimp IHbs hyp.\n          { introv i d; eapply ind; eauto. }\n          pose proof (IHbs bs2) as k.\n          repeat (autodimp k hyp).\n          exrepnd.\n\n          pose proof (fresh_vars\n                        (length l2)\n                        (vs\n                           ++ l2\n                           ++ all_vars t1\n                           ++ all_vars t2\n                           ++ all_vars u1\n                           ++ all_vars u2\n                           ++ all_vars f\n                           ++ all_vars g\n                        )) as fv; exrepnd.\n          allrw disjoint_app_r; repnd.\n\n          exists ((bterm lvn (lsubst_aux u1 (var_ren l2 lvn))) :: bs')\n                 ((bterm lvn (lsubst_aux u2 (var_ren l2 lvn))) :: bs2');\n            dands; simpl;\n            try (apply br_bterms_cons);\n            try (apply alpha_eq_bterm_congr);\n            tcsp.\n          { apply alpha_bterm_change_aux; eauto 3 with slow.\n            allrw disjoint_app_l; dands; eauto 3 with slow. }\n          { apply alpha_bterm_change_aux; eauto 3 with slow.\n            allrw disjoint_app_l; dands; eauto 3 with slow. }\n          { apply differ3_bterm; auto.\n            apply differ3_lsubst_aux; eauto 3 with slow;\n            try (rw @sub_free_vars_var_ren; eauto 3 with slow);\n            try (rw @dom_sub_var_ren; eauto 3 with slow).\n            apply differ3_subs_refl; simpl;\n            try (rw @sub_bound_vars_var_ren; auto). }\n          { allrw disjoint_app_l; dands; eauto 3 with slow.\n            pose proof (subvars_bound_vars_lsubst_aux\n                          u1 (var_ren l2 lvn)) as sv.\n            eapply subvars_disjoint_l;[exact sv|].\n            apply disjoint_app_l; dands; auto.\n            rw @sub_bound_vars_var_ren; auto. }\n          { allrw disjoint_app_l; dands; eauto 3 with slow.\n            pose proof (subvars_bound_vars_lsubst_aux\n                          u2 (var_ren l2 lvn)) as sv.\n            eapply subvars_disjoint_l;[exact sv|].\n            apply disjoint_app_l; dands; auto.\n            rw @sub_bound_vars_var_ren; auto. }\n      }\n\n      exrepnd.\n      allunfold @alpha_eq_bterms.\n      allunfold @differ3_bterms.\n      allunfold @br_bterms.\n      allunfold @br_list; repnd.\n      exists (oterm op bs') (oterm op bs2'); dands; eauto 3 with slow.\n\n      * apply alpha_eq_oterm_combine; dands; auto.\n\n      * apply alpha_eq_oterm_combine; dands; auto.\nQed.\n\nLemma differ3_subst {o} :\n  forall b f g (t1 t2 : @NTerm o) sub1 sub2,\n    disjoint (free_vars f) (dom_sub sub1)\n    -> disjoint (free_vars g) (dom_sub sub2)\n    -> differ3 b f g t1 t2\n    -> differ3_subs b f g sub1 sub2\n    -> differ3_alpha b f g (lsubst t1 sub1) (lsubst t2 sub2).\nProof.\n  introv clf clg dt ds.\n\n  pose proof (unfold_lsubst sub1 t1) as h; exrepnd.\n  pose proof (unfold_lsubst sub2 t2) as k; exrepnd.\n  rw h0; rw k0.\n\n  pose proof (differ3_change_bound_vars\n                b f g (sub_free_vars sub1 ++ sub_free_vars sub2)\n                t1 t2 dt) as d; exrepnd.\n  allrw disjoint_app_r; repnd.\n\n  exists (lsubst_aux u1 sub1) (lsubst_aux u2 sub2); dands; auto.\n\n  - apply lsubst_aux_alpha_congr2; eauto 3 with slow.\n\n  - apply lsubst_aux_alpha_congr2; eauto 3 with slow.\n\n  - apply differ3_lsubst_aux; auto.\nQed.\nHint Resolve differ3_subst : slow.\n\nLemma differ3_bterms_implies_eq_map_num_bvars {o} :\n  forall b f g (bs1 bs2 : list (@BTerm o)),\n    differ3_bterms b f g bs1 bs2\n    -> map num_bvars bs1 = map num_bvars bs2.\nProof.\n  induction bs1; destruct bs2; introv d; allsimpl; auto;\n  allunfold @differ3_bterms; allunfold @br_bterms; allunfold @br_list;\n  allsimpl; repnd; cpx.\n  pose proof (d a b0) as h; autodimp h hyp.\n  inversion h; subst.\n  f_equal.\n  unfold num_bvars; simpl; auto.\nQed.\n\nDefinition differ3_sk {o} b f g (sk1 sk2 : @sosub_kind o) :=\n  differ3_b b f g (sk2bterm sk1) (sk2bterm sk2).\n\nInductive differ3_sosubs {o} b f g : @SOSub o -> @SOSub o -> Type :=\n| dsosub3_nil : differ3_sosubs b f g [] []\n| dsosub3_cons :\n    forall v sk1 sk2 sub1 sub2,\n      differ3_sk b f g sk1 sk2\n      -> differ3_sosubs b f g sub1 sub2\n      -> differ3_sosubs b f g ((v,sk1) :: sub1) ((v,sk2) :: sub2).\nHint Constructors differ3_sosubs.\n\nLemma differ3_bterms_cons {o} :\n  forall b f g (b1 b2 : @BTerm o) bs1 bs2,\n    differ3_bterms b f g (b1 :: bs1) (b2 :: bs2)\n    <=> (differ3_b b f g b1 b2 # differ3_bterms b f g bs1 bs2).\nProof.\n  unfold differ3_bterms; introv.\n  rw @br_bterms_cons_iff; sp.\nQed.\n\nLemma differ3_mk_abs_substs {o} :\n  forall b f g (bs1 bs2 : list (@BTerm o)) vars,\n    differ3_bterms b f g bs1 bs2\n    -> length vars = length bs1\n    -> differ3_sosubs b f g (mk_abs_subst vars bs1) (mk_abs_subst vars bs2).\nProof.\n  induction bs1; destruct bs2; destruct vars; introv d m; allsimpl; cpx; tcsp.\n  - provefalse.\n    apply differ3_bterms_implies_eq_map_num_bvars in d; allsimpl; cpx.\n  - apply differ3_bterms_cons in d; repnd.\n    destruct s, a, b0.\n    inversion d0; subst.\n    boolvar; auto.\nQed.\n\nLemma differ3_b_change_bound_vars {o} :\n  forall b f g vs (b1 b2 : @BTerm o),\n    differ3_b b f g b1 b2\n    -> {u1 : BTerm\n        & {u2 : BTerm\n           & differ3_b b f g u1 u2\n           # alpha_eq_bterm b1 u1\n           # alpha_eq_bterm b2 u2\n           # disjoint (bound_vars_bterm u1) vs\n           # disjoint (bound_vars_bterm u2) vs}}.\nProof.\n  introv d.\n  pose proof (differ3_change_bound_vars\n                b f g vs (oterm Exc [b1]) (oterm Exc [b2])) as h.\n  repeat (autodimp h hyp).\n  - apply differ3_oterm; simpl; tcsp.\n    introv i; dorn i; tcsp; cpx.\n  - exrepnd.\n    inversion h2 as [|?|? ? ? len1 imp1]; subst; allsimpl; cpx.\n    inversion h3 as [|?|? ? ? len2 imp2]; subst; allsimpl; cpx.\n    pose proof (imp1 0) as k1; autodimp k1 hyp; allsimpl; clear imp1.\n    pose proof (imp2 0) as k2; autodimp k2 hyp; allsimpl; clear imp2.\n    allunfold @selectbt; allsimpl.\n    allrw app_nil_r.\n    exists x x0; dands; auto.\n    inversion h0 as [|?|?|? ? ? ? i]; subst; allsimpl; GC.\n    apply i; sp.\nQed.\n\nLemma differ3_sk_change_bound_vars {o} :\n  forall b f g vs (sk1 sk2 : @sosub_kind o),\n    differ3_sk b f g sk1 sk2\n    -> {u1 : sosub_kind\n        & {u2 : sosub_kind\n           & differ3_sk b f g u1 u2\n           # alphaeq_sk sk1 u1\n           # alphaeq_sk sk2 u2\n           # disjoint (bound_vars_sk u1) vs\n           # disjoint (bound_vars_sk u2) vs}}.\nProof.\n  introv d.\n  unfold differ3_sk in d.\n  apply (differ3_b_change_bound_vars b f g vs) in d; exrepnd; allsimpl; auto.\n  exists (bterm2sk u1) (bterm2sk u2).\n  destruct u1, u2, sk1, sk2; allsimpl; dands; auto;\n  apply alphaeq_sk_iff_alphaeq_bterm2; simpl; auto.\nQed.\n\nLemma differ3_sosubs_change_bound_vars {o} :\n  forall b f g vs (sub1 sub2 : @SOSub o),\n    differ3_sosubs b f g sub1 sub2\n    -> {sub1' : SOSub\n        & {sub2' : SOSub\n           & differ3_sosubs b f g sub1' sub2'\n           # alphaeq_sosub sub1 sub1'\n           # alphaeq_sosub sub2 sub2'\n           # disjoint (bound_vars_sosub sub1') vs\n           # disjoint (bound_vars_sosub sub2') vs}}.\nProof.\n  induction sub1; destruct sub2; introv d.\n  - exists ([] : @SOSub o) ([] : @SOSub o); dands; simpl; tcsp.\n  - inversion d.\n  - inversion d.\n  - inversion d as [|? ? ? ? ? dsk dso]; subst; clear d.\n    apply IHsub1 in dso; exrepnd; auto.\n    apply (differ3_sk_change_bound_vars b f g vs) in dsk; exrepnd; auto.\n    exists ((v,u1) :: sub1') ((v,u2) :: sub2'); dands; simpl; auto;\n    allrw disjoint_app_l; dands; eauto 3 with slow.\nQed.\n\nLemma sosub_find_some_if_differ3_sosubs {o} :\n  forall b f g (sub1 sub2 : @SOSub o) v sk,\n    differ3_sosubs b f g sub1 sub2\n    -> sosub_find sub1 v = Some sk\n    -> {sk' : sosub_kind\n        & differ3_sk b f g sk sk'\n        # sosub_find sub2 v = Some sk'}.\nProof.\n  induction sub1; destruct sub2; introv aeq sf; allsimpl; tcsp.\n  - inversion aeq.\n  - destruct a, p; destruct s, s0.\n    inversion aeq as [|? ? ? ? ? dsk dso]; subst; clear aeq.\n    boolvar; subst; cpx; tcsp.\n    + eexists; dands; eauto.\n    + inversion dsk; subst; tcsp.\n    + inversion dsk; subst; tcsp.\nQed.\n\nLemma sosub_find_none_if_differ3_sosubs {o} :\n  forall b f g (sub1 sub2 : @SOSub o) v,\n    differ3_sosubs b f g sub1 sub2\n    -> sosub_find sub1 v = None\n    -> sosub_find sub2 v = None.\nProof.\n  induction sub1; destruct sub2; introv aeq sf; allsimpl; tcsp.\n  - inversion aeq.\n  - destruct a, p; destruct s, s0.\n    inversion aeq as [|? ? ? ? ? dsk dso]; subst; clear aeq.\n    boolvar; subst; cpx; tcsp.\n    inversion dsk; subst; tcsp.\nQed.\n\nLemma differ3_subs_combine {o} :\n  forall b f g (ts1 ts2 : list (@NTerm o)) vs,\n    length ts1 = length ts2\n    -> (forall t1 t2,\n          LIn (t1,t2) (combine ts1 ts2)\n          -> differ3 b f g t1 t2)\n    -> differ3_subs b f g (combine vs ts1) (combine vs ts2).\nProof.\n  induction ts1; destruct ts2; destruct vs; introv len imp; allsimpl; cpx; tcsp.\nQed.\n\nLemma differ3_apply_list {o} :\n  forall b f g (ts1 ts2 : list (@NTerm o)) t1 t2,\n    differ3 b f g t1 t2\n    -> length ts1 = length ts2\n    -> (forall x y, LIn (x,y) (combine ts1 ts2) -> differ3 b f g x y)\n    -> differ3 b f g (apply_list t1 ts1) (apply_list t2 ts2).\nProof.\n  induction ts1; destruct ts2; introv d l i; allsimpl; cpx.\n  apply IHts1; auto.\n  apply differ3_oterm; simpl; auto; tcsp.\n  introv k; repndors; cpx; tcsp; constructor; auto.\nQed.\n\nLemma differ3_sosub_filter {o} :\n  forall b f g (sub1 sub2 : @SOSub o) vs,\n    differ3_sosubs b f g sub1 sub2\n    -> differ3_sosubs b f g (sosub_filter sub1 vs) (sosub_filter sub2 vs).\nProof.\n  induction sub1; destruct sub2; introv d;\n  inversion d as [|? ? ? ? ? dsk dso]; subst; auto.\n  destruct sk1, sk2; allsimpl.\n  inversion dsk; subst.\n  boolvar; tcsp.\nQed.\nHint Resolve differ3_sosub_filter : slow.\n\nLemma no_utokens_sovar {o} :\n  forall v (ts : list (@SOTerm o)),\n    no_utokens (sovar v ts) <=> (forall t, LIn t ts -> no_utokens t).\nProof.\n  introv.\n  unfold no_utokens; simpl.\n  induction ts; simpl; split; intro k; tcsp.\n  - introv i; repndors; subst; tcsp.\n    + rw app_eq_nil_iff in k; sp.\n    + rw app_eq_nil_iff in k; repnd.\n      rw IHts in k; sp.\n  - rw app_eq_nil_iff; dands; tcsp.\n    apply IHts; tcsp.\nQed.\n\nDefinition no_utokens_op {o} (op : @Opid o) :=\n  get_utokens_o op = [].\n\nLemma no_utokens_soterm {o} :\n  forall op (bs : list (@SOBTerm o)),\n    no_utokens (soterm op bs)\n    <=>\n    (no_utokens_op op # (forall vs t, LIn (sobterm vs t) bs -> no_utokens t)).\nProof.\n  introv; unfold cover_so_vars; simpl; split; intro k; repnd; dands; tcsp.\n  - allunfold @no_utokens; allsimpl.\n    rw app_eq_nil_iff in k; repnd; auto.\n  - introv i.\n    allunfold @no_utokens; allsimpl.\n    rw app_eq_nil_iff in k; repnd; auto.\n    rw flat_map_empty in k.\n    apply k in i; allsimpl; auto.\n  - allunfold @no_utokens; simpl.\n    rw app_eq_nil_iff; dands; auto.\n    rw flat_map_empty; introv i.\n    destruct a; apply k in i; allsimpl; auto.\nQed.\n\nLemma differ3_sosub_aux {o} :\n  forall b f g (t : @SOTerm o) sub1 sub2,\n    no_utokens t\n    -> disjoint (fo_bound_vars t) (free_vars f)\n    -> disjoint (fo_bound_vars t) (free_vars g)\n    -> differ3_sosubs b f g sub1 sub2\n    -> disjoint (fo_bound_vars t) (free_vars_sosub sub1)\n    -> disjoint (free_vars_sosub sub1) (bound_vars_sosub sub1)\n    -> disjoint (all_fo_vars t) (bound_vars_sosub sub1)\n    -> disjoint (fo_bound_vars t) (free_vars_sosub sub2)\n    -> disjoint (free_vars_sosub sub2) (bound_vars_sosub sub2)\n    -> disjoint (all_fo_vars t) (bound_vars_sosub sub2)\n    -> cover_so_vars t sub1\n    -> cover_so_vars t sub2\n    -> differ3 b f g (sosub_aux sub1 t) (sosub_aux sub2 t).\nProof.\n  soterm_ind t as [v ts ind|op bs ind] Case;\n  introv nut df dg ds;\n  introv disj1 disj2 disj3 disj4 disj5 disj6 cov1 cov2; allsimpl.\n\n  - Case \"sovar\".\n    allrw @cover_so_vars_sovar; repnd.\n    allrw @no_utokens_sovar.\n    allrw disjoint_cons_l; repnd.\n    remember (sosub_find sub1 (v, length ts)) as f1; symmetry in Heqf1.\n    destruct f1.\n\n    + applydup (sosub_find_some_if_differ3_sosubs b f g sub1 sub2) in Heqf1; auto.\n      exrepnd.\n      rw Heqf2.\n      destruct s as [l1 t1].\n      destruct sk' as [l2 t2].\n      inversion Heqf0; subst.\n      apply differ3_lsubst_aux; auto.\n\n      * apply sosub_find_some in Heqf2; repnd.\n        rw @dom_sub_combine; allrw map_length; eauto 3 with slow.\n\n      * apply sosub_find_some in Heqf2; repnd.\n        rw @dom_sub_combine; allrw map_length; eauto 3 with slow.\n\n      * apply differ3_subs_combine; allrw map_length; 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; allsimpl.\n        disj_flat_map.\n        apply ind; auto.\n\n      * apply sosub_find_some in Heqf1; repnd.\n        rw @sub_free_vars_combine; allrw map_length; auto.\n        rw flat_map_map; unfold compose.\n        eapply disjoint_bound_vars_prop3; eauto 3 with slow.\n        eapply subvars_disjoint_r;[|apply disjoint_sym;eauto].\n        apply subvars_flat_map2; introv i.\n        apply fovars_subvars_all_fo_vars.\n\n      * apply sosub_find_some in Heqf2; repnd.\n        rw @sub_free_vars_combine; allrw map_length; auto.\n        rw flat_map_map; unfold compose.\n        eapply disjoint_bound_vars_prop3; eauto 3 with slow.\n        eapply subvars_disjoint_r;[|apply disjoint_sym;eauto].\n        apply subvars_flat_map2; introv i.\n        apply fovars_subvars_all_fo_vars.\n\n    + applydup (sosub_find_none_if_differ3_sosubs b f g sub1 sub2) in Heqf1; auto.\n      rw Heqf0.\n      apply differ3_apply_list; allrw map_length; auto.\n      introv i.\n      rw <- @map_combine in i; rw in_map_iff in i; exrepnd; cpx.\n      apply in_combine_same in i1; repnd; subst; allsimpl.\n      disj_flat_map.\n      apply ind; auto.\n\n  - Case \"soterm\".\n    allrw @cover_so_vars_soterm.\n    allrw @no_utokens_soterm; repnd.\n    apply differ3_oterm; allrw map_length; tcsp; try (complete (rw nut0; sp)).\n    introv i.\n    rw <- @map_combine in i; rw in_map_iff in i; exrepnd; cpx.\n    apply in_combine_same in i1; repnd; subst; allsimpl.\n    destruct a as [l t].\n    disj_flat_map.\n    allsimpl; allrw disjoint_app_l; repnd.\n    disj_flat_map; allsimpl; allrw disjoint_app_l; repnd.\n    constructor; auto.\n    eapply ind; eauto 3 with slow.\n\n    + pose proof (subvars_free_vars_sosub_sosub_filter sub1 (vars2sovars l)) as sv.\n      eapply subvars_disjoint_r;[exact sv|]; auto.\n\n    + pose proof (subvars_free_vars_sosub_sosub_filter sub1 (vars2sovars l)) as sv1.\n      pose proof (subvars_bound_vars_sosub_filter sub1 (vars2sovars l)) as sv2.\n      eapply subvars_disjoint_r;[exact sv2|]; auto.\n      eapply subvars_disjoint_l;[exact sv1|]; auto.\n\n    + pose proof (subvars_bound_vars_sosub_filter sub1 (vars2sovars l)) as sv1.\n      eapply subvars_disjoint_r;[exact sv1|]; auto.\n\n    + pose proof (subvars_free_vars_sosub_sosub_filter sub2 (vars2sovars l)) as sv1.\n      eapply subvars_disjoint_r;[exact sv1|]; auto.\n\n    + pose proof (subvars_free_vars_sosub_sosub_filter sub2 (vars2sovars l)) as sv1.\n      pose proof (subvars_bound_vars_sosub_filter sub2 (vars2sovars l)) as sv2.\n      eapply subvars_disjoint_r;[exact sv2|]; auto.\n      eapply subvars_disjoint_l;[exact sv1|]; auto.\n\n    + pose proof (subvars_bound_vars_sosub_filter sub2 (vars2sovars l)) as sv1.\n      eapply subvars_disjoint_r;[exact sv1|]; auto.\n\n    + discover.\n      apply cover_so_vars_sosub_filter; auto.\n\n    + discover.\n      apply cover_so_vars_sosub_filter; auto.\nQed.\n\nLemma differ3_sosub {o} :\n  forall b f g (t : @SOTerm o) (sub1 sub2 : SOSub),\n    no_utokens t\n    -> differ3_sosubs b f g sub1 sub2\n    -> cover_so_vars t sub1\n    -> cover_so_vars t sub2\n    -> differ3_alpha b f g (sosub sub1 t) (sosub sub2 t).\nProof.\n  introv nut d c1 c2.\n  pose proof (unfold_sosub sub1 t) as h.\n  destruct h as [sub1' h]; destruct h as [t1 h]; repnd; rw h.\n  pose proof (unfold_sosub sub2 t) as k.\n  destruct k as [sub2' k]; destruct k as [t2 k]; repnd; rw k.\n\n  pose proof (differ3_sosubs_change_bound_vars\n                b\n                f g\n                (all_fo_vars t1\n                             ++ all_fo_vars t2\n                             ++ free_vars_sosub sub1\n                             ++ free_vars_sosub sub2\n                )\n                sub1 sub2\n                d) as e.\n  destruct e as [sub1'' e]; destruct e as [sub2'' e]; repnd.\n\n  pose proof (fo_change_bvars_alpha_spec\n                (free_vars_sosub sub1''\n                                 ++ free_vars_sosub sub2''\n                                 ++ bound_vars_sosub sub1''\n                                 ++ bound_vars_sosub sub2''\n                                 ++ free_vars f\n                                 ++ free_vars g\n                )\n                t) as q.\n  revert q.\n  fo_change t0; simpl; intro q; repnd; GC.\n\n  allrw disjoint_app_l; allrw disjoint_app_r; repnd.\n\n  assert (so_alphaeq t1 t0) as a1 by eauto 3 with slow.\n  assert (so_alphaeq t2 t0) as a2 by eauto 3 with slow.\n\n  pose proof (fovars_subvars_all_fo_vars t1) as sv1.\n  pose proof (fovars_subvars_all_fo_vars t2) as sv2.\n  pose proof (alphaeq_sosub_preserves_free_vars sub1 sub1'') as ev1; autodimp ev1 hyp.\n  pose proof (alphaeq_sosub_preserves_free_vars sub2 sub2'') as ev2; autodimp ev2 hyp.\n  pose proof (fovars_subvars_all_fo_vars t0) as sv3.\n  pose proof (all_fo_vars_eqvars t0) as ev3.\n  pose proof (all_fo_vars_eqvars t1) as ev4.\n  pose proof (so_alphaeq_preserves_free_vars t1 t0 a1) as efv1.\n  pose proof (so_alphaeq_preserves_free_vars t2 t0 a2) as efv2.\n  applydup eqvars_app_r_implies_subvars in ev4 as ev; destruct ev as [ev5 ev6].\n\n  assert (disjoint (fo_bound_vars t0) (free_vars_sosub sub1'')\n          # disjoint (free_vars_sosub sub1'') (bound_vars_sosub sub1'')\n          # disjoint (all_fo_vars t0) (bound_vars_sosub sub1'')\n          # disjoint (fo_bound_vars t0) (free_vars_sosub sub2'')\n          # disjoint (free_vars_sosub sub2'') (bound_vars_sosub sub2'')\n          # disjoint (all_fo_vars t0) (bound_vars_sosub sub2'')) as disj.\n\n  { dands; eauto 3 with slow.\n    - rw <- ev1; eauto 3 with slow.\n    - eapply eqvars_disjoint;[apply eqvars_sym; exact ev3|].\n      apply disjoint_app_l; dands; eauto 3 with slow.\n      rw <- efv1.\n      eapply subvars_disjoint_l;[exact ev6|]; eauto 3 with slow.\n    - rw <- ev2; eauto 3 with slow.\n    - eapply eqvars_disjoint;[apply eqvars_sym; exact ev3|].\n      apply disjoint_app_l; dands; eauto 3 with slow.\n      rw <- efv1.\n      eapply subvars_disjoint_l;[exact ev6|]; eauto 3 with slow. }\n\n  repnd.\n\n  pose proof (sosub_aux_alpha_congr2\n                t1 t0 sub1' sub1'') as aeq1.\n  repeat (autodimp aeq1 hyp); eauto 3 with slow.\n\n  { rw disjoint_app_r; dands; eauto 3 with slow. }\n\n  { rw disjoint_app_r; dands; eauto 3 with slow. }\n\n  pose proof (sosub_aux_alpha_congr2\n                t2 t0 sub2' sub2'') as aeq2.\n  repeat (autodimp aeq2 hyp); eauto 3 with slow.\n\n  { rw disjoint_app_r; dands; eauto 3 with slow. }\n\n  { rw disjoint_app_r; dands; eauto 3 with slow. }\n\n  exists (sosub_aux sub1'' t0) (sosub_aux sub2'' t0); dands;\n  try (apply alphaeq_eq; complete auto).\n\n  apply differ3_sosub_aux; eauto 3 with slow.\n\n  { allapply @get_utokens_so_soalphaeq.\n    unfold no_utokens; rw <- h5; auto. }\nQed.\n\nLemma differ3_mk_instance {o} :\n  forall b f g (t : @SOTerm o) vars bs1 bs2,\n    no_utokens t\n    -> matching_bterms vars bs1\n    -> matching_bterms vars bs2\n    -> socovered t vars\n    -> socovered t vars\n    -> differ3_bterms b f g bs1 bs2\n    -> differ3_alpha b f g (mk_instance vars bs1 t) (mk_instance vars bs2 t).\nProof.\n  introv nut m1 m2 sc1 sc2 dbs.\n  unfold mk_instance.\n  applydup @matching_bterms_implies_eq_length in m1.\n  applydup (@differ3_mk_abs_substs o b f g bs1 bs2 vars) in dbs; auto.\n\n  apply differ3_sosub; auto;\n  apply socovered_implies_cover_so_vars; auto.\nQed.\n\nLemma exists_compute_step_if_reduces_to {o} :\n  forall lib (t1 t2 : @NTerm o),\n    reduces_to lib t1 t2\n    -> isvalue_like t2\n    -> {u : NTerm\n        & compute_step lib t1 = csuccess u\n        # reduces_to lib u t2}.\nProof.\n  introv r isv.\n  unfold reduces_to in r; exrepnd.\n  destruct k.\n  - allrw @reduces_in_atmost_k_steps_0; subst.\n    unfold isvalue_like in isv; repndors.\n    + apply iscan_implies in isv; repndors; exrepnd; subst; simpl;\n      csunf; simpl; eexists; dands; eauto 3 with slow.\n    + apply isexc_implies2 in isv; exrepnd; subst; simpl.\n      csunf; simpl.\n      eexists; eauto 3 with slow.\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    eexists; dands; eauto 3 with slow.\nQed.\n\nDefinition red_to_can {p} lib (t : @NTerm p) :=\n  {u : NTerm\n   & reduces_to lib t u\n   # iscan u}.\n\nLemma if_red_to_can_ncompop_can1 {o} :\n  forall lib c can bs (t : @NTerm o) l,\n    red_to_can\n      lib\n      (oterm (NCan (NCompOp c))\n             (bterm [] (oterm (Can can) bs)\n                    :: bterm [] t\n                    :: l))\n    -> red_to_can lib t.\nProof.\n  introv hv.\n  unfold red_to_can in hv; exrepnd.\n\n  pose proof (converges_to_value_like_ncompop lib c can bs t l) as h.\n  autodimp h hyp.\n\n  { unfold converges_to_value_like; exists u; sp. }\n\n  repndors; exrepnd.\n\n  - exists (pk2term pk); dands; eauto 3 with slow.\n\n  - provefalse.\n    apply isexc_implies2 in h0; exrepnd; subst.\n    pose proof (compose_reduces_to_primarg_ncompop\n                  lib c can bs t (oterm Exc l0) u l) as h.\n    repeat (autodimp h hyp); tcsp.\n\n    apply iscan_implies in hv0; repndors; exrepnd; subst;\n    apply reduces_to_split2 in h; dorn h; simpl in h; ginv;\n    exrepnd; ginv;\n    csunf h2; allsimpl; ginv;\n    dcwf q; ginv;\n    apply reduces_to_if_isvalue_like in h0; tcsp; ginv.\nQed.\n\nLemma if_red_to_can_narithop_can1 {o} :\n  forall lib c can bs (t : @NTerm o) l,\n    red_to_can\n      lib\n      (oterm (NCan (NArithOp c))\n             (bterm [] (oterm (Can can) bs)\n                    :: bterm [] t\n                    :: l))\n    -> red_to_can lib t.\nProof.\n  introv hv.\n  unfold red_to_can in hv; exrepnd.\n\n  pose proof (converges_to_value_like_narithop lib c can bs t l) as h.\n  autodimp h hyp.\n\n  { unfold converges_to_value_like; exists u; sp. }\n\n  repndors; exrepnd.\n\n  - exists (@mk_integer o i); dands.\n    + unfold computes_to_value in h0; sp.\n    + unfold isvalue_like; simpl; sp.\n\n  - provefalse.\n    apply isexc_implies2 in h0; exrepnd; subst.\n    pose proof (compose_reduces_to_primarg_arithop\n                  lib c can bs t (oterm Exc l0) u l) as h.\n    repeat (autodimp h hyp); tcsp.\n\n    apply iscan_implies in hv0; repndors; exrepnd; subst;\n    apply reduces_to_split2 in h; dorn h; simpl in h; ginv;\n    exrepnd; ginv;\n    csunf h2; allsimpl; ginv;\n    dcwf q; ginv;\n    apply reduces_to_if_isvalue_like in h0; tcsp; ginv.\nQed.\n\nDefinition red_to_can_k {p} lib k (t : @NTerm p) :=\n  {u : NTerm\n   & reduces_in_atmost_k_steps lib t u k\n   # iscan u}.\n\nLemma red_to_can_0 {o} :\n  forall lib (t : @NTerm o),\n    red_to_can_k lib 0 t <=> iscan t.\nProof.\n  introv; unfold red_to_can_k; split; intro k; exrepnd.\n  - allrw @reduces_in_atmost_k_steps_0; subst; auto.\n  - exists t; allrw @reduces_in_atmost_k_steps_0; auto.\nQed.\n\nLemma red_to_can_S {o} :\n  forall lib k (t : @NTerm o),\n    red_to_can_k lib (S k) t\n    <=> {u : NTerm\n         & compute_step lib t = csuccess u\n         # red_to_can_k lib k u}.\nProof.\n  introv; unfold red_to_can_k; split; intro h; exrepnd.\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    eexists; eauto.\n  - exists u0; dands; auto.\n    allrw @reduces_in_atmost_k_steps_S.\n    eexists; eauto.\nQed.\n\nLemma if_red_to_can_k_ncompop_can1 {o} :\n  forall lib c can bs k (t : @NTerm o) l,\n    red_to_can_k\n      lib k\n      (oterm (NCan (NCompOp c))\n             (bterm [] (oterm (Can can) bs)\n                    :: bterm [] t\n                    :: l))\n    -> {j : nat & j < k # red_to_can_k lib j t}.\nProof.\n  induction k; introv r.\n  - allrw @red_to_can_0; inversion r.\n  - allrw @red_to_can_S; exrepnd.\n    destruct t as [v|f|op bs1]; try (complete (csunf r1; allsimpl; dcwf h));[].\n    dopid op as [can2|ncan2|exc2|abs2] Case.\n    + exists 0; dands; try omega.\n      rw @red_to_can_0; auto.\n    + rw @compute_step_ncompop_ncan2 in r1.\n      dcwf h.\n      remember (compute_step lib (oterm (NCan ncan2) bs1)) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @red_to_can_S.\n      exists n; tcsp.\n    + csunf r1; simpl in r1; ginv.\n      dcwf h; ginv.\n      provefalse.\n      unfold red_to_can_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in r0; subst; tcsp.\n    + csunf r1; simpl in r1; csunf r1; simpl in r1.\n      dcwf h.\n      unfold on_success in r1.\n      remember (compute_step_lib lib abs2 bs1) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @red_to_can_S.\n      exists n; tcsp.\nQed.\n\nLemma if_red_to_can_k_narithop_can1 {o} :\n  forall lib c can bs k (t : @NTerm o) l,\n    red_to_can_k\n      lib k\n      (oterm (NCan (NArithOp c))\n             (bterm [] (oterm (Can can) bs)\n                    :: bterm [] t\n                    :: l))\n    -> {j : nat & j < k # red_to_can_k lib j t}.\nProof.\n  induction k; introv r.\n  - allrw @red_to_can_0; inversion r.\n  - allrw @red_to_can_S; exrepnd.\n    destruct t as [v|f|op bs1]; try (complete (csunf r1; allsimpl; dcwf h));[].\n    dopid op as [can2|ncan2|exc2|abs2] Case.\n    + exists 0; dands; try omega.\n      rw @red_to_can_0; auto.\n    + rw @compute_step_narithop_ncan2 in r1.\n      dcwf h.\n      remember (compute_step lib (oterm (NCan ncan2) bs1)) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @red_to_can_S.\n      exists n; tcsp.\n    + csunf r1; simpl in r1; ginv.\n      dcwf h; ginv.\n      provefalse.\n      unfold red_to_can_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in r0; subst; tcsp.\n    + csunf r1; simpl in r1; csunf r1; simpl in r1.\n      dcwf h.\n      unfold on_success in r1.\n      remember (compute_step_lib lib abs2 bs1) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @red_to_can_S.\n      exists n; tcsp.\nQed.\n\nLemma red_to_can_k_lt {o} :\n  forall lib k1 k2 (t : @NTerm o),\n    red_to_can_k lib k1 t\n    -> k1 < k2\n    -> red_to_can_k lib k2 t.\nProof.\n  unfold red_to_can_k; introv r l; exrepnd.\n  exists u; dands; auto.\n  pose proof (no_change_after_value_like lib t k1 u) as h.\n  repeat (autodimp h hyp); tcsp.\n  pose proof (h (k2 - k1)) as hh.\n  assert (k2 - k1 + k1 = k2) as e by omega.\n  rw e in hh; auto.\nQed.\n\nLemma if_red_to_can_k_cbv_primarg {o} :\n  forall lib k (t : @NTerm o) bs,\n    red_to_can_k lib k (oterm (NCan NCbv) (bterm [] t :: bs))\n    -> {j : nat & j < k # red_to_can_k lib j t}.\nProof.\n  induction k; introv r.\n\n  - allrw @red_to_can_0; subst.\n    inversion r.\n\n  - allrw @red_to_can_S; exrepnd.\n    destruct t as [v|f|op l].\n\n    { simpl in r1; ginv. }\n\n    { exists 0; dands; try omega.\n      apply red_to_can_0; simpl; auto. }\n\n    dopid op as [can1|ncan1|exc1|abs1] Case.\n\n    + Case \"Can\".\n      exists 0; dands; try omega.\n      rw @red_to_can_0; auto.\n\n    + Case \"NCan\".\n      rw @compute_step_ncan_ncan in r1.\n      remember (compute_step lib (oterm (NCan ncan1) l)) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @red_to_can_S; exists n; sp.\n\n    + Case \"Exc\".\n      csunf r1; allsimpl; ginv.\n      unfold red_to_can_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in r0; subst; tcsp.\n      inversion r1.\n\n    + Case \"Abs\".\n      csunf r1; allsimpl; csunf r1; allsimpl.\n      unfold on_success in r1.\n      remember (compute_step_lib lib abs1 l) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @red_to_can_S; exists n; sp.\nQed.\n\nLemma if_red_to_can_k_force_int_bound {o} :\n  forall lib a v b k (t : @NTerm o),\n    red_to_can_k\n      lib k\n      (force_int_bound v b t (uexc a))\n    -> {j : nat\n        & {z : Z\n        & reduces_in_atmost_k_steps lib t (mk_integer z) j\n        # S (S j) < k\n        # Z.abs_nat z < b}}.\nProof.\n  induction k; introv r.\n\n  - allrw @red_to_can_0; inversion r.\n\n  - allrw @red_to_can_S; exrepnd.\n    destruct t as [v1|f1|op1 bs1].\n\n    { simpl in r1; ginv. }\n\n    { csunf r1; allsimpl; ginv.\n      allunfold @apply_bterm; allsimpl; allrw @fold_subst.\n      pose proof (hasvalue_like_subst_less_bound_seq lib b v (uexc a) f1) as h.\n      autodimp h hyp; tcsp.\n      unfold red_to_can_k in r0; exrepnd.\n      exists u; dands; eauto 3 with slow. }\n\n    dopid op1 as [can1|ncan1|exc1|abs1] Case.\n\n    + Case \"Can\".\n      csunf r1; simpl in r1; ginv.\n      unfold apply_bterm, lsubst in r0; allsimpl.\n      boolvar; fold_terms.\n      destruct k.\n\n      { allrw @red_to_can_0; inversion r0. }\n\n      allrw @red_to_can_S; exrepnd; allsimpl.\n      csunf r0; allsimpl; csunf r0; allsimpl.\n      dcwf h; allsimpl.\n      unfold on_success in r0.\n      fold_terms.\n      match goal with\n        | [ H : context[compute_step_comp ?a1 ?a2 ?a3 ?a4 ?a5 ?a6 ?a7] |- _ ] =>\n          remember (compute_step_comp a1 a2 a3 a4 a5 a6 a7)  as comp\n      end.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply compute_step_compop_success_can_can in Heqcomp.\n      exrepnd; subst; allsimpl; cpx; GC.\n      repndors; exrepnd; ginv.\n      allapply @get_param_from_cop_pki; subst.\n\n      destruct k.\n\n      { allrw @red_to_can_0; inversion r1. }\n\n      allrw @red_to_can_S; exrepnd.\n      csunf r1; allsimpl.\n      boolvar; allsimpl; ginv.\n\n      * destruct k.\n\n        { allrw @red_to_can_0; inversion r0. }\n\n        allrw @red_to_can_S; exrepnd.\n        csunf r0; allsimpl.\n        dcwf h; allsimpl.\n        unfold compute_step_comp in r0; allsimpl; boolvar; ginv.\n\n        { exists 0 n1; dands; try omega; eauto 3 with slow.\n          - rw @reduces_in_atmost_k_steps_0; auto.\n          - apply abs_of_neg; auto. }\n\n        { unfold red_to_can_k in r1; exrepnd.\n          apply reduces_in_atmost_k_steps_if_isvalue_like in r1; subst; tcsp; eauto 2 with slow.\n          inversion r0. }\n\n      * dcwf h; allsimpl.\n        unfold compute_step_comp in r1; allsimpl; boolvar; ginv.\n\n        { exists 0 n1; dands; try omega; eauto 3 with slow.\n          - rw @reduces_in_atmost_k_steps_0; auto.\n          - apply abs_of_pos; auto. }\n\n        { unfold red_to_can_k in r0; exrepnd.\n          apply reduces_in_atmost_k_steps_if_isvalue_like in r0; subst; tcsp; eauto 2 with slow.\n          inversion r1. }\n\n    + Case \"NCan\".\n      unfold force_int_bound in r1.\n      rw @compute_step_mk_cbv_ncan in r1.\n      remember (compute_step lib (oterm (NCan ncan1) bs1)) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n\n      apply IHk in r0; auto; exrepnd.\n\n      exists (S j) z; dands; auto; try omega.\n      rw @reduces_in_atmost_k_steps_S; eexists; eauto.\n\n    + Case \"Exc\".\n      csunf r1; allsimpl; ginv.\n      unfold red_to_can_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in r0; subst; tcsp.\n      inversion r1.\n\n    + Case \"Abs\".\n      simpl in r1; unfold on_success in r1; csunf r1; allsimpl; csunf r1; allsimpl.\n      remember (compute_step_lib lib abs1 bs1) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n\n      apply IHk in r0; auto; exrepnd.\n\n      exists (S j) z; dands; auto; try omega.\n      rw @reduces_in_atmost_k_steps_S; eexists; eauto.\nQed.\n\n(*\nDefinition isvalue_like_except {o} a (t : @NTerm o) :=\n  isvalue_like t # !isnexc (Some a) t.\n\nDefinition has_value_like_except_k {p} lib a k (t : @NTerm p) :=\n  {u : NTerm\n   & reduces_in_atmost_k_steps lib t u k\n   # isvalue_like_except a u}.\n\nLemma has_value_like_except_0 {o} :\n  forall lib a (t : @NTerm o),\n    has_value_like_except_k lib a 0 t <=> isvalue_like_except a t.\nProof.\n  introv; unfold has_value_like_except_k; split; intro k; exrepnd.\n  - allrw @reduces_in_atmost_k_steps_0; subst; auto.\n  - exists t; allrw @reduces_in_atmost_k_steps_0; auto.\nQed.\n\nLemma has_value_like_except_S {o} :\n  forall lib k a (t : @NTerm o),\n    has_value_like_except_k lib a (S k) t\n    <=> {u : NTerm\n         & compute_step lib t = csuccess u\n         # has_value_like_except_k lib a k u}.\nProof.\n  introv; unfold has_value_like_except_k; split; intro h; exrepnd.\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    eexists; eauto.\n  - exists u0; dands; auto.\n    allrw @reduces_in_atmost_k_steps_S.\n    eexists; eauto.\nQed.\n\nLemma if_has_value_like_except_k_ncompop_can1 {o} :\n  forall lib c can bs a k (t : @NTerm o) l,\n    has_value_like_except_k\n      lib a k\n      (oterm (NCan (NCompOp c))\n             (bterm [] (oterm (Can can) bs)\n                    :: bterm [] t\n                    :: l))\n    -> {j : nat & j < k # has_value_like_except_k lib a j t}.\nProof.\n  induction k; introv r.\n  - allrw @has_value_like_except_0; repnd.\n    unfold isvalue_like_except in r; repnd.\n    inversion r0; sp.\n  - allrw @has_value_like_except_S; exrepnd.\n    destruct t as [v|op bs1]; try (complete (allsimpl; ginv)).\n    dopid op as [can2|ncan2|exc2|mrk2|abs2] Case.\n    + exists 0; dands; try omega.\n      rw @has_value_like_except_0; dands; eauto 3 with slow.\n      unfold isvalue_like_except; simpl; sp.\n    + rw @compute_step_ncompop_ncan2 in r1.\n      remember (compute_step lib (oterm (NCan ncan2) bs1)) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @has_value_like_except_S.\n      exists n; tcsp.\n    + simpl in r1; ginv.\n      exists k; sp.\n    + allsimpl; ginv.\n    + simpl in r1.\n      unfold on_success in r1.\n      remember (compute_step_lib lib abs2 bs1) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @has_value_like_except_S.\n      exists n; tcsp.\nQed.\n\nLemma if_has_value_like_except_k_narithop_can1 {o} :\n  forall lib c can bs a k (t : @NTerm o) l,\n    has_value_like_except_k\n      lib a k\n      (oterm (NCan (NArithOp c))\n             (bterm [] (oterm (Can can) bs)\n                    :: bterm [] t\n                    :: l))\n    -> {j : nat & j < k # has_value_like_except_k lib a j t}.\nProof.\n  induction k; introv r.\n  - allrw @has_value_like_except_0; repnd.\n    unfold isvalue_like_except in r; repnd.\n    inversion r0; sp.\n  - allrw @has_value_like_except_S; exrepnd.\n    destruct t as [v|op bs1]; try (complete (allsimpl; ginv)).\n    dopid op as [can2|ncan2|exc2|mrk2|abs2] Case.\n    + exists 0; dands; try omega.\n      rw @has_value_like_except_0; dands; eauto 3 with slow.\n      unfold isvalue_like_except; simpl; sp.\n    + rw @compute_step_narithop_ncan2 in r1.\n      remember (compute_step lib (oterm (NCan ncan2) bs1)) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @has_value_like_except_S.\n      exists n; tcsp.\n    + simpl in r1; ginv.\n      exists k; sp.\n    + allsimpl; ginv.\n    + simpl in r1.\n      unfold on_success in r1.\n      remember (compute_step_lib lib abs2 bs1) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @has_value_like_except_S.\n      exists n; tcsp.\nQed.\n\nLemma has_value_like_except_k_lt {o} :\n  forall lib a k1 k2 (t : @NTerm o),\n    has_value_like_except_k lib a k1 t\n    -> k1 < k2\n    -> has_value_like_except_k lib a k2 t.\nProof.\n  unfold has_value_like_except_k; introv r l; exrepnd.\n  exists u; dands; auto.\n  pose proof (no_change_after_value_like lib t k1 u) as h.\n  repeat (autodimp h hyp); tcsp.\n  { unfold isvalue_like_except in r0; sp. }\n  pose proof (h (k2 - k1)) as hh.\n  assert (k2 - k1 + k1 = k2) as e by omega.\n  rw e in hh; auto.\nQed.\n\nLemma if_has_value_like_except_k_cbv_primarg {o} :\n  forall lib a k (t : @NTerm o) bs,\n    has_value_like_except_k lib a k (oterm (NCan NCbv) (bterm [] t :: bs))\n    -> {j : nat & j < k # has_value_like_except_k lib a j t}.\nProof.\n  induction k; introv r.\n\n  - allrw @has_value_like_except_0; repnd.\n    unfold isvalue_like_except in r; repnd.\n    inversion r0; sp.\n\n  - allrw @has_value_like_except_S; exrepnd.\n    destruct t as [v|op l].\n\n    { simpl in r1; ginv. }\n\n    dopid op as [can1|ncan1|exc1|mrk1|abs1] Case.\n\n    + Case \"Can\".\n      exists 0; dands; try omega.\n      rw @has_value_like_except_0; dands; eauto 3 with slow; simpl; sp.\n      unfold isvalue_like_except; simpl; dands; eauto 3 with slow; sp.\n\n    + Case \"NCan\".\n      rw @compute_step_ncan_ncan in r1.\n      remember (compute_step lib (oterm (NCan ncan1) l)) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @has_value_like_except_S; exists n; sp.\n\n    + Case \"Exc\".\n      allsimpl; ginv.\n      unfold has_value_like_except_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in r0; subst; tcsp.\n      exists 0; dands; try omega.\n      rw @has_value_like_except_0; dands; eauto 3 with slow.\n\n    + Case \"Mrk\".\n      allsimpl; ginv.\n      unfold has_value_like_except_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_primarg_marker in r0; subst.\n      unfold isvalue_like_except in r1; repnd.\n      inversion r0; tcsp.\n\n    + Case \"Abs\".\n      allsimpl.\n      unfold on_success in r1.\n      remember (compute_step_lib lib abs1 l) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @has_value_like_except_S; exists n; sp.\nQed.\n*)\n\n(*\nLemma isvalue_like_except_integer {o} :\n  forall a z, @isvalue_like_except o a (mk_integer z).\nProof.\n  introv; unfold isvalue_like_except; simpl; sp; eauto 3 with slow.\nQed.\nHint Resolve isvalue_like_except_integer : slow.\n\nLemma isvalue_like_except_uni {o} :\n  forall a n, @isvalue_like_except o a (mk_uni n).\nProof.\n  introv; unfold isvalue_like_except; simpl; sp; eauto 3 with slow.\nQed.\nHint Resolve isvalue_like_except_uni : slow.\n\nLemma if_has_value_like_except_k_force_int_bound {o} :\n  forall lib a v b k (t : @NTerm o),\n    has_value_like_except_k\n      lib a k\n      (force_int_bound v b t (uexc a))\n    -> {j : nat\n        & {u : NTerm\n           & reduces_in_atmost_k_steps lib t u j\n           # j < k\n           # isvalue_like_except a u\n           # ({z : Z & u = mk_integer z # Z.abs_nat z < b}[+]isexc u)\n       }}.\nProof.\n  induction k; introv r.\n\n  - allrw @has_value_like_except_0; repnd.\n    unfold isvalue_like_except in r; repnd.\n    inversion r0; sp.\n\n  - allrw @has_value_like_except_S; exrepnd.\n    destruct t as [v1|op1 bs1].\n    { simpl in r1; ginv. }\n    dopid op1 as [can1|ncan1|exc1|mrk1|abs1] Case.\n\n    + Case \"Can\".\n      simpl in r1; ginv.\n      unfold apply_bterm, lsubst in r0; allsimpl.\n      boolvar; fold_terms.\n      destruct k.\n\n      { allrw @has_value_like_except_0; repnd.\n        unfold isvalue_like_except in r0; repnd.\n        inversion r1; sp. }\n\n      allrw @has_value_like_except_S; exrepnd; allsimpl.\n      unfold on_success in r0.\n      fold_terms.\n      match goal with\n        | [ H : context[compute_step_comp ?a1 ?a2 ?a3 ?a4 ?a5 ?a6 ?a7] |- _ ] =>\n          remember (compute_step_comp a1 a2 a3 a4 a5 a6 a7)  as comp\n      end.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply compute_step_compop_success_can_can in Heqcomp.\n      exrepnd; subst; allsimpl; cpx; GC.\n      repndors; exrepnd; ginv.\n      allapply @get_int_from_cop_some; subst.\n\n      destruct k.\n\n      { allrw @has_value_like_except_0; repnd.\n        unfold isvalue_like_except in r1; repnd.\n        inversion r0; sp. }\n\n      allrw @has_value_like_except_S; exrepnd.\n      boolvar; allsimpl; ginv.\n\n      * destruct k.\n\n        { allrw @has_value_like_except_0; repnd.\n          unfold isvalue_like_except in r0; repnd.\n          inversion r1; sp. }\n\n        allrw @has_value_like_except_S; exrepnd.\n        allsimpl.\n        unfold compute_step_comp in r0; allsimpl; boolvar; ginv.\n\n        { exists 0 (@mk_integer o n1); dands; try omega; eauto 3 with slow.\n          - rw @reduces_in_atmost_k_steps_0; auto.\n          - left; exists n1; dands; auto; apply abs_of_neg; auto. }\n\n        { unfold has_value_like_except_k in r1; exrepnd.\n          apply reduces_in_atmost_k_steps_if_isvalue_like in r1; subst; tcsp.\n          unfold isvalue_like_except in r0; repnd; allsimpl; boolvar; allsimpl; ginv; tcsp.\n          destruct r0; sp. }\n\n      * unfold compute_step_comp in r1; allsimpl; boolvar; ginv.\n\n        { exists 0 (@mk_integer o n1); dands; try omega; eauto 3 with slow.\n          - rw @reduces_in_atmost_k_steps_0; auto.\n          - left; exists n1; dands; auto; apply abs_of_pos; auto. }\n\n        { unfold has_value_like_except_k in r0; exrepnd.\n          apply reduces_in_atmost_k_steps_if_isvalue_like in r0; subst; tcsp.\n          unfold isvalue_like_except in r1; repnd; allsimpl; boolvar; allsimpl; ginv; tcsp.\n          destruct r1; sp. }\n\n    + Case \"NCan\".\n      unfold force_int_bound in r1.\n      rw @compute_step_mk_cbv_ncan in r1.\n      remember (compute_step lib (oterm (NCan ncan1) bs1)) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n\n      apply IHk in r0; auto; exrepnd.\n\n      exists (S j) u; dands; auto; try omega.\n      rw @reduces_in_atmost_k_steps_S; eexists; eauto.\n\n    + Case \"Exc\".\n      allsimpl; ginv.\n      unfold has_value_like_except_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in r0; subst; tcsp.\n      allsimpl; boolvar; subst; try (complete (destruct r1; sp)); GC.\n      exists 0 (oterm (Exc exc1) bs1); dands; eauto 3 with slow; try omega.\n      rw @reduces_in_atmost_k_steps_0; auto.\n\n    + Case \"Mrk\".\n      allsimpl; ginv.\n      unfold has_value_like_except_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_primarg_marker in r0; subst.\n      unfold isvalue_like_except in r1; repnd.\n      inversion r0; sp.\n\n    + Case \"Abs\".\n      simpl in r1; unfold on_success in r1.\n      remember (compute_step_lib lib abs1 bs1) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n\n      apply IHk in r0; auto; exrepnd.\n      exists (S j) u; dands; auto; try omega.\n      rw @reduces_in_atmost_k_steps_S; eexists; eauto.\nQed.\n*)\n\nLemma if_has_value_like_k_force_int_bound {o} :\n  forall lib v b k (t : @NTerm o),\n    has_value_like_k\n      lib k\n      (force_int_bound v b t (mk_vbot v))\n    -> {j : nat\n        & {u : NTerm\n           & reduces_in_atmost_k_steps lib t u j\n           # j < k\n           # isvalue_like u\n           # ({z : Z & u = mk_integer z # Z.abs_nat z < b}[+]isexc u)\n       }}.\nProof.\n  induction k; introv r.\n\n  - allrw @has_value_like_0; repnd.\n    unfold isvalue_like in r; allsimpl; sp.\n\n  - allrw @has_value_like_S; exrepnd.\n    destruct t as [v1|f1|op1 bs1].\n\n    { simpl in r1; ginv. }\n\n    { csunf r1; allsimpl; ginv.\n      allunfold @apply_bterm; allsimpl; allrw @fold_subst.\n      pose proof (hasvalue_like_subst_less_bound_seq lib b v (mk_vbot v) f1) as h.\n      autodimp h hyp; tcsp.\n      unfold has_value_like_k, computes_to_val_like_in_max_k_steps in r0; exrepnd.\n      exists u; dands; eauto 3 with slow. }\n\n    dopid op1 as [can1|ncan1|exc1|abs1] Case.\n\n    + Case \"Can\".\n      csunf r1; simpl in r1; ginv.\n      unfold apply_bterm, lsubst in r0; allsimpl.\n      boolvar; fold_terms; repndors; tcsp;\n      allrw app_nil_r;\n      try (complete (match goal with\n                       | [ H : context[fresh_var ?l] |- _ ] =>\n                         let h := fresh \"h\" in\n                         pose proof (fresh_var_not_in l) as h;\n                       unfold all_vars in h;\n                       simpl in h;\n                       repeat (rw in_app_iff in h);\n                       repeat (rw not_over_or in h);\n                       repnd; allsimpl; tcsp\n                     end));\n      GC; allrw not_over_or; repnd; allsimpl; boolvar; tcsp; GC;\n      fold_terms.\n\n      { destruct k.\n\n        { allrw @has_value_like_0; repnd.\n          unfold isvalue_like in r0; allsimpl; sp. }\n\n        allrw @has_value_like_S; exrepnd; allsimpl.\n        csunf r0; allsimpl; unfold on_success in r0.\n        csunf r0; allsimpl.\n        dcwf h; allsimpl.\n        fold_terms.\n        match goal with\n          | [ H : context[compute_step_comp ?a1 ?a2 ?a3 ?a4 ?a5 ?a6 ?a7] |- _ ] =>\n            remember (compute_step_comp a1 a2 a3 a4 a5 a6 a7)  as comp\n        end.\n        symmetry in Heqcomp; destruct comp; ginv.\n        apply compute_step_compop_success_can_can in Heqcomp.\n        exrepnd; subst; allsimpl; cpx; GC.\n        allunfold @all_vars; allsimpl.\n        repndors; exrepnd; tcsp; GC; ginv.\n        allapply @get_param_from_cop_pki; subst.\n\n        destruct k.\n\n        { allrw @has_value_like_0; repnd.\n          unfold isvalue_like in r1; allsimpl; sp. }\n\n        allrw @has_value_like_S; exrepnd.\n        csunf r1; allsimpl.\n        boolvar; allsimpl; ginv.\n\n        * destruct k.\n\n          { allrw @has_value_like_0; repnd.\n            unfold isvalue_like in r0; allsimpl; sp. }\n\n          allrw @has_value_like_S; exrepnd.\n          allsimpl.\n          csunf r0; allsimpl.\n          dcwf h; allsimpl.\n          unfold compute_step_comp in r0; allsimpl; boolvar; ginv.\n\n          { exists 0 (@mk_integer o n1); dands; try omega; eauto 3 with slow.\n            - rw @reduces_in_atmost_k_steps_0; auto.\n            - left; exists n1; dands; auto; apply abs_of_neg; auto. }\n\n          { apply has_value_like_k_vbot in r1; tcsp. }\n\n        * dcwf h; allsimpl.\n          unfold compute_step_comp in r1; allsimpl; boolvar; ginv.\n\n        { exists 0 (@mk_integer o n1); dands; try omega; eauto 3 with slow.\n          - rw @reduces_in_atmost_k_steps_0; auto.\n          - left; exists n1; dands; auto; apply abs_of_pos; auto. }\n\n        { apply has_value_like_k_vbot in r0; tcsp. }\n      }\n\n      { destruct k.\n\n        { allrw @has_value_like_0; repnd.\n          unfold isvalue_like in r0; allsimpl; sp. }\n\n        allrw @has_value_like_S; exrepnd; allsimpl.\n        csunf r0; allsimpl; csunf r0; allsimpl.\n        dcwf h; allsimpl.\n        unfold on_success in r0.\n        fold_terms.\n        match goal with\n          | [ H : context[compute_step_comp ?a1 ?a2 ?a3 ?a4 ?a5 ?a6 ?a7] |- _ ] =>\n            remember (compute_step_comp a1 a2 a3 a4 a5 a6 a7)  as comp\n        end.\n        symmetry in Heqcomp; destruct comp; ginv.\n        apply compute_step_compop_success_can_can in Heqcomp.\n        exrepnd; subst; allsimpl; cpx; GC.\n        allunfold @all_vars; allsimpl.\n        repndors; exrepnd; tcsp; GC; ginv.\n        allapply @get_param_from_cop_pki; subst.\n\n        destruct k.\n\n        { allrw @has_value_like_0; repnd.\n          unfold isvalue_like in r1; allsimpl; sp. }\n\n        allrw @has_value_like_S; exrepnd.\n        csunf r1; allsimpl.\n        boolvar; allsimpl; ginv.\n\n        * destruct k.\n\n          { allrw @has_value_like_0; repnd.\n            unfold isvalue_like in r0; allsimpl; sp. }\n\n          allrw @has_value_like_S; exrepnd.\n          allsimpl.\n          csunf r0; allsimpl.\n          dcwf h; allsimpl.\n          unfold compute_step_comp in r0; allsimpl; boolvar; ginv.\n\n          { exists 0 (@mk_integer o n1); dands; try omega; eauto 3 with slow.\n            - rw @reduces_in_atmost_k_steps_0; auto.\n            - left; exists n1; dands; auto; apply abs_of_neg; auto. }\n\n          { apply has_value_like_k_vbot in r1; tcsp. }\n\n        * dcwf h; allsimpl.\n          unfold compute_step_comp in r1; allsimpl; boolvar; ginv.\n\n        { exists 0 (@mk_integer o n1); dands; try omega; eauto 3 with slow.\n          - rw @reduces_in_atmost_k_steps_0; auto.\n          - left; exists n1; dands; auto; apply abs_of_pos; auto. }\n\n        { apply has_value_like_k_vbot in r0; tcsp. }\n      }\n\n    + Case \"NCan\".\n      unfold force_int_bound in r1.\n      rw @compute_step_mk_cbv_ncan in r1.\n      remember (compute_step lib (oterm (NCan ncan1) bs1)) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n\n      apply IHk in r0; auto; exrepnd.\n\n      exists (S j) u; dands; auto; try omega.\n      rw @reduces_in_atmost_k_steps_S; eexists; eauto.\n\n    + Case \"Exc\".\n      csunf r1; allsimpl; ginv.\n      exists 0 (oterm Exc bs1); dands; eauto 3 with slow; try omega.\n      rw @reduces_in_atmost_k_steps_0; auto.\n\n    + Case \"Abs\".\n      csunf r1; simpl in r1; unfold on_success in r1; csunf r1; allsimpl.\n      remember (compute_step_lib lib abs1 bs1) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n\n      apply IHk in r0; auto; exrepnd.\n      exists (S j) u; dands; auto; try omega.\n      rw @reduces_in_atmost_k_steps_S; eexists; eauto.\nQed.\n\nLemma compute_step_force_int_bound {o} :\n  forall lib v b e z k (t u : @NTerm o),\n    closed e\n    -> compute_step lib (force_int_bound v b t e) = csuccess u\n    -> reduces_in_atmost_k_steps lib t (mk_integer z) k\n    -> Z.abs_nat z < b\n    -> reduces_to lib u (mk_integer z).\nProof.\n  destruct t as [v1|f1|op1 bs1];[allsimpl; ginv| |];\n  introv cl comp r l; ginv.\n\n  { apply computation3.reduces_in_atmost_k_steps_if_isvalue_like in r; eauto 3 with slow; ginv. }\n\n  dopid op1 as [can1|ncan2|exc1|abs1] Case.\n\n  - Case \"Can\".\n    simpl in comp; ginv.\n    apply reduces_in_atmost_k_steps_if_isvalue_like in r; tcsp.\n    inversion r; subst.\n    csunf comp; allsimpl; ginv.\n    unfold apply_bterm, lsubst; simpl; boolvar; fold_terms; GC;\n    try (complete (provefalse; sp)).\n    destruct (Z_lt_le_dec z 0) as [i|i].\n    + apply (reduces_to_if_split2\n               _ _ (mk_less\n                      (mk_minus (mk_integer z))\n                      (mk_nat b)\n                      (mk_integer z)\n                      e));\n      try csunf; simpl; boolvar; tcsp; try omega;\n      try (rw @lsubst_aux_trivial_cl_term2; auto).\n      apply (reduces_to_if_split2\n               _ _ (mk_less\n                      (mk_integer (- z))\n                      (mk_nat b)\n                      (mk_integer z)\n                      e));\n        try csunf; simpl; boolvar; tcsp; try omega.\n      apply reduces_to_if_step.\n      csunf; simpl.\n      dcwf h; allsimpl.\n      unfold compute_step_comp; simpl; boolvar; auto.\n      provefalse.\n      pose proof (Zabs.Zabs_nat_le (Z.of_nat b) (-z)) as kk.\n      autodimp kk hyp; try omega.\n      allrw Znat.Zabs2Nat.id.\n      destruct z; allsimpl; try omega.\n    + apply (reduces_to_if_split2\n               _ _ (mk_less\n                      (mk_integer z)\n                      (mk_nat b)\n                      (mk_integer z)\n                      e));\n      try csunf; simpl; boolvar; tcsp; try omega;\n      try (rw @lsubst_aux_trivial_cl_term2; auto).\n      apply reduces_to_if_step.\n      csunf; simpl.\n      dcwf h; allsimpl.\n      unfold compute_step_comp; simpl; boolvar; auto.\n      provefalse.\n      pose proof (Zabs.Zabs_nat_le (Z.of_nat b) z) as kk.\n      autodimp kk hyp; try omega.\n      allrw Znat.Zabs2Nat.id.\n      destruct z; allsimpl; try omega.\n\n  - Case \"NCan\".\n    destruct k.\n    + allrw @reduces_in_atmost_k_steps_0; ginv.\n    + allrw @reduces_in_atmost_k_steps_S; exrepnd.\n      unfold force_int_bound in comp.\n      rw @compute_step_mk_cbv_ncan in comp.\n      rw r1 in comp; ginv; clear r1.\n      pose proof (reduces_to_prinarg\n                    lib NCbv u0 (mk_integer z)\n                    [bterm [v] (less_bound b (mk_var v) e)]) as h.\n      repeat (autodimp h hyp); eauto 3 with slow.\n      eapply reduces_to_trans;[exact h|].\n      apply (reduces_to_if_split2\n               _ _ (less_bound b (mk_integer z) e)).\n      { csunf; simpl; unfold apply_bterm, lsubst; simpl; boolvar; tcsp;\n        try (complete (provefalse; sp));\n        repeat (rw @lsubst_aux_trivial_cl_term2; auto). }\n      destruct (Z_lt_le_dec z 0) as [i|i].\n      * apply (reduces_to_if_split2\n                 _ _ (mk_less\n                        (mk_minus (mk_integer z))\n                        (mk_nat b)\n                        (mk_integer z)\n                        e));\n        try csunf; simpl; boolvar; tcsp; try omega.\n        apply (reduces_to_if_split2\n                 _ _ (mk_less\n                        (mk_integer (- z))\n                        (mk_nat b)\n                        (mk_integer z)\n                        e));\n          try csunf; simpl; boolvar; tcsp; try omega.\n        apply reduces_to_if_step.\n        csunf; simpl.\n        dcwf q; allsimpl.\n        unfold compute_step_comp; simpl; boolvar; auto.\n        provefalse.\n        pose proof (Zabs.Zabs_nat_le (Z.of_nat b) (-z)) as kk.\n        autodimp kk hyp; try omega.\n        allrw Znat.Zabs2Nat.id.\n        destruct z; allsimpl; try omega.\n      * apply (reduces_to_if_split2\n                 _ _ (mk_less\n                        (mk_integer z)\n                        (mk_nat b)\n                        (mk_integer z)\n                        e));\n        try csunf; simpl; boolvar; tcsp; try omega.\n        apply reduces_to_if_step.\n        csunf; simpl.\n        dcwf q; allsimpl.\n        unfold compute_step_comp; simpl; boolvar; auto.\n        provefalse.\n        pose proof (Zabs.Zabs_nat_le (Z.of_nat b) z) as kk.\n        autodimp kk hyp; try omega.\n        allrw Znat.Zabs2Nat.id.\n        destruct z; allsimpl; try omega.\n\n  - Case \"Exc\".\n    csunf comp; allsimpl; ginv.\n    apply reduces_in_atmost_k_steps_if_isvalue_like in r; tcsp; ginv.\n\n  - Case \"Abs\".\n    destruct k.\n    + allrw @reduces_in_atmost_k_steps_0; ginv.\n    + allrw @reduces_in_atmost_k_steps_S; exrepnd.\n      unfold force_int_bound in comp.\n      rw @compute_step_mk_cbv_abs in comp.\n      csunf r1; allsimpl.\n      rw r1 in comp; ginv; clear r1.\n      pose proof (reduces_to_prinarg\n                    lib NCbv u0 (mk_integer z)\n                    [bterm [v] (less_bound b (mk_var v) e)]) as h.\n      repeat (autodimp h hyp); eauto 3 with slow.\n      eapply reduces_to_trans;[exact h|].\n      apply (reduces_to_if_split2\n               _ _ (less_bound b (mk_integer z) e)).\n      { csunf; simpl; unfold apply_bterm, lsubst; simpl; boolvar; tcsp;\n        try (complete (provefalse; sp));\n        repeat (rw @lsubst_aux_trivial_cl_term2; auto). }\n      destruct (Z_lt_le_dec z 0) as [i|i].\n      * apply (reduces_to_if_split2\n                 _ _ (mk_less\n                        (mk_minus (mk_integer z))\n                        (mk_nat b)\n                        (mk_integer z)\n                        e));\n        try csunf; simpl; boolvar; tcsp; try omega.\n        apply (reduces_to_if_split2\n                 _ _ (mk_less\n                        (mk_integer (- z))\n                        (mk_nat b)\n                        (mk_integer z)\n                        e));\n          try csunf; simpl; boolvar; tcsp; try omega.\n        apply reduces_to_if_step.\n        csunf; simpl.\n        dcwf q; allsimpl.\n        unfold compute_step_comp; simpl; boolvar; auto.\n        provefalse.\n        pose proof (Zabs.Zabs_nat_le (Z.of_nat b) (-z)) as kk.\n        autodimp kk hyp; try omega.\n        allrw Znat.Zabs2Nat.id.\n        destruct z; allsimpl; try omega.\n      * apply (reduces_to_if_split2\n                 _ _ (mk_less\n                        (mk_integer z)\n                        (mk_nat b)\n                        (mk_integer z)\n                        e));\n        try csunf; simpl; boolvar; tcsp; try omega.\n        apply reduces_to_if_step.\n        csunf; simpl.\n        dcwf q; allsimpl.\n        unfold compute_step_comp; simpl; boolvar; auto.\n        provefalse.\n        pose proof (Zabs.Zabs_nat_le (Z.of_nat b) z) as kk.\n        autodimp kk hyp; try omega.\n        allrw Znat.Zabs2Nat.id.\n        destruct z; allsimpl; try omega.\nQed.\n\nLemma compute_step_force_int_bound_exc {o} :\n  forall lib v b a (t u e : @NTerm o),\n    compute_step lib (force_int_bound v b t a) = csuccess u\n    -> reduces_to lib t e\n    -> isexc e\n    -> reduces_to lib u e.\nProof.\n  destruct t as [v1|f1|op1 bs1];[allsimpl; ginv| |];\n  introv comp r l; ginv.\n\n  { apply reduces_to_if_isvalue_like in r; eauto 3 with slow; subst; allsimpl; tcsp. }\n\n  dopid op1 as [can1|ncan2|exc1|abs1] Case.\n\n  - Case \"Can\".\n    apply reduces_to_if_isvalue_like in r; eauto 3 with slow; subst.\n    inversion l.\n\n  - Case \"NCan\".\n    apply reduces_to_split2 in r; dorn r; subst.\n    + inversion l.\n    + exrepnd.\n      unfold force_int_bound in comp.\n      rw @compute_step_mk_cbv_ncan in comp.\n      rw r1 in comp; ginv; clear r1.\n      pose proof (reduces_to_prinarg\n                    lib NCbv v0 e\n                    [bterm [v] (less_bound b (mk_var v) a)]) as h.\n      repeat (autodimp h hyp); eauto 3 with slow.\n      eapply reduces_to_trans;[exact h|].\n      apply isexc_implies2 in l; exrepnd; subst; eauto 3 with slow.\n\n  - Case \"Exc\".\n    csunf comp; allsimpl; ginv; auto.\n\n  - Case \"Abs\".\n    apply reduces_to_split2 in r; dorn r; subst.\n    + inversion l.\n    + exrepnd.\n      unfold force_int_bound in comp.\n      rw @compute_step_mk_cbv_abs in comp.\n      csunf r1; allsimpl; rw r1 in comp; ginv; clear r1.\n      pose proof (reduces_to_prinarg\n                    lib NCbv v0 e\n                    [bterm [v] (less_bound b (mk_var v) a)]) as h.\n      repeat (autodimp h hyp); eauto 3 with slow.\n      eapply reduces_to_trans;[exact h|].\n      apply isexc_implies2 in l; exrepnd; subst; eauto 3 with slow.\nQed.\n\nLemma lsubst_aux_vterm_single {o} :\n  forall v (t : @NTerm o),\n    lsubst_aux (vterm v) [(v, t)] = t.\nProof.\n  introv; simpl; boolvar; auto.\nQed.\n\n(*\nLemma compute_step_lsubst_aux_int {o} :\n  forall lib (t u : @NTerm o) v arg z,\n    reduces_to lib arg (mk_integer z)\n    -> compute_step lib (lsubst_aux t [(v, arg)]) = csuccess u\n    -> red_to_can lib u\n    -> {t' : NTerm\n        & {x : NVar\n        & !LIn x (bound_vars t)\n        # alpha_eq t (lsubst_aux t' [(x,mk_var v)])\n        # reduces_to\n            lib u\n            (lsubst_aux (lsubst_aux t' [(x,mk_integer z)]) [(v,arg)]) }}.\nProof.\n  nterm_ind t as [y|op bs ind] Case; introv r comp rtc.\n\n  - Case \"vterm\".\n    allsimpl; boolvar; allsimpl; ginv.\n    apply reduces_to_split2 in r; dorn r; subst; allsimpl; ginv.\n\n    + exists (@mk_var o y) y; dands; simpl; boolvar; simpl; eauto 3 with slow; tcsp.\n\n    + exrepnd.\n      rw r1 in comp; ginv.\n      exists (@mk_var o y) y; dands; simpl; boolvar; simpl; eauto 3 with slow; tcsp.\n\n  - Case \"oterm\".\n    dopid op as [can|ncan|exc|mrk|abs] SCase.\n\n    + SCase \"Can\".\n      allsimpl; ginv.\n      pose proof (ex_fresh_var (all_vars (oterm (Can can) bs))) as f; exrepnd.\n      unfold all_vars in f0; allsimpl; allrw in_app_iff; allrw not_over_or; repnd.\n      exists (oterm (Can can) bs) v0; dands; auto.\n\n      * rw @lsubst_aux_trivial_cl_term; auto; simpl.\n        rw disjoint_singleton_r; auto.\n\n      * rw (lsubst_aux_trivial_cl_term (oterm (Can can) bs)); eauto 3 with slow; simpl.\n        rw disjoint_singleton_r; auto.\n\n    + SCase \"NCan\".\n      destruct bs as [|b bs]; try (complete (allsimpl; ginv)).\n      destruct b as [l t].\n      destruct l; try (complete (allsimpl; ginv)).\n      destruct t as [v1|op1 bs1]; try (complete (allsimpl; ginv)).\n\n      * destruct (deq_nvar v1 v) as [i|i]; subst;\n        [|simpl in comp; boolvar; tcsp; ginv].\n        allrw @lsubst_aux_oterm.\n        allrw map_cons.\n        allrw @lsubst_aux_bterm_nil.\n        allrw @lsubst_aux_vterm_single.\n\n        destruct arg as [va|opa bsa]; try (complete (allsimpl; ginv)).\n        dopid opa as [cana|ncana|exca|mrka|absa] SSCase.\n\n        { SSCase \"Can\".\n          apply reduces_to_if_isvalue_like in r; eauto 3 with slow.\n          inversion r; subst; fold_terms; GC.\n          dopid_noncan ncan SSSCase; try (complete (allsimpl; ginv)).\n\n          - SSSCase \"NFix\".\n            allsimpl.\n            apply compute_step_fix_success in comp; repnd; subst.\n            unfold red_to_can in rtc; exrepnd.\n            apply iscan_implies in rtc0; exrepnd; subst.\n            apply reduces_to_split2 in rtc1; dorn rtc1; exrepnd; allsimpl; ginv.\n\n          - SSSCase \"NCbv\".\n            allsimpl.\n            apply compute_step_cbv_success in comp; exrepnd; subst.\n            destruct bs; allsimpl; ginv; boolvar.\n            destruct bs; allsimpl; ginv; boolvar.\n            destruct b as [l t]; allsimpl; boolvar; ginv; allsimpl; repdors; tcsp; subst.\n\n            * pose proof (ex_fresh_var (v :: bound_vars t ++ free_vars t)) as h; exrepnd.\n              allsimpl; allrw app_nil_r; allrw in_app_iff; allrw not_over_or; repnd.\n              exists (oterm (NCan NCbv) [nobnd (mk_var v0), bterm [v] t]) v0; dands; auto.\n\n              { allrw not_over_or; sp. }\n\n              { simpl; boolvar; repndors; tcsp; subst.\n                allrw not_over_or; repnd; GC.\n                rw @lsubst_aux_trivial_cl_term; auto; simpl.\n                rw disjoint_singleton_r; auto. }\n\n              { simpl; boolvar; repndors; tcsp; subst; GC; allrw not_over_or; repnd; tcsp; GC.\n                allsimpl.\n                rw (lsubst_aux_trivial_cl_term t); simpl; tcsp.\n                rw (lsubst_aux_trivial_cl_term t); simpl; tcsp;\n                [|allrw disjoint_singleton_r; auto].\n\n            *\nAbort.\n*)\n\nLemma reduces_to_lsubst_aux_int {o} :\n  forall lib z1 z2 (b : @NTerm o) v arg,\n    disjoint (bound_vars b) (free_vars arg)\n    -> reduces_to lib arg (mk_integer z1)\n    -> reduces_to lib (lsubst_aux b [(v,arg)]) (mk_integer z2)\n    -> reduces_to lib (lsubst_aux b [(v,mk_integer z1)]) (mk_integer z2).\nProof.\n  introv d r1 r2.\n  unfold reduces_to in r2; exrepnd.\n  revert dependent arg.\n  revert dependent v.\n  revert dependent b.\n  induction k; introv d compa compf.\n\n  - allrw @reduces_in_atmost_k_steps_0; ginv.\n    destruct b as [x|f|op bs]; allsimpl; ginv.\n\n    + boolvar; ginv.\n      apply reduces_to_if_isvalue_like in compa; eauto 3 with slow; ginv; eauto 3 with slow.\n\n    + boolvar; inversion compf;\n      subst; destruct bs; allsimpl; ginv; fold_terms; GC;\n      eauto 3 with slow.\n\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n\n(*\n    nterm_ind b as [x|op bs indb] Case; ginv.\n\n    + allsimpl; boolvar; allsimpl;\n      unfold subst, lsubst; simpl; boolvar; ginv.\n      assert (reduces_to lib arg (mk_integer z2)) as r.\n      { eapply reduces_to_if_split2; eauto 3 with slow. }\n      pose proof (reduces_to_eq_val_like lib arg (mk_integer z1) (mk_integer z2)) as h.\n      repeat (autodimp h hyp); eauto 3 with slow; ginv; eauto 3 with slow.\n\n    + dopid op as [can|ncan|exc|mrk|abs] Case.\n\n      * Case \"Can\".\n        allsimpl; ginv.\n        apply reduces_in_atmost_k_steps_if_isvalue_like in compf0; eauto 3 with slow.\n        inversion compf0; subst; destruct bs; allsimpl; ginv; eauto 3 with slow.\n\n      * Case \"NCan\".\n        destruct bs as [|b bs]; try (complete (allsimpl; ginv)).\n        destruct b as [l t].\n        destruct l; try (complete (allsimpl; ginv)).\n\n        destruct t as [x|op1 bs1]; try (complete (allsimpl; ginv)).\n\n        { destruct (deq_nvar x v) as [i|i]; subst;\n          [|simpl in compf1; boolvar; tcsp; ginv].\n          rw @lsubst_aux_oterm in compf1.\n          rw map_cons in compf1.\n          rw @lsubst_aux_bterm_nil in compf1.\n          rw @lsubst_aux_vterm_single in compf1.\n\n          destruct arg as [y|opa bsa]; try (complete (allsimpl; ginv)).\n          dopid opa as [cana|ncana|exca|mrka|absa] SCase.\n\n          - SCase \"Can\".\n            apply reduces_to_if_isvalue_like in compa; eauto 3 with slow.\n            inversion compa; subst; fold_terms; GC.\n            dopid_noncan ncan SSCase; try (complete (allsimpl; ginv)).\n\n            + SSCase \"NFix\".\n              allsimpl.\n              apply compute_step_fix_success in compf1; repnd; subst.\n              provefalse.\n              apply reduces_in_atmost_k_steps_implies_reduces_to in compf0.\n              apply reduces_to_split2 in compf0; dorn compf0; exrepnd; allsimpl; ginv.\n\n            + SSCase \"NCbv\".\n              simpl in compf1.\n              apply compute_step_cbv_success in compf1; exrepnd; subst.\n              destruct bs; allsimpl; ginv; boolvar.\n              destruct bs; allsimpl; ginv; boolvar.\n              destruct b as [l t]; allsimpl; boolvar; ginv; allsimpl; repdors; tcsp; subst.\n\n              * apply (reduces_to_if_split2\n                         _ _ (subst (lsubst_aux t []) v (mk_integer z1)));\n                eauto 3 with slow.\n\n              * allrw not_over_or; repnd; GC.\n                apply (reduces_to_if_split2\n                         _ _ (subst (lsubst_aux t [(v, mk_integer z1)]) v0 (mk_integer z1)));\n                  eauto 3 with slow.\n\n            + SSCase \"NSleep\".\n              allsimpl.\n              apply compute_step_sleep_success in compf1; exrepnd; subst.\n              apply reduces_in_atmost_k_steps_implies_reduces_to in compf0.\n              apply reduces_to_if_isvalue_like in compf0; eauto 3 with slow; ginv.\n\n            + SSCase \"NTUni\".\n              allsimpl.\n              apply compute_step_tuni_success in compf1; exrepnd; subst.\n              apply reduces_in_atmost_k_steps_implies_reduces_to in compf0.\n              apply reduces_to_if_isvalue_like in compf0; eauto 3 with slow; ginv.\n\n            + SSCase \"NMinus\".\n              allsimpl.\n              apply compute_step_minus_success in compf1; exrepnd; subst; ginv.\n              apply reduces_in_atmost_k_steps_implies_reduces_to in compf0.\n              apply reduces_to_if_isvalue_like in compf0; eauto 3 with slow; ginv.\n              destruct bs; allsimpl; ginv; fold_terms; GC; ginv.\n              boolvar; eauto 3 with slow.\n\n            + SSCase \"NTryCatch\".\n              allsimpl.\n              apply compute_step_try_success in compf1; exrepnd; subst; allsimpl.\n              apply reduces_in_atmost_k_steps_implies_reduces_to in compf0.\n              apply reduces_to_if_isvalue_like in compf0; eauto 3 with slow; ginv.\n              inversion compf0; subst; fold_terms; GC.\n              boolvar.\n              destruct bs; allsimpl; ginv.\n              destruct bs; allsimpl; ginv.\n              destruct b; allsimpl.\n              destruct l; allsimpl; cpx; allsimpl.\n              boolvar; allsimpl; ginv; repndors; tcsp; subst; eauto 3 with slow.\n\n            + SSCase \"NCompOp\".\n              destruct bs; try (complete (allsimpl; ginv)).\n              destruct b as [l t].\n              destruct l; destruct t as [v1|op1 bs1]; try (complete (allsimpl; ginv)).\n\n              * destruct (deq_nvar v1 v) as [i|i]; subst;\n                [|allsimpl; boolvar; tcsp; complete ginv].\n                rw map_cons in compf1.\n                rw @lsubst_aux_bterm_nil in compf1.\n                rw @lsubst_aux_vterm_single in compf1.\n                simpl in compf1.\n                apply compute_step_compop_success_can_can in compf1; exrepnd; GC.\n                destruct bs; try (complete (allsimpl; ginv)).\n                destruct bs; try (complete (allsimpl; ginv)).\n                destruct bs; try (complete (allsimpl; ginv)).\n                allsimpl; cpx; boolvar.\n                destruct b as [l3 t3]; allsimpl; ginv.\n                destruct l3; allsimpl; ginv.\n                destruct b0 as [l4 t4]; allsimpl; ginv.\n                destruct l4; allsimpl; ginv.\n                cpx; fold_terms; GC.\n                apply reduces_in_atmost_k_steps_implies_reduces_to in compf0.\n                repndors; exrepnd; subst; ginv; eauto 3 with slow.\n\n                { eapply reduces_to_if_split2; eauto; simpl.\n                  unfold compute_step_comp; simpl; auto. }\n\n                { eapply reduces_to_if_split2; eauto; simpl.\n                  unfold compute_step_comp; simpl; auto. }\n\n              * allrw map_cons.\n                allrw @lsubst_aux_bterm_nil.\n                dopid op1 as [can1|ncan1|exc1|mrk1|abs1] SSSSCase.\n\n                { SSSSCase \"Can\".\n                  simpl in compf1.\n                  apply compute_step_compop_success_can_can in compf1; exrepnd; GC.\n                  destruct bs1; allsimpl; cpx; GC.\n                  destruct bs; allsimpl; cpx; GC.\n                  destruct bs; allsimpl; cpx; GC.\n                  destruct bs; allsimpl; cpx; GC.\n                  allsimpl; cpx; boolvar.\n                  destruct b as [l3 t3]; allsimpl; ginv.\n                  destruct l3; allsimpl; ginv.\n                  destruct b0 as [l4 t4]; allsimpl; ginv.\n                  destruct l4; allsimpl; ginv.\n                  cpx; fold_terms; ginv; GC.\n                  apply reduces_in_atmost_k_steps_implies_reduces_to in compf0.\n                  repndors; exrepnd; subst; ginv; eauto 3 with slow.\n\n                  { eapply reduces_to_if_split2; eauto; simpl.\n                    allapply @get_int_from_cop_some; subst; allsimpl.\n                    unfold compute_step_comp; simpl; auto. }\n\n                  { eapply reduces_to_if_split2; eauto; simpl.\n                    allapply @get_int_from_cop_some; subst; allsimpl.\n                    unfold compute_step_comp; simpl; auto. }\n                }\n\n                { SSSSCase \"NCan\".\n                  rw @lsubst_aux_oterm in compf1.\n                  unfold_all_mk; allunfold @mk_integer.\n                  rw @compute_step_ncompop_ncan2 in compf1.\n                  match goal with\n                    | [ H : context[compute_step ?a1 ?a2] |- _ ] =>\n                      remember (compute_step a1 a2) as comp\n                  end.\n                  symmetry in Heqcomp; destruct comp; ginv.\n*)\n\nAbort.\n\n(*\nLemma reduces_to_apply_int {o} :\n  forall lib z1 z2 (f arg : @NTerm o),\n    reduces_to lib arg (mk_integer z1)\n    -> reduces_to lib (mk_apply f arg) (mk_integer z2)\n    -> reduces_to lib (mk_apply f (mk_integer z1)) (mk_integer z2).\nProof.\n  introv r1 r2.\n  unfold reduces_to in r2; exrepnd.\n  revert dependent arg.\n  revert dependent f.\n  induction k; introv compa compf.\n\n  - allrw @reduces_in_atmost_k_steps_0; ginv.\n\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    simpl in compf1.\n    destruct f as [v|f|op bs]; ginv.\n\n    { csunf compf1; allsimpl; ginv.\n\nXXXXXXXXXX\n\n      eapply reduces_to_trans;[|eauto].\n      eapply reduces_to_if_split2;[csunf; simpl; eauto|].\n      apply implies_eapply_red_aux; eauto 3 with slow.\n    }\n\n    dopid op as [can|ncan|exc|abs] Case.\n\n    + Case \"Can\".\n      csunf compf1; allsimpl.\n      apply compute_step_apply_success in compf1; exrepnd; subst.\n      fold_terms; ginv.\n\nAbort.\n*)\n\nLemma reduces_to_force_int_bound_app_z {o} :\n  forall lib v b e z (t f : @NTerm o),\n    closed e\n    -> !LIn v (free_vars f)\n    -> Z.abs_nat z < b\n    -> reduces_to lib t (mk_integer z)\n    -> reduces_to lib (force_int_bound_app v b t f e)\n                  (mk_apply f (mk_integer z)).\nProof.\n  introv cl ni l r.\n  pose proof (reduces_to_prinarg\n                lib NCbv\n                (force_int_bound v b t e)\n                (mk_integer z)\n                [bterm [v] (mk_apply f (mk_var v))]) as h.\n  fold_terms.\n  autodimp h hyp.\n\n  - pose proof (reduces_to_prinarg\n                  lib NCbv\n                  t\n                  (mk_integer z)\n                  [bterm [v] (less_bound b (mk_var v) e)]) as h.\n    fold_terms.\n    autodimp h hyp.\n\n    + eapply reduces_to_trans; eauto.\n      apply (reduces_to_if_split2\n               _ _ (less_bound b (mk_integer z) e)).\n\n      * csunf; simpl; unfold apply_bterm, lsubst; simpl; boolvar; auto;\n        try (complete (provefalse; sp));\n        repeat (rw @lsubst_aux_trivial_cl_term2; auto).\n\n      * destruct (Z_lt_le_dec z 0).\n\n        { apply (reduces_to_if_split2\n                   _ _ (mk_less (mk_minus (mk_integer z))\n                                (mk_nat b)\n                                (mk_integer z)\n                                e)); auto;\n          [csunf; simpl; boolvar; tcsp; try omega|].\n\n          apply (reduces_to_if_split2\n                   _ _ (mk_less (mk_integer (- z))\n                                (mk_nat b)\n                                (mk_integer z)\n                                e)); try csunf; auto.\n          apply reduces_to_if_step; simpl.\n          csunf; simpl.\n          dcwf q; allsimpl.\n          unfold compute_step_comp; simpl; boolvar; tcsp.\n          pose proof (Zabs.Zabs_nat_le (Z.of_nat b) (- z)) as k.\n          autodimp k hyp; try omega.\n          allrw Znat.Zabs2Nat.id.\n          destruct z; allsimpl; try omega. }\n\n        { apply (reduces_to_if_split2\n                   _ _ (mk_less (mk_integer z)\n                                (mk_nat b)\n                                (mk_integer z)\n                                e)); auto;\n          [csunf; simpl; boolvar; tcsp; try omega|].\n          apply reduces_to_if_step; simpl.\n          csunf; simpl.\n          dcwf q; allsimpl.\n          unfold compute_step_comp; simpl; boolvar; tcsp.\n          pose proof (Zabs.Zabs_nat_le (Z.of_nat b) z) as k.\n          autodimp k hyp; try omega.\n          allrw Znat.Zabs2Nat.id.\n          destruct z; allsimpl; try omega. }\n\n  - eapply reduces_to_trans; eauto.\n    apply reduces_to_if_step; simpl.\n    csunf; simpl.\n    unfold apply_bterm, lsubst; simpl; boolvar; tcsp;\n    try (complete (provefalse; sp)).\n\n    rw @lsubst_aux_trivial_cl_term; auto; simpl.\n    rw disjoint_singleton_r; auto.\nQed.\n\nLemma differ3_alpha_integer {o} :\n  forall b f g z (t : @NTerm o),\n    differ3_alpha b f g (mk_integer z) t\n    -> t = mk_integer z.\nProof.\n  introv d.\n  unfold differ3_alpha in d; exrepnd.\n  inversion d0; subst; allsimpl; cpx; fold_terms.\n  inversion d1; subst; allsimpl; cpx.\n  inversion d2; allsimpl; cpx.\nQed.\n\nLemma differ3_alpha_exc {o} :\n  forall b f g (e t : @NTerm o),\n    differ3_alpha b f g e t\n    -> isexc e\n    -> isexc t.\nProof.\n  introv d i.\n  unfold differ3_alpha in d; exrepnd.\n  apply isexc_implies2 in i; exrepnd; subst.\n  inversion d0; subst; allsimpl; cpx; fold_terms.\n  inversion d1; subst; allsimpl; cpx.\n  inversion d2; allsimpl; subst; boolvar; subst; tcsp.\nQed.\n\n(*\nLemma differ3_alpha_exc {o} :\n  forall x b f g (e t : @NTerm o),\n    differ3_alpha b f g e t\n    -> isnexc x e\n    -> isnexc x t.\nProof.\n  introv d i.\n  unfold differ3_alpha in d; exrepnd.\n  apply isnexc_implies in i; exrepnd; subst.\n  inversion d0; subst; allsimpl; cpx; fold_terms.\n  inversion d1; subst; allsimpl; cpx.\n  inversion d2; allsimpl; subst; boolvar; subst; tcsp.\nQed.\n*)\n\n(*\nLemma isvalue_like_except_can {o} :\n  forall a c (bs : list (@BTerm o)), @isvalue_like_except o a (oterm (Can c) bs).\nProof.\n  introv; unfold isvalue_like_except; simpl; sp; eauto 3 with slow.\nQed.\nHint Resolve isvalue_like_except_can : slow.\n*)\n\n(*\nLemma isvalue_like_except_exc {o} :\n  forall a e (bs : list (@BTerm o)),\n    !LIn a (get_utokens_en e)\n    -> isvalue_like_except a (oterm (Exc e) bs).\nProof.\n  introv; unfold isvalue_like_except; simpl; sp; eauto 3 with slow.\n  boolvar; tcsp.\n  destruct e; ginv; allsimpl; tcsp.\nQed.\nHint Resolve isvalue_like_except_exc : slow.\n*)\n\n(*\nLemma if_has_value_like_except_k_ncan_primarg {o} :\n  forall lib a ncan k (t : @NTerm o) bs,\n    !LIn a (get_utokens_nc ncan)\n    -> has_value_like_except_k lib a k (oterm (NCan ncan) (bterm [] t :: bs))\n    -> {j : nat & j < k # has_value_like_except_k lib a j t}.\nProof.\n  induction k; introv ni r.\n\n  - allrw @has_value_like_except_0.\n    unfold isvalue_like_except in r; repnd.\n    inversion r0; tcsp.\n\n  - allrw @has_value_like_except_S; exrepnd.\n    destruct t as [v|op l].\n\n    { simpl in r1; ginv. }\n\n    dopid op as [can1|ncan1|exc1|mrk1|abs1] Case.\n\n    + Case \"Can\".\n      exists 0; dands; try omega.\n      rw @has_value_like_except_0; eauto 3 with slow.\n\n    + Case \"NCan\".\n      rw @compute_step_ncan_ncan in r1.\n      remember (compute_step lib (oterm (NCan ncan1) l)) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply IHk in r0; exrepnd; auto.\n      exists (S j); dands; try omega.\n      rw @has_value_like_except_S.\n      exists n; sp.\n\n    + Case \"Exc\".\n      allsimpl.\n      apply compute_step_catch_success in r1.\n      dorn r1; exrepnd; subst; allsimpl.\n\n      * exists 0; dands; try omega.\n        rw @has_value_like_except_0; eauto 3 with slow.\n\n      * exists 0; dands; try omega.\n        unfold has_value_like_except_k in r0; exrepnd.\n        apply reduces_in_atmost_k_steps_if_isvalue_like in r0; eauto 3 with slow; subst.\n        unfold isvalue_like_except in r1; repnd; allsimpl; boolvar; tcsp;\n        try (complete (destruct r1; sp)); GC.\n        rw @has_value_like_except_0; eauto 3 with slow.\n        apply isvalue_like_except_exc; simpl.\n        destruct exc1; allsimpl; tcsp.\n        intro j; dorn j; tcsp; subst; sp.\n\n    + Case \"Mrk\".\n      allsimpl; ginv.\n      unfold has_value_like_except_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_primarg_marker in r0; subst.\n      unfold isvalue_like_except in r1; repnd.\n      inversion r0; sp.\n\n    + Case \"Abs\".\n      allsimpl.\n      unfold on_success in r1.\n      remember (compute_step_lib lib abs1 l) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply IHk in r0; exrepnd; auto.\n      exists (S j); dands; try omega.\n      rw @has_value_like_except_S.\n      exists n; sp.\nQed.\n*)\n\nLemma differ3_alpha_mk_atom_eq {o} :\n  forall b f g (a1 a2 b1 b2 c1 c2 d1 d2 : @NTerm o),\n    differ3_alpha b f g a1 a2\n    -> differ3_alpha b f g b1 b2\n    -> differ3_alpha b f g c1 c2\n    -> differ3_alpha b f g d1 d2\n    -> differ3_alpha b f g (mk_atom_eq a1 b1 c1 d1) (mk_atom_eq a2 b2 c2 d2).\nProof.\n  introv da1 da2 da3 da4.\n  allunfold @differ3_alpha; exrepnd.\n  exists (mk_atom_eq u6 u4 u0 u1) (mk_atom_eq u7 u5 u3 u2); dands; auto.\n  - apply alpha_eq_oterm_combine; simpl; dands; auto.\n    introv i; repndors; cpx; auto; apply alphaeqbt_nilv2; auto.\n  - apply alpha_eq_oterm_combine; simpl; dands; auto.\n    introv i; repndors; cpx; auto; apply alphaeqbt_nilv2; auto.\n  - constructor; simpl; auto.\n    introv i; repndors; cpx; constructor; auto.\nQed.\nHint Resolve differ3_alpha_mk_atom_eq : slow.\n\nLemma differ3_alpha_mk_exception {o} :\n  forall b f g (a1 a2 b1 b2 : @NTerm o),\n    differ3_alpha b f g a1 a2\n    -> differ3_alpha b f g b1 b2\n    -> differ3_alpha b f g (mk_exception a1 b1) (mk_exception a2 b2).\nProof.\n  introv da1 da2.\n  allunfold @differ3_alpha; exrepnd.\n  exists (mk_exception u0 u1) (mk_exception u3 u2); dands; auto.\n  - apply alpha_eq_oterm_combine; simpl; dands; auto.\n    introv i; repndors; cpx; auto; apply alphaeqbt_nilv2; auto.\n  - apply alpha_eq_oterm_combine; simpl; dands; auto.\n    introv i; repndors; cpx; auto; apply alphaeqbt_nilv2; auto.\n  - constructor; simpl; auto.\n    introv i; repndors; cpx; constructor; auto.\nQed.\nHint Resolve differ3_alpha_mk_exception : slow.\n\nLemma differ3_preserves_isvalue_like {o} :\n  forall b f g (t1 t2 : @NTerm o),\n    differ3 b f g t1 t2\n    -> isvalue_like t1\n    -> isvalue_like t2.\nProof.\n  introv d ivl.\n  allunfold @isvalue_like; exrepnd.\n  repndors;[left|right].\n  - apply iscan_implies in ivl; repndors; exrepnd; subst;\n    inversion d; subst; eauto 3 with slow.\n  - apply isexc_implies2 in ivl; exrepnd; subst.\n    inversion d; subst; eauto 3 with slow.\nQed.\n\nLemma differ3_alpha_mk_fresh {o} :\n  forall b f g v (t1 t2 : @NTerm o),\n    !LIn v (free_vars f)\n    -> !LIn v (free_vars g)\n    -> differ3_alpha b f g t1 t2\n    -> differ3_alpha b f g (mk_fresh v t1) (mk_fresh v t2).\nProof.\n  introv ni1 ni2 d.\n  allunfold @differ3_alpha; exrepnd.\n  exists (mk_fresh v u1) (mk_fresh v u2); dands;\n  try (apply implies_alpha_eq_mk_fresh; eauto 3 with slow).\n  constructor; simpl; auto; introv i; repndors; cpx.\n  constructor; auto; apply disjoint_singleton_l; auto.\nQed.\nHint Resolve differ3_alpha_mk_fresh : slow.\n\nDefinition differ3_b_alpha {o} (b : nat) f g (b1 b2 : @BTerm o) :=\n  {u1 : BTerm\n   & {u2 : BTerm\n      & alpha_eq_bterm b1 u1\n      # alpha_eq_bterm b2 u2\n      # differ3_b b f g u1 u2}}.\n\nDefinition differ3_bs_alpha {o} b f g (bs1 bs2 : list (@BTerm o)) :=\n  br_bterms (differ3_b_alpha b f g) bs1 bs2.\n\nLemma differ3_bterms_nil {o} :\n  forall b f g, @differ3_bterms o b f g [] [].\nProof.\n  unfold differ3_bterms, br_bterms, br_list; simpl; sp.\nQed.\nHint Resolve differ3_bterms_nil : slow.\n\nLemma differ3_bterms_cons_if {o} :\n  forall b f g (b1 b2 : @BTerm o) bs1 bs2,\n    differ3_b b f g b1 b2\n    -> differ3_bterms b f g bs1 bs2\n    -> differ3_bterms b f g (b1 :: bs1) (b2 :: bs2).\nProof.\n  introv d1 d2; apply differ3_bterms_cons; sp.\nQed.\nHint Resolve differ3_bterms_cons_if : slow.\n\nLemma implies_differ3_alpha_oterm {o} :\n  forall b f g op (bs1 bs2 : list (@BTerm o)),\n    differ3_bs_alpha b f g bs1 bs2\n    -> differ3_alpha b f g (oterm op bs1) (oterm op bs2).\nProof.\n  introv diff.\n  unfold differ3_bs_alpha, br_bterms, br_list in diff; repnd.\n\n  assert {bs1' : list BTerm\n          & {bs2' : list BTerm\n          & alpha_eq_bterms bs1 bs1'\n          # alpha_eq_bterms bs2 bs2'\n          # differ3_bterms b f g bs1' bs2'}} as hbs.\n  { revert dependent bs2.\n    induction bs1; introv len imp; destruct bs2; allsimpl; cpx; GC.\n    - exists ([] : list (@BTerm o)) ([] : list (@BTerm o)); dands; eauto 3 with slow.\n    - pose proof (imp a b0) as h; autodimp h hyp.\n      pose proof (IHbs1 bs2) as k; repeat (autodimp k hyp).\n      exrepnd.\n      unfold differ3_b_alpha in h; exrepnd.\n      exists (u1 :: bs1') (u2 :: bs2'); dands; eauto 3 with slow. }\n\n  exrepnd.\n  applydup @alpha_eq_bterms_implies_same_length in hbs0.\n  applydup @alpha_eq_bterms_implies_same_length in hbs2.\n  exists (oterm op bs1') (oterm op bs2'); dands; auto.\n\n  - apply alpha_eq_oterm_combine; dands; tcsp.\n    introv i; apply hbs0; auto.\n\n  - apply alpha_eq_oterm_combine; dands; tcsp.\n    introv i; apply hbs2; auto.\n\n  - constructor; try omega.\n    introv i; apply hbs1; auto.\nQed.\n\nLemma differ3_alpha_pushdown_fresh_isvalue_like {o} :\n  forall b f g v (t1 t2 : @NTerm o),\n    !LIn v (free_vars f)\n    -> !LIn v (free_vars g)\n    -> isvalue_like t1\n    -> differ3 b f g t1 t2\n    -> differ3_alpha b f g (pushdown_fresh v t1) (pushdown_fresh v t2).\nProof.\n  introv nif nig ivl d.\n  destruct t1 as [v1|f1|op1 bs1].\n  - inversion d; allsimpl; subst; allsimpl; eauto 3 with slow.\n  - inversion d; allsimpl; subst; allsimpl; eauto 3 with slow.\n  - inversion d as [? ? d1 d2|?|?|? ? ? len imp d1]; subst; allsimpl; fold_terms; clear d.\n    + unfold isvalue_like in ivl; repndors; inversion ivl.\n    + apply implies_differ3_alpha_oterm.\n      unfold differ3_bs_alpha, br_bterms, br_list.\n      allrw @length_mk_fresh_bterms; dands; auto.\n      introv i.\n      unfold mk_fresh_bterms in i; allrw <- @map_combine; allrw in_map_iff; exrepnd; cpx; allsimpl.\n      applydup imp in i1.\n      destruct a0 as [l1 t1].\n      destruct a as [l2 t2].\n      inversion i0 as [? ? ? d]; subst; clear i0.\n      simpl.\n      unfold maybe_new_var; boolvar.\n\n      * pose proof (ex_fresh_var (all_vars t1 ++ all_vars t2 ++ all_vars f ++ all_vars g)) as fv; exrepnd.\n        allrw in_app_iff; allrw not_over_or; repnd.\n        exists (bterm l2 (mk_fresh v0 t1)) (bterm l2 (mk_fresh v0 t2)).\n        dands; auto.\n\n        { apply alpha_eq_bterm_congr.\n          apply (implies_alpha_eq_mk_fresh_sub v0); allrw in_app_iff; tcsp.\n          repeat (rw @lsubst_trivial3); allsimpl; auto.\n          - introv i; repndors; tcsp; cpx; allsimpl; allrw disjoint_singleton_l.\n            dands; auto.\n          - introv i; repndors; tcsp; cpx; allsimpl; allrw disjoint_singleton_l.\n            dands; auto.\n            apply newvar_prop. }\n\n        { apply alpha_eq_bterm_congr.\n          apply (implies_alpha_eq_mk_fresh_sub v0); allrw in_app_iff; tcsp.\n          repeat (rw @lsubst_trivial3); allsimpl; auto.\n          - introv i; repndors; tcsp; cpx; allsimpl; allrw disjoint_singleton_l.\n            dands; auto.\n          - introv i; repndors; tcsp; cpx; allsimpl; allrw disjoint_singleton_l.\n            dands; auto.\n            apply newvar_prop. }\n\n        { constructor; auto; constructor; simpl; auto.\n          introv i; repndors; cpx.\n          constructor; allrw disjoint_singleton_l; auto. }\n\n      * exists (bterm l2 (mk_fresh v t1)) (bterm l2 (mk_fresh v t2)).\n        dands; auto.\n        constructor; auto; constructor; auto.\n        introv i; allsimpl; repndors; cpx.\n        constructor; allrw disjoint_singleton_l; auto.\nQed.\n\nLemma differ3_preserves_isnoncan_like {o} :\n  forall (b : nat) f g (t1 t2 : @NTerm o),\n    differ3 b f g t1 t2\n    -> isnoncan_like t1\n    -> isnoncan_like t2.\nProof.\n  introv d isn.\n  allunfold @isnoncan_like; exrepnd.\n  repndors;[left|right].\n  - apply isnoncan_implies in isn; exrepnd; subst.\n    inversion d; subst; eauto 3 with slow.\n    unfold force_int_bound_app, mk_cbv; eauto 3 with slow.\n  - apply isabs_implies in isn; exrepnd; subst.\n    inversion d; subst; eauto 3 with slow.\nQed.\n\nLemma differ3_alpha_l {o} :\n  forall b f g (t1 t2 t3 : @NTerm o),\n    alpha_eq t1 t2\n    -> differ3_alpha b f g t2 t3\n    -> differ3_alpha b f g t1 t3.\nProof.\n  introv aeq d.\n  allunfold @differ3_alpha; exrepnd.\n  exists u1 u2; dands; eauto 3 with slow.\nQed.\n\nLemma differ3_alpha_r {o} :\n  forall b f g (t1 t2 t3 : @NTerm o),\n    differ3_alpha b f g t1 t2\n    -> alpha_eq t2 t3\n    -> differ3_alpha b f g t1 t3.\nProof.\n  introv aeq d.\n  allunfold @differ3_alpha; exrepnd.\n  exists u1 u2; dands; eauto 3 with slow.\nQed.\n\nLemma in_bound_vars_utok_sub {o} :\n  forall v (t : @NTerm o) sub,\n    LIn (v,t) sub\n    -> subset (bound_vars t) (bound_vars_utok_sub sub).\nProof.\n  induction sub; introv i; allsimpl; tcsp.\n  destruct a; repndors; cpx; eauto 3 with slow.\nQed.\n\nLemma in_free_vars_utok_sub {o} :\n  forall v (t : @NTerm o) sub,\n    LIn (v,t) sub\n    -> subset (free_vars t) (free_vars_utok_sub sub).\nProof.\n  induction sub; introv i; allsimpl; tcsp.\n  destruct a; repndors; cpx; eauto 3 with slow.\nQed.\n\nLemma differ3_subst_utokens_aux {o} :\n  forall b f g (t1 t2 : @NTerm o) sub,\n    disjoint (bound_vars t1) (free_vars_utok_sub sub)\n    -> disjoint (bound_vars t2) (free_vars_utok_sub sub)\n    -> disjoint (free_vars f) (bound_vars_utok_sub sub)\n    -> disjoint (free_vars g) (bound_vars_utok_sub sub)\n    -> disjoint (get_utokens f) (utok_sub_dom sub)\n    -> disjoint (get_utokens g) (utok_sub_dom sub)\n    -> differ3 b f g t1 t2\n    -> differ3 b f g (subst_utokens_aux t1 sub) (subst_utokens_aux t2 sub).\nProof.\n  nterm_ind t1 as [v1|f1|op1 bs1 ind1] Case; introv disj1 disj2 dff dfg duf dug d.\n\n  - Case \"vterm\".\n    inversion d; subst; allsimpl; eauto 3 with slow.\n\n  - Case \"sterm\".\n    inversion d; subst; allsimpl; eauto 3 with slow.\n\n  - Case \"oterm\".\n    inversion d as [? ? ? ? ? ni1 ni2 d1 a1 a2|?|?|? ? ? len1 imp1]; subst; clear d.\n\n    + allsimpl; allrw app_nil_r; fold_terms.\n      allrw disjoint_app_l; allrw disjoint_cons_l; repnd.\n      constructor; auto.\n\n      * pose proof (ind1 (force_int_bound v b t1 (mk_vbot v)) []) as q; clear ind1; autodimp q hyp.\n        pose proof (q (force_int_bound v b t0 (mk_vbot v)) sub) as ih; clear q; allsimpl.\n        allrw disjoint_app_l; allrw disjoint_cons_l.\n        repeat (autodimp ih hyp).\n\n        { constructor; simpl; auto.\n          introv i; repndors; cpx; tcsp.\n          - constructor; auto.\n          - constructor; allrw disjoint_singleton_l; auto.\n            constructor; simpl; auto.\n            introv i; repndors; cpx; tcsp; constructor; auto; constructor; simpl; auto;\n            introv i; repndors; cpx; tcsp; constructor; auto; constructor; simpl; auto;\n            introv i; repndors; cpx; tcsp; constructor; auto; allrw disjoint_singleton_l; auto.\n        }\n\n        { inversion ih as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear ih.\n          pose proof (imp (bterm [] (subst_utokens_aux t1 sub)) (bterm [] (subst_utokens_aux t0 sub))) as q.\n          autodimp q hyp.\n          inversion q; auto.\n        }\n\n      * rw @trivial_subst_utokens_aux; auto.\n        apply alphaeq_preserves_utokens in a1; rw <- a1; auto.\n\n      * rw @trivial_subst_utokens_aux; auto.\n        apply alphaeq_preserves_utokens in a2; rw <- a2; auto.\n\n    + allrw @subst_utokens_aux_oterm; allsimpl.\n      remember (get_utok op1) as guo1; symmetry in Heqguo1; destruct guo1.\n\n      * unfold subst_utok.\n        remember (utok_sub_find sub g0) as sf; symmetry in Heqsf; destruct sf; eauto 3 with slow.\n        { apply utok_sub_find_some in Heqsf.\n          apply differ3_refl; auto; apply in_bound_vars_utok_sub in Heqsf; eauto 3 with slow. }\n        constructor; allrw map_length; auto.\n        introv i; allrw <- @map_combine; allrw in_map_iff; exrepnd; cpx; allsimpl.\n        applydup imp1 in i1; applydup in_combine in i1; repnd.\n        disj_flat_map.\n        destruct a0 as [l1 u1].\n        destruct a as [l2 u2].\n        allsimpl; allrw disjoint_app_l; repnd.\n        inversion i0 as [? ? ? d1]; subst; clear i0.\n        constructor; auto.\n\n        pose proof (ind1 u1 l2) as q; autodimp q hyp.\n\n      * constructor; allrw map_length; auto.\n        introv i; allrw <- @map_combine; allrw in_map_iff; exrepnd; cpx; allsimpl.\n        applydup imp1 in i1; applydup in_combine in i1; repnd.\n        disj_flat_map.\n        destruct a0 as [l1 u1].\n        destruct a as [l2 u2].\n        allsimpl; allrw disjoint_app_l; repnd.\n        inversion i0 as [? ? ? d1]; subst; clear i0.\n        constructor; auto.\n\n        pose proof (ind1 u1 l2) as q; autodimp q hyp.\nQed.\n\nLemma differ3_alpha_subst_utokens {o} :\n  forall b f g (t1 t2 : @NTerm o) sub,\n    disjoint (free_vars f) (bound_vars_utok_sub sub)\n    -> disjoint (free_vars g) (bound_vars_utok_sub sub)\n    -> disjoint (get_utokens f) (utok_sub_dom sub)\n    -> disjoint (get_utokens g) (utok_sub_dom sub)\n    -> differ3_alpha b f g t1 t2\n    -> differ3_alpha b f g (subst_utokens t1 sub) (subst_utokens t2 sub).\nProof.\n  introv disj1 disj2 disj3 disj4 d.\n  unfold differ3_alpha in d; exrepnd.\n\n  eapply differ3_alpha_l;[eapply alpha_eq_subst_utokens_same;exact d0|].\n  eapply differ3_alpha_r;[|apply alpha_eq_sym;eapply alpha_eq_subst_utokens_same;exact d2].\n  clear dependent t1.\n  clear dependent t2.\n\n  pose proof (differ3_change_bound_vars\n                b f g (free_vars_utok_sub sub)\n                u1 u2 d1) as d; exrepnd.\n  rename u0 into t1.\n  rename u3 into t2.\n\n  eapply differ3_alpha_l;[eapply alpha_eq_subst_utokens_same;exact d3|].\n  eapply differ3_alpha_r;[|apply alpha_eq_sym;eapply alpha_eq_subst_utokens_same;exact d4].\n  clear dependent u1.\n  clear dependent u2.\n\n  pose proof (unfold_subst_utokens sub t1) as h; exrepnd.\n  pose proof (unfold_subst_utokens sub t2) as k; exrepnd.\n  rename t' into u1.\n  rename t'0 into u2.\n  rw h0; rw k0.\n\n  eapply differ3_alpha_l;[apply (alpha_eq_subst_utokens_aux u1 t1 sub sub); eauto 3 with slow|].\n  eapply differ3_alpha_r;[|apply alpha_eq_sym;apply (alpha_eq_subst_utokens_aux u2 t2 sub sub); eauto 3 with slow].\n\n  apply differ3_implies_differ3_alpha.\n  apply differ3_subst_utokens_aux; auto.\nQed.\n\nLemma wf_force_int_bound_app {o} :\n  forall v b (t : @NTerm o) g u,\n    wf_term (force_int_bound_app v b t g u)\n            <=> (wf_term t # wf_term g # wf_term u).\nProof.\n  introv.\n  unfold force_int_bound_app.\n  rw <- @wf_cbv_iff.\n  rw @wf_force_int_bound.\n  rw <- @wf_apply_iff.\n  split; sp.\nQed.\n\nLemma differ3_alpha_mk_eapply {o} :\n  forall b f g (a1 a2 b1 b2 : @NTerm o),\n    differ3_alpha b f g a1 a2\n    -> differ3_alpha b f g b1 b2\n    -> differ3_alpha b f g (mk_eapply a1 b1) (mk_eapply a2 b2).\nProof.\n  introv da1 da2.\n  allunfold @differ3_alpha; exrepnd.\n  exists (mk_eapply u0 u1) (mk_eapply u3 u2); dands; auto.\n  - apply alpha_eq_oterm_combine; simpl; dands; auto.\n    introv i; repndors; cpx; auto; apply alphaeqbt_nilv2; auto.\n  - apply alpha_eq_oterm_combine; simpl; dands; auto.\n    introv i; repndors; cpx; auto; apply alphaeqbt_nilv2; auto.\n  - constructor; simpl; auto.\n    introv i; repndors; cpx; constructor; auto.\nQed.\n\nLemma differ3_mk_eapply {o} :\n  forall b f g (a1 a2 b1 b2 : @NTerm o),\n    differ3 b f g a1 a2\n    -> differ3 b f g b1 b2\n    -> differ3 b f g (mk_eapply a1 b1) (mk_eapply a2 b2).\nProof.\n  introv da1 da2.\n  constructor; simpl; auto.\n  introv i; repndors; cpx; constructor; auto.\nQed.\n\nLemma differ3_preserves_iscan {o} :\n  forall b f g (t1 t2 : @NTerm o),\n    differ3 b f g t1 t2\n    -> iscan t1\n    -> iscan t2.\nProof.\n  introv diff isc.\n  apply iscan_implies in isc; repndors; exrepnd; subst;\n  inversion diff; subst; simpl; auto.\nQed.\n\nLemma differ3_exception_implies {o} :\n  forall b f g (a e t : @NTerm o),\n    differ3 b f g (mk_exception a e) t\n    -> {a' : NTerm\n        & {e' : NTerm\n        & t = mk_exception a' e'\n        # differ3 b f g a a'\n        # differ3 b f g e e' }}.\nProof.\n  introv d.\n  inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; cpx; clear d; allsimpl.\n\n  pose proof (imp (nobnd a) x) as d1; autodimp d1 hyp.\n  pose proof (imp (nobnd e) y) as d2; autodimp d2 hyp.\n  clear imp.\n\n  inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n  inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n  fold_terms.\n\n  eexists; eexists; dands; eauto.\nQed.\n\nLemma differ3_lam_implies {o} :\n  forall b f g v a (t : @NTerm o),\n    differ3 b f g (mk_lam v a) t\n    -> {a' : NTerm\n        & t = mk_lam v a'\n        # differ3 b f g a a' }.\nProof.\n  introv d.\n  inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; cpx; clear d; allsimpl.\n\n  pose proof (imp (bterm [v] a) x) as d1; autodimp d1 hyp.\n  clear imp.\n\n  inversion d1 as [? ? ? df2 dg2 d2]; subst; clear d1.\n  fold_terms.\n\n  eexists; eexists; dands; eauto.\nQed.\n\nLemma differ3_alpha_mk_lam {o} :\n  forall b f g v (t1 t2 : @NTerm o),\n    !LIn v (free_vars f)\n    -> !LIn v (free_vars g)\n    -> differ3_alpha b f g t1 t2\n    -> differ3_alpha b f g (mk_lam v t1) (mk_lam v t2).\nProof.\n  introv ni1 ni2 d.\n  allunfold @differ3_alpha; exrepnd.\n  exists (mk_lam v u1) (mk_lam v u2); dands;\n  try (apply implies_alpha_eq_mk_lam; eauto with slow).\n  constructor; simpl; auto; introv i; repndors; cpx.\n  constructor; simpl; auto; allrw disjoint_singleton_l; auto.\nQed.\n\nLemma comp_force_int_step3 {o} :\n  forall lib b f g (t1 t2 : @NTerm o) kk u,\n    isprog f\n    -> isprog g\n    -> wf_term t1\n    -> wf_term t2\n    -> agree_upto_b lib b f g\n    -> differ3 b f g t1 t2\n    -> compute_step lib t1 = csuccess u\n    -> has_value_like_k lib kk u\n    -> (forall t1 t2 v m, (* induction hypothesis *)\n          m < S kk\n          -> wf_term t1\n          -> wf_term t2\n          -> isvalue_like v\n          -> reduces_in_atmost_k_steps lib t1 v m\n          -> differ3 b f g t1 t2\n          -> {v' : NTerm & reduces_to lib t2 v' # differ3_alpha b f g v v'})\n    -> {t : NTerm\n        & {u' : NTerm\n           & reduces_to lib t2 t\n           # reduces_to lib u u'\n           # differ3_alpha b f g u' t}}.\nProof.\n  nterm_ind1s t1 as [v|s ind|op bs ind] Case;\n  introv ispf ispg wt1 wt2 agree d comp hv compind.\n\n  - Case \"vterm\".\n    simpl.\n    inversion d; subst; allsimpl; ginv.\n\n  - Case \"sterm\".\n    csunf comp; allsimpl; ginv.\n    inversion d; subst; allsimpl; ginv; clear d.\n    exists (sterm s) (sterm s); dands; eauto 3 with slow.\n\n  - Case \"oterm\".\n    dopid op as [can|ncan|exc|abs] SCase; ginv.\n\n    + SCase \"Can\".\n      inversion d; subst.\n      csunf comp; allsimpl; ginv.\n      exists (oterm (Can can) bs2) (oterm (Can can) bs); dands; eauto 3 with slow.\n\n    + SCase \"NCan\".\n      destruct bs as [|b1 bs];\n        try (complete (allsimpl; ginv));[].\n\n      destruct b1 as [l1 t1].\n      destruct l1; try (complete (csunf comp; simpl in comp; ginv));[|].\n\n      {\n      destruct t1 as [v1|f1|op1 bs1].\n\n      * destruct t2 as [v2|f2|op2 bs2]; try (complete (inversion d));[].\n\n        inversion d as [? ? ? ? d1|?|?|? ? ? len imp]; subst; simphyps; cpx; ginv.\n\n      * destruct t2 as [v2|f2|op2 bs2]; try (complete (inversion d));[].\n        csunf comp; allsimpl.\n        dopid_noncan ncan SSCase; allsimpl; ginv.\n\n        { SSCase \"NApply\".\n          apply compute_step_seq_apply_success in comp; exrepnd; subst; allsimpl.\n          inversion d as [? ? ? ? d1|?|?|? ? ? len imp]; subst; simphyps; cpx; ginv; clear d.\n          allsimpl.\n\n          pose proof (imp (nobnd (sterm f1)) x) as d1; autodimp d1 hyp.\n          pose proof (imp (nobnd arg) y) as d2; autodimp d2 hyp.\n          clear imp.\n\n          inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n          inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n          inversion d3; subst; clear d3.\n          fold_terms.\n\n          exists (mk_eapply (sterm f1) t0)\n                 (mk_eapply (sterm f1) arg).\n          dands; eauto 3 with slow.\n          apply differ3_implies_differ3_alpha.\n          apply differ3_mk_eapply; auto.\n        }\n\n        { SSCase \"NEApply\".\n          apply compute_step_eapply_success in comp; exrepnd; subst; allsimpl.\n          inversion d as [? ? ? ? d1|?|?|? ? ? len imp]; subst; simphyps; cpx; ginv; clear d.\n          rw @wf_term_eq in wt1; rw @nt_wf_eapply_iff in wt1; exrepnd; allunfold @nobnd; subst; ginv.\n          simpl in len; repeat cpx.\n          simpl in imp.\n\n          pose proof (imp (nobnd (sterm f1)) x) as d1; autodimp d1 hyp.\n          pose proof (imp (nobnd b0) y) as d2; autodimp d2 hyp.\n          clear imp.\n\n          inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n          inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n          inversion d3; subst; clear d3.\n          fold_terms.\n          allrw <- @wf_eapply_iff; repnd.\n\n          repndors; exrepnd; subst.\n\n          - apply compute_step_eapply2_success in comp1; repnd; GC.\n            repndors; exrepnd; subst; ginv; allsimpl; GC.\n            inversion d4 as [?|?|?|? ? ? len1 imp1]; subst; allsimpl;\n            clear d4; cpx; clear imp1; fold_terms.\n\n            exists (f0 n) (f0 n); dands; eauto 3 with slow.\n            { apply reduces_to_if_step.\n              csunf; simpl.\n              dcwf h; simpl; boolvar; try omega.\n              rw @Znat.Nat2Z.id; auto. }\n            { apply differ3_implies_differ3_alpha.\n              allapply @closed_if_isprog.\n              apply differ3_refl; simpl; try (rw ispf); try (rw ispg); auto. }\n\n          - apply isexc_implies2 in comp0; exrepnd; subst.\n            inversion d4 as [?|?|?|? ? ? len1 imp1]; subst; allsimpl; clear d4.\n            exists (oterm Exc bs2) (oterm Exc l); dands; eauto 3 with slow.\n\n          - pose proof (ind b0 b0 []) as h; clear ind.\n            repeat (autodimp h hyp); eauto 3 with slow.\n            pose proof (h t0 kk x) as ih; clear h.\n            applydup @preserve_nt_wf_compute_step in comp1; eauto 3 with slow.\n            allsimpl; autorewrite with slow in *; auto.\n            repeat (autodimp ih hyp); eauto 3 with slow.\n\n            { eapply has_value_k_like_eapply_sterm_implies in hv; auto; exrepnd.\n              eapply has_value_like_k_lt; eauto. }\n\n            exrepnd.\n\n            exists (mk_eapply (sterm f1) t) (mk_eapply (sterm f1) u'); dands; eauto 3 with slow.\n            { apply implies_eapply_red_aux; eauto 3 with slow. }\n            { apply implies_eapply_red_aux; eauto 3 with slow. }\n            { apply differ3_alpha_mk_eapply; eauto 3 with slow. }\n        }\n\n        { SSCase \"NFix\".\n          apply compute_step_fix_success in comp; repnd; subst; allsimpl.\n          inversion d as [? ? ? ? d1|?|?|? ? ? len imp]; subst; simphyps; cpx; ginv; clear d; allsimpl.\n\n          pose proof (imp (nobnd (sterm f1)) x) as d1; autodimp d1 hyp.\n          clear imp.\n\n          inversion d1 as [? ? ? df2 dg2 d2]; subst; clear d1.\n          inversion d2; subst; clear d2.\n          fold_terms.\n\n          exists (mk_apply (sterm f1) (mk_fix (sterm f1)))\n                 (mk_apply (sterm f1) (mk_fix (sterm f1))).\n          dands; eauto 3 with slow.\n        }\n\n        { SSCase \"NCbv\".\n          apply compute_step_cbv_success in comp; exrepnd; subst; allsimpl.\n          inversion d as [? ? ? d1|?|? xxx|? ? ? len imp]; subst; simphyps; cpx; ginv; clear d; allsimpl; fold_terms.\n\n          pose proof (imp (nobnd (sterm f1)) x0) as d1; autodimp d1 hyp.\n          pose proof (imp (bterm [v] x) y) as d2; autodimp d2 hyp.\n          clear imp.\n\n          inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n          inversion d3; subst; clear d3.\n          inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n          fold_terms.\n\n          exists (subst t2 v (sterm f1))\n                 (subst x v (sterm f1)).\n          dands; eauto 3 with slow.\n          allapply @closed_if_isprog.\n          apply differ3_subst; simpl; try (rw ispf); try (rw ispg); simpl; tcsp.\n        }\n\n        { SSCase \"NTryCatch\".\n          apply compute_step_try_success in comp; exrepnd; subst; allsimpl.\n          inversion d as [? ? ? d1|?|? xxx|? ? ? len imp]; subst; simphyps; cpx; ginv; clear d; allsimpl; fold_terms.\n\n          pose proof (imp (nobnd (sterm f1)) x0) as d1; autodimp d1 hyp.\n          pose proof (imp (nobnd a) y) as d2; autodimp d2 hyp.\n          pose proof (imp (bterm [v] x) z) as d3; autodimp d3 hyp.\n          clear imp.\n\n          inversion d1 as [? ? ? dfx dgx d4]; subst; clear d1.\n          inversion d4; subst; clear d4.\n          inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n          inversion d3 as [? ? ? df5 dg5 d5]; subst; clear d3.\n          fold_terms.\n\n          exists (mk_atom_eq t2 t2 (sterm f1) mk_bot)\n                 (mk_atom_eq a a (sterm f1) mk_bot).\n          dands; eauto 3 with slow.\n          apply differ3_alpha_mk_atom_eq; eauto 3 with slow.\n          apply differ3_implies_differ3_alpha.\n          allapply @closed_if_isprog.\n          apply differ3_refl; simpl; try (rw ispf); try (rw ispg); auto.\n        }\n\n        { SSCase \"NCanTest\".\n          apply compute_step_seq_can_test_success in comp; exrepnd; subst; allsimpl.\n          inversion d as [? ? ? d1|?|? xxx|? ? ? len imp]; subst; simphyps; cpx; ginv; clear d; allsimpl; fold_terms.\n\n          pose proof (imp (nobnd (sterm f1)) x) as d1; autodimp d1 hyp.\n          pose proof (imp (nobnd a) y) as d2; autodimp d2 hyp.\n          pose proof (imp (nobnd b0) z) as d3; autodimp d3 hyp.\n          clear imp.\n\n          inversion d1 as [? ? ? dfx dgx d4]; subst; clear d1.\n          inversion d4; subst; clear d4.\n          inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n          inversion d3 as [? ? ? df5 dg5 d5]; subst; clear d3.\n          fold_terms.\n\n          exists t0 b0.\n          dands; eauto 3 with slow.\n        }\n\n      * (* Now destruct op2 *)\n        dopid op1 as [can1|ncan1|exc1|abs1] SSCase; ginv.\n\n        { SSCase \"Can\".\n\n          (* Because the principal argument is canonical we can destruct ncan *)\n          dopid_noncan ncan SSSCase.\n\n          - SSSCase \"NApply\".\n            clear ind compind.\n            csunf comp; allsimpl.\n            apply compute_step_apply_success in comp; repndors; exrepnd; subst; allsimpl.\n\n            { inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear d.\n              destruct bs2; allsimpl; cpx.\n              cpx; allsimpl.\n\n              pose proof (imp (bterm [] (oterm (Can NLambda) [bterm [v] b0])) b1) as d1.\n              autodimp d1 hyp.\n              pose proof (imp (bterm [] arg) x) as d2.\n              autodimp d2 hyp.\n              clear imp.\n\n              inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n              inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n\n              inversion d3 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; GC; clear d3.\n              destruct bs2; allsimpl; cpx.\n              cpx.\n\n              pose proof (imp1 (bterm [v] b0) b1) as d1.\n              autodimp d1 hyp.\n              clear imp1.\n              inversion d1 as [? ? ? df2 dg2 d2]; subst; clear d1.\n\n              exists (subst t2 v t0) (subst b0 v arg); dands; eauto 3 with slow.\n\n              apply differ3_subst; simpl; eauto 3 with slow.\n            }\n\n            { inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear d; cpx.\n              allsimpl; fold_terms.\n\n              pose proof (imp (nobnd (mk_nseq f0)) x) as d1.\n              autodimp d1 hyp.\n              pose proof (imp (nobnd arg) y) as d2.\n              autodimp d2 hyp.\n              clear imp.\n\n              inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n              inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n              GC.\n\n              inversion d3 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; GC; clear d3.\n              cpx; clear imp1; fold_terms.\n\n              exists (mk_apseq f0 t0) (mk_apseq f0 arg); dands; eauto 3 with slow.\n\n              apply differ3_implies_differ3_alpha.\n              apply differ3_oterm; simpl; tcsp.\n              introv j; repndors; cpx; tcsp.\n              constructor; auto.\n            }\n\n          - SSSCase \"NEApply\".\n            csunf comp; allsimpl.\n            apply compute_step_eapply_success in comp; exrepnd; subst.\n            rw @wf_term_eq in wt1; rw @nt_wf_eapply_iff in wt1; exrepnd; allunfold @nobnd; ginv.\n\n            inversion d as [? ? ? ? d1|?|?|? ? ? len imp]; subst; clear d.\n            simpl in len; cpx; simpl in imp.\n\n            pose proof (imp (nobnd (oterm (Can can1) bs1)) x) as d1; autodimp d1 hyp.\n            pose proof (imp (nobnd b0) y) as d2; autodimp d2 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n            inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n            fold_terms.\n            allrw <- @wf_eapply_iff; repnd.\n            apply eapply_wf_def_oterm_implies in comp2; exrepnd; ginv; fold_terms.\n            apply differ3_lam_implies in d3; exrepnd; subst; fold_terms.\n\n            repndors; exrepnd; subst.\n\n            + apply compute_step_eapply2_success in comp1; repnd; GC.\n              repndors; exrepnd; subst; ginv; allsimpl; GC.\n              allunfold @apply_bterm; allsimpl; allrw @fold_subst.\n\n              exists (subst a' v0 t0) (subst b1 v0 b0); dands; eauto 3 with slow.\n              { apply eapply_lam_can_implies.\n                apply differ3_preserves_iscan in d4; auto.\n                unfold computes_to_can; dands; eauto 3 with slow. }\n              { apply differ3_subst; auto; simpl;\n                allapply @closed_if_isprog; try (rw ispf); try (rw ispg); auto. }\n\n            + apply wf_isexc_implies in comp0; auto; exrepnd; subst; allsimpl.\n              apply differ3_exception_implies in d4; exrepnd; subst.\n              exists (mk_exception a'0 e') (mk_exception a e); dands; eauto 3 with slow.\n              apply differ3_alpha_mk_exception; eauto 3 with slow.\n\n            + pose proof (ind b0 b0 []) as h; clear ind.\n              repeat (autodimp h hyp); eauto 3 with slow.\n              pose proof (h t0 kk x) as ih; clear h.\n              applydup @preserve_nt_wf_compute_step in comp1; auto.\n              repeat (autodimp ih hyp); eauto 3 with slow.\n              { apply has_value_like_k_eapply_lam_implies in hv; auto.\n                exrepnd.\n                eapply has_value_like_k_lt; eauto. }\n              exrepnd.\n\n              exists (mk_eapply (mk_lam v a') t1) (mk_eapply (mk_lam v t) u'); dands; eauto 3 with slow.\n              { apply implies_eapply_red_aux; eauto 3 with slow. }\n              { apply implies_eapply_red_aux; eauto 3 with slow. }\n              { apply differ3_alpha_mk_eapply; eauto 3 with slow.\n                apply differ3_alpha_mk_lam; eauto 3 with slow;\n                allapply @closed_if_isprog; try (rw ispf); try (rw ispg); simpl; tcsp. }\n\n          - SSSCase \"NApseq\".\n            clear ind compind.\n            csunf comp; allsimpl.\n            apply compute_step_apseq_success in comp; exrepnd; subst; allsimpl.\n            fold_terms.\n\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear d.\n            cpx; allsimpl.\n\n            pose proof (imp (nobnd (mk_nat n0)) x) as d1.\n            autodimp d1 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n\n            inversion d3 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; GC; clear d3.\n            cpx; clear imp1; fold_terms.\n\n            exists (@mk_nat o (n n0)) (@mk_nat o (n n0)); dands; eauto 3 with slow.\n            apply reduces_to_if_step; csunf; simpl.\n            rw @Znat.Nat2Z.id.\n            boolvar; try omega; auto.\n\n          - SSSCase \"NFix\".\n            csunf comp; allsimpl.\n            apply compute_step_fix_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear d.\n            destruct bs2; allsimpl; cpx.\n            destruct bs2; allsimpl; cpx.\n            cpx; GC.\n\n            pose proof (imp (bterm [] (oterm (Can can1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n\n            inversion d3 as [|?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; GC; clear d3.\n\n            exists (mk_apply (oterm (Can can1) bs2)\n                             (mk_fix (oterm (Can can1) bs2)))\n                   (mk_apply (oterm (Can can1) bs1)\n                             (mk_fix (oterm (Can can1) bs1))).\n            dands; eauto 3 with slow.\n\n            apply differ3_implies_differ3_alpha.\n            apply differ3_oterm; simpl; tcsp.\n            introv j; repndors; cpx; tcsp.\n\n            { constructor; auto ; constructor; allsimpl; auto. }\n\n            { constructor; auto; constructor; simpl; tcsp.\n              introv j; repndors; cpx; tcsp. }\n\n          - SSSCase \"NSpread\".\n            csunf comp; allsimpl.\n            apply compute_step_spread_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear d.\n            destruct bs2; allsimpl; cpx.\n            cpx; allsimpl.\n\n            pose proof (imp (bterm [] (oterm (Can NPair) [bterm [] a, bterm [] b0])) b1) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [va,vb] arg) x) as d2.\n            autodimp d2 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n            inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n\n            inversion d3 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; GC; clear d3.\n            destruct bs2; allsimpl; cpx.\n            cpx; allsimpl.\n\n            pose proof (imp1 (bterm [] a) b1) as d1.\n            autodimp d1 hyp.\n            pose proof (imp1 (bterm [] b0) x) as d2.\n            autodimp d2 hyp.\n            clear imp1.\n            inversion d1 as [? ? ? df5 dg5 d5]; subst; clear d1.\n            inversion d2 as [? ? ? df6 dg6 d6]; subst; clear d2.\n\n            exists (lsubst t0 [(va,t2),(vb,t3)]) (lsubst arg [(va,a),(vb,b0)]); dands; eauto 3 with slow.\n            apply differ3_subst; simpl; eauto 3 with slow.\n\n          - SSSCase \"NDsup\".\n            csunf comp; allsimpl.\n            apply compute_step_dsup_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear d.\n            destruct bs2; allsimpl; cpx.\n            cpx; allsimpl.\n\n            pose proof (imp (bterm [] (oterm (Can NSup) [bterm [] a, bterm [] b0])) b1) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [va,vb] arg) x) as d2.\n            autodimp d2 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n            inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n\n            inversion d3 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; GC; clear d3.\n            destruct bs2; allsimpl; cpx.\n            cpx; allsimpl.\n\n            pose proof (imp1 (bterm [] a) b1) as d1.\n            autodimp d1 hyp.\n            pose proof (imp1 (bterm [] b0) x) as d2.\n            autodimp d2 hyp.\n            clear imp1.\n            inversion d1 as [? ? ? df5 dg5 d5]; subst; clear d1.\n            inversion d2 as [? ? ? df6 dg6 d6]; subst; clear d2.\n\n            exists (lsubst t0 [(va,t2),(vb,t3)]) (lsubst arg [(va,a),(vb,b0)]); dands; eauto 3 with slow.\n            apply differ3_subst; simpl; eauto 3 with slow.\n\n          - SSSCase \"NDecide\".\n            csunf comp; allsimpl.\n            apply compute_step_decide_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear d.\n            destruct bs2; allsimpl; cpx.\n            destruct bs2; allsimpl; cpx.\n            cpx; allsimpl.\n\n            pose proof (imp (bterm [] (oterm (Can can1) [bterm [] d0])) b0) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [v1] t1) b1) as d2.\n            autodimp d2 hyp.\n            pose proof (imp (bterm [v2] t0) x) as d3.\n            autodimp d3 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df4 dg4 d4]; subst; clear d1.\n            inversion d2 as [? ? ? df5 dg5 d5]; subst; clear d2.\n            inversion d3 as [? ? ? df6 dg6 d6]; subst; clear d3.\n\n            inversion d4 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; GC; clear d4.\n            cpx; allsimpl.\n\n            pose proof (imp1 (bterm [] d0) x) as d1.\n            autodimp d1 hyp.\n            clear imp1.\n            inversion d1 as [? ? ? df2 dg2 d2]; subst; clear d1.\n\n            dorn comp0; repnd; subst.\n\n            + exists (subst t4 v1 t3) (subst t1 v1 d0); dands; eauto 3 with slow.\n              apply differ3_subst; simpl; eauto 3 with slow.\n\n            + exists (subst t5 v2 t3) (subst t0 v2 d0); dands; eauto 3 with slow.\n              apply differ3_subst; simpl; eauto 3 with slow.\n\n          - SSSCase \"NCbv\".\n            csunf comp; allsimpl.\n            apply compute_step_cbv_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear d.\n            destruct bs2; allsimpl; cpx.\n            cpx; allsimpl.\n\n            pose proof (imp (bterm [] (oterm (Can can1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [v] x) x0) as d2.\n            autodimp d2 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n            inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n\n            inversion d3 as [|?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; GC; clear d3.\n\n            exists (subst t0 v (oterm (Can can1) bs2))\n                   (subst x v (oterm (Can can1) bs1)); dands; eauto 3 with slow.\n            apply differ3_subst; simpl; eauto 3 with slow.\n\n          - SSSCase \"NSleep\".\n            csunf comp; allsimpl.\n            apply compute_step_sleep_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear d.\n            cpx; allsimpl.\n\n            pose proof (imp (bterm [] (oterm (Can (Nint z)) [])) x) as d1.\n            autodimp d1 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df2 sg2 d2]; subst; clear d1.\n\n            inversion d2 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; GC; clear d2.\n            cpx; allsimpl.\n\n            exists (@mk_axiom o)\n                   (@mk_axiom o).\n            dands; eauto 3 with slow.\n\n          - SSSCase \"NTUni\".\n            csunf comp; allsimpl.\n            apply compute_step_tuni_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear d.\n            cpx; allsimpl.\n\n            pose proof (imp (bterm [] (oterm (Can (Nint (Z.of_nat n))) [])) x) as d1.\n            autodimp d1 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df2 dg2 d2]; subst; clear d1.\n\n            inversion d2 as [|?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; GC; clear d2.\n            cpx; allsimpl.\n\n            exists (@mk_uni o n)\n                   (@mk_uni o n).\n            dands; eauto 3 with slow.\n            { apply reduces_to_if_step; simpl.\n              csunf; simpl; unfold compute_step_tuni; simpl; boolvar; try omega.\n              rw Znat.Nat2Z.id; auto. }\n\n          - SSSCase \"NMinus\".\n            csunf comp; allsimpl.\n            apply compute_step_minus_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear d.\n            cpx; allsimpl.\n\n            pose proof (imp (bterm [] (oterm (Can (Nint z)) [])) x) as d1.\n            autodimp d1 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df2 dg2 d2]; subst; clear d1.\n\n            inversion d2 as [|?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; GC; clear d2.\n            cpx; allsimpl.\n\n            exists (@mk_integer o (- z))\n                   (@mk_integer o (- z)).\n            dands; eauto 3 with slow.\n\n          - SSSCase \"NFresh\".\n            csunf comp; allsimpl; ginv.\n\n          - SSSCase \"NTryCatch\".\n            csunf comp; allsimpl.\n            apply compute_step_try_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear d.\n            destruct bs2; allsimpl; cpx.\n            cpx; allsimpl.\n\n            pose proof (imp (bterm [] (oterm (Can can1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [] a) x0) as d2.\n            autodimp d2 hyp.\n            pose proof (imp (bterm [v] x) y) as d3.\n            autodimp d3 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df4 dg4 d4]; subst; clear d1.\n            inversion d2 as [? ? ? df5 dg5 d5]; subst; clear d2.\n            inversion d3 as [? ? ? df6 dg6 d6]; subst; clear d3.\n            allrw disjoint_singleton_l.\n\n            inversion d4 as [|?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; GC; clear d4.\n\n            exists (mk_atom_eq t0 t0 (oterm (Can can1) bs2) mk_bot)\n                   (mk_atom_eq a a (oterm (Can can1) bs1) mk_bot);\n              dands; eauto 3 with slow.\n\n            apply differ3_implies_differ3_alpha.\n            constructor; simpl; auto.\n            introv i; repndors; ginv; tcsp; constructor; eauto 3 with slow.\n            apply differ3_refl; simpl; allrw disjoint_singleton_l;\n            try (rw @isprog_eq in ispf; destruct ispf as [c w]; rw c; simpl; tcsp);\n            try (rw @isprog_eq in ispg; destruct ispg as [c w]; rw c; simpl; tcsp).\n\n          - SSSCase \"NParallel\".\n            csunf comp; allsimpl.\n            apply compute_step_parallel_success in comp; subst; allsimpl.\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear d.\n            destruct bs2; allsimpl; cpx.\n\n            pose proof (imp (bterm [] (oterm (Can can1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            inversion d1 as [? ? ? df2 dg2 d2]; subst; clear d1.\n            inversion d2 as [|?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; GC; clear d2.\n\n            exists (@mk_axiom o) (@mk_axiom o); dands; eauto 3 with slow.\n\n          - SSSCase \"NCompOp\".\n            destruct bs; try (complete (csunf comp; allsimpl; dcwf h));[].\n            destruct b0 as [l t].\n            destruct l; destruct t as [v|s|op bs2]; try (complete (csunf comp; allsimpl; dcwf h));[].\n\n            inversion d as [|?|?|? ? ? len imp]; subst; clear d.\n            allsimpl.\n            destruct bs3; allsimpl; cpx.\n            destruct bs3; allsimpl; cpx.\n\n            pose proof (imp (bterm [] (oterm (Can can1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [] (oterm op bs2)) b1) as d2.\n            autodimp d2 hyp.\n\n            inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n            inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n\n            inversion d3 as [|?|?|? ? ? ni1 len1 imp1]; subst; clear d3; cpx.\n\n            dopid op as [can3|ncan3|exc3|abs3] SSSSCase.\n\n            + SSSSCase \"Can\".\n              csunf comp; allsimpl.\n              dcwf h.\n\n              inversion d4 as [|?|?|? ? ? len2 imp2]; subst; clear d4; cpx.\n\n              apply compute_step_compop_success_can_can in comp.\n              exrepnd; subst.\n\n              allsimpl; cpx.\n              clear df3 dg3 df4 dg4 len1 imp2.\n              allsimpl.\n\n              pose proof (imp (nobnd t1) x) as d1.\n              autodimp d1 hyp.\n              pose proof (imp (nobnd t2) y) as d2.\n              autodimp d2 hyp.\n              clear imp.\n\n              inversion d1 as [? ? ? df33 dg33 d3]; subst; clear d1.\n              inversion d2 as [? ? ? df44 dg44 d4]; subst; clear d2.\n\n              repndors; exrepnd; subst.\n\n              * allapply @get_param_from_cop_pki; subst; allsimpl.\n                exists (if Z_lt_le_dec n1 n2 then t3 else t4)\n                       (if Z_lt_le_dec n1 n2 then t1 else t2);\n                  dands; eauto 3 with slow.\n                boolvar; eauto 3 with slow.\n\n              * allrw @get_param_from_cop_some; subst; allsimpl.\n                exists (if param_kind_deq pk1 pk2 then t3 else t4)\n                       (if param_kind_deq pk1 pk2 then t1 else t2);\n                  dands; eauto 3 with slow.\n\n                { apply reduces_to_if_step; csunf; simpl.\n                  dcwf h; allsimpl.\n                  unfold compute_step_comp; allrw @get_param_from_cop_pk2can; auto. }\n\n                boolvar; eauto 3 with slow.\n\n            + SSSSCase \"NCan\".\n              rw @compute_step_ncompop_ncan2 in comp.\n              dcwf h; allsimpl.\n              remember (compute_step lib (oterm (NCan ncan3) bs2)) as comp1;\n                symmetry in Heqcomp1.\n              destruct comp1; ginv.\n\n              pose proof (ind (oterm (NCan ncan3) bs2) (oterm (NCan ncan3) bs2) []) as h; clear ind.\n              repeat (autodimp h hyp); tcsp; eauto 3 with slow.\n\n              pose proof (h t0 kk n) as k; clear h.\n              repeat (autodimp k hyp).\n\n              { apply wf_oterm_iff in wt1; allsimpl; repnd.\n                pose proof (wt1 (bterm [] (oterm (NCan ncan3) bs2))) as h.\n                autodimp h hyp. }\n\n              { apply wf_oterm_iff in wt2; allsimpl; repnd.\n                pose proof (wt2 (bterm [] t0)) as h.\n                autodimp h hyp. }\n\n              { apply if_has_value_like_k_ncompop_can1 in hv; exrepnd.\n                apply (has_value_like_k_lt lib j kk) in hv0; auto. }\n\n              exrepnd.\n\n              exists (oterm (NCan (NCompOp c))\n                            (bterm [] (oterm (Can can1) bs4)\n                                   :: bterm [] t\n                                   :: bs3))\n                     (oterm (NCan (NCompOp c))\n                            (bterm [] (oterm (Can can1) bs1)\n                                   :: bterm [] u'\n                                   :: bs)).\n              dands; eauto 3 with slow.\n\n              * apply reduce_to_prinargs_comp2; eauto 3 with slow; sp.\n                apply co_wf_def_implies_iswfpk.\n                eapply co_wf_def_len_implies;[|eauto];auto.\n\n              * apply reduce_to_prinargs_comp2; eauto 3 with slow; sp.\n\n              * unfold differ3_alpha in k1; exrepnd.\n                exists (oterm (NCan (NCompOp c))\n                              (bterm [] (oterm (Can can1) bs1)\n                                     :: bterm [] u1\n                                     :: bs))\n                       (oterm (NCan (NCompOp c))\n                              (bterm [] (oterm (Can can1) bs4)\n                                     :: bterm [] u2\n                                     :: bs3)).\n                dands.\n\n                { prove_alpha_eq4.\n                  introv j; destruct n0;[|destruct n0]; try omega; cpx.\n                  apply alphaeqbt_nilv2; auto. }\n\n                { prove_alpha_eq4.\n                  introv j; destruct n0;[|destruct n0]; try omega; cpx.\n                  apply alphaeqbt_nilv2; auto. }\n\n                { apply differ3_oterm; simpl; tcsp.\n                  introv j; repndors; cpx. }\n\n            + SSSSCase \"Exc\".\n              csunf comp; allsimpl; ginv.\n              dcwf h; ginv; allsimpl.\n              inversion d4 as [|?|?|? ? ? len2 imp2]; subst; clear d4; cpx.\n              exists (oterm Exc bs5) (oterm Exc bs2); dands; eauto 3 with slow.\n              apply reduces_to_if_step; csunf; allsimpl; dcwf h.\n\n            + SSSSCase \"Abs\".\n              csunf comp; allsimpl; csunf comp; allsimpl.\n              dcwf h.\n              unfold on_success in comp.\n              remember (compute_step_lib lib abs3 bs2) as comp1.\n              symmetry in Heqcomp1; destruct comp1; ginv.\n              apply compute_step_lib_success in Heqcomp1; exrepnd; subst.\n\n              inversion d4 as [|?|?|? ? ? ni2 len2 imp2]; subst; simphyps; clear d4.\n\n              assert (differ3_bterms b f g bs2 bs5) as dbs.\n              { unfold differ3_bterms, br_bterms, br_list; auto. }\n\n              pose proof (found_entry_change_bs abs3 oa2 vars rhs lib bs2 correct bs5) as fe2.\n              repeat (autodimp fe2 hyp).\n\n              { apply differ3_bterms_implies_eq_map_num_bvars in dbs; auto. }\n\n              exists (oterm (NCan (NCompOp c))\n                            (bterm [] (oterm (Can can1) bs4)\n                                   :: bterm [] (mk_instance vars bs5 rhs)\n                                   :: bs3))\n              (oterm (NCan (NCompOp c))\n                     (bterm [] (oterm (Can can1) bs1)\n                            :: bterm [] (mk_instance vars bs2 rhs)\n                            :: bs)).\n\n             dands; eauto 3 with slow.\n\n             * apply reduces_to_if_step.\n               csunf; simpl; csunf; simpl.\n               dcwf h.\n               applydup @compute_step_lib_if_found_entry in fe2.\n               rw fe0; auto.\n\n             * pose proof (differ3_mk_instance b f g rhs vars bs2 bs5) as h.\n               repeat (autodimp h hyp); tcsp; GC.\n               { unfold correct_abs in correct; sp. }\n               { allapply @found_entry_implies_matching_entry.\n                 allunfold @matching_entry; sp. }\n               { allapply @found_entry_implies_matching_entry.\n                 allunfold @matching_entry; sp. }\n               { allunfold @correct_abs; sp. }\n               { allunfold @correct_abs; sp. }\n               unfold differ3_alpha in h.\n               exrepnd.\n\n               exists\n                 (oterm (NCan (NCompOp c))\n                        (bterm [] (oterm (Can can1) bs1)\n                               :: bterm [] u1\n                               :: bs))\n                 (oterm (NCan (NCompOp c))\n                        (bterm [] (oterm (Can can1) bs4)\n                               :: bterm [] u2\n                               :: bs3)).\n               dands.\n\n               { prove_alpha_eq4.\n                 introv j; destruct n;[|destruct n]; try omega; cpx.\n                 apply alphaeqbt_nilv2; auto. }\n\n               { prove_alpha_eq4.\n                 introv j; destruct n;[|destruct n]; try omega; cpx.\n                 apply alphaeqbt_nilv2; auto. }\n\n               { apply differ3_oterm; allsimpl; tcsp.\n                 introv j; repndors; cpx. }\n\n          - SSSCase \"NArithOp\".\n            destruct bs; try (complete (csunf comp; allsimpl; dcwf h));[].\n            destruct b0 as [l t].\n            destruct l; destruct t as [v|s|op bs2]; try (complete (csunf comp; allsimpl; dcwf h));[].\n\n            inversion d as [|?|?|? ? ? len imp]; subst; clear d.\n            simpl in len; GC.\n\n            destruct bs3; simpl in len; cpx.\n            destruct bs3; simpl in len; cpx.\n            simpl in imp.\n\n            pose proof (imp (bterm [] (oterm (Can can1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [] (oterm op bs2)) b1) as d2.\n            autodimp d2 hyp.\n\n            inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n            inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n\n            inversion d3 as [|?|?|? ? ? ni1 len1 imp1]; subst; clear d3; cpx.\n\n            dopid op as [can3|ncan3|exc3|abs3] SSSSCase.\n\n            + SSSSCase \"Can\".\n              csunf comp; simpl in comp.\n              dcwf h; allsimpl.\n\n              inversion d4 as [|?|?|? ? ? ni2 len2 imp2]; subst; clear d4; cpx.\n\n              apply compute_step_arithop_success_can_can in comp.\n              exrepnd; subst.\n\n              allsimpl; cpx.\n\n              allapply @get_param_from_cop_pki; subst; allsimpl; GC.\n              exists (@oterm o (Can (Nint (get_arith_op a n1 n2))) [])\n                     (@oterm o (Can (Nint (get_arith_op a n1 n2))) []);\n                dands; eauto 3 with slow.\n\n            + SSSSCase \"NCan\".\n              rw @compute_step_narithop_ncan2 in comp.\n              dcwf h; allsimpl.\n              remember (compute_step lib (oterm (NCan ncan3) bs2)) as comp1;\n                symmetry in Heqcomp1.\n              destruct comp1; ginv.\n\n              pose proof (ind (oterm (NCan ncan3) bs2) (oterm (NCan ncan3) bs2) []) as h; clear ind.\n              repeat (autodimp h hyp); tcsp; eauto 3 with slow.\n\n              pose proof (h t0 kk n) as k; clear h.\n              repeat (autodimp k hyp).\n\n              { rw @wf_oterm_iff in wt1; allsimpl; repnd.\n                pose proof (wt1 (bterm [] (oterm (NCan ncan3) bs2))) as h.\n                autodimp h hyp. }\n\n              { rw @wf_oterm_iff in wt2; allsimpl; repnd.\n                pose proof (wt2 (bterm [] t0)) as h.\n                autodimp h hyp. }\n\n              { apply if_has_value_like_k_narithop_can1 in hv; exrepnd.\n                apply (has_value_like_k_lt lib j kk) in hv0; auto. }\n\n              exrepnd.\n\n              exists (oterm (NCan (NArithOp a))\n                            (bterm [] (oterm (Can can1) bs4)\n                                   :: bterm [] t\n                                   :: bs3))\n                     (oterm (NCan (NArithOp a))\n                            (bterm [] (oterm (Can can1) bs1)\n                                   :: bterm [] u'\n                                   :: bs)).\n              dands; eauto 3 with slow.\n\n              * apply reduce_to_prinargs_arith2; eauto 3 with slow; sp.\n                allunfold @ca_wf_def; exrepnd; subst; allsimpl; cpx; fold_terms; eauto 3 with slow.\n\n              * apply reduce_to_prinargs_arith2; eauto 3 with slow; sp.\n\n              * unfold differ3_alpha in k1; exrepnd.\n                exists (oterm (NCan (NArithOp a))\n                              (bterm [] (oterm (Can can1) bs1)\n                                     :: bterm [] u1\n                                     :: bs))\n                       (oterm (NCan (NArithOp a))\n                              (bterm [] (oterm (Can can1) bs4)\n                                     :: bterm [] u2\n                                     :: bs3)).\n                dands.\n\n                { prove_alpha_eq4.\n                  introv j; destruct n0;[|destruct n0]; try omega; cpx.\n                  apply alphaeqbt_nilv2; auto. }\n\n                { prove_alpha_eq4.\n                  introv j; destruct n0;[|destruct n0]; try omega; cpx.\n                  apply alphaeqbt_nilv2; auto. }\n\n                { apply differ3_oterm; simpl; tcsp.\n                  introv j; repndors; cpx. }\n\n            + SSSSCase \"Exc\".\n              csunf comp; allsimpl; ginv.\n              dcwf h; allsimpl; ginv.\n              inversion d4 as [|?|?|? ? ? len2 imp2]; subst; clear d4; cpx.\n              exists (oterm Exc bs5) (oterm Exc bs2); dands; eauto 3 with slow.\n              apply reduces_to_if_step; csunf; simpl; dcwf h.\n\n            + SSSSCase \"Abs\".\n              csunf comp; allsimpl; csunf comp; allsimpl.\n              dcwf h.\n              remember (compute_step_lib lib abs3 bs2) as comp1.\n              symmetry in Heqcomp1; destruct comp1; ginv.\n              apply compute_step_lib_success in Heqcomp1; exrepnd; subst.\n\n              inversion d4 as [|?|?|? ? ? ni2 len2 imp2]; subst; simphyps; clear d4.\n\n              assert (differ3_bterms b f g bs2 bs5) as dbs.\n              { unfold differ3_bterms, br_bterms, br_list; auto. }\n\n              pose proof (found_entry_change_bs abs3 oa2 vars rhs lib bs2 correct bs5) as fe2.\n              repeat (autodimp fe2 hyp).\n\n              { apply differ3_bterms_implies_eq_map_num_bvars in dbs; auto. }\n\n              exists (oterm (NCan (NArithOp a))\n                            (bterm [] (oterm (Can can1) bs4)\n                                   :: bterm [] (mk_instance vars bs5 rhs)\n                                   :: bs3))\n              (oterm (NCan (NArithOp a))\n                     (bterm [] (oterm (Can can1) bs1)\n                            :: bterm [] (mk_instance vars bs2 rhs)\n                            :: bs)).\n\n             dands; eauto 3 with slow.\n\n             * apply reduces_to_if_step.\n               csunf; simpl; csunf; simpl.\n               dcwf h; allsimpl.\n               applydup @compute_step_lib_if_found_entry in fe2.\n               rw fe0; auto.\n\n             * pose proof (differ3_mk_instance b f g rhs vars bs2 bs5) as h.\n               repeat (autodimp h hyp); tcsp; GC.\n               { unfold correct_abs in correct; sp. }\n               { allapply @found_entry_implies_matching_entry.\n                 allunfold @matching_entry; sp. }\n               { allapply @found_entry_implies_matching_entry.\n                 allunfold @matching_entry; sp. }\n               { allunfold @correct_abs; sp. }\n               { allunfold @correct_abs; sp. }\n               unfold differ3_alpha in h.\n               exrepnd.\n\n               exists\n                 (oterm (NCan (NArithOp a))\n                        (bterm [] (oterm (Can can1) bs1)\n                               :: bterm [] u1\n                               :: bs))\n                 (oterm (NCan (NArithOp a))\n                        (bterm [] (oterm (Can can1) bs4)\n                               :: bterm [] u2\n                               :: bs3)).\n               dands.\n\n               { prove_alpha_eq4.\n                 introv j; destruct n;[|destruct n]; try omega; cpx.\n                 apply alphaeqbt_nilv2; auto. }\n\n               { prove_alpha_eq4.\n                 introv j; destruct n;[|destruct n]; try omega; cpx.\n                 apply alphaeqbt_nilv2; auto. }\n\n               { apply differ3_oterm; allsimpl; tcsp.\n                 introv j; repndors; cpx. }\n\n          - SSSCase \"NCanTest\".\n            csunf comp; allsimpl.\n            apply compute_step_can_test_success in comp; exrepnd; subst; allsimpl.\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; clear d.\n            destruct bs2; allsimpl; cpx.\n            destruct bs2; allsimpl; cpx.\n            cpx; allsimpl; GC.\n\n            pose proof (imp (bterm [] (oterm (Can can1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [] arg2nt) b1) as d2.\n            autodimp d2 hyp.\n            pose proof (imp (bterm [] arg3nt) x) as d3.\n            autodimp d3 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df4 dg4 d4]; subst; clear d1.\n            inversion d2 as [? ? ? df5 dg5 d5]; subst; clear d2.\n            inversion d3 as [? ? ? df6 dg6 d6]; subst; clear d3.\n\n            inversion d4 as [|?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; clear d4.\n\n            exists (if canonical_form_test_for c can1 then t0 else t3)\n                   (if canonical_form_test_for c can1 then arg2nt else arg3nt).\n            dands; eauto 3 with slow.\n            destruct (canonical_form_test_for c can1); eauto 3 with slow.\n        }\n\n        { SSCase \"NCan\".\n          rw @compute_step_ncan_ncan in comp.\n          remember (compute_step lib (oterm (NCan ncan1) bs1)) as comp1;\n            symmetry in Heqcomp1.\n          destruct comp1; ginv.\n\n          inversion d as [? ? ? ? ? ni1 ni2 d1 aeq1 aeq2|?|?|? ? ? len imp];\n            subst; clear d.\n\n          - (* let's prove that t1 computes to an integer in less than kk steps *)\n            fold_terms; fold (force_int_bound v b t1 (mk_vbot v)) in Heqcomp1.\n            applydup @if_has_value_like_k_cbv_primarg in hv; simpl; tcsp; exrepnd.\n            assert (has_value_like_k lib (S j) (force_int_bound v b t1 (mk_vbot v))) as hvf.\n            { rw @has_value_like_S; eexists; eauto. }\n            apply if_has_value_like_k_force_int_bound in hvf; exrepnd.\n\n            pose proof (compind t1 t0 u j0) as r.\n            repeat (autodimp r hyp); try omega; exrepnd.\n\n            { allrw <- @wf_cbv_iff; repnd; auto. }\n\n            { apply wf_force_int_bound_app in wt2; sp. }\n\n            repndors; exrepnd; subst.\n\n            { apply differ3_alpha_integer in r0; subst.\n              pose proof (agree z) as ag.\n              repeat (autodimp ag hyp); eauto 3 with slow.\n              exrepnd.\n\n              pose proof (compute_step_force_int_bound lib v b (mk_vbot v) z j0 t1 n) as rz.\n              repeat (autodimp rz hyp); eauto 3 with slow.\n\n              exists (@mk_integer o z0) (@mk_integer o z0); dands.\n\n              + pose proof (reduces_to_force_int_bound_app_z\n                              lib v b (mk_vbot v) z t0 ga) as h.\n                repeat (autodimp h hyp); tcsp; eauto 3 with slow.\n                { apply alphaeq_preserves_free_vars in aeq2; rw <- aeq2; auto. }\n                eapply reduces_to_trans;[exact h|].\n\n                pose proof (reduces_to_alpha\n                              lib\n                              (mk_apply g (mk_integer z))\n                              (mk_apply ga (mk_integer z))\n                              (mk_integer z0)) as k.\n                repeat (autodimp k hyp); eauto 3 with slow.\n\n                { apply nt_wf_eq; apply wf_apply; eauto 3 with slow. }\n\n                { prove_alpha_eq4.\n                  introv q; destruct n0;[|destruct n0]; cpx.\n                  apply alphaeqbt_nilv2; auto. }\n\n                exrepnd.\n                inversion k0; subst; allsimpl; cpx.\n\n              + pose proof (reduces_to_prinarg\n                              lib NCbv\n                              n\n                              (mk_integer z)\n                              [bterm [v] (mk_apply fa (mk_var v))]) as h.\n                fold_terms.\n                autodimp h hyp.\n                eapply reduces_to_trans;[exact h|].\n                apply (reduces_to_if_split2\n                         _ _ (mk_apply fa (mk_integer z))).\n\n                { csunf; simpl; unfold apply_bterm, lsubst; simpl; boolvar;\n                  try (complete (provefalse; sp)).\n                  rw @lsubst_aux_trivial_cl_term; auto; simpl.\n                  rw disjoint_singleton_r; auto.\n                  apply alphaeq_preserves_free_vars in aeq1; rw <- aeq1; auto. }\n\n                pose proof (reduces_to_alpha\n                              lib\n                              (mk_apply f (mk_integer z))\n                              (mk_apply fa (mk_integer z))\n                              (mk_integer z0)) as k.\n                repeat (autodimp k hyp).\n\n                { apply nt_wf_eq; apply wf_apply; eauto 3 with slow. }\n\n                { prove_alpha_eq4.\n                  introv q; destruct n0;[|destruct n0]; cpx.\n                  apply alphaeqbt_nilv2; auto. }\n\n                exrepnd.\n                inversion k0; subst; allsimpl; cpx.\n\n              + apply differ3_implies_differ3_alpha.\n                apply differ3_refl; simpl; tcsp.\n            }\n\n            { apply isexc_implies2 in hvf1; exrepnd; subst.\n              applydup @differ3_alpha_exc in r0; eauto 3 with slow;\n              try (complete (simpl; boolvar; tcsp)).\n              apply isexc_implies2 in r2; exrepnd; subst.\n\n              pose proof (compute_step_force_int_bound_exc\n                            lib v b (mk_vbot v) t1 n (oterm Exc l)) as r.\n              repeat (autodimp r hyp); eauto 3 with slow.\n\n              exists (oterm Exc l0) (oterm Exc l); dands; auto.\n\n              - pose proof (reduces_to_prinarg\n                              lib NCbv\n                              (force_int_bound v b t0 (mk_vbot v))\n                              (oterm Exc l0)\n                              [bterm [v] (mk_apply ga (mk_var v))]) as h.\n                fold_terms.\n                autodimp h hyp.\n                { pose proof (reduces_to_prinarg\n                              lib NCbv\n                              t0\n                              (oterm Exc l0)\n                              [bterm [v] (less_bound b (mk_var v) (mk_vbot v))]) as h.\n                  fold_terms.\n                  autodimp h hyp.\n                  eapply reduces_to_trans; eauto 3 with slow. }\n                eapply reduces_to_trans; eauto 3 with slow.\n\n              - pose proof (reduces_to_prinarg\n                              lib NCbv\n                              n\n                              (oterm Exc l)\n                              [bterm [v] (mk_apply fa (mk_var v))]) as h.\n                fold_terms.\n                autodimp h hyp.\n                eapply reduces_to_trans; eauto 3 with slow.\n            }\n\n          - simpl in len.\n            destruct bs2; simpl in len; cpx.\n            simpl in imp.\n            pose proof (imp (bterm [] (oterm (NCan ncan1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            inversion d1 as [? ? ? df2 dg2 d2]; subst; clear d1.\n\n            pose proof (ind (oterm (NCan ncan1) bs1) (oterm (NCan ncan1) bs1) []) as h; clear ind.\n            repeat (autodimp h hyp); tcsp; eauto 3 with slow.\n\n            pose proof (h t2 kk n) as k; clear h.\n            repeat (autodimp k hyp); tcsp.\n\n            { rw @wf_oterm_iff in wt1; allsimpl; repnd.\n              pose proof (wt1 (bterm [] (oterm (NCan ncan1) bs1))) as h.\n              autodimp h hyp. }\n\n            { rw @wf_oterm_iff in wt2; allsimpl; repnd.\n              pose proof (wt2 (bterm [] t2)) as h.\n              autodimp h hyp. }\n\n            { apply if_has_value_like_k_ncan_primarg in hv; auto.\n              exrepnd.\n              apply (has_value_like_k_lt lib j kk); auto. }\n\n            exrepnd.\n\n            exists (oterm (NCan ncan) (bterm [] t :: bs2))\n                   (oterm (NCan ncan) (bterm [] u' :: bs));\n              dands; eauto 3 with slow.\n\n            + apply reduces_to_prinarg; auto.\n            + apply reduces_to_prinarg; auto.\n\n            + unfold differ3_alpha in k1; exrepnd.\n              exists (oterm (NCan ncan) (bterm [] u1 :: bs))\n                     (oterm (NCan ncan) (bterm [] u2 :: bs2));\n                dands.\n\n              * prove_alpha_eq4.\n                introv j; destruct n0; eauto 3 with slow.\n\n              * prove_alpha_eq4.\n                introv j; destruct n0; eauto 3 with slow.\n\n              * apply differ3_oterm; simpl; auto.\n                introv j; dorn j; cpx.\n        }\n\n        { SSCase \"Exc\".\n          csunf comp; allsimpl.\n          apply compute_step_catch_success in comp.\n\n          inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; cpx; clear d.\n          destruct bs2; allsimpl; cpx.\n          pose proof (imp (bterm [] (oterm Exc bs1)) b0) as d1.\n          autodimp d1 hyp.\n          inversion d1 as [? ? ? df2 dg2 d2]; subst; clear d1.\n          inversion d2 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; cpx; clear d2.\n\n          repndors; exrepnd; subst; allsimpl; cpx; allsimpl.\n\n          - pose proof (imp (bterm [] (oterm Exc [bterm [] a', bterm [] e]))\n                            (bterm [] (oterm Exc [x0, y0]))) as d1; autodimp d1 hyp.\n            pose proof (imp (bterm [] a) x) as d2; autodimp d2 hyp.\n            pose proof (imp (bterm [v] b0) y) as d3; autodimp d3 hyp.\n            pose proof (imp1 (bterm [] a') x0) as d4; autodimp d4 hyp.\n            pose proof (imp1 (bterm [] e) y0) as d5; autodimp d5 hyp.\n            clear imp imp1.\n\n            inversion d1 as [? ? ? df66 dg66 d6]; subst; clear d1.\n            inversion d2 as [? ? ? df77 dg77 d7]; subst; clear d2.\n            inversion d3 as [? ? ? df88 dg88 d8]; subst; clear d3.\n            inversion d4 as [? ? ? df99 dg99 d9]; subst; clear d4.\n            inversion d5 as [? ? ? df10 dg10 d10]; subst; clear d5.\n            repeat match goal with\n                     | [ H : disjoint [] _ |- _ ] => clear H\n                   end.\n\n            inversion d6 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; cpx; clear d6.\n            pose proof (imp1 (bterm [] a') (bterm [] t3)) as d1; autodimp d1 hyp.\n            pose proof (imp1 (bterm [] e) (bterm [] t4)) as d2; autodimp d2 hyp.\n            clear imp1.\n\n            inversion d1 as [? ? ? df33 dg33 d3]; subst; clear d1.\n            inversion d2 as [? ? ? df44 dg44 d4]; subst; clear d2.\n            repeat match goal with\n                     | [ H : disjoint [] _ |- _ ] => clear H\n                   end.\n\n            exists (mk_atom_eq t2 t3 (subst t0 v t4) (mk_exception t3 t4))\n                   (mk_atom_eq a a' (subst b0 v e) (mk_exception a' e));\n              dands; eauto 3 with slow.\n\n            apply differ3_alpha_mk_atom_eq; eauto 4 with slow.\n\n            apply differ3_subst; simpl; eauto 3 with slow.\n\n          - exists (oterm Exc bs3) (oterm Exc bs1); dands; eauto 3 with slow.\n\n            apply reduces_to_if_step; csunf; simpl.\n            unfold compute_step_catch; destruct ncan; tcsp.\n        }\n\n        { SSCase \"Abs\".\n          csunf comp; allsimpl; csunf comp; allsimpl.\n          remember (compute_step_lib lib abs1 bs1) as comp1;\n            symmetry in Heqcomp1.\n          destruct comp1; ginv.\n\n          inversion d as [|?|?|? ? ? len imp]; subst; clear d.\n          destruct bs2; allsimpl; cpx.\n          pose proof (imp (bterm [] (oterm (Abs abs1) bs1)) b0) as d1.\n          autodimp d1 hyp.\n          inversion d1 as [? ? ? df2 sg2 d2]; subst; clear d1.\n          inversion d2 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; cpx; clear d2.\n\n          apply compute_step_lib_success in Heqcomp1; exrepnd; subst.\n\n          assert (differ3_bterms b f g bs1 bs3) as dbs.\n          { unfold differ3_bterms, br_bterms, br_list; auto. }\n\n          pose proof (found_entry_change_bs abs1 oa2 vars rhs lib bs1 correct bs3) as fe2.\n          repeat (autodimp fe2 hyp).\n\n          { apply differ3_bterms_implies_eq_map_num_bvars in dbs; auto. }\n\n          exists\n          (oterm (NCan ncan)\n                 (bterm [] (mk_instance vars bs3 rhs)\n                        :: bs2))\n          (oterm (NCan ncan)\n                 (bterm [] (mk_instance vars bs1 rhs)\n                        :: bs)).\n\n          dands; eauto 3 with slow.\n\n          * apply reduces_to_prinarg.\n            apply reduces_to_if_step.\n            csunf; simpl; unfold on_success.\n            applydup @compute_step_lib_if_found_entry in fe2.\n            rw fe0; auto.\n\n          * pose proof (differ3_mk_instance b f g rhs vars bs1 bs3) as h.\n            repeat (autodimp h hyp); tcsp; GC.\n            { unfold correct_abs in correct; sp. }\n            { allapply @found_entry_implies_matching_entry.\n              allunfold @matching_entry; sp. }\n            { allapply @found_entry_implies_matching_entry.\n              allunfold @matching_entry; sp. }\n            { allunfold @correct_abs; sp. }\n            { allunfold @correct_abs; sp. }\n            unfold differ3_alpha in h.\n            exrepnd.\n\n            exists\n              (oterm (NCan ncan) (bterm [] u1 :: bs))\n              (oterm (NCan ncan) (bterm [] u2 :: bs2)).\n            dands.\n\n            { prove_alpha_eq4.\n              introv j; destruct n;[|destruct n]; try omega; cpx.\n              apply alphaeqbt_nilv2; auto. }\n\n            { prove_alpha_eq4.\n              introv j; destruct n;[|destruct n]; try omega; cpx.\n              apply alphaeqbt_nilv2; auto. }\n\n            { apply differ3_oterm; allsimpl; tcsp.\n              introv j; repndors; cpx. }\n        }\n      }\n\n      { (* fresh case *)\n        csunf comp; allsimpl.\n        apply compute_step_fresh_success in comp; repnd; subst; allsimpl.\n\n        inversion d as [|?|?|? ? ? len1 imp1]; subst; clear d.\n        allsimpl; cpx; allsimpl.\n        pose proof (imp1 (bterm [n] t1) x) as d1; autodimp d1 hyp.\n        clear imp1.\n        inversion d1 as [? ? ? disj11 disj12 d2]; subst; clear d1.\n        allrw disjoint_singleton_l.\n\n        repndors; exrepnd; subst; fold_terms.\n\n        - inversion d2; subst.\n          apply has_value_like_k_fresh_id in hv; sp.\n\n        - applydup @differ3_preserves_isvalue_like in d2; auto.\n          exists (pushdown_fresh n t2) (pushdown_fresh n t1); dands; eauto 3 with slow.\n          { apply reduces_to_if_step.\n            apply compute_step_fresh_if_isvalue_like; auto. }\n          { apply differ3_alpha_pushdown_fresh_isvalue_like; auto. }\n\n        - applydup @differ3_preserves_isnoncan_like in d2; auto;[].\n          allrw app_nil_r.\n\n          pose proof (fresh_atom o (get_utokens t1 ++ get_utokens t2 ++ get_utokens f ++ get_utokens g)) as fa; exrepnd.\n          allrw in_app_iff; allrw not_over_or; repnd.\n          rename x0 into a.\n\n          pose proof (compute_step_subst_utoken lib t1 x [(n,mk_utoken (get_fresh_atom t1))]) as comp'.\n          allrw @get_utokens_sub_cons; allrw @get_utokens_sub_nil; allsimpl.\n          allrw disjoint_singleton_l.\n\n          allrw @wf_fresh_iff.\n\n          repeat (autodimp comp' hyp); try (apply get_fresh_atom_prop); eauto 3 with slow.\n          { apply nr_ut_sub_cons; eauto 3 with slow.\n            intro j; apply get_fresh_atom_prop. }\n          exrepnd.\n          pose proof (comp'0 [(n,mk_utoken a)]) as comp''; clear comp'0.\n          allsimpl.\n          allrw @get_utokens_sub_cons; allrw @get_utokens_sub_nil; allsimpl.\n          allrw disjoint_singleton_l.\n          repeat (autodimp comp'' hyp); exrepnd.\n\n          pose proof (differ3_subst b f g t1 t2 [(n, mk_utoken a)] [(n, mk_utoken a)]) as daeq.\n          repeat (autodimp daeq hyp);\n            try (complete (simpl; apply disjoint_singleton_r; auto));\n            try (complete (apply differ3_subs_refl; simpl; auto));\n            eauto 3 with slow.\n\n          unfold differ3_alpha in daeq; exrepnd.\n\n          pose proof (compute_step_alpha lib (lsubst t1 [(n, mk_utoken a)]) u1 s) as comp'''.\n          repeat (autodimp comp''' hyp); exrepnd; eauto 4 with slow.\n          rename t2' into s'.\n\n          assert (wf_term x) as wfx.\n          { eapply compute_step_preserves_wf;[exact comp2|].\n            allrw @wf_fresh_iff.\n            apply wf_term_subst; eauto 3 with slow. }\n\n          assert (!LIn n (free_vars x)) as ninx.\n          { intro i; apply compute_step_preserves in comp2; repnd; eauto 4 with slow.\n            rw subvars_prop in comp0; apply comp0 in i; clear comp0.\n            apply eqset_free_vars_disjoint in i; allsimpl.\n            allrw in_app_iff; allrw in_remove_nvars; allsimpl; boolvar; allsimpl; tcsp. }\n\n          applydup @alphaeq_preserves_wf_term in daeq0; auto;\n          [|apply lsubst_preserves_wf_term; eauto 3 with slow];[].\n          applydup @alphaeq_preserves_wf_term in daeq2; auto;\n          [|apply lsubst_preserves_wf_term; eauto 3 with slow];[].\n          applydup @compute_step_preserves_wf in comp'''1; auto;[].\n          applydup @alphaeq_preserves_wf_term_inv in comp'''0; auto;[].\n\n          pose proof (ind t1 u1 [n]) as q; clear ind.\n          repeat (autodimp q hyp).\n          { apply alpha_eq_preserves_osize in daeq0; rw <- daeq0; allrw @fold_subst.\n            rw @simple_osize_subst; eauto 3 with slow. }\n          pose proof (q u2 kk s') as ih; clear q.\n          repeat (autodimp ih hyp); fold_terms.\n          { eapply alphaeq_preserves_has_value_like_k;[|exact comp'''0|]; eauto 3 with slow.\n            eapply alphaeq_preserves_has_value_like_k;[|apply alpha_eq_sym;exact comp''0|]; eauto 4 with slow.\n            pose proof (has_value_like_k_ren_utokens\n                          lib\n                          kk\n                          (lsubst w [(n, mk_utoken (get_fresh_atom t1))])\n                          [(get_fresh_atom t1,a)]) as hvl.\n            allsimpl.\n            allrw disjoint_singleton_l; allrw in_remove.\n            repeat (autodimp hvl hyp); eauto 3 with slow.\n            { intro k; repnd.\n              apply get_utokens_lsubst_subset in k; unfold get_utokens_sub in k; allsimpl.\n              allrw in_app_iff; allsimpl; repndors; tcsp. }\n            { eapply alphaeq_preserves_has_value_like_k;[|exact comp'1|]; eauto 3 with slow.\n              apply (has_value_like_k_fresh_implies lib kk (get_fresh_atom t1)) in hv; auto;\n              [|apply wf_subst_utokens; eauto 3 with slow\n               |intro i; apply get_utokens_subst_utokens_subset in i; allsimpl;\n                unfold get_utokens_utok_ren in i; allsimpl; allrw app_nil_r;\n                rw in_remove in i; repnd;\n                apply compute_step_preserves_utokens in comp2; eauto 3 with slow; apply comp2 in i;\n                apply get_utokens_subst in i; allsimpl; boolvar; tcsp].\n              pose proof (simple_subst_subst_utokens_aeq x (get_fresh_atom t1) n) as h.\n              repeat (autodimp h hyp).\n              eapply alphaeq_preserves_has_value_like_k in h;[exact h| |]; eauto 4 with slow.\n            }\n            rw @lsubst_ren_utokens in hvl; allsimpl; fold_terms.\n            unfold ren_atom in hvl; allsimpl; boolvar; tcsp.\n            rw @ren_utokens_trivial in hvl; simpl; auto.\n            apply disjoint_singleton_l; intro i; apply comp'4 in i; apply get_fresh_atom_prop in i; sp.\n          }\n          exrepnd.\n\n          pose proof (reduces_to_alpha lib u2 (lsubst t2 [(n, mk_utoken a)]) t) as r1.\n          repeat (autodimp r1 hyp); eauto 3 with slow.\n          exrepnd.\n\n          pose proof (reduces_to_change_utok_sub\n                        lib t2 t2' [(n,mk_utoken a)] [(n,mk_utoken (get_fresh_atom t2))]) as r1'.\n          allrw @get_utokens_sub_cons; allrw @get_utokens_sub_nil; allsimpl.\n          allrw disjoint_singleton_l.\n          repeat (autodimp r1' hyp); try (apply get_fresh_atom_prop); eauto 3 with slow.\n          { apply nr_ut_sub_cons; eauto 3 with slow.\n            intro j; apply get_fresh_atom_prop. }\n          exrepnd.\n          allrw disjoint_singleton_l.\n          fold_terms; allrw @fold_subst.\n\n          pose proof (reduces_to_fresh lib t2 s0 n) as q; simpl in q.\n          repeat (autodimp q hyp).\n          exrepnd.\n\n          (* 1st exists *)\n          exists (mk_fresh n z).\n\n          assert (!LIn a (get_utokens w)) as niaw.\n          { intro k; apply comp'4 in k; sp. }\n\n          pose proof (alpha_eq_subst_utokens\n                        x (subst w n (mk_utoken (get_fresh_atom t1)))\n                        [(get_fresh_atom t1, mk_var n)]\n                        [(get_fresh_atom t1, mk_var n)]) as aeqs.\n          repeat (autodimp aeqs hyp); eauto 3 with slow.\n          pose proof (simple_alphaeq_subst_utokens_subst\n                        w n (get_fresh_atom t1)) as aeqs1.\n          autodimp aeqs1 hyp.\n          eapply alpha_eq_trans in aeqs1;[|exact aeqs]; clear aeqs.\n\n          pose proof (reduces_to_alpha lib s' (subst w n (mk_utoken a)) u') as raeq.\n          repeat (autodimp raeq hyp); eauto 3 with slow; exrepnd;[].\n          rename t2'0 into u''.\n\n          assert (wf_term w) as wfw.\n          { allrw @wf_fresh_iff.\n            apply compute_step_preserves_wf in comp2;\n              [|apply wf_term_subst;eauto 3 with slow].\n            apply alphaeq_preserves_wf_term in comp'1; auto.\n            apply lsubst_wf_term in comp'1; auto.\n          }\n\n          pose proof (reduces_to_fresh2 lib w u'' n a) as rf.\n          repeat (autodimp rf hyp); exrepnd.\n\n          pose proof (reduces_to_alpha\n                        lib\n                        (mk_fresh n w)\n                        (mk_fresh n (subst_utokens x [(get_fresh_atom t1, mk_var n)]))\n                        (mk_fresh n z0)) as r'.\n          repeat (autodimp r' hyp).\n          { apply nt_wf_fresh; eauto 3 with slow. }\n          { apply implies_alpha_eq_mk_fresh; eauto 3 with slow. }\n          exrepnd.\n          rename t2'0 into f'.\n\n          (* 2nd exists *)\n          exists f'; dands; auto.\n          eapply differ3_alpha_l;[apply alpha_eq_sym; exact r'0|].\n          apply differ3_alpha_mk_fresh; auto.\n          eapply differ3_alpha_l;[exact rf0|].\n          eapply differ3_alpha_r;[|apply alpha_eq_sym; exact q0].\n          eapply differ3_alpha_l;[apply alpha_eq_sym;apply alpha_eq_subst_utokens_same;exact raeq0|].\n          eapply differ3_alpha_r;[|apply alpha_eq_sym;apply alpha_eq_subst_utokens_same;exact r1'1].\n\n          pose proof (simple_alphaeq_subst_utokens_subst w0 n (get_fresh_atom t2)) as aeqsu.\n          autodimp aeqsu hyp.\n          { intro j; apply r1'4 in j; apply get_fresh_atom_prop in j; sp. }\n\n          eapply differ3_alpha_r;[|apply alpha_eq_sym;exact aeqsu];clear aeqsu.\n\n          apply (alpha_eq_subst_utokens_same _ _ [(a, mk_var n)]) in r1'0.\n          pose proof (simple_alphaeq_subst_utokens_subst w0 n a) as aeqsu.\n          autodimp aeqsu hyp.\n\n          eapply differ3_alpha_r;[|exact aeqsu];clear aeqsu.\n          eapply differ3_alpha_r;[|exact r1'0].\n          eapply differ3_alpha_r;[|apply alpha_eq_subst_utokens_same; exact r0].\n          apply differ3_alpha_subst_utokens; simpl; auto; allrw disjoint_singleton_r; auto.\n      }\n\n    + SCase \"Exc\".\n      csunf comp; allsimpl; ginv.\n\n      inversion d as [|?|?|? ? ? ni len imp]; subst; allsimpl; cpx; clear d.\n\n      exists (oterm Exc bs2) (oterm Exc bs); dands; eauto 3 with slow.\n\n    + SCase \"Abs\".\n      csunf comp; allsimpl.\n\n      inversion d as [|?|?|? ? ? ni len imp]; subst; clear d.\n\n      apply compute_step_lib_success in comp; exrepnd; subst.\n\n      assert (differ3_bterms b f g bs bs2) as dbs.\n      { unfold differ3_bterms, br_bterms, br_list; auto. }\n\n      pose proof (found_entry_change_bs abs oa2 vars rhs lib bs correct bs2) as fe2.\n      repeat (autodimp fe2 hyp).\n\n      { apply differ3_bterms_implies_eq_map_num_bvars in dbs; auto. }\n\n      exists (mk_instance vars bs2 rhs) (mk_instance vars bs rhs).\n\n      dands; eauto 3 with slow.\n\n      * apply reduces_to_if_step.\n        csunf; simpl; unfold on_success.\n        applydup @compute_step_lib_if_found_entry in fe2.\n        rw fe0; auto.\n\n      * pose proof (differ3_mk_instance b f g rhs vars bs bs2) as h.\n        repeat (autodimp h hyp); tcsp; GC.\n        { unfold correct_abs in correct; sp. }\n        { allapply @found_entry_implies_matching_entry.\n          allunfold @matching_entry; sp. }\n        { allapply @found_entry_implies_matching_entry.\n          allunfold @matching_entry; sp. }\n        { allunfold @correct_abs; sp. }\n        { allunfold @correct_abs; sp. }\nQed.\n\n(*\nLemma isvalue_like_except_implies_isvalue_like {o} :\n  forall a (t : @NTerm o),\n    isvalue_like_except a t\n    -> isvalue_like t.\nProof.\n  introv isv.\n  unfold isvalue_like_except in isv; sp.\nQed.\nHint Resolve isvalue_like_except_implies_isvalue_like : slow.\n\nLemma alpha_eq_preserves_isvalue_like_except {o} :\n  forall a (t1 t2 : @NTerm o),\n    alpha_eq t1 t2\n    -> isvalue_like_except a t1\n    -> isvalue_like_except a t2.\nProof.\n  introv aeq isv.\n  allunfold @isvalue_like_except; repnd.\n  applydup @alpha_eq_preserves_isvalue_like in aeq; auto.\n  dands; auto.\n  intro k.\n  apply isnexc_implies in k; exrepnd; subst.\n  inversion aeq; subst; allsimpl; boolvar; ginv; tcsp.\nQed.\n*)\n\nLemma comp_force_int3_aux {o} :\n  forall lib f g (t1 t2 : @NTerm o) b u,\n    isprog f\n    -> isprog g\n    -> wf_term t1\n    -> wf_term t2\n    -> agree_upto_b lib b f g\n    -> differ3 b f g t1 t2\n    -> isvalue_like u\n    -> reduces_to lib t1 u\n    -> {v : NTerm & reduces_to lib t2 v # differ3_alpha b f g u v}.\nProof.\n  introv ispf ispg wt1 wt2 agree d isv comp.\n  unfold reduces_to in comp; exrepnd.\n  revert t1 t2 u wt1 wt2 d isv comp0.\n  induction k as [n ind] using comp_ind_type; introv wt1 wt2 d isv r.\n  destruct n as [|k]; allsimpl.\n\n  - allrw @reduces_in_atmost_k_steps_0; subst.\n    exists t2; dands; eauto 3 with slow.\n\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n\n    pose proof (comp_force_int_step3 lib b f g t1 t2 k u0) as h.\n    repeat (autodimp h hyp).\n\n    { exists u; unfold computes_to_val_like_in_max_k_steps; sp. }\n\n    { introv l' w1 w2 i' r' d'.\n      apply (ind m l' t0 t3); auto. }\n\n    exrepnd.\n\n    pose proof (reduces_in_atmost_k_steps_if_reduces_to\n                  lib k u0 u' u) as h'.\n    repeat (autodimp h' hyp); eauto 3 with slow.\n    exrepnd.\n\n    unfold differ3_alpha in h1; exrepnd.\n\n    applydup @preserve_nt_wf_compute_step in r1; eauto 3 with slow.\n    applydup @reduces_to_preserves_wf in h2; eauto 3 with slow.\n    applydup @reduces_to_preserves_wf in h0; eauto 3 with slow.\n    applydup @alphaeq_preserves_wf_term in h4; eauto 3 with slow.\n\n    pose proof (reduces_in_atmost_k_steps_alpha\n                  lib u' u1) as h''.\n    repeat (autodimp h'' hyp); eauto 3 with slow.\n\n    pose proof (h'' k' u) as h'''; clear h''.\n    autodimp h''' hyp; exrepnd.\n\n    pose proof (ind k') as h.\n    autodimp h hyp;[omega|].\n    pose proof (h u1 u2 t2') as r'; clear h.\n    repeat (autodimp r' hyp); eauto 3 with slow.\n\n    exrepnd.\n\n    pose proof (reduces_to_steps_alpha lib u2 t v) as r'.\n    repeat (autodimp r' hyp); eauto 3 with slow.\n    exrepnd.\n    exists u3; dands; eauto 3 with slow.\n\n    { eapply reduces_to_trans; eauto. }\n\n    { allunfold @differ3_alpha; exrepnd.\n      exists u4 u5; dands; eauto 3 with slow. }\nQed.\n\nLemma comp_force_int3 {o} :\n  forall lib f g (t1 t2 : @NTerm o) b z,\n    isprog f\n    -> isprog g\n    -> wf_term t1\n    -> wf_term t2\n    -> agree_upto_b lib b f g\n    -> differ3 b f g t1 t2\n    -> reduces_to lib t1 (mk_integer z)\n    -> reduces_to lib t2 (mk_integer z).\nProof.\n  introv ispf ispg wt1 wt2 agree d comp.\n  pose proof (comp_force_int3_aux lib f g t1 t2 b (mk_integer z)) as h.\n  repeat (autodimp h hyp); eauto 3 with slow.\n\n  exrepnd.\n  apply differ3_alpha_integer in h0; subst; auto.\nQed.\n\nLemma differ_app_F3 {o} :\n  forall b (F : @NTerm o) x f g,\n    !LIn x (free_vars f)\n    -> !LIn x (free_vars g)\n    -> disjoint (bound_vars F) (free_vars f)\n    -> disjoint (bound_vars F) (free_vars g)\n    -> differ3\n         b\n         f g\n         (force_int_bound_F x b F f (mk_vbot x))\n         (force_int_bound_F x b F g (mk_vbot x)).\nProof.\n  introv ni1 ni2 df dg.\n  constructor; simpl; tcsp.\n  introv i; dorn i;[|dorn i]; cpx.\n  - constructor; eauto 3 with slow.\n  - constructor; auto; constructor; simpl; tcsp.\n    introv i; dorn i; cpx.\n    constructor; allrw disjoint_singleton_l; auto; constructor; simpl; auto.\nQed.\n\nLemma comp_force_int_app_F3 {o} :\n  forall lib (F f g : @NTerm o) x z b,\n    wf_term F\n    -> isprog f\n    -> isprog g\n    -> !LIn x (free_vars f)\n    -> !LIn x (free_vars g)\n    -> disjoint (bound_vars F) (free_vars f)\n    -> disjoint (bound_vars F) (free_vars g)\n    -> agree_upto_b lib b f g\n    -> reduces_to\n         lib\n         (force_int_bound_F x b F f (mk_vbot x))\n         (mk_integer z)\n    -> reduces_to\n         lib\n         (force_int_bound_F x b F g (mk_vbot x))\n         (mk_integer z).\nProof.\n  introv wF wf wg ni1 ni2 df dg agree r.\n\n  apply (comp_force_int3 _ f g (force_int_bound_F x b F f (mk_vbot x)) _ b); eauto 4 with slow.\n\n  apply differ_app_F3; auto; allrw; tcsp.\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/continuity3_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.2862607791529429}}
{"text": "Require Export List.\nRequire Export Bool.\nRequire Export Arith.\nRequire Export Peano_dec.\nRequire Export Coq.Arith.PeanoNat.\nRequire Export Coq.Program.Wf.\nRequire Export Coq.Program.Tactics.\nRequire Export Coq.Logic.FunctionalExtensionality.\nRequire Export Recdef.\n\nRequire Import common.CpdtTactics.\nRequire Import common.wyv_common.\nRequire Import common.rhs_mat_tree.\n\nRequire Export common.lhs_sel_upp_reduce.rhs_sel_equ_reduce.\nRequire Export common.lhs_sel_upp_reduce.rhs_sel_upp_reduce.\nRequire Export common.lhs_sel_upp_reduce.rhs_sel_low_reduce.\nRequire Export common.lhs_sel_upp_reduce.rhs_sel_nom_reduce.\nRequire Export common.lhs_sel_upp_reduce.rhs_sel_bnd_reduce.\n\nRequire Export common.lhs_sel_upp_reduce.rhs_bot_reduce.\n\nRequire Export common.lhs_sel_upp_reduce.rhs_all_reduce.\n\nRequire Export common.lhs_sel_upp_reduce.rhs_sha_sel_reduce.\nRequire Export common.lhs_sel_upp_reduce.rhs_sha_top_reduce.\nRequire Export common.lhs_sel_upp_reduce.rhs_rfn_sel_reduce.\nRequire Export common.lhs_sel_upp_reduce.rhs_rfn_top_reduce.\n\nRequire Export common.lhs_sel_upp_reduce.rhs_upp_reduce.\nRequire Export common.lhs_sel_upp_reduce.rhs_nom_reduce.\nRequire Export common.lhs_sel_upp_reduce.rhs_equ_reduce.\nRequire Export common.lhs_sel_upp_reduce.rhs_low_reduce.\n\nRequire Export common.lhs_sel_upp_reduce.rhs_nil_reduce.\nRequire Export common.lhs_sel_upp_reduce.rhs_con_reduce.\n\nImport WfExtensionality.\n\nLemma subtype_sel_upp_reduce :\n  forall T1 x1 L1 T1',\n    T1 = (t_sel_upp x1 L1 T1') ->\n    forall T2, subtype T1 T2 = match T2 with\n                          | t_top => true\n                          | t_sel_low x2 L2 T2' => orb (andb (eq_var x1 x2) (eq_label L1 L2)) (orb (subtype T1' T2) (subtype T1 T2'))\n                          | t_sel_equ x2 L2 T2' => orb (andb (eq_var x1 x2) (eq_label L1 L2)) (orb (subtype T1' T2) (subtype T1 T2'))\n                          | t_sel_upp x2 L2 _ => orb (andb (eq_var x1 x2) (eq_label L1 L2)) (subtype T1' T2)\n                          | t_sel_nom x2 L2 _ => orb (andb (eq_var x1 x2) (eq_label L1 L2)) (subtype T1' T2)\n                          | t_sel_bnd x2 L2 => orb (andb (eq_var x1 x2) (eq_label L1 L2)) (subtype T1' T2)\n                          | t_upp L2 T2' => false\n                          | t_low L2 T2' => false\n                          | t_equ L2 T2' => false\n                          | t_nom L2 T2' => false\n\n                          | t_nil => false\n                          | t_con _ _ => false\n                                          \n                          | _ => subtype T1' T2\n                          end.\nProof.\n  intros.\n\n  destruct T2.\n\n  apply subtype_top;\n    subst;\n    intros;\n    intro Hcontra;\n    inversion Hcontra.\n\n  subst;\n    apply subtype_sel_upp_bot_reduce\n      with (x1:=x1)(L1:=L1);\n    auto.\n\n  subst;\n    apply subtype_sel_upp_sel_upp_reduce\n      with (x1:=x1)(L1:=L1)(T2':=T2);\n    auto.\n\n  subst;\n    apply subtype_sel_upp_sel_low_reduce\n      with (x1:=x1)(L1:=L1)(T2':=T2);\n    auto.\n\n  subst;\n    apply subtype_sel_upp_sel_equ_reduce\n      with (x1:=x1)(L1:=L1)(T2':=T2);\n    auto.\n\n  subst;\n    apply subtype_sel_upp_sel_nom_reduce\n      with (x1:=x1)(L1:=L1)(T2':=T2);\n    auto.\n\n  subst;\n    apply subtype_sel_upp_sel_bnd_reduce\n      with (x1:=x1)(L1:=L1);\n    auto.\n\n  subst;\n    apply subtype_sel_upp_rfn_top_reduce\n      with (x1:=x1)(L1:=L1)(Ts:=T2);\n    auto.\n\n  subst;\n    apply subtype_sel_upp_rfn_sel_reduce\n      with (x1:=x1)(L1:=L1)(x2:=v)(L2:=l)(Ts:=T2_1)(T':=T2_2);\n    auto.\n\n  subst;\n    apply subtype_sel_upp_sha_top_reduce\n      with (x1:=x1)(L1:=L1)(x2:=v)(L2:=l)(ss2:=d);\n    auto.\n\n  subst;\n    apply subtype_sel_upp_sha_sel_reduce\n      with (x1:=x1)(L1:=L1)(x2:=v)(L2:=l)(T':=T2)(ss2:=d);\n    auto.\n\n  subst;\n    apply subtype_sel_upp_all_reduce\n      with (x1:=x1)(L1:=L1)(T:=T2_1)(T':=T2_2);\n    auto.\n\n  subst;\n    apply subtype_sel_upp_upp_reduce\n      with (x1:=x1)(L1:=L1)(T1':=T1')(L2:=l)(T2':=T2);\n    auto.\n\n  subst;\n    apply subtype_sel_upp_low_reduce\n      with (x1:=x1)(L1:=L1)(T1':=T1')(L2:=l)(T2':=T2);\n    auto.\n\n  subst;\n    apply subtype_sel_upp_equ_reduce\n      with (x1:=x1)(L1:=L1)(T1':=T1')(L2:=l)(T2':=T2);\n    auto.\n\n  subst;\n    apply subtype_sel_upp_nom_reduce\n      with (x1:=x1)(L1:=L1)(T1':=T1')(L2:=l)(T2':=T2);\n    auto.\n\n  subst T1; erewrite subtype_sel_upp_nil_reduce; eauto.\n\n  subst T1; erewrite subtype_sel_upp_con_reduce; eauto.\n  \nQed.", "meta": {"author": "JulianMackay", "repo": "Wyvern_Formalism", "sha": "7072f2803b500c73c42347544740768e81a8beca", "save_path": "github-repos/coq/JulianMackay-Wyvern_Formalism", "path": "github-repos/coq/JulianMackay-Wyvern_Formalism/Wyvern_Formalism-7072f2803b500c73c42347544740768e81a8beca/wself/lhs_sel_upp_reduce/lhs_sel_upp_reduce.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2862245875659663}}
{"text": "(*Require Import Coq.Logic.FunctionalExtensionality.*)\n(*Require Import Coq.Logic.Eqdep.*)\n\nRequire Export CatSem.RPCF.RPCF_rep.\nRequire Export CatSem.CAT.eq_fibre.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nSet Transparent Obligations.\nUnset Automatic Introduction.\n\nNotation \"M [( s )]\" := (FIB_RMOD_HOM M s) (at level 30).\nNotation \"f 'X' g\" := (product_mor _ f g)(at level 30).\nNotation \"f ** rho\" := (colax_PbRMod_Hom f rho)(at level 34).\n\nNotation \"'IsoPF'\" := (colax_Pb_Fib _ _ _).\nNotation \"'IsoFP'\" := (colax_Fib_Pb _ _ _).\nNotation \"'IsoXP'\" := (colax_PROD_PM _ _ _ _ ).\n\n(*Notation \"f 'D' r [( s )] \" := (DerFib_RMod_Hom f s r) (at level 33).*)\n\nNotation \"*--->*\" := (unit_rmod _ ).\n\n(** morphisms of representations *)\n\n(*\n\nSection arrow_lemmata.\n\nVariables U U': Type.\nVariable Uar : U -> U -> U.\nVariable U'ar : U' -> U' -> U'.\n\nNotation \"u >>> v\" := (U'ar u v) (at level 60, right associativity).\nNotation \"u >> v\" := (Uar u v) (at level 60, right associativity).\n\nVariable g : U -> U'.\nHypothesis H : forall u v, g (u >> v) = g u >>> g v.\n\nLemma arrow_distrib3 : forall u v w, \n   g (u >> v >> w) = \n   g u >>> g v >>> g w.\nProof.\n  intros u v w.\n  repeat rewrite H.\n  reflexivity.\nDefined.\n\nLemma arrow_distrib4 : forall u v y z, \n   g (u >> v >> y >> z) =\n   g u >>> g v >>> g y >>> g z.\nProof.\n  intros u v y z.\n  repeat rewrite H.\n  reflexivity.\nDefined.\n\n\nVariable Ubool : U.\nVariable Unat : U.\nVariable U'bool : U'.\nVariable U'nat : U'.\n\nHypothesis gnat : g Unat = U'nat.\nHypothesis gbool : g Ubool = U'bool.\n\nLemma n_ar_n : g (Unat >> Unat) = U'nat >>> U'nat.\nProof.\n  rewrite <- gnat.\n  apply H.\nDefined.\n\n\n\n(*\nLemma arrow_dist_ct2 : forall r s,\n  g (f r >> f s) = \n  f' r >>> f' s.\nProof.\n  intros.\n  repeat rewrite H.\n  repeat rewrite H'.\n  reflexivity.\nDefined.\n\nLemma arrow_dist_ct3 : forall r s t ,\n  g (f r >> f s >> f t) =\n  f' r >>> f' s >>> f' t.\nProof.\n  intros.\n  repeat rewrite H.\n  repeat rewrite H'.\n  reflexivity.\nDefined.\n\n\nLemma arrow_dist_ct4 : forall r s t u,\n  g (f r >> f s >> f t >> f u) =\n  f' r >>> f' s >>> f' t >>> f' u.\nProof.\n  intros.\n  repeat rewrite H.\n  repeat rewrite H'.\n  reflexivity.\nDefined.\n*)\n(*\nVariable U'' : Type.\nVariable f'' : T -> U''.\nVariable g' : U' -> U''.\nVariable U''ar : U'' -> U'' -> U''.\n\nNotation \"u >>>> v\" := (U''ar u v)\n       (at level 60, right associativity).\n\nHypothesis Hg' : forall u v,\n       g' (u >>> v) = g' u >>>> g' v.\n       \n\nLemma comp_arrow_dist:\nforall u v : U,\n  (fun t => g' (g t)) (u >> v) =\n  (fun t => g' (g t)) u >>>>\n  (fun t => g' (g t) ) v.\nProof.\n  simpl.\n  intros.\n  rewrite H.\n  rewrite Hg'.\n  reflexivity.\nDefined.\n\nHypothesis Hgf : forall t, g' (f' t) = f'' t.\n\nLemma comp_arrow_commute : \n   forall t, g' (g (f t)) = f'' t.\nProof.\n  intros.\n  rewrite H'.\n  rewrite Hgf.\n  reflexivity.\nDefined.\n*)\nEnd arrow_lemmata.\n*)\n\nSection rep_hom.\n\nVariables P R : PCFPO_rep.\n\nSection Rep_Hom_Class.\n\n(** a morphism of representations \n        - (U, f, P, Rep)\n        - (U', f', Q, Rep')\n   is given by \n        - g : U -> U'\n        - H : f ; g = f'\n        - generalized monad morphism P -> Q (with F = RETYPE g)\n        - properties\n*)\n\nVariable Sorts_map : Sorts P -> Sorts R.\n(*Hypothesis H : forall t, f (type_mor P t) = type_mor R t.*)\nHypothesis HArrow : forall u v, Sorts_map (u ~~> v) = Sorts_map u ~~> Sorts_map v.\nHypothesis HBool : Sorts_map (Bool _ ) = Bool _ .\nHypothesis HNat : Sorts_map (Nat _ ) = Nat _ .\n\n\nVariable f : colax_RMonad_Hom P R \n    (G1:=RETYPE (fun t => Sorts_map t))\n    (G2:=RETYPE_PO (fun t => Sorts_map t)) \n  (RT_NT (fun t => Sorts_map t)).\n\n(*\nDefinition MM := gen_PbRMod_ind_Hom M.\nCheck FFib_Mod_Hom. Check FIB_RMOD_HOM.\nPrint FIB_RMOD_eq.\n*)\n\n\n\n(*\nCheck (fun r s => FIB_RMOD_eq (gen_PbRMod M R) (H (r ~> s))).\nCheck (fun r s => app (P:=P) r s).\nCheck (fun r s => app (P:=P) r s ;; \n                  FIB_RMOD_HOM M _  ).\nCheck (fun r s => app (P:=P) r s ;; \n                  FIB_RMOD_HOM M _  ;;\n                  gen_pb_fib _ _ _ ).\n\nCheck FIB_RMOD_HOM.\n\nCheck (fun u v => \n\n               gen_PROD_PM _ _ _ _ ;;\n               gen_PbRMod_Hom M (app (f u) (f v))).\n\nCheck (fun u v => FIB_RMOD_HOM M (u ~~> v);;\n                  FIB_RMOD_eq _ (H' _ _ );;\n                  gen_pb_fib M _ _ ).\n\nCheck (fun u =>  (FIB_RMOD_HOM M (u) ;;\n              gen_pb_fib _ _ _ )).\n\nCheck (fun u v =>  \n          product_mor _\n             (FIB_RMOD_HOM M ((u ~~> v)) ;;\n              FIB_RMOD_eq _ (H' _ _);;\n              gen_pb_fib M _ _ )\n             (FIB_RMOD_HOM M (u) ;;\n              gen_pb_fib M _ _ )).\n \nCheck (fun (u v : type_type P) => app u v;;\n             FIB_RMOD_HOM M _ ).\n\nCheck (fun u v => \n\n           product_mor _ \n             (FIB_RMOD_HOM M ((u ~~> v)) ;;\n              FIB_RMOD_eq _ (H' _ _);;\n              gen_pb_fib _ _ _ )\n             (FIB_RMOD_HOM M (u) ;;\n              gen_pb_fib _ _ _ )\n            ;;\n           gen_PROD_PM _ _ _ _ \n            ;;\n           gen_PbRMod_Hom _ (app (f u) (f v))\n           ==\n           app u v;;\n             FIB_RMOD_HOM M _ ;;\n             gen_pb_fib _ _ _ ).\n*)\n(* this is the correct diag for app *)\n\n(*\nCheck (fun u v : type_type P => abs u v ;;\n             FIB_RMOD_HOM M _ ;;\n             FIB_RMOD_eq _ (H' _ _ ) ;;\n             gen_pb_fib _ _ _ ).\n\nCheck (der_fib_hom).\nCheck (fun u v => der_fib_hom_noeq _ _ _ ;; \n                gen_pb_fib _ _ _ ;;\n                gen_PbRMod_Hom M (abs (f u) (f v))).\n\nCheck (fun u v =>  abs u v ;;\n             FIB_RMOD_HOM M _ ;;\n             FIB_RMOD_eq _ (H' _ _ ) ;;\n             gen_pb_fib _ _ _ \n             ==\n             der_fib_hom_noeq _ _ _ ;; \n                gen_pb_fib _ _ _ ;;\n                gen_PbRMod_Hom M (abs (f u) (f v))).\n\nCheck FFib_DER_Mod_Hom_eqrect.\nCheck der_fib_hom.\n*)\n\n(*\nPrint gen_pb_fib.\nCheck (fun s => gen_pb_fib M s R).\nCheck (der_fib_hom).\n\n\nCheck (fun r s =>   der_fib_hom M _ (H _ ) ;;\n                    FIB_RMOD_eq _ (H _ ) ;;\n                    gen_pb_fib M (type_mor R s) (d R // type_mor R r) ;; \n                    gen_PbRMod_Hom M (abs r s)).\n*)\n(*\nCheck (fun r  s => der_fib_hom _ _ (H r ) ;;\n                  FIB_RMOD_eq M (H s) ). ;;\n                  gen_PbRMod_Hom M (abs r s)).\n  *)   \n(*             \nCheck (fun r s => abs r s ;; \n                  FIB_RMOD_HOM M _ ;;\n                  FIB_RMOD_eq _ (H _ );;\n                  gen_pb_fib _ _ _ ).\n\nCheck (fun t => unit_rmod M  ;; gen_PbRMod_Hom _ (bottom t )).\nCheck (fun t => bottom t ;; \n                FIB_RMOD_HOM M _ ;;\n                FIB_RMOD_eq _ (H _ );;\n                gen_pb_fib _ _ _ ).\n\nCheck (tttt (PCFPO_rep_struct := P) ;; FIB_RMOD_HOM M _ ).\n\nCheck Term.\n\nPrint gen_pb_fib.\n\n*)\n(*\nCheck True.\nCheck (CondB (PCFPO_rep_struct := P)).\n\nCheck (arrow_dist_ct4 H' H).\n\nCheck (CondB  (PCFPO_rep_struct := P) ;;\n          FIB_RMOD_HOM M _  ;;\n          FIB_RMOD_eq _ (arrow_dist_ct4 H' H _ _ _ _)).\n\nCheck FIB_RMOD_small_eq.\n*)\n(*\nCheck FIB_RMOD_HOM.\nCheck (CondB (PCFPO_rep_struct := P)).\n*)\n\nObligation Tactic := \n        intros; simpl; repeat (rew_all || auto).\n\n(*Print Succ.*)\nImplicit Arguments Succ [Sorts P Arrow Bool Nat PCFPO_rep_struct].\n(*Print Succ.*)\nImplicit Arguments CondB [Sorts P Arrow Bool Nat PCFPO_rep_struct].\nImplicit Arguments CondN [Sorts P Arrow Bool Nat PCFPO_rep_struct].\nImplicit Arguments Pred [Sorts P Arrow Bool Nat PCFPO_rep_struct].\nImplicit Arguments Zero [Sorts P Arrow Bool Nat PCFPO_rep_struct].\nImplicit Arguments ffff [Sorts P Arrow Bool Nat PCFPO_rep_struct].\nImplicit Arguments tttt [Sorts P Arrow Bool Nat PCFPO_rep_struct].\nImplicit Arguments Nat [p].\nImplicit Arguments Bool [p].\n(*Print nats.*)\n(*\nImplicit Arguments bottom [U P Arrow Bool Nat].\nImplicit Arguments nats [U P Arrow Bool Nat].\nImplicit Arguments bottom [U P Arrow Bool Nat].\n*)\n\n(*Print app.*)\n\nProgram Definition Succ_hom' := \n  Succ  (*PCFPO_rep_struct := P*) ;; f [(Nat ~~> Nat)] ;;\n(*                FIB_RMOD_HOM M _ ;; *)\n                Fib_eq_RMod _ ( _ );; \n(*                colax_Pb_Fib f _ _ *)\n                IsoPF\n           ==\n           *--->* ;;\n(*           unit_rmod f  ;; *)\n           f ** (Succ  (*PCFPO_rep_struct := R*)).\n\n\n\nProgram Definition CondB_hom' := CondB (*PCFPO_rep_struct := P*) ;;\n                f [( _ )] ;;\n                Fib_eq_RMod _ ( _ );;\n(*                colax_Pb_Fib _ _ _ *)\n                IsoPF\n           ==\n           *--->* ;;\n(*           unit_rmod f  ;; *)\n           f ** (CondB (*PCFPO_rep_struct := R*)).\n\n\nProgram Definition CondN_hom' := CondN (*PCFPO_rep_struct := P*) ;;\n                f [( _ )] ;;\n                Fib_eq_RMod _ _ ;; \n                IsoPF\n           ==\n           *--->* ;;\n(*           unit_rmod f  ;; *)\n           f ** (CondN (*PCFPO_rep_struct := R*)).\n\n\nProgram Definition Pred_hom' := Pred (*PCFPO_rep_struct := P*) ;;\n                f [( _ )] ;;\n                Fib_eq_RMod _ _ ;; \n                IsoPF\n           ==\n           *--->* ;;\n(*           unit_rmod f  ;; *)\n           f ** (Pred (*PCFPO_rep_struct := R*)) .\n\nProgram Definition Zero_hom' := Zero (*PCFPO_rep_struct := P*) ;;\n                f [( _ )] ;;\n                Fib_eq_RMod _ _;; \n                IsoPF\n           ==\n           *--->* ;;\n(*           unit_rmod f  ;; *)\n           f ** (Zero (*PCFPO_rep_struct := R*)).\n\n\nProgram Definition fff_hom' := ffff (*PCFPO_rep_struct := P*) ;;\n                f [( _ )] ;;\n                Fib_eq_RMod _ _ ;; \n                IsoPF\n           ==\n           *--->* ;;\n(*           unit_rmod f  ;; *)\n           f ** (ffff (*PCFPO_rep_struct := R*)).\n\nProgram Definition ttt_hom' := tttt (*PCFPO_rep_struct := P*) ;;\n                f [( _ )] ;;\n                Fib_eq_RMod _ _ ;; \n                IsoPF\n           ==\n           *--->*  ;;\n(*           unit_rmod f ;; *)\n           f ** (tttt (*PCFPO_rep_struct := R*)).\n \nProgram Definition bottom_hom' := forall u,\n           bottom u ;; \n                f [( _ )] ;;\n(*                FIB_RMOD_eq _ (H _ );; *)\n             IsoPF\n           ==\n           *--->*  ;;\n(*           unit_rmod f  ;; *)\n           f ** (bottom (_)).\n\nProgram Definition nats_hom' := forall m,\n           nats m ;;\n                f [( _ )] ;;\n                Fib_eq_RMod _ ( _ );; \n                IsoPF\n           ==\n           *--->*  ;;\n(*           unit_rmod f  ;; *)\n           f ** (nats m).\n\n\n\nProgram Definition app_hom' := forall u v, \n(*          product_mor _ *)\n             (f [(u ~~> v)] ;;\n              Fib_eq_RMod _ (HArrow _ _);;\n              (*colax_Pb_Fib _ _ _ )*) IsoPF ) X \n             (f [(u)] ;;\n              (*colax_Pb_Fib _ _ _ )*)\n              IsoPF )\n            ;;\n(*           colax_PROD_PM _ _ _ _ *)\n             IsoXP\n            ;;\n(*           colax_PbRMod_Hom _ (app (_ u) (_ v)) *)\n           f ** (app _ _ )\n           ==\n           app u v;;\n             f [( _ )] ;; IsoPF.\n(*             colax_Pb_Fib _ _ _ .*)\n\n\n\n (* abs_hom : forall u v,\n       abs u v ;;\n             FIB_RMOD_HOM M _ ;;\n             FIB_RMOD_small_eq _ (H' _ _ ) ;;\n             gen_pb_fib _ _ _ \n             ==\n             der_fib_hom_noeq _ _ _ ;; \n                gen_pb_fib _ _ _ ;;\n                gen_PbRMod_Hom M (abs (f u) (f v))\n;*)\n\nProgram Definition rec_hom' := forall t,\n      rec t ;; \n         f [( _ )] ;; IsoPF\n(*        colax_Pb_Fib f _ _ *)\n      ==\n      f [( _ )] ;;\n      Fib_eq_RMod _  (HArrow _ _) ;;\n(*      colax_Pb_Fib f _ _ ;; *)\n        IsoPF ;;\n      f ** (rec (_ t)) .\n\n\nProgram Definition  abs_hom' := forall u v,\n     abs u v ;;\n         f [( _ )]\n(*        FIB_RMOD_small_eq _ (H' _ _ ) ;;\n        gen_pb_fib _ _ _  *)\n             ==\n        DerFib_RMod_Hom _ _ _ ;; \n(*        D f d u [( v )]  ;; *)\n(*        colax_Pb_Fib _ _ _ ;; *)\n        IsoPF ;;\n        f ** (abs (_ u) (_ v)) ;;\n(*\tcolax_Fib_Pb _ _ _  ;;*)\n        IsoFP ;;\n\tFib_eq_RMod _ (eq_sym (HArrow _ _ )) .\n\n\nClass PCFPO_rep_Hom_struct := {\n\n  CondB_hom :  CondB_hom' \n;\n  CondN_hom : CondN_hom'\n;\n  Pred_hom : Pred_hom'\n;\n  Zero_hom : Zero_hom'\n;\n  Succ_hom : Succ_hom'\n;\n  fff_hom : fff_hom'\n\n;\n  ttt_hom : ttt_hom'\n; \n  bottom_hom : bottom_hom'\n;\n  nats_hom : nats_hom'\n;\n\n  app_hom : app_hom'\n;\n (* abs_hom : forall u v,\n       abs u v ;;\n             FIB_RMOD_HOM M _ ;;\n             FIB_RMOD_small_eq _ (H' _ _ ) ;;\n             gen_pb_fib _ _ _ \n             ==\n             der_fib_hom_noeq _ _ _ ;; \n                gen_pb_fib _ _ _ ;;\n                gen_PbRMod_Hom M (abs (f u) (f v))\n;*)\n  rec_hom : rec_hom'\n;\n  abs_hom : abs_hom'\n}.\n\nEnd Rep_Hom_Class.\n\n\n(** the type of morphismes of representations P -> R *)\n\nRecord PCFPO_rep_Hom := {\n  Sorts_map : Sorts P -> Sorts R ;\n  HArrow : forall u v, Sorts_map (u ~~> v) = Sorts_map u ~~> Sorts_map v;\n  HNat : Sorts_map (Nat _ ) = Nat R ;\n  HBool : Sorts_map (Bool _ ) = Bool R ;\n  rep_Hom_monad :> colax_RMonad_Hom P R (RT_NT (fun t => Sorts_map t));\n  rep_colax_Hom_monad_struct :> PCFPO_rep_Hom_struct \n                 HArrow HBool HNat rep_Hom_monad\n}.\n\nEnd rep_hom.\n\nExisting Instance rep_colax_Hom_monad_struct.\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/RPCF/RPCF_rep_hom.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.28622435708289706}}
{"text": "Require Import Syntax.\nRequire Import SemanticsStatic.\nRequire Import SemanticsDynamic.\n\nLemma transmission : forall program Psi Delta Delta' Gamma Gamma' P P' theta v T,\n  value_t v ->\n  transmittable_type T ->\n  peers_tied program P' P ->\n  List.incl theta (peer_instances_of_type program P) ->\n  program :: Psi; Delta; Gamma; P |- v : T ->\n  program :: Psi; Delta'; Gamma'; P' |- zeta P theta v T : T.\nProof.\nintros until T.\nintros H_value H_transmittable H_tied H_instance H_typing.\ngeneralize dependent T.\ninduction v; intros; inversion H_value; inversion H_typing; subst.\n- inversion H_transmittable.\n- apply T_Unit.\n- apply T_None.\n- inversion H_transmittable.\n  simpl.\n  apply T_Some.\n  apply IHv; assumption.\n- apply T_Nil.\n- inversion H_transmittable.\n  simpl.\n  apply T_Cons.\n  + apply IHv1; assumption.\n  + apply IHv2; assumption.\n- apply T_Peer. assumption.\n- destruct H7; subst.\n  + simpl.\n    apply T_Signal.\n    apply T_ComFrom with (T0 := Unit).\n    * inversion H_transmittable.\n      assumption.\n    * apply U_Unit.\n    * apply T_Unit.\n    * apply T_Now with (T0 := Signal T1); try (left; reflexivity).\n      apply T_Reactive with (T1 := T1); try (left; reflexivity).\n      assumption.\n    * assumption.\n    * apply T_Peer.\n      assumption.\n  + inversion H_transmittable.\n- apply T_Nat.\nQed.\n", "meta": {"author": "scala-loci", "repo": "formalization", "sha": "4047b3425e7d187f03c0e2f244706491c10e9960", "save_path": "github-repos/coq/scala-loci-formalization", "path": "github-repos/coq/scala-loci-formalization/formalization-4047b3425e7d187f03c0e2f244706491c10e9960/ProofTransmission.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.28622435708289706}}
{"text": "From LogRel.AutoSubst Require Import core unscoped Ast Extra.\nFrom LogRel Require Import Utils BasicAst Notations Context NormalForms UntypedReduction Weakening GenericTyping LogicalRelation DeclarativeInstance.\nFrom LogRel.LogicalRelation Require Import Induction Reflexivity Irrelevance Escape.\n\nSet Universe Polymorphism.\n\nSection Neutral.\nContext `{GenericTypingProperties}.\n\nDefinition neu {l Γ A} : Ne[Γ |- A] -> [Γ |- A] -> [ Γ |- A ~ A : U] -> [Γ ||-<l> A].\nProof.\n  intros neA wtyA reflA. apply LRne_.\n  exists A; [gen_typing|..]; assumption.\nDefined.\n\nLemma neU {l Γ A n} (h : [Γ ||-U<l> A]) :\n  Ne[Γ |- n : A] ->\n  [Γ |- n : A] ->\n  [Γ |- n ~ n : A] ->\n  [LogRelRec l | Γ ||-U n : A | h].\nProof.\n  assert [Γ |- A ≅ U] by (destruct h; gen_typing).\n  intros; exists n.\n  * eapply redtmwf_conv; tea; now eapply redtmwf_refl.\n  * now eapply NeType, tm_ne_whne.\n  * eapply tm_nf_conv; [|gen_typing|eassumption].\n    now eapply tm_ne_nf.\n  * eapply convtm_conv; tea; gen_typing.\n  * eapply RedTyRecBwd, neu. 2,3: gen_typing.\n    eapply ty_ne_term, tm_ne_conv; now gen_typing.\nDefined.\n\n\nLemma neElim {Γ l K} : [Γ ||-<l> K] -> whne K -> [Γ ||-ne K].\nProof.\n  intros h; pattern l,Γ,K,h; eapply LR_rect_TyUr;\n  clear l Γ K h.\n  - intros ??? [??? r] ne; pose proof (redtywf_whne r  ne); subst; inversion ne.\n  - intros; assumption.\n  - intros ??? [?? red] ?? ne ; cbn in *.\n    rewrite (redtywf_whne red ne) in ne.\n    inversion ne.\n  - intros ??? [red] ne.\n    rewrite (redtywf_whne red ne) in ne.\n    inversion ne.\n  - intros ??? [red] ne.\n    rewrite (redtywf_whne red ne) in ne.\n    inversion ne.\nQed.\n\nSet Printing Primitive Projection Parameters.\n\n\nLemma neuEq {l Γ A B} (RA : [Γ ||-<l> A]) :\n  Ne[Γ |- A] -> Ne[Γ |- B] ->\n  [Γ |- A] -> [Γ |- B] ->\n  [Γ |- A ~ B : U] ->\n  [Γ ||-<l> A ≅ B | RA].\nProof.\n  intros neA neB wtyA wtyB eqAB.\n  unshelve irrelevance0. 1: assumption. 3: reflexivity.\n  1: apply neu; try assumption; now eapply lrefl.\n  econstructor.\n  1: now apply redtywf_refl.\n  all: cbn; assumption.\nQed.\n\nLemma ty_app_ren {Γ Δ A f a dom cod} (ρ : Δ ≤ Γ) :\n  [Γ |- f : A] -> [Γ |- A ≅ tProd dom cod] -> [Δ |- a : dom⟨ρ⟩] -> [Δ |- tApp f⟨ρ⟩ a : cod[a .: ρ >> tRel]].\nProof.\n  intros.\n  replace (cod[a .: ρ >> tRel]) with (cod⟨wk_up dom ρ⟩[a..]) by (now bsimpl).\n  unshelve eapply ty_app. 3: eassumption.\n  replace (tProd _ _) with (tProd dom cod)⟨ρ⟩ by now bsimpl.\n  gen_typing.\nQed.\n\nLemma convneu_app_ren {Γ Δ A f g a b dom cod} (ρ : Δ ≤ Γ) :\n  [Γ |- f ~ g : A] ->\n  [Γ |- A ≅ tProd dom cod] ->\n  [Δ |- a ≅ b : dom⟨ρ⟩] ->\n  [Δ |- tApp f⟨ρ⟩ a ~ tApp g⟨ρ⟩ b : cod[a .: ρ >> tRel]].\nProof.\n  intros.\n  replace (cod[a .: ρ >> tRel]) with (cod⟨wk_up dom ρ⟩[a..]) by (now bsimpl).\n  unshelve eapply convneu_app. 3: eassumption.\n  replace (tProd _ _) with (tProd dom cod)⟨ρ⟩ by now bsimpl.\n  gen_typing.\nQed.\n\nLemma neu_app_ren {Γ Δ A n a dom cod} (ρ : Δ ≤ Γ) :\n  [|- Δ] ->\n  [Γ |- tProd dom cod] ->\n  Ne[Γ |- n : A] -> [Γ |- A ≅ tProd dom cod] -> Nf[Δ |- a : dom⟨ρ⟩] -> Ne[Δ |- tApp n⟨ρ⟩ a : cod[a .: ρ >> tRel]].\nProof.\n  intros.\n  replace (cod[a .: ρ >> tRel]) with (cod⟨wk_up dom ρ⟩[a..]) by (now bsimpl).\n  eapply tm_ne_app; [|eassumption].\n  change (Ne[Δ |- n⟨ρ⟩ : (tProd dom cod)⟨ρ⟩]).\n  eapply tm_ne_conv; [| |now eapply convty_wk].\n  + now eapply tm_ne_wk.\n  + now eapply wft_wk.\nQed.\n\nRecord complete {l Γ A} (RA : [Γ ||-<l> A]) := {\n  reifyTyConv : forall B, [Γ ||-<l> A ≅ B | RA] -> Nf[Γ |- B];\n  reflect : forall n n',\n    Ne[Γ |- n : A] ->\n    Ne[Γ |- n' : A] ->\n    [Γ |- n : A] ->\n    [Γ |- n' : A] ->\n    [Γ |- n ~ n' : A] ->\n    [Γ ||-<l> n : A | RA] × [Γ ||-<l> n ≅ n' : A| RA];\n  reify : forall a, [Γ ||-<l> a : A | RA] -> Nf[ Γ |- a : A];\n}.\n\nLemma complete_reflect_simpl {l Γ A} (RA : [Γ ||-<l> A]) (c : complete RA) :\n  forall n, Ne[Γ |- n : A] -> [Γ |- n : A] -> [Γ |- n ~ n : A] -> [Γ ||-<l> n : A | RA].\nProof.\nintros; eapply c.\n5: eassumption.\nall: assumption.\nQed.\n\nLemma complete_var0 {l Γ A A'} (RA : [Γ ,, A ||-<l> A']) :\n  complete RA ->\n  [Γ ,, A |- A⟨↑⟩ ≅ A'] ->\n  [Γ |- A] ->\n  [Γ ,, A ||-<l> tRel 0 : A' | RA].\nProof.\n  intros cRA conv HA.\n  assert [Γ ,, A |- tRel 0 : A']\n  by (eapply ty_conv; tea; escape; eapply (ty_var (wfc_wft EscRA) (in_here _ _))).\n  eapply complete_reflect_simpl; tea.\n  - eapply tm_ne_conv; tea. \n    2: now escape. \n    now eapply tm_ne_rel.\n  - eapply convneu_var; tea.\nQed.\n\n\nLemma complete_U : forall l Γ A (RA : [Γ ||-U< l > A]), complete (LRU_ RA).\nProof.\nintros l Γ A h0; split.\n- intros ? [].\n  eapply ty_nf_red, ty_nf_sort; gen_typing.\n- intros ?? ???? h; pose proof (lrefl h); pose proof (urefl h).\n  assert [Γ |- A ≅ U] by (destruct h0; gen_typing); split.\n  2: unshelve econstructor.\n  1-3: now apply neU.\n  + eapply RedTyRecBwd, neu. 2,3: try gen_typing.\n    eapply ty_ne_term, tm_ne_conv; tea; gen_typing.\n  + cbn. gen_typing.\n  + eapply RedTyRecBwd; apply neu. 2, 3: gen_typing.\n    eapply ty_ne_term, tm_ne_conv; tea; gen_typing.\n  + eapply TyEqRecBwd. eapply neuEq. all: try gen_typing.\n    all: eapply ty_ne_term, tm_ne_conv; tea; gen_typing.\n- intros a [a' Hr Ha].\n  assert ([Γ |-[ ta ] U ≅ A]).\n  { destruct h0; gen_typing. }\n  eapply tm_nf_conv; [| |eassumption].\n  + eapply tm_nf_red; [eapply tmr_wf_red|]; eassumption.\n  + now eapply escape, LRU_.\nQed.\n\nLemma complete_ne : forall l Γ A (RA : [Γ ||-ne A]), complete (LRne_ l RA).\nProof.\nintros l Γ A h0; split.\n- intros ? [].\n  eapply ty_nf_red; [|now apply ty_ne_nf].\n  gen_typing.\n- destruct h0 as [B []]; intros ** ; assert ([Γ |- A ≅ B]) by gen_typing ; split.\n  + exists n; cbn.\n    * eapply redtmwf_refl ; gen_typing.\n    * now eapply tm_ne_conv.\n    * eapply lrefl; eapply convneu_conv; eassumption.\n  + exists n n'; cbn.\n    1,2: eapply redtmwf_refl ; eapply ty_conv; gen_typing.\n    1,2: now eapply tm_ne_conv.\n    gen_typing.\n- intros a [a' Hr Hne].\n  assert ([Γ |-[ ta ] neRedTy.ty h0 ≅ A]).\n  { destruct h0; simpl in *; symmetry.\n    eapply convty_exp; [now apply tyr_wf_red| |].\n    all: gen_typing. }\n  eapply tm_nf_conv; [| |eassumption].\n  + eapply tm_nf_red; [now apply tmr_wf_red|].\n    now apply tm_ne_nf.\n  + now eapply escape, LRne_ with (l := l).\nQed.\n\nLemma complete_Pi : forall l Γ A (RA : [Γ ||-Π< l > A]),\n  (forall (Δ : context) (ρ : Δ ≤ Γ) (h : [ |-[ ta ] Δ]),\n        complete (PiRedTyPack.domRed RA ρ h)) ->\n  (forall (Δ : context) (a : term) (ρ : Δ ≤ Γ) (h : [ |-[ ta ] Δ])\n          (ha : [PiRedTyPack.domRed RA ρ h | Δ ||- a : (PiRedTyPack.dom RA)⟨ρ⟩]),\n        complete (PiRedTyPack.codRed RA ρ h ha)) ->\n  complete (LRPi' RA).\nProof.\nintros l Γ A ΠA0 ihdom ihcod; split.\n- intros B ΠB.\n  assert (tΓ : [|- Γ]) by (destruct ΠA0; gen_typing).\n  eapply ty_nf_red; [apply tyr_wf_red, ΠB|].\n  assert [PiRedTyPack.domRed ΠA0 wk_id tΓ | Γ ||- (PiRedTyPack.dom ΠA0)⟨wk_id⟩ ≅ PiRedTyEq.dom ΠB].\n  1: erewrite <- wk_id_ren_on; eapply (PiRedTyEq.domRed ΠB).\n  eapply ty_nf_prod.\n  + now eapply ihdom.\n  + destruct ΠB as [dom cod ?? domRed codRed] ; cbn in *.\n    assert [|- Γ ,, dom]. 1:{\n      apply wfc_cons; tea.\n      now eapply escapeConv.\n    }\n    eapply ihcod.\n    replace cod with cod[tRel 0 .: @wk1 Γ dom >> tRel].\n    2: bsimpl ; rewrite scons_eta' ; now bsimpl.\n    eapply codRed.\n    Unshelve.  1: tea.\n    eapply complete_var0.\n      * eapply ihdom.\n      * symmetry; eapply escapeEq; erewrite <- wk1_ren_on.\n        unshelve eapply domRed. tea.\n      * now eapply escapeConv.\n- set (ΠA := ΠA0); destruct ΠA0 as [dom cod].\n  simpl in ihdom, ihcod.\n  assert [Γ |- A ≅ tProd dom cod] by gen_typing.\n  unshelve refine ( let funred : forall n, Ne[Γ |- n : A] -> [Γ |- n : A] -> [Γ |- n ~ n : A] -> [Γ ||-Π n : A | PiRedTyPack.toPiRedTy ΠA] := _ in _).\n  {\n    intros. exists n; cbn.\n    * eapply redtmwf_refl ; gen_typing.\n    * now eapply NeFun, tm_ne_whne.\n    * eapply tm_nf_conv; [| |eassumption].\n      + now eapply tm_ne_nf.\n      + now eapply wft_prod.\n    * gen_typing.\n    * intros; apply complete_reflect_simpl; [apply ihcod| |..].\n      { eapply neu_app_ren; try eassumption.\n        + now apply wft_prod.\n        + now apply (ihdom _ ρ h). }\n      1: escape ; now eapply ty_app_ren.\n      eapply convneu_app_ren. 1,2: eassumption.\n      eapply LREqTermRefl_ in ha.\n      now escape.\n    * intros. apply ihcod.\n      + eapply neu_app_ren; try eassumption.\n        -- now apply wft_prod.\n        -- now apply (ihdom _ ρ h).\n      + eapply tm_ne_conv.\n        - eapply neu_app_ren; try eassumption.\n          -- now apply wft_prod.\n          -- now apply (ihdom _ ρ h).\n        - now eapply escape, codRed.\n        - symmetry. now unshelve eapply escapeEq, codExt.\n      + apply escapeTerm in ha; now eapply ty_app_ren.\n      + pose proof (cv := escapeEq _ (codExt _ _ _ ρ _ ha hb eq0)).\n        symmetry in cv; unshelve eapply (ty_conv _ cv).\n        apply escapeTerm in hb; now eapply ty_app_ren.\n      + apply escapeEqTerm in eq0; now eapply convneu_app_ren.\n  }\n  intros ?????? h.\n  pose proof (lrefl h); pose proof (urefl h).\n  split. 1: now apply funred.\n  unshelve econstructor.\n  1,2: now apply funred.\n  all: cbn; clear funred.\n  * gen_typing.\n  * intros. apply ihcod; cbn.\n    + eapply neu_app_ren; try eassumption.\n      -- now apply wft_prod.\n      -- now eapply (ihdom _ ρ).\n    + eapply neu_app_ren; try eassumption.\n      -- now apply wft_prod.\n      -- now eapply (ihdom _ ρ).\n    + apply escapeTerm in ha; now eapply ty_app_ren.\n    + apply escapeTerm in ha; now eapply ty_app_ren.\n    + eapply convneu_app_ren. 1,2: eassumption.\n    eapply escapeEqTerm; eapply LREqTermRefl_; eassumption.\n- intros a [a' Hr Ha].\n  destruct ΠA0 as [dom codom]; simpl in *.\n  assert ([Γ |- tProd dom codom ≅ A ]) by gen_typing.\n  eapply tm_nf_conv; [| |eassumption].\n  * eapply tm_nf_red; [now apply tmr_wf_red|].\n    assumption.\n  * destruct red; gen_typing.\nQed.\n\nLemma complete_Nat {l Γ A} (NA : [Γ ||-Nat A]) : complete (LRNat_ l NA).\nProof.\n  split.\n  - intros ? [].\n    eapply ty_nf_red, ty_nf_nat; gen_typing.\n  - intros. \n    assert [Γ |- A ≅ tNat] by (destruct NA; gen_typing). \n    assert [Γ |- n : tNat] by now eapply ty_conv.\n    split; econstructor.\n    1,4,5: eapply redtmwf_refl; tea; now eapply ty_conv.\n    2,4: do 2 constructor; tea.\n    1,7: eapply convtm_convneu.\n    1,4: eapply lrefl.\n    4-6: now (eapply tm_ne_conv; gen_typing).\n    all: eapply convneu_conv; tea.\n  - simpl in *.\n    assert [Γ |- tNat ≅ A] by (destruct NA; gen_typing).\n    assert [Γ |- A] by now (destruct NA; gen_typing).\n    intros a Ha; eapply tm_nf_conv; [|eassumption|eassumption]; revert a Ha.\n    let T := match goal with |- ?P => P end in\n    enough (IH : T × (forall (a : term) (n : NatProp NA a), Nf[ Γ |-[ ta ] a : tNat])); [apply IH|].\n    apply NatRedInduction.\n    + intros.\n      eapply tm_nf_red; [now apply tmr_wf_red|eassumption].\n    + eapply tm_nf_zero; gen_typing.\n    + intros; now eapply tm_nf_succ.\n    + intros ne []. apply tm_ne_nf. assumption.\nQed.\n\nLemma complete_Empty {l Γ A} (NA : [Γ ||-Empty A]) : complete (LREmpty_ l NA).\nProof.\n  split.\n  - intros ? [].\n    eapply ty_nf_red, ty_nf_empty; gen_typing.\n  - intros. \n    assert [Γ |- A ≅ tEmpty] by (destruct NA; gen_typing). \n    assert [Γ |- n : tEmpty] by now eapply ty_conv.\n    split; econstructor.\n    1,4,5: eapply redtmwf_refl; tea; now eapply ty_conv.\n    2,4: do 2 constructor; tea.\n    1,7: eapply convtm_convneu.\n    1,4: eapply lrefl.\n    4-6: now (eapply tm_ne_conv; gen_typing).\n    all: eapply convneu_conv; tea.\n  - simpl in *.\n    assert [Γ |- tEmpty ≅ A] by (destruct NA; gen_typing).\n    intros a Ha; eapply tm_nf_conv; [| |eassumption].\n    + destruct Ha.\n      destruct prop.\n      destruct r.\n      eapply tm_nf_red. exact red.\n      now apply tm_ne_nf.\n    + destruct NA as [[]]; gen_typing.\nQed.\n\nLemma completeness {l Γ A} (RA : [Γ ||-<l> A]) : complete RA.\nProof.\nrevert l Γ A RA; eapply LR_rect_TyUr; cbn; intros.\n- now apply complete_U.\n- now apply complete_ne.\n- now apply complete_Pi.\n- now apply complete_Nat.\n- now apply complete_Empty.\nQed.\n\nLemma neuTerm {l Γ A} (RA : [Γ ||-<l> A]) {n} :\n  Ne[Γ |- n : A] ->\n  [Γ |- n : A] ->\n  [Γ |- n ~ n : A] ->\n  [Γ ||-<l> n : A | RA].\nProof.\n  intros.  now eapply completeness.\nQed.\n\nLemma neuTermEq {l Γ A} (RA : [Γ ||-<l> A]) {n n'} :\n  Ne[Γ |- n : A] ->\n  Ne[Γ |- n' : A] ->\n  [Γ |- n : A] ->\n  [Γ |- n' : A] ->\n  [Γ |- n ~ n' : A] ->\n  [Γ ||-<l> n ≅ n' : A| RA].\nProof.\n  intros; now eapply completeness.\nQed.\n\nLemma var0conv {l Γ A A'} (RA : [Γ ,, A ||-<l> A']) :\n  [Γ,, A |- A⟨↑⟩ ≅ A'] ->\n  [Γ |- A] ->\n  [Γ ,, A ||-<l> tRel 0 : A' | RA].\nProof.\n  apply complete_var0 ; now eapply completeness.\nQed.\n\nLemma var0 {l Γ A A'} (RA : [Γ ,, A ||-<l> A']) :\n  A⟨↑⟩ = A' ->\n  [Γ |- A] ->\n  [Γ ,, A ||-<l> tRel 0 : A' | RA].\nProof.\n  intros eq.\n  apply var0conv.\n  rewrite eq.\n  unshelve eapply escapeEq; tea.\n  eapply LRTyEqRefl_.\nQed.\n\nLemma reifyTerm {l Γ A} (RA : [Γ ||-<l> A]) {t} : [Γ ||-<l> t : A | RA] -> Nf[Γ |- t : A].\nProof.\nintros; now eapply completeness.\nQed.\n\nLemma reifyType {l Γ A} (RA : [Γ ||-<l> A]) : Nf[Γ |- A].\nProof.\n  unshelve eapply reifyTyConv; tea.\n  1: now eapply completeness.\n  apply LRTyEqRefl_.\nQed.\n\nEnd Neutral.\n", "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/LogicalRelation/Neutral.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.286224357082897}}
{"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import TableDataOpsIntro.Spec.\nRequire Import TableDataOpsRef2.Spec.\n\nLocal Open Scope Z_scope.\n\nSection SpecLow.\n\n  Definition table_create3_spec0 (g_rd: Pointer) (map_addr: Z64) (level: Z64) (g_rtt: Pointer) (rtt_addr: Z64) (adt: RData) : option (RData * Z64) :=\n    match g_rd, map_addr, level, g_rtt, rtt_addr with\n    | (_g_rd_base, _g_rd_ofst), VZ64 _map_addr, VZ64 _level, (_g_rtt_base, _g_rtt_ofst), VZ64 _rtt_addr =>\n      rely is_int64 _map_addr;\n      rely is_int64 _level;\n      rely is_int64 _rtt_addr;\n      when' _t'1, adt == table_create2_spec (_g_rd_base, _g_rd_ofst) (VZ64 _map_addr) (VZ64 _level) (_g_rtt_base, _g_rtt_ofst) (VZ64 _rtt_addr) 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/TableDataOpsRef3/LowSpecs/table_create3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283035, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.2862243507044631}}
{"text": "Require Import Lia.\nRequire Import Classical Peano_dec.\nFrom hahn Require Import Hahn.\nRequire Import AuxDef.\nRequire Import Events.\n\nSet Implicit Arguments.\n\n(** Definition of an execution *)\nRecord execution :=\n  { acts_set : actid -> Prop ;\n    threads_set : thread_id -> Prop;\n    lab : actid -> label;\n    rmw : actid -> actid -> Prop ;\n    data : actid -> actid -> Prop ;   (** data dependency *)\n    addr : actid -> actid -> Prop ;   (** address dependency *)\n    ctrl : actid -> actid -> Prop ;   (** control dependency *)\n\n    (** Representation of a data dependency to CAS.\n        It goes from a read to an exclusive read.\n        Consider the example:\n\n        a := [x];\n        CAS(y, a, 1);\n        \n        In the execution, there is an rmw_dep edge between a read event representing `a := [x]'\n        and a read event representing `CAS(y, a, 1)'.\n     *)\n    rmw_dep : actid -> actid -> Prop ;\n\n    rf : actid -> actid -> Prop ;\n    co : actid -> actid -> Prop ;\n  }.\n\nSection Execution.\n\nVariable G : execution.\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 \"'E'\" := (acts_set G).\nNotation \"'threads_set'\" := (threads_set G).\nNotation \"'lab'\" := (lab G).\nNotation \"'rf'\" := (rf G).\nNotation \"'co'\" := (co G).\nNotation \"'rmw'\" := (rmw G).\nNotation \"'data'\" := (data G).\nNotation \"'addr'\" := (addr G).\nNotation \"'ctrl'\" := (ctrl G).\nNotation \"'rmw_dep'\" := (rmw_dep G).\n\nNotation \"'loc'\" := (loc lab).\nNotation \"'val'\" := (val lab).\nNotation \"'mod'\" := (Events.mod lab).\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)).\nNotation \"'RW'\" := (R ∪₁ W).\nNotation \"'FR'\" := (F ∪₁ R).\nNotation \"'FW'\" := (F ∪₁ W).\nNotation \"'R_ex'\" := (fun a => is_true (R_ex lab a)).\n\nNotation \"'Pln'\" := (is_only_pln lab).\nNotation \"'Rlx'\" := (is_rlx lab).\nNotation \"'Rel'\" := (is_rel lab).\nNotation \"'Acq'\" := (is_acq lab).\nNotation \"'Acqrel'\" := (is_acqrel lab).\nNotation \"'Acq/Rel'\" := (is_ra lab).\nNotation \"'Sc'\" := (is_sc lab).\n\nDefinition sb := ⦗E⦘ ⨾ ext_sb ⨾  ⦗E⦘.\n\nRecord Wf :=\n  { wf_index : forall a b, \n      E a /\\ E b /\\ a <> b /\\ tid a = tid b /\\ ~ is_init a -> index a <> index b ;\n    data_in_sb : data ⊆ sb ;\n    wf_dataD : data ≡ ⦗R⦘ ⨾ data ⨾ ⦗W⦘ ;\n    addr_in_sb : addr ⊆ sb ;\n    wf_addrD : addr ≡ ⦗R⦘ ⨾ addr ⨾ ⦗RW⦘ ;\n    ctrl_in_sb : ctrl ⊆ sb ;\n    wf_ctrlD : ctrl ≡ ⦗R⦘ ⨾ ctrl ;\n    ctrl_sb : ctrl ⨾ sb ⊆ ctrl ;\n    wf_rmwD : rmw ≡ ⦗R⦘ ⨾ rmw ⨾ ⦗W⦘ ;\n    wf_rmwl : rmw ⊆ same_loc ;\n    wf_rmwi : rmw ⊆ immediate sb ;\n    wf_rfE : rf ≡ ⦗E⦘ ⨾ rf ⨾ ⦗E⦘ ;\n    wf_rfD : rf ≡ ⦗W⦘ ⨾ rf ⨾ ⦗R⦘ ;\n    wf_rfl : rf ⊆ same_loc ;\n    wf_rfv : funeq val rf ;\n    wf_rff : functional rf⁻¹ ;\n    wf_coE : co ≡ ⦗E⦘ ⨾ co ⨾ ⦗E⦘ ;\n    wf_coD : co ≡ ⦗W⦘ ⨾ co ⨾ ⦗W⦘ ;\n    wf_col : co ⊆ same_loc ;\n    co_trans : transitive co ;\n    wf_co_total : forall ol, is_total (E ∩₁ W ∩₁ (fun x => loc x = ol)) co ;\n    co_irr : irreflexive co ;\n    wf_init : forall l, (exists b, E b /\\ loc b = Some l) -> E (InitEvent l) ;\n    wf_init_lab : forall l, lab (InitEvent l) = Astore Xpln Opln l 0 ;\n\n    rmw_dep_in_sb : rmw_dep ⊆ sb ;\n    wf_rmw_depD : rmw_dep ≡ ⦗R⦘ ⨾ rmw_dep ⨾ ⦗R_ex⦘ ;\n(*     failed_rmw_fail : rmw_dep ⨾ rmw ⊆ ∅₂ ; *)\n\n    wf_threads : forall e (EE : E e), threads_set (tid e);\n  }.\n(*   ⟪  wf_rmw_deps : rmw ⊆ data ∪ addr ∪ ctrl ⟫ /\\\n  ⟪  wf_rmw_ctrl : rmw ⨾ sb ⊆ ctrl ⟫. *)\n\nImplicit Type WF : Wf.\n\n(******************************************************************************)\n(** ** Derived relations  *)\n(******************************************************************************)\n\n(* reads-before, aka from-read *)\nDefinition fr := rf⁻¹ ⨾ co.\n\nDefinition deps := data ∪ addr ∪ ctrl.\n\n(******************************************************************************)\n(** ** Consistency definitions  *)\n(******************************************************************************)\n\nDefinition complete := E ∩₁ R  ⊆₁ codom_rel rf.\nDefinition rmw_atomicity := rmw ∩ ((fr \\ sb) ⨾ (co \\ sb)) ⊆ ∅₂.\n\n(******************************************************************************)\n(** ** Basic transitivity properties *)\n(******************************************************************************)\n\nLemma sb_trans : transitive sb.\nProof using.\nunfold sb; unfolder; ins; desf; splits; auto.\neby eapply ext_sb_trans.\nQed.\n\nLemma sb_sb : sb ⨾ sb ⊆ sb.\nProof using.\ngeneralize sb_trans; basic_solver 21.\nQed.\n\nLemma sb_same_loc_trans: transitive (sb ∩ same_loc).\nProof using.\napply transitiveI.\nunfold Events.same_loc.\nunfolder; ins; desf; eauto.\nsplits.\ngeneralize sb_trans; basic_solver 21.\ncongruence.\nQed.\n\nLemma sb_same_loc_W_trans : transitive (sb ∩ same_loc ⨾ ⦗W⦘).\nProof using.\n  generalize sb_same_loc_trans; unfold transitive.\n  basic_solver 21.\nQed.\n\n\n(******************************************************************************)\n(** ** Basic properties *)\n(******************************************************************************)\n\nLemma E_in_RW_F_AcqRel (FACQREL : E ∩₁ F ⊆₁ Acq/Rel) :\n  E ⊆₁ R ∪₁ W ∪₁ F ∩₁  Acq/Rel.\nProof using.\n  arewrite (E ⊆₁ E ∩₁ E).\n  arewrite (E ⊆₁ R ∪₁ W ∪₁ F) at 2 by type_solver.\n  rewrite set_inter_union_r.\n  generalize FACQREL. clear. basic_solver 10.\nQed.\n\nLemma sb_neq_loc_in_sb : sb \\ same_loc ⊆ sb.\nProof using. basic_solver. Qed.\n\nLemma fr_co WF : fr ⨾ co ⊆ fr.\nProof using. by unfold fr; rewrite seqA, rewrite_trans; [|apply WF]. Qed.\n\nLemma rmw_in_sb WF: rmw ⊆ sb.\nProof using. rewrite wf_rmwi; basic_solver. Qed.\n\nLemma deps_in_sb WF: deps ⊆ sb.\nProof using. unfold deps; unionL; apply WF. Qed.\n\n(******************************************************************************)\n(** ** Same Location relations  *)\n(******************************************************************************)\n\nLemma loceq_rf WF : funeq loc rf.\nProof using. apply WF. Qed.\n\nLemma loceq_co WF : funeq loc co.\nProof using. apply WF. Qed.\n\nLemma loceq_rmw WF : funeq loc rmw.\nProof using. apply WF. Qed.\n\nLemma loceq_fr WF : funeq loc fr.\nProof using.\nunfold funeq.\nunfold fr; unfolder; ins; desf.\ngeneralize (loceq_co WF), (loceq_rf WF).\ntransitivity (loc z); [symmetry; eauto|eauto].\nQed.\n\nLemma wf_frl WF : fr ⊆ same_loc.\nProof using.\nunfold fr.\nrewrite (wf_rfl WF), (wf_col WF).\nunfold Events.same_loc.\nunfolder; ins; desc; congruence. \nQed.\n\n(******************************************************************************)\n(** ** Relations in graph *)\n(******************************************************************************)\n\nLemma wf_sbE : sb ≡ ⦗E⦘ ⨾ sb ⨾ ⦗E⦘.\nProof using. \nsplit; [|basic_solver].\nunfold sb; basic_solver 42. \nQed.\n\nLemma wf_dataE WF: data ≡ ⦗E⦘ ⨾ data ⨾ ⦗E⦘.\nProof using.\nsplit; [|basic_solver].\narewrite (data ⊆ data ∩ data) at 1.\nrewrite (data_in_sb WF) at 1.\nrewrite wf_sbE at 1.\nbasic_solver.\nQed.\n\nLemma wf_addrE WF: addr ≡ ⦗E⦘ ⨾ addr ⨾ ⦗E⦘.\nProof using.\nsplit; [|basic_solver].\narewrite (addr ⊆ addr ∩ addr) at 1.\nrewrite (addr_in_sb WF) at 1.\nrewrite wf_sbE at 1.\nbasic_solver.\nQed.\n\nLemma wf_ctrlE WF: ctrl ≡ ⦗E⦘ ⨾ ctrl ⨾ ⦗E⦘.\nProof using.\nsplit; [|basic_solver].\narewrite (ctrl ⊆ ctrl ∩ ctrl) at 1.\nrewrite (ctrl_in_sb WF) at 1.\nrewrite wf_sbE at 1.\nbasic_solver.\nQed.\n\nLemma wf_rmw_depE WF: rmw_dep ≡ ⦗E⦘ ⨾ rmw_dep ⨾ ⦗E⦘.\nProof using.\nsplit; [|basic_solver].\narewrite (rmw_dep ⊆ rmw_dep ∩ rmw_dep) at 1.\nrewrite (rmw_dep_in_sb WF) at 1.\nrewrite wf_sbE at 1.\nbasic_solver.\nQed.\n\nLemma wf_depsE WF: deps ≡ ⦗E⦘ ⨾ deps ⨾ ⦗E⦘.\nProof using.\nsplit; [|basic_solver].\nunfold deps.\nrewrite (wf_dataE WF) at 1.\nrewrite (wf_ctrlE WF) at 1.\nrewrite (wf_addrE WF) at 1.\nbasic_solver.\nQed.\n\nLemma wf_rmwE WF : rmw ≡ ⦗E⦘ ⨾ rmw ⨾ ⦗E⦘.\nProof using.\nsplit; [|basic_solver].\narewrite (rmw ⊆ rmw ∩ rmw) at 1.\nrewrite (wf_rmwi WF) at 1.\narewrite (immediate sb ⊆ sb).\nrewrite wf_sbE.\nbasic_solver.\nQed.\n\nLemma wf_frE WF : fr ≡ ⦗E⦘ ⨾ fr ⨾ ⦗E⦘.\nProof using.\nsplit; [|basic_solver].\nunfold fr.\nrewrite (wf_rfE WF) at 1.\nrewrite (wf_coE WF) at 1.\nbasic_solver.\nQed.\n\n(******************************************************************************)\n(** ** Domains and codomains  *)\n(******************************************************************************)\n\nLemma wf_frD WF : fr ≡ ⦗R⦘ ⨾ fr ⨾ ⦗W⦘.\nProof using.\nsplit; [|basic_solver].\nunfold fr.\nrewrite (wf_rfD WF) at 1.\nrewrite (wf_coD WF) at 1.\nbasic_solver.\nQed.\n\nLemma wf_depsD WF : deps ≡ ⦗R⦘ ⨾ deps.\nProof using.\nsplit; [|basic_solver].\nunfold deps.\nrewrite (wf_dataD WF) at 1.\nrewrite (wf_ctrlD WF) at 1.\nrewrite (wf_addrD WF) at 1.\nbasic_solver.\nQed.\n\n(******************************************************************************)\n(** ** Irreflexive relations *)\n(******************************************************************************)\n\nLemma sb_irr : irreflexive sb.\nProof using.\nunfold sb; unfolder; ins; desf.\neby eapply ext_sb_irr.\nQed.\n\nLemma fr_irr WF : irreflexive fr.\nProof using.\nrewrite (wf_frD WF); type_solver.\nQed.\n\n(******************************************************************************)\n(** ** Acyclic relations *)\n(******************************************************************************)\n\nLemma sb_acyclic : acyclic sb.\nProof using.\napply trans_irr_acyclic; [apply sb_irr| apply sb_trans]. \nQed.\n\nLemma co_acyclic WF: acyclic co.\nProof using.\nby apply trans_irr_acyclic; [apply co_irr| apply co_trans]. \nQed.\n\nLemma wf_sb : well_founded sb.\nProof using. \n  unfold Execution.sb.\n  rewrite <- restr_relE. eapply wf_mon; [by apply inclusion_restr| ].\n  apply Wf_nat.well_founded_lt_compat\n    with (f := fun (e: actid) => if e then 0 else index e + 1).\n  intros x y SB. destruct x, y; simpl in *; lia. \nQed.\n\n(******************************************************************************)\n(** ** init *)\n(******************************************************************************)\n\nLemma init_w WF: is_init ⊆₁ W.\nProof using.\nunfolder; ins.\nunfold is_init in *; destruct x; desf.\nspecialize (wf_init_lab WF l); unfold is_w; desf.\nQed.\n\nLemma init_pln WF: is_init ⊆₁ Pln.\nProof using.\nunfolder; ins.\nunfold is_init in *; destruct x; desf.\nspecialize (wf_init_lab WF l); unfold is_only_pln, Events.mod; desf.\nQed.\n\nLemma read_or_fence_is_not_init WF a (A: R a \\/ F a) : ~ is_init a.\nProof using.\ngeneralize ((init_w WF) a).\ntype_solver.\nQed.\n\nLemma no_sb_to_init : sb ≡ sb ⨾  ⦗fun x => ~ is_init x⦘.\nProof using.\nsplit; [|basic_solver].\nunfold sb; rewrite ext_sb_to_non_init at 1; basic_solver.\nQed.\n\nLemma no_sb_cr_to_init :\n  ⦗set_compl is_init⦘ ⨾ sb^? ⊆ ⦗set_compl is_init⦘ ⨾ sb^? ⨾ ⦗set_compl is_init⦘.\nProof using. rewrite no_sb_to_init at 1. clear. basic_solver. Qed.\n\nLemma no_rf_to_init WF : rf ≡ rf ⨾  ⦗fun x => ~ is_init x⦘.\nProof using.\nsplit; [|basic_solver].\nrewrite (wf_rfD WF) at 1.\ngeneralize (read_or_fence_is_not_init WF).\nbasic_solver 42.\nQed.\n\nLemma rmw_from_non_init WF : rmw ≡ ⦗fun x => ~ is_init x⦘ ⨾ rmw.\nProof using.\nsplit; [|basic_solver].\nrewrite (wf_rmwD WF).\ngeneralize (read_or_fence_is_not_init WF).\nbasic_solver 42.\nQed.\n\nLemma rmw_non_init_lr WF : rmw ≡ ⦗set_compl is_init⦘ ⨾ rmw ⨾ ⦗set_compl is_init⦘.\nProof using.\n  split; [|basic_solver].\n  rewrite (rmw_from_non_init WF) at 1.\n  rewrite <- seqA.\n  apply codom_rel_helper.\n  rewrite (rmw_in_sb WF).\n  rewrite no_sb_to_init.\n  basic_solver.\nQed.\n\nLemma init_same_loc WF a b (A: is_init a) (B: is_init b) (LOC: loc a = loc b): \n  a = b.\nProof using.\ndestruct a, b; desf.\ncut (l = l0); [by ins; subst|].\nunfold Events.loc in LOC.\nrewrite (wf_init_lab WF l), (wf_init_lab WF l0) in LOC; desf.\nQed.\n\nLemma Rel_not_init WF : Rel ⊆₁ set_compl is_init.\nProof using. rewrite (init_pln WF). mode_solver. Qed.\n\n(******************************************************************************)\n(** ** More properties *)\n(******************************************************************************)\n\nLemma sb_semi_total_l x y z \n  WF (N: ~ is_init x) (NEQ: y <> z) (XY: sb x y) (XZ: sb x z): \n  sb y z \\/ sb z y.\nProof using.\nunfold sb in *; unfolder in *; desf.\ncut (ext_sb y z \\/ ext_sb z y); [basic_solver 12|].\neapply ext_sb_semi_total_l; eauto.\neapply WF; splits; eauto.\nby unfold ext_sb in *; destruct y,z; ins; desf; desf.\nby unfold ext_sb in *; destruct y,z; ins; desf; desf.\nQed.\n\nLemma sb_semi_total_r x y z \n  WF (N: ~ is_init z) (NEQ: y <> z) (XY: sb y x) (XZ: sb z x): \n  sb y z \\/ sb z y.\nProof using.\ncut ((sb ∪ sb⁻¹) y z); [basic_solver|].\nunfold sb in *; unfolder in *; desf.\ndestruct (classic (is_init y)).\nunfold ext_sb; basic_solver.\ncut (ext_sb y z \\/ ext_sb z y); [basic_solver|].\neapply ext_sb_semi_total_r; eauto.\neapply WF; splits; eauto.\nunfold ext_sb in *; destruct y,z; ins; desf; desf.\nQed.\n\nLemma sb_tid_init x y (SB : sb x y): tid x = tid y \\/ is_init x.\nProof using.\ngeneralize ext_sb_tid_init; unfold sb in *.\nunfolder in *; basic_solver.\nQed.\n\nLemma E_ntid_sb_prcl thread :\n  dom_rel (⦗set_compl is_init⦘ ⨾ sb ⨾ ⦗E ∩₁ NTid_ thread⦘) ⊆₁ E ∩₁ NTid_ thread.\nProof using.\n  rewrite (dom_l wf_sbE).\n  unfolder. ins. desf. splits; auto.\n  match goal with\n  | H : sb _ _ |- _ => rename H into SB\n  end.\n  apply sb_tid_init in SB. desf.\n  intros BB. rewrite BB in *. desf.\nQed.\n\nLemma sb_tid_init': sb ≡ sb ∩ same_tid ∪ ⦗is_init⦘ ⨾ sb.\nProof using.\nsplit; [|basic_solver].\nunfold sb.\nrewrite ext_sb_tid_init' at 1.\nbasic_solver 42.\nQed.\n\nLemma ninit_sb_same_tid : ⦗ set_compl is_init ⦘ ⨾ sb ⊆ same_tid.\nProof using.\n  rewrite sb_tid_init'.\n  basic_solver.\nQed.\n\nLemma same_tid_trans : transitive same_tid.\nProof using.\n  red. unfold same_tid. ins.\n  etransitivity; eauto.\nQed.\n\nLemma tid_sb: ⦗E⦘ ⨾ same_tid ⨾  ⦗E⦘ ⊆ sb^? ∪ sb^{-1} ∪ (is_init × is_init).\nProof using.\nunfold sb.\nrewrite tid_ext_sb.\nbasic_solver 21.\nQed.\n\nLemma tid_n_init_sb: ⦗E⦘ ⨾ same_tid ⨾ ⦗set_compl is_init⦘  ⨾  ⦗E⦘ ⊆ sb^? ∪ sb^{-1}.\nProof using.\nunfold sb.\nsin_rewrite tid_n_init_ext_sb.\nbasic_solver 21.\nQed.\n\nLemma init_ninit_sb (WF : Wf) x y (INIT : is_init x) (ININE : E x) (INE : E y)\n      (NINIT : ~ is_init y): sb x y.\nProof using. \nunfold sb, ext_sb; basic_solver.\nQed.\n\nLemma same_thread x y (X : E x) (Y : E y)\n      (NINIT : ~ is_init x) (ST : tid x = tid y):\n  sb^? x y \\/ sb y x.\nProof using.\ncut (sb^? y x \\/ sb x y); [basic_solver|].\ngeneralize tid_n_init_sb.\nunfold same_tid; basic_solver 10.\nQed.\n\nLemma sb_immediate_adjacent WF:\n ⦗fun a => ~ is_init a⦘ ⨾ immediate sb ≡ ⦗fun a => ~ is_init a⦘ ⨾ (adjacent sb ∩ sb).\nProof using.\napply immediate_adjacent.\n- unfolder; ins; desf; destruct (classic (x=y)); auto.\n  forward (apply (@sb_semi_total_r z y x)); eauto; tauto.\n- unfolder; ins; desf; destruct (classic (x=y)); auto.\n  forward (apply (@sb_semi_total_l z y x)); eauto; tauto.\n- apply sb_trans.\n- apply sb_irr.\nQed.\n\nLemma sb_total t:\n  is_total ((E \\₁ is_init) ∩₁ Tid_ t) sb. \nProof using.\n  red. ins. unfolder in IWa. unfolder in IWb. desc. subst. \n  destruct a, b; try by vauto. simpl in *. subst.\n  pose proof (NPeano.Nat.lt_trichotomy index index0) as LT. \n  des; [left | congruence | right]. \n  all: red; apply seq_eqv_lr; splits; vauto. \nQed. \n\nLemma sb_transp_rmw  WF : sb ⨾ rmw ^{-1} ⊆ sb^?.\nProof using.\nrewrite (rmw_from_non_init WF).\nrewrite (wf_rmwi WF); clear -WF.\nrewrite (sb_immediate_adjacent WF).\nunfold adjacent; basic_solver.\nQed.\n\nLemma transp_rmw_sb  WF :  rmw ^{-1} ⨾ sb ⊆ sb^?.\nProof using.\nrewrite (rmw_from_non_init WF).\nrewrite (wf_rmwi WF); clear -WF.\nrewrite (sb_immediate_adjacent WF).\nunfold adjacent; basic_solver.\nQed.\n\nLemma rf_rf WF : rf ⨾ rf ≡ ∅₂.\nProof using. rewrite (wf_rfD WF); type_solver. Qed.\nLemma rf_co WF : rf ⨾ co ≡ ∅₂.\nProof using. rewrite (wf_rfD WF), (wf_coD WF); type_solver. Qed.\nLemma co_transp_rf WF : co ⨾  rf⁻¹ ≡ ∅₂.\nProof using. rewrite (wf_rfD WF), (wf_coD WF); type_solver. Qed.\nLemma co_fr WF : co ⨾ fr ≡ ∅₂.\nProof using. rewrite (wf_coD WF), (wf_frD WF); type_solver. Qed.\nLemma fr_fr WF : fr ⨾ fr ≡ ∅₂.\nProof using. rewrite (wf_frD WF); type_solver. Qed.\nLemma rf_transp_rf WF: rf ⨾ rf⁻¹ ⊆ ⦗fun _ => True⦘.\nProof using. by apply functional_alt, WF. Qed.\nLemma rf_fr WF : rf ⨾ fr ⊆ co.\nProof using. unfold fr; sin_rewrite rf_transp_rf; rels. Qed.\nLemma rmw_in_sb_loc WF: rmw ⊆ sb ∩ same_loc.\nProof using. by rewrite (loceq_same_loc (loceq_rmw WF)), (rmw_in_sb WF). Qed.\nLemma rf_irr WF: irreflexive rf.\nProof using. rewrite (wf_rfD WF); type_solver. Qed.\nLemma co_co WF: co ⨾ co ⊆ co.\nProof using. apply rewrite_trans, WF. Qed.\n\n(*\nLemma rmw_sb_ct WF: (rmw ⨾ sb)⁺ ⊆ rmw ⨾ sb.\nProof using.\nrewrite ct_begin. \nhahn_frame. rewrite (rmw_in_sb WF).\ngeneralize sb_trans; ins; relsf.\nQed.\n\nLemma rmw_sb_rt WF: (rmw ⨾ sb)＊ ⊆ (rmw ⨾ sb)^?.\nProof using. \nrewrite rtE, (rmw_sb_ct WF); basic_solver.\nQed.\n\nLemma rmw_sb_trans WF: transitive (rmw ⨾ sb).\nProof using.\napply transitiveI.\narewrite (rmw ⨾ sb ⊆ (rmw ⨾ sb)＊) at 2.\nrewrite <- seqA; rewrite <- ct_begin.\nby rewrite (rmw_sb_ct WF).\nQed.\n*)\n\nLemma wf_rmwt WF: rmw ⊆ same_tid.\nProof using.\nrewrite (rmw_from_non_init WF).\nrewrite (rmw_in_sb WF), sb_tid_init'.\nbasic_solver.\nQed.\n\nLemma wf_rmwf WF: functional rmw.\nProof using.\nrewrite (rmw_from_non_init WF).\nrewrite (wf_rmwi WF).\nrewrite (sb_immediate_adjacent WF).\nunfolder; ins; desc.\neapply adjacent_unique1; eauto.\napply sb_acyclic.\nQed.\n\nLemma wf_rmw_invf WF: functional (rmw)⁻¹.\nProof using.\nrewrite (rmw_from_non_init WF).\nrewrite (wf_rmwi WF).\nrewrite (sb_immediate_adjacent WF).\nunfolder; ins; desc.\neapply adjacent_unique2; eauto.\napply sb_acyclic.\nQed.\n\n\n(******************************************************************************)\n(** ** external-internal restrictions *)\n(******************************************************************************)\n\nDefinition rfe := rf \\ sb.\nDefinition coe := co \\ sb.\nDefinition fre := fr \\ sb.\nDefinition rfi := rf ∩ sb.\nDefinition coi := co ∩ sb.\nDefinition fri := fr ∩ sb.\n\nLemma ri_union_re r : r ≡ r ∩ sb ∪ r \\ sb.\nProof using. unfolder; split; ins; desf; tauto. Qed.\n\nLemma rfi_union_rfe : rf ≡ rfi ∪ rfe.\nProof using. apply ri_union_re. Qed.\nLemma coi_union_coe : co ≡ coi ∪ coe.\nProof using. apply ri_union_re. Qed.\nLemma fri_union_fre : fr ≡ fri ∪ fre.\nProof using. apply ri_union_re. Qed.\n\nLemma ri_dom r d1 d2 (DOM: r ≡ ⦗d1⦘ ⨾ r ⨾ ⦗d2⦘) : r ∩ sb ⊆ ⦗d1⦘ ⨾ r ∩ sb ⨾ ⦗d2⦘.\nProof using. rewrite DOM at 1; basic_solver. Qed.\nLemma re_dom r d1 d2 (DOM: r ≡ ⦗d1⦘ ⨾ r ⨾ ⦗d2⦘) : r \\ sb ⊆ ⦗d1⦘ ⨾ (r \\ sb) ⨾ ⦗d2⦘.\nProof using. rewrite DOM at 1; basic_solver. Qed.\n\nLemma wf_rfiE WF: rfi ≡ ⦗E⦘ ⨾ rfi ⨾ ⦗E⦘.\nProof using. split; [|basic_solver]. apply (ri_dom (wf_rfE WF)). Qed.\nLemma wf_coiE WF: coi ≡ ⦗E⦘ ⨾ coi ⨾ ⦗E⦘.\nProof using. split; [|basic_solver]. apply (ri_dom (wf_coE WF)). Qed.\nLemma wf_friE WF: fri ≡ ⦗E⦘ ⨾ fri ⨾ ⦗E⦘.\nProof using. split; [|basic_solver]. apply (ri_dom (wf_frE WF)). Qed.\nLemma wf_rfeE WF: rfe ≡ ⦗E⦘ ⨾ rfe ⨾ ⦗E⦘.\nProof using. split; [|basic_solver]. apply (re_dom (wf_rfE WF)). Qed.\nLemma wf_coeE WF: coe ≡ ⦗E⦘ ⨾ coe ⨾ ⦗E⦘.\nProof using. split; [|basic_solver]. apply (re_dom (wf_coE WF)). Qed.\nLemma wf_freE WF: fre ≡ ⦗E⦘ ⨾ fre ⨾ ⦗E⦘.\nProof using. split; [|basic_solver]. apply (re_dom (wf_frE WF)). Qed.\nLemma wf_rfiD WF : rfi ≡ ⦗W⦘ ⨾ rfi ⨾ ⦗R⦘.\nProof using. split; [|basic_solver]. apply (ri_dom (wf_rfD WF)). Qed.\nLemma wf_coiD WF : coi ≡ ⦗W⦘ ⨾ coi ⨾ ⦗W⦘.\nProof using. split; [|basic_solver]. apply (ri_dom (wf_coD WF)). Qed.\nLemma wf_friD WF : fri ≡ ⦗R⦘ ⨾ fri ⨾ ⦗W⦘.\nProof using. split; [|basic_solver]. apply (ri_dom (wf_frD WF)). Qed.\nLemma wf_rfeD WF : rfe ≡ ⦗W⦘ ⨾ rfe ⨾ ⦗R⦘.\nProof using. split; [|basic_solver]. apply (re_dom (wf_rfD WF)). Qed.\nLemma wf_coeD WF : coe ≡ ⦗W⦘ ⨾ coe ⨾ ⦗W⦘.\nProof using. split; [|basic_solver]. apply (re_dom (wf_coD WF)). Qed.\nLemma wf_freD WF : fre ≡ ⦗R⦘ ⨾ fre ⨾ ⦗W⦘.\nProof using. split; [|basic_solver]. apply (re_dom (wf_frD WF)). Qed.\n\nLemma rfi_in_sb : rfi ⊆ sb.\nProof using. unfold rfi; basic_solver. Qed.\n\nLemma rfi_in_rf : rfi ⊆ rf.\nProof using. unfold rfi; basic_solver. Qed.\n\nLemma rfe_in_rf : rfe ⊆ rf.\nProof using. unfold rfe; basic_solver. Qed.\n\n\nLemma coi_in_sb : coi ⊆ sb.\nProof using. unfold coi; basic_solver. Qed.\n\nLemma coi_in_co : coi ⊆ co.\nProof using. unfold coi; basic_solver. Qed.\n\nLemma coe_in_co : coe ⊆ co.\nProof using. unfold coe; basic_solver. Qed.\n\nLemma ninit_rfi_same_tid : ⦗ set_compl is_init ⦘ ⨾ rfi ⊆ same_tid.\nProof using.\n  arewrite (rfi ⊆ sb).\n  apply ninit_sb_same_tid.\nQed.\n\nLemma coi_trans WF : transitive coi.\nProof using.\n  apply transitiveI.\n  generalize sb_trans (co_trans WF). intros SB CO.\n  unfold coi.\n  unfolder. ins. desf.\n  split; [eapply CO|eapply SB]; eauto.\nQed.\n\nLemma fri_in_sb : fri ⊆ sb.\nProof using. unfold fri; basic_solver. Qed.\n\nLemma fri_in_fr : fri ⊆ fr.\nProof using. unfold fri; basic_solver. Qed.\n\nLemma fre_in_fr : fre ⊆ fr.\nProof using. unfold fre; basic_solver. Qed.\n\nLemma fri_coi WF : fri ⨾ coi ⊆ fri.\nProof using.\n  unfold fri, coi.\n  unfolder. ins. desf.\n  split.\n  { apply fr_co; auto. basic_solver. }\n  eapply sb_trans; eauto.\nQed.\n\nLemma codom_rfi_rfe_empty WF : codom_rel rfi ∩₁ codom_rel rfe ⊆₁ ∅.\nProof using.\n  unfold rfi, rfe.\n  unfolder. ins. desf. \n  assert (x0 = x1); subst; eauto.\n  eapply (wf_rff WF); eauto.\nQed.\n\n(******************************************************************************)\n(** ** properties of external/internal relations *)\n(******************************************************************************)\n\nLemma seq_ii r1 r2 r3 (A: r1 ⨾ r2 ⊆ r3): r1 ∩ sb ⨾ r2 ∩ sb ⊆ r3 ∩ sb.\nProof using.\ngeneralize sb_trans.\nunfolder in *; basic_solver 21.\nQed.\n\nLemma re_ri WF  r r' (IRR: irreflexive r)  (IRR2: irreflexive (r ⨾ sb))\n  (N: r ⊆ r ⨾  ⦗ fun x => ~ is_init x ⦘): (r \\ sb) ⨾ (r' ∩ sb) ⊆ r ⨾  r' \\ sb.\nProof using.\nrewrite N at 1.\nunfolder; ins; desf; splits; eauto.\nintro.\neapply sb_semi_total_r with (x:=y) (y:=x) in H1; eauto.\nby desf; revert IRR2; basic_solver.\neby intro; subst; eapply IRR.\nQed.\n\nLemma ri_re WF  r r' (IRR: irreflexive r')  (IRR2: irreflexive (r' ⨾ sb)): \n ⦗ fun x => ~ is_init x ⦘ ⨾ (r ∩ sb) ⨾ (r' \\ sb) ⊆ r ⨾  r' \\ sb.\nProof using.\nunfolder; ins; desf; splits; eauto.\nintro.\neapply sb_semi_total_l with (x:=x) (y:=z) (z:=y) in H4; eauto.\nby desf; revert IRR2; basic_solver.\neby intro; subst; eapply IRR.\nQed.\n\nLemma rfi_in_sbloc WF : rf ∩ sb ⊆ restr_eq_rel loc sb.\nProof using. rewrite wf_rfl; basic_solver 12. Qed.\nLemma coi_in_sbloc WF : co ∩ sb ⊆ restr_eq_rel loc sb.\nProof using. rewrite wf_col; basic_solver 12. Qed.\nLemma fri_in_sbloc WF : fr ∩ sb ⊆ restr_eq_rel loc sb.\nProof using. rewrite (loceq_same_loc (loceq_fr WF)).\nunfolder; unfold Events.same_loc in *.\nins; desf; splits; eauto; congruence.\nQed.\nLemma rfi_in_sbloc' WF : rfi ⊆ sb ∩ same_loc.\nProof using. generalize (wf_rfl WF); unfold rfi; basic_solver 12. Qed.\nLemma coi_in_sbloc' WF : coi ⊆ sb ∩ same_loc.\nProof using. generalize (wf_col WF); unfold coi; basic_solver 12. Qed.\nLemma fri_in_sbloc' WF : fri ⊆ sb ∩ same_loc.\nProof using. generalize (wf_frl WF); unfold fri; basic_solver 12. Qed.\n\nLemma rf_rmw_sb_minus_sb WF: (rf ⨾ rmw ⨾ sb^? ⨾ ⦗W⦘) \\ sb ⊆ rfe ⨾ rmw ⨾ sb^? ⨾ ⦗W⦘.\nProof using.\nrewrite (seq_minus_transitive sb_trans).\nunionL; [by unfold rfe; basic_solver 12|].\nrewrite (rmw_in_sb WF) at 1.\narewrite (sb ⨾ sb^? ⨾ ⦗W⦘ ⊆ sb) by generalize sb_trans; basic_solver 21.\nrelsf.\nQed.\n\nLemma rf_rmw_sb_rt_rf WF: ((rf ⨾ rmw ⨾ sb^? ⨾ ⦗W⦘)＊ ⨾ rf) \\ sb ⊆ sb^? ⨾ rfe ⨾ (rmw ⨾ sb^? ⨾ ⦗W⦘ ⨾ rf)＊.\nProof using.\nrewrite rtE; relsf.\nrewrite rtE, minus_union_l.\nrelsf; unionL; [by unfold rfe; basic_solver 12|].\nrewrite (seq_minus_transitive sb_trans).\nunionL; [|by unfold rfe; basic_solver 12].\nunionR right.\nrewrite (ct_minus_transitive sb_trans).\narewrite ((rf ⨾ rmw ⨾ sb^? ⨾ ⦗W⦘) ∩ sb ⊆ sb).\ngeneralize sb_trans; ins; relsf.\nrewrite (rf_rmw_sb_minus_sb WF).\nrewrite !seqA.\narewrite (rmw ⨾ sb^? ⨾ ⦗W⦘ ⨾ (rf ⨾ rmw ⨾ sb^? ⨾ ⦗W⦘)＊ ⨾ rf ⊆ (rmw ⨾ sb^? ⨾ ⦗W⦘ ⨾ rf )⁺); [|done].\nrewrite rtE; relsf; unionL; [by econs|].\nrewrite ct_seq_swap, !seqA.\nrewrite ct_begin at 2.\nby rewrite inclusion_t_rt, !seqA.\nQed.\n\nLemma rmw_rf_ct WF : (rmw ⨾ sb^? ⨾ ⦗W⦘ ⨾ rf)⁺ ⊆ (rmw ⨾ sb^? ⨾ ⦗W⦘ ∪ rfe)⁺ ⨾ rf.\nProof using.\n  apply inclusion_t_ind_left.\n  { hahn_frame; vauto. }\n  rewrite ct_begin; hahn_frame; relsf.\n  arewrite (rfe ⊆ rf) at 2.\n  seq_rewrite (rf_rf WF).\n  relsf.\n  rewrite rfi_union_rfe; relsf; unionL.\n  { arewrite (rfi ⊆ sb).\n    rewrite (rmw_in_sb WF) at 2.\n    arewrite (sb^? ⨾ ⦗W⦘ ⨾ sb ⨾ sb ⨾ sb^? ⊆ sb^?).\n    generalize sb_trans; basic_solver 21.\n    basic_solver 21. }\n  rewrite rt_begin at 2.\n  rewrite rt_begin at 2.\n  basic_solver 42.\nQed.\n\nLemma rmw_rf_rt_1 WF : (rmw ⨾ sb^? ⨾ ⦗W⦘ ⨾ rf)＊ ⊆ (rmw ⨾ sb^? ⨾ ⦗W⦘ ∪ rfe)＊ ⨾ rfi^?.\nProof using.\nrewrite rtE; unionL; [basic_solver 12|].\nrewrite (rmw_rf_ct WF).\nrewrite rfi_union_rfe; relsf.\nrewrite inclusion_t_rt.\nrelsf; unionL.\nbasic_solver 12.\nrewrite rt_end at 2; basic_solver 12.\nQed.\n\n(******************************************************************************)\n(** ** detour *)\n(******************************************************************************)\n\nDefinition detour := (coe ⨾ rfe) ∩ sb.\n\nLemma wf_detourE WF: detour ≡ ⦗E⦘ ⨾ detour ⨾ ⦗E⦘.\nProof using.\nsplit; [|basic_solver].\nunfold detour.\nsin_rewrite (wf_coeE WF).\nsin_rewrite (wf_rfeE WF).\nbasic_solver 42.\nQed.\n\nLemma wf_detourD WF: detour ≡ ⦗W⦘ ⨾ detour ⨾ ⦗R⦘.\nProof using.\nsplit; [|basic_solver].\nunfold detour.\nsin_rewrite (wf_coeD WF).\nsin_rewrite (wf_rfeD WF).\nbasic_solver 42.\nQed.\n\nLemma detour_fr_in_co WF: detour ⨾ fr ⊆ co.\nProof using.\nunfold detour, coe, rfe.\ngeneralize (rf_fr WF) (co_trans WF).\nbasic_solver 42.\nQed.\n\nLemma detour_transp_rfi WF: detour ⨾ rfi^{-1} ⊆ ∅₂.\nProof using.\nunfold detour, rfe, rfi.\nunfolder; ins; desf.\nassert (y=z0); subst; auto.\neapply WF; basic_solver.\nQed.\n\nLemma detour_in_sb : detour ⊆ sb.\nProof using. unfold detour; basic_solver. Qed.\n\nLemma detour_to_codom_rfe WF: detour ⊆ detour ⨾ ⦗ codom_rel rfe ⦘.\nProof using.\nunfold detour, rfe, rfi.\nunfolder; ins; desf; eauto 20.\nQed.\n\n(******************************************************************************)\n(** ** exclusive reads/writes *)\n(******************************************************************************)\n\nDefinition W_ex := codom_rel rmw.\n\nLemma W_ex_not_init WF : W_ex ⊆₁ set_compl is_init.\nProof using.\n  unfolder. ins. desf.\n  match goal with\n  | H : W_ex _ |- _ => rename H into WEX\n  end.\n  destruct WEX as [z WEX].\n  apply (rmw_in_sb WF) in WEX.\n  apply no_sb_to_init in WEX. unfolder in WEX. desf.\nQed.\n\nLemma W_ex_in_W WF : W_ex ⊆₁ W.\nProof using.\nunfold W_ex; rewrite (dom_r (wf_rmwD WF)); basic_solver.\nQed.\n\nLemma W_ex_in_E WF : W_ex ⊆₁ E.\nProof using.\n  unfold W_ex. rewrite (dom_r (wf_rmwE WF)). basic_solver.\nQed.\n\nLemma W_ex_eq_EW_W_ex WF : W_ex ≡₁ E ∩₁ W ∩₁ W_ex.\nProof using.\n  generalize (W_ex_in_E WF).\n  generalize (W_ex_in_W WF).\n  clear. basic_solver 10.\nQed.\n\nNotation \"'W_ex_acq'\" := (W_ex ∩₁ (fun a => is_true (is_xacq lab a))).\n\nLemma W_ex_acq_in_W WF : W_ex_acq ⊆₁ W.\nProof using.\n  rewrite (W_ex_in_W WF); basic_solver.\nQed.\n\nLemma rmw_W_ex : rmw ⊆ rmw ⨾ ⦗W_ex⦘.\nProof using.\nunfold W_ex; basic_solver.\nQed.\n\nLemma W_ex_acq_not_init WF : W_ex_acq ⊆₁ set_compl is_init.\nProof using.\n  unfolder. ins. desf.\n  match goal with\n  | H : W_ex _ |- _ => rename H into WEX\n  end.\n  destruct WEX as [z WEX].\n  apply (rmw_in_sb WF) in WEX.\n  apply no_sb_to_init in WEX. unfolder in WEX. desf.\nQed.\n\n(******************************************************************************)\n(** ** rf ⨾ rmw *)\n(******************************************************************************)\n\nLemma wf_rfrmwE WF: rf ⨾ rmw ≡ ⦗ E ⦘ ⨾ (rf ⨾ rmw) ⨾ ⦗ E ⦘.\nProof using.\nsplit; [|basic_solver].\nrewrite (wf_rfE WF) at 1. \nrewrite (wf_rmwE WF) at 1.\nbasic_solver.\nQed.\n\nLemma wf_rfrmwD WF: rf ⨾ rmw ≡ ⦗ W ⦘ ⨾ (rf ⨾ rmw) ⨾ ⦗ W ⦘.\nProof using.\nsplit; [|basic_solver].\nrewrite (wf_rfD WF) at 1. \nrewrite (wf_rmwD WF) at 1.\nbasic_solver.\nQed.\n\nLemma wf_rfrmwl WF: rf ⨾ rmw ⊆ same_loc. \nProof using.\nrewrite (wf_rfl WF), (wf_rmwl WF).\ngeneralize same_loc_trans; basic_solver.\nQed.\n\nLemma wf_rfrmwf WF: functional (rf ⨾ rmw)⁻¹.\nProof using.\nhahn_rewrite transp_seq.\nby apply functional_seq; [apply wf_rmw_invf|apply WF].\nQed.\n\nLemma wf_rfirmwf WF : functional (rfi ⨾ rmw)⁻¹.\nProof using. arewrite (rfi ⊆ rf). eapply wf_rfrmwf; eauto. Qed.\n\nLemma wf_rfermwf WF : functional (rfe ⨾ rmw)⁻¹.\nProof using. arewrite (rfe ⊆ rf). eapply wf_rfrmwf; eauto. Qed.\n\nLemma rt_rf_rmw : (rf ⨾ rmw)＊ ⊆ (rfi ⨾ rmw)＊ ⨾ (rfe ⨾ rmw ⨾ (rfi ⨾ rmw)＊)＊.\nProof using.\n  eapply rt_ind_left with (P:=fun r=> r); eauto with hahn.\n  basic_solver 12.\n  intros k H.\n  rewrite !seqA, H.\n  rewrite rfi_union_rfe; relsf; unionL.\n  { rewrite rt_begin at 3.\n    basic_solver 21. }\n  rewrite (rt_begin (rfe ⨾ rmw ⨾ (rfi ⨾ rmw)＊)) at 2.\n  basic_solver 21.\nQed.\n\nLemma ninit_rfi_rmw_same_tid WF : ⦗ set_compl is_init ⦘ ⨾ rfi ⨾ rmw ⊆ same_tid.\nProof using.\n  rewrite (wf_rmwt WF).\n  sin_rewrite ninit_rfi_same_tid.\n  apply transitiveI. apply same_tid_trans.\nQed.\n\nLemma ninit_rfi_rmw_rt_same_tid WF : ⦗ set_compl is_init ⦘ ⨾ (rfi ⨾ rmw)＊ ⊆ same_tid.\nProof using.\n  apply rt_ind_left with (P:= fun r => ⦗set_compl is_init⦘ ⨾ r).\n  { by eauto with hahn. }\n  { unfold same_tid. basic_solver 12. }\n  intros k AA. rewrite !seqA.\n  rewrite (dom_r (rmw_non_init_lr WF)). rewrite !seqA.\n  rewrite AA.\n  sin_rewrite ninit_rfi_rmw_same_tid; auto.\n  apply transitiveI. apply same_tid_trans.\nQed.\n\nLemma sw_in_ar_helper WF:\n  ((sb ∩ same_loc)^? ⨾ rf ⨾ rmw)＊ ⊆\n  (sb ∩ same_loc ⨾ ⦗W⦘)^? ∪ (sb ∩ same_loc)^? ⨾ (rfe ⨾ rmw ⨾ (sb ∩ same_loc)^? ⨾ ⦗W⦘)⁺.\nProof using.\n  rewrite rtE at 1; relsf; unionL; [basic_solver 21|].\n  rewrite rfi_union_rfe; relsf.\n  rewrite path_union.\n  unionL.\n  { rewrite (dom_r (wf_rmwD WF)) at 1.\n    rewrite (rfi_in_sbloc' WF) at 1.\n    rewrite (rmw_in_sb_loc WF) at 1.\n    generalize sb_same_loc_trans; ins; relsf.\n    assert (transitive (sb ∩ same_loc ⨾ ⦗W⦘)).\n    2: by relsf.\n    generalize sb_same_loc_trans; unfold transitive.\n    basic_solver 21. }\n  rewrite ct_seq_swap, !seqA.\n  rewrite (dom_r (wf_rmwD WF)) at 3.\n  rewrite (rfi_in_sbloc' WF) at 1 2.\n  rewrite (rmw_in_sb_loc WF) at 1 3.\n  generalize sb_same_loc_trans; intros HH; relsf.\n  unionR right.\n  rewrite (dom_l (wf_rfeD WF)), !seqA.\n  rewrite <- seqA with (r2:= ⦗W⦘).\n  rewrite ct_rotl, !seqA.\n  arewrite ((sb ∩ same_loc)^? ⨾ (sb ∩ same_loc)^? ⊆ (sb ∩ same_loc)^?).\n  { generalize HH. basic_solver 10. }\n  hahn_frame.\n  arewrite (((sb ∩ same_loc) ⨾ ⦗W⦘)＊ ⨾ (sb ∩ same_loc)^? ⊆ (sb ∩ same_loc)^?).\n  { arewrite_id ⦗W⦘. rewrite seq_id_r. rewrite rt_of_trans.\n    2: by apply sb_same_loc_trans.\n    generalize sb_same_loc_trans.\n    basic_solver 10. }\n  arewrite (rmw ⨾ (sb ∩ same_loc ⨾ ⦗W⦘)＊ ⊆ rmw ⨾ (sb ∩ same_loc)^? ⨾ ⦗W⦘).\n  2: { rewrite (dom_l (wf_rfeD WF)) at 1 2; rewrite !seqA.\n       arewrite_id ⦗W⦘ at 1. rewrite seq_id_l.\n       apply ct_end. }\n  rewrite rtE, seq_union_r.\n  unionL.\n  { rewrite (dom_r (wf_rmwD WF)) at 1. basic_solver 10. }\n  rewrite ct_of_trans.\n  { basic_solver 10. }\n  generalize sb_trans, same_loc_trans. basic_solver 20.\nQed.\n\nLemma s_sw_in_ar_helper WF:\n  (rf ⨾ rmw)＊ ⊆ (sb ∩ same_loc ⨾ ⦗W⦘)^? ∪ (sb ∩ same_loc)^? ⨾ (rfe ⨾ rmw ⨾ (sb ∩ same_loc)^? ⨾ ⦗W⦘)⁺.\nProof using.\n  arewrite (rf ⨾ rmw ⊆ (sb ∩ same_loc)^? ⨾ rf ⨾ rmw).\n  { basic_solver 10. }\n  apply (sw_in_ar_helper WF).\nQed.\n\nLemma sb_co_trans WF :\n  transitive ((⦗F⦘ ⨾ sb)^? ⨾ co).\nProof using.\n  apply transitiveI. rewrite !seqA.\n  rewrite (dom_r (wf_coD WF)). rewrite !seqA.\n  arewrite_id (⦗W⦘ ⨾ (⦗F⦘ ⨾ sb)^?).\n  { type_solver. }\n  rewrite seq_id_l. by sin_rewrite (co_co WF).\nQed.\n\nLemma rel_sb_co_trans WF :\n  transitive (⦗Rel⦘ ⨾ (⦗F⦘ ⨾ sb)^? ⨾ co).\nProof using.\n  apply transitiveI. rewrite !seqA.\n  rewrite (dom_r (wf_coD WF)). rewrite !seqA.\n  arewrite_id (⦗W⦘ ⨾ ⦗Rel⦘ ⨾ (⦗F⦘ ⨾ sb)^?).\n  { type_solver. }\n  rewrite seq_id_l. by sin_rewrite (co_co WF).\nQed.\n\nLemma sb_co_irr WF :\n  irreflexive ((⦗F⦘ ⨾ sb)^? ⨾ co).\nProof using.\n  rewrite crE. rewrite seq_union_l, !seq_id_l.\n  apply irreflexive_union. split.\n  { by apply co_irr. }\n  rewrite (wf_coD WF).\n  type_solver.\nQed.\n\nLemma rel_sb_co_irr WF :\n  irreflexive (⦗Rel⦘ ⨾ (⦗F⦘ ⨾ sb)^? ⨾ co).\nProof using. arewrite_id ⦗Rel⦘. rewrite seq_id_l. by apply sb_co_irr. Qed.\n\nNotation \"'Loc_' l\" := (fun x => loc x = l) (at level 1).\n\nLemma co_E_W_Loc WF l x y (CO : co x y): (E ∩₁ W ∩₁ Loc_ l) x <-> (E ∩₁ W ∩₁ Loc_ l) y.\nProof using.\n  apply (wf_coE WF) in CO.\n  apply seq_eqv_l in CO. destruct CO as [EX CO].\n  apply seq_eqv_r in CO. destruct CO as [CO EY].\n  apply (wf_coD WF) in CO.\n  apply seq_eqv_l in CO. destruct CO as [WX CO].\n  apply seq_eqv_r in CO. destruct CO as [CO WY].\n  apply (wf_col WF) in CO.\n  split; intros [_ LL].\n  all: by split; [split|rewrite <- LL].\nQed.\n\nLemma rfi_rmw_in_sb_same_loc_W WF : rfi ⨾ rmw ⊆ (sb ∩ same_loc) ⨾ ⦗W⦘.\nProof using.\n  rewrite (dom_r (wf_rmwD WF)).\n  rewrite rfi_in_sbloc', rmw_in_sb_loc; auto.\n  sin_rewrite rewrite_trans; [done|].\n  apply sb_same_loc_trans.\nQed.\n\nLemma rfi_rmw_in_sb_loc WF : rfi ⨾ rmw ⊆ sb ∩ same_loc.\nProof using.\n  rewrite (rfi_rmw_in_sb_same_loc_W WF). basic_solver.\nQed.\n\n(******************************************************************************)\n(** ** co *)\n(******************************************************************************)\nLemma wf_immcof WF : functional (immediate co).\nProof using.\n  intros x y z ICOXY ICOXZ.\n  assert (co x y) as COXY by apply ICOXY.\n  assert (co x z) as COXZ by apply ICOXZ.\n  apply (wf_coD WF) in COXY. destruct_seq COXY as [BB1 BB2].\n  apply (wf_coE WF) in COXY. destruct_seq COXY as [BB3 BB4].\n  apply (wf_coD WF) in COXZ. destruct_seq COXZ as [AA1 AA2].\n  apply (wf_coE WF) in COXZ. destruct_seq COXZ as [AA3 AA4].\n  apply is_w_loc in AA1. desf.\n  set (CC:=COXY). apply (wf_col WF) in CC. red in CC.\n  set (DD:=COXZ). apply (wf_col WF) in DD. red in DD.\n  destruct (classic (y = z)); auto.\n  edestruct (wf_co_total WF); eauto.\n  1,2: split; [split|]; eauto.\n  { by etransitivity; [|by eauto]. }\n  { exfalso. by apply ICOXZ with (c:=y). }\n  exfalso. by apply ICOXY with (c:=z).\nQed.\n\nLemma wf_immcotf WF : functional (immediate co)⁻¹.\nProof using.\n  intros x y z ICOXY ICOXZ. red in ICOXY. red in ICOXZ.\n  assert (co y x) as COXY by apply ICOXY.\n  assert (co z x) as COXZ by apply ICOXZ.\n  apply (wf_coD WF) in COXY. destruct_seq COXY as [BB1 BB2].\n  apply (wf_coE WF) in COXY. destruct_seq COXY as [BB3 BB4].\n  apply (wf_coD WF) in COXZ. destruct_seq COXZ as [AA1 AA2].\n  apply (wf_coE WF) in COXZ. destruct_seq COXZ as [AA3 AA4].\n  apply is_w_loc in AA2. desf.\n  set (CC:=COXY). apply (wf_col WF) in CC. red in CC.\n  set (DD:=COXZ). apply (wf_col WF) in DD. red in DD.\n  destruct (classic (y = z)); auto.\n  edestruct (wf_co_total WF); eauto.\n  1,2: split; [split|]; eauto.\n  { exfalso. by apply ICOXY with (c:=z). }\n  exfalso. by apply ICOXZ with (c:=y).\nQed.\n\nLemma wf_immcoPtf WF P : functional (immediate (⦗P⦘ ⨾ co))⁻¹.\nProof using.\n  intros x y z ICOXY ICOXZ. red in ICOXY. red in ICOXZ.\n  assert (co y x /\\ P y) as [COXY PY].\n  { destruct ICOXY as [AA BB]. generalize AA. basic_solver. }\n  assert (co z x /\\ P z) as [COXZ PZ].\n  { destruct ICOXZ as [AA BB]. generalize AA. basic_solver. }\n  apply (wf_coD WF) in COXY. destruct_seq COXY as [BB1 BB2].\n  apply (wf_coE WF) in COXY. destruct_seq COXY as [BB3 BB4].\n  apply (wf_coD WF) in COXZ. destruct_seq COXZ as [AA1 AA2].\n  apply (wf_coE WF) in COXZ. destruct_seq COXZ as [AA3 AA4].\n  apply is_w_loc in AA2. desf.\n  set (CC:=COXY). apply (wf_col WF) in CC. red in CC.\n  set (DD:=COXZ). apply (wf_col WF) in DD. red in DD.\n  destruct (classic (y = z)); auto.\n  edestruct (wf_co_total WF); eauto.\n  1,2: split; [split|]; eauto.\n  { exfalso. apply ICOXY with (c:=z).\n    all: apply seq_eqv_l; split; auto. }\n  exfalso. apply ICOXZ with (c:=y).\n  all: apply seq_eqv_l; split; auto.\nQed.\n\nLemma P_co_nP_co_P_imm WF P\n      (P_in_E : P ⊆₁ E)\n      (P_in_W : P ⊆₁ W) :\n  immediate (⦗P⦘ ⨾ co) ⨾ ⦗set_compl P⦘ ⨾ immediate (co ⨾ ⦗P⦘) ⊆\n            immediate (⦗P⦘ ⨾ co ⨾ ⦗P⦘).\nProof using.\n  intros x y [z [AA BB]].\n  destruct_seq_l BB as CC.\n  set (DD := AA). destruct DD as [DD _]. destruct_seq_l DD as PX.\n  set (EE := BB). destruct EE as [EE _]. destruct_seq_r EE as PY.\n  assert (co x y) as CO.\n  { eapply (co_trans WF); eauto. }\n  apply (wf_coD WF) in CO. destruct_seq CO as [WX WY].\n  apply (wf_coE WF) in CO. destruct_seq CO as [EX EY].\n  apply (wf_coD WF) in DD. destruct_seq DD as [XLOC WZ].\n  apply (wf_coE WF) in DD. destruct_seq DD as [EX' EZ].\n  apply is_w_loc in XLOC. desf.\n  assert (loc y = Some l /\\ loc z = Some l) as [YLOC ZLOC].\n  { split; rewrite <- XLOC; symmetry; by apply (wf_col WF). }\n\n  split.\n  { apply seq_eqv_lr. by splits. }\n  ins.\n  destruct_seq R1 as [A1 B1].\n  destruct_seq R2 as [A2 B2].\n  destruct (classic (c = z)) as [|CNEQ]; desf.\n  assert (loc c = Some l) as LOCC.\n  { rewrite <- YLOC. by apply (wf_col WF). }\n  assert (E c) as EC.\n  { by apply P_in_E. }\n  assert (W c) as WC.\n  { by apply P_in_W. }\n  \n  assert (c <> x /\\ c <> y) as [CNNEXT CNPREV].\n  { split; intros HH; subst; eapply (co_irr WF); eauto. }\n\n  assert (co c z \\/ co z c) as [QQ|QQ].\n  { eapply (wf_co_total WF); eauto; unfolder; eauto. }\n  { eapply AA with (c:=c); apply seq_eqv_l; eauto. }\n  eapply BB with (c:=c); apply seq_eqv_r; eauto.\nQed.\n\nLemma P_co_immediate_P_co_transp_in_co_cr WF P\n      (P_in_E : P ⊆₁ E)\n      (P_in_W : P ⊆₁ W) :\n  (⦗P⦘ ⨾ co) ⨾ (immediate (⦗P⦘⨾ co))⁻¹ ⊆ co^?.\nProof using.\n  intros x y [z [AA [BB CC]]].\n  destruct_seq_l AA as PZ.\n  destruct_seq_l BB as DD.\n  destruct (classic (x = y)) as [|NEQ]; subst; [by left|right].\n  apply (wf_coD WF) in AA. destruct_seq AA as [WX WZ].\n  apply (wf_coE WF) in AA. destruct_seq AA as [EX EZ].\n  apply (wf_coD WF) in BB. destruct_seq BB as [WY ZLOC].\n  apply (wf_coE WF) in BB. destruct_seq BB as [EY FF].\n  apply is_w_loc in ZLOC. desf.\n  assert (loc x = Some l /\\ loc y = Some l) as [XLOC YLOC].\n  { rewrite <- !ZLOC. split; by apply (wf_col WF). }\n  edestruct (wf_co_total WF); eauto.\n  1,2: by split; [split|]; eauto.\n  exfalso.\n  apply CC with (c:=x).\n  all: apply seq_eqv_l; split; auto.\nQed.\n\nLemma co_immediate_co_in_co_cr WF : co ⨾ (immediate co)⁻¹ ⊆ co^?.\nProof using.\n  assert (co ≡ ⦗E∩₁W⦘ ⨾ co) as AA.\n  { split; [|basic_solver].\n    rewrite (wf_coE WF) at 1. rewrite (wf_coD WF) at 1.\n    basic_solver. }\n  rewrite AA at 1 2.\n  apply P_co_immediate_P_co_transp_in_co_cr.\n  all: basic_solver.\nQed.\n\nLemma immediate_co_P_transp_co_P_in_co_cr WF P\n      (P_in_E : P ⊆₁ E)\n      (P_in_W : P ⊆₁ W) :\n  (immediate (co ⨾ ⦗P⦘))⁻¹ ⨾ (co ⨾ ⦗P⦘) ⊆ co^?.\nProof using.\n  intros x y [z [[BB CC] AA]].\n  destruct_seq_r AA as PZ.\n  destruct_seq_r BB as DD.\n  destruct (classic (x = y)) as [|NEQ]; subst; [by left|right].\n  apply (wf_coD WF) in AA. destruct_seq AA as [WZ WY].\n  apply (wf_coE WF) in AA. destruct_seq AA as [EZ EY].\n  apply (wf_coD WF) in BB. destruct_seq BB as [ZLOC WX].\n  apply (wf_coE WF) in BB. destruct_seq BB as [FF EX].\n  apply is_w_loc in ZLOC. desf.\n  assert (loc x = Some l /\\ loc y = Some l) as [XLOC YLOC].\n  { rewrite <- !ZLOC. split; symmetry; by apply (wf_col WF). }\n  edestruct (wf_co_total WF); eauto.\n  1,2: by split; [split|]; eauto.\n  exfalso.\n  apply CC with (c:=y).\n  all: apply seq_eqv_r; split; auto.\nQed.\n\n\n\nEnd Execution.\n\n(******************************************************************************)\n(** ** Tactics *)\n(******************************************************************************)\n\n#[global]\nHint Unfold rfe coe fre rfi coi fri : ie_unfolderDb.\nTactic Notation \"ie_unfolder\" :=  repeat autounfold with ie_unfolderDb in *.\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/Execution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.2862243443260291}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.progs.load_demo.\n\n#[export] Instance 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 [ tptr pair_pair_t, tint ]\n    PROP  (readable_share sh; 0 <= i < array_size)\n    PARAMS (pps; 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 () RETURN (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 [ tptr tuint ]\n          PROP  (Int.unsigned (Int.shru (Int.repr tag) (Int.repr 10)) = n)\n          PARAMS (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          RETURN (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))\n   (Int.shl (Int.repr (Znth 1 arr)) (Int.repr  8)))\n   (Int.shl (Int.repr (Znth 2 arr)) (Int.repr 16)))\n   (Int.shl (Int.repr (Znth 3 arr)) (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 [ tptr tuchar ]\n    PROP (Zlength arr = 4;\n          readable_share in_sh;\n          forall i, 0 <= i < 4 -> 0 <= Znth i arr <= Byte.max_unsigned)\n    PARAMS (input)\n    SEP (data_at in_sh (tarray tuchar 4) (map Vint (map Int.repr arr)) input)\n  POST [ tuint ]\n    PROP() RETURN (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 _] => \n   specialize (H i); spec H; [ computable | ];\n   rewrite Int.unsigned_repr; rep_lia\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. simpl map.\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, !Zlength_map in H0.\n  destruct (zlt n 0); [exfalso | ].\n  rewrite Z.max_l in H0 by lia.\n  pose proof (Zlength_nonneg contents).\n  lia.\n  rewrite Z.max_r in H0 by lia. lia.  \n}\nassert (Zlength (tag :: contents) = 1 + n) as LEN1. {\n  rewrite Zlength_cons. lia.\n}\nassert (N0: 0 <= n). {\n  pose proof (Zlength_nonneg contents). lia.\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.\n(* rewrite !Znth_0_cons. *)\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- (* precondition implies invariant: *)\n  entailer!!.\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. unfold sizeof; simpl. lia.\n  }\n  forward.\n  forward.\n  entailer!.\n  rewrite Znth_pos_cons by lia.\n  autorewrite with sublist. simpl.  \n  f_equal. rewrite Int.add_assoc. f_equal.\n  rewrite (sublist_split 0 i (i+1)) by lia.\n  rewrite sublist_len_1 by lia.\n  replace (1 + i - 1) with i by lia.\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. unfold sizeof; simpl. lia.\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": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs/verif_load_demo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.28622434432602906}}
{"text": "From iris.algebra Require Import numbers.\nFrom iris.proofmode Require Import proofmode.\nFrom lrust.typing Require Export type.\nFrom lrust.typing Require Import type_context lft_contexts product own uniq_bor.\nFrom lrust.typing Require Import shr_bor.\nFrom iris.prelude Require Import options.\n\nSection product_split.\n  Context `{!typeGS Σ}.\n\n  (** General splitting / merging for pointer types *)\n  Fixpoint hasty_ptr_offsets (p : path) (ptr: type → type) tyl (off : nat) : tctx :=\n    match tyl with\n    | [] => []\n    | ty :: tyl =>\n      (p +ₗ #off ◁ ptr ty) :: hasty_ptr_offsets p ptr tyl (off + ty.(ty_size))\n    end.\n\n  Lemma hasty_ptr_offsets_offset (l : loc) p (off1 off2 : nat) ptr tyl tid :\n    eval_path p = Some #l →\n    tctx_interp tid $ hasty_ptr_offsets (p +ₗ #off1) ptr tyl off2 ≡\n    tctx_interp tid $ hasty_ptr_offsets p ptr tyl (off1 + off2)%nat.\n  Proof.\n    intros Hp.\n    revert off1 off2; induction tyl as [|ty tyl IH]; intros off1 off2; simpl; first done.\n    rewrite !tctx_interp_cons. f_equiv; last first.\n    { by rewrite IH assoc_L. }\n    apply tctx_elt_interp_hasty_path. clear Hp. simpl.\n    clear. destruct (eval_path p) as [v|]; last done. destruct v as [l|]; try done.\n    destruct l; try done. rewrite shift_loc_assoc Nat2Z.inj_add //.\n  Qed.\n\n  Lemma tctx_split_ptr_prod E L ptr tyl :\n    (∀ p ty1 ty2,\n        tctx_incl E L [p ◁ ptr $ product2 ty1 ty2]\n                      [p ◁ ptr ty1; p +ₗ #ty1.(ty_size) ◁ ptr ty2]) →\n    (∀ tid ty vl, (ptr ty).(ty_own) tid vl -∗ ⌜∃ l : loc, vl = [(#l) : val]⌝) →\n    ∀ p, tctx_incl E L [p ◁ ptr $ product tyl] (hasty_ptr_offsets p ptr tyl 0).\n  Proof.\n    iIntros (Hsplit Hloc p tid qmax qL) \"#LFT #HE HL H\".\n    iInduction tyl as [|ty tyl IH] \"IH\" forall (p).\n    { rewrite tctx_interp_nil. auto. }\n    rewrite product_cons. iMod (Hsplit with \"LFT HE HL H\") as \"(HL & H)\".\n    cbn -[tctx_elt_interp].\n    iDestruct \"H\" as \"[Hty Htyl]\". iDestruct \"Hty\" as (v) \"[Hp Hty]\". iDestruct \"Hp\" as %Hp.\n    iDestruct (Hloc with \"Hty\") as %[l [=->]].\n    iAssert (tctx_elt_interp tid (p +ₗ #0 ◁ ptr ty)) with \"[Hty]\" as \"$\".\n    { iExists #l. iSplit; last done. simpl; by rewrite Hp shift_loc_0. }\n    iMod (\"IH\" with \"HL [Htyl]\") as \"($ & Htyl)\".\n    { auto. }\n    iClear \"IH\". rewrite (hasty_ptr_offsets_offset l) // -plus_n_O //.\n  Qed.\n\n  Lemma tctx_merge_ptr_prod E L ptr tyl :\n    (Proper (eqtype E L ==> eqtype E L ) ptr) → tyl ≠ [] →\n    (∀ p ty1 ty2,\n        tctx_incl E L [p ◁ ptr ty1; p +ₗ #ty1.(ty_size) ◁ ptr ty2]\n                      [p ◁ ptr $ product2 ty1 ty2]) →\n    (∀ tid ty vl, (ptr ty).(ty_own) tid vl -∗ ⌜∃ l : loc, vl = [(#l) : val]⌝) →\n    ∀ p, tctx_incl E L (hasty_ptr_offsets p ptr tyl 0) [p ◁ ptr $ product tyl].\n  Proof.\n    iIntros (Hptr Htyl Hmerge Hloc p tid qmax qL) \"#LFT #HE HL H\".\n    iInduction tyl as [|ty tyl IH] \"IH\" forall (p Htyl); first done.\n    rewrite product_cons. rewrite /= tctx_interp_singleton tctx_interp_cons.\n    iDestruct \"H\" as \"[Hty Htyl]\". iDestruct \"Hty\" as (v) \"[Hp Hty]\".\n    iDestruct \"Hp\" as %Hp. iDestruct (Hloc with \"Hty\") as %[l [=->]].\n    assert (eval_path p = Some #l) as Hp'.\n    { move:Hp. simpl. clear. destruct (eval_path p) as [v|]; last done.\n      destruct v as [l'|]; try done. destruct l'; try done. rewrite shift_loc_0. done. }\n    clear Hp. destruct tyl.\n    { assert (eqtype E L (ptr ty) (ptr (product2 ty unit))) as [Hincl _].\n      { rewrite right_id. done. }\n      iDestruct (Hincl with \"HL HE\") as \"#(_ & #Heq & _)\".\n      iFrame. iClear \"IH Htyl\". iExists #l. rewrite product_nil. iSplitR; first done.\n      by iApply \"Heq\". }\n    iMod (\"IH\" with \"[] HL [Htyl]\") as \"(HL & Htyl)\"; first done.\n    { change (ty_size ty) with (0+ty_size ty)%nat at 1.\n      rewrite plus_comm -hasty_ptr_offsets_offset //. }\n    iClear \"IH\". iMod (Hmerge with \"LFT HE HL [Hty Htyl]\") as \"($ & ?)\";\n                   last by rewrite tctx_interp_singleton.\n    rewrite tctx_interp_singleton tctx_interp_cons tctx_interp_singleton. iFrame.\n    iExists #l. iSplit; done.\n  Qed.\n\n  (** Owned pointers *)\n  Lemma tctx_split_own_prod2 E L p n ty1 ty2 :\n    tctx_incl E L [p ◁ own_ptr n $ product2 ty1 ty2]\n                  [p ◁ own_ptr n ty1; p +ₗ #ty1.(ty_size) ◁ own_ptr n ty2].\n  Proof.\n    iIntros (tid qmax qL) \"#LFT _ $ H\".\n    rewrite tctx_interp_singleton tctx_interp_cons tctx_interp_singleton.\n    iDestruct \"H\" as ([[]|]) \"[#Hp H]\"; try done.\n    iDestruct \"H\" as \"[H >H†]\". iDestruct \"H\" as (vl) \"[>H↦ H]\".\n    iDestruct \"H\" as (vl1 vl2) \"(>% & H1 & H2)\". subst.\n    rewrite heap_mapsto_vec_app -freeable_sz_split.\n    iDestruct \"H†\" as \"[H†1 H†2]\". iDestruct \"H↦\" as \"[H↦1 H↦2]\".\n    iDestruct (ty_size_eq with \"H1\") as \"#>EQ\".\n    iDestruct \"EQ\" as %->. iSplitL \"H↦1 H†1 H1\".\n    + iExists _. iFrame \"#∗\". iExists _. by iFrame.\n    + iExists _. iSplitR; first (by simpl; iDestruct \"Hp\" as %->).\n      iFrame. iExists _. by iFrame.\n  Qed.\n\n  Lemma tctx_merge_own_prod2 E L p n ty1 ty2 :\n    tctx_incl E L [p ◁ own_ptr n ty1; p +ₗ #ty1.(ty_size) ◁ own_ptr n ty2]\n                  [p ◁ own_ptr n $ product2 ty1 ty2].\n  Proof.\n    iIntros (tid qmax qL) \"#LFT _ $ H\".\n    rewrite tctx_interp_singleton tctx_interp_cons tctx_interp_singleton.\n    iDestruct \"H\" as \"[H1 H2]\". iDestruct \"H1\" as ([[|l|]|]) \"(Hp1 & H1)\"; try done.\n    iDestruct \"H1\" as \"(H↦1 & H†1)\".\n    iDestruct \"H2\" as (v2) \"(Hp2 & H2)\". simpl. iDestruct \"Hp1\" as %Hρ1.\n    rewrite Hρ1. iDestruct \"Hp2\" as %[=<-]. iDestruct \"H2\" as \"[H↦2 H†2]\".\n    iExists #l. iSplitR; first done. rewrite /= -freeable_sz_split. iFrame.\n    iDestruct \"H↦1\" as (vl1) \"[H↦1 H1]\". iDestruct \"H↦2\" as (vl2) \"[H↦2 H2]\".\n    iExists (vl1 ++ vl2). rewrite heap_mapsto_vec_app. iFrame.\n    iDestruct (ty_size_eq with \"H1\") as \"#>EQ\". iDestruct \"EQ\" as %->.\n    rewrite {3}/ty_own /=. auto 10 with iFrame.\n  Qed.\n\n  Lemma tctx_split_own_prod E L n tyl p :\n    tctx_incl E L [p ◁ own_ptr n $ product tyl] (hasty_ptr_offsets p (own_ptr n) tyl 0).\n  Proof.\n    apply tctx_split_ptr_prod.\n    - intros. apply tctx_split_own_prod2.\n    - iIntros (??[|[[]|][]]) \"?\"; eauto.\n  Qed.\n\n  Lemma tctx_merge_own_prod E L n tyl :\n    tyl ≠ [] →\n    ∀ p, tctx_incl E L (hasty_ptr_offsets p (own_ptr n) tyl 0)\n                   [p ◁ own_ptr n $ product tyl].\n  Proof.\n    intros. apply tctx_merge_ptr_prod; try done.\n    - apply _.\n    - intros. apply tctx_merge_own_prod2.\n    - iIntros (??[|[[]|][]]) \"?\"; eauto.\n  Qed.\n\n  (** Unique borrows *)\n  Lemma tctx_split_uniq_prod2 E L p κ ty1 ty2 :\n    tctx_incl E L [p ◁ &uniq{κ}(product2 ty1 ty2)]\n                  [p ◁ &uniq{κ} ty1; p +ₗ #ty1.(ty_size) ◁ &uniq{κ} ty2].\n  Proof.\n    iIntros (tid qmax qL) \"#LFT _ $ H\".\n    rewrite tctx_interp_singleton tctx_interp_cons tctx_interp_singleton.\n    iDestruct \"H\" as ([[]|]) \"[Hp H]\"; try done. iDestruct \"Hp\" as %Hp.\n    rewrite /= split_prod_mt. iMod (bor_sep with \"LFT H\") as \"[H1 H2]\"; first solve_ndisj.\n    rewrite /tctx_elt_interp /=.\n    iSplitL \"H1\"; iExists _; (iSplitR; first by rewrite Hp); auto.\n  Qed.\n\n  Lemma tctx_merge_uniq_prod2 E L p κ ty1 ty2 :\n    tctx_incl E L [p ◁ &uniq{κ} ty1; p +ₗ #ty1.(ty_size) ◁ &uniq{κ} ty2]\n                  [p ◁ &uniq{κ}(product2 ty1 ty2)].\n  Proof.\n    iIntros (tid qmax qL) \"#LFT _ $ H\".\n    rewrite tctx_interp_singleton tctx_interp_cons tctx_interp_singleton.\n    iDestruct \"H\" as \"[H1 H2]\". iDestruct \"H1\" as ([[|l|]|]) \"[Hp1 H1]\"; try done.\n    iDestruct \"Hp1\" as %Hp1. iDestruct \"H2\" as (v2) \"(Hp2 & H2)\". rewrite /= Hp1.\n    iDestruct \"Hp2\" as %[=<-]. iExists #l. iFrame \"%\".\n    iMod (bor_combine with \"LFT H1 H2\") as \"H\"; first solve_ndisj. by rewrite /= split_prod_mt.\n  Qed.\n\n  Lemma uniq_is_ptr κ ty tid (vl : list val) :\n    ty_own (&uniq{κ}ty) tid vl -∗ ⌜∃ l : loc, vl = [(#l) : val]⌝.\n  Proof. iIntros \"H\". destruct vl as [|[[]|][]]; eauto. Qed.\n\n  Lemma tctx_split_uniq_prod E L κ tyl p :\n    tctx_incl E L [p ◁ &uniq{κ}(product tyl)]\n                  (hasty_ptr_offsets p (uniq_bor κ) tyl 0).\n  Proof.\n    apply tctx_split_ptr_prod.\n    - intros. apply tctx_split_uniq_prod2.\n    - intros. apply uniq_is_ptr.\n  Qed.\n\n  Lemma tctx_merge_uniq_prod E L κ tyl :\n    tyl ≠ [] →\n    ∀ p, tctx_incl E L (hasty_ptr_offsets p (uniq_bor κ) tyl 0)\n                   [p ◁ &uniq{κ}(product tyl)].\n  Proof.\n    intros. apply tctx_merge_ptr_prod; try done.\n    - apply _.\n    - intros. apply tctx_merge_uniq_prod2.\n    - intros. apply uniq_is_ptr.\n  Qed.\n\n  (** Shared borrows *)\n  Lemma tctx_split_shr_prod2 E L p κ ty1 ty2 :\n    tctx_incl E L [p ◁ &shr{κ}(product2 ty1 ty2)]\n                  [p ◁ &shr{κ} ty1; p +ₗ #ty1.(ty_size) ◁ &shr{κ} ty2].\n  Proof.\n    iIntros (tid qmax qL) \"#LFT _ $ H\".\n    rewrite tctx_interp_singleton tctx_interp_cons tctx_interp_singleton.\n    iDestruct \"H\" as ([[]|]) \"[Hp H]\"; try iDestruct \"H\" as \"[]\".\n    iDestruct \"H\" as \"[H1 H2]\". iDestruct \"Hp\" as %Hp.\n    by iSplitL \"H1\"; iExists _; (iSplitR; first by rewrite /= Hp).\n  Qed.\n\n  Lemma tctx_merge_shr_prod2 E L p κ ty1 ty2 :\n    tctx_incl E L [p ◁ &shr{κ} ty1; p +ₗ #ty1.(ty_size) ◁ &shr{κ} ty2]\n                  [p ◁ &shr{κ}(product2 ty1 ty2)].\n  Proof.\n    iIntros (tid qmax qL) \"#LFT _ $ H\".\n    rewrite tctx_interp_singleton tctx_interp_cons tctx_interp_singleton.\n    iDestruct \"H\" as \"[H1 H2]\". iDestruct \"H1\" as ([[|l|]|]) \"[Hp1 Hown1]\"; try done.\n    iDestruct \"Hp1\" as %Hp1. iDestruct \"H2\" as ([[]|]) \"[Hp2 Hown2]\"; try done.\n    rewrite /= Hp1. iDestruct \"Hp2\" as %[=<-]. iExists #l. by iFrame.\n  Qed.\n\n  Lemma shr_is_ptr κ ty tid (vl : list val) :\n    ty_own (&shr{κ} ty) tid vl -∗ ⌜∃ l : loc, vl = [(#l) : val]⌝.\n  Proof. iIntros \"H\". destruct vl as [|[[]|][]]; eauto. Qed.\n\n  Lemma tctx_split_shr_prod E L κ tyl p :\n    tctx_incl E L [p ◁ &shr{κ}(product tyl)]\n                  (hasty_ptr_offsets p (shr_bor κ) tyl 0).\n  Proof.\n    apply tctx_split_ptr_prod.\n    - intros. apply tctx_split_shr_prod2.\n    - intros. apply shr_is_ptr.\n  Qed.\n\n  Lemma tctx_merge_shr_prod E L κ tyl :\n    tyl ≠ [] →\n    ∀ p, tctx_incl E L (hasty_ptr_offsets p (shr_bor κ) tyl 0)\n                   [p ◁ &shr{κ}(product tyl)].\n  Proof.\n    intros. apply tctx_merge_ptr_prod; try done.\n    - apply _.\n    - intros. apply tctx_merge_shr_prod2.\n    - intros. apply shr_is_ptr.\n  Qed.\n\n  (* Splitting with [tctx_extract]. *)\n\n  (* We do not state the extraction lemmas directly, because we want the\n     automation system to be able to perform e.g., borrowing or splitting after\n     splitting. *)\n  Lemma tctx_extract_split_own_prod E L p p' n ty tyl T T' :\n    tctx_extract_hasty E L p' ty (hasty_ptr_offsets p (own_ptr n) tyl 0) T' →\n    tctx_extract_hasty E L p' ty ((p ◁ own_ptr n $ Π tyl) :: T) (T' ++ T).\n  Proof.\n    intros. apply (tctx_incl_frame_r T [_] (_::_)). by rewrite tctx_split_own_prod.\n  Qed.\n\n  Lemma tctx_extract_split_uniq_prod E L p p' κ ty tyl T T' :\n    tctx_extract_hasty E L p' ty (hasty_ptr_offsets p (uniq_bor κ) tyl 0) T' →\n    tctx_extract_hasty E L p' ty ((p ◁ &uniq{κ}(Π tyl)) :: T) (T' ++ T).\n  Proof.\n    intros. apply (tctx_incl_frame_r T [_] (_::_)). by rewrite tctx_split_uniq_prod.\n  Qed.\n\n  Lemma tctx_extract_split_shr_prod E L p p' κ ty tyl T T' :\n    tctx_extract_hasty E L p' ty (hasty_ptr_offsets p (shr_bor κ) tyl 0) T' →\n    tctx_extract_hasty E L p' ty ((p ◁ &shr{κ}(Π tyl)) :: T) ((p ◁ &shr{κ}(Π tyl)) :: T).\n  Proof.\n    intros. apply (tctx_incl_frame_r _ [_] [_;_]).\n    rewrite {1}copy_tctx_incl. apply (tctx_incl_frame_r _ [_] [_]).\n    rewrite tctx_split_shr_prod -(contains_tctx_incl _ _ [p' ◁ ty]) //.\n    apply submseteq_skip, submseteq_nil_l.\n  Qed.\n\n  (* Merging with [tctx_extract]. *)\n\n  Fixpoint extract_tyl E L p (ptr: type → type) tyl (off : nat) T T' : Prop :=\n    match tyl with\n    | [] => T = T'\n    | ty :: tyl => ∃ T'',\n        tctx_extract_hasty E L (p +ₗ #off) (ptr ty) T T'' ∧\n        extract_tyl E L p ptr tyl (off + ty.(ty_size)) T'' T'\n    end.\n\n  Lemma tctx_extract_merge_ptr_prod E L p ptr tyl T T' :\n    tctx_incl E L (hasty_ptr_offsets p ptr tyl 0) [p ◁ ptr $ product tyl] →\n    extract_tyl E L p ptr tyl 0 T T' →\n    tctx_extract_hasty E L p (ptr (Π tyl)) T T'.\n  Proof.\n    rewrite /extract_tyl /tctx_extract_hasty=>Hi Htyl.\n    etrans; last by eapply (tctx_incl_frame_r T' _ [_]). revert T Htyl. clear.\n    generalize 0%nat. induction tyl=>[T n /= -> //|T n /= [T'' [-> Htyl]]]. f_equiv. auto.\n  Qed.\n\n  Lemma tctx_extract_merge_own_prod E L p n tyl T T' :\n    tyl ≠ [] →\n    extract_tyl E L p (own_ptr n) tyl 0 T T' →\n    tctx_extract_hasty E L p (own_ptr n (Π tyl)) T T'.\n  Proof. auto using tctx_extract_merge_ptr_prod, tctx_merge_own_prod. Qed.\n\n  Lemma tctx_extract_merge_uniq_prod E L p κ tyl T T' :\n    tyl ≠ [] →\n    extract_tyl E L p (uniq_bor κ) tyl 0 T T' →\n    tctx_extract_hasty E L p (&uniq{κ}(Π tyl)) T T'.\n  Proof. auto using tctx_extract_merge_ptr_prod, tctx_merge_uniq_prod. Qed.\n\n  Lemma tctx_extract_merge_shr_prod E L p κ tyl T T' :\n    tyl ≠ [] →\n    extract_tyl E L p (shr_bor κ) tyl 0 T T' →\n    tctx_extract_hasty E L p (&shr{κ}(Π tyl)) T T'.\n  Proof. auto using tctx_extract_merge_ptr_prod, tctx_merge_shr_prod. Qed.\nEnd product_split.\n\n(* We do not want unification to try to unify the definition of these\n   types with anything in order to try splitting or merging. *)\nGlobal Hint Opaque own_ptr uniq_bor shr_bor tctx_extract_hasty : lrust_typing lrust_typing_merge.\n\n(* We make sure that splitting is tried before borrowing, so that not\n   the entire product is borrowed when only a part is needed. *)\nGlobal Hint Resolve tctx_extract_split_own_prod tctx_extract_split_uniq_prod tctx_extract_split_shr_prod\n    | 5 : lrust_typing.\n\n(* Merging is also tried after everything, except\n   [tctx_extract_hasty_further]. Moreover, it is placed in a\n   difference hint db. The reason is that it can make the proof search\n   diverge if the type is an evar.\n\n   Unfortunately, priorities are not taken into account accross hint\n   databases with [typeclasses eauto], so this is useless, and some\n   solve_typing get slow because of that. See:\n     https://coq.inria.fr/bugs/show_bug.cgi?id=5304\n*)\nGlobal Hint Resolve tctx_extract_merge_own_prod tctx_extract_merge_uniq_prod tctx_extract_merge_shr_prod\n    | 40 : lrust_typing_merge.\nGlobal Hint Unfold extract_tyl : 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/product_split.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.28622434432602906}}
{"text": "(* ------------------------------------------------------- *)\n(** #<hr> <center> <h1>#\n        The double time redundancy (DTR) transformation   \n#</h1>#    \n-  ctr block properties during odd(0) 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 odd(0) cycles  *)\n(* ########################################################## *)\n\n(*Property: from the state '000' the control block goes to the states '001'*)\n(*No glitches*)\n(*by reflection*)\nLemma step0_tcbv_R : forall p t c, ((fun p => pure_bset p) p) -> \n                            step ((fun p =>(ctrBlockTMR false false false)) p)                        \n                                ((fun p => \n                                     let f3_I :=   (fstS(fstS p)) in\n                                     let f2_I :=   (sndS(fstS p)) in\n                                     let f1_I :=   (sndS p) in\n\n                                     {f1_I, f2_I, f3_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                     t={~0,~0,~0,~0,~0} /\\ (c= (ctrBlockTMR false false true))) (p,t,c).\nProof. introv. Reflect_step_g. Qed.\n\n(** The aforementioned property in a more useable form  *)\nLemma step0_tcbv : forall (f1 f2 f3:bool) f1_I f2_I f3_I t c ,\nf1_I = bool2bset f1 -> f2_I= bool2bset f2 ->  f3_I= bool2bset f3\n                    -> step (ctrBlockTMR false false false) {f1_I, f2_I, f3_I} t c\n                    -> t={~0,~0,~0,~0,~0} /\\ c = (ctrBlockTMR false false true).\nProof.\nintrov G1 G2 G3 H. set (p := {bool2bset f3, bool2bset f2,bool2bset f1}).\nassert (X0: f1_I= (sndS p)) by \n(replace p with {bool2bset f3, bool2bset f2,bool2bset f1}; destruct f1 ; easy).\nassert (X1: f2_I= (sndS(fstS p))) by\n(replace p with {bool2bset f3, bool2bset f2,bool2bset f1}; destruct f2 ; easy).\nassert (X2: f3_I =   (fstS(fstS p))) by\n(replace p with {bool2bset f3, bool2bset f2,bool2bset f1}; destruct f3 ; easy).\nrewrite X0 in H. rewrite X1 in H. rewrite  X2 in H. \napply step0_tcbv_R with (t:=t) (c:=c) in H.\nSimpl. 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*)\nLemma step0_tcbv_C: forall fI t ctrTMR c, pure_bset fI->  \n                     corrupt_1in3_cir (ctrBl_dtr false false false) ctrTMR \n                     ->  step (ctrTMR -o- ctrVoting)  {fI,fI,fI}  t  c \n                     -> t={~0,~0,~0,~0,~0} /\\ c=(ctrBlockTMR false false true).\nProof.\nintrov H H0 H1. unfold ctrBlockTMR. split; Inverts H1.\n - apply tmr_corruptc  with (c':=(ctrBl_dtr false false true)) (s:=fI) (t:={~0,~0,~0,~0,~0}) in H0.\n    + apply  det_step_res with (c1:=c1') (t1:=t0 )  in H0. Inverts H0.\n      * assert (F:  fstep ctrVoting {~ 0, ~ 0, ~ 0, ~ 0, ~ 0, \n                                    {~ 0, ~ 0, ~ 0, ~ 0, ~ 0}, \n                                    {~ 0, ~ 0, ~ 0, ~ 0, ~ 0}}  = \n                    Some ({~0,~0,~0,~0,~0} ,  ctrVoting)) by\n        (vm_compute; try easy). eapply fstep_imp_detstep in F; Simpl.\n      * apply H6.\n    + Checkpure.\n    + assert ( exists t, exists c', step (ctrBl_dtr false false false) fI t c' ). apply step_all_ex.\n      Simpl. assert (HA :=  H1). apply fact_stepCtrBl_12 in H1. destruct H1; Simpl.\n - apply tmr_corruptc  with (c':=(ctrBl_dtr false false true)) (s:=fI) (t:={~0,~0,~0,~0,~0}) in H0.\n    + apply  det_step_cod with (c1:=c1') (t1:=t0 ) in H0. Inverts H0.\n      * apply step_comb_cir in H11; Simpl. repeat constructor. \n      * Checkpure.\n      * apply H6.\n    + Checkpure.\n    + assert ( exists t, exists c', step (ctrBl_dtr false false false) fI t c' ). apply step_all_ex.\n      Simpl. assert (HA :=  H1). apply fact_stepCtrBl_12 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/controlStep0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241632752914, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.28622434432602906}}
{"text": "\n(** 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.LanguageFoundations.\nRequire Import ComhCoq.SoftwareLanguage.\nRequire Import ComhCoq.InterfaceLanguage.\nRequire Import ComhCoq.ModeStateLanguage.\n\n(***************Messages*********************)\n\n\n(** A message is a vector of values augmented with coverage and location information.*)\nRecord Message : Type :=\nmkMsg\n{\n  msgPayload :> list BaseType;\n  msgPos : Position;\n  msgCoverage : Distance\n}.\nNotation \"[- v , l , r -]\" := (mkMsg v l r) (at level 40).\n\n(** Extract the delivery radius from a broadcast.*)\nDefinition rangeMsg (m : Message) : Distance :=\n   match m with [-v, l, r-] => r end.\n\n(** Return the first mode that occurs in v, or None if there is no such mode.*)\nFixpoint firstMode (v : list BaseType) : option Mode :=\n  match v with\n  | [] => None\n  | b :: vs => match b with\n    | baseMode m => Some m\n    | _ => firstMode vs\n    end\n  end.\n\n(** modeBc b will return the first mode m, if it exists,\nwithin the list of base values in b.*)\nDefinition modeBc (m : Message) : option Mode :=\n  match m with [-v, l, r-] => firstMode v end.\n\n(** Extract the position information from a broadcast. Note that this is the position\nof the sending entity at the time of sending rather than delivery. The entity may have\nmoved between sending and delivery.*)\nDefinition posBc (m : Message) : Position :=\n  match m with [-v, l, r-] => l end.\n\n\n\n(*************** Syntax (and some other stuff) *********************)\n\n\n(** And entity is a quadruple of components: An interface term, a software term,\nan MState term and a location.*)\nRecord Entity : Type := mkEntity\n{\n  procEnt :> ProcTerm;\n  posEnt :> Position;\n  interEnt :> Interface;\n  mstEnt : ModeState \n}.\nNotation \"[| p , l , i , k |]\" := (mkEntity p l i k) (at level 30).\n\n(** Equality on entities is decidable.*)\nLemma eqDecEnt : eqDec Entity. unfold eqDec.\n  destruct x1, x2. addHyp (eqDecModeState mstEnt0 mstEnt1).\n  addHyp (eqDecPosition posEnt0 posEnt1).\n  addHyp (eqDecInterface interEnt0 interEnt1).\n  addHyp (eqDecProcTerm procEnt0 procEnt1). invertClear H2.\n  invertClear H. invertClear H0. invertClear H1. left.\n  rewrite H2, H, H0, H3. reflexivity.\n  right. unfold not. intro. apply H0. inversion H1. reflexivity.\n  right. unfold not. intro. apply H. inversion H0. reflexivity.\n  right. unfold not. intro. apply H2. inversion H. reflexivity.\n  right. unfold not. intro. apply H3. inversion H2. reflexivity.\n  Qed.\n\n(** The current mode of an entity is the current mode of the mode state.*)\nCoercion currModeEnt (e : Entity) : Mode :=\n  match e with [|_, _, _, a|] => a end.\n\n(** The next mode of an entity is the next mode of the mode state.*)\nDefinition nextModeEnt (e : Entity) : option Mode :=\n  match e with [|_, _, _, a|] => nextModeMState a end.\n\nOpen Scope R_scope.\n\n(** If the minimum distance of compatibiltiy of the respective modes\nof the entities is less than or equal to the separation of the\nentities in space, then they are compatible.*)\nDefinition compatible (e1 e2 : Entity) : Prop :=\n  (minDistComp e1 e2) <= (dist2d e1 e2).\nNotation \"e1 ~~ e2\" := (compatible e1 e2) (left associativity, at level 40).\n\n(** Compatibility is a symmetric relation.*)\nLemma compatibleSymmetric : forall (e1 e2 : Entity), (e1 ~~ e2) <-> (e2 ~~ e1).\n  unfold compatible. intros. split; intros; rewrite minDistCompSymmetric in H;\n  rewrite distSymmetric in H; assumption. Qed.\n\n\n(***************Semantics*********************)\n\n(** A discrete action is either the input, output or ignorance of a message, or\nit is the silent value tau.*)\nInductive ActDiscEnt : Type :=\n  | aeTagOut : Message -> ActDiscEnt\n  | aeTagIn : Message -> ActDiscEnt\n  | aeTagIg : Message -> ActDiscEnt\n  | aeTau : ActDiscEnt.\nNotation \"b #!\" := (aeTagOut b) (at level 30).\nNotation \"b #?\" := (aeTagIn b) (at level 30).\nNotation \"b #:\" := (aeTagIg b) (at level 30).\n\nReserved Notation \"e1 -EA- a ->> e2\" (left associativity, at level 50).\nReserved Notation \"e1 -ED- a ->> e2\" (left associativity, at level 50).\n\n(** The discrete action semantics for entities.*)\nInductive stepDiscEnt : Entity -> ActDiscEnt -> Entity -> Prop :=\n  | stepDeProcTau : forall (p p' : ProcTerm) (l : Position) (i : Interface) (k : ModeState),\n    p -PA- tauAct -PA> p' -> [| p , l , i , k |] -EA- aeTau ->> [| p' , l , i , k |]\n  | stepDeIOProcInter : forall (p p' : ProcTerm) (l : Position)\n    (i i' : Interface) (k : ModeState) (v : list BaseType),\n    p -PA- chanOutProc ;! v -PA> p' -> i -i- chanOutProc {? v -i> i' ->\n    [| p , l , i , k |] -EA- aeTau ->> [| p' , l , i' , k |]\n  | stepDeIOInterProc : forall (p p' : ProcTerm) (l : Position)\n    (i i' : Interface) (k : ModeState) (v : list BaseType),\n    p -PA- chanInProc ;? v -PA> p' -> i -i- chanInProc {! v -i> i' ->\n    [| p , l , i , k |] -EA- aeTau ->> [| p' , l , i' , k |]\n  | stepDeNotif : forall (p p' : ProcTerm) (l : Position)\n    (i i' : Interface) (k : ModeState) (v : list BaseType),\n    p -PA- chanAN ;? v -PA> p' -> i -i- chanAN {! v -i> i' ->\n    [| p , l , i , k |] -EA- aeTau ->> [| p' , l , i' , k |]\n  | stepDeRdStbl : forall (p p' : ProcTerm) (l : Position)\n    (i : Interface) (k k' : ModeState),\n    p -PA- chanMStable *? -PA> p' -> k -ms- chanMStable @! -ms> k' ->\n    [| p , l , i , k |] -EA- aeTau ->> [| p' , l , i , k' |]\n  | stepDeCurrWrite : forall (p p' : ProcTerm) (l : Position)\n    (i : Interface) (k k' : ModeState) (m : Mode),\n    p -PA- chanMCurr *! -PA> p' -> k -ms- chanMCurr @? -ms> k' ->\n    [| p , l , i , k |] -EA- aeTau ->> [| p' , l , i , k' |]\n  | stepDeCurrRead : forall (p p' : ProcTerm) (l : Position)\n    (i : Interface) (k k' : ModeState) (m : Mode),\n    p -PA- chanMCurr ;? [baseMode m] -PA> p' -> k -ms- chanMCurr .! m -ms> k' ->\n    [| p , l , i , k |] -EA- aeTau ->> [| p' , l , i , k' |]\n  | stepDeNextWrite : forall (p p' : ProcTerm) (l : Position)\n    (i : Interface) (k k' : ModeState) (m : Mode),\n    p -PA- chanMNext ;! [baseMode m] -PA> p' -> k -ms- chanMNext .? m -ms> k' ->\n    [| p , l , i , k |] -EA- aeTau ->> [| p' , l , i , k' |]\n  | stepDeNextRead : forall (p p' : ProcTerm) (l : Position)\n    (i : Interface) (k k' : ModeState) (m : Mode),\n    p -PA- chanMNext ;? [baseMode m] -PA> p' -> k -ms- chanMNext .! m -ms> k' ->\n    [| p , l , i , k |] -EA- aeTau ->> [| p' , l , i , k' |]\n  | stepDePosRead : forall (p p' : ProcTerm) (l : Position)\n    (i : Interface) (k : ModeState),\n    p -PA- chanPos ;? [basePosition l] -PA> p' ->\n    [| p , l , i , k |] -EA- aeTau ->> [| p' , l , i , k |]\n  (** If the message sent was too far away, it gets ignored.*)\n  | stepDeIgnore : forall (p : ProcTerm) (l l' : Position)\n    (i : Interface) (k : ModeState) (v : list BaseType) (r : Distance),\n     r < dist2d l l' -> \n    [| p , l , i , k |] -EA- [-v, l', r-]#: ->> [| p , l , i , k |]\n  (** If the message sent was within range, then it gets input. This can be proven not\n  to block by analysing the behaviour of interface components. Therefore, a message\n  should always be accepted.*)\n  | stepDeIn : forall (p : ProcTerm) (l l' : Position)\n    (i i' : Interface) (k : ModeState) (v : list BaseType) (r : Distance),\n    dist2d l l' <= r -> i -i- chanIOEnv {? v -i> i' ->\n    [| p , l , i , k |] -EA- [-v, l', r-]#? ->> [| p , l , i' , k |]\n  | stepDeOut : forall (p : ProcTerm) (l : Position)\n    (i i' : Interface) (k : ModeState) (v : list BaseType) (r : Distance),\n    i -i- chanIOEnv _! v !_ r -i> i' ->\n    [| p , l , i , k |] -EA- [-v, l, r-]#! ->> [| p , l , i' , k |]\n  | stepDeTest : forall (p : ProcTerm) (l : Position)\n    (i : Interface) (k k' : ModeState) (m : Mode),\n    k -ms- chanMNext .? m -ms> k' ->\n    [| p , l , i , k |] -EA- aeTau ->> [| p , l , i , k' |]\n  where \"e1 -EA- a ->> e2\" := (stepDiscEnt e1 a e2).\n\n(**An entity e is discrete action enabled for the discrete action a iff\nthere is some entity e' such that e transitions to e' via a.*)\nDefinition discActEnabledEnt (e : Entity) (a : ActDiscEnt) :=\n  exists e', e -EA- a ->> e'.\n\n(** This predicate says that it is impossible for p to synchronise with either i\nor k via the discrete action a i.e. if p can do a, then neither i nor k can do its\ncomplement.*)\nDefinition noSyncNow (a : DiscAct) (p : ProcTerm)\n  (i : Interface) (k : ModeState) : Prop :=\n  discActEnabled p a ->\n  (~discActEnabledInter (a^) i /\\ ~discActEnabledMState (a^) k).\n\n(** This predicate says that p i and k cannot synchronise now, nor can they\nsynchronise after each has respectively performed a delay of d' that is less\nthan d.*)\nDefinition noSync (p : ProcTerm) (i : Interface)\n  (k : ModeState) (d : Delay) : Prop :=\n  forall a : DiscAct, noSyncNow a p i k /\\\n  (forall (p' : ProcTerm) (i' : Interface) (k' : ModeState) (d' : Delay),\n  d' < d -> p -PD- d' -PD> p' -> i -i- d' -i> i' -> k -ms- d' -ms> k' ->\n  noSyncNow a p' i' k'). \n\n(** The timed action semantics for entities. There is only one delay law. The software,\nmode state and interface components all must delay by the same amount d for the entire\nentity to delay by this amount. After this, there are two interesting premises to the law.\nThe first deals with a displacement vector delta, saying that its absolute value must be\nat most the delay multiplied by the maximum speed. In other words, movement is bounded.\nThe other premise that is of interest says that the components of the entity must not\nbe capable of synchronisation at any point during the delay.*)\nInductive stepTimedEnt : Entity -> Delay -> Entity -> Prop :=\n  | stepTeDel : forall (d : Delay) (p p' : ProcTerm) (l delta : Position)\n    (i i' : Interface) (k k' : ModeState),\n    p -PD- d -PD> p' -> i -i- d -i> i' -> k -ms- d -ms> k' ->\n    displacement delta <= speedMax * d -> noSync p i k d ->\n    [| p , l , i , k |] -ED- d ->> [| p' , addPos l delta, i' , k' |]\n  where \"e1 -ED- d ->> e2\" := (stepTimedEnt e1 d e2).\n\n\n(*************** Results & Tactics *********************)\n\n(*Destruct an entity and then its interface component*)\nLtac destr_ent_inter e p l k li lo ln := let h := fresh in destruct e as [p l h k];\n  destruct h as [li lo ln].\n\n(**If the current mode has changed across a tau transition, then the software process\noutput on mCurr, and the mode state input on the same channel.*)\nTheorem curr_switch_proc (p p' : ProcTerm) (l l' : Position) (h h' : Interface) (k k' : ModeState) :\n  [|p, l, h, k|] -EA- aeTau ->> [|p', l', h', k'|] -> currModeMState k <> currModeMState k' ->\n  p -PA- chanMCurr *! -PA> p' /\\ k -ms- chanMCurr @? -ms> k'.\n  intros H H0.\n  (*By inversion on the discrete entity transition*)\n  (*We first eliminate the cases where the mode state is the preserved.*)\n  invertClear H; try (false; apply H0; assumption);\n  (*We can then eliminate all cases where the the action is not tau,\n  and simultaneously match our goal.*)  \n  try (lets K : curr_switch_mState H10 H0; inversion K).\n  (*Now we have this case which follows from assumptions.*)\n  split;assumption.\n  (*Finally we deal with a stray case that wasn't caught in our earlier elimination.*)\n  lets K : curr_switch_mState H2 H0. inversion K. Qed.\n\n(** The derivative of an ignore transition is the same as the source.*)\nTheorem ignoreEqEnt : forall (e e' : Entity) (m : Message),\n  e -EA- m#: ->> e' -> e = e'. intros. invertClear H. reflexivity. Qed.\n\n(** An entity can always either input or ignore a message.*)\nTheorem inOrIgEnt : forall (e : Entity) (m : Message),\n  discActEnabledEnt e (m#?) \\/ discActEnabledEnt e (m#:). intros.\n  destruct m as [v l' r]. destruct e as [p l i k].\n  addHyp (Rlt_or_le r (dist2d l l')). invertClear H. right.\n  exists ([|p, l, i, k|]). apply stepDeIgnore. assumption. \n  left. addHyp (interfaceInEnabled i v). invertClear H.\n  rename x into i'. exists ([|p, l, i', k|]).\n  apply stepDeIn; assumption. Qed.\n\nConjecture dec_compatible : forall (e1 e2 : Entity),\n  e1 ~~ e2 \\/ ~(e1 ~~e2).\n(**Proof: Obvious*)\n\nConjecture currMode_ent_mState : forall (p : ProcTerm) (l : Position) (h : Interface)\n  (k : ModeState) (m : Mode), currModeEnt ([|p, l, h, k|]) = m -> currModeMState k = m.\n(**Proof: Obvious from definitions*)\n\nLemma link_ent_inter_disc p p' l l' h h' k k' a :\n  [|p, l, h, k|] -EA- a ->> [|p', l', h', k'|] ->\n  h = h' \\/ \n  (k = k' /\\\n  ((exists v, (h -i- chanOutProc {? v -i> h' /\\ p -PA- chanOutProc;! v -PA> p')) \\/\n  (exists v, (h -i- chanInProc {! v -i> h' /\\ p -PA- chanInProc;? v -PA> p')) \\/\n  (exists v, (h -i- chanAN {! v -i> h' /\\ p -PA- chanAN;? v -PA> p')) \\/\n  (exists v, h -i- chanIOEnv {? v -i> h') \\/\n  (exists v r, h -i- chanIOEnv _! v !_ r -i> h'))).\n  (*Inversion on entity transition and try LHS*)\n  introz U. inversion U; subst; try (left; reflexivity); right;\n  (split; [ reflexivity | ]).\n  (*Now we do the other cases.*)\n  left. exists v. split; assumption.\n  right. left. exists v. split; assumption.\n  right. right. left. exists v. split; assumption.\n  do 3 right. left. exists v. assumption.\n  do 4 right. exists v r. assumption. Qed.\n\n(*Adds the result stepDisc_ent_inter to the hypotheses and splits it up and tidies it.*)\nLtac link_entinterdisc_tac v r U := \n  match goal with\n  | [ H : [|?p, ?l, ?h, ?k|] -EA- ?a ->> [|?p', ?l', ?h', ?k'|] |- _] =>\n    let H1 := fresh in lets H1 : link_ent_inter_disc H;\n    let U1 := fresh U in let H0 := fresh in \n    (*Break off first disjunct as U1, leave H0 as chunk*)\n    elim_intro H1 U1 H0;[ | \n    let H7 := fresh in let H8 := fresh in\n    (*Break conjunction H0 into H7 and H8*)\n    decompAnd2 H0 H7 H8; let V := fresh v in\n    (*Break H8 up into 5 disjuncts*)\n    elimOr5 H8 U;\n    [(let H2 := fresh in destruct U1 as [V H2]; \n    andflat U).. | let H2 := fresh in destruct U1 as [V H2]; rename H2 into U1 | \n    let R := fresh r in let H3 := fresh in\n    decompEx2 U1 V R H3;rename H3 into U1 ]\n    ]\n  end.\n\nLemma link_ent_inter_del p p' l l' h h' k k' d :\n  [|p, l, h, k|] -ED- d ->> [|p', l', h', k'|] ->\n  h -i- d -i> h'. intros. inversion H. assumption. Qed.\n\nLtac link_entinterdel_tac U :=\n  match goal with\n  | [ H : [|?p, ?l, ?h, ?k|] -ED- ?d ->> [|?p', ?l', ?h', ?k'|] |- _] =>\n  let U1 := fresh U in lets U1 : link_ent_inter_del H\n  end.\n\nLemma link_ent_soft_del p p' l l' h h' k k' d :\n  [|p, l, h, k|] -ED- d ->> [|p', l', h', k'|] ->\n  p -PD- d -PD> p'. intros. inversion H. assumption. Qed.\n\nLtac link_entsoftdel_tac U :=\n  match goal with\n  | [ H : [|?p, ?l, ?h, ?k|] -ED- ?d ->> [|?p', ?l', ?h', ?k'|] |- _] =>\n  let U1 := fresh U in lets U1 : link_ent_soft_del H\n  end.\n\nLemma link_ent_mState_del p p' l l' h h' k k' d :\n  [|p, l, h, k|] -ED- d ->> [|p', l', h', k'|] ->\n  k -ms- d -ms> k'. intros. inversion H. assumption. Qed.\n\nLtac link_entmstatedel_tac U :=\n  match goal with\n  | [ H : [|?p, ?l, ?h, ?k|] -ED- ?d ->> [|?p', ?l', ?h', ?k'|] |- _] =>\n  let U1 := fresh U in lets U1 : link_ent_mState_del H\n  end.\n\nLemma timeSplit_ent e e'' d d' d'' :\n  e -ED- d'' ->> e'' -> d'' = d +d+ d' ->\n  exists e', e -ED- d ->> e' /\\ e' -ED- d' ->> e''. Admitted. (*6*)\n(**Proof: This should follow from time split properties of the underlying components. Also, it would have to be shown that the noSynch predicate would still hold for the intermediate entity component e', with the time parameter changed.*)\n\n\n(*LOCAL TIDY*)\n\n(** Destructs the next entity it encounters naming its sub-components as fresh instances\nof p, l, h, k.*)\nLtac destrEnt p l h k :=\n  match goal with\n  [ e : Entity |- _ ] =>\n  let vp := fresh p in let vl := fresh l in\n  let vh := fresh h in let vk := fresh k in\n  destruct e as [vp vl vh vk]\n  end.\n\n(** Repeatedly destructs all entities according to the names given.*)\nLtac destrEnts p l h k := repeat destrEnt p l h k.\n\n(**Destructs any entities it finds. May have also be searched for as destr_ents.*)\nLtac destrEnts_norm := let p := fresh \"p\" in let l := fresh \"l\" in\n  let h := fresh \"h\" in let k := fresh \"k\" in destrEnts p l h k.\n\n(** From a delay on an entity creates the hypothesis NS (a parameter) that no synchronisation\nis possible between any of the components of the entity.*)\nLtac del_noSync_tac NS :=\n  match goal with [a : DiscAct, U : [|?p0, _, ?h0, ?k0|] -ED- ?d ->> _ |- _] =>\n  assert (noSync p0 h0 k0 d) as NS; [inversion U; assumption | ]\n  end.\n\n(** From a hypothesis X of noSynch between various components, creates a weakened version of X\nsaying that noSyncNow is possible between those components and calls it NS.*)\nLtac noSync_noSyncNow_tac NS := \n  match goal with\n  [ a : DiscAct, X : noSync ?p0 ?h0 ?k0 _ |- _] =>\n  assert (noSyncNow a p0 h0 k0) as NS; [unfold noSync in X; apply X\n  | ] end.\n\n(** From an entity delay creates the hypothesis NS saying that noSyncNow is possible between\nthe components of the entity, via the first action a matched in the hypotheses.*)\nLtac del_noSyncNow_tac NS :=\n  let X := fresh in del_noSync_tac X; noSync_noSyncNow_tac NS;\n  clear X.\n\n(**Takes a delay hypothesis and inverts to give that noSyncNow holds for\nthe components of the entity in question.*)\nLtac noSyncNow_tac := match goal with\n  [A : [|?p, _, ?h, ?k|] -ED- ?d ->> _ |- _] =>\n  let NS := fresh \"NS\" in\n  assert (forall a, noSyncNow a p h k) as NS;\n  [inversion A; match goal with [B : noSync p h k d |- _] =>\n  apply B end| ] end.\n\n(*Inverts an entity delay to a process delay*)\n  Ltac invertDel_ent_proc := match goal with\n  [U1 : [|?p0, _, _, _|] -ED- ?d ->> [|?p, _, _, _|] |- _ ]\n  => assert (p0 -PD- d -PD> p) as PD; [inversion U1; assumption | ] end.\n\n(** Creates a hypothesis PD saying that some process delays to another process,\nthen rewrites TR, an equality identifying the process with a triple of processes,\nthen creates three hypotheses saying that the sort relations of the three processes\nare distinct, called SORT1_2, SORT1_3 and SORT2_3.*)\nLtac del_triple_sort_tac :=\n  (try invertDel_ent_proc); match goal with\n  [TR : ?p = ?p1 $||$ ?p2 $||$ ?p3, PD : ?p -PD- ?d -PD> ?p' |- _] =>\n  rewrite TR in PD; let U := fresh in let x := fresh \"SORT1_2\" in\n  let y := fresh \"SORT1_3\" in let z := fresh \"SORT2_3\" in\n  (lets U : del_triple_sort PD; decompAnd3 U x y z) 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/EntityLanguage.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.28622434432602906}}
{"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(* A directed graph -Digraph- is a type dependant of a set of           *)\n(* vertices and a set of arcs. An inhabitant of such a type is a        *)\n(* construction, inductively defined, of this graph. Some Digraphs      *)\n(* are not inhabited.                                                   *)\n\n(* The following notions are defined :                                  *)\n(*      - (Digraph v a) : set of directed graph with vertices in v      *)\n(*                              and arcs in a,                          *)\n(*              constructors : D_empty, D_vertex, D_arc, D_eq;          *)\n(*      - DV_list : list of vertices of a Digraph;                      *)\n(*      - DA_list : list of arcs of a Digraph;                          *)\n(*      - D_oreder : number of vertices;                                *)\n(*      - D_size : number of arcs.                                      *)\n\nRequire Export Arcs.\n\nSection DIGRAPH.\n\nVariable A:Type.\nVariable eq_a_dec: forall x y : A, {x = y} + {x <> y}.\n\nInductive Digraph : @V_set A -> @A_set A -> Type :=\n  | D_empty : Digraph (@V_empty A) (@A_empty A)\n  | D_vertex :\n      forall (v : V_set) (a : A_set) (d : Digraph v a) (x : Vertex),\n      ~ v x -> Digraph (V_union (V_single x) v) a\n  | D_arc :\n      forall (v : V_set) (a : A_set) (d : Digraph v a) (x y : Vertex),\n      v x ->\n      v y ->\n      ~ a (A_ends x y) -> Digraph v (A_union (A_single (A_ends x y)) a)\n  | D_eq :\n      forall (v v' : V_set) (a a' : A_set),\n      v = v' -> a = a' -> Digraph v a -> Digraph v' a'.\n\nFixpoint DV_list (v : V_set) (a : A_set) (d : Digraph v a) {struct d} :\n V_list :=\n  match d with\n  | D_empty => V_nil\n  | D_vertex v' a' d' x _ => x :: DV_list v' a' d'\n  | D_arc v' a' d' x y _ _ _ => DV_list v' a' d'\n  | D_eq v v' a a' _ _ d => DV_list v a d\n  end.\n\nFixpoint DA_list (v : V_set) (a : A_set) (d : Digraph v a) {struct d} :\n A_list :=\n  match d with\n  | D_empty => A_nil\n  | D_vertex v' a' d' x _ => DA_list v' a' d'\n  | D_arc v' a' d' x y _ _ _ => A_ends x y :: DA_list v' a' d'\n  | D_eq v v' a a' _ _ d => DA_list v a d\n  end.\n\nDefinition D_order (v : V_set) (a : A_set) (d : Digraph v a) :=\n  length (DV_list v a d).\n\nDefinition D_size (v : V_set) (a : A_set) (d : Digraph v a) :=\n  length (DA_list v a d).\n\nLemma D_v_dec :\n forall (v : V_set) (a : A_set) (d : Digraph v a) (x : Vertex),\n {v x} + {~ v x}.\nProof.\n        intros v a d; elim d; intros.\n        right; apply V_empty_nothing.\n\n        case (X x0); intros.\n        left; apply V_in_right; trivial.\n\n        case (V_eq_dec eq_a_dec x x0); intros.\n        left; apply V_in_left; rewrite e; apply V_in_single.\n\n        right; red in |- *; intros; inversion H.\n        elim n1; inversion H0; trivial.\n\n        elim n0; trivial.\n\n        auto.\n\n        case (X x); intros.\n        left; elim e; trivial.\n\n        right; elim e; trivial.\nQed.\n\nLemma D_a_dec :\n forall (v : V_set) (a : A_set) (d : Digraph v a) (x : Arc), {a x} + {~ a x}.\nProof.\n        intros v a d; elim d; intros.\n        right; apply A_empty_nothing.\n\n        auto.\n\n        case (X x0); intros.\n        left; apply A_in_right; trivial.\n\n        case (A_eq_dec eq_a_dec (A_ends x y) x0); intros.\n        left; apply A_in_left; rewrite e; apply A_in_single.\n\n        right; red in |- *; intros; inversion H.\n        elim n1; inversion H0; trivial.\n\n        elim n0; trivial.\n\n        case (X x); intros.\n        left; elim e0; trivial.\n\n        right; elim e0; trivial.\nQed.\n\nEnd DIGRAPH.\n\nImplicit Arguments Digraph [A].\nImplicit Arguments D_v_dec [A].\nImplicit Arguments D_a_dec [A].\n\nSection UNION_DIGRAPHS.\n\nVariable A:Type.\nVariable eq_a_dec: forall x y : A, {x = y} + {x <> y}.\n\nLemma D_union :\n forall (v1 v2 : V_set) (a1 a2 : @A_set A),\n Digraph v1 a1 -> Digraph v2 a2 -> Digraph (V_union v1 v2) (A_union a1 a2).\nProof.\n        intros; elim X; intros.\n        apply D_eq with (v := v2) (a := a2).\n        symmetry  in |- *; apply V_union_neutral.\n\n        symmetry  in |- *; apply A_union_neutral.\n\n        trivial.\n\n        case (D_v_dec eq_a_dec v2 a2 X0 x); intros.\n        apply D_eq with (v := V_union v v2) (a := A_union a a2).\n        autounfold.\n        rewrite V_union_assoc; rewrite (V_union_absorb (V_single x)); trivial.\n        apply V_included_single; apply V_in_right; trivial.\n\n        trivial.\n\n        trivial.\n\n        apply\n         D_eq\n          with (v := V_union (V_single x) (V_union v v2)) (a := A_union a a2).\n        symmetry  in |- *; apply V_union_assoc.\n\n        trivial.\n\n        apply D_vertex.\n        trivial.\n\n        apply V_not_union; trivial.\n\n        case (D_a_dec eq_a_dec v2 a2 X0 (A_ends x y)); intros.\n        apply D_eq with (v := V_union v v2) (a := A_union a a2).\n        trivial.\n\n        repeat autounfold. \n        rewrite A_union_assoc;\n         rewrite (A_union_absorb (A_single (A_ends x y)));\n         trivial.\n        apply A_included_single; apply A_in_right; trivial.\n\n        trivial.\n\n        apply\n         D_eq\n          with\n            (v := V_union v v2)\n            (a := A_union (A_single (A_ends x y)) (A_union a a2)).\n        trivial.\n\n        symmetry  in |- *; apply A_union_assoc.\n\n        apply D_arc.\n        trivial.\n\n        apply V_in_left; trivial.\n\n        apply V_in_left; trivial.\n\n        apply A_not_union; trivial.\n\n        apply D_eq with (v := V_union v v2) (a := A_union a a2).\n        elim e; trivial.\n\n        elim e0; trivial.\n\n        trivial.\nQed.\n\nEnd UNION_DIGRAPHS.\n\nImplicit Arguments D_empty [A].\nImplicit Arguments D_vertex [A].\nImplicit Arguments D_eq [A].\nImplicit Arguments D_arc [A].\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/GraphBasics/Digraphs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.2861738820200073}}
{"text": "(* begin hide *)\nRequire Import Coq.Strings.String.\nRequire Import Coq.Strings.Ascii.\nRequire Import Coq.Numbers.Natural.Peano.NPeano.\n(* end hide *)\n(** Many languages provide mechanisms for formatted output, with C's\n[printf] undoubtedly being the most influential one. Some of these\nfunctions allow a format to be specified using a concise and intuitive\nsyntax, which is probably part of the reason for them being so\npopular. For [printf], for instance, a format is described using just\na plain string.\n\nUnfortunately, this convenience often comes with a price. In C, a\nmismatch between the output format and the other arguments results in\nincorrect behavior. This non-trivial dependency can't be expressed in\nthe language's type system and requires additional compiler checks to\nbe enforced. Other languages suffer from similar problems. Haskell's\nstandard [printf] also causes a run-time error when a format mismatch\noccurs. OCaml is able to enforce that format and arguments are\ncompatible at compile-time, but at the cost of extending the language\nwith an _ad-hoc_ [format] type that is also represented as\nstrings. Other approaches solve the problem by adopting different\nrepresentations for the output format, which can make it slightly less\nconvenient to specify. In #<a\nhref=\"http://www.brics.dk/RS/98/12/BRICS-RS-98-12.pdf\">Functional\nUnparsing</a>#, Olivier Danvy showed how to implement an analogue of\n[printf] using formatting combinators. More recently, Oleg Kiselyov\nused delimited control operators to implement his own type-safe\nversion of [printf] in #<a\nhref=\"http://okmij.org/ftp/Haskell/ShiftResetGenuine.hs\">Haskell</a>#,\nan idea that has also been ported to #<a\nhref=\"http://mattam.org/repos/coq/misc/shiftreset/GenuineShiftReset.html\">Coq</a>#\nby Matthieu Sozeau.\n\nIt would be a shame if we had to extend our language in an _ad-hoc_\nmanner just to get safe and convenient formatting. We will see how we\ncan use Coq's expressive type system to describe the dependency\nbetween a format string and the arguments it requires, and implement a\nversion of [sprintf] that doesn't suffer from the aforementioned\nissues.\n\nLet's begin by defining some useful notations for lists and\nstrings. *)\n\nNotation \"[ ]\" := nil : list_scope.\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y nil) ..) : list_scope.\nNotation \"x ::: y\" := (String x y)\n                        (at level 60, right associativity) : string_scope.\n\nOpen Scope list_scope.\nOpen Scope char_scope.\n\n(** ** Directives and format\n\nBefore working directly with strings, we will define a new data type\nto describe an output format, and then use it to implement a\npreliminary version of [sprintf]. As we shall see, this will help us\nexpress the not-so-trivial type of [sprintf] and simplify our\nimplementation. Later, we will write a separate function to convert\n[string]s to this new type, and combine both programs to obtain our\nfinal result.\n\nOur [format] type is inspired by [printf] formats in C, which can be\nseen as a sequence of _directives_. Each directive can be either a\nliteral character, to be printed verbatim, or a _control sequence_,\nwhich instructs the function to print one of its arguments in a\ncertain format. Thus, we begin by defining a [directive] type, loosely\nbased upon what is available in C: *)\n\nInductive directive : Type :=\n| DLit : ascii -> directive\n| DNum : option nat -> directive\n| DBool : directive\n| DString : directive\n| DChar : directive.\n\n(** Directive [DLit c] outputs the literal character [c], while [DNum\ns], [DBool], [DString], and [DChar] take an argument of the\ncorresponding type and print it. The [s] field of [DNum s] controls\nhow its argument should be printed. If [s = Some n], then we output\nexactly the [n] least-significant digits of the number, padding it\nwith zeros if necessary. Otherwise, if [s = None], we just print the\nwhole number. Thus, the number [4] should be printed as [4] using the\n[DNum None], but as [04] using [DNum (Some 2)].\n\nWith the [directive] type in hand, defining [format] is\nstraightforward: *)\n\nDefinition format := list directive.\n\n(** ** Relating format and arguments\n\nAs noted above, [sprintf f] should be a function that returns a\n[string] and takes one argument for each directive in [f] that\nrequires one. For instance, [sprintf [DBool, DString]] should have\ntype [bool -> string -> string], whereas [sprintf [DLit \"a\", DLit \"b\",\nDNum None]] should have type [nat -> string].\n\nThis relation is easy to express in Coq using dependent types. Since\ntypes can be the result of computations, it is possible to write a\n[formatType] function that takes a [format] [f] and returns the type\nof [sprintf f]. Let's begin by defining a function that maps each\ndirective to the corresponding argument type. Notice that its result\ntype must be an [option], since [DLit] doesn't need arguments. *)\n\nDefinition directiveType (dir : directive) :=\n  match dir with\n    | DLit _ => None\n    | DNum _ => Some nat\n    | DBool => Some bool\n    | DString => Some string\n    | DChar => Some ascii\n  end.\n\n(** Now, [formatType] itself is just a direct translation of what we\nstated above. *)\n\nFixpoint formatType (f : format) : Type :=\n  match f with\n    | [] => string\n    | dir :: dirs =>\n      match directiveType dir with\n        | Some T => T -> formatType dirs\n        | None => formatType dirs\n      end\n  end.\n\n(** We can check if this definition makes sense on simple examples. *)\n\nExample formatTypeTest1 : formatType [DBool, DString] =\n                          (bool -> string -> string).\nProof. reflexivity. Qed.\n\nExample formatTypeTest2 : formatType [DLit \"a\", DLit \"b\", DNum None] =\n                          (nat -> string).\nProof. reflexivity. Qed.\n\n(** ** The implementation\n\nNow that we can express the type of [sprintf], we can try to implement\nit. We might be tempted to try something like this:\n\n[[\nFixpoint sprintf (f : format) : formatType f :=\n  match f with\n    | [] => \"\"\n    | dir :: dirs =>\n      match dir with\n        | DLit c => c ::: sprintf dirs\n        (* ... *)\n      end\n  end.\n]]\n\nAlas, this approach doesn't work. The problem here is that our\nrecursive call to [sprintf] returns a [formatType dirs] instead of\na [string], which means that we are unable to add character [c] in\nfront of it.\n\nInstead of building the string directly on the body of the match, we\nwill add an auxiliary parameter [k] to [sprintf]. [k] will be a\n_continuation_ of type [string -> string] that builds the final output\nusing the result of the recursive calls. The implementation uses some\nauxiliary functions, such as [writeNat], that have been omitted in the\ninterest of space. Their definitions can be found in the original [.v]\nfile. *)\n\n(* begin hide *)\nDefinition digitToNat (c : ascii) : option nat :=\n  match c with\n    | \"0\" => Some 0\n    | \"1\" => Some 1\n    | \"2\" => Some 2\n    | \"3\" => Some 3\n    | \"4\" => Some 4\n    | \"5\" => Some 5\n    | \"6\" => Some 6\n    | \"7\" => Some 7\n    | \"8\" => Some 8\n    | \"9\" => Some 9\n    | _   => None\n  end.\n\nDefinition natToDigit (n : nat) : ascii :=\n  match n with\n    | 0 => \"0\"\n    | 1 => \"1\"\n    | 2 => \"2\"\n    | 3 => \"3\"\n    | 4 => \"4\"\n    | 5 => \"5\"\n    | 6 => \"6\"\n    | 7 => \"7\"\n    | 8 => \"8\"\n    | _ => \"9\"\n  end%char.\n\nOpen Scope string_scope.\n\nFixpoint writeNatAux (time n : nat) (crop : bool) (acc : string) : string :=\n  match time with\n    | 0 => acc\n    | S time' =>\n      let acc' := natToDigit (n mod 10) ::: acc in\n      match n / 10 with\n        | 0 => if crop then acc'\n               else writeNatAux time' 0 crop acc'\n        | n' => writeNatAux time' n' crop acc'\n      end\n  end.\n\nDefinition writeNat (n : nat) (acc : string) : string :=\n  writeNatAux (S n) n true acc.\n\nDefinition writeNatSize (size : nat) (n : nat) (acc : string) : string :=\n  writeNatAux size n false acc.\n\nDefinition writeBool (b : bool) : string :=\n  if b then \"true\" else \"false\".\n(* end hide *)\n\nModule Internal.\n\nFixpoint sprintf (f : format) (k : string -> string) : formatType f :=\n  match f with\n    | [] => k \"\"\n    | dir :: dirs =>\n      match dir return formatType (dir :: dirs) with\n        | DLit c => sprintf dirs (fun res => k (c ::: res))\n        | DNum o =>\n          fun n =>\n            let k' := match o with\n                        | Some size => fun res => k (writeNatSize size n res)\n                        | None => fun res => k (writeNat n res)\n                      end in\n            sprintf dirs k'\n        | DBool =>\n          fun b =>\n            sprintf dirs (fun res => k (writeBool b ++ res))\n        | DString =>\n          fun s =>\n            sprintf dirs (fun res => k (s ++ res))\n        | DChar =>\n          fun c =>\n            sprintf dirs (fun res => k (c ::: res))\n      end\n  end.\n\n(** Most directives generate an additional argument to [sprintf] by\nwrapping the recursive call with an anonymous function. Also, notice\nthe type annotation on the inner [match]: [return formatType (dir ::\ndirs)]. As one could hope, this mysterious expression is telling Coq\nwhich type is being returned on each branch of the [match]. Dependent\ntypes require more sophisticated type inference, and in some cases it\nis necessary to provide these annotations explicitly.\n\nTo use [sprintf], we just have to pass it the identity continuation\n[fun res => res], which will receive the value built by [sprintf] and\nreturn it as-is. *)\n\nExample sprintfTest1 :\n  sprintf [DNum None, DString] (fun res => res)\n          42 \"This is a string\" = \"42This is a string\".\nProof. reflexivity. Qed.\n\nExample sprintfTest2 :\n  sprintf [DNum (Some 2), DLit \"/\", DNum (Some 2)] (fun res => res)\n          2 4 = \"02/04\".\nProof. reflexivity. Qed.\n\nEnd Internal.\n\n(** ** Strings as format\n\nNow that we have our first implementation, we will write the code\nneeded to parse the format from a [string]. Our format syntax is\ninspired by C's own syntax. All characters are interpreted literally,\nexcept for [%], which signals the beginning of a control sequence. As\nin C, we can write [%<n>d], where [<n>] is a number, to specify how\nmany digits we want when printing a [nat].\n\nThe [parseFormat] function below tries to read a [format], returning\n[Some f] if the [string] argument represents [f], and [None] if there\nwas a parse error. [parseFormatSize] is used to read the [%<n>d]\ndirectives. The auxiliary function [addDir] adds a directive to an\n[option format] when possible, returning [None] otherwise. *)\n\nDefinition addDir (o : option format) (dir : directive) : option format :=\n  match o with\n    | Some f => Some (dir :: f)\n    | None => None\n  end.\n\nFixpoint parseFormat (s : string) : option format :=\n  match s with\n    | \"\" => Some []\n    | \"%\" ::: s' =>\n      match s' with\n        | \"%\" ::: s'' => addDir (parseFormat s'') (DLit \"%\")\n        | \"b\" ::: s'' => addDir (parseFormat s'') DBool\n        | \"s\" ::: s'' => addDir (parseFormat s'') DString\n        | \"c\" ::: s'' => addDir (parseFormat s'') DChar\n        | \"d\" ::: s'' => addDir (parseFormat s'') (DNum None)\n        | _ => parseFormatSize s' 0\n      end\n    | c ::: s' =>\n      addDir (parseFormat s') (DLit c)\n  end\n\nwith parseFormatSize (s : string) (acc : nat) : option format :=\n       match s with\n         | \"\" => None\n         | \"d\" ::: s' => addDir (parseFormat s') (DNum (Some acc))\n         | c ::: s' =>\n           match digitToNat c with\n             | Some n => parseFormatSize s' (10 * acc + n)\n             | None => None\n           end\n       end.\n\n(** We can test our function in some simple cases. *)\n\nExample parseFormatTest1 :\n  parseFormat \"%d%4da\" = Some [DNum None, DNum (Some 4), DLit \"a\"].\nProof. reflexivity. Qed.\n\nExample parseFormatTest2 :\n  parseFormat \"%ca%s%\" = None.\nProof. reflexivity. Qed.\n\nExample parseFormatTest3 :\n  parseFormat \"%s%b\" = Some [DString, DBool].\nProof. reflexivity. Qed.\n\n(** ** Putting the pieces together\n\nUsing [parseFormat], we can now write a convenient wrapper for our\nfirst [sprintf]. Just as we did in the #<a\nhref=\"/posts/2013-04-03-parse-errors-as-type-errors.html\">previous\npost</a>#, we ensure that invalid format strings are detected right\naway by producing a value of a different type when we hit a parse\nerror. *)\n\nInductive printfError := InvalidFormat.\n\nDefinition sprintfOpt (o : option format) : match o with\n                                              | Some f => formatType f\n                                              | None => printfError\n                                            end :=\n  match o with\n    | Some f => Internal.sprintf f (fun res => res)\n    | None => InvalidFormat\n  end.\n\nDefinition sprintf (s : string) := sprintfOpt (parseFormat s).\n\n(** Despite its intricate type, using our function is simple, as the\nexamples below show. *)\n\nDefinition greet name y m d : string :=\n  sprintf \"Hello %s, today is %d/%2d/%2d\" name y m d.\n\nExample greetTest1 : greet \"readers\" 2013 4 19 =\n                     \"Hello readers, today is 2013/04/19\".\nProof. reflexivity. Qed.\n\nDefinition tableRow name value : string :=\n  sprintf \"<tr><td>%s</td><td>%b</td></tr>\" name value.\n\nExample tableRowTest1 : tableRow \"x1\" true =\n                        \"<tr><td>x1</td><td>true</td></tr>\".\nProof. reflexivity. Qed.\n\n(** Trying to pass the wrong number of arguments to [sprintf], or\ngiving it arguments of the wrong type, will result in a type error. *)\n\n(* Example greetTest2 : string := greet 2013 4 19 \"readers\". *)\n\n(* Error: The term \"2013\" has type \"nat\" while it is expected to have type\n  \"string\". *)\n\n(* Example tableRowTest2 : string := tableRow \"x1\". *)\n\n(* Error: The term \"tableRow \"x1\"\" has type \"bool -> string\"\n   while it is expected to have type \"string\". *)\n\n(** ** Summary\n\nWe've seen how to implement a type-safe version of [sprintf] in\nCoq. Unlike other approaches to the problem, our solution did not\nrequire abandoning strings for specifying formats, nor relies on any\nspecial extensions to the language. Type computation and dependent\ntypes, the key ingredients in our implementation, are powerful\ngeneral-purpose features that lie at the heart of Coq. *)\n", "meta": {"author": "arthuraa", "repo": "poleiro", "sha": "c2f2159470872ac83d305b4a50fda8fccc89ae53", "save_path": "github-repos/coq/arthuraa-poleiro", "path": "github-repos/coq/arthuraa-poleiro/poleiro-c2f2159470872ac83d305b4a50fda8fccc89ae53/theories/Printf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.2861738742885876}}
{"text": "\nDefinition Berry (x y z : bool) :=\n  match x, y, z with\n  | true, false, _ => 0\n  | false, _, true => 1\n  | _, true, false => 2\n  end.\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/test-suite/failure/Case4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.28617387428858754}}
{"text": "(*\nCopyright © 2020 Vincent Semeria\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*)\n\n(** Consequence of the Markov principle on constructive reals. *)\n\nRequire Import Coq.QArith.QArith_base.\nRequire Import Coq.Reals.Abstract.ConstructiveReals.\nRequire Import Coq.Reals.Abstract.ConstructiveAbs.\n\nLocal Open Scope ConstructiveReals.\n\n(* This axiom has computational content :\n   run the unbounded search Pdec 0, Pdec 1, ...\n   and the last hypothesis is a proof of termination. *)\nDefinition Markov : Prop\n  := forall (P : nat -> Prop),\n    (forall n:nat, {P n} + {~P n})\n    -> (~~exists n:nat, P n)\n    -> exists n:nat, P n.\n\nLemma Markov_notnot_lt_0 : forall {R : ConstructiveReals} (x : CRcarrier R),\n    Markov -> (~~CRltProp R 0 x) -> CRltProp R 0 x.\nProof.\n  intro R.\n  assert (forall (x : CRcarrier R) (n:nat),\n             x - CR_of_Q R (1#Pos.of_nat n) < x) as bumpDown.\n  { intros x n.\n    apply (CRlt_le_trans _ (x-0)).\n    apply CRplus_lt_compat_l.\n    apply CRopp_gt_lt_contravar, CR_of_Q_lt.\n    reflexivity.\n    unfold CRminus. rewrite CRopp_0, CRplus_0_r.\n    apply CRle_refl. }\n  intros x markov xpos. \n  assert (exists n:nat, Qlt 0 (let (q,_) := CR_Q_dense R _ _ (bumpDown x n) in q)).\n  { apply markov.\n    - intro n.\n      destruct (CR_Q_dense R _ _ (bumpDown x n)) as [q H].\n      destruct (Qlt_le_dec 0 q).\n      left. exact q0. right. apply (Qle_not_lt _ _ q0).\n    - intro abs. contradict xpos; intro xpos.\n      apply CRltEpsilon in xpos.\n      contradict abs.\n      destruct (CR_archimedean R (CRinv R x (inr xpos))) as [n H].\n      exists (Pos.to_nat n).\n      destruct ( CR_Q_dense R (x - CR_of_Q R (1 # Pos.of_nat (Pos.to_nat n)))%ConstructiveReals\n        x (bumpDown x (Pos.to_nat n))) as [q H0].\n      apply (lt_CR_of_Q R).\n      refine (CRle_lt_trans _ _ _ _ (fst H0)).\n      clear H0 q.\n      rewrite Pos2Nat.id.\n      apply (CRplus_le_reg_r (CR_of_Q R (1#n))).\n      unfold CRminus.\n      rewrite CRplus_0_l.\n      rewrite CRplus_assoc.\n      rewrite CRplus_opp_l, CRplus_0_r.\n      apply CRlt_asym in H.\n      apply (CRmult_le_compat_l x) in H.\n      rewrite CRinv_r in H.\n      apply (CRmult_le_compat_r (CR_of_Q R (1#n))) in H.\n      rewrite CRmult_1_l, CRmult_assoc, <- CR_of_Q_mult in H.\n      setoid_replace ((Z.pos n # 1) * (1 # n))%Q with 1%Q in H.\n      rewrite CRmult_1_r in H. exact H.\n      unfold Qeq; simpl.\n      rewrite Pos.mul_1_r, Pos.mul_1_r. reflexivity.\n      apply CR_of_Q_le; discriminate.\n      apply CRlt_asym, xpos. }\n  clear xpos.\n  destruct H as [n H].\n  destruct (CR_Q_dense R _ _ (bumpDown x n)) as [q H0].\n  apply CRltForget.\n  apply (CRlt_trans _ (CR_of_Q R q)).\n  apply CR_of_Q_lt, H. \n  apply H0.\nQed.\n\nLemma Markov_notnot_lt : forall {R : ConstructiveReals} (x y : CRcarrier R),\n    Markov -> (~~CRltProp R x y) -> CRltProp R x y.\nProof.\n  intros. apply CRltForget.\n  apply (CRplus_lt_reg_r (-x)).\n  apply (CRle_lt_trans _ 0).\n  rewrite CRplus_opp_r. apply CRle_refl.\n  apply CRltEpsilon.\n  apply (Markov_notnot_lt_0 (y-x) H).\n  intro abs. contradict H0; intro H0.\n  contradict abs.\n  apply CRltForget.\n  apply (CRplus_lt_reg_r x).\n  apply (CRle_lt_trans _ x).\n  rewrite CRplus_0_l. apply CRle_refl.\n  apply (CRlt_le_trans _ y).\n  apply CRltEpsilon, H0.\n  unfold CRminus.\n  rewrite CRplus_assoc, CRplus_opp_l, CRplus_0_r.\n  apply CRle_refl.\nQed.\n\nLemma Markov_notnot_apart_0 : forall {R : ConstructiveReals} (x : CRcarrier R),\n    Markov -> (~(x == 0)) -> (x ≶ 0).\nProof.\n  intros.\n  apply CRabs_appart_0.\n  apply CRltEpsilon, (Markov_notnot_lt_0 _ H).\n  intro abs. contradict H0.\n  assert (CRabs R x <= 0) as H0.\n  { intro H0. contradict abs.\n    apply CRltForget, H0. }\n  pose proof (CRabs_def2 x 0 H0) as [H1 H2].\n  rewrite CRopp_0 in H2.\n  split; assumption.\nQed.\n\nLemma Markov_notnot_apart : forall {R : ConstructiveReals} (x y : CRcarrier R),\n    Markov -> (~(x == y)) -> (x ≶ y).\nProof.\n  intros. \n  apply (CRplus_appart_reg_r (-y)). \n  rewrite CRplus_opp_r.\n  apply (Markov_notnot_apart_0 _ H).\n  intro abs. contradict H0.\n  apply (CRplus_eq_reg_r (-y)).\n  rewrite CRplus_opp_r. exact abs.\nQed.\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/stdlib/Markov.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.2861738665571678}}
{"text": "(* -*- mode: coq; mode: visual-line -*-  *)\n\nFrom HoTT Require Import Basics.\nFrom WildCat Require Import Basics.\nFrom WildCat Require Export Cat1 Laxity.\n\nGeneralizable Variables m n p A B C.\n\n(** * Inserters and natural transformations *)\n\n(** ** Dependent inserters *)\n\nDefinition GenDInserter (ls : Stream Laxity) `{IsGlob m A} `{HasEquivs n B}\n           (F G : A -> B) `{!IsFunctor0 F, !IsFunctor0 G}\n           (a : A)\n  := lHom (head ls) (F a) (G a).\n\nCoFixpoint isdglob_gendinserter (ls : Stream Laxity)\n           `{IsGlob m A} `{HasEquivs n B}\n           (F G : A -> B) `{!IsFunctor0 F, !IsFunctor0 G}\n  : IsDGlob n (GenDInserter ls F G).\nProof.\n  unshelve econstructor.\n  - intros a b f ta tb; revert f.\n    unfold GenDInserter in ta, tb.\n    destruct (head ls).\n    + exact (GenDInserter (tail ls) (cat_postcomp (F a) tb o fmap F)\n                          (cat_precomp (G b) ta o fmap G)).\n    + exact (GenDInserter (tail ls) (cat_postcomp (F a) tb o fmap F)\n                          (cat_precomp (G b) ta o fmap G)).\n    + exact (GenDInserter (tail ls) (cat_postcomp (G a) tb o fmap G)\n                          (cat_precomp (F b) ta o fmap F)).\n  - intros a b ta tb; cbn.\n    unfold GenDInserter in ta, tb.\n    set (l := head ls) in *.\n    destruct l;\n    apply isdglob_gendinserter.\nDefined.\nGlobal Existing Instance isdglob_gendinserter.\n\n(** We can forget the invertibility of an iso-inserter. *)\nDefinition colax_pseudo_inserter\n           (ls : Stream Laxity) `{IsGlob m A} `{HasEquivs n B}\n           (F G : A -> B) `{!IsFunctor0 F, !IsFunctor0 G} (a : A)\n  : (GenDInserter (scons pseudo ls) F G a) -> (GenDInserter (scons colax ls) F G a)\n  := fun f => cate_fun f.\n\nGlobal Instance isdfunctor0_colax_pseudo_inserter\n       (ls : Stream Laxity) `{IsGlob m A} `{HasEquivs n B}\n       (F G : A -> B) `{!IsFunctor0 F, !IsFunctor0 G}\n  : IsDFunctor0 idmap (colax_pseudo_inserter ls F G).\nProof.\n  unshelve econstructor.\n  - cbn; intros a b u v f g.\n    exact g.\n  - cbn; intros a b u v.\n    apply isdfunctor0_idmap.\nDefined.\n\n(** And we can turn around a lax inserter into a colax one. *)\nDefinition colax_lax_inserter\n           (ls : Stream Laxity) `{IsGlob m A} `{HasEquivs n B}\n           (F G : A -> B) `{!IsFunctor0 F, !IsFunctor0 G} (a : A)\n  : (GenDInserter (scons lax ls) G F a) -> (GenDInserter (scons colax ls) F G a)\n  := fun f => f.\n\nGlobal Instance isdfunctor0_colax_lax_inserter\n       (ls : Stream Laxity) `{IsGlob m A} `{HasEquivs n B}\n       (F G : A -> B) `{!IsFunctor0 F, !IsFunctor0 G}\n  : IsDFunctor0 idmap (colax_lax_inserter ls F G).\nProof.\n  unshelve econstructor.\n  - cbn; intros a b u v f g.\n    exact g.\n  - cbn; intros a b u v.\n    apply isdfunctor0_idmap.\nDefined.\n\n(*\nCoFixpoint iscat0_gendinserter (ls : Stream Laxity)\n           `{IsCat0 m A} `{IsCat1 n B} (F G : A -> B)\n           `{!IsFunctor0 F, !IsFunctor1 F, !IsFunctor0 G, !IsFunctor1 G}\n  : IsDCat0 n (GenDInserter ls F G).\nProof.\n  unshelve econstructor.\n  - intros a b c ta tb tc g f.\n    unfold GenDInserter in ta, tb, tc.\n    cbn; destruct (head ls); cbn; intros p q.\n    all: unfold GenDInserter in p, q.\n    all: unfold GenDInserter.\n    all: destruct (head (tail ls)); cbn in *.\n    all: unfold cat_precomp, cat_postcomp in *.\n    (** Should really be using a library for squares. *)\n    1,4,7:refine (_ $o (_ $<o fmap_comp _ _ _)).\n    1-3:refine (_ $o (cat_assoc _ _ _)^-1$).\n    1-3:refine (((fmap_comp _ _ _)^-1$ $o> _) $o _).\n    1-3:refine ((cat_assoc _ _ _)^-1$ $o _).\n    1-3:refine (_ $o (p $o> _)).\n    1-3:refine ((_ $<o q) $o _).\n    1-3:by apply cat_assoc.\n    1,3,5:refine (_ $oE (_ $<oE fmap_comp _ _ _)).\n    1-3:refine (_ $oE (cat_assoc _ _ _)^-1$).\n    1-3:refine (((fmap_comp _ _ _)^-1$ $o>E _) $oE _).\n    1-3:refine ((cat_assoc _ _ _)^-1$ $oE _).\n    1-3:refine (_ $oE (p $o>E _)).\n    1-3:refine ((_ $<oE q) $oE _).\n    1-3:by apply cat_assoc.\n    all:refine (_ $o (fmap_comp _ _ _ $o> _)).\n    all:refine (_ $o (cat_assoc _ _ _)).\n    all:refine ((_ $<o (fmap_comp _ _ _)^-1$) $o _).\n    all:refine ((cat_assoc _ _ _) $o _).\n    all:refine (_ $o (_ $<o q)).\n    all:refine ((p $o> _) $o _).\n    all:exact (cat_assoc _ _ _)^-1$.\n  - unfold GenDInserter; cbn; intros a ta.\n    destruct (head ls); cbn.\n    all: unfold GenDInserter.\n    all: destruct (head (tail ls)); cbn in *.\n    all: unfold cat_precomp, cat_postcomp in *.\n    1,4,7:refine (_ $o (_ $<o fmap_id _ _)).\n    1-3:refine (((fmap_id _ _)^-1$ $o> _) $o _).\n    1-3:exact ((cat_idl _)^-1$ $o (cat_idr _)).\n    1,3,5:refine (_ $oE (_ $<oE fmap_id _ _)).\n    1-3:refine (((fmap_id _ _)^-1$ $o>E _) $oE _).\n    1-3:exact ((cat_idl _)^-1$ $oE (cat_idr _)).\n    all:refine (_ $o (fmap_id _ _ $o> _)).\n    all:refine ((_ $<o (fmap_id _ _)^-1$) $o _).\n    all:exact ((cat_idr _)^-1$ $o (cat_idl _)).\nAbort.\n*)\n\nNotation DIsoInserter := (GenDInserter all_pseudo).\nNotation DInserter := (GenDInserter one_colax).\n\nDefinition GenInserter (l : Stream Laxity)\n           `{IsGlob m A} `{HasEquivs n B}\n           (F G : A -> B) `{!IsFunctor0 F, !IsFunctor0 G}\n  := sig (GenDInserter l F G).\n\nNotation IsoInserter := (GenInserter all_pseudo).\nNotation Inserter := (GenInserter one_colax).\n\n(** For instance, the category of prespectra (resp. spectra) should be the inserter (resp. isoinserter) of the identity functor of (nat -> pType) over a functor [shift o loops]. *)\n\n\n(** ** Natural transformations *)\n\n(** A natural transformation [F $=> G] is a section of their displayed inserter.  The freedom to choose laxities at all dimensions carries over, although we insist that a transformation always goes from [F] to [G] so that the inserter is colax at the bottom level. *)\n\nDefinition Transformation {A} `{IsGlob n B} (F G : A -> B)\n  := forall a, F a $-> G a.\nNotation \"F $=> G\" := (Transformation F G).\n\nNotation IsGenNatural1 l F G :=\n  (@IsCatSect0 _ _ _ (GenDInserter (scons colax l) F G) _ _).\n\nDefinition isgennat (ls : Stream Laxity) `{IsGlob m A} `{HasEquivs n B}\n      {F : A -> B} `{!IsFunctor0 F} {G : A -> B} `{!IsFunctor0 G}\n      (alpha : F $=> G) {alnat : IsGenNatural1 ls F G alpha}\n      {x y : A} (f : x $-> y)\n  : lHom (head ls) (alpha y $o fmap F f) (fmap G f $o alpha x)\n  := fmapD (B := GenDInserter (scons colax ls) F G) alpha f.\n\nNotation IsNatural1 F G := (IsGenNatural1 all_pseudo F G).\n\nDefinition isnat `{IsGlob m A} `{HasEquivs n B}\n      {F : A -> B} `{!IsFunctor0 F} {G : A -> B} `{!IsFunctor0 G}\n      (alpha : F $=> G) {alnat : IsNatural1 F G alpha}\n      {x y : A} (f : x $-> y)\n  : (alpha y $o fmap F f) $<~> (fmap G f $o alpha x)\n  := isgennat all_pseudo alpha f.\n\nGlobal Instance isgennat_iscolaxnat (ls : Stream Laxity) `{IsGlob m A} `{HasEquivs n B}\n      {F : A -> B} `{!IsFunctor0 F} {G : A -> B} `{!IsFunctor0 G}\n      (alpha : F $=> G)\n      {alnat : IsGenNatural1 (scons colax ls) F G alpha}\n      (x y : A)\n  : IsGenNatural1 ls ((cat_postcomp (F x) (alpha y)) o (fmap' F x y))\n                  ((cat_precomp (G y) (alpha x)) o (fmap' G x y))\n                  (isgennat (scons colax ls) alpha)\n  := iscatsect0_fmapD alpha alnat x y.\n\nGlobal Instance isgennat_ispseudonat (ls : Stream Laxity) `{IsGlob m A} `{HasEquivs n B}\n      {F : A -> B} `{!IsFunctor0 F} {G : A -> B} `{!IsFunctor0 G}\n      (alpha : F $=> G)\n      {alnat : IsGenNatural1 (scons pseudo ls) F G alpha}\n      (x y : A)\n  : IsGenNatural1 ls ((cat_postcomp (F x) (alpha y)) o (fmap' F x y))\n                  ((cat_precomp (G y) (alpha x)) o (fmap' G x y))\n                  (fun f => cate_fun (isgennat (scons pseudo ls) alpha f)).\nProof.\n  (** We have to nudge this from a section of the iso-inserter to a section of the inserter. *)\n  pose (iscatsect0_fmapD alpha alnat x y).\n  exact (iscatsect0_isdfunctor0_compose\n           (colax_pseudo_inserter ls ((cat_postcomp (F x) (alpha y)) o (fmap' F x y))\n                              ((cat_precomp (G y) (alpha x)) o (fmap' G x y)))\n           (@fmapD _ _ _ _ _ _ alpha alnat x y)).\nDefined.\n\nGlobal Instance isgennat_islaxnat (ls : Stream Laxity) `{IsGlob m A} `{HasEquivs n B}\n      {F : A -> B} `{!IsFunctor0 F} {G : A -> B} `{!IsFunctor0 G}\n      (alpha : F $=> G)\n      {alnat : IsGenNatural1 (scons lax ls) F G alpha}\n      (x y : A)\n  : IsGenNatural1 ls ((cat_precomp (G y) (alpha x)) o (fmap' G x y))\n                  ((cat_postcomp (F x) (alpha y)) o (fmap' F x y))\n                  (isgennat (scons lax ls) alpha).\nProof.\n  (** Similarly here, we have to nudge from a section of the lax inserter in one direction to a section of the colax inserter in the other direction. *)\n  pose (iscatsect0_fmapD alpha alnat x y).\n  exact (iscatsect0_isdfunctor0_compose\n           (colax_lax_inserter ls ((cat_precomp (G y) (alpha x)) o (fmap' G x y))\n                                ((cat_postcomp (F x) (alpha y)) o (fmap' F x y)))\n           (@fmapD _ _ _ _ _ _ alpha alnat x y)).\nDefined.\n\n(** If we generalized comma categories (and hence inserters) to act on category-sections rather than just functors, we could in principle iterate this approach to define modifications and higher transfors, analogously to how we iterate [isglob_forall] to define all the higher structure of [Type] and similarly for [pType].  Such a generalization seems to require either that the displayed category is an isofibration, or that we define a more general notion of inserter over a given natural transformation, and either one seems to require 2-coherent categories.  In fact, since the level of coherence seems to go down by one each time we apply a comma construction, we probably wouldn't be able to use this to define a whole oo-category of oo-categories at any fixed coherence level.  *)\n", "meta": {"author": "Alizter", "repo": "WildCat", "sha": "156eb45eda524676271e16bded5b7fb79a271144", "save_path": "github-repos/coq/Alizter-WildCat", "path": "github-repos/coq/Alizter-WildCat/WildCat-156eb45eda524676271e16bded5b7fb79a271144/theories/Transformation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982315512489, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2861149919934692}}
{"text": "Require Import Coq.Lists.List Coq.Setoids.Setoid Coq.Classes.Morphisms.\nRequire Import Coq.omega.Omega.\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.Properties.\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                       | [ |- context[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": "proofskiddie", "repo": "CoqStuff", "sha": "fc8ecdf8045bc835bb10b2e4791f041d82451b5d", "save_path": "github-repos/coq/proofskiddie-CoqStuff", "path": "github-repos/coq/proofskiddie-CoqStuff/CoqStuff-fc8ecdf8045bc835bb10b2e4791f041d82451b5d/idontevnkno/src/Parsers/Refinement/BinOpBrackets/ParenBalancedGrammar.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2861149859870968}}
{"text": "(*Here we give a denotational semantics for Why3, assuming some classical axioms*)\nRequire Import Syntax.\nRequire Import Types.\nRequire Import Typing.\nRequire Import Substitution.\nRequire Import Typechecker. (*We need [typecheck_dec]*)\nRequire Import IndTypes.\nRequire Import Semantics.\nRequire Import Hlist.\nRequire Import Coq.Program.Equality.\nRequire Import Coq.Logic.Eqdep_dec.\nRequire Import Coq.Sorting.Permutation.\nSet Bullet Behavior \"Strict Subproofs\".\n\nFrom Equations Require Import Equations.\n\n(*The axioms we need: excluded middle and definite description*)\nRequire Import Coq.Logic.ClassicalEpsilon.\n(*And for a few lemmas, functional extensionality*)\nRequire Import FunctionalExtensionality.\n\n(*This gives us the following (we give a shorter name)*)\nDefinition all_dec : forall (P : Prop), {P} + {~P} := excluded_middle_informative.\n\nLtac simpl_all_dec_tac :=\n  repeat match goal with |- context[ all_dec ?P ] => destruct (all_dec P); auto end.\n\nLemma all_dec_eq: forall (P Q: Prop),\n  (P <-> Q) ->\n  (@eq bool (proj_sumbool _ _ (all_dec P)) (proj_sumbool _ _ (all_dec Q))).\nProof.\n  intros. simpl_all_dec_tac; exfalso.\n  - apply n. apply H. apply p.\n  - apply n. apply H. apply q.\nQed.\n\nLemma simpl_all_dec (P: Prop):\n   (all_dec P) <-> P.\nProof.\n  split; intros;\n  destruct (all_dec P); auto.\n  inversion H.\nQed.\n\nSection Denot.\n\nContext {sigma: sig} {gamma: context} (gamma_valid: valid_context sigma gamma)\n  (pd: pi_dom) .\n\n(*Representation of terms, formulas, patterns*)\n\nNotation domain := (domain (dom_aux pd)).\nNotation val x :=  (v_subst (v_typevar x)).\nNotation val_typevar := (@val_typevar sigma).\nNotation substi := (substi pd).\n\nDefinition cast_dom_vty {v: val_typevar} \n{v1 v2: vty} (Heq: v1 = v2) (x: domain (val v v1)) : domain (val v v2) :=\n  dom_cast _ (f_equal (val v) Heq) x.\n\n(*First, lemmas for function case - quite nontrivial *)\n\nLemma ty_subst_fun_in: forall params args d (x: typevar),\n  NoDup params ->\n  In x params ->\n  length params = length args ->\n  exists ty, In (x, ty) (combine params args) /\\ ty_subst_fun params args d x = ty.\nProof.\n  intros. generalize dependent args. induction params; simpl; intros; auto.\n  inversion H0.\n  inversion H; subst. destruct args. inversion H1.\n  simpl in H0. destruct H0; subst.\n  - exists v. split. left; auto. destruct (typevar_eq_dec x x); auto. contradiction.\n  - inversion H1. specialize (IHparams H5 H0 args H3). destruct IHparams as [ty [Hin Hty]].\n    exists ty. split. right; auto. destruct (typevar_eq_dec x a); auto.\n    subst. contradiction.\nQed. \n\nLemma ty_subst_fun_notin: forall params args d (x: typevar),\n  ~In x params ->\n  ty_subst_fun params args d x = d.\nProof.\n  intros. revert args. induction params; simpl; intros; auto.\n  destruct args; auto. destruct (typevar_eq_dec x a); auto; subst.\n  exfalso. apply H. left; auto. apply IHparams. intro C. apply H. right; auto.\nQed.\n\n(*A crucial result for the function arguments:\n  Suppose we have a function f<alpha>(tau) : t, where alpha and tau are vectors\n  In a well-typed function application f<mu>(ts), ts_i has type sigma(tau_i), where\n  sigma maps alpha_i -> mu_i. Thus, [[ts_i]]_v has type [[v(sigma(tau_i))]].\n\n  When dealing with valuations, we apply [[f<v(mu)>]] to arguments [[ts_i]]_v,\n  each of which has must have type [[sigma'(tau_i)]], \n  where sigma maps alpha_i -> v(mu_i)\n\n  Thus, we need to show that v(sigma(tau)) = sigma'(tau_i), which we do in the\n  following lemma.\n*)\nLemma funsym_subst_eq: forall (params: list typevar) (args: list vty) (v: typevar -> sort) (ty: vty),\n  NoDup params ->\n  length params = length args ->\n  v_subst v (ty_subst params args ty) =\n  ty_subst_s params (map (v_subst v) args) ty.\nProof.\n  intros. unfold ty_subst_s. unfold ty_subst.\n  apply sort_inj. unfold v_subst; simpl.\n  induction ty; simpl; auto.\n  - destruct (in_dec typevar_eq_dec v0 params).\n     + assert (Hin:=i). \n       apply (ty_subst_fun_in params args vty_int v0 H) in i; auto.\n       destruct i as [ty [Hinty Hty]]. rewrite !Hty.\n       apply (ty_subst_fun_in params (sorts_to_tys\n       (map\n          (fun t : vty =>\n           exist (fun t0 : vty => is_sort t0) (v_subst_aux (fun x : typevar => v x) t) (v_subst_aux_sort v t))\n          args)) vty_int v0 H) in Hin.\n        destruct Hin as [ty' [Hinty' Hty']]; simpl in *.\n        unfold sort. (*annoying type equality thing*) rewrite Hty'.\n        2 : {\n          unfold sorts_to_tys. rewrite !map_length; auto.\n        }\n        unfold sorts_to_tys in Hinty'.\n        rewrite map_map, combine_map2, in_map_iff in Hinty'.\n        destruct Hinty' as [[v1 ty2] [Htup Hinty2]].\n        simpl in Htup. inversion Htup.\n        assert (ty = ty2). {\n          eapply combine_NoDup_l. apply H. apply Hinty. subst; auto. \n        }\n        subst. auto.\n    + rewrite !ty_subst_fun_notin by assumption. auto.\n  - f_equal. apply list_eq_ext'; rewrite !map_length; auto.\n    intros n d Hn. rewrite !map_nth_inbound with (d2:=vty_int); auto.\n    2: rewrite map_length; auto. rewrite Forall_forall in H1. apply H1.\n    apply nth_In. auto.\nQed.\n\nLemma ty_fun_ind_ret {f vs ts ty} (H: term_has_type sigma (Tfun f vs ts) ty):\n  ty = ty_subst (s_params f) vs (f_ret f).\nProof.\n  inversion H; auto.\nQed.\n\n(*We use the above to get the arg list*)\n(*TODO: generalize, don't have type info, have info from inversion*)\n(*TODO: write Fixpoint version?*)\nDefinition get_arg_list (v: val_typevar)\n  (s: fpsym) (vs: list vty) (ts: list term) \n  (reps: forall (t: term) (ty: vty),\n    term_has_type sigma t ty ->\n    domain (val v ty))\n  (Hlents: length ts = length (s_args s))\n  (Hlenvs: length vs = length (s_params s))\n  (Hall: Forall (fun x => term_has_type sigma (fst x) (snd x))\n    (combine ts (map (ty_subst (s_params s) vs) (s_args s)))):\n  arg_list domain\n    (sym_sigma_args s\n      (map (v_subst (v_typevar v)) vs)).\nProof.\n  unfold sym_sigma_args.\n  generalize dependent (s_args s). induction ts; simpl; intros.\n  - assert (l = nil). apply length_zero_iff_nil; auto.\n    rewrite H. simpl. apply HL_nil.\n  - destruct l as [|a1 atl] eqn : Hargs.\n    + discriminate.\n    + simpl in Hlents. simpl in Hall. assert (A:=Hall).\n      apply Forall_inv in Hall. apply Forall_inv_tail in A. simpl.\n      apply HL_cons.\n      * specialize (reps a _ Hall); simpl in reps. \n        rewrite <- funsym_subst_eq; auto. apply s_params_Nodup.\n      * apply IHts; auto.\nDefined.\n\n(*If the reps are equal only for the terms in the list,\n  then the arg_lists are equal, and they are irrelevant\n  in the choice of proof*)\nLemma get_arg_list_ext (v: val_typevar)\n  (s: fpsym) (vs: list vty) (ts1 ts2: list term) \n  (reps1 reps2: forall (t: term) (ty: vty),\n    term_has_type sigma t ty ->\n    domain (val v ty))\n  (Hts: length ts1 = length ts2)\n  (Hreps: forall (i: nat),\n    i < length ts1 ->\n    forall (ty : vty) Hty1 Hty2,\n    reps1 (nth i ts1 tm_d) ty Hty1 = reps2 (nth i ts2 tm_d) ty Hty2)\n  (Hlents1: length ts1 = length (s_args s))\n  (Hlents2: length ts2 = length (s_args s))\n  (Hlenvs1 Hlenvs2: length vs = length (s_params s))\n  (Hall1: Forall (fun x => term_has_type sigma (fst x) (snd x))\n    (combine ts1 (map (ty_subst (s_params s) vs) (s_args s))))\n  (Hall2: Forall (fun x => term_has_type sigma (fst x) (snd x))\n    (combine ts2 (map (ty_subst (s_params s) vs) (s_args s)))):\n  get_arg_list v s vs ts1 reps1 Hlents1 Hlenvs1 Hall1 =\n  get_arg_list v s vs ts2 reps2 Hlents2 Hlenvs2 Hall2.\nProof.\n  unfold get_arg_list. simpl.\n  unfold sym_sigma_args.\n  assert (Hlenvs1 = Hlenvs2). apply UIP_dec. apply Nat.eq_dec.\n  subst.\n  generalize dependent (s_args s).\n  generalize dependent ts2. \n  induction ts1; simpl; intros. \n  - destruct ts2; [|subst; inversion Hts]. simpl.\n    f_equal. f_equal. f_equal. apply nat_eq_refl.\n  - destruct ts2; inversion Hts. simpl.\n    destruct l.\n    + inversion Hlents2.\n    + simpl in Hlenvs2. f_equal.\n      * f_equal.\n        apply (Hreps 0). lia.\n      * apply IHts1; auto.\n        intros j Hj ty Hty1 Hty2.\n        apply (Hreps (S j)); lia.\nQed.\n\n(*A corollary (TODO: change name) when ts are equal*)\nLemma get_arg_list_eq (v: val_typevar)\n(s: fpsym) (vs: list vty) (ts: list term) \n(reps1 reps2: forall (t: term) (ty: vty),\n  term_has_type sigma t ty ->\n  domain (val v ty))\n(Hreps: Forall\n(fun tm : term =>\n forall (ty : vty) (Hty1 Hty2: term_has_type sigma tm ty),\n reps1 tm ty Hty1 = reps2 tm ty Hty2) ts)\n(Hlents1 Hlents2: length ts = length (s_args s))\n(Hlenvs1 Hlenvs2: length vs = length (s_params s))\n(Hall1 Hall2: Forall (fun x => term_has_type sigma (fst x) (snd x))\n  (combine ts (map (ty_subst (s_params s) vs) (s_args s)))):\nget_arg_list v s vs ts reps1 Hlents1 Hlenvs1 Hall1 =\nget_arg_list v s vs ts reps2 Hlents2 Hlenvs2 Hall2.\nProof.\n  apply get_arg_list_ext; auto.\n  intros i Hi ty H1 H2.\n  rewrite Forall_forall in Hreps; apply Hreps.\n  apply nth_In; auto.\nQed.\n\n(*The function version*)\n\nLemma fun_ty_inv {s} {f: funsym} \n  {vs: list vty} {tms: list term} {ty_ret}:\n  term_has_type s (Tfun f vs tms) ty_ret ->\n  length tms = length (s_args f) /\\\n  length vs = length (s_params f) /\\\n  Forall (fun x => term_has_type s (fst x) (snd x)) \n    (combine tms (map (ty_subst (s_params f) vs) (s_args f))) /\\\n  ty_ret = ty_subst (s_params f) vs (f_ret f).\nProof.\n  intros. inversion H; subst; auto.\nQed.\n\nDefinition fun_arg_list {ty} (v: val_typevar)\n(f: funsym) (vs: list vty) (ts: list term) \n(reps: forall (t: term) (ty: vty),\n  term_has_type sigma t ty ->\n  domain (val v ty))\n(Hty: term_has_type sigma (Tfun f vs ts) ty):\narg_list domain\n  (sym_sigma_args f\n    (map (v_subst (v_typevar v)) vs)) :=\nget_arg_list v f vs ts reps (proj1 (fun_ty_inv Hty))\n  (proj1 (proj2 (fun_ty_inv Hty)))\n  (proj1 (proj2 (proj2 (fun_ty_inv Hty)))).\n\n(*The predsym version*)\n\nLemma pred_val_inv {s} {p: predsym} \n  {vs: list vty} {tms: list term}:\n  valid_formula s (Fpred p vs tms) ->\n  length tms = length (s_args p) /\\\n  length vs = length (s_params p) /\\\n  Forall (fun x => term_has_type s (fst x) (snd x)) \n    (combine tms (map (ty_subst (s_params p) vs) (s_args p))).\nProof.\n  intros. inversion H; subst; auto.\nQed.\n\nDefinition pred_arg_list (v: val_typevar)\n(p: predsym) (vs: list vty) (ts: list term) \n(reps: forall (t: term) (ty: vty),\n  term_has_type sigma t ty ->\n  domain (val v ty))\n(Hval: valid_formula sigma (Fpred p vs ts)):\narg_list domain\n  (sym_sigma_args p\n    (map (v_subst (v_typevar v)) vs)) :=\nget_arg_list v p vs ts reps (proj1 (pred_val_inv Hval))\n  (proj1 (proj2 (pred_val_inv Hval)))\n  (proj2 (proj2 (pred_val_inv Hval))).\n\n(*Inversion lemmas we use in the semantics to \n  destruct and reconstruct typing proofs*)\n\nLemma tfun_params_length {s f vs ts ty}:\n  term_has_type s (Tfun f vs ts) ty ->\n  length (s_params f) = length vs.\nProof.\n  intros. inversion H; subst. rewrite H9. reflexivity.\nQed.\n\nLemma fpred_params_length {s p vs ts}:\n  valid_formula s (Fpred p vs ts) ->\n  length (s_params p) = length vs.\nProof.\n  intros. inversion H; subst. auto.\nQed.\n\nLemma ty_constint_inv {s z ty} (H: term_has_type s (Tconst (ConstInt z)) ty) :\n  ty = vty_int.\nProof.\n  inversion H; auto.\nQed.\n\nLemma ty_constreal_inv {s r ty} (H: term_has_type s (Tconst (ConstReal r)) ty) :\nty = vty_real.\nProof.\ninversion H; auto.\nQed.\n\nLemma ty_var_inv {s x ty} (H: term_has_type s (Tvar x) ty):\nty = snd x .\nProof.\n  inversion H; auto.\nQed.\n\nLemma ty_let_inv {s t1 x t2 ty} (H: term_has_type s (Tlet t1 x t2) ty):\nterm_has_type s t1 (snd x) /\\ term_has_type s t2 ty.\nProof.\n  inversion H; auto.\nQed.\n\nLemma ty_if_inv {s f t1 t2 ty} (H: term_has_type s (Tif f t1 t2) ty):\nterm_has_type s t1 ty /\\\nterm_has_type s t2 ty /\\\nvalid_formula s f.\nProof.\n  inversion H; auto.\nQed.\n\nLemma ty_match_inv {s t ty1 ty2 xs} (H: term_has_type s (Tmatch t ty1 xs) ty2):\n  term_has_type s t ty1 /\\\n  Forall (fun x => pattern_has_type s (fst x) ty1) xs /\\\n  Forall (fun x : pattern * term => term_has_type s (snd x) ty2) xs.\nProof.\n  inversion H; subst; split; auto; split; \n  rewrite Forall_forall; auto.\nQed.\n\nLemma ty_eps_inv {s f x ty'} (H: term_has_type s (Teps f x) ty'):\n  valid_formula s f /\\ ty' = snd x.\nProof.\n  inversion H; subst; auto.\nQed.\n\nLemma valid_not_inj {s f} (H: valid_formula s (Fnot f)):\n  valid_formula s f.\nProof.\n  inversion H; auto.\nQed.\n\nLemma valid_let_inj {s t x f} (H: valid_formula s (Flet t x f)):\nterm_has_type s t (snd x) /\\\nvalid_formula s f.\nProof.\n  inversion H; auto.\nQed.\n\nLemma valid_binop_inj {s b f1 f2} (H: valid_formula s (Fbinop b f1 f2)):\nvalid_formula s f1 /\\\nvalid_formula s f2.\nProof.\n  inversion H; auto.\nQed.\n\nLemma valid_if_inj {s f1 f2 f3} (H: valid_formula s (Fif f1 f2 f3)):\nvalid_formula s f1 /\\\nvalid_formula s f2 /\\\nvalid_formula s f3.\nProof.\n  inversion H; auto.\nQed.\n\nLemma valid_quant_inj {s q x f} (H: valid_formula s (Fquant q x f)):\n  valid_formula s f.\nProof.\n  inversion H; auto.\nQed.\n\nLemma valid_match_inv {s t ty1 xs} (H: valid_formula s (Fmatch t ty1 xs)):\n  term_has_type s t ty1 /\\\n  Forall (fun x => pattern_has_type s (fst x) ty1) xs /\\\n  Forall (fun x : pattern * formula => valid_formula s (snd x)) xs.\nProof.\n  inversion H; subst; split; auto.\nQed.\n\nLemma valid_eq_inj {s ty t1 t2} (H: valid_formula s (Feq ty t1 t2)):\n  term_has_type s t1 ty /\\ term_has_type s t2 ty.\nProof.\n  inversion H; auto.\nQed.\n\n(*We assume that all ADTs are uniform*)\nVariable all_unif: forall m,\n  mut_in_ctx m gamma ->\n  uniform m.\n\n(*Getting ADT instances*)\nSection GetADT.\n(*For pattern matches, we need to look at an element of\n  type dom(s), determine if s is an ADT type, and if so,\n  extract the components (constructor and args). We need\n  a lot of machinery to do this; we do this here.*)\n\nDefinition find_ts_in_mut (ts: typesym) (m: mut_adt) : option alg_datatype :=\n  find (fun a => typesym_eq_dec ts (adt_name a)) (typs m).\n\n(*TODO: move*)\nLemma find_none_iff {A: Type} (f: A -> bool) (l: list A):\n  find f l = None <-> forall x, In x l -> f x = false.\nProof.\n  split. apply find_none.\n  induction l; simpl; intros; auto.\n  destruct (f a) eqn : Ha; auto.\n  rewrite H in Ha; auto. inversion Ha.\nQed.\n\nLemma find_ts_in_mut_none: forall ts m,\n  find_ts_in_mut ts m = None <->\n  forall a, adt_in_mut a m -> adt_name a <> ts.\nProof.\n  intros. unfold find_ts_in_mut.\n  rewrite find_none_iff.\n  split; intros Hall x Hin.\n  - intro C; subst.\n    apply in_bool_In in Hin.\n    specialize (Hall _ Hin). simpl_sumbool. contradiction.\n  - apply (In_in_bool adt_dec) in Hin.\n    specialize (Hall _ Hin).\n    destruct (typesym_eq_dec ts (adt_name x)); auto; subst;\n    contradiction.\nQed.\n\nLemma find_ts_in_mut_some: forall ts m a,\n  find_ts_in_mut ts m = Some a ->\n  adt_in_mut a m /\\ adt_name a = ts.\nProof.\n  intros ts m a Hf. apply find_some in Hf.\n  destruct Hf as [Hin Heq].\n  split; auto. apply In_in_bool; auto.\n  simpl_sumbool.\nQed.\n\nLemma find_ts_in_mut_iff: forall ts m a,\n  NoDup (map adt_name (typs m)) ->\n  (find_ts_in_mut ts m = Some a) <-> (adt_in_mut a m /\\ adt_name a = ts).\nProof.\n  intros. eapply iff_trans. apply find_some_nodup.\n  - intros. repeat simpl_sumbool.\n    apply (NoDup_map_in H); auto.\n  - simpl. unfold adt_in_mut. split; intros [Hin Hname];\n    repeat simpl_sumbool; split; auto; try simpl_sumbool;\n    apply (reflect_iff _ _ (in_bool_spec adt_dec a (typs m))); auto.\nQed.\n\nDefinition find_ts_in_ctx (ts: typesym) : option (mut_adt * alg_datatype) :=\n  fold_right (fun m acc => \n    match (find_ts_in_mut ts m) with\n    | Some a => Some (m, a)\n    | None => acc\n    end) None (mut_of_context gamma).\n\nLemma no_adt_name_dups:\n  NoDup (map adt_name (concat (map typs (mut_of_context gamma)))).\nProof.\n  assert (forall g, \n    (map adt_name (concat (map typs (mut_of_context g)))) =\n  typesyms_of_context g). {\n    induction g; unfold typesyms_of_context in *; simpl; auto.\n    unfold datatypes_of_context in *.\n    destruct a; simpl; auto.\n    rewrite !map_app, IHg. f_equal.\n    rewrite map_map.\n    apply map_ext. intros a. destruct a; reflexivity.\n  }\n  rewrite H. apply gamma_valid.\nQed.\n\n(*The real spec we want: *)\nLemma find_ts_in_ctx_iff: forall ts m a,\n  (find_ts_in_ctx ts = Some (m, a) <-> mut_in_ctx m gamma /\\\n    adt_in_mut a m /\\ adt_name a = ts).\nProof.\n  intros. unfold find_ts_in_ctx. rewrite mut_in_ctx_eq.\n  assert (forall m, In m (mut_of_context gamma) ->\n    NoDup (map adt_name (typs m))). {\n      intros m'. rewrite <- mut_in_ctx_eq.\n      eapply adts_names_nodups. apply gamma_valid.\n    }\n  assert (Hnodup:=no_adt_name_dups).\n  induction (mut_of_context gamma); simpl; intros; split; intros; auto.\n  - inversion H0.\n  - destruct H0 as [[] _].\n  - destruct (find_ts_in_mut ts a0) eqn : Hmut.\n    + inversion H0; subst. apply find_ts_in_mut_iff in Hmut. destruct Hmut.\n      repeat split; auto.\n      apply H. left; auto.\n    + apply IHl in H0. destruct H0 as [Hin [Ha Hn]]. repeat split; auto.\n      intros. apply H. right; auto.\n      simpl in Hnodup. rewrite map_app in Hnodup. apply NoDup_app in Hnodup.\n      apply Hnodup.\n  - destruct H0 as [[Ham | Hinm] [Ha Hn]]; subst.\n    + assert (find_ts_in_mut (adt_name a) m = Some a). {\n        apply find_ts_in_mut_iff. apply H. left; auto. split; auto.\n      }\n      rewrite H0. reflexivity.\n    + simpl in Hnodup. rewrite map_app in Hnodup.\n      rewrite NoDup_app_iff in Hnodup.\n      destruct (find_ts_in_mut (adt_name a) a0 ) eqn : Hf.\n      * apply find_ts_in_mut_iff in Hf. 2: apply H; simpl; auto.\n        destruct Hf.\n        destruct Hnodup as [Hn1 [Hn2 [Hi1 Hi2]]].\n        exfalso. apply (Hi1 (adt_name a1)). rewrite in_map_iff.\n        exists a1. split; auto. apply (in_bool_In _ _ _ H0).\n        rewrite H1.\n        rewrite in_map_iff. exists a. split; auto.\n        rewrite in_concat. exists (typs m). split; auto.\n        rewrite in_map_iff. exists m; split; auto.\n        (*TODO: automate this or at least fix lemma w args*)\n        apply (in_bool_In _ _ _ Ha).\n      * apply IHl; auto.\n        intros. apply H. right; auto.\n        apply Hnodup.\nQed.\n\nDefinition is_sort_cons_sorts (*(ts: typesym)*) (l: list vty) \n  (Hall: forall x, In x l -> is_sort x):\n  {s: list sort | sorts_to_tys s = l}.\nProof.\n  induction l.\n  - apply (exist _ nil). reflexivity.\n  - simpl in Hall.\n    assert (is_sort a). apply Hall. left; auto.\n    assert (forall x : vty, In x l -> is_sort x). {\n      intros. apply Hall; right; auto.\n    }\n    specialize (IHl H0). destruct IHl as [tl Htl].\n    apply (exist _ ((exist _ a H) :: tl)).\n    simpl. rewrite Htl. reflexivity.\nDefined.\n\nLemma is_sort_cons_sorts_eq (l: list sort)\n  (Hall: forall x, In x (sorts_to_tys l) -> is_sort x):\n  proj1_sig (is_sort_cons_sorts (sorts_to_tys l) Hall) = l.\nProof.\n  induction l; simpl; auto.\n  destruct (is_sort_cons_sorts (sorts_to_tys l)\n  (fun (x : vty) (H0 : In x (sorts_to_tys l)) => Hall x (or_intror H0))) eqn : ind;\n  simpl.\n  apply (f_equal (@proj1_sig _ _)) in ind.\n  simpl in ind.\n  rewrite IHl in ind. subst. f_equal.\n  destruct a; simpl. \n  f_equal. apply bool_irrelevance.\nQed.\n\n(*A function that tells us if a sort is an ADT and if so,\n  get its info*)\nDefinition is_sort_adt (s: sort) : \n  option (mut_adt * alg_datatype * typesym * list sort).\nProof.\n  destruct s.\n  destruct x.\n  - exact None.\n  - exact None.\n  - exact None.\n  - destruct (find_ts_in_ctx t);[|exact None].\n    exact (Some (fst p, snd p, t, \n      proj1_sig (is_sort_cons_sorts l (is_sort_cons t l i)))).\nDefined.\n\n(*And its proof of correctness*)\nLemma is_sort_adt_spec: forall s m a ts srts,\n  is_sort_adt s = Some (m, a, ts, srts) ->\n  s = typesym_to_sort (adt_name a) srts /\\\n  adt_in_mut a m /\\ mut_in_ctx m gamma /\\ ts = adt_name a.\nProof.\n  intros. unfold is_sort_adt in H.\n  destruct s. destruct x; try solve[inversion H].\n  destruct (find_ts_in_ctx t) eqn : Hf.\n  - inversion H; subst. destruct p as [m a]. simpl.\n    apply find_ts_in_ctx_iff in Hf. destruct Hf as [Hmg [Ham Hat]]; \n    repeat split; auto; subst.\n    apply sort_inj. simpl. f_equal. clear H. \n    generalize dependent (is_sort_cons (adt_name a) l i).\n    intros H.\n    destruct (is_sort_cons_sorts l H). simpl.\n    rewrite <- e; reflexivity.\n  - inversion H.\nQed.\n\n(*A few other things we need for pattern matching:*)\n\n(*Suppose that type is valid and we have valuation, \n  then val v ty is valid*)\nLemma val_valid: forall (v: val_typevar) (ty: vty),\n  valid_type sigma ty ->\n  valid_type sigma (val v ty).\nProof.\n  intros. unfold val. simpl.\n  apply valid_type_v_subst; auto.\n  intros x.\n  destruct v; simpl. apply v_typevar_val.\nQed. \n\n(*We need info about lengths and validity of the srts list*)\nLemma adt_srts_valid: forall {v: val_typevar}  {ty m a ts srts},\n  is_sort_adt (val v ty) = Some (m, a, ts, srts) ->\n  valid_type sigma ty ->\n  valid_type sigma (typesym_to_sort (adt_name a) srts).\nProof.\n  intros v ty m a ts srts H.\n  apply is_sort_adt_spec in H.\n  destruct H as [Hts [a_in [m_in _]]].\n  intros Hval.\n  rewrite <- Hts. apply val_valid. assumption.\nQed.\n\n(*We need to know something about the lengths*)\nLemma adt_srts_length_eq: forall {v: val_typevar} {ty m a ts srts},\n  is_sort_adt (val v ty) = Some (m, a, ts, srts) ->\n  valid_type sigma ty ->\n  length srts = length (m_params m).\nProof.\n  intros v ty m a ts srts H Hval.\n  pose proof (Hval':=adt_srts_valid H Hval).\n  apply is_sort_adt_spec in H.\n  destruct H as [Hts [a_in [m_in _]]].\n  unfold typesym_to_sort in Hval'. \n  simpl in Hval'; inversion Hval'; subst.\n  rewrite map_length in H3. rewrite H3.\n  f_equal. apply (adt_args gamma_valid). split; auto.\nQed.\n\nLemma val_sort_eq: forall (v: val_typevar) (s: sort),\n  s = val v s.\nProof.\n  intros. apply subst_sort_eq.\nQed.\n\n(*Need to know that all sorts are valid types*)\nLemma adts_srts_valid: forall {v : val_typevar} {ty m a ts srts c},\n  is_sort_adt (val v ty) = Some (m, a, ts, srts) ->\n  valid_type sigma ty ->\n  constr_in_adt c a ->\n  Forall (valid_type sigma) (sorts_to_tys (sym_sigma_args c srts)).\nProof.\n  intros v ty m a ts srts c H Hval c_in.\n  pose proof (Hval':=adt_srts_valid H Hval).\n  pose proof (Hlen:=adt_srts_length_eq H Hval).\n  apply is_sort_adt_spec in H.\n  destruct H as [Hts [a_in [m_in _]]].\n  rewrite Forall_forall; intros t.\n  unfold sorts_to_tys. rewrite in_map_iff; intros [srt [Hsrt Hinsrt]]; subst.\n  unfold sym_sigma_args in Hinsrt.\n  unfold ty_subst_list_s in Hinsrt.\n  rewrite in_map_iff in Hinsrt.\n  destruct Hinsrt as [t [Ht Hint]]; subst.\n  unfold ty_subst_s. apply valid_type_v_subst.\n  - apply (constr_ret_valid gamma_valid m_in a_in c_in). apply Hint.\n  - intros. apply make_val_valid_type.\n    + rewrite Hlen. f_equal.\n      apply (adt_constr_params gamma_valid m_in a_in c_in).\n    + intros s Hsin. simpl in Hval'. inversion Hval'; subst.\n      apply H4. rewrite in_map_iff. exists s. split; auto.\nQed.\n\nEnd GetADT.\n\n(*Pattern matches are quite complicated. Rather than compiling down\n  to elementary let statements, as in the paper, we instead build up\n  the entire valuation (consisting of pairs of vsymbols and domain\n  elements for an appropriate type). Doing this is conceptually simple,\n  but very difficult in practice due to depenedent type obligations.\n  \n  The interesting case is the case when we match against a constructor.\n  In this case, we determine if the type is an instance of and ADT, \n  and if so, we use [find_constr_rep] (after some casting) to get \n  the constructor and arguments (arg_list) that comprise this instance.\n  Then, we check if the constructor equals the one in the pattern match,\n  and if so, we iterate through the arg_list and build up the valuation\n  entries recursively, returning None if we ever find a non-matching pattern.\n  \n  We need many of the above lemmas to handle the preconditions for\n  [find_constr_rep] and casting.\n  *)\n\nLemma pat_var_inv {s x ty}:\n  pattern_has_type s (Pvar x) ty ->\n  snd x = ty.\nProof.\n  intros. inversion H; subst; auto.\nQed.\n\nLemma pat_or_inv {s p1 p2 ty}:\n  pattern_has_type s (Por p1 p2) ty ->\n  pattern_has_type s p1 ty /\\ pattern_has_type s p2 ty.\nProof.\n  intros. inversion H; subst. auto.\nQed.\n\nLemma pat_bind_inv {s p x ty}:\n  pattern_has_type s (Pbind p x) ty ->\n  pattern_has_type s p ty /\\ ty = snd x.\nProof.\n  intros. inversion H; subst. auto.\nQed.\n\n(*TODO: put this as condition in overall maybe\nproblem is - inner patterns need NOT be adts - this is not\npreserved throughout - maybe dont have this, just prove\n  \"matches\"*)\nDefinition is_vty_adt (ty: vty) : \n  option (mut_adt * alg_datatype * list vty) :=\n  match ty with\n  | vty_cons ts tys =>\n    match (find_ts_in_ctx ts) with\n    | Some (m, a) => Some (m, a, tys)\n    | None => None\n    end\n  | _ => None\n  end.\n\nLemma is_vty_adt_iff {ty: vty} {m a vs}:\n  is_vty_adt ty = Some (m, a, vs) <->\n  ty = vty_cons (adt_name a) vs /\\\n  adt_in_mut a m /\\\n  mut_in_ctx m gamma.\nProof.\n  unfold is_vty_adt. split.\n  - destruct ty; intro C; inversion C.\n    destruct (find_ts_in_ctx t) eqn : Hts; inversion H0; subst.\n    destruct p. inversion C; subst.\n    apply find_ts_in_ctx_iff in Hts. destruct_all; subst; auto.\n  - intros. destruct_all; subst; simpl.\n    assert (find_ts_in_ctx (adt_name a) = Some (m, a)). {\n      apply find_ts_in_ctx_iff. split; auto.\n    }\n    rewrite H. reflexivity.\nQed.\n\nLemma is_vty_adt_spec {ty: vty} {m a vs}:\n  is_vty_adt ty = Some (m, a, vs) ->\n  ty = vty_cons (adt_name a) vs /\\\n  adt_in_mut a m /\\\n  mut_in_ctx m gamma.\nProof.\n  apply is_vty_adt_iff.\nQed.\n\nLemma adt_vty_length_eq: forall {ty m a vs},\n  is_vty_adt ty = Some (m, a, vs) ->\n  valid_type sigma ty ->\n  length vs = length (m_params m).\nProof.\n  intros ty m a vs H Hval.\n  apply is_vty_adt_spec in H. destruct_all; subst.\n  inversion Hval; subst. rewrite H5.\n  f_equal. apply (adt_args gamma_valid). split; auto.\nQed.\n\n\n(*TOOD: move*)\nLemma v_subst_cons {f} ts vs:\n  v_subst f (vty_cons ts vs) =\n  typesym_to_sort ts (map (v_subst f) vs).\nProof.\n  apply sort_inj. simpl.\n  f_equal. apply list_eq_ext'; rewrite !map_length; auto.\n  intros n d Hn.\n  rewrite !map_nth_inbound with (d2:=s_int); [|rewrite map_length; auto].\n  rewrite !map_nth_inbound with (d2:=vty_int); auto.\nQed.\n\n(*Typecast we need for inner arg list*)\nLemma sym_sigma_args_map (v: val_typevar) (f: funsym) \n  (vs: list vty):\n  length (s_params f) = length vs ->\n  sym_sigma_args f (map (val v) vs) =\n  map (val v) (ty_subst_list (s_params f) vs (s_args f)).\nProof.\n  intros Hlen.\n  unfold sym_sigma_args, ty_subst_list_s, ty_subst_list.\n  apply list_eq_ext'; rewrite !map_length; auto.\n  intros n d Hn.\n  rewrite !map_nth_inbound with (d2:=vty_int); auto;\n  [|rewrite map_length]; auto.\n  symmetry. apply funsym_subst_eq; auto.\n  apply s_params_Nodup.\nQed.\n\nLemma constr_length_eq: forall {ty m a vs c},\n  is_vty_adt ty = Some (m, a, vs) ->\n  valid_type sigma ty ->\n  constr_in_adt c a ->\n  length (s_params c) = length vs.\nProof.\n  intros.\n  rewrite (adt_vty_length_eq H H0).\n  f_equal.\n  apply is_vty_adt_spec in H. destruct_all; subst.\n  apply (adt_constr_params gamma_valid H3 H2 H1).\nQed.\n\n(*TODO: move*)\nLemma ty_subst_cons (vars: list typevar) (params: list vty)\n  (ts: typesym) (vs: list vty):\n  ty_subst vars params (vty_cons ts vs) =\n  vty_cons ts (map (ty_subst vars params) vs).\nProof.\n  reflexivity.\nQed.\n\n(*TODO: assume it is adt, prove that params = ps*)\n\n(*TODO: maybe move*)\nLemma adt_constr_subst_ret {params a m f}:\n  mut_in_ctx m gamma ->\n  adt_in_mut a m ->\n  constr_in_adt f a ->\n  length params = length (s_params f) ->\n  ty_subst (s_params f) params (f_ret f) = vty_cons (adt_name a) params.\nProof.\n  intros m_in a_in c_in Hlen.\n  rewrite (adt_constr_ret gamma_valid m_in a_in c_in).\n  rewrite (adt_constr_params gamma_valid m_in a_in c_in) in Hlen |- *.\n  unfold ty_subst. simpl. f_equal.\n  apply list_eq_ext'; rewrite !map_length; auto.\n  intros n d Hn.\n  rewrite map_nth_inbound with (d2:=vty_int); [|rewrite map_length; auto].\n  rewrite (map_nth_inbound) with (d2:=EmptyString); auto.\n  simpl.\n  rewrite ty_subst_fun_nth with(s:=d); auto.\n  rewrite <- (adt_constr_params gamma_valid m_in a_in c_in).\n  apply s_params_Nodup.\nQed.\n\nLemma pat_constr_ind {s params ps vs f1 f2 m a}:\n  pattern_has_type s (Pconstr f1 params ps) (vty_cons (adt_name a) vs) ->\n  mut_in_ctx m gamma ->\n  adt_in_mut a m ->\n  f1 = f2 ->\n  constr_in_adt f2 a ->\n  Forall (fun x => pattern_has_type s (fst x) (snd x))\n    (combine ps (ty_subst_list (s_params f2) vs (s_args f2))).\nProof.\n  intros. subst.\n  inversion H; subst.\n  subst sigma0.\n  rewrite (adt_constr_subst_ret H0 H1 H3) in H6; auto.\n  inversion H6; subst.\n  rewrite Forall_forall.\n  intros. apply H13.\n  apply H2. \nQed.\n\nDefinition cast_prop {A: Set} (P: A -> Prop) {a1 a2: A} (H: a1 = a2)\n  (Hp: P a1) : P a2 :=\n  match H with\n  |eq_refl => Hp\n  end.\n\nDefinition pat_has_type_eq {s p ty1 ty2} (H: ty1 = ty2) \n  (Hp: pattern_has_type s p ty1):\n  pattern_has_type s p ty2 :=\n  cast_prop (pattern_has_type s p) H Hp.\n\nDefinition cast_bool {A: Set} (P: A -> bool) {a1 a2: A} (H: a1 = a2)\n  (Hp: P a1) : P a2 :=\n  cast_prop P H Hp.\n\n (*A computable version - why is standard version not computable?*)\nDefinition proj1' {A B: Prop} (H: A /\\ B) : A :=\n  match H with\n  | conj x x0 => x\n  end.\n\nDefinition proj2' {A B: Prop} (H: A /\\ B) : B :=\n  match H with\n  | conj x x0 => x0\n  end.\n\n(*Updated version: relies on well-typedness\n  and matches on ty for constr case, NOT (val ty), which\n  removes useful information*)\nFixpoint match_val_single (v: val_typevar) (ty: vty)\n  (p: pattern) \n  (Hp: pattern_has_type sigma p ty)\n  (d: domain (val v ty))\n  {struct p} : \n  (*For a pair (x, d), we just need that there is SOME type t such that\n    d has type [domain (val v t)], but we don't care what t is.\n    We prove later that it matches (snd x)*)\n  option (list (vsymbol * {s: sort & domain s })) :=\n  match p as p' return pattern_has_type sigma p' ty -> \n    option (list (vsymbol * {s: sort & domain s })) with\n  | Pvar x => fun Hty' =>\n    (*Here, it is safe to always give Some*)\n    Some [(x, (existT _ (val v ty) d))]\n    (*TODO: really do want to show that None is never reached*)\n    (*if (vty_eq_dec (snd x) ty) then\n    Some [(x, (existT _ ty d))] else None*)\n  | Pwild => fun _ => Some nil\n  | Por p1 p2 => fun Hty' =>\n    match (match_val_single v ty p1 (proj1' (pat_or_inv Hty')) d) with\n                  | Some v1 => Some v1\n                  | None => match_val_single v ty p2 \n                    (proj2' (pat_or_inv Hty')) d\n                  end\n  | Pbind p1 x => fun Hty' =>\n    (*Binding adds an additional binding at the end for the whole\n      pattern*)\n    match (match_val_single v ty p1 (proj1' (pat_bind_inv Hty')) d) with\n    | None => None\n    | Some l => Some ((x, (existT _ (val v ty) d)) :: l)\n      (*if (vty_eq_dec (snd x) ty) then \n       Some ((x, (existT _ ty d)) :: l) else None*)\n    end\n  | Pconstr f params ps => fun Hty' =>\n    (*Let's try this differently*)\n    (*TODO: want to know that this type is adt - have assumption,\n      will be part of typing*)\n    match (is_vty_adt ty) as o return\n      is_vty_adt ty = o ->\n      option (list (vsymbol * {s: sort & domain s })) \n    with\n    | Some (m, a, vs) => (*TODO*) fun Hisadt => \n      (*Get info from [is_vty_adt_spec]*)\n      let Htyeq : ty = vty_cons (adt_name a) vs :=\n        proj1' (is_vty_adt_spec Hisadt) in\n      let a_in : adt_in_mut a m :=\n        proj1' (proj2' (is_vty_adt_spec Hisadt)) in\n      let m_in : mut_in_ctx m gamma :=\n        proj2' (proj2' (is_vty_adt_spec Hisadt)) in\n\n      let srts := (map (val v) vs) in\n\n      let valeq : val v ty = typesym_to_sort (adt_name a) srts :=\n        eq_trans (f_equal (val v) Htyeq)\n          (v_subst_cons (adt_name a) vs) in\n\n      (*We cast to get an ADT, now that we know that this actually is\n          an ADT*)\n      let adt : adt_rep m srts (dom_aux pd) a a_in :=\n        scast (adts pd m srts a a_in) (dom_cast _ \n          valeq d) in\n\n      (*Need a lemma about lengths for [find_constr_rep]*)\n      let lengths_eq : length srts = length (m_params m) := \n        eq_trans (map_length _ _)\n          (adt_vty_length_eq Hisadt \n          (pat_has_type_valid gamma_valid _ _ Hty')) in\n\n      (*The key part: get the constructor c and arg_list a\n          such that d = [[c(a)]]*)\n      let Hrep := find_constr_rep gamma_valid m m_in srts lengths_eq \n        (dom_aux pd) a a_in (adts pd m srts) \n        (all_unif m m_in) adt in\n\n      (*The different parts of Hrep we need*)\n      let c : funsym := projT1 Hrep in\n      let c_in : constr_in_adt c a :=\n        fst (proj1_sig (projT2 Hrep)) in\n      let args : arg_list domain (sym_sigma_args c srts) := \n        snd (proj1_sig (projT2 Hrep)) in\n\n      let lengths_eq' : length (s_params c) = length vs :=\n        (constr_length_eq Hisadt \n        (pat_has_type_valid gamma_valid _ _ Hty') c_in) in\n      (*If the constructors match, check all arguments,\n        otherwise, gives None*)\n      (*We need proof of equality*)\n      match funsym_eq_dec c f with\n      | left Heq =>\n        (*Idea: iterate over arg list, build up valuation, return None\n        if we every see None*)\n        (*This function is actually quite simple, we just need a bit\n        of dependent pattern matching for the [arg_list]*)\n        let fix iter_arg_list (tys: list vty)\n          (a: arg_list domain (map (val v) tys))\n          (pats: list pattern)\n          (Hall: Forall (fun x => pattern_has_type sigma (fst x) (snd x)) \n            (combine pats tys))\n          {struct pats} :\n          option (list (vsymbol * {s: sort & domain s })) :=\n          match tys as t' return arg_list domain (map (val v) t') ->\n            forall (pats: list pattern)\n            (Hall: Forall (fun x => pattern_has_type sigma (fst x) (snd x)) \n              (combine pats t')),\n            option (list (vsymbol * {s: sort & domain s }))\n          with \n          | nil => fun _ pats _ =>\n            (*matches only if lengths are the same*)\n            match pats with\n            | nil => Some nil\n            | _ => None\n            end\n          | ty :: tl => fun a' ps' Hall' =>\n            match ps' as pats return \n              Forall (fun x => pattern_has_type sigma (fst x) (snd x)) \n                (combine pats (ty :: tl) ) ->\n              option (list (vsymbol * {s: sort & domain s }))\n            with \n            | nil => fun _ => None\n            | phd :: ptl => fun Hall' =>\n              (*We try to evaluate the head against the first pattern.\n                If this succeeds we combine with tail, if either fails\n                we give None*)\n              (*Since ty is a sort, val v ty = ty, therefore we can cast*)\n              match (match_val_single v ty phd (Forall_inv Hall') \n                (hlist_hd a')) with\n              | None => None\n              | Some l =>\n                match iter_arg_list tl (hlist_tl a') ptl\n                  (Forall_inv_tail Hall') with\n                | None => None\n                | Some l' => Some (l ++ l')\n                end\n              end\n            end Hall'\n          end a pats Hall\n        in\n\n        let c_in': constr_in_adt f a :=\n          cast_prop (fun x => constr_in_adt x a) Heq c_in in\n\n        iter_arg_list _ (cast_arg_list \n          (sym_sigma_args_map v c vs lengths_eq') args) ps\n          (pat_constr_ind (pat_has_type_eq Htyeq Hty') m_in a_in \n            (eq_sym Heq) c_in)\n\n      | right Hneq => None\n      end\n\n    (*Has to be ADT, will rule out later*)\n    | None => fun _ => None\n    end eq_refl\n  end Hp.\n\n(*Rewrite version*)\nFixpoint iter_arg_list {v: val_typevar} (tys: list vty)\n  (a: arg_list domain (map (val v) tys))\n  (pats: list pattern)\n  (Hall: Forall (fun x => pattern_has_type sigma (fst x) (snd x)) \n    (combine pats tys))\n  {struct pats} :\n  option (list (vsymbol * {s: sort & domain s })) :=\n  match tys as t' return arg_list domain (map (val v) t') ->\n    forall (pats: list pattern)\n    (Hall: Forall (fun x => pattern_has_type sigma (fst x) (snd x)) \n      (combine pats t')),\n    option (list (vsymbol * {s: sort & domain s }))\n  with \n  | nil => fun _ pats _ =>\n    (*matches only if lengths are the same*)\n    match pats with\n    | nil => Some nil\n    | _ => None\n    end\n  | ty :: tl => fun a' ps' Hall' =>\n    match ps' as pats return \n      Forall (fun x => pattern_has_type sigma (fst x) (snd x)) \n        (combine pats (ty :: tl) ) ->\n      option (list (vsymbol * {s: sort & domain s }))\n    with \n    | nil => fun _ => None\n    | phd :: ptl => fun Hall' =>\n      (*We try to evaluate the head against the first pattern.\n        If this succeeds we combine with tail, if either fails\n        we give None*)\n      (*Since ty is a sort, val v ty = ty, therefore we can cast*)\n      match (match_val_single v ty phd (Forall_inv Hall') \n        (hlist_hd a')) with\n      | None => None\n      | Some l =>\n        match iter_arg_list tl (hlist_tl a') ptl\n          (Forall_inv_tail Hall') with\n        | None => None\n        | Some l' => Some (l ++ l')\n        end\n      end\n    end Hall'\n  end a pats Hall.\n\nLemma match_val_single_rewrite  (v: val_typevar) (ty: vty)\n  (p: pattern) \n  (Hp: pattern_has_type sigma p ty)\n  (d: domain (val v ty)) : \n  match_val_single v ty p Hp d =\n  match p as p' return pattern_has_type sigma p' ty -> \n    option (list (vsymbol * {s: sort & domain s })) with\n  | Pvar x => fun Hty' =>\n    Some [(x, (existT _ (val v ty) d))]\n  | Pwild => fun _ => Some nil\n  | Por p1 p2 => fun Hty' =>\n    match (match_val_single v ty p1 (proj1' (pat_or_inv Hty')) d) with\n                  | Some v1 => Some v1\n                  | None => match_val_single v ty p2 \n                    (proj2' (pat_or_inv Hty')) d\n                  end\n  | Pbind p1 x => fun Hty' =>\n    match (match_val_single v ty p1 (proj1' (pat_bind_inv Hty')) d) with\n    | None => None\n    | Some l => Some ((x, (existT _ (val v ty) d)) :: l)\n    end\n  | Pconstr f params ps => fun Hty' =>\n    match (is_vty_adt ty) as o return\n      is_vty_adt ty = o ->\n      option (list (vsymbol * {s: sort & domain s })) \n    with\n    | Some (m, a, vs) =>  fun Hisadt => \n      let Htyeq : ty = vty_cons (adt_name a) vs :=\n        proj1' (is_vty_adt_spec Hisadt) in\n      let a_in : adt_in_mut a m :=\n        proj1' (proj2' (is_vty_adt_spec Hisadt)) in\n      let m_in : mut_in_ctx m gamma :=\n        proj2' (proj2' (is_vty_adt_spec Hisadt)) in\n\n      let srts := (map (val v) vs) in\n\n      let valeq : val v ty = typesym_to_sort (adt_name a) srts :=\n        eq_trans (f_equal (val v) Htyeq)\n          (v_subst_cons (adt_name a) vs) in\n\n      let adt : adt_rep m srts (dom_aux pd) a a_in :=\n        scast (adts pd m srts a a_in) (dom_cast _ \n          valeq d) in\n\n      let lengths_eq : length srts = length (m_params m) := \n        eq_trans (map_length _ _)\n          (adt_vty_length_eq Hisadt \n          (pat_has_type_valid gamma_valid _ _ Hty')) in\n\n      let Hrep := find_constr_rep gamma_valid m m_in srts lengths_eq \n        (dom_aux pd) a a_in (adts pd m srts) \n        (all_unif m m_in) adt in\n\n      let c : funsym := projT1 Hrep in\n      let c_in : constr_in_adt c a :=\n        fst (proj1_sig (projT2 Hrep)) in\n      let args : arg_list domain (sym_sigma_args c srts) := \n        snd (proj1_sig (projT2 Hrep)) in\n\n      let lengths_eq' : length (s_params c) = length vs :=\n        (constr_length_eq Hisadt \n        (pat_has_type_valid gamma_valid _ _ Hty') c_in) in\n\n      match funsym_eq_dec c f with\n      | left Heq =>\n\n        let c_in': constr_in_adt f a :=\n          cast_prop (fun x => constr_in_adt x a) Heq c_in in\n\n        iter_arg_list _ (cast_arg_list \n          (sym_sigma_args_map v c vs lengths_eq') args) ps\n          (pat_constr_ind (pat_has_type_eq Htyeq Hty') m_in a_in \n            (eq_sym Heq) c_in)\n\n      | right Hneq => None\n      end\n    | None => fun _ => None\n    end eq_refl\n  end Hp.\nProof.\n  destruct p; try solve[reflexivity].\n  (*TODO: we will automate this*)\n  unfold match_val_single; fold match_val_single.\n  generalize dependent (@is_vty_adt_spec ty).\n  generalize dependent (@adt_vty_length_eq ty).\n  generalize dependent (@constr_length_eq ty).\n  destruct (is_vty_adt ty) eqn : Hisadt; [|reflexivity].\n  intros Hvslen1 Hvslen2 Hadtspec.\n  destruct p as [[m adt] vs2].\n  destruct (Hadtspec m adt vs2 eq_refl)\n    as [Htyeq [Hinmut Hinctx]].\n  simpl.\n  destruct (funsym_eq_dec\n  (projT1\n      (find_constr_rep gamma_valid m Hinctx (map (val v) vs2)\n        (eq_trans (map_length (val v) vs2)\n            (Hvslen2 m adt vs2 eq_refl\n              (pat_has_type_valid gamma_valid (Pconstr f l l0) ty Hp)))\n        (dom_aux pd) adt Hinmut (adts pd m (map (val v) vs2)) \n        (all_unif m Hinctx)\n        (scast (adts pd m (map (val v) vs2) adt Hinmut)\n            (dom_cast (dom_aux pd)\n              (eq_trans (f_equal (val v) Htyeq) (v_subst_cons (adt_name adt) vs2)) d))))\n  f); [|reflexivity]. \n  (*Need nested induction, simplify first*)\n  generalize dependent (find_constr_rep gamma_valid m Hinctx (map (val v) vs2)\n  (eq_trans (map_length (val v) vs2)\n      (Hvslen2 m adt vs2 eq_refl\n        (pat_has_type_valid gamma_valid (Pconstr f l l0) ty Hp)))\n  (dom_aux pd) adt Hinmut (adts pd m (map (val v) vs2)) \n  (all_unif m Hinctx)\n  (scast (adts pd m (map (val v) vs2) adt Hinmut)\n      (dom_cast (dom_aux pd)\n        (eq_trans (f_equal (val v) Htyeq) (v_subst_cons (adt_name adt) vs2))\n        d))).\n  intros constr. destruct constr as [f' Hf']. simpl. intros Hf; subst.\n  simpl.\n  match goal with \n  | |- ?f ?x1 ?x2 ?x3 ?x4 = ?g ?x1 ?x2 ?x3 ?x4 =>\n    let H := fresh in\n    assert (H: forall a b c d, f a b c d = g a b c d); [|apply H]\n  end. clear.\n  induction a; intros.\n  - simpl. destruct c; reflexivity.\n  - destruct c; try reflexivity.\n    simpl.\n    destruct (match_val_single v a p (Forall_inv d) (hlist_hd b)) eqn : Hm1;\n    try reflexivity.\n    rewrite IHa. reflexivity.\nQed.\n\n(*TODO: move*)\nDefinition disj {A B: Type} (f: A -> list B) (l: list A) : Prop :=\n  forall i j (d: A) (x: B),\n    i < j ->\n    j < length l ->\n    ~ (In x (f (nth i l d)) /\\ In x (f (nth j l d))).\n\nLemma disj_cons_iff {A B: Type} (f: A -> list B) (a: A) (l: list A):\n  disj f (a :: l) <->\n  disj f l /\\ \n  forall i d x, i < length l -> ~ (In x (f a) /\\ In x (f (nth i l d))).\nProof.\n  unfold disj. split; intros.\n  - split; intros.\n    + simpl in H. \n      apply (H (S i) (S j) d x ltac:(lia) ltac:(lia)).\n    + simpl in H. \n      apply (H 0 (S i) d x ltac:(lia) ltac:(lia)).\n  - destruct j; destruct i; try lia.\n    + simpl. apply (proj2 H). simpl in H1; lia.\n    + simpl in H1 |- *. apply (proj1 H); lia.\nQed.\n\nLemma disj_cons_impl {A B: Type} {f: A -> list B} {a: A} {l: list A}:\n  disj f (a :: l) ->\n  disj f l.\nProof.\n  rewrite disj_cons_iff. \n  intros H; apply H.\nQed.\n\nLemma pat_constr_disj {s f vs ps ty}:\n  pattern_has_type s (Pconstr f vs ps) ty ->\n  disj pat_fv ps.\nProof.\n  intros. inversion H; subst.\n  unfold disj.\n  intros.\n  apply H11; lia.\nQed.\n  \n(*Now we want a generic way to prove things about\n  [match_val_single] so we don't have to do all of the very\n  tedious generalization and nested induction every time*)\nLemma match_val_single_ind \n(P : forall (v : val_typevar) (ty : vty) (p : pattern)\n  (d: domain (val v ty)),\n  option (list (vsymbol * {s: sort & domain s})) -> Prop)\n(*In arg list case, lets us retain info*)\n(Q: forall (l: list sort), arg_list domain l -> Prop)\n(Hvar: forall (v : val_typevar) (ty : vty) (x : vsymbol)\n  (Hty' : pattern_has_type sigma (Pvar x) ty) \n  (d : domain (val v ty)),\n    P v ty (Pvar x) d (*ty (Pvar x) Hty' d*)\n      (Some [(x, existT (fun s => domain s) (val v ty) d)]))\n(*This one is different; we don't want the user to have\n  to do induction every time, so we give more concrete conditions*)\n(*If not ADT, None*)\n(Hconstr1: forall (v: val_typevar) (ty: vty) (f: funsym) (params: list vty)\n  (ps: list pattern) (Hty': pattern_has_type sigma (Pconstr f params ps) ty)\n  (d: domain (val v ty))\n  (Hnone: is_vty_adt ty = None),\n  P v ty (Pconstr f params ps) d None)\n(*If not funsym, None*)\n(Hconstr2: forall (v: val_typevar) (ty: vty) (f: funsym) (params: list vty)\n  (ps: list pattern) (Hty': pattern_has_type sigma (Pconstr f params ps) ty)\n  (d: domain (val v ty))\n  m vs2 adt\n  (Hisadt: is_vty_adt ty = Some (m, adt, vs2))\n  (Htyeq: ty = vty_cons (adt_name adt) vs2)\n  (Hinmut: adt_in_mut adt m)\n  (Hinctx: mut_in_ctx m gamma)\n  (Hvslen2: Datatypes.length vs2 = Datatypes.length (m_params m)),\n  projT1\n  (find_constr_rep gamma_valid m Hinctx (map (val v) vs2)\n    (eq_trans (map_length (val v) vs2)\n        (Hvslen2)) \n    (dom_aux pd) adt Hinmut (adts pd m (map (val v) vs2)) \n    (all_unif m Hinctx)\n    (scast (adts pd m (map (val v) vs2) adt Hinmut)\n        (dom_cast (dom_aux pd)\n          (eq_trans (f_equal (val v) Htyeq) \n          (v_subst_cons (adt_name adt) vs2)) d))) <>\n  f ->\n    P v ty (Pconstr f params ps) d None)\n(*Note: we add as much info as possible to make the condition\n  as weak as possible*)\n(Hq: forall\n  (v: val_typevar) (f: funsym) (*(vs: list vty)*)\n  (adt: alg_datatype) (vs2: list vty) (m: mut_adt)\n  (Hvslen2: forall (m0 : mut_adt) (a : alg_datatype) (vs : list vty),\n    Some (m, adt, vs2) = Some (m0, a, vs) ->\n    valid_type sigma (vty_cons (adt_name adt) vs2) ->\n    Datatypes.length vs = Datatypes.length (m_params m0))\n  (Hisadt: is_vty_adt (vty_cons (adt_name adt) vs2) = Some (m, adt, vs2))\n  (d: domain (val v (vty_cons (adt_name adt) vs2)))\n  (Hinmut: adt_in_mut adt m)\n  (Hinctx: mut_in_ctx m gamma)\n  (i: constr_in_adt f adt)\n  (Hval: valid_type sigma (vty_cons (adt_name adt) vs2))\n  (a: arg_list domain (ty_subst_list_s (s_params f) (map (val v) vs2) \n    (s_args f)))\n  (e: scast (adts pd m (map (val v) vs2) adt Hinmut)\n        (dom_cast (dom_aux pd) (eq_trans eq_refl (v_subst_cons (adt_name adt) vs2)) d) =\n      constr_rep gamma_valid m Hinctx (map (val v) vs2)\n        (eq_trans (map_length (val v) vs2) (Hvslen2 m adt vs2 eq_refl Hval)) \n        (dom_aux pd) adt Hinmut f i (adts pd m (map (val v) vs2)) a),\n    Q _ a)\n(Hconstr3: forall (v: val_typevar) (f: funsym) (params: list vty)\n  (adt: alg_datatype) (vs2: list vty) (m: mut_adt)\n  (Hisadt: is_vty_adt (vty_cons (adt_name adt) vs2) = Some (m, adt, vs2))\n  (d: domain (val v (vty_cons (adt_name adt) vs2)))\n  (Hinmut: adt_in_mut adt m)\n  (Hinctx: mut_in_ctx m gamma)\n  (i: constr_in_adt f adt)\n  (Hval: valid_type sigma (vty_cons (adt_name adt) vs2))\n  (l: list vty)\n  (ps: list pattern)\n  (Hps: disj pat_fv ps) \n  (*Here, we generalize a but assume it satisfies Q, so we can\n    retain some info*)\n  (Hall: Forall\n    (fun p : pattern =>\n    forall (ty : vty) (Hp : pattern_has_type sigma p ty) (d : domain (val v ty)),\n    P v ty p d (match_val_single v ty p Hp d)) ps)\n  (a : arg_list domain (ty_subst_list_s (s_params f) (map (val v) vs2) l))\n  (e : ty_subst_list_s (s_params f) (map (val v) vs2) l =\n        map (val v) (ty_subst_list (s_params f) vs2 l))\n  (f0 : Forall (fun x : pattern * vty => pattern_has_type sigma (fst x) (snd x))\n          (combine ps (ty_subst_list (s_params f) vs2 l)))\n  (*We assume q holds of a*)\n  (Hq: Q _ a),\n  P v (vty_cons (adt_name adt) vs2) (Pconstr f params ps) d (iter_arg_list \n    (ty_subst_list (s_params f) vs2 l) (cast_arg_list e a) ps f0))\n(Hwild: forall (v : val_typevar) (ty : vty)\n  (Hty' : pattern_has_type sigma Pwild ty) \n  (d : domain (val v ty)), P v ty Pwild (*Hty'*) d (Some []))\n(Hor: forall (v : val_typevar) (ty : vty) (p1 p2 : pattern)\n  (Hty' : pattern_has_type sigma (Por p1 p2) ty)\n  (d : domain (val v ty))\n  (IH1: P v ty p1 d (*ty p1 (proj1' (pat_or_inv Hty')) d*)\n    (match_val_single v ty p1 (proj1' (pat_or_inv Hty')) d))\n  (IH2: P v ty p2 d (*ty p2 (proj2' (pat_or_inv Hty')) d*)\n    (match_val_single v ty p2 (proj2' (pat_or_inv Hty')) d)),\n  P v ty (Por p1 p2) d (*ty (Por p1 p2) Hty' d*)\n    match\n      match_val_single v ty p1 (proj1' (pat_or_inv Hty')) d\n    with\n    | Some v1 => Some v1\n    | None => match_val_single v ty p2 (proj2' (pat_or_inv Hty')) d\n    end)\n(Hbind: forall (v : val_typevar) (ty : vty) (p1 : pattern) \n  (x : vsymbol) (Hty' : pattern_has_type sigma (Pbind p1 x) ty)\n  (d : domain (val v ty))\n  (IH: P v ty p1 d (*ty p1 (proj1' (pat_bind_inv Hty')) d*)\n    (match_val_single v ty p1 (proj1' (pat_bind_inv Hty')) d)),\n  P v ty (Pbind p1 x) d (*ty (Pbind p1 x) Hty' d*)\n    match\n      match_val_single v ty p1 (proj1' (pat_bind_inv Hty')) d\n    with\n    | Some l =>\n        Some ((x, existT (fun s => domain s) (val v ty) d) :: l)\n    | None => None\n    end):\nforall (v : val_typevar) (ty : vty) (p : pattern)\n (Hp : pattern_has_type sigma p ty) (d : domain (val v ty)),\nP v ty p (*Hp*) d (match_val_single v ty p Hp d).\nProof.\n  intros. generalize dependent ty.\n  induction p; intros.\n  - simpl. apply Hvar. auto.\n  - (*The hard case: do work here so we don't have to repeat*)\n    rewrite match_val_single_rewrite. simpl.\n    generalize dependent (@is_vty_adt_spec ty).\n    generalize dependent (@adt_vty_length_eq ty).\n    generalize dependent (@constr_length_eq ty).\n    destruct (is_vty_adt ty) eqn : Hisadt.\n    2: {\n      intros. apply (Hconstr1 v ty f vs ps Hp d). auto. }\n    intros Hvslen1 Hvslen2 Hadtspec.\n    destruct p as [[m adt] vs2].\n    destruct (Hadtspec m adt vs2 eq_refl)\n      as [Htyeq [Hinmut Hinctx]].\n    simpl.\n    destruct (funsym_eq_dec\n    (projT1\n       (find_constr_rep gamma_valid m Hinctx (map (val v) vs2)\n          (eq_trans (map_length (val v) vs2)\n             (Hvslen2 m adt vs2 eq_refl\n                (pat_has_type_valid gamma_valid (Pconstr f vs ps) ty Hp)))\n          (dom_aux pd) adt Hinmut (adts pd m (map (val v) vs2)) \n          (all_unif m Hinctx)\n          (scast (adts pd m (map (val v) vs2) adt Hinmut)\n             (dom_cast (dom_aux pd)\n                (eq_trans (f_equal (val v) Htyeq) (v_subst_cons (adt_name adt) vs2)) d))))\n    f).\n    2: {\n      apply (Hconstr2 v ty f vs ps Hp d m vs2 adt Hisadt Htyeq Hinmut _ _ n).\n    }\n    (*Need nested induction, simplify first*)\n    generalize dependent (find_constr_rep gamma_valid m Hinctx (map (val v) vs2)\n    (eq_trans (map_length (val v) vs2)\n       (Hvslen2 m adt vs2 eq_refl\n          (pat_has_type_valid gamma_valid (Pconstr f vs ps) ty Hp)))\n    (dom_aux pd) adt Hinmut (adts pd m (map (val v) vs2)) \n    (all_unif m Hinctx)\n    (scast (adts pd m (map (val v) vs2) adt Hinmut)\n       (dom_cast (dom_aux pd)\n          (eq_trans (f_equal (val v) Htyeq) (v_subst_cons (adt_name adt) vs2))\n          d))).\n    intros constr. destruct constr as [f' Hf']. simpl. intros Hf; subst.\n    simpl.\n    match goal with\n    | |- P ?v ?ty ?p ?d (iter_arg_list ?l ?vs2 ?a ?H) =>\n      generalize dependent H\n    end.\n    destruct Hf'. simpl. (*clear e.*)\n    destruct x. simpl.\n    generalize dependent ((pat_has_type_valid gamma_valid (Pconstr f vs ps)\n    (vty_cons (adt_name adt) vs2) Hp)).\n    intros Hval e. simpl in e.\n    generalize dependent (sym_sigma_args_map v f vs2\n    (Hvslen1 m adt vs2 f eq_refl\n       Hval i)).\n    intros.\n    apply (Hconstr3 v f vs adt vs2 m Hisadt \n      d Hinmut Hinctx i Hval); auto.\n    apply (pat_constr_disj Hp).\n    \n    eapply Hq. apply Hisadt. apply e.\n  - apply (Hwild v ty); auto.\n  - apply Hor. apply IHp1. apply IHp2.\n  - apply Hbind. apply IHp.\nQed.\n\n(*Lemmas about [match_val_single]*)\n(*TODO: move*)\nLemma cons_inj_tl {A: Type} {x y : A} {l1 l2: list A}:\n  x :: l1 = y :: l2 ->\n  l1 = l2.\nProof.\n  intros C. injection C. auto.\nDefined.\n\nLemma cast_arg_list_cons {s: sort} {d: sort -> Set} {s1 s2: list sort} {x} {a}\n  (Heq: s :: s1 = s :: s2):\n  cast_arg_list Heq (HL_cons _ s s1 x a) =\n  HL_cons d s s2 x (cast_arg_list (cons_inj_tl Heq) a).\nProof.\n  inversion Heq. subst.\n  assert (Heq = eq_refl).\n  apply UIP_dec. apply list_eq_dec. apply sort_eq_dec.\n  subst. reflexivity.\nQed.\n\nLemma hlist_tl_cast {d} {s1 s2: sort} {t1 t2: list sort}  \n  (Heq: (s1:: t1) = (s2:: t2)) a:\n  hlist_tl (cast_arg_list Heq a) = \n    @cast_arg_list d _ _ (cons_inj_tl Heq) (hlist_tl a).\nProof.\n  inversion Heq. subst.\n  assert (Heq = eq_refl). apply UIP_dec. apply list_eq_dec.\n    apply sort_eq_dec. subst. reflexivity.\nQed.\n\n(*1. All types align with that of the vsymbol*)\n(*Note that we do NOT need induction on p, and \n  we need no generalization*)\nLemma match_val_single_typs (v: val_typevar) (ty: vty)\n(p: pattern)\n(Hty: pattern_has_type sigma p ty)\n(d: domain (val v ty)) l:\nmatch_val_single v ty p Hty d = Some l ->\nforall x t, In (x, t) l -> projT1 t = val v (snd x).\nProof.\n  revert v ty p Hty d l.\n  apply (match_val_single_ind (fun v ty p d o =>\n  forall l,\n    o = Some l ->\n  forall x t, In (x, t) l -> projT1 t = val v (snd x))\n  (fun _ _ => True)); auto.\n  - intros. inversion H; subst. clear H.\n    destruct H0 as [| []]. inversion H; subst.\n    inversion Hty'; subst. reflexivity.\n  - intros. inversion H.\n  - intros. inversion H0.\n  - intros v f adt vs2 m Hisadt d adt_in m_in f_in Hval.\n    induction l; simpl; intros; auto. \n    + destruct ps. inversion H; subst. inversion H0.\n      inversion H.\n    + revert H. destruct ps; simpl.\n      intros Hc; inversion Hc.\n      repeat match goal with \n      |- (match ?p with |Some l => ?x | None => ?y end) = ?z -> ?q =>\n        let Hp := fresh \"Hmatch\" in \n        destruct p eqn: Hp end.\n      all: intro C; inversion C.\n      subst.\n      apply in_app_or in H0. destruct H0.\n      * inversion Hall; subst.\n        apply H2 with(x:=x) (t:=t) in Hmatch; auto.\n      * rewrite hlist_tl_cast in Hmatch0.\n        apply IHl with(x:=x)(t:=t) in Hmatch0; auto.\n        apply (disj_cons_impl Hps).\n        inversion Hall; auto.\n  - intros. inversion H; subst. inversion H0.\n  - intros. destruct (match_val_single v ty p1 (proj1' (pat_or_inv Hty')) d) eqn : Hm.\n    + apply (IH1 _ H); auto.\n    + apply (IH2 _ H); auto.\n  - intros. destruct (match_val_single v ty p1 (proj1' (pat_bind_inv Hty')) d) eqn : Hm.\n    + inversion H; subst. clear H.\n      destruct H0.\n      * inversion H; subst. inversion Hty'; subst. reflexivity.\n      * apply (IH _ eq_refl); auto.\n    + inversion H.\nQed.\n\n(*2. [match_val_single] is irrelevant in the typing proof*)\nLemma match_val_single_irrel (v: val_typevar) (ty: vty)\n(p: pattern)\n(Hval1 Hval2: pattern_has_type sigma p ty)\n(d: domain (val v ty)) :\n  match_val_single v ty p Hval1 d =\n  match_val_single v ty p Hval2 d.\nProof.\n  revert Hval1 Hval2. revert d. generalize dependent ty.\n  induction p; intros; auto.\n  - rewrite !match_val_single_rewrite; simpl.\n    (*The hard case: need lots of generalization for dependent types\n      and need nested induction*) \n    generalize dependent (@is_vty_adt_spec ty).\n    generalize dependent (@adt_vty_length_eq ty).\n    generalize dependent (@constr_length_eq ty).\n    destruct (is_vty_adt ty) eqn : Hisadt; [|reflexivity].\n    intros Hvslen1 Hvslen2 Hadtspec.\n    destruct p as [[m adt] vs2].\n    destruct (Hadtspec m adt vs2 eq_refl)\n      as [Htyeq [Hinmut Hinctx]].\n    simpl.\n     (*This part is actually easy: all nat equality proofs are equal*)\n    generalize dependent (Hvslen2 m adt vs2 eq_refl\n    (pat_has_type_valid gamma_valid (Pconstr f vs ps) ty Hval1)).\n    generalize dependent (Hvslen2 m adt vs2 eq_refl\n    (pat_has_type_valid gamma_valid (Pconstr f vs ps) ty Hval2)).\n    intros.\n    assert (e = e0) by (apply UIP_dec, Nat.eq_dec). subst.\n    simpl.\n    destruct (funsym_eq_dec\n    (projT1\n       (find_constr_rep gamma_valid m Hinctx (map (val v) vs2)\n          (eq_trans (map_length (val v) vs2)\n             e0)\n          (dom_aux pd) adt Hinmut (adts pd m (map (val v) vs2)) \n          (all_unif m Hinctx)\n          (scast (adts pd m (map (val v) vs2) adt Hinmut)\n             (dom_cast (dom_aux pd)\n                (eq_trans eq_refl (v_subst_cons (adt_name adt) vs2)) d))))\n    f); [|reflexivity].\n\n    (*Need nested induction, simplify first*)\n    generalize dependent (find_constr_rep gamma_valid m Hinctx (map (val v) vs2)\n    (eq_trans (map_length (val v) vs2)\n       e0)\n    (dom_aux pd) adt Hinmut (adts pd m (map (val v) vs2)) \n    (all_unif m Hinctx)\n    (scast (adts pd m (map (val v) vs2) adt Hinmut)\n       (dom_cast (dom_aux pd)\n          (eq_trans eq_refl (v_subst_cons (adt_name adt) vs2))\n          d))).\n    intros constr. destruct constr as [f' Hf']. simpl. intros Hf; subst.\n    simpl.\n    (*Now remove Hvslen1*)\n    generalize dependent (Hvslen1 m adt vs2 f eq_refl\n    (pat_has_type_valid gamma_valid (Pconstr f vs ps)\n       (vty_cons (adt_name adt) vs2) Hval1) (fst (proj1_sig Hf'))).\n    generalize dependent (Hvslen1 m adt vs2 f eq_refl\n    (pat_has_type_valid gamma_valid (Pconstr f vs ps)\n       (vty_cons (adt_name adt) vs2) Hval2) (fst (proj1_sig Hf'))).\n    intros. assert (e = e1) by (apply UIP_dec, Nat.eq_dec); subst.\n    match goal with\n    | |- (iter_arg_list ?l ?vs2 ?a ?H) = iter_arg_list ?l ?vs2 ?a ?H2 =>\n      generalize dependent H;\n      generalize dependent H2\n    end.\n    destruct Hf'. simpl.\n    destruct x. simpl.\n    generalize dependent (sym_sigma_args_map v f vs2 e1).\n    clear Hval1 Hval2.\n    clear e.\n    unfold sym_sigma_args in *.\n    generalize dependent ps.\n    generalize dependent a.\n    generalize dependent (s_args f).\n    clear.\n    induction l; simpl; intros.\n    + destruct ps; reflexivity.\n    + destruct ps; try reflexivity. simpl.\n      inversion H; subst.\n      rewrite H2 with (Hval2:= (Forall_inv f0)). simpl.\n      rewrite !hlist_tl_cast. \n      rewrite IHl with(f:=(Forall_inv_tail f0)); auto.\n  - simpl. replace (match_val_single v ty p1 (proj1' (pat_or_inv Hval1)) d) with\n    (match_val_single v ty p1 (proj1' (pat_or_inv Hval2)) d) by apply IHp1.\n    destruct (match_val_single v ty p1 (proj1' (pat_or_inv Hval2)) d); auto.\n  - simpl. rewrite IHp with (Hval2:=(proj1' (pat_bind_inv Hval2))). reflexivity.\nQed.\n\nVariable vt: val_typevar.\n\n(*3. The variables bound are exactly the free variables of pattern p.\n  Note that we do NOT get equality because of OR patterns, but\n  Permutation is sufficient*)\n\n(*We put one case in a separate lemma because we need it later*)\nLemma iter_arg_list_perm:\nforall (v : val_typevar) (f : funsym)\n(vs2 : list vty),\nforall (l : list vty) (ps : list pattern),\ndisj pat_fv ps ->\nForall\n(fun p : pattern =>\n forall (ty : vty) (Hp : pattern_has_type sigma p ty) (d0 : domain (val v ty))\n   (l0 : list (vsymbol * {s : sort & domain s})),\n match_val_single v ty p Hp d0 = Some l0 -> Permutation (map fst l0) (pat_fv p)) ps ->\nforall (a : arg_list domain (ty_subst_list_s (s_params f) (map (val v) vs2) l))\n(e : ty_subst_list_s (s_params f) (map (val v) vs2) l =\n     map (val v) (ty_subst_list (s_params f) vs2 l))\n(f0 : Forall (fun x : pattern * vty => pattern_has_type sigma (fst x) (snd x))\n        (combine ps (ty_subst_list (s_params f) vs2 l))),\nforall l0 : list (vsymbol * {s: sort & domain s}),\niter_arg_list (ty_subst_list (s_params f) vs2 l) (cast_arg_list e a) ps f0 = Some l0 ->\nPermutation (map fst l0) (big_union vsymbol_eq_dec pat_fv ps).\nProof.\n  intros v f vs2.\n  induction l; simpl; intros; auto. \n  + destruct ps. inversion H1; subst.\n    apply Permutation_refl.\n    inversion H1. \n  + revert H1. destruct ps; simpl.\n    intros Hc; inversion Hc.\n    repeat match goal with \n    |- (match ?p with |Some l => ?x | None => ?y end) = ?z -> ?q =>\n      let Hp := fresh \"Hmatch\" in \n      destruct p eqn: Hp end.\n    all: intro C; inversion C.\n    subst. clear C.\n    (*Now, just need to handle the pieces*)\n    inversion H0; subst.\n    rewrite hlist_tl_cast in Hmatch0.\n    apply IHl in Hmatch0; auto.\n    apply H3 in Hmatch.\n    rewrite map_app, union_app_disjoint.\n    * apply Permutation_app; auto.\n    * rewrite disj_cons_iff in H.\n      destruct_all. intros.\n      intro C.\n      destruct_all. simpl_set.\n      destruct H5 as [p' [Hinp' Hinx2]].\n      destruct (In_nth _ _ Pwild Hinp') as [i[ Hi Hp']]; subst.\n      apply (H1 i Pwild x Hi); auto.\n    * apply NoDup_pat_fv.\n    * apply (disj_cons_impl H).\nQed.\n\nLemma match_val_single_perm ty d p l\n  (Hty: pattern_has_type sigma p ty):\n  match_val_single vt ty p Hty d = Some l ->\n  Permutation (map fst l) (pat_fv p).\nProof.\n  revert vt ty p Hty d l.\n  apply (match_val_single_ind (fun v ty p d o =>\n  forall l,\n    o = Some l ->\n    Permutation (map fst l) (pat_fv p))\n  (fun _ _ => True)); auto.\n  - intros. inversion H; subst. simpl.\n    apply Permutation_refl.\n  - intros. inversion H.\n  - intros. inversion H0.\n  - intros. apply (iter_arg_list_perm v f vs2 l ps Hps Hall a e f0).\n    auto. \n  - intros. inversion H; subst. apply Permutation_refl.\n  - intros.   \n    inversion Hty'; subst.\n    assert (Permutation (pat_fv p1) (pat_fv p2)). {\n      apply NoDup_Permutation; auto; apply NoDup_pat_fv.\n    } \n    simpl.\n    rewrite union_subset; [|intros; apply H6; auto | apply NoDup_pat_fv].\n    destruct (match_val_single v ty p1 (proj1' (pat_or_inv Hty')) d) eqn: Hm.\n    + eapply Permutation_trans. apply IH1; auto. auto.\n    + apply IH2; auto.\n  - simpl; intros.\n    inversion Hty'; subst.\n    rewrite union_app_disjoint; \n    [| intros x2 [Hinx1 [ Heq | []]]; subst; contradiction | \n    apply NoDup_pat_fv ].\n    destruct (match_val_single v (snd x) p1 (proj1' (pat_bind_inv Hty')) d) eqn : Hm.\n    + inversion H; subst; simpl.\n      eapply perm_trans.\n      apply Permutation_cons_append.\n      apply Permutation_app_tail.\n      apply IH; auto. \n    + inversion H.\nQed.\n\n(*Corollaries*)\nCorollary match_val_single_free_var ty p Hty d l x:\n  match_val_single vt ty p Hty d = Some l ->\n  In x (pat_fv p) <-> In x (map fst l).\nProof.\n  intros. apply match_val_single_perm in H.\n  split; apply Permutation_in; auto.\n  apply Permutation_sym; auto.\nQed.\n\nLemma match_val_single_nodup ty p Hty d l: \n  match_val_single vt ty p Hty d = Some l ->\n  NoDup (map fst l).\nProof.\n  intros. apply match_val_single_perm in H; auto.\n  apply Permutation_sym in H.\n  apply Permutation_NoDup in H; auto.\n  apply NoDup_pat_fv.\nQed.\n\nLemma iter_arg_list_free_var:\nforall (v : val_typevar) (f : funsym)\n(vs2 : list vty),\nforall (l : list vty) (ps : list pattern),\ndisj pat_fv ps ->\nForall\n(fun p : pattern =>\n forall (ty : vty) (Hp : pattern_has_type sigma p ty) (d0 : domain (val v ty))\n   (l0 : list (vsymbol * {s : sort & domain s})),\n match_val_single v ty p Hp d0 = Some l0 -> Permutation (map fst l0) (pat_fv p)) ps ->\nforall (a : arg_list domain (ty_subst_list_s (s_params f) (map (val v) vs2) l))\n(e : ty_subst_list_s (s_params f) (map (val v) vs2) l =\n     map (val v) (ty_subst_list (s_params f) vs2 l))\n(f0 : Forall (fun x : pattern * vty => pattern_has_type sigma (fst x) (snd x))\n        (combine ps (ty_subst_list (s_params f) vs2 l))),\nforall l0 : list (vsymbol * {s: sort & domain s}),\niter_arg_list (ty_subst_list (s_params f) vs2 l) (cast_arg_list e a) ps f0 = Some l0 ->\nforall x, In x (big_union vsymbol_eq_dec pat_fv ps) <-> In x (map fst l0).\nProof.\n  intros. apply (iter_arg_list_perm v f vs2) in H1; auto.\n  split; apply Permutation_in; auto.\n  apply Permutation_sym; auto.\nQed.\n\n(*Now we need a notion of extending the valuation\n  with the result from the pattern match*)\nSection ExtendVal.\n\n(*Look up each entry in the list, if the name or type doesn't\n  match, default to existing val*)\nDefinition extend_val_with_list (v: val_typevar) \n  (vv: val_vars pd v)\n  (l: list (vsymbol * {s: sort & domain s })):\n  val_vars pd v := fun x =>\n  match (get_assoc_list vsymbol_eq_dec l x) with\n  | Some a => \n    match (sort_eq_dec (val v (snd x)) (projT1 a)) with\n    | left Heq =>\n      dom_cast _ (eq_sym Heq) (projT2 a)\n    | right _ => vv x\n    end\n  | None => vv x\n  end.\n\n(*Lemmas about [extend_val_with_list]*)\n\nLemma extend_val_with_list_in (vv: val_vars pd vt) \n  (x: vsymbol)\n  (d: domain (val vt (snd x))) (l: list (vsymbol * {s: sort & \n    domain s}))\n  (Hl: forall x y, In (x, y) l -> projT1 y = val vt (snd x)):\n    In x (map fst l) ->\n    extend_val_with_list vt (substi vt vv x d) l =\n    extend_val_with_list vt vv l.\nProof.\n  unfold extend_val_with_list.\n  intros Hinl. apply functional_extensionality_dep; intros v.\n  destruct (get_assoc_list vsymbol_eq_dec l v) eqn : Ha.\n  - apply get_assoc_list_some in Ha.\n    apply Hl in Ha.\n    destruct (sort_eq_dec (val vt (snd v)) (projT1 s)); auto. rewrite Ha in n.\n    contradiction.\n  - rewrite get_assoc_list_none in Ha.\n    unfold substi. \n    destruct (vsymbol_eq_dec v x); auto.\n    subst. contradiction.\nQed.\n\nLemma extend_val_with_list_notin (vv: val_vars pd vt) \n  (x: vsymbol)\n  (d: domain (val vt (snd x))) \n  (l: list (vsymbol * {s: sort & domain s}))\n  (Hl: forall x y, In (x, y) l -> projT1 y = val vt (snd x)):\n    ~In x (map fst l) ->\n    extend_val_with_list vt (substi vt vv x d) l =\n    substi vt (extend_val_with_list vt vv l) x d.\nProof.\n  intros. unfold extend_val_with_list.\n  unfold substi.\n  apply functional_extensionality_dep; intros v.\n  destruct (get_assoc_list vsymbol_eq_dec l v) eqn : Ha; auto.\n  destruct (vsymbol_eq_dec v x); subst; auto.\n  exfalso. assert (get_assoc_list vsymbol_eq_dec l x = None).\n  apply get_assoc_list_none. auto. rewrite H0 in Ha. inversion Ha.\nQed. \n\nLemma extend_val_with_list_in_eq\n  (v1 v2: val_vars pd vt) l x\n  (Htys: forall (x : vsymbol) t,\n  In (x, t) l -> projT1 t = val vt (snd x)):\n  In x (map fst l) ->\n  extend_val_with_list vt v1 l x =\n  extend_val_with_list vt v2 l x.\nProof.\n  intros Hin.\n  unfold extend_val_with_list.\n  destruct (get_assoc_list vsymbol_eq_dec l x) eqn : Hassoc.\n  + apply get_assoc_list_some in Hassoc.\n    apply Htys in Hassoc.\n    destruct (sort_eq_dec (val vt (snd x)) (projT1 s)); auto; try contradiction.\n    rewrite Hassoc in n; contradiction.\n  + rewrite get_assoc_list_none in Hassoc. contradiction.\nQed.\n\n(*TODO: rename*)\nLemma extend_val_with_list_notin'  (vv : val_vars pd vt) \n(x : vsymbol) (d : domain (val vt (snd x)))\n(l : list (vsymbol * {s: sort & domain s})):\n~ In x (map fst l) ->\nextend_val_with_list vt vv l x = vv x.\nProof.\n  intros. unfold extend_val_with_list.\n  rewrite <- get_assoc_list_none in H.\n  rewrite H.\n  reflexivity.\nQed.\n\nLemma extend_val_with_list_lookup (v: val_vars pd vt) l x t:\n  NoDup (map fst l) ->\n  In (x, t) l ->\n  extend_val_with_list vt v l x =\n    match (sort_eq_dec (val vt (snd x)) (projT1 t))  with\n    | left Heq =>\n        dom_cast (dom_aux pd) (eq_sym Heq)\n          (projT2 t)\n    | right _ => v x\n    end.\nProof.\n  intros. unfold extend_val_with_list.\n  destruct (get_assoc_list vsymbol_eq_dec l x) eqn : ha.\n  - apply get_assoc_list_some in ha.\n    assert (t = s). apply (nodup_fst_inj H H0 ha). subst.\n    reflexivity.\n  - apply get_assoc_list_none in ha.\n    exfalso. apply ha. rewrite in_map_iff. exists (x, t). auto.\nQed.\n\nEnd ExtendVal.\n\n(*Now we give the denotational semantics:*)\n\nSection Defs.\n\nVariable (pf: pi_funpred gamma_valid pd).\nNotation funs := (funs gamma_valid pd pf).\n\n(*TODO: need to prove we never hit None on well-typed pattern\n  match by exhaustivenss - need relation of [match] with\n  [match_val_single]*)  \n\n(*Terms*)\n(* There are many dependent type obligations and casting to ensure that\n  the types work out. In each case, we separate the hypotheses and give\n  explicit types for clarity. The final result is often quite simple and just\n  needs 1 or more casts for dependent type purposes. \n  We use Equations to make the dependent pattern matching (on Hty)\n  nicer, but we still need a nested fix.\n  This also avoids needing to prove separate rewrite lemmas\n  for use in different files, since Coq does not unfold some\n  parts of this function*)\n\nEquations term_rep (v: val_vars pd vt) (t: term) (ty: vty)\n(Hty: term_has_type sigma t ty) : domain (val vt ty) by struct t := {\n\nterm_rep v (Tconst (ConstInt z)) ty Hty :=\n  let Htyeq : vty_int = ty :=\n  eq_sym (ty_constint_inv Hty) in\n  cast_dom_vty Htyeq z;\n\nterm_rep v (Tconst (ConstReal r)) ty Hty :=\n  let Htyeq : vty_real = ty :=\n  eq_sym (ty_constreal_inv Hty) in\n  cast_dom_vty Htyeq r;\n\nterm_rep v (Tvar x) ty Hty :=\n  let Heq : ty = snd x := ty_var_inv Hty in\n  (dom_cast _ (f_equal (val vt) (eq_sym Heq)) (var_to_dom _ vt v x));\n\nterm_rep v (Tfun f vs ts) ty Hty :=\n  (*Some proof we need; we give types for clarity*)\n  let Htyeq : ty_subst (s_params f) vs (f_ret f) = ty :=\n    eq_sym (ty_fun_ind_ret Hty) in\n  (*The main typecast: v(sigma(ty_ret)) = sigma'(ty_ret), where\n    sigma sends (s_params f)_i -> vs_i and \n    sigma' sends (s_params f) _i -> v(vs_i)*)\n  let Heqret : v_subst (v_typevar vt) (ty_subst (s_params f) vs (f_ret f)) =\n    ty_subst_s (s_params f) (map (v_subst (v_typevar vt)) vs) (f_ret f) :=\n      funsym_subst_eq (s_params f) vs (v_typevar vt) (f_ret f) (s_params_Nodup f)\n      (tfun_params_length Hty) in\n\n  (* The final result is to apply [funs] to the [arg_list] created recursively\n    from the argument domain values. We need two casts to make the dependent\n    types work out*)\n\n  cast_dom_vty Htyeq (\n    dom_cast (dom_aux pd)\n      (eq_sym Heqret)\n        ((funs f (map (val vt) vs)) \n          (fun_arg_list vt f vs ts (term_rep v) Hty)));\n  \nterm_rep v (Tlet t1 x t2) ty Hty :=\n  let Ht1 : term_has_type sigma t1 (snd x) :=\n    proj1 (ty_let_inv Hty) in\n  let Ht2 : term_has_type sigma t2 ty :=\n    proj2 (ty_let_inv Hty) in \n  term_rep (substi vt v x (term_rep v t1 (snd x) Ht1)) t2 ty Ht2;\n\nterm_rep v (Tif f t1 t2) ty Hty :=\n  let Ht1 : term_has_type sigma t1 ty :=\n    (proj1 (ty_if_inv Hty)) in\n  let Ht2 : term_has_type sigma t2 ty :=\n    (proj1 (proj2 (ty_if_inv Hty))) in\n  let Hf: valid_formula sigma f :=\n    (proj2 (proj2 (ty_if_inv Hty))) in\n  if (formula_rep v f Hf) then term_rep v t1 ty Ht1 \n  else term_rep v t2 ty Ht2;\n\nterm_rep v (Tmatch t ty1 xs) ty Hty :=\n  let Ht1 : term_has_type sigma t ty1 :=\n    proj1 (ty_match_inv Hty) in\n  let Hps : Forall (fun x => pattern_has_type sigma (fst x) ty1) xs :=\n    proj1 (proj2 (ty_match_inv Hty)) in\n  let Hall : Forall (fun x => term_has_type sigma (snd x) ty) xs :=\n    proj2 (proj2 (ty_match_inv Hty)) in\n\n  let dom_t := term_rep v t ty1 Ht1 in\n\n  let fix match_rep (ps: list (pattern * term)) \n      (Hps: Forall (fun x => pattern_has_type sigma (fst x) ty1) ps)\n      (Hall: Forall (fun x => term_has_type sigma (snd x) ty) ps) :\n        domain (val vt ty) :=\n    match ps as l' return \n      Forall (fun x => pattern_has_type sigma (fst x) ty1) l' ->\n      Forall (fun x => term_has_type sigma (snd x) ty) l' ->\n      domain (val vt ty) with\n    | (p , dat) :: ptl => fun Hpats Hall =>\n      match (match_val_single vt ty1 p (Forall_inv Hpats) dom_t) with\n      | Some l => term_rep (extend_val_with_list vt v l) dat ty\n        (Forall_inv Hall) \n      | None => match_rep ptl (Forall_inv_tail Hpats) (Forall_inv_tail Hall)\n      end\n    | _ => (*TODO: show we cannot reach this*) fun _ _ =>\n      match domain_ne pd (val vt ty) with\n      | DE x =>  x\n      end\n    end Hps Hall in\n    match_rep xs Hps Hall;\n\nterm_rep v (Teps f x) ty Hty :=\n  let Hval : valid_formula sigma f := proj1 (ty_eps_inv Hty) in\n  let Heq : ty = snd x := proj2 (ty_eps_inv Hty) in\n  (*We need to show that domain (val v ty) is inhabited*)\n  let def : domain (val vt ty) :=\n  match (domain_ne pd (val vt ty)) with\n  | DE x => x \n  end in\n  (*Semantics for epsilon - use Coq's classical epsilon,\n    we get an instance y of [domain (val v ty)]\n    that makes f true when x evaluates to y\n    TODO: make sure this works*)\n\n  epsilon (inhabits def) (fun (y: domain (val vt ty)) =>\n    is_true (formula_rep (substi vt v x (dom_cast _ (f_equal (val vt) Heq) y)) f Hval));\n}\n\nwith formula_rep (v: val_vars pd vt) (f: formula) \n  (Hval: valid_formula sigma f) : bool by struct f :=\n\n  formula_rep v Ftrue Hval := true;\n  formula_rep v Ffalse Hval := false;\n  formula_rep v (Fnot f') Hval :=\n    let Hf' : valid_formula sigma f' :=\n      valid_not_inj Hval\n    in \n    negb (formula_rep v f' Hf');\n\n  formula_rep v (Fbinop b f1 f2) Hval :=\n    let Hf1 : valid_formula sigma f1 :=\n    proj1 (valid_binop_inj Hval) in\n    let Hf2 : valid_formula sigma f2 :=\n      proj2 (valid_binop_inj Hval) in\n    bool_of_binop b (formula_rep v f1 Hf1) (formula_rep v f2 Hf2);\n\n  formula_rep v (Flet t x f') Hval :=\n    let Ht: term_has_type sigma t (snd x) :=\n      (proj1 (valid_let_inj Hval)) in\n    let Hf': valid_formula sigma f' :=\n      (proj2 (valid_let_inj Hval)) in\n    formula_rep (substi vt v x (term_rep v t (snd x) Ht)) f' Hf';\n\n  formula_rep v (Fif f1 f2 f3) Hval :=\n    let Hf1 : valid_formula sigma f1 :=\n      proj1 (valid_if_inj Hval) in\n    let Hf2 : valid_formula sigma f2 :=\n      proj1 (proj2 (valid_if_inj Hval)) in\n    let Hf3 : valid_formula sigma f3 :=\n      proj2 (proj2 (valid_if_inj Hval)) in\n    if formula_rep v f1 Hf1 then formula_rep v f2 Hf2 else formula_rep v f3 Hf3;\n\n  (*Much simpler than Tfun case above because we don't need casting*)\n  formula_rep v (Fpred p vs ts) Hval :=\n    preds _ _ pf p (map (val vt) vs)\n      (pred_arg_list vt p vs ts (term_rep v) Hval);\n\n  formula_rep v (Fquant Tforall x f') Hval :=\n    let Hf' : valid_formula sigma f' :=\n      valid_quant_inj Hval in\n    (*NOTE: HERE is where we need the classical axiom assumptions*)\n    all_dec (forall d, formula_rep (substi vt v x d) f' Hf');\n  \n  formula_rep v (Fquant Texists x f') Hval :=\n    let Hf' : valid_formula sigma f' :=\n      valid_quant_inj Hval in\n    (*NOTE: HERE is where we need the classical axiom assumptions*)\n    all_dec (exists d, formula_rep (substi vt v x d) f' Hf');\n\n  formula_rep v (Feq ty t1 t2) Hval := \n    let Ht1 : term_has_type sigma t1 ty := \n      proj1 (valid_eq_inj Hval) in\n    let Ht2 : term_has_type sigma t2 ty :=\n      proj2 (valid_eq_inj Hval) in\n    (*TODO: require decidable equality for all domains?*)\n    all_dec (term_rep v t1 ty Ht1 = term_rep v t2 ty Ht2);\n\n  formula_rep v (Fmatch t ty1 xs) Hval :=\n    (*Similar to term case*)\n    let Ht1 : term_has_type sigma t ty1 :=\n      proj1 (valid_match_inv Hval) in\n    let Hps : Forall (fun x => pattern_has_type sigma (fst x) ty1) xs :=\n      proj1 (proj2 (valid_match_inv Hval)) in\n    let Hall : Forall (fun x => valid_formula sigma (snd x)) xs :=\n      proj2 (proj2 (valid_match_inv Hval)) in\n\n    let dom_t := term_rep v t ty1 Ht1 in\n    let fix match_rep (ps: list (pattern * formula)) \n      (Hps: Forall (fun x => pattern_has_type sigma (fst x) ty1) ps)\n      (Hall: Forall (fun x => valid_formula sigma (snd x)) ps) :\n        bool :=\n    match ps as l' return \n      Forall (fun x => pattern_has_type sigma (fst x) ty1) l' ->\n      Forall (fun x => valid_formula sigma (snd x)) l' ->\n      bool with\n    | (p , dat) :: ptl => fun Hpats Hall =>\n      match (match_val_single vt ty1 p (Forall_inv Hpats) dom_t) with\n      | Some l => formula_rep (extend_val_with_list vt v l) dat\n        (Forall_inv Hall) \n      | None => match_rep ptl (Forall_inv_tail Hpats) (Forall_inv_tail Hall)\n      end\n    | _ => (*TODO: show we cannot reach this*) fun _ _ => false\n    end Hps Hall in\n    match_rep xs Hps Hall.\n\nEnd Defs.\n\n(*We want these in the rest of the file*)\nLtac simpl_rep :=\n  repeat match goal with\n  | |- context [term_rep ?pf ?v ?t ?ty ?Hty] =>\n    lazymatch t with\n    | Tconst (ConstInt ?z) => rewrite term_rep_equation_1\n    | Tconst (ConstReal ?r) => rewrite term_rep_equation_2\n    | Tvar ?v => rewrite term_rep_equation_3\n    | Tfun ?f ?l1 ?l2 => rewrite term_rep_equation_4\n    | Tlet ?t1 ?v ?t2 => rewrite term_rep_equation_5\n    | Tif ?f ?t1 ?t2 => rewrite term_rep_equation_6\n    | Tmatch ?t ?v ?ps => rewrite term_rep_equation_7\n    | Teps ?f ?v => rewrite term_rep_equation_8\n    end\n  end.\n\nLtac simpl_rep_full :=\n  repeat (simpl_rep; cbv zeta; simpl).\n\nLtac iter_match_gen Hval Htm Hpat Hty :=\n  match type of Hval with\n  | term_has_type ?s ?t ?ty =>\n    generalize dependent (proj1 (ty_match_inv Hval));\n    generalize dependent (proj1 (proj2 (ty_match_inv Hval)));\n    generalize dependent (proj2 (proj2 (ty_match_inv Hval)))\n  | valid_formula ?s ?f =>\n    generalize dependent (proj1 (valid_match_inv Hval));\n    generalize dependent (proj1 (proj2 (valid_match_inv Hval)));\n    generalize dependent (proj2 (proj2 (valid_match_inv Hval)))\n  end;\n  clear Hval;\n  intros Htm Hpat Hty;\n  revert Htm Hpat Hty.\n\nSection Lemmas.\n\nVariable (pf: pi_funpred gamma_valid pd).\nNotation funs := (funs gamma_valid pd pf).\n\n(*Results about the Denotational Semantics*)\n\n(*We need to know that the valid typing proof is irrelevant.\n  I believe this should be provable without proof irrelevance,\n  but [term_rep] and [formula_rep] already depend on\n  classical logic, which implies proof irrelevance.\n  We prove without proof irrelevance to limit the use of axioms.\n  We need functional extensionality for the epsilon case only*)\n\nLemma term_form_rep_irrel: forall (tm: term) (f: formula),\n  (forall (v: val_vars pd vt) (ty: vty) (Hty1 Hty2:\n    term_has_type sigma tm ty), \n      term_rep pf v tm ty Hty1 = term_rep pf v tm ty Hty2) /\\\n  (forall (v: val_vars pd vt) (Hval1 Hval2:\n    valid_formula sigma f), \n      formula_rep pf v f Hval1 = formula_rep pf v f Hval2).\nProof.\n  apply term_formula_ind; intros; simpl_rep; simpl; auto.\n  - destruct c; simpl_rep; simpl;\n    f_equal; apply UIP_dec; apply vty_eq_dec.\n  - f_equal. f_equal. apply UIP_dec; apply vty_eq_dec.\n  - f_equal. apply UIP_dec; apply vty_eq_dec.\n    f_equal. f_equal. f_equal. apply UIP_dec. apply Nat.eq_dec.\n    f_equal. apply get_arg_list_eq.\n    rewrite Forall_forall. intros x Hinx ty' H1 H2.\n    rewrite Forall_forall in H. apply H. assumption.\n  - replace ((term_rep pf v0 tm1 (snd v) (proj1 (ty_let_inv Hty1))))\n    with  (term_rep pf v0 tm1 (snd v) (proj1 (ty_let_inv Hty2)))\n    by apply H.\n    apply H0.\n  - replace (formula_rep pf v f (proj2 (proj2 (ty_if_inv Hty1))))\n    with (formula_rep pf v f (proj2 (proj2 (ty_if_inv Hty2))))\n    by apply H.\n    match goal with | |- context [ if ?b then ?x else ?y] => destruct b end.\n    apply H0. apply H1.\n  - (*We need a nested induction here - we have a tactic to help\n      with generalization*)\n    iter_match_gen Hty1 Htm1 Hpat1 Hty1.\n    iter_match_gen Hty2 Htm2 Hpat2 Hty2.\n    induction ps; simpl; intros; auto.\n    destruct a.\n    (*Bulk of work done in [match_val_single_irrel]*)\n    rewrite (H _ _ Hty1 Hty2) at 1. \n    rewrite match_val_single_irrel with(Hval2:=(Forall_inv Hpat2)).\n    simpl.\n    destruct (match_val_single vt v p \n      (Forall_inv Hpat2) (term_rep pf v0 tm v Hty2)).\n    + inversion H0; subst. apply (H3 (extend_val_with_list vt v0 l)).\n    + inversion H0; subst.\n      apply IHps. auto.\n  - (*TODO: is this possible without funext?*)\n    f_equal. apply functional_extensionality_dep.\n    intros x.\n    rewrite (H (substi vt v0 v (dom_cast (dom_aux pd)\n    (f_equal (val vt) (proj2 (ty_eps_inv Hty1))) x))\n      (proj1 (ty_eps_inv Hty1))\n    (proj1 (ty_eps_inv Hty2))).\n    assert (proj2 (ty_eps_inv Hty1) =\n    (proj2 (ty_eps_inv Hty2))).\n    apply UIP_dec. apply vty_eq_dec. rewrite H0.\n    reflexivity.\n  - f_equal. apply get_arg_list_eq.\n    rewrite Forall_forall. intros x Hinx ty' H1 H2.\n    rewrite Forall_forall in H. apply H. assumption.\n  - destruct q;\n    repeat match goal with |- context [ all_dec ?P ] => \n      destruct (all_dec P); simpl; auto end.\n    + exfalso. apply n. intros d.\n      erewrite (H (substi vt v0 v d)).\n      apply i.\n    + exfalso. apply n. intros d.\n      erewrite H. apply i.\n    + exfalso. apply n. \n      destruct e as [d Hd].\n      exists d. erewrite H. apply Hd.\n    + exfalso. apply n.\n      destruct e as [d Hd].\n      exists d. erewrite H. apply Hd.\n  - erewrite H. erewrite H0. reflexivity.\n  - erewrite H. erewrite H0. reflexivity.\n  - erewrite H. reflexivity.\n  - erewrite H. erewrite H0. reflexivity.\n  - erewrite H. erewrite H0. erewrite H1. reflexivity.\n  - (*Match case again - proof almost identical*)\n    iter_match_gen Hval1 Htm1 Hpat1 Hty1.\n    iter_match_gen Hval2 Htm2 Hpat2 Hty2.\n    induction ps; simpl; intros; auto.\n    destruct a.\n    (*Bulk of work done in [match_val_single_irrel]*)\n    rewrite (H _ _ Hty1 Hty2) at 1.\n    rewrite match_val_single_irrel with (Hval2:=(Forall_inv Hpat2)); simpl.\n    destruct (match_val_single vt v p (Forall_inv Hpat2) (term_rep pf v0 tm v Hty2)).\n    + inversion H0; subst. apply (H3 (extend_val_with_list vt v0 l)).\n    + inversion H0; subst.\n      apply IHps. auto.\nQed.\n\nDefinition term_rep_irrel t := proj_tm term_form_rep_irrel t.\nDefinition fmla_rep_irrel f := proj_fmla term_form_rep_irrel f.\n\nSection Sub.\n\n(*Prove that substitution is correct: the substituted\n  formula is the same as evaluating the original where\n  x is substituted for y*)\n\nLtac solve_bnd :=  \n  repeat match goal with\n  | H: ~In ?x (bnd_t ?t) |- ~In ?x (bnd_f ?f) =>\n    let C := fresh in\n    intro C; apply H; simpl\n  | H: ~In ?x (bnd_t ?t) |- ~In ?x (bnd_t ?t2) =>\n    let C := fresh in\n    intro C; apply H; simpl\n  | H: ~In ?x (bnd_f ?t) |- ~In ?x (bnd_f ?f) =>\n    let C := fresh in\n    intro C; apply H; simpl\n  | H: ~In ?x (bnd_f ?t) |- ~In ?x (bnd_t ?t2) =>\n    let C := fresh in\n    intro C; apply H; simpl\n  | |- In ?x (?l1 ++ ?l2) => apply in_or_app\n  | |- ?P \\/ ?Q => (*idtac \"x\";*)\n    first [left; solve[solve_bnd] | right; solve[solve_bnd]]\n  | |- In ?x ?y => solve[try assumption; auto]\n  end.\n\n(*Substitution over [get_arg_list]*)\nLemma get_arg_list_sub x y s tys tms \n  (reps1 reps2: forall (t: term) (ty: vty),\n  term_has_type sigma t ty ->\n  domain (val vt ty))\n  (Hreps: Forall (fun tm =>\n    forall (ty:vty) Hty1 Hty2,\n    ~ In y (bnd_t tm) ->\n    reps1 tm ty Hty1 =\n    reps2 (sub_t x y tm) ty Hty2) tms)\n  (Hfree: ~In y (concat (map bnd_t tms)))\n  (Hlents1: length tms = length (s_args s))\n  (Hlents2: length (map (sub_t x y) tms) = length (s_args s))\n  (Hlenvs1 Hlenvs2: length tys = length (s_params s))\n  (Hall1: Forall (fun x => term_has_type sigma (fst x) (snd x))\n    (combine tms (map (ty_subst (s_params s) tys) (s_args s))))\n  (Hall2: Forall (fun x => term_has_type sigma (fst x) (snd x))\n    (combine (map (sub_t x y) tms) (map (ty_subst (s_params s) tys) (s_args s)))):\n  get_arg_list vt s tys tms reps1 Hlents1 Hlenvs1 Hall1 =\n  get_arg_list vt s tys (map (sub_t x y) tms) reps2 Hlents2 Hlenvs2 Hall2.\nProof.\n  apply get_arg_list_ext.\n  - rewrite map_length; auto.\n  - intros. rewrite Forall_forall in Hreps.\n    revert Hty2.\n    rewrite (map_nth_inbound) with(d2:=tm_d); auto; intros.\n    apply Hreps; auto.\n    apply nth_In; auto.\n    intro Hiny.\n    apply Hfree. rewrite in_concat. exists (bnd_t (nth i tms tm_d)).\n    split; auto. rewrite in_map_iff. exists (nth i tms tm_d); split;\n    auto. apply nth_In; auto.\nQed.\n(*\n(*Same for [get_arg_list_pred]*)\nLemma get_arg_list_pred_sub x y p tys tms \n  (reps1 reps2: forall (t: term) (ty: vty),\n  term_has_type sigma t ty ->\n  domain (val vt ty))\n  (Hreps: Forall (fun tm =>\n    forall (ty:vty) Hty1 Hty2,\n    ~ In y (bnd_t tm) ->\n    reps1 tm ty Hty1 =\n    reps2 (sub_t x y tm) ty Hty2) tms)\n  (Hfree: ~In y (bnd_f (Fpred p tys tms)))\n  (Hval1 : valid_formula sigma (Fpred p tys tms))\n  (Hval2: valid_formula sigma (Fpred p tys (map (sub_t x y) tms))):\n  get_arg_list_pred vt p tys tms reps1 Hval1 =\n  get_arg_list_pred vt p tys (map (sub_t x y) tms) reps2 Hval2.\nProof.\n  apply get_arg_list_pred_ext.\n  - rewrite map_length; auto.\n  - intros. rewrite Forall_forall in Hreps.\n    revert Hty2.\n    rewrite (map_nth_inbound) with(d2:=tm_d); auto; intros.\n    apply Hreps; auto.\n    apply nth_In; auto.\n    simpl in Hfree. intro Hiny.\n    apply Hfree. rewrite in_concat. exists (bnd_t (nth i tms tm_d)).\n    split; auto. rewrite in_map_iff. exists (nth i tms tm_d); split;\n    auto. apply nth_In; auto.\nQed.*)\n\n(*TODO: see if we can get rid of casting in Here*)\n(*Could rewrite by saying (x, ty) and (y, ty).\n  Might be nicer*)\nLemma sub_correct (t: term) (f: formula) :\n  (forall (x y: vsymbol) (Heq: snd x = snd y) \n    (v: val_vars pd vt) (ty: vty) \n    (Hty1: term_has_type sigma t ty)\n    (Hty2: term_has_type sigma (sub_t x y t) ty)\n    (Hfree: ~In y (bnd_t t)),\n    term_rep pf (substi vt v x \n    (dom_cast _ (f_equal (val vt) (eq_sym Heq))\n      (v y))) t ty Hty1 =\n    term_rep pf v (sub_t x y t) ty Hty2) /\\\n  (forall (x y: vsymbol) (Heq: snd x = snd y) \n    (v: val_vars pd vt)\n    (Hval1: valid_formula sigma f)\n    (Hval2: valid_formula sigma (sub_f x y f))\n    (Hfree: ~In y (bnd_f f)),\n    formula_rep pf (substi vt v x \n    (dom_cast _ (f_equal (val vt) (eq_sym Heq))\n      (v y))) f Hval1 =\n    formula_rep pf v (sub_f x y f) Hval2).\nProof.\n  revert t f.\n  apply term_formula_ind; intros; simpl_rep_full; auto.\n  - (*constants*) destruct c; simpl_rep_full ; auto;\n    inversion Hty1;\n    inversion Hty2; subst;\n    unfold cast_dom_vty, dom_cast.\n    (*Equality is annoying*)\n    + assert (ty_constint_inv Hty1 = eq_refl).\n        apply UIP_dec. apply vty_eq_dec.\n      rewrite H. simpl.\n      assert (ty_constint_inv Hty2 = eq_refl).\n        apply UIP_dec; apply vty_eq_dec.\n      rewrite H0. reflexivity.\n    + assert (ty_constreal_inv  Hty1 = eq_refl).\n        apply UIP_dec. apply vty_eq_dec. \n      rewrite H. simpl.\n      assert (ty_constreal_inv Hty2 = eq_refl).\n        apply UIP_dec; apply vty_eq_dec.\n      rewrite H0. reflexivity.\n  - (*vars*) unfold var_to_dom.\n    generalize dependent Hty2. simpl.\n    destruct (vsymbol_eq_dec x v); intros; simpl_rep_full.\n    + subst.\n      inversion Hty1; subst.\n      assert (ty_var_inv Hty1 = eq_refl).\n        apply UIP_dec. apply vty_eq_dec.\n      rewrite H.\n      clear H. simpl.\n      unfold dom_cast; simpl.\n      unfold substi.\n      destruct (vsymbol_eq_dec v v); [|contradiction].\n      assert (e = eq_refl).\n        apply UIP_dec. apply vsymbol_eq_dec.\n      rewrite H. clear H.\n      unfold eq_rec_r; simpl.\n      destruct v. simpl in *; subst. simpl.\n      assert (ty_var_inv Hty2 = eq_refl).\n        apply UIP_dec. apply vty_eq_dec.\n      rewrite H. reflexivity.\n    + unfold substi.\n      destruct (vsymbol_eq_dec v x); subst; try contradiction.\n      f_equal. f_equal. f_equal. apply UIP_dec. apply vty_eq_dec.\n  - (*function case*) unfold cast_dom_vty, dom_cast.\n    inversion Hty1; subst.\n    assert (ty_fun_ind_ret Hty1 = eq_refl). {\n      apply UIP_dec. apply vty_eq_dec.\n    }\n    rewrite H0. simpl.\n    assert ((@ty_fun_ind_ret f1 l (@map term term (sub_t x y) l1)\n      (ty_subst (s_params f1) l (f_ret f1)) Hty2) = eq_refl). {\n      apply UIP_dec. apply vty_eq_dec.\n    }\n    rewrite H1. simpl.\n    assert ((tfun_params_length Hty1) =\n    (tfun_params_length Hty2)). {\n      apply UIP_dec. apply Nat.eq_dec.\n    }\n    rewrite H2.\n    clear -H Hfree.\n    unfold eq_sym at 1 3.\n    generalize dependent (funsym_subst_eq (s_params f1) l (v_typevar vt) \n    (f_ret f1) (s_params_Nodup f1)\n    (tfun_params_length Hty2)).\n    generalize dependent (funsym_subst_eq (s_params f1) l (v_typevar vt) \n    (f_ret f1) (s_params_Nodup f1)\n    (@tfun_params_length sigma f1 l (@map term term (sub_t x y) l1)\n      (ty_subst (s_params f1) l (f_ret f1)) Hty2)).\n    simpl.\n    (*To eliminate eqs*)\n    generalize dependent (val vt (ty_subst (s_params f1) l (f_ret f1))).\n    intros. subst.\n    assert (e0 = eq_refl). { apply UIP_dec. apply sort_eq_dec. }\n    rewrite H0.\n    f_equal. f_equal.\n    (*Now we show the arg lists equal by a separate lemma*)\n    apply get_arg_list_sub; auto.\n    eapply Forall_impl. 2: apply H. simpl.\n    intros. apply H1. auto.\n  - (*term let*) \n    inversion Hty2; subst. \n    rewrite H with(Hty2:=H6) by solve_bnd.\n    generalize dependent H7.\n    generalize dependent Hty2.\n    simpl.\n    destruct (vsymbol_eq_dec x v); intros; subst; simpl_rep_full.\n    + rewrite substi_same.\n      rewrite term_rep_irrel with\n        (Hty2:=(proj1 (ty_let_inv Hty2))).\n      apply term_rep_irrel.\n    + rewrite substi_diff; auto.\n      inversion Hty1; subst.\n      rewrite <- H0 with (Heq:=Heq) (Hty1:=H9) by solve_bnd.\n      rewrite term_rep_irrel with (Hty2:=(proj1 (ty_let_inv Hty2))).\n      unfold substi at 5.\n      destruct (vsymbol_eq_dec y v); subst; simpl.\n      * (*Know v <> y because y is not bound*)\n        exfalso. apply Hfree. simpl. left; auto.\n      * apply term_rep_irrel.\n  - (*term if*)\n    erewrite H by solve_bnd.\n    erewrite H0 by solve_bnd.\n    erewrite H1 by solve_bnd.\n    reflexivity.\n  - (*term match case*)\n    simpl in *.\n    iter_match_gen Hty1 Htm1 Hpat1 Hty1.\n    iter_match_gen Hty2 Htm2 Hpat2 Hty2.\n    rewrite !in_app_iff in Hfree.\n    not_or Hfree.\n    induction ps; simpl; intros; auto.\n    simpl. destruct a as [p1 t1]; simpl.\n    simpl in Hfree1.\n    rewrite !in_app_iff in Hfree1.\n    not_or Hfree.\n    destruct (match_val_single vt v p1 (Forall_inv Hpat1)\n    (term_rep pf\n       (substi vt v0 x (dom_cast (dom_aux pd) (f_equal (val vt) (eq_sym Heq)) (v0 y)))\n       tm v Hty1)) as [newval |] eqn : Hmatch.\n    + revert Hpat2 Htm2. simpl.\n      destruct (in_bool vsymbol_eq_dec x (pat_fv p1)) eqn : Hinp1.\n      * intros.\n        rewrite <- H with(Heq:=Heq) (Hty1:=Hty1); auto.\n        rewrite match_val_single_irrel with \n          (Hval2:=(Forall_inv Hpat1)).\n        simpl.\n        rewrite Hmatch.\n        assert (In x (map fst newval)). {\n          apply (match_val_single_free_var) with(x:=x)in Hmatch.\n          apply Hmatch. destruct (in_bool_spec vsymbol_eq_dec x (pat_fv p1)); auto.\n          inversion Hinp1.\n        }\n       rewrite extend_val_with_list_in; auto.\n       apply term_rep_irrel.\n       eapply match_val_single_typs.\n       apply Hmatch.\n      * intros.\n        rewrite <- H with(Heq:=Heq) (Hty1:=Hty1) by auto.\n        rewrite match_val_single_irrel with \n          (Hval2:=(Forall_inv Hpat1)).\n        simpl.\n        rewrite Hmatch.\n        (*Again, use other lemma*)\n        assert (~In x (map fst newval)). {\n          apply (match_val_single_free_var) with(x:=x) in Hmatch.\n          intro C.\n          apply Hmatch in C. destruct (in_bool_spec vsymbol_eq_dec x (pat_fv p1)); auto.\n       }\n       rewrite extend_val_with_list_notin; auto.\n       inversion H0; subst. \n       rewrite <- H4 with(Heq:=Heq)(Hty1:=(Forall_inv Htm1));auto.\n       f_equal. f_equal. f_equal.\n       (*Need to know that y is not bound (in the list)*)\n       unfold extend_val_with_list.\n       destruct (get_assoc_list vsymbol_eq_dec newval y) eqn : Ha; auto.\n       apply get_assoc_list_some in Ha.\n       apply match_val_single_free_var with(x:=y) in Hmatch.\n       exfalso. apply Hfree1. apply Hmatch. rewrite in_map_iff.\n       exists (y, s). split; auto.\n       eapply match_val_single_typs. apply Hmatch.\n        (*Forthis case: if var x not free in match,\n          then list does not contain it, and then\n          that we can rearrange the order of the substi\n          (basically a bigger [substi_diff]), then we apply\n          the IH (the Forall one)*)\n    + revert Hpat2 Htm2. simpl.\n      (*Cases are the same*)\n      destruct (in_bool vsymbol_eq_dec x (pat_fv p1)) eqn : Hinp1;\n      intros;\n      rewrite <- H with(Heq:=Heq) (Hty1:=Hty1); auto;\n      rewrite match_val_single_irrel with \n          (Hval2:=(Forall_inv Hpat1));\n      simpl;\n      rewrite Hmatch;\n      inversion H0; subst;\n      specialize (IHps H4 Hfree2);\n      rewrite IHps with(Hpat2:=Forall_inv_tail Hpat2)\n        (Htm2:= (Forall_inv_tail Htm2))(Hty2:=Hty2);\n      erewrite H; auto.\n  - (*epsilon*) \n    generalize dependent Hty2. simpl. \n    destruct (vsymbol_eq_dec x v); subst; intros; simpl_rep_full.\n    + f_equal. apply functional_extensionality_dep. intros d.\n      inversion Hty1; subst.\n      rewrite substi_same.\n      assert ((proj2 (ty_eps_inv Hty1)) = (proj2 (ty_eps_inv Hty2))). {\n        apply UIP_dec. apply vty_eq_dec.\n      }\n      rewrite H0.\n      erewrite fmla_rep_irrel. reflexivity.\n    + f_equal. apply functional_extensionality_dep. intros d.\n      inversion Hty1; subst.\n      rewrite substi_diff; auto.\n      rewrite <- H with(Heq:=Heq)(Hval1:=H3) by solve_bnd.\n      unfold substi at 5. \n      destruct (vsymbol_eq_dec y v).\n      * exfalso. subst. apply Hfree. left. auto.\n      * assert ((proj2 (ty_eps_inv Hty1)) =\n      (proj2 (ty_eps_inv Hty2))). {\n        apply UIP_dec. apply vty_eq_dec.\n      } rewrite H0. \n      erewrite fmla_rep_irrel. reflexivity.\n  - (*predicate*)\n    f_equal.\n    apply get_arg_list_sub; auto.\n    eapply Forall_impl. 2: apply H. simpl; intros.\n    apply H0. auto.\n  - (*quantifiers*)\n    destruct q; revert Hval2; simpl; destruct (vsymbol_eq_dec x v); \n    intros; subst; simpl;\n    apply all_dec_eq.\n    (*1st and 3rd cases quite similar, same for 2nd and 4th*)\n    + split; intros Hall d; specialize (Hall d); revert Hall;\n      rewrite substi_same; intros Hall; erewrite fmla_rep_irrel; apply Hall.\n    + split; intros Hall d; specialize (Hall d); revert Hall;\n      rewrite substi_diff; auto; inversion Hval1; subst;\n      rewrite <- H with(Heq:=Heq) (Hval1:=H5);try solve_bnd;\n      [unfold substi at 5| unfold substi at 3];\n      destruct (vsymbol_eq_dec y v); \n      try solve[subst; exfalso; apply Hfree; left; reflexivity];\n      intros Hrep; erewrite fmla_rep_irrel; apply Hrep.\n    + split; intros [d Hex]; exists d; revert Hex;\n      rewrite substi_same; intros Hex; erewrite fmla_rep_irrel; apply Hex.\n    + split; intros [d Hex]; exists d; revert Hex;\n      rewrite substi_diff; auto; inversion Hval1; subst;\n      rewrite <- H with(Heq:=Heq) (Hval1:=H5);try solve_bnd;\n      [unfold substi at 5| unfold substi at 3];\n      destruct (vsymbol_eq_dec y v); \n      try solve[subst; exfalso; apply Hfree; left; reflexivity];\n      intros Hrep; erewrite fmla_rep_irrel; apply Hrep.\n  - (*eq*)\n    apply all_dec_eq. \n    rewrite H with(Hty2:=(proj1 (valid_eq_inj Hval2)))\n    by solve_bnd.\n    rewrite H0 with (Hty2:=(proj2 (valid_eq_inj Hval2)))\n    by solve_bnd.\n    reflexivity.\n  - (*binop*)\n    f_equal. apply H; solve_bnd. apply H0; solve_bnd.\n  - (*not*)\n    f_equal. apply H. solve_bnd.\n  - (*fmla let*)\n    inversion Hval2; subst. \n    rewrite H with(Hty2:=H4) by solve_bnd.\n    generalize dependent Hval2. simpl.\n    destruct (vsymbol_eq_dec x v); simpl; intros; subst.\n    + rewrite substi_same.\n      erewrite term_rep_irrel.\n      apply fmla_rep_irrel.\n    + rewrite substi_diff;auto.\n      inversion Hval1; subst.\n      rewrite <- H0 with (Heq:=Heq) (Hval1:=H8) by solve_bnd.\n      unfold substi at 5.\n      destruct (vsymbol_eq_dec y v).\n        exfalso. apply Hfree. left; auto.\n      erewrite term_rep_irrel.\n      apply fmla_rep_irrel.\n  - (*fmla if*)\n    erewrite H by solve_bnd.\n    erewrite H0 by solve_bnd.\n    erewrite H1 by solve_bnd.\n    reflexivity.\n  - (*fmla match - basically identical to term*)\n    simpl in *.\n    iter_match_gen Hval1 Htm1 Hpat1 Hty1.\n    iter_match_gen Hval2 Htm2 Hpat2 Hty2.\n    rewrite !in_app_iff in Hfree.\n    not_or Hfree.\n    induction ps; simpl; intros; auto.\n    simpl. destruct a as [p1 t1]; simpl.\n    simpl in Hfree1.\n    rewrite !in_app_iff in Hfree1.\n    not_or Hfree.\n    destruct (match_val_single vt v p1 (Forall_inv Hpat1)\n    (term_rep pf\n      (substi vt v0 x (dom_cast (dom_aux pd) (f_equal (val vt) (eq_sym Heq)) (v0 y)))\n      tm v Hty1)) as [newval |] eqn : Hmatch.\n    + revert Hpat2 Htm2. simpl.\n      destruct (in_bool vsymbol_eq_dec x (pat_fv p1)) eqn : Hinp1.\n      * intros.\n        rewrite <- H with(Heq:=Heq) (Hty1:=Hty1); auto.\n        rewrite match_val_single_irrel with \n          (Hval2:=(Forall_inv Hpat1)).\n        simpl.\n        rewrite Hmatch.\n        assert (In x (map fst newval)). {\n          apply (match_val_single_free_var) with(x:=x)in Hmatch.\n          apply Hmatch. destruct (in_bool_spec vsymbol_eq_dec x (pat_fv p1)); auto.\n          inversion Hinp1.\n        }\n      rewrite extend_val_with_list_in; auto.\n      apply fmla_rep_irrel.\n      eapply match_val_single_typs.\n      apply Hmatch.\n      * intros.\n        rewrite <- H with(Heq:=Heq) (Hty1:=Hty1) by auto.\n        rewrite match_val_single_irrel with \n          (Hval2:=(Forall_inv Hpat1)).\n        simpl.\n        rewrite Hmatch.\n        (*Again, use other lemma*)\n        assert (~In x (map fst newval)). {\n          apply (match_val_single_free_var) with(x:=x) in Hmatch.\n          intro C.\n          apply Hmatch in C. destruct (in_bool_spec vsymbol_eq_dec x (pat_fv p1)); auto.\n      }\n      rewrite extend_val_with_list_notin; auto.\n      inversion H0; subst. \n      rewrite <- H4 with(Heq:=Heq)(Hval1:=(Forall_inv Htm1));auto.\n      f_equal. f_equal. f_equal.\n      (*Need to know that y is not bound (in the list)*)\n      unfold extend_val_with_list.\n      destruct (get_assoc_list vsymbol_eq_dec newval y) eqn : Ha; auto.\n      apply get_assoc_list_some in Ha.\n      apply match_val_single_free_var with(x:=y) in Hmatch.\n      exfalso. apply Hfree1. apply Hmatch. rewrite in_map_iff.\n      exists (y, s). split; auto.\n      eapply match_val_single_typs. apply Hmatch.\n        (*Forthis case: if var x not free in match,\n          then list does not contain it, and then\n          that we can rearrange the order of the substi\n          (basically a bigger [substi_diff]), then we apply\n          the IH (the Forall one)*)\n    + revert Hpat2 Htm2. simpl.\n      (*Cases are the same*)\n      destruct (in_bool vsymbol_eq_dec x (pat_fv p1)) eqn : Hinp1;\n      intros;\n      rewrite <- H with(Heq:=Heq) (Hty1:=Hty1); auto;\n      rewrite match_val_single_irrel with \n          (Hval2:=(Forall_inv Hpat1));\n      simpl;\n      rewrite Hmatch;\n      inversion H0; subst;\n      specialize (IHps H4 Hfree2);\n      rewrite IHps with(Hpat2:=Forall_inv_tail Hpat2)\n        (Htm2:= (Forall_inv_tail Htm2))(Hty2:=Hty2);\n      erewrite H; auto. \nQed.\n\n(*The useful versions:*)\nCorollary sub_t_correct (t: term) (x y: vsymbol)\n  (Heq: snd x = snd y)\n  (v: val_vars pd vt) (ty: vty)\n  (Hty1: term_has_type sigma t ty)\n  (Hty2: term_has_type sigma (sub_t x y t) ty)\n  (Hfree: ~In y (bnd_t t)):\n  term_rep pf v (sub_t x y t) ty Hty2 =\n  term_rep pf (substi vt v x \n  (dom_cast _ (f_equal (val vt) (eq_sym Heq))\n    (v y))) t ty Hty1.\nProof.\n  symmetry. apply sub_correct; auto. apply Ffalse.\nQed.\n\nCorollary sub_f_correct (f: formula)\n  (x y: vsymbol) (Heq: snd x = snd y) \n  (v: val_vars pd vt)\n  (Hval1: valid_formula sigma f)\n  (Hval2: valid_formula sigma (sub_f x y f))\n  (Hfree: ~In y (bnd_f f)):\n  formula_rep pf v (sub_f x y f) Hval2 =\n  formula_rep pf (substi vt v x \n    (dom_cast _ (f_equal (val vt) (eq_sym Heq))\n      (v y))) f Hval1.\nProof.\n  symmetry. apply sub_correct; auto. apply (Tconst (ConstInt 0)).\nQed.\n  \n(*Other lemma we need: a term/formula is interpreted the\n  same on all valuations that agree on the free variables*)\nLemma val_fv_agree (t: term) (f: formula) :\n(forall (v1 v2: val_vars pd vt) (ty: vty) \n  (Hty: term_has_type sigma t ty),\n  (forall x, In x (term_fv t) -> v1 x = v2 x) ->\n  term_rep pf v1 t ty Hty = term_rep pf v2 t ty Hty) /\\\n(forall (v1 v2: val_vars pd vt) \n  (Hval: valid_formula sigma f),\n  (forall x, In x (form_fv f) -> v1 x = v2 x) ->\n  formula_rep pf v1 f Hval = formula_rep pf v2 f Hval).\nProof.\n  revert t f.\n  apply term_formula_ind; intros; simpl_rep_full; auto.\n  - f_equal. unfold var_to_dom. apply H. left; auto.\n  - f_equal. f_equal. f_equal.\n    apply get_arg_list_eq.\n    rewrite Forall_forall. intros.\n    rewrite Forall_forall in H.\n    rewrite term_rep_irrel with (Hty2:=Hty2).\n    apply H; intros; auto.\n    apply H0.\n    apply big_union_elts. exists x; auto.\n  - apply H0. intros x Hinx.\n    unfold substi. destruct (vsymbol_eq_dec x v); auto; subst.\n    unfold eq_rec_r; simpl. apply H.\n    intros. apply H1. simpl. simpl_set. \n    left; auto.\n    apply H1. simpl. simpl_set; right; auto. \n  - rewrite (H _ v2). \n    rewrite (H0 _ v2).\n    rewrite (H1 _ v2).\n    reflexivity.\n    all: intros x Hinx; apply H2; simpl; simpl_set; auto.\n  - iter_match_gen Hty Htm Hpat Hty.\n    induction ps; simpl; auto; intros.\n    destruct a.\n    inversion H0; subst.\n    rewrite (H v1 v2) at 1.\n    destruct (match_val_single vt v p (Forall_inv Hpat) \n    (term_rep pf v2 tm v Hty)) eqn : Hm;\n    [|apply IHps]; auto.\n    + apply H4.\n      intros.\n      destruct (in_bool_spec vsymbol_eq_dec x (map fst l)).\n      * apply extend_val_with_list_in_eq.\n        apply (match_val_single_typs _ _ _ _ _ _ Hm). auto.\n      * (*Now, need to know that map fst l = free vars of p (elementwise)*)\n        rewrite !extend_val_with_list_notin'; auto.\n        apply H1.\n        apply union_elts. right.\n        apply big_union_elts.\n        exists (p, t). split; auto. left; auto.\n        simpl. simpl_set.\n        split; auto.\n        rewrite (match_val_single_free_var _ _ (Forall_inv Hpat) _ _ _ Hm); auto.\n    + intros x Hinx.\n      apply H1. simpl.\n      revert Hinx. simpl. simpl_set; intros. \n      destruct Hinx as [Hin1 | Hinx]; auto.\n    + intros. apply H1. simpl. simpl_set. auto. \n  - f_equal. apply functional_extensionality_dep; intros.\n    erewrite H. reflexivity.\n    intros y Hiny.\n    unfold substi.\n    destruct (vsymbol_eq_dec y v); auto.\n    apply H0. apply in_in_remove; auto.\n  - f_equal.\n    apply get_arg_list_eq.\n    rewrite Forall_forall. intros.\n    rewrite Forall_forall in H.\n    rewrite term_rep_irrel with (Hty2:=Hty2).\n    apply H; intros; auto.\n    apply H0. simpl; simpl_set.\n     exists x; auto.\n  - destruct q; apply all_dec_eq.\n    + split; intros Hall d; specialize (Hall d);\n      erewrite H; try solve[apply Hall]; intros x Hinx;\n      unfold substi; destruct (vsymbol_eq_dec x v); auto;\n      [symmetry|]; apply H0; apply in_in_remove; auto.\n    + split; intros [d Hex]; exists d;\n      erewrite H; try solve[apply Hex]; intros x Hinx;\n      unfold substi; destruct (vsymbol_eq_dec x v); auto;\n      [symmetry|]; apply H0; apply in_in_remove; auto.\n  - apply all_dec_eq. rewrite (H _ v2). rewrite (H0 _ v2).\n    reflexivity.\n    all: intros x Hinx; apply H1; simpl; rewrite union_elts; auto.\n  - f_equal.\n    + apply H; intros x Hinx. apply H1. simpl. rewrite union_elts. auto.\n    + apply H0. intros x Hinx. apply H1. simpl. rewrite union_elts. auto.\n  - f_equal. apply H. intros x Hinx. apply H0. auto.\n  - apply H0. intros x Hinx.\n    unfold substi. destruct (vsymbol_eq_dec x v); auto.\n    + f_equal. apply H. intros y Hiny. apply H1. simpl.\n      rewrite union_elts. auto.\n    + apply H1. simpl. rewrite union_elts. right.\n      apply in_in_remove; auto.\n  - rewrite (H _ v2).\n    rewrite (H0 _ v2).\n    rewrite (H1 _ v2).\n    reflexivity. \n    all: intros x Hinx; apply H2; simpl; rewrite !union_elts; auto.\n  - iter_match_gen Hval Htm Hpat Hval.\n    induction ps; simpl; auto; intros.\n    destruct a.\n    inversion H0; subst.\n    rewrite (H v1 v2) at 1.\n    destruct (match_val_single vt v p \n      (Forall_inv Hpat) (term_rep pf v2 tm v Hval)) eqn : Hm;\n    [|apply IHps]; auto.\n    + apply H4.\n      intros.\n      destruct (in_bool_spec vsymbol_eq_dec x (map fst l)).\n      * apply extend_val_with_list_in_eq.\n        apply (match_val_single_typs _ _ _ _ _ _ Hm). auto.\n      * rewrite !extend_val_with_list_notin'; auto.\n        apply H1.\n        apply union_elts. right.\n        apply big_union_elts.\n        exists (p, f). split; auto. left; auto.\n        simpl. apply remove_all_elts.\n        split; auto.\n        rewrite (match_val_single_free_var _ _ _ _ _ _ Hm); auto.\n    + intros x Hinx.\n      apply H1. simpl.\n      revert Hinx. simpl; simpl_set; intros.\n      destruct Hinx as [Hin1 | Hinx]; auto.\n    + intros. apply H1. simpl. rewrite union_elts. auto. \nQed. \n\n(*Corollaries:*)\nDefinition term_fv_agree t := proj_tm val_fv_agree t.\nDefinition form_fv_agree f := proj_fmla val_fv_agree f.\n\n(*The interpretation of any \n  closed term is equivalent under any valuation*)\nCorollary term_closed_val (t: term)\n  (v1 v2: val_vars pd vt) (ty: vty)\n  (Hty: term_has_type sigma t ty):\n  closed_term t ->\n  term_rep pf v1 t ty Hty = term_rep pf v2 t ty Hty.\nProof.\n  unfold closed_term. intros.\n  apply term_fv_agree; intros.\n  destruct (term_fv t); inversion H; inversion H0.\nQed.\n\nCorollary fmla_closed_val (f: formula)\n  (v1 v2: val_vars pd vt) \n  (Hval: valid_formula sigma f):\n  closed_formula f ->\n  formula_rep pf v1 f Hval = formula_rep pf v2 f Hval.\nProof.\n  unfold closed_formula; intros.\n  apply form_fv_agree; intros.\n  destruct (form_fv f); inversion H; inversion H0.\nQed.\n\nEnd Sub.\n\nSection Wf.\n\n(*If we know that the bound variable names are unique and do\n  not conflict with the free variable names, we can prove the\n  correctness of many transformations. We define such a notion\n  and provide a function (not necessarily the most efficient one)\n  to alpha-convert our term/formula into this form. The function\n  and proofs are in Substitution.v*)\n(*TODO: make names consistent*)\nDefinition term_wf (t: term) : Prop :=\n  NoDup (bnd_t t) /\\ forall x, ~ (In x (term_fv t) /\\ In x (bnd_t t)).\nDefinition fmla_wf (f: formula) : Prop :=\n  NoDup (bnd_f f) /\\ forall x, ~ (In x (form_fv f) /\\ In x (bnd_f f)).\n\nLemma wf_quant (q: quant) (v: vsymbol) (f: formula) :\n  fmla_wf (Fquant q v f) ->\n  fmla_wf f.\nProof.\n  unfold fmla_wf. simpl. intros. split_all.\n  - inversion H; auto.\n  - intros x C. split_all.\n    apply (H0 x).\n    destruct (vsymbol_eq_dec x v); subst; auto.\n    + inversion H; subst. contradiction.\n    + split; auto. simpl_set; auto. \nQed. \n\nLemma wf_binop (b: binop) (f1 f2: formula) :\n  fmla_wf (Fbinop b f1 f2) ->\n  fmla_wf f1 /\\ fmla_wf f2.\nProof.\n  unfold fmla_wf. simpl. rewrite NoDup_app_iff.\n  intros. split_all; auto; intros x C; split_all.\n  - apply (H0 x).\n    split_all. apply union_elts. auto. \n    apply in_or_app. auto.\n  - apply (H0 x).\n    split_all. apply union_elts. auto.\n    apply in_or_app. auto. \nQed.\n\nLemma wf_let (t: term) (v: vsymbol) (f: formula) :\n  fmla_wf (Flet t v f) ->\n  fmla_wf f.\nProof.\n  unfold fmla_wf. simpl. intros; split_all; auto; \n  inversion H; subst; auto.\n  - rewrite NoDup_app_iff in H4; apply H4.\n  - intros x C. split_all.\n    apply (H0 x). split.\n    + simpl_set; right. split; auto. intro Heq; subst.\n      inversion H; subst.\n      apply H7. apply in_or_app. auto. \n    + right. apply in_or_app. auto.\nQed.\n\nEnd Wf.\n\n(*Iterated version of forall, let, and*)\nSection Iter.\n\n(*Iterated forall*)\nDefinition fforalls (vs: list vsymbol) (f: formula) : formula :=\n  fold_right (fun x acc => Fquant Tforall x acc) f vs.\n\nLemma fforalls_valid (vs: list vsymbol) (f: formula) \n  (Hval: valid_formula sigma f)\n  (Hall: Forall (fun x => valid_type sigma (snd x)) vs) : \n  valid_formula sigma (fforalls vs f).\nProof.\n  induction vs; auto. inversion Hall; subst. \n  simpl. constructor; auto.\nQed.\n\nLemma fforalls_valid_inj (vs: list vsymbol) (f: formula)\n  (Hval: valid_formula sigma (fforalls vs f)):\n  valid_formula sigma f /\\ Forall (fun x => valid_type sigma (snd x)) vs.\nProof.\n  induction vs; auto.\n  simpl in Hval. inversion Hval; subst.\n  specialize (IHvs H4). split_all; auto.\nQed.\n\n(*Substitute in a bunch of values for a bunch of variables,\n  using an hlist to ensure they have the correct type*)\nFixpoint substi_mult (vt: val_typevar) (vv: @val_vars sigma pd vt) \n  (vs: list vsymbol)\n  (vals: hlist (fun x =>\n  domain (v_subst (v_typevar vt) x)) (map snd vs)) :\n  val_vars pd vt :=\n  (match vs as l return hlist  \n    (fun x => domain (v_subst (v_typevar vt) x)) \n    (map snd l) -> val_vars pd vt with\n  | nil => fun _ => vv\n  | x :: tl => fun h' => \n     (substi_mult vt (substi vt vv x (hlist_hd h')) tl (hlist_tl h')) \n  end) vals.\n  \n(*And we show that we can use this multi-substitution\n  to interpret [fforalls_val]*)\nLemma fforalls_val (vv: val_vars pd vt) \n  (vs: list vsymbol) (f: formula) \n  (Hval: valid_formula sigma f)\n  (Hall: Forall (fun x => valid_type sigma (snd x)) vs):\n  formula_rep pf vv (fforalls vs f) \n    (fforalls_valid vs f Hval Hall) =\n    all_dec (forall (h: hlist  (fun x =>\n      domain (v_subst (v_typevar vt) x)) (map snd vs)),\n      formula_rep pf (substi_mult vt vv vs h) f Hval).\nProof.\n  revert vv.\n  generalize dependent (fforalls_valid vs f Hval Hall).\n  induction vs; simpl; intros Hval' vv.\n  - destruct (formula_rep pf vv f Hval') eqn : Hrep; \n    match goal with |- context[ all_dec ?P ] => destruct (all_dec P); auto end; simpl.\n    + exfalso. apply n; intros. erewrite fmla_rep_irrel. apply Hrep.\n    + rewrite <- Hrep. erewrite fmla_rep_irrel. apply i. constructor.\n  - inversion Hall; subst. specialize (IHvs H2).\n    specialize (IHvs (valid_quant_inj Hval')).\n    apply all_dec_eq.\n    split; intros Hforall.\n    + intros h. \n      specialize (Hforall (hlist_hd h)).\n      rewrite IHvs in Hforall.\n      revert Hforall.\n      match goal with |- context[ all_dec ?P ] => destruct (all_dec P); auto end; simpl.\n    + intros d.\n      rewrite IHvs. \n      match goal with |- context[ all_dec ?P ] => destruct (all_dec P); auto end; simpl.\n      exfalso. apply n; clear n. intros h.\n      specialize (Hforall (HL_cons _ (snd a) (map snd vs) d h)).\n      apply Hforall.\nQed.\n\nLemma fforalls_val' (vv: val_vars pd vt) \n  (vs: list vsymbol) (f: formula) \n  Hval1 Hval2:\n  formula_rep pf vv (fforalls vs f) \n    Hval2 =\n    all_dec (forall (h: hlist  (fun x =>\n      domain (v_subst (v_typevar vt) x)) (map snd vs)),\n      formula_rep pf (substi_mult vt vv vs h) f Hval1).\nProof.\n  assert (A:=Hval2).\n  apply fforalls_valid_inj in A. split_all.\n  rewrite fmla_rep_irrel with(Hval2:=(fforalls_valid vs f Hval1 H0)).\n  apply fforalls_val.\nQed.\n\n(*Next we give the valuation for an iterated let. This time,\n  we don't need to worry about hlists*)\nFixpoint substi_multi_let (vv: @val_vars sigma pd vt) \n(vs: list (vsymbol * term)) \n  (Hall: Forall (fun x => term_has_type sigma (snd x) (snd (fst x))) vs) :\nval_vars pd vt := \n  match vs as l return\n  Forall (fun x => term_has_type sigma (snd x) (snd (fst x))) l ->\n  val_vars pd vt\n  with\n  | nil => fun _ => vv\n  | (v, t) :: tl => fun Hall =>\n    substi_multi_let \n      (substi vt vv v \n        (term_rep pf vv t (snd v) \n      (Forall_inv Hall))) tl (Forall_inv_tail Hall)\n  end Hall.\n\nDefinition iter_flet (vs: list (vsymbol * term)) (f: formula) :=\n  fold_right (fun x acc => Flet (snd x) (fst x) acc) f vs.\n\nLemma iter_flet_valid (vs: list (vsymbol * term)) (f: formula)\n  (Hval: valid_formula sigma f)\n  (Hall: Forall (fun x => term_has_type sigma (snd x) (snd (fst x))) vs) :\n  valid_formula sigma (iter_flet vs f).\nProof.\n  induction vs; simpl; auto.\n  inversion Hall; subst.\n  constructor; auto.\nQed.\n\nLemma iter_flet_valid_inj (vs: list (vsymbol * term)) (f: formula)\n(Hval: valid_formula sigma (iter_flet vs f)):\n(valid_formula sigma f) /\\\n(Forall (fun x => term_has_type sigma (snd x) (snd (fst x))) vs).\nProof.\n  induction vs; simpl in *; auto.\n  inversion Hval; subst. specialize (IHvs H4).\n  split_all; auto.\nQed.\n\nLemma iter_flet_val (vv: @val_vars sigma pd vt) \n  (vs: list (vsymbol * term)) (f: formula)\n  (Hval: valid_formula sigma f)\n  (Hall: Forall (fun x => term_has_type sigma (snd x) (snd (fst x))) vs) :\n  formula_rep pf vv (iter_flet vs f) \n    (iter_flet_valid vs f Hval Hall) =\n  formula_rep pf (substi_multi_let vv vs Hall) f Hval.\nProof.\n  generalize dependent (iter_flet_valid vs f Hval Hall).\n  revert vv.\n  induction vs; intros vv Hval'; simpl.\n  - apply fmla_rep_irrel.\n  - destruct a. simpl.\n    inversion Hall; subst.\n    rewrite (IHvs (Forall_inv_tail Hall)).\n    f_equal.\n    (*Separately, show that substi_multi_let irrelevant\n      in choice of proofs*)\n      clear.\n      erewrite term_rep_irrel. reflexivity.\nQed.\n\nDefinition iter_fand (l: list formula) : formula :=\n    fold_right (fun f acc => Fbinop Tand f acc) Ftrue l.\n\nLemma iter_fand_valid (l: list formula) \n  (Hall: Forall (valid_formula sigma) l) :\n  valid_formula sigma (iter_fand l).\nProof.\n  induction l; simpl; constructor; inversion Hall; subst; auto.\nQed.\n\nLemma iter_fand_rep (vv: val_vars pd vt) \n(l: list formula)\n(Hall: valid_formula sigma (iter_fand l)) :\nformula_rep pf vv (iter_fand l) Hall <->\n(forall (f: formula) (Hvalf: valid_formula sigma f),\n  In f l -> formula_rep pf vv f Hvalf).\nProof.\n  revert Hall.\n  induction l; simpl; intros; auto; split; intros; auto.\n  - simpl in H. unfold is_true in H. rewrite andb_true_iff in H.\n    destruct H.\n    destruct H0; subst.\n    + erewrite fmla_rep_irrel. apply H.\n    + inversion Hall; subst.\n      specialize (IHl H7).\n      apply IHl; auto.\n      erewrite fmla_rep_irrel. apply H1.\n  - inversion Hall; subst.\n    specialize (IHl H5).\n    apply andb_true_iff. split.\n    + erewrite fmla_rep_irrel. apply H. auto.\n    + erewrite fmla_rep_irrel. apply IHl. intros.\n      apply H. right; auto.\n      Unshelve.\n      auto.\nQed.\n\nEnd Iter.\n\n(*Some other results we need for IndProp*)\n\n(*true -> P is equivalent to P*)\nLemma true_impl (vv: val_vars pd vt) (f: formula) (Hval1: valid_formula sigma f)\n  (Hval2: valid_formula sigma (Fbinop Timplies Ftrue f)) :\n  formula_rep pf vv f Hval1 =\n  formula_rep pf vv (Fbinop Timplies Ftrue f) Hval2.\nProof.\n  simpl. apply fmla_rep_irrel.\nQed. \n\n(*(f1 /\\ f2) -> f3 is equivalent to f1 -> f2 -> f3*)\nLemma and_impl (vv: val_vars pd vt) \n  (f1 f2 f3: formula) Hval1 Hval2:\n  formula_rep pf vv (Fbinop Timplies (Fbinop Tand f1 f2) f3) Hval1 =\n  formula_rep pf vv (Fbinop Timplies f1 (Fbinop Timplies f2 f3)) Hval2.\nProof.\n  simpl. rewrite implb_curry.\n  f_equal. apply fmla_rep_irrel.\n  f_equal; apply fmla_rep_irrel.\nQed.\n\n(*Lemma to rewrite both a term/formula and a proof at once*)\nLemma fmla_rewrite vv (f1 f2: formula) (Heq: f1 = f2)\n  (Hval1: valid_formula sigma f1)\n  (Hval2: valid_formula sigma f2):\n  formula_rep pf vv f1 Hval1 = formula_rep pf vv f2 Hval2.\nProof.\n  subst. apply fmla_rep_irrel.\nQed.\n\nLemma bool_of_binop_impl: forall b1 b2,\n  bool_of_binop Timplies b1 b2 = all_dec (b1 -> b2).\nProof.\n  intros. destruct b1; destruct b2; simpl;\n  match goal with |- context[ all_dec ?P ] => destruct (all_dec P); auto end;\n  exfalso; apply n; auto.\nQed.\n\n(*Some larger transformations we need for IndProp - TODO maybe\n  move somewhere else*)\n\n(*We can push an implication across a forall if no free variables\n  become bound*)\nLemma distr_impl_forall\n(vv: @val_vars sigma pd vt)  \n(f1 f2: formula) (x: vsymbol)\n(Hval1: valid_formula sigma (Fbinop Timplies f1 (Fquant Tforall x f2)))\n(Hval2: valid_formula sigma (Fquant Tforall x (Fbinop Timplies f1 f2))):\n~In x (form_fv f1) ->\nformula_rep pf vv\n  (Fbinop Timplies f1 (Fquant Tforall x f2)) Hval1 =\nformula_rep pf vv\n  (Fquant Tforall x (Fbinop Timplies f1 f2)) Hval2.\nProof.\n  intros Hnotin. simpl. rewrite bool_of_binop_impl.\n  apply all_dec_eq. split; intros.\n  - rewrite bool_of_binop_impl, simpl_all_dec.\n    intros. \n    assert (formula_rep pf vv f1 (proj1 (valid_binop_inj Hval1))). {\n      erewrite form_fv_agree. erewrite fmla_rep_irrel. apply H0.\n      intros. unfold substi.\n      destruct (vsymbol_eq_dec x0 x); subst; auto. contradiction.\n    }\n    specialize (H H1).\n    rewrite simpl_all_dec in H.\n    specialize (H d).\n    erewrite fmla_rep_irrel. apply H.\n  - rewrite simpl_all_dec. intros d.\n    specialize (H d).\n    revert H. rewrite bool_of_binop_impl, simpl_all_dec;\n    intros.\n    erewrite fmla_rep_irrel.\n    apply H. erewrite form_fv_agree. erewrite fmla_rep_irrel. apply H0.\n    intros. unfold substi. destruct (vsymbol_eq_dec x0 x); subst; auto.\n    contradiction.\nQed.\n\n(*We can push an implication across a let, again assuming no\n  free variables become bound*)\nLemma distr_impl_let (vv: @val_vars sigma pd vt)  \n(f1 f2: formula) (t: term) (x: vsymbol)\n(Hval1: valid_formula sigma (Fbinop Timplies f1 (Flet t x f2)))\n(Hval2: valid_formula sigma (Flet t x (Fbinop Timplies f1 f2))):\n~In x (form_fv f1) ->\nformula_rep pf vv\n  (Fbinop Timplies f1 (Flet t x f2)) Hval1 =\nformula_rep pf vv\n  (Flet t x (Fbinop Timplies f1 f2)) Hval2.\nProof.\n  intros. simpl. rewrite !bool_of_binop_impl.\n  apply all_dec_eq.\n  erewrite form_fv_agree.\n  erewrite (form_fv_agree f2).\n  erewrite fmla_rep_irrel.\n  erewrite (fmla_rep_irrel f2).\n  reflexivity.\n  all: intros; unfold substi;\n  destruct (vsymbol_eq_dec x0 x); subst; auto; try contradiction.\n  unfold eq_rec_r; simpl.\n  apply term_rep_irrel.\nQed.\n  \n\n(*If the formula is wf, we can move an implication\n  across lets and foralls *)\nLemma distr_impl_let_forall (vv: @val_vars sigma pd vt)  \n  (f1 f2: formula)\n  (q: list vsymbol) (l: list (vsymbol * term))\n  (Hval1: valid_formula sigma (fforalls q (iter_flet l (Fbinop Timplies f1 f2))))\n  (Hval2: valid_formula sigma (Fbinop Timplies f1 (fforalls q (iter_flet l f2))))\n  (Hq: forall x, ~ (In x q /\\ In x (form_fv f1)))\n  (Hl: forall x, ~ (In x l /\\ In (fst x) (form_fv f1))) :\n  formula_rep pf vv\n    (fforalls q (iter_flet l (Fbinop Timplies f1 f2))) Hval1 =\n  formula_rep pf vv\n    (Fbinop Timplies f1 (fforalls q (iter_flet l f2))) Hval2.\nProof.\n  revert vv.\n  induction q.\n  - (*Prove let case here*)\n    induction l; auto.\n    + simpl; intros. erewrite fmla_rep_irrel.\n      erewrite (fmla_rep_irrel f2).\n      reflexivity.\n    + intros. simpl fforalls. erewrite distr_impl_let.\n      * rewrite !formula_rep_equation_9. cbv zeta.\n        erewrite IHl.\n        f_equal. f_equal. apply term_rep_irrel.\n        intros x C. apply (Hl x). split_all; auto. right; auto.\n        (*Go back and do [valid_formula]*)\n        Unshelve.\n        simpl in Hval1. simpl in Hval2.\n        inversion Hval1; subst.\n        constructor; auto.\n        inversion Hval2; subst.\n        constructor; auto.\n        inversion H6; subst; auto.\n      * intro C. apply (Hl a). split_all; auto. left; auto.\n  - intros vv. simpl fforalls.\n    erewrite distr_impl_forall.\n    + rewrite !formula_rep_equation_2; cbv zeta. \n      apply all_dec_eq.\n      split; intros.\n      * erewrite  <- IHq. apply H.\n        intros. intro C. apply (Hq x). split_all; auto.\n        right; auto.\n      * erewrite IHq. apply H. intros. intro C. apply (Hq x).\n        split_all; auto. right; auto.\n        (*Go back and do [valid_formula]*)\n        Unshelve.\n        simpl in Hval1; simpl in Hval2; inversion Hval1; \n        inversion Hval2; subst.\n        constructor; auto. constructor; auto.\n        inversion H10; subst. auto.\n    + intro C.\n      apply (Hq a). split; auto. left; auto.\nQed.\n\n(*Kind of a silly lemma, but we need to be able\n  to rewrite the first of an implication without\n  unfolding all bound variables\n  *)\nLemma and_impl_bound  (vv: @val_vars sigma pd vt)  \n(f1 f2 f3: formula)\n(q: list vsymbol) (l: list (vsymbol * term))\nHval1 Hval2: \nformula_rep pf vv\n  (fforalls q (iter_flet l (Fbinop Timplies (Fbinop Tand f1 f2) f3))) Hval1 =\nformula_rep pf vv\n  (fforalls q (iter_flet l (Fbinop Timplies f1 (Fbinop Timplies f2 f3)))) Hval2.\nProof.\n  assert (A:=Hval1).\n  assert (B:=Hval2).\n  apply fforalls_valid_inj in A.\n  apply fforalls_valid_inj in B. split_all.\n  rewrite (fforalls_val') with(Hval1:=H1).\n  rewrite (fforalls_val') with(Hval1:=H).\n  assert (A:=H1).\n  apply iter_flet_valid_inj in A.\n  assert (B:=H).\n  apply iter_flet_valid_inj in B.\n  split_all.\n  apply all_dec_eq. split; intros Hrep h.\n  - specialize (Hrep h).\n    rewrite fmla_rep_irrel with (Hval1:=H) \n      (Hval2:=iter_flet_valid  l _ H3 H4).\n    rewrite fmla_rep_irrel with (Hval1:=H1)\n      (Hval2:=iter_flet_valid l _ H5 H4) in Hrep.\n    revert Hrep. rewrite !iter_flet_val.\n    rewrite and_impl with(Hval2:=H3).\n    intros C; apply C.\n  - specialize (Hrep h).\n    rewrite fmla_rep_irrel with (Hval1:=H) \n      (Hval2:=iter_flet_valid  l _ H3 H4) in Hrep.\n    rewrite fmla_rep_irrel with (Hval1:=H1)\n      (Hval2:=iter_flet_valid l _ H5 H4).\n    revert Hrep. rewrite !iter_flet_val.\n    rewrite and_impl with(Hval2:=H3).\n    intros C; apply C.\nQed.\n\n(*Last (I hope) intermediate lemma: we can\n  push a let outside of foralls if the variable does not\n  appear quantified and no free variables in the term appear in\n  the list either*)\nLemma distr_let_foralls (vv: @val_vars sigma pd vt)  \n(t: term) (x: vsymbol) (f: formula)\n(q: list vsymbol) Hval1 Hval2:\n(~ In x q) ->\n(forall y, In y (term_fv t) -> ~ In y q) ->\nformula_rep pf vv (fforalls q (Flet t x f)) Hval1 =\nformula_rep pf vv (Flet t x (fforalls q f)) Hval2.\nProof.\n  intros. revert vv. induction q; intros vv.\n  - simpl fforalls. apply fmla_rep_irrel.\n  - simpl fforalls. simpl. (*Here, we prove the single transformation*)\n    assert (Hval3: valid_formula sigma (Flet t x (fforalls q f))). {\n        simpl in Hval2. inversion Hval2; subst.\n        inversion H6; subst. constructor; auto.\n      }\n    assert (Hnotx: ~ In x q). {\n      intro C. apply H. right; auto.\n    }\n    assert (Hinq: forall y : vsymbol, In y (term_fv t) -> ~ In y q). {\n      intros y Hy C. apply (H0 y); auto. right; auto.\n    }\n    apply all_dec_eq. split; intros Hrep d; specialize (Hrep d).\n    + rewrite IHq with (Hval2:=Hval3) in Hrep; auto.\n      simpl in Hrep.\n      rewrite substi_diff.\n      rewrite term_rep_irrel with(Hty2:=(proj1 (valid_let_inj Hval3))).\n      rewrite fmla_rep_irrel with (Hval2:=(proj2 (valid_let_inj Hval3))).\n      erewrite term_fv_agree in Hrep. apply Hrep.\n      intros. unfold substi. destruct (vsymbol_eq_dec x0 a); subst; auto.\n      exfalso. apply (H0 a); auto. left; auto.\n      intro; subst. apply H. left; auto.\n    + rewrite IHq with (Hval2:=Hval3); auto.\n      simpl.\n      rewrite substi_diff.\n      rewrite term_rep_irrel with(Hty2:=(proj1 (valid_let_inj Hval2))).\n      rewrite fmla_rep_irrel with (Hval2:=(valid_quant_inj\n         (proj2 (valid_let_inj Hval2)))).\n      erewrite term_fv_agree in Hrep. apply Hrep.\n      intros. unfold substi. destruct (vsymbol_eq_dec x0 a); subst; auto.\n      exfalso. apply (H0 a); auto. left; auto.\n      intro; subst. apply H. left; auto.\nQed.\n\n(*We need to generalize pf below*)\nEnd Lemmas.\n\n(*Suppose we have a term/fmla and 2 pi_funpreds which agree\n  on all predicates that are used. Then, their interp is equiv*)\n(*This proof is not interesting, since we never adjust the\n  pre-interp like we do the valuation. We just need to push through\n  the induction*)\nLemma pi_predsym_agree (t: term) (f: formula) :\n(forall (p1 p2: pi_funpred gamma_valid pd) \n  (v: val_vars pd vt) (ty: vty) \n  (Hty: term_has_type sigma t ty),\n  (forall p, predsym_in_term p t -> \n    preds gamma_valid pd p1 p = preds gamma_valid pd p2 p) ->\n  (forall f, funs gamma_valid pd p1 f = funs gamma_valid pd p2 f) ->\n  term_rep p1 v t ty Hty = term_rep p2 v t ty Hty) /\\\n(forall (p1 p2: pi_funpred gamma_valid pd) (v: val_vars pd vt) \n  (Hval: valid_formula sigma f),\n  (forall p, predsym_in p f -> \n    preds gamma_valid pd p1 p = preds gamma_valid pd p2 p) ->\n  (forall f, funs gamma_valid pd p1 f = funs gamma_valid pd p2 f) ->\n  formula_rep p1 v f Hval = formula_rep p2 v f Hval).\nProof.\n  revert t f.\n  apply term_formula_ind; intros; simpl_rep_full; auto.\n  - rewrite H1. f_equal. f_equal. f_equal.\n    apply get_arg_list_eq.\n    revert H; rewrite !Forall_forall; intros.\n    rewrite (term_rep_irrel) with(Hty2:=Hty2).\n    apply H; auto.\n    intros p Hinp.\n    apply H0. apply existsb_exists. exists x; auto. \n  - erewrite H. apply H0; auto. all: auto.\n    all: intros; apply H1; simpl; rewrite H3; auto.\n    rewrite orb_true_r. auto.\n  - erewrite H. erewrite H1. erewrite H0. reflexivity.\n    all: auto.\n    all: intros p Hinp; apply H2; simpl; rewrite Hinp; simpl; auto;\n    rewrite orb_true_r; auto.\n  - (*match*) \n    iter_match_gen Hty Htm Hpat Hty.\n    revert v0.\n    induction ps; simpl; intros; auto.\n    destruct a as [pat1 t1]; simpl.\n    rewrite H with(p2:=p2) at 1; auto.\n    destruct (match_val_single vt v pat1 (Forall_inv Hpat) \n      (term_rep p2 v0 tm v Hty)) eqn : Hm.\n    + inversion H0; subst.\n      apply H5; auto.\n      intros. apply H1. simpl. rewrite H3; simpl. \n      rewrite orb_true_r; auto.\n    + apply IHps; auto.\n      * inversion H0; subst; auto.\n      * intros. apply H1. simpl.\n        rewrite orb_assoc, (orb_comm (predsym_in_term p tm)), <- orb_assoc, H3,\n        orb_true_r; auto.\n    + intros. apply H1. simpl. rewrite H3; auto.\n  - f_equal. apply functional_extensionality_dep.\n    intros. erewrite H. reflexivity. all: auto.\n  - (*Here, we use fact that predsym in*)\n    rewrite H0; simpl; [|destruct (predsym_eq_dec p p); auto; contradiction].\n    f_equal.\n    apply get_arg_list_eq.\n    revert H; rewrite !Forall_forall; intros.\n    rewrite (term_rep_irrel) with(Hty2:=Hty2).\n    apply H; auto.\n    intros p' Hinp'.\n    apply H0. apply orb_true_iff. right. \n    apply existsb_exists. exists x; auto. \n  - destruct q; apply all_dec_eq.\n    + split; intros Hall d; specialize (Hall d);\n      erewrite H; try apply Hall; auto.\n      intros. rewrite H0; auto.\n    + split; intros [d Hall]; exists d;\n      erewrite H; try apply Hall; auto.\n      intros. rewrite H0; auto.\n  - erewrite H. erewrite H0. reflexivity.\n    all: auto. all: intros; apply H1; simpl; rewrite H3; auto;\n    rewrite orb_true_r; auto.\n  - erewrite H. erewrite H0. reflexivity.\n    all: auto. all: intros p Hinp; apply H1; simpl; rewrite Hinp; auto;\n    rewrite orb_true_r; auto.\n  - erewrite H; auto.\n  - erewrite H. apply H0.\n    all: auto. all: intros p Hinp; apply H1; simpl; rewrite Hinp; auto;\n    rewrite orb_true_r; auto.\n  - erewrite H. erewrite H0. erewrite H1. reflexivity.\n    all: auto. all: intros p Hinp; apply H2; simpl; rewrite Hinp; auto;\n    rewrite !orb_true_r; auto.\n  - (*match*) \n    iter_match_gen Hval Htm Hpat Hty.\n    revert v0.\n    induction ps; simpl; intros; auto.\n    destruct a as [pat1 f1]; simpl.\n    rewrite H with(p2:=p2) at 1; auto.\n    destruct (match_val_single vt v pat1 (Forall_inv Hpat) \n      (term_rep p2 v0 tm v Hty)) eqn : Hm.\n    + inversion H0; subst.\n      apply H5; auto.\n      intros. apply H1. simpl. rewrite H3; simpl. \n      rewrite orb_true_r; auto.\n    + apply IHps; auto.\n      * inversion H0; subst; auto.\n      * intros. apply H1. simpl.\n        rewrite orb_assoc, (orb_comm (predsym_in_term p tm)), <- orb_assoc, H3,\n        orb_true_r; auto.\n    + intros. apply H1. simpl. rewrite H3; auto.\nQed.\n\nDefinition term_predsym_agree t := proj_tm pi_predsym_agree t.\nDefinition fmla_predsym_agree f := proj_fmla pi_predsym_agree f.\n\nEnd Denot.\n\n(*We give the tactics for other files - TODO: can we\n  reduce duplication?*)\n\n(*We want these in the rest of the file*)\nLtac simpl_rep :=\n  repeat match goal with\n  | |- context [term_rep ?valid ?pd ?unif ?vt ?pf ?v ?t ?ty ?Hty] =>\n    lazymatch t with\n    | Tconst (ConstInt ?z) => rewrite term_rep_equation_1\n    | Tconst (ConstReal ?r) => rewrite term_rep_equation_2\n    | Tvar ?v => rewrite term_rep_equation_3\n    | Tfun ?f ?l1 ?l2 => rewrite term_rep_equation_4\n    | Tlet ?t1 ?v ?t2 => rewrite term_rep_equation_5\n    | Tif ?f ?t1 ?t2 => rewrite term_rep_equation_6\n    | Tmatch ?t ?v ?ps => rewrite term_rep_equation_7\n    | Teps ?f ?v => rewrite term_rep_equation_8\n    end\n  | |- context [formula_rep ?valid ?pd ?unif ?vt ?pf ?v ?f ?Hval] =>\n    lazymatch f with\n    | Fpred ?p ?vs ?ts => rewrite formula_rep_equation_1\n    | Fquant Tforall ?x ?f' => rewrite formula_rep_equation_2\n    | Fquant Texists ?x ?f' => rewrite formula_rep_equation_3\n    | Feq ?ty ?t1 ?t2 => rewrite formula_rep_equation_4\n    | Fbinop ?b ?f1 ?f2 => rewrite formula_rep_equation_5\n    | Fnot ?f => rewrite formula_rep_equation_6\n    | Ftrue => rewrite formula_rep_equation_7\n    | Ffalse => rewrite formula_rep_equation_8\n    | Flet ?t ?x ?f' => rewrite formula_rep_equation_9\n    | Fif ?f1 ?f2 ?f3 => rewrite formula_rep_equation_10\n    | Fmatch ?t ?ty1 ?xs => rewrite formula_rep_equation_11\n    end\n  end.\n\nLtac simpl_rep_full :=\n  repeat (simpl_rep; cbv zeta; simpl).\n\n(*TODO: see about ltac here also*)\nLtac iter_match_gen Hval Htm Hpat Hty :=\n  match type of Hval with\n  | term_has_type ?s ?t ?ty =>\n    generalize dependent (proj1 (ty_match_inv Hval));\n    generalize dependent (proj1 (proj2 (ty_match_inv Hval)));\n    generalize dependent (proj2 (proj2 (ty_match_inv Hval)))\n  | valid_formula ?s ?f =>\n    generalize dependent (proj1 (valid_match_inv Hval));\n    generalize dependent (proj1 (proj2 (valid_match_inv Hval)));\n    generalize dependent (proj2 (proj2 (valid_match_inv Hval)))\n  end;\n  clear Hval;\n  intros Htm Hpat Hty;\n  revert Htm Hpat Hty.", "meta": {"author": "joscoh", "repo": "why3-semantics", "sha": "d4d1801e43728a599ffd5442e3b6701797e61774", "save_path": "github-repos/coq/joscoh-why3-semantics", "path": "github-repos/coq/joscoh-why3-semantics/why3-semantics-d4d1801e43728a599ffd5442e3b6701797e61774/proofs/core/Denotational.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2861149859870968}}
{"text": "Require Import String.\nRequire Import Bool.\nRequire Import core.utils.Utils.\nRequire Import core.modeling.Metamodel.\nRequire Import core.Model.\nRequire Import core.modeling.ModelingEngine.\nRequire Import core.modeling.twophases.TwoPhaseEngine.\nRequire Import core.Syntax.\nRequire Import core.Semantics.\nRequire Import core.modeling.ModelingCertification.\nRequire Import core.modeling.twophases.TwoPhaseSemantics.\nRequire Import Coq.Logic.FunctionalExtensionality.\n\n\nSection TwoPhaseCertification.\n\nContext {tc: TransformationConfiguration} {mtc: ModelingTransformationConfiguration tc}. \n(** EXECUTE TRACE *)\n\nLemma tr_executeTraces_in_elements :\nforall (tr: Transformation) (sm : SourceModel) (te : TargetModelElement),\n      In te (allModelElements (executeTraces tr sm)) <->\n      (exists (tl : TraceLink) (sp : list SourceModelElement),\n          In sp (allTuples tr sm) /\\\n          In tl (tracePattern tr sm sp) /\\\n          te = TraceLink_getTargetElement tl).\nProof.\n  intros.\n  split.\n  + intro. \n    assert (exists (tl : TraceLink),\n                In tl (trace tr sm) /\\\n                te = (TraceLink_getTargetElement tl) ).\n    { simpl in H.\n          induction (trace tr sm).\n          ++ crush.\n          ++ intros.\n              simpl in H.\n              destruct H. \n              +++ exists a.\n                  crush.\n              +++ specialize (IHl H).\n                  destruct IHl.\n                  exists x.\n                  crush. }\n    destruct H0.\n    destruct H0.\n    assert (exists (sp : list SourceModelElement),\n                In sp (allTuples tr sm) /\\\n                In x (tracePattern tr sm sp)).\n    { apply in_flat_map. crush. }\n    destruct H2.\n    destruct H2.\n    exists x. exists x0.\n    crush.\n  + intros.\n    destruct H. \n    destruct H.\n    destruct H.\n    destruct H0.\n    rewrite H1.\n    apply in_map.\n    apply in_flat_map.\n    exists x0.\n    split. \n    ++ exact H.\n    ++ exact H0.\nQed. \n\nLemma tr_executeTraces_in_links :\nforall (tr: Transformation) (sm : SourceModel) (tl : TargetModelLink),\n      In tl (allModelLinks (executeTraces tr sm)) <->\n          (exists (sp : list SourceModelElement),\n          In sp (allTuples tr sm) /\\\n          In tl (applyPatternTraces tr sm sp (trace tr sm))).\nProof.\n  intros.\n  split.\n  - simpl. intro.\n    apply in_flat_map in H.\n    destruct H.\n    exists x.\n    crush.\n  - intro.\n    apply in_flat_map.\n    crush.\nQed.\n\n(** Instantiate *)\n\n(* Please check the lemma formula *)\n\n\n(* These lemmas of traces are useful when we get sth like (In e traces) *)\n\nLemma tr_trace_in:\nforall (tr: Transformation) (sm : SourceModel) (tl : TraceLink),\n  In tl (trace tr sm) <->\n  (exists (sp : list SourceModelElement),\n      In sp (allTuples tr sm) /\\\n      In tl (tracePattern tr sm sp)).\nProof.\n  intros.\n  apply in_flat_map.\nQed.\n\nLemma tr_tracePattern_in:\nforall (tr: Transformation) (sm : SourceModel) (sp : list SourceModelElement) (tl : TraceLink),\n  In tl (tracePattern tr sm sp) <->\n  (exists (r:Rule),\n      In r (matchPattern tr sm sp) /\\\n      In tl (traceRuleOnPattern r sm sp)).\nProof.\n  intros.\n  apply in_flat_map.\nQed.\n\nLemma tr_traceRuleOnPattern_in:\nforall (r: Rule) (sm : SourceModel) (sp : list SourceModelElement) (tl : TraceLink),\n  In tl (traceRuleOnPattern r sm sp) <->\n  (exists (iter: nat),\n      In iter (seq 0 (evalIteratorExpr r sm sp)) /\\\n      In tl (traceIterationOnPattern r sm sp iter)).\nProof.\n  intros.\n  apply in_flat_map.\nQed.\n\nLemma tr_traceIterationOnPattern_in:\nforall (r: Rule) (sm : SourceModel) (sp : list SourceModelElement) (iter: nat) (tl : TraceLink),\n  In tl (traceIterationOnPattern r sm sp iter) <->\n  (exists (o: OutputPatternElement),\n      In o (Rule_getOutputPatternElements r) /\\\n      In tl ((fun o => optionToList (traceElementOnPattern o sm sp iter)) o)).\nProof.\n  intros.\n  apply in_flat_map.\nQed.\n\n(* TODO works inside TwoPhaseSemantics.v *)\nLemma tr_traceElementOnPattern_leaf:\nforall (o: OutputPatternElement) (sm : SourceModel) (sp : list SourceModelElement) (iter: nat) (o: OutputPatternElement) (tl : TraceLink),\n  Some tl = (traceElementOnPattern o sm sp iter) <->\n  (exists (e: TargetModelElement),\n      Some e = (instantiateElementOnPattern o sm sp iter) /\\\n      tl = (buildTraceLink (sp, iter, OutputPatternElement_getName o) e)).\nProof.\n  intros.\n  split.\n  - intros. \n    unfold traceElementOnPattern in H.\n    destruct (instantiateElementOnPattern o0 sm sp iter) eqn: e1.\n    -- exists t.\n      split. crush. crush.\n    -- crush.\n  - intros.\n    destruct H.\n    destruct H.\n    unfold traceElementOnPattern.\n    destruct (instantiateElementOnPattern o0 sm sp iter).\n    -- crush.\n    -- crush.\nQed. \n\n\n\n(** * Apply **)\n\nLemma tr_applyTraces_in :\nforall (tr: Transformation) (sm : SourceModel) (sp: list SourceModelElement) (tl : TargetModelLink) (tls: list TraceLink),\n  In tl (applyTraces tr sm tls) <->\n  (exists (sp : list SourceModelElement),\n      In sp (allTuples tr sm) /\\\n      In tl (applyPatternTraces tr sm sp tls)).\nProof.\n  intros.\n  apply in_flat_map.\nQed.\n\nLemma tr_applyPatternTraces_in:\nforall (tr: Transformation) (sm : SourceModel) (sp: list SourceModelElement) (tl : TargetModelLink) (tls: list TraceLink),\n  In tl (applyPatternTraces tr sm sp tls) <->\n  (exists (r : Rule),\n          In r (matchPattern tr sm sp) /\\\n          In tl (applyRuleOnPatternTraces r tr sm sp tls)).\nProof.\n  intros.\n  apply in_flat_map.\nQed.\n\nLemma tr_applyRuleOnPatternTraces_in : \nforall (tr: Transformation) (r : Rule) (sm : SourceModel) (sp: list SourceModelElement) (tl : TargetModelLink) (tls: list TraceLink),\n    In tl (applyRuleOnPatternTraces r tr sm sp tls) <->\n    (exists (i: nat),\n        In i (seq 0 (evalIteratorExpr r sm sp)) /\\\n        In tl (applyIterationOnPatternTraces r tr sm sp i tls)).\nProof.\n  intros.\n  apply in_flat_map.\nQed.\n\nLemma tr_applyIterationOnPatternTraces_in : \n    forall (tr: Transformation) (r : Rule) (sm : SourceModel) (sp: list SourceModelElement) (tl : TargetModelLink) (i:nat)  (tls: list TraceLink),\n      In tl (applyIterationOnPatternTraces r tr sm sp i tls) <->\n      (exists (ope: OutputPatternElement),\n          In ope (Rule_getOutputPatternElements r) /\\ \n          In tl (applyElementOnPatternTraces ope tr sm sp i tls)).\nProof.\n  intros.\n  apply in_flat_map.\nQed.\n\nLemma tr_applyElementOnPatternTraces_in : \n    forall (tr: Transformation) (sm : SourceModel) (sp: list SourceModelElement) (tl : TargetModelLink) \n            (i:nat) (ope: OutputPatternElement)  (tls: list TraceLink),\n      In tl (applyElementOnPatternTraces ope tr sm sp i tls) <->\n      (exists (oper: OutputPatternLink) (te: TargetModelElement),\n          In oper (OutputPatternElement_getOutputLinks ope) /\\ \n          (evalOutputPatternElementExpr sm sp i ope) = Some te /\\\n          applyLinkOnPatternTraces oper tr sm sp i te tls = Some tl).\nProof.\n  split.\n  * intros.\n    apply in_flat_map in H.\n    destruct H.\n    exists x.\n    unfold optionToList in H.\n    destruct H.\n    destruct (evalOutputPatternElementExpr sm sp i ope) eqn: eval_ca.\n    - destruct (applyLinkOnPatternTraces x tr sm sp i t) eqn: ref_ca.\n      -- eexists t.\n          split; crush.\n      -- contradiction.\n    - contradiction.\n  * intros.\n    apply in_flat_map.\n    destruct H.\n    exists x.\n    unfold optionToList.\n    destruct H.\n    destruct H.\n    destruct H0.\n    split.\n    - assumption.\n    - crush.\nQed.\n\nLemma tr_applyLinkOnPatternTraces_leaf : \n    forall (oper: OutputPatternLink)\n            (tr: Transformation)\n            (sm: SourceModel)\n            (sp: list SourceModelElement) (iter: nat) (te: TargetModelElement) (tls: list TraceLink),\n      applyLinkOnPatternTraces oper tr sm sp iter te tls  = evalOutputPatternLinkExpr sm sp te iter tls oper.\nProof.\n  crush.\nQed.\n\nTheorem exe_preserv : \n  forall (tr: Transformation) (sm : SourceModel),\n    core.modeling.twophases.TwoPhaseSemantics.executeTraces tr sm = core.Semantics.execute tr sm.\nProof.\n  intros.\n  unfold core.Semantics.execute, executeTraces. simpl.\n  f_equal.\n\n  unfold trace.\n  rewrite flat_map_concat_map. rewrite flat_map_concat_map.\n  rewrite concat_map. f_equal.\n  rewrite map_map. f_equal.\n\n  unfold tracePattern, Semantics.instantiatePattern.\n  apply functional_extensionality. intros.\n  rewrite flat_map_concat_map. rewrite flat_map_concat_map.\n  rewrite concat_map. f_equal.\n  rewrite map_map. f_equal.\n\n  unfold traceRuleOnPattern, Semantics.instantiateRuleOnPattern.\n  apply functional_extensionality. intros.\n  rewrite flat_map_concat_map. rewrite flat_map_concat_map.\n  rewrite concat_map. f_equal.\n  rewrite map_map. f_equal.\n\n  unfold traceIterationOnPattern, Semantics.instantiateIterationOnPattern.\n  apply functional_extensionality. intros.\n  rewrite flat_map_concat_map. rewrite flat_map_concat_map.\n  rewrite concat_map. f_equal.\n  rewrite map_map. f_equal.\n\n  unfold traceElementOnPattern.\n  apply functional_extensionality. intros.\n  (* TODO FACTOR OUT *)\n  assert ((Semantics.instantiateElementOnPattern x2 sm x x1) = (instantiateElementOnPattern x2 sm x x1)).\n  { crush. }\n  destruct (instantiateElementOnPattern x2 sm x x1). \n  reflexivity. reflexivity.  \nQed. \n\nLemma tr_execute_in_elements' :\nforall (tr: Transformation) (sm : SourceModel) (te : TargetModelElement),\n  In te (allModelElements (executeTraces tr sm)) <->\n  (exists (sp : list SourceModelElement),\n      In sp (allTuples tr sm) /\\\n      In te (instantiatePattern tr sm sp)).\nProof.\n  intros.\n  assert ((executeTraces tr sm) = (execute tr sm)). { apply exe_preserv. }\n  rewrite H.\n  specialize (Certification.tr_execute_in_elements tr sm te).\n  crush.\nQed.\n\nLemma tr_execute_in_links' :\nforall (tr: Transformation) (sm : SourceModel) (tl : TargetModelLink),\n  In tl (allModelLinks (executeTraces tr sm)) <->\n  (exists (sp : list SourceModelElement),\n      In sp (allTuples tr sm) /\\\n      In tl (applyPattern tr sm sp)).\nProof.\n  intros.\n  assert ((executeTraces tr sm) = (execute tr sm)). { apply exe_preserv. }\n  rewrite H.\n  specialize (Certification.tr_execute_in_links tr sm tl).\n  crush.\nQed.\n\n(*Instance TwoPhaseCoqTLEngine :\nTransformationEngineModeling (@ModelingCoqTLEngine SourceModelElement SourceModelLink TargetModelElement TargetModelLink):=\n{\n  SourceModelClass := SourceModelClass;\n  SourceModelReference := SourceModelReference;\n  TargetModelClass := TargetModelClass;\n  TargetModelReference := TargetModelReference;\n\n  resolveAll := resolveAllIter;\n  resolve := resolveIter;\n\n  (* lemmas *)\n\n  tr_resolveAll_in := tr_resolveAllIter_in;\n  tr_resolve_Leaf := tr_resolveIter_leaf;\n}. \n\nInstance CoqTLEngine :\n  TransformationEngine :=\n  {\n    SourceModelElement := SourceModelElement;\n    SourceModelClass := SourceModelClass;\n    SourceModelLink := SourceModelLink;\n    SourceModelReference := SourceModelReference;\n    TargetModelElement := TargetModelElement;\n    TargetModelClass := TargetModelClass;\n    TargetModelLink := TargetModelLink;\n    TargetModelReference := TargetModelReference;\n\n    (* syntax and accessors *)\n\n    Transformation := Transformation;\n    Rule := Rule;\n    OutputPatternElement := OutputPatternElement;\n    OutputPatternLink := OutputPatternLink;\n\n    TraceLink := TraceLink;\n\n    Transformation_getRules := Transformation_getRules;\n\n    Rule_getInTypes := Rule_getInTypes;\n    Rule_getOutputPatternElements := Rule_getOutputPatternElements;\n\n    OutputPatternElement_getOutputLinks := OutputPatternElement_getOutputLinks;\n\n    TraceLink_getSourcePattern := TraceLink_getSourcePattern;\n    TraceLink_getIterator := TraceLink_getIterator;\n    TraceLink_getName := TraceLink_getName;\n    TraceLink_getTargetElement := TraceLink_getTargetElement;\n\n    (* semantic functions *)\n\n    execute := executeTraces;\n\n    matchPattern := matchPattern;\n    matchRuleOnPattern := matchRuleOnPattern;\n\n    instantiatePattern := instantiatePattern;\n    instantiateRuleOnPattern := instantiateRuleOnPattern;\n    instantiateIterationOnPattern := instantiateIterationOnPattern;\n    instantiateElementOnPattern := instantiateElementOnPattern;\n\n    applyPattern := applyPattern;\n    applyRuleOnPattern := applyRuleOnPattern;\n    applyIterationOnPattern := applyIterationOnPattern;\n    applyElementOnPattern := applyElementOnPattern;\n    applyLinkOnPattern := applyLinkOnPattern;\n\n    evalOutputPatternElementExpr := evalOutputPatternElementExpr;\n    evalIteratorExpr := evalIteratorExpr;\n    evalOutputPatternLinkExpr := evalOutputPatternLinkExpr;\n    evalGuardExpr := evalGuardExpr;\n\n    trace := trace;\n\n    resolveAll := resolveAllIter;\n    resolve := resolveIter;\n\n    (* lemmas *)\n\n    tr_execute_in_elements := tr_execute_in_elements';\n    tr_execute_in_links := tr_execute_in_links';\n\n    tr_matchPattern_in := tr_matchPattern_in;\n    tr_matchRuleOnPattern_Leaf := tr_matchRuleOnPattern_Leaf;\n\n    tr_instantiatePattern_in := tr_instantiatePattern_in;\n    tr_instantiateRuleOnPattern_in := tr_instantiateRuleOnPattern_in;\n    tr_instantiateIterationOnPattern_in := tr_instantiateIterationOnPattern_in;\n    tr_instantiateElementOnPattern_leaf := tr_instantiateElementOnPattern_leaf;\n\n    tr_applyPattern_in := tr_applyPattern_in;\n    tr_applyRuleOnPattern_in := tr_applyRuleOnPattern_in;\n    tr_applyIterationOnPattern_in := tr_applyIterationOnPattern_in;\n    tr_applyElementOnPattern_in := tr_applyElementOnPattern_in;\n    tr_applyLinkOnPatternTraces_leaf := tr_applyLinkOnPattern_leaf;\n\n    tr_resolveAll_in := tr_resolveAllIter_in;\n    tr_resolve_Leaf := tr_resolveIter_leaf;\n\n    (*tr_matchPattern_None := tr_matchPattern_None;\n\n    tr_matchRuleOnPattern_None := tr_matchRuleOnPattern_None;\n\n    tr_instantiatePattern_non_None := tr_instantiatePattern_non_None;\n    tr_instantiatePattern_None := tr_instantiatePattern_None;\n\n    tr_instantiateRuleOnPattern_non_None := tr_instantiateRuleOnPattern_non_None;\n\n    tr_instantiateIterationOnPattern_non_None := tr_instantiateIterationOnPattern_non_None;\n\n    tr_instantiateElementOnPattern_None := tr_instantiateElementOnPattern_None;\n    tr_instantiateElementOnPattern_None_iterator := tr_instantiateElementOnPattern_None_iterator;\n\n    tr_applyPattern_non_None := tr_applyPattern_non_None;\n    tr_applyPattern_None := tr_applyPattern_None;\n\n    tr_applyRuleOnPattern_non_None := tr_applyRuleOnPattern_non_None;\n\n    tr_applyIterationOnPattern_non_None := tr_applyIterationOnPattern_non_None;\n\n    tr_applyElementOnPattern_non_None := tr_applyElementOnPattern_non_None;\n\n    tr_applyLinkOnPattern_None := tr_applyLinkOnPattern_None;\n    tr_applyLinkOnPattern_None_iterator := tr_applyLinkOnPattern_None_iterator;\n\n    tr_maxArity_in := tr_maxArity_in;\n\n    tr_instantiateElementOnPattern_Leaf := tr_instantiateElementOnPattern_Leaf;\n    tr_applyLinkOnPattern_Leaf := tr_applyLinkOnPattern_Leaf;\n    tr_matchRuleOnPattern_Leaf := tr_matchRuleOnPattern_Leaf;\n\n    tr_resolveAll_in := tr_resolveAllIter_in;\n    tr_resolve_Leaf := tr_resolveIter_Leaf';*)\n  }.*)\n\n\n(* Instance CoqTLEngineTrace :\n  (TransformationEngineTrace CoqTLEngine).\nProof.\n  eexists.\n(* tr_executeTraces_in_elements *) exact tr_executeTraces_in_elements.\n(* tr_executeTraces_in_links *) exact tr_executeTraces_in_links.\n\n(* tr_tracePattern_in *) exact tr_tracePattern_in.\n(* tr_traceRuleOnPattern_in *) exact tr_traceRuleOnPattern_in.\n(* tr_traceIterationOnPattern_in *) exact tr_traceIterationOnPattern_in.\n(* tr_traceElementOnPattern_leaf *) exact tr_traceElementOnPattern_leaf.\n\n(* tr_applyPatternTraces_in  *) exact tr_applyPatternTraces_in.\n(* tr_applyRuleOnPattern_in *) exact tr_applyRuleOnPatternTraces_in.\n(* tr_applyIterationOnPattern_in *) exact tr_applyIterationOnPatternTraces_in.\n(* tr_applyElementOnPatternTraces_in *) exact tr_applyElementOnPatternTraces_in.\n(* tr_applyLinkOnPatternTraces_leaf *) exact tr_applyLinkOnPatternTraces_leaf.\n\nQed.\n\n*)\n\nEnd TwoPhaseCertification.", "meta": {"author": "atlanmod", "repo": "coqtl", "sha": "5daf5d915b66328ae5ec48f55c44731372563c87", "save_path": "github-repos/coq/atlanmod-coqtl", "path": "github-repos/coq/atlanmod-coqtl/coqtl-5daf5d915b66328ae5ec48f55c44731372563c87/core/modeling/twophases/TwoPhaseCertification.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.28611049161321467}}
{"text": "(* -*- mode: coq; mode: visual-line -*- *)\nRequire Import HoTT.Basics HoTT.Types.\nRequire Import Modality Accessible.\n\nLocal Open Scope path_scope.\n\n\n(** * The identity modality *)\n\n(** Everything to say here is fairly trivial. *)\n\nInductive Identity_Modality : Type1\n  := purely : Identity_Modality.\n\nModule Identity_Modalities <: Modalities.\n\n  Definition Modality : Type2@{u a}\n    := Identity_Modality@{a}.\n\n  Definition O_reflector : forall (O : Modality@{u a}),\n                            Type@{i} -> Type@{i}\n    := fun O X => X.\n\n  Definition In : forall (O : Modality@{u a}),\n                             Type@{i} -> Type@{i}\n    := fun O X => Unit.\n\n  Definition O_inO : forall (O : Modality@{u a}) (T : Type@{i}),\n                               In@{u a i} O (O_reflector@{u a i} O T)\n    := fun O X => tt.\n\n  Definition to : forall (O : Modality@{u a}) (T : Type@{i}),\n                   T -> O_reflector@{u a i} O T\n    := fun O X x => x.\n\n  Definition inO_equiv_inO :\n      forall (O : Modality@{u a}) (T : Type@{i}) (U : Type@{j})\n             (T_inO : In@{u a i} O T) (f : T -> U) (feq : IsEquiv f),\n        let gei := ((fun x => x) : Type@{i} -> Type@{k}) in\n        let gej := ((fun x => x) : Type@{j} -> Type@{k}) in\n        In@{u a j} O U\n    := fun O T U _ _ _ => tt.\n\n  Definition hprop_inO@{u a i}\n  : Funext -> forall (O : Modality@{u a}) (T : Type@{i}),\n                IsHProp (In@{u a i} O T)\n    := fun _ O T => trunc_contr@{i}.\n\n  Definition O_ind_internal\n  : forall (O : Modality@{u a})\n           (A : Type@{i}) (B : O_reflector O A -> Type@{j})\n           (B_inO : forall oa, In@{u a j} O (B oa)),\n      let gei := ((fun x => x) : Type@{i} -> Type@{k}) in\n      let gej := ((fun x => x) : Type@{j} -> Type@{k}) in\n      (forall a, B (to O A a)) -> forall a, B a\n  := fun O A B _ f a => f a.\n\n  Definition O_ind_beta_internal\n  : forall (O : Modality@{u a})\n           (A : Type@{i}) (B : O_reflector O A -> Type@{j})\n           (B_inO : forall oa, In@{u a j} O (B oa))\n           (f : forall a : A, B (to O A a)) (a:A),\n      O_ind_internal O A B B_inO f (to O A a) = f a\n    := fun _ _ _ _ _ _ => 1.\n\n  Definition minO_paths\n  : forall (O : Modality@{u a})\n           (A : Type@{i}) (A_inO : In@{u a i} O A) (z z' : A),\n      In@{u a i} O (z = z')\n    := fun _ _ _ _ _ => tt.\n\n  Definition IsSepFor@{u a}\n    : forall (O' O : Modality@{u a}), Type@{u}\n    := fun _ _ => Unit.\n\n  Definition inO_paths_from_inSepO@{u a i iplus}\n    : forall (O' O : Modality@{u a}) (sep : IsSepFor O' O)\n             (A : Type@{i}) (A_inO : In@{u a i} O' A) (x y : A),\n      In@{u a i} O (x = y)\n    := fun _ _ _ _ _ _ _ => tt.\n\n  Definition inSepO_from_inO_paths@{u a i iplus}\n    : forall (O' O : Modality@{u a}) (sep : IsSepFor O' O)\n             (A : Type@{i}),\n      (forall (x y : A), In@{u a i} O (x = y)) -> In@{u a i} O' A\n    := fun _ _ _ _ _ => tt.\n\nEnd Identity_Modalities.\n\nModule purelyM := Modalities_Theory Identity_Modalities.\nExport purelyM.Coercions.\nExport purelyM.RSU.Coercions.\n\nCoercion Identity_Modalities_to_Modalities := idmap\n  : Identity_Modality -> Identity_Modalities.Modality.\n\n\nModule Accessible_Identity <: Accessible_Modalities Identity_Modalities.\n\n  Module Import Os_Theory := Modalities_Theory Identity_Modalities.\n\n  Definition acc_gen : Modality@{u a} -> NullGenerators@{a}\n    := fun _ => Build_NullGenerators Empty (fun _ => Empty).\n\n  Definition inO_iff_isnull@{u a i}\n  : forall (O : Modality@{u a}) (X : Type@{i}),\n      iff@{i i i}\n        (In@{u a i} O X)\n        (IsNull_Internal.IsNull@{a i} (acc_gen O) X)\n  := fun O X => @pair _ (_ -> Unit)\n     (fun _ => Empty_ind _)\n     (fun _ => tt).\n\nEnd Accessible_Identity.\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/Modalities/Identity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.2861104844729612}}
{"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 int.MinMax.\nRequire set.Set.\n\n(* Why3 assumption *)\nInductive list (a:Type) {a_WT:WhyType a} :=\n  | Nil : list a\n  | Cons : a -> (list a) -> list a.\nAxiom list_WhyType : forall (a:Type) {a_WT:WhyType a}, WhyType (list a).\nExisting Instance list_WhyType.\nImplicit Arguments Nil [[a] [a_WT]].\nImplicit Arguments Cons [[a] [a_WT]].\n\n(* Why3 assumption *)\nFixpoint infix_plpl {a:Type} {a_WT:WhyType a}(l1:(list a)) (l2:(list\n  a)) {struct l1}: (list a) :=\n  match l1 with\n  | Nil => l2\n  | (Cons x1 r1) => (Cons x1 (infix_plpl r1 l2))\n  end.\n\nAxiom Append_assoc : forall {a:Type} {a_WT:WhyType a}, forall (l1:(list a))\n  (l2:(list a)) (l3:(list a)), ((infix_plpl l1 (infix_plpl l2\n  l3)) = (infix_plpl (infix_plpl l1 l2) l3)).\n\nAxiom Append_l_nil : forall {a:Type} {a_WT:WhyType a}, forall (l:(list a)),\n  ((infix_plpl l (Nil :(list a))) = l).\n\n(* Why3 assumption *)\nFixpoint length {a:Type} {a_WT:WhyType a}(l:(list a)) {struct l}: Z :=\n  match l with\n  | Nil => 0%Z\n  | (Cons _ r) => (1%Z + (length r))%Z\n  end.\n\nAxiom Length_nonnegative : forall {a:Type} {a_WT:WhyType a}, forall (l:(list\n  a)), (0%Z <= (length l))%Z.\n\nAxiom Length_nil : forall {a:Type} {a_WT:WhyType a}, forall (l:(list a)),\n  ((length l) = 0%Z) <-> (l = (Nil :(list a))).\n\nAxiom Append_length : forall {a:Type} {a_WT:WhyType a}, forall (l1:(list a))\n  (l2:(list a)), ((length (infix_plpl l1\n  l2)) = ((length l1) + (length l2))%Z).\n\n(* Why3 assumption *)\nFixpoint mem {a:Type} {a_WT:WhyType a}(x:a) (l:(list a)) {struct l}: Prop :=\n  match l with\n  | Nil => False\n  | (Cons y r) => (x = y) \\/ (mem x r)\n  end.\n\nAxiom mem_append : forall {a:Type} {a_WT:WhyType a}, forall (x:a) (l1:(list\n  a)) (l2:(list a)), (mem x (infix_plpl l1 l2)) <-> ((mem x l1) \\/ (mem x\n  l2)).\n\nAxiom mem_decomp : forall {a:Type} {a_WT:WhyType a}, forall (x:a) (l:(list\n  a)), (mem x l) -> exists l1:(list a), exists l2:(list a),\n  (l = (infix_plpl l1 (Cons x l2))).\n\nAxiom map : forall (a:Type) {a_WT:WhyType a} (b:Type) {b_WT:WhyType b}, Type.\nParameter map_WhyType : forall (a:Type) {a_WT:WhyType a}\n  (b:Type) {b_WT:WhyType b}, WhyType (map a b).\nExisting Instance map_WhyType.\n\nParameter get: forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  (map a b) -> a -> b.\n\nParameter set: forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  (map a b) -> a -> b -> (map a b).\n\nAxiom Select_eq : forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  forall (m:(map a b)), forall (a1:a) (a2:a), forall (b1:b), (a1 = a2) ->\n  ((get (set m a1 b1) a2) = b1).\n\nAxiom Select_neq : forall {a:Type} {a_WT:WhyType a}\n  {b:Type} {b_WT:WhyType b}, forall (m:(map a b)), forall (a1:a) (a2:a),\n  forall (b1:b), (~ (a1 = a2)) -> ((get (set m a1 b1) a2) = (get m a2)).\n\nParameter const: forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  b -> (map a b).\n\nAxiom Const : forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  forall (b1:b) (a1:a), ((get (const b1:(map a b)) a1) = b1).\n\n(* Why3 assumption *)\nInductive datatype  :=\n  | TYunit : datatype \n  | TYint : datatype \n  | TYbool : datatype .\nAxiom datatype_WhyType : WhyType datatype.\nExisting Instance datatype_WhyType.\n\n(* Why3 assumption *)\nInductive value  :=\n  | Vvoid : value \n  | Vint : Z -> value \n  | Vbool : bool -> value .\nAxiom value_WhyType : WhyType value.\nExisting Instance value_WhyType.\n\n(* Why3 assumption *)\nInductive operator  :=\n  | Oplus : operator \n  | Ominus : operator \n  | Omult : operator \n  | Ole : operator .\nAxiom operator_WhyType : WhyType operator.\nExisting Instance operator_WhyType.\n\nAxiom mident : Type.\nParameter mident_WhyType : WhyType mident.\nExisting Instance mident_WhyType.\n\nAxiom mident_decide : forall (m1:mident) (m2:mident), (m1 = m2) \\/\n  ~ (m1 = m2).\n\n(* Why3 assumption *)\nInductive ident  :=\n  | mk_ident : Z -> ident .\nAxiom ident_WhyType : WhyType ident.\nExisting Instance ident_WhyType.\n\n(* Why3 assumption *)\nDefinition ident_index(v:ident): Z := match v with\n  | (mk_ident x) => x\n  end.\n\nParameter result: ident.\n\nAxiom ident_decide : forall (m1:ident) (m2:ident), (m1 = m2) \\/ ~ (m1 = m2).\n\n(* Why3 assumption *)\nInductive term  :=\n  | Tvalue : value -> term \n  | Tvar : ident -> term \n  | Tderef : mident -> term \n  | Tbin : term -> operator -> term -> term .\nAxiom term_WhyType : WhyType term.\nExisting Instance term_WhyType.\n\n(* Why3 assumption *)\nFixpoint var_occurs_in_term(x:ident) (t:term) {struct t}: Prop :=\n  match t with\n  | (Tvalue _) => False\n  | (Tvar i) => (x = i)\n  | (Tderef _) => False\n  | (Tbin t1 _ t2) => (var_occurs_in_term x t1) \\/ (var_occurs_in_term x t2)\n  end.\n\n(* Why3 assumption *)\nInductive fmla  :=\n  | Fterm : term -> fmla \n  | Fand : fmla -> fmla -> fmla \n  | Fnot : fmla -> fmla \n  | Fimplies : fmla -> fmla -> fmla \n  | Flet : ident -> term -> fmla -> fmla \n  | Fforall : ident -> datatype -> fmla -> fmla .\nAxiom fmla_WhyType : WhyType fmla.\nExisting Instance fmla_WhyType.\n\n(* Why3 assumption *)\nInductive expr  :=\n  | Evalue : value -> expr \n  | Ebin : expr -> operator -> expr -> expr \n  | Evar : ident -> expr \n  | Ederef : mident -> expr \n  | Eassign : mident -> expr -> expr \n  | Eseq : expr -> expr -> expr \n  | Elet : ident -> expr -> expr -> expr \n  | Eif : expr -> expr -> expr -> expr \n  | Eassert : fmla -> expr \n  | Ewhile : expr -> fmla -> expr -> expr .\nAxiom expr_WhyType : WhyType expr.\nExisting Instance expr_WhyType.\n\n(* Why3 assumption *)\nDefinition type_value(v:value): datatype :=\n  match v with\n  | Vvoid => TYunit\n  | (Vint int) => TYint\n  | (Vbool bool1) => TYbool\n  end.\n\n(* Why3 assumption *)\nInductive type_operator : operator -> datatype -> datatype\n  -> datatype -> Prop :=\n  | Type_plus : (type_operator Oplus TYint TYint TYint)\n  | Type_minus : (type_operator Ominus TYint TYint TYint)\n  | Type_mult : (type_operator Omult TYint TYint TYint)\n  | Type_le : (type_operator Ole TYint TYint TYbool).\n\n(* Why3 assumption *)\nDefinition type_stack  := (list (ident* datatype)%type).\n\nParameter get_vartype: ident -> (list (ident* datatype)%type) -> datatype.\n\nAxiom get_vartype_def : forall (i:ident) (pi:(list (ident* datatype)%type)),\n  match pi with\n  | Nil => ((get_vartype i pi) = TYunit)\n  | (Cons (x, ty) r) => ((x = i) -> ((get_vartype i pi) = ty)) /\\\n      ((~ (x = i)) -> ((get_vartype i pi) = (get_vartype i r)))\n  end.\n\n(* Why3 assumption *)\nDefinition type_env  := (map mident datatype).\n\n(* Why3 assumption *)\nInductive type_term : (map mident datatype) -> (list (ident* datatype)%type)\n  -> term -> datatype -> Prop :=\n  | Type_value : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (v:value), (type_term sigma pi (Tvalue v)\n      (type_value v))\n  | Type_var : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (v:ident) (ty:datatype), ((get_vartype v pi) = ty) ->\n      (type_term sigma pi (Tvar v) ty)\n  | Type_deref : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (v:mident) (ty:datatype), ((get sigma v) = ty) ->\n      (type_term sigma pi (Tderef v) ty)\n  | Type_bin : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (t1:term) (t2:term) (op:operator) (ty1:datatype)\n      (ty2:datatype) (ty:datatype), (type_term sigma pi t1 ty1) ->\n      ((type_term sigma pi t2 ty2) -> ((type_operator op ty1 ty2 ty) ->\n      (type_term sigma pi (Tbin t1 op t2) ty))).\n\n(* Why3 assumption *)\nInductive type_fmla : (map mident datatype) -> (list (ident* datatype)%type)\n  -> fmla -> Prop :=\n  | Type_term : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (t:term), (type_term sigma pi t TYbool) ->\n      (type_fmla sigma pi (Fterm t))\n  | Type_conj : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (f1:fmla) (f2:fmla), (type_fmla sigma pi f1) ->\n      ((type_fmla sigma pi f2) -> (type_fmla sigma pi (Fand f1 f2)))\n  | Type_neg : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (f:fmla), (type_fmla sigma pi f) -> (type_fmla sigma\n      pi (Fnot f))\n  | Type_implies : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (f1:fmla) (f2:fmla), (type_fmla sigma pi f1) ->\n      ((type_fmla sigma pi f2) -> (type_fmla sigma pi (Fimplies f1 f2)))\n  | Type_let : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (x:ident) (t:term) (f:fmla) (ty:datatype),\n      (type_term sigma pi t ty) -> ((type_fmla sigma (Cons (x, ty) pi) f) ->\n      (type_fmla sigma pi (Flet x t f)))\n  | Type_forall1 : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (x:ident) (f:fmla), (type_fmla sigma (Cons (x, TYint)\n      pi) f) -> (type_fmla sigma pi (Fforall x TYint f))\n  | Type_forall2 : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (x:ident) (f:fmla), (type_fmla sigma (Cons (x, TYbool)\n      pi) f) -> (type_fmla sigma pi (Fforall x TYbool f))\n  | Type_forall3 : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (x:ident) (f:fmla), (type_fmla sigma (Cons (x, TYunit)\n      pi) f) -> (type_fmla sigma pi (Fforall x TYunit f)).\n\n(* Why3 assumption *)\nInductive type_expr : (map mident datatype) -> (list (ident* datatype)%type)\n  -> expr -> datatype -> Prop :=\n  | Type_Evalue : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (v:value), (type_expr sigma pi (Evalue v)\n      (type_value v))\n  | Type_Evar : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (v:ident) (ty:datatype), ((get_vartype v pi) = ty) ->\n      (type_expr sigma pi (Evar v) ty)\n  | Type_Ederef : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (v:mident) (ty:datatype), ((get sigma v) = ty) ->\n      (type_expr sigma pi (Ederef v) ty)\n  | Type_Ebinop : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (e1:expr) (e2:expr) (op:operator) (ty1:datatype)\n      (ty2:datatype) (ty:datatype), (type_expr sigma pi e1 ty1) ->\n      ((type_expr sigma pi e2 ty2) -> ((type_operator op ty1 ty2 ty) ->\n      (type_expr sigma pi (Ebin e1 op e2) ty)))\n  | Type_seq : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (e1:expr) (e2:expr) (ty:datatype), (type_expr sigma pi\n      e1 TYunit) -> ((type_expr sigma pi e2 ty) -> (type_expr sigma pi\n      (Eseq e1 e2) ty))\n  | Type_assigns : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (x:mident) (e:expr) (ty:datatype), ((get sigma\n      x) = ty) -> ((type_expr sigma pi e ty) -> (type_expr sigma pi\n      (Eassign x e) TYunit))\n  | Type_if : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (t:expr) (e1:expr) (e2:expr) (ty:datatype),\n      (type_expr sigma pi t TYbool) -> ((type_expr sigma pi e1 ty) ->\n      ((type_expr sigma pi e2 ty) -> (type_expr sigma pi (Eif t e1 e2) ty)))\n  | Type_assert : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (p:fmla), (type_fmla sigma pi p) -> (type_expr sigma\n      pi (Eassert p) TYbool)\n  | Type_while : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (guard:expr) (body:expr) (inv:fmla) (ty:datatype),\n      (type_fmla sigma pi inv) -> ((type_expr sigma pi guard TYbool) ->\n      ((type_expr sigma pi body ty) -> (type_expr sigma pi (Ewhile guard inv\n      body) ty)))\n  | Type_Elet : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (x:ident) (e1:expr) (e2:expr) (ty1:datatype)\n      (ty2:datatype), (type_expr sigma pi e1 ty1) -> ((type_expr sigma\n      (Cons (x, ty1) pi) e2 ty2) -> (type_expr sigma pi (Elet x e1 e2) ty2)).\n\n(* Why3 assumption *)\nDefinition env  := (map mident value).\n\n(* Why3 assumption *)\nDefinition stack  := (list (ident* value)%type).\n\nParameter get_stack: ident -> (list (ident* value)%type) -> value.\n\nAxiom get_stack_def : forall (i:ident) (pi:(list (ident* value)%type)),\n  match pi with\n  | Nil => ((get_stack i pi) = Vvoid)\n  | (Cons (x, v) r) => ((x = i) -> ((get_stack i pi) = v)) /\\ ((~ (x = i)) ->\n      ((get_stack i pi) = (get_stack i r)))\n  end.\n\nAxiom get_stack_eq : forall (x:ident) (v:value) (r:(list (ident*\n  value)%type)), ((get_stack x (Cons (x, v) r)) = v).\n\nAxiom get_stack_neq : forall (x:ident) (i:ident) (v:value) (r:(list (ident*\n  value)%type)), (~ (x = i)) -> ((get_stack i (Cons (x, v) r)) = (get_stack i\n  r)).\n\nParameter eval_bin: value -> operator -> value -> value.\n\nAxiom eval_bin_def : forall (x:value) (op:operator) (y:value), match (x,\n  y) with\n  | ((Vint x1), (Vint y1)) =>\n      match op with\n      | Oplus => ((eval_bin x op y) = (Vint (x1 + y1)%Z))\n      | Ominus => ((eval_bin x op y) = (Vint (x1 - y1)%Z))\n      | Omult => ((eval_bin x op y) = (Vint (x1 * y1)%Z))\n      | Ole => ((x1 <= y1)%Z -> ((eval_bin x op y) = (Vbool true))) /\\\n          ((~ (x1 <= y1)%Z) -> ((eval_bin x op y) = (Vbool false)))\n      end\n  | (_, _) => ((eval_bin x op y) = Vvoid)\n  end.\n\n(* Why3 assumption *)\nFixpoint eval_term(sigma:(map mident value)) (pi:(list (ident* value)%type))\n  (t:term) {struct t}: value :=\n  match t with\n  | (Tvalue v) => v\n  | (Tvar id) => (get_stack id pi)\n  | (Tderef id) => (get sigma id)\n  | (Tbin t1 op t2) => (eval_bin (eval_term sigma pi t1) op (eval_term sigma\n      pi t2))\n  end.\n\nAxiom eval_bool_term : forall (sigma:(map mident value)) (pi:(list (ident*\n  value)%type)) (sigmat:(map mident datatype)) (pit:(list (ident*\n  datatype)%type)) (t:term), (type_term sigmat pit t TYbool) ->\n  exists b:bool, ((eval_term sigma pi t) = (Vbool b)).\n\n(* Why3 assumption *)\nFixpoint eval_fmla(sigma:(map mident value)) (pi:(list (ident* value)%type))\n  (f:fmla) {struct f}: Prop :=\n  match f with\n  | (Fterm t) => ((eval_term sigma pi t) = (Vbool true))\n  | (Fand f1 f2) => (eval_fmla sigma pi f1) /\\ (eval_fmla sigma pi f2)\n  | (Fnot f1) => ~ (eval_fmla sigma pi f1)\n  | (Fimplies f1 f2) => (eval_fmla sigma pi f1) -> (eval_fmla sigma pi f2)\n  | (Flet x t f1) => (eval_fmla sigma (Cons (x, (eval_term sigma pi t)) pi)\n      f1)\n  | (Fforall x TYint f1) => forall (n:Z), (eval_fmla sigma (Cons (x,\n      (Vint n)) pi) f1)\n  | (Fforall x TYbool f1) => forall (b:bool), (eval_fmla sigma (Cons (x,\n      (Vbool b)) pi) f1)\n  | (Fforall x TYunit f1) => (eval_fmla sigma (Cons (x, Vvoid) pi) f1)\n  end.\n\nParameter msubst_term: term -> mident -> ident -> term.\n\nAxiom msubst_term_def : forall (t:term) (r:mident) (v:ident),\n  match t with\n  | ((Tvalue _)|(Tvar _)) => ((msubst_term t r v) = t)\n  | (Tderef x) => ((r = x) -> ((msubst_term t r v) = (Tvar v))) /\\\n      ((~ (r = x)) -> ((msubst_term t r v) = t))\n  | (Tbin t1 op t2) => ((msubst_term t r v) = (Tbin (msubst_term t1 r v) op\n      (msubst_term t2 r v)))\n  end.\n\nParameter subst_term: term -> ident -> ident -> term.\n\nAxiom subst_term_def : forall (t:term) (r:ident) (v:ident),\n  match t with\n  | ((Tvalue _)|(Tderef _)) => ((subst_term t r v) = t)\n  | (Tvar x) => ((r = x) -> ((subst_term t r v) = (Tvar v))) /\\\n      ((~ (r = x)) -> ((subst_term t r v) = t))\n  | (Tbin t1 op t2) => ((subst_term t r v) = (Tbin (subst_term t1 r v) op\n      (subst_term t2 r v)))\n  end.\n\n(* Why3 assumption *)\nDefinition fresh_in_term(id:ident) (t:term): Prop := ~ (var_occurs_in_term id\n  t).\n\nAxiom fresh_in_binop : forall (t:term) (t':term) (op:operator) (v:ident),\n  (fresh_in_term v (Tbin t op t')) -> ((fresh_in_term v t) /\\\n  (fresh_in_term v t')).\n\n(* Why3 assumption *)\nFixpoint fresh_in_fmla(id:ident) (f:fmla) {struct f}: Prop :=\n  match f with\n  | (Fterm e) => (fresh_in_term id e)\n  | ((Fand f1 f2)|(Fimplies f1 f2)) => (fresh_in_fmla id f1) /\\\n      (fresh_in_fmla id f2)\n  | (Fnot f1) => (fresh_in_fmla id f1)\n  | (Flet y t f1) => (~ (id = y)) /\\ ((fresh_in_term id t) /\\\n      (fresh_in_fmla id f1))\n  | (Fforall y ty f1) => (~ (id = y)) /\\ (fresh_in_fmla id f1)\n  end.\n\n(* Why3 assumption *)\nFixpoint subst(f:fmla) (x:ident) (v:ident) {struct f}: fmla :=\n  match f with\n  | (Fterm e) => (Fterm (subst_term e x v))\n  | (Fand f1 f2) => (Fand (subst f1 x v) (subst f2 x v))\n  | (Fnot f1) => (Fnot (subst f1 x v))\n  | (Fimplies f1 f2) => (Fimplies (subst f1 x v) (subst f2 x v))\n  | (Flet y t f1) => (Flet y (subst_term t x v) (subst f1 x v))\n  | (Fforall y ty f1) => (Fforall y ty (subst f1 x v))\n  end.\n\n(* Why3 assumption *)\nFixpoint msubst(f:fmla) (x:mident) (v:ident) {struct f}: fmla :=\n  match f with\n  | (Fterm e) => (Fterm (msubst_term e x v))\n  | (Fand f1 f2) => (Fand (msubst f1 x v) (msubst f2 x v))\n  | (Fnot f1) => (Fnot (msubst f1 x v))\n  | (Fimplies f1 f2) => (Fimplies (msubst f1 x v) (msubst f2 x v))\n  | (Flet y t f1) => (Flet y (msubst_term t x v) (msubst f1 x v))\n  | (Fforall y ty f1) => (Fforall y ty (msubst f1 x v))\n  end.\n\nAxiom subst_fresh_term : forall (t:term) (x:ident) (v:ident),\n  (fresh_in_term x t) -> ((subst_term t x v) = t).\n\nAxiom subst_fresh : forall (f:fmla) (x:ident) (v:ident), (fresh_in_fmla x\n  f) -> ((subst f x v) = f).\n\nAxiom eval_msubst_term : forall (e:term) (sigma:(map mident value)) (pi:(list\n  (ident* value)%type)) (x:mident) (v:ident), (fresh_in_term v e) ->\n  ((eval_term sigma pi (msubst_term e x v)) = (eval_term (set sigma x\n  (get_stack v pi)) pi e)).\n\nAxiom eval_msubst : forall (f:fmla) (sigma:(map mident value)) (pi:(list\n  (ident* value)%type)) (x:mident) (v:ident), (fresh_in_fmla v f) ->\n  ((eval_fmla sigma pi (msubst f x v)) <-> (eval_fmla (set sigma x\n  (get_stack v pi)) pi f)).\n\nAxiom eval_swap_term : forall (t:term) (sigma:(map mident value)) (pi:(list\n  (ident* value)%type)) (l:(list (ident* value)%type)) (id1:ident)\n  (id2:ident) (v1:value) (v2:value), (~ (id1 = id2)) -> ((eval_term sigma\n  (infix_plpl l (Cons (id1, v1) (Cons (id2, v2) pi))) t) = (eval_term sigma\n  (infix_plpl l (Cons (id2, v2) (Cons (id1, v1) pi))) t)).\n\nAxiom eval_swap_term_2 : forall (t:term) (sigma:(map mident value)) (pi:(list\n  (ident* value)%type)) (id1:ident) (id2:ident) (v1:value) (v2:value),\n  (~ (id1 = id2)) -> ((eval_term sigma (Cons (id1, v1) (Cons (id2, v2) pi))\n  t) = (eval_term sigma (Cons (id2, v2) (Cons (id1, v1) pi)) t)).\n\nAxiom eval_swap : forall (f:fmla) (sigma:(map mident value)) (pi:(list\n  (ident* value)%type)) (l:(list (ident* value)%type)) (id1:ident)\n  (id2:ident) (v1:value) (v2:value), (~ (id1 = id2)) -> ((eval_fmla sigma\n  (infix_plpl l (Cons (id1, v1) (Cons (id2, v2) pi))) f) <-> (eval_fmla sigma\n  (infix_plpl l (Cons (id2, v2) (Cons (id1, v1) pi))) f)).\n\nAxiom eval_swap_2 : forall (f:fmla) (id1:ident) (id2:ident) (v1:value)\n  (v2:value), (~ (id1 = id2)) -> forall (sigma:(map mident value)) (pi:(list\n  (ident* value)%type)), (eval_fmla sigma (Cons (id1, v1) (Cons (id2, v2)\n  pi)) f) <-> (eval_fmla sigma (Cons (id2, v2) (Cons (id1, v1) pi)) f).\n\nAxiom eval_term_change_free : forall (t:term) (sigma:(map mident value))\n  (pi:(list (ident* value)%type)) (id:ident) (v:value), (fresh_in_term id\n  t) -> ((eval_term sigma (Cons (id, v) pi) t) = (eval_term sigma pi t)).\n\nAxiom eval_change_free : forall (f:fmla) (id:ident) (v:value),\n  (fresh_in_fmla id f) -> forall (sigma:(map mident value)) (pi:(list (ident*\n  value)%type)), (eval_fmla sigma (Cons (id, v) pi) f) <-> (eval_fmla sigma\n  pi f).\n\n(* Why3 assumption *)\nDefinition valid_fmla(p:fmla): Prop := forall (sigma:(map mident value))\n  (pi:(list (ident* value)%type)), (eval_fmla sigma pi p).\n\n(* Why3 assumption *)\nFixpoint fresh_in_expr(id:ident) (e:expr) {struct e}: Prop :=\n  match e with\n  | (Evalue _) => True\n  | (Ebin e1 op e2) => (fresh_in_expr id e1) /\\ (fresh_in_expr id e2)\n  | (Evar v) => ~ (id = v)\n  | (Ederef _) => True\n  | (Eassign x e1) => (fresh_in_expr id e1)\n  | (Eseq e1 e2) => (fresh_in_expr id e1) /\\ (fresh_in_expr id e2)\n  | (Elet v e1 e2) => (~ (id = v)) /\\ ((fresh_in_expr id e1) /\\\n      (fresh_in_expr id e2))\n  | (Eif e1 e2 e3) => (fresh_in_expr id e1) /\\ ((fresh_in_expr id e2) /\\\n      (fresh_in_expr id e3))\n  | (Eassert f) => (fresh_in_fmla id f)\n  | (Ewhile cond inv body) => (fresh_in_expr id cond) /\\ ((fresh_in_fmla id\n      inv) /\\ (fresh_in_expr id body))\n  end.\n\n(* Why3 assumption *)\nInductive one_step : (map mident value) -> (list (ident* value)%type) -> expr\n  -> (map mident value) -> (list (ident* value)%type) -> expr -> Prop :=\n  | one_step_var : forall (sigma:(map mident value)) (pi:(list (ident*\n      value)%type)) (v:ident), (one_step sigma pi (Evar v) sigma pi\n      (Evalue (get_stack v pi)))\n  | one_step_deref : forall (sigma:(map mident value)) (pi:(list (ident*\n      value)%type)) (v:mident), (one_step sigma pi (Ederef v) sigma pi\n      (Evalue (get sigma v)))\n  | one_step_bin_ctxt1 : forall (sigma:(map mident value)) (sigma':(map\n      mident value)) (pi:(list (ident* value)%type)) (pi':(list (ident*\n      value)%type)) (op:operator) (e1:expr) (e1':expr) (e2:expr),\n      (one_step sigma pi e1 sigma' pi' e1') -> (one_step sigma pi (Ebin e1 op\n      e2) sigma' pi' (Ebin e1' op e2))\n  | one_step_bin_ctxt2 : forall (sigma:(map mident value)) (sigma':(map\n      mident value)) (pi:(list (ident* value)%type)) (pi':(list (ident*\n      value)%type)) (op:operator) (v1:value) (e2:expr) (e2':expr),\n      (one_step sigma pi e2 sigma' pi' e2') -> (one_step sigma pi\n      (Ebin (Evalue v1) op e2) sigma' pi' (Ebin (Evalue v1) op e2'))\n  | one_step_bin_value : forall (sigma:(map mident value)) (pi:(list (ident*\n      value)%type)) (op:operator) (v1:value) (v2:value), (one_step sigma pi\n      (Ebin (Evalue v1) op (Evalue v2)) sigma pi (Evalue (eval_bin v1 op\n      v2)))\n  | one_step_assign_ctxt : forall (sigma:(map mident value)) (sigma':(map\n      mident value)) (pi:(list (ident* value)%type)) (pi':(list (ident*\n      value)%type)) (x:mident) (e:expr) (e':expr), (one_step sigma pi e\n      sigma' pi' e') -> (one_step sigma pi (Eassign x e) sigma' pi'\n      (Eassign x e'))\n  | one_step_assign_value : forall (sigma:(map mident value)) (sigma':(map\n      mident value)) (pi:(list (ident* value)%type)) (x:mident) (v:value),\n      (sigma' = (set sigma x v)) -> (one_step sigma pi (Eassign x (Evalue v))\n      sigma' pi (Evalue Vvoid))\n  | one_step_seq_ctxt : forall (sigma:(map mident value)) (sigma':(map mident\n      value)) (pi:(list (ident* value)%type)) (pi':(list (ident*\n      value)%type)) (e1:expr) (e1':expr) (e2:expr), (one_step sigma pi e1\n      sigma' pi' e1') -> (one_step sigma pi (Eseq e1 e2) sigma' pi' (Eseq e1'\n      e2))\n  | one_step_seq_value : forall (sigma:(map mident value)) (pi:(list (ident*\n      value)%type)) (e:expr), (one_step sigma pi (Eseq (Evalue Vvoid) e)\n      sigma pi e)\n  | one_step_let_ctxt : forall (sigma:(map mident value)) (sigma':(map mident\n      value)) (pi:(list (ident* value)%type)) (pi':(list (ident*\n      value)%type)) (id:ident) (e1:expr) (e1':expr) (e2:expr),\n      (one_step sigma pi e1 sigma' pi' e1') -> (one_step sigma pi (Elet id e1\n      e2) sigma' pi' (Elet id e1' e2))\n  | one_step_let_value : forall (sigma:(map mident value)) (pi:(list (ident*\n      value)%type)) (id:ident) (v:value) (e:expr), (one_step sigma pi\n      (Elet id (Evalue v) e) sigma (Cons (id, v) pi) e)\n  | one_step_if_ctxt : forall (sigma:(map mident value)) (sigma':(map mident\n      value)) (pi:(list (ident* value)%type)) (pi':(list (ident*\n      value)%type)) (e1:expr) (e1':expr) (e2:expr) (e3:expr), (one_step sigma\n      pi e1 sigma' pi' e1') -> (one_step sigma pi (Eif e1 e2 e3) sigma' pi'\n      (Eif e1' e2 e3))\n  | one_step_if_true : forall (sigma:(map mident value)) (pi:(list (ident*\n      value)%type)) (e1:expr) (e2:expr), (one_step sigma pi\n      (Eif (Evalue (Vbool true)) e1 e2) sigma pi e1)\n  | one_step_if_false : forall (sigma:(map mident value)) (pi:(list (ident*\n      value)%type)) (e1:expr) (e2:expr), (one_step sigma pi\n      (Eif (Evalue (Vbool false)) e1 e2) sigma pi e2)\n  | one_step_assert : forall (sigma:(map mident value)) (pi:(list (ident*\n      value)%type)) (f:fmla), (eval_fmla sigma pi f) -> (one_step sigma pi\n      (Eassert f) sigma pi (Evalue Vvoid))\n  | one_step_while_true : forall (sigma:(map mident value)) (pi:(list (ident*\n      value)%type)) (cond:expr) (body:expr) (inv:fmla), (eval_fmla sigma pi\n      inv) -> (one_step sigma pi (Ewhile (Evalue (Vbool true)) inv body)\n      sigma pi (Eseq body (Ewhile cond inv body)))\n  | one_step_while_false : forall (sigma:(map mident value)) (pi:(list\n      (ident* value)%type)) (inv:fmla) (body:expr), (eval_fmla sigma pi\n      inv) -> (one_step sigma pi (Ewhile (Evalue (Vbool false)) inv body)\n      sigma pi (Evalue Vvoid)).\n\n(* Why3 assumption *)\nInductive many_steps : (map mident value) -> (list (ident* value)%type)\n  -> expr -> (map mident value) -> (list (ident* value)%type) -> expr\n  -> Z -> Prop :=\n  | many_steps_refl : forall (sigma:(map mident value)) (pi:(list (ident*\n      value)%type)) (s:expr), (many_steps sigma pi s sigma pi s 0%Z)\n  | many_steps_trans : forall (sigma1:(map mident value)) (sigma2:(map mident\n      value)) (sigma3:(map mident value)) (pi1:(list (ident* value)%type))\n      (pi2:(list (ident* value)%type)) (pi3:(list (ident* value)%type))\n      (s1:expr) (s2:expr) (s3:expr) (n:Z), (0%Z < n)%Z -> ((one_step sigma1\n      pi1 s1 sigma2 pi2 s2) -> ((many_steps sigma2 pi2 s2 sigma3 pi3 s3\n      (n - 1%Z)%Z) -> (many_steps sigma1 pi1 s1 sigma3 pi3 s3 n))).\n\nAxiom steps_non_neg : forall (sigma1:(map mident value)) (sigma2:(map mident\n  value)) (pi1:(list (ident* value)%type)) (pi2:(list (ident* value)%type))\n  (s1:expr) (s2:expr) (n:Z), (many_steps sigma1 pi1 s1 sigma2 pi2 s2 n) ->\n  (0%Z <= n)%Z.\n\nAxiom many_steps_seq : forall (sigma1:(map mident value)) (sigma3:(map mident\n  value)) (pi1:(list (ident* value)%type)) (pi3:(list (ident* value)%type))\n  (e1:expr) (e2:expr) (n:Z), (many_steps sigma1 pi1 (Eseq e1 e2) sigma3 pi3\n  (Evalue Vvoid) n) -> exists sigma2:(map mident value), exists pi2:(list\n  (ident* value)%type), exists n1:Z, exists n2:Z, (many_steps sigma1 pi1 e1\n  sigma2 pi2 (Evalue Vvoid) n1) /\\ ((many_steps sigma2 pi2 e2 sigma3 pi3\n  (Evalue Vvoid) n2) /\\ (n = ((1%Z + n1)%Z + n2)%Z)).\n\n(* Why3 assumption *)\nDefinition valid_triple(p:fmla) (e:expr) (q:fmla): Prop := forall (sigma:(map\n  mident value)) (pi:(list (ident* value)%type)), (eval_fmla sigma pi p) ->\n  forall (sigma':(map mident value)) (pi':(list (ident* value)%type)) (n:Z),\n  (many_steps sigma pi e sigma' pi' (Evalue Vvoid) n) -> (eval_fmla sigma'\n  pi' q).\n\n(* Why3 assumption *)\nDefinition total_valid_triple(p:fmla) (e:expr) (q:fmla): Prop :=\n  forall (sigma:(map mident value)) (pi:(list (ident* value)%type)),\n  (eval_fmla sigma pi p) -> exists sigma':(map mident value),\n  exists pi':(list (ident* value)%type), exists n:Z, (many_steps sigma pi e\n  sigma' pi' (Evalue Vvoid) n) /\\ (eval_fmla sigma' pi' q).\n\n(* Why3 assumption *)\nDefinition assigns(sigma:(map mident value)) (a:(set.Set.set mident))\n  (sigma':(map mident value)): Prop := forall (i:mident), (~ (set.Set.mem i\n  a)) -> ((get sigma i) = (get sigma' i)).\n\nAxiom assigns_refl : forall (sigma:(map mident value)) (a:(set.Set.set\n  mident)), (assigns sigma a sigma).\n\nAxiom assigns_trans : forall (sigma1:(map mident value)) (sigma2:(map mident\n  value)) (sigma3:(map mident value)) (a:(set.Set.set mident)),\n  ((assigns sigma1 a sigma2) /\\ (assigns sigma2 a sigma3)) -> (assigns sigma1\n  a sigma3).\n\nAxiom assigns_union_left : forall (sigma:(map mident value)) (sigma':(map\n  mident value)) (s1:(set.Set.set mident)) (s2:(set.Set.set mident)),\n  (assigns sigma s1 sigma') -> (assigns sigma (set.Set.union s1 s2) sigma').\n\nAxiom assigns_union_right : forall (sigma:(map mident value)) (sigma':(map\n  mident value)) (s1:(set.Set.set mident)) (s2:(set.Set.set mident)),\n  (assigns sigma s2 sigma') -> (assigns sigma (set.Set.union s1 s2) sigma').\n\n(* Why3 assumption *)\nFixpoint expr_writes(s:expr) (w:(set.Set.set mident)) {struct s}: Prop :=\n  match s with\n  | ((Evalue _)|((Evar _)|((Ederef _)|(Eassert _)))) => True\n  | (Eassign id _) => (set.Set.mem id w)\n  | (Eseq e1 e2) => (expr_writes e1 w) /\\ (expr_writes e2 w)\n  | (Eif e1 e2 e3) => (expr_writes e1 w) /\\ ((expr_writes e2 w) /\\\n      (expr_writes e3 w))\n  | (Ewhile cond _ body) => (expr_writes cond w) /\\ (expr_writes body w)\n  | (Ebin e1 o e2) => (expr_writes e1 w) /\\ (expr_writes e2 w)\n  | (Elet id e1 e2) => (expr_writes e1 w) /\\ (expr_writes e2 w)\n  end.\n\nParameter fresh_from: fmla -> expr -> ident.\n\nAxiom fresh_from_fmla : forall (s:expr) (f:fmla),\n  (fresh_in_fmla (fresh_from f s) f).\n\nAxiom fresh_from_expr : forall (s:expr) (f:fmla),\n  (fresh_in_expr (fresh_from f s) s).\n\nParameter abstract_effects: expr -> fmla -> fmla.\n\nAxiom abstract_effects_generalize : forall (sigma:(map mident value))\n  (pi:(list (ident* value)%type)) (s:expr) (f:fmla), (eval_fmla sigma pi\n  (abstract_effects s f)) -> (eval_fmla sigma pi f).\n\nAxiom abstract_effects_monotonic : forall (s:expr) (f:fmla),\n  forall (sigma:(map mident value)) (pi:(list (ident* value)%type)),\n  (eval_fmla sigma pi f) -> forall (sigma1:(map mident value)) (pi1:(list\n  (ident* value)%type)), (eval_fmla sigma1 pi1 (abstract_effects s f)).\n\n(* Why3 assumption *)\nFixpoint wp(e:expr) (q:fmla) {struct e}: fmla :=\n  match e with\n  | (Evalue v) => (Flet result (Tvalue v) q)\n  | (Evar v) => (Flet result (Tvar v) q)\n  | (Ederef v) => (Flet result (Tderef v) q)\n  | (Eassert f) => (Fand f (Fimplies f q))\n  | (Eseq e1 e2) => (wp e1 (wp e2 q))\n  | (Elet id e1 e2) => (wp e1 (Flet id (Tvar result) (wp e2 q)))\n  | (Ebin e1 op e2) => let t1 := (fresh_from q e) in let t2 :=\n      (fresh_from (Fand (Fterm (Tvar t1)) q) e) in let q' := (Flet result\n      (Tbin (Tvar t1) op (Tvar t2)) q) in let f := (wp e2 (Flet t2\n      (Tvar result) q')) in (wp e1 (Flet t1 (Tvar result) f))\n  | (Eassign x e1) => let id := (fresh_from q e1) in let q' := (Flet result\n      (Tvalue Vvoid) q) in (wp e1 (Flet id (Tvar result) (msubst q' x id)))\n  | (Eif e1 e2 e3) => let f := (Fand (Fimplies (Fterm (Tvar result)) (wp e2\n      q)) (Fimplies (Fnot (Fterm (Tvar result))) (wp e3 q))) in (wp e1 f)\n  | (Ewhile cond inv body) => (Fand inv (abstract_effects body (wp cond\n      (Fand (Fimplies (Fand (Fterm (Tvar result)) inv) (wp body inv))\n      (Fimplies (Fand (Fnot (Fterm (Tvar result))) inv) q)))))\n  end.\n\nAxiom abstract_effects_writes : forall (sigma:(map mident value)) (pi:(list\n  (ident* value)%type)) (s:expr) (q:fmla), (eval_fmla sigma pi\n  (abstract_effects s q)) -> (eval_fmla sigma pi (wp s (abstract_effects s\n  q))).\n\n(* Why3 goal *)\nTheorem monotonicity : forall (s:expr),\n  match s with\n  | (Evalue v) => True\n  | (Ebin e o e1) => True\n  | (Evar i) => True\n  | (Ederef m) => True\n  | (Eassign m e) => True\n  | (Eseq e e1) => True\n  | (Elet i e e1) => (forall (p:fmla) (q:fmla), (valid_fmla (Fimplies p\n      q)) -> (valid_fmla (Fimplies (wp e1 p) (wp e1 q)))) ->\n      ((forall (p:fmla) (q:fmla), (valid_fmla (Fimplies p q)) ->\n      (valid_fmla (Fimplies (wp e p) (wp e q)))) -> forall (p:fmla) (q:fmla),\n      (valid_fmla (Fimplies p q)) -> (valid_fmla (Fimplies (wp s p) (wp s\n      q))))\n  | (Eif e e1 e2) => True\n  | (Eassert f) => True\n  | (Ewhile e f e1) => True\n  end.\ndestruct s; auto.\nunfold valid_fmla.\nsimpl.\nintros.\napply H0 with (p := (wp s1 (Flet i (Tvar result) (wp s2 p)))). auto.\nintros sigma' pi' _.\nsimpl.\n\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/hoare_logic/draft/blocking_semantics4/blocking_semantics4_WP_monotonicity_11.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.2861104844729612}}
{"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 Arith.\nRequire Import NArith Ndec.\nRequire Import ZArith.\nRequire Import Bool.\nFrom IntMap Require Import Allmaps.\nRequire Import bases.\nRequire Import defs.\nRequire Import semantics.\nRequire Import pl_path.\nRequire Import signature.\n\n(* définition des adresses d'états produits *)\n\nFixpoint iad_conv_aux_0 (p : positive) : positive :=\n  match p with\n  | xH => 2%positive\n  | xO p' => xO (xO (iad_conv_aux_0 p'))\n  | xI p' => xO (xI (iad_conv_aux_0 p'))\n  end.\n\nFixpoint iad_conv_aux_1 (p : positive) : positive :=\n  match p with\n  | xH => 1%positive\n  | xO p' => xO (xO (iad_conv_aux_1 p'))\n  | xI p' => xI (xO (iad_conv_aux_1 p'))\n  end.\n\nFixpoint iad_conv_aux_2 (p0 p1 : positive) {struct p1} : positive :=\n  match p0, p1 with\n  | xH, xH => 3%positive\n  | xH, xO p1' => xI (xO (iad_conv_aux_0 p1'))\n  | xH, xI p1' => xI (xI (iad_conv_aux_0 p1'))\n  | xO p0', xH => xO (xI (iad_conv_aux_1 p0'))\n  | xO p0', xO p1' => xO (xO (iad_conv_aux_2 p0' p1'))\n  | xO p0', xI p1' => xO (xI (iad_conv_aux_2 p0' p1'))\n  | xI p0', xH => xI (xI (iad_conv_aux_1 p0'))\n  | xI p0', xO p1' => xI (xO (iad_conv_aux_2 p0' p1'))\n  | xI p0', xI p1' => xI (xI (iad_conv_aux_2 p0' p1'))\n  end.\n\nDefinition iad_conv (a0 a1 : ad) : ad :=\n  match a0, a1 with\n  | N0, N0 => N0\n  | N0, Npos p1 => Npos (iad_conv_aux_0 p1)\n  | Npos p0, N0 => Npos (iad_conv_aux_1 p0)\n  | Npos p0, Npos p1 => Npos (iad_conv_aux_2 p0 p1)\n  end.\n\nLemma iad_conv_aux_0_inj :\n forall p0 p1 : positive, iad_conv_aux_0 p0 = iad_conv_aux_0 p1 -> p0 = p1.\nProof.\n\tsimple induction p0. simple induction p1. intros. simpl in H1. inversion H1.\n\trewrite (H p2 H3). trivial. intros. simpl in H1. inversion H1.\n\tintros. simpl in H0. inversion H0. intros. induction  p1 as [p1 Hrecp1| p1 Hrecp1| ]. simpl in H0.\n\tinversion H0. simpl in H0. inversion H0. rewrite (H p1 H2). trivial.\n\tinversion H0. simple induction p1. intros. inversion H0. intros. inversion H0.\n\tintros. trivial.\nQed.\n\nLemma iad_conv_aux_1_inj :\n forall p0 p1 : positive, iad_conv_aux_1 p0 = iad_conv_aux_1 p1 -> p0 = p1.\nProof.\n\tsimple induction p0. simple induction p1. intros. simpl in H1. inversion H1.\n\trewrite (H p2 H3). trivial. intros. inversion H1. intros.\n\tinversion H0. intros. induction  p1 as [p1 Hrecp1| p1 Hrecp1| ]. inversion H0. simpl in H0.\n\tinversion H0. rewrite (H p1 H2). trivial. inversion H0. simple induction p1.\n\tintros. inversion H0. intros. inversion H0. intros. trivial.\nQed.\n\nLemma iad_conv_aux_0_1_img_disj :\n forall p0 p1 : positive, iad_conv_aux_0 p0 <> iad_conv_aux_1 p1.\nProof.\n\tsimple induction p0. simple induction p1. intros. intro. simpl in H1. inversion H1.\n\tintros. intro. inversion H1. intro. inversion H0. intros. induction  p1 as [p1 Hrecp1| p1 Hrecp1| ].\n\tintro. inversion H0. intro. unfold iad_conv_aux_0 in H0.\n\tunfold iad_conv_aux_1 in H0. inversion H0. exact (H p1 H2). intro.\n\tinversion H0. simple induction p1. intros. intro. inversion H0. intros. intro.\n\tinversion H0. intro. inversion H.\nQed.\n\nLemma iad_conv_aux_img_disj :\n forall p0 p1 p2 : positive,\n iad_conv_aux_0 p0 <> iad_conv_aux_2 p1 p2 /\\\n iad_conv_aux_1 p0 <> iad_conv_aux_2 p1 p2.\nProof.\n\tsimple induction p0. simple induction p1. simple induction p3. intros. split; intro.\n\tinversion H2. inversion H2. intros. split; intro. inversion H2.\n\tsimpl in H2. inversion H2. elim (H p2 p4); intros. exact (H5 H4).\n\tsplit; intro. inversion H1. inversion H1. simple induction p3. intros.\n\tsplit; intro. simpl in H2. inversion H2. elim (H p2 p4); intros.\n\texact (H3 H4). inversion H2. intros. split; intro. inversion H2.\n\tinversion H2. split; intro. simpl in H1. inversion H1.\n\texact (iad_conv_aux_0_1_img_disj p p2 H3). inversion H1. simple induction p2.\n\tintros. split; intro. inversion H1. inversion H1. intros. \n\tsplit; intro. inversion H1. simpl in H1. inversion H1.\n\texact (iad_conv_aux_0_1_img_disj _ _ (sym_equal H3)).\n\tsplit; intro. inversion H0. inversion H0. intros. induction  p1 as [p1 Hrecp1| p1 Hrecp1| ].\n\tinduction  p2 as [p2 Hrecp2| p2 Hrecp2| ]. split; intro. inversion H0. inversion H0.\n\tsplit; intro. inversion H0. inversion H0. split; intro. inversion H0.\n\tinversion H0. induction  p2 as [p2 Hrecp2| p2 Hrecp2| ]. split; intro. inversion H0. inversion H0.\n\tsplit; intro. simpl in H0. inversion H0. elim (H p1 p2). intros.\n\texact (H1 H2). simpl in H0. inversion H0. elim (H p1 p2); intros.\n\texact (H3 H2). split; intro. inversion H0. inversion H0. induction  p2 as [p2 Hrecp2| p2 Hrecp2| ].\n\tsplit; intro. inversion H0. inversion H0. split; intro. inversion H0.\n\tinversion H0. split; intro. inversion H0. inversion H0. simple induction p1.\n\tintros. induction  p2 as [p2 Hrecp2| p2 Hrecp2| ]. split; intro. inversion H0. inversion H0.\n\tsplit; intro. inversion H0. inversion H0. split; intro. inversion H0.\n\tinversion H0. intros. induction  p2 as [p2 Hrecp2| p2 Hrecp2| ]. split; intro. inversion H0.\n\tinversion H0. split; intro. inversion H0. inversion H0. split; intro.\n\tinversion H0. inversion H0. intros. induction  p2 as [p2 Hrecp2| p2 Hrecp2| ]. split; intro.\n\tinversion H. inversion H. split; intro. inversion H. inversion H.\n\tsplit; intro. inversion H. inversion H.\nQed.\n\nLemma iad_conv_aux_0_2_img_disj :\n forall p0 p1 p2 : positive, iad_conv_aux_0 p0 <> iad_conv_aux_2 p1 p2.\nProof.\n\tintros. elim (iad_conv_aux_img_disj p0 p1 p2). intros. assumption.\nQed.\n\nLemma iad_conv_aux_1_2_img_disj :\n forall p0 p1 p2 : positive, iad_conv_aux_1 p0 <> iad_conv_aux_2 p1 p2.\nProof.\n\tintros. elim (iad_conv_aux_img_disj p0 p1 p2). intros. assumption.\nQed.\n\nLemma iad_conv_aux_2_inj :\n forall p0 p1 p2 p3 : positive,\n iad_conv_aux_2 p0 p1 = iad_conv_aux_2 p2 p3 -> p0 = p2 /\\ p1 = p3.\nProof.\n\tsimple induction p0. intros. induction  p2 as [p2 Hrecp2| p2 Hrecp2| ]. induction  p1 as [p1 Hrecp1| p1 Hrecp1| ]. induction  p3 as [p3 Hrecp3| p3 Hrecp3| ].\n\tsimpl in H0. inversion H0. elim (H p1 p2 p3). intros. rewrite H1.\n\trewrite H3. split. trivial. trivial. assumption. inversion H0.\n\tsimpl in H0. inversion H0. elim (iad_conv_aux_1_2_img_disj p2 p p1 (sym_equal H2)). induction  p3 as [p3 Hrecp3| p3 Hrecp3| ]. inversion H0. simpl in H0.\n\tinversion H0. elim (H p1 p2 p3 H2). intros. rewrite H1. rewrite H3.\n\tsplit; trivial. inversion H0. induction  p3 as [p3 Hrecp3| p3 Hrecp3| ]. simpl in H0. inversion H0.\n\telim (iad_conv_aux_1_2_img_disj p p2 p3 H2). inversion H0.\n\tsimpl in H0. inversion H0. rewrite (iad_conv_aux_1_inj p p2 H2).\n\tsplit; trivial. induction  p1 as [p1 Hrecp1| p1 Hrecp1| ]. induction  p3 as [p3 Hrecp3| p3 Hrecp3| ]. simpl in H0. inversion H0.\n\tinversion H0. inversion H0. induction  p3 as [p3 Hrecp3| p3 Hrecp3| ]. inversion H0. inversion H0.\n\tinversion H0. induction  p3 as [p3 Hrecp3| p3 Hrecp3| ]. inversion H0. inversion H0. inversion H0.\n\tinduction  p1 as [p1 Hrecp1| p1 Hrecp1| ]. induction  p3 as [p3 Hrecp3| p3 Hrecp3| ]. simpl in H0. inversion H0.\n\telim (iad_conv_aux_0_2_img_disj p3 p p1 (sym_equal H2)).\n\tinversion H0. inversion H0. induction  p3 as [p3 Hrecp3| p3 Hrecp3| ]. inversion H0. simpl in H0.\n\tinversion H0. elim (iad_conv_aux_0_2_img_disj p3 p p1 (sym_equal H2)). inversion H0. induction  p3 as [p3 Hrecp3| p3 Hrecp3| ]. simpl in H0. \n\tinversion H0. elim (iad_conv_aux_0_1_img_disj p3 p (sym_equal H2)). inversion H0. inversion H0. simple induction p1. intros. induction  p3 as [p3 Hrecp3| p3 Hrecp3| ].\n\tinduction  p4 as [p4 Hrecp4| p4 Hrecp4| ]. inversion H1. inversion H1. inversion H1. induction  p4 as [p4 Hrecp4| p4 Hrecp4| ].\n\tsimpl in H1. inversion H1. elim (H p2 p3 p4 H3). intros. rewrite H2.\n\trewrite H4. split; trivial. inversion H1. simpl in H1. inversion H1.\n\telim (iad_conv_aux_1_2_img_disj p3 p p2 (sym_equal H3)).\n\tinduction  p4 as [p4 Hrecp4| p4 Hrecp4| ]. inversion H1. inversion H1. inversion H1. intros.\n\tinduction  p3 as [p3 Hrecp3| p3 Hrecp3| ]. induction  p4 as [p4 Hrecp4| p4 Hrecp4| ]. inversion H1. inversion H1. inversion H1.\n\tinduction  p4 as [p4 Hrecp4| p4 Hrecp4| ]. inversion H1. simpl in H1. inversion H1. \n\telim (H p2 p3 p4 H3). intros. rewrite H2. rewrite H4. split; trivial.\n\tinversion H1. induction  p4 as [p4 Hrecp4| p4 Hrecp4| ]; inversion H1. intros. induction  p2 as [p2 Hrecp2| p2 Hrecp2| ].\n\tinduction  p3 as [p3 Hrecp3| p3 Hrecp3| ]. inversion H0. inversion H0. inversion H0. induction  p3 as [p3 Hrecp3| p3 Hrecp3| ].\n\tsimpl in H0. inversion H0. elim (iad_conv_aux_1_2_img_disj p p2 p3 H2).\n\tinversion H0. simpl in H0. inversion H0. rewrite (iad_conv_aux_1_inj _ _ H2). split; trivial. induction  p3 as [p3 Hrecp3| p3 Hrecp3| ]; inversion H0. intros.\n\tinduction  p1 as [p1 Hrecp1| p1 Hrecp1| ]. induction  p2 as [p2 Hrecp2| p2 Hrecp2| ]. induction  p3 as [p3 Hrecp3| p3 Hrecp3| ]. simpl in H. inversion H.\n\telim (iad_conv_aux_0_2_img_disj _ _ _ H1). inversion H. simpl in H.\n\tinversion H. elim (iad_conv_aux_0_1_img_disj _ _ H1). \n\tinduction  p3 as [p3 Hrecp3| p3 Hrecp3| ]; inversion H. induction  p3 as [p3 Hrecp3| p3 Hrecp3| ]. simpl in H. inversion H.\n\trewrite (iad_conv_aux_0_inj _ _ H1). split; trivial. inversion H.\n\tsimpl in H. inversion H.  induction  p2 as [p2 Hrecp2| p2 Hrecp2| ]. induction  p3 as [p3 Hrecp3| p3 Hrecp3| ]. inversion H.\n\tsimpl in H. inversion H. elim (iad_conv_aux_0_2_img_disj _ _ _ H1).\n\tinversion H. induction  p3 as [p3 Hrecp3| p3 Hrecp3| ]; inversion H. induction  p3 as [p3 Hrecp3| p3 Hrecp3| ]. inversion H.\n\tsimpl in H. inversion H. rewrite (iad_conv_aux_0_inj _ _ H1).\n\tsplit; trivial. inversion H. induction  p2 as [p2 Hrecp2| p2 Hrecp2| ]. induction  p3 as [p3 Hrecp3| p3 Hrecp3| ]. simpl in H.\n\tinversion H. inversion H. simpl in H. inversion H.\n\tinduction  p3 as [p3 Hrecp3| p3 Hrecp3| ]; inversion H. induction  p3 as [p3 Hrecp3| p3 Hrecp3| ]. simpl in H. inversion H.\n\tinversion H. split; trivial.\nQed.\n\nLemma iad_conv_inj :\n forall a0 a1 a2 a3 : ad,\n iad_conv a0 a1 = iad_conv a2 a3 -> a0 = a2 /\\ a1 = a3.\nProof.\n\tsimple induction a0; simple induction a1; simple induction a2;\n  simple induction a3; intros.\n\tsplit; trivial. inversion H. inversion H. inversion H. inversion H.\n\tsimpl in H. inversion H. rewrite (iad_conv_aux_0_inj _ _ H1).\n\tsplit; trivial. simpl in H. inversion H. elim (iad_conv_aux_0_1_img_disj _ _ H1). simpl in H. inversion H.\n\telim (iad_conv_aux_0_2_img_disj _ _ _ H1). inversion H.\n\tsimpl in H. inversion H. elim (iad_conv_aux_0_1_img_disj _ _ (sym_equal H1)). simpl in H. inversion H. rewrite (iad_conv_aux_1_inj _ _ H1). split; trivial. simpl in H.\n\tinversion H. elim (iad_conv_aux_1_2_img_disj _ _ _ H1).\n\tinversion H. simpl in H. inversion H. \n\telim (iad_conv_aux_0_2_img_disj _ _ _ (sym_equal H1)).\n\tsimpl in H. inversion H.\n\telim (iad_conv_aux_1_2_img_disj _ _ _ (sym_equal H1)).\n\tsimpl in H. inversion H. elim (iad_conv_aux_2_inj _ _ _ _ H1).\n\tintros. rewrite H0. rewrite H2. split; trivial.\nQed.\n\n(* surjectivité de iad_conv *)\n\nDefinition iad_conv_prop (p : positive) : Prop :=\n  (exists q : positive, p = iad_conv_aux_0 q) \\/\n  (exists q : positive, p = iad_conv_aux_1 q) \\/\n  (exists q : positive, (exists r : positive, p = iad_conv_aux_2 q r)).\n\nLemma iad_conv_surj_0 :\n forall p : positive, iad_conv_prop p -> iad_conv_prop (xO (xO p)).\nProof.\n\tintros. elim H. intro. elim H0. intros. left. split with (xO x).\n\tsimpl in |- *. rewrite <- H1. trivial. intros. elim H0. intros. elim H1.\n\tintros. right. left. split with (xO x). simpl in |- *. rewrite <- H2.\n\ttrivial. intro. elim H1. intros. elim H2. intros. right. right.\n\tsplit with (xO x). split with (xO x0). simpl in |- *. rewrite <- H3.\n\ttrivial.\nQed.\n\nLemma iad_conv_surj_1 :\n forall p : positive, iad_conv_prop p -> iad_conv_prop (xO (xI p)).\nintros.\n\telim H; intros. elim H0. intros. left. split with (xI x).\n\tsimpl in |- *. rewrite <- H1. trivial. elim H0; intros. elim H1. intros.\n\tright. right. split with (xO x). split with 1%positive. simpl in |- *. rewrite H2.\n\ttrivial. elim H1. intros. elim H2. intros. right. right.\n\tsplit with (xO x). split with (xI x0). simpl in |- *. rewrite H3.\n\ttrivial.\nQed.\n\nLemma iad_conv_surj_2 :\n forall p : positive, iad_conv_prop p -> iad_conv_prop (xI (xO p)).\nProof.\n\tintros. elim H; intros. elim H0. intros. right. right. \n\tsplit with 1%positive. split with (xO x). simpl in |- *. rewrite H1. trivial.\n\telim H0; intros. right. left. elim H1. intros. split with (xI x).\n\tsimpl in |- *. rewrite H2. trivial. elim H1. intros. elim H2. intros.\n\tright. right. split with (xI x). split with (xO x0). simpl in |- *.\n\trewrite H3. trivial.\nQed.\n\nLemma iad_conv_surj_3 :\n forall p : positive, iad_conv_prop p -> iad_conv_prop (xI (xI p)).\nProof.\n\tintros. elim H; intros. elim H0. intros. right. right.\n\tsplit with 1%positive. split with (xI x). simpl in |- *. rewrite H1. trivial.\n\telim H0; intros. right. right. elim H1. intros. split with (xI x).\n\tsplit with 1%positive. simpl in |- *. rewrite H2. trivial. elim H1. intros.\n\telim H2. intros. right. right. split with (xI x). split with (xI x0).\n\tsimpl in |- *. rewrite H3. trivial.\nQed.\n\nLemma iad_conv_surj_4 :\n forall p : positive,\n iad_conv_prop p /\\ iad_conv_prop (xO p) /\\ iad_conv_prop (xI p).\nProof.\n\tsimple induction p. intros. elim H. intros. elim H1. intros. split.\n\texact H3. split. exact (iad_conv_surj_1 p0 H0). \n\texact (iad_conv_surj_3 p0 H0). intros. elim H. intros. elim H1. \n\tintros. split. exact H2. split. exact (iad_conv_surj_0 p0 H0).\n\texact (iad_conv_surj_2 p0 H0). split. right. left. split with 1%positive.\n\ttrivial. split. left. split with 1%positive. reflexivity. right. right.\n\tsplit with 1%positive. split with 1%positive. reflexivity.\nQed.\n\nLemma iad_conv_surj_5 : forall p : positive, iad_conv_prop p.\nProof.\n\tintros. elim (iad_conv_surj_4 p). intros. assumption.\nQed.\n\nLemma iad_conv_surj :\n forall a : ad, exists b : ad, (exists c : ad, a = iad_conv b c).\nProof.\n\tsimple induction a. split with N0. split with N0. reflexivity.\n\tintro. elim (iad_conv_surj_5 p). intros. elim H. intros.\n\tsplit with N0. split with (Npos x). simpl in |- *. rewrite H0.\n\ttrivial. intros. elim H. intros. elim H0. intros. split with (Npos x). split with N0. simpl in |- *. rewrite H1. trivial. intros.\n\telim H0. intros. elim H1. intros. split with (Npos x). split with (Npos x0). simpl in |- *. rewrite H2. trivial.\nQed.\n\n(* fonctions réciproques gauche et droite de iad_conv *)\n\nInductive ad_couple : Set :=\n    cpla : ad -> ad -> ad_couple.\n\nFixpoint iad_conv_inv_0 (p : positive) : ad_couple :=\n  match p with\n  | xH => cpla (Npos 1) N0\n  | xO xH => cpla N0 (Npos 1)\n  | xI xH => cpla (Npos 1) (Npos 1)\n  | xO (xO p') =>\n      match iad_conv_inv_0 p' with\n      | cpla N0 N0 => cpla N0 N0\n      | cpla N0 (Npos p1) => cpla N0 (Npos (xO p1))\n      | cpla (Npos p0) N0 => cpla (Npos (xO p0)) N0\n      | cpla (Npos p0) (Npos p1) => cpla (Npos (xO p0)) (Npos (xO p1))\n      end\n  | xO (xI p') =>\n      match iad_conv_inv_0 p' with\n      | cpla N0 N0 => cpla N0 (Npos 1)\n      | cpla N0 (Npos p1) => cpla N0 (Npos (xI p1))\n      | cpla (Npos p0) N0 => cpla (Npos (xO p0)) (Npos 1)\n      | cpla (Npos p0) (Npos p1) => cpla (Npos (xO p0)) (Npos (xI p1))\n      end\n  | xI (xO p') =>\n      match iad_conv_inv_0 p' with\n      | cpla N0 N0 => cpla (Npos 1) N0\n      | cpla N0 (Npos p1) => cpla (Npos 1) (Npos (xO p1))\n      | cpla (Npos p0) N0 => cpla (Npos (xI p0)) N0\n      | cpla (Npos p0) (Npos p1) => cpla (Npos (xI p0)) (Npos (xO p1))\n      end\n  | xI (xI p') =>\n      match iad_conv_inv_0 p' with\n      | cpla N0 N0 => cpla (Npos 1) (Npos 1)\n      | cpla N0 (Npos p1) => cpla (Npos 1) (Npos (xI p1))\n      | cpla (Npos p0) N0 => cpla (Npos (xI p0)) (Npos 1)\n      | cpla (Npos p0) (Npos p1) => cpla (Npos (xI p0)) (Npos (xI p1))\n      end\n  end.\n\nDefinition iad_conv_inv (a : ad) : ad_couple :=\n  match a with\n  | N0 => cpla N0 N0\n  | Npos p => iad_conv_inv_0 p\n  end.\n\nLemma iad_inv_0 :\n forall p : positive, iad_conv_inv_0 (iad_conv_aux_0 p) = cpla N0 (Npos p).\nProof.\n\tintros. induction  p as [p Hrecp| p Hrecp| ]. unfold iad_conv_aux_0 in |- *. simpl in |- *.\n\tunfold iad_conv_aux_0 in Hrecp. rewrite Hrecp. reflexivity.\n\tunfold iad_conv_aux_0 in |- *. unfold iad_conv_aux_0 in Hrecp.\n\tsimpl in |- *. rewrite Hrecp. reflexivity. simpl in |- *. reflexivity.\nQed.\n\nLemma iad_inv_1 :\n forall p : positive, iad_conv_inv_0 (iad_conv_aux_1 p) = cpla (Npos p) N0.\nProof.\n\tsimple induction p. intros. unfold iad_conv_aux_1 in |- *. unfold iad_conv_aux_1 in H.\n\tsimpl in |- *. rewrite H. reflexivity. intros. unfold iad_conv_aux_1 in H.\n\tunfold iad_conv_aux_1 in |- *. simpl in |- *. rewrite H. reflexivity. simpl in |- *.\n\treflexivity.\nQed.\n\nLemma iad_inv_2 :\n forall p0 p1 : positive,\n iad_conv_inv_0 (iad_conv_aux_2 p0 p1) = cpla (Npos p0) (Npos p1).\nProof.\n\tsimple induction p0. simple induction p1. intros. simpl in |- *. rewrite (H p2). reflexivity. \n\tintros. simpl in |- *. rewrite (H p2). reflexivity. simpl in |- *. rewrite (iad_inv_1 p).\n\treflexivity. simple induction p1. intros. simpl in |- *. rewrite (H p2). reflexivity.\n\tintros. simpl in |- *. rewrite (H p2). reflexivity. simpl in |- *. rewrite (iad_inv_1 p).\n\treflexivity. simple induction p1. intros. simpl in |- *. rewrite (iad_inv_0 p).\n\treflexivity. intros. simpl in |- *. rewrite (iad_inv_0 p). reflexivity.\n\tsimpl in |- *. reflexivity.\nQed.\n\nLemma iad_inv_inv_0 :\n forall a0 a1 : ad, iad_conv_inv (iad_conv a0 a1) = cpla a0 a1.\nProof.\n\tsimple induction a0. simple induction a1. simpl in |- *. reflexivity. simpl in |- *.\n\texact iad_inv_0. simple induction a1. simpl in |- *. exact (iad_inv_1 p).\n\tintros. exact (iad_inv_2 p p0).\nQed.\n\nLemma iad_inv_inv_1 :\n forall a a0 a1 : ad, iad_conv_inv a = cpla a0 a1 -> iad_conv a0 a1 = a.\nProof.\n\tintros. elim (iad_conv_surj a). intros. elim H0. intros.\n\trewrite H1 in H. rewrite (iad_inv_inv_0 x x0) in H. inversion H.\n\trewrite H3 in H1. rewrite H4 in H1. rewrite H1. reflexivity.\nQed.\n\n(* algorithme de calcul d'intersection : calcul de l'état produit *)\n\n(* calcul d'une prec_list produit *)\n\nFixpoint pl_produit_0 (a : ad) (la pl : prec_list) \n (n : nat) {struct n} : prec_list -> prec_list :=\n  fun l : prec_list =>\n  match n with\n  | O => prec_empty\n  | S m =>\n      match pl with\n      | prec_empty => l\n      | prec_cons a0 la0 ls0 =>\n          prec_cons (iad_conv a a0) (pl_produit_1 la m la0)\n            (pl_produit_0 a la ls0 m l)\n      end\n  end\n \n with pl_produit_1 (pl0 : prec_list) (n : nat) {struct n} :\n prec_list -> prec_list :=\n  fun pl1 : prec_list =>\n  match n with\n  | O => prec_empty\n  | S m =>\n      match pl0, pl1 with\n      | prec_empty, prec_empty => prec_empty\n      | prec_empty, prec_cons a1 la1 ls1 => prec_empty\n      | prec_cons a0 la0 ls0, prec_empty => prec_empty\n      | prec_cons a0 la0 ls0, prec_cons a1 la1 ls1 =>\n          pl_produit_0 a0 la0 (prec_cons a1 la1 ls1) m\n            (pl_produit_1 ls0 m (prec_cons a1 la1 ls1))\n      end\n  end.\n\nFixpoint pl_card (pl : prec_list) : nat :=\n  match pl with\n  | prec_empty => 1\n  | prec_cons a la ls => S (pl_card la + pl_card ls)\n  end.\n\n(* terminaison des fonctions précédantes *)\n\nDefinition pl_essence (pl0 pl1 : prec_list) : nat :=\n  pl_card pl0 + pl_card pl1.\n\nDefinition pl_produit (pl0 pl1 : prec_list) : prec_list :=\n  pl_produit_1 pl0 (pl_essence pl0 pl1) pl1.\n\nLemma pl_card_0 : forall pl : prec_list, 1 <= pl_card pl.\nProof.\n\tsimple induction pl. intros. simpl in |- *. exact (le_n_S 0 (pl_card p + pl_card p0) (le_O_n (pl_card p + pl_card p0))). simpl in |- *. exact (le_n_n 1).\nQed.\n\nLemma pl_ess_aux_0 : forall pl : prec_list, 1 <= pl_card pl.\nProof.\n\tsimple induction pl. intros. simpl in |- *. exact (le_n_S _ _ (le_O_n _)).\n\tsimpl in |- *. exact (le_n_n _).\nQed.\n\nLemma pl_ess_aux_1 :\n forall (a : ad) (la ls : prec_list),\n S (pl_card la) <= pl_card (prec_cons a la ls).\nProof.\n\tintros. simpl in |- *. apply (le_n_S (pl_card la) (pl_card la + pl_card ls)). exact (le_plus_l (pl_card la) (pl_card ls)).\nQed.\n\nLemma pl_ess_aux_2 :\n forall (a : ad) (la ls : prec_list),\n S (pl_card ls) <= pl_card (prec_cons a la ls).\nProof.\n\tintros. simpl in |- *. exact\n  (le_n_S (pl_card ls) (pl_card la + pl_card ls)\n     (le_plus_r (pl_card la) (pl_card ls))).\nQed.\n\nLemma pl_ess_invar_0 : forall pl0 pl1 : prec_list, 1 <= pl_essence pl0 pl1.\nProof.\n\tintros. unfold pl_essence in |- *. apply (le_plus_trans 1 (pl_card pl0) (pl_card pl1)). exact (pl_ess_aux_0 pl0).\nQed.\n\nLemma pl_ess_invar_1 :\n forall (a a' : ad) (la ls la' ls' : prec_list),\n S (pl_essence la (prec_cons a' la' ls')) <=\n pl_essence (prec_cons a la ls) (prec_cons a' la' ls').\nProof.\n\tintros. unfold pl_essence in |- *. rewrite (S_plus_l (pl_card la) (pl_card (prec_cons a' la' ls'))). exact\n  (plus_le_compat (S (pl_card la)) (pl_card (prec_cons a la ls))\n     (pl_card (prec_cons a' la' ls')) (pl_card (prec_cons a' la' ls'))\n     (pl_ess_aux_1 a la ls) (le_n_n (pl_card (prec_cons a' la' ls')))).\nQed.\n\nLemma pl_ess_invar_2 :\n forall (a a' : ad) (la ls la' ls' : prec_list),\n S (pl_essence ls (prec_cons a' la' ls')) <=\n pl_essence (prec_cons a la ls) (prec_cons a' la' ls').\nProof.\n\tintros. unfold pl_essence in |- *. rewrite (S_plus_l (pl_card ls) (pl_card (prec_cons a' la' ls'))). exact\n  (plus_le_compat (S (pl_card ls)) (pl_card (prec_cons a la ls))\n     (pl_card (prec_cons a' la' ls')) (pl_card (prec_cons a' la' ls'))\n     (pl_ess_aux_2 a la ls) (le_n_n (pl_card (prec_cons a' la' ls')))).\nQed.\n\nLemma pl_ess_invar_3 :\n forall (a' : ad) (la la' ls' : prec_list),\n S (pl_essence la la') <= pl_essence la (prec_cons a' la' ls').\nProof.\n\tintros. unfold pl_essence in |- *. rewrite (S_plus_r (pl_card la) (pl_card la')). exact\n  (plus_le_compat (pl_card la) (pl_card la) (S (pl_card la'))\n     (pl_card (prec_cons a' la' ls')) (le_n_n (pl_card la))\n     (pl_ess_aux_1 a' la' ls')).\nQed.\n\nLemma pl_ess_invar_4 :\n forall (a' : ad) (la la' ls' : prec_list),\n S (pl_essence la ls') <= pl_essence la (prec_cons a' la' ls').\nProof.\n\tintros. unfold pl_essence in |- *. rewrite (S_plus_r (pl_card la) (pl_card ls')). exact\n  (plus_le_compat (pl_card la) (pl_card la) (S (pl_card ls'))\n     (pl_card (prec_cons a' la' ls')) (le_n_n (pl_card la))\n     (pl_ess_aux_2 a' la' ls')).\nQed.\n\nLemma pl_ess_invar_5 : forall pl0 pl1 : prec_list, 2 <= pl_essence pl0 pl1.\nProof.\n\tintros. exact\n  (plus_le_compat 1 (pl_card pl0) 1 (pl_card pl1) (pl_card_0 pl0)\n     (pl_card_0 pl1)).\nQed.\n\n(* invariance du résultat de pl_produit lorsqu'on augmente la quantité d'essence *)\n\nFixpoint pl_prof (pl : prec_list) : nat :=\n  match pl with\n  | prec_empty => 0\n  | prec_cons a la ls => S (max (pl_prof la) (pl_prof ls))\n  end.\n\nLemma indprinciple_0 :\n forall P0 P1 : prec_list -> prec_list -> Prop,\n (forall p : prec_list, P0 p prec_empty) ->\n (forall p : prec_list, P1 p prec_empty) ->\n (forall p : prec_list, P1 prec_empty p) ->\n (forall (a : ad) (la ls p : prec_list),\n  P0 p ls -> P1 p la -> P0 p (prec_cons a la ls)) ->\n (forall (a : ad) (la ls p : prec_list),\n  P0 la p -> P1 ls p -> P1 (prec_cons a la ls) p) ->\n forall n : nat,\n (forall p p' : prec_list,\n  pl_prof p <= n -> pl_prof p' <= n -> P0 p p' /\\ P1 p p') ->\n forall p p' : prec_list,\n pl_prof p <= S n -> pl_prof p' <= S n -> P0 p p' /\\ P1 p p'.\nProof.\n\tintros. induction  p as [a p1 Hrecp1 p0 Hrecp0| ]. induction  p' as [a0 p'1 Hrecp'1 p'0 Hrecp'0| ]. simpl in H5. simpl in H6. cut (pl_prof p1 <= n).\n\tcut (pl_prof p0 <= n). cut (pl_prof p'1 <= n). cut (pl_prof p'0 <= n). intros.\n\tsplit. apply (H2 a0 p'1 p'0 (prec_cons a p1 p0)). elim Hrecp'0. intros. assumption.\n\texact (le_trans (pl_prof p'0) n (S n) H7 (le_n_Sn n)). intros. exact (H4 p1 p'0 H10 H7).\n\tintros. exact (H4 p0 p'0 H9 H7). elim Hrecp'1. intros. exact H12. exact (le_trans (pl_prof p'1) n (S n) H8 (le_n_Sn n)). intros. exact (H4 p1 p'1 H10 H8). intros.\n\texact (H4 p0 p'1 H9 H8). apply (H3 a p1 p0 (prec_cons a0 p'1 p'0)). elim Hrecp1.\n\tintros. assumption. exact (le_trans (pl_prof p1) n (S n) H10 (le_n_Sn n)). elim Hrecp0.\n\tintros. assumption. exact (le_trans (pl_prof p0) n (S n) H9 (le_n_Sn n)).  \n\texact\n  (le_trans (pl_prof p'0) (max (pl_prof p'1) (pl_prof p'0)) n\n     (le_max_r (pl_prof p'1) (pl_prof p'0)) (le_S_n _ _ H6)). exact\n  (le_trans (pl_prof p'1) (max (pl_prof p'1) (pl_prof p'0)) n\n     (le_max_l (pl_prof p'1) (pl_prof p'0)) (le_S_n _ _ H6)). exact\n  (le_trans (pl_prof p0) (max (pl_prof p1) (pl_prof p0)) n\n     (le_max_r (pl_prof p1) (pl_prof p0)) (le_S_n _ _ H5)).\n\texact\n  (le_trans (pl_prof p1) (max (pl_prof p1) (pl_prof p0)) n\n     (le_max_l (pl_prof p1) (pl_prof p0)) (le_S_n _ _ H5)). split. exact (H (prec_cons a p1 p0)). exact (H0 (prec_cons a p1 p0)). induction  p' as [a p'1 Hrecp'1 p'0 Hrecp'0| ]. split. apply (H2 a p'1 p'0 prec_empty). elim Hrecp'0. intros.\n\tassumption. simpl in H6. exact\n  (le_trans (pl_prof p'0) n (S n)\n     (le_trans _ _ _ (le_max_r (pl_prof p'1) (pl_prof p'0)) (le_S_n _ _ H6))\n     (le_n_Sn n)). exact (H1 p'1).\n\texact (H1 (prec_cons a p'1 p'0)). split. exact (H prec_empty). exact (H0 prec_empty).\nQed.\n\nLemma indprinciple_1 :\n forall P0 P1 : prec_list -> prec_list -> Prop,\n (forall p : prec_list, P0 p prec_empty) ->\n (forall p : prec_list, P1 p prec_empty) ->\n (forall p : prec_list, P1 prec_empty p) ->\n (forall (a : ad) (la ls p : prec_list),\n  P0 p ls -> P1 p la -> P0 p (prec_cons a la ls)) ->\n (forall (a : ad) (la ls p : prec_list),\n  P0 la p -> P1 ls p -> P1 (prec_cons a la ls) p) ->\n forall p p' : prec_list,\n pl_prof p <= 0 -> pl_prof p' <= 0 -> P0 p p' /\\ P1 p p'.\nProof.\n\tintros. induction  p as [a p1 Hrecp1 p0 Hrecp0| ]. induction  p' as [a0 p'1 Hrecp'1 p'0 Hrecp'0| ]. simpl in H4. elim (le_Sn_O (max (pl_prof p1) (pl_prof p0)) H4). simpl in H4. elim (le_Sn_O (max (pl_prof p1) (pl_prof p0)) H4).\n\tinduction  p' as [a p'1 Hrecp'1 p'0 Hrecp'0| ]. simpl in H5. elim (le_Sn_O (max (pl_prof p'1) (pl_prof p'0)) H5).\n\tsplit. exact (H prec_empty). exact (H0 prec_empty).\nQed.\n\nLemma indprinciple_2 :\n forall P0 P1 : prec_list -> prec_list -> Prop,\n (forall p : prec_list, P0 p prec_empty) ->\n (forall p : prec_list, P1 p prec_empty) ->\n (forall p : prec_list, P1 prec_empty p) ->\n (forall (a : ad) (la ls p : prec_list),\n  P0 p ls -> P1 p la -> P0 p (prec_cons a la ls)) ->\n (forall (a : ad) (la ls p : prec_list),\n  P0 la p -> P1 ls p -> P1 (prec_cons a la ls) p) ->\n forall (n : nat) (p p' : prec_list),\n pl_prof p <= n -> pl_prof p' <= n -> P0 p p' /\\ P1 p p'.\nProof.\n\tsimple induction n. exact (indprinciple_1 P0 P1 H H0 H1 H2 H3). exact (indprinciple_0 P0 P1 H H0 H1 H2 H3).\nQed.\n\nLemma indprinciple_pl :\n forall P0 P1 : prec_list -> prec_list -> Prop,\n (forall p : prec_list, P0 p prec_empty) ->\n (forall p : prec_list, P1 p prec_empty) ->\n (forall p : prec_list, P1 prec_empty p) ->\n (forall (a : ad) (la ls p : prec_list),\n  P0 p ls -> P1 p la -> P0 p (prec_cons a la ls)) ->\n (forall (a : ad) (la ls p : prec_list),\n  P0 la p -> P1 ls p -> P1 (prec_cons a la ls) p) ->\n forall p p' : prec_list, P0 p p' /\\ P1 p p'.\nProof.\n\tintros. elim\n  (indprinciple_2 P0 P1 H H0 H1 H2 H3 (max (pl_prof p) (pl_prof p')) p p').\n\tintros. split; assumption. exact (le_max_l _ _). exact (le_max_r _ _).\nQed.\n\nDefinition pl_produit_0_incr (p0 p1 : prec_list) : Prop :=\n  forall (a : ad) (l : prec_list) (n : nat),\n  pl_essence p0 p1 <= n ->\n  pl_produit_0 a p0 p1 (pl_essence p0 p1) l = pl_produit_0 a p0 p1 n l.\n\nDefinition pl_produit_1_incr (p0 p1 : prec_list) : Prop :=\n  forall n : nat,\n  pl_essence p0 p1 <= n ->\n  pl_produit_1 p0 (pl_essence p0 p1) p1 = pl_produit_1 p0 n p1.\n\nLemma pl_product_0_0 : forall p : prec_list, pl_produit_0_incr p prec_empty.\nProof.\n\tunfold pl_produit_0_incr in |- *. intros. induction  p as [a0 p1 Hrecp1 p0 Hrecp0| ]. simpl in |- *. \n\tunfold pl_essence in H. induction  n as [| n Hrecn]. elim\n  (le_Sn_O 0\n     (le_trans (pl_card prec_empty)\n        (pl_card (prec_cons a0 p1 p0) + pl_card prec_empty) 0 \n        (le_plus_l _ _) H)). simpl in |- *. reflexivity. simpl in |- *.\n\tinduction  n as [| n Hrecn]. unfold pl_essence in H. simpl in H. elim (le_Sn_O 1 H).\n\tsimpl in |- *. reflexivity.\nQed.\n\nLemma pl_product_0_1 : forall p : prec_list, pl_produit_1_incr p prec_empty.\nProof.\n\tsimple induction p. unfold pl_produit_1_incr in |- *. intros. simpl in |- *. induction  n as [| n Hrecn].\n\tsimpl in |- *. reflexivity. simpl in |- *. reflexivity. unfold pl_produit_1_incr in |- *.\n\tintros. induction  n as [| n Hrecn]; simpl in |- *. reflexivity. reflexivity.\nQed.\n\nLemma pl_product_0_2 : forall p : prec_list, pl_produit_1_incr prec_empty p.\nProof.\n\tunfold pl_produit_1_incr in |- *. intros. induction  p as [a p1 Hrecp1 p0 Hrecp0| ]. simpl in |- *. induction  n as [| n Hrecn].\n\tsimpl in |- *. reflexivity. simpl in |- *. reflexivity. simpl in |- *. induction  n as [| n Hrecn]. simpl in |- *.\n\treflexivity. reflexivity.\nQed.\n\nLemma pl_product_0_3 :\n forall (a : ad) (la ls p : prec_list),\n pl_produit_0_incr p ls ->\n pl_produit_1_incr p la -> pl_produit_0_incr p (prec_cons a la ls).\nProof.\n\tunfold pl_produit_0_incr in |- *. unfold pl_produit_1_incr in |- *. intros.\n\tinduction  n as [| n Hrecn]. elim\n  (le_Sn_O 0\n     (le_trans 1 (pl_essence p (prec_cons a la ls)) 0\n        (pl_ess_invar_0 p (prec_cons a la ls)) H1)). elim (nat_sum (pl_essence p (prec_cons a la ls))). intros. elim (le_Sn_O 0). exact\n  (eq_ind (pl_essence p (prec_cons a la ls)) (fun n : nat => 1 <= n)\n     (pl_ess_invar_0 p (prec_cons a la ls)) 0 H2). intros. elim H2. intros.\n\trewrite H3. replace (pl_produit_0 a0 p (prec_cons a la ls) (S x) l) with\n  (prec_cons (iad_conv a0 a) (pl_produit_1 p x la) (pl_produit_0 a0 p ls x l)). replace (pl_produit_0 a0 p (prec_cons a la ls) (S n) l) with\n  (prec_cons (iad_conv a0 a) (pl_produit_1 p n la) (pl_produit_0 a0 p ls n l)). rewrite <- (H0 x). rewrite <- (H0 n). rewrite <- (H a0 l x).\n\trewrite <- (H a0 l n). reflexivity. exact (le_S_n _ _ (le_trans _ _ _ (pl_ess_invar_4 a p la ls) H1)). exact\n  (le_S_n _ _\n     (le_trans _ _ _ (pl_ess_invar_4 a p la ls)\n        (eq_ind (pl_essence p (prec_cons a la ls))\n           (fun z : nat => pl_essence p (prec_cons a la ls) <= z)\n           (le_n_n (pl_essence p (prec_cons a la ls))) \n           (S x) H3))). exact (le_S_n _ _ (le_trans _ _ _ (pl_ess_invar_3 a p la ls) H1)). exact\n  (le_S_n _ _\n     (le_trans _ _ _ (pl_ess_invar_3 a p la ls)\n        (eq_ind (pl_essence p (prec_cons a la ls))\n           (fun z : nat => pl_essence p (prec_cons a la ls) <= z)\n           (le_n_n (pl_essence p (prec_cons a la ls))) \n           (S x) H3))). reflexivity. reflexivity.\nQed.\n\nLemma pl_product_0_4 :\n forall (a : ad) (la ls p : prec_list),\n pl_produit_0_incr la p ->\n pl_produit_1_incr ls p -> pl_produit_1_incr (prec_cons a la ls) p.\nProof.\n\tunfold pl_produit_0_incr in |- *. unfold pl_produit_1_incr in |- *. intros. induction  n as [| n Hrecn].\n\telim (le_Sn_O 0 (le_trans _ _ _ (pl_ess_invar_0 (prec_cons a la ls) p) H1)).\n\telim (nat_sum (pl_essence (prec_cons a la ls) p)); intro. elim (le_Sn_O 0).\n\texact\n  (eq_ind (pl_essence (prec_cons a la ls) p) (fun n : nat => 1 <= n)\n     (pl_ess_invar_0 (prec_cons a la ls) p) 0 H2). elim H2. intros. rewrite H3.\n\tinduction  p as [a0 p1 Hrecp1 p0 Hrecp0| ]. replace (pl_produit_1 (prec_cons a la ls) (S x) (prec_cons a0 p1 p0)) with\n  (pl_produit_0 a la (prec_cons a0 p1 p0) x\n     (pl_produit_1 ls x (prec_cons a0 p1 p0))). replace (pl_produit_1 (prec_cons a la ls) (S n) (prec_cons a0 p1 p0)) with\n  (pl_produit_0 a la (prec_cons a0 p1 p0) n\n     (pl_produit_1 ls n (prec_cons a0 p1 p0))). rewrite <- (H0 x). rewrite <- (H0 n). rewrite <-\n  (H a\n     (pl_produit_1 ls (pl_essence ls (prec_cons a0 p1 p0))\n        (prec_cons a0 p1 p0)) x). rewrite <-\n  (H a\n     (pl_produit_1 ls (pl_essence ls (prec_cons a0 p1 p0))\n        (prec_cons a0 p1 p0)) n). reflexivity.\n\texact (le_S_n _ _ (le_trans _ _ _ (pl_ess_invar_1 a a0 la ls p1 p0) H1)).\n\texact\n  (le_S_n _ _\n     (le_trans _ _ _ (pl_ess_invar_1 a a0 la ls p1 p0)\n        (eq_ind (pl_essence (prec_cons a la ls) (prec_cons a0 p1 p0))\n           (fun z : nat =>\n            pl_essence (prec_cons a la ls) (prec_cons a0 p1 p0) <= z)\n           (le_n_n (pl_essence (prec_cons a la ls) (prec_cons a0 p1 p0)))\n           (S x) H3))).\n\texact (le_S_n _ _ (le_trans _ _ _ (pl_ess_invar_2 a a0 la ls p1 p0) H1)).\n\texact\n  (le_S_n _ _\n     (le_trans _ _ _ (pl_ess_invar_2 a a0 la ls p1 p0)\n        (eq_ind (pl_essence (prec_cons a la ls) (prec_cons a0 p1 p0))\n           (fun z : nat =>\n            pl_essence (prec_cons a la ls) (prec_cons a0 p1 p0) <= z)\n           (le_n_n _) (S x) H3))). reflexivity. reflexivity. simpl in |- *. reflexivity.\nQed.\n\nLemma pl_product_0_5 :\n forall p p' : prec_list, pl_produit_0_incr p p' /\\ pl_produit_1_incr p p'.\nProof.\n\texact\n  (indprinciple_pl pl_produit_0_incr pl_produit_1_incr pl_product_0_0\n     pl_product_0_1 pl_product_0_2 pl_product_0_3 pl_product_0_4).\nQed.\n\nLemma pl_product_0 :\n forall p0 p1 : prec_list,\n (forall (a : ad) (l : prec_list) (n : nat),\n  pl_essence p0 p1 <= n ->\n  pl_produit_0 a p0 p1 (pl_essence p0 p1) l = pl_produit_0 a p0 p1 n l) /\\\n (forall n : nat,\n  pl_essence p0 p1 <= n ->\n  pl_produit_1 p0 (pl_essence p0 p1) p1 = pl_produit_1 p0 n p1).\nProof.\n\texact\n  (indprinciple_pl pl_produit_0_incr pl_produit_1_incr pl_product_0_0\n     pl_product_0_1 pl_product_0_2 pl_product_0_3 pl_product_0_4).\nQed.\n\nLemma pl_product_0_invar_essence :\n forall (p0 p1 : prec_list) (n : nat),\n pl_essence p0 p1 <= n ->\n pl_produit_1 p0 (pl_essence p0 p1) p1 = pl_produit_1 p0 n p1.\nProof.\n\tintro. intro. elim (pl_product_0 p0 p1). intros. exact (H0 n H1).\nQed.\n\nLemma pl_product_1 :\n forall (a : ad) (la pl l : prec_list) (n : nat),\n pl_essence la pl <= n ->\n pl_produit_0 a la pl n l = prec_empty -> pl = prec_empty.\nProof.\n\tintros. induction  n as [| n Hrecn]. elim (le_Sn_n 0 (le_trans _ _ _ (pl_ess_invar_0 la pl) H)).\n\tinduction  pl as [a0 pl1 Hrecpl1 pl0 Hrecpl0| ]. simpl in H0. inversion H0. reflexivity.\nQed.\n\n(* passage au produit de la propriété pl_tl_length *)\n\nDefinition pl_tl_length_prod_def_0 (pl0 pl1 : prec_list) : Prop :=\n  forall (l : prec_list) (a : ad) (n m : nat),\n  pl_essence pl0 pl1 <= m ->\n  pl_tl_length pl0 n ->\n  pl_tl_length l (S n) \\/ l = prec_empty ->\n  (pl_tl_length pl1 (S n) -> pl_tl_length (pl_produit_0 a pl0 pl1 m l) (S n)) /\\\n  (pl1 = prec_empty ->\n   (pl_tl_length l (S n) -> pl_tl_length (pl_produit_0 a pl0 pl1 m l) (S n)) /\\\n   (l = prec_empty -> pl_produit_0 a pl0 pl1 m l = prec_empty)).\n\nDefinition pl_tl_length_prod_def_1 (pl0 pl1 : prec_list) : Prop :=\n  forall n m : nat,\n  pl_tl_length pl0 n ->\n  pl_tl_length pl1 n ->\n  pl_essence pl0 pl1 <= m -> pl_tl_length (pl_produit_1 pl0 m pl1) n.\n\nLemma pl_tl_length_prod_0 :\n forall p : prec_list, pl_tl_length_prod_def_0 p prec_empty.\nProof.\n\tunfold pl_tl_length_prod_def_0 in |- *. intros. split. intros. inversion H2.\n\tintros. split. intros. elim (nat_sum m); intro. rewrite H4 in H.\n\telim (le_Sn_n 0 (le_trans _ _ _ (pl_ess_invar_0 p prec_empty) H)).\n\telim H4. intros. rewrite H5. simpl in |- *. exact H3. intros. elim (nat_sum m).\n\tintro. rewrite H4. reflexivity. intros. elim H4. elim H4. intros.\n\trewrite H5. simpl in |- *. exact H3.\nQed.\n\nLemma pl_tl_length_prod_1 :\n forall p : prec_list, pl_tl_length_prod_def_1 p prec_empty.\nProof.\n\tunfold pl_tl_length_prod_def_1 in |- *. intros. elim (nat_sum m); intros. \n\trewrite H2. simpl in |- *. exact H0. elim H2. intros. rewrite H3. simpl in |- *.\n\tinduction  p as [a p1 Hrecp1 p0 Hrecp0| ]; exact H0.\nQed.\n\nLemma pl_tl_length_prod_2 :\n forall p : prec_list, pl_tl_length_prod_def_1 prec_empty p.\nProof.\n\tunfold pl_tl_length_prod_def_1 in |- *. intros. elim (nat_sum m); intros.\n\trewrite H2. simpl in |- *. exact H. elim H2. intros. rewrite H3. simpl in |- *.\n\tinduction  p as [a p1 Hrecp1 p0 Hrecp0| ]; exact H.\nQed.\n\nLemma pl_tl_length_prod_3 :\n forall (a : ad) (la ls p : prec_list),\n pl_tl_length_prod_def_0 p ls ->\n pl_tl_length_prod_def_1 p la ->\n pl_tl_length_prod_def_0 p (prec_cons a la ls).\nProof.\n\tunfold pl_tl_length_prod_def_0 in |- *. unfold pl_tl_length_prod_def_1 in |- *.\n\tintros. split. intros. elim (nat_sum m); intro. rewrite H5 in H1.\n\telim (le_Sn_O 0 (le_trans _ _ _ (pl_ess_invar_0 p (prec_cons a la ls)) H1)). elim H5. intros. rewrite H6. replace (pl_produit_0 a0 p (prec_cons a la ls) (S x) l) with\n  (prec_cons (iad_conv a0 a) (pl_produit_1 p x la) (pl_produit_0 a0 p ls x l)). elim (H l a0 n x).\n\tintros. cut (pl_tl_length (pl_produit_1 p x la) n). intro. inversion H4.\n\telim H3. intros. elim (H8 (sym_eq H13)). intros.\n\tapply\n  (pl_tl_propag (iad_conv a0 a) (pl_produit_1 p x la)\n     (pl_produit_0 a0 p prec_empty x l) n H9). elim (nat_sum x); intro. rewrite H18 in H16.\n\tsimpl in H16. cut (pl_tl_length prec_empty (S n)). intro. inversion H19.\n\texact (H16 H15). elim H18. intros. rewrite H19. simpl in |- *. exact H15.\n\tintro. replace (pl_produit_0 a0 p prec_empty x l) with prec_empty.\n\texact (pl_tl_S (iad_conv a0 a) (pl_produit_1 p x la) n H9).\n\telim (nat_sum x); intro. rewrite H16. reflexivity. elim H16. intros.\n\trewrite H17. simpl in |- *. symmetry  in |- *. exact H15. exact\n  (pl_tl_propag (iad_conv a0 a) (pl_produit_1 p x la)\n     (pl_produit_0 a0 p ls x l) n H9 (H7 H15)).\n\tapply (H0 n x H2). inversion H4. exact H10. exact H11. unfold pl_essence in |- *.\n\tunfold pl_essence in H1. rewrite H6 in H1. simpl in H1. elim (le_or_lt (pl_card p + pl_card la) x); intro. exact H9. elim (le_Sn_n (S x)).\n\tapply (le_trans (S (S x)) (pl_card p + S (pl_card la + pl_card ls)) (S x)). rewrite <- (plus_Snm_nSm (pl_card p) (pl_card la + pl_card ls)). simpl in |- *. apply (le_n_S (S x) (pl_card p + (pl_card la + pl_card ls))). exact\n  (le_trans _ _ _ (lt_le_S _ _ H9)\n     (plus_le_compat (pl_card p) (pl_card p) (pl_card la)\n        (pl_card la + pl_card ls) (le_n_n _) (le_plus_l _ _))). exact H1. unfold pl_essence in |- *.\n\tunfold pl_essence in H1. rewrite H6 in H1. simpl in H1. elim (le_or_lt (pl_card p + pl_card ls) x); intro. exact H7. elim (le_Sn_n (S x)).\n\tapply (le_trans (S (S x)) (pl_card p + S (pl_card la + pl_card ls)) (S x)). rewrite <- (plus_Snm_nSm (pl_card p) (pl_card la + pl_card ls)). simpl in |- *. apply (le_n_S (S x) (pl_card p + (pl_card la + pl_card ls))). exact\n  (le_trans _ _ _ (lt_le_S _ _ H7)\n     (plus_le_compat (pl_card p) (pl_card p) (pl_card ls)\n        (pl_card la + pl_card ls) (le_n_n _) (le_plus_r _ _))). exact H1. exact H2. exact H3.\n\treflexivity. intros. inversion H4.\nQed.\n\nLemma pl_tl_length_prod_4 :\n forall (a : ad) (la ls p : prec_list),\n pl_tl_length_prod_def_0 la p ->\n pl_tl_length_prod_def_1 ls p ->\n pl_tl_length_prod_def_1 (prec_cons a la ls) p.\nProof.\n\tunfold pl_tl_length_prod_def_0 in |- *. unfold pl_tl_length_prod_def_1 in |- *. intros.\n\telim (nat_sum m); intros. rewrite H4 in H3. elim (le_Sn_O 0 (le_trans _ _ _ (pl_ess_invar_0 (prec_cons a la ls) p) H3)). elim H4. intros. \n\trewrite H5. elim (pl_sum p). intros. rewrite H6 in H2. inversion H2.\n\trewrite <- H8 in H1. inversion H1. intros. elim H6. intros. elim H7.\n\tintros. elim H8. intros. rewrite H9. replace (pl_produit_1 (prec_cons a la ls) (S x) (prec_cons x0 x1 x2)) with\n  (pl_produit_0 a la (prec_cons x0 x1 x2) x\n     (pl_produit_1 ls x (prec_cons x0 x1 x2))). inversion H1.\n\trewrite <- H9. elim (H (pl_produit_1 prec_empty x p) a n0 x). intros.\n\trewrite <- H11 in H2. exact (H15 H2). rewrite H5 in H3. unfold pl_essence in H3. unfold pl_essence in |- *. simpl in H3. elim (le_or_lt (pl_card la + pl_card p) x). intro. exact H15. intro. elim (le_Sn_n (S x)). apply (le_trans (S (S x)) (S (pl_card la + pl_card ls + pl_card p)) (S x)). apply (le_n_S (S x) (pl_card la + pl_card ls + pl_card p)). exact\n  (le_trans _ _ _ (lt_le_S _ _ H15)\n     (plus_le_compat (pl_card la) (pl_card la + pl_card ls) \n        (pl_card p) (pl_card p) (le_plus_l _ _) (le_n_n _))). exact H3. exact H14. right. elim (nat_sum x).\n\tintro. rewrite H15. reflexivity. intros. elim H15. intros. rewrite H16.\n\tinduction  p as [a1 p1 Hrecp1 p0 Hrecp0| ]; reflexivity. elim (H (pl_produit_1 ls x (prec_cons x0 x1 x2)) a n0 x). intros. rewrite <- H12 in H2. rewrite H9 in H16. rewrite H9 in H2.\n\texact (H16 H2). unfold pl_essence in |- *. unfold pl_essence in H3. rewrite H5 in H3.\n\tsimpl in H3. elim (le_or_lt (pl_card la + pl_card p) x). intro.\n\texact H16. intro. elim (le_Sn_n (S x)). apply (le_trans (S (S x)) (S (pl_card la + pl_card ls + pl_card p)) (S x)).\n\tapply (le_n_S (S x) (pl_card la + pl_card ls + pl_card p)).\n\texact\n  (le_trans _ _ _ (lt_le_S _ _ H16)\n     (plus_le_compat (pl_card la) (pl_card la + pl_card ls) \n        (pl_card p) (pl_card p) (le_plus_l _ _) (le_n_n _))). exact H3. exact H14. left. rewrite <- H9. apply (H0 (S n0) x H15).\n\trewrite H12. exact H2. unfold pl_essence in |- *. unfold pl_essence in H3.\n\trewrite H5 in H3. simpl in H3. elim (le_or_lt (pl_card ls + pl_card p) x); intro. exact H16. elim (le_Sn_n (S x)). apply (le_trans (S (S x)) (S (pl_card la + pl_card ls + pl_card p)) (S x)).\n\tapply (le_n_S (S x) (pl_card la + pl_card ls + pl_card p)).\n\texact\n  (le_trans _ _ _ (lt_le_S _ _ H16)\n     (plus_le_compat (pl_card ls) (pl_card la + pl_card ls) \n        (pl_card p) (pl_card p) (le_plus_r _ _) (le_n_n _))). exact H3. reflexivity.\nQed.\n\nLemma pl_tl_length_prod_5 :\n forall p p' : prec_list,\n pl_tl_length_prod_def_0 p p' /\\ pl_tl_length_prod_def_1 p p'.\nProof.\n\texact\n  (indprinciple_pl pl_tl_length_prod_def_0 pl_tl_length_prod_def_1\n     pl_tl_length_prod_0 pl_tl_length_prod_1 pl_tl_length_prod_2\n     pl_tl_length_prod_3 pl_tl_length_prod_4).\nQed.\n\nLemma pl_tl_length_prod :\n forall (pl0 pl1 : prec_list) (n : nat),\n pl_tl_length pl0 n ->\n pl_tl_length pl1 n -> pl_tl_length (pl_produit pl0 pl1) n.\nProof.\n\tintros. elim (pl_tl_length_prod_5 pl0 pl1). intros. unfold pl_produit in |- *.\n\texact (H2 n (pl_essence pl0 pl1) H H0 (le_n_n _)).\nQed.\n\n(* lemmes de conservation des pl_path_incl par passage au pl_produit *)\n\nLemma pl_produit_path_incl_0 :\n forall (n : nat) (a : ad) (la pl l : prec_list) (plp : pl_path),\n pl_path_incl plp l ->\n plp <> pl_path_nil ->\n pl_essence la pl <= n -> pl_path_incl plp (pl_produit_0 a la pl n l).\nProof.\n\tsimple induction n. intros. elim (le_Sn_O 0 (le_trans _ _ _ (pl_ess_invar_0 la pl) H1)). intros. induction  pl as [a0 pl1 Hrecpl1 pl0 Hrecpl0| ]. replace (pl_produit_0 a la (prec_cons a0 pl1 pl0) (S n0) l) with\n  (prec_cons (iad_conv a a0) (pl_produit_1 la n0 pl1)\n     (pl_produit_0 a la pl0 n0 l)). apply\n  (pl_path_incl_next plp (iad_conv a a0) (pl_produit_1 la n0 pl1)\n     (pl_produit_0 a la pl0 n0 l)). apply (H a la pl0 l plp H0 H1). unfold pl_essence in |- *. unfold pl_essence in H2. elim (le_or_lt (pl_card la + pl_card pl0) n0). intro. exact H3. intro. simpl in H2.\n\tcut\n  (pl_card la + S (S (pl_card pl0)) <=\n   pl_card la + S (pl_card pl1 + pl_card pl0)). intro. cut (pl_card la + S (S (pl_card pl0)) <= S n0). intros. cut (pl_card la + S (S (pl_card pl0)) = S (S (pl_card la + pl_card pl0))). intro. rewrite H6 in H5.\n\telim\n  (le_Sn_n _\n     (le_trans _ _ _\n        (le_trans _ _ _ (le_n_S _ _ (le_n_S _ _ (lt_le_S _ _ H3))) H5)\n        (le_n_Sn (S n0)))). rewrite <- (plus_Snm_nSm (pl_card la) (S (pl_card pl0))). simpl in |- *. rewrite <- (plus_Snm_nSm (pl_card la) (pl_card pl0)). simpl in |- *. reflexivity. exact (le_trans _ _ _ H4 H2). apply\n  (plus_le_compat (pl_card la) (pl_card la) (S (S (pl_card pl0)))\n     (S (pl_card pl1 + pl_card pl0))). exact (le_n_n _). apply (le_n_S (S (pl_card pl0)) (pl_card pl1 + pl_card pl0)). exact\n  (plus_le_compat 1 (pl_card pl1) (pl_card pl0) (pl_card pl0) \n     (pl_card_0 pl1) (le_n_n _)). exact H1.\n\treflexivity. simpl in |- *. exact H0.\nQed.\n\nFixpoint pl_path_product (p0 p1 : pl_path) {struct p1} : pl_path :=\n  match p0, p1 with\n  | pl_path_nil, pl_path_nil => pl_path_nil\n  | pl_path_nil, pl_path_cons a b => pl_path_nil\n  | pl_path_cons a b, pl_path_nil => pl_path_nil\n  | pl_path_cons a0 b0, pl_path_cons a1 b1 =>\n      pl_path_cons (iad_conv a0 a1) (pl_path_product b0 b1)\n  end.\n\nLemma pl_path_product_n :\n forall (n : nat) (p0 p1 : pl_path),\n pl_path_length p0 = n ->\n pl_path_length p1 = n -> pl_path_length (pl_path_product p0 p1) = n.\nProof.\n\tsimple induction n. intros. induction  p0 as [| a p0 Hrecp0]. induction  p1 as [| a p1 Hrecp1]. simpl in |- *. reflexivity.\n\tinversion H0. inversion H. intros. induction  p0 as [| a p0 Hrecp0]. inversion H0. induction  p1 as [| a0 p1 Hrecp1].\n\tinversion H1. simpl in |- *. simpl in H0. simpl in H1. inversion H0. inversion H1.\n\trewrite H3. rewrite (H p0 p1 H3 H4). reflexivity.\nQed.\n\nLemma pl_produit_path_incl_inj :\n forall (plp0 plp1 plp2 plp3 : pl_path) (n : nat),\n pl_path_length plp0 = n ->\n pl_path_length plp1 = n ->\n pl_path_length plp2 = n ->\n pl_path_length plp3 = n ->\n pl_path_product plp0 plp1 = pl_path_product plp2 plp3 ->\n plp0 = plp2 /\\ plp1 = plp3.\nProof.\n\tsimple induction plp0. simple induction plp1. simple induction plp2. simple induction plp3. intros.\n\tsplit; reflexivity. intros. simpl in H2. rewrite <- H2 in H3. simpl in H3.\n\tinversion H3. intros. simpl in H0. rewrite <- H0 in H2. simpl in H2.\n\tinversion H2. intros. simpl in H0. rewrite <- H0 in H1. simpl in H1.\n\tinversion H1. intros. induction  plp1 as [| a0 plp1 Hrecplp1]. simpl in H0. simpl in H1. rewrite <- H1 in H0. inversion H0. induction  plp2 as [| a1 plp2 Hrecplp2]. simpl in H2. rewrite <- H2 in H0.\n\tsimpl in H0. inversion H0. induction  plp3 as [| a2 plp3 Hrecplp3]. simpl in H3. rewrite <- H3 in H0.\n\tsimpl in H0. inversion H0. simpl in H4. inversion H4. elim (iad_conv_inj _ _ _ _ H6). intros. rewrite H5. rewrite H8. elim (nat_sum n). intros.\n\trewrite H9 in H0. simpl in H0. inversion H0. intros. elim H9. intros.\n\trewrite H10 in H0. rewrite H10 in H1. rewrite H10 in H2. rewrite H10 in H3.\n\tsimpl in H0. simpl in H1. simpl in H2. simpl in H3. inversion H0. inversion H1.\n\tinversion H2. inversion H3. elim (H plp1 plp2 plp3 x H12 H13 H14 H15 H7).\n\tintros. rewrite H11. rewrite H16. split; reflexivity.\nQed.\n\nDefinition pl_produit_path_incl_def_0 (pl0 pl1 : prec_list) :=\n  forall (n m : nat) (plp0 plp1 : pl_path) (a : ad) (l : prec_list),\n  pl_path_incl plp0 (prec_cons a pl0 prec_empty) ->\n  pl_tl_length pl0 n ->\n  pl_path_incl plp1 pl1 ->\n  pl_tl_length pl1 (S n) ->\n  pl_essence pl0 pl1 <= m ->\n  pl_path_incl (pl_path_product plp0 plp1) (pl_produit_0 a pl0 pl1 m l).\n\nDefinition pl_produit_path_incl_def_1 (pl0 pl1 : prec_list) :=\n  forall (n m : nat) (plp0 plp1 : pl_path),\n  pl_path_incl plp0 pl0 ->\n  pl_tl_length pl0 n ->\n  pl_path_incl plp1 pl1 ->\n  pl_tl_length pl1 n ->\n  pl_essence pl0 pl1 <= m ->\n  pl_path_incl (pl_path_product plp0 plp1) (pl_produit_1 pl0 m pl1).\n\nLemma pl_produit_path_incl_1_0 :\n forall p : prec_list, pl_produit_path_incl_def_0 p prec_empty.\nProof.\n\tunfold pl_produit_path_incl_def_0 in |- *. intros. inversion H2.\nQed.\n\nLemma pl_produit_path_incl_1_1 :\n forall p : prec_list, pl_produit_path_incl_def_1 p prec_empty.\nProof.\n\tunfold pl_produit_path_incl_def_1 in |- *. intros. inversion H1. inversion H2.\n\trewrite <- H6 in H0. inversion H0. rewrite <- H5 in H. inversion H. simpl in |- *.\n\telim (nat_sum m). intros. rewrite H8. simpl in |- *. exact pl_path_incl_nil.\n\tintros. elim H8. intros. rewrite H9. simpl in |- *. exact pl_path_incl_nil.\nQed.\n\nLemma pl_produit_path_incl_1_2 :\n forall p : prec_list, pl_produit_path_incl_def_1 prec_empty p.\nProof.\n\tunfold pl_produit_path_incl_def_1 in |- *. intros. inversion H0. rewrite <- H5 in H2.\n\tinversion H2. rewrite <- H4 in H1. inversion H1. inversion H. simpl in |- *.\n\telim (nat_sum m); intros. rewrite H8. simpl in |- *. exact pl_path_incl_nil.\n\telim H8. intros. rewrite H9. simpl in |- *. exact pl_path_incl_nil.\nQed.\n\nLemma pl_produit_path_incl_1_3 :\n forall (a : ad) (la ls p : prec_list),\n pl_produit_path_incl_def_0 p ls ->\n pl_produit_path_incl_def_1 p la ->\n pl_produit_path_incl_def_0 p (prec_cons a la ls).\nProof.\n\tunfold pl_produit_path_incl_def_1 in |- *. unfold pl_produit_path_incl_def_0 in |- *.\n\tintros. elim (nat_sum m); intros. rewrite H6 in H5. elim (le_Sn_O 0 (le_trans _ _ _ (pl_ess_invar_0 p (prec_cons a la ls)) H5)). elim H6.\n\tintros. rewrite H7. replace (pl_produit_0 a0 p (prec_cons a la ls) (S x) l) with\n  (prec_cons (iad_conv a0 a) (pl_produit_1 p x la) (pl_produit_0 a0 p ls x l)). inversion H3. inversion H1. simpl in |- *. apply\n  (pl_path_incl_cons (pl_path_product plp2 plp) (iad_conv a0 a)\n     (pl_produit_1 p x la) (pl_produit_0 a0 p ls x l)). apply (H0 n x plp2 plp H15 H2 H10). \n\tinversion H4. exact H19. exact H20.  rewrite H7 in H5. unfold pl_essence in |- *.\n\tunfold pl_essence in H5. elim (le_or_lt (pl_card p + pl_card la) x); intros. exact H18. cut (S (pl_card la) <= pl_card (prec_cons a la ls)).\n\tintro. elim (le_Sn_n (S x)). apply (le_trans (S (S x)) (pl_card p + S (pl_card la)) (S x)). rewrite <- (plus_Snm_nSm (pl_card p) (pl_card la)). simpl in |- *. exact (le_n_S _ _ (lt_le_S _ _ H18)). exact\n  (le_trans _ _ _\n     (plus_le_compat (pl_card p) (pl_card p) (S (pl_card la))\n        (pl_card (prec_cons a la ls)) (le_n_n _) H19) H5). simpl in |- *. exact\n  (le_n_S (pl_card la) (pl_card la + pl_card ls)\n     (le_plus_l (pl_card la) (pl_card ls))).\n\tinversion H16. elim (H18 (sym_eq H19)). apply\n  (pl_path_incl_next (pl_path_product plp0 plp1) (iad_conv a0 a)\n     (pl_produit_1 p x la) (pl_produit_0 a0 p ls x l)). apply (H n x plp0 plp1 a0 l H1 H2). exact H11. inversion H4. rewrite <- H17 in H11.\n\tinversion H11. elim (H13 (sym_eq H19)). exact H19.\n\trewrite H7 in H5. unfold pl_essence in |- *. unfold pl_essence in H5.\n\telim (le_or_lt (pl_card p + pl_card ls) x). intro. exact H14.\n\tintro. simpl in H5. rewrite <- (plus_Snm_nSm (pl_card p) (pl_card la + pl_card ls)) in H5. simpl in H5. elim (le_Sn_n (S x)).\n\tapply (le_trans (S (S x)) (S (pl_card p + (pl_card la + pl_card ls))) (S x)). apply (le_n_S (S x) (pl_card p + (pl_card la + pl_card ls))). exact\n  (le_trans _ _ _ (lt_le_S _ _ H14)\n     (plus_le_compat (pl_card p) (pl_card p) (pl_card ls)\n        (pl_card la + pl_card ls) (le_n_n _)\n        (le_plus_r (pl_card la) (pl_card ls)))). exact H5. \n\tinversion H1. induction  plp1 as [| a3 plp1 Hrecplp1]. elim (H13 (refl_equal _)).\n\tsimpl in |- *. intro. inversion H19. inversion H17. elim (H19 (sym_eq H20)). reflexivity.\nQed.\n\nLemma pl_produit_path_incl_1_4 :\n forall (a : ad) (la ls p : prec_list),\n pl_produit_path_incl_def_0 la p ->\n pl_produit_path_incl_def_1 ls p ->\n pl_produit_path_incl_def_1 (prec_cons a la ls) p.\nProof.\n\tunfold pl_produit_path_incl_def_0 in |- *. unfold pl_produit_path_incl_def_1 in |- *.\n\tintros. induction  p as [a0 p1 Hrecp1 p0 Hrecp0| ]. clear Hrecp0. clear Hrecp1. elim (nat_sum m).\n\tintro. rewrite H6 in H5. elim\n  (le_Sn_O 0\n     (le_trans _ _ _\n        (pl_ess_invar_0 (prec_cons a la ls) (prec_cons a0 p1 p0)) H5)).\n\tintros. elim H6. intros. rewrite H7. replace (pl_produit_1 (prec_cons a la ls) (S x) (prec_cons a0 p1 p0)) with\n  (pl_produit_0 a la (prec_cons a0 p1 p0) x\n     (pl_produit_1 ls x (prec_cons a0 p1 p0))). inversion H1.\n\telim (nat_sum n). intros. rewrite H13 in H2. inversion H2. intros.\n\telim H13. intros. rewrite <- H8. rewrite H9. rewrite H8. apply (H x0 x plp0 plp1 a (pl_produit_1 ls x (prec_cons a0 p1 p0))). rewrite H8 in H9. rewrite <- H9. exact (pl_path_incl_cons plp a la prec_empty H10).\n\trewrite H14 in H2. inversion H2. exact H16. exact H17. exact H3.\n\trewrite H14 in H4. exact H4. unfold pl_essence in |- *. unfold pl_essence in H5.\n\telim (le_or_lt (pl_card la + pl_card (prec_cons a0 p1 p0)) x).\n\tintro. exact H15. intro. rewrite H7 in H5. elim (le_Sn_n (S x)).\n\tapply\n  (le_trans (S (S x))\n     (pl_card (prec_cons a la ls) + pl_card (prec_cons a0 p1 p0)) \n     (S x)). simpl in |- *. simpl in H15.\n\tapply (le_n_S (S x) (pl_card la + pl_card ls + S (pl_card p1 + pl_card p0))). apply\n  (le_trans (S x) (pl_card la + S (pl_card p1 + pl_card p0))\n     (pl_card la + pl_card ls + S (pl_card p1 + pl_card p0))). exact (lt_le_S _ _ H15).\n\texact\n  (plus_le_compat (pl_card la) (pl_card la + pl_card ls)\n     (S (pl_card p1 + pl_card p0)) (S (pl_card p1 + pl_card p0))\n     (le_plus_l (pl_card la) (pl_card ls)) (le_n_n _)). exact H5.\n\tapply\n  (pl_produit_path_incl_0 x a la (prec_cons a0 p1 p0)\n     (pl_produit_1 ls x (prec_cons a0 p1 p0)) (pl_path_product plp0 plp1)). apply (H0 n x plp0 plp1). exact H11. inversion H2. rewrite <- H17 in H11. inversion H11.\n\trewrite <- H19 in H13. elim (H13 (refl_equal pl_path_nil)).\n\texact H19. exact H3. exact H4. rewrite H7 in H5. unfold pl_essence in |- *.\n\tunfold pl_essence in H5. elim (le_or_lt (pl_card ls + pl_card (prec_cons a0 p1 p0)) x). intro. exact H14. intro. simpl in H14.\n\tsimpl in H5. elim (le_Sn_n (S x)). apply\n  (le_trans (S (S x))\n     (S (pl_card la + pl_card ls + S (pl_card p1 + pl_card p0))) \n     (S x)). apply (le_n_S (S x) (pl_card la + pl_card ls + S (pl_card p1 + pl_card p0))). exact\n  (le_trans (S x) (pl_card ls + S (pl_card p1 + pl_card p0))\n     (pl_card la + pl_card ls + S (pl_card p1 + pl_card p0))\n     (lt_le_S x (pl_card ls + S (pl_card p1 + pl_card p0)) H14)\n     (plus_le_compat (pl_card ls) (pl_card la + pl_card ls)\n        (S (pl_card p1 + pl_card p0)) (S (pl_card p1 + pl_card p0))\n        (le_plus_r (pl_card la) (pl_card ls)) (le_n_n _))). exact H5. \n\tinversion H3. inversion H1. simpl in |- *. intro. inversion H24. induction  plp0 as [| a4 plp0 Hrecplp0].\n\telim (H24 (refl_equal pl_path_nil)). simpl in |- *. intro. inversion H25.\n\tinduction  plp0 as [| a3 plp0 Hrecplp0]. elim (H13 (refl_equal _)). induction  plp1 as [| a4 plp1 Hrecplp1].\n\telim (H19 (refl_equal _)). simpl in |- *. intro. inversion H20.\n\trewrite H7 in H5. unfold pl_essence in H5. unfold pl_essence in |- *. simpl in H5.\n\tsimpl in |- *. elim (le_or_lt (pl_card la + S (pl_card p1 + pl_card p0)) x). intro. exact H14. intro. elim (le_Sn_n (S x)). apply\n  (le_trans (S (S x))\n     (S (pl_card la + pl_card ls + S (pl_card p1 + pl_card p0)))). apply (le_n_S (S x) (pl_card la + pl_card ls + S (pl_card p1 + pl_card p0))). exact\n  (le_trans (S x) (pl_card la + S (pl_card p1 + pl_card p0))\n     (pl_card la + pl_card ls + S (pl_card p1 + pl_card p0))\n     (lt_le_S _ _ H14)\n     (plus_le_compat (pl_card la) (pl_card la + pl_card ls)\n        (S (pl_card p1 + pl_card p0)) (S (pl_card p1 + pl_card p0))\n        (le_plus_l _ _) (le_n_n _))). exact H5. reflexivity. inversion H4.\n\trewrite <- H7 in H2. inversion H2.\nQed.\n\nLemma pl_produit_path_incl_1_5 :\n forall p p' : prec_list,\n pl_produit_path_incl_def_0 p p' /\\ pl_produit_path_incl_def_1 p p'.\nProof.\n\texact\n  (indprinciple_pl pl_produit_path_incl_def_0 pl_produit_path_incl_def_1\n     pl_produit_path_incl_1_0 pl_produit_path_incl_1_1\n     pl_produit_path_incl_1_2 pl_produit_path_incl_1_3\n     pl_produit_path_incl_1_4).\nQed.\n\nLemma pl_produit_path_incl_1 :\n forall (pl0 pl1 : prec_list) (n m : nat) (plp0 plp1 : pl_path),\n pl_path_incl plp0 pl0 ->\n pl_tl_length pl0 n ->\n pl_path_incl plp1 pl1 ->\n pl_tl_length pl1 n ->\n pl_essence pl0 pl1 <= m ->\n pl_path_incl (pl_path_product plp0 plp1) (pl_produit_1 pl0 m pl1).\nProof.\n\tintros. elim (pl_produit_path_incl_1_5 pl0 pl1). intros.\n\tunfold pl_produit_path_incl_def_1 in H5.\n\texact (H5 n m plp0 plp1 H H0 H1 H2 H3).\nQed.\n\nLemma pl_produit_path_incl_2 :\n forall (pl0 pl1 : prec_list) (n : nat) (plp0 plp1 : pl_path),\n pl_path_incl plp0 pl0 ->\n pl_tl_length pl0 n ->\n pl_path_incl plp1 pl1 ->\n pl_tl_length pl1 n ->\n pl_path_incl (pl_path_product plp0 plp1) (pl_produit pl0 pl1).\nProof.\n\tintros. unfold pl_produit in |- *. exact\n  (pl_produit_path_incl_1 pl0 pl1 n (pl_essence pl0 pl1) plp0 plp1 H H0 H1 H2\n     (le_n_n _)).\nQed.\n\nDefinition pl_produit_path_incl_def_2 (pl0 pl1 : prec_list) :=\n  forall (n m : nat) (plp : pl_path) (a : ad) (l : prec_list),\n  pl_path_incl plp (pl_produit_0 a pl0 pl1 m l) ->\n  pl_tl_length pl0 n ->\n  pl_tl_length pl1 (S n) ->\n  pl_essence pl0 pl1 <= m ->\n  (exists plp0 : pl_path,\n     (exists plp1 : pl_path,\n        plp = pl_path_product plp0 plp1 /\\\n        pl_path_incl plp0 (prec_cons a pl0 prec_empty) /\\\n        pl_path_incl plp1 pl1)) \\/ pl_path_incl plp l.\n\nDefinition pl_produit_path_incl_def_3 (pl0 pl1 : prec_list) :=\n  forall (n m : nat) (plp : pl_path),\n  pl_path_incl plp (pl_produit_1 pl0 m pl1) ->\n  pl_tl_length pl0 n ->\n  pl_tl_length pl1 n ->\n  pl_essence pl0 pl1 <= m ->\n  exists plp0 : pl_path,\n    (exists plp1 : pl_path,\n       plp = pl_path_product plp0 plp1 /\\\n       pl_path_incl plp0 pl0 /\\ pl_path_incl plp1 pl1).\n\nLemma pl_produit_path_incl_3_0 :\n forall p : prec_list, pl_produit_path_incl_def_2 p prec_empty.\nProof.\n\tunfold pl_produit_path_incl_def_2 in |- *. intros. elim (nat_sum m). intro.\n\trewrite H3 in H2. elim (le_Sn_n 0 (le_trans _ _ _ (pl_ess_invar_0 p prec_empty) H2)). intros. elim H3. intros. rewrite H4 in H. simpl in H.\n\tright. exact H.\nQed.\n\nLemma pl_produit_path_incl_3_1 :\n forall p : prec_list, pl_produit_path_incl_def_3 p prec_empty.\nProof.\n\tunfold pl_produit_path_incl_def_3 in |- *. intros. split with pl_path_nil.\n\tsplit with pl_path_nil. split. elim (nat_sum m). intro. rewrite H3 in H.\n\tsimpl in H. inversion H. reflexivity. intro. elim H3. intros. rewrite H4 in H. simpl in H. induction  p as [a p1 Hrecp1 p0 Hrecp0| ]; inversion H; reflexivity. split. inversion H1.\n\trewrite <- H4 in H0. inversion H0. exact pl_path_incl_nil.\n\texact pl_path_incl_nil.\nQed.\n\nLemma pl_produit_path_incl_3_2 :\n forall p : prec_list, pl_produit_path_incl_def_3 prec_empty p.\nProof.\n\tunfold pl_produit_path_incl_def_3 in |- *. intros. split with pl_path_nil.\n\tsplit with pl_path_nil. split. elim (nat_sum m). intro. rewrite H3 in H.\n\tsimpl in H. inversion H. reflexivity. intros. elim H3. intros. rewrite H4 in H.\n\tsimpl in H. induction  p as [a p1 Hrecp1 p0 Hrecp0| ]; simpl in H; inversion H;\n  reflexivity. split.\n\texact pl_path_incl_nil. inversion H0. rewrite <- H4 in H1. inversion H1.\n\texact pl_path_incl_nil.\nQed.\n\nLemma pl_produit_path_incl_3_3 :\n forall (a : ad) (la ls p : prec_list),\n pl_produit_path_incl_def_2 p ls ->\n pl_produit_path_incl_def_3 p la ->\n pl_produit_path_incl_def_2 p (prec_cons a la ls).\nProof.\n\tunfold pl_produit_path_incl_def_2 in |- *. unfold pl_produit_path_incl_def_3 in |- *. intros.\n\telim (nat_sum m); intros. rewrite H5 in H4. elim (le_Sn_n 0 (le_trans _ _ _ (pl_ess_invar_0 p (prec_cons a la ls)) H4)). elim H5. intros. rewrite H6 in H1.\n\tcut\n  (pl_produit_0 a0 p (prec_cons a la ls) (S x) l =\n   prec_cons (iad_conv a0 a) (pl_produit_1 p x la) (pl_produit_0 a0 p ls x l)). intro. rewrite H7 in H1.\n\tclear H7. inversion H1. elim (H0 n x plp0 H9 H2). intros. elim H12. intros.\n\tleft. split with (pl_path_cons a0 x0). split with (pl_path_cons a x1). elim H13.\n\tintros. elim H15. intros. split. simpl in |- *. rewrite <- H14. reflexivity. split.\n\texact (pl_path_incl_cons x0 a0 p prec_empty H16). exact (pl_path_incl_cons x1 a la ls H17). inversion H3. exact H13. exact H14. unfold pl_essence in |- *. unfold pl_essence in H4. rewrite H6 in H4. simpl in H4. elim (le_or_lt (pl_card p + pl_card la) x). intro. exact H12. intro. elim (le_Sn_n (S x)). apply (le_trans (S (S x)) (pl_card p + S (pl_card la + pl_card ls)) (S x)).\n\trewrite <- (plus_Snm_nSm (pl_card p) (pl_card la + pl_card ls)). simpl in |- *.\n\tapply (le_n_S (S x) (pl_card p + (pl_card la + pl_card ls))).\n\texact\n  (le_trans _ _ _ (lt_le_S _ _ H12)\n     (plus_le_compat (pl_card p) (pl_card p) (pl_card la)\n        (pl_card la + pl_card ls) (le_n_n _)\n        (le_plus_l (pl_card la) (pl_card ls)))). exact H4. elim (pl_sum ls); intro. rewrite H13 in H10.\n\telim (nat_sum x). intros. rewrite H14 in H10. simpl in H10. inversion H10.\n\telim (H12 (sym_eq H15)). intros. elim H14. intros. rewrite H15 in H10.\n\tsimpl in H10. right. exact H10. elim (H n x plp a0 l H10 H2). intros. elim H14.\n\tintros. elim H15. intros. elim H16. intros. elim H18. intros. left. split with x0.\n\tsplit with x1. split. exact H17. split. exact H19. apply (pl_path_incl_next x1 a la ls H20). intro. rewrite H21 in H17. induction  x0 as [| a2 x0 Hrecx0]; inversion H17; rewrite H17 in H12;\n  elim (H12 (refl_equal _)). intro. right. exact H14. inversion H3.\n\trewrite <- H17 in H13. elim H13. intros. elim H19. intros. elim H20. intros.\n\tinversion H21. exact H19. unfold pl_essence in |- *. unfold pl_essence in H4. rewrite H6 in H4. simpl in H4. elim (le_or_lt (pl_card p + pl_card ls) x); intro.\n\texact H14. elim (le_Sn_n (S x)). apply (le_trans (S (S x)) (pl_card p + S (pl_card la + pl_card ls)) (S x)). rewrite <- (plus_Snm_nSm (pl_card p) (pl_card la + pl_card ls)). simpl in |- *. apply (le_n_S (S x) (pl_card p + (pl_card la + pl_card ls))). exact\n  (le_trans (S x) (pl_card p + pl_card ls)\n     (pl_card p + (pl_card la + pl_card ls)) (lt_le_S _ _ H14)\n     (plus_le_compat (pl_card p) (pl_card p) (pl_card ls)\n        (pl_card la + pl_card ls) (le_n_n _) (le_plus_r _ _))). exact H4. reflexivity.\nQed.\n\nLemma pl_produit_path_incl_3_4 :\n forall (a : ad) (la ls p : prec_list),\n pl_produit_path_incl_def_2 la p ->\n pl_produit_path_incl_def_3 ls p ->\n pl_produit_path_incl_def_3 (prec_cons a la ls) p.\nProof.\n\tunfold pl_produit_path_incl_def_3 in |- *. unfold pl_produit_path_incl_def_2 in |- *. intros.\n\telim (nat_sum m). intro. rewrite H5 in H4. elim (le_Sn_n 0 (le_trans _ _ _ (pl_ess_invar_0 (prec_cons a la ls) p) H4)). intros. elim H5. intros. rewrite H6 in H1. elim (pl_sum p). intros. rewrite H7 in H1. rewrite H7 in H3. inversion H3.\n\trewrite <- H9 in H2. inversion H2. intros. cut\n  (pl_produit_1 (prec_cons a la ls) (S x) p =\n   pl_produit_0 a la p x (pl_produit_1 ls x p)). intro. rewrite H8 in H1.\n\tclear H8. inversion H1. rewrite (pl_product_1 a la p (pl_produit_1 ls x p) x) in H7.\n\telim H7. intros. elim H9. intros. elim H11. intros. inversion H12. rewrite H6 in H4.\n\tunfold pl_essence in |- *. unfold pl_essence in H4. simpl in H4. elim (le_or_lt (pl_card la + pl_card p) x). intro. exact H9. intro. elim (le_Sn_n (S x)).\n\tapply (le_trans (S (S x)) (S (pl_card la + pl_card ls + pl_card p)) (S x)). apply (le_n_S (S x) (pl_card la + pl_card ls + pl_card p)).\n\texact\n  (le_trans _ _ _ (lt_le_S _ _ H9)\n     (plus_le_compat (pl_card la) (pl_card la + pl_card ls) \n        (pl_card p) (pl_card p) (le_plus_l _ _) (le_n_n _))). exact H4.\n\texact (sym_eq H10). elim (nat_sum n). intro. rewrite H11 in H2.\n\tinversion H2. intro. elim H11. intros. rewrite H12 in H2. elim (H x0 x plp a (pl_produit_1 ls x p) H1). intros. elim H13. intros. elim H14. intros. elim H15.\n\tintros. elim H17. intros. split with x1. split with x2. split. rewrite <- H16.\n\texact H9. split. inversion H18. exact (pl_path_incl_cons plp1 a la ls H22).\n\tinversion H23. elim (H25 (sym_eq H26)). exact H19. intro. elim (pl_sum ls). intro. rewrite H14 in H13. induction  x as [| x Hrecx]; simpl in H13. inversion H13.\n\trewrite <- H15 in H9. inversion H9. induction  p as [a1 p1 Hrecp1 p0 Hrecp0| ]; inversion H13. rewrite <- H15 in H9.\n\tinversion H9. rewrite <- H15 in H9. inversion H9. intros. elim (H0 n x plp H13).\n\tintros. elim H15. intros. elim H16. intros. elim H18. intros. split with x1.\n\tsplit with x2. split. rewrite <- H17. exact H9. split. apply (pl_path_incl_next x1 a la ls H19). intro. rewrite H21 in H17. induction  x2 as [| a1 x2 Hrecx2]; inversion H17; rewrite H17 in H9;\n  inversion H9. exact H20. inversion H2. rewrite <- H18 in H14. elim H14.\n\tintros. elim H20. intros. elim H21. intros. inversion H22. rewrite H12. exact H20.\n\texact H3. rewrite H6 in H4. unfold pl_essence in |- *. unfold pl_essence in H4. simpl in H4.\n\telim (le_or_lt (pl_card ls + pl_card p) x). intro. exact H15. intros.\n\telim (le_Sn_n (S x)). apply (le_trans (S (S x)) (S (pl_card la + pl_card ls + pl_card p)) (S x)). apply (le_n_S (S x) (pl_card la + pl_card ls + pl_card p)). exact\n  (le_trans _ _ _ (lt_le_S _ _ H15)\n     (plus_le_compat (pl_card ls) (pl_card la + pl_card ls) \n        (pl_card p) (pl_card p) (le_plus_r _ _) (le_n_n _))). exact H4. inversion H2. exact H14. exact H15.\n\trewrite H12 in H3. exact H3. unfold pl_essence in |- *. unfold pl_essence in H4. \n\trewrite H6 in H4. simpl in H4. elim (le_or_lt (pl_card la + pl_card p) x).\n\tintro. exact H13. intro. elim (le_Sn_n (S x)). apply (le_trans (S (S x)) (S (pl_card la + pl_card ls + pl_card p)) (S x)). apply (le_n_S (S x) (pl_card la + pl_card ls + pl_card p)). apply\n  (le_trans (S x) (pl_card la + pl_card p)\n     (pl_card la + pl_card ls + pl_card p)).\n\texact (lt_le_S _ _ H13). exact\n  (plus_le_compat (pl_card la) (pl_card la + pl_card ls) \n     (pl_card p) (pl_card p) (le_plus_l _ _) (le_n_n _)). exact H4. elim (nat_sum n).\n\tintro. rewrite H12 in H2. inversion H2. intro. elim H12. intros. elim (H x0 x plp a (pl_produit_1 ls x p) H1). intros. elim H14. intros. elim H15. intros. elim H16.\n\tintros. elim H18. intros. split with x1. split with x2. split. exact H17. split.\n\tinversion H19. exact (pl_path_incl_cons plp1 a la ls H23). inversion H24.\n\trewrite <- H27 in H26. elim (H26 (refl_equal _)). exact H20. intro.\n\telim (pl_sum ls). intro. rewrite H15 in H14. elim (nat_sum x); intro.\n\trewrite H16 in H14. inversion H14. elim (H11 (sym_eq H17)). elim H16.\n\tintros. rewrite H17 in H14. elim (pl_sum p). intro. rewrite H18 in H14. simpl in H14.\n\tinversion H14. elim (H11 (sym_eq H19)). intros. elim H18. intros.\n\telim H19. intros. elim H20. intros. rewrite H21 in H14. simpl in H14. inversion H14.\n\telim (H11 (sym_eq H22)). intro. inversion H2. rewrite <- H19 in H15.\n\telim H15. intros. elim H21. intros. elim H22. intros. inversion H23.\n\telim (H0 (S n0) x plp H14 H21). intros. elim H22. intros. elim H23. intros. elim H25.\n\tintros. split with x1. split with x2. split. exact H24. split. apply (pl_path_incl_next x1 a la ls H26). intro. rewrite H28 in H24. induction  x2 as [| a2 x2 Hrecx2]; inversion H24; rewrite H24 in H11;\n  elim (H11 (refl_equal pl_path_nil)).\n\texact H27. rewrite H18. exact H3. unfold pl_essence in |- *. rewrite H6 in H4.\n\tunfold pl_essence in H4. simpl in H4. elim (le_or_lt (pl_card ls + pl_card p) x); intro. exact H22. elim (le_Sn_n (S x)). apply (le_trans (S (S x)) (S (pl_card la + pl_card ls + pl_card p)) (S x)). apply (le_n_S (S x) (pl_card la + pl_card ls + pl_card p)). exact\n  (le_trans _ _ _ (lt_le_S _ _ H22)\n     (plus_le_compat (pl_card ls) (pl_card la + pl_card ls) \n        (pl_card p) (pl_card p) (le_plus_r _ _) (le_n_n _))). exact H4. rewrite H13 in H2. inversion H2; assumption.\n\trewrite H13 in H3. exact H3. unfold pl_essence in H4. rewrite H6 in H4. simpl in H4.\n\tunfold pl_essence in |- *. elim (le_or_lt (pl_card la + pl_card p) x). intro.\n\texact H14. intro. elim (le_Sn_n (S x)). apply (le_trans (S (S x)) (S (pl_card la + pl_card ls + pl_card p)) (S x)). apply (le_n_S (S x) (pl_card la + pl_card ls + pl_card p)). exact\n  (le_trans _ _ _ (lt_le_S _ _ H14)\n     (plus_le_compat (pl_card la) (pl_card la + pl_card ls) \n        (pl_card p) (pl_card p) (le_plus_l _ _) (le_n_n _))). exact H4. elim H7. intros. elim H8; intros.\n\telim H9. intros. rewrite H10. reflexivity.\nQed.\n\nLemma pl_produit_path_incl_3_5 :\n forall p p' : prec_list,\n pl_produit_path_incl_def_2 p p' /\\ pl_produit_path_incl_def_3 p p'.\nProof.\n\texact\n  (indprinciple_pl pl_produit_path_incl_def_2 pl_produit_path_incl_def_3\n     pl_produit_path_incl_3_0 pl_produit_path_incl_3_1\n     pl_produit_path_incl_3_2 pl_produit_path_incl_3_3\n     pl_produit_path_incl_3_4).\nQed.\n\nLemma pl_produit_path_incl_3 :\n forall (pl0 pl1 : prec_list) (n m : nat) (plp : pl_path),\n pl_path_incl plp (pl_produit_1 pl0 m pl1) ->\n pl_tl_length pl0 n ->\n pl_tl_length pl1 n ->\n pl_essence pl0 pl1 <= m ->\n exists plp0 : pl_path,\n   (exists plp1 : pl_path,\n      plp = pl_path_product plp0 plp1 /\\\n      pl_path_incl plp0 pl0 /\\ pl_path_incl plp1 pl1).\nProof.\n\tintro. intro. elim (pl_produit_path_incl_3_5 pl0 pl1). intro. intro. exact H0.\nQed.\n\nLemma pl_produit_path_incl_4 :\n forall (pl0 pl1 : prec_list) (n : nat) (plp : pl_path),\n pl_path_incl plp (pl_produit pl0 pl1) ->\n pl_tl_length pl0 n ->\n pl_tl_length pl1 n ->\n exists plp0 : pl_path,\n   (exists plp1 : pl_path,\n      plp = pl_path_product plp0 plp1 /\\\n      pl_path_incl plp0 pl0 /\\ pl_path_incl plp1 pl1).\nProof.\n\tintros. unfold pl_produit in H. exact\n  (pl_produit_path_incl_3 pl0 pl1 n (pl_essence pl0 pl1) plp H H0 H1\n     (le_n_n _)).\nQed.\n\n(* calcul de l'état produit *)\n\nFixpoint s_produit_l (a : ad) (p : prec_list) (s : state) {struct s} :\n state :=\n  match s with\n  | M0 => M0 prec_list\n  | M1 a' p' =>\n      if Neqb a a' then M1 prec_list a (pl_produit p p') else M0 prec_list\n  | M2 s0 s1 =>\n      match a with\n      | N0 => M2 prec_list (s_produit_l N0 p s0) (M0 prec_list)\n      | Npos q =>\n          match q with\n          | xH => M2 prec_list (M0 prec_list) (s_produit_l N0 p s1)\n          | xO q' => M2 prec_list (s_produit_l (Npos q') p s0) (M0 prec_list)\n          | xI q' => M2 prec_list (M0 prec_list) (s_produit_l (Npos q') p s1)\n          end\n      end\n  end.\n\nDefinition sproductl_0_def (s : state) : Prop :=\n  forall (a : ad) (p : prec_list) (c : ad) (r0 r1 : prec_list),\n  MapGet prec_list (M1 prec_list a p) c = Some r0 ->\n  MapGet prec_list s c = Some r1 ->\n  MapGet prec_list (s_produit_l a p s) c = Some (pl_produit r0 r1).\n\nLemma sproductl_0_0 : sproductl_0_def (M0 prec_list).\nProof.\n\tunfold sproductl_0_def in |- *. intros. inversion H0.\nQed.\n\nLemma sproductl_0_1 :\n forall (a : ad) (a0 : prec_list), sproductl_0_def (M1 prec_list a a0).\nProof.\n\tunfold sproductl_0_def in |- *. intros. simpl in H. simpl in H0.\n\telim (bool_is_true_or_false (Neqb a1 c)); intro; rewrite H1 in H.\n\telim (bool_is_true_or_false (Neqb a c)); intro; rewrite H2 in H0.\n\tinversion H. inversion H0. rewrite (Neqb_complete _ _ H1).\n\trewrite (Neqb_complete _ _ H2). simpl in |- *. rewrite (Neqb_correct c).\n\tsimpl in |- *. rewrite (Neqb_correct c). trivial. inversion H0. inversion H.\nQed.\n\nLemma sproductl_0_2 :\n forall m : state,\n sproductl_0_def m ->\n forall m0 : state, sproductl_0_def m0 -> sproductl_0_def (M2 prec_list m m0).\nProof.\n\tunfold sproductl_0_def in |- *.\n\tintros. simpl in H1. elim (bool_is_true_or_false (Neqb a c)); intro.\n\trewrite H3 in H1. inversion H1. rewrite (Neqb_complete _ _ H3). \n\tinduction  c as [| p0]. simpl in |- *. elim (H N0 r0 N0 r0 r1). reflexivity. reflexivity.\n\tsimpl in H2. exact H2.  induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in |- *. elim (H0 (Npos p0) r0 (Npos p0) r0 r1). reflexivity. simpl in |- *. rewrite (aux_Neqb_1_0 p0).\n\treflexivity. simpl in H2. exact H2. simpl in |- *. elim (H (Npos p0) r0 (Npos p0) r0 r1). reflexivity. simpl in |- *. rewrite (aux_Neqb_1_0 p0). reflexivity.\n\tsimpl in H2. exact H2. simpl in |- *. elim (H0 N0 r0 N0 r0 r1). reflexivity.\n\treflexivity. simpl in H2. exact H2. rewrite H3 in H1. inversion H1.\nQed.\n\nLemma sproductl_0_3 : forall m : state, sproductl_0_def m.\nProof.\n\texact\n  (Map_ind prec_list sproductl_0_def sproductl_0_0 sproductl_0_1\n     sproductl_0_2).\nQed.\n\nLemma sproductl_0 :\n forall (s : state) (a : ad) (p : prec_list) (c : ad) (r0 r1 : prec_list),\n MapGet prec_list (M1 prec_list a p) c = Some r0 ->\n MapGet prec_list s c = Some r1 ->\n MapGet prec_list (s_produit_l a p s) c = Some (pl_produit r0 r1).\nProof.\n\texact\n  (Map_ind prec_list sproductl_0_def sproductl_0_0 sproductl_0_1\n     sproductl_0_2).\nQed.\n\nDefinition sproductl_1_def (s : state) : Prop :=\n  forall (a : ad) (p : prec_list) (c : ad) (r : prec_list),\n  MapGet prec_list (s_produit_l a p s) c = Some r ->\n  exists r0 : prec_list,\n    (exists r1 : prec_list,\n       MapGet prec_list (M1 prec_list a p) c = Some r0 /\\\n       MapGet prec_list s c = Some r1).\n\nLemma sproductl_1_0 : sproductl_1_def (M0 prec_list).\nProof.\n\tunfold sproductl_1_def in |- *. intros. inversion H.\nQed.\n\nLemma sproductl_1_1 :\n forall (a : ad) (a0 : prec_list), sproductl_1_def (M1 prec_list a a0).\nProof.\n\tunfold sproductl_1_def in |- *. intros. simpl in H. elim (bool_is_true_or_false (Neqb a1 a)); intro; rewrite H0 in H. simpl in H. elim (bool_is_true_or_false (Neqb a1 c)); intro; rewrite H1 in H. split with p. split with a0. simpl in |- *.\n\tsplit. rewrite H1. reflexivity. rewrite <- (Neqb_complete _ _ H0).\n\trewrite H1. reflexivity. inversion H. inversion H.\nQed.\n\nLemma sproductl_1_2 :\n forall m : state,\n sproductl_1_def m ->\n forall m0 : state, sproductl_1_def m0 -> sproductl_1_def (M2 prec_list m m0).\nProof.\n\tunfold sproductl_1_def in |- *. intros. induction  a as [| p0]. induction  c as [| p0]. simpl in H1.\n\telim (H N0 p N0 r H1). intros. elim H2. intros. elim H3. intros.\n\tsplit with x. split with x0. split. exact H4. simpl in |- *. exact H5. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ].\n\tsimpl in H1. inversion H1. simpl in H1. elim (H N0 p (Npos p0) r H1).\n\tintros. elim H2. intros. elim H3. intros. split with x. split with x0.\n\tsplit. exact H4. simpl in |- *. exact H5. simpl in H1. inversion H1. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ].\n\tinduction  c as [| p1]. simpl in H1. inversion H1. simpl in H1. induction  p1 as [p1 Hrecp1| p1 Hrecp1| ].\n\telim (H0 (Npos p0) p (Npos p1) r H1). intros. elim H2. intros. elim H3.\n\tintros. intros. split with x. split with x0. split. exact H4. simpl in |- *.\n\texact H5. inversion H1. elim (H0 (Npos p0) p N0 r H1). intros. elim H2.\n\tintros. elim H3. intros. split with x. split with x0. simpl in |- *. split. simpl in H4. exact H4. exact H5. induction  c as [| p1]. simpl in H1. elim (H (Npos p0) p N0 r H1). intros. elim H2. intros. elim H3. intros. split with x.\n\tsplit with x0. simpl in |- *. split. simpl in H4. exact H4. exact H5. simpl in H1.\n\tinduction  p1 as [p1 Hrecp1| p1 Hrecp1| ]. inversion H1. elim (H (Npos p0) p (Npos p1) r H1). intros.\n\telim H2. intros. elim H3. intros. split with x. split with x0. simpl in |- *.\n\tsplit. simpl in H4. exact H4. exact H5. inversion H1. induction  c as [| p0]. simpl in H1.\n\tinversion H1. simpl in H1. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. elim (H0 N0 p (Npos p0) r H1).\n\tintros. elim H2. intros. elim H3. intros. split with x. split with x0.\n\tsimpl in |- *. simpl in H4. split. exact H4. exact H5. inversion H1. elim (H0 N0 p N0 r H1). intros. elim H2. intros. elim H3. intros. split with x.\n\tsplit with x0. simpl in |- *. split. simpl in H4. exact H4. exact H5.\nQed.\n\nLemma sproductl_1_3 : forall m : state, sproductl_1_def m.\nProof.\n\texact\n  (Map_ind prec_list sproductl_1_def sproductl_1_0 sproductl_1_1\n     sproductl_1_2).\nQed.\n\nLemma sproductl_1 :\n forall (s : state) (a : ad) (p : prec_list) (c : ad) (r : prec_list),\n MapGet prec_list (s_produit_l a p s) c = Some r ->\n exists r0 : prec_list,\n   (exists r1 : prec_list,\n      MapGet prec_list (M1 prec_list a p) c = Some r0 /\\\n      MapGet prec_list s c = Some r1).\nProof.\n\texact\n  (Map_ind prec_list sproductl_1_def sproductl_1_0 sproductl_1_1\n     sproductl_1_2).\nQed.\n\nFixpoint s_produit_r (a : ad) (p : prec_list) (s : state) {struct s} :\n state :=\n  match s with\n  | M0 => M0 prec_list\n  | M1 a' p' =>\n      if Neqb a a' then M1 prec_list a (pl_produit p' p) else M0 prec_list\n  | M2 s0 s1 =>\n      match a with\n      | N0 => M2 prec_list (s_produit_r N0 p s0) (M0 prec_list)\n      | Npos q =>\n          match q with\n          | xH => M2 prec_list (M0 prec_list) (s_produit_r N0 p s1)\n          | xO q' => M2 prec_list (s_produit_r (Npos q') p s0) (M0 prec_list)\n          | xI q' => M2 prec_list (M0 prec_list) (s_produit_r (Npos q') p s1)\n          end\n      end\n  end.\n\nDefinition sproductr_0_def (s : state) : Prop :=\n  forall (a : ad) (p : prec_list) (c : ad) (r0 r1 : prec_list),\n  MapGet prec_list (M1 prec_list a p) c = Some r0 ->\n  MapGet prec_list s c = Some r1 ->\n  MapGet prec_list (s_produit_r a p s) c = Some (pl_produit r1 r0).\n\nLemma sproductr_0_0 : sproductr_0_def (M0 prec_list).\nProof.\n\tunfold sproductr_0_def in |- *. intros. inversion H0.\nQed.\n\nLemma sproductr_0_1 :\n forall (a : ad) (a0 : prec_list), sproductr_0_def (M1 prec_list a a0).\nProof.\n\tunfold sproductr_0_def in |- *. intros. simpl in H. simpl in H0.\n\telim (bool_is_true_or_false (Neqb a1 c)); intro; rewrite H1 in H.\n\telim (bool_is_true_or_false (Neqb a c)); intro; rewrite H2 in H0.\n\tinversion H. inversion H0. rewrite (Neqb_complete _ _ H1).\n\trewrite (Neqb_complete _ _ H2). simpl in |- *. rewrite (Neqb_correct c).\n\tsimpl in |- *. rewrite (Neqb_correct c). trivial. inversion H0. inversion H.\nQed.\n\nLemma sproductr_0_2 :\n forall m : state,\n sproductr_0_def m ->\n forall m0 : state, sproductr_0_def m0 -> sproductr_0_def (M2 prec_list m m0).\nProof.\n\tunfold sproductr_0_def in |- *.\n\tintros. simpl in H1. elim (bool_is_true_or_false (Neqb a c)); intro; rewrite H3 in H1. inversion H1. rewrite (Neqb_complete _ _ H3).\n\tinduction  c as [| p0]. simpl in |- *. elim (H N0 r0 N0 r0 r1). reflexivity. reflexivity.\n\tsimpl in H2. exact H2. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in |- *. elim (H0 (Npos p0) r0 (Npos p0) r0 r1). reflexivity. simpl in |- *. rewrite (aux_Neqb_1_0 p0). reflexivity.\n\tsimpl in H2. exact H2. simpl in |- *. elim (H (Npos p0) r0 (Npos p0) r0 r1).\n\treflexivity. simpl in |- *. rewrite (aux_Neqb_1_0 p0). reflexivity.\n\tsimpl in H2. exact H2. simpl in |- *. elim (H0 N0 r0 N0 r0 r1). reflexivity.\n\treflexivity. simpl in H2. exact H2. inversion H1.\nQed.\n\nLemma sproductr_0_3 : forall m : state, sproductr_0_def m.\nProof.\n\texact\n  (Map_ind prec_list sproductr_0_def sproductr_0_0 sproductr_0_1\n     sproductr_0_2).\nQed.\n\nLemma sproductr_0 :\n forall (s : state) (a : ad) (p : prec_list) (c : ad) (r0 r1 : prec_list),\n MapGet prec_list (M1 prec_list a p) c = Some r0 ->\n MapGet prec_list s c = Some r1 ->\n MapGet prec_list (s_produit_r a p s) c = Some (pl_produit r1 r0).\nProof.\n\texact\n  (Map_ind prec_list sproductr_0_def sproductr_0_0 sproductr_0_1\n     sproductr_0_2).\nQed.\n\nDefinition sproductr_1_def (s : state) : Prop :=\n  forall (a : ad) (p : prec_list) (c : ad) (r : prec_list),\n  MapGet prec_list (s_produit_r a p s) c = Some r ->\n  exists r0 : prec_list,\n    (exists r1 : prec_list,\n       MapGet prec_list (M1 prec_list a p) c = Some r0 /\\\n       MapGet prec_list s c = Some r1).\n\nLemma sproductr_1_0 : sproductr_1_def (M0 prec_list).\nProof.\n\tunfold sproductr_1_def in |- *. intros. inversion H.\nQed.\n\nLemma sproductr_1_1 :\n forall (a : ad) (a0 : prec_list), sproductr_1_def (M1 prec_list a a0).\nProof.\n\tunfold sproductr_1_def in |- *.\n\tintros. simpl in H. elim (bool_is_true_or_false (Neqb a1 a)); intro; rewrite H0 in H. simpl in H. elim (bool_is_true_or_false (Neqb a1 c)); intro; rewrite H1 in H. split with p. split with a0. simpl in |- *. split. rewrite H1.\n\treflexivity. rewrite <- (Neqb_complete _ _ H0). rewrite H1. reflexivity.\n\tinversion H. inversion H.\nQed.\n\nLemma sproductr_1_2 :\n forall m : state,\n sproductr_1_def m ->\n forall m0 : state, sproductr_1_def m0 -> sproductr_1_def (M2 prec_list m m0).\nProof.\n\tunfold sproductr_1_def in |- *.\n\tintros. induction  a as [| p0]. induction  c as [| p0]. simpl in H1. elim (H N0 p N0 r H1).\n\tintros. elim H2. intros. elim H3. intros. elim H4. intros. split with x.\n\tsplit with x0. simpl in |- *. split. simpl in H4. exact H4. exact H5. simpl in H1.\n\tinduction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. inversion H1. simpl in H1. elim (H N0 p (Npos p0) r H1).\n\tintros. elim H2. intros. elim H3. intros. elim H4. intros. split with x.\n\tsplit with x0. simpl in |- *. split. simpl in H4. exact H4. exact H5. inversion H1.\n\tinduction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. induction  c as [| p1]. simpl in H1. inversion H1. simpl in H1.\n\tinduction  p1 as [p1 Hrecp1| p1 Hrecp1| ]. elim (H0 (Npos p0) p (Npos p1) r H1). intros. elim H2.\n\tintros. elim H3. intros. elim H4. intros. split with x. split with x0.\n\tsimpl in |- *. split. simpl in H4. exact H4. exact H5. inversion H1.\n\telim (H0 (Npos p0) p N0 r H1). intros. elim H2. intros. elim H3. intros.\n\telim H4. intros. split with x. split with x0. simpl in |- *. split. simpl in H4.\n\texact H4. exact H5. induction  c as [| p1]. simpl in H1. elim (H (Npos p0) p N0 r H1).\n\tintros. elim H2. intros. elim H3. intros. elim H4. intros. split with x.\n\tsplit with x0. simpl in |- *. split. simpl in H4. exact H4. exact H5. simpl in H1.\n\tinduction  p1 as [p1 Hrecp1| p1 Hrecp1| ]. inversion H1. elim (H (Npos p0) p (Npos p1) r H1). intros.\n\telim H2. intros. elim H3. intros. elim H4. intros. split with x. split with x0. simpl in |- *. split. simpl in H4. exact H4. exact H5. inversion H1. induction  c as [| p0].\n\tsimpl in H1. inversion H1. simpl in H. simpl in H1. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ].\n\telim (H0 N0 p (Npos p0) r H1). intros. elim H2. intros. elim H3. intros.\n\telim H4. intros. split with x. split with x0. simpl in |- *. split. simpl in H4.\n\texact H4. exact H5. inversion H1. elim (H0 N0 p N0 r H1). intros.\n\telim H2. intros. elim H3. intros. elim H4. intros. split with x. split with x0. simpl in |- *. split. simpl in H4. exact H4.  exact H5.\nQed.\n\nLemma sproductr_1_3 : forall m : state, sproductr_1_def m.\nProof.\n\texact\n  (Map_ind prec_list sproductr_1_def sproductr_1_0 sproductr_1_1\n     sproductr_1_2).\nQed.\n\nLemma sproductr_1 :\n forall (s : state) (a : ad) (p : prec_list) (c : ad) (r : prec_list),\n MapGet prec_list (s_produit_r a p s) c = Some r ->\n exists r0 : prec_list,\n   (exists r1 : prec_list,\n      MapGet prec_list (M1 prec_list a p) c = Some r0 /\\\n      MapGet prec_list s c = Some r1).\nProof.\n\texact\n  (Map_ind prec_list sproductr_1_def sproductr_1_0 sproductr_1_1\n     sproductr_1_2).\nQed.\n\nFixpoint s_produit (s0 s1 : state) {struct s1} : state :=\n  match s0, s1 with\n  | M0, M0 => M0 prec_list\n  | M0, M1 a1 p1 => M0 prec_list\n  | M0, M2 s10 s11 => M0 prec_list\n  | M1 a0 p0, M0 => M0 prec_list\n  | M1 a0 p0, M1 a1 p1 => s_produit_l a0 p0 (M1 prec_list a1 p1)\n  | M1 a0 p0, M2 s10 s11 => s_produit_l a0 p0 (M2 prec_list s10 s11)\n  | M2 s00 s01, M0 => M0 prec_list\n  | M2 s00 s01, M1 a1 p1 => s_produit_r a1 p1 (M2 prec_list s00 s01)\n  | M2 s00 s01, M2 s10 s11 =>\n      M2 prec_list (s_produit s00 s10) (s_produit s01 s11)\n  end.\n\nLemma s_produit_0 :\n forall (s0 s1 : state) (c : ad) (p0 p1 : prec_list),\n MapGet prec_list s0 c = Some p0 ->\n MapGet prec_list s1 c = Some p1 ->\n MapGet prec_list (s_produit s0 s1) c = Some (pl_produit p0 p1).\nProof.\n\tsimple induction s0. intros. inversion H. intros. induction  s1 as [| a1 a2| s1_1 Hrecs1_1 s1_0 Hrecs1_0]. inversion H0.\n\tunfold s_produit in |- *. exact (sproductl_0 (M1 prec_list a1 a2) a a0 c p0 p1 H H0).\n\tunfold s_produit in |- *. exact (sproductl_0 (M2 prec_list s1_1 s1_0) a a0 c p0 p1 H H0).\n\tintros. induction  s1 as [| a a0| s1_1 Hrecs1_1 s1_0 Hrecs1_0]. inversion H2. unfold s_produit in |- *. exact (sproductr_0 (M2 prec_list m m0) a a0 c p1 p0 H2 H1). induction  c as [| p]. simpl in |- *.\n\tsimpl in H1. simpl in H2. exact (H s1_1 N0 p0 p1 H1 H2). induction  p as [p Hrecp| p Hrecp| ].\n\tsimpl in |- *. simpl in H1. simpl in H2. exact (H0 s1_0 (Npos p) p0 p1 H1 H2).\n\tsimpl in H1. simpl in H2. simpl in |- *. exact (H s1_1 (Npos p) p0 p1 H1 H2).\n\tsimpl in |- *. simpl in H1. simpl in H2. exact (H0 s1_0 N0 p0 p1 H1 H2).\nQed.\n\nLemma s_produit_1 :\n forall (s0 s1 : state) (c : ad) (p : prec_list),\n MapGet prec_list (s_produit s0 s1) c = Some p ->\n exists p0 : prec_list,\n   (exists p1 : prec_list,\n      MapGet prec_list s0 c = Some p0 /\\\n      MapGet prec_list s1 c = Some p1).\nProof.\n\tsimple induction s0. simple induction s1. intros. simpl in H. inversion H. intros.\n\tsimpl in H. inversion H. intros. simpl in H1. inversion H1. simple induction s1.\n\tintros. simpl in H. inversion H. intros. unfold s_produit in H.\n\texact (sproductl_1 (M1 prec_list a1 a2) a a0 c p H). intros. simpl in H.\n\tunfold s_produit in H1. exact (sproductl_1 (M2 prec_list m m0) a a0 c p H1).\n\tsimple induction s1; intros. inversion H1. unfold s_produit in H1. elim (sproductr_1 (M2 prec_list m m0) a a0 c p H1). intros. elim H2. intros. elim H3. intros.\n\tsplit with x0. split with x. split. exact H5. exact H4. induction  c as [| p0]. \n\tsimpl in H3. elim (H m1 N0 p H3). intros. elim H4. intros. elim H5. intros.\n\tsplit with x. split with x0. split. simpl in |- *. exact H6. simpl in |- *. exact H7.\n\tinduction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in H3. elim (H0 m2 (Npos p0) p H3). intros. elim H4.\n\tintros. elim H5. intros. split with x. split with x0. simpl in |- *. split. \n\texact H6. exact H7. simpl in H3. elim (H m1 (Npos p0) p H3). intros.\n\telim H4. intros. elim H5. intros. split with x. split with x0. simpl in |- *.\n\tsplit. exact H6. exact H7. simpl in H3. elim (H0 m2 N0 p H3). intros.\n\telim H4. intros. elim H5. intros. split with x. split with x0. simpl in |- *.\n\tsplit. exact H6. exact H7.\nQed.\n\n(* preDTA produit *)\n\nFixpoint preDTA_produit_l (a : ad) (s : state) (d : preDTA) {struct d} :\n preDTA :=\n  match d with\n  | M0 => M0 state\n  | M1 a' s' => M1 state (iad_conv a a') (s_produit s s')\n  | M2 s0 s1 =>\n      match a with\n      | N0 =>\n          M2 state\n            (M2 state (preDTA_produit_l N0 s s0)\n               (preDTA_produit_l N0 s s1)) (M0 state)\n      | Npos p =>\n          match p with\n          | xH =>\n              M2 state (M0 state)\n                (M2 state (preDTA_produit_l N0 s s0)\n                   (preDTA_produit_l N0 s s1))\n          | xO p' =>\n              M2 state\n                (M2 state (preDTA_produit_l (Npos p') s s0)\n                   (preDTA_produit_l (Npos p') s s1)) \n                (M0 state)\n          | xI p' =>\n              M2 state (M0 state)\n                (M2 state (preDTA_produit_l (Npos p') s s0)\n                   (preDTA_produit_l (Npos p') s s1))\n          end\n      end\n  end.\n\nFixpoint preDTA_produit_r (a : ad) (s : state) (d : preDTA) {struct d} :\n preDTA :=\n  match d with\n  | M0 => M0 state\n  | M1 a' s' => M1 state (iad_conv a' a) (s_produit s' s)\n  | M2 s0 s1 =>\n      match a with\n      | N0 =>\n          M2 state (M2 state (preDTA_produit_r N0 s s0) (M0 state))\n            (M2 state (preDTA_produit_r N0 s s1) (M0 state))\n      | Npos p =>\n          match p with\n          | xH =>\n              M2 state (M2 state (M0 state) (preDTA_produit_r N0 s s0))\n                (M2 state (M0 state) (preDTA_produit_r N0 s s1))\n          | xO p' =>\n              M2 state\n                (M2 state (preDTA_produit_r (Npos p') s s0) (M0 state))\n                (M2 state (preDTA_produit_r (Npos p') s s1) (M0 state))\n          | xI p' =>\n              M2 state\n                (M2 state (M0 state) (preDTA_produit_r (Npos p') s s0))\n                (M2 state (M0 state) (preDTA_produit_r (Npos p') s s1))\n          end\n      end\n  end.\n\n\nFixpoint preDTA_produit (d0 d1 : preDTA) {struct d1} : preDTA :=\n  match d0, d1 with\n  | M0, M0 => M0 state\n  | M0, M1 a1 s1 => M0 state\n  | M0, M2 s10 s11 => M0 state\n  | M1 a0 s0, M0 => M0 state\n  | M1 a0 s0, M1 a1 s1 => preDTA_produit_l a0 s0 (M1 state a1 s1)\n  | M1 a0 s0, M2 s10 s11 => preDTA_produit_l a0 s0 (M2 state s10 s11)\n  | M2 s00 s01, M0 => M0 state\n  | M2 s00 s01, M1 a1 s1 => preDTA_produit_r a1 s1 (M2 state s00 s01)\n  | M2 s00 s01, M2 s10 s11 =>\n      M2 state (M2 state (preDTA_produit s00 s10) (preDTA_produit s00 s11))\n        (M2 state (preDTA_produit s01 s10) (preDTA_produit s01 s11))\n  end.\n\n\nDefinition predta_produit_0d_def (d : preDTA) : Prop :=\n  forall (a : ad) (s : state) (a0 a1 : ad) (s0 s1 : state),\n  MapGet state (M1 state a s) a0 = Some s0 ->\n  MapGet state d a1 = Some s1 ->\n  MapGet state (preDTA_produit_l a s d) (iad_conv a0 a1) =\n  Some (s_produit s0 s1).\n\nLemma predta_produit_0_0 : predta_produit_0d_def (M0 state).\nProof.\n\tunfold predta_produit_0d_def in |- *. intros. inversion H0.\nQed.\n\nLemma predta_produit_0_1 :\n forall (a : ad) (a0 : state), predta_produit_0d_def (M1 state a a0).\nProof.\n\tunfold predta_produit_0d_def in |- *. intros. simpl in H. simpl in H0.\n\telim (bool_is_true_or_false (Neqb a1 a2)); intro; rewrite H1 in H.\n\trewrite (Neqb_complete a1 a2 H1). elim (bool_is_true_or_false (Neqb a a3)); intro; rewrite H2 in H0. rewrite (Neqb_complete a a3 H2). inversion H.\n\tinversion H0. simpl in |- *. rewrite (Neqb_correct (iad_conv a2 a3)). trivial.\n\tinversion H0. inversion H.\nQed.\n\nLemma predta_produit_0_2 :\n forall m : preDTA,\n predta_produit_0d_def m ->\n forall m0 : preDTA,\n predta_produit_0d_def m0 -> predta_produit_0d_def (M2 state m m0).\nProof.\n\tunfold predta_produit_0d_def in |- *. intros. simpl in H1.\n\telim (bool_is_true_or_false (Neqb a a0)); intro; rewrite H3 in H1.\n\tinversion H1. induction  a1 as [| p]. induction  a0 as [| p]. rewrite (Neqb_complete a N0 H3). simpl in |- *. elim (H N0 s0 N0 N0 s0 s1). simpl in |- *. trivial.\n\tsimpl in |- *. trivial. simpl in H2. exact H2. induction  p as [p Hrecp| p Hrecp| ]. rewrite (Neqb_complete _ _ H3). simpl in |- *. elim (H (Npos p) s0 (Npos p) N0 s0 s1). simpl in |- *. trivial.\n\tsimpl in |- *. rewrite (aux_Neqb_1_0 p). trivial. simpl in H2. assumption.\n\trewrite (Neqb_complete _ _ H3). simpl in |- *. elim (H (Npos p) s0 (Npos p) N0 s0 s1). simpl in |- *. trivial. simpl in |- *. rewrite (aux_Neqb_1_0 p). trivial.\n\tsimpl in H2. trivial. rewrite (Neqb_complete _ _ H3). simpl in |- *.\n\telim (H N0 s0 N0 N0 s0 s1). simpl in |- *. trivial. simpl in |- *. trivial.\n\tsimpl in H2. trivial. induction  p as [p Hrecp| p Hrecp| ]. rewrite (Neqb_complete _ _ H3).\n\tinduction  a0 as [| p0]. simpl in |- *. elim (H0 N0 s0 N0 (Npos p) s0 s1). simpl in |- *.\n\ttrivial. reflexivity. simpl in H2. exact H2. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in |- *.\n\tsimpl in H2. elim (H0 (Npos p0) s0 (Npos p0) (Npos p) s0 s1). simpl in |- *.\n\ttrivial. simpl in |- *. rewrite (aux_Neqb_1_0 p0). trivial. exact H2. simpl in |- *.\n\telim (H0 (Npos p0) s0 (Npos p0) (Npos p) s0 s1). simpl in |- *. trivial. simpl in |- *.\n\trewrite (aux_Neqb_1_0 p0). trivial. simpl in H2. exact H2. simpl in |- *.\n\telim (H0 N0 s0 N0 (Npos p) s0 s1). simpl in |- *. reflexivity. reflexivity.\n\tsimpl in H2. exact H2. rewrite (Neqb_complete _ _ H3). induction  a0 as [| p0].\n\tsimpl in |- *. elim (H N0 s0 N0 (Npos p) s0 s1). reflexivity. reflexivity.\n\tsimpl in H2. exact H2. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in |- *. elim (H (Npos p0) s0 (Npos p0) (Npos p) s0 s1). reflexivity. simpl in |- *. rewrite (aux_Neqb_1_0 p0). reflexivity.\n\tsimpl in H2. exact H2. simpl in |- *. elim (H (Npos p0) s0 (Npos p0) (Npos p) s0 s1).\n\treflexivity. simpl in |- *. rewrite (aux_Neqb_1_0 p0). trivial. simpl in H2.\n\texact H2. simpl in |- *. elim (H N0 s0 N0 (Npos p) s0 s1). reflexivity.\n\treflexivity. simpl in H2. exact H2. rewrite (Neqb_complete _ _ H3).\n\tinduction  a0 as [| p]. simpl in |- *. elim (H0 N0 s0 N0 N0 s0 s1). reflexivity.\n\treflexivity. simpl in H2. exact H2. induction  p as [p Hrecp| p Hrecp| ]. simpl in |- *.\n\telim (H0 (Npos p) s0 (Npos p) N0 s0 s1). reflexivity. simpl in |- *.\n\trewrite (aux_Neqb_1_0 p). trivial. simpl in H2. exact H2. simpl in |- *.\n\telim (H0 (Npos p) s0 (Npos p) N0 s0 s1). reflexivity. simpl in |- *. rewrite (aux_Neqb_1_0 p). reflexivity. simpl in H2. exact H2. simpl in |- *.\n\telim (H0 N0 s0 N0 N0 s0 s1). reflexivity. reflexivity. simpl in H2.\n\texact H2. inversion H1.\nQed.\n\nLemma predta_produit_0_3 : forall m : preDTA, predta_produit_0d_def m.\nProof.\n\texact\n  (Map_ind state predta_produit_0d_def predta_produit_0_0 predta_produit_0_1\n     predta_produit_0_2).\nQed.\n\nLemma predta_produit_0 :\n forall (a : ad) (s : state) (d : preDTA) (a0 a1 : ad) (s0 s1 : state),\n MapGet state (M1 state a s) a0 = Some s0 ->\n MapGet state d a1 = Some s1 ->\n MapGet state (preDTA_produit_l a s d) (iad_conv a0 a1) =\n Some (s_produit s0 s1).\nProof.\n\tintros. exact (predta_produit_0_3 d a s a0 a1 s0 s1 H H0).\nQed.\n\nDefinition predta_produit_1_def (d : preDTA) : Prop :=\n  forall (a : ad) (s : state) (a0 a1 : ad) (s0 s1 : state),\n  MapGet state (M1 state a s) a0 = Some s0 ->\n  MapGet state d a1 = Some s1 ->\n  MapGet state (preDTA_produit_r a s d) (iad_conv a1 a0) =\n  Some (s_produit s1 s0).\n\nLemma predta_produit_1_0 : predta_produit_1_def (M0 state).\nProof.\n\tunfold predta_produit_1_def in |- *. intros. inversion H0.\nQed.\n\nLemma predta_produit_1_1 :\n forall (a : ad) (a0 : state), predta_produit_1_def (M1 state a a0).\nProof.\n\tunfold predta_produit_1_def in |- *. intros. simpl in H. simpl in H0.\n\telim (bool_is_true_or_false (Neqb a1 a2)); intro; rewrite H1 in H.\n\telim (bool_is_true_or_false (Neqb a a3)); intro; rewrite H2 in H0.\n\tinversion H. inversion H0. rewrite (Neqb_complete _ _ H1).\n\trewrite (Neqb_complete _ _ H2). simpl in |- *. rewrite (Neqb_correct (iad_conv a3 a2)). trivial. inversion H0. inversion H.\nQed.\n\nLemma predta_produit_1_2 :\n forall m : preDTA,\n predta_produit_1_def m ->\n forall m0 : preDTA,\n predta_produit_1_def m0 -> predta_produit_1_def (M2 state m m0).\nProof.\n\tunfold predta_produit_1_def in |- *. intros. simpl in H1. \n\telim (bool_is_true_or_false (Neqb a a0)); intro; rewrite H3 in H1.\n\trewrite (Neqb_complete _ _ H3). inversion H1. induction  a0 as [| p]. induction  a1 as [| p].\n\tsimpl in |- *. elim (H N0 s0 N0 N0 s0 s1). reflexivity. reflexivity.\n\tsimpl in H2. exact H2. induction  p as [p Hrecp| p Hrecp| ]. simpl in |- *. elim (H0 N0 s0 N0 (Npos p) s0 s1). reflexivity. reflexivity. simpl in H2. exact H2. simpl in |- *.\n\telim (H N0 s0 N0 (Npos p) s0 s1). reflexivity. reflexivity.\n\tsimpl in H2. exact H2. simpl in |- *. elim (H0 N0 s0 N0 N0 s0 s1).\n\treflexivity. reflexivity. simpl in H2. exact H2. induction  p as [p Hrecp| p Hrecp| ].\n\tinduction  a1 as [| p0]. simpl in |- *. elim (H (Npos p) s0 (Npos p) N0 s0 s1).\n\treflexivity. simpl in |- *. rewrite (aux_Neqb_1_0 p). reflexivity.\n\tsimpl in H2. exact H2. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in |- *. elim (H0 (Npos p) s0 (Npos p) (Npos p0) s0 s1). reflexivity. simpl in |- *. rewrite (aux_Neqb_1_0 p).\n\treflexivity. simpl in H2. exact H2. simpl in |- *. elim (H (Npos p) s0 (Npos p) (Npos p0) s0 s1). reflexivity. simpl in |- *. rewrite (aux_Neqb_1_0 p).\n\treflexivity. simpl in H2. exact H2. simpl in |- *. elim (H0 (Npos p) s0 (Npos p) N0 s0 s1). reflexivity. simpl in |- *. rewrite (aux_Neqb_1_0 p). reflexivity.\n\tsimpl in H2. exact H2. induction  a1 as [| p0]. simpl in |- *. elim (H (Npos p) s0 (Npos p) N0 s0 s1). reflexivity. simpl in |- *. rewrite (aux_Neqb_1_0 p). reflexivity.\n\tsimpl in H2. exact H2. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in |- *. elim (H0 (Npos p) s0 (Npos p) (Npos p0) s0 s1). reflexivity. simpl in |- *. rewrite (aux_Neqb_1_0 p).\n\treflexivity. simpl in H2. exact H2. simpl in |- *. elim (H (Npos p) s0 (Npos p) (Npos p0) s0 s1). reflexivity. simpl in |- *. rewrite (aux_Neqb_1_0 p).\n\treflexivity. simpl in H2. exact H2. simpl in |- *. elim (H0 (Npos p) s0 (Npos p) N0 s0 s1). reflexivity. simpl in |- *. rewrite (aux_Neqb_1_0 p). reflexivity.\n\tsimpl in H2. exact H2. induction  a1 as [| p]. simpl in |- *. elim (H N0 s0 N0 N0 s0 s1). reflexivity. reflexivity. simpl in H2. exact H2. induction  p as [p Hrecp| p Hrecp| ].\n\tsimpl in |- *. elim (H0 N0 s0 N0 (Npos p) s0 s1). reflexivity. reflexivity.\n\tsimpl in H2. exact H2. simpl in |- *. elim (H N0 s0 N0 (Npos p) s0 s1).\n\treflexivity. reflexivity. simpl in H2. exact H2. simpl in |- *.\n\telim (H0 N0 s0 N0 N0 s0 s1). reflexivity. reflexivity.\n\tsimpl in H2. exact H2. inversion H1.\nQed.\n\nLemma predta_produit_1_3 : forall m : preDTA, predta_produit_1_def m.\nProof.\n\texact\n  (Map_ind state predta_produit_1_def predta_produit_1_0 predta_produit_1_1\n     predta_produit_1_2).\nQed.\n\nLemma predta_produit_1 :\n forall (a : ad) (s : state) (d : preDTA) (a0 a1 : ad) (s0 s1 : state),\n MapGet state (M1 state a s) a0 = Some s0 ->\n MapGet state d a1 = Some s1 ->\n MapGet state (preDTA_produit_r a s d) (iad_conv a1 a0) =\n Some (s_produit s1 s0).\nProof.\n\tintros. exact (predta_produit_1_3 d a s a0 a1 s0 s1 H H0).\nQed.\n\nLemma predta_produit_2 :\n forall (d0 d1 : preDTA) (a0 a1 : ad) (s0 s1 : state),\n MapGet state d0 a0 = Some s0 ->\n MapGet state d1 a1 = Some s1 ->\n MapGet state (preDTA_produit d0 d1) (iad_conv a0 a1) =\n Some (s_produit s0 s1).\nProof.\n\tsimple induction d0. intros. inversion H. intros. induction  d1 as [| a3 a4| d1_1 Hrecd1_1 d1_0 Hrecd1_0];\n  unfold preDTA_produit in |- *. inversion H0. exact (predta_produit_0 a a0 (M1 state a3 a4) a1 a2 s0 s1 H H0). exact (predta_produit_0 a a0 (M2 state d1_1 d1_0) a1 a2 s0 s1 H H0). intros. induction  d1 as [| a a2| d1_1 Hrecd1_1 d1_0 Hrecd1_0].\n\tinversion H2. unfold preDTA_produit in |- *. exact (predta_produit_1 a a2 (M2 state m m0) a1 a0 s1 s0 H2 H1). induction  a0 as [| p]. induction  a1 as [| p]. simpl in |- *.\n\tsimpl in H1. simpl in H2. exact (H d1_1 N0 N0 s0 s1 H1 H2).\n\tinduction  p as [p Hrecp| p Hrecp| ]. simpl in |- *. simpl in H1. simpl in H2. exact (H d1_0 N0 (Npos p) s0 s1 H1 H2). simpl in |- *. simpl in H1. simpl in H2. exact (H d1_1 N0 (Npos p) s0 s1 H1 H2). simpl in |- *. exact (H d1_0 N0 N0 s0 s1 H1 H2). simpl in H1.\n\tinduction  p as [p Hrecp| p Hrecp| ]. induction  a1 as [| p0]. simpl in H2. simpl in |- *. exact (H0 d1_1 (Npos p) N0 s0 s1 H1 H2). induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in |- *. simpl in H2. exact (H0 d1_0 (Npos p) (Npos p0) s0 s1 H1 H2). simpl in |- *. exact (H0 d1_1 (Npos p) (Npos p0) s0 s1 H1 H2).\n\tsimpl in H2. simpl in |- *. exact (H0 d1_0 (Npos p) N0 s0 s1 H1 H2). induction  a1 as [| p0].\n\tsimpl in H2. simpl in |- *. exact (H d1_1 (Npos p) N0 s0 s1 H1 H2). induction  p0 as [p0 Hrecp0| p0 Hrecp0| ].\n\tsimpl in |- *. simpl in H2. simpl in H1. exact (H d1_0 (Npos p) (Npos p0) s0 s1 H1 H2).\n\tsimpl in |- *. simpl in H2. exact (H d1_1 (Npos p) (Npos p0) s0 s1 H1 H2). \n\tsimpl in H2. simpl in |- *. exact (H d1_0 (Npos p) N0 s0 s1 H1 H2). induction  a1 as [| p].\n\tsimpl in H2. simpl in |- *. exact (H0 d1_1 N0 N0 s0 s1 H1 H2). induction  p as [p Hrecp| p Hrecp| ].\n\tsimpl in H2. simpl in |- *. exact (H0 d1_0 N0 (Npos p) s0 s1 H1 H2). simpl in H2.\n\tsimpl in |- *. exact (H0 d1_1 N0 (Npos p) s0 s1 H1 H2). simpl in H2. simpl in |- *.\n\texact (H0 d1_0 N0 N0 s0 s1 H1 H2).\nQed.\n\nDefinition predta_produit_3_def (d0 : preDTA) : Prop :=\n  forall (a a0 : ad) (s s0 : state),\n  MapGet state (preDTA_produit_l a0 s0 d0) a = Some s ->\n  exists a1 : ad,\n    (exists a2 : ad,\n       (exists s1 : state,\n          (exists s2 : state,\n             a = iad_conv a1 a2 /\\\n             MapGet state (M1 state a0 s0) a1 = Some s1 /\\\n             MapGet state d0 a2 = Some s2))).\n\nLemma predta_produit_3_0 : predta_produit_3_def (M0 state).\nProof.\n\tunfold predta_produit_3_def in |- *. intros. simpl in H. inversion H.\nQed.\n\nLemma predta_produit_3_1 :\n forall (a : ad) (a0 : state), predta_produit_3_def (M1 state a a0).\nProof.\n\tunfold predta_produit_3_def in |- *. intros. simpl in H. split with a2.\n\tsplit with a. split with s0. split with a0. elim (bool_is_true_or_false (Neqb (iad_conv a2 a) a1)); intro. rewrite (Neqb_complete _ _ H0).\n\tsplit. reflexivity. split. simpl in |- *. rewrite (Neqb_correct a2). reflexivity.\n\tsimpl in |- *. rewrite (Neqb_correct a). reflexivity. rewrite H0 in H.\n\tinversion H.\nQed.\n\nLemma predta_produit_3_2 :\n forall m : preDTA,\n predta_produit_3_def m ->\n forall m0 : preDTA,\n predta_produit_3_def m0 -> predta_produit_3_def (M2 state m m0).\nProof.\n\tunfold predta_produit_3_def in |- *. intros. elim (iad_conv_surj a). intros. elim H2.\n\tintros. rewrite H3 in H1. rewrite H3. induction  a0 as [| p]. induction  x as [| p]. induction  x0 as [| p].\n\tsimpl in H1. elim (H N0 N0 s s0 H1). intros. elim H4. intros. elim H5.\n\tintros. elim H6. intros. elim H7. intros. elim H9. intros. split with N0.\n\tsplit with N0. split with x1. split with x2. split. reflexivity.\n\telim (iad_conv_inj N0 N0 x x0 H8). intros. rewrite <- H12 in H10.\n\trewrite <- H13 in H11. split. exact H10. exact H11. induction  p as [p Hrecp| p Hrecp| ]. simpl in H1.\n\telim (H0 (Npos (iad_conv_aux_0 p)) N0 s s0 H1). intros. elim H4. intros.\n\telim H5. intros. elim H6. intros. elim H7. intros. elim H9. intros.\n\tsplit with N0. split with (Npos (xI p)). split with x1. split with x2.\n\tsplit. reflexivity. elim (iad_conv_inj N0 (Npos p) x x0 H8). intros.\n\tintros. rewrite <- H12 in H10. rewrite <- H13 in H11. split. exact H10.\n\texact H11. simpl in H1. elim (H (Npos (iad_conv_aux_0 p)) N0 s s0 H1).\n\tintros. elim H4. intros. elim H5. intros. elim H6. intros. elim H7. intros.\n\telim H9. intros. split with N0. split with (Npos (xO p)). split with x1.\n\tsplit with x2. elim (iad_conv_inj N0 (Npos p) x x0 H8). intros. split.\n\treflexivity. intros. rewrite <- H12 in H10. rewrite <- H13 in H11. split.\n\texact H10. exact H11. simpl in H1. elim (H0 N0 N0 s s0 H1). intros.\n\telim H4. intros. elim H5. intros. elim H6. intros. elim H7. intros. elim H9.\n\tintros. split with N0. split with (Npos 1). split with x1. split with x2.\n\telim (iad_conv_inj N0 N0 x x0 H8). intros. split. reflexivity. intros.\n\trewrite <- H12 in H10. rewrite <- H13 in H11. split. exact H10. exact H11.\n\tinduction  p as [p Hrecp| p Hrecp| ]. induction  x0 as [| p0]. simpl in H1. inversion H1. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ].\n\tsimpl in H1. inversion H1. simpl in H1. inversion H1. simpl in H1. \n\tinversion H1. induction  x0 as [| p0]. simpl in H1. elim (H (Npos (iad_conv_aux_1 p)) N0 s s0 H1). intros. elim H4. intros. elim H5. intros. elim H6. intros.\n\telim H7. intros. elim H9. intros. split with (Npos (xO p)). split with N0.\n\tsplit with x1. split with x2. elim (iad_conv_inj (Npos p) N0 x x0 H8). intros.\n\tsplit. reflexivity. intros. rewrite <- H12 in H10. rewrite <- H13 in H11. split.\n\texact H10. exact H11. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. clear Hrecp0. clear Hrecp. simpl in H1.\n\telim (H0 (Npos (iad_conv_aux_2 p p0)) N0 s s0 H1). intros. elim H4. intros. elim H5.\n\tintros. elim H6. intros. elim H7. intros. elim H9. intros. split with (Npos (xO p)).\n\tsplit with (Npos (xI p0)). split with x1. split with x2. elim (iad_conv_inj (Npos p) (Npos p0) x x0 H8). intros. split. reflexivity. intros. rewrite <- H12 in H10.\n\trewrite <- H13 in H11. split. exact H10. exact H11. clear Hrecp0. simpl in H1.\n\telim (H (Npos (iad_conv_aux_2 p p0)) N0 s s0 H1). intros. elim H4. intros. elim H5.\n\tintros. elim H6. intros. elim H7. intros. elim H9. intros. split with (Npos (xO p)).\n\tsplit with (Npos (xO p0)). split with x1. split with x2. elim (iad_conv_inj (Npos p) (Npos p0) x x0 H8). intros. split. reflexivity. intros. rewrite <- H12 in H10.\n\trewrite <- H13 in H11. split. exact H10. exact H11. simpl in H1. elim (H0 (Npos (iad_conv_aux_1 p)) N0 s s0 H1). intros. elim H4. intros. elim H5. intros. elim H6.\n\tintros. elim H7. intros. elim H9. intros. split with (Npos (xO p)). split with (Npos 1).\n\tsplit with x1. split with x2. elim (iad_conv_inj (Npos p) N0 x x0 H8). intros. split.\n\treflexivity.  intros. rewrite <- H12 in H10. rewrite <- H13 in H11. split. exact H10.\n\texact H11. induction  x0 as [| p]. simpl in H1. inversion H1. induction  p as [p Hrecp| p Hrecp| ]. simpl in H1.\n\tinversion H1. simpl in H1. inversion H1. simpl in H1. inversion H1. induction  p as [p Hrecp| p Hrecp| ].\n\tinduction  x as [| p0]. induction  x0 as [| p0]. simpl in H1. inversion H1. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in H1.\n\tinversion H1. simpl in H1. inversion H1. simpl in H1. inversion H1. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ].\n\tinduction  x0 as [| p1]. simpl in H1. elim (H (Npos (iad_conv_aux_1 p0)) (Npos p) s s0 H1).\n\tintros. elim H4. intros. elim H5. intros. elim H6. intros. elim H7. intros. elim H9.\n\tintros. split with (Npos (xI p0)). split with N0. split with x1. split with x2.\n\telim (iad_conv_inj (Npos p0) N0 x x0 H8). intros. split. reflexivity. intros.\n\trewrite <- H12 in H10. rewrite <- H13 in H11. split. exact H10. exact H11.\n\tinduction  p1 as [p1 Hrecp1| p1 Hrecp1| ]. clear Hrecp1. clear Hrecp0. simpl in H1. elim (H0 (Npos (iad_conv_aux_2 p0 p1)) (Npos p) s s0 H1). intros. elim H4. intros. elim H5. intros. elim H6. intros.\n\telim H7. intros. elim H9. intros. split with (Npos (xI p0)). split with (Npos (xI p1)).\n\tsplit with x1. split with x2. elim (iad_conv_inj (Npos p0) (Npos p1) x x0 H8). intros.\n\tsplit. reflexivity. intros. rewrite <- H12 in H10. rewrite <- H13 in H11. split.\n\texact H10. exact H11. clear Hrecp1. clear Hrecp0. simpl in H1. elim (H (Npos (iad_conv_aux_2 p0 p1)) (Npos p) s s0 H1). intros. elim H4. intros. elim H5. intros.\n\telim H6. intros. elim H7. intros. elim H9. intros. split with (Npos (xI p0)).\n\tsplit with (Npos (xO p1)). split with x1. split with x2. elim (iad_conv_inj (Npos p0) (Npos p1) x x0 H8). intros. split. reflexivity. intros. rewrite <- H12 in H10.\n\trewrite <- H13 in H11. split. exact H10. exact H11. clear Hrecp0. simpl in H1.\n\telim (H0 (Npos (iad_conv_aux_1 p0)) (Npos p) s s0 H1). intros. elim H4. intros.\n\telim H5. intros. elim H6. intros. elim H7. intros. elim H9. intros.\n\tsplit with (Npos (xI p0)). split with (Npos 1). split with x1. split with x2.\n\telim (iad_conv_inj (Npos p0) N0 x x0 H8). intros. split. reflexivity. intros.\n\trewrite <- H12 in H10. rewrite <- H13 in H11. split. exact H10. exact H11.\n\tinduction  x0 as [| p1]. simpl in H1. inversion H1. induction  p1 as [p1 Hrecp1| p1 Hrecp1| ]. simpl in H1. inversion H1.\n\tsimpl in H1. inversion H1. simpl in H1. inversion H1. induction  x0 as [| p0]. simpl in H1.\n\telim (H N0 (Npos p) s s0 H1). intros. elim H4. intros. elim H5. intros. elim H6.\n\tintros. elim H7. intros. elim H9. intros. split with (Npos 1). split with N0.\n\tsplit with x1. split with x2. elim (iad_conv_inj N0 N0 x x0 H8). intros.\n\tsplit. reflexivity. intros. rewrite <- H12 in H10. rewrite <- H13 in H11.\n\tsplit. exact H10. exact H11. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in H1. elim (H0 (Npos (iad_conv_aux_0 p0)) (Npos p) s s0 H1). intros. elim H4. intros. elim H5. intros. elim H6. intros.\n\telim H7. intros. elim H9. intros. split with (Npos 1). split with (Npos (xI p0)).\n\tsplit with x1. split with x2. elim (iad_conv_inj N0 (Npos p0) x x0 H8). intros.\n\tsplit. reflexivity. intros. rewrite <- H12 in H10. rewrite <- H13 in H11. split.\n\texact H10. exact H11. simpl in H1. elim (H (Npos (iad_conv_aux_0 p0)) (Npos p) s s0 H1).\n\tintros. elim H4. intros. elim H5. intros. elim H6. intros. elim H7. intros. elim H9.\n\tintros. split with (Npos 1). split with (Npos (xO p0)). split with x1. split with x2.\n\telim (iad_conv_inj N0 (Npos p0) x x0 H8). intros. split. reflexivity. intros.\n\trewrite <- H12 in H10. rewrite <- H13 in H11. split. exact H10. exact H11.\n\tsimpl in H1. elim (H0 N0 (Npos p) s s0 H1). intros. elim H4. intros. elim H5.\n\tintros. elim H6. intros. elim H7. intros. elim H9. intros. split with (Npos 1).\n\tsplit with (Npos 1). split with x1. split with x2. elim (iad_conv_inj N0 N0 x x0 H8).\n\tintros. split. reflexivity. intros. rewrite <- H12 in H10. rewrite <- H13 in H11.\n\tsplit. exact H10. exact H11. induction  x as [| p0]. induction  x0 as [| p0]. simpl in H1. \n\telim (H N0 (Npos p) s s0 H1). intros. elim H4. intros. elim H5. intros. elim H6.\n\tintros. elim H7. intros. elim H9. intros. split with N0. split with N0.\n\tsplit with x1. split with x2. elim (iad_conv_inj N0 N0 x x0). intros. split.\n\treflexivity. intros. rewrite <- H12 in H10. rewrite <- H13 in H11. split.\n\texact H10. exact H11. simpl in |- *. exact H8. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in H1. elim (H0 (Npos (iad_conv_aux_0 p0)) (Npos p) s s0 H1). intros. elim H4. intros. elim H5. intros.\n\telim H6. intros. elim H7. intros. elim H9. intros. split with N0. split with (Npos (xI p0)). split with x1. split with x2. elim (iad_conv_inj N0 (Npos p0) x x0 H8).\n\tintros. split. reflexivity. intros. rewrite <- H12 in H10. rewrite <- H13 in H11.\n\tsplit. exact H10. exact H11. simpl in H1. elim (H (Npos (iad_conv_aux_0 p0)) (Npos p) s s0 H1). intros. elim H4. intros. elim H5. intros. elim H6. intros. elim H7. intros.\n\telim H9. intros. split with N0. split with (Npos (xO p0)). split with x1.\n\tsplit with x2. elim (iad_conv_inj N0 (Npos p0) x x0 H8). intros. split. reflexivity.\n\tintros. rewrite <- H12 in H10. rewrite <- H13 in H11. split. exact H10. exact H11.\n\tsimpl in H1. elim (H0 N0 (Npos p) s s0 H1). intros. elim H4. intros. elim H5.\n\tintros. elim H6. intros. elim H7. intros. elim H9. intros. split with N0.\n\tsplit with (Npos 1). split with x1. split with x2. elim (iad_conv_inj N0 N0 x x0 H8).\n\tintros. split. reflexivity. intros. rewrite <- H12 in H10. rewrite <- H13 in H11. split.\n\texact H10. exact H11. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. induction  x0 as [| p1]. simpl in H1. inversion H1.\n\tinduction  p1 as [p1 Hrecp1| p1 Hrecp1| ]. simpl in H1. inversion H1. simpl in H1. inversion H1. simpl in H1.\n\tinversion H1. induction  x0 as [| p1]. simpl in H1. elim (H (Npos (iad_conv_aux_1 p0)) (Npos p) s s0 H1). intros. elim H4. intros. elim H5. intros. elim H6. intros. elim H7. intros.\n\telim H9. intros. split with (Npos (xO p0)). split with N0. split with x1.\n\tsplit with x2. elim (iad_conv_inj (Npos p0) N0 x x0 H8). intros. split. reflexivity.\n\tintros. rewrite <- H12 in H10. rewrite <- H13 in H11. split. exact H10. exact H11.\n\tinduction  p1 as [p1 Hrecp1| p1 Hrecp1| ]. clear Hrecp1. clear Hrecp0. simpl in H1. elim (H0 (Npos (iad_conv_aux_2 p0 p1)) (Npos p) s s0 H1). intros. elim H4. intros. elim H5. intros. elim H6. intros.\n\telim H7. intros. elim H9. intros. split with (Npos (xO p0)). split with (Npos (xI p1)).\n\tsplit with x1. split with x2. elim (iad_conv_inj (Npos p0) (Npos p1) x x0 H8). intros.\n\tsplit. reflexivity. intros. rewrite <- H12 in H10. rewrite <- H13 in H11. split.\n\texact H10. exact H11. clear Hrecp1. clear Hrecp0. simpl in H1. elim (H (Npos (iad_conv_aux_2 p0 p1)) (Npos p) s s0 H1). intros. elim H4. intros. elim H5. intros. elim H6. intros.\n\telim H7. intros. elim H9. intros. split with (Npos (xO p0)). split with (Npos (xO p1)).\n\tsplit with x1. elim (iad_conv_inj (Npos p0) (Npos p1) x x0 H8). intros. intros.\n\trewrite <- H12 in H10. split with x2. split. reflexivity. rewrite <- H13 in H11.\n\tsplit. simpl in |- *. simpl in H10. exact H10. exact H11. simpl in H1. elim (H0 (Npos (iad_conv_aux_1 p0)) (Npos p) s s0 H1). intros. elim H4. intros. elim H5. intros.\n\telim H6. intros. elim H7. intros. elim H9. intros. split with (Npos (xO p0)).\n\tsplit with (Npos 1). split with x1. split with x2. elim (iad_conv_inj (Npos p0) N0 x x0 H8). intros. split. reflexivity. intros. rewrite <- H12 in H10. rewrite <- H13 in H11.\n\tsplit. exact H10. exact H11. induction  x0 as [| p0]. simpl in H1. inversion H1. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ].\n\tsimpl in H1. inversion H1. simpl in H1. inversion H1. simpl in H1. inversion H1.\n\tinduction  x as [| p]. induction  x0 as [| p]. simpl in H1. inversion H1. induction  p as [p Hrecp| p Hrecp| ]. simpl in H1.\n\tinversion H1. simpl in H1. inversion H1. simpl in H1. inversion H1. induction  p as [p Hrecp| p Hrecp| ].\n\tinduction  x0 as [| p0]. simpl in H1. elim (H (Npos (iad_conv_aux_1 p)) N0 s s0 H1).\n\tintros. elim H4. intros. elim H5. intros. elim H6. intros. elim H7. intros. elim H9.\n\tintros. split with (Npos (xI p)). split with N0. split with x1. split with x2.\n\telim (iad_conv_inj (Npos p) N0 x x0 H8). intros. split. reflexivity. intros.\n\trewrite <- H12 in H10. rewrite <- H13 in H11. split. exact H10. exact H11.\n\tinduction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in H1. elim (H0 (Npos (iad_conv_aux_2 p p0)) N0 s s0 H1).\n\tintros. elim H4. intros. elim H5. intros. elim H6. intros. elim H7. intros. elim H9.\n\tintros. split with (Npos (xI p)). split with (Npos (xI p0)). split with x1. split with x2.\n\telim (iad_conv_inj (Npos p) (Npos p0) x x0 H8). intros. split. reflexivity. intros.\n\trewrite <- H12 in H10. rewrite <- H13 in H11. split. exact H10. exact H11. simpl in H1.\n\telim (H (Npos (iad_conv_aux_2 p p0)) N0 s s0 H1). intros. elim H4. intros. elim H5.\n\tintros. elim H6. intros. elim H7. intros. elim H9. intros. split with (Npos (xI p)).\n\tsplit with (Npos (xO p0)). split with x1. split with x2. elim (iad_conv_inj (Npos p) (Npos p0) x x0 H8). intros. split. reflexivity. intros. rewrite <- H12 in H10. \n\trewrite <- H13 in H11. split. exact H10. exact H11. simpl in H1. elim (H0 (Npos (iad_conv_aux_1 p)) N0 s s0 H1). intros. elim H4. intros. elim H5. intros. elim H6.\n\tintros. elim H7. intros. elim H9. intros. split with (Npos (xI p)). split with (Npos 1).\n\tsplit with x1. split with x2. elim (iad_conv_inj (Npos p) N0 x x0 H8). intros.\n\tintros. split. reflexivity. intros. rewrite <- H12 in H10. rewrite <- H13 in H11.\n\tsplit. exact H10. exact H11. induction  x0 as [| p0]. simpl in H1. inversion H1. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ].\n\tsimpl in H1. inversion H1. simpl in H1. inversion H1. simpl in H1. inversion H1.\n\tinduction  x0 as [| p]. simpl in H1. elim (H N0 N0 s s0 H1). intros. elim H4. intros.\n\telim H5. intros. elim H6. intros. elim H7. intros. elim H9. intros. split with (Npos 1). split with N0. split with x1. split with x2. elim (iad_conv_inj N0 N0 x x0 H8). intros. split. reflexivity. intros. rewrite <- H12 in H10.\n\trewrite <- H13 in H11. split. exact H10. exact H11. induction  p as [p Hrecp| p Hrecp| ]. simpl in H1.\n\telim (H0 (Npos (iad_conv_aux_0 p)) N0 s s0 H1). intros. elim H4. intros. elim H5. \n\tintros. elim H6. intros. elim H7. intros. elim H9. intros. split with (Npos 1).\n\tsplit with (Npos (xI p)). split with x1. split with x2. elim (iad_conv_inj N0 (Npos p) x x0 H8). intros. split. reflexivity. intros. rewrite <- H12 in H10.\n\trewrite <- H13 in H11. split. exact H10. exact H11. simpl in H1. elim (H (Npos (iad_conv_aux_0 p)) N0 s s0 H1). intros. elim H4. intros. elim H5. intros.\n\telim H6. intros. elim H7. intros. elim H9. intros. split with (Npos 1). split with (Npos (xO p)). split with x1. split with x2. elim (iad_conv_inj N0 (Npos p) x x0 H8).\n\tintros. split. reflexivity. intros. rewrite <- H12 in H10. rewrite <- H13 in H11.\n\tsplit. exact H10. exact H11. simpl in H1. elim (H0 N0 N0 s s0 H1). intros.\n\telim H4. intros. elim H5. intros. elim H6. intros. elim H7. intros. elim H9.\n\tintros. split with (Npos 1). split with (Npos 1). split with x1. split with x2.\n\telim (iad_conv_inj N0 N0 x x0 H8). intros. split. reflexivity. intros. \n\trewrite <- H12 in H10. rewrite <- H13 in H11. split. exact H10. exact H11.\nQed.\n\nLemma predta_produit_3_3 : forall m : preDTA, predta_produit_3_def m.\nProof.\n\texact\n  (Map_ind state predta_produit_3_def predta_produit_3_0 predta_produit_3_1\n     predta_produit_3_2).\nQed.\n\nLemma predta_produit_3 :\n forall (d0 : preDTA) (a a0 : ad) (s s0 : state),\n MapGet state (preDTA_produit_l a0 s0 d0) a = Some s ->\n exists a1 : ad,\n   (exists a2 : ad,\n      (exists s1 : state,\n         (exists s2 : state,\n            a = iad_conv a1 a2 /\\\n            MapGet state (M1 state a0 s0) a1 = Some s1 /\\\n            MapGet state d0 a2 = Some s2))).\nProof.\n\texact\n  (Map_ind state predta_produit_3_def predta_produit_3_0 predta_produit_3_1\n     predta_produit_3_2).\nQed.\n\nDefinition predta_produit_4_def (d0 : preDTA) : Prop :=\n  forall (a a0 : ad) (s s0 : state),\n  MapGet state (preDTA_produit_r a0 s0 d0) a = Some s ->\n  exists a1 : ad,\n    (exists a2 : ad,\n       (exists s1 : state,\n          (exists s2 : state,\n             a = iad_conv a1 a2 /\\\n             MapGet state (M1 state a0 s0) a2 = Some s1 /\\\n             MapGet state d0 a1 = Some s2))).\n\nLemma predta_produit_4_0 : predta_produit_4_def (M0 state).\nProof.\n\tunfold predta_produit_4_def in |- *. intros. inversion H.\nQed.\n\nLemma predta_produit_4_1 :\n forall (a : ad) (a0 : state), predta_produit_4_def (M1 state a a0).\nProof.\n\tunfold predta_produit_4_def in |- *. intros. simpl in H. elim (bool_is_true_or_false (Neqb (iad_conv a a2) a1)). intro. rewrite H0 in H. inversion H. split with a.\n\tsplit with a2. split with s0. split with a0. split. symmetry  in |- *. \n\texact (Neqb_complete _ _ H0). split. simpl in |- *. rewrite (Neqb_correct a2).\n\treflexivity. simpl in |- *. rewrite (Neqb_correct a). reflexivity. intro.\n\trewrite H0 in H. inversion H.\nQed.\n\nLemma predta_produit_4_2 :\n forall m : preDTA,\n predta_produit_4_def m ->\n forall m0 : preDTA,\n predta_produit_4_def m0 -> predta_produit_4_def (M2 state m m0).\nProof.\n\tunfold predta_produit_4_def in |- *. intros. elim (iad_conv_surj a). intros.\n\telim H2. intros. rewrite H3 in H1. induction  a0 as [| p]. induction  x as [| p]. induction  x0 as [| p]. simpl in H1. elim (H N0 N0 s s0 H1). intros. elim H4. intros.\n\telim H5. intros. elim H6. intros. elim H7. intros. elim H9. intros.\n\tsplit with x. split with x0. split with x1. split with x2.\n\telim (iad_conv_inj N0 N0 _ _ H8). intros. split. rewrite H3.\n\tsimpl in |- *. assumption. split. assumption. rewrite <- H12. simpl in |- *.\n\trewrite <- H12 in H11. assumption. induction  p as [p Hrecp| p Hrecp| ]. simpl in H1.\n\tinversion H1. simpl in H1. elim (H (Npos (iad_conv_aux_0 p)) N0 s s0 H1). intros. elim H4. intros. elim H5. intros. elim H6. intros.\n\telim H7. intros. elim H9. intros. split with N0. split with (Npos (xO p)). split with x1. split with x2. simpl in H3. split.\n\tsimpl in |- *. exact H3. elim (iad_conv_inj N0 (Npos p) _ _ H8). intros.\n\trewrite <- H12 in H11. rewrite <- H13 in H10. split; simpl in |- *; assumption.\n\tsimpl in H1. inversion H1. induction  p as [p Hrecp| p Hrecp| ]. induction  x0 as [| p0]. simpl in H1.\n\telim (H0 (Npos (iad_conv_aux_1 p)) N0 s s0 H1). intros. elim H4.\n\tintros. elim H5. intros. elim H6. intros. elim H7. intros. elim H9.\n\tintros. split with (Npos (xI p)). split with N0. split with x1.\n\tsplit with x2. split. assumption. elim (iad_conv_inj (Npos p) N0 _ _ H8). intros. rewrite <- H12 in H11. rewrite <- H13 in H10.\n\tsplit; simpl in |- *; assumption. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in H1. inversion H1.\n\tsimpl in H1. elim (H0 (Npos (iad_conv_aux_2 p p0)) N0 s s0 H1).\n\tintros. elim H4. intros. elim H5. intros. elim H6. intros. elim H7.\n\tintros. elim H9. intros. split with (Npos (xI p)). split with (Npos (xO p0)). split with x1. split with x2. split. assumption.\n\telim (iad_conv_inj (Npos p) (Npos p0) _ _ H8). intros. rewrite <- H12 in H11. rewrite <- H13 in H10. split; simpl in |- *; assumption.\n\tsimpl in H1. inversion H1. induction  x0 as [| p0]. simpl in H1. elim (H (Npos (iad_conv_aux_1 p)) N0 s s0 H1). intros. elim H4. intros. elim H5. intros. elim H6. intros. elim H7. intros. elim H9. intros.\n\tsplit with (Npos (xO p)). split with N0. split with x1. split with x2.\n\telim (iad_conv_inj (Npos p) N0 _ _ H8). intros. split. assumption.\n\trewrite <- H13 in H10. rewrite <- H12 in H11. split; simpl in |- *; assumption.\n\tinduction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in H1. inversion H1. simpl in H1. elim (H (Npos (iad_conv_aux_2 p p0)) N0 s s0 H1). intros. elim H4. intros. elim H5.\n\tintros. elim H6. intros. elim H7. intros. elim H9. intros. split with (Npos (xO p)). split with (Npos (xO p0)). split with x1. split with x2.\n\telim (iad_conv_inj (Npos p) (Npos p0) _ _ H8). intros. split. \n\tassumption. rewrite <- H12 in H11. rewrite <- H13 in H10. split; simpl in |- *; assumption. inversion H1. induction  x0 as [| p]. simpl in H1. elim (H0 N0 N0 s s0 H1). intros. elim H4. intros. elim H5. intros. elim H6. intros.\n\telim H7. intros. elim H9. intros. split with (Npos 1). split with N0.\n\tsplit with x1. split with x2. elim (iad_conv_inj N0 N0 _ _ H8).\n\tintros. split. assumption. rewrite <- H13 in H10. rewrite <- H12 in H11.\n\tsplit; simpl in |- *; assumption. induction  p as [p Hrecp| p Hrecp| ]. simpl in H1. inversion H1.\n\tsimpl in H1. elim (H0 (Npos (iad_conv_aux_0 p)) N0 s s0 H1). intros.\n\telim H4. intros. elim H5. intros. elim H6. intros. elim H7. intros.\n\telim H9. intros. split with (Npos 1). split with (Npos (xO p)).\n\tsplit with x1. split with x2. elim (iad_conv_inj N0 (Npos p) _ _ H8).\n\tintros. split. assumption. rewrite <- H13 in H10. rewrite <- H12 in H11.\n\tsplit; simpl in |- *; assumption. simpl in H1. inversion H1. induction  p as [p Hrecp| p Hrecp| ].\n\tclear Hrecp. induction  x as [| p0]. induction  x0 as [| p0]. simpl in H1. inversion H1.\n\tinduction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in H1. elim (H (Npos (iad_conv_aux_0 p0)) (Npos p) s s0 H1). intros. elim H4. intros. elim H5. intros. elim H6.\n\tintros. elim H7. intros. elim H9. intros. split with N0. split with (Npos (xI p0)). split with x1. split with x2. elim (iad_conv_inj N0 (Npos p0) _ _ H8). intros. split. assumption. rewrite <- H13 in H10. rewrite <- H12 in H11. split; simpl in |- *; assumption. simpl in H1.\n\tinversion H1. simpl in H1. elim (H N0 (Npos p) s s0 H1). intros.\n\telim H4. intros. elim H5. intros. elim H6. intros. elim H7. intros.\n\telim H9. intros. split with N0. split with (Npos 1). \n\tsplit with x1. split with x2. elim (iad_conv_inj N0 N0 _ _ H8).\n\tintros. split. assumption. rewrite <- H13 in H10. rewrite <- H12 in H11. split; simpl in |- *; assumption. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. induction  x0 as [| p1].\n\tsimpl in H1. inversion H1. clear Hrecp0. induction  p1 as [p1 Hrecp1| p1 Hrecp1| ]. simpl in H1.\n\telim (H0 (Npos (iad_conv_aux_2 p0 p1)) (Npos p) s s0 H1). intros.\n\telim H4. intros. elim H5. intros. elim H6. intros. elim H7. intros.\n\telim H9. intros. split with (Npos (xI p0)). split with (Npos (xI p1)). split with x1. split with x2. elim (iad_conv_inj (Npos p0) (Npos p1) _ _ H8). intros. split. assumption. rewrite <- H13 in H10.\n\trewrite <- H12 in H11. split; simpl in |- *; assumption. simpl in H1.\n\tinversion H1. simpl in H1. elim (H0 (Npos (iad_conv_aux_1 p0)) (Npos p) s s0 H1). intros. elim H4. intros. elim H5. intros. elim H6.\n\tintros. elim H7. intros. elim H9. intros. split with (Npos (xI p0)).\n\tsplit with (Npos 1). split with x1. split with x2. elim (iad_conv_inj (Npos p0) N0 _ _ H8). intros. split. assumption.\n\trewrite <- H13 in H10. rewrite <- H12 in H11. split; simpl in |- *; assumption. induction  x0 as [| p1]. simpl in H1. inversion H1. clear Hrecp0.\n\tinduction  p1 as [p1 Hrecp1| p1 Hrecp1| ]. simpl in H1. elim (H (Npos (iad_conv_aux_2 p0 p1)) (Npos p) s s0 H1). intros. elim H4. intros. elim H5. intros.\n\telim H6. intros. elim H7. intros. elim H9. intros. split with (Npos (xO p0)). split with (Npos (xI p1)). split with x1. split with x2. elim (iad_conv_inj (Npos p0) (Npos p1) _ _ H8). intros.\n\tsplit. assumption. rewrite <- H13 in H10. rewrite <- H12 in H11.\n\tsplit; simpl in |- *; assumption. simpl in H1. inversion H1. simpl in H1.\n\telim (H (Npos (iad_conv_aux_1 p0)) (Npos p) s s0 H1). intros. \n\telim H4. intros. elim H5. intros. elim H6. intros. elim H7. intros.\n\telim H9. intros. split with (Npos (xO p0)). split with (Npos 1).\n\tsplit with x1. split with x2. elim (iad_conv_inj (Npos p0) N0 _ _ H8).  intros. split. assumption. rewrite <- H13 in H10. rewrite <- H12 in H11. split; simpl in |- *; assumption. induction  x0 as [| p0]. simpl in H1.\n\tinversion H1. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in H1. elim (H0 (Npos (iad_conv_aux_0 p0)) (Npos p) s s0 H1). intros. elim H4. intros.\n\telim H5. intros. elim H6. intros. elim H7. intros. elim H9. intros.\n\tsplit with (Npos 1). split with (Npos (xI p0)). split with x1.\n\tsplit with x2. elim (iad_conv_inj N0 (Npos p0) _ _ H8). intros.\n\tsplit. assumption. rewrite <- H13 in H10. rewrite <- H12 in H11.\n\tsplit; simpl in |- *; assumption. simpl in H1. inversion H1. simpl in H1.\n\telim (H0 N0 (Npos p) s s0 H1). intros. elim H4. intros. elim H5.\n\tintros. elim H6. intros. elim H7. intros. elim H9. intros.\n\tsplit with (Npos 1). split with (Npos 1). split with x1. split with x2. elim (iad_conv_inj N0 N0 _ _ H8). intros. split.\n\tassumption. rewrite <- H13 in H10. rewrite <- H12 in H11.\n\tsplit; simpl in |- *; assumption. clear Hrecp. induction  x as [| p0]. induction  x0 as [| p0].\n\tsimpl in H1. elim (H N0 (Npos p) s s0 H1). intros. elim H4.\n\tintros. elim H5. intros. elim H6. intros. elim H7. intros.\n\telim H9. intros. split with N0. split with N0. split with x1.\n\tsplit with x2. elim (iad_conv_inj N0 N0 _ _ H8). intros.\n\tsplit. assumption. rewrite <- H13 in H10. rewrite <- H12 in H11.\n\tsplit; simpl in |- *; assumption. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in H1. inversion H1.\n\tsimpl in H1. elim (H (Npos (iad_conv_aux_0 p0)) (Npos p) s s0 H1).\n\tintros. elim H4. intros. elim H5. intros. elim H6. intros. elim H7.\n\tintros. elim H9. intros. split with N0. split with (Npos (xO p0)).\n\tsplit with x1. split with x2. elim (iad_conv_inj N0 (Npos p0) _ _ H8). intros. split. assumption. rewrite <- H13 in H10.\n\trewrite <- H12 in H11. split; simpl in |- *; assumption. simpl in H1.\n\tinversion H1. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. clear Hrecp0. induction  x0 as [| p1].\n\tsimpl in H1. elim (H0 (Npos (iad_conv_aux_1 p0)) (Npos p) s s0 H1).\n\tintros. elim H4. intros. elim H5. intros. elim H6. intros. elim H7.\n\tintros. elim H9. intros. split with (Npos (xI p0)). split with N0.\n\tsplit with x1. split with x2. elim (iad_conv_inj (Npos p0) N0 _ _ H8). intros. split. assumption. rewrite <- H13 in H10. rewrite <- H12 in H11. split; simpl in |- *; assumption. induction  p1 as [p1 Hrecp1| p1 Hrecp1| ]. simpl in H1.\n\tinversion H1. simpl in H1. elim (H0 (Npos (iad_conv_aux_2 p0 p1)) (Npos p) s s0 H1). intros. elim H4. intros. elim H5. intros. elim H6.\n\tintros. elim H7. intros. elim H9. intros. split with (Npos (xI p0)).\n\tsplit with (Npos (xO p1)). split with x1. split with x2. elim (iad_conv_inj (Npos p0) (Npos p1) _ _ H8). intros. split. assumption.\n\trewrite <- H13 in H10. rewrite <- H12 in H11. split; simpl in |- *; assumption.\n\tsimpl in H1. inversion H1. clear Hrecp0. induction  x0 as [| p1]. simpl in H1.\n\telim (H (Npos (iad_conv_aux_1 p0)) (Npos p) s s0 H1). intros. elim H4.\n\tintros. elim H5. intros. elim H6. intros. elim H7. intros. elim H9.\n\tintros. split with (Npos (xO p0)). split with N0. split with x1.\n\tsplit with x2. elim (iad_conv_inj (Npos p0) N0 _ _ H8). intros.\n\tsplit. assumption. rewrite <- H13 in H10. rewrite <- H12 in H11.\n\tsplit; simpl in |- *; assumption. induction  p1 as [p1 Hrecp1| p1 Hrecp1| ]. simpl in H1. inversion H1.\n\tsimpl in H1. elim (H (Npos (iad_conv_aux_2 p0 p1)) (Npos p) s s0 H1).\n\tintros. elim H4. intros. elim H5. intros. elim H6. intros. elim H7.\n\tintros. elim H9. intros. split with (Npos (xO p0)). split with (Npos (xO p1)). split with x1. split with x2. elim (iad_conv_inj (Npos p0) (Npos p1) _ _ H8). intros. split. assumption. rewrite <- H13 in H10.\n\trewrite <- H12 in H11. split; simpl in |- *; assumption. simpl in H1.\n\tinversion H1. induction  x0 as [| p0]. simpl in H1. elim (H0 N0 (Npos p) s s0 H1). intros. elim H4. intros. elim H5. intros. elim H6. intros.\n\telim H7. intros. elim H9. intros. split with (Npos 1). split with N0. split with x1. split with x2. elim (iad_conv_inj N0 N0 _ _ H8). intros. split. assumption. rewrite <- H13 in H10. rewrite <- H12 in H11. split; simpl in |- *; assumption. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in H1. inversion H1. simpl in H1. elim (H0 (Npos (iad_conv_aux_0 p0)) (Npos p) s s0 H1).\n\tintros. elim H4. intros. elim H5. intros. elim H6. intros. elim H7.\n\tintros. elim H9. intros. split with (Npos 1). split with (Npos (xO p0)). split with x1. split with x2. elim (iad_conv_inj N0 (Npos p0) _ _ H8). intros. split. assumption. rewrite <- H13 in H10. rewrite <- H12 in H11. split; simpl in |- *; assumption. simpl in H1. inversion H1.\n\tinduction  x as [| p]. induction  x0 as [| p]. simpl in H1. inversion H1. induction  p as [p Hrecp| p Hrecp| ].\n\tsimpl in H1. elim (H (Npos (iad_conv_aux_0 p)) N0 s s0 H1). \n\tintros. elim H4. intros. elim H5. intros. elim H6. intros. elim H7.\n\tintros. elim H9. intros. split with N0. split with (Npos (xI p)).\n\tsplit with x1. split with x2. elim (iad_conv_inj N0 (Npos p) _ _ H8).  intros. split. assumption. rewrite <- H13 in H10. rewrite <- H12 in H11. split; simpl in |- *; assumption. simpl in H1. inversion H1.\n\tsimpl in H1. elim (H N0 N0 s s0 H1). intros. elim H4. intros.\n\telim H5. intros. elim H6. intros. elim H7. intros. elim H9. intros.\n\tsplit with N0. split with (Npos 1). split with x1. split with x2.\n\telim (iad_conv_inj N0 N0 _ _ H8). intros. split. assumption.\n\trewrite <- H13 in H10. rewrite <- H12 in H11. split; simpl in |- *; assumption. induction  p as [p Hrecp| p Hrecp| ]. clear Hrecp. induction  x0 as [| p0]. simpl in H1.\n\tinversion H1. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in H1. elim (H0 (Npos (iad_conv_aux_2 p p0)) N0 s s0 H1). intros. elim H4. intros.\n\telim H5. intros. elim H6. intros. elim H7. intros. elim H9. intros.\n\tsplit with (Npos (xI p)). split with (Npos (xI p0)). split with x1.\n\tsplit with x2. elim (iad_conv_inj (Npos p) (Npos p0) _ _ H8). intros.\n\tsplit. assumption. rewrite <- H13 in H10. rewrite <- H12 in H11.\n\tsplit; simpl in |- *; assumption. simpl in H1. inversion H1. simpl in H1.\n\telim (H0 (Npos (iad_conv_aux_1 p)) N0 s s0 H1). intros. elim H4.\n\tintros. elim H5. intros. elim H6. intros. elim H7. intros. elim H9.\n\tintros. split with (Npos (xI p)). split with (Npos 1). \n\tsplit with x1. split with x2. elim (iad_conv_inj (Npos p) N0 _ _ H8).\n\tintros. split. assumption. rewrite <- H13 in H10. rewrite <- H12 in H11.\n\tsplit; simpl in |- *; assumption. induction  x0 as [| p0]. simpl in H1. inversion H1.\n\tclear Hrecp. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in H1. elim (H (Npos (iad_conv_aux_2 p p0)) N0 s s0 H1). intros. elim H4. intros. elim H5. intros. elim H6.\n\tintros. elim H7. intros. elim H9. intros. split with (Npos (xO p)).\n\tsplit with (Npos (xI p0)). split with x1. split with x2. elim (iad_conv_inj (Npos p) (Npos p0) _ _ H8). intros. split. assumption.\n\trewrite <- H13 in H10. rewrite <- H12 in H11. split; simpl in |- *; assumption.\n\tsimpl in H1. inversion H1. simpl in H1. elim (H (Npos (iad_conv_aux_1 p)) N0 s s0 H1). intros. elim H4. intros. elim H5. intros. elim H6.\n\tintros. elim H7. intros. elim H9. intros. split with (Npos (xO p)).\n\tsplit with (Npos 1). split with x1. split with x2. elim (iad_conv_inj (Npos p) N0 _ _ H8). intros. split. assumption. rewrite <- H13 in H10.\n\trewrite <- H12 in H11. split; simpl in |- *; assumption. induction  x0 as [| p]. \n\tsimpl in H1. inversion H1. induction  p as [p Hrecp| p Hrecp| ]. simpl in H1. elim (H0 (Npos (iad_conv_aux_0 p)) N0 s s0 H1). intros. elim H4. intros. elim H5.\n\tintros. elim H6. intros. elim H7. intros. elim H9. intros. split with (Npos 1). split with (Npos (xI p)). split with x1. split with x2.\n\telim (iad_conv_inj N0 (Npos p) _ _ H8). intros. split. assumption.\n\trewrite <- H13 in H10. rewrite <- H12 in H11. split; simpl in |- *; assumption.\n\tsimpl in H1. inversion H1. simpl in H1. elim (H0 N0 N0 s s0 H1).\n\tintros. elim H4. intros. elim H5. intros. elim H6. intros. elim H7.\n\tintros. elim H9. intros. split with (Npos 1). split with (Npos 1).\n\tsplit with x1. split with x2. elim (iad_conv_inj N0 N0 _ _ H8).\n\tintros. split. assumption. rewrite <- H13 in H10. rewrite <- H12 in H11. split; simpl in |- *; assumption.\nQed.\n\nLemma predta_produit_4_3 : forall m : preDTA, predta_produit_4_def m.\nProof.\n\texact\n  (Map_ind state predta_produit_4_def predta_produit_4_0 predta_produit_4_1\n     predta_produit_4_2).\nQed.\n\nLemma predta_produit_4 :\n forall (d0 : preDTA) (a a0 : ad) (s s0 : state),\n MapGet state (preDTA_produit_r a0 s0 d0) a = Some s ->\n exists a1 : ad,\n   (exists a2 : ad,\n      (exists s1 : state,\n         (exists s2 : state,\n            a = iad_conv a1 a2 /\\\n            MapGet state (M1 state a0 s0) a2 = Some s1 /\\\n            MapGet state d0 a1 = Some s2))).\nProof.\n\texact\n  (Map_ind state predta_produit_4_def predta_produit_4_0 predta_produit_4_1\n     predta_produit_4_2).\nQed.\n\nLemma predta_produit_5 :\n forall (d0 d1 : preDTA) (a : ad) (s : state),\n MapGet state (preDTA_produit d0 d1) a = Some s ->\n exists a0 : ad,\n   (exists a1 : ad,\n      (exists s0 : state,\n         (exists s1 : state,\n            a = iad_conv a0 a1 /\\\n            MapGet state d0 a0 = Some s0 /\\\n            MapGet state d1 a1 = Some s1))).\nProof.\n\tsimple induction d0. intros. induction  d1 as [| a0 a1| d1_1 Hrecd1_1 d1_0 Hrecd1_0]; inversion H. intros.\n\tinduction  d1 as [| a2 a3| d1_1 Hrecd1_1 d1_0 Hrecd1_0]. simpl in H. inversion H. cut\n  (preDTA_produit (M1 state a a0) (M1 state a2 a3) =\n   preDTA_produit_l a a0 (M1 state a2 a3)). intro. rewrite H0 in H. exact (predta_produit_3 (M1 state a2 a3) a1 a s a0 H). reflexivity. cut\n  (preDTA_produit (M1 state a a0) (M2 state d1_1 d1_0) =\n   preDTA_produit_l a a0 (M2 state d1_1 d1_0)).\n\tintro. rewrite H0 in H. exact (predta_produit_3 (M2 state d1_1 d1_0) a1 a s a0 H). reflexivity. simple induction d1. intros. inversion H1. intros.\n\tcut\n  (preDTA_produit (M2 state m m0) (M1 state a a0) =\n   preDTA_produit_r a a0 (M2 state m m0)). intro. rewrite H2 in H1. elim (predta_produit_4 (M2 state m m0) a1 a s a0 H1). intros. elim H3. intros. elim H4. intros.\n\telim H5. intros. elim H6. intros. elim H8. intros. split with x.\n\tsplit with x0. split with x2. split with x1. split. assumption. split; assumption. reflexivity. intros. clear H1. clear H2. induction  a as [| p]. simpl in H3.\n\telim (H m1 N0 s H3). intros. elim H1. intros. elim H2. intros. elim H4.\n\tintros. elim H5. intros. elim H7. intros. split with N0. split with N0.\n\tsimpl in |- *. split with x1. split with x2. elim (iad_conv_inj N0 N0 _ _ H6); intros. rewrite <- H10 in H8. rewrite <- H11 in H9. split. reflexivity.\n\tsplit. exact H8. exact H9. induction  p as [p Hrecp| p Hrecp| ]. clear Hrecp. induction  p as [p Hrecp| p Hrecp| ].\n\tclear Hrecp. simpl in H3. elim (H0 m2 (Npos p) s H3). intros. elim H1.\n\tintros. elim H2. intros. elim H4. intros. elim H5. intros. elim H7. intros.\n\tinduction  x as [| p0]. induction  x0 as [| p0]. inversion H6. split with (Npos 1). split with (Npos (xI p0)). split with x1. split with x2. split. simpl in |- *. simpl in H6.\n\tinversion H6. reflexivity. simpl in |- *. split; assumption. induction  x0 as [| p1].\n\tsplit with (Npos (xI p0)). split with (Npos 1). split with x1. split with x2.\n\tsimpl in |- *. split. simpl in H6. inversion H6. reflexivity. split; assumption.\n\tsplit with (Npos (xI p0)). split with (Npos (xI p1)). split with x1.\n\tsplit with x2. simpl in |- *. simpl in H6. inversion H6. split. reflexivity.\n\tsplit; assumption.  clear Hrecp. simpl in H3. elim (H0 m1 (Npos p) s H3).\n\tintros. elim H1. intros. elim H2. intros. elim H4. intros. elim H5. intros.\n\telim H7. intros. induction  x as [| p0]. induction  x0 as [| p0]. inversion H6. split with (Npos 1). split with (Npos (xO p0)). split with x1. split with x2. simpl in H6.\n\tinversion H6. simpl in |- *. split. reflexivity. split; assumption. induction  x0 as [| p1].\n\tsplit with (Npos (xI p0)). split with N0. split with x1. split with x2.\n\tsimpl in H6. inversion H6. simpl in |- *. split. reflexivity. split; assumption.\n\tsplit with (Npos (xI p0)). split with (Npos (xO p1)). split with x1.\n\tsplit with x2. simpl in H6. inversion H6. split. reflexivity. split; assumption. simpl in H3. elim (H0 m2 N0 s H3). intros. elim H1. intros.\n\telim H2. intros. elim H4. intros. elim H5. intros. elim H7. intros. induction  x as [| p]. induction  x0 as [| p]. split with (Npos 1). split with (Npos 1). split with x1.\n\tsplit with x2. simpl in |- *. split. reflexivity. split; assumption. simpl in H6.\n\tinversion H6. induction  x0 as [| p0]; simpl in H6; inversion H6. clear Hrecp.\n\tinduction  p as [p Hrecp| p Hrecp| ]. clear Hrecp. simpl in H3. elim (H m2 (Npos p) s H3). intros.\n\telim H1. intros. elim H2. intros. elim H4. intros. elim H5. intros. elim H7.\n\tintros. induction  x as [| p0]. induction  x0 as [| p0]. simpl in H6. inversion H6. split with N0.\n\tsplit with (Npos (xI p0)). split with x1. split with x2. simpl in H6.\n\tinversion H6. simpl in |- *. split. reflexivity. split; assumption. induction  x0 as [| p1].\n\tsplit with (Npos (xO p0)). split with (Npos 1). split with x1. split with x2.\n\tsimpl in H6. inversion H6. simpl in |- *. split. reflexivity. split; assumption.\n\tsplit with (Npos (xO p0)). split with (Npos (xI p1)). split with x1.\n\tsplit with x2. simpl in H6. inversion H6. simpl in |- *. split. reflexivity.\n\tsplit; assumption. clear Hrecp. simpl in H3. elim (H m1 (Npos p) s H3).\n\tintros. elim H1. intros. elim H2. intros. elim H4. intros. elim H5. intros.\n\telim H7. intros. induction  x as [| p0]. induction  x0 as [| p0]. simpl in H6. inversion H6.\n\tsplit with N0. split with (Npos (xO p0)). split with x1. split with x2.\n\tsimpl in H6. inversion H6. simpl in |- *. split. reflexivity. split; assumption.\n\tinduction  x0 as [| p1]. simpl in H6. split with (Npos (xO p0)). split with N0.\n\tsplit with x1. split with x2. simpl in H6. inversion H6. split. reflexivity.\n\tsplit; assumption. split with (Npos (xO p0)). split with (Npos (xO p1)).\n\tsplit with x1. split with x2. simpl in H6. inversion H6. simpl in |- *. split.\n\treflexivity. split; assumption. simpl in H3. elim (H m2 N0 s H3). intros.\n\telim H1. intros. elim H2. intros. elim H4. intros. elim H5. intros. elim H7.\n\tintros. induction  x as [| p]. induction  x0 as [| p]. split with N0. split with (Npos 1).\n\tsplit with x1. split with x2. simpl in |- *. split. reflexivity. split; assumption.\n\tsimpl in H6. inversion H6. induction  x0 as [| p0]. simpl in H6. inversion H6.\n\tsimpl in H6. inversion H6. simpl in H3. elim (H0 m1 N0 s H3). intros.\n\telim H1. intros. elim H2. intros. elim H4. intros. elim H5. intros. elim H7.\n\tintros. split with (Npos 1). split with N0. split with x1. split with x2.\n\tsimpl in |- *. split. reflexivity. elim (iad_conv_inj N0 N0 _ _ H6). intros.\n\trewrite <- H10 in H8. rewrite <- H11 in H9. split; assumption.\nQed.\n\nLemma pl_produit_rec_0 :\n forall tl : term_list,\n (forall u : term,\n  term_list_occur u tl ->\n  forall (d0 d1 : preDTA) (a0 a1 : ad),\n  predta_compatible d0 d1 ->\n  reconnaissance d0 a0 u ->\n  reconnaissance d1 a1 u ->\n  reconnaissance (preDTA_produit d0 d1) (iad_conv a0 a1) u) ->\n forall (d0 d1 : preDTA) (plp0 plp1 : pl_path),\n predta_compatible d0 d1 ->\n pl_path_recon d0 tl plp0 ->\n pl_path_recon d1 tl plp1 ->\n pl_path_recon (preDTA_produit d0 d1) tl (pl_path_product plp0 plp1).\nProof.\n\tsimple induction tl. intros. inversion H1. inversion H2. simpl in |- *. exact (pl_path_rec_nil (preDTA_produit d0 d1)). intros. inversion H2. inversion H3. simpl in |- *. apply\n  (pl_path_rec_cons (preDTA_produit d0 d1) (iad_conv a a0) t\n     (pl_path_product plp plp2) t0).\n\texact (H0 t (tlo_head t t t0 (to_eq t)) d0 d1 a a0 H1 H7 H13). \n\texact\n  (H (fun (u : term) (p : term_list_occur u t0) => H0 u (tlo_tail u t t0 p))\n     d0 d1 plp plp2 H1 H9 H15).\nQed.\n\nLemma pl_produit_rec_1 :\n forall (d0 d1 : preDTA) (tl : term_list) (pl0 pl1 : prec_list),\n liste_reconnait d0 pl0 tl ->\n liste_reconnait d1 pl1 tl ->\n pl_tl_length pl0 (lst_length tl) ->\n pl_tl_length pl1 (lst_length tl) ->\n predta_compatible d0 d1 ->\n (forall u : term,\n  term_list_occur u tl ->\n  forall (d0 d1 : preDTA) (a0 a1 : ad),\n  predta_compatible d0 d1 ->\n  reconnaissance d0 a0 u ->\n  reconnaissance d1 a1 u ->\n  reconnaissance (preDTA_produit d0 d1) (iad_conv a0 a1) u) ->\n liste_reconnait (preDTA_produit d0 d1) (pl_produit pl0 pl1) tl.\nProof.\n\tintros. elim (pl_path_rec_equiv_0 d0 pl0 tl H). elim (pl_path_rec_equiv_0 d1 pl1 tl H0).\n\tintros. cut (pl_path_incl (pl_path_product x0 x) (pl_produit pl0 pl1)). intro. elim H5.\n\tintros. elim H6. intros. apply\n  (pl_path_rec_equiv_1 (pl_path_product x0 x) (pl_produit pl0 pl1) H7\n     (preDTA_produit d0 d1) tl (lst_length tl)). exact (pl_produit_rec_0 tl H4 d0 d1 x0 x H3 H11 H9). apply (pl_tl_length_prod pl0 pl1 (lst_length tl)). exact H1.\n\texact H2. elim H5. intros. elim H6. intros. exact (pl_produit_path_incl_2 pl0 pl1 (lst_length tl) x0 x H9 H1 H7 H2).\nQed.\n\nLemma pl_produit_rec_2 :\n forall tl : term_list,\n (forall u : term,\n  term_list_occur u tl ->\n  forall (d0 d1 : preDTA) (a0 a1 : ad),\n  predta_compatible d0 d1 ->\n  reconnaissance (preDTA_produit d0 d1) (iad_conv a0 a1) u ->\n  reconnaissance d0 a0 u /\\ reconnaissance d1 a1 u) ->\n forall (d0 d1 : preDTA) (plp : pl_path),\n predta_compatible d0 d1 ->\n pl_path_recon (preDTA_produit d0 d1) tl plp ->\n exists plp0 : pl_path,\n   (exists plp1 : pl_path,\n      plp = pl_path_product plp0 plp1 /\\\n      pl_path_recon d0 tl plp0 /\\ pl_path_recon d1 tl plp1).\nProof.\n\tsimple induction tl. intros. inversion H1. split with pl_path_nil. split with pl_path_nil.\n\tsimpl in |- *. split. reflexivity. split. exact (pl_path_rec_nil d0). exact (pl_path_rec_nil d1). intros. inversion H2. elim\n  (H\n     (fun (u : term) (pr : term_list_occur u t0) => H0 u (tlo_tail u t t0 pr))\n     d0 d1 plp0 H1 H8). intros. elim H9. intros. elim (iad_conv_surj a).\n\tintros. elim H11. intros. rewrite H12 in H6. elim (H0 t (tlo_head t t t0 (to_eq t)) d0 d1 x1 x2 H1 H6). intros. split with (pl_path_cons x1 x). split with (pl_path_cons x2 x0). simpl in |- *. split. rewrite H12. elim H10. intros. rewrite H15. reflexivity.\n\telim H10. intros. elim H16. intros. split. exact (pl_path_rec_cons d0 x1 t x t0 H13 H17). exact (pl_path_rec_cons d1 x2 t x0 t0 H14 H18).\nQed.\n\nLemma pl_produit_rec_3 :\n forall (d0 d1 : preDTA) (tl : term_list) (pl0 pl1 : prec_list) (n : nat),\n liste_reconnait (preDTA_produit d0 d1) (pl_produit pl0 pl1) tl ->\n predta_compatible d0 d1 ->\n pl_tl_length pl0 n ->\n pl_tl_length pl1 n ->\n (forall u : term,\n  term_list_occur u tl ->\n  forall (d0 d1 : preDTA) (a0 a1 : ad),\n  predta_compatible d0 d1 ->\n  reconnaissance (preDTA_produit d0 d1) (iad_conv a0 a1) u ->\n  reconnaissance d0 a0 u /\\ reconnaissance d1 a1 u) ->\n liste_reconnait d0 pl0 tl /\\ liste_reconnait d1 pl1 tl.\nProof.\n\tintros. elim (pl_path_rec_equiv_0 (preDTA_produit d0 d1) (pl_produit pl0 pl1) tl H). intros. elim H4. intros. elim (pl_produit_rec_2 tl H3 d0 d1 x H0 H6).\n\tintros. elim H7. intros. elim H8. intros. elim H10. intros. elim (pl_produit_path_incl_4 pl0 pl1 n x H5 H1 H2). intros. elim H13. intros. elim H14. intros. elim H16. intros.\n\telim (pl_produit_path_incl_inj x0 x1 x2 x3 n). intros. rewrite <- H19 in H17.\n\trewrite <- H20 in H18. split. exact (pl_path_rec_equiv_1 x0 pl0 H17 d0 tl n H11 H1).\n\texact (pl_path_rec_equiv_1 x1 pl1 H18 d1 tl n H12 H2). transitivity (lst_length tl).\n\texact (pl_path_rec_length x0 tl d0 H11). symmetry  in |- *. exact\n  (liste_rec_length (pl_produit pl0 pl1) tl (preDTA_produit d0 d1) n H\n     (pl_tl_length_prod pl0 pl1 n H1 H2)).\n\ttransitivity (lst_length tl). exact (pl_path_rec_length x1 tl d1 H12). symmetry  in |- *.\n\texact\n  (liste_rec_length (pl_produit pl0 pl1) tl (preDTA_produit d0 d1) n H\n     (pl_tl_length_prod pl0 pl1 n H1 H2)). exact (pl_path_incl_length x2 pl0 n H17 H1).\n\texact (pl_path_incl_length x3 pl1 n H18 H2). transitivity x. symmetry  in |- *. exact H9.\n\texact H15.\nQed.\n\nDefinition predta_inter_def_0 (t : term) : Prop :=\n  forall (d0 d1 : preDTA) (a0 a1 : ad),\n  predta_compatible d0 d1 ->\n  reconnaissance d0 a0 t ->\n  reconnaissance d1 a1 t ->\n  reconnaissance (preDTA_produit d0 d1) (iad_conv a0 a1) t.\n\nDefinition predta_inter_def_1 (t : term) : Prop :=\n  forall (d0 d1 : preDTA) (a0 a1 : ad),\n  predta_compatible d0 d1 ->\n  reconnaissance (preDTA_produit d0 d1) (iad_conv a0 a1) t ->\n  reconnaissance d0 a0 t /\\ reconnaissance d1 a1 t.\n\nLemma predta_inter_0 :\n forall (a : ad) (tl : term_list),\n (forall u : term, term_list_occur u tl -> predta_inter_def_0 u) ->\n predta_inter_def_0 (app a tl).\nProof.\n\tunfold predta_inter_def_0 in |- *. intros. inversion H1. inversion H2. inversion H4.\n\tinversion H9. apply\n  (rec_dta (preDTA_produit d0 d1) (iad_conv a0 a1) \n     (app a tl) (s_produit ladj ladj0)). exact (predta_produit_2 d0 d1 a0 a1 ladj ladj0 H3 H8).\n\tapply\n  (rec_st (preDTA_produit d0 d1) (s_produit ladj ladj0) a tl\n     (pl_produit l l0)).\n\texact (s_produit_0 ladj ladj0 a l l0 H17 H23). apply (pl_produit_rec_1 d0 d1 tl l l0 H18 H24). cut (pl_compatible l l0). intro. elim H25. intros. elim H26. intros.\n\trewrite <- (liste_rec_length l tl d0 x H18 H27). exact H27. cut (st_compatible ladj ladj0).\n\tintro. exact (H25 a l l0 H17 H23). apply (H0 ladj ladj0). split with a0. exact H3.\n\tsplit with a1. exact H8. cut (pl_compatible l l0). intro. elim H25. intros. elim H26.\n\tintros. rewrite <- (liste_rec_length l0 tl d1 x H24 H28). exact H28. cut (st_compatible ladj ladj0). intro. exact (H25 a l l0 H17 H23). apply (H0 ladj ladj0). split with a0.\n\texact H3. split with a1. exact H8. exact H0. exact H.\nQed.\n\nLemma predta_inter_1 :\n forall (a : ad) (tl : term_list),\n (forall u : term, term_list_occur u tl -> predta_inter_def_1 u) ->\n predta_inter_def_1 (app a tl).\nProof.\n\tunfold predta_inter_def_1 in |- *. intros. inversion H1. inversion H3.\n\telim (predta_produit_5 d0 d1 (iad_conv a0 a1) ladj H2). intros. elim H13.\n\tintros. elim H14. intros. elim H15. intros. elim H16. intros. elim H18. intros.\n\telim (iad_conv_inj _ _ _ _ H17). intros. rewrite <- H21 in H19. rewrite <- H22 in H20. rewrite (predta_produit_2 d0 d1 a0 a1 x1 x2 H19 H20) in H2. inversion H2.\n\trewrite <- H24 in H11. elim (s_produit_1 x1 x2 a l H11). intros. elim H23.\n\tintros. elim H25. intros. rewrite (s_produit_0 x1 x2 a x3 x4 H26 H27) in H11.\n\tinversion H11. cut (pl_compatible x3 x4). intros. elim H28. intros. elim H30.\n\tintros. rewrite <- H29 in H12. elim (pl_produit_rec_3 d0 d1 tl x3 x4 x5 H12 H0 H31 H32 H). intros. split. apply (rec_dta d0 a0 (app a tl) x1 H19). exact (rec_st d0 x1 a tl x3 H26 H33). apply (rec_dta d1 a1 (app a tl) x2 H20).\n\texact (rec_st d1 x2 a tl x4 H27 H34). cut (st_compatible x1 x2). intro. exact (H28 a x3 x4 H26 H27). apply (H0 x1 x2). split with a0. exact H19. split with a1.\n\texact H20.\nQed.\n\nLemma predta_inter_direct :\n forall (d0 d1 : preDTA) (a0 a1 : ad) (t : term),\n predta_compatible d0 d1 ->\n reconnaissance d0 a0 t ->\n reconnaissance d1 a1 t ->\n reconnaissance (preDTA_produit d0 d1) (iad_conv a0 a1) t.\nProof.\n\tintro. intro. intro. intro. intro. exact (indprinciple_term predta_inter_def_0 predta_inter_0 t d0 d1 a0 a1).\t\nQed.\n\nLemma predta_inter_reciproque :\n forall (d0 d1 : preDTA) (a0 a1 : ad) (t : term),\n predta_compatible d0 d1 ->\n reconnaissance (preDTA_produit d0 d1) (iad_conv a0 a1) t ->\n reconnaissance d0 a0 t /\\ reconnaissance d1 a1 t.\nProof.\n\tintro. intro. intro. intro. intro. exact (indprinciple_term predta_inter_def_1 predta_inter_1 t d0 d1 a0 a1).\nQed.\n\nDefinition inter (d0 d1 : DTA) : DTA :=\n  match d0, d1 with\n  | dta p0 a0, dta p1 a1 => dta (preDTA_produit p0 p1) (iad_conv a0 a1)\n  end.\n\nLemma inter_semantics_0 :\n forall (d0 d1 : DTA) (t : term),\n dta_compatible d0 d1 ->\n (reconnait d0 t /\\ reconnait d1 t <-> reconnait (inter d0 d1) t).\nProof.\n\tsimple induction d0. simple induction d1. intros. simpl in H. simpl in |- *. split. intros.\n\telim H0. intros. exact (predta_inter_direct p p0 a a0 t H H1 H2). intros.\n\texact (predta_inter_reciproque p p0 a a0 t H H0).\nQed.\n\nLemma inter_semantics :\n forall (d0 d1 : DTA) (sigma : signature) (t : term),\n dta_correct_wrt_sign d0 sigma ->\n dta_correct_wrt_sign d1 sigma ->\n (reconnait d0 t /\\ reconnait d1 t <-> reconnait (inter d0 d1) t).\nProof.\n\texact\n  (fun (d0 d1 : DTA) (sigma : signature) (t : term)\n     (pr0 : dta_correct_wrt_sign d0 sigma)\n     (pr1 : dta_correct_wrt_sign d1 sigma) =>\n   inter_semantics_0 d0 d1 t\n     (dtas_correct_wrt_sign_compatibles sigma d0 d1 pr0 pr1)).\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/inter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.28611047733270767}}
{"text": "(* Disable notation conflict warnings *)\nSet Warnings \"-notation-overridden\".\n\nFrom Coq Require Import ssreflect ssrfun ssrbool.\nRequire Import Psatz.\nRequire Import Coq.Lists.List.\nRequire Import Coq.NArith.BinNat.\nImport ListNotations.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Coq.Classes.Morphisms.\nRequire Import SetoidList.\n\nRequire Import GHC.Base.\n\nRequire Import Proofs.Prelude.\n\nRequire Import CoreFVs.\nRequire Import Id.\nRequire Import Core.\nRequire UniqFM.\n\nRequire Import Proofs.Axioms.\nRequire Import Proofs.ContainerAxioms.\nRequire Import Proofs.GhcTactics.\nRequire Import Proofs.Unique.\nRequire Import Proofs.Var.\nRequire Import Proofs.VarSetFSet.\nRequire Import Proofs.Base.\n\nOpen Scope Z_scope.\n\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nSet Bullet Behavior \"Strict Subproofs\".\n\n\n\n(* Stephanie's hack. *)\nLemma fold_is_true : forall b, b = true <-> b.\nProof. intros. unfold is_true. reflexivity. Qed.\n\nLemma false_is_not_true :\n  forall b, b = false <-> b <> true.\nProof.\n  destruct b; intuition.\nQed.\n\n(* Why is this not part of ssr? *)\nLemma eqE : forall (a b:bool), a = b <-> (a <-> b).\nProof.  \n  move=> a b.\n  elim Ea: a;\n  elim Eb: b;\n  try tauto.\n  intuition.\n  symmetry.\n  rewrite fold_is_true.\n  apply H0. auto.\n  intuition.\nQed.\n\nLemma andE a b : a && b <-> a /\\ b.\nProof. \n  elim: a; elim: b; try tauto.\n  split; move=> /andP; try done. \n  split; move=> /andP; try done. \nQed.\n\nLemma orE : forall a b, (a || b) <-> a \\/ b.\nProof. intros a b. unfold is_true. rewrite orb_true_iff. tauto. Qed.\n\nLemma notE : forall a, ~~a <-> ~ a.\nProof. move=>a. unfold is_true. rewrite negb_true_iff. \nsplit. move=>h. rewrite h. auto.\napply not_true_is_false.\nQed.\n\n\n\n(** ** NOTE: VarSets and equality *)\n\n(* VarSets have several different notions of equality. \n   In all three definitions, equal varsets must have the same domain. \n   Now suppose:\n       lookupVarSet m1 x = Some v1 and\n       lookupVarSet m2 x = Some v2\n   The sets are equal when:\n    - v1 = v2                (i.e. coq equality) \n    - almostEqual v1 v2      \n    - v1 == v2               (i.e. same uniques ONLY)\n\n   The last (coarsest) equality is the one used in the FSet signature, \n   and denoted by the [=] notation. \n\n   The almostEqual equality is denoted by {=}.\n\n   Because of this distinction, we have to do some lemmas twice: once \n   for [=] equality, and once for {=} equality.\n  \n*)\n\n\n(** ** VarSet operations respect GHC.Base.==  *)\n\nLemma elemVarSet_eq : forall v1 v2 vs,\n  (v1 == v2) -> \n  elemVarSet v1 vs = elemVarSet v2 vs.\nProof.\n  intros v1 v2 vs h.\n  unfold elemVarSet, UniqSet.elementOfUniqSet.\n  destruct vs.\n  unfold UniqFM.elemUFM.\n  destruct getUniqSet'.\n  move: h.\n  rewrite eq_unique.\n  move=> h.\n  f_equal.\n  auto.\nQed.\n\nLemma lookupVarSet_eq :\n  forall v1 v2 vs,\n    (v1 == v2) ->\n    lookupVarSet vs v1 = lookupVarSet vs v2.\nProof. \n  intros v1 v2 vs.\n  unfold lookupVarSet.\n  unfold UniqSet.lookupUniqSet.\n  destruct vs.\n  unfold UniqFM.lookupUFM.\n  destruct getUniqSet'.\n  intro h.\n  rewrite -> eq_unique in h.\n  rewrite h.\n  reflexivity.\nQed.\n\nLemma extendVarSet_eq : \n  forall x y vs, x == y -> extendVarSet vs x [=] extendVarSet vs y.\nProof.\n  move => x y vs Eq.\n  set_b_iff.\n  move: (add_m) => h.\n  unfold Proper,respectful in h.\n  apply h.\n  assumption.\n  reflexivity.\nQed.\n\n\nLemma delVarSet_eq : \n  forall x y vs, x == y -> delVarSet vs x = delVarSet vs y.\nProof.\n  move => x y vs Eq.\n  unfold delVarSet.\n  move: vs => [i].\n  move: i => [m].\n  rewrite -> eq_unique in Eq.\n  unfold UniqSet.delOneFromUniqSet.\n  unfold UniqFM.delFromUFM.\n  rewrite Eq.\n  reflexivity.\nQed.\n\n\n\n\n\n\n(** ** List based operations in terms of folds *)\n\nLemma extendVarSetList_foldl' : forall x xs, \n    extendVarSetList x xs = Foldable.foldl' (fun x y => add y x) x xs.\nProof.\n  intros.\n  unfold extendVarSetList, UniqSet.addListToUniqSet;\n  replace UniqSet.addOneToUniqSet with \n      (fun x y => add y x).\n  auto.\n  auto.\nQed.\n\nLemma delVarSetList_foldl : forall vl vs,\n    delVarSetList vs vl = Foldable.foldl delVarSet vs vl.\nProof. \n  induction vl.\n  - intro vs. \n    destruct vs. destruct getUniqSet'.\n    unfold_Foldable_foldl.\n    simpl.\n    auto.\n  - intro vs. \n    unfold delVarSetList in *.\n    unfold UniqSet.delListFromUniqSet in *.\n    destruct vs.\n    unfold UniqFM.delListFromUFM in *.\n    revert IHvl.\n    unfold_Foldable_foldl.\n    simpl.\n    intro IHvl.\n    rewrite (IHvl (UniqSet.Mk_UniqSet (UniqFM.delFromUFM getUniqSet' a))).\n    auto.\nQed.\n\n\nLemma mkVarSet_extendVarSetList : forall xs,\n    mkVarSet xs = extendVarSetList emptyVarSet xs.\nProof.\n  reflexivity.\nQed.\n\n\nHint Rewrite mkVarSet_extendVarSetList : hs_simpl.\n\n\n(** ** [lookupVarSet] and [elemVarSet] correspondence *)\n\nLemma lookupVarSet_In:\n  forall vs v, (exists v', lookupVarSet vs v = Some v') <-> In v vs.\nProof.\n  unfold lookupVarSet, UniqSet.lookupUniqSet,\n    UniqFM.lookupUFM, Unique.getWordKey, Unique.getKey.\n  intros.\n  destruct vs.\n  destruct getUniqSet'.\n  destruct (Unique.getUnique v) as [n] eqn:Hv.\n  unfold In, elemVarSet, UniqSet.elementOfUniqSet,\n  UniqFM.elemUFM, Unique.getKey, Unique.getWordKey,\n  Unique.getKey.\n  rewrite Hv.\n  rewrite <- member_lookup.\n  reflexivity.\nQed.\n\nLemma lookupVarSet_elemVarSet : \n  forall v1 v2 vs, lookupVarSet vs v1 = Some v2 -> elemVarSet v1 vs.\nProof.\n  intros.\n  unfold lookupVarSet, elemVarSet in *.\n  unfold UniqSet.lookupUniqSet, UniqSet.elementOfUniqSet in *.\n  destruct vs.\n  unfold UniqFM.lookupUFM, UniqFM.elemUFM in *.\n  destruct getUniqSet'. \n  set (key := Unique.getWordKey (Unique.getUnique v1)) in *.\n  rewrite member_lookup.\n  exists v2. auto.\nQed.\n\nLemma lookupVarSet_None_elemVarSet: \n  forall v1 vs, lookupVarSet vs v1 = None <-> elemVarSet v1 vs = false.\nProof.\n  intros.\n  unfold lookupVarSet, elemVarSet in *.\n  unfold UniqSet.lookupUniqSet, UniqSet.elementOfUniqSet in *.\n  destruct vs.\n  unfold UniqFM.lookupUFM, UniqFM.elemUFM in *.\n  destruct getUniqSet'.\n  set (key := Unique.getWordKey (Unique.getUnique v1)) in *.\n  rewrite non_member_lookup.\n  intuition.\nQed.\n\nLemma elemVarSet_lookupVarSet :\n  forall v1 vs, elemVarSet v1 vs -> exists v2, lookupVarSet vs v1 = Some v2.\nProof.\n  intros.\n  unfold lookupVarSet, elemVarSet in *.\n  unfold UniqSet.lookupUniqSet, UniqSet.elementOfUniqSet in *.\n  destruct vs.\n  unfold UniqFM.lookupUFM, UniqFM.elemUFM in *.\n  destruct getUniqSet'.\n  set (key := Unique.getWordKey (Unique.getUnique v1)) in *.\n  rewrite <- member_lookup.\n  auto.\nQed.\n\n(** ** [lookupVarSet] is Proper  *)\n\nInstance lookupVarSet_m : \n  Proper (Equal ==> (fun x y => x == y) ==> (fun x y => x == y)) lookupVarSet.\nProof.\n  unfold Equal.\n  intros x y H v1 v2 EV.\n  erewrite lookupVarSet_eq; eauto.\n  pose (h1 := H v1).\n  pose (h2 := H v2).\n  repeat rewrite -> mem_iff in h1.\n  repeat rewrite -> mem_iff in h2.\n  destruct (lookupVarSet x v2) eqn:LX;\n  destruct (lookupVarSet y v2) eqn:LY;\n  hs_simpl.\n  - apply ValidVarSet_Axiom in LX.\n    apply ValidVarSet_Axiom in LY.\n    eapply Eq_trans.\n    rewrite Eq_sym.\n    eapply LX.\n    eapply LY.\n  - apply lookupVarSet_elemVarSet in LX.\n    rewrite -> lookupVarSet_None_elemVarSet in LY.\n    set_b_iff.\n    intuition.\n  - apply lookupVarSet_elemVarSet in LY.\n    rewrite -> lookupVarSet_None_elemVarSet in LX.\n    set_b_iff.\n    intuition.\n  - auto.\nQed.\n\n\n(** ** [lookupVarSet . extendVarSet ] simplification *)\n\nLemma lookupVarSet_extendVarSet_self:\n  forall v vs,\n  lookupVarSet (extendVarSet vs v) v = Some v.\nProof.\n  intros.\n  unfold lookupVarSet, extendVarSet in *.\n  unfold UniqSet.lookupUniqSet, UniqSet.addOneToUniqSet in *.\n  destruct vs.\n  unfold UniqFM.lookupUFM, UniqFM.addToUFM in *.\n  destruct getUniqSet'.\n  set (key := Unique.getWordKey (Unique.getUnique v)) in *.\n  apply lookup_insert.\nQed.\n\nHint Rewrite lookupVarSet_extendVarSet_self : hs_simpl.\n\nLemma lookupVarSet_extendVarSet_eq :\n      forall v1 v2 vs,\n      v1 == v2  ->\n      lookupVarSet (extendVarSet vs v1) v2 = Some v1.\nProof.\n  intros v1 v2 vs H.\n  rewrite Eq_sym in H.\n  rewrite (lookupVarSet_eq _ H).\n  unfold lookupVarSet, extendVarSet.\n  unfold UniqSet.lookupUniqSet, UniqSet.addOneToUniqSet.\n  destruct vs.\n  unfold UniqFM.lookupUFM, UniqFM.addToUFM.\n  destruct getUniqSet'.\n  set (k1 := Unique.getWordKey (Unique.getUnique v1)).\n  rewrite lookup_insert.\n  reflexivity.\nQed.\n\nLemma lookupVarSet_extendVarSet_neq :\n      forall v1 v2 vs,\n      not (v1 == v2) ->\n      lookupVarSet (extendVarSet vs v1) v2 = lookupVarSet vs v2.\nProof.\n  intros v1 v2 vs H.\n  assert (Unique.getWordKey (Unique.getUnique v1) <> \n          Unique.getWordKey (Unique.getUnique v2)).\n  { intro h.\n    eapply H.\n    rewrite eq_unique.\n    auto.\n  }\n  unfold lookupVarSet, extendVarSet.\n  unfold UniqSet.lookupUniqSet, UniqSet.addOneToUniqSet.\n  destruct vs.\n  unfold UniqFM.lookupUFM, UniqFM.addToUFM.\n  destruct getUniqSet'.\n  eapply lookup_insert_neq.\n  auto.\nQed.\n\n\n(* --------------------------------- *)\n\n(* Tactics that don't really work. *)\n                                   \nLocal Ltac unfold_VarSet_to_IntMap :=\n  repeat match goal with\n         | [vs : VarSet |- _ ] =>\n           let u := fresh \"u\" in\n           destruct vs as [u]; destruct u; simpl\n         | [ |- UniqSet.Mk_UniqSet _ = UniqSet.Mk_UniqSet _ ] =>\n           f_equal\n         | [ |- UniqFM.UFM _ = UniqFM.UFM _ ] =>\n           f_equal\n         end.\n\n(*\n(* Q: is there a way to do the automatic destructs safely? Sometimes \n   loses too much information. *)\n\nLtac unfold_VarSet :=\n  unfold subVarSet,elemVarSet, isEmptyVarSet, \n         minusVarSet, extendVarSet, extendVarSetList in *;\n  unfold UniqSet.elementOfUniqSet, \n         UniqSet.isEmptyUniqSet, \n         UniqSet.addOneToUniqSet,\n         UniqSet.minusUniqSet,\n         UniqSet.addListToUniqSet in *;\n  try repeat match goal with\n  | vs: VarSet, H : context[match ?vs with _ => _ end]  |- _ => destruct vs\n  end;\n  try repeat match goal with\n  | vs: VarSet |- context[match ?vs with _ => _ end ] => destruct vs\n  end;\n\n  unfold UniqFM.addToUFM, \n         UniqFM.minusUFM, UniqFM.isNullUFM, \n         UniqFM.elemUFM in *;\n  try repeat match goal with\n  | u: UniqFM.UniqFM ?a, H : context[match ?u with _ => _ end]  |- _ => destruct u\n  end;\n  try repeat match goal with\n  | u: UniqFM.UniqFM ?a |- context[match ?u with _ => _ end] => destruct u\n  end. \n\nLtac safe_unfold_VarSet :=\n  unfold subVarSet,elemVarSet, isEmptyVarSet, \n         minusVarSet, extendVarSet, extendVarSetList in *;\n  unfold UniqSet.elementOfUniqSet, \n         UniqSet.isEmptyUniqSet, \n         UniqSet.addOneToUniqSet,\n         UniqSet.minusUniqSet,\n         UniqSet.addListToUniqSet in *;\n  unfold UniqFM.addToUFM, \n         UniqFM.minusUFM, UniqFM.isNullUFM, \n         UniqFM.elemUFM in *. *)\n\n(**************************************)\n\n(** ** [extendVarSetList] simplifications *)\n\nLemma extendVarSetList_nil:\n  forall s,\n  extendVarSetList s [] = s.\nProof.\n  intro s.\n  reflexivity.\nQed.\n\nLemma extendVarSetList_cons:\n  forall s v vs,\n  extendVarSetList s (v :: vs) = extendVarSetList (extendVarSet s v) vs.\nProof.\n  intros.\n  rewrite extendVarSetList_foldl'.\n  autorewrite with hs_simpl.\n  reflexivity.\nQed.\n\nLemma extendVarSetList_singleton:\n  forall vs v, extendVarSetList vs [v] = extendVarSet vs v.\nProof. intros. reflexivity. Qed.\n\n\nLemma extendVarSetList_append:\n  forall s vs1 vs2,\n  extendVarSetList s (vs1 ++ vs2) = extendVarSetList (extendVarSetList s vs1) vs2.\nProof.\n  intros.\n  rewrite extendVarSetList_foldl'.\n  autorewrite with hs_simpl.\n  reflexivity.\nQed.\n\nHint Rewrite extendVarSetList_nil \n             extendVarSetList_cons\n             extendVarSetList_singleton\n             extendVarSetList_append : hs_simpl.\n\n\n\n(** ** [delVarSetList] simplification  *)\n\nLemma delVarSetList_nil:\n  forall e, delVarSetList e [] = e.\nProof.\n  intros.\n  rewrite delVarSetList_foldl.\n  reflexivity.\nQed.\n\nLemma delVarSetList_single:\n  forall e a, delVarSetList e [a] = delVarSet e a.\nProof.\n  intros.\n  rewrite delVarSetList_foldl.\n  autorewrite with hs_simpl.\n  reflexivity.\nQed.\n\nLemma delVarSetList_cons:\n  forall e a vs, delVarSetList e (a :: vs) = delVarSetList (delVarSet e a) vs.\nProof.\n  intros.\n  repeat rewrite delVarSetList_foldl.\n  autorewrite with hs_simpl.\n  reflexivity.\nQed.\n\nLemma delVarSetList_app:\n  forall e vs vs', delVarSetList e (vs ++ vs') = delVarSetList (delVarSetList e vs) vs'.\nProof.\n  intros.\n  repeat rewrite delVarSetList_foldl.\n  autorewrite with hs_simpl.\n  reflexivity.\nQed.\n\nHint Rewrite delVarSetList_nil \n             delVarSetList_cons\n             delVarSetList_single\n             delVarSetList_app : hs_simpl.\n\n\n(** ** [elemVarSet] simplification *)\n\nLemma elemVarSet_emptyVarSet : forall v, (elemVarSet v emptyVarSet) = false.\n  intro v.\n  set_b_iff.\n  fsetdec.\nQed.\n\nLemma elemVarSet_unionVarSet:\n  forall v vs1 vs2,\n    elemVarSet v (unionVarSet vs1 vs2) = elemVarSet v vs1 || elemVarSet v vs2.\nProof.\n  move => v [[i]] [[i0]] /=.\n  rewrite member_union.\n  auto.\nQed.\n\nHint Rewrite elemVarSet_emptyVarSet elemVarSet_unionVarSet : hs_simpl.\n\n\n(** ** [extendVarSet]  *)\n\nLemma extendVarSet_elemVarSet_true : forall set v, \n    elemVarSet v set -> extendVarSet set v [=] set.\nProof. \n  intros.\n  apply add_equal.\n  auto.\nQed.\n\n\nLemma elemVarSet_extendVarSet:\n  forall v vs v',\n  elemVarSet v (extendVarSet vs v') = (v' == v) || elemVarSet v vs.\nProof.\n  intros.\n  rewrite var_eq_realUnique.\n  replace (realUnique v' == realUnique v)%N with \n      (F.eqb v' v). \n\n  eapply F.add_b.\n  unfold F.eqb.\n  cbn.\n  destruct F.eq_dec.\n  - unfold Var_as_DT.eq in e.\n    rewrite <- realUnique_eq in e; auto.\n  - unfold Var_as_DT.eq in n.\n    rewrite <- realUnique_eq in n; apply not_true_is_false in n; auto.\nQed.\n\nHint Rewrite elemVarSet_extendVarSet : hs_simpl.\n\nLemma elemVarSet_extendVarSetList:\n  forall v vs vs',\n  elemVarSet v (extendVarSetList vs vs') = Foldable.elem v vs' || elemVarSet v vs.\nProof.\n  intros.\n  generalize vs.\n  induction vs'.\n  + intros vs0. hs_simpl.\n    simpl.\n    auto.\n  + intros vs0. hs_simpl.\n    rewrite IHvs'.\n    hs_simpl.\n    rewrite Eq_sym.\n    ssrbool.bool_congr.\n    reflexivity.\nQed.\n\nHint Rewrite elemVarSet_extendVarSetList : hs_simpl.\n\nLemma extendVarSet_commute : forall x y vs, \n    extendVarSet (extendVarSet vs y) x  [=] extendVarSet (extendVarSet vs x) y.\nProof.\n  intros.\n  set_b_iff.\n  fsetdec.\nQed.\n\n\n\n(** ** [extendVarSetList] and [delVarSetList] are Proper **)\n\n(* These lemmas show that extendVarSetList respects [=] *)\n\nLemma extendVarSetList_iff : forall l x vs,\n  In x (extendVarSetList vs l) <->\n  In x vs \\/ Foldable.elem x l.\nProof.\n  induction l.\n  - intros x vs.\n    hs_simpl.\n    intuition.\n    inversion H0.\n  - intros x vs.\n    hs_simpl.\n    rewrite IHl.\n    set_b_iff.\n    rewrite add_iff.\n    unfold Var_as_DT.eqb.\n    rewrite Eq_sym.\n    rewrite orE.\n    intuition.\nQed.\n\nLemma delVarSetList_iff : forall l x vs,\n  In x (delVarSetList vs l) <->\n  In x vs /\\ ~ (Foldable.elem x l).\nProof.\n  induction l.\n  - intros x vs. \n    hs_simpl.\n    intuition.\n  - intros x vs.\n    hs_simpl.\n    rewrite IHl.\n    rewrite delVarSet_remove. rewrite remove_iff.\n    unfold Var_as_DT.eqb.\n    rewrite Eq_sym.\n    rewrite orE.\n    intuition.\nQed.\n\nInstance extendVarSetList_m : \n  Proper (Equal ==> (eqlistA (fun x y => x == y)) ==> Equal) extendVarSetList.\nProof.\n  unfold Equal.\n  intros x y H s s' H0 a.\n  do 2 rewrite extendVarSetList_iff.\n  rewrite H.\n  intuition; right.\n  erewrite <- eqlist_Foldable_elem; eauto.\n  eapply EqLaws_Var.\n  erewrite eqlist_Foldable_elem; eauto.\n  eapply EqLaws_Var.\nQed.\n\nInstance delVarSetList_m : \n  Proper (Equal ==> (eqlistA (fun x y => x == y)) ==> Equal) delVarSetList.\nProof.\n  unfold Equal.\n  intros x y H s s' H0 a.\n  do 2 rewrite delVarSetList_iff.\n  rewrite H.\n  intuition.\n  apply H3.\n  erewrite eqlist_Foldable_elem; eauto using EqLaws_Var.\n  apply H3.\n  erewrite <- eqlist_Foldable_elem; eauto using EqLaws_Var.\nQed.\n\n\n(* We can commute the order of addition to varsets. \n   This is only true for [=] *)\nLemma extendVarSetList_extendVarSet_iff: forall l x vs,\n  extendVarSetList (extendVarSet vs x) l [=]\n  extendVarSet (extendVarSetList vs l) x.\nProof.\n  induction l.\n  - intros.\n    hs_simpl.\n    reflexivity.\n  - intros.\n    hs_simpl.\n    rewrite extendVarSet_commute.\n    rewrite IHl.\n    reflexivity.\nQed.\n\n\nLemma elemVarSet_extend_add : forall v s vs a,\n  elemVarSet v (extendVarSetList s vs) ->\n  elemVarSet v (extendVarSetList (add a s) vs).\nProof. \n  intros v s vs a.\n  rewrite InE.\n  rewrite InE.\n  rewrite extendVarSetList_iff.\n  rewrite extendVarSetList_iff.\n  intuition.\n  left.\n  fsetdec.\nQed.\n\nLemma elemVarSet_extendVarSetList_r:\n  forall v s vs,\n  elemVarSet v (mkVarSet vs)  ->\n  elemVarSet v (extendVarSetList s vs) .\nProof.\n  intros v s vs.\n  rewrite mkVarSet_extendVarSetList.\n  rewrite InE.\n  rewrite InE.\n  rewrite extendVarSetList_iff.\n  rewrite extendVarSetList_iff.\n  intuition.\nQed.\n\n\nLemma elemVarSet_mkVarSet_cons:\n  forall v v' vs,\n  elemVarSet v (mkVarSet (v' :: vs)) = false\n  <-> (v' == v) = false /\\ elemVarSet v (mkVarSet vs) = false.\nProof.\n  intros v v' vs.\n  rewrite mkVarSet_extendVarSetList.\n  rewrite extendVarSetList_cons.\n  rewrite mkVarSet_extendVarSetList.\n  rewrite <- not_mem_iff.\n  rewrite <- not_mem_iff.\n  rewrite extendVarSetList_iff.\n  rewrite extendVarSetList_iff.\n  set_b_iff.\n  rewrite add_iff.\n  unfold Var_as_DT.eqb.\n  intuition.\n  apply not_true_is_false.\n  unfold not. auto.\n  destruct H.\n  rewrite H1 in H0.\n  done.\nQed.\n\n\n(* ** Properties about [lookupVarSet (extendVarSetList vs vars) v]\n\n   Note, we can specify what happens when v is an Foldable.elem of vars with\n   varying degrees of precision. When we lookup v, we won't get [Some v]\n   exactly, but we will get something == to v, and that was the most recently\n   added var in vars.\n   \n*)\n\n\nLemma lookupVarSet_extendVarSetList_false:\n  forall (vars:list Var) v vs,\n    ~~ (Foldable.elem v vars ) -> \n    lookupVarSet (extendVarSetList vs vars) v = lookupVarSet vs v.\nProof.\n  elim=> [|x xs IH] //.   (* // is try done. *)\n  - move => v vs.\n    hs_simpl.\n    rewrite negb_or.     (* de morgan law to push ~~ in *)\n    move => /andP [h1 h2]. (* split && into two hypotheses *)\n    rewrite IH //.\n    rewrite lookupVarSet_extendVarSet_neq //.\n    rewrite Eq_sym. by apply /negP.\nQed.\n\n\nLemma lookupVarSet_extendVarSetList_l\n  v vs vars :\n  ~~ elemVarSet v (mkVarSet vars) ->\n  lookupVarSet (extendVarSetList vs vars) v = lookupVarSet vs v.\nProof.\n  hs_simpl.\n  elim: vars vs => [|a vars IH] vs //.\n  hs_simpl.\n\n  rewrite negb_orb => /andP [? ?].\n\n  rewrite lookupVarSet_extendVarSetList_false //.\n  rewrite lookupVarSet_extendVarSet_neq //.\n\n  apply /negP.\n  rewrite Eq_sym //. \nQed.\n\n\nLemma lookupVarSet_extendVarSetList_self_in:\n  forall (vars:list Var) v vs,\n    List.In v vars -> \n    NoDup (map varUnique vars) -> \n    lookupVarSet (extendVarSetList vs vars) v = Some v.\nProof.\n  induction vars.\n  - intros v vs H.\n    inversion H.\n  - intros v vs H ND.\n    hs_simpl.\n    simpl in ND.\n    inversion ND. subst.\n    inversion H; subst.\n    + rewrite lookupVarSet_extendVarSetList_false.\n      by hs_simpl.\n      apply /negP.\n      by rewrite -In_varUnique_elem.\n    + eauto. \nQed.      \n\n\nLemma lookupVarSet_extendVarSetList_self:\n  forall (vars:list Var) v vs,\n    (Foldable.elem v vars) -> \n    lookupVarSet (extendVarSetList vs vars) v == Some v.\nProof.\n  induction vars.\n  - intros v vs H.\n    rewrite elem_nil in H.\n    done.\n  - intros v vs H.\n    rewrite elem_cons in H.\n    hs_simpl.\n    rewrite -> orE in H.\n    elim: H.\n    move => H.\n    case Hv: (Foldable.elem v vars).\n    + specialize (IHvars v (extendVarSet vs a)).\n      unfold is_true in *.\n      apply IHvars. \n      done.\n    + rewrite (lookupVarSet_eq _ H).\n      rewrite lookupVarSet_extendVarSetList_false.\n      rewrite lookupVarSet_extendVarSet_self.\n      hs_simpl.\n      symmetry. done.\n      setoid_rewrite H in Hv.\n      rewrite Hv. done.\n    + move=> h.\n      apply IHvars.\n      auto.\nQed.\n\nInductive LastIn : Var -> list Var -> Prop :=\n  | LastIn_head: forall v1 vs, \n      Foldable.elem v1 vs = false ->\n      LastIn v1 (v1 :: vs)\n  | LastIn_tail: forall v1 v2 vs,\n      LastIn v1 vs ->\n      LastIn v1 (v2 :: vs).\n\nLemma LastIn_elem : forall v vs, \n    LastIn v vs -> Foldable.elem v vs.\nProof.\n  move => v vs h. \n  induction h; hs_simpl; apply /orP. \n  left. reflexivity.\n  right. assumption.\nQed.  \n  \nLemma LastIn_inj : forall v1 v2 vs, \n    LastIn v1 vs -> v1 == v2 -> LastIn v2 vs -> v1 = v2.\nProof.    \n  move=> v1 v2 vs h. induction h.\n  - move=> eq FI.\n    inversion FI. auto. \n    subst. \n    move: (LastIn_elem H2) => h.\n    rewrite -> HSUtil.elem_resp_eq with (a:= v2) in H; try done.\n    rewrite Eq_sym. done.\n  - move=> eq FI. inversion FI.\n    subst. \n    move: (LastIn_elem h) => h0.\n    rewrite -> HSUtil.elem_resp_eq with (a:= v1) in H1; try done.\n    subst. eauto.\nQed.\n\n\n\nLemma lookupVarSet_extendVarSetList_self_exists_LastIn:\n  forall (vars:list Var) v vs,\n    (Foldable.elem v vars) -> \n    exists v', and3 (lookupVarSet (extendVarSetList vs vars) v = Some v')\n               (v == v')\n               (LastIn v' vars).\nProof.\n  elim => // a vars IH.       (* Do induction on first var, \n                                then trivially discharge goal. *)\n                          (* Then introduce names for list components *)\n  move=> v vs.\n  hs_simpl.\n\n  move => /orP [h1 | h1].  (* case analysis on boolean || *)\n\n  case IN: (Foldable.elem v vars). \n\n  + unfold is_true in *.\n    move: (IH v (extendVarSet vs a) IN) => [v' [p q r]].\n    exists v'; split; eauto.\n    eapply LastIn_tail. auto.\n  + rewrite lookupVarSet_extendVarSetList_false ; try by rewrite IN.\n    exists a. split; eauto.\n    rewrite lookupVarSet_extendVarSet_eq //. \n    symmetry => //.\n    eapply LastIn_head.\n    rewrite <- (elem_eq vars _ _ h1).\n    done.\n  + unfold is_true in *.\n    move: (IH v (extendVarSet vs a) h1) => [v' [p q r]].\n    exists v'; split; eauto.\n    eapply LastIn_tail. auto.\nQed.\n\n\n(*\nLemma lookupVarSet_extendVarSetList_self_exists_in:\n  forall (vars:list Var) v vs,\n    (Foldable.elem v vars) -> \n    exists v', and3 (lookupVarSet (extendVarSetList vs vars) v = Some v')\n               (v == v')\n               (List.In v' vars).\nProof.\n  elim => // a vars IH.       (* Do induction on first var, \n                                then trivially discharge goal. *)\n                          (* Then introduce names for list components *)\n  move=> v vs.\n  hs_simpl.\n\n  move => /orP [h1 | h1].  (* case analysis on boolean || *)\n\n  case IN: (Foldable.elem v vars). \n\n  all: try ( unfold is_true in * ; match goal with \n      [ H : Foldable.elem ?v ?vars = true |- _ ] =>\n        move: (IH v (extendVarSet vs a) H) => [v'[]]* ;\n        exists v'; split; eauto using in_cons\n     end ).\n\n   + rewrite lookupVarSet_extendVarSetList_false ; try by rewrite IN.\n     exists a. split; eauto.\n       rewrite lookupVarSet_extendVarSet_eq //. \n       symmetry => //.\n       eapply in_eq.\nQed.\n*)\n\n\nLemma extendVarSetList_same v vars : forall vs1 vs2 ,\n  Foldable.elem v vars ->\n  lookupVarSet (extendVarSetList  vs1 vars) v = \n  lookupVarSet (extendVarSetList vs2 vars)  v.\nProof.\n  elim: vars => // a vars IHvars. \n  - move => vs1 vs2.\n    hs_simpl.  \n    move=> /orP [h1|h2].\n    + case h: (Foldable.elem v vars); eauto.\n      (* ! rewrites one or more times. *)\n      rewrite !lookupVarSet_extendVarSetList_false; try (rewrite h; done).\n      rewrite !lookupVarSet_extendVarSet_eq // ; symmetry ; done.\n    + auto.\nQed.\n\n\n\n(** ** [mkVarSet]  *)\n\n\nLemma elemVarSet_mkVarset_iff_In:\n  forall v vs,\n  elemVarSet v (mkVarSet vs)  <->  List.In (varUnique v) (map varUnique vs).\nProof.\n  intros.\n  rewrite mkVarSet_extendVarSetList.\n  induction vs.\n  - hs_simpl.\n    simpl.\n    done.\n  - hs_simpl.\n    simpl map.\n    split.\n    + move /orP.        \n      rewrite -> varUnique_iff.\n      rewrite -In_varUnique_elem //. \n      move => [h1|h2] //.\n      rewrite h1.\n      apply in_eq.\n      apply in_cons => //.\n    + move => h.\n      apply /orP.\n      inversion h.\n      ++ left.\n         rewrite varUnique_iff //.\n      ++ right.\n         apply In_varUnique_elem => //.\nQed.\n\n(** ** [delVarSet]  *)\n\nLemma delVarSet_elemVarSet_false : forall v set, \n    elemVarSet v set = false -> delVarSet set v [=] set.\nintros.\nset_b_iff.\napply remove_equal.\nauto.\nQed.\n\n\nLemma delVarSet_emptyVarSet x :\n  delVarSet emptyVarSet x = emptyVarSet.\nProof.\n  unfold delVarSet, emptyVarSet.\n  unfold  UniqSet.delOneFromUniqSet , UniqSet.emptyUniqSet.\n  unfold UniqFM.delFromUFM, UniqFM.emptyUFM.\n  f_equal.\nQed.\nHint Rewrite delVarSet_emptyVarSet : hs_simpl. \n\n\nLemma delVarSet_extendVarSet : \n  forall set v, \n    elemVarSet v set = false -> (delVarSet (extendVarSet set v) v) [=] set.\nProof.\n  intros.\n  set_b_iff.\n  apply remove_add.\n  auto.\nQed.\n\nLemma elemVarSet_delVarSet: forall v1 fvs v2,\n  elemVarSet v1 (delVarSet fvs v2) = negb (v2 == v1) && elemVarSet v1 fvs.\nProof.\n  intros.\n  destruct elemVarSet eqn:EL.\n  + symmetry.\n    apply andb_true_intro.\n    set_b_iff.\n    rewrite -> remove_iff in EL.\n    unfold Var_as_DT.eqb in EL. unfold not in EL.\n    rewrite negb_true_iff.\n    intuition.\n    apply not_true_is_false.\n    auto.\n  + symmetry.\n    apply not_true_is_false.\n    intro H.\n    apply andb_prop in H.\n    set_b_iff.\n    rewrite -> remove_iff in EL.\n    unfold Var_as_DT.eqb in *.\n    intuition.\n    rewrite -> negb_true_iff in H0.\n    apply H2.\n    intro h.\n    unfold Var_as_DT.t in *.\n    rewrite h in H0.\n    inversion H0.\nQed.\n\nHint Rewrite elemVarSet_delVarSet : hs_simpl.\n\nLemma lookupVarSet_delVarSet_neq :\n      forall v1 v2 vs,\n      not (v1 == v2) ->\n      lookupVarSet (delVarSet vs v1) v2 = lookupVarSet vs v2.\nProof.\n  intros v1 v2 vs H.\n  unfold lookupVarSet,delVarSet.\n  unfold UniqSet.lookupUniqSet, UniqSet.delOneFromUniqSet.\n  destruct vs.\n  unfold UniqFM.lookupUFM, UniqFM.delFromUFM.\n  destruct getUniqSet'.\n  assert (Unique.getWordKey (Unique.getUnique v1) <>\n          Unique.getWordKey (Unique.getUnique v2)).\n  { intro h. apply H. rewrite eq_unique. done. }\n  rewrite delete_neq.\n  auto.\n  auto.\nQed.\n\n\n\nLemma elemVarSet_delVarSet_eq x y vs :\n  (x == y) -> elemVarSet x (delVarSet vs y) = false.\nProof.\n  rewrite -> eq_unique.\n  move => Eq.\n  unfold elemVarSet, delVarSet.\n  unfold UniqSet.elementOfUniqSet, UniqSet.delOneFromUniqSet.\n  move: vs => [i].\n  move: i => [m].\n  unfold UniqFM.elemUFM, UniqFM.delFromUFM.\n  rewrite Eq.\n  set key :=  Unique.getWordKey (Unique.getUnique y).\n  move: (@delete_eq key Var m).\n  rewrite <- non_member_lookup.\n  move => h. rewrite h.\n  done.\nQed.\n\n\n(** ** [delVarSetList]  *)\n\n(* These next two rely on this strong property about the unique \n   representations of IntMaps. *)\nLemma delVarSet_commute : forall x y vs, \n    delVarSet (delVarSet vs x) y = delVarSet (delVarSet vs y) x.\nProof.\n  intros.\n  unfold delVarSet.\n  unfold UniqSet.delOneFromUniqSet.\n  destruct vs.\n  f_equal.\n  unfold UniqFM.delFromUFM.\n  destruct getUniqSet'.\n  f_equal.\n  set (kx := Unique.getWordKey (Unique.getUnique x)).\n  set (ky := Unique.getWordKey (Unique.getUnique y)).\n  eapply delete_commute; eauto.\nQed.\n\nLemma delVarSetList_cons2:\n  forall vs e a, delVarSetList e (a :: vs) = delVarSet (delVarSetList e vs) a.\nProof.\n  induction vs; intros e a1;\n  rewrite -> delVarSetList_cons in *.\n  - set_b_iff.\n    hs_simpl.\n    reflexivity.\n  - rewrite delVarSetList_cons.\n    rewrite delVarSetList_cons.\n    rewrite delVarSet_commute.\n    rewrite <- IHvs.\n    rewrite delVarSetList_cons.\n    auto.\nQed.\n\nLemma delVarSetList_rev:\n  forall vs1 vs2,\n  delVarSetList vs1 (rev vs2) = delVarSetList vs1 vs2.\nProof.\n  induction vs2.\n  - simpl. auto.\n  - simpl rev.\n    rewrite delVarSetList_cons.\n    rewrite delVarSetList_app.\n    rewrite IHvs2.\n    rewrite delVarSetList_cons.\n    rewrite delVarSetList_nil.\n    rewrite <- delVarSetList_cons2.\n    rewrite delVarSetList_cons.\n    reflexivity.\nQed.\n\n\nLemma elemVarSet_delVarSetList_false_l:\n  forall v vs vs2,\n  elemVarSet v vs = false ->\n  elemVarSet v (delVarSetList vs vs2) = false.\nProof.\n  intros.\n  revert vs H; induction vs2; intros.\n  * rewrite delVarSetList_nil.\n    assumption.\n  * rewrite delVarSetList_cons.\n    apply IHvs2.\n    set_b_iff; fsetdec.\nQed.\n\nLemma delVarSet_unionVarSet:\n  forall vs1 vs2 x,\n  delVarSet (unionVarSet vs1 vs2) x [=] \n  unionVarSet (delVarSet vs1 x) (delVarSet vs2 x).\nProof.\n  intros.\n  set_b_iff.\n  fsetdec.\nQed.\n\nLemma delVarSetList_unionVarSet:\n  forall vs3 vs1 vs2,\n  delVarSetList (unionVarSet vs1 vs2) vs3 [=] \n  unionVarSet (delVarSetList vs1 vs3) (delVarSetList vs2 vs3).\nProof.\n  induction vs3; intros.\n  - repeat rewrite delVarSetList_nil.\n    reflexivity.\n  - repeat rewrite delVarSetList_cons.\n    rewrite delVarSet_unionVarSet.\n    rewrite IHvs3.\n    reflexivity.\nQed.\n\n\n(**************************************)\n\n\n(** ** [subVarSet]  *)\n  \nLemma subVarSet_refl:\n  forall vs1,\n  subVarSet vs1 vs1 .\nProof.\n  intros.\n  set_b_iff.\n  fsetdec.\nQed.\n\nLemma subVarSet_trans:\n  forall vs1 vs2 vs3,\n  subVarSet vs1 vs2  ->\n  subVarSet vs2 vs3  ->\n  subVarSet vs1 vs3 .\nProof.\n  intros.\n  set_b_iff.\n  fsetdec.\nQed.\n\n\nLemma subVarSet_emptyVarSet:\n  forall vs,\n  subVarSet emptyVarSet vs .\nProof.\n  intros.\n  set_b_iff.\n  fsetdec.\nQed.\n\n\nLemma subVarSet_unitVarSet:\n  forall v vs,\n  subVarSet (unitVarSet v) vs = elemVarSet v vs.\nProof.\n  intros.\n  destruct subVarSet eqn:SV; symmetry.\n  + set_b_iff.\n    fsetdec.\n  + rewrite -> false_is_not_true in *.\n    set_b_iff.\n    intro h.\n    unfold Subset in SV.\n    apply SV.\n    intros.\n    rewrite In_eq_iff; eauto.\nQed.\n\nLemma elemVarSet_false_true:\n  forall v1 fvs v2,\n  elemVarSet v1 fvs = false ->\n  elemVarSet v2 fvs  ->\n  varUnique v1 <> varUnique v2.\nProof.\n  intros v1 fvs v2.\n  intros.\n  assert (not (v2 == v1 )).\n  intro h. \n  set_b_iff.\n  rewrite -> In_eq_iff in H0; eauto.\n  intro h.\n  rewrite <- varUnique_iff in h.\n  apply H1.\n  rewrite Eq_sym.\n  auto.\nQed.\n\nLemma subVarSet_elemVarSet_true:\n  forall v vs vs',\n  subVarSet vs vs'  ->\n  elemVarSet v vs  ->\n  elemVarSet v vs' .\nProof.\n  intros v vs vs'.\n  set_b_iff.\n  fsetdec.\nQed.\n\nLemma subVarSet_elemVarSet_false:\n  forall v vs vs',\n  subVarSet vs vs'  ->\n  elemVarSet v vs' = false ->\n  elemVarSet v vs = false.\nProof.\n  intros v vs vs'.\n  set_b_iff.\n  fsetdec.\nQed.\n\nLemma subVarSet_extendVarSetList_l:\n  forall vs1 vs2 vs,\n  subVarSet vs1 vs2  ->\n  subVarSet vs1 (extendVarSetList vs2 vs) .\nProof.\n  intros vs1 vs2 vs.\n  generalize dependent vs2.\n  induction vs.\n  - intro vs2. rewrite extendVarSetList_nil. auto.\n  - intro vs2. intro h. \n    rewrite extendVarSetList_cons. \n    rewrite IHvs. auto. \n    set_b_iff. fsetdec.\nQed.\n\n\n    \n\nLemma subVarSet_extendVarSet_both:\n  forall vs1 vs2 v,\n  subVarSet vs1 vs2  ->\n  subVarSet (extendVarSet vs1 v) (extendVarSet vs2 v) .\nProof.\n  intros.\n  set_b_iff.\n  fsetdec.\nQed.\n\n\nLemma subVarSet_extendVarSet:\n  forall vs1 vs2 v,\n  subVarSet vs1 vs2  ->\n  subVarSet vs1 (extendVarSet vs2 v) .\nProof.\n  intros.\n  set_b_iff.\n  fsetdec.\nQed.\n\n\nLemma subVarSet_extendVarSetList:\n  forall vs1 vs2 vs3,\n  subVarSet vs1 vs2  ->\n  subVarSet vs1 (extendVarSetList vs2 vs3) .\nProof.\n\n  induction vs3; autorewrite with hs_simpl.\n  - auto.\n  - intro h. \n    rewrite extendVarSetList_extendVarSet_iff.\n    rewrite subVarSet_extendVarSet; auto.\nQed.\n\nLemma subVarSet_extendVarSet_l:\n  forall vs1 vs2 v v',\n  subVarSet vs1 vs2  ->\n  lookupVarSet vs2 v = Some v' ->\n  subVarSet (extendVarSet vs1 v) vs2 .\nProof.\n  intros.\n  set_b_iff.\n  apply MP.subset_add_3; try assumption.\n  apply lookupVarSet_In.\n  eauto.\nQed.\n\nLemma extendVarSet_subset: forall v1 v2 x,\n  v1 [<=] v2 ->\n  extendVarSet v1 x [<=] extendVarSet v2 x.\nProof.\n  intros.\n  set_b_iff.\n  fsetdec.\nQed.\n  \nLemma extendVarSetList_subset: forall x y vs,\n  x [<=] y ->\n  extendVarSetList x vs [<=] extendVarSetList y vs.\nProof.\n  intros.\n  induction vs; hs_simpl; [assumption|].\n  do 2 rewrite extendVarSetList_extendVarSet_iff.\n  apply extendVarSet_subset.\n  assumption.\nQed.\n\nLemma subVarSet_extendVarSetList_r:\n  forall vs vs1 vs2,\n  subVarSet vs1 (mkVarSet vs)  ->\n  subVarSet vs1 (extendVarSetList vs2 vs) .\nProof.\n  intros vs. \n  rewrite mkVarSet_extendVarSetList.\n  induction vs; intros vs1 vs2.\n  - autorewrite with hs_simpl.\n    set_b_iff.\n    fsetdec.\n  - intro h.     \n    autorewrite with hs_simpl in *.\n    rewrite -> extendVarSetList_extendVarSet_iff in *.\n    destruct (mem a (extendVarSetList empty vs)) eqn:Hd;\n    [|destruct (mem a vs1) eqn:Hd'].\n    + specialize (IHvs vs1 vs2). \n      set_b_iff.\n      assert (Hvs2: In a (extendVarSetList vs2 vs)).\n      * clear -Hd.\n        eapply MP.in_subset.\n        apply Hd. clear Hd a.\n        apply extendVarSetList_subset.\n        fsetdec.\n      * pose proof (subset_equal\n                     (equal_sym (add_equal Hvs2))).\n        eapply (Subset_trans); [apply IHvs| apply H].\n        pose proof (subset_equal (add_equal Hd)).\n        fsetdec.\n    + specialize (IHvs (remove a vs1) vs2). \n      set_b_iff.\n      apply remove_s_m with (x:= a) (y:=a) in h;\n        [|fsetdec].\n      assert (Hs: remove a (add a\n                                (extendVarSetList empty vs))\n                         [<=] (extendVarSetList empty vs)).\n      { apply subset_equal.\n        apply remove_add.\n        assumption. }\n        specialize (IHvs (Subset_trans h Hs)).\n      apply add_s_m with (x:= a) (y:=a) in IHvs;\n        [|fsetdec].\n      assert (Hs': vs1 [<=] add a (remove a vs1)).\n      { apply subset_equal.\n        apply equal_sym.\n        apply add_remove.\n        assumption. }\n      eapply Subset_trans.\n      apply Hs'.\n      assumption.\n    + specialize (IHvs vs1 vs2). \n      set_b_iff.\n      apply subset_add_2.\n      apply IHvs.\n      eapply remove_s_m with (x:= a) (y:=a) in h;\n        [|fsetdec].\n      apply remove_equal in Hd'.\n      fsetdec.\nQed.\n\n    \n\nLemma subVarSet_delVarSet:\n  forall vs1 v,\n  subVarSet (delVarSet vs1 v) vs1 .\nProof.\n  intros.\n  set_b_iff.\n  fsetdec.\nQed.\n\n\nLemma subVarSet_delVarSetList:\n  forall vs1 vl,\n  subVarSet (delVarSetList vs1 vl) vs1 .\nProof.\n  intros.\n  set_b_iff.\n  generalize vs1. clear vs1. induction vl.\n  - intros vs1. hs_simpl. \n    fsetdec.\n  - intros vs1. revert IHvl.\n    hs_simpl.\n    simpl.\n    intro IH. \n    rewrite -> IH with (vs1 := delVarSet vs1 a).\n    set_b_iff.\n    fsetdec.\nQed.\n\n\nLemma subVarSet_delVarSetList_both:\n  forall vs1 vs2 vl,\n  subVarSet vs1 vs2  ->\n  subVarSet (delVarSetList vs1 vl) (delVarSetList vs2 vl) .\nProof.\n  intros.\n  revert vs1 vs2 H. induction vl; intros.\n  - rewrite !delVarSetList_nil.\n    assumption.\n  - rewrite !delVarSetList_cons.\n    apply IHvl.\n    set_b_iff.\n    fsetdec.\nQed.\n\nLemma subVarSet_delVarSet_extendVarSet:\n  forall jps isvs v,\n  subVarSet jps isvs  ->\n  subVarSet (delVarSet jps v) (extendVarSet isvs v) .\nProof.\n  intros.\n  eapply subVarSet_trans.\n  apply subVarSet_delVarSet.\n  apply subVarSet_extendVarSet.\n  assumption.\nQed.\n\nLemma subVarSet_delVarSetList_extendVarSetList:\n  forall jps isvs vs,\n  subVarSet jps isvs  ->\n  subVarSet (delVarSetList jps vs) (extendVarSetList isvs vs) .\nProof.\n  intros.\n  eapply subVarSet_trans.\n  apply subVarSet_delVarSetList.\n  apply subVarSet_extendVarSetList.\n  assumption.\nQed.\n\n\nLemma subVarSet_delVarSetList_extendVarSetList_dual:\n  forall jps isvs vs,\n  subVarSet jps (extendVarSetList isvs vs)  ->\n  subVarSet (delVarSetList jps vs) isvs .\nProof.\n  intros.\n  revert jps isvs H.\n  induction vs; intros.\n  - rewrite !delVarSetList_nil.\n    rewrite !extendVarSetList_nil in H.\n    assumption.\n  - rewrite delVarSetList_cons2.\n    revert H.\n    hs_simpl.\n    intro H.\n    apply IHvs in H.\n    set_b_iff.\n    fsetdec.\nQed.\n\n\nLemma mapUnionVarSet_In_subVarSet:\n  forall a (x : a) xs f,\n  List.In x xs ->\n  subVarSet (f x) (mapUnionVarSet f xs).\nProof.\n  intros a x xs f H.\n  generalize dependent x.\n  induction xs; intros x H.\n  - inversion H.\n  - \n    inversion H as [H'|H'].\n    + unfold mapUnionVarSet.\n      unfold_Foldable_foldr.\n      subst.\n      simpl.\n      set_b_iff.\n      fsetdec.\n    + apply IHxs in H'.\n      clear H IHxs.\n      revert H'.\n      unfold mapUnionVarSet.\n      unfold_Foldable_foldr.\n      intros H'.\n      eapply subVarSet_trans.\n      apply H'.\n      clear H'.\n      set_b_iff.\n      simpl.\n      fsetdec.\nQed.\n\n\nLemma subVarSet_mapUnionVarSet:\n  forall a (xs : list a) f vs,\n  Forall (fun x => subVarSet (f x) vs ) xs ->\n  subVarSet (mapUnionVarSet f xs) vs.\nProof.\n  intros a xs f vs H.\n  induction xs.\n  - unfold mapUnionVarSet.\n    unfold_Foldable_foldr.\n    simpl.\n    apply subVarSet_emptyVarSet.\n  - inversion H.\n    subst.\n    apply IHxs in H3.\n    clear IHxs.\n    revert H3.\n    unfold mapUnionVarSet.\n    unfold_Foldable_foldr.\n    intros H3.\n    set_b_iff.\n    simpl.\n    fsetdec.\nQed.\n\n\nLemma subVarSet_unionVarSet:\n  forall vs1 vs2 vs3,\n  subVarSet (unionVarSet vs1 vs2) vs3 = subVarSet vs1 vs3 && subVarSet vs2 vs3.\nProof.\n  intros.\n  apply eq_iff_eq_true.\n  rewrite andb_true_iff.\n  set_b_iff.\n  split; intro H.\n  - split; fsetdec.\n  - destruct H; fsetdec.\nQed.\n\n\nAxiom null_intersection_eq : forall b (x1 x2 y1 y2 : IntMap.Internal.IntMap b), \n  (forall a, IntMap.Internal.member a x1 <-> IntMap.Internal.member a y1) ->\n  (forall a, IntMap.Internal.member a x2 <-> IntMap.Internal.member a y2) ->\n  IntMap.Internal.null (IntMap.Internal.intersection x1 x2) = IntMap.Internal.null (IntMap.Internal.intersection y1 y2).\n\n\n(** ** [disjointVarSet]  *)\n\nInstance disjointVarSet_m : Proper (Equal ==> Equal ==> Logic.eq) disjointVarSet.\nProof. \n  move => x1 y1.  \n  move: (@ValidVarSet_Axiom x1).\n  move: (@ValidVarSet_Axiom y1).\n  move: x1 => [x1]. move: y1=> [y1].\n  move: x1 => [x1]. move: y1=> [y1].\n  move=> vx1 vy1 Eq1.\n  move=> x2 y2. \n  move: (@ValidVarSet_Axiom x2).   move: (@ValidVarSet_Axiom y2).\n  move: x2 => [x2]. move: y2=> [y2].\n  move: x2 => [x2]. move: y2=> [y2].\n  move=> vx2 vy2 Eq2.  \n\n  unfold ValidVarSet, disjointVarSet,\n         UniqFM.disjointUFM,\n         UniqSet.getUniqSet, \n         UniqSet.getUniqSet' in *.\n  unfold lookupVarSet, UniqSet.lookupUniqSet,UniqFM.lookupUFM in *.\n  unfold Equal, In, elemVarSet, UniqSet.elementOfUniqSet, UniqFM.elemUFM in Eq1.\n  unfold Equal, In, elemVarSet, UniqSet.elementOfUniqSet, UniqFM.elemUFM in Eq2.\n  apply null_intersection_eq; eauto.\n  move=> k1.  \n  split. move=> Ink1.\nAdmitted.\n\n\n(*\nLemma foldl'_simplify (a b c :Type) (f:c -> b) (g:b->c) (h:b -> a -> b)\n      (xb:b) (xs : list a):\n  (forall x, f (g x) = x) ->\n  Foldable.foldl' (fun x y => g (h (f x) y)) (g xb) xs = \n  g (Foldable.foldl' h xb xs).\nProof.  \n  move => eq.\n  induction xs.\n  hs_simpl. auto.\n  hs_simpl.\n  rewrite eq.\n*)\n\nLemma UniqSet_Mk_UniqSet_eta :\n  forall a b (x : UniqSet.UniqSet a) (f : UniqSet.UniqSet a -> b), \n    match x with\n    | UniqSet.Mk_UniqSet set => f (UniqSet.Mk_UniqSet set)\n    end = f x.\nProof.            \n  move => a b [set] //.\nQed.\n\n\nLemma disjointVarSet_empytVarSet:\n  forall vs,\n  disjointVarSet vs emptyVarSet.\nProof.\n  move => vs1.\n  elim: vs1 => [i].\n  unfold disjointVarSet, emptyVarSet, elemVarSet.\n  simpl.\n  elim: i => [j].\n  simpl.\n  apply intersection_empty.\n  done.\nQed.\nHint Rewrite disjointVarSet_empytVarSet:hs_simpl.\n\nLemma disjointVarSet_mkVarSet_nil:\n  forall vs,\n  disjointVarSet vs (mkVarSet []).\nProof.\n  rewrite mkVarSet_extendVarSetList.\n  hs_simpl.\n  apply disjointVarSet_empytVarSet.\nQed.\n\nLemma disjointVarSet_extendVarSet vs1 var vs2 : \n  disjointVarSet vs1 (extendVarSet vs2 var) <->\n  elemVarSet var vs1 = false /\\ disjointVarSet vs1 vs2.\nProof.\n  move: vs1 vs2 => [[i1]] [[i2]].\n  unfold disjointVarSet, elemVarSet, extendVarSet.\n  unfold UniqSet.getUniqSet,UniqSet.getUniqSet',\n         UniqSet.elementOfUniqSet, UniqSet.addOneToUniqSet.\n  unfold UniqFM.disjointUFM, UniqFM.elemUFM, UniqFM.addToUFM.\n  set k:=  (Unique.getWordKey (Unique.getUnique var)).\n  apply null_intersection_non_member.\nQed.\n\nLemma disjointVarSet_mkVarSet_cons:\n  forall v vs1 vs2,\n  disjointVarSet vs1 (mkVarSet (v :: vs2))  <->\n  elemVarSet v vs1 = false /\\ disjointVarSet vs1 (mkVarSet vs2) .\nProof.\n  move=> v vs1 vs2.\n  rewrite mkVarSet_extendVarSetList.\n  hs_simpl.\n  rewrite extendVarSetList_extendVarSet_iff.\n  rewrite disjointVarSet_extendVarSet.\n  tauto.\nQed.\n\n      \nLemma disjointVarSet_mkVarSet_append:\n  forall vs1 vs2 vs3,\n  disjointVarSet vs1 (mkVarSet (vs2 ++ vs3))  <->\n  disjointVarSet vs1 (mkVarSet vs2)  /\\ disjointVarSet vs1 (mkVarSet vs3).\nProof.  \n  move=> vs1 vs2 vs3.\n  rewrite mkVarSet_extendVarSetList.\n  hs_simpl.\n  elim: vs3 => [|var vars IH]; hs_simpl.\n  + rewrite mkVarSet_extendVarSetList.\n    intuition.\n  + rewrite disjointVarSet_mkVarSet_cons.\n    rewrite and_comm.\n    rewrite and_assoc.\n    rewrite -> and_comm in IH.\n    rewrite <- IH.\n    rewrite extendVarSetList_extendVarSet_iff.\n    rewrite disjointVarSet_extendVarSet.\n    tauto.\nQed. \n\n\nLemma disjointVarSet_mkVarSet:\n  forall vs1 vs2,\n  disjointVarSet vs1 (mkVarSet vs2)  <->\n  Forall (fun v => elemVarSet v vs1 = false) vs2.\nProof.\n  move => vs1 vs2.\n  elim: vs2 => [|v vars IH].\n  rewrite disjointVarSet_mkVarSet_nil. intuition.\n  rewrite disjointVarSet_mkVarSet_cons. rewrite IH.\n  intuition.\n  - inversion H1. auto.\n  - inversion H1. auto.\nQed.\n\n\nLemma disjointVarSet_subVarSet_l:\n  forall vs1 vs2 vs3,\n  disjointVarSet vs2 vs3  ->\n  subVarSet vs1 vs2  ->\n  disjointVarSet vs1 vs3 .\nProof.\n  move=> [[i1]][[i2]][[i3]].\n  unfold disjointVarSet, subVarSet, isEmptyVarSet,minusVarSet.\n  unfold UniqSet.getUniqSet,UniqSet.getUniqSet',\n  UniqSet.isEmptyUniqSet, UniqSet.minusUniqSet.\n  unfold UniqFM.disjointUFM, UniqFM.isNullUFM, UniqFM.minusUFM.\n  apply disjoint_difference.\nQed.\n\n\n(** ** [filterVarSet] *)\n\nLemma filterVarSet_comp : forall f f' vs,\n    filterVarSet f (filterVarSet f' vs) = filterVarSet (fun v => f v && f' v) vs.\nProof.\n  intros.\n  destruct vs; destruct getUniqSet'. simpl. do 2 f_equal.\n  apply filter_comp.\nQed.\n\n\nLemma filterSingletonTrue : forall f x,\n  RespectsVar f ->\n  f x = true -> \n  filterVarSet f (unitVarSet x) [=] unitVarSet x.\nProof. \n  move=> f x RR TR.\n  set_b_iff.\n  replace (singleton x) with (add x empty).\n  rewrite -> filter_add_1; auto.\n  fsetdec.\n  fsetdec.\nQed.\n\nLemma filterSingletonFalse : forall f x,\n  RespectsVar f ->\n  f x = false -> \n  filterVarSet f (unitVarSet x) [=] emptyVarSet.\nProof. \n  move=> f x RR TR.\n  set_b_iff.\n  replace (singleton x) with (add x empty).\n  rewrite -> filter_add_2; auto.\n  fsetdec.\n  fsetdec.\nQed.\n\nLemma filterVarSet_emptyVarSet f :\n  filterVarSet f emptyVarSet = emptyVarSet.\nProof.\n  set_b_iff.\n  fsetdec.\nQed.\nHint Rewrite filterVarSet_emptyVarSet : hs_simpl.\n\n\nLemma filterVarSet_constTrue vs : \n  filterVarSet (const true) vs = vs.\nProof. \n  unfold filterVarSet.\n  elim: vs => [i].\n  elim: i => [m].\n  unfold UniqSet.filterUniqSet.\n  unfold UniqFM.filterUFM.\n  f_equal.\n  f_equal.\n  rewrite filter_true.\n  reflexivity.\nQed.\nHint Rewrite filterVarSet_constTrue : hs_simpl.\n\nLemma elemVarSet_filterVarSet x f vs :\n  RespectsVar f ->\n  elemVarSet x (filterVarSet f vs) = f x && elemVarSet x vs.\nProof.\n  move => h.\n  rewrite eqE.\n  set_b_iff.\n  rewrite andE.\n  unfold is_true.\n  set_b_iff.\n  rewrite and_comm.\n  apply F.filter_iff.\n  auto.\nQed.\n\nLemma filterVarSet_iff (f1 f2 : Var -> bool) vs : \n  (forall x, (f1 x) <-> (f2 x)) -> \n  filterVarSet f1 vs [=] filterVarSet f2 vs.\nAdmitted.\n\nLemma filterVarSet_equal f vs1 vs2 :\n  RespectsVar f -> \n  vs1 [=] vs2 ->\n  filterVarSet f vs1 [=] filterVarSet f vs2.\nProof.\n  move => RF EQ.\n  set_b_iff.\n  eapply filter_equal; eauto.\nQed.\n\nLemma filterVarSet_extendVarSet : \n  forall f v vs,\n    RespectsVar f ->\n    filterVarSet f (extendVarSet vs v) [=] \n    if (f v) then extendVarSet (filterVarSet f vs) v \n    else (filterVarSet f vs).\nProof.\n  intros.\n  set_b_iff.\n  destruct (f v) eqn:Hfv; auto.\n  rewrite -> filter_add_1; try done.\n  rewrite -> filter_add_2; try done.\nQed.\n\n\nLemma lookupVarSet_filterVarSet_true : forall f v vs,\n  RespectsVar f ->\n  f v = true ->\n  lookupVarSet (filterVarSet f vs) v = lookupVarSet vs v.\nProof.\n  intros.\n  destruct (lookupVarSet (filterVarSet f vs) v) eqn:Hl.\n  - revert Hl.\n    unfold_VarSet_to_IntMap.\n    unfold IntMap.Internal.filter.\n    symmetry.\n    erewrite lookup_filterWithKey; eauto.\n  - apply lookupVarSet_None_elemVarSet in Hl.\n    symmetry.\n    apply lookupVarSet_None_elemVarSet.\n    set_b_iff.\n    intros Hin.\n    eapply filter_3 in Hin; eauto.\nQed.\n\nLemma lookupVarSet_filterVarSet_false : forall f v vs,\n  RespectsVar f ->\n  f v = false ->\n  lookupVarSet (filterVarSet f vs) v = None.\nProof.\n  intros.\n  apply lookupVarSet_None_elemVarSet.\n  set_b_iff.\n  rewrite filter_iff; [|auto].\n  intros [H1 H2].\n  rewrite H0 in H2.\n  inversion H2.\nQed.\n\nLemma unionVarSet_filterVarSet f vs1 vs2 :\n  RespectsVar f ->\n  unionVarSet (filterVarSet f vs1) (filterVarSet f vs2) [=] filterVarSet f (unionVarSet vs1 vs2).\nProof.\n  move=> g.\n  set_b_iff.\n  rewrite <- filter_union.\n  reflexivity.\n  eauto.\nQed.\n\nLemma filterVarSet_delVarSet f vs v :\n  RespectsVar f ->\n  filterVarSet f (delVarSet vs v) [=]\n  delVarSet (filterVarSet f vs) v.\nProof.\n  move=> Ff. unfold RespectsVar in Ff.\n  set_b_iff. \nAdmitted.\n\n\nLemma filterVarSet_delVarSetList:\n  forall (f : Var -> bool)  (vars : list Var) (vs : VarSet),\n  RespectsVar f ->\n  filterVarSet f (delVarSetList  vs vars) [=] delVarSetList (filterVarSet f vs) vars.\nProof.\n  induction vars.\n  - move=> vs h. hs_simpl. reflexivity.\n  - move=> vs h.  hs_simpl. \n    rewrite IHvars; try done.\n    rewrite <- filterVarSet_delVarSet; try done.\nQed.\n\n\n(** ** [unionVarSet] *)\n\nLemma unionVarSet_sym vs1 vs2 : unionVarSet vs1 vs2 [=] unionVarSet vs2 vs1.\nProof. set_b_iff. fsetdec. Qed.\n\n\nLemma unionEmpty_l : forall vs,\n    unionVarSet emptyVarSet vs [=] vs.\nProof. set_b_iff. fsetdec. Qed.\nLemma unionEmpty_r : forall vs,\n    unionVarSet vs emptyVarSet [=] vs.\nProof. set_b_iff. fsetdec. Qed.\nLemma unionSingle_l : forall x s,\n    unionVarSet (unitVarSet x) s [=] extendVarSet s x.\nProof. intros. set_b_iff. fsetdec. Qed.\nLemma unionSingle_r : forall x s,\n    unionVarSet s (unitVarSet x) [=] extendVarSet s x.\nProof. intros. set_b_iff. fsetdec. Qed.\n\nHint Rewrite unionEmpty_l unionEmpty_r \n     unionSingle_l unionSingle_r :\n  hs_simpl.\n\n\n(** ** [minusVarSet] *)\n\nLemma minusVarSet_emptyVarSet vs : \n  minusVarSet vs emptyVarSet = vs.\nProof.\n  unfold minusVarSet, emptyVarSet.\n  unfold UniqSet.minusUniqSet, UniqSet.emptyUniqSet.\n  elim: vs => [i].\n  elim: i => [m].\n  unfold UniqFM.minusUFM, UniqFM.emptyUFM.\n  f_equal.\n  f_equal.\n  unfold IntMap.Internal.empty.\n  rewrite difference_nil_r.\n  reflexivity.\nQed.\n\nHint Rewrite minusVarSet_emptyVarSet : hs_simpl.\n\nLemma minusVarSet_emptyVarSet_l vs : \n  minusVarSet emptyVarSet vs = emptyVarSet.\nProof.\n  unfold minusVarSet, emptyVarSet.\n  unfold UniqSet.minusUniqSet, UniqSet.emptyUniqSet.\n  elim: vs => [i].\n  elim: i => [m].\n  unfold UniqFM.minusUFM, UniqFM.emptyUFM.\n  f_equal.\n  f_equal.\n  unfold IntMap.Internal.empty.\n  rewrite difference_nil_l.\n  reflexivity.\nQed.\n\nHint Rewrite minusVarSet_emptyVarSet_l : hs_simpl.\n\n\n\nLemma elemVarSet_minusVarSetTrue : forall x s,\n  elemVarSet x s = true -> \n  minusVarSet (unitVarSet x) s [=] emptyVarSet.\nProof. intros. set_b_iff. \n       split; try fsetdec.\n       move=> h.\n       move: (diff_1 _ _ _ h) => h1.\n       move: (diff_2 _ _ _ h) => h2.\n       inversion h1. clear h1.\n       rewrite <- var_eq_realUnique in H1.\n       rewrite -> fold_is_true in H1.\n       unfold In in H, h2.\n       rewrite (@elemVarSet_eq a x) in h2.\n       done.\n       done.\nQed.\n\n\nLemma elemVarSet_minusVarSetFalse : forall x s,\n  elemVarSet x s = false -> \n  minusVarSet (unitVarSet x) s [=] unitVarSet x.\nProof.\n  intros. \n  set_b_iff.\n  split; try fsetdec.\n  move=> h.\n  apply diff_3; try done.\n  inversion h.\n  unfold In, singleton in *.\n  rewrite  (@elemVarSet_eq x a) in H; try done.\n  rewrite var_eq_realUnique.\n  rewrite Eq_sym; done.\nQed.\n\n\n\nLemma elemVarSet_minusVarSet x vs1 vs2 :\n  elemVarSet x (minusVarSet vs1 vs2) = elemVarSet x vs1 && ~~ elemVarSet x vs2.\nProof.\n  rewrite eqE.\n  set_b_iff.\n  rewrite F.diff_iff.\n  split.\n  move => [h1 h2]. apply /andP. split. auto.\n  apply /negPf.\n  set_b_iff. auto.\n  move => /andP [h1 h2].\n  move: h2 => /negPf => h2.\n  set_b_iff. auto.\nQed.\n\n\nLemma unionVarSet_minusVarSet vs1 vs2 vs :\n  unionVarSet (minusVarSet vs1 vs) (minusVarSet vs2 vs) [=]\n  minusVarSet (unionVarSet vs1 vs2) vs.\nProof.\n  unfold Equal.\n  move=> x.\n  unfold In.\n  rewrite! elemVarSet_minusVarSet.\n  rewrite! elemVarSet_unionVarSet.\n  rewrite! elemVarSet_minusVarSet.\n  rewrite! andb_orb_distrib_l.\n  reflexivity.\nQed.\n\n\n(** ** Compatibility with [almostEqual] *)\n\nLemma lookupVarSet_ae : \n  forall vs v1 v2, \n    almostEqual v1 v2 -> \n    lookupVarSet vs v1 = lookupVarSet vs v2.\nProof. \n  induction 1; simpl; unfold UniqFM.lookupUFM; simpl; auto.\nQed.\n\nLemma delVarSet_ae:\n  forall vs v1 v2,\n  almostEqual v1 v2 ->\n  delVarSet vs v1 = delVarSet vs v2.\nProof.\n  induction 1; simpl;\n  unfold UniqFM.delFromUFM; simpl; auto.\nQed.\n\nLemma elemVarSet_ae:\n  forall vs v1 v2,\n  almostEqual v1 v2 ->\n  elemVarSet v1 vs = elemVarSet v2 vs.\nProof.\n  induction 1; simpl;\n  unfold UniqFM.delFromUFM; simpl; auto.\nQed.\n\n(** ** [StrongSubset] *)\n\n\n(* A strong subset doesn't just have a subset of the uniques, but \n     also requires that the variables in common be almostEqual. *)\nDefinition StrongSubset (vs1 : VarSet) (vs2: VarSet) := \n  forall var, match lookupVarSet vs1 var with \n           | Some v =>  match lookupVarSet vs2 var with\n                          | Some v' => almostEqual v v'\n                          | None => False\n                       end\n           | None => True \n         end.\n\n\nNotation \"s1 {<=} s2\" := (StrongSubset s1 s2) (at level 70, no associativity).\nNotation \"s1 {=} s2\" := (StrongSubset s1 s2 /\\ StrongSubset s2 s1) (at level 70, no associativity).\n\n\nLemma StrongSubset_refl : forall vs, \n    StrongSubset vs vs.\nProof.\n  unfold StrongSubset.\n  move=> vs var.\n  elim h: (lookupVarSet vs var) => //.\n  eapply almostEqual_refl.\nQed.\n\nInstance StrongSubset_Reflexive : Reflexive StrongSubset := StrongSubset_refl.\n\nLemma StrongSubset_trans : forall vs1 vs2 vs3, \n    StrongSubset vs1 vs2 -> StrongSubset vs2 vs3 -> StrongSubset vs1 vs3.\nProof.\n  move => vs1 vs2 vs3 h1 h2 var.\n  specialize (h1 var).\n  specialize (h2 var).\n  move: h1 h2.\n  elim p1: (lookupVarSet vs1 var) => //;\n  elim p2: (lookupVarSet vs2 var) => //;\n  elim p3: (lookupVarSet vs3 var) => //.\n  eapply almostEqual_trans.\nQed.\n\n\nInstance StrongSubset_Transitive : Transitive StrongSubset := StrongSubset_trans.\n\n\nLemma strongSubset_implies_subset :\n  forall vs1 vs2 , \n    StrongSubset vs1 vs2 -> vs1 [<=] vs2.\nProof. \n  intros vs1 vs2.\n  unfold StrongSubset, Subset.\n  intros SS var IN.\n  unfold In in *.\n  specialize (SS var). \n  destruct (lookupVarSet vs1 var) eqn:VS1;\n  destruct (lookupVarSet vs2 var) eqn:VS2; try contradiction.\n  - apply lookupVarSet_elemVarSet in VS2.   \n    auto.\n  - apply elemVarSet_lookupVarSet in IN. destruct IN.\n    rewrite VS1 in H. discriminate.\n  - apply elemVarSet_lookupVarSet in IN. destruct IN.\n    rewrite VS1 in H. discriminate.\nQed.\n\n\n\nLemma StrongSubset_extend_fresh :\n  forall vs v,\n  lookupVarSet vs v = None ->\n  StrongSubset vs (extendVarSet vs v).\nProof.\n  intros.\n  unfold StrongSubset.\n  intros var.\n  destruct (var == v) eqn:EQV.\n  rewrite -> lookupVarSet_eq with (v2 := v); auto.\n  rewrite H. auto.\n  destruct (lookupVarSet vs var) eqn:Lvar; auto.\n  rewrite lookupVarSet_extendVarSet_neq.\n  rewrite Lvar.\n  apply almostEqual_refl.\n  unfold CoreBndr in *. intro h. rewrite Base.Eq_sym in h. rewrite h in EQV. discriminate.\nQed.\n\nLemma elemNegbDisjoint : forall vs vs2, \n    disjointVarSet vs (mkVarSet vs2) ->\n    forall v, Foldable.elem v vs2 -> negb (elemVarSet v vs).\nProof.\n  move=> vs.\n  elim => [|x xs IHxs].\n  - move => ? v. hs_simpl. done.\n  - rewrite disjointVarSet_mkVarSet_cons.\n    move => [h1 h2] v.\n    hs_simpl.\n    move => /orP [h3|h3].\n    erewrite (@elemVarSet_eq x v) in h1.\n    rewrite h1. done.\n    symmetry. done.\n    apply IHxs; try done.\nQed.\n\n\n\nLemma StrongSubset_extendList_fresh :\n  forall vs vs2,\n  disjointVarSet vs (mkVarSet vs2)  ->\n  StrongSubset vs (extendVarSetList vs vs2).\nProof.\n  intros.\n  unfold StrongSubset.\n  intros v.\n  destruct_match; try trivial.\n  case in2: (Foldable.elem v vs2).  \n  * eapply elemNegbDisjoint in in2; eauto.\n    eapply lookupVarSet_elemVarSet in Heq; eauto. \n    erewrite Heq in in2. done.\n  * rewrite lookupVarSet_extendVarSetList_false; try done.\n    rewrite Heq.\n    eapply almostEqual_refl.\n    rewrite in2. done.\nQed.\n\n\nLemma StrongSubset_extend_ae :\n  forall vs1 vs2 v1 v2,\n  StrongSubset vs1 vs2 ->\n  almostEqual v1 v2 ->\n  StrongSubset (extendVarSet vs1 v1) (extendVarSet vs2 v2).\nProof.\n  intros.\n  unfold StrongSubset in *.\n  intro var.\n  destruct (v1 == var) eqn:EQv.\n  rewrite lookupVarSet_extendVarSet_eq; auto.  \n  rewrite lookupVarSet_extendVarSet_eq.\n  assumption.\n  apply almostEqual_eq in H0. eapply Eq_trans; try eassumption; try symmetry; assumption.\n  rewrite lookupVarSet_extendVarSet_neq; auto.\n  rewrite lookupVarSet_extendVarSet_neq; auto.\n  eapply H.\n  rewrite <- not_true_iff_false in EQv. contradict EQv.\n  apply almostEqual_eq in H0. eapply Eq_trans; try eassumption; try symmetry; assumption.\n  rewrite not_true_iff_false. assumption.\nQed.\n\n\nLemma StrongSubset_extend :\n  forall vs1 vs2 v,\n  StrongSubset vs1 vs2 ->\n  StrongSubset (extendVarSet vs1 v) (extendVarSet vs2 v).\nProof.\n  intros.\n  apply StrongSubset_extend_ae.\n  * assumption.\n  * apply almostEqual_refl.\nQed.\n\nLemma StrongSubset_extendVarSetList_ae :\n  forall l1 l2 vs1 vs2,\n  Forall2 almostEqual l1 l2 ->\n  StrongSubset vs1 vs2 ->\n  StrongSubset (extendVarSetList vs1 l1) (extendVarSetList vs2 l2).\nProof.\n  intros.\n  revert vs1 vs2 H0. induction H; intros.\n  * apply H0.\n  * rewrite extendVarSetList_cons.\n    apply IHForall2.\n    apply StrongSubset_extend_ae; assumption.\nQed.\n\nLemma Forall2_diag:\n  forall a P (xs: list a),\n  Forall2 P xs xs <-> Forall (fun x => P x x) xs.\nProof.\n  intros.\n  induction xs.\n  * split; intro; constructor.\n  * split; intro H; constructor; inversion H; intuition.\nQed.\n\nLemma StrongSubset_extendVarSetList :\n  forall l vs1 vs2,\n  StrongSubset vs1 vs2 ->\n  StrongSubset (extendVarSetList vs1 l) (extendVarSetList vs2 l).\nProof.\n  intros.\n  apply StrongSubset_extendVarSetList_ae; only 2: assumption.\n  apply Forall2_diag.\n  rewrite Forall_forall. intros. apply almostEqual_refl.\nQed.\n\nLemma lookupVarSet_delVarSet_None:\n  forall v vs, lookupVarSet (delVarSet vs v) v = None.\nProof.\n  intros.\n  unfold lookupVarSet,\n  UniqSet.lookupUniqSet,\n  UniqFM.lookupUFM.\n  unfold delVarSet,\n  UniqSet.delOneFromUniqSet,\n  UniqFM.delFromUFM.\n  destruct vs.\n  destruct getUniqSet'.\n  simpl.\n  apply delete_eq.\nQed.\n\nLemma StrongSubset_delVarSet :\n  forall vs1 vs2 v,\n  StrongSubset vs1 vs2 ->\n  StrongSubset (delVarSet vs1 v) (delVarSet vs2 v).\nProof.\n  intros.\n  unfold StrongSubset in *.\n  intro var.\n  specialize (H var).\n  destruct (v == var) eqn:EQv.\n  - rewrite Base.Eq_sym in EQv.\n    erewrite lookupVarSet_eq;\n      [|eassumption].\n    rewrite lookupVarSet_delVarSet_None.\n    trivial.\n  - rewrite lookupVarSet_delVarSet_neq;\n      [|rewrite EQv; auto].\n    destruct (lookupVarSet vs1 var) eqn:Hl; auto.\n    rewrite lookupVarSet_delVarSet_neq;\n      [|rewrite EQv; auto].\n    auto.\nQed.\n\nLemma StrongSubset_delete_fresh :\n  forall vs v,\n  lookupVarSet vs v = None ->\n  StrongSubset vs (delVarSet vs v).\nProof.\n  intros.\n  unfold StrongSubset in *.\n  intro var.\n  destruct (v == var) eqn:EQv.\n  - rewrite Base.Eq_sym in EQv.\n    erewrite lookupVarSet_eq;\n      [|eassumption].\n    rewrite H.\n    trivial.\n  - rewrite lookupVarSet_delVarSet_neq;\n      [|rewrite EQv; auto].\n    destruct (lookupVarSet vs var) eqn:Hl; auto.\n    apply almostEqual_refl.\nQed.\n\nLemma StrongSubset_delVarSetList:\n  forall vs1 vs2 vs,\n  StrongSubset vs1 vs2 ->\n  StrongSubset (delVarSetList vs1 vs) (delVarSetList vs2 vs).\nProof.\n  intros vs1 vs2 vs.\n  generalize dependent vs2.\n  generalize dependent vs1.\n  induction vs;\n    intros vs1 vs2 H; hs_simpl;\n      [assumption|].\n  eapply StrongSubset_delVarSet in H.\n  eauto.\nQed.\n\n(* Respects_StrongSubset *)\n\nDefinition Respects_StrongSubset (P : VarSet -> Prop) : Prop :=\n  forall (vs1 vs2 : VarSet),\n  StrongSubset vs1 vs2 ->\n  P vs1 -> P vs2.\nExisting Class Respects_StrongSubset.\n\nRequire Import Coq.Classes.Morphisms.\nGlobal Instance Respects_StrongSubset_iff_morphism:\n  Proper (pointwise_relation VarSet iff ==> iff) Respects_StrongSubset.\nProof.\n  intros ???.\n  split; intros ?????;\n  unfold pointwise_relation in H;\n  firstorder.\nQed.\n\nLemma Respects_StrongSubset_const:\n  forall P, Respects_StrongSubset (fun _ => P).\nProof. intros ?????. assumption. Qed.\n\nLemma Respects_StrongSubset_and:\n  forall P Q,\n    Respects_StrongSubset P ->\n    Respects_StrongSubset Q ->\n    Respects_StrongSubset (fun x => P x /\\ Q x).\nProof.\n  unfold Respects_StrongSubset in *.\n  intros ????????.\n  firstorder.\nQed.\n\nLemma Respects_StrongSubset_andb:\n  forall (P Q : VarSet -> bool),\n    Respects_StrongSubset (fun x => P x = true) ->\n    Respects_StrongSubset (fun x => Q x = true) ->\n    Respects_StrongSubset (fun x => P x && Q x = true).\nProof.\n  unfold Respects_StrongSubset in *.\n  intros ????????.\n  simpl_bool.\n  firstorder.\nQed.\n\n\nLemma Respects_StrongSubset_forall:\n  forall a (xs : list a) P,\n    Forall (fun x => Respects_StrongSubset (fun vs => P vs x)) xs ->\n    Respects_StrongSubset (fun vs => Forall (P vs) xs).\nProof.\n  unfold Respects_StrongSubset in *.\n  intros.\n  rewrite -> Forall_forall in *.\n  firstorder.\nQed.\n\nLemma Respects_StrongSubset_forallb:\n  forall a (xs : list a) P,\n    Forall (fun x => Respects_StrongSubset (fun vs => P vs x = true)) xs ->\n    Respects_StrongSubset (fun vs => forallb (P vs) xs = true).\nProof.\n  unfold Respects_StrongSubset in *.\n  intros.\n  rewrite -> forallb_forall in *.\n  rewrite -> Forall_forall in *.\n  firstorder.\nQed.\n\n\nLemma Respects_StrongSubset_elemVarSet:\n  forall v,\n  Respects_StrongSubset (fun vs => elemVarSet v vs = true).\nProof.\n  intros ????.\n  simpl_bool; intuition.\n  apply strongSubset_implies_subset in H.\n  set_b_iff; fsetdec.\nQed.\n\nLemma Respects_StrongSubset_delVarSet:\n  forall v P,\n  Respects_StrongSubset (fun vs : VarSet => P vs) ->\n  Respects_StrongSubset (fun vs : VarSet => P (delVarSet vs v)).\nProof.\n  intros v P H vs1 vs2 Hs Hvs1.\n  apply StrongSubset_delVarSet with (v:=v) in Hs.\n  unfold Respects_StrongSubset in H.  \n  apply H in Hs; auto.\nQed.\n\nLemma Respects_StrongSubset_delVarSetList:\n  forall vs2 P,\n  Respects_StrongSubset (fun vs : VarSet => P vs) ->\n  Respects_StrongSubset (fun vs : VarSet => P (delVarSetList vs vs2)).\nProof.\n  intros vs2 P H vs vs' Hs Hvs2.\n  apply StrongSubset_delVarSetList with (vs:=vs2) in Hs.\n  unfold Respects_StrongSubset in H.  \n  apply H in Hs; auto.\nQed.\n\n\nLemma Respects_StrongSubset_extendVarSet:\n  forall v P,\n  Respects_StrongSubset (fun vs : VarSet => P vs) ->\n  Respects_StrongSubset (fun vs : VarSet => P (extendVarSet vs v)).\nProof.\n  intros v P H vs vs' Hs Hvs.\n  apply StrongSubset_extend with (v:=v) in Hs.\n  unfold Respects_StrongSubset in H.\n  apply H in Hs; auto.\nQed.\n\n\nLemma Respects_StrongSubset_extendVarSetList:\n  forall vs' P,\n  Respects_StrongSubset (fun vs : VarSet => P vs) ->\n  Respects_StrongSubset (fun vs : VarSet => P (extendVarSetList vs vs')).\nProof.\n  intros vs P H vs1 vs2 Hs Hvs1.\n  eapply StrongSubset_extendVarSetList with (l:=vs) in Hs.\n  unfold Respects_StrongSubset in H.\n  apply H in Hs; auto.\nQed. \n\nLemma StrongSubset_filterVarSet: \n  forall f1 f2 vs,\n    RespectsVar f1 -> RespectsVar f2 ->\n  (forall v, f1 v = true  -> f2 v = true) ->\n  filterVarSet f1 vs {<=} filterVarSet f2 vs.\nProof.\n  intros.\n  unfold StrongSubset.\n  intros var.\n  destruct (f1 var) eqn:Heq1.\n  - rewrite lookupVarSet_filterVarSet_true; auto.\n    destruct (lookupVarSet vs var) eqn:Hl; [|trivial].\n    rewrite lookupVarSet_filterVarSet_true; auto.\n    rewrite Hl.\n    apply almostEqual_refl.\n  - rewrite lookupVarSet_filterVarSet_false; auto.\nQed.\n\n(* Is this weakening? *)\nLemma weaken:\n  forall {P : VarSet -> Prop} {R : Respects_StrongSubset P},\n  forall {vs1} {vs2},\n  StrongSubset vs1 vs2 ->\n  P vs1 -> P vs2.\nProof. intros. unfold Respects_StrongSubset in R. eapply R; eassumption. Qed.\n\nLemma weakenb:\n  forall {P : VarSet -> bool} {R : Respects_StrongSubset (fun x => P x )},\n  forall {vs1} {vs2},\n  StrongSubset vs1 vs2 ->\n  P vs1  -> P vs2 .\nProof. intros. unfold Respects_StrongSubset in R. eapply R; eassumption. Qed.\n\nLemma Respects_StrongSubset_extendVarSet_ae:\n  forall {P : VarSet -> Prop} {R : Respects_StrongSubset P},\n  forall vs v1 v2,\n  almostEqual v1 v2 ->\n  P (extendVarSet vs v1) <-> P (extendVarSet vs v2).\nProof.\n  intros.\n  split; apply R; (apply StrongSubset_extend_ae;\n    [ reflexivity | assumption + (apply almostEqual_sym; assumption) ]).\nQed.\n\n\nLemma Respects_StrongSubset_extendVarSetList_ae:\n  forall {P : VarSet -> Prop} {R : Respects_StrongSubset P},\n  forall vs vs1 vs2,\n  Forall2 almostEqual vs1 vs2 ->\n  P (extendVarSetList vs vs1) <-> P (extendVarSetList vs vs2).\nProof.\n  split; apply R; apply StrongSubset_extendVarSetList_ae.\n  * assumption.\n  * reflexivity.\n  * clear -H.\n    induction H; constructor.\n    + apply almostEqual_sym; assumption.\n    + assumption.\n  * reflexivity.\nQed.\n\n\n\n\n\n(* A list of variables is fresh for a given varset when \n   any variable with a unique found in the list is not found \n   in the set. i.e. this is list membership using GHC.Base.==\n   for vars. \n*)\n\nDefinition freshList (vars: list Var) (vs :VarSet) :=\n  (forall (v:Var), Foldable.elem v vars  -> \n              lookupVarSet vs v = None).\n\nLemma freshList_nil : forall v,  freshList nil v.\nProof.\n  unfold freshList. intros v v0 H. inversion H.\nQed.\n\nLemma freshList_cons : forall (x:Var) l (v:VarSet),  \n    lookupVarSet v x = None /\\ freshList l v <-> freshList (x :: l) v.\nProof.\n  unfold freshList. intros. \n  split. \n  + intros [? ?] ? ?.\n    rewrite elem_cons in H1.\n    destruct (orb_prop _ _ H1) as [EQ|IN].\n    rewrite -> lookupVarSet_eq with (v2 := x); auto.\n    eauto.\n  + intros. split.\n    eapply H. \n    rewrite elem_cons.\n    eapply orb_true_intro.\n    left. eapply Base.Eq_refl.\n    intros.\n    eapply H.\n    rewrite elem_cons.\n    eapply orb_true_intro.\n    right. auto.\nQed.\n\n\nLemma freshList_app :\n  forall v l1 l2, freshList (l1 ++ l2) v <-> freshList l1 v /\\ freshList l2 v.\nProof.\n  intros.\n  induction l1; simpl.\n  split.\n  intros. split. apply freshList_nil. auto.\n  tauto.\n  split.\n  + intros.\n    rewrite <- freshList_cons in *. tauto. \n  + intros.\n    rewrite <- freshList_cons in *. tauto.\nQed.\n    \nLemma StrongSubset_extendVarSet_fresh : \n  forall vs var, lookupVarSet vs var = None ->\n            StrongSubset vs (extendVarSet vs var).\nProof.\n  apply StrongSubset_extend_fresh.\nQed.\n\nLemma StrongSubset_extendVarSetList_fresh : \n  forall vs vars, freshList vars vs ->\n             StrongSubset vs (extendVarSetList vs vars).\nProof.\n  intros.\n  apply StrongSubset_extendList_fresh.\n  apply disjointVarSet_mkVarSet.\n  induction vars; auto.\n  apply freshList_cons in H as [H1 H2].\n  apply Forall_cons; auto.\n  apply lookupVarSet_None_elemVarSet.\n  assumption.\nQed.\n\n\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/ghc/theories/VarSet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.28611047733270767}}
{"text": "(***************************************************************)\n(* Basci Coq lib                                               *)\n(***************************************************************)\nRequire Import Omega.\nRequire Export ZArith.\nRequire Export Znumtheory.\nRequire Export List.\nRequire Export Bool.\n\n(* *********************************************************************** *)\n(** * The [skip] tactic from Stephanie Weirich and Brian Andemir of UPenn  *)\n\n(** The [skip] tactic will prove any goal, since we assert below that\n    [False] is provable.  This is a useful technique for skipping over\n    troublesome parts of proofs.  In a complete development, one would\n    comment out the [skip] axiom and tactic.\n\n    In the exercises below, [skip] lets us give partial proofs by\n    using it as a placeholder for locations in the proof script where\n    the reader should fill in the proof.\n*)\n(* Axiom false_false : forall P, P. *)\n(* Ltac skip := apply false_false. *)\n(* *)\n\n(** Section 1: optionT and pairT **)\nAxiom extensionality:\n  forall (A B: Set) (f g : A -> B),\n  (forall x, f x = g x) -> f = g.\n\nInductive OptionT (T : Type) : Type :=\n    NoneT1 : OptionT T\n  | SomeT1 : T -> OptionT T.\n\nInductive optionT (A : Type) : Type :=\n  | SomeT : A -> optionT A\n  | NoneT : optionT A.\n\nImplicit Arguments SomeT [A].\nImplicit Arguments NoneT [A].\n\nNotation opt_predT :=\n  (fun opt:optionT _ => \n    fun f =>\n      match opt with\n\t| SomeT t => f t\n\t| NoneT => False\n      end).\n\nNotation optpT :=\n  (fun f => fun opt:optionT _ => \n    match opt with\n      | SomeT t => f t\n      | NoneT => False\n    end).\n\nNotation optgT :=\n  (fun f => fun opt:optionT _ =>\n    fun t' =>\n      match opt with\n        | SomeT t => f t t'\n        | NoneT => False\n      end).\n\nNotation opt_predT2 :=\n  (fun opt:optionT _ => \n    fun opt':optionT _ => \n      fun f =>\n\tmatch opt, opt' with\n\t  | SomeT t, SomeT t' => f t t'\n\t  | _, _ => False\n\tend).\n\nInductive prodT (A : Set) (B : Type) : Type :=\n    pairT : A -> B -> prodT A B.\nImplicit Arguments pairT [A B].\n\nNotation \"( x , y , .. , z )\" :=\n  (pairT .. (pairT x y) .. z) : t_type_scope.\n\n(** Section 2: Tactics **)\n(***************************************************************)\n\nLtac hypreplace H y :=\n  let H' := fresh in\n    (assert (H' := y); try (clear H; rename H' into H)).\n\nLtac hypreplace2 H y Hn:=\n  let H' := fresh in\n    (assert (H' := y); try (clear H; rename H' into Hn)).\n\nTactic Notation \"substH\" hyp (H) :=\n  match goal with\n    | |- ?a -> ?b => clear H; intro H\n    | |- _ => fail 1 \"goal must be 'A -> B'.\"\n  end.\n\nTactic Notation \"substH\" hyp (H) \"with\" constr (t) := \n  hypreplace H t.\n\nTactic Notation \"substH\" hyp (H) \"with\" constr (t) \"into\" ident (Hn) := \n  hypreplace2 H t Hn.\n\nTactic Notation \"bool_destruct\" hyp (H) \"as\" simple_intropattern (pat) :=\n  let H0 := fresh \"H\" in\n    (rename H into H0;\n    match type of (H0) with\n      | (andb ?a ?b = true) => \n        destruct (andb_prop a b H0) as pat; clear H0\n      | (orb ?a ?b = true) =>\n        destruct (orb_prop a b H0) as pat; clear H0\n      | _ => fail \"not destructable\" \n    end).\n\n\nTactic Notation \"destructH\" hyp (H) \"with\" constr (t) :=\n  destruct t; clear H.\n\nTactic Notation \"destructH\" hyp (H) \"with\" constr (t)\n  \"as\" simple_intropattern (p) :=\n  destruct t as p; clear H.\n  \nTactic Notation \"discri\" :=\n  match goal with\n    | H : ?a <> ?a |- _ => \n      elimtype False; apply H; reflexivity\n    | |- _ -> _ => intros; discriminate\n    | H : False |- _ => destruct H\n    | _ => discriminate\n  end.\n\nTactic Notation \"gen_clear\" hyp (H) :=\n  generalize H; clear H.\n\nTactic Notation \"gen_clear\" hyp (H1) hyp (H2) :=\n  generalize H1 H2; clear H1 H2.\n\nTactic Notation \"gen_clear\" \n  hyp (H1) hyp (H2) hyp (H3) :=\n  generalize H1 H2 H3; clear H1 H2 H3.\n\nTactic Notation \"gen_clear\" \n  hyp (H1) hyp (H2) hyp (H3) hyp (H4) :=\n  generalize H1 H2 H3 H4; \n    clear H1 H2 H3 H4.\n\nTactic Notation \"gen_clear\" \n  hyp (H1) hyp (H2) hyp (H3) \n  hyp (H4) hyp (H5):=\n  generalize H1 H2 H3 H4 H5; \n    clear H1 H2 H3 H4 H5.\n\nTactic Notation \"gen_clear\" \n  hyp (H1) hyp (H2) hyp (H3) \n  hyp (H4) hyp (H5) hyp (H6):=\n  generalize H1 H2 H3 H4 H5 H6; \n    clear H1 H2 H3 H4 H5 H6.\n\nTactic Notation \"split_l\" :=\n  split; [trivial | idtac].\n\nTactic Notation \"split_r\" :=\n  split; [idtac | trivial ].\n\nTactic Notation \"split_lr\" :=\n  split; [trivial | trivial ].\n\nTactic Notation \"split_l\" \"with\" constr (t) :=\n  split; [apply t | idtac].\n\nTactic Notation \"split_r\" \"with\" constr (t) :=\n  split; [idtac | apply t ].\n\nTactic Notation \"split_l\" \"by\" tactic (tac) :=\n  split; [tac | idtac ].\n\nTactic Notation \"split_r\" \"by\" tactic (tac) :=\n  split; [idtac | tac ].\n\nTactic Notation \"split_l_clear\" \"with\" hyp (H) :=\n  split; [apply H | clear H].\n\nTactic Notation \"split_r_clear\" \"with\" hyp (H) :=\n  split; [clear H | apply H ].\n\nLemma and_sym : forall (A B : Prop), A /\\ B -> B /\\ A.\nProof. intros  A B [HA HB]; split; trivial. Qed.\nImplicit Arguments and_sym [A B].\n\nLtac rsplit := apply and_sym; split.\n\nLemma and_sym_rr : forall A B C : Prop, A /\\ B /\\ C -> B /\\ C /\\ A.\nProof.\n  tauto.\nQed.\n\nLtac rrsplit := apply and_sym_rr; split.\n\nTactic Notation \"inj_hyp\" hyp (H) :=\n  injection H; clear H; intro H.\n\nTactic Notation \"rew_clear\" hyp (H) :=\n  rewrite H; clear H.\n\nTactic Notation \"injection\" hyp (H) :=\n  injection H.\n\nTactic Notation \"injection\" hyp (H) \"as\" \n  simple_intropattern (pat) :=\n  injection H; intros pat.\n\nTactic Notation \"injsubst\" ident (id) \"in\" hyp (H) :=\n  injection H; intro; subst id; clear H.\n\nLtac InvertAll :=\n  repeat\n    match goal with\n      | H: _ /\\ _ |- _ => inversion_clear H\n      | H: ex _   |- _ => inversion_clear H\n    end.\n\nLtac arith_replace t1 t2 := \n  (replace t1 with t2; fail \"error\") ||\n    (replace t1 with t2; [trivial | try omega; fail \"error\" ]).\n\nLtac arith_replaceH H t1 t2 := \n  (replace t1 with t2 in H; fail \"error\") ||\n    (replace t1 with t2 in H; [trivial | try omega; fail \"error\" ]).\n\nTactic Notation \"arith_rep\" constr(t1) \"with\" constr (t2) :=\n  arith_replace t1 t2.\n\nTactic Notation \"arith_rep\" constr(t1) \"with\" constr (t2) \"in\" hyp (H):=\n  arith_replaceH H t1 t2.\n\n\nLtac clearall := \n  match goal with \n    | H : _ |- _ =>\n      (clear H || (generalize H; clear H)); clearall\n    | _ => intros\n  end.\n\nLtac clearall_arith := \n  match goal with \n    | H : ?a > ?b |- _ => (generalize H; clear H); clearall_arith\n    | H : ?a >= ?b |- _ => (generalize H; clear H); clearall_arith\n    | H : ?a < ?b |- _ => (generalize H; clear H); clearall_arith\n    | H : ?a <= ?b |- _ => (generalize H; clear H); clearall_arith\n    | H : ?a = ?b |- _ => \n      match type of a with\n        | nat => (generalize H; clear H); clearall_arith\n        | _ => (clear H || (generalize H; clear H)); clearall_arith\n      end\n    | H : _ |- _ =>\n      (clear H || (generalize H; clear H)); clearall_arith\n    | _ => intros\n  end.\n\n\n\n\n(** * Useful tactics *)\n\nLtac inv H := inversion H; clear H; subst.\n\nLtac predSpec pred predspec x y :=\n  generalize (predspec x y); case (pred x y); intro.\n\nLtac caseEq name :=\n  generalize (refl_equal name); pattern name at -1 in |- *; case name.\n\nLtac destructEq name :=\n  destruct name eqn:?.\n\nLtac decEq :=\n  match goal with\n  | [ |- _ = _ ] => f_equal\n  | [ |- (?X ?A <> ?X ?B) ] =>\n      cut (A <> B); [intro; congruence | try discriminate]\n  end.\n\nLtac byContradiction :=\n  cut False; [contradiction|idtac].\n\nLtac omegaContradiction :=\n  cut False; [contradiction|omega].\n\nLemma modusponens: forall (P Q: Prop), P -> (P -> Q) -> Q.\nProof. auto. Qed.\n\nLtac exploit x :=\n    refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _ _) _)\n || refine (modusponens _ _ (x _ _ _) _)\n || refine (modusponens _ _ (x _ _) _)\n || refine (modusponens _ _ (x _) _).\n\n(** * Definitions and theorems over the type [positive] *)\n\nDefinition peq: forall (x y: positive), {x = y} + {x <> y} := Pos.eq_dec.\nGlobal Opaque peq.\n\nLemma peq_true:\n  forall (A: Type) (x: positive) (a b: A), (if peq x x then a else b) = a.\nProof.\n  intros. case (peq x x); intros.\n  auto.\n  elim n; auto.\nQed.\n\nLemma peq_false:\n  forall (A: Type) (x y: positive) (a b: A), x <> y -> (if peq x y then a else b) = b.\nProof.\n  intros. case (peq x y); intros.\n  elim H; auto.\n  auto.\nQed.  \n\nDefinition Plt: positive -> positive -> Prop := Pos.lt.\n\nLemma Plt_ne:\n  forall (x y: positive), Plt x y -> x <> y.\nProof.\n  unfold Plt; intros. red; intro. subst y. eelim Pos.lt_irrefl; eauto. \nQed.\nHint Resolve Plt_ne: coqlib.\n\nLemma Plt_trans:\n  forall (x y z: positive), Plt x y -> Plt y z -> Plt x z.\nProof (Pos.lt_trans).\n\nLemma Plt_succ:\n  forall (x: positive), Plt x (Psucc x).\nProof.\n  unfold Plt; intros. apply Pos.lt_succ_r. apply Pos.le_refl. \nQed.\nHint Resolve Plt_succ: coqlib.\n\nLemma Plt_trans_succ:\n  forall (x y: positive), Plt x y -> Plt x (Psucc y).\nProof.\n  intros. apply Plt_trans with y. assumption. apply Plt_succ.\nQed.\nHint Resolve Plt_succ: coqlib.\n\nLemma Plt_succ_inv:\n  forall (x y: positive), Plt x (Psucc y) -> Plt x y \\/ x = y.\nProof.\n  unfold Plt; intros. rewrite Pos.lt_succ_r in H. \n  apply Pos.le_lteq; auto.\nQed.\n\nDefinition plt (x y: positive) : {Plt x y} + {~ Plt x y}.\nProof.\n  unfold Plt, Pos.lt; intros. destruct (Pos.compare x y).\n  - right; congruence.\n  - left; auto.\n  - right; congruence.\nDefined.\nGlobal Opaque plt.\n\nDefinition Ple: positive -> positive -> Prop := Pos.le.\n\nLemma Ple_refl: forall (p: positive), Ple p p.\nProof (Pos.le_refl).\n\nLemma Ple_trans: forall (p q r: positive), Ple p q -> Ple q r -> Ple p r.\nProof (Pos.le_trans).\n\nLemma Plt_Ple: forall (p q: positive), Plt p q -> Ple p q.\nProof (Pos.lt_le_incl).\n\nLemma Ple_succ: forall (p: positive), Ple p (Psucc p).\nProof.\n  intros. apply Plt_Ple. apply Plt_succ.\nQed.\n\nLemma Plt_Ple_trans:\n  forall (p q r: positive), Plt p q -> Ple q r -> Plt p r.\nProof (Pos.lt_le_trans).\n\nLemma Plt_strict: forall p, ~ Plt p p.\nProof (Pos.lt_irrefl).\n\nHint Resolve Ple_refl Plt_Ple Ple_succ Plt_strict: coqlib.\n\nLtac xomega := unfold Plt, Ple in *; zify; omega.\nLtac xomegaContradiction := exfalso; xomega.\n\n(** Peano recursion over positive numbers. *)\n\nSection POSITIVE_ITERATION.\n\nLemma Plt_wf: well_founded Plt.\nProof.\n  apply well_founded_lt_compat with nat_of_P.\n  intros. apply nat_of_P_lt_Lt_compare_morphism. exact H.\nQed.\n\nVariable A: Type.\nVariable v1: A.\nVariable f: positive -> A -> A.\n\nLemma Ppred_Plt:\n  forall x, x <> xH -> Plt (Ppred x) x.\nProof.\n  intros. elim (Psucc_pred x); intro. contradiction.\n  set (y := Ppred x) in *. rewrite <- H0. apply Plt_succ.\nQed.\n\nLet iter (x: positive) (P: forall y, Plt y x -> A) : A :=\n  match peq x xH with\n  | left EQ => v1\n  | right NOTEQ => f (Ppred x) (P (Ppred x) (Ppred_Plt x NOTEQ))\n  end.\n\nDefinition positive_rec : positive -> A :=\n  Fix Plt_wf (fun _ => A) iter.\n\nLemma unroll_positive_rec:\n  forall x,\n  positive_rec x = iter x (fun y _ => positive_rec y).\nProof.\n  unfold positive_rec. apply (Fix_eq Plt_wf (fun _ => A) iter).\n  intros. unfold iter. case (peq x 1); intro. auto. decEq. apply H.\nQed.\n\nLemma positive_rec_base:\n  positive_rec 1%positive = v1.\nProof.\n  rewrite unroll_positive_rec. unfold iter. case (peq 1 1); intro.\n  auto. elim n; auto.\nQed.\n\nLemma positive_rec_succ:\n  forall x, positive_rec (Psucc x) = f x (positive_rec x).\nProof.\n  intro. rewrite unroll_positive_rec. unfold iter.\n  case (peq (Psucc x) 1); intro.\n  destruct x; simpl in e; discriminate.\n  rewrite Ppred_succ. auto.\nQed.\n\nLemma positive_Peano_ind:\n  forall (P: positive -> Prop),\n  P xH ->\n  (forall x, P x -> P (Psucc x)) ->\n  forall x, P x.\nProof.\n  intros.\n  apply (well_founded_ind Plt_wf P).\n  intros. \n  case (peq x0 xH); intro.\n  subst x0; auto.\n  elim (Psucc_pred x0); intro. contradiction. rewrite <- H2.\n  apply H0. apply H1. apply Ppred_Plt. auto. \nQed.\n\nEnd POSITIVE_ITERATION.\n\n(** * Definitions and theorems over the type [Z] *)\n\nDefinition zeq: forall (x y: Z), {x = y} + {x <> y} := Z.eq_dec.\n\nLemma zeq_true:\n  forall (A: Type) (x: Z) (a b: A), (if zeq x x then a else b) = a.\nProof.\n  intros. case (zeq x x); intros.\n  auto.\n  elim n; auto.\nQed.\n\nLemma zeq_false:\n  forall (A: Type) (x y: Z) (a b: A), x <> y -> (if zeq x y then a else b) = b.\nProof.\n  intros. case (zeq x y); intros.\n  elim H; auto.\n  auto.\nQed.  \n\nOpen Scope Z_scope.\n\nDefinition zlt: forall (x y: Z), {x < y} + {x >= y} := Z_lt_dec.\n\nLemma zlt_true:\n  forall (A: Type) (x y: Z) (a b: A), \n  x < y -> (if zlt x y then a else b) = a.\nProof.\n  intros. case (zlt x y); intros.\n  auto.\n  omegaContradiction.\nQed.\n\nLemma zlt_false:\n  forall (A: Type) (x y: Z) (a b: A), \n  x >= y -> (if zlt x y then a else b) = b.\nProof.\n  intros. case (zlt x y); intros.\n  omegaContradiction.\n  auto.\nQed.\n\nDefinition zle: forall (x y: Z), {x <= y} + {x > y} := Z_le_gt_dec.\n\nLemma zle_true:\n  forall (A: Type) (x y: Z) (a b: A), \n  x <= y -> (if zle x y then a else b) = a.\nProof.\n  intros. case (zle x y); intros.\n  auto.\n  omegaContradiction.\nQed.\n\nLemma zle_false:\n  forall (A: Type) (x y: Z) (a b: A), \n  x > y -> (if zle x y then a else b) = b.\nProof.\n  intros. case (zle x y); intros.\n  omegaContradiction.\n  auto.\nQed.\n\n(** Properties of powers of two. *)\n\nLemma two_power_nat_O : two_power_nat O = 1.\nProof. reflexivity. Qed.\n\nLemma two_power_nat_pos : forall n : nat, two_power_nat n > 0.\nProof.\n  induction n. rewrite two_power_nat_O. omega.\n  rewrite two_power_nat_S. omega.\nQed.\n\nLemma two_power_nat_two_p:\n  forall x, two_power_nat x = two_p (Z_of_nat x).\nProof.\n  induction x. auto. \n  rewrite two_power_nat_S. rewrite inj_S. rewrite two_p_S. omega. omega.\nQed.\n\nLemma two_p_monotone:\n  forall x y, 0 <= x <= y -> two_p x <= two_p y.\nProof.\n  intros.\n  replace (two_p x) with (two_p x * 1) by omega. \n  replace y with (x + (y - x)) by omega.\n  rewrite two_p_is_exp; try omega.\n  apply Zmult_le_compat_l.\n  assert (two_p (y - x) > 0). apply two_p_gt_ZERO. omega. omega.\n  assert (two_p x > 0). apply two_p_gt_ZERO. omega. omega.\nQed.\n\nLemma two_p_monotone_strict:\n  forall x y, 0 <= x < y -> two_p x < two_p y.\nProof.\n  intros. assert (two_p x <= two_p (y - 1)). apply two_p_monotone; omega.\n  assert (two_p (y - 1) > 0). apply two_p_gt_ZERO. omega.\n  replace y with (Zsucc (y - 1)) by omega. rewrite two_p_S. omega. omega.\nQed.\n\nLemma two_p_strict:\n  forall x, x >= 0 -> x < two_p x.\nProof.\n  intros x0 GT. pattern x0. apply natlike_ind.\n  simpl. omega.\n  intros. rewrite two_p_S; auto. generalize (two_p_gt_ZERO x H). omega. \n  omega.\nQed.\n\nLemma two_p_strict_2:\n  forall x, x >= 0 -> 2 * x - 1 < two_p x.\nProof.\n  intros. assert (x = 0 \\/ x - 1 >= 0) by omega. destruct H0.\n  subst. vm_compute. auto.\n  replace (two_p x) with (2 * two_p (x - 1)).\n  generalize (two_p_strict _ H0). omega. \n  rewrite <- two_p_S. decEq. omega. omega.\nQed.\n\n(** Properties of [Zmin] and [Zmax] *)\n\nLemma Zmin_spec:\n  forall x y, Zmin x y = if zlt x y then x else y.\nProof.\n  intros. case (zlt x y); unfold Zlt, Zge; intro z.\n  unfold Zmin. rewrite z. auto.\n  unfold Zmin. caseEq (x ?= y); intro. \n  apply Zcompare_Eq_eq. auto.\n  contradiction.\n  reflexivity.\nQed.\n\nLemma Zmax_spec:\n  forall x y, Zmax x y = if zlt y x then x else y.\nProof.\n  intros. case (zlt y x); unfold Zlt, Zge; intro z.\n  unfold Zmax. rewrite <- (Zcompare_antisym y x).\n  rewrite z. simpl. auto.\n  unfold Zmax. rewrite <- (Zcompare_antisym y x).\n  caseEq (y ?= x); intro; simpl.\n  symmetry. apply Zcompare_Eq_eq. auto.\n  contradiction. reflexivity.\nQed.\n\nLemma Zmax_bound_l:\n  forall x y z, x <= y -> x <= Zmax y z.\nProof.\n  intros. generalize (Zmax1 y z). omega.\nQed.\nLemma Zmax_bound_r:\n  forall x y z, x <= z -> x <= Zmax y z.\nProof.\n  intros. generalize (Zmax2 y z). omega.\nQed.\n\n(** Properties of Euclidean division and modulus. *)\n\nLemma Zdiv_small:\n  forall x y, 0 <= x < y -> x / y = 0.\nProof.\n  intros. assert (y > 0). omega. \n  assert (forall a b,\n    0 <= a < y ->\n    0 <= y * b + a < y ->\n    b = 0).\n  intros. \n  assert (b = 0 \\/ b > 0 \\/ (-b) > 0). omega.\n  elim H3; intro.\n  auto.\n  elim H4; intro.\n  assert (y * b >= y * 1). apply Zmult_ge_compat_l. omega. omega. \n  omegaContradiction. \n  assert (y * (-b) >= y * 1). apply Zmult_ge_compat_l. omega. omega.\n  rewrite <- Zopp_mult_distr_r in H6. omegaContradiction.\n  apply H1 with (x mod y). \n  apply Z_mod_lt. auto.\n  rewrite <- Z_div_mod_eq. auto. auto.\nQed.\n\nLemma Zmod_small:\n  forall x y, 0 <= x < y -> x mod y = x.\nProof.\n  intros. assert (y > 0). omega.\n  generalize (Z_div_mod_eq x y H0). \n  rewrite (Zdiv_small x y H). omega.\nQed.\n\nLemma Zmod_unique:\n  forall x y a b,\n  x = a * y + b -> 0 <= b < y -> x mod y = b.\nProof.\n  intros. subst x. rewrite Zplus_comm. \n  rewrite Z_mod_plus. apply Zmod_small. auto. omega.\nQed.\n\nLemma Zdiv_unique:\n  forall x y a b,\n  x = a * y + b -> 0 <= b < y -> x / y = a.\nProof.\n  intros. subst x. rewrite Zplus_comm.\n  rewrite Z_div_plus. rewrite (Zdiv_small b y H0). omega. omega.\nQed.\n\nLemma Zdiv_Zdiv:\n  forall a b c,\n  b > 0 -> c > 0 -> (a / b) / c = a / (b * c).\nProof.\n  intros.\n  generalize (Z_div_mod_eq a b H). generalize (Z_mod_lt a b H). intros.\n  generalize (Z_div_mod_eq (a/b) c H0). generalize (Z_mod_lt (a/b) c H0). intros.\n  set (q1 := a / b) in *. set (r1 := a mod b) in *.\n  set (q2 := q1 / c) in *. set (r2 := q1 mod c) in *.\n  symmetry. apply Zdiv_unique with (r2 * b + r1). \n  rewrite H2. rewrite H4. ring.\n  split. \n  assert (0 <= r2 * b). apply Zmult_le_0_compat. omega. omega. omega.\n  assert ((r2 + 1) * b <= c * b).\n  apply Zmult_le_compat_r. omega. omega. \n  replace ((r2 + 1) * b) with (r2 * b + b) in H5 by ring.\n  replace (c * b) with (b * c) in H5 by ring.\n  omega.\nQed.\n\nLemma Zmult_le_compat_l_neg :\n  forall n m p:Z, n >= m -> p <= 0 -> p * n <= p * m.\nProof.\n  intros.\n  assert ((-p) * n >= (-p) * m). apply Zmult_ge_compat_l. auto. omega.\n  replace (p * n) with (- ((-p) * n)) by ring.\n  replace (p * m) with (- ((-p) * m)) by ring.\n  omega.\nQed.\n\nLemma Zdiv_interval_1:\n  forall lo hi a b,\n  lo <= 0 -> hi > 0 -> b > 0 ->\n  lo * b <= a < hi * b ->\n  lo <= a/b < hi.\nProof.\n  intros. \n  generalize (Z_div_mod_eq a b H1). generalize (Z_mod_lt a b H1). intros.\n  set (q := a/b) in *. set (r := a mod b) in *.\n  split.\n  assert (lo < (q + 1)).\n  apply Zmult_lt_reg_r with b. omega.  \n  apply Zle_lt_trans with a. omega. \n  replace ((q + 1) * b) with (b * q + b) by ring.\n  omega.\n  omega.\n  apply Zmult_lt_reg_r with b. omega. \n  replace (q * b) with (b * q) by ring.\n  omega.\nQed.\n\nLemma Zdiv_interval_2:\n  forall lo hi a b,\n  lo <= a <= hi -> lo <= 0 -> hi >= 0 -> b > 0 ->\n  lo <= a/b <= hi.\nProof.\n  intros.\n  assert (lo <= a / b < hi+1).\n  apply Zdiv_interval_1. omega. omega. auto.\n  assert (lo * b <= lo * 1). apply Zmult_le_compat_l_neg. omega. omega. \n  replace (lo * 1) with lo in H3 by ring.\n  assert ((hi + 1) * 1 <= (hi + 1) * b). apply Zmult_le_compat_l. omega. omega.\n  replace ((hi + 1) * 1) with (hi + 1) in H4 by ring.\n  omega.\n  omega.\nQed.\n\nLemma Zmod_recombine:\n  forall x a b,\n  a > 0 -> b > 0 ->\n  x mod (a * b) = ((x/b) mod a) * b + (x mod b).\nProof.\n  intros. \n  set (xb := x/b). \n  apply Zmod_unique with (xb/a).\n  generalize (Z_div_mod_eq x b H0); fold xb; intro EQ1.\n  generalize (Z_div_mod_eq xb a H); intro EQ2.\n  rewrite EQ2 in EQ1. \n  eapply trans_eq. eexact EQ1. ring.\n  generalize (Z_mod_lt x b H0). intro. \n  generalize (Z_mod_lt xb a H). intro.\n  assert (0 <= xb mod a * b <= a * b - b).\n    split. apply Zmult_le_0_compat; omega.\n    replace (a * b - b) with ((a - 1) * b) by ring.\n    apply Zmult_le_compat; omega. \n  omega.\nQed.\n\n(** Properties of divisibility. *)\n\nLemma Zdivides_trans:\n  forall x y z, (x | y) -> (y | z) -> (x | z).\nProof.\n  intros x y z [a A] [b B]; subst. exists (a*b); ring.\nQed.\n\nDefinition Zdivide_dec:\n  forall (p q: Z), p > 0 -> { (p|q) } + { ~(p|q) }.\nProof.\n  intros. destruct (zeq (Zmod q p) 0).\n  left. exists (q / p). \n  transitivity (p * (q / p) + (q mod p)). apply Z_div_mod_eq; auto.\n  transitivity (p * (q / p)). omega. ring.\n  right; red; intros. elim n. apply Z_div_exact_1; auto. \n  inv H0. rewrite Z_div_mult; auto. ring.\nDefined.\nGlobal Opaque Zdivide_dec.\n\nLemma Zdivide_interval:\n  forall a b c,\n  0 < c -> 0 <= a < b -> (c | a) -> (c | b) -> 0 <= a <= b - c.\nProof.\n  intros. destruct H1 as [x EQ1]. destruct H2 as [y EQ2]. subst. destruct H0.\n  split. omega. exploit Zmult_lt_reg_r; eauto. intros. \n  replace (y * c - c) with ((y - 1) * c) by ring.\n  apply Zmult_le_compat_r; omega.\nQed.\n\n(** Conversion from [Z] to [nat]. *)\n\nDefinition nat_of_Z: Z -> nat := Z.to_nat.\n\nLemma nat_of_Z_of_nat:\n  forall n, nat_of_Z (Z_of_nat n) = n.\nProof.\n  exact Nat2Z.id.\nQed.\n\nLemma nat_of_Z_max:\n  forall z, Z_of_nat (nat_of_Z z) = Zmax z 0.\nProof.\n  intros. unfold Zmax. destruct z; simpl; auto. \n  change (Z.of_nat (Z.to_nat (Zpos p)) = Zpos p).\n  apply Z2Nat.id. compute; intuition congruence. \nQed.\n\nLemma nat_of_Z_eq:\n  forall z, z >= 0 -> Z_of_nat (nat_of_Z z) = z.\nProof.\n  unfold nat_of_Z; intros. apply Z2Nat.id. omega.\nQed.\n\nLemma nat_of_Z_neg:\n  forall n, n <= 0 -> nat_of_Z n = O.\nProof.\n  destruct n; unfold Zle; simpl; auto. congruence.\nQed.\n\nLemma nat_of_Z_plus:\n  forall p q,\n  p >= 0 -> q >= 0 ->\n  nat_of_Z (p + q) = (nat_of_Z p + nat_of_Z q)%nat.\nProof.\n  unfold nat_of_Z; intros. apply Z2Nat.inj_add; omega. \nQed.\n\n\n(** Alignment: [align n amount] returns the smallest multiple of [amount]\n  greater than or equal to [n]. *)\n\nDefinition align (n: Z) (amount: Z) :=\n  ((n + amount - 1) / amount) * amount.\n\nLemma align_le: forall x y, y > 0 -> x <= align x y.\nProof.\n  intros. unfold align. \n  generalize (Z_div_mod_eq (x + y - 1) y H). intro.\n  replace ((x + y - 1) / y * y) \n     with ((x + y - 1) - (x + y - 1) mod y).\n  generalize (Z_mod_lt (x + y - 1) y H). omega.\n  rewrite Zmult_comm. omega.\nQed.\n\nLemma align_divides: forall x y, y > 0 -> (y | align x y).\nProof.\n  intros. unfold align. apply Zdivide_factor_l. \nQed.\n\n(** * Definitions and theorems on the data types [option], [sum] and [list] *)\n\nSet Implicit Arguments.\n\n(** Comparing option types. *)\n\nDefinition option_eq (A: Type) (eqA: forall (x y: A), {x=y} + {x<>y}):\n  forall (x y: option A), {x=y} + {x<>y}.\nProof. decide equality. Defined.\nGlobal Opaque option_eq.\n\n(** Mapping a function over an option type. *)\n\nDefinition option_map (A B: Type) (f: A -> B) (x: option A) : option B :=\n  match x with\n  | None => None\n  | Some y => Some (f y)\n  end.\n\n(** Mapping a function over a sum type. *)\n\nDefinition sum_left_map (A B C: Type) (f: A -> B) (x: A + C) : B + C :=\n  match x with\n  | inl y => inl C (f y)\n  | inr z => inr B z\n  end.\n\n(** Properties of [List.nth] (n-th element of a list). *)\n\nHint Resolve in_eq in_cons: coqlib.\n\nLemma nth_error_in:\n  forall (A: Type) (n: nat) (l: list A) (x: A),\n  List.nth_error l n = Some x -> In x l.\nProof.\n  induction n; simpl.\n   destruct l; intros.\n    discriminate.\n    injection H; intro; subst a. apply in_eq.\n   destruct l; intros.\n    discriminate.\n    apply in_cons. auto.\nQed.\nHint Resolve nth_error_in: coqlib.\n\nLemma nth_error_nil:\n  forall (A: Type) (idx: nat), nth_error (@nil A) idx = None.\nProof.\n  induction idx; simpl; intros; reflexivity.\nQed.\nHint Resolve nth_error_nil: coqlib.\n\n(** Compute the length of a list, with result in [Z]. *)\n\nFixpoint list_length_z_aux (A: Type) (l: list A) (acc: Z) {struct l}: Z :=\n  match l with\n  | nil => acc\n  | hd :: tl => list_length_z_aux tl (Zsucc acc)\n  end.\n\nRemark list_length_z_aux_shift:\n  forall (A: Type) (l: list A) n m,\n  list_length_z_aux l n = list_length_z_aux l m + (n - m).\nProof.\n  induction l; intros; simpl.\n  omega.\n  replace (n - m) with (Zsucc n - Zsucc m) by omega. auto.\nQed.\n\nDefinition list_length_z (A: Type) (l: list A) : Z :=\n  list_length_z_aux l 0.\n\nLemma list_length_z_cons:\n  forall (A: Type) (hd: A) (tl: list A),\n  list_length_z (hd :: tl) = list_length_z tl + 1.\nProof.\n  intros. unfold list_length_z. simpl.\n  rewrite (list_length_z_aux_shift tl 1 0). omega. \nQed.\n\nLemma list_length_z_pos:\n  forall (A: Type) (l: list A),\n  list_length_z l >= 0.\nProof.\n  induction l; simpl. unfold list_length_z; simpl. omega. \n  rewrite list_length_z_cons. omega.\nQed.\n\nLemma list_length_z_map:\n  forall (A B: Type) (f: A -> B) (l: list A),\n  list_length_z (map f l) = list_length_z l.\nProof.\n  induction l. reflexivity. simpl. repeat rewrite list_length_z_cons. congruence.\nQed. \n\n(** Extract the n-th element of a list, as [List.nth_error] does,\n    but the index [n] is of type [Z]. *)\n\nFixpoint list_nth_z (A: Type) (l: list A) (n: Z) {struct l}: option A :=\n  match l with\n  | nil => None\n  | hd :: tl => if zeq n 0 then Some hd else list_nth_z tl (Zpred n)\n  end.\n\nLemma list_nth_z_in:\n  forall (A: Type) (l: list A) n x,\n  list_nth_z l n = Some x -> In x l.\nProof.\n  induction l; simpl; intros. \n  congruence.\n  destruct (zeq n 0). left; congruence. right; eauto.\nQed.\n\nLemma list_nth_z_map:\n  forall (A B: Type) (f: A -> B) (l: list A) n,\n  list_nth_z (List.map f l) n = option_map f (list_nth_z l n).\nProof.\n  induction l; simpl; intros.\n  auto.\n  destruct (zeq n 0). auto. eauto.\nQed.\n\nLemma list_nth_z_range:\n  forall (A: Type) (l: list A) n x,\n  list_nth_z l n = Some x -> 0 <= n < list_length_z l.\nProof.\n  induction l; simpl; intros.\n  discriminate.\n  rewrite list_length_z_cons. destruct (zeq n 0).\n  generalize (list_length_z_pos l); omega.\n  exploit IHl; eauto. unfold Zpred. omega. \nQed.\n\n(** Properties of [List.incl] (list inclusion). *)\n\nLemma incl_cons_inv:\n  forall (A: Type) (a: A) (b c: list A),\n  incl (a :: b) c -> incl b c.\nProof.\n  unfold incl; intros. apply H. apply in_cons. auto.\nQed.\nHint Resolve incl_cons_inv: coqlib.\n\nLemma incl_app_inv_l:\n  forall (A: Type) (l1 l2 m: list A),\n  incl (l1 ++ l2) m -> incl l1 m.\nProof.\n  unfold incl; intros. apply H. apply in_or_app. left; assumption.\nQed.\n\nLemma incl_app_inv_r:\n  forall (A: Type) (l1 l2 m: list A),\n  incl (l1 ++ l2) m -> incl l2 m.\nProof.\n  unfold incl; intros. apply H. apply in_or_app. right; assumption.\nQed.\n\nHint Resolve  incl_tl incl_refl incl_app_inv_l incl_app_inv_r: coqlib.\n\nLemma incl_same_head:\n  forall (A: Type) (x: A) (l1 l2: list A),\n  incl l1 l2 -> incl (x::l1) (x::l2).\nProof.\n  intros; red; simpl; intros. intuition. \nQed.\n\n(** Properties of [List.map] (mapping a function over a list). *)\n\nLemma list_map_exten:\n  forall (A B: Type) (f f': A -> B) (l: list A),\n  (forall x, In x l -> f x = f' x) ->\n  List.map f' l = List.map f l.\nProof.\n  induction l; simpl; intros.\n  reflexivity.\n  rewrite <- H. rewrite IHl. reflexivity.\n  intros. apply H. tauto.\n  tauto.\nQed.\n\nLemma list_map_compose:\n  forall (A B C: Type) (f: A -> B) (g: B -> C) (l: list A),\n  List.map g (List.map f l) = List.map (fun x => g(f x)) l.\nProof.\n  induction l; simpl. reflexivity. rewrite IHl; reflexivity.\nQed.\n\nLemma list_map_identity:\n  forall (A: Type) (l: list A),\n  List.map (fun (x:A) => x) l = l.\nProof.\n  induction l; simpl; congruence.\nQed.\n\nLemma list_map_nth:\n  forall (A B: Type) (f: A -> B) (l: list A) (n: nat),\n  nth_error (List.map f l) n = option_map f (nth_error l n).\nProof.\n  induction l; simpl; intros.\n  repeat rewrite nth_error_nil. reflexivity.\n  destruct n; simpl. reflexivity. auto.\nQed.\n\nLemma list_length_map:\n  forall (A B: Type) (f: A -> B) (l: list A),\n  List.length (List.map f l) = List.length l.\nProof.\n  induction l; simpl; congruence.\nQed.\n\nLemma list_in_map_inv:\n  forall (A B: Type) (f: A -> B) (l: list A) (y: B),\n  In y (List.map f l) -> exists x:A, y = f x /\\ In x l.\nProof.\n  induction l; simpl; intros.\n  contradiction.\n  elim H; intro. \n  exists a; intuition auto.\n  generalize (IHl y H0). intros [x [EQ IN]]. \n  exists x; tauto.\nQed.\n\nLemma list_append_map:\n  forall (A B: Type) (f: A -> B) (l1 l2: list A),\n  List.map f (l1 ++ l2) = List.map f l1 ++ List.map f l2.\nProof.\n  induction l1; simpl; intros.\n  auto. rewrite IHl1. auto.\nQed.\n\nLemma list_append_map_inv:\n  forall (A B: Type) (f: A -> B) (m1 m2: list B) (l: list A),\n  List.map f l = m1 ++ m2 ->\n  exists l1, exists l2, List.map f l1 = m1 /\\ List.map f l2 = m2 /\\ l = l1 ++ l2.\nProof.\n  induction m1; simpl; intros.\n  exists (@nil A); exists l; auto.\n  destruct l; simpl in H; inv H. \n  exploit IHm1; eauto. intros [l1 [l2 [P [Q R]]]]. subst l. \n  exists (a0 :: l1); exists l2; intuition. simpl; congruence.\nQed.\n\n(** Folding a function over a list *)\n\nSection LIST_FOLD.\n\nVariables A B: Type.\nVariable f: A -> B -> B.\n\n(** This is exactly [List.fold_left] from Coq's standard library,\n  with [f] taking arguments in a different order. *)\n\nFixpoint list_fold_left (accu: B) (l: list A) : B :=\n  match l with nil => accu | x :: l' => list_fold_left (f x accu) l' end.\n\n(** This is exactly [List.fold_right] from Coq's standard library,\n  except that it runs in constant stack space. *)\n\nDefinition list_fold_right (l: list A) (base: B) : B :=\n  list_fold_left base (List.rev' l).\n\nRemark list_fold_left_app:\n  forall l1 l2 accu,\n  list_fold_left accu (l1 ++ l2) = list_fold_left (list_fold_left accu l1) l2.\nProof.\n  induction l1; simpl; intros. \n  auto.\n  rewrite IHl1. auto.\nQed.\n\nLemma list_fold_right_eq:\n  forall l base,\n  list_fold_right l base =\n  match l with nil => base | x :: l' => f x (list_fold_right l' base) end.\nProof.\n  unfold list_fold_right; intros. \n  destruct l.\n  auto.\n  unfold rev'. rewrite <- ! rev_alt. simpl.  \n  rewrite list_fold_left_app. simpl. auto. \nQed.\n\nLemma list_fold_right_spec:\n  forall l base, list_fold_right l base = List.fold_right f base l.\nProof.\n  induction l; simpl; intros; rewrite list_fold_right_eq; congruence.\nQed.\n\nEnd LIST_FOLD.\n\n(** Properties of list membership. *)\n\nLemma in_cns:\n  forall (A: Type) (x y: A) (l: list A), In x (y :: l) <-> y = x \\/ In x l.\nProof.\n  intros. simpl. tauto.\nQed.\n\nLemma in_app:\n  forall (A: Type) (x: A) (l1 l2: list A), In x (l1 ++ l2) <-> In x l1 \\/ In x l2.\nProof.\n  intros. split; intro. apply in_app_or. auto. apply in_or_app. auto.\nQed.\n\nLemma list_in_insert:\n  forall (A: Type) (x: A) (l1 l2: list A) (y: A),\n  In x (l1 ++ l2) -> In x (l1 ++ y :: l2).\nProof.\n  intros. apply in_or_app; simpl. elim (in_app_or _ _ _ H); intro; auto.\nQed.\n\n(** [list_disjoint l1 l2] holds iff [l1] and [l2] have no elements \n  in common. *)\n\nDefinition list_disjoint (A: Type) (l1 l2: list A) : Prop :=\n  forall (x y: A), In x l1 -> In y l2 -> x <> y.\n\nLemma list_disjoint_cons_l:\n  forall (A: Type) (a: A) (l1 l2: list A),\n  list_disjoint l1 l2 -> ~In a l2 -> list_disjoint (a :: l1) l2.\nProof.\n  unfold list_disjoint; simpl; intros. destruct H1. congruence. apply H; auto.\nQed.\n\nLemma list_disjoint_cons_r:\n  forall (A: Type) (a: A) (l1 l2: list A),\n  list_disjoint l1 l2 -> ~In a l1 -> list_disjoint l1 (a :: l2).\nProof.\n  unfold list_disjoint; simpl; intros. destruct H2. congruence. apply H; auto.\nQed.\n\nLemma list_disjoint_cons_left:\n  forall (A: Type) (a: A) (l1 l2: list A),\n  list_disjoint (a :: l1) l2 -> list_disjoint l1 l2.\nProof.\n  unfold list_disjoint; simpl; intros. apply H; tauto. \nQed.\n\nLemma list_disjoint_cons_right:\n  forall (A: Type) (a: A) (l1 l2: list A),\n  list_disjoint l1 (a :: l2) -> list_disjoint l1 l2.\nProof.\n  unfold list_disjoint; simpl; intros. apply H; tauto. \nQed.\n\nLemma list_disjoint_notin:\n  forall (A: Type) (l1 l2: list A) (a: A),\n  list_disjoint l1 l2 -> In a l1 -> ~(In a l2).\nProof.\n  unfold list_disjoint; intros; red; intros. \n  apply H with a a; auto.\nQed.\n\nLemma list_disjoint_sym:\n  forall (A: Type) (l1 l2: list A),\n  list_disjoint l1 l2 -> list_disjoint l2 l1.\nProof.\n  unfold list_disjoint; intros. \n  apply sym_not_equal. apply H; auto.\nQed.\n\nLemma list_disjoint_dec:\n  forall (A: Type) (eqA_dec: forall (x y: A), {x=y} + {x<>y}) (l1 l2: list A),\n  {list_disjoint l1 l2} + {~list_disjoint l1 l2}.\nProof.\n  induction l1; intros.\n  left; red; intros. elim H.\n  case (In_dec eqA_dec a l2); intro.\n  right; red; intro. apply (H a a); auto with coqlib. \n  case (IHl1 l2); intro.\n  left; red; intros. elim H; intro. \n    red; intro; subst a y. contradiction.\n    apply l; auto.\n  right; red; intros. elim n0. eapply list_disjoint_cons_left; eauto.\nDefined.\n\n(** [list_equiv l1 l2] holds iff the lists [l1] and [l2] contain the same elements. *)\n\nDefinition list_equiv (A : Type) (l1 l2: list A) : Prop :=\n  forall x, In x l1 <-> In x l2.\n\n(** [list_norepet l] holds iff the list [l] contains no repetitions,\n  i.e. no element occurs twice. *)\n\nInductive list_norepet (A: Type) : list A -> Prop :=\n  | list_norepet_nil:\n      list_norepet nil\n  | list_norepet_cons:\n      forall hd tl,\n      ~(In hd tl) -> list_norepet tl -> list_norepet (hd :: tl).\n\nLemma list_norepet_dec:\n  forall (A: Type) (eqA_dec: forall (x y: A), {x=y} + {x<>y}) (l: list A),\n  {list_norepet l} + {~list_norepet l}.\nProof.\n  induction l.\n  left; constructor.\n  destruct IHl. \n  case (In_dec eqA_dec a l); intro.\n  right. red; intro. inversion H. contradiction. \n  left. constructor; auto.\n  right. red; intro. inversion H. contradiction.\nDefined.\n\nLemma list_map_norepet:\n  forall (A B: Type) (f: A -> B) (l: list A),\n  list_norepet l ->\n  (forall x y, In x l -> In y l -> x <> y -> f x <> f y) ->\n  list_norepet (List.map f l).\nProof.\n  induction 1; simpl; intros.\n  constructor.\n  constructor.\n  red; intro. generalize (list_in_map_inv f _ _ H2).\n  intros [x [EQ IN]]. generalize EQ. change (f hd <> f x).\n  apply H1. tauto. tauto. \n  red; intro; subst x. contradiction.\n  apply IHlist_norepet. intros. apply H1. tauto. tauto. auto.\nQed.\n\nRemark list_norepet_append_commut:\n  forall (A: Type) (a b: list A),\n  list_norepet (a ++ b) -> list_norepet (b ++ a).\nProof.\n  intro A.\n  assert (forall (x: A) (b: list A) (a: list A), \n           list_norepet (a ++ b) -> ~(In x a) -> ~(In x b) -> \n           list_norepet (a ++ x :: b)).\n    induction a; simpl; intros.\n    constructor; auto.\n    inversion H. constructor. red; intro.\n    elim (in_app_or _ _ _ H6); intro.\n    elim H4. apply in_or_app. tauto.\n    elim H7; intro. subst a. elim H0. left. auto. \n    elim H4. apply in_or_app. tauto.\n    auto.\n  induction a; simpl; intros.\n  rewrite <- app_nil_end. auto.\n  inversion H0. apply H. auto. \n  red; intro; elim H3. apply in_or_app. tauto.\n  red; intro; elim H3. apply in_or_app. tauto.\nQed.\n\nLemma list_norepet_app:\n  forall (A: Type) (l1 l2: list A),\n  list_norepet (l1 ++ l2) <->\n  list_norepet l1 /\\ list_norepet l2 /\\ list_disjoint l1 l2.\nProof.\n  induction l1; simpl; intros; split; intros.\n  intuition. constructor. red;simpl;auto.\n  tauto.\n  inversion H; subst. rewrite IHl1 in H3. rewrite in_app in H2.\n  intuition.\n  constructor; auto. red; intros. elim H2; intro. congruence. auto. \n  destruct H as [B [C D]]. inversion B; subst. \n  constructor. rewrite in_app. intuition. elim (D a a); auto. apply in_eq. \n  rewrite IHl1. intuition. red; intros. apply D; auto. apply in_cons; auto. \nQed.\n\nLemma list_norepet_append:\n  forall (A: Type) (l1 l2: list A),\n  list_norepet l1 -> list_norepet l2 -> list_disjoint l1 l2 ->\n  list_norepet (l1 ++ l2).\nProof.\n  generalize list_norepet_app; firstorder.\nQed.\n\nLemma list_norepet_append_right:\n  forall (A: Type) (l1 l2: list A),\n  list_norepet (l1 ++ l2) -> list_norepet l2.\nProof.\n  generalize list_norepet_app; firstorder.\nQed.\n\nLemma list_norepet_append_left:\n  forall (A: Type) (l1 l2: list A),\n  list_norepet (l1 ++ l2) -> list_norepet l1.\nProof.\n  generalize list_norepet_app; firstorder.\nQed.\n\n(** [is_tail l1 l2] holds iff [l2] is of the form [l ++ l1] for some [l]. *)\n\nInductive is_tail (A: Type): list A -> list A -> Prop :=\n  | is_tail_refl:\n      forall c, is_tail c c\n  | is_tail_cons:\n      forall i c1 c2, is_tail c1 c2 -> is_tail c1 (i :: c2).\n\nLemma is_tail_in:\n  forall (A: Type) (i: A) c1 c2, is_tail (i :: c1) c2 -> In i c2.\nProof.\n  induction c2; simpl; intros.\n  inversion H.\n  inversion H. tauto. right; auto.\nQed.\n\nLemma is_tail_cons_left:\n  forall (A: Type) (i: A) c1 c2, is_tail (i :: c1) c2 -> is_tail c1 c2.\nProof.\n  induction c2; intros; inversion H.\n  constructor. constructor. constructor. auto. \nQed.\n\nHint Resolve is_tail_refl is_tail_cons is_tail_in is_tail_cons_left: coqlib.\n\nLemma is_tail_incl:\n  forall (A: Type) (l1 l2: list A), is_tail l1 l2 -> incl l1 l2.\nProof.\n  induction 1; eauto with coqlib.\nQed.\n\nLemma is_tail_trans:\n  forall (A: Type) (l1 l2: list A),\n  is_tail l1 l2 -> forall (l3: list A), is_tail l2 l3 -> is_tail l1 l3.\nProof.\n  induction 1; intros. auto. apply IHis_tail. eapply is_tail_cons_left; eauto.\nQed.\n\n(** [list_forall2 P [x1 ... xN] [y1 ... yM]] holds iff [N = M] and\n  [P xi yi] holds for all [i]. *)\n\nSection FORALL2.\n\nVariable A: Type.\nVariable B: Type.\nVariable P: A -> B -> Prop.\n\nInductive list_forall2: list A -> list B -> Prop :=\n  | list_forall2_nil:\n      list_forall2 nil nil\n  | list_forall2_cons:\n      forall a1 al b1 bl,\n      P a1 b1 ->\n      list_forall2 al bl ->\n      list_forall2 (a1 :: al) (b1 :: bl).\n\nLemma list_forall2_app:\n  forall a2 b2 a1 b1,\n  list_forall2 a1 b1 -> list_forall2 a2 b2 -> \n  list_forall2 (a1 ++ a2) (b1 ++ b2).\nProof.\n  induction 1; intros; simpl. auto. constructor; auto. \nQed.\n\nLemma list_forall2_length:\n  forall l1 l2,\n  list_forall2 l1 l2 -> length l1 = length l2.\nProof.\n  induction 1; simpl; congruence.\nQed.\n\nEnd FORALL2.\n\nLemma list_forall2_imply:\n  forall (A B: Type) (P1: A -> B -> Prop) (l1: list A) (l2: list B),\n  list_forall2 P1 l1 l2 ->\n  forall (P2: A -> B -> Prop),\n  (forall v1 v2, In v1 l1 -> In v2 l2 -> P1 v1 v2 -> P2 v1 v2) ->\n  list_forall2 P2 l1 l2.\nProof.\n  induction 1; intros.\n  constructor.\n  constructor. auto with coqlib. apply IHlist_forall2; auto. \n  intros. auto with coqlib.\nQed.\n\n(** Dropping the first N elements of a list. *)\n\nFixpoint list_drop (A: Type) (n: nat) (x: list A) {struct n} : list A :=\n  match n with\n  | O => x\n  | S n' => match x with nil => nil | hd :: tl => list_drop n' tl end\n  end.\n\nLemma list_drop_incl:\n  forall (A: Type) (x: A) n (l: list A), In x (list_drop n l) -> In x l.\nProof.\n  induction n; simpl; intros. auto. \n  destruct l; auto with coqlib.\nQed.\n\nLemma list_drop_norepet:\n  forall (A: Type) n (l: list A), list_norepet l -> list_norepet (list_drop n l).\nProof.\n  induction n; simpl; intros. auto.\n  inv H. constructor. auto.\nQed.\n\nLemma list_map_drop:\n  forall (A B: Type) (f: A -> B) n (l: list A),\n  list_drop n (map f l) = map f (list_drop n l).\nProof.\n  induction n; simpl; intros. auto. \n  destruct l; simpl; auto.\nQed.\n\n(** A list of [n] elements, all equal to [x]. *)\n\nFixpoint list_repeat {A: Type} (n: nat) (x: A) {struct n} :=\n  match n with\n  | O => nil\n  | S m => x :: list_repeat m x\n  end.\n\nLemma length_list_repeat:\n  forall (A: Type) n (x: A), length (list_repeat n x) = n.\nProof.\n  induction n; simpl; intros. auto. decEq; auto.\nQed.\n\nLemma in_list_repeat:\n  forall (A: Type) n (x: A) y, In y (list_repeat n x) -> y = x.\nProof.\n  induction n; simpl; intros. elim H. destruct H; auto.\nQed.\n\n(** * Definitions and theorems over boolean types *)\n\nDefinition proj_sumbool (P Q: Prop) (a: {P} + {Q}) : bool :=\n  if a then true else false.\n\nImplicit Arguments proj_sumbool [P Q].\n\nCoercion proj_sumbool: sumbool >-> bool.\n\nLemma proj_sumbool_true:\n  forall (P Q: Prop) (a: {P}+{Q}), proj_sumbool a = true -> P.\nProof.\n  intros P Q a. destruct a; simpl. auto. congruence.\nQed.\n\nLemma proj_sumbool_is_true:\n  forall (P: Prop) (a: {P}+{~P}), P -> proj_sumbool a = true.\nProof.\n  intros. unfold proj_sumbool. destruct a. auto. contradiction. \nQed.\n\nLtac InvBooleans :=\n  match goal with\n  | [ H: _ && _ = true |- _ ] =>\n      destruct (andb_prop _ _ H); clear H; InvBooleans\n  | [ H: _ || _ = false |- _ ] =>\n      destruct (orb_false_elim _ _ H); clear H; InvBooleans\n  | [ H: proj_sumbool ?x = true |- _ ] =>\n      generalize (proj_sumbool_true _ H); clear H; intro; InvBooleans\n  | _ => idtac\n  end.\n\nSection DECIDABLE_EQUALITY.\n\nVariable A: Type.\nVariable dec_eq: forall (x y: A), {x=y} + {x<>y}.\nVariable B: Type.\n\nLemma dec_eq_true:\n  forall (x: A) (ifso ifnot: B),\n  (if dec_eq x x then ifso else ifnot) = ifso.\nProof.\n  intros. destruct (dec_eq x x). auto. congruence.\nQed.\n\nLemma dec_eq_false:\n  forall (x y: A) (ifso ifnot: B),\n  x <> y -> (if dec_eq x y then ifso else ifnot) = ifnot.\nProof.\n  intros. destruct (dec_eq x y). congruence. auto.\nQed.\n\nLemma dec_eq_sym:\n  forall (x y: A) (ifso ifnot: B),\n  (if dec_eq x y then ifso else ifnot) =\n  (if dec_eq y x then ifso else ifnot).\nProof.\n  intros. destruct (dec_eq x y). \n  subst y. rewrite dec_eq_true. auto.\n  rewrite dec_eq_false; auto.\nQed.\n\nEnd DECIDABLE_EQUALITY.\n\nSection DECIDABLE_PREDICATE.\n\nVariable P: Prop.\nVariable dec: {P} + {~P}.\nVariable A: Type.\n\nLemma pred_dec_true:\n  forall (a b: A), P -> (if dec then a else b) = a.\nProof.\n  intros. destruct dec. auto. contradiction.\nQed.\n\nLemma pred_dec_false:\n  forall (a b: A), ~P -> (if dec then a else b) = b.\nProof.\n  intros. destruct dec. contradiction. auto.\nQed.\n\nEnd DECIDABLE_PREDICATE.\n\n(** * Well-founded orderings *)\n\nRequire Import Relations.\n\n(** A non-dependent version of lexicographic ordering. *)\n\nSection LEX_ORDER.\n\nVariable A: Type.\nVariable B: Type.\nVariable ordA: A -> A -> Prop.\nVariable ordB: B -> B -> Prop.\n\nInductive lex_ord: A*B -> A*B -> Prop :=\n  | lex_ord_left: forall a1 b1 a2 b2,\n      ordA a1 a2 -> lex_ord (a1,b1) (a2,b2)\n  | lex_ord_right: forall a b1 b2,\n      ordB b1 b2 -> lex_ord (a,b1) (a,b2).\n\nLemma wf_lex_ord: \n  well_founded ordA -> well_founded ordB -> well_founded lex_ord.\nProof.\n  intros Awf Bwf.\n  assert (forall a, Acc ordA a -> forall b, Acc ordB b -> Acc lex_ord (a, b)).\n    induction 1. induction 1. constructor; intros. inv H3.\n    apply H0. auto. apply Bwf.\n    apply H2; auto. \n  red; intros. destruct a as [a b]. apply H; auto.\nQed.\n\nLemma transitive_lex_ord:\n  transitive _ ordA -> transitive _ ordB -> transitive _ lex_ord.\nProof.\n  intros trA trB; red; intros. \n  inv H; inv H0. \n  left; eapply trA; eauto.\n  left; auto.\n  left; auto.\n  right; eapply trB; eauto.\nQed.\n\nEnd LEX_ORDER.\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/framework/auxlibs/Coqlib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.2860522664194274}}
{"text": "Require Import Bool String List.\nRequire Import Lib.CommonTactics Lib.ilist Lib.Word Lib.Indexer Lib.StringAsList.\nRequire Import Kami.Syntax Kami.Notations Kami.Semantics.\nRequire Import Kami.Wf Kami.Tactics.\nRequire Import FunctionalExtensionality Eqdep Eqdep_dec.\n\nSet Implicit Arguments.\n  \nSection Fifo.\n  Variable fifoName: string.\n  Variable sz: nat.\n  Variable dType: Kind.\n\n  Local Notation \"^ s\" := (fifoName -- s) (at level 0).\n\n  Definition enq {ty} : forall (d: ty dType), ActionT ty Void := fun d =>\n    (Read isFull <- ^\"full\";\n     Assert !#isFull;\n     Read eltT <- ^\"elt\";\n     Read enqPT <- ^\"enqP\";\n     Read deqPT <- ^\"deqP\";\n     Write ^\"elt\" <- #eltT@[#enqPT <- #d];\n     Write ^\"empty\" <- $$false;\n     LET next_enqP <- (#enqPT + $1) :: Bit sz;\n     Write ^\"full\" <- (#deqPT == #next_enqP);\n     Write ^\"enqP\" <- #next_enqP;\n     Retv)%kami_action.\n\n  Definition deq {ty} : ActionT ty dType :=\n    (Read isEmpty <- ^\"empty\";\n     Assert !#isEmpty;\n     Read eltT <- ^\"elt\";\n     Read enqPT <- ^\"enqP\";\n     Read deqPT <- ^\"deqP\";\n     Write ^\"full\" <- $$false;\n     LET next_deqP <- (#deqPT + $1) :: Bit sz;\n     Write ^\"empty\" <- (#enqPT == #next_deqP);\n     Write ^\"deqP\" <- #next_deqP;\n     Ret #eltT@[#deqPT])%kami_action.\n\n  Definition firstElt {ty} : ActionT ty dType :=\n    (Read isEmpty <- ^\"empty\";\n     Assert !#isEmpty;\n     Read eltT : Vector dType sz <- ^\"elt\";\n     Read deqPT <- ^\"deqP\";\n     Ret #eltT@[#deqPT])%kami_action.\n  \n  Definition fifo := MODULE {\n    Register ^\"elt\" : Vector dType sz <- Default\n    with Register ^\"enqP\" : Bit sz <- Default\n    with Register ^\"deqP\" : Bit sz <- Default\n    with Register ^\"empty\" : Bool <- true\n    with Register ^\"full\" : Bool <- Default\n\n    with Method ^\"enq\"(d : dType) : Void := (enq d)\n    with Method ^\"deq\"() : dType := deq\n    with Method ^\"firstElt\"() : dType := firstElt\n  }.\n\n  Definition simpleFifo := MODULE {\n    Register ^\"elt\" : Vector dType sz <- Default\n    with Register ^\"enqP\" : Bit sz <- Default\n    with Register ^\"deqP\" : Bit sz <- Default\n    with Register ^\"empty\" : Bool <- true\n    with Register ^\"full\" : Bool <- Default\n\n    with Method ^\"enq\"(d : dType) : Void := (enq d)\n    with Method ^\"deq\"() : dType := deq\n  }.\n\nEnd Fifo.\n\n#[global] Hint Unfold fifo simpleFifo : ModuleDefs.\n#[global] Hint Unfold enq deq firstElt : MethDefs.\n\nSection Facts.\n  Variable fifoName: string.\n  Variable sz: nat.\n  Variable dType: Kind.\n\n  Hypothesis HfifoName: index 0 indexSymbol fifoName = None.\n\n  Lemma fifo_ModEquiv:\n    ModPhoasWf (fifo fifoName sz dType).\n  Proof. kequiv. Qed.\n  #[local] Hint Resolve fifo_ModEquiv.\n\n  Lemma simpleFifo_ModEquiv:\n    ModPhoasWf (simpleFifo fifoName sz dType).\n  Proof. kequiv. Qed.\n  #[local] Hint Resolve simpleFifo_ModEquiv.\n\n  Lemma fifo_ValidRegs:\n    ModRegsWf (fifo fifoName sz dType).\n  Proof. kvr. Qed.\n  #[local] Hint Resolve fifo_ValidRegs.\n\n  Lemma simpleFifo_ValidRegs:\n    ModRegsWf (simpleFifo fifoName sz dType).\n  Proof. kvr. Qed.\n  #[local] Hint Resolve simpleFifo_ValidRegs.\n\nEnd Facts.\n\n#[global] Hint Resolve fifo_ModEquiv simpleFifo_ModEquiv.\n#[global] Hint Resolve fifo_ValidRegs simpleFifo_ValidRegs.\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/Fifo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.2860522664194273}}
{"text": "Set Warnings \"-notation-overridden\".\n\nRequire Import Category.Lib.\nRequire Export Category.Theory.Morphisms.\nRequire Export Category.Theory.Isomorphism.\nRequire Export Category.Theory.Functor.\nRequire Export Category.Functor.Bifunctor.\nRequire Export Category.Structure.Cartesian.\nRequire Export Category.Structure.Monoidal.Semicartesian.\nRequire Export Category.Structure.Monoidal.Relevance.\nRequire Export Category.Structure.Monoidal.Cartesian.\nRequire Export Category.Structure.Monoidal.Cartesian.Proofs.\n\nGeneralizable All Variables.\nSet Primitive Projections.\nSet Universe Polymorphism.\nUnset Transparent Obligations.\n\nSection CartesianMonoidalCartesian.\n\nContext `{@Monoidal C}.\nContext `{@CartesianMonoidal C _}.\n\nGlobal Program Definition CartesianMonoidal_Cartesian : @Cartesian C := {|\n  product_obj := fun x y => (x ⨂ y)%object;\n  fork := fun x _ _ f g => f ⨂ g ∘ ∆x;\n  exl  := fun _ _ => proj_left;\n  exr  := fun _ _ => proj_right\n|}.\nNext Obligation. apply is_relevance. Defined.\nNext Obligation. proper; rewrites; reflexivity. Qed.\nNext Obligation.\n  split; intros.\n    split.\n      rewrites.\n      rewrite comp_assoc.\n      rewrite proj_left_natural.\n      rewrite <- comp_assoc.\n      rewrite proj_left_diagonal; cat.\n    rewrites.\n    rewrite comp_assoc.\n    rewrite proj_right_natural.\n    rewrite <- comp_assoc.\n    rewrite proj_right_diagonal; cat.\n  rewrite <- (fst X), <- (snd X).\n  rewrite bimap_comp.\n  rewrite <- !comp_assoc.\n  srewrite diagonal_natural.\n  rewrite comp_assoc.\n  rewrite proj_left_right_diagonal; cat.\nQed.\n\nEnd CartesianMonoidalCartesian.\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/Structure/Monoidal/Cartesian/Cartesian.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2860375588287087}}
{"text": "Require Import ExtLib.Data.HList.\nRequire Import MirrorCore.ExprI.\nRequire Import MirrorCore.SubstI.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nSection with_Expr.\n  Variable typ : Set.\n  Variable expr : Set.\n  Variable subst : Type.\n  Context {RType_typ : RType typ}.\n  Context {RTypeOk_typ : RTypeOk}.\n  Context {Expr_expr : @Expr typ _ expr}.\n  Context {Subst_subst : Subst subst expr}.\n  Context {SubstOk_subst : SubstOk subst typ expr}.\n  Context {SubstUpdate_subst : SubstUpdate subst expr}.\n  Context {SubstUpdateOk_subst : SubstUpdateOk subst typ expr}.\n\n  Local Existing Instance RType_typ.\n  Local Existing Instance Expr_expr.\n\n  Definition unifier : Type :=\n    forall (tus tvs : tenv typ) (under : nat) (l r : expr)\n           (t : typ) (s : subst), option subst.\n\n  Variable unify : unifier.\n\n  Definition unify_sound : Prop :=\n    forall (tu tv : tenv typ) (e1 e2 : expr) (s s' : subst)\n           (t : typ) (tv' : tenv typ),\n      unify tu (tv' ++ tv) (length tv') e1 e2 t s = Some s' ->\n      WellFormed_subst s ->\n      WellFormed_subst s' /\\\n      forall v1 v2 sD,\n        exprD tu (tv' ++ tv) t e1 = Some v1 ->\n        exprD tu (tv' ++ tv) t e2 = Some v2 ->\n        substD tu tv s = Some sD ->\n        exists sD',\n             substR tu tv s s'\n          /\\ substD tu tv s' = Some sD'\n          /\\ forall us vs,\n               sD' us vs ->\n               sD us vs /\\\n               forall vs',\n                 v1 us (hlist_app vs' vs) = v2 us (hlist_app vs' vs).\n\nEnd with_Expr.\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/UnifyI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2860375588287087}}
{"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\nRequire Import Polarity.\nRequire Import ZArith.\n\nInductive atomsEx : Set :=\n  | s : atomsEx\n  | sn : atomsEx\n  | n : atomsEx.\n\nLemma atomsEx_dec : forall x y : atomsEx, {x = y} + {x <> y}.\n intros x y.\n elim x; elim y; first [ left; reflexivity | right; discriminate ].\nDefined.\n\nLemma notDerivableSequence :\n ~\n weak\n   (gentzenSequent NL_Sequent\n      (Comma (OneForm (At s)) (OneForm (Slash (At sn) (At n)))) (\n      At s)). \n\n Proof.\n  red in |- *.\n  intro H.\n  elim H.\n  intro H0.\n  clear H.\n  Polartest sn (atomsEx_dec sn) H0. \n  apply NLEqualPolarity.\n  simpl in |- *.\n  auto with zarith.\n Qed.", "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/ExamplePol.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2860375588287087}}
{"text": "Require 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(* 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", "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/Step/Frame.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.2860375588287087}}
{"text": "From iris.proofmode Require Import tactics.\nFrom Perennial.program_logic Require Export crash_weakestpre staged_invariant_alt.\nSet Default Proof Using \"Type\".\nImport uPred.\n\nSection modality.\nContext `{IRISG: !irisGS Λ Σ, !generationGS Λ Σ}.\n\nDefinition wpc_nval E (P : iProp Σ) : iProp Σ :=\n  (∀ E' e s Φ Φc,\n    ⌜ to_val e = None ⌝ →\n    ⌜ E ⊆ E' ⌝ →\n    (WPC e @ s; E' {{ λ v, P -∗ Φ v }} {{ Φc }}) -∗\n    WPC e @ s; E' {{ λ v, Φ v }} {{ Φc }}).\n\n\nLemma wpc_nval_strong_mono E P P' :\n  wpc_nval E P -∗\n  ▷ (P -∗ |NC={E}=> P') -∗\n  wpc_nval E P'.\nProof.\n  iIntros \"Hwpc_nval Hwand\".\n  rewrite /wpc_nval. iIntros (????? Hnval Hsub) \"H\".\n  iApply wpc_ncfupd.\n  iApply \"Hwpc_nval\"; auto.\n  iApply (wpc_step_strong_mono with \"[$]\"); eauto.\n  iSplit; last eauto.\n  iNext. iIntros (?) \"HP'\". iModIntro. iIntros \"HP\".\n  iApply (ncfupd_mask_mono E); auto.\n  iMod (\"Hwand\" with \"[$]\"). iDestruct (\"HP'\" with \"[$]\") as \"$\".\n  eauto.\nQed.\n\nLemma wpc_nval_True E : ⊢ wpc_nval E True%I.\nProof.\n  rewrite /wpc_nval. iIntros (?????) \"Hnval Hsub H\".\n  iApply (wpc_strong_mono with \"H\"); eauto.\n  iSplit; last eauto.\n  iIntros (?) \"H\". iApply \"H\". eauto.\nQed.\n\nLemma wpc_nval_intro E P :\n  ▷ P -∗ wpc_nval E P.\nProof.\n  iIntros \"HP\".\n  iPoseProof (wpc_nval_True) as \"Htrue\".\n  iApply (wpc_nval_strong_mono with \"Htrue\"); eauto.\nQed.\n\nLemma wpc_nval_ncfupd E P :\n  wpc_nval E (|NC={E}=> P) -∗ wpc_nval E P.\nProof.\n  iIntros \"HP\".\n  iApply (wpc_nval_strong_mono with \"HP\"); eauto.\nQed.\n\nLemma ncfupd_wpc_nval E P :\n  (|NC={E}=> wpc_nval E P) -∗ wpc_nval E P.\nProof.\n  iIntros \"HP\".\n  rewrite /wpc_nval. iIntros (????? Hnval Hsub) \"H\".\n  rewrite ?wpc_unfold. iIntros (mj).\n  rewrite /wpc_pre.\n  rewrite Hnval.\n  iSplit; last first.\n  { iDestruct (\"H\" $! _) as \"(_&H)\". eauto. }\n  iIntros. rewrite ncfupd_eq.\n  iSpecialize (\"HP\" with \"[$]\").\n  iMod (fupd_mask_mono with \"HP\") as \"(HP&HNC)\"; auto.\n  iSpecialize (\"HP\" $! E' e s Φ Φc with \"[//] [//]\").\n  rewrite ?wpc_unfold.\n  rewrite /wpc_pre.\n  rewrite Hnval.\n  iSpecialize (\"HP\" with \"H\").\n  iDestruct (\"HP\" $! mj) as \"(H&_)\".\n  iApply (\"H\" with \"[$] [$] [$] [$]\").\nQed.\n\nLemma wpc_nval_elim E1 E2 P e s Φ Φc :\n  to_val e = None →\n  E1 ⊆ E2 →\n  wpc_nval E1 P -∗\n  (WPC e @ s; E2 {{ λ v, P -∗ Φ v }} {{ Φc }}) -∗\n  WPC e @ s; E2 {{ λ v, Φ v }} {{ Φc }}.\nProof.\n  iIntros (Hnval Hsub) \"Hwpc_nval Hwpc\".\n  iApply \"Hwpc_nval\"; eauto.\nQed.\n\nLemma wpc_nval_elim_wp E1 E2 P e s Φ :\n  to_val e = None →\n  E1 ⊆ E2 →\n  wpc_nval E1 P -∗\n  (WP e @ s; E2 {{ λ v, P -∗ Φ v }}) -∗\n  WP e @ s; E2 {{ λ v, Φ v }}.\nProof.\n  iIntros (Hnval Hsub) \"Hwpc_nval Hwpc\".\n  rewrite wp_eq /wp_def.\n  iApply (wpc_nval_elim with \"[$]\"); eauto.\nQed.\n\nEnd modality.\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/wpc_nval.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160666, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2859553105621071}}
{"text": "Require Export Db.Inst.\nRequire Export Db.Lemmas.\nRequire Export Db.WellScoping.\nRequire Export StlcFix.SpecSyntax.\n\n#[export]\n#[refine] Instance vrTm : Vr Tm := {| vr := var |}.\nProof. inversion 1; auto. Defined.\n\nLocal Ltac crush :=\n  intros; cbn in * |-;\n  repeat\n    (cbn;\n     repeat crushStlcSyntaxMatchH;\n     repeat crushDbSyntaxMatchH;\n     repeat crushDbLemmasMatchH;\n     rewrite ?comp_up, ?up_liftSub, ?up_comp_lift\n    );\n  auto.\n\nModule TmKit <: Kit.\n\n  Definition TM := Tm.\n  Definition inst_vr := vrTm.\n\n  Section Application.\n\n    Context {Y: Type}.\n    Context {vrY : Vr Y}.\n    Context {wkY: Wk Y}.\n    Context {liftY: Lift Y Tm}.\n\n    #[export]\n    #[refine] Instance inst_ap : Ap Tm Y := {| ap := apTm |}.\n    Proof. induction x; crush. Defined.\n\n    #[export]\n    #[refine] Instance inst_ap_vr : LemApVr Tm Y := {}.\n    Proof. reflexivity. Qed.\n\n  End Application.\n\n  #[export]\n  #[refine] Instance inst_ap_inj: LemApInj Tm Ix := {}.\n  Proof.\n    intros m Inj_m x. revert m Inj_m.\n    induction x; destruct y; simpl; try discriminate;\n    inversion 1; subst; f_equal; eauto using InjSubIxUp.\n  Qed.\n\n  #[export]\n  #[refine] Instance inst_ap_comp (Y Z: Type)\n    {vrY: Vr Y} {wkY: Wk Y} {liftY: Lift Y Tm}\n    {vrZ: Vr Z} {wkZ: Wk Z} {liftZ: Lift Z Tm}\n    {apYZ: Ap Y Z} {compUpYZ: LemCompUp Y Z}\n    {apLiftYTmZ: LemApLift Y Z Tm} :\n    LemApComp Tm Y Z := {}.\n  Proof. induction x; crush. Qed.\n\n  #[export]\n  #[refine] Instance inst_ap_liftSub (Y: Type)\n    {vrY: Vr Y} {wkY: Wk Y} {liftY: Lift Y Tm} :\n    LemApLiftSub Tm Y := {}.\n  Proof. induction t; crush. Qed.\n\n  Lemma inst_ap_ixComp (t: Tm) :\n    ∀ (ξ: Sub Ix) (ζ: Sub Tm), t[ξ][ζ] = t[⌈ξ⌉ >=> ζ].\n  Proof. pose proof up_comp_lift. induction t; crush. Qed.\n\nEnd TmKit.\n\nModule InstTm := Inst TmKit.\nExport InstTm. (* Export for shorter names. *)\n\n#[export]\nInstance wsVrTm: WsVr Tm.\nProof.\n  constructor.\n  - now constructor.\n  - now inversion 1.\nQed.\n\nSection Application.\n\n  Context {Y: Type}.\n  Context {vrY : Vr Y}.\n  Context {wkY: Wk Y}.\n  Context {liftY: Lift Y Tm}.\n  Context {wsY: Ws Y}.\n  Context {wsVrY: WsVr Y}.\n  Context {wsWkY: WsWk Y}.\n  Context {wsLiftY: WsLift Y Tm}.\n\n  Hint Resolve wsLift : ws.\n  Hint Resolve wsSub_up : ws.\n\n\n  Global Instance wsApTm : WsAp Tm Y.\n  Proof.\n    constructor.\n    - intros ξ γ δ t wξ wt; revert ξ δ wξ.\n      induction wt; intros ξ δ wξ; crush;\n      try econstructor;\n      try match goal with\n            | |- wsTm ?δ ?t =>\n              change (wsTm δ t) with ⟨ δ ⊢ t ⟩\n          end; eauto with ws.\n    - intros γ t wt.\n      induction wt; crush.\n      + apply IHwt; inversion 1; crush.\n      + apply IHwt2; inversion 1; crush.\n      + apply IHwt3; inversion 1; crush.\n  Qed.\nEnd Application.\n\n#[export]\nInstance wsWkTm: WsWk Tm.\nProof.\n  constructor; crush.\n  - refine (wsAp _ H); eauto.\n    constructor; eauto.\nQed.\n(*   - admit. *)\n(*     (* induction x; cbn in H; inversion H. *) *)\n(*     (* + change (wk i) with (S i) in *. *) *)\n(*     (*   inversion H1; subst. eapply WsVar; eassumption. *) *)\n(*     (* +  *) *)\n(* Admitted. *)\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/StlcFix/Inst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160664, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.285955310562107}}
{"text": "From bisimulations Require Import prelude.\nFrom bisimulations Require Import system.\nFrom bisimulations Require Import relations.\nFrom bisimulations Require Import paths.\nFrom bisimulations Require Import nonreflexive.semibranching.\nFrom bisimulations Require Import reflexive.branching.\n\nSection NonreflVsRefl.\nContext `{System : system X}.\n\nNotation nr_sb_apart := (@nonreflexive.semibranching.sb_apart X System).\nNotation r_b_apart := (@reflexive.branching.b_apart X WithRefl).\n\nTheorem nonrefl_to_refl : ∀ p q, nr_sb_apart p q → r_b_apart p q.\nProof. eapply nonreflexive.semibranching.sb_apart_strong_ind'; [eauto with hints|..].\n  - intros p1 p2 q1 Hp12 Ha_p2_q1 HQ.\n    eapply reflexive.branching.b_apart_step; [by eapply WithRefl_can_step|].\n    intros q2 Hq12 q3 Hq23.\n    rewrite <- WithRefl_rtc_can_step in Hq12.\n    destruct Hq23 as [Hq23|[_ <-]].\n    { by destruct (HQ q2 Hq12 q3 Hq23) as [[]|]; [left|right]. }\n    eapply rtc_inv_r in Hq12 as [<-|(qm & Hq1m & Hqm2)].\n    { by right. }\n    by destruct (HQ qm Hq1m q2 Hqm2) as [[]|]; [left|right].\n  - intros p1 p2 q1 Hp12 HQ. \n    eapply reflexive.branching.b_apart_step; [by eapply WithRefl_can_step|].\n    intros q2 Hq12 q3 Hq23.\n    rewrite <- WithRefl_rtc_can_step in Hq12.\n    rewrite <- WithRefl_can_step_loud in Hq23.\n    by destruct (HQ q2 Hq12 q3 Hq23); [left|right].\nQed.\n\nTheorem refl_to_nonrefl : ∀ p q, r_b_apart p q → nr_sb_apart p q.\nProof. eapply reflexive.branching.b_apart_strong_ind'; [eauto with hints|intros [] p1 p2 q1 Hp12 HQ].\n  - assert (rtc (@can_step X WithRefl silent) q1 q1) as Hq11 by eauto with steps.\n    assert (@can_step X WithRefl silent q1 q1) as Hq11' by by right.\n    destruct (HQ q1 Hq11 q1 Hq11'); try done.\n    destruct Hp12 as [Hp12|[_ <-]]; [|done].\n    eapply sb_apart_silent; try done. \n    intros q2 Hq12 q3 Hq23.\n    rewrite WithRefl_rtc_can_step in Hq12.\n    eapply WithRefl_can_step in Hq23. \n    assert (rtc (@can_step X WithRefl silent) q1 q3) as Hq13 by eauto with steps.\n    assert (@can_step X WithRefl silent q3 q3) as Hq33' by by right.\n    destruct (HQ q3 Hq13 q3 Hq33') as [|]; [|by right].\n    destruct (HQ q2 Hq12 q3 Hq23) as [|]; [left|right]; eauto with hints.\n  - eapply WithRefl_can_step_loud in Hp12.\n    eapply sb_apart_loud; try done. \n    intros q2 Hq12 q3 Hq23.\n    rewrite WithRefl_rtc_can_step in Hq12.\n    eapply WithRefl_can_step_loud in Hq23.\n    by destruct (HQ q2 Hq12 q3 Hq23) as [|]; [left|right].\nQed.\n\nEnd NonreflVsRefl.", "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/reflexive_closure_b.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.2858960144137968}}
{"text": "From iris.proofmode Require Import base proofmode classes.\nFrom iris.base_logic.lib Require Export fancy_updates.\nFrom iris.algebra Require Import excl.\nFrom iris.bi Require Export weakestpre fixpoint big_op.\nFrom iris.prelude Require Import options.\nFrom iris.base_logic.lib Require Export ghost_map invariants.\n\nFrom self.prelude Require Import stdpp_ext iris_ext.\nFrom self.program_logic Require Export exec weakestpre.\nFrom self.prob_lang Require Import\n  primitive_laws class_instances spec_ra tactics notation erasure\n  metatheory lang.\nFrom self.prob Require Export couplings distribution.\nImport uPred.\n\nSection adequacy.\n  Context `{!prelocGS Σ}.\n\n  Lemma refRcoupl_dbind' `{Countable A, Countable A', Countable B, Countable B'}\n    (f : A → distr A') (g : B → distr B') (μ1 : distr A) (μ2 : distr B) (R : A → B → Prop) (T : A' → B' → Prop) n :\n    ⌜refRcoupl μ1 μ2 R⌝ -∗\n    (∀ a b, ⌜R a b⌝ ={∅}▷=∗^(S n) ⌜refRcoupl (f a) (g b) T⌝) -∗\n    |={∅}▷=>^(S n) ⌜refRcoupl (dbind f μ1) (dbind g μ2) T⌝ : iProp Σ.\n  Proof.\n    iIntros (HR) \"H\".\n    iApply (step_fupdN_mono _ _ _ (⌜(∀ a b, R a b → refRcoupl (f a) (g b) T)⌝)).\n    { iIntros (?). iPureIntro. by eapply refRcoupl_dbind. }\n    iIntros (???) \"/=\".\n    iMod (\"H\" with \"[//]\"); auto.\n  Qed.\n\n  Lemma exec_coupl_erasure (e1 : expr) (σ1 : state) (e1' : expr) (σ1' : state) (n : nat) φ :\n    to_val e1 = None →\n    exec_coupl e1 σ1 e1' σ1' (λ '(e2, σ2) '(e2', σ2'),\n        |={∅}▷=>^(S n) ⌜refRcoupl (exec_val n (e2, σ2)) (lim_exec_val (e2', σ2')) φ⌝)\n    ⊢ |={∅}▷=>^(S n) ⌜refRcoupl (exec_val (S n) (e1, σ1)) (lim_exec_val (e1', σ1')) φ⌝.\n  Proof.\n    iIntros (Hv) \"Hexec\".\n    iAssert (⌜to_val e1 = None⌝)%I as \"-#H\"; [done|]. iRevert \"Hexec H\".\n    rewrite /exec_coupl /exec_coupl'.\n    set (Φ := (λ '((e1, σ1), (e1', σ1')),\n                (⌜to_val e1 = None⌝ ={∅}▷=∗^(S n)\n                 ⌜refRcoupl (exec_val (S n) (e1, σ1))\n                            (lim_exec_val (e1', σ1')) φ⌝)%I) :\n           prodO cfgO cfgO → iPropI Σ).\n    assert (NonExpansive Φ).\n    { intros m ((?&?)&(?&?)) ((?&?)&(?&?)) [[[=] [=]] [[=] [=]]]. by simplify_eq. }\n    set (F := (exec_coupl_pre (λ '(e2, σ2) '(e2', σ2'),\n                   |={∅}▷=>^(S n) ⌜refRcoupl (exec_val n (e2, σ2))\n                     (lim_exec_val (e2', σ2')) φ⌝)%I)).\n    iPoseProof (least_fixpoint_iter F Φ with \"[]\") as \"H\"; last first.\n    { iIntros \"Hfix %\". by iMod (\"H\" $! ((_, _), (_, _)) with \"Hfix [//]\"). }\n    clear.\n    iIntros \"!#\" ([[e1 σ1] [e1' σ1']]). rewrite /exec_coupl_pre.\n    iIntros \"[(%R & % & %Hcpl & H) | [(%R & % & %Hcpl & H) | [(%R & %m & %Hcpl & H) | [H | [H | H]]]]] %Hv\".\n    - rewrite exec_val_Sn_not_val; [|done].\n      rewrite lim_exec_val_prim_step.\n      destruct (to_val e1') eqn:Hv'.\n      + destruct (decide (prim_step e1 σ1 = dzero)) as [Hs|].\n        * rewrite /= Hs dbind_dzero.\n          do 3 iModIntro. iApply step_fupdN_intro; [done|].\n          iModIntro. iPureIntro.\n          apply refRcoupl_dzero.\n        * assert (prim_step e1' σ1' = dzero) as Hz by by apply val_stuck_dzero.\n          rewrite /= (val_stuck_dzero e1') in Hcpl; [|eauto].\n          by apply Rcoupl_dzero_r_inv in Hcpl.\n      + rewrite prim_step_or_val_no_val; [|done].\n        iApply (refRcoupl_dbind' _ _ _ _ R).\n        { iPureIntro. by apply Rcoupl_refRcoupl. }\n        iIntros ([] [] HR). by iMod (\"H\" with \"[//]\").\n    - rewrite exec_val_Sn_not_val; [|done].\n      rewrite -(dret_id_left (lim_exec_val)).\n      iApply refRcoupl_dbind'.\n      { iPureIntro. apply Rcoupl_pos_R in Hcpl. by apply Rcoupl_refRcoupl. }\n      iIntros ([] [] (?&?& [= -> ->]%dret_pos)).\n      by iMod (\"H\"  with \"[//]\").\n    - rewrite -(dret_id_left (exec_val _)).\n      rewrite (lim_exec_val_exec m).\n      iApply refRcoupl_dbind'.\n      { iPureIntro. apply Rcoupl_pos_R in Hcpl. by apply Rcoupl_refRcoupl. }\n      iIntros ([] [] (?& [= -> ->]%dret_pos &?)).\n      by iMod (\"H\"  with \"[//] [//]\").\n    - iDestruct (big_orL_mono _ (λ _ _,\n                     |={∅}▷=>^(S n)\n                       ⌜refRcoupl (exec_val (S n) (e1, σ1))\n                                  (lim_exec_val (e1', σ1')) φ⌝)%I\n                  with \"H\") as \"H\".\n      { iIntros (i α Hα%elem_of_list_lookup_2) \"(% & % & %Hcpl & H)\".\n        iApply (step_fupdN_mono _ _ _\n                  (⌜∀ e2 σ2 σ2', R2 (e2, σ2) σ2' → refRcoupl (exec_val n (e2, σ2))\n                                                             (lim_exec_val (e1', σ2')) φ⌝)%I).\n        - iIntros (?). iPureIntro.\n          rewrite /= /get_active in Hα.\n          apply elem_of_elements, elem_of_dom in Hα as [].\n          eapply refRcoupl_erasure_r; eauto.\n        - iIntros (????). by iMod (\"H\" with \"[//]\"). }\n      iInduction (language.get_active σ1') as [| α'] \"IH\"; [done|].\n      rewrite big_orL_cons.\n      iDestruct \"H\" as \"[H | Ht]\"; [done|].\n      by iApply \"IH\".\n    - iDestruct (big_orL_mono _ (λ _ _,\n                     |={∅}▷=>^(S n)\n                       ⌜refRcoupl (exec_val (S n) (e1, σ1))\n                                  (lim_exec_val (e1', σ1')) φ⌝)%I\n                  with \"H\") as \"H\".\n      { iIntros (i α' Hα'%elem_of_list_lookup_2) \"(% & %Hcpl & H)\".\n        iApply (step_fupdN_mono _ _ _\n                  (⌜∀ σ2 e2' σ2', R2 σ2 (e2', σ2') → refRcoupl (exec_val (S n) (e1, σ2))\n                                                               (lim_exec_val (e2', σ2')) φ⌝)%I).\n        - iIntros (?). iPureIntro.\n          rewrite /= /get_active in Hα'.\n          apply elem_of_elements, elem_of_dom in Hα' as [].\n          eapply refRcoupl_erasure_l; eauto.\n        - iIntros (????). by iMod (\"H\" with \"[//] [//]\"). }\n      iInduction (language.get_active σ1) as [| α'] \"IH\"; [done|].\n      rewrite big_orL_cons.\n      iDestruct \"H\" as \"[H | Ht]\"; [done|].\n      by iApply \"IH\".\n    - rewrite exec_val_Sn_not_val; [|done].\n      iDestruct (big_orL_mono _ (λ _ _,\n                     |={∅}▷=>^(S n)\n                       ⌜refRcoupl (prim_step e1 σ1 ≫= exec_val n)\n                                  (lim_exec_val (e1', σ1')) φ⌝)%I\n                  with \"H\") as \"H\".\n      { iIntros (i [α1 α2] [Hα1 Hα2]%elem_of_list_lookup_2%elem_of_list_prod_1) \"(% & %Hcpl & H)\".\n        rewrite -exec_val_Sn_not_val; [|done].\n        iApply (step_fupdN_mono _ _ _\n                  (⌜∀ σ2 σ2', R2 σ2 σ2' → refRcoupl (exec_val (S n) (e1, σ2))\n                                                    (lim_exec_val (e1', σ2')) φ⌝)%I).\n        - iIntros (?). iPureIntro.\n          rewrite /= /get_active in Hα1, Hα2.\n          apply elem_of_elements, elem_of_dom in Hα1 as [], Hα2 as [].\n          eapply refRcoupl_erasure; eauto.\n        - iIntros (???). by iMod (\"H\" with \"[//] [//]\"). }\n      iInduction (list_prod (language.get_active σ1) (language.get_active σ1'))\n        as [| [α α']] \"IH\"; [done|].\n      rewrite big_orL_cons.\n      iDestruct \"H\" as \"[H | Ht]\"; [done|].\n      by iApply \"IH\".\n  Qed.\n\n  Theorem wp_refRcoupl_step_fupdN (e e' : expr) (σ σ' : state) n φ :\n    state_interp σ ∗ spec_interp (e', σ') ∗ spec_ctx ∗ WP e {{ v, ∃ v', ⤇ Val v' ∗ ⌜φ v v'⌝ }} ⊢\n    |={⊤,∅}=> |={∅}▷=>^n ⌜refRcoupl (exec_val n (e, σ)) (lim_exec_val (e', σ')) φ⌝.\n  Proof.\n    iInduction n as [|n] \"IH\" forall (e σ e' σ'); iIntros \"([Hh Ht] & HspecI_auth & #Hctx & Hwp)\".\n    - rewrite /exec_val /=.\n      destruct (to_val e) eqn:Heq.\n      + apply of_to_val in Heq as <-.\n        rewrite wp_value_fupd.\n        iMod \"Hwp\" as (v') \"[Hspec_frag %]\".\n        iInv specN as (ρ e0 σ0 n) \">(HspecI_frag & %Hexec & Hspec_auth & Hstate)\" \"_\".\n        iDestruct (spec_interp_auth_frag_agree with \"HspecI_auth HspecI_frag\") as %<-.\n        iDestruct (spec_prog_auth_frag_agree with \"Hspec_auth Hspec_frag\") as %->.\n        iApply fupd_mask_intro; [set_solver|]; iIntros \"_\".\n        erewrite lim_exec_val_exec_det; [|done].\n        iPureIntro.\n        rewrite /dmap.\n        by apply refRcoupl_dret.\n      + iApply fupd_mask_intro; [set_solver|]; iIntros \"_\".\n        iPureIntro.\n        apply refRcoupl_dzero.\n    - rewrite exec_val_Sn /prim_step_or_val /=.\n      destruct (to_val e) eqn:Heq.\n      + apply of_to_val in Heq as <-.\n        rewrite wp_value_fupd.\n        iMod \"Hwp\" as (v') \"[Hspec_frag %]\".\n        iInv specN as (ξ ρ e0 σ0) \">(HspecI_frag & %Hexec & Hspec_auth & Hstate)\" \"_\".\n        iDestruct (spec_interp_auth_frag_agree with \"HspecI_auth HspecI_frag\") as %<-.\n        iDestruct (spec_prog_auth_frag_agree with \"Hspec_auth Hspec_frag\") as %->.\n        iApply fupd_mask_intro; [set_solver|]; iIntros \"_\".\n        iApply step_fupdN_intro; [done|]. do 4 iModIntro.\n        iPureIntro.\n        rewrite exec_val_unfold dret_id_left /=.\n        erewrite lim_exec_val_exec_det; [|done].\n        by apply refRcoupl_dret.\n      + rewrite wp_unfold /wp_pre /= Heq.\n        iMod (\"Hwp\" with \"[$]\") as \"Hcpl\".\n        iModIntro.\n        iPoseProof\n          (exec_coupl_mono _ (λ '(e2, σ2) '(e2', σ2'), |={∅}▷=>^(S n)\n             ⌜refRcoupl (exec_val n (e2, σ2)) (lim_exec_val (e2', σ2')) φ⌝)%I\n            with \"[] Hcpl\") as \"H\".\n        { iIntros ([] []) \"H !> !>\".\n          iMod \"H\" as \"(Hstate & HspecI_auth & Hwp)\".\n          iMod (\"IH\" with \"[$]\") as \"H\".\n          iModIntro. done. }\n        rewrite -exec_val_Sn_not_val; [|done].\n        by iApply (exec_coupl_erasure with \"H\").\n  Qed.\n\nEnd adequacy.\n\nClass prelocGpreS Σ := PrelocGpreS {\n  prelocGpreS_iris  :> invGpreS Σ;\n  prelocGpreS_heap  :> ghost_mapG Σ loc val;\n  prelocGpreS_tapes :> ghost_mapG Σ loc (list bool);\n  prelocGpreS_cfg   :> inG Σ (authUR cfgUR);\n  prelocGpreS_prog  :> inG Σ (authR progUR);\n}.\n\nDefinition prelocΣ : gFunctors :=\n  #[invΣ; ghost_mapΣ loc val; ghost_mapΣ loc (list bool);\n    GFunctor (authUR cfgUR); GFunctor (authUR progUR)].\nGlobal Instance subG_prelocGPreS {Σ} : subG prelocΣ Σ → prelocGpreS Σ.\nProof. solve_inG. Qed.\n\nTheorem wp_refRcoupl Σ `{prelocGpreS Σ} (e e' : expr) (σ σ' : state) n φ :\n  (∀ `{prelocGS Σ}, ⊢ spec_ctx -∗ ⤇ e' -∗ WP e {{ v, ∃ v', ⤇ Val v' ∗ ⌜φ v v'⌝ }}) →\n  refRcoupl (exec_val n (e, σ)) (lim_exec_val (e', σ')) φ.\nProof.\n  intros Hwp.\n  eapply (step_fupdN_soundness_no_lc _ n 0).\n  iIntros (Hinv) \"_\".\n  iMod (ghost_map_alloc σ.(heap)) as \"[%γH [Hh _]]\".\n  iMod (ghost_map_alloc σ.(tapes)) as \"[%γT [Ht _]]\".\n  iMod (ghost_map_alloc σ'.(heap)) as \"[%γHs [Hh_spec _]]\".\n  iMod (ghost_map_alloc σ'.(tapes)) as \"[%γTs [Ht_spec _]]\".\n  iMod (own_alloc ((● (Excl' (e', σ'))) ⋅ (◯ (Excl' (e', σ'))))) as \"(%γsi & Hsi_auth & Hsi_frag)\".\n  { by apply auth_both_valid_discrete. }\n  iMod (own_alloc ((● (Excl' e')) ⋅ (◯ (Excl' e')))) as \"(%γp & Hprog_auth & Hprog_frag)\".\n  { by apply auth_both_valid_discrete. }\n  set (HspecGS := CfgSG Σ _ γsi _ γp _ _ γHs γTs).\n  set (HprelocGS := HeapG Σ _ _ _ γH γT HspecGS).\n  iMod (inv_alloc specN ⊤ spec_inv with \"[Hsi_frag Hprog_auth Hh_spec Ht_spec]\") as \"#Hctx\".\n  { iModIntro. iExists _, _, _, O. iFrame. rewrite exec_O dret_1_1 //. }\n  iApply wp_refRcoupl_step_fupdN.\n  iFrame. iFrame \"Hctx\".\n  by iApply (Hwp with \"[Hctx] [Hprog_frag]\").\nQed.\n", "meta": {"author": "logsem", "repo": "clutch", "sha": "35144f9b1fe9c913b4bd24106a12ac7f02b20ec5", "save_path": "github-repos/coq/logsem-clutch", "path": "github-repos/coq/logsem-clutch/clutch-35144f9b1fe9c913b4bd24106a12ac7f02b20ec5/theories/prob_lang/adequacy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.285859508239037}}
{"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 PendingCheckAux.Spec.\nRequire Import RVIC4.Spec.\n\nLocal Open Scope Z_scope.\n\nSection SpecLow.\n\n  Definition check_pending_ptimers_spec0 (rec: Pointer) (adt: RData) : option RData :=\n    match rec with\n    | (_rec_base, _rec_ofst) =>\n      when'' _g_rec_base, _g_rec_ofst == get_rec_g_rec_spec (_rec_base, _rec_ofst) adt;\n      rely is_int _g_rec_ofst;\n      when' _cntp_ctl == sysreg_read_spec 32 adt;\n      rely is_int64 _cntp_ctl;\n      when'' _t'6_base, _t'6_ofst == get_rec_ptimer_spec (_rec_base, _rec_ofst) adt;\n      rely is_int _t'6_ofst;\n      when _t'7, adt == check_timer_became_asserted_spec (_t'6_base, _t'6_ofst) (VZ64 _cntp_ctl) adt;\n      rely is_int _t'7;\n      if (_t'7 =? 1) then\n        when adt == granule_lock_spec (_g_rec_base, _g_rec_ofst) adt;\n        rely is_int64 (Z.lor _cntp_ctl 2);\n        let _cntp_ctl := (Z.lor _cntp_ctl 2) in\n        when adt == sysreg_write_spec 32 (VZ64 _cntp_ctl) adt;\n        when' _t'3 == get_rec_sysregs_spec (_rec_base, _rec_ofst) 69 adt;\n        rely is_int64 _t'3;\n        rely is_int64 (Z.land _t'3 18446744073709549567);\n        when adt == set_rec_sysregs_spec (_rec_base, _rec_ofst) 69 (VZ64 (Z.land _t'3 18446744073709549567)) adt;\n        when' _t'4 == get_rec_sysregs_spec (_rec_base, _rec_ofst) 69 adt;\n        rely is_int64 _t'4;\n        when adt == sysreg_write_spec 69 (VZ64 _t'4) adt;\n        when adt == set_rec_ptimer_asserted_spec (_rec_base, _rec_ofst) 1 adt;\n        when'' _t'5_base, _t'5_ofst == get_rec_rvic_spec (_rec_base, _rec_ofst) adt;\n        rely is_int _t'5_ofst;\n        when adt == rvic_set_pending_spec (_t'5_base, _t'5_ofst) (VZ64 30) adt;\n        when adt == granule_unlock_spec (_g_rec_base, _g_rec_ofst) adt;\n        Some adt\n      else\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/PendingCheck/LowSpecs/check_pending_ptimers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584175139669998, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2857409971639399}}
{"text": "Require Import Ctl.Paths.\nRequire Import Ctl.Definition.\nRequire Import Ctl.Basic.\nOpen Scope tprop_scope.\n\nRequire Import Glib.Glib.\n\nLtac tentails :=\n  match goal with \n  | |- ?R @?s ⊨ ⟦?P⟧   => change (P s)\n  | |- ?R @?s ⊭ ⟦?P⟧   => change (~ P s)\n  | |- ?R @?s ⊨ !⟦?P⟧ => change (~ P s)\n  end.\n\nTactic Notation \"tentails!\" :=\n  cbn;\n  repeat match goal with \n  | |- ?R @?s ⊨ ?P => unfold P\n  | |- ?R @?s ⊭ ?P => unfold P\n  | |- ?R @?s ⊨ ! ?P => unfold P\n  end;\n  tentails;\n  cbn.\n\nTactic Notation \"tentails\" \"in\" hyp(H) :=\n  change (?R @?s ⊨ ⟦?P⟧)   with (P s) in H +\n  change (?R @?s ⊭ ⟦?P⟧)   with (~ P s) in H +\n  change (?R @?s ⊨ !⟦?P⟧) with (~ P s) in H.\n\nTactic Notation \"tentails!\" \"in\" hyp(H) :=\n  cbn in H;\n  repeat match type of H with \n  | ?R @?s ⊨ ?P => unfold P in H\n  | ?R @?s ⊭ ?P => unfold P in H\n  | ?R @?s ⊨ ! ?P => unfold P in H\n  end;\n  progress tentails in H;\n  cbn in H.\n\nTactic Notation \"tentails\" \"in\" \"*\" :=\n  try tentails;\n  repeat find (fun H => tentails in H).\n\nTactic Notation \"tentails!\" \"in\" \"*\" :=\n  try tentails!;\n  repeat find (fun H => tentails! in H).\n\nTactic Notation \"unfold_timpl\" :=\n  progress change_no_check (?R @?s ⊨ ?p ⇾ ?q) with (R @s ⊨ p -> R @s ⊨ q) +\n  rewrite rew_timpl +\n  setoid_rewrite rew_timpl.\nTactic Notation \"unfold_timpl\" \"in\" hyp(H) :=\n  progress change_no_check (?R @?s ⊨ ?p ⇾ ?q) with (R @s ⊨ p -> R @s ⊨ q) in H +\n  rewrite rew_timpl in H +\n  setoid_rewrite rew_timpl in H.\n\nTactic Notation \"unfold_tnot\" :=\n  progress change_no_check (?R @?s ⊨ !?P) with (R @s ⊭ P) +\n  rewrite rew_tnot +\n  setoid_rewrite rew_tnot.\nTactic Notation \"unfold_tnot\" \"in\" hyp(H) :=\n  progress change_no_check (?R @?s ⊨ !?P) with (R @s ⊭ P) in H +\n  rewrite rew_tnot in H +\n  setoid_rewrite rew_tnot in H.\n\nTactic Notation \"unfold_tconj\" := \n  progress change_no_check (?R @?s ⊨ ?P && ?Q) with (R @s ⊨ P /\\ R @s ⊨ Q) +\n  rewrite rew_tconj +\n  setoid_rewrite rew_tconj.\nTactic Notation \"unfold_tconj\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ ?P && ?Q) with (R @s ⊨ P /\\ R @s ⊨ Q) in H +\n  rewrite rew_tconj in H +\n  setoid_rewrite rew_tconj in H.\n\nTactic Notation \"unfold_tdisj\" := \n  progress change_no_check (?R @?s ⊨ ?P || ?Q) with (R @s ⊨ P \\/ R @s ⊨ Q) +\n  rewrite rew_tdisj +\n  setoid_rewrite rew_tdisj.\nTactic Notation \"unfold_tdisj\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ ?P || ?Q) with (R @s ⊨ P \\/ R @s ⊨ Q) in H +\n  rewrite rew_tdisj in H +\n  setoid_rewrite rew_tdisj in H.\n\nTactic Notation \"unfold_tbiimpl\" := \n  progress change_no_check (?R @?s ⊨ ?P ⇿ ?Q) with (R @s ⊨ P <-> R @s ⊨ Q) +\n  rewrite rew_tbiimpl +\n  setoid_rewrite rew_tbiimpl.\nTactic Notation \"unfold_tbiimpl\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ ?P ⇿ ?Q) with (R @s ⊨ P <-> R @s ⊨ Q) in H +\n  rewrite rew_tbiimpl in H +\n  setoid_rewrite rew_tbiimpl in H.\n\nTactic Notation \"unfold_tlift\" := \n  progress change_no_check (?R @?s ⊨ ⟦?P⟧) with (P s) +\n  rewrite rew_tlift +\n  setoid_rewrite rew_tlift.\nTactic Notation \"unfold_tlift\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ ⟦?P⟧) with (P s) in H +\n  rewrite rew_tlift in H +\n  setoid_rewrite rew_tlift in H.\n\nTactic Notation \"unfold_AX\" := \n  progress change_no_check (?R @?s ⊨ AX ?P) with (forall s', R s s' -> R @s' ⊨ P) +\n  rewrite rew_AX +\n  setoid_rewrite rew_AX.\nTactic Notation \"unfold_AX\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ AX ?P) with (forall s', R s s' -> R @s' ⊨ P) in H +\n  rewrite rew_AX in H +\n  setoid_rewrite rew_AX in H.\n\nTactic Notation \"unfold_EX\" := \n  progress change_no_check (?R @?s ⊨ EX ?P) with (exists s', R s s' /\\ R @s' ⊨ P) +\n  rewrite rew_EX +\n  setoid_rewrite rew_EX.\nTactic Notation \"unfold_EX\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ EX ?P) with (exists s', R s s' /\\ R @s' ⊨ P) in H +\n  rewrite rew_EX in H +\n  setoid_rewrite rew_EX in H.\n\nTactic Notation \"unfold_AG\" := \n  progress change_no_check (?R @?s ⊨ AG ?P) with \n    (forall (p: path R s) s', in_path s' p -> R @s' ⊨ P) +\n  rewrite rew_AG +\n  setoid_rewrite rew_AG.\nTactic Notation \"unfold_AG\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ AG ?P) with \n    (forall (p: path R s) s', in_path s' p -> R @s' ⊨ P) in H +\n  rewrite rew_AG in H +\n  setoid_rewrite rew_AG in H.\n\nTactic Notation \"unfold_EG\" := \n  progress change_no_check (?R @?s ⊨ EG ?P) with \n    (exists p: path R s, forall s', in_path s' p -> R @s' ⊨ P) +\n  rewrite rew_EG +\n  setoid_rewrite rew_EG.\nTactic Notation \"unfold_EG\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ EG ?P) with \n    (exists p: path R s, forall s', in_path s' p -> R @s' ⊨ P) in H +\n  rewrite rew_EG in H +\n  setoid_rewrite rew_EG in H.\n\nTactic Notation \"unfold_AF\" := \n  progress change_no_check (?R @?s ⊨ AF ?P) with \n    (forall p: path R s, exists s', in_path s' p /\\ R @s' ⊨ P) +\n  rewrite rew_AF +\n  setoid_rewrite rew_AF.\nTactic Notation \"unfold_AF\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ AF ?P) with \n    (forall p: path R s, exists s', in_path s' p /\\ R @s' ⊨ P) in H +\n  rewrite rew_AF in H +\n  setoid_rewrite rew_AF in H.\n\nTactic Notation \"unfold_EF\" := \n  progress change_no_check (?R @?s ⊨ EF ?P) with \n    (exists (p: path R s) s', in_path s' p /\\ R @s' ⊨ P) +\n  rewrite rew_EF +\n  setoid_rewrite rew_EF.\nTactic Notation \"unfold_EF\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ EF ?P) with \n    (exists (p: path R s) s', in_path s' p /\\ R @s' ⊨ P) in H +\n  rewrite rew_EF in H +\n  setoid_rewrite rew_EF in H.\n\nTactic Notation \"unfold_AU\" := \n  progress change_no_check (?R @?s ⊨ A[?P U ?Q]) with \n    (forall p: path R s, exists i,\n      (forall x, in_path_before x i p -> R @x ⊨ P) /\\ \n      R @(p i) ⊨ Q) +\n  rewrite rew_AU +\n  setoid_rewrite rew_AU.\nTactic Notation \"unfold_AU\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ A[?P U ?Q]) with \n    (forall p: path R s, exists i,\n      (forall x, in_path_before x i p -> R @x ⊨ P) /\\ \n      R @(p i) ⊨ Q) +\n  rewrite rew_AU in H +\n  setoid_rewrite rew_AU in H.\n\nTactic Notation \"unfold_EU\" := \n  progress change_no_check (?R @?s ⊨ E[?P U ?Q]) with \n    (exists (p: path R s) i,\n      (forall x, in_path_before x i p -> R @x ⊨ P) /\\ \n      R @(p i) ⊨ Q) +\n  rewrite rew_EU +\n  setoid_rewrite rew_EU.\nTactic Notation \"unfold_EU\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ E[?P U ?Q]) with \n    (exists (p: path R s) i,\n      (forall x, in_path_before x i p -> R @x ⊨ P) /\\ \n      R @(p i) ⊨ Q) +\n  rewrite rew_EU in H +\n  setoid_rewrite rew_EU in H.\n\nTactic Notation \"unfold_AW\" := \n  progress change_no_check (?R @?s ⊨ A[?P W ?Q]) with \n    (forall p: path R s,\n      (forall x, in_path x p -> R @x ⊨ P && !Q) \\/\n      (exists i,\n        (forall x, in_path_before x i p -> R @x ⊨ P) /\\ \n        R @(p i) ⊨ Q)) +\n  rewrite rew_AW +\n  setoid_rewrite rew_AW.\nTactic Notation \"unfold_AW\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ A[?P W ?Q]) with \n    (forall p: path R s,\n      (forall x, in_path x p -> R @x ⊨ P && !Q) \\/\n      (exists i,\n        (forall x, in_path_before x i p -> R @x ⊨ P) /\\ \n        R @(p i) ⊨ Q)) in H +\n  rewrite rew_AW in H +\n  setoid_rewrite rew_AW in H.\n \n\n(* tintro - intro a timpl *)\n\nTactic Notation \"tintro\" := \n  match goal with\n  | |- _ @_ ⊨ !_ => unfold_tnot; intro\n  | |- _ @_ ⊨ _ ⇾ _ => unfold_timpl; intro\n  end.\n\nTactic Notation \"tintro\" ident(x) := \n  match goal with\n  | |- _ @_ ⊨ !_ => unfold_tnot; intro x\n  | |- _ @_ ⊨ _ ⇾ _ => unfold_timpl; intro x\n  end.\n\nTactic Notation \"tintros\" :=\n  repeat tintro.\nTactic Notation \"tintros\" ident(x1) :=\n  tintro x1.\nTactic Notation \"tintros\" ident(x1) ident(x2) :=\n  tintro x1; tintros x2.\nTactic Notation \"tintros\" ident(x1) ident(x2) ident(x3) :=\n  tintro x1; tintros x2 x3.\nTactic Notation \"tintros\" ident(x1) ident(x2) ident(x3) ident(x4) :=\n  tintro x1; tintros x2 x3 x4.\nTactic Notation \"tintros\" ident(x1) ident(x2) ident(x3) ident(x4) ident(x5) :=\n  tintro x1; tintros x2 x3 x4 x5.\nTactic Notation \"tintros\" ident(x1) ident(x2) ident(x3) ident(x4) ident(x6) :=\n  tintro x1; tintros x2 x3 x4 x5 x6.\n\n\n(* tsimpl - simple a tprop *)\n\n(* Remove AX? May go on forever *)\nTactic Notation \"tsimpl_step\" :=\n  unfold_timpl +\n  unfold_tbiimpl +\n  unfold_tnot +\n  unfold_AX +\n  unfold_EX +\n  unfold_AG +\n  unfold_EG +\n  unfold_AF +\n  unfold_EF +\n  unfold_AU + \n  unfold_EU +\n  unfold_AW.\n\nTactic Notation \"tsimpl_step\" \"in\" hyp(H) :=\n  unfold_timpl in H +\n  unfold_tbiimpl in H +\n  unfold_tnot in H +\n  unfold_AX in H +\n  unfold_EX in H +\n  unfold_AG in H +\n  unfold_EG in H +\n  unfold_AF in H +\n  unfold_EF in H +\n  unfold_AU in H +\n  unfold_EU in H + \n  unfold_AW in H.\n\nTactic Notation \"tsimpl\" := repeat tsimpl_step.\nTactic Notation \"tsimpl\" \"in\" hyp(H) := repeat tsimpl_step in H.\nTactic Notation \"tsimpl\" \"in\" \"*\" :=\n  try tsimpl;\n  repeat match goal with \n  | H: _ @_ ⊨ _ |- _ => tsimpl in H\n  end.\n\n(* tapply: carefully unfolds TProp hypothesis just enough to use apply *)\n\nLtac _tapply_unfold_step H :=\n  match type of H with \n  | _ @_ ⊨ _ ⇾ _ => \n      unfold_timpl in H\n  | _ @_ ⊨ !_ =>\n      unfold_tnot in H\n  | _ @_ ⊨ _ ⇿ _ =>\n      unfold_tbiimpl in H\n  | _ @_ ⊨ AX _ =>\n      unfold_AX in H\n  | _ @_ ⊨ AG _ => \n      unfold_AG in H\n  end + \n  unfold_timpl in H +\n  unfold_tnot in H +\n  unfold_tbiimpl in H +\n  unfold_AX in H +\n  unfold_AG in H.\n\nLtac _tapply_aux H :=\n  apply H + (_tapply_unfold_step H; _tapply_aux H).\n\nLtac _tapply_aux_in H H2 :=\n  apply H in H2 + (_tapply_unfold_step H; _tapply_aux_in H H2).\n\nLtac _etapply_aux H :=\n  eapply H + (_tapply_unfold_step H; _etapply_aux H).\n\nLtac _etapply_aux_in H H2 :=\n  eapply H in H2 + (_tapply_unfold_step H; _etapply_aux_in H H2).\n\n\nTactic Notation \"tapply\" uconstr(c) :=\n  let Htemp := fresh in \n  eset (Htemp := c);\n  _tapply_aux Htemp;\n  clear Htemp.\n\nTactic Notation \"tapply\" uconstr(c) \"in\" hyp(H) :=\n  let Htemp := fresh in \n  eset (Htemp := c);\n  _tapply_aux_in Htemp H;\n  clear Htemp.\n\nTactic Notation \"etapply\" uconstr(c) :=\n  let Htemp := fresh in \n  eset (Htemp := c);\n  _etapply_aux Htemp;\n  clear Htemp.\n\nTactic Notation \"etapply\" uconstr(c) \"in\" hyp(H) :=\n  let Htemp := fresh in \n  eset (Htemp := c);\n  _etapply_aux_in Htemp H;\n  clear Htemp.\n\nTactic Notation \"tapplyc\" hyp(H) :=\n  tapply H; clear H.\nTactic Notation \"tapplyc\" hyp(H) \"in\" hyp(H2) :=\n  tapply H in H2; clear H.\nTactic Notation \"etapplyc\" hyp(H) :=\n  etapply H; clear H.\nTactic Notation \"etapplyc\" hyp(H) \"in\" hyp(H2) :=\n  etapply H in H2; clear H.\n\nTactic Notation \"tcut\" uconstr(P) :=\n  match goal with \n  | |- ?R @?s ⊨ ?Q =>\n      cut (R @s ⊨ P); [change (R @s ⊨ P ⇾ Q)| ]\n  end.\n\nTactic Notation \"tforward\" hyp(H):=\n  match type of H with \n  | ?R @?s ⊨ ?P ⇾ ?Q =>\n      let _temp := fresh in\n      define (R @s ⊨ P) as _temp;\n      [ |\n        specialize (H _temp); \n        unfold _temp in H;\n        clear _temp\n      ]\n end.\n\nTactic Notation \"tforward\" hyp(H) \"by\" tactic3(tac) :=\n  tforward H; [solve [tac]| ].\n\nClose Scope tprop_scope.", "meta": {"author": "ku-sldg", "repo": "CTL", "sha": "75bb188ae2689baeb28d34a789fe839871c240fe", "save_path": "github-repos/coq/ku-sldg-CTL", "path": "github-repos/coq/ku-sldg-CTL/CTL-75bb188ae2689baeb28d34a789fe839871c240fe/Ctl/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.28574098552862176}}
{"text": "\nRequire Import FiatFormal.Language.Step.\nRequire Import FiatFormal.Language.SubstExpExp.\nRequire Import FiatFormal.Language.SubstTypeExp.\nRequire Import FiatFormal.Language.SubstTypeType.\nRequire Import FiatFormal.Language.TyJudge.\n\n\nLemma In_Context :\n  forall C Val x,\n    exps_ctx Val C\n    -> @In exp x (C x).\nProof.\n  intros.\n  induction H; auto.\nQed.\n\n\nLemma canonicalFormTFun :\n  forall ds ke te t1 t2 x,\n    TYPE ds ke te x (TFun t1 t2)\n    -> value x\n    -> exists x', x = (XFix t1 t2 x').\nProof.\n  intros. gen ds ke te t1 t2 H0.\n  induction x using exp_mutind\n    with (PA := fun a => a = a); rip; try inverts H0; try nope; try inverts H.\n  exists x; reflexivity.\nQed.\n\n\nLemma canonicalFormTNFun :\n  forall ds ke te tsArgs tRes x,\n    TYPE ds ke te x (TNFun tsArgs tRes)\n    -> value x\n    -> exists x', x = (XNFun tsArgs x').\nProof.\n  intros. gen ds ke te tsArgs tRes H0.\n  induction x using exp_mutind\n    with (PA := fun a => a = a); rip; try inverts H0; try nope; try inverts H.\n  exists x; reflexivity.\nQed.\n\n\nLemma canonicalFormTNProd :\n  forall ds ke te ts x,\n    TYPE ds ke te x (TNProd ts)\n    -> value x\n    -> exists xs, x = (XTup xs).\nProof.\n  intros. gen ds ke te ts H0.\n  induction x using exp_mutind\n    with (PA := fun a => a = a); rip; try inverts H0; try nope; try inverts H.\n  exists (@nil exp); reflexivity.\n  exists (l0 :> x); reflexivity.\nQed.\n\n\nLemma wellTypedProjHasX :\n  forall ds ke te ts t xs n,\n    TYPE ds ke te (XTup xs) (TNProd ts)\n    -> get n ts = Some t\n    -> exists x, get n xs = Some x.\nProof.\n  intros.\n  inverts H.\n  pose proof @get_length_less_exists exp.\n  pose proof(Forall2_length _ _ _ H5).\n  apply get_length_less in H0. rewrite <- H1 in H0.\n  spec H H0. dest x. eauto.\nQed.\n\n\n(* A well typed expression is either a value, can take a step,\n   or contains a choice. *)\nTheorem progress\n  : forall pb ds pbOK x,\n    (exists t, TYPE ds nil nil x t)\n    -> value x \\/ (exists x', STEP pb ds pbOK x x') \\/ hasChoiceX x.\nProof.\n intros. gen pb ds pbOK.\n induction x using exp_mutind with\n     (PA := fun a => a = a);\n   rip; first [destruct H as [tx] | destruct H0 as [tx]];\n     try invert_exp_type; nope.\n\n Case \"XApp\".\n right.\n edestruct IHx1; eauto.\n SCase \"value x1\".\n edestruct IHx2; eauto.\n SSCase \"value x2\".\n pose proof (canonicalFormTFun).\n spec H1 H4. spec H1 H. destruct H1 as [x' LAM]; subst.\n SSSCase \"fix\".\n left; exists (substXX 0 (XFix t11 tx x') (substXX 0 x2 x')). apply EsFixApp. inverts H0; auto.\n destruct H0 as [STx2 | HCx2].\n SSCase \"x2 steps\".\n destruct STx2 as [x2'].\n left; exists (XApp x1 x2'). eauto.\n SSCase \"x2 hasChoice\".\n right; auto.\n destruct H as [STx1 | HCx1].\n SCase \"x1 steps\".\n destruct STx1 as [x1'].\n left; exists (XApp x1' x2).\n eapply (EsContext pb ds pbOK (fun xx => XApp xx x2)); eauto.\n SCase \"x1 hasChoice\".\n right; auto.\n\n Case \"XTup\".\n assert (Forall (fun x => wnfX x \\/ (exists x', STEP pb ds pbOK x x') \\/ hasChoiceX x) xs) as HWS.\n repeat nforall. rip.\n have (exists t, TYPE ds nil nil x t). dest t.\n have (value x \\/ (exists x', STEP pb ds pbOK x x') \\/ hasChoiceX x).\n inverts H2; rip.\n inverts H3; rip.\n (* All ctor args are wnf, or there is a context where one can step *)\n lets D: (@exps_ctx_run exp exp) HWS.\n inverts D.\n (* All ctor args are wnf *)\n left. eauto 6.\n (* There is a context where one ctor arg can step *)\n right.\n dest C. dest x'.\n rip. destruct H3 as [STx' | HCx'].\n left.\n lets D: step_context_XTup_exists H1 STx'.\n destruct D as [x'']. eauto.\n SCase \"hasChoice x\".\n (* nope. *)\n right; apply HcTup.\n apply Exists_exists. exists x'. rip.\n eapply In_Context; eauto.\n\n Case \"XProj\".\n right. assert (exists t, TYPE ds nil nil x t) by eauto.\n destruct (IHx pb ds H pbOK); eauto.\n SCase \"value x\".\n pose proof (canonicalFormTNProd).\n spec H1 H4. spec H1 H0. dest xs; subst.\n left.\n pose proof (wellTypedProjHasX _ _ _ _ _ _ _ H4 H6).\n dest x. exists x. apply EsTupProj; auto.\n inverts H0. inverts H2; auto.\n destruct H0 as [STx | HCx].\n SCase \"x steps\".\n left. dest x'. exists (XProj n x').\n eapply (EsContext pb ds pbOK (fun xx => XProj n xx)); eauto.\n SCase \"x hasChoice\".\n (* nope. *)\n right; auto.\n\n Case \"XNFun\".\n left; eauto.\n\n Case \"XNApp\".\n right. assert (exists t, TYPE ds nil nil x t) by eauto.\n destruct (IHx pb ds H0 pbOK); eauto.\n pose proof (canonicalFormTNFun).\n spec H2 H5. spec H2 H1. dest x'; subst.\n assert (Forall (fun x => wnfX x \\/ (exists x', STEP pb ds pbOK x x') \\/ hasChoiceX x) xs) as HWS.\n\n repeat nforall. rip.\n have (exists t, TYPE ds nil nil x t). dest t.\n have (value x \\/ (exists x', STEP pb ds pbOK x x') \\/ hasChoiceX x).\n inverts H4; rip. inverts H6. auto.\n (* All args are wnf, or there is a context where one can step *)\n lets D: (@exps_ctx_run exp exp) HWS.\n inverts D.\n (* All ctor args are wnf *)\n left. eauto 6.\n (* There is a context where one ctor arg can step *)\n dest C. rename x' into x''. dest x'.\n rip. destruct H6 as [STx' | HCx'].\n left.\n destruct STx'.\n exists (XNApp (XNFun ts x'') (C x)).\n eapply (EsContext pb ds pbOK (fun xx => XNApp (XNFun ts x'') (C xx))).\n apply XcNApp2; eauto. auto.\n SCase \"x' hasChoice\".\n right; apply HcNApp2.\n apply Exists_exists. exists x'. rip.\n eapply In_Context; eauto.\n destruct H1 as [STx | HCx].\n left.\n dest x'.\n exists (XNApp x' xs); eauto.\n eapply (EsContext pb ds pbOK (fun xx => XNApp xx xs)); eauto.\n SCase \"x hasChoice\".\n right; eauto.\n\n Case \"XFix\".\n left; eauto.\n\n Case \"XCon\".\n (* All ctor args are either wnf or can step *)\n assert (Forall (fun x => wnfX x \\/ (exists x', STEP pb ds pbOK x x') \\/ hasChoiceX x) xs) as HWS.\n repeat nforall. rip.\n have (exists t, TYPE ds nil nil x t). dest t.\n have (value x \\/ (exists x', STEP pb ds pbOK x x') \\/ hasChoiceX x).\n inverts H2; rip.\n inverts H6; rip.\n (* All ctor args are wnf, or there is a context where one can step *)\n lets D: (@exps_ctx_run exp exp) HWS.\n inverts D.\n (* All ctor args are wnf *)\n left. eauto 6.\n (* There is a context where one ctor arg can step *)\n right.\n dest C. dest x'.\n rip. destruct H6 as [STx' | HCx'].\n left.\n lets D: step_context_XCon_exists H1 STx'.\n destruct D as [x'']. eauto.\n SCase \"hasChoice x\".\n right; apply HcCon.\n apply Exists_exists. exists x'. rip.\n eapply In_Context; eauto.\n\n Case \"XMatch\".\n right. assert (exists t, TYPE ds nil nil x t) by eauto.\n destruct (IHx pb ds H0 pbOK); eauto.\n SCase \"x value\".\n destruct x; nope.\n SSCase \"XCon\".\n inverts_type.\n rewrite H8 in H11. inversion H11; subst.\n assert (exists ts x, getAlt d aa = Some (AAlt d ts x)).\n apply getAlt_exists.\n repeat nforall. spec H10 H15. auto.\n dest ts. dest x.\n left. exists (substXXs 0 l x). eapply EsMatchAlt.\n inverts H1. inverts H3; auto. eauto.\n destruct H1 as [STx | HCx].\n SCase \"x steps\".\n left; destruct STx as [x'].\n exists (XMatch x' aa).\n lets D: EsContext XcMatch; eauto.\n SCase \"x hasChoice\".\n right; auto.\nQed.\n", "meta": {"author": "paulkrog", "repo": "formalized-fiat", "sha": "8f9022980c038f500aeea9b2f85062f0bfc33eb6", "save_path": "github-repos/coq/paulkrog-formalized-fiat", "path": "github-repos/coq/paulkrog-formalized-fiat/formalized-fiat-8f9022980c038f500aeea9b2f85062f0bfc33eb6/FiatFormal/Language/Progress.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2857051938559796}}
{"text": "From ExtLib Require Import\n     Structures.Functor\n     Structures.Monad.\n\nFrom ITree Require Import\n     Events.State\n     CategoryOps.\nImport Basics.Monads.\n\nFrom CTree Require Import\n     CTree\n     Fold\n     Eq\n     Eq.Epsilon.\n\nImport SBisimNotations.\nImport MonadNotation.\nOpen Scope monad_scope.\n\nSet Implicit Arguments.\n\n#[global] Instance MonadBr_stateT {S M C} {MM : Monad M} {AM : MonadBr C M}: MonadBr C (stateT S M) :=\n  fun b X c s => f <- mbr b c;; ret (s,f).\n\n#[global] Instance MonadTrigger_stateT {E S M} {MM : Monad M} {MT: MonadTrigger E M} :\n  MonadTrigger E (stateT S M) :=\n  fun _ e s => v <- mtrigger e;; ret (s, v).\n\nDefinition fold_state {E C M} S\n  {FM : Functor M} {MM : Monad M} {IM : MonadIter M}\n  (h : E ~> stateT S M) (g : bool -> C ~> stateT S M) :\n  ctree E C ~> stateT S M := fold h g.\n\nDefinition interp_state {E C M} S\n  {FM : Functor M} {MM : Monad M} {IM : MonadIter M} {BM : MonadBr C M}\n  (h : E ~> stateT S M) :\n  ctree E C ~> stateT S M := interp h.\n\nDefinition refine_state {E C M} S\n  {FM : Functor M} {MM : Monad M} {IM : MonadIter M} {TM : MonadTrigger E M}\n  (g : bool -> C ~> stateT S M) :\n  ctree E C ~> stateT S M := refine g.\n\n#[global] Typeclasses Opaque fold_state interp_state refine_state.\n\nSection State.\n  Variable (S : Type).\n  Variant stateE : Type -> Type :=\n    | Get : stateE S\n    | Put : S -> stateE unit.\n\n  Definition get {E C} `{stateE -< E} : ctree E C S := trigger Get.\n  Definition put {E C} `{stateE -< E} : S -> ctree E C unit := fun s => trigger (Put s).\n\n  Definition h_state {E C} : stateE ~> stateT S (ctree E C) :=\n    fun _ e s =>\n      match e with\n      | Get => Ret (s, s)\n      | Put s' => Ret (s', tt)\n      end.\n\n  Definition pure_state {E C} : E ~> stateT S (ctree E C)\n    := fun _ e s => Vis e (fun x => Ret (s, x)).\n\n  Definition pure_state_choice {E C} b : C ~> stateT S (ctree E C)\n    := fun _ c s => br b c (fun x => Ret (s, x)).\n\n  Definition run_state {E C} `{B1 -< C}\n    : ctree (stateE +' E) C ~> stateT S (ctree E C) :=\n    fold_state (case_ h_state pure_state) pure_state_choice.\n\nEnd State.\n\nLtac break :=\n  match goal with\n  | v: _ * _ |- _ => destruct v\n  end.\n\n(* Stateful handlers [E ~> stateT S (itree F)] and morphisms\n   [E ~> state S] define stateful itree morphisms\n   [itree E ~> stateT S (itree F)]. *)\nSection State.\n\n  Variable (S : Type).\n  Context {E F C D : Type -> Type}\n          `{B1 -< D}\n          {R : Type}\n          (h : E ~> stateT S (ctree F D))\n          (g : bool -> C ~> stateT S (ctree F D)).\n\n  (** Unfolding of [fold]. *)\n  Notation fold_state_ h g t s :=\n    (match observe t with\n     | RetF r => Ret (s, r)\n     | VisF e k => bind (h _ e s) (fun xs => Guard (fold_state h g (k (snd xs)) (fst xs)))\n     | BrF b c k => bind (g b _ c s) (fun xs => Guard (fold_state h g (k (snd xs)) (fst xs)))\n     end)%function.\n\n  Lemma unfold_fold_state (t : ctree E C R) (s : S) :\n    fold_state h g t s ≅ fold_state_ h g t s.\n  Proof.\n    unfold fold_state, fold, Basics.iter, MonadIter_stateT0, iter, MonadIter_ctree.\n    rewrite unfold_iter at 1.\n    cbn.\n    rewrite bind_bind.\n    destruct (observe t); cbn.\n    - now repeat (cbn; rewrite ?bind_ret_l).\n    - rewrite bind_map. cbn.\n      upto_bind_eq.\n      now cbn; rewrite ?bind_ret_l.\n    - rewrite bind_map. cbn.\n      upto_bind_eq.\n      now cbn; rewrite ?bind_ret_l.\n  Qed.\n\n  #[global] Instance equ_fold_state:\n    Proper (equ eq ==> eq ==> equ eq)\n           (fold_state h g (T := R)).\n  Proof.\n    unfold Proper, respectful.\n    coinduction ? IH; intros * EQ1 * <-.\n    rewrite !unfold_fold_state.\n    step in EQ1; inv EQ1; auto.\n    - cbn. upto_bind_eq.\n      constructor; intros; auto.\n    - simpl bind. upto_bind_eq.\n      constructor; auto.\n  Qed.\n\n  Lemma fold_state_ret\n        (s : S) (r : R) :\n    (fold_state h g (Ret r) s) ≅ (Ret (s, r)).\n  Proof.\n    rewrite ctree_eta. reflexivity.\n  Qed.\n\n  Lemma fold_state_vis {T : Type}\n    (e : E T) (k : T -> ctree E C R) (s : S) :\n    fold_state h g (Vis e k) s ≅ h e s >>= fun sx => Guard (fold_state h g (k (snd sx)) (fst sx)).\n  Proof.\n    rewrite unfold_fold_state; reflexivity.\n  Qed.\n\n  Lemma fold_state_br {T: Type} `{C -< D}\n    (b : bool) (c : C T) (k : T -> ctree E C R) (s : S) :\n    fold_state h g (br b c k) s ≅ g b c s >>= fun sx => Guard (fold_state h g (k (snd sx)) (fst sx)).\n  Proof.\n    rewrite !unfold_fold_state; reflexivity.\n  Qed.\n\n  (* TODO move *)\n  #[global] Instance equ_Guard:\n    forall {E B : Type -> Type} {R : Type} `{B1 -< B},\n      Proper (equ eq ==> equ eq) (@Guard E B R _).\n  Proof.\n    repeat intro.\n    unfold Guard; now setoid_rewrite H1.\n  Qed.\n\n  Lemma fold_state_trigger (e : E R) (s : S) :\n    fold_state h g (CTree.trigger e) s ≅\n    h e s >>= fun x => Guard (Ret x).\n  Proof.\n    unfold CTree.trigger.\n    rewrite fold_state_vis; cbn.\n    upto_bind_eq; cbn.\n    rewrite fold_state_ret.\n    now break.\n  Qed.\n\n  Lemma fold_state_trigger_sb `{B0 -< D} (e : E R) (s : S)\n    : fold_state h g (CTree.trigger e) s ~ h e s.\n  Proof.\n    unfold CTree.trigger. rewrite fold_state_vis.\n    rewrite <- (bind_ret_r (h e s)) at 2.\n    cbn.\n    upto_bind_eq.\n    rewrite sb_guard, fold_state_ret.\n    now break.\n  Qed.\n\n  (** Unfolding of [interp]. *)\n  Notation interp_state_ h t s :=\n    (match observe t with\n     | RetF r => Ret (s, r)\n\t   | VisF e k => bind (h _ e s) (fun xs => Guard (interp_state h (k (snd xs)) (fst xs)))\n\t   | BrF b c k => bind (mbr (M := stateT _ _) b c s) (fun xs => Guard (interp_state h (k (snd xs)) (fst xs)))\n     end)%function.\n\n  Lemma unfold_interp_state `{C-<D} (t : ctree E C R) (s : S) :\n    interp_state h t s ≅ interp_state_ h t s.\n  Proof.\n    unfold interp_state, interp, Basics.iter, MonadIter_stateT0, fold, MonadIter_ctree, iter.\n    rewrite unfold_iter at 1.\n    cbn.\n    rewrite bind_bind.\n    destruct (observe t); cbn.\n    - now repeat (cbn; rewrite ?bind_ret_l).\n    - rewrite bind_map. cbn.\n      upto_bind_eq.\n      now cbn; rewrite ?bind_ret_l.\n    - rewrite bind_map. cbn.\n      upto_bind_eq.\n      now cbn; rewrite ?bind_ret_l.\n  Qed.\n\n  #[global] Instance equ_interp_state `{C-<D}:\n    Proper (equ eq ==> eq ==> equ eq)\n           (interp_state (C := C) h (T := R)).\n  Proof.\n    unfold Proper, respectful.\n    coinduction ? IH; intros * EQ1 * <-.\n    rewrite !unfold_interp_state.\n    step in EQ1; inv EQ1; auto.\n    - cbn. upto_bind_eq.\n      constructor; intros; auto.\n    - simpl bind. upto_bind_eq.\n      constructor; auto.\n  Qed.\n\n  Lemma interp_state_ret `{C-<D}\n        (s : S) (r : R) :\n    (interp_state (C := C) h (Ret r) s) ≅ (Ret (s, r)).\n  Proof.\n    rewrite ctree_eta. reflexivity.\n  Qed.\n\n  Lemma interp_state_vis `{C-<D} {T : Type}\n    (e : E T) (k : T -> ctree E C R) (s : S) :\n    interp_state h (Vis e k) s ≅ h e s >>= fun sx => Guard (interp_state h (k (snd sx)) (fst sx)).\n  Proof.\n    rewrite unfold_interp_state; reflexivity.\n  Qed.\n\n  Lemma interp_state_br {T: Type} `{C -< D}\n    (b : bool) (c : C T) (k : T -> ctree E C R) (s : S) :\n    interp_state h (Br b c k) s ≅ branch b c >>= fun x => Guard (interp_state h (k x) s).\n  Proof.\n    rewrite !unfold_interp_state; cbn.\n    rewrite bind_bind.\n    upto_bind_eq.\n    rewrite bind_ret_l.\n    reflexivity.\n  Qed.\n\n  Lemma interp_state_guard `{B1 -< C} `{C -< D}\n    (t : ctree E C R) (s : S) :\n    interp_state h (Guard t) s ≅\n    brD (▷ branch1: C _) (fun _ => (Guard (interp_state h t s))).\n  Proof.\n    unfold Guard at 1.\n    rewrite interp_state_br.\n    cbn.\n    unfold branch; rewrite bind_br.\n    step; constructor; intros [].\n    rewrite bind_ret_l.\n    reflexivity.\n  Qed.\n\n  (** Unfolding of [refine]. *)\n  Notation refine_state_ g t s :=\n    (match observe t with\n     | RetF r => Ret (s, r)\n\t   | VisF e k => bind (mtrigger e) (fun x => Guard (refine_state g (k x) s))\n\t   | BrF b c k => bind (g b _ c s) (fun xs => Guard (refine_state g (k (snd xs)) (fst xs)))\n     end)%function.\n\n  Lemma unfold_refine_state `{E-<F} (t : ctree E C R) (s : S) :\n    refine_state g t s ≅ refine_state_ g t s.\n  Proof.\n    unfold refine_state, refine, Basics.iter, MonadIter_stateT0, fold, MonadIter_ctree, iter.\n    rewrite unfold_iter at 1.\n    cbn.\n    rewrite !bind_bind.\n    destruct (observe t); cbn.\n    - now repeat (cbn; rewrite ?bind_ret_l).\n    - rewrite bind_map. cbn.\n      rewrite !bind_bind.\n      upto_bind_eq.\n      now cbn; rewrite ?bind_ret_l.\n    - rewrite bind_map. cbn.\n      upto_bind_eq.\n      now cbn; rewrite ?bind_ret_l.\n  Qed.\n\n  #[global] Instance equ_refine_state `{E-<F}:\n    Proper (equ eq ==> eq ==> equ eq)\n           (refine_state (E := E) g (T := R)).\n  Proof.\n    unfold Proper, respectful.\n    coinduction ? IH; intros * EQ1 * <-.\n    rewrite !unfold_refine_state.\n    step in EQ1; inv EQ1; auto.\n    - cbn. upto_bind_eq.\n      constructor; intros; auto.\n    - simpl bind. upto_bind_eq.\n      constructor; auto.\n  Qed.\n\n  Lemma refine_state_ret `{E-<F}\n        (s : S) (r : R) :\n    (refine_state (E := E) g (Ret r) s) ≅ (Ret (s, r)).\n  Proof.\n    rewrite ctree_eta. reflexivity.\n  Qed.\n\n  Lemma refine_state_vis `{E-<F} {T : Type}\n    (e : E T) (k : T -> ctree E C R) (s : S) :\n    refine_state g (Vis e k) s ≅\n      trigger e >>= fun x => Guard (refine_state g (k x) s).\n  Proof.\n    rewrite unfold_refine_state; reflexivity.\n  Qed.\n\n  Lemma refine_state_br {T: Type} `{E -< F}\n    (b : bool) (c : C T) (k : T -> ctree E C R) (s : S) :\n    refine_state g (Br b c k) s ≅\n    g b c s >>= fun xs => Guard (refine_state g (k (snd xs)) (fst xs)).\n  Proof.\n    rewrite !unfold_refine_state; cbn.\n    now upto_bind_eq.\n  Qed.\n\nEnd State.\n\nSection FoldBind.\n  Variable (S : Type).\n  Context {E F C D : Type -> Type}\n    `{B1 -< D}.\n\n  Lemma fold_state_bind\n    (h : E ~> stateT S (ctree F D))\n    (g : bool -> C ~> stateT S (ctree F D))\n    {A B}\n    (t : ctree E C A) (k : A -> ctree E C B)\n    (s : S) :\n    fold_state h g (t >>= k) s\n      ≅ fold_state h g t s >>= fun st => fold_state h g (k (snd st)) (fst st).\n  Proof.\n    revert s t.\n    coinduction ? IH; intros.\n    rewrite (ctree_eta t).\n    cbn.\n    rewrite unfold_bind.\n    rewrite unfold_fold_state.\n    destruct (observe t) eqn:Hobs; cbn.\n    - rewrite fold_state_ret. rewrite bind_ret_l. cbn.\n      rewrite unfold_fold_state. reflexivity.\n    - rewrite fold_state_vis.\n      cbn.\n      rewrite bind_bind. cbn.\n      upto_bind_eq.\n      rewrite bind_guard.\n      constructor; intros ?; apply IH.\n    - rewrite unfold_fold_state.\n      cbn.\n\n      rewrite bind_bind.\n      upto_bind_eq.\n      rewrite bind_guard.\n      constructor; intros ?; apply IH.\n  Qed.\n\n  Lemma interp_state_bind `{C -< D}\n    (h : E ~> stateT S (ctree F D))\n    {A B}\n    (t : ctree E C A) (k : A -> ctree E C B)\n    (s : S) :\n    interp_state h (t >>= k) s ≅ interp_state h t s >>= fun xs => interp_state h (k (snd xs)) (fst xs).\n  Proof.\n    eapply fold_state_bind.\n  Qed.\n\n  Lemma refine_state_bind `{E -< F}\n    (g : bool -> C ~> stateT S (ctree F D))\n    {A B}\n    (t : ctree E C A) (k : A -> ctree E C B)\n    (s : S) :\n    refine_state g (t >>= k) s ≅ refine_state g t s >>= fun xs => refine_state g (k (snd xs)) (fst xs).\n  Proof.\n    eapply fold_state_bind.\n  Qed.\n\nEnd FoldBind.\n\n(* Stateful handlers [E ~> stateT S (itree F)] and morphisms\n   [E ~> state S] define stateful itree morphisms\n   [itree E ~> stateT S (itree F)]. *)\nFrom CTree Require Import FoldCTree.\n\n(* TODO MOVE *)\nLemma trans_branch :\n  forall {E B : Type -> Type} {X : Type} {H : B0 -< B} {Y : Type}\n    [l : label] [t t' : ctree E B X] (c : B Y) (k : Y -> ctree E B X) (x : Y),\n    trans l t t' -> k x ≅ t -> trans l (CTree.branch false c >>= k) t'.\nProof.\n  intros.\n  setoid_rewrite bind_branch.\n  eapply trans_brD; eauto.\nQed.\n\nSection transi_state.\n\n  Variable S : Type.\n  Context {E F C D : Type -> Type}\n    `{CST1 : B0 -< C} {CST2 : C -< D} `{CST3 : B1 -< D} `{CST4 : E -< F}.\n  Context {X : Type}.\n  Variable (h : E ~> stateT S (ctree F D)).\n\n  Lemma epsilon_interp_state : forall (t t' : ctree E C X) s,\n      epsilon t t' ->\n      epsilon (interp_state h t s) (interp_state h t' s).\n  Proof.\n    intros; red in H.\n    rewrite (ctree_eta t), (ctree_eta t').\n    genobs t ot. genobs t' ot'. clear t Heqot t' Heqot'.\n    induction H.\n    - constructor. rewrite H. reflexivity.\n    - rewrite unfold_interp_state. cbn.\n      rewrite bind_bind.\n      unfold mbr, MonadBr_ctree, CTree.branch.\n      rewrite bind_br.\n      eapply EpsilonBr with (x := x).\n      rewrite !bind_ret_l.\n      cbn.\n      eapply EpsilonBr with (x := tt).\n      apply IHepsilon_.\n  Qed.\n\n  (* transi *)\n\n  Instance foo : B0 -< D.\n  intros ? ?; now apply CST2, CST1.\n  Defined.\n\n  Inductive transi_state : @label F -> S -> S -> ctree E C X -> ctree E C X -> Prop :=\n  | transis_val : forall (x : X) t t' s,\n      trans (val x) t t' ->\n      transi_state (val (s, x)) s s t t'\n  | transis_tau : forall t t' s,\n      trans tau t t' ->\n      transi_state tau s s t t'\n  | transis_obs : forall Y (e : E Y) x l t t' t'' s s',\n      trans (obs e x) t t' ->\n      epsilon_det t'' (Ret (s', x)) ->\n      trans l (h e s) t'' ->\n      transi_state l s s' t t'\n  | transis_obs0 : forall Y (e : E Y) l x t t' t'' s s' s'',\n      trans (obs e x) t t' ->\n      transi_state l s' s'' t' t'' ->\n      trans (val (s', x)) (h e s) stuckD ->\n      transi_state l s s'' t t''\n  .\n\n  #[global] Instance transis_equ :\n    forall l s s',\n      Proper (equ eq ==> equ eq ==> flip impl) (@transi_state l s s').\n  Proof.\n    cbn. intros.\n    revert x x0 H H0. induction H1; intros.\n    - apply transis_val. rewrite H0, H1. apply H.\n    - apply transis_tau. rewrite H0, H1. apply H.\n    - rewrite <- H2, <- H3 in *. eapply transis_obs; eauto.\n    - rewrite <- H2 in *. eapply transis_obs0; eauto.\n  Qed.\n\n  #[global] Instance transis_equ' :\n    forall l s s',\n      Proper (equ eq ==> equ eq ==> impl) (@transi_state l s s').\n  Proof.\n    cbn. intros. rewrite <- H, <- H0. apply H1.\n  Qed.\n\n  Lemma transis_brD : forall Y l s s' (t' : ctree E C X) (c : C Y) k x,\n      transi_state l s s' (k x) t' ->\n      transi_state l s s' (BrD c k) t'.\n  Proof.\n    intros. inv H.\n    - apply transis_val. etrans.\n    - apply transis_tau. etrans.\n    - eapply transis_obs; etrans.\n    - eapply transis_obs0; etrans.\n  Qed.\n\n  Lemma epsilon_transi :\n    forall l s s' (t t' t'' : ctree E C X),\n      epsilon t t' ->\n      transi_state l s s' t' t'' ->\n      transi_state l s s' t t''.\n  Proof.\n    intros.\n    red in H. rewrite (ctree_eta t). rewrite (ctree_eta t') in H0.\n    genobs t ot. genobs t' ot'. clear t Heqot. clear t' Heqot'.\n    revert l t'' H0. induction H; intros.\n    - rewrite H. apply H0.\n    - eapply transis_brD. setoid_rewrite <- ctree_eta in IHepsilon_. apply IHepsilon_. apply H0.\n  Qed.\n\n  Lemma transis_sbisim :\n    forall l s s' (t t' u : ctree E C X),\n      transi_state l s s' t t' ->\n      t ~ u ->\n      exists u', transi_state l s s' u u' /\\ t' ~ u'.\n  Proof.\n    intros. revert u H0.\n    induction H; intros.\n    - step in H0. destruct H0 as [? _]. apply H0 in H.\n      destruct H as (? & ? & ? & ? & ?); subst.\n      eexists. split. eapply transis_val; eauto. apply H1.\n    - step in H0. destruct H0 as [? _]. apply H0 in H.\n      destruct H as (? & ? & ? & ? & ?); subst.\n      eexists. split. eapply transis_tau; eauto. apply H1.\n    - step in H2. destruct H2 as [? _]. apply H2 in H.\n      destruct H as (? & ? & ? & ? & ?); subst.\n      eexists. split. eapply transis_obs; eauto. apply H3.\n    - step in H2. destruct H2 as [? _]. apply H2 in H.\n      destruct H as (? & ? & ? & ? & ?); subst.\n      apply IHtransi_state in H3 as (? & ? & ?).\n      eexists; split. eapply transis_obs0; eauto. apply H4.\n  Qed.\n\n  Lemma transis_trans (Hh : forall X (e : _ X) s, vsimple (h e s)) :\n    forall l s s' (t t' : ctree E C X),\n      transi_state l s s' t t' ->\n      exists t0, trans l (interp_state h t s) t0 /\\ epsilon_det t0 (interp_state h t' s').\n  Proof.\n    intros. induction H.\n    - exists stuckD. apply trans_val_inv in H as ?.\n      apply trans_val_epsilon in H as [].\n      eapply epsilon_interp_state in H. rewrite interp_state_ret in H. setoid_rewrite H0.\n      setoid_rewrite interp_state_br.\n      split.\n      eapply epsilon_trans in H; etrans.\n      left.\n      setoid_rewrite bind_branch.\n      step.\n      constructor; intros [].\n\n    - exists (Guard (interp_state h t' s)). split; [| eright; eauto; now left ].\n      apply trans_tau_epsilon in H as (? & ? & ? & ? & ? & ?).\n      eapply epsilon_interp_state in H. setoid_rewrite H0. eapply epsilon_trans; etrans.\n      rewrite interp_state_br. setoid_rewrite bind_branch.\n      econstructor. reflexivity.\n    - exists (x <- t'';; Guard (interp_state h t' s')).\n      split.\n      2: { eapply epsilon_det_bind_ret_l; eauto. eright; eauto. }\n      apply trans_obs_epsilon in H as (? & ? & ?).\n      eapply epsilon_interp_state in H. setoid_rewrite H2. eapply epsilon_trans; etrans.\n      setoid_rewrite interp_state_vis.\n      eapply trans_bind_l with (k := fun sx => Guard (interp_state h (x0 (snd sx)) (fst sx))) in H1.\n      setoid_rewrite epsilon_det_bind_ret_l_equ in H1 at 2; eauto. cbn in *. eapply H1.\n      { intro. inv H3. apply trans_val_inv in H1. rewrite H1 in H0. inv H0. step in H3. inv H3. step in H4. inv H4. auto using void_unit_elim. }\n    - destruct IHtransi_state as (? & ? & ?).\n      destruct (Hh Y e s).\n      2: { destruct H4. rewrite H4 in H1. apply trans_vis_inv in H1 as (? & ? & ?). step in H1. inv H1. }\n      destruct H4. rewrite H4 in H1. inv_trans. subst.\n      exists x0. split. 2: auto.\n      apply trans_obs_epsilon in H as (? & ? & ?). eapply epsilon_interp_state in H.\n      setoid_rewrite interp_state_vis in H. setoid_rewrite H4 in H. setoid_rewrite bind_ret_l in H.\n      eapply epsilon_trans; etrans. setoid_rewrite <- H1. etrans.\n  Qed.\n\n  Lemma interp_state_ret_inv :\n    forall s (t : ctree E C X) r,\n      interp_state h t s ≅ Ret r -> t ≅ Ret (snd r) /\\ s = fst r.\n  Proof.\n    intros. setoid_rewrite (ctree_eta t) in H. setoid_rewrite (ctree_eta t).\n    destruct (observe t) eqn:?.\n    - rewrite interp_state_ret in H. step in H. inv H. split; reflexivity.\n    - rewrite interp_state_vis in H. apply ret_equ_bind in H as (? & ? & ?). step in H0. inv H0.\n    - rewrite interp_state_br in H. step in H. inv H.\n  Qed.\n\n  Lemma trans_interp_state_inv_gen (Hh : forall X (e : _ X) s, vsimple (h e s)) :\n    forall Y l s (k : Y -> ctree E C X) t' (pre : ctree F D Y),\n      is_simple pre ->\n      trans l (x <- pre;; interp_state h (k x) s) t' ->\n      exists t0 s', epsilon_det t' (interp_state h t0 s') /\\\n                 ((exists l t1 x, trans l pre t1 /\\ epsilon_det t1 (Ret x : ctree F D Y) /\\ t0 ≅ k x) \\/\n                    exists (x : Y), trans (val x) pre stuckD /\\ trans l (interp_state h (k x) s) t' /\\ transi_state l s s' (k x) t0).\n  Proof.\n    intros * Hpre H.\n    do 3 red in H. remember (observe (x <- pre;; interp_state h (k x) s)) as oi.\n    setoid_rewrite (ctree_eta t') at 1.\n    setoid_rewrite (ctree_eta t') at 2.\n    genobs t' ot'. clear t' Heqot'.\n    assert (go oi ≅ x <- pre;; interp_state h (k x) s).\n    { rewrite Heqoi, <- ctree_eta. reflexivity. } clear Heqoi.\n    revert Y s k pre Hpre H0. induction H; intros.\n    - symmetry in H0. apply br_equ_bind in H0 as ?.\n      destruct H1 as [[] | (? & ? & ?)].\n      + rewrite H1 in H0. setoid_rewrite bind_ret_l in H0. setoid_rewrite H1. clear pre Hpre H1.\n        rewrite (ctree_eta (k0 x0)) in H0. destruct (observe (k0 x0)) eqn:?.\n        * rewrite interp_state_ret in H0. step in H0. inv H0.\n        * rewrite interp_state_vis in H0. apply br_equ_bind in H0 as ?. destruct H1 as [[] | (? & ? & ?)].\n          --setoid_rewrite H1 in H0. setoid_rewrite bind_ret_l in H0.\n            inv_equ.\n            rewrite <- EQ in H.\n            specialize (IHtrans_ _ (fst x1) (fun (_ : unit) => k1 (snd x1)) (Ret tt)).\n            edestruct IHtrans_ as (? & ? & ?).\n            { apply is_simple_ret. }\n            { rewrite <- ctree_eta. setoid_rewrite bind_ret_l. setoid_rewrite EQ. reflexivity. }\n            destruct H0. exists x2, x3. split; auto. right. destruct H2.\n            { destruct H2 as (? & ? & ? & ? & ? & ?). inv_trans. subst.\n              inv H3. step in H2. inv H2. step in H5. inv H5.\n              exfalso; now apply void_unit_elim.\n            }\n            destruct H2 as (_ & _ & ? & ?). exists x0. split. etrans. split.\n            ++setoid_rewrite (ctree_eta (k0 x0)). rewrite Heqc0.\n              setoid_rewrite interp_state_vis. setoid_rewrite H1. setoid_rewrite bind_ret_l. apply trans_guard. apply H2.\n            ++setoid_rewrite (ctree_eta (k0 x0)). rewrite Heqc0. destruct x1.\n              eapply transis_obs0. etrans. 2: { rewrite H1. etrans. } cbn in H3. cbn in *. etrans.\n          -- destruct (Hh _ e s).\n             destruct H3. rewrite H3 in H1. step in H1. inv H1.\n             destruct H3. rewrite H3 in H1. step in H1. inv H1.\n        * rewrite interp_state_br in H0.\n          setoid_rewrite bind_branch in H0.\n          inv_equ.\n          specialize (IHtrans_ _ s (fun _ : unit => k1 x) (Guard (Ret tt))).\n          edestruct IHtrans_ as (? & ? & ? & ?).\n          { apply is_simple_guard_ret. }\n          { rewrite <- ctree_eta. setoid_rewrite bind_br. setoid_rewrite bind_ret_l. now rewrite <- EQ. }\n          destruct H1.\n          { destruct H1 as (? & ? & ? & ? & ? & ?). inv_trans. subst.\n            inv H2. step in H1. inv H1. step in H3. inv H3.\n            exfalso; now apply void_unit_elim.\n          }\n          destruct H1 as (? & ? & ? & ?).\n          exists x1, x2. split; auto. right. exists x0. split; etrans. split.\n          rewrite (ctree_eta (k0 x0)), Heqc0, interp_state_br.\n          eapply trans_branch.\n          2: reflexivity. apply trans_guard. apply H2.\n          rewrite (ctree_eta (k0 x0)), Heqc0. eapply transis_brD; etrans.\n      + specialize (IHtrans_ _ s k0 (x0 x)).\n        edestruct IHtrans_ as (? & ? & ? & ?).\n        { eapply is_simple_brD. red. setoid_rewrite <- H1. apply Hpre. }\n        rewrite <- ctree_eta. apply H2. destruct H4 as [(? & ? & ? & ? & ? & ?) | (? & ? & ? & ?)].\n        exists (k0 x5), x2. split. { now rewrite H6 in H3. }\n        left. eapply trans_brD in H4. 2: reflexivity. rewrite <- H1 in H4. eauto 6.\n        * exists x1, x2. split; auto. right. exists x3. rewrite H1. etrans.\n    - symmetry in H0. apply br_equ_bind in H0 as ?. destruct H1 as [[] | (? & ? & ?)].\n      + rewrite H1 in H0. setoid_rewrite bind_ret_l in H0.\n        rewrite (ctree_eta (k0 x0)) in H0. destruct (observe (k0 x0)) eqn:?.\n        * rewrite interp_state_ret in H0. step in H0. inv H0.\n        * rewrite interp_state_vis in H0. apply br_equ_bind in H0 as ?.\n          destruct H2 as [[] | (? & ? & ?)].\n          { rewrite H2 in H0. setoid_rewrite bind_ret_l in H0. step in H0. inv H0. }\n          pose proof (trans_brS c x1 x). rewrite <- H2 in H4.\n          edestruct Hh. { destruct H5. rewrite H5 in H4. inv_trans. }\n          destruct H5. rewrite H5 in H4. apply trans_vis_inv in H4 as (? & ? & ?). discriminate.\n        * rewrite interp_state_br in H0.\n          setoid_rewrite bind_branch in H0.\n          inv_equ.\n          specialize (EQ x). rewrite H in EQ.\n          exists (k1 x), s. symmetry in EQ. split.\n          { rewrite <- ctree_eta. rewrite EQ. eapply epsilon_det_tau; auto. }\n          right. exists x0. rewrite H1. split; etrans.\n          split; setoid_rewrite (ctree_eta (k0 x0)); setoid_rewrite Heqc0.\n          { setoid_rewrite interp_state_br. rewrite EQ.\n            setoid_rewrite bind_branch.\n            econstructor. now rewrite <- ctree_eta. }\n          econstructor; etrans.\n      + pose proof (trans_brS c x0 x).\n        rewrite <- H1 in H3. edestruct Hpre.\n        { apply H4 in H3. inv H3. }\n        apply H4 in H3 as [].\n        specialize (H2 x).\n        exists (k0 x1), s. rewrite H in H2. split.\n        { rewrite <- ctree_eta, H2. eapply epsilon_det_bind_ret_l; eauto. }\n        left. exists tau, (x0 x), x1. split; auto. rewrite H1. etrans.\n    - symmetry in H0. apply vis_equ_bind in H0 as ?. destruct H1 as [[] | (? & ? & ?)].\n      + rewrite H1 in H0. setoid_rewrite bind_ret_l in H0.\n        rewrite (ctree_eta (k0 x0)) in H0. destruct (observe (k0 x0)) eqn:?.\n        * rewrite interp_state_ret in H0. step in H0. inv H0.\n        * rewrite interp_state_vis in H0. apply vis_equ_bind in H0 as ?.\n          destruct H2 as [[] | (? & ? & ?)].\n          { rewrite H2 in H0. setoid_rewrite bind_ret_l in H0. step in H0. inv H0. }\n          pose proof (trans_vis e x x1). rewrite <- H2 in H4.\n          edestruct Hh. { destruct H5. rewrite H5 in H4. inv H4. }\n          destruct H5. rewrite H5 in H4.\n          specialize (H3 x). rewrite H5 in H2.\n          inv_equ.\n          rewrite <- EQ in *. rewrite bind_ret_l in H3.\n          exists (k1 (snd x)), (fst x).\n          rewrite H in H3. split. { rewrite <- ctree_eta, H3. eright; eauto. }\n          right.\n          exists x0. rewrite H1. split; etrans.\n          split; setoid_rewrite (ctree_eta (k0 x0)); setoid_rewrite Heqc.\n          { setoid_rewrite interp_state_vis. rewrite H5. setoid_rewrite bind_vis.\n            econstructor. rewrite bind_ret_l. rewrite <- H3, <- ctree_eta. reflexivity. }\n          eapply transis_obs; etrans. rewrite H5. destruct x. etrans.\n        * rewrite interp_state_br in H0. step in H0. inv H0.\n      + pose proof (trans_vis e x x0).\n        rewrite <- H1 in H3. edestruct Hpre.\n        { apply H4 in H3. inv H3. }\n        apply H4 in H3 as [].\n        specialize (H2 x).\n        exists (k0 x1), s. rewrite H in H2. split.\n        { rewrite <- ctree_eta, H2. eapply epsilon_det_bind_ret_l; eauto. }\n        left. exists (obs e x), (x0 x), x1. split; auto. rewrite H1. etrans.\n    - exists stuckD, (fst r). split.\n      + left. unfold stuck. rewrite interp_state_br.\n        rewrite !br0_always_stuck.\n        setoid_rewrite bind_branch.\n        step.\n        constructor; intros [].\n      + right. symmetry in H0. apply ret_equ_bind in H0 as (? & ? & ?).\n        exists x. rewrite H. split; etrans. split.\n        rewrite H0. rewrite br0_always_stuck. etrans.\n        apply interp_state_ret_inv in H0 as []. subst. rewrite H0. destruct r. cbn. apply transis_val. econstructor; etrans.\n  Qed.\n\n  Lemma trans_interp_state_inv (Hh : forall X (e : _ X) s, vsimple (h e s)) :\n    forall l (t : ctree E C X) t' s,\n      trans l (interp_state h t s) t' ->\n      exists l t0 s', epsilon_det t' (interp_state h t0 s') /\\ transi_state l s s' t t0.\n  Proof.\n    intros.\n    assert (trans l (Guard (Ret tt);; interp_state h t s) t').\n    { cbn. etrans. }\n    eapply trans_interp_state_inv_gen in H0; eauto. destruct H0 as (? & ? & ? & ?).\n    destruct H1 as [(? & ? & ? & ? & ? & ?) | (? & ? & ? & ?)].\n    - inv_trans. subst. inv H2. step in H1. inv H1. step in H3. inv H3.\n      exfalso; now apply void_unit_elim.\n    - inv_trans. subst. eauto.\n    - left. intros. inv_trans. subst. constructor.\n  Qed.\n\n(** The main theorem stating that fold_state preserves sbisim. *)\n\n  Theorem interp_state_sbisim_gen {Y} (Hh : forall X (e : _ X) s, vsimple (h e s)) :\n    forall s (k k' : Y -> ctree E C X) (pre pre' : ctree F D Y),\n      (forall x, sbisim eq (k x) (k' x)) ->\n      pre ≅ pre' ->\n      vsimple pre ->\n      sbisim eq (a <- pre;; Guard (interp_state h (k a) s)) (a <- pre';; Guard (interp_state h (k' a) s)).\n  Proof.\n    revert Y. coinduction R CH.\n    (* We would like to use a symmetry argument here, as is done in the 0.1 branch *)\n    symmetric using idtac.\n    { intros. apply H. now symmetry. now symmetry. red. now setoid_rewrite <- H1. }\n    assert (CH' : forall (t t' : ctree E C X) s, t ~ t' -> st eq R (interp_state h t s) (interp_state h t' s)).\n    {\n      intros.\n      assert (st eq R (a <- Ret tt;; Guard (interp_state h ((fun _ => t) a) s))\n                (a <- Ret tt;; Guard (interp_state h ((fun _ => t') a) s))).\n      { apply CH; eauto. left; eauto. }\n      setoid_rewrite bind_ret_l in H0.\n      rewrite !sb_guard in H0.\n      apply H0.\n    }\n    intros. setoid_rewrite <- H0. clear pre' H0. cbn.\n    cbn; intros.\n    copy H0. rewrite bind_guard_r in H0.\n    eapply trans_interp_state_inv_gen in H0 as (? & ? & ? & ?); auto.\n    2: { destruct H1 as [[] | []]; rewrite H1.\n         rewrite bind_ret_l. apply is_simple_guard_ret.\n         rewrite bind_trigger. right. intros. inv_trans. subst.\n         exists x0. rewrite EQ. eright. left. reflexivity. reflexivity.\n    }\n    destruct H2.\n    + destruct H2 as (? & ? & ? & ? & ? & ?). rewrite H4 in H0. clear x H4.\n      destruct H1 as [[] | []].\n      * rewrite H1, bind_ret_l in H2. rewrite H1, bind_ret_l in cpy. inv_trans. subst.\n        inv H3. step in H2. inv H2. step in H4. inv H4.\n        exfalso; now apply void_unit_elim.\n      * rewrite H1 in *. rewrite bind_trigger in H2. apply trans_vis_inv in H2 as (? & ? & ?). subst.\n        rewrite H2 in H3. inv H3. step in H4. inv H4.\n        apply equ_br_invE in H5 as [_ ?].\n        rewrite <- H3 in H4; auto. inv H4.\n        2: { step in H6. inv H6. }\n        step in H5. inv H5.\n        rewrite bind_trigger in cpy. apply trans_vis_inv in cpy. destruct cpy as (? & ? & ?). subst.\n        eexists. exists (Guard (interp_state h (k' x1) s)). rewrite H1. rewrite bind_trigger. split.\n        now constructor.\n        split; auto.\n        rewrite H4, !sb_guard. apply CH'. apply H.\n    + destruct H2 as (? & ? & ? & ?).\n      destruct H1 as [[] | []].\n      2: { rewrite H1 in H2. setoid_rewrite bind_trigger in H2. inv_trans. }\n      rewrite H1 in *. rewrite bind_ret_l in H2. inv_trans. subst. clear EQ.\n      eapply transis_sbisim in H4; eauto. destruct H4 as (? & ? & ?).\n      apply transis_trans in H2 as (? & ? & ?); auto.\n      eexists; exists x3. rewrite H1, bind_ret_l. split.\n      etrans.\n      assert (st eq R (interp_state h x x0) (interp_state h x1 x0)).\n      { apply CH'. apply H4. }\n      split; auto.\n      rewrite sbisim_epsilon_det. 2: apply H0.\n      apply sbisim_epsilon_det in H5; rewrite H5.\n      apply H6.\n  Qed.\n\n  #[global] Instance interp_state_sbisim (Hh : forall X (e : _ X) s, vsimple (h e s)) :\n    Proper (sbisim eq ==> eq ==> sbisim eq) (interp_state h (C := C) (T := X)).\n  Proof.\n    cbn. intros. subst.\n    assert (a <- Ret tt;; Guard (interp_state h ((fun _ => x) a) y0) ~\n                           a <- Ret tt;; Guard (interp_state h ((fun _ => y) a) y0)).\n    apply interp_state_sbisim_gen; auto.\n    red; eauto.\n    setoid_rewrite bind_ret_l in H0. rewrite !sb_guard in H0. apply H0.\n  Qed.\n\nEnd transi_state.\n\nArguments get {S E C _}.\nArguments put {S E C _}.\nArguments run_state {S E C} [_] _ _.\nArguments fold_state {E C M S FM MM IM} h g [T].\nArguments interp_state {E C M S FM MM IM BM} h [T].\nArguments refine_state {E C M S FM MM IM TM} g [T].\n", "meta": {"author": "vellvm", "repo": "ctrees", "sha": "a622bc2e63eaa987e081b862e9aafeea3f8f5d79", "save_path": "github-repos/coq/vellvm-ctrees", "path": "github-repos/coq/vellvm-ctrees/ctrees-a622bc2e63eaa987e081b862e9aafeea3f8f5d79/theories/Interp/FoldStateT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.2857051938559796}}
{"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 A B C D P Q C0 : Universe, ((wd_ C0 A /\\ (wd_ A B /\\ (wd_ C0 B /\\ (wd_ C D /\\ (wd_ D P /\\ (wd_ C P /\\ (wd_ B Q /\\ (wd_ A Q /\\ (wd_ P C0 /\\ (wd_ C A /\\ (wd_ C B /\\ (wd_ D A /\\ (wd_ D B /\\ (col_ A B P /\\ (col_ C D C0 /\\ (col_ C0 P A /\\ col_ C0 P B)))))))))))))))) -> col_ C0 A B)).\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_0266.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.28561158006324894}}
{"text": "From Coq Require Import ZArith.\nFrom Coq Require Import List. Import ListNotations.\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 ContractCommon.\nFrom ConCert.Execution Require Import Monad.\nFrom ConCert.Execution Require Import ResultMonad.\nFrom ConCert.Execution Require Import Serializable.\nFrom ConCert.Examples.FA2 Require Import FA2LegacyInterface.\n\n\n\nSection FA2Token.\n  Context {BaseTypes : ChainBase}.\n  Set Primitive Projections.\n  Set Nonrecursive Elimination Schemes.\n  Open Scope N_scope.\n\n  (* Any contract that wants to receive callback messages from the FA2 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 FA2ReceiverMsg {Msg' : Type} :=\n  | receive_balance_of_param : list balance_of_response -> FA2ReceiverMsg\n  | receive_total_supply_param : list total_supply_response -> FA2ReceiverMsg\n  | receive_metadata_callback : list token_metadata -> FA2ReceiverMsg\n  | receive_is_operator : is_operator_response -> FA2ReceiverMsg\n  | receive_permissions_descriptor : permissions_descriptor -> FA2ReceiverMsg\n  | other_msg : Msg' -> FA2ReceiverMsg.\n\n  (* Transfer hook contracts of the FA2 Contract should use this type as their Msg type *)\n  Inductive FA2TransferHook {Msg : Type} :=\n  | transfer_hook : transfer_descriptor_param -> FA2TransferHook\n  | hook_other_msg : Msg -> FA2TransferHook.\n\n  (* The FA2 Endpoints. *)\n  Inductive Msg :=\n  | msg_transfer : list transfer -> Msg\n  | msg_set_transfer_hook : set_hook_param -> Msg\n  | msg_receive_hook_transfer : transfer_descriptor_param -> Msg\n  | msg_balance_of : balance_of_param -> Msg\n  | msg_total_supply : total_supply_param -> Msg\n  | msg_token_metadata : token_metadata_param -> Msg\n  | msg_permissions_descriptor : callback permissions_descriptor -> Msg\n  | msg_update_operators : list update_operator -> Msg\n  | msg_is_operator : is_operator_param -> Msg\n  | msg_create_tokens : token_id -> Msg.\n\n  Record TokenLedger :=\n    build_token_ledger {\n      fungible : bool;\n      balances : FMap Address N\n    }.\n\n  Record State :=\n    build_state {\n      fa2_owner          : Address;\n      assets             : FMap token_id TokenLedger;\n      operators          : FMap Address (FMap Address operator_tokens);\n      permission_policy  : permissions_descriptor;\n      tokens             : FMap token_id token_metadata;\n      transfer_hook_addr : option Address;\n    }.\n\n  Record Setup :=\n    build_setup {\n      setup_total_supply        : list (token_id * N);\n      setup_tokens              : FMap token_id token_metadata;\n      initial_permission_policy : permissions_descriptor;\n      transfer_hook_addr_       : option Address;\n    }.\n\n  Definition Error : Type := nat.\n  Definition default_error : Error := 1%nat.\n\n  MetaCoq Run (make_setters TokenLedger).\n  MetaCoq Run (make_setters State).\n  MetaCoq Run (make_setters Setup).\n\n  Section Serialization.\n\n    Global Instance setup_serializable : Serializable Setup :=\n      Derive Serializable Setup_rect <build_setup>.\n\n    Global Instance FA2ReceiverMsg_serializable {Msg : Type}\n                                                `{Serializable Msg}\n                                                : Serializable (@FA2ReceiverMsg Msg) :=\n      Derive Serializable (@FA2ReceiverMsg_rect Msg) <\n        (@receive_balance_of_param Msg),\n        (@receive_total_supply_param Msg),\n        (@receive_metadata_callback Msg),\n        (@receive_is_operator Msg),\n        (@receive_permissions_descriptor Msg),\n        (@other_msg Msg)>.\n\n    Global Instance FA2TransferHook_serializable {Msg : Type}\n                                                `{Serializable Msg}\n                                                : Serializable (@FA2TransferHook Msg) :=\n      Derive Serializable (@FA2TransferHook_rect Msg) <\n        (@transfer_hook Msg),\n        (@hook_other_msg Msg)>.\n\n    Global Instance callback_permissions_descriptor_serializable : Serializable (callback permissions_descriptor) :=\n      callback_serializable.\n\n    Global Instance msg_serializable : Serializable Msg :=\n      Derive Serializable Msg_rect <\n        msg_transfer,\n        msg_set_transfer_hook,\n        msg_receive_hook_transfer,\n        msg_balance_of,\n        msg_total_supply,\n        msg_token_metadata,\n        msg_permissions_descriptor,\n        msg_update_operators,\n        msg_is_operator,\n        msg_create_tokens>.\n\n    Global Instance TokenLedger_serializable : Serializable TokenLedger :=\n      Derive Serializable TokenLedger_rect <build_token_ledger>.\n\n    Global Instance state_serializable : Serializable State :=\n      Derive Serializable State_rect <build_state>.\n\n  End Serialization.\n\n\n  Definition address_balance (token_id : token_id)\n                             (addr : Address)\n                             (state : State)\n                             : N :=\n    match FMap.find token_id state.(assets) with\n    | Some ledger => with_default 0%N (FMap.find addr ledger.(balances))\n    | None => 0%N\n    end.\n\n  Definition address_has_sufficient_asset_balance (token_id : token_id)\n                                                  (owner : Address)\n                                                  (transaction_amount : N)\n                                                  (state : State)\n                                                  : result unit Error :=\n    if transaction_amount <=? address_balance token_id owner state\n    then Ok tt\n    else Err default_error.\n\n  Definition policy_disallows_operator_transfer (policy : permissions_descriptor) : bool :=\n    match policy.(descr_operator) with\n    | operator_transfer_permitted => false\n    | operator_transfer_denied => true\n    end.\n\n  Definition policy_disallows_self_transfer (policy : permissions_descriptor) : bool :=\n    match policy.(descr_self) with\n    | self_transfer_permitted => false\n    | self_transfer_denied => true\n    end.\n\n  Definition get_owner_operator_tokens (owner operator : Address)\n                                       (state : State)\n                                       : option operator_tokens :=\n    do operator_tokens <- FMap.find owner state.(operators) ;\n    FMap.find operator operator_tokens.\n\n  (* Executes a single transfer by returning a new state, if successful. *)\n  Definition try_single_transfer (caller : Address)\n                                 (params : transfer)\n                                 (state : State)\n                                 : result State Error :=\n    do _ <- throwIf (negb (1 =? N.of_nat (length params.(txs)))) default_error;\n    do transfer_dst <- result_of_option (hd_error (params.(txs))) default_error;\n    do ledger <- result_of_option (FMap.find transfer_dst.(dst_token_id) state.(assets)) default_error;\n    let current_owner_balance := address_balance transfer_dst.(dst_token_id) params.(from_) state in\n    let new_balances := FMap.add params.(from_) (current_owner_balance - transfer_dst.(amount)) ledger.(balances) in\n    let new_balances := FMap.partial_alter (fun balance =>\n      Some ((with_default 0 balance) + transfer_dst.(amount))) transfer_dst.(to_) new_balances in\n    let new_ledger := ledger<|balances := new_balances|> in\n      Ok (state<|assets ::= FMap.add transfer_dst.(dst_token_id) new_ledger|>).\n\n  Definition transfer_check_permissions (caller : Address)\n                                        (params : transfer)\n                                        (policy : permissions_descriptor)\n                                        (state : State)\n                                        : result unit Error :=\n    do _ <- throwIf (negb (1 =? N.of_nat (length params.(txs)))) default_error;\n    do transfer_dst <- result_of_option (hd_error (params.(txs))) default_error;\n    (* check for sufficient permissions *)\n    do _ <- address_has_sufficient_asset_balance transfer_dst.(dst_token_id) params.(from_) transfer_dst.(amount) state ;\n    (* only allow transfers of known token_ids *)\n    do _ <- result_of_option (FMap.find transfer_dst.(dst_token_id) state.(tokens)) default_error;\n    (* if caller is owner of transfer, then check policy if self_transfer is allowed *)\n    if (address_eqb caller params.(from_))\n    then\n      throwIf (policy_disallows_self_transfer policy) default_error\n    else\n      (* check if policy allows operator transfer *)\n      do _ <- throwIf (policy_disallows_operator_transfer policy) default_error;\n      do operators_map <- result_of_option (FMap.find params.(from_) state.(operators)) default_error;\n      do op_tokens <- result_of_option (FMap.find caller operators_map) default_error;\n      (* check if operator has permission to transfer the given token_id type *)\n      match op_tokens with\n      | all_tokens => Ok tt\n      | some_tokens token_ids => if (existsb (fun id => id =? transfer_dst.(dst_token_id)) token_ids)\n                                then Ok tt\n                                else Err default_error\n      end.\n\n  (* Executes all transfers in a batch operation and returns a new state if *all*\n    transfers were successful. *)\n  Definition try_transfer (caller : Address)\n                          (transfers : list transfer)\n                          (state : State)\n                          : result State Error :=\n    let check_transfer_iterator state_opt params :=\n      do state <- state_opt ;\n      do _ <- transfer_check_permissions caller params state.(permission_policy) state;\n      try_single_transfer caller params state in\n    (* returns the new state if all transfers *can* succeed, otherwise returns None *)\n    fold_left check_transfer_iterator transfers (Ok state).\n\n  (* Forwards the transfer to the hook to approve/reject *)\n  Definition call_transfer_hook (caller : Address)\n                                (caddr : Address)\n                                (transfer_hook_addr : Address)\n                                (transfers : list transfer)\n                                (state : State)\n                                : ActionBody :=\n    let mk_transfer_dst_descr tr_dst := {|\n      transfer_dst_descr_to_ := Some tr_dst.(to_);\n      transfer_dst_descr_token_id := tr_dst.(dst_token_id);\n      transfer_dst_descr_amount := tr_dst.(amount)\n      |} in\n    let mk_transfer_descr tr := {|\n      transfer_descr_from_ := Some (tr.(from_));\n      transfer_descr_txs := map mk_transfer_dst_descr tr.(txs)\n      |} in\n    let transfer_decr_param := {|\n      transfer_descr_fa2 := caddr;\n      transfer_descr_batch := map mk_transfer_descr transfers;\n      transfer_descr_operator := caller;\n      |} in\n    act_call transfer_hook_addr 0%Z (serialize (transfer_hook transfer_decr_param)).\n\n  Definition group_transfer_descriptors (params : list transfer_descriptor)\n                                        : list (list transfer_descriptor) :=\n    let trx_map := fold_right (fun trx trx_map =>\n    match FMap.find trx.(transfer_descr_from_) trx_map with\n    | Some trxs => FMap.add trx.(transfer_descr_from_) (trx :: trxs) trx_map\n    | None => FMap.add trx.(transfer_descr_from_) [trx] trx_map\n    end\n    ) FMap.empty params in\n    FMap.values trx_map.\n\n  (* Handles incoming transfers:\n    - if the contract has a transfer_hook, then it uses the hook\n    - otherwise it checks & performs the transfers now *)\n  Definition handle_transfer (caller : Address)\n                             (caddr : Address)\n                             (transfers : list transfer)\n                             (state : State)\n                             : result (State * list ActionBody) Error :=\n    match state.(transfer_hook_addr) with\n    (* send call transfer hook (approved transfers will be received in the msg_receive_hook_transfer endpoint) *)\n    | Some transfer_hook_addr =>\n      let call_hook_act := call_transfer_hook caller caddr transfer_hook_addr transfers state in\n      Ok (state, [call_hook_act])\n    (* if no hook is attached, send transfer message to self, and notify senders of transfer *)\n    | None =>\n    let mk_transfer_dst_descr tr_dst := {|\n      transfer_dst_descr_to_ := Some tr_dst.(to_);\n      transfer_dst_descr_token_id := tr_dst.(dst_token_id);\n      transfer_dst_descr_amount := tr_dst.(amount)\n      |} in\n    let mk_transfer_descr tr := {|\n      transfer_descr_from_ := Some (tr.(from_));\n      transfer_descr_txs := map mk_transfer_dst_descr tr.(txs)\n      |} in\n      let mk_transfer_decr_param batch := {|\n        transfer_descr_fa2 := caddr;\n        transfer_descr_batch := batch;\n        transfer_descr_operator := caller;\n      |} in\n      let transfer_decr_param := mk_transfer_decr_param (map mk_transfer_descr transfers) in\n      let is_from_contract descriptors := existsb (fun descr =>\n        match descr.(transfer_descr_from_) with\n        | Some addr => address_is_contract addr\n        | None => false\n        end) descriptors in\n      let trx_descriptors_grouped := (group_transfer_descriptors (map mk_transfer_descr transfers)) in\n      let self_transfer_act := act_call caddr 0%Z (serialize (msg_receive_hook_transfer transfer_decr_param)) in\n\n      let mk_sender_hook_act trx :=\n        match trx.(sender_callback_addr) with\n        | Some callback_addr =>\n          let descr := mk_transfer_decr_param [mk_transfer_descr trx] in\n          Some (act_call callback_addr 0%Z (@serialize fa2_token_sender _ (tokens_sent descr)))\n        | None => None\n        end in\n      let sender_hook_acts := fold_right (fun act_opt acc =>\n        match act_opt with\n        | Some act => act :: acc\n        | None => acc\n        end\n      ) [] (map mk_sender_hook_act transfers) in\n      (* If no sender callbacks need to be made, just perform transfers now *)\n      if Nat.eqb (length sender_hook_acts) 0%nat then\n        (try_transfer caller transfers state) >>= (fun new_state => Ok (new_state, []))\n      else\n        (* Notice that sender hooks are invoked before the transfer *)\n        Ok (state, sender_hook_acts ++ [self_transfer_act])\n    end.\n\n  Open Scope bool_scope.\n  Definition mk_transfer_destination_from_descr (dst_descr: transfer_destination_descriptor)\n                                                : option transfer_destination :=\n    do to <- dst_descr.(transfer_dst_descr_to_) ;\n    Some {|\n      to_ := to;\n      dst_token_id := dst_descr.(transfer_dst_descr_token_id);\n      amount := dst_descr.(transfer_dst_descr_amount)\n    |}.\n\n  Definition mk_transfer_from_descr (descr: transfer_descriptor) : option transfer :=\n    do from <- descr.(transfer_descr_from_) ;\n    let iter := (fun dst_descr acc_opt =>\n      do acc <- acc_opt;\n      do tx_dst <- mk_transfer_destination_from_descr dst_descr;\n      Some (tx_dst :: acc)) in\n    do txs_list <- fold_right iter (Some []) descr.(transfer_descr_txs);\n    Some {|\n      from_ := from;\n      txs := txs_list;\n      sender_callback_addr := None\n    |}.\n\n  Definition handle_transfer_hook_receive (caller : Address)\n                                          (param : transfer_descriptor_param)\n                                          (self_addr : Address)\n                                          (state : State)\n                                          : result State Error :=\n    (* check if caller is current hook or self - only hook or self is allowed to call this endpoint *)\n    do _ <- if (match state.(transfer_hook_addr) with\n            | Some hook_addr => ((address_eqb caller hook_addr) || (address_eqb caller self_addr))\n            | None => (address_eqb caller self_addr)\n            end)\n            then Ok tt\n            else Err default_error;\n    let iter := (fun descr acc_opt =>\n      do acc <- acc_opt;\n      do trans <- result_of_option (mk_transfer_from_descr descr) default_error;\n      Ok (trans :: acc)) in\n    do transfers <- fold_right iter (Ok []) param.(transfer_descr_batch) ;\n    try_transfer param.(transfer_descr_operator) transfers state.\n  Close Scope bool_scope.\n\n  (* create a 'balance_of' action to send to the callback address *)\n  Definition get_balance_of_callback (param : balance_of_param)\n                                     (state : State)\n                                     : ActionBody :=\n    let bal_req_iterator (bal_req : balance_of_request) :=\n      let owner_bal := address_balance bal_req.(bal_req_token_id) bal_req.(owner) state in\n      Build_balance_of_response bal_req owner_bal in\n    let responses := map bal_req_iterator param.(bal_requests) in\n    let response_msg := serialize (receive_balance_of_param responses) in\n    act_call param.(bal_callback) 0%Z response_msg.\n\n  (* create a 'total_supply' action to send to the callback address *)\n  Definition get_total_supply_callback (param : total_supply_param)\n                                       (state : State)\n                                       : ActionBody :=\n    let token_id_balance (token_id : token_id) : N :=\n      match FMap.find token_id state.(assets) with\n      | Some ledger => fold_left N.add (FMap.values ledger.(balances)) 0%N\n      | None => 0%N\n      end in\n    let mk_response (token_id : token_id) : total_supply_response :=\n      Build_total_supply_response token_id (token_id_balance token_id) in\n    let responses := map mk_response param.(supply_param_token_ids) in\n    let response_msg := serialize (receive_total_supply_param responses) in\n    act_call param.(supply_param_callback) 0%Z response_msg.\n\n  (* Updates operators if policy allows it, and if the caller is the owner. *)\n  Definition update_operators (caller : Address)\n                              (updates : list update_operator)\n                              (state : State)\n                              : result State Error :=\n    (* If policy doesn't allow operator transfer, then this operation fails *)\n    do _ <- throwIf (policy_disallows_operator_transfer state.(permission_policy)) default_error;\n    let exec_add params (state_opt : result State Error) : result State Error :=\n      do state_ <- state_opt ;\n      (* only the owner of the token is allowed to update their operators *)\n      if (address_neqb caller params.(op_param_owner))\n      then Err default_error\n      else\n        let operator_tokens : FMap Address operator_tokens :=\n          with_default FMap.empty (FMap.find caller state_.(operators)) in\n        (* Add new operator *)\n        let operator_tokens :=\n          FMap.add params.(op_param_operator) params.(op_param_tokens) operator_tokens in\n        Ok (state_<| operators ::= FMap.add caller operator_tokens |>) in\n    let exec_update state_ op := match op with\n                                | add_operator params => exec_add params state_\n                                | remove_operator params => exec_add params state_\n                                end in\n    (fold_left exec_update updates (Ok state)).\n\n  Definition operator_tokens_eqb (a b : operator_tokens) : bool :=\n    match (a, b) with\n    | (all_tokens, all_tokens) => true\n    | (some_tokens a', some_tokens b') =>\n      let fix my_list_eqb l1 l2 :=\n        match (l1, l2) with\n        | (x :: l1, y :: l2) => if x =? y\n                                then my_list_eqb l1 l2\n                                else false\n        | ([], []) => true\n        | _ => false\n        end in my_list_eqb a' b'\n    | _ => false\n    end.\n\n  Definition get_is_operator_response_callback (params : is_operator_param)\n                                               (state : State)\n                                               : result (State * list ActionBody) Error :=\n    (* if policy doesn't allow operator transfers, then this operation will fail *)\n    do _ <- throwIf (policy_disallows_operator_transfer state.(permission_policy)) default_error;\n    let operator_params := params.(is_operator_operator) in\n    let operator_tokens_opt := get_owner_operator_tokens operator_params.(op_param_owner)\n                                                         operator_params.(op_param_operator) in\n    let is_operator_result := match operator_tokens_opt state with\n                              (* check if operator_tokens from the params and from the state are equal *)\n                              | Some op_tokens => operator_tokens_eqb op_tokens operator_params.(op_param_tokens)\n                              | None => false\n                              end in\n    let response : is_operator_response := {| operator := operator_params; is_operator := is_operator_result |} in\n    let act := act_call params.(is_operator_callback) 0%Z (serialize (receive_is_operator response)) in\n      Ok (state, [act]).\n\n  Definition get_permissions_descriptor_callback (caller : Address)\n                                                 (state : State)\n                                                 : ActionBody :=\n    let response := serialize (receive_permissions_descriptor state.(permission_policy)) in\n    act_call caller 0%Z response.\n\n  Definition try_set_transfer_hook (caller : Address)\n                                   (params : set_hook_param)\n                                   (state : State)\n                                   : result State Error :=\n    (* only owner can set transfer hook *)\n    do _ <- throwIf (address_neqb caller state.(fa2_owner)) default_error;\n    Ok (state<| transfer_hook_addr := Some params.(hook_addr)|>\n              <| permission_policy := params.(hook_permissions_descriptor) |>).\n\n  Definition get_token_metadata_callback (param : token_metadata_param)\n                                         (state : State)\n                                         : ActionBody :=\n    let token_ids := param.(metadata_token_ids) in\n    let state_tokens := state.(tokens) in\n    let metadata_list : list token_metadata := fold_right (fun id acc =>\n        match FMap.find id state_tokens with\n        | Some metadata => metadata :: acc\n        | None => acc\n        end\n      ) [] token_ids in\n    let response := serialize (receive_metadata_callback metadata_list) in\n    act_call param.(metadata_callback) 0%Z response.\n\n  (* creates some tokens with a fixed exchange ratio of 1:100 *)\n  Definition try_create_tokens (caller : Address)\n                               (amount : Amount)\n                               (tokenid : token_id)\n                               (state : State)\n                               : result State Error :=\n    let exchange_rate := 100%Z in\n    do ledger <- result_of_option (FMap.find tokenid state.(assets)) default_error;\n    (* only allow amounts > 0 *)\n    do _ <- throwIf (Z.leb amount 0%Z) default_error;\n    let amount := Z.to_N (amount * exchange_rate) in\n    let caller_bal := with_default 0 (FMap.find caller ledger.(balances)) in\n    let new_balances := FMap.add caller (caller_bal + amount) ledger.(balances) in\n    let new_ledger := ledger<| balances := new_balances |> in\n    Ok (state<| assets ::= FMap.add tokenid new_ledger |>).\n\n\n  Open Scope Z_scope.\n  Definition receive (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 caddr := ctx.(ctx_contract_address) in\n    let without_statechange acts := Ok (state, acts) in\n    (* Only 'create_token' messages are allowed to carry money *)\n    if ctx.(ctx_amount) >? 0\n    then match maybe_msg with\n    | Some (msg_create_tokens tokenid) =>\n        without_actions (try_create_tokens sender ctx.(ctx_amount) tokenid state)\n    | _ => Err default_error\n    end\n    else match maybe_msg with\n    | Some (msg_transfer transfers) =>\n        handle_transfer sender caddr transfers state\n    | Some (msg_receive_hook_transfer param) =>\n        without_actions (handle_transfer_hook_receive sender param caddr state)\n    | Some (msg_is_operator params) =>\n        get_is_operator_response_callback params state\n    | Some (msg_balance_of params) =>\n        without_statechange [get_balance_of_callback params state]\n    | Some (msg_total_supply params) =>\n        without_statechange [get_total_supply_callback params state]\n    | Some (msg_permissions_descriptor _) =>\n        without_statechange [get_permissions_descriptor_callback sender state]\n    | Some (msg_token_metadata param) =>\n        without_statechange [get_token_metadata_callback param state]\n    | Some (msg_update_operators updates) =>\n        without_actions (update_operators sender updates state)\n    | Some (msg_set_transfer_hook params) =>\n        without_actions (try_set_transfer_hook sender params state)\n    | _ => Err default_error\n    end.\n\n  Definition map_values_FMap {A B C: Type}\n                            `{countable.Countable A}\n                            `{base.EqDecision A}\n                             (f : B -> C)\n                             (m : FMap A B)\n                             : FMap A C :=\n    let l := FMap.elements m in\n    let mapped_l := List.map (fun '(a, b) => (a, f b)) l in\n    FMap.of_list mapped_l.\n\n  Definition init (chain : Chain)\n                  (ctx : ContractCallContext)\n                  (setup : Setup)\n                  : result State Error :=\n    (* setup ledgers with empty balance for each initial token id *)\n    let assets' := map_values_FMap (fun _ =>\n      build_token_ledger false FMap.empty\n    ) setup.(setup_tokens) in\n    Ok {| permission_policy := setup.(initial_permission_policy);\n            fa2_owner := ctx.(ctx_from);\n            transfer_hook_addr := setup.(transfer_hook_addr_);\n            assets := assets';\n            operators := FMap.empty;\n            tokens := setup.(setup_tokens)\n      |}.\n\n  Definition contract : Contract Setup Msg State Error :=\n    build_contract init receive.\n\nEnd FA2Token.\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/fa2/FA2Token.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.28551368149172723}}
{"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 6\n*)\n\n(** 1 Mutual Coinduction *)\n\nSection Arg6_1.\n\nDefinition monotone6 T0 T1 T2 T3 T4 T5 (gf: rel6 T0 T1 T2 T3 T4 T5 -> rel6 T0 T1 T2 T3 T4 T5) :=\n  forall x0 x1 x2 x3 x4 x5 r r' (IN: gf r x0 x1 x2 x3 x4 x5) (LE: r <6= r'), gf r' x0 x1 x2 x3 x4 x5.\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 gf : rel6 T0 T1 T2 T3 T4 T5 -> rel6 T0 T1 T2 T3 T4 T5.\nArguments gf : clear implicits.\n\nTheorem paco6_acc: forall\n  l r (OBG: forall rr (INC: r <6= rr) (CIH: l <_paco_6= rr), l <_paco_6= paco6 gf rr),\n  l <6= paco6 gf r.\nProof.\n  intros; assert (SIM: paco6 gf (r \\6/ l) x0 x1 x2 x3 x4 x5) by eauto.\n  clear PR; repeat (try left; do 7 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco6_mon: monotone6 (paco6 gf).\nProof. paco_cofix_auto; repeat (left; do 7 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco6_mult_strong: forall r,\n  paco6 gf (upaco6 gf r) <6= paco6 gf r.\nProof. paco_cofix_auto; repeat (left; do 7 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco6_mult: forall r,\n  paco6 gf (paco6 gf r) <6= paco6 gf r.\nProof. intros; eapply paco6_mult_strong, paco6_mon; eauto. Qed.\n\nTheorem paco6_fold: forall r,\n  gf (upaco6 gf r) <6= paco6 gf r.\nProof. intros; econstructor; [ |eauto]; eauto. Qed.\n\nTheorem paco6_unfold: forall (MON: monotone6 gf) r,\n  paco6 gf r <6= gf (upaco6 gf r).\nProof. unfold monotone6; intros; destruct PR; eauto. Qed.\n\nEnd Arg6_1.\n\nHint Unfold monotone6.\nHint Resolve paco6_fold.\n\nArguments paco6_acc            [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_mon            [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_mult_strong    [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_mult           [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_fold           [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_unfold         [ T0 T1 T2 T3 T4 T5 ].\n\nInstance paco6_inst  T0 T1 T2 T3 T4 T5 (gf : rel6 T0 T1 T2 T3 T4 T5->_) r x0 x1 x2 x3 x4 x5 : paco_class (paco6 gf r x0 x1 x2 x3 x4 x5) :=\n{ pacoacc    := paco6_acc gf;\n  pacomult   := paco6_mult gf;\n  pacofold   := paco6_fold gf;\n  pacounfold := paco6_unfold gf }.\n\n(** 2 Mutual Coinduction *)\n\nSection Arg6_2.\n\nDefinition monotone6_2 T0 T1 T2 T3 T4 T5 (gf: rel6 T0 T1 T2 T3 T4 T5 -> rel6 T0 T1 T2 T3 T4 T5 -> rel6 T0 T1 T2 T3 T4 T5) :=\n  forall x0 x1 x2 x3 x4 x5 r_0 r_1 r'_0 r'_1 (IN: gf r_0 r_1 x0 x1 x2 x3 x4 x5) (LE_0: r_0 <6= r'_0)(LE_1: r_1 <6= r'_1), gf r'_0 r'_1 x0 x1 x2 x3 x4 x5.\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 gf_0 gf_1 : rel6 T0 T1 T2 T3 T4 T5 -> rel6 T0 T1 T2 T3 T4 T5 -> rel6 T0 T1 T2 T3 T4 T5.\nArguments gf_0 : clear implicits.\nArguments gf_1 : clear implicits.\n\nTheorem paco6_2_0_acc: forall\n  l r_0 r_1 (OBG: forall rr (INC: r_0 <6= rr) (CIH: l <_paco_6= rr), l <_paco_6= paco6_2_0 gf_0 gf_1 rr r_1),\n  l <6= paco6_2_0 gf_0 gf_1 r_0 r_1.\nProof.\n  intros; assert (SIM: paco6_2_0 gf_0 gf_1 (r_0 \\6/ l) r_1 x0 x1 x2 x3 x4 x5) by eauto.\n  clear PR; repeat (try left; do 7 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco6_2_1_acc: forall\n  l r_0 r_1 (OBG: forall rr (INC: r_1 <6= rr) (CIH: l <_paco_6= rr), l <_paco_6= paco6_2_1 gf_0 gf_1 r_0 rr),\n  l <6= paco6_2_1 gf_0 gf_1 r_0 r_1.\nProof.\n  intros; assert (SIM: paco6_2_1 gf_0 gf_1 r_0 (r_1 \\6/ l) x0 x1 x2 x3 x4 x5) by eauto.\n  clear PR; repeat (try left; do 7 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco6_2_0_mon: monotone6_2 (paco6_2_0 gf_0 gf_1).\nProof. paco_cofix_auto; repeat (left; do 7 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco6_2_1_mon: monotone6_2 (paco6_2_1 gf_0 gf_1).\nProof. paco_cofix_auto; repeat (left; do 7 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco6_2_0_mult_strong: forall r_0 r_1,\n  paco6_2_0 gf_0 gf_1 (upaco6_2_0 gf_0 gf_1 r_0 r_1) (upaco6_2_1 gf_0 gf_1 r_0 r_1) <6= paco6_2_0 gf_0 gf_1 r_0 r_1.\nProof. paco_cofix_auto; repeat (left; do 7 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco6_2_1_mult_strong: forall r_0 r_1,\n  paco6_2_1 gf_0 gf_1 (upaco6_2_0 gf_0 gf_1 r_0 r_1) (upaco6_2_1 gf_0 gf_1 r_0 r_1) <6= paco6_2_1 gf_0 gf_1 r_0 r_1.\nProof. paco_cofix_auto; repeat (left; do 7 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco6_2_0_mult: forall r_0 r_1,\n  paco6_2_0 gf_0 gf_1 (paco6_2_0 gf_0 gf_1 r_0 r_1) (paco6_2_1 gf_0 gf_1 r_0 r_1) <6= paco6_2_0 gf_0 gf_1 r_0 r_1.\nProof. intros; eapply paco6_2_0_mult_strong, paco6_2_0_mon; eauto. Qed.\n\nCorollary paco6_2_1_mult: forall r_0 r_1,\n  paco6_2_1 gf_0 gf_1 (paco6_2_0 gf_0 gf_1 r_0 r_1) (paco6_2_1 gf_0 gf_1 r_0 r_1) <6= paco6_2_1 gf_0 gf_1 r_0 r_1.\nProof. intros; eapply paco6_2_1_mult_strong, paco6_2_1_mon; eauto. Qed.\n\nTheorem paco6_2_0_fold: forall r_0 r_1,\n  gf_0 (upaco6_2_0 gf_0 gf_1 r_0 r_1) (upaco6_2_1 gf_0 gf_1 r_0 r_1) <6= paco6_2_0 gf_0 gf_1 r_0 r_1.\nProof. intros; econstructor; [ | |eauto]; eauto. Qed.\n\nTheorem paco6_2_1_fold: forall r_0 r_1,\n  gf_1 (upaco6_2_0 gf_0 gf_1 r_0 r_1) (upaco6_2_1 gf_0 gf_1 r_0 r_1) <6= paco6_2_1 gf_0 gf_1 r_0 r_1.\nProof. intros; econstructor; [ | |eauto]; eauto. Qed.\n\nTheorem paco6_2_0_unfold: forall (MON: monotone6_2 gf_0) (MON: monotone6_2 gf_1) r_0 r_1,\n  paco6_2_0 gf_0 gf_1 r_0 r_1 <6= gf_0 (upaco6_2_0 gf_0 gf_1 r_0 r_1) (upaco6_2_1 gf_0 gf_1 r_0 r_1).\nProof. unfold monotone6_2; intros; destruct PR; eauto. Qed.\n\nTheorem paco6_2_1_unfold: forall (MON: monotone6_2 gf_0) (MON: monotone6_2 gf_1) r_0 r_1,\n  paco6_2_1 gf_0 gf_1 r_0 r_1 <6= gf_1 (upaco6_2_0 gf_0 gf_1 r_0 r_1) (upaco6_2_1 gf_0 gf_1 r_0 r_1).\nProof. unfold monotone6_2; intros; destruct PR; eauto. Qed.\n\nEnd Arg6_2.\n\nHint Unfold monotone6_2.\nHint Resolve paco6_2_0_fold.\nHint Resolve paco6_2_1_fold.\n\nArguments paco6_2_0_acc            [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_2_1_acc            [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_2_0_mon            [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_2_1_mon            [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_2_0_mult_strong    [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_2_1_mult_strong    [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_2_0_mult           [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_2_1_mult           [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_2_0_fold           [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_2_1_fold           [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_2_0_unfold         [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_2_1_unfold         [ T0 T1 T2 T3 T4 T5 ].\n\nInstance paco6_2_0_inst  T0 T1 T2 T3 T4 T5 (gf_0 gf_1 : rel6 T0 T1 T2 T3 T4 T5->_) r_0 r_1 x0 x1 x2 x3 x4 x5 : paco_class (paco6_2_0 gf_0 gf_1 r_0 r_1 x0 x1 x2 x3 x4 x5) :=\n{ pacoacc    := paco6_2_0_acc gf_0 gf_1;\n  pacomult   := paco6_2_0_mult gf_0 gf_1;\n  pacofold   := paco6_2_0_fold gf_0 gf_1;\n  pacounfold := paco6_2_0_unfold gf_0 gf_1 }.\n\nInstance paco6_2_1_inst  T0 T1 T2 T3 T4 T5 (gf_0 gf_1 : rel6 T0 T1 T2 T3 T4 T5->_) r_0 r_1 x0 x1 x2 x3 x4 x5 : paco_class (paco6_2_1 gf_0 gf_1 r_0 r_1 x0 x1 x2 x3 x4 x5) :=\n{ pacoacc    := paco6_2_1_acc gf_0 gf_1;\n  pacomult   := paco6_2_1_mult gf_0 gf_1;\n  pacofold   := paco6_2_1_fold gf_0 gf_1;\n  pacounfold := paco6_2_1_unfold gf_0 gf_1 }.\n\n(** 3 Mutual Coinduction *)\n\nSection Arg6_3.\n\nDefinition monotone6_3 T0 T1 T2 T3 T4 T5 (gf: rel6 T0 T1 T2 T3 T4 T5 -> rel6 T0 T1 T2 T3 T4 T5 -> rel6 T0 T1 T2 T3 T4 T5 -> rel6 T0 T1 T2 T3 T4 T5) :=\n  forall x0 x1 x2 x3 x4 x5 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) (LE_0: r_0 <6= r'_0)(LE_1: r_1 <6= r'_1)(LE_2: r_2 <6= r'_2), gf r'_0 r'_1 r'_2 x0 x1 x2 x3 x4 x5.\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 gf_0 gf_1 gf_2 : rel6 T0 T1 T2 T3 T4 T5 -> rel6 T0 T1 T2 T3 T4 T5 -> rel6 T0 T1 T2 T3 T4 T5 -> rel6 T0 T1 T2 T3 T4 T5.\nArguments gf_0 : clear implicits.\nArguments gf_1 : clear implicits.\nArguments gf_2 : clear implicits.\n\nTheorem paco6_3_0_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_0 <6= rr) (CIH: l <_paco_6= rr), l <_paco_6= paco6_3_0 gf_0 gf_1 gf_2 rr r_1 r_2),\n  l <6= paco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco6_3_0 gf_0 gf_1 gf_2 (r_0 \\6/ l) r_1 r_2 x0 x1 x2 x3 x4 x5) by eauto.\n  clear PR; repeat (try left; do 7 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco6_3_1_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_1 <6= rr) (CIH: l <_paco_6= rr), l <_paco_6= paco6_3_1 gf_0 gf_1 gf_2 r_0 rr r_2),\n  l <6= paco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco6_3_1 gf_0 gf_1 gf_2 r_0 (r_1 \\6/ l) r_2 x0 x1 x2 x3 x4 x5) by eauto.\n  clear PR; repeat (try left; do 7 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco6_3_2_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_2 <6= rr) (CIH: l <_paco_6= rr), l <_paco_6= paco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 rr),\n  l <6= paco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 (r_2 \\6/ l) x0 x1 x2 x3 x4 x5) by eauto.\n  clear PR; repeat (try left; do 7 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco6_3_0_mon: monotone6_3 (paco6_3_0 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 7 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco6_3_1_mon: monotone6_3 (paco6_3_1 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 7 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco6_3_2_mon: monotone6_3 (paco6_3_2 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 7 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco6_3_0_mult_strong: forall r_0 r_1 r_2,\n  paco6_3_0 gf_0 gf_1 gf_2 (upaco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <6= paco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 7 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco6_3_1_mult_strong: forall r_0 r_1 r_2,\n  paco6_3_1 gf_0 gf_1 gf_2 (upaco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <6= paco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 7 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco6_3_2_mult_strong: forall r_0 r_1 r_2,\n  paco6_3_2 gf_0 gf_1 gf_2 (upaco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <6= paco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 7 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco6_3_0_mult: forall r_0 r_1 r_2,\n  paco6_3_0 gf_0 gf_1 gf_2 (paco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <6= paco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco6_3_0_mult_strong, paco6_3_0_mon; eauto. Qed.\n\nCorollary paco6_3_1_mult: forall r_0 r_1 r_2,\n  paco6_3_1 gf_0 gf_1 gf_2 (paco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <6= paco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco6_3_1_mult_strong, paco6_3_1_mon; eauto. Qed.\n\nCorollary paco6_3_2_mult: forall r_0 r_1 r_2,\n  paco6_3_2 gf_0 gf_1 gf_2 (paco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <6= paco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco6_3_2_mult_strong, paco6_3_2_mon; eauto. Qed.\n\nTheorem paco6_3_0_fold: forall r_0 r_1 r_2,\n  gf_0 (upaco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <6= paco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco6_3_1_fold: forall r_0 r_1 r_2,\n  gf_1 (upaco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <6= paco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco6_3_2_fold: forall r_0 r_1 r_2,\n  gf_2 (upaco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <6= paco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco6_3_0_unfold: forall (MON: monotone6_3 gf_0) (MON: monotone6_3 gf_1) (MON: monotone6_3 gf_2) r_0 r_1 r_2,\n  paco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2 <6= gf_0 (upaco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2).\nProof. unfold monotone6_3; intros; destruct PR; eauto. Qed.\n\nTheorem paco6_3_1_unfold: forall (MON: monotone6_3 gf_0) (MON: monotone6_3 gf_1) (MON: monotone6_3 gf_2) r_0 r_1 r_2,\n  paco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2 <6= gf_1 (upaco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2).\nProof. unfold monotone6_3; intros; destruct PR; eauto. Qed.\n\nTheorem paco6_3_2_unfold: forall (MON: monotone6_3 gf_0) (MON: monotone6_3 gf_1) (MON: monotone6_3 gf_2) r_0 r_1 r_2,\n  paco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2 <6= gf_2 (upaco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2).\nProof. unfold monotone6_3; intros; destruct PR; eauto. Qed.\n\nEnd Arg6_3.\n\nHint Unfold monotone6_3.\nHint Resolve paco6_3_0_fold.\nHint Resolve paco6_3_1_fold.\nHint Resolve paco6_3_2_fold.\n\nArguments paco6_3_0_acc            [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_3_1_acc            [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_3_2_acc            [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_3_0_mon            [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_3_1_mon            [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_3_2_mon            [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_3_0_mult_strong    [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_3_1_mult_strong    [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_3_2_mult_strong    [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_3_0_mult           [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_3_1_mult           [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_3_2_mult           [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_3_0_fold           [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_3_1_fold           [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_3_2_fold           [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_3_0_unfold         [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_3_1_unfold         [ T0 T1 T2 T3 T4 T5 ].\nArguments paco6_3_2_unfold         [ T0 T1 T2 T3 T4 T5 ].\n\nInstance paco6_3_0_inst  T0 T1 T2 T3 T4 T5 (gf_0 gf_1 gf_2 : rel6 T0 T1 T2 T3 T4 T5->_) r_0 r_1 r_2 x0 x1 x2 x3 x4 x5 : paco_class (paco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2 x0 x1 x2 x3 x4 x5) :=\n{ pacoacc    := paco6_3_0_acc gf_0 gf_1 gf_2;\n  pacomult   := paco6_3_0_mult gf_0 gf_1 gf_2;\n  pacofold   := paco6_3_0_fold gf_0 gf_1 gf_2;\n  pacounfold := paco6_3_0_unfold gf_0 gf_1 gf_2 }.\n\nInstance paco6_3_1_inst  T0 T1 T2 T3 T4 T5 (gf_0 gf_1 gf_2 : rel6 T0 T1 T2 T3 T4 T5->_) r_0 r_1 r_2 x0 x1 x2 x3 x4 x5 : paco_class (paco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2 x0 x1 x2 x3 x4 x5) :=\n{ pacoacc    := paco6_3_1_acc gf_0 gf_1 gf_2;\n  pacomult   := paco6_3_1_mult gf_0 gf_1 gf_2;\n  pacofold   := paco6_3_1_fold gf_0 gf_1 gf_2;\n  pacounfold := paco6_3_1_unfold gf_0 gf_1 gf_2 }.\n\nInstance paco6_3_2_inst  T0 T1 T2 T3 T4 T5 (gf_0 gf_1 gf_2 : rel6 T0 T1 T2 T3 T4 T5->_) r_0 r_1 r_2 x0 x1 x2 x3 x4 x5 : paco_class (paco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2 x0 x1 x2 x3 x4 x5) :=\n{ pacoacc    := paco6_3_2_acc gf_0 gf_1 gf_2;\n  pacomult   := paco6_3_2_mult gf_0 gf_1 gf_2;\n  pacofold   := paco6_3_2_fold gf_0 gf_1 gf_2;\n  pacounfold := paco6_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/paco6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2855136814917272}}
{"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 approx_star_props1.\n(** printing #  $\\times$ #×# *)\n(** printing <=>  $\\Leftrightarrow$ #&hArr;# *)\n(** printing $  $\\times$ #×# *)\n(** printing &  $\\times$ #×# *)\n\nHint Resolve approx_star_relates_only_wf : slow.\n\n\nLemma alpha_implies_approx_star {p} :\n  forall lib nt1 nt2,\n  @nt_wf p nt1\n  -> alpha_eq nt1 nt2\n  -> approx_star lib nt1 nt2.\nProof.\n  introv H1nt H2nt.\n  apply approx_open_implies_approx_star.\n  apply alpha_implies_approx_open; trivial.\nQed.\n\nLemma approx_star_trans {p} : forall lib t1 t2 t3,\n  @approx_star p lib t1 t2\n  -> approx_star lib t2 t3\n  -> approx_star lib t1 t3.\nProof.\n  nterm_ind1s t1 as [v1|f ind|o lbt1 Hind] Case; introv H1as H2as;\n  inversion H1as as [? ? ? aop|?|]; subst; clear H1as.\nAbort. (** see comments above for approx_star_open_trans*)\n\nLemma le_approx_ntwf {p} :\n  forall lib, le_bin_rel (approx_star lib) (indep_bin_rel nt_wf (@nt_wf p)).\nProof.\n  eauto with slow.\nQed.\n\nLemma approx_rel_wf_sub {p} :\n  forall lib lvi lnta lntb,\n  bin_rel_nterm (@approx_star p lib) lnta lntb\n  -> wf_sub (combine lvi lnta) # wf_sub (combine lvi lntb).\nProof.\n  introv Hb. apply (le_binrel_list_un _ _ _ _ (le_approx_ntwf lib)) in Hb.\n  exrepnd. unfold wf_sub, sub_range_sat.   dands; eauto with slow.\nQed.\n\nLemma approx_star_btermd_fr {p} :\n  forall lib op bt1 bt2 lva,\n    op = NCan NFresh\n    -> approx_star_bterm lib op bt1 bt2\n    -> {lvn : list NVar\n        & {nt1',nt2' : @NTerm p\n        $ {sub : Sub\n        $ approx_star lib (lsubst nt1' sub) (lsubst nt2' sub)\n        # nrut_sub (get_utokens nt1' ++ get_utokens nt2') sub\n        # lvn = dom_sub sub\n        # alpha_eq_bterm bt1 (bterm lvn nt1')\n        # alpha_eq_bterm bt2 (bterm lvn nt2')\n        # no_repeats lvn\n        (* # disjoint lvn (all_vars (get_nt bt1) ++ all_vars (get_nt bt2)) *)\n        # disjoint (lvn ++ (bound_vars nt1') ++ (bound_vars nt2')) lva }}}.\nProof.\n  introv d Hab.\n  unfold approx_star_bterm in Hab.\n  repnud Hab. exrepnd.\n  pose proof (alpha_bterm_pair_change _ _ _ _ _ lva Hab2 Hab0) as Hp.\n  exrepnd.\n  exists lvn.\n\n  repndors; exrepnd; subst; tcsp; GC.\n  allrw disjoint_app_r; allrw disjoint_app_l; repnd.\n\n  exists (lsubst nt1n (var_ren (dom_sub sub) lvn))\n         (lsubst nt2n (var_ren (dom_sub sub) lvn))\n         (combine lvn (range sub)).\n  rw @boundvars_lsubst_vars; auto.\n  rw @boundvars_lsubst_vars; auto.\n  rw @get_utokens_lsubst_allvars; eauto 3 with slow.\n  rw @get_utokens_lsubst_allvars; eauto 3 with slow.\n  rw @dom_sub_combine; allrw @length_range; allrw @length_dom; auto.\n\n  dands; eauto 3 with slow.\n\n  - pose proof (lsubst_nest_same_alpha nt1n (dom_sub sub) lvn (range sub)) as nest1.\n    allrw @length_dom; allrw @length_range.\n    repeat (autodimp nest1 hyp).\n    { apply alphaeq_preserves_free_vars in Hp2; rw <- Hp2; auto. }\n    rw <- @sub_eta in nest1.\n\n    pose proof (lsubst_nest_same_alpha nt2n (dom_sub sub) lvn (range sub)) as nest2.\n    allrw @length_dom; allrw @length_range.\n    repeat (autodimp nest2 hyp).\n    { apply alphaeq_preserves_free_vars in Hp3; rw <- Hp3; auto. }\n    rw <- @sub_eta in nest2.\n\n    pose proof (lsubst_alpha_congr2 nt1 nt1n sub Hp2) as as1.\n    pose proof (lsubst_alpha_congr2 nt2 nt2n sub Hp3) as as2.\n\n    eapply approx_star_alpha_fun_l;[|apply alpha_eq_sym; exact nest1].\n    eapply approx_star_alpha_fun_r;[|apply alpha_eq_sym; exact nest2].\n    eauto 3 with slow.\n\n  - apply alphaeq_preserves_utokens in Hp2.\n    apply alphaeq_preserves_utokens in Hp3.\n    rw <- Hp2; rw <- Hp3.\n    eapply nrut_sub_change_sub_same_range;[|exact Hab5].\n    rw @range_combine; auto; allrw @length_range; allrw @length_dom; auto.\n\n  - allrw disjoint_app_l; dands; auto.\nQed.\n\n(*\nLemma change_nr_ut_sub_in_lsubst_aux_approx_star {o} :\n  forall lib (t1 t2 : @NTerm o) sub1 sub2 l,\n    wf_term t1\n    -> wf_term t2\n    -> approx_star lib (lsubst_aux t1 sub1) (lsubst_aux t2 sub1)\n    -> subset (get_utokens t1) l\n    -> subset (get_utokens t2) l\n    -> nrut_sub l sub1\n    -> nrut_sub l sub2\n    -> dom_sub sub1 = dom_sub sub2\n    -> approx_star lib (lsubst_aux t1 sub2) (lsubst_aux t2 sub2).\nProof.\n  nterm_ind1s t1 as [v|op bs ind] Case;\n  introv w1 s2 ap ss1 ss2 nrut1 nrut2 eqdoms; allsimpl.\n\nFocus 2.\n{\n  destruct t2 as [v2|op2 bs2]; allsimpl.\n\nFocus 2.\n{\n  \n}\n\n  - pose proof (sub_find_some_eq_doms_nrut_sub sub1 sub2 v2 l) as e.\n    repeat (autodimp e hyp).\n    remember (sub_find sub1 v2) as sf; symmetry in Heqsf; destruct sf.\n\n(*\nFocus 2.\n{\n  rw e.\n  inversion ap as [? ? ? ao|]; subst; clear ap.\n  constructor.\n       apply approx_open_vterm_iff_reduces_to in ao;\n       [|apply lsubst_aux_preserves_wf_term2; eauto with slow];\n       apply approx_open_vterm_iff_reduces_to;\n       [apply lsubst_aux_preserves_wf_term2; eauto with slow|];\n       apply (reduces_to_vterm_nrut_sub_change lib t2 sub1 sub2 l); auto\n}\n*)\n\n    + exrepnd; rw e0.\n      applydup @sub_find_some in Heqsf.\n      eapply in_nrut_sub in Heqsf0; eauto.\n      exrepnd; subst.\n      inversion ap as [|? ? ? ? ? len lift apo]; subst; allsimpl; cpx; clear ap.\n      allrw map_length.\n      apply approx_open_simpler_equiv in apo.\n      unfold simpl_olift in apo; repnd.\n      pose proof (apo (ax_sub (free_vars (oterm op lbt1')))) as ap; clear apo.\n      repeat (autodimp ap hyp).\n      { apply isprogram_lsubst_prog_sub; eauto 3 with slow.\n        rw @dom_sub_ax_sub; auto. }\n      { rw @cl_lsubst_lsubst_aux; eauto 1 with slow.\n        simpl; repeat constructor; simpl; sp. }\n      repeat (rw @cl_lsubst_lsubst_aux in ap; eauto 1 with slow).\n      simpl in ap.\n      allfold (@mk_utoken o a0).\n\nSearchAbout dom_sub ax_sub.\n}\n\n  - Case \"vterm\".\n    pose proof (sub_find_some_eq_doms_nrut_sub sub1 sub2 v l) as h.\n    repeat (autodimp h hyp).\n    remember (sub_find sub1 v) as sf1; symmetry in Heqsf1; destruct sf1; exrepnd;\n    [|rw h;\n       inversion ap as [? ? ? ao|]; subst; clear ap;\n       constructor;\n       apply approx_open_vterm_iff_reduces_to in ao;\n       [|apply lsubst_aux_preserves_wf_term2; eauto with slow];\n       apply approx_open_vterm_iff_reduces_to;\n       [apply lsubst_aux_preserves_wf_term2; eauto with slow|];\n       apply (reduces_to_vterm_nrut_sub_change lib t2 sub1 sub2 l); auto\n    ].\n\n    rw h0.\n    apply (apso _ _ _ _ []); simpl; auto; fold_terms.\n    { unfold lblift_sub; simpl; tcsp. }\n    dup Heqsf1 as i.\n    apply sub_find_some in Heqsf1.\n    eapply in_nrut_sub in Heqsf1; eauto; exrepnd; subst.\n    assert (!LIn a0 (get_utokens t2)) as ni by (intro k; apply ss2 in k; sp).\n    inversion ap as [|? ? ? ? ? len lift apo]; subst; allsimpl; cpx; clear lift ap.\n    fold_terms.\n\n    apply approx_open_simpler_equiv in apo.\n    unfold simpl_olift in apo; repnd.\n\n    apply approx_open_simpler_equiv.\n    apply lsubst_aux_nt_wf in apo1.\n    unfold simpl_olift; dands; eauto 3 with slow.\n    introv ps isp1 isp2.\n    rw (cl_lsubst_trivial (mk_utoken a)); simpl; eauto 3 with slow.\n\n    (* replace the [a]s in sub by [a0]s to build a sub' and instantiate apo using that? *)\n\n    rw <- @cl_lsubst_lsubst_aux; eauto 2 with slow.\n    rw <- @cl_lsubst_lsubst_aux in isp2; eauto 2 with slow.\n    rw @cl_lsubst_swap_sub_filter; eauto 2 with slow.\n    rw @cl_lsubst_swap_sub_filter in isp2; eauto 2 with slow.\n    remember (sub_filter sub (dom_sub sub2)) as sub0.\n\nLemma pull_out_nrut_sub_from_term {o} :\n  forall (t : @NTerm o) (sub : @Sub o) l,\n    nrut_sub l sub\n    -> {t' : NTerm\n        & t = lsubst t' sub\n        # disjoint (get_utokens t) (get_utokens_sub sub)}.\nProof.\n  nterm_ind t as [v|op bs ind] Case; introv nrut; allsimpl.\n\n  - exists ([] : @Sub o); simpl; dands; auto.\n    unfold get_utokens_sub; simpl; auto.\n\n  - destruct x as [v t].\n    pose proof (IHsub1 sub2 l nrut) as h; exrepnd.\nQed.\n\nLemma pull_out_nrut_sub_from_sub {o} :\n  forall (sub1 sub2 : @Sub o) l,\n    nrut_sub l sub2\n    -> {sub : Sub\n        & sub1 = lsubst_sub sub sub2\n        # disjoint (get_utokens_sub sub) (get_utokens_sub sub2)}.\nProof.\n  induction sub1 as [|x sub1]; introv nrut.\n\n  - exists ([] : @Sub o); simpl; dands; auto.\n    unfold get_utokens_sub; simpl; auto.\n\n  - destruct x as [v t].\n    pose proof (IHsub1 sub2 l nrut) as h; exrepnd.\nQed.\n\n      remember (ren_utokens_sub (nrut_subs_to_utok_ren sub2 sub1) sub0) as sub0'.\n\n      pose proof (dom_sub_ren_utokens_sub (nrut_subs_to_utok_ren sub2 sub1) sub0) as eqdoms0.\n      rw <- Heqsub0' in eqdoms0.\n\n      pose proof (apo sub0') as h; clear apo.\n      rw <- @cl_lsubst_lsubst_aux in h; eauto 2 with slow.\n\n      assertdimp h hh.\n      { subst; eauto with slow. }\n      rw @cl_lsubst_swap_sub_filter in h; eauto 2 with slow.\n      rw eqdoms in h.\n      rw @sub_filter_disjoint1 in h;\n        [|rw eqdoms0; rw Heqsub0; rw <- @dom_sub_sub_filter; complete (eauto with slow)].\n      rw (cl_lsubst_trivial (mk_utoken a0)) in h; simpl; eauto 2 with slow.\n\n      repeat (assertdimp h hh); eauto 2 with slow.\n      { apply (prog_sub_change sub2 sub1); eauto 2 with slow.\n        apply lsubst_program_implies in isp2.\n        unfold isprogram; dands.\n        - unfold closed.\n          rw @free_vars_cl_lsubst; eauto 2 with slow.\n          apply null_iff_nil.\n          apply null_remove_nvars_subvars.\n          eapply subvars_eqvars;[|apply eqvars_sym; apply eqvars_free_vars_disjoint].\n          rw eqdoms0.\n          apply subvars_eq in isp2.\n          eapply subvars_eqvars in isp2;[|apply eqvars_free_vars_disjoint].\n          rw Heqsub0'.\n          rw @sub_keep_first_ren_utokens_sub.\n          rw @sub_free_vars_ren_utokens_sub; auto.\n        - apply lsubst_wf_if_eauto; eauto with slow. }\n\n      apply approx_utoken_implies_reduces_to in h.\n      apply reduces_to_implies_approx1; auto.\n\n(* pull out the atoms from [lsubst t2 sub0'] in [h]\n   and from [lsubst t2 sub0] in the conclusion.\n   Something like that, maybe:\n *)\n\nLemma xxx {o} :\n  forall (t : @NTerm o) (sub sub1 sub2 : @Sub o) l,\n    let sub' := ren_utokens_sub (nrut_subs_to_utok_ren sub2 sub1) sub in\n    nrut_sub l sub1\n    -> nrut_sub l sub2\n    -> dom_sub sub1 = dom_sub sub2\n    -> {sub0 : Sub\n        & sub' = lsubst_sub sub0 sub1\n        # sub  = lsubst_sub sub0 sub2\n        # disjoint (get_utokens_sub sub1) (get_utokens_sub sub0)\n        # disjoint (get_utokens_sub sub2) (get_utokens_sub sub0)}.\n\nCheck reduces_in_atmost_k_steps_change_utok_sub.\n\nXXXXXXX\n\n      unfold reduces_to in h; exrepnd.\n\n(*\n      pose proof (reduces_in_atmost_k_steps_change_utok_sub\n                    lib k t (mk_utoken a0) sub1 sub2) as h.\n      repeat (autodimp h hyp); eauto 3 with slow.\n*)\n\n(*\nXXXXXXXXXXXXXXXXXX\n\n      pose proof (apo sub) as h; clear apo.\n      rw (cl_lsubst_trivial (mk_utoken a0)) in h; simpl; eauto 3 with slow.\n      repeat (autodimp h hyp); eauto 2 with slow.\n      { rw <- @cl_lsubst_lsubst_aux; eauto 2 with slow.\n        rw <- @cl_lsubst_lsubst_aux in isp2; eauto 2 with slow.\n        rw @cl_lsubst_swap_sub_filter in isp2; eauto 2 with slow.\n        rw @cl_lsubst_swap_sub_filter; eauto 2 with slow.\n        rw eqdoms.\n        eapply prog_sub_change; eauto with slow. }\n\n      rw <- @cl_lsubst_lsubst_aux in h; eauto 2 with slow.\n      rw @cl_lsubst_swap_sub_filter in h; eauto 2 with slow.\n      rw eqdoms in h.\n\n      remember (lsubst t2 (sub_filter sub (dom_sub sub2))) as t.\n\n      apply approx_utoken_implies_reduces_to in h.\n      unfold reduces_to in h; exrepnd.\n      pose proof (reduces_in_atmost_k_steps_change_utok_sub\n                    lib k t (mk_utoken a0) sub1 sub2) as h.\n      repeat (autodimp h hyp); eauto 3 with slow.\n\n      assert (subset (get_utokens t) l) as ss3.\n      {\n        subst; introv j; apply get_utokens_lsubst in j.\n        allrw in_app_iff; repndors; tcsp.\n        rw @sub_keep_first_sub_filter in j.\n        apply in_get_utokens_sub in j; exrepnd.\n        apply in_sub_filter in j0; repnd.\n        apply in_sub_keep_first in j2; repnd.\n\n      }\n*)\n\nAbort.\n*)\n\n\nLemma isprogram_ren_utokens_iff {o} :\n  forall (ren : @utok_ren o) (t : NTerm),\n    isprogram (ren_utokens ren t) <=> isprogram t.\nProof.\n  introv; split; intro k; try (apply isprogram_ren_utokens); auto.\n  allunfold @isprogram; repnd; allunfold @closed.\n  allrw @free_vars_ren_utokens; dands; auto.\n  allrw @nt_wf_ren_utokens_iff; auto.\nQed.\n\nLemma prog_sub_ren_utokens_sub_iff {o} :\n  forall (ren : @utok_ren o) (sub : Sub),\n    prog_sub (ren_utokens_sub ren sub) <=> prog_sub sub.\nProof.\n  induction sub; allsimpl; tcsp.\n  destruct a as [v t]; allsimpl; allrw @prog_sub_cons.\n  rw IHsub; rw @isprogram_ren_utokens_iff; sp.\nQed.\n\nLemma approx_open_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_open lib t1 t2\n    -> approx_open lib (ren_utokens ren t1) (ren_utokens ren t2).\nProof.\n  introv norep1 norep2 disj1 disj2 apo.\n\n  allrw <- @approx_open_simpler_equiv.\n  allunfold @simpl_olift.\n  repnd.\n  allrw @nt_wf_ren_utokens_iff; dands; auto.\n  introv ps isp1 isp2.\n\n  pose proof (ex_ren_utokens_sub\n                sub\n                ren\n                (get_utokens t1 ++ get_utokens t2)) as exren.\n  autodimp exren hyp; exrepnd.\n\n  pose proof (apo sub') as h.\n  repeat (autodimp h hyp).\n  { subst; allrw @prog_sub_ren_utokens_sub_iff; 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 (approx_change_utoks lib (lsubst t1 sub') (lsubst t2 sub') (ren ++ ren')) as k.\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 k 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 b2; repnd.\n      pose proof (exren1 t) as hh.\n      repeat (autodimp hh hyp).\n      rw lin_flat_map; apply sub_find_some in b3; apply in_sub_eta in b3; 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 b2; repnd.\n      pose proof (exren1 t) as hh.\n      repeat (autodimp hh hyp).\n      rw lin_flat_map; apply sub_find_some in b3; apply in_sub_eta in b3; 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 k).\n      rw exren0 in k.\n      repeat (rw @ren_utokens_app_weak_l in k; eauto 2 with slow).\n    }\nQed.\n\nDefinition utok_ren_cond2 {o} atoms (ren ren' : @utok_ren o) :=\n  forall a,\n    LIn a atoms\n    -> LIn a (range_utok_ren ren)\n    -> !LIn a (dom_utok_ren ren)\n    -> LIn a (dom_utok_ren ren').\n\nDefinition utok_ren_cond2_nil {o} :\n  forall (ren1 ren2 : @utok_ren o),\n    utok_ren_cond2 [] ren1 ren2.\nProof.\n  introv i j k; allsimpl; tcsp.\nQed.\nHint Resolve utok_ren_cond2_nil : slow.\n\nDefinition utok_ren_cond2_app {o} :\n  forall atoms1 atoms2 (ren1 ren2 : @utok_ren o),\n    utok_ren_cond2 atoms1 ren1 ren2\n    -> utok_ren_cond2 atoms2 ren1 ren2\n    -> utok_ren_cond2 (atoms1 ++ atoms2) ren1 ren2.\nProof.\n  introv c1 c2 i j k; allsimpl; tcsp.\n  allrw in_app_iff; repndors.\n  - apply c1 in i; repeat (autodimp i hyp).\n  - apply c2 in i; repeat (autodimp i hyp).\nQed.\nHint Resolve utok_ren_cond2_app : slow.\n\nLemma ex_ren_atom2 {o} :\n  forall (a : get_patom_set o) ren atoms,\n    {ren' : utok_ren\n     & disjoint (range_utok_ren ren') (a :: atoms ++ dom_utok_ren ren ++ range_utok_ren ren)\n     # disjoint (dom_utok_ren ren') (dom_utok_ren ren)\n     # subset (dom_utok_ren ren') (range_utok_ren ren)\n     # subset (dom_utok_ren ren') [a]\n     # no_repeats (dom_utok_ren ren')\n     # no_repeats (range_utok_ren ren')\n     # utok_ren_cond2 [a] ren ren' }.\nProof.\n  introv.\n  destruct (in_deq _ (get_patom_deq o) a (dom_utok_ren ren)) as [d|d].\n\n  - exists ([] : @utok_ren o); allsimpl; dands; tcsp.\n    introv i j k; allsimpl; repndors; subst; tcsp.\n\n  - destruct (in_deq _ (get_patom_deq o) a (range_utok_ren ren)) as [r|r].\n\n    + pose proof (fresh_atom o (a :: atoms ++ dom_utok_ren ren ++ range_utok_ren ren)) as h.\n      exrepnd.\n      exists [(a,x)]; simpl.\n      allrw disjoint_singleton_l.\n      rw singleton_subset.\n      dands; auto.\n      introv i j k; allsimpl; repndors; subst; tcsp.\n\n    + exists ([] : @utok_ren o); allsimpl; dands; tcsp.\n      introv i j k; allsimpl; repndors; subst; tcsp.\nQed.\n\nLemma ex_ren_utokens_o2 {o} :\n  forall (op : @Opid o) ren atoms,\n    {ren' : utok_ren\n     & disjoint (range_utok_ren ren') (get_utokens_o op ++ atoms ++ dom_utok_ren ren ++ range_utok_ren ren)\n     # disjoint (dom_utok_ren ren') (dom_utok_ren ren)\n     # subset (dom_utok_ren ren') (range_utok_ren ren)\n     # subset (dom_utok_ren ren') (get_utokens_o op)\n     # no_repeats (dom_utok_ren ren')\n     # no_repeats (range_utok_ren ren')\n     # utok_ren_cond2 (get_utokens_o op) ren ren' }.\nProof.\n  introv.\n  remember (get_utok op) as guo; symmetry in Heqguo; destruct guo.\n  - apply get_utok_some in Heqguo; subst; allsimpl.\n    pose proof (ex_ren_atom2 g ren atoms) as h; exrepnd.\n    exists ren'; dands; auto.\n  - exists ([] : @utok_ren o); allsimpl; dands; auto.\n    apply get_utok_none in Heqguo; allrw; eauto with slow.\nQed.\n\nLemma ex_ren_utokens2 {o} :\n  forall (t : @NTerm o) ren atoms,\n    {ren' : utok_ren\n     & disjoint (range_utok_ren ren') (get_utokens t ++ atoms ++ dom_utok_ren ren ++ range_utok_ren ren)\n     # disjoint (dom_utok_ren ren') (dom_utok_ren ren)\n     # subset (dom_utok_ren ren') (range_utok_ren ren)\n     # subset (dom_utok_ren ren') (get_utokens t)\n     # no_repeats (dom_utok_ren ren')\n     # no_repeats (range_utok_ren ren')\n     # utok_ren_cond2 (get_utokens t) ren ren' }.\nProof.\n  nterm_ind t as [v|f ind|op bs ind] Case; introv.\n\n  - Case \"vterm\".\n    exists ([] : @utok_ren o); simpl; dands; eauto with slow.\n\n  - Case \"sterm\".\n    exists ([] : @utok_ren o); simpl; dands; eauto with slow.\n\n  - Case \"oterm\".\n\n    assert\n      (forall atoms ren,\n         {ren' : utok_ren\n          & disjoint (range_utok_ren ren') (get_utokens_bs bs ++ atoms ++ dom_utok_ren ren ++ range_utok_ren ren)\n          # disjoint (dom_utok_ren ren') (dom_utok_ren ren)\n          # subset (dom_utok_ren ren') (range_utok_ren ren)\n          # subset (dom_utok_ren ren') (get_utokens_bs bs)\n          # no_repeats (dom_utok_ren ren')\n          # no_repeats (range_utok_ren ren')\n          # utok_ren_cond2 (get_utokens_bs bs) ren ren' }) as ebs.\n    { clear ren atoms.\n      induction bs; introv.\n      - exists ([] : @utok_ren o); simpl; dands; eauto with slow.\n      - destruct a as [l t].\n        autodimp IHbs hyp.\n        { introv i; apply (ind nt lv); eauto; simpl; sp. }\n        pose proof (IHbs (atoms ++ get_utokens t) ren) as ibs; clear IHbs; exrepnd; allsimpl.\n        pose proof (ind t l) as h; clear ind; autodimp h hyp.\n        pose proof (h (ren ++ ren') (get_utokens_bs bs ++ atoms)) as k; clear h; exrepnd.\n        exists (ren' ++ ren'0); simpl.\n        allrw @range_utok_ren_app.\n        allrw @dom_utok_ren_app.\n        allrw no_repeats_app.\n        allrw disjoint_app_l.\n        allrw subset_app.\n        allrw disjoint_app_r.\n        allrw app_assoc.\n        repnd; dands; eauto 2 with slow.\n\n        {\n          introv i; applydup k3 in i as j; allrw in_app_iff; repndors; tcsp.\n          apply k4 in i; apply ibs8 in j; sp.\n        }\n\n        {\n          apply utok_ren_cond2_app; auto.\n          - introv i j k.\n            applydup k0 in i.\n            allrw @range_utok_ren_app.\n            allrw @dom_utok_ren_app.\n            allrw in_app_iff; allrw not_over_or.\n            destruct (in_deq _ (get_patom_deq o) a (dom_utok_ren ren')) as [d|d]; tcsp.\n          - introv i j k.\n            applydup ibs0 in i.\n            allrw @dom_utok_ren_app; allrw in_app_iff.\n            repeat (autodimp i0 hyp).\n        }\n    }\n\n    pose proof (ebs (atoms ++ get_utokens_o op) ren) as ebs'; clear ebs; exrepnd.\n\n    pose proof (ex_ren_utokens_o2 op (ren ++ ren') (get_utokens_bs bs ++ atoms)) as eop; exrepnd.\n    allrw @range_utok_ren_app.\n    allrw @dom_utok_ren_app.\n    allrw disjoint_app_l; repnd.\n    allrw disjoint_app_r; repnd.\n\n    exists (ren' ++ ren'0); simpl.\n    allrw @range_utok_ren_app.\n    allrw @dom_utok_ren_app.\n    allrw no_repeats_app.\n    allrw subset_app.\n    allrw disjoint_app_l; allrw disjoint_app_r.\n    repeat (rw app_assoc).\n    dands; eauto 3 with slow.\n\n    {\n      introv i; applydup eop3 in i as j; allrw in_app_iff; repndors; tcsp.\n      apply eop4 in i; apply ebs'8 in j; sp.\n    }\n\n    {\n      apply utok_ren_cond2_app; auto.\n      - introv i j k.\n        applydup eop0 in i.\n        allrw @range_utok_ren_app.\n        allrw @dom_utok_ren_app.\n        allrw in_app_iff; allrw not_over_or.\n        destruct (in_deq _ (get_patom_deq o) a (dom_utok_ren ren')) as [d|d]; tcsp.\n      - introv i j k.\n        applydup ebs'0 in i.\n        allrw @dom_utok_ren_app; allrw in_app_iff.\n        repeat (autodimp i0 hyp).\n    }\nQed.\n\nLemma ex_ren_utokens_sub2 {o} :\n  forall (sub : @Sub o) ren atoms,\n    {ren' : utok_ren\n     & disjoint (range_utok_ren ren') (get_utokens_sub sub ++ atoms ++ dom_utok_ren ren ++ range_utok_ren ren)\n     # disjoint (dom_utok_ren ren') (dom_utok_ren ren)\n     # subset (dom_utok_ren ren') (range_utok_ren ren)\n     # subset (dom_utok_ren ren') (get_utokens_sub sub)\n     # no_repeats (dom_utok_ren ren')\n     # no_repeats (range_utok_ren ren')\n     # utok_ren_cond2 (get_utokens_sub sub) ren ren' }.\nProof.\n  induction sub; introv.\n  - exists ([] : @utok_ren o); simpl; rw @get_utokens_sub_nil; dands; eauto with slow.\n  - destruct a as [v t]; allsimpl.\n    pose proof (IHsub ren (atoms ++ get_utokens t)) as ih; clear IHsub; exrepnd.\n\n    pose proof (ex_ren_utokens2 t (ren ++ ren') (get_utokens_sub sub ++ atoms)) as h; exrepnd.\n\n    exists (ren' ++ ren'0); simpl.\n    repeat (rw app_assoc).\n    allrw @range_utok_ren_app.\n    allrw @dom_utok_ren_app.\n    allrw no_repeats_app.\n    allrw @get_utokens_sub_cons.\n    allrw disjoint_app_l; allrw disjoint_app_r.\n    allrw subset_app.\n\n    repnd; dands; eauto 3 with slow.\n\n    {\n      introv i; applydup h3 in i as j; allrw in_app_iff; repndors; tcsp.\n      apply h4 in i; apply ih8 in j; sp.\n    }\n\n    {\n      apply utok_ren_cond2_app; auto.\n      - introv i j k.\n        applydup h0 in i.\n        allrw @range_utok_ren_app.\n        allrw @dom_utok_ren_app.\n        allrw in_app_iff; allrw not_over_or.\n        destruct (in_deq _ (get_patom_deq o) a (dom_utok_ren ren')) as [d|d]; tcsp.\n      - introv i j k.\n        applydup ih0 in i.\n        allrw @dom_utok_ren_app; allrw in_app_iff.\n        repeat (autodimp i0 hyp).\n    }\nQed.\n\nLemma ren_utokens_o_app_weak_l {o} :\n  forall (op : @Opid o) ren1 ren2,\n    disjoint (dom_utok_ren ren2) (get_utokens_o op)\n    -> ren_utok_op (ren1 ++ ren2) op\n       = ren_utok_op ren1 op.\nProof.\n  introv disj.\n  destruct op; tcsp.\n  destruct c; tcsp.\n  allsimpl.\n  allrw disjoint_cons_r; repnd.\n  rw @ren_atom_app_weak_l; auto.\nQed.\n\nLemma length_ren_utokens_bs {o} :\n  forall (bs : list (@BTerm o)) ren,\n    length (ren_utokens_bs ren bs) = length bs.\nProof.\n  induction bs; introv; allsimpl; tcsp.\nQed.\n\nLemma ren_utok_op_diff_fresh {o} :\n  forall (op : @Opid o) ren,\n    (ren_utok_op ren op = NCan NFresh) <=> (op = NCan NFresh).\nProof.\n  introv; split; intro e; subst; tcsp.\n  destruct op; tcsp.\n  destruct c; tcsp.\n  allsimpl; ginv.\nQed.\n\nLemma ut_sub_ren_utokens_sub {o} :\n  forall (sub : @Sub o) ren,\n    ut_sub sub\n    -> ut_sub (ren_utokens_sub ren sub).\nProof.\n  induction sub; introv uts; allsimpl; tcsp.\n  destruct a as [v t]; allrw @ut_sub_cons; repnd; dands; tcsp.\n  allunfold @isutoken; exrepnd; subst; allsimpl; fold_terms.\n  eexists; dands; eauto.\nQed.\nHint Resolve ut_sub_ren_utokens_sub : slow.\n\nLemma nrut_sub_implies_ut_sub {o} :\n  forall (sub : @Sub o) l,\n    nrut_sub l sub -> ut_sub sub.\nProof.\n  introv nrut; unfold nrut_sub in nrut; sp.\nQed.\nHint Resolve nrut_sub_implies_ut_sub : slow.\n\nLemma utok_ren_cond_app_iff {o} :\n  forall (atoms1 atoms2 : list (get_patom_set o)) (ren : utok_ren),\n    utok_ren_cond (atoms1 ++ atoms2) ren\n    <=> (utok_ren_cond atoms1 ren # utok_ren_cond atoms2 ren).\nProof.\n  introv; split; intro k; try (apply utok_ren_cond_app; tcsp).\n  dands; introv i j; pose proof (k a) as h; allrw in_app_iff; tcsp.\nQed.\n\nLemma false_if_utok_ren_cond_on_eq_ren_atoms {o} :\n  forall ren (a b : @get_patom_set o) atoms1 atoms2,\n    no_repeats (range_utok_ren ren)\n    -> utok_ren_cond atoms1 ren\n    -> utok_ren_cond atoms2 ren\n    -> disjoint atoms1 atoms2\n    -> LIn a atoms1\n    -> LIn b atoms2\n    -> ren_atom ren a = ren_atom ren b\n    -> False.\nProof.\n  introv nrr cond1 cond2 disj ia ib e.\n  destruct (get_patom_deq o a b) as [x|x]; subst; tcsp.\n  { apply disj in ib; sp. }\n\n  pose proof (in_deq _ (get_patom_deq o) a (dom_utok_ren ren)) as [d1|d1];\n    pose proof (in_deq _ (get_patom_deq o) b (dom_utok_ren ren)) as [d2|d2].\n\n  + apply ren_atom_eq1 in e; sp.\n\n  + rw (ren_atom_not_in ren b) in e; auto.\n\n    pose proof (in_deq _ (get_patom_deq o) b (range_utok_ren ren)) as [r|r].\n\n    * pose proof (cond2 b) as h; allsimpl; repeat (autodimp h hyp).\n\n    * pose proof (in_dom_in_range ren a d1) as h.\n      rw e in h; sp.\n\n  + rw (ren_atom_not_in ren a) in e; auto.\n\n    pose proof (in_deq _ (get_patom_deq o) a (range_utok_ren ren)) as [r|r].\n\n    * pose proof (cond1 a) as h; allsimpl; repeat (autodimp h hyp).\n\n    * pose proof (in_dom_in_range ren b d2) as h.\n      rw <- e in h; sp.\n\n  + rw (ren_atom_not_in ren a) in e; auto.\n    rw (ren_atom_not_in ren b) in e; auto.\nQed.\n\nLemma no_repeats_get_utokens_ren_utokens {o} :\n  forall (t : @NTerm o) ren,\n    no_repeats (range_utok_ren ren)\n    -> no_repeats (get_utokens t)\n    -> utok_ren_cond (get_utokens t) ren\n    -> no_repeats (get_utokens (ren_utokens ren t)).\nProof.\n  nterm_ind t as [v|f ind|op bs ind] Case; introv nrr nrt cond; allsimpl; auto.\n  Case \"oterm\".\n  allrw no_repeats_app; repnd; dands; eauto 3 with slow.\n\n  - destruct op; tcsp.\n    destruct c; allsimpl; tcsp.\n\n  - rw flat_map_map; unfold compose.\n\n    induction bs; allsimpl; tcsp.\n    allrw disjoint_app_r; repnd.\n    allrw no_repeats_app; repnd.\n    repeat (autodimp IHbs hyp).\n    { introv i nr1 nr2; eapply ind; eauto. }\n    { allrw @utok_ren_cond_app_iff; tcsp. }\n    dands; eauto 3 with slow.\n\n    + destruct a as [l t]; allsimpl.\n      eapply ind; eauto.\n      allrw @utok_ren_cond_app_iff; tcsp.\n\n    + destruct a as [l1 t1]; allsimpl.\n      allrw disjoint_flat_map_r.\n      introv i; destruct x as [l2 t2]; allsimpl.\n      applydup nrt1 in i; allsimpl.\n      allrw @get_utokens_ren_utokens.\n      apply disjoint_map_l; introv a b; allrw in_map_iff; exrepnd.\n\n      allrw @utok_ren_cond_app_iff; repnd.\n      pose proof (false_if_utok_ren_cond_on_eq_ren_atoms\n                    ren x a0 (get_utokens t1) (get_utokens t2)) as h.\n      repeat (autodimp h hyp).\n      introv p q; apply cond; auto.\n      rw lin_flat_map; eexists; dands; eauto.\n\n  - destruct op; try (complete (allsimpl; tcsp)).\n    destruct c; allsimpl; tcsp.\n    allrw disjoint_singleton_l.\n    intro i.\n    allrw flat_map_map; allunfold @compose.\n    allrw lin_flat_map; exrepnd.\n    destruct x as [l t]; allsimpl.\n    allrw @get_utokens_ren_utokens; allrw in_map_iff; exrepnd.\n\n    rw cons_as_app in cond.\n    allrw @utok_ren_cond_app_iff; repnd.\n\n    pose proof (false_if_utok_ren_cond_on_eq_ren_atoms\n                  ren g a [g] (get_utokens t)) as h.\n    repeat (autodimp h hyp); allsimpl; tcsp.\n\n    + introv p q; apply cond; auto.\n      rw lin_flat_map; eexists; dands; eauto.\n\n    + apply disjoint_singleton_l; intro i.\n      destruct nrt; eexists; dands; eauto; simpl; auto.\nQed.\n\nLemma get_utokens_sub_ren_utokens_sub {o} :\n  forall (sub : @Sub o) ren,\n    get_utokens_sub (ren_utokens_sub ren sub)\n    = map (ren_atom ren) (get_utokens_sub sub).\nProof.\n  induction sub; introv; allsimpl; tcsp.\n  destruct a as [v t]; allsimpl.\n  allrw @get_utokens_sub_cons; allrw map_app.\n  rw IHsub.\n  rw @get_utokens_ren_utokens; auto.\nQed.\n\nLemma no_repeats_get_utokens_sub_ren_utokens_sub {o} :\n  forall (sub : @Sub o) ren,\n    no_repeats (range_utok_ren ren)\n    -> no_repeats (get_utokens_sub sub)\n    -> utok_ren_cond (get_utokens_sub sub) ren\n    -> no_repeats (get_utokens_sub (ren_utokens_sub ren sub)).\nProof.\n  induction sub; introv nrr nrs cond; allsimpl;\n  allrw @get_utokens_sub_nil; auto.\n  destruct a as [v t]; allrw @get_utokens_sub_cons.\n  allrw @utok_ren_cond_app_iff; repnd.\n  allrw no_repeats_app; dands; repnd; eauto 3 with slow.\n  - apply no_repeats_get_utokens_ren_utokens; auto.\n  - allrw @get_utokens_ren_utokens.\n    allrw @get_utokens_sub_ren_utokens_sub.\n    clear IHsub.\n    remember (get_utokens t) as atoms1; clear Heqatoms1.\n    remember (get_utokens_sub sub) as atoms2; clear Heqatoms2.\n    introv i j.\n    allrw in_map_iff; exrepnd; subst.\n    pose proof (false_if_utok_ren_cond_on_eq_ren_atoms\n                  ren a0 a atoms2 atoms1) as h.\n    repeat (autodimp h hyp); eauto with slow.\nQed.\nHint Resolve no_repeats_get_utokens_sub_ren_utokens_sub : slow.\n\nLemma nrut_sub_implies_no_repeats {o} :\n  forall (sub : @Sub o) l,\n    nrut_sub l sub\n    -> no_repeats (get_utokens_sub sub).\nProof.\n  introv nr; unfold nrut_sub in nr; sp.\nQed.\nHint Resolve nrut_sub_implies_no_repeats : slow.\n\nLemma change_nr_ut_sub_in_lsubst_aux_approx_star {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_star lib t1 t2\n    -> approx_star lib (ren_utokens ren t1) (ren_utokens ren t2).\nProof.\n  nterm_ind1s t1 as [v1|f1 ind1|op1 bs1 ind1] Case; introv norep1 norep2 disj1 disj2 apr.\n\n  - Case \"vterm\".\n    allsimpl.\n    constructor.\n    inversion apr as [? ? ? apo|?|]; subst; clear apr.\n\n    pose proof (approx_open_change_utoks lib (vterm v1) t2 ren) as h.\n    repeat (autodimp h hyp).\n\n  - Case \"sterm\".\n    allsimpl.\n    inversion apr as [|? ? ? ? imp aop|]; subst; clear apr.\n    econstructor; eauto.\n    apply (approx_open_change_utoks _ _ _ ren) in aop; auto.\n\n  - Case \"oterm\".\n    inversion apr as [|?|? ? ? ? ? len lift apo]; subst.\n\n    pose proof (ex_ren_utokens2\n                  (oterm op1 lbt1')\n                  ren\n                  (get_utokens (oterm op1 bs1) ++ get_utokens t2))\n      as extra_ren; exrepnd.\n    allsimpl; allrw disjoint_app_r; repnd.\n\n    pose proof (approx_open_change_utoks lib (oterm op1 lbt1') t2 (ren ++ ren')) as h.\n    allrw @range_utok_ren_app.\n    allrw @dom_utok_ren_app.\n    allrw no_repeats_app.\n    allrw disjoint_app_l; allrw disjoint_app_r.\n    repeat (autodimp h hyp); dands; eauto 3 with slow.\n\n    { introv i j; allrw in_diff; allsimpl; allrw in_app_iff; allrw not_over_or; repnd.\n      pose proof (extra_ren0 t) as h; allrw in_app_iff; repeat (autodimp h hyp). }\n\n    { introv i j; allrw in_diff; allsimpl; allrw in_app_iff; allrw not_over_or; repnd.\n      applydup extra_ren12 in i.\n      applydup extra_ren7 in i.\n      repndors; tcsp. }\n\n    { introv i j; apply disj2 in i; allrw in_diff; allrw in_app_iff; allrw not_over_or; tcsp. }\n\n    { introv i j; allrw in_diff; allrw in_app_iff; allrw not_over_or; repnd.\n      apply extra_ren8 in i; sp. }\n\n    allsimpl.\n    rw (ren_utokens_app_weak_l t2) in h;\n      [|introv i j; applydup extra_ren3 in i;\n        applydup disj2 in i0; allrw in_diff; tcsp].\n    rw (ren_utokens_o_app_weak_l op1) in h;\n      [|introv i j; applydup extra_ren3 in i;\n        applydup disj1 in i0; allrw in_diff;\n        allrw in_app_iff; tcsp].\n\n    apply (apso _ _ _ _ (ren_utokens_bs (ren ++ ren') lbt1'));\n    allrw map_length; allrw @length_ren_utokens_bs; auto.\n\n    allunfold @lblift_sub;\n    allrw map_length; allrw @length_ren_utokens_bs;\n    repnd; dands; auto.\n\n    introv i.\n    applydup lift in i; clear lift.\n    allunfold @blift_sub; exrepnd.\n    exists lv (ren_utokens ren nt1) (ren_utokens (ren ++ ren') nt2).\n    dands; auto;\n    [|rw @selectbt_map; auto;\n      apply (alpha_eq_bterm_ren_utokens_b _ _ ren) in i2;\n      allsimpl; auto\n     |unfold ren_utokens_bs; rw @selectbt_map; auto; try omega;\n      apply (alpha_eq_bterm_ren_utokens_b _ _ (ren ++ ren')) in i1;\n      allsimpl; auto].\n\n    pose proof (selectbt_in n bs1) as in1; autodimp in1 hyp.\n    pose proof (selectbt_in n lbt1') as in2; autodimp in2 hyp; try omega.\n    remember (selectbt bs1 n) as b1.\n    remember (selectbt lbt1' n) as b2.\n    destruct b1 as [l1 u1]; destruct b2 as [l2 u2].\n    applydup @alpha_eq_bterm_preserves_osize in i2 as sz1.\n    applydup @alpha_eq_bterm_preserves_osize in i1 as sz2.\n\n    assert (subset (get_utokens nt1) (get_utokens_bs bs1)) as ss1.\n    { introv a; unfold get_utokens_bs.\n      rw lin_flat_map; eexists; dands; eauto; simpl.\n      apply alpha_eq_bterm_preserves_utokens in i2; allsimpl; rw i2; auto. }\n\n    assert (subset (get_utokens nt2) (get_utokens_bs lbt1')) as ss2.\n    { introv a; unfold get_utokens_bs.\n      rw lin_flat_map; eexists; dands; eauto; simpl.\n      apply alpha_eq_bterm_preserves_utokens in i1; allsimpl; rw i1; auto. }\n\n    repndors;exrepnd;[left|right].\n\n    + dands; auto;[intro e; apply ren_utok_op_diff_fresh in e; auto|].\n      pose proof (ind1 u1 nt1 l1) as q; clear ind1.\n      rw sz1 in q.\n      repeat (autodimp q hyp); eauto 3 with slow.\n      pose proof (q nt2 (ren ++ ren')) as aprs; clear q.\n      allrw @range_utok_ren_app.\n      allrw @dom_utok_ren_app.\n      allrw no_repeats_app.\n      allrw disjoint_app_l; allrw disjoint_app_r.\n      repeat (autodimp aprs hyp); dands; eauto 3 with slow.\n\n      { introv a b; apply disj1 in a; allrw in_diff; allrw in_app_iff; allrw not_over_or; repnd; tcsp. }\n\n      { introv a b; allrw in_diff; allrw in_app_iff; allrw not_over_or; repnd.\n        apply extra_ren10 in a; sp. }\n\n      { introv a b; allrw in_diff; allsimpl; allrw in_app_iff; allrw not_over_or; repnd.\n        pose proof (extra_ren0 t) as q; allrw in_app_iff; repeat (autodimp q hyp). }\n\n      { introv a b; allrw in_diff; allsimpl; allrw in_app_iff; allrw not_over_or; repnd.\n        applydup extra_ren7 in a; tcsp. }\n\n      rw (ren_utokens_app_weak_l nt1) in aprs; auto.\n\n      introv a b.\n      applydup extra_ren3 in a.\n      applydup extra_ren2 in a.\n      applydup disj1 in a0; allrw in_diff; destruct a2; dands; tcsp.\n      rw in_app_iff; right; rw lin_flat_map; eexists; dands; eauto; simpl.\n      apply alpha_eq_bterm_preserves_utokens in i2; allsimpl; rw i2; auto.\n\n    + pose proof (ex_ren_utokens_sub2\n                    sub\n                    (ren ++ ren')\n                    (get_utokens nt1\n                                 ++ get_utokens nt2\n                                 ++ get_utokens (lsubst nt1 sub)\n                                 ++ get_utokens (lsubst nt2 sub)))\n        as extra_ren'; exrepnd.\n      allsimpl; allrw disjoint_app_r; repnd.\n\n      pose proof (ind1 u1 (lsubst nt1 sub) l1) as ih; clear ind1.\n      rw sz1 in ih; repeat (autodimp ih hyp).\n      { rw @simple_osize_lsubst; eauto with slow. }\n      pose proof (ih (lsubst nt2 sub) ((ren ++ ren') ++ ren'0)) as q; clear ih.\n\n      allrw @range_utok_ren_app.\n      allrw @dom_utok_ren_app.\n      allrw no_repeats_app.\n      allrw disjoint_app_l; allrw disjoint_app_r.\n      repnd; repeat (autodimp q hyp); dands; eauto 3 with slow.\n\n      { introv a b; allrw in_diff; allsimpl; allrw in_app_iff; allrw not_over_or; repnd.\n        apply get_utokens_lsubst in b0; allrw in_app_iff; repndors; tcsp.\n        - applydup ss1 in b0.\n          applydup disj1 in a.\n          allrw in_diff; allrw in_app_iff; allrw not_over_or; sp.\n        - apply in_get_utokens_sub in b0; exrepnd.\n          apply in_sub_keep_first in b3; repnd.\n          apply sub_find_some in b4.\n          pose proof (extra_ren'0 t) as r.\n          allrw @range_utok_ren_app; allrw @dom_utok_ren_app.\n          allrw in_app_iff.\n          repeat (autodimp r hyp); tcsp.\n          apply in_get_utokens_sub.\n          eexists; eexists; dands; eauto.\n      }\n\n      { introv a b; 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        - applydup ss1 in b0; tcsp.\n          apply extra_ren10 in a; tcsp.\n        - apply in_get_utokens_sub in b0; exrepnd.\n          apply in_sub_keep_first in b3; repnd.\n          apply sub_find_some in b4.\n          pose proof (extra_ren'0 t) as r.\n          allrw @range_utok_ren_app; allrw @dom_utok_ren_app.\n          allrw in_app_iff.\n          repeat (autodimp r hyp); tcsp.\n          apply in_get_utokens_sub.\n          eexists; eexists; dands; eauto.\n      }\n\n      { introv a b; allrw in_diff; allrw in_app_iff; allrw not_over_or; repnd.\n        apply extra_ren'12 in a; sp.\n      }\n\n      { introv a b; allrw in_diff; allsimpl; allrw in_app_iff; allrw not_over_or; repnd.\n        apply get_utokens_lsubst in b0; allrw in_app_iff; repndors; tcsp.\n        - applydup ss2 in b0.\n          pose proof (extra_ren0 t) as q; allrw in_app_iff.\n          repeat (autodimp q hyp); tcsp.\n        - apply in_get_utokens_sub in b0; exrepnd.\n          apply in_sub_keep_first in b3; repnd.\n          apply sub_find_some in b4.\n          pose proof (extra_ren'0 t) as r.\n          allrw @range_utok_ren_app; allrw @dom_utok_ren_app.\n          allrw in_app_iff.\n          repeat (autodimp r hyp); tcsp.\n          apply in_get_utokens_sub.\n          eexists; eexists; dands; eauto.\n      }\n\n      { introv a b; 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        - applydup ss2 in b0.\n          apply extra_ren7 in a; tcsp.\n        - apply in_get_utokens_sub in b0; exrepnd.\n          apply in_sub_keep_first in b3; repnd.\n          apply sub_find_some in b4.\n          pose proof (extra_ren'0 t) as r.\n          allrw @range_utok_ren_app; allrw @dom_utok_ren_app.\n          allrw in_app_iff.\n          repeat (autodimp r hyp); tcsp.\n          apply in_get_utokens_sub.\n          eexists; eexists; dands; eauto.\n      }\n\n      { introv a b; allrw in_diff; allrw in_app_iff; allrw not_over_or; repnd.\n        apply extra_ren'8 in a; sp.\n      }\n\n      repeat (rw @lsubst_ren_utokens in q).\n\n      assert (disjoint (dom_utok_ren ren'0) (get_utokens nt1)) as disj'0nt1.\n      { introv a b.\n        applydup extra_ren'3 in a.\n        applydup extra_ren'2 in a.\n        allrw in_app_iff.\n        repndors; tcsp.\n        - applydup extra_ren'13 in a.\n          applydup disj1 in a0; allrw in_diff; allrw in_app_iff; allrw not_over_or.\n          destruct a3; dands; tcsp.\n        - apply extra_ren10 in a0; tcsp.\n      }\n\n      pose proof (ren_utokens_app_weak_l nt1 (ren ++ ren') ren'0 disj'0nt1) as e1.\n      rw e1 in q.\n\n      assert (disjoint (dom_utok_ren ren') (get_utokens nt1)) as disj'nt1.\n      { introv a b.\n        applydup extra_ren3 in a.\n        applydup extra_ren2 in a.\n        applydup disj1 in a0; allrw in_diff; destruct a2; dands; tcsp.\n        rw in_app_iff; right; rw lin_flat_map; eexists; dands; eauto; simpl.\n        apply alpha_eq_bterm_preserves_utokens in i2; allsimpl; rw i2; auto.\n      }\n\n      pose proof (ren_utokens_app_weak_l nt1 ren ren' disj'nt1) as e2.\n      rw e2 in q.\n\n      assert (disjoint (dom_utok_ren ren'0) (get_utokens nt2)) as disj'0nt2.\n      { introv a b.\n        applydup extra_ren'3 in a.\n        applydup extra_ren'2 in a.\n        allrw in_app_iff.\n        repndors; tcsp.\n        - applydup extra_ren'13 in a.\n          pose proof (extra_ren0 t) as r; allrw in_app_iff.\n          repeat (autodimp r hyp); tcsp.\n        - apply extra_ren7 in a0; tcsp.\n      }\n\n      pose proof (ren_utokens_app_weak_l nt2 (ren ++ ren') ren'0 disj'0nt2) as e3.\n      rw e3 in q.\n\n      exists (ren_utokens_sub ((ren ++ ren') ++ ren'0) sub).\n      rw @ren_utok_op_diff_fresh.\n      rw @dom_sub_ren_utokens_sub.\n      dands; auto.\n\n      assert (no_repeats (range_utok_ren ((ren ++ ren') ++ ren'0))) as norep_ren.\n      { repeat (rw @range_utok_ren_app).\n        repeat (rw no_repeats_app).\n        rw disjoint_app_l; dands; eauto with slow. }\n\n      assert (utok_ren_cond (get_utokens_sub sub) ((ren ++ ren') ++ ren'0)) as cond1.\n      { introv x y.\n        pose proof (extra_ren'0 a) as r.\n        allrw @dom_utok_ren_app; allrw @range_utok_ren_app.\n        allrw in_app_iff; allrw not_over_or.\n        repndors.\n        - destruct (in_deq _ (get_patom_deq o) a (dom_utok_ren ren)); tcsp.\n          destruct (in_deq _ (get_patom_deq o) a (dom_utok_ren ren')); tcsp.\n        - destruct (in_deq _ (get_patom_deq o) a (dom_utok_ren ren)); tcsp.\n          destruct (in_deq _ (get_patom_deq o) a (dom_utok_ren ren')); tcsp.\n        - apply extra_ren'7 in y; sp. }\n\n      assert (utok_ren_cond (get_utokens nt1) ren) as cond2.\n      { introv x y.\n        applydup ss1 in x.\n        applydup disj1 in y.\n        rw in_diff in y0; rw in_app_iff in y0.\n        destruct (in_deq _ (get_patom_deq o) a (dom_utok_ren ren)); tcsp.\n        destruct y0; dands; tcsp.\n      }\n\n      assert (utok_ren_cond (get_utokens nt2) (ren ++ ren')) as cond3.\n      { introv x y.\n        applydup ss2 in x.\n        allrw @range_utok_ren_app.\n        allrw @dom_utok_ren_app.\n        pose proof (extra_ren0 a) as r.\n        allrw in_app_iff.\n        destruct (in_deq _ (get_patom_deq o) a (dom_utok_ren ren)); tcsp.\n        repndors; tcsp.\n        clear r.\n        apply extra_ren7 in y; sp.\n      }\n\n      unfold nrut_sub; dands; eauto 3 with slow.\n\n      rw <- e3; rw <- e2; rw <- e1.\n      repeat (rw @get_utokens_ren_utokens).\n      rw @get_utokens_sub_ren_utokens_sub.\n      rw <- map_app.\n      apply disjoint_map_l; introv u v.\n      rw in_map_iff in v; exrepnd.\n\n      pose proof (false_if_utok_ren_cond_on_eq_ren_atoms\n                    ((ren ++ ren') ++ ren'0)\n                    x a\n                    (get_utokens nt1 ++ get_utokens nt2)\n                    (get_utokens_sub sub)) as hh.\n      allunfold @nrut_sub; repnd.\n      repeat (autodimp hh hyp); tcsp.\n\n      clear u.\n      apply utok_ren_cond_app.\n\n      { introv z w.\n        applydup cond2 in z.\n        allrw @range_utok_ren_app.\n        allrw @dom_utok_ren_app.\n        allrw in_app_iff.\n        repndors; tcsp.\n        - apply extra_ren10 in w.\n          apply ss1 in z; sp.\n        - apply extra_ren'10 in w; sp.\n      }\n\n      { introv z w.\n        applydup cond3 in z.\n        allrw @range_utok_ren_app.\n        allrw @dom_utok_ren_app.\n        allrw in_app_iff.\n        repndors; tcsp.\n        apply extra_ren'11 in w; sp.\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/approx_star_props2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5621765155565327, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.28547990441875004}}
{"text": "Require Import String.\nRequire Import ExtLib.Data.Strings.\nRequire Import CoqCompile.Parse.\nRequire Import CoqCompile.Lambda.\nRequire Import CoqCompile.CpsKConvert.\nRequire Import CoqCompile.CpsCommon.\nRequire Import CoqCompile.Cps.\nRequire Import CoqCompile.CpsK.\nRequire Import CoqCompile.CpsKExamples.\nRequire Import CoqCompile.CloConvK.\nRequire Import CoqCompile.CpsK2Low.\nRequire Import CoqCompile.Low.\n\n(*\nExtraction Language Scheme.\nRecursive Extraction fact.\n*)\n\nDefinition lambda2low (e:option Lambda.exp) : string.\nrefine (\n  match e with\n    | Some e =>\n      let cps_e := CpsKConvert.CPS_io e in\n      match CPSK.exp_sane (m' := sum string) cps_e with\n        | inl err => \"CpsConv: \" ++ err ++ (String Char.chr_newline (CPSK.exp2string cps_e))\n        | inr _ =>\n          match ClosureConvert.cloconv_exp cps_e with\n            | inl ex => \"CloConv: \" ++ ex ++ (String Char.chr_newline (CPSK.exp2string cps_e))\n            | inr (ds, e) => (* CPSK.exp2string e *)\n              match @cpsk2low (sum string) _ _ ds e with\n                | inl ex => \"Lower: \" ++ ex ++ (String Char.chr_newline (CPSK.exp2string cps_e)) (* (String Char.chr_newline (CPSK.exp2string (CPSK.Letrec_e ds e))) *)\n                | inr prog => string_of_program prog\n              end\n          end\n      end\n    | None => \"Parsing failed\"%string\n  end%string\n).\nDefined.\n\n\nEval compute in lambda2low (Some plus_lam).\nEval compute in lambda2low (Some mult_lam).\nEval compute in lambda2low (Some fact_lam).\n\nDefinition identity : string := \"(define ident33 (lambda (x) x))\"%string.\nDefinition identity_e := Parse.parse_topdecls identity.\nEval vm_compute in lambda2low identity_e.\n\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/Test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.28547989696877696}}
{"text": "Require Import Template.All.\nRequire Import List.\nImport ListNotations.\n\n\n(* Taken from the template-coq parametricity translation *)\n\nDefinition tsl_table := list (global_reference * term).\n\nFixpoint lookup_tsl_table (E : tsl_table) (gr : global_reference)\n  : option term :=\n  match E with\n  | nil => None\n  | hd :: tl =>\n    if gref_eq_dec gr (fst hd) then Some (snd hd)\n    else lookup_tsl_table tl gr\n  end.\n\nDefinition default_term := tVar \"constant_not_found\".\n\nDefinition lookup_default (E : tsl_table) (gr : global_reference)\n  : term :=\n  match (lookup_tsl_table E gr) with\n  | None => default_term\n  | Some t => t\n  end.\n\n(* Partly taken from Template.Typing *)\nFixpoint it_mkLambda_or_LetIn (t : term) (l : context) :=\n  List.fold_left\n    (fun acc d =>\n       match d.(decl_body) with\n       | None => tLambda d.(decl_name) d.(decl_type) acc\n       | Some b => tLetIn d.(decl_name) b d.(decl_type) acc\n       end) l t.\n\nFixpoint it_mkProd_or_LetIn (t : term) (l : context) :=\n  List.fold_left\n    (fun acc d =>\n       match d.(decl_body) with\n       | None => tProd d.(decl_name) d.(decl_type) acc\n       | Some b => tLetIn d.(decl_name) b d.(decl_type) acc\n       end) l t.\n\nFixpoint fold_map_internal {A B C : Type} (f : A -> B -> A * C) (a : A)\n         (cs : list C) (bs : list B) : A * (list C)\n  := match bs with\n     | [] => (a, rev cs)\n     | hd :: tl => let (a_, c_) := f a hd in fold_map_internal f a_ (c_ :: cs) tl\n     end.\n\nDefinition fold_map {A B C : Type} (f : A -> B -> A * C) (a : A)\n           (bs : list B) : A * (list C) := fold_map_internal f a [] bs.\n\nFixpoint fold_map' {A B C : Type} (f : A -> B -> A * C) (a : A)\n         (bs : list B) : A * (list C)\n  := match bs with\n     | [] => (a, [])\n     | hd :: tl => let (a_, c_) := f a hd in\n                   let (a__, cs) := fold_map' f a_ tl in\n                   (a__, c_ :: cs)\n     end.\n\nExample ex_fold_map : fold_map (fun x y => (x+y, y+1)) 0 [1;2;3] = (6,[2;3;4]).\nreflexivity.\nQed.\n\nExample ex_fold_map_fold_map' :\n  fold_map (fun x y => (x+y, y+1)) 0 [1;2;3] = fold_map' (fun x y => (x+y, y+1)) 0 [1;2;3].\nreflexivity.\nQed.", "meta": {"author": "CoqHott", "repo": "template-coq-forcing", "sha": "853b54e092cd5d80506c0f028242e6f33492dcfc", "save_path": "github-repos/coq/CoqHott-template-coq-forcing", "path": "github-repos/coq/CoqHott-template-coq-forcing/template-coq-forcing-853b54e092cd5d80506c0f028242e6f33492dcfc/forcing/TFUtils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.28547989696877696}}
{"text": "From Hammer Require Import Hammer.\n\nSet Warnings \"-notation-overridden\".\n\nRequire Export Category.Lib.Setoid.\nRequire Export Category.Lib.Tactics.\n\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Coq.NArith.NArith.\nRequire Import Coq.omega.Omega.\n\nGeneralizable All Variables.\nSet Primitive Projections.\nSet Universe Polymorphism.\nUnset Transparent Obligations.\n\nOpen Scope lazy_bool_scope.\n\nLemma K_dec_on_type A (x : A) (eq_dec : ∀ y : A, x = y \\/ x ≠ y)\n(P : x = x -> Type) :\nP eq_refl -> forall p:x = x, P p.\nProof. hammer_hook \"Equality\" \"Equality.K_dec_on_type\".\nintros.\nelim (@Eqdep_dec.eq_proofs_unicity_on A _) with x eq_refl p.\ntrivial.\nexact eq_dec.\nQed.\n\nLemma Nat_eq_dec' : ∀ (x y : nat), x = y \\/ x ≠ y.\nProof. hammer_hook \"Equality\" \"Equality.Nat_eq_dec'\". intros; destruct (Nat.eq_dec x y); auto. Qed.\n\nLemma Nat_eq_dec_refl (x : nat) :\nNat.eq_dec x x = left (@eq_refl (nat) x).\nProof. hammer_hook \"Equality\" \"Equality.Nat_eq_dec_refl\".\ndestruct (Nat.eq_dec x x); [| contradiction].\nrefine (K_dec_on_type (nat) x (Nat_eq_dec' x)\n(fun H => @left _ _ H = @left _ _ (@eq_refl (nat) x)) _ _); auto.\nQed.\n\nLemma Nat_eqb_refl (x : nat) : Nat.eqb x x = true.\nProof. hammer_hook \"Equality\" \"Equality.Nat_eqb_refl\". now apply Nat.eqb_eq. Qed.\n\nLemma Pos_eq_dec' : ∀ x y : positive, x = y \\/ x ≠ y.\nProof. hammer_hook \"Equality\" \"Equality.Pos_eq_dec'\".\nintros.\ndestruct (Pos.eq_dec x y); auto.\nQed.\n\nLemma Pos_eq_dec_refl n : Pos.eq_dec n n = left (@eq_refl positive n).\nProof. hammer_hook \"Equality\" \"Equality.Pos_eq_dec_refl\".\ndestruct (Pos.eq_dec n n).\nrefine (K_dec_on_type positive n (Pos_eq_dec' n)\n(fun x => @left _ _ x = @left _ _ (@eq_refl positive n)) _ _).\nreflexivity.\ncontradiction.\nQed.\n\nTheorem Pos_eqb_eq (p q : positive) : (p =? q)%positive = true <-> p=q.\nProof. hammer_hook \"Equality\" \"Equality.Pos_eqb_eq\".\nrevert q. induction p; destruct q; simpl; rewrite ?IHp; split; congruence.\nQed.\n\nFixpoint Pos_eqb_refl (x : positive) : Pos.eqb x x = true :=\nmatch x with\n| xI x => Pos_eqb_refl x\n| xO x => Pos_eqb_refl x\n| xH => eq_refl\nend.\n\nLemma N_eq_dec' : ∀ x y : N, x = y \\/ x ≠ y.\nProof. hammer_hook \"Equality\" \"Equality.N_eq_dec'\".\nintros.\ndestruct (N.eq_dec x y); auto.\nQed.\n\nLemma N_eq_dec_refl n : N.eq_dec n n = left (@eq_refl N n).\nProof. hammer_hook \"Equality\" \"Equality.N_eq_dec_refl\".\ndestruct (N.eq_dec n n).\nrefine (K_dec_on_type N n (N_eq_dec' n)\n(fun x => @left _ _ x = @left _ _ (@eq_refl N n)) _ _).\nreflexivity.\ncontradiction.\nQed.\n\nDefinition nth_safe {a} (xs : list a) (n : nat) (H : (n < length xs)%nat) : a.\nProof. hammer_hook \"Equality\" \"Equality.nth_safe\".\ninduction xs; simpl in *; auto.\ncontradiction (Nat.nlt_0_r n).\nDefined.\n\nDefinition nth_pos {a} (xs : list a) (n : positive) (default : a) : a.\nProof. hammer_hook \"Equality\" \"Equality.nth_pos\".\ngeneralize dependent n.\ninduction xs; intros.\nexact default.\ndestruct n using Pos.peano_rect.\nexact a0.\nexact (IHxs n).\nDefined.\n\nDefinition within_bounds {A} (x : positive) (xs : list A) : Prop :=\n(Nat.pred (Pos.to_nat x) < length xs)%nat.\n\nDefinition Pos_to_fin {n} (x : positive) :\n(Nat.pred (Pos.to_nat x) < n)%nat -> Fin.t n := Fin.of_nat_lt.\n\nDefinition nth_pos_bounded {a} (xs : list a) (n : positive)\n(H : within_bounds n xs) : a.\nProof. hammer_hook \"Equality\" \"Equality.nth_pos_bounded\".\ngeneralize dependent n.\ninduction xs; intros.\nunfold within_bounds in H; simpl in H; omega.\ndestruct n using Pos.peano_rect.\nexact a0.\nclear IHn.\napply IHxs with (n:=n).\nunfold within_bounds in *.\nsimpl in H.\nrewrite Pos2Nat.inj_succ in H.\nsimpl in H.\napply lt_S_n.\nrewrite Nat.succ_pred_pos; auto.\napply Pos2Nat.is_pos.\nDefined.\n\nLemma Nat_eqb_eq n m : Nat.eqb n m = true <-> n = m.\nProof. hammer_hook \"Equality\" \"Equality.Nat_eqb_eq\".\nrevert m.\ninduction n; destruct m; simpl; rewrite ?IHn; split; try easy.\n- now intros ->.\n- now injection 1.\nDefined.\n\nLemma Fin_eqb_eq : forall n (p q : Fin.t n), Fin.eqb p q = true <-> p = q.\nProof. hammer_hook \"Equality\" \"Equality.Fin_eqb_eq\".\napply Fin.rect2; simpl; intros.\n- split; intros ; [ reflexivity | now apply Nat_eqb_eq ].\n- now split.\n- now split.\n- split; intros.\n* f_equal.\nnow apply H.\n* apply Fin.FS_inj in H0.\nnow apply H.\nDefined.\n\nLemma Fin_eqb_eq' n (x y : Fin.t n) (H : Fin.eqb x y = true) : x = y.\nProof. hammer_hook \"Equality\" \"Equality.Fin_eqb_eq'\".\ninduction x.\nrevert H.\napply Fin.caseS with (p:=y); intros; eauto.\nsimpl in H; discriminate.\nrevert H.\napply Fin.caseS' with (p:=y); intros; eauto.\nsimpl in H; discriminate.\nsimpl in H.\nf_equal.\nnow apply IHx.\nDefined.\n\nLemma Fin_eq_dec {n} (x y : Fin.t n): {x = y} + {x <> y}.\nProof. hammer_hook \"Equality\" \"Equality.Fin_eq_dec\".\ncase_eq (Fin.eqb x y); intros.\n- left; now apply Fin_eqb_eq.\n- right. intros Heq. apply <- Fin_eqb_eq in Heq. congruence.\nDefined.\n\nLemma Fin_eq_dec' : ∀ n (x y : Fin.t n), x = y \\/ x ≠ y.\nProof. hammer_hook \"Equality\" \"Equality.Fin_eq_dec'\". intros; destruct (Fin_eq_dec x y); auto. Qed.\n\nLemma Fin_eq_dec_refl n (x : Fin.t n) :\nFin_eq_dec x x = left (@eq_refl (Fin.t n) x).\nProof. hammer_hook \"Equality\" \"Equality.Fin_eq_dec_refl\".\ndestruct (Fin_eq_dec x x).\nrefine (K_dec_on_type (Fin.t n) x (Fin_eq_dec' n x)\n(fun H => @left _ _ H = @left _ _ (@eq_refl (Fin.t n) x)) _ _).\nreflexivity.\ncontradiction.\nQed.\n\nFixpoint Fin_eqb_refl n (x : Fin.t n) : Fin.eqb x x = true :=\nmatch x with\n| @Fin.F1 m'    => Nat_eqb_refl m'\n| @Fin.FS n0 p' => Fin_eqb_refl n0 _\nend.\n\nImport EqNotations.\n\nFixpoint nth_fin {a} (xs : list a) (n : Fin.t (length xs)) : a :=\nmatch xs as xs' return length xs = length xs' -> a with\n| nil => fun H => Fin.case0 _ (rew H in n)\n| cons x xs' => fun H =>\nmatch n in Fin.t n' return length xs = n' -> a with\n| Fin.F1 => fun _ => x\n| @Fin.FS n0 x => fun H0 =>\nnth_fin\nxs' (rew (eq_add_S n0 (length xs')\n(rew [fun n => n = S (length xs')] H0 in H)) in x)\nend eq_refl\nend eq_refl.\n\nClass Equality (A : Type) := {\nEq_eq := @eq A;\nEq_eq_refl x := eq_refl;\n\nEq_eqb : A -> A -> bool;\nEq_eqb_refl x : Eq_eqb x x = true;\n\nEq_eqb_eq x y : Eq_eqb x y = true -> x = y;\n\nEq_eq_dec  (x y : A) : { x = y } + { x ≠ y };\nEq_eq_dec_refl x : Eq_eq_dec x x = left (@Eq_eq_refl x)\n}.\n\nProgram Instance Pos_Eq : Equality positive := {\nEq_eqb         := Pos.eqb;\nEq_eqb_refl    := Pos_eqb_refl;\n\nEq_eqb_eq x y  := proj1 (Pos_eqb_eq x y);\n\nEq_eq_dec      := Pos.eq_dec;\nEq_eq_dec_refl := Pos_eq_dec_refl\n}.\n\nProgram Instance Fin_Eq (n : nat) : Equality (Fin.t n) := {\nEq_eqb         := Fin.eqb;\nEq_eqb_refl    := Fin_eqb_refl n;\n\nEq_eqb_eq x y  := proj1 (Fin_eqb_eq n x y);\n\nEq_eq_dec      := Fin_eq_dec;\nEq_eq_dec_refl := Fin_eq_dec_refl n\n}.\n\n\n\nFixpoint list_beq {A : Type} (eq_A : A -> A -> bool) (X Y : list A)\n{struct X} : bool :=\nmatch X with\n| [] => match Y with\n| [] => true\n| _ :: _ => false\nend\n| x :: x0 =>\nmatch Y with\n| [] => false\n| x1 :: x2 => eq_A x x1 &&& list_beq eq_A x0 x2\nend\nend.\n\nLemma list_beq_eq {A} (R : A -> A -> bool) xs ys :\n(∀ x y, R x y = true -> x = y) ->\nlist_beq R xs ys = true -> xs = ys.\nProof. hammer_hook \"Equality\" \"Equality.list_beq_eq\".\ngeneralize dependent ys.\ninduction xs; simpl; intros.\ndestruct ys; congruence.\ndestruct ys.\ndiscriminate.\ndestruct (R a a0) eqn:Heqe.\napply H in Heqe; subst.\nerewrite IHxs; eauto.\ndiscriminate.\nQed.\n\nLemma list_beq_refl {A} (R : A -> A -> bool) xs :\n(∀ x, R x x = true) -> list_beq R xs xs = true.\nProof. hammer_hook \"Equality\" \"Equality.list_beq_refl\".\nintros.\ninduction xs; auto; simpl.\nnow rewrite H.\nQed.\n\nProgram Instance list_Eq `{Equality A} : Equality (list A) := {\nEq_eqb         := list_beq Eq_eqb;\nEq_eqb_refl x  := list_beq_refl Eq_eqb x Eq_eqb_refl;\n\nEq_eqb_eq x y  := list_beq_eq Eq_eqb x y Eq_eqb_eq;\n\nEq_eq_dec      := list_eq_dec Eq_eq_dec;\nEq_eq_dec_refl := _\n}.\nNext Obligation.\ninduction x; simpl; auto.\nunfold sumbool_rec, sumbool_rect.\nrewrite Eq_eq_dec_refl, IHx.\nreflexivity.\nQed.\n\n\nDefinition prod_eqb {A B} (A_eqb : A -> A -> bool) (B_eqb : B -> B -> bool)\n(x y : A * B) : bool :=\nA_eqb (fst x) (fst y) && B_eqb (snd x) (snd y).\n\n\nProgram Definition prod_eq_dec {A B}\n(A_eq_dec : forall x y : A, {x = y} + {x ≠ y})\n(B_eq_dec : forall x y : B, {x = y} + {x ≠ y})\n(x y : A * B) : {x = y} + {x ≠ y} :=\nmatch A_eq_dec (fst x) (fst y) with\n| in_left =>\nmatch B_eq_dec (snd x) (snd y) with\n| in_left  => in_left\n| in_right => in_right\nend\n| in_right => in_right\nend.\nNext Obligation. simpl in *; congruence. Qed.\n\nLemma prod_eq_dec' :\n∀ (A B : Type) (A_eq_dec : ∀ x y : A, x = y ∨ x ≠ y)\n(B_eq_dec : ∀ x y : B, x = y ∨ x ≠ y)\n(x y : A ∧ B), x = y \\/ x ≠ y.\nProof. hammer_hook \"Equality\" \"Equality.prod_eq_dec'\".\nintros.\ndestruct x, y; simpl.\ndestruct (A_eq_dec a a0); subst.\ndestruct (B_eq_dec b b0); subst.\nleft; reflexivity.\nright; congruence.\nright; congruence.\nQed.\n\nLemma prod_eq_dec_refl (A B : Type) n\n(A_eq_dec : ∀ x y : A, x = y ∨ x ≠ y)\n(B_eq_dec : ∀ x y : B, x = y ∨ x ≠ y) :\nprod_eq_dec A_eq_dec B_eq_dec n n = left (@eq_refl (A ∧ B) n).\nProof. hammer_hook \"Equality\" \"Equality.prod_eq_dec_refl\".\ndestruct (prod_eq_dec _ _ n n).\nrefine (K_dec_on_type (A ∧ B) n (prod_eq_dec' _ _ A_eq_dec B_eq_dec n)\n(fun x => @left _ _ x = @left _ _ (@eq_refl (A ∧ B) n)) _ _).\nreflexivity.\ncontradiction.\nQed.\n\nProgram Instance prod_Eq `{Equality A} `{Equality B} : Equality (prod A B) := {\nEq_eqb           := prod_eqb Eq_eqb Eq_eqb;\nEq_eqb_refl      := _;\n\nEq_eqb_eq x y    := _;\n\nEq_eq_dec        := prod_eq_dec Eq_eq_dec Eq_eq_dec;\nEq_eq_dec_refl x := prod_eq_dec_refl _ _ x Eq_eq_dec Eq_eq_dec\n}.\nNext Obligation.\nunfold prod_eqb; simpl.\nnow rewrite !Eq_eqb_refl.\nDefined.\nNext Obligation.\nunfold prod_eqb in H1; simpl in H1.\napply andb_true_iff in H1.\ndestruct H1.\napply Eq_eqb_eq in H1.\napply Eq_eqb_eq in H2.\nnow subst.\nDefined.\n\nLtac equalities' :=\nsimplify;\nmatch goal with\n| [ H : (?X; _) = (?X; _) |- _ ] =>\ntry (apply Eqdep_dec.inj_pair2_eq_dec in H; [|apply Eq_eq_dec])\n\n| [ H : context[Pos.eq_dec ?N ?M] |- _ ] =>\nreplace (Pos.eq_dec N M) with (Eq_eq_dec N M) in H\n| [ |- context[Pos.eq_dec ?N ?M] ] =>\nreplace (Pos.eq_dec N M) with (Eq_eq_dec N M)\n| [ H : context[(?N =? ?M)%positive] |- _ ] =>\nreplace ((N =? M)%positive) with (Eq_eqb N M) in H\n| [ |- context[(?N =? ?M)%positive] ] =>\nreplace ((N =? M)%positive) with (Eq_eqb N M)\n\n| [ H : context[@Fin_eq_dec ?N ?X ?Y] |- _ ] =>\nreplace (@Fin_eq_dec N X Y) with (Eq_eq_dec X Y) in H\n| [ |- context[Fin_eq_dec ?N ?X ?Y] ] =>\nreplace (@Fin_eq_dec N X Y) with (Eq_eq_dec X Y)\n| [ H : context[@Fin.eqb ?N ?X ?Y] |- _ ] =>\nreplace (@Fin.eqb ?N ?X ?Y) with (Eq_eqb X Y) in H\n| [ |- context[@Fin.eqb ?N ?X ?Y] ] =>\nreplace (@Fin.eqb ?N ?X ?Y) with (Eq_eqb X Y)\n\n| [ |- Eq_eqb ?X ?X = true ]     => apply Eq_eqb_refl\n| [ H : Eq_eqb _ _ = true |- _ ] => apply Eq_eqb_eq in H\n| [ |- Eq_eqb _ _ = true ]       => apply Eq_eqb_eq\n\n| [ H : context[match Eq_eq_dec ?X ?X with _ => _ end] |- _ ] =>\nrewrite (Eq_eq_dec_refl X) in H\n| [ |- context[match Eq_eq_dec ?X ?X with _ => _ end] ] =>\nrewrite (Eq_eq_dec_refl X)\n| [ H : context[match Eq_eq_dec ?X ?Y with _ => _ end] |- _ ] =>\ndestruct (Eq_eq_dec X Y); subst\n| [ |- context[match Eq_eq_dec ?X ?Y with _ => _ end] ] =>\ndestruct (Eq_eq_dec X Y); subst\n\n| [ H : list_beq _ _ _ = true |- _ ] => apply list_beq_eq in H\n| [ |- list_beq _ _ _ = true ]       => apply list_beq_eq\nend.\n\nLtac equalities :=\ntry equalities';\nrepeat (\nequalities';\nsubst; simpl; auto;\ntry discriminate;\ntry tauto;\ntry intuition idtac;\nsubst; simpl; auto).\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/category-theory/Equality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.28547989696877696}}
{"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(*                   Substitution.v                                   *)\n(*                                                                    *)\n(*                     Barry Jay                                      *)\n(*                                                                    *)\n(* adapted from Substitution.v of Project Coq  to act on Tree-terms   *)\n(**********************************************************************)\n\nRequire Import Arith Omega List.\nRequire Import IntensionalLib.SF_calculus.Test.  \nRequire Import IntensionalLib.SF_calculus.General.  \nRequire Import IntensionalLib.Tree_calculus.Tree_Terms.  \nRequire Import IntensionalLib.Tree_calculus.Tree_Tactics.  \nRequire Import IntensionalLib.Tree_calculus.Tree_reduction.  \nRequire Import IntensionalLib.Tree_calculus.Tree_Normal.  \nRequire Import IntensionalLib.Tree_calculus.Tree_Closed.  \n\n\n\n(* Lifting *)\n\nDefinition relocate (i k n : nat) :=\n  match test k i with\n   (* k<=i *) | left _ => n+i\n   (* k>i  *) | _ => i\n  end.\n\nLemma relocate_null :\nforall (n n0 : nat), relocate n n0 0 = n.\nProof. split_all. unfold relocate. case (test n0 n); intro; auto with arith. Qed.\n\nLemma relocate_lessthan : forall m n k, m<=k -> relocate k m n = (n+k). \nProof. split_all. unfold relocate. elim(test m k); split_all; try noway. Qed. \nLemma relocate_greaterthan : forall m n k, m>k -> relocate k m n = k. \nProof. split_all. unfold relocate. elim(test m k); split_all; try noway. Qed. \n\nLtac relocate_lt := \ntry (rewrite relocate_lessthan; [| omega]; relocate_lt); \ntry (rewrite relocate_greaterthan; [| omega]; relocate_lt);\ntry(rewrite relocate_null). \n\n\nLemma relocate_zero_succ :\nforall n k, relocate 0 (S n) k = 0.\nProof.  split_all. Qed.\n\nLemma relocate_succ :\nforall n n0 k, relocate (S n) (S n0) k = S(relocate n n0 k).\nProof. \nintros; unfold relocate. elim(test(S n0) (S n)); elim(test n0 n); split_all. \nnoway. \nnoway. \nQed. \n\nLemma relocate_mono : forall M N n k, relocate M n k = relocate N n k -> M=N. \nProof. \nintros M N n k. \nunfold relocate.\nelim(test n M); elim(test n N); split_all; omega. \nQed. \n\nLemma relocate_null2 :\nforall n k, relocate 0 (S n) k = 0.\nProof. split_all. Qed. \n\n\nFixpoint lift_rec (L : Tree) : nat -> nat -> Tree :=\n  fun k n => \n  match L with\n  | Ref i => Ref (relocate i k n)\n  | Op o => Op o\n  | App M N => App (lift_rec M k n) (lift_rec N k n)\n   end.\n\nDefinition lift (n : nat) (N : Tree) := lift_rec N 0 n.\n\n\n(* Lifting lemmas *)\n\n\n\nLemma lift_rec_null_term : \nforall (U : Tree)(n: nat), lift_rec U n 0 = U.\nProof. \nsimple induction U; split_all.  \nrelocate_lt; auto. \nrewrite H; auto. rewrite H0; auto. \nQed.\n\nLemma lift1 :\n forall (U : Tree) (j i k : nat),\n lift_rec (lift_rec U i j) (j + i) k = lift_rec U i (j + k).\nProof.\nsimple induction U; simpl in |- *;  split_all. \nunfold relocate. \nelim (test i n); elim (test (j+i) (j+ n)); split_all; try noway. \nassert(k + (j + n) = j + k + n) by omega. congruence. \nelim (test (j + i) n); split_all; try noway. rewrite H; auto. rewrite H0; auto. \nQed. \n\nLemma lift_lift_rec :\n forall (U : Tree) (k p n i : nat),\n i <= n ->\n lift_rec (lift_rec U i p) (p + n) k = lift_rec (lift_rec U n k) i p.\nProof.\nsimple induction U; simpl in |- *;  split_all.\n(* Ref *) \nunfold relocate.\nelim(test i n); split_all; try noway. \nelim(test n0 n); split_all; try noway. \nelim(test (p+n0) (p+n)); split_all; try noway. \nelim(test i (k+n)); split_all; try noway. \nassert(k+(p+n) = p+ (k+n)) by omega. \nrewrite H0; auto. \nelim(test (p+n0) (p+n)); split_all; try noway. \nelim(test i n); split_all; try noway. \nelim(test n0 n); split_all; try noway. \nelim(test (p+n0) n); split_all; try noway. \nelim(test i n); split_all; try noway. \n(* Ap *)\nrewrite H; split_all.  rewrite H0; split_all. \nQed. \n\n\nLemma lift_lift_term :\n forall (U : Tree) (k p n : nat),\n lift_rec (lift p U) (p+ n) k = lift p (lift_rec U n k).\nProof.\nunfold lift in |- *; intros; apply lift_lift_rec; trivial with arith.\nQed.\n\nLemma liftrecO : forall (U : Tree) (n : nat), lift_rec U n 0 = U.\nProof.\nsimple induction U; simpl in |- *; intros; split_all; relocate_lt; congruence. \nQed.\n\nLemma liftO : forall (U : Tree) , lift 0 U = U.\nProof.\nunfold lift in |- *; split_all; apply liftrecO.\nQed.\n\nLemma lift_rec_lift_rec :\n forall (U : Tree) (n p k i : nat),\n k <= i + n ->\n i <= k -> lift_rec (lift_rec U i n) k p = lift_rec U i (p + n).\n\nProof.\nsimple induction U; split_all.\n(* Ref *) \nunfold relocate. \nelim(test i n); split_all; try noway. \nelim(test k (n0 + n)); split_all; try noway. \nreplace (p+(n0+n)) with (p + n0 + n) by omega. auto. \nelim(test k n); split_all; try noway. \n(* Ap *)\nrewrite H; split_all; rewrite H0; split_all; split_all.\nQed. \n\nLemma lift_rec_lift :\n forall (U : Tree)  (n p k i : nat),\n k <= n -> lift_rec (lift  n U)  k p = lift (p + n) U.\nProof.\nunfold lift in |- *; intros; rewrite lift_rec_lift_rec; trivial with arith.\nQed.\n\nLemma lift_rec_lift2 : \nforall M n k, lift_rec (lift 1 M) (S n) k = lift 1 (lift_rec M n k).\nProof.\nsplit_all.\nunfold lift. \nreplace (S n) with (1+n) by omega.\nrewrite lift_lift_rec; auto. \nomega.\nQed.\n\nLemma lift_rec_app: forall M N n k, lift_rec (App M N) n k = App (lift_rec M n k) (lift_rec N n k). \nProof. split_all. Qed. \nLemma lift_rec_op: forall o n k, lift_rec (Op o) n k = Op o. \nProof. split_all. Qed. \nLemma lift_rec_ref: forall i n k, lift_rec (Ref i) n k = Ref (relocate i n k). \nProof. split_all. Qed. \n\nLemma lift_rec_not_ref_0 : forall M, lift_rec M 0 1 <> Ref 0.\nProof. induction M; split_all; try discriminate. case n; split_all; discriminate. Qed. \n\n\nLemma lift_rec_null : \nforall (U : Tree) (n: nat), lift_rec U n 0 = U.\nProof. simple induction U; split_all.\n rewrite relocate_null; congruence.\nrewrite H; auto. rewrite H0; auto. \nQed.\n\nLtac  lift_tac := \nunfold_op; rewrite ? lift_rec_app; rewrite ? lift_rec_op; rewrite ? lift_rec_ref; relocate_lt; \nrewrite ? lift_rec_not_ref_0. \n\n\n\nLemma lift_rec_preserves_compound : \nforall (M: Tree), compound M -> forall (n k : nat), compound(lift_rec M n k).\nProof. \nintros M c; induction c; split_all. \nQed. \nHint Resolve lift_rec_preserves_compound.\n\n\n\nLemma lift_rec_preserves_status: \nforall M n k, status (lift_rec M n k) = status M.\nProof.\nmatch goal with \n  | |- forall M, ?P  =>   cut (forall p M, p >= rank M -> P );\n      [intros H M;  eapply2 H |\n       intro p; induction p; intro M;  [ assert(rank M >0) by eapply2 rank_positive; noway |]\n      ]\n  end.\n\ninduction M; split_all.\nrewrite IHM1. (* pepm 2: omega.  *) \ngen_case H M1. gen_case H t. gen_case H t1. gen_case H o. eapply2 IHp; omega. omega.\nQed. \n\nLemma lift_rec_preserves_normal: forall M n k, normal M -> normal (lift_rec M n k).\nProof. induction M; intros. split_all. split_all. \ninversion H. apply nf_active; fold lift_rec; auto.\nreplace  (App (lift_rec M1 n k) (lift_rec M2 n k)) \nwith (lift_rec (App M1 M2) n k) by auto. \nrewrite lift_rec_preserves_status. auto. \nsimpl. eapply2 nf_compound. \nreplace  (App (lift_rec M1 n k) (lift_rec M2 n k)) \nwith (lift_rec (App M1 M2) n k) by auto. \neapply2 lift_rec_preserves_compound. \nQed. \n\n\n\nLemma lift_rec_closed: forall M n k, maxvar M = 0 -> lift_rec M n k = M. \nProof. induction M; split_all. omega. max_out. rewrite IHM1; auto;  rewrite IHM2; auto. Qed. \n\nLemma map_lift0 : forall Ms, map (lift 0) Ms = Ms. \nProof. induction Ms; split_all.   rewrite IHMs. unfold lift; rewrite lift_rec_null. auto. Qed.\n\n\nLemma lift_preserves_maxvar2:\n  forall M, forall k, maxvar (lift k M) - k = maxvar M.\nProof.\n  induction M; split_all. relocate_lt. induction k; split_all.\n  rewrite max_minus. unfold lift in *; rewrite IHM1; rewrite IHM2; auto.\nQed.\n  \nLemma lift_rec_reflects_compound : forall M n k, compound (lift_rec M n k) -> compound M. \nProof. \ninduction M; split_all; inversion H; subst; split_all. \ngen_case H1 M1; try discriminate.  invsub.\ngen_case H1 M1; try discriminate. inversion H1. \ngen_case H2 t; try discriminate. case o; auto. \nQed. \n\nLemma lift_rec_reflects_normal : forall M n k, normal (lift_rec M n k) -> normal M. \nProof. \ninduction M; split_all. inversion H; split_all. \nreplace (App (lift_rec M1 n k) (lift_rec M2 n k)) with (lift_rec (App M1 M2) n k) in H4 by auto. \nrewrite lift_rec_preserves_status in *. eapply2 nf_active. \nreplace (App (lift_rec M1 n k) (lift_rec M2 n k)) with (lift_rec (App M1 M2) n k) in H4 by auto. \neapply2 nf_compound. eapply2 lift_rec_reflects_compound.\nQed. \n\n(* Substitution *)\n\n\nDefinition insert_Ref (N : Tree) (i k : nat) :=\n  match compare k i with\n  \n   (* k<i *) | inleft (left _) => Ref (pred i)\n   (* k=i *) | inleft _ => lift k N\n   (* k>i *) | _ => Ref i\n  end.\n\nFixpoint subst_rec (L : Tree) : Tree -> nat -> Tree :=\n  fun (N : Tree) (k : nat) =>\n  match L with\n  | Ref i => insert_Ref N i k\n  | Op o => Op o\n  | App M M' => App (subst_rec M N k) (subst_rec M' N k)\n  end.\n\nLemma subst_rec_op: \nforall o N k, subst_rec (Op o) N k = Op o.\nProof.  split_all. Qed. \n\nLemma subst_rec_app: \nforall M1 M2 N k, subst_rec (App M1 M2) N k = App (subst_rec M1 N k) (subst_rec M2 N k).\nProof.  split_all. Qed. \n\nLemma subst_rec_ref: forall i N k,  subst_rec (Ref i) N k = insert_Ref N i k.\nProof.  split_all. Qed. \n                                                      \n\nDefinition subst (M N : Tree) := subst_rec M N 0.\n\n\n(* The three cases of substitution of U for (Ref n) *)\n\nLemma subst_eq :\n forall (M U : Tree) (n : nat), subst_rec (Ref n) U n = lift n U. \nProof.\nsimpl in |- *; unfold insert_Ref in |- *; split_all. \nelim (compare n n); intro P; try noway. \nelim P; intro Q; simpl in |- *; trivial with arith; try noway.\nQed.\n\nLemma subst_gt :\n forall (M U : Tree) (n p : nat),\n n > p -> subst_rec (Ref n) U p = Ref (pred n).\nProof.\nsimpl in |- *; unfold insert_Ref in |- *.\nintros; elim (compare p n); intro P.\nelim P; intro Q; trivial with arith.\nabsurd (n > p); trivial with arith; rewrite Q; trivial with arith.\nabsurd (n > p); auto with arith.\nQed. \n\nLemma subst_lt :\n forall (M U : Tree) (n p : nat), p > n -> subst_rec (Ref n) U p = Ref n.\nProof.\nsimpl in |- *; unfold insert_Ref in |- *.\nintros; elim (compare p n); intro P; trivial with arith.\nabsurd (p > n); trivial with arith; elim P; intro Q; auto with arith.\nrewrite Q; trivial with arith.\nQed.\n\n(* Substitution lemma *)\n\nLemma lift_rec_subst_rec :\n forall (V U : Tree) (k p n : nat),\n lift_rec (subst_rec V U p) (p + n) k =\n subst_rec (lift_rec V (S (p + n)) k) (lift_rec U n k) p.\nProof.\nsimple induction V; split_all. \n(* 1 Ref *)\nunfold insert_Ref, relocate in |- *.\nelim (test (S(p + n0)) n); elim (compare p n); split_all.\nelim a; elim(compare p (k+n)); split_all. \nunfold relocate. \nelim(test (p+n0) (pred n)); elim a1; split_all; try noway. \nreplace (k + pred n) with (pred (k + n)) by omega; auto.\nnoway. \nnoway. \nnoway. \nnoway. \nelim a; split_all.\nunfold relocate. elim(test(p+n0) (pred n)); split_all. \nnoway.\nunfold lift.\nrewrite lift_lift_rec; auto; omega. \nunfold relocate. \nelim(test (p+n0) n); split_all. \nnoway.\nrewrite H; auto; rewrite H0; auto. \nQed. \n\n\nLemma lift_subst :\n forall (U V : Tree) (k n : nat),\n lift_rec (subst U V) n k =\n subst (lift_rec U (S n) k) (lift_rec V n k).\nProof.\nunfold subst in |- *; intros.\nreplace n with (0 + n).\nrewrite lift_rec_subst_rec; trivial with arith.\nauto. \nQed.\n\nLemma subst_rec_lift_rec1 :\n forall (U V : Tree) (n p k : nat),\n k <= n ->\n subst_rec (lift_rec U k p) V (p + n) =\n lift_rec (subst_rec U V n) k p.\nProof.\nsimple induction U; intros; simpl in |- *; split_all.\n(* Ref *) \nunfold insert_Ref, relocate. \nelim(test k n); split_all. \nelim(compare n0 n); split_all; try noway. \nelim a0; split_all; try noway. \nelim(compare (p+n0) (p+n)); split_all. \nelim a2; split_all; try noway. \nunfold relocate. \nelim(test k (pred n)); split_all; try noway. \nassert(pred (p+n) = p + pred n) by omega. auto. \nnoway. \nelim(compare (p+n0) (p+n)); split_all. \nelim a1; split_all; try noway. \nunfold lift. rewrite lift_rec_lift_rec; split_all; try omega.  \nunfold lift. rewrite lift_rec_lift_rec; split_all; try omega.  \nelim(compare (p+n0) (p+n)); split_all. \nelim a0; split_all; try noway. \nunfold relocate. \nelim(test k n); split_all; try noway. \nelim(compare (p+n0) n); split_all; try noway. \nelim a; split_all; try noway. \nelim(compare n0 n); split_all; try noway. \nelim a; split_all; try noway. \nunfold relocate. \nelim(test k n); split_all; try noway. \n(* 1 *) \nrewrite H; split_all.  rewrite H0; split_all. \nQed. \n\nLemma subst_rec_lift1 :\n forall (U V : Tree) (n p : nat),\n subst_rec (lift p U) V (p + n) = lift p (subst_rec U V n).\nProof.\nunfold lift in |- *; intros; rewrite subst_rec_lift_rec1;\n trivial with arith.\nQed.\n\n\nLemma subst_rec_lift_rec :\n forall (U V : Tree) (p q n : nat),\n q <= p + n ->\n n <= q -> subst_rec (lift_rec U n (S p)) V q = lift_rec U n p.\nProof.\nsimple induction U; intros; simpl in |- *; split_all. \nunfold relocate. elim(test n0 n); split_all. \nunfold insert_Ref. \nelim(compare q (S(p+n))); split_all; try noway. \nelim a0; split_all; try noway. \nunfold insert_Ref. \nelim(compare q n); split_all; try noway. \nelim a; split_all; try noway. \n\n(* 1 *) \nrewrite H; split_all. \nrewrite H0; auto.\nQed.\n\n(* subst_rec_subst_rec *)\n\nLemma subst_rec_subst_rec :\n forall (V U W : Tree) (n p : nat),\n subst_rec (subst_rec V U p) W (p + n) =\n subst_rec (subst_rec V W (S (p + n))) (subst_rec U W n) p.\nProof.\nsimple induction V;  split_all.\n\nunfold insert_Ref in |- *.\nelim (compare p n); split_all. \nelim a; split_all. \nelim (compare (S (p + n0)) n); split_all. \nelim a1; split_all; try noway. \nunfold insert_Ref.\nelim (compare (p+n0) (pred n)); split_all; try noway. \nelim a3; split_all; try noway.\nelim (compare p (pred n)); split_all; try noway. \nelim a5; split_all; try noway.\nunfold lift; split_all. \nunfold insert_Ref. \nelim (compare (p+n0) (pred n)); split_all; try noway. \nelim a2; split_all; try noway.\nsubst. unfold lift. \nrewrite subst_rec_lift_rec; split_all; try omega. \nunfold insert_Ref. \nelim(compare (p+n0) (pred n)); split_all; try noway. \nelim a1; split_all; try noway. \nelim(compare p n); split_all; try noway. \nelim a1; split_all; try noway. \nelim (compare (S (p + n0)) n); split_all; try noway. \nelim a0; split_all; try noway.\nunfold insert_Ref. \nelim(compare p n); split_all; try noway. \nelim a0; split_all; try noway. \nunfold lift. \nsubst. \nrewrite subst_rec_lift_rec1; split_all.  omega. \n\nunfold insert_Ref. \nelim(compare (p+n0) n); split_all; try noway. \nelim a; split_all; try noway.\nelim(compare (S(p+n0)) n); split_all; try noway. \nelim a; split_all; try noway. \nunfold insert_Ref. \nelim(compare p n); split_all; try noway. \nelim a; split_all; try noway. \nrewrite H; auto. rewrite H0; auto. \nQed.\n\n\nLemma subst_rec_subst_0 :\n forall (U V W : Tree) (n : nat),\n subst_rec (subst_rec V U 0) W n =\n subst_rec (subst_rec V W (S n)) (subst_rec U W n) 0.\nProof.\nintros; pattern n at 1 3 in |- *.\nreplace n with (0 + n) by trivial with arith.\nrewrite (subst_rec_subst_rec V U W n 0); trivial with arith.\nQed.\n\n(**************************)\n(* The Substitution Lemma *)\n(**************************)\n\nLemma substitution :\n forall (U V W : Tree) (n : nat),\n subst_rec (subst U V) W n =\n subst (subst_rec U W (S n)) (subst_rec V W n).\nProof.\nunfold subst in |- *; intros; apply subst_rec_subst_0; trivial with arith.\nQed.\n\n(* to show (\\ t)0 -> t  *) \n\n\nLemma subst_lift_null :\nforall (W V : Tree)(n : nat), subst_rec (lift_rec W n 1) V n = W.\nProof.\nsimple induction W; split_all. \nunfold insert_Ref. \nunfold relocate. \nelim(test n0 n); split_all. \nelim(compare n0 (S n)); split_all.\nelim a0; split_all; noway. \nnoway. \nelim(compare n0 n); split_all.\nelim a; split_all. noway. \nnoway.\nrewrite H; auto; rewrite H0; auto. \nQed. \n\n\n(* more  Properties *) \n\n\n\nLemma subst_rec_lift2 : \nforall M N n , subst_rec (lift 1 M) N (S n)  = lift 1 (subst_rec M N n).\nProof.\nsplit_all.\nunfold lift. \nreplace (S n) with (1+n) by omega.\nrewrite subst_rec_lift_rec1; auto. \nomega.\nQed.\n\n\n\nLemma insert_Ref_lt : forall M n k, n< k -> insert_Ref M n k = Ref n.\nProof.\ninduction M; unfold insert_Ref; split_all. \nelim (compare k n0); split_all. \nelim a; split_all; try noway. \nelim (compare k n); split_all. \nelim a; split_all; try noway. \nelim (compare k n); split_all. \nelim a; split_all; try noway. \nQed. \n\nLemma insert_Ref_eq : forall M n k, n= k -> insert_Ref M n k = lift k M.\nProof.\ninduction M; unfold insert_Ref; split_all. \nelim (compare k n0); split_all. \nelim a; split_all; try noway. \nunfold lift; unfold lift_rec. unfold relocate. elim(test 0 n); split_all; try noway. \nelim (compare k n); split_all. \nelim a; split_all; try noway. \nunfold lift; unfold lift_rec. unfold relocate. elim(test 0 n); split_all; try noway. \nelim (compare k n); split_all. \nelim a; split_all; try noway. \nnoway.\nQed. \n\n\nLemma insert_Ref_gt : forall M n k, n> k -> insert_Ref M n k = Ref (pred n).\nProof.\ninduction M; unfold insert_Ref; split_all. \nelim (compare k n0); split_all. \nelim a; split_all; try noway. \nnoway. \nelim (compare k n); split_all. \nelim a; split_all; try noway. \nnoway. \nelim (compare k n); split_all. \nelim a; split_all; try noway. \nnoway.\nQed. \n\nLtac insert_Ref_out := \ntry (rewrite insert_Ref_lt; [|unfold relocate; split_all; omega]; insert_Ref_out); \ntry (rewrite insert_Ref_eq; [|unfold relocate; split_all; omega]; insert_Ref_out); \ntry (rewrite insert_Ref_gt; [|unfold relocate; split_all; omega]; insert_Ref_out). \n\n\nLemma fold_subst :  forall M1 M2 N, App (subst_rec M1 N 0) M2 = subst (App M1 (lift 1 M2)) N.\nProof.\n  unfold subst, lift, subst_rec; split_all; fold subst_rec.\n  rewrite subst_rec_lift_rec; try omega. rewrite lift_rec_null; auto.  \nQed.\n\n\n\nLtac  subst_tac := \nunfold_op; unfold subst; \nrewrite ? subst_rec_app; rewrite ? subst_rec_op; rewrite ? subst_rec_ref; \nrewrite ? subst_rec_lift_rec; try omega; rewrite ? lift_rec_null; \nunfold subst_rec; fold subst_rec; insert_Ref_out; unfold pred.  \n\n\n\nDefinition subst_preserves_l (red: termred) := \nforall (M M' N : Tree), red M M' -> red  (subst M N) (subst M' N).\n\nDefinition subst_preserves_r (red: termred) := \nforall (M N N' : Tree), red N N' -> red  (subst M N) (subst M N').\n\nDefinition subst_preserves (red: termred) := \nforall (M M' : Tree), red M M' -> forall N N', red N N' -> \nred  (subst M N) (subst M' N').\n\nLemma subst_preserves_l_multi_step : \nforall (red: termred), subst_preserves_l red -> subst_preserves_l (multi_step red). \nProof. unfold subst_preserves_l. \n induction 2; split_all.  \napply succ_red with (subst N0 N); auto.\nQed.\n\nLemma subst_preserves_r_multi_step : \nforall (red: termred), subst_preserves_r red -> subst_preserves_r (multi_step red). \nProof. unfold subst_preserves_r. \n induction 2; split_all.  \napply succ_red with (subst M N); auto.\nQed. \n\nLemma subst_preserves_multi_step : \nforall (red: termred), subst_preserves_l red -> subst_preserves_r red -> subst_preserves (multi_step red). \nProof. \nunfold subst_preserves. split_all.\nassert(transitive (multi_step red)) by eapply2 transitive_red. \nunfold transitive in *.\napply X with  (subst M' N); auto. \neapply2 subst_preserves_l_multi_step.\neapply2 subst_preserves_r_multi_step.\nQed.\n\n\nLemma subst_preserves_compound: \nforall (M: Tree), compound M -> forall N, compound(subst M N).\nProof. intros M c; induction c; unfold subst; split_all. Qed. \nHint Resolve subst_preserves_compound.\n\nLemma  subst_rec_preserves_components_l : forall (M : Tree) n k, compound M -> \n  subst_rec(left_component M) n k = left_component(subst_rec M n k).\nProof. induction M; split_all; inv1 compound. Qed. \n\n\nLemma  subst_rec_preserves_components_r : \nforall (M : Tree),  compound M -> forall n k,   \nsubst_rec(right_component M) n k = right_component(subst_rec M n k).\nProof. induction M; split_all; inversion H; subst; split_all. Qed. \nLemma subst_rec_preserves_compounds: \nforall M N k, compound M -> compound (subst_rec M N k). \nProof. intros; inv1 compound. Qed. \n\nLemma subst_rec_preserves_left_component: \nforall M N k, compound M -> \n              subst_rec (left_component M) N k = left_component (subst_rec M N k) . \nProof. intros; inv1 compound. Qed. \n\nLemma subst_rec_preserves_right_component: \nforall M N k, compound M -> \n              subst_rec (right_component M) N k = right_component (subst_rec M N k) . \nProof. intros; inv1 compound. Qed. \n\nLemma subst_preserves_sf_red1 : subst_preserves sf_red1. \nProof. \nred. \nintros M M' R; induction R; unfold subst; split_all. \n(* 5 *) \nunfold insert_Ref. elim(compare 0 i); split_all. elim a; split_all. \nunfold lift. repeat rewrite lift_rec_null_term; auto. \n(* 4 *) \neapply2 app_sf_red. \n(* 3 *) \neapply2 s_red. \n(* 2 *) \neapply2 k_red. \n(* 1 *) \neapply2 f_red. \nQed. \n\nLemma subst_preserves_sf_red : subst_preserves sf_red. \nProof. eapply2 subst_preserves_multi_step. red; split_all. \neapply2 subst_preserves_sf_red1. red; split_all. \neapply2 subst_preserves_sf_red1. \nQed. \n\nLemma subst_rec_closed: forall M N k, maxvar M <= k -> subst_rec M N k = M. \nProof. \ninduction M; split_all. \nunfold insert_Ref. elim(compare k n); split_all. elim a; split_all. noway. noway. \nassert (max (maxvar M1) (maxvar M2) >= maxvar M1) by eapply2 max_is_max. \nassert (max (maxvar M1) (maxvar M2) >= maxvar M2) by eapply2 max_is_max. \nrewrite IHM1; try omega;  rewrite IHM2; try omega. auto. \nQed. \n\n\nLemma subst_decreases_maxvar : \nforall M N,  max (pred (maxvar M)) (maxvar N) >= maxvar(subst M N).\nProof. \nunfold subst; induction M; split_all. \nunfold insert_Ref. \ncase n; split_all. unfold lift. rewrite lift_rec_null_term. auto.\ncase (maxvar N); split_all. \nassert(max n0 n1  >= n0) by eapply2 max_is_max. \nomega. \nomega. \n(* 1 *) \nrewrite max_pred.\nassert(max (max (pred (maxvar M1)) (pred (maxvar M2))) (maxvar N) >=\nmax (pred (maxvar M1)) (maxvar N)).\neapply2 max_monotonic. eapply2 max_is_max. \nassert(max (max (pred (maxvar M1)) (pred (maxvar M2))) (maxvar N) >=\nmax (pred (maxvar M2)) (maxvar N)).\neapply2 max_monotonic. eapply2 max_is_max. \nassert(max (max (pred (maxvar M1)) (pred (maxvar M2))) (maxvar N) >=\nmax(max (pred (maxvar M1)) (maxvar N)) (max (pred (maxvar M2)) (maxvar N))).\neapply2 max_max2. \nassert(max (max (pred (maxvar M1)) (maxvar N))\n         (max (pred (maxvar M2)) (maxvar N))>= \nmax (maxvar (subst_rec M1 N 0)) (maxvar (subst_rec M2 N 0))).\neapply2 max_monotonic. \nomega. \nQed. \n\n\n\nLemma subst_closed : forall M, maxvar M = 0 -> forall N, subst M N = M.\nProof.\ninduction M; split_all; subst. omega. \nmax_out. unfold subst in *; simpl. rewrite IHM1; try omega; rewrite IHM2; try omega; split_all. \nQed. \n\n\nLtac closed_tac M := repeat (rewrite (subst_rec_closed M); [| auto]); \n                     repeat (rewrite (lift_rec_closed M); [| auto]).\n\n\n\nLemma fold_subst_list:\n  forall sigma M N,  App (fold_left subst sigma M) N =\n                     fold_left subst sigma (App M (lift (length sigma) N)).\nProof.\n  induction sigma; split_all.\n  (* 2 *)\n  unfold lift; rewrite lift_rec_null. auto. \n  (* 1 *) \n  rewrite IHsigma. unfold subst. simpl. unfold lift. rewrite subst_rec_lift_rec; try omega. auto.\nQed.\n\n\nLemma list_subst_preserves_op:\n  forall sigma o, fold_left subst sigma (Op o) = Op o. \n  Proof. induction sigma; split_all. unfold subst in *. split_all. Qed. \n\nLemma list_subst_preserves_app:\n  forall sigma M N, fold_left subst sigma (App M N) =\n                    App (fold_left subst sigma M) (fold_left subst sigma N).\n  Proof. induction sigma; split_all. unfold subst in *. split_all. Qed. \n\nLemma list_subst_preserves_sf_red:\n  forall sigma M N, sf_red M N -> sf_red (fold_left subst sigma M) (fold_left subst sigma N).\nProof.  induction sigma; split_all. eapply2 IHsigma. eapply2 subst_preserves_sf_red. Qed. \n\n\n\nLemma list_subst_lift: forall sigma M, fold_left subst sigma (lift (length sigma) M) = M.\nProof.\n  induction sigma; split_all. unfold lift; rewrite lift_rec_null. auto. \nunfold lift, subst. rewrite subst_rec_lift_rec; try omega. unfold lift in *. rewrite IHsigma. auto. \nQed.\n\n\n\nLemma lift_rec_preserves_variables: forall M n k, maxvar M >0 -> maxvar (lift_rec M n k) > 0.\nProof. \ninduction M; split_all. \nomega. \nassert((maxvar M1 > 0) \\/ (maxvar M2 >0)).\ngen_case H (maxvar M1). left; omega. \ninversion H0; subst. \nassert(Nat.max (maxvar (lift_rec M1 n k)) (maxvar (lift_rec M2 n k))  >= maxvar (lift_rec M1 n k)) by eapply2 max_is_max. \nassert(maxvar(lift_rec M1 n k) >0) by eapply2 IHM1. omega. \nassert(Nat.max (maxvar (lift_rec M1 n k)) (maxvar (lift_rec M2 n k))  >= maxvar (lift_rec M2 n k)) by eapply2 max_is_max. \nassert(maxvar(lift_rec M2 n k) >0) by eapply2 IHM2. omega.\nQed. \n\n", "meta": {"author": "Barry-Jay", "repo": "Intensional-computation", "sha": "de09d3e646c1ea50127c5033b46576d8b4773259", "save_path": "github-repos/coq/Barry-Jay-Intensional-computation", "path": "github-repos/coq/Barry-Jay-Intensional-computation/Intensional-computation-de09d3e646c1ea50127c5033b46576d8b4773259/Tree_calculus/Substitution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.28547989696877696}}
{"text": "Set Implicit Arguments.\n\nRequire Import Platform.Cito.Syntax.\nRequire Import Platform.Cito.SyntaxExpr.\nRequire Import Platform.Cito.GeneralTactics.\nRequire Import Platform.Cito.Notations3.\nRequire Import Platform.Cito.SemanticsExpr.\nRequire Import Platform.Cito.GoodOptimizer.\n\nRequire Import Bedrock.StringSet.\nModule Import SS := StringSet.\nRequire Import Platform.Cito.StringSetFacts.\nModule SSF := StringSetFacts.\nRequire Import Platform.Cito.StringSetTactics.\n\nRequire Import Platform.Cito.StringMap.\nImport StringMap.\nRequire Import 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 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 : context [ { _ | _ } ] |- _ => 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 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 Platform.Cito.ADT.\n\nModule Make (Import E : ADT).\n\n  Module Import GoodOptimizerMake := GoodOptimizer.Make E.\n  Require Import 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 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 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 Platform.Cito.MaxFacts.\n\n    Hint Resolve both_le Le.le_n_S.\n\n    Require Import 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 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 Platform.Cito.GetLocalVars.\n    Require Import 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 Platform.Cito.CompileStmtSpec.\n    Require Import Platform.Cito.SetoidListFacts.\n    Require Import Platform.Cito.GeneralTactics2.\n\n    Require Import 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.", "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/optimizers/ConstFolding.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.28546860554653974}}
{"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 Wfsimpl Maps Errors Integers.\nRequire Import AST Linking.\nRequire Import Op Registers 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 ctx.(dstk) op.\n\nDefinition saddr (ctx: context) (addr: addressing) :=\n  shift_stack_addressing ctx.(dstk) addr.\n\nFixpoint sbuiltinarg (ctx: context) (a: builtin_arg reg) : builtin_arg reg :=\n  match a with\n  | BA x => BA (sreg ctx x)\n  | BA_loadstack chunk ofs => BA_loadstack chunk (Ptrofs.add ofs (Ptrofs.repr ctx.(dstk)))\n  | BA_addrstack ofs => BA_addrstack (Ptrofs.add ofs (Ptrofs.repr ctx.(dstk)))\n  | BA_splitlong hi lo => BA_splitlong (sbuiltinarg ctx hi) (sbuiltinarg ctx lo)\n  | _ => a\n  end.\n\nDefinition sbuiltinres (ctx: context) (a: builtin_res reg) : builtin_res reg :=\n  match a with\n  | BR x => BR (sreg ctx x)\n  | _    => BR_none\n  end.\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 (map (sbuiltinarg ctx) args) (sbuiltinres 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 [Ptrofs.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) Ptrofs.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": "CertiKOS", "repo": "SingleStackCompCert", "sha": "04eb987a8cc0f428365edaa4dffb2237d02d9500", "save_path": "github-repos/coq/CertiKOS-SingleStackCompCert", "path": "github-repos/coq/CertiKOS-SingleStackCompCert/SingleStackCompCert-04eb987a8cc0f428365edaa4dffb2237d02d9500/backend/Inlining.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2854685988073392}}
{"text": "Inductive Vec (A:Set) : forall n1 n2:nat, Set :=\nnil : Vec A 0 0.\n\nCheck Vec.\n(*\nVec\n     : Set -> nat -> nat -> Set\n     \nWhen we have cons, we will obviously need A_R.\nWe want to get rid of n1 and n2?\nWhy is that justified?\nIn the type of Vec, there is absolutely no difference between parameters and indices --\nwe can write another Vec of the same type where all of them are params or all\nof them are indices.\nPerhaps the principle is the difference between Sort and Type in the domain of Pi Type.\nIf so, we will not want to erase the indices_R of the following:\n\nλ x.x : Type -> Type\nthe translation  is λ x1 x2 xr, xr. the input xr is crucial.\n\nAnother example below, which I dont understand.\n*)\n\nInductive Monad  : Type -> Type :=\nret : forall T, Monad T.\n\n(*\nIf we cannot erase the index here, we will be forced to keep the equalities\nand implement the hard things anyway. So there is no advantage of trying\nto enforce irrelevance over small type domains in function types, because\nthat seems ugly to implement, as discussed in this file\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/indIndicesEqCannotBeRemoved.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.28546859880733916}}
{"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 uniq_tac.\nImport MachineInt.\nRequire Import mips_seplog mips_contrib mips_tactics mapstos.\nRequire Import multi_lt_prg.\n\nLocal Open Scope machine_int_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\nSection multi_lt.\n\nVariables k a b i flag ret ret2 a0 a1 : reg.\n\nLemma multi_lt_triple : uniq(k, a, b, i, flag, ret, ret2, a0, a1, r0) ->\n  forall nk A B va vb, size A = nk -> size B = nk ->\n  {{ fun s h => u2Z [ k ]_s = Z_of_nat nk /\\ [ a ]_s = va /\\ [ b ]_s = vb /\\\n     (var_e a |--> A ** var_e b |--> B) s h }}\n  multi_lt k a b i flag ret ret2 a0 a1\n  {{ fun s h => u2Z [ k ]_s = Z_of_nat nk /\\ [ a ]_s = va /\\ [ b ]_s = vb /\\\n    (((\\S_{ nk } A < \\S_{ nk } B /\\ [ret]_s = one32 /\\ [ret2]_s = zero32) \\/\n      (\\S_{ nk } A > \\S_{ nk } B /\\ [ret]_s = zero32 /\\ [ret2]_s = one32) \\/\n      (\\S_{ nk } A = \\S_{ nk } B /\\ [ret]_s = zero32 /\\ [ret2]_s = zero32)) /\\\n    (var_e a |--> A ** var_e b |--> B) s h) }}.\nProof.\nmove=> Hset nk A B va vb HlenA HlenB.\nrewrite /multi_lt.\n\n(** addiu i k zero16 ; *)\n\napply hoare_addiu with (fun s h => u2Z [k]_s = Z_of_nat nk /\\ [a]_s = va /\\\n  [b]_s = vb /\\ (var_e a |--> A ** var_e b |--> B) s h /\\ [i]_s = [k]_s).\n\nmove => s h [r_k [r_a [r_b Hmem]]].\nrewrite /wp_addiu; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nby rewrite sext_0 addi0.\n\n(** addiu flag r0 one16 ; *)\n\napply hoare_addiu with (fun s h => u2Z [k]_s = Z_of_nat nk /\\ [a]_s = va /\\\n  [b]_s = vb /\\ (var_e a |--> A ** var_e b |--> B) s h /\\\n  [i]_s = [k]_s /\\ [flag]_s = one32).\n\nmove=> s h [r_k [r_a [r_b [Hmem r_i]]]].\nrewrite /wp_addiu; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nby rewrite add0i sext_Z2u.\n\n(** ifte (beq i r0) *)\n\napply while.hoare_ifte.\n\n(** addiu ret r0 zero16 *)\n\napply hoare_addiu with (fun s h => u2Z [k]_s = Z_of_nat nk /\\ [a]_s = va /\\\n  [b]_s = vb /\\ (var_e a |--> A ** var_e b |--> B) s h /\\\n  [i]_s = [k]_s /\\ [flag]_s = one32 /\\ [i]_s = zero32 /\\ [ret]_s = zero32).\n\nrewrite /wp_addiu => s h [[r_k [r_a [r_b [Hmem [r_i r_flag]]]]] r_i'].\nrepeat Reg_upd.\nhave {}r_i' : [i]_s = zero32.\n  move/eqP : r_i' => /= /u2Z_inj ->.\n  by rewrite store.get_r0.\nrepeat (split; trivial).\nby Assert_upd.\nby rewrite sext_Z2u // addi0.\n\napply hoare_addiu'.\nmove => s h [r_k [r_a [r_b [Hmem [r_i [r_flag [r_i' r_ret]]]]]]].\nrewrite /wp_addiu; repeat Reg_upd; repeat (split; trivial).\n- right; right.\n  rewrite -r_i r_i' Z2uK // in r_k.\n  destruct nk; last by [].\n  by rewrite sext_Z2u // addi0.\n- by Assert_upd.\n\n(** while (bne flag r0) ( *)\n\napply hoare_prop_m.hoare_while_invariant with (fun s h => u2Z [k]_s = Z_of_nat nk /\\ [a]_s = va /\\\n  [b]_s = vb /\\ (var_e a |--> A ** var_e b |--> B) s h /\\\n  exists ni, u2Z [i]_s = Z_of_nat ni /\\\n    (ni <= nk)%nat /\\\n    (([flag]_s <> zero32 /\\ [i]_s <> zero32 /\\\n      \\S_{ nk - ni } (drop ni A) = \\S_{ nk - ni } (drop ni B)) \\/\n     [flag]_s = zero32 /\\\n     (([ret]_s = one32 /\\ [ret2]_s = zero32 /\\\n       \\S_{ nk - ni } (drop ni A) < \\S_{ nk - ni } (drop ni B)) \\/\n      ([ret]_s = zero32 /\\ [ret2]_s = one32 /\\\n        \\S_{ nk - ni } (drop ni A) > \\S_{ nk - ni } (drop ni B)) \\/\n      ([ret]_s = zero32 /\\ [i]_s = zero32 /\\ [ret2]_s = zero32 /\\\n       \\S_{ nk - ni } (drop ni A) = \\S_{ nk - ni } (drop ni B))))).\n\nmove=> s h [[r_k [r_a [r_b [Hmem [r_i r_flag]]]]] r_i'].\nrewrite /= store.get_r0 Z2uK // in r_i'; move/eqP in r_i'.\nrepeat (split; trivial).\nexists nk; split; first by rewrite r_i r_k.\nsplit => //.\nleft; split.\n- rewrite r_flag; exact: Z2u_dis.\n- split.\n  + contradict r_i'; by rewrite r_i' Z2uK.\n  + by rewrite subnn.\n\nmove=> s h [ [r_k [r_a [r_b [Hmem [ni [r_i [Hnink [\n  [r_flag [r_ret2 Hsum]] |\n  [ r_flag [ [r_ret [r_ret2 Hsum] ] |\n  [ [r_ret [r_ret2 Hsum]] |\n  [gprret [r_i' [r_ret2 Hsum]]]]]]]]]]]]]] Hneq]; rewrite /= in Hneq.\n- have {}Hneq : u2Z [flag]_s = u2Z zero32.\n    move/negPn/eqP : Hneq.\n    by rewrite store.get_r0.\n  apply u2Z_inj in Hneq; contradiction.\n- repeat (split; trivial).\n  left; split; last by [].\n  by eapply lSum_skipn; eauto.\n- repeat (split; trivial).\n  right; left; split; last by [].\n  apply Z.lt_gt.\n  apply Z.gt_lt in Hsum.\n  by eapply lSum_skipn; eauto.\n- repeat (split; trivial).\n  right; right; split; last by [].\n  have ni_O : ni = O .\n    symmetry in r_i; move: r_i.\n    rewrite r_i' /zero32 Z2uK //; by move/Z_of_nat_0.\n  by rewrite ni_O subn0 !drop0 in Hsum.\n\n(**  addiu i i mone16 ; *)\n\napply hoare_addiu with (fun s h => u2Z [k]_s = Z_of_nat nk /\\ [a]_s = va /\\\n  [b]_s = vb /\\ (var_e a |--> A ** var_e b |--> B) s h /\\\n  exists ni, u2Z [i]_s = Z_of_nat ni /\\ (ni < nk)%nat /\\\n    ([flag]_s <> zero32 /\\\n      \\S_{ nk - S ni } (drop (S ni) A) = \\S_{ nk - S ni } (drop (S ni) B))).\n\nmove=> s h [ [r_k [ r_a [r_b [Hmem [ni [r_i [Hnink [\n  [r_flag [r_i' Hsum] ] |\n  [ r_flag [ [r_ret Hsum] |\n  [ [r_ret Hsum] |\n  [r_ret [r_i' Hsum]]]]]]]]]]]]] Hneq]; rewrite /= in Hneq.\n- have X : (1 <= ni)%nat.\n    apply/ltP/not_ge; contradict r_i'.\n    apply u2Z_inj; rewrite r_i Z2uK //.\n    apply le_n_0_eq in r_i'; by subst ni.\n  rewrite /wp_addiu; repeat Reg_upd; repeat (split; trivial).\n  + by Assert_upd.\n  + exists (ni - 1)%nat; repeat (split; trivial).\n    * rewrite sext_Z2s // u2Z_add_Z2s //.\n      rewrite r_i inj_minus1 //; exact/leP.\n      rewrite r_i.\n      apply (@leZ_trans (1 + -1)); first by [].\n      apply leZ_add2r.\n      rewrite (_ : 1 = Z_of_nat 1) //; exact/inj_le/leP.\n    * destruct ni.\n      by move/leP in X; apply le_Sn_0 in X.\n      by rewrite /= subn1.\n    * by rewrite -subSn //= subn1.\n- move/eqP: Hneq; by rewrite r_flag store.get_r0.\n- move/eqP: Hneq; by rewrite r_flag store.get_r0.\n- move/eqP: Hneq; by rewrite r_flag store.get_r0.\n\n(**  lwxs a0 i a ; *)\n\napply hoare_lwxs_back_alt'' with (fun s h => u2Z [k]_s = Z_of_nat nk /\\\n  [a]_s = va /\\ [b]_s = vb /\\ (var_e a |--> A ** var_e b |--> B) s h /\\\n  exists ni, u2Z [i]_s = Z_of_nat ni /\\ (ni < nk)%nat /\\\n    ([flag]_s <> zero32 /\\\n      \\S_{ nk - S ni } (drop (S ni) A) = \\S_{ nk - S ni } (drop (S ni) B)) /\\\n    [a0]_s = A `32_ ni).\n\nmove=> s h [r_k [r_a [r_b [Hmem [ni [r_i [ni_nk [r_flag Hsum]]]]]]]].\nexists (A `32_ ni); split.\n- Decompose_32 A ni A1 A2 HlenA1 HA'; last by rewrite HlenA.\n  rewrite HA' (decompose_equiv _ _ _ _ _ HlenA1) !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_i inj_mult mulZC.\n- rewrite /update_store_lwxs; repeat Reg_upd; repeat (split; trivial).\n  by Assert_upd.\n  by exists ni.\n\n(**  lwxs a1 i b ; *)\n\napply hoare_lwxs_back_alt'' with (fun s h => u2Z [k]_s = Z_of_nat nk /\\\n  [a]_s = va /\\ [b]_s = vb /\\ (var_e a |--> A ** var_e b |--> B) s h /\\\n  exists ni, u2Z [i]_s = Z_of_nat ni /\\ (ni < nk)%nat /\\\n    ([flag]_s <> zero32 /\\\n      \\S_{ nk - S ni } (drop (S ni) A) = \\S_{ nk - S ni } (drop (S ni) B)) /\\\n    [a0]_s = A `32_ ni /\\ [a1]_s = B `32_ ni).\n\nmove=> s h [r_k [r_a [r_b [Hmem [ni [r_i [ni_nk [[r_flag Hsum] r_a0]]]]]]]].\nexists (B `32_ ni); split.\n- Decompose_32 B ni B1 B2 HlenB1 HB'; last by rewrite HlenB.\n  rewrite HB' (decompose_equiv _ _ _ _ _ HlenB1) 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_i inj_mult mulZC.\n- rewrite /update_store_lwxs; repeat Reg_upd; repeat (split; trivial).\n  by Assert_upd.\n  by exists ni.\n\n(**  sltu ret a0 a1 ; *)\n\napply hoare_sltu with (fun s h => u2Z [k]_s = Z_of_nat nk /\\ [a]_s = va /\\\n  [b]_s = vb /\\ (var_e a |--> A ** var_e b |--> B) s h /\\\n  exists ni, u2Z [i]_s = Z_of_nat ni /\\ (ni < nk)%nat /\\\n    ([flag]_s <> zero32 /\\\n      \\S_{ nk - S ni } (drop (S ni) A) = \\S_{ nk - S ni } (drop (S ni) B)) /\\\n    [a0]_s = A `32_ ni /\\ [a1]_s = B `32_ ni /\\\n    (([ret]_s = one32 /\\ u2Z [a0]_s < u2Z [a1]_s) \\/\n      ([ret]_s = zero32 /\\ u2Z [a0]_s >= u2Z [a1]_s))).\n\nmove=> s h [r_k [r_a [r_b [Hmem [ni [r_i [ni_nk [[r_flag Hsum [r_a0 r_a1]]]]]]]]]].\nrewrite /wp_sltu; repeat Reg_upd; repeat (split; trivial).\n- by Assert_upd.\n- exists ni; repeat (split; trivial).\n  case: ifP; move/ltZP.\n  by move=> ?; left.\n  by move/Znot_lt_ge; right.\n\n(**  movn flag r0 ret ; *)\n\napply hoare_movn with (fun s h => u2Z [k]_s = Z_of_nat nk /\\ [a]_s = va /\\\n  [b]_s = vb /\\ (var_e a |--> A ** var_e b |--> B) s h /\\\n  exists ni, u2Z [i]_s = Z_of_nat ni /\\ (ni < nk)%nat /\\\n    (\\S_{ nk - S ni } (drop (S ni) A) = \\S_{ nk - S ni } (drop (S ni) B)) /\\\n    [a0]_s = A `32_ ni /\\ [a1]_s = B `32_ ni /\\\n    (([ret]_s = one32 /\\ [flag]_s = zero32 /\\\n      u2Z [a0]_s < u2Z [a1]_s) \\/\n     ([ret]_s = zero32 /\\ [flag]_s <> zero32 /\\\n      u2Z [a0]_s >= u2Z [a1]_s))).\n\nmove=> s h [r_k [r_a [r_b [Hmem [ni [r_i [ni_nk [[r_flag HSum]]]]]]]] [r_a0 [r_a1 [ [X1 X2] | [X1 X2]]]]].\n- rewrite /wp_movn; repeat Reg_upd; split => Hr_ret.\n  + repeat (split; trivial).\n    * by Assert_upd.\n    * exists ni; repeat (split; trivial); by left.\n  + rewrite X1 in Hr_ret.\n    have {Hr_ret}: u2Z one32 = u2Z zero32 by rewrite Hr_ret.\n    by rewrite ?Z2uK.\n- rewrite /wp_movn; repeat Reg_upd; split => Hr_ret.\n  + done.\n  + repeat (split; trivial).\n    exists ni; repeat (split; trivial).\n    by right.\n\n(**  sltu ret2 a1 a0 ; *)\n\napply hoare_sltu with (fun s h => u2Z [k]_s = Z_of_nat nk /\\ [a]_s = va /\\\n  [b]_s = vb /\\ (var_e a |--> A ** var_e b |--> B) s h /\\\n  exists ni, u2Z [i]_s = Z_of_nat ni /\\ (ni < nk)%nat /\\\n    \\S_{ nk - S ni } (drop (S ni) A) = \\S_{ nk - S ni } (drop (S ni) B) /\\\n    [a0]_s = A `32_ ni /\\ [a1]_s = B `32_ ni /\\\n    (([ret]_s = one32 /\\ [ret2]_s = zero32 /\\\n        [flag]_s = zero32 /\\ u2Z [a0]_s < u2Z [a1]_s) \\/\n     ([ret]_s = zero32 /\\ [ret2]_s = one32 /\\\n        [flag]_s <> zero32 /\\ u2Z [a0]_s > u2Z [a1]_s) \\/\n     ([ret]_s = zero32 /\\ [ret2]_s = zero32 /\\\n        [flag]_s <> zero32 /\\ u2Z [a0]_s = u2Z [a1]_s))).\n\nmove=> s h [r_k [r_a [r_b [Hmem [ni [r_i [ni_nk [Hsum [r_a0 [r_a1 [\n  [r_ret [r_flag Hneq] ] |\n  [r_ret [r_flag Hneq]]]]]]]]]]]]].\n- rewrite /wp_sltu; repeat Reg_upd; repeat (split; trivial).\n  by Assert_upd.\n  exists ni; repeat (split; trivial).\n  left; split; first by [].\n  rewrite ifF //; apply/negbTE/ltZP; rewrite -leZNgt; exact/ltZW.\n- rewrite /wp_sltu; repeat Reg_upd; repeat (split; trivial).\n  by Assert_upd.\n  exists ni; repeat (split; trivial).\n  right.\n  move/Z.ge_le : Hneq; case/leZ_eqVlt => Hneq.\n  * right; repeat (split => //).\n    by rewrite Hneq ltZZ'.\n  * left; repeat (split; trivial).\n    by move/ltZP : Hneq => ->.\n    exact/Z.lt_gt.\n\n(**  movn flag r0 ret2 ; *)\n\napply hoare_movn with (fun s h => u2Z [k]_s = Z_of_nat nk /\\ [a]_s = va /\\\n  [b]_s = vb /\\ (var_e a |--> A ** var_e b |--> B) s h /\\\n  exists ni, u2Z [i]_s = Z_of_nat ni /\\ (ni < nk)%nat /\\\n    \\S_{ nk - S ni } (drop (S ni) A) = \\S_{ nk - S ni} (drop (S ni) B) /\\\n    [a0]_s = A `32_ ni /\\ [a1]_s = B `32_ ni /\\\n    (([ret]_s = one32 /\\ [ret2]_s = zero32 /\\ [flag]_s = zero32 /\\ u2Z [a0]_s < u2Z [a1]_s) \\/\n     ([ret]_s = zero32 /\\ [ret2]_s = one32 /\\ [flag]_s = zero32 /\\ u2Z [a0]_s > u2Z [a1]_s) \\/\n     ([ret]_s = zero32 /\\ [ret2]_s = zero32 /\\ [flag]_s <> zero32 /\\ u2Z [a0]_s = u2Z [a1]_s))).\n\nmove=> s h [r_k [r_a [r_b [Hmem [ni [r_i [ni_nk [Hsum [r_a0 [r_a1 [\n[r_ret [r_ret2 [r_flag Hneq] ] ] |\n[[r_ret [r_ret2 [r_flag Hneq] ] ] |\n[r_ret [r_ret2 [r_flag Hneq]]]]]]]]]]]]]]].\n- rewrite /wp_movn; repeat Reg_upd; split=> r_ret2'.\n  + by rewrite r_ret2 in r_ret2'.\n  + repeat (split; trivial).\n    exists ni; repeat (split; trivial).\n    by left.\n- rewrite /wp_movn; repeat Reg_upd; split=> r_ret2'.\n  + repeat (split; trivial).\n    by Assert_upd.\n    exists ni; repeat (split; trivial).\n    by right; left.\n  + rewrite r_ret2 in r_ret2'.\n    have {r_ret2'} : u2Z one32 = u2Z zero32 by rewrite r_ret2'.\n    by rewrite ?Z2uK.\n- rewrite /wp_movn; repeat Reg_upd; split => r_ret2'.\n  + by rewrite r_ret2 in r_ret2'.\n  + repeat (split; trivial).\n    exists ni; repeat (split; trivial).\n    by right; right.\n\n(**  movz flag r0 i\n). *)\n\napply hoare_movz'.\n\nmove=> s h [r_k [r_a [r_b [Hmem [ni [r_i [Hnink [Hsum [r_a0 [r_a1 [ [r_ret [r_ret2 [r_flag Hneq]] ] |\n[ [r_ret [r_ret2 [r_flag Hneq]] ] |\n[r_ret [r_ret2 [r_flag Hneq] ]]]]]]]]]]]]]].\n- rewrite /wp_movz; repeat Reg_upd; split => r_i'.\n  + repeat (split; trivial).\n    by Assert_upd.\n    exists ni; repeat (split; trivial).\n    by rewrite ltnW.\n    right; split; first by [].\n    left; split; first by [].\n    have ? : ni = O.\n      symmetry in r_i; move: r_i.\n      rewrite r_i' Z2uK //; by move/Z_of_nat_0.\n    subst ni.\n    rewrite subn0 !drop0.\n    destruct nk as [|nk].\n    * by move: (lt_irrefl O).\n    * split; first by [].\n      destruct A => //; destruct B => //.\n      rewrite /= subn1 /= !drop0 in Hsum.\n      rewrite /nth' /= in r_a0 r_a1.\n      rewrite 2!lSum_S Hsum -r_a0 -r_a1; exact/ltZ_add2r.\n  + repeat (split; trivial).\n    exists ni; repeat (split; trivial).\n    exact/ltnW.\n    right; split; first by [].\n    left; split; first by [].\n    destruct nk as [|nk].\n    * by rewrite ltn0 in Hnink.\n    * split; first by []; rewrite /= in Hsum.\n      rewrite subSn; last by rewrite -ltnS.\n      rewrite (drop_nth zero32); last by rewrite HlenA.\n      apply Z.gt_lt.\n      rewrite -/(A `32_ ni) -r_a0 lSum_S [drop _ _]/= (drop_nth zero32); last by rewrite HlenB.\n      rewrite -/(B `32_ ni) [drop _ _]/= -r_a1 lSum_S Hsum; exact/Z.lt_gt/ltZ_add2r.\n- rewrite /wp_movz; repeat Reg_upd; split => r_i'.\n  + repeat (split; trivial).\n    by Assert_upd.\n    exists ni; split; first by [].\n    split; first exact/ltnW.\n    right; split; first by [].\n    right; left; split; first by [].\n    have ? : ni = O.\n      symmetry in r_i; move: r_i.\n      rewrite r_i' Z2uK //; by move/Z_of_nat_0.\n    subst ni.\n    rewrite /= subn0.\n    rewrite /= in Hsum.\n    destruct A.\n    * rewrite -HlenA in Hnink; by rewrite lt0n in Hnink.\n    * destruct B.\n      - by rewrite -HlenB in Hnink; rewrite lt0n in Hnink.\n      - rewrite /= in Hsum.\n        destruct nk.\n        + by rewrite ltnn in Hnink.\n        + split; first by [].\n          rewrite /= subn1 !drop0 in Hsum.\n          rewrite /nth' /= in r_a0 r_a1.\n          rewrite 2!lSum_S Hsum -r_a0 -r_a1; exact/Z.lt_gt/ltZ_add2r/Z.gt_lt.\n  + repeat (split; trivial).\n    exists ni; split; trivial.\n    split; first exact/ltnW.\n    right; split; first by [].\n    right; left; split; first by [].\n    rewrite /= in Hsum.\n    destruct A.\n    * rewrite -HlenA in Hnink; by rewrite ltn0 in Hnink.\n    * destruct B.\n      - rewrite -HlenB in Hnink; by rewrite ltn0 in Hnink.\n      - split; first by [].\n        rewrite /= in Hsum.\n        rewrite (drop_nth zero32); last by rewrite HlenA.\n        apply Z.lt_gt.\n        rewrite (drop_nth zero32); last by rewrite HlenB.\n        have -> : (nk - ni = S (nk - S ni))%nat by rewrite -subSn.\n        simpl drop; rewrite 2!lSum_S.\n        rewrite Hsum -!/(nth' _ _ _).\n        rewrite -r_a0 -r_a1; exact/ltZ_add2r/Z.gt_lt.\n- rewrite /wp_movz; repeat Reg_upd; split=> r_i'.\n  + repeat (split; trivial).\n    by Assert_upd.\n    exists ni; split; trivial.\n    split; first exact/ltnW.\n    right; split; first by [].\n    right; right; split; first by [].\n    split; first by [].\n    have ? : ni = O.\n      rewrite r_i' Z2uK // in r_i.\n      symmetry in r_i; by move/Z_of_nat_0 : r_i.\n    subst ni.\n    rewrite /= subn0.\n    rewrite /= in Hsum.\n    destruct nk => //; destruct A => //; destruct B => //.\n    rewrite /= subn1 !drop0 in Hsum.\n    rewrite /nth' /= in r_a0 r_a1.\n    by rewrite 2!lSum_S Hsum -r_a0 -r_a1 Hneq.\n  + repeat (split; trivial).\n    exists ni; split; first by [].\n    split; first exact/ltnW.\n    left; split; first by [].\n    split; first by [].\n    rewrite /= in Hsum.\n    destruct nk as [|nk].\n    * by rewrite ltn0 in Hnink.\n    * destruct A => //; destruct B => //.\n      rewrite /= in Hsum.\n      rewrite subSn; last by rewrite -ltnS.\n      rewrite (drop_nth zero32); last by rewrite HlenA.\n      symmetry.\n      rewrite (drop_nth zero32); last by rewrite HlenB.\n      rewrite 2!lSum_S Hsum; simpl drop.\n      by rewrite -!/(nth' _ _ _) -r_a0 -r_a1 Hneq.\nQed.\n\nEnd multi_lt.\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_lt_triple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6406358548398982, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.28542219453649903}}
{"text": "Require Import Arith.\nRequire Import ZArith.\nRequire Import List.\nImport ListNotations.\n\nRequire Import v1.NeutronTactics.\nRequire Import v1.Util.\nRequire Import v1.Multi.\n\nRequire Import epics.SpecTypes.\nRequire Import expr.Expr.\n\n\nDefinition abs_value := option (Z * Z).\n\n\n(* calc *)\nRecord calc_abs : Set :=\n    CalcAbs {\n        calc_A_to_L : multi 12 abs_value;\n        calc_VAL : abs_value\n    }.\n\n(* calc_out *)\nRecord calc_out_abs : Set :=\n    CalcOutAbs {\n        calc_out_A_to_L : multi 12 abs_value;\n        calc_out_VAL : abs_value;\n        calc_out_PVAL : abs_value;\n        calc_out_OVAL : abs_value;\n        calc_out_tmp0 : abs_value\n    }.\n\n(* str_calc_out *)\nRecord str_calc_out_abs : Set :=\n    StrCalcOutAbs {\n        str_calc_out_A_to_L : multi 12 abs_value;\n        (* str_calc_out_AA_to_LL : HAVOC; *)\n        str_calc_out_VAL : abs_value;\n        (* str_calc_out_SVAL : HAVOC; *)\n        str_calc_out_PVAL : abs_value;\n        str_calc_out_OVAL : abs_value;\n        (* str_calc_out_OSV : HAVOC; *)\n        str_calc_out_tmp0 : abs_value\n    }.\n\n(* array_calc_out *)\nRecord array_calc_out_abs {n : nat} : Set :=\n    ArrayCalcOutAbs {\n        array_calc_out_A_to_L : multi 12 abs_value;\n        (* array_calc_out_AA_to_LL : HAVOC; *)\n        array_calc_out_VAL : abs_value;\n        (* array_calc_out_AVAL : HAVOC; *)\n        array_calc_out_PVAL : abs_value;\n        array_calc_out_OVAL : abs_value;\n        (* array_calc_out_OAV : HAVOC; *)\n        array_calc_out_tmp0 : abs_value\n    }.\nImplicit Arguments array_calc_out_abs.\n\n(* fanout *)\nRecord fanout_abs : Set :=\n    FanoutAbs {\n    }.\n\n(* ai *)\nRecord analog_in_abs : Set :=\n    AnalogInAbs {\n        analog_in_VAL : abs_value\n    }.\n\n(* ao *)\nRecord analog_out_abs : Set :=\n    AnalogOutAbs {\n        analog_out_VAL : abs_value;\n        analog_out_PVAL : abs_value\n    }.\n\n(* bi *)\nRecord binary_in_abs : Set :=\n    BinaryInAbs {\n        binary_in_VAL : abs_value\n    }.\n\n(* bo *)\nRecord binary_out_abs : Set :=\n    BinaryOutAbs {\n        binary_out_VAL : abs_value;\n    }.\n\n(* mbbo *)\nRecord mbbo_abs : Set :=\n    MBBOAbs {\n        mbbo_VAL : abs_value\n    }.\n\n(* stringin *)\nRecord string_in_abs : Set :=\n    StringInAbs {\n    }.\n\n(* stringout *)\nRecord string_out_abs : Set :=\n    StringOutAbs {\n    }.\n\n(* longin *)\nRecord long_in_abs : Set :=\n    LongInAbs {\n        long_in_VAL : abs_value\n    }.\n\n(* longout *)\nRecord long_out_abs : Set :=\n    LongOutAbs {\n        long_out_VAL : abs_value\n    }.\n\n(* dfanout *)\nRecord dfanout_abs : Set :=\n    DFanoutAbs {\n        dfanout_VAL : abs_value\n    }.\n\n(* seq *)\nRecord seq_abs : Set :=\n    SeqAbs {\n        seq_DO1_to_DOA : multi 10 abs_value\n    }.\n\n(* waveform *)\nRecord waveform_abs {ty : elem_type} {n : nat} : Set :=\n    WaveformAbs {\n        (* waveform_VAL : HAVOC *)\n    }.\nImplicit Arguments waveform_abs.\n\n(* subarray *)\nRecord subarray_abs {ty : elem_type} {n m : nat} : Set :=\n    SubarrayAbs {\n        (* subarray_VAL : HAVOC; *)\n        (* subarray_tmp0 : HAVOC *)\n    }.\nImplicit Arguments subarray_abs.\n\n(* asyn *)\nRecord asyn_abs : Set :=\n    AsynAbs {\n    }.\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/floatabs/RecordData.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6406358548398982, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.28542219453649903}}
{"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_recvA_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          Token (if if i then false else true then \"true\" else \"false\");\n        (New\n        (CoNm (Free (String.append \"recv_\" (if i 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!(1-i); rest *)\n  eapply TypPrefixOutput with\n      (s:=SDual (SAck t (token_of_bool (negb i))))\n      (rho:=TSingleton (token_of_bool (negb i)))\n      (t:=SDual (SAck t (token_of_bool (negb 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      | apply LToken; destruct i; ctx_wf; discriminate_w_list\n      | right; split; [reflexivity | constructor]\n      | reflexivity\n      | ].\n  (* recv_i(err2, out), i.e. New d *)\n  apply TypNew with (s:=SRecv i)\n      (L:=xc :: xerr2 :: xout :: \"recv_true\" :: \"recv_false\" :: 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 i)))\n      (rho:=TChannel (SRecv i)) (t:=SDual (SFwd (SRecv 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 i))\n      (rho:=TChannel (SDual (SAck t (token_of_bool (negb i)))))\n      (t:=SDual (SRecv1 i (SAck t (token_of_bool (negb i))) t));\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  (* d!out; rest *)\n  eapply TypPrefixOutput with\n      (s:=SDual (SRecv1 i (SAck t (token_of_bool (negb i))) t))\n      (rho:=TChannel (SDual (SToks t)))\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/ExampleABPRecvAAck.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.28542219453649903}}
{"text": "Set Implicit Arguments.\n\nSection ADTValue.\n\n  Variable ADTValue : Type.\n\n  Require Import Coq.Lists.List.\n\n  Require Import Platform.Cito.WordMap.\n  Import WordMap.\n  Require Import Platform.Cito.WordMapFacts.\n  Import FMapNotations.\n  Open Scope fmap_scope.\n\n  Require Import Platform.Cito.GeneralTactics4.\n\n  Arguments empty {_}.\n\n  Require Import Platform.Cito.SemanticsUtil.\n\n  Definition make_heap' := fold_right (fun x m => @store_pair ADTValue m x) empty.\n\n  Definition no_clash A (p1 p2 : A * Value ADTValue) :=\n    match snd p1, snd p2 with\n      | ADT _, ADT _ => (fst p1 <> fst p2)%type\n      | _, _ => True\n    end.\n\n  Definition no_clash_ls A p := List.Forall (@no_clash A p).\n\n  Definition not_in_heap elt w (v : Value ADTValue) (h : WordMap.t elt) :=\n    match v with\n      | SCA _ => True\n      | ADT _ => ~ WordMap.In w h\n    end.\n\n  Require Import Coq.Setoids.Setoid.\n\n  Add Morphism (@store_pair ADTValue) with signature Equal ==> eq ==> Equal as store_pair_Equal_m.\n  Proof.\n    intros st1 st2 Heq [w v].\n    unfold store_pair.\n    destruct v.\n    eauto.\n    simpl.\n    rewrite Heq.\n    reflexivity.\n  Qed.\n\n  Add Parametric Morphism elt : (@not_in_heap elt) with signature eq ==> eq ==> Equal ==> iff as not_in_heap_Equal_m.\n  Proof.\n    intros w v st1 st2 Heq.\n    destruct v; simpl in *.\n    intuition.\n    rewrite Heq.\n    intuition.\n  Qed.\n\n  Lemma store_pair_comm p1 p2 h : no_clash p1 p2 -> store_pair (store_pair h p1) p2 == store_pair (store_pair h p2) p1.\n  Proof.\n    intros Hnc.\n    intros p.\n    destruct p1 as [w1 v1].\n    destruct p2 as [w2 v2].\n    unfold store_pair.\n    simpl.\n    destruct v1 as [? | a1]; destruct v2 as [? | a2]; eauto.\n    unfold no_clash in *.\n    simpl in *.\n    Require Import Bedrock.Word.\n    destruct (weq p w2) as [? | Hne2].\n    {\n      subst.\n      rewrite add_eq_o by eauto.\n      rewrite add_neq_o by eauto.\n      rewrite add_eq_o by eauto.\n      eauto.\n    }\n    rewrite add_neq_o by eauto.\n    destruct (weq p w1) as [? | Hne1].\n    {\n      subst.\n      rewrite add_eq_o by eauto.\n      rewrite add_eq_o by eauto.\n      eauto.\n    }\n    rewrite add_neq_o by eauto.\n    rewrite add_neq_o by eauto.\n    rewrite add_neq_o by eauto.\n    eauto.\n  Qed.\n\n  Definition DisjointPtrs A := List.ForallOrdPairs (@no_clash A).\n\n  Require Import Bedrock.Memory.\n\n  Definition disjoint_ptrs_ls (p : W * Value ADTValue) (pairs : list (W * Value ADTValue)):=\n    match (snd p) with\n      | SCA _ => True\n      | ADT _ => ~ List.In (fst p) (List.map fst (List.filter (fun p => is_adt (snd p)) pairs))\n    end.\n\n  Require Import Platform.Cito.Semantics.\n\n  Lemma disjoint_ptrs_cons_elim' pairs : forall p, disjoint_ptrs (p :: pairs) -> disjoint_ptrs_ls p pairs /\\ disjoint_ptrs pairs.\n  Proof.\n    induction pairs; simpl; intros [w1 v1] H.\n    {\n      split.\n      unfold disjoint_ptrs_ls; simpl.\n      destruct v1; intuition.\n      unfold disjoint_ptrs; simpl.\n      econstructor.\n    }\n    destruct a as [w2 v2]; simpl in *.\n    destruct v1 as [? | a1]; destruct v2 as [? | a2]; simpl in *; try solve [unfold disjoint_ptrs, disjoint_ptrs_ls in *; simpl in *; eauto].\n    {\n      inversion H; subst; clear H.\n      split; eauto.\n    }\n    {\n      inversion H; subst; clear H.\n      split; eauto.\n    }\n  Qed.\n\n  Lemma disjoint_ptrs_ls_no_clash_ls pairs : forall p, disjoint_ptrs_ls p pairs -> no_clash_ls p pairs.\n  Proof.\n    induction pairs; simpl; intros [w1 v1] H.\n    {\n      econstructor.\n    }\n    destruct a as [w2 v2]; simpl in *.\n    destruct v1 as [? | a1]; destruct v2 as [? | a2]; simpl in *; eauto.\n    {\n      unfold disjoint_ptrs_ls, no_clash_ls, no_clash in *.\n      econstructor.\n      eauto.\n      eapply Forall_forall.\n      intuition.\n    }\n    {\n      unfold disjoint_ptrs_ls, no_clash_ls, no_clash in *.\n      econstructor.\n      eauto.\n      eapply Forall_forall.\n      intuition.\n    }\n    {\n      unfold disjoint_ptrs_ls, no_clash_ls, no_clash in *; simpl in *.\n      econstructor; simpl in *.\n      eauto.\n      eapply (IHpairs (w1, ADT a1)); eauto.\n    }      \n    {\n      unfold disjoint_ptrs_ls, no_clash_ls, no_clash in *; simpl in *.\n      intuition.\n      econstructor; simpl in *.\n      eauto.\n      eapply (IHpairs (w1, ADT a1)); eauto.\n    }      \n  Qed.\n\n  Lemma disjoint_ptrs_cons_elim pairs : forall p, disjoint_ptrs (p :: pairs) -> no_clash_ls p pairs /\\ disjoint_ptrs pairs.\n    intros p H.\n    eapply disjoint_ptrs_cons_elim' in H.\n    Require Import Platform.Cito.GeneralTactics.\n    openhyp.\n    split; eauto.\n    eapply disjoint_ptrs_ls_no_clash_ls; eauto.\n  Qed.\n\n  Lemma disjoint_ptrs_DisjointPtrs ls : disjoint_ptrs ls -> DisjointPtrs ls.\n  Proof.\n    induction ls; simpl; intros H.\n    {\n      econstructor.\n    }\n    eapply disjoint_ptrs_cons_elim in H.\n    openhyp.\n    econstructor; eauto.\n    eapply IHls; eauto.\n  Qed.\n\n  Lemma no_clash_ls_not_in_heap pairs : forall w v, no_clash_ls (w, v) pairs -> not_in_heap w v (make_heap' pairs).\n  Proof.\n    induction pairs; simpl; intros w v H.\n    {\n      destruct v; simpl.\n      eauto.\n      intros Hin.\n      eapply empty_in_iff in Hin.\n      eauto.\n    }\n    inversion H; subst.\n    destruct a as [w' v'].\n    destruct v as [? | a]; simpl in *.\n    { eauto. }\n    unfold store_pair.\n    destruct v' as [? | a']; simpl in *.\n    {\n      eapply IHpairs in H3.\n      simpl in *.\n      eauto.\n    }\n    unfold no_clash in H2; simpl in *.\n    intros Hin.\n    eapply add_in_iff in Hin.\n    destruct Hin as [Hin | Hin].\n    {\n      subst; intuition.\n    }\n    eapply IHpairs in H3.\n    simpl in *.\n    intuition.\n  Qed.\n\n  Arguments store_pair {_} _ _.\n\n  Lemma fold_left_store_pair_comm pairs : forall w v h1 h2, no_clash_ls (w, v) pairs -> h2 == store_pair h1 (w, v) -> fold_left store_pair pairs h2 == store_pair (fold_left store_pair pairs h1) (w, v).\n  Proof.\n    induction pairs; simpl; intros w v h1 h2 Hnin Hh.\n    rewrite Hh; reflexivity.\n    destruct a as [w' v'].\n    inversion Hnin; subst.\n    eapply IHpairs; eauto.\n    rewrite Hh.\n    rewrite store_pair_comm by eauto.\n    reflexivity.\n  Qed.\n\n  Lemma make_heap_make_heap' pairs : disjoint_ptrs pairs -> make_heap pairs == make_heap' pairs.\n  Proof.\n    induction pairs; simpl; intros Hdisj.\n    reflexivity.\n    unfold make_heap in *.\n    simpl.\n    destruct a as [w v].\n    eapply disjoint_ptrs_cons_elim in Hdisj.\n    destruct Hdisj as [Hnin Hdisj].\n    rewrite <- IHpairs by eauto.\n    eapply fold_left_store_pair_comm; eauto.\n    reflexivity.\n  Qed.\n\n  Add Morphism (@Semantics.word_adt_match ADTValue) with signature Equal ==> eq ==> iff as word_adt_match_Equal_m.\n  Proof.\n    intros st1 st2 Heq [w v].\n    unfold Semantics.word_adt_match.\n    simpl.\n    destruct v.\n    {\n      intuition.\n    }\n    rewrite Heq.\n    intuition.\n  Qed.\n\n  Arguments word_scalar_match {ADTValue} _.\n\n  Lemma DisjointPtrs_good_scalars_forall_word_adt_match : forall pairs h, DisjointPtrs pairs -> List.Forall word_scalar_match pairs -> List.Forall (word_adt_match (fold_left store_pair pairs h)) pairs.\n  Proof.\n    induction pairs; simpl; try solve [intuition].\n    intros h Hdisj H.\n    inversion H; subst.\n    inversion Hdisj; subst.\n    destruct a as [w v]; simpl in *.\n    econstructor.\n    {\n      rewrite fold_left_store_pair_comm; try reflexivity; trivial.\n      unfold word_adt_match.\n      unfold Semantics.word_adt_match.\n      unfold word_scalar_match in *.\n      simpl in *.\n      destruct v; simpl in *; trivial.\n      unfold store_pair; simpl.\n      rewrite add_eq_o by eauto.\n      eauto.\n    }\n    eapply IHpairs; eauto.\n  Qed.\n\n  Lemma disjoint_ptrs_good_scalars_good_inputs pairs :\n    @disjoint_ptrs ADTValue pairs ->\n    good_scalars pairs ->\n    good_inputs (make_heap pairs) pairs.\n  Proof.\n    intros Hdisj Hgs.\n    split; eauto.\n    eapply DisjointPtrs_good_scalars_forall_word_adt_match; eauto.\n    eapply disjoint_ptrs_DisjointPtrs; eauto.\n  Qed.\n\n  Lemma good_inputs_add addr (a : ADTValue) h : ~ In addr h -> good_inputs (add addr a h) ((addr, ADT a) :: nil).\n  Proof.\n    intros Hnin.\n    unfold good_inputs.\n    unfold Semantics.good_inputs.\n    unfold Semantics.disjoint_ptrs.\n    unfold Semantics.word_adt_match.\n    simpl.\n    split.\n    - repeat econstructor; simpl.\n      rewrite add_eq_o by eauto.\n      eauto.\n    - repeat econstructor; 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/SemanticsFacts9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040617, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.28526816914806113}}
{"text": "(* En este archivo se demuestra la corrección de la acción revokeGroup *)\nRequire Export Exec.\nRequire Export 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.\nRequire Import ValidStateLemmas.\n\nSection RevokeGroup.\n\nLemma postRevokeGroupCorrect : forall (s:System) (a:idApp) (p:idGrp), (pre (revokePermGroup p a) s) -> validstate s -> post_revokeGroup p a s (revokegroup_post p a s).\nProof.\n    intros.\n    unfold post_revokeGroup.\n    split. simpl; auto.\n    simpl in H.\n    unfold pre_revokeGroup in H;simpl in H.\n    destruct H.\n    \n    split.\n    destruct H.\n    unfold Semantica.revokePermGroup.\n    unfold revokegroup_post;unfold revokePermissionGroup;simpl.\n    rewrite H.\n    split;intros.\n    elim (classic (a=a'));intros.\n    exists x.\n    \n    split.\n    rewrite<- H3.\n    auto.\n    intros.\n    rewrite<- H3 in H2.\n    rewrite <-(addAndApply idApp_eq a (remove idGrp_eq p x) (grantedPermGroups (state s))) in H2.\n    inversion H2.\n    rewrite<- H6 in H4.\n    apply removeSthElse in H4.\n    destruct H4.\n    auto.\n    \n    exists lGrp'.\n    split.\n    rewrite overrideNotEq in H2.\n    auto.\n    auto.\n    intros.\n    auto.\n    \n    \n    split;intros.\n    elim (classic (a=a'));intros.\n    exists (remove idGrp_eq p x).\n    split.\n    rewrite H3.\n    symmetry.\n    apply addAndApply.\n    intros.\n    split;auto.\n    symmetry.\n    apply (notInRemove idGrp x g' p idGrp_eq ).\n    rewrite H3 in H.\n    rewrite H in H2.\n    inversion H2.\n    auto.\n    auto.\n    \n    \n    exists lGrp.\n    split.\n    rewrite overrideNotEq.\n    auto.\n    auto.\n    intros.\n    contradiction.\n    split.\n    exists (remove idGrp_eq p x).\n    split.\n    symmetry.\n    apply addAndApply.\n    rewrite <-removeSthElse.\n    unfold not;intros.\n    destruct H2.\n    apply H2;auto.\n    apply addPreservesCorrectness.\n    apply grantedPermGroupsCorrect;auto.\n\n    split.\n  - unfold revokegroup_post. unfold revokeGroupedPerms; simpl.\n    assert (exists l : list Perm,\n             map_apply idApp_eq (perms (state s)) a = Value idApp l).\n    destructVS H0.\n    destructSC statesConsistencyVS a.\n    destruct H.\n    destruct grantedPermGroupsSC. clear H1.\n    assert (exists l : list idGrp,\n        map_apply idApp_eq (grantedPermGroups (state s)) a = Value idApp l).\n    exists x; auto.\n    apply H2 in H1.\n    apply permsSC in H1. auto.\n    repeat split.\n -- intros.\n    elim (classic (a=a'));intros.\n    rewrite <- H3. destruct H1 as [lPerm H1].\n    exists lPerm. split; auto.\n    intros. unfold revokeAllPermsOfGroup in H2; rewrite H1 in H2.\n    rewrite <- H3 in H2.\n    rewrite <- addAndApply in H2.\n    inversion H2. clear H2.\n    rewrite <- H6 in H4. clear H6.\n    induction (getPermsOfGroup p a s).\n    simpl in H4. auto.\n    simpl in H4. apply removeSthElse in H4.\n    destruct H4. apply IHl. auto.\n\n    (* Caso a <> a' *)\n    exists lPerm'. destruct H1 as [lPerm H1].\n    unfold revokeAllPermsOfGroup in H2. rewrite H1 in H2.\n    split.\n    apply (overrideNotEq idApp_eq (MyList.removeAll EqTheorems.Perm_eq (getPermsOfGroup p a s) lPerm) (perms (state s))) in H3.\n    rewrite <- H3. auto.\n    intros; auto.\n -- intros.\n    elim (classic (a=a'));intros.\n    unfold revokeAllPermsOfGroup.\n    rewrite H3. clear H1. rewrite H2.\n    exists (MyList.removeAll EqTheorems.Perm_eq (getPermsOfGroup p a' s) lPerm).\n    split.\n    rewrite <- addAndApply. auto.\n    intros. split; auto.\n\n    assert (In p' (getPermsOfGroup p a' s)).\n    specialize (notInRemoveAll Perm (getPermsOfGroup p a' s) lPerm p' EqTheorems.Perm_eq H1 H4).\n    intros; auto.\n\n    apply (ifInPermsOfGroupThenSome p' p a' s).\n    auto.\n    exists lPerm. split.\n    destruct H1.\n    unfold revokeAllPermsOfGroup.\n    rewrite H1.\n    rewrite overrideNotEq.\n    auto. auto.\n    intros. contradiction.\n -- destruct H1 as [lPerm H1].\n    unfold revokeAllPermsOfGroup. rewrite H1.\n    exists (MyList.removeAll EqTheorems.Perm_eq (getPermsOfGroup p a s) lPerm).\n    split.\n\n    rewrite <- addAndApply. auto.\n    intros. unfold not. intros.\n    apply inRemoveAll in H3.\n    destruct H3.\n\n    assert (In p0 (getPermsOfGroup p a s)).\n    unfold getPermsOfGroup. unfold grantedPermsForApp.\n    rewrite H1. clear H1.\n    induction lPerm.\n    intros. inversion H3.\n    simpl in *.\n    destruct H3.\n    rewrite <- H1 in H2. rewrite H2.\n    destruct (idGrp_eq p p).\n    simpl. left. auto.\n    contradiction.\n    apply IHlPerm in H1.\n    case_eq (maybeGrp a0); intros.\n    simpl. destruct (idGrp_eq p i).\n    simpl. right. auto. auto. auto.\n\n    contradiction.\n -- unfold revokeAllPermsOfGroup.\n    destruct H1. rewrite H1.\n    apply addPreservesCorrectness.\n    apply permsCorrect;auto.\n\n  - repeat (split;auto).\nQed.\n\nLemma notPreRevokeGroupThenError : forall (s:System) (a:idApp) (p:idGrp), ~(pre (revokePermGroup p a) s) -> validstate s -> exists ec : ErrorCode, response (step s (revokePermGroup p a)) = error ec /\\ ErrorMsg s (revokePermGroup p a) ec /\\ s = system (step s (revokePermGroup p a)).\nProof.\n    intros.\n    simpl.\n    simpl in H.\n    unfold pre_revokeGroup in H.\n    exists group_wasnt_granted.\n    assert (revokegroup_pre p a s=Some group_wasnt_granted).\n    unfold revokegroup_pre.\n    case_eq (map_apply idApp_eq (grantedPermGroups (state s)) a);intros.\n    assert (InBool idGrp idGrp_eq p l=false).\n    rewrite<- not_true_iff_false.\n    unfold not;intros.\n    apply H.\n    unfold InBool in H2.\n    rewrite existsb_exists in H2.\n    destruct H2.\n    destruct H2.\n    unfold grantedPermsForApp in H2.\n    destruct idGrp_eq in H3.\n    exists l.\n    rewrite e.\n    auto.\n    discriminate H3.\n    rewrite H2;auto.\n    auto.\n    unfold revokegroup_safe.\n    rewrite H1.\n    simpl.\n    auto.\nQed.\n\nLemma revokegroupIsSound : forall (s:System) (a:idApp) (p:idGrp),\n        validstate s -> exec s (revokePermGroup p a) (system (step s (revokePermGroup p a))) (response (step s (revokePermGroup p a))).\nProof.\n    intros.\n    unfold exec.\n    split.\n    auto.\n    elim (classic (pre (revokePermGroup p a) s));intro.\n    left.\n    assert(revokegroup_pre p a s = None).\n    unfold revokegroup_pre.\n    destruct H0.\n    \n    destruct H0.\n    rewrite H0.\n    assert (InBool idGrp idGrp_eq p x = true).\n    unfold InBool.\n    rewrite existsb_exists.\n    exists p.\n    split.\n    auto.\n    destruct idGrp_eq.\n    auto.\n    destruct n.\n    auto.\n    rewrite H2.\n    auto.\n    \n    unfold step;simpl.\n    unfold revokegroup_safe;simpl.\n    rewrite H1;simpl.\n    split;auto.\n    split;auto.\n    apply postRevokeGroupCorrect;auto.\n    right.\n    apply notPreRevokeGroupThenError;auto.\n    \nQed.\nEnd RevokeGroup.\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/RevokeGroupIsSound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.28526816266606764}}
{"text": "From Coq Require Import Extraction.\nFrom Coq Require Import ZArith.\n\nExtract Inductive nat => \"u64\" [\"0\" \"__nat_succ\"] \"__nat_elim!\".\nExtract Inductive positive => \"u64\" [\"__pos_onebit\" \"__pos_zerobit\" \"1\"] \"__pos_elim!\".\nExtract Inductive N => \"u64\" [\"0\" \"__N_frompos\"] \"__N_elim!\".\nExtract Inductive Z => \"i64\" [\"0\" \"__Z_frompos\" \"__Z_fromneg\"] \"__Z_elim!\".\nExtract Inductive comparison =>\n  \"std::cmp::Ordering\"\n    [\"std::cmp::Ordering::Equal\"\n     \"std::cmp::Ordering::Less\"\n     \"std::cmp::Ordering::Greater\"].\n\nExtract Constant BinPosDef.Pos.add => \"fn ##name##(&'a self, a: u64, b: u64) -> u64 { a.checked_add(b).unwrap() }\".\nExtract Constant BinPosDef.Pos.succ => \"fn ##name##(&'a self, a: u64) -> u64 { a.checked_add(1).unwrap() }\".\nExtract Constant BinPosDef.Pos.pred => \"fn ##name##(&'a self, a: u64) -> u64 { a.checked_sub(1).unwrap_or(1) }\".\nExtract Constant BinPosDef.Pos.sub => \"fn ##name##(&'a self, a: u64, b: u64) -> u64 { a.checked_sub(b).unwrap_or(1) }\".\nExtract Constant BinPosDef.Pos.mul => \"fn ##name##(&'a self, a: u64, b: u64) -> u64 { a.checked_mul(b).unwrap() }\".\nExtract Constant BinPosDef.Pos.min => \"fn ##name##(&'a self, a: u64, b: u64) -> u64 { std::cmp::min(a, b) }\".\nExtract Constant BinPosDef.Pos.max => \"fn ##name##(&'a self, a: u64, b: u64) -> u64 { std::cmp::max(a, b) }\".\nExtract Constant BinPosDef.Pos.eqb => \"fn ##name##(&'a self, a: u64, b: u64) -> bool { a == b }\".\nExtract Constant BinPosDef.Pos.compare =>\n\"fn ##name##(&'a self, a: u64, b: u64) -> std::cmp::Ordering {\n  a.cmp(&b)\n}\".\nExtract Constant BinPosDef.Pos.compare_cont =>\n\"fn ##name##(&'a self, cont: std::cmp::Ordering, a: u64, b: u64) -> std::cmp::Ordering {\n  if a < b then\n    std::cmp::Ordering::Less\n  else if a == b then\n    cont\n  else\n    std::cmp::Ordering::Greater\".\n\nExtract Constant BinNatDef.N.add => \"fn ##name##(&'a self, a: u64, b: u64) -> u64 { a.checked_add(b).unwrap() }\".\nExtract Constant BinNatDef.N.succ => \"fn ##name##(&'a self, a: u64) -> u64 { a.checked_add(1).unwrap() }\".\nExtract Constant BinNatDef.N.pred => \"fn ##name##(&'a self, a: u64) -> u64 { a.checked_sub(1).unwrap_or(0) }\".\nExtract Constant BinNatDef.N.sub => \"fn ##name##(&'a self, a: u64, b: u64) -> u64 { a.checked_sub(b).unwrap_or(0) }\".\nExtract Constant BinNatDef.N.mul => \"fn ##name##(&'a self, a: u64, b: u64) -> u64 { a.checked_mul(b).unwrap() }\".\nExtract Constant BinNatDef.N.div => \"fn ##name##(&'a self, a: u64, b: u64) -> u64 { a.checked_div(b).unwrap_or(0) }\".\nExtract Constant BinNatDef.N.modulo => \"fn ##name##(&'a self, a: u64, b: u64) -> u64 { a.checked_rem(b).unwrap_or(a) }\".\nExtract Constant BinNatDef.N.min => \"fn ##name##(&'a self, a: u64, b: u64) -> u64 { std::cmp::min(a, b) }\".\nExtract Constant BinNatDef.N.max => \"fn ##name##(&'a self, a: u64, b: u64) -> u64 { std::cmp::max(a, b) }\".\nExtract Constant BinNatDef.N.eqb => \"fn ##name##(&'a self, a: u64, b: u64) -> bool { a == b }\".\nExtract Constant BinNatDef.N.compare =>\n\"fn ##name##(&'a self, a: u64, b: u64) -> std::cmp::Ordering { a.cmp(&b) }\".\n\nExtract Constant BinIntDef.Z.add => \"fn ##name##(&'a self, a: i64, b: i64) -> i64 { a.checked_add(b).unwrap() }\".\nExtract Constant BinIntDef.Z.succ => \"fn ##name##(&'a self, a: i64) -> i64 { a.checked_add(1).unwrap() }\".\nExtract Constant BinIntDef.Z.pred => \"fn ##name##(&'a self, a: i64) -> i64 { a.checked_sub(1).unwrap() }\".\nExtract Constant BinIntDef.Z.sub => \"fn ##name##(&'a self, a: i64, b: i64) -> i64 { a.checked_sub(b).unwrap() }\".\nExtract Constant BinIntDef.Z.mul => \"fn ##name##(&'a self, a: i64, b: i64) -> i64 { a.checked_mul(b).unwrap() }\".\nExtract Constant BinIntDef.Z.opp => \"fn ##name##(&'a self, a: i64) -> i64 { a.checked_neg().unwrap() }\".\nExtract Constant BinIntDef.Z.min => \"fn ##name##(&'a self, a: i64, b: i64) -> i64 { std::cmp::min(a, b) }\".\nExtract Constant BinIntDef.Z.max => \"fn ##name##(&'a self, a: i64, b: i64) -> i64 { std::cmp::max(a, b) }\".\nExtract Constant BinIntDef.Z.eqb => \"fn ##name##(&'a self, a: i64, b: i64) -> bool { a == b }\".\n(* TODO: div and modulo are nontrivial since Coq rounds towards negative infinity *)\n(*Extract ConstanBinIntDef.t Z.div => \"fn ##name##(a: i64, b: i64) -> i64 { a.checked_div(b).unwrap_or(0) }\".\nExtract Constant BinIntDef.Z.modulo => \"fn ##name##(a: i64, b: i64) -> i64 { a.checked_rem(b).unwrap_or(a) }\".*)\nExtract Constant BinIntDef.Z.compare =>\n\"fn ##name##(&'a self, a: i64, b: i64) -> std::cmp::Ordering { a.cmp(&b) }\".\nExtract Constant BinIntDef.Z.of_N =>\n\"fn ##name##(&'a self, a: u64) -> i64 {\n  use std::convert::TryFrom;\n  i64::try_from(a).unwrap()\n}\".\nExtract Constant BinIntDef.Z.abs_N => \"fn ##name#(&'a self, a: i64) -> u64 { a.unsigned_abs() }\".\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/extraction/plugin/theories/ExtrRustCheckedArith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2852461667911225}}
{"text": "Require Import Coq.Logic.FunctionalExtensionality Coq.Arith.EqNat Coq.Vectors.Vector Coq.MSets.MSets Names Sets Fun.\n\nInductive config : Set :=\n  | nil : config\n  | create : name -> name -> config -> config\n  | send : name -> name -> config\n  | restrict : name -> config -> config\n  | compose : config -> config -> config\n  | caseof : name -> list (name * config) -> config\n  | instantiate_1 : forall n, name -> Vector.t name n ->\n                              name -> config ->\n                              name -> Vector.t name n -> config\n  | instantiate_2 : forall n, name -> name -> Vector.t name n ->\n                              name -> config ->\n                              name -> name -> Vector.t name n -> config.\n\nInductive ConfigName (x : name) : config -> Prop :=\n  | send_name_1 : forall y, ConfigName x (send x y)\n  | send_name_2 : forall y, ConfigName x (send y x)\n  | create_name_1 : forall y p, ConfigName x (create x y p)\n  | create_name_2 : forall y p, ConfigName x (create y x p)\n  | create_name_p : forall y z p, ConfigName x p -> ConfigName x (create y z p)\n  | compose_name_l : forall pl pr, ConfigName x pl -> ConfigName x (compose pl pr)\n  | compose_name_r : forall pl pr, ConfigName x pr -> ConfigName x (compose pl pr)\n  | restrict_name : forall p, ConfigName x (restrict x p)\n  | restrict_name_p : forall y p, ConfigName x p -> ConfigName x (restrict y p)\n  | caseof_name : forall l, ConfigName x (caseof x l)\n  | caseof_name_h_fst : forall y c l, ConfigName x (caseof y ((x, c) :: l))\n  | caseof_name_h_snd : forall y n c l, ConfigName x c -> ConfigName x (caseof y ((n, c) :: l))\n  | caseof_name_t : forall y nc l, ConfigName x (caseof y l) -> ConfigName x (caseof y (nc :: l)).\n\nHint Constructors ConfigName.\n\nInductive ConfigBoundedName (x : name) : config -> Prop :=\n  | create_bounded : forall y p, x <> y -> ConfigBoundedName x (create y x p)\n  | create_bounded_p : forall y z p, ConfigBoundedName x p -> x <> y ->\n                                     ConfigBoundedName x (create y z p)\n  | compose_bounded_b : forall pl pr, ConfigBoundedName x pl ->\n                                      ConfigBoundedName x pr ->\n                                      ConfigBoundedName x (compose pl pr)\n  | compose_bounded_l : forall pl pr, ConfigBoundedName x pl ->\n                                      ~ ConfigName x pr ->\n                                      ConfigBoundedName x (compose pl pr)\n  | compose_bounded_r : forall pl pr, ConfigBoundedName x pr ->\n                                      ~ ConfigName x pl ->\n                                      ConfigBoundedName x (compose pl pr)\n  | restrict_bounded : forall p, ConfigBoundedName x (restrict x p)\n  | restrict_bounded_p : forall y p, ConfigBoundedName x p ->\n                                     ConfigBoundedName x (restrict y p)\n  | caseof_bounded_s : forall y n c l, ConfigBoundedName x c ->\n                                       ~ ConfigName x (caseof y l) ->\n                                       x <> n ->\n                                       ConfigBoundedName x (caseof y ((n, c) :: l))\n  | caseof_bounded_h : forall y n c l, ConfigBoundedName x c ->\n                                       ConfigBoundedName x (caseof y l) ->\n                                       x <> n ->\n                                       ConfigBoundedName x (caseof y ((n, c) :: l))\n  | caseof_bounded_t : forall y n c l, ConfigBoundedName x (caseof y l) ->\n                                       ~ ConfigName x c ->\n                                       x <> n ->\n                                       ConfigBoundedName x (caseof y ((n, c) :: l)).\n\n  (* | caseof_bounded_s : forall y n c, ConfigBoundedName x c -> *)\n  (*                                    x <> y -> *)\n  (*                                    x <> n -> *)\n  (*                                    ConfigBoundedName x (caseof y ((n, c) :: List.nil)) *)\n  (* | caseof_bounded_h : forall y n c l, ConfigBoundedName x c -> *)\n  (*                                      ~ ConfigBoundedName x (caseof y l) -> *)\n  (* | caseof_bounded_t : forall y n c l, ConfigBoundedName x (caseof y l) -> *)\n  (*                                      x <> n -> *)\n  (*                                      ConfigBoundedName x (caseof y ((n, c) :: l)) *)\n  (* | caseof_bounded : forall y l, Forall (fun nc => ConfigBoundedName x (snd nc)) l -> *)\n  (*                                ConfigBoundedName x (caseof y l). *)\n\nHint Constructors ConfigBoundedName.\n\nInductive ConfigFreeName (x : name) : config -> Prop :=\n  | send_free_1 : forall y, ConfigFreeName x (send x y)\n  | send_free_2 : forall y, ConfigFreeName x (send y x)\n  | create_free : forall y p, ConfigFreeName x (create x y p)\n  | create_free_p : forall y z p, ConfigFreeName x p -> x <> z -> ConfigFreeName x (create y z p)\n  | compose_free_l : forall pl pr, ConfigFreeName x pl -> ConfigFreeName x (compose pl pr)\n  | compose_free_r : forall pl pr, ConfigFreeName x pr -> ConfigFreeName x (compose pl pr)\n  | restrict_free : forall r p, ConfigFreeName x p -> x <> r -> ConfigFreeName x (restrict r p)\n  | caseof_free : forall l, ConfigFreeName x (caseof x l)\n  | caseof_free_h_fst : forall y c l, ConfigFreeName x (caseof y ((x, c) :: l))\n  | caseof_free_h_snd : forall y n c l, ConfigFreeName x c -> ConfigFreeName x (caseof y ((n, c) :: l))\n  | caseof_free_t : forall y nc l, ConfigFreeName x (caseof y l) -> ConfigFreeName x (caseof y (nc :: l))\n  | instantiate_1_free_x : forall n u v z p y,\n                             ConfigFreeName x (instantiate_1 n u v z p x y)\n  | instantiate_1_free_y : forall n u v z p x' y,\n                             Vector.In x y ->\n                             ConfigFreeName x (instantiate_1 n u v z p x' y)\n  | instantiate_1_free_p : forall n u v z p x' y,\n                             ConfigFreeName x p ->\n                             x <> u ->\n                             ~ Vector.In x v ->\n                             x <> z ->\n                             ConfigFreeName x (instantiate_1 n u v z p x' y)\n  | instantiate_2_free_x_1 : forall n u1 u2 v z p x2 y,\n                               ConfigFreeName x (instantiate_2 n u1 u2 v z p x x2 y)\n  | instantiate_2_free_x_2 : forall n u1 u2 v z p x1 y,\n                               ConfigFreeName x (instantiate_2 n u1 u2 v z p x1 x y)\n  | instantiate_2_free_y : forall n u1 u2 v z p x1 x2 y,\n                             Vector.In x y ->\n                             ConfigFreeName x (instantiate_2 n u1 u2 v z p x1 x2 y)\n  | instantiate_2_free_p : forall n u1 u2 v z p x1 x2 y,\n                             ConfigFreeName x p ->\n                             x <> u1 ->\n                             x <> u2 ->\n                             ~ Vector.In x v ->\n                             x <> z ->\n                             ConfigFreeName x (instantiate_2 n u1 u2 v z p x1 x2 y).\n\nHint Constructors ConfigFreeName.\n\n(* Lemma config_name_dec : forall x p, {ConfigName x p} + {~ ConfigName x p}. *)\n(* Proof. *)\n(*   intros. *)\n(*   induction p. *)\n(*     right; intro. *)\n(*     inversion H. *)\n\n(*     inversion IHp. *)\n(*       left; auto. *)\n\n(*       destruct (name_dec x n). *)\n(*         rewrite e; left; auto. *)\n\n(*         destruct (name_dec x n0). *)\n(*           rewrite e; left; auto. *)\n\n(*           right; intro. *)\n(*           inversion H0; auto. *)\n\n(*     destruct (name_dec x n). *)\n(*       rewrite e; left; auto. *)\n\n(*       destruct (name_dec x n0). *)\n(*         rewrite e; left; auto. *)\n\n(*         right; intro. *)\n(*         inversion H; auto. *)\n\n(*     destruct (name_dec x n). *)\n(*       rewrite e; left; auto. *)\n\n(*       inversion IHp. *)\n(*         left; auto. *)\n\n(*         right; intro. *)\n(*         inversion H0; auto. *)\n\n(*     inversion IHp1; inversion IHp2. *)\n(*       left; auto. *)\n\n(*       left; auto. *)\n\n(*       left; auto. *)\n\n(*       right; intro. *)\n(*       inversion H1; auto. *)\n\n(*     destruct (name_dec x n). *)\n(*       rewrite e; left; auto. *)\n\n(*       induction l. *)\n(*         right; intro. *)\n(*         inversion H. *)\n(*           apply n0; auto. *)\n\n(*         inversion IHl. *)\n(*           left. *)\n(*           inversion H; subst. *)\n(*             auto. *)\n\n(*             apply caseof_name_t; auto. *)\n\n(*             apply caseof_name_t; auto. *)\n\n(*             apply caseof_name_t; auto. *)\n\n(*           destruct a. *)\n(*           destruct (name_dec x n1). *)\n(*             left; rewrite e; auto. *)\n\n(*             destruct (config_name_dec x c). *)\n(* Qed. *)\n\n(* Lemma config_free_dec : forall x p, {ConfigFreeName x p} + {~ ConfigFreeName x p}. *)\n(* Proof. *)\n(*   intros. *)\n(*   induction p. *)\n(*     right; intro; inversion H. *)\n\n(*     destruct (name_dec x n). *)\n(*       rewrite e; left; auto. *)\n(*       destruct (name_dec x n0). *)\n(*         rewrite e; right; intro; inversion H; subst; auto. *)\n(*         inversion IHp. *)\n(*           left; auto. *)\n(*           right; intro; inversion H0; subst; auto. *)\n\n(*     destruct (name_dec x n); destruct (name_dec x n0). *)\n(*       rewrite e; auto. *)\n(*       rewrite e; auto. *)\n(*       rewrite e; auto. *)\n(*       right; intro; inversion H; subst; auto. *)\n\n(*     destruct (name_dec x n). *)\n(*       rewrite e; right; intro; inversion H; subst; auto. *)\n(*       inversion IHp. *)\n(*         left; auto. *)\n(*         right; intro; inversion H0; subst; auto. *)\n\n(*     inversion_clear IHp1; inversion_clear IHp2. *)\n(*       left; auto. *)\n(*       left; auto. *)\n(*       left; auto. *)\n(*       right; intro; inversion H1; subst; auto. *)\n(* Qed. *)\n\n(* Lemma config_bounded_prop : forall x p, ConfigBoundedName x p -> ConfigName x p. *)\n(* Proof. *)\n(*   intros. *)\n(*   induction p; inversion H; subst; auto. *)\n(* Qed. *)\n\n(* Lemma config_free_prop : forall x p, ConfigFreeName x p -> ConfigName x p. *)\n(* Proof. *)\n(*   intros. *)\n(*   induction p; inversion H; subst; auto. *)\n(* Qed. *)\n\n(* Lemma config_name_prop : forall x p, ConfigName x p -> *)\n(*                                      (ConfigBoundedName x p <-> ~ ConfigFreeName x p) /\\ *)\n(*                                      (ConfigFreeName x p <-> ~ ConfigBoundedName x p). *)\n(* Proof. *)\n(*   intros. *)\n(*   induction p. *)\n(*     inversion H. *)\n\n(*     inversion H; subst. *)\n(*       split; split; intros; try intro. *)\n(*         inversion H0; subst; auto. *)\n\n(*         absurd (ConfigFreeName n (create n n0 p)); auto. *)\n\n(*         inversion H1; subst; auto. *)\n\n(*         auto. *)\n\n(*       split; split; intros; try intro. *)\n(*         inversion H0; subst; inversion H1; subst; auto. *)\n\n(*         apply create_bounded. *)\n(*         intro; subst; apply H0; auto. *)\n\n(*         inversion H0; subst; inversion H1; subst; auto. *)\n\n(*         assert (n <> n0 -> False). *)\n(*           intro. *)\n(*           apply H0. *)\n(*           auto. *)\n(*         apply eq_name_double_neg in H1. *)\n(*         rewrite H1; auto. *)\n\n(*       apply IHp in H1. *)\n(*       inversion_clear H1. *)\n(*       split; split; intros; try intro. *)\n(*         inversion H1; subst; inversion H3; subst; auto. *)\n(*         apply H0 in H6; auto. *)\n\n(*         assert (x <> n). *)\n(*           intro; apply H1. *)\n(*           rewrite H3; auto. *)\n(*         destruct (beq_name x n0) eqn:?. *)\n(*           apply beq_name_true_iff in Heqb. *)\n(*           rewrite <- Heqb. *)\n(*           apply create_bounded; auto. *)\n\n(*           apply beq_name_false_iff in Heqb. *)\n(*           apply create_bounded_p. *)\n(*             apply H0. *)\n(*             intro. *)\n(*             apply H1. *)\n(*             apply create_free_p; auto. *)\n\n(*             auto. *)\n\n(*         inversion H1; subst; inversion H3; subst; auto. *)\n(*         apply H0 in H6; auto. *)\n\n(*         destruct (beq_name x n) eqn:?. *)\n(*           apply beq_name_true_iff in Heqb. *)\n(*           rewrite Heqb; auto. *)\n\n(*           apply beq_name_false_iff in Heqb. *)\n(*           assert (x <> n0). *)\n(*             intro. *)\n(*             rewrite <- H3 in H1. *)\n(*             apply H1. *)\n(*             auto. *)\n(*           apply create_free_p; auto. *)\n(*           apply H2. *)\n(*           intro. *)\n(*           apply H1. *)\n(*           auto. *)\n\n(*     inversion_clear H; subst. *)\n(*       split; split; intros; try intro. *)\n(*         inversion H. *)\n\n(*         exfalso; apply H; auto. *)\n\n(*         inversion H0. *)\n\n(*         auto. *)\n(*       split; split; intros; try intro. *)\n(*         inversion H. *)\n\n(*         exfalso; apply H; auto. *)\n\n(*         inversion H0. *)\n\n(*         auto. *)\n\n(*     inversion_clear H; subst. *)\n(*       split; split; intros; try intro. *)\n(*         inversion H0; auto. *)\n\n(*         auto. *)\n\n(*         inversion H; auto. *)\n\n(*         exfalso; apply H; auto. *)\n(*       apply IHp in H0. *)\n(*       clear IHp. *)\n(*       inversion_clear H0. *)\n(*       split; split; intros; try intro. *)\n(*         inversion H0; subst; inversion H2; subst; auto. *)\n(*         apply H in H4; auto. *)\n\n(*         destruct (beq_name x n) eqn:?. *)\n(*           apply beq_name_true_iff in Heqb. *)\n(*           rewrite Heqb; auto. *)\n\n(*           apply beq_name_false_iff in Heqb. *)\n(*           apply restrict_bounded_p. *)\n(*           apply H; intro. *)\n(*           apply H0; apply restrict_free; auto. *)\n\n(*         inversion H0; subst; inversion H2; subst; auto. *)\n(*         apply H in H4; auto. *)\n\n(*         destruct (beq_name x n) eqn:?. *)\n(*           apply beq_name_true_iff in Heqb. *)\n(*           rewrite Heqb in H0. *)\n(*           exfalso; apply H0; auto. *)\n\n(*           apply beq_name_false_iff in Heqb. *)\n(*           apply restrict_free; auto. *)\n(*           apply H1. *)\n(*           intro. *)\n(*           apply H0; auto. *)\n\n(*     inversion_clear H; subst. *)\n(*       assert (ConfigName x p1); auto. *)\n(*       apply IHp1 in H0. *)\n(*       inversion_clear H0. *)\n(*       split; split; intros; try intro. *)\n(*         inversion_clear H0; subst; inversion_clear H3; subst; auto. *)\n(*           apply H1 in H4; auto. *)\n\n(*           assert (ConfigBoundedName x p2); auto. *)\n(*           apply config_bounded_prop in H3. *)\n(*           apply IHp2 in H3. *)\n(*           inversion_clear H3. *)\n(*           apply H6 in H5; auto. *)\n\n(*           apply H1 in H0; auto. *)\n\n(*           apply config_free_prop in H0; auto. *)\n\n(*         assert (~ ConfigFreeName x p1 /\\ ~ ConfigFreeName x p2). *)\n(*           split. *)\n(*             intro; apply H0; auto. *)\n(*             intro; apply H0; auto. *)\n(*         inversion_clear H3. *)\n(*         apply H1 in H4. *)\n(*         destruct (config_name_dec x p2). *)\n(*           apply IHp2 in c. *)\n(*           inversion_clear c. *)\n(*           apply H3 in H5. *)\n(*           auto. *)\n\n(*           auto. *)\n\n(*         inversion H0; subst; inversion H3; subst; auto. *)\n(*           apply H1 in H7; auto. *)\n\n(*           apply H1 in H7; auto. *)\n\n(*           assert (ConfigBoundedName x p2); auto. *)\n(*           apply config_bounded_prop in H4; apply IHp2 in H4. *)\n(*           inversion_clear H4. *)\n(*           apply H6 in H8; auto. *)\n\n(*           apply config_free_prop in H5; auto. *)\n\n(*         destruct (config_name_dec x p2). *)\n(*           apply IHp2 in c. *)\n(*           inversion_clear c. *)\n(*           destruct (config_free_dec x p1); auto. *)\n(*           destruct (config_free_dec x p2); auto. *)\n(*           apply H1 in n. *)\n(*           apply H3 in n0. *)\n(*           exfalso; apply H0; auto. *)\n\n(*           apply compose_free_l. *)\n(*           apply H2. *)\n(*           intro. *)\n(*           apply H0. *)\n(*           auto. *)\n\n(*       assert (ConfigName x p2); auto. *)\n(*       apply IHp2 in H0. *)\n(*       inversion_clear H0. *)\n(*       clear IHp2. *)\n(*       split; split; intros; try intro. *)\n(*         inversion H0; subst; inversion H3; subst; auto. *)\n(*           assert (ConfigBoundedName x p1); auto. *)\n(*           apply config_bounded_prop in H4. *)\n(*           apply IHp1 in H4. *)\n(*           inversion_clear H4. *)\n(*           apply H8 in H6; auto. *)\n\n(*           apply H1 in H7; auto. *)\n\n(*           apply config_free_prop in H5; auto. *)\n\n(*           apply H1 in H5; auto. *)\n\n(*         assert (~ ConfigFreeName x p1 /\\ ~ ConfigFreeName x p2). *)\n(*           split. *)\n(*             intro; apply H0; auto. *)\n(*             intro; apply H0; auto. *)\n(*         inversion_clear H3. *)\n(*         apply H1 in H5. *)\n(*         destruct (config_name_dec x p1). *)\n(*           apply IHp1 in c; inversion_clear c. *)\n(*           apply H3 in H4. *)\n(*           auto. *)\n\n(*           auto. *)\n\n(*         inversion H0; subst; inversion H3; subst; auto. *)\n(*           assert (ConfigBoundedName x p1); auto. *)\n(*           apply config_bounded_prop in H4; apply IHp1 in H4; inversion_clear H4. *)\n(*           apply H6 in H7; auto. *)\n\n(*           apply config_free_prop in H5; auto. *)\n\n(*           apply H1 in H8; auto. *)\n\n(*           apply H1 in H7; auto. *)\n\n(*         destruct (config_free_dec x p1); auto. *)\n(*         destruct (config_free_dec x p2); auto. *)\n(*         destruct (config_name_dec x p1). *)\n(*           apply IHp1 in c; inversion_clear c. *)\n(*           apply H3 in n. *)\n(*           apply H1 in n0. *)\n(*           exfalso; apply H0; auto. *)\n\n(*           apply compose_free_r. *)\n(*           apply H2. *)\n(*           intro. *)\n(*           apply H0. *)\n(*           auto. *)\n(* Qed. *)\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/Config.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2852461667911225}}
{"text": "Require Import\n        Coq.Vectors.Vector\n        Coq.ZArith.ZArith\n        Coq.Strings.Ascii\n        Coq.Strings.String\n        Coq.Bool.Bool\n        Coq.Vectors.Vector\n        Coq.Lists.List.\n\nRequire Import\n        Fiat.Common.BoundedLookup\n        Fiat.Common.SumType\n        Fiat.Common.EnumType\n        Fiat.Narcissus.Formats.DomainNameOpt\n        Fiat.QueryStructure.Specification.Representation.Notations\n        Fiat.QueryStructure.Specification.Representation.Heading\n        Fiat.QueryStructure.Specification.Representation.Tuple.\n\nRequire Import\n        Bedrock.Word\n        Bedrock.Memory.\n\nImport Lists.List.ListNotations.\nImport Vectors.Vector.VectorNotations.\n\nLocal Open Scope string_scope.\nLocal Open Scope Tuple_scope.\nLocal Open Scope vector_scope.\n\nRequire Export Fiat.Narcissus.Examples.DNS.SimpleRRecordTypes.\n\nSection QTypes.\n\n  (* DNS packet Query Types are a superset of RR Types. *)\n  Definition QTypes :=\n    [\"TKEY\"; (* Transaction Key \t[RFC2930] *)\n     \"TSIG\"; (* Transaction Signature \t[RFC2845] *)\n     \"IXFR\"; (* incremental transfer \t[RFC1995] *)\n     \"AXFR\"; (* transfer of an entire zone \t[RFC1035][RFC5936] *)\n     \"MAILB\"; (* mailbox-related RRs (MB, MG or MR) \t[RFC1035] *)\n     \"MAILA\"; (* mail agent RRs (OBSOLETE - see MX) \t[RFC1035] *)\n     \"STAR\" (*A request for all records the server/cache has available \t[RFC1035][RFC6895] *)\n    ].\n\n  Definition QType_Ws : t (word 16) 11 :=\n    Eval simpl in RRecordType_Ws ++ Vector.map (natToWord 16)\n                             [249; (*\"TKEY\" *)\n                                250; (*\"TSIG\" *)\n                                251; (*\"IXFR\" *)\n                                252; (*\"AXFR\" *)\n                                253;(*\"MAILB\" *)\n                                254;(*\"MAILA\" *)\n                                255 (* \"STAR\" *)].\n\n  Definition QType := EnumType ((OurRRecordTypes(* ++ ExtraRRecordTypes) *) ++ QTypes)).\n\n  Definition QType_inj (rr : RRecordType) : QType :=\n    Fin.L _ rr.\n\n  Definition beq_QType (a b : QType) : bool :=\n    fin_beq a b.\n\n  Definition QType_dec (a b : QType) :=\n    fin_eq_dec a b.\n\n  Lemma beq_QType_sym :\n    forall rrT rrT', beq_QType rrT rrT' = beq_QType rrT' rrT.\n  Proof.\n    intros; eapply fin_beq_sym.\n  Qed.\n\n  Coercion QType_inj : RRecordType >-> QType.\n\n  Definition QType_match (rtype : RRecordType) (qtype : QType) :=\n    qtype = ```\"STAR\" \\/ qtype = rtype.\n\nEnd QTypes.\n\nSection RRecordClass.\n\n  Definition RRecordClasses :=\n    [ \"Internet\"; (* (IN) \t[RFC1035] *)\n        \"Chaos\"; (* (CH) \t[D. Moon, \"Chaosnet\", A.I. Memo 628, Massachusetts Institute of Technology Artificial Intelligence Laboratory, June 1981.] *)\n        \"Hesiod\" (* (HS) \t[Dyer, S., and F. Hsu, \"Hesiod\", Project Athena Technical Plan - Name Service, April 1987.] *)\n    ].\n\n  Definition RRecordClass_Ws : t (word 16) 3 :=\n    Eval simpl in Vector.map (natToWord 16)\n                             [1; (* \"IN\" *)\n                                3; (* \"CH\" *)\n                                4 (* \"Hesiod\" *)].\n\n  Definition RRecordClass := EnumType RRecordClasses.\n\n  Definition beq_RRecordClass (a b : RRecordClass) : bool\n    := fin_beq a b.\n\n  Definition RRecordClass_dec (a b : RRecordClass) :=\n    fin_eq_dec a b.\n\n  (* DNS Packet Question Classes *)\n  Definition QClass := EnumType (RRecordClasses ++ [\"Any\"]).\n\n  Definition QClass_Ws : t (word 16) 4 :=\n    Eval simpl in Vector.append\n                    RRecordClass_Ws\n                    [natToWord 16 255 (* \"Any\"*)].\n\n  Definition QClass_inj (qclass : RRecordClass) : QClass :=\n    Fin.L _ qclass.\n\n  Definition beq_QClass (a b : QClass) : bool\n    := fin_beq a b.\n\n  Definition QClass_dec (a b : QClass) :=\n    fin_eq_dec a b.\n\nEnd RRecordClass.\n\nSection ResponseCode.\n\n    Definition ResponseCodes :=\n    [\"NoError\";  (* No Error [RFC1035] *)\n       \"FormErr\";  (* Format Error [RFC1035] *)\n       \"ServFail\"; (* Server Failure [RFC1035] *)\n       \"NXDomain\"; (* Non-Existent  Domain \t[RFC1035] *)\n       \"NotImp\";   (* Not Implemented [RFC1035] *)\n       \"Refused\";  (* Query Refused [RFC1035] *)\n       \"YXDomain\"; (* Name Exists when it should not [RFC2136][RFC6672] *)\n       \"YXRRSet\";  (* RR Set Exists when it should not \t[RFC2136] *)\n       \"NXRRSet\";  (* RR Set that should exist does not \t[RFC2136] *)\n       \"NotAuth\";  (* Server Not Authoritative for zone \t[RFC2136] *)\n                   (* and Not Authorized [RFC2845] *)\n       \"NotZone\" \t (* Name not  contained in zone \t[RFC2136] *)\n    ].\n\n  Definition RCODE_Ws : t (word 4) 11 :=\n    Eval simpl in Vector.map (natToWord 4)\n    [0;  (* No Error [RFC1035] *)\n     1;  (* Format Error [RFC1035] *)\n     2; (* Server Failure [RFC1035] *)\n     3; (* Non-Existent  Domain \t[RFC1035] *)\n     4;   (* Not Implemented [RFC1035] *)\n     5;  (* Query Refused [RFC1035] *)\n     6; (* Name Exists when it should not [RFC2136][RFC6672] *)\n     7;  (* RR Set Exists when it should not \t[RFC2136] *)\n     8;  (* RR Set that should exist does not \t[RFC2136] *)\n     9;  (* Server Not Authoritative for zone \t[RFC2136] *)\n         (* and Not Authorized [RFC2845] *)\n     10 \t (* Name not  contained in zone \t[RFC2136] *)\n    ].\n\n  Definition ResponseCode := EnumType ResponseCodes.\n\n  Definition beq_ResponseCode (a b : ResponseCode) : bool\n    := fin_beq a b.\n\n  Definition ResponseCode_dec (a b : ResponseCode) :=\n    fin_eq_dec a b.\nEnd ResponseCode.\n\nSection OpCode.\n\n  Definition OpCodes :=\n    [\"Query\";    (* RFC1035] *)\n     \"IQuery\"; (* Inverse Query  OBSOLETE) [RFC3425] *)\n     \"Status\"; (* [RFC1035] *)\n     \"Notify\"  (* [RFC1996] [RFC2136] *)\n    ].\n\n  Definition OpCode := EnumType OpCodes.\n\n  Definition Opcode_Ws : t (word 4) 4 :=\n    Eval simpl in Vector.map (natToWord 4)\n                             [0;    (* RFC1035] *)\n                              1; (* Inverse Query  OBSOLETE) [RFC3425] *)\n                              2; (* [RFC1035] *)\n                              4  (* [RFC1996] [RFC2136] *)].\n\n  Definition beq_OpCode (a b : OpCode) : bool\n    := fin_beq a b.\n\n  Definition OpCode_dec (a b : OpCode) :=\n    fin_eq_dec a b.\n\nEnd OpCode.\n\nSection Packet.\n\n  (* The question section of a DNS packet. *)\n  Definition question :=\n    @Tuple <\n    \"qname\" :: DomainName,\n    \"qtype\" :: QType,\n    \"qclass\" :: QClass >%Heading.\n  (* [\"google\", \"com\"] *)\n\n  (* DNS Resource Records. *)\n  Definition sRRecords := \"ResourceRecords\".\n  Definition sNAME := \"Name\".\n  Definition sTTL := \"TTL\".\n  Definition sCLASS := \"Class\".\n  Definition sTYPE := \"Type\".\n  Definition sRDATA := \"rdata\".\n  Definition sRLENGTH := \"rlength\".\n\n  Definition resourceRecordHeading :=\n    < sNAME :: DomainName,\n      sTTL :: timeT,\n      sCLASS :: RRecordClass,\n      sRDATA :: RDataType>%Heading.\n\n  Definition resourceRecord := @Tuple resourceRecordHeading.\n\n  (* Variant headings for each RDataType *)\n  Definition VariantResourceRecordHeading RDATAT :=\n    < sNAME :: DomainName,\n      sTTL :: timeT,\n      sCLASS :: RRecordClass,\n      sRDATA :: RDATAT >%Heading.\n\n  Definition VariantResourceRecord RDATAT := @Tuple (VariantResourceRecordHeading RDATAT).\n\n  (* Aliases for the Common Record Types *)\n  Definition CNAME_Record :=\n    VariantResourceRecord ResourceRecordTypeTypes[@ OurCNAME].\n  Definition A_Record :=\n    VariantResourceRecord ResourceRecordTypeTypes[@ OurA ].\n  Definition NS_Record :=\n    VariantResourceRecord ResourceRecordTypeTypes[@ OurNS].\n  Definition SOA_Record :=\n    VariantResourceRecord ResourceRecordTypeTypes[@ OurSOA].\n\n  Definition RRecord2VariantResourceRecord\n             (rr : resourceRecord)\n    : VariantResourceRecord ResourceRecordTypeTypes[@(SumType_index ResourceRecordTypeTypes (rr!sRDATA))] :=\n    < sNAME :: rr!sNAME,\n      sTTL :: rr!sTTL,\n      sCLASS :: rr!sCLASS,\n      sRDATA :: SumType_proj _ (rr!sRDATA)>.\n\n  Definition VariantResourceRecord2RRecord\n             {idx}\n             (vrr : VariantResourceRecord ResourceRecordTypeTypes[@idx])\n    : resourceRecord :=\n    < sNAME :: vrr!sNAME,\n      sTTL :: vrr!sTTL,\n      sCLASS :: vrr!sCLASS,\n      sRDATA :: inj_SumType _ idx (vrr!sRDATA)>.\n\n  Definition CNAME_Record2RRecord\n             (vrr : CNAME_Record)\n    : resourceRecord := VariantResourceRecord2RRecord vrr.\n  Definition A_Record2RRecord\n             (vrr : A_Record)\n    : resourceRecord := VariantResourceRecord2RRecord vrr.\n  Definition NS_Record2RRecord\n             (vrr : NS_Record)\n    : resourceRecord := VariantResourceRecord2RRecord vrr.\n  Definition SOA_Record2RRecord\n             (vrr : SOA_Record)\n    : resourceRecord := VariantResourceRecord2RRecord vrr.\n\n  (* Binary Format of DNS Header:\n                              1  1  1  1  1  1\n0  1  2  3  4  5  6  7  8  9  0  1  2  3  4  5\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n|                      ID                       |\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n|QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n|                    QDCOUNT                    |\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n|                    ANCOUNT                    |\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n|                    NSCOUNT                    |\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n|                    ARCOUNT                    |\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n   *)\n\n  (* DNS Packet Layout:\n+---------------------+\n|        Header       |\n+---------------------+\n|       Question      |\n+---------------------+\n|        Answer       |\n+---------------------+\n|      Authority      |\n+---------------------+\n|      Additional     |\n+---------------------+\n   *)\n\n(* Unique Request IDs *)\nDefinition ID : Type := word 16.\n\n  Definition packetHeading :=\n    < \"id\" :: ID, (* 16 bit Word. *)\n      \"QR\" :: bool, (* is packet a query (0), or a response (1) *)\n      \"Opcode\" :: OpCode, (* kind of query in packet *)\n      \"AA\" :: bool, (* is responding server authorative *)\n      \"TC\" :: bool, (* is packet truncated *)\n      \"RD\" :: bool, (* are recursive queries desired *)\n      \"RA\" :: bool, (* are recursive queries supported by responding server *)\n      \"RCODE\" :: ResponseCode, (* response code *)\n      \"question\" :: question, (* `list question` in case we can have multiple questions? *)\n      \"answers\" :: list resourceRecord,\n      \"authority\" :: list resourceRecord,\n      \"additional\" :: list resourceRecord >%Heading.\n\n  Definition packet := @Tuple packetHeading.\n\n  Definition buildempty (is_authority : bool)\n             (rcode : BoundedIndex ResponseCodes)\n             (p : packet) :=\n    p ○ [ \"AA\" ::= is_authority; (* Update Authority field *)\n          \"QR\" ::= true; (* Set response flag to true *)\n          \"RCODE\" ::= ibound (indexb rcode);\n          \"answers\" ::= nil;\n          \"authority\"  ::= nil;\n          \"additional\" ::= nil ].\n\n  (* add a resource record to a packet's answers *)\n  Definition add_answer (p : packet) (t : resourceRecord) :=\n    p ○ [o !! \"answers\" / t :: o].\n\n  (* add a resource record authority to a packet's authorities\n   (ns = name server). *)\n  Definition add_ns (p : packet) (t : resourceRecord) :=\n    p ○ [o !! \"authority\" / t :: o].\n\n  (* combine with above? *)\n  Definition add_additional (p : packet) (t : resourceRecord) :=\n    p ○ [o !! \"additional\" / t :: o].\n\n  Definition updateRecords (p : packet) answers' authority' additional' :=\n    p ○ [\"answers\" ::= answers';\n           \"authority\" ::= authority';\n           \"additional\" ::= additional'].\n\n  Definition get_name (r : resourceRecord) := r!sNAME.\n  Definition name_length (r : resourceRecord) := String.length (get_name r).\n\n  Definition isQuestion (p : packet) :=\n    match p!\"answers\", p!\"authority\", p!\"additional\" with\n    | nil, nil, nil => true\n    | _, _, _ => false\n    end.\n\n  Definition is_empty {A} (l : list A) : bool :=\n    match l with\n    | nil => true\n    | _ => false\n    end.\n\n  Lemma is_empty_app {A} :\n    forall (l l' : list A),\n      is_empty (l ++ l') = andb (is_empty l) (is_empty l').\n  Proof.\n    induction l; simpl; eauto.\n  Qed.\n\n  Definition isAnswer (p : packet) := negb (is_empty (p!\"answers\")).\n\n  Definition isReferral (p : packet) :=\n    is_empty (p!\"answers\")\n             && (negb (is_empty (p!\"authority\")))\n             && (negb (is_empty (p!\"additional\"))).\n\n  Definition add_answers := List.fold_left add_answer.\n  Definition add_nses := List.fold_left add_ns.\n  Definition add_additionals := List.fold_left add_additional.\n\nEnd Packet.\n\nCoercion CNAME_Record2RRecord : CNAME_Record >-> resourceRecord.\nCoercion A_Record2RRecord : A_Record >-> resourceRecord.\nCoercion NS_Record2RRecord : NS_Record >-> resourceRecord.\nCoercion SOA_Record2RRecord : SOA_Record >-> resourceRecord.\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/SimpleDNSPacket.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891307678319, "lm_q2_score": 0.4843800842769843, "lm_q1q2_score": 0.28524616679112247}}
{"text": "Require Export SpecializedCommaCategory ProductCategory.\nRequire Import Common Notations.\n\nSet Implicit Arguments.\n\nGeneralizable All Variables.\n\nSet Asymmetric Patterns.\n\nSet Universe Polymorphism.\n\nLocal Open Scope category_scope.\n\nSection CommaCategory.\n  Context `(A : @SpecializedCategory objA).\n  Context `(B : @SpecializedCategory objB).\n  Context `(C : @SpecializedCategory objC).\n  Variable S : SpecializedFunctor A C.\n  Variable T : SpecializedFunctor B C.\n\n  Definition CommaCategoryProjection : SpecializedFunctor (S ↓ T) (A * B)\n    := Build_SpecializedFunctor (S ↓ T) (A * B)\n                                (@projT1 _ _)\n                                (fun _ _ m => proj1_sig m)\n                                (fun _ _ _ _ _ => eq_refl)\n                                (fun _ => eq_refl).\nEnd CommaCategory.\n\nSection SliceCategory.\n  Context `(A : @SpecializedCategory objA).\n\n  Local Arguments ComposeFunctors' / .\n\n  Definition ArrowCategoryProjection : SpecializedFunctor (ArrowSpecializedCategory A) A\n    := Eval simpl in ComposeFunctors' fst_Functor (CommaCategoryProjection _ (IdentityFunctor A)).\n\n  Definition SliceCategoryOverProjection (a : A) : SpecializedFunctor (A / a) A\n    := Eval simpl in ComposeFunctors' fst_Functor (CommaCategoryProjection (IdentityFunctor A) _).\n\n  Definition CosliceCategoryOverProjection (a : A) : SpecializedFunctor (a \\ A) A\n    := ComposeFunctors' snd_Functor (CommaCategoryProjection _ (IdentityFunctor A)).\n\n  Section Slice_Coslice.\n    Context `(C : @SpecializedCategory objC).\n    Variable a : C.\n    Variable S : SpecializedFunctor A C.\n\n    Section Slice.\n      Definition SliceCategoryProjection : SpecializedFunctor (S ↓ a) A\n        := Eval simpl in ComposeFunctors' fst_Functor (CommaCategoryProjection S (FunctorFromTerminal C a)).\n    End Slice.\n\n    Section Coslice.\n      Definition CosliceCategoryProjection : SpecializedFunctor (a ↓ S) A\n        := Eval simpl in ComposeFunctors' snd_Functor (CommaCategoryProjection (FunctorFromTerminal C a) S).\n      Check CosliceCategoryProjection.\n      Eval simpl in SpecializedFunctor (a ↓ S) A.\n    End Coslice.\n  End Slice_Coslice.\nEnd SliceCategory.\n", "meta": {"author": "CategoricalData", "repo": "catdb", "sha": "ce74dd70c52116a29f4589fd8d12c6439181254e", "save_path": "github-repos/coq/CategoricalData-catdb", "path": "github-repos/coq/CategoricalData-catdb/catdb-ce74dd70c52116a29f4589fd8d12c6439181254e/CommaCategoryProjection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.285220232519147}}
{"text": "From iris.prelude Require Export prelude.\nFrom iris.prelude Require Import options.\nSet Primitive Projections.\n\n(** This files defines (a shallow embedding of) the category of OFEs:\n    Complete ordered families of equivalences. This is a cartesian closed\n    category, and mathematically speaking, the entire development lives\n    in this category. However, we will generally prefer to work with raw\n    Coq functions plus some registered Proper instances for non-expansiveness.\n    This makes writing such functions much easier. It turns out that it many\n    cases, we do not even need non-expansiveness.\n*)\n\n\n(** The tactic [si_solver] solves goals that are solely concerned with\n    step-indices and their relations (i.e., [0], [S n], [n < m], and [n ≤ m]).\n    Currently, this tactic is just an alias for [lia]. However, in the future,\n    Iris will generalize over the type of step-indices, and this tactic will\n    be able to solve step-indexing goals also in this generalized setting.\n\n    The tactic can be used as part of [eauto] by using the hint database\n    [si_solver].\n*)\n\nLtac si_solver := lia.\n\nCreate HintDb si_solver.\nGlobal Hint Extern 1 => si_solver : si_solver.\n\n(** Unbundled version *)\nClass Dist A := dist : nat → relation A.\nGlobal Hint Mode Dist ! : typeclass_instances.\nGlobal Instance: Params (@dist) 3 := {}.\nNotation \"x ≡{ n }≡ y\" := (dist n x y)\n  (at level 70, n at next level, format \"x  ≡{ n }≡  y\").\nNotation \"x ≡{ n }@{ A }≡ y\" := (dist (A:=A) n x y)\n  (at level 70, n at next level, only parsing).\nNotation \"(≡{ n }≡)\" := (dist n) (only parsing).\nNotation \"(≡{ n }@{ A }≡)\" := (dist (A:=A) n) (only parsing).\nNotation \"( x ≡{ n }≡.)\" := (dist n x) (only parsing).\nNotation \"(.≡{ n }≡ y )\" := (λ x, x ≡{n}≡ y) (only parsing).\n\nGlobal Hint Extern 0 (_ ≡{_}≡ _) => reflexivity : core.\nGlobal Hint Extern 0 (_ ≡{_}≡ _) => symmetry; assumption : core.\nNotation NonExpansive f := (∀ n, Proper (dist n ==> dist n) f).\nNotation NonExpansive2 f := (∀ n, Proper (dist n ==> dist n ==> dist n) f).\nNotation NonExpansive3 f :=\n  (∀ n, Proper (dist n ==> dist n ==> dist n ==> dist n) f).\nNotation NonExpansive4 f :=\n  (∀ n, Proper (dist n ==> dist n ==> dist n ==> dist n ==> dist n) f).\n\nTactic Notation \"ofe_subst\" ident(x) :=\n  repeat match goal with\n  | _ => progress simplify_eq/=\n  | H:@dist ?A ?d ?n x _ |- _ => setoid_subst_aux (@dist A d n) x\n  | H:@dist ?A ?d ?n _ x |- _ => symmetry in H;setoid_subst_aux (@dist A d n) x\n  end.\nTactic Notation \"ofe_subst\" :=\n  repeat match goal with\n  | _ => progress simplify_eq/=\n  | H:@dist ?A ?d ?n ?x _ |- _ => setoid_subst_aux (@dist A d n) x\n  | H:@dist ?A ?d ?n _ ?x |- _ => symmetry in H;setoid_subst_aux (@dist A d n) x\n  end.\n\nRecord OfeMixin A `{Equiv A, Dist A} := {\n  mixin_equiv_dist (x y : A) : x ≡ y ↔ ∀ n, x ≡{n}≡ y;\n  mixin_dist_equivalence n : Equivalence (@dist A _ n);\n  mixin_dist_lt n m (x y : A) : x ≡{n}≡ y → m < n → x ≡{m}≡ y;\n}.\n\n(** Bundled version *)\nStructure ofe := Ofe {\n  ofe_car :> Type;\n  ofe_equiv : Equiv ofe_car;\n  ofe_dist : Dist ofe_car;\n  ofe_mixin : OfeMixin ofe_car\n}.\nGlobal Arguments Ofe _ {_ _} _.\nAdd Printing Constructor ofe.\n(* FIXME(Coq #6294) : we need the new unification algorithm here. *)\nGlobal Hint Extern 0 (Equiv _) => refine (ofe_equiv _); shelve : typeclass_instances.\nGlobal Hint Extern 0 (Dist _) => refine (ofe_dist _); shelve : typeclass_instances.\nGlobal Arguments ofe_car : simpl never.\nGlobal Arguments ofe_equiv : simpl never.\nGlobal Arguments ofe_dist : simpl never.\nGlobal Arguments ofe_mixin : simpl never.\n\n(** When declaring instances of subclasses of OFE (like CMRAs and unital CMRAs)\nwe need Coq to *infer* the canonical OFE instance of a given type and take the\nmixin out of it. This makes sure we do not use two different OFE instances in\ndifferent places (see for example the constructors [Cmra] and [Ucmra] in the\nfile [cmra.v].)\n\nIn order to infer the OFE instance, we use the definition [ofe_mixin_of'] which\nis inspired by the [clone] trick in ssreflect. It works as follows, when type\nchecking [@ofe_mixin_of' A ?Ac id] Coq faces a unification problem:\n\n  ofe_car ?Ac  ~  A\n\nwhich will resolve [?Ac] to the canonical OFE instance corresponding to [A]. The\ndefinition [@ofe_mixin_of' A ?Ac id] will then provide the corresponding mixin.\nNote that type checking of [ofe_mixin_of' A id] will fail when [A] does not have\na canonical OFE instance.\n\nThe notation [ofe_mixin_of A] that we define on top of [ofe_mixin_of' A id]\nhides the [id] and normalizes the mixin to head normal form. The latter is to\nensure that we do not end up with redundant canonical projections to the mixin,\ni.e. them all being of the shape [ofe_mixin_of' A id]. *)\nDefinition ofe_mixin_of' A {Ac : ofe} (f : Ac → A) : OfeMixin Ac := ofe_mixin Ac.\nNotation ofe_mixin_of A :=\n  ltac:(let H := eval hnf in (ofe_mixin_of' A id) in exact H) (only parsing).\n\n(** Lifting properties from the mixin *)\nSection ofe_mixin.\n  Context {A : ofe}.\n  Implicit Types x y : A.\n  Lemma equiv_dist x y : x ≡ y ↔ ∀ n, x ≡{n}≡ y.\n  Proof. apply (mixin_equiv_dist _ (ofe_mixin A)). Qed.\n  Global Instance dist_equivalence n : Equivalence (@dist A _ n).\n  Proof. apply (mixin_dist_equivalence _ (ofe_mixin A)). Qed.\n  Lemma dist_lt n m x y : x ≡{n}≡ y → m < n → x ≡{m}≡ y.\n  Proof. apply (mixin_dist_lt _ (ofe_mixin A)). Qed.\nEnd ofe_mixin.\n\nGlobal Hint Extern 1 (_ ≡{_}≡ _) => apply equiv_dist; assumption : core.\n\n(** Discrete OFEs and discrete OFE elements *)\nClass Discrete {A : ofe} (x : A) := discrete y : x ≡{0}≡ y → x ≡ y.\nGlobal Arguments discrete {_} _ {_} _ _.\nGlobal Hint Mode Discrete + ! : typeclass_instances.\nGlobal Instance: Params (@Discrete) 1 := {}.\n\nClass OfeDiscrete (A : ofe) := ofe_discrete_discrete (x : A) :> Discrete x.\nGlobal Hint Mode OfeDiscrete ! : typeclass_instances.\n\n(** OFEs with a completion *)\nRecord chain (A : ofe) := {\n  chain_car :> nat → A;\n  chain_cauchy n i : n ≤ i → chain_car i ≡{n}≡ chain_car n\n}.\nGlobal Arguments chain_car {_} _ _.\nGlobal Arguments chain_cauchy {_} _ _ _ _.\n\nProgram Definition chain_map {A B : ofe} (f : A → B)\n    `{!NonExpansive f} (c : chain A) : chain B :=\n  {| chain_car n := f (c n) |}.\nNext Obligation. by intros A B f Hf c n i ?; apply Hf, chain_cauchy. Qed.\n\nNotation Compl A := (chain A%type → A).\nClass Cofe (A : ofe) := {\n  compl : Compl A;\n  conv_compl n c : compl c ≡{n}≡ c n;\n}.\nGlobal Arguments compl : simpl never.\nGlobal Hint Mode Cofe ! : typeclass_instances.\n\nLemma compl_chain_map `{!Cofe A, !Cofe B} (f : A → B) c `(!NonExpansive f) :\n  compl (chain_map f c) ≡ f (compl c).\nProof. apply equiv_dist=>n. by rewrite !conv_compl. Qed.\n\nProgram Definition chain_const {A : ofe} (a : A) : chain A :=\n  {| chain_car n := a |}.\nNext Obligation. by intros A a n i _. Qed.\n\nLemma compl_chain_const {A : ofe} `{!Cofe A} (a : A) :\n  compl (chain_const a) ≡ a.\nProof. apply equiv_dist=>n. by rewrite conv_compl. Qed.\n\n(** General properties *)\nSection ofe.\n  Context {A : ofe}.\n  Implicit Types x y : A.\n  Global Instance ofe_equivalence : Equivalence ((≡) : relation A).\n  Proof.\n    split.\n    - by intros x; rewrite equiv_dist.\n    - by intros x y; rewrite !equiv_dist.\n    - by intros x y z; rewrite !equiv_dist; intros; trans y.\n  Qed.\n  Global Instance dist_ne n : Proper (dist n ==> dist n ==> iff) (@dist A _ n).\n  Proof.\n    intros x1 x2 ? y1 y2 ?; split; intros.\n    - by trans x1; [|trans y1].\n    - by trans x2; [|trans y2].\n  Qed.\n  Global Instance dist_proper n : Proper ((≡) ==> (≡) ==> iff) (@dist A _ n).\n  Proof.\n    by move => x1 x2 /equiv_dist Hx y1 y2 /equiv_dist Hy; rewrite (Hx n) (Hy n).\n  Qed.\n  Global Instance dist_proper_2 n x : Proper ((≡) ==> iff) (dist n x).\n  Proof. by apply dist_proper. Qed.\n  Global Instance Discrete_proper : Proper ((≡) ==> iff) (@Discrete A).\n  Proof. intros x y Hxy. rewrite /Discrete. by setoid_rewrite Hxy. Qed.\n\n  Lemma dist_le n n' x y : x ≡{n}≡ y → n' ≤ n → x ≡{n'}≡ y.\n  Proof. intros ? [Hm | ->]%Nat.lt_eq_cases; [by eapply dist_lt | auto]. Qed.\n  Lemma dist_le' n n' x y : n' ≤ n → x ≡{n}≡ y → x ≡{n'}≡ y.\n  Proof. eauto using dist_le. Qed.\n  Lemma dist_S n x y : x ≡{S n}≡ y → x ≡{n}≡ y.\n  Proof. eauto using dist_le. Qed.\n  (** [ne_proper] and [ne_proper_2] are not instances to improve efficiency of\n  type class search during setoid rewriting.\n  Local Instances of [NonExpansive{,2}] are hence accompanied by instances of\n  [Proper] built using these lemmas. *)\n  Lemma ne_proper {B : ofe} (f : A → B) `{!NonExpansive f} :\n    Proper ((≡) ==> (≡)) f.\n  Proof. by intros x1 x2; rewrite !equiv_dist; intros Hx n; rewrite (Hx n). Qed.\n  Lemma ne_proper_2 {B C : ofe} (f : A → B → C) `{!NonExpansive2 f} :\n    Proper ((≡) ==> (≡) ==> (≡)) f.\n  Proof.\n     unfold Proper, respectful; setoid_rewrite equiv_dist.\n     by intros x1 x2 Hx y1 y2 Hy n; rewrite (Hx n) (Hy n).\n  Qed.\n\n  Lemma conv_compl' `{!Cofe A} n (c : chain A) : compl c ≡{n}≡ c (S n).\n  Proof.\n    transitivity (c n); first by apply conv_compl. symmetry.\n    apply chain_cauchy. lia.\n  Qed.\n\n  Lemma discrete_iff n (x : A) `{!Discrete x} y : x ≡ y ↔ x ≡{n}≡ y.\n  Proof.\n    split; intros; auto. apply (discrete _), dist_le with n; auto with lia.\n  Qed.\n  Lemma discrete_iff_0 n (x : A) `{!Discrete x} y : x ≡{0}≡ y ↔ x ≡{n}≡ y.\n  Proof. by rewrite -!discrete_iff. Qed.\nEnd ofe.\n\n(** Contractive functions *)\n(** Defined as a record to avoid eager unfolding. *)\nRecord dist_later `{!Dist A} n (x y : A) : Prop :=\n  { dist_later_lt : ∀ m, m < n → x ≡{m}≡ y }.\n\nSection dist_later.\n  Context {A : ofe}.\n  Implicit Types x y : A.\n\n  Global Instance dist_later_equivalence n : Equivalence (@dist_later A _ n).\n  Proof.\n    split.\n    - intros ?; by split.\n    - intros ?? [Hlater]; split; intros ??; by rewrite Hlater.\n    - intros ??? [Hlater1] [Hlater2]; split; intros ??; by rewrite Hlater1 ?Hlater2.\n  Qed.\n\n  Lemma dist_dist_later n x y : dist n x y → dist_later n x y.\n  Proof. intros. split; eauto using dist_le. Qed.\n\n  Lemma dist_later_dist_lt n m x y : m < n → dist_later n x y → dist m x y.\n  Proof. intros ? []; eauto. Qed.\n\n  Lemma dist_later_0 x y : dist_later 0 x y.\n  Proof. split; intros ? []%Nat.nlt_0_r. Qed.\n\n  Lemma dist_later_S n x y: x ≡{n}≡ y ↔ dist_later (S n) x y.\n  Proof.\n    split.\n    - intros Hn; split; intros m Hm. eapply dist_le; first done. lia.\n    - intros Hdist. apply Hdist. lia.\n  Qed.\nEnd dist_later.\n\n\n(* We don't actually need this lemma (as our tactics deal with this through\n   other means), but technically speaking, this is the reason why\n   pre-composing a non-expansive function to a contractive function\n   preserves contractivity. *)\nLemma ne_dist_later {A B : ofe} (f : A → B) :\n  NonExpansive f → ∀ n, Proper (dist_later n ==> dist_later n) f.\nProof. intros Hf ??? Hlater; split; intros ??; by eapply Hf, Hlater. Qed.\n\n(** We define [dist_later_fin], an equivalent (see dist_later_fin_iff) version of\n   [dist_later] that uses a [match] on the step-index instead of the\n   quantification over smaller step-indicies. The definition of [dist_later_fin]\n   matches how [dist_later] used to be defined (i.e., with a [match] on the\n   step-index), so [dist_later_fin] simplifies adapting existing Iris\n   developments that used to rely on the reduction behavior of [dist_later].\n\n   The \"fin\" indicates that when, in the future, the step-index is abstracted away,\n   this equivalence will only hold for finite step-indices (as in, ordinals without\n   \"limit\" steps such as natural numbers).\n*)\nDefinition dist_later_fin {A : ofe} (n : nat) (x y : A) :=\n  match n with 0 => True | S n => x ≡{n}≡ y end.\n\nLemma dist_later_fin_iff {A : ofe} (n : nat) (x y : A):\n  dist_later n x y ↔ dist_later_fin n x y.\nProof.\n  destruct n; unfold dist_later_fin; first by split; eauto using dist_later_0.\n  by rewrite dist_later_S.\nQed.\n\nNotation Contractive f := (∀ n, Proper (dist_later n ==> dist n) f).\n\nGlobal Instance const_contractive {A B : ofe} (x : A) : Contractive (@const A B x).\nProof. by intros n y1 y2. Qed.\n\nSection contractive.\n  Local Set Default Proof Using \"Type*\".\n  Context {A B : ofe} (f : A → B) `{!Contractive f}.\n  Implicit Types x y : A.\n\n  Lemma contractive_0 x y : f x ≡{0}≡ f y.\n  Proof. by apply (_ : Contractive f), dist_later_0. Qed.\n  Lemma contractive_dist_later_dist n x y : dist_later n x y → f x ≡{n}≡ f y.\n  Proof. intros. by apply (_ : Contractive f). Qed.\n  Lemma contractive_S n x y : x ≡{n}≡ y → f x ≡{S n}≡ f y.\n  Proof. intros. by apply contractive_dist_later_dist, dist_later_S. Qed.\n\n  Global Instance contractive_ne : NonExpansive f | 100.\n  Proof. intros n x y ?. eapply contractive_dist_later_dist. by apply dist_dist_later. Qed.\n  Global Instance contractive_proper : Proper ((≡) ==> (≡)) f | 100.\n  Proof. apply (ne_proper _). Qed.\nEnd contractive.\n\nLemma dist_pointwise_lt {A} {B: ofe} n m (f g: A → B):\n  m < n →\n  pointwise_relation A (dist_later n) f g →\n  pointwise_relation A (dist m) f g.\nProof. intros Hlt Hp a. by apply Hp. Qed.\n\n(** The tactic [f_contractive] can be used to prove contractiveness or\nnon-expansiveness of a function [f]. Inside of the proof of\ncontractiveness/non-expansiveness, if the current goal is\n  [g x1 ... xn ≡{i}≡ g y1 ... yn]\nfor a contractive function [g] (that is used inside of the body of [f]),\nthen the tactic will try to find a suitable [Contractive] instance for [g]\nand apply it. Currently, the tactic only supports one (i.e., [n = 1]) and\ntwo (i.e., [n = 2]) arguments. As a result of applying the [Contractive]\ninstance for [g], one of the goals will be [dist_later i xi yi] and the tactic\nwill try to simplify or solve the goal. By simplify we mean that it will\nturn hypotheses [dist_later] into [dist].\n\nFor backwards compatibility, we also define the tactic [f_contractive_fin] that\nworks with an earlier definition of [dist_later] now called [dist_later_fin]. The\nnew version of [f_contractive] is future proof with respect to generalizing the\ntype of step-indices, while the old tactic relies crucially on the step-indices\nbeing [nat] and the reduction behavior of [dist_later]. The tactic [f_contractive_fin]\nsimplifies backwards compatibility of existing Iris developments (e.g., RustBelt),\nthat define custom notions of [dist] and [dist_later] but should be avoided if\npossible.\n\nThe tactics [f_contractive] and [f_contractive_fin] are implemented using\n\n1. [f_contractive_prepare] which looks up a [Contractive] looks at which\n   function is being applied on both sides of a [dist], looks up the\n   [Contractive] instance (or the equivalent for two arguments) and applies it.\n2. [dist_later_intro] and [dist_later_fin_intro] which introduces the resulting\n   goals with [dist_later n x y]/[dist_later_fin n x y]. The tactic\n   [dist_later_intro] works with the normal definition of [dist_later] and is\n   future compatible with generalizing the step-index beyond natural numbers.\n   The tactic [dist_later_fin_intro] is a special case which only works for\n   natural numbers as step-indicies. It changes [dist_later] to [dist_later_fin],\n   which only makes sense on natural numbers. We keep [dist_later_fin_intro]\n   around for backwards compatibility.\n*)\nLtac f_contractive_prepare :=\n  match goal with\n  | |- ?f _ ≡{_}≡ ?f _ => simple apply (_ : Proper (dist_later _ ==> dist _) f)\n  | |- ?f _ _ ≡{_}≡ ?f _ _ => simple apply (_ : Proper (dist_later _ ==> _ ==> dist _) f)\n  | |- ?f _ _ ≡{_}≡ ?f _ _ => simple apply (_ : Proper (_ ==> dist_later _ ==> dist _) f)\n  end.\n\n(** For the goal [dist_later n x y], the tactic [dist_later_intro as m Hm]\nintroduces a smaller step-index [Hm : m < n] and tries to lower assumptions in\nthe context to [m] where possible. The arguments [m] and [Hm] can be omitted,\nin which case a fresh identifier is used. *)\nTactic Notation \"dist_later_intro\" \"as\" ident(idxName) ident(ltName) :=\n  match goal with\n  | |- dist_later ?n ?x ?y =>\n      constructor; intros idxName ltName;\n      repeat match goal with\n      | H: dist_later n _ _ |- _ => destruct H as [H]; specialize (H idxName ltName) as H\n      | H: pointwise_relation _ (dist_later n) _ _ |- _ =>\n         apply (dist_pointwise_lt _ idxName _ _ ltName) in H\n      end\n  end.\nTactic Notation \"dist_later_intro\" :=\n  let m := fresh \"m\" in\n  let Hlt := fresh \"Hlt\" in\n  dist_later_intro as m Hlt.\n\n(** For the goal [dist_later n x y], the tactic [dist_later_fin_intro] changes\nthe goal to [dist_later_fin] and takes care of the case where [n=0], such\nthat we are only left with the case where [n = S n'] for some [n']. Changing\n[dist_later] to [dist_later_fin] enables reduction and thus works better with\ncustom versions of [dist] as used e.g. by LambdaRust. *)\nLtac dist_later_fin_intro :=\n  match goal with\n  | |- @dist_later ?A _ ?n ?x ?y =>\n      apply dist_later_fin_iff;\n      destruct n as [|n]; [exact I|change (@dist A _ n x y)]\n  end.\n\n(** We combine [f_contractive_prepare] and [dist_later_intro] into the\n[f_contractive] tactic.\n\nFor all the goals not solved by [dist_later_intro] (i.e., the ones that are\nnot [dist_later n x y]), we try reflexivity. Since reflexivity can be very\nexpensive when unification fails, we use [fast_reflexivity]. *)\n\nTactic Notation \"f_contractive\" \"as\" ident(idxName) ident(ltName) :=\n  f_contractive_prepare;\n  try dist_later_intro as idxName ltName;\n  try fast_reflexivity.\n\nTactic Notation \"f_contractive\" :=\n  let m := fresh \"m\" in\n  let Hlt := fresh \"Hlt\" in\n  f_contractive as m Hlt.\n\nTactic Notation \"f_contractive_fin\" :=\n  f_contractive_prepare;\n  try dist_later_fin_intro;\n  try fast_reflexivity.\n\nLtac solve_contractive :=\n  solve_proper_core ltac:(fun _ => first [f_contractive | f_equiv]).\n\n(** Limit preserving predicates *)\nClass LimitPreserving `{!Cofe A} (P : A → Prop) : Prop :=\n  limit_preserving (c : chain A) : (∀ n, P (c n)) → P (compl c).\nGlobal Hint Mode LimitPreserving + + ! : typeclass_instances.\n\nSection limit_preserving.\n  Context {A : ofe} `{!Cofe A}.\n  (* These are not instances as they will never fire automatically...\n     but they can still be helpful in proving things to be limit preserving. *)\n\n  Lemma limit_preserving_ext (P Q : A → Prop) :\n    (∀ x, P x ↔ Q x) → LimitPreserving P → LimitPreserving Q.\n  Proof. intros HP Hlimit c ?. apply HP, Hlimit=> n; by apply HP. Qed.\n\n  Global Instance limit_preserving_const (P : Prop) : LimitPreserving (λ _ : A, P).\n  Proof. intros c HP. apply (HP 0). Qed.\n\n  Lemma limit_preserving_discrete (P : A → Prop) :\n    Proper (dist 0 ==> impl) P → LimitPreserving P.\n  Proof. intros PH c Hc. by rewrite (conv_compl 0). Qed.\n\n  Lemma limit_preserving_and (P1 P2 : A → Prop) :\n    LimitPreserving P1 →\n    LimitPreserving P2 →\n    LimitPreserving (λ x, P1 x ∧ P2 x).\n  Proof.\n    intros Hlim1 Hlim2 c Hc.\n    split.\n    - apply Hlim1, Hc.\n    - apply Hlim2, Hc.\n  Qed.\n\n  Lemma limit_preserving_impl (P1 P2 : A → Prop) :\n    Proper (dist 0 ==> impl) P1 →\n    LimitPreserving P2 →\n    LimitPreserving (λ x, P1 x → P2 x).\n  Proof.\n    intros Hlim1 Hlim2 c Hc HP1. apply Hlim2=> n; apply Hc.\n    eapply Hlim1, HP1. apply dist_le with n; last lia. apply (conv_compl n).\n  Qed.\n\n  (** This is strictly weaker than the [_impl] variant, but sometimes automation\n      is better at proving [Proper] for [iff] than for [impl]. *)\n  Lemma limit_preserving_impl' (P1 P2 : A → Prop) :\n    Proper (dist 0 ==> iff) P1 →\n    LimitPreserving P2 →\n    LimitPreserving (λ x, P1 x → P2 x).\n  Proof.\n    intros HP1. apply limit_preserving_impl. intros ???.\n    apply iff_impl_subrelation. eapply HP1. done.\n  Qed.\n\n  Lemma limit_preserving_forall {B} (P : B → A → Prop) :\n    (∀ y, LimitPreserving (P y)) →\n    LimitPreserving (λ x, ∀ y, P y x).\n  Proof. intros Hlim c Hc y. by apply Hlim. Qed.\n\n  Lemma limit_preserving_equiv `{!Cofe B} (f g : A → B) :\n    NonExpansive f → NonExpansive g → LimitPreserving (λ x, f x ≡ g x).\n  Proof.\n    intros Hf Hg c Hc. apply equiv_dist=> n.\n    by rewrite -!compl_chain_map !conv_compl /= Hc.\n  Qed.\nEnd limit_preserving.\n\n(** Fixpoint *)\nProgram Definition fixpoint_chain {A : ofe} `{Inhabited A} (f : A → A)\n  `{!Contractive f} : chain A := {| chain_car i := Nat.iter (S i) f inhabitant |}.\nNext Obligation.\n  intros A ? f ? n.\n  induction n as [|n IH]=> -[|i] //= ?; try lia.\n  - apply (contractive_0 f).\n  - apply (contractive_S f), IH; auto with lia.\nQed.\n\nLocal Program Definition fixpoint_def `{Cofe A, Inhabited A} (f : A → A)\n  `{!Contractive f} : A := compl (fixpoint_chain f).\nLocal Definition fixpoint_aux : seal (@fixpoint_def). Proof. by eexists. Qed.\nDefinition fixpoint := fixpoint_aux.(unseal).\nGlobal Arguments fixpoint {A _ _} f {_}.\nLocal Definition fixpoint_unseal :\n  @fixpoint = @fixpoint_def := fixpoint_aux.(seal_eq).\n\nSection fixpoint.\n  Context `{!Cofe A, !Inhabited A} (f : A → A) `{!Contractive f}.\n\n  (** This lemma does not work well with [rewrite]; we usually define a specific\n  unfolding lemma for each fixpoint and then [apply fixpoint_unfold] in the\n  proof of that unfolding lemma. *)\n  Lemma fixpoint_unfold : fixpoint f ≡ f (fixpoint f).\n  Proof.\n    apply equiv_dist=>n.\n    rewrite fixpoint_unseal /fixpoint_def (conv_compl n (fixpoint_chain f)) //.\n    induction n as [|n IH]; simpl; eauto using contractive_0, contractive_S.\n  Qed.\n\n  Lemma fixpoint_unique (x : A) : x ≡ f x → x ≡ fixpoint f.\n  Proof.\n    rewrite !equiv_dist=> Hx n. induction n as [|n IH]; simpl in *.\n    - rewrite Hx fixpoint_unfold; eauto using contractive_0.\n    - rewrite Hx fixpoint_unfold. eauto using contractive_S.\n  Qed.\n\n  Lemma fixpoint_ne (g : A → A) `{!Contractive g} n :\n    (∀ z, f z ≡{n}≡ g z) → fixpoint f ≡{n}≡ fixpoint g.\n  Proof.\n    intros Hfg. rewrite fixpoint_unseal /fixpoint_def\n      (conv_compl n (fixpoint_chain f)) (conv_compl n (fixpoint_chain g)) /=.\n    induction n as [|n IH]; simpl in *; [by rewrite !Hfg|].\n    rewrite Hfg; apply contractive_S, IH; eauto using dist_le with si_solver.\n  Qed.\n  Lemma fixpoint_proper (g : A → A) `{!Contractive g} :\n    (∀ x, f x ≡ g x) → fixpoint f ≡ fixpoint g.\n  Proof. setoid_rewrite equiv_dist; naive_solver eauto using fixpoint_ne. Qed.\n\n  Lemma fixpoint_ind (P : A → Prop) :\n    Proper ((≡) ==> impl) P →\n    (∃ x, P x) → (∀ x, P x → P (f x)) →\n    LimitPreserving P →\n    P (fixpoint f).\n  Proof.\n    intros ? [x Hx] Hincr Hlim. set (chcar i := Nat.iter (S i) f x).\n    assert (Hcauch : ∀ n i : nat, n ≤ i → chcar i ≡{n}≡ chcar n).\n    { intros n. rewrite /chcar. induction n as [|n IH]=> -[|i] //=;\n        eauto using contractive_0, contractive_S with si_solver. }\n    set (fp2 := compl {| chain_cauchy := Hcauch |}).\n    assert (f fp2 ≡ fp2).\n    { apply equiv_dist=>n. rewrite /fp2 (conv_compl n) /= /chcar.\n      induction n as [|n IH]; simpl; eauto using contractive_0, contractive_S. }\n    rewrite -(fixpoint_unique fp2) //.\n    apply Hlim=> n /=. by apply Nat.iter_ind.\n  Qed.\nEnd fixpoint.\n\n\n(** Fixpoint of f when f^k is contractive. **)\nDefinition fixpointK {A : ofe} `{!Cofe A, !Inhabited A} k (f : A → A)\n  `{!Contractive (Nat.iter k f)} := fixpoint (Nat.iter k f).\n\nSection fixpointK.\n  Local Set Default Proof Using \"Type*\".\n  Context {A : ofe} `{!Cofe A, !Inhabited A} (f : A → A) (k : nat).\n  Context {f_contractive : Contractive (Nat.iter k f)} {f_ne : NonExpansive f}.\n  (* Note than f_ne is crucial here:  there are functions f such that f^2 is contractive,\n     but f is not non-expansive.\n     Consider for example f: SPred → SPred (where SPred is \"downclosed sets of natural numbers\").\n     Define f (using informative excluded middle) as follows:\n     f(N) = N  (where N is the set of all natural numbers)\n     f({0, ..., n}) = {0, ... n-1}  if n is even (so n-1 is at least -1, in which case we return the empty set)\n     f({0, ..., n}) = {0, ..., n+2} if n is odd\n     In other words, if we consider elements of SPred as ordinals, then we decreaste odd finite\n     ordinals by 1 and increase even finite ordinals by 2.\n     f is not non-expansive:  Consider f({0}) = ∅ and f({0,1}) = f({0,1,2,3}).\n     The arguments are clearly 0-equal, but the results are not.\n\n     Now consider g := f^2. We have\n     g(N) = N\n     g({0, ..., n}) = {0, ... n+1}  if n is even\n     g({0, ..., n}) = {0, ..., n+4} if n is odd\n     g is contractive.  All outputs contain 0, so they are all 0-equal.\n     Now consider two n-equal inputs. We have to show that the outputs are n+1-equal.\n     Either they both do not contain n in which case they have to be fully equal and\n     hence so are the results.  Or else they both contain n, so the results will\n     both contain n+1, so the results are n+1-equal.\n   *)\n\n  Let f_proper : Proper ((≡) ==> (≡)) f := ne_proper f.\n  Local Existing Instance f_proper.\n\n  Lemma fixpointK_unfold : fixpointK k f ≡ f (fixpointK k f).\n  Proof.\n    symmetry. rewrite /fixpointK. apply fixpoint_unique.\n    by rewrite -Nat.iter_succ_r Nat.iter_succ -fixpoint_unfold.\n  Qed.\n\n  Lemma fixpointK_unique (x : A) : x ≡ f x → x ≡ fixpointK k f.\n  Proof.\n    intros Hf. apply fixpoint_unique. clear f_contractive.\n    induction k as [|k' IH]=> //=. by rewrite -IH.\n  Qed.\n\n  Section fixpointK_ne.\n    Context (g : A → A) `{g_contractive : !Contractive (Nat.iter k g)}.\n    Context {g_ne : NonExpansive g}.\n\n    Lemma fixpointK_ne n : (∀ z, f z ≡{n}≡ g z) → fixpointK k f ≡{n}≡ fixpointK k g.\n    Proof.\n      rewrite /fixpointK=> Hfg /=. apply fixpoint_ne=> z.\n      clear f_contractive g_contractive.\n      induction k as [|k' IH]=> //=. by rewrite IH Hfg.\n    Qed.\n\n    Lemma fixpointK_proper : (∀ z, f z ≡ g z) → fixpointK k f ≡ fixpointK k g.\n    Proof. setoid_rewrite equiv_dist; naive_solver eauto using fixpointK_ne. Qed.\n  End fixpointK_ne.\n\n  Lemma fixpointK_ind (P : A → Prop) :\n    Proper ((≡) ==> impl) P →\n    (∃ x, P x) → (∀ x, P x → P (f x)) →\n    LimitPreserving P →\n    P (fixpointK k f).\n  Proof.\n    intros. rewrite /fixpointK. apply fixpoint_ind; eauto.\n    intros; apply Nat.iter_ind; auto.\n  Qed.\nEnd fixpointK.\n\n(** Mutual fixpoints *)\nSection fixpointAB.\n  Context {A B : ofe} `{!Cofe A, !Cofe B, !Inhabited A, !Inhabited B}.\n  Context (fA : A → B → A).\n  Context (fB : A → B → B).\n  Context {fA_contractive : ∀ n, Proper (dist_later n ==> dist n ==> dist n) fA}.\n  Context {fB_contractive : ∀ n, Proper (dist_later n ==> dist_later n ==> dist n) fB}.\n\n  Local Definition fixpoint_AB (x : A) : B := fixpoint (fB x).\n  Local Instance fixpoint_AB_contractive : Contractive fixpoint_AB.\n  Proof.\n    intros n x x' Hx; rewrite /fixpoint_AB.\n    apply fixpoint_ne=> y. by f_contractive.\n  Qed.\n\n  Local Definition fixpoint_AA (x : A) : A := fA x (fixpoint_AB x).\n  Local Instance fixpoint_AA_contractive : Contractive fixpoint_AA.\n  Proof using fA_contractive. solve_contractive. Qed.\n\n  Definition fixpoint_A : A := fixpoint fixpoint_AA.\n  Definition fixpoint_B : B := fixpoint_AB fixpoint_A.\n\n  Lemma fixpoint_A_unfold : fA fixpoint_A fixpoint_B ≡ fixpoint_A.\n  Proof. by rewrite {2}/fixpoint_A (fixpoint_unfold _). Qed.\n  Lemma fixpoint_B_unfold : fB fixpoint_A fixpoint_B ≡ fixpoint_B.\n  Proof. by rewrite {2}/fixpoint_B /fixpoint_AB (fixpoint_unfold _). Qed.\n\n  Local Instance: Proper ((≡) ==> (≡) ==> (≡)) fA.\n  Proof using fA_contractive.\n    apply ne_proper_2=> n x x' ? y y' ?. f_contractive;\n      eauto using dist_le with si_solver.\n  Qed.\n  Local Instance: Proper ((≡) ==> (≡) ==> (≡)) fB.\n  Proof using fB_contractive.\n    apply ne_proper_2=> n x x' ? y y' ?. f_contractive;\n      eauto using dist_le with si_solver.\n  Qed.\n\n  Lemma fixpoint_A_unique p q : fA p q ≡ p → fB p q ≡ q → p ≡ fixpoint_A.\n  Proof.\n    intros HfA HfB. rewrite -HfA. apply fixpoint_unique. rewrite /fixpoint_AA.\n    f_equiv=> //. apply fixpoint_unique. by rewrite HfA HfB.\n  Qed.\n  Lemma fixpoint_B_unique p q : fA p q ≡ p → fB p q ≡ q → q ≡ fixpoint_B.\n  Proof. intros. apply fixpoint_unique. by rewrite -fixpoint_A_unique. Qed.\nEnd fixpointAB.\n\nSection fixpointAB_ne.\n  Context {A B : ofe} `{!Cofe A, !Cofe B, !Inhabited A, !Inhabited B}.\n  Context (fA fA' : A → B → A).\n  Context (fB fB' : A → B → B).\n  Context `{∀ n, Proper (dist_later n ==> dist n ==> dist n) fA}.\n  Context `{∀ n, Proper (dist_later n ==> dist n ==> dist n) fA'}.\n  Context `{∀ n, Proper (dist_later n ==> dist_later n ==> dist n) fB}.\n  Context `{∀ n, Proper (dist_later n ==> dist_later n ==> dist n) fB'}.\n\n  Lemma fixpoint_A_ne n :\n    (∀ x y, fA x y ≡{n}≡ fA' x y) → (∀ x y, fB x y ≡{n}≡ fB' x y) →\n    fixpoint_A fA fB ≡{n}≡ fixpoint_A fA' fB'.\n  Proof.\n    intros HfA HfB. apply fixpoint_ne=> z.\n    rewrite /fixpoint_AA /fixpoint_AB HfA. f_equiv. by apply fixpoint_ne.\n  Qed.\n  Lemma fixpoint_B_ne n :\n    (∀ x y, fA x y ≡{n}≡ fA' x y) → (∀ x y, fB x y ≡{n}≡ fB' x y) →\n    fixpoint_B fA fB ≡{n}≡ fixpoint_B fA' fB'.\n  Proof.\n    intros HfA HfB. apply fixpoint_ne=> z. rewrite HfB. f_contractive.\n    apply fixpoint_A_ne; eauto using dist_le with si_solver.\n  Qed.\n\n  Lemma fixpoint_A_proper :\n    (∀ x y, fA x y ≡ fA' x y) → (∀ x y, fB x y ≡ fB' x y) →\n    fixpoint_A fA fB ≡ fixpoint_A fA' fB'.\n  Proof. setoid_rewrite equiv_dist; naive_solver eauto using fixpoint_A_ne. Qed.\n  Lemma fixpoint_B_proper :\n    (∀ x y, fA x y ≡ fA' x y) → (∀ x y, fB x y ≡ fB' x y) →\n    fixpoint_B fA fB ≡ fixpoint_B fA' fB'.\n  Proof. setoid_rewrite equiv_dist; naive_solver eauto using fixpoint_B_ne. Qed.\nEnd fixpointAB_ne.\n\n(** Non-expansive function space *)\nRecord ofe_mor (A B : ofe) : Type := OfeMor {\n  ofe_mor_car :> A → B;\n  ofe_mor_ne : NonExpansive ofe_mor_car\n}.\nGlobal Arguments OfeMor {_ _} _ {_}.\nAdd Printing Constructor ofe_mor.\nGlobal Existing Instance ofe_mor_ne.\n\nNotation \"'λne' x .. y , t\" :=\n  (@OfeMor _ _ (λ x, .. (@OfeMor _ _ (λ y, t) _) ..) _)\n  (at level 200, x binder, y binder, right associativity).\n\nSection ofe_mor.\n  Context {A B : ofe}.\n  Global Instance ofe_mor_proper (f : ofe_mor A B) : Proper ((≡) ==> (≡)) f.\n  Proof. apply ne_proper, ofe_mor_ne. Qed.\n  Local Instance ofe_mor_equiv : Equiv (ofe_mor A B) := λ f g, ∀ x, f x ≡ g x.\n  Local Instance ofe_mor_dist : Dist (ofe_mor A B) := λ n f g, ∀ x, f x ≡{n}≡ g x.\n  Definition ofe_mor_ofe_mixin : OfeMixin (ofe_mor A B).\n  Proof.\n    split.\n    - intros f g; split; [intros Hfg n k; apply equiv_dist, Hfg|].\n      intros Hfg k; apply equiv_dist=> n; apply Hfg.\n    - intros n; split.\n      + by intros f x.\n      + by intros f g ? x.\n      + by intros f g h ?? x; trans (g x).\n    - intros n m f g ? x ?; eauto using dist_le with si_solver.\n  Qed.\n  Canonical Structure ofe_morO := Ofe (ofe_mor A B) ofe_mor_ofe_mixin.\n\n  Program Definition ofe_mor_chain (c : chain ofe_morO)\n    (x : A) : chain B := {| chain_car n := c n x |}.\n  Next Obligation. intros c x n i ?. by apply (chain_cauchy c). Qed.\n  Program Definition ofe_mor_compl `{!Cofe B} : Compl ofe_morO := λ c,\n    {| ofe_mor_car x := compl (ofe_mor_chain c x) |}.\n  Next Obligation.\n    intros ? c n x y Hx. by rewrite (conv_compl n (ofe_mor_chain c x))\n      (conv_compl n (ofe_mor_chain c y)) /= Hx.\n  Qed.\n  Global Program Instance ofe_mor_cofe `{!Cofe B} : Cofe ofe_morO :=\n    {| compl := ofe_mor_compl |}.\n  Next Obligation.\n    intros ? n c x; simpl.\n    by rewrite (conv_compl n (ofe_mor_chain c x)) /=.\n  Qed.\n\n  Global Instance ofe_mor_car_ne :\n    NonExpansive2 (@ofe_mor_car A B).\n  Proof. intros n f g Hfg x y Hx; rewrite Hx; apply Hfg. Qed.\n  Global Instance ofe_mor_car_proper :\n    Proper ((≡) ==> (≡) ==> (≡)) (@ofe_mor_car A B) := ne_proper_2 _.\n  Lemma ofe_mor_ext (f g : ofe_mor A B) : f ≡ g ↔ ∀ x, f x ≡ g x.\n  Proof. done. Qed.\nEnd ofe_mor.\n\nGlobal Arguments ofe_morO : clear implicits.\nNotation \"A -n> B\" :=\n  (ofe_morO A B) (at level 99, B at level 200, right associativity).\nGlobal Instance ofe_mor_inhabited {A B : ofe} `{Inhabited B} :\n  Inhabited (A -n> B) := populate (λne _, inhabitant).\n\n(** Identity and composition and constant function *)\nDefinition cid {A} : A -n> A := OfeMor id.\nGlobal Instance: Params (@cid) 1 := {}.\nDefinition cconst {A B : ofe} (x : B) : A -n> B := OfeMor (const x).\nGlobal Instance: Params (@cconst) 2 := {}.\n\nDefinition ccompose {A B C}\n  (f : B -n> C) (g : A -n> B) : A -n> C := OfeMor (f ∘ g).\nGlobal Instance: Params (@ccompose) 3 := {}.\nInfix \"◎\" := ccompose (at level 40, left associativity).\nGlobal Instance ccompose_ne {A B C} :\n  NonExpansive2 (@ccompose A B C).\nProof. intros n ?? Hf g1 g2 Hg x. rewrite /= (Hg x) (Hf (g2 x)) //. Qed.\nGlobal Instance ccompose_proper {A B C} :\n  Proper ((≡) ==> (≡) ==> (≡)) (@ccompose A B C).\nProof. apply ne_proper_2; apply _. Qed.\n\n(* Function space maps *)\nDefinition ofe_mor_map {A A' B B'} (f : A' -n> A) (g : B -n> B')\n  (h : A -n> B) : A' -n> B' := g ◎ h ◎ f.\nGlobal Instance ofe_mor_map_ne {A A' B B'} :\n  NonExpansive3 (@ofe_mor_map A A' B B').\nProof. intros n ??? ??? ???. by repeat apply ccompose_ne. Qed.\n\nDefinition ofe_morO_map {A A' B B'} (f : A' -n> A) (g : B -n> B') :\n  (A -n> B) -n> (A' -n>  B') := OfeMor (ofe_mor_map f g).\nGlobal Instance ofe_morO_map_ne {A A' B B'} :\n  NonExpansive2 (@ofe_morO_map A A' B B').\nProof.\n  intros n f f' Hf g g' Hg ?. rewrite /= /ofe_mor_map.\n  by repeat apply ccompose_ne.\nQed.\n\n(** * Unit type *)\nSection unit.\n  Local Instance unit_dist : Dist unit := λ _ _ _, True.\n  Definition unit_ofe_mixin : OfeMixin unit.\n  Proof. by repeat split; try exists 0. Qed.\n  Canonical Structure unitO : ofe := Ofe unit unit_ofe_mixin.\n\n  Global Program Instance unit_cofe : Cofe unitO := { compl x := () }.\n  Next Obligation. by repeat split; try exists 0. Qed.\n\n  Global Instance unit_ofe_discrete : OfeDiscrete unitO.\n  Proof. done. Qed.\nEnd unit.\n\n(** * Empty type *)\nSection empty.\n  Local Instance Empty_set_dist : Dist Empty_set := λ _ _ _, True.\n  Definition Empty_set_ofe_mixin : OfeMixin Empty_set.\n  Proof. by repeat split; try exists 0. Qed.\n  Canonical Structure Empty_setO : ofe := Ofe Empty_set Empty_set_ofe_mixin.\n\n  Global Program Instance Empty_set_cofe : Cofe Empty_setO := { compl x := x 0 }.\n  Next Obligation. by repeat split; try exists 0. Qed.\n\n  Global Instance Empty_set_ofe_discrete : OfeDiscrete Empty_setO.\n  Proof. done. Qed.\nEnd empty.\n\n(** * Product type *)\nSection product.\n  Context {A B : ofe}.\n\n  Local Instance prod_dist : Dist (A * B) := λ n, prod_relation (dist n) (dist n).\n\n  Definition prod_ofe_mixin : OfeMixin (A * B).\n  Proof.\n    split.\n    - intros x y; unfold dist, prod_dist, equiv, prod_equiv, prod_relation.\n      rewrite !equiv_dist; naive_solver.\n    - apply _.\n    - by intros n m [x1 y1] [x2 y2] [??] ?; split;\n        eauto using dist_le with si_solver.\n  Qed.\n  Canonical Structure prodO : ofe := Ofe (A * B) prod_ofe_mixin.\n\n  Global Program Instance prod_cofe `{Cofe A, Cofe B} : Cofe prodO :=\n    { compl c := (compl (chain_map fst c), compl (chain_map snd c)) }.\n  Next Obligation.\n    intros ?? n c; split.\n    - apply (conv_compl n (chain_map fst c)).\n    - apply (conv_compl n (chain_map snd c)).\n  Qed.\n\n  Global Instance prod_discrete (x : A * B) :\n    Discrete (x.1) → Discrete (x.2) → Discrete x.\n  Proof. by intros ???[??]; split; apply (discrete _). Qed.\n  Global Instance prod_ofe_discrete :\n    OfeDiscrete A → OfeDiscrete B → OfeDiscrete prodO.\n  Proof. intros ?? [??]; apply _. Qed.\nEnd product.\n\nGlobal Arguments prodO : clear implicits.\n\n(** Below we make [prod_dist] type class opaque, so we first lift all\ninstances *)\nGlobal Instance pair_ne {A B : ofe} : NonExpansive2 (@pair A B) := _.\nGlobal Instance pair_dist_inj {A B : ofe} n :\n  Inj2 (≡{n}≡) (≡{n}≡) (≡{n}≡) (@pair A B) := _.\nGlobal Instance fst_ne {A B : ofe} : NonExpansive (@fst A B) := _.\nGlobal Instance snd_ne {A B : ofe} : NonExpansive (@snd A B) := _.\n\nGlobal Instance curry_ne {A B C : ofe} n :\n  Proper (((≡{n}@{A*B}≡) ==> (≡{n}@{C}≡)) ==>\n          (≡{n}≡) ==> (≡{n}≡) ==> (≡{n}≡)) curry := _.\nGlobal Instance uncurry_ne {A B C : ofe} n :\n  Proper (((≡{n}≡) ==> (≡{n}≡) ==> (≡{n}≡)) ==>\n          (≡{n}@{A*B}≡) ==> (≡{n}@{C}≡)) uncurry := _.\n\nGlobal Instance curry3_ne {A B C D : ofe} n :\n  Proper (((≡{n}@{A*B*C}≡) ==> (≡{n}@{D}≡)) ==>\n          (≡{n}≡) ==> (≡{n}≡) ==> (≡{n}≡) ==> (≡{n}≡)) curry3 := _.\nGlobal Instance uncurry3_ne {A B C D : ofe} n :\n  Proper (((≡{n}≡) ==> (≡{n}≡) ==> (≡{n}≡) ==> (≡{n}≡)) ==>\n          (≡{n}@{A*B*C}≡) ==> (≡{n}@{D}≡)) uncurry3 := _.\n\nGlobal Instance curry4_ne {A B C D E : ofe} n :\n  Proper (((≡{n}@{A*B*C*D}≡) ==> (≡{n}@{E}≡)) ==>\n          (≡{n}≡) ==> (≡{n}≡) ==> (≡{n}≡) ==> (≡{n}≡) ==> (≡{n}≡)) curry4 := _.\nGlobal Instance uncurry4_ne {A B C D E : ofe} n :\n  Proper (((≡{n}≡) ==> (≡{n}≡) ==> (≡{n}≡) ==> (≡{n}≡) ==> (≡{n}≡)) ==>\n          (≡{n}@{A*B*C*D}≡) ==> (≡{n}@{E}≡)) uncurry4 := _.\n\nTypeclasses Opaque prod_dist.\n\nGlobal Instance prod_map_ne {A A' B B' : ofe} n :\n  Proper ((dist n ==> dist n) ==> (dist n ==> dist n) ==>\n           dist n ==> dist n) (@prod_map A A' B B').\nProof. by intros f f' Hf g g' Hg ?? [??]; split; [apply Hf|apply Hg]. Qed.\nDefinition prodO_map {A A' B B'} (f : A -n> A') (g : B -n> B') :\n  prodO A B -n> prodO A' B' := OfeMor (prod_map f g).\nGlobal Instance prodO_map_ne {A A' B B'} :\n  NonExpansive2 (@prodO_map A A' B B').\nProof. intros n f f' Hf g g' Hg [??]; split; [apply Hf|apply Hg]. Qed.\n\n(** * COFE → OFE Functors *)\nRecord oFunctor := OFunctor {\n  oFunctor_car : ∀ A `{!Cofe A} B `{!Cofe B}, ofe;\n  oFunctor_map `{!Cofe A1, !Cofe A2, !Cofe B1, !Cofe B2} :\n    ((A2 -n> A1) * (B1 -n> B2)) → oFunctor_car A1 B1 -n> oFunctor_car A2 B2;\n  oFunctor_map_ne `{!Cofe A1, !Cofe A2, !Cofe B1, !Cofe B2} :\n    NonExpansive (@oFunctor_map A1 _ A2 _ B1 _ B2 _);\n  oFunctor_map_id `{!Cofe A, !Cofe B} (x : oFunctor_car A B) :\n    oFunctor_map (cid,cid) x ≡ x;\n  oFunctor_map_compose `{!Cofe A1, !Cofe A2, !Cofe A3, !Cofe B1, !Cofe B2, !Cofe B3}\n      (f : A2 -n> A1) (g : A3 -n> A2) (f' : B1 -n> B2) (g' : B2 -n> B3) x :\n    oFunctor_map (f◎g, g'◎f') x ≡ oFunctor_map (g,g') (oFunctor_map (f,f') x)\n}.\nGlobal Existing Instance oFunctor_map_ne.\nGlobal Instance: Params (@oFunctor_map) 9 := {}.\n\nDeclare Scope oFunctor_scope.\nDelimit Scope oFunctor_scope with OF.\nBind Scope oFunctor_scope with oFunctor.\n\nClass oFunctorContractive (F : oFunctor) :=\n  oFunctor_map_contractive `{!Cofe A1, !Cofe A2, !Cofe B1, !Cofe B2} :>\n    Contractive (@oFunctor_map F A1 _ A2 _ B1 _ B2 _).\nGlobal Hint Mode oFunctorContractive ! : typeclass_instances.\n\n(** Not a coercion due to the [Cofe] type class argument, and to avoid\nambiguous coercion paths, see https://gitlab.mpi-sws.org/iris/iris/issues/240. *)\nDefinition oFunctor_apply (F: oFunctor) (A: ofe) `{!Cofe A} : ofe :=\n  oFunctor_car F A A.\n\nProgram Definition oFunctor_oFunctor_compose (F1 F2 : oFunctor)\n  `{!∀ `{Cofe A, Cofe B}, Cofe (oFunctor_car F2 A B)} : oFunctor := {|\n  oFunctor_car A _ B _ := oFunctor_car F1 (oFunctor_car F2 B A) (oFunctor_car F2 A B);\n  oFunctor_map A1 _ A2 _ B1 _ B2 _ 'fg :=\n    oFunctor_map F1 (oFunctor_map F2 (fg.2,fg.1),oFunctor_map F2 fg)\n|}.\nNext Obligation.\n  intros F1 F2 ? A1 ? A2 ? B1 ? B2 ? n [f1 g1] [f2 g2] [??]; simpl in *.\n  apply oFunctor_map_ne; split; apply oFunctor_map_ne; by split.\nQed.\nNext Obligation.\n  intros F1 F2 ? A ? B ? x; simpl in *. rewrite -{2}(oFunctor_map_id F1 x).\n  apply equiv_dist=> n. apply oFunctor_map_ne.\n  split=> y /=; by rewrite !oFunctor_map_id.\nQed.\nNext Obligation.\n  intros F1 F2 ? A1 ? A2 ? A3 ? B1 ? B2 ? B3 ? f g f' g' x; simpl in *.\n  rewrite -oFunctor_map_compose. apply equiv_dist=> n. apply oFunctor_map_ne.\n  split=> y /=; by rewrite !oFunctor_map_compose.\nQed.\nGlobal Instance oFunctor_oFunctor_compose_contractive_1 (F1 F2 : oFunctor)\n    `{!∀ `{Cofe A, Cofe B}, Cofe (oFunctor_car F2 A B)} :\n  oFunctorContractive F1 → oFunctorContractive (oFunctor_oFunctor_compose F1 F2).\nProof.\n  intros ? A1 ? A2 ? B1 ? B2 ? n [f1 g1] [f2 g2] Hfg; simpl in *.\n  f_contractive; destruct Hfg; split; simpl in *; apply oFunctor_map_ne; by split.\nQed.\nGlobal Instance oFunctor_oFunctor_compose_contractive_2 (F1 F2 : oFunctor)\n    `{!∀ `{Cofe A, Cofe B}, Cofe (oFunctor_car F2 A B)} :\n  oFunctorContractive F2 → oFunctorContractive (oFunctor_oFunctor_compose F1 F2).\nProof.\n  intros ? A1 ? A2 ? B1 ? B2 ? n [f1 g1] [f2 g2] Hfg; simpl in *.\n  f_equiv; split; simpl in *; f_contractive; destruct Hfg; by split.\nQed.\n\nProgram Definition constOF (B : ofe) : oFunctor :=\n  {| oFunctor_car A1 A2 _ _ := B; oFunctor_map A1 _ A2 _ B1 _ B2 _ f := cid |}.\nSolve Obligations with done.\nCoercion constOF : ofe >-> oFunctor.\n\nGlobal Instance constOF_contractive B : oFunctorContractive (constOF B).\nProof. rewrite /oFunctorContractive; apply _. Qed.\n\nProgram Definition idOF : oFunctor :=\n  {| oFunctor_car A1 _ A2 _ := A2; oFunctor_map A1 _ A2 _ B1 _ B2 _ f := f.2 |}.\nSolve Obligations with done.\nNotation \"∙\" := idOF : oFunctor_scope.\n\nProgram Definition prodOF (F1 F2 : oFunctor) : oFunctor := {|\n  oFunctor_car A _ B _ := prodO (oFunctor_car F1 A B) (oFunctor_car F2 A B);\n  oFunctor_map A1 _ A2 _ B1 _ B2 _ fg :=\n    prodO_map (oFunctor_map F1 fg) (oFunctor_map F2 fg)\n|}.\nNext Obligation.\n  intros ?? A1 ? A2 ? B1 ? B2 ? n ???; by apply prodO_map_ne; apply oFunctor_map_ne.\nQed.\nNext Obligation. by intros F1 F2 A ? B ? [??]; rewrite /= !oFunctor_map_id. Qed.\nNext Obligation.\n  intros F1 F2 A1 ? A2 ? A3 ? B1 ? B2 ? B3 ? f g f' g' [??]; simpl.\n  by rewrite !oFunctor_map_compose.\nQed.\nNotation \"F1 * F2\" := (prodOF F1%OF F2%OF) : oFunctor_scope.\n\nGlobal Instance prodOF_contractive F1 F2 :\n  oFunctorContractive F1 → oFunctorContractive F2 →\n  oFunctorContractive (prodOF F1 F2).\nProof.\n  intros ?? A1 ? A2 ? B1 ? B2 ? n ???;\n    by apply prodO_map_ne; apply oFunctor_map_contractive.\nQed.\n\nProgram Definition ofe_morOF (F1 F2 : oFunctor) : oFunctor := {|\n  oFunctor_car A _ B _ := oFunctor_car F1 B A -n> oFunctor_car F2 A B;\n  oFunctor_map A1 _ A2 _ B1 _ B2 _ fg :=\n    ofe_morO_map (oFunctor_map F1 (fg.2, fg.1)) (oFunctor_map F2 fg)\n|}.\nNext Obligation.\n  intros F1 F2 A1 ? A2 ? B1 ? B2 ? n [f g] [f' g'] Hfg; simpl in *.\n  apply ofe_morO_map_ne; apply oFunctor_map_ne; split; by apply Hfg.\nQed.\nNext Obligation.\n  intros F1 F2 A ? B ? [f ?] ?; simpl. rewrite /= !oFunctor_map_id.\n  apply (ne_proper f). apply oFunctor_map_id.\nQed.\nNext Obligation.\n  intros F1 F2 A1 ? A2 ? A3 ? B1 ? B2 ? B3 ? f g f' g' [h ?] ?; simpl in *.\n  rewrite -!oFunctor_map_compose. do 2 apply (ne_proper _). apply oFunctor_map_compose.\nQed.\nNotation \"F1 -n> F2\" := (ofe_morOF F1%OF F2%OF) : oFunctor_scope.\n\nGlobal Instance ofe_morOF_contractive F1 F2 :\n  oFunctorContractive F1 → oFunctorContractive F2 →\n  oFunctorContractive (ofe_morOF F1 F2).\nProof.\n  intros ?? A1 ? A2 ? B1 ? B2 ? n [f g] [f' g'] Hfg; simpl in *.\n  apply ofe_morO_map_ne; apply oFunctor_map_contractive;\n    split; intros m Hlt; split; simpl.\n  all: destruct Hfg as [Hfg]; destruct (Hfg m); auto.\nQed.\n\n(** * Sum type *)\nSection sum.\n  Context {A B : ofe}.\n\n  Local Instance sum_dist : Dist (A + B) := λ n, sum_relation (dist n) (dist n).\n  Global Instance inl_ne : NonExpansive (@inl A B) := _.\n  Global Instance inr_ne : NonExpansive (@inr A B) := _.\n  Global Instance inl_ne_inj n : Inj (dist n) (dist n) (@inl A B) := _.\n  Global Instance inr_ne_inj n : Inj (dist n) (dist n) (@inr A B) := _.\n\n  Definition sum_ofe_mixin : OfeMixin (A + B).\n  Proof.\n    split.\n    - intros x y; split=> Hx.\n      + destruct Hx=> n; constructor; by apply equiv_dist.\n      + destruct (Hx 0); constructor; apply equiv_dist=> n; by apply (inj _).\n    - apply _.\n    - destruct 1; constructor; eapply dist_lt; eauto.\n  Qed.\n  Canonical Structure sumO : ofe := Ofe (A + B) sum_ofe_mixin.\n\n  Program Definition inl_chain (c : chain sumO) (a : A) : chain A :=\n    {| chain_car n := match c n return _ with inl a' => a' | _ => a end |}.\n  Next Obligation. intros c a n i ?; simpl. by destruct (chain_cauchy c n i). Qed.\n  Program Definition inr_chain (c : chain sumO) (b : B) : chain B :=\n    {| chain_car n := match c n return _ with inr b' => b' | _ => b end |}.\n  Next Obligation. intros c b n i ?; simpl. by destruct (chain_cauchy c n i). Qed.\n\n  Definition sum_compl `{!Cofe A, !Cofe B} : Compl sumO := λ c,\n    match c 0 with\n    | inl a => inl (compl (inl_chain c a))\n    | inr b => inr (compl (inr_chain c b))\n    end.\n  Global Program Instance sum_cofe `{Cofe A, Cofe B} : Cofe sumO :=\n    { compl := sum_compl }.\n  Next Obligation.\n    intros ?? n c; rewrite /compl /sum_compl.\n    feed inversion (chain_cauchy c 0 n); first by si_solver.\n    - rewrite (conv_compl n (inl_chain c _)) /=. destruct (c n); naive_solver.\n    - rewrite (conv_compl n (inr_chain c _)) /=. destruct (c n); naive_solver.\n  Qed.\n\n  Global Instance inl_discrete (x : A) : Discrete x → Discrete (inl x).\n  Proof. inversion_clear 2; constructor; by apply (discrete _). Qed.\n  Global Instance inr_discrete (y : B) : Discrete y → Discrete (inr y).\n  Proof. inversion_clear 2; constructor; by apply (discrete _). Qed.\n  Global Instance sum_ofe_discrete :\n    OfeDiscrete A → OfeDiscrete B → OfeDiscrete sumO.\n  Proof. intros ?? [?|?]; apply _. Qed.\nEnd sum.\n\nGlobal Arguments sumO : clear implicits.\nTypeclasses Opaque sum_dist.\n\nGlobal Instance sum_map_ne {A A' B B' : ofe} n :\n  Proper ((dist n ==> dist n) ==> (dist n ==> dist n) ==>\n           dist n ==> dist n) (@sum_map A A' B B').\nProof.\n  intros f f' Hf g g' Hg ??; destruct 1; constructor; [by apply Hf|by apply Hg].\nQed.\nDefinition sumO_map {A A' B B'} (f : A -n> A') (g : B -n> B') :\n  sumO A B -n> sumO A' B' := OfeMor (sum_map f g).\nGlobal Instance sumO_map_ne {A A' B B'} :\n  NonExpansive2 (@sumO_map A A' B B').\nProof. intros n f f' Hf g g' Hg [?|?]; constructor; [apply Hf|apply Hg]. Qed.\n\nProgram Definition sumOF (F1 F2 : oFunctor) : oFunctor := {|\n  oFunctor_car A _ B _ := sumO (oFunctor_car F1 A B) (oFunctor_car F2 A B);\n  oFunctor_map A1 _ A2 _ B1 _ B2 _ fg :=\n    sumO_map (oFunctor_map F1 fg) (oFunctor_map F2 fg)\n|}.\nNext Obligation.\n  intros ?? A1 ? A2 ? B1 ? B2 ? n ???; by apply sumO_map_ne; apply oFunctor_map_ne.\nQed.\nNext Obligation. by intros F1 F2 A ? B ? [?|?]; rewrite /= !oFunctor_map_id. Qed.\nNext Obligation.\n  intros F1 F2 A1 ? A2 ? A3 ? B1 ? B2 ? B3 ? f g f' g' [?|?]; simpl;\n    by rewrite !oFunctor_map_compose.\nQed.\nNotation \"F1 + F2\" := (sumOF F1%OF F2%OF) : oFunctor_scope.\n\nGlobal Instance sumOF_contractive F1 F2 :\n  oFunctorContractive F1 → oFunctorContractive F2 →\n  oFunctorContractive (sumOF F1 F2).\nProof.\n  intros ?? A1 ? A2 ? B1 ? B2 ? n ???;\n    by apply sumO_map_ne; apply oFunctor_map_contractive.\nQed.\n\n(** * Discrete OFEs *)\nSection discrete_ofe.\n  Context {A : Type} `{!Equiv A} (Heq : @Equivalence A (≡)).\n\n  Local Instance discrete_dist : Dist A := λ n x y, x ≡ y.\n  Definition discrete_ofe_mixin : OfeMixin A.\n  Proof using Type*.\n    split.\n    - intros x y; split; [done|intros Hn; apply (Hn 0)].\n    - done.\n    - done.\n  Qed.\n\n  Global Instance discrete_ofe_discrete : OfeDiscrete (Ofe A discrete_ofe_mixin).\n  Proof. by intros x y. Qed.\n\n  Global Program Instance discrete_cofe : Cofe (Ofe A discrete_ofe_mixin) :=\n    { compl c := c 0 }.\n  Next Obligation.\n    intros n c. rewrite /compl /=;\n    symmetry; apply (chain_cauchy c 0 n). lia.\n  Qed.\nEnd discrete_ofe.\n\n(** The combinators [discreteO] and [leibnizO] should be used with care. There\nare two ways in which they can be used:\n\n1. To define an OFE on a ground type, such as [nat], [expr], etc. The OFE\n   instance should be defined as [Canonical Structure tyO := leibnizO ty] or\n   [Canonical Structure tyO := discreteO ty], so not using [Definition]. See\n   [natO] below for an example. Make sure to avoid overlapping instances, so\n   always check if no instance has already been defined. For most of the types\n   from Coq, std++, and Iris, instances are present in Iris. The convention is\n   to use the name [tyO] for the OFE instance of a type [ty].\n2. As part of abstractions that are parametrized with a [Type], but where an\n   [ofe] is needed to use (camera) combinators. See [ghost_var] as an example.\n   In this case, the public API of the abstraction should exclusively use\n   [Type], i.e., the use of [leibnizO] or [discreteO] should not leak. Otherwise\n   client code can end up with overlapping instances, and thus experience odd\n   unification failures.\n\nYou should *never* use [leibnizO] or [discreteO] on compound types such as\n[list nat]. That creates overlapping canonical instances for the head symbol\n(e.g., [listO] and [leibnizO (list nat)]) and confuses unification. Instead, you\nhave two options:\n- declare/use a canonical instance for the ground type, e.g., [listO natO].\n- declare a newtype, e.g., [Record ty := Ty { ty_car : list nat }], and then\n  declare a canonical instance for that type, e.g.,\n  [Canonical Structure tyO := leibnizO ty]. *)\n\n(** The combinator [discreteO A] lifts an existing [Equiv A] instance into a\ndiscrete OFE. *)\nNotation discreteO A := (Ofe A (discrete_ofe_mixin _)).\n\n(** The combinator [leibnizO A] lifts Leibniz equality [=] into a discrete OFE.\nThe implementation forces the [Equivalence] proof to be [eq_equivalence] so that\nCoq does not accidentally use another one, like [ofe_equivalence], in the case of\naliases. See also https://gitlab.mpi-sws.org/iris/iris/issues/299 *)\nNotation leibnizO A := (Ofe A (@discrete_ofe_mixin _ equivL eq_equivalence)).\n\n(** In order to define a discrete CMRA with carrier [A] (in the file [cmra.v])\nwe need to determine the [Equivalence A] proof that was used to construct the\nOFE instance of [A] (note that this proof is not the same as the one we obtain\nvia [ofe_equivalence]).\n\nWe obtain the proof of [Equivalence A] by inferring the canonical OFE mixin\nusing [ofe_mixin_of A], and then check whether it is indeed a discrete OFE. This\nwill fail if no OFE, or an OFE other than the discrete OFE, was registered. *)\nNotation discrete_ofe_equivalence_of A := ltac:(\n  match constr:(ofe_mixin_of A) with\n  | discrete_ofe_mixin ?H => exact H\n  end) (only parsing).\n\nGlobal Instance leibnizO_leibniz A : LeibnizEquiv (leibnizO A).\nProof. by intros x y. Qed.\n\n(** * Basic Coq types *)\nCanonical Structure boolO := leibnizO bool.\nCanonical Structure natO := leibnizO nat.\nCanonical Structure positiveO := leibnizO positive.\nCanonical Structure NO := leibnizO N.\nCanonical Structure ZO := leibnizO Z.\n\nSection prop.\n  Local Instance Prop_equiv : Equiv Prop := iff.\n  Local Instance Prop_equivalence : Equivalence (≡@{Prop}) := _.\n  Canonical Structure PropO := discreteO Prop.\nEnd prop.\n\n(** * Option type *)\nSection option.\n  Context {A : ofe}.\n\n  Local Instance option_dist : Dist (option A) := λ n, option_Forall2 (dist n).\n  Lemma dist_option_Forall2 n mx my : mx ≡{n}≡ my ↔ option_Forall2 (dist n) mx my.\n  Proof. done. Qed.\n\n  Definition option_ofe_mixin : OfeMixin (option A).\n  Proof.\n    split.\n    - intros mx my; split; [by destruct 1; constructor; apply equiv_dist|].\n      intros Hxy; destruct (Hxy 0); constructor; apply equiv_dist.\n      by intros n; feed inversion (Hxy n).\n    - apply _.\n    - destruct 1; constructor; eauto using dist_le with si_solver.\n  Qed.\n  Canonical Structure optionO := Ofe (option A) option_ofe_mixin.\n\n  Program Definition option_chain (c : chain optionO) (x : A) : chain A :=\n    {| chain_car n := default x (c n) |}.\n  Next Obligation. intros c x n i ?; simpl. by destruct (chain_cauchy c n i). Qed.\n  Definition option_compl `{!Cofe A} : Compl optionO := λ c,\n    match c 0 with Some x => Some (compl (option_chain c x)) | None => None end.\n  Global Program Instance option_cofe `{Cofe A} : Cofe optionO :=\n    { compl := option_compl }.\n  Next Obligation.\n    intros ? n c; rewrite /compl /option_compl.\n    feed inversion (chain_cauchy c 0 n); auto with lia; [].\n    constructor. rewrite (conv_compl n (option_chain c _)) /=.\n    destruct (c n); naive_solver.\n  Qed.\n\n  Global Instance option_ofe_discrete : OfeDiscrete A → OfeDiscrete optionO.\n  Proof. destruct 2; constructor; by apply (discrete _). Qed.\n\n  Global Instance Some_ne : NonExpansive (@Some A).\n  Proof. by constructor. Qed.\n  Global Instance is_Some_ne n : Proper (dist n ==> iff) (@is_Some A).\n  Proof. destruct 1; split; eauto. Qed.\n  Global Instance Some_dist_inj n : Inj (dist n) (dist n) (@Some A).\n  Proof. by inversion_clear 1. Qed.\n  Global Instance from_option_ne {B} (R : relation B) n :\n    Proper ((dist (A:=A) n ==> R) ==> R ==> dist n ==> R) from_option.\n  Proof. destruct 3; simpl; auto. Qed.\n\n  Global Instance None_discrete : Discrete (@None A).\n  Proof. inversion_clear 1; constructor. Qed.\n  Global Instance Some_discrete x : Discrete x → Discrete (Some x).\n  Proof. by intros ?; inversion_clear 1; constructor; apply discrete. Qed.\n\n  Lemma dist_None n mx : mx ≡{n}≡ None ↔ mx = None.\n  Proof. split; [by inversion_clear 1|by intros ->]. Qed.\n  Lemma dist_Some_inv_l n mx my x :\n    mx ≡{n}≡ my → mx = Some x → ∃ y, my = Some y ∧ x ≡{n}≡ y.\n  Proof. destruct 1; naive_solver. Qed.\n  Lemma dist_Some_inv_r n mx my y :\n    mx ≡{n}≡ my → my = Some y → ∃ x, mx = Some x ∧ x ≡{n}≡ y.\n  Proof. destruct 1; naive_solver. Qed.\n  Lemma dist_Some_inv_l' n my x : Some x ≡{n}≡ my → ∃ x', Some x' = my ∧ x ≡{n}≡ x'.\n  Proof. intros ?%(dist_Some_inv_l _ _ _ x); naive_solver. Qed.\n  Lemma dist_Some_inv_r' n mx y : mx ≡{n}≡ Some y → ∃ y', mx = Some y' ∧ y ≡{n}≡ y'.\n  Proof. intros ?%(dist_Some_inv_r _ _ _ y); naive_solver. Qed.\nEnd option.\n\nTypeclasses Opaque option_dist.\nGlobal Arguments optionO : clear implicits.\n\nGlobal Instance option_fmap_ne {A B : ofe} n:\n  Proper ((dist n ==> dist n) ==> dist n ==> dist n) (@fmap option _ A B).\nProof. intros f f' Hf ?? []; constructor; auto. Qed.\nGlobal Instance option_mbind_ne {A B : ofe} n:\n  Proper ((dist n ==> dist n) ==> dist n ==> dist n) (@mbind option _ A B).\nProof. destruct 2; simpl; auto. Qed.\nGlobal Instance option_mjoin_ne {A : ofe} n:\n  Proper (dist n ==> dist n) (@mjoin option _ A).\nProof. destruct 1 as [?? []|]; simpl; by constructor. Qed.\n\nLemma fmap_Some_dist {A B : ofe} (f : A → B) (mx : option A) (y : B) n :\n  f <$> mx ≡{n}≡ Some y ↔ ∃ x : A, mx = Some x ∧ y ≡{n}≡ f x.\nProof.\n  split; [|by intros (x&->&->)].\n  intros (?&?%fmap_Some&?)%dist_Some_inv_r'; naive_solver.\nQed.\n\nDefinition optionO_map {A B} (f : A -n> B) : optionO A -n> optionO B :=\n  OfeMor (fmap f : optionO A → optionO B).\nGlobal Instance optionO_map_ne A B : NonExpansive (@optionO_map A B).\nProof. by intros n f f' Hf []; constructor; apply Hf. Qed.\n\nProgram Definition optionOF (F : oFunctor) : oFunctor := {|\n  oFunctor_car A _ B _ := optionO (oFunctor_car F A B);\n  oFunctor_map A1 _ A2 _ B1 _ B2 _ fg := optionO_map (oFunctor_map F fg)\n|}.\nNext Obligation.\n  by intros F A1 ? A2 ? B1 ? B2 ? n f g Hfg; apply optionO_map_ne, oFunctor_map_ne.\nQed.\nNext Obligation.\n  intros F A ? B ? x. rewrite /= -{2}(option_fmap_id x).\n  apply option_fmap_equiv_ext=>y; apply oFunctor_map_id.\nQed.\nNext Obligation.\n  intros F A1 ? A2 ? A3 ? B1 ? B2 ? B3 ? f g f' g' x. rewrite /= -option_fmap_compose.\n  apply option_fmap_equiv_ext=>y; apply oFunctor_map_compose.\nQed.\n\nGlobal Instance optionOF_contractive F :\n  oFunctorContractive F → oFunctorContractive (optionOF F).\nProof.\n  by intros ? A1 ? A2 ? B1 ? B2 ? n f g Hfg;\n    apply optionO_map_ne, oFunctor_map_contractive.\nQed.\n\n(** * Later type *)\n(** Note that the projection [later_car] is not non-expansive (see also the\nlemma [later_car_anti_contractive] below), so it cannot be used in the logic.\nIf you need to get a witness out, you should use the lemma [Next_uninj]\ninstead. *)\nRecord later (A : Type) : Type := Next { later_car : A }.\nAdd Printing Constructor later.\nGlobal Arguments Next {_} _.\nGlobal Arguments later_car {_} _.\nGlobal Instance: Params (@Next) 1 := {}.\n\nSection later.\n  Context {A : ofe}.\n  Local Instance later_equiv : Equiv (later A) := λ x y, later_car x ≡ later_car y.\n  Local Instance later_dist : Dist (later A) := λ n x y,\n    dist_later n (later_car x) (later_car y).\n  Definition later_ofe_mixin : OfeMixin (later A).\n  Proof.\n    split.\n    - intros x y; unfold equiv, later_equiv; rewrite !equiv_dist.\n      split; intros Hxy n; [done|].\n      eapply (Hxy (S n)). lia.\n    - split; rewrite /dist /later_dist.\n      + by intros [x].\n      + by intros [x] [y].\n      + by intros [x] [y] [z] ??; trans y.\n    - intros n m [x] [y] Hdist ?; split; intros p Hp. eapply Hdist; by trans m.\n  Qed.\n  Canonical Structure laterO : ofe := Ofe (later A) later_ofe_mixin.\n\n  Program Definition later_chain (c : chain laterO) : chain A :=\n    {| chain_car n := later_car (c (S n)) |}.\n  Next Obligation. intros c n i ?; apply (chain_cauchy c (S n)); lia. Qed.\n  Global Program Instance later_cofe `{Cofe A} : Cofe laterO :=\n    { compl c := Next (compl (later_chain c)) }.\n  Next Obligation.\n    intros ? n c. apply dist_later_fin_iff.\n    destruct n as [|n]; [done|by apply (conv_compl n (later_chain c))].\n  Qed.\n\n  Global Instance Next_contractive : Contractive (@Next A).\n  Proof. by intros n x y. Qed.\n  Global Instance Next_inj n : Inj (dist_later n) (dist n) (@Next A).\n  Proof. by intros x y. Qed.\n\n  Lemma Next_uninj x : ∃ a, x ≡ Next a.\n  Proof. by exists (later_car x). Qed.\n  Local Instance later_car_anti_contractive n :\n    Proper (dist n ==> dist_later n) later_car.\n  Proof. move=> [x] [y] /= Hxy. done. Qed.\n\n  (** [f] is contractive iff it can factor into [Next] and a non-expansive\n  function. *)\n  Lemma contractive_alt {B : ofe} (f : A → B) :\n    Contractive f ↔ ∃ g : later A → B, NonExpansive g ∧ ∀ x, f x ≡ g (Next x).\n  Proof.\n    split.\n    - intros Hf. exists (f ∘ later_car); split=> // n x y ?. by f_equiv.\n    - intros (g&Hg&Hf) n x y Hxy. rewrite !Hf. by apply Hg.\n  Qed.\nEnd later.\n\nGlobal Arguments laterO : clear implicits.\n\nDefinition later_map {A B} (f : A → B) (x : later A) : later B :=\n  Next (f (later_car x)).\nGlobal Instance later_map_ne {A B : ofe} (f : A → B) n :\n  Proper (dist_later n ==> dist_later n) f →\n  Proper (dist n ==> dist n) (later_map f) | 0.\nProof.\n  intros P [x] [y] Hdist; rewrite /later_map //=.\n  split; intros m Hm; apply P, Hm. apply Hdist.\nQed.\nGlobal Instance later_map_ne' {A B : ofe} (f : A → B) `{NonExpansive f} :\n  NonExpansive (later_map f).\nProof.\n  intros ? [x] [y] Hdist. unfold later_map; simpl.\n  split; intros ??; simpl. f_equiv. by eapply Hdist.\nQed.\nGlobal Instance later_map_proper {A B : ofe} (f : A → B) :\n  Proper ((≡) ==> (≡)) f →\n  Proper ((≡) ==> (≡)) (later_map f).\nProof. solve_proper. Qed.\nLemma later_map_id {A} (x : later A) : later_map id x = x.\nProof. by destruct x. Qed.\nLemma later_map_compose {A B C} (f : A → B) (g : B → C) (x : later A) :\n  later_map (g ∘ f) x = later_map g (later_map f x).\nProof. by destruct x. Qed.\nLemma later_map_ext {A B : ofe} (f g : A → B) x :\n  (∀ x, f x ≡ g x) → later_map f x ≡ later_map g x.\nProof. destruct x; intros Hf; apply Hf. Qed.\nDefinition laterO_map {A B} (f : A -n> B) : laterO A -n> laterO B :=\n  OfeMor (later_map f).\nGlobal Instance laterO_map_contractive (A B : ofe) : Contractive (@laterO_map A B).\nProof. intros n f g Hlater [x]; split; intros ??; simpl. by apply Hlater. Qed.\n\nProgram Definition laterOF (F : oFunctor) : oFunctor := {|\n  oFunctor_car A _ B _ := laterO (oFunctor_car F A B);\n  oFunctor_map A1 _ A2 _ B1 _ B2 _ fg := laterO_map (oFunctor_map F fg)\n|}.\nNext Obligation.\n  intros F A1 ? A2 ? B1 ? B2 ? n fg fg' ?.\n  by apply (contractive_ne laterO_map), oFunctor_map_ne.\nQed.\nNext Obligation.\n  intros F A ? B ? x; simpl. rewrite -{2}(later_map_id x).\n  apply later_map_ext=>y. by rewrite oFunctor_map_id.\nQed.\nNext Obligation.\n  intros F A1 ? A2 ? A3 ? B1 ? B2 ? B3 ? f g f' g' x; simpl. rewrite -later_map_compose.\n  apply later_map_ext=>y; apply oFunctor_map_compose.\nQed.\nNotation \"▶ F\"  := (laterOF F%OF) (at level 20, right associativity) : oFunctor_scope.\n\nGlobal Instance laterOF_contractive F : oFunctorContractive (laterOF F).\nProof.\n  intros A1 ? A2 ? B1 ? B2 ? n fg fg' Hfg. apply laterO_map_contractive.\n  split; intros ???; simpl. by eapply oFunctor_map_ne, Hfg.\nQed.\n\n(** * Dependently-typed functions over a discrete domain *)\n(** This separate notion is useful whenever we need dependent functions, and\nwhenever we want to avoid the hassle of the bundled non-expansive function type.\n\nNote that non-dependent functions over a discrete domain, [A -d> B] (following\nthe notation we introduce below) are non-expansive if they are\n[Proper ((≡) ==> (≡))]. In other words, since the domain is discrete,\nnon-expansiveness and respecting [(≡)] are the same. If the domain is moreover\nLeibniz ([LeibnizEquiv A]), we get both for free.\n\nWe make [discrete_fun] a definition so that we can register it as a canonical\nstructure.  We do not bundle the [Proper] proof to keep [discrete_fun] easier to\nuse. It turns out all the desired OFE and functorial properties do not rely on\nthis [Proper] instance. *)\nDefinition discrete_fun {A} (B : A → ofe) := ∀ x : A, B x.\n\nSection discrete_fun.\n  Context {A : Type} {B : A → ofe}.\n  Implicit Types f g : discrete_fun B.\n\n  Local Instance discrete_fun_equiv : Equiv (discrete_fun B) := λ f g, ∀ x, f x ≡ g x.\n  Local Instance discrete_fun_dist : Dist (discrete_fun B) := λ n f g, ∀ x, f x ≡{n}≡ g x.\n  Definition discrete_fun_ofe_mixin : OfeMixin (discrete_fun B).\n  Proof.\n    split.\n    - intros f g; split; [intros Hfg n k; apply equiv_dist, Hfg|].\n      intros Hfg k; apply equiv_dist=> n; apply Hfg.\n    - intros n; split.\n      + by intros f x.\n      + by intros f g ? x.\n      + by intros f g h ?? x; trans (g x).\n    - by intros n m f g ? ? x; eauto using dist_le with si_solver.\n  Qed.\n  Canonical Structure discrete_funO := Ofe (discrete_fun B) discrete_fun_ofe_mixin.\n\n  Program Definition discrete_fun_chain `(c : chain discrete_funO)\n    (x : A) : chain (B x) := {| chain_car n := c n x |}.\n  Next Obligation. intros c x n i ?. by apply (chain_cauchy c). Qed.\n  Global Program Instance discrete_fun_cofe `{∀ x, Cofe (B x)} : Cofe discrete_funO :=\n    { compl c x := compl (discrete_fun_chain c x) }.\n  Next Obligation. intros ? n c x. apply (conv_compl n (discrete_fun_chain c x)). Qed.\n\n  Global Instance discrete_fun_inhabited `{∀ x, Inhabited (B x)} : Inhabited discrete_funO :=\n    populate (λ _, inhabitant).\n  Global Instance discrete_fun_lookup_discrete `{EqDecision A} f x :\n    Discrete f → Discrete (f x).\n  Proof.\n    intros Hf y ?.\n    set (g x' := if decide (x = x') is left H then eq_rect _ B y _ H else f x').\n    trans (g x).\n    { apply Hf=> x'. unfold g. by destruct (decide _) as [[]|]. }\n    unfold g. destruct (decide _) as [Hx|]; last done.\n    by rewrite (proof_irrel Hx eq_refl).\n  Qed.\nEnd discrete_fun.\n\nGlobal Arguments discrete_funO {_} _.\nNotation \"A -d> B\" :=\n  (@discrete_funO A (λ _, B)) (at level 99, B at level 200, right associativity).\n\nDefinition discrete_fun_map {A} {B1 B2 : A → ofe} (f : ∀ x, B1 x → B2 x)\n  (g : discrete_fun B1) : discrete_fun B2 := λ x, f _ (g x).\n\nLemma discrete_fun_map_ext {A} {B1 B2 : A → ofe} (f1 f2 : ∀ x, B1 x → B2 x)\n  (g : discrete_fun B1) :\n  (∀ x, f1 x (g x) ≡ f2 x (g x)) → discrete_fun_map f1 g ≡ discrete_fun_map f2 g.\nProof. done. Qed.\nLemma discrete_fun_map_id {A} {B : A → ofe} (g : discrete_fun B) :\n  discrete_fun_map (λ _, id) g = g.\nProof. done. Qed.\nLemma discrete_fun_map_compose {A} {B1 B2 B3 : A → ofe}\n    (f1 : ∀ x, B1 x → B2 x) (f2 : ∀ x, B2 x → B3 x) (g : discrete_fun B1) :\n  discrete_fun_map (λ x, f2 x ∘ f1 x) g = discrete_fun_map f2 (discrete_fun_map f1 g).\nProof. done. Qed.\n\nGlobal Instance discrete_fun_map_ne {A} {B1 B2 : A → ofe} (f : ∀ x, B1 x → B2 x) n :\n  (∀ x, Proper (dist n ==> dist n) (f x)) →\n  Proper (dist n ==> dist n) (discrete_fun_map f).\nProof. by intros ? y1 y2 Hy x; rewrite /discrete_fun_map (Hy x). Qed.\n\nDefinition discrete_funO_map {A} {B1 B2 : A → ofe} (f : discrete_fun (λ x, B1 x -n> B2 x)) :\n  discrete_funO B1 -n> discrete_funO B2 := OfeMor (discrete_fun_map f).\nGlobal Instance discrete_funO_map_ne {A} {B1 B2 : A → ofe} :\n  NonExpansive (@discrete_funO_map A B1 B2).\nProof. intros n f1 f2 Hf g x; apply Hf. Qed.\n\nProgram Definition discrete_funOF {C} (F : C → oFunctor) : oFunctor := {|\n  oFunctor_car A _ B _ := discrete_funO (λ c, oFunctor_car (F c) A B);\n  oFunctor_map A1 _ A2 _ B1 _ B2 _ fg := discrete_funO_map (λ c, oFunctor_map (F c) fg)\n|}.\nNext Obligation.\n  intros C F A1 ? A2 ? B1 ? B2 ? n ?? g.\n  by apply discrete_funO_map_ne=>?; apply oFunctor_map_ne.\nQed.\nNext Obligation.\n  intros C F A ? B ? g; simpl. rewrite -{2}(discrete_fun_map_id g).\n  apply discrete_fun_map_ext=> y; apply oFunctor_map_id.\nQed.\nNext Obligation.\n  intros C F A1 ? A2 ? A3 ? B1 ? B2 ? B3 ? f1 f2 f1' f2' g.\n  rewrite /= -discrete_fun_map_compose.\n  apply discrete_fun_map_ext=>y; apply oFunctor_map_compose.\nQed.\n\nNotation \"T -d> F\" := (@discrete_funOF T%type (λ _, F%OF)) : oFunctor_scope.\n\nGlobal Instance discrete_funOF_contractive {C} (F : C → oFunctor) :\n  (∀ c, oFunctorContractive (F c)) → oFunctorContractive (discrete_funOF F).\nProof.\n  intros ? A1 ? A2 ? B1 ? B2 ? n ?? g.\n  by apply discrete_funO_map_ne=>c; apply oFunctor_map_contractive.\nQed.\n\n(** * Constructing isomorphic OFEs *)\nLemma iso_ofe_mixin {A : ofe} {B : Type} `{!Equiv B, !Dist B} (g : B → A)\n  (g_equiv : ∀ y1 y2, y1 ≡ y2 ↔ g y1 ≡ g y2)\n  (g_dist : ∀ n y1 y2, y1 ≡{n}≡ y2 ↔ g y1 ≡{n}≡ g y2) : OfeMixin B.\nProof.\n  split.\n  - intros y1 y2. rewrite g_equiv. setoid_rewrite g_dist. apply equiv_dist.\n  - split.\n    + intros y. by apply g_dist.\n    + intros y1 y2. by rewrite !g_dist.\n    + intros y1 y2 y3. rewrite !g_dist. intros ??; etrans; eauto.\n  - intros n m y1 y2. rewrite !g_dist. eauto using dist_le with si_solver.\nQed.\n\nSection iso_cofe_subtype.\n  Context {A B : ofe} `{Cofe A} (P : A → Prop) (f : ∀ x, P x → B) (g : B → A).\n  Context (g_dist : ∀ n y1 y2, y1 ≡{n}≡ y2 ↔ g y1 ≡{n}≡ g y2).\n  Let Hgne : NonExpansive g.\n  Proof. intros n y1 y2. apply g_dist. Qed.\n  Local Existing Instance Hgne.\n  Context (gf : ∀ x Hx, g (f x Hx) ≡ x).\n  Context (Hlimit : ∀ c : chain B, P (compl (chain_map g c))).\n  Program Definition iso_cofe_subtype : Cofe B :=\n    {| compl c := f (compl (chain_map g c)) _ |}.\n  Next Obligation. apply Hlimit. Qed.\n  Next Obligation.\n    intros n c; simpl. apply g_dist. by rewrite gf conv_compl.\n  Qed.\nEnd iso_cofe_subtype.\n\nLemma iso_cofe_subtype' {A B : ofe} `{Cofe A}\n  (P : A → Prop) (f : ∀ x, P x → B) (g : B → A)\n  (Pg : ∀ y, P (g y))\n  (g_dist : ∀ n y1 y2, y1 ≡{n}≡ y2 ↔ g y1 ≡{n}≡ g y2)\n  (gf : ∀ x Hx, g (f x Hx) ≡ x)\n  (Hlimit : LimitPreserving P) : Cofe B.\nProof. apply: (iso_cofe_subtype P f g)=> // c. apply Hlimit=> ?; apply Pg. Qed.\n\nDefinition iso_cofe {A B : ofe} `{Cofe A} (f : A → B) (g : B → A)\n  (g_dist : ∀ n y1 y2, y1 ≡{n}≡ y2 ↔ g y1 ≡{n}≡ g y2)\n  (gf : ∀ x, g (f x) ≡ x) : Cofe B.\nProof. by apply (iso_cofe_subtype (λ _, True) (λ x _, f x) g). Qed.\n\n(** * Sigma type *)\nSection sigma.\n  Context {A : ofe} {P : A → Prop}.\n  Implicit Types x : sig P.\n\n  (* TODO: Find a better place for this Equiv instance. It also\n     should not depend on A being an OFE. *)\n  Local Instance sig_equiv : Equiv (sig P) := λ x1 x2, `x1 ≡ `x2.\n  Local Instance sig_dist : Dist (sig P) := λ n x1 x2, `x1 ≡{n}≡ `x2.\n\n  Definition sig_equiv_def x y : (x ≡ y) = (`x ≡ `y) := reflexivity _.\n  Definition sig_dist_def n x y : (x ≡{n}≡ y) = (`x ≡{n}≡ `y) := reflexivity _.\n\n  Lemma exist_ne n a1 a2 (H1 : P a1) (H2 : P a2) :\n    a1 ≡{n}≡ a2 → a1 ↾ H1 ≡{n}≡ a2 ↾ H2.\n  Proof. done. Qed.\n\n  Global Instance proj1_sig_ne : NonExpansive (@proj1_sig _ P).\n  Proof. by intros n [a Ha] [b Hb] ?. Qed.\n  Definition sig_ofe_mixin : OfeMixin (sig P).\n  Proof. by apply (iso_ofe_mixin proj1_sig). Qed.\n  Canonical Structure sigO : ofe := Ofe (sig P) sig_ofe_mixin.\n\n  Global Instance sig_cofe `{!Cofe A, !LimitPreserving P} : Cofe sigO.\n  Proof. apply (iso_cofe_subtype' P (exist P) proj1_sig)=> //. by intros []. Qed.\n\n  Global Instance sig_discrete (x : sig P) :  Discrete (`x) → Discrete x.\n  Proof. intros ? y. rewrite sig_dist_def sig_equiv_def. apply (discrete _). Qed.\n  Global Instance sig_ofe_discrete : OfeDiscrete A → OfeDiscrete sigO.\n  Proof. intros ??. apply _. Qed.\nEnd sigma.\n\nGlobal Arguments sigO {_} _.\n\n(** * SigmaT type *)\n(** Ofe for [sigT]. The first component must be discrete and use Leibniz\nequality, while the second component might be any OFE. *)\nSection sigT.\n  Import EqNotations.\n\n  Context {A : Type} {P : A → ofe}.\n  Implicit Types x : sigT P.\n\n  (**\n    The distance for [{ a : A & P }] uses Leibniz equality on [A] to\n    transport the second components to the same type,\n    and then step-indexed distance on the second component.\n    Unlike in the topos of trees, with (C)OFEs we cannot use step-indexed equality\n    on the first component.\n  *)\n  Local Instance sigT_dist : Dist (sigT P) := λ n x1 x2,\n    ∃ Heq : projT1 x1 = projT1 x2, rew Heq in projT2 x1 ≡{n}≡ projT2 x2.\n\n  (**\n    Usually we'd give a direct definition, and show it equivalent to\n    [∀ n, x1 ≡{n}≡ x2] when proving the [equiv_dist] OFE axiom.\n    But here the equivalence requires UIP — see [sigT_equiv_eq_alt].\n    By defining [equiv] in terms of [dist], we can define an OFE\n    without assuming UIP, at the cost of complex reasoning on [equiv].\n  *)\n  Local Instance sigT_equiv : Equiv (sigT P) := λ x1 x2,\n    ∀ n, x1 ≡{n}≡ x2.\n\n  (** Unfolding lemmas.\n      Written with [↔] not [=] to avoid https://github.com/coq/coq/issues/3814. *)\n  Definition sigT_equiv_eq x1 x2 : (x1 ≡ x2) ↔ ∀ n, x1 ≡{n}≡ x2 :=\n      reflexivity _.\n\n  Definition sigT_dist_eq x1 x2 n : (x1 ≡{n}≡ x2) ↔\n    ∃ Heq : projT1 x1 = projT1 x2, (rew Heq in projT2 x1) ≡{n}≡ projT2 x2 :=\n      reflexivity _.\n\n  Definition sigT_dist_proj1 n {x y} : x ≡{n}≡ y → projT1 x = projT1 y := proj1_ex.\n  Definition sigT_equiv_proj1 {x y} : x ≡ y → projT1 x = projT1 y := λ H, proj1_ex (H 0).\n\n  Definition sigT_ofe_mixin : OfeMixin (sigT P).\n  Proof.\n    split => // n.\n    - split; hnf; setoid_rewrite sigT_dist_eq.\n      + intros. by exists eq_refl.\n      + move => [xa x] [ya y] /=. destruct 1 as [-> Heq].\n        by exists eq_refl.\n      + move => [xa x] [ya y] [za z] /=.\n        destruct 1 as [-> Heq1].\n        destruct 1 as [-> Heq2]. exists eq_refl => /=. by trans y.\n    - setoid_rewrite sigT_dist_eq.\n      move => m [xa x] [ya y] /=. destruct 1 as [-> Heq].\n      exists eq_refl. by eapply dist_dist_later.\n  Qed.\n\n  Canonical Structure sigTO : ofe := Ofe (sigT P) sigT_ofe_mixin.\n\n  Lemma sigT_equiv_eq_alt `{!∀ a b : A, ProofIrrel (a = b)} x1 x2 :\n    x1 ≡ x2 ↔\n    ∃ Heq : projT1 x1 = projT1 x2, rew Heq in projT2 x1 ≡ projT2 x2.\n  Proof.\n    setoid_rewrite equiv_dist; setoid_rewrite sigT_dist_eq; split => Heq.\n    - move: (Heq 0) => [H0eq1 _].\n      exists H0eq1 => n. move: (Heq n) => [] Hneq1.\n      by rewrite (proof_irrel H0eq1 Hneq1).\n    - move: Heq => [Heq1 Heqn2] n. by exists Heq1.\n  Qed.\n\n  (** [projT1] is non-expansive and proper. *)\n  Global Instance projT1_ne : NonExpansive (projT1 : sigTO → leibnizO A).\n  Proof. solve_proper. Qed.\n\n  Global Instance projT1_proper : Proper ((≡) ==> (≡)) (projT1 : sigTO → leibnizO A).\n  Proof. apply ne_proper, projT1_ne. Qed.\n\n  (** [projT2] is \"non-expansive\"; the properness lemma [projT2_ne] requires UIP. *)\n  Lemma projT2_ne n (x1 x2 : sigTO) (Heq : x1 ≡{n}≡ x2) :\n    rew (sigT_dist_proj1 n Heq) in projT2 x1 ≡{n}≡ projT2 x2.\n  Proof. by destruct Heq. Qed.\n\n  Lemma projT2_proper `{!∀ a b : A, ProofIrrel (a = b)} (x1 x2 : sigTO) (Heqs : x1 ≡ x2):\n    rew (sigT_equiv_proj1 Heqs) in projT2 x1 ≡ projT2 x2.\n  Proof.\n    move: x1 x2 Heqs => [a1 x1] [a2 x2] Heqs.\n    case: (proj1 (sigT_equiv_eq_alt _ _) Heqs) => /=. intros ->.\n    rewrite (proof_irrel (sigT_equiv_proj1 Heqs) eq_refl) /=. done.\n  Qed.\n\n  (** [existT] is \"non-expansive\" — general, dependently-typed statement. *)\n  Lemma existT_ne n {i1 i2} {v1 : P i1} {v2 : P i2} :\n    ∀ (Heq : i1 = i2), (rew f_equal P Heq in v1 ≡{n}≡ v2) →\n      existT i1 v1 ≡{n}≡ existT i2 v2.\n  Proof. intros ->; simpl. exists eq_refl => /=. done. Qed.\n\n  Lemma existT_proper {i1 i2} {v1 : P i1} {v2 : P i2} :\n    ∀ (Heq : i1 = i2), (rew f_equal P Heq in v1 ≡ v2) →\n      existT i1 v1 ≡ existT i2 v2.\n  Proof. intros Heq Heqv n. apply (existT_ne n Heq), equiv_dist, Heqv. Qed.\n\n  (** [existT] is \"non-expansive\" — non-dependently-typed version. *)\n  Global Instance existT_ne_2 a : NonExpansive (@existT A P a).\n  Proof. move => ??? Heq. apply (existT_ne _ eq_refl Heq). Qed.\n\n  Global Instance existT_proper_2 a : Proper ((≡) ==> (≡)) (@existT A P a).\n  Proof. apply ne_proper, _. Qed.\n\n  Implicit Types (c : chain sigTO).\n\n  Global Instance sigT_discrete x : Discrete (projT2 x) → Discrete x.\n  Proof.\n    move: x => [xa x] ? [ya y] [] /=; intros -> => /= Hxy n.\n    exists eq_refl => /=. apply equiv_dist, (discrete _), Hxy.\n  Qed.\n\n  Global Instance sigT_ofe_discrete : (∀ a, OfeDiscrete (P a)) → OfeDiscrete sigTO.\n  Proof. intros ??. apply _. Qed.\n\n  Lemma sigT_chain_const_proj1 c n : projT1 (c n) = projT1 (c 0).\n  Proof. refine (sigT_dist_proj1 _ (chain_cauchy c 0 n _)). lia. Qed.\n\n  (* For this COFE construction we need UIP (Uniqueness of Identity Proofs)\n    on [A] (i.e. [∀ x y : A, ProofIrrel (x = y)]. UIP is most commonly obtained\n    from decidable equality (by Hedberg’s theorem, see\n    [stdpp.proof_irrel.eq_pi]). *)\n  Section cofe.\n    Context `{!∀ a b : A, ProofIrrel (a = b)} `{!∀ a, Cofe (P a)}.\n\n    Program Definition chain_map_snd c : chain (P (projT1 (c 0))) :=\n      {| chain_car n := rew (sigT_chain_const_proj1 c n) in projT2 (c n) |}.\n    Next Obligation.\n      move => c n i Hle /=.\n      (* [Hgoal] is our thesis, up to casts: *)\n      case: (chain_cauchy c n i Hle) => [Heqin Hgoal] /=.\n      (* Pretty delicate. We have two casts to [projT1 (c 0)].\n        We replace those by one cast. *)\n      move: (sigT_chain_const_proj1 c i) (sigT_chain_const_proj1 c n)\n        => Heqi0 Heqn0.\n      (* Rewrite [projT1 (c 0)] to [projT1 (c n)] in goal and [Heqi0]: *)\n      destruct Heqn0.\n      by rewrite /= (proof_irrel Heqi0 Heqin).\n    Qed.\n\n    Definition sigT_compl : Compl sigTO :=\n      λ c, existT (projT1 (chain_car c 0)) (compl (chain_map_snd c)).\n\n    Global Program Instance sigT_cofe : Cofe sigTO := { compl := sigT_compl }.\n    Next Obligation.\n      intros n c. rewrite /sigT_compl sigT_dist_eq /=.\n      exists (symmetry (sigT_chain_const_proj1 c n)).\n      (* Our thesis, up to casts: *)\n      pose proof (conv_compl n (chain_map_snd c)) as Hgoal.\n      move: (compl (chain_map_snd c)) Hgoal => pc0 /=.\n      destruct (sigT_chain_const_proj1 c n); simpl. done.\n    Qed.\n  End cofe.\nEnd sigT.\n\nGlobal Arguments sigTO {_} _.\n\nSection sigTOF.\n  Context {A : Type}.\n\n  Program Definition sigT_map {P1 P2 : A → ofe} :\n    discrete_funO (λ a, P1 a -n> P2 a) -n>\n    sigTO P1 -n> sigTO P2 :=\n    λne f xpx, existT _ (f _ (projT2 xpx)).\n  Next Obligation.\n    move => ?? f n [x px] [y py] [/= Heq]. destruct Heq; simpl.\n    exists eq_refl => /=. by f_equiv.\n  Qed.\n  Next Obligation.\n    move => ?? n f g Heq [x px] /=. exists eq_refl => /=. apply Heq.\n  Qed.\n\n  Program Definition sigTOF (F : A → oFunctor) : oFunctor := {|\n    oFunctor_car A CA B CB := sigTO (λ a, oFunctor_car (F a) A B);\n    oFunctor_map A1 _ A2 _ B1 _ B2 _ fg := sigT_map (λ a, oFunctor_map (F a) fg)\n  |}.\n  Next Obligation.\n    repeat intro. exists eq_refl => /=. solve_proper.\n  Qed.\n  Next Obligation.\n    simpl; intros. apply (existT_proper eq_refl), oFunctor_map_id.\n  Qed.\n  Next Obligation.\n    simpl; intros. apply (existT_proper eq_refl), oFunctor_map_compose.\n  Qed.\n\n  Global Instance sigTOF_contractive {F} :\n    (∀ a, oFunctorContractive (F a)) → oFunctorContractive (sigTOF F).\n  Proof.\n    repeat intro. apply sigT_map => a. exact: oFunctor_map_contractive.\n  Qed.\nEnd sigTOF.\nGlobal Arguments sigTOF {_} _%OF.\n\nNotation \"{ x  &  P }\" := (sigTOF (λ x, P%OF)) : oFunctor_scope.\nNotation \"{ x : A &  P }\" := (@sigTOF A%type (λ x, P%OF)) : oFunctor_scope.\n\n(** * Isomorphisms between OFEs *)\nRecord ofe_iso (A B : ofe) := OfeIso {\n  ofe_iso_1 : A -n> B;\n  ofe_iso_2 : B -n> A;\n  ofe_iso_12 y : ofe_iso_1 (ofe_iso_2 y) ≡ y;\n  ofe_iso_21 x : ofe_iso_2 (ofe_iso_1 x) ≡ x;\n}.\nGlobal Arguments OfeIso {_ _} _ _ _ _.\nGlobal Arguments ofe_iso_1 {_ _} _.\nGlobal Arguments ofe_iso_2 {_ _} _.\nGlobal Arguments ofe_iso_12 {_ _} _ _.\nGlobal Arguments ofe_iso_21 {_ _} _ _.\n\nSection ofe_iso.\n  Context {A B : ofe}.\n\n  Local Instance ofe_iso_equiv : Equiv (ofe_iso A B) := λ I1 I2,\n    ofe_iso_1 I1 ≡ ofe_iso_1 I2 ∧ ofe_iso_2 I1 ≡ ofe_iso_2 I2.\n\n  Local Instance ofe_iso_dist : Dist (ofe_iso A B) := λ n I1 I2,\n    ofe_iso_1 I1 ≡{n}≡ ofe_iso_1 I2 ∧ ofe_iso_2 I1 ≡{n}≡ ofe_iso_2 I2.\n\n  Global Instance ofe_iso_1_ne : NonExpansive (ofe_iso_1 (A:=A) (B:=B)).\n  Proof. by destruct 1. Qed.\n  Global Instance ofe_iso_2_ne : NonExpansive (ofe_iso_2 (A:=A) (B:=B)).\n  Proof. by destruct 1. Qed.\n\n  Lemma ofe_iso_ofe_mixin : OfeMixin (ofe_iso A B).\n  Proof. by apply (iso_ofe_mixin (λ I, (ofe_iso_1 I, ofe_iso_2 I))). Qed.\n  Canonical Structure ofe_isoO : ofe := Ofe (ofe_iso A B) ofe_iso_ofe_mixin.\n\n  Global Instance ofe_iso_cofe `{!Cofe A, !Cofe B} : Cofe ofe_isoO.\n  Proof.\n    apply (iso_cofe_subtype'\n      (λ I : prodO (A -n> B) (B -n> A),\n        (∀ y, I.1 (I.2 y) ≡ y) ∧ (∀ x, I.2 (I.1 x) ≡ x))\n      (λ I HI, OfeIso (I.1) (I.2) (proj1 HI) (proj2 HI))\n      (λ I, (ofe_iso_1 I, ofe_iso_2 I))); [by intros []|done|done|].\n    apply limit_preserving_and; apply limit_preserving_forall=> ?;\n      apply limit_preserving_equiv; first [intros ???; done|solve_proper].\n  Qed.\nEnd ofe_iso.\n\nGlobal Arguments ofe_isoO : clear implicits.\n\nProgram Definition iso_ofe_refl {A} : ofe_iso A A := OfeIso cid cid _ _.\nSolve Obligations with done.\n\nDefinition iso_ofe_sym {A B : ofe} (I : ofe_iso A B) : ofe_iso B A :=\n  OfeIso (ofe_iso_2 I) (ofe_iso_1 I) (ofe_iso_21 I) (ofe_iso_12 I).\nGlobal Instance iso_ofe_sym_ne {A B} : NonExpansive (iso_ofe_sym (A:=A) (B:=B)).\nProof. intros n I1 I2 []; split; simpl; by f_equiv. Qed.\n\nProgram Definition iso_ofe_trans {A B C}\n    (I : ofe_iso A B) (J : ofe_iso B C) : ofe_iso A C :=\n  OfeIso (ofe_iso_1 J ◎ ofe_iso_1 I) (ofe_iso_2 I ◎ ofe_iso_2 J) _ _.\nNext Obligation. intros A B C I J z; simpl. by rewrite !ofe_iso_12. Qed.\nNext Obligation. intros A B C I J z; simpl. by rewrite !ofe_iso_21. Qed.\nGlobal Instance iso_ofe_trans_ne {A B C} : NonExpansive2 (iso_ofe_trans (A:=A) (B:=B) (C:=C)).\nProof. intros n I1 I2 [] J1 J2 []; split; simpl; by f_equiv. Qed.\n\nProgram Definition iso_ofe_cong (F : oFunctor) `{!Cofe A, !Cofe B}\n    (I : ofe_iso A B) : ofe_iso (oFunctor_apply F A) (oFunctor_apply F B) :=\n  OfeIso (oFunctor_map F (ofe_iso_2 I, ofe_iso_1 I))\n    (oFunctor_map F (ofe_iso_1 I, ofe_iso_2 I)) _ _.\nNext Obligation.\n  intros F A ? B ? I x. rewrite -oFunctor_map_compose -{2}(oFunctor_map_id F x).\n  apply equiv_dist=> n.\n  apply oFunctor_map_ne; split=> ? /=; by rewrite ?ofe_iso_12 ?ofe_iso_21.\nQed.\nNext Obligation.\n  intros F A ? B ? I y. rewrite -oFunctor_map_compose -{2}(oFunctor_map_id F y).\n  apply equiv_dist=> n.\n  apply oFunctor_map_ne; split=> ? /=; by rewrite ?ofe_iso_12 ?ofe_iso_21.\nQed.\nGlobal Instance iso_ofe_cong_ne (F : oFunctor) `{!Cofe A, !Cofe B} :\n  NonExpansive (iso_ofe_cong F (A:=A) (B:=B)).\nProof. intros n I1 I2 []; split; simpl; by f_equiv. Qed.\nGlobal Instance iso_ofe_cong_contractive (F : oFunctor) `{!Cofe A, !Cofe B} :\n  oFunctorContractive F → Contractive (iso_ofe_cong F (A:=A) (B:=B)).\nProof. intros ? n I1 I2 HI; split; simpl; f_contractive; by destruct HI. 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/ofe.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.285220232519147}}
{"text": "Require Import id_and_loc mmemory mlattice mimperative types language LibTactics tactics Coq.Program.Tactics Coq.Program.Equality.\n\nModule Augmented (L: Lattice) (M: Memory L).\n  Module Imp := Imperative L M.\n  Import Imp TDefs M T LatProp Lang L.\n  \n  Inductive event  :=\n  | EmptyEvent : event\n  | AssignEvent : level_proj1 -> id -> value -> event\n  | NewEvent : level_proj1 -> id -> loc -> event\n  | GetEvent : level_proj1 -> id -> id -> value -> event\n  | SetEvent : level_proj1 -> level_proj1 -> id -> nat -> value -> event\n  | TimeEvent : level_proj1 -> id -> nat -> event\n  | RestoreEvent: level_proj1 -> nat -> event.\n  Hint Constructors event.\n\n  Lemma eq_event_dec:\n    forall ev1 ev2 : event,\n      {ev1 = ev2} + {ev1 <> ev2}.\n  Proof.\n    repeat decide equality.\n  Defined.\n\n  Definition onvals (φ: loc -> option loc) (v: value) :=\n    match v with\n    | ValNum n => Some (ValNum n)\n    | ValLoc l =>\n      match φ l with\n      | Some l' => Some (ValLoc l')\n      | None => None\n      end\n    end.\n  Hint Unfold onvals.\n  \n  Inductive iso_events: (loc -> option loc) -> event -> event -> Prop :=\n  | IsoEventEmpty:\n      forall φ,\n        iso_events φ EmptyEvent EmptyEvent\n  | IsoEventAssign:\n      forall φ ℓ x v1 v2,\n        onvals φ v1 = Some v2 ->\n        iso_events φ (AssignEvent ℓ x v1) (AssignEvent ℓ x v2)\n  | IsoEventNew:\n      forall φ x ℓ l1 l2 l,\n        (φ l1 = Some l -> l = l2) ->\n        iso_events φ (NewEvent ℓ x l1) (NewEvent ℓ x l2)\n  | IsoEventGet:\n      forall φ ℓ_x x y v1 v2,\n        onvals φ v1 = Some v2 ->\n        iso_events φ (GetEvent ℓ_x x y v1) (GetEvent ℓ_x x y v2)\n  | IsoEventSet:\n      forall φ ℓ ℓ_x x n v1 v2,\n        onvals φ v1 = Some v2 ->\n        iso_events φ (SetEvent ℓ ℓ_x x n v1) (SetEvent ℓ ℓ_x x n v2)\n  | IsoEventTime:\n      forall φ ℓ x n,\n        iso_events φ (TimeEvent ℓ x n) (TimeEvent ℓ x n)\n  | IsoEventRestore:\n      forall ℓ n φ,\n        iso_events φ (RestoreEvent ℓ n) (RestoreEvent ℓ n).\n  Hint Constructors iso_events.\n\nInductive event_sem_step : config -> config -> tenv -> stenv -> stenv -> event -> Prop :=\n | event_sem_step_skip:\n     forall Γ Σ Σ' pc m h t t',\n       sem_step (Config Skip pc m h t) (Config Stop pc m h t') Γ Σ Σ' ->\n       event_sem_step (Config Skip pc m h t) (Config Stop pc m h t') Γ Σ Σ' EmptyEvent\n | event_sem_step_assign:\n     forall Γ Σ Σ' pc m m' h x e v t t' τ ℓ ι,\n       eval m e = Some v ->\n       Γ x = Some (SecType τ (ℓ, ι)) ->\n       sem_step (Config (Assign x e) pc m h t) (Config Stop pc m' h t') Γ Σ Σ' ->\n       event_sem_step (Config (Assign x e) pc m h t) (Config Stop pc m' h t') Γ Σ Σ'\n                  (AssignEvent ℓ x v)\n | event_sem_step_if:\n     forall Γ Σ Σ' pc m h e c1 c2 c' t t',\n       sem_step (Config (If e c1 c2) pc m h t) (Config c' pc m h t') Γ Σ Σ' ->\n       event_sem_step (Config (If e c1 c2) pc m h t) (Config c' pc m h t') Γ Σ Σ'\n                  EmptyEvent\n | event_sem_step_while:\n     forall Γ Σ Σ' pc m h e c c' t t',\n       sem_step (Config (While e c) pc m h t) (Config c' pc m h t') Γ Σ Σ' ->\n       event_sem_step (Config (While e c) pc m h t) (Config c' pc m h t') Γ Σ Σ' EmptyEvent\n | event_sem_step_seq_nonstop:\n     forall Γ Σ Σ' pc pc' m m' h h' c1 c2 c1' t t' ev,\n       event_step (Config c1 pc m h t) (Config c1' pc' m' h' t') Γ Σ Σ' ev ->\n       c1' <> Stop ->\n       c1' <> TimeOut ->\n       event_sem_step (Config (Seq c1 c2) pc m h t) (Config (Seq c1' c2) pc' m' h' t') Γ Σ Σ' ev\n | event_sem_step_seq_stop:\n     forall Γ Σ Σ' pc pc' m m' h h' c1 c2 t t' ev,\n       event_step (Config c1 pc m h t) (Config Stop pc' m' h' t') Γ Σ Σ' ev ->\n       event_sem_step (Config (Seq c1 c2) pc m h t) (Config c2 pc' m' h' t') Γ Σ Σ' ev\n | event_sem_step_time:\n     forall Γ Σ Σ' pc m m' h t t' x τ ℓ ι,\n       Γ x = Some (SecType τ (ℓ, ι)) ->\n       sem_step (Config (Time x) pc m h t) (Config Stop pc m' h t') Γ Σ Σ' ->\n       event_sem_step (Config (Time x) pc m h t) (Config Stop pc m' h t') Γ Σ Σ'\n                  (TimeEvent ℓ x t)\n | event_sem_step_new:\n     forall Γ Σ Σ' pc m h t t' e e_init level x l τ ℓ h' ι,\n       Γ x = Some (SecType τ (ℓ, ι)) ->\n       sem_step (Config (NewArr x level e e_init) pc m h t)\n            (Config Stop pc (extend_memory x (ValLoc l) m) h' t') Γ Σ Σ' ->\n       event_sem_step (Config (NewArr x level e e_init) pc m h t)\n                  (Config Stop pc (extend_memory x (ValLoc l) m) h' t') Γ Σ Σ'\n                  (NewEvent ℓ x l)\n | event_sem_step_get:\n     forall Γ Σ Σ' pc m m' h t t' x y e l n v τ_x ℓ_x τ_y ℓ_y ι μ ℓ,\n       Γ x = Some (SecType τ_x (ℓ_x, ι)) ->\n       Γ y = Some (SecType τ_y ℓ_y) ->\n       memory_lookup m y = Some (ValLoc l) ->\n       eval m e = Some (ValNum n) ->\n       heap_lookup l h = Some (ℓ, μ) ->\n       lookup μ n = Some v ->\n       sem_step (Config (GetArr x y e) pc m h t) (Config Stop pc m' h t') Γ Σ Σ' ->\n       event_sem_step (Config (GetArr x y e) pc m h t) (Config Stop pc m' h t') Γ Σ Σ'\n                  (GetEvent ℓ_x x y v)\n | event_sem_step_set:\n     forall Γ Σ Σ' pc m h h' t t' x e1 e2 l n v τ ℓ ι ℓ_p ℓ_x ι_x,\n       memory_lookup m x = Some (ValLoc l) ->\n       Γ x = Some (SecType (Array (SecType τ (ℓ, ι)) ℓ_p) (ℓ_x, ι_x)) ->\n       eval m e1 = Some (ValNum n) ->\n       eval m e2 = Some v ->\n       sem_step (Config (SetArr x e1 e2) pc m h t) (Config Stop pc m h' t') Γ Σ Σ' ->\n       event_sem_step (Config (SetArr x e1 e2) pc m h t)\n                  (Config Stop pc m h' t') Γ Σ Σ' (SetEvent ℓ ℓ_x x n v)\n | event_sem_step_at:\n     forall Γ Σ Σ' pc m h t t' level c c' e,\n       sem_step (Config (At level e c) pc m h t) (Config c' level m h t') Γ Σ Σ' ->\n       event_sem_step (Config (At level e c) pc m h t) (Config c' level m h t') Γ Σ Σ' EmptyEvent\n | event_sem_step_backat_wait:\n     forall Γ Σ Σ' pc pc' m h t t' c' level n,\n       t < n ->\n       sem_step (Config (BackAt level n) pc m h t) (Config c' pc' m h t') Γ Σ Σ' ->\n       event_sem_step (Config (BackAt level n) pc m h t) (Config c' pc' m h t') Γ Σ Σ' EmptyEvent\n | event_sem_step_backat_progress:\n     forall Γ Σ Σ' pc pc' m h t t' c' level,\n       sem_step (Config (BackAt level t) pc m h t) (Config c' pc' m h t') Γ Σ Σ' ->\n       event_sem_step (Config (BackAt level t) pc m h t) (Config c' pc' m h t') Γ Σ Σ' (RestoreEvent pc' t)\n | event_sem_step_backat_timeout:\n     forall Γ Σ Σ' pc pc' m h t t' c' level n,\n       n < t ->\n       sem_step (Config (BackAt level n) pc m h t) (Config c' pc' m h t') Γ Σ Σ' ->\n       event_sem_step (Config (BackAt level n) pc m h t) (Config c' pc' m h t') Γ Σ Σ' (RestoreEvent pc' t)\nwith event_step: config -> config -> tenv -> stenv -> stenv -> event -> Prop :=\n     | EventSemStep:\n         forall c c' pc pc' m m' h h' t t' Γ Σ Σ' ev,\n           event_sem_step (Config c pc m h t) (Config c' pc' m' h' t') Γ Σ Σ' ev ->\n           event_step (Config c pc m h t) (Config c' pc' m' h' t') Γ Σ Σ' ev\n     | EventGCStep:\n           forall c c' pc pc' m m' h h' t t' Γ Σ Σ',\n             gc_step (Config c pc m h t) (Config c' pc' m' h' t') Γ Σ Σ' ->\n             event_step (Config c pc m h t) (Config c' pc' m' h' t') Γ Σ Σ' EmptyEvent.\nHint Constructors event_step.\nHint Constructors event_sem_step.\n\nScheme event_sem_step_mut := Induction for event_sem_step Sort Prop\n                       with event_step_mut := Induction for event_step Sort Prop.\n\nNotation \"cfg '⇒' '[' evt ',' Γ ',' Σ ',' Σ2 ']' cfg'\":=\n  (event_step cfg cfg' Γ Σ Σ2 evt) (at level 0).\n\nLtac invert_event_sem_step:=\n    match goal with [ H : event_sem_step _ _ _ _ _ _ |-  _ ] => inverts H end.\n  \n  Ltac invert_event_step:=\n    match goal with [ H : _ ⇒ [_, _, _, _] _ |-  _ ] => inverts H; [> invert_event_sem_step | invert_gc_step] end.\n\n  Ltac invert_wt_stop :=\n    match goal with\n      [H: wt_aux _ _ Stop _ |- _] => inverts H\n    end.\n  \nLemma event_step_if_does_not_step_to_stop:\n  forall e c1 c2 pc m h t ev Γ Σ Σ' pc' m' h' t' pc'',\n    wellformed_aux Γ Σ ⟨If e c1 c2, pc, m, h, t⟩ pc'' ->\n    ⟨If e c1 c2, pc, m, h, t⟩ ⇒ [ev, Γ, Σ, Σ'] ⟨Stop, pc', m', h', t'⟩ -> False.\nProof.\n  intros.\n  invert_event_step.\n  invert_sem_step.\n  - invert_wf_aux.\n    do 2 specialize_gen.\n    invert_wt_cmd.\n    invert_wt_stop.\n  - invert_wf_aux.\n    do 2 specialize_gen.\n    invert_wt_cmd.\n    invert_wt_stop.\nQed.\nHint Resolve event_step_if_does_not_step_to_stop.\n\nLemma if_event_step_properties:\n  forall Γ Σ Σ' e c1 c2 pc m h t c' pc' m' h' t',\n    ⟨If e c1 c2, pc, m, h, t⟩ ⇒ (Γ, Σ, Σ') ⟨c', pc', m', h', t'⟩ ->\n    ((exists k, eval m e = Some (ValNum k) /\\ k <> 0 /\\ c' = c1) \\/\n     (eval m e = Some (ValNum 0) /\\ c' = c2)) \\/\n    gc_occurred (If e c1 c2) c' pc pc' m m' h h' t t' Σ Σ'.\nProof.\n  intros.\n  invert_step.\n  - left; right.\n    eauto.\n  - left; left.\n    eauto.\n  - right.\n    unfolds.\n    splits*.\n    do 7 eexists.\n    splits; reflexivity || eauto.\nQed.\n\nLemma if_does_not_have_fixed_points1:\n    forall e c1 c2,\n      If e c1 c2 <> c1.\n  Proof.\n    intros.\n    constructors_dont_have_fixed_points c1.\n  Qed.\n  Hint Resolve if_does_not_have_fixed_points1.\n\n  Lemma if_does_not_have_fixed_points2:\n    forall e c1 c2,\n      If e c1 c2 <> c2.\n  Proof.\n    intros.\n    constructors_dont_have_fixed_points c2.\n  Qed.\n  Hint Resolve if_does_not_have_fixed_points2.\n\n  Lemma seq_does_not_have_fixed_points1:\n    forall c1 c2,\n      c1 <> (c1;; c2).\n  Proof.\n    constructors_dont_have_fixed_points c1.\n  Qed.\n  Hint Resolve seq_does_not_have_fixed_points1.\n  \n  Lemma seq_does_not_have_fixed_points2:\n    forall c1 c2,\n      c2 <> (c1;; c2).\n  Proof.\n    constructors_dont_have_fixed_points c2.\n  Qed.\n  Hint Resolve seq_does_not_have_fixed_points2.\n\n  Lemma event_step_adequacy:\n    forall c c' pc pc' pc'' m m' h h' t t' Γ Σ Σ',\n      wellformed_aux Γ Σ ⟨c, pc, m, h, t⟩ pc'' ->\n      ⟨c, pc, m, h, t⟩ ⇒ (Γ, Σ, Σ') ⟨c', pc', m', h', t'⟩ ->\n      exists ev,\n        ⟨c, pc, m, h, t⟩ ⇒ [ev, Γ, Σ, Σ'] ⟨c', pc', m', h', t'⟩.\n  Proof.\n    intros.\n    inverts H0; eauto.\n    revert c' pc pc' pc'' m m' h h' t t' Σ Σ' H H14.\n    induction c; intros; try solve[invert_sem_step; eauto].\n    - invert_sem_step.\n      invert_wf_aux.\n      repeat specialize_gen.\n      invert_wt_cmd.\n      invert_lifted.\n      destruct l2.\n      eauto.\n    - invert_sem_step.\n      + assert (exists pc'', wellformed_aux Γ Σ ⟨c1, pc, m, h, t⟩ pc'') by eauto.\n        super_destruct.\n        inverts_step; eauto.\n        * assert (exists ev, (⟨ c1, pc, m, h, t ⟩) ⇒ [ev, Γ, Σ, Σ'] (⟨ Stop, pc', m', h', t' ⟩)) by eauto 2.\n          super_destruct.\n          eauto.\n      + assert (exists pc'', wellformed_aux Γ Σ ⟨c1, pc, m, h, t⟩ pc'') by eauto.\n        inverts_step; eauto.\n        super_destruct.\n        assert (exists ev, (⟨ c1, pc, m, h, t ⟩) ⇒ [ev, Γ, Σ, Σ'] (⟨ c1', pc', m', h', t' ⟩)) by eauto 2.\n        super_destruct.\n        eauto.\n    - invert_sem_step.\n      destruct τ as [σ [ℓ' ι']].\n      destruct ℓ.\n      eauto.\n    - invert_sem_step.\n      invert_wf_aux.\n      do 2 specialize_gen.\n      invert_wt_cmd.\n      invert_lifted.\n      assert (exists τ, Γ i = Some τ) by eauto.\n      super_destruct.\n      destruct τ as [σ' [ℓ' ι']].\n      assert (exists ℓ μ, heap_lookup l0 h = Some (ℓ, μ)) by eauto.\n      super_destruct.\n      assert (exists τ, Σ' l0 = Some τ) by eauto.\n      super_destruct; subst.\n      assert (Σ' l0 = Some (SecType σ l2)) by eauto 2.\n      rewrite_inj.\n      destruct l2.\n      eauto.\n    - invert_sem_step.\n      invert_wf_aux.\n      assert (exists τ, Γ i0 = Some τ) by eauto.\n      super_destruct.\n      destruct t0.\n      destruct τ.\n      destruct t1.\n      eauto.\n    - invert_sem_step.\n      invert_wf_aux.\n      do 2 specialize_gen.\n      invert_wt_cmd.\n      eauto.\n  Qed.\n\nEnd Augmented.\n", "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/augmented.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017746, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.28517847193940576}}
{"text": "From Perennial.program_proof.mvcc Require Import\n     txn_prelude txn_repr tuple_repr\n     wrbuf_proof index_proof tuple_read_version proph_proof.\n\nSection lemma.\nContext `{!heapGS Σ, !mvcc_ghostG Σ}.\n\n#[local]\nLemma ltuple_ptuple_ptsto_eq {γ key tmods ts m past} tid v1 v2 :\n  per_key_inv_def γ key tmods ts m past -∗\n  ltuple_ptsto γ key v1 tid -∗\n  ptuple_ptsto γ key v2 tid -∗\n  ⌜v1 = v2⌝.\nProof.\n  iIntros \"Hkey Hlpts Hppts\".\n  iNamed \"Hkey\".\n  apply tuple_mods_rel_prefix in Htmrel.\n  iDestruct \"Hlpts\" as (logi') \"[Hllb %Hv1]\".\n  iDestruct \"Hppts\" as (phys') \"[Hplb %Hv2]\".\n  iDestruct (ltuple_prefix with \"Hltuple Hllb\") as \"%Hl\".\n  iDestruct (ptuple_prefix with \"Hptuple Hplb\") as \"%Hp\".\n  iPureIntro.\n  unshelve epose proof (prefix_lookup logi' logi tid v1 _ _); [done | done |].\n  unshelve epose proof (prefix_lookup phys' phys tid v2 _ _); [done | done |].\n  unshelve epose proof (prefix_lookup phys logi tid v2 _ _); [done | done |].\n  rewrite H in H1. by inversion H1.\nQed.\n\nEnd lemma.\n\nSection program.\nContext `{!heapGS Σ, !mvcc_ghostG Σ}.\n\n(*****************************************************************)\n(* func (txn *Txn) Get(key uint64) (string, bool)                *)\n(*****************************************************************)\nTheorem wp_txn__Get txn tid view (k : u64) dbv γ τ :\n  {{{ own_txn txn tid view γ τ ∗ txnmap_ptsto τ k dbv }}}\n    Txn__Get #txn #k\n  {{{ (v : string) (found : bool), RET (#(LitString v), #found);\n      own_txn txn tid view γ τ ∗ txnmap_ptsto τ k dbv ∗ ⌜dbv = to_dbval found v⌝\n  }}}.\nProof.\n  iIntros (Φ) \"[Htxn Hptsto] HΦ\".\n  (* We need this to obtain a lb on logical tuple of key [k]. *)\n  iDestruct (own_txn_txnmap_ptsto_dom with \"Htxn Hptsto\") as \"%Hindom\".\n  iNamed \"Htxn\".\n  iNamed \"Himpl\".\n  wp_call.\n\n  (***********************************************************)\n  (* wrbuf := txn.wrbuf                                      *)\n  (* valb, wr, found := wrbuf.Lookup(key)                    *)\n  (***********************************************************)\n  wp_loadField.\n  wp_pures.\n  wp_apply (wp_wrbuf__Lookup with \"HwrbufRP\").\n  iIntros (v d ok) \"[HwrbufRP %Hlookup]\".\n  wp_pures.\n\n  (***********************************************************)\n  (* if found {                                              *)\n  (*     return valb, wr                                     *)\n  (* }                                                       *)\n  (***********************************************************)\n  unfold spec_wrbuf__Lookup in Hlookup.\n  wp_if_destruct.\n  { wp_pures.\n    iModIntro.\n    iApply \"HΦ\".\n    iDestruct (txnmap_lookup with \"Htxnmap Hptsto\") as \"%Hlookup'\".\n    apply (lookup_union_Some_l _ view) in Hlookup.\n    rewrite Hlookup' in Hlookup.\n    inversion_clear Hlookup.\n    iSplitR \"Hptsto\".\n    { eauto 25 with iFrame. }\n    by iFrame.\n  }\n\n  (***********************************************************)\n  (* idx := txn.idx                                          *)\n  (* tuple := idx.GetTuple(key)                              *)\n  (***********************************************************)\n  wp_loadField.\n  wp_pures.\n  wp_apply (wp_index__GetTuple with \"HidxRI\").\n  iIntros (tuple) \"#HtupleRI\".\n  wp_pures.\n\n  (***********************************************************)\n  (* tuple.ReadWait(txn.tid)                                 *)\n  (***********************************************************)\n  wp_loadField.\n  wp_apply (wp_tuple__ReadWait with \"HtupleRI\").\n  iIntros (owned vchain) \"(Htuple & HtupleOwn & Hptuple & %Hwait)\".\n  wp_pures.\n\n  (***********************************************************)\n  (* proph.ResolveRead(txn.txnMgr.p, txn.tid, key)           *)\n  (***********************************************************)\n  do 3 wp_loadField.\n  wp_apply (wp_ResolveRead γ); first auto.\n  iInv \"Hinv\" as \"> HinvO\" \"HinvC\".\n  iApply ncfupd_mask_intro; first set_solver.\n  iIntros \"Hclose\".\n  iNamed \"HinvO\".\n  iExists future.\n  iFrame \"Hproph\".\n  iIntros \"(%future' & %Hhead & Hproph)\".\n  (* Extend the physical tuple. *)\n  unfold ptuple_auth_owned.\n  (* iMod (tuple_read_safe with \"Hkeys Hcmt Hread\") as \"(Hkeys & Hcmt & Htuple & Hptuple)\"; first set_solver. *)\n  set Ψ := (λ key, per_key_inv_def γ key tmods ts m (past ++ [ActRead tid k]))%I.\n  iDestruct (big_sepS_elem_of_acc_impl k with \"Hkeys\") as \"[Hkey Hkeys]\"; first set_solver.\n  iRename \"Hptuple\" into \"Hptuple'\".\n  iDestruct (cmt_inv_fcc_tmods with \"Hcmt\") as \"%Hcmtfcc\".\n  iAssert (|==> ptuple_auth_owned γ k owned (extend (S tid) vchain) ∗ Ψ k)%I\n    with \"[Hptuple' Hkey]\" as \"> [Hptuple Hkey]\".\n  { destruct Hwait as [Howned | Hlen].\n    - (* Case [owned = 0]. *)\n      unfold ptuple_auth_owned.\n      rewrite Howned.\n      iNamed \"Hkey\".\n      iDestruct (ptuple_agree with \"Hptuple Hptuple'\") as \"%Eptuple\".\n      subst vchain.\n      iMod (vchain_update (extend (S tid) phys) with \"Hptuple Hptuple'\") as \"[Hptuple Hptuple']\".\n      { apply extend_prefix. }\n      iModIntro.\n      iFrame \"Hptuple'\".\n      subst Ψ. simpl.\n      do 2 iExists _.\n      (* Get a lb on [logi] required by [tuplext_read]. *)\n      rewrite elem_of_dom in Hindom. destruct Hindom as [u Hlookup'].\n      iDestruct (big_sepM_lookup _ _ k with \"Hltuples\") as (logi') \"[#Hlb %Hlen]\"; first done.\n      apply lookup_lt_Some in Hlen.\n      iDestruct (ltuple_prefix with \"Hltuple Hlb\") as \"%Hprefix\".\n      apply prefix_length in Hprefix.\n      iFrame \"∗ %\".\n      iPureIntro.\n      split.\n      { (* Prove [tuple_mods_rel] (i.e., safe extension). *)\n        apply tuplext_read; [lia | | done].\n        apply fcc_head_read_le_all with future; [done | set_solver].\n      }\n      { (* Prove [ptuple_past_rel]. *)\n        apply ptuple_past_rel_read_lt_len.\n        { (* Note: [x < y] is a notation for [S x ≤ y]. *)\n          apply extend_length_ge_n.\n          by eapply tuple_mods_rel_last_phys.\n        }\n        apply (ptuple_past_rel_extensible _ phys); last done.\n        apply extend_prefix.\n      }\n    - (* Case [tid < length vchain]. *)\n      iModIntro.\n      (* First we deduce eq between physical tuples in global and tuple invs. *)\n      iNamed \"Hkey\".\n      iDestruct (ptuple_agree with \"Hptuple Hptuple'\") as \"%Eptuple\".\n      subst vchain.\n      iSplitL \"Hptuple'\".\n      { replace (extend (S tid) phys) with phys; first done.\n        symmetry.\n        apply extend_length_same. lia.\n      }\n      subst Ψ. simpl.\n      do 2 iExists _.\n      iFrame \"∗ %\".\n      iPureIntro.\n      apply ptuple_past_rel_read_lt_len; [lia | done].\n  }\n  iDestruct (\"Hkeys\" with \"[] [Hkey]\") as \"Hkeys\"; [ | iAccu | ].\n  { (* Adding [ActRead tid k] to [past] where [key ≠ k] preserves [per_key_inv_def]. *)\n    iIntros \"!>\" (key) \"%Helem %Hneq Hkey\".\n    subst Ψ. simpl.\n    iApply per_key_inv_past_snoc_diff_key; done.\n  }\n  iMod \"Hclose\".\n  iMod (\"HinvC\" with \"[Hproph Hm Hts Hkeys Hcmt Hnca Hfa Hfci Hfcc]\") as \"_\".\n  { (* Close the inv. *)\n    iNext. unfold mvcc_inv_sst_def.\n    do 7 iExists _.\n    iExists (past ++ [ActRead tid k]), future'.\n    iDestruct (nca_inv_any_action with \"Hnca\") as \"Hnca\"; first apply Hhead.\n    iDestruct (fa_inv_diff_action  with \"Hfa\")  as \"Hfa\";  [apply Hhead | done |].\n    iDestruct (fci_inv_diff_action with \"Hfci\") as \"Hfci\"; [apply Hhead | done |].\n    iDestruct (fcc_inv_diff_action with \"Hfcc\") as \"Hfcc\"; [apply Hhead | done |].\n    iDestruct (cmt_inv_diff_action with \"Hcmt\") as \"Hcmt\"; [apply Hhead | done |].\n    by iFrame.\n  }\n  iModIntro.\n  iIntros \"_\".\n  wp_pures.\n\n  (***********************************************************)\n  (* val, found := tuple.ReadVersion(txn.tid)                *)\n  (***********************************************************)\n  wp_loadField.\n  iDestruct (is_tuple_invgc with \"HtupleRI\") as \"#Hinvgc\".\n  wp_apply (wp_tuple__ReadVersion with \"[$Hactive $Htuple $HtupleOwn Hptuple]\").\n  { rewrite Etid. iFrame. iPureIntro. destruct Hwait; [by left | word]. }\n  iIntros (val found) \"[Hactive Hpptsto]\".\n  rewrite Etid.\n  wp_pures.\n  iInv \"Hinv\" as \"> HinvO\" \"HinvC\".\n  iNamed \"HinvO\".\n  (* Deduce eq between logical and physical read. *)\n  iDestruct (big_sepS_elem_of_acc _ _ k with \"Hkeys\") as \"[Hkey Hkeys]\"; first set_solver.\n  iDestruct (txnmap_lookup with \"Htxnmap Hptsto\") as \"%Hlookup'\".\n  rewrite lookup_union_r in Hlookup'; last auto.\n  iDestruct (big_sepM_lookup with \"Hltuples\") as \"Hlptsto\"; first apply Hlookup'.\n  iDestruct (ltuple_ptuple_ptsto_eq with \"Hkey Hlptsto Hpptsto\") as \"%Heq\".\n  iDestruct (\"Hkeys\" with \"Hkey\") as \"Hkeys\".\n  iMod (\"HinvC\" with \"[Hproph Hm Hts Hkeys Hcmt Hnca Hfa Hfci Hfcc]\") as \"_\".\n  { eauto 20 with iFrame. }\n\n  (***********************************************************)\n  (* return val, found                                       *)\n  (***********************************************************)\n  iModIntro.\n  iApply \"HΦ\".\n  iSplitR \"Hptsto\".\n  { iExists _, _.\n    iFrame \"Hltuples Htxnmap Hwrbuf HwrbufRP\".\n    iSplitL; last done.\n    do 5 iExists _.\n    iFrame \"Hactive Htid Hsid\".\n    iFrame \"Hidx HidxRI Htxnmgr HtxnmgrRI Hp Hinv\".\n    done.\n  }\n  by iFrame \"Hptsto\".\nQed.\n\nEnd program.\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_get.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.28517846601314933}}
{"text": "(****************************************************************************)\n(*                                                                          *)\n(*                                                                          *)\n(*              Solange Coupet-Grimal & Catherine Nouvet                    *)\n(*                                                                          *)\n(*                                                                          *)\n(*       Laboratoire d'Informatique Fondamentale de Marseille               *)\n(*               CMI-Technopole de Chateau-Gombert                          *)\n(*                   39, Rue F. Joliot Curie                                *)\n(*                   13453 MARSEILLE Cedex 13                               *)\n(*           Contact :Solange.Coupet@cmi.univ-mrs.fr                        *)\n(*                                                                          *)\n(*                                                                          *)\n(*                                Coq V7.0                                  *)\n(*                             Septembre 2002                               *)\n(*                                                                          *)\n(****************************************************************************)\n(*                              accnotfree.v                                *)\n(****************************************************************************)\n\nSection invariant4.\n\nRequire Export lemma_step.\nRequire Export sweepnogrey.\nRequire Export rtgreyorblack.\n\nLemma acc_imp_notfree_init :\n forall s : state, init_state s -> acc_imp_notfree s.\n\nunfold acc_imp_notfree in |- *.\nintros s init n acces_s_n.\nelim acces_s_n; clear acces_s_n.\ncut (rt_grey_or_black s); unfold rt_grey_or_black in |- *.\nintro mksrt; elim mksrt; clear mksrt.\nintro mksrt; rewrite mksrt; discriminate.\nintro mksrt; rewrite mksrt; discriminate.\napply (rt_grey_or_black_init s); assumption.\nintros n0 m acces_s_m mksm hsmn0; elim init; clear init.\nintros ctls H_mark_col; elim H_mark_col; clear H_mark_col.\nintros init heap; absurd (hp s m n0 = false); auto.\nrewrite hsmn0; discriminate.\nQed.\n\n\nLemma acc_imp_notfree_addedge :\n forall s t : state, acc_imp_notfree s -> add_edge s t -> acc_imp_notfree t.\n\nunfold acc_imp_notfree in |- *.\nintros s t H_s addedge n acces_t_n.\napply (add_notfrees_notfreet s t); auto.\napply H_s; apply (add_accest_access s t); assumption.\nQed.\n\nLemma acc_imp_notfree_removeedge :\n forall s t : state,\n acc_imp_notfree s -> remove_edge s t -> acc_imp_notfree t.\n\nunfold acc_imp_notfree in |- *.\nintros s t H_s removeedge n acces_t_n.\napply (remove_notfrees_notfreet s t); auto.\napply H_s; apply (remove_accest_access s t); assumption.\nQed.\n\nLemma acc_imp_notfree_alloc :\n forall s t : state, acc_imp_notfree s -> alloc s t -> acc_imp_notfree t.\n\nunfold acc_imp_notfree in |- *.\nintros s t H_s alloc n acces_t_n.\nelim alloc; clear alloc.\nintros ctls ctlt n0 mksn0 H_fils mark add; elim mark; clear mark.\nintros mark mktn0; elim (eq_dec_node n n0).\nintro neqn0; rewrite neqn0; rewrite mktn0; discriminate.\nintro ndifn0.\nrewrite <- (mark n ndifn0).\napply H_s; apply (alloc_accest_access s t n0); auto.\nunfold update_color in |- *; auto.\nQed.\n\nLemma acc_imp_notfree_gccall :\n forall s t : state,\n nogrey_accn_imp_blackn s ->\n acc_imp_notfree s -> gc_call s t -> acc_imp_notfree t.\n\nunfold acc_imp_notfree in |- *.\nintros s t inv5_s H_s gccall.\nelim gccall; clear gccall.\nintros ctls ctlt heap H_col init n acces_t_n.\napply (initcolor_notfrees_notfreet s t); auto.\napply H_s; rewrite <- heap; assumption.\nintros ctls ctlt heap H_sons n acces_t_n.\napply (greynode_notfrees_notfreet s t n); auto.\napply H_s; elim H_sons; clear H_sons.\nintros g mksg mktg H_col1 H_col2; rewrite <- heap; assumption.\nintros ctls ctlt heap H_col m mksm mark n acces_t_n.\nelim mark; clear mark.\nintros mark mktm.\nunfold nogrey_accn_imp_blackn in inv5_s.\nrewrite <- (mark n).\nrewrite inv5_s; auto.\ndiscriminate.\nrewrite heap; assumption.\napply (noteqmar_noteqnod (mk s) n m); rewrite mksm; rewrite inv5_s; auto.\ndiscriminate.\nrewrite heap; assumption.\nQed.\n\nLemma acc_imp_notfree_marknode :\n forall s t : state, acc_imp_notfree s -> mark_node s t -> acc_imp_notfree t.\n\nunfold acc_imp_notfree in |- *.\nintros s t H_s marknode n acces_t_n.\napply (marknode_notfrees_notfreet s t); auto.\napply H_s; apply (marknode_accest_access s t); assumption.\nQed.\n\nLemma acc_imp_notfree_gcstop :\n forall s t : state, acc_imp_notfree s -> gc_stop s t -> acc_imp_notfree t.\n\nunfold acc_imp_notfree in |- *.\nintros s t H_s gcstop n acces_t_n.\napply (gcstop_notfrees_notfreet s t); auto.\napply H_s; apply (gcstop_accest_access s t); assumption.\nQed.\n\nLemma acc_imp_notfree_gcfree :\n forall s t : state,\n nogrey_accn_imp_blackn s ->\n acc_imp_notfree s -> gc_free s t -> acc_imp_notfree t.\n\nunfold acc_imp_notfree in |- *.\nunfold nogrey_accn_imp_blackn in |- *.\nintros s t inv5_s H_s gcfree n acces_t_n.\nelim gcfree; clear gcfree.\nintros ctls ctlt H_col heap m mksm mark; elim mark; clear mark.\nintros mark mktm; rewrite <- (mark n).\nrewrite inv5_s; auto.\ndiscriminate.\nrewrite <- heap; assumption.\napply (noteqmar_noteqnod (mk s) n m); rewrite mksm; rewrite inv5_s; auto.\ndiscriminate.\nrewrite <- heap; assumption.\nQed.\n\nLemma acc_imp_notfree_gcfree1 :\n forall s t : state,\n sweep_no_greys s ->\n nogrey_accn_imp_blackn s ->\n acc_imp_notfree s -> gc_free1 s t -> acc_imp_notfree t.\n\nunfold nogrey_accn_imp_blackn in |- *.\nunfold sweep_no_greys in |- *.\nunfold acc_imp_notfree in |- *.\nintros s t inv4_s inv5_s H_s gcfree1 n acces_t_n.\nelim gcfree1; clear gcfree1.\nintros ctls ctlt heap n0 mksn0 mark; elim mark; clear mark.\nintros mark mktn0; rewrite <- (mark n).\nrewrite inv5_s; auto.\ndiscriminate.\nrewrite heap; assumption.\napply (noteqmar_noteqnod (mk s) n n0); rewrite mksn0; rewrite inv5_s; auto.\ndiscriminate.\nrewrite heap; assumption.\nQed.\n\nLemma acc_imp_notfree_gcend :\n forall s t : state, acc_imp_notfree s -> gc_end s t -> acc_imp_notfree t.\n\nunfold acc_imp_notfree in |- *.\nintros s t H_s gcend n acces_t_n.\napply (gcend_notfrees_notfreet s t); auto.\napply H_s; apply (gcend_accest_access s t); assumption.\nQed.\n\nEnd invariant4.\n\nHint Immediate acc_imp_notfree_addedge.\nHint Immediate acc_imp_notfree_removeedge.\nHint Immediate acc_imp_notfree_alloc.\nHint Immediate acc_imp_notfree_gccall.\nHint Immediate acc_imp_notfree_marknode.\nHint Immediate acc_imp_notfree_gcstop.\nHint Immediate acc_imp_notfree_gcfree.\nHint Immediate acc_imp_notfree_gcfree1.\nHint Immediate acc_imp_notfree_gcend.\n\n", "meta": {"author": "coq-contribs", "repo": "gc", "sha": "ee41f2fad9fb3bbc2cbf3f90dc440cc31dbd7376", "save_path": "github-repos/coq/coq-contribs-gc", "path": "github-repos/coq/coq-contribs-gc/gc-ee41f2fad9fb3bbc2cbf3f90dc440cc31dbd7376/safety/accnotfree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.28517846601314933}}
{"text": "Require Import VerdiRaft.Raft.\nRequire Import VerdiRaft.CommonDefinitions.\n\nRequire Import VerdiRaft.LastAppliedCommitIndexMatchingInterface.\nRequire Import VerdiRaft.LogMatchingInterface.\nRequire Import VerdiRaft.StateMachineSafetyInterface.\nRequire Import VerdiRaft.MaxIndexSanityInterface.\n\nSection LastAppliedCommitIndexMatching.\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 {lmi : log_matching_interface}.\n  Context {smsi : state_machine_safety_interface}.\n  Context {misi : max_index_sanity_interface}.\n\n  Theorem lastApplied_commitIndex_match_invariant :\n    forall net,\n      raft_intermediate_reachable net ->\n      lastApplied_commitIndex_match net.\n  Proof using misi smsi lmi. \n    intros.\n    find_copy_apply_lem_hyp log_matching_invariant. unfold log_matching in *.\n    find_copy_apply_lem_hyp state_machine_safety_invariant. unfold state_machine_safety in *.\n    find_copy_apply_lem_hyp max_index_sanity_invariant. unfold maxIndex_sanity in *.\n    unfold lastApplied_commitIndex_match.\n    intuition; simpl in *.\n    - unfold log_matching_hosts in *. intuition. simpl in *.\n      match goal with\n        | H : forall (_ : name) (_ : nat), _ |- In ?e (_ (_ ?h)) =>\n          specialize (H h (eIndex e)); forward H;\n          intuition\n      end.\n      + find_apply_hyp_hyp; omega.\n      + eapply le_trans; [|eapply_prop maxIndex_commitIndex].\n        simpl. omega.\n      + break_exists. intuition.\n        match goal with\n          | _ : eIndex ?e = eIndex ?e' |- _ =>\n            cut (e = e'); [intros; subst; auto|]\n        end.\n        eapply_prop state_machine_safety_host; unfold commit_recorded; intuition eauto;\n        simpl in *; intuition.\n    - unfold log_matching_hosts in *. intuition. simpl in *.\n      match goal with\n        | H : forall (_ : name) (_ : nat), _ |- In ?e (_ (_ ?h)) =>\n          specialize (H h (eIndex e)); forward H;\n          intuition\n      end.\n      + find_apply_hyp_hyp; omega.\n      + eapply le_trans; [|eapply_prop maxIndex_lastApplied].\n        simpl. omega.\n      + break_exists. intuition.\n        match goal with\n          | _ : eIndex ?e = eIndex ?e' |- _ =>\n            cut (e = e'); [intros; subst; auto|]\n        end.\n        eapply_prop state_machine_safety_host; unfold commit_recorded; intuition eauto;\n        simpl in *; intuition.\n  Qed.\n\n  Theorem commitIndex_lastApplied_match_invariant :\n    forall net,\n      raft_intermediate_reachable net ->\n      commitIndex_lastApplied_match net.\n  Proof using misi smsi lmi. \n    intros.\n    find_copy_apply_lem_hyp log_matching_invariant. unfold log_matching in *.\n    find_copy_apply_lem_hyp state_machine_safety_invariant. unfold state_machine_safety in *.\n    find_copy_apply_lem_hyp max_index_sanity_invariant. unfold maxIndex_sanity in *.\n    unfold commitIndex_lastApplied_match.\n    intuition; simpl in *.\n    - unfold log_matching_hosts in *. intuition. simpl in *.\n      match goal with\n        | H : forall (_ : name) (_ : nat), _ |- In ?e (_ (_ ?h)) =>\n          specialize (H h (eIndex e)); forward H;\n          intuition\n      end.\n      + find_apply_hyp_hyp; omega.\n      + eapply le_trans; [|eapply_prop maxIndex_lastApplied].\n        simpl. omega.\n      + break_exists. intuition.\n        match goal with\n          | _ : eIndex ?e = eIndex ?e' |- _ =>\n            cut (e = e'); [intros; subst; auto|]\n        end.\n        eapply_prop state_machine_safety_host; unfold commit_recorded; intuition eauto;\n        simpl in *; intuition.\n    - unfold log_matching_hosts in *. intuition. simpl in *.\n      match goal with\n        | H : forall (_ : name) (_ : nat), _ |- In ?e (_ (_ ?h)) =>\n          specialize (H h (eIndex e)); forward H;\n          intuition\n      end.\n      + find_apply_hyp_hyp; omega.\n      + eapply le_trans; [|eapply_prop maxIndex_commitIndex].\n        simpl. omega.\n      + break_exists. intuition.\n        match goal with\n          | _ : eIndex ?e = eIndex ?e' |- _ =>\n            cut (e = e'); [intros; subst; auto|]\n        end.\n        eapply_prop state_machine_safety_host; unfold commit_recorded; intuition eauto;\n        simpl in *; intuition.\n  Qed.\n  \n  Theorem lastApplied_lastApplied_match_invariant :\n    forall net,\n      raft_intermediate_reachable net ->\n      lastApplied_lastApplied_match net.\n  Proof using misi smsi lmi. \n    intros.\n    find_copy_apply_lem_hyp log_matching_invariant. unfold log_matching in *.\n    find_copy_apply_lem_hyp state_machine_safety_invariant. unfold state_machine_safety in *.\n    find_copy_apply_lem_hyp max_index_sanity_invariant. unfold maxIndex_sanity in *.\n    unfold lastApplied_lastApplied_match.\n    intuition; simpl in *.\n    - unfold log_matching_hosts in *. intuition. simpl in *.\n      match goal with\n        | H : forall (_ : name) (_ : nat), _ |- In ?e (_ (_ ?h)) =>\n          specialize (H h (eIndex e)); forward H;\n          intuition\n      end.\n      + find_apply_hyp_hyp; omega.\n      + eapply le_trans; [|eapply_prop maxIndex_lastApplied].\n        simpl. omega.\n      + break_exists. intuition.\n        match goal with\n          | _ : eIndex ?e = eIndex ?e' |- _ =>\n            cut (e = e'); [intros; subst; auto|]\n        end.\n        eapply_prop state_machine_safety_host; unfold commit_recorded; intuition eauto;\n        simpl in *; intuition.\n    - unfold log_matching_hosts in *. intuition. simpl in *.\n      match goal with\n        | H : forall (_ : name) (_ : nat), _ |- In ?e (_ (_ ?h)) =>\n          specialize (H h (eIndex e)); forward H;\n          intuition\n      end.\n      + find_apply_hyp_hyp; omega.\n      + eapply le_trans; [|eapply_prop maxIndex_lastApplied].\n        simpl. omega.\n      + break_exists. intuition.\n        match goal with\n          | _ : eIndex ?e = eIndex ?e' |- _ =>\n            cut (e = e'); [intros; subst; auto|]\n        end.\n        eapply_prop state_machine_safety_host; unfold commit_recorded; intuition eauto;\n        simpl in *; intuition.\n  Qed.\n\n  Instance lacimi : lastApplied_commitIndex_match_interface.\n  split.\n  - exact lastApplied_commitIndex_match_invariant.\n  - exact commitIndex_lastApplied_match_invariant.\n  - exact lastApplied_lastApplied_match_invariant.\n  Defined.\nEnd LastAppliedCommitIndexMatching.\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/LastAppliedCommitIndexMatchingProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.28517846601314933}}
{"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.\nFrom cap_machine.rules Require Import rules_StoreU. \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 isU_nonO p p' :\n    PermFlows p p' → isU p = true → p' ≠ O.\n  Proof.\n    intros Hfl' Hra. destruct p'; auto. destruct p; inversion Hfl'. inversion Hra.\n  Qed.\n\n  Lemma wb_implies_verify_access p g:\n    ∀ b e a,\n      withinBounds ((p, g), b, e, a) = true ->\n      match (a + 0)%a with\n        | Some a' =>\n            if Addr_le_dec b a'\n            then if Addr_le_dec a' a then if Addr_lt_dec a e then Some a' else None else None\n            else None\n        | None => None\n        end = Some a. \n  Proof.\n    intros b e a Hwb. \n    rewrite /= addr_add_0 /=. \n    apply withinBounds_le_addr in Hwb as [Hle Hlt].\n    destruct (Addr_le_dec b a);[|contradiction].\n    destruct (Addr_le_dec a a);[|solve_addr].\n    destruct (Addr_lt_dec a e);[|contradiction].\n    auto. \n  Qed.\n  \n  (* store and increment *)\n  Lemma wp_storeU_success_0_reg E pc_p pc_g pc_b pc_e pc_a pc_a' w dst src w'\n         p g b e a a' w'' pc_p' p' :\n    decodeInstrW w = StoreU dst (inl 0%Z) (inr src) →\n    PermFlows pc_p pc_p' →\n    PermFlows p p' →\n    isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) →\n    (pc_a + 1)%a = Some pc_a' →\n    isU p  = true -> canStoreU p w'' = true ->\n    withinBounds ((p, g), b, e, a) = true ->\n    (a + 1)%a = Some a' ->\n    \n\n     {{{ ▷ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n           ∗ ▷ pc_a ↦ₐ[pc_p'] w\n           ∗ ▷ src ↦ᵣ w''\n           ∗ ▷ dst ↦ᵣ inr ((p,g),b,e,a)\n           ∗ ▷ a ↦ₐ[p'] w' }}}\n       Instr Executable @ E\n       {{{ RET NextIV;\n           PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a')\n              ∗ pc_a ↦ₐ[pc_p'] w\n              ∗ src ↦ᵣ w''\n              ∗ dst ↦ᵣ inr ((p,g),b,e,a')\n              ∗ a ↦ₐ[p'] w'' }}}.\n    Proof.\n      iIntros (Hinstr Hfl Hfl' Hvpc Hpca' HU HstoreU Hwb Ha' φ)\n             \"(>HPC & >Hi & >Hsrc & >Hdst & >Hsrca) Hφ\".\n    iDestruct (map_of_regs_3 with \"HPC Hsrc Hdst\") as \"[Hmap (%&%&%)]\".\n    pose proof (isU_nonO _ _ Hfl' HU) as Hp''.\n    pose proof (correctPC_nonO _ _ _ _ _ _ Hfl Hvpc) as Hpc_p'.\n    iDestruct (memMap_resource_2ne_apply with \"Hi Hsrca\") as \"[Hmem %]\"; auto.\n\n    iApply (wp_storeU _ pc_p with \"[$Hmap $Hmem]\"); eauto; simplify_map_eq; eauto.\n    { by rewrite !dom_insert; set_solver+. }\n    { rewrite HU HstoreU. erewrite wb_implies_verify_access; eauto. \n      by simplify_map_eq. }\n    iNext. iIntros (regs' mem' retv) \"(#Hspec & Hmem & Hmap)\".\n    iDestruct \"Hspec\" as %Hspec.\n\n    destruct Hspec as [ | * Hfail ].\n     { (* Success *)\n       iApply \"Hφ\".\n       simplify_map_eq.\n       erewrite wb_implies_verify_access in H11; eauto. simplify_eq.\n       rewrite insert_commute // insert_insert.\n       iDestruct (memMap_resource_2ne with \"Hmem\") as \"[Hpc_a Ha]\";auto.\n       destruct (addr_eq_dec a'0 a'0);[|contradiction]. \n       incrementPC_inv.\n       simplify_map_eq.\n       rewrite (insert_commute _ _ PC) // insert_insert.\n       rewrite (insert_commute _ _ src) // insert_insert. \n       iDestruct (regs_of_map_3 with \"[$Hmap]\") as \"[HPC [Hsrc Hdst] ]\"; eauto. iFrame. }\n     { (* Failure (contradiction) *)\n       destruct Hfail; try incrementPC_inv; simplify_map_eq; eauto.\n       all: try congruence.\n       erewrite wb_implies_verify_access in e6; eauto. simplify_eq. \n       Unshelve. all:auto. \n     }\n    Qed.\n\n  (* store and increment from and to the same register *)\n  Lemma wp_storeU_success_0_reg_same E pc_p pc_g pc_b pc_e pc_a pc_a' w dst w'\n         p g b e a a' pc_p' p' :\n    decodeInstrW w = StoreU dst (inl 0%Z) (inr dst) →\n    PermFlows pc_p pc_p' →\n    PermFlows p p' →\n    isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) →\n    (pc_a + 1)%a = Some pc_a' →\n    isU p  = true -> canStoreU p (inr (p, g, b, e, a)) = true ->\n    withinBounds ((p, g), b, e, a) = true ->\n    (a + 1)%a = Some a' ->\n\n\n     {{{ ▷ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n           ∗ ▷ pc_a ↦ₐ[pc_p'] w\n           ∗ ▷ dst ↦ᵣ inr ((p,g),b,e,a)\n           ∗ ▷ a ↦ₐ[p'] w' }}}\n       Instr Executable @ E\n       {{{ RET NextIV;\n           PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a')\n              ∗ pc_a ↦ₐ[pc_p'] w\n              ∗ dst ↦ᵣ inr ((p,g),b,e,a')\n              ∗ a ↦ₐ[p'] inr ((p,g),b,e,a)}}}.\n    Proof.\n      iIntros (Hinstr Hfl Hfl' Hvpc Hpca' HU HstoreU Hwb Ha' φ)\n             \"(>HPC & >Hi & >Hdst & >Hsrca) Hφ\".\n    iDestruct (map_of_regs_2 with \"HPC Hdst\") as \"[Hmap %]\".\n    pose proof (isU_nonO _ _ Hfl' HU) as Hp''.\n    pose proof (correctPC_nonO _ _ _ _ _ _ Hfl Hvpc) as Hpc_p'.\n    iDestruct (memMap_resource_2ne_apply with \"Hi Hsrca\") as \"[Hmem %]\"; auto.\n\n    iApply (wp_storeU _ pc_p with \"[$Hmap $Hmem]\"); eauto; simplify_map_eq; eauto.\n    { by rewrite !dom_insert; set_solver+. }\n    { unfold canStoreU. rewrite HU HstoreU. erewrite wb_implies_verify_access; eauto.\n      by simplify_map_eq. }\n    iNext. iIntros (regs' mem' retv) \"(#Hspec & Hmem & Hmap)\".\n    iDestruct \"Hspec\" as %Hspec.\n\n    destruct Hspec as [ | * Hfail ].\n     { (* Success *)\n       iApply \"Hφ\".\n       simplify_map_eq.\n       erewrite wb_implies_verify_access in H9; eauto. simplify_eq.\n       rewrite insert_commute // insert_insert.\n       iDestruct (memMap_resource_2ne with \"Hmem\") as \"[Hpc_a Ha]\";auto.\n       destruct (addr_eq_dec a'0 a'0);[|contradiction].\n       incrementPC_inv.\n       simplify_map_eq.\n       rewrite (insert_commute _ _ PC) // insert_insert.\n       rewrite insert_insert.\n       iDestruct (regs_of_map_2 with \"[$Hmap]\") as \"[HPC [Hsrc Hdst] ]\"; eauto. iFrame. }\n     { (* Failure (contradiction) *)\n       destruct Hfail; try incrementPC_inv; simplify_map_eq; eauto.\n       all: try congruence.\n       erewrite wb_implies_verify_access in e6; eauto. simplify_eq.\n       Unshelve. all:auto.\n     }\n    Qed.\n\n    Lemma wp_storeU_success_0_z E pc_p pc_g pc_b pc_e pc_a pc_a' w dst z w'\n         p g b e a a' pc_p' p' :\n    decodeInstrW w = StoreU dst (inl 0%Z) (inl z) →\n    PermFlows pc_p pc_p' →\n    PermFlows p p' →\n    isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) →\n    (pc_a + 1)%a = Some pc_a' →\n    isU p  = true -> \n    withinBounds ((p, g), b, e, a) = true ->\n    (a + 1)%a = Some a' ->\n    \n\n     {{{ ▷ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n           ∗ ▷ pc_a ↦ₐ[pc_p'] w\n           ∗ ▷ dst ↦ᵣ inr ((p,g),b,e,a)\n           ∗ ▷ a ↦ₐ[p'] w' }}}\n       Instr Executable @ E\n       {{{ RET NextIV;\n           PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a')\n              ∗ pc_a ↦ₐ[pc_p'] w\n              ∗ dst ↦ᵣ inr ((p,g),b,e,a')\n              ∗ a ↦ₐ[p'] (inl z) }}}.\n    Proof.\n      iIntros (Hinstr Hfl Hfl' Hvpc Hpca' HU Hwb Ha' φ)\n             \"(>HPC & >Hi & >Hdst & >Hsrca) Hφ\".\n    iDestruct (map_of_regs_2 with \"HPC Hdst\") as \"[Hmap %]\".\n    pose proof (isU_nonO _ _ Hfl' HU) as Hp''.\n    pose proof (correctPC_nonO _ _ _ _ _ _ Hfl Hvpc) as Hpc_p'.\n    iDestruct (memMap_resource_2ne_apply with \"Hi Hsrca\") as \"[Hmem %]\"; auto.\n\n    iApply (wp_storeU _ pc_p with \"[$Hmap $Hmem]\"); eauto; simplify_map_eq; eauto.\n    { by rewrite !dom_insert; set_solver+. }\n    { rewrite HU. erewrite wb_implies_verify_access; eauto. \n      by simplify_map_eq. }\n    iNext. iIntros (regs' mem' retv) \"(#Hspec & Hmem & Hmap)\".\n    iDestruct \"Hspec\" as %Hspec.\n\n    destruct Hspec as [ | * Hfail ].\n     { (* Success *)\n       iApply \"Hφ\".\n       simplify_map_eq.\n       erewrite wb_implies_verify_access in H9; eauto. simplify_eq.\n       rewrite insert_commute // insert_insert.\n       iDestruct (memMap_resource_2ne with \"Hmem\") as \"[Hpc_a Ha]\";auto.\n       destruct (addr_eq_dec a'0 a'0);[|contradiction]. \n       incrementPC_inv.\n       simplify_map_eq.\n       rewrite (insert_commute _ _ PC) // insert_insert. rewrite insert_insert. \n       iDestruct (regs_of_map_2 with \"[$Hmap]\") as \"[HPC Hdst]\"; eauto. iFrame. }\n     { (* Failure (contradiction) *)\n       destruct Hfail; try incrementPC_inv; simplify_map_eq; eauto.\n       all: try congruence.\n       erewrite wb_implies_verify_access in e6; eauto. simplify_eq. \n       Unshelve. all:auto. \n     }\n    Qed.\n\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_StoreU_derived.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.28517846601314933}}
{"text": "Require Import VST.msl.msl_direct.\nRequire Import CertiGraph.msl_ext.abs_addr.\nRequire Import Peano_dec.\n\nInstance Join_discrete (A : Type): Join A := fun a1 a2 a3 : A => False.\n\nInstance Perm_discrete (A: Type)  : @Perm_alg A (Join_discrete A).\nProof. constructor; intros; inv H. Qed.\n\nInstance psa_discrete (A: Type) :  @Pos_alg A  (Join_discrete A).\nProof. repeat intro. inv H. Qed.\n\n(* Definition var := nat. *)\nDefinition adr := nat.\n\nDefinition world := (fpm adr adr).\n\nInstance Join_world: Join world := Join_fpm (Join_discrete adr).\n\nInstance Perm_world : Perm_alg world. apply Perm_fpm; apply Perm_discrete. Qed.\n\nInstance Sep_world : Sep_alg world. apply Sep_fpm. Qed.\n\nInstance Canc_world : Canc_alg world. apply Canc_fpm; [intuition | repeat intro; inversion H]. Qed.\n\nInstance Disj_world : Disj_alg world. apply Disj_fpm; repeat intro; [apply Perm_discrete | |]; inversion H. Qed.\n\nInstance Cross_world : Cross_alg world. apply Cross_fpm; [apply Perm_discrete | apply psa_discrete | repeat intro; inv H]. Qed.\n\nInstance Trip_world : @Trip_alg world Join_world.\nProof.\n  repeat intro.\n  destruct ab as [fab Hab]. destruct c as [fc Hc].\n  remember (fun x => match (fab x) with\n                       | Some v => Some v\n                       | None => match (fc x) with\n                                   | Some v' => Some v'\n                                   | None => None\n                                 end\n                     end) as fabc.\n  assert (finMap fabc). {\n    hnf in Hab, Hc. destruct Hab as [lab ?]. destruct Hc as [lc ?].\n    exists (lab ++ lc). intro z; intros.\n    assert (~ In z lab). intro. apply H2. apply in_or_app. left; auto.\n    assert (~ In z lc). intro. apply H2. apply in_or_app. right; auto.\n    hnf in *. simpl in *. specialize (e0 z H4). specialize (e z H3).\n    rewrite Heqfabc. destruct (fab z) eqn:? . inv e. destruct (fc z) eqn:? . inv e0. auto.\n  } exists (exist (finMap (B:=adr)) fabc H2).\n  hnf. simpl. intros. rewrite Heqfabc. destruct (fab x) eqn:? .\n  + destruct (fc x) eqn:? .\n    - destruct a as [fa ?]. destruct b as [fb ?]. hnf in *. simpl in *.\n      specialize (H x). rewrite Heqo in *. inversion H.\n      * specialize (H0 x). rewrite H6, Heqo0 in *. inversion H0. inversion H9.\n      * specialize (H1 x). rewrite H6, Heqo0 in *. inversion H1. inversion H9.\n      * inversion H6.\n    - constructor.\n  + destruct (fc x) eqn:? .\n    - constructor.\n    - constructor.\nDefined.\n\nDefinition adr_conflict (a1 a2 : adr) : bool := if (NPeano.Nat.eq_dec a1 a2) then true else false.\n\nInstance AbsAddr_world : AbsAddr adr adr.\n  apply (mkAbsAddr adr adr adr_conflict); intros; unfold adr_conflict in *.\n  + destruct (NPeano.Nat.eq_dec p1 p2). subst. destruct (NPeano.Nat.eq_dec p2 p2); auto. exfalso; tauto.\n    destruct (NPeano.Nat.eq_dec p2 p1). subst. exfalso; tauto. trivial.\n  + destruct (NPeano.Nat.eq_dec p1 p1). inversion H. exfalso; tauto.\nDefined.\n\nFixpoint extractSome (f : adr -> option adr) (li : list adr) : list adr :=\n  match li with\n    | nil => nil\n    | x :: lx => match f x with\n                   | Some _ => x :: extractSome f lx\n                   | None => extractSome f lx\n                 end\n  end.\n\nLemma world_finite: forall w: world, exists l: list adr, forall a:adr, In a l <-> lookup_fpm w a <> None.\nProof.\n  intro; destruct w as [f [li ?]]; simpl; exists (extractSome f li); split; intros.\n  clear e; induction li; simpl in H; auto.\n  destruct (f a0) eqn: ?. destruct (in_inv H). subst. rewrite Heqo. intro. inversion H0.\n  apply IHli; auto. apply IHli; auto. destruct (in_dec nat_eq_dec a li). clear e.\n  induction li; simpl in *; auto. destruct (f a0) eqn : ?. destruct i. subst. apply in_eq.\n  apply in_cons. apply IHli; auto. destruct i. subst. exfalso; auto. apply IHli; auto.\n  specialize (e a n). exfalso; auto.\nQed.\n\nLemma lookup_fpm_join_sub: forall (w1 w2 : world) x, join_sub w1 w2 -> lookup_fpm w1 x <> None -> lookup_fpm w2 x <> None.\nProof.\n  intros. destruct H as [w3 ?].\n  destruct w1 as [f1 [l1 ?]]. destruct w2 as [f2 [l2 ?]]. destruct w3 as [f3 [l3 ?]]. hnf in H; simpl in *.\n  specialize (H x). inversion H. exfalso; auto. auto. auto.\nQed.\n", "meta": {"author": "CertiGraph", "repo": "CertiGraph", "sha": "1be51414c139f8bc16b3e22f72989e454c37ce3c", "save_path": "github-repos/coq/CertiGraph-CertiGraph", "path": "github-repos/coq/CertiGraph-CertiGraph/CertiGraph-1be51414c139f8bc16b3e22f72989e454c37ce3c/heap_model_direct/SeparationAlgebra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2851784600868928}}
{"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_Ф_addLockStake (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 DePoolContract_Ф_addVestingOrLock.\n\nLemma DePoolContract_Ф_addLockStake_exec : forall ( Л_stake : XInteger64 )\n                                                   (Л_beneficiary: XAddress)\n\t\t\t\t\t\t\t\t\t\t                               (Л_withdrawalPeriod: XInteger32)\n\t\t\t\t\t\t\t\t\t\t                               (Л_totalPeriod: XInteger32)\n                                                   (l: Ledger) , \nexec_state ( ↓ DePoolContract_Ф_addLockStake Л_stake Л_beneficiary Л_withdrawalPeriod Л_totalPeriod ) l = \nexec_state ( ↓ DePoolContract_Ф_addVestingOrLock Л_stake Л_beneficiary Л_withdrawalPeriod Л_totalPeriod xBoolFalse ) l .  \n Proof. \n  intros.\n  destructLedger l. \n  compute.\n\n  destructFunction5 DePoolContract_Ф_addVestingOrLock; auto. \n Qed. \n \n Lemma DePoolContract_Ф_addLockStake_eval : forall ( Л_stake : XInteger64 )\n                                                   (Л_beneficiary: XAddress)\n\t\t\t\t\t\t\t\t\t\t                               (Л_withdrawalPeriod: XInteger32)\n\t\t\t\t\t\t\t\t\t\t                               (Л_totalPeriod: XInteger32)\n                                                   (l: Ledger) ,\neval_state ( ↓ DePoolContract_Ф_addLockStake Л_stake Л_beneficiary Л_withdrawalPeriod Л_totalPeriod )  l = \neval_state ( ↓ DePoolContract_Ф_addVestingOrLock Л_stake Л_beneficiary Л_withdrawalPeriod Л_totalPeriod xBoolFalse )  l .  \n Proof. \n  intros.\n  destructLedger l. \n  compute.\n\n  destructFunction5 DePoolContract_Ф_addVestingOrLock; auto. \nQed. \n \nLemma DePoolContract_Ф_addVestingStake_exec : forall ( Л_stake : XInteger64 )\n                                                   (Л_beneficiary: XAddress)\n\t\t\t\t\t\t\t\t\t\t                               (Л_withdrawalPeriod: XInteger32)\n\t\t\t\t\t\t\t\t\t\t                               (Л_totalPeriod: XInteger32)\n                                                   (l: Ledger) , \nexec_state ( ↓ DePoolContract_Ф_addVestingStake Л_stake Л_beneficiary Л_withdrawalPeriod Л_totalPeriod ) l = \nexec_state ( ↓ DePoolContract_Ф_addVestingOrLock Л_stake Л_beneficiary Л_withdrawalPeriod Л_totalPeriod xBoolTrue ) l .  \n Proof. \n  intros.\n  destructLedger l. \n  compute.\n\n  destructFunction5 DePoolContract_Ф_addVestingOrLock; auto. \n Qed. \n \n Lemma DePoolContract_Ф_addVesingStake_eval : forall ( Л_stake : XInteger64 )\n                                                   (Л_beneficiary: XAddress)\n\t\t\t\t\t\t\t\t\t\t                               (Л_withdrawalPeriod: XInteger32)\n\t\t\t\t\t\t\t\t\t\t                               (Л_totalPeriod: XInteger32)\n                                                   (l: Ledger) ,\neval_state ( ↓ DePoolContract_Ф_addVestingStake Л_stake Л_beneficiary Л_withdrawalPeriod Л_totalPeriod )  l = \neval_state ( ↓ DePoolContract_Ф_addVestingOrLock Л_stake Л_beneficiary Л_withdrawalPeriod Л_totalPeriod xBoolTrue )  l .  \n Proof. \n  intros.\n  destructLedger l. \n  compute.\n\n  destructFunction5 DePoolContract_Ф_addVestingOrLock; auto. \nQed. \n\n\nEnd DePoolContract_Ф_addLockStake.", "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_addLockStake.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548511303336, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.28517846008689274}}
{"text": "From Coq Require Import List.\nImport List.ListNotations.\nOpen Scope list_scope.\nRequire Import Omega.\n\nFrom Velus Require Import Common.\nFrom Velus Require Import Operators Environment.\nFrom Velus Require Import Clocks.\nFrom Velus Require Import Lustre.LSyntax Lustre.LCausality Lustre.LClocking.\nFrom Velus Require Import Lustre.Normalization.Fresh Lustre.Normalization.Normalization.\n\n(** * Preservation of Typing through Normalization *)\n\nModule Type NCLOCKING\n       (Import Ids : IDS)\n       (Op : OPERATORS)\n       (OpAux : OPERATORS_AUX Op)\n       (Import Syn : LSYNTAX Ids Op)\n       (Caus : LCAUSALITY Ids Op Syn)\n       (Import Clo : LCLOCKING Ids Op Syn)\n       (Import Norm : NORMALIZATION Ids Op OpAux Syn Caus).\n  Import Fresh Fresh.Facts Fresh.Tactics.\n\n  (** ** Rest of clockof preservation (started in Normalization.v) *)\n\n  Fact unnest_noops_exps_nclocksof : forall cks es es' eqs' st st',\n      length cks = length es ->\n      Forall (fun e => numstreams e = 1) es ->\n      unnest_noops_exps cks es st = (es', eqs', st') ->\n      nclocksof es' = nclocksof es.\n  Proof.\n    intros.\n    repeat rewrite nclocksof_annots.\n    erewrite unnest_noops_exps_annots; eauto.\n  Qed.\n\n  Fact unnest_reset_clockof : forall G vars e e' eqs' st st',\n      LiftO True (wc_exp G vars) e ->\n      LiftO True (fun e => numstreams e = 1) e ->\n      unnest_reset (unnest_exp G true) e st = (e', eqs', st') ->\n      LiftO True (fun e => LiftO True (fun e' => clockof e' = clockof e) e') e.\n  Proof.\n    intros * Hwc Hnum Hunn.\n    unnest_reset_spec; simpl in *; auto.\n    1,2:assert (length l = 1) by\n        (eapply unnest_exp_length in Hk0; eauto; congruence);\n      singleton_length.\n    - eapply unnest_exp_clockof in Hk0; eauto.\n    - eapply unnest_exp_annot in Hk0; eauto.\n      simpl in Hk0. rewrite app_nil_r in Hk0.\n      rewrite <- length_annot_numstreams in Hnum.\n      rewrite clockof_annot, <- Hk0.\n      singleton_length. rewrite Hk0 in *; simpl in Hhd; subst.\n      reflexivity.\n  Qed.\n\n  Hint Resolve nth_In.\n  Corollary map_bind2_unnest_exp_clocksof' :\n    forall G vars is_control es es' eqs' st st',\n      Forall (wc_exp G vars) es ->\n      map_bind2 (unnest_exp G is_control) es st = (es', eqs', st') ->\n      Forall2 (fun es' e => clocksof es' = clockof e) es' es.\n  Proof with eauto.\n    intros G vars is_control es es' eqs' st st' Hwt Hmap.\n    eapply map_bind2_unnest_exp_annots' in Hmap...\n    clear Hwt.\n    induction Hmap; constructor; eauto.\n    rewrite clocksof_annots, H, <- clockof_annot...\n  Qed.\n\n  Corollary map_bind2_unnest_exp_clocksof'' : forall G vars is_control es es' eqs' st st',\n      Forall (wc_exp G vars) es ->\n      map_bind2 (unnest_exp G is_control) es st = (es', eqs', st') ->\n      Forall2 (fun e ck => clockof e = [ck]) (concat es') (clocksof es).\n  Proof.\n    intros * Hwl Hmap.\n    eapply map_bind2_unnest_exp_annots'' in Hmap; eauto.\n    rewrite clocksof_annots, Forall2_map_2, Forall2_map_2.\n    eapply Forall2_impl_In; eauto. intros; simpl in *.\n    rewrite clockof_annot, H1; auto.\n  Qed.\n\n  Corollary map_bind2_unnest_exp_clocksof''' : forall G vars is_control ck es es' eqs' st st',\n      Forall (wc_exp G vars) es ->\n      Forall (eq ck) (clocksof es) ->\n      map_bind2 (unnest_exp G is_control) es st = (es', eqs', st') ->\n      Forall (fun e => clockof e = [ck]) (concat es').\n  Proof.\n    intros * Hwl Hck Hmap.\n    assert (Hmap':=Hmap). eapply map_bind2_unnest_exp_numstreams in Hmap.\n    eapply map_bind2_unnest_exp_annots'' in Hmap'; eauto.\n    rewrite clocksof_annots in Hck.\n    assert (length (concat es') = length (annots es)) by (apply Forall2_length in Hmap'; auto).\n    assert (Forall (fun e => exists y, In y (annots es) /\\ (clockof e = [ck])) (concat es')) as Hf'.\n    { eapply Forall2_ignore2. solve_forall.\n      rewrite clockof_annot, H2; simpl in *. congruence. }\n    solve_forall. destruct H1 as [_ [_ ?]]; auto.\n  Qed.\n\n  Corollary map_bind2_unnest_exp_clocksof :\n    forall G vars is_control es es' eqs' st st',\n      Forall (wc_exp G vars) es ->\n      map_bind2 (unnest_exp G is_control) es st = (es', eqs', st') ->\n      clocksof (concat es') = clocksof es.\n  Proof.\n    intros.\n    eapply map_bind2_unnest_exp_annots in H0; eauto.\n    rewrite clocksof_annots, H0, <- clocksof_annots; eauto.\n  Qed.\n  Hint Resolve map_bind2_unnest_exp_clocksof.\n\n  Corollary unnest_exps_clocksof : forall G vars es es' eqs' st st',\n      Forall (wc_exp G vars) es ->\n      unnest_exps G es st = (es', eqs', st') ->\n      clocksof es' = clocksof es.\n  Proof.\n    intros.\n    eapply unnest_exps_annots in H0; eauto.\n    repeat rewrite clocksof_annots.\n    congruence.\n  Qed.\n\n  Fact fby_iteexp_clockof : forall e0 e ann es' eqs' st st',\n      fby_iteexp e0 e ann st = (es', eqs', st') ->\n      clockof es' = [fst (snd ann)].\n  Proof.\n    intros e0 e [ty [cl name]] es' eqs' st st' Hfby; simpl in *.\n    destruct (is_constant e0); repeat inv_bind; reflexivity.\n  Qed.\n\n  Fact unnest_fby_clockof : forall anns e0s es,\n      length e0s = length anns ->\n      length es = length anns ->\n      clocksof (unnest_fby e0s es anns) = List.map clock_of_nclock anns.\n  Proof.\n    intros * Hlen1 Hlen2.\n    rewrite clocksof_annots, unnest_fby_annot, map_map; auto.\n  Qed.\n\n  Fact unnest_rhs_clockof: forall G vars e es' eqs' st st',\n      wc_exp G vars e ->\n      unnest_rhs G e st = (es', eqs', st') ->\n      clocksof es' = clockof e.\n  Proof.\n    intros * Hwc Hnorm.\n    eapply unnest_rhs_annot in Hnorm; eauto.\n    rewrite clocksof_annots, Hnorm, <- clockof_annot. reflexivity.\n  Qed.\n\n  Corollary unnest_rhss_clocksof: forall G vars es es' eqs' st st',\n      Forall (wc_exp G vars) es ->\n      unnest_rhss G es st = (es', eqs', st') ->\n      clocksof es' = clocksof es.\n  Proof.\n    intros.\n    eapply unnest_rhss_annots in H0; eauto.\n    repeat rewrite clocksof_annots. congruence.\n  Qed.\n\n  (** ** nclockof is also preserved by unnest_exp *)\n\n  Fact fby_iteexp_nclockof : forall e0 e ann es' eqs' st st',\n      fby_iteexp e0 e ann st = (es', eqs', st') ->\n      nclockof es' = [snd ann].\n  Proof.\n    intros e0 e [ty [cl name]] es' eqs' st st' Hfby; simpl in *.\n    destruct (is_constant e0); repeat inv_bind; reflexivity.\n  Qed.\n\n  Fact unnest_merge_nclockof : forall ckid ets efs tys ck,\n      length ets = length tys ->\n      length efs = length tys ->\n      Forall (fun e => nclockof e = [ck]) (unnest_merge ckid ets efs tys ck).\n  Proof.\n    intros * Hlen1 Hlen2.\n    unfold unnest_merge. simpl_forall.\n    eapply Forall3_forall3; split; eauto. congruence.\n  Qed.\n\n  Fact unnest_ite_nclockof : forall e ets efs tys ck,\n      length ets = length tys ->\n      length efs = length tys ->\n      Forall (fun e => nclockof e = [ck]) (unnest_ite e ets efs tys ck).\n  Proof.\n    intros * Hlen1 Hlen2.\n    unfold unnest_ite. simpl_forall.\n    eapply Forall3_forall3; split; eauto. congruence.\n  Qed.\n\n  Fact unnest_exp_nclockof : forall G vars e is_control es' eqs' st st',\n      wc_exp G vars e ->\n      unnest_exp G is_control e st = (es', eqs', st') ->\n      nclocksof es' = nclockof e.\n  Proof with eauto.\n    intros.\n    eapply unnest_exp_annot in H0; eauto.\n    rewrite nclocksof_annots, H0, <- nclockof_annot. reflexivity.\n  Qed.\n\n  Fact map_bind2_unnest_exp_nclocksof : forall G vars es is_control es' eqs' st st',\n      Forall (wc_exp G vars) es ->\n      map_bind2 (unnest_exp G is_control) es st = (es', eqs', st') ->\n      nclocksof (concat es') = nclocksof es.\n  Proof with eauto.\n    intros.\n    eapply map_bind2_unnest_exp_annots in H0; eauto.\n    repeat rewrite nclocksof_annots. congruence.\n  Qed.\n\n  Fact unnest_exps_nclocksof : forall G vars es es' eqs' st st',\n      Forall (wc_exp G vars) es ->\n      unnest_exps G es st = (es', eqs', st') ->\n      nclocksof es' = nclocksof es.\n  Proof with eauto.\n    intros.\n    eapply unnest_exps_annots in H0; eauto.\n    repeat rewrite nclocksof_annots. congruence.\n  Qed.\n\n  Fact unnest_rhs_nclockof : forall G vars e es' eqs' st st',\n      wc_exp G vars e ->\n      unnest_rhs G e st = (es', eqs', st') ->\n      nclocksof es' = nclockof e.\n  Proof with eauto.\n    intros.\n    eapply unnest_rhs_annot in H0; eauto.\n    rewrite nclocksof_annots, H0, <- nclockof_annot. reflexivity.\n  Qed.\n\n  Fact unnest_rhss_nclocksof : forall G vars es es' eqs' st st',\n      Forall (wc_exp G vars) es ->\n      unnest_rhss G es st = (es', eqs', st') ->\n      nclocksof es' = nclocksof es.\n  Proof with eauto.\n    intros.\n    eapply unnest_rhss_annots in H0; eauto.\n    rewrite nclocksof_annots, H0, <- nclocksof_annots. reflexivity.\n  Qed.\n\n  (** ** A few additional things *)\n\n  Definition st_clocks (st : fresh_st (Op.type * clock)) :=\n    idck (st_anns st).\n  Definition st_clocks' (st : fresh_st ((Op.type * clock) * bool)) :=\n    idck (idty (st_anns st)).\n\n  Local Ltac In_st_clocks id t cl b :=\n    unfold st_clocks, idck, idty in *;\n    repeat simpl_In; exists (id, (t, cl)); split; auto;\n    simpl_In; exists (id, (t, cl, b)); eauto.\n\n  Fact idents_for_anns_incl_clocks : forall anns ids st st',\n    idents_for_anns anns st = (ids, st') ->\n    incl (List.map (fun '(id, (_, (cl, _))) => (id, cl)) ids) (st_clocks st').\n  Proof.\n    intros anns ids st st' Hids.\n    apply idents_for_anns_incl in Hids.\n    intros [id cl] Hin.\n    repeat simpl_In. inv H.\n    specialize (Hids (id, (t, cl))).\n    assert (In (id, (t, cl)) (st_anns st')).\n    { eapply Hids. repeat simpl_In. exists (id, (t, (cl, o))); auto. }\n    In_st_clocks id t cl b.\n  Qed.\n\n  Fact idents_for_anns'_incl_clocks : forall anns ids st st',\n    idents_for_anns' anns st = (ids, st') ->\n    incl (List.map (fun '(id, (_, (cl, _))) => (id, cl)) ids) (st_clocks st').\n  Proof.\n    intros anns ids st st' Hids.\n    apply idents_for_anns'_incl in Hids.\n    intros [id cl] Hin.\n    repeat simpl_In. inv H.\n    specialize (Hids (id, (t, cl))).\n    assert (In (id, (t, cl)) (st_anns st')).\n    { eapply Hids. repeat simpl_In. exists (id, (t, (cl, o))); auto. }\n    In_st_clocks id t cl b.\n  Qed.\n\n  Fact idents_for_anns'_clocknames : forall anns ids st st',\n      idents_for_anns' anns st = (ids, st') ->\n      Forall (fun x => LiftO True (eq (fst x)) (snd (snd (snd x)))) ids.\n  Proof with eauto.\n    induction anns; intros ids st st' Hids; repeat inv_bind...\n    destruct a as [ty [cl [name|]]]; repeat inv_bind; constructor; simpl...\n  Qed.\n\n  Fact st_follows_clocks_incl : forall st st',\n      st_follows st st' ->\n      incl (st_clocks st) (st_clocks st').\n  Proof.\n    intros st st' Hfollows.\n    apply st_follows_incl in Hfollows.\n    unfold st_clocks.\n    repeat apply incl_map.\n    assumption.\n  Qed.\n\n  Ltac solve_incl :=\n    match goal with\n    | H : wc_clock ?l1 ?cl |- wc_clock ?l2 ?cl =>\n      eapply wc_clock_incl; [| eauto]\n    | H : wc_exp ?G ?l1 ?e |- wc_exp ?G ?l2 ?e =>\n      eapply wc_exp_incl; [| eauto]\n    | H : wc_equation ?G ?l1 ?eq |- wc_equation ?G ?l2 ?eq =>\n      eapply wc_equation_incl; [| eauto]\n    | H : In ?i ?l1 |- In ?i ?l2 =>\n      assert (incl l1 l2) by repeat solve_incl; eauto\n    | |- incl ?l1 ?l1 => reflexivity\n    | |- incl ?l1 (?l1 ++ ?l2) =>\n      eapply incl_appl; reflexivity\n    | |- incl (?l1 ++ ?l2) (?l1 ++ ?l3) =>\n      eapply incl_app\n    | |- incl ?l1 (?l2 ++ ?l3) =>\n      eapply incl_appr\n    | |- incl ?l1 (?a::?l2) =>\n      eapply incl_tl\n    | |- incl (st_clocks ?st1) (st_clocks _) =>\n      eapply st_follows_clocks_incl; repeat solve_st_follows\n    | |- incl (st_clocks' ?st1) (st_clocks' _) =>\n      unfold st_clocks', idty, idck; do 2 eapply incl_map; eapply st_follows_incl; repeat solve_st_follows\n    | H : incl ?l1 ?l2 |- incl (idty ?l1) (idty ?l2) =>\n      eapply incl_map; eauto\n    end; auto.\n\n  (** ** Preservation of clocking through first pass *)\n\n  Import Permutation.\n\n  Fact fresh_ident_wc_env : forall pref vars ty ck id st st',\n      wc_env (vars++st_clocks st) ->\n      wc_clock (vars++st_clocks st) ck ->\n      fresh_ident pref (ty, ck) st = (id, st') ->\n      wc_env (vars++st_clocks st').\n  Proof.\n    intros * Hwenv Hwc Hfresh.\n    apply fresh_ident_anns in Hfresh.\n    unfold st_clocks in *. rewrite Hfresh; simpl.\n    rewrite <- Permutation_middle.\n    constructor; simpl.\n    - repeat solve_incl.\n    - eapply Forall_impl; [|eauto].\n      intros; simpl in *. repeat solve_incl.\n  Qed.\n\n  Fact idents_for_anns_wc_env : forall vars anns ids st st',\n      wc_env (vars++st_clocks st) ->\n      Forall (wc_clock (vars++st_clocks st)) (map fst (map snd anns)) ->\n      idents_for_anns anns st = (ids, st') ->\n      wc_env (vars++st_clocks st').\n  Proof with eauto.\n    induction anns as [|[ty [ck id]]]; intros ids st st' Hwenv Hwc Hids;\n      repeat inv_bind...\n    inv Hwc.\n    eapply IHanns in H0... 2:(solve_forall; repeat solve_incl).\n    eapply fresh_ident_wc_env...\n  Qed.\n\n  Fact reuse_ident_wc_env : forall vars ty ck id st st',\n      wc_env (vars++st_clocks st) ->\n      wc_clock (vars++st_clocks st') ck ->\n      reuse_ident id (ty, ck) st = (tt, st') ->\n      wc_env (vars++st_clocks st').\n  Proof.\n    intros * Hwenv Hwc Hfresh.\n    apply reuse_ident_anns in Hfresh.\n    unfold st_clocks in *. rewrite Hfresh; simpl.\n    rewrite <- Permutation_middle.\n    constructor; simpl.\n    - solve_incl. rewrite Hfresh; simpl.\n      rewrite Permutation_middle. apply incl_refl.\n    - eapply Forall_impl; [|eauto].\n      intros; simpl in *. repeat solve_incl.\n  Qed.\n\n  Fact idents_for_anns'_st_anns : forall anns ids st st',\n      idents_for_anns' anns st = (ids, st') ->\n      Permutation (st_anns st') (map (fun '(id, (ty, (cl, _))) => (id, (ty, cl))) ids++(st_anns st)).\n  Proof with eauto.\n    induction anns; intros ids st st' Hids;\n      repeat inv_bind; simpl in *...\n    destruct a as [ty [cl [name|]]]; repeat inv_bind; simpl in *.\n    - rewrite IHanns...\n      rewrite Permutation_middle. apply Permutation_app_head.\n      destruct x. apply reuse_ident_anns in H.\n      rewrite H. reflexivity.\n    - rewrite IHanns...\n      rewrite Permutation_middle. apply Permutation_app_head.\n      apply fresh_ident_anns in H.\n      rewrite H. reflexivity.\n  Qed.\n\n  Fact idents_for_anns'_wc_env : forall vars anns ids st st',\n      wc_env (vars++st_clocks st) ->\n      Forall (wc_clock (vars++st_clocks st')) (map fst (map snd anns)) ->\n      idents_for_anns' anns st = (ids, st') ->\n      wc_env (vars++st_clocks st').\n  Proof with eauto.\n    intros vars anns ids st st' Hwenv Hwc Hids.\n    specialize (idents_for_anns'_values _ _ _ _ Hids) as Hids'.\n    apply idents_for_anns'_st_anns in Hids.\n    unfold st_clocks. rewrite Hids.\n    unfold st_clocks, idck, idty in *; repeat simpl_list.\n    unfold wc_env in *. repeat rewrite Forall_app in *.\n    destruct Hwenv as [Hwenv1 Hwenv2]. repeat split.\n    - eapply Forall_impl... intros; simpl in *. repeat solve_incl.\n    - clear Hwenv1 Hwenv2.\n      rewrite <- Hids' in Hwc.\n      repeat rewrite Forall_map. repeat rewrite Forall_map in Hwc.\n      eapply Forall_impl...\n      intros [id [ty [cl name]]] ?; simpl in *.\n      intros; simpl in *.\n      solve_incl. apply incl_appr'.\n      rewrite Hids. unfold idck. rewrite map_app, map_map.\n      eapply incl_appr', incl_refl.\n    - eapply Forall_impl... intros; simpl in *. repeat solve_incl.\n  Qed.\n\n  Hint Constructors wc_exp.\n\n  Fact hd_default_wc_exp : forall G vars es,\n      Forall (wc_exp G vars) es ->\n      wc_exp G vars (hd_default es).\n  Proof.\n    intros G vars es Hf.\n    destruct es; simpl.\n    - constructor.\n    - inv Hf; auto.\n  Qed.\n  Hint Resolve hd_default_wc_exp.\n\n  Fact idents_for_anns_wc : forall G vars anns ids st st',\n      Forall unnamed_stream anns ->\n      idents_for_anns anns st = (ids, st') ->\n      Forall (wc_exp G (vars++st_clocks st')) (List.map (fun '(x, ann) => Evar x ann) ids).\n  Proof.\n    induction anns; intros ids st st' Hunnamed Hident;\n      repeat inv_bind; simpl; auto.\n    destruct a as [? [? ?]]. repeat inv_bind.\n    inv Hunnamed. constructor; eauto.\n    unfold unnamed_stream in H3; simpl in H3; subst.\n    constructor.\n    eapply fresh_ident_In in H.\n    eapply idents_for_anns_st_follows in H0.\n    eapply st_follows_incl in H; eauto.\n    eapply in_or_app. right.\n    In_st_clocks x t c false.\n  Qed.\n\n  Fact idents_for_anns'_wc : forall G vars anns ids st st',\n      idents_for_anns' anns st = (ids, st') ->\n      Forall (wc_exp G (vars++st_clocks st')) (List.map (fun '(x, ann) => Evar x ann) ids).\n  Proof.\n    induction anns; intros ids st st' Hident;\n      repeat inv_bind; simpl; auto.\n    destruct a as [? [? ?]].\n    destruct o; repeat inv_bind; constructor; eauto.\n    - constructor.\n      destruct x. eapply reuse_ident_In in H.\n      eapply idents_for_anns'_st_follows in H0.\n      eapply st_follows_incl in H; eauto.\n      eapply in_or_app. right.\n      In_st_clocks i t c false.\n    - constructor.\n      eapply fresh_ident_In in H.\n      eapply idents_for_anns'_st_follows in H0.\n      eapply st_follows_incl in H; eauto.\n      eapply in_or_app. right.\n      In_st_clocks x t c false.\n  Qed.\n\n  Fact map_bind2_wc {A B} :\n    forall G vars (k : A -> Fresh (list exp * list equation) B) a es' eqs' st st',\n      map_bind2 k a st = (es', eqs', st') ->\n      (forall st st' a es eqs', k a st = (es, eqs', st') -> st_follows st st') ->\n      Forall (fun a => forall es' eqs' st0 st0',\n                  k a st0 = (es', eqs', st0') ->\n                  st_follows st st0 ->\n                  st_follows st0' st' ->\n                  Forall (wc_exp G vars) es' /\\\n                  Forall (wc_equation G vars) eqs') a ->\n      Forall (wc_exp G vars) (concat es') /\\\n      Forall (wc_equation G vars) (concat eqs').\n  Proof with eauto.\n    intros G vars k a.\n    induction a; intros * Hmap Hfollows Hforall;\n      repeat inv_bind; simpl.\n    - repeat constructor.\n    - inv Hforall.\n      assert (H':=H). eapply H3 in H' as [Hwc1 Hwc1']... 2,3:repeat solve_st_follows.\n      eapply IHa in H0 as [Hwc2 Hwc2']...\n      2:{ solve_forall. eapply H2 in H4... etransitivity... }\n      repeat rewrite Forall_app. repeat split; eauto.\n  Qed.\n\n  Fact unnest_fby_wc_exp : forall G vars e0s es anns,\n      Forall (wc_exp G vars) e0s ->\n      Forall (wc_exp G vars) es ->\n      Forall unnamed_stream anns ->\n      Forall2 (fun e0 a => clockof e0 = [a]) e0s (map clock_of_nclock anns) ->\n      Forall2 (fun e a => clockof e = [a]) es (map clock_of_nclock anns) ->\n      Forall (wc_exp G vars) (unnest_fby e0s es anns).\n  Proof.\n    intros * Hwc1 Hwc2 Hunnamed Hck1 Hck2.\n    unfold unnest_fby.\n    assert (length e0s = length anns) as Hlen1 by (eapply Forall2_length in Hck1; solve_length).\n    assert (length es = length anns) as Hlen2 by (eapply Forall2_length in Hck2; solve_length).\n    solve_forall.\n    constructor; simpl; try rewrite app_nil_r; eauto.\n  Qed.\n\n  Fact unnest_arrow_wc_exp : forall G vars e0s es anns,\n      Forall (wc_exp G vars) e0s ->\n      Forall (wc_exp G vars) es ->\n      Forall unnamed_stream anns ->\n      Forall2 (fun e0 a => clockof e0 = [a]) e0s (map clock_of_nclock anns) ->\n      Forall2 (fun e a => clockof e = [a]) es (map clock_of_nclock anns) ->\n      Forall (wc_exp G vars) (unnest_arrow e0s es anns).\n  Proof.\n    intros * Hwc1 Hwc2 Hunnamed Hck1 Hck2.\n    unfold unnest_arrow.\n    assert (length e0s = length anns) as Hlen1 by (eapply Forall2_length in Hck1; solve_length).\n    assert (length es = length anns) as Hlen2 by (eapply Forall2_length in Hck2; solve_length).\n    solve_forall.\n    constructor; simpl; try rewrite app_nil_r; eauto.\n  Qed.\n\n  Fact unnest_when_wc_exp : forall G vars ckid ck b es tys,\n      length es = length tys ->\n      In (ckid, ck) vars ->\n      Forall (wc_exp G vars) es ->\n      Forall (fun e => clockof e = [ck]) es ->\n      Forall (wc_exp G vars) (unnest_when ckid b es tys (Con ck ckid b, None)).\n  Proof.\n    intros * Hlen Hin Hwc Hck. unfold unnest_when.\n    solve_forall.\n    repeat constructor; auto;\n      simpl; rewrite app_nil_r, H1; auto.\n  Qed.\n\n  Fact unnest_merge_wc_exp : forall G vars ckid ck ets efs tys,\n      length ets = length tys ->\n      length efs = length tys ->\n      In (ckid, ck) vars ->\n      Forall (wc_exp G vars) ets ->\n      Forall (wc_exp G vars) efs ->\n      Forall (fun e => clockof e = [Con ck ckid true]) ets ->\n      Forall (fun e => clockof e = [Con ck ckid false]) efs ->\n      Forall (wc_exp G vars) (unnest_merge ckid ets efs tys (ck, None)).\n  Proof.\n    intros * Hlen1 Hlen2 Hin Hwc1 Hwc2 Hck1 Hck2. unfold unnest_merge.\n    solve_forall.\n    repeat constructor; auto;\n      simpl; rewrite app_nil_r; try rewrite H2; try rewrite H3; auto.\n  Qed.\n\n  Fact unnest_ite_wc_exp : forall G vars ck e ets efs tys,\n      length ets = length tys ->\n      length efs = length tys ->\n      wc_exp G vars e ->\n      Forall (wc_exp G vars) ets ->\n      Forall (wc_exp G vars) efs ->\n      clockof e = [ck] ->\n      Forall (fun e => clockof e = [ck]) ets ->\n      Forall (fun e => clockof e = [ck]) efs ->\n      Forall (wc_exp G vars) (unnest_ite e ets efs tys (ck, None)).\n  Proof.\n    intros * Hlen1 Hlen2 Hwc1 Hwc2 Hwc3 Hck1 Hck2 Hck3. unfold unnest_ite.\n    solve_forall.\n    repeat constructor; auto;\n      simpl; rewrite app_nil_r; try rewrite H2; try rewrite H3; auto.\n  Qed.\n\n  Fact unnest_reset_wc : forall G vars e e' eqs' st st' ck,\n      LiftO True (fun e => forall es' eqs' st',\n                   unnest_exp G true e st = (es', eqs', st') ->\n                   Forall (wc_exp G (vars++st_clocks st')) es' /\\\n                   Forall (wc_equation G (vars++st_clocks st')) eqs') e ->\n      LiftO True (wc_exp G (vars++st_clocks st)) e ->\n      LiftO True (fun e => clockof e = [ck]) e ->\n      unnest_reset (unnest_exp G true) e st = (e', eqs', st') ->\n      LiftO True (fun e' => clockof e' = [ck]) e' /\\\n      LiftO True (wc_exp G (vars++st_clocks st')) e' /\\\n      Forall (wc_equation G (vars++st_clocks st')) eqs'.\n  Proof.\n    intros * Hkwc Hwc Hck Hunn.\n    repeat split.\n    - unnest_reset_spec; simpl in *; auto.\n      1,2:assert (length l = 1) by\n          (eapply unnest_exp_length in Hk0; eauto;\n           rewrite <- length_clockof_numstreams, Hck in Hk0; auto).\n      1,2:singleton_length.\n      + eapply unnest_exp_clockof in Hk0; eauto.\n        rewrite Hck in Hk0; auto.\n      + eapply unnest_exp_clockof in Hk0; eauto.\n        simpl in Hk0. rewrite app_nil_r, Hck in Hk0.\n        rewrite clockof_annot in Hk0.\n        destruct (annot e); inv Hk0. destruct l; inv H1.\n        simpl in *; subst; auto.\n    - unnest_reset_spec; simpl in *; auto.\n      1,2:assert (Hk:=Hk0);eapply Hkwc in Hk0 as [Hwt1 Hwt2]; auto.\n      + destruct l; simpl in H; [inv H|]; subst. \n        inv Hwt1; auto.\n      + constructor.\n        eapply fresh_ident_In in Hfresh.\n      apply in_or_app; right.\n      unfold st_clocks, idck. simpl_In.\n      repeat eexists; eauto. split; auto.\n    - destruct e; simpl in *; repeat inv_bind; auto.\n      assert (length x = 1).\n      { eapply unnest_exp_length in H; eauto.\n        rewrite <- length_clockof_numstreams, Hck in H; auto. }\n      singleton_length.\n      assert (Hk:=H). apply unnest_exp_normalized_cexp, Forall_singl in H.\n      eapply Hkwc in Hk as [Hwc1 Hwc2]; auto.\n      inv H; [| | inv H1]; simpl in *.\n      1-7:try destruct cl as [ck' ?]; repeat inv_bind.\n      1-3,5-7:constructor.\n      2,4,6,8,10,12,13:solve_forall; repeat solve_incl.\n      1-6:inv Hwc1.\n      1-6:repeat split; [constructor;[|constructor]| |]; repeat solve_incl.\n      1-12:simpl; repeat constructor.\n      2,4,5,7,9,11:\n        (unfold clock_of_nclock, stripname; simpl;\n         match goal with\n         | H : fresh_ident _ _ _ = _ |- _ =>\n           apply fresh_ident_In in H\n         end;\n         apply in_or_app, or_intror;\n         unfold st_clocks, idck; simpl_In;\n         repeat eexists; eauto; auto).\n      + inv H4; simpl; auto.\n      + inv H5; simpl; auto.\n      + inv H3; simpl; auto.\n      + inv H4; simpl; auto.\n      + inv H3; simpl; auto.\n  Qed.\n\n  Lemma not_is_noops_exp_anon : forall G vars ck e,\n      normalized_lexp e ->\n      wc_exp G vars e ->\n      is_noops_exp ck e = false ->\n      Forall unnamed_stream (annot e).\n  Proof.\n    intros * Hnormed Hwc Hnoops.\n    destruct ck; simpl in *. try congruence.\n    induction Hnormed; simpl in *; try congruence.\n    - inv Hwc. repeat constructor.\n    - inv Hwc. repeat constructor.\n    - inv Hwc. repeat constructor.\n  Qed.\n\n  Lemma unnest_noops_exps_wc : forall G vars cks es es' eqs' st st' ,\n      length es = length cks ->\n      Forall normalized_lexp es ->\n      Forall (fun e => numstreams e = 1) es ->\n      Forall (wc_exp G (vars++st_clocks st)) es ->\n      unnest_noops_exps cks es st = (es', eqs', st') ->\n      Forall (wc_exp G (vars++st_clocks st')) es' /\\\n      Forall (wc_equation G (vars++st_clocks st')) eqs'.\n  Proof.\n    unfold unnest_noops_exps.\n    induction cks; intros * Hlen Hnormed Hnums Hwt Hunt; repeat inv_bind; simpl; auto.\n    destruct es; simpl in *; inv Hlen; repeat inv_bind.\n    inv Hwt. inv Hnums. inv Hnormed.\n    assert (Forall (wc_exp G (vars ++ st_clocks x2)) es) as Hes.\n    { solve_forall. repeat solve_incl; eauto. }\n    eapply IHcks in Hes as (Hes'&Heqs'). 2-4:eauto.\n    2:repeat inv_bind; repeat eexists; eauto; inv_bind; eauto.\n    unfold unnest_noops_exp in H.\n    rewrite <-length_annot_numstreams in H6. singleton_length.\n    destruct p as (?&?&?).\n    split; simpl; try constructor; try (rewrite Forall_app; split); auto.\n    1,2:destruct (is_noops_exp) eqn:Hnoops; repeat inv_bind; auto.\n    + repeat solve_incl.\n    + eapply not_is_noops_exp_anon in Hnoops; eauto.\n      rewrite Hsingl in Hnoops. eapply Forall_singl in Hnoops. inv Hnoops; simpl in *; subst.\n      constructor. eapply fresh_ident_In in H.\n      eapply in_or_app. right. unfold st_clocks, idck. simpl_In. exists (x0, (t, c)).\n      split; auto.\n      eapply st_follows_incl in H; eauto. repeat solve_st_follows.\n    + repeat constructor; auto; simpl; try rewrite app_nil_r.\n      * repeat solve_incl.\n      * eapply not_is_noops_exp_anon in Hnoops; eauto.\n        rewrite Hsingl in Hnoops. eapply Forall_singl in Hnoops. inv Hnoops; simpl in *; subst.\n        rewrite nclockof_annot, Hsingl; simpl.\n        do 2 constructor; auto.\n      * rewrite clockof_annot, Hsingl; simpl.\n        constructor; auto.\n        eapply fresh_ident_In in H.\n       eapply in_or_app. right. unfold st_clocks, idck. simpl_In. exists (x0, (t, c)).\n      split; auto.\n      eapply st_follows_incl in H; eauto. repeat solve_st_follows.\n  Qed.\n\n  Hint Resolve nth_In.\n  Fact unnest_exp_wc : forall G vars e is_control es' eqs' st st',\n      wc_exp G (vars++st_clocks st) e ->\n      unnest_exp G is_control e st = (es', eqs', st') ->\n      Forall (wc_exp G (vars++st_clocks st')) es' /\\\n      Forall (wc_equation G (vars++st_clocks st')) eqs'.\n  Proof with eauto.\n    induction e using exp_ind2; intros is_control es' eqs' st st' Hwc Hnorm;\n      inv Hwc; simpl in Hnorm. 1-11: repeat inv_bind.\n    - (* const *) repeat constructor.\n    - (* var *)\n      repeat constructor...\n    - (* var (anon) *)\n      repeat constructor...\n    - (* unop *)\n      assert (length x = numstreams e) as Hlen by eauto.\n      rewrite <- length_clockof_numstreams, H3 in Hlen; simpl in Hlen.\n      singleton_length.\n      assert (Hnorm:=H); eapply IHe in H as [Hwc1 Hwc1']; eauto.\n      repeat econstructor...\n      + inv Hwc1; eauto.\n      + eapply unnest_exp_clockof in Hnorm; simpl in Hnorm; eauto.\n        rewrite app_nil_r, H3 in Hnorm...\n    - (* binop *)\n      repeat inv_bind.\n      assert (length x = numstreams e1) as Hlen1 by eauto.\n      rewrite <- length_clockof_numstreams, H5 in Hlen1; simpl in Hlen1.\n      assert (length x2 = numstreams e2) as Hlen2 by eauto.\n      rewrite <- length_clockof_numstreams, H6 in Hlen2; simpl in Hlen2. repeat singleton_length.\n      assert (Hnorm1:=H); eapply IHe1 in H as [Hwc1 Hwc1']; eauto.\n      assert (Hnorm2:=H0); eapply IHe2 in H0 as [Hwc2 Hwc2']; eauto. 2:repeat solve_incl.\n      repeat econstructor...\n      + inv Hwc1. repeat solve_incl.\n      + inv Hwc2...\n      + eapply unnest_exp_clockof in Hnorm1; simpl in Hnorm1; eauto.\n        rewrite app_nil_r, H5 in Hnorm1...\n      + eapply unnest_exp_clockof in Hnorm2; simpl in Hnorm2; eauto.\n        rewrite app_nil_r, H6 in Hnorm2...\n      + apply Forall_app; split; auto.\n        solve_forall. repeat solve_incl.\n    - (* fby *)\n      Local Ltac solve_map_bind2 :=\n        solve_forall;\n        match goal with\n        | Hnorm : unnest_exp _ _ _ _ = _, H : context [unnest_exp _ _ _ _ = _ -> _] |- _ =>\n          eapply H in Hnorm as [? ?]; eauto;\n          [split|]; try solve_forall; repeat solve_incl\n        end.\n      rewrite Forall2_eq in H6, H7.\n      assert (length (concat x2) = length (annots e0s)) as Hlen1 by eauto.\n      assert (length (concat x6) = length (annots es)) as Hlen2 by eauto.\n      remember (unnest_fby _ _ _) as fby.\n      assert (length (concat x2) = length a) as Hlen1'.\n      { eapply map_bind2_unnest_exp_length in H1...\n        repeat simpl_length. erewrite <- map_length, <- map_length. setoid_rewrite <- H6. apply map_length. }\n      assert (length (concat x6) = length a) as Hlen2'.\n      { eapply map_bind2_unnest_exp_length in H2...\n        repeat simpl_length. erewrite <- map_length, <- map_length. setoid_rewrite <- H7. apply map_length. }\n      assert (length a = length fby) as Hlen4.\n      { repeat simpl_length.\n        rewrite unnest_fby_length... }\n      assert (length x5 = length fby) as Hlen3.\n      { eapply idents_for_anns_length in H3. solve_length. }\n      assert (H1':=H1). eapply map_bind2_wc with (G0:=G) (vars0:=vars++st_clocks x1) in H1' as [Hwc1 Hwc1']...\n      2:solve_map_bind2.\n      assert (H2':=H2). eapply map_bind2_wc with (G0:=G) (vars0:=vars++st_clocks x4) in H2' as [Hwc2 Hwc2']...\n      2:solve_map_bind2.\n      clear H H0.\n      repeat rewrite Forall_app; repeat split.\n      3,4:solve_forall; repeat solve_incl.\n      + eapply idents_for_anns_wc...\n      + assert (annots fby = a) as Hanns.\n        { rewrite Heqfby, unnest_fby_annot... }\n        assert (Forall (wc_exp G (vars++st_clocks st')) fby) as Hwcf.\n        { rewrite Heqfby. eapply unnest_fby_wc_exp...\n          1,2:solve_forall; repeat solve_incl.\n          + eapply map_bind2_unnest_exp_clocksof'' in H1... congruence.\n          + eapply map_bind2_unnest_exp_clocksof'' in H2... congruence. }\n        assert (Forall2 (fun '(_, nck) e => nclockof e = [nck]) (map snd x5) fby) as Hcks.\n        { eapply idents_for_anns_values in H3; subst.\n          specialize (unnest_fby_annot' _ _ _ Hlen1' Hlen2') as Hanns'; eauto. clear - Hanns'.\n          eapply Forall2_swap_args. solve_forall.\n          destruct a0 as [ty ck]; simpl in *. rewrite nclockof_annot, H1; auto. } subst a.\n        solve_forall.\n        repeat constructor; eauto.\n        * destruct a as [ty [ck name]]; simpl in *.\n          rewrite app_nil_r, H9. constructor; auto.\n          eapply idents_for_anns_values in H3; rewrite <- H3 in H8.\n          eapply Forall_forall in H8. 2:simpl_In; exists (i, (ty, (ck, name))); auto.\n          inv H8; simpl in H11; subst. constructor.\n        * destruct a as [ty [ck name]]; simpl in *.\n          rewrite app_nil_r, clockof_nclockof, H9; simpl.\n          constructor; auto.\n          eapply idents_for_anns_incl_clocks in H3.\n          apply in_or_app, or_intror, H3.\n          repeat simpl_In. exists (i, (ty, (ck, name))); auto.\n    - (* arrow *)\n      rewrite Forall2_eq in H6, H7.\n      assert (length (concat x2) = length (annots e0s)) as Hlen1 by eauto.\n      assert (length (concat x6) = length (annots es)) as Hlen2 by eauto.\n      remember (unnest_arrow _ _ _) as fby.\n      assert (length (concat x2) = length a) as Hlen1'.\n      { eapply map_bind2_unnest_exp_length in H1...\n        repeat simpl_length. erewrite <- map_length, <- map_length. setoid_rewrite <- H6. apply map_length. }\n      assert (length (concat x6) = length a) as Hlen2'.\n      { eapply map_bind2_unnest_exp_length in H2...\n        repeat simpl_length. erewrite <- map_length, <- map_length. setoid_rewrite <- H7. apply map_length. }\n      assert (length a = length fby) as Hlen4.\n      { repeat simpl_length.\n        rewrite unnest_arrow_length... }\n      assert (length x5 = length fby) as Hlen3.\n      { eapply idents_for_anns_length in H3. solve_length. }\n      assert (H1':=H1). eapply map_bind2_wc with (G0:=G) (vars0:=vars++st_clocks x1) in H1' as [Hwc1 Hwc1']...\n      2:solve_map_bind2.\n      assert (H2':=H2). eapply map_bind2_wc with (G0:=G) (vars0:=vars++st_clocks x4) in H2' as [Hwc2 Hwc2']...\n      2:solve_map_bind2.\n      clear H H0.\n      repeat rewrite Forall_app; repeat split.\n      3,4:solve_forall; repeat solve_incl.\n      + eapply idents_for_anns_wc...\n      + assert (annots fby = a) as Hanns.\n        { rewrite Heqfby, unnest_arrow_annot... }\n        assert (Forall (wc_exp G (vars++st_clocks st')) fby) as Hwcf.\n        { rewrite Heqfby. eapply unnest_arrow_wc_exp...\n          1,2:solve_forall; repeat solve_incl.\n          + eapply map_bind2_unnest_exp_clocksof'' in H1... congruence.\n          + eapply map_bind2_unnest_exp_clocksof'' in H2... congruence. }\n        assert (Forall2 (fun '(_, nck) e => nclockof e = [nck]) (map snd x5) fby) as Hcks.\n        { eapply idents_for_anns_values in H3; subst.\n          specialize (unnest_arrow_annot' _ _ _ Hlen1' Hlen2') as Hanns'; eauto. clear - Hanns'.\n          eapply Forall2_swap_args. solve_forall.\n          destruct a0 as [ty ck]; simpl in *. rewrite nclockof_annot, H1; auto. } subst a.\n        solve_forall.\n        repeat constructor; eauto.\n        * destruct a as [ty [ck name]]; simpl in *.\n          rewrite app_nil_r, H9. constructor; auto.\n          eapply idents_for_anns_values in H3; rewrite <- H3 in H8.\n          eapply Forall_forall in H8. 2:simpl_In; exists (i, (ty, (ck, name))); auto.\n          inv H8; simpl in H11; subst. constructor.\n        * destruct a as [ty [ck name]]; simpl in *.\n          rewrite app_nil_r, clockof_nclockof, H9; simpl.\n          constructor; auto.\n          eapply idents_for_anns_incl_clocks in H3.\n          apply in_or_app, or_intror, H3.\n          repeat simpl_In. exists (i, (ty, (ck, name))); auto.\n    - (* when *)\n      assert (H0':=H0). eapply map_bind2_wc with (G0:=G) (vars0:=vars++st_clocks st') in H0' as [Hwc1 Hwc1']...\n      2:solve_map_bind2.\n      split; auto.\n      apply unnest_when_wc_exp...\n      + eapply map_bind2_unnest_exp_length in H0...\n        solve_length.\n      + assert (incl (vars ++ st_clocks st) (vars ++ st_clocks st')) as Hincl by repeat solve_incl...\n      + eapply map_bind2_unnest_exp_clocksof''' in H0...\n    - (* merge *)\n      assert (length (concat x3) = length (annots ets)) as Hlen1 by eauto.\n      assert (length (concat x6) = length (annots efs)) as Hlen2 by eauto.\n      assert (st_follows x5 st') as Hfollows by (destruct is_control; repeat inv_bind; repeat solve_st_follows).\n      assert (H1':=H1). eapply map_bind2_wc with (G0:=G) (vars0:=vars++st_clocks x2) in H1' as [Hwc1 Hwc1']...\n      2:solve_map_bind2.\n      assert (H2':=H2). eapply map_bind2_wc with (G0:=G) (vars0:=vars++st_clocks x5) in H2' as [Hwc2 Hwc2']...\n      2:solve_map_bind2.\n      clear H H0.\n      assert (Forall (wc_exp G (vars++st_clocks st')) (unnest_merge x (concat x3) (concat x6) tys (ck, None))) as Hwcexp.\n      { eapply unnest_merge_wc_exp...\n        4,5:solve_forall; repeat solve_incl.\n        + rewrite Hlen1, H10. solve_length.\n        + rewrite Hlen2, H11. solve_length.\n        + assert (incl (vars++st_clocks st) (vars++st_clocks st'))...\n          destruct is_control; repeat inv_bind; repeat solve_incl.\n        + eapply map_bind2_unnest_exp_clocksof''' in H1...\n        + eapply map_bind2_unnest_exp_clocksof''' in H2... }\n      destruct is_control; repeat inv_bind; repeat rewrite Forall_app; repeat split.\n      1,2,3,6,7:solve_forall; repeat solve_incl.\n      + eapply idents_for_anns_wc in H...\n        solve_forall. unfold unnamed_stream; auto.\n      + assert (Forall (fun e : exp => nclockof e = [(ck, None)]) (unnest_merge x (concat x3) (concat x6) tys (ck, None))) as Hnck.\n        { eapply unnest_merge_nclockof; solve_length. }\n        solve_forall. 2:(eapply idents_for_anns_length in H; solve_length).\n        repeat split. 2,3:rewrite app_nil_r.\n        * repeat constructor...\n        * rewrite H4. repeat constructor.\n        * rewrite clockof_nclockof, H4; simpl. repeat constructor.\n          assert (H':=H). apply idents_for_anns_values in H'.\n          apply idents_for_anns_incl_clocks in H.\n          destruct a as [ty [ck' name']].\n          apply in_or_app; right. apply H.\n          simpl_In. exists (i, (ty, (ck', name'))). split; auto.\n          assert (In (ty, (ck', name')) (map snd x0)) by (simpl_In; exists (i, (ty, (ck', name'))); auto).\n          rewrite H' in H13. simpl_In. inv H13; auto.\n    - (* ite *)\n      assert (length x = 1). 2:singleton_length.\n      { eapply unnest_exp_length in H1; eauto.\n        rewrite <- length_clockof_numstreams, H8 in H1; auto. }\n      assert (length (concat x5) = length (annots ets)) as Hlen1 by eauto.\n      assert (length (concat x8) = length (annots efs)) as Hlen2 by eauto.\n      assert (st_follows x7 st') as Hfollows by (destruct is_control; repeat inv_bind; repeat solve_st_follows).\n      assert (H1':=H1). eapply IHe in H1' as [Hwc1 Hwc1']...\n      assert (H2':=H2). eapply map_bind2_wc with (G0:=G) (vars0:=vars++st_clocks x4) in H2' as [Hwc2 Hwc2']...\n      2:solve_map_bind2.\n      assert (H3':=H3). eapply map_bind2_wc with (G0:=G) (vars0:=vars++st_clocks x7) in H3' as [Hwc3 Hwc3']...\n      2:solve_map_bind2.\n      clear H H0 IHe.\n      assert (Forall (wc_exp G (vars++st_clocks st')) (unnest_ite e0 (concat x5) (concat x8) tys (ck, None))) as Hwcexp.\n      { eapply unnest_ite_wc_exp...\n        3:inv Hwc1; repeat solve_incl.\n        3,4:solve_forall; repeat solve_incl.\n        + rewrite Hlen1, H11. solve_length.\n        + rewrite Hlen2, H12. solve_length.\n        + eapply unnest_exp_clockof in H1...\n          simpl in H1; rewrite app_nil_r in H1. congruence.\n        + eapply map_bind2_unnest_exp_clocksof''' in H2...\n        + eapply map_bind2_unnest_exp_clocksof''' in H3... }\n      destruct is_control; repeat inv_bind; repeat rewrite Forall_app; repeat split.\n      1,2,3,4,7,8,9:solve_forall;repeat solve_incl.\n      + eapply idents_for_anns_wc in H...\n        solve_forall. unfold unnamed_stream; auto.\n      + assert (Forall (fun e : exp => nclockof e = [(ck, None)]) (unnest_ite e0 (concat x5) (concat x8) tys (ck, None))) as Hnck.\n        { eapply unnest_ite_nclockof; solve_length. }\n        solve_forall. 2:(eapply idents_for_anns_length in H; solve_length).\n        repeat split. 2,3:rewrite app_nil_r.\n        * repeat constructor...\n        * rewrite H14. repeat constructor.\n        * rewrite clockof_nclockof, H14; simpl. repeat constructor.\n          assert (H':=H). apply idents_for_anns_values in H'.\n          apply idents_for_anns_incl_clocks in H.\n          destruct a as [ty [ck' name']].\n          apply in_or_app; right. apply H.\n          simpl_In. exists (i, (ty, (ck', name'))). split; auto.\n          assert (In (ty, (ck', name')) (map snd x)) by (simpl_In; exists (i, (ty, (ck', name'))); auto).\n          rewrite H' in H16. simpl_In. inv H16; auto.\n    - (* app *)\n      rewrite app_nil_r.\n      assert (Hnorm:=H1). eapply map_bind2_wc with (G0:=G) (vars0:=vars++st_clocks x1) in H1 as [Hwc1 Hwc1']...\n      2:solve_map_bind2.\n\n      assert (length (find_node_incks G f) = length (concat x5)) as Hlen1.\n      { unfold find_node_incks. rewrite H6.\n        eapply Forall2_length in H7. rewrite map_length.\n        eapply map_bind2_unnest_exp_length in Hnorm; eauto. rewrite length_nclocksof_annots in H7.\n        rewrite length_idck in H7. congruence. }\n      assert (Forall (fun e : exp => numstreams e = 1) (concat x5)) as Hnum.\n      { eapply map_bind2_unnest_exp_numstreams; eauto. }\n\n      repeat econstructor; simpl...\n      + eapply idents_for_anns'_wc...\n      + eapply unnest_noops_exps_wc with (G:=G) (vars:=vars) in H2 as (?&?)...\n        solve_forall; repeat solve_incl.\n      + erewrite unnest_noops_exps_nclocksof, map_bind2_unnest_exp_nclocksof...\n      + erewrite idents_for_anns'_values...\n      + rewrite app_nil_r, map_map, Forall2_map_1, Forall2_map_2, <- Forall2_same.\n        eapply idents_for_anns'_clocknames...\n      + unfold clock_of_nclock, stripname.\n        rewrite app_nil_r, map_map, Forall2_map_1, Forall2_map_2, <- Forall2_same.\n        eapply idents_for_anns'_incl_clocks in H3.\n        apply Forall_forall; intros.\n        apply in_or_app; right. apply H3.\n        rewrite in_map_iff. exists x; split; auto. destruct x as [? [? [? ?]]]; auto.\n      + apply Forall_app; split. solve_forall; repeat solve_incl.\n        eapply unnest_noops_exps_wc with (G:=G) (vars:=vars) in H2 as (?&?)...\n        solve_forall; repeat solve_incl.\n    - (* app (reset) *)\n      do 5 inv_bind.\n      assert (st_follows x4 x7) as Hfollows.\n      { eapply (unnest_reset_st_follows _ _ (Some r)) in H3; eauto. }\n      assert (Hs:=H3). eapply unnest_reset_Some in Hs as [er' ?]; subst.\n      eapply (unnest_reset_wc G vars (Some r)) in H3 as [Hwt2 [Hwt2' Hwt2'']]; simpl; eauto.\n      2-3:clear H3. 1-3:repeat inv_bind.\n      2:intros; eapply H in H3; eauto. 2,3:repeat solve_incl.\n      assert (Hnorm:=H1). eapply map_bind2_wc with (G0:=G) (vars0:=vars++st_clocks x1) in H1 as [Hwc1 Hwc1']...\n      2:solve_map_bind2.\n\n      assert (length (find_node_incks G f) = length (concat x5)) as Hlen1.\n      { unfold find_node_incks. rewrite H6.\n        eapply Forall2_length in H7. rewrite map_length.\n        eapply map_bind2_unnest_exp_length in Hnorm; eauto. rewrite length_nclocksof_annots in H7.\n        rewrite length_idck in H7. congruence. }\n      assert (Forall (fun e : exp => numstreams e = 1) (concat x5)) as Hnum.\n      { eapply map_bind2_unnest_exp_numstreams; eauto. }\n\n      repeat econstructor; simpl...\n      + eapply idents_for_anns'_wc...\n      + eapply unnest_noops_exps_wc with (G:=G) (vars:=vars) in H2 as (?&?)...\n        solve_forall; repeat solve_incl.\n      + erewrite unnest_noops_exps_nclocksof, map_bind2_unnest_exp_nclocksof...\n      + erewrite idents_for_anns'_values...\n      + repeat solve_incl.\n      + rewrite app_nil_r, map_map, Forall2_map_1, Forall2_map_2, <- Forall2_same.\n        eapply idents_for_anns'_clocknames...\n      + unfold clock_of_nclock, stripname.\n        rewrite app_nil_r, map_map, Forall2_map_1, Forall2_map_2, <- Forall2_same.\n        eapply idents_for_anns'_incl_clocks in H4.\n        apply Forall_forall; intros.\n        apply in_or_app; right. apply H4.\n        rewrite in_map_iff. exists x; split; auto. destruct x as [? [? [? ?]]]; auto.\n      + repeat rewrite Forall_app; repeat split. 1,3:solve_forall; repeat solve_incl.\n        eapply unnest_noops_exps_wc with (G:=G) (vars:=vars) in H2 as (?&?)...\n        solve_forall; repeat solve_incl.\n  Qed.\n\n  Corollary map_bind2_unnest_exp_wc : forall G vars is_control es es' eqs' st st',\n      Forall (wc_exp G (vars++st_clocks st)) es ->\n      map_bind2 (unnest_exp G is_control) es st = (es', eqs', st') ->\n      Forall (wc_exp G (vars++st_clocks st')) (concat es') /\\\n      Forall (wc_equation G (vars++st_clocks st')) (concat eqs').\n  Proof.\n    intros * Hwt Hmap.\n    eapply map_bind2_wc in Hmap; eauto.\n    solve_forall. eapply unnest_exp_wc with (G:=G) (vars:=vars) in H1 as [? ?]; eauto.\n    split. 1,2:solve_forall. 1,2,3:repeat solve_incl.\n  Qed.\n\n  Corollary unnest_exps_wc : forall G vars es es' eqs' st st',\n      Forall (wc_exp G (vars++st_clocks st)) es ->\n      unnest_exps G es st = (es', eqs', st') ->\n      Forall (wc_exp G (vars++st_clocks st')) es' /\\\n      Forall (wc_equation G (vars++st_clocks st')) eqs'.\n  Proof.\n    intros * Hwt Hmap.\n    unfold unnest_exps in Hmap; repeat inv_bind.\n    eapply map_bind2_unnest_exp_wc in H; eauto.\n  Qed.\n\n  Fact unnest_rhs_wc : forall G vars e es' eqs' st st',\n      wc_exp G (vars++st_clocks st) e ->\n      unnest_rhs G e st = (es', eqs', st') ->\n      Forall (wc_exp G (vars++st_clocks st')) es' /\\\n      Forall (wc_equation G (vars++st_clocks st')) eqs'.\n  Proof with eauto.\n    intros * Hwc Hnorm.\n    destruct e; unfold unnest_rhs in Hnorm;\n      try (solve [eapply unnest_exp_wc in Hnorm; eauto]); inv Hwc.\n    - (* fby *)\n      rewrite Forall2_eq in H4, H5.\n      repeat inv_bind.\n      assert (H':=H). eapply unnest_exps_wc in H' as [Hwc1 Hwc1']...\n      assert (H0':=H0). eapply unnest_exps_wc with (G:=G) (vars:=vars) in H0' as [Hwc2 Hwc2']...\n      2:solve_forall; repeat solve_incl.\n      rewrite Forall_app; repeat split.\n      2,3:solve_forall; repeat solve_incl.\n      eapply unnest_fby_wc_exp...\n      + solve_forall; repeat solve_incl.\n      + unfold unnest_exps in H; repeat inv_bind.\n        eapply map_bind2_unnest_exp_clocksof'' in H... congruence.\n      + unfold unnest_exps in H0; repeat inv_bind.\n        eapply map_bind2_unnest_exp_clocksof'' in H0... congruence.\n    - (* arrow *)\n      rewrite Forall2_eq in H4, H5.\n      repeat inv_bind.\n      assert (H':=H). eapply unnest_exps_wc in H' as [Hwc1 Hwc1']...\n      assert (H0':=H0). eapply unnest_exps_wc with (G:=G) (vars:=vars) in H0' as [Hwc2 Hwc2']...\n      2:solve_forall; repeat solve_incl.\n      rewrite Forall_app; repeat split.\n      2,3:solve_forall; repeat solve_incl.\n      eapply unnest_arrow_wc_exp...\n      + solve_forall; repeat solve_incl.\n      + unfold unnest_exps in H; repeat inv_bind.\n        eapply map_bind2_unnest_exp_clocksof'' in H... congruence.\n      + unfold unnest_exps in H0; repeat inv_bind.\n        eapply map_bind2_unnest_exp_clocksof'' in H0... congruence.\n    - (* app *)\n      repeat inv_bind. rewrite app_nil_r.\n      assert (Hnorm:=H). eapply unnest_exps_wc in H as [Hwc1 Hwc1']...\n      assert (length (find_node_incks G i) = length x) as Hlen1.\n      { unfold find_node_incks. rewrite H4.\n        eapply Forall2_length in H5. rewrite map_length.\n        eapply unnest_exps_length in Hnorm; eauto. rewrite length_nclocksof_annots, length_idck in H5.\n        congruence. }\n      assert (Forall (fun e : exp => numstreams e = 1) x) as Hnum.\n      { eapply unnest_exps_numstreams; eauto. }\n      repeat econstructor...\n      + eapply unnest_noops_exps_wc in H0 as (?&?)...\n      + erewrite unnest_noops_exps_nclocksof, unnest_exps_nclocksof...\n      + rewrite Forall_app. split. solve_forall; repeat solve_incl.\n        eapply unnest_noops_exps_wc in H0 as (?&?)...\n    - (* app (reset) *)\n      do 5 inv_bind.\n      assert (Hnorm:=H). eapply unnest_exps_wc in H as [Hwc1 Hwc1']...\n      assert (Hs:=H1). eapply unnest_reset_Some in Hs as [er' ?]; subst.\n      assert (st_follows x4 st') as Hfollows.\n      { eapply (unnest_reset_st_follows _ _ (Some r)) in H1; eauto. }\n      eapply (unnest_reset_wc G vars (Some r)) in H1 as [Hwc2 [Hwc2' Hwc2'']]; simpl in *; eauto.\n      2:intros; eapply unnest_exp_wc in H; eauto. 2,3:repeat solve_incl.\n      assert (length (find_node_incks G i) = length x) as Hlen1.\n      { unfold find_node_incks. rewrite H4.\n        eapply Forall2_length in H5. rewrite map_length.\n        eapply unnest_exps_length in Hnorm; eauto. rewrite length_nclocksof_annots, length_idck in H5.\n        congruence. }\n      assert (Forall (fun e : exp => numstreams e = 1) x) as Hnum.\n      { eapply unnest_exps_numstreams; eauto. }\n\n      repeat econstructor...\n      + eapply unnest_noops_exps_wc in H0 as (?&?)...\n        solve_forall; repeat solve_incl.\n      + erewrite unnest_noops_exps_nclocksof, unnest_exps_nclocksof...\n      + repeat rewrite Forall_app; repeat split.\n        2:eapply unnest_noops_exps_wc in H0 as (?&?)...\n        1-3:solve_forall; repeat solve_incl.\n  Qed.\n\n  Corollary unnest_rhss_wc : forall G vars es es' eqs' st st',\n      Forall (wc_exp G (vars++st_clocks st)) es ->\n      unnest_rhss G es st = (es', eqs', st') ->\n      Forall (wc_exp G (vars++st_clocks st')) es' /\\\n      Forall (wc_equation G (vars++st_clocks st')) eqs'.\n  Proof.\n    intros * Hwc Hnorm.\n    unfold unnest_rhss in Hnorm; repeat inv_bind.\n    eapply map_bind2_wc in H; eauto.\n    solve_forall.\n    eapply unnest_rhs_wc with (G:=G) (vars:=vars) in H2 as [? ?]; eauto.\n    split. 1,2:solve_forall. 1,2,3:repeat solve_incl.\n  Qed.\n\n  Fact unnest_equation_wc_eq : forall G vars e eqs' st st',\n      wc_equation G (vars++st_clocks st) e ->\n      unnest_equation G e st = (eqs', st') ->\n      Forall (wc_equation G (vars++st_clocks st')) eqs'.\n  Proof with eauto.\n    intros G vars [xs es] eqs' st st' Hwc Hnorm.\n    unfold unnest_equation in Hnorm. repeat inv_bind.\n    destruct Hwc as [Hwc1 [Hwc2 Hwc3]].\n    assert (st_follows st st') as Hfollows by eauto.\n    assert (H':=H). eapply unnest_rhss_wc in H' as [Hwc1' Hwc1'']...\n    apply Forall_app; split...\n    rewrite clocksof_nclocksof, Forall2_map_2 in Hwc3.\n    eapply Forall2_Forall2 in Hwc2; [|eapply Hwc3]. clear Hwc3.\n    replace (nclocksof es) with (nclocksof x) in Hwc2.\n    2: { eapply unnest_rhss_nclocksof in H... }\n    clear H Hwc1 Hwc1''.\n    revert es xs Hwc2.\n    induction x; intros; simpl in *; constructor.\n    + inv Hwc1'.\n      assert (length (firstn (numstreams a) xs) = length (nclockof a)) as Hlen1.\n      { apply Forall2_length in Hwc2. rewrite app_length in Hwc2.\n        rewrite firstn_length, Hwc2, length_nclockof_numstreams.\n        apply Nat.min_l. omega. }\n      rewrite <- (firstn_skipn (numstreams a) xs) in Hwc2.\n      apply Forall2_app_split in Hwc2 as [Hwc2 _]...\n      repeat constructor...\n      * simpl. rewrite app_nil_r.\n        eapply Forall2_impl_In... intros; simpl in *. destruct H3...\n      * simpl. rewrite app_nil_r, clockof_nclockof, Forall2_map_2.\n        eapply Forall2_impl_In... intros; simpl in *. destruct H3...\n        apply in_or_app. apply in_app_or in H3. destruct H3...\n        right. eapply st_follows_clocks_incl...\n    + inv Hwc1'. apply IHx...\n      assert (length (firstn (numstreams a) xs) = length (nclockof a)) as Hlen1.\n      { apply Forall2_length in Hwc2. rewrite app_length in Hwc2.\n        rewrite firstn_length, Hwc2, length_nclockof_numstreams.\n        apply Nat.min_l. omega. }\n      rewrite <- (firstn_skipn (numstreams a) xs) in Hwc2.\n      apply Forall2_app_split in Hwc2 as [_ Hwc2]...\n  Qed.\n\n  Corollary unnest_equations_wc_eq : forall G vars eqs eqs' st st',\n      Forall (wc_equation G (vars++st_clocks st)) eqs ->\n      unnest_equations G eqs st = (eqs', st') ->\n      Forall (wc_equation G (vars++st_clocks st')) eqs'.\n  Proof with eauto.\n    induction eqs; intros * Hwc Hnorm;\n      unfold unnest_equations in *; simpl in *; repeat inv_bind...\n    assert (st_follows st x1) as Hfollows1 by repeat solve_st_follows.\n    assert (st_follows x1 st') as Hfollows2 by repeat solve_st_follows.\n    inv Hwc. eapply unnest_equation_wc_eq in H...\n    assert (unnest_equations G eqs x1 = (concat x2, st')) as Hnorm.\n      { unfold unnest_equations; repeat inv_bind. repeat eexists; eauto. inv_bind; eauto. }\n    apply IHeqs in Hnorm... 2:solve_forall; repeat solve_incl.\n    apply Forall_app; split...\n    solve_forall; repeat solve_incl.\n  Qed.\n\n  (** *** The produced environment is also well-clocked *)\n\n  Fact unnest_reset_wc_env : forall G vars e e' eqs' st st',\n      wc_global G ->\n      wc_env (vars++st_clocks st) ->\n      LiftO True (fun e => forall es' eqs' st',\n                   unnest_exp G true e st = (es', eqs', st') ->\n                   wc_env (vars++st_clocks st')) e ->\n      LiftO True (wc_exp G (vars ++ st_clocks st)) e ->\n      unnest_reset (unnest_exp G true) e st = (e', eqs', st') ->\n      wc_env (vars++st_clocks st').\n  Proof with eauto.\n    intros * HwcG Hwenv Hun Hwc Hnorm.\n    unnest_reset_spec; simpl in *; eauto.\n    eapply fresh_ident_wc_env in Hfresh; eauto.\n    assert (Hwc' := Hk0). eapply unnest_exp_wc in Hwc' as [Hwc' _]; eauto.\n    eapply wc_exp_clocksof in Hwc'; eauto.\n    eapply unnest_exp_no_fresh in Hk0.\n    rewrite Hk0 in Hwc'; simpl in Hwc'; rewrite app_nil_r in Hwc'.\n    destruct l; simpl in *; inv Hhd. constructor.\n    apply Forall_app in Hwc' as [Hwc' _].\n    rewrite clockof_annot in Hwc'.\n    destruct (annot e); simpl in *. inv H0; constructor.\n    inv Hwc'; auto.\n  Qed.\n\n  Fact map_bind2_wc_env {A A1 A2 : Type} :\n    forall vars (k : A -> Unnesting.FreshAnn (A1 * A2)) a a1s a2s st st',\n      wc_env (vars++st_clocks st) ->\n      map_bind2 k a st = (a1s, a2s, st') ->\n      (forall st st' a es a2s, k a st = (es, a2s, st') -> st_follows st st') ->\n      Forall (fun a => forall a1s a2s st0 st0',\n                  wc_env (vars++st_clocks st0) ->\n                  k a st0 = (a1s, a2s, st0') ->\n                  st_follows st st0 ->\n                  st_follows st0' st' ->\n                  wc_env (vars++st_clocks st0')) a ->\n      wc_env (vars++st_clocks st').\n  Proof with eauto.\n    induction a; intros a1s a2s st st' Hclocks Hmap Hfollows Hf;\n      simpl in Hmap; repeat inv_bind...\n    inv Hf.\n    specialize (H3 _ _ _ _ Hclocks H).\n    eapply IHa in H3...\n    - reflexivity.\n    - eapply map_bind2_st_follows...\n      solve_forall...\n    - solve_forall.\n      eapply H2 in H5...\n      etransitivity...\n  Qed.\n\n  Lemma unnest_noops_exps_wc_env : forall G vars cks es es' eqs' st st' ,\n      wc_global G ->\n      length es = length cks ->\n      Forall normalized_lexp es ->\n      Forall (fun e => numstreams e = 1) es ->\n      Forall (wc_exp G (vars++st_clocks st)) es ->\n      wc_env (vars++st_clocks st) ->\n      unnest_noops_exps cks es st = (es', eqs', st') ->\n      wc_env (vars++st_clocks st').\n  Proof.\n    unfold unnest_noops_exps.\n    intros * HwcG Hl Hnormed Hnum Hwc Henv Hunt. repeat inv_bind.\n    eapply map_bind2_wc_env in H; eauto.\n    1:intros ? ? (?&?) ? ? Hun; eauto.\n    eapply Forall2_combine'. eapply Forall2_forall2. split; auto.\n    intros * Hn Hnth1 Hnth2 * Henv' Hunt Hf1 Hf2; subst.\n    unfold unnest_noops_exp in Hunt.\n    assert (In (nth n es b) es) as Hin by (eapply nth_In; congruence).\n    eapply Forall_forall in Hnormed; eauto.\n    eapply Forall_forall in Hnum; eauto.\n    eapply Forall_forall in Hwc; eauto.\n    rewrite <- length_annot_numstreams in Hnum. singleton_length.\n    destruct p as (?&?&?).\n    destruct (is_noops_exp _ _); repeat inv_bind; eauto.\n    eapply fresh_ident_wc_env in H0; eauto.\n    eapply wc_exp_clockof in Hwc; eauto.\n    rewrite clockof_annot, Hsingl in Hwc; simpl in Hwc.\n    erewrite normalized_lexp_no_fresh, app_nil_r in Hwc; auto. inv Hwc.\n    repeat solve_incl.\n  Qed.\n\n  Fact unnest_exp_wc_env : forall G vars e is_control es' eqs' st st',\n      wc_global G ->\n      wc_env (vars++st_clocks st) ->\n      wc_exp G (vars++st_clocks st) e ->\n      unnest_exp G is_control e st = (es', eqs', st') ->\n      wc_env (vars++st_clocks st').\n  Proof with eauto.\n    induction e using exp_ind2; intros is_control es' eqs' st st' HwG Hwenv Hwc Hnorm;\n      assert (Hnorm':=Hnorm); apply unnest_exp_fresh_incl in Hnorm';\n      simpl in *;\n      assert (Hwc':=Hwc); inv Hwc'. 1-11:repeat inv_bind...\n    - (* binop *)\n      assert (st_follows st x1) as Hfollows by eauto.\n      eapply IHe1 in H...\n      eapply IHe2 in H0...\n      repeat solve_incl.\n    - (* fby *)\n      Local Ltac solve_map_bind2' :=\n        solve_forall;\n        match goal with\n        | Hnorm : unnest_exp _ _ _ _ = _, H : context [unnest_exp _ _ _ _ = _ -> _] |- _ =>\n          eapply H in Hnorm; eauto; repeat solve_incl\n        end.\n      rewrite Forall2_eq in H6, H7.\n      assert (Hwenv1:=H1). eapply map_bind2_wc_env in Hwenv1... 2:solve_map_bind2'.\n      assert (Hwenv2:=H2). eapply map_bind2_wc_env in Hwenv2... 2:solve_map_bind2'.\n      eapply idents_for_anns_wc_env in H3...\n      assert (Forall (wc_clock ((vars ++ st_clocks x1))) (map clock_of_nclock a)).\n        { rewrite H6.\n          eapply wc_exp_clocksof in H4... eapply Forall_impl; [|eauto]. intros.\n          eapply wc_clock_incl; [|eauto]. rewrite <- app_assoc in *.\n          apply incl_appr', incl_app; repeat solve_incl.\n          apply map_bind2_unnest_exp_fresh_incl in H1...\n          unfold st_clocks. apply incl_map, H1. }\n        solve_forall; repeat solve_incl.\n    - (* arrow *)\n      rewrite Forall2_eq in H6, H7.\n      assert (Hwenv1:=H1). eapply map_bind2_wc_env in Hwenv1... 2:solve_map_bind2'.\n      assert (Hwenv2:=H2). eapply map_bind2_wc_env in Hwenv2... 2:solve_map_bind2'.\n      eapply idents_for_anns_wc_env in H3...\n      assert (Forall (wc_clock ((vars ++ st_clocks x1))) (map clock_of_nclock a)).\n        { rewrite H6.\n          eapply wc_exp_clocksof in H4... eapply Forall_impl; [|eauto]. intros.\n          eapply wc_clock_incl; [|eauto]. rewrite <- app_assoc in *.\n          apply incl_appr', incl_app; repeat solve_incl.\n          apply map_bind2_unnest_exp_fresh_incl in H1...\n          unfold st_clocks. apply incl_map, H1. }\n        solve_forall; repeat solve_incl.\n    - (* when *)\n      eapply map_bind2_wc_env in H0... solve_map_bind2'.\n    - (* merge *)\n      assert (Hwenv1:=H1). eapply map_bind2_wc_env in Hwenv1... 2:solve_map_bind2'.\n      assert (Hwenv2:=H2). eapply map_bind2_wc_env in Hwenv2... 2:solve_map_bind2'.\n      destruct is_control; repeat inv_bind...\n      eapply idents_for_anns_wc_env in H3...\n      repeat rewrite Forall_map.\n      rewrite Forall_forall. intros ty _; simpl.\n      unfold wc_env in Hwenv; rewrite Forall_forall in Hwenv; eapply Hwenv in H7; simpl in H7.\n      repeat solve_incl.\n    - (* ite *)\n      assert (Hwenv1:=H1). eapply IHe in Hwenv1...\n      assert (Hwenv2:=H2). eapply map_bind2_wc_env in Hwenv2... 2:solve_map_bind2'.\n      assert (Hwenv3:=H3). eapply map_bind2_wc_env in Hwenv3... 2:solve_map_bind2'.\n      destruct is_control; repeat inv_bind...\n      eapply idents_for_anns_wc_env in H4...\n      repeat rewrite Forall_map.\n      rewrite Forall_forall. intros ty _; simpl.\n      eapply wc_exp_clockof in H5... rewrite H8 in H5. inv H5.\n      solve_incl. rewrite <- app_assoc. apply incl_appr', incl_app; [repeat solve_incl|].\n      unfold st_clocks. apply incl_map.\n      eapply unnest_exp_fresh_incl in H1. etransitivity...\n      apply st_follows_incl. repeat solve_st_follows.\n    - (* app *)\n      assert (Hwenv1:=H1). eapply map_bind2_wc_env in Hwenv1... 2:solve_map_bind2'.\n      assert (Hwenv2:=H2). eapply unnest_noops_exps_wc_env in Hwenv2...\n      2:{ unfold find_node_incks. rewrite H6.\n          eapply Forall2_length in H7. rewrite map_length.\n          eapply map_bind2_unnest_exp_length in H1; eauto. rewrite length_nclocksof_annots, length_idck in H7.\n          congruence. }\n      2:{ eapply map_bind2_unnest_exp_numstreams; eauto. }\n      2:{ eapply map_bind2_unnest_exp_wc; eauto. }\n      eapply idents_for_anns'_wc_env...\n      apply wc_exp_clockof in Hwc... simpl in Hwc.\n      unfold clock_of_nclock, stripname in Hwc.\n      rewrite map_map. eapply Forall_impl; [|eauto].\n      intros. rewrite <- app_assoc in H4. repeat solve_incl.\n      apply incl_app; [repeat solve_incl|].\n        unfold st_clocks. apply incl_map...\n    - (* app (reset) *)\n      do 6 inv_bind.\n      assert (st_follows x4 x7) as Hfollows.\n      { eapply (unnest_reset_st_follows _ _ (Some r)) in H3; eauto. }\n      assert (Hwenv2:=H2). eapply unnest_noops_exps_wc_env in Hwenv2...\n      2:{ unfold find_node_incks. rewrite H6.\n          eapply Forall2_length in H7. rewrite map_length.\n          eapply unnest_exps_length in H1; eauto. rewrite length_nclocksof_annots, length_idck in H7.\n          congruence. }\n      2:{ eapply unnest_exps_numstreams; eauto. }\n      2:{ eapply unnest_exps_wc; eauto. }\n      2:{ clear H3; repeat inv_bind. eapply map_bind2_wc_env... solve_map_bind2'. }\n      eapply idents_for_anns'_wc_env in H4...\n      + assert (Hs:=H3). eapply unnest_reset_Some in Hs as [er' ?]; subst.\n        eapply (unnest_reset_wc_env _ _ (Some r)) in H3; simpl in *; eauto.\n        1-2:clear H3; repeat inv_bind.\n        intros; eapply H in H3; eauto.\n        1,2:repeat solve_incl.\n      + clear H3; repeat inv_bind.\n        apply wc_exp_clockof in Hwc... simpl in Hwc.\n        unfold clock_of_nclock, stripname in Hwc.\n        rewrite map_map. eapply Forall_impl; [|eauto].\n        intros. rewrite <- app_assoc in H3. repeat solve_incl.\n        apply incl_app; [repeat solve_incl|].\n        unfold st_clocks. apply incl_map...\n  Qed.\n\n  Corollary map_bind2_unnest_exp_wc_env : forall G vars es is_control es' eqs' st st',\n      wc_global G ->\n      wc_env (vars++st_clocks st) ->\n      Forall (wc_exp G (vars++st_clocks st)) es ->\n      map_bind2 (unnest_exp G is_control) es st = (es', eqs', st') ->\n      wc_env (vars++st_clocks st').\n  Proof.\n    intros.\n    eapply map_bind2_wc_env in H2; eauto.\n    rewrite Forall_forall in *; intros.\n    eapply unnest_exp_wc_env in H5; eauto.\n    eapply H1 in H3. repeat solve_incl.\n  Qed.\n\n  Corollary unnest_exps_wc_env : forall G vars es es' eqs' st st',\n      wc_global G ->\n      wc_env (vars++st_clocks st) ->\n      Forall (wc_exp G (vars++st_clocks st)) es ->\n      unnest_exps G es st = (es', eqs', st') ->\n      wc_env (vars++st_clocks st').\n  Proof with eauto.\n    intros * HwG Hwenv Hwc Hnorm.\n    unfold unnest_exps in Hnorm; repeat inv_bind.\n    eapply map_bind2_wc_env in H...\n    solve_forall.\n    eapply unnest_exp_wc_env in H3...\n    repeat solve_incl.\n  Qed.\n\n  Fact unnest_rhs_wc_env : forall G vars e es' eqs' st st',\n      wc_global G ->\n      wc_env (vars++st_clocks st) ->\n      wc_exp G (vars++st_clocks st) e ->\n      unnest_rhs G e st = (es', eqs', st') ->\n      wc_env (vars++st_clocks st').\n  Proof with eauto.\n    intros * HwG Hwenv Hwc Hnorm.\n    destruct e; unfold unnest_rhs in Hnorm;\n      try (solve [eapply unnest_exp_wc_env in Hnorm; eauto]);\n      inv Hwc. 1-3:repeat inv_bind.\n    - (* fby *)\n      assert (Hwenv1:=H). eapply unnest_exps_wc_env in Hwenv1...\n      assert (Hwenv2:=H0). eapply unnest_exps_wc_env in Hwenv2...\n      solve_forall; repeat solve_incl.\n    - (* arrow *)\n      assert (Hwenv1:=H). eapply unnest_exps_wc_env in Hwenv1...\n      assert (Hwenv2:=H0). eapply unnest_exps_wc_env in Hwenv2...\n      solve_forall; repeat solve_incl.\n    - (* app *)\n      assert (Hnorm:=H). eapply unnest_exps_wc_env in H...\n      eapply unnest_noops_exps_wc_env in H0...\n      + unfold find_node_incks. rewrite H4.\n        eapply Forall2_length in H5. rewrite map_length.\n        eapply unnest_exps_length in Hnorm; eauto. rewrite length_nclocksof_annots, length_idck in H5.\n        congruence.\n      + eapply unnest_exps_numstreams; eauto.\n      + eapply unnest_exps_wc; eauto.\n    - (* app (reset) *)\n      do 5 inv_bind.\n      assert (wc_env (vars ++ st_clocks x4)).\n      { clear H1.\n        assert (Hnorm:=H). eapply unnest_exps_wc_env in H...\n        eapply unnest_noops_exps_wc_env in H0...\n        + unfold find_node_incks. rewrite H4.\n          eapply Forall2_length in H5. rewrite map_length.\n          eapply unnest_exps_length in Hnorm; eauto. rewrite length_nclocksof_annots, length_idck in H5.\n          congruence.\n        + eapply unnest_exps_numstreams; eauto.\n        + eapply unnest_exps_wc; eauto.\n      }\n      eapply (unnest_reset_wc_env G vars (Some r)) in H1; simpl; eauto.\n      1-2:clear H1.\n      intros; eapply unnest_exp_wc_env in H1; eauto.\n      1,2:repeat solve_incl.\n  Qed.\n\n  Corollary unnest_rhss_wc_env : forall G vars es es' eqs' st st',\n      wc_global G ->\n      wc_env (vars++st_clocks st) ->\n      Forall (wc_exp G (vars++st_clocks st)) es ->\n      unnest_rhss G es st = (es', eqs', st') ->\n      wc_env (vars++st_clocks st').\n  Proof with eauto.\n    intros * HwG Hwenv Hwc Hnorm.\n    unfold unnest_rhss in Hnorm; repeat inv_bind.\n    eapply map_bind2_wc_env in H...\n    solve_forall.\n    eapply unnest_rhs_wc_env in H3...\n    repeat solve_incl.\n  Qed.\n\n  Fact unnest_equation_wc_env : forall G vars e eqs' st st',\n      wc_global G ->\n      wc_env (vars++st_clocks st) ->\n      wc_equation G (vars++st_clocks st) e ->\n      unnest_equation G e st = (eqs', st') ->\n      wc_env (vars++st_clocks st').\n  Proof with eauto.\n    intros G vars [xs es] * HwG Hwenv [Hwc _] Hnorm.\n    unfold unnest_equation in Hnorm. repeat inv_bind.\n    eapply unnest_rhss_wc_env in H...\n  Qed.\n\n  Corollary unnest_equations_wc_env : forall G vars eqs eqs' st st',\n      wc_global G ->\n      wc_env (vars++st_clocks st) ->\n      Forall (wc_equation G (vars++st_clocks st)) eqs ->\n      unnest_equations G eqs st = (eqs', st') ->\n      wc_env (vars++st_clocks st').\n  Proof with eauto.\n    induction eqs; intros * HwG Hwenv Hwc Hnorm;\n      unfold unnest_equations in *; simpl in *; repeat inv_bind...\n    assert (st_follows st x1) as Hfollows1 by repeat solve_st_follows.\n    inv Hwc. eapply unnest_equation_wc_env in H...\n    assert (unnest_equations G eqs x1 = (concat x2, st')) as Hnorm.\n    { unfold unnest_equations; repeat inv_bind. repeat eexists; eauto. inv_bind; eauto. }\n    apply IHeqs in Hnorm as Hwenv2... solve_forall; repeat solve_incl.\n  Qed.\n\n  Lemma unnest_node_wc : forall G n Hwl Hpref,\n      wc_global G ->\n      wc_node G n ->\n      wc_node G (unnest_node G n Hwl Hpref).\n  Proof with eauto.\n    intros * HwG [Hin [Hout [Henv Heq]]].\n    unfold unnest_node.\n    repeat constructor; simpl; auto.\n    - remember (unnest_equations _ _ _) as res. symmetry in Heqres.\n      destruct res as [eqs' st']; simpl.\n      unfold idck. repeat rewrite map_app.\n      eapply unnest_equations_wc_env in Heqres as Henv'...\n      2,3:unfold st_clocks; rewrite init_st_anns, app_nil_r...\n      2:rewrite (Permutation_app_comm (n_vars _)) in Heq...\n      unfold idck in Henv'; repeat rewrite map_app in Henv'; repeat rewrite <- app_assoc in Henv'...\n    - remember (unnest_equations _ _ _) as res. symmetry in Heqres.\n      destruct res as [eqs' st']; simpl.\n      unfold idck. repeat rewrite map_app.\n      eapply unnest_equations_wc_eq in Heqres as Hwc'...\n      2:unfold st_clocks; rewrite init_st_anns, app_nil_r...\n      unfold st_clocks, idck in Hwc'; repeat rewrite map_app in Hwc'; repeat rewrite <- app_assoc in *.\n      solve_forall; solve_incl.\n      apply incl_appr', incl_appr'.\n      rewrite Permutation_app_comm. reflexivity.\n  Qed.\n\n  Lemma unnest_global_wc : forall G Hwl Hprefs,\n      wc_global G ->\n      wc_global (unnest_global G Hwl Hprefs).\n  Proof.\n    induction G; intros * Hwc; simpl; inv Hwc.\n    - constructor.\n    - constructor.\n      + eapply IHG; eauto.\n      + eapply iface_eq_wc_node; eauto.\n        eapply unnest_global_eq.\n        eapply unnest_node_wc; eauto.\n      + eapply unnest_global_names; eauto.\n  Qed.\n\n  (** ** Preservation of clocking through second pass *)\n\n  Fact add_whens_clockof : forall e ty ck,\n      clockof e = [Cbase] ->\n      clockof (add_whens e ty ck) = [ck].\n  Proof. induction ck; intros Hlen; auto. Qed.\n\n  Fact add_whens_wc_exp : forall G vars e ty ck,\n      clockof e = [Cbase] ->\n      wc_exp G vars e ->\n      wc_clock vars ck ->\n      wc_exp G vars (add_whens e ty ck).\n  Proof with eauto.\n    induction ck; intros Hclof Hwc Hwc2; inv Hwc2; simpl...\n    repeat constructor; simpl... 1,2:rewrite app_nil_r.\n    + rewrite add_whens_clockof...\n    + rewrite add_whens_clockof...\n  Qed.\n\n  Fact fby_iteexp_wc_exp : forall G vars e0 e ty ck name e' eqs' st st',\n      wc_exp G (vars++st_clocks' st) e0 ->\n      wc_exp G (vars++st_clocks' st) e ->\n      clockof e0 = [ck] ->\n      clockof e = [ck] ->\n      unnamed_stream (ty, (ck, name)) ->\n      fby_iteexp e0 e (ty, (ck, name)) st = (e', eqs', st') ->\n      wc_exp G (vars++st_clocks' st') e'.\n  Proof with eauto.\n    intros * Hwc1 Hwc2 Hck1 Hck2 Hunnamed Hfby.\n    unfold fby_iteexp in Hfby; simpl in *.\n    inv Hunnamed; simpl in H; subst.\n    assert (st_follows st st') as Hfollows.\n    { eapply (fby_iteexp_st_follows _ _ (ty, (ck, None))) in Hfby; eauto. }\n    repeat inv_bind; repeat econstructor; simpl...\n    4,5:rewrite app_nil_r; unfold clock_of_nclock, stripname; simpl.\n    4-5:rewrite Hck1; repeat constructor.\n    2:repeat solve_incl.\n    1-2:(apply in_or_app, or_intror; unfold st_clocks', idty, idck; rewrite map_map).\n    (apply init_var_for_clock_In in H; simpl in *;\n     eapply st_follows_incl in H; eauto;\n     simpl_In; eexists; split; eauto; eauto).\n    (simpl_In; exists (x2, (ty, ck, false)); simpl; split; auto;\n     eapply fresh_ident_In in H0; eauto).\n  Qed.\n\n  Fact fresh_ident_wc_env' : forall pref vars ty ck b id st st',\n      wc_env (vars++st_clocks' st) ->\n      wc_clock (vars++st_clocks' st) ck ->\n      fresh_ident pref (ty, ck, b) st = (id, st') ->\n      wc_env (vars++st_clocks' st').\n  Proof.\n    intros * Hwenv Hwc Hfresh.\n    apply fresh_ident_anns in Hfresh.\n    unfold st_clocks' in *. rewrite Hfresh; simpl.\n    rewrite <- Permutation_middle.\n    constructor; simpl.\n    - repeat solve_incl.\n    - eapply Forall_impl; [|eauto].\n      intros; simpl in *. repeat solve_incl.\n  Qed.\n\n  Fact init_var_for_clock_wc_env : forall vars cl id eqs' st st',\n      wc_env (vars++st_clocks' st) ->\n      wc_clock (vars++st_clocks' st) cl ->\n      init_var_for_clock cl st = (id, eqs', st') ->\n      wc_env (vars++st_clocks' st').\n  Proof with eauto.\n    intros vars cl id eqs' st st' Hwenv Hwc Hinit.\n    unfold init_var_for_clock in Hinit.\n    destruct find.\n    - destruct p. inv Hinit...\n    - destruct fresh_ident eqn:Hfresh. inv Hinit.\n      eapply fresh_ident_wc_env' in Hfresh...\n  Qed.\n\n  Fact fby_iteexp_wc_env : forall vars e0 e ty cl es' eqs' st st',\n      wc_env (vars++st_clocks' st) ->\n      wc_clock (vars++st_clocks' st) (fst cl) ->\n      fby_iteexp e0 e (ty, cl) st = (es', eqs', st') ->\n      wc_env (vars++st_clocks' st').\n  Proof with eauto.\n    intros vars e0 e ty [ck name] es' eqs' st st' Hwenv Hwc Hfby.\n    unfold fby_iteexp in Hfby; repeat inv_bind...\n    eapply fresh_ident_wc_env' in H0... 2:repeat solve_incl.\n    eapply init_var_for_clock_wc_env in H... eapply init_var_for_clock_st_follows in H...\n  Qed.\n\n  Fact init_var_for_clock_wc_eq : forall G vars ck id eqs' st st',\n      wc_clock (vars++st_clocks' st) ck ->\n      init_var_for_clock ck st = (id, eqs', st') ->\n      Forall (wc_equation G (vars++st_clocks' st')) eqs'.\n  Proof with eauto.\n    intros * Hwc Hinit.\n    unfold init_var_for_clock in Hinit.\n    destruct find.\n    - destruct p; repeat inv_bind...\n    - destruct fresh_ident eqn:Hfresh; repeat inv_bind.\n      repeat constructor; simpl...\n      + apply add_whens_wc_exp... repeat solve_incl.\n      + apply add_whens_wc_exp... repeat solve_incl.\n      + rewrite app_nil_r, add_whens_clockof...\n      + rewrite app_nil_r, add_whens_clockof...\n      + apply fresh_ident_In in Hfresh.\n        apply in_or_app; right.\n        unfold st_clocks', idck, idty. rewrite map_map.\n        simpl_In. exists (id, (Op.bool_type, ck, true)); auto.\n  Qed.\n\n  Fact normalized_lexp_wc_exp_clockof : forall G vars e,\n      normalized_lexp e ->\n      wc_env vars ->\n      wc_exp G vars e ->\n      Forall (wc_clock vars) (clockof e).\n  Proof with eauto.\n    intros G vars e Hnormed Hwenv Hwc.\n    induction Hnormed; inv Hwc;\n      simpl; unfold clock_of_nclock, stripname; simpl; repeat constructor...\n    1,2:(unfold wc_env in Hwenv; rewrite Forall_forall in Hwenv; eapply Hwenv in H0; eauto).\n    - eapply IHHnormed in H1. rewrite H4 in H1. inv H1...\n    - eapply IHHnormed1 in H3. rewrite H6 in H3. inv H3...\n    - inv H3.\n      eapply IHHnormed in H1.\n      simpl in H7. rewrite app_nil_r in H7. symmetry in H7.\n      singleton_length.\n      inv H6. inv H1...\n  Qed.\n\n  Fact fby_iteexp_wc_eq : forall G vars e0 e ty ck name e' eqs' st st',\n      normalized_lexp e0 ->\n      wc_env (vars++st_clocks' st) ->\n      wc_exp G (vars++st_clocks' st) e0 ->\n      wc_exp G (vars++st_clocks' st) e ->\n      clockof e0 = [ck] ->\n      clockof e = [ck] ->\n      unnamed_stream (ty, (ck, name)) ->\n      fby_iteexp e0 e (ty, (ck, name)) st = (e', eqs', st') ->\n      Forall (wc_equation G (vars++st_clocks' st')) eqs'.\n  Proof with eauto.\n    intros * Hnormed Henv Hwc1 Hwc2 Hcl1 Hcl2 Hunnamed Hfby.\n    assert (wc_clock (vars++st_clocks' st) ck) as Hwck.\n    { eapply normalized_lexp_wc_exp_clockof in Hwc1...\n      rewrite Hcl1 in Hwc1; inv Hwc1; auto. }\n    unfold fby_iteexp in Hfby; simpl in *.\n    repeat inv_bind; repeat constructor; simpl...\n    - eapply add_whens_wc_exp...\n      eapply init_var_for_clock_st_follows in H. repeat solve_incl.\n    - eapply init_var_for_clock_st_follows in H. repeat solve_incl.\n    - rewrite app_nil_r, add_whens_clockof...\n    - rewrite app_nil_r. rewrite Hcl2...\n    - unfold unnamed_stream in Hunnamed; simpl in Hunnamed. rewrite Hunnamed. constructor.\n    - eapply fresh_ident_In in H0.\n      apply in_or_app; right.\n      unfold clock_of_nclock, stripname; simpl in *.\n      unfold st_clocks', idck, idty. rewrite map_map.\n      simpl_In. exists (x2, (ty, ck, false)); auto.\n    - eapply init_var_for_clock_wc_eq with (G:=G) in H...\n      solve_forall; repeat solve_incl.\n  Qed.\n\n  Fact fby_equation_wc_eq : forall G vars to_cut eq eqs' st st',\n      unnested_equation G eq ->\n      wc_env (vars++st_clocks' st) ->\n      wc_equation G (vars++st_clocks' st) eq ->\n      fby_equation to_cut eq st = (eqs', st') ->\n      (Forall (wc_equation G (vars++st_clocks' st')) eqs' /\\ wc_env (vars++st_clocks' st')).\n  Proof with eauto.\n    intros * Hunt Hwenv Hwc Hfby.\n    inv_fby_equation Hfby to_cut eq; destruct x2 as (ty&ck&name).\n    - (* fby (constant) *)\n      destruct PS.mem; repeat inv_bind; auto.\n      destruct Hwc as (Hwc&Hn&Hins).\n      apply Forall_singl in Hwc. apply Forall2_singl in Hn. apply Forall2_singl in Hins.\n      assert (Hwc':=Hwc). inv Hwc'.\n      simpl in *; rewrite app_nil_r in *.\n      apply Forall_singl in H3; apply Forall_singl in H4.\n      apply Forall_singl in H7; inv H7; simpl in H0; subst.\n      assert (wc_clock (vars ++ st_clocks' st) ck).\n      { eapply wc_env_var; eauto. }\n      eapply wc_exp_incl with (vars':=vars ++ st_clocks' st') in Hwc; repeat solve_incl.\n      repeat (econstructor; eauto).\n      + eapply fresh_ident_In in H.\n        eapply in_or_app, or_intror. unfold st_clocks', idck, idty.\n        simpl_In. exists (x2, (ty, ck)); split; auto.\n        simpl_In. eexists; split; eauto. auto.\n      + assert (incl (vars++st_clocks' st) (vars++st_clocks' st')); eauto. repeat solve_incl.\n      + eapply fresh_ident_In in H.\n        eapply in_or_app, or_intror. unfold st_clocks', idck, idty.\n        simpl_In. exists (x2, (ty, ck)); split; auto.\n        simpl_In. eexists; split; eauto. auto.\n      + eapply fresh_ident_wc_env' in H; eauto.\n    - (* fby *)\n      assert (st_follows st st') as Hfollows by eauto.\n      destruct Hwc as [Hwc [Hn Hins]].\n      apply Forall_singl in Hwc. apply Forall2_singl in Hn. apply Forall2_singl in Hins.\n      inv Hwc.\n      simpl in *; rewrite app_nil_r in *.\n      apply Forall_singl in H3; apply Forall_singl in H4.\n      apply Forall_singl in H7; inv H7. simpl in H0; subst.\n      rewrite Forall2_eq in H5, H6.\n      assert (Hwce:=H). eapply fby_iteexp_wc_exp in Hwce; eauto. 2:constructor.\n      assert (Hck:=H). eapply (fby_iteexp_nclockof _ _ (ty, (ck, None))) in Hck; eauto.\n      assert (Hwceq:=H). eapply fby_iteexp_wc_eq in Hwceq; eauto.\n      2:(clear - Hunt; inv Hunt; eauto; inv H0; inv H). 2:constructor; auto.\n      assert (wc_clock (vars ++ st_clocks' st) ck).\n      { eapply wc_env_var; eauto. }\n      eapply (fby_iteexp_wc_env _ _ _ ty (ck, None)) in H...\n      repeat constructor; auto; simpl; rewrite app_nil_r.\n      + rewrite Hck. repeat constructor.\n      + rewrite clockof_nclockof, Hck. repeat constructor.\n        repeat solve_incl.\n    - (* arrow *)\n      repeat inv_bind.\n      destruct Hwc as [Hwc [Hn Hins]].\n      apply Forall_singl in Hwc. apply Forall2_singl in Hn. apply Forall2_singl in Hins.\n      inv Hwc.\n      simpl in *; rewrite app_nil_r in *.\n      apply Forall_singl in H3; apply Forall_singl in H4.\n      apply Forall_singl in H7; inv H7.\n      rewrite Forall2_eq in H5, H6.\n      assert (wc_clock (vars ++ st_clocks' st) ck).\n      { eapply wc_env_var; eauto. }\n      assert (Hwce:=H). eapply init_var_for_clock_wc_env in Hwce; eauto.\n      split; eauto.\n      assert (st_follows st st') as Hfollows.\n      { eapply init_var_for_clock_st_follows; eauto. }\n      simpl in *; inv H0.\n      repeat econstructor; auto.\n      2,3,4,7:repeat solve_incl.\n      2,3,4,5:simpl; rewrite app_nil_r; try rewrite <- H5; try rewrite <- H6; auto.\n      + eapply init_var_for_clock_In in H.\n        apply in_or_app, or_intror. unfold st_clocks', idck, idty. rewrite map_map.\n        repeat simpl_In. exists (x2, (Op.bool_type, ck, true)); auto.\n      + assert (incl (vars++st_clocks' st) (vars++st_clocks' st')) by repeat solve_incl; auto.\n      + eapply init_var_for_clock_wc_eq in H; eauto.\n  Qed.\n\n  Fact fby_equations_wc_eq : forall G vars to_cut eqs eqs' st st',\n      Forall (unnested_equation G) eqs ->\n      wc_env (vars++st_clocks' st) ->\n      Forall (wc_equation G (vars++st_clocks' st)) eqs ->\n      fby_equations to_cut eqs st = (eqs', st') ->\n      (Forall (wc_equation G (vars++st_clocks' st')) eqs' /\\ wc_env (vars++st_clocks' st')).\n  Proof.\n    induction eqs; intros * Hunt Henv Hwc Hfby;\n      unfold fby_equations in *; repeat inv_bind; simpl; auto.\n    inv Hunt. inv Hwc.\n    assert (fby_equations to_cut eqs x1 = (concat x2, st')) as Hnorm.\n    { unfold fby_equations. repeat inv_bind. repeat eexists; eauto.\n      inv_bind; auto. }\n    assert (H':=H). eapply fby_equation_wc_eq in H as [Hwc' Henv']; auto. 2,3,4:eauto.\n    apply IHeqs in Hnorm as [Hwc'' Henv'']; auto.\n    2:solve_forall; repeat solve_incl; eapply fby_equation_st_follows in H'; eauto.\n    rewrite Forall_app; repeat split; eauto.\n    solve_forall; repeat solve_incl.\n  Qed.\n\n  Lemma normfby_node_wc : forall G to_cut n Hunt Hpref,\n      wc_node G n ->\n      wc_node G (normfby_node G to_cut n Hunt Hpref).\n  Proof.\n    intros * [Hclin [Hclout [Hclvars Heq]]].\n    unfold normfby_node.\n    repeat constructor; simpl; auto.\n    - remember (fby_equations _ _ _) as res. symmetry in Heqres. destruct res as [eqs' st'].\n      eapply fby_equations_wc_eq in Heqres as [_ ?]; eauto.\n      2,3:unfold st_clocks'; rewrite init_st_anns, app_nil_r.\n      2:eapply Hclvars.\n      + repeat rewrite idck_app in *.\n        repeat rewrite <- app_assoc in H; auto.\n      + solve_forall.\n        eapply wc_equation_incl; eauto.\n        rewrite (Permutation_app_comm (n_out n)). reflexivity.\n    - remember (fby_equations _ _ _) as res. symmetry in Heqres. destruct res as [eqs' st'].\n      eapply fby_equations_wc_eq in Heqres as [? _]; eauto.\n      2,3:unfold st_clocks'; rewrite init_st_anns, app_nil_r.\n      2:eapply Hclvars.\n      + repeat rewrite idck_app in *.\n        repeat rewrite <- app_assoc in *.\n        solve_forall. eapply wc_equation_incl; eauto.\n        apply incl_appr'.\n        rewrite (Permutation_app_comm (idck (n_out _))), <- app_assoc. apply incl_appr', incl_refl.\n      + solve_forall.\n        eapply wc_equation_incl; eauto.\n        rewrite (Permutation_app_comm (n_out n)). reflexivity.\n  Qed.\n\n  Lemma normfby_global_wc : forall G Hunt Hprefs,\n      wc_global G ->\n      wc_global (normfby_global G Hunt Hprefs).\n  Proof.\n    induction G; intros * Hwt; simpl; inv Hwt.\n    - constructor.\n    - constructor.\n      + eapply IHG; eauto.\n      + remember (normfby_node _ _) as n'. symmetry in Heqn'.\n        subst.\n        eapply iface_eq_wc_node; eauto.\n        eapply normfby_global_eq.\n        eapply normfby_node_wc; eauto.\n      + eapply normfby_global_names; eauto.\n  Qed.\n\n  (** ** Conclusion *)\n\n  Lemma normalize_global_wc : forall G G' Hwl Hprefs,\n      wc_global G ->\n      normalize_global G Hwl Hprefs = Errors.OK G' ->\n      wc_global G'.\n  Proof.\n    intros * Hwc Hnorm.\n    unfold normalize_global in Hnorm. destruct (Caus.check_causality _); inv Hnorm.\n    eapply normfby_global_wc, unnest_global_wc, Hwc.\n  Qed.\n\nEnd NCLOCKING.\n\nModule NClockingFun\n       (Ids : IDS)\n       (Op : OPERATORS)\n       (OpAux : OPERATORS_AUX Op)\n       (Syn : LSYNTAX Ids Op)\n       (Caus : LCAUSALITY Ids Op Syn)\n       (Clo : LCLOCKING Ids Op Syn)\n       (Norm : NORMALIZATION Ids Op OpAux Syn Caus)\n       <: NCLOCKING Ids Op OpAux Syn Caus Clo Norm.\n  Include NCLOCKING Ids Op OpAux Syn Caus Clo Norm.\nEnd NClockingFun.\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/Normalization/NClocking.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2851580978249484}}
{"text": "(** 単一型に関するモジュールです。 *)\n\nRequire Googology_In_Coq.Base.\nRequire Googology_In_Coq.Path.\n\n(** ライブラリを要求します。 *)\n\nImport Googology_In_Coq.Base.\nImport Googology_In_Coq.Path.\n\n(** ライブラリを開きます。 *)\n\nInductive Unit@{ i | } : Type@{ i } := unit_Unit : Unit.\n(* from: originally defined by Hexirp *)\n\n(** 単一型です。 *)\n\nDefinition matching_Unit@{ i j | } ( P : Type@{ j } ) ( cu : P ) ( x : Unit@{ i } ) : P := match x with unit_Unit => cu end.\n(* from: originally defined by Hexirp *)\n\n(** 単一型の場合分けです。 *)\n\nDefinition identity_matching_Unit@{ i j | } ( P : Type@{ j } ) ( display : P -> Unit@{ i } ) ( cu : P ) ( icu : Path Unit@{ i } ( display cu ) unit_Unit ) ( x : Unit@{ i } ) : Path Unit@{ i } ( display ( matching_Unit P cu x ) ) x := match x as x_ return Path Unit ( display ( matching_Unit P cu x_ ) ) x_ with unit_Unit => icu end.\n(* from: originally defined by Hexirp *)\n\n(** 単一型の場合分けの恒等式です。 *)\n\nDefinition dependent_matching_Unit@{ i j | } ( P : Unit@{ i } -> Type@{ j } ) ( cu : P unit_Unit ) ( x : Unit@{ i } ) : P x := match x as x_ return P x_ with unit_Unit => cu end.\n(* from: originally defined by Hexirp *)\n\n(** 単一型の依存場合分けです。 *)\n\nDefinition from_path_cons_Unit@{ i | } ( x : Unit@{ i } ) ( y : Unit@{ i } ) : Path Unit@{ i } x y := dependent_matching_Unit ( fun x_ : Unit@{i} => forall y_ : Unit@{ i }, Path Unit@{ i } x_ y_ ) ( fun y_ : Unit@{ i } => dependent_matching_Unit ( fun y__ : Unit@{ i } => Path Unit@{ i } unit_Unit y__ ) ( id_Path Unit@{ i } unit_Unit ) y_ ) x y.\n(* from: originally defined by Hexirp *)\n\n(** 単一型の構築子の道から単一型の道を作る関数です。 *)\n\nDefinition comatching_Unit@{ i j | } ( P : Type@{ j } ) ( x : P ) : Unit@{ i } := unit_Unit.\n(* from: originally defined by Hexirp *)\n\n(** 単一型の余場合分けです。 *)\n\nDefinition identity_comatching_Unit@{ i j | } ( P : Type@{ j } ) ( codisplay : Unit@{ i } -> P ) ( x : Unit@{ i } ) : Path Unit@{ i } ( comatching_Unit P ( codisplay x ) ) x := dependent_matching_Unit ( fun x_ : Unit@{ i } => Path Unit@{ i } ( comatching_Unit P ( codisplay x_ ) ) x_ ) ( id_Path Unit@{ i } unit_Unit ) x.\n(* from: originally defined by Hexirp *)\n\n(** 単一型の余場合分けの恒等式です。 *)\n\nDefinition from_path_dest_Unit@{ i | } ( x : Unit@{ i } ) ( y : Unit@{ i } ) : Path Unit@{ i } x y := from_path_cons_Unit x y.\n(* from: originally defined by Hexirp *)\n\n(** 単一型の構築子の道から単一型の道を作る関数です。 *)\n\nDefinition const_Unit@{ i j | } ( A : Type@{ j } ) : A -> Unit@{ i } := fun x : A => unit_Unit.\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/Unit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2849263330122419}}
{"text": "Require Export Iron.Language.SystemF2Effect.Step.Frame.\nRequire Export Iron.Language.SystemF2Effect.Store.Bind.\nRequire Export Iron.Language.SystemF2Effect.Store.TypeB.\nRequire Export Iron.Language.SystemF2Effect.Store.StoreT.\nRequire Export Iron.Language.SystemF2Effect.Store.StoreM.\nRequire Export Iron.Language.SystemF2Effect.Store.StoreP.\n\n(*******************************************************************)\n(* Well formed store. *)\nInductive WfS   : stenv -> stprops -> store -> Prop :=\n | WfS_\n   :  forall se sp ss\n   ,  Forall ClosedT se\n   -> StoreM se    ss\n   -> StoreT se sp ss\n   -> WfS se sp ss.\nHint Constructors WfS.\n\n\n(* Well formed store and frame stack. *)\nInductive WfFS : stenv -> stprops -> store -> stack -> Prop :=\n | WfFS_\n   :  forall se sp ss fs\n   ,  Forall ClosedT se\n   -> StoreM se ss\n   -> StoreT se sp ss\n   -> StoreP sp fs\n   -> WfFS se sp ss fs.\nHint Constructors WfFS.\n\n\n(*******************************************************************)\n(* If a well formed frame stack and store is well formed,\n   then the store is also well formed by itself. *)\nLemma wfFS_wfS\n :  forall se sp ss fs\n ,  WfFS   se sp ss fs\n -> WfS    se sp ss.\nProof. intros. inverts H. eauto. Qed.\nHint Resolve wfFS_wfS.\n\n\nLemma wfFS_closedT\n :  forall se sp ss fs\n ,  WfFS   se sp ss fs\n -> Forall ClosedT se.\nProof. intros. inverts H. eauto. Qed.\nHint Resolve wfFS_closedT.\n\n\nLemma wfFS_typeb\n :  forall se sp ss fs b\n ,  WfFS se sp ss fs\n -> In b ss\n -> (exists t, TypeB nil nil se sp b t).\nProof.\n intros.\n inverts H.\n eapply Forall2_exists_left; eauto.\nQed.\nHint Resolve wfFS_typeb.\n\n\n(* The region handles of private regions are present in the\n   store properties. *)\nLemma wfFS_fpriv_sregion\n :  forall se sp ss fs m1 p2\n ,  WfFS se sp ss fs\n -> In (FPriv   m1 p2) fs\n -> In (SRegion p2)    sp.\nProof. intros. inverts H. firstorder. Qed.\nHint Resolve wfFS_fpriv_sregion.\n\n\n(* The length of the store enviroment is the same as the length\n   of the store. We have one entry in the store environment for\n   each binding in the store. *)\nLemma wfFS_storem_length\n :  forall se sp ss fs\n ,  WfFS   se sp ss fs\n -> length se = length ss.\nProof. intros. inverts H. auto. Qed.\nHint Resolve wfFS_storem_length.\n\n\n(* Creating a top level private region preserves well-formedness\n   of the store. *)\nLemma wfFS_push_priv_top\n :  forall se sp ss fs p2\n ,  WfFS se sp ss fs\n -> WfFS se (SRegion p2 <: sp) ss (fs :> FPriv None p2).\nProof. intros. inverts H. auto. Qed.\nHint Resolve wfFS_push_priv_top.\n\n\n(* Creating an extension region preserves well-formedness\n   of the store. *)\nLemma wfFS_push_priv_ext\n :  forall se sp ss fs p1 p2\n ,  In (SRegion p1) sp\n -> WfFS  se  sp ss fs\n -> WfFS  se  (SRegion p2 <: sp) ss (fs :> FPriv (Some p1) p2).\nProof.\n intros.\n inverts H0. eapply WfFS_; rip.\n unfold StoreP in *. rip.\n - inverts H0; eauto.\n   inverts H4. eauto.\n - inverts H0; eauto.\n   inverts H4; eauto.\nQed.\nHint Resolve wfFS_push_priv_ext.\n\n\n(* Deallocating a region preserves well-formedness of the store. *)\nLemma typeB_deallocate\n :  forall ke te se sp p b t\n ,  TypeB  ke te se sp b t\n -> TypeB  ke te se sp (deallocRegion p b) t.\nProof.\n intros.\n destruct b.\n - snorm. subst.\n   inverts H. eauto.\n - snorm.\nQed.\n\n\n(* Deallocating bindings preserves the well typedness of the store. *)\nLemma storeT_deallocate\n :  forall se sp ss p\n ,  StoreT se sp ss\n -> StoreT se sp (map (deallocRegion p) ss).\nProof.\n intros.\n unfold StoreT in *.\n eapply Forall2_map_left.\n eapply Forall2_impl.\n - intros.\n    eapply typeB_deallocate. eauto.\n - auto.\nQed.\n\n\n(* Deallocating top-level region on the top of the frame stack\n   preserves the well formedness of the store. *)\nLemma wfFS_region_deallocate\n :  forall se sp ss fs p\n ,  WfFS se sp ss                     (fs :> FPriv None p)\n -> WfFS se sp (map (deallocRegion p) ss) fs.\nProof.\n intros.\n inverts H. eapply WfFS_; rip.\n - unfold StoreM in *.\n   rewrite map_length; auto.\n - eapply storeT_deallocate; auto.\n - unfold StoreP in *; snorm; eauto.\nQed.\n\n\nLemma wfFS_pop_priv_ext\n :  forall se sp ss fs p1 p2\n ,  In (SRegion p1) sp\n -> WfFS se sp ss (fs :> FPriv (Some p1) p2)\n -> WfFS (mergeTE p1 p2 se) sp (mergeBs p1 p2 ss) fs.\nProof.\n intros.\n inverts H0. split.\n - eapply Forall_map.\n   eapply Forall_impl with (P := ClosedT).\n   + intros. eapply mergeT_wfT; eauto.\n   + auto.\n\n - unfold StoreM in *.\n   unfold mergeTE.\n   unfold mergeBs.\n   repeat (rewrite map_length). auto.\n\n - unfold StoreT.\n   eapply storeT_mergeB; auto.\n\n - eapply storeP_pop; eauto.\nQed.\n\n\n(* Appending a closed store binding to the store preserves its\n   well formedness. *)\nLemma wfFS_stbind_snoc\n :  forall se sp ss fs p v t\n ,  In (SRegion p) sp\n -> TypeV  nil nil se sp v t\n -> WfFS           se sp ss fs\n -> WfFS   (TRef (TRgn p) t <: se) sp\n           (StValue p v <: ss) fs.\nProof.\n intros.\n inverts H1.\n eapply WfFS_; rip.\n eapply Forall_snoc; eauto.\nQed.\n\n\n(* Updating bindings preserves the well formedness of the store. *)\nLemma wfFS_stbind_update\n :  forall se sp ss fs l p v t\n ,  get l se = Some (TRef (TRgn p) t)\n -> In (SRegion p) sp\n -> TypeV nil nil se sp v t\n -> WfFS se sp ss fs\n -> WfFS se sp (update l (StValue p v) ss) fs.\nProof.\n intros se sp ss fs l p v t HG HK HV HWF1.\n inverts HWF1. eapply WfFS_; rip.\n - have (length se = length ss).\n   unfold StoreM.\n   rewritess.\n   rewrite update_length. auto.\n - unfold StoreT.\n   eapply Forall2_update_right; eauto.\nQed.\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/Wf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2849263257070786}}
{"text": "Require Import ssreflect ssrbool ssrnat eqtype seq fintype.\nRequire Import procstate procstatemonad bitsops bitsprops bitsopsprops.\nRequire Import SPred septac spectac spec safe pointsto cursor instr.\nRequire Import basic basicprog program instrsyntax macros instrrules.\nRequire Import Setoid RelationClasses Morphisms.\n\nDefinition retreg := EBP.\n\n(* Toy function calling convention *)\nDefinition toyfun f P Q :=\n  Forall iret, safe @ (EIP~=iret ** retreg? ** Q)\n          -->> safe @ (EIP~=f ** retreg~=iret ** P).\n\n(* Use this macro for calling f *)\nDefinition call_toyfun f :=\n  (LOCAL iret;\n    MOV retreg, iret;; JMP f;;\n  iret:;)\n  %asm.\n\n(* Use this macro to make a function that returns in the end *)\nDefinition mkbody_toyfun (p: program) :=\n  p;; JMP retreg.\n\n(* It's useful to define local functions *)\nNotation \"'let_toyfun' f  ':=' p 'in' q\" :=\n  (LOCAL skip; JMP skip;; LOCAL f; f:;; mkbody_toyfun p;; skip:;; q)%asm\n  (at level 45, f ident, right associativity).\n\nLemma spec_at_toyfun f P Q R:\n  toyfun f P Q @ R -|- toyfun f (P**R) (Q**R).\nProof.\n  rewrite /toyfun.\n  autorewrite with push_at. cancel1 => iret.\n  autorewrite with push_at. rewrite !sepSPA. reflexivity.\nQed.\nHint Rewrite spec_at_toyfun : push_at.\n\nLemma toyfun_call (f:DWORD) P Q:\n  |> toyfun f P Q |-- basic P (call_toyfun f) Q @ retreg?.\nProof.\n  autorewrite with push_at. rewrite /call_toyfun.\n  apply basic_local => iret. rewrite /stateIsAny. specintros => old.\n  eapply basic_seq. eapply basic_basic. apply MOV_RI_rule; by ssimpl. by ssimpl.\n  by ssimpl.\n\n  rewrite /basic. specintros => i j. unfold_program. specintros => _ <- -> {j}.\n  specapply JMP_I_rule. by ssimpl.\n  rewrite <-spec_reads_frame. autorewrite with push_at.\n  rewrite /toyfun. autorewrite with push_later. apply lforallL with iret.\n  autorewrite with push_later. cancel2. rewrite <-spec_later_weaken.\n  cancel1. rewrite /stateIsAny. sbazooka.\n  apply _.\n  apply _.\nQed.\n\nLemma toyfun_mkbody (f f': DWORD) P p Q:\n  (Forall iret, basic P p Q @ (retreg ~= iret)) |--\n    toyfun f P Q <@ (f--f' :-> mkbody_toyfun p).\nProof.\n  rewrite /toyfun. specintro => iret. rewrite /mkbody_toyfun.\n  unfold_program. specintro => i1.\n  apply lforallL with iret. autorewrite with push_at.\n  eapply safe_safe_ro; first reflexivity.\n  - apply lforallL with f. apply lforallL with i1. reflexivity.\n  - split; sbazooka.\n  specapply JMP_R_rule. by ssimpl.\n  rewrite <-spec_reads_frame. apply: limplAdj. apply: landL2.\n  rewrite <-spec_later_weaken. rewrite /stateIsAny. autorewrite with push_at.\n  cancel1. by sbazooka.\nQed.\n\n\n(*\n   Example that shows a caller and a callee independently verified and then\n   composed.\n *)\n\nDefinition toyfun_example_callee : program :=\n  mkbody_toyfun (\n    INC EAX;;\n    INC EAX\n  )%asm.\n\nDefinition toyfun_example_caller f : program :=\n  call_toyfun f;;\n  call_toyfun f.\n\nDefinition toyfun_example (entry: DWORD) : program :=\n  LOCAL f;\n  f:;;\n    toyfun_example_callee;;\n  entry:;;\n    toyfun_example_caller f.\n\nExample toyfun_example_callee_correct (f f': DWORD):\n  |-- (Forall a, toyfun f (EAX ~= a) (EAX ~= a +# 2))\n        @ OSZCP? <@ (f--f' :-> toyfun_example_callee).\nProof.\n  specintro => a. autorewrite with push_at.\n  etransitivity; [|apply toyfun_mkbody]. specintro => iret.\n  autorewrite with push_at. rewrite /stateIsAny.\n  specintros => o s z c p.\n  try_basicapply INC_R_rule; rewrite /OSZCP; sbazooka.\n  try_basicapply INC_R_rule; rewrite /OSZCP; sbazooka.\n  rewrite addIsIterInc /OSZCP /iter; sbazooka.\nQed.\n\n(* The toyfun spec assumed for f here is actually stronger than what lemma\n   toyfun_example_callee_correct guarantees: we ask for a function that does\n   not have OSZCP? in its footprint. But thanks to the higher-order frame\n   rule, it will still be possible to compose the caller and the callee. *)\n(** TODO(t-jagro): Find a better way of doing this, or a better place for this. *)\nLocal Opaque spec_at.\nExample toyfun_example_caller_correct a (f:DWORD):\n  Forall a', toyfun f (EAX ~= a') (EAX ~= a' +# 2)\n  |-- basic (EAX ~= a) (toyfun_example_caller f) (EAX ~= a +# 4) @ retreg?.\nProof.\n  rewrite /toyfun_example_caller. rewrite /RegOrFlag_target.\n  autorewrite with push_at.\n  eapply basic_seq.\n  - apply lforallL with a.\n    eapply basic_basic_context.\n    - have H := toyfun_call. setoid_rewrite spec_at_basic in H. apply H.\n    - by apply spec_later_weaken.\n    - by sbazooka.\n    done.\n  apply lforallL with (a +# 2).\n  eapply basic_basic_context.\n  - have H := toyfun_call. setoid_rewrite spec_at_basic in H. apply H.\n  - by apply spec_later_weaken.\n  - by ssimpl.\n  rewrite -addB_addn. sbazooka. reflexivity.\nQed.\n\nExample toyfun_example_correct entry (i j: DWORD) a:\n  |-- (\n      safe @ (EIP ~= j ** EAX ~= a +# 4) -->>\n      safe @ (EIP ~= entry ** EAX ~= a)\n    ) @ (retreg? ** OSZCP?) <@ (i--j :-> toyfun_example entry).\nProof.\n  rewrite /toyfun_example. unfold_program.\n  specintros => f _ <- -> {i} i1 _ <- ->. rewrite !empSPL.\n  rewrite [X in _ <@ X]sepSPC. rewrite <-spec_reads_merge.\n  rewrite ->toyfun_example_callee_correct.\n  (* The following rewrite underneath a @ is essentially a second-order frame\n     rule application. *)\n  rewrite ->toyfun_example_caller_correct.\n  cancel2; last reflexivity. autorewrite with push_at.\n  eapply safe_safe_ro; first reflexivity.\n  - eapply lforallL. eapply lforallL. reflexivity.\n  - split; sbazooka.\n  rewrite <-spec_reads_frame. apply: limplAdj. apply: landL2.\n  rewrite spec_at_emp. cancel1. sbazooka.\nQed.\n\n(*\n   Higher-order function example.\n *)\n\n(* This simple definition is the implementation of a higher-order function. It\n   takes a pointer to another function in EBX and calls that. *)\nDefinition toyfun_apply :=\n  JMP EBX.\n\nLemma limpland (S1 S2 S3: spec) :\n  S1 -->> S2 -->> S3 -|- S1 //\\\\ S2 -->> S3.\nProof.\n  split.\n  - apply: limplAdj.\n    apply: limplL; first exact: landL1.\n    apply: limplL; first exact: landL2. exact: landL1.\n  - apply: limplAdj.  apply: limplAdj. rewrite landA.\n    exact: landAdj.\nQed.\n\n(* It is possible but does not seem necessary to put a |> in front of the -->>.\n   There will be a function call somewhere to provide the |> unless we're just\n   making the apply function call itself in a tight loop. *)\nExample toyfun_apply_correct (f f' g: DWORD) P Q:\n  |-- (\n      toyfun g (P ** EBX?) Q -->> toyfun f (P ** EBX ~= g) Q\n    ) <@ (f--f' :-> toyfun_apply).\nProof.\n  rewrite /toyfun_apply. rewrite {2}/toyfun.\n  specintro => iret. rewrite limpland.\n  specapply JMP_R_rule. by ssimpl.\n  autorewrite with push_at.\n  rewrite <-spec_reads_frame. rewrite -limpland. apply limplValid.\n  rewrite /toyfun. eapply lforallL. rewrite <-spec_later_weaken.\n  rewrite /stateIsAny. cancel2; cancel1; by sbazooka.\nQed.\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/call.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5, "lm_q1q2_score": 0.28492632570707854}}
{"text": "From Coq Require Import ssreflect ssrfun ssrbool.\n\nFrom Coq Require Import Strings.String.\nFrom Coq Require Import Logic.PropExtensionality Logic.Eqdep_dec.\nFrom Equations Require Import Equations.\n\nFrom stdpp Require Export base gmap fin_sets sets list countable.\nFrom MatchingLogic Require Import Syntax Semantics StringSignature ProofSystem ProofMode.MLPM.\nFrom MatchingLogicProver Require Import Named NamedProofSystem NMatchers.\n\nFrom stdpp Require Import base finite gmap mapset listset_nodup numbers propset list.\n\n(* TODO: move this near to the definition of Pattern *)\nDerive NoConfusion for Pattern.\nDerive Subterm for Pattern.\n\nLtac invert_tuples :=\n  repeat (match goal with\n          | [H: (?x1,?y1)=(?x2,?y2) |- _] => inversion H; clear H; subst\n          end).\n\nLtac do_rewrites_everywhere := \n  repeat (match goal with\n  | [H: ?l = ?r , H' : _ |- _] => rewrite H in H'; simpl in H'\n  end).\n\nLtac case_match_in_hyp H :=\n  lazymatch type of H with\n  | context [ match ?x with _ => _ end ] => destruct x eqn:?\n  end.\n\n\n(* In an empty context, this rewrites: *)\n(* ∃ (x.x) /\\ (∃ y.y) ~> (∃ x.x) /\\ (∃ x.x) *)\n(* But in some other context C, it might rewrite *)\n(* C[∃ (x.x) /\\ (∃ y.y)] ~> C[(∃ z.z) /\\ (∃ z.z)] *)\n(* because we might see some ∃ z.z in the context C. *)\n\n\n(* TODO we have to implement the two-phase approach to proof system translation.\n   The cache-based on was too complicated, so I removed the proofs from this file.\n*)\n(*\nRecord AlphaConversion {Σ : Signature} :=\n  {\n    ac_list : list evar ;\n  }.\n\nDefinition AlphaConversion_valid {Σ : Signature}\n  (ac : AlphaConversion) (nϕ : NamedPattern)\n  := (ac_list ac) ## elements (named_free_evars nϕ).\n\nPrint NamedPattern.\n*)\n\n(*\nDefinition head_or_id {Σ : Signature}\n  (l : list evar) (p : NamedPattern) : NamedPattern \n  match l with\n  | [] => p\n  | (x::xs) => \n*)\n\nFixpoint number_of_exists\n  {Σ : Signature} (ϕ : NamedPattern) : nat :=\n  match ϕ with\n  | npatt_app phi1 phi2\n    => number_of_exists phi1 + number_of_exists phi2\n  | npatt_imp phi1 phi2\n    => number_of_exists phi1 + number_of_exists phi2\n  | npatt_exists _ phi\n    => S (number_of_exists phi)\n  | npatt_mu _ phi\n    => number_of_exists phi\n  | _ => 0\n  end.\n\n  Fixpoint number_of_mus\n  {Σ : Signature} (ϕ : NamedPattern) : nat :=\n  match ϕ with\n  | npatt_app phi1 phi2\n    => number_of_mus phi1 + number_of_mus phi2\n  | npatt_imp phi1 phi2\n    => number_of_mus phi1 + number_of_mus phi2\n  | npatt_exists _ phi\n    => (number_of_mus phi)\n  | npatt_mu _ phi\n    => S ( number_of_mus phi)\n  | _ => 0\n  end.\n\nFixpoint rename {Σ : Signature}\n  (bevs : list evar)\n  (bsvs : list svar)\n  (fevs : gmap evar evar)\n  (fsvs : gmap svar svar)\n  (nϕ : NamedPattern)\n  : NamedPattern :=\n  match nϕ with\n  | npatt_evar x\n    => match (fevs !! x) with\n       | None => npatt_evar x\n       | Some y => npatt_evar y\n       end\n  | npatt_svar X\n       => match (fsvs !! X) with\n          | None => npatt_svar X\n          | Some Y => npatt_svar Y\n          end\n  | npatt_sym s => npatt_sym s\n  | npatt_bott => npatt_bott\n  | npatt_imp phi1 phi2 =>\n    npatt_imp\n      (rename bevs bsvs fevs fsvs phi1)\n      (rename (drop (number_of_exists phi1) bevs)\n              (drop (number_of_mus phi1) bsvs)\n              fevs fsvs phi2) \n  | npatt_app phi1 phi2 =>\n    npatt_app\n      (rename bevs bsvs fevs fsvs phi1)\n      (rename (drop (number_of_exists phi1) bevs)\n      (drop (number_of_exists phi1) bsvs)\n              fevs fsvs phi2) \n  | npatt_exists x phi =>\n    match bevs with\n    | [] => npatt_exists x phi\n    | (y::ys)\n      => npatt_exists y\n          (rename ys bsvs (<[x:=y]>fevs) fsvs phi)\n    end\n  | npatt_mu X phi =>\n    match bsvs with\n    | [] => npatt_mu X phi\n    | (Y::Ys)\n      => npatt_mu Y\n          (rename bevs Ys fevs (<[X:=Y]>fsvs) phi)\n    end\n  end.\n\n\n  Record PartialBijection (A : Type)\n    {_eqd : EqDecision A}\n    {_cnt : Countable A}\n     :=\n  mkPartialBijection\n  {\n    pbr : gset (prod A A) ;\n    pb1 : forall (x y1 y2 : A),\n      (x,y1) ∈ pbr -> (x,y2) ∈ pbr -> y1 = y2 ;\n    pb2 : forall (x1 x2 y : A),\n      (x1,y) ∈ pbr -> (x2,y) ∈ pbr -> x1 = x2 ;\n  }.\n\n  Lemma pb_eq_dep (A : Type) \n    {_eqd : EqDecision A}\n    {_cnt : Countable A}\n    (s s' : gset (prod A A))\n    pf1 pf1' pf2 pf2'\n    : s = s' ->\n      @mkPartialBijection A _eqd _cnt s pf1 pf2 = @mkPartialBijection A _eqd _cnt s' pf1' pf2'.\n    Proof.\n      intros H.\n      subst s'.\n      f_equal; apply proof_irrelevance.\n    Qed.\n\n  Arguments pbr {A%type_scope} {_eqd _cnt} p.\n\n  Definition myswap {A : Type} (p : prod A A) : prod A A := (p.2, p.1).\n\n  Program Definition pbr_converse {A : Type}\n    {_eqd : EqDecision A}\n    {_cnt : Countable A}\n    (R : PartialBijection A) : PartialBijection A\n  := {|\n    pbr := (set_map myswap (pbr R))  ;\n  |}.\n  Next Obligation.\n    intros ??????? H1 H2.\n    rewrite elem_of_map in H1.\n    rewrite elem_of_map in H2.\n    destruct H1 as [[x11 x12] [H11 H12] ].\n    destruct H2 as [[x21 x22] [H21 H22] ].\n    simpl in *.\n    inversion H11; clear H11; inversion H21; clear H21; subst.\n    destruct R as [r pf1 pf2]; simpl in *.\n    naive_solver.\n  Qed.\n  Next Obligation.\n    intros ??????? H1 H2.\n    rewrite elem_of_map in H1.\n    rewrite elem_of_map in H2.\n    destruct H1 as [[x11 x12] [H11 H12] ].\n    destruct H2 as [[x21 x22] [H21 H22] ].\n    simpl in *.\n    inversion H11; clear H11; inversion H21; clear H21; subst.\n    destruct R as [r pf1 pf2]; simpl in *.\n    naive_solver.\n  Qed.\n \n  Lemma pbr_converse_sym (A : Type)\n    {_eqd : EqDecision A}\n    {_cnt : Countable A}\n    (R : PartialBijection A)\n    : forall (x y : A), ((x,y) ∈ (pbr (pbr_converse R))) <-> ((y,x) ∈ (pbr R)).\n  Proof.\n    intros x y.\n    destruct R as [r pf1 pf2]; simpl.\n    rewrite elem_of_map.\n    unfold myswap.\n    split; intros H.\n    {\n      destruct H as [[a1 a2] [H1 H2] ].\n      simpl in *.\n      naive_solver.\n    }\n    {\n      exists (y,x).\n      split;[reflexivity|assumption].\n    }\n  Qed.\n\n  Definition related {A : Type} (u v : prod A A) : Prop\n  := u.1 = v.1 \\/ u.2 = v.2.\n\n  Definition unrelated {A : Type} (u v : prod A A) : Prop\n  := ~ (related u v).\n\n  #[global]\n  Instance related_dec (A : Type)\n    {eq_dec : EqDecision A}\n  : RelDecision (@unrelated A).\n  Proof.\n    solve_decision.\n  Defined.\n\n  Program Definition pb_update\n  {A : Type}\n  {_eqd : EqDecision A}\n  {_cnt : Countable A}\n  (pb : PartialBijection A)\n  (x y : A)\n  : PartialBijection A := {|\n    pbr := (filter (unrelated (x,y)) (pbr pb) ) ∪ {[ (x,y) ]} ;\n  |}.\n  Next Obligation.\n    intros ???? ????? H1 H2.\n    rewrite elem_of_union in H1.\n    rewrite elem_of_union in H2.\n    rewrite elem_of_singleton in H1.\n    rewrite elem_of_singleton in H2.\n    rewrite elem_of_filter in H1.\n    rewrite elem_of_filter in H2.\n    destruct pb.\n    unfold unrelated,related in *.\n    simpl in *.\n    naive_solver.\n  Qed.\n Next Obligation.\n  intros ???? ????? H1 H2.\n  rewrite elem_of_union in H1.\n  rewrite elem_of_union in H2.\n  rewrite elem_of_singleton in H1.\n  rewrite elem_of_singleton in H2.\n  rewrite elem_of_filter in H1.\n  rewrite elem_of_filter in H2.\n  destruct pb.\n  unfold unrelated,related in *.\n  simpl in *.\n  naive_solver.\n Qed.\n\n Lemma pbr_update_converse\n  {A : Type}\n  {_eqd : EqDecision A}\n  {_cnt : Countable A}\n  (R : PartialBijection A)\n  : forall x y, pbr_converse (pb_update R x y) = pb_update (pbr_converse R) y x.\n  Proof.\n    intros x y.\n    destruct R as [r pf1 pf2]; simpl in *.\n    unfold pb_update,pbr_converse; simpl.\n    apply pb_eq_dep.\n    rewrite set_map_union_L.\n    rewrite set_map_singleton_L.\n    simpl.\n\n    cut ((@set_map (A * A) (gset (A * A)) _ (A * A) (gset (A * A)) _ _ _ myswap (filter (unrelated (x, y)) r)) = (filter (unrelated (y, x)) (set_map myswap r))).\n    {\n      intros H. rewrite H. reflexivity.\n    }\n    apply anti_symm with (S := @subseteq (gset (prod A A)) _).\n    { apply _. }\n    1,2: rewrite elem_of_subseteq; intros x0 Hx0.\n    {\n      rewrite elem_of_map in Hx0.\n      destruct Hx0 as [[x' y'] [Hx'y'1 Hx'y'2] ].\n      rewrite elem_of_filter in Hx'y'2.\n      rewrite elem_of_filter.\n      rewrite elem_of_map.\n      unfold unrelated,related,myswap in *.\n      simpl in *.\n      subst.\n      naive_solver.\n    }\n    {\n      rewrite elem_of_filter in Hx0.\n      rewrite elem_of_map in Hx0.\n      rewrite elem_of_map.\n      unfold unrelated,related,myswap in *.\n      simpl in *.\n      exists (x0.2, x0.1). simpl.\n      rewrite -surjective_pairing.\n      rewrite elem_of_filter. simpl.\n      naive_solver.\n    }\n  Qed.\n\n  Inductive alpha_equiv'\n    {Σ : Signature}\n    (R : PartialBijection evar)\n    (R' : PartialBijection svar)\n    : relation NamedPattern\n    :=\n    | ae_evar (x y : evar) (pf : (x, y) ∈ (pbr R))\n      : alpha_equiv' R R' (npatt_evar x) (npatt_evar y)\n    | ae_svar (X Y : svar) (pf : (X, Y) ∈ (pbr R'))\n      : alpha_equiv' R R' (npatt_svar X) (npatt_svar Y)\n    | ae_app\n      (t t' u u' : NamedPattern)\n      (tEt' : alpha_equiv' R R' t t')\n      (uEu' : alpha_equiv' R R' u u')\n      : alpha_equiv' R R' (npatt_app t u) (npatt_app t' u')\n    | ae_imp\n      (t t' u u' : NamedPattern)\n      (tEt' : alpha_equiv' R R' t t')\n      (uEu' : alpha_equiv' R R' u u')\n      : alpha_equiv' R R' (npatt_imp t u) (npatt_imp t' u')\n    | ae_bott : alpha_equiv' R R' npatt_bott npatt_bott\n    | ae_sym (s : symbols) : alpha_equiv' R R' (npatt_sym s) (npatt_sym s) \n    | ae_ex (x y : evar) (t u : NamedPattern)\n      (tEu : alpha_equiv'\n        (pb_update R x y) R' t u)\n      : alpha_equiv' R R'\n        (npatt_exists x t)\n        (npatt_exists y u)\n    | ae_mu (X Y : svar) (t u : NamedPattern)\n      (tEu : alpha_equiv'\n        R (pb_update R' X Y) t u)\n      : alpha_equiv' R R'\n        (npatt_mu X t)\n        (npatt_mu Y u)\n  .\n\n  #[global]\n  Instance myswap_involutive\n    (A : Type) :\n    Involutive (=) (@myswap A).\n  Proof.\n    unfold Involutive.\n    intros p.\n    destruct p.\n    unfold myswap.\n    reflexivity.\n  Qed.\n\n  #[global]\n  Instance myswap_inj (A : Type) : Inj (=) (=) (@myswap A).\n  Proof.\n    intros p1 p2 Hp1p2.\n    unfold myswap in Hp1p2.\n    destruct p1,p2.\n    simpl in *.\n    inversion Hp1p2.\n    subst.\n    reflexivity.\n  Qed.\n\n  Check @set_map.\n\n  #[global]\n  Instance set_map_involutive (A C : Type)\n    {_eoAC : ElemOf A C}\n    {_eleAC : Elements A C}\n    {_singAC : Singleton A C}\n    {_emptyC : Empty C}\n    {_uniC : Union C}\n    {_interC : Intersection C}\n    {_difC : Difference C}\n    {_eqdecA : EqDecision A}\n    {_finac : FinSet A C}\n    (f : A -> A)\n    {_injF : Inj (=) (=) f}\n    {_invF : Involutive (=) f}\n    {_lC : LeibnizEquiv C}\n    :\n    Involutive (=) (@set_map A C _eleAC A C _singAC _emptyC _uniC f).\n  Proof.\n    intros x.\n    unfold set_map.\n    Search list_to_set elements.\n    rewrite -[x in _ = x]list_to_set_elements_L.\n    rewrite elements_list_to_set.\n    {\n      rewrite NoDup_fmap.\n      apply NoDup_elements.\n    }\n    rewrite -list_fmap_compose.\n    unfold compose.\n    under [fun x0 => _]functional_extensionality => x0.\n    {\n      rewrite _invF.\n      over.\n    }\n    fold (@Coq.Init.Datatypes.id A).\n    rewrite list_fmap_id.\n    reflexivity.\n  Qed.\n\n  #[global]\n  Instance pbr_converse_involutive\n    (A : Type)\n    {_eqd : EqDecision A}\n    {_cnt : Countable A}\n     : Involutive (=) (@pbr_converse A _eqd _cnt).\n  Proof.\n    unfold Involutive.\n    intros R.\n    destruct R.\n    apply pb_eq_dep.\n    simpl.\n    rewrite cancel.\n    reflexivity.\n  Qed.\n\n  Lemma alpha_equiv_converse'\n    {Σ : Signature}\n    (R : PartialBijection evar)\n    (R' : PartialBijection svar)\n    : forall x y,\n      alpha_equiv' R R' x y ->\n      alpha_equiv' (pbr_converse R) (pbr_converse R') y x.\n  Proof.\n    intros x y H.\n    induction H; try (solve [constructor; auto]).\n      { constructor. rewrite pbr_converse_sym; assumption. }\n      { constructor. rewrite pbr_converse_sym; assumption. }\n      { constructor. rewrite pbr_update_converse in IHalpha_equiv'. assumption. }\n      { constructor. rewrite pbr_update_converse in IHalpha_equiv'. assumption. }\n  Qed.\n\n  Lemma alpha'_sym\n    {Σ : Signature}\n    (R : PartialBijection evar)\n    (R' : PartialBijection svar)\n    : forall x y,\n      alpha_equiv' R R' x y <->\n      alpha_equiv' (pbr_converse R) (pbr_converse R') y x.\n  Proof.\n    intros x y; split; intros H.\n    {\n      apply alpha_equiv_converse'.\n      apply H.\n    }\n    { \n      rewrite -[R](@cancel (PartialBijection evar) _ eq (@pbr_converse evar _ _)).\n      rewrite -[R'](@cancel (PartialBijection svar) _ eq (@pbr_converse svar _ _)).\n      apply alpha_equiv_converse'.\n      apply H.\n    }\n  Qed.\n\n  #[global]\n  Instance alpha'_dec\n    {Σ : Signature}\n    (R : PartialBijection evar)\n    (R' : PartialBijection svar)\n    : RelDecision (alpha_equiv' R R').\n  Proof.\n    unfold RelDecision.\n    intros x y.\n    unfold Decision.\n    move: R R' y.\n    (*remember (size' x) as szx.*)\n    induction x; intros R R' y; destruct y; try (solve [repeat constructor]);\n      try (solve [right; intros HH; inversion HH]).\n    {\n      destruct (decide ((x, x0) ∈ pbr R)).\n      {\n        left. constructor. assumption.\n      }\n      {\n        right. intros HContra. inversion HContra.\n        contradiction.\n      }\n    }\n    {\n      destruct (decide ((X, X0) ∈ pbr R')).\n      {\n        left. constructor. assumption.\n      }\n      {\n        right. intros HContra. inversion HContra.\n        contradiction.\n      }\n    }\n    {\n      destruct (decide (sigma = sigma0)).\n      {\n        left. subst. constructor.\n      }\n      {\n        right. intros HContra. inversion HContra.\n        contradiction.\n      }\n    }\n    {\n      specialize (IHx1 R R' y1).\n      specialize (IHx2 R R' y2).\n      destruct IHx1, IHx2.\n      {\n        left. constructor; assumption.\n      }\n      all: right; intros HContra; inversion HContra; contradiction.\n    }\n    {\n      specialize (IHx1 R R' y1).\n      specialize (IHx2 R R' y2).\n      destruct IHx1, IHx2.\n      {\n        left. constructor; assumption.\n      }\n      all: right; intros HContra; inversion HContra; contradiction.\n    }\n    {\n      pose proof (IH' := IHx (pb_update R x x1) R' y).\n      destruct IH'.\n      {\n        left. constructor. assumption.\n      }\n      {\n        right. intros HContra. inversion HContra. clear HContra.\n        subst.\n        contradiction.\n      }\n    }\n    {\n      pose proof (IH' := IHx R (pb_update R' X X0) y).\n      destruct IH'.\n      {\n        left. constructor. assumption.\n      }\n      {\n        right. intros HContra. inversion HContra. clear HContra.\n        subst.\n        contradiction.\n      }\n    }\n  Defined.\n\n  Definition twice {A : Type} (x : A) : prod A A := (x, x).\n\n  #[global]\n  Instance twice_inj {A : Type} : Inj (=) (=) (@twice A).\n  Proof.\n    intros x y H.\n    inversion H.\n    reflexivity.\n  Qed.\n\n  Program Definition diagonal\n    {A : Type}\n    {_eqd : EqDecision A}\n    {_cnt : Countable A}\n    (S : gset A)\n     : PartialBijection A :=\n    {|\n      pbr := set_map twice S ;\n    |}.\n  Next Obligation.\n    intros ??????? H1 H2.\n    rewrite elem_of_map in H1.\n    rewrite elem_of_map in H2.\n    destruct H1 as [w1 [Hw1 H'w1] ].\n    destruct H2 as [w2 [Hw2 H'w2] ].\n    inversion Hw1; clear Hw1; subst.\n    inversion Hw2; clear Hw2; subst.\n    reflexivity.\n  Qed.\n  Next Obligation.\n    intros ??????? H1 H2.\n    rewrite elem_of_map in H1.\n    rewrite elem_of_map in H2.\n    destruct H1 as [w1 [Hw1 H'w1] ].\n    destruct H2 as [w2 [Hw2 H'w2] ].\n    inversion Hw1; clear Hw1; subst.\n    inversion Hw2; clear Hw2; subst.\n    reflexivity.\n  Qed.\n\n  Definition alpha_equiv {Σ : Signature} (phi psi : NamedPattern) : Prop :=\n    alpha_equiv'\n      (diagonal (named_free_evars phi ∪ named_free_evars psi))\n      (diagonal (named_free_svars phi ∪ named_free_svars psi))\n      phi psi\n  .\n\n  #[global]\n  Instance alpha_dec\n    {Σ : Signature}\n    : RelDecision alpha_equiv.\n  Proof.\n    intros x y.\n    apply alpha'_dec.\n  Defined.\n\n  Lemma myswap_twice (A : Type) : myswap ∘ (@twice A) = twice.\n  Proof.\n    apply functional_extensionality.\n    intros x. reflexivity.\n  Qed.\n\n  Lemma pbr_converse_diagonal (A : Type) {_eqd : EqDecision A} {_cnt : Countable A} (S : gset A):\n    pbr_converse (diagonal S) = diagonal S.\n  Proof.\n    unfold diagonal,pbr_converse.\n    apply pb_eq_dep.\n    simpl.\n    unfold set_map.\n    apply anti_symm with (S := @subseteq (gset (prod A A)) _).\n    { apply _. }\n    1,2: rewrite elem_of_subseteq; intros x Hx.\n    {\n      rewrite elem_of_list_to_set in Hx.\n      rewrite elem_of_list_to_set.\n      rewrite elements_list_to_set in Hx.\n      { apply NoDup_fmap.\n        { apply _. }\n        { apply NoDup_elements. }\n      }\n      rewrite -list_fmap_compose in Hx.\n      rewrite myswap_twice in Hx.\n      exact Hx.\n    }\n    {\n      rewrite elem_of_list_to_set.\n      rewrite elem_of_list_to_set in Hx.\n      rewrite elements_list_to_set.\n      { apply NoDup_fmap.\n        { apply _. }\n        { apply NoDup_elements. }\n      }\n      rewrite -list_fmap_compose.\n      rewrite myswap_twice.\n      exact Hx.\n    }\n  Qed.\n\n  Lemma alpha_equiv_sym\n  {Σ : Signature}\n  : forall x y,\n    alpha_equiv x y <->\n    alpha_equiv y x.\n  Proof.\n    intros x y.\n    unfold alpha_equiv.\n    rewrite alpha'_sym.\n    rewrite !pbr_converse_diagonal.\n    rewrite [named_free_evars y ∪ named_free_evars x]union_comm_L.\n    rewrite [named_free_svars y ∪ named_free_svars x]union_comm_L.\n    apply reflexivity.\n  Qed.\n\n  Lemma alpha_equiv_refl {Σ : Signature} :\n    forall p, alpha_equiv p p.\n  Proof.\n    intros p.\n    unfold alpha_equiv.\n    do 2 rewrite union_idemp_L.\n    cut (forall R R', pbr (diagonal (named_free_evars p)) ⊆ (pbr R) ->\n      pbr (diagonal (named_free_svars p)) ⊆ (pbr R')\n     -> alpha_equiv' R R' p p).\n    {\n      intros H. apply H; apply reflexivity.\n    }\n    \n    induction p; intros H1 H2; constructor; try set_solver.\n    {\n      simpl in *.\n      apply IHp.\n      {\n        simpl in *.\n        rewrite elem_of_subseteq.\n        intros x0 Hx0.\n        rewrite elem_of_map in Hx0.\n        destruct Hx0 as [x' [Hx'1 Hx'2] ].\n        subst.\n        rewrite elem_of_union.\n        rewrite elem_of_singleton.\n        unfold twice.\n        destruct (decide (x = x')).\n        {\n          subst. right. reflexivity.\n        }\n        {\n          left.\n          rewrite elem_of_filter.\n          unfold unrelated,related.\n          simpl.\n          set_solver.\n        }\n      }\n      {\n        assumption.\n      }\n    }\n    {\n      apply IHp.\n      {\n        assumption.\n      }\n      {\n        simpl in *.\n        rewrite elem_of_subseteq.\n        intros [X1 X2] HX1X2.\n        rewrite elem_of_map in HX1X2.\n        destruct HX1X2 as [X3 [HX3 HX4] ].\n        unfold twice in *.\n        simpl in *.\n        inversion HX3. clear HX3. subst.\n        rewrite elem_of_union. \n        destruct (decide (X3 = X)).\n        {\n          subst. right. rewrite elem_of_singleton. reflexivity.\n        }\n        {\n          left.\n          rewrite elem_of_filter.\n          unfold unrelated,related.\n          simpl.\n          set_solver.\n        }\n      }\n    }\n  Qed.\n\n  Fixpoint npfoldtopdown {Σ : Signature} {State : Type} \n    (f : State -> NamedPattern -> State)\n    (state : State) (nϕ : NamedPattern)\n    : (State)%type\n  :=\n    match nϕ with\n    | npatt_evar x => f state (npatt_evar x)\n    | npatt_svar X => f state (npatt_svar X)\n    | npatt_sym s => f state (npatt_sym s)\n    | npatt_bott => f state npatt_bott\n    | npatt_imp nϕ1 nϕ2 =>\n      let state' := f state (npatt_imp nϕ1 nϕ2) in\n      let state'' := npfoldtopdown f state' nϕ1 in\n      let state''' := npfoldtopdown f state' nϕ2 in\n      state'''      \n    | npatt_app nϕ1 nϕ2 =>\n      let state' := f state (npatt_app nϕ1 nϕ2) in\n      let state'' := npfoldtopdown f state' nϕ1 in\n      let state''' := npfoldtopdown f state' nϕ2 in\n      state'''\n    | npatt_exists x nϕ' =>\n      let state' := f state (npatt_exists x nϕ') in\n      let state'' := npfoldtopdown f state' nϕ' in\n      state''\n    | npatt_mu X nϕ' =>\n      let state' := f state (npatt_mu X nϕ') in\n      let state'' := npfoldtopdown f state' nϕ' in\n      state''\n    end.\n  \n\n  Record CollapseState {Σ : Signature} := mkCollapseState {\n    cs_history : list NamedPattern;\n  }.\n\n  Definition lookup_or\n    {Σ : Signature}\n    (state : CollapseState)\n    (nϕ : NamedPattern)\n    (owise : (CollapseState * NamedPattern)%type)\n    : (CollapseState * NamedPattern)%type\n    := match (list_find (alpha_equiv nϕ) (cs_history state)) with\n    | Some (_, nϕ') => (state, nϕ')\n    | None => owise\n    end.\n\n\n  Definition lookup_or_node\n    {Σ : Signature}\n    (state : CollapseState)\n    (nϕ : NamedPattern)\n    (owise : (CollapseState * NamedPattern)%type)\n    : (CollapseState * NamedPattern)%type\n    := lookup_or state nϕ (mkCollapseState Σ ((owise.2)::(cs_history owise.1)), (owise.2)).\n\n  Definition lookup_or_leaf\n    {Σ : Signature}\n    (state : CollapseState)\n    (nϕ : NamedPattern)\n    : (CollapseState * NamedPattern)%type\n    := lookup_or_node state nϕ (state, nϕ).\n\n\n  Program Fixpoint collapse_aux\n    {Σ : Signature}\n    (state : CollapseState)\n    (nϕ : NamedPattern)\n    : (CollapseState * NamedPattern)%type\n  :=\n    match nϕ with\n    | npatt_evar x\n      => lookup_or_leaf state nϕ\n    | npatt_svar X\n      => lookup_or_leaf state nϕ\n    | npatt_bott\n      => lookup_or_leaf state nϕ\n    | npatt_sym s\n      => lookup_or_leaf state nϕ\n    | npatt_imp nϕ1 nϕ2\n      => lookup_or_node state nϕ\n        ( let res := collapse_aux state nϕ1 in\n          let res' := collapse_aux (res.1) nϕ2 in\n          (res'.1, (npatt_imp res.2 res'.2))\n        )\n    | npatt_app nϕ1 nϕ2\n        => lookup_or_node state nϕ\n          ( let res := collapse_aux state nϕ1 in\n            let res' := collapse_aux (res.1) nϕ2 in\n            (res'.1, (npatt_app res.2 res'.2))\n          )\n    | npatt_exists x nϕ'\n      => lookup_or_node state nϕ\n        (\n          let res := collapse_aux state nϕ' in\n          (res.1, (npatt_exists x res.2))\n        )\n    | npatt_mu X nϕ'\n        => lookup_or_node state nϕ\n          (\n            let res := collapse_aux state nϕ' in\n            (res.1, (npatt_mu X res.2))\n          )\n    end.\n\n    (* (exists x. x) ---> (exists y. (y ---> exists z. z)) *)\n\n    Lemma lookup_or_leaf_alpha\n      {Σ : Signature}\n      (state : CollapseState)\n      (nϕ : NamedPattern)\n      : alpha_equiv (lookup_or_leaf state nϕ).2 nϕ.\n    Proof.\n      unfold lookup_or_leaf, lookup_or_node, lookup_or.\n      simpl.\n      destruct (list_find (alpha_equiv nϕ) (cs_history state)) as [[n phi] |] eqn:Heq; simpl.\n      {\n        rewrite list_find_Some in Heq.\n        destruct Heq as [H1 [H2 H3] ].\n        apply alpha_equiv_sym.\n        assumption.\n      }\n      {\n        apply alpha_equiv_refl.\n      }\n    Qed.\n\n\n    Lemma alpha_equiv'_impl_almost_same_evars {Σ : Signature} R R' nϕ1 nϕ2:\n      alpha_equiv' R R' nϕ1 nϕ2 ->\n      forall x1, x1 ∈ (named_free_evars nϕ1) ->\n        exists x2, x2 ∈ (named_free_evars nϕ2) /\\\n          (x1, x2) ∈ pbr R.\n    Proof.\n      intros Halpha x1 Hx1.\n      induction Halpha; simpl in *.\n      {\n        rewrite elem_of_singleton in Hx1.\n        subst.\n        exists y.\n        rewrite elem_of_singleton.\n        split;[reflexivity|assumption].\n      }\n      { exfalso. set_solver. }\n      {\n        rewrite elem_of_union in Hx1.\n        destruct Hx1 as [Hx1|Hx1].\n        {\n          specialize (IHHalpha1 Hx1).\n          destruct IHHalpha1 as [x2 [Hx21 Hx22] ].\n          exists x2.\n          rewrite elem_of_union.\n          naive_solver.\n        }\n        {\n          specialize (IHHalpha2 Hx1).\n          destruct IHHalpha2 as [x2 [Hx21 Hx22] ].\n          exists x2.\n          rewrite elem_of_union.\n          naive_solver.\n        }\n      }\n      {\n        rewrite elem_of_union in Hx1.\n        destruct Hx1 as [Hx1|Hx1].\n        {\n          specialize (IHHalpha1 Hx1).\n          destruct IHHalpha1 as [x2 [Hx21 Hx22] ].\n          exists x2.\n          rewrite elem_of_union.\n          naive_solver.\n        }\n        {\n          specialize (IHHalpha2 Hx1).\n          destruct IHHalpha2 as [x2 [Hx21 Hx22] ].\n          exists x2.\n          rewrite elem_of_union.\n          naive_solver.\n        }\n      }\n      { exfalso. set_solver. }\n      { exfalso. set_solver. }\n      {\n        destruct (decide (x1 = x)).\n        {\n          subst. clear -Hx1. exfalso. set_solver.\n        }\n        {\n          feed specialize IHHalpha.\n          {\n            set_solver.\n          }\n          destruct IHHalpha as [x2 [Hx21 Hx22] ].\n          rewrite elem_of_union in Hx22.\n          rewrite elem_of_filter in Hx22.\n          unfold unrelated,related in Hx22.\n          rewrite elem_of_singleton in Hx22.\n          simpl in Hx22.\n          destruct Hx22; try naive_solver.\n          exists x2. set_solver.\n        }\n      }\n      {\n        specialize (IHHalpha Hx1).\n        exact IHHalpha.\n      }\n    Qed.\n\n    Lemma alpha_equiv'_impl_almost_same_svars {Σ : Signature} R R' nϕ1 nϕ2:\n      alpha_equiv' R R' nϕ1 nϕ2 ->\n      forall X1, X1 ∈ (named_free_svars nϕ1) ->\n        exists X2, X2 ∈ (named_free_svars nϕ2) /\\\n          (X1, X2) ∈ pbr R'.\n    Proof.\n      intros Halpha X1 HX1.\n      induction Halpha; simpl in *.\n      { exfalso. set_solver. }\n      {\n        rewrite elem_of_singleton in HX1.\n        subst.\n        exists Y.\n        rewrite elem_of_singleton.\n        split;[reflexivity|assumption].\n      }\n      {\n        rewrite elem_of_union in HX1.\n        destruct HX1 as [HX1|HX1].\n        {\n          specialize (IHHalpha1 HX1).\n          destruct IHHalpha1 as [X2 [HX21 HX22] ].\n          exists X2.\n          rewrite elem_of_union.\n          naive_solver.\n        }\n        {\n          specialize (IHHalpha2 HX1).\n          destruct IHHalpha2 as [X2 [HX21 HX22] ].\n          exists X2.\n          rewrite elem_of_union.\n          naive_solver.\n        }\n      }\n      {\n        rewrite elem_of_union in HX1.\n        destruct HX1 as [HX1|HX1].\n        {\n          specialize (IHHalpha1 HX1).\n          destruct IHHalpha1 as [X2 [HX21 HX22] ].\n          exists X2.\n          rewrite elem_of_union.\n          naive_solver.\n        }\n        {\n          specialize (IHHalpha2 HX1).\n          destruct IHHalpha2 as [X2 [HX21 HX22] ].\n          exists X2.\n          rewrite elem_of_union.\n          naive_solver.\n        }\n      }\n      { exfalso. set_solver. }\n      { exfalso. set_solver. }\n      {\n        specialize (IHHalpha HX1).\n        exact IHHalpha.\n      }\n      {\n        destruct (decide (X1 = X)).\n        {\n          subst. clear -HX1. exfalso. set_solver.\n        }\n        {\n          feed specialize IHHalpha.\n          {\n            set_solver.\n          }\n          destruct IHHalpha as [X2 [HX21 HX22] ].\n          rewrite elem_of_union in HX22.\n          rewrite elem_of_filter in HX22.\n          unfold unrelated,related in HX22.\n          rewrite elem_of_singleton in HX22.\n          simpl in HX22.\n          destruct HX22; try naive_solver.\n          exists X2. set_solver.\n        }\n      }\n    Qed.\n\n    Lemma alpha_equiv_impl_same_evars {Σ : Signature} nϕ1 nϕ2:\n      alpha_equiv nϕ1 nϕ2 ->\n      (named_free_evars nϕ1) = (named_free_evars nϕ2).\n    Proof.\n      intros Halpha.\n      unfold alpha_equiv in Halpha.\n      pose proof (H1 := alpha_equiv'_impl_almost_same_evars _ _ nϕ1 nϕ2 Halpha).\n      pose proof (H2 := alpha_equiv'_impl_almost_same_evars _ _ nϕ2 nϕ1 (proj1 (alpha_equiv_sym nϕ1 nϕ2) Halpha)).\n      simpl in *. unfold twice in *.\n      apply anti_symm with (S := @subseteq (gset (evar)) _).\n      { apply _. }\n      {\n        rewrite elem_of_subseteq.\n        intros x Hx.\n        specialize (H1 _ Hx).\n        destruct H1 as [x2 [Hx21 Hx22] ].\n        rewrite elem_of_map in Hx22.\n        destruct Hx22 as [x0 [Hx01 Hx02] ].\n        inversion Hx01; clear Hx01; subst.\n        assumption.\n      }\n      {\n        rewrite elem_of_subseteq.\n        intros x Hx.\n        specialize (H2 _ Hx).\n        destruct H2 as [x2 [Hx21 Hx22] ].\n        rewrite elem_of_map in Hx22.\n        destruct Hx22 as [x0 [Hx01 Hx02] ].\n        inversion Hx01; clear Hx01; subst.\n        assumption.\n      }\n    Qed.\n\n    Lemma alpha_equiv_impl_same_svars {Σ : Signature} nϕ1 nϕ2:\n      alpha_equiv nϕ1 nϕ2 ->\n      (named_free_svars nϕ1) = (named_free_svars nϕ2).\n    Proof.\n      intros Halpha.\n      unfold alpha_equiv in Halpha.\n      pose proof (H1 := alpha_equiv'_impl_almost_same_svars _ _ nϕ1 nϕ2 Halpha).\n      pose proof (H2 := alpha_equiv'_impl_almost_same_svars _ _ nϕ2 nϕ1 (proj1 (alpha_equiv_sym nϕ1 nϕ2) Halpha)).\n      simpl in *. unfold twice in *.\n      apply anti_symm with (S := @subseteq (gset (svar)) _).\n      { apply _. }\n      {\n        rewrite elem_of_subseteq.\n        intros x Hx.\n        specialize (H1 _ Hx).\n        destruct H1 as [x2 [Hx21 Hx22] ].\n        rewrite elem_of_map in Hx22.\n        destruct Hx22 as [x0 [Hx01 Hx02] ].\n        inversion Hx01; clear Hx01; subst.\n        assumption.\n      }\n      {\n        rewrite elem_of_subseteq.\n        intros x Hx.\n        specialize (H2 _ Hx).\n        destruct H2 as [x2 [Hx21 Hx22] ].\n        rewrite elem_of_map in Hx22.\n        destruct Hx22 as [x0 [Hx01 Hx02] ].\n        inversion Hx01; clear Hx01; subst.\n        assumption.\n      }\n    Qed.\n\n    Lemma alpha_equiv_same_size {Σ : Signature}\n      (nϕ1 nϕ2 : NamedPattern) R R'\n      : alpha_equiv' R R' nϕ1 nϕ2 ->\n        nsize' nϕ1 = nsize' nϕ2.\n    Proof.\n      intros H.\n      induction H; simpl; lia.\n    Qed.\n\n    Lemma collapse_aux_nsize' {Σ : Signature}\n      (state : CollapseState)\n      (nϕ : NamedPattern)\n      : nsize' (collapse_aux state nϕ).2 = nsize' nϕ.\n    Proof.\n      move: state.\n      induction nϕ; intros state; simpl;\n        unfold lookup_or_leaf,lookup_or_node,lookup_or,alpha_equiv;\n        repeat case_match; subst; simpl; try lia;\n      match goal with\n      | [H' : list_find _ _ = Some _ |- _] =>\n        rewrite list_find_Some in H';\n        destruct_and!;\n        match goal with\n        | [ Ha: alpha_equiv' _ _ _ _ |- _] => apply alpha'_sym in Ha\n        end;\n        erewrite alpha_equiv_same_size;[|eassumption];reflexivity\n      | _ => congruence\n      end.\n    Qed.\n\n    Definition list_of_pairs_apply {A B : Type}\n    {_eqdA : EqDecision A}\n    {_eqdB : EqDecision B}\n    (x : A) (s : list (prod A B))\n     : list B\n   := fmap snd (filter (fun p => p.1 = x) s).\n\n   Definition list_of_pairs_compose {A B C : Type}\n      {_eqdA : EqDecision A}\n      {_eqdB : EqDecision B}\n      {_eqdC : EqDecision C}\n      (s1 : list (prod A B))\n      (s2 : list (prod B C))\n      : list (prod A C)\n    := foldr (fun (p : prod A B) (g' : list (prod A C)) =>\n        let a := p.1 in\n        let b := p.2 in\n        g' ++ (fmap (fun (c : C) => (a,c))  (list_of_pairs_apply b s2))\n    ) [] s1.\n\n\n    Lemma list_of_pairs_compose_correct {A B C : Type}\n    {_eqdA : EqDecision A}\n    {_eqdB : EqDecision B}\n    {_eqdC : EqDecision C}\n    (s1 : list (prod A B))\n    (s2 : list (prod B C))\n    : forall (a : A) (c : C),\n      (a, c) ∈ (list_of_pairs_compose s1 s2)\n      <-> exists (b : B), (a, b) ∈ s1 /\\ (b, c) ∈ s2.\n    Proof.\n      intros a c.\n      unfold list_of_pairs_compose.\n      split; intros H'.\n      {\n        induction s1; simpl in *.\n        {\n          inversion H'.\n        }\n        {\n          rewrite elem_of_app in H'.\n          destruct H' as [H'|H'].\n          {\n            specialize (IHs1 H').\n            destruct IHs1 as [b [Hb1 Hb2] ].\n            exists b.\n            split.\n            {\n              right. exact Hb1.\n            }\n            {\n              exact Hb2.\n            }\n          }\n          {\n            unfold fmap in H'.\n            rewrite elem_of_list_fmap in H'.\n            destruct H' as [y [Hy1 Hy2] ].\n            inversion Hy1; clear Hy1; subst.\n            unfold list_of_pairs_apply in Hy2.\n            unfold fmap in Hy2.\n            rewrite elem_of_list_fmap in Hy2.\n            destruct Hy2 as [[b c][Hc1 Hc2] ].\n            simpl in Hc1. subst y.\n            unfold filter in Hc2.\n            rewrite elem_of_list_filter in Hc2.\n            destruct a0 as [a0 b0]. simpl in *.\n            destruct Hc2 as [Hc2 Hc3].\n            simpl in Hc2. subst b.\n            exists b0.\n            split.\n            {\n              left.\n            }\n            {\n              exact Hc3.\n            }\n          }\n        }\n      }\n      {\n        move: a c H'.\n        induction s1; intros a' c' H'; simpl.\n        {\n          destruct H' as [b [Hb1 Hb2] ].\n          inversion Hb1.  \n        }\n        {\n          destruct H' as [b [Hb1 Hb2] ].\n          rewrite elem_of_app.\n          destruct a as [a'' b'']. simpl in *.\n          inversion Hb1; clear Hb1; subst.\n          {\n            specialize (IHs1 a'' c').\n            destruct (decide ((a'',b'') ∈ s1)).\n            {\n              feed specialize IHs1.\n              {\n                exists b''. split; assumption.\n              }\n              left. apply IHs1.\n            }\n            {\n              right.\n              unfold fmap.\n              rewrite elem_of_list_fmap.\n              exists c'.\n              split;[reflexivity|].\n              unfold list_of_pairs_apply.\n              unfold filter.\n              rewrite elem_of_list_fmap.\n              exists (b'', c').\n              split;[reflexivity|].\n              rewrite elem_of_list_filter.\n              simpl.\n              split;[reflexivity|assumption].\n            }\n          }\n          {\n            specialize (IHs1 a' c').\n            feed specialize IHs1.\n            {\n              exists b.\n              split; assumption.\n            }\n            left. apply IHs1.\n          }\n        }\n      }\n    Qed.\n\n    Program Definition pb_compose {A : Type}\n      {_eqd : EqDecision A }\n      {_cnd : Countable A }\n      (pb1 pb2 : PartialBijection A)\n      : PartialBijection A\n    := {|\n      pbr := list_to_set (list_of_pairs_compose (elements (pbr pb1)) (elements (pbr pb2))) ;\n    |}.\n    Next Obligation.\n      intros A _eqd _cnt pb1 pb2 x y1 y2 H1 H2.\n      rewrite elem_of_list_to_set in H1.\n      rewrite elem_of_list_to_set in H2.\n      rewrite list_of_pairs_compose_correct in H1.\n      rewrite list_of_pairs_compose_correct in H2.\n      destruct H1 as [B1 [HB11 HB12] ].\n      destruct H2 as [B2 [HB21 HB22] ].\n      rewrite elem_of_elements in HB11.\n      rewrite elem_of_elements in HB22.\n      rewrite elem_of_elements in HB12.\n      rewrite elem_of_elements in HB21.\n\n      destruct pb1 as [pbA pbApf1 pbApf2], pb2 as [pbB pbBpf1 pbBpf2].\n      simpl in *.\n      pose proof (pbApf1 _ _ _ HB11 HB21).\n      subst B2.\n      pose proof (pbBpf1 _ _ _ HB22 HB12).\n      subst y2.\n      reflexivity.\n    Qed.\n    Next Obligation.\n    intros A _eqd _cnt pb1 pb2 x y1 y2 H1 H2.\n    rewrite elem_of_list_to_set in H1.\n    rewrite elem_of_list_to_set in H2.\n    rewrite list_of_pairs_compose_correct in H1.\n    rewrite list_of_pairs_compose_correct in H2.\n    destruct H1 as [B1 [HB11 HB12] ].\n    destruct H2 as [B2 [HB21 HB22] ].\n    rewrite elem_of_elements in HB11.\n    rewrite elem_of_elements in HB22.\n    rewrite elem_of_elements in HB12.\n    rewrite elem_of_elements in HB21.\n\n    destruct pb1 as [pbA pbApf1 pbApf2], pb2 as [pbB pbBpf1 pbBpf2].\n    simpl in *.\n    pose proof (pbBpf2 _ _ _ HB22 HB12).\n    subst B2.\n    pose proof (pbApf2 _ _ _ HB11 HB21).\n    subst y1.\n    reflexivity.\n  Qed.\n  \n  Lemma compose_update {A : Type} {_eqd : EqDecision A} {_cnt : Countable A}\n    (R1 R2 : PartialBijection A) (x y z : A) :\n  pbr (pb_compose (pb_update R1 x y) (pb_update R2 y z))\n  ⊆ pbr (pb_update (pb_compose R1 R2) x z).\n  Proof.\n    destruct R1, R2.\n    simpl.\n      rewrite elem_of_subseteq.\n      intros [e1 e2] H.\n      rewrite elem_of_list_to_set in H.\n      rewrite list_of_pairs_compose_correct in H.\n      destruct H as [e' [He'1 He'2] ].\n      rewrite elem_of_elements in He'1.\n      rewrite elem_of_elements in He'2.\n      rewrite elem_of_union in He'1.\n      rewrite elem_of_union in He'2.\n      rewrite elem_of_filter in He'1.\n      rewrite elem_of_filter in He'2.\n      rewrite elem_of_singleton in He'1.\n      rewrite elem_of_singleton in He'2.\n      rewrite elem_of_union.\n      rewrite elem_of_filter.\n      rewrite elem_of_singleton.\n      rewrite elem_of_list_to_set.\n      rewrite list_of_pairs_compose_correct.\n      setoid_rewrite elem_of_elements.\n      unfold unrelated, related in *.\n      naive_solver.\n  Qed.\n\n  Lemma pb_update_mono {A : Type}\n    {_eqd : EqDecision A }\n    {_cnd : Countable A }\n    (R1 R2 : PartialBijection A)\n    (x y : A) :\n    pbr R1 ⊆ pbr R2 ->\n    pbr (pb_update R1 x y) ⊆ pbr (pb_update R2 x y).\n  Proof.\n    intros H.\n    unfold pb_update. simpl.\n    apply union_mono.\n    {\n      unfold filter.\n      rewrite elem_of_subseteq.\n      intros aa Haa.\n      rewrite elem_of_filter in Haa.\n      rewrite elem_of_filter.\n      destruct Haa as [H1 H2].\n      split;[assumption|].\n      set_solver.\n    }\n    {\n      apply reflexivity.\n    }\n  Qed.\n\n\n  Lemma alpha'_mono {Σ : Signature}\n    (R1 R2 : PartialBijection evar)\n    (R'1 R'2 : PartialBijection svar)\n    (t u : NamedPattern)\n    : \n      pbr R1 ⊆ pbr R2 ->\n      pbr R'1 ⊆ pbr R'2 ->\n      alpha_equiv' R1 R'1 t u ->\n      alpha_equiv' R2 R'2 t u.\n  Proof.\n    intros H1 H2 Ha.\n    move: R2 R'2 H1 H2.\n    induction Ha; intros R2 R'2 H1 H2; constructor; auto.\n    {\n      apply IHHa.\n      {\n        apply pb_update_mono.\n        exact H1.\n      }\n      {\n        apply H2.\n      }\n    }\n    {\n      apply IHHa.\n      { apply H1. }\n      {\n        apply pb_update_mono.\n        exact H2.\n      }\n    }\n  Qed.\n\n\n  Lemma compose_alpha' {Σ : Signature}\n    (R1 R2 : PartialBijection evar)\n    (R'1 R'2 : PartialBijection svar)\n    (t u v : NamedPattern):\n    alpha_equiv' R1 R'1 t u ->\n    alpha_equiv' R2 R'2 u v ->\n    alpha_equiv' (pb_compose R1 R2) (pb_compose R'1 R'2) t v.\n  Proof.\n    intros Htu Huv.\n    move : R1 R2 R'1 R'2 t v Htu Huv.\n    induction u; intros R1 R2 R'1 R'2 t v Htu Huv; inversion Htu; inversion Huv; clear Htu; clear Huv; subst;\n      constructor.\n    {\n      unfold pb_compose. simpl.\n      rewrite elem_of_list_to_set.\n      rewrite list_of_pairs_compose_correct.\n      exists x.\n      do 2 rewrite elem_of_elements.\n      split; assumption.\n    }\n    {\n      unfold pb_compose. simpl.\n      rewrite elem_of_list_to_set.\n      rewrite list_of_pairs_compose_correct.\n      exists X.\n      do 2 rewrite elem_of_elements.\n      split; assumption.\n    }\n    { naive_solver. }\n    { naive_solver. }\n    { naive_solver. }\n    { naive_solver. }\n    { \n      pose proof (H'' := IHu _ _ _ _ _ _ tEu tEu0).\n      eapply alpha'_mono;[apply compose_update|idtac|].\n      2: apply H''.\n      apply reflexivity.\n    }\n    {\n      eapply alpha'_mono;[|apply compose_update|idtac].\n      2: apply IHu.\n      3: apply tEu0.\n      2: apply tEu.\n      apply reflexivity.\n    }\n  Qed.\n\n  Lemma diagonal_mono {A : Type}\n  {_eqd : EqDecision A }\n  {_cnd : Countable A }\n  ( R1 R2 : gset A)\n  : R1 ⊆ R2 -> pbr (diagonal R1) ⊆ pbr (diagonal R2).\n  Proof.\n    intros H.\n    unfold diagonal. simpl.\n    apply set_map_mono;[|assumption].\n    unfold pointwise_relation.\n    intros a. reflexivity.\n  Qed.\n\n\n    Lemma collapse_aux_alpha'\n      {Σ : Signature}\n      (state : CollapseState)\n      (nϕ : NamedPattern)\n      : alpha_equiv (collapse_aux state nϕ).2 nϕ.\n    Proof.\n      remember (nsize' nϕ) as sz.\n      assert (Hsz: nsize' nϕ <= sz) by lia.\n      clear Heqsz.\n\n      move: nϕ Hsz state.\n      induction sz; intros nϕ Hsz state; destruct nϕ;\n        simpl in *; try lia; try apply lookup_or_leaf_alpha.\n      {\n        unfold lookup_or_node,lookup_or. simpl.\n        repeat case_match.\n        {\n          subst. simpl.\n          rewrite list_find_Some in H.\n          destruct H as [H1 [H2 H3] ].\n          apply alpha_equiv_sym.\n          apply H2.\n        }\n        {\n          simpl.\n          clear H.\n\n          constructor; simpl; unfold alpha_equiv in *.\n          {\n            pose proof (IH1 := (IHsz nϕ1 ltac:(lia) state)).\n            pose proof (IH2 := (IHsz nϕ2 ltac:(lia) state)).\n            pose proof (H1e := alpha_equiv_impl_same_evars _ _ IH1).\n            pose proof (H1s := alpha_equiv_impl_same_svars _ _ IH1).\n    \n            rewrite H1e H1s.\n\n            eapply alpha'_mono;[idtac|idtac|apply IH1].\n            {\n              apply diagonal_mono.\n              rewrite H1e. clear. set_solver.\n            }\n            {\n              apply diagonal_mono.\n              rewrite H1s. clear. set_solver.\n            }\n          }\n          {\n            erewrite alpha_equiv_impl_same_evars.\n            2: apply IHsz; lia.\n            erewrite alpha_equiv_impl_same_svars.\n            2: apply IHsz; lia.\n            \n            eapply alpha'_mono.\n            3: { eapply IHsz. lia. }\n            { apply diagonal_mono. clear. set_solver. } \n            { apply diagonal_mono. clear. set_solver. } \n          }\n        }\n      }\n      {\n        unfold lookup_or_node,lookup_or. simpl.\n        repeat case_match.\n        {\n          subst. simpl.\n          rewrite list_find_Some in H.\n          destruct H as [H1 [H2 H3] ].\n          apply alpha_equiv_sym.\n          apply H2.\n        }\n        {\n          simpl.\n          clear H.\n\n          constructor; simpl; unfold alpha_equiv in *.\n          {\n            pose proof (IH1 := (IHsz nϕ1 ltac:(lia) state)).\n            pose proof (IH2 := (IHsz nϕ2 ltac:(lia) state)).\n            pose proof (H1e := alpha_equiv_impl_same_evars _ _ IH1).\n            pose proof (H1s := alpha_equiv_impl_same_svars _ _ IH1).\n    \n            rewrite H1e H1s.\n\n            eapply alpha'_mono;[idtac|idtac|apply IH1].\n            {\n              apply diagonal_mono.\n              rewrite H1e. clear. set_solver.\n            }\n            {\n              apply diagonal_mono.\n              rewrite H1s. clear. set_solver.\n            }\n          }\n          {\n            erewrite alpha_equiv_impl_same_evars.\n            2: apply IHsz; lia.\n            erewrite alpha_equiv_impl_same_svars.\n            2: apply IHsz; lia.\n            \n            eapply alpha'_mono.\n            3: { eapply IHsz. lia. }\n            { apply diagonal_mono. clear. set_solver. } \n            { apply diagonal_mono. clear. set_solver. } \n          }\n        }\n      }\n      {\n        unfold lookup_or_node,lookup_or. simpl.\n        repeat case_match; simpl.\n        {\n          rewrite list_find_Some in H.\n          destruct H as [H1 [H2 H3] ].\n          apply alpha_equiv_sym.\n          apply H2.\n        }\n        {\n          clear H.\n          constructor.\n          eapply alpha'_mono.\n          3: apply IHsz; lia.\n          { \n            eapply transitivity.\n            {\n              eapply diagonal_mono.\n              erewrite alpha_equiv_impl_same_evars.\n              2: apply IHsz; lia.\n              rewrite union_idemp_L.\n              apply reflexivity.\n            }\n            simpl.\n            rewrite elem_of_subseteq.\n            intros [e1 e2] He1e2.\n            rewrite elem_of_map in He1e2.\n            destruct He1e2 as [x' [H1 H2] ].\n            unfold twice in H1. inversion H1. subst. clear H1.\n            rewrite elem_of_union.\n            rewrite elem_of_singleton.\n            destruct (decide (x = x')).\n            {\n              subst. right. reflexivity.\n            }\n            {\n              rewrite elem_of_filter.\n              unfold unrelated,related.\n              simpl.\n              left.\n              split;[naive_solver|].\n              rewrite elem_of_map.\n              exists x'.\n              split;[reflexivity|].\n              rewrite elem_of_union.\n              left.\n              rewrite elem_of_difference.\n              rewrite elem_of_singleton.\n              split;[|congruence].\n              erewrite alpha_equiv_impl_same_evars.\n              { exact H2. }\n              apply IHsz.\n              lia.\n            }\n          }\n          {\n            eapply transitivity.\n            {\n              eapply diagonal_mono.\n              erewrite alpha_equiv_impl_same_svars.\n              2: apply IHsz; lia.\n              rewrite union_idemp_L.\n              apply reflexivity.\n            }\n            simpl.\n            rewrite elem_of_subseteq.\n            intros [e1 e2] He1e2.\n            rewrite elem_of_map in He1e2.\n            destruct He1e2 as [x' [H1 H2] ].\n            unfold twice in H1. inversion H1. subst. clear H1.\n            rewrite elem_of_map.\n            exists x'.\n            split;[reflexivity|].\n            rewrite elem_of_union.\n            right. assumption.\n          }\n        }\n      }\n      {\n        unfold lookup_or_node,lookup_or. simpl.\n        repeat case_match; simpl.\n        {\n          rewrite list_find_Some in H.\n          destruct H as [H1 [H2 H3] ].\n          apply alpha_equiv_sym.\n          apply H2.\n        }\n        {\n          clear H.\n          constructor.\n          eapply alpha'_mono.\n          3: apply IHsz; lia.\n          { \n            eapply transitivity.\n            {\n              eapply diagonal_mono.\n              erewrite alpha_equiv_impl_same_evars.\n              2: apply IHsz; lia.\n              rewrite union_idemp_L.\n              apply reflexivity.\n            }\n            simpl.\n            rewrite elem_of_subseteq.\n            intros [e1 e2] He1e2.\n            rewrite elem_of_map in He1e2.\n            destruct He1e2 as [x' [H1 H2] ].\n            unfold twice in H1. inversion H1. subst. clear H1.\n\n            rewrite elem_of_map.\n            exists x'.\n            split;[reflexivity|].\n            rewrite elem_of_union.\n            right. assumption.\n          }\n          {\n            eapply transitivity.\n            {\n              eapply diagonal_mono.\n              erewrite alpha_equiv_impl_same_svars.\n              2: apply IHsz; lia.\n              rewrite union_idemp_L.\n              apply reflexivity.\n            }\n            simpl.\n            rewrite elem_of_subseteq.\n            intros [e1 e2] He1e2.\n            rewrite elem_of_map in He1e2.\n            destruct He1e2 as [X' [H1 H2] ].\n            unfold twice in H1. inversion H1. subst. clear H1.\n            \n            rewrite elem_of_union.\n            rewrite elem_of_singleton.\n            destruct (decide (X = X')).\n            {\n              subst. right. reflexivity.\n            }\n            {\n              rewrite elem_of_filter.\n              unfold unrelated,related.\n              simpl.\n              left.\n              split;[naive_solver|].\n              rewrite elem_of_map.\n              exists X'.\n              split;[reflexivity|].\n              rewrite elem_of_union.\n              left.\n              rewrite elem_of_difference.\n              rewrite elem_of_singleton.\n              split;[|congruence].\n              erewrite alpha_equiv_impl_same_svars.\n              { exact H2. }\n              apply IHsz.\n              lia.\n            }\n          }\n        }\n      }\n    Qed.\n\n  (*\n  (* TESTS *)\nFrom MatchingLogic Require Import StringSignature.\n\nDefinition Σ : Signature :=\n  {|\n   |}\n#[local]\nExample ex_rename {Σ : Signature} :\n  rename  = patt_bott.\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/ProofSystemTranslation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5, "lm_q1q2_score": 0.28492632570707854}}
{"text": "From CoreErlang.FrameStack Require Export CIU.\n\nImport ListNotations.\n\nLtac scope_solver_step :=\n  match goal with \n  | |- EXP _ ⊢ _ => constructor; simpl; auto\n  | |- VAL _ ⊢ _ => constructor; simpl; auto\n  | |- RED _ ⊢ _ => constructor; simpl; auto\n  | |- NVAL _ ⊢ _ => constructor; simpl; auto\n  | |- forall i, i < _ -> _ => simpl; intros\n  | [H : ?i < _ |- _] => inv H; simpl in *; auto; try lia\n  | [H : ?i <= _ |- _] => inv H; simpl in *; auto; try lia\n  | [H : EXP ?n1 ⊢ ?e |- EXP ?n2 ⊢ ?e] => try now (eapply (loosen_scope_exp n2 n1 ltac:(lia)) in H)\n  | [H : VAL ?n1 ⊢ ?e |- VAL ?n2 ⊢ ?e] => try now (eapply (loosen_scope_val n2 n1 ltac:(lia)) in H)\n  | [H : NVAL ?n1 ⊢ ?e |- NVAL ?n2 ⊢ ?e] => try now (eapply (loosen_scope_nonval n2 n1 ltac:(lia)) in H)\n  end.\n\nLtac scope_solver := repeat scope_solver_step; try lia.\n\nLtac deriv :=\n  match goal with\n  | [H : ?i < length _ |- _] => simpl in *; inv H; auto; try lia\n  | [H : ?i <= length _ |- _] => simpl in *; inv H;  auto; try lia\n  | [H : | _, _ | ↓ |- _] => inv H; try inv_val\n  | [H : | _ :: _, RValSeq _ | _ ↓ |- _] => inv H; try inv_val\n  | [H : | _ :: _, RExc _ | _ ↓ |- _] => inv H; try inv_val\n  | [H : | _, RExp (EExp _) | _ ↓ |- _] => inv H; try inv_val\n  | [H : | _, RExp (VVal _) | _ ↓ |- _] => inv H; try inv_val\n  | [H : | _, RBox | _ ↓ |- _] => inv H; try inv_val\n  end.\n\nLtac extract_meta_eval H :=\n  let r := fresh \"r\" in\n  let k := fresh \"k\" in\n  let Hr := fresh \"Hr\" in\n  let Hd := fresh \"Hd\" in\n  let Hd' := fresh \"Hd'\" in\n  let Hk := fresh \"Hk\" in\n  let H' := fresh \"H'\" in\n  eapply term_eval_both in H as H'; destruct H' as [r [k [Hr [Hd [Hd' Hk]]]]];\n  eapply term_step_term in Hd'; [|eassumption]; inv Hr.\n\nLtac unfold_list := \n  match goal with\n  | [H : length ?l = 0 |- _] => destruct l; try inv H\n  | [H : 0 = length ?l |- _] => destruct l; try inv H\n  | [H : length ?l = S ?n |- _] => destruct l; try inv H; unfold_list\n  | [H : S ?n = length ?l |- _] => destruct l; try inv H; unfold_list\n  end.\n\nTactic Notation \"replace\" \"counter\" \"with\" constr(num) :=\n  match goal with\n  | |- | _, _ | ?k ↓ => replace k with num by lia\n  end.\n\nSection case_if_equiv.\n\n  Open Scope string_scope.\n  Variables (e1 e2 e3 : Exp) (Γ : nat).\n  Hypotheses (He1 : EXP Γ ⊢ e1)\n             (He2 : EXP Γ ⊢ e2)\n             (He3 : EXP Γ ⊢ e3).\n\n  Local Definition nonidiomatic :=\n    ELet 1 e1\n      (ECase (`VVar 0) \n              [([PLit (Atom \"true\")], `VLit \"true\", e2);\n              ([PVar], `VLit \"true\", e3.[ren (fun n => 2 + n) ])]).\n\n  Local Definition idiomatic :=\n    ELet 1 e1\n      (ECase (EValues [])\n          [([], °ECall \"erlang\" \"=:=\" [`VVar 0;`VLit \"true\"], e2);\n          ([], `VLit \"true\", e3.[ren (fun n => 1 + n) ])]).\n\n  Local Proposition nonidiomatic_scope :\n    EXP Γ ⊢ nonidiomatic.\n  Proof.\n    unfold nonidiomatic.\n    scope_solver.\n    apply -> subst_preserves_scope_exp. exact He3.\n    intro. intros. simpl. lia. \n  Qed.\n\n  Local Proposition idiomatic_scope :\n    EXP Γ ⊢ idiomatic.\n  Proof.\n    unfold idiomatic.\n    scope_solver.\n    apply -> subst_preserves_scope_exp. exact He3.\n    intro. intros. simpl. lia. \n  Qed.\n\n  Local Theorem equivalence_part1 :\n    CIU_open Γ nonidiomatic idiomatic.\n  Proof.\n    split. 2: split.\n    constructor. apply -> subst_preserves_scope_exp; try apply nonidiomatic_scope; auto.\n    constructor. apply -> subst_preserves_scope_exp; try apply idiomatic_scope; auto.\n    {\n      intros. unfold nonidiomatic in H1. simpl in H1.\n      repeat deriv.\n      extract_meta_eval H7; clear H7.\n      { (* e1 evaluates to an exception *)\n        inv Hd'. clear H5.\n        unfold idiomatic.\n        exists (S (S k1 + k0)). simpl. econstructor.\n        eapply frame_indep_nil in Hd.\n        eapply step_term_term. eassumption. 2: lia.\n        replace (S (k1 + k0) - k0) with (S k1) by lia. constructor. congruence.\n        eassumption.\n      }\n      { (* e1 evaluates correctly *)\n        deriv. unfold_list. simpl in H7.\n        do 3 deriv.\n        { (* v is true *)\n          simpl in H10. destruct v; try congruence. break_match_hyp; try congruence.\n          break_match_hyp; try congruence. destruct l; simpl in Heqb; try congruence.\n          break_match_hyp; try congruence. inv Heqo. simpl in H10. inv H10.\n          simpl in H11. do 2 deriv.\n          cbn in H9. inv H9.\n          unfold idiomatic.\n          exists (S (12 + k2 + k0)). simpl. econstructor.\n          eapply frame_indep_nil in Hd.\n          eapply step_term_term. eassumption. 2: lia.\n          replace counter with (12 + k2).\n          constructor. reflexivity.\n          simpl. constructor.\n          constructor. econstructor. congruence. simpl. reflexivity.\n          econstructor. reflexivity.\n          simpl. constructor. econstructor. congruence.\n          constructor. constructor. constructor. simpl. econstructor. cbn. reflexivity.\n          econstructor. reflexivity. eassumption.\n        }\n        { (* v is not true *)\n          deriv.\n          2: { (* no more cases *)\n            inv H9.\n          }\n          simpl in H12. do 2 deriv. rewrite H11 in H9. inv H9.\n          unfold idiomatic.\n          exists (S (15 + k1 + k0)). simpl. econstructor.\n          eapply frame_indep_nil in Hd.\n          eapply step_term_term. eassumption. 2: lia.\n          replace counter with (15 + k1).\n          constructor. reflexivity.\n          simpl. constructor.\n          constructor. econstructor. congruence. simpl. reflexivity.\n          econstructor. reflexivity.\n          simpl. constructor. econstructor. congruence.\n          constructor. constructor. constructor. simpl. econstructor.\n          { (* v is not true *)\n            cbn. clear Hd H11 H12 H6. destruct v; simpl; try reflexivity.\n            2: destruct n; reflexivity.\n            destruct l; try reflexivity. simpl.\n            destruct string_dec; try reflexivity. subst. simpl in H10. congruence.\n          } \n          constructor. econstructor. reflexivity. constructor. econstructor.\n          reflexivity.\n          simpl in H11. inv H11.\n          do 2 rewrite subst_comp_exp in *.\n          clear Hd H10. cbn in *.\n          rewrite substcomp_id_r.\n          rewrite subst_extend in H12.\n          rewrite substcomp_scons_core, subst_extend in H12.\n          rewrite subst_extend.\n          rewrite subst_comp_exp in *.\n          rewrite ren_scons in *.\n          rewrite ren_scons in H12. assumption.\n        }\n      }\n    }\n  Qed.\n\n  Local Theorem equivalence_part2 :\n    CIU_open Γ idiomatic nonidiomatic.\n  Proof.\n    apply Rrel_implies_CIU.\n    apply Rrel_exp_compat. apply Erel_Let_compat; auto.\n    apply Rrel_exp_compat_reverse. apply CIU_implies_Rrel.\n    pose proof (nonidiomatic_scope).\n    pose proof (idiomatic_scope).\n    unfold idiomatic, nonidiomatic in *. inv H. inv H0. inv H3. inv H2.\n    split. 2: split.\n    1-2: constructor; apply -> subst_preserves_scope_exp; eauto.\n    clear H6 H3 H7. intros. simpl in H1.\n    do 4 deriv. simpl in H9. deriv. 2: { inv H11. }\n    inv H11.\n    simpl in H12. rewrite idsubst_is_id_val in H12. do 3 deriv.\n    break_match_hyp.\n    2: { (* technical, Q: should this be possible? Evaluation of variables shouldn't just fail? -> variables are values or expressions? *)\n      do 3 deriv. cbn in H11.\n      do 2 deriv. 2: { deriv. inv H12. }\n      simpl in H13. do 2 deriv. inv H11. inv H12.\n      exists (6 + k0). simpl.\n      econstructor. rewrite Heqs. do 2 constructor. reflexivity.\n      econstructor. reflexivity. simpl. constructor. econstructor.\n      reflexivity. simpl.\n      rewrite subst_comp_exp in *. simpl in *.\n      rewrite subst_extend, subst_comp_exp in *.\n      rewrite substcomp_id_r, ren_scons in *. assumption.\n    }\n    do 3 deriv. cbn in H11.\n    break_match_hyp.\n    { (* e1 is true *)\n      deriv. inv H9. simpl in H12. rewrite idsubst_is_id_exp in H12.\n      exists (5 + k). simpl.\n      econstructor. rewrite Heqs.\n      destruct v; simpl in Heqb; try congruence.\n      destruct l; simpl in Heqb; try congruence.\n      break_match_hyp; try congruence. subst.\n      econstructor. econstructor. reflexivity.\n      constructor. econstructor. reflexivity.\n      simpl. now rewrite idsubst_is_id_exp.\n    }\n    { (* e1 is false *)\n      do 2 deriv. 2: { inv H12. }\n      simpl in H13. do 2 deriv. inv H12. inv H11.\n      exists (6 + k0). simpl.\n      econstructor. rewrite Heqs. do 2 constructor.\n      {\n        destruct v; simpl in Heqb; try reflexivity.\n        destruct l; simpl in Heqb; try reflexivity.\n        break_match_hyp; subst; try congruence.\n        cbn. destruct string_dec; auto. congruence.\n      }\n      econstructor. reflexivity. simpl. constructor. econstructor.\n      reflexivity. simpl.\n      rewrite subst_comp_exp in *. simpl in *.\n      rewrite subst_extend, subst_comp_exp in *.\n      rewrite substcomp_id_r, ren_scons in *. assumption.\n    }\n  Qed.\nEnd case_if_equiv.\n\nSection length_0.\n\n  Open Scope string_scope.\n  Variables (e1 e2 : Exp) (Γ : nat).\n  Hypotheses (He1 : EXP Γ ⊢ e1)\n             (He2 : EXP Γ ⊢ e2).\n\n  Local Definition nonidiomatic2 :=\n    ECase e1\n    [([PVar], \n      °ETry \n      (\n        ELet 1 (ECall \"erlang\" \"length\" [`VVar 0])\n          (ECall \"erlang\" \"==\" [`VVar 0;`VLit 0%Z])\n      )\n      1 (`VVar 0)\n      3 (`VLit \"false\")\n      , e2.[ren (fun n => 1 + n)])\n    ;\n    ([PVar], `VLit \"true\", °EPrimOp \"match_fail\" [°ETuple [`VLit \"function_clause\";`VVar 0]])].\n\n  Local Definition idiomatic2 :=\n    ECase e1 [(\n      [PNil], `VLit \"true\", e2);\n      ([PVar], `VLit \"true\", °EPrimOp \"match_fail\" [°ETuple [`VLit \"function_clause\"; `VVar 0]])].\n\n  Local Proposition nonidiomatic2_scope :\n    EXP Γ ⊢ nonidiomatic2.\n  Proof.\n    unfold nonidiomatic2.\n    scope_solver.\n    apply -> subst_preserves_scope_exp. exact He2.\n    intro. intros. simpl. lia. \n  Qed.\n\n  Local Proposition idiomatic2_scope :\n    EXP Γ ⊢ idiomatic2.\n  Proof.\n    unfold idiomatic2.\n    scope_solver.\n  Qed.\n\n  Local Theorem equivalence2_part1 :\n    CIU_open Γ nonidiomatic2 idiomatic2.\n  Proof.\n    (* we cannot use compatibility lemmas here, because\n       the patterns are different in the clauses *)\n    pose proof idiomatic2_scope as Sc1.\n    pose proof nonidiomatic2_scope as Sc2.\n    split. 2: split.\n    1-2: constructor; apply -> subst_preserves_scope_exp; eauto.\n    intros. simpl in H1. destruct H1 as [k D].\n    deriv. extract_meta_eval H5; clear H5.\n    { (* e1 evaluates to an exception *)\n      inv Hd'. exists (2 + k + k1). simpl.\n      econstructor. eapply step_term_term.\n      eapply frame_indep_nil in Hd. exact Hd. 2: lia.\n      replace counter with (S k1). econstructor; auto. congruence. \n    }\n    { (* e1 evaluates correctly *)\n      deriv.\n      { (* pattern matching succeeds *)\n        destruct vs. inv H3. destruct vs. 2: inv H3.\n        simpl in H3. inv H3.\n        inv H9. inv H10. repeat deriv.\n        simpl in H10. destruct (eval_length [v]) eqn:EQ.\n        {\n          simpl in EQ. break_match_hyp; try congruence.\n        }\n        { (* v is a list *)\n          apply eval_length_number in EQ as EQ'. intuition; repeat destruct_hyps.\n          { (* v = VNil *)\n            inv H1. inv H3. clear H2. simpl in EQ. rewrite EQ in H10.\n            inv H10. simpl in H7. repeat deriv. cbn in H12. inv EQ.\n            simpl in H12. inv H12. simpl in H14.\n            repeat deriv. inv H12. simpl in H14.\n            rewrite subst_comp_exp, subst_extend, subst_comp_exp in H14.\n            rewrite ren_scons, substcomp_id_l in H14.\n            (* evaluation *)\n            exists (4 + k + k1). simpl.\n            econstructor. eapply step_term_term.\n            eapply frame_indep_nil in Hd; exact Hd. 2: lia.\n            replace counter with (3 + k1). econstructor. reflexivity.\n            constructor. econstructor. reflexivity. simpl.\n            now rewrite idsubst_is_id_exp.\n          }\n          { (* v = VCons v1 v2 *)\n            inv H1. inv H2. clear H3.\n            pose proof EQ as EQ'. simpl in EQ. rewrite EQ in H10. clear EQ.\n            simpl in H10. repeat deriv.\n            simpl in H7. repeat deriv. cbn in H12.\n            break_match_hyp. {\n              pose proof (eval_length_positive _ _ _ EQ').\n              lia.\n            }\n            repeat deriv. simpl in H14.\n            repeat deriv. 2: inv H14. inv H14.\n            simpl in H15. repeat deriv.\n            inv H12. simpl in H14. repeat deriv. simpl in H15.\n            repeat deriv. simpl in H10.\n            (* evaluation *)\n            simpl. exists (14 + k + k1). simpl.\n            econstructor. eapply step_term_term.\n            eapply frame_indep_nil in Hd; exact Hd. 2: lia.\n            replace counter with (13 + k1). constructor. reflexivity.\n            econstructor. reflexivity. simpl.\n            do 2 econstructor. reflexivity. simpl.\n            do 2 econstructor. congruence.\n            do 2 econstructor. congruence.\n            do 4 econstructor. reflexivity. simpl.\n            econstructor. reflexivity. simpl. assumption.\n          }\n        }\n        { (* exception *)\n          simpl in EQ. rewrite EQ in H10. inv H10. inv H6. 2: {\n            specialize (H5 _ _ _ _ eq_refl). contradiction.\n          }\n          simpl in H11. repeat deriv. 2: inv H12.\n          simpl in H13. repeat deriv.\n          inv H12. inv H11. simpl in H13. repeat deriv.\n          simpl in H13. inv H13. simpl in H10.\n          (* evaluation *)\n          simpl. exists (14 + k + k1). simpl.\n          econstructor. eapply step_term_term.\n          eapply frame_indep_nil in Hd; exact Hd. 2: lia.\n          replace counter with (13 + k1). constructor.\n          destruct v; auto. inv EQ. clear H4 H8.\n          econstructor. reflexivity. constructor.\n          econstructor. reflexivity. simpl.\n          constructor. constructor. congruence.\n          do 2 constructor. congruence. do 4 econstructor.\n          reflexivity. simpl. econstructor. reflexivity. simpl.\n          assumption.\n        }\n        {\n          simpl in EQ. break_match_hyp; inv EQ.\n        }\n      }\n      { (* pattern matching fails due to the degree of `vs` - in the concrete Core Erlang implementation this cannot happen, because such programs are filtered out by the compiler *)\n        repeat deriv. congruence.\n        (* evaluation *)\n        simpl. exists (4 + k + k1). simpl.\n        econstructor. eapply step_term_term.\n        eapply frame_indep_nil in Hd; exact Hd. 2: lia.\n        replace counter with (3 + k1). constructor.\n        {\n          destruct vs; auto. destruct vs; simpl; destruct v; auto.\n          inv H11.\n        }\n        constructor. assumption. constructor. assumption.\n      }\n    }\n  Qed.\n\n  Local Theorem equivalence2_part2 :\n    CIU_open Γ idiomatic2 nonidiomatic2.\n  Proof.\n    (* the beginning of this proof is the same as before *)\n    (* we cannot use compatibility lemmas here, because\n    the patterns are different in the clauses *)\n    pose proof idiomatic2_scope as Sc1.\n    pose proof nonidiomatic2_scope as Sc2.\n    split. 2: split.\n    1-2: constructor; apply -> subst_preserves_scope_exp; eauto.\n    intros. simpl in H1. destruct H1 as [k D].\n    deriv. extract_meta_eval H5; clear H5.\n    { (* e1 evaluates to an exception *)\n      inv Hd'. exists (2 + k + k1). simpl.\n      econstructor. eapply step_term_term.\n      eapply frame_indep_nil in Hd. exact Hd. 2: lia.\n      replace counter with (S k1). econstructor; auto. congruence. \n    }\n    (* new stuff *)\n    { (* e1 evaluates correctly *)\n      inv Hd'.\n      { (* vs = [VNil] *)\n        simpl in H9. destruct vs. 2: destruct vs. all: inv H3.\n        all: destruct v; inv H2.\n        repeat deriv. inv H9. simpl in H10.\n        rewrite idsubst_is_id_exp in H10.\n        (* evaluation *)\n        simpl. exists (18 + k + k1). simpl.\n        econstructor. eapply step_term_term.\n        eapply frame_indep_nil in Hd. exact Hd. 2: lia.\n        replace counter with (17 + k1).\n        econstructor. reflexivity. simpl.\n        repeat econstructor. 1-2: congruence. simpl.\n        rewrite subst_comp_exp, subst_extend, subst_comp_exp.\n        rewrite ren_scons, substcomp_id_l.\n        assumption.\n      }\n      inv H9.\n      { (* vs == [v] /\\ v <> VNil *)\n        destruct vs. 2: destruct vs.\n        all: inv H11.\n        simpl in H12. repeat deriv. inv H10.\n        simpl in H11. repeat deriv.\n        simpl in H12. repeat deriv.\n        simpl in H9.\n        (* evaluation *)\n        simpl.\n        simpl. destruct (eval_length [v]) eqn:EQ.\n        {\n          simpl in EQ. break_match_hyp; try congruence.\n        }\n        {\n          exists (30 + k + k1). simpl.\n          econstructor. eapply step_term_term.\n          eapply frame_indep_nil in Hd. exact Hd. 2: lia.\n          replace counter with (29 + k1).\n          econstructor. reflexivity.\n          simpl. econstructor. constructor.\n          do 2 constructor. congruence.\n          constructor. econstructor. reflexivity.\n          apply eval_length_number in EQ as EQ'.\n          intuition; repeat destruct_hyps. inv H1. inv H4. clear H2.\n          inv EQ.\n          { (* v = VNil*)\n            inv H3.\n          }\n          (* boiler plate so that we can see the individual steps\n             of the evaluation *)\n          { (* v = VCons v1 v2 *)\n            inv H2.\n            apply eval_length_positive in EQ as EQ'.\n            Opaque eval_length. simpl. rewrite EQ.\n            econstructor. reflexivity. simpl.\n            econstructor. econstructor. congruence.\n            econstructor. econstructor. econstructor.\n            econstructor. reflexivity. cbn. break_match_goal. lia.\n            econstructor. reflexivity. simpl.\n            econstructor. econstructor.\n            econstructor. reflexivity.\n            econstructor. econstructor. reflexivity. simpl.\n            econstructor. constructor. congruence.\n            econstructor. constructor. congruence.\n            econstructor. econstructor. simpl.\n            econstructor. econstructor. reflexivity.\n            econstructor. reflexivity. simpl.\n            assumption.\n          }\n        }\n        {\n          (* boiler plate so that we can see the individual steps\n             of the evaluation *)\n          exists (24 + k + k1). simpl.\n          econstructor. eapply step_term_term.\n          eapply frame_indep_nil in Hd. exact Hd. 2: lia.\n          replace counter with (23 + k1).\n          econstructor. reflexivity.\n          simpl. econstructor. constructor.\n          do 2 constructor. congruence.\n          constructor. econstructor. reflexivity. cbn.\n          rewrite EQ.\n          Transparent eval_length.\n          econstructor. congruence.\n          destruct e, p. apply cool_try_err.\n          econstructor. econstructor. econstructor. reflexivity.\n          econstructor. econstructor. reflexivity. cbn.\n          econstructor. econstructor. congruence.\n          econstructor. econstructor. congruence.\n          econstructor. econstructor. simpl.\n          econstructor. econstructor. reflexivity.\n          econstructor. reflexivity. simpl.\n          assumption.\n        }\n        {\n          simpl in EQ. break_match_hyp; inv EQ.\n        }\n      }\n      { (* pattern matching fails due to the degree of `vs` - in the concrete Core Erlang implementation this cannot happen, because such programs are filtered out by the compiler *)\n        inv H12. simpl.\n        (* evaluation *)\n        exists (4 + k1 + k). simpl.\n        econstructor. eapply step_term_term.\n        eapply frame_indep_nil in Hd. exact Hd. 2: lia.\n        replace counter with (3 + k1).\n        constructor. assumption.\n        constructor. assumption.\n        constructor. assumption.\n      }\n    }\n  Qed.\n\nEnd length_0.\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/Examples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5, "lm_q1q2_score": 0.28492632570707854}}
{"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                      Comma Category (x|G)            \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\nRequire Export Functor.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\n(* (x|G) *)\n\nSection comma_def.\n\nVariables (A X : Category) (G : Functor A X) (x : X).\n\nStructure Com_ob : Type :=  {Ob_com_ob : A; Mor_com_ob : x --> G Ob_com_ob}.\n\n Section com_arrow_def.\n\n Variable axf bxg : Com_ob.\n \n Definition Com_law (h : Ob_com_ob axf --> Ob_com_ob bxg) :=\n   Mor_com_ob bxg =_S Mor_com_ob axf o FMor G h.\n\n Structure > Com_arrow : Type := \n   {Mor_com_arrow : Ob_com_ob axf --> Ob_com_ob bxg;\n    Prf_com_law :> Com_law Mor_com_arrow}.\n\n (*** rewrite rules ***)\n\n (* *)\n\n Definition Equal_com_arrow (h h' : Com_arrow) :=\n   Mor_com_arrow h =_S Mor_com_arrow h'.\n\n Lemma Equal_com_arrow_equiv : Equivalence Equal_com_arrow.\n Proof.\n apply Build_Equivalence; unfold Equal_com_arrow in |- *.\n unfold Reflexive in |- *; intro f.\n apply Refl.\n apply Build_Partial_equivalence.\n unfold Transitive in |- *; intros f g h H1 H2.\n (* *) apply Trans with (Mor_com_arrow g); assumption. \n unfold Symmetric in |- *; intros f g H.\n apply Sym; assumption.\n Qed.\n\n Canonical Structure Com_arrow_setoid : Setoid := Equal_com_arrow_equiv.\n\n End com_arrow_def. \n\n(* composition of two arrows in comma *)\n\n Section comp_com_def.\n\n Variables (axf bxg cxh : Com_ob) (f : Com_arrow axf bxg)\n   (g : Com_arrow bxg cxh).\n\n Definition Comp_com_mor := Mor_com_arrow f o Mor_com_arrow g.\n\n Lemma Comp_com_law : Com_law Comp_com_mor.\n Proof.\n unfold Com_law, Comp_com_mor in |- *.\n (* *) apply Trans with (Mor_com_ob bxg o FMor G (Mor_com_arrow g)).\n apply (Prf_com_law g).\n (* *) apply\n        Trans\n         with\n           (Mor_com_ob axf\n            o FMor G (Mor_com_arrow f) o FMor G (Mor_com_arrow g)).\n (* *) apply\n        Trans\n         with\n           ((Mor_com_ob axf o FMor G (Mor_com_arrow f))\n            o FMor G (Mor_com_arrow g)).\n apply Comp_r; apply (Prf_com_law f).\n apply Ass1.\n apply Comp_l; apply FComp1.\n Qed.\n\n Canonical Structure Comp_com_arrow := Build_Com_arrow Comp_com_law.\n\n End comp_com_def.\n \n(* composition operator *)\n\nLemma Comp_com_congl : Congl_law Comp_com_arrow.\nProof.\nunfold Congl_law in |- *; simpl in |- *.\nintros a b c f1; elim f1; intros h e f2.\nelim f2; intros h' e' f3; elim f3; intros h'' e''.\nunfold Equal_com_arrow in |- *; simpl in |- *.\nunfold Comp_com_mor in |- *; simpl in |- *.\nintro H; apply Comp_l; trivial.\nQed.\n\nLemma Comp_com_congr : Congr_law Comp_com_arrow.\nProof.\nunfold Congr_law in |- *; simpl in |- *.\nintros a b c f1; elim f1; intros h e f2.\nelim f2; intros h' e' f3; elim f3; intros h'' e''.\nunfold Equal_com_arrow in |- *; simpl in |- *.\nunfold Comp_com_mor in |- *; simpl in |- *.\nintro H; apply Comp_r; trivial.\nQed.\n\nDefinition Comp_Comma := Build_Comp Comp_com_congl Comp_com_congr. \n\nLemma Assoc_Comma : Assoc_law Comp_Comma.\nProof.\nunfold Assoc_law in |- *; intros a b c d f1; elim f1.\nintros h1 e1 f2; elim f2; intros h2 e2 f3.\nelim f3; intros h3 e3.\nsimpl in |- *; unfold Equal_com_arrow in |- *; simpl in |- *.\nunfold Comp_com_mor in |- *; simpl in |- *.\nunfold Comp_com_mor in |- *; simpl in |- *.\napply Ass.\nQed.\n\n(* Id *)\n\nLemma Id_com_law : forall axf : Com_ob, Com_law (Id (Ob_com_ob axf)).\nProof.\nintro axf; unfold Com_law in |- *.\n(* *) apply Trans with (Mor_com_ob axf o Id (G (Ob_com_ob axf))).\napply Idr.\napply Comp_l; apply FId1.\nQed.\n\nCanonical Structure Id_Comma (axf : Com_ob) :=\n  Build_Com_arrow (Id_com_law axf).\n\nLemma Idl_Comma : Idl_law Comp_Comma Id_Comma.\nProof.\nunfold Idl_law in |- *; intros a b f1; elim f1; intros h e.\nsimpl in |- *; unfold Equal_com_arrow in |- *; simpl in |- *.\nunfold Comp_com_mor in |- *; simpl in |- *.\napply Idl.\nQed.\n\nLemma Idr_Comma : Idr_law Comp_Comma Id_Comma.\nProof.\nunfold Idr_law in |- *; intros a b f1; elim f1; intros h e.\nsimpl in |- *; unfold Equal_com_arrow in |- *; simpl in |- *.\nunfold Comp_com_mor in |- *; simpl in |- *.\napply Idr.\nQed.\n\nCanonical Structure Comma := Build_Category Assoc_Comma Idl_Comma Idr_Comma.\n\nEnd comma_def.", "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/FUNCTOR/Comma.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5, "lm_q1q2_score": 0.28492632570707854}}
{"text": "Require Export SpathIncl.\nRequire Import Lia.\n\nSection disj.\n\n  Infix \"-->\" := edge__P.\n\n  Context `(D : DiamondPaths).\n  Hypothesis (Hjle : j1 ⊴ j2).\n\n  Lemma split_node\n        (Hnempty : r1 <> nil \\/ r2 <> nil)\n    : hd (s,k) (rev r1) <> hd (s,k) (rev r2).\n  Proof.\n    destruct Hnempty.\n    - destr_r' r1;subst;[contradiction|].\n      destruct D.\n      rewrite rev_rcons. cbn.\n      destr_r' r2;subst;cbn in Dqj2.\n      + inv Dqj2. cbn. intro N. subst x. eapply path_rcons in Dsk1;eauto.\n        eapply tcfg_enroot in Dsk1;eauto. destructH.\n        eapply tpath_NoDup in Dsk1.\n        eapply NoDup_app with (a:=(q2,j2)).\n        * rewrite <-app_assoc in Dsk1. eapply Dsk1.\n        * rewrite app_comm_cons. eapply In_rcons. left. auto.\n        * cbn. left. auto.\n      + cbn. rewrite rev_rcons. cbn.\n        eapply disjoint2;eauto.\n    - destr_r' r2;subst;[contradiction|].\n      destruct D.\n      rewrite rev_rcons. cbn.\n      destr_r' r1;subst;cbn in Dqj1.\n      + inv Dqj2. cbn. intro N. subst x. eapply path_rcons in Dsk2;eauto.\n        eapply tcfg_enroot in Dsk2;eauto. destructH.\n        eapply tpath_NoDup in Dsk2.\n        eapply NoDup_app with (a:=(q1,j1)).\n        * rewrite <-app_assoc in Dsk2. eapply Dsk2.\n        * rewrite app_comm_cons. eapply In_rcons. left. auto.\n        * cbn. left. auto.\n      + cbn. rewrite rev_rcons. cbn.\n        eapply disjoint2;eauto.\n  Qed.\n\n  Lemma s_deq_q\n    : deq_loop s q1.\n  Proof.\n    clear Hjle.\n    eapply diamond_split in D. eapply spath_s_deq_q;eauto.\n  Qed.\n\n  Lemma no_head_inst (h : Lab) (l : Tag)\n        (Hcont : innermost_loop h q1)\n        (Hel : (h,l) ∈ r1)\n    : False.\n  Proof.\n    eapply diamond_split in D. eapply spath_no_head_inst;eauto.\n  Qed.\n\n  Lemma no_back : forall x : Lab, x ∈ (map fst r1) -> ~ loop_contains x q1.\n  Proof. (* Hjle needed *)\n    eapply diamond_split in D. eapply spath_no_back;eauto.\n  Qed.\n\nEnd disj.\n\nLemma r1_incl_head_q `(D : DiamondPaths)\n  : forall x, x ∈ map fst r1 -> deq_loop x q1.\nProof.\n  eapply diamond_split in D.\n  eapply spath_r1_incl_head_q. eassumption.\nQed.\n\nLemma r2_incl_head_q `(D : DiamondPaths)\n  : forall x, x ∈ map fst r2 -> deq_loop x q1.\nProof.\n  eapply diamond_split in D.\n  eapply spath_r2_incl_head_q. eassumption.\nQed.\n\nLemma tag_eq1 `(D : DiamondPaths)\n      (Hjle : j1 ⊴ j2)\n  : forall j, j ∈ map snd r1 -> take_r (depth q1) j = j1.\nProof.\n  eapply diamond_split in D.\n  eapply spath_tag_eq1;eauto.\nQed.\n\n  Lemma tag_eq_kj1 `(D : DiamondPaths)\n        (Hjle : j1 ⊴ j2)\n    : take_r (depth q1) k = j1.\n  Proof.\n    destruct r1;inv_Dpaths D.\n    - rewrite take_r_geq;eauto. rewrite Dlen. eauto.\n    - assert (l1 ∈ map snd ((q1,j1) :: r1)) as Hin.\n      {\n        destruct D. inv_path Dpath1. eapply path_contains_back in H.\n        eapply in_map with (f:=snd) in H. unfold snd in H at 1. eauto.\n      }\n      assert (depth q1 <= | k |) as Hdep.\n      {\n        erewrite Dlen. eapply deq_loop_depth. eapply s_deq_q;eauto.\n      }\n      specialize (tcfg_edge_destruct' Dsk1) as Dsk1.\n      destruct Dsk1 as [H|[H|[H|H]]].\n      all: destruct H as [Htag Hedge].\n      + rewrite <-Htag. eapply tag_eq1;eauto.\n      + destruct l1;[congruence|]. inv Htag.\n        setoid_rewrite <-tag_eq1 at 3. 2,3,4:eauto.\n        rewrite take_r_cons_drop;eauto.\n      + decide (loop_contains u1 q1).\n        * exfalso.\n          eapply no_back;eauto.\n          destruct D. inv_path Dpath1. eapply path_contains_back in H.\n          eapply in_map with (f:=fst) in H. cbn in H. cbn. eauto.\n        * setoid_rewrite <-tag_eq1 at 3. 2,3,4:eauto.\n          destruct k;[exfalso|].\n          {\n            cbn in *. eapply loop_contains_ledge in Hedge. eapply loop_contains_depth_lt in Hedge.\n            destruct D. cbn in Dlen. lia.\n          }\n          assert (depth q1 < depth u1) as Hlt.\n          {\n            eapply le_lt_or_eq in Hdep.\n            destruct Hdep.\n            - cbn in H. cbn in Htag. eapply u_len1 in D. rewrite Htag in D. cbn in D. lia.\n            - exfalso. eapply n. cbn in *. eapply u_len1 in D as Hlen. rewrite Htag in Hlen.\n              cbn in Hlen.\n              eapply deq_loop_head_loop_contains.\n              + eapply deq_loop_depth_eq. eapply r1_incl_head_q;eauto. 2:lia.\n                destruct D. inv_path Dpath1. eapply path_contains_back in H0.\n                eapply in_map with (f:=fst) in H0. cbn in *. eauto.\n              + eexists;eauto.\n          }\n          destruct l1;[cbn in *;congruence|]. inv Htag.\n          erewrite take_r_cons_replace;eauto.\n          eapply back_edge_eq_loop in Hedge. rewrite <-Hedge in Hlt. cbn in Hdep.\n          destruct D. cbn in Dlen. lia.\n      + setoid_rewrite <-tag_eq1 at 3. 2-4:eauto.\n        destruct k;[exfalso|].\n        * destruct D. cbn in Dlen. eapply depth_exit in Hedge. lia.\n        * cbn. cbn in Htag.\n          erewrite take_r_cons_drop.\n          -- subst. reflexivity.\n          -- eapply u_len1 in D as Hlen. subst k. rewrite Hlen. eapply deq_loop_depth.\n             eapply r1_incl_head_q;eauto.\n             destruct D. inv_path Dpath1. eapply path_contains_back in H.\n             eapply in_map with (f:=fst) in H. cbn in *. eauto.\n  Qed.\n\n  Lemma k_eq_j `(D : DiamondPaths)\n        (Hdeq : deq_loop q1 s)\n        (Hjle : j1 ⊴ j2)\n    : k = j1.\n  Proof.\n    rewrite <-take_r_geq at 1. eapply tag_eq_kj1;eauto. erewrite Dlen.\n    eapply deq_loop_depth. eauto.\n  Qed.\n\n  Section disj_eqdep.\n    Context `(C : redCFG).\n    Variables (s u1 u2 p1 p2 q1 q2 : Lab)\n              (k i l1 l2 j1 j2 : Tag)\n              (r1 r2 : list (Lab * Tag)).\n    Hypothesis (Hdeq : deq_loop q1 s).\n    Hypothesis (Hjle : j1 ⊴ j2).\n\n    Lemma lj_eq1 (D : DiamondPaths s u1 u2 p1 p2 q1 q2 k i l1 l2 j1 j2 ((q1,j1) :: r1) r2)\n      : l1 = j1 \\/ (l1 = 0 :: j1 /\\ loop_head u1).\n    Proof. (* Hjle needed *)\n      specialize (tcfg_edge_destruct' Dsk1) as Dsk1.\n      destruct Dsk1 as [Dsk1|[Dsk1|[Dsk1|Dsk1]]].\n      all: destruct Dsk1 as [Htag Hedge].\n      - left. rewrite Htag. eapply k_eq_j;eauto.\n      - right. rewrite Htag. split.\n        + f_equal. eapply k_eq_j;eauto.\n        + destruct Hedge. eauto.\n      - exfalso. eapply no_back;eauto;cycle 1.\n        + eapply loop_contains_ledge in Hedge. eapply Hdeq in Hedge. eauto.\n        + destruct D. inv_path Dpath1. eapply path_contains_back in H.\n          eapply in_map with (f:=fst) in H. unfold fst in H at 1. eauto.\n      - exfalso. destruct Hedge. eapply exit_not_deq in H;eauto.\n        eapply eq_loop_exiting in H. rewrite H. transitivity q1;eauto.\n        eapply r1_incl_head_q;eauto.\n        destruct D. inv_path Dpath1. eapply path_contains_back in H0.\n        eapply in_map with (f:=fst) in H0. unfold fst in H0 at 1. eauto.\n    Qed.\n\n    Lemma lj_eq2 (D : DiamondPaths s u1 u2 p1 p2 q1 q2 k i l1 l2 j1 j2 r1 ((q2,j2) :: r2))\n      : l2 = j1 \\/ (l2 = 0 :: j1 /\\ loop_head u2) \\/ loop_contains u2 q1.\n    Proof. (* Hjle needed *)\n      specialize (tcfg_edge_destruct' Dsk2) as Dsk2.\n      destruct Dsk2 as [Dsk1|[Dsk1|[Dsk1|Dsk1]]].\n      all: destruct Dsk1 as [Htag Hedge].\n      - left. rewrite Htag. eapply k_eq_j;eauto.\n      - right. left. rewrite Htag. split.\n        + f_equal. eapply k_eq_j;eauto.\n        + destruct Hedge. eauto.\n      - right. right. eapply loop_contains_ledge in Hedge. eapply Hdeq;eauto.\n      - exfalso. destruct Hedge. eapply exit_not_deq in H;eauto.\n        eapply eq_loop_exiting in H. rewrite H. transitivity q1;eauto.\n        eapply r2_incl_head_q;eauto.\n        destruct D. inv_path Dpath2. eapply path_contains_back in H0.\n        eapply in_map with (f:=fst) in H0. unfold fst in H0 at 1. eauto.\n    Qed.\n\n  End disj_eqdep.\n\n\nLemma no_back2 `(D : DiamondPaths)\n      (Htageq : j1 = j2)\n  : forall x : Lab, x ∈ (map fst r2) -> ~ loop_contains x q1.\nProof.\n  setoid_rewrite Dloop.\n  eapply no_back.\n  - eapply DiamondPaths_sym;eauto.\n  - subst. reflexivity.\nQed.\n\nLemma u1_deq_q `(D : DiamondPaths)\n      (Hnnil : r1 <> [])\n  : deq_loop u1 q1.\nProof.\n  eapply r1_incl_head_q;eauto.\n  destruct r1;[contradiction|].\n  destruct D.\n  inv_path Dpath1.\n  eapply path_contains_back in H.\n  fold (fst (u1,l1)).\n  eapply in_map;eauto.\nQed.\n\nLemma u2_deq_q `(D : DiamondPaths)\n      (Hnnil : r2 <> [])\n  : deq_loop u2 q1.\nProof.\n  rewrite Dloop.\n  eapply u1_deq_q;eauto using DiamondPaths_sym.\nQed.\n\nLemma diamond_teq `(C : redCFG)\n      (s u1 u2 p1 p2 q1 q2 : Lab) (k i l1 l2 j1 j2 : Tag) r1 r2\n      (Hdeq : deq_loop q1 s)\n      (Hjle : j1 ⊴ j2)\n      (D : DiamondPaths s u1 u2 p1 p2 q1 q2 k i l1 l2 j1 j2 ((q1,j1) :: r1) ((q2,j2) :: r2))\n  : TeqPaths u1 u2 q1 q2 l1 l2 j1 j2 (r1) (r2).\nProof.\n  copy D D'.\n  destruct D.\n  inv_path Dpath1. inv_path Dpath2.\n  econstructor; eauto using tl_eq, lj_eq1, lj_eq2, jj_len, j_len1.\n  eapply diamond_split in D'. do 4 eexists.\n  split_conj;eauto.\n  1,2: econstructor.\nQed.\n\nLemma diamond_qj_eq1 `(C : redCFG) s u1 u2 p1 p2 q1 q2 k i l1 l2 j1 j2 qj1 r1 r2\n      (D : DiamondPaths s u1 u2 p1 p2 q1 q2 k i l1 l2 j1 j2 (qj1 :: r1) r2)\n  : qj1 = (q1,j1).\nProof.\n  destruct D. cbn in Dqj1. auto.\nQed.\n\nLemma diamond_qj_eq2 `(C : redCFG) s u1 u2 p1 p2 q1 q2 k i l1 l2 j1 j2 qj2 r1 r2\n      (D : DiamondPaths s u1 u2 p1 p2 q1 q2 k i l1 l2 j1 j2 r1 (qj2 :: r2))\n  : qj2 = (q2,j2).\nProof.\n  destruct D. cbn in Dqj2. auto.\nQed.\n", "meta": {"author": "cdl-saarland", "repo": "uniana", "sha": "abef56560e9b1b2e8653f732b4c14a823125f212", "save_path": "github-repos/coq/cdl-saarland-uniana", "path": "github-repos/coq/cdl-saarland-uniana/uniana-abef56560e9b1b2e8653f732b4c14a823125f212/uniana/disj/DiamondIncl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.28486679816365085}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nFrom compcert Require Import Coqlib.\nFrom compcert Require Import Maps.\nFrom compcert Require Import AST.\nFrom compcert Require Import Values.\nFrom compcert Require Import Memory.\nFrom compcert Require Import Op.\nFrom compcert Require Import Registers.\nFrom compcert Require Import RTL.\n\n\n\nDefinition valnum := positive.\n\nInductive rhs : Type :=\n| Op: operation -> list valnum -> rhs\n| Load: memory_chunk -> addressing -> list valnum -> rhs.\n\nInductive equation : Type :=\n| Eq (v: valnum) (strict: bool) (r: rhs).\n\nDefinition eq_valnum: forall (x y: valnum), {x=y}+{x<>y} := peq.\n\nDefinition eq_list_valnum: forall (x y: list valnum), {x=y}+{x<>y} := list_eq_dec peq.\n\nDefinition eq_rhs (x y: rhs) : {x=y}+{x<>y}.\nProof. hammer_hook \"CSEdomain\" \"CSEdomain.eq_rhs\".\ngeneralize chunk_eq eq_operation eq_addressing eq_valnum eq_list_valnum.\ndecide equality.\nDefined.\n\n\n\nRecord numbering : Type := mknumbering {\nnum_next: valnum;\nnum_eqs: list equation;\nnum_reg: PTree.t valnum;\nnum_val: PMap.t (list reg)\n}.\n\nDefinition empty_numbering :=\n{| num_next := 1%positive;\nnum_eqs  := nil;\nnum_reg  := PTree.empty _;\nnum_val  := PMap.init nil |}.\n\n\n\nDefinition valnums_rhs (r: rhs): list valnum :=\nmatch r with\n| Op op vl => vl\n| Load chunk addr vl => vl\nend.\n\nDefinition wf_rhs (next: valnum) (r: rhs) : Prop :=\nforall v, In v (valnums_rhs r) -> Plt v next.\n\nDefinition wf_equation (next: valnum) (e: equation) : Prop :=\nmatch e with Eq l str r => Plt l next /\\ wf_rhs next r end.\n\nRecord wf_numbering (n: numbering) : Prop := {\nwf_num_eqs: forall e,\nIn e n.(num_eqs) -> wf_equation n.(num_next) e;\nwf_num_reg: forall r v,\nPTree.get r n.(num_reg) = Some v -> Plt v n.(num_next);\nwf_num_val: forall r v,\nIn r (PMap.get v n.(num_val)) -> PTree.get r n.(num_reg) = Some v\n}.\n\nHint Resolve wf_num_eqs wf_num_reg wf_num_val: cse.\n\n\n\nDefinition valuation := valnum -> val.\n\nInductive rhs_eval_to (valu: valuation) (ge: genv) (sp: val) (m: mem):\nrhs -> val -> Prop :=\n| op_eval_to: forall op vl v,\neval_operation ge sp op (map valu vl) m = Some v ->\nrhs_eval_to valu ge sp m (Op op vl) v\n| load_eval_to: forall chunk addr vl a v,\neval_addressing ge sp addr (map valu vl) = Some a ->\nMem.loadv chunk m a = Some v ->\nrhs_eval_to valu ge sp m (Load chunk addr vl) v.\n\nInductive equation_holds (valu: valuation) (ge: genv) (sp: val) (m: mem):\nequation -> Prop :=\n| eq_holds_strict: forall l r,\nrhs_eval_to valu ge sp m r (valu l) ->\nequation_holds valu ge sp m (Eq l true r)\n| eq_holds_lessdef: forall l r v,\nrhs_eval_to valu ge sp m r v -> Val.lessdef v (valu l) ->\nequation_holds valu ge sp m (Eq l false r).\n\nRecord numbering_holds (valu: valuation) (ge: genv) (sp: val)\n(rs: regset) (m: mem) (n: numbering) : Prop := {\nnum_holds_wf:\nwf_numbering n;\nnum_holds_eq: forall eq,\nIn eq n.(num_eqs) -> equation_holds valu ge sp m eq;\nnum_holds_reg: forall r v,\nn.(num_reg)!r = Some v -> rs#r = valu v\n}.\n\nHint Resolve num_holds_wf num_holds_eq num_holds_reg: cse.\n\nLemma empty_numbering_holds:\nforall valu ge sp rs m,\nnumbering_holds valu ge sp rs m empty_numbering.\nProof. hammer_hook \"CSEdomain\" \"CSEdomain.empty_numbering_holds\".\nintros; split; simpl; intros.\n- split; simpl; intros.\n+ contradiction.\n+ rewrite PTree.gempty in H; discriminate.\n+ rewrite PMap.gi in H; contradiction.\n- contradiction.\n- rewrite PTree.gempty in H; discriminate.\nQed.\n\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/CSEdomain.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.28486679816365085}}
{"text": "Require Export Qual.metalib.\nRequire Export Qual.grade. \nRequire Export Qual.geq.\n\nSet Implicit Arguments.\nOpen Scope grade_scope.\n\n\nLemma CDefEq_DefEq_Grade : \n  (forall P psi phi a b, CDefEq P psi phi a b -> CGrade P psi phi a /\\ CGrade P psi phi b) /\\\n  (forall P psi a b, DefEq P psi a b -> Grade P psi a /\\ Grade P psi b).\nProof.\n  apply CDefEq_DefEq_mutual.\n  all: intros; split; split_hyp; eauto.\n  all: try solve [eauto using leq_join_r ].\n  all: try solve [repeat invert_Grade; subst; eauto].\n  all: try solve [fresh_apply_Grade x; auto;\n    repeat spec x; split_hyp; eauto].\n  all: try solve [repeat invert_Grade; subst;\n    pick fresh x; repeat spec x;\n    eapply Grade_open; eauto using leq_join_r].\n\n  all: try solve [pick fresh x;\n  repeat spec x;\n  split_hyp;\n  eapply Grade_open_irrel with (y := x); eauto].\n\nQed.\n\nLemma DefEq_Grade : forall P psi a b, DefEq P psi a b -> Grade P psi a /\\ Grade P psi b.\nProof. apply  CDefEq_DefEq_Grade. Qed.\n\nLemma DefEq_Grade1 : forall {W psi a b}, DefEq W psi a b -> Grade W psi a. \neapply DefEq_Grade; auto. Qed.\nLemma DefEq_Grade2 : forall {W psi a b}, DefEq W psi a b -> Grade W psi b. \neapply DefEq_Grade; auto. Qed.\n\n\nLemma CEqGEq_DefEq : \n  (forall P phi phi0 a b, CEq P phi phi0 a b -> CDefEq P phi phi0 a b) /\\\n  (forall P phi a b, GEq P phi a b -> DefEq P phi a b).\nProof. \n  eapply CEq_GEq_mutual.\n  all: intros; eauto 3.\nQed.\n\n\nLemma CDefEq_substitution1 : forall P2 x psi0 P1 psi a a1 a2, \n  Grade (P2 ++ [(x, psi0)] ++ P1) psi a -> \n  CDefEq P1 psi psi0 a1 a2 -> \n  Grade (P2 ++ P1) psi (subst_tm_tm a1 x a).\nProof. \n  intros.\n  inversion H0; subst.\n  eapply Grade_substitution_same; eauto using DefEq_Grade1.\n  eapply Grade_substitution_irrel; eauto using DefEq_lc1.\nQed.\n\nLemma CDefEq_substitution2 : forall P2 x psi0 P1 psi a a1 a2, \n  Grade (P2 ++ [(x, psi0)] ++ P1) psi a -> \n  CDefEq P1 psi psi0 a1 a2 -> \n  Grade (P2 ++ P1) psi (subst_tm_tm a2 x a).\nProof. \n  intros.\n  inversion H0; subst.\n  eapply Grade_substitution_same; eauto using DefEq_Grade2.\n  eapply Grade_substitution_irrel; eauto using DefEq_lc2.\nQed.\n\nParameter star : sort.\n\nLemma DefEq_equality_substitution : (forall P phi b1 b2,\n  DefEq P phi b1 b2 -> forall P1 x psi, \n        P = [(x,psi)] ++ P1 \n       -> forall a1 a2, DefEq P1 phi a1 a2  \n       -> psi <= phi\n       -> DefEq P1 phi (subst_tm_tm a1 x b1) (subst_tm_tm a2 x b2)). \nProof. \n  intros.\n  subst.\n  move: (DefEq_uniq H) => h. destruct_uniq.\n  have RE: DefEq P1 phi (a_Pi psi (a_Type star) (close_tm_wrt_tm x b1))\n                        (a_Pi psi (a_Type star) (close_tm_wrt_tm x b2)).\n  + pick fresh y and apply Eq_Pi. eapply Eq_Refl; eauto.\n    rewrite <- subst_tm_tm_spec.\n    rewrite <- subst_tm_tm_spec.\n    eapply DefEq_substitution_same with (P2 := nil) (P1 := [(y,phi)] ++ P1).\n    2: { simpl_env; eauto. }\n    eapply DefEq_weakening_middle; eauto.\n    eapply G_Var with (psi0:=phi); auto. reflexivity.\n  + rewrite subst_tm_tm_spec.\n    rewrite subst_tm_tm_spec.\n    eapply Eq_PiSnd; eauto.\nQed.\n\nLemma DefEq_substitution_irrel2 : (forall P phi b1 b2,\n  DefEq P phi b1 b2 -> forall P1 x psi, \n        P = [(x,psi)] ++ P1 \n       -> not (psi <= phi)\n       -> forall a1 a2, lc_tm a1 -> lc_tm a2\n       -> DefEq P1 phi (subst_tm_tm a1 x b1) (subst_tm_tm a2 x b2)). \nProof.\n  intros. subst.\n  move: (DefEq_uniq H) => u. destruct_uniq.\n  rewrite subst_tm_tm_spec.\n  rewrite subst_tm_tm_spec.\n  pick fresh y and apply Eq_SubstIrrel; eauto 2.\n  eapply (@DefEq_renaming x). repeat rewrite fv_tm_tm_close_tm_wrt_tm. fsetdec.\n  repeat rewrite fv_tm_tm_close_tm_wrt_tm. fsetdec.\n  rewrite open_tm_wrt_tm_close_tm_wrt_tm.\n  rewrite open_tm_wrt_tm_close_tm_wrt_tm.\n  auto.\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/DDC/src/defeq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.28486679150201294}}
{"text": "From Coq Require Import List FinFun.\n\nFrom CasperCBC\n  Require Import\n    Lib.Preamble\n    Lib.Traces\n    Lib.Measurable\n    VLSM.Common\n    VLSM.Decisions\n    VLSM.Composition\n    VLSM.Equivocation. (* for has_been_sent *)\n\n(** * VLSM Liveness *)\n\n(**\n A composite VLSM is live if every complete trace reaches a [decision].\n*)\n\n(**\n   This module defines liveness, and contains basic defintiions\n   that will be used for proving liveness properties,\n   constructing protocols designed for liveness, and\n   stating the assumptions under which those protocols are live.\n *)\n\n(** ** Liveness definitions *)\n\nSection Liveness.\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\nDefinition live : Prop :=\n  forall\n    (tr : Trace)\n    (Htr: complete_trace_prop X tr),\n  exists\n    (n : nat)\n    (i : index)\n    (st : vstate X),\n    trace_nth tr n = (Some st)\n    /\\ (ID i) (st i) <> None.\n\nEnd Liveness.\n\n(** ** Clocks\n\nLiveness always requires some notion of time, and assumptions\nthat messages are not infinitely delayed.\n\nWe will use logical clocks that assign states and\nmessages to times in [nat], with messages carrying the\ntime from the sending component, and messages only\nexpected to be received by a node at the matching time.\n *)\n\nSection Clocks.\n\n  (** A clock for a VLSM assigns a time to any state, and is\n      nondecreasing on transitions.\n   *)\n  Record ClockFor `(X:VLSM message) : Type := {\n    clock : vstate X -> nat;\n    clock_monotone : forall l s om s' om',\n        vtransition X l (s,om) = (s',om') -> clock s <= clock s';\n    }.\n\n  (** For a composite VLSM we usually want to have a separate\n      clock for each component\n   *)\n  Definition ClocksFor `(IM:index -> VLSM message) : Type :=\n    forall i, ClockFor (IM i).\n\n  (** A message time function is consistent with a\n      set of clocks for a composite VLSM if\n      the message time always agrees with the time\n      of the sending component at the begining of\n      the transition where the message is sent.\n   *)\n  Record MessageTimeProp\n        `(IM: index -> VLSM message) `{EqDecision index} `{Inhabited index} constraint\n        (X := composite_vlsm IM constraint)\n        (clocks : ClocksFor IM)\n        (message_time : message -> nat)\n    : Type := {\n    message_time_accurate :\n      forall m t,\n        message_time m = t\n        <-> (forall (l:vlabel X) s om l s',\n             vtransition X l (s,om) = (s', Some m) -> clock _ (clocks _) (s (projT1 l)) = t)\n             }.\n\nEnd Clocks.\n\n(** ** Plans\n\nProtocols may be designed so that only a subset of validators\nare expected to send messages in each phase.\n\nOur example protocol will use a fixed that specifies the\nexpected set of senders for each time.\nHere we define the conditions that such a fixed plan will\nneed to satisfy.\n\nLater protocols will dyanmically construct plans to\nreact to failures, and we will need to generalize\nthese properties to apply to dynamic plans.\n *)\nSection Plan.\n  Context\n    (index: Type)\n    {Hweights: Measurable index}\n    {index_listing: list index}\n    {Hfinite: FinFun.Listing index_listing}\n  .\n\n  (** An \"odd\" set cannot be partitioned into\n      two disjoint pieces with equal weight,\n      so votes cannot have ties *)\n  Definition odd_set (P: index -> Prop) : Prop :=\n    forall l1 l2,\n      (forall i, P i <-> (In i l1 \\/ In i l2)) ->\n      NoDup (l1++l2) ->\n      sum_weights l1 <> sum_weights l2.\n\n  Record Plan (plan: nat -> index -> Prop) := {\n    stages_nonempty : forall n, ~forall v, ~plan n v;\n    plan_has_odd_stage: exists n, odd_set (plan n);\n    recurring_sends: forall n v, exists n', n' > n /\\ plan n' v;\n    }.\nEnd Plan.\n\n(** ** Synchrony Constraints\n\nSynchrony assumptions will be expresed with composition constraints.\n\nCurrently we define only a strong assumption that doesn't allow\nany messages to be delayed, which will be used for example proofs of\nliveness.\n\nDefinitions allowing a limited rate of \"synchronization faults\" will\nbe added before verifying more robust protocols over more realistic\nassumptions.\n *)\nSection StrongSynchrony.\n  Context\n    {message : Type}\n    {index : Type}\n    {index_listing : list index}\n    (finite_index : Listing index_listing)\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    {Hsents : forall i, has_been_sent_capability (IM i)}\n    {Hobserveds: forall i, has_been_observed_capability (IM i)}\n    (clocks : ClocksFor IM)\n    (message_time : message -> nat)\n  .\n\n  (** This portion of a constraint ensures that messages are received only\n      by components at the proper time.\n\n      Perhaps this condition should be added to [MessageTimeProp] and\n      required as a property of the components in [IM] rather than\n      imposed as a composition constraint.\n   *)\n  Definition delivery_time_constraint :\n    composite_label IM -> composite_state IM * option message -> Prop\n    := fun l som =>\n         let (i,_) := l in\n         let (s,om) := som in\n         match om with\n         | Some m => message_time m = clock _ (clocks i) (s i)\n         | None => True\n         end.\n\n  Definition all_earlier_messages_received (i:index) (s:composite_state IM) : Prop :=\n    forall msg, (exists (j:index), has_been_sent (IM j) (s j) msg) ->\n                message_time msg <= clock _ (clocks i) (s i) ->\n                has_been_observed (IM i) (s i) msg.\n\n  (** This portion of a constraint prevents a component from advancing its clock\n      if it has not received all oustanding messages from the time\n      it is leaving.\n\n      N.B. As written, this does not prevent the possiblity that some\n      other component which is still in the earlier time hasn't even\n      sent a message yet. Combined with the use of [lt] in\n      [all_earlier_messages_received], and the [delivery_time_constraint],\n      this component would never be able to advance its clock again\n      after such a \"late send\".\n   *)\n  Definition timely_reception_constraint:\n    composite_label IM -> composite_state IM * option message -> Prop\n    := fun l som =>\n         let (i,l_i) := l in\n         let (s,om) := som in\n         let (s',_) := vtransition (IM i) l_i (s i,om) in\n         clock _ (clocks i) (s i) < clock _ (clocks i) s'\n         -> all_earlier_messages_received i s.\n\n  Context\n    (Free := free_composite_vlsm IM)\n    (composite_has_been_sent_capability : has_been_sent_capability Free := composite_has_been_sent_capability IM (free_constraint IM) finite_index Hsents)\n    .\n\n  Existing Instance composite_has_been_sent_capability.\n\n  (** This strong constraint allows no equivocations and\n      no failures of synchrony.\n   *)\n  Definition no_synch_faults_no_equivocation_constraint :\n    composite_label IM -> composite_state IM * option message -> Prop\n    := fun l som =>\n         no_equivocations Free l som\n         /\\ delivery_time_constraint l som\n         /\\ timely_reception_constraint l som.\n\nEnd StrongSynchrony.\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.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2848296808270126}}
{"text": "(** * Mutable map whose lookup operation provides a default value.*)\n\n(* begin hide *)\nSet Implicit Arguments.\nSet Contextual Implicit.\n\nFrom Coq Require Import\n     Morphisms\n     Setoid\n     RelationClasses.\n\nFrom ExtLib Require Import\n     Core.RelDec.\n\nFrom ExtLib.Structures Require\n     Functor Monoid Maps.\n\nFrom Paco Require Import paco.\n\nFrom ITree Require Import\n     ITreeDefinition\n     Basics.Basics\n     Basics.Tacs\n     Basics.CategoryOps\n     Basics.HeterogeneousRelations\n     Eq.Eq\n     Eq.UpToTaus\n     Eq.Paco2\n     Indexed.Sum\n     Interp.Interp\n     Interp.InterpFacts\n     Events.State\n     Events.MapDefault Core.Subevent.\n\n\nImport ITree.Basics.Basics.Monads.\nImport Structures.Maps.\n(* end hide *)\n\nSection MapFacts.\n\n  Variables (K V : Type).\n  Context {map : Type}.\n  Context {M : Map K V map}.\n  Context {MOk: MapOk eq M}.\n  Context {Kdec: @RelDec K eq}.\n  Context {KdecOk: RelDec_Correct Kdec}.\n\n  (* Should move to extlib *)\n  Lemma lookup_add_eq: forall k v s, lookup k (add k v s) = Some v.\n  Proof.\n    intros.\n    rewrite mapsto_lookup; apply mapsto_add_eq.\n    Unshelve.\n    2: typeclasses eauto.\n  Qed.\n\n  (* Should move to extlib *)\n  Lemma lookup_add_neq: forall k k' v s, k' <> k -> lookup k (add k' v s) = lookup k s.\n  Proof.\n    intros.\n    generalize (@mapsto_add_neq _ _ _ eq _ _ s k' v k H); clear H; intros H.\n    setoid_rewrite <- mapsto_lookup in H.\n    destruct (lookup k s) as [v' |] eqn:EQ.\n    - specialize (H v').\n      apply H; auto.\n    - destruct (lookup k (add k' v s)) as [v' |] eqn:EQ'; [| reflexivity].\n      specialize (H v').\n      symmetry; apply H; auto.\n  Qed.\n\n  (* Should move to extlib *)\n  Lemma lookup_remove_eq:\n    forall k s, lookup k (remove k s) = None.\n  Proof.\n    intros.\n    match goal with\n      |- ?x = _ => destruct x eqn:EQ\n    end; [| reflexivity].\n    rewrite mapsto_lookup in EQ.\n    exfalso; eapply mapsto_remove_eq; eauto.\n  Qed.\n\n  (* Should move to extlib *)\n  Lemma lookup_remove_neq:\n    forall k k' s, k <> k' -> lookup k (remove k' s) = lookup k s.\n  Proof.\n    intros.\n    match goal with\n      |- ?x = _ => destruct x eqn:EQ\n    end.\n    - rewrite mapsto_lookup in EQ.\n      apply mapsto_remove_neq in EQ; auto.\n      symmetry; rewrite mapsto_lookup; eauto.\n    -  match goal with\n         |- _ = ?x => destruct x eqn:EQ'\n       end; auto.\n       rewrite mapsto_lookup in EQ'.\n       eapply mapsto_remove_neq in EQ'; eauto.\n       rewrite <- mapsto_lookup in EQ'.\n       rewrite EQ in EQ'; inv EQ'.\n       Unshelve.\n       all: typeclasses eauto.\n  Qed.\n\n  Global Instance eq_map_refl {d} : Reflexive (@eq_map _ _ _ _ d).\n  Proof.\n    red. intros. unfold eq_map. tauto.\n  Qed.\n\n  Global Instance eq_map_sym {d} : Symmetric (@eq_map _ _ _ _ d).\n  Proof.\n    repeat intro.\n    unfold eq_map in H.\n    rewrite H.\n    reflexivity.\n  Qed.\n\n  Global Instance eq_map_trans {d} : Transitive (@eq_map _ _ _ _ d).\n  Proof.\n    repeat intro.\n    unfold eq_map in *.\n    rewrite H. rewrite H0. reflexivity.\n  Qed.\n\n\n  Section Relations.\n  Context {R1 R2 : Type}.\n  Variable RR : R1 -> R2 -> Prop.\n\n  Definition map_default_eq d {E}\n    : (stateT map (itree E) R1) -> (stateT map (itree E) R2) -> Prop :=\n    fun t1 t2 => forall s1 s2, (@eq_map _ _ _ _ d) s1 s2 -> eutt (prod_rel (@eq_map _ _ _ _ d) RR) (t1 s1) (t2 s2).\n\n  End Relations.\n\n  Lemma eq_map_add:\n    forall (d : V) (s1 s2 : map) (k : K) (v : V), (@eq_map _ _ _ _ d) s1 s2 -> (@eq_map _ _ _ _ d) (add k v s1) (add k v s2).\n  Proof.\n    intros d s1 s2 k v H.\n    unfold eq_map in *.\n    intros k'.\n    destruct (rel_dec_p k k').\n    - subst.\n      unfold lookup_default in *.\n      rewrite 2 lookup_add_eq; reflexivity.\n    - unfold lookup_default in *.\n      rewrite 2 lookup_add_neq; auto.\n  Qed.\n\n  Lemma eq_map_remove:\n    forall (d : V) (s1 s2 : map) (k : K), (@eq_map _ _ _ _ d) s1 s2 -> (@eq_map _ _ _ _ d) (remove k s1) (remove k s2).\n  Proof.\n    intros d s1 s2 k H.\n    unfold eq_map in *; intros k'.\n    unfold lookup_default.\n    destruct (rel_dec_p k k').\n    - subst; rewrite 2 lookup_remove_eq; auto.\n    - rewrite 2 lookup_remove_neq; auto.\n      apply H.\n  Qed.\n\n  Lemma handle_map_eq :\n    forall d E X (s1 s2 : map) (m : mapE K d X),\n      (@eq_map _ _ _ _ d) s1 s2 ->\n      eutt (prod_rel (@eq_map _ _ _ _ d) eq) (handle_map m s1) ((handle_map m s2) : itree E (map * X)).\n  Proof.\n    intros.\n    destruct m; cbn; red; apply eqit_Ret; constructor; auto.\n    - apply eq_map_add. assumption.\n    - apply eq_map_remove. assumption.\n  Qed.\n\n\n  Global Instance Proper_handle_map {E R}  d :\n    Proper (eq ==> map_default_eq eq d) (@handle_map _ _ _ _ E d R).\n  Proof.\n    repeat intro.\n    subst.\n    apply handle_map_eq.\n    assumption.\n  Qed.\n\n  (* (* This lemma states that the operations provided by [handle_map] respect *)\n  (*    the equivalence on the underlying map interface *)\n  (*       Lemma interp_map_id d {E X} (t : itree (mapE K d +' E) X) : *)\n  (*  *) *)\n  (* Lemma interp_map_id d {E F X} {SE:mapE K d +? E -< F} (t : itree F X) : *)\n  (*   map_default_eq eq d (interp_map (d := d) t) (interp_map (d := d)t). *)\n  (* Proof. *)\n  (*   unfold map_default_eq, interp_map; intros. *)\n  (*   revert t s1 s2 H. *)\n  (*   einit. *)\n  (*   ecofix CH. *)\n  (*   intros. *)\n  (*   repeat rewrite unfold_interp_state. unfold _interp_state. *)\n  (*   destruct (observe t). *)\n  (*   - estep. *)\n  (*   - estep. *)\n  (*   - ebind. econstructor. *)\n  (*     (* YZ. First case relates trees made of calls to over applied to the same event *) *)\n  (*     + unfold over. destruct (case e). *)\n  (*       * apply handle_map_eq; assumption. *)\n  (*       (* YZ: Hence in this case we relate two trees defined as triggers *) *)\n  (*       * unfold trigger, Trigger_MonadT, trigger, Trigger_ITree, ITree.trigger. *)\n  (*         cbn. rewrite 2 bind_vis. apply eqit_Vis. *)\n  (*         intros. rewrite 2 bind_ret_l.  apply eqit_Ret. constructor; auto. *)\n  (*     (* We get away with it by unfolding the instances though *) *)\n  (*     + intros. destruct u1. destruct u2. cbn. *)\n  (*       inversion H. subst. *)\n  (*       estep. *)\n  (* Qed. *)\n\n  (* Global Instance interp_map_proper {R E F d} {SE:mapE K d +? F -< E} {RR : R -> R -> Prop} : *)\n  (*   Proper ((eutt RR) ==> (@map_default_eq _ _ RR d F)) (@interp_map _ _ _ _ E d _ _ R). *)\n  (* Proof. *)\n  (*   unfold map_default_eq, interp_map. *)\n  (*   repeat intro. *)\n  (*   revert x y H s1 s2 H0. *)\n  (*   einit. *)\n  (*   ecofix CH. *)\n  (*   intros. *)\n  (*   rewrite! unfold_interp_state. *)\n  (*   punfold H0. red in H0. *)\n  (*   revert s1 s2 H1. *)\n  (*   induction H0; intros; subst; simpl; pclearbot. *)\n  (*   - eret.  *)\n  (*   - etau. *)\n  (*   - ebind. *)\n  (*     apply pbc_intro_h with (RU := prod_rel (@eq_map _ _ _ _ d) eq). *)\n  (*     { (* SAZ: I must be missing some lemma that should solve this case *) *)\n  (*       unfold over. *)\n  (*       destruct (case e). *)\n  (*       - apply handle_map_eq. assumption. *)\n  (*       - unfold trigger, Trigger_MonadT, trigger, Trigger_ITree, ITree.trigger. *)\n  (*         pstep. cbn. red. cbn. (* YZ: this is ugly... A better way? *) *)\n  (*         econstructor. intros. constructor. pfold. *)\n  (*         red; cbn. *)\n  (*         econstructor. constructor; auto. *)\n  (*     } *)\n  (*     intros. *)\n  (*     inversion H. subst. *)\n  (*     estep; constructor. ebase. *)\n  (*   - rewrite tau_euttge, unfold_interp_state. *)\n  (*     eauto. *)\n  (*   - rewrite tau_euttge, unfold_interp_state. *)\n  (*     eauto. *)\n  (* Qed. *)\n\nEnd MapFacts.\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/MapDefaultFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.28476366446907925}}
{"text": "From iris.proofmode Require Import tactics.\nFrom iris.program_logic Require Export weakestpre.\nFrom F_mu_ref_conc_sub Require Export rules typing.\nFrom iris.algebra Require Import list.\nFrom iris.base_logic Require Import invariants.\nImport uPred.\n\nDefinition logN : namespace := nroot .@ \"logN\".\n\n(** interp : is a unary logical relation. *)\nSection logrel.\n  Context `{heapIG Σ}.\n  Notation D := (valO F_mu_ref_conc_lang -n> iProp Σ).\n  Implicit Types τi : D.\n  Implicit Types Δ : listO D.\n  Implicit Types interp : listO D → D.\n\n  Program Definition env_lookup (x : var) : listO D -n> D := λne Δ,\n    from_option id (cconst False)%I (Δ !! x).\n  Solve Obligations with solve_proper.\n\n  Definition interp_top : listO D -n> D := λne Δ w, True%I.\n\n  Program Definition interp_unit : listO D -n> D := λne Δ w, ⌜w = UnitV⌝%I.\n  Program Definition interp_nat : listO D -n> D := λne Δ w, ⌜∃ n, w = #nv n⌝%I.\n  Program Definition interp_bool : listO D -n> D := λne Δ w, ⌜∃ n, w = #♭v n⌝%I.\n\n  Program Definition interp_prod\n      (interp1 interp2 : listO D -n> D) : listO D -n> D := λne Δ w,\n    (∃ w1 w2, ⌜w = PairV w1 w2⌝ ∧ interp1 Δ w1 ∧ interp2 Δ w2)%I.\n  Solve Obligations with repeat intros ?; simpl; solve_proper.\n\n  Program Definition interp_sum\n      (interp1 interp2 : listO D -n> D) : listO D -n> D := λne Δ w,\n    ((∃ w1, ⌜w = InjLV w1⌝ ∧ interp1 Δ w1) ∨ (∃ w2, ⌜w = InjRV w2⌝ ∧ interp2 Δ w2))%I.\n  Solve Obligations with repeat intros ?; simpl; solve_proper.\n\n  Program Definition interp_arrow\n      (interp1 interp2 : listO D -n> D) : listO D -n> D := λne Δ w,\n    (□ ∀ v, interp1 Δ v → WP App (of_val w) (of_val v) {{ interp2 Δ }})%I.\n  Solve Obligations with repeat intros ?; simpl; solve_proper.\n\n  Program Definition interp_forall\n      (interp_bound interp : listO D -n> D) : listO D -n> D := λne Δ w,\n    (□ ∀ τi : D,\n      ⌜∀ v, Persistent (τi v)⌝ → □ (∀ v, τi v -∗ interp_bound Δ v) → WP TApp (of_val w) {{ interp (τi :: Δ) }})%I.\n  Solve Obligations with repeat intros ?; simpl; solve_proper.\n\n  Program Definition interp_rec1\n      (interp : listO D -n> D) (Δ : listO D) (τi : D) : D := λne w,\n    (□ (∃ v, ⌜w = FoldV v⌝ ∧ ▷ interp (τi :: Δ) v))%I.\n\n  Global Instance interp_rec1_contractive\n    (interp : listO D -n> D) (Δ : listO D) : Contractive (interp_rec1 interp Δ).\n  Proof. by solve_contractive. Qed.\n\n  Lemma fixpoint_interp_rec1_eq (interp : listO D -n> D) Δ x :\n    fixpoint (interp_rec1 interp Δ) x ≡ interp_rec1 interp Δ (fixpoint (interp_rec1 interp Δ)) x.\n  Proof. exact: (fixpoint_unfold (interp_rec1 interp Δ) x). Qed.\n\n  Program Definition interp_rec (interp : listO D -n> D) : listO D -n> D := λne Δ,\n    fixpoint (interp_rec1 interp Δ).\n  Next Obligation.\n    intros interp n Δ1 Δ2 HΔ; apply fixpoint_ne => τi w. solve_proper.\n  Qed.\n\n  Program Definition interp_ref_inv (l : loc) : D -n> iProp Σ := λne τi,\n    (∃ v, l ↦ᵢ v ∗ τi v)%I.\n  Solve Obligations with solve_proper.\n\n  Program Definition interp_ref\n      (interp : listO D -n> D) : listO D -n> D := λne Δ w,\n    (∃ l, ⌜w = LocV l⌝ ∧ inv (logN .@ l) (interp_ref_inv l (interp Δ)))%I.\n  Solve Obligations with solve_proper.\n\n  Fixpoint interp (τ : type) : listO D -n> D :=\n    match τ return _ with\n    | Top => interp_top\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 => env_lookup x\n    | TForall σ τ' => interp_forall (interp σ) (interp τ')\n    | TRec τ' => interp_rec (interp τ')\n    | Tref τ' => interp_ref (interp τ')\n    end.\n  Notation \"⟦ τ ⟧\" := (interp τ).\n\n  Definition interp_env (Γ : list type)\n      (Δ : listO D) (vs : list val) : iProp Σ :=\n    (⌜length Γ = length vs⌝ ∗ [∗] zip_with (λ τ, ⟦ τ ⟧ Δ) Γ vs)%I.\n  Notation \"⟦ Γ ⟧*\" := (interp_env Γ).\n\n  Definition interp_expr (τ : type) (Δ : listO D) (e : expr) :\n    iProp Σ := WP e {{ ⟦ τ ⟧ Δ }}%I.\n\n  Class env_Persistent Δ :=\n    env_persistent : Forall (λ τi, ∀ v, Persistent (τi v)) Δ.\n  Global Instance env_persistent_nil : env_Persistent [].\n  Proof. by constructor. Qed.\n  Global Instance env_persistent_cons τi Δ :\n    (∀ v, Persistent (τi v)) → env_Persistent Δ → env_Persistent (τi :: Δ).\n  Proof. by constructor. Qed.\n  Global Instance env_persistent_lookup Δ x v :\n    env_Persistent Δ → Persistent (env_lookup x Δ v).\n  Proof. intros HΔ; revert x; induction HΔ=>-[|?] /=; apply _. Qed.\n  Global Instance interp_persistent τ Δ v :\n    env_Persistent Δ → Persistent (interp τ Δ v).\n  Proof.\n    revert v Δ; induction τ=> v Δ HΔ; simpl; try apply _.\n    rewrite /Persistent fixpoint_interp_rec1_eq /interp_rec1 /= intuitionistically_into_persistently.\n    by apply persistently_intro'.\n  Qed.\n  Global Instance interp_env_base_persistent Δ Γ vs :\n  env_Persistent Δ → TCForall Persistent (zip_with (λ τ, ⟦ τ ⟧ Δ) Γ vs).\n  Proof.\n    intros HΔ. revert vs.\n    induction Γ => vs; simpl; destruct vs; constructor; apply _.\n  Qed.\n  Global Instance interp_env_persistent Γ Δ vs :\n    env_Persistent Δ → Persistent (⟦ Γ ⟧* Δ vs) := _.\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 w; simpl; properness; auto. by apply IHτ1. by apply IHτ2.\n    - intros w; simpl; properness; auto. by apply IHτ1. by apply IHτ2.\n    - intros w; simpl; properness; auto. by apply IHτ1. by apply IHτ2.\n    - apply fixpoint_proper=> τi w /=.\n      properness; auto. apply (IHτ (_ :: _)).\n    - rewrite iter_up; destruct lt_dec as [Hl | Hl]; simpl.\n      { by rewrite !lookup_app_l. }\n      (* FIXME: Ideally we wouldn't have to do this kinf of surgery. *)\n      change (bi_ofeO (uPredI (iResUR Σ))) with (uPredO (iResUR Σ)).\n      rewrite !lookup_app_r; [|lia ..]. do 2 f_equiv. lia.\n    - intros w; simpl; properness; auto. by apply IHτ.\n      by apply (IHτ0 (_ :: _)).\n    - intros w; 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 w; simpl; properness; auto. by apply IHτ1. by apply IHτ2.\n    - intros w; simpl; properness; auto. by apply IHτ1. by apply IHτ2.\n    - intros w; simpl; properness; auto. by apply IHτ1. by apply IHτ2.\n    - apply fixpoint_proper=> τi w /=.\n      properness; auto. apply (IHτ (_ :: _)).\n    - rewrite iter_up; destruct lt_dec as [Hl | Hl]; simpl.\n      { by rewrite !lookup_app_l. }\n      (* FIXME: Ideally we wouldn't have to do this kinf of surgery. *)\n      change (bi_ofeO (uPredI (iResUR Σ))) with (uPredO (iResUR Σ)).\n      rewrite !lookup_app_r; [|lia ..].\n      case EQ: (x - length Δ1) => [|n]; simpl.\n      { symmetry. asimpl. by rewrite (interp_weaken [] Δ1 Δ2 τ') . }\n      change (bi_ofeO (uPredI (iResUR Σ))) with (uPredO (iResUR Σ)).\n      rewrite !lookup_app_r; [|lia ..]. do 2 f_equiv. lia.\n    - intros w; simpl; properness; auto. by apply IHτ. apply (IHτ0 (_ :: _)).\n    - intros w; simpl; properness; auto. by apply IHτ.\n  Qed.\n\n  Lemma interp_subst Δ2 τ τ' v :\n    ⟦ τ ⟧ (⟦ τ' ⟧ Δ2 :: Δ2) v ≡ ⟦ τ.[τ'/] ⟧ Δ2 v.\n  Proof. apply (interp_subst_up []). Qed.\n\n  Lemma interp_env_length Δ Γ vs : ⟦ Γ ⟧* Δ vs ⊢ ⌜length Γ = length vs⌝.\n  Proof. by iIntros \"[% ?]\". Qed.\n\n  Lemma interp_env_Some_l Δ Γ vs x τ :\n    Γ !! x = Some τ → ⟦ Γ ⟧* Δ vs ⊢ ∃ v, ⌜vs !! x = Some v⌝ ∧ ⟦ τ ⟧ Δ v.\n  Proof.\n    iIntros (?) \"[Hlen HΓ]\"; iDestruct \"Hlen\" as %Hlen.\n    destruct (lookup_lt_is_Some_2 vs x) as [v Hv].\n    { by rewrite -Hlen; apply lookup_lt_Some with τ. }\n    iExists v; iSplit. done. iApply (big_sepL_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 Δ : ⟦ [] ⟧* Δ [].\n  Proof. iSplit; simpl; auto. Qed.\n  Lemma interp_env_cons Δ Γ vs τ v :\n    ⟦τ :: Γ ⟧* Δ (v :: vs) ⊣⊢ ⟦ τ ⟧ Δ v ∗ ⟦ Γ ⟧* Δ vs.\n  Proof.\n    rewrite /interp_env /= (assoc _ (⟦ _ ⟧ _ _)) -(comm _ ⌜(_ = _)⌝%I) -assoc.\n    by apply sep_proper; [apply pure_proper; lia|].\n  Qed.\n\n  Lemma interp_env_ren Δ (Γ : list type) (vs : list val) τi :\n    ⟦ subst (ren (+1)) <$> Γ ⟧* (τi :: Δ) vs ⊣⊢ ⟦ Γ ⟧* Δ vs.\n  Proof.\n    apply sep_proper; [apply pure_proper; by rewrite fmap_length|].\n    revert Δ vs τi; induction Γ=> Δ [|v vs] τi; csimpl; auto.\n    apply sep_proper; auto. apply (interp_weaken [] [τi] Δ).\n  Qed.\n\n  Definition interp_Tenv (Δ : listO D) (Ξ : list type) : iProp Σ:=\n    (⌜length Δ = length Ξ⌝ ∧ ∀ x τ, ⌜Ξ !! x = Some τ⌝ →\n                                    □ (∀ v, env_lookup x Δ v -∗ interp τ Δ v))%I.\n\n  Lemma interp_Tenv_weaken Δ Ξ τ τi :\n    □ (∀ v, τi v -∗ interp τ Δ v) ∧ interp_Tenv Δ Ξ\n    ⊣⊢ interp_Tenv (τi :: Δ) (τ.[ren (+1)] :: (subst (ren (+1)) <$> Ξ)).\n  Proof.\n    iSplit.\n    - iIntros \"#[Hτ [Hlen HΞ]]\". iDestruct \"Hlen\" as %Hlen.\n      iSplit.\n      { rewrite /= fmap_length; auto. }\n      iIntros (x σ Hσ) \"!#\". iIntros (v) \"Hv\".\n      destruct x; simpl in *; simplify_eq.\n      + rewrite (interp_weaken [] [τi] Δ τ _) /=.\n        by iApply \"Hτ\".\n      + rewrite list_lookup_fmap in Hσ.\n        destruct (Ξ !! x) as [δ|]eqn:Hxeq; last done.\n        simpl in *; simplify_eq.\n        rewrite (interp_weaken [] [τi] Δ δ _) /=.\n        iApply \"HΞ\"; eauto.\n    - iIntros \"#[Hlen HΞ]\". iDestruct \"Hlen\" as %Hlen.\n      iSplit.\n      { iAlways. iIntros (v) \"Hv\".\n        rewrite -(interp_weaken [] [τi] Δ τ _) /=.\n        by iApply (\"HΞ\" $! 0). }\n      iSplit.\n      { rewrite /= fmap_length in Hlen; auto. }\n      iIntros (x σ Hσ) \"!#\". iIntros (v) \"Hv\".\n      rewrite -(interp_weaken [] [τi] Δ σ _) /=.\n      iApply (\"HΞ\" $! (S x)); last done.\n      rewrite /= list_lookup_fmap Hσ //.\n  Qed.\n\n  Lemma logrel_subtyp Δ Ξ τ τ' v :\n    env_Persistent Δ →\n    subtype Ξ τ τ' →\n    interp_Tenv Δ Ξ ⊢ □ (interp τ Δ v -∗ interp τ' Δ v).\n  Proof.\n    iIntros (HΔ Hsb) \"#HΞ\".\n    iIntros \"!# #Hτ\".\n    iInduction Hsb as [] \"IH\" forall (Δ HΔ v) \"HΞ Hτ\"; simpl; auto.\n    - iDestruct \"HΞ\" as \"[% HΞ]\".\n      iApply (\"HΞ\" $! x); eauto.\n    - iApply \"IH1\"; eauto.\n      iAlways. iApply \"IH\"; eauto.\n    - rewrite -/interp.\n      iAlways. iIntros (w) \"#Hw\".\n      iApply wp_wand_r; iSplitL.\n      + iApply \"Hτ\". iApply \"IH\"; eauto.\n      + iIntros (?) \"#?\"; iApply \"IH1\"; eauto.\n    - rewrite -/interp.\n      iAlways. iIntros (τi Hτi) \"#Hτi\".\n      iApply wp_wand_r; iSplitL; first by iApply \"Hτ\"; eauto.\n      iIntros (?) \"#?\"; iApply \"IH\"; eauto.\n      + by iPureIntro; apply env_persistent_cons.\n      + iAlways. rewrite -interp_Tenv_weaken; auto.\n    - iLöb as \"ILH\" forall (v) \"Hτ\".\n      rewrite (fixpoint_unfold (interp_rec1 ⟦ σ ⟧ Δ) v).\n      rewrite (fixpoint_unfold (interp_rec1 ⟦ τ ⟧ Δ) v).\n      simpl.\n      iAlways.\n      iDestruct \"Hτ\" as (w ?) \"Hτ\".\n      iExists _; iSplit; first done.\n      iNext.\n      iSpecialize (\"IH\" $! (fixpoint (interp_rec1 ⟦ σ ⟧ Δ) ::\n                            fixpoint (interp_rec1 ⟦ τ ⟧ Δ) :: Δ) with \"[]\").\n      { iPureIntro.\n        constructor; last constructor; last done.\n        - intros; by apply (interp_persistent (TRec σ)).\n        - intros; by apply (interp_persistent (TRec τ)). }\n      iSpecialize (\"IH\" $! w with \"[]\").\n      { iAlways.\n        iDestruct \"HΞ\" as \"[HΞ1 HΞ2]\".\n        iSplit.\n        { rewrite /= fmap_length. by iDestruct \"HΞ1\" as %->. }\n        iIntros (x ρ Hx).\n        destruct x as [|[|x]]; simpl in *; simplify_eq; simpl.\n        - change (fixpoint (interp_rec1 ⟦ σ ⟧ Δ)) with (⟦ TRec σ ⟧ Δ).\n          iAlways. by iIntros (u) \"#?\"; iApply \"ILH\".\n        - change (fixpoint (interp_rec1 ⟦ τ ⟧ Δ)) with (⟦ TRec τ ⟧ Δ).\n          change (fixpoint (interp_rec1 ⟦ σ ⟧ Δ)) with (⟦ TRec σ ⟧ Δ).\n          iAlways. by iIntros (u) \"#?\".\n        - iAlways.\n          rewrite list_lookup_fmap in Hx.\n          iIntros (u) \"Hu\".\n          destruct (Δ !! x) as [δ|] eqn:HΔx; rewrite HΔx; last done.\n          destruct (Ξ !! x) as [δ'|] eqn:HΞx; last done.\n          iSpecialize (\"HΞ2\" $! x δ' with \"[]\"); first done.\n          rewrite HΔx; simpl.\n          iSpecialize (\"HΞ2\" $! u with \"Hu\").\n          simpl in *; simplify_eq.\n          change (δ'.[ren (+2)]) with (δ'.[upn 0 (ren (+2))]).\n          by rewrite (interp_weaken [] [_; _] _ _ _). }\n      rewrite (interp_weaken [] [_] (_ :: _) _ _).\n      rewrite (interp_weaken [_] [_] _ _ _).\n      by iApply \"IH\".\n  Qed.\n\nEnd logrel.\n\nTypeclasses Opaque interp_env.\nNotation \"⟦ τ ⟧\" := (interp τ).\nNotation \"⟦ τ ⟧ₑ\" := (interp_expr τ).\nNotation \"⟦ Γ ⟧*\" := (interp_env Γ).\n", "meta": {"author": "amintimany", "repo": "F_mu_ref_conc_sub", "sha": "d5c154e11bc646c8e474e87b6a9959db93ec733e", "save_path": "github-repos/coq/amintimany-F_mu_ref_conc_sub", "path": "github-repos/coq/amintimany-F_mu_ref_conc_sub/F_mu_ref_conc_sub-d5c154e11bc646c8e474e87b6a9959db93ec733e/logrel_unary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.28476366446907925}}
{"text": "Require Export DEX_ElemLemmas.\n\n\nImport DEX_BigStepWithTypes.DEX_BigStepWithTypes DEX_BigStep.DEX_Dom DEX_Prog.\n\n(*  Opaque BigStep.Dom.Heap.update.*)\n\nSection p.\n  Variable kobs : L.t.\n  Variable p : DEX_ExtendedProgram.\n\nLemma some_eq: forall (A:Type) (x y:A), Some x = Some y -> x = y.\nProof. intros; inversion H; auto. Qed.\n\nLemma leql_join_eq: forall (k k1 k2: L.t) , k2 = L.join k k1 -> L.leql k k2.\nProof. intros. subst; apply leql_join2; apply L.leql_refl; auto. Qed.\n\nLtac indist2_intra_normal_aux Hindistreg rn:=\n  specialize Hindistreg with rn;\n  inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist];\n  try (constructor 1 with (k:=lvl) (k':=lvl'); \n  try (rewrite VarMap.get_update2; auto); auto);\n  try (constructor 2; rewrite ?DEX_Registers.get_update_old; auto).\n\nLemma indist2_intra_normal : \n forall se reg m sgn pc pc2 pc2' i r1 rt1 r1' rt1' r2 r2' rt2 rt2',\n   instructionAt m pc = Some i ->\n\n   NormalStep se reg m sgn i (pc,r1) rt1 (pc2,r2) rt2 ->\n   NormalStep se reg m sgn i (pc,r1') rt1' (pc2',r2') rt2' ->\n   st_in kobs rt1 rt1' (pc,r1) (pc,r1') ->\n\n   st_in kobs rt2 rt2' (pc2,r2) (pc2',r2').\nProof.\n  intros se reg m sgn pc pc2 pc2' i r1 rt1 r1' rt1' r2 r2' rt2 rt2'\n    Hins Hstep Hstep' Hindist.\n  destruct i; simpl in Hstep, Hstep';\n  inversion_clear Hstep in Hins Hstep' Hindist;\n  inversion_clear Hstep' in Hindist;\n  apply inv_st_in in Hindist;  \n(*   destruct (inv_st_in H2) as [Rin]; clear H2; *)\n  constructor; auto.\n  (* DEX_Move *)\n  subst.\n  inversion Hindist as [Heqset Hindistreg].\n  constructor; auto. \n  (* proving eq_set *)\n  rewrite VarMap.domain_inv; auto. rewrite VarMap.domain_inv; auto.\n  intros rn.\n  destruct Reg_eq_dec with (x:=rn) (y:=rt) as [Hreg | Hreg].\n    (* rn = rt *)\n    rewrite Hreg.\n    specialize Hindistreg with (rn:=rs).  \n    inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist]. \n    constructor 1 with (k:=L.join k0 (se pc)) (k':=L.join k1 (se pc)); \n      try (rewrite VarMap.get_update1; auto); auto.\n    rewrite Hget in H7; inversion H7; subst; apply not_leql_join1; auto.\n    rewrite Hget' in H17; inversion H17; subst; apply not_leql_join1; auto.\n    constructor 2. rewrite <- H5 in Hvalueindist; rewrite <- H15 in Hvalueindist.\n    rewrite ?DEX_Registers.get_update_new; auto.\n    (* rn <> rt *) \n    indist2_intra_normal_aux Hindistreg rn.\n  (* DEX_Const *)\n  subst.\n  inversion Hindist as [Heqset Hindistreg].\n  constructor; auto.\n  (* proving eq_set *)\n  rewrite VarMap.domain_inv; auto. rewrite VarMap.domain_inv; auto.\n  intros rn. \n  destruct Reg_eq_dec with (x:=rn) (y:=rt) as [Hreg | Hreg].\n    (* rn = rt *)\n    rewrite Hreg.\n    constructor 2.\n    rewrite ?DEX_Registers.get_update_new.\n    constructor 1. constructor.\n    (* rn <> rt *) \n    indist2_intra_normal_aux Hindistreg rn.\n  (* DEX_Ineg *)\n  subst.\n  inversion Hindist as [Heqset Hindistreg].\n  constructor; auto.\n  (* proving eq_set *)\n  rewrite VarMap.domain_inv; auto. rewrite VarMap.domain_inv; auto.\n  intros rn. \n  destruct Reg_eq_dec with (x:=rn) (y:=rt) as [Hreg | Hreg].\n    (* rn = rt *)\n    rewrite Hreg.\n    specialize Hindistreg with (rn:=rs).  \n    inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist]. \n    constructor 1 with (k:=L.join k (se pc)) (k':=L.join k0 (se pc)); \n      try (rewrite VarMap.get_update1; auto); auto.\n    rewrite Hget in H5; inversion H5; subst; apply not_leql_join1; auto.\n    rewrite Hget' in H14; inversion H14; subst; apply not_leql_join1; auto.\n    constructor 2. rewrite <- H4 in Hvalueindist; rewrite <- H13 in Hvalueindist.\n    rewrite ?DEX_Registers.get_update_new; auto.\n    inversion Hvalueindist. inversion H15. constructor 1; constructor.\n    (* rn <> rt *) \n    indist2_intra_normal_aux Hindistreg rn.\n  (* DEX_Inot *)\n  subst.\n  inversion Hindist as [Heqset Hindistreg].\n  constructor; auto.\n  (* proving eq_set *)\n  rewrite VarMap.domain_inv; auto. rewrite VarMap.domain_inv; auto.\n  intros rn. \n  destruct Reg_eq_dec with (x:=rn) (y:=rt) as [Hreg | Hreg].\n    (* rn = rt *)\n    rewrite Hreg.\n    specialize Hindistreg with (rn:=rs).  \n    inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist]. \n    constructor 1 with (k:=L.join k (se pc)) (k':=L.join k0 (se pc)); \n      try (rewrite VarMap.get_update1; auto); auto.\n    rewrite Hget in H5; inversion H5; subst; apply not_leql_join1; auto.\n    rewrite Hget' in H14; inversion H14; subst; apply not_leql_join1; auto.\n    constructor 2. rewrite <- H4 in Hvalueindist; rewrite <- H13 in Hvalueindist.\n    rewrite ?DEX_Registers.get_update_new; auto.\n    inversion Hvalueindist. inversion H15. constructor 1; constructor.\n    (* rn <> rt *) \n    indist2_intra_normal_aux Hindistreg rn.\n  (* DEX I2b *)\n  subst.\n  inversion Hindist as [Heqset Hindistreg].\n  constructor; auto.\n  (* proving eq_set *)\n  rewrite VarMap.domain_inv; auto. rewrite VarMap.domain_inv; auto.\n  intros rn. \n  destruct Reg_eq_dec with (x:=rn) (y:=rt) as [Hreg | Hreg].\n    (* rn = rt *)\n    rewrite Hreg.\n    specialize Hindistreg with (rn:=rs).  \n    inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist]. \n    constructor 1 with (k:=L.join k (se pc)) (k':=L.join k0 (se pc)); \n      try (rewrite VarMap.get_update1; auto); auto.\n    rewrite Hget in H5; inversion H5; subst; apply not_leql_join1; auto.\n    rewrite Hget' in H14; inversion H14; subst; apply not_leql_join1; auto.\n    constructor 2. rewrite <- H4 in Hvalueindist; rewrite <- H13 in Hvalueindist.\n    rewrite ?DEX_Registers.get_update_new; auto.\n    inversion Hvalueindist. inversion H15. constructor 1; constructor.\n    (* rn <> rt *) \n    indist2_intra_normal_aux Hindistreg rn.\n  (* DEX_I2s *)\n  subst.\n  inversion Hindist as [Heqset Hindistreg].\n  constructor; auto.\n  (* proving eq_set *)\n  rewrite VarMap.domain_inv; auto. rewrite VarMap.domain_inv; auto.\n  intros rn. \n  destruct Reg_eq_dec with (x:=rn) (y:=rt) as [Hreg | Hreg].\n    (* rn = rt *)\n    rewrite Hreg.\n    specialize Hindistreg with (rn:=rs).  \n    inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist]. \n    constructor 1 with (k:=L.join k (se pc)) (k':=L.join k0 (se pc)); \n      try (rewrite VarMap.get_update1; auto); auto.\n    rewrite Hget in H5; inversion H5; subst; apply not_leql_join1; auto.\n    rewrite Hget' in H14; inversion H14; subst; apply not_leql_join1; auto.\n    constructor 2. rewrite <- H4 in Hvalueindist; rewrite <- H13 in Hvalueindist.\n    rewrite ?DEX_Registers.get_update_new; auto.\n    inversion Hvalueindist. inversion H15. constructor 1; constructor.\n    (* rn <> rt *) \n    indist2_intra_normal_aux Hindistreg rn.\n  (* DEX_IBinop *)\n  subst.\n  inversion Hindist as [Heqset Hindistreg].\n  constructor; auto.\n  (* proving eq_set *)\n  rewrite VarMap.domain_inv; auto. rewrite VarMap.domain_inv; auto.\n  intros rn. \n  destruct Reg_eq_dec with (x:=rn) (y:=rt) as [Hreg | Hreg].\n    (* rn = rt *)\n    rewrite Hreg.\n    assert (Hindistreg' := Hindistreg).\n    specialize Hindistreg with (rn:=ra).\n    specialize Hindistreg' with (rn:=rb).  \n    inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist]. \n    constructor 1 with (k:=L.join k1 (L.join k2 (se pc))) (k':=L.join k0 (L.join k3 (se pc))); \n      try (rewrite VarMap.get_update1; auto); auto.\n    rewrite Hget in H8; inversion H8; subst; apply not_leql_join1; auto.\n    rewrite Hget' in H21; inversion H21; subst; apply not_leql_join1; auto.\n    (* case of register b *)\n    inversion Hindistreg' as [lvl2 lvl2' Hget2 Hget2' Hleq2 Hleq2' | Hvalueindist'].\n    constructor 1 with (k:=L.join k1 (L.join k2 (se pc))) (k':=L.join k0 (L.join k3 (se pc))); \n      try (rewrite VarMap.get_update1; auto); auto.\n    rewrite Hget2 in H9; inversion H9; subst.\n    apply not_leql_join2; apply not_leql_join1; auto.\n    rewrite Hget2' in H22; inversion H22; subst.\n    apply not_leql_join2; apply not_leql_join1; auto.\n    constructor 2. \n    rewrite ?DEX_Registers.get_update_new.\n    rewrite <- H6 in Hvalueindist; rewrite <- H19 in Hvalueindist.\n    rewrite <- H7 in Hvalueindist'; rewrite <- H20 in Hvalueindist'.\n    inversion Hvalueindist as [v v' Hin | Hnone]; inversion Hvalueindist' as [v2 v2' Hin' | Hnone']; \n    inversion Hin; inversion Hin'. repeat (constructor); auto.\n    (* rn <> rt *) \n    indist2_intra_normal_aux Hindistreg rn.\n  (* DEX_IBinopConst *)\n  subst.\n  inversion Hindist as [Heqset Hindistreg].\n  constructor; auto.\n  (* proving eq_set *)\n  rewrite VarMap.domain_inv; auto. rewrite VarMap.domain_inv; auto.\n  intros rn. \n  destruct Reg_eq_dec with (x:=rn) (y:=rt) as [Hreg | Hreg].\n    (* rn = rt *)\n    rewrite Hreg.\n    specialize Hindistreg with (rn:=r).\n    inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist]. \n    constructor 1 with (k:=L.join k (se pc)) (k':=L.join k0 (se pc)); \n      try (rewrite VarMap.get_update1; auto); auto.\n    rewrite Hget in H5; inversion H5; subst; apply not_leql_join1; auto.\n    rewrite Hget' in H14; inversion H14; subst; apply not_leql_join1; auto.\n    constructor 2. \n    rewrite ?DEX_Registers.get_update_new.\n    rewrite <- H4 in Hvalueindist; rewrite <- H13 in Hvalueindist. \n    inversion Hvalueindist as [val val' Hin | Hnone]; inversion Hin;\n    repeat (constructor); auto.\n    (* rn <> rt *) \n    indist2_intra_normal_aux Hindistreg rn.\n\nQed.\n\n\nEnd p.\n\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_ElemLemmaNormalIntra2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.2847636575553128}}
{"text": "(* NOTE: broken, fix after Crypto.Bedrock.Group.ScalarMult.MontgomeryLadder. *)\nRequire Import Rupicola.Lib.Api. (* for helpful tactics + notations *)\nRequire Import coqutil.Byte.\nRequire Import Crypto.Algebra.Hierarchy.\nRequire Import Crypto.Algebra.ScalarMult.\nRequire Import Crypto.Arithmetic.PrimeFieldTheorems.\nRequire Import Crypto.Bedrock.Group.ScalarMult.MontgomeryEquivalence.\nRequire Import Crypto.Bedrock.Group.ScalarMult.MontgomeryLadder.\nRequire Import Crypto.Bedrock.Specs.Field.\nRequire Import Crypto.Bedrock.Specs.Group.\nRequire Import Crypto.Curves.Montgomery.AffineInstances.\nRequire Import Crypto.Curves.Montgomery.XZ.\nRequire Import Crypto.Curves.Montgomery.XZProofs.\nRequire Import Crypto.Spec.MontgomeryCurve.\n\nModule M.\n  Section __.\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    Context {field_parameters : FieldParameters}\n            {field_parameters_ok : FieldParameters_ok}\n            {field_representation : FieldRepresentation}\n            {field_representation_ok : FieldRepresentation_ok}\n            {scalarbits : nat}.\n    Context (char_ge_3 :\n               @Ring.char_ge (F M_pos) Logic.eq F.zero F.one F.opp F.add\n                             F.sub F.mul 3)\n            (char_ge_5 :\n               @Ring.char_ge (F M_pos) Logic.eq F.zero F.one F.opp F.add\n                             F.sub F.mul 5)\n            (char_ge_12 :\n               @Ring.char_ge (F M_pos) Logic.eq F.zero F.one F.opp F.add\n                              F.sub F.mul 12)\n            (char_ge_28 :\n               @Ring.char_ge (F M_pos) Logic.eq F.zero F.one F.opp F.add\n                             F.sub F.mul 28)\n            (a b : F M_pos) (scmul : string).\n    Context\n      (b_nonzero : b <> F.zero)\n      (discriminant_nonzero : (a * a - (1 + 1 + 1 + 1) <> 0)%F)\n      (a24_correct : ((1 + 1 + 1 + 1) * a24)%F = (a - (1 + 1))%F)\n      (a2m4_nonsquare :\n         forall r : F M_pos,\n           (r * r)%F <> (a * a - (1 + 1 + 1 + 1))%F).\n\n    Local Notation to_xz := (M.to_xz (F:=F M_pos) (Feq:=Logic.eq)\n                                     (Fzero:=F.zero) (Fone:=F.one)\n                                     (Fadd:=F.add) (Fmul:=F.mul)\n                                     (a:=a) (b:=b)).\n    Local Notation to_x := (M.to_x (F:=F M_pos) (Feq:=Logic.eq)\n                                   (Fzero:=F.zero) (Fdiv:=F.div)\n                                   (Feq_dec:=F.eq_dec)).\n\n    Global Instance group_parameters\n      : GroupParameters :=\n      { G := @M.point (F M_pos) Logic.eq F.add F.mul a b;\n        eq := @M.eq (F M_pos) Logic.eq F.add F.mul a b;\n        add := @M.add (F M_pos) Logic.eq F.zero F.one F.opp F.add F.sub\n                      F.mul F.inv F.div (@F.field_modulo M_pos M_prime)\n                      F.eq_dec char_ge_3 a b b_nonzero;\n        zero := @M.zero (F M_pos) Logic.eq F.add F.mul a b;\n        opp := @Affine.M.opp _ _ _ _ _ _ _ _ _ _ (@F.field_modulo M_pos M_prime) F.eq_dec a b b_nonzero;\n        scalarmult :=\n          @scalarmult_ref _\n                          (M.add\n                             (field := @F.field_modulo M_pos M_prime)\n                             (char_ge_3 := char_ge_3)\n                             (b_nonzero := b_nonzero))\n                          M.zero\n                          (Affine.M.opp\n                             (field := @F.field_modulo M_pos M_prime)\n                             (b_nonzero := b_nonzero));\n        scmul := scmul;\n      }.\n\n    Global Instance group_parameters_ok : GroupParameters_ok.\n    Proof.\n      constructor.\n      { apply M.MontgomeryWeierstrassIsomorphism; auto. }\n      { apply @scalarmult_ref_is_scalarmult.\n        apply M.MontgomeryWeierstrassIsomorphism; auto. }\n    Qed.\n\n    Definition xrepresents (x : list byte) (P : G) : Prop :=\n      feval_bytes x = to_x (to_xz P) /\\ bytes_in_bounds x.\n\n    Global Instance x_representation : GroupRepresentation :=\n      { gelem := list byte; (* x only, as bytes *)\n        grepresents := xrepresents;\n        GElem := FElemBytes;\n      }.\n\n    Section Implementation.\n      Local Instance spec_of_montladder : spec_of \"montladder\" := spec_of_montladder scalarbits.\n\n      (* redeclaration plugs in implicits so [enter] works *)\n      Definition spec_of_scmul : spec_of scmul :=\n        Eval cbv [spec_of_scmul] in\n          (@spec_of_scmul _ _ _ _ _ _  group_parameters x_representation (Nat.div_up scalarbits 8)).\n      Definition spec_of_from_bytes : spec_of from_bytes := spec_of_from_bytes.\n      Definition spec_of_to_bytes : spec_of to_bytes := spec_of_to_bytes.\n      Existing Instances spec_of_scmul spec_of_from_bytes spec_of_to_bytes.\n\n      Fixpoint repeat_stackalloc\n               (size : Z) (names : list string)\n        : cmd.cmd -> cmd.cmd :=\n        match names with\n        | [] => fun post => post\n        | n :: names' =>\n          fun post =>\n            cmd.stackalloc n size (repeat_stackalloc size names' post)\n        end.\n\n      Import NotationsCustomEntry.\n      Definition scmul_func := func! (out, x_bytes, k) {\n        (* TODO: remove stack allocation of temporaries, it is no longer needed for Rupicola *)\n                 $(repeat_stackalloc\n                   felem_size_in_bytes\n                   [\"X1\"; \"Z1\"; \"X2\"; \"Z2\"; \"A\"; \"AA\"; \"B\"; \"BB\"; \"E\"; \"C\"; \"D\"; \"DA\"; \"CB\"; \"x\"; \"r\"]\n                   (cmd.seq\n                      (cmd.call [] from_bytes [expr.var \"x\"; expr.var \"x_bytes\"])\n                      (cmd.seq\n                         (cmd.call [] \"montladder\"\n                                   [expr.var \"r\"; expr.var \"k\"; expr.var \"x\"; expr.var \"X1\";\n                                      expr.var \"Z1\"; expr.var \"X2\"; expr.var \"Z2\"; expr.var \"A\";\n                                        expr.var \"AA\"; expr.var \"B\"; expr.var \"BB\"; expr.var \"E\";\n                                          expr.var \"C\"; expr.var \"D\"; expr.var \"DA\"; expr.var \"CB\"])\n                         (cmd.call [] to_bytes [expr.var \"out\"; expr.var \"r\"]))))}.\n\n      Lemma and_iff1_l (X : Prop) (P : mem -> Prop) :\n        X ->\n        Lift1Prop.iff1 (fun m => X /\\ P m) P.\n      Proof.\n        repeat intro.\n        split; intros; sepsimpl; eauto.\n      Qed.\n\n      (* TODO: generalize this tactic and upstream to bedrock2 *)\n      Ltac extract_pred' pred P :=\n        lazymatch P with\n        | (pred ?X * ?Q)%sep => constr:(pair X Q)\n        | (?Q * pred ?X)%sep => constr:(pair X Q)\n        | (?P * ?Q)%sep =>\n          lazymatch P with\n          | context [pred] =>\n            match extract_pred' pred P with\n            | pair ?X ?P' => constr:(pair X (P' * Q)%sep)\n            end\n          | _ => lazymatch Q with\n                 | context [pred] =>\n                   match extract_pred' pred Q with\n                   | pair ?X ?Q' => constr:(pair X (P * Q')%sep)\n                   end\n                 | _ => fail \"No emp found in\" P Q\n                 end\n          end\n        | _ => fail \"expected a separation-logic conjunct with at least 2 terms, got\" P\n        end.\n      Ltac extract_pred pred :=\n        match goal with\n        | |- context [pred] =>\n          match goal with\n          | |- sep ?P ?Q ?m =>\n            let r := extract_pred' pred (sep P Q) in\n            match r with\n            | pair ?X ?Y =>\n              let H := fresh in\n              assert (sep (pred X) Y m) as H;\n              [ | clear - H; ecancel_assumption ]\n            end\n          end\n        end.\n      Ltac extract_emp :=\n        let pred := constr:(emp (map:=mem)) in\n        extract_pred pred.\n      Ltac extract_ex1 :=\n        lazymatch goal with\n        | |- context [@Lift1Prop.ex1 ?A ?B] =>\n            let pred := constr:(@Lift1Prop.ex1 A B) in\n            extract_pred pred\n        | _ => fail \"extract_ex1 : no ex1 found in goal!\"\n        end.\n\n      Ltac prove_anybytes_postcondition :=\n        repeat lazymatch goal with\n               | |- exists m mS,\n                   Memory.anybytes ?p ?n mS\n                   /\\ map.split ?mC m mS\n                   /\\ ?K =>\n                 let H := fresh in\n                 let mp := fresh in\n                 let mq := fresh in\n                 assert (sep (fun m => K) (Placeholder p) mC) as H;\n                 [ | clear - H; cbv [sep] in H; cbv [Placeholder];\n                     destruct H as [mp [mq [? [? ?]]]];\n                     exists mp, mq; ssplit; solve [eauto] ]\n               | |- sep (fun mC =>\n                           exists m mS,\n                             Memory.anybytes ?p ?n mS\n                             /\\ map.split mC m mS\n                             /\\ ?K) ?Q ?mem =>\n                 let H := fresh in\n                 let H' := fresh in\n                 let mp := fresh in\n                 let mq := fresh in\n                 let mp2 := fresh in\n                 let mq2 := fresh in\n                 assert (sep (sep (fun m => K) (Placeholder p)) Q mem) as H;\n                 [ eapply sep_assoc\n                 | clear - H; cbv [sep] in H; cbv [Placeholder];\n                   destruct H as [mp [mq [? [H' ?] ] ] ];\n                   exists mp, mq; ssplit; eauto; [ ];\n                   destruct H' as [mp2 [mq2 [? [? ?] ] ] ];\n                   exists mp2, mq2; ssplit; solve [eauto] ]\n               end.\n\n      (* speedier proof if straightline doesn't try to compute the stack\n         allocation sizes *)\n      Local Opaque felem_size_in_bytes.\n      Lemma scmul_func_correct : forall functions, spec_of_scmul ((scmul, scmul_func)::functions).\n      Proof.\n        (* straightline doesn't work properly for setup, so the first step\n           is inlined and changed here *)\n        enter scmul_func. intros.\n        WeakestPrecondition.unfold1_call_goal.\n        (cbv beta match delta [WeakestPrecondition.call_body]).\n        lazymatch goal with\n        | |- if ?test then ?T else _ =>\n          replace test with true by (rewrite String.eqb_refl; reflexivity);\n            change_no_check T\n        end; (cbv beta match delta [WeakestPrecondition.func]).\n\n        cbv [GElem x_representation grepresents xrepresents] in *.\n        sepsimpl.\n        (* plain straightline should do this but doesn't (because locals\n           representation is abstract?); using enhanced version from\n           rupicola (straightline') *)\n        repeat lazymatch goal with\n               | |- (felem_size_in_bytes mod _ = 0)%Z /\\ _ =>\n                 split; [ solve [apply felem_size_in_bytes_mod] | ]\n               | Hb : Memory.anybytes ?p ?n ?mS,\n                      Hs : map.split ?mC ?m ?mS,\n                           Hm : ?P ?m |- _ =>\n                   assert (sep P (Placeholder p) mC)\n                     by (remember P; cbv [sep]; exists m, mS;\n                         ssplit; solve [eauto]);\n                   clear Hb Hs\n               | _ => clear_old_seps; straightline'\n               end.\n\n(* NOTE: broken, fix after Crypto.Bedrock.Group.ScalarMult.MontgomeryLadder. *)\n(*\n        (* call from_bytes *)\n        handle_call; [ solve [eauto] .. | ].\n        sepsimpl; repeat straightline'.\n\n        (* call montladder *)\n        handle_call; [ solve [eauto] .. | ].\n        sepsimpl; repeat straightline'.\n\n        (* clean up *)\n        cbv [MontLadderResult] in *.\n        clear_old_seps. sepsimpl.\n\n        (* call to_bytes *)\n        handle_call; [ solve [eauto] .. | ].\n        sepsimpl; subst. clear_old_seps.\n\n        (* prove postcondition, including dealloc *)\n        repeat straightline'.\n        prove_anybytes_postcondition.\n        cbn [WeakestPrecondition.list_map\n               WeakestPrecondition.list_map_body].\n        seprewrite and_iff1_l; [ reflexivity | ].\n        sepsimpl; [ reflexivity .. | ].\n        lift_eexists; sepsimpl.\n\n        extract_emp.\n\n        extract_emp.\n\n        sepsimpl; [ | | ].\n        {\n          pose proof scalarbits_pos.\n          match goal with\n          | H : context [montladder_gallina] |- _ =>\n            erewrite montladder_gallina_equiv in H\n              by (reflexivity || lia)\n          end.\n          cbv [grepresents xrepresents] in *.\n          cbn [scalarmult group_parameters].\n          match goal with\n          | H : M.montladder _ _ _ = feval ?x\n            |- feval_bytes ?y = _ =>\n            let H' := fresh in\n            assert (feval x = feval_bytes y) as H' by eauto;\n              rewrite <-H', <-H; clear H H'\n          end.\n          apply @M.montladder_correct with (Feq := Logic.eq);\n            eauto using F.inv_0, sceval_range with lia; try congruence. }\n        { eauto. }\n        { repeat match goal with\n                 | H : context [FElem ?p] |- context [Placeholder ?p] =>\n                   seprewrite (FElem_from_bytes p)\n                 end.\n          sepsimpl. lift_eexists.\n          ecancel_assumption. }\n      Qed.\n *)\n      Abort.\n    End Implementation.\n  End __.\nEnd M.\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/Group/ScalarMult/ScalarMult.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2847587230525278}}
{"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 SelectOp.\n\nDefinition valnum := positive.\n\nInductive rhs : Type :=\n  | Op: operation -> list valnum -> rhs\n  | Load: memory_chunk -> addressing -> list valnum -> rhs.\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  | _ => 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  | _ => 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\n(* Problem: on ARM, not all load/store instructions accept the Aindexed2\n   and Aindexed2shift addressing modes.  For the time being,\n   avoid producing them. *)\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 (Oaddimm m) ys) =>\n          Some(Aindexed (Int.add m 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  | Oaddimm n, x :: nil =>\n      match get x with\n      | Some(Op (Oaddimm m) ys) => Some(Oaddimm (Int.add m n), ys)\n      | Some(Op (Orsubimm m) ys) => Some(Orsubimm (Int.add m n), ys)\n      | _ => None\n      end\n  | Orsubimm n, x :: nil =>\n      match get x with\n      | Some(Op (Oaddimm m) ys) => Some(Orsubimm (Int.sub n m), ys)\n      | _ => 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": "Ptival", "repo": "compcert-alias", "sha": "c839efb9cd2a4c27add46a1868fe0444d1dfdd9e", "save_path": "github-repos/coq/Ptival-compcert-alias", "path": "github-repos/coq/Ptival-compcert-alias/compcert-alias-c839efb9cd2a4c27add46a1868fe0444d1dfdd9e/arm/CombineOp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2847243700151911}}
{"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 hypermap.\nRequire Import geometry.\nRequire Import coloring.\nRequire Import znat.\nRequire Import grid.\nRequire Import matte.\nRequire Import gridmap.\nRequire Import real.\nRequire Import realmap.\nRequire Import realprop.\nRequire Import approx.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nSection DiscretizeMap.\n\n(* Discretizing the coloring problem for an arbitrary finite map. We compute *)\n(* a finite hypermap whose colorings induce colorings of the map, using the  *)\n(* grid computation package.                                                 *)\n(* The discrete approximation is constructed in five steps :                 *)\n(* 1) enumerate the regions and adjacencies of m0, choosing a representative *)\n(*    border point for each adjacency;                                       *)\n(* 2) construct disjoint rectangles covering the border points;              *)\n(* 3) construct approximations of the border rectangles;                     *)\n(* 4) construct matte approximations of the regions that meet all the        *)\n(*    corresponding border rectangles;                                       *)\n(* 5) construct a hypermap from the mattes using the grid package.           *)\n\nVariable R : real_model.\n\nNotation point := (point R).\nNotation region := (region R).\nNotation map := (map R).\nNotation rect := (rect R).\nNotation interval := (interval R).\n\nLet Hclassical : excluded_middle := reals_classic R.\n\nVariable m0 : map.\nHypothesis Hm0 : finite_simple_map m0.\n\nDefinition map_repr : Type := nat -> nat -> point.\nDefinition adj_repr : Type := nat -> nat -> rect.\n\nDefinition adj_point z1 z2 z :=\n  adjacent m0 z1 z2 -> intersect (not_corner m0) (border m0 z1 z2) z.\n\nDefinition proper_map_repr (mr : map_repr) n :=\n    (forall i, i < n -> inmap m0 (mr i i))\n /\\ (forall i j, i < j -> j < n ->\n      ~ m0 (mr i i) (mr j j) /\\ adj_point (mr i i) (mr j j) (mr i j)).\n\nDefinition cover_map_repr (mr : map_repr) n :=\n  subregion (inmap m0) (fun z => exists2 i, i < n & m0 z (mr i i)).\n\nLemma exists_map_repr : exists n, exists2 mr,\n  proper_map_repr mr n & cover_map_repr mr n.\nProof.\nmove: Hm0 => [_ [n0 Hmn0]]; pose n1 := S n0.\ncase: (Hclassical (exists mr, proper_map_repr mr n1)).\n  move: Hmn0 => [f Hf] [mr [Hmr Imr]].\n  have [s Ls Ds]: exists2 s, size s = n1\n     & forall i, i < n1 -> let j := sub 0 s i in j < n0 /\\ m0 (f j) (mr i i).\n  - elim: n1 mr Hmr {Imr} => [|n Hrec] mr Hmr; first by exists (seq0 : natseq).\n    case: {Hrec}(Hrec (fun i j => mr (S i) (S j))) ltnW => [|s Ls Hs]; auto.\n    case: (Hf (mr 0 0)) => [|j Hjn0 Hjf _]; auto.\n    exists (Adds j s); first by rewrite /= Ls.\n    by move=> [|i]; [ split; first by apply/ltP | apply: Hs ].\n  clear Hf Hmr; have Us: uniq s.\n    rewrite -[s]take_size; move: (leqnn (size s)).\n    elim: {-2}(size s) => [|n Hrec] Hn; first by rewrite take0.\n    rewrite (take_sub 0 Hn) uniq_add_last {}Hrec 1?ltnW // andbT.\n    apply/(subPx 0 _ _); rewrite size_take Hn; move=> [i Hi Ei].\n    rewrite Ls in Hn; case: (Imr _ _ Hi Hn); case.\n    case: (Ds _ Hn) => [_]; rewrite -Ei sub_take //; apply: (map_trans Hm0).\n    by apply (map_sym Hm0); case: (Ds _ (ltn_trans Hi Hn)).\n  have [s' Ls' Ds']: exists2 s', size s' = n0 & s' =1 (fun i => i < n0).\n    exists (traject S 0 n0); first by rewrite size_traject.\n    have EitS: forall i, iter i S 0 = i by elim=> //= *; congr S.\n    by move=> i; apply/trajectP/idP => [[i' Hi' <-]|]; [ rewrite EitS | exists i ].\n  case/idP: (ltnn n0); rewrite -/n1 -Ls -Ls'; apply: uniq_leq_size => // i.\n  by rewrite Ds'; move/(subPx 0)=> [j Hj <-]; rewrite Ls in Hj; case: (Ds _ Hj).\nelim: {n0 Hmn0}n1 => [|n Hrec] Hn.\n  by case: Hn; exists (fun i j : nat => scale_point R 0 Gb00); split.\ncase: (Hclassical (exists mr, proper_map_repr mr n)); auto.\nmove=> [mr Hmr]; exists n; exists mr; move=> //= z Hz.\ncase: (Hclassical (exists2 i, i < n & m0 z (mr i i))) => // Hmrz.\nsuffice [f Hf]: exists f, forall i, i < n -> adj_point (mr i i) z (f i).\n  case: Hn; case: Hmr => [Dmr Hmr].\n  exists (fun i j => if j < n then mr i j else if i < j then f i else z).\n  split; first by move=> i _; case Hi: (i < n); auto; rewrite ltnn.\n  move=> i j Hi; rewrite ltnS leq_eqVlt orbC !ltnn Hi.\n  case Hj: (j < n); first by rewrite (ltn_trans Hi Hj); auto.\n  move/(j =P n)=> Dj; rewrite Dj in Hi; rewrite Hi; split; auto.\n  by move=> Hiz; case Hmrz; exists i; last exact: (map_sym Hm0).\nelim: n {Hrec Hn Hmr Hz Hmrz} => [|n [f Hf]].\n  by exists (fun i : nat => scale_point R 0 Gb00).\ncase: (Hclassical (adjacent m0 (mr n n) z)) => Hn.\n  case: Hn => [t Ht]; exists (fun i => if i < n then f i else t).\n  move=> i; rewrite ltnS leq_eqVlt orbC; case Hi: (i < n); auto.\n  by move/(i =P n)=> Di; rewrite Di; move.\nexists f; move=> i; rewrite ltnS leq_eqVlt orbC; case Hi: (i < n); auto.\nby move/(i =P n)=> Di; rewrite Di; move=> *; case Hn.\nQed.\n\nSection AdjRepr.\n\nVariables (nr : nat) (mr : map_repr).\nHypothesis Hmr : proper_map_repr mr nr.\n\nDefinition proper_adj_repr_at (ar : adj_repr) i j :=\n  and4 (nonempty (ar i j) -> adjacent m0 (mr i i) (mr j j))\n       (adjacent m0 (mr i i) (mr j j) -> ar i j (mr i j))\n       (forall i', i' < nr -> meet (m0 (mr i' i')) (ar i j) -> set2 i j i')\n       (forall i' j', meet (ar i j) (ar i' j') -> i = i' /\\ j = j').\n\nLemma exists_proper_adj_repr : exists ar,\n  forall i j, regpair nr i j -> proper_adj_repr_at ar i j.\nProof.\npose ltp i j i' j' := if j =d j' then i < i' else regpair j' i j.\nhave Eltp0: forall i j j', ltp i j 0 (S j') = ltp i j j' j'.\n  move=> i j j'; rewrite /ltp /regpair ltnS (leq_eqVlt j).\n  case: (j =P S j') => [Dj|_].\n    by rewrite eqn_leq (ltn_neqAle j) Dj ltnn !andbF.\n  by case: (j =P j') => // <-; rewrite andbT.\nhave EltpS: forall i j i' j',\n    ltp i j (S i') j' = (i =d i') && (j =d j') || ltp i j i' j'.\n  by move=> i j i' j'; rewrite andbC /ltp ltnS (leq_eqVlt i); case: (j =d j').\npose patp ar i' j' := forall i j : nat,\n  if ltp i j i' j' then proper_adj_repr_at ar i j else ~ nonempty (ar i j).\nsuffice [ar Har]: exists ar, patp ar 0 nr.\n  exists ar => i j Hij; move: (Har i j); rewrite /ltp Hij.\n  by case: (j =P nr) => // Dj; rewrite Dj /regpair ltnn andbF in Hij.\nelim: {-2}nr (leqnn nr) => [|j' Hrec] Hj'.\n  pose r0 := real0 R; pose int0 := Interval r0 r0.\n  exists (fun i j : nat => Rect int0 int0) => i j.\n  by rewrite /ltp /regpair andbF if_same; move=> [[x y] [[Hx []]]]; exact: ltrW.\nsuffice [ar Har]: exists ar, patp ar j' j'.\n  exists ar => i j; rewrite Eltp0; auto; apply: Har.\n  elim: {1 3}j' (leqnn j') => [|i' Hrec'] Hi'; first by apply Hrec; exact:ltnW.\n  case: {Hrec Hrec'}(Hrec' (ltnW Hi')) => [ar Har].\n  case: (Hclassical (adjacent m0 (mr i' i') (mr j' j'))) => Ha.\n    move: Hmr => [Emr Amr]; case: (Amr _ _ Hi' Hj').\n    set zi' := mr i' i'; set zj' := mr j' j'; set zij' := mr i' j'.\n  move=> _ H; move: {H}(H Ha) => [Hcij' [Hbi' Hbj']].\n  have [rr Err Hrr]: exists2 rr : rect, rr zij'\n      & forall i, i < nr -> meet (m0 (mr i i)) rr -> set2 i' j' i.\n    elim: {-2}nr (leqnn nr) => [|i Hrec] Hi.\n      by exists (sep_rect zij' zij'); first exact: mem_sep_rect.\n    pose zi := mr i i; case: {Hrec}(Hrec (ltnW Hi)) => [rr Err Hrr].\n    case: (Hclassical (exists2 rr' : rect, rr' zij' & ~ meet (m0 zi) rr')).\n      move=> [rr' Err' Hrr']; have Drr := mem_cap_rect rr rr'.\n      exists (cap_rect rr rr'); first by case (Drr zij'); tauto.\n      move=> k; rewrite ltnS leq_eqVlt; case/setU1P=> [Dk|Hk].\n        rewrite Dk -/zi; move=> [z [Hiz Hz]]; case: Hrr'; exists z.\n        case (Drr z); split; tauto.\n      move=> [z [Hkz Hz]]; apply Hrr; first done; exists z.\n      case (Drr z); split; tauto.\n    move=> Hzi; exists rr; first done; move=> k; rewrite ltnS leq_eqVlt.\n    case/setU1P; [ move=> -> _ {k rr Err Hrr} | by auto ].\n    case: Hcij' => f; set cij' := corner_map m0 zij' => Hf.\n    have Hi'n: i' < nr by exact (ltn_trans Hi' Hj').\n    have [ii Hii Dii]: exists2 ii, ii < 2 & m0 (f ii) zi'.\n      case: (Hf zi'); first by split; auto; exact: Emr.\n      by move=> ii Hii [Dii _]; exists ii; first by apply/ltP.\n    have [ij Hij Dij]: exists2 ij, ij < 2 & m0 (f ij) zj'.\n      case: (Hf zj'); first by split; auto; exact: Emr.\n      by move=> ij Hij [Dij _]; exists ij; first by apply/ltP.\n    have [ik Hik Dik]: exists2 ik, ik < 2 & m0 (f ik) zi.\n      case: (Hf zi).\n        split; first by apply: Emr.\n        move=> r Hr Hrzij'; case: (Hr _ Hrzij') => [rr Hrr Err].\n        case (Hclassical (meet (m0 zi) rr)).\n          move=> [t [Hti Ht]]; exists t; split; auto.\n        by move=> Hirr; case Hzi; exists rr.\n      by move=> ik Hik [Dik _]; exists ik; first by apply/ltP.\n    have If: forall i1 i2 j1 j2,\n        m0 (f i1) (mr j1 j1) -> m0 (f i2) (mr j2 j2) ->\n        j1 < nr -> j2 < nr -> negb (j1 =d j2) -> False \\/ negb (i1 =d i2).\n    - have If': forall i1 j1 j2,\n          j1 < nr -> m0 (f i1) (mr j1 j1) -> m0 (f i1) (mr j2 j2) -> j1 <= j2.\n      + move=> i1 j1 j2 Hj1 Hmj1 Hmj2; rewrite leqNgt; apply/idP => Hj2.\n        case: (Amr _ _ Hj2 Hj1); case; apply: (map_trans Hm0) Hmj1.\n        exact: (map_sym Hm0).\n      move=> i1 i2 j1 j2 Hmj1 Hmj2 Hj1 Hj2 Hj12; right; apply/eqP => Di1.\n      by rewrite Di1 in Hmj1; rewrite eqn_leq in Hj12; case/andP: Hj12; eauto.\n    apply/norP; rewrite ltn_neqAle in Hi'; case/andP: Hi' => [Hi'j' _] [Hi'i Hj'i].\n    case: (If _ _ _ _ Dii Dij) => //; case: {Dii}(If _ _ _ _ Dii Dik) => //.\n    case: {If Dij Dik}(If _ _ _ _ Dij Dik) => //.\n    by case: ii ij ik Hii Hij Hik => [|[|ii]] // [|[|ij]] // [|[|ik]].\n  pose ar' i j := cap_rect (ar i j) (sep_rect zij' (mr i j)).\n  have [rr' [Err' Drr'] Hrr']: exists2 rr' : rect, rr' zij' /\\ subregion rr' rr\n      & forall i j, ltp i j j' j' -> meet (ar' i j) rr' -> i = i' /\\ j = j'.\n    elim: {1 2}j' => [|j'' Hrec].\n      exists rr; first by split; move.\n      by move=> i j; rewrite /ltp /regpair andbF if_same.\n    elim: {1}(S j'') => [|i'' Hreci].\n      case: Hrec => [rr' Drr' Hrr']; exists rr'; first done.\n      by move=> i j; rewrite Eltp0; auto.\n    move: {Hrec}Hreci => [rr' [Err' Drr'] Hrr'].\n    have Drr'' := mem_cap_rect rr' (sep_rect (mr i'' (S j'')) zij').\n    exists (cap_rect rr' (sep_rect (mr i'' (S j'')) zij')).\n      split; last by move=> z; case: (Drr'' z) (Drr' z); tauto.\n      by case: (Drr'' zij') (mem_sep_rect (mr i'' (S j'')) zij'); tauto.\n    move=> i j Hij [z [Harz Hrrz]]; rewrite EltpS in Hij.\n    case: (Drr'' z) => [_ H]; case: {H Hrrz}(H Hrrz) => [Hrrz Hz].\n    case/orP: Hij; last by move=> Hij; apply (Hrr' _ _ Hij); exists z; split.\n    case/andP; move/eqP=> Di; move/eqP=> Dj.\n    have Dar' := mem_cap_rect (ar i j) (sep_rect zij' (mr i j)).\n    case: (Dar' z) => [_ H]; case: {H Harz}(H Harz) => [Harz Hz'].\n    have Emrij: forall rr : rect, rr (mr i j) -> rr zij'.\n      by rewrite -Di -Dj in Hz; apply meet_sep_rect; exists z; split.\n    move: (Har i j); case Hij: (ltp i j i' j'); last by case; exists z.\n    move=> [Hmrij1 Hmrij2 Harij _]; have Hmrij: ar i j (mr i j).\n      by apply Hmrij2; apply Hmrij1; exists z.\n    case Hij': (i =d j').\n      move: Hij; rewrite (eqP Hij') /ltp; case: (j =P j') => [Dj'|_].\n        by rewrite ltnNge ltnW.\n      by rewrite /regpair ltn_neqAle leqNgt andbC andbCA andb_neg_b andbF.\n    have Dj': j = j'.\n      apply: eqP; case: (orP (Harij _ Hj' _)) => //; last by rewrite Hij'.\n      rewrite -/zj'; apply: Hbj'; auto.\n      by move=> t Ht; exists (ar i j); move.\n    split; auto; apply: eqP.\n    case: (orP (Harij _ (ltn_trans Hi' Hj') _)) => //.\n      rewrite -/zi'; apply: Hbi'; auto.\n      by move=> t Ht; exists (ar i j); move.\n    by move/eqP=> Di'; rewrite -Di' -Dj' ltnn in Hi'.\n  exists (fun i j => if (i =d i') && (j =d j') then rr' else ar' i j).\n  move=> i j; rewrite EltpS /proper_adj_repr_at.\n  case Dij: ((i =d i') && (j =d j')).\n    case/andP: Dij; move/eqP=> Di; move/eqP=> Dj; rewrite {i}Di {j}Dj.\n    split; auto.\n      move=> i Hi [z [Hiz Hrrz]]; apply (Hrr _ Hi); exists z; split; auto.\n      move=> i j; case Dij: ((i =d i') && (j =d j')).\n      by case/andP: Dij; split; symmetry; apply: eqP.\n    move=> [z [Hrrz Harz]]; case (Hrr' i j); try by try exists z; split.\n    have Dar' := mem_cap_rect (ar i j) (sep_rect zij' (mr i j)).\n    case: (Dar' z) => [_ H]; case: {H Harz}(H Harz) => [Harz _].\n    case Hij: (ltp i j i' j') (Har i j); last by case; exists z.\n    clear; move: Hij; rewrite /ltp; case: (j =d j') => // Hi.\n    exact (ltn_trans Hi Hi').\n  have Dar' := mem_cap_rect (ar i j) (sep_rect zij' (mr i j)).\n  case Hij: (ltp i j i' j') (Har i j) {Dij} => //.\n    move=> [Hmrij1 Hmrij2 Harij Iarij]; split.\n    - by move=> [z Hz]; apply Hmrij1; exists z; case: (Dar' z); tauto.\n    - by move/Hmrij2; case: (Dar' (mr i j)) (mem_sep_rect zij' (mr i j)); tauto.\n    - move=> k Hk [z [Hkz Hz]]; apply (Harij _ Hk); exists z; case (Dar' z).\n      by split; tauto.\n    - move=> i'' j''; case Dij'': ((i'' =d i') && (j'' =d j')).\n      case/andP: Dij''; do 2 move/eqP=> ->; apply: Hrr'.\n      move: Hij; rewrite /ltp; case: (j =d j') => // Hi.\n      exact (ltn_trans Hi Hi').\n    move=> [z [Hiz Hi''z]]; apply Iarij; exists z.\n    split; first by case (Dar' z); tauto.\n    by case (mem_cap_rect (ar i'' j'') (sep_rect zij' (mr i'' j'')) z); tauto.\n  move=> H [z Hz]; case: H; case (Dar' z); exists z; tauto.\nexists ar; move=> i j; rewrite EltpS.\ncase Dij: ((i =d i') && (j =d j')) (Har i j) => //.\ncase/andP: Dij; do 2 move/eqP=> ->; clear i j.\nrewrite /ltp set11 ltnn /=; move=> Harij'; split.\n- by move=> *; case Harij'.\n- by move=> *; case Ha.\n- by move=> i _ [z [_ Hz]]; case: Harij'; exists z.\nby move=> i j [z [Hz _]]; case: Harij'; exists z.\nQed.\n\nSection DiscrAdj.\n\nVariable ar : adj_repr.\nHypothesis Har : forall i j, regpair nr i j -> proper_adj_repr_at ar i j.\n\nDefinition proper_discr_adj_at s b i j :=\n  if garea b =d 0 then ~ adjacent m0 (mr i i) (mr j j) else\n  mem_approx s (inset2 b) (mr i j) /\\ subregion (mem_approx s b) (ar i j).\n\nLemma refine_garea0 : forall s b,\n  (garea (iter s refine_rect b) =d 0) = (garea b =d 0).\nProof.\nmove=> s b; rewrite -!leqn0; elim: s => //= [s Hrec].\nby rewrite garea_refine_rect -2!double0 !leq_double.\nQed.\n\nLemma refine_discr_adj : forall s s' b i j, proper_discr_adj_at s' b i j ->\n  proper_discr_adj_at (s + s') (iter s refine_rect b) i j.\nProof.\nmove=> s s' b i j; rewrite /proper_discr_adj_at refine_garea0.\ncase: (garea b =d 0) => // [] [Hbmr Hbar]; split.\n  case: s => //= s; rewrite addSn; apply mem_approx_inset2.\n  by apply: mem_approx_inset; apply: sub_mem_approx Hbmr => p; case/andP.\nmove=> p; case (mem_approx_refine_rect s s' b p); auto.\nQed.\n\nLemma exists_proper_discr_adj : exists s, exists da,\n  forall i j, regpair nr i j -> proper_discr_adj_at s (da i j) i j.\nProof.\npose ltp i j i' j' := if j =d j' then i < i' else regpair j' i j.\nhave Eltp0: forall i j j', ltp i j 0 (S j') = ltp i j j' j'.\n  move=> i j j'; rewrite /ltp /regpair ltnS (leq_eqVlt j).\n  case: (j =P S j') => [Dj|_]; last by case: (j =P j') => // [<-]; rewrite andbT.\n  by rewrite eqn_leq (ltn_neqAle j) Dj ltnn !andbF.\nhave EltpS: forall i j i' j',\n    ltp i j (S i') j' = (i =d i') && (j =d j') || ltp i j i' j'.\n  by move=> i j i' j'; rewrite andbC /ltp ltnS (leq_eqVlt i); case: (j =d j').\npose patp s da i' j' := forall i j,\n  if ltp i j i' j' then proper_discr_adj_at s (da i j) i j else\n  garea (da i j) =d 0.\nsuffice [s [da Hda]]: exists s, exists da, patp s da 0 nr.\n  exists s; exists da => i j Hij; move: (Hda i j); rewrite /ltp Hij;\n  by  case: (j =P nr) => // Dj; rewrite Dj /regpair ltnn andbF in Hij.\nelim: {-2}nr (leqnn nr) => [|j' Hrec] Hj'.\n  exists 0; exists (fun i j : nat => Grect 1 0 0 0).\n  by move=> i j; rewrite /ltp /regpair andbF if_same.\nsuffice [s [da Hda]]: exists s, exists da, patp s da j' j'.\n  exists s; exists da => i j; rewrite Eltp0; auto; exact: Hda.\nelim: {1 3}j' (leqnn j') => [|i' Hrec'] Hi'; first by apply Hrec; exact:ltnW.\ncase: {Hrec Hrec'}(Hrec' (ltnW Hi')) => [s [da Hda]].\nhave Hij': regpair nr i' j' by apply/andP; split.\ncase: (Hclassical (adjacent m0 (mr i' i') (mr j' j'))) => Ha.\n  case: (Har Hij') => [_ H Harij' Iarij']; move: {H}(H Ha) => Hmrij'.\n  case: (approx_rect Hmrij') => [s' [b [p Dp Hbp] Hbar]]; exists (S (s + s')).\n  have Hb: proper_discr_adj_at (S s') (refine_rect b) i' j'.\n    move: (mem_sub_grect Hbp (gtouch_refl _)).\n    rewrite /proper_discr_adj_at garea_refine_rect -size_enum_grect.\n    rewrite -mem_enum_grect; case: (enum_grect b) => //= _ _ _; split.\n      by apply mem_approx_inset2; exists p.\n    by move=> z; case (mem_approx_refine1_rect s' b z); auto.\n  exists (fun i j => if (i =d i') && (j =d j') then iter (S s) refine_rect b else\n                     iter (S s') refine_rect (da i j)).\n  move=> i j /=; rewrite /proper_discr_adj_at EltpS.\n  case Dij: ((i =d i') && (j =d j')).\n    rewrite /= f_iter -iter_f -addnS; apply: refine_discr_adj.\n    by case/andP: Dij; do 2 move/eqP=> ->.\n  rewrite /= f_iter -addnS addnC; move: (ltp i j i' j') (Hda i j).\n  by case=> *; [ apply: refine_discr_adj | rewrite refine_garea0 ].\nexists s; exists da => i j; move: (Hda i j); rewrite EltpS orbC.\ncase: (ltp i j i' j'); first done.\ncase Dij: ((i =d i') && (j =d j')); last done.\ncase/andP: Dij; do 2 move/eqP => ->; move{i j} => Hg0.\nby rewrite /proper_discr_adj_at Hg0.\nQed.\n\nLemma connected_matte : forall z (r : region) s  (m : matte),\n    let rm := mem_approx s m in\n    r z -> subregion rm r -> open r -> connected r ->\n  exists s', exists m' : matte,\n  let rm' := mem_approx s' m' in\n  and3 (rm' z) (subregion rm rm') (subregion rm' r).\nProof.\nmove=> z r s m rm Hrz Hrm Hr Cr.\npose r1p t s' m' := let rm' := mem_approx s' m' in\n  and3 (rm' t) (subregion rm rm') (subregion rm' r).\npose r1 t := exists s', exists m' : matte, r1p t s' m'.\npose r2 t := r t /\\ ~ r1 t.\nhave Hrr12: subregion r (union r1 r2).\n  move=> t Ht; rewrite /union /r2; case: (Hclassical (r1 t)); tauto.\nhave Hr1r: meet r1 r.\n  have [p Hmp]: exists p, m p.\n    case: (m) => /= [[|p m'] c H _ _ _] //; exists p; exact: setU11.\n  have [t Ht]: exists t, rm t.\n    by exists (scale_point R s p); apply: (mem_approx_scale R s m p).\n  by exists t; split; auto; exists s; exists m; split; try move.\ncase: (Hrr12 _ Hrz) => // Hr2z.\nhave Hr2r: meet r2 r by exists z; split.\npose sbr s' (t : point) := exists2 b,\n  mem_approx s' (inset b) t & subregion (mem_approx s' b) r.\nhave Hr1: open r1.\n  move=> t [s1 [m1 [Ht Hmm1 Hm1r]]].\n  case: (Hr t (Hm1r _ Ht)) => [rr Hrrt Hrrr].\n  case/approx_rect: Hrrt => [s2 [b2 Hb2t Hb2rr]].\n  have [s3 Hb3 [m3 Hm3]]: exists2 s3, sbr s3 t & exists m3 : matte, r1p t s3 m3.\n    exists (s1 + s2).\n      exists (iter s1 refine_rect b2); first by apply mem_approx_inset.\n      by move=> u; case (mem_approx_refine_rect s1 s2 b2 u); auto.\n    exists (iter s2 refine_matte m1); rewrite addnC.\n    split; try by move=> u; case (mem_approx_refine_matte s2 s1 m1 u); auto.\n    by case (mem_approx_refine_matte s2 s1 m1 t); auto.\n  clear s1 m1 Ht Hmm1 Hm1r rr Hrrr s2 b2 Hb2t Hb2rr.\n  have [n Hn]: exists n, mem_approx s3 (fun p => matte_order m3 p <= n) t.\n    case: Hb3 => [_ [p Hp _] _]; exists (matte_order m3 p); exists p; auto.\n    exact: leqnn.\n  elim: n s3 m3 Hn Hm3 Hb3 => [|n Hrec] s' m' [p Dp Hn].\n    move: Hn; rewrite leqn0; move/eqP=> Hn Hm' _.\n    case: (rect_approx Dp) => [rr Hrrt Hrr]; exists rr; first done.\n    case Dmxy: p (matte_order0 Hn) Hrr => [mx my] Hbm' Hrrb.\n    move=> u Hu; exists s'; exists m'; split; try by case Hm'.\n    by apply sub_mem_approx with (1 := Hbm'); auto.\n  move: Hn; rewrite leq_eqVlt; case/setU1P=> [Dn|Hn]; last by apply Hrec; exists p.\n  move=> [Hm't Hmm' Hm'r] [b Hbt Hbr].\n  case: (approx_point_exists (S s') t) => [p' Dp'].\n  have Epp': halfg p' = p by apply: approx_point_inj Dp; apply approx_halfg.\n  have Hm'p: m' p by case: Hm't => [q Dq Hq]; rewrite (approx_point_inj Dp Dq).\n  have Hbp: inset b p by case: Hbt => [q Dq Hq]; rewrite (approx_point_inj Dp Dq).\n  case: (@refine_matte_order m' b p'); rewrite ?Epp' ?Dn //.\n  move=> m'' [Hm'm'' Hm''m'] Hn; apply: (Hrec (S s') m''); try by exists p'.\n    split; try by exists p'; last by apply: Hm'm''; rewrite Epp'.\n      move=> u; move/Hmm'.\n      case: (mem_approx_refine1_matte s' m' u) => [_ H]; move/H {H}.\n      by apply: sub_mem_approx u => [u]; rewrite mem_refine_matte; auto.\n    move=> u [q Dq]; move/(Hm''m' _); case/orP=> Hu.\n      by apply Hbr; exists (halfg q); try exact: approx_halfg.\n    by apply Hm'r; exists (halfg q); try exact: approx_halfg.\n  exists (refine_rect b); first exact: mem_approx_inset1.\n  by move=> u; case (mem_approx_refine1_rect s' b u); auto.\nhave Hr2: open r2.\n  move=> t [Hrt Hr1t]; move/Hr: Hrt => [rr Hrrt Hrrr].\n  move/approx_rect: Hrrt => [s2 [b2 Hb2t Hb2rr]].\n  case: (Hclassical (meet (mem_approx s2 b2) r1)).\n    move=> [u [Hb2u [s1 [m1 [Hu Hmm1 Hm1r]]]]]; case: Hr1t.\n    have [s' [b' [Hb'u Hb't Hb'r] [m' [Hm'u Hmm' Hm'r] Hm'b']]]:\n      exists s', exists2 b' : grect,\n        let rb' := mem_approx s' b' in\n        and3 (rb' u) (mem_approx s' (inset b') t) (subregion rb' r)\n      & exists2 m' : matte, r1p u s' m' & refined_in (m' : set _) b'.\n    - exists (s1 + S s2); exists (iter (S s1) refine_rect b2).\n        rewrite -addSnnS; split; try by apply mem_approx_inset.\n          by case (mem_approx_refine_rect (S s1) s2 b2 u); auto.\n        by move=> v; case (mem_approx_refine_rect (S s1) s2 b2 v); auto.\n      exists (iter (S s2) refine_matte m1); rewrite 1?addnC.\n        split; first [ by case (mem_approx_refine_matte (S s2) s1 m1 u); auto\n        | by move=> v; case (mem_approx_refine_matte (S s2) s1 m1 v); auto ].\n      exact: refine_matte_refined.\n    clear s1 m1 Hu Hmm1 Hm1r rr Hrrr s2 b2 Hb2t Hb2u Hb2rr.\n    have Hb'm': has b' m'.\n      case: Hb'u Hm'u => [p Dp Hp] [p' Dp' Hp']; apply/hasP; exists p; auto.\n      by rewrite (approx_point_inj Dp Dp').\n    move: Hb't => [p Dp Hb'p].\n    case: (refined_extends_in Hm'b' Hb'm' Hb'p) => [m'' Hm'm'' Hm''m' Hm''p].\n    exists s'; exists m''; split; auto; try by exists p.\n      by move=> v Hv; apply: sub_mem_approx (mem_extension Hm'm'') _ _; auto.\n    move=> v [q Dq]; move/Hm''m'.\n    by case/orP=> *; [ apply Hb'r | apply Hm'r ]; exists q.\n  move: Hb2t => [p Dp Hp]; case: (rect_approx Dp) => [rr' Hrr't Hrr'b2] Hb2r1.\n  exists rr'; auto => u Hu; have Hb2u: mem_approx s2 b2 u.\n  apply: sub_mem_approx u {Hu}(Hrr'b2 _ Hu) => [[mx my]] Hu.\n    apply: (mem_sub_grect Hp); move: (p) Hu => [mx' my'].\n    move/and4P=> [Hx0 Hx1 Hy0 Hy1].\n    by rewrite /= Hx0 Hy0 leqz_dec decz_inc Hx1 leqz_dec decz_inc Hy1 !orbT.\n  by split; auto; move=> Hr1u; case: Hb2r1; exists u; split.\nby case: (Cr _ _ Hrr12 Hr1r Hr2r Hr1 Hr2) => [t [Ht [_ []]]].\nQed.\n\nSection DiscrMatte.\n\nVariables (sab : nat) (ab : adjbox).\nHypothesis\n  Hab : forall i j, regpair nr i j -> proper_discr_adj_at sab (ab i j) i j.\n\nDefinition ab_pair i j := regpair nr i j && ab_adj ab i j.\n\nDefinition ab_region i j : region := mem_approx sab (inset (ab i j)).\n\nDefinition proper_discr_matte_at s (m : matte) i nj :=\n  let rm := mem_approx s (m : set _) in\n  and3 (rm (mr i i)) (subregion rm (m0 (mr i i)))\n       (forall j, j < nj -> (ab_pair i j -> meet rm (ab_region i j))\n                         /\\ (ab_pair j i -> meet rm (ab_region j i))).\n\nLemma refine_discr_matte : forall s s' m i nj, proper_discr_matte_at s' m i nj ->\n  proper_discr_matte_at (s + s') (iter s refine_matte m) i nj.\nProof.\nmove=> s s' m i nj [Hmi Hmri Hmb]; split;\n  try by move=> z; case (mem_approx_refine_matte s s' m z); auto.\n- by case (mem_approx_refine_matte s s' m (mr i i)); auto.\nhave Href: forall r : region, meet (mem_approx s' m) r ->\n    meet (mem_approx (s + s') (iter s refine_matte m)) r.\n  move=> r [z Hz]; exists z; rewrite /intersect.\n  by case (mem_approx_refine_matte s s' m z); case Hz; split; auto.\nmove=> j Hj; case (Hmb _ Hj); split; auto.\nQed.\n\nLemma exists_proper_discr_matte : exists s, exists cm,\n  forall i, i < nr -> proper_discr_matte_at s (cm i) i nr.\nProof.\nhave Habp: forall i j, ab_pair i j ->\n    let mij k := meet (m0 (mr k k)) (ab_region i j) in mij i /\\ mij j.\n  move=> i j; move/andP=> [Hij Habij]; rewrite /ab_adj ltnNge leqn0 in Habij.\n  move: (Hab Hij); rewrite /proper_discr_adj_at (negbE Habij).\n  move=> [Hmrij Harij]; case: (Hmrij) => [pij Dpij Hpij].\n  move: (rect_approx Dpij) => [rr Hrrij Hrr].\n  have Hrrab: subregion rr (ab_region i j).\n    case: pij Hrr Hpij {Dpij} => [x y] Hrr Hpij u Hu.\n    apply: sub_mem_approx u {Hu}(Hrr _ Hu) => [[x' y']].\n    move/and4P=> [Hx'0 Hx'1 Hy'0 Hy'1]; case/andP: Hpij; case (ab i j).\n    move=> x0 x1 y0 y1; move/and4P=> [_ Hx1 _ Hy1]; move/and4P=> [Hx0 _ Hy0 _].\n    rewrite -!decz_def in Hx0 Hy0; rewrite /inset /=.\n    rewrite -leqz_dec2 in Hx'0; rewrite -leqz_inc2 in Hx'1.\n    rewrite -leqz_dec2 in Hy'0; rewrite -leqz_inc2 in Hy'1.\n    by apply/and4P; split; eapply leqz_trans; eauto.\n  have Hcij: forall k, let rk := m0 (mr k k) in\n      closure rk (mr i j) -> meet rk (ab_region i j).\n    move=> k rz Hk; case: (Hk rr); auto.\n      by move=> t Ht; exists rr; try move.\n    by move=> t [Ht Hrrt]; exists t; split; auto.\n  have Harij': nonempty (ar i j).\n    exists (mr i j); apply Harij; apply: sub_mem_approx Hmrij => p.\n    case/andP=> [H _]; apply: {H}(mem_sub_grect H); exact: gtouch_refl.\n  case: (Har Hij) => [Haij _ _ _]; case/andP: Hij => [Hi Hj].\n  case: Hmr => [_ H]; case: {H}(H _ _ Hi Hj) => [_ Hapij].\n  by case: (Hapij (Haij Harij')) => [_ [Hcli Hclj]]; split; auto.\nelim: {1 3}nr (leqnn nr) => [|i Hrec] Hi.\n  by exists 0; exists (fun i : nat => point_matte Gb00).\nsuffice: exists s, exists m, proper_discr_matte_at s m i nr.\n  move: {Hrex}(Hrec (ltnW Hi)) => [s1 [cm Hcm]] [s2 [m2 Hm2]]; exists (s1 + s2).\n  exists (fun i' => if i' =d i then iter s1 refine_matte m2 else\n                                    iter s2 refine_matte (cm i')).\n    move=> i'; rewrite ltnS leq_eqVlt; case: (i' =P i) => [Di' _|_ Hi'].\n    by rewrite Di'; apply: refine_discr_matte.\n  by rewrite addnC; apply: refine_discr_matte; auto.\nelim: nr {Hrec} => [|j [s [m [Hmi Hmri Hma]]]].\ncase: Hmr => [H _]; move: {H}(H _ Hi) => Hzi.\ncase: (map_open Hm0 Hzi) => [rr Hrri Hrrm0].\ncase: (approx_rect Hrri) => [s [b [p Dp Hbp] Hbrr]]; exists s.\n  exists (point_matte p); split; try done.\n    by exists p; last by apply: setU11.\n  move=> z Hz; apply Hrrm0; apply Hbrr; apply: sub_mem_approx z Hz => q /=.\n  case/setU1P=> // [<-]; apply (mem_sub_grect Hbp); exact: gtouch_refl.\nhave Hmm: forall r1 r2 r3 : region, subregion r1 r2 -> meet r1 r3 -> meet r2 r3.\n  by move=> r1 r2 r3 Hr12 [z [Hz1 Hz3]]; exists z; split; auto.\ncase Hij: (ab_pair i j).\n  case: (Habp _ _ Hij) => [[z [Hzi Hzj]] _].\n  case: (connected_matte Hzi Hmri ((map_open Hm0) _) ((map_connected Hm0) _)).\n  move=> s' [m' [Hm'z Hmm' Hm'ri]]; exists s'; exists m'; split; auto.\n  move=> j'; rewrite ltnS leq_eqVlt; case/setU1P=> [Dj'|Hj'].\n    rewrite Dj'; split; first by exists z; split; auto.\n    case/andP: Hij; case/andP=> [Hij _] _; rewrite /ab_pair /regpair.\n    by rewrite ltn_neqAle leqNgt Hij andbF.\n  by case: (Hma _ Hj'); split; eauto.\ncase Hji: (ab_pair j i).\n  case: (Habp _ _ Hji) => [_ [z [Hzi Hzj]]].\n  case: (connected_matte Hzi Hmri ((map_open Hm0) _) ((map_connected Hm0) _)).\n  move=> s' [m' [Hm'z Hmm' Hm'ri]]; exists s'; exists m'; split; auto.\n  move=> j'; rewrite ltnS leq_eqVlt; case/setU1P=> [Dj'|Hj'].\n    by rewrite Dj' Hij; split; last by exists z; split; auto.\n  by case: (Hma _ Hj'); split; eauto.\nexists s; exists m; split; auto.\nmove=> j'; rewrite ltnS leq_eqVlt; case/setU1P=> [Dj'|Hj']; auto.\nby rewrite Dj' Hij Hji; split.\nQed.\n\nEnd DiscrMatte.\n\nEnd DiscrAdj.\n\nEnd AdjRepr.\n\nLemma discretize_to_hypermap : exists2 g,\n  planar_bridgeless g & four_colorable g -> map_colorable 4 m0.\nProof.\ncase: exists_map_repr => [nr [mr Hmr Emr]].\ncase: (exists_proper_adj_repr Hmr) => [ar Har].\ncase: (exists_proper_discr_adj Har) => [s1 [ab1 Hab1]].\ncase: (exists_proper_discr_matte Hmr Har Hab1) => [s2 [cm2 Hcm2]].\npose s := s1 + s2.\npose ab i j := iter s2 refine_rect (ab1 i j).\npose cm i := iter s1 refine_matte (cm2 i).\nhave Hab0: forall i j, regpair nr i j -> proper_discr_adj_at mr ar s (ab i j) i j.\n  by move=> *; rewrite /s addnC; apply: refine_discr_adj; auto.\nhave Hcm0: forall i, i < nr -> proper_discr_matte_at nr mr s ab s (cm i) i nr.\n  have Hrab: (forall (r : realmap.region R) (i j : nat),\n              meet r (ab_region s1 ab1 i j) -> meet r (ab_region s ab i j)).\n    move=> r i j [u [Hru Hu]]; exists u; split; auto.\n    by rewrite /ab_region /s addnC; apply: mem_approx_inset.\n  have Eabp: ab_pair nr ab =2 ab_pair nr ab1.\n    by move=> i j; rewrite /ab_pair /ab_adj !ltnNge !leqn0 /ab refine_garea0.\n  move=> i Hi; apply: refine_discr_matte.\n  case: (Hcm2 _ Hi) => [Hcmi Hcmr Hcma]; split; auto.\n  by move=> j Hj; rewrite !Eabp; case (Hcma _ Hj); split; auto.\nmove: {s1 s2}s {ab1 Hab1}ab {cm2 Hcm2}cm => s ab cm in Hab0 Hcm0.\nhave Hab1: forall i j, regpair nr i j ->\n    subregion (mem_approx s (ab i j)) (ar i j).\n- move=> i j Hij; move: (Hab0 _ _ Hij); rewrite /proper_discr_adj_at.\n  case Dab: (garea (ab i j) =d 0); last by case.\n  move=> _ z [p _]; move: Dab; rewrite -size_enum_grect -mem_enum_grect.\n  by case (enum_grect (ab i j)).\nhave Hab: ab_proper nr ab.\n  move=> i1 j1 i2 j2 Hij1 Hij2 p Hab1p Hab2p.\n  case: (Har _ _ Hij1) => [_ _ _ H]; apply: H; exists (scale_point R s p).\n  split; apply: Hab1 => //; exact: mem_approx_scale.\nhave Hcm: cm_proper nr cm.\n  move=> i j Hij; apply/hasP => [[p Hpi Hpj]].\n  case/andP: Hij => [Hij Hj]; have Hi := ltn_trans Hij Hj.\n  case: Hmr => [_ H]; case: {H}(H _ _ Hij Hj); case.\n  case: (Hcm0 _ Hi) (Hcm0 _ Hj) => [_ Hcmi _] [_ Hcmj _].\n  apply (map_trans Hm0) with (scale_point R s p);\n    [ apply Hcmi | apply (map_sym Hm0); apply Hcmj ]; exact: mem_approx_scale.\nhave Habcm: ab_cm_proper nr ab cm.\n  move=> i j Hij Habij.\n  case/andP: Hij (Hij) => [Hij Hj] Hijn; have Hi := ltn_trans Hij Hj.\n  have Habi: has (inset (ab i j)) (cm i).\n    case: (Hcm0 _ Hi) => [_ _ H]; case: {H}(H _ Hj); case.\n      by rewrite /ab_pair Hijn.\n    move=> z [[p Dp Hip] [p' Dp' Habp']] _; apply/hasP; exists p; auto.\n    by rewrite (approx_point_inj Dp Dp').\n  have Habj: has (inset (ab i j)) (cm j).\n    case: (Hcm0 _ Hj) => [_ _ H]; case: {H}(H _ Hi); clear; case.\n      by rewrite /ab_pair Hijn.\n    move=> z [[p Dp Hip] [p' Dp' Habp']]; apply/hasP; exists p; auto.\n    by rewrite (approx_point_inj Dp Dp').\n  split; auto; move=> k; apply/andP/idP => [[Hk]|Dk].\n  move/hasP=> [p Habp Hip]; case: (Har _ _ Hijn) => [_ _ H _]; apply: H => //.\n    exists (scale_point R s p); split.\n      case: (Hcm0 _ Hk) => [_ Hcmk _]; apply Hcmk; exact: mem_approx_scale.\n    apply Hab1; auto; exact: mem_approx_scale.\n  suffice: k < nr /\\ has (inset (ab i j)) (cm k).\n    case; move=> Hk; move/hasP=> [p Hkp Habp]; split; auto.\n    apply/hasP; exists p; auto; apply (mem_sub_grect Habp); exact: gtouch_refl.\n  by case/orP: Dk; move/eqP=> <-; split.\nexists (grid_map Hab Hcm Habcm); first by apply planar_bridgeless_grid_map.\nmove/grid_map_coloring=> [k0 Ek0 Hk0].\npose k z1 z2 := exists2 i1, i1 < nr /\\ m0 (mr i1 i1) z1\n              & exists2 i2, i2 < nr /\\ m0 (mr i2 i2) z2 & k0 i1 = k0 i2.\nhave Hm0k: forall z1 z2, m0 z1 z2 ->\n    forall i1, i1 < nr /\\ m0 (mr i1 i1) z1 ->\n    forall i2, i2 < nr /\\ m0 (mr i2 i2) z2 -> i1 = i2.\n- case: Hmr => [_ Hmr] z1 z2 Hz12 i1 [Hi1 Hiz1] i2 [Hi2 Hiz2].\n  have Hm0i12: m0 (mr i1 i1) (mr i2 i2).\n    by apply: (map_trans Hm0 (map_trans Hm0 Hiz1 Hz12)); exact: (map_sym Hm0).\n  apply: eqP; rewrite eqn_leq; apply/nandP; case; rewrite -ltnNge.\n    by move=> Hi21; case: (Hmr _ _ Hi21 Hi1); case; exact: (map_sym Hm0).\n  by move=> Hi12; case: (Hmr _ _ Hi12 Hi2); case.\nexists k.\n  have Hpm0: forall z1 z2, m0 z1 z2 -> inmap m0 z1 /\\ inmap m0 z2.\n    move=> z1 z2 Hz12; have Hz21 := (map_sym Hm0 Hz12).\n    by move: (map_trans Hm0); rewrite /inmap /subregion; split; eauto.\n  split.\n  - split; move=> z1 z2 [i1 Hiz1 [i2 Hiz2 Hi12]].\n      by exists i2; last by exists i1.\n    move: (Hiz2) => [_ Hz2] z3 [j2 Hjz2 [i3 Hiz3 Hi23]].\n    exists i1; auto; exists i3; auto; rewrite {i1 Hiz1}Hi12 -{i3 Hiz3}Hi23.\n    by congr k0; case/(Hpm0 _ _): Hz2 => *; eapply Hm0k; eauto.\n  - by move=> z [i [Hi Hiz] _]; case/Hpm0: Hiz.\n  - move=> z1 z2 Hz12; case/Hpm0: (Hz12).\n    move/Emr=> [i1 Hi1 Hiz1]; move/Emr=> [i2 Hi2 Hiz2].\n    exists i1; first by split; last exact: (map_sym Hm0).\n    exists i2; first by split; last exact: (map_sym Hm0).\n    by congr k0; apply: (Hm0k _ _ Hz12); (split; last exact: (map_sym Hm0)).\n  move=> z1 z2 [i1 [Hi1 Hiz1] [i2 [Hi2 Hiz2] Hi12]] Hz12a.\n  apply: (map_trans Hm0) (Hiz2); apply (map_sym Hm0); suffice: i1 = i2 by move <-.\n  have Hi12a: adjacent m0 (mr i1 i1) (mr i2 i2).\n    have Hm0c: forall z z', m0 z z' ->\n        subregion (closure (m0 z')) (closure (m0 z)).\n    - move=> z z' Hzz' t Ht r Hr Hrt.\n      case: (Ht r Hr Hrt) => [u [Hu Hur]]; exists u; split; auto.\n      exact: (map_trans Hm0) Hu.\n    move: Hz12a => [t [Ht [Ht1 Ht2]]]; rewrite /subregion in Hm0c.\n    by exists t; repeat split; eauto.\n  clear z1 z2 Hiz1 Hiz2 Hz12a.\n  suffice Heq: forall i j, j < nr -> k0 i = k0 j ->\n      adjacent m0 (mr i i) (mr j j) -> j <= i.\n  - apply: eqP; rewrite eqn_leq; apply/andP; split; auto.\n    by apply Heq; auto; case: Hi12a => [z [Hz [Hz1 Hz2]]]; exists z; repeat split.\n  clear i1 i2 Hi1 Hi2 Hi12 Hi12a.\n  move=> i j Hj Ekij Haij; rewrite leqNgt; apply/idP => Hij.\n  have Hijn: regpair nr i j by rewrite /regpair Hij.\n  move: (Hab0 _ _ Hijn); rewrite /proper_discr_adj_at -leqn0 leqNgt.\n  case Habij: (0 < garea (ab i j)); last by case.\n  by case/eqP: (Hk0 _ _ Hijn Habij).\npose ic c := index c (maps k0 (traject S 0 nr)).\nexists (fun c => mr (ic c) (ic c)).\nhave EitS: forall n, iter n S 0 = n by elim=> //= n ->.\nmove=> z [i [Hi Hiz] _]; exists (k0 i); first by apply: ltP; auto.\nhave Hk0i: maps k0 (traject S 0 nr) (k0 i).\n  by apply maps_f; apply/trajectP; exists i; rewrite ?EitS.\nset j := ic (k0 i).\nhave Hj: j < nr by rewrite -index_mem size_maps size_traject in Hk0i.\nexists j; first by case: Hmr => [H _]; split; try exact: H.\nexists i; first by split.\nby rewrite -(sub_index 0 Hk0i) (sub_maps 0 0) ?size_traject ?sub_traject // EitS.\nQed.\n\nEnd DiscretizeMap.\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/discretize.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.284724370015191}}
{"text": "(*\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *)\nFrom stdpp Require Import base strings gmap stringmap fin_maps.\n(* Not using iris but importing their ssreflect dependencies *)\nFrom iris.proofmode Require Import tactics.\n\n(* Helper tactics *)\nLtac inv H := inversion H; subst; clear H.\n\nDefinition tag := string.\n\nLocal Instance tag_equiv : Equiv tag := fun s0 s1 => String.eqb s0 s1 = true.\nLocal Instance tag_equivalence : Equivalence (≡@{tag}).\nProof.\n  split.\n  - now move => x; apply String.eqb_refl.\n  - move => x y hxy.\n    now rewrite /equiv /tag_equiv String.eqb_sym.\n  - move => x y z.\n    move => /String.eqb_eq hxy /String.eqb_eq hyz.\n    now apply String.eqb_eq; transitivity y.\nQed.\n\nDefinition loc := positive.\nGlobal Instance loc_dec_eq (l l' : loc) : Decision (l = l') := _.\n\nInductive value : Set :=\n  | IntV (z: Z)\n  | BoolV (b: bool)\n  | NullV\n  | LocV (ℓ : loc).\nLocal Instance value_inhabited : Inhabited value := populate NullV.\n\nSection nested_ind.\n  Local Unset Elimination Schemes.\n\n  Inductive lang_ty :=\n    | IntT\n    | BoolT\n    | NothingT\n    | MixedT\n    | ClassT (exact: bool) (cname: tag) (targs: list lang_ty)\n    | NullT\n    | NonNullT\n    | UnionT (s t: lang_ty)\n    | InterT (s t: lang_ty)\n    | GenT (n: nat)\n    | DynamicT\n    | SupportDynT\n    | ThisT\n  .\n\n  Variable P : lang_ty -> Prop.\n  Hypothesis case_IntT : P IntT.\n  Hypothesis case_BoolT : P BoolT.\n  Hypothesis case_NothingT : P NothingT.\n  Hypothesis case_MixedT : P MixedT.\n  Hypothesis case_ClassT : ∀ exact cname targs,\n    Forall P targs → P (ClassT exact cname targs).\n  Hypothesis case_NullT : P NullT.\n  Hypothesis case_NonNullT : P NonNullT.\n  Hypothesis case_UnionT :  ∀ s t, P s → P t → P (UnionT s t).\n  Hypothesis case_InterT :  ∀ s t, P s → P t → P (InterT s t).\n  Hypothesis case_GenT: ∀ n, P (GenT n).\n  Hypothesis case_DynamicT : P DynamicT.\n  Hypothesis case_SupportDynT : P SupportDynT.\n  Hypothesis case_ThisT : P ThisT.\n\n  Fixpoint lang_ty_ind (t : lang_ty) :=\n    match t with\n    | IntT => case_IntT\n    | BoolT => case_BoolT\n    | NothingT => case_NothingT\n    | MixedT => case_MixedT\n    | ClassT exact cname targs =>\n        let H := (fix fold (xs : list lang_ty) : Forall P xs :=\n          match xs with\n          | nil => List.Forall_nil _\n          | x :: xs => List.Forall_cons _ x xs (lang_ty_ind x) (fold xs)\n          end) targs in\n        case_ClassT exact cname targs H\n    | NullT => case_NullT\n    | NonNullT => case_NonNullT\n    | UnionT s t => case_UnionT s t (lang_ty_ind s) (lang_ty_ind t)\n    | InterT s t => case_InterT s t (lang_ty_ind s) (lang_ty_ind t)\n    | GenT n => case_GenT n\n    | DynamicT => case_DynamicT\n    | SupportDynT => case_SupportDynT\n    | ThisT => case_ThisT\n    end.\nEnd nested_ind.\n\nFixpoint no_this ty : bool :=\n  match ty with\n  | ClassT _ _ σ => List.forallb no_this σ\n  | UnionT A B => no_this A && no_this B\n  | InterT A B => no_this A && no_this B\n  | ThisT => false\n  | _ => true\n  end.\n\n(* A type is bounded by n if any generic that might be\n * present in it is < n\n *)\nInductive bounded (n: nat) : lang_ty → Prop :=\n  | ClassIsBounded exact cname targs :\n      Forall (bounded n) targs → bounded n (ClassT exact cname targs)\n  | UnionIsBounded s t :\n      bounded n s → bounded n t → bounded n (UnionT s t)\n  | InterIsBounded s t :\n      bounded n s → bounded n t → bounded n (InterT s t)\n  | GenIsBounded k:\n      k < n → bounded n (GenT k)\n  | IntIsBounded : bounded n IntT\n  | BoolIsBounded : bounded n BoolT\n  | NothingIsBounded : bounded n NothingT\n  | MixedIsBounded : bounded n MixedT\n  | NullIsBounded : bounded n NullT\n  | NonNullIsBounded : bounded n NonNullT\n  | DynamicIsBounded : bounded n DynamicT\n  | SupportDynIsBounded : bounded n SupportDynT\n  | ThisIsBounded : bounded n ThisT\n.\n\nGlobal Hint Constructors bounded : core.\n\n(* Inversion lemma, so we can name things more easily *)\nLemma boundedI n ty:\n  bounded n ty →\n  match ty with\n  | ClassT _ _ σ => Forall (bounded n) σ\n  | UnionT A B | InterT A B => bounded n A ∧ bounded n B\n  | GenT k => k < n\n  | _ => True\n  end.\nProof. move => h; by inv h. Qed.\n\nLemma bounded_exact n ex0 ex1 t σ:\n  bounded n (ClassT ex0 t σ) → bounded n (ClassT ex1 t σ).\nProof. move => h; inv h; by constructor. Qed.\n\nLemma bounded_ge ty n:\n  bounded n ty → ∀ m, m ≥ n → bounded m ty.\nProof.\n  elim: ty => //=.\n  - move => ? t σ hi /boundedI h m hge.\n    econstructor.\n    rewrite !Forall_lookup in hi, h.\n    rewrite Forall_lookup => k ty hk.\n    eapply hi => //.\n    by eapply h.\n  - move => A B hA hB /boundedI [h0 h1] m hge.\n    by eauto.\n  - move => A B hA hB /boundedI [h0 h1] m hge.\n    by eauto.\n  - move => k /boundedI hlt m hge.\n    constructor; by lia.\nQed.\n\nLemma bounded_rigid exact t start len:\n  bounded (start + len) (ClassT exact t (map GenT (seq start len))).\nProof.\n  constructor.\n  rewrite Forall_lookup => i ty h.\n  apply list_lookup_fmap_inv in h.\n  destruct h as [k [-> h]].\n  rewrite lookup_seq in h; destruct h as [-> h].\n  constructor.\n  by lia.\nQed.\n\n(* To be used with `bounded`: Generics must be always bound *)\nFixpoint subst_ty (targs:list lang_ty) (ty: lang_ty):  lang_ty :=\n  match ty with\n  | ClassT exact cname cargs => ClassT exact cname (subst_ty targs <$> cargs)\n  | UnionT s t => UnionT (subst_ty targs s) (subst_ty targs t)\n  | InterT s t => InterT (subst_ty targs s) (subst_ty targs t)\n  | GenT n => default ty (targs !! n)\n  | _ => ty\n  end.\n\nFixpoint subst_this this ty :=\n  match ty with\n  | ClassT ex cname cargs => ClassT ex cname (subst_this this <$> cargs)\n  | UnionT s t => UnionT (subst_this this s) (subst_this this t)\n  | InterT s t => InterT (subst_this this s) (subst_this this t)\n  | ThisT => this\n  | _ => ty\n  end.\n\nCorollary subst_ty_nil ty : subst_ty [] ty = ty.\nProof.\n  elim: ty => //=.\n  - move => ? t σ hi.\n    f_equal.\n    rewrite Forall_forall in hi.\n    rewrite -{2}(map_id σ).\n    apply map_ext_in => s /elem_of_list_In hin.\n    by apply hi.\n  - by move => ?? -> ->.\n  - by move => ?? -> ->.\nQed.\n\nCorollary map_subst_ty_nil (σ: list lang_ty) : subst_ty [] <$> σ = σ.\nProof.\n  elim: σ => //= hd tl hi.\n  f_equal; first by rewrite subst_ty_nil.\n  by apply hi.\nQed.\n\nCorollary fmap_subst_ty_nil (σ: stringmap lang_ty) : subst_ty [] <$> σ = σ.\nProof.\n  (* TODO: ask PY *)\n  induction σ as [| s ty ftys Hs IH] using map_ind.\n  - by rewrite fmap_empty.\n  - by rewrite fmap_insert IH subst_ty_nil.\nQed.\n\nLemma subst_ty_subst ty l k:\n  bounded (length k) ty →\n  subst_ty l (subst_ty k ty) = subst_ty (subst_ty l <$> k) ty.\nProof.\n  elim: ty => //=.\n  - move => ? t σ hi /boundedI h.\n    f_equal.\n    rewrite -list_fmap_compose.\n    rewrite Forall_forall in hi.\n    apply map_ext_in => s /elem_of_list_In hin.\n    apply hi => //.\n    rewrite Forall_forall in h.\n    by apply h.\n  - move => A B hiA hiB /boundedI [hA hB].\n    by rewrite hiA // hiB.\n  - move => A B hiA hiB /boundedI [hA hB].\n    by rewrite hiA // hiB.\n  - move => n /boundedI hlt.\n    rewrite list_lookup_fmap.\n    destruct (k !! n) as [ ty | ] eqn:hty => //=.\n    apply lookup_lt_is_Some_2 in hlt.\n    rewrite hty in hlt.\n    by elim: hlt.\nQed.\n\nLemma map_subst_ty_subst (j k l: list lang_ty):\n  Forall (bounded (length k)) l →\n  subst_ty j <$> (subst_ty k <$> l) =\n  subst_ty (subst_ty j <$> k) <$> l.\nProof.\n  elim : l => //= hd lt hi hb.\n  apply Forall_cons_1 in hb as [].\n  rewrite subst_ty_subst => //.\n  f_equal.\n  by rewrite list_fmap_compose -/subst_ty list_fmap_id -/fmap hi.\nQed.\n\nLemma fmap_subst_ty_subst j k (l: stringmap lang_ty):\n  map_Forall (λ _, bounded (length k)) l →\n  subst_ty j <$> (subst_ty k <$> l) =\n  subst_ty (subst_ty j <$> k) <$> l.\nProof.\n  move => hwf.\n  move: j k hwf.\n  induction l as [| s ty ftys Hs IH] using map_ind => j k hwf;\n    first by rewrite !fmap_empty.\n  rewrite map_Forall_insert // in hwf.\n  destruct hwf as [hhd htl].\n  by rewrite !fmap_insert subst_ty_subst // IH.\nQed.\n\nLemma bounded_subst n ty:\n  bounded n ty →\n  ∀ m targs, length targs = n →\n  Forall (bounded m) targs →\n  bounded m (subst_ty targs ty).\nProof.\n  elim: ty => //=.\n  - move => ? t σ hi /boundedI hb m σ0 hlen hσ0.\n    constructor.\n    rewrite Forall_lookup => k ty hk.\n    apply list_lookup_fmap_inv in hk as [ty0 [-> hty0]].\n    rewrite Forall_lookup in hi.\n    eapply hi => //.\n    rewrite Forall_lookup in hb.\n    by eapply hb.\n  - move => s t his hit /boundedI [hs ht] m σ0 hlen hσ0.\n    constructor; by eauto.\n  - move => s t his hit /boundedI [hs ht] m σ0 hlen hσ0.\n    constructor; by eauto.\n  - move => k /boundedI hlt m σ0 hlen hσ0.\n    rewrite -hlen in hlt.\n    rewrite Forall_lookup in hσ0.\n    apply (hσ0 k).\n    apply lookup_lt_is_Some_2 in hlt.\n    destruct (σ0 !! k) as [ ty | ] eqn:hty => //.\n    by elim: hlt.\nQed.\n\nLemma bounded_subst_this n ty this:\n  bounded n ty →\n  bounded n this →\n  bounded n (subst_this this ty).\nProof.\n  elim : ty => //=.\n  - move => ? t σ hi /boundedI hb hthis.\n    constructor.\n    rewrite Forall_forall => ty /elem_of_list_fmap hin.\n    destruct hin as [ty' [-> hin]].\n    rewrite Forall_forall in hi.\n    apply hi in hin => //.\n    rewrite Forall_forall in hb.\n    by apply hb.\n  - move => s t hs ht /boundedI [??] hthis.\n    constructor; by eauto.\n  - move => s t hs ht /boundedI [??] hthis.\n    constructor; by eauto.\nQed.\n\nDefinition var := string.\nGlobal Instance var_dec_eq (l l' : var) : Decision (l = l') := _.\n\nInductive binop :=\n  | PlusO | MinusO | TimesO | DivO | LtO | GtO | EqO\n.\n\nInductive uniop := | NotO.\n\nInductive expr :=\n  | IntE (z: Z)\n  | BoolE (b: bool)\n  | NullE\n  | BinOpE (op: binop) (e1: expr) (e2: expr)\n  | UniOpE (op: uniop) (e: expr)\n  | VarE (v: var)\n  | ThisE (* $this *)\n  | UpcastE (e: expr) (ty: lang_ty)\n.\n\nFixpoint subst_expr (σ:list lang_ty) (expr: expr) :=\n  match expr with\n  | BinOpE op e1 e2 => BinOpE op (subst_expr σ e1) (subst_expr σ e2)\n  | UniOpE op e => UniOpE op (subst_expr σ e)\n  | UpcastE e ty => UpcastE (subst_expr σ e) (subst_ty σ ty)\n  | _ => expr\n  end.\n\nLemma subst_expr_nil expr : subst_expr [] expr = expr.\nProof.\n  induction expr as [ | | | op e1 hi1 e2 hi2 | op e hi | | | e hi ty] => //=.\n  - by rewrite hi1 hi2.\n  - by rewrite hi.\n  - by rewrite hi subst_ty_nil.\nQed.\n\nLemma map_subst_expr_nil (l : list expr) : subst_expr [] <$> l = l.\nProof.\n  induction l as [ | hd tl hi] => //.\n  by rewrite fmap_cons subst_expr_nil hi.\nQed.\n\nLemma fmap_subst_expr_nil (l : stringmap expr) : subst_expr [] <$> l = l.\nProof.\n  induction l as [| s e es Hs IH] using map_ind; first by rewrite fmap_empty.\n  by rewrite fmap_insert subst_expr_nil IH.\nQed.\n\nInductive expr_bounded (n: nat) : expr → Prop :=\n  | IntEBounded z : expr_bounded n (IntE z)\n  | BoolEBounded b : expr_bounded n (BoolE b)\n  | NullEBounded : expr_bounded n NullE\n  | BinOpEBounded op e1 e2:\n      expr_bounded n e1 →\n      expr_bounded n e2 →\n      expr_bounded n (BinOpE op e1 e2)\n  | UniOpEBounded op e:\n      expr_bounded n e →\n      expr_bounded n (UniOpE op e)\n  | VarEBounded v : expr_bounded n (VarE v)\n  | ThisEBounded : expr_bounded n ThisE\n  | UpcastEBounded e ty : expr_bounded n e →\n      bounded n ty →\n      expr_bounded n (UpcastE e ty)\n.\n\nLemma subst_expr_subst k l expr :\n  expr_bounded (length l) expr →\n  subst_expr k (subst_expr l expr) = subst_expr (subst_ty k <$> l) expr.\nProof.\n  elim: expr => //=.\n  - move => op e1 hi1 e2 hi2 hb.\n    inv hb.\n    by rewrite hi1 // hi2.\n  - move => op e hi hb.\n    inv hb.\n    by rewrite hi.\n  - move => e hi ty hb.\n    inv hb.\n    by rewrite hi // subst_ty_subst.\nQed.\n\nLemma map_subst_expr_subst (j k: list lang_ty) (l: list expr):\n  Forall (expr_bounded (length k)) l →\n  subst_expr j <$> (subst_expr k <$> l) =\n  subst_expr (subst_ty j <$> k) <$> l.\nProof.\n  elim: l => //= hd tl hi hb.\n  apply Forall_cons_1 in hb as [].\n  f_equal; first by rewrite subst_expr_subst.\n  by rewrite list_fmap_compose -/subst_ty list_fmap_id -/fmap hi.\nQed.\n\nLemma fmap_subst_expr_subst j k (l: stringmap expr):\n  map_Forall (λ _, expr_bounded (length k)) l →\n  subst_expr j <$> (subst_expr k <$> l) =\n  subst_expr (subst_ty j <$> k) <$> l.\nProof.\n  move => hwf.\n  move: j k hwf.\n  induction l as [| s e es Hs IH] using map_ind => j k hwf;\n    first by rewrite !fmap_empty.\n  rewrite map_Forall_insert // in hwf.\n  destruct hwf as [hhd htl].\n  by rewrite !fmap_insert subst_expr_subst // IH.\nQed.\n\nLemma expr_bounded_subst n expr:\n  expr_bounded n expr →\n  ∀ m targs, length targs = n →\n  Forall (bounded m) targs →\n  expr_bounded m (subst_expr targs expr).\nProof.\n  elim: expr; try (intros; by constructor).\n  - move => op e1 hi1 e2 hi2 h m σ hlen hF.\n    inv h.\n    constructor; first by apply hi1.\n    by apply hi2.\n  - move => op e hi h m σ hlen hF.\n    inv h.\n    constructor; by apply hi.\n  - move => e hi ty h m σ hlen hF.\n    inv h.\n    constructor; first by apply hi.\n    by apply bounded_subst with (length σ).\nQed.\n\nInductive runtime_check :=\n  | RCTag of tag\n  | RCInt\n  | RCBool\n  | RCNull\n  | RCNonNull\n.\n\nInductive cmd : Set :=\n  | SkipC\n  | SeqC (fstc: cmd) (sndc: cmd)\n  | LetC (lhs: var) (e: expr)\n  | IfC (cond: expr) (thn: cmd) (els: cmd)\n  | CallC (lhs: var) (recv: expr) (name: string) (args: stringmap expr)\n  (* When performing New, one can specify the type parameter, or\n   * expect them to be infered (and pass nothing).\n   * It is not possible to only pass some of them at the moment, it is\n   * an all or nothing situation.\n   *)\n  | NewC (lhs: var) (class_name: tag) (targs: option (list lang_ty)) (args: stringmap expr)\n  | GetC (lhs: var) (recv: expr) (name: string)\n  | SetC (recv: expr) (fld: string) (rhs: expr)\n      (* tag test \"if ($v is C<_>) { ... }\".  *)\n  | RuntimeCheckC (v : var) (rc: runtime_check) (thn els: cmd)\n  | ErrorC\n.\n\nFixpoint subst_cmd (σ:list lang_ty) (cmd: cmd) :=\n  match cmd with\n  | SkipC => SkipC\n  | SeqC fst snd => SeqC (subst_cmd σ fst) (subst_cmd σ snd)\n  | LetC lhs e => LetC lhs (subst_expr σ e)\n  | IfC cond thn els => IfC (subst_expr σ cond) (subst_cmd σ thn) (subst_cmd σ els)\n  | CallC lhs recv name args =>\n      CallC lhs (subst_expr σ recv) name (subst_expr σ <$> args)\n  | NewC lhs C oσ args =>\n      NewC lhs C ((λ (targs: list lang_ty), subst_ty σ <$> targs) <$> oσ) (subst_expr σ <$> args)\n  | GetC lhs recv name => GetC lhs (subst_expr σ recv) name\n  | SetC recv fld rhs => SetC (subst_expr σ recv) fld (subst_expr σ rhs)\n  | RuntimeCheckC v rc thn els =>\n      RuntimeCheckC v rc (subst_cmd σ thn) (subst_cmd σ els)\n  | ErrorC => ErrorC\n  end.\n\nLemma subst_cmd_nil cmd : subst_cmd [] cmd = cmd.\nProof.\n  induction cmd as [ | fst hi0 snd hi1 | lhs e | ? thn hi0 els hi1\n    | lhs recv name args | lhs C oσ args | lhs recv name\n    | recv fld rhs | v rc thn hi0 els hi1 | ] => //=.\n  - by rewrite hi0 hi1.\n  - by rewrite subst_expr_nil.\n  - by rewrite subst_expr_nil hi0 hi1.\n  - by rewrite subst_expr_nil fmap_subst_expr_nil.\n  - f_equal; last by rewrite fmap_subst_expr_nil.\n    case: oσ => [ σ0 | ] //=.\n    by rewrite map_subst_ty_nil.\n  - by rewrite subst_expr_nil.\n  - by rewrite !subst_expr_nil.\n  - by rewrite hi0 hi1.\nQed.\n\nInductive cmd_bounded (n: nat) : cmd → Prop :=\n  | SkipBounded : cmd_bounded n SkipC\n  | SeqBounded fstc sndc : cmd_bounded n fstc →\n      cmd_bounded n sndc → cmd_bounded n (SeqC fstc sndc)\n  | LetBounded lhs e : expr_bounded n e → cmd_bounded n (LetC lhs e)\n  | IfBounded cond thn els : expr_bounded n cond →\n      cmd_bounded n thn → cmd_bounded n els → cmd_bounded n (IfC cond thn els)\n  | CallBounded lhs recv name args:\n      expr_bounded n recv →\n      map_Forall (λ _, expr_bounded n) args →\n      cmd_bounded n (CallC lhs recv name args)\n  | NewBounded lhs C oσ args:\n      match oσ with\n      | None => True\n      | Some σ => Forall (bounded n) σ\n      end →\n      map_Forall (λ _, expr_bounded n) args →\n      cmd_bounded n (NewC lhs C oσ args)\n  | GetBounded lhs recv name: expr_bounded n recv →\n      cmd_bounded n (GetC lhs recv name)\n  | SetBounded recv fld rhs : expr_bounded n recv →\n      expr_bounded n rhs →\n      cmd_bounded n (SetC recv fld rhs)\n  | RuntimeCheckBounded v rc thn els:\n      cmd_bounded n thn →\n      cmd_bounded n els →\n      cmd_bounded n (RuntimeCheckC v rc thn els)\n  | ErrorBounded : cmd_bounded n ErrorC\n.\n\nLemma cmd_boundedI n cmd:\n  cmd_bounded n cmd →\n  match cmd with\n  | IfC e c0 c1 => expr_bounded n e ∧ cmd_bounded n c0 ∧ cmd_bounded n c1\n  | GetC _ e _\n  | LetC _ e => expr_bounded n e\n  | SetC e0 _ e1 => expr_bounded n e0 ∧ expr_bounded n e1\n  | CallC _ e _ args =>\n      expr_bounded n e ∧ map_Forall (λ _, expr_bounded n) args\n  | NewC _ _ oσ args =>\n      match oσ with\n      | None => True\n      | Some σ => Forall (bounded n) σ\n      end ∧ map_Forall (λ _, expr_bounded n) args\n  | SeqC c0 c1\n  | RuntimeCheckC _ _ c0 c1 => cmd_bounded n c0 ∧ cmd_bounded n c1\n  | _ => True\n  end.\nProof. move => h; by inv h. Qed.\n\nLemma subst_cmd_cmd k l cmd :\n  cmd_bounded (length l) cmd →\n  subst_cmd k (subst_cmd l cmd) = subst_cmd (subst_ty k <$> l) cmd.\nProof.\n  elim: cmd => /=.\n  - by idtac.\n  - move => ? hi0 ? hi1 /cmd_boundedI [h0 h1].\n    by rewrite hi0 // hi1.\n  - move => lhs e /cmd_boundedI hb.\n    by rewrite subst_expr_subst.\n  - move => ?? hi0 ? hi1 /cmd_boundedI [? [? ?]].\n    by rewrite subst_expr_subst // hi0 // hi1.\n  - move => ???? /cmd_boundedI [??].\n    by rewrite fmap_subst_expr_subst // subst_expr_subst.\n  - move => ?? σ ? /cmd_boundedI [h0 ?].\n    case: σ h0 => [ σ | ] h0 //=.\n    + rewrite map_subst_ty_subst //.\n      by rewrite fmap_subst_expr_subst.\n    + by rewrite fmap_subst_expr_subst.\n  - move => ??? /cmd_boundedI ?.\n    by rewrite subst_expr_subst.\n  - move => ??? /cmd_boundedI [??].\n    by rewrite !subst_expr_subst.\n  - move => ??? hi0 ? hi1 /cmd_boundedI [??].\n    by rewrite hi0 // hi1.\n  - by idtac.\nQed.\n\nLemma cmd_bounded_subst n cmd:\n  cmd_bounded n cmd →\n  ∀ m targs, length targs = n →\n  Forall (bounded m) targs →\n  cmd_bounded m (subst_cmd targs cmd).\nProof.\n  elim: cmd => /=.\n  - move => ?????; by constructor.\n  - move => ? hi0 ? hi1 /cmd_boundedI [??] m σ hlen hF.\n    constructor; first by apply hi0.\n    by apply hi1.\n  - move  => ?? /cmd_boundedI hb m σ hlen hF.\n    rewrite -hlen in hb.\n    constructor; by eapply expr_bounded_subst.\n  - move => ?? hi0 ? hi1 /cmd_boundedI [he [??]] m σ hlen hF.\n    rewrite -hlen in he.\n    constructor; first by eapply expr_bounded_subst.\n    + by apply hi0.\n    + by apply hi1.\n  - move => ???? /cmd_boundedI [h hs] m σ hlen hF.\n    rewrite -hlen in h.\n    constructor; first by eapply expr_bounded_subst.\n    rewrite map_Forall_lookup => i ?.\n    rewrite lookup_fmap_Some => [[e [<- he]]].\n    apply expr_bounded_subst with (length σ) => //.\n    apply hs in he.\n    by rewrite hlen.\n  - move => ?? oσ ? /cmd_boundedI [h ?] m σ hlen hF.\n    constructor.\n    { case: oσ h => [ σ0 | ] //= h.\n      rewrite Forall_lookup => ? hi hk.\n      apply list_lookup_fmap_inv in hk as [ty [-> hty]].\n      apply bounded_subst with (length σ) => //.\n      rewrite Forall_lookup in h.\n      rewrite hlen.\n      by eapply h.\n    }\n    rewrite map_Forall_lookup => i ?.\n    rewrite lookup_fmap_Some => [[e [<- he]]].\n    apply expr_bounded_subst with (length σ) => //.\n    rewrite hlen.\n    by eauto.\n  - move => ??? /cmd_boundedI h m σ hlen hF.\n    rewrite -hlen in h.\n    constructor; by eapply expr_bounded_subst.\n  - move => ??? /cmd_boundedI [h0 h1] m σ hlen hF.\n    rewrite -hlen in h0.\n    constructor; first by eapply expr_bounded_subst.\n    by eapply expr_bounded_subst.\n  - move => ??? hi0 ? hi1 /cmd_boundedI [??] m σ hlen hF.\n    constructor; first by apply hi0.\n    by apply hi1.\n  - move => ?????; by constructor.\nQed.\n\nInductive visibility := Public | Private.\n\nRecord methodDef := {\n  methodvisibility : visibility;\n  methodargs: stringmap lang_ty;\n  methodrettype: lang_ty;\n  methodbody: cmd;\n  methodret: expr;\n}.\n\nDefinition no_this_mdef mdef :=\n  map_Forall (λ _argname, no_this) mdef.(methodargs) ∧\n  no_this mdef.(methodrettype)\n.\n\nDefinition subst_mdef targs mdef : methodDef := {|\n    methodvisibility := mdef.(methodvisibility);\n    methodargs := subst_ty targs <$> mdef.(methodargs);\n    methodrettype := subst_ty targs mdef.(methodrettype);\n    methodbody := subst_cmd targs mdef.(methodbody);\n    methodret := subst_expr targs mdef.(methodret);\n  |}.\n\nLemma subst_mdef_nil mdef : subst_mdef [] mdef = mdef.\nProof.\n  rewrite /subst_mdef subst_ty_nil fmap_subst_ty_nil subst_cmd_nil subst_expr_nil.\n  by destruct mdef.\nQed.\n\nDefinition mdef_bounded n mdef : Prop :=\n  map_Forall (λ _argname, bounded n) mdef.(methodargs) ∧ bounded n mdef.(methodrettype) ∧\n  cmd_bounded n mdef.(methodbody) ∧\n  expr_bounded n mdef.(methodret).\n\nLemma subst_mdef_mdef k l mdef :\n  mdef_bounded (length l) mdef →\n  subst_mdef k (subst_mdef l mdef) = subst_mdef (subst_ty k <$> l) mdef.\nProof.\n  rewrite /mdef_bounded map_Forall_lookup => [[hargs [hret [hbody hmret]]]].\n  rewrite /subst_mdef; destruct mdef as [? args ret body ?]; f_equiv => //=.\n  - by rewrite fmap_subst_ty_subst.\n  - by rewrite subst_ty_subst.\n  - by rewrite subst_cmd_cmd.\n  - by rewrite subst_expr_subst.\nQed.\n\nLemma mdef_bounded_subst n mdef:\n  mdef_bounded n mdef →\n  ∀ m targs, length targs = n →\n  Forall (bounded m) targs →\n  mdef_bounded m (subst_mdef targs mdef).\nProof.\n  move => [/map_Forall_lookup hargs [hret [hbody hmret]]] m σ hl hf.\n  rewrite /mdef_bounded /subst_mdef /=; split.\n  { rewrite map_Forall_lookup => k ty hty.\n    apply lookup_fmap_Some in hty as [ty' [ <- hm]].\n    apply bounded_subst with n => //.\n    by eapply hargs.\n  }\n  split; first by apply bounded_subst with n.\n  split; first by apply cmd_bounded_subst with n.\n  by apply expr_bounded_subst with n.\nQed.\n\nInductive variance : Set :=\n  | Invariant\n  | Covariant\n  | Contravariant\n.\n\nDefinition neg_variance v :=\n  match v with\n  | Invariant => Invariant\n  | Covariant => Contravariant\n  | Contravariant => Covariant\n  end\n.\n\nLemma neg_variance_idem v : neg_variance (neg_variance v) = v.\nProof. by destruct v. Qed.\n\nLemma neg_variance_fmap_idem (vs: list variance) : neg_variance <$> (neg_variance <$> vs) = vs.\nProof.\n  induction vs as [ | v vs hi] => //.\n  by rewrite !fmap_cons neg_variance_idem hi.\nQed.\n\nDefinition not_cov v :=\n  match v with\n  | Invariant | Contravariant => true\n  | Covariant => false\n  end\n.\n\nDefinition not_contra v :=\n  match v with\n  | Invariant | Covariant => true\n  | Contravariant => false\n  end\n.\n\n(* S <: T *)\nDefinition constraint := (lang_ty * lang_ty)%type.\n\nDefinition bounded_constraint n c := bounded n c.1 ∧ bounded n c.2.\n\nLemma bounded_constraints_ge Δ n m:\n  Forall (bounded_constraint n) Δ → m ≥ n →\n  Forall (bounded_constraint m) Δ.\nProof.\n  move => /Forall_lookup h hge.\n  rewrite Forall_lookup => i c hc.\n  apply h in hc as [h0 h1].\n  split; by eapply bounded_ge.\nQed.\n\nRecord classDef := {\n  (* variance of the generics *)\n  generics: list variance;\n  (* sets of constraints. All generics in this set must be bound\n   * by the `generics` list above.\n   *)\n  constraints : list constraint;\n  superclass: option (tag * list lang_ty);\n  classfields : stringmap (visibility * lang_ty);\n  classmethods : stringmap methodDef;\n}.\n\n(* \"Identity\" substitution for n generics *)\nDefinition gen_targs n : list lang_ty := map GenT (seq 0 n).\n\nLemma lookup_gen_targs_lt :\n  ∀ n pos, pos < n → gen_targs n !! pos = Some (GenT pos).\nProof.\n  move => n pos h.\n  by rewrite /gen_targs list_lookup_fmap lookup_seq_lt.\nQed.\n\nLemma lookup_gen_targs_ge:\n  ∀ n pos, n <= pos → gen_targs n !! pos = None.\nProof.\n  move => n pos h.\n  by rewrite /gen_targs list_lookup_fmap lookup_seq_ge.\nQed.\n\nLemma lookup_gen_targs:\n  ∀ n pos ty, gen_targs n !! pos = Some ty -> ty = GenT pos.\nProof.\n  move => n pos ty.\n  rewrite /gen_targs => h.\n  apply list_lookup_fmap_inv in h.\n  destruct h as [? [-> h]].\n  rewrite lookup_seq in h.\n  by destruct h as [-> ?].\nQed.\n\nLemma length_gen_targs n : length (gen_targs n) = n.\nProof. by rewrite /gen_targs map_length seq_length. Qed.\n\nLemma gen_targs_has_no_this n: Forall no_this (gen_targs n).\nProof.\n  rewrite Forall_lookup => k ty hty.\n  apply lookup_gen_targs in hty.\n  by rewrite hty.\nQed.\n\n(* Short-hand for subst_this + gen_thargs, used mostly for interpretation *)\nDefinition subst_gen t tdef ty :=\n  let σ := gen_targs (length tdef.(generics)) in\n  subst_this (ClassT true t σ) ty\n.\n\nLemma subst_ty_has_no_this σ ty:\n  no_this ty → Forall no_this σ → no_this (subst_ty σ ty).\nProof.\n  elim: ty => //=.\n  - move => ?? σ0 hi h hσ0.\n    apply forallb_True in h.\n    apply forallb_True.\n    rewrite Forall_lookup => k ty hSome.\n    apply list_lookup_fmap_inv in hSome as [ty0 [-> hty0]].\n    rewrite Forall_lookup in h.\n    rewrite Forall_lookup in hi.\n    assert (hty0_ := hty0).\n    apply h in hty0_; clear h.\n    by apply hi in hty0.\n  - move => s t hs ht h hσ0.\n    apply andb_prop_elim in h as [h0 h1].\n    apply andb_prop_intro; split; by firstorder.\n  - move => s t hs ht h hσ0.\n    apply andb_prop_elim in h as [h0 h1].\n    apply andb_prop_intro; split; by firstorder.\n  - move => k _ hσ; rewrite Forall_lookup in hσ.\n    destruct (σ !! k) as [ ty0 | ] eqn:hty0; last done.\n    by apply hσ in hty0.\nQed.\n\nLemma subst_ty_has_no_this_map (σ σ0: list lang_ty):\n  Forall no_this σ → Forall no_this σ0 → Forall no_this (subst_ty σ <$> σ0).\nProof.\n  move => h.\n  induction σ0 as [ | hd tl hi] => h0; first done.\n  apply Forall_cons in h0 as [hhd htl].\n  constructor.\n  { by apply subst_ty_has_no_this. }\n  by apply hi.\nQed.\n\nLemma subst_this_has_no_this ty:\n  ∀ this, no_this this → no_this (subst_this this ty).\nProof.\n  elim: ty => //=.\n  - move => _exact C σ hi this hthis.\n    apply forallb_True.\n    rewrite Forall_lookup => k ty hSome.\n    apply list_lookup_fmap_inv in hSome as [ty0 [-> hty0]].\n    rewrite Forall_lookup in hi.\n    assert (hty0_ := hty0).\n    by apply hi with (this := this) in hty0_.\n  - move => s t hs ht this hthis.\n    apply andb_prop_intro.\n    firstorder.\n  - move => s t hs ht this hthis.\n    apply andb_prop_intro.\n    firstorder.\nQed.\n\nLemma subst_this_no_this_id ty:\n  ∀ this, no_this ty → subst_this this ty = ty.\nProof.\n  elim: ty => //=.\n  - move => ? t σ hi this /forallb_True hσ.\n    f_equal.\n    apply list_eq => k.\n    rewrite !Forall_lookup in hi, hσ.\n    rewrite list_lookup_fmap.\n    destruct (σ !! k) as [ ty | ] eqn:hty; last done.\n    rewrite /= (hi k ty hty); first done.\n    by eapply hσ.\n  - move => s t hs ht this /andb_prop_elim [hnos hnot].\n    f_equal; by eauto.\n  - move => s t hs ht this /andb_prop_elim [hnos hnot].\n    f_equal; by eauto.\nQed.\n\nLemma subst_ty_id n ty:\n  bounded n ty →\n  subst_ty (gen_targs n) ty = ty.\nProof.\n  elim : ty => //=.\n  - move => ? t σ hi /boundedI hf; f_equal.\n    rewrite Forall_forall in hi.\n    rewrite -{2}(map_id σ).\n    apply map_ext_in => /= s /elem_of_list_In hin.\n    apply hi => //.\n    rewrite Forall_forall in hf.\n    by apply hf.\n  - move => s t his hit /boundedI [hs ht]; f_equal; by eauto.\n  - move => s t his hit /boundedI [hs ht]; f_equal; by eauto.\n  - move => k /boundedI hlt.\n    by rewrite lookup_gen_targs_lt.\nQed.\n\nLemma subst_tys_id n σ:\n  Forall (bounded n) σ →\n  subst_ty (gen_targs n) <$> σ = σ.\nProof.\n  elim: σ n => //= hd tl hi n hf.\n  f_equal.\n  - apply subst_ty_id.\n    apply Forall_inv in hf.\n    by apply hf.\n  - apply hi.\n    by apply Forall_inv_tail in hf.\nQed.\n\nLemma fmap_subst_tys_id n (m: stringmap lang_ty):\n  map_Forall (λ _, bounded n) m →\n  subst_ty (gen_targs n) <$> m = m.\nProof.\n  revert n.\n  induction m as [| s ty ftys Hs IH] using map_ind => n hm; first by rewrite fmap_empty.\n  rewrite fmap_insert; f_equal.\n  - apply subst_ty_id.\n    apply hm with s.\n    by rewrite lookup_insert.\n  - apply IH.\n    rewrite map_Forall_lookup => k tk hk.\n    apply hm with k.\n    rewrite lookup_insert_ne // => heq; subst.\n    by rewrite Hs in hk.\nQed.\n\nLemma subst_ty_gen_targs n targs :\n  length targs = n →\n  subst_ty targs <$> (gen_targs n) = targs.\nProof.\n  move => hlen.\n  apply nth_ext with NothingT NothingT.\n  - by rewrite map_length length_gen_targs.\n  - rewrite map_length length_gen_targs => k hk.\n    rewrite !nth_lookup.\n    f_equal.\n    rewrite list_lookup_fmap lookup_gen_targs_lt => //=.\n    rewrite -hlen in hk.\n    apply lookup_lt_is_Some_2 in hk.\n    destruct (targs !! k) => //=.\n    by elim hk.\nQed.\n\nLemma subst_expr_gen_targs n expr:\n  expr_bounded n expr →\n  subst_expr (gen_targs n) expr = expr.\nProof.\n  elim: expr => //=.\n  - move => op e1 hi1 e2 hi2 h; inv h.\n    by rewrite hi1 // hi2.\n  - move => op e hi h; inv h.\n    by rewrite hi.\n  - move => e hi ty h; inv h.\n    by rewrite subst_ty_id // hi.\nQed.\n\nLemma fmap_subst_exprs_id n (m: stringmap expr):\n  map_Forall (λ _, expr_bounded n) m →\n  subst_expr (gen_targs n) <$> m = m.\nProof.\n  revert n.\n  induction m as [| s e es Hs IH] using map_ind => n hm; first by rewrite fmap_empty.\n  rewrite fmap_insert; f_equal.\n  - apply subst_expr_gen_targs.\n    apply hm with s.\n    by rewrite lookup_insert.\n  - apply IH.\n    rewrite map_Forall_lookup => k tk hk.\n    apply hm with k.\n    rewrite lookup_insert_ne // => heq; subst.\n    by rewrite Hs in hk.\nQed.\n\nLemma subst_cmd_gen_targs n cmd :\n  cmd_bounded n cmd →\n  subst_cmd (gen_targs n) cmd = cmd.\nProof.\n  elim : cmd => /=.\n  - by idtac.\n  - move => ? hi0 ? hi1 /cmd_boundedI [??].\n    by rewrite hi0 // hi1.\n  - move => ?? /cmd_boundedI ?.\n    by rewrite subst_expr_gen_targs.\n  - move => ?? hi0 ? hi1 /cmd_boundedI [? [??]].\n    by rewrite subst_expr_gen_targs // hi0 // hi1.\n  - move => ???? /cmd_boundedI [??].\n    by rewrite subst_expr_gen_targs // fmap_subst_exprs_id.\n  - move => ?? oσ ? /cmd_boundedI [h ?].\n    f_equal; last by rewrite fmap_subst_exprs_id.\n    case: oσ h => [ σ | ] //= hσ.\n    by rewrite subst_tys_id.\n  - move => ??? /cmd_boundedI h.\n    by rewrite subst_expr_gen_targs.\n  - move => ??? /cmd_boundedI [??].\n    by rewrite !subst_expr_gen_targs.\n  - move => ??? hi0 ? hi1 /cmd_boundedI [??].\n    by rewrite hi0 // hi1.\n  - by idtac.\nQed.\n\nLemma subst_mdef_gen_targs n mdef :\n  mdef_bounded n mdef →\n  subst_mdef (gen_targs n) mdef = mdef.\nProof.\n  rewrite /mdef_bounded /subst_mdef.\n  move => [hargs [hret [hbody hmret]]].\n  rewrite subst_ty_id //.\n  rewrite fmap_subst_tys_id //.\n  rewrite subst_cmd_gen_targs //.\n  rewrite subst_expr_gen_targs //.\n  by destruct mdef.\nQed.\n\nLemma bounded_gen_targs n: Forall (bounded n) (gen_targs n).\nProof.\n  rewrite Forall_forall => ty.\n  rewrite /gen_targs => h.\n  apply elem_of_list_fmap_2 in h as [ k [-> hk]].\n  constructor.\n  rewrite elem_of_seq /= in hk.\n  by destruct hk.\nQed.\n\nLemma bounded_forall_ge n σ:\n  Forall (bounded n) σ →\n  ∀ m, m ≥ n → Forall (bounded m) σ.\nProof.\n  move/Forall_lookup => h m hge.\n  rewrite Forall_lookup => k ty hk.\n  eapply bounded_ge; by eauto.\nQed.\n", "meta": {"author": "facebookresearch", "repo": "shack", "sha": "e51cfcd3e72a0941feb337f9e152f6c429f3af63", "save_path": "github-repos/coq/facebookresearch-shack", "path": "github-repos/coq/facebookresearch-shack/shack-e51cfcd3e72a0941feb337f9e152f6c429f3af63/theories/lang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.284724370015191}}
{"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 ZArith.\nImport ListNotations.\n\nFrom compcert.cfrontend Require Csyntax Ctypes Cop.\nFrom compcert.common Require Import Values AST Memdata.\nFrom compcert.lib Require Import Integers.\n\nDefinition well_chunk_Z (chunk: memory_chunk):Z := \n  match chunk with\n  | Mint8unsigned => 1\n  | Mint16unsigned => 2\n  | Mint32 => 4\n  | Mint64 => 8\n  | _ => 10\n  end.\n\nDefinition memory_chunk_to_valu32 (chunk: memory_chunk): val := \n  Vint (Int.repr (well_chunk_Z chunk)). (**r well_chunk implies align_chunk, so we didn't need align_chunk, but we must prove a lemma! *)\n\nDefinition memory_chunk_to_valu32_upbound (chunk: memory_chunk): val :=\n  Vint (Int.repr (Int.max_unsigned-(well_chunk_Z chunk))).\n\nDefinition chunk_eqb (c1 c2: memory_chunk) : bool :=\n  match c1, c2 with\n  | Mint8signed, Mint8signed\n  | Mint8unsigned, Mint8unsigned\n  | Mint16signed, Mint16signed\n  | Mint16unsigned, Mint16unsigned\n  | Mint32, Mint32\n  | Mint64, Mint64\n  | Mfloat32, Mfloat32\n  | Mfloat64, Mfloat64\n  | Many32, Many32\n  | Many64, Many64 => true\n  | _, _ => false\n  end.\n\nLemma chunk_eqb_true:\n  forall x y, x = y <-> chunk_eqb x y = true.\nProof.\n  destruct x, y; simpl; intuition congruence.\nQed.\n\nLemma chunk_eqb_false:\n  forall x y, x <> y <-> chunk_eqb x y = false.\nProof.\n  destruct x, y; simpl; intuition congruence.\nQed.\n\nDefinition is_well_chunkb (chunk: memory_chunk) : bool :=\n  match chunk with\n  | Mint8unsigned | Mint16unsigned | Mint32 | Mint64 => true\n  | _ => false\n  end.\n\nDefinition is_vint_or_vlong_chunk (chunk: memory_chunk) (v: val): bool :=\n  match chunk, v with\n  | Mint8unsigned, Vint _\n  | Mint16unsigned, Vint _\n  | Mint32, Vint _\n  | Mint64, Vlong _  => true\n  | _, _ => false\n  end.\n\nDefinition _to_vlong (v: val): option val :=\n  match v with\n  | Vlong n => Some (Vlong n) (**r Mint64 *)\n  | Vint  n => Some (Vlong (Int64.repr (Int.unsigned n))) (**r Mint8unsigned, Mint16unsigned, Mint32 *) (* (u64) v *)\n  | _       => None\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 => Vint (Int.zero_ext 8 (Int.repr (Int64.unsigned n)))\n    | Mint16unsigned => Vint (Int.zero_ext 16 (Int.repr (Int64.unsigned n)))\n    | Mint32 => Vint (Int.repr (Int64.unsigned n))\n    | Mint64 => Vlong n\n    | _      => Vundef\n    end\n  | _       => Vundef\n  end.\n\nDefinition vint_to_vint_or_vlong (chunk: memory_chunk) (v: val): val :=\n  match v with\n  | Vint n =>\n    match chunk with\n    | Mint8unsigned => (Vint (Int.zero_ext 8 n))\n    | Mint16unsigned => (Vint (Int.zero_ext 16 n))\n    | Mint32 => Vint n\n    | Mint64 => (Vlong (Int64.repr (Int.signed n)))\n    | _      => Vundef\n    end\n  | _       => Vundef\n  end.", "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/comm/rBPFAST.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.2846499133109315}}
{"text": "Require Import\n        Coq.Vectors.Vector\n        Coq.Vectors.VectorDef.\n\nRequire Import\n        Fiat.Common.BoundedLookup.\n\nImport Vectors.VectorDef.VectorNotations.\nLocal Open Scope vector_scope.\nLocal Open Scope string_scope.\n\nDefinition EnumType\n           {len : nat}\n           {A : Type}\n           (ta : t A (S len)) := Fin.t (S len).\n\nDefinition EnumType_inj_BoundedIndex {len} {A} {ta}\n           (e : @EnumType len A ta) : BoundedIndex ta :=\n   {| indexb := {| ibound := e; boundi := eq_refl |} |}.\n\nDefinition BoundedIndex_inj_EnumType {len} {A} {ta}\n           (idx : BoundedIndex ta) : @EnumType len A ta :=\n  idx.(indexb).(ibound).\n\nCoercion EnumType_inj_BoundedIndex : EnumType >-> BoundedIndex.\n\nNotation \"``` idx\" := (BoundedIndex_inj_EnumType ``idx) (at level 0).\n\nGlobal Arguments EnumType {len} {A} ta%vector_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/Common/EnumType.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.2846499070912027}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\nRequire Import bedrock2.Semantics.\nRequire Import bedrock2.Map.Separation.\nRequire Import bedrock2.Array bedrock2.Scalars.\nRequire Import coqutil.Map.Interface.\nRequire Import coqutil.Word.Interface.\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 Equivalent.\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 {listZ : rep.rep base_listZ}.\n  Existing Instance rep.Z.\n\n  (* relation that states whether a fiat-crypto value and a bedrock2 value are\n     equivalent in a given bedrock2 context *)\n  Fixpoint equivalent_base {t}\n    : base.interp t -> (* fiat-crypto value *)\n      base_rtype t -> (* bedrock2 value *)\n      base_access_sizes t -> (* size in memory (if applicable) *)\n      locals ->\n      mem -> Prop :=\n    match t with\n    | base.type.prod a b =>\n      fun (x : base.interp a * base.interp b)\n          (y : base_rtype a * base_rtype b)\n          (s : base_access_sizes a * base_access_sizes b)\n          locals =>\n        sep (equivalent_base (fst x) (fst y) (fst s) locals)\n            (equivalent_base (snd x) (snd y) (snd s) locals)\n    | base_listZ => rep.equiv\n    | base_Z => rep.equiv\n    |  _ => fun _ _ _ _ => emp False\n    end.\n\n  (* produces a separation-logic condition stating that the values of\n     arguments are equivalent *)\n  Fixpoint equivalent_args {t}\n    : type.for_each_lhs_of_arrow\n        API.interp_type t -> (* fiat-crypto value *)\n      type.for_each_lhs_of_arrow rtype t -> (* bedrock2 value *)\n      type.for_each_lhs_of_arrow\n        access_sizes t -> (* sizes in memory *)\n      locals ->\n      mem -> Prop :=\n    match t with\n    | type.base b => fun _ _ _ _ _ => True\n    | type.arrow (type.base a) b =>\n      fun (x : base.interp a * _) (y : base_rtype a * _)\n          (s : base_access_sizes a * _) locals mem =>\n        (exists R,\n            sep (equivalent_base (fst x) (fst y) (fst s) locals) R mem)\n        /\\ (equivalent_args (snd x) (snd y) (snd s) locals mem)\n    | _ => fun _ _ _ _ _ => False\n    end.\n\n  Definition locally_equivalent_base {t} x y locals :=\n    @equivalent_base t x y (base_dummy_access_sizes t) locals map.empty.\n\n  Definition locally_equivalent_args {t} x y locals :=\n    @equivalent_args t x y (dummy_access_sizes_args t) locals map.empty.\n\n  (* wrapper that uses non-base types *)\n  Definition equivalent {t : API.type}\n    : API.interp_type t -> (* fiat-crypto value *)\n      rtype t -> (* bedrock2 value *)\n      access_sizes t -> (* sizes in memory *)\n      locals ->\n      mem -> Prop :=\n    match t with\n    | type.base b => equivalent_base\n    | _ => fun _ _ _ _ _ => False\n    end.\n  Definition locally_equivalent {t} x y locals :=\n    @equivalent t x y (dummy_access_sizes t) locals map.empty.\n\n  Fixpoint equivalent_listonly {t}\n    : base.interp t -> (* fiat-crypto value *)\n      listonly_base_rtype t -> (* bedrock2 value *)\n      base_access_sizes t ->\n      locals ->\n      mem -> Prop :=\n    match t with\n    | base.type.prod a b =>\n      fun x y s locals =>\n        sep (equivalent_listonly (fst x) (fst y) (fst s) locals)\n            (equivalent_listonly (snd x) (snd y) (snd s) locals)\n    | base_listZ => rep.equiv\n    | base_Z => fun _ _ _ _ => emp True\n    |  _ => fun _ _ _ _ => emp False\n    end.\n\n  Fixpoint equivalent_listexcl {t}\n    : base.interp t -> (* fiat-crypto value *)\n      listexcl_base_rtype t -> (* bedrock2 value *)\n      base_access_sizes t ->\n      locals ->\n      mem -> Prop :=\n    match t with\n    | base.type.prod a b =>\n      fun x y s locals =>\n        sep (equivalent_listexcl (fst x) (fst y) (fst s) locals)\n            (equivalent_listexcl (snd x) (snd y) (snd s) locals)\n    | base_listZ => fun _ _ _ _ => emp True\n    | base_Z => rep.equiv\n    |  _ => fun _ _ _ _ => emp False\n    end.\nEnd Equivalent.\n\n(* equivalence with flat lists of words *)\nSection EquivalentFlat.\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  Existing Instances rep.listZ_mem rep.Z.\n\n  Fixpoint equivalent_flat_base {t}\n    : base.interp t ->\n      list word ->\n      base_access_sizes t ->\n      mem -> Prop :=\n    match t as t0 return\n          base.interp t0 -> list word\n          -> base_access_sizes t0 -> _ with\n    | base.type.prod a b =>\n      fun (x : base.interp a * base.interp b) words sizes =>\n        Lift1Prop.ex1\n          (fun i =>\n             sep (equivalent_flat_base (fst x) (firstn i words) (fst sizes))\n                 (equivalent_flat_base (snd x) (skipn i words) (snd sizes)))\n    | base_listZ =>\n      fun (x : list Z) words (sizes : rep.size) =>\n        (* since this is in-memory representation, [words] should be one word\n             that indicates the memory location of the head of the list *)\n        sep\n          (map:=mem)\n          (emp (length words = 1%nat))\n          (let addr := word.unsigned (hd (word.of_Z 0%Z) words) in\n           rep.equiv (rep:=rep.listZ_mem)\n                     x (Syntax.expr.literal addr) sizes map.empty)\n    | base_Z =>\n      fun (x : Z) words sizes =>\n        sep\n          (map:=mem)\n          (emp (length words = 1%nat))\n          (let w := word.unsigned (hd (word.of_Z 0%Z) words) in\n           rep.equiv (rep:=rep.Z) x\n                     (Syntax.expr.literal w) sizes map.empty)\n    | _ => fun _ _ _ => emp False\n    end.\n\n  Fixpoint equivalent_flat_args {t}\n    : type.for_each_lhs_of_arrow API.interp_type t ->\n      list word ->\n      type.for_each_lhs_of_arrow access_sizes t ->\n      mem -> Prop :=\n    match t as t0\n          return type.for_each_lhs_of_arrow _ t0 -> _ ->\n                 type.for_each_lhs_of_arrow _ t0 -> _\n    with\n    | type.base _ => fun (_:unit) words _ _ => words = nil\n    | type.arrow (type.base a) b =>\n      fun x words sizes mem =>\n        exists i,\n          (exists R,\n              sep (equivalent_flat_base\n                     (fst x) (firstn i words) (fst sizes)) R mem)\n          /\\ (equivalent_flat_args\n                (snd x) (skipn i words) (snd sizes) mem)\n    | _ => fun _ _ _ _ => False (* invalid argument *)\n    end.\n  Fixpoint equivalent_listexcl_flat_base {t}\n    : base.interp t ->\n      list word ->\n      base_access_sizes t ->\n      mem -> Prop :=\n    match t as t0 return\n          base.interp t0 -> _ -> base_access_sizes t0\n          -> mem -> Prop with\n    | base.type.prod a b =>\n      fun (x : base.interp a * base.interp b) words s=>\n        Lift1Prop.ex1\n          (fun i =>\n             sep (equivalent_listexcl_flat_base\n                    (fst x) (firstn i words) (fst s))\n                 (equivalent_listexcl_flat_base\n                    (snd x) (skipn i words) (snd s)))\n    | base_listZ => fun _ words _ => emp (words = nil)\n    | base_Z => equivalent_flat_base\n    | _ => fun _ _ _ => emp False\n    end.\n\n  Fixpoint equivalent_listonly_flat_base {t}\n    : base.interp t ->\n      list word ->\n      base_access_sizes t ->\n      mem -> Prop :=\n    match t as t0 return\n          base.interp t0 -> _ -> base_access_sizes t0\n          -> mem -> Prop with\n    | base.type.prod a b =>\n      fun (x : base.interp a * base.interp b) words sizes =>\n        Lift1Prop.ex1\n          (fun i =>\n             sep (equivalent_listonly_flat_base\n                    (fst x) (firstn i words) (fst sizes))\n                 (equivalent_listonly_flat_base\n                    (snd x) (skipn i words) (snd sizes)))\n    | base_listZ => equivalent_flat_base\n    | base_Z => fun _ words _ => emp (words = nil)\n    | _ => fun _ _ _ => emp False\n    end.\nEnd EquivalentFlat.\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/Equivalence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.685949467848392, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2845996424852056}}
{"text": "Require Import List.\nRequire Import ListSet.\nRequire Import Coqlib.\nRequire Import Metatheory.\nRequire Import Maps.\nRequire Import maps_ext.\nRequire Import Lattice.\nRequire Import Kildall.\nRequire Import Iteration.\nRequire Export cfg.\nRequire Export reach.\nRequire Export dom_decl.\nRequire Import dom_type.\nRequire Import Dipaths.\nRequire Import util.\n\nRequire Import syntax.\nRequire Import infrastructure.\nRequire Import infrastructure_props.\nImport LLVMsyntax.\nImport LLVMinfra.\n\n(***************************************************)\n(* This file implements the set-based dominaton analysis *)\n\nModule AlgDom : ALGDOM.\n\nDefinition transfer (lbl: l) (before: Dominators.t) :=\n  Dominators.add before lbl.\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 [None] is returned. *)\n\nModule DomDS := Dataflow_Solver_Var_Top(AtomNodeSet).\n\n(***************************************************)\n(* All elements in a worklist must be in the CFG. *)\n\nModule WorklistProps. Section WorklistProps.\n\nVariable successors: ATree.t (list atom).\nDefinition in_cfg := XATree.in_cfg successors.\n\nDefinition wf_state (st: DomDS.state) : Prop :=\n  (forall n (Hinwrk: AtomNodeSet.In n st.(DomDS.st_wrk)), in_cfg n) /\\\n  NoDup (st.(DomDS.st_wrk)).\n\nLemma wf_state_pick_in_cfg: forall st (WF : wf_state st) n rem\n  (Hpick : Some (n, rem) = AtomNodeSet.pick (DomDS.st_wrk st)),\n  in_cfg n.\nProof.\n  intros.\n  symmetry_ctx.\n  apply AtomNodeSet.pick_in in Hpick.\n  apply WF in Hpick; auto.\nQed.\n\nLemma wf_state_pick_NoDup: forall st (WF : wf_state st) n rem\n  (Hpick : Some (n, rem) = AtomNodeSet.pick (DomDS.st_wrk st)),\n  NoDup rem.\nProof.\n  intros.\n  unfold AtomNodeSet.pick in Hpick.\n  case_eq (DomDS.st_wrk st).\n    intro Heq. rewrite Heq in *. congruence.\n\n    intros a l0 Heq. rewrite Heq in *. inv Hpick.\n    destruct WF as [_ WF]. \n    rewrite Heq in WF. inv WF.\n    apply AtomSet.set_remove_NoDup; auto.\nQed.\n\nLemma propagate_succ_list_wf_state_aux: forall p\n  out scs (st : DomDS.state) (Hwf : wf_state st)\n  (Hinscs: forall sc, In sc scs -> In sc successors !!! p),\n  wf_state (DomDS.propagate_succ_list st out scs).\nProof.\n  induction scs; simpl; intros; auto.\n    apply IHscs; auto.\n    Case \"1\".\n      unfold DomDS.propagate_succ.\n      destruct_if; auto.\n      split; simpl.\n      SCase \"1.1\".\n        intros n Hinwrk. \n        unfold AtomNodeSet.In, AtomNodeSet.add in Hinwrk.\n        apply set_add_elim in Hinwrk.\n        destruct Hinwrk as [Hinwrk | Hinwrk]; subst.\n          eapply XATree.in_succ__in_cfg; eauto.\n          apply Hwf; auto.\n      SCase \"1.2\".\n        apply AtomSet.set_add_NoDup. apply Hwf.\nQed.\n\nLemma propagate_succ_list_wf_state: forall st (Hwf: wf_state st) rem p \n  (Hpick: AtomNodeSet.pick (DomDS.st_wrk st) = Some (p, rem)),\n  wf_state \n    (DomDS.propagate_succ_list \n      {| DomDS.st_in := DomDS.st_in st; DomDS.st_wrk := rem |}\n      (transfer p (DomDS.st_in st) !! p) successors !!! p).\nProof.\n  intros.\n  assert \n    (wf_state {| DomDS.st_in := DomDS.st_in st; DomDS.st_wrk := rem |}) \n    as Hwf'.\n    split; simpl.\n      intros n Hin. simpl in *.\n      apply AtomNodeSet.pick_some with (n':=n) in Hpick.\n      apply Hwf. tauto.\n\n      eapply wf_state_pick_NoDup; eauto.\n  eapply propagate_succ_list_wf_state_aux; eauto.\nQed.\n\nLemma step_wf_state: forall (st st': DomDS.state)\n  (Hstep: DomDS.step successors transfer st = inr st'),\n  wf_state st -> wf_state st'.\nProof.\n  unfold DomDS.step.\n  intros.\n  remember (AtomNodeSet.pick (DomDS.st_wrk st)) as R.\n  destruct R as [ [n rem] | ]; inv Hstep.\n  apply propagate_succ_list_wf_state; auto.\nQed.\n\nLemma in_parents_of_tree__in_initial: forall p\n  (Hin : In p (XATree.parents_of_tree successors)),\n  AtomNodeSet.In p (AtomNodeSet.initial successors).\nProof.\n  intros.\n  apply XATree.parents_of_tree__in_successors in Hin.\n  destruct Hin as [s Hin].\n  eapply AtomNodeSet.initial_spec; eauto.\nQed.\n\nVariable entrypoints: list (atom * DomDS.L.t).\n\nLemma entrypoints_wf_state:\n  wf_state (DomDS.mkstate (DomDS.start_state_in entrypoints) \n                          (AtomNodeSet.initial successors)).\nProof.\n  split.\n    intros x Hin.\n    simpl in *.\n    apply AtomNodeSet.initial_spec' in Hin.\n    apply XATree.parents_of_tree__in_successors in Hin.\n    apply XATree.in_parents_of_tree__in_cfg; auto.\n\n    simpl. apply AtomNodeSet.NoDup__initial.\nQed.\n\nEnd WorklistProps. End WorklistProps.\n\n(**************************************************************)\n(* Dominators of a node must be parents of the node. *)\n\nModule DomsInParents. Section DomsInParents.\n\nVariable succs : ATree.t (list l).\nDefinition transf := transfer.\nDefinition top := Dominators.top.\nDefinition bot := Dominators.bot.\nVariable entry: l.\nDefinition entrypoints : list (atom * DomDS.L.t) := (entry, Dominators.top)::nil.\n\nDefinition wf_dom (res: DomDS.L.t) : Prop :=\n  match res with\n  | Some ns0 => incl ns0 (XATree.parents_of_tree succs)\n  | None => True\n  end.\n\nDefinition wf_doms (res: AMap.t DomDS.L.t) : Prop := \n  forall l0, wf_dom (res !! l0).\n\nLemma start_wf_doms:\n  wf_doms (DomDS.st_in (DomDS.start_state succs entrypoints)).\nProof.\n  simpl. intros l0.\n  rewrite AMap.gsspec.\n  rewrite AMap.gi. simpl. \n  destruct_if; simpl.\n    intros x Hinx. inv Hinx.\n    rewrite AMap.gi. simpl. auto.\nQed.\n\n(** We show that the start state satisfies the invariant, and that\n  the [step] function preserves it. *)\n\nLemma wf_dom_eq: forall dt1 dt2 (Heq: DomDS.L.eq dt1 dt2) (Hwf: wf_dom dt2),\n  wf_dom dt1.\nProof.\n  unfold wf_dom.\n  intros.\n  destruct dt1; destruct dt2; tinv Heq; auto.\n    elim Heq. intros. eauto with datatypes.\nQed.\n\nLemma propagate_succ_wf_doms: forall st n out,\n  wf_dom out ->\n  wf_doms st.(DomDS.st_in) ->\n  wf_doms (DomDS.propagate_succ st out n).(DomDS.st_in).\nProof.\n  unfold wf_doms.\n  intros.\n  destruct (@DomDS.propagate_succ_spec st out n) as [J1 J2].\n  destruct (eq_atom_dec n l0); subst.\n    apply wf_dom_eq in J1; auto.\n    assert (J:=H0 l0).\n    clear - J H.\n    unfold wf_dom in *.\n    destruct out, (DomDS.st_in st) !! l0; simpl; auto.\n      apply AtomSet.incl_inter_left; auto.\n\n    rewrite J2; auto.\nQed.\n\nLemma propagate_succ_list_wf_doms:\n  forall scs st out (Hsc: scs <> nil -> wf_dom out),\n  wf_doms st.(DomDS.st_in) ->\n  wf_doms (DomDS.propagate_succ_list st out scs).(DomDS.st_in).\nProof.\n  induction scs; simpl; intros; auto.\n    apply IHscs; auto.\n      intro J. apply Hsc. congruence.\n      apply propagate_succ_wf_doms; auto.\n        apply Hsc. congruence.\nQed.\n\nLemma pick_wf_doms:\n  forall st n rem,\n  AtomNodeSet.pick st.(DomDS.st_wrk) = Some(n, rem) ->\n  wf_doms st.(DomDS.st_in) ->\n  wf_doms (DomDS.propagate_succ_list\n             (DomDS.mkstate st.(DomDS.st_in) rem)\n             (transf n st.(DomDS.st_in)!!n)\n             (succs!!!n)).(DomDS.st_in).\nProof.\n  intros st n rem WKL GOOD.\n  destruct st. simpl.\n  apply propagate_succ_list_wf_doms; auto.\n    intro Hnnil.\n    assert (J:=GOOD n). simpl in J.\n    unfold wf_dom. unfold wf_dom in J.    \n    destruct (st_in !! n); simpl; auto.\n    intros x Hin.\n    destruct_in Hin; auto.\n      apply XATree.nonleaf_is_parent; auto.\nQed.\n\nLemma step_wf_doms: forall (st st': DomDS.state)\n  (Hstep: DomDS.step succs transfer st = inr st'),\n  wf_doms st.(DomDS.st_in) -> wf_doms st'.(DomDS.st_in).\nProof.\n  unfold DomDS.step.\n  intros.\n  remember (AtomNodeSet.pick (DomDS.st_wrk st)) as R.\n  destruct R as [ [n rem] | ]; inv Hstep.\n  apply pick_wf_doms; auto.\nQed.\n\nTheorem fixpoint_wf: forall res ni,\n  DomDS.fixpoint succs transf entrypoints ni = Some res ->\n  wf_doms res.\nProof.\n  unfold DomDS.fixpoint. intros res ni PI. pattern res.\n  eapply (PrimIter.iter_prop _ _ (DomDS.step _ _)\n    (fun st => wf_doms st.(DomDS.st_in))); eauto.\n    intros st GOOD. unfold DomDS.step.\n    caseEq (AtomNodeSet.pick st.(DomDS.st_wrk)); auto.\n    intros [n rem] PICK.\n    apply pick_wf_doms; auto.\n\n    apply start_wf_doms.\nQed.\n\nEnd DomsInParents. End DomsInParents.\n\n(**************************************************************)\n(* Prove that the analyis must terminate. *)\n\nModule Termination. Section Termination.\n\nVariable successors: ATree.t (list atom).\nDefinition in_cfg := XATree.in_cfg successors.\n\nDefinition elements_of_cfg : list atom := \n  XATree.elements_of_cfg successors eq_atom_dec.\n\nDefinition psize_of_cfg := (plength elements_of_cfg + 2)%positive. (*same*)\n\nDefinition psize_of_dom (dms: DomDS.L.t) : positive :=\n  match dms with\n  | None => psize_of_cfg\n  | Some x => plength (AtomSet.elements_of_set eq_atom_dec x)\n  end.\n\nDefinition num_of_doms_fun (dmap: AMap.t DomDS.L.t) (acc:positive) (a:atom) \n  : positive :=\n  Pplus acc (psize_of_dom (dmap !! a)).\n\nDefinition num_of_doms (dmap: AMap.t DomDS.L.t) : positive := (*same*)\nfold_left (num_of_doms_fun dmap) elements_of_cfg 1%positive.\n\nDefinition num_iters := Pcubeplus psize_of_cfg. (* same *)\nDefinition psize_of_worklist (wrk: AtomNodeSet.t) : positive :=\n(plength wrk + 1)%positive.\n\nDefinition num_iters_aux (st: DomDS.state) := \n(psize_of_cfg * (num_of_doms (st.(DomDS.st_in))) + \n  psize_of_worklist (st.(DomDS.st_wrk)))%positive.\n\nLemma elements_of_cfg__lt__psize_of_cfg: (*same*)\n  (plength elements_of_cfg < psize_of_cfg)%positive.\nProof.\n  unfold psize_of_cfg. zify; omega.\nQed.\n\nLemma psize_of_worklist_ge_one: forall wrk, (*same*)\n  (psize_of_worklist wrk > 1)%positive.\nProof.\n  unfold psize_of_worklist.\n  intros. zify. omega.\nQed.\n\nHint Unfold num_iters_aux.\n\nLemma num_iters_aux_gt_one: forall st, (num_iters_aux st > 1)%positive. (*same*)\nProof.\n  intros.\n  autounfold.  \n  assert (J:=psize_of_worklist_ge_one (DomDS.st_wrk st)).\n  zify. omega.\nQed.\n\nDefinition DomMap_eq bd (in1 in2: AMap.t DomDS.L.t) : Prop := (*same*)\n  forall n (Hin: In n bd),  DomDS.L.eq in2!!n in1!!n.\n\nLemma propagate_succ_records_unchanges: (*almost same*)\n  forall st out n st' (Heq: st' = DomDS.propagate_succ st out n) bd\n  (H: DomMap_eq bd st.(DomDS.st_in) st'.(DomDS.st_in)) (Hin: In n bd),\n  st.(DomDS.st_wrk) = st'.(DomDS.st_wrk).\nProof.\n  unfold DomDS.propagate_succ.\n  intros. \n  case_eq (DomDS.L.lub (DomDS.st_in st) !! n out).\n    intros newl Heq'.\n    rewrite Heq' in *.\n    destruct_if; subst; auto.\n    symmetry in HeqR.\n    apply DomDS.L.beq_correct' in HeqR.\n    assert (J:=H n Hin). simpl in *.\n    rewrite AMap.gss in J.\n    apply DomDS.L.eq_sym in J.\n    congruence.\n\n    intros Heq'.\n    rewrite Heq' in *.\n    assert (G:=DomDS.L.ge_lub_left (DomDS.st_in st) !! n out).\n    rewrite Heq' in G. \n    destruct ((DomDS.st_in st) !! n); inv G.\n    unfold DomDS.L.beq. \n    destruct (DomDS.L.eq_dec None None) as [|n0]; auto.\n      contradict n0. apply DomDS.L.eq_refl.\nQed.\n\nLemma DomMap_eq_incr_incr__eq_eq: forall bd dm1 dm2 dm3 (Heq13: DomMap_eq bd dm1 dm3)\n  (Hincr12: DomDS.in_incr dm1 dm2) (Hincr23: DomDS.in_incr dm2 dm3),\n  DomMap_eq bd dm1 dm2 /\\ DomMap_eq bd dm2 dm3.  (*almost same*)\nProof.\n  intros.\n  split.\n    intros x Hinx.\n    apply Heq13 in Hinx.\n    assert (J1:=Hincr12 x).\n    assert (J2:=Hincr23 x).\n    unfold DomDS.L.eq.\n    destruct (dm2 !! x) as [x2|]; simpl in *; auto.\n      destruct (dm1 !! x) as [x1|]; simpl in *.\n        destruct (dm3 !! x) as [x3|]; simpl in *; try tauto.\n          split; auto.\n             destruct Hinx. eauto with datatypes.\n        destruct (dm3 !! x) as [x3|]; simpl in *; try tauto.\n\n    intros x Hinx.\n    apply Heq13 in Hinx.\n    assert (J1:=Hincr12 x).\n    assert (J2:=Hincr23 x).\n    unfold DomDS.L.eq.\n    destruct (dm3 !! x) as [x3|]; simpl in *; auto.\n      destruct (dm1 !! x) as [x1|]; simpl in *.\n        destruct (dm2 !! x) as [x2|]; simpl in *; try tauto.\n          split; auto.\n             destruct Hinx. eauto with datatypes.\n        destruct (dm2 !! x) as [x2|]; simpl in *; try tauto.\nQed.\n\nLemma propagate_succ_list_records_unchanges: (*almost same*)\n  forall out bd scs (Hinc: incl scs bd)\n  st st' (Heq: st' = DomDS.propagate_succ_list st out scs)\n  (H: DomMap_eq bd st.(DomDS.st_in) st'.(DomDS.st_in)),\n  st.(DomDS.st_wrk) = st'.(DomDS.st_wrk).\nProof.\n  induction scs; simpl; intros; subst; auto.\n    assert (J1:=DomDS.propagate_succ_incr st out a).\n    assert (J2:=DomDS.propagate_succ_list_incr out scs (DomDS.propagate_succ st out a)).\n    eapply DomMap_eq_incr_incr__eq_eq in H; eauto.\n    destruct H.\n    transitivity (DomDS.st_wrk (DomDS.propagate_succ st out a)).\n      eapply propagate_succ_records_unchanges; eauto with datatypes.\n      apply IHscs; eauto with datatypes.\nQed.\n\nLemma stable_step_decreases_wrk: forall st st' (*same*)\n  (Hstep : DomDS.step successors transfer st = inr st')\n  (Heq: DomMap_eq elements_of_cfg (st.(DomDS.st_in)) (st'.(DomDS.st_in))),\n  exists n, AtomNodeSet.pick st.(DomDS.st_wrk) = Some (n, st'.(DomDS.st_wrk)).\nProof.\n  unfold DomDS.step.\n  intros.\n  case_eq (AtomNodeSet.pick st.(DomDS.st_wrk)).\n    intros [max rem] Hpick.\n    rewrite Hpick in *. exists max.\n    inv Hstep.\n    erewrite <- propagate_succ_list_records_unchanges; eauto.\n      simpl. auto.\n      apply XATree.succs_in_elements_of_cfg.\n\n    intros Hpick.\n    rewrite Hpick in *. congruence.\nQed.\n\nLemma dom_eq__psize_of_dom: forall sdms1 sdms2 (Heq: DomDS.L.eq sdms1 sdms2),\n  psize_of_dom sdms1 = psize_of_dom sdms2.\nProof.\n  destruct sdms1 as [x|]; destruct sdms2 as [y|]; simpl; intros; try tauto.\n  destruct Heq as [J1 J2].\n  apply AtomSet.length_incl_elements_of_set with (Hdec:=eq_atom_dec) in J1.\n  apply AtomSet.length_incl_elements_of_set with (Hdec:=eq_atom_dec) in J2.\n  unfold plength. \n  zify. omega.\nQed.\n\nLemma stable_step_num_of_doms: forall dm1 dm2 (* almost same *)\n  (Heq : DomMap_eq elements_of_cfg dm1 dm2),\n  num_of_doms dm1 = num_of_doms dm2.\nProof.\n  unfold num_of_doms.\n  intros.\n  revert Heq.\n  generalize 1%positive as p.\n  generalize elements_of_cfg as l0.\n  induction l0 as [|a l0]; simpl; auto.\n    intros.\n    rewrite IHl0. \n      f_equal.\n      unfold num_of_doms_fun.\n      f_equal.\n      apply dom_eq__psize_of_dom.\n      apply DomDS.L.eq_sym.\n      apply Heq; simpl; auto.\n\n      intros x Hinx.\n      apply Heq. simpl; auto.\nQed.\n\nLemma stable_step_psize_of_worklist: forall wrk wrk' max (* almost same *)\n  (Hpick : AtomNodeSet.pick wrk = Some (max, wrk')),\n  (psize_of_worklist wrk >= psize_of_worklist wrk' + 1)%positive.\nProof.\n  unfold AtomNodeSet.pick.\n  intros.\n  destruct wrk; inv Hpick.\n  assert (J:=@AtomSet.set_remove_length _ eq_atom_dec max wrk).\n  unfold psize_of_worklist. unfold plength. simpl.\n  zify. omega.\nQed.\n\nLemma Pplus_pminus_spec1: forall p1 p2 p3, (* same *)\n  (p2 > p3)%positive -> (p1 + (p2 - p3) = p1 + p2 - p3)%positive.\nProof.\n  intros. apply Pos.add_sub_assoc. apply Pos.gt_lt; auto.\nQed.\n\nLemma stable_step_num_iters_aux: forall (st st': DomDS.state) max (* almost same *)\n  (Hpick : AtomNodeSet.pick (DomDS.st_wrk st) = Some (max, DomDS.st_wrk st'))\n  (Heq : DomMap_eq elements_of_cfg (DomDS.st_in st) (DomDS.st_in st')),\n  (num_iters_aux st >= num_iters_aux st' + 1)%positive.\nProof.\n  intros.\n  autounfold.\n  apply stable_step_num_of_doms in Heq.\n  apply stable_step_psize_of_worklist in Hpick.\n  rewrite Heq. clear Heq.\n  zify. omega.\nQed.\n\nLemma propagate_succ_wrk_range:  (* almost same *)\n  forall st out n st' (Heq: st' = DomDS.propagate_succ st out n),\n  (psize_of_worklist st'.(DomDS.st_wrk) <=\n    (psize_of_worklist st.(DomDS.st_wrk) + 1)%positive)%positive.\nProof.\n  unfold DomDS.propagate_succ.\n  intros. \n  destruct_if.\n    zify; omega.\n\n    simpl.\n    assert (J:=@AtomSet.set_add_length _ eq_atom_dec n (DomDS.st_wrk st)).\n    unfold psize_of_worklist, AtomNodeSet.add, plength.\n    zify; omega.\nQed.\n\nLemma propagate_succ_list_wrk_range:  (* same *)\n  forall out scs st st' (Heq: st' = DomDS.propagate_succ_list st out scs),\n  (psize_of_worklist st'.(DomDS.st_wrk) <=\n    (psize_of_worklist st.(DomDS.st_wrk) + plength scs)%positive)%positive.\nProof.\n  induction scs; simpl; intros; subst.\n    zify; omega.\n\n    assert\n      (psize_of_worklist (DomDS.propagate_succ st out a).(DomDS.st_wrk) <=\n        (psize_of_worklist st.(DomDS.st_wrk) + 1)%positive)%positive as J1.\n      eapply propagate_succ_wrk_range; eauto.\n    assert (DomDS.propagate_succ_list (DomDS.propagate_succ st out a) out scs = \n            DomDS.propagate_succ_list  (DomDS.propagate_succ st out a) out scs) \n      as J2. auto.\n    apply IHscs in J2. unfold plength in *. simpl.\n    zify; omega.\nQed.\n\nLemma wrk_in_cfg__psize_of_worklist_lt_psize_of_cfg: forall st\n  (Hwf : WorklistProps.wf_state successors st),\n  (psize_of_worklist st.(DomDS.st_wrk) < psize_of_cfg)%positive.\nProof.\n  intros.\n  unfold  WorklistProps.wf_state in Hwf.\n  unfold psize_of_worklist, psize_of_cfg.\n  destruct Hwf as [Hwf1 Hwf2].\n  assert (length (DomDS.st_wrk st) <= length elements_of_cfg)%nat as Hle.\n    eapply NoDup_incl_length; eauto using eq_atom_dec.\n    Case \"1\".\n      apply remove_redundancy_NoDup; auto.\n    Case \"2\".\n      intros x Hinx. \n      apply Hwf1 in Hinx.\n      apply remove_redundancy_in; auto.\n      apply in_or_app. auto.\n  unfold plength. zify; omega.     \nQed.\n\nLemma instable_step_wrk_range: forall st st'\n  (Hwf: WorklistProps.wf_state successors st)\n  (Hstep : DomDS.step successors transfer st = inr st'),\n  (psize_of_worklist st'.(DomDS.st_wrk) <\n    psize_of_worklist st.(DomDS.st_wrk) + psize_of_cfg)%positive.\nProof.\n  intros.\n  apply WorklistProps.step_wf_state in Hstep; auto.\n  apply wrk_in_cfg__psize_of_worklist_lt_psize_of_cfg in Hstep.\n  zify; omega.\nQed.\n\nDefinition DomMap_gt bd dm1 dm2 : Prop :=\nDomDS.in_incr dm1 dm2 /\\ exists n, In n bd /\\ DomDS.L.gt (dm2 !! n) (dm1 !! n).\n\nLemma DomMap_in_incr__gt_or_eq: forall dm1 dm2 \n  (Hincr: DomDS.in_incr dm1 dm2) bd,\n  DomMap_eq bd dm1 dm2 \\/ DomMap_gt bd dm1 dm2.\nProof.\n  induction bd; simpl; intros.\n    left.\n    intros x Hinx. tauto.\n\n    assert (G:=Hincr a).\n    destruct (DomDS.L.ge__gt_or_eq (dm2!!a) (dm1!!a)) as [J | J]; auto.\n      destruct IHbd as [IHbd | IHbd].\n        left.\n        intros x Hinx.\n        destruct_in Hinx.\n          apply IHbd in Hinx; auto.\n       \n       right.\n       split; auto.\n         destruct IHbd as [_ [n [J1 J2]]]. \n         exists n.\n         simpl; auto.\n\n     right.\n     split; auto.\n       exists a.\n       simpl; auto.\nQed.\n\nDefinition doms_lt_psize_of_cfg (dm2:AMap.t DomDS.L.t) :=\n  forall p2 dms2 (Hget2: (dm2 !! p2) = Some dms2),\n    (psize_of_dom (Some dms2) < psize_of_cfg)%positive.\n\nLemma ge__num_of_doms_fun__le_le: forall (dm1 dm2:AMap.t DomDS.L.t)\n  (Hincfg: doms_lt_psize_of_cfg dm2)\n  (p2 p1 : positive) (Hle : (p2 <= p1)%positive) a\n  (J : DomDS.L.ge dm2 !! a dm1 !! a),\n  (num_of_doms_fun dm2 p2 a <= num_of_doms_fun dm1 p1 a)%positive.\nProof.\n  intros.\n  unfold num_of_doms_fun.\n  unfold DomDS.L.ge in J.\n  case_eq (dm1 !! a).\n    intros l0 Heq0. rewrite Heq0 in *.\n    case_eq (dm2 !! a).\n      intros l1 Heq1. rewrite Heq1 in *. simpl in J.\n      apply AtomSet.length_incl_elements_of_set with (Hdec:=eq_atom_dec) in J; \n        auto.\n      unfold psize_of_dom, plength. zify; omega.\n  \n      intros Heq1. rewrite Heq1 in *. tauto.\n  \n    intros Heq0. rewrite Heq0 in *. \n    case_eq (dm2 !! a).\n      intros l1 Heq1. rewrite Heq1 in *.\n      apply Hincfg in Heq1. simpl in *.\n      zify; omega.\n  \n      intros Heq1. rewrite Heq1 in *.\n      zify; omega.\nQed.\n\nLemma ge__num_of_doms_fun__lt_lt: forall (dm1 dm2:AMap.t DomDS.L.t)\n  (Hincfg: doms_lt_psize_of_cfg dm2)\n  (p2 p1 : positive) (Hle : (p2 < p1)%positive) a\n  (J : DomDS.L.ge dm2 !! a dm1 !! a),\n  (num_of_doms_fun dm2 p2 a < num_of_doms_fun dm1 p1 a)%positive.\nProof.\n  intros.\n  unfold num_of_doms_fun.\n  unfold DomDS.L.ge in J.\n  case_eq (dm1 !! a).\n    intros l0 Heq0. rewrite Heq0 in *.\n    case_eq (dm2 !! a).\n      intros l1 Heq1. rewrite Heq1 in *.\n      apply AtomSet.length_incl_elements_of_set with (Hdec:=eq_atom_dec) in J; \n        auto.\n      unfold psize_of_dom, plength. zify; omega.\n  \n      intros Heq1. rewrite Heq1 in *. tauto.\n  \n    intros Heq0. rewrite Heq0 in *. \n    case_eq (dm2 !! a).\n      intros l1 Heq1. rewrite Heq1 in *.\n      apply Hincfg in Heq1. simpl in *.\n      zify; omega.\n  \n      intros Heq1. rewrite Heq1 in *.\n      zify; omega.\nQed.\n\nLemma ge__num_of_doms_fun__lt_le: forall (dm1 dm2:AMap.t DomDS.L.t)\n  (Hincfg: doms_lt_psize_of_cfg dm2)\n  (p2 p1 : positive) (Hle : (p2 < p1)%positive) a\n  (J : DomDS.L.ge dm2 !! a dm1 !! a),\n  (num_of_doms_fun dm2 p2 a <= num_of_doms_fun dm1 p1 a)%positive.\nProof.\n  intros.\n  eapply ge__num_of_doms_fun__lt_lt in J; eauto.\n  zify; omega.\nQed.\n\nLemma incr_num_of_doms: forall (dm1 dm2:AMap.t DomDS.L.t)\n  (Hincfg: doms_lt_psize_of_cfg dm2)\n  (Hlt : DomDS.in_incr dm1 dm2) bd p2 p1 (Hle: (p2 < p1)%positive),\n  (fold_left (num_of_doms_fun dm2) bd p2 <\n    fold_left (num_of_doms_fun dm1) bd p1)%positive.\nProof.\n  unfold num_of_doms.\n  intros dm1 dm2 Hincfg.\n  induction bd as [|a bd]; simpl; intros; auto.\n    apply IHbd; auto.\n      assert (J:=Hlt a).\n      apply ge__num_of_doms_fun__lt_lt; auto.\nQed.\n\nLemma gt__num_of_doms_fun__le_lt: forall (dm1 dm2:AMap.t DomDS.L.t)\n  (Hincfg: doms_lt_psize_of_cfg dm2)\n  (p2 p1 : positive) (Hle : (p2 <= p1)%positive) a\n  (J : DomDS.L.gt dm2 !! a dm1 !! a),\n  (num_of_doms_fun dm2 p2 a < num_of_doms_fun dm1 p1 a)%positive.\nProof.\n  intros.\n  unfold num_of_doms_fun.\n  unfold DomDS.L.gt in J.\n  case_eq (dm1 !! a).\n    intros l0 Heq0. rewrite Heq0 in *.\n    case_eq (dm2 !! a).\n      intros l1 Heq1. rewrite Heq1 in *.\n      destruct J as [J J'].\n      apply AtomSet.length_exact_incl_elements_of_set \n        with (Hdec:=eq_atom_dec) in J'; auto.\n      unfold psize_of_dom, plength.\n      zify; omega.\n  \n      intros Heq1. rewrite Heq1 in *. tauto.\n  \n    intros Heq0. rewrite Heq0 in *. \n    case_eq (dm2 !! a).\n      intros l1 Heq1. rewrite Heq1 in *.\n      apply Hincfg in Heq1. simpl in *.\n      zify; omega.\n  \n      intros Heq1. rewrite Heq1 in *.\n      zify; omega.\nQed.\n\nLemma gt__num_of_doms__le_lt: forall (dm1 dm2:AMap.t DomDS.L.t)\n  (Hincfg: doms_lt_psize_of_cfg dm2)\n  bd (Hlt : DomMap_gt bd dm1 dm2) p2 p1 (Hle: (p2 <= p1)%positive),\n  (fold_left (num_of_doms_fun dm2) bd p2 <\n    fold_left (num_of_doms_fun dm1) bd p1)%positive.\nProof.\n  intros dm1 dm2 Hincfg.\n  unfold DomMap_gt.\n  induction bd as [|a bd]; simpl; intros.\n    destruct Hlt as [J1 [J2 J3]]. tauto.\n\n    destruct Hlt as [Hincr [n [Hin Hlt]]].\n    destruct Hin as [Hin | Hin]; subst.\n      eapply gt__num_of_doms_fun__le_lt in Hlt; eauto.\n      apply incr_num_of_doms; auto.\n\n      apply IHbd; eauto.\n      eapply ge__num_of_doms_fun__le_le; eauto.\nQed.\n\nLemma gt_num_of_doms: forall (dm1 dm2:AMap.t DomDS.L.t)\n  (Hincfg: doms_lt_psize_of_cfg dm2)\n  (Hlt : DomMap_gt elements_of_cfg dm1 dm2),\n  (num_of_doms dm2 < num_of_doms dm1)%positive.\nProof.\n  unfold num_of_doms.\n  intros.\n  apply gt__num_of_doms__le_lt; auto.\n    zify; omega.\nQed.\n\nLemma instable_step_num_iters_aux: forall (st st': DomDS.state)\n  (Hwf: WorklistProps.wf_state successors st)\n  (Hincfg: doms_lt_psize_of_cfg (st'.(DomDS.st_in)))\n  (Hstep : DomDS.step successors transfer st = inr st')\n  (Hlt : DomMap_gt elements_of_cfg (DomDS.st_in st) (DomDS.st_in st')),\n  (num_iters_aux st' + 1 <= (num_iters_aux st))%positive.\nProof.\n  intros.\n  autounfold.\n  apply gt_num_of_doms in Hlt; auto.\n  apply instable_step_wrk_range in Hstep; auto.\n  revert Hlt Hstep.\n  generalize (num_of_doms (DomDS.st_in st')) as A. \n  generalize (num_of_doms (DomDS.st_in st)) as B.\n  generalize (psize_of_worklist (DomDS.st_wrk st)) as C. \n  generalize (psize_of_worklist (DomDS.st_wrk st')) as D.\n  generalize (psize_of_cfg) as E.\n  intros.\n  assert (E * A + E = E * (A + 1))%positive as J2.\n    rewrite Pmult_plus_distr_l.\n    zify. omega.\n  assert (E * (A + 1) <= E * B)%positive as J4.\n    zify.\n    apply Zmult_le_compat_l; omega.\n  zify. omega.\nQed.\n\nLemma doms_in_parants__doms_lt_psize_of_cfg: forall dms\n  (Hwf : DomsInParents.wf_doms successors dms),\n  doms_lt_psize_of_cfg dms.\nProof.\n  intros.\n  intros n sds Hget2.\n  assert (J:=Hwf n). rewrite Hget2 in J. simpl in J.\n  simpl.\n  assert (length (AtomSet.elements_of_set eq_atom_dec sds) <= \n            length elements_of_cfg)%nat as Hle.\n    eapply NoDup_incl_length; eauto using eq_atom_dec.\n    Case \"1\".\n      apply remove_redundancy_NoDup.\n    Case \"2\".\n      apply remove_redundancy_NoDup; auto.\n    Case \"3\".\n      intros x Hinx. \n      apply remove_redundancy_in with (Hdec:=eq_atom_dec) in Hinx; auto.\n      apply remove_redundancy_in.\n      apply in_or_app. auto.\n  unfold psize_of_cfg, plength. zify; omega.     \nQed.\n\nDefinition fixpoint_iter_P := \n  (fun ni => \n     forall st \n     (Hbound: (ni >= num_iters_aux st)%positive)\n     (Hwf1: DomsInParents.wf_doms successors (DomDS.st_in st))\n     (Hwf2: WorklistProps.wf_state successors st),\n     exists res : AMap.t DomDS.L.t,\n       PrimIter.iter DomDS.state (AMap.t DomDS.L.t)\n         (DomDS.step successors transfer) ni\n         st = Some res).\n\nLemma fixpoint_iter: forall ni, fixpoint_iter_P ni.\nProof.\n  apply (well_founded_ind Plt_wf fixpoint_iter_P). \n  unfold fixpoint_iter_P. intros.\n  rewrite PrimIter.unroll_iter.\n  unfold PrimIter.iter_step. \n  case (peq x 1); intro.\n  Case \"x=1\".\n    subst x.\n    contradict Hbound.    \n    assert (J:=num_iters_aux_gt_one st).\n    zify; omega.\n\n  Case \"x<>1\".\n    case_eq (DomDS.step successors transfer st); eauto.\n    intros st' Hstep.\n    assert (DomsInParents.wf_doms successors (DomDS.st_in st')) as Hwf1'.    \n      eapply DomsInParents.step_wf_doms; eauto.\n    assert (WorklistProps.wf_state successors st') as Hwf2'.\n      eapply WorklistProps.step_wf_state; eauto.\n    apply H; auto.\n    SCase \"1\".\n      apply Ppred_Plt; auto. \n    SCase \"2\".\n      assert (Hmono:=Hstep).\n      apply DomDS.step_incr in Hmono.\n      apply DomMap_in_incr__gt_or_eq with (bd:=elements_of_cfg) in Hmono; auto.\n      destruct Hmono as [Heq | Hgt].\n      SSCase \"2.1\".\n        apply stable_step_decreases_wrk in Hstep; auto.\n        destruct Hstep as [max Hpick].\n        eapply stable_step_num_iters_aux in Heq; eauto.\n        clear - Hbound n Heq. zify. rewrite Pos.sub_1_r. rewrite Pos2Z.inj_pred.\n        omega. zify. omega.\n      SSCase \"2.2\".\n        eapply instable_step_num_iters_aux in Hgt; eauto.\n        SSSCase \"2.2.1\".\n          zify. rewrite Pos.sub_1_r. rewrite Pos2Z.inj_pred.\n          omega. zify. omega.\n        SSSCase \"2.2.2\".\n          apply doms_in_parants__doms_lt_psize_of_cfg; auto. \nQed.\n\nLemma doms_lt_psize_of_cfg__num_of_doms: forall dms \n  (Hwf: doms_lt_psize_of_cfg dms) bd (p:positive),\n  (plength bd * psize_of_cfg + p >=\n    fold_left (num_of_doms_fun dms) bd p)%positive.\nProof.\n  unfold plength.\n  induction bd; simpl; intros.\n    zify; omega.\n    \n    assert (J:=IHbd (num_of_doms_fun dms p a)%positive).\n    assert (num_of_doms_fun dms p a <= p + psize_of_cfg)%positive as J'.\n      unfold num_of_doms_fun.\n      case_eq (dms !! a).\n        intros l Heq.\n        apply Hwf in Heq. zify; omega.\n\n        intros Heq. simpl. zify; omega.\n    revert J J'.\n    generalize (P_of_succ_nat (length bd)) as B.\n    generalize (psize_of_cfg) as D.\n    intros.\n    assert (Psucc B = (B + 1))%positive as EQ.\n      zify; omega.\n    rewrite EQ. clear EQ. \n    assert ((B + 1) * D = B * D + D)%positive as EQ.\n      rewrite Pmult_plus_distr_r.\n      zify; omega.\n    zify; omega.\nQed.\n\nVariable entrypoint: atom.\nDefinition entrypoints := (entrypoint, DomDS.L.top) :: nil.\n\nLemma entry_psize_of_worklist:\n  (psize_of_cfg >=\n     psize_of_worklist\n       (DomDS.st_wrk (DomDS.start_state successors entrypoints)))%positive.\nProof.\n  assert (J:=WorklistProps.entrypoints_wf_state successors entrypoints).\n  apply wrk_in_cfg__psize_of_worklist_lt_psize_of_cfg in J.\n  simpl in *. zify; omega.\nQed.\n\nLemma entry_num_of_doms:\n  (psize_of_cfg * psize_of_cfg >=\n   num_of_doms (DomDS.st_in (DomDS.start_state successors entrypoints)))%positive.\nProof.\n  unfold num_of_doms.\n  assert (J:=elements_of_cfg__lt__psize_of_cfg).\n  assert (doms_lt_psize_of_cfg \n           (DomDS.st_in (DomDS.start_state successors entrypoints))) as J'.\n    assert (G:=WorklistProps.entrypoints_wf_state successors entrypoints).\n    assert (G':=DomsInParents.start_wf_doms successors entrypoint).\n    apply doms_in_parants__doms_lt_psize_of_cfg; auto.\n  apply doms_lt_psize_of_cfg__num_of_doms \n    with (p:=xH)(bd:=elements_of_cfg) in J'.\n  revert J J'.\n  generalize (fold_left\n               (num_of_doms_fun\n                  (DomDS.st_in (DomDS.start_state successors entrypoints)))\n               elements_of_cfg xH).\n  generalize (plength elements_of_cfg).\n  generalize (psize_of_cfg).\n  intros A B C. intros.\n  assert (B * A + A = (B+1) * A)%positive.\n    rewrite Pmult_plus_distr_r.\n    zify; omega.\n  assert ((B+1) * A <= A * A)%positive.\n    zify.\n    apply Zmult_le_compat_r; omega.\n  zify; omega.\nQed.\n\nLemma num_iters__ge__num_iters_aux: \n  (num_iters >= \n    num_iters_aux (DomDS.start_state successors entrypoints))%positive.\nProof.\n  unfold num_iters, num_iters_aux, Pcubeplus. \n  assert (J1:=entry_num_of_doms).\n  assert (J2:=entry_psize_of_worklist).\n  revert J1 J2.\n  generalize \n    (num_of_doms (DomDS.st_in (DomDS.start_state successors entrypoints))) \n    as C.\n  intros C. intros.\n  assert (psize_of_cfg * (psize_of_cfg * psize_of_cfg) >= psize_of_cfg * C)%positive.\n    zify. apply Zmult_ge_compat_l; omega.\n  zify. omega.\nQed.\n\nLemma fixpoint_wf: forall ni (Hge: (ni >= num_iters)%positive),\n  exists res, \n    DomDS.fixpoint successors transfer entrypoints ni = Some res.\nProof.\n  intros.\n  apply fixpoint_iter.\n  Case \"1\".\n    assert (J:=num_iters__ge__num_iters_aux).\n    zify. omega.\n  Case \"2\". eapply DomsInParents.start_wf_doms; eauto.\n  Case \"3\". eapply WorklistProps.entrypoints_wf_state; eauto.\nQed.\n\nEnd Termination. End Termination.\n\nLtac termination_tac :=\nmatch goal with\n| Hlarge_enough: (?ni >= Termination.num_iters ?successors)%positive |- _ =>\n    let J:=fresh \"J\" in \n    assert (J:=Hlarge_enough);\n    eapply Termination.fixpoint_wf in J; eauto;\n    destruct J as [dms Hfix_tmn];\n    unfold Termination.entrypoints in Hfix_tmn;\n    rewrite Hfix_tmn in *\nend.\n\n(*********************************************************************)\n\n(* The main function that computes dominators. *)\nDefinition dom_analyze (f: fdef) : AMap.t Dominators.t :=\n  let '(fdef_intro _ bs) := f in\n  let top := Dominators.top in\n  match getEntryBlock f with\n  | Some (le, _) =>\n      match DomDS.fixpoint (successors_blocks bs) transfer\n        ((le, top) :: nil) (num_iters f) with\n      | None => AMap.init top\n      | Some res => res\n      end\n  | None => AMap.init top\n  end.\n\n(* The iteration bound we choose is large enough to ensure termination. *)\nSection Num_iters__is__large_enough.\n\nVariable f:fdef.\nHypothesis Huniq: uniqFdef f.\nHypothesis branches_in_bound_fdef: forall p ps0 cs0 tmn0 l2\n  (J3 : blockInFdefB (p, stmts_intro ps0 cs0 tmn0) f)\n  (J4 : In l2 (successors_terminator tmn0)),\n  In l2 (bound_fdef f).\n\nLemma num_iters__is__large_enough:\n  (num_iters f >= Termination.num_iters (successors f))%positive.\nProof.\n  intros. \n  assert (NoDup (XATree.elements_of_cfg (successors f) eq_atom_dec)) as Hpnodup.\n    apply remove_redundancy_NoDup; auto.\n  assert (NoDup (bound_fdef f)) as Hnodupf.\n    apply uniqFdef__NoDup_bounds_fdef; auto.\n  assert (J:=elements_of_acfg__eq__bound).\n  eapply AtomSet.NoDup_set_eq_length_eq in J; eauto using eq_atom_dec.\n  destruct f as [? bs]. simpl.\n  unfold num_iters, Termination.num_iters, pnum_of_blocks_in_fdef,\n         Termination.psize_of_cfg.\n  repeat rewrite plength_of_blocks__eq__P_of_plus_nat.\n  apply Pcubeplus_ge.\n  unfold Termination.elements_of_cfg, plength.\n  simpl in *. unfold ATree.elt in *. rewrite <- J.\n  rewrite <- P_of_plus_one_nat__P_of_succ_nat.\n  change 3%positive with (2+1)%positive.\n  rewrite <- P_of_plus_nat_Pplus_commut.\n  zify. omega.\nQed.\n\nEnd Num_iters__is__large_enough.\n\nLtac termination_tac2 :=\nlet foo pe :=\n  match goal with\n  | Huniq : uniqFdef ?f |- _ =>\n    let J := fresh \"J\" in\n    let dms := fresh \"dms\" in\n    let Hfix_tmn := fresh \"Hfix_tmn\" in\n    assert (J:=Huniq);\n    apply num_iters__is__large_enough in J; auto;\n    eapply Termination.fixpoint_wf with (entrypoint:=pe) in J; \n      try solve [eauto];\n    unfold Termination.entrypoints in J;\n    destruct J as [dms Hfix_tmn]; simpl in Hfix_tmn; unfold l in *;\n    rewrite Hfix_tmn in *\n  end in\nmatch goal with\n| |- context [DomDS.fixpoint (successors_blocks _) _ \n               ((?pe, _)::_) ?ni] => foo pe\n| _: context [DomDS.fixpoint (successors_blocks _) _ \n             ((?pe, _)::_) ?ni] |- _ => foo pe\nend.\n\nDefinition bound_dom bd (res: Dominators.t) : set atom :=\nmatch res with\n| Some dts2 => dts2\n| None => bd\nend.\n\nDefinition sdom f : atom -> set atom :=\nlet dt := dom_analyze f in\nlet b := bound_fdef f in\nfun l0 => bound_dom b (dt !! l0).\n\nImport AtomSet.\n\nLemma dom_entrypoint : forall f l0 s0\n  (Hentry : getEntryBlock f = Some (l0, s0)),\n  sdom f l0 = nil.\nProof.\n  intros.\n  unfold sdom, dom_analyze.\n  destruct f as [f b].\n  rewrite Hentry.\n  remember (DomDS.fixpoint (successors_blocks b)\n              transfer ((l0, Dominators.top) :: nil) \n              (num_iters (fdef_intro f b))) as R1.\n  destruct R1; subst.\n  SCase \"analysis is done\".\n    symmetry in HeqR1.\n    apply DomDS.fixpoint_entry with (n:=l0)(v:=Some nil) in HeqR1; simpl; eauto.\n    unfold DomDS.L.ge, DomDS.L.sub in HeqR1.\n    destruct (t !! l0); try tauto.\n      apply incl_empty_inv in HeqR1; subst; auto.\n\n  SCase \"analysis fails\".\n    rewrite AMap.gi. auto.\nQed.\n\n(* The entry point dominates all other nodes. *)\nModule EntryDomsOthers. Section EntryDomsOthers.\n\nVariable bs : blocks.\nDefinition predecessors := XATree.make_predecessors (successors_blocks bs).\nDefinition transf := transfer.\nDefinition top := Dominators.top.\nDefinition bot := Dominators.bot.\nVariable entry: l.\nVariable entrypoints: list (atom * DomDS.L.t).\n\nHypothesis wf_entrypoints:\n  match bs with\n  | (l0, _) :: _ => l0 = entry\n  | _ => False\n  end /\\\n  exists v, [(entry, v)] = entrypoints /\\ Dominators.eq v top.\n\nLemma dom_entry_start_state_in:\n  forall n v,\n  In (n, v) entrypoints ->\n  Dominators.eq (DomDS.start_state_in entrypoints)!!n v.\nProof.\n  destruct wf_entrypoints as [_ J]. clear wf_entrypoints.\n  destruct J as [v [Heq J]]; subst. simpl.\n  intros.\n  destruct H as [H | H]; inv H.\n  rewrite AMap.gss. rewrite AMap.gi.\n  apply Dominators.eq_trans with (y:=DomDS.L.lub v0 bot).\n    apply Dominators.lub_commut.\n    apply Dominators.lub_preserves_ge.\n    apply Dominators.ge_compat with (x:=top)(y:=bot).\n      apply Dominators.eq_sym; auto.\n      apply Dominators.eq_refl.\n      apply Dominators.ge_bot.\nQed.\n\nLemma dom_nonentry_start_state_in:\n  forall n,\n  n <> entry ->\n  Dominators.eq (DomDS.start_state_in entrypoints)!!n bot.\nProof.\n  destruct wf_entrypoints as [_ J]. clear wf_entrypoints.\n  destruct J as [v [Heq J]]; subst. simpl.\n  intros.\n  rewrite AMap.gi. rewrite AMap.gso; auto. rewrite AMap.gi.\n  apply Dominators.eq_refl.\nQed.\n\nLemma transf_mono: forall p x y,\n  Dominators.ge x y -> Dominators.ge (transf p x) (transf p y).\nProof.\n  unfold transf, transfer. intros.\n  apply Dominators.add_mono; auto.\nQed.\n\nDefinition lub_of_preds (res: AMap.t DomDS.L.t) (n:atom) : DomDS.L.t :=\n  Dominators.lubs (List.map (fun p => transf p res!!p)\n    (predecessors!!!n)).\n\nDefinition entry_doms_others (res: AMap.t DomDS.L.t) : Prop :=\n  forall l0, l0 <> entry -> Dominators.member entry res!!l0.\n\nLemma start_entry_doms_others:\n  entry_doms_others\n    (DomDS.st_in (DomDS.start_state (successors_blocks bs) entrypoints)).\nProof.\n  intros l0 Hneq.\n  apply dom_nonentry_start_state_in in Hneq.\n  unfold DomDS.start_state. simpl.\n  apply Dominators.member_eq with (x2:=bot); auto.\n  destruct wf_entrypoints as [J _]. unfold bot.\n  destruct bs; tinv J.\n  destruct b; subst. simpl. auto.\nQed.\n\n(** We show that the start state satisfies the invariant, and that\n  the [step] function preserves it. *)\n\nLemma propagate_succ_entry_doms_others: forall st n out,\n  Dominators.member entry out ->\n  entry_doms_others st.(DomDS.st_in) ->\n  entry_doms_others (DomDS.propagate_succ st out n).(DomDS.st_in).\nProof.\n  unfold entry_doms_others.\n  intros.\n  destruct (@DomDS.propagate_succ_spec st out n) as [J1 J2].\n  apply H0 in H1.\n  destruct (eq_atom_dec n l0); subst.\n    apply Dominators.member_eq with (a:=entry) in J1; auto.\n    apply Dominators.member_lub; auto.\n\n    rewrite J2; auto.\nQed.\n\nLemma propagate_succ_list_entry_doms_others:\n  forall scs st out,\n  Dominators.member entry out ->\n  entry_doms_others st.(DomDS.st_in) ->\n  entry_doms_others (DomDS.propagate_succ_list st out scs).(DomDS.st_in).\nProof.\n  induction scs; simpl; intros; auto.\n    apply IHscs; auto.\n    apply propagate_succ_entry_doms_others; auto.\nQed.\n\nLemma step_entry_doms_others:\n  forall st n rem,\n  AtomNodeSet.pick st.(DomDS.st_wrk) = Some(n, rem) ->\n  entry_doms_others st.(DomDS.st_in) ->\n  entry_doms_others (DomDS.propagate_succ_list\n                                  (DomDS.mkstate st.(DomDS.st_in) rem)\n                                  (transf n st.(DomDS.st_in)!!n)\n                                  ((successors_blocks bs)!!!n)).(DomDS.st_in).\nProof.\n  intros st n rem WKL GOOD.\n  destruct st. simpl.\n  apply propagate_succ_list_entry_doms_others; auto.\n    simpl in *.\n    unfold transf, transfer.\n    destruct (eq_atom_dec n entry); subst.\n      apply Dominators.add_member1.\n      destruct wf_entrypoints as [J _].\n      destruct bs; tinv J.\n      destruct b; subst. simpl. auto.\n\n      apply GOOD in n0.\n      apply Dominators.add_member2; auto.\nQed.\n\nTheorem dom_entry_doms_others: forall res ni,\n  DomDS.fixpoint (successors_blocks bs) transf entrypoints ni = Some res ->\n  entry_doms_others res.\nProof.\n  unfold DomDS.fixpoint. intros res ni PI. pattern res.\n  eapply (PrimIter.iter_prop _ _ (DomDS.step _ _)\n    (fun st => entry_doms_others st.(DomDS.st_in))); eauto.\n  intros st GOOD. unfold DomDS.step.\n  caseEq (AtomNodeSet.pick st.(DomDS.st_wrk)); auto.\n  intros [n rem] PICK.\n  apply step_entry_doms_others; auto.\n    apply start_entry_doms_others.\nQed.\n\nLemma dom_solution_ge: forall res ni,\n  DomDS.fixpoint (successors_blocks bs) transf entrypoints ni = Some res ->\n  forall n,\n  Dominators.ge res!!n (lub_of_preds res n).\nProof.\n  intros.\n  apply Dominators.lubs_spec3.\n  intros.\n  apply in_map_iff in H0.\n  destruct H0 as [x [J1 J2]]; subst.\n  eapply DomDS.fixpoint_solution; eauto.\n  apply XATree.make_predecessors_correct'; auto.\nQed.\n\nEnd EntryDomsOthers. End EntryDomsOthers.\n\nDefinition branchs_in_fdef f :=\n  forall (p : l) (ps0 : phinodes) (cs0 : cmds) \n         (tmn0 : terminator) (l2 : l),\n  blockInFdefB (p, stmts_intro ps0 cs0 tmn0) f ->\n  In l2 (successors_terminator tmn0) -> In l2 (bound_fdef f).\n\nLemma dom_in_bound: forall successors le t ni\n  (Hfix: DomDS.fixpoint successors transfer\n            ((le, Dominators.top) :: nil) ni = Some t),\n  forall l0 ns0 (Hget: t !! l0 = Some ns0) n (Hin: In n ns0),\n    In n (XATree.parents_of_tree successors).\nProof.\n  intros.\n  apply DomsInParents.fixpoint_wf in Hfix; auto.\n  assert (J:=Hfix l0).\n  unfold DomsInParents.wf_dom in J.\n  rewrite Hget in J. auto.\nQed.\n\nLemma dom_in_bound_blocks: forall bs le t ni\n  (Hfix: DomDS.fixpoint (successors_blocks bs) transfer\n            ((le, Dominators.top) :: nil) ni = Some t),\n  forall l0 ns0 (Hget: t !! l0 = Some ns0), incl ns0 (bound_blocks bs).\nProof.\n  intros.\n  intros x Hinx.\n  apply in_parents__in_bound.\n  eapply dom_in_bound; eauto.\nQed.\n\nLemma sdom_in_bound: forall fh bs l5, \n  incl (sdom (fdef_intro fh bs) l5) (bound_blocks bs).\nProof.\n  intros.\n  unfold sdom, dom_analyze.\n  destruct (getEntryBlock (fdef_intro fh bs)) as [[]|]; simpl. \n    remember (DomDS.fixpoint (successors_blocks bs) transfer\n                ((l0, Dominators.top) :: nil) \n                (num_iters (fdef_intro fh bs))) as R.\n    destruct R.\n      symmetry in HeqR.\n      remember (t !! l5) as R.\n      destruct R; try rewrite <- HeqR0; simpl; auto with datatypes.\n        eapply dom_in_bound_blocks; eauto.\n\n      rewrite AMap.gi. simpl. intros x Hin. inv Hin.\n    rewrite AMap.gi. simpl. intros x Hin. inv Hin.\nQed.\n\nLemma dom_successors : forall\n  (l3 : l) (l' : l) f\n  (contents3 contents': ListSet.set atom)\n  (Hinscs : In l' (successors f) !!! l3)\n  (Heqdefs3 : contents3 = sdom f l3)\n  (Heqdefs' : contents' = sdom f l'),\n  incl contents' (l3 :: contents3).\nProof.\n  intros. \n  unfold sdom, dom_analyze in *.\n  remember (getEntryBlock f) as R.\n  destruct f as [fh bs].\n  destruct R as [[le []]|].\n  Case \"entry is good\".\n    remember (DomDS.fixpoint (successors_blocks bs)\n                transfer ((le, Dominators.top) :: nil)\n                (num_iters (fdef_intro fh bs))) as R1.\n    destruct R1; subst.\n    SCase \"analysis is done\".\n      symmetry in HeqR1.\n      assert (Hinbd: forall l0 ns0 (Hget: t !! l0 = Some ns0), \n                     incl ns0 (bound_blocks bs)).\n        eapply dom_in_bound_blocks; eauto.\n      apply DomDS.fixpoint_solution with (s:=l')(n:=l3) in HeqR1; eauto.\n      unfold transfer, DomDS.L.ge, DomDS.L.sub, Dominators.add in HeqR1.\n      remember (t !! l') as R2.\n      remember (t !! l3) as R3.\n      destruct R2 as [els2|]; destruct R3 as [els3|];\n      try rewrite <- HeqR2; try rewrite <- HeqR3;\n        simpl; try solve [auto with datatypes | tauto].\n        symmetry in HeqR2.\n        apply Hinbd in HeqR2. auto with datatypes.\n\n    SCase \"analysis fails\".\n      repeat rewrite AMap.gi. simpl. auto with datatypes.\n\n  Case \"entry is wrong\".\n    subst. repeat rewrite AMap.gi. simpl. auto with datatypes.\nQed.\n\n(* The completeness of the analysis. *)\nModule DomComplete. Section DomComplete.\n\nVariable fh : fheader.\nVariable bs : blocks.\nDefinition predecessors := XATree.make_predecessors (successors_blocks bs).\nDefinition transf := transfer.\nDefinition top := Dominators.top.\nDefinition bot := Dominators.bot.\nVariable entry: l.\nVariable entrypoints: list (atom * DomDS.L.t).\n\nHypothesis wf_entrypoints:\n  match bs with\n  | (l0, _) :: _ => l0 = entry\n  | _ => False\n  end /\\\n  exists v, [(entry, v)] = entrypoints /\\ Dominators.eq v top.\n\nDefinition non_sdomination (l1 l2:l) : Prop :=\n  ACfg.non_sdomination (successors (fdef_intro fh bs)) entry l1 l2.\n\nDefinition non_sdomination_prop (res: AMap.t DomDS.L.t) : Prop :=\n  forall l1 l2,\n    vertexes_fdef (fdef_intro fh bs) (index l1) ->\n    ~ Dominators.member l1 res!!l2 ->\n    non_sdomination l1 l2.\n\nLemma start_non_sdomination:\n  non_sdomination_prop\n    (DomDS.st_in (DomDS.start_state (successors_blocks bs) entrypoints)).\nProof.\n  intros l1 l2 Hin Hnotin.\n  destruct (eq_atom_dec l2 entry); try subst l2.\n    unfold non_sdomination.\n    exists V_nil. exists A_nil.\n    split.\n      constructor.\n      destruct wf_entrypoints as [J _].\n      destruct bs; tinv J.\n      destruct b; subst.\n      eapply entry_in_vertexes; simpl; eauto.\n\n      intro J. inv J.\n\n    eapply EntryDomsOthers.dom_nonentry_start_state_in in n; eauto.\n    contradict Hnotin.\n    unfold DomDS.start_state. simpl.\n    apply Dominators.member_eq with (x2:=bot); simpl; auto.\nQed.\n\nLemma non_sdomination_refl : forall l1,\n  l1 <> entry ->\n  reachable (fdef_intro fh bs) l1 ->\n  non_sdomination l1 l1.\nProof.\n  unfold reachable, non_sdomination. \n  intros.\n  destruct bs as [|[]]; simpl in *; try congruence.\n  destruct wf_entrypoints as [Heq _]; subst.\n  apply ACfg.non_sdomination_refl; auto.\nQed.\n\nLemma propagate_succ_non_sdomination: forall st p n out\n  (Hinpds: In p predecessors!!!n)\n  (Hout: Dominators.ge (transf p st.(DomDS.st_in)!!p) out)\n  (Hdom: non_sdomination_prop st.(DomDS.st_in)),\n  non_sdomination_prop (DomDS.propagate_succ st out n).(DomDS.st_in).\nProof.\n  unfold non_sdomination_prop. intros.\n  destruct (@DomDS.propagate_succ_spec st out n) as [J1 J2].\n  destruct (eq_atom_dec n l2) as [Heq | Hneq]; subst.\n  Case \"n=l2\".\n    destruct (Dominators.member_dec l1 (DomDS.st_in st) !! l2)\n      as [Hin12 | Hnotin12]; auto.\n    assert (~ Dominators.member l1\n      (DomDS.L.lub (DomDS.st_in st) !! l2 out)) as Hnotlub12.\n      intro J. apply H0.\n      eapply Dominators.member_eq; eauto.\n    clear J1 J2.\n    destruct (Dominators.member_dec l1 out) as [Hinout | Hnotout]; auto.\n    SCase \"l1 in out\".\n      contradict Hnotlub12. apply Dominators.lub_intro; auto.\n    SCase \"l1 notin out\".\n      assert (~ Dominators.member l1 (transf p (DomDS.st_in st) !! p))\n        as Hnotintransf.\n        intro J. apply Hnotout.\n        eapply Dominators.ge_elim in Hout; eauto.\n      unfold transf, transfer in Hnotintransf.\n      assert (l1 <> p /\\ ~ Dominators.member l1 (DomDS.st_in st)!!p)\n        as J.\n        split; intro J; subst; apply Hnotintransf.\n          apply Dominators.add_member1; auto.\n          apply Dominators.add_member2; auto.\n      clear Hnotintransf.\n      destruct J as [Hneq J].\n      apply Hdom in J; auto.\n      destruct J as [vl [al [J1 J2]]].\n      exists (index p::vl). exists (A_ends (index l2) (index p)::al).\n      split.\n      SSCase \"1\".\n        apply XATree.make_predecessors_correct' in Hinpds.\n        change (successors_blocks bs) with (successors (fdef_intro fh bs))\n          in Hinpds.\n        constructor; eauto.\n          eapply XATree.in_succ__in_cfg; eauto.\n\n      SSCase \"2\".\n          intro J. simpl in J.\n          destruct J as [J | J]; auto.\n            inv J. auto.\n  Case \"n<>l2\".\n    rewrite J2 in H0; auto.\nQed.\n\nLemma propagate_succ_list_non_sdomination_aux:\n  forall p scs st out,\n  (forall s, In s scs -> In p predecessors!!!s) ->\n  non_sdomination_prop st.(DomDS.st_in) ->\n  Dominators.ge (transf p st.(DomDS.st_in)!!p) out ->\n  non_sdomination_prop (DomDS.propagate_succ_list st out scs).(DomDS.st_in).\nProof.\n  induction scs; simpl; intros; auto.\n    apply IHscs; auto.\n      eapply propagate_succ_non_sdomination; eauto.\n      apply Dominators.ge_trans with (y:=transf p (DomDS.st_in st) !! p);\n        auto.\n        eapply EntryDomsOthers.transf_mono; eauto.\n        destruct (@DomDS.propagate_succ_spec st out a) as [J1 J2].\n        destruct (eq_atom_dec a p); subst.\n          apply Dominators.ge_trans with\n            (y:=Dominators.lub (DomDS.st_in st) !! p out).\n            apply Dominators.ge_refl; auto.\n            apply Dominators.ge_lub_left.\n          rewrite J2; auto.\n            apply Dominators.ge_refl'.\nQed.\n\nLemma propagate_succ_list_non_sdomination:\n  forall p scs st,\n  (forall s, In s scs -> In p predecessors!!!s) ->\n  non_sdomination_prop st.(DomDS.st_in) ->\n  non_sdomination_prop (DomDS.propagate_succ_list st\n    (transf p st.(DomDS.st_in)!!p) scs).(DomDS.st_in).\nProof.\n  intros.\n  eapply propagate_succ_list_non_sdomination_aux; eauto.\n    apply Dominators.ge_refl'.\nQed.\n\nLemma step_non_sdomination:\n  forall st n rem,\n  AtomNodeSet.pick st.(DomDS.st_wrk) = Some(n, rem) ->\n  non_sdomination_prop st.(DomDS.st_in) ->\n  non_sdomination_prop (DomDS.propagate_succ_list \n                                 (DomDS.mkstate st.(DomDS.st_in) rem)\n                                 (transf n st.(DomDS.st_in)!!n)\n                                 ((successors_blocks bs)!!!n)).(DomDS.st_in).\nProof.\n  intros st n rem WKL GOOD.\n  destruct st. simpl.\n  apply propagate_succ_list_non_sdomination; auto.\n    apply XATree.make_predecessors_correct.\nQed.\n\nTheorem dom_non_sdomination: forall res ni,\n  DomDS.fixpoint (successors_blocks bs) transf entrypoints ni = Some res ->\n  non_sdomination_prop res.\nProof.\n  unfold DomDS.fixpoint. intros res ni PI. pattern res.\n  eapply (PrimIter.iter_prop _ _ (DomDS.step _ _)\n    (fun st => non_sdomination_prop st.(DomDS.st_in))); eauto.\n    intros st GOOD. unfold DomDS.step.\n    caseEq (AtomNodeSet.pick st.(DomDS.st_wrk)); auto.\n    intros [n rem] PICK. apply step_non_sdomination; auto.\n\n    apply start_non_sdomination.\nQed.\n\nEnd DomComplete. End DomComplete.\n\nSection sdom_is_complete.\n\nVariable f:fdef.\nHypothesis branches_in_bound_fdef: branchs_in_fdef f.\n\nLemma sdom_is_complete: forall\n  (l3 : l) (l' : l) s3 s'\n  (HuniqF : uniqFdef f)\n  (HBinF' : blockInFdefB (l', s') f = true)\n  (HBinF : blockInFdefB (l3, s3) f = true)\n  (Hsdom: strict_domination f l' l3),\n  In l' (sdom f l3).\nProof.\n  intros. \n  unfold sdom, dom_analyze in *. \n  destruct f as [fh bs].\n  assert (Hentry:=Hsdom). apply DecDom.strict_domination__getEntryLabel in Hentry.\n  destruct Hentry as [e Hentry].\n  apply getEntryLabel__getEntryBlock in Hentry.\n  destruct Hentry as [[le []] [Hentry Heq]]; subst e.\n  rewrite Hentry.\n  termination_tac2.\n  eapply DomComplete.dom_non_sdomination with (entry:=le) in Hfix_tmn; eauto.\n    SSCase \"1\".\n      unfold DomComplete.non_sdomination_prop in Hfix_tmn.\n      assert (vertexes_fdef (fdef_intro fh bs) (index l')) as J.\n        apply blockInFdefB_in_vertexes in HBinF'; auto.\n      destruct (Dominators.member_dec l' (dms!!l3)).\n      SSSCase \"1\".\n        unfold Dominators.member in H.\n        destruct (dms!!l3); auto.\n          apply blockInFdefB_in_bound_fdef in HBinF'. auto.\n\n      SSSCase \"2\".\n        apply Hfix_tmn with (l2:=l3) in J; auto.\n          unfold DomComplete.non_sdomination in J.\n          destruct J as [vl [al [J1 J2]]].\n          unfold strict_domination in Hsdom. autounfold with cfg in Hsdom.\n          rewrite Hentry in Hsdom.\n          simpl in Hsdom.\n          apply Hsdom in J1.\n          destruct J1; subst; congruence.\n\n    SSCase \"2\".\n      split.\n        simpl in *.\n        destruct bs; uniq_result; auto.\n\n        exists Dominators.top. \n        split; auto. simpl. apply set_eq_refl.\nQed.\n\nEnd sdom_is_complete.\n\n(* Unreachable nodes are dominated by any nodes. *)\nModule UnreachableDoms. Section UnreachableDoms.\n\nVariable fh : fheader.\nVariable bs : blocks.\nDefinition predecessors := XATree.make_predecessors (successors_blocks bs).\nDefinition transf := transfer.\nDefinition top := Dominators.top.\nDefinition bot := Dominators.bot.\nVariable entry: l.\nVariable entrypoints: list (atom * DomDS.L.t).\n\nHypothesis wf_entrypoints:\n  match bs with\n  | (l0, _) :: _ => l0 = entry\n  | _ => False\n  end /\\\n  exists v, [(entry, v)] = entrypoints /\\ Dominators.eq v top.\n\nDefinition unreachable_doms (res: AMap.t DomDS.L.t) : Prop :=\n  forall l0, ~ reachable (fdef_intro fh bs) l0 -> l0 <> entry ->\n  Dominators.eq res!!l0 bot.\n\nLemma start_unreachable_doms:\n  unreachable_doms\n    (DomDS.st_in (DomDS.start_state (successors_blocks bs) entrypoints)).\nProof.\n  intros l0 Hunreach Heq.\n  unfold DomDS.start_state. simpl.\n  eapply EntryDomsOthers.dom_nonentry_start_state_in in Heq; eauto.\nQed.\n\n(** We show that the start state satisfies the invariant, and that\n  the [step] function preserves it. *)\n\nLemma propagate_succ_unreachable_doms: forall st n out,\n  (~ reachable (fdef_intro fh bs) n -> n <> entry -> \n   Dominators.eq out bot) ->\n  unreachable_doms st.(DomDS.st_in) ->\n  unreachable_doms (DomDS.propagate_succ st out n).(DomDS.st_in).\nProof.\n  unfold unreachable_doms.\n  intros.\n  destruct (@DomDS.propagate_succ_spec st out n) as [J1 J2].\n  assert (H':=H1).\n  apply H0 in H1; auto.\n  destruct (eq_atom_dec n l0); subst.\n    apply H in H'; auto.\n    apply Dominators.eq_trans with\n      (y:=DomDS.L.lub (DomDS.st_in st) !! l0 out); auto.\n    apply Dominators.eq_trans with (y:=DomDS.L.lub bot bot); auto.\n       apply Dominators.lub_compat_eq; auto.\n       apply Dominators.eq_sym. apply Dominators.lub_refl.\n\n    rewrite J2; auto.\nQed.\n\nLemma propagate_succ_list_unreachable_doms:\n  forall scs st out,\n  (forall s, In s scs ->\n             ~ reachable (fdef_intro fh bs) s -> s <> entry ->\n             Dominators.eq out bot) ->\n  unreachable_doms st.(DomDS.st_in) ->\n  unreachable_doms (DomDS.propagate_succ_list st out scs).(DomDS.st_in).\nProof.\n  induction scs; simpl; intros; auto.\n    apply IHscs.\n      intros. apply H with (s:=s); auto.\n      apply propagate_succ_unreachable_doms; auto.\n        intros J1 J2. eapply H; eauto.\nQed.\n\nHypothesis UniqF: uniqFdef (fdef_intro fh bs).\n\nLemma step_unreachable_doms:\n  forall st n rem,\n  AtomNodeSet.pick st.(DomDS.st_wrk) = Some(n, rem) ->\n  unreachable_doms st.(DomDS.st_in) ->\n  unreachable_doms (DomDS.propagate_succ_list \n                                  (DomDS.mkstate st.(DomDS.st_in) rem)\n                                  (transf n st.(DomDS.st_in)!!n)\n                                  ((successors_blocks bs)!!!n)).(DomDS.st_in).\nProof.\n  intros st n rem WKL GOOD.\n  destruct st. simpl.\n  apply propagate_succ_list_unreachable_doms; auto.\n  intros s Hin Hunreach.\n    destruct (reachable_dec (fdef_intro fh bs) n).\n    Case \"reach\".\n      assert(exists ps0, exists cs0, exists tmn0,\n        blockInFdefB (n, stmts_intro ps0 cs0 tmn0) (fdef_intro fh bs) /\\\n        In s (successors_terminator tmn0)) as J.\n        apply successors__blockInFdefB; auto.\n      destruct J as [ps0 [cs0 [tmn0 [J1 J2]]]].\n      eapply DecRD.reachable_successors with (l1:=s) in H; eauto.\n        congruence.\n        eapply XATree.in_succ__in_cfg; eauto.\n\n    Case \"unreach\".\n      apply GOOD in H. simpl in H.\n      unfold transf, transfer.\n      intros.\n      destruct (eq_atom_dec n entry); subst.\n        assert (exists ps0, exists cs0, exists tmn0,\n          blockInFdefB (entry, stmts_intro ps0 cs0 tmn0) (fdef_intro fh bs) /\\\n          In s (successors_terminator tmn0)) as J.\n          apply successors__blockInFdefB; auto.\n        destruct J as [ps0 [cs0 [tmn0 [J1 J2]]]].\n        contradict Hunreach.\n        unfold reachable. \n        destruct wf_entrypoints as [J _].\n        destruct bs as [|b ?]; tinv J. \n        destruct b as [l5 ? ? ?]. subst entry. \nLocal Opaque successors. \n        simpl. clear J.\n        exists (index l5::nil). exists (A_ends (index s) (index l5)::nil).\n        constructor; eauto.\n          constructor.\n            eapply entry_in_vertexes; simpl; eauto.\n          eapply XATree.in_succ__in_cfg; eauto.\n      apply Dominators.eq_trans with (y:=Dominators.add (Dominators.bot) n).\n        apply Dominators.add_eq; auto.\n        apply Dominators.add_bot.\nTransparent successors.\nQed.\n\nTheorem dom_unreachable_doms: forall res ni,\n  DomDS.fixpoint (successors_blocks bs) transf entrypoints ni = Some res ->\n  unreachable_doms res.\nProof.\n  unfold DomDS.fixpoint. intros res ni PI. pattern res.\n  eapply (PrimIter.iter_prop _ _ (DomDS.step _ _)\n    (fun st => unreachable_doms st.(DomDS.st_in))); eauto.\n  intros st GOOD. unfold DomDS.step.\n  caseEq (AtomNodeSet.pick st.(DomDS.st_wrk)); auto.\n  intros [n rem] PICK.\n  apply step_unreachable_doms; auto.\n    apply start_unreachable_doms.\nQed.\n\nEnd UnreachableDoms. End UnreachableDoms. \n\nSection dom_unreachable.\n\nVariable f:fdef.\nHypothesis branches_in_bound_fdef: branchs_in_fdef f.\nHypothesis Hhasentry: getEntryBlock f <> None.\n\nLemma dom_unreachable: forall\n  (l3 : l) s3\n  (HuniqF: uniqFdef f)\n  (HBinF : blockInFdefB (l3, s3) f = true)\n  (Hunreach: ~ reachable f l3),\n  sdom f l3 = bound_fdef f.\nProof.\n  intros.\n  case_eq (getEntryBlock f); try congruence.\n  intros [l0 [p c t]] Hentry. \n  match goal with | H1: getEntryBlock _ = _ |- _ =>\n    assert (J:=H1); apply dom_entrypoint in H1 end.\n  destruct f as [fh bs].\n  destruct (id_dec l3 l0); subst.\n  Case \"l3=l0\".\n    contradict Hunreach.\n    eapply reachable_entrypoint; eauto.\n  Case \"l3<>l0\".\n    unfold sdom, dom_analyze in *.\n    match goal with | H1: getEntryBlock _ = _ |- _ => rewrite H1 in * end.\n    termination_tac2.\n    eapply UnreachableDoms.dom_unreachable_doms with (entry:=l0) in Hfix_tmn;\n      eauto.\n    SCase \"1\".\n      apply Hfix_tmn in n; auto.\n      simpl. destruct dms !! l3; tinv n. auto.\n    SCase \"2\".\n      split.\n        simpl in J.\n        destruct bs; uniq_result; auto.\n\n        exists Dominators.top. \n        split; auto. simpl. apply set_eq_refl.\nQed.\n\nEnd dom_unreachable.\n\n(* Transformationthat preserve CFGs preserves analysis results. *)\nSection pres_dom.\n\nVariable ftrans: fdef -> fdef.\nVariable btrans: block -> block.\n\nHypothesis ftrans_spec: forall fh bs, \n  ftrans (fdef_intro fh bs) = fdef_intro fh (List.map btrans bs).\n\nHypothesis btrans_eq_label: forall b, getBlockLabel b = getBlockLabel (btrans b).\n\nLemma pres_getEntryBlock : forall f b\n  (Hentry : getEntryBlock f = Some b),\n  getEntryBlock (ftrans f) = Some (btrans b).\nProof.\n  intros. destruct f as [fh bs]. rewrite ftrans_spec.\n  destruct bs; inv Hentry; auto.\nQed.\n\nLemma pres_getEntryBlock_None : forall f\n  (Hentry : getEntryBlock f = None),\n  getEntryBlock (ftrans f) = None.\nProof.\n  intros. destruct f as [fh bs]. rewrite ftrans_spec.\n  destruct bs; inv Hentry; auto.\nQed.\n\nLemma pres_bound_blocks : forall bs,\n  bound_blocks bs = bound_blocks (List.map btrans bs).\nProof.\n  induction bs as [|a bs]; simpl; auto.\n    assert (J:=btrans_eq_label a);\n    remember (btrans a) as R.\n    destruct R as [l1 ? ? ?]; destruct a; simpl in *; subst l1.\n    congruence.\nQed.\n\nHypothesis btrans_eq_tmn: forall b, \n  terminator_match (getTerminator b) (getTerminator (btrans b)).\n\nLemma pres_successors_blocks : forall bs,\n  successors_blocks bs = successors_blocks (List.map btrans bs).\nProof.\n  induction bs as [|b bs]; simpl; auto.\n    assert (J:=btrans_eq_tmn b).\n    assert (J':=btrans_eq_label b).\n    remember (btrans b) as R.\n    destruct R as [l1 []]; destruct b as [? []]; simpl in *; subst l1.\n    rewrite IHbs. \n    terminator_match_tac.\nQed.\n\nLemma pres_num_iters: forall f, num_iters f = num_iters (ftrans f).\nProof.\n  destruct f as [fh bs]. \n  rewrite ftrans_spec. unfold num_iters. simpl.\n  f_equal.\n  generalize 3%positive.\n  induction bs; simpl; intros; auto.\nQed.\n\nLemma pres_sdom: forall (f : fdef) (l5 l0 : l),\n  ListSet.set_In l5 (AlgDom.sdom f l0) <->\n  ListSet.set_In l5 (AlgDom.sdom (ftrans f) l0).\nProof.\n  intros.\n  unfold AlgDom.sdom, AlgDom.dom_analyze. destruct f as [fh bs]. \n  case_eq (getEntryBlock (fdef_intro fh bs)).\n    intros b Hentry.\n    apply pres_getEntryBlock in Hentry; eauto.\n    assert (J:=btrans_eq_label b);\n    remember (btrans b) as R.\n    destruct R as [l1 ? ? ?]; destruct b; simpl in *; subst l1.\n    rewrite Hentry. rewrite <- pres_num_iters.\n    rewrite ftrans_spec. simpl.\n    rewrite <- pres_bound_blocks.\n    rewrite <- pres_successors_blocks. split; eauto.\n\n    intros Hentry.\n    apply pres_getEntryBlock_None in Hentry; eauto.\n    rewrite Hentry. rewrite ftrans_spec. simpl.\n    rewrite <- pres_bound_blocks. split; auto.\nQed.\n\nEnd pres_dom.\n\nEnd AlgDom.\n\nModule AlgDomProps := AlgDom_Properties (AlgDom).\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/Dominators/dom_set.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2845996318304377}}
{"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 terms_per.\nRequire Export csubst2.\n\n(*\nLemma subst_mk_erase :\n  forall a v u,\n    isprog u\n    -> subst (mk_erase a) v u = mk_erase (subst a v u).\nProof.\n  introv isp.\n  unfold subst, mk_erase, mk_ufun, newvar, fresh_var; simpl.\n  fold nvarx.\n  destruct (deq_nvar nvarx v); subst.\n  apply subst_mk_isect2; auto.\n  apply subst_mk_isect; auto.\nQed.\n*)\n\nLemma cover_vars_erase_rel {o} :\n  forall a s,\n    cover_vars (@erase_rel o a) s\n    <=> cover_vars a s.\nProof.\n  introv.\n  unfold erase_rel.\n  remember (newvars2 [a]); repnd.\n  apply newvars2_prop2 in Heqp; allsimpl; allrw app_nil_r; repnd.\n  rw @cover_vars_lam.\n  rw @cover_vars_upto_lam.\n  rw <- @csub_filter_app_r; simpl.\n  apply cover_vars_upto_csub_filter_disjoint; sp.\n  rw eqvars_prop; simpl; sp; split; sp.\n  repeat (rw disjoint_cons_r); sp.\nQed.\n\nLemma cover_vars_upto_erase_rel {o} :\n  forall a s vs,\n    cover_vars_upto (@erase_rel o a) s vs\n    <=> cover_vars_upto a s vs.\nProof.\n  introv.\n  unfold erase_rel.\n  remember (newvars2 [a]); repnd.\n  apply newvars2_prop2 in Heqp; allsimpl; allrw app_nil_r; repnd.\n  rw @cover_vars_upto_lam.\n  rw @cover_vars_upto_lam.\n  rw <- @csub_filter_app_r; simpl.\n  assert (p :: p0 :: vs = [p,p0] ++ vs) as e by sp; rw e; clear e.\n  apply cover_vars_upto_csub_filter_app.\n  rw eqvars_prop; simpl; sp; split; sp.\n  repeat (rw disjoint_cons_r); sp.\nQed.\n\nLemma covered_erase_rel {o} :\n  forall a vs,\n    covered (@erase_rel o a) vs\n    <=> covered a vs.\nProof.\n  introv.\n  unfold erase_rel.\n  remember (newvars2 [a]); repnd.\n  apply newvars2_prop2 in Heqp; allsimpl; allrw app_nil_r; repnd.\n  rw @covered_lam.\n  rw @covered_lam.\n  generalize (covered_cons_weak_iff a p Heqp1 (p0 :: vs)); intro e; rw e; clear e.\n  apply covered_cons_weak_iff; sp.\nQed.\n\nLemma cover_vars_erase {o} :\n  forall a s,\n    cover_vars (@erase o a) s\n    <=> cover_vars a s.\nProof.\n  introv.\n  unfold erase.\n  rw @cover_vars_pertype.\n  rw @cover_vars_erase_rel; sp.\nQed.\n\nLemma cover_vars_upto_erase {o} :\n  forall a s vs,\n    cover_vars_upto (@erase o a) s vs\n    <=> cover_vars_upto a s vs.\nProof.\n  introv.\n  unfold erase.\n  rw @cover_vars_upto_pertype.\n  rw @cover_vars_upto_erase_rel; sp.\nQed.\n\nLemma covered_erase {o} :\n  forall a vs,\n    covered (@erase o a) vs\n    <=> covered a vs.\nProof.\n  introv.\n  rw @covered_pertype.\n  apply covered_erase_rel.\nQed.\n\nLemma cover_vars_uand {o} :\n  forall A B s,\n    cover_vars (@mk_uand o A B) s\n    <=> (cover_vars A s # cover_vars B s).\nProof.\n  introv.\n  rw @cover_vars_eq.\n  rw @free_vars_uand.\n  rw subvars_app_l; sp.\nQed.\n\nLemma cover_vars_mk_per_function_rel {o} :\n  forall A B s,\n    cover_vars (@mk_per_function_rel o A B) s\n    <=> (cover_vars A s # cover_vars B s).\nProof.\n  introv.\n  allrw @cover_vars_eq.\n  rw @free_vars_per_function_rel_eq.\n  allrw subvars_app_l; split; sp.\nQed.\n\nLemma covered_per_function_rel {o} :\n  forall a b vs,\n    covered (@mk_per_function_rel o a b) vs\n    <=> covered a vs\n        # covered b vs.\nProof.\n  introv.\n  unfold covered.\n  rw @free_vars_per_function_rel_eq.\n  allrw subvars_app_l; split; sp.\nQed.\n\nLemma cover_vars_per_function {o} :\n  forall A B s,\n    cover_vars (@mk_per_function o A B) s\n    <=> (cover_vars A s # cover_vars B s).\nProof.\n  introv.\n  unfold mk_per_function.\n  rw @cover_vars_pertype.\n  rw @cover_vars_mk_per_function_rel; sp.\nQed.\n\nLemma unfold_mk_uand {o} :\n  forall A B,\n    {v1, v2 : NVar\n     $ @mk_uand o A B\n       = mk_isect mk_base v1\n                  (mk_isect (mk_halts (mk_var v1)) v2\n                            (mk_isaxiom (mk_var v1) A B))\n     # (v1, v2) = newvars2 [A, B] }.\nProof.\n  introv.\n  remember (newvarlst [A,B]) as v1.\n  exists v1.\n  remember (newvarlst ([A,B] ++ [mk_var v1])) as v2.\n  exists v2.\n  subst; sp.\nQed.\n\nLemma unfold_mk_per_function_rel {o} :\n  forall A B,\n    {v1, v2, v3, v4, v5 : NVar\n     $ mk_per_function_rel A B\n       = mk_lam\n           v3\n           (mk_lam\n              v4\n              (erase\n                 (mk_isect\n                    mk_base\n                    v1\n                    (mk_isect\n                       mk_base\n                       v2\n                       (mk_isect\n                          (mk_equality (mk_var v1) (mk_var v2) A)\n                          v5\n                          (mk_uand\n                             (mk_equality\n                                (mk_apply (mk_var v3) (mk_var v1))\n                                (mk_apply (mk_var v4) (mk_var v2))\n                                (mk_apply B (mk_var v1)))\n                             (mk_tequality\n                                (mk_apply B (mk_var v1))\n                                (mk_apply B (@mk_var o v2)))))))))\n     # (v1, v2, v3, v4, v5) = newvars5 [A, B] }.\nProof.\n  introv.\n  remember (newvarlst [A,B]) as v1.\n  exists v1.\n  remember (newvarlst ([A,B] ++ [mk_var v1])) as v2.\n  exists v2.\n  remember (newvarlst ([A,B] ++ [mk_var v1, mk_var v2])) as v3.\n  exists v3.\n  remember (newvarlst ([A,B] ++ [mk_var v1, mk_var v2, mk_var v3])) as v4.\n  exists v4.\n  remember (newvarlst ([A,B] ++ [mk_var v1, mk_var v2, mk_var v3, mk_var v4])) as v5.\n  exists v5.\n  subst; sp.\nQed.\n\n(*\nLemma lsubstc_mk_per_function_rel :\n  forall A B sub,\n  forall w1 : wf_term A,\n  forall w2 : wf_term B,\n  forall w  : wf_term (mk_per_function_rel A B),\n  forall c1 : cover_vars A sub,\n  forall c2 : cover_vars B sub,\n  forall c  : cover_vars (mk_per_function_rel A B) sub,\n    alphaeqc\n      (lsubstc (mk_per_function_rel A B) w sub c)\n      (mkc_per_function_rel\n         (lsubstc A w1 sub c1)\n         (lsubstc B w2 sub c2)).\nProof.\n  sp; unfold lsubstc; simpl.\n  remember (isprog_csubst (mk_per_function_rel A B) sub w c) as isp1; clear Heqisp1.\n  remember (isprog_mk_per_function_rel\n              (csubst A sub)\n              (csubst B sub)\n              (isprog_csubst A sub w1 c1)\n              (isprog_csubst B sub w2 c2)) as isp2; clear Heqisp2.\n  generalize (unfold_mk_per_function_rel A B); introv eq; exrepnd.\n  generalize (unfold_mk_per_function_rel (csubst A sub) (csubst B sub)); introv eq; exrepnd.\n\n  unfold alphaeqc; simpl.\n  clear isp1 isp2.\n\n  rewrite eq1; clear eq1.\n  rewrite eq3; clear eq3.\n\n  repeat (rewrite csubst_mk_lam);\n    repeat (rewrite csubst_mk_isect);\n    repeat (rewrite csubst_mk_base);\n    repeat (rewrite csubst_mk_equality);\n    repeat (rewrite csubst_mk_apply);\n    repeat (rewrite <- csub_filter_app_r); simpl;\n    repeat (rewrite csubst_mk_var_out2; [idtac | complete sp]).\n\n(*\n  apply alpha_eq_lam.\n  apply isprogram_lam.\n  apply isprog_vars_lam.\n  apply isprog_vars_isect.\n  apply isprog_vars_base.\n  apply isprog_vars_isect.\n  apply isprog_vars_base.\n  apply isprog_vars_isect.\n  apply isprog_vars_equality.\n  apply isprog_vars_var_if; sp.\n  apply isprog_vars_var_if; sp.\n  apply isprog_vars_csubst; sp.\n  apply nt_wf_eq; sp.\nadmit.\n  apply isprog_vars_equality.\n  apply isprog_vars_apply; sp.\n  apply isprog_vars_var_if; sp.\n  apply isprog_vars_var_if; sp.\n  apply isprog_vars_apply; sp.\n  apply isprog_vars_var_if; sp.\n  apply isprog_vars_var_if; sp.\n  apply isprog_vars_apply; sp.\n  apply isprog_vars_csubst; sp.\n  apply nt_wf_eq; sp.\nadmit.\n  apply isprog_vars_var_if; sp.\n*)\n\nAbort.\n\nLemma lsubstc_mk_per_function_rel_ex :\n  forall 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        & alphaeqc\n            (lsubstc (mk_per_function_rel A B) w s c)\n            (mkc_per_function_rel\n               (lsubstc A wa s ca)\n               (lsubstc B wb s cb))}}}}.\nProof.\n  introv.\n  duplicate w as w'.\n  rw wf_term_mk_per_function_rel in w; repnd.\n  exists w0 w.\n  duplicate c as c'.\n  rw cover_vars_mk_per_function_rel in c; repnd.\n  exists c0 c.\n\n  unfold alphaeqc; simpl.\n  allrw csubst_as_lsubst_aux.\n\n(*\n  unfold mk_per_function_rel at 1.\n  remember (newvars5 [A,B]); repnd.\n  allrw lsubst_aux_lam_csub2sub; allrw <- csub_filter_app_r.\n  allrw lsubst_aux_isect_csub2sub; allrw <- csub_filter_app_r.\n  allrw lsubst_aux_base_csub2sub.\n  allrw lsubst_aux_equality_csub2sub; allrw <- csub_filter_app_r.\n  allrw lsubst_aux_apply_csub2sub; allrw <- csub_filter_app_r.\n  allrw lsubst_aux_var_csub2sub_out;\n    try (complete (rw dom_csub_csub_filter; rw in_remove_nvars; simpl; sp;\n                   apply newvars5_prop2 in Heqp; repnd;\n                   repeat (apply not_over_or in X; repnd); sp)).\n  simpl.\n\n  duplicate Heqp as nv5.\n  apply newvars5_prop2 in Heqp; repnd; allsimpl; allrw app_nil_r; allrw in_app_iff.\n  apply not_over_or in Heqp0; repnd.\n  apply not_over_or in Heqp1; repnd.\n  apply not_over_or in Heqp2; repnd.\n  apply not_over_or in Heqp3; repnd.\n  apply not_over_or in Heqp4; repnd.\n\n  allrw <- sub_filter_csub2sub.\n  allrw lsubst_aux_sub_filter;\n    try (complete (sp; allapply in_csub2sub; sp));\n    try (complete (unfold disjoint; simpl; sp; subst; sp)).\n\n  unfold mk_per_function_rel.\n  remember (newvars5 [lsubst_aux A (csub2sub s), lsubst_aux B (csub2sub s)]); repnd.\n\n  constructor; simpl; sp; unfold selectbt; destruct n; sp; simpl.\n  generalize (fresh_vars 5 (all_vars A ++ all_vars B ++ [p, p0, p1, p2, p3] ++ [p4, p5, p6, p7, p8]));\n    intro nvs; exrepnd.\n  repeat (destruct lvn; allsimpl; sp; try (complete omega)).\n  apply al_bterm with (lv := [n]);\n    try (complete (simpl; sp));\n    try (complete (apply no_rep_cons; sp)).\n*)\n\nAbort.\n*)\n\nLemma cover_vars_mk_iper_function_rel {o} :\n  forall A B s,\n    cover_vars (@mk_iper_function_rel o A B) s\n    <=> (cover_vars A s # cover_vars B s).\nProof.\n  introv.\n  rw @cover_vars_eq.\n  rw @free_vars_iper_function_rel_eq.\n  allrw subvars_app_l; split; sp.\nQed.\n\nLemma covered_iper_function_rel {o} :\n  forall a b vs,\n    covered (@mk_iper_function_rel o a b) vs\n    <=> covered a vs\n        # covered b vs.\nProof.\n  introv.\n  unfold covered.\n  rw @free_vars_iper_function_rel_eq.\n  allrw subvars_app_l; split; sp.\nQed.\n\nLemma cover_vars_iper_function {o} :\n  forall A B s,\n    cover_vars (@mk_iper_function o A B) s\n    <=> (cover_vars A s # cover_vars B s).\nProof.\n  introv.\n  unfold mk_iper_function.\n  rw @cover_vars_ipertype.\n  rw @cover_vars_mk_iper_function_rel; sp.\nQed.\n\nLemma cover_vars_sper_function {o} :\n  forall A B s,\n    cover_vars (@mk_sper_function o A B) s\n    <=> (cover_vars A s # cover_vars B s).\nProof.\n  introv.\n  unfold mk_sper_function.\n  rw @cover_vars_spertype.\n  rw @cover_vars_mk_iper_function_rel; sp.\nQed.\n\nLemma unfold_mk_iper_function_rel {o} :\n  forall A B,\n    {v1, v2, v3, v4, v5 : NVar\n     $ mk_iper_function_rel A B\n       = mk_lam\n           v3\n           (mk_lam\n              v4\n              (mk_isect\n                 mk_base\n                 v1\n                 (mk_isect\n                    mk_base\n                    v2\n                    (mk_isect\n                       (mk_equality (mk_var v1) (mk_var v2) A)\n                       v5\n                       (mk_uand\n                          (mk_equality\n                             (mk_apply (mk_var v3) (mk_var v1))\n                             (mk_apply (mk_var v4) (mk_var v2))\n                             (mk_apply B (mk_var v1)))\n                          (mk_tequality\n                             (mk_apply B (mk_var v1))\n                             (mk_apply B (@mk_var o v2))))))))\n     # (v1, v2, v3, v4, v5) = newvars5 [A, B] }.\nProof.\n  introv.\n  remember (newvarlst [A,B]) as v1.\n  exists v1.\n  remember (newvarlst ([A,B] ++ [mk_var v1])) as v2.\n  exists v2.\n  remember (newvarlst ([A,B] ++ [mk_var v1, mk_var v2])) as v3.\n  exists v3.\n  remember (newvarlst ([A,B] ++ [mk_var v1, mk_var v2, mk_var v3])) as v4.\n  exists v4.\n  remember (newvarlst ([A,B] ++ [mk_var v1, mk_var v2, mk_var v3, mk_var v4])) as v5.\n  exists v5.\n  subst; sp.\nQed.\n\nLemma alpha_eq_lam2 {o} :\n  forall v1 v2 b1 b2 v,\n    isprogram (mk_lam v1 b1)\n    -> isprogram (mk_lam v2 b2)\n    -> alpha_eq (lsubst b1 (var_ren [v1] [v])) (lsubst b2 (@var_ren o [v2] [v]))\n    -> alpha_eq (mk_lam v1 b1) (mk_lam v2 b2).\nProof.\n  introv isp1 isp2 aeq.\n  apply alpha_eq_trans with (nt2 := mk_lam v (lsubst b1 (var_ren [v1] [v]))).\n  unfold mk_lam.\n  prove_alpha_eq3.\n  apply alpha_eq_bterm_single_change2.\n  apply implies_isprogram_bt_lam; auto.\n  apply alpha_eq_trans with (nt2 := mk_lam v (lsubst b2 (var_ren [v2] [v]))).\n  unfold mk_lam.\n  prove_alpha_eq3.\n  apply alpha_eq_bterm_congr; auto.\n  unfold mk_lam.\n  prove_alpha_eq3.\n  apply alpha_eq_bterm_sym.\n  apply alpha_eq_bterm_single_change2.\n  apply implies_isprogram_bt_lam; auto.\nQed.\n\nLemma cover_vars_implies_cover_vars_upto {o} :\n  forall t sub vs,\n    @cover_vars o t sub\n    -> cover_vars_upto t sub vs.\nProof.\n  introv cv.\n  allrw @cover_vars_eq.\n  unfold cover_vars_upto.\n  provesv.\n  rw in_app_iff; sp.\nQed.\n\nLemma subst_mk_lam2 {o} :\n  forall v b x u,\n    disjoint (bound_vars b) (@free_vars o u)\n    -> !LIn v (free_vars u)\n    -> v <> x\n    -> subst (mk_lam v b) x u = mk_lam v (subst b x u).\nProof.\n  introv disj ni neq.\n  unfold subst.\n  change_to_lsubst_aux4; allsimpl; allrw app_nil_r; allrw disjoint_cons_l; sp.\n  boolvar; sp.\nQed.\n\nLemma cover_vars_if_disjoint {o} :\n  forall t sub vs,\n    disjoint vs (@free_vars o t)\n    -> (cover_vars t sub <=> cover_vars t (csub_filter sub vs)).\nProof.\n  introv disj; split; intro k;\n  allrw @cover_vars_eq; provesv;\n  allrw @dom_csub_csub_filter; allrw in_remove_nvars;\n  dands; auto; repnd; auto.\n  intro j; apply disj in j; sp.\nQed.\n\nLemma lsubstc_erase_rel {o} :\n  forall R sub,\n  forall w  : @wf_term o R,\n  forall w' : wf_term (erase_rel R),\n  forall c  : cover_vars R sub,\n  forall c' : cover_vars (erase_rel R) sub,\n    alphaeqc (lsubstc (erase_rel R) w' sub c')\n             (erasec_rel (lsubstc R w sub c)).\nProof.\n  introv.\n  destruct_cterms.\n  unfold erasec_rel, erase_rel, alphaeqc; simpl.\n  repeat (rw @csubst_mk_lam).\n  remember (newvarlst [R]) as v1.\n  remember (newvarlst [R, mk_var v1]) as v2.\n  remember (newvarlst [csubst R sub]) as v3.\n  remember (newvarlst [csubst R sub, mk_var v3]) as v4.\n  allunfold @newvarlst; allsimpl; allrw app_nil_r.\n\n  generalize (fresh_var_not_in (free_vars R)); intro k1.\n  rw <- Heqv1 in k1; clear Heqv1.\n  generalize (fresh_var_not_in (free_vars R ++ [v1])); intro k2.\n  rw <- Heqv2 in k2; clear Heqv2.\n  generalize (fresh_var_not_in (free_vars (csubst R sub))); intro k3.\n  rw <- Heqv3 in k3; clear Heqv3.\n  generalize (fresh_var_not_in (free_vars (csubst R sub) ++ [v3])); intro k4.\n  rw <- Heqv4 in k4; clear Heqv4.\n  allrw in_app_iff; allrw not_over_or; repnd.\n\n  generalize (ex_fresh_var (v2\n                              :: v4\n                              :: (bound_vars (csubst R (csub_filter sub [v1, v2])))\n                              ++ (bound_vars (csubst R sub))));\n    intro f; exrepnd.\n  simpl in f0; repeat (rw in_app_iff in f0); repeat (rw not_over_or in f0); repnd.\n\n  apply @alpha_eq_lam2 with (v := v).\n\n  { apply isprogram_lam.\n    apply isprog_vars_lam.\n    rw <- @csub_filter_app_r; simpl.\n    apply csubst.isprog_vars_csubst; sp.\n    allrw @dom_csub_csub_filter; allrw in_app_iff; allsimpl.\n    allrw in_remove_nvars; allsimpl.\n    apply cover_vars_upto_csub_filter_disjoint.\n    rw eqvars_prop; simpl; sp; split; sp.\n    repeat (rw disjoint_cons_r); sp.\n    allrw @cover_vars_erase_rel; sp. }\n\n  { apply isprogram_lam.\n    apply isprog_vars_lam.\n    apply csubst.isprog_vars_csubst; sp.\n    allrw @cover_vars_erase_rel; sp.\n    apply cover_vars_implies_cover_vars_upto; sp. }\n\n  unfold var_ren; simpl.\n  allrw @fold_subst.\n\n  rw @subst_mk_lam2; simpl; sp; allrw disjoint_singleton_r;\n  allrw <- @csub_filter_app_r; allsimpl; sp.\n\n  rw @subst_mk_lam2; simpl; sp; allrw disjoint_singleton_r;\n  allrw <- @csub_filter_app_r; allsimpl; sp.\n\n  unfold subst.\n  rw @lsubst_trivial3;\n    try (simpl; introv h; repdors; cpx; simpl; rw disjoint_singleton_l; sp;\n         allrw @free_vars_csubst; allrw in_remove_nvars; sp).\n  rw @lsubst_trivial3;\n    try (simpl; introv h; repdors; cpx; simpl; rw disjoint_singleton_l; sp;\n         allrw @free_vars_csubst; allrw in_remove_nvars; sp).\n\n  generalize (ex_fresh_var ((bound_vars (csubst R (csub_filter sub [v1, v2])))\n                              ++ (bound_vars (csubst R sub))));\n    intro g; exrepnd.\n  simpl in g0; repeat (rw in_app_iff in g0); repeat (rw not_over_or in g0); repnd.\n\n  apply @alpha_eq_lam2 with (v := v0);\n    try (apply @isprogram_lam;\n         allrw @cover_vars_erase_rel; sp;\n         apply @csubst.isprog_vars_csubst; sp;\n         try (apply @cover_vars_implies_cover_vars_upto); sp).\n  apply @cover_vars_if_disjoint; sp.\n  allrw disjoint_cons_l; sp.\n\n  rw @lsubst_trivial3;\n    try (simpl; introv h; repdors; cpx; simpl; rw disjoint_singleton_l; sp;\n         allrw @free_vars_csubst; allrw in_remove_nvars; sp).\n  rw @lsubst_trivial3;\n    try (simpl; introv h; repdors; cpx; simpl; rw disjoint_singleton_l; sp;\n         allrw @free_vars_csubst; allrw in_remove_nvars; sp).\n\n  rw @csubst_csub_filter; sp.\n  allrw disjoint_cons_r; sp.\nQed.\n\nLemma lsubstc_erase_rel_ex {o} :\n  forall R sub,\n  forall w : wf_term (@erase_rel o R),\n  forall c : cover_vars (erase_rel R) sub,\n    {w1 : wf_term R\n     & {c1 : cover_vars R sub\n        & alphaeqc (lsubstc (erase_rel R) w sub c)\n                   (erasec_rel (lsubstc R w1 sub c1))}}.\nProof.\n  sp.\n\n  assert (wf_term R) as w1.\n  { allrw <- @wf_erase_rel_iff; sp. }\n\n  assert (cover_vars R sub) as c1.\n  { allrw @cover_vars_eq; allrw subvars_prop; introv i.\n    apply c.\n    unfold erase_rel.\n    remember (newvars2 [R]); repnd; allsimpl; allrw app_nil_r.\n    apply newvars2_prop2 in Heqp.\n    allsimpl; allrw app_nil_r; repnd.\n    allrw in_remove_nvars; allrw in_single_iff; dands; auto; intro k; subst; sp. }\n\n  exists w1 c1.\n  apply lsubstc_erase_rel.\nQed.\n\n(* !! MOVE to alphaeq.v *)\nLemma alphaeqc_mkc_pertype {o} :\n  forall R1 R2,\n    @alphaeqc o R1 R2\n    -> alphaeqc (mkc_pertype R1) (mkc_pertype R2).\nProof.\n  introv aeq.\n  destruct_cterms.\n  allunfold @alphaeqc; allsimpl.\n  unfold mk_pertype.\n  prove_alpha_eq3.\nQed.\n\n(* !! MOVE to alphaeq.v *)\nLemma alphaeqc_mkc_ipertype {o} :\n  forall R1 R2,\n    @alphaeqc o R1 R2\n    -> alphaeqc (mkc_ipertype R1) (mkc_ipertype R2).\nProof.\n  introv aeq.\n  destruct_cterms.\n  allunfold @alphaeqc; allsimpl.\n  unfold mk_ipertype.\n  prove_alpha_eq3.\nQed.\n\n(* !! MOVE to alphaeq.v *)\nLemma alphaeqc_mkc_spertype {o} :\n  forall R1 R2,\n    @alphaeqc o R1 R2\n    -> alphaeqc (mkc_spertype R1) (mkc_spertype R2).\nProof.\n  introv aeq.\n  destruct_cterms.\n  allunfold @alphaeqc; allsimpl.\n  unfold mk_spertype.\n  prove_alpha_eq3.\nQed.\n\nLemma lsubstc_erase {o} :\n  forall R sub,\n  forall w  : @wf_term o R,\n  forall w' : wf_term (erase R),\n  forall c  : cover_vars R sub,\n  forall c' : cover_vars (erase R) sub,\n    alphaeqc (lsubstc (erase R) w' sub c')\n             (erasec (lsubstc R w sub c)).\nProof.\n  introv.\n  rw @erasec_eq.\n  unfold erase.\n  generalize (lsubstc_mk_pertype_ex (erase_rel R) sub w' c'); intro k; exrepnd.\n  rw k1.\n  apply alphaeqc_mkc_pertype.\n  apply lsubstc_erase_rel.\nQed.\n\nLemma lsubstc_erase_ex {o} :\n  forall R sub,\n  forall w : wf_term (@erase o R),\n  forall c : cover_vars (erase R) sub,\n    {w1 : wf_term R\n     & {c1 : cover_vars R sub\n        & alphaeqc (lsubstc (erase R) w sub c)\n                   (erasec (lsubstc R w1 sub c1))}}.\nProof.\n  sp.\n\n  assert (wf_term R) as w1.\n  { allrw <- @wf_erase_iff; sp. }\n\n  assert (cover_vars R sub) as c1.\n  { rw @cover_vars_erase in c; sp. }\n\n  exists w1 c1.\n  apply lsubstc_erase.\nQed.\n\nLemma isprogram_isaxiom {o} :\n  forall a b c,\n    isprogram a\n    -> isprogram b\n    -> @isprogram o c\n    -> isprogram (mk_isaxiom a b c).\nProof.\n  repeat constructor.\n  unfold closed; simpl.\n  allrw <- null_iff_nil.\n  repeat (rw null_app).\n  repeat (rw null_iff_nil).\n  allunfold @isprogram; allunfold @closed.\n  repeat (rewrite remove_nvars_nil_l); sp.\n  simpl; sp; allunfold @isprogram; sp; subst; constructor; auto.\nQed.\n\nLemma isprogram_isaxiom_iff {p} :\n  forall a b c, (isprogram a # isprogram b # @isprogram p c) <=> isprogram (mk_isaxiom a b c).\nProof.\n  intros; split; intro i.\n  apply isprogram_isaxiom; sp.\n  inversion i as [cl w].\n  allunfold @closed; allsimpl.\n  allrw remove_nvars_nil_l.\n  allrw app_nil_r.\n  allrw app_eq_nil_iff; repnd; allrw.\n  inversion w as [| | o lnt k meq ]; allsimpl; subst.\n  generalize (k (nobnd a)) (k (nobnd b)) (k (nobnd c)); intros i1 i2 i3.\n  dest_imp i1 hyp; dest_imp i2 hyp; dest_imp i3 hyp.\n  unfold isprogram; allrw.\n  inversion i1; inversion i2; inversion i3; subst; sp.\nQed.\n\nLemma isprog_isaxiom {p} :\n  forall a b c,\n    isprog a\n    -> isprog b\n    -> @isprog p c\n    -> isprog (mk_isaxiom a b c).\nProof.\n  sp; allrw @isprog_eq.\n  apply isprogram_isaxiom; auto.\nQed.\n\nDefinition mkc_isaxiom {p} (t1 t2 t3 : @CTerm p) : CTerm :=\n  let (a,x) := t1 in\n  let (b,y) := t2 in\n  let (c,z) := t3 in\n    exist isprog (mk_isaxiom a b c) (isprog_isaxiom a b c x y z).\n\nLemma mkc_isaxiom_eq {p} :\n  forall a b c d e f,\n    mkc_isaxiom a b c = @mkc_isaxiom p d e f\n    -> a = d # b = e # c = f.\nProof.\n  introv eq.\n  destruct_cterms.\n  allunfold @mkc_isaxiom.\n  inversion eq; subst; dands; tcsp; eauto with pi.\nQed.\n\nLemma fold_isaxiom {p} :\n  forall a b c,\n    oterm (NCan (NCanTest CanIsaxiom)) [ nobnd a, nobnd b, @nobnd p c ]\n    = mk_isaxiom a b c.\nProof.\n  sp.\nQed.\n\nLemma lsubstc_mk_isaxiom {p} :\n  forall t1 t2 t3 sub,\n  forall w1 : wf_term t1,\n  forall w2 : wf_term t2,\n  forall w3 : @wf_term p t3,\n  forall w  : wf_term (mk_isaxiom t1 t2 t3),\n  forall c1 : cover_vars t1 sub,\n  forall c2 : cover_vars t2 sub,\n  forall c3 : cover_vars t3 sub,\n  forall c  : cover_vars (mk_isaxiom t1 t2 t3) sub,\n    lsubstc (mk_isaxiom t1 t2 t3) w sub c\n    = mkc_isaxiom (lsubstc t1 w1 sub c1)\n                  (lsubstc t2 w2 sub c2)\n                  (lsubstc t3 w3 sub c3).\nProof.\n  introv; apply cterm_eq; simpl.\n  unfold csubst; simpl;\n  change_to_lsubst_aux4; simpl;\n  rw @sub_filter_nil_r;\n  allrw @fold_nobnd;\n  rw @fold_isaxiom; sp.\nQed.\n\nLemma lsubstc_mk_isaxiom_ex {p} :\n  forall t1 t2 t3 sub,\n  forall w  : wf_term (@mk_isaxiom p t1 t2 t3),\n  forall c  : cover_vars (mk_isaxiom t1 t2 t3) sub,\n  {w1 : wf_term t1\n   & {w2 : wf_term t2\n   & {w3 : wf_term t3\n   & {c1 : cover_vars t1 sub\n   & {c2 : cover_vars t2 sub\n   & {c3 : cover_vars t3 sub\n      & lsubstc (mk_isaxiom t1 t2 t3) w sub c\n           = mkc_isaxiom (lsubstc t1 w1 sub c1)\n                         (lsubstc t2 w2 sub c2)\n                         (lsubstc t3 w3 sub c3)}}}}}}.\nProof.\n  sp.\n\n  assert (wf_term t1) as w1.\n  { allrw @wf_isaxiom; sp. }\n\n  assert (wf_term t2) as w2.\n  { allrw @wf_isaxiom; sp. }\n\n  assert (wf_term t3) as w3.\n  { allrw @wf_isaxiom; sp. }\n\n  assert (cover_vars t1 sub) as c1.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  assert (cover_vars t2 sub) as c2.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  assert (cover_vars t3 sub) as c3.\n  { unfold cover_vars in c.\n    simpl in c.\n    repeat (rw remove_nvars_nil_l in c).\n    rw app_nil_r in c.\n    repeat (rw @over_vars_app_l in c); sp. }\n\n  exists w1 w2 w3 c1 c2 c3.\n  apply lsubstc_mk_isaxiom.\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/subst_per.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.2845983252697498}}
{"text": "From CoqMTL Require Import Control.All.\n\n(** An attempt at monad that models a computation that has no side effects,\n    but is evaluated lazily. According to my experiments, it doesn't really\n    work. *)\nDefinition Lazy (A : Type) : Type := unit -> A.\n\nDefinition delay {A : Type} (a : A) : Lazy A :=\n  fun _ => a.\n\nDefinition force {A : Type} (la : Lazy A) : A := la tt.\n\n(** All [Functor], [Applicative] and [Monad] operations are just like\n    these for [Identity], but wrapped in [delay] for laziness. *)\n\nDefinition fmap_Lazy {A B : Type} (f : A -> B) (la : Lazy A) : Lazy B :=\n  delay $ f (la tt).\n\n#[refine]\n#[export]\nInstance Functor_Lazy : Functor Lazy :=\n{\n  fmap := @fmap_Lazy;\n}.\nProof. all: monad. Defined.\n\nDefinition pure_Lazy {A : Type} (a : A) : Lazy A :=\n  fun _ => a.\n\nDefinition ap_Lazy\n  {A B : Type} (f : Lazy (A -> B)) (x : Lazy A) : Lazy B :=\n    fun _ => f tt (x tt).\n\n#[refine]\n#[export]\nInstance Applicative_Lazy : Applicative Lazy :=\n{\n  is_functor := Functor_Lazy;\n  pure := @pure_Lazy;\n  ap := @ap_Lazy;\n}.\nProof.\n  monad.\n  all: reflexivity.\nDefined.\n\nDefinition bind_Lazy\n  {A B : Type} (la : Lazy A) (f : A -> Lazy B) : Lazy B :=\n    fun _ => f (la tt) tt.\n\n#[refine]\n#[export]\nInstance Monad_Lazy : Monad Lazy :=\n{\n  is_applicative := Applicative_Lazy;\n  bind := @bind_Lazy\n}.\nProof. all: monad. Defined.\n\n(** Running these computations gives the following times:\n    - [cbn] takes ~9.1 seconds for both [repeat 42 10000] and\n      [delay $ repeat 42 10000]\n    - [lazy] takes ~1.3 seconds in both cases\n*)\n(*\nTime Eval cbn in repeat 42 10000.\nTime Eval lazy in repeat 42 10000.\nTime Eval lazy in delay $ repeat 42 10000.\nTime Eval cbn in delay $ repeat 42 10000.\n*)", "meta": {"author": "wkolowski", "repo": "coq-mtl", "sha": "e3ecb0cf0378e62816d391783e7421d769aec26b", "save_path": "github-repos/coq/wkolowski-coq-mtl", "path": "github-repos/coq/wkolowski-coq-mtl/coq-mtl-e3ecb0cf0378e62816d391783e7421d769aec26b/Control/Monad/Lazy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.28459831803789404}}
{"text": "Require Import VST.progs.io.\nRequire Import VST.progs.io_specs.\nRequire Import VST.floyd.proofauto.\nRequire Import ITree.ITree.\n(*Import ITreeNotations.*)\nNotation \"t1 >>= k2\" := (ITree.bind t1 k2)\n  (at level 50, left associativity) : itree_scope.\nNotation \"x <- t1 ;; t2\" := (ITree.bind t1 (fun x => t2))\n  (at level 100, t1 at next level, right associativity) : itree_scope.\nNotation \"t1 ;; t2\" := (ITree.bind t1 (fun _ => t2))\n  (at level 100, 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\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nDefinition putchar_spec := DECLARE _putchar putchar_spec.\nDefinition getchar_spec := DECLARE _getchar getchar_spec.\n\nLemma div_10_dec : forall n, 0 < n ->\n  (Z.to_nat (n / 10) < Z.to_nat n)%nat.\nProof.\n  intros.\n  change 10 with (Z.of_nat 10).\n  rewrite <- (Z2Nat.id n) by omega.\n  rewrite <- div_Zdiv by discriminate.\n  rewrite !Nat2Z.id.\n  apply Nat2Z.inj_lt.\n  rewrite div_Zdiv, Z2Nat.id by omega; simpl.\n  apply Z.div_lt; auto; omega.\nQed.\n\nProgram Fixpoint chars_of_Z (n : Z) { measure (Z.to_nat n) } : list int :=\n  let n' := n / 10 in\n  match n' <=? 0 with true => [Int.repr (n + char0)] | false => chars_of_Z n' ++ [Int.repr (n mod 10 + char0)] end.\nNext Obligation.\nProof.\n  apply div_10_dec.\n  symmetry in Heq_anonymous; apply Z.leb_nle in Heq_anonymous.\n  eapply Z.lt_le_trans, Z_mult_div_ge with (b := 10); omega.\nDefined.\n\n(* The function computed by print_intr *)\nProgram Fixpoint intr n { measure (Z.to_nat n) } : list int :=\n  match n <=? 0 with\n  | true => []\n  | false => intr (n / 10) ++ [Int.repr (n mod 10 + char0)]\n  end.\nNext Obligation.\nProof.\n  apply div_10_dec.\n  symmetry in Heq_anonymous; apply Z.leb_nle in Heq_anonymous; omega.\nDefined.\n\nDefinition print_intr_spec :=\n DECLARE _print_intr\n  WITH i : Z, tr : IO_itree\n  PRE [ _i OF tuint ]\n    PROP (0 <= i <= Int.max_unsigned)\n    LOCAL (temp _i (Vint (Int.repr i)))\n    SEP (ITREE (write_list (intr i) ;; tr))\n  POST [ tvoid ]\n    PROP ()\n    LOCAL ()\n    SEP (ITREE tr).\n\nDefinition print_int_spec :=\n DECLARE _print_int\n  WITH i : Z, tr : IO_itree\n  PRE [ _i OF tuint ]\n    PROP (0 <= i <= Int.max_unsigned)\n    LOCAL (temp _i (Vint (Int.repr i)))\n    SEP (ITREE (write_list (chars_of_Z i) ;; tr))\n  POST [ tvoid ]\n    PROP ()\n    LOCAL ()\n    SEP (ITREE tr).\n\nDefinition read_sum n d : IO_itree :=\n   ITree.aloop (fun '(n, d) =>\n       if zlt n 1000 then if zlt d 10 then\n         inl (write_list (chars_of_Z (n + d));; write (Int.repr newline);;\n              c <- read;;\n              Ret (n + d, Int.unsigned c - char0)) (* loop again with these parameters *)\n       else inr tt else inr tt) (* inr to end the loop *)\n     (n, d).\n\nDefinition main_itree := c <- read;; read_sum 0 (Int.unsigned c - char0).\n\nDefinition main_spec :=\n DECLARE _main\n  WITH gv : globals\n  PRE  [] main_pre_ext prog main_itree nil gv\n  POST [ tint ] main_post prog nil gv.\n\nDefinition Gprog : funspecs := ltac:(with_library prog [putchar_spec; getchar_spec;\n  print_intr_spec; print_int_spec; main_spec]).\n\nLemma divu_repr : forall x y,\n  0 <= x <= Int.max_unsigned -> 0 <= y <= Int.max_unsigned ->\n  Int.divu (Int.repr x) (Int.repr y) = Int.repr (x / y).\nProof.\n  intros; unfold Int.divu.\n  rewrite !Int.unsigned_repr; auto.\nQed.\n\nOpaque Nat.div Nat.modulo.\n\nLemma intr_eq : forall n, intr n =\n  match n <=? 0 with\n  | true => []\n  | false => intr (n / 10) ++ [Int.repr (n mod 10 + char0)]\n  end.\nProof.\n  intros.\n  unfold intr at 1.\n  rewrite Wf.WfExtensionality.fix_sub_eq_ext; simpl; fold intr.\n  destruct n; reflexivity.\nQed.\n\nLemma bind_ret' : forall E (s : itree E unit), eutt eq (s;; Ret tt) s.\nProof.\n  intros.\n  etransitivity; [|apply subrelation_eq_eutt, bind_ret2].\n  apply eutt_bind; [intros []|]; reflexivity.\nQed.\n\nLemma body_print_intr: semax_body Vprog Gprog f_print_intr print_intr_spec.\nProof.\n  start_function.\n  forward_if (PROP () LOCAL () SEP (ITREE tr)).\n  - forward.\n    forward.\n    rewrite modu_repr, divu_repr by (omega || computable).\n    rewrite intr_eq.\n    destruct (Z.leb_spec i 0); try omega.\n    erewrite ITREE_ext by (rewrite write_list_app, bind_bind; reflexivity).\n    forward_call (i / 10, write_list [Int.repr (i mod 10 + char0)];; tr).\n    { split; [apply Z.div_pos; omega | apply Z.div_le_upper_bound; omega]. }\n    simpl write_list.\n    forward_call (Int.repr (i mod 10 + char0), tr).\n    { rewrite <- sepcon_emp at 1; apply sepcon_derives; [|cancel].\n      apply ITREE_impl; rewrite bind_ret'; reflexivity. }\n    entailer!.\n  - forward.\n    subst; entailer!.\n    erewrite ITREE_ext; [apply derives_refl|].\n    simpl.\n    rewrite Shallow.bind_ret; reflexivity.\n  - forward.\nQed.\n\nLemma chars_of_Z_eq : forall n, chars_of_Z n =\n  let n' := n / 10 in\n  match n' <=? 0 with true => [Int.repr (n + char0)] | false => chars_of_Z n' ++ [Int.repr (n mod 10 + char0)] end.\nProof.\n  intros.\n  unfold chars_of_Z at 1.\n  rewrite Wf.WfExtensionality.fix_sub_eq_ext; simpl; fold chars_of_Z.\n  destruct (_ <=? _); reflexivity.\nQed.\n\nLemma chars_of_Z_intr : forall n, 0 < n ->\n  chars_of_Z n = intr n.\nProof.\n  induction n using (well_founded_induction (Zwf.Zwf_well_founded 0)); intro.\n  rewrite chars_of_Z_eq, intr_eq.\n  destruct (n <=? 0) eqn: Hn; [apply Zle_bool_imp_le in Hn; omega|].\n  simpl.\n  destruct (n / 10 <=? 0) eqn: Hdiv.\n  - apply Zle_bool_imp_le in Hdiv.\n    assert (0 <= n / 10).\n    { apply Z.div_pos; omega. }\n    assert (n / 10 = 0) as Hz by omega.\n    rewrite Hz; simpl.\n    apply Z.div_small_iff in Hz as [|]; try omega.\n    rewrite Zmod_small; auto.\n  - apply Z.leb_nle in Hdiv.\n    rewrite H; auto; try omega.\n    split; try omega.\n    apply Z.div_lt; auto; omega.\nQed.\n\nLemma body_print_int: semax_body Vprog Gprog f_print_int print_int_spec.\nProof.\n  start_function.\n  forward_if (PROP () LOCAL () SEP (ITREE tr)).\n  - subst.\n    forward_call (Int.repr char0, tr).\n    { rewrite chars_of_Z_eq; simpl.\n      erewrite <- sepcon_emp at 1; apply sepcon_derives; [|cancel].\n      erewrite ITREE_ext; [apply derives_refl|].\n      rewrite bind_ret'; reflexivity. }\n    entailer!.\n  - forward_call (i, tr).\n    { rewrite chars_of_Z_intr by omega; cancel. }\n    entailer!.\n  - forward.\nQed.\n\nLemma read_sum_eq : forall n d, read_sum n d ≈\n  (if zlt n 1000 then if zlt d 10 then\n     write_list (chars_of_Z (n + d));; write (Int.repr newline);;\n     c <- read;; read_sum (n + d) (Int.unsigned c - char0)\n   else Ret tt else Ret tt).\nProof.\n  intros.\n  unfold read_sum; rewrite unfold_aloop.\n  unfold ITree._aloop.\n  if_tac; [|reflexivity].\n  if_tac; [|reflexivity].\n  unfold id.\n  repeat setoid_rewrite bind_bind.\n  setoid_rewrite Shallow.bind_ret.\n  reflexivity.\nQed.\n\nLemma body_main: semax_body Vprog Gprog f_main main_spec.\nProof.\n  start_function.\n  unfold main_pre_ext.\n  replace_SEP 0 (ITREE main_itree).\n  { go_lower.\n    apply has_ext_ITREE. }\n  forward.\n  unfold main_itree.\n  rewrite <- !seq_assoc. (* Without this, forward_call gives a type error! *)\n  forward_call (fun c => read_sum 0 (Int.unsigned c - char0)).\n  Intros c.\n  forward.\n  rewrite sign_ext_inrange by auto.\n  set (Inv := EX n : Z, EX c : int,\n    PROP (0 <= n < 1009)\n    LOCAL (temp _c (Vint c); temp _n (Vint (Int.repr n)))\n    SEP (ITREE (read_sum n (Int.unsigned c - char0)))).\n  unfold Swhile; forward_loop Inv break: Inv.\n  { Exists 0 c; entailer!. }\n  subst Inv.\n  clear dependent c; Intros n c.\n  forward_if.\n  forward.\n  forward_if.\n  { forward.\n    Exists n c; entailer!. }\n  forward.\n  rewrite <- (Int.repr_unsigned c) in H1.\n  rewrite sub_repr in H1.\n  pose proof (Int.unsigned_range c).\n  destruct (zlt (Int.unsigned c) char0).\n  { rewrite Int.unsigned_repr_eq in H1.\n    rewrite <- Z_mod_plus_full with (b := 1), Zmod_small in H1; unfold char0 in *; rep_omega. }\n  rewrite Int.unsigned_repr in H1 by (unfold char0 in *; rep_omega).\n  erewrite ITREE_ext by apply read_sum_eq.\n  rewrite if_true by auto.\n  destruct (zlt _ _); [|unfold char0 in *; omega].\n  forward_call (n + (Int.unsigned c - char0),\n    write (Int.repr newline);; c' <- read;; read_sum (n + (Int.unsigned c - char0)) (Int.unsigned c' - char0)).\n  { entailer!.\n    rewrite <- (Int.repr_unsigned c) at 1.\n    rewrite sub_repr, add_repr; auto. }\n  { unfold char0 in *; rep_omega. }\n  forward_call (Int.repr newline, c' <- read;; read_sum (n + (Int.unsigned c - char0)) (Int.unsigned c' - char0)).\n  forward_call (fun c' => read_sum (n + (Int.unsigned c - char0)) (Int.unsigned c' - char0)).\n  Intros c'.\n  forward.\n  rewrite sign_ext_inrange by auto.\n  Exists (n + (Int.unsigned c - char0)) c'; entailer!.\n  rewrite <- (Int.repr_unsigned c) at 2; rewrite sub_repr, add_repr; auto.\n  { forward.\n    Exists n c; entailer!. }\n  subst Inv.\n  Intros n c'.\n  forward.\nQed.\n\nDefinition ext_link := ext_link_prog prog.\n\nInstance Espec : OracleKind := IO_Espec ext_link.\n\nLemma prog_correct:\n  semax_prog_ext prog main_itree Vprog Gprog.\nProof.\nprove_semax_prog.\nsemax_func_cons_ext.\n{ simpl; Intro i.\n  apply typecheck_return_value; auto. }\nsemax_func_cons_ext.\nsemax_func_cons body_print_intr.\nsemax_func_cons body_print_int.\nsemax_func_cons body_main.\nQed.\n\nRequire Import VST.veric.SequentialClight.\nRequire Import VST.progs.io_dry.\n\nDefinition init_mem_exists : { m | Genv.init_mem prog = Some m }.\nProof.\n  unfold Genv.init_mem; simpl.\nAdmitted. (* seems true, but hard to prove -- can we compute it? *)\n\nDefinition init_mem := proj1_sig init_mem_exists.\n\nDefinition main_block_exists : {b | Genv.find_symbol (Genv.globalenv prog) (prog_main prog) = Some b}.\nProof.\n  eexists; simpl.\n  unfold Genv.find_symbol; simpl; reflexivity.\nQed.\n\nDefinition main_block := proj1_sig main_block_exists.\n\nTheorem prog_toplevel : exists q : Clight_new.corestate,\n  semantics.initial_core (Clight_new.cl_core_sem (globalenv prog)) 0 init_mem q init_mem (Vptr main_block Ptrofs.zero) [] /\\\n  forall n, @step_lemmas.dry_safeN _ _ _ _ Clight_sim.genv_symb_injective (Clight_sim.coresem_extract_cenv (Clight_new.cl_core_sem (globalenv prog)) (prog_comp_env prog))\n             (io_dry_spec ext_link) {| Clight_sim.CC.genv_genv := Genv.globalenv prog; Clight_sim.CC.genv_cenv := prog_comp_env prog |} n\n            main_itree q init_mem.\nProof.\n  edestruct whole_program_sequential_safety_ext with (V := Vprog) as (b & q & m' & Hb & Hq & Hsafe).\n  - apply juicy_dry_specs.\n  - apply dry_spec_mem.\n  - apply CSHL_Sound.semax_prog_ext_sound, prog_correct.\n  - apply (proj2_sig init_mem_exists).\n  - exists q.\n    rewrite (proj2_sig main_block_exists) in Hb; inv Hb.\n    assert (m' = init_mem); [|subst; auto].\n    destruct Hq; tauto.\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_io.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.284598318037894}}
{"text": "Add LoadPath \"vst\".\nRequire Import msl.Coqlib2.\nRequire Import msl.log_normalize.\nRequire Import msl.eq_dec.\nRequire Import Coq.Unicode.Utf8.\nRequire Import Coq.Program.Equality.\n\nRequire Import Translation.\nRequire Import WFLemmas.\nRequire Import SubstLemmas.\nRequire Import Types.\nRequire Import Judge.\nRequire Import Language.\nRequire Import ProgramLogic.\nRequire Import Tactics.\n\nOpen Scope pred.\n\nLemma var_val :\n  forall Γ x b φ, \n    (x,{ ν : b | φ}) ∈ Γ ->\n    sep_env Γ |-- (EX v : (base_of_type b),\n                          (fun s => !!(eval s (var_e x) = val_of_base b v))).\nProof.\n  induction Γ. \n  intuition.\n  intuition.\n  destruct H.\n  + apply andp_left1. \n    apply andp_left1.\n    apply andp_left1.\n    destruct b.\n    inversion H. subst. \n    apply andp_left1.\n    apply exp_left.\n    intro bb.\n    apply andp_left1.\n    apply (exp_right bb).\n    apply derives_refl.\n  + apply andp_left1.\n    apply andp_left2.\n    fold sep_env.\n    apply IHΓ with (φ := φ).\n    assumption.\nQed.\n\nLemma var_eval :\n  forall Γ x b φ, \n    (x, { ν : b | φ }) ∈ Γ -> \n    sep_env Γ |-- (EX v : value, (fun s => !!(eval s (var_e x) = v))).\nProof.\n  intros.\n  pose (var_val Γ x b φ H).\n  apply derives_trans with (Q := EX x0 : base_of_type b, (fun s => !!(eval s (var_e x) = val_of_base b x0))).\n  assumption.\n  destruct b.\n  apply exp_left.\n  intro xv.\n  simpl.\n  intro w.\n  apply prop_left.\n  intro.\n  rewrite H0.\n  simpl in xv.\n  apply (exp_right (int_v xv)).\n  apply prop_right.\n  reflexivity.\nQed.\n\nLemma expr_eval :\n  forall Γ Ξ e b φ,\n    expr_type Γ Ξ e { ν : b | φ } ->\n    sep_env Γ |-- (EX v : value, (fun s => !!(eval s e = v))).\nProof.\n  intros.\n  induction H.\n  * apply (exp_right v). simpl. intro. apply prop_right. reflexivity.\n  * apply var_eval with (Γ := Γ) (b := τ) (φ := φ0); assumption.\n  * apply IHexpr_type. \nQed.\n\nLemma expr_eval_ty :\n  forall Γ Ξ e b φ,\n    expr_type Γ Ξ e { ν : b | φ } ->\n    sep_env Γ |-- \n      (EX v : base_of_type b , (fun s => !!(eval s e = val_of_base b v))).\nProof.\n  intros.\n  apply expr_eval with (e := e) (b := b) (φ := φ) (Ξ := Ξ) in H.\n  apply derives_trans with \n    (Q := EX v : value, (fun s => !!(eval s e = v))).\n  assumption.\n  apply exp_left. intro vv.\n  destruct b.\n  destruct vv.\n  simpl.\n  intro w.\n  apply prop_left.\n  intro.\n  apply (exp_right n).\n  apply prop_right.\n  assumption.\nQed.\n\nLemma exfalso_etype_fun :\n  forall G Ξ f e1 e2 T,\n    expr_type G Ξ (fun_e f e1 e2) T -> False.\nProof.\n  intros.\n  dependent induction H.\n  auto.\nQed.\n\nLemma subst_env_eq_expr :\n  forall G Grds b x e φ, \n    expr_type G Grds e { ν : b | φ } ->\n    sep_env G && \n    (subst_pred (subst_one x e) (sep_env G))\n    |-- subst_pred (subst_one x e) (sep_env ((x, { ν : b | var_e ν .= e }) :: G)).\nProof.\n  intros.\n  pose (expr_eval_ty G Grds e b φ H).\n  rewrite subst_env_cons.\n  apply derives_trans with (Q := sep_env G && subst_pred (subst_one x e) (sep_env G) && emp).\n  apply andp_right. normalize. apply andp_left1. apply sep_env_pure.\n  apply andp_derives.\n  apply andp_derives.\n  unfold sep_ty.\n  destruct {ν : b | var_e ν .= e} eqn: T.\n  inversion T. subst.\n  rewrite subst_distr_andp.\n  apply andp_right.\n  apply derives_trans with \n   (Q := (EX v : base_of_type reft_base, (fun s => !!(eval s e = val_of_base reft_base v))) && emp).\n    apply andp_right.\n    assumption.\n    apply sep_env_pure.\n    unfold sep_env. \n    rewrite exp_andp1.\n    apply exp_left. intro v. intro w. \n    (* apply prop_left. intro F. *)\n    unfold sep_base, subst_one, subst, Subst_pred, subst_pred.\n    simpl.\n    apply andp_right.\n    apply (exp_right v). \n    destruct (eq_dec x x). \n      apply derives_refl.\n      congruence.\n    apply andp_derives.\n    unfold subst, Subst_pred, subst_pred. simpl.\n    unfold subst, Subst_pred, Subst_var_expr, subst_pred.\n    destruct (eq_dec ν ν).\n    simpl.\n    destruct e.\n    simpl.\n    destruct (eq_dec x x).\n    simpl.\n    normalize.\n    normalize.\n    congruence.\n    normalize.\n    destruct (eq_dec x x).\n    simpl.\n    destruct (eq_dec v0 ν).\n    simpl.\n    destruct (eq_dec x x).\n    reflexivity.\n    congruence.\n    simpl.\n    destruct (eq_dec v0 x).\n    reflexivity.\n    reflexivity.\n    congruence.\n    exfalso; eapply exfalso_etype_fun; eauto.\n    congruence.\n    normalize.\n    apply sep_env_pure.\n    normalize.\n    normalize.\nQed.", "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/EvalLemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.28454902142751093}}
{"text": "Require Import Events.  \nRequire Import TraceModel.\nRequire Import Properties.\nRequire Import CommonST.\nRequire Import Robustdef.\nRequire Import Criteria. \nRequire Import ClassicalExtras.\nRequire Import FunctionalExtensionality.\nRequire Import Coq.Logic.ClassicalFacts.\n\n(** This file proves the collapses that happens in presence of\n    reflection in the source language *)\n\n(* \n\n       RrHP  ---  \n                 \\ \n        |  ----- RrSCP --- \n          /      /         \\ \n       RHP      /          RrTP ---\n(<-> RFrSCP)   /           /       \\  \n        |     /---------- /          RrSP\n                         /          /\n     RSCP (<-> RFrTP)   /          /\n                       /          / \n        |             /          /\n                     /          /\n       RTP --------- --        /\n                       \\      /\n      /   \\             RHSP (<-> RFrSP)\n                       /\n    RDP   RSP   -------\n\n*)\n\n\nVariable code_intro : forall {P1 P2 : par src} (h : P1 <> P2) (Cs1 Cs2 : ctx src), ctx src. \n\nAxiom beh_intro1 : forall P1 P2 (h : P1 <> P2)Cs1 Cs2,\n    forall t,\n     sem src ((code_intro h Cs1 Cs2) [P1]) t <-> sem src (Cs1 [P1]) t. \n\nAxiom beh_intro2 : forall P1 P2 (h : P1 <> P2) Cs1 Cs2,\n    forall t,\n    sem src ((code_intro h Cs1 Cs2) [P2]) t = sem src (Cs2 [P2]) t.                   \n\n(* R2HSP -> r2RSP and a similar argument for k >= 2 *)\nLemma R2HSP_R2rSP : R2HSP -> R2rSP.\nProof.\n  rewrite <- R2HSC_R2HSP, <- R2rSC_R2rSP.\n  intros H2rsc Ct P1 P2 m1 m2 H1 H2.\n  destruct H1 as [t1 [Hpref1 H1]]. \n  destruct H2 as [t2 [Hpref2 H2]].\n  destruct (classic (P1 = P2)) as [Heq | Hneq]. \n  + rewrite <- Heq in *.  \n    destruct (H2rsc P1 Ct m1 m2) as [Cs Hspref].\n    ++ intros x [Hx | Hx]; [exists t1 | exists t2]; subst; auto.\n    ++ exists Cs. split.\n       +++ destruct (Hspref m1) as [tt1 Hpref11]; simpl; auto.\n           now exists tt1.\n       +++ destruct (Hspref m2) as [tt2 Hpref22]; simpl; auto.\n           now exists tt2.\n  + apply R2HSC_RSC in H2rsc.\n    destruct (H2rsc P1 Ct t1 H1 m1 Hpref1) as [Cs1 [t1' [H' H'']]].\n    destruct (H2rsc P2 Ct t2 H2 m2 Hpref2) as [Cs2 [t2' [H2' H2'']]]. \n    exists (code_intro Hneq Cs1 Cs2). \n    split; [exists t1' | exists t2'];\n      split; auto; [  now rewrite (beh_intro1 P1 P2 Hneq Cs1 Cs2)\n                    | now rewrite (beh_intro2 P1 P2 Hneq Cs1 Cs2)].\nQed.\n\n(* RHP -> r2RHP *)\n\n(* as usual we need prop_extensionality *)\n\nHypothesis prop_ext : prop_extensionality. \n\nLemma RHP_R2rHP : RHP -> R2rHP.\nProof.\n  rewrite <- RHC_RHP, <- R2rHC_R2rHP.\n  intros hrc P1 P2 Ct.\n  destruct (hrc P1 Ct) as [Cs1 H1].\n  destruct (hrc P2 Ct) as [Cs2 H2].\n  destruct (classic (P1 = P2)) as [Heq | Hneq].  \n  + rewrite Heq in *.\n    exists Cs1. split; apply functional_extensionality;\n             intros t; apply prop_ext; now auto.\n  + exists (code_intro Hneq Cs1 Cs2).\n    split; apply functional_extensionality; intros t;\n      apply prop_ext; \n    [ now rewrite beh_intro1 | now rewrite beh_intro2].\nQed.\n\n(* RSCP -> R2rSCP *)\n\nLemma RSCP_R2rSCP : RSCHP -> R2rSCHP. \nProof.\n  rewrite <- R2rSCHC_R2rSCHP, <- RSCHC_RSCHP.    \n  intros sscr P1 P2 Ct.\n  destruct (classic (P1 = P2)) as [Heq | Hneq].\n  + rewrite <- Heq in *. destruct (sscr P1 Ct) as [Cs H].\n    now exists Cs.\n  + destruct (sscr P1 Ct) as [Cs1 H1].\n    destruct (sscr P2 Ct) as [Cs2 H2].\n    exists (code_intro Hneq Cs1 Cs2).\n    split; intros t H; [rewrite beh_intro1; now apply H1\n                       | rewrite beh_intro2; now apply H2].        \nQed.\n\n\nLemma R2rSCP_R2rTP : R2rSCHP -> R2rTP.  \nProof.\n  rewrite <- R2rSCHC_R2rSCHP, <- R2rTC_R2rTP.\n  intros rp Ct P1 P2 t1 t2 H1 H2.\n  destruct (rp P1 P2 Ct) as [Cs [HH1 HH2]].\n  exists Cs; split; [now apply HH1 | now apply HH2].\nQed.\n\nTheorem RSCHP_R2rTP : RSCHP -> R2rTP.\nProof.\n  intros H. now apply R2rSCP_R2rTP; apply RSCP_R2rSCP. \nQed.   \n", "meta": {"author": "JourneyBeyondFullAbstraction", "repo": "Anonymous", "sha": "db63e973a889738ec3b20453c82307a2857b216b", "save_path": "github-repos/coq/JourneyBeyondFullAbstraction-Anonymous", "path": "github-repos/coq/JourneyBeyondFullAbstraction-Anonymous/Anonymous-db63e973a889738ec3b20453c82307a2857b216b/FullReflection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.284549015024254}}
{"text": "Require compcert.backend.Linearizeproof.\nRequire LinearX.\nRequire LTLX.\n\nImport Coqlib.\nImport Errors.\nImport Globalenvs.\nImport Events.\nImport Smallstep.\nImport LTLX.\nImport LinearX.\nImport Linearize.\nExport Linearizeproof.\n\nSection WITHCONFIG.\n\nContext `{external_calls_prf: ExternalCalls}.\n\nVariable prog: LTL.program.\nVariable tprog: Linear.program.\n\nHypothesis TRANSF: transf_program prog = OK tprog.\n\nLet MATCH_PROG: match_prog prog tprog.\nProof.\n  apply transf_program_match.\n  assumption.\nQed.\n\nLemma transf_initial_states:\n  forall init_ls i sg args m,\n  forall st1, LTLX.initial_state init_ls prog i sg args m st1 ->\n         exists st2, LinearX.initial_state init_ls tprog i sg args m st2 /\\ match_states st1 st2.\nProof.\n  intros. inv H.\n  exploit function_ptr_translated; eauto.\n  destruct 1 as [? [? ?]].\n  econstructor; split.\n  econstructor; eauto.\n  erewrite symbols_preserved; eauto.\n  subst. symmetry; eauto using sig_preserved.\n  constructor; auto. constructor.\nQed.\n\nLemma transf_final_states:\n  forall init_ls,\n  forall sg,\n  forall st1 st2 r, \n    match_states st1 st2 -> LTLX.final_state init_ls sg st1 r -> LinearX.final_state init_ls sg st2 r.\nProof.\n  intros. inv H0. inv H. inv H4. econstructor; eauto.\nQed.\n\nTheorem transf_program_correct:\n  forall init_ls i sg args m,\n    forward_simulation (LTLX.semantics init_ls prog i sg args m) (LinearX.semantics init_ls tprog i sg args m).\nProof.\n  intros.\n  eapply forward_simulation_star.\n  apply senv_preserved; eauto.\n  apply transf_initial_states.\n  apply transf_final_states.\n  apply transf_step_correct; eauto.\nQed.\n\nEnd WITHCONFIG.\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/LinearizeproofX.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.284549008620997}}
{"text": "Require Import List.\nExport ListNotations.\n\nRequire Import genT gen.\nRequire Import PeanoNat.\nRequire Import Ensembles.\n\nRequire Import FO_Bi_Int_Syntax.\nRequire Import Set_FO_Bi_Int_calcs.\n\nSection Logics.\n\n  Context {Σ_funcs : funcs_signature}.\n  Context {Σ_preds : preds_signature}.\n\nLemma subst_Ax : forall A f, (BIAxioms A) -> (BIAxioms A[f]).\nProof.\nintros A f Ax. revert f. induction Ax ; intro f.\n- destruct H. destruct H. destruct H. subst. apply RA1_I.\n  exists (x[f]). exists (x0[f]). exists (x1[f]). unfold RA1. reflexivity.\n- destruct H. destruct H. subst. apply RA2_I.\n  exists (x[f]). exists (x0[f]). reflexivity.\n- destruct H. destruct H. subst. apply RA3_I.\n  exists (x[f]). exists (x0[f]). reflexivity.\n- destruct H. destruct H. destruct H. subst. apply RA4_I.\n  exists (x[f]). exists (x0[f]). exists (x1[f]). reflexivity.\n- destruct H. destruct H. subst. apply RA5_I.\n  exists (x[f]). exists (x0[f]). reflexivity.\n- destruct H. destruct H. subst. apply RA6_I.\n  exists (x[f]). exists (x0[f]). reflexivity.\n- destruct H. destruct H. destruct H. subst. apply RA7_I.\n  exists (x[f]). exists (x0[f]). exists (x1[f]). reflexivity.\n- destruct H. destruct H. destruct H. subst. apply RA8_I.\n  exists (x[f]). exists (x0[f]). exists (x1[f]). reflexivity.\n- destruct H. destruct H. destruct H. subst. apply RA9_I.\n  exists (x[f]). exists (x0[f]). exists (x1[f]). reflexivity.\n- destruct H. destruct H. subst. apply RA10_I.\n  exists (x[f]). exists (x0[f]). reflexivity.\n- destruct H. destruct H. subst. apply RA11_I.\n  exists (x[f]). exists (x0[f]). reflexivity.\n- destruct H. destruct H. subst. apply RA12_I.\n  exists (x[f]). exists (x0[f]). reflexivity.\n- destruct H. destruct H. destruct H. subst. apply RA13_I.\n  exists (x[f]). exists (x0[f]). exists (x1[f]). reflexivity.\n- destruct H. destruct H. subst. apply RA14_I.\n  exists (x[f]). exists (x0[f]). reflexivity.\n- destruct H. subst. apply RA15_I. exists (x[f]). reflexivity.\n- destruct H. subst. apply RA16_I. exists (x[f]). reflexivity.\n- destruct H. destruct H. subst. apply RA17_I.\n  unfold RA17. simpl. exists (x[f]). exists (x0[up f]).\n  rewrite up_form. reflexivity.\n- destruct H. destruct H. subst. apply RA18_I.\n  unfold RA18. simpl. exists (x[up f]).\n  assert (exists t, x[x0..][f] = x[up f][t..]).\n  { rewrite subst_comp. unfold funcomp. \n     exists (subst_term f x0).\n    rewrite subst_comp. unfold funcomp. apply subst_ext. intros.\n    induction n. simpl. auto. simpl. unfold funcomp. rewrite subst_term_comp.\n    rewrite subst_term_id. auto. auto. }\n  destruct H. exists x1. rewrite H. auto.\n- destruct H. destruct H. subst. apply RA19_I.\n  unfold RA19. simpl. exists (x[up f]).\n  assert (exists t, x[x0..][f] = x[up f][t..]).\n  { rewrite subst_comp. unfold funcomp. \n     exists (subst_term f x0).\n    rewrite subst_comp. unfold funcomp. apply subst_ext. intros.\n    induction n. simpl. auto. simpl. unfold funcomp. rewrite subst_term_comp.\n    rewrite subst_term_id. auto. auto. }\n  destruct H. exists x1. rewrite H. auto.\nQed.\n\nTheorem wFOBIC_subst : forall s f, wFOBIC_rules s ->\n    wFOBIC_rules (fun x : form => exists B : form, x = B[f] /\\ In form (fst s) B, (snd s)[f]).\nProof.\nintros s f D. revert f. induction D ; intro f.\n(* Id *)\n- inversion H. subst. apply Id. apply IdRule_I. simpl. exists A. auto.\n(* Ax *)\n- inversion H. subst. apply Ax. apply AxRule_I. simpl. apply subst_Ax. auto.\n(* MP *)\n- inversion H1. subst. simpl. apply MP with (ps:=[(fun x : form => exists B : form, x = B[f] /\\ In form Γ B, (A --> B)[f]); (fun x : form => exists B : form, x = B[f] /\\ In form Γ B, A[f])]).\n  intros. inversion H2. subst. assert (J1: List.In (Γ, A --> B) ((Γ, A --> B) :: (Γ, A) :: nil)). apply in_eq.\n  pose (H0 (Γ, A --> B) J1). apply w. inversion H3. subst.\n  assert (J2: List.In (Γ, A) ((Γ, A --> B) :: (Γ, A) :: nil)). apply in_cons. apply in_eq.\n  pose (H0 (Γ, A) J2). apply w. inversion H4. simpl. apply MPRule_I.\n(* DNw *)\n- inversion H1. subst. simpl. apply DNw with (ps:=[(Empty_set _ , A[f])]).\n  intros. inversion H2. subst. 2: inversion H3. 2: apply DNwRule_I.\n  assert (J1: List.In (Empty_set form, A) ((Empty_set form, A) :: nil)). apply in_eq.\n  pose (H0 (Empty_set _, A) J1 f). simpl in w.\n  assert ((fun x : form => exists B : form, x = B[f] /\\ In form (Empty_set form) B) = Empty_set _).\n  apply Extensionality_Ensembles. split. intro. intros. inversion H3. destruct H4. inversion H5.\n  intro. intros. inversion H3. rewrite H3 in w ; auto.\n(* Gen *)\n- inversion H1. subst. simpl.\n  apply Gen with (ps:=[((fun x : form => exists C : form, x = C[↑] /\\ In _ (fun x : form => exists B : form, x = B[f] /\\ In form Γ B) C), A[up f])]).\n  2: apply GenRule_I. intros. inversion H2. 2: inversion H3. subst.\n  assert (J1: List.In ((fun x : form => exists B : form, x = B[↑] /\\ In form Γ B), A) (((fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A) :: nil))). apply in_eq.\n  pose (@H0 (fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A) J1). simpl in w.\n  pose (w (up f)).\n  assert ((fun x : form => exists B : form, x = B[up f] /\\ In form (fun x0 : form => exists B0 : form, x0 = B0[↑] /\\ In form Γ B0) B) =\n  (fun x : form => exists C : form, x = C[↑] /\\ In form (fun x0 : form => exists B : form, x0 = B[f] /\\ In form Γ B) C)).\n  apply Extensionality_Ensembles. split ; intro ; intro. inversion H3. destruct H4. inversion H5. destruct H6.\n  subst. unfold In. exists x1[f]. split. apply up_form. exists x1. split ; auto. inversion H3.\n  destruct H4. subst. inversion H5. destruct H4. subst. unfold In. exists x[↑]. split.\n  rewrite up_form. auto. exists x ; split ; auto. rewrite <- H3 ; auto.\n(* EC *)\n- inversion H1. subst. simpl.\n  apply EC with (ps:=[((fun x : form => exists C : form, x = C[↑] /\\ In _ (fun x : form => exists B : form, x = B[f] /\\ In form Γ B) C), A[up f] --> B[f][↑])]).\n  2: apply ECRule_I. intros. inversion H2. 2: inversion H3. subst.\n  assert (J1: List.In (fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A --> B[↑]) ((fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A --> B[↑]) :: nil)). apply in_eq.\n  pose (@H0 _ J1). simpl in w. pose (w (up f)).\n  assert ((fun x : form => exists B : form, x = B[up f] /\\ In form (fun x0 : form => exists B0 : form, x0 = B0[↑] /\\ In form Γ B0) B) =\n  (fun x : form => exists C : form, x = C[↑] /\\ In form (fun x0 : form => exists B0 : form, x0 = B0[f] /\\ In form Γ B0) C)).\n  apply Extensionality_Ensembles. split ; intro ; intro. inversion H3. destruct H4. inversion H5. destruct H6.\n  subst. unfold In. exists x1[f]. split. apply up_form. exists x1. split ; auto. inversion H3.\n  destruct H4. subst. inversion H5. destruct H4. subst. unfold In. exists x[↑]. split.\n  rewrite up_form. auto. exists x ; split ; auto.  rewrite up_form in w0. rewrite <- H3 ; auto.\nQed.\n\nTheorem sFOBIC_subst : forall s f, sFOBIC_rules s -> sFOBIC_rules (fun x : form => exists B : form, x = B[f] /\\ In form (fst s) B, (snd s)[f]).\nProof.\nintros s f D. revert f. induction D ; intro f.\n(* Ids *)\n- inversion H. subst. apply Ids. apply IdRule_I. simpl. exists A. auto.\n(* Axs *)\n- inversion H. subst. apply Axs. apply AxRule_I. simpl. apply subst_Ax. auto.\n(* MPs *)\n- inversion H1. subst. simpl. apply MPs with (ps:=[(fun x : form => exists B : form, x = B[f] /\\ In form Γ B, (A --> B)[f]); (fun x : form => exists B : form, x = B[f] /\\ In form Γ B, A[f])]).\n  intros. inversion H2. subst. assert (J1: List.In (Γ, A --> B) ((Γ, A --> B) :: (Γ, A) :: nil)). apply in_eq.\n  pose (H0 (Γ, A --> B) J1). apply s. inversion H3. subst.\n  assert (J2: List.In (Γ, A) ((Γ, A --> B) :: (Γ, A) :: nil)). apply in_cons. apply in_eq.\n  pose (H0 (Γ, A) J2). apply s. inversion H4. simpl. apply MPRule_I.\n(* DNs *)\n- inversion H1. subst. simpl. apply DNs with (ps:=[(fun x : form => exists B : form, x = B[f] /\\ In form Γ B, A[f])]).\n  intros. inversion H2. subst. 2: inversion H3. 2: apply DNsRule_I.\n  apply H0 with (prem:=(Γ, A)). apply in_eq.\n(* Gens *)\n- inversion H1. subst. simpl.\n  apply Gens with (ps:=[((fun x : form => exists C : form, x = C[↑] /\\ In _ (fun x : form => exists B : form, x = B[f] /\\ In form Γ B) C), A[up f])]).\n  2: apply GenRule_I. intros. inversion H2. 2: inversion H3. subst.\n  assert (J1: List.In ((fun x : form => exists B : form, x = B[↑] /\\ In form Γ B), A) (((fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A) :: nil))). apply in_eq.\n  pose (@H0 (fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A) J1). simpl in s.\n  pose (s (up f)).\n  assert ((fun x : form => exists B : form, x = B[up f] /\\ In form (fun x0 : form => exists B0 : form, x0 = B0[↑] /\\ In form Γ B0) B) =\n  (fun x : form => exists C : form, x = C[↑] /\\ In form (fun x0 : form => exists B : form, x0 = B[f] /\\ In form Γ B) C)).\n  apply Extensionality_Ensembles. split ; intro ; intro. inversion H3. destruct H4. inversion H5. destruct H6.\n  subst. unfold In. exists x1[f]. split. apply up_form. exists x1. split ; auto. inversion H3.\n  destruct H4. subst. inversion H5. destruct H4. subst. unfold In. exists x[↑]. split.\n  rewrite up_form. auto. exists x ; split ; auto. rewrite <- H3 ; auto.\n(* ECs *)\n- inversion H1. subst. simpl.\n  apply ECs with (ps:=[((fun x : form => exists C : form, x = C[↑] /\\ In _ (fun x : form => exists B : form, x = B[f] /\\ In form Γ B) C), A[up f] --> B[f][↑])]).\n  2: apply ECRule_I. intros. inversion H2. 2: inversion H3. subst.\n  assert (J1: List.In (fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A --> B[↑]) ((fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A --> B[↑]) :: nil)). apply in_eq.\n  pose (@H0 _ J1). simpl in s. pose (s (up f)).\n  assert ((fun x : form => exists B : form, x = B[up f] /\\ In form (fun x0 : form => exists B0 : form, x0 = B0[↑] /\\ In form Γ B0) B) =\n  (fun x : form => exists C : form, x = C[↑] /\\ In form (fun x0 : form => exists B0 : form, x0 = B0[f] /\\ In form Γ B0) C)).\n  apply Extensionality_Ensembles. split ; intro ; intro. inversion H3. destruct H4. inversion H5. destruct H6.\n  subst. unfold In. exists x1[f]. split. apply up_form. exists x1. split ; auto. inversion H3.\n  destruct H4. subst. inversion H5. destruct H4. subst. unfold In. exists x[↑]. split.\n  rewrite up_form. auto. exists x ; split ; auto.  rewrite up_form in s0. rewrite <- H3 ; auto.\nQed.\n\nTheorem wFOBIC_monot : forall s,\n          (wFOBIC_rules s) ->\n          (forall Γ1, Included _ (fst s) Γ1 -> (wFOBIC_rules (Γ1, (snd s)))).\nProof.\nintros s D0. induction D0.\n(* Id *)\n- intros Γ1 incl. inversion H. subst. apply Id. apply IdRule_I. simpl. apply incl ; auto.\n(* Ax *)\n- intros Γ1 incl. inversion H. subst. apply Ax. apply AxRule_I. assumption.\n(* MP *)\n- intros Γ1 incl. inversion H1. subst. simpl. apply MP with (ps:=[(Γ1, A --> B); (Γ1, A)]).\n  intros. inversion H2. subst. assert (J1: List.In (Γ, A --> B) ((Γ, A --> B) :: (Γ, A) :: nil)). apply in_eq.\n  pose (H0 (Γ, A --> B) J1 Γ1). apply w ; auto. inversion H3. subst.\n  assert (J2: List.In (Γ, A) ((Γ, A --> B) :: (Γ, A) :: nil)). apply in_cons. apply in_eq.\n  pose (H0 (Γ, A) J2 Γ1). apply w ; auto. inversion H4. apply MPRule_I.\n(* DNw *)\n- intros Γ1 incl. inversion H1. subst. simpl. apply DNw with (ps:=[(Empty_set _ , A)]).\n  intros. inversion H2. subst. auto. inversion H3. apply DNwRule_I.\n(* Gen *)\n- intros Γ1 incl. inversion H1. subst. simpl. simpl in incl. apply Gen with (ps:=[(fun x : form => exists B : form, x = B[↑] /\\ In form Γ1 B, A)]).\n  2: apply GenRule_I. intros. inversion H2. 2: inversion H3. subst.\n  assert (J1: List.In (fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A) ((fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A) :: nil)). apply in_eq.\n  pose (H0 (fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A) J1 (fun x : form => exists B : form, x = B[↑] /\\ In form Γ1 B)). apply w.\n  intro. simpl. intro. inversion H3. destruct H4 ; subst. unfold In. exists x0 ; split ; auto. apply incl ; auto.\n(* EC *)\n- intros Γ1 incl. inversion H1. subst. simpl. apply EC with (ps:=[(fun x : form => exists B : form, x = B[↑] /\\ In form Γ1 B, A --> B[↑])]).\n  2: apply ECRule_I. intros. inversion H2. 2: inversion H3. subst.\n  assert (J1: List.In (fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A --> B[↑]) ((fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A --> B[↑]) :: nil)). apply in_eq.\n  pose (H0 (fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A --> B[↑]) J1 (fun x : form => exists B : form, x = B[↑] /\\ In form Γ1 B)). apply w.\n  intro. simpl. intro. inversion H3. destruct H4 ; subst. unfold In. exists x0 ; split ; auto. apply incl ; auto.\nQed.\n\nTheorem sFOBIC_monot : forall s,\n          (sFOBIC_rules s) ->\n          (forall Γ1, Included _ (fst s) Γ1 -> (sFOBIC_rules (Γ1, (snd s)))).\nProof.\nintros s D0. induction D0.\n(* Ids *)\n- intros Γ1 incl. inversion H. subst. apply Ids. apply IdRule_I. simpl. apply incl ; auto.\n(* Axs *)\n- intros Γ1 incl. inversion H. subst. apply Axs. apply AxRule_I. assumption.\n(* MPs *)\n- intros Γ1 incl. inversion H1. subst. simpl. apply MPs with (ps:=[(Γ1, A --> B); (Γ1, A)]).\n  intros. inversion H2. subst. assert (J1: List.In (Γ, A --> B) ((Γ, A --> B) :: (Γ, A) :: nil)). apply in_eq.\n  pose (H0 (Γ, A --> B) J1 Γ1). apply s ; auto. inversion H3. subst.\n  assert (J2: List.In (Γ, A) ((Γ, A --> B) :: (Γ, A) :: nil)). apply in_cons. apply in_eq.\n  pose (H0 (Γ, A) J2 Γ1). apply s ; auto. inversion H4. apply MPRule_I.\n(* DNs *)\n- intros Γ1 incl. inversion H1. subst. simpl. apply DNs with (ps:=[(Γ1 , A)]).\n  intros. inversion H2. subst. 2: inversion H3. 2: apply DNsRule_I.\n  apply H0 with (prem:=(Γ, A)). apply in_eq. auto.\n(* Gens *)\n- intros Γ1 incl. inversion H1. subst. simpl. simpl in incl. apply Gens with (ps:=[(fun x : form => exists B : form, x = B[↑] /\\ In form Γ1 B, A)]).\n  2: apply GenRule_I. intros. inversion H2. 2: inversion H3. subst.\n  assert (J1: List.In (fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A) ((fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A) :: nil)). apply in_eq.\n  pose (H0 (fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A) J1 (fun x : form => exists B : form, x = B[↑] /\\ In form Γ1 B)). apply s.\n  intro. simpl. intro. inversion H3. destruct H4 ; subst. unfold In. exists x0 ; split ; auto. apply incl ; auto.\n(* ECs *)\n- intros Γ1 incl. inversion H1. subst. simpl. apply ECs with (ps:=[(fun x : form => exists B : form, x = B[↑] /\\ In form Γ1 B, A --> B[↑])]).\n  2: apply ECRule_I. intros. inversion H2. 2: inversion H3. subst.\n  assert (J1: List.In (fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A --> B[↑]) ((fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A --> B[↑]) :: nil)). apply in_eq.\n  pose (H0 (fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A --> B[↑]) J1 (fun x : form => exists B : form, x = B[↑] /\\ In form Γ1 B)). apply s.\n  intro. simpl. intro. inversion H3. destruct H4 ; subst. unfold In. exists x0 ; split ; auto. apply incl ; auto.\nQed.\n\nTheorem wFOBIC_comp : forall s,\n          (wFOBIC_rules s) ->\n          (forall Γ,  (forall A, (In _ (fst s) A) -> wFOBIC_rules (Γ, A)) ->\n          wFOBIC_rules (Γ, (snd s))).\nProof.\nintros s D0. induction D0.\n(* Id *)\n- intros Γ derall. inversion H. subst. pose (derall A). apply w. auto.\n(* Ax *)\n- intros Γ derall. inversion H. subst. apply Ax. apply AxRule_I. assumption.\n(* MP *)\n- intros Γ derall. inversion H1. subst. apply MP with (ps:=[(Γ, A --> B); (Γ, A)]).\n  intros. inversion H2. subst. assert (J1: List.In (Γ0, A --> B) ((Γ0, A --> B) :: (Γ0, A) :: nil)). apply in_eq.\n  pose (H0 (Γ0, A --> B) J1 Γ). apply w. simpl. auto. inversion H3. subst.\n  assert (J2: List.In (Γ0, A) ((Γ0, A --> B) :: (Γ0, A) :: nil)). apply in_cons. apply in_eq.\n  pose (H0 (Γ0, A) J2 Γ). apply w. auto. inversion H4. apply MPRule_I.\n(* DNw *)\n- intros Γ derall. inversion H1. subst. simpl. apply DNw with (ps:=[(Empty_set _, A)]).\n  intros. inversion H2. subst. auto. inversion H3. apply DNwRule_I.\n(* Gen *)\n- intros Γ derall. inversion H1. subst. simpl. apply Gen with (ps:=[(fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A)]).\n  intros. inversion H2. subst. 2: inversion H3. 2: apply GenRule_I.\n  apply H0 with (prem:=(fun x : form => exists B : form, x = B[↑] /\\ In form Γ0 B, A)). apply in_eq. simpl. intros. simpl in derall.\n  inversion H3. destruct H4. subst. pose (derall x). apply w in H5.\n  apply wFOBIC_subst with (f:=↑) (s:=(Γ, x)) ; auto.\n(* EC *)\n- intros Γ derall. inversion H1. subst. simpl. apply EC with (ps:=[(fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A --> B[↑])]).\n  intros. inversion H2. subst. 2: inversion H3. 2: apply ECRule_I.\n  apply H0 with (prem:=(fun x : form => exists B : form, x = B[↑] /\\ In form Γ0 B, A --> B[↑])). apply in_eq. simpl. intros. simpl in derall.\n  inversion H3. destruct H4. subst. pose (derall x). apply w in H5.\n  apply wFOBIC_subst with (f:=↑) (s:=(Γ, x)) ; auto.\nQed.\n\nTheorem sFOBIC_comp : forall s,\n          (sFOBIC_rules s) ->\n          (forall Γ,  (forall A, (In _ (fst s) A) -> sFOBIC_rules (Γ, A)) ->\n          sFOBIC_rules (Γ, (snd s))).\nProof.\nintros s D0. induction D0.\n(* Ids *)\n- intros Γ derall. inversion H. subst. pose (derall A). apply s. auto.\n(* Axs *)\n- intros Γ derall. inversion H. subst. apply Axs. apply AxRule_I. assumption.\n(* MPs *)\n- intros Γ derall. inversion H1. subst. apply MPs with (ps:=[(Γ, A --> B); (Γ, A)]).\n  intros. inversion H2. subst. assert (J1: List.In (Γ0, A --> B) ((Γ0, A --> B) :: (Γ0, A) :: nil)). apply in_eq.\n  pose (H0 (Γ0, A --> B) J1 Γ). apply s. simpl. auto. inversion H3. subst.\n  assert (J2: List.In (Γ0, A) ((Γ0, A --> B) :: (Γ0, A) :: nil)). apply in_cons. apply in_eq.\n  pose (H0 (Γ0, A) J2 Γ). apply s. auto. inversion H4. apply MPRule_I.\n(* DNs *)\n- intros Γ derall. inversion H1. subst. simpl. apply DNs with (ps:=[(Γ, A)]).\n  intros. inversion H2. subst. auto. 2: inversion H3. 2: apply DNsRule_I.\n  pose (H0 (Γ0, A)). apply s. apply in_eq. intros. simpl in H3. apply derall. auto.\n(* Gens *)\n- intros Γ derall. inversion H1. subst. simpl. apply Gens with (ps:=[(fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A)]).\n  intros. inversion H2. subst. 2: inversion H3. 2: apply GenRule_I.\n  apply H0 with (prem:=(fun x : form => exists B : form, x = B[↑] /\\ In form Γ0 B, A)). apply in_eq. simpl. intros. simpl in derall.\n  inversion H3. destruct H4. subst. pose (derall x). apply s in H5.\n  apply sFOBIC_subst with (f:=↑) (s:=(Γ, x)) ; auto.\n(* ECs *)\n- intros Γ derall. inversion H1. subst. simpl. apply ECs with (ps:=[(fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A --> B[↑])]).\n  intros. inversion H2. subst. 2: inversion H3. 2: apply ECRule_I.\n  apply H0 with (prem:=(fun x : form => exists B : form, x = B[↑] /\\ In form Γ0 B, A --> B[↑])). apply in_eq. simpl. intros. simpl in derall.\n  inversion H3. destruct H4. subst. pose (derall x). apply s in H5.\n  apply sFOBIC_subst with (f:=↑) (s:=(Γ, x)) ; auto.\nQed.\n\nLemma List_Reverse_arrow : forall l0 Γ0 Γ1,\n  (Included form Γ0 (fun x : form => exists B : form, x = B[↑] /\\ In form Γ1 B)) ->\n  (forall A : form, (Γ0 A -> List.In A l0) * (List.In A l0 -> Γ0 A)) ->\n      (exists l1, (map (subst_form ↑) l1 = l0) /\\ (forall y, List.In y l1 -> In _ Γ1 y)).\nProof.\ninduction l0 ; intros.\n- exists []. split ; auto. intros. inversion H1.\n- destruct (In_dec eq_dec_form a l0).\n  + assert (J1: forall A : form, (Γ0 A -> List.In A l0) * (List.In A l0 -> Γ0 A)).\n     intros. split ; intro. apply H0 in H1. inversion H1. subst. auto. auto.\n     apply H0. apply in_cons. auto.\n     pose (IHl0 Γ0 Γ1 H J1). destruct e. destruct H1. subst. pose (H0 a).\n     destruct p. assert (List.In a (a :: map (subst_form ↑) x)). apply in_eq.\n     apply γ in H1. apply H in H1. unfold In in H1. destruct H1. destruct H1. subst.\n     exists (x0 :: x). simpl. split ; auto. intros. destruct H1 ; subst ; auto.\n  + assert (J1: Included form (fun x : form => x <> a /\\ In form Γ0 x)\n     (fun x : form => exists B : form, x = B[↑] /\\ In form Γ1 B)).\n     intro. intros. unfold In in H1. destruct H1. apply H in H2. auto.\n     assert (J2: (forall A : form, ((fun x : form => x <> a /\\ In form Γ0 x) A -> List.In A l0) *\n     (List.In A l0 -> (fun x : form => x <> a /\\ In form Γ0 x) A))).\n     intros. split. intro. destruct H1. apply H0 in H2. inversion H2. exfalso ; auto. auto.\n     intros. split. intro. subst. auto. assert (List.In A (a :: l0)). apply in_cons ; auto.\n     apply H0 in H2. auto.\n     pose (IHl0 (fun x => x <> a /\\ In _ Γ0 x) Γ1 J1 J2). destruct e. destruct H1. subst.\n     pose (H0 a). destruct p. assert (List.In a (a :: map (subst_form ↑) x)). apply in_eq.\n     apply γ in H1. apply H in H1. unfold In in H1. destruct H1. destruct H1. subst.\n     exists (x0 :: x). simpl. split ; auto. intros. destruct H1 ; subst ; auto.\nQed.\n\nTheorem wFOBIC_finite : forall s,\n          (wFOBIC_rules s) ->\n          (exists (Γ : Ensemble _), prod (Included _ Γ (fst s))\n                                     (prod (wFOBIC_rules (Γ, snd s))\n                                     (exists (l : list form), (forall A, ((Γ A) -> List.In A l) * (List.In A l -> (Γ A)))))).\nProof.\nintros s D0. induction D0.\n(* Id *)\n- inversion H. subst. simpl. exists (fun x => x = A).\n  repeat split. intro. intro. unfold In. inversion H1. assumption.\n  apply Id. apply IdRule_I. auto. unfold In ; auto.\n  exists [A]. intro. split. intro. subst. apply in_eq. intro. inversion H1.\n  subst. auto. inversion H2.\n(* Ax *)\n- inversion H. subst. simpl. exists (Empty_set _).\n  repeat split. intro. intro. unfold In. inversion H1.\n  apply Ax. apply AxRule_I. auto.\n  exists []. intro. split. intro. subst. inversion H1. intro. inversion H1.\n(* MP *)\n- inversion H1. subst. assert (J1: List.In (Γ, A --> B) ((Γ, A --> B) :: (Γ, A) :: nil)). apply in_eq.\n  pose (H0 (Γ, A --> B) J1). destruct e. destruct H2. destruct p. destruct e.\n  assert (J2: List.In (Γ, A) ((Γ, A --> B) :: (Γ, A) :: nil)). apply in_cons. apply in_eq.\n  pose (H0 (Γ, A) J2). destruct e. destruct H3. destruct p. destruct e.\n  exists (Union _ x x1). repeat split. intro. intro. simpl. inversion H4.\n  subst. apply i. assumption. apply i0. assumption. simpl.\n  apply MP with (ps:=[(Union _ x x1, A --> B); (Union _ x x1, A)]).\n  intros. inversion H4. subst.\n  assert (J3: Included _ (fst (x, A --> B)) (Union _ x x1)). intro. simpl. intro.\n  apply Union_introl. assumption. pose (@wFOBIC_monot (x, A --> B) w (Union _ x x1) J3). assumption.\n  inversion H5. subst. assert (J4: Included _ (fst (x1, A)) (Union _ x x1)). intro. simpl. intro.\n  apply Union_intror. assumption. pose (@wFOBIC_monot (x1, A) w0 (Union _ x x1) J4). assumption.\n  inversion H6. apply MPRule_I.\n  exists (x0 ++ x2). intro. split. intro. inversion H4. subst. pose (H2 A0).\n  destruct p. apply in_or_app. apply i1 in H5. auto. subst. pose (H3 A0).\n  destruct p. apply i1 in H5. apply in_or_app. auto. intro. apply in_app_or in H4.\n  destruct H4. apply Union_introl. apply H2. assumption. apply Union_intror.\n  apply H3. assumption.\n(* DNw *)\n- inversion H1. subst. exists (Empty_set _). repeat split.\n  intro. intro. simpl. inversion H2. apply DNw with (ps:=[(Empty_set _, A)]).\n  assumption. apply DNwRule_I. exists []. intro. split. intro. inversion H2.\n  intro. inversion H2.\n(* Gen *)\n- inversion H1. subst. simpl.\n  assert (J1: List.In (fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A) ((fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A) :: nil)). apply in_eq.\n  pose (H0 (fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A) J1). destruct e. destruct H2. destruct p. destruct e.\n  simpl in i. simpl in w.\n  assert (exists x1, (map (subst_form ↑) x1 = x0) /\\ (forall y, List.In y x1 -> In _ Γ y)).\n  pose (List_Reverse_arrow x0 x Γ). apply e ; auto.\n  destruct H3. destruct H3.\n  exists (fun y => List.In y x1). repeat split. intro. intro. unfold In in H5. apply H4 ; auto.\n  apply Gen with (ps:=[((fun z => exists C, z = C[↑] /\\ In form (fun y : form => List.In y x1) C), A)]).\n  intros. 2: apply GenRule_I. inversion H5. subst. 2: inversion H6.\n  assert ((fun z : form => exists C : form, z = C[↑] /\\ In form (fun y : form => List.In y x1) C) = x).\n  apply Extensionality_Ensembles. split ; intro ; intro.\n  inversion H3. destruct H6. subst. unfold In in H7. apply H2.\n  apply in_map_iff. exists x2 ; split ; auto. unfold In. apply H2 in H3. apply in_map_iff in H3.\n  destruct H3. destruct H3 ; subst. exists x2. split ; auto.\n  rewrite H3. auto. exists x1. intros ; auto.\n(* EC *)\n- inversion H1. subst. simpl.\n  assert (J1: List.In (fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A --> B[↑]) ((fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A --> B[↑]) :: nil)). apply in_eq.\n  pose (H0 (fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A --> B[↑]) J1). destruct e. destruct H2. destruct p. destruct e.\n  simpl in i. simpl in w.\n  assert (exists x1, (map (subst_form ↑) x1 = x0) /\\ (forall y, List.In y x1 -> In _ Γ y)).\n  pose (List_Reverse_arrow x0 x Γ). apply e ; auto.\n  destruct H3. destruct H3.\n  exists (fun y => List.In y x1). repeat split. intro. intro. unfold In in H5. apply H4 ; auto.\n  apply EC with (ps:=[((fun z => exists C, z = C[↑] /\\ In form (fun y : form => List.In y x1) C), A --> B[↑])]).\n  intros. 2: apply ECRule_I. inversion H5. subst. 2: inversion H6.\n  assert ((fun z : form => exists C : form, z = C[↑] /\\ In form (fun y : form => List.In y x1) C) = x).\n  apply Extensionality_Ensembles. split ; intro ; intro.\n  inversion H3. destruct H6. subst. unfold In in H7. apply H2.\n  apply in_map_iff. exists x2 ; split ; auto. unfold In. apply H2 in H3. apply in_map_iff in H3.\n  destruct H3. destruct H3 ; subst. exists x2. split ; auto.\n  rewrite H3. auto. exists x1. intros ; auto.\nQed.\n\nTheorem sFOBIC_finite : forall s,\n          (sFOBIC_rules s) ->\n          (exists (Γ : Ensemble _), prod (Included _ Γ (fst s))\n                                     (prod (sFOBIC_rules (Γ, snd s))\n                                     (exists (l : list form), (forall A, ((Γ A) -> List.In A l) * (List.In A l -> (Γ A)))))).\nProof.\nintros s D0. induction D0.\n(* Ids *)\n- inversion H. subst. simpl. exists (fun x => x = A).\n  repeat split. intro. intro. unfold In. inversion H1. assumption.\n  apply Ids. apply IdRule_I. auto. unfold In ; auto.\n  exists [A]. intro. split. intro. subst. apply in_eq. intro. inversion H1.\n  subst. auto. inversion H2.\n(* Axs *)\n- inversion H. subst. simpl. exists (Empty_set _).\n  repeat split. intro. intro. unfold In. inversion H1.\n  apply Axs. apply AxRule_I. auto.\n  exists []. intro. split. intro. subst. inversion H1. intro. inversion H1.\n(* MPs *)\n- inversion H1. subst. assert (J1: List.In (Γ, A --> B) ((Γ, A --> B) :: (Γ, A) :: nil)). apply in_eq.\n  pose (H0 (Γ, A --> B) J1). destruct e. destruct H2. destruct p. destruct e.\n  assert (J2: List.In (Γ, A) ((Γ, A --> B) :: (Γ, A) :: nil)). apply in_cons. apply in_eq.\n  pose (H0 (Γ, A) J2). destruct e. destruct H3. destruct p. destruct e.\n  exists (Union _ x x1). repeat split. intro. intro. simpl. inversion H4.\n  subst. apply i. assumption. apply i0. assumption. simpl.\n  apply MPs with (ps:=[(Union _ x x1, A --> B); (Union _ x x1, A)]).\n  intros. inversion H4. subst.\n  assert (J3: Included _ (fst (x, A --> B)) (Union _ x x1)). intro. simpl. intro.\n  apply Union_introl. assumption. pose (@sFOBIC_monot (x, A --> B) s (Union _ x x1) J3). assumption.\n  inversion H5. subst. assert (J4: Included _ (fst (x1, A)) (Union _ x x1)). intro. simpl. intro.\n  apply Union_intror. assumption. pose (@sFOBIC_monot (x1, A) s0 (Union _ x x1) J4). assumption.\n  inversion H6. apply MPRule_I.\n  exists (x0 ++ x2). intro. split. intro. inversion H4. subst. pose (H2 A0).\n  destruct p. apply in_or_app. apply i1 in H5. auto. subst. pose (H3 A0).\n  destruct p. apply i1 in H5. apply in_or_app. auto. intro. apply in_app_or in H4.\n  destruct H4. apply Union_introl. apply H2. assumption. apply Union_intror.\n  apply H3. assumption.\n(* DNs *)\n- inversion H1. subst. simpl. assert (J1: List.In (Γ, A) ((Γ, A) :: nil)). apply in_eq.\n  pose (H0 (Γ, A) J1). destruct e. destruct H2. destruct p. destruct e.\n  exists x. repeat split. intro. intro. simpl. apply i. assumption.\n  simpl in s. apply DNs with (ps:=[(x, A)]). 2: apply DNsRule_I. intros.\n  inversion H3. subst. 2: inversion H4. auto. exists x0. intro. split ; intro ;\n  apply H2 ; auto.\n(* Gens *)\n- inversion H1. subst. simpl.\n  assert (J1: List.In (fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A) ((fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A) :: nil)). apply in_eq.\n  pose (H0 (fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A) J1). destruct e. destruct H2. destruct p. destruct e.\n  simpl in i. simpl in s.\n  assert (exists x1, (map (subst_form ↑) x1 = x0) /\\ (forall y, List.In y x1 -> In _ Γ y)).\n  pose (List_Reverse_arrow x0 x Γ). apply e ; auto.\n  destruct H3. destruct H3.\n  exists (fun y => List.In y x1). repeat split. intro. intro. unfold In in H5. apply H4 ; auto.\n  apply Gens with (ps:=[((fun z => exists C, z = C[↑] /\\ In form (fun y : form => List.In y x1) C), A)]).\n  intros. 2: apply GenRule_I. inversion H5. subst. 2: inversion H6.\n  assert ((fun z : form => exists C : form, z = C[↑] /\\ In form (fun y : form => List.In y x1) C) = x).\n  apply Extensionality_Ensembles. split ; intro ; intro.\n  inversion H3. destruct H6. subst. unfold In in H7. apply H2.\n  apply in_map_iff. exists x2 ; split ; auto. unfold In. apply H2 in H3. apply in_map_iff in H3.\n  destruct H3. destruct H3 ; subst. exists x2. split ; auto.\n  rewrite H3. auto. exists x1. intros ; auto.\n(* ECs *)\n- inversion H1. subst. simpl.\n  assert (J1: List.In (fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A --> B[↑]) ((fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A --> B[↑]) :: nil)). apply in_eq.\n  pose (H0 (fun x : form => exists B : form, x = B[↑] /\\ In form Γ B, A --> B[↑]) J1). destruct e. destruct H2. destruct p. destruct e.\n  simpl in i. simpl in s.\n  assert (exists x1, (map (subst_form ↑) x1 = x0) /\\ (forall y, List.In y x1 -> In _ Γ y)).\n  pose (List_Reverse_arrow x0 x Γ). apply e ; auto.\n  destruct H3. destruct H3.\n  exists (fun y => List.In y x1). repeat split. intro. intro. unfold In in H5. apply H4 ; auto.\n  apply ECs with (ps:=[((fun z => exists C, z = C[↑] /\\ In form (fun y : form => List.In y x1) C), A --> B[↑])]).\n  intros. 2: apply ECRule_I. inversion H5. subst. 2: inversion H6.\n  assert ((fun z : form => exists C : form, z = C[↑] /\\ In form (fun y : form => List.In y x1) C) = x).\n  apply Extensionality_Ensembles. split ; intro ; intro.\n  inversion H3. destruct H6. subst. unfold In in H7. apply H2.\n  apply in_map_iff. exists x2 ; split ; auto. unfold In. apply H2 in H3. apply in_map_iff in H3.\n  destruct H3. destruct H3 ; subst. exists x2. split ; auto.\n  rewrite H3. auto. exists x1. intros ; auto.\nQed.\n\nEnd Logics.\n", "meta": {"author": "ianshil", "repo": "FO_Bi_Int", "sha": "f2be82e6baa29f87066c04f5ae011ab71fd77311", "save_path": "github-repos/coq/ianshil-FO_Bi_Int", "path": "github-repos/coq/ianshil-FO_Bi_Int/FO_Bi_Int-f2be82e6baa29f87066c04f5ae011ab71fd77311/Set_FO_Bi_Int_logics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.28454900862099697}}
{"text": "Require Import Algebra.Utils Algebra.SetoidCat Algebra.SetoidCat.PairUtils Algebra.Monad Algebra.Monoid Algebra.Traversable Algebra.FoldableFunctor Algebra.Functor SetoidUtils Algebra.Applicative Algebra.Alternative Tactics Algebra.SetoidCat.BoolUtils Algebra.Functor.Utils Algebra.Functor.Compose Algebra.Applicative.Compose Algebra.Functor.List Algebra.SetoidCat.ListUtils Algebra.Applicative.List Algebra.Applicative.Utils Algebra.Applicative.Transformation Algebra.Applicative.TransformationUtils.\n\nRequire Import RelationClasses Relation_Definitions Morphisms SetoidClass.\n\nRequire Import Coq.Lists.List.\n\nImport ListNotations.\n\n\n\nSection Generic.\n\n\n\n  Definition l A {AS : Setoid A} := list A.\n  Instance lS {A} (AS : Setoid A) : Setoid (l A) := listS AS.\n\n\n  Existing Instance ComposeFunctor.\n  Existing Instance Compose_Applicative.\n  Existing Instance ComposeS.\n  \n  Existing Instance ComposeIso'_Proper.\n  Existing Instance listFunctor.\n  \n  Instance list_Traversable : @Traversable l (@lS) _.\n  Proof.\n    exists (@sequenceS).\n    intros. simpl. arrequiv. induction a.\n    simpl. reflexivity.\n    simpl. constructor. reflexivity. destruct (sequence a0). auto.\n\n    intros. simpl_equiv. induction a.\n    simpl. repeat rewrite fmap_fmap. evalproper. evalproper. simpl. arrequiv.\n    rewrite sequenceS_cons. repeat rewrite comp_eval. rewrite mapS_cons. rewrite sequenceS_cons. rewrite IHa. unfold ap at 1. unfold fmap at 1 2. unfold ComposeFunctor. unfold compFunc_fmap. unfold comp2S. normalizecomp. evalproper.\n    match goal with\n      | |- _ <$> _ @ (_ @ ?a ** _ @ ?b) == _ =>\n        rewrite (ComposeIsoS'_prod _ _ _ _ _ _ app' app'' _ _ _ _ a b)\n    end.\n    rewrite naturality_prod. rewrite <- uncurry_fmap_prod.  repeat rewrite fmap_fmap. evalproper. evalproper. simpl. arrequiv. simpl_let. reflexivity.\n\n    intros. simpl_equiv. induction a.\n    rewrite comp_eval. rewrite sequenceS_nil. rewrite app_trans_pure. reflexivity. auto.\n    rewrite comp_eval. rewrite sequenceS_cons. rewrite app_trans_ap. rewrite app_trans_naturality.\n    rewrite comp_eval. simpl (tr A AS <$> (a :: a0)). rewrite sequenceS_cons. evalproper. auto. auto.\n  Defined.\n\nEnd Generic.\n\nSection MapM.\n\n\n  Context\n    {m mS}\n    {func}\n    {app : @Applicative m mS func}\n    {A B : Type}\n    {SA : Setoid A}\n    {SB : Setoid B}.\n  \n\n  Existing Instance listFunctor.\n  Existing Instance list_Applicative.\n  Existing Instance list_Traversable.\n  Definition mapM : (SA ~~> mS _ SB) ~> listS SA ~~> mS _ (listS SB) :=\n    comp2S @ fmap @ sequenceA.\n\n\n  Lemma mapM_cons :\n    forall (f: SA ~> mS _ SB) (a : A) ( l : list A),\n      mapM @ f @ ( a :: l) == consS <$> f @ a <*> mapM @ f @ l.\n  Proof.\n    intros.  unfold mapM at 1. unfold comp2S. normalizecomp. simpl fmap. rewrite mapS_cons. rewrite (sequenceS_cons).  evalproper.\n  Qed.\n\n\n  Lemma mapM_consS :\n    forall (f: SA ~> mS _ SB) (a : A) ( l : list A),\n      mapM @ f @ (consS @ a @ l) == consS <$> f @ a <*> mapM @ f @ l.\n  Proof.\n    apply mapM_cons.\n  Qed.\n\n  Lemma mapM_nil : forall  (f : SA ~> mS _ SB), mapM @ f @ nil == pure @ nil.\n  Proof.\n    intros. simpl. reflexivity.\n  Qed.\n\n  Lemma mapM_app :\n    forall (f: SA ~> mS _ SB) (l l2 : list A),\n      mapM @ f @ (  l ++ l2) ==\n      appS <$> mapM @ f @ l <*> mapM @ f @ l2.\n  Proof.\n    intros. induction l0.\n    simpl (([] ++ l2)). rewrite mapM_nil. rewrite fmap_pure. assert (appS @ [] == idS).\n    simpl. arrequiv.\n    rewrite H. rewrite ap_pure. rewrite fmap_idS_absorb. reflexivity.\n    simpl (( _ :: _ ) ++ _ ). repeat rewrite mapM_cons. rewrite IHl0.\n    simpl. normalizecomp. rewrite <- (fmap_idS_absorb (sequence (map (fun a0 : A => f @ a0) l2))) at 1. rewrite naturality_prod. rewrite fmap_fmap. rewrite naturality_prod. rewrite <- associativity_applicative. rewrite fmap_fmap. rewrite fmap_fmap.\n    rewrite <- (fmap_idS_absorb (sequence (map (fun a0 : A => f @ a0) l0))) at 2. rewrite naturality_prod. repeat rewrite fmap_fmap. rewrite <- (fmap_idS_absorb (sequence (map (fun a0 : A => f @ a0) l2))) at 2. rewrite naturality_prod. repeat rewrite fmap_fmap. evalproper. evalproper. simpl. arrequiv. destruct a0. destruct p. simpl. reflexivity. \n  Qed.\n  \n  Lemma mapM_appS :\n    forall (f: SA ~> mS _ SB) (l l2 :  (list A)),\n      mapM @ f @ (appS @ l @ l2) ==\n      appS <$> mapM @ f @ l <*> mapM @ f @ l2.\n  Proof.\n    apply mapM_app.\n  Qed.\nEnd MapM.\n\n\nSection ConcatMap.\n  Context\n    {m mS}\n    {func}\n    {app : @Applicative m mS func}\n    {A B : Type}\n    {SA : Setoid A}\n    {SB : Setoid B}.\n  Definition concatMapM  : (SA ~~> mS _ (listS SB)) ~> listS SA ~~> mS _ (listS SB).\n    simple refine (injF (fun f : SA ~> mS _ (listS SB) => injF (fun l => concatS <$> mapM @ f @ l) _ ) _).\n    exact mS.\n    exact func.\n    exact func.\n    exact app.\n    Lemma concatMap_1 : forall f, Proper (equiv ==> equiv) (fun l : list A => concatS <$> mapM @ f @ l).\n    Proof.\n      repeat autounfold. intros. rewrite H. reflexivity.\n    Qed.\n    apply concatMap_1.\n\n    Lemma concatMap_2 : forall pr, Proper (equiv ==> equiv)\n                                          (fun f : SA ~> mS _ (listS SB) =>\n                                             injF (fun l : list A => concatS <$> mapM @ f @ l) (pr f)).\n    Proof.\n      repeat autounfold. intros. arrequiv. evalproper. apply sequence_Proper. apply map_Proper. autounfold. intros. rewritesr.  reflexivity. \n    Qed.\n    apply concatMap_2.\n  Defined.\nEnd ConcatMap.  \n\n", "meta": {"author": "xu-hao", "repo": "CertifiedQueryArrow", "sha": "8db512e0ebea8011b0468d83c9066e4a94d8d1c4", "save_path": "github-repos/coq/xu-hao-CertifiedQueryArrow", "path": "github-repos/coq/xu-hao-CertifiedQueryArrow/CertifiedQueryArrow-8db512e0ebea8011b0468d83c9066e4a94d8d1c4/Algebra/Traversable/List.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863695, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.28453683910644834}}
{"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\nRequire Import Coqlib Compopts.\nRequire Import AST Integers Floats Values Memory Globalenvs.\nRequire Import Op RTL ValueDomain.\n\n(** Value analysis for RISC V 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  | Ccompl c, v1 :: v2 :: nil => cmpl_bool c v1 v2\n  | Ccomplu c, v1 :: v2 :: nil => cmplu_bool c v1 v2\n  | Ccomplimm c n, v1 :: nil => cmpl_bool c v1 (L n)\n  | Ccompluimm c n, v1 :: nil => cmplu_bool c v1 (L 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  | _, _ => Bnone\n  end.\n\nDefinition eval_static_addressing (addr: addressing) (vl: list aval): aval :=\n  match addr, vl with\n  | Aindexed n, v1::nil => offset_ptr v1 n\n  | Aglobal s ofs, nil => Ptr (Gl s ofs)\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  | Olongconst n, nil => L n\n  | Ofloatconst n, nil => if propagate_float_constants tt then F n else ntop\n  | Osingleconst n, nil => if propagate_float_constants tt then FS n else ntop\n  | Oaddrsymbol id ofs, nil => Ptr (Gl id ofs)\n  | Oaddrstack ofs, nil => Ptr (Stk ofs)\n  | Ocast8signed, v1 :: nil => sign_ext 8 v1\n  | Ocast16signed, v1 :: nil => sign_ext 16 v1\n  | Oadd, v1::v2::nil => add v1 v2\n  | Oaddimm n, v1::nil => add v1 (I n)\n  | Oneg, v1::nil => neg v1\n  | Osub, v1::v2::nil => sub v1 v2\n  | Omul, v1::v2::nil => mul v1 v2\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  | 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  | Oshru, v1::v2::nil => shru v1 v2\n  | Oshruimm n, v1::nil => shru v1 (I n)\n  | Oshrximm n, v1::nil => shrx v1 (I n)\n  | Omakelong, v1::v2::nil => longofwords v1 v2\n  | Olowlong, v1::nil => loword v1\n  | Ohighlong, v1::nil => hiword v1\n  | Ocast32signed, v1::nil => longofint v1\n  | Ocast32unsigned, v1::nil => longofintu v1\n  | Oaddl, v1::v2::nil => addl v1 v2\n  | Oaddlimm n, v1::nil => addl v1 (L n)\n  | Onegl, v1::nil => negl v1\n  | Osubl, v1::v2::nil => subl v1 v2\n  | Omull, v1::v2::nil => mull v1 v2\n  | Omullhs, v1::v2::nil => mullhs v1 v2\n  | Omullhu, v1::v2::nil => mullhu v1 v2\n  | Odivl, v1::v2::nil => divls v1 v2\n  | Odivlu, v1::v2::nil => divlu v1 v2\n  | Omodl, v1::v2::nil => modls v1 v2\n  | Omodlu, v1::v2::nil => modlu v1 v2\n  | Oandl, v1::v2::nil => andl v1 v2\n  | Oandlimm n, v1::nil => andl v1 (L n)\n  | Oorl, v1::v2::nil => orl v1 v2\n  | Oorlimm n, v1::nil => orl v1 (L n)\n  | Oxorl, v1::v2::nil => xorl v1 v2\n  | Oxorlimm n, v1::nil => xorl v1 (L n)\n  | Oshll, v1::v2::nil => shll v1 v2\n  | Oshllimm n, v1::nil => shll v1 (I n)\n  | Oshrl, v1::v2::nil => shrl v1 v2\n  | Oshrlimm n, v1::nil => shrl v1 (I n)\n  | Oshrlu, v1::v2::nil => shrlu v1 v2\n  | Oshrluimm n, v1::nil => shrlu v1 (I n)\n  | Oshrxlimm n, v1::nil => shrxl v1 (I n)\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  | Ointuoffloat, v1::nil => intuoffloat v1\n  | Ofloatofint, v1::nil => floatofint v1\n  | Ofloatofintu, v1::nil => floatofintu v1\n  | Ointofsingle, v1::nil => intofsingle v1\n  | Ointuofsingle, v1::nil => intuofsingle v1\n  | Osingleofint, v1::nil => singleofint v1\n  | Osingleofintu, v1::nil => singleofintu v1\n  | Olongoffloat, v1::nil => longoffloat v1\n  | Olonguoffloat, v1::nil => longuoffloat v1\n  | Ofloatoflong, v1::nil => floatoflong v1\n  | Ofloatoflongu, v1::nil => floatoflongu v1\n  | Olongofsingle, v1::nil => longofsingle v1\n  | Olonguofsingle, v1::nil => longuofsingle v1\n  | Osingleoflong, v1::nil => singleoflong v1\n  | Osingleoflongu, v1::nil => singleoflongu 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  list_forall2 (vmatch bc) vargs aargs ->\n  cmatch (eval_condition cond vargs m) (eval_static_condition cond aargs).\nProof.\n  intros until aargs; intros VM. 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\nLemma symbol_address_sound_2:\n  forall id ofs,\n  vmatch bc (Genv.symbol_address ge id ofs) (Ifptr (Gl id ofs)).\nProof.\n  intros. unfold Genv.symbol_address. destruct (Genv.find_symbol ge id) as [b|] eqn:F.\n  constructor. constructor. apply GENV; auto.\n  constructor.\nQed.\n\nHint Resolve symbol_address_sound symbol_address_sound_2: 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: list_forall2 _ ?vl _ |- _ ] => inv H2; InvHyps\n  | [H: (if Archi.ptr64 then _ else _) = Some _ |- _] => destruct Archi.ptr64 eqn:?; InvHyps\n  | _ => idtac\n  end.\n\nTheorem eval_static_addressing_sound:\n  forall addr vargs vres aargs,\n  eval_addressing ge (Vptr sp Ptrofs.zero) addr vargs = Some vres ->\n  list_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 Ptrofs.add_zero_l; eauto with va.\nQed.\n\nTheorem eval_static_operation_sound:\n  forall op vargs m vres aargs,\n  eval_operation ge (Vptr sp Ptrofs.zero) op vargs m = Some vres ->\n  list_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  rewrite Ptrofs.add_zero_l; eauto with va.\n  apply of_optbool_sound. eapply eval_static_condition_sound; eauto.\nQed.\n\nEnd SOUNDNESS.\n\n", "meta": {"author": "AbsInt", "repo": "CompCert", "sha": "f4ddce910894bf6dbdf83c0642c4b275854b60dd", "save_path": "github-repos/coq/AbsInt-CompCert", "path": "github-repos/coq/AbsInt-CompCert/CompCert-f4ddce910894bf6dbdf83c0642c4b275854b60dd/riscV/ValueAOp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.28437002224495267}}
{"text": "Require Import CommonST.\nRequire Import Events.\nRequire Import TraceModel.\nRequire Import Criteria.\nRequire Import ClassicalExtras.\n\nSection Quick.\n\n(* Very strange thing: This doesn't use RTEP at all! *)\n(* - Any chance that going beyond RTC will fix this? *)\n\n(* Less strange thing: this doesn't use compiler correctness any more *)\n\nDefinition valid_trace P t := exists Cs, sem src (Cs[P]) t.\n\nDefinition valid_finpref P m := exists Cs, @psem src (Cs[P]) m.\n\nDefinition err := esbad. (* This esbad thing is not general enough *)\n\nHypothesis fsb : forall P t,\n  (exists Ct, sem tgt (Ct[P↓]) t /\\ ~valid_trace P t) ->\n  (exists m, t = tapp m (tstop err) /\\ valid_finpref P m).\n\nLemma rtc_informative : forall P Ct t,\n  sem tgt (Ct[P↓]) t ->\n  exists Cs,\n    (valid_trace P t -> sem src (Cs[P]) t) /\\\n    (~valid_trace P t -> exists m, psem (Cs[P]) m /\\ t = (tapp m (tstop err))).\nProof.\n  intros P Ct t H. destruct (classic (valid_trace P t)) as [Hv | Hnv].\n  - destruct Hv as [Cs Hv]. exists Cs. split.\n    + intros _. exact Hv.\n    + intro Hnv. apply False_ind. apply Hnv. exists Cs. exact Hv.\n  - assert(H':exists Ct, sem tgt (Ct [P ↓]) t /\\ ~ valid_trace P t) by eauto.\n    specialize (fsb P t H'). clear H'.\n    destruct fsb as [m [H1 H2]]. clear fsb. subst. destruct H2 as [Cs H2].\n    exists Cs. split.\n    + intro Hv. apply False_ind. tauto.\n    + intros _. exists m. split. assumption. reflexivity.\nQed.\n\n(* If we can do the final `err` in the source then we can prove the original rtc\n   - but there are still concerns about fsb and valid needing to be amended\n     in this case to say that err is not in t\n   - and more importantly the err_ctx_correct assumption seems too strong;\n     context would be able to preempt program at any point and produce any action\n*)\n\nVariable err_ctx : ctx src -> ctx src.\n\nHypothesis err_ctx_correct : forall C P m,\n  @psem src (C[P]) m ->\n  sem src ((err_ctx C)[P]) (tapp m (tstop err)).\n\nLemma rtc : RTC.\nProof.\n  rewrite RTC'.\n  intros P Ct t H. destruct (classic (valid_trace P t)) as [Hv | Hnv].\n  - destruct Hv as [Cs Hv]. exists Cs. exact Hv.\n  - assert(H':exists Ct, sem tgt (Ct [P ↓]) t /\\ ~ valid_trace P t) by eauto.\n    specialize (fsb P t H'). clear H'.\n    destruct fsb as [m [H1 H2]]. clear fsb. subst. destruct H2 as [Cs H2].\n    exists (err_ctx Cs). now apply err_ctx_correct.\nQed.\n\nEnd Quick.\n\n\nSection Stefan.\n\n  Definition question_mark := forall P1 P2 Ct,\n    beh (Ct [P1 ↓]) ⊆ beh (Ct [P2 ↓]) ->\n    exists Cs, beh (Cs [P1 ]) ⊆ beh (Cs [P2 ]).\n\n  Variable Wt : trace -> par src.\n\n  Hypothesis only_t:  forall Ct t t', sem tgt (Ct [(Wt t)↓]) t' -> t = t'.\n  Hypothesis t_src : forall Cs t, sem src (Cs [(Wt t)]) t. (* CC for Wt *)\n\n  Lemma question_mark_RTC : question_mark -> RTC.\n  Proof.\n    rewrite RTC'. intros Hqm P Ct t Ht.\n    destruct (classic (valid_trace P t)).\n    - exact H.\n    - unfold valid_trace in H. rewrite not_ex_forall_not in H.\n      destruct (Hqm (Wt t) P Ct) as [Cs HCs].\n      + intros b Hb. apply only_t in Hb. rewrite <- Hb. auto.\n      + exfalso. apply ((H Cs)). apply HCs. apply t_src.\n  Qed.\n\n  (* CA:\n\n     only_t + t_src => ((~ valid P t) -> False)\n\n  *)\n\nEnd Stefan.", "meta": {"author": "secure-compilation", "repo": "exploring-robust-property-preservation", "sha": "9ab3f8f03b7eae224326fbbf16a4aaeb3c0df996", "save_path": "github-repos/coq/secure-compilation-exploring-robust-property-preservation", "path": "github-repos/coq/secure-compilation-exploring-robust-property-preservation/exploring-robust-property-preservation-9ab3f8f03b7eae224326fbbf16a4aaeb3c0df996/FSB.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.28437002224495267}}
{"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 proof_with_lib.\nRequire Export proof_with_lib_notation.\n\n\n\nDefinition opabs_myint : opabs := Build_opabs \"myint\" [] [].\n\nDefinition cmds1 {o} : @commands o :=\n  [\n    (* We add the 'member' abstraction *)\n    COM_add_def\n      opabs_member\n      [(nvart, 0), (nvarT, 0)]\n      (mk_so_equality (sovar nvart []) (sovar nvart []) (sovar nvarT []))\n      opabs_member_correct,\n\n    (* We prove that 'member' is well-formed *)\n    COM_start_proof\n      \"member_wf\"\n      (mk_uall\n         (mk_uni 0)\n         nvarT\n         (mk_uall\n            (mk_var nvarT)\n            nvart\n            (mk_member\n               (mk_abs opabs_member [nobnd (mk_var nvart), nobnd (mk_var nvarT)])\n               (mk_uni 0))))\n      (eq_refl, eq_refl),\n    COM_update_proof\n      \"member_wf\"\n      []\n      (proof_step_isect_member_formation (nvar \"T\") 1),\n    COM_update_proof\n      \"member_wf\"\n      [1]\n      (proof_step_isect_member_formation (nvar \"t\") 0),\n    COM_update_proof\n      \"member_wf\"\n      [1,1]\n      (proof_step_cut\n         (nvar \"w\")\n         (mk_cequiv\n            (mk_abs opabs_member [nobnd (mk_var (nvar \"t\")), nobnd (mk_var (nvar \"T\"))])\n            (mk_equality (mk_var (nvar \"t\")) (mk_var (nvar \"t\")) (mk_var (nvar \"T\"))))),\n    COM_update_proof\n      \"member_wf\"\n      [1,1,1]\n      (proof_step_cequiv_computation 1),\n    COM_update_proof\n      \"member_wf\"\n      [1,1,2]\n      (proof_step_cequiv_subst_concl\n         (nvar \"x\")\n         (mk_equality (vterm (nvar \"x\")) (vterm (nvar \"x\")) (mk_uni 0))\n         (mk_abs opabs_member [nobnd (mk_var (nvar \"t\")), nobnd (mk_var (nvar \"T\"))])\n         (mk_equality (mk_var (nvar \"t\")) (mk_var (nvar \"t\")) (mk_var (nvar \"T\")))),\n    COM_update_proof\n      \"member_wf\"\n      [1,1,2,1]\n      (proof_step_hypothesis (nvar \"w\")),\n    COM_update_proof\n      \"member_wf\"\n      [2]\n      (proof_step_universe_equality),\n    COM_update_proof\n      \"member_wf\"\n      [1,2]\n      (proof_step_unhide_equality (nvar \"T\")),\n    COM_update_proof\n      \"member_wf\"\n      [1,2,1]\n      (proof_step_hypothesis_equality),\n    COM_update_proof\n      \"member_wf\"\n      [1,1,2,2]\n      (proof_step_equality_equality),\n    COM_update_proof\n      \"member_wf\"\n      [1,1,2,2,1]\n      (proof_step_unhide_equality (nvar \"T\")),\n    COM_update_proof\n      \"member_wf\"\n      [1,1,2,2,1,1]\n      (proof_step_hypothesis_equality),\n    COM_update_proof\n      \"member_wf\"\n      [1,1,2,2,2]\n      (proof_step_unhide_equality (nvar \"t\")),\n    COM_update_proof\n      \"member_wf\"\n      [1,1,2,2,2,1]\n      (proof_step_hypothesis_equality),\n    COM_update_proof\n      \"member_wf\"\n      [1,1,2,2,3]\n      (proof_step_unhide_equality (nvar \"t\")),\n    COM_update_proof\n      \"member_wf\"\n      [1,1,2,2,3,1]\n      (proof_step_hypothesis_equality),\n    COM_find_holes \"member_wf\",\n    COM_finish_proof \"member_wf\",\n\n    (* We prove that Z is inhabited (by 17 here) *)\n    COM_start_proof\n      \"int_member\"\n      mk_int\n      (eq_refl, eq_refl),\n    COM_update_proof\n      \"int_member\"\n      []\n      (proof_step_introduction (mk_integer 17)),\n    COM_update_proof\n      \"int_member\"\n      [1]\n      (proof_step_integer_equality),\n    COM_finish_proof \"int_member\",\n    COM_find_holes \"int_member\",\n\n    (* We prove that 'int_member' computes to 17 in 1 computation step *)\n    COM_start_proof\n      \"int_member_cequiv\"\n      (mk_cequiv (mk_abs (opname2opabs \"int_member\") []) (mk_integer 17))\n      (eq_refl, eq_refl),\n    COM_update_proof\n      \"int_member_cequiv\"\n      []\n      (proof_step_cequiv_computation 1),\n    COM_find_holes \"int_member_cequiv\",\n    COM_finish_proof \"int_member_cequiv\",\n\n    (* We define a new abstraction on top of the one we got from \"int_member\"'s proof *)\n    COM_add_def\n      opabs_myint\n      []\n      (mk_simple_so_abs (opname2opabs \"int_member\"))\n      (eq_refl, (eq_refl, (eq_refl, (eq_refl, eq_refl)))),\n\n    (* We prove that 'myint' computes to 17 in 2 computation steps *)\n    COM_start_proof\n      \"myint_cequiv\"\n      (mk_cequiv (mk_abs opabs_myint []) (mk_integer 17))\n      (eq_refl, eq_refl),\n    COM_update_proof\n      \"myint_cequiv\"\n      []\n      (proof_step_cequiv_computation 2),\n    COM_find_holes \"myint_cequiv\",\n    COM_finish_proof \"myint_cequiv\",\n\n    (* We prove once more that Z is inhabited.  We'll use our previous proof *)\n    COM_start_proof\n      \"int_member_v2\"\n      mk_int\n      (eq_refl, eq_refl),\n    COM_update_proof\n      \"int_member_v2\"\n      []\n      (proof_step_lemma \"int_member\"),\n    COM_find_holes \"int_member_v2\",\n    COM_finish_proof \"int_member_v2\",\n\n    (* rename 'member' into 'MEMBER' *)\n    COM_rename \"member\" \"MEMBER\"\n  ].\n\nDefinition lib1 {o} : @UpdRes o := update_list_from_init cmds1.\nEval compute in lib1.\n\nTime Eval compute in (update_list_from_init_with_validity cmds1).\n\n(*\n(*\n\n***********************************************\n                  TESTING\n(compute wrapped in a Some below takes forever)\n***********************************************\n\n*)\n\nDefinition cmds2 {o} : @commands o :=\n  [\n    (* We prove that Z is inhabited (by 17 here) *)\n    COM_start_proof\n      \"int_member\"\n      mk_int\n      (eq_refl, eq_refl),\n    COM_update_proof\n      \"int_member\"\n      []\n      (proof_step_introduction (mk_integer 17)),\n    COM_update_proof\n      \"int_member\"\n      [1]\n      (proof_step_integer_equality),\n    COM_finish_proof \"int_member\",\n    COM_find_holes \"int_member\"\n  ].\n\nDefinition lib2 {o} : @UpdRes o := update_list_from_init cmds2.\n\nEval compute in lib2.\nEval compute in (Library2ProofContext (upd_res_state lib2)).\n\nEval compute in (compute_atmost_k_steps\n                   (Library2ProofContext (upd_res_state lib2))\n                   1\n                   (mk_abs (opname2opabs \"int_member\") [])).\n\nLemma reduces_to_of_compute_atmost_k_steps_if_eq {o} :\n  forall lib k (t : @NTerm o) u,\n    compute_atmost_k_steps lib k t = u\n    -> reduces_to lib t u.\nProof.\n  introv h; subst.\n  apply reduces_to_of_compute_atmost_k_steps.\nQed.\n\nOpaque reduces_to_of_compute_atmost_k_steps.\n\nEval compute in\n    (@apply_proof_step_cequiv_computation\n       _\n       (Library2ProofContext (upd_res_state lib2))\n       (mk_pre_bseq [] (pre_concl_ext\n                          (mk_cequiv\n                             (mk_abs (opname2opabs \"int_member\") [])\n                             (mk_integer 17))))\n       1).\n\nEval compute in\n    (* this is fine *)\n    (reduces_to_of_compute_atmost_k_steps [] 0 (mk_integer 1)).\n\nEval compute in\n    (* the [Some] triggers the long computation!  WTF is going on? *)\n    (Some (reduces_to_of_compute_atmost_k_steps [] 0 (mk_integer 1))).\n\nEval compute in\n    (let ctxt := Library2ProofContext (upd_res_state lib2) in\n     let a := mk_abs (opname2opabs \"int_member\") [] in\n     let b := mk_integer 17 in\n     let x := compute_atmost_k_steps ctxt 1 a in\n(*     match term_dec_op x b with\n     | Some p =>\n*)\n       Some (reduces_to_of_compute_atmost_k_steps ctxt 1 a)\n\n(*       Some (reduces_to_of_compute_atmost_k_steps_if_eq ctxt 1 a b p)*)\n\n     (*\n                   Some ((*pre_proof_cequiv_computation\n                           ctxt a b []*)\n                           (eq_rect\n                              _\n                              _\n                              (reduces_to_of_compute_atmost_k_steps ctxt 1 a)\n                              _\n                              p))*)\n\n(*     | None => None\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/rules/proof_with_lib_example1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.28424930096402395}}
{"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 : encodable 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 `{encodable 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 : encodable 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 `{encodable 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 : encodable 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": "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/Datatypes/List/List_nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.28424930096402395}}
{"text": "Add LoadPath \"../metatheory\".\nRequire Export F_init.\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  constr:(A \\u B \\u C \\u D1 \\u D2 \\u D3).\n\n(** Mutual induction principles *)\nScheme pval_mut_ind_aux := Induction for pval Sort Prop\nwith   val_mut_ind_aux  := Induction for val  Sort Prop.\nCombined Scheme pval_val_mut_ind from pval_mut_ind_aux, val_mut_ind_aux.\n\nScheme wfenv_mut_ind_aux := Induction for wfenv Sort Prop\nwith   wftyp_mut_ind_aux := Induction for wftyp Sort Prop.\nCombined Scheme wfenv_wftyp_mut_ind from\n  wfenv_mut_ind_aux, wftyp_mut_ind_aux.\n\n(** Administrative lemmas *)\nLemma pval_val_regular :\n  (forall p, pval p → lc_term p) ∧ (forall v, val v → lc_term v).\nProof.\napply pval_val_mut_ind; eauto.\nQed.\n\nLemma pval_regular : forall p, pval p → lc_term p.\nProof.\nintros; destruct pval_val_regular as [H1 _]; auto.\nQed.\n\nLemma val_regular : forall v, val v → lc_term v.\nProof.\nintros; destruct pval_val_regular as [_ H2]; auto.\nQed.\nHint Resolve pval_regular val_regular.\n\nLemma red0_regular1 : forall e e', red0 e e' → lc_term e.\nProof.\nintros e e' H. destruct H; auto.\nQed.\n\nLemma red0_regular2 : forall e e', red0 e e' → lc_term e'.\nProof.\nintros e e' H; destruct H; eauto with lngen.\nQed.\nHint Resolve red0_regular1 red0_regular2.\n\nLemma red1_regular1 : forall e e', e ⇝ e' → lc_term e.\nProof.\nintros e e' H. induction H; eauto.\nQed.\n\nLemma red1_regular2 : forall e e', e ⇝ e' → lc_term e'.\nProof.\nintros e e' H; induction H; eauto.\nQed.\nHint Resolve red1_regular1 red1_regular2.\n\nLemma wftyp_regular : forall Γ τ, wftyp Γ τ → lc_typ τ.\nProof.\nintros Γ τ H.\ninduction H; eauto.\nQed.\nHint Resolve wftyp_regular.\n\nLemma wfenv_wftyp_aux :\n  (forall Γ, wfenv Γ → forall Γ₁ x τ, Γ = x ~ (Some τ) ++ Γ₁ → wftyp Γ₁ τ) ∧\n  (forall Γ τ, wftyp Γ τ → wfenv Γ).\nProof.\napply wfenv_wftyp_mut_ind; intros; eauto.\ninversion H.\ninversion H0; subst; auto.\ninversion H0.\npick fresh a; assert (a ~ None ++ G ⊢ ok) by auto; inversion H0; subst; auto.\nQed.\n\nLemma wfenv_wftyp :\nforall Γ₁ Γ₂ x τ, wfenv (Γ₁ ++ x ~ Some τ ++ Γ₂) → wftyp Γ₂ τ.\nProof.\ndestruct wfenv_wftyp_aux as [H1 H2].\nintros Γ₁ Γ₂ x τ H0.\ngeneralize dependent Γ₂.\ninduction Γ₁; intros; simpl_env in H0; eauto.\ninversion H0; subst; simpl_env in H5; eauto.\nQed.\nHint Resolve wfenv_wftyp.\n\nLemma wftyp_wfenv : forall Γ τ, wftyp Γ τ → wfenv Γ.\nProof.\ndestruct wfenv_wftyp_aux; auto.\nQed.\nHint Resolve wftyp_wfenv.\n\nLemma wfenv_wftyp_uniq_aux :\n  (forall Γ, wfenv Γ → uniq Γ) ∧ (forall Γ τ, wftyp Γ τ → uniq Γ).\nProof.\napply wfenv_wftyp_mut_ind; intros; auto.\npick fresh a. assert (uniq (a ~ None ++ G)) by auto. destruct_uniq; auto.\nQed.\n\nLemma wfenv_uniq : forall Γ, wfenv Γ → uniq Γ.\nProof.\ndestruct wfenv_wftyp_uniq_aux; auto.\nQed.\nHint Resolve wfenv_uniq.\n\nLemma wftyp_uniq :  forall Γ τ, wftyp Γ τ → uniq Γ.\nProof.\neauto.\nQed.\nHint Resolve wftyp_uniq.\n\n(** Lemmas about [wfenv] and [wftyp] *)\nLemma wfenv_wftyp_weakening :\n(forall Γ, wfenv Γ → forall Γ₁ Γ₂ Γ₃, Γ = Γ₁ ++ Γ₃ → wfenv (Γ₂ ++ Γ₃) → disjoint Γ₁ Γ₂ → wfenv (Γ₁ ++ Γ₂ ++ Γ₃))\n∧\n(forall Γ τ, wftyp Γ τ → forall Γ₁ Γ₂ Γ₃, Γ = Γ₁ ++ Γ₃ → wfenv (Γ₂ ++ Γ₃) → disjoint Γ₁ Γ₂ → wftyp (Γ₁ ++ Γ₂ ++ Γ₃) τ).\nProof.\napply wfenv_wftyp_mut_ind; intros; auto.\nCase \"wfenv_empty\".\ndestruct Γ₁. destruct Γ₃. simpl_env in *; auto.\nsimpl in H; inversion H.\nsimpl in H; inversion H.\nCase \"wfenv_cons_x\".\ndestruct Γ₁; simpl_env in *.\ndestruct Γ₃; simpl_env in *; auto.\ninversion H0; subst.\napply wfenv_cons_x.\nsimpl in H2; apply disjoint_cons_1 in H2; auto.\napply H; auto.\nsimpl in H2; apply disjoint_cons_2 in H2; auto.\nCase \"wfenv_cons_a\".\ndestruct Γ₁; simpl_env in *.\ndestruct Γ₃; simpl_env in *; auto.\ninversion H0; subst.\napply wfenv_cons_a.\nsimpl in H2; apply disjoint_cons_1 in H2; auto.\napply H; auto.\nsimpl in H2; apply disjoint_cons_2 in H2; auto.\nCase \"wftyp_var\".\nsubst G; analyze_binds b.\nCase \"wftyp_forall\".\nsubst G; apply wftyp_forall with (L := L ∪ dom Γ₂); intros.\nrewrite_env ((a~None ++ Γ₁) ++ Γ₂ ++ Γ₃); apply H; eauto.\nQed.\n\nLemma wfenv_weakening :\nforall Γ₁ Γ₂ Γ₃, wfenv (Γ₁ ++ Γ₃) → wfenv (Γ₂ ++ Γ₃) → disjoint Γ₁ Γ₂ → wfenv (Γ₁ ++ Γ₂ ++ Γ₃).\nProof.\ndestruct wfenv_wftyp_weakening as [H1 H2].\nintros; apply (H1 (Γ₁ ++ Γ₃)); auto.\nQed.\n\nLemma wftyp_weakening :\nforall Γ₁ Γ₂ Γ₃ τ, wftyp (Γ₁ ++ Γ₃) τ → wfenv (Γ₂ ++ Γ₃) → disjoint Γ₁ Γ₂ → wftyp (Γ₁ ++ Γ₂ ++ Γ₃) τ.\nProof.\ndestruct wfenv_wftyp_weakening as [H1 H2].\nintros. apply (H2 (Γ₁ ++ Γ₃)); auto.\nQed.\n\nLemma wfenv_wftyp2 :\nforall Γ x τ, wfenv Γ → binds x (Some τ) Γ → wftyp Γ τ.\nProof.\nintro Γ; induction Γ; intros.\nanalyze_binds H0.\ndestruct a; destruct o; simpl_env in *; analyze_binds H0.\nreplace t with τ in * by congruence.\nrewrite_env (nil ++ a ~ Some τ ++ Γ).\ninversion H; subst.\napply wftyp_weakening; auto.\nrewrite_env (nil ++ a ~ Some t ++ Γ).\napply wftyp_weakening; auto. simpl.\ninversion H; subst. eapply IHΓ; eauto.\nrewrite_env (nil ++ a ~ None ++ Γ).\napply wftyp_weakening; auto.\ninversion H; subst. eapply IHΓ; eauto.\nQed.\nHint Resolve wfenv_wftyp2.\n\nLemma wfenv_wftyp3 :\nforall Γ x τ, wfenv (x ~ Some τ ++ Γ) → wftyp Γ τ.\nProof.\nintros Γ x τ H; inversion H; subst; auto.\nQed.\nHint Resolve wfenv_wftyp3.\n\nLemma wfenv_regular :\nforall Γ x τ, wfenv Γ → binds x (Some τ) Γ → lc_typ τ.\nProof.\nintros. induction H; analyze_binds H0.\nreplace t with τ in * by congruence; eauto.\neauto.\nQed.\nHint Resolve wfenv_regular.\n\nLemma wftyp_regular2 : forall Γ x τ τ',\n  wftyp (x ~ Some τ ++ Γ) τ' → lc_typ τ.\nProof.\nintros Γ x τ τ' H. eauto.\nQed.\nHint Resolve wftyp_regular2.\n\nLemma wfenv_wftyp_subst :\n  (forall Γ, wfenv Γ → forall Γ₁ Γ₂ x τ, Γ = Γ₁ ++ x ~ (Some τ) ++ Γ₂ → wfenv (Γ₁ ++ Γ₂)) ∧\n  (forall Γ τ, wftyp Γ τ → forall Γ₁ Γ₂ x τ', Γ = Γ₁ ++ x ~ (Some τ') ++ Γ₂ → wftyp (Γ₁ ++ Γ₂) τ).\nProof.\napply wfenv_wftyp_mut_ind; intros.\nCase \"wfenv_empty\".\nassert (binds x (Some τ) nil). rewrite H; auto. analyze_binds H0.\nCase \"wfenv_cons_x\".\ndestruct Γ₁; simpl_env in *.\ninversion H0; subst; eauto.\ndestruct p; destruct o; inversion H0; subst; simpl_env in *.\nconstructor; eauto.\nCase \"wfenv_cons_a\".\ndestruct Γ₁; simpl_env in *.\ninversion H0; subst; eauto.\ndestruct p; destruct o; inversion H0; subst; simpl_env in *.\nconstructor; eauto.\nCase \"wftyp_var\".\nsubst G. constructor. analyze_binds b. eauto.\nCase \"wftyp_arrow\".\nsubst G. constructor; eauto.\nCase \"wftyp_forall\".\nsubst G. econstructor; intros.\nrewrite_env (([(a, None)] ++ Γ₁) ++ Γ₂). eapply H; simpl_env; eauto.\nQed.\n\nLemma wfenv_subst :\nforall Γ₁ Γ₂ x τ, wfenv (Γ₁ ++ x ~ (Some τ) ++ Γ₂) → wfenv (Γ₁ ++ Γ₂).\nProof.\ndestruct wfenv_wftyp_subst as [H1 H2].\nintros Γ₁ Γ₂ x τ H. eapply H1; eauto.\nQed.\nHint Resolve wfenv_subst.\n\nLemma wftyp_subst :\nforall Γ₁ Γ₂ τ x τ', wftyp (Γ₁ ++ x ~ (Some τ') ++ Γ₂) τ → wftyp (Γ₁ ++ Γ₂) τ.\nProof.\ndestruct wfenv_wftyp_subst as [H1 H2].\nintros. eapply H2; eauto.\nQed.\nHint Resolve wftyp_subst.\n\nLemma wfenv_wftyp_tsubst :\n  (forall Γ, wfenv Γ → forall Γ₁ Γ₂ a τ, Γ = Γ₁ ++ a ~ None ++ Γ₂ → wftyp Γ₂ τ → wfenv ((env_map (tsubst_typ τ a) Γ₁) ++ Γ₂)) ∧\n  (forall Γ τ, wftyp Γ τ → forall Γ₁ Γ₂ a τ', Γ = Γ₁ ++ a ~ None ++ Γ₂ → wftyp Γ₂ τ' → wftyp ((env_map (tsubst_typ τ' a) Γ₁) ++ Γ₂) (tsubst_typ τ' a τ)).\nProof.\napply wfenv_wftyp_mut_ind; intros.\nCase \"wfenv_empty\".\nassert (binds a (@None typ) nil). rewrite H; auto. analyze_binds H1.\nCase \"wfenv_cons_x\".\ndestruct Γ₁; simpl_env in *.\ninversion H0; subst; eauto.\ndestruct p; destruct o; inversion H0; subst; simpl_env in *.\nsimpl; simpl_env.\nconstructor. unfold env_map; auto. eapply H; auto.\nCase \"wfenv_cons_a\".\ndestruct Γ₁; simpl_env in *.\ninversion H0; subst; eauto.\ndestruct p; destruct o; inversion H0; subst; simpl_env in *.\nsimpl; simpl_env.\nconstructor. unfold env_map; auto. eapply H; auto.\nCase \"wftyp_var\".\nsubst G. simpl.\ndestruct (a == a0); subst.\nrewrite_env (nil ++ env_map (tsubst_typ τ' a0) Γ₁ ++ Γ₂); apply wftyp_weakening; auto.\nconstructor; auto.\nanalyze_binds b;\nreplace (@None typ) with (option_map (tsubst_typ τ' a0) None) by reflexivity;\nunfold env_map; auto.\nCase \"wftyp_arrow\".\nsubst G. simpl; constructor; auto.\nCase \"wftyp_forall\".\nsubst G. simpl; apply wftyp_forall with (L := L ∪ {{a}}); intros.\nrewrite_env (([(a0, None)] ++ env_map (tsubst_typ τ' a) Γ₁) ++ Γ₂).\nreplace ([(a0, None)] ++ env_map (tsubst_typ τ' a) Γ₁) with (env_map (tsubst_typ τ' a) ([(a0, None)] ++ Γ₁)) by reflexivity.\nreplace (typ_var_f a0) with (tsubst_typ τ' a (typ_var_f a0)).\nrewrite <- tsubst_typ_open_typ_wrt_typ.\neapply H; simpl_env; eauto. eauto.\nautorewrite with lngen; auto.\nQed.\n\nLemma wfenv_tsubst :\n  forall Γ₁ Γ₂ a τ, wfenv (Γ₁ ++ a ~ None ++ Γ₂) → wftyp Γ₂ τ →\n    wfenv (env_map (tsubst_typ τ a) Γ₁ ++ Γ₂).\nProof.\ndestruct wfenv_wftyp_tsubst as [H1 H2].\nintros Γ₁ Γ₂ x τ H. eapply H1; eauto.\nQed.\nHint Resolve wfenv_tsubst.\n\nLemma wftyp_tsubst :\nforall Γ₁ Γ₂ τ a τ', wftyp (Γ₁ ++ a ~ None ++ Γ₂) τ →\nwftyp Γ₂ τ' → wftyp (env_map (tsubst_typ τ' a) Γ₁ ++ Γ₂) (tsubst_typ τ' a τ).\nProof.\ndestruct wfenv_wftyp_tsubst as [H1 H2].\nintros. eapply H2; eauto.\nQed.\nHint Resolve wftyp_tsubst.\n\nLemma wftyp_fv : forall Γ τ, wftyp Γ τ → ftv_typ τ [<=] dom Γ.\nProof.\nintros Γ τ H. induction H; simpl in *; try fsetdec.\nassert (a ∈ dom G) by eauto; fsetdec.\npick fresh a.\nassert (ftv_typ (open_typ_wrt_typ t (typ_var_f a))[<=]add a (dom G)) by auto.\nassert (ftv_typ t [<=] ftv_typ (open_typ_wrt_typ t (typ_var_f a))); auto with lngen.\nfsetdec.\nQed.\nHint Resolve wftyp_fv.\n\n(** Lemmas about [wfterm] *)\nLemma wfterm_wfenv : forall Γ e τ,\n  wfterm Γ e τ → wfenv Γ.\nProof.\nintros Γ e τ H.\ninduction H; auto.\npick fresh x; assert (wfenv ([(x, Some t1)] ++ G)) by auto; inversion H1; subst; eauto.\npick fresh a; assert (wfenv ([(a, None)] ++ G)) by auto; inversion H1; subst; eauto.\nQed.\nHint Resolve wfterm_wfenv.\n\nLemma wfterm_wftyp : forall Γ e τ,\n  wfterm Γ e τ → wftyp Γ τ.\nProof.\nintros Γ e τ H.\ninduction H.\nCase \"var\". eapply wfenv_wftyp2; eauto.\nCase \"app\". inversion IHwfterm1; subst; auto.\nCase \"abs\". pick fresh x. assert ([(x, Some t1)] ++ G ⊢ t2 ok) by auto.\nassert (wfenv ([(x, Some t1)] ++ G)) by eauto.\ninversion H2; subst.\nconstructor; auto. rewrite_env (nil ++ G). eauto.\nCase \"inst\". inversion IHwfterm; subst.\ninversion IHwfterm; subst.\npick fresh a. rewrite tsubst_typ_intro with (a1 := a); auto.\nrewrite_env (env_map (tsubst_typ t a) nil ++ G).\napply wftyp_tsubst; simpl_env; auto.\nCase \"gen\".\napply wftyp_forall with (L := L); auto.\nQed.\nHint Resolve wfterm_wftyp.\n\nLemma wfterm_regular2 : forall Γ e τ,\n  wfterm Γ e τ → lc_typ τ.\nProof.\nintros Γ e τ H; induction H; eauto.\nQed.\nHint Resolve wfterm_regular2.\n\nLemma wfterm_regular1 : forall Γ e τ,\n  wfterm Γ e τ → lc_term e.\nProof.\nintros Γ e τ H; induction H; auto.\npick fresh x.\napply lc_term_abs_exists with (x1 := x).\napply wfenv_regular with (Γ := [(x, Some t1)] ++ G) (x := x); eauto.\nauto.\neauto.\nQed.\nHint Resolve wfterm_regular1.\n\nLemma wfterm_env_uniq : forall Γ e τ,\n  wfterm Γ e τ → uniq Γ.\nProof.\nintros Γ e τ H. eauto.\nQed.\nHint Resolve wfterm_env_uniq.\n\n(** Lemmas about values *)\nLemma value_is_normal_aux :\n  (forall v, pval v → ~ exists e, v ⇝ e) ∧\n  (forall v, val v → ~ exists e, v ⇝ e).\nProof.\napply pval_val_mut_ind; intros; intros [e0 Hred]; inversion Hred; subst; eauto.\ninversion H.\ninversion H1; subst. inversion p.\ninversion H0; subst. inversion p.\ninversion H0.\npick fresh x. eapply H; eauto.\ninversion H0.\npick fresh a. eapply H; eauto.\nQed.\n\nLemma value_is_normal : forall v, val v → ~ exists e, v ⇝ e.\nProof.\ndestruct value_is_normal_aux as [_ Th]. intuition auto.\nQed.\n\n(** Renaming lemmas *)\nLemma pval_val_renaming : forall x y,\n  (forall v, pval v → pval (subst_term (term_var_f y) x v)) ∧\n  (forall v, val v → val (subst_term (term_var_f y) x v)).\nProof.\nintros x y.\napply pval_val_mut_ind; intros; simpl; auto.\nCase \"var\". destruct (x0 == x); auto.\nCase \"abs\". pick fresh z and apply val_abs; auto.\n  rewrite subst_term_open_term_wrt_term_var; auto.\nCase \"gen\". pick fresh a and apply val_gen; auto.\n  rewrite subst_term_open_term_wrt_typ_var; auto.\nQed.\n\nLemma val_renaming : forall x y v,\n  val v → val (subst_term (term_var_f y) x v).\nProof.\nintros x y v H. destruct (pval_val_renaming x y); auto.\nQed.\nHint Resolve val_renaming.\n\nLemma pval_val_trenaming : forall a b,\n  (forall v, pval v → pval (tsubst_term (typ_var_f b) a v)) ∧\n  (forall v, val v → val (tsubst_term (typ_var_f b) a v)).\nProof.\nintros a b.\napply pval_val_mut_ind; intros; simpl; auto with lngen.\nCase \"abs\". pick fresh z and apply val_abs; auto with lngen.\n  rewrite tsubst_term_open_term_wrt_term_var; auto.\nCase \"gen\". pick fresh c and apply val_gen; auto.\n  rewrite tsubst_term_open_term_wrt_typ_var; auto.\nQed.\n\nLemma val_trenaming : forall a b v,\n  val v → val (tsubst_term (typ_var_f b) a v).\nProof.\nintros a b v H. destruct (pval_val_trenaming a b); auto.\nQed.\nHint Resolve val_trenaming.\n\n(** Lemmas about red0, red1 *)\nLemma red0_subst : forall x e'' e e', lc_term e'' → red0 e e' →\n  red0 (subst_term e'' x e) (subst_term e'' x e').\nProof.\nintros x e'' e e' Hlc H.\ninversion H; subst; simpl.\nrewrite subst_term_open_term_wrt_term; auto. apply red0_beta; auto with lngen.\nassert (lc_term (subst_term e'' x (term_abs t e1))) by auto with lngen; auto.\nrewrite subst_term_open_term_wrt_typ; auto. apply red0_beta_t; auto with lngen.\nassert (lc_term (subst_term e'' x (term_gen e0))) by auto with lngen; auto.\nQed.\nHint Resolve red0_subst.\n\nLemma red1_subst : forall x e'' e e', lc_term e'' → e ⇝ e' →\n  (subst_term e'' x e) ⇝ (subst_term e'' x e').\nProof.\nintros x e'' e e' Hlc H.\ninduction H; subst; simpl; auto with lngen.\napply red1_abs with (L := L `union` {{x}}); auto; intros z Hz.\nreplace (term_var_f z) with (subst_term e'' x (term_var_f z)) by auto with lngen.\nrepeat rewrite <- subst_term_open_term_wrt_term; eauto.\napply red1_gen with (L := L `union` {{x}}); intros a Ha.\nrepeat rewrite <- subst_term_open_term_wrt_typ; eauto.\nQed.\nHint Resolve red1_subst.\n\nLemma red1_open : forall L e'' e e',\n  lc_term e'' →\n  (forall x, x ∉ L → e ^ x ⇝ e' ^ x) →\n  e ^^ e'' ⇝ e' ^^ e''.\nProof.\nintros L e'' e e' Hlc H.\npick fresh x.\nrewrite subst_term_intro with (x1 := x) (e1 := e); auto.\nrewrite subst_term_intro with (x1 := x) (e1 := e'); auto.\nQed.\nHint Resolve red1_open.\n\nLemma red0_tsubst : forall a τ e e', lc_typ τ → red0 e e' →\n  red0 (tsubst_term τ a e) (tsubst_term τ a e').\nProof.\nintros a τ e e' Hlc H.\ninversion H; subst; simpl.\nrewrite tsubst_term_open_term_wrt_term; auto. apply red0_beta; auto with lngen.\nassert (lc_term (tsubst_term τ a (term_abs t e1))) by auto with lngen; auto.\nrewrite tsubst_term_open_term_wrt_typ; auto. apply red0_beta_t; auto with lngen.\nassert (lc_term (tsubst_term τ a (term_gen e0))) by auto with lngen; auto.\nQed.\nHint Resolve red0_tsubst.\n\nLemma red1_tsubst : forall a τ e e', lc_typ τ → e ⇝ e' →\n  (tsubst_term τ a e) ⇝ (tsubst_term τ a e').\nProof.\nintros a τ e e' Hlc H.\ninduction H; subst; simpl; auto with lngen.\napply red1_abs with (L := L `union` {{a}}); auto with lngen ; intros z Hz.\nreplace (term_var_f z) with (tsubst_term τ a (term_var_f z)) by reflexivity.\nrepeat rewrite <- tsubst_term_open_term_wrt_term; eauto.\napply red1_gen with (L := L `union` {{a}}); intros b Hb.\nreplace (typ_var_f b) with (tsubst_typ τ a (typ_var_f b)) by auto with lngen.\nrepeat rewrite <- tsubst_term_open_term_wrt_typ; eauto.\nQed.\nHint Resolve red1_tsubst.\n\nLemma red1_topen : forall L τ e e',\n  lc_typ τ →\n  (forall a, a ∉ L → open_term_wrt_typ e (typ_var_f a) ⇝ open_term_wrt_typ e' (typ_var_f a)) →\n  open_term_wrt_typ e τ ⇝ open_term_wrt_typ e' τ.\nProof.\nintros L τ e e' Hlc H.\npick fresh a.\nrewrite tsubst_term_intro with (a1 := a) (e1 := e); auto.\nrewrite tsubst_term_intro with (a1 := a) (e1 := e'); auto.\nQed.\nHint Resolve red1_topen.\n\n(*\n(* Lemmas about wfterm *)\nLemma wfterm_fv : forall Γ e τ,\n  wfterm Γ e τ → fv_term e [<=] dom Γ.\nProof.\nintros Γ e τ H. induction H; simpl fv_term in *.\nassert (x ∈ dom G) by eauto; fsetdec.\nfsetdec.\npick fresh x. assert (fv_term (e ^ x) [<=] dom (x ~ t1 ++ G)) by auto.\nassert (fv_term e [<=] fv_term (e ^ x)) by auto with lngen.\nassert (fv_term e [<=] {{x}} ∪ dom G). simpl in *; fsetdec.\nfsetdec.\nQed.\n*)\n\nLemma wfterm_uniqueness : forall Γ e τ τ',\n  wfterm Γ e τ → wfterm Γ e τ' → τ = τ'.\nProof.\nintros Γ e τ τ' H1 H2. generalize dependent τ'.\ninduction H1; intros τ' H2; inversion H2; subst.\nCase \"var\".\nassert (Some t = Some τ'). eapply binds_unique; eauto. congruence.\nCase \"app\".\nassert (typ_arrow t2 t1 = typ_arrow t3 τ') by auto; congruence.\nCase \"abs\".\npick fresh x; assert (t2 = t3) by eauto; congruence.\nCase \"inst\".\nassert (typ_forall t' = typ_forall t'0) by auto; congruence.\nCase \"gen\".\npick fresh a. assert (open_typ_wrt_typ t (typ_var_f a) = open_typ_wrt_typ t0 (typ_var_f a)) by auto.\nf_equal; eapply open_typ_wrt_typ_inj; eauto.\nQed.\n\n(*\nLemma wfterm_strengthening : forall Γ₁ Γ₂ x τ τ' e,\n  x ∉ fv_term e →\n  wfterm (Γ₁ ++ x ~ τ' ++ Γ₂) e τ →\n  wfterm (Γ₁ ++ Γ₂) e τ.\nProof.\nintros Γ₁ Γ₂ x τ τ' e Hx He.\ndependent induction He; simpl in Hx.\nCase \"var\".\nconstructor. solve_uniq. analyze_binds_uniq H0.\nCase \"app\".\neconstructor; eauto.\nCase \"abs\".\napply wfterm_abs with (L := L `union` {{x}}); intros.\nrewrite_env (([(x0, t1)] ++ Γ₁) ++ Γ₂).\neapply H0 with (x1 := x); auto.\nassert (fv_term (e ^ x0) [<=] fv_term (term_var_f x0) ∪ fv_term e) as H2\n by auto with lngen.\nsimpl in H2; fsetdec.\nsimpl_env; eauto.\nQed.\n*)\n\n(** Major lemmas about [wfterm] *)\nLemma wfterm_weakening : forall Γ₁ Γ₂ Γ₃ e τ,\n  wfterm (Γ₁ ++ Γ₃) e τ →\n  wfenv (Γ₂ ++ Γ₃) →\n  disjoint Γ₁ Γ₂ →\n  wfterm (Γ₁ ++ Γ₂ ++ Γ₃) e τ.\nProof.\nintros Γ₁ Γ₂ Γ₃ e τ H. dependent induction H; intros; eauto.\nCase \"var\".\nconstructor. auto using wfenv_weakening. analyze_binds H0.\nCase \"abs\". pick fresh x and apply wfterm_abs.\nrewrite_env (([(x, Some t1)] ++ Γ₁) ++ Γ₂ ++ Γ₃).\napply H0; simpl_env; auto.\nCase \"inst\". constructor. auto using wftyp_weakening. eauto.\nCase \"gen\". pick fresh a and apply wfterm_gen.\nrewrite_env (([(a, None)] ++ Γ₁) ++ Γ₂ ++ Γ₃).\napply H0; simpl_env; auto.\nQed.\n\nLemma wfterm_subst : forall Γ₁ Γ₂ x τ₁ τ₂ e₁ e₂,\n  wfterm (Γ₁ ++ x ~ Some τ₂ ++ Γ₂) e₁ τ₁ →\n  wfterm Γ₂ e₂ τ₂ →\n  wfterm (Γ₁ ++ Γ₂) (subst_term e₂ x e₁) τ₁.\nProof with eauto.\nintros Γ₁ Γ₂ x τ₁ τ₂ e₁ e₂ H. dependent induction H; intro; simpl...\nCase \"var\".\n  destruct (x == x0); subst.\n  SCase \"x = x0\".\n    analyze_binds_uniq H0; apply wfterm_weakening with (Γ₁ := nil); auto.\n    replace t with τ₂ by congruence; auto.\n    eapply wfenv_subst; eauto.\n  SCase \"x <> x0\".\n    analyze_binds_uniq H0...\nCase \"abs\".\n  pick fresh z and apply wfterm_abs.\n  rewrite_env ((z ~ Some t1 ++ Γ₁) ++ Γ₂).\n  rewrite subst_term_open_term_wrt_term_var...\n  apply H0 with (τ₂0 := τ₂)...\nCase \"gen\".\n  pick fresh a and apply wfterm_gen.\n  rewrite_env ((a ~ None ++ Γ₁) ++ Γ₂).\n  rewrite subst_term_open_term_wrt_typ_var...\n  apply H0 with (τ₂0 := τ₂)...\nQed.\n\nLemma wfterm_tsubst : forall Γ₁ Γ₂ a τ₁ e₁ τ₂,\n  wfterm (Γ₁ ++ a ~ None ++ Γ₂) e₁ τ₁ →\n  wftyp Γ₂ τ₂ →\n  wfterm (env_map (tsubst_typ τ₂ a) Γ₁ ++ Γ₂) (tsubst_term τ₂ a e₁) (tsubst_typ τ₂ a τ₁).\nProof with eauto.\nintros Γ₁ Γ₂ a τ₁ e₁ τ₂ H. dependent induction H; intro; simpl...\nCase \"var\".\nconstructor. auto using wfenv_tsubst.\nreplace (Some (tsubst_typ τ₂ a t)) with (option_map (tsubst_typ τ₂ a) (Some t)) by reflexivity.\nunfold env_map. analyze_binds H0.\nsimpl.\nassert (a ∉ ftv_typ t).\n  assert (ftv_typ t [<=] dom Γ₂) by eauto.\n  assert (uniq (Γ₁ ++ [(a, None)] ++ Γ₂)) by auto.\n  destruct_uniq. fsetdec.\nautorewrite with lngen; auto.\nCase \"app\".\neconstructor.\neapply IHwfterm1; auto.\neapply IHwfterm2; auto.\nCase \"abs\".\n  pick fresh z and apply wfterm_abs.\n  rewrite_env (env_map (tsubst_typ τ₂ a) ([(z, Some t1)] ++ Γ₁) ++ Γ₂).\n  rewrite tsubst_term_open_term_wrt_term_var...\nCase \"inst\".\n  rewrite tsubst_typ_open_typ_wrt_typ...\n  constructor; auto. apply IHwfterm; auto.\nCase \"gen\".\n  pick fresh b and apply wfterm_gen.\n  rewrite_env (env_map (tsubst_typ τ₂ a) ([(b, None)] ++ Γ₁) ++ Γ₂).\n  rewrite tsubst_term_open_term_wrt_typ_var...\n  rewrite tsubst_typ_open_typ_wrt_typ_var...\nQed.\n\n(** Soundness *)\nTheorem subject_reduction : forall Γ e e' τ,\n  wfterm Γ e τ → e ⇝ e' → wfterm Γ e' τ.\nProof with eauto.\n  intros Γ e e' τ H. generalize dependent e'.\n  dependent induction H.\n  Case \"var\".\n    intros e' J; inversion J; subst; inversion H1.\n  Case \"app\".\n    intros e' J; inversion J; subst...\n    inversion H; subst; inversion H1; subst.\n    pick fresh z.\n    rewrite (subst_term_intro z)...\n    eapply wfterm_subst with (Γ₁ := nil); simpl_env...\n  Case \"abs\".\n    intros e' J; inversion J; subst.\n    inversion H1.\n    pick fresh z and apply wfterm_abs...\n  Case \"inst\".\n    intros e' J; inversion J; subst; auto.\n    inversion H1; subst.\n    inversion H0; subst.\n    pick fresh a.\n    rewrite (tsubst_term_intro a)...\n    rewrite (tsubst_typ_intro a)...\n    rewrite_env (env_map (tsubst_typ t a) nil ++ G).\n    eapply wfterm_tsubst; simpl_env...\n  Case \"gen\".\n    intros e' J; inversion J; subst.\n    inversion H1.\n    pick fresh a and apply wfterm_gen...\nQed.\n\nTheorem progress : forall Γ e τ,\n  wfterm Γ e τ →\n  (exists e', e ⇝ e') ∨ val e.\nProof with eauto.\n  intros Γ e τ H.\n  dependent induction H; simpl...\n  Case \"typing_app\".\n    destruct IHwfterm1 as [[e1' ?] | ?]...\n    destruct IHwfterm2 as [[e2' ?] | ?]...\n    destruct e1; simpl in H1; inversion H1; subst; try solve [inversion H]; eauto 7.\n  Case \"abs\".\n    pick fresh z. edestruct (H0 z) as [[e1 ?] | ?]...\n    left.\n      exists (term_abs t1 (close_term_wrt_term z e1)).\n      apply red1_abs with (L := L `union` {{z}}); intros...\n      rewrite <- subst_term_spec.\n      rewrite (subst_term_intro z)...\n    right.\n      apply val_abs with (L := L `union` {{z}}); intros...\n      rewrite (subst_term_intro z)...\n  Case \"inst\".\n    destruct IHwfterm as [[e' ? ] | ? ]...\n    destruct e; simpl in H1; inversion H1; subst; eauto.\n    inversion H0.\n    eauto 7.\n  Case \"gen\".\n    pick fresh a. edestruct (H0 a) as [[e1 ?] | ?]...\n    left.\n      exists (term_gen (close_term_wrt_typ a e1)).\n      apply red1_gen with (L := L `union` {{a}}); intros.\n      rewrite <- tsubst_term_spec.\n      rewrite (tsubst_term_intro a)...\n    right.\n      apply val_gen with (L := L `union` {{a}}); intros.\n      rewrite (tsubst_term_intro a)...\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_soundness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.2842493009640239}}
{"text": "(*\nCopyright © 2006-2008 Russell O’Connor\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis proof and associated documentation files (the \"Proof\"), to deal in\nthe Proof without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Proof, and to permit persons to whom the Proof is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Proof.\n\nTHE PROOF IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE PROOF OR THE USE OR OTHER DEALINGS IN THE PROOF.\n*)\n\nRequire Import CoRN.algebra.RSetoid.\nRequire Import CoRN.metric2.Metric.\nRequire Import CoRN.metric2.UniformContinuity.\nRequire Import CoRN.reals.fast.CRcorrect.\nRequire Export CoRN.model.metric2.CRmetric.\nRequire Export CoRN.algebra.CSetoids.\nRequire Import CoRN.tactics.CornTac.\n\n#[global]\nInstance CR_default : @DefaultRelation CR (@msp_eq CR) | 2 := {}.\n\n(**\n** Example of a setoid: [CR]\n*** [CR]\n*)\n\nLemma CRisCSetoid : is_CSetoid CR (@msp_eq CR) CRapartT.\nProof.\n split;simpl.\n    intros x H.\n    eapply ap_irreflexive.\n    apply CR_ap_as_Cauchy_IR_ap_1.\n    apply H.\n   intros x y H.\n   apply CR_ap_as_Cauchy_IR_ap_2.\n   eapply ap_symmetric.\n   apply CR_ap_as_Cauchy_IR_ap_1.\n   apply H.\n  intros x y H1 z.\n  destruct (ap_cotransitive _ _ _ (CR_ap_as_Cauchy_IR_ap_1 _ _ H1) (CRasCauchy_IR z));[left|right];\n    apply CR_ap_as_Cauchy_IR_ap_2; assumption.\n intros x y.\n change (Not (CRapartT x y)<->(x==y)%CR).\n rewrite <- CR_eq_as_Cauchy_IR_eq.\n destruct (ap_tight _ (CRasCauchy_IR x) (CRasCauchy_IR y)) as [A B].\n split.\n  intros H.\n  apply A.\n  intros X.\n  apply H.\n  apply CR_ap_as_Cauchy_IR_ap_2.\n  assumption.\n intros H X.\n apply (B H).\n apply CR_ap_as_Cauchy_IR_ap_1.\n apply X.\nQed.\n\nDefinition CRasCSetoid : CSetoid := makeCSetoid (msp_as_RSetoid CR) _ CRisCSetoid.\n\nCanonical Structure CRasCSetoid.\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/model/setoids/CRsetoid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.2842493009640239}}
{"text": "Require Import VST.msl.msl_standard.\nRequire Import VST.msl.corable.\nRequire Import RamifyCoq.msl_ext.ramify_tactics.\nRequire Import RamifyCoq.msl_ext.msl_ext.\nRequire Import RamifyCoq.msl_ext.sepalg.\n\nLocal Open Scope pred.\n\nLemma join_age {A}{JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A}:\n  forall h1 h2 h12 h1' h2' h12', join h1 h2 h12 -> join h1' h2' h12' -> age h1 h1' -> age h2 h2' -> age h12 h12'.\nProof.\n  intros; destruct (age1_join _ H H1) as [w2 [w12 [? [? ?]]]];\n  equate_age h2' w2; equate_join h12' w12; auto.\nQed.\n\nProgram Definition ocon {A: Type}{JA: Join A}{PA : Perm_alg A}{AG : ageable A} {AA : Age_alg A} (p q:pred A) : pred A :=\n  fun h:A => exists h1 h2 h3 h12 h23, join h1 h2 h12 /\\ join h2 h3 h23 /\\ join h12 h3 h /\\ p h12 /\\ q h23.\nNext Obligation.\n  destruct H0 as [h1 [h2 [h3 [h12 [h23 [? [? [? [? ?]]]]]]]]].\n  try_join h2 h3 h23'; equate_join h23 h23'.\n  destruct (age1_join2 _ H2 H) as [w12 [w3 [? [? ?]]]].\n  destruct (age1_join2 _ H0 H7) as [w1 [w2 [? [? ?]]]].\n  try_join w2 w3 w23.\n  exists w1, w2, w3, w12, w23.\n  repeat split; auto.\n  apply pred_hereditary with h12; auto.\n  apply pred_hereditary with h23; auto.\n  apply (join_age h2 h3 _ w2 w3 _); auto.\nQed.\n\nNotation \"P ⊗ Q\" := (ocon P Q) (at level 40, left associativity) : pred.\n\nProgram Definition owand {A: Type}{JA: Join A}{PA : Perm_alg A}{AG : ageable A} {AA : Age_alg A} (p q:pred A) : pred A :=\n  fun h23':A => forall h23 h1 h2 h3 h12 h123, necR h23' h23 -> join h1 h2 h12 -> join h2 h3 h23 -> join h12 h3 h123 -> p h12 -> q h123.\nNext Obligation.\n  rename a' into h23'.\n  eapply (H0 h23 h1 h2 h3 h12 h123); eauto.\n  apply necR_power_age.\n  apply necR_power_age in H1.\n  destruct H1 as [n ?H].\n  exists (S n).\n  exists h23'; auto.\nQed.\n\nLemma ocon_emp {A}{JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{CA: Canc_alg A}{AG : ageable A} {AA : Age_alg A}: forall P: pred A, P ⊗ emp = P.\nProof.\n  intros; apply pred_ext; hnf; intros; simpl in *; intros.\n  destruct_ocon H h; try_join h2 h3 h23'; equate_join h23 h23'.\n  rewrite (H3 _ _ (join_comm H5)) in H.\n  generalize (join_positivity H H1); intro; rewrite H4; trivial.\n  exists a, (core a), (core a), a, (core a).\n  generalize (core_unit a); intro.\n  unfold unit_for in H0.\n  repeat split; auto.\n  apply core_duplicable.\n  apply core_identity.\nQed.\n\nLemma ocon_TT {A}{JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{CA: Canc_alg A}{AG : ageable A} {AA : Age_alg A}: forall P: pred A, P ⊗ TT = P * TT.\nProof.\n  intros; apply pred_ext; hnf; intros; simpl in *; intros.\n  + destruct_ocon H h.\n    exists h12, h3; auto.\n  + destruct H as [? [? [? [? ?]]]].\n    exists x, (core x), x0, x, x0.\n    repeat split; auto.\n    - apply join_comm, core_unit.\n    - apply join_core2 in H.\n      rewrite H.\n      apply core_unit.\nQed.\n\nLemma andp_ocon {A}{JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG : ageable A} {AA : Age_alg A}: forall P Q, P && Q |-- P ⊗ Q.\nProof.\n  intros.\n  hnf; intros; simpl in *; intros.\n  destruct H.\n  remember (core a) as u.\n  exists u, a, u, a, a.\n  repeat split; try rewrite Hequ; auto;\n  try apply core_unit;\n  apply join_comm; apply core_unit.\nQed.\n\nLemma ocon_andp_prop {A}{JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG : ageable A} {AA : Age_alg A}: forall P Q R, P ⊗ (!!Q && R) = !!Q && (P ⊗ R).\nProof.\n  intros; apply pred_ext; hnf; intros; simpl in *.\n  + destruct H as [h1 [h2 [h3 [h12 [h23 [? [? [? [? [? ?]]]]]]]]]].\n    split; auto. exists h1, h2, h3, h12, h23. intuition.\n  + destruct H as [? [h1 [h2 [h3 [h12 [h23 [? [? [? [? ?]]]]]]]]]].\n    exists h1, h2, h3, h12, h23. intuition.\nQed.\n\nLemma sepcon_ocon {A}{JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG : ageable A} {AA : Age_alg A}: forall P Q, P * Q |-- P ⊗ Q.\nProof.\n  intros; hnf; intros; simpl in *; intros.\n  destruct H as [y [z [? [? ?]]]].\n  remember (core z) as u.\n  exists y, u, z, y, z.\n  repeat split; auto.\n  generalize (join_core H); intro.\n  generalize (join_core (join_comm H)); intro.\n  rewrite Hequ.\n  replace (core z) with (core y).\n  apply join_comm, core_unit.\n  rewrite H2, H3; trivial.\n  rewrite Hequ. apply core_unit.\nQed.\n\nLemma join_necR {A}{JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A}:\n  forall h1 h2 h12 h1' h2' h12', join h1 h2 h12 -> join h1' h2' h12' -> necR h1 h1' -> necR h2 h2' -> necR h12 h12'.\nProof.\n  intros; destruct (nec_join H H1) as [w2 [w12 [? [? ?]]]];\n  destruct (join_level _ _ _ H3); rewrite <- H7 in H6;\n  destruct (join_level _ _ _ H0); rewrite <- H9 in H8;\n  rewrite H8 in H6; generalize (necR_linear' H2 H4 H6); intro;\n  rewrite <- H10 in H3; equate_join h12' w12; auto.\nQed.\n\nLemma ocon_wand {A}{JA: Join A}{PA: Perm_alg A}{AG : ageable A} {AA : Age_alg A}: forall P Q, P ⊗ Q = EX R : pred A, (R -* P) * (R -* Q) * R.\nProof.\n  intros; apply pred_ext; hnf; intros; simpl in *.\n  destruct H as [h1 [h2 [h3 [h12 [h23 [? [? [? [? ?]]]]]]]]].\n  try_join h2 h3 h23'; equate_join h23 h23'; try_join h1 h3 h13.\n  exists (exactly h2), h13, h2; repeat split; simpl; auto; exists h1, h3; repeat split; auto.\n  intros h1' h2' h12'; intros; apply (pred_nec_hereditary P h12); auto; apply (join_necR h1 h2 _ h1' h2' _); auto.\n  intros h3' h2' h23'; intros; apply (pred_nec_hereditary Q h23); auto; apply (join_necR h2 h3 _ h2' h3' _); auto.\n  (* another direction *)\n  destruct H as [R [w13 [w2 [? [[w1 [w3 [? [HP HQ]]]] HR]]]]].\n  try_join w2 w3 w23; try_join w1 w2 w12.\n  exists w1, w2, w3, w12, w23; repeat split; auto.\n  apply (HP w1 w2); auto. apply (HQ w3 w2); auto.\nQed.\n\nLemma ocon_comm {A}{JA: Join A}{PA: Perm_alg A}{AG : ageable A} {AA : Age_alg A}: forall P Q, P ⊗ Q = Q ⊗ P.\nProof.\n  intros; apply pred_ext; hnf; intros; simpl in *; intros;\n  destruct_ocon H h; exists h3, h2, h1, h23, h12;\n  repeat split; auto; try_join h2 h3 h23'; equate_join h23 h23'; auto.\nQed.\n\nLemma cross_rev {A}{JA: Join A}{PA: Perm_alg A}{AG : ageable A} {AA : Age_alg A}: forall h1 h2 h3 h4\n  h12 h34 h13 h24 h1234, join h1 h2 h12 -> join h1 h3 h13 -> join h3 h4\n  h34 -> join h2 h4 h24 -> join h12 h34 h1234 -> join h13 h24 h1234.\nProof.\n  intros; try_join h2 h34 h234;\n  try_join h2 h4 h24'; equate_join h24 h24';\n  try_join h1 h3 h13'; equate_join h13 h13'; auto.\nQed.\n\nLemma ocon_assoc {A}{JA: Join A}{PA: Perm_alg A}{CA: Cross_alg A}{AG : ageable A} {AA : Age_alg A}:\n  forall P Q R: pred A, P ⊗ Q ⊗ R = P ⊗ (Q ⊗ R).\nProof.\n  intros; apply pred_ext; hnf; intros; simpl in *; intros.\n  destruct H as [w124 [w567 [w3 [w124567 [w3567 [? [? [? [[w15 [w47 [w26 [w1457 [w2467 [? [? [? [? ?]]]]]]]]] ?]]]]]]]]].\n  destruct (cross_split _ _ _ _ _ H H4) as [[[[w14 w2] w57] w6] [? [? [? ?]]]].\n  destruct (cross_split _ _ _ _ _ H2 H10) as [[[[w1 w5] w4] w7] [? [? [? ?]]]].\n  try_join w5 w47 w457; try_join w3 w26 w236; try_join w236 w457 w234567.\n  exists w1, w457, w236, w1457, w234567; repeat split; auto.\n  try_join w2 w4 w24; try_join w6 w7 w67; try_join w3 w5 w35.\n  exists w24, w67, w35, w2467, w3567; repeat split; auto.\n  apply (cross_rev w2 w6 w4 w7 w26 w47); auto. apply (cross_rev w47 w5 w26 w3 w457 w236); auto.\n  (* another direction *)\n  destruct H as [w1 [w457 [w236 [w1457 [w234567 [? [? [? [? [w24 [w67 [w35 [w2467 [w3567 [? [? [? [? ?]]]]]]]]]]]]]]]]]].\n  destruct (cross_split _ _ _ _ _ H0 H5) as [[[[w47 w5] w26] w3] [? [? [? ?]]]].\n  destruct (cross_split _ _ _ _ _ H3 H10) as [[[[w4 w2] w7] w6] [? [? [? ?]]]].\n  try_join w26 w1457 w124567; try_join w5 w67 w567; try_join w5 w7 w57; try_join w1 w4 w14;\n  try_join w14 w26 w1246; try_join w2 w14 w124.\n  exists w124, w567, w3, w124567, w3567; repeat split; auto.\n  apply join_comm; apply (cross_rev w6 w2 w57 w14 w26 w1457); auto.\n  try_join_through w67 w5 w7 w57'; equate_join w57 w57'; auto.\n  try_join w1 w5 w15; exists w15, w47, w26, w1457, w2467;\n  repeat split; auto.\nQed.\n\nLemma ocon_derives {A} {JA: Join A}{PA: Perm_alg A}{AG : ageable A} {AA : Age_alg A}: forall p q p' q', (p |-- p') -> (q |-- q') -> (p ⊗ q |-- p' ⊗ q').\nProof.\n  repeat (intros; hnf).\n  simpl in H1.\n  destruct_ocon H1 w.\n  exists w1,w2,w3,w12,w23.\n  repeat split; auto.\nQed.\n\nLemma owand_ocon_adjoint {A} {JA: Join A}{PA: Perm_alg A}{AG : ageable A} {AA : Age_alg A}: forall P Q R, ocon P Q |-- R <-> P |-- owand Q R.\nProof.\n  intros.\n  rewrite ocon_comm.\n  unfold ocon, owand, derives.\n  simpl.\n  split; intros.\n  + apply H.\n    exists h1, h2, h3, h12, h23.\n    repeat split; auto.\n    inversion P.\n    apply pred_nec_hereditary with a; auto.\n  + destruct H0 as [h1 [h2 [h3 [h12 [h23 [? [? [? [? ?]]]]]]]]].\n    specialize (H h23 H4).\n    specialize (H h23 h1 h2 h3 h12 a).\n    apply H; auto.\nQed.\n\nLemma ocon_contain {A} {JA: Join A} {PA: Perm_alg A} {SA: Sep_alg A}{AG : ageable A} {AA : Age_alg A}: forall P Q, Q |-- P * TT -> Q |-- ocon P Q.\nProof.\n  unfold ocon, owand, derives; simpl; intros.\n  destruct (H a H0) as [y [z [? [? ?]]]].\n  exists (core y), y, z, y, a.\n  repeat split; auto.\n  apply core_unit.\nQed.\n\nLemma precise_ocon_contain {A} {JA: Join A} {PA: Perm_alg A} {SA: Sep_alg A} {CA: Canc_alg A} {DA: Disj_alg A} {AG : ageable A} {AA : Age_alg A}: forall P Q, precise P -> Q |-- P * TT -> Q = ocon P Q.\nProof.\n  intros; apply pred_ext; [apply ocon_contain; auto |].\n  unfold ocon, owand, derives in *; simpl in *.\n  intros.\n  destruct H1 as [h1 [h2 [h3 [h12 [h23 [? [? [? [? ?]]]]]]]]].\n  destruct (H0 _ H5) as [y [z [? [? ?]]]].\n  try_join h2 h3 h23'. equate_join h23 h23'. assertSub y a HS1.\n  equate_precise y h12.\n  try_join z h1 h3'. equate_canc h3 h3'.\n  assert (identity h1).\n  1: {\n    try_join h1 h3 h_temp.\n    assertSub h1 h3 H12.\n    eapply join_sub_joins_identity; eauto.\n  }\n  apply join_comm in H4.\n  apply H9 in H10; apply H9 in H4.\n  subst.\n  auto.\nQed.\n\nDefinition disjointed {A: Type} {JA: Join A} {AG : ageable A} (P Q: pred A):=\n  forall h1 h2 h3 h12 h23,\n  join h1 h2 h12 -> join h2 h3 h23 -> P h12 -> Q h23 -> identity h2 /\\ joins h1 h3.\n\nLemma ocon_sepcon {A: Type} {JA: Join A} {SA: Sep_alg A} {PA : Perm_alg A} {AG : ageable A} {AA : Age_alg A}:\n  forall P Q, disjointed P Q -> ocon P Q |-- P * Q.\nProof.\n  unfold ocon, sepcon, disjointed, derives; simpl.\n  intros.\n  destruct H0 as [h1 [h2 [h3 [h12 [h23 [? [? [? [? ?]]]]]]]]].\n  destruct (H h1 h2 h3 h12 h23 H0 H1 H3 H4) as [? ?].\n  apply join_comm in H0.\n  apply H5 in H0.\n  apply H5 in H1.\n  subst.\n  exists h12, h23.\n  auto.\nQed.\n\nLemma disj_emp {A: Type} {JA: Join A} {SA: Sep_alg A} {PA : Perm_alg A} {CA: Canc_alg A} {AG : ageable A} {AA : Age_alg A}: forall P, disjointed P emp.\nProof.\n  intros.\n  unfold disjointed, emp; simpl; intros.\n  pose proof split_identity _ _ H0 H2.\n  pose proof split_identity _ _ (join_comm H0) H2.\n  pose proof identities_unique H3 H4 (ex_intro _ h23 H0).\n  subst.\n  split; eauto.\nQed.\n\nLemma disj_comm {A: Type} {JA: Join A} {PA: Perm_alg A} {AG : ageable A}: forall P Q, disjointed P Q -> disjointed Q P.\nProof.\n  unfold disjointed; intros.\n  specialize (H h3 h2 h1 h23 h12).\n  do 2 (spec H; [apply join_comm; auto |]).\n  do 2 (spec H; [auto |]).\n  destruct H; split; auto.\n  apply joins_comm; auto.\nQed.\n\nLemma disj_derives {A: Type} {JA: Join A} {PA: Perm_alg A} {AG : ageable A}:\n  forall P P' Q Q', P |-- P' -> Q |-- Q' -> disjointed P' Q' -> disjointed P Q.\nProof.\n  unfold derives, disjointed.\n  intros.\n  apply H1 with h12 h23; auto.\nQed.\n\n(**************************************************************************\n\n\n\n          |------------------------------------------|\n          |                                          | \n          |                                          | \n          |                                          | \n          |                     P                    | \n          |                                          | \n          |                                          | \n|---------|----------|-----------------------|-------|------------|\n|         |          |                       |       |            |\n|         |    p1    |         p2            |   p3  |            |\n|         |          |                       |       |            |\n|         |------------------------------------------|            |\n|                    |                       |                    |\n|                    |                       |                    |\n|        r1          |          r2           |         r3         |\n|                    |                       |                    |\n|                    |                       |                    |\n|                    |                       |                    |\n|--------------------|-----------------------|--------------------|\n\n\n\n\n**************************************************************************)\n\nLemma disj_ocon_right {A: Type} {JA: Join A} {SA: Sep_alg A} {PA : Perm_alg A} {CA: Canc_alg A} {CrA: Cross_alg A} {TA: Trip_alg A} {AG : ageable A} {AA : Age_alg A}:\n  forall P Q R, disjointed P Q -> disjointed P R -> disjointed P (ocon Q R).\nProof.\n  unfold ocon, disjointed, precise; simpl.\n  intros P Q R ? ? hP hp1p2p3 hr1r2r3 hPp h123.\n  intros.\n  destruct H4 as [h1 [h2 [h3 [h12 [h23 [? [? [? [? ?]]]]]]]]].\n  destruct (join_assoc H4 H6) as [h23' [? ?]]; equate_join h23 h23'.\n  destruct (cross_split _ _ _ _ _ H10 H2) as [[[[hp1 hr1] hp2p3] hr2r3] [? [? [? ?]]]].\n  destruct (cross_split _ _ _ _ _ H5 H11) as [[[[hp2 hr2] hp3] hr3] [? [? [? ?]]]].\n  try_join hp1 hp2 hp1p2.\n  try_join hr1 hr2 hr1r2.\n  assert (join hp1p2 hr1r2 h12).\n  1: {\n    try_join hp1 h2 hp1p2r2.\n    destruct (join_assoc (join_comm H14) (join_comm H22)) as [hp1p2' [? ?]].\n    equate_join hp1p2 hp1p2'.\n    destruct (join_assoc (join_comm H25) (join_comm H23)) as [hr1r2' [? ?]].\n    equate_join hr1r2 hr1r2'.\n    auto.\n  }\n\n  try_join hP hp3 hPp3.\n  assert (identity hp1p2 /\\ joins hPp3 hr1r2) as [? ?] by (apply H with hPp h12; auto).\n  try_join hP hp1 hPp1.\n  assert (identity hp2p3 /\\ joins hPp1 hr2r3) as [? ?] by (apply H0 with hPp h23; auto).\n\n  assert (identity hp1) by (apply split_identity with hp2 hp1p2; auto).\n  assert (identity hp3) by (apply split_identity with hp2 hp2p3; auto).\n  split.\n  + apply join_identity with hp1 hp2p3; auto.\n  + apply H31 in H27.\n    apply H32 in H23.\n    subst hPp1 hPp3.\n    destruct H26 as [hPr1r2 ?].\n    destruct H30 as [hPr1r3 ?].\n    destruct (join_assoc H20 (join_comm H23)) as [hPr1 [? ?]].\n    destruct (triple_join_exists _ _ _ _ _ _ H13 (join_comm H26) H27) as [hPr1r2r3 ?H].\n    apply joins_comm; eauto.\nQed.\n\nDefinition covariant {B A : Type} {AG: ageable A} (F: (B -> pred A) -> (B -> pred A)) : Prop :=\nforall (P Q: B -> pred A), (forall x, P x |-- Q x) -> (forall x, F P x |-- F Q x).\n\nLemma covariant_ocon {B}{A} {JA: Join A}{PA: Perm_alg A}{AG : ageable A} {AA : Age_alg A}:\n   forall F1 F2 : (B -> pred A) -> (B -> pred A),\n    covariant F1 -> covariant F2 ->\n    covariant (fun (x : B -> pred A) b => F1 x b ⊗ F2 x b).\nProof.\n  intros; hnf.\n  intros P Q ? ?.\n  eapply ocon_derives.\n  apply H, H1.\n  apply H0, H1.\nQed.\n\nDefinition contravariant {B A : Type} {AG: ageable A} (F: (B -> pred A) -> (B -> pred A)) : Prop :=\nforall (P Q: B -> pred A), (forall x, P x |-- Q x) -> (forall x, F Q x |-- F P x).\n\nLemma contravariant_ocon {B}{A} {JA: Join A}{PA: Perm_alg A}{AG : ageable A} {AA : Age_alg A}:\n   forall F1 F2 : (B -> pred A) -> (B -> pred A),\n    contravariant F1 -> contravariant F2 ->\n    contravariant (fun (x : B -> pred A) b => F1 x b ⊗ F2 x b).\nProof.\n  intros; hnf.\n  intros P Q ? ?.\n  eapply ocon_derives.\n  apply H, H1.\n  apply H0, H1.\nQed.\n\nLemma later_ocon {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)) = |> Q ⊗ |> P).\nProof.\n  intros; repeat rewrite later_age; apply pred_ext; hnf; intros; simpl in *.\n  case_eq (age1 a); intros.\n  destruct (H a0) as [h1' [h2' [h3' [h12' [h23' [? [? [? [? ?]]]]]]]]]; auto.\n  destruct (unage_join2 _ H3 H0) as [x12 [x3 [? [? ?]]]].\n  destruct (unage_join2 _ H1 H7) as [x1 [x2 [? [? ?]]]].\n  try_join x2 x3 x23; exists x3, x2, x1, x23, x12; repeat (split; auto).\n  assert (age x23 h23') by (apply (join_age x2 x3 _ h2' h3' _); auto); intro h23; intros; equate_age h23' h23; auto.\n  assert (age x12 h12') by (apply (join_age x1 x2 _ h1' h2' _); auto); intro h12; intros; equate_age h12' h12; auto.\n  exists (core a), a, (core a), a, a. repeat split.\n  apply core_unit. apply join_comm, core_unit. apply join_comm, core_unit.\n  intros; unfold age in H1; rewrite H0 in H1; discriminate H1.\n  intros; unfold age in H1; rewrite H0 in H1; discriminate H1.\n  (* another direction *)\n  destruct H as [x1 [x2 [x3 [x12 [x23 [? [? [? [? ?]]]]]]]]]; intros.\n  destruct (age1_join2 _ H1 H4) as [h12 [h3 [? [? ?]]]].\n  destruct (age1_join2 _ H H6) as [h1 [h2 [? [? ?]]]].\n  try_join h2 h3 h23; exists h3, h2, h1, h23, h12; repeat (split; auto).\n  apply H3; apply (join_age x2 x3 _ h2 h3 _); auto.\nQed.\n\nLemma precise_ocon {A} {JA : Join A} {PA : Perm_alg A} {SA: Sep_alg A}{CaA : Canc_alg A}{CrA : Cross_alg A}{DA : Disj_alg A}{AG : ageable A} {AA : Age_alg A} :\n  forall P Q, precise P -> precise Q -> precise (P ⊗ Q).\nProof.\n  intros; intro; intros.\n  destruct_ocon H1 h; destruct_ocon H2 i.\n  generalize (join_join_sub H6); intro; generalize (join_sub_trans H13 H3); intro.\n  generalize (join_join_sub H10); intro; generalize (join_sub_trans H15 H4); intro.\n  generalize (H w h12 i12 H7 H11 H14 H16); intro.\n  try_join h2 h3 h23'; equate_join h23 h23'; try_join i2 i3 i23'; equate_join i23 i23'.\n  generalize (join_join_sub' H19); intro; generalize (join_sub_trans H18 H3); intro.\n  generalize (join_join_sub' H20); intro; generalize (join_sub_trans H22 H4); intro.\n  generalize (H0 w h23 i23 H8 H12 H21 H23); intro.\n  rewrite H17 in *; rewrite H24 in *. clear h12 h23 H7 H8 H11 H12 H13 H14 H15 H16 H17 H18 H21 H22 H23 H24.\n  apply (overlapping_eq h1 h2 h3 i1 i2 i3 i12 i23); trivial.\nQed.\n\nLemma precise_tri_exp_ocon {A} {JA : Join A} {PA : Perm_alg A} {SA: Sep_alg A} {CaA : Canc_alg A}\n      {CrA : Cross_alg A} {DA : Disj_alg A}{AG : ageable A} {AA : Age_alg A} B:\n  forall (P : B -> B -> B -> pred A) (Q R: B -> pred A),\n    precise (EX x : B, EX y : B, EX z : B, P x y z) -> precise (exp Q) -> precise (exp R) ->\n    precise (EX x : B, EX y : B, EX z : B, P x y z ⊗ Q y ⊗ R z).\nProof.\n  repeat intro.\n  destruct H2 as [x1 [y1 [z1 ?]]]; destruct_ocon H2 h; destruct_ocon H8 j;\n  destruct H3 as [x2 [y2 [z2 ?]]]; destruct_ocon H3 i; destruct_ocon H16 k.\n  assert (j12 = k12) by (hnf in H; apply H with (w := w);\n                         [exists x1, y1, z1 | exists x2, y2, z2 | assertSub j12 w Hsub | assertSub k12 w Hsub]; auto).\n  assert (j23 = k23) by (hnf in H0; apply H0 with (w := w);\n                         [exists y1 | exists y2 | try_join j2 j3 j23'; equate_join j23 j23'; assertSub j23 w Hsub |\n                                 try_join k2 k3 k23'; equate_join k23 k23'; assertSub k23 w Hsub]; auto).\n  rewrite H22 in *; rewrite H23 in *; assert (h12 = i12) by (apply (overlapping_eq j1 j2 j3 k1 k2 k3 k12 k23); trivial).\n  assert (h23 = i23) by (hnf in H1; apply H1 with (w := w);\n                         [exists z1 | exists z2 | try_join h2 h3 h23'; equate_join h23 h23'; assertSub h23 w Hsub |\n                                 try_join i2 i3 i23'; equate_join i23 i23'; assertSub i23 w Hsub]; auto).\n  rewrite H24 in *; rewrite H25 in *; apply (overlapping_eq h1 h2 h3 i1 i2 i3 i12 i23); trivial.\nQed.\n\nLemma extract_andp_ocon_ocon_left {A} {JA : Join A} {PA : Perm_alg A} {SA: Sep_alg A}{AG : ageable A} {AA : Age_alg A}:\n  forall (w : A) P Q R S, (P && Q ⊗ R ⊗ S) w -> exists w', P w'.\nProof. repeat intro; destruct_ocon H h; destruct_ocon H2 i; destruct H6; exists i12; trivial. Qed.\n\nLemma ocon_precise_elim  {A}{JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{CA: Canc_alg A}{DA : Disj_alg A}{AG : ageable A} {AA : Age_alg A}:\n  forall P : pred A, precise P -> P ⊗ P = P.\nProof.\n  intros; apply pred_ext; intro w; intro. destruct_ocon H0 h. try_join h2 h3 h23'; equate_join h23 h23'. equate_precise h12 h23.\n  assert (emp h1). assertSub h1 h12 HS. assert (joins h1 h12). exists w; auto. apply (join_sub_joins_identity HS H4).\n  equate_canc h1 h3. apply (join_unit1_e _ _ H4) in H6. subst. auto. hnf. exists (core w), w, (core w), w, w. split.\n  apply core_unit. split. apply join_comm, core_unit. split. apply join_comm, core_unit. split; auto.\nQed.\n\nLemma corable_ocon: forall {A}{JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG : ageable A} {AA : Age_alg A} P Q, corable P -> corable Q -> corable (ocon P Q).\nProof.\n  intros.\n  rewrite corable_spec in H, H0 |- *.\n  unfold ocon.\n  intros.\n  simpl in H2 |- *.\n  destruct H2 as [h1 [h2 [h3 [h12 [h23 [? [? [? [? ?]]]]]]]]].\n  exists (core y), (core y), y, (core y), y.\n  pose proof join_core H2.\n  pose proof join_core (join_comm H2).\n  pose proof join_core H3.\n  pose proof join_core (join_comm H3).\n  pose proof join_core H4.\n  pose proof join_core (join_comm H4).\n  repeat split.\n  + rewrite <- core_idem at 1.\n    apply core_unit.\n  + apply core_unit.\n  + apply core_unit.\n  + apply H with h12; auto.\n    rewrite core_idem.\n    congruence.\n  + apply H0 with h23; auto.\n    congruence.\nQed.\n\nLemma corable_andp_ocon1{A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{agA: ageable A}{AgeA: Age_alg A}:\n   forall P Q R, corable P ->  ocon (P && Q) R = P && (ocon Q R).\nProof.\n  intros.\n  apply pred_ext.\n  + intros h [h1 [h2 [h3 [h12 [h23 [? [? [? [[? ?] ?]]]]]]]]].\n    split.\n    - apply join_core in H2.\n      rewrite corable_spec in H.\n      apply H with h12; [congruence | auto].\n    - exists h1, h2, h3, h12, h23.\n      tauto.\n  + intros h [? [h1 [h2 [h3 [h12 [h23 [? [? [? [? ?]]]]]]]]]].\n    exists h1, h2, h3, h12, h23.\n    rewrite corable_spec in H.\n    repeat split; auto.\n    apply join_core in H3.\n    apply H with h; [congruence | auto].\nQed.\n\n", "meta": {"author": "johndoe20190406", "repo": "RamifyCoq", "sha": "72fb538b40ee8ea641e4bf5fe6cd232756d0929c", "save_path": "github-repos/coq/johndoe20190406-RamifyCoq", "path": "github-repos/coq/johndoe20190406-RamifyCoq/RamifyCoq-72fb538b40ee8ea641e4bf5fe6cd232756d0929c/msl_ext/overlapping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.28424790072960565}}
{"text": "From iris.program_logic Require Export total_weakestpre.\nFrom iris.bi Require Export big_op.\nFrom iris.proofmode Require Import tactics.\nSet Default Proof Using \"Type\".\n\nSection lifting.\nContext `{irisG Λ Σ}.\nImplicit Types v : val Λ.\nImplicit Types e : expr Λ.\nImplicit Types σ : state Λ.\nImplicit Types P Q : iProp Σ.\nImplicit Types Φ : val Λ → iProp Σ.\n\nLemma twp_lift_step s E Φ e1 :\n  to_val e1 = None →\n  (∀ σ1, state_interp σ1 ={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 ∗ WP e2 @ s; E [{ Φ }] ∗ [∗ list] ef ∈ efs, WP ef @ s; ⊤ [{ _, True }])\n  ⊢ WP e1 @ s; E [{ Φ }].\nProof. by rewrite twp_unfold /twp_pre=> ->. Qed.\n\n(** Derived lifting lemmas. *)\nLemma twp_lift_pure_step `{Inhabited (state Λ)} s E Φ e1 :\n  (∀ σ1, reducible e1 σ1) →\n  (∀ σ1 e2 σ2 efs, prim_step e1 σ1 e2 σ2 efs → σ1 = σ2) →\n  (|={E}=> ∀ e2 efs σ, ⌜prim_step e1 σ e2 σ efs⌝ →\n    WP e2 @ s; E [{ Φ }] ∗ [∗ list] ef ∈ efs, WP ef @ s; ⊤ [{ _, True }])\n  ⊢ WP e1 @ s; E [{ Φ }].\nProof.\n  iIntros (Hsafe Hstep) \"H\". iApply twp_lift_step.\n  { eapply reducible_not_val, (Hsafe inhabitant). }\n  iIntros (σ1) \"Hσ\". iMod \"H\".\n  iMod fupd_intro_mask' as \"Hclose\"; last iModIntro; first set_solver.\n  iSplit; [by destruct s|]; iIntros (e2 σ2 efs ?).\n  destruct (Hstep σ1 e2 σ2 efs); auto; subst.\n  iMod \"Hclose\" as \"_\". iFrame \"Hσ\". iApply \"H\"; auto.\nQed.\n\n(* Atomic steps don't need any mask-changing business here, one can\n   use the generic lemmas here. *)\nLemma twp_lift_atomic_step {s E Φ} e1 :\n  to_val e1 = None →\n  (∀ σ1, state_interp σ1 ={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 ∗\n      from_option Φ False (to_val e2) ∗ [∗ list] ef ∈ efs, WP ef @ s; ⊤ [{ _, True }])\n  ⊢ WP e1 @ s; E [{ Φ }].\nProof.\n  iIntros (?) \"H\". iApply (twp_lift_step _ E _ e1)=>//; iIntros (σ1) \"Hσ1\".\n  iMod (\"H\" $! σ1 with \"Hσ1\") as \"[$ H]\".\n  iMod (fupd_intro_mask' E ∅) as \"Hclose\"; first set_solver.\n  iIntros \"!>\" (e2 σ2 efs) \"%\". iMod \"Hclose\" as \"_\".\n  iMod (\"H\" $! e2 σ2 efs with \"[#]\") as \"($ & HΦ & $)\"; first by eauto.\n  destruct (to_val e2) eqn:?; last by iExFalso.\n  iApply twp_value; last done. by apply of_to_val.\nQed.\n\nLemma twp_lift_pure_det_step `{Inhabited (state Λ)} {s E Φ} e1 e2 efs :\n  (∀ σ1, reducible e1 σ1) →\n  (∀ σ1 e2' σ2 efs', prim_step e1 σ1 e2' σ2 efs' → σ1 = σ2 ∧ e2 = e2' ∧ efs = efs')→\n  (|={E}=> WP e2 @ s; E [{ Φ }] ∗ [∗ list] ef ∈ efs, WP ef @ s; ⊤ [{ _, True }])\n  ⊢ WP e1 @ s; E [{ Φ }].\nProof.\n  iIntros (? Hpuredet) \">H\". iApply (twp_lift_pure_step _ E); try done.\n  { by intros; eapply Hpuredet. }\n  by iIntros \"!>\" (e' efs' σ (_&->&->)%Hpuredet).\nQed.\n\nLemma twp_pure_step `{Inhabited (state Λ)} s E e1 e2 φ Φ :\n  PureExec φ e1 e2 →\n  φ →\n  WP e2 @ s; E [{ Φ }] ⊢ WP e1 @ s; E [{ Φ }].\nProof.\n  iIntros ([??] Hφ) \"HWP\".\n  iApply (twp_lift_pure_det_step with \"[HWP]\"); [eauto|naive_solver|auto].\nQed.\nEnd lifting.\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/total_lifting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2842479007296056}}
{"text": "Require Import IL SepIL.\nRequire Import Word Memory.\nImport List.\nRequire Import DepList EqdepClass.\nRequire Import PropX.\nRequire Import Expr SepExpr SepCancel.\nRequire Import Prover ILEnv.\nRequire Import Tactics Reflection.\nRequire Import TacPackIL.\nRequire 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": "csgordon", "repo": "bedrock", "sha": "debab1b6e491b7c5e83bd3b1fe5d0e4c4e728d12", "save_path": "github-repos/coq/csgordon-bedrock", "path": "github-repos/coq/csgordon-bedrock/bedrock-debab1b6e491b7c5e83bd3b1fe5d0e4c4e728d12/src/CancelIL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2842478938921761}}
{"text": "From Undecidability Require Import Hoare.HoareLogic.\nFrom Undecidability.TM Require Import TMTac.\nFrom Undecidability.TM Require Export CodeTM LiftTapes ChangeAlphabet.\n\n\n(* ** Tape/Register Specification *)\n\n(* Register specifications are deep embeded because this makes it\neasier to do computation with the specifications. A tapes\nspecification is a list of assertions about tapes. Each tape may\ncontain a value (optionally with size), or be right. *)\n\nSection RegSpec.\n\n  Variable sig : Type.\n\n  (* Notation without EqType stuff *)\n  Local Notation \"sig '^+'\" := ((boundary + sig) % type) (at level 0) : type_scope.\n\n  Inductive RegSpec : Type :=\n  | Contains {sigX X : Type} {cX : codable sigX X} (r : Retract sigX sig) : X -> RegSpec\n  | Contains_size {sigX X : Type} {cX : codable sigX X} (r : Retract sigX sig) : X -> nat -> RegSpec\n  | Void : RegSpec\n  | Void_size : nat -> RegSpec\n  | Custom : (tape sig^+ -> Prop) -> RegSpec. (* Allows the user to specify the tape manually *)\n\n  (* Semantics *)\n  Definition tspec_single (spec : RegSpec) (t : tape sig^+) : Prop :=\n    match spec with\n    | Contains r x => t ≃(r) x\n    | Contains_size r x s => t ≃(r; s) x\n    | Void => isVoid t\n    | Void_size s => isVoid_size t s\n    | Custom p => p t\n    end.\n\n  Lemma tspec_single_Contains_size_Contains {sigX X : Type} {cX : codable sigX X} (r : Retract sigX sig) (x : X) (s : nat) (t : tape sig^+) :\n    tspec_single (Contains_size r x s) t -> tspec_single (Contains r x) t.\n  Proof. cbn. auto. Qed.\n\n  Definition SpecV n := Vector.t (RegSpec) n.\n  Definition Spec n :Type := list Prop * SpecV n.\n\n  Definition tspec {n : nat} (spec : Spec n) : Assert sig^+ n :=\n    match spec with\n    | (P,spec) => fun (t : tapes sig^+ n) =>\n       List.fold_right and (forall (i : Fin.t n), tspec_single spec[@i] t[@i]) P\n    end.\n\n  Arguments tspec : simpl never.\n\n  (* These rules are needed for abstract lemmas, where Ps is a variable *)\n  Lemma tspecE {n : nat} Ps Pv t:\n  tspec (n:=n) (Ps,Pv) t -> (List.fold_right and True Ps /\\ forall (i : Fin.t n), tspec_single Pv[@i] t[@i]).\n  Proof.\n    cbn. induction Ps;cbn in *. easy. intros []. specialize (IHPs H0) as [H' ?]. split. all:eauto. \n  Qed.\n\n  Lemma tspecI {n : nat} P t:\n  (List.fold_right and True (fst P))\n  -> (forall (i : Fin.t n), tspec_single (snd P)[@i] t[@i])\n  -> tspec (n:=n) P t.\n  Proof.\n    destruct P as (Ps&P). induction Ps;cbn in *. easy. intros H' ?. split. now eapply H';left.\n    eapply IHPs. all:easy. \n  Qed.\n\nLemma tspec_iff {n : nat} Ps Pv t:\n  tspec (n:=n) (Ps,Pv) t <-> (List.fold_right and True Ps /\\ forall (i : Fin.t n), tspec_single Pv[@i] t[@i]).\nProof. split. eapply tspecE;eauto. intros []. eapply tspecI;eauto. Qed. \n\nLemma tspec_Entails {n : nat} Ps Pv:\nEntails (tspec (n:=n) (Ps,Pv)) (fun t => List.fold_right and True Ps /\\ forall (i : Fin.t n), tspec_single Pv[@i] t[@i]).\nProof. apply EntailsI. now setoid_rewrite tspec_iff. Qed.\n\n(* \n  Lemma tspec_pureE {n : nat} Ps Pv v:\n    tspec (n:=n) (Ps,Pv) v -> (forall P, In P Ps -> P).\n  Proof. intros ?%tspecE. easy. Qed. *)\n\n  (* Enrich the specification with spaces *)\n  Definition withSpace_single (P : RegSpec) (size : nat) :=\n    match P with\n    | Contains r x => Contains_size r x size\n    | Void => Void_size size\n    | _ => P\n    end.\n\n  Definition withSpace {n : nat} (P : SpecV n) (spaces : Vector.t nat n) : SpecV n :=\n    Vector.map2 withSpace_single P spaces.\n\n  (* Drop the spaces *)\n  Lemma tspec_single_withSpace_tspec_single (P : RegSpec) (size : nat) t :\n    tspec_single (withSpace_single P size) t -> tspec_single P t.\n  Proof. intros. destruct P; cbn in *; auto. Qed.\n\n  Lemma tspec_withSpace_tspec {n : nat} Q P (s : Vector.t nat n) t :\n    tspec (Q,withSpace P s) t -> tspec (Q,P) t.\n  Proof. unfold withSpace. intros [HP H]%tspecE. apply tspecI. easy. intros i; specialize (H i). simpl_vector in *. eapply tspec_single_withSpace_tspec_single; eauto. Qed.\n\n  (* Invent some dummy spaces *)\n\n  Definition dummy_size (t : tape sig^+) (P : RegSpec) : nat :=\n    match P with\n    | Contains r x => length (left t)\n    | Void => length (tape_local_l t)\n    | _ => 0\n    end.\n\n  Lemma tspec_single_tspec_single_withSpace (P : RegSpec) t :\n    tspec_single P t -> tspec_single (withSpace_single P (dummy_size t P)) t.\n  Proof. intros H. destruct P; cbn in *; eauto. Qed.\n\n\n  Definition dummy_sizes (n : nat) (t : tapes sig^+ n) (P : SpecV n) : Vector.t nat n :=\n     Vector.map2 dummy_size t P.\n\n  Lemma tspec_tspec_withSpace (n : nat) Q (P : SpecV n) t :\n    tspec (Q,P) t -> tspec (Q,withSpace P (dummy_sizes t P)) t.\n  Proof.\n    unfold withSpace, dummy_sizes in *. intros [HP ?]%tspecE. eapply tspecI. cbn in *; auto.\n    intros i; specialize (H i); cbn in *. simpl_vector. now apply tspec_single_tspec_single_withSpace.\n  Qed.\n\n  (*\n  (* Remove the space annotations *)\n  Definition removeSpace_reg (P : RegSpec) :=\n    match P with\n    | Contains_size r x size => Contains r x\n    | Void_size size => Void\n    | _ => P\n    end.\n\n  Lemma tspec_single_removeSpace_reg (P : RegSpec) t :\n    tspec_single P t ->\n    tspec_single (removeSpace_reg P) t.\n  Proof. intros H. destruct P; cbn in *; auto. Qed.\n\n  Definition removeSpace (n : nat) (P : Spec n) :=\n    match P with\n    | SpecVector spec => SpecVector (Vector.map removeSpace_reg spec)\n    | SpecFalse _ => SpecFalse _\n    end.\n\n  Lemma tspec_removeSpace (n : nat) (P : Spec n) t :\n    tspec P t ->\n    tspec (removeSpace P) t.\n  Proof.\n    intros H; destruct P; cbn; auto.\n    intros i; specialize (H i); cbn in *.\n    simpl_vector. eapply tspec_single_removeSpace_reg; eauto.\n  Qed.\n*)\n\nEnd RegSpec.\n\nArguments Custom {sig}.\nArguments Void {sig}.\nArguments Void_size {sig}.\nArguments dummy_sizes : simpl never.\nHint Resolve tspec_single_Contains_size_Contains : core.\n\n\nDeclare Scope spec_scope.\nDelimit Scope spec_scope with spec.\nBind Scope spec_scope with Spec.\nNotation \"'≃≃(' S ')'\" := (tspec S%spec) (at level 0, S at level 200, no associativity, format \"'≃≃(' S ')'\").\nNotation \"'≃≃(' P ',' S ')'\" := (tspec (P%list,S%vector)) (at level 0, P at level 200, S at level 200, no associativity, format \"'≃≃(' P ','  S ')'\").\n\nNotation \"t ≃≃ S\" := (tspec S%spec t) (at level 70, no associativity).\n\nNotation \"≃( I ) x\" := (Contains I x) (at level 70, I at level 200, no associativity, format \"'≃(' I ')'  x\").\nNotation \"≃( I ';' s ) x\" := (Contains_size I s x) (at level 70, I at level 200, s at level 200, no associativity, format \"'≃(' I ';' s ')'  x\").\n\nArguments tspec _%spec _.\n\nFixpoint implList (Ps : list Prop) (Q : Prop) :=\n  match Ps with\n    [] => Q\n  | P::Ps => P -> implList Ps Q \n  end.\nArguments implList !_ _.\n\nInstance fold_right_impl' : Proper (Forall2 Basics.impl --> Basics.impl ==> Basics.impl) (implList).\nProof. intros xs;induction xs;cbn;intros ? H';inv H';cbn. easy. firstorder. Qed.\n\nInstance fold_right_iff : Proper (Forall2 iff ==> iff ==> iff) (implList).\nProof. intros xs;induction xs;cbn;intros ? H';inv H';cbn. easy. firstorder. Qed.\n\nLemma implList_iff P (Ps : list Prop):\n  implList Ps P\n  <-> (List.fold_right and True Ps -> P).\nProof.\n  induction Ps in P|-*;cbn. firstorder. setoid_rewrite IHPs. tauto.\nQed.\n\nLemma implListE P (Ps : list Prop): implList Ps P -> (List.fold_right and True Ps -> P).\nProof. now rewrite implList_iff. Qed.\n\nLemma implListI (P:Prop) (Ps : list Prop): (List.fold_right and True Ps -> P) -> implList Ps P.\nProof. now rewrite implList_iff. Qed.\n\nInstance Forall2_refl X (R: X -> _): Reflexive R -> Reflexive (Forall2 R).\nProof. intros ? xs;induction xs;eauto. Qed. \n\nLemma tspec_introPure (sig: finType) (n : nat) P (Ps : SpecV sig n) Q:\n  implList P (Entails (≃≃([],Ps)) Q)\n  -> Entails (tspec (P,Ps)) Q.\nProof.\n  setoid_rewrite Entails_iff. rewrite implList_iff. intros H ? []%tspecE. eapply H. eassumption. now apply tspecI.\nQed.\n\nLemma tspec_revertPure (sig: finType) (n : nat) (P0:Prop) P (Ps : SpecV sig n) Q:\n  P0\n  -> Entails (tspec (P0::P,Ps)) Q\n  -> Entails (tspec (P,Ps)) Q.\nProof.\n  setoid_rewrite Entails_iff. unfold tspec;cbn. intuition.\nQed.\n\nLemma Triple_introPure (F sig: finType) (n : nat) P (Ps : SpecV sig n) Q (pM : pTM sig^+ F n) :\n  implList P (Triple (≃≃([],Ps)) pM Q)\n  -> Triple (tspec (P,Ps)) pM Q.\nProof.\n  intros. rewrite tspec_Entails. apply Triple_and_pre. cbn in H. now rewrite <- implList_iff.\nQed.\n\nLemma TripleT_introPure (sig F : finType) (n : nat) P (Ps : SpecV sig n) Q k (pM : pTM sig^+ F n) :\n  implList P (TripleT (≃≃([],Ps)) k pM Q)\n  -> TripleT (tspec (P,Ps)) k pM Q.\nProof.\n  intros. rewrite tspec_Entails. apply TripleT_and_pre. cbn in H. now rewrite <- implList_iff.\nQed.\n\n(*\nLemma Triple_SpecFalse {sig : finType} {n : nat} {F : Type} P (pM : pTM sig^+ F n) Q :\n  Triple (≃≃([False],P)) pM Q.\nProof. hnf;cbn. tauto. Qed.\n\nLemma TripleT_SpecFalse {sig : finType} {n : nat} {F : Type} P (k : nat) (pM : pTM sig^+ F n) Q :\n  TripleT (≃≃([False],P)) k pM Q.\nProof. eapply ConsequenceT. 1,3,4:now eauto. hnf;cbn;tauto. Qed.\n\nLemma tspec_not_SpecFalse {sig : Type} {n : nat} (t : tapes (boundary+sig) n) P :\n  t ≃≃ ([False],P) -> False.\nProof. cbn. tauto. Qed.\n\nLemma tspec_not_SpecFalse_withSpace {sig : Type} {n : nat} (t : tapes (boundary+sig) n) P (ss : Vector.t nat n) :\n  t ≃≃  ([False], withSpace P ss) -> False.\nProof. cbn. tauto. Qed.\n\n\nHint Immediate Triple_SpecFalse TripleT_SpecFalse : core.\n*)\n\n\n(* TODO: [SpecFalse] could be defined in the same manner. We could then remove the unhandy [SpecVector] constructor. *)\nDefinition SpecVTrue {sig : Type} {n : nat} : SpecV sig n := Vector.const (Custom (fun _ => True)) n.\n\n(*\nLemma tspec_SpecTrue {sig : finType} {n : nat} (t : tapes sig^+ n) :\n  t ≃≃ SpecTrue.\nProof. cbn. intros i. unfold tspec_single, SpecTrue. cbn. now rewrite Vector.const_nth. Qed.\n\n\nLemma tspec_SpecTrue_withSpace {sig : finType} {n : nat} (t : tapes sig^+ n) (ss : Vector.t nat n) :\n  t ≃≃ withSpace SpecTrue ss.\nProof. cbn. intros i. unfold tspec_single, SpecTrue. now rewrite nth_map2', Vector.const_nth. Qed.\n\nHint Immediate tspec_SpecTrue tspec_SpecTrue_withSpace : core.\n\n\nLemma Triple_SpecTrue {sig : finType} {n : nat} {F : Type} (pM : pTM sig^+ F n) P :\n  Triple P pM (fun _ => tspec SpecTrue).\nProof. eapply Consequence_post. apply Triple_True. auto. Qed.\n\n\n\nHint Extern 4 =>\n     lazymatch goal with\n     | [H : _ ≃≃ SpecFalse |- _] => exfalso; now eapply tspec_not_SpecFalse in H\n     | [H : _ ≃≃ withSpace SpecFalse _ |- _] => exfalso; now eapply tspec_not_SpecFalse_withSpace in H\n     end : core.\n\nGoal forall (t : tapes sigNat^+ 4) P,\n    t ≃≃ ([False],P) -> 3 = 4.\nProof. auto. Qed.\n\n*)\n\nArguments tspec : simpl never.\n\n\n(* TODO: Move to [TM.Code.CodeTM] *)\nDefinition appSize {n : nat} : Vector.t (nat->nat) n -> Vector.t nat n -> Vector.t nat n :=\n  fun fs s => tabulate (fun i => fs[@i] s[@i]).\n\n  \nLemma Triple_RemoveSpace_ex (n : nat) (sig : finType) (F : Type) X\n(P : SpecV sig n) P' (M : pTM sig^+ F n) Q Q' Ctx (fs : _ -> Vector.t (nat->nat) n) :\n  (forall s, Triple (tspec (P',withSpace P s)) M (fun y t => exists x:X, Ctx x (tspec (Q' x y,withSpace (Q x y) (appSize (fs x) s)) t))) -> (* Specifications with size will always have this form *)\n  (forall x, Proper (Basics.impl ==> Basics.impl) (Ctx x)) ->\n  Triple (tspec (P',P)) M (fun y t => exists x, Ctx x (tspec (Q' x y ,Q x y) t)).\nProof.\n  intros HTrip Hctx. setoid_rewrite Triple_iff in HTrip. rewrite Triple_iff. \n  eapply Realise_monotone with\n  (R' := fun tin '(yout, tout) => forall s, tspec (P',withSpace P s) tin\n    -> exists x:X, Ctx x (tspec (Q' x yout,withSpace (Q x yout) (appSize (fs x) s)) tout)).\n  - unfold Triple_Rel, Realise in *. intros tin k outc HLoop. intros s HP.\n    specialize HTrip with (1 := HLoop) (2 := HP) as [x H'']. eexists. eauto.\n  - clear HTrip. intros tin (yout, tout). intros H HP.\n    specialize (H (dummy_sizes tin P)). spec_assert H by now apply tspec_tspec_withSpace.\n    destruct H as (x&H). exists x. eapply Hctx. 2:eassumption.\n    intro H'. now apply tspec_withSpace_tspec in H'.\nQed.\n\nLemma Triple_RemoveSpace (n : nat) (sig : finType) (F : Type) (P : SpecV sig n) P' (M : pTM sig^+ F n) (Q : F -> SpecV sig n) Q' (fs : Vector.t (nat->nat) n) :\n  (forall s, Triple (tspec (P',withSpace P s)) M (fun y => tspec (Q' y,withSpace (Q y) (appSize fs s)))) -> (* Specifications with size will always have this form *)\n  Triple (tspec (P',P)) M (fun y => tspec (Q' y ,Q y)).\nProof.\n  intro HTrip. setoid_rewrite Triple_iff in HTrip. rewrite Triple_iff. \n  eapply Realise_monotone with (R' := fun tin '(yout, tout) => forall s, tspec (P',withSpace P s) tin -> tspec (Q' yout,withSpace (Q yout) (appSize fs s)) tout).\n  - unfold Triple_Rel, Realise in *. intros tin k outc HLoop. intros s HP.\n    now specialize HTrip with (1 := HLoop) (2 := HP).\n  - clear HTrip. intros tin (yout, tout). intros H HP.\n    specialize (H (dummy_sizes tin P)). spec_assert H by now apply tspec_tspec_withSpace.\n    now apply tspec_withSpace_tspec in H.\nQed.\n\nLemma TripleT_RemoveSpace (n : nat) (sig : finType) (F : Type) P' (P : SpecV sig n) (k : nat) (M : pTM sig^+ F n) Q' (Q : F -> SpecV sig n) (fs : Vector.t (nat->nat) n) :\n  (forall s, TripleT (tspec (P',withSpace P s)) k M (fun y => tspec (Q' y,withSpace (Q y) (appSize fs s)))) ->\n  TripleT (tspec (P',P)) k M (fun y => tspec (Q' y,Q y)).\nProof.\n  intros HTrip. split.\n  - eapply Triple_RemoveSpace. intros s. apply HTrip.\n  - setoid_rewrite TripleT_iff in HTrip. \n   eapply TerminatesIn_monotone with (T' := fun tin k' => tspec (P',P) tin /\\ k <= k').\n    + unfold Triple_TRel, TerminatesIn in *. intros tin k' (HP&Hk).\n      specialize (HTrip (dummy_sizes tin P)) as (_&HT).\n      specialize HT with (tin0 := tin) (k0 := k). spec_assert HT as (conf&HLoop).\n      { split. now apply tspec_tspec_withSpace. reflexivity. }\n      exists conf. eapply loop_monotone; eauto.\n    + unfold Triple_TRel. intros tin k' (HP&Hk). eauto.\nQed.\n\n\nInstance fold_right_and : Proper (iff ==> Forall2 iff ==> iff) (fold_right and).\nProof. intros ? ? ? xs;induction xs;cbn;intros ? H';inv H';cbn. easy. firstorder. Qed.\n\nInstance fold_right_and' : Proper (Basics.impl ==> Forall2 iff ==> Basics.impl) (fold_right and).\nProof. intros ? ? ? xs;induction xs;cbn;intros ? H';inv H';cbn. easy. firstorder. Qed.\n\n\n\n\n(* For good reasons, [tspec] will be declared to don't simplify with [cbn]. However, [tspec_single] simplifies with [cbn]. *)\nLemma tspec_solve (sig : Type) (n : nat) (t : tapes (boundary+sig) n) (R : SpecV sig n) P:\nList.fold_right and (forall i, tspec_single R[@i] t[@i]) P ->\n  tspec (P,R) t.\nProof. refine (fun P => P). Qed.\n\n(* [withSpace] does also not simplify; but [withSpace_single] does. *)\nLemma tspec_space_solve (sig : Type) (n : nat) (t : tapes (boundary+sig) n) (R : SpecV sig n) P (ss : Vector.t nat n) :\n  List.fold_right and (forall i, tspec_single (withSpace_single R[@i] ss[@i]) t[@i]) P ->\n  tspec (P,withSpace R ss) t.\nProof. unfold withSpace. intros. apply tspec_solve. simpl_vector. auto. Qed.\n\nLemma tspec_ext (sig : finType) (n : nat) (t : tapes (boundary+sig) n) (P P' : list Prop) (R R' : Vector.t (RegSpec sig) n) :\n  tspec (P',R') t ->\n  implList P' (List.fold_right and True P) ->\n  (forall i, tspec_single R'[@i] t[@i] -> tspec_single R[@i] t[@i]) ->\n  tspec (P,R) t.\nProof.\n  intros [HP H1]%tspecE H1' H2. eapply tspecI.\n  eapply implList_iff. 2:eassumption. eapply fold_right_impl'. 2:reflexivity. 2:eassumption. easy.\n  intros i; specialize (H1 i); specialize (H2 i); eauto.\nQed.\n\nLemma tspec_space_ext (sig : finType) (n : nat) (t : tapes (boundary+sig) n) (P P':list Prop) (R R' : SpecV sig n)\n      (ss ss' : Vector.t nat n) :\n  tspec (P',withSpace R' ss') t ->\n  implList P' (List.fold_right and True P) ->\n  (forall i, tspec_single (withSpace_single R'[@i] ss'[@i]) t[@i] -> tspec_single (withSpace_single R[@i] ss[@i]) t[@i]) ->\n  tspec (P,withSpace R ss) t.\nProof.\n  unfold withSpace. intros [HP H1]%tspecE H1' H2. eapply tspecI.\n  eapply implList_iff. 2:eassumption. eapply fold_right_impl'. 2:reflexivity. 2:eassumption. easy.\n  intros i; specialize (H1 i); specialize (H2 i); eauto.\n  cbn. simpl_vector in *; cbn. eauto.\nQed.\n\n\n\n(* ** Tape Lifting *)\n\n\nSection Lifting.\n\n  Variable (sig : Type).\n\n  Variable (m n : nat).\n\n  (* [P] is the premise of the lifted machine [M@I]. *)\n  Variable (P : @SpecV sig n).\n\n  Variable (I : Vector.t (Fin.t n) m). (* [m<=n] *)\n  Hypothesis (HI : dupfree I).\n\n\n  (* We want to extract from [P] the premise [P'] for [M] *)\n  Definition Downlift : @SpecV sig m :=\n    (select I P).\n\n  Lemma tape_fulfill_Downlift_select P' tp :\n    tspec (P',P) tp ->\n    tspec (P',Downlift) (select I tp).\n  Proof.\n    unfold Downlift. \n    intros [? H]%tspecE.\n    eapply tspecI. easy. \n    intros i;cbn. rewrite !select_nth. easy.\n  Qed.\n\n\n  (* Same specification as in [P] on indices not in [I], but as in [Q] for indices in [I] (lifted).  *)\n  Definition Frame (Q : @SpecV sig m) : @SpecV sig n := fill I P Q.\n\nEnd Lifting.\n\nLemma LiftTapes_Spec_ex (sig : finType) X (F : finType) (m n : nat) (I : Vector.t (Fin.t n) m) \nP' P Q' Q (pM : pTM sig^+ F m) :\n  dupfree I ->\n  Triple (tspec (P',Downlift P I)) pM (fun y t => exists x:X, tspec (Q' x y,Q x y) t) ->\n  Triple (tspec (P',P)) (LiftTapes pM I) (fun y t=> exists x, tspec (Q' x y,Frame P I (Q x y)) t ).\nProof.\n  unfold Frame. rewrite !Triple_iff.\n  intros HDup HTrip. \n  eapply Realise_monotone.\n  { apply LiftTapes_Realise. assumption. apply HTrip. }\n  {\n    intros tin (yout, tout) (H&HInj). cbn -[Downlift tspec] in *.\n    intros HP.\n    spec_assert H by now apply tape_fulfill_Downlift_select.\n    destruct H as [x H].\n    eapply tspecE in H as [H' H]. eapply tspecE in HP as [HP' HP].\n    exists x.\n    eapply tspecI;cbn.\n    { clear - H' HP'. induction P';cbn in *. all:firstorder. }\n    clear H' HP'.\n    hnf. intros j. decide (Vector.In j I) as [HD|HD].\n    - unfold Frame.\n      apply vect_nth_In' in HD as (ij&HD).\n      erewrite fill_correct_nth; eauto.\n      specialize (H ij).\n      now rewrite select_nth, HD in H.\n    - unfold Frame. rewrite fill_not_index; eauto.\n      specialize (HInj j HD). rewrite HInj. now apply HP.\n  }\nQed.\n\n\nLemma LiftTapes_Spec (sig : finType) (F : finType) (m n : nat) (I : Vector.t (Fin.t n) m) P' (P : SpecV sig n) Q' (Q : F -> SpecV sig m) (pM : pTM sig^+ F m) :\n  dupfree I ->\n  Triple (tspec (P',Downlift P I)) pM (fun y => tspec (Q' y,Q y)) ->\n  Triple (tspec (P',P)) (LiftTapes pM I) (fun y => tspec (Q' y,Frame P I (Q y))).\nProof.\n  unfold Frame. rewrite !Triple_iff.\n  intros HDup HTrip. \n  eapply Realise_monotone.\n  { apply LiftTapes_Realise. assumption. apply HTrip. }\n  {\n    intros tin (yout, tout) (H&HInj). cbn -[Downlift tspec] in *.\n    intros HP.\n    spec_assert H by now apply tape_fulfill_Downlift_select.\n    eapply tspecE in H as [H' H]. eapply tspecE in HP as [HP' HP].\n    eapply tspecI;cbn.\n    { clear - H' HP'. induction P';cbn in *. all:firstorder. }\n    clear H' HP'.\n    hnf. intros j. decide (Vector.In j I) as [HD|HD].\n    - unfold Frame.\n      apply vect_nth_In' in HD as (ij&HD).\n      erewrite fill_correct_nth; eauto.\n      specialize (H ij).\n      now rewrite select_nth, HD in H.\n    - unfold Frame. rewrite fill_not_index; eauto.\n      specialize (HInj j HD). rewrite HInj. now apply HP.\n  }\nQed.\n\n\nLemma LiftTapes_Spec_con (sig : finType) (F : finType) (m n : nat) (I : Vector.t (Fin.t n) m) P' (P : SpecV sig n) Q' (Q : F -> SpecV sig m) R' (R : F -> SpecV sig n) (pM : pTM sig^+ F m) :\n  dupfree I ->\n  Triple (tspec (P',Downlift P I)) pM (fun y => tspec (Q' y,Q y)) ->\n  (forall yout, Entails (tspec (Q' yout,Frame P I (Q yout))) (tspec (R' yout,R yout))) ->\n  Triple (tspec (P',P)) (LiftTapes pM I) (fun y => tspec (R' y,R y)).\nProof.\n   intros ? ? <-%asPointwise. eapply LiftTapes_Spec. all:easy.\nQed.\n\n\n(*\n(* Version with disregarded labels *)\nLemma LiftTapes_Spec' (sig : finType) (F : Type) (m n : nat) (I : Vector.t (Fin.t n) m) (P : Spec sig n) (Q : Spec sig m) (pM : pTM sig^+ F m) :\n  dupfree I ->\n  Triple (tspec (Downlift I P)) pM (fun y => tspec Q) ->\n  Triple (tspec P) (LiftTapes pM  I) (fun _ => tspec (Frame I P Q)).\nProof. apply LiftTapes_Spec. Qed.\n*)\n\n\nLemma LiftTapes_SpecT (sig F : finType)(m n : nat) (I : Vector.t (Fin.t n) m) P' (P : SpecV sig n) (k : nat) Q' (Q : F -> SpecV sig m) (pM : pTM sig^+ F m) :\n  dupfree I ->\n  TripleT (tspec (P',Downlift P I)) k pM (fun y => tspec (Q' y,Q y)) ->\n  TripleT (tspec (P',P)) k (LiftTapes pM  I) (fun y => tspec (Q' y,Frame P I (Q y))).\nProof.\n  intros HDup (HTrip&HTrip').\n  split.\n  - apply LiftTapes_Spec; eauto.\n  - eapply TerminatesIn_monotone.\n    + apply LiftTapes_Terminates; eauto.\n    + intros tin k' (H&H'). split; auto.\n      now apply tape_fulfill_Downlift_select.\nQed.\n\n\nLemma LiftTapes_SpecT_con (sig : finType) (F : finType) (m n : nat) (I : Vector.t (Fin.t n) m)\nP' (P : SpecV sig n) Q' (Q : F -> SpecV sig m) R' (R : F -> SpecV sig n)\n      (k : nat) (pM : pTM sig^+ F m) :\n  dupfree I ->\n  TripleT (tspec (P',Downlift P I)) k pM (fun y => tspec (Q' y,Q y)) ->\n  (forall yout, Entails (tspec (Q' yout,Frame P I (Q yout))) (tspec (R' yout,R yout))) ->\n  TripleT (tspec (P',P)) k (LiftTapes pM  I) (fun y => tspec (R' y,R y)).\nProof. eauto using ConsequenceT_post, LiftTapes_SpecT. Qed.\n\n\n(* Swap [Downlift] and [withSpace] *)\nLemma Downlift_withSpace (m n : nat) (sig : Type) (P : SpecV sig n) (I : Vector.t (Fin.t n) m) (ss : Vector.t nat n) :\n  Downlift (withSpace P ss) I = withSpace (Downlift P I) (select I ss).\nProof.\n  unfold withSpace, Downlift.\n  eapply VectorSpec.eq_nth_iff; intros ? ? ->.\n  simpl_vector. rewrite !select_nth. simpl_vector. reflexivity.\nQed.\n\nLemma tspec_Downlift_withSpace (m n : nat) (sig : Type) P' (P : SpecV sig n) (I : Vector.t (Fin.t n) m) (ss : Vector.t nat n):\n  Entails ≃≃( P', Downlift (sig:=sig) (m:=m) (n:=n) (withSpace P ss) I) ≃≃( P',withSpace (Downlift P I) (select I ss)).\nProof. rewrite Entails_iff. intros H. erewrite <- Downlift_withSpace; eauto. Qed.\n\nLemma Triple_Downlift_withSpace (m n : nat) (sig : finType) P' (P : SpecV sig n) (I : Vector.t (Fin.t n) m) (ss : Vector.t nat n)\n      (F : Type) (M : pTM sig^+ F m) (Q : F -> Assert sig^+ m) :\n  Triple (tspec (P',withSpace (Downlift P I) (select I ss))) M Q ->\n  Triple (tspec (P',Downlift (withSpace P ss) I)) M Q.\nProof. now rewrite <- tspec_Downlift_withSpace. Qed.\n\nLemma TripleT_Downlift_withSpace (m n : nat) (sig : finType) P' (P : SpecV sig n) (I : Vector.t (Fin.t n) m) (ss : Vector.t nat n)\n      (F : Type) (k : nat) (M : pTM sig^+ F m) (Q : F -> Assert sig^+ m) :\n  TripleT (tspec (P',withSpace (Downlift P I) (select I ss))) k M Q ->\n  TripleT (tspec (P',Downlift (withSpace P ss) I)) k M Q.\nProof. now rewrite <- tspec_Downlift_withSpace. Qed.\n\n\n(* TODO: Why is this needed? If needed: Move into base *)\nInstance dec_ex_fin (n : nat) (P : Fin.t n -> Prop) (decP: forall (i : Fin.t n), dec (P i)) : dec (exists (i : Fin.t n), P i).\nProof.\n  induction n.\n  - right. intros (i&?). destruct_fin i.\n  - decide (P Fin0).\n    + left. eauto.\n    + specialize (IHn (fun i => P (Fin.FS i))). spec_assert IHn as [IH|IH] by eauto.\n      * left. destruct IH as (i&IH). exists (Fin.FS i). eauto.\n      * right. intros (j&H). pose proof (fin_destruct_S j) as [(j'&->) | ->]; eauto.\nQed.\n\n\n(* Move [withFrame] out of [Frame] *)\nLemma Frame_withSpace (m n : nat) (sig : Type) (P : SpecV sig n) (P' : SpecV sig m) (I : Vector.t (Fin.t n) m) (ss : Vector.t nat n) (ss' : Vector.t nat m) :\n  dupfree I ->\n  Frame (withSpace P ss) I (withSpace P' ss') = withSpace (Frame P I P') (fill I ss ss').\nProof.\n  intros Hdup. unfold Frame,withSpace. \n  eapply VectorSpec.eq_nth_iff; intros ? i ->.\n  simpl_vector.\n  decide (exists j, I[@j]=i) as [(j&Hj)|Hj].\n  + erewrite !fill_correct_nth by eauto. now simpl_vector.\n  + assert (not_index I i).\n    { hnf. intros (k&<-) % vect_nth_In'. contradict Hj. eauto. }\n    erewrite !fill_not_index by eauto. now simpl_vector.\nQed.\n\n(*)\nLemma tspec_Frame_withSpace\n      (m n : nat) (sig : Type) (P : Spec sig n) (P' : Spec sig m) (I : Vector.t (Fin.t n) m) (ss : Vector.t nat n) (ss' : Vector.t nat m)\n      (t : tapes (boundary+sig) n) :\n  t ≃≃ Frame (withSpace P ss) I (withSpace P' ss') ->\n  dupfree I ->\n  t ≃≃ withSpace (Frame P I P') (fill I ss ss').\nProof. intros H1 H2. erewrite <- Frame_withSpace; eauto. Qed.\n*)\n\nLemma tspec_Frame_withSpace'\n      (m n : nat) (I : Vector.t (Fin.t n) m):\n  dupfree I -> forall (sig : Type) Q (P : SpecV sig n) (P' : SpecV sig m) (ss : Vector.t nat n) (ss' : Vector.t nat m),\n  Entails ≃≃( Q , Frame (withSpace P ss) I (withSpace P' ss')) ≃≃( Q, withSpace (Frame P I P') (fill I ss ss')).\nProof. intros H1 **. erewrite <- Frame_withSpace; eauto. Qed.\n\n(*\nLemma Triple_Frame_withSpace \n      (m n : nat) (sig : finType) (P : Spec sig n) (P' : Spec sig m)(I : Vector.t (Fin.t n) m) (ss : Vector.t nat n) (ss' : Vector.t nat m)\n      (F : Type) (M : pTM sig^+ F n) (Q : F -> Assert sig^+ n) :\n  dupfree I ->\n  Triple (tspec (withSpace (Frame P I P') (fill I ss ss')))    M Q ->\n  Triple (tspec (Frame (withSpace P ss) I (withSpace P' ss'))) M Q.\nProof. intros H1 H2. erewrite Frame_withSpace; eauto. Qed.\n\nLemma TripleT_Frame_withSpace \n      (m n : nat) (sig : finType) (P : Spec sig n) (P' : Spec sig m)(I : Vector.t (Fin.t n) m) (ss : Vector.t nat n) (ss' : Vector.t nat m)\n      (F : Type) (k : nat) (M : pTM sig^+ F n) (Q : F -> Assert sig^+ n) :\n  dupfree I ->\n  TripleT (tspec (withSpace (Frame P I P') (fill I ss ss')))    k M Q ->\n  TripleT (tspec (Frame (withSpace P ss) I (withSpace P' ss'))) k M Q.\nProof. intros H1 H2. erewrite Frame_withSpace; eauto. Qed.\n\n*)\n\n(* Versions of [LiftTapes] with space *)\n\nLemma LiftTapes_Spec_space (sig F : finType) (m n : nat) (I : Vector.t (Fin.t n) m) P' (P : SpecV sig n) Q' (Q : F -> SpecV sig m) (pM : pTM sig^+ F m)\n     (ss : Vector.t nat n) (ss' : Vector.t nat m) :\n  dupfree I ->\n  Triple (tspec (P',withSpace (Downlift P I) (select I ss))) pM (fun y => tspec (Q' y,withSpace (Q y) ss')) ->\n  Triple (tspec (P',withSpace P ss)) (LiftTapes pM  I) (fun y => tspec (Q' y,withSpace (Frame P I (Q y)) (fill I ss ss'))).\nProof.\n  intros H1 H2. rewrite <- Downlift_withSpace in H2. apply LiftTapes_Spec in H2. setoid_rewrite tspec_Frame_withSpace' in H2. all:eauto.\nQed.\n\nLemma LiftTapes_SpecT_space (sig F : finType) (m n : nat) (I : Vector.t (Fin.t n) m) P' (P : SpecV sig n) (k : nat) Q' (Q : F -> SpecV sig m) (pM : pTM sig^+ F m)\n     (ss : Vector.t nat n) (ss' : Vector.t nat m) :\n  dupfree I ->\n  TripleT (tspec (P',withSpace (Downlift P I) (select I ss))) k pM (fun y => tspec (Q' y,withSpace (Q y) ss')) ->\n  TripleT (tspec (P',withSpace P ss)) k (LiftTapes pM  I) (fun y => tspec (Q' y,withSpace (Frame P I (Q y)) (fill I ss ss'))).\nProof.\n  intros H1 H2. rewrite <- Downlift_withSpace in H2. apply LiftTapes_SpecT in H2. setoid_rewrite tspec_Frame_withSpace' in H2. all:eauto.\nQed.\n\n\nLemma LiftTapes_Spec_space_con (sig : finType) (F : finType) (m n : nat) (I : Vector.t (Fin.t n) m)\n      P' (P : SpecV sig n) Q' (Q : F -> SpecV sig m) R' (R : F -> SpecV sig n) (ss : Vector.t nat n) (ss' : Vector.t nat m) (ss'' : Vector.t nat n)\n      (pM : pTM sig^+ F m) :\n  dupfree I ->\n  Triple (tspec (P',withSpace (Downlift P I) (select I ss))) pM (fun y => tspec (Q' y,withSpace (Q y) ss')) ->\n  (forall yout, Entails (tspec (Q' yout,withSpace (Frame P I (Q yout)) (fill I ss ss'))) (tspec (R' yout,withSpace (R yout) ss''))) ->\n  Triple (tspec (P',withSpace P ss)) (LiftTapes pM  I) (fun y => tspec (R' y,withSpace (R y) ss'')).\nProof.\n  intros H1 H2 <-%asPointwise. rewrite <- Downlift_withSpace in H2. apply LiftTapes_Spec in H2. \n  setoid_rewrite tspec_Frame_withSpace' in H2. all:easy.\nQed.\n\nLemma LiftTapes_SpecT_space_con (sig : finType) (F : finType) (m n : nat) (I : Vector.t (Fin.t n) m)\n      P' (P : SpecV sig n) Q' (Q : F -> SpecV sig m) R' (R : F -> SpecV sig n) (ss : Vector.t nat n) (ss' : Vector.t nat m) (ss'' : Vector.t nat n)\n      (k : nat) (pM : pTM sig^+ F m) :\n  dupfree I ->\n  TripleT (tspec (P',withSpace (Downlift P I) (select I ss))) k pM (fun y => tspec (Q' y,withSpace (Q y) ss')) ->\n  (forall yout, Entails (tspec (Q' yout,withSpace (Frame P I (Q yout)) (fill I ss ss'))) (tspec (R' yout,withSpace (R yout) ss''))) ->\n  TripleT (tspec (P',withSpace P ss)) k (LiftTapes pM  I) (fun y => tspec (R' y,withSpace (R y) ss'')).\nProof.\n  intros H1 H2 <-%asPointwise. rewrite <- Downlift_withSpace in H2. apply LiftTapes_SpecT in H2. \n  setoid_rewrite tspec_Frame_withSpace' in H2. all:easy.\nQed.\n\n\n\n\n\n\n\n(* ** Alphabet Lifting *)\n\n(* Alphabet lifting is easy. We only have to add the retraction to the specification. *)\n(* We could also implement this for abstract hoare triples, like in the below rule for [Custom]. *)\n\nSection AlphabetLifting.\n\n  Variable (sig tau : Type).\n  Variable (retr : Retract sig tau).\n\n  Definition LiftSpec_single (T : RegSpec sig) : RegSpec tau :=\n    match T with\n    | Contains r x => Contains (ComposeRetract retr r) x\n    | Contains_size r x s => Contains_size (ComposeRetract retr r) x s\n    | Void => Void\n    | Void_size s => Void_size s\n    | Custom p => Custom (fun t => p (surjectTape (Retr_g) (inl UNKNOWN) t))\n    end.\n\n  Variable (n : nat).\n\n  Definition LiftSpec (T : SpecV sig n) : SpecV tau n :=\n    Vector.map LiftSpec_single T.\n\n  Lemma LiftSpec_surjectTape_tspec_single t T :\n    tspec_single (LiftSpec_single T) t ->\n    tspec_single T (surjectTape Retr_g (inl UNKNOWN) t).\n  Proof. destruct T; cbn in *; intros; simpl_surject; eauto. Qed.\n\n  Lemma LiftSpec_surjectTape_tspec_single' t T :\n    tspec_single T (surjectTape Retr_g (inl UNKNOWN) t) ->\n    tspec_single (LiftSpec_single T) t.\n  Proof. destruct T; cbn in *; intros; simpl_surject; eauto. Qed.\n\n  Lemma LiftSpec_surjectTapes_tspec tin P' P :\n    tin ≃≃ (P', LiftSpec P) ->\n    surjectTapes Retr_g (inl UNKNOWN) tin ≃≃ (P',P).\n  Proof.\n    intros (H'&H)%tspecE. eapply tspecI. easy. \n    intros i; specialize (H i); cbn. unfold LiftSpec in *.\n    simpl_tape in *. now apply LiftSpec_surjectTape_tspec_single.\n  Qed.\n\n  Lemma LiftSpec_surjectTapes_tspec' tin P P':\n    surjectTapes Retr_g (inl UNKNOWN) tin ≃≃ (P',P) ->\n    tin ≃≃ (P',LiftSpec P).\n  Proof.\n    intros (H'&H)%tspecE. eapply tspecI. easy. unfold LiftSpec in *.\n    intros i; specialize (H i); cbn.\n    simpl_tape in *. now apply LiftSpec_surjectTape_tspec_single'.\n  Qed.\n\n  \nEnd AlphabetLifting.\n\n\nLemma LiftSpec_withSpace_single (sig tau : Type) (I : Retract sig tau) (P : RegSpec sig) (s : nat) :\n  LiftSpec_single I (withSpace_single P s) = withSpace_single (LiftSpec_single I P) s.\nProof. destruct P; cbn; eauto. Qed.\n\nLemma LiftSpec_withSpace (sig tau : Type) (n : nat) (I : Retract sig tau) (P : SpecV sig n) (ss : Vector.t nat n) :\n  LiftSpec I (withSpace P ss) = withSpace (LiftSpec I P) ss.\nProof.\n  eapply VectorSpec.eq_nth_iff; intros ? ? ->. unfold LiftSpec, withSpace.\n  simpl_vector. apply LiftSpec_withSpace_single.\nQed.\n(*\nLemma tspec_LiftSpec_withSpace (sig tau : Type) (n : nat) (I : Retract sig tau) P' (P : SpecV sig n) (ss : Vector.t nat n):\n  Entails ≃≃( P',LiftSpec I (withSpace P ss)) ≃≃( P', withSpace (LiftSpec I P) ss).\nProof. now rewrite LiftSpec_withSpace. Qed.\n\nLemma tspec_LiftSpec_withSpace' (sig tau : Type) (n : nat) (I : Retract sig tau) (P : Spec sig n) (ss : Vector.t nat n):\n  Entails ≃≃( withSpace (LiftSpec I P) ss) ≃≃( LiftSpec I (withSpace P ss)).\nProof. now rewrite LiftSpec_withSpace. Qed.\n\nLemma Triple_LiftSpec_withSpace (sig tau : finType) (n : nat) (I : Retract sig tau) (P : Spec sig n) (ss : Vector.t nat n)\n      (F : Type) (M : pTM tau^+ F n) (Q : F -> Assert (boundary+tau) n) :\n  Triple (tspec (withSpace (LiftSpec I P) ss)) M Q ->\n  Triple (tspec (LiftSpec I (withSpace P ss))) M Q.\nProof. now rewrite LiftSpec_withSpace. Qed.\n\nLemma TripleT_LiftSpec_withSpace (sig tau : finType) (n : nat) (I : Retract sig tau) (P : Spec sig n) (ss : Vector.t nat n)\n      (F : Type) (k : nat) (M : pTM tau^+ F n) (Q : F -> Assert (boundary+tau) n) :\n  TripleT (tspec (withSpace (LiftSpec I P) ss)) k M Q ->\n  TripleT (tspec (LiftSpec I (withSpace P ss))) k M Q.\nProof. now rewrite LiftSpec_withSpace. Qed.\n*)\n\n\nSection AlphabetLifting'.\n\n  Variable (sig tau : finType) (n : nat).\n  Variable (retr : Retract sig tau).\n\n  \n  Lemma ChangeAlphabet_Spec_ex (F : finType) X P' (Ctx : X -> Prop -> Prop) (P : SpecV sig n) (pM : pTM sig^+ F n) Q' (Q : X -> F -> SpecV sig n) :\n    Triple (tspec (P',P)) pM (fun y t => exists x:X, Ctx x (tspec (Q' x y,Q x y) t)) ->\n    (forall x, Proper (Basics.impl ==> Basics.impl) (Ctx x)) ->\n    Triple (tspec (P',LiftSpec retr P)) (ChangeAlphabet pM retr)\n      (fun yout t => exists x, Ctx x (tspec (Q' x yout,LiftSpec retr (Q x yout)) t)).\n  Proof.\n    rewrite !Triple_iff. intros HTrip HCtx. eapply Realise_monotone.\n    - TM_Correct. eassumption.\n    - intros tin (yout, tout) H Henc. cbn in *.\n      spec_assert H by now apply LiftSpec_surjectTapes_tspec.\n      destruct H as (x&H). exists x. cbv in HCtx. eapply HCtx. 2:apply H.\n      now apply LiftSpec_surjectTapes_tspec'.\n  Qed.\n\n  Lemma ChangeAlphabet_Spec (F : finType) P' (P : SpecV sig n) (pM : pTM sig^+ F n) Q' (Q : F -> SpecV sig n) :\n    Triple (tspec (P',P)) pM (fun yout => tspec (Q' yout,Q yout)) ->\n    Triple (tspec (P',LiftSpec retr P)) (ChangeAlphabet pM retr) (fun yout => tspec (Q' yout,LiftSpec retr (Q yout))).\n  Proof.\n    rewrite !Triple_iff. intros HTrip. eapply Realise_monotone.\n    - TM_Correct. eassumption.\n    - intros tin (yout, tout) H Henc. cbn in *.\n      spec_assert H by now apply LiftSpec_surjectTapes_tspec.\n      now apply LiftSpec_surjectTapes_tspec'.\n  Qed.\n\n  Lemma ChangeAlphabet_SpecT (F : finType) P' (P : SpecV sig n) (k : nat) (pM : pTM sig^+ F n) Q' (Q : F -> SpecV sig n) :\n    TripleT (tspec (P',P)) k pM (fun yout => tspec (Q' yout, Q yout)) ->\n    TripleT (tspec (P',LiftSpec retr P)) k (ChangeAlphabet pM retr) (fun yout => tspec (Q' yout,LiftSpec retr (Q yout))).\n  Proof.\n    intros HTrip. split.\n    { apply ChangeAlphabet_Spec. eapply TripleT_Triple; eauto. }\n    {\n      eapply TerminatesIn_monotone.\n      - TM_Correct. apply HTrip.\n      - unfold Triple_TRel. intros tin k' (H&Hk). cbn. split; auto.\n        now apply LiftSpec_surjectTapes_tspec.\n    }\n  Qed.\n\n\n\n  (* We always have to use at least [Consequence_pre], because the premise will never match. *)\n\n  Lemma ChangeAlphabet_Spec_pre_post (F : finType)\n        P0 (P : SpecV sig n) (P' : SpecV tau n)\n        (pM : pTM sig^+ F n)\n        Q0 (Q : F -> SpecV sig n) (Q' : F -> SpecV tau n) :\n    Triple (tspec (P0,P)) pM (fun yout => tspec (Q0 yout, Q yout) ) ->\n    (Entails ≃≃( P0,P') ≃≃( P0,LiftSpec retr P)) ->\n    (forall yout, Entails ≃≃( Q0 yout, LiftSpec retr (Q yout)) ≃≃( (Q0 yout,Q' yout))) ->\n    Triple (tspec (P0, P')) (ChangeAlphabet pM retr) (fun yout => tspec (Q0 yout, Q' yout)).\n  Proof.\n    intros H1 H2 H3.\n    eapply Consequence.\n    - apply ChangeAlphabet_Spec. apply H1.\n    - apply H2.\n    - apply H3.\n  Qed.\n\n  Lemma ChangeAlphabet_SpecT_pre_post (F : finType)\n        P0 (P : SpecV sig n) (P' : SpecV tau n)\n        (k : nat) (pM : pTM sig^+ F n)\n        Q0 (Q : F -> SpecV sig n) (Q' : F -> SpecV tau n) :\n    TripleT (tspec (P0,P)) k pM (fun yout => tspec (Q0 yout, Q yout) ) ->\n    (Entails ≃≃( P0,P') ≃≃( P0,LiftSpec retr P)) ->\n    (forall yout, Entails ≃≃( Q0 yout, LiftSpec retr (Q yout)) ≃≃( (Q0 yout,Q' yout))) ->\n    TripleT (tspec (P0, P')) k (ChangeAlphabet pM retr) (fun yout => tspec (Q0 yout, Q' yout)).\n  Proof.\n    intros H1 H2 H3.\n    eapply ConsequenceT.\n    - apply ChangeAlphabet_SpecT. apply H1.\n    - apply H2.\n    - apply H3.\n    - reflexivity.\n  Qed.\n\n  \n  Lemma ChangeAlphabet_Spec_pre (F : finType)\n        P0 (P : SpecV sig n) (P' : SpecV tau n)\n        (pM : pTM sig^+ F n)\n        Q0 (Q : F -> SpecV sig n) :\n    Triple (tspec (P0,P)) pM (fun yout => tspec (Q0 yout, Q yout)) ->\n    (Entails ≃≃( P0,P') ≃≃( P0, LiftSpec retr P)) ->\n    Triple (tspec (P0,P')) (ChangeAlphabet pM retr) (fun yout => tspec (Q0 yout,LiftSpec retr (Q yout))).\n  Proof.\n    intros H1 H2.\n    eapply Consequence.\n    - apply ChangeAlphabet_Spec. apply H1.\n    - apply H2.\n    - eauto.\n  Qed.\n\n  Lemma ChangeAlphabet_SpecT_pre (F : finType)\n        P0 (P : SpecV sig n) (P' : SpecV tau n)\n        (k : nat) (pM : pTM sig^+ F n)\n        Q0 (Q : F -> SpecV sig n) :\n    TripleT (tspec (P0,P)) k pM (fun yout => tspec (Q0 yout, Q yout)) ->\n    (Entails ≃≃( P0, P') ≃≃( P0,LiftSpec retr P)) ->\n    TripleT (tspec (P0,P')) k (ChangeAlphabet pM retr) (fun yout => tspec (Q0 yout,LiftSpec retr (Q yout))).\n  Proof.\n    intros H1 H2.\n    eapply ConsequenceT.\n    - apply ChangeAlphabet_SpecT. apply H1.\n    - apply H2.\n    - eauto.\n    - reflexivity.\n  Qed.\n\n\n\n  (* Versions with space *)\n\n  Lemma ChangeAlphabet_Spec_space_pre_post (F : finType)\n        P0 (P : SpecV sig n) (P' : SpecV tau n)\n        (pM : pTM sig^+ F n)\n        Q0 (Q : F -> SpecV sig n) (Q' : F -> SpecV tau n)\n        (ss ss' : Vector.t nat n) :\n    Triple (tspec (P0,withSpace P ss)) pM (fun yout => tspec (Q0 yout,withSpace (Q yout) ss')) ->\n    (Entails ≃≃( P0, withSpace P' ss) ≃≃( P0, withSpace (LiftSpec retr P) ss)) ->\n    (forall yout, Entails ≃≃( Q0 yout, withSpace (LiftSpec retr (Q yout)) ss') (tspec (Q0 yout,withSpace (Q' yout) ss'))) ->\n    Triple (tspec (P0,withSpace P' ss)) (ChangeAlphabet pM retr) (fun yout => tspec (Q0 yout, withSpace (Q' yout) ss')).\n  Proof.\n    intros H1 H2 H3.\n    eapply Consequence.\n    - apply ChangeAlphabet_Spec. apply H1.\n    - rewrite LiftSpec_withSpace. apply H2.\n    - setoid_rewrite Entails_iff. cbn. intros. rewrite LiftSpec_withSpace in H. now apply H3.\n  Qed.\n\n  Lemma ChangeAlphabet_SpecT_space_pre_post (F : finType)\n        P0 (P : SpecV sig n) (P' : SpecV tau n)\n        (k : nat) (pM : pTM sig^+ F n)\n        Q0  (Q : F -> SpecV sig n) (Q' : F -> SpecV tau n)\n        (ss ss' : Vector.t nat n) :\n        TripleT (tspec (P0,withSpace P ss)) k pM (fun yout => tspec (Q0 yout,withSpace (Q yout) ss')) ->\n        (Entails ≃≃( P0, withSpace P' ss) ≃≃( P0, withSpace (LiftSpec retr P) ss)) ->\n        (forall yout, Entails ≃≃( Q0 yout, withSpace (LiftSpec retr (Q yout)) ss') (tspec (Q0 yout,withSpace (Q' yout) ss'))) ->\n        TripleT (tspec (P0,withSpace P' ss)) k (ChangeAlphabet pM retr) (fun yout => tspec (Q0 yout, withSpace (Q' yout) ss')).\n  Proof.\n    intros H1 H2 H3.\n    eapply ConsequenceT.\n    - apply ChangeAlphabet_SpecT. apply H1.\n    - rewrite LiftSpec_withSpace. apply H2.\n    - setoid_rewrite Entails_iff.  cbn. intros. rewrite LiftSpec_withSpace in H. now apply H3.\n    - reflexivity.\n  Qed.\n\n  \n\n  Lemma ChangeAlphabet_Spec_space_pre (F : finType)\n        P0 (P : SpecV sig n) (P' : SpecV tau n)\n        (pM : pTM sig^+ F n)\n        Q0 (Q : F -> SpecV sig n)\n        (ss ss' : Vector.t nat n) :\n    Triple (tspec (P0,withSpace P ss)) pM (fun yout => tspec (Q0 yout,withSpace (Q yout) ss')) ->\n    Entails ≃≃( P0, withSpace P' ss) ≃≃( P0, withSpace (LiftSpec retr P) ss) ->\n    Triple (tspec (P0, withSpace P' ss)) (ChangeAlphabet pM retr) (fun yout => tspec (Q0 yout, withSpace (LiftSpec retr (Q yout)) ss')).\n  Proof.\n    intros H1 H2.\n    eapply Consequence.\n    - apply ChangeAlphabet_Spec. apply H1.\n    - rewrite LiftSpec_withSpace. apply H2.\n    - setoid_rewrite Entails_iff. cbn. intros. rewrite LiftSpec_withSpace in H. now apply H.\n  Qed.\n\n  Lemma ChangeAlphabet_SpecT_space_pre (F : finType)\n        P0 (P : SpecV sig n) (P' : SpecV tau n)\n        (k : nat) (pM : pTM sig^+ F n)\n        Q0 (Q : F -> SpecV sig n)\n        (ss ss' : Vector.t nat n) :\n    TripleT (tspec (P0,withSpace P ss)) k pM (fun yout => tspec (Q0 yout, withSpace (Q yout) ss')) ->\n    Entails ≃≃( P0, withSpace P' ss) ≃≃( P0, withSpace (LiftSpec retr P) ss) ->\n    TripleT (tspec (P0, withSpace P' ss)) k (ChangeAlphabet pM retr) (fun yout => tspec (Q0 yout,withSpace (LiftSpec retr (Q yout)) ss')).\n  Proof.\n    intros H1 H2.\n    eapply ConsequenceT.\n    - apply ChangeAlphabet_SpecT. apply H1.\n    - rewrite LiftSpec_withSpace. apply H2.\n    - setoid_rewrite Entails_iff. cbn. intros. rewrite LiftSpec_withSpace in H. now apply H.\n    - reflexivity.\n  Qed.\n  \nEnd AlphabetLifting'.\n\n\n(*\nLemma ChangeAlphabet_Rel (sig tau : finType) (I : Retract sig tau) (n : nat) (F : finType) (M : pTM sig^+ F n) (R : pRel sig^+ F n) (R' : pRel tau^+ F n) :\n  M ⊨ R ->\n  (forall (tin : tapes tau^+ n) yout tout, R (surjectTapes Retr_g (inl UNKNOWN) tin) (yout, surjectTapes Retr_g (inl UNKNOWN) tout) -> R' tin (yout, tout)) ->\n  M ⇑ I ⊨ R'.\nProof.\n  intros HRel H.\n  eapply Realise_monotone.\n  - TM_Correct. apply HRel.\n  - intros tin (yout, tout) H'. cbn in *. eauto.\nQed.\n*)\n\n\n\n\n\n\n(* We always want to keep [withSpace] right after [tspec] in the assertions. *)\nGlobal Arguments withSpace : simpl never.\n\n\n(*\nDefinition coerceSpec {sig n} V : Spec sig n := ([],V).\nCoercion coerceSpec : SpecV >-> Spec.\n*)\n\n(* TODO: remove legacy *)\nNotation \"'SpecFalse'\" := ([False],_): spec_scope.\n(*Notation SpecVector P := (coerceSpec P) (only parsing). *)\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/TM/Hoare/HoareRegister.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.2842363671782047}}
{"text": "\n(*\npredict-max-ctx-size-ip-pr-muDot:\n\nIdea: Judgment max_ctx_subtyp is given an env G and two types T1 and T2, and it predicts\nthe max size of the env in the subtype derivation [G |- T1 <: T2].\nThen we can use this upper bound on the env size as a termination measure in\nnarrowing/exp_preserves_sub.\n\nT1 = { z =>\n  List: bot .. { y =>\n    h: Int\n    t: z.List\n  }\n  l: z.List\n}\n\nis subtype of\n\nT2 = { z =>\n  List: bot .. { y =>\n    h: Int\n    t: z.List\n  }\n  // can \"inline\" z.List as many times as we want\n  // --> env grows arbitrarily (is this a problem?)\n  l: { l =>\n    h: Int\n    t: z.List\n  }\n}\n\n*)\n\nSet Implicit Arguments.\n\n(* CoqIDE users: Run open.sh (in ./ln) to start coqide, then open this file. *)\nRequire Import LibLN.\n\n\n(* ###################################################################### *)\n(* ###################################################################### *)\n(** * Definitions *)\n\n(* ###################################################################### *)\n(** ** Syntax *)\n\n(** If it's clear whether a type, field or method is meant, we use nat, \n    if not, we use label: *)\nInductive label: Type :=\n| label_typ: nat -> label\n| label_fld: nat -> label\n| label_mtd: nat -> label.\n\nInductive avar : Type :=\n  | avar_b : nat -> avar  (* bound var (de Bruijn index) *)\n  | avar_f : var -> avar. (* free var (\"name\"), refers to tenv or venv *)\n\nInductive pth : Type :=\n  | pth_var : avar -> pth.\n\nInductive typ : Type :=\n  | typ_top  : typ\n  | typ_bot  : typ\n  | typ_bind : decs -> typ (* { z => decs } *)\n  | typ_sel : pth -> label -> typ (* p.L *)\nwith dec : Type :=\n  | dec_typ  : typ -> typ -> dec\n  | dec_fld  : typ -> dec\n  | dec_mtd : typ -> typ -> dec\nwith decs : Type :=\n  | decs_nil : decs\n  | decs_cons : nat -> dec -> decs -> decs.\n\nInductive trm : Type :=\n  | trm_var  : avar -> trm\n  | trm_new  : decs -> defs -> trm\n  | trm_sel  : trm -> nat -> trm\n  | trm_call : trm -> nat -> trm -> trm\nwith def : Type :=\n  | def_typ : def (* just a placeholder *)\n  | def_fld : avar -> def (* cannot have term here, need to assign first *)\n  | def_mtd : trm -> def (* one nameless argument *)\nwith defs : Type :=\n  | defs_nil : defs\n  | defs_cons : nat -> def -> defs -> defs.\n\nInductive obj : Type :=\n  | object : decs -> defs -> obj. (* { z => Ds }{ z => ds } *)\n\n(** *** Typing environment (\"Gamma\") *)\nDefinition ctx := env typ.\n\n(** *** Value environment (\"store\") *)\nDefinition sto := env obj.\n\n(** *** Syntactic sugar *)\nDefinition trm_fun(T U: typ)(body: trm) := \n            trm_new (decs_cons 0 (dec_mtd T U)  decs_nil)\n                    (defs_cons 0 (def_mtd body) defs_nil).\nDefinition trm_app(func arg: trm) := trm_call func 0 arg.\nDefinition trm_let(T U: typ)(rhs body: trm) := trm_app (trm_fun T U body) rhs.\nDefinition typ_arrow(T1 T2: typ) := typ_bind (decs_cons 0 (dec_mtd T1 T2) decs_nil).\n\n\n(* ###################################################################### *)\n(** ** Declaration and definition lists *)\n\nDefinition label_for_def(n: nat)(d: def): label := match d with\n| def_typ     => label_typ n\n| def_fld _   => label_fld n\n| def_mtd _   => label_mtd n\nend.\nDefinition label_for_dec(n: nat)(D: dec): label := match D with\n| dec_typ _ _ => label_typ n\n| dec_fld _   => label_fld n\n| dec_mtd _ _ => label_mtd n\nend.\n\nFixpoint get_def(l: label)(ds: defs): option def := match ds with\n| defs_nil => None\n| defs_cons n d ds' => If l = label_for_def n d then Some d else get_def l ds'\nend.\nFixpoint get_dec(l: label)(Ds: decs): option dec := match Ds with\n| decs_nil => None\n| decs_cons n D Ds' => If l = label_for_dec n D then Some D else get_dec l Ds'\nend.\n\nDefinition defs_has(ds: defs)(l: label)(d: def): Prop := (get_def l ds = Some d).\nDefinition decs_has(Ds: decs)(l: label)(D: dec): Prop := (get_dec l Ds = Some D).\n\nDefinition defs_hasnt(ds: defs)(l: label): Prop := (get_def l ds = None).\nDefinition decs_hasnt(Ds: decs)(l: label): Prop := (get_dec l Ds = None).\n\n\n(* ###################################################################### *)\n(** ** Opening *)\n\n(** Opening replaces in some syntax a bound variable with dangling index (k) \n   by a free variable x. *)\n\nDefinition open_rec_avar (k: nat) (u: var) (a: avar) : avar :=\n  match a with\n  | avar_b i => If k = i then avar_f u else avar_b i\n  | avar_f x => avar_f x\n  end.\n\nDefinition open_rec_pth (k: nat) (u: var) (p: pth) : pth :=\n  match p with\n  | pth_var a => pth_var (open_rec_avar k u a)\n  end.\n\nFixpoint open_rec_typ (k: nat) (u: var) (T: typ) { struct T } : typ :=\n  match T with\n  | typ_top     => typ_top\n  | typ_bot     => typ_bot\n  | typ_bind Ds => typ_bind (open_rec_decs (S k) u Ds)\n  | typ_sel p L => typ_sel (open_rec_pth k u p) L\n  end\nwith open_rec_dec (k: nat) (u: var) (D: dec) { struct D } : dec :=\n  match D with\n  | dec_typ T U => dec_typ (open_rec_typ k u T) (open_rec_typ k u U)\n  | dec_fld T   => dec_fld (open_rec_typ k u T)\n  | dec_mtd T U => dec_mtd (open_rec_typ k u T) (open_rec_typ k u U)\n  end\nwith open_rec_decs (k: nat) (u: var) (Ds: decs) { struct Ds } : decs :=\n  match Ds with\n  | decs_nil          => decs_nil\n  | decs_cons n D Ds' => decs_cons n (open_rec_dec k u D) (open_rec_decs k u Ds')\n  end.\n\nFixpoint open_rec_trm (k: nat) (u: var) (t: trm) { struct t } : trm :=\n  match t with\n  | trm_var a      => trm_var (open_rec_avar k u a)\n  | trm_new Ds ds  => trm_new (open_rec_decs k u Ds) (open_rec_defs (S k) u ds)\n  | trm_sel e n    => trm_sel (open_rec_trm k u e) n\n  | trm_call o m a => trm_call (open_rec_trm k u o) m (open_rec_trm k u a)\n  end\nwith open_rec_def (k: nat) (u: var) (d: def) { struct d } : def :=\n  match d with\n  | def_typ   => def_typ\n  | def_fld a => def_fld (open_rec_avar k u a)\n  | def_mtd e => def_mtd (open_rec_trm (S k) u e)\n  end\nwith open_rec_defs (k: nat) (u: var) (ds: defs) { struct ds } : defs :=\n  match ds with\n  | defs_nil => defs_nil\n  | defs_cons n d tl => defs_cons n (open_rec_def k u d) (open_rec_defs k u tl)\n  end.\n\nDefinition open_avar u a := open_rec_avar  0 u a.\nDefinition open_pth  u p := open_rec_pth   0 u p.\nDefinition open_typ  u t := open_rec_typ   0 u t.\nDefinition open_dec  u d := open_rec_dec   0 u d.\nDefinition open_decs u l := open_rec_decs  0 u l.\nDefinition open_trm  u e := open_rec_trm   0 u e.\nDefinition open_def  u d := open_rec_def   0 u d.\nDefinition open_defs u l := open_rec_defs  0 u l.\n\n\n(* ###################################################################### *)\n(** ** Free variables *)\n\nDefinition fv_avar (a: avar) : vars :=\n  match a with\n  | avar_b i => \\{}\n  | avar_f x => \\{x}\n  end.\n\nDefinition fv_pth (p: pth) : vars :=\n  match p with\n  | pth_var a => fv_avar a\n  end.\n\nFixpoint fv_typ (T: typ) { struct T } : vars :=\n  match T with\n  | typ_top     => \\{}\n  | typ_bot     => \\{}\n  | typ_bind Ds => fv_decs Ds\n  | typ_sel p L => fv_pth p\n  end\nwith fv_dec (D: dec) { struct D } : vars :=\n  match D with\n  | dec_typ T U => (fv_typ T) \\u (fv_typ U)\n  | dec_fld T   => (fv_typ T)\n  | dec_mtd T U => (fv_typ T) \\u (fv_typ U)\n  end\nwith fv_decs (Ds: decs) { struct Ds } : vars :=\n  match Ds with\n  | decs_nil          => \\{}\n  | decs_cons n D Ds' => (fv_dec D) \\u (fv_decs Ds')\n  end.\n\n(* Since we define defs ourselves instead of using [list def], we don't have any\n   termination proof problems: *)\nFixpoint fv_trm (t: trm) : vars :=\n  match t with\n  | trm_var x        => (fv_avar x)\n  | trm_new Ds ds    => (fv_decs Ds) \\u (fv_defs ds)\n  | trm_sel t l      => (fv_trm t)\n  | trm_call t1 m t2 => (fv_trm t1) \\u (fv_trm t2)\n  end\nwith fv_def (d: def) : vars :=\n  match d with\n  | def_typ   => \\{}\n  | def_fld x => fv_avar x\n  | def_mtd u => fv_trm u\n  end\nwith fv_defs(ds: defs) : vars :=\n  match ds with\n  | defs_nil         => \\{}\n  | defs_cons n d tl => (fv_def d) \\u (fv_defs tl)\n  end.\n\n\n(* ###################################################################### *)\n(** ** Operational Semantics *)\n\n(** Note: Terms given by user are closed, so they only contain avar_b, no avar_f.\n    Whenever we introduce a new avar_f (only happens in red_new), we choose one\n    which is not in the store, so we never have name clashes. *)\nInductive red : trm -> sto -> trm -> sto -> Prop :=\n  (* computation rules *)\n  | red_call : forall s x y m T ds body,\n      binds x (object T ds) s ->\n      defs_has (open_defs x ds) (label_mtd m) (def_mtd body) ->\n      red (trm_call (trm_var (avar_f x)) m (trm_var (avar_f y))) s\n          (open_trm y body) s\n  | red_sel : forall s x y l T ds,\n      binds x (object T ds) s ->\n      defs_has (open_defs x ds) (label_fld l) (def_fld y) ->\n      red (trm_sel (trm_var (avar_f x)) l) s\n          (trm_var y) s\n  | red_new : forall s T ds x,\n      x # s ->\n      red (trm_new T ds) s\n          (trm_var (avar_f x)) (s & x ~ (object T ds))\n  (* congruence rules *)\n  | red_call1 : forall s o m a s' o',\n      red o s o' s' ->\n      red (trm_call o  m a) s\n          (trm_call o' m a) s'\n  | red_call2 : forall s x m a s' a',\n      red a s a' s' ->\n      red (trm_call (trm_var (avar_f x)) m a ) s\n          (trm_call (trm_var (avar_f x)) m a') s'\n  | red_sel1 : forall s o l s' o',\n      red o s o' s' ->\n      red (trm_sel o  l) s\n          (trm_sel o' l) s'.\n\n\n(* ###################################################################### *)\n(** ** Typing *)\n\n(* tmode = \"is transitivity at top level accepted?\" *)\nInductive tmode : Type := notrans | oktrans.\n\n(* pmode = \"do the \"has\" judgments needed in subtyping have to be precise?\" *)\nInductive pmode : Type := pr | ip.\n\n(* Does this type, and all types that it syntactically contains, have collapsed\n   bounds for all type members? *)\nInductive cbounds_typ: typ -> Prop :=\n  | cbounds_top:\n      cbounds_typ typ_top\n  | cbounds_bot:\n      cbounds_typ typ_bot\n  | cbounds_bind : forall Ds,\n      cbounds_decs Ds ->\n      cbounds_typ (typ_bind Ds)\n  | cbounds_sel: forall p L,\n      cbounds_typ (typ_sel p L)\nwith cbounds_dec: dec -> Prop :=\n  | cbounds_dec_typ: forall T,\n      cbounds_dec (dec_typ T T) (* <-- that's the whole point *)\n  | cbounds_dec_fld: forall T,\n      cbounds_dec (dec_fld T)\n  | cbounds_dec_mtd: forall T U,\n      cbounds_dec (dec_mtd T U)\nwith cbounds_decs: decs -> Prop :=\n  | cbounds_nil:\n      cbounds_decs decs_nil\n  | cbounds_cons: forall n D Ds,\n      cbounds_dec D ->\n      cbounds_decs Ds ->\n      cbounds_decs (decs_cons n D Ds).\n\nInductive cbounds_ctx: ctx -> Prop :=\n  | cbounds_empty: \n      cbounds_ctx empty\n  | cbounds_push: forall G x T,\n      cbounds_typ T ->\n      cbounds_ctx G ->\n      cbounds_ctx (G & x ~ T).\n\n(* expansion returns a set of decs without opening them *)\nInductive exp : pmode -> ctx -> typ -> decs -> Prop :=\n  | exp_top : forall m G, \n      exp m G typ_top decs_nil\n(*| exp_bot : typ_bot has no expansion *)\n  | exp_bind : forall m G Ds,\n      exp m G (typ_bind Ds) Ds\n  | exp_sel : forall m G x L Lo Hi Ds,\n      has m G (trm_var (avar_f x)) L (dec_typ Lo Hi) ->\n      exp m G Hi Ds ->\n      exp m G (typ_sel (pth_var (avar_f x)) L) Ds\nwith has : pmode -> ctx -> trm -> label -> dec -> Prop :=\n  | has_trm : forall G t T Ds l D,\n      ty_trm G t T ->\n      exp ip G T Ds ->\n      decs_has Ds l D ->\n      (forall z, (open_dec z D) = D) ->\n      has ip G t l D\n  | has_var : forall G v T Ds l D,\n      ty_trm G (trm_var (avar_f v)) T ->\n      exp ip G T Ds ->\n      decs_has Ds l D ->\n      has ip G (trm_var (avar_f v)) l (open_dec v D)\n  | has_pr : forall G v T Ds l D,\n      binds v T G ->\n      exp pr G T Ds ->\n      decs_has Ds l D ->\n      has pr G (trm_var (avar_f v)) l (open_dec v D)\nwith subtyp : pmode -> tmode -> ctx -> typ -> typ -> Prop :=\n  | subtyp_refl : forall m G x L Lo Hi,\n      has m G (trm_var (avar_f x)) L (dec_typ Lo Hi) ->\n      subtyp m notrans G (typ_sel (pth_var (avar_f x)) L) (typ_sel (pth_var (avar_f x)) L)\n  | subtyp_top : forall m G T,\n      subtyp m notrans G T typ_top\n  | subtyp_bot : forall m G T,\n      subtyp m notrans G typ_bot T\n  | subtyp_bind : forall L m G Ds1 Ds2,\n      (forall z, z \\notin L -> \n         subdecs m (G & z ~ (typ_bind Ds1))\n                   (open_decs z Ds1) \n                   (open_decs z Ds2)) ->\n      subtyp m notrans G (typ_bind Ds1) (typ_bind Ds2)\n  | subtyp_sel_l : forall m G x L S U T,\n      has m G (trm_var (avar_f x)) L (dec_typ S U) ->\n      subtyp m oktrans G U T ->\n      subtyp m notrans G (typ_sel (pth_var (avar_f x)) L) T\n  | subtyp_sel_r : forall m G x L S U T,\n      has m G (trm_var (avar_f x)) L (dec_typ S U) ->\n      subtyp m oktrans G S U -> (* <--- makes proofs a lot easier!! *)\n      subtyp m oktrans G T S ->\n      subtyp m notrans G T (typ_sel (pth_var (avar_f x)) L)\n  | subtyp_tmode : forall m G T1 T2,\n      subtyp m notrans G T1 T2 ->\n      subtyp m oktrans G T1 T2\n  | subtyp_trans : forall m G T1 T2 T3,\n      subtyp m oktrans G T1 T2 ->\n      subtyp m oktrans G T2 T3 ->\n      subtyp m oktrans G T1 T3\nwith subdec : pmode -> ctx -> dec -> dec -> Prop :=\n  | subdec_typ : forall m G Lo1 Hi1 Lo2 Hi2,\n      (* only allow implementable decl *)\n      subtyp m oktrans G Lo1 Hi1 ->\n      subtyp m oktrans G Lo2 Hi2 ->\n      (* lhs narrower range than rhs *)\n      subtyp m oktrans G Lo2 Lo1 ->\n      subtyp m oktrans G Hi1 Hi2 ->\n      (* conclusion *)\n      subdec m G (dec_typ Lo1 Hi1) (dec_typ Lo2 Hi2)\n  | subdec_fld : forall m G T1 T2,\n      subtyp m oktrans G T1 T2 ->\n      subdec m G (dec_fld T1) (dec_fld T2)\n  | subdec_mtd : forall m G S1 T1 S2 T2,\n      subtyp m oktrans G S2 S1 ->\n      subtyp m oktrans G T1 T2 ->\n      subdec m G (dec_mtd S1 T1) (dec_mtd S2 T2)\nwith subdecs : pmode -> ctx -> decs -> decs -> Prop :=\n  | subdecs_empty : forall m G Ds,\n      subdecs m G Ds decs_nil\n  | subdecs_push : forall m G n Ds1 Ds2 D1 D2,\n      decs_has Ds1 (label_for_dec n D2) D1 ->\n      subdec  m G D1 D2 ->\n      subdecs m G Ds1 Ds2 ->\n      subdecs m G Ds1 (decs_cons n D2 Ds2)\nwith ty_trm : ctx -> trm -> typ -> Prop :=\n  | ty_var : forall G x T,\n      binds x T G ->\n      ty_trm G (trm_var (avar_f x)) T\n  | ty_sel : forall G t l T,\n      has ip G t (label_fld l) (dec_fld T) ->\n      ty_trm G (trm_sel t l) T\n  | ty_call : forall G t m U V u,\n      has ip G t (label_mtd m) (dec_mtd U V) ->\n      ty_trm G u U ->\n      ty_trm G (trm_call t m u) V\n  | ty_new : forall L G ds Ds,\n      (forall x, x \\notin L ->\n                 ty_defs (G & x ~ typ_bind Ds) (open_defs x ds) (open_decs x Ds)) ->\n      cbounds_decs Ds ->\n      ty_trm G (trm_new Ds ds) (typ_bind Ds)\n  | ty_sbsm : forall G t T U,\n      ty_trm G t T ->\n      subtyp ip oktrans G T U ->\n      ty_trm G t U\nwith ty_def : ctx -> def -> dec -> Prop :=\n  | ty_typ : forall G S T,\n      ty_def G def_typ (dec_typ S T)\n  | ty_fld : forall G v T,\n      ty_trm G (trm_var v) T ->\n      ty_def G (def_fld v) (dec_fld T)\n  | ty_mtd : forall L G S T t,\n      (forall x, x \\notin L -> ty_trm (G & x ~ S) (open_trm x t) T) ->\n      ty_def G (def_mtd t) (dec_mtd S T)\nwith ty_defs : ctx -> defs -> decs -> Prop :=\n  | ty_dsnil : forall G,\n      ty_defs G defs_nil decs_nil\n  | ty_dscons : forall G ds d Ds D n,\n      ty_defs G ds Ds ->\n      ty_def  G d D ->\n      ty_defs G (defs_cons n d ds) (decs_cons n D Ds).\n\nInductive wf_typ: ctx -> typ -> Prop :=\n  | wf_top : forall G,\n      wf_typ G typ_top\n  | wf_bot : forall G,\n      wf_typ G typ_bot\n  | wf_bind : forall L G Ds,\n      (forall z, z \\notin L -> wf_decs (G & z ~ typ_bind Ds) Ds) ->\n      wf_typ G (typ_bind Ds)\n  | wf_sel1 : forall G x L Lo Hi,\n      has pr G (trm_var (avar_f x)) L (dec_typ Lo Hi) ->\n      wf_typ G Lo ->\n      wf_typ G Hi ->\n      wf_typ G (typ_sel (pth_var (avar_f x)) L)\n  | wf_sel2 : forall G x L U,\n      has pr G (trm_var (avar_f x)) L (dec_typ typ_bot U) ->\n      (* note: no check on U --> allows recursive class types are possible *)\n      wf_typ G (typ_sel (pth_var (avar_f x)) L)\nwith wf_dec : ctx -> dec -> Prop :=\n  | wf_tmem : forall G Lo Hi,\n      wf_typ G Lo ->\n      wf_typ G Hi ->\n      wf_dec G (dec_typ Lo Hi)\n  | wf_fld : forall G T,\n      wf_typ G T ->\n      wf_dec G (dec_fld T)\n  | wf_mtd : forall G A R,\n      wf_typ G A ->\n      wf_typ G R ->\n      wf_dec G (dec_mtd A R)\nwith wf_decs : ctx -> decs -> Prop :=\n  | wf_nil : forall G,\n      wf_decs G decs_nil\n  | wf_cons : forall G n D Ds,\n      wf_dec G D ->\n      wf_decs G Ds ->\n      wf_decs G (decs_cons n D Ds).\n\n(** *** Well-formed store *)\nInductive wf_sto: sto -> ctx -> Prop :=\n  | wf_sto_empty : wf_sto empty empty\n  | wf_sto_push : forall s G x ds Ds,\n      wf_sto s G ->\n      x # s ->\n      x # G ->\n      (* What's below is the same as the ty_new rule, but we don't use ty_trm,\n         because it could be subsumption *)\n      ty_defs (G & x ~ typ_bind Ds) (open_defs x ds) (open_decs x Ds) ->\n      cbounds_decs Ds ->\n      wf_sto (s & x ~ (object Ds ds)) (G & x ~ typ_bind Ds).\n\n\n(* ###################################################################### *)\n(** ** Statements we want to prove *)\n\nDefinition progress := forall s G e T,\n  wf_sto s G ->\n  ty_trm G e T -> \n  (\n    (* can step *)\n    (exists e' s', red e s e' s') \\/\n    (* or is a value *)\n    (exists x o, e = (trm_var (avar_f x)) /\\ binds x o s)\n  ).\n\nDefinition preservation := forall s G e T e' s',\n  wf_sto s G -> ty_trm G e T -> red e s e' s' ->\n  (exists G', wf_sto s' G' /\\ ty_trm G' e' T).\n\n\n(* ###################################################################### *)\n(* ###################################################################### *)\n(** * Infrastructure *)\n\n(* ###################################################################### *)\n(** ** Induction principles *)\n\nScheme trm_mut  := Induction for trm  Sort Prop\nwith   def_mut  := Induction for def  Sort Prop\nwith   defs_mut := Induction for defs Sort Prop.\nCombined Scheme trm_mutind from trm_mut, def_mut, defs_mut.\n\nScheme typ_mut  := Induction for typ  Sort Prop\nwith   dec_mut  := Induction for dec  Sort Prop\nwith   decs_mut := Induction for decs Sort Prop.\nCombined Scheme typ_mutind from typ_mut, dec_mut, decs_mut.\n\nScheme exp_mut     := Induction for exp     Sort Prop\nwith   has_mut     := Induction for has     Sort Prop\nwith   subtyp_mut  := Induction for subtyp  Sort Prop\nwith   subdec_mut  := Induction for subdec  Sort Prop\nwith   subdecs_mut := Induction for subdecs Sort Prop\nwith   ty_trm_mut  := Induction for ty_trm  Sort Prop\nwith   ty_def_mut  := Induction for ty_def  Sort Prop\nwith   ty_defs_mut := Induction for ty_defs Sort Prop.\nCombined Scheme ty_mutind from exp_mut, has_mut,\n                               subtyp_mut, subdec_mut, subdecs_mut,\n                               ty_trm_mut, ty_def_mut, ty_defs_mut.\n\nScheme has_mut2    := Induction for has    Sort Prop\nwith   ty_trm_mut2 := Induction for ty_trm Sort Prop.\nCombined Scheme ty_has_mutind from has_mut2, ty_trm_mut2.\n\nScheme exp_mut20  := Induction for exp Sort Prop\nwith   has_mut20  := Induction for has Sort Prop.\nCombined Scheme exp_has_mutind from exp_mut20, has_mut20.\n\nScheme exp_mut4     := Induction for exp     Sort Prop\nwith   has_mut4     := Induction for has     Sort Prop\nwith   subtyp_mut4  := Induction for subtyp  Sort Prop\nwith   ty_trm_mut4  := Induction for ty_trm  Sort Prop.\nCombined Scheme exp_has_subtyp_ty_mutind from exp_mut4, has_mut4, subtyp_mut4, ty_trm_mut4.\n\nScheme exp_mut5     := Induction for exp     Sort Prop\nwith   has_mut5     := Induction for has     Sort Prop\nwith   subtyp_mut5  := Induction for subtyp  Sort Prop\nwith   subdec_mut5  := Induction for subdec  Sort Prop\nwith   subdecs_mut5 := Induction for subdecs Sort Prop.\nCombined Scheme mutind5 from exp_mut5, has_mut5,\n                             subtyp_mut5, subdec_mut5, subdecs_mut5.\n\nScheme exp_mut6     := Induction for exp     Sort Prop\nwith   has_mut6     := Induction for has     Sort Prop\nwith   subtyp_mut6  := Induction for subtyp  Sort Prop\nwith   subdec_mut6  := Induction for subdec  Sort Prop\nwith   subdecs_mut6 := Induction for subdecs Sort Prop\nwith   ty_trm_mut6  := Induction for ty_trm  Sort Prop.\nCombined Scheme mutind6 from exp_mut6, has_mut6,\n                             subtyp_mut6, subdec_mut6, subdecs_mut6,\n                             ty_trm_mut6.\n\nScheme wf_typ_mut  := Induction for wf_typ  Sort Prop\nwith   wf_dec_mut  := Induction for wf_dec  Sort Prop\nwith   wf_decs_mut := Induction for wf_decs Sort Prop.\nCombined Scheme wf_mutind from wf_typ_mut, wf_dec_mut, wf_decs_mut.\n\n\n(* ###################################################################### *)\n(** ** Tactics *)\n\nLtac auto_specialize :=\n  repeat match goal with\n  | Impl: ?Cond ->            _ |- _ => let HC := fresh in \n      assert (HC: Cond) by auto; specialize (Impl HC); clear HC\n  | Impl: forall (_ : ?Cond), _ |- _ => match goal with\n      | p: Cond |- _ => specialize (Impl p)\n      end\n  end.\n\nLtac gather_vars :=\n  let A := gather_vars_with (fun x : vars      => x         ) in\n  let B := gather_vars_with (fun x : var       => \\{ x }    ) in\n  let C := gather_vars_with (fun x : ctx       => dom x     ) in\n  let D := gather_vars_with (fun x : sto       => dom x     ) in\n  let E := gather_vars_with (fun x : avar      => fv_avar  x) in\n  let F := gather_vars_with (fun x : trm       => fv_trm   x) in\n  let G := gather_vars_with (fun x : def       => fv_def   x) in\n  let H := gather_vars_with (fun x : defs      => fv_defs  x) in\n  let I := gather_vars_with (fun x : typ       => fv_typ   x) in\n  let J := gather_vars_with (fun x : dec       => fv_dec   x) in\n  let K := gather_vars_with (fun x : decs      => fv_decs  x) in\n  constr:(A \\u B \\u C \\u D \\u E \\u F \\u G \\u H \\u I \\u J \\u K).\n\nLtac pick_fresh x :=\n  let L := gather_vars in (pick_fresh_gen L x).\n\nTactic Notation \"apply_fresh\" constr(T) \"as\" ident(x) :=\n  apply_fresh_base T gather_vars x.\n\nHint Constructors subtyp.\nHint Constructors subdec.\n\n\n(* ###################################################################### *)\n(** ** Library extensions *)\n\nLemma fresh_push_eq_inv: forall A x a (E: env A),\n  x # (E & x ~ a) -> False.\nProof.\n  intros. rewrite dom_push in H. false H. rewrite in_union.\n  left. rewrite in_singleton. reflexivity.\nQed.\n\nDefinition vars_empty: vars := \\{}. (* because tactic [exists] cannot infer type var *)\n\n\n(* ###################################################################### *)\n(** ** Definition of var-by-var substitution *)\n\n(** Note that substitution is not part of the definitions, because for the\n    definitions, opening is sufficient. For the proofs, however, we also\n    need substitution, but only var-by-var substitution, not var-by-term\n    substitution. That's why we don't need a judgment asserting that a term\n    is locally closed. *)\n\nDefinition subst_avar (z: var) (u: var) (a: avar) : avar :=\n  match a with\n  | avar_b i => avar_b i\n  | avar_f x => If x = z then (avar_f u) else (avar_f x)\n  end.\n\nDefinition subst_pth (z: var) (u: var) (p: pth) : pth :=\n  match p with\n  | pth_var a => pth_var (subst_avar z u a)\n  end.\n\nFixpoint subst_typ (z: var) (u: var) (T: typ) { struct T } : typ :=\n  match T with\n  | typ_top     => typ_top\n  | typ_bot     => typ_bot\n  | typ_bind Ds => typ_bind (subst_decs z u Ds)\n  | typ_sel p L => typ_sel (subst_pth z u p) L\n  end\nwith subst_dec (z: var) (u: var) (D: dec) { struct D } : dec :=\n  match D with\n  | dec_typ T U => dec_typ (subst_typ z u T) (subst_typ z u U)\n  | dec_fld T   => dec_fld (subst_typ z u T)\n  | dec_mtd T U => dec_mtd (subst_typ z u T) (subst_typ z u U)\n  end\nwith subst_decs (z: var) (u: var) (Ds: decs) { struct Ds } : decs :=\n  match Ds with\n  | decs_nil          => decs_nil\n  | decs_cons n D Ds' => decs_cons n (subst_dec z u D) (subst_decs z u Ds')\n  end.\n\nFixpoint subst_trm (z: var) (u: var) (t: trm) : trm :=\n  match t with\n  | trm_var x        => trm_var (subst_avar z u x)\n  | trm_new Ds ds    => trm_new (subst_decs z u Ds) (subst_defs z u ds)\n  | trm_sel t l      => trm_sel (subst_trm z u t) l\n  | trm_call t1 m t2 => trm_call (subst_trm z u t1) m (subst_trm z u t2)\n  end\nwith subst_def (z: var) (u: var) (d: def) : def :=\n  match d with\n  | def_typ => def_typ\n  | def_fld x => def_fld (subst_avar z u x)\n  | def_mtd b => def_mtd (subst_trm z u b)\n  end\nwith subst_defs (z: var) (u: var) (ds: defs) : defs :=\n  match ds with\n  | defs_nil => defs_nil\n  | defs_cons n d rest => defs_cons n (subst_def z u d) (subst_defs z u rest)\n  end.\n\nDefinition subst_ctx (z: var) (u: var) (G: ctx) : ctx := map (subst_typ z u) G.\n\n\n(* ###################################################################### *)\n(** ** Lemmas for var-by-var substitution *)\n\nLemma subst_fresh_avar: forall x y,\n  (forall a: avar, x \\notin fv_avar a -> subst_avar x y a = a).\nProof.\n  intros. destruct* a. simpl. case_var*. simpls. notin_false.\nQed.\n\nLemma subst_fresh_pth: forall x y,\n  (forall p: pth, x \\notin fv_pth p -> subst_pth x y p = p).\nProof.\n  intros. destruct p. simpl. f_equal. apply* subst_fresh_avar.\nQed.\n\nLemma subst_fresh_typ_dec_decs: forall x y,\n  (forall T : typ , x \\notin fv_typ  T  -> subst_typ  x y T  = T ) /\\\n  (forall d : dec , x \\notin fv_dec  d  -> subst_dec  x y d  = d ) /\\\n  (forall ds: decs, x \\notin fv_decs ds -> subst_decs x y ds = ds).\nProof.\n  intros x y. apply typ_mutind; intros; simpls; f_equal*. apply* subst_fresh_pth.\nQed.\n\nLemma subst_fresh_trm_def_defs: forall x y,\n  (forall t : trm , x \\notin fv_trm  t  -> subst_trm  x y t  = t ) /\\\n  (forall d : def , x \\notin fv_def  d  -> subst_def  x y d  = d ) /\\\n  (forall ds: defs, x \\notin fv_defs ds -> subst_defs x y ds = ds).\nProof.\n  intros x y. apply trm_mutind; intros; simpls; f_equal*.\n  + apply* subst_fresh_avar.\n  + apply* subst_fresh_typ_dec_decs.\n  + apply* subst_fresh_avar.\nQed.\n\nDefinition subst_fvar(x y z: var): var := If x = z then y else z.\n\nLemma subst_open_commute_avar: forall x y u,\n  (forall a: avar, forall n: nat,\n    subst_avar x y (open_rec_avar n u a) \n    = open_rec_avar n (subst_fvar x y u) (subst_avar  x y a)).\nProof.\n  intros. unfold subst_fvar, subst_avar, open_avar, open_rec_avar. destruct a.\n  + repeat case_if; auto.\n  + case_var*.\nQed.\n\nLemma subst_open_commute_pth: forall x y u,\n  (forall p: pth, forall n: nat,\n    subst_pth x y (open_rec_pth n u p) \n    = open_rec_pth n (subst_fvar x y u) (subst_pth x y p)).\nProof.\n  intros. unfold subst_pth, open_pth, open_rec_pth. destruct p.\n  f_equal. apply subst_open_commute_avar.\nQed.\n\n(* \"open and then substitute\" = \"substitute and then open\" *)\nLemma subst_open_commute_typ_dec_decs: forall x y u,\n  (forall t : typ, forall n: nat,\n     subst_typ x y (open_rec_typ n u t)\n     = open_rec_typ n (subst_fvar x y u) (subst_typ x y t)) /\\\n  (forall d : dec , forall n: nat, \n     subst_dec x y (open_rec_dec n u d)\n     = open_rec_dec n (subst_fvar x y u) (subst_dec x y d)) /\\\n  (forall ds: decs, forall n: nat, \n     subst_decs x y (open_rec_decs n u ds)\n     = open_rec_decs n (subst_fvar x y u) (subst_decs x y ds)).\nProof.\n  intros. apply typ_mutind; intros; simpl; f_equal*. apply subst_open_commute_pth.\nQed.\n\n(* \"open and then substitute\" = \"substitute and then open\" *)\nLemma subst_open_commute_trm_def_defs: forall x y u,\n  (forall t : trm, forall n: nat,\n     subst_trm x y (open_rec_trm n u t)\n     = open_rec_trm n (subst_fvar x y u) (subst_trm x y t)) /\\\n  (forall d : def , forall n: nat, \n     subst_def x y (open_rec_def n u d)\n     = open_rec_def n (subst_fvar x y u) (subst_def x y d)) /\\\n  (forall ds: defs, forall n: nat, \n     subst_defs x y (open_rec_defs n u ds)\n     = open_rec_defs n (subst_fvar x y u) (subst_defs x y ds)).\nProof.\n  intros. apply trm_mutind; intros; simpl; f_equal*.\n  + apply* subst_open_commute_avar.\n  + apply* subst_open_commute_typ_dec_decs.\n  + apply* subst_open_commute_avar.\nQed.\n\nLemma subst_open_commute_trm: forall x y u t,\n  subst_trm x y (open_trm u t) = open_trm (subst_fvar x y u) (subst_trm x y t).\nProof.\n  intros. apply* subst_open_commute_trm_def_defs.\nQed.\n\nLemma subst_open_commute_defs: forall x y u ds,\n  subst_defs x y (open_defs u ds) = open_defs (subst_fvar x y u) (subst_defs x y ds).\nProof.\n  intros. apply* subst_open_commute_trm_def_defs.\nQed.\n\nLemma subst_open_commute_typ: forall x y u T,\n  subst_typ x y (open_typ u T) = open_typ (subst_fvar x y u) (subst_typ x y T).\nProof.\n  intros. apply* subst_open_commute_typ_dec_decs.\nQed.\n\nLemma subst_open_commute_dec: forall x y u D,\n  subst_dec x y (open_dec u D) = open_dec (subst_fvar x y u) (subst_dec x y D).\nProof.\n  intros. apply* subst_open_commute_typ_dec_decs.\nQed.\n\nLemma subst_open_commute_decs: forall x y u Ds,\n  subst_decs x y (open_decs u Ds) = open_decs (subst_fvar x y u) (subst_decs x y Ds).\nProof.\n  intros. apply* subst_open_commute_typ_dec_decs.\nQed.\n\n(* \"Introduce a substitution after open\": Opening a term t with a var u is the\n   same as opening t with x and then replacing x by u. *)\nLemma subst_intro_trm: forall x u t, x \\notin (fv_trm t) ->\n  open_trm u t = subst_trm x u (open_trm x t).\nProof.\n  introv Fr. unfold open_trm. rewrite* subst_open_commute_trm.\n  destruct (@subst_fresh_trm_def_defs x u) as [Q _]. rewrite* (Q t).\n  unfold subst_fvar. case_var*.\nQed.\n\nLemma subst_intro_defs: forall x u ds, x \\notin (fv_defs ds) ->\n  open_defs u ds = subst_defs x u (open_defs x ds).\nProof.\n  introv Fr. unfold open_trm. rewrite* subst_open_commute_defs.\n  destruct (@subst_fresh_trm_def_defs x u) as [_ [_ Q]]. rewrite* (Q ds).\n  unfold subst_fvar. case_var*.\nQed.\n\nLemma subst_intro_typ: forall x u T, x \\notin (fv_typ T) ->\n  open_typ u T = subst_typ x u (open_typ x T).\nProof.\n  introv Fr. unfold open_typ. rewrite* subst_open_commute_typ.\n  destruct (@subst_fresh_typ_dec_decs x u) as [Q _]. rewrite* (Q T).\n  unfold subst_fvar. case_var*.\nQed.\n\nLemma subst_intro_dec: forall x u D, x \\notin (fv_dec D) ->\n  open_dec u D = subst_dec x u (open_dec x D).\nProof.\n  introv Fr. unfold open_trm. rewrite* subst_open_commute_dec.\n  destruct (@subst_fresh_typ_dec_decs x u) as [_ [Q _]]. rewrite* (Q D).\n  unfold subst_fvar. case_var*.\nQed.\n\nLemma subst_intro_decs: forall x u Ds, x \\notin (fv_decs Ds) ->\n  open_decs u Ds = subst_decs x u (open_decs x Ds).\nProof.\n  introv Fr. unfold open_trm. rewrite* subst_open_commute_decs.\n  destruct (@subst_fresh_typ_dec_decs x u) as [_ [_ Q]]. rewrite* (Q Ds).\n  unfold subst_fvar. case_var*.\nQed.\n\nLemma subst_undo_avar: forall x y,\n  (forall a, y \\notin fv_avar a -> (subst_avar y x (subst_avar x y a)) = a).\nProof.\n  intros. unfold subst_avar, subst_fvar, open_avar, open_rec_avar; destruct a.\n  + reflexivity.\n  + unfold fv_avar in H. assert (y <> v) by auto. repeat case_if; reflexivity.\nQed.\n\nLemma subst_undo_pth: forall x y,\n  (forall p, y \\notin fv_pth p -> (subst_pth y x (subst_pth x y p)) = p).\nProof.\n  intros. destruct p. unfold subst_pth. f_equal.\n  unfold fv_pth in H.\n  apply* subst_undo_avar.\nQed.\n\nLemma subst_undo_typ_dec_decs: forall x y,\n   (forall T , y \\notin fv_typ  T  -> (subst_typ  y x (subst_typ  x y T )) = T )\n/\\ (forall D , y \\notin fv_dec  D  -> (subst_dec  y x (subst_dec  x y D )) = D )\n/\\ (forall Ds, y \\notin fv_decs Ds -> (subst_decs y x (subst_decs x y Ds)) = Ds).\nProof.\n  intros.\n  apply typ_mutind; intros; simpl; unfold fv_typ, fv_dec, fv_decs in *; f_equal*.\n  apply* subst_undo_pth.\nQed.\n\nLemma subst_undo_trm_def_defs: forall x y,\n   (forall t , y \\notin fv_trm  t  -> (subst_trm  y x (subst_trm  x y t )) = t )\n/\\ (forall d , y \\notin fv_def  d  -> (subst_def  y x (subst_def  x y d )) = d )\n/\\ (forall ds, y \\notin fv_defs ds -> (subst_defs y x (subst_defs x y ds)) = ds).\nProof.\n  intros.\n  apply trm_mutind; intros; simpl; unfold fv_trm, fv_def, fv_defs in *; f_equal*.\n  + apply* subst_undo_avar.\n  + apply* subst_undo_typ_dec_decs.\n  + apply* subst_undo_avar.\nQed.\n\nLemma subst_typ_undo: forall x y T,\n  y \\notin fv_typ T -> (subst_typ y x (subst_typ x y T)) = T.\nProof.\n  apply* subst_undo_typ_dec_decs.\nQed.\n\nLemma subst_trm_undo: forall x y t,\n  y \\notin fv_trm t -> (subst_trm y x (subst_trm x y t)) = t.\nProof.\n  apply* subst_undo_trm_def_defs.\nQed.\n\n\n(* ###################################################################### *)\n(** ** Helper lemmas for definition/declaration lists *)\n\nLemma defs_has_fld_sync: forall n d ds,\n  defs_has ds (label_fld n) d -> exists x, d = (def_fld x).\nProof.\n  introv Hhas. induction ds; unfolds defs_has, get_def. \n  + discriminate.\n  + case_if.\n    - inversions Hhas. unfold label_for_def in H. destruct* d; discriminate.\n    - apply* IHds.\nQed.\n\nLemma defs_has_mtd_sync: forall n d ds,\n  defs_has ds (label_mtd n) d -> exists e, d = (def_mtd e).\nProof.\n  introv Hhas. induction ds; unfolds defs_has, get_def. \n  + discriminate.\n  + case_if.\n    - inversions Hhas. unfold label_for_def in H. destruct* d; discriminate.\n    - apply* IHds.\nQed.\n\nLemma decs_has_typ_sync: forall n D Ds,\n  decs_has Ds (label_typ n) D -> exists Lo Hi, D = (dec_typ Lo Hi).\nProof.\n  introv Hhas. induction Ds; unfolds decs_has, get_dec. \n  + discriminate.\n  + case_if.\n    - inversions Hhas. unfold label_for_dec in H. destruct* D; discriminate.\n    - apply* IHDs.\nQed.\n\nLemma decs_has_fld_sync: forall n d ds,\n  decs_has ds (label_fld n) d -> exists x, d = (dec_fld x).\nProof.\n  introv Hhas. induction ds; unfolds decs_has, get_dec. \n  + discriminate.\n  + case_if.\n    - inversions Hhas. unfold label_for_dec in H. destruct* d; discriminate.\n    - apply* IHds.\nQed.\n\nLemma decs_has_mtd_sync: forall n d ds,\n  decs_has ds (label_mtd n) d -> exists T U, d = (dec_mtd T U).\nProof.\n  introv Hhas. induction ds; unfolds decs_has, get_dec. \n  + discriminate.\n  + case_if.\n    - inversions Hhas. unfold label_for_dec in H. destruct* d; discriminate.\n    - apply* IHds.\nQed.\n\nLemma get_def_cons : forall l n d ds,\n  get_def l (defs_cons n d ds) = If l = (label_for_def n d) then Some d else get_def l ds.\nProof.\n  intros. unfold get_def. case_if~.\nQed.\n\nLemma get_dec_cons : forall l n D Ds,\n  get_dec l (decs_cons n D Ds) = If l = (label_for_dec n D) then Some D else get_dec l Ds.\nProof.\n  intros. unfold get_dec. case_if~.\nQed.\n\n\n(* ###################################################################### *)\n(** ** Trivial inversion lemmas *)\n\nLemma invert_subdec_typ_sync_left: forall m G D Lo2 Hi2,\n   subdec m G D (dec_typ Lo2 Hi2) ->\n   exists Lo1 Hi1, D = (dec_typ Lo1 Hi1) /\\\n                   subtyp m oktrans G Lo2 Lo1 /\\\n                   subtyp m oktrans G Lo1 Hi1 /\\\n                   subtyp m oktrans G Hi1 Hi2.\nProof.\n  introv Sd. inversions Sd. exists Lo1 Hi1. auto.\nQed.\n\nLemma invert_subdec_fld_sync_left: forall m G D T2,\n   subdec m G D (dec_fld T2) ->\n   exists T1, D = (dec_fld T1) /\\\n              subtyp m oktrans G T1 T2.\nProof.\n  introv Sd. inversions Sd. exists T1. auto.\nQed.\n\nLemma invert_subdec_mtd_sync_left: forall m G D T2 U2,\n   subdec m G D (dec_mtd T2 U2) ->\n   exists T1 U1, D = (dec_mtd T1 U1) /\\\n                 subtyp m oktrans G T2 T1 /\\\n                 subtyp m oktrans G U1 U2.\nProof.\n  introv Sd. inversions Sd. exists S1 T1. auto.\nQed.\n\nLemma invert_subdec_typ: forall m G Lo1 Hi1 Lo2 Hi2,\n  subdec m G (dec_typ Lo1 Hi1) (dec_typ Lo2 Hi2) ->\n  subtyp m oktrans G Lo2 Lo1 /\\ subtyp m oktrans G Hi1 Hi2.\nProof.\n  introv Sd. inversions Sd. auto.\nQed.\n\nLemma invert_subdecs: forall m G Ds1 Ds2,\n  subdecs m G Ds1 Ds2 -> \n  forall l D2, decs_has Ds2 l D2 -> \n               (exists D1, decs_has Ds1 l D1 /\\ subdec m G D1 D2).\nProof.\n  introv Sds. induction Ds2; introv Has.\n  + inversion Has.\n  + inversions Sds.\n    unfold decs_has, get_dec in Has. case_if.\n    - inversions Has.\n      exists D1. split; assumption.\n    - fold get_dec in Has. apply IHDs2; assumption.\nQed.\n\nLemma wf_sto_to_ok_s: forall s G,\n  wf_sto s G -> ok s.\nProof. intros. induction H; jauto. Qed.\n\nLemma wf_sto_to_ok_G: forall s G,\n  wf_sto s G -> ok G.\nProof. intros. induction H; jauto. Qed.\n\nHint Resolve wf_sto_to_ok_s wf_sto_to_ok_G.\n\nLemma wf_sto_to_cbounds_ctx: forall s G,\n  wf_sto s G -> cbounds_ctx G.\nAdmitted. (* TODO holds *)\n\nLemma ctx_binds_to_sto_binds: forall s G x T,\n  wf_sto s G ->\n  binds x T G ->\n  exists o, binds x o s.\nProof.\n  introv Wf Bi. gen x T Bi. induction Wf; intros.\n  + false* binds_empty_inv.\n  + unfolds binds. rewrite get_push in *. case_if.\n    - eauto.\n    - eauto.\nQed.\n\nLemma sto_binds_to_ctx_binds: forall s G x Ds ds,\n  wf_sto s G ->\n  binds x (object Ds ds) s ->\n  binds x (typ_bind Ds) G.\nProof.\n  introv Wf Bi. gen x Ds Bi. induction Wf; intros.\n  + false* binds_empty_inv.\n  + unfolds binds. rewrite get_push in *. case_if.\n    - inversions Bi. reflexivity.\n    - auto.\nQed.\n\nLemma sto_unbound_to_ctx_unbound: forall s G x,\n  wf_sto s G ->\n  x # s ->\n  x # G.\nProof.\n  introv Wf Ub_s.\n  induction Wf.\n  + auto.\n  + destruct (classicT (x0 = x)) as [Eq | Ne].\n    - subst. false (fresh_push_eq_inv Ub_s). \n    - auto.\nQed.\n\nLemma ctx_unbound_to_sto_unbound: forall s G x,\n  wf_sto s G ->\n  x # G ->\n  x # s.\nProof.\n  introv Wf Ub.\n  induction Wf.\n  + auto.\n  + destruct (classicT (x0 = x)) as [Eq | Ne].\n    - subst. false (fresh_push_eq_inv Ub). \n    - auto.\nQed.\n\nLemma invert_wf_sto: forall s G,\n  wf_sto s G ->\n    forall x ds Ds T,\n      binds x (object Ds ds) s -> \n      binds x T G ->\n      T = (typ_bind Ds) /\\ exists G1 G2,\n        G = G1 & x ~ typ_bind Ds & G2 /\\ \n        ty_defs (G1 & x ~ typ_bind Ds) (open_defs x ds) (open_decs x Ds) /\\\n        cbounds_decs Ds.\nProof.\n  intros s G Wf. induction Wf; intros.\n  + false* binds_empty_inv.\n  + unfold binds in *. rewrite get_push in *.\n    case_if.\n    - inversions H3. inversions H4. split. reflexivity.\n      exists G (@empty typ). rewrite concat_empty_r. auto.\n    - specialize (IHWf x0 ds0 Ds0 T H3 H4).\n      destruct IHWf as [EqDs [G1 [G2 [EqG [Ty F]]]]]. subst.\n      apply (conj eq_refl).\n      exists G1 (G2 & x ~ typ_bind Ds).\n      rewrite concat_assoc.\n      apply (conj eq_refl). auto.\nQed.\n\nLemma subdec_sync: forall m G D1 D2,\n   subdec m G D1 D2 ->\n   (exists Lo1 Hi1 Lo2 Hi2, D1 = dec_typ Lo1 Hi1 /\\ D2 = dec_typ Lo2 Hi2)\n\\/ (exists T1 T2, D1 = dec_fld T1 /\\ D2 = dec_fld T2)\n\\/ (exists T1 U1 T2 U2, D1 = dec_mtd T1 U1 /\\ D2 = dec_mtd T2 U2).\nProof.\n  introv Sd. inversions Sd.\n  + left. do 4 eexists. eauto.\n  + right. left. eauto.\n  + right. right. do 4 eexists. eauto.\nQed.\n\nLtac subdec_sync_for Hyp :=\n  let Lo1 := fresh \"Lo1\" in\n  let Hi1 := fresh \"Hi1\" in\n  let Lo2 := fresh \"Lo2\" in\n  let Hi2 := fresh \"Hi2\" in\n  let Eq1 := fresh \"Eq1\" in\n  let Eq2 := fresh \"Eq2\" in\n  let T1  := fresh \"T1\"  in\n  let T2  := fresh \"T2\"  in\n  let U1  := fresh \"U1\"  in\n  let U2  := fresh \"U2\"  in\n  destruct (subdec_sync Hyp) as [[Lo1 [Hi1 [Lo2 [Hi2 [Eq1 Eq2]]]]] \n    | [[T1 [T2 [Eq1 Eq2]]] | [T1 [U1 [T2 [U2 [Eq1 Eq2]]]]]]].\n\nLemma subdec_to_label_for_eq: forall m G D1 D2 n,\n  subdec m G D1 D2 ->\n  (label_for_dec n D1) = (label_for_dec n D2).\nProof.\n  introv Sd. subdec_sync_for Sd; subst; reflexivity.\nQed.\n\nLemma invert_subdecs_push: forall m G Ds1 Ds2 n D2,\n  subdecs m G Ds1 (decs_cons n D2 Ds2) -> \n    exists D1, decs_has Ds1 (label_for_dec n D2) D1\n            /\\ subdec m G D1 D2\n            /\\ subdecs m G Ds1 Ds2.\nProof.\n  intros. inversions H. eauto.\nQed.\n\nLemma ty_def_to_label_for_eq: forall G d D n, \n  ty_def G d D ->\n  label_for_def n d = label_for_dec n D.\nProof.\n  intros. inversions H; reflexivity.\nQed.\n\nLemma extract_ty_def_from_ty_defs: forall G l d ds D Ds,\n  ty_defs G ds Ds ->\n  defs_has ds l d ->\n  decs_has Ds l D ->\n  ty_def G d D.\nProof.\n  introv HdsDs. induction HdsDs.\n  + intros. inversion H.\n  + introv dsHas DsHas. unfolds defs_has, decs_has, get_def, get_dec. \n    rewrite (ty_def_to_label_for_eq n H) in dsHas. case_if.\n    - inversions dsHas. inversions DsHas. assumption.\n    - apply* IHHdsDs.\nQed.\n\nLemma invert_ty_mtd_inside_ty_defs: forall G ds Ds m S T body,\n  ty_defs G ds Ds ->\n  defs_has ds (label_mtd m) (def_mtd body) ->\n  decs_has Ds (label_mtd m) (dec_mtd S T) ->\n  (* conclusion is the premise needed to construct a ty_mtd: *)\n  exists L, forall x, x \\notin L -> ty_trm (G & x ~ S) (open_trm x body) T.\nProof.\n  introv HdsDs dsHas DsHas.\n  lets H: (extract_ty_def_from_ty_defs HdsDs dsHas DsHas).\n  inversions* H. \nQed.\n\nLemma invert_ty_fld_inside_ty_defs: forall G ds Ds l v T,\n  ty_defs G ds Ds ->\n  defs_has ds (label_fld l) (def_fld v) ->\n  decs_has Ds (label_fld l) (dec_fld T) ->\n  (* conclusion is the premise needed to construct a ty_fld: *)\n  ty_trm G (trm_var v) T.\nProof.\n  introv HdsDs dsHas DsHas.\n  lets H: (extract_ty_def_from_ty_defs HdsDs dsHas DsHas).\n  inversions* H. \nQed.\n\nLemma decs_has_to_defs_has: forall G l ds Ds D,\n  ty_defs G ds Ds ->\n  decs_has Ds l D ->\n  exists d, defs_has ds l d.\nProof.\n  introv Ty Bi. induction Ty; unfolds decs_has, get_dec. \n  + discriminate.\n  + unfold defs_has. folds get_dec. rewrite get_def_cons. case_if.\n    - exists d. reflexivity.\n    - rewrite <- (ty_def_to_label_for_eq n H) in Bi. case_if. apply (IHTy Bi).\nQed.\n\nPrint Assumptions decs_has_to_defs_has.\n\nLemma defs_has_to_decs_has: forall G l ds Ds d,\n  ty_defs G ds Ds ->\n  defs_has ds l d ->\n  exists D, decs_has Ds l D.\nProof.\n  introv Ty dsHas. induction Ty; unfolds defs_has, get_def. \n  + discriminate.\n  + unfold decs_has. folds get_def. rewrite get_dec_cons. case_if.\n    - exists D. reflexivity.\n    - rewrite -> (ty_def_to_label_for_eq n H) in dsHas. case_if. apply (IHTy dsHas).\nQed.\n\nPrint Assumptions defs_has_to_decs_has.\n\nLemma label_for_dec_open: forall z D n,\n  label_for_dec n (open_dec z D) = label_for_dec n D.\nProof.\n  intros. destruct D; reflexivity.\nQed.\n\n(* The converse does not hold because\n   [(open_dec z D1) = (open_dec z D2)] does not imply [D1 = D2]. *)\nLemma decs_has_open: forall Ds l D z,\n  decs_has Ds l D -> decs_has (open_decs z Ds) l (open_dec z D).\nProof.\n  introv Has. induction Ds.\n  + inversion Has.\n  + unfold open_decs, open_rec_decs. fold open_rec_decs. fold open_rec_dec.\n    unfold decs_has, get_dec. case_if.\n    - unfold decs_has, get_dec in Has. rewrite label_for_dec_open in Has. case_if.\n      inversions Has. reflexivity.\n    - fold get_dec. apply IHDs. unfold decs_has, get_dec in Has.\n      rewrite label_for_dec_open in H. case_if. apply Has.\nQed.\n\n(* TODO does not hold because\n   [(open_dec z D1) = (open_dec z D2)] does not imply [D1 = D2]. *)\nAxiom decs_has_close_admitted: forall Ds l D z,\n  decs_has (open_decs z Ds) l (open_dec z D) -> decs_has Ds l D.\n\n\n(* ###################################################################### *)\n(** ** Uniqueness *)\n\nLemma exp_has_unique:\n  (forall m G T Ds1, exp m G T Ds1 -> m = pr ->\n     forall Ds2, exp pr G T Ds2 -> Ds1 = Ds2) /\\ \n  (forall m G v l D1, has m G v l D1 -> m = pr ->\n     forall D2, has pr G v l D2 -> D1 = D2).\nProof.\n  apply exp_has_mutind; intros.\n  + inversions H0. reflexivity.\n  + inversions H0. reflexivity.\n  + inversions H2. specialize (H eq_refl _ H7). inversions H. apply* (H0 eq_refl).\n  + discriminate.\n  + discriminate.\n  + inversions H1. unfold decs_has in *.\n    lets Eq: (binds_func b H3). subst.\n    specialize (H eq_refl _ H4). subst.\n    rewrite d in H5.\n    inversion H5. reflexivity.\nQed.\n\nLemma exp_unique: forall G T Ds1 Ds2,\n  exp pr G T Ds1 -> exp pr G T Ds2 -> Ds1 = Ds2.\nProof. intros. apply* exp_has_unique. Qed.\n\nLemma has_unique: forall G v l D1 D2,\n  has pr G v l D1 -> has pr G v l D2 -> D1 = D2.\nProof. intros. apply* exp_has_unique. Qed.\n\n\n(* ###################################################################### *)\n(** ** Weakening *)\n\nLemma weakening:\n   (forall m G T Ds, exp m G T Ds -> forall G1 G2 G3,\n      G = G1 & G3 ->\n      ok (G1 & G2 & G3) ->\n      exp m (G1 & G2 & G3) T Ds)\n/\\ (forall m G t l d, has m G t l d -> forall G1 G2 G3,\n      G = G1 & G3 ->\n      ok (G1 & G2 & G3) ->\n      has m (G1 & G2 & G3) t l d)\n/\\ (forall m1 m2 G T1 T2, subtyp m1 m2 G T1 T2 -> forall G1 G2 G3,\n      G = G1 & G3 ->\n      ok (G1 & G2 & G3) ->\n      subtyp m1 m2 (G1 & G2 & G3) T1 T2)\n/\\ (forall m G D1 D2, subdec m G D1 D2 -> forall G1 G2 G3,\n      G = G1 & G3 ->\n      ok (G1 & G2 & G3) ->\n      subdec m (G1 & G2 & G3) D1 D2)\n/\\ (forall m G Ds1 Ds2, subdecs m G Ds1 Ds2 -> forall G1 G2 G3,\n      G = G1 & G3 ->\n      ok (G1 & G2 & G3) ->\n      subdecs m (G1 & G2 & G3) Ds1 Ds2)\n/\\ (forall G t T, ty_trm G t T -> forall G1 G2 G3,\n      G = G1 & G3 ->\n      ok (G1 & G2 & G3) ->\n      ty_trm (G1 & G2 & G3) t T)\n/\\ (forall G d D, ty_def G d D -> forall G1 G2 G3,\n      G = G1 & G3 ->\n      ok (G1 & G2 & G3) ->\n      ty_def (G1 & G2 & G3) d D)\n/\\ (forall G ds Ds, ty_defs G ds Ds -> forall G1 G2 G3,\n      G = G1 & G3 ->\n      ok (G1 & G2 & G3) ->\n      ty_defs (G1 & G2 & G3) ds Ds).\nProof.\n  apply ty_mutind.\n  + (* case exp_top *)\n    intros. apply exp_top.\n  + (* case exp_bind *)\n    intros. apply exp_bind.\n  + (* case exp_sel *)\n    intros. apply* exp_sel.\n  + (* case has_trm *)\n    intros. apply* has_trm.\n  + (* case has_var *)\n    intros. apply* has_var.\n  + (* case has_pr *)\n    intros. subst. apply has_pr with T Ds.\n    - apply* binds_weaken.\n    - apply* H. \n    - assumption.\n  + (* case subtyp_refl *)\n    introv Has IHHas Ok Eq. subst.\n    apply* subtyp_refl.\n  + (* case subtyp_top *)\n    introv Hok123 Heq; subst.\n    apply (subtyp_top _ _).\n  + (* case subtyp_bot *)\n    introv Hok123 Heq; subst.\n    apply (subtyp_bot _ _).\n  + (* case subtyp_bind *)\n    introv Hc IH Hok123 Heq; subst.\n    apply_fresh subtyp_bind as z.\n    rewrite <- concat_assoc.\n    refine (IH z _ G1 G2 (G3 & z ~ typ_bind Ds1) _ _).\n    - auto.\n    - rewrite <- concat_assoc. reflexivity.\n    - rewrite concat_assoc. auto.\n  + (* case subtyp_asel_l *)\n    intros. subst. apply* subtyp_sel_l.\n  + (* case subtyp_asel_r *)\n    intros. subst. apply* subtyp_sel_r.\n  + (* case subtyp_tmode *)\n    introv Hst IH Hok Heq. apply subtyp_tmode. apply* IH.\n  + (* case subtyp_trans *)\n    intros. subst. apply* subtyp_trans.\n  + (* case subdec_typ *)\n    intros.\n    apply subdec_typ; gen G1 G2 G3; assumption.\n  + (* case subdec_fld *)\n    intros.\n    apply subdec_fld; gen G1 G2 G3; assumption.\n  + (* case subdec_mtd *)\n    intros.\n    apply subdec_mtd; gen G1 G2 G3; assumption.\n  + (* case subdecs_empty *)\n    intros.\n    apply subdecs_empty.\n  + (* case subdecs_push *)\n    introv Hb Hsd IHsd Hsds IHsds Hok123 Heq.\n    apply (subdecs_push n Hb).\n    apply (IHsd _ _ _ Hok123 Heq).\n    apply (IHsds _ _ _ Hok123 Heq).\n  + (* case ty_var *)\n    intros. subst. apply ty_var. apply* binds_weaken.\n  + (* case ty_sel *)\n    intros. subst. apply* ty_sel.\n  + (* case ty_call *)\n    intros. subst. apply* ty_call.\n  + (* case ty_new *)\n    intros L G ds Ds Tyds IHTyds Cb G1 G2 G3 Eq Ok. subst.\n    apply_fresh ty_new as x.\n    - assert (xL: x \\notin L) by auto.\n      specialize (IHTyds x xL G1 G2 (G3 & x ~ typ_bind Ds)).\n      rewrite <- concat_assoc. apply IHTyds.\n      * rewrite concat_assoc. reflexivity.\n      * rewrite concat_assoc. auto.\n    - exact Cb.\n  + (* case ty_sbsm *)\n    intros. apply ty_sbsm with T.\n    - apply* H.\n    - apply* H0.\n  + (* case ty_typ *)\n    intros. apply ty_typ. \n  + (* case ty_fld *)\n    intros. apply* ty_fld.\n  + (* case ty_mtd *) \n    intros. subst. rename H into IH.\n    apply_fresh ty_mtd as x.\n    rewrite <- concat_assoc.\n    refine (IH x _ G1 G2 (G3 & x ~ S) _ _).\n    - auto.\n    - symmetry. apply concat_assoc.\n    - rewrite concat_assoc. auto.\n  + (* case ty_dsnil *) \n    intros. apply ty_dsnil.\n  + (* case ty_dscons *) \n    intros. apply* ty_dscons.\nQed.\n\nPrint Assumptions weakening.\n\nLemma weaken_exp_middle: forall m G1 G2 G3 T Ds,\n  ok (G1 & G2 & G3) -> exp m (G1 & G3) T Ds -> exp m (G1 & G2 & G3) T Ds.\nProof.\n  intros. apply* weakening.\nQed.\n\nLemma weaken_exp_end: forall m G1 G2 T Ds,\n  ok (G1 & G2) -> exp m G1 T Ds -> exp m (G1 & G2) T Ds.\nProof.\n  introv Ok Exp.\n  assert (Eq1: G1 = G1 & empty) by (rewrite concat_empty_r; reflexivity).\n  assert (Eq2: G1 & G2 = G1 & G2 & empty) by (rewrite concat_empty_r; reflexivity).\n  rewrite Eq1 in Exp. rewrite Eq2 in Ok. rewrite Eq2.\n  apply (weaken_exp_middle Ok Exp).\nQed.\n\nLemma weaken_subtyp_middle: forall m1 m2 G1 G2 G3 S U,\n  ok (G1 & G2 & G3) -> \n  subtyp m1 m2 (G1      & G3) S U ->\n  subtyp m1 m2 (G1 & G2 & G3) S U.\nProof.\n  destruct weakening as [_ [_ [W _]]].\n  introv Hok123 Hst.\n  specialize (W m1 m2 (G1 & G3) S U Hst).\n  specialize (W G1 G2 G3 eq_refl Hok123).\n  apply W.\nQed.\n\nLemma env_add_empty: forall (P: ctx -> Prop) (G: ctx), P G -> P (G & empty).\nProof.\n  intros.\n  assert ((G & empty) = G) by apply concat_empty_r.\n  rewrite -> H0. assumption.\nQed.  \n\nLemma env_remove_empty: forall (P: ctx -> Prop) (G: ctx), P (G & empty) -> P G.\nProof.\n  intros.\n  assert ((G & empty) = G) by apply concat_empty_r.\n  rewrite <- H0. assumption.\nQed.\n\nLemma weaken_subtyp_end: forall m1 m2 G1 G2 S U,\n  ok (G1 & G2) -> \n  subtyp m1 m2 G1        S U ->\n  subtyp m1 m2 (G1 & G2) S U.\nProof.\n  introv Hok Hst.\n  apply (env_remove_empty (fun G0 => subtyp m1 m2 G0 S U) (G1 & G2)).\n  apply weaken_subtyp_middle.\n  apply (env_add_empty (fun G0 => ok G0) (G1 & G2) Hok).\n  apply (env_add_empty (fun G0 => subtyp m1 m2 G0 S U) G1 Hst).\nQed.\n\nLemma weaken_has_end: forall m G1 G2 t l d,\n  ok (G1 & G2) -> has m G1 t l d -> has m (G1 & G2) t l d.\nProof.\n  intros.\n  destruct weakening as [_ [W _]].\n  rewrite <- (concat_empty_r (G1 & G2)).\n  apply (W m (G1 & empty)); rewrite* concat_empty_r.\nQed.\n\nLemma weaken_subdec_middle: forall m G1 G2 G3 S U,\n  ok (G1 & G2 & G3) -> \n  subdec m (G1      & G3) S U ->\n  subdec m (G1 & G2 & G3) S U.\nProof.\n  destruct weakening as [_ [_ [_ [W _]]]].\n  introv Hok123 Hst.\n  specialize (W m (G1 & G3) S U Hst).\n  specialize (W G1 G2 G3 eq_refl Hok123).\n  apply W.\nQed.\n\nLemma weaken_subdec_end: forall m G1 G2 D1 D2,\n  ok (G1 & G2) -> \n  subdec m G1        D1 D2 ->\n  subdec m (G1 & G2) D1 D2.\nProof.\n  introv Hok Hsd.\n  apply (env_remove_empty (fun G0 => subdec m G0 D1 D2) (G1 & G2)).\n  apply weaken_subdec_middle.\n  apply (env_add_empty (fun G0 => ok G0) (G1 & G2) Hok).\n  apply (env_add_empty (fun G0 => subdec m G0 D1 D2) G1 Hsd).\nQed.\n\nLemma weaken_ty_trm_end: forall G1 G2 e T,\n  ok (G1 & G2) -> ty_trm G1 e T -> ty_trm (G1 & G2) e T.\nProof.\n  intros.\n  destruct weakening as [_ [_ [_ [_ [_ [W _]]]]]].\n  rewrite <- (concat_empty_r (G1 & G2)).\n  apply (W (G1 & empty)); rewrite* concat_empty_r.\nQed.\n\nLemma weaken_ty_def_end: forall G1 G2 i d,\n  ok (G1 & G2) -> ty_def G1 i d -> ty_def (G1 & G2) i d.\nProof.\n  intros.\n  destruct weakening as [_ [_ [_ [_ [_ [_ [W _]]]]]]].\n  rewrite <- (concat_empty_r (G1 & G2)).\n  apply (W (G1 & empty)); rewrite* concat_empty_r.\nQed.\n\nLemma weaken_ty_defs_end: forall G1 G2 is Ds,\n  ok (G1 & G2) -> ty_defs G1 is Ds -> ty_defs (G1 & G2) is Ds.\nProof.\n  intros.\n  destruct weakening as [_ [_ [_ [_ [_ [_ [_ W]]]]]]].\n  rewrite <- (concat_empty_r (G1 & G2)).\n  apply (W (G1 & empty)); rewrite* concat_empty_r.\nQed.\n\nLemma weaken_ty_trm_middle: forall G1 G2 G3 t T,\n  ok (G1 & G2 & G3) -> ty_trm (G1 & G3) t T -> ty_trm (G1 & G2 & G3) t T.\nProof.\n  intros. apply* weakening.\nQed.\n\nLemma weaken_ty_def_middle: forall G1 G2 G3 d D,\n  ty_def (G1 & G3) d D -> ok (G1 & G2 & G3) -> ty_def (G1 & G2 & G3) d D.\nProof.\n  intros. apply* weakening.\nQed.\n\nLemma weaken_ty_defs_middle: forall G1 G2 G3 ds Ds,\n  ty_defs (G1 & G3) ds Ds -> ok (G1 & G2 & G3) -> ty_defs (G1 & G2 & G3) ds Ds.\nProof.\n  intros. apply* weakening.\nQed.\n\n\n(* ###################################################################### *)\n(** ** The substitution principle *)\n\n(*\n\nwithout dependent types:\n\n                  G, x: S |- e : T      G |- u : S\n                 ----------------------------------\n                            G |- [u/x]e : T\n\nwith dependent types:\n\n                  G1, x: S, G2 |- t : T      G1 |- y : S\n                 ---------------------------------------\n                      G1, [y/x]G2 |- [y/x]t : [y/x]T\n\n\nNote that in general, u is a term, but for our purposes, it suffices to consider\nthe special case where u is a variable.\n*)\n\nLemma subst_label_for_dec: forall n x y D,\n  label_for_dec n (subst_dec x y D) = label_for_dec n D.\nProof.\n  intros. destruct D; reflexivity.\nQed.\n\nLemma subst_decs_has: forall x y Ds l D,\n  decs_has Ds l D ->\n  decs_has (subst_decs x y Ds) l (subst_dec x y D).\nProof.\n  introv Has. induction Ds.\n  + inversion Has.\n  + unfold subst_decs, decs_has, get_dec. fold subst_decs subst_dec get_dec.\n    rewrite subst_label_for_dec.\n    unfold decs_has, get_dec in Has. fold get_dec in Has. case_if.\n    - inversions Has. reflexivity.\n    - apply* IHDs.\nQed.\n\nLemma subst_binds: forall x y v T G,\n  binds v T G ->\n  binds v (subst_typ x y T) (subst_ctx x y G).\nProof.\n  introv Bi. unfold subst_ctx. apply binds_map. exact Bi.\nQed.\n\nLemma subst_principles: forall y S,\n   (forall m G T Ds, exp m G T Ds -> forall G1 G2 x,\n     m = ip ->\n     G = G1 & x ~ S & G2 ->\n     ty_trm G1 (trm_var (avar_f y)) S ->\n     ok (G1 & x ~ S & G2) ->\n     exp ip (G1 & (subst_ctx x y G2)) (subst_typ x y T) (subst_decs x y Ds))\n/\\ (forall m G t l D, has m G t l D -> forall G1 G2 x,\n     m = ip ->\n     G = (G1 & (x ~ S) & G2) ->\n     ty_trm G1 (trm_var (avar_f y)) S ->\n     ok (G1 & (x ~ S) & G2) ->\n     has ip (G1 & (subst_ctx x y G2)) (subst_trm x y t) l (subst_dec x y D))\n/\\ (forall m1 m2 G T U, subtyp m1 m2 G T U -> forall G1 G2 x,\n     m1 = ip ->\n     G = (G1 & (x ~ S) & G2) ->\n     ty_trm G1 (trm_var (avar_f y)) S ->\n     ok (G1 & (x ~ S) & G2) ->\n     subtyp ip m2 (G1 & (subst_ctx x y G2)) (subst_typ x y T) (subst_typ x y U))\n/\\ (forall m G D1 D2, subdec m G D1 D2 -> forall G1 G2 x,\n     m = ip ->\n     G = (G1 & (x ~ S) & G2) ->\n     ty_trm G1 (trm_var (avar_f y)) S ->\n     ok (G1 & (x ~ S) & G2) ->\n     subdec ip (G1 & (subst_ctx x y G2)) (subst_dec x y D1) (subst_dec x y D2))\n/\\ (forall m G Ds1 Ds2, subdecs m G Ds1 Ds2 -> forall G1 G2 x,\n     m = ip ->\n     G = (G1 & (x ~ S) & G2) ->\n     ty_trm G1 (trm_var (avar_f y)) S ->\n     ok (G1 & (x ~ S) & G2) ->\n     subdecs ip (G1 & (subst_ctx x y G2)) (subst_decs x y Ds1) (subst_decs x y Ds2))\n/\\ (forall G t T, ty_trm G t T -> forall G1 G2 x,\n     G = (G1 & (x ~ S) & G2) ->\n     ty_trm G1 (trm_var (avar_f y)) S ->\n     ok (G1 & (x ~ S) & G2) ->\n     ty_trm (G1 & (subst_ctx x y G2)) (subst_trm x y t) (subst_typ x y T))\n/\\ (forall G d D, ty_def G d D -> forall G1 G2 x,\n     G = (G1 & (x ~ S) & G2) ->\n     ty_trm G1 (trm_var (avar_f y)) S ->\n     ok (G1 & (x ~ S) & G2) ->\n     ty_def (G1 & (subst_ctx x y G2)) (subst_def x y d) (subst_dec x y D))\n/\\ (forall G ds Ds, ty_defs G ds Ds -> forall G1 G2 x,\n     G = (G1 & (x ~ S) & G2) ->\n     ty_trm G1 (trm_var (avar_f y)) S ->\n     ok (G1 & (x ~ S) & G2) ->\n     ty_defs (G1 & (subst_ctx x y G2)) (subst_defs x y ds) (subst_decs x y Ds)).\nProof.\n  intros y S. apply ty_mutind.\n  (* case exp_top *)\n  + intros. simpl. apply exp_top.\n  (* case exp_bind *)\n  + intros. simpl. apply exp_bind.\n  (* case exp_sel *)\n  + intros m G v L Lo Hi Ds Has IHHas Exp IHExp G1 G2 x Eqm EqG Tyy Ok. subst.\n    specialize (IHHas _ _ _ eq_refl eq_refl Tyy Ok).\n    specialize (IHExp _ _ _ eq_refl eq_refl Tyy Ok).\n    unfold subst_typ. unfold subst_pth. unfold subst_avar. case_if.\n    - simpl in IHHas. case_if.\n      apply (exp_sel IHHas IHExp).\n    - simpl in IHHas. case_if.\n      apply (exp_sel IHHas IHExp).\n  + (* case has_trm *)\n    intros G t T Ds l D Ty IHTy Exp IHExp Has Clo G1 G2 x Eqm EqG Bi Ok.\n    subst. specialize (IHTy _ _ _ eq_refl Bi Ok).\n    apply has_trm with (subst_typ x y T) (subst_decs x y Ds).\n    - exact IHTy.\n    - apply* IHExp.\n    - apply* subst_decs_has.\n    - intro z. specialize (Clo z). admit.\n  + (* case has_var *)\n    intros G z T Ds l D Ty IHTy Exp IHExp Has G1 G2 x Eqm EqG Bi Ok.\n    subst. specialize (IHTy _ _ _ eq_refl Bi Ok). simpl in *. case_if.\n    - (* case z = x *)\n      rewrite (subst_open_commute_dec x y x D). unfold subst_fvar. case_if.\n      apply has_var with (subst_typ x y T) (subst_decs x y Ds).\n      * exact IHTy.\n      * apply* IHExp.\n      * apply (subst_decs_has x y Has).\n    - (* case z <> x *)\n      rewrite (subst_open_commute_dec x y z D). unfold subst_fvar. case_if.\n      apply has_var with (subst_typ x y T) (subst_decs x y Ds).\n      * exact IHTy.\n      * apply* IHExp.\n      * apply (subst_decs_has x y Has).\n  + (* case has_pr *)\n    intros. discriminate.\n  + (* case subtyp_refl *)\n    intros m G v L Lo Hi Has IHHas G1 G2 x Eqm EqG Tyy Ok. subst.\n    specialize (IHHas _ _ _ eq_refl eq_refl Tyy Ok).\n    unfold subst_dec in IHHas. fold subst_typ in IHHas.\n    unfold subst_trm, subst_avar in IHHas.\n    simpl. case_if; apply (subtyp_refl IHHas).\n  + (* case subtyp_top *)\n    intros. simpl. apply subtyp_top.\n  + (* case subtyp_bot *)\n    intros. simpl. apply subtyp_bot.\n  + (* case subtyp_bind *)\n    intros L m G Ds1 Ds2 Sds IH G1 G2 x Eqm EqG Bi Ok. subst.\n    apply_fresh subtyp_bind as z. fold subst_decs.\n    assert (zL: z \\notin L) by auto.\n    specialize (IH z zL G1 (G2 & z ~ typ_bind Ds1) x).\n    rewrite concat_assoc in IH.\n    specialize (IH eq_refl eq_refl Bi).\n    unfold subst_ctx in IH. rewrite map_push in IH. simpl in IH.\n    rewrite concat_assoc in IH.\n    rewrite (subst_open_commute_decs x y z Ds1) in IH.\n    rewrite (subst_open_commute_decs x y z Ds2) in IH.\n    unfold subst_fvar in IH.\n    assert (x <> z) by auto. case_if.\n    unfold subst_ctx. apply IH. admit.\n  + (* case subtyp_sel_l *)\n    intros m G v L Lo Hi T Has IHHas St IHSt G1 G2 x Eqm EqG Bi Ok. subst.\n    specialize (IHSt _ _ _ eq_refl eq_refl Bi Ok).\n    specialize (IHHas _ _ _ eq_refl eq_refl Bi Ok).\n    simpl in *.\n    case_if; apply (subtyp_sel_l IHHas IHSt).\n  + (* case subtyp_sel_r *)\n    intros m G v L Lo Hi T Has IHHas St1 IHSt1 St2 IHSt2 G1 G2 x Eqm EqG Bi Ok. subst.\n    specialize (IHSt1 _ _ _ eq_refl eq_refl Bi Ok).\n    specialize (IHSt2 _ _ _ eq_refl eq_refl Bi Ok).\n    specialize (IHHas _ _ _ eq_refl eq_refl Bi Ok).\n    simpl in *.\n    case_if; apply (subtyp_sel_r IHHas IHSt1 IHSt2).\n  + (* case subtyp_tmode *)\n    intros m G T1 T2 St IH G1 G2 x Eqm EqG Bi Ok. subst.\n    specialize (IH _ _ _ eq_refl eq_refl Bi Ok).\n    apply (subtyp_tmode IH).\n  + (* case subtyp_trans *)\n    intros m G T1 T2 T3 St12 IH12 St23 IH23 G1 G2 x Eqm EqG Bi Ok. subst.\n    apply* subtyp_trans.\n  + (* case subdec_typ *)\n    intros. apply* subdec_typ.\n  + (* case subdec_fld *)\n    intros. apply* subdec_fld.\n  + (* case subdec_mtd *)\n    intros. apply* subdec_mtd.\n  + (* case subdecs_empty *)\n    intros. apply subdecs_empty.\n  + (* case subdecs_push *)\n    intros m G n Ds1 Ds2 D1 D2 Has Sd IH1 Sds IH2 G1 G2 x Eq1 Eq2 Bi Ok. subst.\n    specialize (IH1 _ _ _ eq_refl eq_refl Bi Ok).\n    specialize (IH2 _ _ _ eq_refl eq_refl Bi Ok).\n    apply (subst_decs_has x y) in Has.\n    rewrite <- (subst_label_for_dec n x y D2) in Has.\n    apply subdecs_push with (subst_dec x y D1); \n      fold subst_dec; fold subst_decs; assumption.\n  + (* case ty_var *)\n    intros G z T Biz G1 G2 x EqG Biy Ok.\n    subst G. unfold subst_trm, subst_avar. case_var.\n    - (* case z = x *)\n      assert (EqST: T = S) by apply (binds_middle_eq_inv Biz Ok). subst.\n      assert (yG2: y # (subst_ctx x y G2)) by admit.\n      assert (xG1: x # G1) by admit.\n      assert (Eq: (subst_typ x y S) = S) by admit.\n      rewrite Eq. \n      apply weaken_ty_trm_end.\n      * unfold subst_ctx. auto.\n      * assumption.\n    - (* case z <> x *)\n      apply ty_var. admit. (* TODO! *)\n  (* case ty_sel *)\n  + intros G t l T Has IH G1 G2 x Eq Bi Ok. apply* ty_sel.\n  (* case ty_call *)\n  + intros G t m U V u Has IHt Tyu IHu G1 G2 x Eq Bi Ok. apply* ty_call.\n  (* case ty_new *)\n  + intros L G ds Ds Tyds IHTyds Cb G1 G2 x Eq Bi Ok. subst G.\n    apply_fresh ty_new as z.\n    - fold subst_defs.\n      lets C: (@subst_open_commute_defs x y z ds).\n      unfolds open_defs. unfold subst_fvar in C. case_var.\n      rewrite <- C.\n      lets D: (@subst_open_commute_decs x y z Ds).\n      unfolds open_defs. unfold subst_fvar in D. case_var.\n      rewrite <- D.\n      rewrite <- concat_assoc.\n      assert (zL: z \\notin L) by auto.\n      specialize (IHTyds z zL G1 (G2 & z ~ typ_bind Ds) x). rewrite concat_assoc in IHTyds.\n      specialize (IHTyds eq_refl Bi).\n      unfold subst_ctx in IHTyds. rewrite map_push in IHTyds. unfold subst_ctx.\n      apply IHTyds. auto.\n    - admit. (* TODO holds *)\n  (* case ty_sbsm *)\n  + intros G t T U Ty IHTy St IHSt G1 G2 x Eq Bi Ok. subst.\n    apply ty_sbsm with (subst_typ x y T).\n    - apply* IHTy.\n    - apply* IHSt.\n  (* case ty_typ *)\n  + intros. simpl. apply ty_typ.\n  (* case ty_fld *)\n  + intros. apply* ty_fld.\n  (* case ty_mtd *)\n  + intros L G T U t Ty IH G1 G2 x Eq Bi Ok. subst.\n    apply_fresh ty_mtd as z. fold subst_trm. fold subst_typ.\n    lets C: (@subst_open_commute_trm x y z t).\n    unfolds open_trm. unfold subst_fvar in C. case_var.\n    rewrite <- C.\n    rewrite <- concat_assoc.\n    assert (zL: z \\notin L) by auto.\n    specialize (IH z zL G1 (G2 & z ~ T) x). rewrite concat_assoc in IH.\n    specialize (IH eq_refl Bi).\n    unfold subst_ctx in IH. rewrite map_push in IH. unfold subst_ctx.\n    apply IH. auto.\n  (* case ty_dsnil *)\n  + intros. apply ty_dsnil.\n  (* case ty_dscons *)\n  + intros. apply* ty_dscons.\nQed.\n\nPrint Assumptions subst_principles.\n\nLemma trm_subst_principle: forall G x y t S T,\n  ok (G & x ~ S) ->\n  ty_trm (G & x ~ S) t T ->\n  ty_trm G (trm_var (avar_f y)) S ->\n  ty_trm G (subst_trm x y t) (subst_typ x y T).\nProof.\n  introv Hok tTy yTy. destruct (subst_principles y S) as [_ [_ [_ [_ [_ [P _]]]]]].\n  specialize (P _ t T tTy G empty x).\n  unfold subst_ctx in P. rewrite map_empty in P.\n  repeat (progress (rewrite concat_empty_r in P)).\n  apply* P.\nQed.\n\nLemma subdecs_subst_principle: forall G x y S Ds1 Ds2,\n  ok (G & x ~ S) ->\n  subdecs ip (G & x ~ S) Ds1 Ds2 ->\n  ty_trm G (trm_var (avar_f y)) S ->\n  subdecs ip G (subst_decs x y Ds1) (subst_decs x y Ds2).\nProof.\n  introv Hok Sds yTy. destruct (subst_principles y S) as [_ [_ [_ [_ [P _]]]]].\n  specialize (P _ _ Ds1 Ds2 Sds G empty x).\n  unfold subst_ctx in P. rewrite map_empty in P.\n  repeat (progress (rewrite concat_empty_r in P)).\n  apply* P.\nQed.\n\n\n(* ###################################################################### *)\n(** ** Narrowing *)\n\nLemma narrow_ty_trm: forall G y T1 T2 u U,\n  ok (G & y ~ T2) ->\n  subtyp ip oktrans G T1 T2 ->\n  ty_trm (G & y ~ T2) u U ->\n  ty_trm (G & y ~ T1) u U.\nProof.\n  introv Ok St Tyu.\n  (* Step 1: rename *)\n  pick_fresh z.\n  assert (Okzy: ok (G & z ~ T2 & y ~ T2)) by admit.\n  apply (weaken_ty_trm_middle Okzy) in Tyu.\n  assert (Biz: binds z T2 (G & z ~ T2)) by auto.\n  lets Tyz: (ty_var Biz).\n  lets Tyu': (trm_subst_principle Okzy Tyu Tyz).\n  (* Step 2: the actual substitution *)\n  assert (Biy: binds y T1 (G & y ~ T1)) by auto.\n  assert (Ok': ok (G & y ~ T1)) by admit.\n  apply (weaken_subtyp_end Ok') in St.\n  lets Tyy: (ty_sbsm (ty_var Biy) St).\n  assert (Okyz: ok (G & y ~ T1 & z ~ T2)) by auto.\n  apply (weaken_ty_trm_middle Okyz) in Tyu'.\n  lets Tyu'': (trm_subst_principle Okyz Tyu' Tyy).\n  rewrite subst_trm_undo, subst_typ_undo in Tyu''; auto.\nQed.\n\nLemma narrow_subdec_adm: forall G y T1 T2 D1 D2,\n  ok (G & y ~ T2) ->\n  subtyp ip oktrans G T1 T2 ->\n  subdec ip (G & y ~ T2) D1 D2 ->\n  subdec ip (G & y ~ T1) D1 D2.\nAdmitted.\n\nLemma narrow_subdecs_adm: forall G y T1 T2 Ds1 Ds2,\n  ok (G & y ~ T2) ->\n  subtyp ip oktrans G T1 T2 ->\n  subdecs ip (G & y ~ T2) Ds1 Ds2 ->\n  subdecs ip (G & y ~ T1) Ds1 Ds2.\nAdmitted.\n\n\n(* ###################################################################### *)\n(** ** More inversion lemmas *)\n\nLemma invert_var_has_dec: forall G x l D,\n  has ip G (trm_var (avar_f x)) l D ->\n  exists T Ds D', ty_trm G (trm_var (avar_f x)) T /\\\n                  exp ip G T Ds /\\\n                  decs_has Ds l D' /\\\n                  open_dec x D' = D.\nProof.\n  introv Has. inversions Has.\n  (* case has_trm *)\n  + subst. exists T Ds D. auto.\n  (* case has_var *)\n  + exists T Ds D0. auto.\nQed.\n\nLemma invert_has: forall G t l D,\n   has ip G t l D ->\n   (exists T Ds,      ty_trm G t T /\\\n                      exp ip G T Ds /\\\n                      decs_has Ds l D /\\\n                      (forall z : var, open_dec z D = D))\n\\/ (exists x T Ds D', t = (trm_var (avar_f x)) /\\\n                      ty_trm G (trm_var (avar_f x)) T /\\\n                      exp ip G T Ds /\\\n                      decs_has Ds l D' /\\\n                      open_dec x D' = D).\nProof.\n  introv Has. inversions Has.\n  (* case has_trm *)\n  + subst. left. exists T Ds. auto.\n  (* case has_var *)\n  + right. exists v T Ds D0. auto.\nQed.\n\nLemma invert_var_has_dec_typ: forall G x l S U,\n  has ip G (trm_var (avar_f x)) l (dec_typ S U) ->\n  exists X Ds S' U', ty_trm G (trm_var (avar_f x)) X /\\\n                     exp ip G X Ds /\\\n                     decs_has Ds l (dec_typ S' U') /\\\n                     open_typ x S' = S /\\\n                     open_typ x U' = U.\nProof.\n  introv Has. apply invert_var_has_dec in Has.\n  destruct Has as [X [Ds [D [Tyx [Exp [Has Eq]]]]]].\n  destruct D as [ Lo Hi | T' | S' U' ]; try solve [ inversion Eq ].\n  unfold open_dec, open_rec_dec in Eq. fold open_rec_typ in Eq.\n  inversion Eq as [Eq'].\n  exists X Ds Lo Hi. auto.\nQed.\n\nLemma invert_var_has_dec_fld: forall G x l T,\n  has ip G (trm_var (avar_f x)) l (dec_fld T) ->\n  exists X Ds T', ty_trm G (trm_var (avar_f x)) X /\\\n                  exp ip G X Ds /\\\n                  decs_has Ds l (dec_fld T') /\\\n                  open_typ x T' = T.\nProof.\n  introv Has. apply invert_var_has_dec in Has.\n  destruct Has as [X [Ds [D [Tyx [Exp [Has Eq]]]]]].\n  destruct D as [ Lo Hi | T' | T1 T2 ]; try solve [ inversion Eq ].\n  unfold open_dec, open_rec_dec in Eq. fold open_rec_typ in Eq.\n  inversion Eq as [Eq'].\n  exists X Ds T'. auto.\nQed.\n\nLemma invert_var_has_dec_mtd: forall G x l S U,\n  has ip G (trm_var (avar_f x)) l (dec_mtd S U) ->\n  exists X Ds S' U', ty_trm G (trm_var (avar_f x)) X /\\\n                     exp ip G X Ds /\\\n                     decs_has Ds l (dec_mtd S' U') /\\\n                     open_typ x S' = S /\\\n                     open_typ x U' = U.\nProof.\n  introv Has. apply invert_var_has_dec in Has.\n  destruct Has as [X [Ds [D [Tyx [Exp [Has Eq]]]]]].\n  destruct D as [ Lo Hi | T' | S' U' ]; try solve [ inversion Eq ].\n  unfold open_dec, open_rec_dec in Eq. fold open_rec_typ in Eq.\n  inversion Eq as [Eq'].\n  exists X Ds S' U'. auto.\nQed.\n\nLemma invert_has_pr: forall G x l D,\n  has pr G (trm_var (avar_f x)) l D ->\n  exists T Ds D', binds x T G /\\\n                  exp pr G T Ds /\\\n                  decs_has Ds l D' /\\\n                  D = open_dec x D'.\nProof.\n  introv Has. inversions Has. exists T Ds D0. auto.\nQed.\n\nLemma invert_exp_sel: forall m G v L Ds,\n  exp m G (typ_sel (pth_var (avar_f v)) L) Ds ->\n  exists Lo Hi, has m G (trm_var (avar_f v)) L (dec_typ Lo Hi) /\\\n                exp m G Hi Ds.\nProof.\n  introv Exp. inversions Exp. exists Lo Hi. auto.\nQed.\n\nLemma subtyp_refl_all: forall m1 m2 G T, subtyp m1 m2 G T T.\nAdmitted.\n\nLemma invert_ty_var: forall G x T,\n  ty_trm G (trm_var (avar_f x)) T ->\n  exists T', subtyp ip oktrans G T' T /\\ binds x T' G.\nProof.\n  introv Ty. gen_eq t: (trm_var (avar_f x)). gen x.\n  induction Ty; intros x' Eq; try (solve [ discriminate ]).\n  + inversions Eq. exists T. apply (conj (subtyp_refl_all _ _ _ _)). auto.\n  + subst. specialize (IHTy _ eq_refl). destruct IHTy as [T' [St Bi]].\n    exists T'. split.\n    - apply subtyp_trans with T; assumption.\n    - exact Bi.\nQed.\n\nLemma invert_ty_sel_var: forall G x l T,\n  ty_trm G (trm_sel (trm_var (avar_f x)) l) T ->\n  has ip G (trm_var (avar_f x)) (label_fld l) (dec_fld T).\nProof.\n  introv Ty. gen_eq t0: (trm_sel (trm_var (avar_f x)) l). gen x l.\n  induction Ty; try (solve [ intros; discriminate ]).\n  (* base case: no subsumption *)\n  + intros x l0 Eq. inversions Eq. assumption.\n  (* step: subsumption *)\n  + intros x l Eq. subst. specialize (IHTy _ _ eq_refl).\n    apply invert_var_has_dec_fld in IHTy.\n    destruct IHTy as [X [Ds [T' [Tyx [Exp [Has Eq]]]]]].\n    (*\n    assert Tyx': ty_trm G (trm_var (avar_f x)) (ty_or X (typ_bind (dec_fld U)))\n      by subsumption\n    then the expansion of (ty_or X (typ_bind (dec_fld U))) has (dec_fld (t_or T U))\n    since T <: U, (t_or T U) is kind of the same as U <-- but not enough!\n    *)\nAbort.\n\n(* TODO does not hold currently! *)\nAxiom top_subtyp_of_empty_bind: forall m1 m2 G, \n  subtyp m1 m2 G typ_top (typ_bind decs_nil).\n\nLemma exp_to_subtyp: forall G T Ds,\n  exp ip G T Ds ->\n  subtyp ip oktrans G T (typ_bind Ds).\nProof.\n  introv Exp. gen_eq m: ip. induction Exp; intro Eq; subst.\n  + apply top_subtyp_of_empty_bind.\n  + apply subtyp_refl_all.\n  + specialize (IHExp eq_refl). apply subtyp_tmode. apply (subtyp_sel_l H IHExp).\nQed.\n\nLemma invert_ty_sel: forall G t l T,\n  ty_trm G (trm_sel t l) T ->\n  exists T', subtyp ip oktrans G T' T /\\ has ip G t (label_fld l) (dec_fld T').\nProof.\n  introv Ty. gen_eq t0: (trm_sel t l). gen t l.\n  induction Ty; intros t' l' Eq; try (solve [ discriminate ]).\n  + inversions Eq. exists T. apply (conj (subtyp_refl_all _ _ _ _)). auto.\n  + subst. rename t' into t, l' into l. specialize (IHTy _ _ eq_refl).\n    destruct IHTy as [T' [St Has]]. exists T'. split.\n    - apply subtyp_trans with T; assumption.\n    - exact Has.\nQed.\n\nLemma invert_ty_call: forall G t m V u,\n  ty_trm G (trm_call t m u) V ->\n  exists U, has ip G t (label_mtd m) (dec_mtd U V) /\\ ty_trm G u U.\nProof.\n  intros. inversions H.\n  + eauto.\n  + admit. (* subsumption case *)\nAbort.\n\nLemma invert_ty_call: forall G t m V2 u,\n  ty_trm G (trm_call t m u) V2 ->\n  exists U V1, has ip G t (label_mtd m) (dec_mtd U V1)\n               /\\ subtyp ip oktrans G V1 V2\n               /\\ ty_trm G u U.\nProof.\n  introv Ty. gen_eq e: (trm_call t m u). gen t m u.\n  induction Ty; intros t0 m0 u0 Eq; try solve [ discriminate ]; symmetry in Eq.\n  + (* case ty_call *)\n    inversions Eq. exists U V. lets StV: (subtyp_refl_all ip oktrans G V). auto.\n  + (* case ty_sbsm *)\n    subst t. specialize (IHTy _ _ _ eq_refl).\n    rename t0 into t, m0 into m, u0 into u, U into V3, T into V2.\n    destruct IHTy as [U [V1 [Has [St12 Tyu]]]].\n    exists U V1.\n    lets St13: (subtyp_trans St12 H).\n    auto.\nQed.\n\nLemma invert_ty_new: forall G ds Ds T2,\n  ty_trm G (trm_new Ds ds) T2 ->\n  subtyp ip oktrans G (typ_bind Ds) T2 /\\\n  exists L, (forall x, x \\notin L ->\n               ty_defs (G & x ~ typ_bind Ds) (open_defs x ds) (open_decs x Ds)) /\\\n            cbounds_decs Ds.\nProof.\n  introv Ty. gen_eq t0: (trm_new Ds ds). gen Ds ds.\n  induction Ty; intros Ds' ds' Eq; try (solve [ discriminate ]); symmetry in Eq.\n  + (* case ty_new *)\n    inversions Eq. apply (conj (subtyp_refl_all _ _ _ _)).\n    exists L. auto.\n  + (* case ty_sbsm *)\n    subst. rename Ds' into Ds, ds' into ds. specialize (IHTy _ _ eq_refl).\n    destruct IHTy as [St IHTy].\n    apply (conj (subtyp_trans St H) IHTy).\nQed.\n\n(* Note: This is only for notrans mode. Proving it for oktrans mode is the main\n   challenge of the whole proof. *)\nLemma invert_subtyp_bind: forall m G Ds1 Ds2,\n  subtyp m notrans G (typ_bind Ds1) (typ_bind Ds2) ->\n  exists L, forall z, z \\notin L ->\n            subdecs m (G & z ~ typ_bind Ds1) (open_decs z Ds1) (open_decs z Ds2).\nProof.\n  introv St. inversions St. exists L. assumption.\nQed.\n\nLemma invert_wf_sto_with_weakening: forall s G,\n  wf_sto s G ->\n  forall x ds Ds T,\n    binds x (object Ds ds) s -> \n    binds x T G \n    -> T = (typ_bind Ds) \n    /\\ ty_defs G (open_defs x ds) (open_decs x Ds)\n    /\\ cbounds_decs Ds.\nProof.\n  introv Wf Bs BG.\n  lets P: (invert_wf_sto Wf).\n  specialize (P x ds Ds T Bs BG).\n  destruct P as [EqT [G1 [G2 [EqG [Ty F]]]]]. subst.\n  apply (conj eq_refl).\n  lets Ok: (wf_sto_to_ok_G Wf).\n  split.\n  + apply (weaken_ty_defs_end Ok Ty).\n  + exact F.\nQed.\n\nLemma invert_wf_sto_with_sbsm: forall s G,\n  wf_sto s G ->\n  forall x ds Ds T, \n    binds x (object Ds ds) s ->\n    ty_trm G (trm_var (avar_f x)) T (* <- instead of binds *)\n    -> subtyp ip oktrans G (typ_bind Ds) T\n    /\\ ty_defs G (open_defs x ds) (open_decs x Ds)\n    /\\ cbounds_decs Ds.\nProof.\n  introv Wf Bis Tyx.\n  apply invert_ty_var in Tyx. destruct Tyx as [T'' [St BiG]].\n  destruct (invert_wf_sto_with_weakening Wf Bis BiG) as [EqT [Tyds F]].\n  subst T''.\n  lets Ok: (wf_sto_to_ok_G Wf).\n  apply (conj St).\n  auto.\nQed.\n\nLemma collapse_bounds: forall G v l Lo Hi,\n  cbounds_ctx G ->\n  has pr G (trm_var (avar_f v)) l (dec_typ Lo Hi) ->\n  Lo = Hi.\nProof.\n  introv Cb Has. induction Cb.\n  + inversions Has. false (binds_empty_inv H1).\n  + apply invert_has_pr in Has. destruct Has as [T0 [Ds [D [Bi [Exp [DsHas Eq]]]]]].\n    apply binds_push_inv in Bi. destruct Bi as [[Eq1 Eq2] | [Ne Bi]].\n    - (* case x = v *)\n      subst.\nAdmitted. (* TODO should hold *)\n\n\n(* ------------------------------------------------------------------------- *)\n(* ------------------------------------------------------------------------- *)\n(* ------------------------------------------------------------------------- *)\n\n(* subdecs_refl does not hold, because subdecs requires that for each dec in rhs\n   (including hidden ones), there is an unhidden one in lhs *)\n(* or that there are no hidden decs in rhs *)\nLemma subdecs_refl: forall m G Ds,\n  subdecs m G Ds Ds.\nProof.\nAdmitted. (* TODO does not hold!! *)\n\nLemma decs_has_preserves_sub: forall m G Ds1 Ds2 l D2,\n  decs_has Ds2 l D2 ->\n  subdecs m G Ds1 Ds2 ->\n  exists D1, decs_has Ds1 l D1 /\\ subdec m G D1 D2.\nProof.\n  introv Has Sds. induction Ds2.\n  + inversion Has.\n  + unfold decs_has, get_dec in Has. inversions Sds. case_if.\n    - inversions Has. exists D1. auto.\n    - fold get_dec in Has. apply* IHDs2.\nQed.\n\nLemma decs_has_preserves_sub_D1_known: forall m G Ds1 Ds2 l D1 D2,\n  decs_has Ds1 l D1 ->\n  decs_has Ds2 l D2 ->\n  subdecs m G Ds1 Ds2 ->\n  subdec m G D1 D2.\nProof.\n  introv Has1 Has2 Sds. induction Ds2.\n  + inversion Has2.\n  + unfold decs_has, get_dec in Has2. inversions Sds. case_if.\n    - inversions Has2. rename H5 into Has1'.\n      unfold decs_has in Has1, Has1'.\n      rewrite Has1' in Has1. inversions Has1. assumption.\n    - fold get_dec in Has2. apply* IHDs2.\nQed.\n\nLemma subdec_trans: forall m G D1 D2 D3,\n  subdec m G D1 D2 -> subdec m G D2 D3 -> subdec m G D1 D3.\nProof.\n  introv H12 H23. inversions H12; inversions H23; constructor;\n  solve [ assumption | (eapply subtyp_trans; eassumption)].\nQed.\n\nLemma subdecs_trans: forall m G Ds1 Ds2 Ds3,\n  subdecs m G Ds1 Ds2 ->\n  subdecs m G Ds2 Ds3 ->\n  subdecs m G Ds1 Ds3.\nProof.\n  introv H12 H23.\n  induction Ds3.\n  + apply subdecs_empty.\n  + rename d into D3.\n    apply invert_subdecs_push in H23.\n    destruct H23 as [D2 [H23a [H23b H23c]]].\n    lets H12': (invert_subdecs H12).\n    specialize (H12' _ _ H23a).\n    destruct H12' as [D1 [Has Sd]].\n    apply subdecs_push with D1.\n    - assumption.\n    - apply subdec_trans with D2; assumption.\n    - apply (IHDs3 H23c).\nQed.\n\n(* precise substitution *)\nLemma pr_subdecs_subst_principle: forall G x y S Ds1 Ds2,\n  ok (G & x ~ S) ->\n  subdecs pr (G & x ~ S) Ds1 Ds2 ->\n  binds y S G ->\n  subdecs pr G (subst_decs x y Ds1) (subst_decs x y Ds2).\nAdmitted.\n\nLemma open_decs_nil: forall z, (open_decs z decs_nil) = decs_nil.\nProof.\n  intro z. reflexivity.\nQed.\n\n(* a variation of exp_preserves_sub where the first expansion is not a hypothesis,\n   but a conclusion (doesn't work because what if T1 has no expansion?)\nLemma swap_sub_and_exp: forall m2 s G T1 T2 Ds2,\n  wf_sto s G ->\n  subtyp pr m2 G T1 T2 ->\n  exp pr G T2 Ds2 ->\n  exists L Ds1,\n    exp pr G T1 Ds1 /\\\n    forall z, z \\notin L ->\n      subdecs pr (G & z ~ typ_bind Ds1) (open_decs z Ds1) (open_decs z Ds2)\n*)\n\n(* does not hold currently! *)\nAxiom exp_total: forall G T, exists Ds, exp pr G T Ds.\n\n(* does not hold because T1 could be a permutation of T2 *)\nAxiom subsub2eq: forall m1 m2 G T1 T2,\n  subtyp m1 m2 G T1 T2 ->\n  subtyp m1 m2 G T2 T1 ->\n  T1 = T2.\n\nAxiom okadmit: forall G: ctx, ok G.\n\n(* substitution principle for precise has\n   TODO prove both substitution principle for ip and pr in the same lemma *)\nLemma pr_subst_has: forall y S t l D G1 G2 x,\n     has pr (G1 & x ~ S & G2) t l D ->\n     binds y S G1 ->\n     ok (G1 & (x ~ S) & G2) ->\n     has pr (G1 & (subst_ctx x y G2)) (subst_trm x y t) l (subst_dec x y D).\nAdmitted.\n\nLemma pr_subst_subdec: forall y S D1 D2 G1 G2 x,\n     subdec pr (G1 & x ~ S & G2) D1 D2 ->\n     binds y S G1 ->\n     ok (G1 & x ~ S & G2) ->\n     subdec pr (G1 & (subst_ctx x y G2)) (subst_dec x y D1) (subst_dec x y D2).\nAdmitted.\n\nLemma invert_cbounds_bind: forall Ds,\n  cbounds_typ (typ_bind Ds) -> cbounds_decs Ds.\nProof.\n  intros. inversions H. assumption.\nQed.\n\nLemma open_decs_preserves_cbounds: forall z Ds,\n  cbounds_decs Ds -> cbounds_decs (open_decs z Ds).\nAdmitted.\n\n(*\nprecise subdecs narrowing is used by exp_preserves_sub_pr/case subtyp_trans,\nwhich cannot guarantee `cbounds Ds1` nor `cbounds Ds2`, so we cannot pass\nany of these two to narrowing, so narrowing cannot get cbounds_ctx for\nold env nor for new env, so this lemma (which needs cbounds_ctx for both old\nand new env) is not really useful\n*)\nLemma pr_narrowing_cbounds:\n   (forall m G T Ds2, exp m G T Ds2 -> forall G1 G2 x DsA DsB,\n    m = pr ->\n    ok G ->\n    G = G1 & x ~ (typ_bind DsB) & G2 ->\n    cbounds_typ T ->\n    cbounds_ctx (G1 & x ~ (typ_bind DsB) & G2) ->\n    cbounds_ctx (G1 & x ~ (typ_bind DsA) & G2) ->\n    subdecs pr (G1 & x ~ (typ_bind DsA)) (open_decs x DsA) (open_decs x DsB) ->\n    exists L Ds1,\n      exp pr (G1 & x ~ (typ_bind DsA) & G2) T Ds1 /\\ \n      forall z, z \\notin L ->\n        subdecs pr (G1 & x ~ (typ_bind DsA) & G2 & z ~ typ_bind Ds1)\n                (open_decs z Ds1) (open_decs z Ds2))\n/\\ (forall m G t l D2, has m G t l D2 ->  forall G1 G2 x DsA DsB,\n    m = pr ->\n    ok G ->\n    G = G1 & x ~ (typ_bind DsB) & G2 ->\n    cbounds_ctx (G1 & x ~ (typ_bind DsB) & G2) ->\n    cbounds_ctx (G1 & x ~ (typ_bind DsA) & G2) ->\n    subdecs pr (G1 & x ~ (typ_bind DsA)) (open_decs x DsA) (open_decs x DsB) ->\n    exists D1,\n      has    pr (G1 & x ~ (typ_bind DsA) & G2) t l D1 /\\ \n      subdec pr (G1 & x ~ (typ_bind DsA) & G2) D1 D2)\n/\\ (forall m1 m2 G T1 T2, subtyp m1 m2 G T1 T2 ->  forall G1 G2 x DsA DsB,\n    m1 = pr ->\n    ok G ->\n    G = G1 & x ~ (typ_bind DsB) & G2 ->\n    cbounds_typ T1 ->\n    cbounds_typ T2 ->\n    cbounds_ctx (G1 & x ~ (typ_bind DsB) & G2) ->\n    cbounds_ctx (G1 & x ~ (typ_bind DsA) & G2) ->\n    subdecs pr (G1 & x ~ (typ_bind DsA)) (open_decs x DsA) (open_decs x DsB) ->\n    subtyp pr oktrans (G1 & x ~ (typ_bind DsA) & G2) T1 T2)\n/\\ (forall m G D1 D2, subdec m G D1 D2 ->  forall G1 G2 x DsA DsB,\n    m = pr ->\n    ok G ->\n    G = G1 & x ~ (typ_bind DsB) & G2 ->\n    cbounds_dec D1 ->\n    cbounds_dec D2 ->\n    cbounds_ctx (G1 & x ~ (typ_bind DsB) & G2) ->\n    cbounds_ctx (G1 & x ~ (typ_bind DsA) & G2) ->\n    subdecs pr (G1 & x ~ (typ_bind DsA)) (open_decs x DsA) (open_decs x DsB) ->\n    subdec pr (G1 & x ~ (typ_bind DsA) & G2) D1 D2)\n/\\ (forall m G Ds1 Ds2, subdecs m G Ds1 Ds2 ->  forall G1 G2 x DsA DsB,\n    m = pr ->\n    ok G ->\n    G = G1 & x ~ (typ_bind DsB) & G2 ->\n    cbounds_decs Ds1 ->\n    cbounds_decs Ds2 ->\n    cbounds_ctx (G1 & x ~ (typ_bind DsB) & G2) ->\n    cbounds_ctx (G1 & x ~ (typ_bind DsA) & G2) ->\n    subdecs pr (G1 & x ~ (typ_bind DsA)) (open_decs x DsA) (open_decs x DsB) ->\n    subdecs pr (G1 & x ~ (typ_bind DsA) & G2) Ds1 Ds2).\nProof.\n  apply mutind5.\n  + (* case exp_top *)\n    intros. exists vars_empty decs_nil. split.\n    - apply exp_top.\n    - intros. rewrite open_decs_nil. apply subdecs_empty.\n  + (* case exp_bind *)\n    intros. subst. exists vars_empty Ds. split.\n    - apply exp_bind.\n    - intros. apply subdecs_refl.\n  + (* case exp_sel *)\n    intros m G v L Lo2 Hi2 Ds Has2 IHHas Exp2 IHExp.\n    intros G1 G2 x DsA DsB E1 Ok2 E2 CbL CbB CbA SdsAB. subst.\n    (* all path types satisfy cbounds_typ --> CbL is useless *)\n    clear CbL.\n    lets Eq: (collapse_bounds CbB Has2). rename Hi2 into U2. subst.\n             (***************)\n    specialize (IHHas _ _ _ _ _ eq_refl Ok2 eq_refl CbB CbA SdsAB).\n    destruct IHHas as [D1 [Has1 Sd]].\n    apply invert_subdec_typ_sync_left in Sd.\n    destruct Sd as [Lo1 [Hi1 [Eq [StLo21 [StLoHi1 StHi12]]]]]. subst D1.\n    lets Eq: (collapse_bounds CbA Has1). rename Hi1 into U. subst.\n             (***************)\n    (*invert_has_pr Has1*)\n    (* only typ_bind in env, which all have cbounds --> U, which is [by Has1] part\n       of such a typ_bind, also has cbounds *)\n    assert (CbU: cbounds_typ U) by admit.\n    assert (A: exists DsU, exp pr (G1 & x ~ (typ_bind DsA) & G2) U DsU)\n      by apply exp_total.\n              (*********)\n    destruct A as [DsU ExpU].\n    lets Eq: (subsub2eq StHi12 StLo21). symmetry in Eq. subst. clear StHi12 StLo21 StLoHi1.\n             (*********)\n    specialize (IHExp _ _ _ _ _ eq_refl Ok2 eq_refl CbU CbB CbA SdsAB).\n    destruct IHExp as [L0 [DsU' [ExpU' Sds2]]].\n    lets Eq: (exp_unique ExpU' ExpU). subst. clear ExpU'.\n             (**********)\n    exists L0 DsU. split.\n    - apply (exp_sel Has1 ExpU).\n    - exact Sds2.\n  + (* case has_trm *)\n    intros; discriminate.\n  + (* case has_var *)\n    intros; discriminate.\n  + (* case has_pr *)\n    intros G v T Ds2 l D2 Bi Exp IHExp DsHas.\n    introv _ Ok Eq CbB CbA SdsAB. subst.\n    assert (OkA: ok (G1 & x ~ typ_bind DsA & G2)) by apply okadmit.\n    destruct (classicT (v = x)) as [Eq | Ne].\n    - (* case v = x *)\n      subst. lets Eq: (binds_middle_eq_inv Bi Ok). subst.\n      inversions Exp. (* DsB = Ds2 *) rename Ds2 into DsB.\n      apply (decs_has_open x) in DsHas.\n      lets Sd: (decs_has_preserves_sub DsHas SdsAB).\n      destruct Sd as [D1' [DsAHas Sd]].\n      assert (exists D1, open_dec x D1 = D1') by admit.\n      destruct H as [D1 Eq]. subst.\n      exists (open_dec x D1).\n      apply (weaken_subdec_end OkA) in Sd.\n      refine (conj _ Sd).\n      apply has_pr with (typ_bind DsA) DsA.\n      * assert (xG2: x # G2) by admit.\n        apply (binds_middle_eq G1 (typ_bind DsA) xG2).\n      * apply exp_bind.\n      * apply (decs_has_close_admitted DsA D1 x DsAHas).\n    - lets BiA: (binds_weaken (binds_subst Bi Ne) OkA).\n      assert (CbT: cbounds_typ T) by admit. (* since by BiA, T is bound in a cbounds env *)\n      specialize (IHExp _ _ _ _ _ eq_refl Ok eq_refl CbT CbB CbA SdsAB).\n      destruct IHExp as [L [Ds1 [Exp1 Sds12]]].\n      pick_fresh z. assert (zL: z \\notin L) by auto.\n      specialize (Sds12 z zL).\n      apply (decs_has_open z) in DsHas.\n      lets Sd: (decs_has_preserves_sub DsHas Sds12).\n      destruct Sd as [D1' [Ds1Has Sd]].\n      assert (exists D1, open_dec z D1 = D1') by admit.\n      destruct H as [D1 Eq]. subst.\n      exists (open_dec v D1).\n      (* T appears in env, and suppose env only typ_bind: *)\n      assert (Eq: T = typ_bind Ds1) by admit. (* <------ *)\n      subst.\n      lets P: (@pr_subst_subdec v (typ_bind Ds1) (open_dec z D1) (open_dec z D2)\n        (G1 & x ~ typ_bind DsA & G2) empty z).\n      unfold subst_ctx in P. rewrite map_empty in P.\n      repeat (progress rewrite -> concat_empty_r in P).\n      assert (OkA': ok (G1 & x ~ typ_bind DsA & G2 & z ~ typ_bind Ds1)) by auto.\n      specialize (P Sd BiA OkA').\n      assert (Impl1: z \\notin fv_decs Ds1 -> z \\notin fv_dec D1) by admit.\n      assert (Impl2: z \\notin fv_decs Ds2 -> z \\notin fv_dec D2) by admit.\n      assert (FrD1: z \\notin fv_dec D1) by auto.\n      assert (FrD2: z \\notin fv_dec D2) by auto.\n      rewrite <- (@subst_intro_dec z v D1 FrD1) in P.\n      rewrite <- (@subst_intro_dec z v D2 FrD2) in P.\n      refine (conj _ P).\n      apply has_pr with (typ_bind Ds1) Ds1.\n      * exact BiA.\n      * apply exp_bind.\n      * apply (decs_has_close_admitted Ds1 D1 z Ds1Has).\n  + (* case subtyp_refl *)\n    introv Has IHHas Eq1 Ok Eq2 Cb1 Cb2 CbB CbA SdsAB. subst.\n    (* apply subtyp_tmode. apply subtyp_refl with Lo Hi. *)\n    apply subtyp_refl_all.\n  + (* case subtyp_top *)\n    intros. apply subtyp_tmode. apply subtyp_top.\n  + (* case subtyp_bot *)\n    intros. apply subtyp_tmode. apply subtyp_bot.\n  + (* case subtyp_bind *)\n    introv Sds IHSds. introv Eq1 Ok Eq2 CbDs1 CbDs2 CbB CbA SdsAB. subst.\n    apply invert_cbounds_bind in CbDs1.\n    apply invert_cbounds_bind in CbDs2.\n    apply subtyp_tmode. apply_fresh subtyp_bind as z.\n    assert (zL: z \\notin L) by auto.\n    specialize (Sds z zL).\n    specialize (IHSds z zL).\n    rewrite <- concat_assoc in IHSds.\n    specialize (IHSds G1 (G2 & z ~ typ_bind Ds1) x DsA DsB eq_refl).\n    repeat (progress rewrite -> concat_assoc in IHSds).\n    assert (ok (G1 & x ~ typ_bind DsB & G2 & z ~ typ_bind Ds1)) by auto.\n    refine (IHSds H eq_refl _ _ _ _ SdsAB).\n    - apply (open_decs_preserves_cbounds z CbDs1).\n    - apply (open_decs_preserves_cbounds z CbDs2).\n    - apply (cbounds_push _ (cbounds_bind CbDs1) CbB).\n    - apply (cbounds_push _ (cbounds_bind CbDs1) CbA).\n  + (* case subtyp_sel_l *)\n    (* note: here we don't depend on bounds being collapsed *)\n    introv Has2 IHHas St IHSt.\n    introv Eq1 Ok Eq2 CbL CbT CbB CbA SdsAB. subst.\n    assert (CbU: cbounds_typ U) by admit. (* by Has2 and \"only typ_decs in env\", x is of\n      typ_bind in env, which contains U *)\n    specialize (IHSt _ _ _ _ _ eq_refl Ok eq_refl CbU CbT CbB CbA SdsAB).\n    specialize (IHHas _ _ _ _ _ eq_refl Ok eq_refl CbB CbA SdsAB).\n    destruct IHHas as [D1 [Has1 Sd]].\n    apply invert_subdec_typ_sync_left in Sd.\n    destruct Sd as [Lo1 [Hi1 [Eq [StLo21 [StLoHi1 StHi12]]]]]. subst D1.\n    apply subtyp_tmode. apply (subtyp_sel_l Has1).\n    apply (subtyp_trans StHi12 IHSt).\n  + (* case subtyp_sel_r *)\n    (* note: here we don't depend on bounds being collapsed *)\n    intros m G v L Lo2 Hi2 T Has2 IHHas StLo2Hi2 IHStLo2Hi2 StT1Lo2 IHStTLo2.\n    introv Eq1 Ok Eq2 CbT CbL CbB CbA SdsAB. subst.\n    specialize (IHHas _ _ _ _ _ eq_refl Ok eq_refl CbB CbA SdsAB).\n    destruct IHHas as [D1 [Has1 Sd]].\n    apply invert_subdec_typ_sync_left in Sd.\n    destruct Sd as [Lo1 [Hi1 [Eq [StLo21 [StLoHi1 StHi12]]]]]. subst D1.\n    assert (CbLo2: cbounds_typ Lo2) by admit. (* by Has2, ... *)\n    specialize (IHStTLo2 _ _ _ _ _ eq_refl Ok eq_refl CbT CbLo2 CbB CbA SdsAB).\n    apply subtyp_tmode.\n    lets StTLo1: (subtyp_trans IHStTLo2 StLo21).\n    apply (subtyp_sel_r Has1 StLoHi1 StTLo1).\n  + (* case subtyp_tmode *)\n    introv St IHSt Eq1 Ok Eq2 CbB CbA SdsAB. subst.\n    refine (IHSt _ _ _ _ _ eq_refl _ eq_refl _ _ _); assumption.\n  + (* case subtyp_trans *)\n    introv St12 IHSt12 St23 IHSt23 Eq1 Ok Eq2. introv CbT1 CbT3 CbB CbA SdsAB. subst.\n    (* !!! T2 does not have collapsed bounds !!! *)\nAbort. (*\n    apply subtyp_trans with T2.\n    - refine (IHSt12 _ _ _ _ _ eq_refl _ eq_refl _ _ _ _ _); assumption.\n    - refine (IHSt23 _ _ _ _ _ eq_refl _ eq_refl _ _ _); assumption.\n  + (* case subdec_typ *)\n    intros. subst. apply* subdec_typ.\n  + (* case subdec_fld *)\n    intros. subst. apply* subdec_fld.\n  + (* case subdec_mtd *)\n    intros. subst. apply* subdec_mtd.\n  + (* case subdecs_empty *)\n    intros. subst. apply subdecs_empty.\n  + (* case subdecs_push *)\n    intros. subst. apply* subdecs_push.\nQed.*)\n\nLemma exp_preserves_sub_pr_admitted: forall m2 G T1 T2 Ds1 Ds2,\n  subtyp pr m2 G T1 T2 ->\n  exp pr G T1 Ds1 ->\n  exp pr G T2 Ds2 ->\n  exists L, forall z, z \\notin L ->\n    subdecs pr (G & z ~ typ_bind Ds1) (open_decs z Ds1) (open_decs z Ds2).\nAdmitted.\n\nLemma narrow_subdecs_admitted:\n  forall m G Ds1 Ds2, subdecs m G Ds1 Ds2 ->  forall G1 G2 x DsA DsB,\n    m = pr ->\n    ok G ->\n    G = G1 & x ~ (typ_bind DsB) & G2 ->\n    subdecs pr (G1 & x ~ (typ_bind DsA)) (open_decs x DsA) (open_decs x DsB) ->\n    subdecs pr (G1 & x ~ (typ_bind DsA) & G2) Ds1 Ds2.\nAdmitted.\n\nAxiom ctx_size: ctx -> nat.\n\n(* given a type T which is well-formed in the environment G, what's the max env size that\n   can appear in any subtyp derivation of the form [G |- X <: T] ?\n   Note: self reference might appear in upper bound -> env can become arbitrarily large\n   in { z => List: Bot .. ... } <: X.\n   But not in lower bound -> [G |- X <: T] instead of [G |- T <: X].\n   But contravariance swaps direction -> give both lhs and rhs as args.\n *)\n\nInductive notsel: typ -> Prop :=\n  | notsel_top  : notsel typ_top\n  | notsel_bot  : notsel typ_bot\n  | notsel_bind : forall Ds, notsel (typ_bind Ds).\n\n(* Given types T1 and T2 which are well-formed in the environment G,\n   how big can the env become until we can decide if T1 <: T2 ?\n   I.e. if T1 <: T2, what's the max env size that can appear the subtype derivation,\n   and if T1 is not a subtype of T2, how big can the env become until we know it? *)\nInductive max_ctx_subtyp: ctx -> typ -> typ -> nat -> Prop :=\n  (* yes *)\n  | max_ctx_refl : forall G T,\n      max_ctx_subtyp G T T (ctx_size G)\n  | max_ctx_top : forall G T1,\n      max_ctx_subtyp G T1 typ_top (ctx_size G)\n  | max_ctx_bot : forall G T2,\n      max_ctx_subtyp G typ_bot T2 (ctx_size G)\n  | max_ctx_bind : forall L G Ds1 Ds2 n,\n      (forall z, z \\notin L -> max_ctx_subdecs (G & z ~ typ_bind Ds1) Ds1 Ds2 n) ->\n      max_ctx_subtyp G (typ_bind Ds1) (typ_bind Ds2) (S n) (* <--- n+1 *)\n  (* when checking if p.L <: q.M, we can apply both subtyp_sel_l/r, but maybe only\n     one of them works *)\n  | max_ctx_sel : forall G x1 L1 Lo1 Hi1 x2 L2 Lo2 Hi2 n1 n2,\n      has pr G (trm_var (avar_f x1)) L1 (dec_typ Lo1 Hi1) ->\n      has pr G (trm_var (avar_f x2)) L2 (dec_typ Lo2 Hi2) ->\n      max_ctx_subtyp G (typ_sel (pth_var (avar_f x1)) L1) Lo2 n1 ->\n      max_ctx_subtyp G Hi2 (typ_sel (pth_var (avar_f x2)) L2) n2 ->\n      max_ctx_subtyp G (typ_sel (pth_var (avar_f x1)) L1)\n                       (typ_sel (pth_var (avar_f x2)) L2) (max n1 n2)\n  | max_ctx_sel_l : forall G x L Lo Hi T n,\n      notsel T ->\n      has pr G (trm_var (avar_f x)) L (dec_typ Lo Hi) ->\n      max_ctx_subtyp G Hi T n ->\n      max_ctx_subtyp G (typ_sel (pth_var (avar_f x)) L) T n\n  | max_ctx_sel_r : forall G T x L Lo Hi n1 n2,\n      notsel T ->\n      has pr G (trm_var (avar_f x)) L (dec_typ Lo Hi) ->\n      max_ctx_subtyp G T Lo n1 ->\n      max_ctx_subtyp G Lo Hi n2 ->\n      max_ctx_subtyp G T (typ_sel (pth_var (avar_f x)) L) (max n1 n2)\n  (* can't have transitivity rule because \"T1 not subtype of TWeird\" and\n     \"TWeird not subtype of T2\" does not imply \"T1 not subtype of T2\" *)\n  (* no *)\n  | max_ctx_top_bot : forall G,\n      max_ctx_subtyp G typ_top typ_bot (ctx_size G)\n  | max_ctx_top_bind : forall G Ds,\n      max_ctx_subtyp G typ_top (typ_bind Ds) (ctx_size G)\n  | max_ctx_bind_bot : forall G Ds,\n      max_ctx_subtyp G (typ_bind Ds) typ_bot (ctx_size G)\nwith max_ctx_subdec : ctx -> dec -> dec -> nat -> Prop :=\n  | max_ctx_typ : forall G Lo1 Hi1 Lo2 Hi2 n1 n2,\n      max_ctx_subtyp G Lo2 Lo1 n1 ->\n      max_ctx_subtyp G Hi1 Hi2 n2 ->\n      max_ctx_subdec G (dec_typ Lo1 Hi1) (dec_typ Lo2 Hi2) (max n1 n2)\n  | max_ctx_fld : forall G T1 T2 n,\n      max_ctx_subtyp G T1 T2 n ->\n      max_ctx_subdec G (dec_fld T1) (dec_fld T2) n\n  | max_ctx_mtd : forall G A1 R1 A2 R2 n1 n2,\n      max_ctx_subtyp G A2 A1 n1 ->\n      max_ctx_subtyp G R1 R2 n2 ->\n      max_ctx_subdec G (dec_mtd A1 R1) (dec_mtd A2 R2) (max n1 n2)\nwith max_ctx_subdecs : ctx -> decs -> decs -> nat -> Prop :=\n  | max_ctx_nil : forall G Ds1,\n      max_ctx_subdecs G Ds1 decs_nil (ctx_size G)\n  | max_ctx_cons : forall G D1 D2 Ds1 Ds2 n n1 n2,\n      decs_has Ds1 (label_for_dec n D2) D1 ->\n      max_ctx_subdec G D1 D2 n1 ->\n      max_ctx_subdecs G Ds1 Ds2 n2 ->\n      max_ctx_subdecs G Ds1 (decs_cons n D2 Ds2) (max n1 n2).\n\nLemma top_not_subtyp_of_bot: forall m1 G, ~ subtyp m1 notrans G typ_top typ_bot.\nProof.\n  intros m1 G St. inversions St.\nQed.\n\n(* Lemma max_ctx_trans_top: forall G T1 T2 n,\n  wf_typ G T1 ->\n  wf_typ G T2 ->\n  max_ctx_subtyp G typ_top T2 n ->\n  max_ctx_subtyp G T1 T2 n.\ndoes not hold: maybe T1 and T2 are typ_bind, so typ_top is not the correct \"middle guy\" *)\n\nLemma calc_max_ctx_size:\n   (forall G T1, wf_typ G T1 -> forall G' T2, wf_typ G' T2 -> G' = G -> \n     exists n, max_ctx_subtyp G T1 T2 n)\n/\\ (forall G D1, wf_dec G D1 -> forall G' D2, wf_dec G' D2 -> G' = G ->\n     exists n, max_ctx_subdec G D1 D2 n)\n/\\ (forall G Ds1, wf_decs G Ds1 -> forall G' Ds2, wf_decs G' Ds2 -> G' = G ->\n     exists n, max_ctx_subdecs G Ds1 Ds2 n).\nProof.\n  apply wf_mutind.\n  + intro G.\n    assert (\n    apply (wf_typ_ind (fun G' T2 => G' = G -> exists n, _)).\n    - intros. subst. exists (ctx_size G). apply max_ctx_top.\n    - intros. subst. exists (ctx_size G). apply max_ctx_top_bot.\n    - intros. subst. exists (ctx_size G). apply max_ctx_top_bind.\n    - introv Has WfLo IHLo WfHi IHHi Eq.\n      specialize (IHLo Eq). specialize (IHHi Eq). subst.\n      destruct IHLo as [n1 IHLo].\n      destruct IHHi as [n2 IHHi].\n   \n (* TODO \"transitivity\": Lo <: typ_top <: Hi --> Lo <: Hi *)\n...\nQed.\n\nLemma calc_max_ctx_size:\n   (forall G T1, wf_typ G T1 -> forall T2,\n     wf_typ G T2 ->\n     (exists n, max_ctx_subtyp G T1 T2 n) /\\ (exists n, max_ctx_subtyp G T2 T1 n))\n/\\ (forall G D1, wf_dec G D1 -> forall D2,\n     wf_dec G D2 ->\n     (exists n, max_ctx_subdec G D1 D2 n) /\\ (exists n, max_ctx_subdec G D2 D1 n))\n/\\ (forall G Ds1, wf_decs G Ds1 -> forall Ds2,\n     wf_decs G Ds2 ->\n     (exists n, max_ctx_subdecs G Ds1 Ds2 n) /\\ (exists n, max_ctx_subdecs G Ds2 Ds1 n)).\nProof.\n  apply wf_mutind; introv Wf2; split.\n  + admit.\n  + exists (ctx_size G). apply max_ctx_top.\n  ...\nQed.\n\n(* given a type T which is well-formed in the environment G, what's the max env size that\n   can appear in any subtyp derivation of the form [G |- T <: X] ?\nFixpoint max_ctx_subtyp(G: ctx)(T: typ): nat :=\n  match T with\n  | typ_top => ctx_size G\n  | typ_bot => ctx_size G\n  | typ_bind Ds => S (max_ctx_subdecs G Ds) (* <-- +1 because self ref is put into env *)\n  | typ_sel p L => ctx_size G (* TODO need to lookup lower and upper bound of p.L ! *)\n  end\nwith max_ctx_subdec(G: ctx)(D: dec): nat :=\n  match D with\n  | dec_typ Lo Hi => max (max_ctx_subtyp G Lo) (max_ctx_subtyp G Hi)\n  | dec_fld T     => max_ctx_subtyp G T\n  | dec_mtd T U   => max (max_ctx_subtyp G T) (max_ctx_subtyp G U)\n  end\nwith max_ctx_subdecs(G: ctx)(Ds: decs): nat :=\n  match Ds with\n  | decs_nil => ctx_size G\n  | decs_cons n D1 Ds1 => max (max_ctx_subdec G D1) (max_ctx_subdecs G Ds1)\n  end.\n*)\n\nLemma pr_narrowing:\n   (forall m G T Ds2, exp m G T Ds2 -> forall G1 G2 x DsA DsB,\n    m = pr ->\n    ok G ->\n    G = G1 & x ~ (typ_bind DsB) & G2 ->\n    subdecs pr (G1 & x ~ (typ_bind DsA)) (open_decs x DsA) (open_decs x DsB) ->\n    exists L Ds1,\n      exp pr (G1 & x ~ (typ_bind DsA) & G2) T Ds1 /\\ \n      forall z, z \\notin L ->\n        subdecs pr (G1 & x ~ (typ_bind DsA) & G2 & z ~ typ_bind Ds1)\n                (open_decs z Ds1) (open_decs z Ds2))\n/\\ (forall m G t l D2, has m G t l D2 ->  forall G1 G2 x DsA DsB,\n    m = pr ->\n    ok G ->\n    G = G1 & x ~ (typ_bind DsB) & G2 ->\n    subdecs pr (G1 & x ~ (typ_bind DsA)) (open_decs x DsA) (open_decs x DsB) ->\n    exists D1,\n      has    pr (G1 & x ~ (typ_bind DsA) & G2) t l D1 /\\ \n      subdec pr (G1 & x ~ (typ_bind DsA) & G2) D1 D2)\n/\\ (forall m1 m2 G T1 T2, subtyp m1 m2 G T1 T2 ->  forall G1 G2 x DsA DsB,\n    m1 = pr ->\n    ok G ->\n    G = G1 & x ~ (typ_bind DsB) & G2 ->\n    subdecs pr (G1 & x ~ (typ_bind DsA)) (open_decs x DsA) (open_decs x DsB) ->\n    subtyp pr oktrans (G1 & x ~ (typ_bind DsA) & G2) T1 T2)\n/\\ (forall m G D1 D2, subdec m G D1 D2 ->  forall G1 G2 x DsA DsB,\n    m = pr ->\n    ok G ->\n    G = G1 & x ~ (typ_bind DsB) & G2 ->\n    subdecs pr (G1 & x ~ (typ_bind DsA)) (open_decs x DsA) (open_decs x DsB) ->\n    subdec pr (G1 & x ~ (typ_bind DsA) & G2) D1 D2)\n/\\ (forall m G Ds1 Ds2, subdecs m G Ds1 Ds2 ->  forall G1 G2 x DsA DsB,\n    m = pr ->\n    ok G ->\n    G = G1 & x ~ (typ_bind DsB) & G2 ->\n    subdecs pr (G1 & x ~ (typ_bind DsA)) (open_decs x DsA) (open_decs x DsB) ->\n    subdecs pr (G1 & x ~ (typ_bind DsA) & G2) Ds1 Ds2).\nProof.\n  apply mutind5.\n  + (* case exp_top *)\n    intros. exists vars_empty decs_nil. split.\n    - apply exp_top.\n    - intros. rewrite open_decs_nil. apply subdecs_empty.\n  + (* case exp_bind *)\n    intros. subst. exists vars_empty Ds. split.\n    - apply exp_bind.\n    - intros. apply subdecs_refl.\n  + (* case exp_sel *)\n    intros m G v L Lo2 Hi2 Ds2 Has2 IHHas Exp2 IHExp.\n    intros G1 G2 x DsA DsB E1 Ok2 E2 SdsAB. subst.\n    specialize (IHHas _ _ _ _ _ eq_refl Ok2 eq_refl SdsAB).\n    specialize (IHExp _ _ _ _ _ eq_refl Ok2 eq_refl SdsAB).\n    destruct IHHas as [D1 [IHHas Sd]].\n    destruct IHExp as [L0 [Dsm [IHExp Sds2]]].\n    apply invert_subdec_typ_sync_left in Sd.\n    destruct Sd as [Lo1 [Hi1 [Eq [StLo21 [StLoHi1 StHi12]]]]]. subst D1.\n    assert (A: exists Ds1, exp pr (G1 & x ~ (typ_bind DsA) & G2) Hi1 Ds1) \n      by apply exp_total. (* <- *)\n    destruct A as [Ds1 Exp1].\n    (* !!! applying IH of exp_preserves_sub_pr to StHi12, which is conclusion of IHHas\n           and thus not structurally smaller !!! *)\n    lets Sds1: (@exp_preserves_sub_pr_admitted _ _ Hi1 Hi2 Ds1 Dsm StHi12 Exp1 IHExp).\n    destruct Sds1 as [L1 Sds1].\n    exists (L0 \\u L1) Ds1. apply (conj (exp_sel IHHas Exp1)).\n    intros z zL01.\n    assert (zL0: z \\notin L0) by auto. specialize (Sds2 z zL0).\n    assert (zL1: z \\notin L1) by auto. specialize (Sds1 z zL1).\n    assert (Sds2n: subdecs pr (G1 & x ~ typ_bind DsA & G2 & z ~ typ_bind Ds1 & empty)\n                           (open_decs z Dsm) (open_decs z Ds2)). {\n     (* !!! applying IH of narrow_subdecs to Sds2, which is conclusion of IHExp\n            and thus not structurally smaller !!! *)\n     refine (@narrow_subdecs_admitted pr _ _ _ Sds2 (G1 & x ~ typ_bind DsA & G2) empty\n                z Ds1 Dsm eq_refl _ _ Sds1).\n     - admit. (* ok-stuff *)\n     - symmetry. apply concat_empty_r.\n    }\n    rewrite concat_empty_r in Sds2n.\n    apply (subdecs_trans Sds1 Sds2n).\n  + (* case has_trm *)\n    intros; discriminate.\n  + (* case has_var *)\n    intros; discriminate.\n  + (* case has_pr *)\n    intros G v T Ds2 l D2 Bi Exp IHExp DsHas.\n    introv _ Ok Eq SdsAB. subst.\n    assert (OkA: ok (G1 & x ~ typ_bind DsA & G2)) by apply okadmit.\n    destruct (classicT (v = x)) as [Eq | Ne].\n    - (* case v = x *)\n      subst. lets Eq: (binds_middle_eq_inv Bi Ok). subst.\n      inversions Exp. (* DsB = Ds2 *) rename Ds2 into DsB.\n      apply (decs_has_open x) in DsHas.\n      lets Sd: (decs_has_preserves_sub DsHas SdsAB).\n      destruct Sd as [D1' [DsAHas Sd]].\n      assert (exists D1, open_dec x D1 = D1') by admit.\n      destruct H as [D1 Eq]. subst.\n      exists (open_dec x D1).\n      apply (weaken_subdec_end OkA) in Sd.\n      refine (conj _ Sd).\n      apply has_pr with (typ_bind DsA) DsA.\n      * assert (xG2: x # G2) by admit.\n        apply (binds_middle_eq G1 (typ_bind DsA) xG2).\n      * apply exp_bind.\n      * apply (decs_has_close_admitted DsA D1 x DsAHas).\n    - lets BiA: (binds_weaken (binds_subst Bi Ne) OkA).\n      specialize (IHExp _ _ _ _ _ eq_refl Ok eq_refl SdsAB).\n      destruct IHExp as [L [Ds1 [Exp1 Sds12]]].\n      pick_fresh z. assert (zL: z \\notin L) by auto.\n      specialize (Sds12 z zL).\n      apply (decs_has_open z) in DsHas.\n      lets Sd: (decs_has_preserves_sub DsHas Sds12).\n      destruct Sd as [D1' [Ds1Has Sd]].\n      assert (exists D1, open_dec z D1 = D1') by admit.\n      destruct H as [D1 Eq]. subst.\n      exists (open_dec v D1).\n      (* T appears in env, and suppose env only typ_bind: *)\n      assert (Eq: T = typ_bind Ds1) by admit. (* <------ *)\n      subst.\n      lets P: (@pr_subst_subdec v (typ_bind Ds1) (open_dec z D1) (open_dec z D2)\n        (G1 & x ~ typ_bind DsA & G2) empty z).\n      unfold subst_ctx in P. rewrite map_empty in P.\n      repeat (progress rewrite -> concat_empty_r in P).\n      assert (OkA': ok (G1 & x ~ typ_bind DsA & G2 & z ~ typ_bind Ds1)) by auto.\n      specialize (P Sd BiA OkA').\n      assert (Impl1: z \\notin fv_decs Ds1 -> z \\notin fv_dec D1) by admit.\n      assert (Impl2: z \\notin fv_decs Ds2 -> z \\notin fv_dec D2) by admit.\n      assert (FrD1: z \\notin fv_dec D1) by auto.\n      assert (FrD2: z \\notin fv_dec D2) by auto.\n      rewrite <- (@subst_intro_dec z v D1 FrD1) in P.\n      rewrite <- (@subst_intro_dec z v D2 FrD2) in P.\n      refine (conj _ P).\n      apply has_pr with (typ_bind Ds1) Ds1.\n      * exact BiA.\n      * apply exp_bind.\n      * apply (decs_has_close_admitted Ds1 D1 z Ds1Has).\n  + (* case subtyp_refl *)\n    introv Has IHHas Eq1 Ok Eq2 SdsAB. subst.\n    (* apply subtyp_tmode. apply subtyp_refl with Lo Hi. *)\n    apply subtyp_refl_all.\n  + (* case subtyp_top *)\n    intros. apply subtyp_tmode. apply subtyp_top.\n  + (* case subtyp_bot *)\n    intros. apply subtyp_tmode. apply subtyp_bot.\n  + (* case subtyp_bind *)\n    introv Sds IHSds. introv Eq1 Ok Eq2 SdsAB. subst.\n    apply subtyp_tmode. apply_fresh subtyp_bind as z.\n    assert (zL: z \\notin L) by auto.\n    specialize (Sds z zL).\n    specialize (IHSds z zL).\n    rewrite <- concat_assoc in IHSds.\n    specialize (IHSds G1 (G2 & z ~ typ_bind Ds1) x DsA DsB eq_refl).\n    repeat (progress rewrite -> concat_assoc in IHSds).\n    assert (ok (G1 & x ~ typ_bind DsB & G2 & z ~ typ_bind Ds1)) by auto.\n    specialize (IHSds H eq_refl SdsAB).\n    exact IHSds.\n  + (* case subtyp_sel_l *)\n    (* note: here we don't depend on bounds being collapsed *)\n    introv Has2 IHHas St IHSt.\n    introv Eq1 Ok Eq2 SdsAB. subst.\n    specialize (IHSt _ _ _ _ _ eq_refl Ok eq_refl SdsAB).\n    specialize (IHHas _ _ _ _ _ eq_refl Ok eq_refl SdsAB).\n    destruct IHHas as [D1 [Has1 Sd]].\n    apply invert_subdec_typ_sync_left in Sd.\n    destruct Sd as [Lo1 [Hi1 [Eq [StLo21 [StLoHi1 StHi12]]]]]. subst D1.\n    apply subtyp_tmode. apply (subtyp_sel_l Has1).\n    apply (subtyp_trans StHi12 IHSt).\n  + (* case subtyp_sel_r *)\n    (* note: here we don't depend on bounds being collapsed *)\n    intros m G v L Lo2 Hi2 T Has2 IHHas StLo2Hi2 IHStLo2Hi2 StT1Lo2 IHStTLo2.\n    introv Eq1 Ok Eq2 SdsAB. subst.\n    specialize (IHHas _ _ _ _ _ eq_refl Ok eq_refl SdsAB).\n    destruct IHHas as [D1 [Has1 Sd]].\n    apply invert_subdec_typ_sync_left in Sd.\n    destruct Sd as [Lo1 [Hi1 [Eq [StLo21 [StLoHi1 StHi12]]]]]. subst D1.\n    specialize (IHStTLo2 _ _ _ _ _ eq_refl Ok eq_refl SdsAB).\n    apply subtyp_tmode.\n    lets StTLo1: (subtyp_trans IHStTLo2 StLo21).\n    apply (subtyp_sel_r Has1 StLoHi1 StTLo1).\n  + (* case subtyp_tmode *)\n    introv St IHSt Eq1 Ok Eq2 SdsAB. subst.\n    refine (IHSt _ _ _ _ _ eq_refl _ eq_refl _); assumption.\n  + (* case subtyp_trans *)\n    introv St12 IHSt12 St23 IHSt23 Eq1 Ok Eq2 SdsAB. subst.\n    apply subtyp_trans with T2.\n    - refine (IHSt12 _ _ _ _ _ eq_refl _ eq_refl _); assumption.\n    - refine (IHSt23 _ _ _ _ _ eq_refl _ eq_refl _); assumption.\n  + (* case subdec_typ *)\n    intros. subst. apply* subdec_typ.\n  + (* case subdec_fld *)\n    intros. subst. apply* subdec_fld.\n  + (* case subdec_mtd *)\n    intros. subst. apply* subdec_mtd.\n  + (* case subdecs_empty *)\n    intros. subst. apply subdecs_empty.\n  + (* case subdecs_push *)\n    intros. subst. apply* subdecs_push.\nQed.\n\nPrint Assumptions pr_narrowing.\n\nLemma exp_preserves_sub_pr: forall m2 G T1 T2 Ds1 Ds2,\n  cbounds_ctx G ->\n  subtyp pr m2 G T1 T2 ->\n  exp pr G T1 Ds1 ->\n  exp pr G T2 Ds2 ->\n  exists L, forall z, z \\notin L ->\n    subdecs pr (G & z ~ typ_bind Ds1) (open_decs z Ds1) (open_decs z Ds2).\nProof.\n  (* We don't use the [induction] tactic because we want to intro everything ourselves: *)\n  intros m2 G T1 T2 Ds1 Ds2 Cb St.\n  gen_eq m1: pr. gen m1 m2 G T1 T2 St Ds1 Ds2 Cb.\n  apply (subtyp_ind (fun m1 m2 G T1 T2 => forall Ds1 Ds2,\n    cbounds_ctx G ->\n    m1 = pr ->\n    exp m1 G T1 Ds1 ->\n    exp m1 G T2 Ds2 ->\n    exists L, forall z, _ ->\n      subdecs m1 (G & z ~ typ_bind Ds1) (open_decs z Ds1) (open_decs z Ds2))).\n  + (* case subtyp_refl *)\n    introv Has Cb Eq Exp1 Exp2. subst.\n    lets Eq: (exp_unique Exp1 Exp2).\n    subst. exists vars_empty. intros z zL. apply subdecs_refl.\n  + (* case subtyp_top *)\n    introv Cb Eq1 Exp1 Exp2.\n    inversions Exp2. exists vars_empty. intros z zL.\n    unfold open_decs, open_rec_decs. apply subdecs_empty.\n  + (* case subtyp_bot *)\n    introv Cb Eq1 Exp1.\n    inversions Exp1.\n  + (* case subtyp_bind *)\n    introv Sds Cb Eq1 Exp1 Exp2.\n    inversions Exp1. inversions Exp2. exists L.\n    intros z zL. apply (Sds z zL).\n  + (* case subtyp_sel_l *)\n    (* This case does not need subdecs_trans, because Exp1 is precise, so the expansion\n       of x.L is the same as the expansion of its upper bound Hi1, and we can just apply\n       the IH for Hi1<:T *)\n    introv Has2 St IHSt Cb Eq Exp1 Exp2. subst.\n    apply invert_exp_sel in Exp1. destruct Exp1 as [Lo1 [Hi1 [Has1 Exp1]]].\n    lets Eq: (has_unique Has2 Has1).\n             (**********)\n    inversions Eq.\n    apply* IHSt.\n  + (* case subtyp_sel_r *)\n    introv Has St1 IHSt1 St2 IHSt2 Cb Eq Exp1 Exp2.\n    rename S into Lo, U into Hi. subst.\n    apply invert_exp_sel in Exp2. destruct Exp2 as [Lo' [Hi' [Has' Exp2]]].\n    lets Eq: (has_unique Has' Has). inversions Eq. clear Has'.\n             (**********)\n    lets Eq: (collapse_bounds Cb Has). rename Hi into U. subst.\n             (***************)\n    apply* IHSt2.\n  + (* case subtyp_mode *)\n    intros. subst. apply* H0.\n  + (* case subtyp_trans *)\n    introv St12 IHSt12 St23 IHSt23 Cb Eq Exp1 Exp3.\n    rename Ds2 into Ds3. subst.\n    assert (Exp2: exists Ds2, exp pr G T2 Ds2) by apply exp_total.\n    destruct Exp2 as [Ds2 Exp2].\n    specialize (IHSt12 Ds1 Ds2 Cb eq_refl Exp1 Exp2).\n    destruct IHSt12 as [L1 Sds12].\n    specialize (IHSt23 Ds2 Ds3 Cb eq_refl Exp2 Exp3).\n    destruct IHSt23 as [L2 Sds23].\n    exists (L1 \\u L2). intros z zn.\n    assert (zL1: z \\notin L1) by auto. specialize (Sds12 z zL1).\n    assert (zL2: z \\notin L2) by auto. specialize (Sds23 z zL2).\n    apply (subdecs_trans Sds12).\n    destruct pr_narrowing as [_ [_ [_ [_ N]]]].\n            (************)\n    specialize (N pr _ _ _ Sds23 G empty z Ds1 Ds2 eq_refl).\n    do 2 rewrite concat_empty_r in N.\n    refine (N _ eq_refl Sds12).\n    - admit. (* ok-stuff *)\n    (* not needed any more:\n    - admit. (* !! does `cbounds_decs Ds2` hold ?? hmm might be any \"middle\" type *)\n    - admit. (* does `cbounds_decs Ds1` hold?\n      Yes if we give it as a hypothesis. But then we cannot use IHSt23 any more! *)\n    *)\nQed.\n\nPrint Assumptions exp_preserves_sub_pr.\n\nLemma ip2pr:\n   (forall m G T Ds2, exp m G T Ds2 -> forall s,\n      m = ip ->\n      wf_sto s G ->\n      exists L Ds1,\n        exp pr G T Ds1 /\\\n        forall z, z \\notin L ->\n                  subdecs pr (G & z ~ typ_bind Ds1) (open_decs z Ds1) (open_decs z Ds2))\n/\\ (forall m G t L D2, has m G t L D2 -> forall s v,\n      m = ip ->\n      wf_sto s G ->\n      t = (trm_var (avar_f v)) ->\n      exists D1, has pr G (trm_var (avar_f v)) L D1 /\\\n                 subdec pr G D1 D2)\n/\\ (forall m1 m2 G T1 T2, subtyp m1 m2 G T1 T2 -> forall s,\n      m1 = ip ->\n      wf_sto s G ->\n      subtyp pr oktrans G T1 T2)\n/\\ (forall m G D1 D2, subdec m G D1 D2 -> forall s,\n      m = ip ->\n      wf_sto s G ->\n      subdec pr G D1 D2)\n/\\ (forall m G Ds1 Ds2, subdecs m G Ds1 Ds2 -> forall s,\n      m = ip ->\n      wf_sto s G ->\n      subdecs pr G Ds1 Ds2)\n/\\ (forall G t T2, ty_trm G t T2 -> forall s v,\n      wf_sto s G ->\n      t = (trm_var (avar_f v)) ->\n      exists T1, binds v T1 G /\\\n                 subtyp pr oktrans G T1 T2).\nAdmitted. (*\nProof.\n  apply mutind6; try (intros; discriminate).\n  + (* case exp_top *)\n    intros. subst. exists vars_empty decs_nil.\n    apply (conj (exp_top _ _)).\n    intros. apply subdecs_empty.\n  + (* case exp_bind *)\n    intros m G Ds s Eq Wf. subst.\n    exists vars_empty Ds.\n    apply (conj (exp_bind _ _ _)).\n    intros. apply subdecs_refl.\n  + (* case exp_sel *)\n    intros m G v L Lo2 Hi2 Ds2 Has IHHas Exp IHExp s Eq Wf. subst.\n    lets Ok: (wf_sto_to_ok_G Wf).\n    specialize (IHHas _ _ eq_refl Wf eq_refl). destruct IHHas as [D1 [IHHas IHSd]].\n    specialize (IHExp _ eq_refl Wf).\n    destruct IHExp as [L0 [Ds1 [ExpHi2 Sds12]]].\n    apply invert_subdec_typ_sync_left in IHSd.\n    destruct IHSd as [Lo1 [Hi1 [Eq [StLo [_ StHi]]]]]. subst.\n    assert (E: exists Ds0, exp pr G Hi1 Ds0) by admit. (* hopefully by wf_sto... *)\n    destruct E as [Ds0 ExpHi1].\n    assert (Cb: cbounds_ctx G) by admit. (* <------- TODO *)\n    lets Sds01: (exp_preserves_sub_pr Cb StHi ExpHi1 ExpHi2).\n    destruct Sds01 as [L1 Sds01].\n    exists (L0 \\u L1) Ds0. split.\n    - apply (exp_sel IHHas ExpHi1).\n    - intros z Fr.\n      assert (zL1: z \\notin L1) by auto. specialize (Sds01 z zL1).\n      assert (zL0: z \\notin L0) by auto. specialize (Sds12 z zL0).\n      apply (subdecs_trans Sds01).\n      destruct pr_narrowing as [_ [_ [_ [_ N]]]].\n      specialize (N pr _ _ _ Sds12 G empty z Ds0 Ds1 eq_refl).\n      do 2 rewrite concat_empty_r in N.\n      refine (N _ eq_refl _ _ Sds01).\n      * admit. (* ok-stuff *)\n      * admit. (* !! does `cbounds_decs Ds1` hold ?? *)\n      * admit. (* !! does `cbounds_decs Ds0` hold ?? *)\n\n  + (* case has_trm *)\n    intros G t X2 Ds2 l D2 Ty IHTy Exp2 IHExp Ds2Has Clo s v _ Wf Eq. subst.\n    lets Ok: (wf_sto_to_ok_G Wf).\n    specialize (IHExp s eq_refl Wf). destruct IHExp as [L2 [Dsm [Expm Sds2]]].\n    specialize (IHTy s v Wf eq_refl). destruct IHTy as [X1 [BiG St]].\n    assert (E: exists Ds1, exp pr G X1 Ds1) by admit. (* hopefully by wf_sto... *)\n    destruct E as [Ds1 Exp1].\n    lets Cb: (wf_sto_to_cbounds_ctx Wf).\n    lets Sds1: (exp_preserves_sub_pr Cb St Exp1 Expm).\n    destruct Sds1 as [L1 Sds1].\n    assert (Sds: forall z, z \\notin L1 -> z \\notin L2 ->\n      subdecs pr (G & z ~ typ_bind Ds1) (open_decs z Ds1) (open_decs z Ds2)). {\n      intros z zL1 zL2. specialize (Sds1 z zL1). specialize (Sds2 z zL2).\n      apply (subdecs_trans Sds1).\n      destruct pr_narrowing as [_ [_ [_ [_ N]]]].\n      specialize (N pr _ _ _ Sds2 G empty z Ds1 Dsm eq_refl).\n      do 2 rewrite concat_empty_r in N.\n      refine (N _ eq_refl _ _ Sds1).\n      * admit. (* ok-stuff *)\n      * admit. (* !! does `cbounds_decs Dsm` hold ?? *)\n      * admit. (* !! does `cbounds_decs Ds1` hold ?? *)\n   }\n   pick_fresh z. assert (zL1: z \\notin L1) by auto. assert (zL2: z \\notin L2) by auto.\n   specialize (Sds z zL1 zL2).\n   (* T appears in env, and suppose env only typ_bind: *)\n   assert (Eq: X1 = typ_bind Ds1) by admit. (* <------ *)\n   subst.\n   (* precise substitution with BiG and Sds: *)\n   assert (Sds12: subdecs pr G (open_decs v Ds1) (open_decs v Ds2)) by admit.\n   apply (decs_has_open v) in Ds2Has.\n   lets Sd: (decs_has_preserves_sub Ds2Has Sds12).\n   destruct Sd as [D1' [Ds1Has Sd]].\n   assert (exists D1, open_dec v D1 = D1') by admit.\n   destruct H as [D1 Eq]. subst.\n   rename D2 into D2'.\n   assert (exists D2, open_dec v D2 = D2') by admit.\n   destruct H as [D2 Eq]. subst.\n   exists (open_dec v D1).\n   lets P: (@pr_subst_subdec v (typ_bind Ds1) (open_dec z D1) (open_dec z D2) G empty z).\n   unfold subst_ctx in P. rewrite map_empty in P.\n   repeat (progress rewrite -> concat_empty_r in P).\n   assert (Ok': ok (G & z ~ typ_bind Ds1)) by auto.\n   assert (Sd': subdec pr (G & z ~ typ_bind Ds1) (open_dec z D1) (open_dec z D2)) by admit.\n   specialize (P Sd' BiG Ok').\n   assert (Impl1: z \\notin fv_decs Ds1 -> z \\notin fv_dec D1) by admit.\n   assert (Impl2: z \\notin fv_decs Ds2 -> z \\notin fv_dec D2) by admit.\n   assert (FrD1: z \\notin fv_dec D1) by auto.\n   assert (FrD2: z \\notin fv_dec D2) by auto.\n   rewrite <- (@subst_intro_dec z v D1 FrD1) in P.\n   rewrite <- (@subst_intro_dec z v D2 FrD2) in P.\n   refine (conj _ P).\n   apply has_pr with (typ_bind Ds1) Ds1.\n   * exact BiG.\n   * apply exp_bind.\n   * apply (decs_has_close_admitted Ds1 D1 v Ds1Has).\n  + (* case has_var *)\n    intros G x0 X2 Ds2 l D2 Ty IHTy Exp2 IHExp Ds2Has s x _ Wf Eq. inversions Eq.\n    lets Ok: (wf_sto_to_ok_G Wf).\n    specialize (IHExp s eq_refl Wf x Ty). destruct IHExp as [Dsm [Expm Sds2]].\n    specialize (IHTy s x Wf eq_refl). destruct IHTy as [X1 [BiG St]].\n    assert (E: exists Ds1, exp pr G X1 Ds1) by admit. (* hopefully by wf_sto... *)\n    destruct E as [Ds1 Exp1].\n    lets Sds1: (exp_preserves_sub_pr Wf St Exp1 Expm).\n    specialize (Sds1 x (ty_var BiG)).\n    lets Sds: (subdecs_trans Sds1 Sds2).\n    apply (decs_has_open x) in Ds2Has.\n    lets P: (decs_has_preserves_sub Ds2Has Sds).\n    destruct P as [D1o [Ds1Has Sd]].\n    assert (E: exists D1, D1o = (open_dec x D1)) by admit.\n    destruct E as [D1 Eq]. subst D1o.\n    exists (open_dec x D1).\n    refine (conj _ Sd).\n    apply (has_pr BiG Exp1).\n    assert (decs_has (open_decs x Ds1) l (open_dec x D1)\n         -> decs_has Ds1 l D1) by admit. (* TODO does not hold! *) auto.\n\n  + (* case subtyp_refl *)\n    intros m G v L Lo2 Hi2 Has2 IHHas2 s Eq Wf. subst.\n    specialize (IHHas2 _ _ eq_refl Wf eq_refl).\n    destruct IHHas2 as [D1 [Has1 Sd]].\n    apply invert_subdec_typ_sync_left in Sd.\n    destruct Sd as [Lo1 [Hi1 [Eq [StLo StHi]]]]. subst D1.\n    apply subtyp_tmode. apply (subtyp_refl Has1).\n  + (* case subtyp_top *)\n    intros. apply subtyp_tmode. apply subtyp_top.\n  + (* case subtyp_bot *)\n    intros. apply subtyp_tmode. apply subtyp_bot.\n  + (* case subtyp_bind *)\n    intros L m G Ds1 Ds2 Sds IH s Eq Wf. subst.\n    apply subtyp_tmode. apply subtyp_bind with L.\n    intros z zL.\n    specialize (Sds z zL).\n    (* TODO: what if these Ds1 are not realizable?? Then we don't have hyp for IH! *)\n    refine (IH z zL _ eq_refl _).\n    assert (wf_sto empty (G & z ~ typ_bind Ds1)) by admit. (* <---- *)\n    eassumption.\n  + (* case subtyp_sel_l *)\n    intros m G x L Lo2 Hi2 T Has2 IHHas2 St IHSt s Eq Wf. subst.\n    specialize (IHHas2 _ _ eq_refl Wf eq_refl).\n    specialize (IHSt _ eq_refl Wf).\n    destruct IHHas2 as [D1 [Has1 Sd]].\n    apply invert_subdec_typ_sync_left in Sd.\n    destruct Sd as [Lo1 [Hi1 [Eq [StLo [_ StHi]]]]]. subst D1.\n    apply subtyp_tmode.\n    lets StHi1T: (subtyp_trans StHi IHSt).\n    apply (subtyp_sel_l Has1 StHi1T).\n  + (* case subtyp_sel_r *)\n    intros m G x L Lo2 Hi2 T Has2 IHHas StLo2Hi2 IHStLo2Hi2 StTLo2 IHStTLo2 s Eq Wf. subst.\n    specialize (IHHas _ _ eq_refl  Wf eq_refl).\n    specialize (IHStLo2Hi2 s eq_refl Wf).\n    specialize (IHStTLo2 s eq_refl Wf).\n    destruct IHHas as [D1 [Has1 Sd]].\n    apply invert_subdec_typ_sync_left in Sd.\n    destruct Sd as [Lo1 [Hi1 [Eq [StLo2Lo1 [StLo1Hi1 StHi1Hi2]]]]]. subst D1.\n    apply subtyp_tmode.\n    lets StTLo1: (subtyp_trans IHStTLo2 StLo2Lo1).\n    apply (subtyp_sel_r Has1 StLo1Hi1 StTLo1).\n  + (* case subtyp_tmode *)\n    introv St IHSt Eq Wf. subst. apply* IHSt.\n  + (* case subtyp_trans *)\n    introv St12 IH12 St23 IH23 Eq Wf. subst.\n    apply subtyp_trans with T2; auto_star.\n\n  + (* case subdec_typ *)\n    intros. subst. apply* subdec_typ.\n  + (* case subdec_fld *)\n    intros. subst. apply* subdec_fld.\n  + (* case subdec_mtd *)\n    intros. subst. apply* subdec_mtd.\n\n  + (* case subdecs_empty *)\n    intros. subst. apply* subdecs_empty.\n  + (* case subdecs_push *)\n    intros. subst. apply* subdecs_push.\n\n  + (* case ty_var *)\n    intros G x' T BiG s x Wf Eq. inversions Eq. exists T.\n    apply (conj BiG).\n    apply subtyp_refl_all.\n  + (* case ty_sbsm *)\n    intros G t T2 T3 Ty IHTy St23 IHSt23 s x Wf Eq. subst.\n    specialize (IHTy s x Wf eq_refl). destruct IHTy as [T1 [BiG St12]].\n    specialize (IHSt23 s eq_refl Wf).\n    exists T1. apply (conj BiG). apply (subtyp_trans St12 IHSt23).\nQed.\n*)\nPrint Assumptions ip2pr.\n\nLemma pr2ip:\n   (forall m G T Ds, exp m G T Ds -> exp ip G T Ds)\n/\\ (forall m G t L D, has m G t L D -> has ip G t L D)\n/\\ (forall m1 m2 G T1 T2, subtyp m1 m2 G T1 T2 -> subtyp ip m2 G T1 T2)\n/\\ (forall m G D1 D2, subdec m G D1 D2 -> subdec ip G D1 D2)\n/\\ (forall m G Ds1 Ds2, subdecs m G Ds1 Ds2 -> subdecs ip G Ds1 Ds2).\nAdmitted.\n\nLemma invert_subtyp_bind_oktrans: forall s G Ds1 Ds2,\n  wf_sto s G ->\n  subtyp ip oktrans G (typ_bind Ds1) (typ_bind Ds2) ->\n  exists L, forall z, z \\notin L ->\n            subdecs ip (G & z ~ typ_bind Ds1) (open_decs z Ds1) (open_decs z Ds2).\nProof.\n  introv Wf St. destruct ip2pr as [_ [_ [P _]]].\n  specialize (P _ _ _ _ _ St _ eq_refl Wf).\n  lets Exp1: (exp_bind pr G Ds1).\n  lets Exp2: (exp_bind pr G Ds2).\n  lets Cb: (wf_sto_to_cbounds_ctx Wf).\n  lets Q: (exp_preserves_sub_pr Cb P Exp1 Exp2).\n          (********************)\n  destruct Q as [L Q]. exists L. intros z zL. specialize (Q z zL). apply* pr2ip.\nQed.\n\n\n(* ###################################################################### *)\n(** ** Soundness helper lemmas *)\n\nLemma has_sound: forall s G x Ds1 ds l D2,\n  wf_sto s G ->\n  binds x (object Ds1 ds) s ->\n  has ip G (trm_var (avar_f x)) l D2 ->\n  exists Ds1 D1,\n    ty_defs G (open_defs x ds) (open_decs x Ds1) /\\\n    decs_has (open_decs x Ds1) l D1 /\\\n    subdec ip G D1 D2.\nProof.\n  introv Wf Bis Has.\n  apply invert_var_has_dec in Has.\n  destruct Has as [X2 [Ds2 [T [Tyx [Exp2 [Ds2Has Eq]]]]]]. subst.\n  destruct (invert_wf_sto_with_sbsm Wf Bis Tyx) as [St [Tyds Cb]].\n  lets St': (exp_to_subtyp Exp2).\n  lets Sds: (invert_subtyp_bind_oktrans Wf (subtyp_trans St St')).\n            (**************************)\n  destruct Sds as [L Sds].\n  pick_fresh z. assert (zL: z \\notin L) by auto. specialize (Sds z zL).\n  lets BiG: (sto_binds_to_ctx_binds Wf Bis).\n  lets Tyx1: (ty_var BiG).\n  lets Ok: (wf_sto_to_ok_G Wf).\n  assert (Ok': ok (G & z ~ typ_bind Ds1)) by auto.\n  lets Sds': (@subdecs_subst_principle _ z x (typ_bind Ds1)\n              (***********************) (open_decs z Ds1) (open_decs z Ds2) Ok' Sds Tyx1).\n  assert (zDs1: z \\notin fv_decs Ds1) by auto.\n  assert (zDs2: z \\notin fv_decs Ds2) by auto.\n  rewrite <- (@subst_intro_decs z x Ds1 zDs1) in Sds'.\n  rewrite <- (@subst_intro_decs z x Ds2 zDs2) in Sds'.\n  apply (decs_has_open x) in Ds2Has.\n  destruct (decs_has_preserves_sub Ds2Has Sds') as [D1 [Ds1Has Sd]].\n  exists Ds1 D1.\n  apply (conj Tyds (conj Ds1Has Sd)).\nQed.\n\nPrint Assumptions has_sound.\n\nLemma ty_open_defs_change_var: forall x y G ds Ds S,\n  ok (G & x ~ S) ->\n  ok (G & y ~ S) ->\n  x \\notin fv_defs ds ->\n  x \\notin fv_decs Ds ->\n  ty_defs (G & x ~ S) (open_defs x ds) (open_decs x Ds) ->\n  ty_defs (G & y ~ S) (open_defs y ds) (open_decs y Ds).\nProof.\n  introv Okx Oky Frds FrDs Ty.\n  destruct (classicT (x = y)) as [Eq | Ne].\n  + subst. assumption.\n  + assert (Okyx: ok (G & y ~ S & x ~ S)) by destruct* (ok_push_inv Okx).\n    assert (Ty': ty_defs (G & y ~ S & x ~ S) (open_defs x ds) (open_decs x Ds))\n      by apply (weaken_ty_defs_middle Ty Okyx).\n    rewrite* (@subst_intro_defs x y ds).\n    rewrite* (@subst_intro_decs x y Ds).\n    lets Tyy: (ty_var (binds_push_eq y S G)).\n    destruct (subst_principles y S) as [_ [_ [_ [_ [_ [_ [_ P]]]]]]].\n             (****************)\n    specialize (P _ _ _ Ty' (G & y ~ S) empty x).\n    rewrite concat_empty_r in P.\n    specialize (P eq_refl Tyy Okyx).\n    unfold subst_ctx in P. rewrite map_empty in P. rewrite concat_empty_r in P.\n    exact P.\nQed.\n\n\n(* ###################################################################### *)\n(** ** Progress *)\n\nTheorem progress_result: progress.\nProof.\n  introv Wf Ty. gen G e T Ty s Wf.\n  set (progress_for := fun s e =>\n                         (exists e' s', red e s e' s') \\/\n                         (exists x o, e = (trm_var (avar_f x)) /\\ binds x o s)).\n  apply (ty_has_mutind\n    (fun m G e l d Has => forall s, wf_sto s G -> m = ip -> progress_for s e)\n    (fun G e T Ty      => forall s, wf_sto s G ->           progress_for s e));\n    unfold progress_for; clear progress_for.\n  (* case has_trm *)\n  + intros. auto.\n  (* case has_var *)\n  + intros G v T Ds l D Ty IH Exp Has s Wf.\n    right. apply invert_ty_var in Ty. destruct Ty as [T' [St BiG]].\n    destruct (ctx_binds_to_sto_binds Wf BiG) as [o Bis].\n    exists v o. auto.\n  (* case has_pr *)\n  + intros. discriminate.\n  (* case ty_var *)\n  + intros G x T BiG s Wf.\n    right. destruct (ctx_binds_to_sto_binds Wf BiG) as [o Bis].\n    exists x o. auto.\n  (* case ty_sel *)\n  + intros G t l T Has IH s Wf.\n    left. specialize (IH s Wf eq_refl). destruct IH as [IH | IH].\n    (* receiver is an expression *)\n    - destruct IH as [s' [e' IH]]. do 2 eexists. apply (red_sel1 l IH).\n    (* receiver is a var *)\n    - destruct IH as [x [[X1 ds] [Eq Bis]]]. subst.\n      lets P: (has_sound Wf Bis Has).\n              (*********)\n      destruct P as [Ds1 [D1 [Tyds [Ds1Has Sd]]]].\n      destruct (decs_has_to_defs_has Tyds Ds1Has) as [d dsHas].\n      destruct (defs_has_fld_sync dsHas) as [r Eqd]. subst.\n      exists (trm_var r) s.\n      apply (red_sel Bis dsHas).\n  (* case ty_call *)\n  + intros G t m U V u Has IHrec Tyu IHarg s Wf. left.\n    specialize (IHrec s Wf eq_refl). destruct IHrec as [IHrec | IHrec].\n    - (* case receiver is an expression *)\n      destruct IHrec as [s' [e' IHrec]]. do 2 eexists. apply (red_call1 m _ IHrec).\n    - (* case receiver is  a var *)\n      destruct IHrec as [x [[Tds ds] [Eq Bis]]]. subst.\n      specialize (IHarg s Wf). destruct IHarg as [IHarg | IHarg].\n      * (* arg is an expression *)\n        destruct IHarg as [s' [e' IHarg]]. do 2 eexists. apply (red_call2 x m IHarg).\n      * (* arg is a var *)\n        destruct IHarg as [y [o [Eq Bisy]]]. subst.\n        lets P: (has_sound Wf Bis Has).\n                (*********)\n        destruct P as [Ds1 [D1 [Tyds [Ds1Has Sd]]]].\n        destruct (decs_has_to_defs_has Tyds Ds1Has) as [d dsHas].\n        destruct (defs_has_mtd_sync dsHas) as [body Eqd]. subst.\n        exists (open_trm y body) s.\n        apply (red_call y Bis dsHas).\n  (* case ty_new *)\n  + intros L G ds Ds Tyds F s Wf.\n    left. pick_fresh x.\n    exists (trm_var (avar_f x)) (s & x ~ (object Ds ds)).\n    apply* red_new.\n  (* case ty_sbsm *)\n  + intros. auto_specialize. assumption.\nQed.\n\nPrint Assumptions progress_result.\n\n\n(* ###################################################################### *)\n(** ** Preservation *)\n\nTheorem preservation_proof:\n  forall e s e' s' (Hred: red e s e' s') G T (Hwf: wf_sto s G) (Hty: ty_trm G e T),\n  exists H, wf_sto s' (G & H) /\\ ty_trm (G & H) e' T.\nProof.\n  intros s e s' e' Red. induction Red.\n  (* red_call *)\n  + intros G U3 Wf TyCall. rename H into Bis, H0 into dsHas, T into X1.\n    exists (@empty typ). rewrite concat_empty_r. apply (conj Wf).\n    apply invert_ty_call in TyCall.\n    destruct TyCall as [T2 [U2 [Has [StU23 Tyy]]]].\n    lets P: (has_sound Wf Bis Has).\n            (*********)\n    destruct P as [Ds1 [D1 [Tyds [Ds1Has Sd]]]].\n    apply invert_subdec_mtd_sync_left in Sd.\n    destruct Sd as [T1 [U1 [Eq [StT StU12]]]]. subst D1.\n    destruct (invert_ty_mtd_inside_ty_defs Tyds dsHas Ds1Has) as [L0 Tybody].\n    apply invert_ty_var in Tyy.\n    destruct Tyy as [T3 [StT3 Biy]].\n    pick_fresh y'.\n    rewrite* (@subst_intro_trm y' y body).\n    assert (Fry': y' \\notin fv_typ U3) by auto.\n    assert (Eqsubst: (subst_typ y' y U3) = U3)\n      by apply* subst_fresh_typ_dec_decs.\n    rewrite <- Eqsubst.\n    lets Ok: (wf_sto_to_ok_G Wf).\n    apply (@trm_subst_principle G y' y (open_trm y' body) T1 _).\n           (*******************)\n    - auto.\n    - assert (y'L0: y' \\notin L0) by auto. specialize (Tybody y' y'L0).\n      apply (ty_sbsm Tybody).\n      apply weaken_subtyp_end. auto. apply (subtyp_trans StU12 StU23).\n    - refine (ty_sbsm _ StT). refine (ty_sbsm _ StT3). apply (ty_var Biy).\n  (* red_sel *)\n  + intros G T3 Wf TySel. rename H into Bis, H0 into dsHas.\n    exists (@empty typ). rewrite concat_empty_r. apply (conj Wf).\n    apply invert_ty_sel in TySel.\n    destruct TySel as [T2 [StT23 Has]].\n    lets P: (has_sound Wf Bis Has).\n            (*********)\n    destruct P as [Ds1 [D1 [Tyds [Ds1Has Sd]]]].\n    apply invert_subdec_fld_sync_left in Sd.\n    destruct Sd as [T1 [Eq StT12]]. subst D1.\n    refine (ty_sbsm _ StT23).\n    refine (ty_sbsm _ StT12).\n    apply (invert_ty_fld_inside_ty_defs Tyds dsHas Ds1Has).\n  (* red_new *)\n  + rename T into Ds1. intros G T2 Wf Ty.\n    apply invert_ty_new in Ty.\n    destruct Ty as [StT12 [L [Tyds Cb]]].\n    exists (x ~ (typ_bind Ds1)).\n    pick_fresh x'. assert (Frx': x' \\notin L) by auto.\n    specialize (Tyds x' Frx').\n    assert (xG: x # G) by apply* sto_unbound_to_ctx_unbound.\n    split.\n    - apply (wf_sto_push _ Wf H xG).\n      * apply* (@ty_open_defs_change_var x').\n      * exact Cb. (* was a \"meh TODO\" before cbounds :-) *)\n    - lets Ok: (wf_sto_to_ok_G Wf). assert (Okx: ok (G & x ~ (typ_bind Ds1))) by auto.\n      apply (weaken_subtyp_end Okx) in StT12.\n      refine (ty_sbsm _ StT12). apply ty_var. apply binds_push_eq.\n  (* red_call1 *)\n  + intros G Tr2 Wf TyCall.\n    apply invert_ty_call in TyCall.\n    destruct TyCall as [Ta [Tr1 [Has [St Tya]]]].\n    apply invert_has in Has.\n    destruct Has as [Has | Has].\n    - (* case has_trm *)\n      destruct Has as [To [Ds [Tyo [Exp [DsHas Clo]]]]].\n      specialize (IHRed G To Wf Tyo). destruct IHRed as [H [Wf' Tyo']].\n      lets Ok: (wf_sto_to_ok_G Wf').\n      exists H. apply (conj Wf').\n      apply (weaken_subtyp_end Ok) in St.\n      refine (ty_sbsm _ St).\n      apply (@ty_call (G & H) o' m Ta Tr1 a).\n      * refine (has_trm Tyo' _ DsHas Clo).\n        apply (weaken_exp_end Ok Exp).\n      * apply (weaken_ty_trm_end Ok Tya).\n    - (* case has_var *)\n      destruct Has as [x [Tx [Ds [D' [Eqx _]]]]]. subst.\n      inversion Red. (* contradiction: vars don't step *)\n  (* red_call2 *)\n  + intros G Tr2 Wf TyCall.\n    apply invert_ty_call in TyCall.\n    destruct TyCall as [Ta [Tr1 [Has [St Tya]]]].\n    specialize (IHRed G Ta Wf Tya).\n    destruct IHRed as [H [Wf' Tya']].\n    exists H. apply (conj Wf').\n    lets Ok: wf_sto_to_ok_G Wf'.\n    apply (weaken_subtyp_end Ok) in St.\n    refine (ty_sbsm _ St).\n    apply (@ty_call (G & H) _ m Ta Tr1 a').\n    - apply (weaken_has_end Ok Has).\n    - assumption.\n  (* red_sel1 *)\n  + intros G T2 Wf TySel.\n    apply invert_ty_sel in TySel.\n    destruct TySel as [T1 [St Has]].\n    apply invert_has in Has.\n    destruct Has as [Has | Has].\n    - (* case has_trm *)\n      destruct Has as [To [Ds [Tyo [Exp [DsHas Clo]]]]].\n      specialize (IHRed G To Wf Tyo). destruct IHRed as [H [Wf' Tyo']].\n      lets Ok: (wf_sto_to_ok_G Wf').\n      exists H. apply (conj Wf').\n      apply (weaken_subtyp_end Ok) in St.\n      refine (ty_sbsm _ St). apply (@ty_sel (G & H) o' l T1).\n      refine (has_trm Tyo' _ DsHas Clo).\n      apply (weaken_exp_end Ok Exp).\n    - (* case has_var *)\n      destruct Has as [x [Tx [Ds [D' [Eqx _]]]]]. subst.\n      inversion Red. (* contradiction: vars don't step *)\nQed.\n\nTheorem preservation_result: preservation.\nProof.\n  introv Hwf Hty Hred.\n  destruct (preservation_proof Hred Hwf Hty) as [H [Hwf' Hty']].\n  exists (G & H). split; assumption.\nQed.\n\nPrint Assumptions preservation_result.\n", "meta": {"author": "samuelgruetter", "repo": "dot-calculus", "sha": "f34c4f142c48ecc60c4aa50720a0cda93189da43", "save_path": "github-repos/coq/samuelgruetter-dot-calculus", "path": "github-repos/coq/samuelgruetter-dot-calculus/dot-calculus-f34c4f142c48ecc60c4aa50720a0cda93189da43/dev/expansion/predict-max-ctx-size-ip-pr-muDot.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2842324466776147}}
{"text": "(**************************************************************************)\n(*           *                                                            *)\n(*     _     *   The Coccinelle Library / Evelyne Contejean               *)\n(*    <o>    *          CNRS-LRI-Universite Paris Sud                     *)\n(*  -/@|@\\-  *                   A3PAT Project                            *)\n(*  -@ | @-  *                                                            *)\n(*  -\\@|@/-  *      This file is distributed under the terms of the       *)\n(*    -v-    *      CeCILL-C licence                                      *)\n(*           *                                                            *)\n(**************************************************************************)\n\n(* Usable rules, adapted from the exam of Xavier for MPRI 2-5, 2009 *)\n\n\n(** * Termination of rewriting *)\n\nFrom Coq Require Import List Relations Wellfounded Arith Recdef Setoid.\nFrom CoLoR Require Import closure more_list weaved_relation term_spec\n     equational_theory_spec dp graph_dp terminaison interp.\n\nModule MakeUsableDP (E : EqTh).\n\n  Module GDp := graph_dp.MakeGDP (E).\n  Import GDp.\n  Import Dp.\n  Import E.\n  Import T.\n\nDefinition filter_top R G : relation term := \n  fun r l => R r l /\\ match l with Var _ => False | Term f _ => G f end.\n\nDefinition symb_sup_gen R1 R2 : relation symbol :=\n  fun f g => \n            exists r, exists l, \n            filter_top R1 (fun f' => f = f') r l /\\ \n            symb_in_term g r = true /\\ \n            defined R2 g.\n\nLemma symb_sup_gen_list : \n  forall R1 Rlist1 R2 Rlist2, (forall l r, R1 r l <-> In (l,r) Rlist1) -> (forall l r, R2 r l <-> In (l,r) Rlist2) -> \n  {Slist | forall f g, symb_sup_gen R1 R2 f g <-> In (f,g) Slist}.\nProof.\nintros R1 Rlist1; revert R1.\ninduction Rlist1 as [ | [l r] Rlist1]; intros R1 R2 Rlist2 Rlist_ok1 Rlist_ok2.\nexists nil; intros f g; split; intro H.\ndestruct H as [r [l [[H _] _]]]; rewrite Rlist_ok1 in H; contradiction.\ncontradiction.\nset (R' := fun b a => R1 b a /\\ In (a,b) Rlist1).\nassert (Rlist_ok' : forall a b, R' b a <-> In (a,b) Rlist1).\nintros a b; split; intro H.\ndestruct H as [_ H]; assumption.\nsplit; [rewrite Rlist_ok1; right | ]; assumption.\ndestruct (IHRlist1 R' R2 Rlist2 Rlist_ok' Rlist_ok2) as [Slist Slist_ok].\ndestruct l as [x | f l].\nexists Slist; intros f g; split.\nintros [u [v [[H1 H2] [H3 H4]]]].\nrewrite Rlist_ok1 in H1; simpl in H1; destruct H1 as [H1 | H1].\ninjection H1; intros; subst; contradiction H2.\nrewrite <- Slist_ok; exists u; exists v; split; split.\nrewrite Rlist_ok'; assumption.\nassumption.\nassumption.\ndestruct H4 as [g l t H4]; constructor 1 with l t.\nassumption.\nintro H; rewrite <- Slist_ok in H; destruct H as [u [v [[H1 H2] [H3 H4]]]].\nexists u; exists v; split; split.\nrewrite Rlist_ok1; right; rewrite <- Rlist_ok'; assumption.\nassumption.\nassumption.\ndestruct H4 as [g l t H4]; constructor 1 with l t.\nassumption.\nexists ((map (fun g => (f,g)) (filter (fun g => if defined_dec _ _ Rlist_ok2 g then true else false) (symb_list r))) ++ Slist).\nintros g g'; split; intro H.\ndestruct H as [u [v [H1 [H2 H3]]]].\ndestruct H1 as [H H1].\nrewrite Rlist_ok1 in H; simpl in H; destruct H as [H | H].\ninjection H; clear H; intros; subst; subst.\napply in_or_app; left; rewrite in_map_iff; exists g'; split; [apply eq_refl | ].\nrewrite filter_In; split.\nrewrite symb_list_ok; assumption.\ndestruct (defined_dec R2 Rlist2 Rlist_ok2 g') as [Dg' | NDg'].\napply eq_refl.\napply False_rect; apply NDg'; assumption.\napply in_or_app; right; rewrite <- Slist_ok.\nexists u; exists v; split; split.\nrewrite Rlist_ok'; assumption.\nassumption.\nassumption.\nassumption.\ndestruct (in_app_or _ _ _ H) as [H1 | H2]; clear H.\nrewrite in_map_iff in H1; destruct H1 as [g'' [H1 H2]].\ninjection H1; clear H1; intros; subst.\nrewrite filter_In in H2; destruct H2 as [g'_in_r H2].\ndestruct (defined_dec R2 Rlist2 Rlist_ok2 g') as [Dg' | NDg']; [ clear H2 | discriminate H2].\nexists r; exists (Term g l); split; split.\nrewrite Rlist_ok1; left; apply eq_refl.\napply eq_refl.\nrewrite <- symb_list_ok; assumption.\nassumption.\nrewrite <- Slist_ok in H2; destruct H2 as [u [v [[H1 H2]  [H3 H4]]]].\nexists u; exists v; split; split.\nrewrite Rlist_ok1; right; rewrite <- Rlist_ok'; assumption.\nassumption.\nassumption.\nassumption.\nDefined.\n\nDefinition symb_sup R : relation symbol :=\n  fun f g => \n      exists r, exists l, \n      filter_top R (fun f' => f = f') r l /\\ \n      symb_in_term g r = true /\\ \n      defined R g.\n\nDefinition Usable R t : relation term :=\n   filter_top R \n   (fun g => exists f, symb_in_term f t = true /\\ \n                       refl_trans_clos (symb_sup R) f g).\n\nDefinition UsableRules (R C : relation term) : relation term :=\n  fun u v => exists r, exists l, C r l /\\ Usable R r u v.\n\nLemma symb_sup_list : \n  forall R Rlist, (forall l r, R r l <-> In (l,r) Rlist) -> \n  {Slist | forall f g, symb_sup R f g <-> In (f,g) Slist}.\nProof.\nintros R Rlist Rlist_ok.\nexact (symb_sup_gen_list R Rlist R Rlist Rlist_ok Rlist_ok).\nDefined.\n\nLemma usable_dec : \n  forall R Rlist, (forall l r, R r l <-> In (l,r) Rlist) -> \n  forall t, {URlist | forall r l,  Usable R t r l <-> In (l,r) URlist}.\nProof.\nintros R Rlist Rlist_ok t.\ndestruct (symb_sup_list _ _ Rlist_ok) as [Slist Slist_ok].\nassert (SR_dec := refl_trans_clos_dec _ F.Symb.eq_bool_ok _ _ Slist_ok).\nunfold Usable; set (SR := refl_trans_clos (symb_sup R)) in *; clearbody SR; clear Slist Slist_ok.\nrevert R Rlist_ok; induction Rlist as [ | [l r] Rlist]; intros R Rlist_ok.\nexists nil; intros r l; split; intro H.\ndestruct H as [H _]; rewrite Rlist_ok in H; assumption.\ncontradiction.\nset (R' := fun b a => R b a /\\ In (a,b) Rlist).\nassert (Rlist_ok' : forall a b, R' b a <-> In (a,b) Rlist).\nintros a b; split; intro H.\ndestruct H as [_ H]; assumption.\nsplit; [rewrite Rlist_ok; right | ]; assumption.\ndestruct (IHRlist _ Rlist_ok') as [URlist URlist_ok].\ndestruct l as [x | f l].\nexists URlist; intros u v; split; intro H.\ndestruct H as [H1 H2]; rewrite Rlist_ok in H1; simpl in H1; destruct H1 as [H1 | H1].\ninjection H1; clear H1; intros; subst.\ncontradiction.\nrewrite <- URlist_ok; split; [rewrite Rlist_ok' | ]; assumption.\nrewrite <- URlist_ok in H; destruct H as [H1 H2]; split; [ rewrite Rlist_ok; right; rewrite <- Rlist_ok' | ]; assumption.\nassert (split_case : {f0 : symbol | symb_in_term f0 t = true /\\ SR f0 f}+{forall f0, ~(symb_in_term f0 t = true /\\ SR f0 f)}).\ncase_eq (filter (fun g => if SR_dec g f then true else false) (symb_list t)).\nintro H; right; intros g [g_in_t Sgf].\nassert (g_in_nil : In g nil).\nrewrite <- H; rewrite filter_In; split.\nrewrite symb_list_ok; assumption.\ndestruct (SR_dec g f); [apply eq_refl | absurd (SR g f); assumption].\ncontradiction g_in_nil.\nintros g k H; left; exists g.\nassert (g_in_gk : In g (g :: k)).\nleft; apply eq_refl.\nrewrite <- H in g_in_gk; rewrite filter_In in g_in_gk; destruct g_in_gk as [g_in_t Sgf]; split.\nrewrite <- symb_list_ok; assumption.\ndestruct (SR_dec g f); [assumption | discriminate].\ndestruct split_case as [[g [g_in_t Sgf]] | Ko].\nexists ((Term f l,r) :: URlist); intros u v; split; intro H.\ndestruct H as [H1 H2].\nrewrite Rlist_ok in H1; simpl in H1; destruct H1 as [H1 | H1].\nleft; assumption.\nright; rewrite <- URlist_ok; split; [rewrite Rlist_ok' | ]; assumption.\nsimpl in H; destruct H as [H | H].\ninjection H; clear H; intros; subst; split.\nrewrite Rlist_ok; left; apply eq_refl.\nexists g; split; assumption.\nrewrite <- URlist_ok in H; destruct H as [H1 H2]; split; [ rewrite Rlist_ok; right; rewrite <- Rlist_ok' | ]; assumption.\nexists URlist; intros u v; split; intro H.\ndestruct H as [H1 H2]; rewrite Rlist_ok in H1; simpl in H1; destruct H1 as [H1 | H1].\ninjection H1; clear H1; intros; subst.\ndestruct H2 as [g H2]; apply False_rect; apply (Ko g); assumption.\nrewrite <- URlist_ok; split; [rewrite Rlist_ok' | ]; assumption.\nrewrite <- URlist_ok in H; destruct H as [H1 H2]; split; [ rewrite Rlist_ok; right; rewrite <- Rlist_ok' | ]; assumption.\nDefined.\n\nLemma usablerules_dec : \n  forall R Rlist, (forall l r, R r l <-> In (l,r) Rlist) -> \n  forall P Plist, (forall u v, P v u <-> In (u,v) Plist) ->\n  {URlist | forall l r,  UsableRules R P r l <-> In (l,r) URlist}.\nProof.\nintros R Rlist Rlist_ok P Plist; revert P; induction Plist as [ | [u v] Plist]; intros P Plist_ok.\nexists nil; intros l r; split; intro H.\ndestruct H as [u [v [H _]]]; rewrite Plist_ok in H; assumption.\ncontradiction.\nset (P' := fun b a => P b a /\\ In (a,b) Plist).\nassert (Plist_ok' : forall a b, P' b a <-> In (a,b) Plist).\nintros a b; split; intro H.\ndestruct H as [_ H]; assumption.\nsplit; [rewrite Plist_ok; right | ]; assumption.\ndestruct (IHPlist _ Plist_ok') as [URlist URlist_ok].\ndestruct (usable_dec _ _ Rlist_ok v) as [Uv Uv_ok].\nexists (Uv ++ URlist); intros l r; split; intro H.\ndestruct H as [s [t [H1 H2]]].\nrewrite Plist_ok in H1; simpl in H1; destruct H1 as [H1 | H1].\ninjection H1; clear H1; intros; subst.\napply in_or_app; left; rewrite <- Uv_ok; assumption.\napply in_or_app; right; rewrite <- URlist_ok; exists s; exists t; split; [ rewrite Plist_ok' | ]; assumption.\ndestruct (in_app_or _ _ _ H) as [H1 | H1]; clear H.\nrewrite <- Uv_ok in H1.\nexists v; exists u; split; [rewrite Plist_ok; left; apply eq_refl | assumption].\nrewrite <- URlist_ok in H1; destruct H1 as [s [t [H1 H2]]].\nexists s; exists t; split; [ rewrite Plist_ok; right; rewrite <- Plist_ok' |  ]; assumption.\nDefined.\n\nLemma eq_term_dec2 : forall (s12 t12 : term * term), {s12 = t12}+{s12 <> t12}.\nProof.\nintros [s1 s2] [t1 t2].\ngeneralize (T.eq_bool_ok s1 t1); case (T.eq_bool s1 t1); [intro s1_eq_t1 | intro s1_diff_t1].\ngeneralize (T.eq_bool_ok s2 t2); case (T.eq_bool s2 t2); [intro s2_eq_t2 | intro s2_diff_t2].\nleft; apply f_equal2; assumption.\nright; intro s12_eq_t12; apply s2_diff_t2; injection s12_eq_t12; intros s2_eq_t2 _; assumption.\nright; intro s12_eq_t12; apply s1_diff_t1; injection s12_eq_t12; intros _ s1_eq_t1; assumption.\nDefined.\n\nLemma split_rules :\n  forall R Rlist, (forall l r, R r l <-> In (l,r) Rlist) ->\n  forall P Plist, (forall u v, P v u <-> In (u,v) Plist) ->\n  (forall v t, ~ R t (Var v)) ->\n  forall G, \n  (forall f, G f <-> defined (fun r l => R r l /\\ ~ UsableRules R P r l) f) -> \n  (forall r l, R r l <-> (UsableRules R P r l \\/ filter_top R G r l)) /\\\n  (forall r l, UsableRules R P r l -> forall g, symb_in_term g r = true -> ~G g).\nProof.\nintros R Rlist Rlist_ok P Plist Plist_ok R_var G Gdef.\nassert (Pdec := rel_dec P Plist Plist_ok).\ndestruct (usablerules_dec _ _ Rlist_ok _ _ Plist_ok) as [URlist URlist_ok].\nsplit.\nintros r l; split; intro H.\nrewrite URlist_ok.\ndestruct (In_dec eq_term_dec2 (l,r) URlist) as [lr_in_U | lr_not_in_U].\nleft; assumption.\nright; split; [assumption | destruct l as [x | f l]].\napply (R_var _ _ H).\nrewrite Gdef; constructor 1 with l r; split; [ | rewrite URlist_ok]; assumption.\ndestruct H as [[v [u [_ [H _]]]] | [H _]]; assumption.\nintros r [x | f l] [v [u [H1 [H2 H3]]]] g g_in_r Gg.\ncontradiction H3.\nrewrite Gdef in Gg; inversion Gg as [g' k t [K1 K2]]; subst g'.\napply K2; constructor 1 with v; exists u; split.\nassumption.\nsplit; [assumption | destruct H3 as [f' [H3 H4]]; exists f'; split].\nassumption.\napply refl_trans_clos_is_trans with f; trivial.\nright; left; constructor 1 with r; exists (Term f l); split.\nsplit; [assumption | apply eq_refl].\nsplit; [ | constructor 1 with k t]; assumption.\nQed.\n\nLemma Gdec :\n  forall R Rlist, (forall l r, R r l <-> In (l,r) Rlist) ->\n  forall P Plist, (forall u v, P v u <-> In (u,v) Plist) ->\n  let G := fun f => defined (fun r l => R r l /\\ ~ UsableRules R P r l) f in \n  forall f, {~G f} + {G f}.\nProof.\nintros R Rlist Rlist_ok P Plist Plist_ok.\nassert (H : {rule_list : list (term * term) |\n (forall l r : term, R r l /\\ ~ UsableRules R P r l <-> In (l, r) rule_list)}).\ndestruct (usablerules_dec _ _ Rlist_ok _ _ Plist_ok) as [URlist URlist_ok].\nexists (filter (fun st => if In_dec eq_term_dec2 st URlist then false else true) Rlist).\nintros l r; split.\nintros [H1 H2]; rewrite filter_In; split.\nrewrite <- Rlist_ok; assumption.\ndestruct (In_dec eq_term_dec2 (l,r) URlist).\napply False_rect; apply H2; rewrite URlist_ok; assumption.\napply eq_refl.\nrewrite filter_In; intros [H1 H2]; split.\nrewrite Rlist_ok; assumption.\ndestruct (In_dec eq_term_dec2 (l,r) URlist).\ndiscriminate.\nrewrite URlist_ok; assumption.\ndestruct H as [rule_list H].\nintros G f;\ndestruct (defined_dec(fun r l : term => R r l /\\ ~ UsableRules R P r l) _ H f) as [Df | nDf].\nright; assumption.\nleft; assumption.\nDefined.\n\n(*\nDefinition pair_sup_symb (R P : relation term) g :=\n  exists r, exists l, P r l /\\ exists g', symb_in_term g' r = true /\\ refl_trans_clos (symb_sup R) g' g.\n*)\nInductive Pi pi (v1 v2 : variable) : relation term :=\n  | Pi1 : Pi pi v1 v2 (Var v1) (Term pi (Var v1 :: Var v2 :: nil))\n  | Pi2 : Pi pi v1 v2 (Var v2) (Term pi (Var v1 :: Var v2 :: nil)).\n\nDefinition is_primary_pi pi R := \n   forall s t, R s t -> (forall f, ((symb_in_term f s = true -> f <> pi) /\\\n                                             (symb_in_term f t = true -> f <> pi))).\n\nSection Interp_definition.\nVariable V0 : variable.\nVariable V1 : variable.\nVariable V0_diff_V1 : V0 <> V1.\nVariable pi : symbol.\nVariable bot : symbol.\nVariable R : relation term.\nVariable R_reg : forall s t, R s t -> forall x, In x (var_list s) -> In x (var_list t) .\nVariable R_var : forall v t, ~ R t (Var v).\nVariable Rlist : list (term * term).\nVariable Rlist_ok : forall l r, R r l <-> In (l,r) Rlist.\nVariable PPi : is_primary_pi pi R. \nVariable G : symbol -> Prop.\nVariable P : relation term.\nVariable Plist : list (term * term).\nVariable Plist_ok : forall u v, P v u <-> In (u,v) Plist.\nVariable Gdef' : \n  forall f, G f <-> defined (fun r l => R r l /\\ ~ UsableRules R P r l) f.\n\nLemma Gdef : forall f, G f -> defined R f.\nProof.\nintros f Gf; rewrite Gdef' in Gf; inversion Gf as [f' l t [H _]]; subst f'.\nconstructor 1 with l t; assumption.\nQed.\n\nDefinition R_red := compute_red Rlist.\nDefinition FB : forall t s, In s (R_red t) <-> one_step R s t.\napply compute_red_is_correct.\nintros l r H; apply R_reg; rewrite Rlist_ok; assumption.\nassumption.\nDefined.\n\nFixpoint Comb (l : list term) : term :=\n  match l with\n  | nil => Term bot nil\n  | t :: l => Term pi (t :: (Comb l) :: nil)\n  end.\n\nInductive interp_call : term -> term -> Prop :=\n  | Subt : forall f1 l t, In t l -> interp_call t (Term f1 l)\n  | Defd : forall f2 l t, G f2 -> one_step R t (Term f2 l) -> interp_call t (Term f2 l).\n\nDefinition Interp_dom t :=\n  forall p f l, subterm_at_pos t p = Some (Term f l) -> G f -> Acc (one_step R) (Term f l).\n\nLemma interp_dom_subterm :\n  forall s t p, Interp_dom s -> subterm_at_pos s p = Some t -> Interp_dom t.\nProof.\nintros s t p Is Sub q g l Sub' Dg.\napply Is with (p ++ q); trivial.\napply subterm_in_subterm with t; trivial.\nQed.\n\nLemma acc_one_step_interp_dom : \n\tforall t, Acc (one_step R) t -> Interp_dom t.\nProof.\nintros t Acc_t; rewrite acc_with_subterm in Acc_t; induction Acc_t as [t Acc_t' IH].\nassert (Acc_t : Acc (union term (one_step R) direct_subterm) t).\napply Acc_intro; apply Acc_t'.\nclear Acc_t'.\nintros p f l K f_not_in_H.\napply acc_subterms_3 with p t; trivial.\nrewrite acc_with_subterm; assumption.\nQed.\n\nLemma interp_well_defined : forall t, Interp_dom t -> Acc interp_call t.\nProof.\nintro t; pattern t; apply term_rec3; clear t.\nintros v _.\napply Acc_intro; intros t K; inversion K.\nintros f l IH K.\napply Acc_intro; intros t K'; inversion K'; subst.\napply IH; trivial.\ndestruct (in_split _ _ H1) as [l1 [l2 K'']].\napply interp_dom_subterm with (Term f l) (length l1 :: nil); trivial.\nsubst l; simpl; rewrite nth_error_at_pos; apply eq_refl.\napply Acc_inv with (Term f l); trivial.\ngeneralize (K nil f l (eq_refl _) H2).\nset (s := Term f l) in *; clearbody s; clear.\nintro Acc_s; rewrite acc_with_subterm in Acc_s.\ninduction Acc_s as [s Acc_s' IH].\nassert (Acc_s : Acc (union term (one_step R) direct_subterm) s).\napply Acc_intro; apply Acc_s'.\nclear Acc_s'.\napply Acc_intro; intros t K; inversion K; clear K; subst.\napply IH; right; assumption.\napply IH; left; assumption.\nQed.\n\nInductive Interp : term -> term -> Prop :=\n  | Vcase : forall x, Interp (Var x) (Var x)\n  | notGcase : forall f l l' ll , ~G f -> \n                l = (map (fun st => fst st)) ll -> l' = (map (fun st => snd st)) ll ->\n                (forall s s', In (s,s') ll -> Interp s s') -> \n                Interp (Term f l) (Term f l')\n  | Gcase : forall f l l' ll k' kk, G f ->\n               l = (map (fun st => fst st)) ll -> l' = (map (fun st => snd st)) ll ->\n               (forall s s', In (s,s') ll -> Interp s s') -> \n               R_red (Term f l) = (map (fun st => fst st)) kk -> k' = (map (fun st => snd st)) kk ->\n               (forall s s', In (s,s') kk -> Interp s s') -> \n               Interp (Term f l) (Comb (Term f l' :: k')).\n\nLemma interp_unicity : forall t, Acc interp_call t -> forall s1 s2, Interp t s1 -> Interp t s2 -> s1 = s2.\nProof.\nintros t Acc_t;\ninduction Acc_t as [t Acc_t IH].\ndestruct t as [x | f l];\nintros s1 s2 H1 H2; \ninversion H1 as [ | f1 l1 l1' ll1 Cf1 Hl1 Hl1' Hll1 | f1 l1 l1' ll1 k1 kk1 Df1 Hl1 Hl1' Hll1 Hk1 Hk1' Hkk1];\ninversion H2 as [ | f2 l2 l2' ll2 Cf2 Hl2 Hl2' Hll2 | f2 l2 l2' ll2 k2 kk2 Df2 Hl2 Hl2' Hll2 Hk2 Hk2' Hkk2]; subst; trivial.\n(* 1/4 f not in G *)\ndo 2 apply f_equal.\nassert (K : forall s s1 s2, In (s,s1) ll1 -> In (s,s2) ll2 -> s1 = s2).\nintros s s1 s2 ss1_in_ll1 ss2_in_ll2.\nassert (s_in_l : In s (map (fun st => fst st) ll1)).\nrewrite in_map_iff; exists (s,s1); split; trivial.\napply IH with s.\nleft; assumption.\ndestruct (in_split _ _ s_in_l) as [kk1 [kk2 K]].\napply Hll1; assumption.\napply Hll2; assumption.\nclear -Hl2 K.\nrevert ll2 Hl2 K.\ninduction ll1 as [ | [s s1] ll1]; intros [ | [s' s2] ll2] Hl2 K; trivial.\ndiscriminate.\ndiscriminate.\nsimpl in Hl2; injection Hl2; clear Hl2; intros H' s_eq_s'; subst s'.\nrewrite (K s s1 s2); try (left; trivial).\nrewrite IHll1 with ll2; trivial.\nintros t t1 t2 tt1_in_ll1 tt2_in_ll2; apply (K t t1 t2); right; trivial.\nabsurd (G f); trivial.\nabsurd (G f); trivial.\n(* 1/1 f in G *)\napply f_equal; apply f_equal2.\ndo 2 apply f_equal.\nassert (K : forall s s1 s2, In (s,s1) ll1 -> In (s,s2) ll2 -> s1 = s2).\nintros s s1 s2 ss1_in_ll1 ss2_in_ll2.\nassert (s_in_l : In s (map (fun st => fst st) ll1)).\nrewrite in_map_iff; exists (s,s1); split; trivial.\napply IH with s.\nleft; assumption.\ndestruct (in_split _ _ s_in_l) as [lll1 [lll2 K]].\napply Hll1; assumption.\napply Hll2; assumption.\nclear -Hl2 K.\nrevert ll2 Hl2 K.\ninduction ll1 as [ | [s s1] ll1]; intros [ | [s' s2] ll2] Hl2 K; trivial.\ndiscriminate.\ndiscriminate.\nsimpl in Hl2; injection Hl2; clear Hl2; intros H' s_eq_s'; subst s'.\nrewrite (K s s1 s2); try (left; trivial).\nrewrite IHll1 with ll2; trivial.\nintros t t1 t2 tt1_in_ll1 tt2_in_ll2; apply (K t t1 t2); right; trivial.\napply f_equal.\nassert (K : forall s s1 s2, In (s,s1) kk1 -> In (s,s2) kk2 -> s1 = s2).\nintros s s1 s2 ss1_in_kk1 ss2_in_kk2.\nassert (s_in_l : In s (map (fun st => fst st) kk1)).\nrewrite in_map_iff; exists (s,s1); split; trivial.\napply IH with s.\nright; trivial.\nrewrite <- FB; rewrite Hk1; assumption.\ndestruct (in_split _ _ s_in_l) as [kkk1 [kkk2 K]].\napply Hkk1; assumption.\napply Hkk2; assumption.\nrewrite Hk1 in Hk2.\nclear -Hk2 K.\nrevert kk2 Hk2 K.\ninduction kk1 as [ | [s s1] kk1]; intros [ | [s' s2] kk2] Hk2 K; trivial.\ndiscriminate.\ndiscriminate.\nsimpl in Hk2; injection Hk2; clear Hk2; intros H' s_eq_s'; subst s'.\nrewrite (K s s1 s2); try (left; trivial).\nrewrite IHkk1 with kk2; trivial.\nintros t t1 t2 tt1_in_ll1 tt2_in_ll2; apply (K t t1 t2); right; trivial.\nQed.\n\nLemma interp_defined : forall t, Acc interp_call t -> {t' | Interp t t'}.\nProof.\nintros t Acc_t; induction Acc_t as [t Acc_t' IH].\nassert (Acc_t : Acc interp_call t).\napply Acc_intro; apply Acc_t'.\nclear Acc_t'; destruct t as [x | f l].\nexists (Var x); apply Vcase.\nassert (Il : {ll : list (term * term) | l = map (@fst term term) ll /\\ forall t t', In (t,t') ll -> Interp t t'}).\nassert (IHl : forall t, In t l -> {t' : term | Interp t t'}).\nintros t t_in_l.\napply IH; left; trivial.\nrevert IHl; clear; induction l as [ | t l]; intros IH.\nexists nil; split; [apply eq_refl | intros; contradiction].\ndestruct (IHl (tail_set _ IH)) as [ll [H1 H2]].\ndestruct (IH _ (or_introl _ (eq_refl _))) as [t' H3].\nexists ((t,t') :: ll); split; \n[ subst l; apply eq_refl\n| intros u u' [uu'_eq_tt' | uu'_in_ll]; [injection uu'_eq_tt'; intros; subst; assumption | apply H2; assumption]].\ndestruct Il as [ll [H1 H2]].\ndestruct (Gdec _ _ Rlist_ok _ _ Plist_ok f) as [f_not_in_G | f_in_G].\n(* 1/2 f not in G *)\nexists (Term f (map (@snd _ _) ll)).\napply notGcase with ll; trivial.\nrewrite Gdef'; assumption.\n(* 1/1 f in G *)\nassert (Ik : {kk : list (term * term) |  R_red  (Term f l) = map (@fst term term) kk /\\ forall t t', In (t,t') kk -> Interp t t'}).\nassert (IHk : forall t, In t (R_red (Term f l)) -> {t' : term | Interp t t'}).\nintros t t_in_red; rewrite FB in t_in_red.\napply IH; right; trivial.\nrewrite Gdef'; assumption.\nrevert IHk; generalize ((R_red (Term f l))); clear.\nintro k; induction k as [ | t k]; intro Hk.\nexists nil; split; [apply eq_refl | intros; contradiction].\ndestruct (IHk (tail_set _ Hk)) as [kk [H1 H2]].\ndestruct (Hk _ (or_introl _ (eq_refl _))) as [t' H3].\nexists ((t,t') :: kk); split; \n[ subst k; apply eq_refl\n| intros u u' [uu'_eq_tt' | uu'_in_ll]; [injection uu'_eq_tt'; intros; subst; assumption | apply H2; assumption]].\ndestruct Ik as [kk [K1 K2]].\nexists (Comb (Term f (map (@snd _ _) ll) :: (map (@snd _ _) kk))).\napply Gcase with ll kk; trivial.\nrewrite Gdef'; assumption.\nQed.\n\nLemma project_comb :  forall t l, In t l -> rwr (Pi pi V0 V1) t (Comb l).\nProof.\nintros t l; induction l as [ | a l].\ncontradiction.\nsimpl; set (sigma := (V0,a) :: (V1, Comb l) :: nil).\nassert (H1 : a = apply_subst sigma (Var V0)).\nsimpl; rewrite eq_var_bool_refl; apply eq_refl.\nassert (H2 : Comb l = apply_subst sigma (Var V1)).\nsimpl; rewrite eq_var_bool_refl; case_eq (eq_var_bool V1 V0).\nintro V1_eq_V0; apply False_rect; apply V0_diff_V1; apply sym_eq.\ngeneralize (eq_var_bool_ok V1 V0); rewrite V1_eq_V0; intro; assumption.\nintros _; apply eq_refl.\nassert (H3 : Term pi (a :: Comb l :: nil) = apply_subst sigma (Term pi (Var V0 :: Var V1 :: nil))).\nrewrite H1, H2; apply eq_refl.\nintros [t_eq_a | t_in_l].\nsubst t; do 2 left.\nrewrite H3, H1; apply instance; left.\napply trans_clos_is_trans with (Comb l).\napply IHl; assumption.\nrewrite H3, H2; do 2 left; apply instance; right.\nQed.\n\nLemma interp_in_H :\n  forall t, (forall g, symb_in_term g t = true -> ~G g) ->\n  forall sigma sigma', (forall x, In x (var_list t) -> Interp (apply_subst sigma (Var x)) (apply_subst sigma' (Var x))) ->\n  Interp (apply_subst sigma t) (apply_subst sigma' t).\nProof.\nintros t; pattern t; apply term_rec3; clear t.\nintros v _ sigma sigma' Isigma; apply Isigma; left; apply eq_refl.\nintros f l IH fl_in_H sigma sigma' Isigma.\n\nsimpl; constructor 2 with (map (fun t => (apply_subst sigma t, apply_subst sigma' t)) l).\napply fl_in_H; simpl.\nrewrite eq_symb_bool_refl; apply eq_refl.\nrewrite map_map; simpl; apply eq_refl.\nrewrite map_map; simpl; apply eq_refl.\nintros s s' K; rewrite in_map_iff in K; destruct K as [t [K t_in_l]]; injection K; clear K; intros; subst.\napply IH. \nassumption.\nintros g g_in_t; apply fl_in_H; apply symb_in_direct_subterm with t; trivial.\nintros x x_in_t; apply Isigma.\ndestruct (In_split _ _ t_in_l) as [l1 [l2 K']].\napply var_in_subterm with t (length l1 :: nil); trivial.\nsubst l; simpl; rewrite nth_error_at_pos; apply eq_refl.\nQed.\n\nLemma rwr_interp_subst : \n  forall sigma, \n  forall t, Interp_dom (apply_subst sigma t) ->\n  forall tsigma' sigma', \n  Interp (apply_subst sigma t) tsigma' ->\n  (forall x, In x (var_list t) -> Interp (apply_subst sigma (Var x)) (apply_subst sigma' (Var x))) ->\n  (refl_trans_clos (one_step (Pi pi V0 V1)) (apply_subst sigma' t) tsigma' /\\\n  match t with\n  | Var _ => True\n  | Term f l => ~G f ->\n     match tsigma' with \n     | Var _ => False \n     | Term g k => f = g /\\ refl_trans_clos (one_step_list (one_step (Pi pi V0 V1))) (map (apply_subst sigma') l) k\n     end\n   end).\nProof.\nintros sigma t; pattern t; apply term_rec3; clear t.\n(* 1/2 variable case *)\nintros v Acc_t tsigma' sigma' I1 I2.\nassert (Acc_t' :=  interp_well_defined _ Acc_t).\nrewrite <- (interp_unicity _  Acc_t' _ _ I1 (I2 v (or_introl _ (eq_refl _)))); split; [left | exact I].\n(* 1/1 compound case *)\nintros f l IHl Acc_t tsigma' sigma' I1 I2.\nassert (IHl' : forall t : term,\n      In t l ->\n      forall (tsigma' : term) (sigma' : substitution),\n      Interp (apply_subst sigma t) tsigma' ->\n      (forall x : variable, In x (var_list t) ->\n       Interp (apply_subst sigma (Var x)) (apply_subst sigma' (Var x))) ->\n      refl_trans_clos (one_step (Pi pi V0 V1)) (apply_subst sigma' t) tsigma').\nintros s s_in_l ssigma'' sigma'' Issigma Isigma''.\nassert (Acc_ssigma : Interp_dom (apply_subst sigma s)). \ndestruct (In_split _ _ s_in_l) as [l1 [l2 H3]].\napply interp_dom_subterm with (apply_subst sigma (Term f l)) (length l1 :: nil); trivial.\nsubst l; simpl; rewrite map_app.\nrewrite <- (map_length (apply_subst sigma) l1); simpl.\nrewrite nth_error_at_pos; apply eq_refl.\napply (proj1 (IHl s s_in_l Acc_ssigma ssigma'' sigma'' Issigma Isigma'')).\ninversion I1 as [ | f1 l1 l1' ll1 Cf1 Hl1 Hl1' Hll1 | f1 l1 l1' ll1 k1 kk1 Df1 Hl1 Hl1' Hll1 Hk1 Hk1' Hkk1]; clear I1; subst.\nassert (H0 : refl_trans_clos (one_step_list (one_step (Pi pi V0 V1)))\n   (map (apply_subst sigma') l) (map (fun st : term * term => snd st) ll1)).\nclear IHl Acc_t; revert ll1 Hl1 Hll1 IHl'.\ninduction l as [ | a l]; intros ll1 Hl1 Hll1 IH.\ndestruct ll1; [left | discriminate Hl1].\ndestruct ll1 as [ | [a' a1] ll1]; [discriminate Hl1 | injection Hl1; clear Hl1; intros; subst].\nsimpl; rewrite refl_trans_clos_one_step_list_head_tail; split.\napply IH; trivial.\nleft; apply eq_refl.\napply Hll1; left; apply eq_refl.\nintros; apply I2; simpl; apply in_or_app; left; assumption.\napply IHl; trivial.\nintros; apply I2; simpl; apply in_or_app; right; assumption.\nintros; apply Hll1; right; trivial.\napply (tail_prop _ IH).\ninversion H0 as [k | k1 k2 K].\nsplit.\nleft.\nintros _; split.\napply eq_refl.\nleft.\nsplit.\nright; apply general_context; assumption.\nintros _; split.\napply eq_refl.\nright; assumption.\nsplit; [idtac | intro f_not_in_G; absurd (G f); assumption].\napply refl_trans_clos_is_trans with (Term f (map (fun st : term * term => snd st) ll1)).\nassert (refl_trans_clos (one_step_list (one_step (Pi pi V0 V1))) \n                      (map (apply_subst sigma') l)\n                      (map (fun st : term * term => snd st) ll1)).\nclear IHl Acc_t; revert ll1 Hl1 Hll1 IHl'; clear -I2.\ninduction l as [ | a l]; intros ll1 Hl1 Hll1 IH.\ndestruct ll1; [left | discriminate Hl1].\ndestruct ll1 as [ | [a' a1] ll1]; [discriminate Hl1 | injection Hl1; clear Hl1; intros; subst].\nsimpl; rewrite refl_trans_clos_one_step_list_head_tail; split.\napply IH; trivial.\nleft; apply eq_refl.\napply Hll1; left; apply eq_refl.\nintros; apply I2; simpl; apply in_or_app; left; assumption.\napply IHl; trivial.\nintros; apply I2; simpl; apply in_or_app; right; assumption.\nintros; apply Hll1; right; trivial.\napply (tail_prop _ IH).\nsimpl; destruct H as [k | k1 k2 H0].\nleft.\nright; apply general_context; assumption.\nright; apply project_comb; left; apply eq_refl.\nQed.\n\nLemma interp_subst :\n  forall l sigma, Interp_dom (apply_subst sigma l) -> \n   {sigma' |  forall x, In x (var_list l) -> Interp (apply_subst sigma (Var x)) (apply_subst sigma' (Var x)) }.\nProof.\nintros l sigma Acc_ls.\nassert (Acc_sigma : forall x, In x (var_list l) -> Interp_dom (apply_subst sigma (Var x))).\nintros x x_in_l; assert (x_mem_l : mem (@eq _) x (var_list l)).\napply in_impl_mem; trivial.\ndestruct (var_in_subterm2 x l x_mem_l) as [p Sub].\napply interp_dom_subterm with (apply_subst sigma l) p; trivial.\ngeneralize (subterm_at_pos_apply_subst_apply_subst_subterm_at_pos l p sigma).\nrewrite Sub; exact (fun p => p).\nset (varl := var_list l) in *; clearbody varl.\ndestruct (remove_garbage_subst sigma) as [tau [H1 [H2 H3]]].\nassert (H4 : { tau' : list (variable * (term * term)) | \n                tau = map (fun xtt' => match xtt' with (x,(t,t')) => (x,t) end) tau' /\\\n                (forall x t t', In x varl -> In (x,(t,t')) tau' -> Interp t t') }).\nassert (Acc_tau : forall x : variable, In x varl -> Interp_dom (apply_subst tau (Var x))).\nintros; simpl; rewrite <- H1; apply Acc_sigma; assumption.\nrevert H2 H3 Acc_tau; clear -R_reg Rlist_ok P Plist Plist_ok Gdef'; induction tau as [ | [v vval] tau]; intros H2 H3 Acc_tau.\nexists nil; split; [apply eq_refl | intros; contradiction].\ndestruct IHtau as [tau' [K1 K2]].\nintros x xval xval_in_tau; generalize (H2 _ _ (or_intror _ xval_in_tau)); simpl.\ngeneralize (eq_var_bool_ok x v); case (eq_var_bool x v); [intro x_eq_v | intros _; trivial].\napply False_rect.\ndestruct (In_split _ _ xval_in_tau) as [tau' [tau'' H4]].\napply (H3 v x vval xval nil tau' tau''); subst; trivial.\nintros x y xval yval tau1 tau2 tau3 H4; apply (H3 x y xval yval ((v,vval) :: tau1) tau2 tau3); subst; trivial.\nintros x x_in_l; generalize (Acc_tau x x_in_l); simpl.\nassert (Acc_x : Interp_dom (Var x)).\nintros [ | i p] f l Sub; discriminate.\ngeneralize (eq_var_bool_ok x v); case (eq_var_bool x v); [intro x_eq_v | intros _; trivial].\nintros _; subst x; generalize (find_mem _ _ eq_var_bool_ok v tau).\ncase (find eq_var_bool v tau).\nintros t K; destruct (K _ (eq_refl _)) as [v' [tau1 [tau2 [K' K'']]]].\napply False_rect.\napply (H3 v v' vval t nil tau1 tau2); subst; trivial.\nintros; assumption.\ngeneralize (mem_bool_ok _ _ eq_var_bool_ok v varl); case (mem_bool eq_var_bool v varl).\nintro v_mem_varl; assert (v_in_varl : In v varl).\napply mem_impl_in with (@eq _); trivial.\nassert (Acc_vval :  Interp_dom vval).\ngeneralize (Acc_tau _ v_in_varl); simpl; rewrite eq_var_bool_refl; exact (fun p => p).\ndestruct (interp_defined _ (interp_well_defined _ Acc_vval)) as [vval' K].\nexists ((v,(vval,vval')) :: tau'); split.\nsimpl; rewrite K1; apply eq_refl.\nintros x t t' x_in_varl [x_eq_v | xtt'_in_tau']; [injection x_eq_v; intros; subst; assumption | apply (K2 x); assumption].\nintro v_not_in_varl; exists ((v,(vval,vval)) :: tau'); split.\nsimpl; rewrite K1; apply eq_refl.\nintros x t t' x_in_varl [x_eq_v | xtt'_in_tau']; \n[ injection x_eq_v; intros; subst; apply False_rect; apply v_not_in_varl; apply in_impl_mem; trivial\n| apply (K2 x); assumption].\ndestruct H4 as [tau' [H4 H5]].\nexists (map (fun xtt' => match xtt' with (x,(t,t')) => (x,t') end) tau').\nintros x x_in_varl; simpl; rewrite (H1 x).\nrewrite H4.\ngeneralize (find_map eq_var_bool (fun y : (term * term) => fst y) x tau')\n                 (find_map eq_var_bool (fun y : (term * term) => snd y) x tau')\n                 (find_mem _ _  eq_var_bool_ok x tau').\nrewrite (map_eq (fun xval0 : variable * (term * term) => (fst xval0, fst (snd xval0)))\n                               (fun xtt' : variable * (term * term) => let (x0, y) := xtt' in let (t, _) := y in (x0, t)) \n                               tau'\n                               (fun xtt' _ => match xtt' with (x,(t,_)) => eq_refl (x,t) end)).\nrewrite (map_eq (fun xval0 : variable * (term * term) => (fst xval0, snd (snd xval0)))\n                               (fun xtt' : variable * (term * term) => let (x0, y) := xtt' in let (_, t'0) := y in (x0, t'0)) \n                               tau'\n                               (fun xtt' _ => match xtt' with (x,(_,t')) => eq_refl (x,t') end)).\ncase (find eq_var_bool x tau').\nintros [xval xval']; simpl.\nintros K1 K2 K3; rewrite K1, K2.\ndestruct (K3 _ (eq_refl _)) as [x' [tau1 [tau2 [K4 K5]]]].\nsubst x'; apply (H5 x); trivial.\nsubst tau'; apply in_or_app; right; left; apply eq_refl.\nintros K1 K2 _; rewrite K1, K2; apply Vcase.\nQed.\n\nLemma Hclosed : forall f g, ~G f -> symb_sup R f g -> ~G g.\nProof.\nintros f g Hf H Gg; apply Hf.\nrewrite Gdef' in Gg; rewrite Gdef'.\ninversion Gg as [g' l t [K1 K2]]; clear Gg; subst g'.\ndestruct H as [v [u [[J1 J2] [J3 J4]]]].\ndestruct u as [x | f' k].\ncontradiction.\nsubst f'.\nconstructor 1 with k v; split.\nassumption.\nintros [x [y [H1 [H2 [f' [H3 H4]]]]]]; apply K2.\nexists x; exists y; split; [ | split].\nassumption.\nassumption.\nexists f'; split.\nassumption.\napply refl_trans_clos_is_trans with f.\nassumption.\nright; left.\nconstructor 1 with v.\nexists (Term f k); split; split.\nassumption.\napply eq_refl.\nassumption.\nassumption.\nQed.\n\nLemma rwr_at_top_H :\n  forall l r, R r l -> (match l with Var _ => False | Term g _ => ~G g end) ->\n  forall sigma,  Interp_dom (apply_subst sigma r) -> Interp_dom (apply_subst sigma l) ->\n  forall s' t', Interp (apply_subst sigma l) s' -> Interp (apply_subst sigma r) t' -> \n  rwr (union _ (fun r' l' => In (r',l') ((r,l) :: nil))  (Pi pi V0 V1)) t' s'.\nProof.\nintros l r K K' sigma Acc_rs Acc_ls s' t' Il Ir.\ndestruct (interp_subst l sigma Acc_ls) as [sigma' Isigma].\nassert (K'' : t' = apply_subst sigma' r).\napply interp_unicity with (apply_subst sigma r); trivial.\napply interp_well_defined; assumption.\napply interp_in_H.\ndestruct l as [ | f k].\ncontradiction.\nintros g g_in_r.\ndestruct (Gdec _ _ Rlist_ok _ _ Plist_ok g) as [not_Gg | Gg].\nrewrite Gdef'; assumption.\napply Hclosed with f; trivial.\nconstructor 1 with r; exists (Term f k); split.\nconstructor 1; trivial.\nsplit; [ | apply Gdef].\nassumption.\nrewrite Gdef'; assumption.\nintros x x_in_r; apply Isigma; apply R_reg with r; trivial.\nsubst t'; assert (K'' := proj1 (rwr_interp_subst _ _ Acc_ls _ sigma' Il Isigma)).\ninversion K''; clear K''; subst.\nleft; left; constructor; do 2 left; apply eq_refl.\napply trans_clos_is_trans with (apply_subst sigma' l).\nleft; left; constructor; do 2 left; apply eq_refl.\napply trans_incl with (one_step (Pi pi V0 V1)); trivial.\nrefine (one_step_incl _ _ _); intros; right; assumption.\nQed.\n\nLemma rwr_at_top_not_H :\n  forall l r, R r l -> (match l with Var _ => False | Term g _ => G g end) ->\n  forall sigma, Interp_dom (apply_subst sigma l) -> Interp_dom (apply_subst sigma r) ->\n  forall s' t', Interp (apply_subst sigma l) s' -> Interp (apply_subst sigma r) t' -> \n  rwr (Pi pi V0 V1) t' s'.\nProof.\nintros l r K K' sigma Acc_ls Acc_rs s' t' Il Ir.\ndestruct l as [ | f l].\ncontradiction.\nsimpl in Il; inversion Il; clear Il; subst.\nabsurd (G f); assumption.\napply project_comb; right.\nrewrite in_map_iff; exists (apply_subst sigma r, t'); split; trivial.\nassert (rs_in_kk : In (apply_subst sigma r) (map (fun st : term * term => fst st) kk)).\nrewrite <- H5; rewrite FB; left; apply (instance R r (Term f l) sigma); assumption.\nrewrite in_map_iff in rs_in_kk.\ndestruct rs_in_kk as [[rs t''] [K1 K2]]; simpl in K1; subst.\nassert (Acc_rs' : Acc interp_call (apply_subst sigma r)).\napply interp_well_defined; trivial.\nrewrite (interp_unicity (apply_subst sigma r) Acc_rs' t' t''); trivial.\napply H8; assumption.\nQed.\n\nLemma rwr_not_H :\n  forall l r, R r l -> \n  forall s t, Interp_dom s -> Interp_dom t ->\n  (match s with Var _ => False | Term g _ => G g end) ->\n  one_step (fun r' l' => In (r',l') ((r,l) :: nil)) t s ->\n  forall s' t', Interp s s' -> Interp t t' -> \n  rwr (Pi pi V0 V1) t' s'.\nProof.\nintros l r K s; pattern s; apply term_rec3; clear s.\nintros; contradiction.\nintros f k IH t Acc_s Acc_t K' K'' s' t' Is It.\ninversion K''; clear K''; intros; subst.\n(* 1/2 rewriting at top *)\ninversion H; clear H; subst.\ndestruct H2 as [H2 | H2]; [injection H2; clear H2; intros; subst | contradiction].\napply rwr_at_top_not_H with t2 t1 sigma; trivial.\ndestruct t2 as [x2 | f2 l2]; simpl in K'.\napply (R_var _ _ K).\ninjection H0; clear H0; intros; subst; assumption.\nrewrite H0; assumption.\nrewrite H0; assumption.\n(* 1/1 rewriting in context *)\ninversion Is; clear Is.\n(* 1/2 f in H *)\nsubst; absurd (G f); assumption.\n(* 1/1 f not in H *)\nsubst f0 l0 s'.\nassert (fl1_in_kk : In (Term f l1) (map (fun st : term * term => fst st) kk)).\nrewrite <- H6, FB.\napply one_step_incl with (fun r' l' : term => In (r', l') ((r, l) :: nil)).\nintros t1 t2 [t1t2_eq_rl | t1t2_in_nil]; [injection t1t2_eq_rl; intros; subst; assumption | contradiction].\napply in_context; assumption.\napply project_comb; right; subst k'; rewrite in_map_iff in fl1_in_kk.\ndestruct fl1_in_kk as [[fl1 t''] [fl1_eq_fl1 fl1_in_kk]].\nsimpl in fl1_eq_fl1; subst fl1.\nrewrite in_map_iff; exists (Term f l1, t''); split; trivial.\nsimpl; apply (interp_unicity (Term f l1)); trivial.\napply interp_well_defined; assumption.\napply H9; trivial.\nQed.\n\nLemma rwr_rule_not_H :\n  forall l r, R r l -> (match l with Var _ => False | Term g _ => G g end) ->\n  forall s t, Interp_dom s -> Interp_dom t ->\n  one_step (fun r' l' => In (r',l') ((r,l) :: nil)) t s ->\n  forall s' t', Interp s s' -> Interp t t' -> \n  rwr (Pi pi V0 V1) t' s'.\nProof.\nintros l r K K' s; pattern s; apply term_rec3; clear s.\nintros v t _ _ K''; inversion K''; clear K''; subst.\ninversion H; inversion H; subst.\ndestruct H5 as [H5 | H5]; [injection H5; clear H5; intros; subst | contradiction].\ndestruct t3 as [x3 | ]; [contradiction | discriminate].\nintros f k IH t Acc_s Acc_t K'' s' t' Is It.\ninversion K''; clear K''; intros; subst.\n(* 1/2 rewriting at top *)\ninversion H; clear H; subst.\ndestruct H2 as [H2 | H2]; [injection H2; clear H2; intros; subst | contradiction].\napply rwr_at_top_not_H with t2 t1 sigma; trivial.\nrewrite H0; assumption.\nrewrite H0; assumption.\n(* 1/1 rewriting in context *)\ninversion Is; clear Is.\n(* 1/2 f in H *)\ninversion It; clear It.\nsubst; apply general_context.\ndestruct (one_step_in_list H1) as [u [u' [l1 [l2 [K1 [K2 K3]]]]]].\ndestruct (split_map_set _ _ _ _ K2) as [ll1 [[ | [u1 u2] ll2] [K4 [K5 K6]]]]; clear K2.\ndiscriminate.\ndestruct (split_map_set _ _ _ _ K3) as [ll3 [[ | [u3 u4] ll4] [K7 [K8 K9]]]]; clear K3.\ndiscriminate.\nsimpl in K6; injection K6; clear K6; intros K10 K11; subst.\nsimpl in K9; injection K9; clear K9; intros K10 K11; subst.\ndo 2 rewrite map_app; simpl.\nassert (ll1_eq_ll3 : ll1 = ll3).\nassert (Aux : forall t t' t'', In (t,t') ll1 -> In (t,t'') ll3 -> t' = t'').\nintros t t' t'' tt'_in_ll1 tt''_in_ll3; apply (interp_unicity t).\napply interp_well_defined.\ndestruct (In_split _ _ tt'_in_ll1) as [lll1 [lll2 H15]].\napply interp_dom_subterm with\n            (Term f\n               (map (fun st : term * term => fst st) (ll1 ++ (u, u2) :: ll2)))\n            (length lll1 :: nil); trivial.\nsubst ll1; simpl; rewrite <- ass_app; rewrite map_app.\nrewrite <- (length_map (fun st : term * term => fst st) lll1).\nsimpl; rewrite nth_error_at_pos; apply eq_refl.\napply H6; apply in_or_app; left; trivial.\napply H13; apply in_or_app; left; trivial.\nrevert K8 Aux; clear; revert ll3; induction ll1 as [ | [a1 a2] ll1]; intros [ | [b1 b2] ll3] K8 Aux.\napply eq_refl.\ndiscriminate.\ndiscriminate.\nsimpl in K8; injection K8; clear K8; intros; subst.\nrewrite (Aux a1 a2 b2 (or_introl _ (eq_refl _)) (or_introl _ (eq_refl _))); rewrite (IHll1 ll3); trivial.\nintros t t' t'' H1 H2; apply (Aux t); right; assumption.\nassert (ll2_eq_ll4 : ll2 = ll4).\nassert (Aux : forall t t' t'', In (t,t') ll2 -> In (t,t'') ll4 -> t' = t'').\nintros t t' t'' tt'_in_ll2 tt''_in_ll4; apply (interp_unicity t).\napply interp_well_defined.\ndestruct (In_split _ _ tt'_in_ll2) as [lll1 [lll2 H15]].\napply interp_dom_subterm with\n            (Term f\n               (map (fun st : term * term => fst st) (ll1 ++ (u, u2) :: ll2)))\n            (length (ll1 ++ (u,u2) :: lll1) :: nil); trivial.\nsubst ll2; simpl; rewrite app_comm_cons; rewrite ass_app; rewrite map_app.\nrewrite <- (length_map (fun st : term * term => fst st) (ll1 ++ (u,u2) :: lll1)).\nsimpl; rewrite nth_error_at_pos; apply eq_refl.\napply H6; apply in_or_app; do 2 right; trivial.\napply H13; apply in_or_app; do 2 right; trivial.\nrevert K10 Aux; clear; revert ll4; induction ll2 as [ | [a1 a2] ll2]; intros [ | [b1 b2] ll4] K10 Aux.\napply eq_refl.\ndiscriminate.\ndiscriminate.\nsimpl in K10; injection K10; clear K10; intros; subst.\nrewrite (Aux a1 a2 b2 (or_introl _ (eq_refl _)) (or_introl _ (eq_refl _))); rewrite (IHll2 ll4); trivial.\nintros t t' t'' H1 H2; apply (Aux t); right; assumption.\nsubst ll3 ll4.\nunfold rwr_list; rewrite rwr_list_expand_strong; \nexists u2; exists u4;\nexists (map (fun st : term * term => snd st) ll1);\nexists (map (fun st : term * term => snd st) ll2);\nexists (map (fun st : term * term => snd st) ll2).\nsplit.\napply eq_refl.\nsplit.\napply eq_refl.\nsplit.\napply IH with u u'.\nrewrite map_app; apply in_or_app; right; left; apply eq_refl.\napply interp_dom_subterm with\n            (Term f\n               (map (fun st : term * term => fst st) (ll1 ++ (u, u2) :: ll2)))\n            (length ll1 :: nil); trivial.\nrewrite map_app.\nrewrite <- (length_map (fun st : term * term => fst st) ll1).\nsimpl; rewrite nth_error_at_pos; apply eq_refl.\napply interp_dom_subterm with\n            (Term f\n               (map (fun st : term * term => fst st) (ll1 ++ (u', u4) :: ll2)))\n            (length ll1 :: nil); trivial.\nrewrite map_app.\nrewrite <- (length_map (fun st : term * term => fst st) ll1).\nsimpl; rewrite nth_error_at_pos; apply eq_refl.\nassumption.\napply H6; apply in_or_app; right; left; apply eq_refl.\napply H13; apply in_or_app; right; left; apply eq_refl.\nleft.\n(* 1/2 *)\nabsurd (G f); assumption.\n(* 1/1 f not in H *)\nsubst f0 l0 s'.\nassert (fl1_in_kk : In (Term f l1) (map (fun st : term * term => fst st) kk)).\nrewrite <- H6, FB.\napply one_step_incl with (fun r' l' : term => In (r', l') ((r, l) :: nil)).\nintros t1 t2 [t1t2_eq_rl | t1t2_in_nil]; [injection t1t2_eq_rl; intros; subst; assumption | contradiction].\napply in_context; assumption.\napply project_comb; right; subst k'; rewrite in_map_iff in fl1_in_kk.\ndestruct fl1_in_kk as [[fl1 t''] [fl1_eq_fl1 fl1_in_kk]].\nsimpl in fl1_eq_fl1; subst fl1.\nrewrite in_map_iff; exists (Term f l1, t''); split; trivial.\nsimpl; apply (interp_unicity (Term f l1)); trivial.\napply interp_well_defined; trivial.\napply H9; trivial.\nQed.\n\nLemma rwr_rule_H :\n  forall l r, R r l -> (match l with Var _ => False | Term g _ => ~G g end) -> \n  forall s t, Interp_dom s -> Interp_dom t ->\n  one_step (fun r' l' => In (r',l') ((r,l) :: nil)) t s ->\n  forall s' t', Interp s s' -> Interp t t' -> \n  rwr (union _ (fun r' l' => In (r',l') ((r,l) :: nil)) (Pi pi V0 V1)) t' s'.\nProof.\nintros l r K K' s; pattern s; apply term_rec3; clear s.\nintros v t _ _ K''; inversion K''; clear K''; subst.\ninversion H; inversion H; subst.\ndestruct H5 as [H5 | H5]; [injection H5; clear H5; intros; subst | contradiction].\ndestruct t3 as [x3 | ]; [contradiction | discriminate].\nintros f k IH t Acc_s Acc_t K'' s' t' Is It.\ninversion K''; clear K''; intros; subst.\n(* 1/2 rewriting at top *)\ninversion H; clear H; subst.\ndestruct H2 as [H2 | H2]; [injection H2; clear H2; intros; subst | contradiction].\napply rwr_at_top_H with sigma; trivial.\nrewrite H0; assumption.\nrewrite H0; assumption.\n(* 1/1 rewriting in context *)\ninversion Is.\n(* 1/2 f in H *)\ninversion It; clear Is It.\nsubst; apply general_context.\ndestruct (one_step_in_list H1) as [u [u' [l1 [l2 [K1 [K2 K3]]]]]].\ndestruct (split_map_set _ _ _ _ K2) as [ll1 [[ | [u1 u2] ll2] [K4 [K5 K6]]]]; clear K2.\ndiscriminate.\ndestruct (split_map_set _ _ _ _ K3) as [ll3 [[ | [u3 u4] ll4] [K7 [K8 K9]]]]; clear K3.\ndiscriminate.\nsimpl in K6; injection K6; clear K6; intros K10 K11; subst.\nsimpl in K9; injection K9; clear K9; intros K10 K11; subst.\ndo 2 rewrite map_app; simpl.\nassert (ll1_eq_ll3 : ll1 = ll3).\nassert (Aux : forall t t' t'', In (t,t') ll1 -> In (t,t'') ll3 -> t' = t'').\nintros t t' t'' tt'_in_ll1 tt''_in_ll3; apply (interp_unicity t).\napply interp_well_defined.\ndestruct (In_split _ _ tt'_in_ll1) as [lll1 [lll2 H15]].\napply interp_dom_subterm with\n            (Term f\n               (map (fun st : term * term => fst st) (ll1 ++ (u, u2) :: ll2)))\n            (length lll1 :: nil); trivial.\nsubst ll1; simpl; rewrite <- ass_app; rewrite map_app.\nrewrite <- (length_map (fun st : term * term => fst st) lll1).\nsimpl; rewrite nth_error_at_pos; apply eq_refl.\napply H6; apply in_or_app; left; trivial.\napply H13; apply in_or_app; left; trivial.\nrevert K8 Aux; clear; revert ll3; induction ll1 as [ | [a1 a2] ll1]; intros [ | [b1 b2] ll3] K8 Aux.\napply eq_refl.\ndiscriminate.\ndiscriminate.\nsimpl in K8; injection K8; clear K8; intros; subst.\nrewrite (Aux a1 a2 b2 (or_introl _ (eq_refl _)) (or_introl _ (eq_refl _))); rewrite (IHll1 ll3); trivial.\nintros t t' t'' H1 H2; apply (Aux t); right; assumption.\nassert (ll2_eq_ll4 : ll2 = ll4).\nassert (Aux : forall t t' t'', In (t,t') ll2 -> In (t,t'') ll4 -> t' = t'').\nintros t t' t'' tt'_in_ll2 tt''_in_ll4; apply (interp_unicity t).\napply interp_well_defined.\ndestruct (In_split _ _ tt'_in_ll2) as [lll1 [lll2 H15]].\napply interp_dom_subterm with\n            (Term f\n               (map (fun st : term * term => fst st) (ll1 ++ (u, u2) :: ll2)))\n            (length (ll1 ++ (u,u2) :: lll1) :: nil); trivial.\nsubst ll2; simpl; rewrite app_comm_cons; rewrite ass_app; rewrite map_app.\nrewrite <- (length_map (fun st : term * term => fst st) (ll1 ++ (u,u2) :: lll1)).\nsimpl; rewrite nth_error_at_pos; apply eq_refl.\napply H6; apply in_or_app; do 2 right; trivial.\napply H13; apply in_or_app; do 2 right; trivial.\nrevert K10 Aux; clear; revert ll4; induction ll2 as [ | [a1 a2] ll2]; intros [ | [b1 b2] ll4] K10 Aux.\napply eq_refl.\ndiscriminate.\ndiscriminate.\nsimpl in K10; injection K10; clear K10; intros; subst.\nrewrite (Aux a1 a2 b2 (or_introl _ (eq_refl _)) (or_introl _ (eq_refl _))); rewrite (IHll2 ll4); trivial.\nintros t t' t'' H1 H2; apply (Aux t); right; assumption.\nsubst ll3 ll4.\nunfold rwr_list; rewrite rwr_list_expand_strong; \nexists u2; exists u4;\nexists (map (fun st : term * term => snd st) ll1);\nexists (map (fun st : term * term => snd st) ll2);\nexists (map (fun st : term * term => snd st) ll2).\nsplit.\napply eq_refl.\nsplit.\napply eq_refl.\nsplit.\napply IH with u u'.\nrewrite map_app; apply in_or_app; right; left; apply eq_refl.\napply interp_dom_subterm with\n            (Term f\n               (map (fun st : term * term => fst st) (ll1 ++ (u, u2) :: ll2)))\n            (length ll1 :: nil); trivial.\nsimpl; rewrite map_app.\nrewrite <- (length_map (fun st : term * term => fst st) ll1).\nsimpl; rewrite nth_error_at_pos; apply eq_refl.\napply interp_dom_subterm with\n            (Term f\n               (map (fun st : term * term => fst st) (ll1 ++ (u', u4) :: ll2)))\n            (length ll1 :: nil); trivial.\nsimpl; rewrite map_app.\nrewrite <- (length_map (fun st : term * term => fst st) ll1).\nsimpl; rewrite nth_error_at_pos; apply eq_refl.\nassumption.\napply H6; apply in_or_app; right; left; apply eq_refl.\napply H13; apply in_or_app; right; left; apply eq_refl.\nleft.\n(* 1/2 *)\nabsurd (G f); assumption.\n(* 1/1 f not in H *)\nsubst f0 l0 s'.\napply trans_incl with (one_step  (Pi pi V0 V1)).\ndo 2 intro; apply one_step_incl; intros; right; assumption.\napply (rwr_not_H _ _ K (Term f k) (Term f l1)); trivial.\napply in_context; assumption.\nQed.\n\nLemma rwr_rule_H_not_H :\n  forall s t, Interp_dom s -> Interp_dom t ->\n  one_step R t s ->\n  forall s' t', Interp s s' -> Interp t t' -> \n  rwr (union _ (UsableRules R P) (Pi pi V0 V1)) t' s'.\nProof.\nintros s t Acc_s Acc_t K s' t' Is It.\ndestruct (split_rules _ _ Rlist_ok _ _ Plist_ok R_var G Gdef') as [U1 U2].\nassert (Erule := one_step_one_rule R _ _ K).\ndestruct Erule as [r [l [K1 K2]]].\ndestruct l as [x | f l].\napply False_rect; apply (R_var _ _ K1).\ndestruct (Gdec _ _ Rlist_ok _ _ Plist_ok f) as [f_in_H | f_not_in_H].\napply trans_incl with\n  (one_step (union term (fun r' l' : term => In (r', l') ((r, Term f l) :: nil))\n      (Pi pi V0 V1))).\nintros x y; apply one_step_incl; clear x y.\nintros x y [[K3 | Abs] | K3].\ninjection K3; clear K3; intros; subst x y; left.\nrewrite U1 in K1; destruct K1 as [K1 | K1].\nassumption.\ndestruct K1 as [_ K1]; apply False_rect; apply f_in_H;\nrewrite <- Gdef'; assumption.\ncontradiction.\nright; assumption.\nrewrite <- Gdef' in f_in_H.\napply (rwr_rule_H _ _ K1 f_in_H _ _ Acc_s Acc_t K2 _ _ Is It).\napply trans_incl with (one_step (Pi pi V0 V1)).\nintros x y; apply one_step_incl; clear x y.\nintros x y K3; right; assumption.\nrewrite <- Gdef' in f_not_in_H.\napply (rwr_rule_not_H _ _ K1 f_not_in_H _ _ Acc_s Acc_t K2 _ _ Is It).\nQed.\n\nLemma trans_rwr_rule_H_not_H :\n  forall s t, Acc (one_step R) s ->\n  trans_clos (one_step R) t s ->\n  forall s' t', Interp s s' -> Interp t t' -> \n  rwr (union _ (UsableRules R P) (Pi pi V0 V1)) t' s'.\nProof.\nintros s t Acc_s' K; induction K as [t1 t2 K | t1 t2 t3 K1 K2].\napply rwr_rule_H_not_H; trivial.\napply acc_one_step_interp_dom; assumption.\napply acc_one_step_interp_dom; apply Acc_inv with t2; assumption.\nintros t3' t1' I3 I1.\nassert (Acc_t2 : Interp_dom t2).\napply acc_one_step_interp_dom; apply Acc_incl with (trans_clos (one_step R)).\ndo 3 intro; left; assumption.\napply Acc_inv with t3; trivial.\napply acc_trans; assumption.\ndestruct (interp_defined _ (interp_well_defined _ Acc_t2)) as [t2' I2].\napply trans_clos_is_trans with t2'.\napply rwr_rule_H_not_H with t2 t1; trivial.\napply acc_one_step_interp_dom; apply Acc_incl with (trans_clos (one_step R)).\ndo 3 intro; left; assumption.\napply Acc_inv with t3.\napply acc_trans; assumption.\nright with t2; assumption.\napply IHK2; trivial.\nQed.\n\nLemma interp_dom_interp_dom_1 :\n  forall f l1 l2, ~G f -> acc_sub R (Term f l1) -> refl_trans_clos (one_step_list (one_step R)) l2 l1 -> Interp_dom (Term f l2).\nProof.\nintros f l1 l2 f_in_H Acc_l1 K1.\nintros [ | i q] g l Sub g_not_in_H.\ninjection Sub; clear Sub; intros; subst; apply False_rect; apply f_in_H; assumption.\nsimpl in Sub.\ngeneralize (nth_error_ok_in i l2); \ndestruct (nth_error l2 i) as [ai | ]; [idtac | discriminate].\nintro K; destruct (K _ (eq_refl _)) as [l2' [l2'' [L K']]]; clear K.\napply acc_subterms_3 with q ai; trivial.\napply rwr_sub_acc_sub_acc_sub with l1 l2; trivial.\n\nsubst l2; apply in_or_app; right; left; apply eq_refl.\nQed.\n\nLemma head_P_in_H :\n  forall mark,\n  (forall u v, P v u -> mrel mark (dp R) v u) ->\n  forall t1 t2 sigma f l, P t1 t2 -> apply_subst sigma t1 = Term f l -> ~G f.\nProof.\nintros mark P_in_dpR t1 t2 sigma f l K1 K2 K3.\nrewrite Gdef' in K3; inversion K3 as [f' k t [K4 K5]]; subst f'.\napply K5.\nconstructor 1 with t1; exists t2; split.\nassumption.\nsplit.\nassumption.\nexists f; split.\ndestruct t1 as [x | f' l'].\nassert (_D := P_in_dpR _ _ K1); inversion _D as [a b D J1 J2].\ninversion D; subst; discriminate.\nsimpl in K2; injection K2; intros; subst f'.\nsimpl; rewrite eq_symb_bool_refl; apply eq_refl.\nleft.\nQed.\n\nLemma interp_dom_interp_dom_2 :\n  forall mark, (forall v u, P u v -> mrel mark (dp R) u v) ->\n  forall s t, acc_sub R s -> acc_sub R t ->  rdp_step (axiom P) R t s -> Interp_dom s -> Interp_dom t.\nProof.\nintros mark P_in_dpR s t Acc_sub_s Acc_sub_t K Is.\ninversion K as [_f ls l H1 H2]; clear K; subst.\ninversion H as [_t _fl sigma K1 K2 K3]; clear H; subst.\nassert (_K := P_in_dpR _ _ K1).\ninversion _K as [t fk K]; clear _K; subst.\ndestruct fk as [x | f k].\ninversion K; subst; apply False_rect; apply (R_var _ _ H).\ninjection K3; clear K3; intros; subst.\ninversion K as [u v p f2 l2 H Sub Df2]; subst.\nassert (f2_in_H : ~G (mark f2)).\napply (head_P_in_H mark P_in_dpR _ _ nil (mark f2) l2 K1).\nrewrite empty_subst_is_id; apply eq_refl.\nintros [ | i q] g k' Sub' g_not_in_H.\nsimpl in Sub'; injection Sub'; clear Sub'; intros; subst; apply False_rect; apply f2_in_H; assumption.\nsimpl in Sub'.\ngeneralize (nth_error_ok_in i (map (apply_subst sigma) l2)); \ndestruct (nth_error (map (apply_subst sigma) l2) i) as [ai | ]; [idtac | discriminate].\nintro K'; destruct (K' _ (eq_refl _)) as [l2' [l2'' [L K'']]]; clear K'.\napply acc_subterms_3 with q ai; trivial.\napply Acc_sub_t; simpl; rewrite K''; apply in_or_app; right; left; apply eq_refl.\nQed.\n\nLemma pi_in_H : ~G pi.\nProof.\nrewrite Gdef'; intro Dpi; inversion Dpi as [f l t [H1 H2]]; subst f.\napply (proj2 (PPi t (Term pi l) H1 pi)).\nsimpl; rewrite eq_symb_bool_refl; apply eq_refl.\napply eq_refl.\nQed.\n\nLemma Q8_weak :\n  forall mark,\n  (forall f, ~defined R (mark f)) ->\n  (forall v u, P u v -> mrel mark (dp R) u v) -> \n  forall s, Interp_dom s ->\n  forall s', Interp s s' -> Acc (rdp_step (axiom P) (union _  (UsableRules R P) (Pi pi V0 V1))) s' -> \n              Acc (rest (acc_sub R) (rdp_step (axiom P) R)) s.\nProof.\nintros mark mark_ok P_in_dpR.\nassert (acc_rdp_var : \n         forall x, Acc (rest (acc_sub R) (rdp_step (axiom P) R)) (Var x)).\nintros x; apply Acc_intro; intros s [H _].\ninversion H as [f l1 l2 t3 H1 H2]; subst.\n\nintros s Acc_s s' Is Acc_s'; revert s Acc_s Is.\ninduction Acc_s' as [s' Acc_s'' IH].\nassert (Acc_s' : Acc (rdp_step (axiom P) (union _  (UsableRules R P) (Pi pi V0 V1))) s').\napply Acc_intro; exact Acc_s''.\nclear Acc_s''.\nintros s Acc_s Is.\ndestruct s as [x | f ls].\napply acc_rdp_var.\ndestruct (Gdec _ _ Rlist_ok _ _ Plist_ok f) as [f_in_H | f_not_in_H]; \n[ rewrite <- Gdef' in f_in_H\n| rewrite <- Gdef' in f_not_in_H].\napply Acc_intro; intros t [K [Acc_sub_t  Acc_sub_s]].\nassert (Acc_t := interp_dom_interp_dom_2 mark P_in_dpR _ _ Acc_sub_s Acc_sub_t K Acc_s).\ndestruct (interp_defined _ (interp_well_defined _ Acc_t)) as [t' It].\napply IH with t'; trivial.\ninversion K as [_f _ls l H1 H2 H3 H4 H5]; clear K; subst.\ninversion H3 as [_v _fl sigma H1 H4 H5']; clear H3; subst.\nassert (_K := P_in_dpR _ _ H1).\ninversion _K as [v fl K]; subst.\ninversion K as [fl' r p g lv H0 Sub Dg]; clear K; subst.\ninversion Is as [ | f' _ls ls' lls _ H8 H9 Ills | ]; \n[subst f' _ls s' | absurd (G f); assumption].\nassert (g_in_H := head_P_in_H mark P_in_dpR _ _ sigma _ _ H1 (eq_refl _)).\ninversion It as [ |  g' lt lt' llt _ H4 H5 Illt | ]; [ subst g' t' | absurd (G (mark g)); assumption].\n\nassert (Acc_fl := interp_dom_interp_dom_1 _ _ _ f_in_H Acc_sub_s H2).\nrewrite <- H5' in Acc_fl; destruct (interp_subst _ sigma Acc_fl) as [sigma' Isigma].\ndestruct (interp_defined _ (interp_well_defined _ Acc_fl)) as [fl' Ifl].\nrewrite H5' in Ifl; inversion Ifl as [ | f' _l l' ll _ H10 H11 Ill | ]; [subst f' _l fl' | absurd (G f); assumption].\napply rwr_subterm_rdp_rdp with l'.\nsubst; revert Ills Ill Acc_sub_s H2; clear -R_reg Rlist_ok P Plist Plist_ok Gdef' V0_diff_V1 R_var; revert ll.\ninduction lls as [ | [s s'] lls]; intros [ | [u u'] ll] Ills Ill Acc_sub_s K.\nleft.\ngeneralize (refl_trans_clos_one_step_list_length_eq K); intro; discriminate.\ngeneralize (refl_trans_clos_one_step_list_length_eq K); intro; discriminate.\nsimpl in K; rewrite refl_trans_clos_one_step_list_head_tail in K.\ndestruct K as [K1 K2].\nsimpl; rewrite refl_trans_clos_one_step_list_head_tail; split.\nassert (Acc_s : Acc (one_step R) s).\napply Acc_sub_s; left; apply eq_refl.\ninversion K1; subst.\nassert (Acc_s' : Acc interp_call s).\napply interp_well_defined; apply acc_one_step_interp_dom; assumption.\nrewrite (interp_unicity s Acc_s' s' u').\nleft.\napply Ills; left; apply eq_refl.\napply Ill; left; apply eq_refl.\nright; apply trans_rwr_rule_H_not_H with s u; trivial.\napply Ills; left; apply eq_refl.\napply Ill; left; apply eq_refl.\napply IHlls; trivial.\nintros; apply Ills; right; assumption.\nintros; apply Ill; right; assumption.\ndo 2 intro; apply Acc_sub_s; right; assumption.\nassert (Acc_sub : acc_sub R (Term f l)).\nunfold acc_sub; apply (rwr_sub_acc_sub_acc_sub R _ _ H2 Acc_sub_s).\n\nrewrite <- H5' in Ifl.\ngeneralize (rwr_interp_subst _ _ Acc_fl (Term f l') sigma' Ifl Isigma).\ndestruct fl as [x | _f _l].\napply False_rect; apply (R_var _ _ H0).\nsimpl in H5'; injection H5'; intros; subst f.\napply rwr_subterm_rdp_rdp with  (map (apply_subst sigma') _l).\ndestruct H7 as [_ H7].\ngeneralize (H7 f_in_H); clear H7; intros [_ H7].\napply refl_trans_incl with (one_step_list (one_step (Pi pi V0 V1))); trivial.\ndo 2 intro; apply one_step_list_incl.\ndo 2 intro; apply one_step_incl.\ndo 3 intro; right; assumption.\nassert (t'_eq_glvs' : Term (mark g) lt' = apply_subst sigma' (Term (mark g) lv)).\napply (interp_unicity _ (interp_well_defined _ Acc_t)); trivial.\napply interp_in_H.\nintros g' g'_glv.\nrewrite symb_in_term_unfold in g'_glv.\ngeneralize (eq_symb_bool_ok g' (mark g)); destruct (eq_symb_bool g' (mark g)).\nintro; subst g'; assumption.\nsimpl in g'_glv; intros _.\nrewrite Gdef'.\nintro Dg'; inversion Dg' as [g'' k t [K K']]; subst g''; apply K'.\nexists (mark_term mark (Term g lv));\nexists (mark_term mark (Term _f _l)); split; [ | split]; trivial.\nexists g'; split; [ | left].\nrewrite symb_in_term_unfold; simpl; rewrite g'_glv.\ndestruct (eq_symb_bool g' (mark g)); apply eq_refl.\nintros x x_in_lv; apply Isigma.\napply (R_reg _ _ H0 x).\napply var_in_subterm with (Term g lv) p; trivial.\nrewrite t'_eq_glvs'.\napply Rdp_step with (map (apply_subst sigma') _l).\nleft.\napply (instance P (Term (mark g) lv) (Term (mark _f) _l) sigma'); trivial.\n\n\napply Acc_intro; intros s [H _]; inversion H; clear H; subst.\ninversion H4 as [_t1 _t2 sigma]; clear H4; subst.\nassert (_K1 := P_in_dpR _ _ H).\ninversion _K1 as [t1 t2 K1]; subst.\ninversion K1; clear K1; subst.\ndestruct t2 as [x2 | g2 k2].\napply False_rect; apply (R_var _ _ H0).\nsimpl in H1; injection H1; clear H1; intros; subst.\nrewrite Gdef' in f_not_in_H.\napply False_rect; apply (mark_ok g2).\ninversion f_not_in_H as [g2' l t [H' _]].\nconstructor 1 with l t; assumption.\nQed.\n\nLemma Q8_strong :\n  forall mark,\n  (forall f, ~defined R (mark f)) ->\n  (forall v u, P u v -> mrel mark (dp R) u v) -> \n  well_founded (rdp_step (axiom P) (union _  (UsableRules R P) (Pi pi V0 V1))) ->\n  well_founded  (rest (acc_sub R) (rdp_step (axiom P) R)).\nProof.\nintros mark mark_ok P_in_dpR Wf t.\napply Acc_intro; intros s H; apply Acc_inv with t; trivial.\ndestruct H as [H [_ Ht]].\ninversion H as [f l1 l2 s' H1 H2 H3 H4]; clear H; subst.\ninversion H2 as [_t1 _t2 sigma _H2]; clear H2; subst.\nassert (_K2 := P_in_dpR _ _ _H2).\ninversion _K2 as [t1 t2 K2]; clear _K2; subst.\ninversion K2 as [u1 u2 p f2 k2 H Sub Df2]; subst.\ndestruct t2 as [x2 | g2].\napply False_rect; apply (R_var _ _ H).\nsimpl in H0; injection H0; clear H0; intros; subst.\nassert (Acc_t : Interp_dom (Term (mark g2) l1)).\nintros [ | i q] f k Sub' Gf.\nsimpl in Sub'; injection Sub'; clear Sub'; intros; subst.\nrewrite Gdef' in Gf.\ninversion Gf as [f l' t [K _]]; subst.\napply False_rect; apply (mark_ok g2); constructor 1 with l' t; assumption.\nsimpl in Sub'.\ngeneralize (nth_error_ok_in i l1).\ndestruct (nth_error l1 i) as [ai | ]; [ | discriminate].\nintro K; destruct (K _ (eq_refl _)) as [kk1 [kk2 [L K1]]]; clear K.\napply acc_subterms_3 with q ai; trivial.\napply Ht; subst l1; simpl; apply in_or_app; right; left; apply eq_refl.\ndestruct (interp_defined (Term (mark g2) l1)) as [t' It].\napply interp_well_defined; assumption.\napply Q8_weak with mark t'; trivial.\nQed.\n\nEnd Interp_definition.\n\nEnd MakeUsableDP.\n\n", "meta": {"author": "fblanqui", "repo": "color", "sha": "f2ef98f7d13c5d71dd2a614ed2e6721703a34532", "save_path": "github-repos/coq/fblanqui-color", "path": "github-repos/coq/fblanqui-color/color-f2ef98f7d13c5d71dd2a614ed2e6721703a34532/Coccinelle/term_orderings/usable_rules_dp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2842324400938139}}
{"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 * MagicWandExistsHelper.v\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.\n\nFixpoint localizeExists (s : absState) (n : nat) :=\n    match s with\n    | AbsStar s1 s2 => AbsStar (localizeExists s1 n) (localizeExists s2 n)\n    | AbsOrStar s1 s2 => AbsOrStar (localizeExists s1 n) (localizeExists s2 n)\n    | AbsMagicWand s1 s2 => AbsMagicWand (localizeExists s1 n) (localizeExists s2 n)\n    | AbsUpdateVar s vv vall => AbsUpdateVar (localizeExists s n) vv vall\n    | AbsUpdateWithLoc s vv vall => AbsUpdateWithLoc (localizeExists s n) vv vall\n    | AbsUpdateLoc s vv vall => AbsUpdateLoc (localizeExists s n) vv vall\n    | AbsUpdState s1 s2 s3 => AbsUpdState (localizeExists s1 n) (localizeExists s2 n) (localizeExists s3 n)\n    | AbsAll e s => AbsAll e (localizeExists s (S n))\n    | AbsEach e s => AbsEach e (localizeExists s (S n))\n\n    | AbsExistsT (AbsStar s1 s2) => if hasVnState s1 0 then\n                                        if hasVnState s2 0 then\n                                            AbsExistsT (AbsStar (localizeExists s1 (S n)) (localizeExists s2 (S n) ))\n                                        else\n                                            (AbsStar (AbsExistsT (localizeExists s1 (S n))) (removeStateVar 0 s2))\n                                    else\n                                        (AbsStar (removeStateVar 0 s1) (AbsExistsT (localizeExists s2 (S n))))\n    | AbsExists e (AbsStar s1 s2) => if hasVnState s1 0 then\n                                         if hasVnState s2 0 then\n                                             AbsExists e (AbsStar (localizeExists s1 (S n)) (localizeExists s2 (S n)))\n                                         else\n                                             (AbsStar (AbsExists e (localizeExists s1 (S n))) (removeStateVar 0 s2))\n                                     else\n                                         (AbsStar (removeStateVar 0 s1) (AbsExists e (localizeExists s2 (S n))))\n    | AbsExistsT s => AbsExistsT (localizeExists s (S n))\n    | AbsExists e s => AbsExists e (localizeExists s (S n))\n    | x => x\n    end.\n\nTheorem localizeExistsThm1 : forall bindings s state1 state2,\n    state1 = localizeExists state2 0 ->\n    (realizeState state1 bindings s -> realizeState state2 bindings s).\nProof.\n    admit.\nAdmitted.\n\nTheorem localizeExistsThm2 : forall bindings s state1 state2,\n    state1 =localizeExists state2 0 ->\n    (realizeState state2 bindings s -> realizeState state1 bindings s).\nProof.\n    admit.\nAdmitted.\n\nTheorem localizeExistsLeft : forall right res state1 state2,\n    state1 = localizeExists state2 0 ->\n    (mergeStates state1 right res -> mergeStates state2 right res).\nProof.\n    admit.\nAdmitted.\n\nFixpoint hasVarExpList (e : absExp) (l : list id) :=\n    match l with\n    | nil => false\n    | (a::b) => if hasVarExp e a then true else hasVarExpList e b\n    end.\n\nFixpoint findVal vlist v (e : absState) :=\n    match e with\n    | AbsStar l r => match findVal vlist v l with\n                     | Some x => Some x\n                     | None => findVal vlist v r\n                     end\n    | AbsUpdateVar s vv r => if hasVarExp v vv then None else findVal (vv::vlist) v s\n    | AbsUpdateWithLoc s vv r => if hasVarExp v vv then None else findVal (vv::vlist) v s\n    | ( l |-> vv) => if hasVarExpList vv vlist then None else if beq_absExp l v then Some vv\n                    else None\n    | _ => None\n    end.\n\nFixpoint clearUpdateWithLoc (s : absState) :=\n    match s with\n    | AbsUpdateWithLoc ss v e => match clearUpdateWithLoc ss with\n                                 | sss => match findVal nil e sss with\n                                          | None => AbsUpdateWithLoc sss v e\n                                          | Some x => AbsUpdateVar sss v x\n                                          end\n                                 end\n    | AbsUpdateVar ss v e => AbsUpdateVar (clearUpdateWithLoc ss) v e\n    | x => x\n    end.\n\nFixpoint clearMagicWandUpdateWithLoc (s : absState) :=\n    match s with\n    | AbsExistsT e => AbsExistsT (clearMagicWandUpdateWithLoc e)\n    | AbsExists e s => AbsExists e (clearMagicWandUpdateWithLoc s)\n    | AbsUpdateVar s v e => AbsUpdateVar (clearMagicWandUpdateWithLoc s) v e\n    | AbsUpdateWithLoc s v e => AbsUpdateWithLoc (clearMagicWandUpdateWithLoc s) v e\n    | AbsMagicWand l r => AbsMagicWand (clearUpdateWithLoc l) r\n    | x => x\n    end.\n\nTheorem clearMagicWandUpdateWithLocThm : forall s s' bindings ss,\n    s' = clearMagicWandUpdateWithLoc s ->\n    (realizeState s bindings ss -> realizeState s' bindings ss).\nProof.\n    admit.\nAdmitted.\n\nFixpoint pair_apply1 {t} {r} (f : r -> t -> t -> option r) (b :r) (l1 : list t) (l2 : list t) : option r :=\n    match l1,l2 with\n    | nil,nil => Some b\n    | f1::r1,f2::r2 => match f b f1 f2 with\n                         | Some bb => pair_apply1 f bb r1 r2\n                         | None => None\n                         end\n    | _, _ => None\n    end.\n\nDefinition funFix1 (x : option (list (nat * absExp))) :=\n    match x with\n    | Some b => Some b\n    | None => None\n    end.\n\nFixpoint matchBinding (v : nat) (e : absExp) (bindings : list (nat * absExp)) :=\n    match bindings with\n    | nil => Some ((v,e)::nil)\n    | ((vv,f)::r) => if beq_nat v vv then\n                         (if beq_absExp e f then Some bindings else None)\n                     else\n                         matchBinding v e r\n    end.\n\nFixpoint is_instance (limit : nat) (bindings: list (nat * absExp)) (e1 : absExp) (e2 : absExp) :=\n    match (e1,e2) with\n    | (AbsConstVal v1,AbsConstVal v2) => if beq_val v1 v2 then Some bindings else None\n    | (AbsVar v1,AbsVar v2) => if beq_id v1 v2 then (Some bindings) else None\n    | (AbsQVar v1,AbsQVar v2) => if ble_nat limit v1 then\n                                   (if beq_nat v1 (v2+limit) then Some bindings else None)\n                                 else matchBinding v1 (AbsQVar v2) bindings\n    | (AbsQVar v1,t) => if ble_nat limit v1 then\n                            None\n                        else matchBinding v1 t bindings\n    | (AbsFun i1 el1,AbsFun i2 el2) => if beq_id i1 i2 then\n                                         (fix go b l1 l2 :=\n                                           match l1,l2 with\n                                           | (f1::r1),(f2::r2) => match is_instance limit b f1 f2 with\n                                                                  | Some b => go b r1 r2\n                                                                  | None => None\n                                                                  end\n                                           | nil,nil => Some b\n                                           | _,_ => None\n                                           end) bindings el1 el2\n                                       else None\n    | (l,r) => None\n    end.\n\nFixpoint is_instance_state (limit : nat) (bindings: list (nat * absExp)) (p : absState) (e : absState) :=\n   match (p,e) with\n    | (AbsStar l1 l2,AbsStar r1 r2) => match is_instance_state limit bindings l1 r1 with\n                                             | Some b => is_instance_state limit bindings l2 r2\n                                             | None => None\n                                       end\n    | (AbsOrStar l1 l2,AbsOrStar r1 r2) => match is_instance_state limit bindings l1 r1 with\n                                             | Some b => is_instance_state limit bindings l2 r2\n                                             | None => None\n                                       end\n    | (AbsEmpty,AbsEmpty) => Some bindings\n    | (AbsLeaf i1 el1,AbsLeaf i2 el2) => if beq_id i1 i2 then \n                                       pair_apply1 (is_instance limit) bindings el1 el2\n                                   else None\n    | (AbsAccumulate i1 e1a e1b e1c,AbsAccumulate i2 e2a e2b e2c) =>\n          if beq_id i1 i2 then\n              match is_instance limit bindings e1a e2a with\n              | Some b2 => match is_instance limit b2 e1b e2b with\n                                      | Some b3 => is_instance limit b3 e1c e2c\n                                      | None => None\n                                      end\n              | None => None\n              end\n          else None\n    | (_,_) => None\n    end.\n\nFixpoint matchExistential (v : nat) (p : absState) (e: absState) :=\n    match p with\n    | AbsExistsT s => matchExistential (v+1) s e\n    | _ => is_instance_state v nil p e\n    end.\n\nFixpoint removeSubterm (p : absState) (e: absState) :=\n    match e with\n    | AbsStar l r => match removeSubterm p l with\n                     | Some ll => Some (AbsStar ll r)\n                     | None => match removeSubterm p r with\n                               | Some rr => Some (AbsStar l rr)\n                               | None => None\n                               end\n                     end\n    | AbsExistsT e => match removeSubterm (addStateVar 0 p) e with\n                      | Some l => Some (AbsExistsT l)\n                      | None => None\n                      end\n    | AbsExists ee e => match removeSubterm (addStateVar 0 p) e with\n                        | Some l => Some (AbsExists ee l)\n                        | None => None\n                        end\n    | AbsUpdateVar s v e => if hasVarState p v then None else\n                            match removeSubterm p s with\n                            | Some x => Some (AbsUpdateVar x v e)\n                            | None => None\n                            end\n    | AbsUpdateWithLoc s v e => if hasVarState p v then None else\n                                match removeSubterm p s with\n                                | Some x => Some (AbsUpdateWithLoc x v e)\n                                | None => None\n                                end\n    | _ => match matchExistential 0 p e with\n           | Some x => Some AbsEmpty\n           | None => None\n           end\n    end.\n\nFixpoint removeSubterms (p : absState) (e : absState) :=\n    match p with\n    | AbsStar l r => match removeSubterms l e with\n                     | Some x => removeSubterms r x\n                     | None => None\n                     end\n    | x => removeSubterm x e\n    end.\n\nFixpoint removeMagicWand (s : absState) :=\n    match s with\n    | AbsExistsT e => match removeMagicWand e with\n                      | Some x => Some (AbsExistsT x)\n                      | None => None\n                      end\n    | AbsExists e s => match removeMagicWand s with\n                       | Some x => Some (AbsExists e x)\n                       | None => None\n                       end\n    | AbsStar l r => match removeMagicWand l with\n                       | Some x => Some (AbsStar x r)\n                       | None => match removeMagicWand r with\n                                 | Some x => Some (AbsStar l x)\n                                 | None => None\n                                 end\n                       end\n    | AbsUpdateVar s v e => match removeMagicWand s with\n                            | Some x => Some (AbsUpdateVar x v e)\n                            | None => None\n                            end\n    | AbsUpdateWithLoc s v e => match removeMagicWand s with\n                                | Some x => Some (AbsUpdateWithLoc x v e)\n                                | None => None\n                                end\n    | AbsUpdateLoc s v e => match removeMagicWand s with\n                            | Some x => Some (AbsUpdateLoc x v e)\n                            | None => None\n                            end\n    | AbsMagicWand l r => removeSubterms r l\n    | x => None\n    end.\n\nTheorem removeMagicWandThm : forall s s' bindings ss,\n    Some s' = removeMagicWand s ->\n    (realizeState s bindings ss -> realizeState s' bindings ss).\nProof.\n    admit.\nAdmitted.\n\nTheorem removeMagicWandLeft : forall s s' r m,\n    Some s' = removeMagicWand s ->\n    (mergeStates s' r m -> mergeStates s r m).\nProof.\n    admit.\nAdmitted.\n\nTheorem removeMagicWandRight : forall s s' l m,\n    Some s' = removeMagicWand s ->\n    (mergeStates l s' m -> mergeStates l s m).\nProof.\n    admit.\nAdmitted.\n\nFixpoint clearSubterm (p : absState) (e: absState) :=\n    match e with\n    | AbsStar l r => match clearSubterm p l with\n                     | Some b => Some b\n                     | None => clearSubterm p r\n                     end\n    | AbsUpdateWithLoc s v e => if hasVarState p v then None else clearSubterm p s\n    | AbsUpdateVar s v e => if hasVarState p v then None else clearSubterm p s\n    | _ => matchExistential 0 p e\n    end.\n\nFixpoint clearAllSubterms (p : absState) (e: absState) :=\n    match p with\n    | AbsStar l r => match clearAllSubterms l e with\n                     | Some x => clearAllSubterms r e\n                     | None => None\n                     end\n    | _ => clearSubterm p e\n    end.\n\nInductive propagateInExists : nat -> absState -> absState -> Prop :=\n    | propagateInExistsId: forall x y n, x=y -> propagateInExists n x y\n    | propagateInExistsSimp: forall x y z n,\n          y = localizeExists x n ->\n          propagateInExists n y z ->\n          propagateInExists n x z.\n          \n\nFixpoint subn n (s : absState) :=\n    match n with\n    | 0 => s\n    | S n' => subn n' (removeStateVar 0 s)\n    end.\n\nTheorem magicWandStateExists : forall core st state sub q sub' sub'' n,\n    getRoot state = AbsMagicWand core sub ->\n    (exists s, realizeState st nil s) ->\n    getRoot st = core ->\n    getRootLevel st = n ->\n    sub' = subn n sub ->\n    propagateInExists 0 sub' sub'' ->\n    clearAllSubterms sub'' core=Some q ->\n    (exists s, realizeState state nil s).\nProof.\n    admit.\nAdmitted.\n\nTheorem simplifyExists : forall st st',\n    st' = simplifyState nil st ->\n    (exists s, realizeState st' nil s) ->\n    (exists s, realizeState st nil s).\nProof.\n    admit.\nAdmitted.\n\nTheorem existsWithLoc : forall st a b,\n    (exists s, realizeState st nil s) ->\n    (exists s, realizeState (AbsUpdateWithLoc st a b) nil s).\nProof.\n    admit.\nAdmitted.\n\nTheorem existsVar : forall st a b,\n    (exists s, realizeState st nil s) ->\n    (exists s, realizeState (AbsUpdateVar st a b) nil s).\nProof.\n    admit.\nAdmitted.\n\n\nTheorem localizeExistsRightp\n    : forall P1 P2 P,\n      mergeStates P1 (localizeExists P2 0) 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\nTheorem existsRealizeState :\n     forall st st' b s,\n     (realizeState st b s -> realizeState st' b s) ->\n     (exists s, realizeState st b s) ->\n     (exists s, realizeState st' b s).\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", "meta": {"author": "kendroe", "repo": "CoqPIE", "sha": "946009445e532dd4632a11a58a64f72a1dd28304", "save_path": "github-repos/coq/kendroe-CoqPIE", "path": "github-repos/coq/kendroe-CoqPIE/CoqPIE-946009445e532dd4632a11a58a64f72a1dd28304/PEDANTIC/MagicWandExistsHelper.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2842324400938138}}
{"text": "From Undecidability.FOL Require Import Syntax.Facts Semantics.Tarski.FullFacts Syntax.BinSig Semantics.FiniteTarski.Full.\nFrom Undecidability.FOL.TRAKHTENBROT Require bpcp. (* keep this Require to avoid universe problems *)\nFrom Undecidability.FOL.TRAKHTENBROT Require Import fo_sat fo_sig fo_terms fo_logic fol_ops.\nRequire Import Undecidability.Synthetic.DecidabilityFacts.\nRequire Import Vector Lia.\n\nSet Default Goal Selector \"!\".\n\n(* Reduction from the TRAKHTENBROT development to the FSAT problems in FOL *)\n\n(* syntax translation **)\n\nDefinition term' := @fo_term Empty_set (fun f => match f with end).\nDefinition form' := fol_form (Σrel 2).\n\n#[local]\nExisting Instance falsity_on.\nDefinition translate_term (t : term') : term :=\n  match t with\n  | in_var n => $n\n  | _ => $0\n  end.\n\nFixpoint translate (phi : form') : form :=\n  match phi with\n  | @fol_false _  => ⊥\n  | fol_atom tt v => atom tt (map translate_term v)\n  | fol_bin fol_conj phi psi => translate phi ∧ translate psi\n  | fol_bin fol_disj phi psi => translate phi ∨ translate psi\n  | fol_bin fol_imp phi psi => translate phi → translate psi\n  | fol_quant fol_ex phi => ∃ translate phi\n  | fol_quant fol_fa phi => ∀ translate phi\n  end.\n\n(* verification **)\n\nSection Forward.\n  \n  Variable D : Type.\n  Variable M : fo_model (Σrel 2) D.\n\n  Instance M1 :\n    interp D.\n  Proof using M.\n    split.\n    - intros [].\n    - intros [] v. exact (fom_rels M tt v).\n  Defined.\n\n  Lemma fwd_eval rho t :\n    fo_term_sem M rho t = eval rho (translate_term t).\n  Proof.\n    destruct t as [n|[]]; cbn. reflexivity.\n  Qed.\n\n  Lemma fwd_sat rho phi :\n    fol_sem M rho phi <-> rho ⊨ translate phi.\n  Proof.\n    induction phi in rho |- *; try destruct p; try destruct f; cbn; try now intuition; try firstorder.\n    - unfold sat. rewrite map_map. erewrite map_ext. \n      1:{ match goal with [ |- ?P <-> ?Q ] => enough (P = Q) as ->  end. 1: reflexivity. reflexivity. } \n      eapply fwd_eval.\n    - split; intros [d H]; exists d; apply IHphi.\n      + eapply fol_sem_ext; try apply H. now intros [].\n      + eapply sat_ext; try apply H. now intros [].\n    - split; intros H d; apply IHphi.\n      + eapply fol_sem_ext; try apply H. now intros [].\n      + eapply sat_ext; try apply H. now intros [].\n  Qed.\n\nEnd Forward.\n\nSection Backward.\n\n  Variable D : Type.\n  Variable M : interp D.\n\n  Definition M2 :\n    fo_model (Σrel 2) D.\n  Proof using M.\n    split.\n    - intros [].\n    - intros [] v. exact (i_atom (P:=tt) v).\n  Defined.\n\n  Lemma bwd_eval rho t :\n    fo_term_sem M2 rho t = eval rho (translate_term t).\n  Proof.\n    destruct t as [n|[]]; cbn. reflexivity.\n  Qed.\n\n  Lemma bwd_sat rho phi :\n    fol_sem M2 rho phi <-> rho ⊨ translate phi.\n  Proof.\n    induction phi in rho |- *; try destruct p; try destruct f; cbn; try now intuition; try firstorder.\n    - unfold sat. rewrite map_map. erewrite map_ext.\n      1:{ match goal with [ |- ?P <-> ?Q ] => enough (P = Q) as ->  end. 1: reflexivity. reflexivity. }\n      eapply bwd_eval.\n    - split; intros [d H]; exists d; apply IHphi.\n      + eapply fol_sem_ext; try apply H. now intros [].\n      + eapply sat_ext; try apply H. now intros [].\n    - split; intros H d; apply IHphi.\n      + eapply fol_sem_ext; try apply H. now intros [].\n      + eapply sat_ext; try apply H. now intros [].\n  Qed.\n\nEnd Backward.\n\n(* reduction theorems **)\n\nLemma reduction :\n  @fo_form_fin_dec_SAT (Σrel 2) ⪯ Full.FSAT.\nProof.\n  exists translate. intros phi. split.\n  - intros (D & M & [L HL] & HD & rho & H). exists D, (@M1 D M), rho. repeat split.\n    + exists L. apply HL.\n    + intros [ ]. apply decidable_iff. constructor. apply HD.\n    + now apply fwd_sat.\n  - intros (D & M & rho & [L HL] & HD & H). specialize (HD tt). apply decidable_iff in HD. destruct HD as [HD]. exists D, (@M2 D M), (exist _ L HL). eexists.\n    + intros []. apply HD.\n    + exists rho. now apply bwd_sat.\nQed.\n\nLemma reduction_disc :\n  @fo_form_fin_discr_dec_SAT (Σrel 2) ⪯ FSATd.\nProof.\n  exists translate. intros phi. split.\n  - intros (D & HE & M & [L HL] & HD & rho & H). exists D, (@M1 D M), rho. repeat split.\n    + exists L. apply HL.\n    + apply discrete_iff. constructor. apply HE.\n    + intros [ ]. apply decidable_iff. constructor. apply HD.\n    + now apply fwd_sat.\n  - intros (D & M & rho & [L HL] & [HE] % discrete_iff & HD & H).\n    specialize (HD tt).\n    apply decidable_iff in HD. destruct HD as [HD].\n    exists D, HE, (@M2 D M), (exist _ L HL). eexists.\n    + intros []. apply HD.\n    + exists rho. now apply bwd_sat.\nQed.\n\n\n  \n\n\n\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/TRAKHTENBROT_to_FSAT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2842324400938138}}
{"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\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 _).\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; lia.\n    + intros; hnf in *.\n      lia.\n    + intros; hnf in *.\n      lia.\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 tt 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 lia.\n  Intro z; apply sepcon_derives; [cancel|].\n  Exists z; apply derives_refl.\nQed.\n#[export] Hint 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.\n#[export] Hint 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 sum_ghost). }\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; lia).\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_lia).\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 lia.\n      apply Z2Nat.inj_le in Hi; lia. }\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 lia.\n    inv H9; inv H10.\n    assert (readable_share (Znth i shs)) by (apply Forall_Znth; auto; lia).\n    assert (Znth i gshs <> Share.bot).\n    { intro X; contradiction bot_unreadable.\n      rewrite <- X; apply Forall_Znth; auto; lia. }\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 lia.\n      rewrite iter_sepcon_app; simpl.\n      rewrite Z2Nat.id, Z.add_0_r by lia; 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; [lia|].\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 lia.\n          rewrite Ptrofs.add_unsigned, Ptrofs.unsigned_repr;\n            rewrite Ptrofs.unsigned_repr; unfold N in *; try rep_lia.\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_lia.\n          simpl; rewrite <- Z.add_assoc, Zred_factor4.\n          apply H29; lia. }\n    - apply Z2Nat.inj; try lia.\n      rewrite Nat2Z.id, Z2Nat.inj_sub by lia; simpl; lia. }\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. simpl; cancel. }\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_lia).\n    Opaque upto.\n    rewrite sublist_next with (i0 := i) by (auto; rewrite Zlength_upto, Z2Nat.id; lia); simpl.\n    rewrite Znth_upto by (simpl; unfold N in *; lia).\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 lia.\n    rewrite sublist_next with (i0 := i) in Hshs by lia.\n    rewrite sublist_next with (i0 := i) in Hgshs by lia.\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 lia.\n    Exists sh' gsh'; entailer!.\n    { split; eapply sepalg_list.list_join_app; eauto; econstructor; eauto; constructor. }\n    rewrite Z2Nat.inj_add by lia.\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 lia.\n    erewrite split2_data_at_Tarray_app by (rewrite Zlength_list_repeat; auto; lia).\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 lia.\n      apply field_compatible_array_smaller0 with (n' := N); auto; lia. }\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; lia. }\n    { eapply readable_share_list_join; eauto. }\n    { apply Forall_Znth; auto; lia. } }\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.\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.\ndo 7 semax_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\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_gen.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2842324400938138}}
{"text": "Require Import List.\nRequire Export Util Get Drop Var Val Isa.Ops IL.Exp\n        Envs Map CSet AutoIndTac MoreList OptionMap.\nRequire Export IL.Events SizeInduction SmallStepRelations StateType.\nRequire Import SetOperations While IL.\nRequire Import Sim SimTactics SimI Infra.Status Position ILN Sawtooth Program.Tactics.\n\n\nProgram Fixpoint whileToILI (s:list statement) (cont:nat) {measure (size s)} : stmt :=\n  match s with\n  | WhileLet x e::p =>\n    stmtLet x e (whileToILI p cont)\n  | WhileCond e s t::p =>\n    stmtFun ((nil, whileToILI p (S cont))::nil)\n            (stmtIf e (whileToILI s 0) (whileToILI t 0))\n  | WhileWhile e s::p =>\n    stmtFun ((nil, (stmtIf e\n                           (whileToILI s 0)\n                           (whileToILI p (S cont))))::nil)\n            (stmtApp (LabI 0) nil)\n  | WhileReturn e::p => stmtReturn e\n  | nil => stmtApp (LabI cont) nil\n  end.\n\nRequire Import Program.Equality Program.Wf.\n\nLemma whileToILI_nil cont\n  :  whileToILI nil cont = stmtApp (LabI cont) nil.\nProof.\n  unfold whileToILI at 1. unfold whileToILI_func.\n  WfExtensionality.unfold_sub whileToILI (whileToILI nil cont).\n  reflexivity.\nQed.\n\nLemma whileToILI_let x e p cont\n  :  whileToILI (WhileLet x e::p) cont = stmtLet x e (whileToILI p cont).\nProof.\n  unfold whileToILI at 1. unfold whileToILI_func.\n  WfExtensionality.unfold_sub whileToILI (whileToILI (WhileLet x e::p) cont).\n  reflexivity.\nQed.\n\nLemma whileToILI_return e p cont\n  :  whileToILI (WhileReturn e::p) cont = stmtReturn e.\nProof.\n  unfold whileToILI at 1. unfold whileToILI_func.\n  WfExtensionality.unfold_sub whileToILI (whileToILI (WhileReturn e::p) cont).\n  reflexivity.\nQed.\n\nLemma whileToILI_cond e s t p cont\n  :  whileToILI (WhileCond e s t :: p) cont\n     = stmtFun ((nil, whileToILI p (S cont))::nil)\n               (stmtIf e (whileToILI s 0) (whileToILI t 0)).\nProof.\n  unfold whileToILI at 1. unfold whileToILI_func.\n  WfExtensionality.unfold_sub whileToILI (whileToILI (WhileCond e s t :: p) cont).\n  reflexivity.\nQed.\n\nLemma whileToILI_while e s p cont\n  :  whileToILI (WhileWhile e s:: p) cont\n     =  stmtFun ((nil, (stmtIf e\n                           (whileToILI s 0)\n                           (whileToILI p (S cont))))::nil)\n                (stmtApp (LabI 0) nil).\nProof.\n  unfold whileToILI at 1. unfold whileToILI_func.\n  WfExtensionality.unfold_sub whileToILI (whileToILI (WhileWhile e s::p) cont).\n   reflexivity.\nQed.\n\nLtac single_step_while :=\n  match goal with\n  | [ H : val2bool _ = false |- @StateType.step _ statetype_While _ _ _ ] =>\n    econstructor 4; try eassumption; try reflexivity\n  | [ H : val2bool _ = true |- @StateType.step _ statetype_While _ _ _ ] =>\n    econstructor 3; try eassumption; try reflexivity\n  | [ H : val2bool _ = false |- @StateType.step _ statetype_While _ _ _ ] =>\n    econstructor 5; try eassumption; try reflexivity\n  | [ H : val2bool _ = true |- @StateType.step _ statetype_While _ _ _ ] =>\n    econstructor 6; try eassumption; try reflexivity\n  | [ |- @StateType.step _ statetype_While _ _ _ ] =>\n    econstructor; eauto\n  end.\n\nSmpl Add single_step_while : single_step.\n\nLemma whileToILI_correct_while r (L:list IL.I.block) E e s p (t:stmt)\n      (IH:forall q (L:IL.I.labenv) E r,\n          (exists v, op_eval E e = Some v /\\ val2bool v = true) ->\n          sawtooth L ->\n          (forall E, sim r Bisim\n                      (E, q) (L, E, stmtApp (LabI 0) nil))\n          -> sim r Bisim (E, s ++ q) (L, E, whileToILI s 0))\n      (SM:sawtooth L)\n      v (EV:op_eval E e = Some v)\n      (TR:val2bool v = true)\n      (CONT:forall E0,\n          sim r Bisim\n                   (E0, p) (IL.I.mkBlock 0 (nil, stmtIf e (whileToILI s 0) t) :: L, E0, t))\n  :  sim r Bisim (E, s ++ WhileWhile e s :: p)\n         (IL.I.mkBlock 0 (nil, stmtIf e (whileToILI s 0) t) :: L, E,\n          whileToILI s 0).\nProof.\n  revert_all. pcofix CIH. intros.\n  eapply (IH (WhileWhile e s :: p)); eauto.\n  - intros.\n    eapply (sawtooth_I_mkBlocks ((nil, stmtIf e (whileToILI s 0) t)::nil)); eauto.\n  - intros. dcr.\n    + case_eq (op_eval E0 e); intros.\n      * case_eq (val2bool v0); intros.\n        -- pone_step_right.\n           pone_step.\n           right. eapply CIH; eauto.\n        -- pone_step_right.\n           pone_step.\n           left. eapply paco3_mon. eapply CONT. eauto.\n      * pone_step_right.\n        pno_step.\nQed.\n\nLemma whileToILI_correct r (L:IL.I.labenv) E p q cont\n      (SM:sawtooth L)\n  :  (forall E, sim r Bisim\n               (E, q) (L, E, stmtApp (LabI cont) nil))\n    -> sim r Bisim (E, p ++ q) (L, E, whileToILI p cont).\nProof.\n  revert_except p.\n  sind p; destruct p; simpl; intros.\n  { rewrite whileToILI_nil. simpl. eauto. }\n  destruct s; simpl.\n  - rewrite whileToILI_cond.\n    pone_step_right.\n    case_eq (op_eval E e); intros.\n    + case_eq (val2bool v); intros.\n      * pone_step.\n        left. eapply IH; eauto; intros.\n        pone_step_right.\n        eapply IH; eauto. eapply sawtooth_I_mkBlocks; eauto.\n        intros.\n        eapply stmtApp_sim_tl; eauto.\n        eapply sawtooth_smaller; eauto.\n      * pone_step.\n        left. eapply IH; eauto. intros.\n        pone_step_right.\n        eapply IH; eauto. eapply sawtooth_I_mkBlocks; eauto.\n        intros.\n        eapply stmtApp_sim_tl; eauto.\n        eapply sawtooth_smaller; eauto.\n    + clear IH.\n      pno_step.\n  - rewrite whileToILI_while.\n    pone_step_right.\n    + case_eq (op_eval E e); intros.\n      * case_eq (val2bool v); intros.\n        -- pone_step_right.\n           pone_step. simpl.\n           left.\n           eapply whileToILI_correct_while; eauto.\n           ++ intros. eapply IH; eauto.\n             eapply (sawtooth_I_mkBlocks ((nil, stmtIf e (whileToILI s 0) _)::nil)); eauto.\n             intros.\n             eapply stmtApp_sim_tl; eauto.\n             eapply sawtooth_smaller; eauto.\n        -- intros.\n           pone_step_right.\n           pone_step.\n           left. eapply IH; eauto.\n           eapply (sawtooth_I_mkBlocks ((nil, stmtIf e (whileToILI s 0) _)::nil)); eauto.\n           intros. eapply stmtApp_sim_tl; eauto.\n           eapply sawtooth_smaller; eauto.\n      * pone_step_right. simpl.\n        pno_step.\n  - rewrite whileToILI_let.\n    destruct e.\n    + case_eq (op_eval E e); intros.\n      * pone_step.\n        left. eapply IH; eauto.\n      * pno_step.\n    + case_eq (omap (op_eval E) Y); intros.\n      * pextern_step.\n        -- econstructor; eauto. eexists. single_step.\n        -- left. eapply IH; eauto.\n        -- assert (l = vl) by congruence; subst.\n           left. eapply IH; eauto.\n      * pno_step.\n  - rewrite whileToILI_return.\n    pno_step.\n    Grab Existential Variables.\n    eapply default_val.\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/While/WhileToIL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819591324418, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.284232433510013}}
{"text": "Set Implicit Arguments.\nRequire Import Metalib.Metatheory.\nRequire Import Program.Equality.\nRequire Export Preservation.\n\nLemma canonical_form_abs : forall e U1 U2 S,\n  value e ->\n  typing empty e S ->\n  sub empty S (typ_arrow U1 U2) ->\n  exists V, exists e1, e = exp_abs V e1.\nProof with auto.\n  intros.\n  generalize dependent U1.\n  generalize dependent U2.\n  dependent induction H0;intros;try solve [inversion H|inversion H1|inversion H2]...\n  -\n    exists V.\n    exists e1...\n  -\n    apply IHtyping with (U1:=U1) (U2:=U2)...\n    apply sub_transitivity with (Q:=T)...\nQed.\n\nLemma canonical_form_tabs : forall e U1 U2 S,\n  value e ->\n  typing empty e S ->\n  sub empty S (typ_all U1 U2) ->\n  exists V, exists e1, e = exp_tabs V e1.\nProof with auto.\n  intros.\n  generalize dependent U1.\n  generalize dependent U2.\n  dependent induction H0;intros;try solve [inversion H|inversion H1|inversion H2]...\n  -\n    exists V.\n    exists e1...\n  -\n    apply IHtyping with (U1:=U1) (U2:=U2)...\n    apply sub_transitivity with (Q:=T)...\nQed.\n\nLemma canonical_form_fold : forall e U S,\n  value e ->\n  typing empty e S ->\n  sub empty S (typ_mu U) ->\n  exists V, exists e1, (sub empty (typ_mu V) (typ_mu U) /\\ value e1 /\\ e = exp_fold (typ_mu V) e1).\nProof with auto.\n  intros.\n  generalize dependent U.\n  dependent induction H0;intros;try solve [inversion H|inversion H1|inversion H2]...\n  -\n    dependent destruction H.\n    exists A...\n    exists e...\n  -\n    apply IHtyping with (U:=U)...\n    apply sub_transitivity with (Q:=T)...\nQed.\n\n\nLemma value_expr: forall e,\n    value e -> expr e.\nProof with auto.\n  intros.\n  induction H...\nQed.\n\nLemma progress : forall e T,\n  typing empty e T ->\n  value e \\/ exists e', step e e'.\nProof with eauto.\n  intros.\n  dependent induction H...\n  -\n    inversion H0...\n  - (* abs *)\n    left.\n    constructor.\n    apply expr_abs with (L:=L).\n    pick fresh Y.\n    specialize_x_and_L Y L.\n    apply typing_regular in H.\n    destruct_hypos.\n    dependent destruction H...\n    apply WF_type in H0...\n    intros.\n    apply H in H1.\n    apply typing_regular in H1.\n    destruct_hypos...\n  - (* app *)\n    right.\n    destruct IHtyping1;destruct IHtyping2...\n    +\n      apply canonical_form_abs with (S:=typ_arrow T1 T2) (U1:=T1) (U2:=T2) in H...\n      destruct_hypos.\n      exists (open_ee x0 e2).\n      subst.\n      apply step_beta...\n      apply value_expr...\n      apply Reflexivity...\n      apply typing_regular in H.\n      destruct_hypos...\n    +\n      destruct_hypos.\n      exists (exp_app e1 x).\n      apply step_app2...\n    +\n      destruct_hypos.\n      exists (exp_app x e2).\n      apply step_app1...\n      apply value_expr...\n    +\n      destruct_hypos.\n      exists (exp_app x0 e2).\n      apply step_app1...\n      apply typing_regular in H0.\n      destruct_hypos...\n  - (* tabs *)\n    left.\n    constructor.\n    apply expr_tabs with (L:=L).\n    pick fresh Y.\n    specialize_x_and_L Y L.\n    apply typing_regular in H.\n    destruct_hypos.\n    dependent destruction H...\n    apply WF_type in H0...\n    intros.\n    apply H in H1.\n    apply typing_regular in H1.\n    destruct_hypos...\n  - (* tapp *)\n    right.\n    destruct IHtyping...\n    +\n      apply canonical_form_tabs with (U1:=T1) (U2:=T2) in H...\n      destruct_hypos.\n      exists (open_te x0 T).\n      subst.\n      apply step_tabs...\n      apply value_expr...\n      get_type...\n      apply Reflexivity...\n      apply typing_regular in H.\n      destruct_hypos...\n    +\n      destruct_hypos.\n      exists (exp_tapp x T).\n      apply step_tapp...\n      get_type...\n  - (* fold *)\n    assert (empty ~= empty) by auto.\n    apply IHtyping in H1.\n    destruct H1.\n    left.\n    constructor...\n    apply WF_type in H0...\n    right.\n    destruct H1.\n    exists (exp_fold (typ_mu A) x).\n    constructor...\n    apply typing_regular in H.\n    destruct H.\n    destruct H2.\n    apply WF_type in H0...\n  - (* unfold *)\n    right.\n    destruct IHtyping...\n    +\n      apply canonical_form_fold with (S:=typ_mu T) (U:=T) in H0...\n      destruct_hypos.\n      exists x0...\n      rewrite H2.\n      get_well_form...\n      apply step_fld...\n      apply WF_type in H3...\n      apply WF_type in H4...\n      apply Reflexivity...\n      apply typing_regular in H...\n      destruct_hypos...\n    +\n      destruct_hypos.\n      exists (exp_unfold (typ_mu T) x).\n      apply step_unfold...\n      apply typing_regular in H...\n      destruct_hypos.\n      apply WF_type in H2...\nQed.\n", "meta": {"author": "juda", "repo": "Recursive-Subtyping-for-All", "sha": "04e00cefca2330cbb23a758854c571ebaf6c6bb3", "save_path": "github-repos/coq/juda-Recursive-Subtyping-for-All", "path": "github-repos/coq/juda-Recursive-Subtyping-for-All/Recursive-Subtyping-for-All-04e00cefca2330cbb23a758854c571ebaf6c6bb3/kernel_fsub_minimal/Progress.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2842324335100129}}
{"text": "(* * Kripke Semantics *)\n\nFrom Undecidability Require Import FOL.Semantics.Tarski.FragmentFacts.\nFrom Undecidability Require Import FOL.Semantics.Kripke.FragmentCore.\nFrom Undecidability Require Import Shared.ListAutomation.\nImport ListAutomationNotations.\n\nSet Default Proof Using \"Type\".\n\nLocal Set Implicit Arguments.\nLocal Unset Strict Implicit.\n\nLocal Notation vec := Vector.t.\n\n#[local] Ltac comp := repeat (progress (cbn in *; autounfold in *)).\n\n(* ** Connection to Tarski Semantics *)\n\nSection ToTarski.\n\n  Context {Σ_funcs : funcs_signature}.\n  Context {Σ_preds : preds_signature}.\n\n  Program Instance interp_kripke {domain} (I : interp domain) : kmodel domain :=\n    {| nodes := unit ; reachable u v := True |}.\n  Next Obligation.\n    - now apply I in X.\n  Defined.\n\n  Lemma kripke_tarski {ff : falsity_flag} domain (I : interp domain) rho phi :\n    rho ⊨ phi <-> ksat (interp_kripke I) tt rho phi.\n  Proof.\n    revert rho. induction phi; intros rho.\n    - tauto.\n    - tauto.\n    - destruct b0. cbn. rewrite IHphi1, IHphi2. intuition. destruct v. tauto.\n    - destruct q. cbn. split; intros H; cbn in *.\n      + intros i. apply IHphi, H.\n      + intros i. apply IHphi, H.\n  Qed.\n\n  Lemma kvalid_valid b (phi : form b) :\n    kvalid phi -> valid phi.\n  Proof.\n    intros H domain I rho. apply kripke_tarski, H.\n  Qed.\n\n  Lemma ksatis_satis b (phi : form b) :\n    satis phi -> ksatis phi.\n  Proof.\n    intros (domain & I & rho & ?). eapply kripke_tarski in H.\n    now exists domain, (interp_kripke I), tt, rho.\n  Qed.\n\nEnd ToTarski.\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/FOL/Semantics/Kripke/FragmentToTarski.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.28421475809295166}}
{"text": "From Undecidability.L Require Export Util.L_facts Tactics.Extract.\nRequire Import Undecidability.Shared.Libs.PSL.Bijection String.\n\n(* * Correctness and time bounds *)\n\n(* Typeclass for registering types *)\n\n\nClass registered (X : Type) := mk_registered\n  {\n    enc :> encodable X ; (* the encoding function for X *)\n    proc_enc : forall x, proc (enc x) ; (* encodings need to be a procedure *)\n    inj_enc : injective enc (* encoding is injective *)\n  }.\n\n#[export] Hint Mode registered + : typeclass_instances. (* treat argument as input and force evar-freeness*)\n\nArguments enc : simpl never.  (* Never unfold with cbn/simpl *)\n\n(* ** Correctness *)\n\n(* Definition of the valid types for extraction *)\n\nInductive TT : Type -> Type :=\n  TyB t (R : registered t) : TT t\n| TyArr t1 t2 (tt1 : TT t1) (tt2 : TT t2)\n  : TT (t1 -> t2).\n\nExisting Class TT.\nExisting Instance TyB.\nExisting Instance TyArr.\n  \nArguments TyB _ {_}.\nArguments TyArr {_} {_} _ _.\n\n#[export] Hint Mode TT + : typeclass_instances. (* treat argument as input and force evar-freeness*)\n\nNotation \"! X\" := (TyB X) (at level 69).\nNotation \"X ~> Y\" := (TyArr X Y) (right associativity, at level 70).\n\n\nFixpoint computes {A} (tau : TT A) {struct tau}: A -> L.term -> Type :=\n  match tau with\n    !_ => fun x xInt => (xInt = enc x)\n  | @TyArr A B tau1 tau2 =>\n    fun f t_f  =>\n      proc t_f * forall (a : A) t_a,\n        computes tau1 a t_a\n        ->  {v : term & (app t_f t_a >* v) * computes tau2 (f a) v}\n  end%type.\n\nLemma computesProc t (ty : TT t) (f : t) fInt:\n  computes ty f fInt -> proc fInt.\nProof.\n  destruct ty.\n  -intros ->. unfold enc. now destruct R. \n  -now intros [? _].\nQed.\n\n(* This is for a user to give an definition *)\nClass computable X {ty : TT X} (x : X) : Type :=\n  {\n    ext : extracted x;\n    extCorrect : computes ty x ext;\n  }.\n\nGlobal Arguments computable {X} {ty} x.\nGlobal Arguments extCorrect {X} ty x {computable} : simpl never.\nGlobal Arguments ext {X} {ty} x {computable} : simpl never.\n\n#[export] Hint Mode computable + - +: typeclass_instances. (* treat argument as input and force evar-freeness*)\n#[export] Hint Extern 4 (@extracted ?t ?f) => let ty := constr:(_ : TT t) in notypeclasses refine (ext (ty:=ty) f) : typeclass_instances.\n\nTypeclasses Opaque ext.\n\nLemma proc_ext X (ty : TT X) (x : X) ( H : computable x) : proc (ext x).\nProof.\n  unfold ext. destruct H. apply (computesProc extCorrect0). \nQed.\n\n\nInstance reg_is_ext ty (R : registered ty) (x : ty) : computable x.\nProof.\n  exists (enc x). reflexivity.\nDefined. (* because ? *)\n\n\nLemma computesTyB (t:Type) (x:t) `{registered t}: computes (TyB t) x (ext x).\nProof.\n  unfold ext. now destruct R.\nQed.\n\nInstance extApp' t1 t2 {tt1:TT t1} {tt2 : TT t2} (f: t1 -> t2) (x:t1) (Hf : computable f) (Hx : computable x) : computable (f x).\nProof.\n  destruct Hf, Hx.\n  edestruct extCorrect0 as [? H].\n  edestruct H as (?&?&?).\n  eassumption.\n  now eapply (@Build_computable _ _ _ x0). \nDefined. (* because ? *)\n\nLemma extApp t1 t2 {tt1:TT t1} {tt2 : TT t2} (f: t1 -> t2) (x:t1) (Hf : computable f) (Hx : computable x) :\n  app (ext f) (ext x) >* ext (f x).\nProof.\n  unfold ext, extApp'.\n  destruct Hf, Hx.\n  destruct extCorrect0 as (? & correct0).\n  destruct correct0 as (?&?&?). tauto. \nQed.\n\nLemma ext_is_enc t1 (R:registered t1) (x: t1) (Hf : computable x) :\n  @ext _ _ x Hf = enc x.\nProof.\n  now destruct Hf. \nDefined. (* because ? *)\n\nDefinition computesExp {t} (ty : TT t) (f:t) (s fExt : term) : Type :=\n  eval s fExt * computes ty f fExt.\n\nLemma computesExpStart t1 (tt1 : TT t1) (f : t1) (fExt : term):\n  proc fExt ->\n  {v :term & computesExp tt1 f fExt v} ->  computes tt1 f fExt.\nProof.\n  intros ? (?&?&?). replace fExt with x. tauto. apply unique_normal_forms. eapply e. eapply H. destruct e as [e ?]. now rewrite e. \nQed.\n\nLemma computesExpStep t1 t2 (tt1 : TT t1) (tt2 : TT t2) (f : t1 -> t2) (s:term) (fExt : term):\n  eval s fExt -> closed s -> \n  (forall (y : t1) (yExt : term), computes tt1 y yExt -> {v : term & computesExp tt2 (f y) (app s yExt) v}%type) ->\n  computesExp (tt1 ~> tt2) f s fExt.\nProof.\n  intros ? ? H. split. assumption. split. split. now rewrite <-H0. now destruct H0.\n  intros ? ? exted.\n  edestruct H as (v&?&?). eassumption. \n  eexists v. split. rewrite H0 in e. now rewrite e. eauto.\nQed.\n\nLemma computesTyArr t1 t2 (tt1 : TT t1) (tt2 : TT t2) f fExt :\n  proc fExt\n  -> (forall (y : t1) (yExt : term),\n        computes tt1 y yExt\n        -> {v : term & eval (app fExt yExt) v * (proc v -> computes tt2 (f y) v)}%type)\n  -> computes (tt1 ~> tt2) f fExt.\nProof.\n  intros ? H'.\n  split;[assumption|].\n  intros y yExt yCorrect.\n  edestruct H' as (?&(R&?) & H''). eassumption. \n  eexists. split.\n  eassumption. \n  eapply H''.\n  split. 2:assumption.\n  rewrite <- R. apply app_closed. now destruct H. specialize (computesProc yCorrect) as []. easy.\nQed.\n\n(* Extensional equality to extract similar functions without unsopported features (e.g. informative deciders) instead *)\n\nFixpoint extEq t {tt:TT t} : t -> t -> Prop:=\n  match tt with\n    TyB _ _ => eq\n  | @TyArr t1 t2 _ _ => fun f f' => forall (x : t1), extEq (f x) (f' x)\n  end.\n\n\nInstance extEq_refl t (tt:TT t): Reflexive (extEq (tt:=tt)).\nProof.\n  unfold Reflexive.\n  induction tt;cbn.\n  -reflexivity.\n  -intros f x. eauto.\nQed.\n\nLemma computesExt X (tt : TT X) (x x' : X) s:\n  extEq x x' -> computes tt x s -> computes tt x' s.\nProof.\n  induction tt in x,x',s |-*;intros eq.\n  -inv eq. tauto.\n  -cbn in eq|-*. intros [H1 H2]. split. 1:tauto.\n   intros y t exts.\n   specialize (H2 y t exts) as (v&R&H2).\n   exists v. split. 1:assumption.\n   eapply IHtt2. 2:now eassumption.\n   apply eq.\nQed.\n\nLemma computableExt X (tt : TT X) (x x' : X):\n  extEq x x' -> computable x -> computable x'.\nProof.\n  intros ? (s&?). exists s. eauto using computesExt.\nDefined. (* because ? *)\n\n(* register a datatype via an (injectve) function to another, e.g. vectors as lists *)\n\nLemma registerAs X Y `{registered X} (f:Y -> X) : injective f -> registered Y.\nProof.\n  intros Hf. eexists (fun x => enc (f x)). now destruct H.\n  intros ? ? ?. now eapply H, Hf in H0.\nDefined. (* because ? *)\nArguments registerAs {_ _ _} _ _.\n\n(* Support for extracting registerAs-ed functions *)\n\nFixpoint changeResType t1 t2 (tt1:TT t1) (tt2 : TT t2) : {t & TT t}:=\n  match tt1 with\n    TyB _ _ => existT _ t2 tt2\n  | TyArr _ _ tt11 tt12 =>\n    existT _ _ (TyArr tt11 (projT2 (changeResType tt12 tt2)))\n  end.\n\nFixpoint resType t1 (tt1 : TT t1) : {t & registered t} :=\n  match tt1 with\n    @TyB _ R => existT _ _ R\n  | TyArr _ _ _ t2 => resType t2\n  end.\n\nFixpoint insertCast t1 (tt1 : TT t1) Y (R: registered Y) {struct tt1}:\n  forall (cast : projT1 (resType tt1) -> Y) (f : t1), projT1 (changeResType tt1 (TyB Y)) :=\n  match tt1 with\n    TyB _ _ => fun cast x => cast x\n  | TyArr _ _ tt11 tt12 => fun cast f x=> (insertCast (tt1:=tt12) R cast (f x))\n  end.\n\n\nLemma cast_registeredAs t1 (tt1 : TT t1) Y (R: registered Y) (cast : projT1 (resType tt1) -> Y) (f:t1)\n  (Hc : injective cast) :\n  projT2 (resType tt1) = registerAs cast Hc ->\n  computable (ty:=projT2 (changeResType tt1 (TyB Y))) (insertCast R cast f) ->\n  computable f.\nProof.\n  intros H (s&exts).\n  exists s.\n  induction tt1 in cast,f,H,s,exts,Hc |- *.\n  -cbn in H,exts|-*;unfold enc in *. rewrite H. exact exts.\n  -destruct exts as (?&exts). split. assumption.\n   intros x s__x ext__x.\n   specialize (exts x s__x ext__x) as (v &?&exts).\n   exists v. split. tauto.\n   eapply IHtt1_2. all:eassumption.\nQed.\n\nOpaque computes.\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/Tactics/Computable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.2842147580929516}}
{"text": "From Coq Require Import ZArith List.\nFrom mathcomp Require Import ssreflect ssrbool ssrnat eqtype seq.\nFrom BitBlasting Require Import QFBV CNF BBCommon BBUle.\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_uge ===== *)\n\nDefinition bit_blast_uge g ls1 ls2 : generator * cnf * literal :=\n  bit_blast_ule g ls2 ls1.\n\nDefinition mk_env_uge E g ls1 ls2 : env * generator * cnf * literal :=\n  mk_env_ule E g ls2 ls1.\n\nLemma bit_blast_uge_correct g bs1 bs2 E ls1 ls2 g' cs lr :\n  bit_blast_uge 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 (geB bs1 bs2).\nProof.\n  rewrite /geB.\n  rewrite /bit_blast_uge.\n  move => Hule Hsz Henc1 Henc2 Hcnf.\n  symmetry in Hsz.\n  exact : (bit_blast_ule_correct Hule Hsz Henc2 Henc1 Hcnf) => Hrule.\nQed.\n\nLemma mk_env_uge_is_bit_blast_uge E g ls1 ls2 E' g' cs lr:\n    mk_env_uge E g ls1 ls2 = (E', g', cs, lr) ->\n    bit_blast_uge g ls1 ls2 = (g', cs, lr).\nProof.\n  rewrite /mk_env_uge /bit_blast_uge.\n  exact: mk_env_ule_is_bit_blast_ule.\nQed.\n\nLemma mk_env_uge_newer_gen E g ls1 ls2 E' g' cs lr:\n    mk_env_uge E g ls1 ls2 = (E', g', cs, lr) ->\n    (g <=? g')%positive.\nProof.\n  rewrite /mk_env_uge.\n  exact: mk_env_ule_newer_gen.\nQed.\n\nLemma mk_env_uge_newer_res E g ls1 ls2 E' g' cs lr:\n    mk_env_uge E g ls1 ls2 = (E', g', cs, lr) ->\n    newer_than_lit g' lr.\nProof.\n  rewrite /mk_env_uge. move=> H.\n  exact: (mk_env_ule_newer_res H).\nQed.\n\nLemma mk_env_uge_newer_cnf E g ls1 ls2 E' g' cs lr:\n    mk_env_uge 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_uge.\n  move=> H e0 e1 e2.\n  exact: (mk_env_ule_newer_cnf H e0 e2 e1).\nQed.\n\nLemma mk_env_uge_preserve E g ls1 ls2 E' g' cs lr:\n    mk_env_uge E g ls1 ls2 = (E', g', cs, lr) ->\n    env_preserve E E' g.\nProof.\n  rewrite /mk_env_uge.\n  exact: mk_env_ule_preserve.\nQed.\n\nLemma mk_env_uge_sat E g ls1 ls2 E' g' cs lr:\n    mk_env_uge 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_uge.\n  move=> H e0 e1 e2.\n  exact: (mk_env_ule_sat H e0 e2 e1).\nQed.\n\nLemma mk_env_uge_env_equal E1 E2 g ls1 ls2 E1' E2' g1' g2' cs1 cs2 lrs1 lrs2 :\n  env_equal E1 E2 ->\n  mk_env_uge E1 g ls1 ls2 = (E1', g1', cs1, lrs1) ->\n  mk_env_uge E2 g ls1 ls2 = (E2', g2', cs2, lrs2) ->\n  env_equal E1' E2' /\\ g1' = g2' /\\ cs1 = cs2 /\\ lrs1 = lrs2.\nProof. exact: mk_env_ule_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/BBUge.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947155710234, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.28421216795584525}}
{"text": "(**********************************************************************)\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 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(**********************************************************************)\n(*             Intensional Lambda Calculus                            *)\n(*                                                                    *)\n(* is implemented in Coq by adapting the implementation of            *) \n(* Lambda Calculus from Project Coq                                   *)\n(* 2015                                                               *)\n(**********************************************************************)\n\n(**********************************************************************)\n(*                           Marks.v                                  *)\n(*                                                                    *)\n(* adapted from Marks.v for Lambda Calculus                           *)\n(*                                                                    *)\n(*                          Barry Jay                                 *)\n(*                                                                    *)\n(**********************************************************************)\n\nRequire Import Arith.\nRequire Import Lambda.Test.\nRequire Import Lambda.General.\nRequire Import Lambda.Terms.\nRequire Import Lambda.Redexes.\nRequire Import Lambda.Residuals.\n\n(* Translation from terms to redexes *)\n\nFixpoint mark (e : lambda) : redexes :=\n  match e with\n  | Ref i => Var i\n  | App M N => Ap false (mark M) (mark N)\n  | Abs M => Fun (mark M)\n  end. \n\n\n(* Reverse translation : erasing the marks *)\n\nFixpoint unmark (e : redexes) : lambda :=\n  match e with\n  | Var i => Ref i\n  | Ap b U V => App (unmark U) (unmark V)\n  | Fun U => Abs (unmark U)\n  end.\n\nLemma inverse : forall M : lambda, M = unmark (mark M).\nProof.\nsimple induction M; simpl in |- *; trivial; simple induction 1; trivial.\nsimple induction 1; trivial.\nQed.\n\nLemma comp_unmark_eq : forall U V : redexes, comp U V -> unmark U = unmark V.\nProof.\nsimple induction 1; simpl in |- *; trivial; split_all. \nQed.\n\n(* The converse is true, but not needed in the rest of the development *)\n\nLemma residuals_mark :\nforall M, residuals (mark M) (mark M) (mark M).\nProof. induction M; split_all. Qed.\n\nHint Resolve residuals_mark.\n", "meta": {"author": "Barry-Jay", "repo": "lambdaSF", "sha": "22a80d136e2986387e6c1e27b3872b39c974bcc1", "save_path": "github-repos/coq/Barry-Jay-lambdaSF", "path": "github-repos/coq/Barry-Jay-lambdaSF/lambdaSF-22a80d136e2986387e6c1e27b3872b39c974bcc1/Lambda/Marks.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.2841456891028712}}
{"text": "(*\n * Defining Hexadecimal\n *)\nInductive address :=\n | Nil\n | D0 (_:address)\n | D1 (_:address)\n | D2 (_:address)\n | D3 (_:address)\n | D4 (_:address)\n | D5 (_:address)\n | D6 (_:address)\n | D7 (_:address)\n | D8 (_:address)\n | D9 (_:address)\n | Da (_:address)\n | Db (_:address)\n | Dc (_:address)\n | Dd (_:address)\n | De (_:address)\n | Df (_:address).\n\nFixpoint compare_address (h1 : address) (h2 : address) : bool :=\n    match h1 with\n    | Nil => \n        match h2 with\n        | Nil => true\n        | _ => false\n        end\n    | D0 h1' => \n        match h2 with\n        | D0 h2' => compare_address h1' h2'\n        | _ => false\n        end \n    | D1 h1' => \n        match h2 with\n        | D1 h2' => compare_address h1' h2'\n        | _ => false\n        end\n    | D2 h1' => \n        match h2 with\n        | D2 h2' => compare_address h1' h2'\n        | _ => false\n        end\n    | D3 h1' => \n        match h2 with\n        | D3 h2' => compare_address h1' h2'\n        | _ => false\n        end\n    | D4 h1' => \n        match h2 with\n        | D4 h2' => compare_address h1' h2'\n        | _ => false\n        end\n    | D5 h1' => \n        match h2 with\n        | D5 h2' => compare_address h1' h2'\n        | _ => false\n        end\n    | D6 h1' => \n        match h2 with\n        | D6 h2' => compare_address h1' h2'\n        | _ => false\n        end\n    | D7 h1' => \n        match h2 with\n        | D7 h2' => compare_address h1' h2'\n        | _ => false\n        end\n    | D8 h1' => \n        match h2 with\n        | D8 h2' => compare_address h1' h2'\n        | _ => false\n        end\n    | D9 h1' => \n        match h2 with\n        | D9 h2' => compare_address h1' h2'\n        | _ => false\n        end\n    | Da h1' => \n        match h2 with\n        | Da h2' => compare_address h1' h2'\n        | _ => false\n        end\n    | Db h1' => \n        match h2 with\n        | Db h2' => compare_address h1' h2'\n        | _ => false\n        end\n    | Dc h1' => \n        match h2 with\n        | Dc h2' => compare_address h1' h2'\n        | _ => false\n        end\n    | Dd h1' => \n        match h2 with\n        | Dd h2' => compare_address h1' h2'\n        | _ => false\n        end\n    | De h1' => \n        match h2 with\n        | De h2' => compare_address h1' h2'\n        | _ => false\n        end\n    | Df h1' => \n        match h2 with\n        | Df h2' => compare_address h1' h2'\n        | _ => false\n        end\n    end.\n\nLemma compare_same_address : forall (addr : address),\n    compare_address addr addr = true.\nProof.\n    intros. induction addr as [ | l' | l' | l' | l' | l' | l' | l' | \n    l' | l' | l' | l' | l' | l' | l' | l' | l' IHl'].\n    - simpl. reflexivity.\n    - simpl. apply IHl'.\n    - simpl. apply IHl'.\n    - simpl. apply IHl'.\n    - simpl. apply IHl'.\n    - simpl. apply IHl'.\n    - simpl. apply IHl'.\n    - simpl. apply IHl'.\n    - simpl. apply IHl'.\n    - simpl. apply IHl'.\n    - simpl. apply IHl'.\n    - simpl. apply IHl'.\n    - simpl. apply IHl'.\n    - simpl. apply IHl'.\n    - simpl. apply IHl'.\n    - simpl. apply IHl'.\n    - simpl. apply IHl'.\nQed.\n    \n", "meta": {"author": "DjedAlliance", "repo": "Oracle-FormalMethods", "sha": "dad11f28cf6e270cab19e2cd77113241e880d727", "save_path": "github-repos/coq/DjedAlliance-Oracle-FormalMethods", "path": "github-repos/coq/DjedAlliance-Oracle-FormalMethods/Oracle-FormalMethods-dad11f28cf6e270cab19e2cd77113241e880d727/oracle-formalization/Hexadecimal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.28414568910287114}}
{"text": "(*  DEC 2.0 language specification.\n   Paolo Torrini, \n   Universite' de Lille - CRIStAL-CNRS\n*)\n\nRequire Import List.\nRequire Import Equality.\n\nRequire Import AuxLibI1.\nRequire Import TypSpecI1. \nRequire Import ModTypI1. \nRequire Import LangSpecI1. \nRequire Import StaticSemI1.\nRequire Import DynamicSemI1.\nRequire Import WeakenI1.\nRequire Import UniqueTypI1.\n\nImport ListNotations.\n\n\n(** * DEC 2.0 language specification *)\n\n(** Derived dynamic rules *)\n\nModule DerivDyn (IdT: ModTyp) <: ModTyp.\n\nModule UniqueTypL := UniqueTyp IdT.\nExport UniqueTypL.\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\n(*********************************************************************)\n\n(** big-step lifting of congruence rules *)\n\nLemma BindN_extended_congruence : \n   forall (fenv: funEnv) (env: valEnv)  \n                          (s1 s2: W) (n1 n2: nat) (p1 p2 p3: Exp),\n     EClosure fenv env (Conf Exp s1 n1 p1) (Conf Exp s2 n2 p2) ->\n     EClosure fenv env (Conf Exp s1 n1 (BindN p1 p3))\n                            (Conf Exp s2 n2 (BindN p2 p3)).\nProof.\n  intros.\n  dependent induction X.\n  constructor.\n  destruct p5.\n  specialize (IHX state s2).\n  specialize (IHX fuel n2).\n  specialize (IHX qq).\n  specialize (IHX p2).\n  econstructor.\n  - instantiate (1:= Conf Exp state fuel (BindN qq p3)).\n    eapply BindN_Cg_EStep.\n    assumption.\n  - apply IHX.\n    reflexivity.\n    reflexivity.\nDefined.    \n\n\nLemma BindMS_extended_congruence :\n        forall (fenv: funEnv) (env envL env': valEnv)\n                (s1 s2: W) (n1 n2: nat) (e1 e2: Exp),\n          env' = envL ++ env -> \n          EClosure fenv env' (Conf Exp s1 n1 e1) (Conf Exp s2 n2 e2) ->\n          EClosure fenv env (Conf Exp s1 n1 (BindMS envL e1))\n                   (Conf Exp s2 n2 (BindMS envL e2)).\nProof.\n  intros.\n  dependent induction X.\n  constructor.\n  destruct p2.\n  econstructor.\n  - instantiate (1 := Conf Exp state fuel (BindMS envL qq)).  \n    econstructor.\n    reflexivity.\n    assumption.\n  - eapply IHX.\n    reflexivity.\n    reflexivity.\n    reflexivity.\nDefined.\n\n\nLemma BindS_extended_congruence :\n   forall (fenv: funEnv) (env: valEnv)\n      (s1 s2: W) (n1 n2: nat) (x: Id) (mt: option VTyp) (p1 p2 p3: Exp),\n           EClosure fenv env (Conf Exp s1 n1 p1) (Conf Exp s2 n2 p2) ->\n           EClosure fenv env (Conf Exp s1 n1 (BindS x mt p1 p3))\n                             (Conf Exp s2 n2 (BindS x mt p2 p3)).\nProof.\n  intros.\n  dependent induction X.\n  constructor.\n  destruct p5.\n  econstructor.\n  - econstructor.\n    eassumption.\n  - eapply IHX.\n    reflexivity.\n    reflexivity.\nDefined.\n\n\nLemma Apply1_extended_congruence :\n     forall (fenv: funEnv) (env: valEnv)\n                           (s s': W) (n n': nat) \n                           (x: Id) (ps ps': Prms) (v: Value),\n     PClosure fenv env (Conf Prms s n ps) (Conf Prms s' n' ps') ->\n     EClosure fenv env (Conf Exp s n (Apply x ps (Val v)))\n                            (Conf Exp s' n' (Apply x ps' (Val v))).\nProof.\n  intros.\n  dependent induction X.\n  constructor.\n  destruct p2.\n  econstructor.\n  - instantiate (1 := Conf Exp state fuel (Apply x qq (Val v))).\n    econstructor.\n    assumption.\n  - specialize (IHX state s' fuel n' qq ps').\n    eapply IHX. \n    reflexivity.\n    reflexivity.\nDefined.\n\n\nLemma Apply2_extended_congruence \n      (fenv: funEnv) (env: valEnv) (s s': W) (n n': nat)\n      (x: Id) (ps: Prms) (e e': Exp) : \n     EClosure fenv env (Conf Exp s n e) (Conf Exp s' n' e') ->\n     EClosure fenv env (Conf Exp s n (Apply x ps e))\n                            (Conf Exp s' n' (Apply x ps e')).\nProof.\n  intros.\n  dependent induction X.\n  constructor.\n  destruct p2.\n  econstructor.\n  - instantiate (1:= Conf Exp state fuel (Apply x ps qq)). \n    econstructor.\n    eassumption.\n  - eapply IHX.\n    reflexivity.\n    reflexivity.\nDefined.  \n\n\nLemma IfThenElse_extended_congruence :\n     forall (fenv: funEnv) (env: valEnv)\n                           (s s': W) (n n': nat) \n                           (e e' e1 e2: Exp),\n     EClosure fenv env (Conf Exp s n e) (Conf Exp s' n' e') ->\n     EClosure fenv env (Conf Exp s n\n                                 (IfThenElse e e1 e2))\n                            (Conf Exp s' n'\n                                 (IfThenElse e' e1 e2)).\nProof.\n  intros. \n  dependent induction X.\n  constructor.\n  intros.\n  destruct p2.\n  specialize (IHX state s' fuel n' qq e' eq_refl eq_refl). \n  econstructor.\n  - econstructor.\n    eassumption.\n  - assumption.\nDefined.  \n\n\nLemma Call_extended_congruence :\n     forall (fenv: funEnv) (env: valEnv)\n                           (s s': W) (n n': nat) \n                           (x: Id) (ps ps': Prms),\n     PClosure fenv env (Conf Prms s n ps) (Conf Prms s' n' ps') ->\n     EClosure fenv env (Conf Exp s n (Call x ps))\n                            (Conf Exp s' n' (Call x ps')).\nProof.\n  intros.\n  dependent induction X.\n  constructor.\n  destruct p2.\n  econstructor.\n  - instantiate (1 := Conf Exp state fuel (Call x qq)).\n    econstructor.\n    assumption.\n  - specialize (IHX state s' fuel n' qq ps').\n    eapply IHX. \n    reflexivity.\n    reflexivity.\nDefined.\n\n\nLemma Modify_extended_congruence :\n     forall (fenv: funEnv) (env: valEnv)\n            (s s': W) (n n': nat) (t1 t2: VTyp)\n            (xf: XFun t1 t2) (e e': Exp),\n     EClosure fenv env (Conf Exp s n e) (Conf Exp s' n' e') ->\n     EClosure fenv env (Conf Exp s n\n                                 (Modify t1 t2 xf e))\n                       (Conf Exp s' n'\n                                 (Modify t1 t2 xf e')).\nProof.\n  intros. \n  dependent induction X.\n  constructor.\n  destruct p2.\n  specialize (IHX state s' fuel n' xf qq e' eq_refl eq_refl). \n  econstructor.\n  - econstructor.\n    eassumption.\n  - assumption.\nDefined.  \n\n\nLemma Prms_extended_congruence1 :\n    forall (fenv: funEnv) (env: valEnv)\n                   (s s': W) (n n': nat)\n                   (es es': list Exp) (v: Value),\n         PClosure fenv env (Conf Prms s n (PS es))\n                                   (Conf Prms s' n' (PS es')) ->\n         PClosure fenv env (Conf Prms s n (PS (Val v :: es)))\n                                   (Conf Prms s' n' (PS (Val v :: es'))).  \nProof.\n  intros.\n  revert v.\n  dependent induction X.\n  - intros.\n    constructor.\n  - intros.\n    destruct p2.\n    destruct qq. \n    specialize (IHX state s' fuel n' es0 es').\n    specialize (IHX eq_refl eq_refl v).\n    econstructor.\n    econstructor.\n    eassumption.\n    assumption.\nDefined.\n  \n\nLemma Prms_extended_congruence2 :\n    forall (fenv: funEnv) (env: valEnv)\n           (s s': W) (n n': nat) (es: list Exp) (e e': Exp),\n         EClosure fenv env (Conf Exp s n e)\n                                (Conf Exp s' n' e') ->\n         PClosure fenv env (Conf Prms s n (PS (e::es)))\n                           (Conf Prms s' n' (PS (e'::es))).  \n  intros.\n  revert es.\n  dependent induction X.\n  - constructor.\n  - intros.\n    destruct p2.\n    specialize (IHX state s' fuel n' qq e').\n    specialize (IHX eq_refl eq_refl es).\n    econstructor.\n    econstructor.\n    eassumption.\n    assumption.\nDefined.  \n  \n\nLemma Prms_extended_congruence3 :\n       forall (fenv: funEnv) (env: valEnv)\n                   (s s': W) (n n': nat) \n                   (es evs: list Exp) (vs: list Value),\n         isValueList2T evs vs ->                             \n         PClosure fenv env (Conf Prms s n (PS es))\n                                   (Conf Prms s' n' (PS evs)) ->\n         PClosure fenv env (Conf Prms s n (PS es))\n                                   (Conf Prms s' n' (PS (map Val vs))).  \nProof.\n  intros.\n  inversion X; subst.\n  assumption.\nDefined.  \n\n\nLemma Prms_extended_congruence4 :\n    forall (fenv: funEnv) (env: valEnv)\n           (s s' s'': W) (n n' n'': nat)\n           (es es': list Exp) (e: Exp) (v: Value),\n         EClosure fenv env (Conf Exp s n e)\n                                (Conf Exp s' n' (Val v)) ->\n         PClosure fenv env (Conf Prms s' n' (PS es))\n                                   (Conf Prms s'' n'' (PS es')) ->  \n         PClosure fenv env (Conf Prms s n (PS (e::es)))\n                                   (Conf Prms s'' n'' (PS (Val v::es'))).  \n  intros.\n  revert es es' X0.\n  revert s'' n''.\n  dependent induction X.\n  - intros.\n    eapply PConcat.\n    econstructor.\n    eapply Prms_extended_congruence1.\n    assumption.\n  - intros.\n    destruct p2.\n    specialize (IHX state s' fuel n' qq v).\n    specialize (IHX eq_refl eq_refl s'' n'' es es' X0).\n    econstructor.\n    econstructor.\n    eassumption.\n    assumption.\nDefined.  \n\n(****************************************************************************)\n\nLemma BindN_FStep :   \n   forall (fenv: funEnv) (env: valEnv)\n          (s0 s1 s2: W) (n0 n1 n2: nat)\n          (e1 e2: Exp) (v1 v2: Value),\n    EClosure fenv env (Conf Exp s0 n0 e1) (Conf Exp s1 n1 (Val v1)) ->\n    EClosure fenv env (Conf Exp s1 n1 e2) (Conf Exp s2 n2 (Val v2)) ->\n    EClosure fenv env (Conf Exp s0 n0 (BindN e1 e2))\n                      (Conf Exp s2 n2 (Val v2)).\n  intros.\n  eapply (EClosConcat fenv env).\n  instantiate (1:=Conf Exp s1 n1 (BindN (Val v1) e2)).\n  eapply BindN_extended_congruence.\n  assumption.\n  econstructor.\n  econstructor.\n  assumption.\nDefined.\n\nLemma BindS_FStep :   \n   forall (fenv: funEnv) (env: valEnv)\n          (s0 s1 s2: W) (n0 n1 n2: nat)\n          (e1 e2: Exp) (x: Id) (m: option VTyp) (v1 v2: Value),\n    EClosure fenv env (Conf Exp s0 n0 e1) (Conf Exp s1 n1 (Val v1)) ->\n    EClosure fenv ((x,v1)::env) (Conf Exp s1 n1 e2) (Conf Exp s2 n2 (Val v2)) ->\n    EClosure fenv env (Conf Exp s0 n0 (BindS x m e1 e2))\n                      (Conf Exp s2 n2 (Val v2)).\n  intros.\n  eapply (EClosConcat fenv env).\n  instantiate (1:=Conf Exp s1 n1 (BindS x m (Val v1) e2)).\n  eapply BindS_extended_congruence.\n  assumption.\n  econstructor.\n  econstructor.\n  eapply (EClosConcat fenv env).\n  instantiate (1:=Conf Exp s2 n2 (BindMS (singleE x v1) (Val v2))).\n  eapply BindMS_extended_congruence.\n  reflexivity.\n  unfold singleE.\n  simpl.\n  assumption.\n  econstructor.\n  econstructor.\n  econstructor.\nDefined.\n\nLemma BindMS_FStep :   \n   forall (fenv: funEnv) (env env0: valEnv)\n          (s0 s1: W) (n0 n1: nat)\n          (e: Exp) (v: Value),\n    EClosure fenv (env0 ++ env) (Conf Exp s0 n0 e) (Conf Exp s1 n1 (Val v)) ->\n    EClosure fenv env (Conf Exp s0 n0 (BindMS env0 e))\n                      (Conf Exp s1 n1 (Val v)).\n  intros.\n  eapply (EClosConcat fenv env).\n  instantiate (1:=Conf Exp s1 n1 (BindMS env0 (Val v))).\n  eapply BindMS_extended_congruence.\n  reflexivity.\n  assumption.\n  econstructor.\n  econstructor.\n  constructor.\nDefined.  \n\nLemma IfThenElse_FStep1 :   \n   forall (fenv: funEnv) (env: valEnv)\n          (s0 s1 s2: W) (n0 n1 n2: nat)\n          (e1 e2 e3: Exp) (v: Value),\n  EClosure fenv env (Conf Exp s0 n0 e1)\n         (Conf Exp s1 n1 (Val (existT ValueI Bool (Cst Bool true)))) ->    \n  EClosure fenv env (Conf Exp s1 n1 e2) (Conf Exp s2 n2 (Val v)) ->\n  EClosure fenv env (Conf Exp s0 n0 (IfThenElse e1 e2 e3))\n    (Conf Exp s2 n2 (Val v)).\n  intros.\n  eapply (EClosConcat fenv env).\n  instantiate (1:=Conf Exp s1 n1 (IfThenElse (Val (cst Bool true)) e2 e3)).\n  eapply IfThenElse_extended_congruence.\n  assumption.\n  econstructor.\n  econstructor.\n  assumption.\nDefined.  \n\nLemma IfThenElse_FStep2 :   \n   forall (fenv: funEnv) (env: valEnv)\n          (s0 s1 s2: W) (n0 n1 n2: nat)\n          (e1 e2 e3: Exp) (v: Value),\n  EClosure fenv env (Conf Exp s0 n0 e1)\n         (Conf Exp s1 n1 (Val (existT ValueI Bool (Cst Bool false)))) ->    \n  EClosure fenv env (Conf Exp s1 n1 e3) (Conf Exp s2 n2 (Val v)) ->\n  EClosure fenv env (Conf Exp s0 n0 (IfThenElse e1 e2 e3))\n    (Conf Exp s2 n2 (Val v)).\n  intros.\n  eapply (EClosConcat fenv env).\n  instantiate (1:=Conf Exp s1 n1 (IfThenElse (Val (cst Bool false)) e2 e3)).\n  eapply IfThenElse_extended_congruence.\n  assumption.\n  econstructor.\n  econstructor.\n  assumption.\nDefined.  \n\nLemma Apply_FStep :   \n   forall (fenv: funEnv) (env: valEnv)\n          (s0 s1: W) (n0 n1 n2 n3: nat) (x: Id)\n          (e: Exp) (v: Value) (vs: list Value) (f: Fun) (ps: Prms),\n     EClosure fenv env (Conf Exp s0 n0 e) (Conf Exp s0 n0 (Val v)) ->\n     PClosure fenv env (Conf Prms s0 n0 ps)\n              (Conf Prms s1 n1 (PS (map Val vs))) ->\n     v = cst Nat n2 ->\n     n3 = min n1 n2 ->\n     findE fenv x = Some f ->\n     EClosure fenv env (Conf Exp s0 n0 (Apply x ps e))\n              (Conf Exp s1 n3 (Call x (PS (map Val vs)))).\n  intros.\n  eapply (EClosConcat fenv env).\n  instantiate (1:=Conf Exp s0 n0 (Apply x ps (Val v))).\n  eapply Apply2_extended_congruence.\n  eapply EClosWeaken.\n  eassumption.\n  instantiate (1:=nil).\n  rewrite app_nil_r.\n  auto.\n  instantiate (1:=nil).\n  rewrite app_nil_r.\n  auto.\n  eapply (EClosConcat fenv env).\n  instantiate (1:= Conf Exp s1 n1 (Apply x (PS (map Val vs)) (Val v))).\n  eapply Apply1_extended_congruence.\n  assumption.\n  eapply StepIsEClos.\n  econstructor.\n  exact f.\n  exact H.\n  unfold isValueListT.\n  eapply forallValues.\n  assumption.\nDefined.  \n\nLemma Call_FStep0 :   \n   forall (fenv: funEnv) (env: valEnv)\n          (s: W) (n: nat) (x: Id)\n          (v: Value) (vs: list Value) (f: Fun),\n     findE fenv x = Some f ->\n     v = fun0Exp f ->\n     funArity f = length vs ->\n     n = 0 ->\n     EClosure fenv env (Conf Exp s n (Call x (PS (map Val vs))))\n                       (Conf Exp s n (Val v)).\n  intros.\n  eapply StepIsEClos.\n  rewrite H2.\n  econstructor.\n  eassumption.\n  econstructor.\n  assumption.\n  reflexivity.\n  assumption.\nDefined.  \n\nLemma Call_FStep01 :   \n   forall (fenv: funEnv) (env: valEnv)\n          (s0 s1: W) (n0 n1: nat) (x: Id)\n          (v: Value) (vs: list Value) (f: Fun) (ps: Prms),\n     PClosure fenv env (Conf Prms s0 n0 ps)\n              (Conf Prms s1 n1 (PS (map Val vs))) ->\n     findE fenv x = Some f ->\n     v = fun0Exp f ->\n     funArity f = length vs ->\n     n1 = 0 ->\n     EClosure fenv env (Conf Exp s0 n0 (Call x ps))\n                       (Conf Exp s1 n1 (Val v)).\n  intros.  \n  eapply (EClosConcat fenv env).\n  eapply Call_extended_congruence.\n  eassumption.\n  eapply Call_FStep0.\n  eassumption.\n  assumption.\n  assumption.\n  assumption.\nDefined.\n\n\nLemma Call_FStepS :   \n   forall (fenv: funEnv) (env: valEnv)\n          (s0 s2 s3: W) (n0 n2 n3: nat) (x: Id)\n          (v3: Value) (vs: list Value) (f: Fun) (ls: list Exp),\n    findE fenv x = Some f ->\n     funArity f = length vs -> \n    EClosure fenv env\n         (Conf Exp s2 n2 (BindMS (mkVEnv (funValTC f) vs) (funSExp f)))\n         (Conf Exp s3 n3 (Val v3)) ->\n    PClosure fenv env (Conf Prms s0 n0 (PS ls))\n         (Conf Prms s2 (S n2) (PS (map Val vs))) ->  \n    EClosure fenv env (Conf Exp s0 n0 (Call x (PS ls)))\n                           (Conf Exp s3 n3 (Val v3)).\nProof.\n  intros.\n  eapply Call_extended_congruence with (x:=x) in X0.\n  eapply EClosConcat.\n  exact X0.\n  econstructor.\n  instantiate (1:= Conf Exp s2 n2\n                        (BindMS (mkVEnv (funValTC f) vs) (funSExp f))).\n  econstructor.\n  econstructor.\n  eassumption.\n  assumption.\n  auto.\n  auto.\n  assumption.\nDefined.  \n\n\n\nLemma Call_FStepS1 :   \n   forall (fenv: funEnv) (env: valEnv)\n          (s0 s3: W) (n0 n3: nat) (x: Id)\n          (v3: Value) (vs: list Value) (f: Fun) (ls: list Exp),\n    findE fenv x = Some f ->\n     funArity f = length vs -> \n    EClosure fenv env\n         (Conf Exp s0 n0 (BindMS (mkVEnv (funValTC f) vs) (funSExp f)))\n         (Conf Exp s3 n3 (Val v3)) ->\n    isValueList2T ls vs -> \n    EClosure fenv env (Conf Exp s0 (S n0) (Call x (PS ls)))\n                           (Conf Exp s3 n3 (Val v3)).\nProof.\n  intros.\n  econstructor.\n  eapply Call_EStepS.\n  exact X0.\n  exact H.\n  exact H0.\n  reflexivity.\n  reflexivity.\n  exact X.\nDefined.  \n\n\nLemma Apply_FStepS :   \n   forall (fenv: funEnv) (env: valEnv)\n          (s0 s2 s3: W) (n0 n2 n3 n5 n6: nat) (x: Id)\n          (v3: Value) (vs: list Value) (e: Exp) (f: Fun) (ls: list Exp),\n    findE fenv x = Some f ->\n    funArity f = length vs ->\n    n6 = min n2 n5 ->\n    EClosure fenv env (Conf Exp s0 n0 e)\n             (Conf Exp s0 n0 (Val (cst Nat (S n5)))) -> \n    EClosure fenv env\n             (Conf Exp s2 n6\n                   (BindMS (mkVEnv (funValTC f) vs) (funSExp f)))\n         (Conf Exp s3 n3 (Val v3)) ->\n    PClosure fenv env (Conf Prms s0 n0 (PS ls))\n         (Conf Prms s2 (S n2) (PS (map Val vs))) ->  \n    EClosure fenv env (Conf Exp s0 n0 (Apply x (PS ls) e))\n                           (Conf Exp s3 n3 (Val v3)).\nProof.\n  intros.\n  eapply Apply2_extended_congruence with (x:=x) (e:=e) (ps:=PS ls) in X.\n  eapply EClosConcat.\n  exact X.\n  eapply Apply1_extended_congruence\n            with (x:=x) (ps:=PS ls) (v:=cst Nat (S n5)) in X1.\n  eapply EClosConcat.\n  exact X1.\n  econstructor.\n  instantiate (1:= Conf Exp s2 (S n6)\n                        (Call x (PS (map Val vs)))).\n  econstructor.\n  exact f.\n  reflexivity.\n  eapply forallValues.\n  simpl.\n  inversion H1; subst.\n  auto.\n  econstructor.\n  instantiate (1:=(Conf Exp s2 n6\n                        (BindMS (mkVEnv (funValTC f) vs) (funSExp f)))).\n  econstructor.\n  econstructor.\n  eassumption.\n  assumption.\n  reflexivity.\n  reflexivity.\n  assumption.\nDefined.  \n\n\nLemma Apply_FStep0 :   \n   forall (fenv: funEnv) (env: valEnv)\n          (s0 s1: W) (n0 n1 n2: nat) (x: Id)\n          (e: Exp) (v0 v: Value) (vs: list Value) (f: Fun) (ps: Prms),\n     EClosure fenv env (Conf Exp s0 n0 e) (Conf Exp s0 n0 (Val v0)) ->\n     PClosure fenv env (Conf Prms s0 n0 ps)\n              (Conf Prms s1 n1 (PS (map Val vs))) ->\n     findE fenv x = Some f ->\n     v = fun0Exp f ->\n     v0 = cst Nat n2 ->\n     n1 = 0 -> \n     funArity f = length vs ->\n     EClosure fenv env (Conf Exp s0 n0 (Apply x ps e))\n                       (Conf Exp s1 n1 (Val v)).\n  intros.\n  eapply (EClosConcat fenv env).\n  instantiate (1:=Conf Exp s1 0 (Call x (PS (map Val vs)))).\n  eapply Apply_FStep.\n  eassumption.\n  eassumption.\n  eassumption.\n  rewrite H2.\n  simpl.\n  reflexivity.\n  eassumption.\n  rewrite H2.\n  eapply Call_FStep0.\n  eassumption.\n  assumption.\n  assumption.\n  reflexivity.\nDefined.\n\n\nLemma Apply_FStep01 :   \n   forall (fenv: funEnv) (env: valEnv)\n          (s0 s1: W) (n0 n1 n2: nat) (x: Id)\n          (e: Exp) (v0 v: Value) (vs: list Value) (f: Fun) (ps: Prms),\n     EClosure fenv env (Conf Exp s0 n0 e) (Conf Exp s0 n0 (Val v0)) ->\n     PClosure fenv env (Conf Prms s0 n0 ps)\n              (Conf Prms s1 n1 (PS (map Val vs))) ->\n     findE fenv x = Some f ->\n     v = fun0Exp f ->\n     v0 = cst Nat n2 ->\n     0 = min n1 n2 -> \n     funArity f = length vs ->\n     EClosure fenv env (Conf Exp s0 n0 (Apply x ps e))\n                       (Conf Exp s1 0 (Val v)).\n  intros.\n  eapply (EClosConcat fenv env).\n  instantiate (1:=Conf Exp s1 (min n1 n2) (Call x (PS (map Val vs)))).\n  eapply Apply_FStep.\n  eassumption.\n  eassumption.\n  eassumption.\n  reflexivity.\n  eassumption.\n  rewrite <- H2. \n  eapply Call_FStep0.\n  eassumption.\n  assumption.\n  assumption.\n  reflexivity.\nDefined.\n\n\n\nLemma Modify_FStep :   \n   forall (n: nat) (fenv: funEnv) (env: valEnv)\n          (s0 s1 s2: W) (n0 n1: nat) (t1 t2: VTyp)\n          (xf: XFun t1 t2)\n          (e: Exp) (v1: sVTyp t1) (v2: Value),\n     EClosure fenv env (Conf Exp s0 n0 e) (Conf Exp s1 n1 (Val (cst t1 v1))) ->\n     v2 = (cst t2 (x_eval t1 t2 xf v1 s1)) ->\n     s2 = x_exec t1 t2 xf v1 s1 -> \n     EClosure fenv env (Conf Exp s0 n0 (Modify t1 t2 xf e))\n                       (Conf Exp s2 n1 (Val v2)).\n  intros.\n  eapply (EClosConcat fenv env).\n  instantiate (1:=Conf Exp s1 n1 (Modify t1 t2 xf (Val (cst t1 v1)))).\n  eapply Modify_extended_congruence.\n  eassumption.\n  eapply StepIsEClos.\n  inversion H; subst.\n  econstructor.\nDefined.  \n  \n\n(****************************************************************************)\n\nLemma Pure_step_inv1 :\n     forall (fenv: funEnv) (env: valEnv)\n                           (s s': W) (n n': nat) \n                           (e e': Exp),\n     Pure e ->   \n     EStep fenv env (Conf Exp s n e) (Conf Exp s' n' e') ->\n     Pure e'.\nProof.\n  intros.\n  revert X0.\n  revert s s' n n' e'.\n  induction X.\n  intros.\n  inversion X0.\n  intros.\n  inversion X0; subst.\n  constructor.\nDefined.\n  \nLemma Pure_inv1 :\n     forall (fenv: funEnv) (env: valEnv)\n                           (s s': W) (n n': nat) \n                           (e e': Exp),\n     Pure e ->   \n     EClosure fenv env (Conf Exp s n e) (Conf Exp s' n' e') ->\n     Pure e'.\nProof.\n  intros.\n  dependent induction X0.\n  assumption.\n  destruct p2.\n  specialize (IHX0 e' qq).\n  eapply IHX0.\n  eapply Pure_step_inv1 with (e':=qq) (e:=e).\n  assumption.\n  eassumption.\n  reflexivity.\n  reflexivity.\nDefined.  \n\nLemma Pure_step_sideffect :\n     forall (fenv: funEnv) (env: valEnv)\n                           (s s': W) (n n': nat) \n                           (e e': Exp),\n     Pure e ->   \n     EStep fenv env (Conf Exp s n e) (Conf Exp s' n' e') ->\n     s = s' /\\ n = n'.\nProof.\n  intros.\n  inversion X; subst.\n  inversion X0.\n  inversion X0; subst.\n  auto.\nDefined.\n\nLemma Pure_sideffect :\n     forall (fenv: funEnv) (env: valEnv)\n                           (s s': W) (n n': nat) \n                           (e e': Exp),\n     Pure e ->   \n     EClosure fenv env (Conf Exp s n e) (Conf Exp s' n' e') ->\n     s = s' /\\ n = n'.\nProof.\n  intros.\n  dependent induction X0.\n  auto.\n  destruct p2.\n  generalize e0.\n  intro k.\n  eapply Pure_step_sideffect in k.\n  destruct k.\n  inversion H; subst.\n  specialize (IHX0 e' qq).\n  eapply Pure_step_inv1 in e0.\n  specialize (IHX0 e0).\n  specialize (IHX0 n' fuel s' state).\n  specialize (IHX0 eq_refl eq_refl).\n  assumption.\n  assumption.\n  assumption.\nDefined.  \n  \n\n(******************************************************************)\n\n(** lemmas about parameters *)\n\nLemma PrmsStep_aux0 :\n    forall (fenv: funEnv) (env: valEnv)\n           (s s': W) (n n': nat) (es es': list Exp),\n         PStep fenv env (Conf Prms s n (PS es))\n                     (Conf Prms s' n' (PS es')) ->\n         length es = length es'.  \nProof.\n  intros.\n  dependent induction X.\n  specialize (IHX s s' n n' es0 es'0 eq_refl eq_refl).\n  simpl.\n  auto.\n  auto.\nDefined.  \n \nLemma PrmsClos_aux0 :\n    forall (fenv: funEnv) (env: valEnv)\n            (s s': W) (n n': nat) (es es': list Exp),\n         PClosure fenv env (Conf Prms s n (PS es))\n                     (Conf Prms s' n' (PS es')) ->\n         length es = length es'.  \nProof.\n  intros.\n  dependent induction X.\n  auto.\n  destruct p2.\n  destruct qq.\n  eapply PrmsStep_aux0 in p.\n  specialize (IHX state s' fuel n' es0 es' eq_refl eq_refl).\n  rewrite <- p in IHX.\n  auto.\nDefined.  \n\n\nLemma PrmsClos_aux1 (fenv: funEnv) (env: valEnv)\n                     (e: Exp) (v: Value) (es es': list Exp) (w: W * nat)\n      : {w' : W * nat &\n      PClosure fenv env (Conf Prms (fst w) (snd w) (PS (e :: es)))\n                  (Conf Prms (fst w') (snd w') (PS (Val v :: es')))} ->\n      {w' : W * nat &\n         prod (EClosure fenv env (Conf Exp (fst w) (snd w) e)\n               (Conf Exp (fst w') (snd w') (Val v)))\n            {w'' : W * nat &\n                  PClosure fenv env (Conf Prms (fst w') (snd w') (PS es))\n                                (Conf Prms (fst w'') (snd w'') (PS es'))} }.         \nProof.\n  intros.\n  destruct X as [w2 X].\n  dependent induction X.\n  - econstructor.\n    split.\n    econstructor.\n    econstructor.\n    econstructor.\n  - destruct p2.\n    destruct qq.\n    destruct es0 as [| e1 es1].\n    inversion p.\n    specialize (IHX e1 v es1 es' (state,fuel) w2 eq_refl eq_refl).\n    destruct IHX.\n    destruct p0.\n    destruct s.\n    inversion e0; subst.\n    inversion p; subst.\n    econstructor.\n    split.\n    econstructor.\n    econstructor.\n    econstructor.\n    exact X0.\n    exact p0.\n    econstructor.\n    split.\n    eapply StepIsEClos.\n    exact X0.\n    econstructor.\n    exact p0.\n    (**)\n    inversion e0; subst.\n    inversion X0.\n    inversion p; subst.\n    inversion X0.\n    econstructor.\n    split.\n    econstructor.\n    exact X4.\n    exact e0.\n    econstructor.\n    exact p0.\nDefined.    \n\n\nLemma PrmsClos_aux2 (fenv: funEnv) (env: valEnv)\n      (e: Exp) (v: Value) (es es': list Exp)\n      (w0 w1: W) (n0 n1: nat) : \n      PClosure fenv env (Conf Prms w0 n0 (PS (Val v :: es)))\n                  (Conf Prms w1 n1 (PS (Val v :: es'))) ->\n      PClosure fenv env (Conf Prms w0 n0 (PS es))\n                  (Conf Prms w1 n1 (PS es')).         \nProof.\n  intros.\n  dependent induction X.\n  - constructor.\n  - destruct p2.\n    destruct qq.\n    destruct es0.\n    inversion p.\n    inversion p; subst.\n    specialize (IHX v es0 es' state w1 fuel n1 eq_refl eq_refl).\n    econstructor.\n    exact X0.\n    exact IHX.\n    inversion X0.\nDefined.    \n    \n\nLemma PrmsClos_aux3 (fenv: funEnv) (env: valEnv)\n      (e: Exp) (v: Value) (es es': list Exp)\n      (w0 w1: W) (n0 n1: nat) :\n      PClosure fenv env (Conf Prms w0 n0 (PS (e :: es)))\n                  (Conf Prms w1 n1 (PS (Val v :: es'))) ->\n      {s : W * nat &\n        prod (EClosure fenv env (Conf Exp w0 n0 e)\n               (Conf Exp (fst s) (snd s) (Val v)))\n             (PClosure fenv env (Conf Prms (fst s) (snd s) (PS es))\n                                (Conf Prms w1 n1 (PS es'))) }.         \nProof.\n  intros.\n  dependent induction X.\n  - econstructor 1 with (x:=(w1,n1)).\n    split.\n    simpl.\n    econstructor.\n    simpl.\n    econstructor.\n  - destruct p2.\n    destruct qq.\n    destruct es0 as [| e1 es1].\n    inversion p.\n    inversion p; subst.\n    \n    specialize (IHX (Val v0) v es1 es' state w1 fuel n1 eq_refl eq_refl).\n    destruct IHX.\n    destruct p0.\n    destruct x.\n    \n    constructor 1 with (x:=(w0,n0)).\n    simpl in *.\n    inversion e; subst.\n    split.\n    constructor.\n    econstructor.\n    exact X0.\n    exact p0.\n\n    inversion X1.\n    \n    specialize (IHX e1 v es1 es' state w1 fuel n1 eq_refl eq_refl).\n    destruct IHX.\n    destruct p0.\n    destruct x.\n\n    constructor 1 with (x:=(w,n)).\n    simpl in *.\n    split.\n    econstructor.\n    exact X0.\n    exact e0.\n    exact p0.\nDefined.\n    \n    \nLemma prmsAux1\n      (ftenv: funTC) (tenv: valTC) (ps: Prms) (pt: PTyp) :  \n  forall (fenv: funEnv) (env: valEnv),                      \n    FEnvTyping fenv ftenv ->\n    EnvTyping env tenv ->\n    forall w: W * nat, \n    (sigT (fun (w': W * nat) => \n           sigT (fun (es: list Exp) => \n           prod (isValueListT es) \n           (prod (PClosure fenv env (Conf Prms (fst w) (snd w) ps)\n                                    (Conf Prms (fst w') (snd w') (PS es))) \n                 (PrmsTyping ftenv tenv (PS es) pt))))) ->       \n    (sigT (fun (w': W * nat) =>\n           sigT (fun (vs: list Value) => \n           prod (PClosure fenv env (Conf Prms (fst w) (snd w) ps)\n                            (Conf Prms (fst w') (snd w') (PS (map Val vs)))) \n                (PrmsTyping ftenv tenv (PS (map Val vs)) pt)))).\nProof.\n  intros.\n  destruct X as [n1 X].\n  destruct X as [es X].\n  destruct X as [X1 X2].\n  destruct X2 as [X2 X3].\n  exists n1.\n  eapply isValueList22_T in X1.\n  inversion X1.\n  destruct X1 as [vs].\n  constructor 1 with (x:=vs).\n  split.\n  - eapply PConcat.\n    eassumption.\n    inversion i; subst.\n    constructor.\n  - destruct pt.\n    inversion i; subst.\n    exact X3.\nDefined.    \n   \n\nLemma NoPrmsStep (fenv: funEnv) (env: valEnv)\n                  (w0 w1: W * nat) (es1 es2: list Exp):\n  PStep fenv env (Conf Prms (fst w0) (snd w0) (PS es1))\n                      (Conf Prms (fst w1) (snd w1) (PS es2)) ->\n   isValueListT es1 -> False.\nProof.\n  intros.\n  revert X0.\n  dependent induction X.\n  intros.\n  inversion X0; subst.\n  eapply IHX.\n  reflexivity.\n  reflexivity.\n  auto.\n  intro.\n  inversion X0; subst.\n  inversion X; subst.\n  inversion e0.\nDefined.\n\n\nLemma NoNilPrmsClos1 (fenv: funEnv) (env: valEnv)\n                  (s0 s1: W) (n0 n1: nat) (e: Exp) (es: list Exp):\n  PClosure fenv env (Conf Prms s0 n0 (PS (e::es)))\n                      (Conf Prms s1 n1 (PS nil)) -> False.\n  intros.\n  dependent induction X.\n  destruct p2.\n  destruct qq.\n  destruct es0.\n  inversion p.\n  specialize (IHX state s1 fuel n1 e0 es0 eq_refl eq_refl).\n  exact IHX.\nDefined.  \n\nLemma NoNilPrmsClos2 (fenv: funEnv) (env: valEnv)\n                  (s0 s1: W) (n0 n1: nat) (e: Exp) (es: list Exp):\n  PClosure fenv env (Conf Prms s0 n0 (PS nil))\n                      (Conf Prms s1 n1 (PS (e::es))) -> False.\n  intros.\n  dependent induction X.\n  destruct p2.\n  destruct qq.\n  destruct es0.\n  specialize (IHX state s1 fuel n1 e es eq_refl eq_refl).\n  exact IHX.\n  inversion p.\nDefined.  \n\n\n\n(************* from TSoundness ***************************************)\n(********************************************************************)\n\nProgram Definition ExtRelTyp (tenv : valTC) (x : Id)\n      (v : Value) (t : VTyp) (mB: valueVTyp v = t)\n       (env: valEnv) (m2: EnvTyping env tenv) (mA: findE env x = Some v) :\n   findE tenv x = Some t.  \n  unfold EnvTyping in m2.\n  unfold MatchEnvs in m2.\n  rewrite m2.\n  unfold thicken.\n  rewrite <- mB.\n  revert m2.\n  revert tenv.\n  induction env.\n  inversion mA.\n  intros tenv m2.\n  destruct a.\n  simpl in *.\n  destruct (IdT.IdEqDec x i).\n  injection mA; intro.\n  rewrite H.\n  reflexivity.\n  specialize (IHenv mA (map (thicken StaticSemL.Id valueVTyp) env) eq_refl).\n  exact IHenv.\nDefined. \n\n\n\nProgram Definition ExtRelVal2A {K V1 V2: Type} {h: DEq K} (f: V1 -> V2)\n       (tenv: Envr K V2) (venv: Envr K V1) (x: K) (t: V2): \n    MatchEnvs K f venv tenv ->\n    findE tenv x = Some t ->\n    sigT2 (fun v: V1 => findE venv x = Some v) (fun v: V1 => f v = t). \nProof.\n  unfold MatchEnvs.\n  unfold thicken.\n  intros.\n  rewrite H in H0.\n  clear H.\n  clear tenv.\n  induction venv.\n  simpl in *.\n  discriminate H0.\n  destruct a.\n  simpl in *.\n  destruct (dEq x k).\n  injection H0; intro.\n  clear H0.\n  constructor 1 with (x:=v).\n  reflexivity.\n  rewrite H in *.\n  reflexivity.\n  eapply IHvenv.\n  intuition n.\nDefined.  \n\n\nDefinition ExtRelVal2A_1 {K V1 V2: Type} {h: DEq K} (f: V1 -> V2)\n       (tenv: Envr K V2) (venv: Envr K V1) (x: K) (t: V2) \n    (k1: MatchEnvs K f venv tenv)\n    (k2: findE tenv x = Some t) : V1 :=\n   proj1_of_sigT2 (ExtRelVal2A f tenv venv x t k1 k2).\n\nDefinition ExtRelVal2A_2 {K V1 V2: Type} {h: DEq K} (f: V1 -> V2)\n       (tenv: Envr K V2) (venv: Envr K V1) (x: K) (t: V2) \n    (k1: MatchEnvs K f venv tenv)\n    (k2: findE tenv x = Some t) :\n  findE venv x = Some (ExtRelVal2A_1 f tenv venv x t k1 k2) :=\n  projT2 (fst_sigT_of_sigT2 (ExtRelVal2A f tenv venv x t k1 k2)).\n\nDefinition ExtRelVal2A_3 {K V1 V2: Type} {h: DEq K} (f: V1 -> V2)\n       (tenv: Envr K V2) (venv: Envr K V1) (x: K) (t: V2) \n    (k1: MatchEnvs K f venv tenv)\n    (k2: findE tenv x = Some t) : sigT (fun v: V1 => f v = t) :=\n  snd_sigT_of_sigT2 (ExtRelVal2A f tenv venv x t k1 k2). \n\nDefinition ExtRelVal2A_4 {K V1 V2: Type} {h: DEq K} (f: V1 -> V2)\n       (tenv: Envr K V2) (venv: Envr K V1) (x: K) (t: V2) \n    (k1: MatchEnvs K f venv tenv)\n    (k2: findE tenv x = Some t) :\n  f (ExtRelVal2A_1 f tenv venv x t k1 k2) = t :=\n  projT2 (snd_sigT_of_sigT2 (ExtRelVal2A f tenv venv x t k1 k2)). \n\n\nLemma TransformA_Var (P : valEnv -> Exp -> VTyp -> Type)\n      (Q : VTyp -> Type)\n      (F1 : forall (env: valEnv) (x: Id) (t: VTyp), P env (Var x) t -> Type)\n      (F2: forall t: VTyp, Q t -> Type)\n  : (forall (tenv : valTC) (x : Id)\n    (v : Value) \n    (t : VTyp) (i : findE tenv x = Some t) (mB: valueVTyp v = t)\n    (env: valEnv) (mA: findE env x = Some v)\n    (m2: EnvTyping env tenv), \n    (P env (Var x) t * Q t) ->\n     sigT (fun I: (P env (Var x) t * Q t) => \n             F1 env x t (fst I) = F2 t (snd I))) -> \n    forall (tenv : valTC) (x : Id) (t: VTyp)\n    (i : findE tenv x = Some t) \n    (env: valEnv) \n    (m2: EnvTyping env tenv), \n    (P env (Var x) t * Q t) ->\n     sigT (fun I: (P env (Var x) t * Q t) => \n             F1 env x t (fst I) = F2 t (snd I)).\nProof.\n  intros.\n  specialize (X tenv x (ExtRelVal2A_1 valueVTyp tenv env x t m2 i) t i\n         (ExtRelVal2A_4 valueVTyp tenv env x t m2 i)     \n         env                                          \n         (ExtRelVal2A_2 valueVTyp tenv env x t m2 i) \n         m2 X0).       \n  exact X.   \nDefined.\n\n\n(*****************************************************************)\n\n\nProgram Definition ExtRelVal2B \n       (env: valEnv) (x: Id) (t: VTyp): \n    findE (valEnv2valTC env) x = Some t ->\n    sigT2 (fun v: Value => findE env x = Some v)\n          (fun v: Value => projT1 v = t). \nProof.\n  induction env.\n  simpl in *.\n  intros.\n  discriminate H.\n  destruct a.\n  simpl in *.\n  destruct (IdT.IdEqDec x i).\n  intro.\n  injection H; intro.\n  constructor 1 with (x:=v).\n  reflexivity.\n  exact H0.\n  intro.\n  eapply IHenv.\n  exact H.\nDefined.  \n\nLemma ExtRelVal2B_ok (env: valEnv)\n    (x: Id) (t: VTyp) (v: Value) \n    (k1: findE (valEnv2valTC env) x = Some t)\n    (k2: findE env x = Some v) :\n  v = proj1_of_sigT2 (ExtRelVal2B env x t k1).\n  induction env.\n  inversion k1.\n  destruct a.\n  simpl in k1, k2.\n  simpl.\n  unfold ExtRelVal2B.\n  unfold proj1_of_sigT2.\n  unfold sigT_of_sigT2.\n  simpl.\n  destruct (IdT.IdEqDec x i).\n  inversion k2; subst.\n  reflexivity.\n  specialize (IHenv k1 k2).\n  rewrite IHenv.\n  reflexivity.\nDefined.\n\nLemma ExtRelVal2B_Typ_ok (env: valEnv)\n    (x: Id) (t: VTyp) (v: Value) \n    (k1: findE (valEnv2valTC env) x = Some t)\n    (k2: findE env x = Some v) :\n  (sVTyp (projT1 v)) =\n      sVTyp (projT1\n       (proj1_of_sigT2\n          (ExtRelVal2B env x t k1))).\n  rewrite (ExtRelVal2B_ok env x t v k1 k2).\n  reflexivity.\nDefined.  \n\nLemma ExtRelVal2B_TypS_ok (env: valEnv)\n    (x: Id) (t: VTyp) (v: Value) \n    (k1: findE (valEnv2valTC env) x = Some t)\n    (k2: findE env x = Some v) :\n    sVTyp (projT1\n       (proj1_of_sigT2\n          (ExtRelVal2B env x t k1))) =\n    (sVTyp (projT1 v)).\n  rewrite (ExtRelVal2B_ok env x t v k1 k2).\n  reflexivity.\nDefined.  \n\n\n\nDefinition ExtRelVal2B_1\n           (env: valEnv) (x: Id) (t: VTyp)\n           (k: findE (valEnv2valTC env) x = Some t) : Value :=\n proj1_of_sigT2 (ExtRelVal2B env x t k).\n  \nDefinition ExtRelVal2B_2\n           (env: valEnv) (x: Id) (t: VTyp)\n           (k: findE (valEnv2valTC env) x = Some t) :\n  findE env x = Some (ExtRelVal2B_1 env x t k) :=\n projT2 (fst_sigT_of_sigT2 (ExtRelVal2B env x t k)).\n\n\nDefinition ExtRelVal2B_3 (env: valEnv) (x: Id) (t: VTyp)\n           (k: findE (valEnv2valTC env) x = Some t) :\n    sigT (fun v: Value => valueVTyp v = t) :=\n snd_sigT_of_sigT2 (ExtRelVal2B env x t k).\n\n\nDefinition ExtRelVal2B_4\n           (env: valEnv) (x: Id) (t: VTyp)\n           (k: findE (valEnv2valTC env) x = Some t) :\n  valueVTyp (ExtRelVal2B_1 env x t k) = t :=\n projT2 (snd_sigT_of_sigT2 (ExtRelVal2B env x t k)).\n\n\nEnd DerivDyn.\n\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/DerivDynI1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.2841456813606196}}
{"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 A B C D Aprime Bprime Cprime Dprime X Y E Z Eprime : Universe, ((wd_ X A /\\ (wd_ X Aprime /\\ (wd_ X C /\\ (wd_ X Cprime /\\ (wd_ Y B /\\ (wd_ Y Bprime /\\ (wd_ Y D /\\ (wd_ Y Dprime /\\ (wd_ A C /\\ (wd_ B D /\\ (wd_ A Aprime /\\ (wd_ E Z /\\ (wd_ A D /\\ (wd_ D E /\\ (wd_ A E /\\ (wd_ X Y /\\ (wd_ X B /\\ (wd_ A Y /\\ (wd_ A B /\\ (wd_ B C /\\ (wd_ Bprime Cprime /\\ (wd_ Aprime Dprime /\\ (wd_ Aprime Bprime /\\ (col_ X A C /\\ (col_ X A Aprime /\\ (col_ X A Cprime /\\ (col_ Y B D /\\ (col_ Y B Bprime /\\ (col_ Y B Dprime /\\ (col_ E A B /\\ (col_ E C D /\\ (col_ X E Z /\\ (col_ A E Z /\\ (col_ Eprime Aprime Bprime /\\ (col_ Eprime E Z /\\ col_ E X A))))))))))))))))))))))))))))))))))) -> col_ A C E)).\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_1130.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.28410254223357523}}
{"text": "(******************************************************************************)\n(** * Proof of Power fairness for Power-consistent,                           *)\n(** * location- and thread-finite executions.                                 *)\n(******************************************************************************)\n\nFrom hahn Require Import Hahn.\nFrom ZornsLemma Require Classical_Wf. \nRequire Import Events.\nRequire Import Execution.\nRequire Import Execution_eco.\nRequire Import Power_fences.\nRequire Import Power_ppo.\nRequire Import Power.\nRequire Import imm_bob.\nRequire Import imm_ppo.\nRequire Import imm_hb.\nRequire Import imm_rfppo. \nRequire Import imm.\nRequire Import ImmFair.\nRequire Import FairExecution.\nRequire Import immToPower.\nRequire Import FinThreads.\nRequire Import Lia.\nRequire Import ClassicalChoice.\nRequire Import ChoiceFacts.\nRequire Import IndefiniteDescription. \nRequire Import AuxRel2.\nRequire Import Program.Basics.\nRequire Import EnumProperties.\nRequire Import HardwareFairness.\nRequire Import AuxDef.\nImport ListNotations. \n\nSet Implicit Arguments.\n\nSection immToPowerFairness.\n\nVariable G : execution.\n\nNotation \"'E'\" := (acts_set G).\nNotation \"'lab'\" := (lab G).\nNotation \"'sb'\" := (sb G).\nNotation \"'rf'\" := (rf G).\nNotation \"'co'\" := (co G).\nNotation \"'rmw'\" := (rmw G).\nNotation \"'data'\" := (data G).\nNotation \"'addr'\" := (addr G).\nNotation \"'ctrl'\" := (ctrl G).\nNotation \"'deps'\" := (deps G).\nNotation \"'rmw_dep'\" := (rmw_dep G).\n\nNotation \"'fre'\" := (fre G).\nNotation \"'rfe'\" := (rfe G).\nNotation \"'coe'\" := (coe G).\nNotation \"'rfi'\" := (rfi G).\nNotation \"'fri'\" := (fri G).\nNotation \"'coi'\" := (coi G).\nNotation \"'fr'\" := (fr G).\nNotation \"'eco'\" := (eco G).\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)).\nNotation \"'R_ex'\" := (fun a => is_true (R_ex lab a)).\nNotation \"'RW'\" := (R ∪₁ W).\nNotation \"'FR'\" := (F ∪₁ R).\nNotation \"'FW'\" := (F ∪₁ W).\nNotation \"'W_ex'\" := (W_ex G).\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 \"'loc'\" := (loc lab).\nNotation \"'val'\" := (val lab).\nNotation \"'mod'\" := (mod lab).\nNotation \"'same_loc'\" := (same_loc lab).\n\n\n(* power *)\nNotation \"'ctrli'\" := (ctrli G).\nNotation \"'sync'\" := (sync G).\nNotation \"'lwsync'\" := (lwsync G).\nNotation \"'fence'\" := (fence G).\nNotation \"'ppop'\" := (Power_ppo.ppo G).\nNotation \"'hbp'\" := (Power.hb G).\n(* Notation \"'S'\" := (S G). *)\nNotation \"'detour'\" := (detour G).\n\nNotation \"'F^isync'\" := (F ∩₁ (fun a => is_true (is_rlx lab a))).\nNotation \"'F^lwsync'\" := (F ∩₁ (fun a => is_true (is_ra lab a))).\nNotation \"'F^sync'\" := (F ∩₁ (fun a => is_true (is_sc lab a))).\n\nNotation \"'Tid_' t\" := (fun x => tid x = t) (at level 1).\nNotation \"'Loc_' l\" := (fun x => loc x = l) (at level 1).\n\nHypothesis SC_F: Sc ⊆₁ F∩₁Sc.\nHypothesis NO_W_REL : W∩₁Rel ≡₁ ∅.\nHypothesis R_ACQ_SB : ⦗R∩₁Acq⦘ ⨾ sb ⊆ rmw ∪ ctrl ⨾ ⦗F^isync⦘ ⨾ sb^? ∪ sb ⨾ ⦗F^lwsync⦘ ⨾ sb^?.\nHypothesis RMW_DEPS : rmw ⊆ ctrl ∪ data.\nHypothesis RMW_CTRL_FAIL : ⦗R_ex⦘ ⨾ sb ⊆ ctrl.\nHypothesis DATA_RMW : data ⨾ ⦗W_ex⦘ ⨾ sb ⊆ ctrl.\nHypothesis DEPS_RMW_FAIL : rmw_dep ⨾ (rmw ∪ ctrl) ⊆ ctrl.\n\nHypothesis CON: PowerConsistent G.\n\n\nLemma wf_hbpE:\n  hbp ≡ ⦗E⦘ ⨾ hbp ⨾ ⦗E⦘.\nProof using CON.\n  apply dom_helper_3. unfold \"hbp\".\n  rewrite Power_ppo.wf_ppoE, wf_fenceE, wf_rfeE; auto; try apply CON. \n  basic_solver.\nQed. \n\nLemma hb_po_loc_hb:\n  hbp⁺ ⨾ sb ∩ same_loc ⊆ hbp⁺. \nProof using CON. \nAdmitted. \n\nLemma exists_inf_thread (f: nat -> actid) (S: actid -> Prop) b \n      (IN_E: f ↑₁ set_full ⊆₁ E \\₁ is_init)\n      (INF: ~ set_finite (f ↓₁ S))\n      (FINTHREADS : threads_bound G b):\n    exists t, BinPos.Pos.lt t b /\\ ~ set_finite (f ↓₁ (S ∩₁ Tid_ t)).\nProof using. \n  apply set_infinite_bunion.\n  { exists (mk_list (Datatypes.S (BinPos.Pos.to_nat b)) BinPos.Pos.of_nat). intros.\n    apply in_mk_list_iff. eexists. split.\n    2: { symmetry. apply Pnat.Pos2Nat.id. }\n    red in IN. apply Pnat.Pos2Nat.inj_lt in IN. lia. }\n  intros FIN. destruct INF.\n  rewrite AuxRel2.set_bunion_separation with (fab := tid).\n  rewrite set_map_bunion. \n  rewrite AuxRel2.set_full_split with (S := flip BinPos.Pos.lt b).\n  rewrite set_bunion_union_l, set_finite_union. split; auto. \n  exists []. ins. unfolder in IN. desc. destruct IN. red. \n  rewrite <- IN1. apply FINTHREADS. apply IN_E. vauto.\nQed. \n\nLemma exists_inf_loc (f: nat -> actid) (S: actid -> Prop) locs\n      (IN_E: f ↑₁ set_full ⊆₁ E \\₁ is_init)\n      (INF: ~ set_finite (f ↓₁ S))\n      (FINLOCS: forall e (ENIe: (E \\₁ is_init) e), In (loc e) locs):\n    exists l, In l locs /\\ ~ set_finite (f ↓₁ (S ∩₁ Loc_ l)).\nProof using.\n  eapply set_infinite_bunion; [by vauto| ]. \n  intros FIN. destruct INF.\n  rewrite AuxRel2.set_bunion_separation with (fab := loc).\n  rewrite set_map_bunion.\n  rewrite AuxRel2.set_full_split with (S := fun l => In l locs).\n  rewrite set_bunion_union_l, set_finite_union. split; auto.\n  exists []. ins. unfolder in IN. desc.    \n  destruct IN. rewrite <- IN1. apply FINLOCS. apply IN_E. vauto.\nQed.\n  \n\nLemma fin_threads_locs_power_hb_ct_fsupp \n      (FINLOCS: exists locs, forall e (ENIe: (E \\₁ is_init) e), In (loc e) locs)\n      (FINTHREADS: exists b, threads_bound G b):\n  fsupp (⦗set_compl is_init⦘ ⨾ hbp^+). \nProof using CON.\n  desc. \n  assert (Wf G) as WF by apply CON. \n  rewrite clos_trans_domb_begin.\n  2: { rewrite no_hbp_to_init; basic_solver. }\n  apply AuxDef.fsupp_wf_implies_fsupp_ct.\n  2: { unfold \"hbp\".\n       rewrite Power_ppo.ppo_in_sb, fence_in_sb, unionK, rfe_in_rf; auto.\n       rewrite seq_union_r. apply fsupp_union.\n       { by apply fsupp_sb. }\n       eapply fsupp_mori; [| by apply fsupp_rf; eauto]. red. basic_solver. }\n\n  contra NWF. apply not_wf_inf_decr_enum in NWF as [f DECR].\n  assert (forall i, (transp hbp) (f i) (f (i + 1))) as DECR'.\n  { ins. red. eapply seq_eqv_l. eauto. }\n\n  assert (f ↑₁ set_full ⊆₁ E \\₁ is_init) as ENUM_E.\n  { intros e [i [_ Fie]].\n    specialize (DECR i). eapply same_relation_exp in DECR.\n    2: { rewrite no_hbp_to_init, wf_hbpE; auto. }\n    generalize DECR. subst e. basic_solver. }\n  \n  assert (~ set_finite (f ↓₁ W)) as INFW'.\n  { intros [iws FINW].\n    set (wb := list_max iws + 1).\n    assert (forall j (GE: j >= wb), sb (f (j + 1)) (f j)) as SB_STEPS.\n    { intros. specialize (DECR j). apply seq_eqv_l in DECR. desc.\n      unfold \"hbp\" in DECR0. eapply hahn_inclusion_exp in DECR0.\n      2: { rewrite Power_ppo.ppo_in_sb, fence_in_sb, unionK; auto. reflexivity. }\n      destruct DECR0; auto.\n      specialize (FINW (j + 1)). specialize_full FINW.\n      { apply wf_rfeD, seq_eqv_lr in H; auto. desc. vauto. }\n      apply In_gt_list_max in FINW; vauto. lia. }\n    \n    forward eapply fsupp_dom_enum with (f := fun k => f (wb + k))\n                                       (r := ⦗set_compl is_init⦘ ⨾ sb) as []. \n    { ins. apply seq_eqv_l. split.\n      { apply ENUM_E. vauto. }\n      rewrite PeanoNat.Nat.add_assoc. apply SB_STEPS. lia. }\n    { eapply acyclic_mori; [| by apply sb_acyclic]. red. basic_solver. }\n    eapply fsupp_mori; [| by apply fsupp_sb; eauto]. \n    red. rewrite inclusion_ct_seq_eqv_l.\n    rewrite ct_of_trans; vauto. apply sb_trans. }\n  \n  eapply exists_inf_thread in INFW' as [t [TBt INFt]]; eauto.\n\n  eapply exists_inf_loc in INFt as [ol [Ll INFtl]]; eauto. \n  destruct ol.\n  2: { destruct INFtl. exists []. unfolder. ins. desc.\n       forward eapply is_w_loc; eauto. ins. desc. vauto. }\n\n  eapply enum_order_contradiction with (r' := sb ∩ same_loc)\n                                       (S := (E \\₁ is_init) ∩₁ (W ∩₁ Tid_ t ∩₁ Loc_ (Some l))); eauto.\n  { intros FIN. destruct INFtl. eapply set_finite_mori; eauto.\n    red. rewrite set_map_inter with (d := _ \\₁ _).\n    apply set_subset_inter_r. split; [| basic_solver].\n    red. ins. red. red in H. apply ENUM_E. vauto. }\n  { red. ins. forward eapply sb_total with (a := a) (b := b0) (t := t) as SB;\n      try by (generalize IWa; generalize IWb; vauto || basic_solver). \n    unfolder in IWa. unfolder in IWb. desc. \n    des; [left | right]; split; congruence. }\n  { by apply CON. }\n  { by apply fsupp_sb_loc. }\n\n  apply hb_po_loc_hb.\nQed.\n\n\nEnd immToPowerFairness.\n", "meta": {"author": "weakmemory", "repo": "imm", "sha": "7942cc3f204cabca065b8fbf749323c398bc0973", "save_path": "github-repos/coq/weakmemory-imm", "path": "github-repos/coq/weakmemory-imm/imm-7942cc3f204cabca065b8fbf749323c398bc0973/src/hardware/PowerFairness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723317123102956, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2840632645836593}}
{"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\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 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.\nHint 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.\nHint 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.\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_incr.\nsemax_func_cons body_read.\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_lock_coupling.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2840632590357469}}
{"text": "Require Import Coq.Strings.String Coq.omega.Omega Coq.Lists.List Coq.Logic.FunctionalExtensionality Coq.Sets.Ensembles\n        Fiat.Common.List.ListFacts\n        Fiat.Computation\n        Fiat.Computation.Refinements.Iterate_Decide_Comp\n        Fiat.ADT\n        Fiat.ADTRefinement 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.Common.Ensembles.IndexedEnsembles\n        Fiat.QueryStructure.Specification.Operations.Query\n        Fiat.QueryStructure.Specification.Operations.Delete\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.QueryStructure.Implementation.Operations.General.MutateRefinements\n        Fiat.Common.Ensembles.EnsembleListEquivalence.\n\n(* Facts about implements delete operations. *)\n\nSection DeleteRefinements.\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  Local Transparent QSDelete.\n\n  Definition QSDeletedTuples\n             {qsSchema}\n             (qs : UnConstrQueryStructure qsSchema) Ridx\n             (DeletedTuples : Ensemble RawTuple) :=\n    (UnIndexedEnsembleListEquivalence\n       (Intersection _\n                     (GetUnConstrRelation qs Ridx)\n                     (Complement _ (EnsembleDelete (GetUnConstrRelation qs Ridx) DeletedTuples)))).\n\n  Lemma QSDeleteSpec_UnConstr_refine_AttributeConstraints :\n    forall qsSchema qs  Ridx\n           (DeletedTuples : Ensemble RawTuple)\n           or,\n      @DropQSConstraints_AbsR qsSchema or qs ->\n      refine\n        {b : bool |\n         (forall tup,\n            GetUnConstrRelation qs Ridx tup ->\n            SatisfiesAttributeConstraints Ridx (indexedElement tup)) ->\n         decides b\n                 (MutationPreservesAttributeConstraints\n                    (EnsembleDelete (GetRelation or Ridx) DeletedTuples)\n                    (SatisfiesAttributeConstraints Ridx))}\n        (ret true).\n  Proof.\n    unfold MutationPreservesAttributeConstraints; intros * AbsR_or_qs v Comp_v.\n    computes_to_econstructor; intros; computes_to_inv; subst; simpl; intros.\n    unfold DropQSConstraints_AbsR in *; eapply H; inversion H0; subst;\n    rewrite GetRelDropConstraints; eauto.\n  Qed.\n\n  Lemma QSDeleteSpec_UnConstr_refine_CrossConstraints' :\n    forall qsSchema qs  Ridx\n           (DeletedTuples : Ensemble RawTuple)\n           or,\n      @DropQSConstraints_AbsR qsSchema or qs ->\n  refine\n   {b : bool |\n   (forall Ridx',\n    Ridx' <> Ridx ->\n    forall tup',\n    GetUnConstrRelation qs Ridx tup' ->\n    SatisfiesCrossRelationConstraints Ridx Ridx' (indexedElement tup')\n      (GetUnConstrRelation qs Ridx')) ->\n   decides b\n     (forall Ridx',\n      Ridx' <> Ridx ->\n      MutationPreservesCrossConstraints\n        (EnsembleDelete (GetRelation or Ridx) DeletedTuples)\n        (GetUnConstrRelation qs Ridx')\n        (SatisfiesCrossRelationConstraints Ridx Ridx'))}\n   (ret true).\n  Proof.\n    unfold MutationPreservesCrossConstraints; intros * AbsR_or_qs v Comp_v.\n    computes_to_econstructor; intros;  computes_to_inv; subst; simpl; intros.\n    unfold DropQSConstraints_AbsR in *; eapply H; inversion H1; subst; eauto.\n    rewrite GetRelDropConstraints; eauto.\n  Qed.\n\n  Lemma QSDeleteSpec_UnConstr_refine_opt :\n    forall qsSchema qs Ridx DeletedTuples or,\n      @DropQSConstraints_AbsR qsSchema or qs ->\n      refine\n        (or' <- (QSDelete or Ridx DeletedTuples);\n         nr' <- {nr' | DropQSConstraints_AbsR (fst or') nr'};\n         ret (nr', snd or'))\n        match (tupleConstraints (GetNRelSchema (qschemaSchemas qsSchema) Ridx)) with\n          | 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                                                  (EnsembleDelete (GetRelation or Ridx) DeletedTuples)\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                                                  (EnsembleDelete (GetRelation or Ridx) DeletedTuples)\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              match tupleConstr, crossConstr with\n                | true, true =>\n                  deleted  <- Pick (QSDeletedTuples qs Ridx DeletedTuples);\n                    ret (UpdateUnConstrRelation qs Ridx (EnsembleDelete (GetUnConstrRelation qs Ridx) DeletedTuples), deleted)\n                | _, _  => ret (qs, [])\n              end\n          | 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                                                  (EnsembleDelete (GetRelation or Ridx) DeletedTuples)\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 with\n                | true  =>\n                  deleted   <- Pick (QSDeletedTuples qs Ridx DeletedTuples);\n                    ret (UpdateUnConstrRelation qs Ridx (EnsembleDelete (GetUnConstrRelation qs Ridx) DeletedTuples), deleted)\n                | _ => ret (qs, [])\n            end\n        end.\n  Proof.\n    unfold QSDelete.\n    intros; rewrite QSMutateSpec_UnConstr_refine;\n    eauto using\n          QSDeleteSpec_UnConstr_refine_AttributeConstraints,\n    refine_SatisfiesTupleConstraintsMutate,\n    refine_SatisfiesCrossConstraintsMutate,\n    QSDeleteSpec_UnConstr_refine_CrossConstraints'.\n    simplify with monad laws.\n    unfold SatisfiesTupleConstraints.\n    case_eq (tupleConstraints (GetNRelSchema (qschemaSchemas qsSchema) Ridx)); intros;\n    [eapply refine_under_bind; intros\n    | simplify with monad laws].\n    simpl; unfold DropQSConstraints_AbsR, QSDeletedTuples in *; subst.\n    f_equiv; unfold pointwise_relation; intros;\n    repeat find_if_inside; try simplify with monad laws; try reflexivity.\n    rewrite GetRelDropConstraints, get_update_unconstr_eq; f_equiv.\n    f_equiv; unfold pointwise_relation; intros; eauto.\n    simpl; unfold DropQSConstraints_AbsR, QSDeletedTuples in *; subst.\n    repeat find_if_inside; try simplify with monad laws; try reflexivity.\n    rewrite GetRelDropConstraints, get_update_unconstr_eq; f_equiv.\n  Qed.\n\n  Lemma EnsembleComplementIntersection {A}\n  : forall E (P : Ensemble A),\n      DecideableEnsemble P\n      -> forall (a : @IndexedElement A),\n           (In _ (Intersection _ E\n                               (Complement _ (EnsembleDelete E P))) a\n            <-> In _ (Intersection _ E\n                                   (fun itup => P (indexedElement itup))) a).\n  Proof.\n    unfold EnsembleDelete, Complement, In in *; intuition;\n    destruct H; constructor; eauto; unfold In in *.\n    - case_eq (DecideableEnsembles.dec (indexedElement x)); intros.\n      + eapply dec_decides_P; eauto.\n      + exfalso; apply H0; constructor; unfold In; eauto.\n        intros H'; apply dec_decides_P in H'; congruence.\n    - intros H'; destruct H'; unfold In in *; eauto.\n  Qed.\n\n  Lemma DeletedTuplesIntersection {qsSchema}\n  : forall qs Ridx (P : Ensemble RawTuple),\n      DecideableEnsemble P\n      -> refine {x | @QSDeletedTuples qsSchema qs Ridx P x}\n                {x | UnIndexedEnsembleListEquivalence\n                       (Intersection _ (GetUnConstrRelation qs Ridx)\n                                     (fun itup => P (indexedElement itup))) x}.\n  Proof.\n    intros qs Ridx P P_dec v Comp_v;  computes_to_inv.\n    computes_to_constructor.\n    unfold QSDeletedTuples, UnIndexedEnsembleListEquivalence in *; destruct_ex;\n    intuition; subst.\n    eexists; intuition.\n    unfold EnsembleListEquivalence in *; intuition; eauto with typeclass_instances.\n    + eapply H; eapply EnsembleComplementIntersection; eauto with typeclass_instances.\n    + eapply EnsembleComplementIntersection; eauto with typeclass_instances.\n      eapply H; eauto.\n  Qed.\n\n  Definition UpdateUnConstrRelationDeleteC {qsSchema} (qs : UnConstrQueryStructure qsSchema) Ridx DeletedTuples :=\n    ret (UpdateUnConstrRelation qs Ridx (EnsembleDelete (GetUnConstrRelation qs Ridx) DeletedTuples)).\n\n  Lemma QSDeleteSpec_refine_subgoals ResultT :\n    forall qsSchema (qs : QueryStructure qsSchema) qs' Ridx\n           default success\n           refined_schConstr refined_qsConstr\n           (DeletedTuples : Ensemble RawTuple)\n           (k : _ -> Comp ResultT),\n      DropQSConstraints_AbsR qs qs'\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                                     (EnsembleDelete (GetUnConstrRelation qs' Ridx) DeletedTuples)\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 BuildQueryStructureConstraints qsSchema Ridx' Ridx with\n                                        | Some CrossConstr =>\n                                          Some\n                                            (MutationPreservesCrossConstraints (GetUnConstrRelation qs' Ridx')\n                                                                               (EnsembleDelete (GetUnConstrRelation qs' Ridx) DeletedTuples)\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      -> (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 <-> EnsembleDelete (GetRelation qs Ridx) DeletedTuples t)\n             -> QSDeletedTuples qs' Ridx DeletedTuples mutated\n             -> refine (k (qs'', mutated))\n                       (success qs''' mutated))\n      -> refine (k (qs, [ ])) default\n      -> refine\n           (qs' <- QSDelete qs Ridx DeletedTuples; k qs')\n           ( schConstr <- refined_schConstr;\n             qsConstr <- refined_qsConstr;\n             match schConstr, qsConstr with\n             | true, true =>\n               mutated  <- Pick (QSDeletedTuples qs' Ridx DeletedTuples);\n                 qs'' <- UpdateUnConstrRelationDeleteC qs' Ridx DeletedTuples;\n                 success qs'' mutated\n             | _, _ => default\n             end).\n  Proof.\n    intros.\n    unfold QSDelete.\n    rewrite QSMutateSpec_refine_subgoals' with (refined_schConstr_self := ret true)\n                                                (refined_qsConstr' := ret true);\n      try first [eassumption | reflexivity ].\n    simplify with monad laws.\n    repeat (f_equiv; unfold pointwise_relation; intros).\n    rewrite <- H0, <- (GetRelDropConstraints qs Ridx), <- H.\n    rewrite refine_SatisfiesTupleConstraintsMutate; eauto.\n    destruct (tupleConstraints (GetNRelSchema (qschemaSchemas qsSchema) Ridx));\n    f_equiv.\n    rewrite refine_SatisfiesCrossConstraintsMutate; eauto.\n    rewrite <- (GetRelDropConstraints qs Ridx).\n    rewrite <- H1, H; f_equiv.\n    repeat find_if_inside.\n    unfold QSDeletedTuples.\n    f_equiv.\n    rewrite <- (GetRelDropConstraints qs Ridx).\n    unfold GetUnConstrRelation, UpdateUnConstrRelation.\n    rewrite ilist2.ith_replace2_Index_eq, <- H; reflexivity.\n    unfold UpdateUnConstrRelationDeleteC, UpdateUnConstrRelationMutateC;\n    rewrite <- H, GetRelDropConstraints; reflexivity.\n    reflexivity.\n    reflexivity.\n    eauto using QSDeleteSpec_UnConstr_refine_AttributeConstraints.\n    eauto using QSDeleteSpec_UnConstr_refine_CrossConstraints'.\n    intros; eapply H2; eauto.\n    unfold QSDeletedTuples.\n    unfold GetUnConstrRelation, UpdateUnConstrRelation in H7.\n    rewrite ilist2.ith_replace2_Index_eq in H7.\n    rewrite <- GetRelDropConstraints, H in H7; eauto.\n  Qed.\n\n  Local Transparent Query_For.\n\n  Lemma DeletedTuplesFor {qsSchema}\n  : forall qs Ridx P,\n      DecideableEnsemble P\n      -> refine {x | @QSDeletedTuples qsSchema qs Ridx P x}\n                (For (UnConstrQuery_In qs Ridx\n                                       (fun tup => Where (P tup) Return tup))).\n  Proof.\n    intros qs Ridx P P_dec v Comp_v; rewrite DeletedTuplesIntersection by auto.\n    computes_to_constructor.\n    unfold UnIndexedEnsembleListEquivalence.\n    unfold Query_For in *.\n    computes_to_inv.\n    destruct Comp_v as [l [Perm_l_v Comp_v] ].\n    unfold UnConstrQuery_In, QueryResultComp in *;  computes_to_inv.\n    remember (GetUnConstrRelation qs Ridx); clear Heqi.\n    revert P_dec i v v0 Perm_l_v Comp_v Comp_v'; clear; induction l; simpl; intros.\n    - apply Return_inv in Comp_v; subst.\n      eexists nil; simpl; split; eauto.\n      rewrite Permutation_nil by eauto; reflexivity.\n      + unfold EnsembleListEquivalence in *; intuition.\n        * destruct H; intuition.\n          apply Pick_inv in Perm_l_v; inversion Perm_l_v.\n          unfold In in *; intuition; subst.\n          apply H1 in H.\n          eapply (@FlattenCompList.flatten_CompList_nil _ P x0); eauto.\n          destruct x0; simpl in *; try discriminate; computes_to_econstructor.\n        * constructor.\n    - apply Pick_inv in Perm_l_v.\n       unfold UnConstrRelation in i.\n       destruct Perm_l_v as [ [ | [a' x'] ] [x_eq [equiv_u_x' NoDup_x'] ] ].\n       destruct l; simpl in *; try discriminate.\n       unfold In in Comp_v; pose (Bind_inv Comp_v); destruct_ex; intuition; subst; computes_to_inv; subst.\n       simpl in x_eq; injections.\n      case_eq (@DecideableEnsembles.dec _ P P_dec a); intros.\n      + apply Pick_inv in H0; intuition.\n        apply dec_decides_P in H2. apply H3 in H2.\n        apply Return_inv in H2; simpl in *; subst; simpl in *.\n        pose proof (PermutationConsSplit _ _ _ Comp_v'); destruct_ex; subst.\n        unfold UnIndexedEnsembleListEquivalence in *.\n        destruct (H (fun x => i x /\\ x <> {|indexedElement := a; elementIndex := a' |}) (app x x0) v1); intuition eauto.\n        apply PickComputes.\n        computes_to_inv; injections.\n        eexists _; intuition eauto.\n        unfold In in *; intuition.\n        rewrite equiv_u_x' in H2; destruct H2; subst; eauto; congruence.\n        unfold In; intuition.\n        apply equiv_u_x'; simpl; intuition.\n        inversion NoDup_x'; subst; eauto.\n        apply H7; apply in_map_iff; eexists; split; eauto; simpl; eauto.\n        inversion NoDup_x'; subst; eauto.\n        eapply Permutation_cons_inv; rewrite Permutation_middle; eassumption.\n        * symmetry in H2; pose proof (app_map_inv _ _ _ _ H2); destruct_ex;\n          intuition; subst.\n          eexists (app x2 ({|indexedElement := a; elementIndex := a' |} :: x3));\n            simpl; rewrite map_app.\n          { simpl; intuition; computes_to_inv; injections.\n            - destruct H5; unfold In in *; apply equiv_u_x' in H5; simpl in *; intuition.\n              apply in_or_app; simpl; eauto.\n              assert (i x) as u_x by (apply equiv_u_x'; eauto).\n              assert (List.In x (x2 ++ x3)) as In_x by\n                    (apply H0; constructor; unfold In; intuition; subst;\n                inversion NoDup_x'; subst; eapply H10; apply in_map_iff; eexists;\n                split; cbv beta; simpl; eauto; reflexivity).\n              apply in_or_app; simpl; apply in_app_or in In_x; intuition.\n            - unfold In.\n              assert (List.In x (x2 ++ x3) \\/ x = {|indexedElement := a; elementIndex := a' |})\n                as In_x0\n                  by (apply in_app_or in H5; simpl in H5; intuition).\n              intuition.\n              + apply H0 in H7; destruct H7; unfold In in *; intuition.\n                constructor; eauto.\n              + subst; constructor; eauto.\n                apply equiv_u_x'; simpl; eauto.\n                case_eq (@DecideableEnsembles.dec _ P P_dec a); intros.\n                apply dec_decides_P; eauto.\n                assert (~ P a) as H''\n                    by (unfold not; intros H'; apply dec_decides_P in H'; congruence);\n                apply H4 in H''; discriminate.\n            - rewrite map_app; apply NoDup_app_swap; simpl; constructor; eauto.\n              inversion NoDup_x'; subst; unfold not; intros; apply H8.\n              rewrite <- map_app in H5; apply in_map_iff in H5; destruct_ex; intuition.\n              assert (List.In x (x2 ++ x3)) as In_a by\n                    (apply in_or_app; apply in_app_or in H10; intuition).\n              apply H0 in In_a; destruct In_a; unfold In in *; intuition.\n              apply equiv_u_x' in H12; simpl in *; intuition.\n              destruct x; simpl in *; subst.\n              apply in_map_iff; eexists; split; eauto; simpl; eauto.\n              apply NoDup_app_swap; rewrite <- map_app; eauto.\n          }\n      + unfold Query_Where, Query_Return in H0;\n        computes_to_inv; intuition.\n        assert (~ P a) as H''\n            by (unfold not; intros H'; apply dec_decides_P in H'; congruence\n        ).\n        apply H4 in H''; subst; simpl in *; subst.\n        destruct (H (fun x => i x /\\ x <> {|indexedElement := a; elementIndex := a' |}) v v1); intuition eauto.\n        * computes_to_econstructor.\n          eexists; intuition; eauto.\n          unfold In in *; intuition.\n          apply equiv_u_x' in H5; destruct H5; subst; eauto.\n          congruence.\n          unfold In; intuition.\n          unfold In; intuition.\n          subst.\n          apply equiv_u_x'; simpl; intuition.\n          inversion NoDup_x'; subst; eauto.\n          apply H8; apply in_map_iff; eexists; split; eauto; simpl; eauto.\n          inversion NoDup_x'; subst; eauto.\n        * unfold In.\n          eexists; split; eauto.\n          unfold UnIndexedEnsembleListEquivalence in *; intuition.\n          destruct H6; intuition.\n          eapply H0; constructor; unfold In in *; subst; intuition.\n          subst; apply_in_hyp dec_decides_P; simpl in *; congruence.\n          constructor;\n            apply H0 in H6; destruct H6; unfold In in *; intuition.\n  Qed.\n\nEnd DeleteRefinements.\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/DeleteRefinements.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.28406325348783446}}
{"text": "Require Import Hask.Prelude.\nRequire Import Hask.Ltac.\nRequire Import Hask.Data.Functor.Identity.\nRequire Import Hask.Data.Functor.Kan.\nRequire Import Hask.Control.Monad.\n\nGeneralizable All Variables.\nSet Primitive Projections.\nSet Universe Polymorphism.\nUnset Transparent Obligations.\nSet Asymmetric Patterns.\n\nDefinition Yoneda (f : Type -> Type) (a : Type) :=\n  forall r : Type, (a -> r) -> f r.\n\n(* #[export] *)\n(* Instance Yoneda_lemma `{Functor f} : forall a, Yoneda f a ≅ f a := { *)\n(*   iso_to   := fun x => x _ id; *)\n(*   iso_from := fun x _ k => fmap k x *)\n(* }. *)\n\n#[export]\nInstance Yoneda_Functor {f : Type -> Type} : Functor (Yoneda f) := {\n  fmap := fun _ _ g k _ h => k _ (h \\o g)\n}.\n\n#[export]\nInstance Yoneda_Applicative `{Applicative f} :\n  Applicative (Yoneda f) := {\n  pure := fun _ x => fun _ k => pure (k x);\n  ap   := fun a b g x => fun _ k => g _ (comp k) <*> x _ id\n}.\n\nDefinition Yoneda_join `{Monad m} `(k : Yoneda m (Yoneda m a)) : Yoneda m a :=\n  fun _ h => join (k _ (fun y => y _ h)).\n\n#[export]\nInstance Yoneda_Monad `{Monad m} : Monad (Yoneda m) := {\n  join := @Yoneda_join m _\n}.\n\nRequire Import FunctionalExtensionality.\n\nModule YonedaLaws.\n\n(* Include IsomorphismLaws. *)\nInclude MonadLaws.\n\n(* Parametricity theorem. *)\nCorollary Yoneda_parametricity : forall `{Functor f} a b c (k : Yoneda f a)\n  (g : b -> c) (h : a -> b), fmap g (k _ h) = k _ (g \\o h).\nProof.\n  intros.\n  pose proof (@Ran_parametricity a b c Identity _ f _).\n  simpl in H0.\n  unfold id in H0.\nAdmitted.\n(* jww (2017-04-24): Universe inconsistency in Coq 8.6 *)\n(*\n  apply (H0 k g h).\nQed.\n*)\n\n(* #[export] *)\n(* Program Instance Yoneda_lemma `{FunctorLaws f} : *)\n(*   forall a, @IsomorphismLaws (Yoneda f a) (f a) (Yoneda_lemma a). *)\n(* Obligation 1. *)\n(*   extensionality x. *)\n(*   simpl. *)\n(*   extensionality r. *)\n(*   extensionality g. *)\n(*   apply Yoneda_parametricity. *)\n(* Qed. *)\n(* Obligation 2. *)\n(*   extensionality x. *)\n(*   unfold comp. *)\n(*   rewrite fmap_id. *)\n(*   reflexivity. *)\n(* Qed. *)\n\n#[export]\nProgram Instance Yoneda_FunctorLaws {f : Type -> Type} : FunctorLaws (Yoneda f).\n\n#[export]\nProgram Instance Yoneda_ApplicativeLaws `{ApplicativeLaws f} :\n  ApplicativeLaws (Yoneda f).\nObligation 1.\n  extensionality x.\n  extensionality r.\n  extensionality k0.\n  rewrite ap_fmap, <- fmap_comp, fmap_id.\n  unfold comp, id.\n  apply Yoneda_parametricity.\nQed.\nObligation 2.\n  extensionality r.\n  extensionality k.\n  rewrite <- ap_comp; f_equal.\n  repeat rewrite ap_fmap; f_equal.\n  repeat rewrite Yoneda_parametricity; f_equal.\nQed.\nObligation 3.\n  extensionality r.\n  extensionality k.\n  rewrite ap_fmap.\n  unfold comp.\n  rewrite <- fmap_comp_x.\n  repeat rewrite fmap_pure_x.\n  reflexivity.\nQed.\nObligation 4.\n  extensionality r.\n  extensionality k.\n  rewrite ap_fmap, <- fmap_comp, ap_interchange.\n  unfold comp.\n  rewrite ap_fmap.\n  repeat rewrite Yoneda_parametricity.\n  f_equal.\nQed.\nObligation 5.\n  extensionality k.\n  extensionality r.\n  extensionality g.\n  rewrite ap_fmap, <- fmap_comp_x.\n  unfold comp.\n  repeat rewrite Yoneda_parametricity.\n  f_equal.\nQed.\n\n#[export]\nProgram Instance Yoneda_MonadLaws `{MonadLaws m} : MonadLaws (Yoneda m).\nObligation 1.\n  extensionality k.\n  unfold Yoneda_join.\n  extensionality r.\n  extensionality h.\n  simpl.\n  rewrite <- join_fmap_join_x, Yoneda_parametricity.\n  reflexivity.\nQed.\nObligation 2.\n  extensionality k.\n  unfold Yoneda_join.\n  extensionality r.\n  extensionality h.\n  unfold comp.\n  replace (fun x : a => pure[m] (h x)) with (pure[m] \\o h).\n    rewrite <- Yoneda_parametricity.\n    rewrite join_fmap_pure_x.\n    reflexivity.\n  reflexivity.\nQed.\nObligation 3.\n  extensionality k.\n  unfold Yoneda_join.\n  extensionality r.\n  extensionality h.\n  unfold comp.\n  rewrite join_pure_x.\n  reflexivity.\nQed.\n\nEnd YonedaLaws.\n\n(**************************************************************************)\n\n(* The contravariant Yoneda lemma, made applicable to covariant functors by\n   changing it from a universally quantified function to an existentially\n   quantified construction of two arguments. *)\n\nInductive Coyoneda (f : Type -> Type) (a : Type) :=\n  COYO : forall x, (x -> a) -> f x -> Coyoneda f a.\n\nArguments COYO {f a x} _ _.\n\nDefinition liftCoyoneda {f : Type -> Type} {a : Type} : f a -> Coyoneda f a :=\n  COYO id.\n\nDefinition lowerCoyoneda `{Functor f} {a : Type} (c : Coyoneda f a) : f a :=\n  match c with COYO _ g h => fmap g h end.\n\n#[export]\nInstance Coyoneda_Functor (f : Type -> Type) : Functor (Coyoneda f) := {\n  fmap := fun _ _ f x => match x with COYO _ g h => COYO (f \\o g) h end\n}.\n\nRequire Import FunctionalExtensionality.\n\nModule CoyonedaLaws.\n\nInclude FunctorLaws.\n\n#[export]\nProgram Instance Coyoneda_FunctorLaws (f : Type -> Type) :\n  FunctorLaws (Coyoneda f).\nObligation 1. extensionality x. destruct x; reflexivity. Qed.\nObligation 2. extensionality x. destruct x; reflexivity. Qed.\n\nTheorem coyo_to `{FunctorLaws f} : forall a (x : f a),\n  lowerCoyoneda (liftCoyoneda x) = x.\nProof.\n  intros a x.\n  unfold lowerCoyoneda, liftCoyoneda.\n  rewrite fmap_id.\n  reflexivity.\nQed.\n\nTheorem coyo_lower_naturality `{FunctorLaws f} : forall a b (g : a -> b),\n  fmap g \\o lowerCoyoneda (f:=f) = lowerCoyoneda \\o fmap g.\nProof.\n  intros a b k.\n  extensionality x.\n  destruct x as [x g h]; simpl.\n  rewrite fmap_comp_x.\n  reflexivity.\nQed.\n\nAxiom coyo_parametricity : forall `{FunctorLaws f} a b (g : a -> b),\n  COYO g = COYO id \\o fmap g.\n\nTheorem coyo_lift_naturality `{FunctorLaws f} : forall a b (g : a -> b),\n  fmap g \\o liftCoyoneda (f:=f) = liftCoyoneda \\o fmap g.\nProof.\n  intros a b g.\n  unfold liftCoyoneda.\n  extensionality x.\n  simpl.\n  replace (g \\o id) with g; auto.\n  rewrite coyo_parametricity.\n  reflexivity.\nQed.\n\nTheorem coyo_from `{FunctorLaws f} : forall a (x : Coyoneda f a),\n  liftCoyoneda (lowerCoyoneda x) = x.\nProof.\n  intros a [x g h].\n  unfold lowerCoyoneda.\n  replace (liftCoyoneda ((fmap[f] g) h)) with ((liftCoyoneda \\o (fmap[f] g)) h).\n    rewrite <- coyo_lift_naturality.\n    reflexivity.\n  reflexivity.\nQed.\n\nEnd CoyonedaLaws.\n", "meta": {"author": "jwiegley", "repo": "coq-haskell", "sha": "56a185af5767177d410113a03bd765135e07c9ca", "save_path": "github-repos/coq/jwiegley-coq-haskell", "path": "github-repos/coq/jwiegley-coq-haskell/coq-haskell-56a185af5767177d410113a03bd765135e07c9ca/src/Data/Functor/Yoneda.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.2840421274806909}}
{"text": "(*\n  This file showcases the use of packages.\n *)\n\n\nFrom Coq Require Import Utf8.\nSet Warnings \"-ambiguous-paths,-notation-overridden,-notation-incompatible-format\".\nFrom mathcomp Require Import ssrnat ssreflect ssrfun ssrbool ssrnum eqtype choice seq.\nSet Warnings \"ambiguous-paths,notation-overridden,notation-incompatible-format\".\nFrom extructures Require Import ord fset fmap.\nFrom Crypt Require Import RulesStateProb Package Prelude.\nImport PackageNotation.\n\nFrom Equations Require Import Equations.\nRequire Equations.Prop.DepElim.\n\n\nSet Bullet Behavior \"Strict Subproofs\".\nSet Default Goal Selector \"!\".\nSet Primitive Projections.\n\n#[local] Open Scope package_scope.\n\nDefinition I0 : Interface :=\n  [interface #val #[3] : 'nat → 'nat].\n\nDefinition I1 : Interface :=\n  [interface\n    #val #[0] : 'bool → 'bool ;\n    #val #[1] : 'nat → 'unit ;\n    #val #[2] : 'unit → 'bool\n  ].\n\nDefinition I2 : Interface :=\n  [interface\n    #val #[4] : 'bool × 'bool → 'bool\n  ].\n\nDefinition pempty : package fset0 [interface] [interface] :=\n  [package].\n\nDefinition p0 : package fset0 [interface] I0 :=\n  [package\n    #def #[3] (x : 'nat) : 'nat {\n      ret x\n    }\n  ].\n\nDefinition p1 : package fset0 [interface] I1 :=\n  [package\n    #def #[0] (z : 'bool) : 'bool {\n      ret z\n    } ;\n    #def #[1] (y : 'nat) : 'unit {\n      ret Datatypes.tt\n    } ;\n    #def #[2] (u : 'unit) : 'bool {\n      ret false\n    }\n  ].\n\nDefinition foo (x : bool) : code fset0 [interface] bool_choiceType :=\n  {code let u := x in ret u}.\n\nDefinition bar (b : bool) : code fset0 [interface] nat_choiceType :=\n  {code if b then ret 0 else ret 1}.\n\nDefinition p2 : package fset0 [interface] I2 :=\n  [package\n    #def #[4] (x : 'bool × 'bool) : 'bool {\n      let '(u,v) := x in ret v\n    }\n  ].\n\nDefinition test₁ :\n  package\n    [fset (chNat; 0)]\n    [interface #val #[0] : 'nat → 'nat]\n    [interface\n      #val #[1] : 'nat → 'nat ;\n      #val #[2] : 'unit → 'unit\n    ]\n  :=\n  [package\n    #def #[1] (x : 'nat) : 'nat {\n      getr ('nat; 0) (λ n : nat,\n        opr (0, ('nat, 'nat)) n (λ m,\n          putr ('nat; 0) m (ret m)\n        )\n      )\n    } ;\n    #def #[2] (_ : 'unit) : 'unit {\n      putr ('nat; 0) 0 (ret Datatypes.tt)\n    }\n  ].\n\nDefinition sig := {sig #[0] : 'nat → 'nat }.\n\n#[program] Definition test₂ :\n  package\n    [fset ('nat; 0)]\n    [interface #val #[0] : 'nat → 'nat ]\n    [interface\n      #val #[1] : 'nat → 'nat ;\n      #val #[2] : 'unit → 'option ('fin 2) ;\n      #val #[3] : {map 'nat → 'nat} → 'option 'nat\n    ]\n  :=\n  [package\n    #def #[1] (x : 'nat) : 'nat {\n      n ← get ('nat ; 0) ;;\n      m ← op sig ⋅ n ;;\n      n ← get ('nat ; 0) ;;\n      m ← op sig ⋅ n ;;\n      #put ('nat ; 0) := m ;;\n      ret m\n    } ;\n    #def #[2] (_ : 'unit) : 'option ('fin 2) {\n      #put ('nat ; 0) := 0 ;;\n      ret (Some (gfin 1))\n    } ;\n    #def #[3] (m : {map 'nat → 'nat}) : 'option 'nat {\n      ret (getm m 0)\n    }\n  ].\n\n(* Testing the #import notation *)\nDefinition test₃ :\n  package\n    fset0\n    [interface\n      #val #[0] : 'nat → 'bool ;\n      #val #[1] : 'bool → 'unit\n    ]\n    [interface\n      #val #[2] : 'nat → 'nat ;\n      #val #[3] : 'bool × 'bool → 'bool\n    ]\n  :=\n  [package\n    #def #[2] (n : 'nat) : 'nat {\n      #import {sig #[0] : 'nat → 'bool } as f ;;\n      #import {sig #[1] : 'bool → 'unit } as g ;;\n      b ← f n ;;\n      if b then\n        g false ;;\n        ret 0\n      else ret n\n    } ;\n    #def #[3] ('(b₀,b₁) : 'bool × 'bool) : 'bool {\n      ret b₀\n    }\n  ].\n\n(** Information is redundant between the export interface and the package\n    definition, so it can safely be skipped.\n*)\nDefinition test₄ : package fset0 [interface] _ :=\n  [package\n    #def #[ 0 ] (n : 'nat) : 'nat {\n      ret (n + n)%N\n    } ;\n    #def #[ 1 ] (b : 'bool) : 'nat {\n      if b then ret 0 else ret 13\n    }\n  ].\n\nDefinition ℓ : Location := ('nat ; 0).\n\n#[tactic=notac] Equations? foo : code fset0 [interface] 'nat :=\n  foo := {code\n    n ← get ℓ ;;\n    ret n\n  }.\nProof.\n  ssprove_valid.\nAbort.\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/examples/package_usage_example.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.2840421198068635}}
{"text": "(*\n * Copyright (c) 2009-2011, Andrew Appel, Robert Dockins and Aquinas Hobor.\n *\n *)\n\nRequire Import VST.msl.base.\n\nSet Implicit Arguments.\n\nModule CovariantFunctor.\n\nRecord functorFacts (PS : Type -> Type)\n  (fmap : forall A B (f : A -> B), PS A -> PS B) : Type :=\nFunctorFacts {\n  ff_id : forall A, fmap _ _ (id A) = id (PS A);\n  ff_comp : forall A B C (f : B -> C) (g : A -> B),\nfmap _ _ f oo fmap _ _ g = fmap _ _ (f oo g)\n}.\n\nRecord functor : Type := Functor {\n  _functor: Type -> Type;\n  fmap : forall A B (f : A -> B), _functor A -> _functor B;\n  functor_facts : functorFacts _functor fmap\n}.\n\nEnd CovariantFunctor.\n\nModule ContraVariantFunctor.\n\nRecord functorFacts (PS : Type -> Type)\n  (fmap : forall A B (f : B -> A), PS A -> PS B) : Type :=\nFunctorFacts {\n  ff_id : forall A, fmap _ _ (id A) = id (PS A);\n  ff_comp : forall A B C (f : C -> B) (g : B -> A),\nfmap _ _ f oo fmap _ _ g = fmap _ _ (g oo f)\n}.\n\nRecord functor : Type := Functor {\n  _functor: Type -> Type;\n  fmap : forall A B (f : B -> A), _functor A -> _functor B;\n  functor_facts : functorFacts _functor fmap\n}.\n\nEnd ContraVariantFunctor.\n\nModule MixVariantFunctor.\n\nRecord functorFacts (PS : Type -> Type)\n (fmap : forall A B (f1 : A -> B) (f2 : B -> A), PS A -> PS B) : Type :=\nFunctorFacts {\n  ff_id : forall A, fmap _ _ (id A) (id A) = id (PS A);\n  ff_comp : forall A B C (f1 : B -> C) (f2 : C -> B) (g1 : A -> B)\n(g2 : B -> A), fmap _ _ f1 f2 oo fmap _ _ g1 g2 = fmap _ _ (f1 oo g1) (g2 oo f2)\n}.\n\nRecord functor : Type := Functor {\n  _functor: Type -> Type;\n  fmap : forall A B (f1 : A -> B) (f2 : B -> A), _functor A -> _functor B;\n  functor_facts : functorFacts _functor fmap\n}.\n\nEnd MixVariantFunctor.\n\nModule CovariantBiFunctor.\n\nRecord functorFacts (PS : Type -> Type -> Type)\n (fmap : forall A1 B1 A2 B2 (f1 : A1 -> B1) (f2 : A2 -> B2),\n    PS A1 A2 -> PS B1 B2) : Type :=\nFunctorFacts {\n  ff_id : forall A1 A2, fmap _ _ _ _ (id A1) (id A2) = id (PS A1 A2);\n  ff_comp : forall A1 A2 B1 B2 C1 C2 (f1 : B1 -> C1) (f2 : B2 -> C2)\n(g1 : A1 -> B1) (g2 : A2 -> B2),\n  fmap _ _ _ _ f1 f2 oo fmap _ _ _ _ g1 g2 = fmap _ _ _ _ (f1 oo g1) (f2 oo g2)\n}.\n\nRecord functor : Type := Functor {\n  _functor: Type -> Type -> Type;\n  fmap : forall A1 B1 A2 B2 (f1 : A1 -> B1) (f2 : A2 -> B2),\n    _functor A1 A2 -> _functor B1 B2;\n  functor_facts : functorFacts _functor fmap\n}.\n\nEnd CovariantBiFunctor.\n\nModule CoContraVariantBiFunctor.\n\nRecord functorFacts (PS : Type -> Type -> Type)\n (fmap : forall A1 B1 A2 B2 (f1 : A1 -> B1) (f2 : B2 -> A2),\n    PS A1 A2 -> PS B1 B2) : Type :=\nFunctorFacts {\n  ff_id : forall A1 A2, fmap _ _ _ _ (id A1) (id A2) = id (PS A1 A2);\n  ff_comp : forall A1 A2 B1 B2 C1 C2 (f1 : B1 -> C1) (f2 : C2 -> B2)\n(g1 : A1 -> B1) (g2 : B2 -> A2),\n  fmap _ _ _ _ f1 f2 oo fmap _ _ _ _ g1 g2 = fmap _ _ _ _ (f1 oo g1) (g2 oo f2)\n}.\n\nRecord functor : Type := Functor {\n  _functor: Type -> Type -> Type;\n  fmap : forall A1 B1 A2 B2 (f1 : A1 -> B1) (f2 : B2 -> A2),\n    _functor A1 A2 -> _functor B1 B2;\n  functor_facts : functorFacts _functor fmap\n}.\n\nEnd CoContraVariantBiFunctor.\n\nCoercion CovariantFunctor._functor:\n  CovariantFunctor.functor >-> Funclass.\nCoercion ContraVariantFunctor._functor:\n  ContraVariantFunctor.functor >-> Funclass.\nCoercion MixVariantFunctor._functor:\n  MixVariantFunctor.functor >-> Funclass.\nCoercion CovariantBiFunctor._functor:\n  CovariantBiFunctor.functor >-> Funclass.\nCoercion CoContraVariantBiFunctor._functor:\n  CoContraVariantBiFunctor.functor >-> Funclass.\n\nModule CovariantFunctorLemmas.\n\nImport CovariantFunctor.\n\nLemma fmap_id {F: functor} : forall A, fmap F (id A) = id (F A).\nProof. intros. destruct F as [F FM [ff_id ?]]; simpl. apply ff_id. Qed.\n\nLemma fmap_comp {F: functor} : forall A B C (f : B -> C) (g : A -> B),\n  fmap F f oo fmap F g = fmap F (f oo g).\nProof. intros. destruct F as [F FM [? ff_comp]]; simpl. apply ff_comp. Qed.\n\nLemma fmap_app {F: functor} : forall A B C (f : B -> C) (g : A -> B) x,\n  fmap F f (fmap F g x) = fmap F (f oo g) x.\nProof. intros. rewrite <- fmap_comp; auto. Qed.\n\nEnd CovariantFunctorLemmas.\n\nModule ContraVariantFunctorLemmas.\n\nImport ContraVariantFunctor.\n\nLemma fmap_id {F: functor} : forall A, fmap F (id A) = id (F A).\nProof. intros. destruct F as [F FM [ff_id ?]]; simpl. apply ff_id. Qed.\n\nLemma fmap_comp {F: functor} : forall A B C (f : C -> B) (g : B -> A),\n  fmap F f oo fmap F g = fmap F (g oo f).\nProof. intros. destruct F as [F FM [? ff_comp]]; simpl. apply ff_comp. Qed.\n\nLemma fmap_app {F: functor} : forall A B C (f : C -> B) (g : B -> A) x,\n  fmap F f (fmap F g x) = fmap F (g oo f) x.\nProof. intros. rewrite <- fmap_comp; auto. Qed.\n\nEnd ContraVariantFunctorLemmas.\n\nModule MixVariantFunctorLemmas.\n\nImport MixVariantFunctor.\n\nLemma fmap_id {F: functor} : forall A, fmap F (id A) (id A) = id (F A).\nProof. intros. destruct F as [F FM [ff_id ?]]; simpl. apply ff_id. Qed.\n\nLemma fmap_comp {F: functor} : forall A B C (f1 : B -> C) (f2: C -> B)\n(g1 : A -> B) (g2: B -> A),\n  fmap F f1 f2 oo fmap F g1 g2 = fmap F (f1 oo g1) (g2 oo f2).\nProof. intros. destruct F as [F FM [? ff_comp]]; simpl. apply ff_comp. Qed.\n\nLemma fmap_app {F: functor} : forall A B C (f1 : B -> C) (f2: C -> B)\n(g1 : A -> B) (g2: B -> A) x,\n  fmap F f1 f2 (fmap F g1 g2 x) = fmap F (f1 oo g1) (g2 oo f2) x.\nProof. intros. rewrite <- fmap_comp; auto. Qed.\n\nEnd MixVariantFunctorLemmas.\n\nModule CovariantBiFunctorLemmas.\n\nImport CovariantBiFunctor.\n\nLemma fmap_id {F: functor} : forall A1 A2, fmap F (id A1) (id A2) = id (F A1 A2).\nProof. intros. destruct F as [F FM [ff_id ?]]; simpl. apply ff_id. Qed.\n\nLemma fmap_comp {F: functor} : forall A1 A2 B1 B2 C1 C2 (f1 : B1 -> C1)\n(f2: B2 -> C2) (g1 : A1 -> B1) (g2: A2 -> B2),\n  fmap F f1 f2 oo fmap F g1 g2 = fmap F (f1 oo g1) (f2 oo g2).\nProof. intros. destruct F as [F FM [? ff_comp]]; simpl. apply ff_comp. Qed.\n\nLemma fmap_app {F: functor} : forall A1 A2 B1 B2 C1 C2 (f1 : B1 -> C1)\n(f2: B2 -> C2) (g1 : A1 -> B1) (g2: A2 -> B2) x,\n  fmap F f1 f2 (fmap F g1 g2 x) = fmap F (f1 oo g1) (f2 oo g2) x.\nProof. intros. rewrite <- fmap_comp; auto. Qed.\n\nEnd CovariantBiFunctorLemmas.\n\nModule CoContraVariantBiFunctorLemmas.\n\nImport CoContraVariantBiFunctor.\n\nLemma fmap_id {F: functor} : forall A1 A2, fmap F (id A1) (id A2) = id (F A1 A2).\nProof. intros. destruct F as [F FM [ff_id ?]]; simpl. apply ff_id. Qed.\n\nLemma fmap_comp {F: functor} : forall A1 A2 B1 B2 C1 C2 (f1 : B1 -> C1)\n(f2: C2 -> B2) (g1 : A1 -> B1) (g2: B2 -> A2),\n  fmap F f1 f2 oo fmap F g1 g2 = fmap F (f1 oo g1) (g2 oo f2).\nProof. intros. destruct F as [F FM [? ff_comp]]; simpl. apply ff_comp. Qed.\n\nLemma fmap_app {F: functor} : forall A1 A2 B1 B2 C1 C2 (f1 : B1 -> C1)\n(f2: C2 -> B2) (g1 : A1 -> B1) (g2: B2 -> A2) x,\n  fmap F f1 f2 (fmap F g1 g2 x) = fmap F (f1 oo g1) (g2 oo f2) x.\nProof. intros. rewrite <- fmap_comp; auto. Qed.\n\nEnd CoContraVariantBiFunctorLemmas.\n\nModule GeneralFunctorGenerator.\n\nDefinition CovariantFunctor_MixVariantFunctor (F: CovariantFunctor.functor):\n  MixVariantFunctor.functor.\n  refine (@MixVariantFunctor.Functor\n   (fun T => F T)\n   (fun A B f _ => CovariantFunctor.fmap F f) _).\n  constructor; intros; simpl.\n  + apply CovariantFunctor.ff_id, CovariantFunctor.functor_facts.\n  + apply CovariantFunctor.ff_comp, CovariantFunctor.functor_facts.\nDefined.\n\nDefinition ContraVariantFunctor_MixVariantFunctor\n (F: ContraVariantFunctor.functor):\n  MixVariantFunctor.functor.\n  refine (@MixVariantFunctor.Functor\n   (fun T => F T)\n   (fun A B _ f => ContraVariantFunctor.fmap F f) _).\n  constructor; intros; simpl.\n  + apply ContraVariantFunctor.ff_id, ContraVariantFunctor.functor_facts.\n  + apply ContraVariantFunctor.ff_comp, ContraVariantFunctor.functor_facts.\nDefined.\n\nDefinition CovariantFunctor_CoContraVariantBiFunctor\n (F: CovariantFunctor.functor):\n  CoContraVariantBiFunctor.functor.\n  refine (@CoContraVariantBiFunctor.Functor\n   (fun T1 T2 => F T1)\n   (fun A B C D f _ => CovariantFunctor.fmap F f) _).\n  constructor; intros; simpl.\n  + apply CovariantFunctor.ff_id, CovariantFunctor.functor_facts.\n  + apply CovariantFunctor.ff_comp, CovariantFunctor.functor_facts.\nDefined.\n\nDefinition CoContraVariantBiFunctor_MixVariantFunctor\n (F: CoContraVariantBiFunctor.functor):\n  MixVariantFunctor.functor.\n  refine (@MixVariantFunctor.Functor\n   (fun T => F T T)\n   (fun A B f g => CoContraVariantBiFunctor.fmap F f g) _).\n  constructor; intros; simpl.\n  + apply CoContraVariantBiFunctor.ff_id,\n          CoContraVariantBiFunctor.functor_facts.\n  + apply CoContraVariantBiFunctor.ff_comp,\n          CoContraVariantBiFunctor.functor_facts.\nDefined.\n\nDefinition CovariantFunctor_CovariantFunctor_compose\n(F1 F2: CovariantFunctor.functor):\n  CovariantFunctor.functor.\n  refine (@CovariantFunctor.Functor\n   (fun T => F1 (F2 T))\n   (fun A B f => CovariantFunctor.fmap F1 (CovariantFunctor.fmap F2 f)) _).\n  constructor; intros; simpl.\n  + rewrite !CovariantFunctorLemmas.fmap_id; auto.\n  + rewrite !CovariantFunctorLemmas.fmap_comp; auto.\nDefined.\n\nDefinition CovariantFunctor_MixVariantFunctor_compose\n(F1: CovariantFunctor.functor) (F2: MixVariantFunctor.functor):\n  MixVariantFunctor.functor.\n  refine (@MixVariantFunctor.Functor\n   (fun T => F1 (F2 T))\n   (fun A B f g => CovariantFunctor.fmap F1 (MixVariantFunctor.fmap F2 f g)) _).\n  constructor; intros; simpl.\n  + rewrite MixVariantFunctorLemmas.fmap_id, CovariantFunctorLemmas.fmap_id; auto.\n  + rewrite !CovariantFunctorLemmas.fmap_comp, MixVariantFunctorLemmas.fmap_comp; auto.\nDefined.\n\nDefinition CovariantBiFunctor_CovariantFunctor_compose\n(F: CovariantBiFunctor.functor)\n(F1 F2: CovariantFunctor.functor):\n  CovariantFunctor.functor.\n  refine (@CovariantFunctor.Functor\n   (fun T => F (F1 T) (F2 T))\n   (fun A B f => CovariantBiFunctor.fmap F\n      (CovariantFunctor.fmap F1 f) (CovariantFunctor.fmap F2 f)) _).\n  constructor; intros; simpl.\n  + rewrite !CovariantFunctorLemmas.fmap_id, CovariantBiFunctorLemmas.fmap_id; auto.\n  + rewrite CovariantBiFunctorLemmas.fmap_comp, !CovariantFunctorLemmas.fmap_comp; auto.\nDefined.\n\nDefinition CovariantBiFunctor_MixVariantFunctor_compose\n(F: CovariantBiFunctor.functor)\n(F1 F2: MixVariantFunctor.functor):\n  MixVariantFunctor.functor.\n  refine (@MixVariantFunctor.Functor\n   (fun T => F (F1 T) (F2 T))\n   (fun A B f g => CovariantBiFunctor.fmap F\n      (MixVariantFunctor.fmap F1 f g) (MixVariantFunctor.fmap F2 f g)) _).\n  constructor; intros; simpl.\n  + rewrite !MixVariantFunctorLemmas.fmap_id, CovariantBiFunctorLemmas.fmap_id; auto.\n  + rewrite CovariantBiFunctorLemmas.fmap_comp, !MixVariantFunctorLemmas.fmap_comp; auto.\nDefined.\n\nDefinition CoContraVariantBiFunctor_CoContraVariantFunctor_compose\n(F: CoContraVariantBiFunctor.functor)\n(F1: CovariantFunctor.functor)\n(F2: ContraVariantFunctor.functor):\n  CovariantFunctor.functor.\n  refine (@CovariantFunctor.Functor\n   (fun T => F (F1 T) (F2 T))\n   (fun A B f => CoContraVariantBiFunctor.fmap F\n      (CovariantFunctor.fmap F1 f) (ContraVariantFunctor.fmap F2 f)) _).\n  constructor; intros; simpl.\n  + rewrite CovariantFunctorLemmas.fmap_id, ContraVariantFunctorLemmas.fmap_id, CoContraVariantBiFunctorLemmas.fmap_id; auto.\n  + rewrite CoContraVariantBiFunctorLemmas.fmap_comp, CovariantFunctorLemmas.fmap_comp, ContraVariantFunctorLemmas.fmap_comp; auto.\nDefined.\n\nDefinition CoContraVariantBiFunctor_MixVariantFunctor_compose\n(F: CoContraVariantBiFunctor.functor)\n(F1 F2: MixVariantFunctor.functor):\n  MixVariantFunctor.functor.\n  refine (@MixVariantFunctor.Functor\n   (fun T => F (F1 T) (F2 T))\n   (fun A B f g => CoContraVariantBiFunctor.fmap F\n      (MixVariantFunctor.fmap F1 f g) (MixVariantFunctor.fmap F2 g f)) _).\n  constructor; intros; simpl.\n  + rewrite !MixVariantFunctorLemmas.fmap_id, CoContraVariantBiFunctorLemmas.fmap_id; auto.\n  + rewrite CoContraVariantBiFunctorLemmas.fmap_comp, !MixVariantFunctorLemmas.fmap_comp; auto.\nDefined.\n\nEnd GeneralFunctorGenerator.\n\nModule CovariantBiFunctorGenerator.\n\nImport CovariantBiFunctor.\nImport CovariantBiFunctorLemmas.\n\nDefinition Fpair: functor.\n  refine (@Functor\n   (fun T1 T2 => prod T1 T2)\n   (fun _ _ _ _ f1 f2 x => (f1 (fst x), f2 (snd x))) _).\n  constructor; intros; simpl; auto.\n  extensionality p; destruct p as [a1 a2]; simpl; auto.\nDefined.\n\nDefinition Fchoice: functor.\n  refine (@Functor\n   (fun T1 T2 => sum T1 T2)\n   (fun _ _ _ _ f1 f2 x =>\n      match x with\n      | inl x => inl (f1 x)\n      | inr x => inr (f2 x)\n      end) _).\n  constructor; intros; simpl.\n  + extensionality c.\n    destruct c; auto.\n  + extensionality c.\n    destruct c; unfold compose; simpl; auto.\nDefined.\n\nEnd CovariantBiFunctorGenerator.\n\nModule CoContraVariantBiFunctorGenerator.\n\nImport CoContraVariantBiFunctor.\nImport CoContraVariantBiFunctorLemmas.\n\nDefinition Ffunc: functor.\n  refine (@Functor\n   (fun T1 T2 => T2 -> T1)\n   (fun _ _ _ _ f1 f2 x => fun a => f1 (x (f2 a))) _).\n  constructor; intros; simpl; auto.\nDefined.\n\nEnd CoContraVariantBiFunctorGenerator.\n\nModule CovariantFunctorGenerator.\n\nImport CovariantFunctor.\nImport CovariantFunctorLemmas.\n\nDefinition fconst (T : Type): functor.\n  refine (@Functor (fun _ => T) (fun _ _ _ x => x) _).\n  constructor; intros; auto.\nDefined.\n\nDefinition fidentity: functor.\n  refine (@Functor (fun T => T) (fun _ _ f => f) _).\n  constructor; intros; auto.\nDefined.\n\nDefinition Foption: functor.\n  refine (@Functor (fun T => option T)\n   (fun _ _ f x => match x with Some x0 => Some (f x0) | _ => None end) _).\n  constructor; intros; simpl; auto.\n  + extensionality x; destruct x; auto.\n  + extensionality x; destruct x; auto.\nDefined.\n\nDefinition Flist: functor.\n  refine (@Functor (fun T => list T)\n   (fun _ _ f x => map f x) _).\n  constructor; intros; simpl; auto.\n  + extensionality x; apply map_id.\n  + extensionality x; apply map_map.\nDefined.\n\nDefinition fpair (F1 F2: functor): functor :=\n  GeneralFunctorGenerator.CovariantBiFunctor_CovariantFunctor_compose\n  CovariantBiFunctorGenerator.Fpair\n  F1\n  F2.\n\nGoal forall (F1 F2: functor) (T: Type), fpair F1 F2 T = prod (F1 T) (F2 T).\nreflexivity.\nQed.\n\nDefinition fchoice (F1 F2: functor): functor :=\n  GeneralFunctorGenerator.CovariantBiFunctor_CovariantFunctor_compose\n  CovariantBiFunctorGenerator.Fchoice\n  F1\n  F2.\n\nDefinition foption (F: functor): functor :=\n  GeneralFunctorGenerator.CovariantFunctor_CovariantFunctor_compose\n  Foption\n  F.\n\nDefinition flist (F: functor): functor :=\n  GeneralFunctorGenerator.CovariantFunctor_CovariantFunctor_compose\n  Flist\n  F.\n\nGoal forall (F : functor) (T: Type), foption F T = option (F T).\nreflexivity.\nQed.\n\nDefinition ffunc (F1: ContraVariantFunctor.functor) (F2: functor): functor :=\n  GeneralFunctorGenerator.CoContraVariantBiFunctor_CoContraVariantFunctor_compose\n  CoContraVariantBiFunctorGenerator.Ffunc\n  F2\n  F1.\n\nGoal forall (F1 : ContraVariantFunctor.functor) (F2: functor) (T: Type),\n  ffunc F1 F2 T = (F1 T -> F2 T).\nreflexivity.\nQed.\n\nDefinition fsig {I: Type} (F: I -> functor): functor.\n  refine (@Functor\n   (fun T => @sigT I (fun i => F i T))\n   (fun _ _ f x => match x with existT _ i x0 => existT _ i (fmap (F i) f x0) end) _).\n  constructor; intros; simpl.\n  + extensionality p; destruct p as [i a]; simpl.\n    rewrite !fmap_id; auto.\n  + extensionality p; destruct p as [i a]; simpl.\n    unfold compose at 1. rewrite !fmap_app; auto.\nDefined.\n\nDefinition fsubset (F: functor) (P: forall A, F A -> Prop)\n  (Pfmap: forall A B (f: A -> B) x, P A x -> P B (fmap F f x)): functor.\n  refine (@Functor\n   (fun T => {x: F T | P T x})\n   (fun _ _ f x =>\n      match x with exist _ x' H => exist _ (fmap F f x')\n                                           (Pfmap _ _ f x' H) end) _).\n  constructor; intros; simpl.\n  + extensionality x; destruct x as [x ?H].\n    apply exist_ext.\n    rewrite !fmap_id; auto.\n  + extensionality x; destruct x as [x ?H].\n    apply exist_ext.\n    rewrite !fmap_app; auto.\nDefined.\n\nEnd CovariantFunctorGenerator.\n\nModule MixVariantFunctorGenerator.\n\nImport MixVariantFunctor.\nImport MixVariantFunctorLemmas.\n\nDefinition fconst (T : Type): functor :=\n  GeneralFunctorGenerator.CovariantFunctor_MixVariantFunctor\n  (CovariantFunctorGenerator.fconst T).\n\nDefinition fidentity: functor :=\n  GeneralFunctorGenerator.CovariantFunctor_MixVariantFunctor\n  CovariantFunctorGenerator.fidentity.\n\nDefinition fpair (F1 F2: functor): functor :=\n  GeneralFunctorGenerator.CovariantBiFunctor_MixVariantFunctor_compose\n  CovariantBiFunctorGenerator.Fpair\n  F1\n  F2.\n\nDefinition fchoice (F1 F2: functor): functor :=\n  GeneralFunctorGenerator.CovariantBiFunctor_MixVariantFunctor_compose\n  CovariantBiFunctorGenerator.Fchoice\n  F1\n  F2.\n\nDefinition foption (F: functor): functor :=\n  GeneralFunctorGenerator.CovariantFunctor_MixVariantFunctor_compose\n  CovariantFunctorGenerator.Foption\n  F.\n\nDefinition flist (F: functor): functor :=\n  GeneralFunctorGenerator.CovariantFunctor_MixVariantFunctor_compose\n  CovariantFunctorGenerator.Flist\n  F.\n\nDefinition ffunc (F1 F2: functor): functor :=\n  GeneralFunctorGenerator.CoContraVariantBiFunctor_MixVariantFunctor_compose\n  CoContraVariantBiFunctorGenerator.Ffunc\n  F2\n  F1.\n\nDefinition fsig {I: Type} (F: I -> functor): functor.\n  refine (@Functor\n   (fun T => @sigT I (fun i => F i T))\n   (fun _ _ f g x => match x with existT _ i x0 => existT _ i (fmap (F i) f g x0) end) _).\n  constructor; intros; simpl.\n  + extensionality p; destruct p as [i a]; simpl.\n    rewrite !fmap_id; auto.\n  + extensionality p; destruct p as [i a]; simpl.\n    unfold compose at 1. rewrite !fmap_app; auto.\nDefined.\n\nDefinition fpi {I: Type} (F: I -> functor): functor.\n  refine (@Functor\n   (fun T => forall i: I, F i T)\n   (fun _ _ f g x => fun i => fmap (F i) f g (x i)) _).\n  constructor; intros; simpl.\n  + extensionality p i; simpl.\n    rewrite !fmap_id; auto.\n  + extensionality p i; simpl.\n    unfold compose at 1. rewrite !fmap_app; auto.\nDefined.\n\nDefinition fsubset (F: functor) (P: forall A, F A -> Prop)\n  (Pfmap: forall A B f g x, P A x -> P B (fmap F f g x)): functor.\n  refine (@Functor\n   (fun T => {x: F T | P T x})\n   (fun _ _ f g x =>\n      match x with exist _ x' H => exist _ (fmap F f g x')\n                                           (Pfmap _ _ f g x' H) end) _).\n  constructor; intros; simpl.\n  + extensionality x; destruct x as [x ?H].\n    apply exist_ext.\n    rewrite !fmap_id; auto.\n  + extensionality x; destruct x as [x ?H].\n    apply exist_ext.\n    rewrite !fmap_app; auto.\nDefined.\n\nEnd MixVariantFunctorGenerator.\n\nUnset Implicit Arguments.\n\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/msl/functors.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521307073646, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.28404211934607626}}
{"text": "(** Separation logic. *)\n\nFrom Coq Require Import ZArith Lia Bool List Program.Equality.\nFrom Coq Require Import FunctionalExtensionality PropExtensionality.\nFrom CDF Require Import Sequences Separation.\n\nLocal Open Scope Z_scope.\n\n(** * 1. A language of pointers *)\n\n(** We now define a small programming language to work with pointers to\n    mutable state.  The language has variables, but these variables are\n    immutable.  This in unlike IMP but like ML: mutable variables are\n    expressed as immutable pointers (references) to mutable state. *)\n\n(** As in ML too, we blur the distinction between expressions and commands.\n    Every command returns a value, which we take to be an integer,\n    in addition to possibly performing effects. *)\n\n(** We use higher-order abstract syntax to represent commands in this\n    language.  With first-order abstract syntax, a \"let\" binding\n    [let x = a in b] would be represented using the constructor \n<<\n    LET: forall (x: ident) (a b: com), com\n>>\n    With higher-order syntax, we use a Coq function [fun x => b] to\n    represent the binding of [x] inside [b]:\n<<\n    LET: forall (a: com) (b: Z -> com), com\n>>\n    As a benefit, we can use any Coq expression of type [Z] as a\n    pure command of the language, making it unnecessary to define\n    syntax and semantics for a specific expression language.\n*)\n\nCoInductive com: Type :=\n  | PURE (x: Z)                         (**r command without effects *)\n  | LET (c: com) (f: Z -> com)          (**r sequencing of commands *)\n  | IFTHENELSE (b: Z) (c1 c2: com)      (**r conditional *)\n  | ALLOC (sz: nat)                     (**r allocate [sz] words of storage *)\n  | GET (l: addr)                       (**r dereference a pointer *)\n  | SET (l: addr) (v: Z)                (**r assign through a pointer *)\n  | FREE (l: addr)                      (**r free one word of storage *)\n  | PICK (n: Z).                        (**r pick a number between 0 and [n] *)\n\n(** Some derived forms. *)\n\nDefinition SKIP: com := PURE 0.\n\nDefinition SEQ (c1 c2: com) := LET c1 (fun _ => c2).\n\nDefinition EITHER (c1 c2: com) := LET (PICK 2) (fun n => IFTHENELSE n c1 c2).\n\n(** Reduction semantics. *)\n\nInductive red: com * heap -> com * heap -> Prop :=\n  | red_pick: forall n i h,\n      0 <= i < n ->\n      red (PICK n, h) (PURE i, h)\n  | red_let_done: forall x f h,\n      red (LET (PURE x) f, h) (f x, h)\n  | red_let_step: forall c f h c' h',\n      red (c, h) (c', h') ->\n      red (LET c f, h) (LET c' f, h')\n  | red_ifthenelse: forall b c1 c2 h,\n      red (IFTHENELSE b c1 c2, h) ((if b =? 0 then c2 else c1), h)\n  | red_alloc: forall sz (h: heap) l,\n      (forall i, l <= i < l + Z.of_nat sz -> h i = None) ->\n      l <> 0 ->\n      red (ALLOC sz, h) (PURE l, hinit l sz h)\n  | red_get: forall l (h: heap) v,\n      h l = Some v ->\n      red (GET l, h) (PURE v, h)\n  | red_set: forall l v (h: heap),\n      h l <> None ->\n      red (SET l v, h) (SKIP, hupdate l v h)\n  | red_free: forall l (h: heap),\n      h l <> None ->\n      red (FREE l, h) (SKIP, hfree l h).\n\n(** Absence of run-time errors. [immsafe c h] holds if [c / h] is not\n    going to abort immediately on a run-time error, such as dereferencing \n    an invalid pointer. *)\n\nInductive immsafe: com * heap -> Prop :=\n  | immsafe_pure: forall v h,\n      immsafe (PURE v, h)\n  | immsafe_let: forall c f h,\n      immsafe (c, h) -> immsafe (LET c f, h)\n  | immsafe_ifthenelse: forall b c1 c2 h,\n      immsafe (IFTHENELSE b c1 c2, h)\n  | immsafe_alloc: forall sz (h: heap) l,\n      l <> 0 -> (forall i, l <= i < l + Z.of_nat sz -> h i = None) ->\n      immsafe (ALLOC sz, h)\n  | immsafe_get: forall l (h: heap),\n      h l <> None -> immsafe (GET l, h)\n  | immsafe_set: forall l v (h: heap),\n      h l <> None -> immsafe (SET l v, h)\n  | immsafe_free: forall l (h: heap),\n      h l <> None -> immsafe (FREE l, h)\n  | immsafe_pick: forall n h,\n      immsafe (PICK n, h).\n\n(** * 2.  The rules of separation logic *)\n\nDefinition precond := assertion.\nDefinition postcond := Z -> assertion.\n\n(** ** 2.1.  Semantic definition of strong triples *)\n\n(** Instead of axiomatizing the rules of separation logic, then prove\n    their soundness against the operational semantics, we define\n    triples [ ⦃ P ⦄ c ⦃ Q ⦄ ] directly in terms of the\n    operational semantics, then show the rules of separation logic as\n    lemmas about these semantic triples.\n\n    Note: the way triples are defined below, they are strong triples\n    that guarantee termination.  However, we write them with braces\n    instead of brackets, for consistency with the third lecture\n    and with the literature on separation logic.\n *)\n\n(** [safe c h Q] holds if [c] started in [h] always terminates without errors,\n    and when it terminates with value [v], the postcondition [Q v] holds\n    of the final heap. *)\n\nInductive safe: com -> heap -> postcond -> Prop :=\n  | safe_done: forall v h (Q: postcond),\n      Q v h ->\n      safe (PURE v) h Q\n  | safe_step: forall c h Q,\n      match c with PURE _ => False | _ => True end ->\n      immsafe (c, h) ->\n      (forall c' h', red (c, h) (c', h') -> safe c' h' Q) ->\n      safe c h Q.\n\n(** We define semantic triples like we did for Hoare logic: *)\n\nDefinition triple (P: precond) (c: com) (Q: postcond) :=\n  forall h, P h -> safe c h Q.\n\nNotation \"⦃ P ⦄ c ⦃ Q ⦄\" := (triple P c Q) (at level 90, c at next level).\n\n(** ** 2.2. The frame rule *)\n\n(** The frame rule is valid because the operational semantics has nice\n    properties with respect to heap extension: if a command is safe\n    in a small heap, it is safe in a bigger heap, and any reduction\n    from the bigger heap is simulated by a reduction from the smaller heap. *)\n\nLtac inv H := inversion H; clear H; subst.\n\nLemma immsafe_frame: forall h' c h,\n  immsafe (c, h) -> hdisjoint h h' -> immsafe (c, hunion h h').\nProof.\n  intros h' c h IMM; dependent induction IMM; intros DISJ.\n- constructor.\n- constructor; auto.\n- constructor.\n- destruct (isfinite (hunion h h')) as [l' FIN].\n  apply immsafe_alloc with (Z.max 1 l').\n  lia.\n  intros. apply FIN. lia.\n- constructor. cbn. destruct (h l); congruence. \n- constructor. cbn. destruct (h l); congruence. \n- constructor. cbn. destruct (h l); congruence. \n- constructor.\nQed.\n\nLemma red_frame: forall h2 c h1 c' h',\n  red (c, hunion h1 h2) (c', h') ->\n  immsafe (c, h1) ->\n  hdisjoint h1 h2 ->\n  exists h1', red (c, h1) (c', h1') /\\ hdisjoint h1' h2 /\\ h' = hunion h1' h2.\nProof.\n  intros until h'; intros RED; dependent induction RED; intros IMM DISJ; inv IMM.\n- exists h1; intuition auto. constructor; auto.\n- exists h1; intuition auto. constructor; auto.\n- edestruct IHRED as (h1' & R & D & U); eauto.\n  exists h1'; intuition auto. constructor; auto.\n- exists h1; intuition auto. constructor; auto.\n- exists (hinit l sz h1); intuition auto.\n  + constructor; auto. intros. apply H in H1. cbn in H1. destruct (h1 i); congruence.\n  + red; cbn; intros i.\n    assert (EITHER: l <= i < l + Z.of_nat sz \\/ (i < l \\/ l + Z.of_nat sz <= i)) by lia.\n    destruct EITHER.\n    * right. apply H in H1. cbn in H1. destruct (h1 i), (h2 i); congruence.\n    * rewrite hinit_outside by auto. apply DISJ.\n  + apply heap_extensionality; intros i; cbn.\n    assert (EITHER: l <= i < l + Z.of_nat sz \\/ (i < l \\/ l + Z.of_nat sz <= i)) by lia.\n    destruct EITHER.\n    * rewrite ! hinit_inside by auto. auto.\n    * rewrite ! hinit_outside by auto. auto.\n- exists h1; intuition auto. constructor; auto. cbn in H. destruct (h1 l); congruence.\n- exists (hupdate l v h1); intuition auto.\n  + constructor; auto.\n  + intros i; cbn. generalize (DISJ i). \n    destruct (Z.eq_dec l i); intuition congruence.\n  + apply heap_extensionality; intros i; cbn.\n    destruct (Z.eq_dec l i); auto.\n- exists (hfree l h1); intuition auto.\n  + constructor; auto.\n  + intros i; cbn. generalize (DISJ i). \n    destruct (Z.eq_dec l i); intuition congruence.\n  + apply heap_extensionality; intros i; cbn.\n    destruct (Z.eq_dec l i); auto.\n    subst i. generalize (DISJ l). intuition.\nQed.\n\nLemma safe_frame:\n  forall (R: assertion) h', R h' ->\n  forall c h Q,\n  safe c h Q -> hdisjoint h h' -> safe c (hunion h h') (fun v => Q v ** R).\nProof.\n  induction 2; intros DISJ.\n- constructor. exists h, h'; auto.\n- constructor. auto. apply immsafe_frame; auto. \n  intros. edestruct red_frame as (h1' & RED1 & D & U); eauto. subst h'0.\n  apply H3; auto.\nQed.\n\nLemma triple_frame: forall P c Q R,\n  ⦃ P ⦄ c ⦃ Q ⦄ ->\n  ⦃ P ** R ⦄ c ⦃ fun v => Q v ** R ⦄.\nProof.\n  intros P c Q R TR h (h1 & h2 & P1 & R2 & D & U). subst h.\n  apply safe_frame; auto.\nQed.\n\n(** ** 2.3. The \"small rules\" for heap operations *)\n\nLemma triple_get: forall l v,\n  ⦃ contains l v ⦄ GET l ⦃ fun v' => (v' = v) //\\\\ contains l v ⦄.\nProof.\n  intros l v h P.\n  assert (L: h l = Some v).\n  { red in P. subst h. apply hupdate_same. }\n  constructor; auto.\n  - constructor. congruence.\n  - intros c' h' RED. inv RED. constructor. split; auto; congruence.\nQed.\n\nLemma triple_set: forall l v,\n  ⦃ valid l ⦄ SET l v ⦃ fun _ => contains l v ⦄.\nProof.\n  intros l v h (v0 & P).\n  assert (L: h l = Some v0).\n  { red in P; subst h; apply hupdate_same. }\n  constructor; auto.\n  - constructor. congruence.\n  - intros c' h' RED. inv RED. constructor.\n    red in P; subst h.\n    red. apply heap_extensionality; intros l'; cbn.\n    destruct (Z.eq_dec l l'); auto.\nQed.\n\nFixpoint valid_N (l: addr) (sz: nat) : assertion :=\n  match sz with O => emp | S sz => valid l ** valid_N (l + 1) sz end.\n\nRemark valid_N_init: forall sz l,\n  (valid_N l sz) (hinit l sz hempty).\nProof.\n  induction sz as [ | sz]; intros l; cbn.\n- red; auto.\n- exists (hupdate l 0 hempty), (hinit (l + 1) sz hempty); intuition auto.\n  + exists 0. red; auto.\n  + intros x. unfold hupdate, hempty; cbn. destruct (Z.eq_dec l x); auto.\n  right. rewrite hinit_outside by lia. auto.\n  + apply heap_extensionality; intros x. cbn. destruct (Z.eq_dec l x); auto.\nQed. \n\nLemma triple_alloc: forall sz,\n  ⦃ emp ⦄\n  ALLOC sz\n  ⦃ fun l => (l <> 0) //\\\\ valid_N l sz ⦄.\nProof.\n  intros sz h P. red in P. subst h.\n  constructor; auto.\n- apply immsafe_alloc with 1; intros.\n  + lia.\n  + auto.\n- intros c' h' RED; inv RED. constructor.\n  split; auto. apply valid_N_init; auto.\nQed. \n\nLemma triple_free: forall l,\n  ⦃ valid l ⦄\n  FREE l\n  ⦃ fun _ => emp ⦄.\nProof.\n  intros l h (v0 & P). red in P.\n  assert (L: h l = Some v0).\n  { subst h. apply hupdate_same. }\n  constructor; auto.\n- constructor. congruence. \n- intros c' h' RED; inv RED. constructor.\n  red. apply heap_extensionality; intros x. cbn.\n  destruct (Z.eq_dec l x); auto.\nQed.\n\n(** ** 2.4. Properties of the [safe] predicate *)\n\nLemma safe_pure: forall v h Q,\n  safe (PURE v) h Q -> Q v h.\nProof.\n  intros. inv H. \n- auto.\n- contradiction.\nQed.\n\nLemma safe_red: forall c h Q c' h',\n  safe  c h Q -> red (c, h) (c', h') -> safe c' h' Q.\nProof.\n  intros. inv H.\n- inv H0.\n- eauto.\nQed.\n\nLemma safe_immsafe: forall c h Q,\n  safe c h Q -> immsafe (c, h).\nProof.\n  intros. inv H.\n- constructor.\n- auto.\nQed.\n\nLemma safe_let: forall (Q R: postcond) f,\n  (forall v h', Q v h' -> safe (f v) h' R) ->\n  forall c h,\n  safe c h Q ->\n  safe (LET c f) h R.\nProof.\n  intros Q R f POST. induction 1.\n- constructor; auto.\n  + constructor. constructor.\n  + intros c' h' RED; inv RED. apply POST; auto. inv H1.\n- constructor; auto.\n  + constructor; auto.\n  + intros c' h' RED; inv RED. contradiction. eauto.\nQed.\n\nLemma safe_consequence: forall (Q Q': postcond),\n  (forall v, Q v -->> Q' v) ->\n  forall c h, safe c h Q -> safe c h Q'.\nProof.\n  intros Q Q' IMP. induction 1.\n- apply safe_done. apply IMP. assumption.\n- apply safe_step; auto.\nQed.\n\n(** ** 2.5. Rules for control structures *)\n\nLemma triple_pure: forall P v (Q: postcond),\n  P -->> Q v ->\n  ⦃ P ⦄ PURE v ⦃ Q ⦄.\nProof.\n  intros; intros h Ph. constructor. apply H; auto.\nQed.\n\nLemma triple_let:\n  forall c f (P: precond) (Q R: postcond),\n  ⦃ P ⦄ c ⦃ Q ⦄ ->\n  (forall v, ⦃ Q v ⦄ f v ⦃ R ⦄) ->\n  ⦃ P ⦄ LET c f ⦃ R ⦄.\nProof.\n  intros until R; intros HR1 HR2 h Ph.\n  apply safe_let with Q. apply HR2. apply HR1. auto.\nQed.\n\nLemma triple_ifthenelse: forall b c1 c2 P Q,\n  ⦃ (b <> 0) //\\\\ P ⦄ c1 ⦃ Q ⦄ ->\n  ⦃ (b = 0) //\\\\ P ⦄ c2 ⦃ Q ⦄ ->\n  ⦃ P ⦄ IFTHENELSE b c1 c2 ⦃ Q ⦄.\nProof.\n  intros until Q; intros HR1 HR2 h Ph. constructor; auto.\n- constructor.\n- intros c' h' RED; inv RED. destruct (Z.eqb_spec b 0).\n  + apply HR2. split; auto.\n  + apply HR1. split; auto.\nQed.\n\nLemma triple_consequence: forall P P' c Q' Q,\n  ⦃ P' ⦄ c ⦃ Q' ⦄ ->\n  P -->> P' -> (forall v, Q' v -->> Q v) ->\n  ⦃ P ⦄ c ⦃ Q ⦄.\nProof.\n  intros; red; intros. apply safe_consequence with Q'; auto. \nQed.\n\nLemma triple_pick: forall n,\n  ⦃ emp ⦄\n  PICK n\n  ⦃ fun i => pure (0 <= i < n) ⦄.\nProof.\n  intros n h Ph. constructor; auto.\n- constructor.\n- intros c' h' RED; inv RED. constructor. split; auto.\nQed.\n\n(** ** 2.6.  Useful derived rules *)\n\n(** The following rules are heavily used in the examples of section 3. *)\n\nLemma triple_consequence_pre: forall P P' c Q,\n  ⦃ P' ⦄ c ⦃ Q ⦄ ->\n  P -->> P' ->\n  ⦃ P ⦄ c ⦃ Q ⦄.\nProof.\n  intros. apply triple_consequence with P' Q; auto. intros; red; auto.\nQed.\n\nLemma triple_consequence_post: forall P c Q Q',\n  ⦃ P ⦄ c ⦃ Q' ⦄ ->\n  (forall v, Q' v -->> Q v) ->\n  ⦃ P ⦄ c ⦃ Q ⦄.\nProof.\n  intros. apply triple_consequence with P Q'; auto. red; auto.\nQed.\n\nLemma triple_lift_pure: forall (P: Prop) P' c Q,\n  (P -> ⦃ P' ⦄ c ⦃ Q ⦄) ->\n  ⦃ P //\\\\ P' ⦄ c ⦃ Q ⦄.\nProof.\n  intros. intros h [P1 P2]. apply H; auto.\nQed.\n\nLemma triple_lift_exists: forall (X: Type) (P: X -> assertion) c Q,\n  (forall x, ⦃ P x ⦄ c ⦃ Q ⦄) ->\n  ⦃ aexists P ⦄ c ⦃ Q ⦄.\nProof.\n  intros. intros h (x & Px). apply (H x); auto.\nQed.\n\nLemma triple_ifthen: forall b c1 c2 P Q,\n  b <> 0 -> ⦃ P ⦄ c1 ⦃ Q ⦄ ->\n  ⦃ P ⦄ IFTHENELSE b c1 c2 ⦃ Q ⦄.\nProof.\n  intros. apply triple_ifthenelse; apply triple_lift_pure; intros.\n- auto.\n- lia.\nQed.\n\nLemma triple_ifelse: forall b c1 c2 P Q,\n  b = 0 -> ⦃ P ⦄ c2 ⦃ Q ⦄ ->\n  ⦃ P ⦄ IFTHENELSE b c1 c2 ⦃ Q ⦄.\nProof.\n  intros. apply triple_ifthenelse; apply triple_lift_pure; intros.\n- lia.\n- auto.\nQed.\n\nLemma unroll_com: forall c,\n  c = match c with\n      | PURE x => PURE x\n      | LET c f => LET c f\n      | IFTHENELSE b c1 c2 => IFTHENELSE b c1 c2\n      | ALLOC sz => ALLOC sz\n      | GET l => GET l\n      | SET l v => SET l v\n      | FREE l => FREE l\n      | PICK n => PICK n\n      end.\nProof.\n  destruct c; auto.\nQed.\n\n(** * 3. Singly-linked lists *)\n\n(** ** Representation predicate *)\n\n(** Here is a separation logic assertion that describes the in-memory\n    representation of a list.\n-   [a] is the pointer to the list head (or 0 if the list is empty).\n-   [l] is the Coq list of the list elements.\n*)\n\nFixpoint list_at (a: addr) (l: list Z) : assertion :=\n  match l with\n  | nil => (a = 0) //\\\\ emp\n  | h :: t => (a <> 0) //\\\\ aexists (fun a' => contains a h ** contains (a + 1) a' ** list_at a' t)\n  end.\n\n(** ** The \"cons\" operation *)\n\nDefinition list_cons (n: Z) (a: addr) : com :=\n  LET (ALLOC 2) (fun a' => SEQ (SET a' n) (SEQ (SET (a' + 1) a) (PURE a'))).\n\nLemma list_cons_correct: forall a n l,\n    ⦃ list_at a l ⦄\n  list_cons n a\n    ⦃ fun a' => list_at a' (n :: l) ⦄.\nProof.\n  intros. eapply triple_let.\n  rewrite <- sepconj_emp at 1. apply triple_frame. apply triple_alloc.\n  intros b; simpl. rewrite lift_pureconj, ! sepconj_assoc, sepconj_emp.\n  apply triple_lift_pure; intros H1.\n  eapply triple_let. apply triple_frame. apply triple_set. simpl; intros _.\n  eapply triple_let. rewrite sepconj_pick2. \n  apply triple_frame. apply triple_set. simpl; intros _.\n  rewrite sepconj_pick2. \n  apply triple_pure. intros h A. split. auto. exists a; auto.\nQed.   \n\n(** ** Computing the length of a list *)\n\n(** Taking advantage of the coinductive nature of type [com],\n    we use infinite commands to represent loops and tail-recursive functions. *)\n\nCoFixpoint list_length_rec (a: addr) (len: Z) : com :=\n  IFTHENELSE a (LET (GET (a + 1)) (fun t => list_length_rec t (len + 1))) (PURE len).\n\nDefinition list_length (a: addr) : com := list_length_rec a 0.\n\n(** Normally we would write\n<<\n   len = 0;\n   while (a != 0) { a = get (a + 1); len = len + 1; }\n>>\n   With the coinductive definition, we write the equivalent infinite command\n<<\n   if (a == 0) return 0; else {\n     a1 = get (a + 1);\n     if (a1 == 0) return 1; else {\n       a2 = get (a1 + 1);\n       if (a2 == 0) return 2; else ...\n>>\n*)\n\nLemma list_length_rec_correct: forall l a len,\n    ⦃ list_at a l ⦄\n  list_length_rec a len\n    ⦃ fun len' => (len' = len + Z.of_nat (List.length l)) //\\\\ list_at a l ⦄.\nProof.\nLocal Opaque Z.of_nat.\n  induction l as [ | h t]; intros; rewrite (unroll_com (list_length_rec a len)); cbn.\n- apply triple_lift_pure; intro H1.\n  apply triple_ifelse; auto.\n  apply triple_pure. intros h H2. split. lia. split; auto.\n- apply triple_lift_pure; intro H1.\n  apply triple_lift_exists; intros a'.\n  apply triple_ifthen; auto.\n  eapply triple_let.\n  rewrite sepconj_pick2. apply triple_frame. apply triple_get. simpl.\n  intros a''. rewrite lift_pureconj. apply triple_lift_pure; intros H3. subst a''.\n  rewrite sepconj_swap3.\n  eapply triple_consequence_post.\n  apply triple_frame. apply IHt. intros len'; simpl.\n  rewrite lift_pureconj. rewrite <- sepconj_swap3, sepconj_pick2.\n  intros h1 (A & B). split. lia. split. auto. exists a'; auto.\nQed.\n\nCorollary list_length_correct: forall l a,\n    ⦃ list_at a l ⦄\n  list_length a\n    ⦃ fun len => (len = Z.of_nat (length l)) //\\\\ list_at a l ⦄.\nProof.\n  intros. apply list_length_rec_correct.\nQed.\n\n(** ** Concatenating two lists in-place *)\n\n(** In loop notation:\n<<\n  if (l1 == 0) return l2; else {\n    t = get(l1 + 1);\n    while (get (t + 1) != 0) t = get (t + 1);\n    set (t + 1, l2);\n    return l1;\n  }\n>>\n*)\n\nCoFixpoint list_concat_rec (a1 a2: addr) : com :=\n  LET (GET (a1 + 1)) (fun t => IFTHENELSE t (list_concat_rec t a2) (SET (a1 + 1) a2)).\n\nDefinition list_concat (a1 a2: addr) : com :=\n  IFTHENELSE a1 (SEQ (list_concat_rec a1 a2) (PURE a1)) (PURE a2).\n\nLemma list_concat_rec_correct: forall l2 a2 l1 a1,\n  a1 <> 0 ->\n    ⦃ list_at a1 l1 ** list_at a2 l2 ⦄\n  list_concat_rec a1 a2\n    ⦃ fun _ => list_at a1 (l1 ++ l2) ⦄.\nProof.\n  induction l1 as [ | h1 t1]; intros; rewrite (unroll_com (list_concat_rec a1 a2)); simpl.\n- rewrite lift_pureconj. apply triple_lift_pure; intros. lia.\n- rewrite lift_pureconj. apply triple_lift_pure. intros H1.\n  rewrite lift_aexists. apply triple_lift_exists. intros a'.\n  rewrite sepconj_assoc.\n  eapply triple_let.\n  + rewrite sepconj_assoc, sepconj_pick2. apply triple_frame. apply triple_get.\n  + intros t. simpl. \n    rewrite lift_pureconj. apply triple_lift_pure. intros H2; subst t.\n    apply triple_ifthenelse.\n    * apply triple_lift_pure. intros H2.\n      rewrite <- sepconj_assoc, sepconj_comm.\n      eapply triple_consequence_post. apply triple_frame. apply IHt1. auto.\n      simpl. intros _. rewrite sepconj_pick2, sepconj_swap3.\n      intros h P. split; auto. exists a'; auto.\n    * apply triple_lift_pure. intros H2.\n      eapply triple_consequence_post.\n      apply triple_frame.\n      eapply triple_consequence_pre. apply triple_set.\n      intros h P; exists a'; auto.\n      simpl. intros _. rewrite sepconj_pick2, sepconj_pick3.\n      destruct t1; simpl.\n      ** rewrite lift_pureconj, sepconj_emp.\n         intros h (A & B). split; auto. exists a2; auto.\n      ** rewrite lift_pureconj. intros h (A & B). lia.\nQed.\n\nLemma list_concat_correct: forall l1 a1 l2 a2,\n    ⦃ list_at a1 l1 ** list_at a2 l2 ⦄\n  list_concat a1 a2\n    ⦃ fun a => list_at a (l1 ++ l2) ⦄.\nProof.\n  intros. unfold list_concat. apply triple_ifthenelse.\n- apply triple_lift_pure; intros H1. \n  eapply triple_let. apply list_concat_rec_correct; auto.\n  simpl. intros _. apply triple_pure. red; auto.\n- apply triple_lift_pure; intros H1.\n  destruct l1; simpl.\n  + apply triple_pure. rewrite lift_pureconj, sepconj_emp. intros h (A & B); auto.\n  + rewrite lift_pureconj. apply triple_lift_pure. intros; lia.\nQed.\n\n(** ** List reversal in place *)\n\n(** In loop notation:\n<<\n  p = 0;\n  while (l != 0) {\n    n = get (l + 1);\n    set (l + 1, p);\n    p = l;\n    l = n;\n  }\n  return p;\n>>\n*)\n\nCoFixpoint list_rev_rec (a p: addr) : com :=\n  IFTHENELSE a\n    (LET (GET (a + 1)) (fun n =>\n     SEQ (SET (a + 1) p)\n         (list_rev_rec n a)))\n    (PURE p).\n\nDefinition list_rev (a: addr) : com := list_rev_rec a 0.\n\nLemma list_rev_rec_correct: forall l a l' p,\n    ⦃ list_at a l ** list_at p l' ⦄\n  list_rev_rec a p\n    ⦃ fun x => list_at x (List.rev_append l l') ⦄.\nProof.\n  induction l as [ | hd l]; intros; rewrite (unroll_com (list_rev_rec a p)); simpl.\n- rewrite lift_pureconj, sepconj_emp. apply triple_lift_pure; intros H1.\n  apply triple_ifelse; auto. apply triple_pure. red; auto.\n- rewrite lift_pureconj; apply triple_lift_pure; intros H1.\n  rewrite lift_aexists; apply triple_lift_exists; intros a'.\n  apply triple_ifthen; auto.\n  eapply triple_let.\n  rewrite ! sepconj_assoc, sepconj_pick2. \n  apply triple_frame. apply triple_get. intros a''. simpl.\n  rewrite lift_pureconj. apply triple_lift_pure. intros H3. subst a''.\n  eapply triple_let.\n  apply triple_frame. eapply triple_consequence_pre. \n  apply triple_set. \n  intros h P; exists a'; auto.\n  simpl. intros _.\n  rewrite sepconj_pick2, sepconj_pick3.\n  eapply triple_consequence_pre.\n  apply IHl.\n  simpl. apply sepconj_imp_r. intros h A. split; auto. exists p; auto.\nQed.\n\nLemma list_rev_correct: forall a l,\n    ⦃ list_at a l ⦄\n  list_rev a\n    ⦃ fun x => list_at x (List.rev l) ⦄.\nProof.\n  intros. rewrite List.rev_alt.\n  eapply triple_consequence_pre. apply list_rev_rec_correct. \n  simpl. rewrite sepconj_comm, lift_pureconj, sepconj_emp.\n  intros h A; split; auto.\nQed.\n\n(** * 4. An alternate definition of separation logic triples *)\n\nModule AlternateSeplog.\n\n(** For some languages, the frame property for reductions (lemma\n    [red_frame] above) does not hold, e.g. because allocations are\n    deterministic.  Or maybe we do not want to prove the [red_frame]\n    lemma.\n\n    In this case, not all is lost: we can define our separation\n    triples [ ⦃ P ⦄ c ⦃ Q ⦄ ] as Hoare triples plus framing. *)\n\nDefinition Hoare (P: precond) (c: com) (Q: postcond) : Prop :=\n  forall h, P h -> safe c h Q.\n\nDefinition triple (P: precond) (c: com) (Q: postcond) :=\n  forall (R: assertion), Hoare (P ** R) c (fun v => Q v ** R).\n\nNotation \"⦃ P ⦄ c ⦃ Q ⦄\" := (triple P c Q) (at level 90, c at next level).\n\n(** This definition validates the frame rule. *)\n\nLemma triple_frame: forall P c Q R,\n  ⦃ P ⦄ c ⦃ Q ⦄ ->\n  ⦃ P ** R ⦄ c ⦃ fun v => Q v ** R ⦄.\nProof.\n  intros P c Q R TR R'. rewrite sepconj_assoc.\n  replace (fun v => (Q v ** R) ** R') with (fun v => Q v ** (R ** R')).\n  apply TR.\n  apply functional_extensionality; intros. rewrite sepconj_assoc; auto.\nQed.\n\n(** It also validates the \"small rules\" for heap operations. *)\n\nLemma triple_get: forall l v,\n  ⦃ contains l v ⦄ GET l ⦃ fun v' => (v' = v) //\\\\ contains l v ⦄.\nProof.\n  intros l v R h (h1 & h2 & H1 & H2 & D & U).\n  assert (L1: h1 l = Some v).\n  { red in H1. subst h1. apply hupdate_same. }\n  assert (L: h l = Some v).\n  { intros. rewrite U; simpl. rewrite L1; auto. } \n  constructor; auto.\n  - constructor. congruence.\n  - intros c' h' RED. inv RED. constructor. \n    exists h1, h2. unfold pureconj. intuition congruence.\nQed.\n\nLemma triple_set: forall l v,\n  ⦃ valid l ⦄ SET l v ⦃ fun _ => contains l v ⦄.\nProof.\n  intros l v R h (h1 & h2 & H1 & H2 & D & U).\n  destruct H1 as (v0 & H1). red in H1.\n  assert (L1: h1 l = Some v0).\n  { subst h1; apply hupdate_same. }\n  assert (L: h l = Some v0).\n  { rewrite U; cbn. rewrite L1; auto. } \n  constructor; auto.\n  - constructor. congruence.\n  - intros c' h' RED. inv RED. constructor. \n    exists (hupdate l v hempty), h2.\n    split. red. auto.\n    split. auto.\n    split. intro l'. specialize (D l'). cbn in *. destruct D; auto. destruct (Z.eq_dec l l'); auto. congruence.\n    apply heap_extensionality; intros l'; cbn. destruct (Z.eq_dec l l'); auto.\nQed.\n\nRemark valid_N_init:\n  forall (R: assertion) sz l h,\n  R h ->\n  (forall i, l <= i < l + Z.of_nat sz -> h i = None) ->\n  (valid_N l sz ** R) (hinit l sz h).\nProof.\n  induction sz as [ | sz]; intros l h Rh EMPTY; cbn.\n- rewrite sepconj_emp. auto.\n- rewrite sepconj_assoc. exists (hupdate l 0 hempty), (hinit (l + 1) sz h).\n  split. exists 0. red; auto.\n  split. apply IHsz. auto. intros. apply EMPTY. lia.\n  split. intros x. unfold hupdate, hempty; cbn. destruct (Z.eq_dec l x); auto.\n  right. rewrite hinit_outside by lia. apply EMPTY; lia.\n  apply heap_extensionality; intros x. cbn. destruct (Z.eq_dec l x); auto.\nQed. \n\nLemma triple_alloc: forall sz,\n  ⦃ emp ⦄\n  ALLOC sz\n  ⦃ fun l => (l <> 0) //\\\\ valid_N l sz ⦄.\nProof.\n  intros sz R h H. rewrite sepconj_emp in H.\n  constructor; auto.\n- destruct (isfinite h) as (l0 & FIN). apply immsafe_alloc with (Z.max l0 1); intros.\n  + lia.\n  + apply FIN. lia.\n- intros c' h' RED; inv RED. constructor.\n  rewrite lift_pureconj; split. auto. apply valid_N_init; auto.\nQed. \n\nLemma triple_free: forall l,\n  ⦃ valid l ⦄\n  FREE l\n  ⦃ fun _ => emp ⦄.\nProof.\n  intros l R h (h1 & h2 & H1 & H2 & D & U).\n  destruct H1 as (v0 & H1).\n  assert (L1: h1 l = Some v0).\n  { rewrite H1. apply hupdate_same. }\n  assert (L: h l = Some v0).\n  { rewrite U; cbn. rewrite L1. auto. } \n  constructor; auto.\n- constructor. congruence. \n- intros c' h' RED; inv RED. constructor. rewrite sepconj_emp.\n  replace (hfree l (hunion h1 h2)) with h2; auto.\n  apply heap_extensionality; intros x. generalize (D x); rewrite H1; cbn.\n  destruct (Z.eq_dec l x); auto. intuition congruence.\nQed.\n\n(** The rules for control structures are also valid.  \n    Proof plan: first show Hoare-style rules for the [Hoare] triple,\n    then frame by an arbitrary [R] to obtain the separation triple. *)\n\nLemma Hoare_pure: forall P v (Q: postcond),\n  P -->> Q v ->\n  Hoare P (PURE v) Q.\nProof.\n  intros; intros h Ph. constructor. apply H; auto.\nQed.\n\nLemma triple_pure: forall P v (Q: postcond),\n  P -->> Q v ->\n  ⦃ P ⦄ PURE v ⦃ Q ⦄.\nProof.\n  intros; intros R. apply Hoare_pure. apply sepconj_imp_l; auto.\nQed.\n\nLemma Hoare_let:\n  forall c f (P: precond) (Q R: postcond),\n  Hoare P c Q ->\n  (forall v, Hoare (Q v) (f v) R) ->\n  Hoare P (LET c f) R.\nProof.\n  intros until R; intros HR1 HR2 h Ph.\n  apply safe_let with Q. apply HR2. apply HR1. auto.\nQed.\n\nLemma triple_let:\n  forall c f (P: precond) (Q R: postcond),\n  ⦃ P ⦄ c ⦃ Q ⦄ ->\n  (forall v, ⦃ Q v ⦄ f v ⦃ R ⦄) ->\n  ⦃ P ⦄ LET c f ⦃ R ⦄.\nProof.\n  intros c f P Q R TR1 TR2 R'.\n  apply Hoare_let with (fun v => Q v ** R').\n  apply TR1.\n  intros. apply TR2.\nQed.\n\nLemma Hoare_ifthenelse: forall b c1 c2 P Q,\n  Hoare ((b <> 0) //\\\\ P) c1 Q ->\n  Hoare ((b = 0) //\\\\ P) c2 Q ->\n  Hoare P (IFTHENELSE b c1 c2) Q.\nProof.\n  intros until Q; intros HR1 HR2 h Ph. constructor; auto.\n- constructor.\n- intros c' h' RED; inv RED. destruct (Z.eqb_spec b 0).\n  + apply HR2. split; auto.\n  + apply HR1. split; auto.\nQed.\n\nLemma triple_ifthenelse: forall b c1 c2 P Q,\n  ⦃ (b <> 0) //\\\\ P ⦄ c1 ⦃ Q ⦄ ->\n  ⦃ (b = 0) //\\\\ P ⦄ c2 ⦃ Q ⦄ ->\n  ⦃ P ⦄ IFTHENELSE b c1 c2 ⦃ Q ⦄.\nProof.\n  intros b c1 c2 P Q TR1 TR2 R.\n  apply Hoare_ifthenelse; rewrite <- lift_pureconj; auto.\nQed.\n\nLemma Hoare_consequence: forall P P' c Q' Q,\n  Hoare P' c Q' ->\n  P -->> P' -> (forall v, Q' v -->> Q v) ->\n  Hoare P c Q.\nProof.\n  intros; red; intros. apply safe_consequence with Q'; auto. \nQed.\n\nLemma triple_consequence: forall P P' c Q' Q,\n  ⦃ P' ⦄ c ⦃ Q' ⦄ ->\n  P -->> P' -> (forall v, Q' v -->> Q v) ->\n  ⦃ P ⦄ c ⦃ Q ⦄.\nProof.\n  intros; red; intros. apply Hoare_consequence with (P' ** R) (fun v => Q' v ** R).\n  apply H.\n  apply sepconj_imp_l; auto.\n  intros; apply sepconj_imp_l; auto.\nQed.\n\nLemma Hoare_pick: forall P n,\n  Hoare P (PICK n) (fun i => (0 <= i < n) //\\\\ P).\nProof.\n  intros P n h Ph. constructor; auto.\n- constructor.\n- intros c' h' RED; inv RED. constructor. split; auto.\nQed. \n\nLemma triple_pick: forall n,\n  ⦃ emp ⦄\n  PICK n\n  ⦃ fun i => pure (0 <= i < n) ⦄.\nProof.\n  intros; intros R. rewrite sepconj_emp. eapply Hoare_consequence with (P' := R). apply Hoare_pick.\n  red; auto.\n  intros; red; intros. rewrite pureconj_sepconj. auto.\nQed.\n\nEnd AlternateSeplog.\n\n(** * 5. Ramification *)\n\n(** Assume we have a triple [{P'} c {Q'}] and we want to conclude [{P} c {Q}].\n    In general, we need to frame the former triple by an appropriate [R],\n    then use the consequence rule to conclude. *)\n\nLemma triple_frame_consequence: forall R P c Q P' Q',\n  ⦃ P ⦄ c ⦃ Q ⦄ ->\n  P' -->> P ** R ->\n  (forall v, Q v ** R -->> Q' v) ->\n  ⦃ P' ⦄ c ⦃ Q' ⦄.\nProof.\n  intros. apply triple_consequence with (P ** R) (fun v => Q v ** R); auto. apply triple_frame; auto.\nQed.\n\n(** This rule still needs the user to guess the framing predicate [R].\n    An alternate presentation uses the magic wand instead.\n    This approach is called \"ramification\" in the literature. *)\n\nLemma triple_ramification: forall P c Q P' Q',\n ⦃ P ⦄ c ⦃ Q ⦄ ->\n  P' -->> P ** (aforall (fun v => Q v --* Q' v)) ->\n  ⦃ P' ⦄ c ⦃ Q' ⦄.\nProof.\n  intros. eapply triple_frame_consequence with (R := aforall (fun v => Q v --* Q' v)).\n  eassumption.\n  assumption.\n  intros v h (h1 & h2 & Q1 & W2 & D & U).\n  apply (wand_cancel (Q v)). exists h1, h2; auto.\nQed.\n\n(** * 6. Weakest preconditions *)\n\n(** ** 6.1.  Definition and characterization *)\n\n(** Here is one possible definition of the weakest precondition for\n    command [c] with postcondition [Q]. *)\n\nDefinition wp (c: com) (Q: postcond) : precond :=\n  aexists (fun P => ⦃ P ⦄ c ⦃ Q ⦄ //\\\\ P).\n\n(** What matters about [wp c Q] is that it is a precondition... *)\n\nLemma wp_precond: forall c Q,\n  ⦃ wp c Q ⦄ c ⦃ Q ⦄.\nProof.\n  intros c Q h (P & T & C). apply T. auto.\nQed.\n\n(** ... and it is implied by any other precondition. *)\n\nLemma wp_weakest: forall P c Q,\n  ⦃ P ⦄ c ⦃ Q ⦄ ->\n  P -->> wp c Q.\nProof.\n  intros P c Q T h Ph. exists P; split; auto.\nQed.\n\n(** This leads to the following alternate definition of triples in terms\n    of weakest preconditions. *)\n\nCorollary wp_equiv: forall P c Q,\n  ⦃ P ⦄ c ⦃ Q ⦄ <-> (P -->> wp c Q).\nProof.\n  intros; split; intros.\n- apply wp_weakest; auto.\n- apply triple_consequence_pre with (wp c Q); auto using wp_precond.\nQed.\n\n(** Here is another definition of the weakest precondition, using the\n    operational semantics directly. *)\n\nDefinition wp' (c: com) (Q: postcond) : precond :=\n  fun h => safe c h Q.\n\nLemma wp'_precond: forall c Q,\n  ⦃ wp' c Q ⦄ c ⦃ Q ⦄.\nProof.\n  intros c Q h SAFE. apply SAFE.\nQed.\n\nLemma wp'_weakest: forall P c Q,\n  ⦃ P ⦄ c ⦃ Q ⦄ ->\n  P -->> wp' c Q.\nProof.\n  intros; intros h Ph. apply H. auto.\nQed.\n\n(** ** 6.2. Structural rules for weakest preconditions *)\n\nLemma wp_consequence: forall (Q Q': postcond) c,\n  (forall v, Q v -->> Q' v) ->\n  wp c Q -->> wp c Q'.\nProof.\n  intros. apply wp_weakest. apply triple_consequence_post with Q; auto using wp_precond.\nQed.\n\nLemma wp_frame: forall R c Q,\n  wp c Q ** R -->> wp c (fun v => Q v ** R).\nProof.\n  intros. apply wp_weakest. apply triple_frame. apply wp_precond.\nQed.\n\nCorollary wp_frame_consequence: forall R Q c Q',\n  (forall v, Q v ** R -->> Q' v) ->\n  wp c Q ** R -->> wp c Q'.\nProof.\n  intros; red; intros. apply wp_consequence with (fun v => Q v ** R). assumption.\n  apply wp_frame; auto.\nQed.\n\nCorollary wp_ramification: forall c Q Q',\n  wp c Q ** aforall (fun v => Q v --* Q' v) -->> wp c Q'.\nProof.\n  intros. apply wp_frame_consequence.\n  intros v h (h1 & h2 & A & B & D & U). apply (wand_cancel (Q v)). exists h1, h2; auto.\nQed.\n\n(** ** 6.3.  Weakest precondition rules for our language of pointers *)\n\nLemma wp_pure: forall (Q: postcond) v,\n  Q v -->> wp (PURE v) Q.\nProof.\n  intros. apply wp_weakest. apply triple_pure. red; auto.\nQed.\n\nLemma wp_let: forall c f Q,\n  wp c (fun v => wp (f v) Q) -->> wp (LET c f) Q.\nProof.\n  intros. apply wp_weakest. eapply triple_let.\n  apply wp_precond.\n  intros. apply wp_precond.\nQed.\n\nLemma wp_ifthenelse: forall b c1 c2 Q,\n  (if b =? 0 then wp c2 Q else wp c1 Q) -->> wp (IFTHENELSE b c1 c2) Q.\nProof.\n  intros. apply wp_weakest. apply triple_ifthenelse.\n- apply triple_consequence_pre with (wp c1 Q). apply wp_precond.\n  intros h (A & B). rewrite <- Z.eqb_neq in A. rewrite A in B. auto.\n- apply triple_consequence_pre with (wp c2 Q). apply wp_precond.\n  intros h (A & B). subst b. auto.\nQed.\n\nLemma wp_alloc: forall sz Q,\n  aforall (fun l => (l <> 0) //\\\\ valid_N l sz --* Q l) -->> wp (ALLOC sz) Q.\nProof.\n  intros; red; intros.\n  apply wp_ramification with (Q := fun l => (l <> 0) //\\\\ valid_N l sz).\n  apply sepconj_imp_l with emp.\n  apply wp_weakest. apply triple_alloc.\n  rewrite sepconj_emp. assumption.\nQed.\n\nLemma wp_get: forall l v Q,\n  contains l v ** (contains l v --* Q v) -->> wp (GET l) Q.\nProof.\n  intros.\n  assert (W: contains l v -->> wp (GET l) (fun v' => (v' = v) //\\\\ contains l v)).\n  { apply wp_weakest. apply triple_get. }\n  intros; red; intros.\n  eapply wp_ramification. eapply sepconj_imp_l. eexact W. \n  eapply sepconj_imp_r. 2: eexact H.\n  intros h' H' v' h'' D (A & B). subst v'. apply H'; auto.\nQed.\n\nLemma wp_set: forall l v Q,\n  valid l ** aforall (fun v' => (contains l v --* Q v')) -->> wp (SET l v) Q. \nProof.\n  intros.\n  assert (W: valid l -->> wp (SET l v) (fun _ => contains l v)).\n  { apply wp_weakest. apply triple_set. }\n  intros; red; intros.\n  eapply wp_ramification. eapply sepconj_imp_l. eexact W. \n  eapply sepconj_imp_r. 2: eexact H.\n  red; auto.\nQed.\n\nCorollary wp_set': forall l v Q,\n  valid l ** (contains l v --* Q) -->> wp (SET l v) (fun _ => Q). \nProof.\n  intros; red; intros. apply wp_set. eapply sepconj_imp_r; eauto.\n  intros h' H' v'. auto.\nQed.\n\nLemma wp_free: forall l Q,\n  valid l ** aforall (fun v' => Q v') -->> wp (FREE l) Q.\nProof.\n  intros.\n  assert (W: valid l -->> wp (FREE l) (fun _ => emp)).\n  { apply wp_weakest. apply triple_free. }\n  intros; red; intros.\n  eapply wp_ramification. eapply sepconj_imp_l. eexact W. \n  eapply sepconj_imp_r. 2: eexact H.\n  red; intros. intros v h' D E. rewrite E in *. rewrite hunion_comm, hunion_empty by HDISJ.\n  apply H0.\nQed.\n\nCorollary wp_free': forall l Q,\n  valid l ** Q -->> wp (FREE l) (fun _ => Q).\nProof.\n  intros; red; intros. apply wp_free. eapply sepconj_imp_r; eauto.\n  intros h' H' v'. auto.\nQed.\n\nLemma wp_pick: forall n Q,\n  aforall (fun i => pure (0 <= i < n) --* Q i) -->> wp (PICK n) Q.\nProof.\n  intros.\n  assert (W: emp -->> wp (PICK n) (fun i => pure (0 <= i < n))).\n  { apply wp_weakest. apply triple_pick. }\n  intros; red; intros.\n  eapply wp_ramification. eapply sepconj_imp_l. eexact W. \n  eapply sepconj_imp_r. 2: rewrite sepconj_emp; eexact H.\n  red; auto.\nQed.\n\n\n\n", "meta": {"author": "xavierleroy", "repo": "cdf-program-logics", "sha": "5c16d588e702810688180e80576d1a7b2e65085c", "save_path": "github-repos/coq/xavierleroy-cdf-program-logics", "path": "github-repos/coq/xavierleroy-cdf-program-logics/cdf-program-logics-5c16d588e702810688180e80576d1a7b2e65085c/Seplog.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.28390413101837647}}
{"text": "\nRequire Import Coq.Lists.List.\n\nRequire Import Axioms.\nRequire Import Tactics.\nRequire Import Equality.\nRequire Import Relation.\nRequire Import Syntax.\nRequire Import SimpSub.\nRequire Import Hygiene.\nRequire Import ContextHygiene.\nRequire Import Dynamic.\nRequire Import Reduction.\nRequire Import Equivalence.\nRequire Import Ofe.\nRequire Import Sequence.\nRequire Import Promote.\n\n\nArguments rw_nil {object}.\nArguments rw_cons {object i a}.\nArguments reducer {object a}.\n\n\nDefinition map_operator {A B : Type} (f : A -> B) (a : list nat) (th : operator A a)\n  : operator B a\n  :=\n  match th with\n  | oper_ext _ x => oper_ext _ (f x)\n  | oper_extt _ x => oper_extt _ (f x)\n\n  | oper_univ _ => oper_univ _\n  | oper_cty _ => oper_cty _\n  | oper_con _ => oper_con _\n  | oper_karrow _ => oper_karrow _\n  | oper_arrow _ => oper_arrow _\n  | oper_pi _ => oper_pi _\n  | oper_clam _ => oper_clam _\n  | oper_capp _ => oper_capp _\n  | oper_ctlam _ => oper_ctlam _\n  | oper_ctapp _ => oper_ctapp _\n  | oper_lam _ => oper_lam _\n  | oper_app _ => oper_app _\n  | oper_intersect _ => oper_intersect _\n  | oper_fut _ => oper_fut _\n  | oper_cnext _ => oper_cnext _\n  | oper_cprev _ => oper_cprev _\n  | oper_next _ => oper_next _\n  | oper_prev _ => oper_prev _\n  | oper_rec _ => oper_rec _\n  | oper_equal _ => oper_equal _\n  | oper_triv _ => oper_triv _\n  | oper_eqtype _ => oper_eqtype _\n  | oper_subtype _ => oper_subtype _\n  | oper_kuniv _ => oper_kuniv _\n  | oper_all _ => oper_all _\n  | oper_alltp _ => oper_alltp _\n  | oper_exist _ => oper_exist _\n  | oper_mu _ => oper_mu _\n  | oper_ispositive _ => oper_ispositive _\n  | oper_isnegative _ => oper_isnegative _\n  | oper_voidtp _ => oper_voidtp _\n  | oper_unittp _ => oper_unittp _\n  | oper_cunit _ => oper_cunit _\n  | oper_booltp _ => oper_booltp _\n  | oper_btrue _ => oper_btrue _\n  | oper_bfalse _ => oper_bfalse _\n  | oper_bite _ => oper_bite _\n  | oper_prod _ => oper_prod _\n  | oper_sigma _ => oper_sigma _\n  | oper_cpair _ => oper_cpair _\n  | oper_cpi1 _ => oper_cpi1 _\n  | oper_cpi2 _ => oper_cpi2 _\n  | oper_ppair _ => oper_ppair _\n  | oper_ppi1 _ => oper_ppi1 _\n  | oper_ppi2 _ => oper_ppi2 _\n  | oper_set _ => oper_set _\n  | oper_quotient _ => oper_quotient _\n  | oper_guard _ => oper_guard _\n  | oper_wt _ => oper_wt _\n  end.\n\n\nArguments map_operator {A B} f {a}.\n\n\nFixpoint map_term {A B : Type} (f : A -> B) (m : term A) {struct m} : @term B\n  :=\n  (match m with\n   | var j => var j\n   | oper a th r => oper a (map_operator f th) (map_row f a r)\n   end)\n\nwith map_row {A B : Type} (f : A -> B) (a : list nat) (r : row _ a) {struct r} : @row B a\n  :=\n  match r\n    in @row _ a\n    return @row B a\n  with\n  | rw_nil => rw_nil\n  | @rw_cons _ i a m r => @rw_cons _ i a (map_term f m) (map_row f a r)\n  end.\n\n\nArguments map_row {A B} f {a}.\n\n\nLemma map_ext :\n  forall A B (f : A -> B) (x : A),\n    map_term f (ext x) = ext (f x).\nProof.\nauto.\nQed.\n\n\nLemma map_extt :\n  forall A B (f : A -> B) (x : A),\n    map_term f (extt x) = extt (f x).\nProof.\nauto.\nQed.\n\n\nLemma map_var :\n  forall A B (f : A -> B) i, map_term f (var i) = var i.\nProof.\nauto.\nQed.\n\n\nLemma map_univ :\n  forall A B (f : A -> B) m, map_term f (univ m) = univ (map_term f m).\nProof.\nauto.\nQed.\n\n\nLemma map_cty :\n  forall A B (f : A -> B) m, map_term f (cty m) = cty (map_term f m).\nProof.\nauto.\nQed.\n\n\nLemma map_con :\n  forall A B (f : A -> B) m1 m2, map_term f (con m1 m2) = con (map_term f m1) (map_term f m2).\nProof.\nauto.\nQed.\n\n\nLemma map_karrow :\n  forall A B (f : A -> B) m1 m2, map_term f (karrow m1 m2) = karrow (map_term f m1) (map_term f m2).\nProof.\nauto.\nQed.\n\n\nLemma map_arrow :\n  forall A B (f : A -> B) m1 m2, map_term f (arrow m1 m2) = arrow (map_term f m1) (map_term f m2).\nProof.\nauto.\nQed.\n\n\nLemma map_pi :\n  forall A B (f : A -> B) m1 m2, map_term f (pi m1 m2) = pi (map_term f m1) (map_term f m2).\nProof.\nauto.\nQed.\n\n\nLemma map_clam :\n  forall A B (f : A -> B) k a, map_term f (clam k a) = clam (map_term f k) (map_term f a).\nProof.\nauto.\nQed.\n\n\nLemma map_capp :\n  forall A B (f : A -> B) m1 m2, map_term f (capp m1 m2) = capp (map_term f m1) (map_term f m2).\nProof.\nauto.\nQed.\n\n\nLemma map_ctlam :\n  forall A B (f : A -> B) a b k, map_term f (ctlam a b k) = ctlam (map_term f a) (map_term f b) (map_term f k).\nProof.\nauto.\nQed.\n\n\nLemma map_ctapp :\n  forall A B (f : A -> B) m1 m2, map_term f (ctapp m1 m2) = ctapp (map_term f m1) (map_term f m2).\nProof.\nauto.\nQed.\n\n\nLemma map_lam :\n  forall A B (f : A -> B) m, map_term f (lam m) = lam (map_term f m).\nProof.\nauto.\nQed.\n\n\nLemma map_app :\n  forall A B (f : A -> B) m1 m2, map_term f (app m1 m2) = app (map_term f m1) (map_term f m2).\nProof.\nauto.\nQed.\n\n\nLemma map_intersect :\n  forall A B (f : A -> B) m1 m2, map_term f (intersect m1 m2) = intersect (map_term f m1) (map_term f m2).\nProof.\nauto.\nQed.\n\n\nLemma map_fut :\n  forall A B (f : A -> B) k, map_term f (fut k) = fut (map_term f k).\nProof.\nauto.\nQed.\n\n\nLemma map_cnext :\n  forall A B (f : A -> B) a, map_term f (cnext a) = cnext (map_term f a).\nProof.\nauto.\nQed.\n\n\nLemma map_cprev :\n  forall A B (f : A -> B) a, map_term f (cprev a) = cprev (map_term f a).\nProof.\nauto.\nQed.\n\n\nLemma map_next :\n  forall A B (f : A -> B) a, map_term f (next a) = next (map_term f a).\nProof.\nauto.\nQed.\n\n\nLemma map_prev :\n  forall A B (f : A -> B) a, map_term f (prev a) = prev (map_term f a).\nProof.\nauto.\nQed.\n\n\nLemma map_rec :\n  forall A B (f : A -> B) k, map_term f (rec k) = rec (map_term f k).\nProof.\nauto.\nQed.\n\n\nLemma map_equal :\n  forall A B (f : A -> B) a m n, map_term f (equal a m n) = equal (map_term f a) (map_term f m) (map_term f n).\nProof.\nauto.\nQed.\n\n\nLemma map_triv :\n  forall A B (f : A -> B), map_term f triv = triv.\nProof.\nauto.\nQed.\n\n\nLemma map_eqtype :\n  forall A B (f : A -> B) m1 m2, map_term f (eqtype m1 m2) = eqtype (map_term f m1) (map_term f m2).\nProof.\nauto.\nQed.\n\n\nLemma map_subtype :\n  forall A B (f : A -> B) m1 m2, map_term f (subtype m1 m2) = subtype (map_term f m1) (map_term f m2).\nProof.\nauto.\nQed.\n\n\nLemma map_kuniv :\n  forall A B (f : A -> B) m, map_term f (kuniv m) = kuniv (map_term f m).\nProof.\nauto.\nQed.\n\n\nLemma map_all :\n  forall A B (f : A -> B) m1 m2 m3, map_term f (all m1 m2 m3) = all (map_term f m1) (map_term f m2) (map_term f m3).\nProof.\nauto.\nQed.\n\n\nLemma map_alltp :\n  forall A B (f : A -> B) m1, map_term f (alltp m1) = alltp (map_term f m1).\nProof.\nauto.\nQed.\n\n\nLemma map_exist :\n  forall A B (f : A -> B) m1 m2 m3, map_term f (exist m1 m2 m3) = exist (map_term f m1) (map_term f m2) (map_term f m3).\nProof.\nauto.\nQed.\n\n\nLemma map_mu :\n  forall A B (f : A -> B) m, map_term f (mu m) = mu (map_term f m).\nProof.\nauto.\nQed.\n\n\nLemma map_ispositive :\n  forall A B (f : A -> B) m, map_term f (ispositive m) = ispositive (map_term f m).\nProof.\nauto.\nQed.\n\n\nLemma map_isnegative :\n  forall A B (f : A -> B) m, map_term f (isnegative m) = isnegative (map_term f m).\nProof.\nauto.\nQed.\n\n\nLemma map_voidtp :\n  forall A B (f : A -> B), map_term f voidtp = voidtp.\nProof.\nauto.\nQed.\n\n\nLemma map_unittp :\n  forall A B (f : A -> B), map_term f unittp = unittp.\nProof.\nauto.\nQed.\n\n\nLemma map_cunit :\n  forall A B (f : A -> B), map_term f cunit = cunit.\nProof.\nauto.\nQed.\n\n\nLemma map_booltp :\n  forall A B (f : A -> B), map_term f booltp = booltp.\nProof.\nauto.\nQed.\n\n\nLemma map_btrue :\n  forall A B (f : A -> B), map_term f btrue = btrue.\nProof.\nauto.\nQed.\n\n\nLemma map_bfalse :\n  forall A B (f : A -> B), map_term f bfalse = bfalse.\nProof.\nauto.\nQed.\n\n\nLemma map_bite :\n  forall A B (f : A -> B) a m n, map_term f (bite a m n) = bite (map_term f a) (map_term f m) (map_term f n).\nProof.\nauto.\nQed.\n\n\nLemma map_prod :\n  forall A B (f : A -> B) m1 m2, map_term f (prod m1 m2) = prod (map_term f m1) (map_term f m2).\nProof.\nauto.\nQed.\n\n\nLemma map_sigma :\n  forall A B (f : A -> B) m1 m2, map_term f (sigma m1 m2) = sigma (map_term f m1) (map_term f m2).\nProof.\nauto.\nQed.\n\n\nLemma map_cpair :\n  forall A B (f : A -> B) m1 m2, map_term f (cpair m1 m2) = cpair (map_term f m1) (map_term f m2).\nProof.\nauto.\nQed.\n\n\nLemma map_cpi1 :\n  forall A B (f : A -> B) a, map_term f (cpi1 a) = cpi1 (map_term f a).\nProof.\nauto.\nQed.\n\n\nLemma map_cpi2 :\n  forall A B (f : A -> B) a, map_term f (cpi2 a) = cpi2 (map_term f a).\nProof.\nauto.\nQed.\n\n\nLemma map_ppair :\n  forall A B (f : A -> B) m1 m2, map_term f (ppair m1 m2) = ppair (map_term f m1) (map_term f m2).\nProof.\nauto.\nQed.\n\n\nLemma map_ppi1 :\n  forall A B (f : A -> B) a, map_term f (ppi1 a) = ppi1 (map_term f a).\nProof.\nauto.\nQed.\n\n\nLemma map_ppi2 :\n  forall A B (f : A -> B) a, map_term f (ppi2 a) = ppi2 (map_term f a).\nProof.\nauto.\nQed.\n\n\nLemma map_set :\n  forall A B (f : A -> B) m1 m2, map_term f (set m1 m2) = set (map_term f m1) (map_term f m2).\nProof.\nauto.\nQed.\n\n\nLemma map_quotient :\n  forall A B (f : A -> B) m1 m2, map_term f (quotient m1 m2) = quotient (map_term f m1) (map_term f m2).\nProof.\nauto.\nQed.\n\n\nLemma map_guard :\n  forall A B (f : A -> B) m1 m2, map_term f (guard m1 m2) = guard (map_term f m1) (map_term f m2).\nProof.\nauto.\nQed.\n\n\nLemma map_wt :\n  forall A B (f : A -> B) m1 m2, map_term f (wt m1 m2) = wt (map_term f m1) (map_term f m2).\nProof.\nauto.\nQed.\n\n\nHint Rewrite map_ext map_extt map_var map_univ map_cty map_con map_karrow map_arrow map_pi map_clam map_capp map_ctlam map_ctapp map_lam map_app map_intersect map_fut map_cnext map_cprev map_next map_prev map_rec map_equal map_triv map_eqtype map_subtype map_kuniv map_all map_alltp map_exist map_mu map_ispositive map_isnegative map_voidtp map_unittp map_cunit map_booltp map_btrue map_bfalse map_bite map_prod map_sigma map_cpair map_cpi1 map_cpi2 map_ppair map_ppi1 map_ppi2 map_wt map_set map_quotient map_guard : map.\n\n\nLemma map_sumbool :\n  forall A B (f : A -> B) P Q (c : {P} + {Q}) m n,\n    map_term f (if c then m else n) = if c then map_term f m else map_term f n.\nProof.\nintros A B f P Q c m n.\ndestruct c; auto.\nQed.\n\n\nHint Rewrite map_sumbool : map.\n\n\nFixpoint map_sub {A B : Type} (f : A -> B) (s : @sub A) {struct s} : @sub B\n  :=\n  match s with\n  | dot m s' => dot (map_term f m) (map_sub f s')\n  | sh i => sh i\n  end.\n\n\nLemma map_dot :\n  forall A B (f : A -> B) m s,\n    map_sub f (dot m s) = dot (map_term f m) (map_sub f s).\nProof.\nauto.\nQed.\n\n\nLemma map_sh :\n  forall A B (f : A -> B) i,\n    map_sub f (sh i) = sh i.\nProof.\nauto.\nQed.\n\n\nLemma map_id :\n  forall A B (f : A -> B),\n    map_sub f id = id.\nProof.\nauto.\nQed.\n\n\nLemma map_project :\n  forall A B (f : A -> B) s i,\n    map_term f (project s i) = project (map_sub f s) i.\nProof.\nintros A B f s i.\nrevert s.\ninduct i.\n\n(* 0 *)\n{\nintros s.\ncase s; clear s.\n  {\n  intros m s.\n  simpsub.\n  rewrite -> map_dot.\n  simpsub.\n  reflexivity.\n  }\n\n  {\n  intro i.\n  simpsub.\n  rewrite -> map_sh.\n  simpsub.\n  rewrite -> map_var.\n  reflexivity.\n  }\n}\n\n(* S *)\n{\nintros n IH s.\ncase s; clear s.\n  {\n  intros m s.\n  simpsub.\n  rewrite -> map_dot.\n  simpsub.\n  apply IH.\n  }\n\n  {\n  intro i.\n  simpsub.\n  rewrite -> map_sh.\n  simpsub.\n  rewrite -> map_var.\n  reflexivity.\n  }\n}\nQed.\n\n\nLemma map_traverse_and_row :\n  forall A B (f : A -> B) (resolve : nat -> nat -> term A),\n    (forall i m,\n       map_term f (traverse A resolve i m)\n       =\n       traverse B (fun i j => map_term f (resolve i j)) i (map_term f m))\n    /\\\n    (forall i a r,\n       map_row f (traverse_row A resolve i a r)\n       =\n       traverse_row B (fun i j => map_term f (resolve i j)) i a (map_row f r)).\nProof.\nintros A B f resolve.\nexploit\n  (syntax_ind A\n     (fun m =>\n        forall i,\n          map_term f (traverse A resolve i m)\n          =\n          traverse B (fun i j => map_term f (resolve i j)) i (map_term f m))\n     (fun a r =>\n        forall i,\n          map_row f (traverse_row A resolve i a r)\n          =\n          traverse_row B (fun i j => map_term f (resolve i j)) i a (map_row f r))) as Hprop;\n  intros; cbn; f_equal; eauto.\n\ncbn in Hprop.\ndestruct Hprop.\nsplit; intros; eauto.\nQed.\n\n\nLemma map_traverse :\n  forall A B (f : A -> B) (resolve : nat -> nat -> term A) i m,\n    map_term f (traverse A resolve i m)\n    =\n    traverse B (fun i j => map_term f (resolve i j)) i (map_term f m).\nProof.\nintros A B f resolve.\nexact (map_traverse_and_row A B f resolve andel).\nQed.\n\n\nLemma map_shift :\n  forall A B (f : A -> B) n (m : term A),\n    map_term f (shift n m)\n    =\n    shift n (map_term f m).\nProof.\nintros A B f n m.\nunfold shift.\netransitivity.\n  {\n  apply map_traverse.\n  }\nf_equal.\nfextensionality 2.\nintros i j.\nset (X := Compare_dec.lt_dec j i).\ndestruct X; auto.\nQed.\n\n\nLemma map_subst :\n  forall A B (f : A -> B) (s : @sub A) (m : term A),\n    map_term f (subst s m)\n    =\n    subst (map_sub f s) (map_term f m).\nProof.\nintros A B f s m.\nunfold subst.\netransitivity.\n  {\n  apply map_traverse.\n  }\nf_equal.\nfextensionality 2.\nintros i j.\nset (X := Compare_dec.lt_dec j i).\ndestruct X; auto.\nrewrite -> map_shift.\nrewrite -> map_project.\nreflexivity.\nQed.\n\n\nLemma map_trunc :\n  forall A B (f : A -> B) n (s : @sub A),\n    map_sub f (trunc n s) = trunc n (map_sub f s).\nProof.\nintros A B f n s.\nrevert s.\ninduct n; auto.\n(* S *)\nintros n IH s.\ncbn.\ndestruct s as [m s | i]; auto.\nrewrite -> map_dot.\napply IH.\nQed.\n\n\nLemma map_compose :\n  forall A B (f : A -> B) s1 s2,\n    map_sub f (compose s1 s2) = compose (map_sub f s1) (map_sub f s2).\nProof.\nintros A B f s1 s2.\nrevert s2.\ninduct s1.\n\n(* dot *)\n{\nintros m s1 IH s2.\nsimpsub.\nrewrite -> !map_dot.\nsimpsub.\nrewrite -> IH.\nrewrite -> map_subst.\nreflexivity.\n}\n\n(* sh *)\n{\nintros n s2.\ncbn.\napply map_trunc.\n}\nQed.\n\n\nLemma map_under :\n  forall A B (f : A -> B) i s,\n    map_sub f (under i s) = under i (map_sub f s).\nProof.\nintros A B f i s.\ninduct i.\n\n(* 0 *)\n{\nsimpsub.\nreflexivity.\n}\n\n(* S *)\n{\nintros n IH.\nrewrite -> !under_succ.\nrewrite -> map_dot.\nrewrite -> map_var.\nrewrite -> map_compose.\nrewrite -> IH.\nrewrite -> map_sh.\nreflexivity.\n}\nQed.\n\n\nLemma map_subst1 :\n  forall A B (f : A -> B) (m n : term A),\n    map_term f (subst1 m n)\n    =\n    subst1 (map_term f m) (map_term f n).\nProof.\nintros A B f m n.\nunfold subst1.\napply map_subst.\nQed.\n\n\nLemma map_sh1 :\n  forall A B (f : A -> B), map_sub f sh1 = sh1.\nProof.\nintros A B f.\nunfold sh1.\napply map_sh.\nQed.\n\n\nHint Rewrite map_dot map_sh map_id map_project map_subst map_compose map_under map_subst1 map_sh1 : map.\n\n\nDefinition map_hyp {A B : Type} (f : A -> B) (h : @hyp A) : @hyp B :=\n  match h with\n  | hyp_tpl => hyp_tpl\n  | hyp_tp => hyp_tp\n  | hyp_tml m => hyp_tml (map_term f m)\n  | hyp_tm m => hyp_tm (map_term f m)\n  | hyp_emp => hyp_emp\n  end.\n\n\nLemma map_tpl :\n  forall A B (f : A -> B),\n    map_hyp f hyp_tpl = hyp_tpl.\nProof.\nauto.\nQed.\n\n\nLemma map_tp :\n  forall A B (f : A -> B),\n    map_hyp f hyp_tp = hyp_tp.\nProof.\nauto.\nQed.\n\n\nLemma map_tml :\n  forall A B (f : A -> B) m,\n    map_hyp f (hyp_tml m) = hyp_tml (map_term f m).\nProof.\nauto.\nQed.\n\n\nLemma map_tm :\n  forall A B (f : A -> B) m,\n    map_hyp f (hyp_tm m) = hyp_tm (map_term f m).\nProof.\nauto.\nQed.\n\n\nLemma map_emp :\n  forall A B (f : A -> B),\n    map_hyp f hyp_emp = hyp_emp.\nProof.\nauto.\nQed.\n\n\nHint Rewrite map_tpl map_tp map_tml map_tm map_emp : map.\n\n\nDefinition map_ctx {A B : Type} (f : A -> B) :=\n  map (map_hyp f).\n\n\nLemma map_nil :\n  forall A B (f : A -> B),\n    map_ctx f nil = nil.\nProof.\nauto.\nQed.  \n\n\nLemma map_cons :\n  forall A B (f : A -> B) h G,\n    map_ctx f (cons h G) = cons (map_hyp f h) (map_ctx f G).\nProof.\nauto.\nQed.\n\n\nLemma map_appctx :\n  forall A B (f : A -> B) G1 G2,\n    map_ctx f (G2 ++ G1) = map_ctx f G2 ++ map_ctx f G1.\nProof.\nintros A B f G1 G2.\ninduct G2; auto.\nintros; cbn.\nf_equal; auto.\nQed.\n\n\nHint Rewrite map_nil map_cons map_appctx : map.\n\n\nLemma length_map_ctx :\n  forall A B (f : A -> B) (G : @context A),\n    length (map_ctx f G) = length G.\nProof.\nintros A B f G.\ninduct G; cbn; auto.\nQed.\n\n\nLemma map_index :\n  forall A B (f : A -> B) i G h,\n    index i G h\n    -> index i (map_ctx f G) (map_hyp f h).\nProof.\nintros A B f i G h H.\ninduct H.\n\n(* 0 *)\n{\nintros; apply index_0.\n}\n\n(* S *)\n{\nintros i h' G h _ IH.\ncbn.\napply index_S; auto.\n}\nQed.\n\n\nLemma map_promote_hyp :\n  forall A B (f : A -> B) h,\n    map_hyp f (promote_hyp h) = promote_hyp (map_hyp f h).\nProof.\nintros A B f h.\ninduct h; auto.\nQed.\n\n\nLemma map_promote :\n  forall A B (f : A -> B) G,\n    map_ctx f (promote G) = promote (map_ctx f G).\nProof.\nintros A B f G.\ninduct G; auto.\nintros h G IH.\ncbn.\nf_equal; auto using map_promote_hyp.\nQed.\n\n\nHint Rewrite map_promote_hyp map_promote : map.\n\n\nDefinition map_jud {A B : Type} (f : A -> B) (J : @judgement A) : @judgement B :=\n  match J with\n  | deq m1 m2 m3 => deq (map_term f m1) (map_term f m2) (map_term f m3)\n  end.\n\n\nLemma map_deq :\n  forall A B (f : A -> B) m1 m2 m3,\n    map_jud f (deq m1 m2 m3) = deq (map_term f m1) (map_term f m2) (map_term f m3).\nProof.\nauto.\nQed.\n\n\nHint Rewrite map_deq : map.\n\n\nLtac simpmap :=\n  autorewrite with map.\n\n\nLtac simpmapin H :=\n  autorewrite with map in H.\n\n\nLemma map_substh :\n  forall A B (f : A -> B) (s : sub) (h : @hyp A),\n    map_hyp f (substh s h) = substh (map_sub f s) (map_hyp f h).\nProof.\nintros A B f s h.\ncases h; intros; simpsub; simpmap; auto.\nQed.\n\n\nLemma map_substctx :\n  forall A B (f : A -> B) (s : sub) (G : @context A),\n    map_ctx f (substctx s G) = substctx (map_sub f s) (map_ctx f G).\nProof.\nintros A B f s G.\ninduct G; auto.\nintros h G IH.\ncbn.\nf_equal; auto.\nrewrite -> map_substh.\nsimpmap.\nrewrite -> length_map_ctx.\nreflexivity.\nQed.\n\n\nLemma map_substj :\n  forall A B (f : A -> B) (s : sub) (J : @judgement A),\n    map_jud f (substj s J) = substj (map_sub f s) (map_jud f J).\nProof.\nintros A B f s J.\ndestruct J as [m n a].\nsimpmap; simpsub.\nsimpmap.\nreflexivity.\nQed.\n\n\nHint Rewrite map_substh map_substctx map_substj : map.\n\n\nLemma map_hygiene :\n  forall A B (f : A -> B) P (m : term A),\n    hygiene P m\n    -> hygiene P (map_term f m).\nProof.\nintros A B f P m Hcl.\ninduct Hcl\n  using (fun X => hygiene_mut_ind _ X\n           (fun P a r => hygiene_row P (map_row f r))).\n\n(* var *)\n{\nintros P i H.\napply hygiene_var; auto.\n}\n\n(* oper *)\n{\nintros P a th r _ IH.\n*cbn.\napply hygiene_oper; auto.\n}\n\n(* nil *)\n{\nintros; apply hygiene_nil.\n}\n\n(* cons *)\n{\nintros P i a m r _ IH1 _ IH2.\ncbn.\napply hygiene_cons; auto.\n}\nQed.\n\n\nLemma map_hygiene_conv :\n  forall A B (f : A -> B) P (m : term A),\n    hygiene P (map_term f m)\n    -> hygiene P m.\nProof.\nintros A B f P m Hcl.\nremember (map_term f m) as m' eqn:Heq.\nrevert m Heq.\ninduct Hcl\n  using (fun X => hygiene_mut_ind _ X\n           (fun P a r' => forall r, r' = map_row f r -> hygiene_row P r)).\nProof.\n\n(* var *)\n{\nintros P i H m.\ncases m.\n2:{\n  intros; discriminate.\n  }\nintros ? Heq.\ncbn in Heq.\ninjection Heq.\nintros <-.\napply hygiene_var; auto.\n}\n\n(* oper *)\n{\nintros P a' th' r' _ IH m.\ncases m.\n  {\n  intros; discriminate.\n  }\nintros a th r Heq.\ncbn in Heq.\ninjection Heq.\nintros H1 H2 <-.\ninjectionT H1.\nintros ->.\ninjectionT H2.\nintros ->.\napply hygiene_oper; auto.\n}\n\n(* nil *)\n{\nintros P r.\ncases r.\nintros _.\napply hygiene_nil.\n}\n\n(* cons *)\n{\nintros P i' a' m' r' _ IH1 _ IH2 r.\ncases r.\nintros i a m r Heq Heq'.\ninjection Heq.\nintros <- <-.\nso (proof_irrelevance _ Heq (eq_refl _)); subst Heq.\ncbn in Heq'.\ninjection Heq'.\nintros H ->.\ninjectionT H.\nintros ->.\napply hygiene_cons; auto.\n}\nQed.\n\n\nLemma map_hygieneh :\n  forall A B (f : A -> B) P (h : @hyp A),\n    hygieneh P h\n    -> hygieneh P (map_hyp f h).\nProof.\nintros A B f P h H.\ncases H; intros; simpmap;\n[apply hygieneh_tpl | apply hygieneh_tp | apply hygieneh_tml | apply hygieneh_tm | apply hygieneh_emp]; auto using map_hygiene.\nQed.\n\n\nLemma map_hygieneh_conv :\n  forall A B (f : A -> B) P (h : @hyp A),\n    hygieneh P (map_hyp f h)\n    -> hygieneh P h.\nProof.\nintros A B f P h H.\nrevert H.\ncases h; intros; [apply hygieneh_tpl | apply hygieneh_tp | apply hygieneh_tml | apply hygieneh_tm | apply hygieneh_emp].\n  {\n  simpmapin H.\n  invert H.\n  eauto using map_hygiene_conv.\n  }\n\n  {\n  simpmapin H.\n  invert H.\n  eauto using map_hygiene_conv.\n  }\nQed.\n\n\nLemma map_term_sh1_under_form :\n  forall A B i (f : A -> B) (m : term A) (n : term B),\n    map_term f m = subst (under i sh1) n\n    -> exists m',\n         m = subst (under i sh1) m'\n         /\\ n = map_term f m'.\nProof.\nintros A B i f m n Heq.\nassert (hygiene (fun j => j <> i) (subst (under i sh1) n)) as Hhyg.\n  {\n  eapply hygiene_shift_under'.\n  refine (hygiene_weaken _#4 _ (hygiene_okay _ _)).\n  intros x _.\n  omega.\n  }\nrewrite <- Heq in Hhyg.\nso (map_hygiene_conv _#5 Hhyg) as Hhyg'.\nso (subst_into_absent_single _#3 unittp Hhyg') as Heq'.\nsimpsubin Heq'.\nexists (subst (under i (dot unittp id)) m).\nsplit.\n  {\n  rewrite <- subst_compose.\n  rewrite <- compose_under.\n  simpsub.\n  auto.\n  }\n\n  {\n  so (f_equal (fun z => subst (under i (dot unittp id)) z) Heq) as Heq''.\n  cbn in Heq''.\n  rewrite <- subst_compose in Heq''.\n  rewrite <- compose_under in Heq''.\n  simpsubin Heq''.  \n  rewrite <- Heq''.\n  rewrite -> map_subst.\n  simpmap.\n  reflexivity.\n  }\nQed.\n\n\nLemma map_term_sh1_form :\n  forall A B (f : A -> B) (m : term A) (n : term B),\n    map_term f m = subst sh1 n\n    -> exists m',\n         m = subst sh1 m'\n         /\\ n = map_term f m'.\nProof.\nintros A B f m n H.\napply (map_term_sh1_under_form A B 0 f m n); auto.\nQed.\n\n\nLemma map_term_sh_form :\n  forall A B i (f : A -> B) (m : term A) (n : term B),\n    map_term f m = subst (sh i) n\n    -> exists m',\n         m = subst (sh i) m'\n         /\\ n = map_term f m'.\nProof.\nintros A B i f m n H.\nrevert m n H.\ninduct i.\n\n(* 0 *)\n{\nintros m n H.\nsimpsubin H.\nsubst n.\nexists m.\nsplit; auto.\nsimpsub; auto.\n}\n\n(* S *)\n{\nintros i IH m n Heq.\nreplace (S i) with (i + 1) in Heq by omega.\nrewrite <- compose_sh_sh in Heq.\nrewrite -> subst_compose in Heq.\nso (map_term_sh1_form _#5 Heq) as (m' & -> & Heq').\nsymmetry in Heq'.\nso (IH _ _ Heq') as (m'' & -> & Heq'').\nexists m''.\nsplit; auto.\nsimpsub.\nreplace (i + 1) with (S i) by omega.\nreflexivity.\n}\nQed.\n\n\nDefinition inverses {A B : Type} (f : B -> A) (g : A -> B) : Prop\n  :=\n  forall x, f (g x) = x.\n\n\nDefinition injective {A B : Type} (f : A -> B) : Prop\n  :=\n  forall x y, f x = f y -> x = y.\n\n\nLemma inverses_impl_injective :\n  forall A B f g,\n    @inverses A B f g\n    -> injective g.\nProof.\nintros A B f g Hinv x y Heq.\nso (f_equal f Heq) as Heq'.\nrewrite -> !Hinv in Heq'.\nauto.\nQed.\n\n\nLemma map_operator_inv :\n  forall A B f g,\n    @inverses A B f g\n    -> forall a, inverses (@map_operator _ _ f a) (@map_operator _ _ g a).\nProof.\nintros A B f g Hinv a th.\ncases th; try (intros; auto; done).\n\n(* ext *)\n{\nintros a.\ncbn.\nrewrite -> Hinv.\nreflexivity.\n}\n\n(* extt *)\n{\nintros a.\ncbn.\nrewrite -> Hinv.\nreflexivity.\n}\nQed.\n\n\nLemma map_operator_inj :\n  forall A B (f : A -> B),\n    injective f\n    -> forall a, injective (@map_operator _ _ f a).\nProof.\nintros A B f Hinj a th th' Heq.\nset (a' := a) in th'.\nassert (eq_dep _ (operator B) a (map_operator f th) a' (@map_operator _ _ f a' th')) as Heq'.\n  {\n  apply eq_impl_eq_dep_snd; auto.\n  }\ncut (eq_dep _ (operator A) a th a' th').\n  {\n  apply eq_dep_impl_eq_snd; auto.\n  }\nrenameover Heq' into Heq.\nassert (a = a') as Heqa by reflexivity.\nclearbody a'.\nrevert Heqa Heq.\ncases th; cases th';\ntry (intros; discriminate Heqa);\ntry (intros; so (eq_dep_impl_eq_snd _#5 Heq) as Heqth; discriminate Heqth);\ntry (intros; apply eq_dep_refl; done);\ntry (intros; apply eq_impl_eq_dep_snd; f_equal; cbn in Heq; injection (eq_dep_impl_eq_snd _#5 Heq); auto; done).\nQed.\n\n\nLemma map_term_inv :\n  forall A B f g,\n    @inverses A B f g\n    -> inverses (map_term f) (map_term g).\nProof.\nintros A B f g Hinv m.\ninduct m using\n  (fun z => term_mut_ind _ z\n     (fun a r => map_row f (map_row g r) = r)); auto.\n\n(* oper *)\n{\nintros a th r IH.\ncbn.\nrewrite -> map_operator_inv; auto.\nrewrite -> IH.\nreflexivity.\n}\n\n(* cons *)\n{\nintros i a m IH1 r IH2.\ncbn.\nrewrite -> IH2.\nrewrite -> IH1.\nreflexivity.\n}\nQed.\n\n\nLemma map_term_inj :\n  forall A B (f : A -> B),\n    injective f\n    -> injective (map_term f).\nProof.\nintros A B f Hinj m n Heq.\nrevert n Heq.\ninduct m using\n  (fun z => term_mut_ind _ z\n     (fun a r => forall s, map_row f r = map_row f s -> r = s)).\n\n(* var *)\n{\nintros i n Heq.\ndestruct n as [j |]; cbn in Heq; [| discriminate Heq].\ninjection Heq.\nauto.\n}\n\n(* oper *)\n{\nintros a th r IH n Heq.\ndestruct n as [| a' th' r']; cbn in Heq; [discriminate Heq |].\ninjection Heq.\nintros H1 H2 <-.\ninjectionT H1.\ninjectionT H2.\nintros Heqth Heqr.\nf_equal.\n  {\n  eapply map_operator_inj; eauto.\n  }\napply IH; auto.\n}\n\n(* nil *)\n{\nintros s H.\nso (row_nil_invert _ s); subst s.\nreflexivity.\n}\n\n(* cons *)\n{\nintros i a m IH1 r IH2 s Heq.\nso (row_cons_invert _#3 s) as (m' & r' & ->).\ncbn in Heq.\ninjectionc Heq.\nintros H Heqm.\ninjectionT H.\nintros Heqr.\nf_equal; auto.\n}\nQed.\n\n\nLemma map_reduce :\n  forall A B (f : A -> B) (m n : term A),\n    reduce m n\n    -> reduce (map_term f m) (map_term f n).\nProof.\nintros A B f m n Hmn.\ninduct Hmn using\n  (fun z => reduce_mut_ind _ z\n     (fun a r s => reducer (map_row f r) (map_row f s)));\ntry (intros; cbn; eauto using reduce_var, reduce_oper, reducer_nil, reducer_cons; done).\n\n(* tapp_beta *)\n{\nintros m m' n n' _ IH1 _ IH2.\nsimpmap.\napply reduce_app_beta; auto.\n}\n\n(* prev_beta *)\n{\nintros m m' _ IH.\nsimpmap.\napply reduce_prev_beta; auto.\n}\n\n(* bite_beta1 *)\n{\nintros n n' p _ IH.\nsimpmap.\napply reduce_bite_beta1; auto.\n}\n\n(* bite_beta2 *)\n{\nintros n n' p _ IH.\nsimpmap.\napply reduce_bite_beta2; auto.\n}\n\n(* ppi1_beta *)\n{\nintros m m' n _ IH.\nsimpmap.\napply reduce_ppi1_beta; auto.\n}\n\n(* ppi2_beta *)\n{\nintros m m' n _ IH.\nsimpmap.\napply reduce_ppi2_beta; auto.\n}\nQed.\n\n\nLemma map_reduces :\n  forall A B (f : A -> B) (m n : term A),\n    star reduce m n\n    -> star reduce (map_term f m) (map_term f n).\nProof.\nintros A B f m n H.\neapply star_map; eauto using map_reduce.\nQed.\n\n\nLemma map_step :\n  forall A B (f : A -> B) (m n : term A),\n    step m n\n    -> step (map_term f m) (map_term f n).\nProof.\nintros A B f m n Hmn.\ninduct Hmn;\ntry (intros; simpmap; eauto using step_app1, step_app2, step_prev1, step_prev2, step_bite1, step_bite2, step_bite3, step_ppi11, step_ppi12, step_ppi21, step_ppi22; done).\nQed.\n\n\nLemma map_steps :\n  forall A B (f : A -> B) (m n : term A),\n    star step m n\n    -> star step (map_term f m) (map_term f n).\nProof.\nintros A B f m n H.\neapply star_map; eauto using map_step.\nQed.\n\n\nLemma map_eq_oper_invert :\n  forall A B (f : A -> B) m a th r,\n    map_term f m = oper a th r\n    -> exists th' r',\n         m = oper a th' r'\n         /\\ map_operator f th' = th\n         /\\ map_row f r' = r.\nProof.\nintros A B f m a th r Heq.\ndestruct m as [n | a' th' r'].\n  {\n  cbn in Heq.\n  discriminate Heq.\n  }\ncbn in Heq.\ninjection Heq.\nintros Heqr Heqth ->.\nexists th', r'.\nso (existT_injection_2 _#5 Heqth).\nsubst th.\nso (existT_injection_2 _#5 Heqr).\nsubst r.\nauto.\nQed.\n\n\nLemma map_operator_same :\n  forall A B (f : A -> B) a (th : operator A a) (th' : operator B a),\n    map_operator f th = th'\n    -> same_operator a a th th'.\nProof.\nintros A B f a th' th Heqth.\nrevert th Heqth.\ninduct th';\ntry (intros;\n     so (eq_impl_eq_dep _#6 (eq_refl _) Heqth) as Heq;\n     clear Heqth;\n     revert Heq;\n     induct th;\n     try (intros;\n          injectionT Heq;\n          intros; discriminate);\n     intros;\n     eauto with same_operator;\n     so (eq_dep_impl_eq_snd _#5 Heq) as Heq';\n     cbn in Heq';\n     injection Heq';\n     intros; subst;\n     eauto with same_operator;\n     done).\nQed.\n\n\nLemma map_eq_lam_invert :\n  forall A B (f : A -> B) m l,\n    map_term f m = lam l\n    -> exists l',\n         m = lam l'\n         /\\ map_term f l' = l.\nProof.\nintros A B f m l Heq.\nso (map_eq_oper_invert _#7 Heq) as (th & r & -> & Heqth & Heqr).\nso (row_cons_invert _ 1 nil r) as (l' & r' & ->).\nso (row_nil_invert _ r'); subst r'.\nexists l'.\nsplit.\n  {\n  unfold lam.\n  f_equal.\n  so (map_operator_same _#6 Heqth) as H.\n  invert H.\n  auto.\n  }\n\n  {\n  cbn in Heqr.\n  injection Heqr.\n  auto.\n  }\nQed.\n\n\nLemma map_eq_next_invert :\n  forall A B (f : A -> B) m n,\n    map_term f m = next n\n    -> exists n',\n         m = next n'\n         /\\ map_term f n' = n.\nProof.\nintros A B f m n Heq.\nso (map_eq_oper_invert _#7 Heq) as (th & r & -> & Heqth & Heqr).\nso (row_invert_auto _ _ r) as H; cbn in H.\ndestruct H as (n' & ->).\nexists n'.\nsplit.\n  {\n  unfold next.\n  f_equal.\n  so (map_operator_same _#6 Heqth) as H.\n  invert H.\n  auto.\n  }\n\n  {\n  cbn in Heqr.\n  injection Heqr.\n  auto.\n  }\nQed.\n\n\nLemma map_eq_prev_invert :\n  forall A B (f : A -> B) m n,\n    map_term f m = prev n\n    -> exists n',\n         m = prev n'\n         /\\ map_term f n' = n.\nProof.\nintros A B f m n Heq.\nso (map_eq_oper_invert _#7 Heq) as (th & r & -> & Heqth & Heqr).\nso (row_invert_auto _ _ r) as H; cbn in H.\ndestruct H as (n' & ->).\nexists n'.\nsplit.\n  {\n  unfold prev.\n  f_equal.\n  so (map_operator_same _#6 Heqth) as H.\n  invert H.\n  auto.\n  }\n\n  {\n  cbn in Heqr.\n  injection Heqr.\n  auto.\n  }\nQed.\n\n\nLemma map_eq_triv_invert :\n  forall A B (f : A -> B) m,\n    map_term f m = triv\n    -> m = triv.\nProof.\nintros A B f m Heq.\nso (map_eq_oper_invert _#7 Heq) as (th & r & -> & Heqth & _).\nunfold triv.\nf_equal.\n2:{\n  so (row_nil_invert _ r); subst r.\n  reflexivity.\n  }\nso (map_operator_same _#6 Heqth) as H.\ninvert H.\nintros <-.\nreflexivity.\nQed.\n\n\nLemma map_eq_bite_invert :\n  forall A B (f : A -> B) m n p q,\n    map_term f m = bite n p q\n    -> exists n' p' q',\n         m = bite n' p' q'\n         /\\ map_term f n' = n\n         /\\ map_term f p' = p\n         /\\ map_term f q' = q.\nProof.\nintros A B f m n p q Heq.\nso (map_eq_oper_invert _#7 Heq) as (th & r & -> & Heqth & Heqr).\nso (row_invert_auto _ _ r) as H; cbn in H.\ndestruct H as (n' & p' & q' & ->).\nexists n', p', q'.\nsplit.\n  {\n  unfold next.\n  f_equal.\n  so (map_operator_same _#6 Heqth) as H.\n  invert H.\n  intros <-.\n  auto.\n  }\n\n  {\n  cbn in Heqr.\n  injection Heqr.\n  auto.\n  }\nQed.\n\n\nLemma map_eq_btrue_invert :\n  forall A B (f : A -> B) m,\n    map_term f m = btrue\n    -> m = btrue.\nProof.\nintros A B f m Heq.\nso (map_eq_oper_invert _#7 Heq) as (th & r & -> & Heqth & _).\nunfold btrue.\nf_equal.\n2:{\n  so (row_nil_invert _ r); subst r.\n  reflexivity.\n  }\nso (map_operator_same _#6 Heqth) as H.\ninvert H.\nintros <-.\nreflexivity.\nQed.\n\n\nLemma map_eq_bfalse_invert :\n  forall A B (f : A -> B) m,\n    map_term f m = bfalse\n    -> m = bfalse.\nProof.\nintros A B f m Heq.\nso (map_eq_oper_invert _#7 Heq) as (th & r & -> & Heqth & _).\nunfold bfalse.\nf_equal.\n2:{\n  so (row_nil_invert _ r); subst r.\n  reflexivity.\n  }\nso (map_operator_same _#6 Heqth) as H.\ninvert H.\nintros <-.\nreflexivity.\nQed.\n\n\nLemma map_eq_ppair_invert :\n  forall A B (f : A -> B) m n p,\n    map_term f m = ppair n p\n    -> exists n' p',\n         m = ppair n' p'\n         /\\ map_term f n' = n\n         /\\ map_term f p' = p.\nProof.\nintros A B f m n p Heq.\nso (map_eq_oper_invert _#7 Heq) as (th & r & -> & Heqth & Heqr).\nso (row_invert_auto _ _ r) as H; cbn in H.\ndestruct H as (n' & p' & ->).\nexists n', p'.\nsplit.\n  {\n  unfold next.\n  f_equal.\n  so (map_operator_same _#6 Heqth) as H.\n  invert H.\n  intros <-.\n  auto.\n  }\n\n  {\n  cbn in Heqr.\n  injection Heqr.\n  auto.\n  }\nQed.\n\n\nLemma map_eq_ppi1_invert :\n  forall A B (f : A -> B) m n,\n    map_term f m = ppi1 n\n    -> exists n',\n         m = ppi1 n'\n         /\\ map_term f n' = n.\nProof.\nintros A B f m n Heq.\nso (map_eq_oper_invert _#7 Heq) as (th & r & -> & Heqth & Heqr).\nso (row_invert_auto _ _ r) as H; cbn in H.\ndestruct H as (n' & ->).\nexists n'.\nsplit.\n  {\n  unfold ppi1.\n  f_equal.\n  so (map_operator_same _#6 Heqth) as H.\n  invert H.\n  auto.\n  }\n\n  {\n  cbn in Heqr.\n  injection Heqr.\n  auto.\n  }\nQed.\n\n\nLemma map_eq_ppi2_invert :\n  forall A B (f : A -> B) m n,\n    map_term f m = ppi2 n\n    -> exists n',\n         m = ppi2 n'\n         /\\ map_term f n' = n.\nProof.\nintros A B f m n Heq.\nso (map_eq_oper_invert _#7 Heq) as (th & r & -> & Heqth & Heqr).\nso (row_invert_auto _ _ r) as H; cbn in H.\ndestruct H as (n' & ->).\nexists n'.\nsplit.\n  {\n  unfold ppi2.\n  f_equal.\n  so (map_operator_same _#6 Heqth) as H.\n  invert H.\n  auto.\n  }\n\n  {\n  cbn in Heqr.\n  injection Heqr.\n  auto.\n  }\nQed.\n\n\nLemma map_eq_ext_invert :\n  forall A B (f : A -> B) m x,\n    map_term f m = ext x\n    -> exists y,\n         m = ext y\n         /\\ f y = x.\nProof.\nintros A B f m x Heq.\nso (map_eq_oper_invert _#7 Heq) as (th & r & -> & Heqth & Heqr).\nso (row_invert_auto _ _ r) as H; cbn in H.\nsubst r.\nclear Heq Heqr.\nrevert Heqth.\ncases th; try (intros; discriminate Heqth).\nintros y Heq.\ncbn in Heq.\ninjection Heq.\nintros <-.\nexists y; auto.\nQed.\n\n\nLemma map_step_form :\n  forall A B (f : A -> B) (m : term A) (n : term B),\n    step (map_term f m) n\n    -> exists p,\n         n = map_term f p\n         /\\ step m p.\nProof.\nintros A B f m n H.\nremember (map_term f m) as x eqn:Heqx.\nrevert m Heqx.\ninduct H.\n\n(* tapp1 *)\n{\nintros m1 m1' m2 _ IH mm Heqx.\nso (map_eq_oper_invert _#7 (eqsymm Heqx)) as (th & r & -> & Heqth & Heqr).\nclear Heqx.\nrevert Heqth.\ncases th; try (intros; discriminate Heqth).\nintros _.\nso (row_2_invert _#3 r) as (n1 & n2 & ->).\ncbn in Heqr.\ninjectionc Heqr.\nintros <- <-.\nso (IH n1 (eq_refl _)) as (n1' & -> & Hstep).\nexists (app n1' n2).\nsplit.\n  {\n  simpmap.\n  reflexivity.\n  }\n\n  {\n  apply step_app1; auto.\n  }\n}\n\n(* tapp2 *)\n{\nintros m1 m2 mm Heqx.\nso (map_eq_oper_invert _#7 (eqsymm Heqx)) as (th & r & -> & Heqth & Heqr).\nclear Heqx.\nrevert Heqth.\ncases th; try (intros; discriminate Heqth).\nintros _.\nso (row_2_invert _#3 r) as (a & p' & ->).\ncbn in Heqr.\ninjectionc Heqr.\nintros <- Heqa.\nso (map_eq_lam_invert _#5 Heqa) as (m' & -> & <-).\nclear Heqa.\nfold (app (lam m') p').\nexists (subst1 p' m').\nsplit.\n  {\n  simpmap.\n  reflexivity.\n  }\n\n  {\n  apply step_app2.\n  }\n}\n\n(* prev1 *)\n{\nintros m m' _ IH mm Heq.\nso (map_eq_prev_invert _#5 (eqsymm Heq)) as (n & -> & Hn).\nso (IH _ (eqsymm Hn)) as (p & -> & Hp).\nexists (prev p).\nsplit; auto.\napply step_prev1; auto.\n}\n\n(* prev2 *)\n{\nintros m m' Heq.\nso (map_eq_prev_invert _#5 (eqsymm Heq)) as (n & -> & Hn).\nso (map_eq_next_invert _#5 Hn) as (p & -> & Hp).\nexists p.\nsplit; auto.\napply step_prev2.\n}\n\n(* bite1 *)\n{\nintros m1 m1' m2 m3 _ IH mm Heq.\nso (map_eq_bite_invert _#7 (eqsymm Heq)) as (n & p & q & -> & Hn & Hp & Hq).\nso (IH _ (eqsymm Hn)) as (n' & -> & Hn').\nexists (bite n' p q).\nsplit.\n  {\n  simpmap.\n  f_equal; auto.\n  }\n\n  {\n  apply step_bite1; auto.\n  }\n}\n\n(* bite2 *)\n{\nintros m1 m2 mm Heq.\nso (map_eq_bite_invert _#7 (eqsymm Heq)) as (n & p & q & -> & Hn & Hp & Hq).\nso (map_eq_btrue_invert _#4 Hn); subst n.\nexists p.\nsplit; auto.\napply step_bite2.\n}\n\n(* bite3 *)\n{\nintros m1 m2 mm Heq.\nso (map_eq_bite_invert _#7 (eqsymm Heq)) as (n & p & q & -> & Hn & Hp & Hq).\nso (map_eq_bfalse_invert _#4 Hn); subst n.\nexists q.\nsplit; auto.\napply step_bite3.\n}\n\n(* ppi11 *)\n{\nintros m m' _ IH mm Heq.\nso (map_eq_ppi1_invert _#5 (eqsymm Heq)) as (n & -> & Hn).\nso (IH _ (eqsymm Hn)) as (p & -> & Hp).\nexists (ppi1 p).\nsplit; auto.\napply step_ppi11; auto.\n}\n\n(* ppi12 *)\n{\nintros m m' mm Heq.\nso (map_eq_ppi1_invert _#5 (eqsymm Heq)) as (n & -> & Hn).\nso (map_eq_ppair_invert _#6 Hn) as (p & q & -> & Hp & Hq).\nexists p.\nsplit; auto.\napply step_ppi12.\n}\n\n(* ppi21 *)\n{\nintros m m' _ IH mm Heq.\nso (map_eq_ppi2_invert _#5 (eqsymm Heq)) as (n & -> & Hn).\nso (IH _ (eqsymm Hn)) as (p & -> & Hp).\nexists (ppi2 p).\nsplit; auto.\napply step_ppi21; auto.\n}\n\n(* ppi22 *)\n{\nintros m m' mm Heq.\nso (map_eq_ppi2_invert _#5 (eqsymm Heq)) as (n & -> & Hn).\nso (map_eq_ppair_invert _#6 Hn) as (p & q & -> & Hp & Hq).\nexists q.\nsplit; auto.\napply step_ppi22.\n}\nQed.\n\n\nLemma map_steps_form :\n  forall A B (f : A -> B) (m : term A) (n : term B),\n    star step (map_term f m) n\n    -> exists p,\n         n = map_term f p\n         /\\ star step m p.\nProof.\nintros A B f m n H.\nremember (map_term f m) as x eqn:Heqx.\nrevert m Heqx.\ninduct H.\n\n(* refl *)\n{\nintros x m ->.\nexists m.\nauto using star_refl.\n}\n\n(* step *)\n{\nintros m n p Hmn _ IH m' ->.\nso (map_step_form _#5 Hmn) as (n' & -> & Hmn').\nso (IH n' (eq_refl _)) as (p' & -> & Hnp').\nexists p'.\nsplit; auto.\neapply star_step; eauto.\n}\nQed.\n\n\nLemma map_reduce_form :\n  forall A B (f : A -> B) (m : term A) (n : term B),\n    reduce (map_term f m) n\n    -> exists p,\n         n = map_term f p\n         /\\ reduce m p.\nProof.\nintros A B f m n H.\nremember (map_term f m) as x eqn:Heqx.\nrevert m Heqx.\ninduct H using\n  (fun z => reduce_mut_ind _ z\n     (fun a r s => forall r', r = map_row f r' -> exists s', s = map_row f s' /\\ reducer r' s')).\n\n(* var *)\n{\nintros i m.\ncases m; try (intros; discriminate Heqx).\nintros j Heq.\nrewrite -> map_var in Heq.\ninjection Heq.\nintros <-.\nexists (var i).\nsplit; auto.\napply reduce_var.\n}\n\n(* oper *)\n{\nintros a th r s _ IH m.\ncases m; try (intros; discriminate Heqx).\nintros a' th' r' Heq.\ncbn in Heq.\ninjection Heq.\nintros Heqr Heqth <-.\nso (existT_injection_2 _#5 Heqth); subst th.\nso (existT_injection_2 _#5 Heqr); subst r.\nclear Heq Heqr Heqth.\nso (IH _ (eq_refl _)) as (s' & -> & Hrs).\nexists (oper a th' s').\nsplit; auto.\napply reduce_oper; auto.\n}\n\n(* tapp_beta *)\n{\nintros m n p q Hmn IH1 Hpq IH2 x Heqx.\nso (map_eq_oper_invert _#7 (eqsymm Heqx)) as (th & r & -> & Heqth & Heqr).\nclear Heqx.\nrevert Heqth.\ncases th; try (intros; discriminate Heqth).\nintros _.\nso (row_2_invert _#3 r) as (a & p' & ->).\ncbn in Heqr.\ninjectionc Heqr.\nintros <- Heqa.\nso (map_eq_lam_invert _#5 Heqa) as (m' & -> & <-).\nclear Heqa.\nfold (app (lam m') p').\nso (IH1 _ (eq_refl _)) as (n' & -> & Hmn').\nso (IH2 _ (eq_refl _)) as (q' & -> & Hpq').\nexists (subst1 q' n').\nsplit.\n  {\n  symmetry.\n  apply map_subst.\n  }\n\n  {\n  apply reduce_app_beta; auto.\n  }\n}\n\n(* prev_beta *)\n{\nintros m n Hmn IH x Heqx.\nso (map_eq_prev_invert _#5 (eqsymm Heqx)) as (y & -> & Heqy).\nso (map_eq_next_invert _#5 Heqy) as (p & -> & Hp).\nso (IH _ (eqsymm Hp)) as (q & -> & Hq).\nexists q.\nsplit; auto.\napply reduce_prev_beta; auto.\n}\n\n(* bite_beta1 *)\n{\nintros m1 m1' m2 _ IH m Heqx.\nso (map_eq_bite_invert _#7 (eqsymm Heqx)) as (n & p & q & -> & Hn & Hp & Hq).\nso (map_eq_btrue_invert _#4 Hn); subst n.\nso (IH _ (eqsymm Hp)) as (p' & -> & Hp').\nexists p'.\nsplit; auto.\napply reduce_bite_beta1; auto.\n}\n\n(* bite_beta2 *)\n{\nintros m1 m1' m2 _ IH m Heqx.\nso (map_eq_bite_invert _#7 (eqsymm Heqx)) as (n & p & q & -> & Hn & Hp & Hq).\nso (map_eq_bfalse_invert _#4 Hn); subst n.\nso (IH _ (eqsymm Hq)) as (q' & -> & Hq').\nexists q'.\nsplit; auto.\napply reduce_bite_beta2; auto.\n}\n\n(* ppi1_beta *)\n{\nintros m1 m1' m2 _ IH x Heqx.\nso (map_eq_ppi1_invert _#5 (eqsymm Heqx)) as (n & -> & Hn).\nso (map_eq_ppair_invert _#6 Hn) as (p & q & -> & Hp & Hq).\nso (IH _ (eqsymm Hp)) as (p' & -> & Hp').\nexists p'.\nsplit; auto.\napply reduce_ppi1_beta; auto.\n}\n\n(* ppi2_beta *)\n{\nintros m1 m1' m2 _ IH x Heqx.\nso (map_eq_ppi2_invert _#5 (eqsymm Heqx)) as (n & -> & Hn).\nso (map_eq_ppair_invert _#6 Hn) as (p & q & -> & Hp & Hq).\nso (IH _ (eqsymm Hq)) as (p' & -> & Hp').\nexists p'.\nsplit; auto.\napply reduce_ppi2_beta; auto.\n}\n\n(* nil *)\n{\nintros r' H.\nso (row_nil_invert _ r'); subst r'.\nexists rw_nil.\nauto using reducer_nil.\n}\n\n(* cons *)\n{\nintros i a m n r s Hmn IH1 Hrs IH2 x Heq.\nso (row_cons_invert _#3 x) as (m' & r' & ->).\ncbn in Heq.\ninjectionc Heq.\nintros Heqr ->.\ninjectionT Heqr.\nintros ->.\nso (IH1 _ (eq_refl _)) as (n' & -> & Hmn').\nso (IH2 _ (eq_refl _)) as (s' & -> & Hrs').\nexists (rw_cons n' s').\nsplit; eauto using reducer_cons.\n}\nQed.\n\n\nLemma map_reduces_form :\n  forall A B (f : A -> B) (m : term A) (n : term B),\n    star reduce (map_term f m) n\n    -> exists p,\n         n = map_term f p\n         /\\ star reduce m p.\nProof.\nintros A B f m n H.\nremember (map_term f m) as x eqn:Heqx.\nrevert m Heqx.\ninduct H.\n\n(* refl *)\n{\nintros x m ->.\nexists m.\nauto using star_refl.\n}\n\n(* step *)\n{\nintros m n p Hmn _ IH m' ->.\nso (map_reduce_form _#5 Hmn) as (n' & -> & Hmn').\nso (IH n' (eq_refl _)) as (p' & -> & Hnp').\nexists p'.\nsplit; auto.\neapply star_step; eauto.\n}\nQed.\n\n\nLemma map_equiv :\n  forall A B (f : A -> B) (m n : term A),\n    equiv m n\n    -> equiv (map_term f m) (map_term f n).\nProof.\nintros A B f m n H.\neapply (star_map _ _ _ _ (map_term f)); eauto.\nclear m n H.\nintros m n H.\ndestruct H; eauto using map_reduce.\nQed.\n\n\nLemma map_equivh :\n  forall A B (f : A -> B) (h h' : @hyp A),\n    equivh h h'\n    -> equivh (map_hyp f h) (map_hyp f h').\nProof.\nintros A B f h h' Hequiv.\ncases Hequiv;\nintros;\nsimpmap;\n[apply equivh_tpl | apply equivh_tp | apply equivh_tml | apply equivh_tm | apply equivh_emp]; apply map_equiv; auto.\nQed.\n\n\nLemma map_equiv_conv :\n  forall A B (f : A -> B) (m n : term A),\n    injective f\n    -> equiv (map_term f m) (map_term f n)\n    -> equiv m n.\nProof.\nintros A B f m n Hinj H.\nso (church_rosser _#3 H) as (p & Hmp & Hnp).\nso (map_reduces_form _#5 Hmp) as (p' & -> & Hmp').\nso (map_reduces_form _#5 Hnp) as (p'' & Heq & Hnp').\nso (map_term_inj _#3 Hinj _ _ Heq); subst p''.\neapply equiv_trans.\n  {\n  apply reduces_equiv; eauto.\n  }\n\n  {\n  apply equiv_symm.\n  apply reduces_equiv; auto.\n  }\nQed.\n\n\nLemma map_term_equiv_inj :\n  forall A B (f : A -> B),\n    injective f\n    -> forall (m n : term A),\n         equiv (map_term f m) (map_term f n)\n         -> equiv m n.\nProof.\nintros v w h m n Heq.\neapply map_equiv_conv; eauto.\nQed.\n\n\nLemma map_closub :\n  forall A B (f : A -> B) P (s : @sub A),\n    closub P s\n    -> closub P (map_sub f s).\nProof.\nintros A B f P s Hcl.\nintros j Hj.\nrewrite <- map_project.\napply map_hygiene.\neapply Hcl; eauto.\nQed.\n\n\nLemma map_operator_compose :\n  forall (A B C : Type) (f : B -> C) (g : A -> B) a (th : @operator A a),\n    map_operator f (map_operator g th)\n    =\n    map_operator (fun z => f (g z)) th.\nProof.\nintros A B C f g a th.\ncase th; reflexivity.\nQed.\n\n\nLemma map_term_and_row_compose :\n  forall (A B C : Type) (f : B -> C) (g : A -> B),\n    (forall (m : term A),\n       map_term f (map_term g m)\n       =\n       map_term (fun z => f (g z)) m)\n    /\\\n    (forall a (r : @row A a),\n       map_row f (map_row g r)\n       =\n       map_row (fun z => f (g z)) r).\nProof.\nintros A B C f g.\nexploit (syntax_ind A\n           (fun m =>\n              map_term f (map_term g m)\n              =\n              map_term (fun z => f (g z)) m)\n           (fun a r =>\n              map_row f (map_row g r)\n              =\n              map_row (fun z => f (g z)) r)) as Hprop;\n  intros; cbn; f_equal; eauto using map_operator_compose.\nQed.\n\n\nLemma map_term_compose :\n  forall (A B C : Type) (f : B -> C) (g : A -> B) (m : term A),\n    map_term f (map_term g m)\n    =\n    map_term (fun z => f (g z)) m.\nProof.\nintros A B C f g.\nexact (map_term_and_row_compose _#5 andel).\nQed.\n\n\nLemma map_sub_compose :\n  forall (A B C : Type) (f : B -> C) (g : A -> B) (s : @sub A),\n    map_sub f (map_sub g s)\n    =\n    map_sub (fun z => f (g z)) s.\nProof.\nintros A B C f g s.\ninduct s; auto.\n(* dot *)\n{\nintros m s IH.\ncbn.\nf_equal; auto.\napply map_term_compose.\n}\nQed.\n\n\nLemma map_operator_id :\n  forall A a (th : @operator A a),\n    map_operator (fun z => z) th = th.\nProof.\nintros A a th.\ncase th; reflexivity.\nQed.\n\n\nLemma map_term_and_row_id :\n  forall (A : Type),\n    (forall (m : term A), map_term (fun z => z) m = m)\n    /\\\n    (forall a (r : @row A a), map_row (fun z => z) r = r).\nProof.\nintros A.\nexploit\n  (syntax_ind A\n     (fun m => map_term (fun z => z) m = m)\n     (fun a r => map_row (fun z => z) r = r)) as Hprop;\n  intros; cbn; f_equal; eauto using map_operator_id.\nQed.\n\n\nLemma map_term_id :\n  forall (A : Type) (m : term A),\n    map_term (fun z => z) m = m.\nProof.\nintro A.\nexact (map_term_and_row_id _ andel).\nQed.\n\n\nLemma map_sub_id :\n  forall (A : Type) (s : @sub A),\n    map_sub (fun z => z) s = s.\nProof.\nintros A s.\ninduct s; auto.\nintros m s IH.\ncbn.\nrewrite -> map_term_id.\nf_equal; auto.\nQed.\n\n\nLemma map_value :\n  forall A B (f : A -> B) m,\n    value m\n    -> value (map_term f m).\nProof.\nintros A B f m H.\ninvertc H.\nintros a th r Hcanon <-.\ncbn.\napply value_i.\nclear r.\ncases Hcanon; intros; cbn; auto using canon.\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/MapTerm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.28390412341375226}}
{"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.NArith.NArith.\nRequire Import Cava.Core.Core.\nRequire Import Cava.Semantics.Combinational.\nRequire Import Cava.Util.Tactics.\nRequire Import Cava.Util.Vector.\nRequire Import Cava.Util.Identity.\nRequire Coq.Vectors.Vector.\nRequire Cava.Lib.Vec.\nImport Vector.VectorNotations.\nLocal Open Scope vector_scope.\n\nExisting Instance CombinationalSemantics.\n\nLocal Ltac crush :=\n  (* inline Vec definition *)\n  lazymatch goal with\n  | |- ?x = _ =>\n    let f := app_head x in cbv [f]\n  end;\n  cbv [Monad.mcompose]; simpl_ident; eauto;\n  try solve\n      [ repeat first [ rewrite map_id_ext; intros; simpl_ident\n                     | reflexivity ] ].\n\nLemma bitvec_literal_correct n (v : Vector.t bool n) :\n  Vec.bitvec_literal v = v.\nProof. crush. Qed.\nHint Rewrite @bitvec_literal_correct using solve [eauto] : simpl_ident.\n\nLemma of_N_correct n (x : N) : Vec.of_N x = N2Bv_sized n x.\nProof. crush. Qed.\nHint Rewrite @of_N_correct using solve [eauto] : simpl_ident.\n\nHint Rewrite @bitvec_literal_correct using solve [eauto] : simpl_ident.\nLemma map_literal_correct {A B} n (f : A -> cava (combType B)) (v : Vector.t A n) :\n  Vec.map_literal f v = Vector.map f v.\nProof. crush. Qed.\nHint Rewrite @map_literal_correct using solve [eauto] : simpl_ident.\n\nLemma unpackV2_correct {A n0 n1} (v : combType (Vec (Vec A n0) n1)) :\n  Vec.unpackV2 v = v.\nProof. crush. Qed.\nHint Rewrite @unpackV2_correct using solve [eauto] : simpl_ident.\n\nLemma unpackV3_correct {A n0 n1 n2} (v : combType (Vec (Vec (Vec A n0) n1) n2)) :\n  Vec.unpackV3 v = v.\nProof. crush. Qed.\nHint Rewrite @unpackV3_correct using solve [eauto] : simpl_ident.\n\nLemma unpackV4_correct {A n0 n1 n2 n3}\n      (v : combType (Vec (Vec (Vec (Vec A n0) n1) n2) n3)) :\n  Vec.unpackV4 v = v.\nProof. crush. Qed.\nHint Rewrite @unpackV4_correct using solve [eauto] : simpl_ident.\n\nLemma packV2_correct {A n0 n1} (v : combType (Vec (Vec A n0) n1)) :\n  Vec.packV2 v = v.\nProof. crush. Qed.\nHint Rewrite @packV2_correct using solve [eauto] : simpl_ident.\n\nLemma packV3_correct {A n0 n1 n2} (v : combType (Vec (Vec (Vec A n0) n1) n2)) :\n  Vec.packV3 v = v.\nProof. crush. Qed.\nHint Rewrite @packV3_correct using solve [eauto] : simpl_ident.\n\nLemma packV4_correct {A n0 n1 n2 n3}\n      (v : combType (Vec (Vec (Vec (Vec A n0) n1) n2) n3)) :\n  Vec.packV4 v = v.\nProof. crush. Qed.\nHint Rewrite @packV4_correct using solve [eauto] : simpl_ident.\n\nLemma nil_correct A :\n  @Vec.nil _ _ A = [].\nProof. crush. Qed.\nHint Rewrite @nil_correct using solve [eauto] : simpl_ident.\n\nLemma cons_correct A n x (v : combType (Vec A n)) :\n  Vec.cons x v = (x :: v).\nProof. crush. Qed.\nHint Rewrite @cons_correct using solve [eauto] : simpl_ident.\n\nLemma tl_correct A n (v : combType (Vec A (S n))) :\n  Vec.tl v = Vector.tl v.\nProof. crush. Qed.\nHint Rewrite @tl_correct using solve [eauto] : simpl_ident.\n\nLemma hd_correct A n (v : combType (Vec A (S n))) :\n  Vec.hd v = Vector.hd v.\nProof. crush. Qed.\nHint Rewrite @hd_correct using solve [eauto] : simpl_ident.\n\nLemma const_correct A (x : combType A) n :\n  Vec.const x n = Vector.const x n.\nProof. crush. Qed.\nHint Rewrite @const_correct using solve [eauto] : simpl_ident.\n\nLemma rev_correct A n (v : combType (Vec A (S n))) :\n  Vec.rev v = Vector.reverse v.\nProof. crush. Qed.\nHint Rewrite @rev_correct using solve [eauto] : simpl_ident.\n\nLemma last_correct A n (v : combType (Vec A (S n))) :\n  Vec.last v = Vector.last v.\nProof. crush. Qed.\nHint Rewrite @last_correct using solve [eauto] : simpl_ident.\n\nLemma shiftin_correct A n x (v : combType (Vec A n)) :\n  Vec.shiftin x v = (Vector.shiftin x v).\nProof. crush. Qed.\nHint Rewrite @shiftin_correct using solve [eauto] : simpl_ident.\n\nLemma shiftout_correct A n (v : combType (Vec A (S n))) :\n  Vec.shiftout v = Vector.shiftout v.\nProof. crush. Qed.\nHint Rewrite @shiftout_correct using solve [eauto] : simpl_ident.\n\nLemma transpose_correct A n m (v : combType (Vec (Vec A n) m)) :\n  Vec.transpose v = transpose v.\nProof. crush. Qed.\nHint Rewrite @transpose_correct using solve [eauto] : simpl_ident.\n\nLemma reshape_correct A n m (v : combType (Vec A (n * m))) :\n  Vec.reshape v = reshape v.\nProof. crush. Qed.\nHint Rewrite @reshape_correct using solve [eauto] : simpl_ident.\n\nLemma flatten_correct A n m (v : combType (Vec (Vec A m) n)) :\n  Vec.flatten v = flatten v.\nProof. crush. Qed.\nHint Rewrite @flatten_correct using solve [eauto] : simpl_ident.\n\nLemma resize_default_correct A n m (v : combType (Vec A n)) :\n  Vec.resize_default m v = resize_default (defaultCombValue A) m v.\nProof. crush. Qed.\nHint Rewrite @resize_default_correct using solve [eauto] : simpl_ident.\n\nLemma fold_left_correct A B n f b v :\n  @Vec.fold_left _ _ A B f n v b\n  = Vector.fold_left (fun x y => f (x,y)) b v.\nProof.\n  revert v b; induction n; intros;\n    [ apply Vector.case0 with (v:=v); reflexivity | ].\n  rewrite (Vector.eta v).\n  cbn [Vec.fold_left Vector.fold_left].\n  simpl_ident. autorewrite with vsimpl.\n  rewrite IHn. reflexivity.\nQed.\nHint Rewrite @fold_left_correct using solve [eauto] : simpl_ident.\n\nLemma fold_left2_correct A B C n f c i :\n  @Vec.fold_left2 _ _ A B C f n i c\n  = Vector.fold_left2 (fun x y z => f (x,y,z)) c (fst i) (snd i).\nProof.\n  destruct i as [va vb].\n  revert va vb c; induction n; intros;\n    [ apply Vector.case0 with (v:=va);\n      apply Vector.case0 with (v:=vb);\n      reflexivity | ].\n  rewrite (Vector.eta va), (Vector.eta vb).\n  cbn [Vec.fold_left2 Vector.fold_left2].\n  simpl_ident. autorewrite with vsimpl.\n  rewrite IHn. reflexivity.\nQed.\nHint Rewrite @fold_left2_correct using solve [eauto] : simpl_ident.\n\nLemma map_correct A B n f v :\n  @Vec.map _ _ A B n f v = Vector.map f v.\nProof. crush. Qed.\nHint Rewrite @map_correct using solve [eauto] : simpl_ident.\n\nLemma map2_correct A B C n f i :\n  @Vec.map2 _ _ A B C n f i\n  = Vector.map2 (fun x y => f (x,y)) (fst i) (snd i).\nProof.\n  crush. rewrite map_vcombine_map2.\n  reflexivity.\nQed.\nHint Rewrite @map2_correct using solve [eauto] : simpl_ident.\n\nLemma inv_correct n (v : Vector.t bool n) :\n  Vec.inv v = Vector.map negb v.\nProof. crush. Qed.\nHint Rewrite @inv_correct using solve [eauto] : simpl_ident.\n\nLemma and_correct n (i : Vector.t bool n * Vector.t bool n) :\n  Vec.and i = Vector.map2 andb (fst i) (snd i).\nProof. crush. Qed.\nHint Rewrite @and_correct using solve [eauto] : simpl_ident.\n\nLemma nand_correct n (i : Vector.t bool n * Vector.t bool n) :\n  Vec.nand i = Vector.map2 nandb (fst i) (snd i).\nProof. crush. Qed.\nHint Rewrite @nand_correct using solve [eauto] : simpl_ident.\n\nLemma or_correct n (i : Vector.t bool n * Vector.t bool n) :\n  Vec.or i = Vector.map2 orb (fst i) (snd i).\nProof. crush. Qed.\nHint Rewrite @or_correct using solve [eauto] : simpl_ident.\n\nLemma nor_correct n (i : Vector.t bool n * Vector.t bool n) :\n  Vec.nor i = Vector.map2 norb (fst i) (snd i).\nProof. crush. Qed.\nHint Rewrite @nor_correct using solve [eauto] : simpl_ident.\n\nLemma xor_correct n (i : Vector.t bool n * Vector.t bool n) :\n  Vec.xor i = Vector.map2 xorb (fst i) (snd i).\nProof. crush. Qed.\nHint Rewrite @xor_correct using solve [eauto] : simpl_ident.\n\nLemma xnor_correct n (i : Vector.t bool n * Vector.t bool n) :\n  Vec.xnor i = Vector.map2 xnorb (fst i) (snd i).\nProof. crush. Qed.\nHint Rewrite @xnor_correct using solve [eauto] : simpl_ident.\n\nLemma xorcy_correct n (i : Vector.t bool n * Vector.t bool n) :\n  Vec.xorcy i = Vector.map2 xorb (fst i) (snd i).\nProof. crush. Qed.\nHint Rewrite @xorcy_correct using solve [eauto] : simpl_ident.\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/cava/Cava/Lib/VecProperties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.28390412341375226}}
{"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 translation from Linear to Mach. *)\n\n(** This file proves semantic preservation for the [Stacking] pass. *)\n\nRequire Import Coqlib Errors.\nRequire Import Integers AST Linking.\nRequire Import Values Memory Separation Events Globalenvs Smallstep.\nRequire Import LTL Op Locations Linear Mach.\nRequire Import Bounds Conventions Stacklayout Lineartyping.\nRequire Import Stacking.\n\nLocal Open Scope sep_scope.\n\nDefinition match_prog (p: Linear.program) (tp: Mach.program) :=\n  match_program (fun _ 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\n(** * Basic properties of the translation *)\n\nLemma typesize_typesize:\n  forall ty, AST.typesize ty = 4 * Locations.typesize ty.\nProof.\n  destruct ty; auto.\nQed.\n\nRemark size_type_chunk:\n  forall ty, size_chunk (chunk_of_type ty) = AST.typesize ty.\nProof.\n  destruct ty; reflexivity.\nQed.\n\nRemark align_type_chunk:\n  forall ty, align_chunk (chunk_of_type ty) = 4 * Locations.typealign ty.\nProof.\n  destruct ty; reflexivity.\nQed.\n\nLemma slot_outgoing_argument_valid:\n  forall f ofs ty sg,\n  In (S Outgoing ofs ty) (regs_of_rpairs (loc_arguments sg)) -> slot_valid f Outgoing ofs ty = true.\nProof.\n  intros. exploit loc_arguments_acceptable_2; eauto. intros [A B].\n  unfold slot_valid. unfold proj_sumbool.\n  rewrite zle_true by lia.\n  rewrite pred_dec_true by auto.\n  auto.\nQed.\n\nLemma load_result_inject:\n  forall j ty v v',\n  Val.inject j v v' -> Val.has_type v ty -> Val.inject j v (Val.load_result (chunk_of_type ty) v').\nProof.\n  intros until v'; unfold Val.has_type, Val.load_result; destruct Archi.ptr64;\n  destruct 1; intros; auto; destruct ty; simpl;\n  try contradiction; try discriminate; econstructor; eauto.\nQed.\n\nSection PRESERVATION.\n\nVariable return_address_offset: Mach.function -> Mach.code -> ptrofs -> Prop.\n\nHypothesis return_address_offset_exists:\n  forall f sg ros c,\n  is_tail (Mcall sg ros :: c) (fn_code f) ->\n  exists ofs, return_address_offset f c ofs.\n\nLet step := Mach.step return_address_offset.\n\nVariable prog: Linear.program.\nVariable tprog: Mach.program.\nHypothesis TRANSF: match_prog prog tprog.\nLet ge := Genv.globalenv prog.\nLet tge := Genv.globalenv tprog.\n\nSection FRAME_PROPERTIES.\n\nVariable f: Linear.function.\nLet b := function_bounds f.\nLet fe := make_env b.\nVariable tf: Mach.function.\nHypothesis TRANSF_F: transf_function f = OK tf.\n\nLemma unfold_transf_function:\n  tf = Mach.mkfunction\n         f.(Linear.fn_sig)\n         (transl_body f fe)\n         fe.(fe_size)\n         (Ptrofs.repr fe.(fe_ofs_link))\n         (Ptrofs.repr fe.(fe_ofs_retaddr)).\nProof.\n  generalize TRANSF_F. unfold transf_function.\n  destruct (wt_function f); simpl negb.\n  destruct (zlt Ptrofs.max_unsigned (fe_size (make_env (function_bounds f)))).\n  intros; discriminate.\n  intros. unfold fe. unfold b. congruence.\n  intros; discriminate.\nQed.\n\nLemma transf_function_well_typed:\n  wt_function f = true.\nProof.\n  generalize TRANSF_F. unfold transf_function.\n  destruct (wt_function f); simpl negb. auto. intros; discriminate.\nQed.\n\nLemma size_no_overflow: fe.(fe_size) <= Ptrofs.max_unsigned.\nProof.\n  generalize TRANSF_F. unfold transf_function.\n  destruct (wt_function f); simpl negb.\n  destruct (zlt Ptrofs.max_unsigned (fe_size (make_env (function_bounds f)))).\n  intros; discriminate.\n  intros. unfold fe. unfold b. lia.\n  intros; discriminate.\nQed.\n\nRemark bound_stack_data_stacksize:\n  f.(Linear.fn_stacksize) <= b.(bound_stack_data).\nProof.\n  unfold b, function_bounds, bound_stack_data. apply Z.le_max_l.\nQed.\n\n(** * Memory assertions used to describe the contents of stack frames *)\n\nLocal Opaque Z.add Z.mul Z.divide.\n\n(** Accessing the stack frame using [load_stack] and [store_stack]. *)\n\nLemma contains_get_stack:\n  forall spec m ty sp ofs,\n  m |= contains (chunk_of_type ty) sp ofs spec ->\n  exists v, load_stack m (Vptr sp Ptrofs.zero) ty (Ptrofs.repr ofs) = Some v /\\ spec v.\nProof.\n  intros. unfold load_stack.\n  replace (Val.offset_ptr (Vptr sp Ptrofs.zero) (Ptrofs.repr ofs)) with (Vptr sp (Ptrofs.repr ofs)).\n  eapply loadv_rule; eauto.\n  simpl. rewrite Ptrofs.add_zero_l; auto.\nQed.\n\nLemma hasvalue_get_stack:\n  forall ty m sp ofs v,\n  m |= hasvalue (chunk_of_type ty) sp ofs v ->\n  load_stack m (Vptr sp Ptrofs.zero) ty (Ptrofs.repr ofs) = Some v.\nProof.\n  intros. exploit contains_get_stack; eauto. intros (v' & A & B). congruence.\nQed.\n\nLemma contains_set_stack:\n  forall (spec: val -> Prop) v spec1 m ty sp ofs P,\n  m |= contains (chunk_of_type ty) sp ofs spec1 ** P ->\n  spec (Val.load_result (chunk_of_type ty) v) ->\n  exists m',\n      store_stack m (Vptr sp Ptrofs.zero) ty (Ptrofs.repr ofs) v = Some m'\n  /\\ m' |= contains (chunk_of_type ty) sp ofs spec ** P.\nProof.\n  intros. unfold store_stack.\n  replace (Val.offset_ptr (Vptr sp Ptrofs.zero) (Ptrofs.repr ofs)) with (Vptr sp (Ptrofs.repr ofs)).\n  eapply storev_rule; eauto.\n  simpl. rewrite Ptrofs.add_zero_l; auto.\nQed.\n\n(** [contains_locations j sp pos bound sl ls] is a separation logic assertion\n  that holds if the memory area at block [sp], offset [pos], size [4 * bound],\n  reflects the values of the stack locations of kind [sl] given by the\n  location map [ls], up to the memory injection [j].\n\n  Two such [contains_locations] assertions will be used later, one to\n  reason about the values of [Local] slots, the other about the values of\n  [Outgoing] slots. *)\n\nProgram Definition contains_locations (j: meminj) (sp: block) (pos bound: Z) (sl: slot) (ls: locset) : massert := {|\n  m_pred := fun m =>\n    (8 | pos) /\\ 0 <= pos /\\ pos + 4 * bound <= Ptrofs.modulus /\\\n    Mem.range_perm m sp pos (pos + 4 * bound) Cur Freeable /\\\n    forall ofs ty, 0 <= ofs -> ofs + typesize ty <= bound -> (typealign ty | ofs) ->\n    exists v, Mem.load (chunk_of_type ty) m sp (pos + 4 * ofs) = Some v\n           /\\ Val.inject j (ls (S sl ofs ty)) v;\n  m_footprint := fun b ofs =>\n    b = sp /\\ pos <= ofs < pos + 4 * bound\n|}.\nNext Obligation.\n  intuition auto.\n- red; intros. eapply Mem.perm_unchanged_on; eauto. simpl; auto.\n- exploit H4; eauto. intros (v & A & B). exists v; split; auto.\n  eapply Mem.load_unchanged_on; eauto.\n  simpl; intros. rewrite size_type_chunk, typesize_typesize in H8.\n  split; auto. lia.\nQed.\nNext Obligation.\n  eauto with mem.\nQed.\n\nRemark valid_access_location:\n  forall m sp pos bound ofs ty p,\n  (8 | pos) ->\n  Mem.range_perm m sp pos (pos + 4 * bound) Cur Freeable ->\n  0 <= ofs -> ofs + typesize ty <= bound -> (typealign ty | ofs) ->\n  Mem.valid_access m (chunk_of_type ty) sp (pos + 4 * ofs) p.\nProof.\n  intros; split.\n- red; intros. apply Mem.perm_implies with Freeable; auto with mem.\n  apply H0. rewrite size_type_chunk, typesize_typesize in H4. lia.\n- rewrite align_type_chunk. apply Z.divide_add_r.\n  apply Z.divide_trans with 8; auto.\n  exists (8 / (4 * typealign ty)); destruct ty; reflexivity.\n  apply Z.mul_divide_mono_l. auto.\nQed.\n\nLemma get_location:\n  forall m j sp pos bound sl ls ofs ty,\n  m |= contains_locations j sp pos bound sl ls ->\n  0 <= ofs -> ofs + typesize ty <= bound -> (typealign ty | ofs) ->\n  exists v,\n     load_stack m (Vptr sp Ptrofs.zero) ty (Ptrofs.repr (pos + 4 * ofs)) = Some v\n  /\\ Val.inject j (ls (S sl ofs ty)) v.\nProof.\n  intros. destruct H as (D & E & F & G & H).\n  exploit H; eauto. intros (v & U & V). exists v; split; auto.\n  unfold load_stack; simpl. rewrite Ptrofs.add_zero_l, Ptrofs.unsigned_repr; auto.\n  unfold Ptrofs.max_unsigned. generalize (typesize_pos ty). lia.\nQed.\n\nLemma set_location:\n  forall m j sp pos bound sl ls P ofs ty v v',\n  m |= contains_locations j sp pos bound sl ls ** P ->\n  0 <= ofs -> ofs + typesize ty <= bound -> (typealign ty | ofs) ->\n  Val.inject j v v' ->\n  exists m',\n     store_stack m (Vptr sp Ptrofs.zero) ty (Ptrofs.repr (pos + 4 * ofs)) v' = Some m'\n  /\\ m' |= contains_locations j sp pos bound sl (Locmap.set (S sl ofs ty) v ls) ** P.\nProof.\n  intros. destruct H as (A & B & C). destruct A as (D & E & F & G & H).\n  edestruct Mem.valid_access_store as [m' STORE].\n  eapply valid_access_location; eauto.\n  assert (PERM: Mem.range_perm m' sp pos (pos + 4 * bound) Cur Freeable).\n  { red; intros; eauto with mem. }\n  exists m'; split.\n- unfold store_stack; simpl. rewrite Ptrofs.add_zero_l, Ptrofs.unsigned_repr; eauto.\n  unfold Ptrofs.max_unsigned. generalize (typesize_pos ty). lia.\n- simpl. intuition auto.\n+ unfold Locmap.set.\n  destruct (Loc.eq (S sl ofs ty) (S sl ofs0 ty0)); [|destruct (Loc.diff_dec (S sl ofs ty) (S sl ofs0 ty0))].\n* (* same location *)\n  inv e. rename ofs0 into ofs. rename ty0 into ty.\n  exists (Val.load_result (chunk_of_type ty) v'); split.\n  eapply Mem.load_store_similar_2; eauto. lia.\n  apply Val.load_result_inject; auto.\n* (* different locations *)\n  exploit H; eauto. intros (v0 & X & Y). exists v0; split; auto.\n  rewrite <- X; eapply Mem.load_store_other; eauto.\n  destruct d. congruence. right. rewrite ! size_type_chunk, ! typesize_typesize. lia.\n* (* overlapping locations *)\n  destruct (Mem.valid_access_load m' (chunk_of_type ty0) sp (pos + 4 * ofs0)) as [v'' LOAD].\n  apply Mem.valid_access_implies with Writable; auto with mem.\n  eapply valid_access_location; eauto.\n  exists v''; auto.\n+ apply (m_invar P) with m; auto.\n  eapply Mem.store_unchanged_on; eauto.\n  intros i; rewrite size_type_chunk, typesize_typesize. intros; red; intros.\n  eelim C; eauto. simpl. split; auto. lia.\nQed.\n\nLemma initial_locations:\n  forall j sp pos bound P sl ls m,\n  m |= range sp pos (pos + 4 * bound) ** P ->\n  (8 | pos) ->\n  (forall ofs ty, ls (S sl ofs ty) = Vundef) ->\n  m |= contains_locations j sp pos bound sl ls ** P.\nProof.\n  intros. destruct H as (A & B & C). destruct A as (D & E & F). split.\n- simpl; intuition auto. red; intros; eauto with mem.\n  destruct (Mem.valid_access_load m (chunk_of_type ty) sp (pos + 4 * ofs)) as [v LOAD].\n  eapply valid_access_location; eauto.\n  red; intros; eauto with mem.\n  exists v; split; auto. rewrite H1; auto.\n- split; assumption.\nQed.\n\nLemma contains_locations_exten:\n  forall ls ls' j sp pos bound sl,\n  (forall ofs ty, Val.lessdef (ls' (S sl ofs ty)) (ls (S sl ofs ty))) ->\n  massert_imp (contains_locations j sp pos bound sl ls)\n              (contains_locations j sp pos bound sl ls').\nProof.\n  intros; split; simpl; intros; auto.\n  intuition auto. exploit H5; eauto. intros (v & A & B). exists v; split; auto. \n  specialize (H ofs ty). inv H. congruence. auto. \nQed.\n\nLemma contains_locations_incr:\n  forall j j' sp pos bound sl ls,\n  inject_incr j j' ->\n  massert_imp (contains_locations j sp pos bound sl ls)\n              (contains_locations j' sp pos bound sl ls).\nProof.\n  intros; split; simpl; intros; auto.\n  intuition auto. exploit H5; eauto. intros (v & A & B). exists v; eauto.\nQed.\n\n(** [contains_callee_saves j sp pos rl ls] is a memory assertion that holds\n  if block [sp], starting at offset [pos], contains the values of the\n  callee-save registers [rl] as given by the location map [ls],\n  up to the memory injection [j].  The memory layout of the registers in [rl]\n  is the same as that implemented by [save_callee_save_rec]. *)\n\nFixpoint contains_callee_saves (j: meminj) (sp: block) (pos: Z) (rl: list mreg) (ls: locset) : massert :=\n  match rl with\n  | nil => pure True\n  | r :: rl =>\n      let ty := mreg_type r in\n      let sz := AST.typesize ty in\n      let pos1 := align pos sz in\n      contains (chunk_of_type ty) sp pos1 (fun v => Val.inject j (ls (R r)) v)\n      ** contains_callee_saves j sp (pos1 + sz) rl ls\n  end.\n\nLemma contains_callee_saves_incr:\n  forall j j' sp ls,\n  inject_incr j j' ->\n  forall rl pos,\n  massert_imp (contains_callee_saves j sp pos rl ls)\n              (contains_callee_saves j' sp pos rl ls).\nProof.\n  induction rl as [ | r1 rl]; simpl; intros.\n- reflexivity.\n- apply sepconj_morph_1; auto. apply contains_imp. eauto.\nQed.\n\nLemma contains_callee_saves_exten:\n  forall j sp ls ls' rl pos,\n  (forall r, In r rl -> ls' (R r) = ls (R r)) ->\n  massert_eqv (contains_callee_saves j sp pos rl ls)\n              (contains_callee_saves j sp pos rl ls').\nProof.\n  induction rl as [ | r1 rl]; simpl; intros.\n- reflexivity.\n- apply sepconj_morph_2; auto. rewrite H by auto. reflexivity.\nQed.\n\n(** Separation logic assertions describing the stack frame at [sp].\n  It must contain:\n  - the values of the [Local] stack slots of [ls], as per [contains_locations]\n  - the values of the [Outgoing] stack slots of [ls], as per [contains_locations]\n  - the [parent] pointer representing the back link to the caller's frame\n  - the [retaddr] pointer representing the saved return address\n  - the initial values of the used callee-save registers as given by [ls0],\n    as per [contains_callee_saves].\n\nIn addition, we use a nonseparating conjunction to record the fact that\nwe have full access rights on the stack frame, except the part that\nrepresents the Linear stack data. *)\n\nDefinition frame_contents_1 (j: meminj) (sp: block) (ls ls0: locset) (parent retaddr: val) :=\n    contains_locations j sp fe.(fe_ofs_local) b.(bound_local) Local ls\n ** contains_locations j sp fe_ofs_arg b.(bound_outgoing) Outgoing ls\n ** hasvalue Mptr sp fe.(fe_ofs_link) parent\n ** hasvalue Mptr sp fe.(fe_ofs_retaddr) retaddr\n ** contains_callee_saves j sp fe.(fe_ofs_callee_save) b.(used_callee_save) ls0.\n\nDefinition frame_contents (j: meminj) (sp: block) (ls ls0: locset) (parent retaddr: val) :=\n  mconj (frame_contents_1 j sp ls ls0 parent retaddr)\n        (range sp 0 fe.(fe_stack_data) **\n         range sp (fe.(fe_stack_data) + b.(bound_stack_data)) fe.(fe_size)).\n\n(** Accessing components of the frame. *)\n\nLemma frame_get_local:\n  forall ofs ty j sp ls ls0 parent retaddr m P,\n  m |= frame_contents j sp ls ls0 parent retaddr ** P ->\n  slot_within_bounds b Local ofs ty -> slot_valid f Local ofs ty = true ->\n  exists v,\n     load_stack m (Vptr sp Ptrofs.zero) ty (Ptrofs.repr (offset_local fe ofs)) = Some v\n  /\\ Val.inject j (ls (S Local ofs ty)) v.\nProof.\n  unfold frame_contents, frame_contents_1; intros. unfold slot_valid in H1; InvBooleans.\n  apply mconj_proj1 in H. apply sep_proj1 in H. apply sep_proj1 in H.\n  eapply get_location; eauto.\nQed.\n\nLemma frame_get_outgoing:\n  forall ofs ty j sp ls ls0 parent retaddr m P,\n  m |= frame_contents j sp ls ls0 parent retaddr ** P ->\n  slot_within_bounds b Outgoing ofs ty -> slot_valid f Outgoing ofs ty = true ->\n  exists v,\n     load_stack m (Vptr sp Ptrofs.zero) ty (Ptrofs.repr (offset_arg ofs)) = Some v\n  /\\ Val.inject j (ls (S Outgoing ofs ty)) v.\nProof.\n  unfold frame_contents, frame_contents_1; intros. unfold slot_valid in H1; InvBooleans.\n  apply mconj_proj1 in H. apply sep_proj1 in H. apply sep_pick2 in H.\n  eapply get_location; eauto.\nQed.\n\nLemma frame_get_parent:\n  forall j sp ls ls0 parent retaddr m P,\n  m |= frame_contents j sp ls ls0 parent retaddr ** P ->\n  load_stack m (Vptr sp Ptrofs.zero) Tptr (Ptrofs.repr fe.(fe_ofs_link)) = Some parent.\nProof.\n  unfold frame_contents, frame_contents_1; intros.\n  apply mconj_proj1 in H. apply sep_proj1 in H. apply sep_pick3 in H. rewrite <- chunk_of_Tptr in H.\n  eapply hasvalue_get_stack; eauto.\nQed.\n\nLemma frame_get_retaddr:\n  forall j sp ls ls0 parent retaddr m P,\n  m |= frame_contents j sp ls ls0 parent retaddr ** P ->\n  load_stack m (Vptr sp Ptrofs.zero) Tptr (Ptrofs.repr fe.(fe_ofs_retaddr)) = Some retaddr.\nProof.\n  unfold frame_contents, frame_contents_1; intros.\n  apply mconj_proj1 in H. apply sep_proj1 in H. apply sep_pick4 in H. rewrite <- chunk_of_Tptr in H.\n  eapply hasvalue_get_stack; eauto.\nQed.\n\n(** Assigning a [Local] or [Outgoing] stack slot. *)\n\nLemma frame_set_local:\n  forall ofs ty v v' j sp ls ls0 parent retaddr m P,\n  m |= frame_contents j sp ls ls0 parent retaddr ** P ->\n  slot_within_bounds b Local ofs ty -> slot_valid f Local ofs ty = true ->\n  Val.inject j v v' ->\n  exists m',\n     store_stack m (Vptr sp Ptrofs.zero) ty (Ptrofs.repr (offset_local fe ofs)) v' = Some m'\n  /\\ m' |= frame_contents j sp (Locmap.set (S Local ofs ty) v ls) ls0 parent retaddr ** P.\nProof.\n  intros. unfold frame_contents in H.\n  exploit mconj_proj1; eauto. unfold frame_contents_1.\n  rewrite ! sep_assoc; intros SEP.\n  unfold slot_valid in H1; InvBooleans. simpl in H0.\n  exploit set_location; eauto. intros (m' & A & B).\n  exists m'; split; auto.\n  assert (forall i k p, Mem.perm m sp i k p -> Mem.perm m' sp i k p).\n  {  intros. unfold store_stack in A; simpl in A. eapply Mem.perm_store_1; eauto. }\n  eapply frame_mconj. eauto.\n  unfold frame_contents_1; rewrite ! sep_assoc; exact B.\n  eapply sep_preserved.\n  eapply sep_proj1. eapply mconj_proj2. eassumption.\n  intros; eapply range_preserved; eauto.\n  intros; eapply range_preserved; eauto.\nQed.\n\nLemma frame_set_outgoing:\n  forall ofs ty v v' j sp ls ls0 parent retaddr m P,\n  m |= frame_contents j sp ls ls0 parent retaddr ** P ->\n  slot_within_bounds b Outgoing ofs ty -> slot_valid f Outgoing ofs ty = true ->\n  Val.inject j v v' ->\n  exists m',\n     store_stack m (Vptr sp Ptrofs.zero) ty (Ptrofs.repr (offset_arg ofs)) v' = Some m'\n  /\\ m' |= frame_contents j sp (Locmap.set (S Outgoing ofs ty) v ls) ls0 parent retaddr ** P.\nProof.\n  intros. unfold frame_contents in H.\n  exploit mconj_proj1; eauto. unfold frame_contents_1.\n  rewrite ! sep_assoc, sep_swap. intros SEP.\n  unfold slot_valid in H1; InvBooleans. simpl in H0.\n  exploit set_location; eauto. intros (m' & A & B).\n  exists m'; split; auto.\n  assert (forall i k p, Mem.perm m sp i k p -> Mem.perm m' sp i k p).\n  {  intros. unfold store_stack in A; simpl in A. eapply Mem.perm_store_1; eauto. }\n  eapply frame_mconj. eauto.\n  unfold frame_contents_1; rewrite ! sep_assoc, sep_swap; eauto.\n  eapply sep_preserved.\n  eapply sep_proj1. eapply mconj_proj2. eassumption.\n  intros; eapply range_preserved; eauto.\n  intros; eapply range_preserved; eauto.\nQed.\n\n(** Invariance by change of location maps. *)\n\nLemma frame_contents_exten:\n  forall ls ls0 ls' ls0' j sp parent retaddr P m,\n  (forall ofs ty, Val.lessdef (ls' (S Local ofs ty)) (ls (S Local ofs ty))) ->\n  (forall ofs ty, Val.lessdef (ls' (S Outgoing ofs ty)) (ls (S Outgoing ofs ty))) ->\n  (forall r, In r b.(used_callee_save) -> ls0' (R r) = ls0 (R r)) ->\n  m |= frame_contents j sp ls ls0 parent retaddr ** P ->\n  m |= frame_contents j sp ls' ls0' parent retaddr ** P.\nProof.\n  unfold frame_contents, frame_contents_1; intros.\n  rewrite <- ! (contains_locations_exten ls ls') by auto.\n  erewrite  <- contains_callee_saves_exten by eauto.\n  assumption.\nQed.\n\n(** Invariance by assignment to registers. *)\n\nCorollary frame_set_reg:\n  forall r v j sp ls ls0 parent retaddr m P,\n  m |= frame_contents j sp ls ls0 parent retaddr ** P ->\n  m |= frame_contents j sp (Locmap.set (R r) v ls) ls0 parent retaddr ** P.\nProof.\n  intros. apply frame_contents_exten with ls ls0; auto.\nQed.\n\nCorollary frame_undef_regs:\n  forall j sp ls ls0 parent retaddr m P rl,\n  m |= frame_contents j sp ls ls0 parent retaddr ** P ->\n  m |= frame_contents j sp (LTL.undef_regs rl ls) ls0 parent retaddr ** P.\nProof.\nLocal Opaque sepconj.\n  induction rl; simpl; intros.\n- auto.\n- apply frame_set_reg; auto.\nQed.\n\nCorollary frame_set_regpair:\n  forall j sp ls0 parent retaddr m P p v ls,\n  m |= frame_contents j sp ls ls0 parent retaddr ** P ->\n  m |= frame_contents j sp (Locmap.setpair p v ls) ls0 parent retaddr ** P.\nProof.\n  intros. destruct p; simpl.\n  apply frame_set_reg; auto.\n  apply frame_set_reg; apply frame_set_reg; auto.\nQed.\n\nCorollary frame_set_res:\n  forall j sp ls0 parent retaddr m P res v ls,\n  m |= frame_contents j sp ls ls0 parent retaddr ** P ->\n  m |= frame_contents j sp (Locmap.setres res v ls) ls0 parent retaddr ** P.\nProof.\n  induction res; simpl; intros.\n- apply frame_set_reg; auto.\n- auto.\n- eauto.\nQed.\n\n(** Invariance by change of memory injection. *)\n\nLemma frame_contents_incr:\n  forall j sp ls ls0 parent retaddr m P j',\n  m |= frame_contents j sp ls ls0 parent retaddr ** P ->\n  inject_incr j j' ->\n  m |= frame_contents j' sp ls ls0 parent retaddr ** P.\nProof.\n  unfold frame_contents, frame_contents_1; intros.\n  rewrite <- (contains_locations_incr j j') by auto.\n  rewrite <- (contains_locations_incr j j') by auto.\n  erewrite  <- contains_callee_saves_incr by eauto.\n  assumption.\nQed.\n\n(** * Agreement between location sets and Mach states *)\n\n(** Agreement with Mach register states *)\n\nDefinition agree_regs (j: meminj) (ls: locset) (rs: regset) : Prop :=\n  forall r, Val.inject j (ls (R r)) (rs r).\n\n(** Agreement over locations *)\n\nRecord agree_locs (ls ls0: locset) : Prop :=\n  mk_agree_locs {\n\n    (** Unused registers have the same value as in the caller *)\n    agree_unused_reg:\n       forall r, ~(mreg_within_bounds b r) -> ls (R r) = ls0 (R r);\n\n    (** Incoming stack slots have the same value as the\n        corresponding Outgoing stack slots in the caller *)\n    agree_incoming:\n       forall ofs ty,\n       In (S Incoming ofs ty) (regs_of_rpairs (loc_parameters f.(Linear.fn_sig))) ->\n       ls (S Incoming ofs ty) = ls0 (S Outgoing ofs ty)\n}.\n\n(** ** Properties of [agree_regs]. *)\n\n(** Values of registers *)\n\nLemma agree_reg:\n  forall j ls rs r,\n  agree_regs j ls rs -> Val.inject j (ls (R r)) (rs r).\nProof.\n  intros. auto.\nQed.\n\nLemma agree_reglist:\n  forall j ls rs rl,\n  agree_regs j ls rs -> Val.inject_list j (reglist ls rl) (rs##rl).\nProof.\n  induction rl; simpl; intros.\n  auto. constructor; auto using agree_reg.\nQed.\n\nHint Resolve agree_reg agree_reglist: stacking.\n\n(** Preservation under assignments of machine registers. *)\n\nLemma agree_regs_set_reg:\n  forall j ls rs r v v',\n  agree_regs j ls rs ->\n  Val.inject j v v' ->\n  agree_regs j (Locmap.set (R r) v ls) (Regmap.set r v' rs).\nProof.\n  intros; red; intros.\n  unfold Regmap.set. destruct (RegEq.eq r0 r). subst r0.\n  rewrite Locmap.gss; auto.\n  rewrite Locmap.gso; auto. red. auto.\nQed.\n\nLemma agree_regs_set_pair:\n  forall j p v v' ls rs,\n  agree_regs j ls rs ->\n  Val.inject j v v' ->\n  agree_regs j (Locmap.setpair p v ls) (set_pair p v' rs).\nProof.\n  intros. destruct p; simpl.\n- apply agree_regs_set_reg; auto.\n- apply agree_regs_set_reg. apply agree_regs_set_reg; auto.\n  apply Val.hiword_inject; auto. apply Val.loword_inject; auto.\nQed.\n\nLemma agree_regs_set_res:\n  forall j res v v' ls rs,\n  agree_regs j ls rs ->\n  Val.inject j v v' ->\n  agree_regs j (Locmap.setres res v ls) (set_res res v' rs).\nProof.\n  induction res; simpl; intros.\n- apply agree_regs_set_reg; auto.\n- auto.\n- apply IHres2. apply IHres1. auto.\n  apply Val.hiword_inject; auto.\n  apply Val.loword_inject; auto.\nQed.\n\nLemma agree_regs_exten:\n  forall j ls rs ls' rs',\n  agree_regs j ls rs ->\n  (forall r, ls' (R r) = Vundef \\/ ls' (R r) = ls (R r) /\\ rs' r = rs r) ->\n  agree_regs j ls' rs'.\nProof.\n  intros; red; intros.\n  destruct (H0 r) as [A | [A B]].\n  rewrite A. constructor.\n  rewrite A; rewrite B; auto.\nQed.\n\nLemma agree_regs_undef_regs:\n  forall j rl ls rs,\n  agree_regs j ls rs ->\n  agree_regs j (LTL.undef_regs rl ls) (Mach.undef_regs rl rs).\nProof.\n  induction rl; simpl; intros.\n  auto.\n  apply agree_regs_set_reg; auto.\nQed.\n\nLemma agree_regs_undef_caller_save_regs:\n  forall j ls rs,\n  agree_regs j ls rs ->\n  agree_regs j (LTL.undef_caller_save_regs ls) (Mach.undef_caller_save_regs rs).\nProof.\n  intros; red; intros. \n  unfold LTL.undef_caller_save_regs, Mach.undef_caller_save_regs. \n  destruct (is_callee_save r); auto. \nQed.\n\n(** Preservation under assignment of stack slot *)\n\nLemma agree_regs_set_slot:\n  forall j ls rs sl ofs ty v,\n  agree_regs j ls rs ->\n  agree_regs j (Locmap.set (S sl ofs ty) v ls) rs.\nProof.\n  intros; red; intros. rewrite Locmap.gso; auto. red. auto.\nQed.\n\n(** Preservation by increasing memory injections *)\n\nLemma agree_regs_inject_incr:\n  forall j ls rs j',\n  agree_regs j ls rs -> inject_incr j j' -> agree_regs j' ls rs.\nProof.\n  intros; red; intros; eauto with stacking.\nQed.\n\n(** Preservation at function entry. *)\n\nLemma agree_regs_call_regs:\n  forall j ls rs,\n  agree_regs j ls rs ->\n  agree_regs j (call_regs ls) rs.\nProof.\n  intros.\n  unfold call_regs; intros; red; intros; auto.\nQed.\n\n(** ** Properties of [agree_locs] *)\n\n(** Preservation under assignment of machine register. *)\n\nLemma agree_locs_set_reg:\n  forall ls ls0 r v,\n  agree_locs ls ls0 ->\n  mreg_within_bounds b r ->\n  agree_locs (Locmap.set (R r) v ls) ls0.\nProof.\n  intros. inv H; constructor; auto; intros.\n  rewrite Locmap.gso. auto. red. intuition congruence.\nQed.\n\nLemma caller_save_reg_within_bounds:\n  forall r,\n  is_callee_save r = false -> mreg_within_bounds b r.\nProof.\n  intros; red; intros. congruence.\nQed.\n\nLemma agree_locs_set_pair:\n  forall ls0 p v ls,\n  agree_locs ls ls0 ->\n  forall_rpair (fun r => is_callee_save r = false) p ->\n  agree_locs (Locmap.setpair p v ls) ls0.\nProof.\n  intros.\n  destruct p; simpl in *.\n  apply agree_locs_set_reg; auto. apply caller_save_reg_within_bounds; auto.\n  destruct H0.\n  apply agree_locs_set_reg; auto. apply agree_locs_set_reg; auto.\n  apply caller_save_reg_within_bounds; auto. apply caller_save_reg_within_bounds; auto.\nQed.\n\nLemma agree_locs_set_res:\n  forall ls0 res v ls,\n  agree_locs ls ls0 ->\n  (forall r, In r (params_of_builtin_res res) -> mreg_within_bounds b r) ->\n  agree_locs (Locmap.setres res v ls) ls0.\nProof.\n  induction res; simpl; intros.\n- eapply agree_locs_set_reg; eauto.\n- auto.\n- apply IHres2; auto using in_or_app.\nQed.\n\nLemma agree_locs_undef_regs:\n  forall ls0 regs ls,\n  agree_locs ls ls0 ->\n  (forall r, In r regs -> mreg_within_bounds b r) ->\n  agree_locs (LTL.undef_regs regs ls) ls0.\nProof.\n  induction regs; simpl; intros.\n  auto.\n  apply agree_locs_set_reg; auto.\nQed.\n\nLemma agree_locs_undef_locs_1:\n  forall ls0 regs ls,\n  agree_locs ls ls0 ->\n  (forall r, In r regs -> is_callee_save r = false) ->\n  agree_locs (LTL.undef_regs regs ls) ls0.\nProof.\n  intros. eapply agree_locs_undef_regs; eauto.\n  intros. apply caller_save_reg_within_bounds. auto.\nQed.\n\nLemma agree_locs_undef_locs:\n  forall ls0 regs ls,\n  agree_locs ls ls0 ->\n  existsb is_callee_save regs = false ->\n  agree_locs (LTL.undef_regs regs ls) ls0.\nProof.\n  intros. eapply agree_locs_undef_locs_1; eauto.\n  intros. destruct (is_callee_save r) eqn:CS; auto.\n  assert (existsb is_callee_save regs = true).\n  { apply existsb_exists. exists r; auto. }\n  congruence.\nQed.\n\n(** Preservation by assignment to local slot *)\n\nLemma agree_locs_set_slot:\n  forall ls ls0 sl ofs ty v,\n  agree_locs ls ls0 ->\n  slot_writable sl = true ->\n  agree_locs (Locmap.set (S sl ofs ty) v ls) ls0.\nProof.\n  intros. destruct H; constructor; intros.\n- rewrite Locmap.gso; auto. red; auto.\n- rewrite Locmap.gso; auto. red. left. destruct sl; discriminate.\nQed.\n\n(** Preservation at return points (when [ls] is changed but not [ls0]). *)\n\nLemma agree_locs_return:\n  forall ls ls0 ls',\n  agree_locs ls ls0 ->\n  agree_callee_save ls' ls ->\n  agree_locs ls' ls0.\nProof.\n  intros. red in H0. inv H; constructor; auto; intros.\n- rewrite H0; auto. unfold mreg_within_bounds in H. tauto.\n- rewrite <- agree_incoming0 by auto. apply H0. congruence.\nQed.\n\n(** ** Properties of destroyed registers. *)\n\nDefinition no_callee_saves (l: list mreg) : Prop :=\n  existsb is_callee_save l = false.\n\nRemark destroyed_by_op_caller_save:\n  forall op, no_callee_saves (destroyed_by_op op).\nProof.\n  unfold no_callee_saves; destruct op; (reflexivity || destruct c; reflexivity).\nQed.\n\nRemark destroyed_by_load_caller_save:\n  forall chunk addr, no_callee_saves (destroyed_by_load chunk addr).\nProof.\n  unfold no_callee_saves; destruct chunk; reflexivity.\nQed.\n\nRemark destroyed_by_store_caller_save:\n  forall chunk addr, no_callee_saves (destroyed_by_store chunk addr).\nProof.\nLocal Transparent destroyed_by_store.\n  unfold no_callee_saves, destroyed_by_store; intros; destruct chunk; try reflexivity; destruct Archi.ptr64; reflexivity.\nQed.\n\nRemark destroyed_by_cond_caller_save:\n  forall cond, no_callee_saves (destroyed_by_cond cond).\nProof.\n  unfold no_callee_saves; destruct cond; reflexivity.\nQed.\n\nRemark destroyed_by_jumptable_caller_save:\n  no_callee_saves destroyed_by_jumptable.\nProof.\n  red; reflexivity.\nQed.\n\nRemark destroyed_by_setstack_caller_save:\n  forall ty, no_callee_saves (destroyed_by_setstack ty).\nProof.\n  unfold no_callee_saves; destruct ty; reflexivity.\nQed.\n\nRemark destroyed_at_function_entry_caller_save:\n  no_callee_saves destroyed_at_function_entry.\nProof.\n  red; reflexivity.\nQed.\n\nHint Resolve destroyed_by_op_caller_save destroyed_by_load_caller_save\n    destroyed_by_store_caller_save\n    destroyed_by_cond_caller_save destroyed_by_jumptable_caller_save\n    destroyed_at_function_entry_caller_save: stacking.\n\nRemark destroyed_by_setstack_function_entry:\n  forall ty, incl (destroyed_by_setstack ty) destroyed_at_function_entry.\nProof.\nLocal Transparent destroyed_by_setstack destroyed_at_function_entry.\n  unfold incl; destruct ty; simpl; tauto.\nQed.\n\nRemark transl_destroyed_by_op:\n  forall op e, destroyed_by_op (transl_op e op) = destroyed_by_op op.\nProof.\n  intros; destruct op; reflexivity.\nQed.\n\nRemark transl_destroyed_by_load:\n  forall chunk addr e, destroyed_by_load chunk (transl_addr e addr) = destroyed_by_load chunk addr.\nProof.\n  intros; destruct chunk; reflexivity.\nQed.\n\nRemark transl_destroyed_by_store:\n  forall chunk addr e, destroyed_by_store chunk (transl_addr e addr) = destroyed_by_store chunk addr.\nProof.\n  intros; destruct chunk; reflexivity.\nQed.\n\n(** * Correctness of saving and restoring of callee-save registers *)\n\n(** The following lemmas show the correctness of the register saving\n  code generated by [save_callee_save]: after this code has executed,\n  the register save areas of the current frame do contain the\n  values of the callee-save registers used by the function. *)\n\nSection SAVE_CALLEE_SAVE.\n\nVariable j: meminj.\nVariable cs: list stackframe.\nVariable fb: block.\nVariable sp: block.\nVariable ls: locset.\n\nHypothesis ls_temp_undef:\n  forall ty r, In r (destroyed_by_setstack ty) -> ls (R r) = Vundef.\n\nHypothesis wt_ls: forall r, Val.has_type (ls (R r)) (mreg_type r).\n\nLemma save_callee_save_rec_correct:\n  forall k l pos rs m P,\n  (forall r, In r l -> is_callee_save r = true) ->\n  m |= range sp pos (size_callee_save_area_rec l pos) ** P ->\n  agree_regs j ls rs ->\n  exists rs', exists m',\n     star step tge\n        (State cs fb (Vptr sp Ptrofs.zero) (save_callee_save_rec l pos k) rs m)\n     E0 (State cs fb (Vptr sp Ptrofs.zero) k rs' m')\n  /\\ m' |= contains_callee_saves j sp pos l ls ** P\n  /\\ (forall ofs k p, Mem.perm m sp ofs k p -> Mem.perm m' sp ofs k p)\n  /\\ agree_regs j ls rs'.\nProof.\nLocal Opaque mreg_type.\n  induction l as [ | r l]; simpl; intros until P; intros CS SEP AG.\n- exists rs, m.\n  split. apply star_refl.\n  split. rewrite sep_pure; split; auto. eapply sep_drop; eauto.\n  split. auto.\n  auto.\n- set (ty := mreg_type r) in *.\n  set (sz := AST.typesize ty) in *.\n  set (pos1 := align pos sz) in *.\n  assert (SZPOS: sz > 0) by (apply AST.typesize_pos).\n  assert (SZREC: pos1 + sz <= size_callee_save_area_rec l (pos1 + sz)) by (apply size_callee_save_area_rec_incr).\n  assert (POS1: pos <= pos1) by (apply align_le; auto).\n  assert (AL1: (align_chunk (chunk_of_type ty) | pos1)).\n  { unfold pos1. apply Z.divide_trans with sz.\n    unfold sz; rewrite <- size_type_chunk. apply align_size_chunk_divides.\n    apply align_divides; auto. }\n  apply range_drop_left with (mid := pos1) in SEP; [ | lia ].\n  apply range_split with (mid := pos1 + sz) in SEP; [ | lia ].\n  unfold sz at 1 in SEP. rewrite <- size_type_chunk in SEP.\n  apply range_contains in SEP; auto.\n  exploit (contains_set_stack (fun v' => Val.inject j (ls (R r)) v') (rs r)).\n  eexact SEP.\n  apply load_result_inject; [auto|apply wt_ls].\n  clear SEP; intros (m1 & STORE & SEP).\n  set (rs1 := undef_regs (destroyed_by_setstack ty) rs).\n  assert (AG1: agree_regs j ls rs1).\n  { red; intros. unfold rs1. destruct (In_dec mreg_eq r0 (destroyed_by_setstack ty)).\n    erewrite ls_temp_undef by eauto. auto.\n    rewrite undef_regs_other by auto. apply AG. }\n  rewrite sep_swap in SEP.\n  exploit (IHl (pos1 + sz) rs1 m1); eauto.\n  intros (rs2 & m2 & A & B & C & D).\n  exists rs2, m2.\n  split. eapply star_left; eauto. constructor. exact STORE. auto. traceEq.\n  split. rewrite sep_assoc, sep_swap. exact B.\n  split. intros. apply C. unfold store_stack in STORE; simpl in STORE. eapply Mem.perm_store_1; eauto.\n  auto.\nQed.\n\nEnd SAVE_CALLEE_SAVE.\n\nRemark LTL_undef_regs_same:\n  forall r rl ls, In r rl -> LTL.undef_regs rl ls (R r) = Vundef.\nProof.\n  induction rl; simpl; intros. contradiction.\n  unfold Locmap.set. destruct (Loc.eq (R a) (R r)). auto.\n  destruct (Loc.diff_dec (R a) (R r)); auto.\n  apply IHrl. intuition congruence.\nQed.\n\nRemark LTL_undef_regs_others:\n  forall r rl ls, ~In r rl -> LTL.undef_regs rl ls (R r) = ls (R r).\nProof.\n  induction rl; simpl; intros. auto.\n  rewrite Locmap.gso. apply IHrl. intuition. red. intuition.\nQed.\n\nRemark LTL_undef_regs_slot:\n  forall sl ofs ty rl ls, LTL.undef_regs rl ls (S sl ofs ty) = ls (S sl ofs ty).\nProof.\n  induction rl; simpl; intros. auto.\n  rewrite Locmap.gso. apply IHrl. red; auto.\nQed.\n\nRemark undef_regs_type:\n  forall ty l rl ls,\n  Val.has_type (ls l) ty -> Val.has_type (LTL.undef_regs rl ls l) ty.\nProof.\n  induction rl; simpl; intros.\n- auto.\n- unfold Locmap.set. destruct (Loc.eq (R a) l). red; auto.\n  destruct (Loc.diff_dec (R a) l); auto. red; auto.\nQed.\n\nLemma save_callee_save_correct:\n  forall j ls ls0 rs sp cs fb k m P,\n  m |= range sp fe.(fe_ofs_callee_save) (size_callee_save_area b fe.(fe_ofs_callee_save)) ** P ->\n  (forall r, Val.has_type (ls (R r)) (mreg_type r)) ->\n  agree_callee_save ls ls0 ->\n  agree_regs j ls rs ->\n  let ls1 := LTL.undef_regs destroyed_at_function_entry (LTL.call_regs ls) in\n  let rs1 := undef_regs destroyed_at_function_entry rs in\n  exists rs', exists m',\n     star step tge\n        (State cs fb (Vptr sp Ptrofs.zero) (save_callee_save fe k) rs1 m)\n     E0 (State cs fb (Vptr sp Ptrofs.zero) k rs' m')\n  /\\ m' |= contains_callee_saves j sp fe.(fe_ofs_callee_save) b.(used_callee_save) ls0 ** P\n  /\\ (forall ofs k p, Mem.perm m sp ofs k p -> Mem.perm m' sp ofs k p)\n  /\\ agree_regs j ls1 rs'.\nProof.\n  intros until P; intros SEP TY AGCS AG; intros ls1 rs1.\n  exploit (save_callee_save_rec_correct j cs fb sp ls1).\n- intros. unfold ls1. apply LTL_undef_regs_same. eapply destroyed_by_setstack_function_entry; eauto.\n- intros. unfold ls1. apply undef_regs_type. apply TY.\n- exact b.(used_callee_save_prop).\n- eexact SEP.\n- instantiate (1 := rs1). apply agree_regs_undef_regs. apply agree_regs_call_regs. auto.\n- clear SEP. intros (rs' & m' & EXEC & SEP & PERMS & AG').\n  exists rs', m'.\n  split. eexact EXEC.\n  split. rewrite (contains_callee_saves_exten j sp ls0 ls1). exact SEP.\n  intros. apply b.(used_callee_save_prop) in H.\n    unfold ls1. rewrite LTL_undef_regs_others. unfold call_regs.\n    apply AGCS; auto.\n    red; intros.\n    assert (existsb is_callee_save destroyed_at_function_entry = false)\n       by  (apply destroyed_at_function_entry_caller_save).\n    assert (existsb is_callee_save destroyed_at_function_entry = true).\n    { apply existsb_exists. exists r; auto. }\n    congruence.\n  split. exact PERMS. exact AG'.\nQed.\n\n(** As a corollary of the previous lemmas, we obtain the following\n  correctness theorem for the execution of a function prologue\n  (allocation of the frame + saving of the link and return address +\n  saving of the used callee-save registers). *)\n\nLemma function_prologue_correct:\n  forall j ls ls0 ls1 rs rs1 m1 m1' m2 sp parent ra cs fb k P,\n  agree_regs j ls rs ->\n  agree_callee_save ls ls0 ->\n  agree_outgoing_arguments (Linear.fn_sig f) ls ls0 ->\n  (forall r, Val.has_type (ls (R r)) (mreg_type r)) ->\n  ls1 = LTL.undef_regs destroyed_at_function_entry (LTL.call_regs ls) ->\n  rs1 = undef_regs destroyed_at_function_entry rs ->\n  Mem.alloc m1 0 f.(Linear.fn_stacksize) = (m2, sp) ->\n  Val.has_type parent Tptr -> Val.has_type ra Tptr ->\n  m1' |= minjection j m1 ** globalenv_inject ge j ** P ->\n  exists j', exists rs', exists m2', exists sp', exists m3', exists m4', exists m5',\n     Mem.alloc m1' 0 tf.(fn_stacksize) = (m2', sp')\n  /\\ store_stack m2' (Vptr sp' Ptrofs.zero) Tptr tf.(fn_link_ofs) parent = Some m3'\n  /\\ store_stack m3' (Vptr sp' Ptrofs.zero) Tptr tf.(fn_retaddr_ofs) ra = Some m4'\n  /\\ star step tge\n         (State cs fb (Vptr sp' Ptrofs.zero) (save_callee_save fe k) rs1 m4')\n      E0 (State cs fb (Vptr sp' Ptrofs.zero) k rs' m5')\n  /\\ agree_regs j' ls1 rs'\n  /\\ agree_locs ls1 ls0\n  /\\ m5' |= frame_contents j' sp' ls1 ls0 parent ra ** minjection j' m2 ** globalenv_inject ge j' ** P\n  /\\ j' sp = Some(sp', fe.(fe_stack_data))\n  /\\ inject_incr j j'.\nProof.\n  intros until P; intros AGREGS AGCS AGARGS WTREGS LS1 RS1 ALLOC TYPAR TYRA SEP.\n  rewrite unfold_transf_function.\n  unfold fn_stacksize, fn_link_ofs, fn_retaddr_ofs.\n  (* Stack layout info *)\nLocal Opaque b fe.\n  generalize (frame_env_range b) (frame_env_aligned b). replace (make_env b) with fe by auto. simpl.\n  intros LAYOUT1 LAYOUT2.\n  (* Allocation step *)\n  destruct (Mem.alloc m1' 0 (fe_size fe)) as [m2' sp'] eqn:ALLOC'.\n  exploit alloc_parallel_rule_2.\n  eexact SEP. eexact ALLOC. eexact ALLOC'.\n  instantiate (1 := fe_stack_data fe). tauto.\n  reflexivity.\n  instantiate (1 := fe_stack_data fe + bound_stack_data b). rewrite Z.max_comm. reflexivity.\n  generalize (bound_stack_data_pos b) size_no_overflow; lia.\n  tauto.\n  tauto.\n  clear SEP. intros (j' & SEP & INCR & SAME).\n  (* Remember the freeable permissions using a mconj *)\n  assert (SEPCONJ:\n    m2' |= mconj (range sp' 0 (fe_stack_data fe) ** range sp' (fe_stack_data fe + bound_stack_data b) (fe_size fe))\n                 (range sp' 0 (fe_stack_data fe) ** range sp' (fe_stack_data fe + bound_stack_data b) (fe_size fe))\n           ** minjection j' m2 ** globalenv_inject ge j' ** P).\n  { apply mconj_intro; rewrite sep_assoc; assumption. }\n  (* Dividing up the frame *)\n  apply (frame_env_separated b) in SEP. replace (make_env b) with fe in SEP by auto.\n  (* Store of parent *)\n  rewrite sep_swap3 in SEP.\n  apply (range_contains Mptr) in SEP; [|tauto].\n  exploit (contains_set_stack (fun v' => v' = parent) parent (fun _ => True) m2' Tptr).\n  rewrite chunk_of_Tptr; eexact SEP. apply Val.load_result_same; auto.\n  clear SEP; intros (m3' & STORE_PARENT & SEP).\n  rewrite sep_swap3 in SEP.\n  (* Store of return address *)\n  rewrite sep_swap4 in SEP.\n  apply (range_contains Mptr) in SEP; [|tauto].\n  exploit (contains_set_stack (fun v' => v' = ra) ra (fun _ => True) m3' Tptr).\n  rewrite chunk_of_Tptr; eexact SEP. apply Val.load_result_same; auto.\n  clear SEP; intros (m4' & STORE_RETADDR & SEP).\n  rewrite sep_swap4 in SEP.\n  (* Saving callee-save registers *)\n  rewrite sep_swap5 in SEP.\n  exploit (save_callee_save_correct j' ls ls0 rs); eauto.\n  apply agree_regs_inject_incr with j; auto.\n  replace (LTL.undef_regs destroyed_at_function_entry (call_regs ls)) with ls1 by auto.\n  replace (undef_regs destroyed_at_function_entry rs) with rs1 by auto.\n  clear SEP; intros (rs2 & m5' & SAVE_CS & SEP & PERMS & AGREGS').\n  rewrite sep_swap5 in SEP.\n  (* Materializing the Local and Outgoing locations *)\n  exploit (initial_locations j'). eexact SEP. tauto.\n  instantiate (1 := Local). instantiate (1 := ls1).\n  intros; rewrite LS1. rewrite LTL_undef_regs_slot. reflexivity.\n  clear SEP; intros SEP.\n  rewrite sep_swap in SEP.\n  exploit (initial_locations j'). eexact SEP. tauto.\n  instantiate (1 := Outgoing). instantiate (1 := ls1).\n  intros; rewrite LS1. rewrite LTL_undef_regs_slot. reflexivity.\n  clear SEP; intros SEP.\n  rewrite sep_swap in SEP.\n  (* Now we frame this *)\n  assert (SEPFINAL: m5' |= frame_contents j' sp' ls1 ls0 parent ra ** minjection j' m2 ** globalenv_inject ge j' ** P).\n  { eapply frame_mconj. eexact SEPCONJ.\n    rewrite chunk_of_Tptr in SEP.\n    unfold frame_contents_1; rewrite ! sep_assoc. exact SEP.\n    assert (forall ofs k p, Mem.perm m2' sp' ofs k p -> Mem.perm m5' sp' ofs k p).\n    { intros. apply PERMS.\n      unfold store_stack in STORE_PARENT, STORE_RETADDR.\n      simpl in STORE_PARENT, STORE_RETADDR.\n      eauto using Mem.perm_store_1. }\n    eapply sep_preserved. eapply sep_proj1. eapply mconj_proj2. eexact SEPCONJ.\n    intros; apply range_preserved with m2'; auto.\n    intros; apply range_preserved with m2'; auto.\n  }\n  clear SEP SEPCONJ.\n(* Conclusions *)\n  exists j', rs2, m2', sp', m3', m4', m5'.\n  split. auto.\n  split. exact STORE_PARENT.\n  split. exact STORE_RETADDR.\n  split. eexact SAVE_CS.\n  split. exact AGREGS'.\n  split. rewrite LS1. apply agree_locs_undef_locs; [|reflexivity].\n    constructor; intros. unfold call_regs. apply AGCS.\n    unfold mreg_within_bounds in H; tauto.\n    unfold call_regs. apply AGARGS. apply incoming_slot_in_parameters; auto.\n  split. exact SEPFINAL.\n  split. exact SAME. exact INCR.\nQed.\n\n(** The following lemmas show the correctness of the register reloading\n  code generated by [reload_callee_save]: after this code has executed,\n  all callee-save registers contain the same values they had at\n  function entry. *)\n\nSection RESTORE_CALLEE_SAVE.\n\nVariable j: meminj.\nVariable cs: list stackframe.\nVariable fb: block.\nVariable sp: block.\nVariable ls0: locset.\nVariable m: mem.\n\nDefinition agree_unused (ls0: locset) (rs: regset) : Prop :=\n  forall r, ~(mreg_within_bounds b r) -> Val.inject j (ls0 (R r)) (rs r).\n\nLemma restore_callee_save_rec_correct:\n  forall l ofs rs k,\n  m |= contains_callee_saves j sp ofs l ls0 ->\n  agree_unused ls0 rs ->\n  (forall r, In r l -> mreg_within_bounds b r) ->\n  exists rs',\n    star step tge\n      (State cs fb (Vptr sp Ptrofs.zero) (restore_callee_save_rec l ofs k) rs m)\n   E0 (State cs fb (Vptr sp Ptrofs.zero) k rs' m)\n  /\\ (forall r, In r l -> Val.inject j (ls0 (R r)) (rs' r))\n  /\\ (forall r, ~(In r l) -> rs' r = rs r)\n  /\\ agree_unused ls0 rs'.\nProof.\nLocal Opaque mreg_type.\n  induction l as [ | r l]; simpl; intros.\n- (* base case *)\n  exists rs. intuition auto. apply star_refl.\n- (* inductive case *)\n  set (ty := mreg_type r) in *.\n  set (sz := AST.typesize ty) in *.\n  set (ofs1 := align ofs sz).\n  assert (SZPOS: sz > 0) by (apply AST.typesize_pos).\n  assert (OFSLE: ofs <= ofs1) by (apply align_le; auto).\n  assert (BOUND: mreg_within_bounds b r) by eauto.\n  exploit contains_get_stack.\n    eapply sep_proj1; eassumption.\n  intros (v & LOAD & SPEC).\n  exploit (IHl (ofs1 + sz) (rs#r <- v)).\n    eapply sep_proj2; eassumption.\n    red; intros. rewrite Regmap.gso. auto. intuition congruence.\n    eauto.\n  intros (rs' & A & B & C & D).\n  exists rs'.\n  split. eapply star_step; eauto.\n    econstructor. exact LOAD. traceEq.\n  split. intros.\n    destruct (In_dec mreg_eq r0 l). auto.\n    assert (r = r0) by tauto. subst r0.\n    rewrite C by auto. rewrite Regmap.gss. exact SPEC.\n  split. intros.\n    rewrite C by tauto. apply Regmap.gso. intuition auto.\n  exact D.\nQed.\n\nEnd RESTORE_CALLEE_SAVE.\n\nLemma restore_callee_save_correct:\n  forall m j sp ls ls0 pa ra P rs k cs fb,\n  m |= frame_contents j sp ls ls0 pa ra ** P ->\n  agree_unused j ls0 rs ->\n  exists rs',\n    star step tge\n       (State cs fb (Vptr sp Ptrofs.zero) (restore_callee_save fe k) rs m)\n    E0 (State cs fb (Vptr sp Ptrofs.zero) k rs' m)\n  /\\ (forall r,\n        is_callee_save r = true -> Val.inject j (ls0 (R r)) (rs' r))\n  /\\ (forall r,\n        is_callee_save r = false -> rs' r = rs r).\nProof.\n  intros.\n  unfold frame_contents, frame_contents_1 in H.\n  apply mconj_proj1 in H. rewrite ! sep_assoc in H. apply sep_pick5 in H.\n  exploit restore_callee_save_rec_correct; eauto.\n  intros; unfold mreg_within_bounds; auto.\n  intros (rs' & A & B & C & D).\n  exists rs'.\n  split. eexact A.\n  split; intros.\n  destruct (In_dec mreg_eq r (used_callee_save b)).\n  apply B; auto.\n  rewrite C by auto. apply H0. unfold mreg_within_bounds; tauto.\n  apply C. red; intros. apply (used_callee_save_prop b) in H2. congruence.\nQed.\n\n(** As a corollary, we obtain the following correctness result for\n  the execution of a function epilogue (reloading of used callee-save\n  registers + reloading of the link and return address + freeing\n  of the frame). *)\n\nLemma function_epilogue_correct:\n  forall m' j sp' ls ls0 pa ra P m rs sp m1 k cs fb,\n  m' |= frame_contents j sp' ls ls0 pa ra ** minjection j m ** P ->\n  agree_regs j ls rs ->\n  agree_locs ls ls0 ->\n  j sp = Some(sp', fe.(fe_stack_data)) ->\n  Mem.free m sp 0 f.(Linear.fn_stacksize) = Some m1 ->\n  exists rs1, exists m1',\n     load_stack m' (Vptr sp' Ptrofs.zero) Tptr tf.(fn_link_ofs) = Some pa\n  /\\ load_stack m' (Vptr sp' Ptrofs.zero) Tptr tf.(fn_retaddr_ofs) = Some ra\n  /\\ Mem.free m' sp' 0 tf.(fn_stacksize) = Some m1'\n  /\\ star step tge\n       (State cs fb (Vptr sp' Ptrofs.zero) (restore_callee_save fe k) rs m')\n    E0 (State cs fb (Vptr sp' Ptrofs.zero) k rs1 m')\n  /\\ agree_regs j (return_regs ls0 ls) rs1\n  /\\ agree_callee_save (return_regs ls0 ls) ls0\n  /\\ m1' |= minjection j m1 ** P.\nProof.\n  intros until fb; intros SEP AGR AGL INJ FREE.\n  (* Can free *)\n  exploit free_parallel_rule.\n    rewrite <- sep_assoc. eapply mconj_proj2. eexact SEP.\n    eexact FREE.\n    eexact INJ.\n    auto. rewrite Z.max_comm; reflexivity.\n  intros (m1' & FREE' & SEP').\n  (* Reloading the callee-save registers *)\n  exploit restore_callee_save_correct.\n    eexact SEP.\n    instantiate (1 := rs).\n    red; intros. destruct AGL. rewrite <- agree_unused_reg0 by auto. apply AGR.\n  intros (rs' & LOAD_CS & CS & NCS).\n  (* Reloading the back link and return address *)\n  unfold frame_contents in SEP; apply mconj_proj1 in SEP.\n  unfold frame_contents_1 in SEP; rewrite ! sep_assoc in SEP.\n  exploit (hasvalue_get_stack Tptr). rewrite chunk_of_Tptr. eapply sep_pick3; eexact SEP. intros LOAD_LINK.\n  exploit (hasvalue_get_stack Tptr). rewrite chunk_of_Tptr. eapply sep_pick4; eexact SEP. intros LOAD_RETADDR.\n  clear SEP.\n  (* Conclusions *)\n  rewrite unfold_transf_function; simpl.\n  exists rs', m1'.\n  split. assumption.\n  split. assumption.\n  split. assumption.\n  split. eassumption.\n  split. red; unfold return_regs; intros.\n    destruct (is_callee_save r) eqn:C.\n    apply CS; auto.\n    rewrite NCS by auto. apply AGR.\n  split. red; unfold return_regs; intros.\n    destruct l. rewrite H; auto. destruct sl; auto; contradiction. \n  assumption.\nQed.\n\nEnd FRAME_PROPERTIES.\n\n(** * Call stack invariants *)\n\n(** This is the memory assertion that captures the contents of the stack frames\n  mentioned in the call stacks. *)\n\nFixpoint stack_contents (j: meminj) (cs: list Linear.stackframe) (cs': list Mach.stackframe) : massert :=\n  match cs, cs' with\n  | nil, nil => pure True\n  | Linear.Stackframe f _ ls c :: cs, Mach.Stackframe fb (Vptr sp' _) ra c' :: cs' =>\n      frame_contents f j sp' ls (parent_locset cs) (parent_sp cs') (parent_ra cs')\n      ** stack_contents j cs cs'\n  | _, _ => pure False\n  end.\n\n(** [match_stacks] captures additional properties (not related to memory)\n  of the Linear and Mach call stacks. *)\n\nInductive match_stacks (j: meminj):\n       list Linear.stackframe -> list stackframe -> signature -> Prop :=\n  | match_stacks_empty: forall sg,\n      tailcall_possible sg ->\n      match_stacks j nil nil sg\n  | match_stacks_cons: forall f sp ls c cs fb sp' ra c' cs' sg trf\n        (TAIL: is_tail c (Linear.fn_code f))\n        (FINDF: Genv.find_funct_ptr tge fb = Some (Internal trf))\n        (TRF: transf_function f = OK trf)\n        (TRC: transl_code (make_env (function_bounds f)) c = c')\n        (INJ: j sp = Some(sp', (fe_stack_data (make_env (function_bounds f)))))\n        (TY_RA: Val.has_type ra Tptr)\n        (AGL: agree_locs f ls (parent_locset cs))\n        (ARGS: forall ofs ty,\n           In (S Outgoing ofs ty) (regs_of_rpairs (loc_arguments sg)) ->\n           slot_within_bounds (function_bounds f) Outgoing ofs ty)\n        (STK: match_stacks j cs cs' (Linear.fn_sig f)),\n      match_stacks j\n                   (Linear.Stackframe f (Vptr sp Ptrofs.zero) ls c :: cs)\n                   (Stackframe fb (Vptr sp' Ptrofs.zero) ra c' :: cs')\n                   sg.\n\n(** Invariance with respect to change of memory injection. *)\n\nLemma stack_contents_change_meminj:\n  forall m j j', inject_incr j j' ->\n  forall cs cs' P,\n  m |= stack_contents j cs cs' ** P ->\n  m |= stack_contents j' cs cs' ** P.\nProof.\nLocal Opaque sepconj.\n  induction cs as [ | [] cs]; destruct cs' as [ | [] cs']; simpl; intros; auto.\n  destruct sp0; auto.\n  rewrite sep_assoc in *.\n  apply frame_contents_incr with (j := j); auto.\n  rewrite sep_swap. apply IHcs. rewrite sep_swap. assumption.\nQed.\n\nLemma match_stacks_change_meminj:\n  forall j j', inject_incr j j' ->\n  forall cs cs' sg,\n  match_stacks j cs cs' sg ->\n  match_stacks j' cs cs' sg.\nProof.\n  induction 2; intros.\n- constructor; auto.\n- econstructor; eauto.\nQed.\n\n(** Invariance with respect to change of signature. *)\n\nLemma match_stacks_change_sig:\n  forall sg1 j cs cs' sg,\n  match_stacks j cs cs' sg ->\n  tailcall_possible sg1 ->\n  match_stacks j cs cs' sg1.\nProof.\n  induction 1; intros.\n  econstructor; eauto.\n  econstructor; eauto. intros. elim (H0 _ H1).\nQed.\n\n(** Typing properties of [match_stacks]. *)\n\nLemma match_stacks_type_sp:\n  forall j cs cs' sg,\n  match_stacks j cs cs' sg ->\n  Val.has_type (parent_sp cs') Tptr.\nProof.\n  induction 1; unfold parent_sp. apply Val.Vnullptr_has_type. apply Val.Vptr_has_type.\nQed.\n\nLemma match_stacks_type_retaddr:\n  forall j cs cs' sg,\n  match_stacks j cs cs' sg ->\n  Val.has_type (parent_ra cs') Tptr.\nProof.\n  induction 1; unfold parent_ra. apply Val.Vnullptr_has_type. auto.\nQed.\n\n(** * Syntactic properties of the translation *)\n\n(** Preservation of code labels through the translation. *)\n\nSection LABELS.\n\nRemark find_label_save_callee_save:\n  forall lbl l ofs k,\n  Mach.find_label lbl (save_callee_save_rec l ofs k) = Mach.find_label lbl k.\nProof.\n  induction l; simpl; auto.\nQed.\n\nRemark find_label_restore_callee_save:\n  forall lbl l ofs k,\n  Mach.find_label lbl (restore_callee_save_rec l ofs k) = Mach.find_label lbl k.\nProof.\n  induction l; simpl; auto.\nQed.\n\nLemma transl_code_eq:\n  forall fe i c, transl_code fe (i :: c) = transl_instr fe i (transl_code fe c).\nProof.\n  unfold transl_code; intros. rewrite list_fold_right_eq. auto.\nQed.\n\nLemma find_label_transl_code:\n  forall fe lbl c,\n  Mach.find_label lbl (transl_code fe c) =\n    option_map (transl_code fe) (Linear.find_label lbl c).\nProof.\n  induction c; simpl; intros.\n- auto.\n- rewrite transl_code_eq.\n  destruct a; unfold transl_instr; auto.\n  destruct s; simpl; auto.\n  destruct s; simpl; auto.\n  unfold restore_callee_save. rewrite find_label_restore_callee_save. auto.\n  simpl. destruct (peq lbl l). reflexivity. auto.\n  unfold restore_callee_save. rewrite find_label_restore_callee_save. auto.\nQed.\n\nLemma transl_find_label:\n  forall f tf lbl c,\n  transf_function f = OK tf ->\n  Linear.find_label lbl f.(Linear.fn_code) = Some c ->\n  Mach.find_label lbl tf.(Mach.fn_code) =\n    Some (transl_code (make_env (function_bounds f)) c).\nProof.\n  intros. rewrite (unfold_transf_function _ _ H).  simpl.\n  unfold transl_body. unfold save_callee_save. rewrite find_label_save_callee_save.\n  rewrite find_label_transl_code. rewrite H0. reflexivity.\nQed.\n\nEnd LABELS.\n\n(** Code tail property for Linear executions. *)\n\nLemma find_label_tail:\n  forall lbl c c',\n  Linear.find_label lbl c = Some c' -> is_tail c' c.\nProof.\n  induction c; simpl.\n  intros; discriminate.\n  intro c'. case (Linear.is_label lbl a); intros.\n  injection H; intro; subst c'. auto with coqlib.\n  auto with coqlib.\nQed.\n\n(** Code tail property for translations *)\n\nLemma is_tail_save_callee_save:\n  forall l ofs k,\n  is_tail k (save_callee_save_rec l ofs k).\nProof.\n  induction l; intros; simpl. auto with coqlib.\n  constructor; auto.\nQed.\n\nLemma is_tail_restore_callee_save:\n  forall l ofs k,\n  is_tail k (restore_callee_save_rec l ofs k).\nProof.\n  induction l; intros; simpl. auto with coqlib.\n  constructor; auto.\nQed.\n\nLemma is_tail_transl_instr:\n  forall fe i k,\n  is_tail k (transl_instr fe i k).\nProof.\n  intros. destruct i; unfold transl_instr; auto with coqlib.\n  destruct s; auto with coqlib.\n  destruct s; auto with coqlib.\n  unfold restore_callee_save.  eapply is_tail_trans. 2: apply is_tail_restore_callee_save. auto with coqlib.\n  unfold restore_callee_save.  eapply is_tail_trans. 2: apply is_tail_restore_callee_save. auto with coqlib.\nQed.\n\nLemma is_tail_transl_code:\n  forall fe c1 c2, is_tail c1 c2 -> is_tail (transl_code fe c1) (transl_code fe c2).\nProof.\n  induction 1; simpl. auto with coqlib.\n  rewrite transl_code_eq.\n  eapply is_tail_trans. eauto. apply is_tail_transl_instr.\nQed.\n\nLemma is_tail_transf_function:\n  forall f tf c,\n  transf_function f = OK tf ->\n  is_tail c (Linear.fn_code f) ->\n  is_tail (transl_code (make_env (function_bounds f)) c) (fn_code tf).\nProof.\n  intros. rewrite (unfold_transf_function _ _ H). simpl.\n  unfold transl_body, save_callee_save.\n  eapply is_tail_trans. 2: apply is_tail_save_callee_save.\n  apply is_tail_transl_code; auto.\nQed.\n\n(** * Semantic preservation *)\n\n(** Preservation / translation of global symbols and functions. *)\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 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 b f,\n  Genv.find_funct_ptr ge b = Some f ->\n  exists tf,\n  Genv.find_funct_ptr tge b = Some tf /\\ transf_fundef f = OK tf.\nProof (Genv.find_funct_ptr_transf_partial TRANSF).\n\nLemma sig_preserved:\n  forall f tf, transf_fundef f = OK tf -> Mach.funsig tf = Linear.funsig f.\nProof.\n  intros until tf; unfold transf_fundef, transf_partial_fundef.\n  destruct f; intros; monadInv H.\n  rewrite (unfold_transf_function _ _ EQ). auto.\n  auto.\nQed.\n\nLemma find_function_translated:\n  forall j ls rs m ros f,\n  agree_regs j ls rs ->\n  m |= globalenv_inject ge j ->\n  Linear.find_function ge ros ls = Some f ->\n  exists bf, exists tf,\n     find_function_ptr tge ros rs = Some bf\n  /\\ Genv.find_funct_ptr tge bf = Some tf\n  /\\ transf_fundef f = OK tf.\nProof.\n  intros until f; intros AG [bound [_ [?????]]] FF.\n  destruct ros; simpl in FF.\n- exploit Genv.find_funct_inv; eauto. intros [b EQ]. rewrite EQ in FF.\n  rewrite Genv.find_funct_find_funct_ptr in FF.\n  exploit function_ptr_translated; eauto. intros [tf [A B]].\n  exists b; exists tf; split; auto. simpl.\n  generalize (AG m0). rewrite EQ. intro INJ. inv INJ.\n  rewrite DOMAIN in H2. inv H2. simpl. auto. eapply FUNCTIONS; eauto.\n- destruct (Genv.find_symbol ge i) as [b|] eqn:?; try discriminate.\n  exploit function_ptr_translated; eauto. intros [tf [A B]].\n  exists b; exists tf; split; auto. simpl.\n  rewrite symbols_preserved. auto.\nQed.\n\n(** Preservation of the arguments to an external call. *)\n\nSection EXTERNAL_ARGUMENTS.\n\nVariable j: meminj.\nVariable cs: list Linear.stackframe.\nVariable cs': list stackframe.\nVariable sg: signature.\nVariables bound bound': block.\nHypothesis MS: match_stacks j cs cs' sg.\nVariable ls: locset.\nVariable rs: regset.\nHypothesis AGR: agree_regs j ls rs.\nHypothesis AGCS: agree_callee_save ls (parent_locset cs).\nHypothesis AGARGS: agree_outgoing_arguments sg ls (parent_locset cs).\nVariable m': mem.\nHypothesis SEP: m' |= stack_contents j cs cs'.\n\nLemma transl_external_argument:\n  forall l,\n  In l (regs_of_rpairs (loc_arguments sg)) ->\n  exists v, extcall_arg rs m' (parent_sp cs') l v /\\ Val.inject j (ls l) v.\nProof.\n  intros.\n  assert (loc_argument_acceptable l) by (apply loc_arguments_acceptable_2 with sg; auto).\n  destruct l; red in H0.\n- exists (rs r); split. constructor. auto.\n- destruct sl; try contradiction.\n  inv MS.\n+ elim (H1 _ H).\n+ simpl in SEP. unfold parent_sp.\n  assert (slot_valid f Outgoing pos ty = true).\n  { destruct H0. unfold slot_valid, proj_sumbool.\n    rewrite zle_true by lia. rewrite pred_dec_true by auto. reflexivity. }\n  assert (slot_within_bounds (function_bounds f) Outgoing pos ty) by eauto.\n  exploit frame_get_outgoing; eauto. intros (v & A & B).\n  exists v; split.\n  constructor. exact A. rewrite AGARGS by auto. exact B. \nQed.\n\nLemma transl_external_argument_2:\n  forall p,\n  In p (loc_arguments sg) ->\n  exists v, extcall_arg_pair rs m' (parent_sp cs') p v /\\ Val.inject j (Locmap.getpair p ls) v.\nProof.\n  intros. destruct p as [l | l1 l2].\n- destruct (transl_external_argument l) as (v & A & B). eapply in_regs_of_rpairs; eauto; simpl; auto.\n  exists v; split; auto. constructor; auto.\n- destruct (transl_external_argument l1) as (v1 & A1 & B1). eapply in_regs_of_rpairs; eauto; simpl; auto.\n  destruct (transl_external_argument l2) as (v2 & A2 & B2). eapply in_regs_of_rpairs; eauto; simpl; auto.\n  exists (Val.longofwords v1 v2); split.\n  constructor; auto.\n  apply Val.longofwords_inject; auto.\nQed.\n\nLemma transl_external_arguments_rec:\n  forall locs,\n  incl locs (loc_arguments sg) ->\n  exists vl,\n      list_forall2 (extcall_arg_pair rs m' (parent_sp cs')) locs vl\n   /\\ Val.inject_list j (map (fun p => Locmap.getpair p ls) locs) vl.\nProof.\n  induction locs; simpl; intros.\n  exists (@nil val); split. constructor. constructor.\n  exploit transl_external_argument_2; eauto with coqlib. intros [v [A B]].\n  exploit IHlocs; eauto with coqlib. intros [vl [C D]].\n  exists (v :: vl); split; constructor; auto.\nQed.\n\nLemma transl_external_arguments:\n  exists vl,\n      extcall_arguments rs m' (parent_sp cs') sg vl\n   /\\ Val.inject_list j (map (fun p => Locmap.getpair p ls) (loc_arguments sg)) vl.\nProof.\n  unfold extcall_arguments.\n  apply transl_external_arguments_rec.\n  auto with coqlib.\nQed.\n\nEnd EXTERNAL_ARGUMENTS.\n\n(** Preservation of the arguments to a builtin. *)\n\nSection BUILTIN_ARGUMENTS.\n\nVariable f: Linear.function.\nLet b := function_bounds f.\nLet fe := make_env b.\nVariable tf: Mach.function.\nHypothesis TRANSF_F: transf_function f = OK tf.\nVariable j: meminj.\nVariables m m': mem.\nVariables ls ls0: locset.\nVariable rs: regset.\nVariables sp sp': block.\nVariables parent retaddr: val.\nHypothesis INJ: j sp = Some(sp', fe.(fe_stack_data)).\nHypothesis AGR: agree_regs j ls rs.\nHypothesis SEP: m' |= frame_contents f j sp' ls ls0 parent retaddr ** minjection j m ** globalenv_inject ge j.\n\nLemma transl_builtin_arg_correct:\n  forall a v,\n  eval_builtin_arg ge ls (Vptr sp Ptrofs.zero) m a v ->\n  (forall l, In l (params_of_builtin_arg a) -> loc_valid f l = true) ->\n  (forall sl ofs ty, In (S sl ofs ty) (params_of_builtin_arg a) -> slot_within_bounds b sl ofs ty) ->\n  exists v',\n     eval_builtin_arg ge rs (Vptr sp' Ptrofs.zero) m' (transl_builtin_arg fe a) v'\n  /\\ Val.inject j v v'.\nProof.\n  assert (SYMB: forall id ofs, Val.inject j (Senv.symbol_address ge id ofs) (Senv.symbol_address ge id ofs)).\n  { assert (G: meminj_preserves_globals ge j).\n    { eapply globalenv_inject_preserves_globals. eapply sep_proj2. eapply sep_proj2. eexact SEP. }\n    intros; unfold Senv.symbol_address; simpl; unfold Genv.symbol_address.\n    destruct (Genv.find_symbol ge id) eqn:FS; auto.\n    destruct G. econstructor. eauto. rewrite Ptrofs.add_zero; auto. }\nLocal Opaque fe.\n  induction 1; simpl; intros VALID BOUNDS.\n- assert (loc_valid f x = true) by auto.\n  destruct x as [r | [] ofs ty]; try discriminate.\n  + exists (rs r); auto with barg.\n  + exploit frame_get_local; eauto. intros (v & A & B).\n    exists v; split; auto. constructor; auto.\n- econstructor; eauto with barg.\n- econstructor; eauto with barg.\n- econstructor; eauto with barg.\n- econstructor; eauto with barg.\n- set (ofs' := Ptrofs.add ofs (Ptrofs.repr (fe_stack_data fe))).\n  apply sep_proj2 in SEP. apply sep_proj1 in SEP. exploit loadv_parallel_rule; eauto.\n  instantiate (1 := Val.offset_ptr (Vptr sp' Ptrofs.zero) ofs').\n  simpl. rewrite ! Ptrofs.add_zero_l. econstructor; eauto.\n  intros (v' & A & B). exists v'; split; auto. constructor; auto.\n- econstructor; split; eauto with barg.\n  unfold Val.offset_ptr. rewrite ! Ptrofs.add_zero_l. econstructor; eauto.\n- apply sep_proj2 in SEP. apply sep_proj1 in SEP. exploit loadv_parallel_rule; eauto.\n  intros (v' & A & B). exists v'; auto with barg.\n- econstructor; split; eauto with barg.\n- destruct IHeval_builtin_arg1 as (v1 & A1 & B1); auto using in_or_app.\n  destruct IHeval_builtin_arg2 as (v2 & A2 & B2); auto using in_or_app.\n  exists (Val.longofwords v1 v2); split; auto with barg.\n  apply Val.longofwords_inject; auto.\n- destruct IHeval_builtin_arg1 as (v1' & A1 & B1); auto using in_or_app.\n  destruct IHeval_builtin_arg2 as (v2' & A2 & B2); auto using in_or_app.\n  econstructor; split. eauto with barg.\n  destruct Archi.ptr64; auto using Val.add_inject, Val.addl_inject.\nQed.\n\nLemma transl_builtin_args_correct:\n  forall al vl,\n  eval_builtin_args ge ls (Vptr sp Ptrofs.zero) m al vl ->\n  (forall l, In l (params_of_builtin_args al) -> loc_valid f l = true) ->\n  (forall sl ofs ty, In (S sl ofs ty) (params_of_builtin_args al) -> slot_within_bounds b sl ofs ty) ->\n  exists vl',\n     eval_builtin_args ge rs (Vptr sp' Ptrofs.zero) m' (List.map (transl_builtin_arg fe) al) vl'\n  /\\ Val.inject_list j vl vl'.\nProof.\n  induction 1; simpl; intros VALID BOUNDS.\n- exists (@nil val); split; constructor.\n- exploit transl_builtin_arg_correct; eauto using in_or_app. intros (v1' & A & B).\n  exploit IHlist_forall2; eauto using in_or_app. intros (vl' & C & D).\n  exists (v1'::vl'); split; constructor; auto.\nQed.\n\nEnd BUILTIN_ARGUMENTS.\n\n(** The proof of semantic preservation relies on simulation diagrams\n  of the following form:\n<<\n           st1 --------------- st2\n            |                   |\n           t|                  +|t\n            |                   |\n            v                   v\n           st1'--------------- st2'\n>>\n  Matching between source and target states is defined by [match_states]\n  below.  It implies:\n- Satisfaction of the separation logic assertions that describe the contents\n  of memory.  This is a separating conjunction of facts about:\n-- the current stack frame\n-- the frames in the call stack\n-- the injection from the Linear memory state into the Mach memory state\n-- the preservation of the global environment.\n- Agreement between, on the Linear side, the location sets [ls]\n  and [parent_locset s] of the current function and its caller,\n  and on the Mach side the register set [rs].\n- The Linear code [c] is a suffix of the code of the\n  function [f] being executed.\n- Well-typedness of [f].\n*)\n\nInductive match_states: Linear.state -> Mach.state -> Prop :=\n  | match_states_intro:\n      forall cs f sp c ls m cs' fb sp' rs m' j tf\n        (STACKS: match_stacks j cs cs' f.(Linear.fn_sig))\n        (TRANSL: transf_function f = OK tf)\n        (FIND: Genv.find_funct_ptr tge fb = Some (Internal tf))\n        (AGREGS: agree_regs j ls rs)\n        (AGLOCS: agree_locs f ls (parent_locset cs))\n        (INJSP: j sp = Some(sp', fe_stack_data (make_env (function_bounds f))))\n        (TAIL: is_tail c (Linear.fn_code f))\n        (SEP: m' |= frame_contents f j sp' ls (parent_locset cs) (parent_sp cs') (parent_ra cs')\n                 ** stack_contents j cs cs'\n                 ** minjection j m\n                 ** globalenv_inject ge j),\n      match_states (Linear.State cs f (Vptr sp Ptrofs.zero) c ls m)\n                   (Mach.State cs' fb (Vptr sp' Ptrofs.zero) (transl_code (make_env (function_bounds f)) c) rs m')\n  | match_states_call:\n      forall cs f ls m cs' fb rs m' j tf\n        (STACKS: match_stacks j cs cs' (Linear.funsig f))\n        (TRANSL: transf_fundef f = OK tf)\n        (FIND: Genv.find_funct_ptr tge fb = Some tf)\n        (AGREGS: agree_regs j ls rs)\n        (SEP: m' |= stack_contents j cs cs'\n                 ** minjection j m\n                 ** globalenv_inject ge j),\n      match_states (Linear.Callstate cs f ls m)\n                   (Mach.Callstate cs' fb rs m')\n  | match_states_return:\n      forall cs ls m cs' rs m' j sg\n        (STACKS: match_stacks j cs cs' sg)\n        (AGREGS: agree_regs j ls rs)\n        (SEP: m' |= stack_contents j cs cs'\n                 ** minjection j m\n                 ** globalenv_inject ge j),\n      match_states (Linear.Returnstate cs ls m)\n                  (Mach.Returnstate cs' rs m').\n\nTheorem transf_step_correct:\n  forall s1 t s2, Linear.step ge s1 t s2 ->\n  forall (WTS: wt_state s1) s1' (MS: match_states s1 s1'),\n  exists s2', plus step tge s1' t s2' /\\ match_states s2 s2'.\nProof.\n  induction 1; intros;\n  try inv MS;\n  try rewrite transl_code_eq;\n  try (generalize (function_is_within_bounds f _ (is_tail_in TAIL));\n       intro BOUND; simpl in BOUND);\n  unfold transl_instr.\n\n- (* Lgetstack *)\n  destruct BOUND as [BOUND1 BOUND2].\n  exploit wt_state_getstack; eauto. intros SV.\n  unfold destroyed_by_getstack; destruct sl.\n+ (* Lgetstack, local *)\n  exploit frame_get_local; eauto. intros (v & A & B).\n  econstructor; split.\n  apply plus_one. apply exec_Mgetstack. exact A.\n  econstructor; eauto with coqlib.\n  apply agree_regs_set_reg; auto.\n  apply agree_locs_set_reg; auto.\n+ (* Lgetstack, incoming *)\n  unfold slot_valid in SV. InvBooleans.\n  exploit incoming_slot_in_parameters; eauto. intros IN_ARGS.\n  inversion STACKS; clear STACKS.\n  elim (H1 _ IN_ARGS).\n  subst s cs'.\n  exploit frame_get_outgoing.\n  apply sep_proj2 in SEP. simpl in SEP. rewrite sep_assoc in SEP. eexact SEP.\n  eapply ARGS; eauto.\n  eapply slot_outgoing_argument_valid; eauto.\n  intros (v & A & B).\n  econstructor; split.\n  apply plus_one. eapply exec_Mgetparam; eauto.\n  rewrite (unfold_transf_function _ _ TRANSL). unfold fn_link_ofs.\n  eapply frame_get_parent. eexact SEP.\n  econstructor; eauto with coqlib. econstructor; eauto.\n  apply agree_regs_set_reg. apply agree_regs_set_reg. auto. auto.\n  erewrite agree_incoming by eauto. exact B.\n  apply agree_locs_set_reg; auto. apply agree_locs_undef_locs; auto.\n+ (* Lgetstack, outgoing *)\n  exploit frame_get_outgoing; eauto. intros (v & A & B).\n  econstructor; split.\n  apply plus_one. apply exec_Mgetstack. exact A.\n  econstructor; eauto with coqlib.\n  apply agree_regs_set_reg; auto.\n  apply agree_locs_set_reg; auto.\n\n- (* Lsetstack *)\n  exploit wt_state_setstack; eauto. intros (SV & SW).\n  set (ofs' := match sl with\n               | Local => offset_local (make_env (function_bounds f)) ofs\n               | Incoming => 0 (* dummy *)\n               | Outgoing => offset_arg ofs\n               end).\n  eapply frame_undef_regs with (rl := destroyed_by_setstack ty) in SEP.\n  assert (A: exists m'',\n              store_stack m' (Vptr sp' Ptrofs.zero) ty (Ptrofs.repr ofs') (rs0 src) = Some m''\n           /\\ m'' |= frame_contents f j sp' (Locmap.set (S sl ofs ty) (rs (R src))\n                                               (LTL.undef_regs (destroyed_by_setstack ty) rs))\n                                            (parent_locset s) (parent_sp cs') (parent_ra cs')\n                  ** stack_contents j s cs' ** minjection j m ** globalenv_inject ge j).\n  { unfold ofs'; destruct sl; try discriminate.\n    eapply frame_set_local; eauto.\n    eapply frame_set_outgoing; eauto. }\n  clear SEP; destruct A as (m'' & STORE & SEP).\n  econstructor; split.\n  apply plus_one. destruct sl; try discriminate.\n    econstructor. eexact STORE. eauto.\n    econstructor. eexact STORE. eauto.\n  econstructor. eauto. eauto. eauto.\n  apply agree_regs_set_slot. apply agree_regs_undef_regs. auto.\n  apply agree_locs_set_slot. apply agree_locs_undef_locs. auto. apply destroyed_by_setstack_caller_save. auto.\n  eauto. eauto with coqlib. eauto.\n\n- (* Lop *)\n  assert (exists v',\n          eval_operation ge (Vptr sp' Ptrofs.zero) (transl_op (make_env (function_bounds f)) op) rs0##args m' = Some v'\n       /\\ Val.inject j v v').\n  eapply eval_operation_inject; eauto.\n  eapply globalenv_inject_preserves_globals. eapply sep_proj2. eapply sep_proj2. eapply sep_proj2. eexact SEP.\n  eapply agree_reglist; eauto.\n  apply sep_proj2 in SEP. apply sep_proj2 in SEP. apply sep_proj1 in SEP. exact SEP.\n  destruct H0 as [v' [A B]].\n  econstructor; split.\n  apply plus_one. econstructor.\n  instantiate (1 := v'). rewrite <- A. apply eval_operation_preserved.\n  exact symbols_preserved. eauto.\n  econstructor; eauto with coqlib.\n  apply agree_regs_set_reg; auto.\n  rewrite transl_destroyed_by_op.  apply agree_regs_undef_regs; auto.\n  apply agree_locs_set_reg; auto. apply agree_locs_undef_locs. auto. apply destroyed_by_op_caller_save.\n  apply frame_set_reg. apply frame_undef_regs. exact SEP.\n\n- (* Lload *)\n  assert (exists a',\n          eval_addressing ge (Vptr sp' Ptrofs.zero) (transl_addr (make_env (function_bounds f)) addr) rs0##args = Some a'\n       /\\ Val.inject j a a').\n  eapply eval_addressing_inject; eauto.\n  eapply globalenv_inject_preserves_globals. eapply sep_proj2. eapply sep_proj2. eapply sep_proj2. eexact SEP.\n  eapply agree_reglist; eauto.\n  destruct H1 as [a' [A B]].\n  exploit loadv_parallel_rule.\n  apply sep_proj2 in SEP. apply sep_proj2 in SEP. apply sep_proj1 in SEP. eexact SEP.\n  eauto. eauto.\n  intros [v' [C D]].\n  econstructor; split.\n  apply plus_one. econstructor.\n  instantiate (1 := a'). rewrite <- A. apply eval_addressing_preserved. exact symbols_preserved.\n  eexact C. eauto.\n  econstructor; eauto with coqlib.\n  apply agree_regs_set_reg. rewrite transl_destroyed_by_load. apply agree_regs_undef_regs; auto. auto.\n  apply agree_locs_set_reg. apply agree_locs_undef_locs. auto. apply destroyed_by_load_caller_save. auto.\n\n- (* Lstore *)\n  assert (exists a',\n          eval_addressing ge (Vptr sp' Ptrofs.zero) (transl_addr (make_env (function_bounds f)) addr) rs0##args = Some a'\n       /\\ Val.inject j a a').\n  eapply eval_addressing_inject; eauto.\n  eapply globalenv_inject_preserves_globals. eapply sep_proj2. eapply sep_proj2. eapply sep_proj2. eexact SEP.\n  eapply agree_reglist; eauto.\n  destruct H1 as [a' [A B]].\n  rewrite sep_swap3 in SEP.\n  exploit storev_parallel_rule. eexact SEP. eauto. eauto. apply AGREGS.\n  clear SEP; intros (m1' & C & SEP).\n  rewrite sep_swap3 in SEP.\n  econstructor; split.\n  apply plus_one. econstructor.\n  instantiate (1 := a'). rewrite <- A. apply eval_addressing_preserved. exact symbols_preserved.\n  eexact C. eauto.\n  econstructor. eauto. eauto. eauto.\n  rewrite transl_destroyed_by_store. apply agree_regs_undef_regs; auto.\n  apply agree_locs_undef_locs. auto. apply destroyed_by_store_caller_save.\n  auto. eauto with coqlib.\n  eapply frame_undef_regs; eauto.\n\n- (* Lcall *)\n  exploit find_function_translated; eauto.\n    eapply sep_proj2. eapply sep_proj2. eapply sep_proj2. eexact SEP.\n  intros [bf [tf' [A [B C]]]].\n  exploit is_tail_transf_function; eauto. intros IST.\n  rewrite transl_code_eq in IST. simpl in IST.\n  exploit return_address_offset_exists. eexact IST. intros [ra D].\n  econstructor; split.\n  apply plus_one. econstructor; eauto.\n  econstructor; eauto.\n  econstructor; eauto with coqlib.\n  apply Val.Vptr_has_type.\n  intros; red.\n    apply Z.le_trans with (size_arguments (Linear.funsig f')); auto. \n    apply loc_arguments_bounded; auto.\n  simpl. rewrite sep_assoc. exact SEP.\n\n- (* Ltailcall *)\n  rewrite (sep_swap (stack_contents j s cs')) in SEP.\n  exploit function_epilogue_correct; eauto.\n  clear SEP. intros (rs1 & m1' & P & Q & R & S & T & U & SEP).\n  rewrite sep_swap in SEP.\n  exploit find_function_translated; eauto.\n    eapply sep_proj2. eapply sep_proj2. eexact SEP.\n  intros [bf [tf' [A [B C]]]].\n  econstructor; split.\n  eapply plus_right. eexact S. econstructor; eauto. traceEq.\n  econstructor; eauto.\n  apply match_stacks_change_sig with (Linear.fn_sig f); auto.\n  apply zero_size_arguments_tailcall_possible. eapply wt_state_tailcall; eauto.\n\n- (* Lbuiltin *)\n  destruct BOUND as [BND1 BND2].\n  exploit transl_builtin_args_correct.\n    eauto. eauto. rewrite sep_swap in SEP; apply sep_proj2 in SEP; eexact SEP.\n    eauto. rewrite <- forallb_forall. eapply wt_state_builtin; eauto.\n    exact BND2.\n  intros [vargs' [P Q]].\n  rewrite <- sep_assoc, sep_comm, sep_assoc in SEP.\n  exploit external_call_parallel_rule; eauto.\n  clear SEP; intros (j' & res' & m1' & EC & RES & SEP & INCR & ISEP).\n  rewrite <- sep_assoc, sep_comm, sep_assoc in SEP.\n  econstructor; split.\n  apply plus_one. econstructor; 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  eapply match_states_intro with (j := j'); eauto with coqlib.\n  eapply match_stacks_change_meminj; eauto.\n  apply agree_regs_set_res; auto. apply agree_regs_undef_regs; auto. eapply agree_regs_inject_incr; eauto.\n  apply agree_locs_set_res; auto. apply agree_locs_undef_regs; auto.\n  apply frame_set_res. apply frame_undef_regs. apply frame_contents_incr with j; auto.\n  rewrite sep_swap2. apply stack_contents_change_meminj with j; auto. rewrite sep_swap2.\n  exact SEP.\n\n- (* Llabel *)\n  econstructor; split.\n  apply plus_one; apply exec_Mlabel.\n  econstructor; eauto with coqlib.\n\n- (* Lgoto *)\n  econstructor; split.\n  apply plus_one; eapply exec_Mgoto; eauto.\n  apply transl_find_label; eauto.\n  econstructor; eauto.\n  eapply find_label_tail; eauto.\n\n- (* Lcond, true *)\n  econstructor; split.\n  apply plus_one. eapply exec_Mcond_true; eauto.\n  eapply eval_condition_inject with (m1 := m). eapply agree_reglist; eauto. apply sep_pick3 in SEP; exact SEP. auto.\n  eapply transl_find_label; eauto.\n  econstructor. eauto. eauto. eauto.\n  apply agree_regs_undef_regs; auto.\n  apply agree_locs_undef_locs. auto. apply destroyed_by_cond_caller_save.\n  auto.\n  eapply find_label_tail; eauto.\n  apply frame_undef_regs; auto.\n\n- (* Lcond, false *)\n  econstructor; split.\n  apply plus_one. eapply exec_Mcond_false; eauto.\n  eapply eval_condition_inject with (m1 := m). eapply agree_reglist; eauto. apply sep_pick3 in SEP; exact SEP. auto.\n  econstructor. eauto. eauto. eauto.\n  apply agree_regs_undef_regs; auto.\n  apply agree_locs_undef_locs. auto. apply destroyed_by_cond_caller_save.\n  auto. eauto with coqlib.\n  apply frame_undef_regs; auto.\n\n- (* Ljumptable *)\n  assert (rs0 arg = Vint n).\n  { generalize (AGREGS arg). rewrite H. intro IJ; inv IJ; auto. }\n  econstructor; split.\n  apply plus_one; eapply exec_Mjumptable; eauto.\n  apply transl_find_label; eauto.\n  econstructor. eauto. eauto. eauto.\n  apply agree_regs_undef_regs; auto.\n  apply agree_locs_undef_locs. auto. apply destroyed_by_jumptable_caller_save.\n  auto. eapply find_label_tail; eauto.\n  apply frame_undef_regs; auto.\n\n- (* Lreturn *)\n  rewrite (sep_swap (stack_contents j s cs')) in SEP.\n  exploit function_epilogue_correct; eauto.\n  intros (rs' & m1' & A & B & C & D & E & F & G).\n  econstructor; split.\n  eapply plus_right. eexact D. econstructor; eauto. traceEq.\n  econstructor; eauto.\n  rewrite sep_swap; exact G.\n\n- (* internal function *)\n  revert TRANSL. unfold transf_fundef, transf_partial_fundef.\n  destruct (transf_function f) as [tfn|] eqn:TRANSL; simpl; try congruence.\n  intros EQ; inversion EQ; clear EQ; subst tf.\n  rewrite sep_comm, sep_assoc in SEP.\n  exploit wt_callstate_agree; eauto. intros [AGCS AGARGS].\n  exploit function_prologue_correct; eauto.\n  red; intros; eapply wt_callstate_wt_regs; eauto.\n  eapply match_stacks_type_sp; eauto.\n  eapply match_stacks_type_retaddr; eauto.\n  clear SEP;\n  intros (j' & rs' & m2' & sp' & m3' & m4' & m5' & A & B & C & D & E & F & SEP & J & K).\n  rewrite (sep_comm (globalenv_inject ge j')) in SEP.\n  rewrite (sep_swap (minjection j' m')) in SEP.\n  econstructor; split.\n  eapply plus_left. econstructor; eauto.\n  rewrite (unfold_transf_function _ _ TRANSL). unfold fn_code. unfold transl_body.\n  eexact D. traceEq.\n  eapply match_states_intro with (j := j'); eauto with coqlib.\n  eapply match_stacks_change_meminj; eauto.\n  rewrite sep_swap in SEP. rewrite sep_swap. eapply stack_contents_change_meminj; eauto.\n\n- (* external function *)\n  simpl in TRANSL. inversion TRANSL; subst tf.\n  exploit wt_callstate_agree; eauto. intros [AGCS AGARGS].\n  exploit transl_external_arguments; eauto. apply sep_proj1 in SEP; eauto. intros [vl [ARGS VINJ]].\n  rewrite sep_comm, sep_assoc in SEP.\n  exploit external_call_parallel_rule; eauto.\n  intros (j' & res' & m1' & A & B & C & D & E).\n  econstructor; split.\n  apply plus_one. eapply exec_function_external; eauto.\n  eapply external_call_symbols_preserved; eauto. apply senv_preserved.\n  eapply match_states_return with (j := j').\n  eapply match_stacks_change_meminj; eauto.\n  apply agree_regs_set_pair. apply agree_regs_undef_caller_save_regs. \n  apply agree_regs_inject_incr with j; auto.\n  auto.\n  apply stack_contents_change_meminj with j; auto.\n  rewrite sep_comm, sep_assoc; auto.\n\n- (* return *)\n  inv STACKS. exploit wt_returnstate_agree; eauto. intros [AGCS OUTU].\n  simpl in AGCS. simpl in SEP. rewrite sep_assoc in SEP.\n  econstructor; split.\n  apply plus_one. apply exec_return.\n  econstructor; eauto.\n  apply agree_locs_return with rs0; auto.\n  apply frame_contents_exten with rs0 (parent_locset s); auto.\n  intros; apply Val.lessdef_same; apply AGCS; red; congruence.\n  intros; rewrite (OUTU ty ofs); auto. \nQed.\n\nLemma transf_initial_states:\n  forall st1, Linear.initial_state prog st1 ->\n  exists st2, Mach.initial_state tprog st2 /\\ match_states st1 st2.\nProof.\n  intros. inv H.\n  exploit function_ptr_translated; eauto. intros [tf [FIND TR]].\n  econstructor; split.\n  econstructor.\n  eapply (Genv.init_mem_transf_partial TRANSF); eauto.\n  rewrite (match_program_main TRANSF).\n  rewrite symbols_preserved. eauto.\n  set (j := Mem.flat_inj (Mem.nextblock m0)).\n  eapply match_states_call with (j := j); eauto.\n  constructor. red; intros. rewrite H3, loc_arguments_main in H. contradiction.\n  red; simpl; auto.\n  simpl. rewrite sep_pure. split; auto. split;[|split].\n  eapply Genv.initmem_inject; eauto.\n  simpl. exists (Mem.nextblock m0); split. apply Ple_refl.\n  unfold j, Mem.flat_inj; constructor; intros.\n    apply pred_dec_true; auto.\n    destruct (plt b1 (Mem.nextblock m0)); congruence.\n    change (Mem.valid_block m0 b0). eapply Genv.find_symbol_not_fresh; eauto.\n    change (Mem.valid_block m0 b0). eapply Genv.find_funct_ptr_not_fresh; eauto.\n    change (Mem.valid_block m0 b0). eapply Genv.find_var_info_not_fresh; eauto.\n  red; simpl; tauto.\nQed.\n\nLemma transf_final_states:\n  forall st1 st2 r,\n  match_states st1 st2 -> Linear.final_state st1 r -> Mach.final_state st2 r.\nProof.\n  intros. inv H0. inv H. inv STACKS.\n  assert (R: exists r, loc_result signature_main = One r).\n  { destruct (loc_result signature_main) as [r1 | r1 r2] eqn:LR.\n  - exists r1; auto.\n  - generalize (loc_result_type signature_main). rewrite LR. discriminate.\n  }\n  destruct R as [rres EQ]. rewrite EQ in H1. simpl in H1.\n  generalize (AGREGS rres). rewrite H1. intros A; inv A.\n  econstructor; eauto.\nQed.\n\nLemma wt_prog:\n  forall i fd, In (i, Gfun fd) prog.(prog_defs) -> wt_fundef fd.\nProof.\n  intros.\n  exploit list_forall2_in_left. eexact (proj1 TRANSF). eauto.\n  intros ([i' g] & P & Q & R). simpl in *. inv R. destruct fd; simpl in *.\n- monadInv H2. unfold transf_function in EQ.\n  destruct (wt_function f). auto. discriminate.\n- auto.\nQed.\n\nTheorem transf_program_correct:\n  forward_simulation (Linear.semantics prog) (Mach.semantics return_address_offset tprog).\nProof.\n  set (ms := fun s s' => wt_state s /\\ match_states s s').\n  eapply forward_simulation_plus with (match_states := ms).\n- apply senv_preserved.\n- intros. exploit transf_initial_states; eauto. intros [st2 [A B]].\n  exists st2; split; auto. split; auto.\n  apply wt_initial_state with (prog := prog); auto. exact wt_prog.\n- intros. destruct H. eapply transf_final_states; eauto.\n- intros. destruct H0.\n  exploit transf_step_correct; eauto. intros [s2' [A B]].\n  exists s2'; split. exact A. split.\n  eapply step_type_preservation; eauto. eexact wt_prog. eexact H.\n  auto.\nQed.\n\nEnd PRESERVATION.\n", "meta": {"author": "AbsInt", "repo": "CompCert", "sha": "f4ddce910894bf6dbdf83c0642c4b275854b60dd", "save_path": "github-repos/coq/AbsInt-CompCert", "path": "github-repos/coq/AbsInt-CompCert/CompCert-f4ddce910894bf6dbdf83c0642c4b275854b60dd/backend/Stackingproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.28390412341375226}}
{"text": "\n(** A long script to test (non-nested) induction and case analysis **)\n\nRequire Import MetaCoq.Template.All.\nRequire Import destruct_lemma.\nRequire Import MetaCoq.Template.Pretty.\nRequire Import List String.\nImport ListNotations MCMonadNotation.\n\n\n\n\n\n\n\n(* Load destruct_lemma. *)\n(* Require Import MetaCoq.Template.Pretty. *)\n\n\n(* mutual inductive test *)\n\n(* Inductive even : nat -> Prop := *)\n(*   | even_O : even 0 *)\n(*   | even_S : forall n, odd n -> even (S n) *)\n(* with odd : nat -> Prop := *)\n(*   odd_S : forall n, even n -> odd (S n). *)\n\n(* Print even_ind. *)\n(* Print odd_ind. *)\n\n(* Goal forall n, even n -> exists k, n=2*k. *)\n(* Proof. *)\n(*   induction 1. *)\n(*   - now exists 0. *)\n(*   - destruct H. *)\n(* Restart. *)\n(*   induction n. *)\n(*   - intros _. now exists 0. *)\n(*   - destruct 1. *)\n(*     + now exists 0. *)\n(*     + destruct H. *)\n(* Abort. *)\n\n(* Print even_ind. *)\n(* MetaCoq Run (create even true true). *)\n\nUnset Strict Unquote Universe Mode.\nMetaCoq Run (create nat true false).\nMetaCoq Run (create nat true true).\n\nRequire Import de_bruijn_print.\n(* MetaCoq TemplateCoq Pretty.v *)\n\n\nCheck fresh_name.\nPrint global_env_ext.\nPrint universes_decl.\nPrint ContextSet.t.\nSearch global_env_ext.\nPrint global_env.\nPrint tmPrint.\nPrint program.\n\nMetaCoq Run (tmPrint <% nat %>).\n(* MetaCoq Run (tmEval lazy (inductive_mind <% nat %>) >>= tmPrint). *)\nMetaCoq Run (tmQuoteInductive \"nat\" >>= tmPrint).\nMetaCoq Run (tmQuoteRec \"nat\" >>= tmPrint).\nMetaCoq Run (p <- tmQuoteRec nat;;\n               t <- tmEval lazy (p.2);;\n               tmPrint t).\n\nMetaCoq Run (tmPrint \"A\";;match true with true => tmPrint \"B\" | _ => tmPrint \"C\" end).\n\nMetaCoq Run (p <- tmQuoteRec le;;\n               t <- tmEval lazy (p.2);;\n               tmPrint t).\n(* MetaCoq Run (tmQuoteInductive <% nat %> >>= tmPrint). *)\n\nMetaCoq Run (p <- tmQuoteRec nat;;\n             n <- tmEval lazy (empty_ext( p.1));;\n             tmPrint n).\n\n(* Definition env := *)\n(* ([InductiveDecl (* \"Coq.Init.Datatypes.nat\" *) *)\n(*     {| *)\n(*     ind_finite := Finite; *)\n(*     ind_npars := 0; *)\n(*     ind_params := []; *)\n(*     ind_bodies := [{| *)\n(*                    ind_name := \"nat\"; *)\n(*                    ind_type := tSort (NEL.sing (Level.lSet, false)); *)\n(*                    ind_kelim := [InProp; InSet; InType]; *)\n(*                    ind_ctors := [(\"O\", tRel 0, 0); (\"S\", tProd nAnon (tRel 0) (tRel 1), 1)]; *)\n(*                    ind_projs := [] |}]; *)\n(*     ind_universes := Monomorphic_ctx *)\n(*                        ({| LevelSet.this := []; LevelSet.is_ok := LevelSet.Raw.empty_ok |}, *)\n(*                        {| ConstraintSet.this := []; ConstraintSet.is_ok := ConstraintSet.Raw.empty_ok |}) |}], *)\n(* Monomorphic_ctx *)\n(*   ({| LevelSet.this := []; LevelSet.is_ok := LevelSet.Raw.empty_ok |}, *)\n(*   {| ConstraintSet.this := []; ConstraintSet.is_ok := ConstraintSet.Raw.empty_ok |})) *)\n(* . *)\n\n(* Compute (fresh_name _ _ nAnon <% nat %>). *)\n(* MetaCoq Quote Definition q := (fun n => S n). *)\n(* MetaCoq Unquote Definition m := (tLambda nAnon <% nat %> <% nat %>). *)\n(* MetaCoq Unquote Definition m2 := (tLambda nAnon <% nat %> (tApp <% S %> [tRel 0] )). *)\n(* MetaCoq Unquote Definition m3 := (tLambda (nNamed \"n\") <% nat %> (tApp <% S %> [tRel 0] )). *)\n(* (* Check Σ. *) *)\n(* MetaCoq Unquote Definition m4 := (tLambda (fresh_name env [] nAnon <% nat %>) <% nat %> (tApp <% S %> [tRel 0] )). *)\n(* MetaCoq Unquote Definition m5 := (tLambda (fresh_name env [] (nNamed \"n\") <% nat %>) <% nat %> (tApp <% S %> [tRel 0] )). *)\n(* MetaCoq Unquote Definition m6 := (tLambda (fresh_name env [] nAnon <% bool %>) <% nat %> (tApp <% S %> [tRel 0] )). *)\n(* MetaCoq Unquote Definition m7 := (tLambda (fresh_name env [] (nNamed \"IH\") <% nat %>) <% nat %> (tLambda (fresh_name env [] (nNamed \"IH\") <% nat %>) <% nat %> (tApp <% add %> [tRel 0;tRel 1] ))). *)\n(* Definition m8 := (tLambda (fresh_name env [] (nNamed \"IH\") <% nat %>) <% nat %> (tLambda (fresh_name env [] (nNamed \"IH\") <% nat %>) <% nat %> (tApp <% add %> [tRel 0;tRel 1] ))). *)\n(* Print m. *)\n(* Print m2. *)\n(* Print m3. *)\n(* Print m4. *)\n(* Print m5. *)\n(* Print m6. *)\n(* Print m7. *)\n(* Print m8. *)\n(* MetaCoq Run (tmEval lazy m8 >>= tmPrint). *)\n\nPrint term.\n\n\n(* MetaCoq Quote Definition added := (fun (x:nat) => x+0). *)\n(* Print added. *)\n\n(* tLambda (nNamed \"x\") *)\n(* (tInd {| *)\n(*         inductive_mind := \"nat\"; *)\n(*         inductive_ind := 0 *)\n(*         |} *)\n(*     []) *)\n(* (tApp (tConst \"add\" []) *)\n(*      [tRel 0; *)\n(*      tConstruct {| *)\n(*         inductive_mind := \"nat\"; *)\n(*         inductive_ind := 0 *)\n(*         |} *)\n(*         0 *)\n(*         [] *)\n(*     ]) *)\n(* tLambda (nNamed \"x\") (tInd {| inductive_mind := \"Coq.Init.Datatypes.nat\"; inductive_ind := 0 |} []) *)\n(*   (tApp (tConst \"Coq.Init.Nat.add\" []) *)\n(*      [tRel 0; tConstruct {| inductive_mind := \"Coq.Init.Datatypes.nat\"; inductive_ind := 0 |} 0 []]) *)\n\n(** non Uniform test **)\n\nInductive G3 (f:nat->bool) (n:nat) : Prop :=\n  G3I : (f n = false -> G3 f (S n)) -> G3 f n.\n\nScheme Induction for G3 Sort Type.\nPrint G3_rect_dep.\n\n\n\nMetaCoq Quote Definition I_G3 :=\n  (\nfun (f : nat -> bool) (P : forall n : nat, G3 f n -> Type)\n  (f0 : forall (n : nat) (g : f n = false -> G3 f (S n)),\n        (forall e : f n = false, P (S n) (g e)) -> P n (G3I f n g)) =>\nfix F (n : nat) (g : G3 f n) {struct g} : P n g :=\n  match g as g0 return (P n g0) with\n  | @G3I _ _ g0 => f0 n g0 (fun e : f n = false => F (S n) (g0 e))\n  end\n  ).\nFrom MetaCoq.PCUIC Require Import TemplateToPCUIC.\nMetaCoq Run (bruijn_print (trans I_G3)).\n\n(*\nλ (f : (nat) -> bool).\nλ (P : ∀ (n : nat), ((G3 (R1) (R0))) -> LTop.2132).\nλ (f0 : ∀ (n : nat), ∀ (g : ((eq (bool) ((R2 (R0))) (false))) -> (G3 (R3) ((S (R1))))), (∀ (e : (eq (bool) ((R3 (R1))) (false))), (R3 ((S (R2))) ((R1 (R0))))) -> (R3 (R2) ((G3I (R4) (R2) (R1))))).\n(fix F : ∀ (n : nat), ∀ (g : (G3 (R3) (R0))), (R3 (R1) (R0)) :=\nλ (n : nat). λ (g : (G3 (R4) (R0))).\nmatch (P:2) R0 return λ (g0 : (G3 (R5) (R1))). (R5 (R2) (R0)) with\n | (1) λ (g0 : ((eq (bool) ((R5 (R1))) (false))) -> (G3 (R6) ((S (R2))))). (R4 (R2) (R0) (λ (e : (eq (bool) ((R6 (R2))) (false))). (R4 ((S (R3))) ((R1 (R0))))))\nend)\nλ (f : (nat) -> bool).\nλ (P : ∀ (n : nat), ((G3 (R1) (R0))) -> LTop.2446).\nλ (f0 : ∀ (n : nat), ∀ (g : ((eq (bool) ((R2 (R0))) (false))) -> (G3 (R3) ((S (R1))))), (∀ (e : (eq (bool) ((R3 (R1))) (false))), (R3 ((S (R2))) ((R1 (R0))))) -> (R3 (R2) ((G3I (R4) (R2) (R1))))).\n(fix F : ∀ (n : nat), ∀ (g : (G3 (R3) (R0))), (R3 (R1) (R0)) :=\nλ (n : nat). λ (g : (G3 (R4) (R0))).\nmatch (P:2) R0 return λ (g0 : (G3 (R5) (R1))). (R5 (R2) (R0)) with\n | (1) λ (g0 : ((eq (bool) ((R5 (R1))) (false))) -> (G3 (R6) ((S (R2))))). (R4 (R2) (R0) (λ (e : (eq (bool) ((R6 (R2))) (false))). (R4 ((S (R3))) ((R1 (R0))))))\nend)\n*)\n\nPrint G3.\nMetaCoq Run (create G3 true false).\n(*\nλ (f : (nat) -> bool).\nλ (p : ∀ (n : nat), ∀ (inst : (G3 (R1) (R0))), LTop.1887).\nλ (H_G3I : ∀ (n : nat), (((eq (bool) ((R2 (R0))) (false))) -> (G3 (R3) ((S (R1))))) -> ∀ (IH : ((eq (bool) ((R3 (R1))) (false))) -> (R3 ((S (R2))) ((R1 (R0))))), (R3 (R2) ((G3I (R4) (R2) (R1))))).\n(fix f : ∀ (n : nat), ∀ (inst : (G3 (R3) (R0))), (R3 (R1) (R0)) :=\nλ (n : nat). λ (inst : (G3 (R4) (R0))).\nmatch (P:2) R0 return λ (inst : (G3 (R5) (R1))). (R6 (R2) (R0)) with\n | (1) λ (_ : ((eq (bool) ((R5 (R1))) (false))) -> (G3 (R6) ((S (R2))))). (R4 (R2) (R0) (λ (_ : (eq (bool) ((R6 (R2))) (false))). (R4 ((S (R3))) ((R1 (R0))))))\nend)\n*)\n(*\n | (1) λ (_ : ((eq (bool) ((R5 (R1))) (false))) -> (G3 (R6) ((S (R2))))). (R4 (R2) (R0) (λ (_ : (eq (bool) ((R6 (R2))) (false))). (R4 ((S (R3))) ((R1 (R0))))))\n | (1) λ (_ : ((eq (bool) ((R5 (R1))) (false))) -> (G3 (R6) ((S (R2))))). (R4 (R2) (R0) (λ (_ : (eq (bool) ((R7 (R2))) (false))). (R4 ((S (R3))) ((R1 (R0))))))\n | (1) λ (_ : ((eq (bool) ((R5 (R1))) (false))) -> (G3 (R6) ((S (R2))))). (R4 (R2) (R0) (λ (_ : (eq (bool) ((R2 (R0))) (false))). (R4 ((S (R1))) ((R1 (R0))))))\n*)\n(*\nλ (f : (nat) -> bool).\nλ (p : ∀ (n : nat), ∀ (inst : (G3 (R1) (R0))), LTop.230).\nλ (H_G3I : ∀ (n : nat), (((eq (bool) ((R2 (R0))) (false))) -> (G3 (R3) ((S (R1))))) -> ∀ (IH : ((eq (bool) ((R3 (R1))) (false))) -> (R3 ((S (R2))) ((R1 (R0))))), (R3 (R2) ((G3I (R4) (R2) (R1))))).\n(fix f : ∀ (n : nat), ∀ (inst : (G3 (R3) (R0))), (R3 (R1) (R0)) :=\nλ (n : nat). λ (inst : (G3 (R4) (R0))).\nmatch (P:2) R0 return λ (inst : (G3 (R5) (R1))). (R5 (R2) (R0)) with\n                                                                                                              !   !\n | (1) λ (_ : ((eq (bool) ((R5 (R1))) (false))) -> (G3 (R6) ((S (R2))))). (R4 (R2) (R0) (λ (_ : (eq (bool) ((R5 (R0))) (false))). (R3 ((S (R1))) ((R1 (R0))))))\n                 !       !\nend)\n *)\n\n(* have *)\n(*   λ (f : (nat) -> bool). *)\n(* λ (p : ∀ (n : nat), ∀ (inst : ((G3 R1) R0)), Ldestruct_lemma.447). *)\n(* λ (H_G3I : ∀ (n : nat), (((((eq bool) (R2 R0)) false)) -> ((G3 R3) (S R1))) -> (((((eq bool) (R3 R1)) false)) -> ((R3 R4) (R1 R0))) -> ((R3 R4) (((G3I R4) R2) R1))). *)\n(*                                                                                                             **                   ** *)\n(* (fix f : ∀ (n : nat), ∀ (inst : ((G3 R3) R0)), ((R3 R1) R0) := *)\n(* λ (n : nat). λ (inst : ((G3 R4) R0)). *)\n(* match (P:2) R0 return λ (inst : ((G3 R5) R1)). ((R5 R2) R0) with *)\n(*  | (1) λ (_ : ((((eq bool) (R5 R1)) false)) -> ((G3 R6) (S R2))). (((R4 R2) R0) λ (_ : (((eq bool) (R6 R2)) false)). ((R4 R7) (R1 R0))) *)\n(* end) *)\n\n(*   have 2 *)\n(*   λ (f : (nat) -> bool). *)\n(* λ (p : ∀ (n : nat), ∀ (inst : ((G3 R1) R0)), Ldestruct_lemma.447). *)\n(* λ (H_G3I : ∀ (n : nat), (((((eq bool) (R2 R0)) false)) -> ((G3 R3) (S R1))) -> (((((eq bool) (R3 R1)) false)) -> ((R3 (S R2)) (R1 R0))) -> ((R3 R2) (((G3I R4) R2) R1))). *)\n(* (fix f : ∀ (n : nat), ∀ (inst : ((G3 R3) R0)), ((R3 R1) R0) := *)\n(* λ (n : nat). λ (inst : ((G3 R4) R0)). *)\n(* match (P:2) R0 return λ (inst : ((G3 R5) R1)). ((R5 R2) R0) with *)\n(*  | (1) λ (_ : ((((eq bool) (R5 R1)) false)) -> ((G3 R6) (S R2))). (((R4 R2) R0) λ (_ : (((eq bool) (R6 R2)) false)). ((R4 (S R3)) (R1 R0))) *)\n(* end) *)\n\n(* want *)\n(* λ (f : (nat) -> bool). *)\n(* λ (P : ∀ (n : nat), (((G3 R1) R0)) -> LTop.409). *)\n(* λ (f0 : ∀ (n : nat), ∀ (g : ((((eq bool) (R2 R0)) false)) -> ((G3 R3) (S R1))), (∀ (e : (((eq bool) (R3 R1)) false)), ((R3 (S R2)) (R1 R0))) -> ((R3 R2) (((G3I R4) R2) R1))). *)\n(* (fix F : ∀ (n : nat), ∀ (g : ((G3 R3) R0)), ((R3 R1) R0) := *)\n(* λ (n : nat). λ (g : ((G3 R4) R0)). *)\n(* match (P:2) R0 return λ (g0 : ((G3 R5) R1)). ((R5 R2) R0) with *)\n(*  | (1) λ (g0 : ((((eq bool) (R5 R1)) false)) -> ((G3 R6) (S R2))). (((R4 R2) R0) λ (e : (((eq bool) (R6 R2)) false)). ((R4 (S R3)) (R1 R0))) *)\n(* end) *)\n\n\nMetaCoq Run (create G3 true true).\n\n\nMetaCoq Quote Definition E_G3 := (fun (f : nat -> bool) (p : forall n : nat, G3 f n -> Type)\n  (HG3I : forall (n : nat) (h : f n = false -> G3 f (S n)),\n        p n (G3I f n h)) =>\nfix F (n : nat) (g : G3 f n) {struct g} : p n g :=\n  match g as g0 return (p n g0) with\n  | @G3I _ _ h => HG3I n h\n  end).\n\n(* MetaCoq Run (bruijn_print E_G3). *)\n(*\nλ (f : (nat) -> bool).\nλ (p : ∀ (n : nat), ((G3 (R1) (R0))) -> LTop.481).\nλ (HG3I : ∀ (n : nat), ∀ (h : ((eq (bool) ((R2 (R0))) (false))) -> (G3 (R3) ((S (R1))))), (R2 (R1) ((G3I (R3) (R1) (R0))))).\n(fix F : ∀ (n : nat), ∀ (g : (G3 (R3) (R0))), (R3 (R1) (R0)) :=\nλ (n : nat). λ (g : (G3 (R4) (R0))).\nmatch (P:2) R0 return λ (g0 : (G3 (R5) (R1))). (R5 (R2) (R0)) with\n | (1) λ (h : ((eq (bool) ((R5 (R1))) (false))) -> (G3 (R6) ((S (R2))))). (R4 (R2) (R0))\nend)\n *)\n\nMetaCoq Run (create G3 false false).\nMetaCoq Run (create G3 false true).\nPrint G3_case_MC.\nPrint G3_case_MC.\n(*\n | (1) λ (_ : ((eq (bool) ((R5 (R1))) (false))) -> (G3 (R6) ((S (R2))))). (R4 (R2) (R0))\n | (1) λ (_ : ((eq (bool) ((R6 (R1))) (false))) -> (G3 (R7) ((S (R2))))). (R4 (R2) (R0))\n | (1) λ (_ : ((eq (bool) ((R4 (R0))) (false))) -> (G3 (R5) ((S (R1))))). (R4 (R2) (R0))\n | (1) λ (_ : ((eq (bool) ((R1 (R0))) (false))) -> (G3 (R2) ((S (R1))))). (R4 (R2) (R0))\n | (1) λ (_ : ((eq (bool) ((R5 (R4))) (false))) -> (G3 (R6) ((S (R5))))). (R4 (R2) (R0))\n | (1) λ (_ : ((eq (bool) ((R5 (R4))) (false))) -> (G3 (R6) ((S (R5))))). (R4 (R2) (R0))\n | (1) λ (_ : ((eq (bool) ((R5 (R4))) (false))) -> (G3 (R6) ((S (R5))))). (R3 (R2) (R0))\n | (1) λ (_ : ((eq (bool) ((R5 (R4))) (false))) -> (G3 (R6) ((S (R5))))). (R3 (R1) (R0))\n *)\n(*\nλ (f : (nat) -> bool).\nλ (p : ∀ (n : nat), ∀ (inst : (G3 (R1) (R0))), LTop.230).\nλ (H_G3I : ∀ (n : nat), (((eq (bool) ((R2 (R0))) (false))) -> (G3 (R3) ((S (R1))))) -> (R2 (R1) ((G3I (R3) (R1) (R0))))).\n(fix f : ∀ (n : nat), ∀ (inst : (G3 (R3) (R0))), (R3 (R1) (R0)) :=\nλ (n : nat). λ (inst : (G3 (R4) (R0))).\nmatch (P:2) R0 return λ (inst : (G3 (R5) (R1))). (R5 (R2) (R0)) with\n | (1) λ (_ : ((eq (bool) ((R5 (R4))) (false))) -> (G3 (R6) ((S (R5))))). (R3 (R0))\n                                 !                                !         !!\nend)\n*)\n(*\nλ (f : (nat) -> bool). λ (p : ∀ (n : nat), ∀ (inst : (G3 (R1) (R0))), LTop.905). λ (H_G3I : ∀ (n : nat), (((eq (bool) ((R2 (R0))) (false))) -> (G3 (R3) ((S (R1))))) -> (R2 (R1) ((G3I (R3) (R1) (R0))))).\n(fix f : ∀ (n : nat), ∀ (inst : (G3 (R3) (R0))), (R3 (R1) (R0)) :=\nλ (n : nat). λ (inst : (G3 (R4) (R0))).\nmatch (P:2) R0 return λ (inst : (G3 (R5) (R0))). (R1 (R1) (R0)) with\n | R42\nend)\n*)\n(*\nλ (f : (nat) -> bool).\nλ (p : ∀ (n : nat), ∀ (inst : (G3 (R1) (R0))), LTop.230).\nλ (H_G3I : ∀ (n : nat), (((eq (bool) ((R2 (R0))) (false))) -> (G3 (R3) ((S (R1))))) -> (R2 (R1) ((G3I (R3) (R1) (R0))))).\n(fix f : ∀ (n : nat), ∀ (inst : (G3 (R3) (R0))), (R3 (R1) (R0)) :=\nλ (n : nat). λ (inst : (G3 (R4) (R0))).\nR42\n)\n*)\n\n\nInductive G4 (f:nat->bool) (n:nat) : nat -> Prop :=\n  G4I : (f n = false -> G4 f (S n) 1) -> G4 f n 0.\nMetaCoq Quote Definition E_G4 := (fun (f : nat -> bool) (p : forall (n m : nat), G4 f n m -> Type)\n  (HG4I : forall (n : nat) (h : f n = false -> G4 f (S n) 1),\n        p n 0 (G4I f n h)) =>\nfix F (n : nat) (m:nat) (g : G4 f n m) {struct g} : p n m g :=\n  match g in G4 _ _ m0 return (p n m0 g) with\n  | @G4I _ _ h => HG4I n h\n  end).\n(* MetaCoq Run (bruijn_print E_G4). *)\n(*\nλ (f : (nat) -> bool).\nλ (p : ∀ (n : nat), ∀ (m : nat), ((G4 (R2) (R1) (R0))) -> LTop.2226).\nλ (HG4I : ∀ (n : nat), ∀ (h : ((eq (bool) ((R2 (R0))) (false))) -> (G4 (R3) ((S (R1))) ((S (O))))), (R2 (R1) (O) ((G4I (R3) (R1) (R0))))).\n(fix F : ∀ (n : nat), ∀ (m : nat), ∀ (g : (G4 (R4) (R1) (R0))), (R4 (R2) (R1) (R0)) :=\nλ (n : nat). λ (m : nat). λ (g : (G4 (R5) (R1) (R0))).\nmatch (P:2) R0 return λ (m0 : nat). λ (g : (G4 (R7) (R3) (R0))). (R7 (R4) (R1) (R0)) with\n | (1) λ (h : ((eq (bool) ((R6 (R2))) (false))) -> (G4 (R7) ((S (R3))) ((S (O))))). (R5 (R3) (R0))\nend)\n*)\nMetaCoq Run (create G4 false false).\n(*\nλ (f : (nat) -> bool).\nλ (p : ∀ (n : nat), (nat) -> ∀ (inst : (G4 (R2) (R1) (R0))), LTop.230).\nλ (H_G4I : ∀ (n : nat), (((eq (bool) ((R2 (R0))) (false))) -> (G4 (R3) ((S (R1))) ((S (O))))) -> (R2 (R1) (O) ((G4I (R3) (R1) (R0))))).\n(fix f : ∀ (n : nat), (nat) -> ∀ (inst : (G4 (R4) (R1) (R0))), (R4 (R2) (R1) (R0)) :=\nλ (n : nat). λ (_ : nat). λ (inst : (G4 (R5) (R1) (R0))).\nmatch (P:2) R0 return λ (_ : nat). λ (inst : (G4 (R7) (R3) (R0))). (R6 (R4) (R1) (R0)) with\n                                                                     !\n | (1) λ (_ : ((eq (bool) ((R6 (R2))) (false))) -> (G4 (R7) ((S (R3))) ((S (O))))). (R5 (R3) (R0))\nend)\n *)\nMetaCoq Run (create G4 false true).\n\nScheme Induction for G4 Sort Type.\nPrint G4_rect_dep.\nMetaCoq Quote Definition I_G4 := (\nfun (f : nat -> bool) (P : forall n n0 : nat, G4 f n n0 -> Type)\n  (f0 : forall (n : nat) (g : f n = false -> G4 f (S n) 1),\n        (forall e : f n = false, P (S n) 1 (g e)) -> P n 0 (G4I f n g)) =>\nfix F (n n0 : nat) (g : G4 f n n0) {struct g} : P n n0 g :=\n  match g as g0 in (G4 _ _ n1) return (P n n1 g0) with\n  | @G4I _ _ g0 => f0 n g0 (fun e : f n = false => F (S n) 1 (g0 e))\n  end\n                        ).\n(* MetaCoq Run (bruijn_print I_G4). *)\n(*\nλ (f : (nat) -> bool).\nλ (P : ∀ (n : nat), ∀ (n0 : nat), ((G4 (R2) (R1) (R0))) -> LTop.1150).\nλ (f0 : ∀ (n : nat), ∀ (g : ((eq (bool) ((R2 (R0))) (false))) -> (G4 (R3) ((S (R1))) ((S (O))))), (∀ (e : (eq (bool) ((R3 (R1))) (false))), (R3 ((S (R2))) ((S (O))) ((R1 (R0))))) -> (R3 (R2) (O) ((G4I (R4) (R2) (R1))))).\n(fix F : ∀ (n : nat), ∀ (n0 : nat), ∀ (g : (G4 (R4) (R1) (R0))), (R4 (R2) (R1) (R0)) :=\nλ (n : nat). λ (n0 : nat). λ (g : (G4 (R5) (R1) (R0))).\nmatch (P:2) R0 return λ (n1 : nat). λ (g0 : (G4 (R7) (R3) (R0))). (R7 (R4) (R1) (R0)) with\n | (1) λ (g0 : ((eq (bool) ((R6 (R2))) (false))) -> (G4 (R7) ((S (R3))) ((S (O))))). (R5 (R3) (R0) (λ (e : (eq (bool) ((R7 (R3))) (false))). (R5 ((S (R4))) ((S (O))) ((R1 (R0))))))\nend)\n*)\n\nMetaCoq Run (create G4 true false).\n(*\nλ (f : (nat) -> bool).\nλ (p : ∀ (n : nat), (nat) -> ∀ (inst : (G4 (R2) (R1) (R0))), LTop.709).\nλ (H_G4I : ∀ (n : nat), (((eq (bool) ((R2 (R0))) (false))) -> (G4 (R3) ((S (R1))) ((S (O))))) -> ∀ (IH : ((eq (bool) ((R3 (R1))) (false))) -> (R3 ((S (R2))) ((S (O))) ((R1 (R0))))), (R3 (R2) (O) ((G4I (R4) (R2) (R1))))).\n(fix f : ∀ (n : nat), (nat) -> ∀ (inst : (G4 (R4) (R1) (R0))), (R4 (R2) (R1) (R0)) :=\nλ (n : nat). λ (_ : nat). λ (inst : (G4 (R5) (R1) (R0))).\nmatch (P:2) R0 return λ (_ : nat). λ (inst : (G4 (R7) (R3) (R0))). (R7 (R4) (R1) (R0)) with\n | (1) λ (_ : ((eq (bool) ((R6 (R2))) (false))) -> (G4 (R7) ((S (R3))) ((S (O))))). (R5 (R3) (R0) (λ (_ : (eq (bool) ((R8 (R3))) (false))). (R5 ((S (R4))) ((S (O))) ((R1 (R0))))))\n        !                         !\nend)\n*)\nMetaCoq Run (create G4 true true).\n\n\n\nInductive G5 (f:nat->bool) (n:nat) (n2:nat) : nat -> Prop :=\n  G5I : (f n = false -> G5 f (S n) (2+n2) 1) -> G5 f n n2 0.\nMetaCoq Run (create G5 false true).\nPrint G5_case_MC.\nScheme Induction for G5 Sort Type.\nPrint G5_rect_dep.\nMetaCoq Quote Definition I_G5 := (\nfun (f : nat -> bool) (P : forall n n2 n0 : nat, G5 f n n2 n0 -> Type)\n  (f0 : forall (n n2 : nat) (g : f n = false -> G5 f (S n) (2 + n2) 1),\n        (forall e : f n = false, P (S n) (2 + n2) 1 (g e)) -> P n n2 0 (G5I f n n2 g)) =>\nfix F (n n2 n0 : nat) (g : G5 f n n2 n0) {struct g} : P n n2 n0 g :=\n  match g as g0 in (G5 _ _ _ n1) return (P n n2 n1 g0) with\n  | @G5I _ _ _ g0 => f0 n n2 g0 (fun e : f n = false => F (S n) (2 + n2) 1 (g0 e))\n  end\n                        ).\n(* MetaCoq Run (bruijn_print I_G5). *)\n(*\nλ (f : (nat) -> bool).\nλ (P : ∀ (n : nat), ∀ (n2 : nat), ∀ (n0 : nat), ((G5 (R3) (R2) (R1) (R0))) -> LTop.6844).\nλ (f0 : ∀ (n : nat), ∀ (n2 : nat), ∀ (g : ((eq (bool) ((R3 (R1))) (false))) -> (G5 (R4) ((S (R2))) ((Coq.Init.Nat.add ((S ((S (O))))) (R1))) ((S (O))))), (∀ (e : (eq (bool) ((R4 (R2))) (false))), (R4 ((S (R3))) ((Coq.Init.Nat.add ((S ((S (O))))) (R2))) ((S (O))) ((R1 (R0))))) -> (R4 (R3) (R2) (O) ((G5I (R5) (R3) (R2) (R1))))).\n(fix F : ∀ (n : nat), ∀ (n2 : nat), ∀ (n0 : nat), ∀ (g : (G5 (R5) (R2) (R1) (R0))), (R5 (R3) (R2) (R1) (R0)) :=\nλ (n : nat). λ (n2 : nat). λ (n0 : nat). λ (g : (G5 (R6) (R2) (R1) (R0))).\nmatch (P:3) R0 return λ (n1 : nat). λ (g0 : (G5 (R8) (R4) (R3) (R0))). (R8 (R5) (R4) (R1) (R0)) with\n | (1) λ (g0 : ((eq (bool) ((R7 (R3))) (false))) -> (G5 (R8) ((S (R4))) ((Coq.Init.Nat.add ((S ((S (O))))) (R3))) ((S (O))))). (R6 (R4) (R3) (R0) (λ (e : (eq (bool) ((R8 (R4))) (false))). (R6 ((S (R5))) ((Coq.Init.Nat.add ((S ((S (O))))) (R4))) ((S (O))) ((R1 (R0))))))\nend)\n*)\nMetaCoq Run (create G5 true false).\n(*\nλ (f : (nat) -> bool).\nλ (p : ∀ (n : nat), ∀ (n2 : nat), (nat) -> ∀ (inst : (G5 (R3) (R2) (R1) (R0))), LTop.6376).\nλ (H_G5I : ∀ (n : nat), ∀ (n2 : nat), (((eq (bool) ((R3 (R1))) (false))) -> (G5 (R4) ((S (R2))) ((Coq.Init.Nat.add ((S ((S (O))))) (R1))) ((S (O))))) -> ∀ (IH : ((eq (bool) ((R4 (R2))) (false))) -> (R4 ((S (R3))) ((Coq.Init.Nat.add ((S ((S (O))))) (R2))) ((S (O))) ((R1 (R0))))), (R4 (R3) (R2) (O) ((G5I (R5) (R3) (R2) (R1))))).\n(fix f : ∀ (n : nat), ∀ (n2 : nat), (nat) -> ∀ (inst : (G5 (R5) (R2) (R1) (R0))), (R5 (R3) (R2) (R1) (R0)) := \nλ (n : nat). λ (n2 : nat). λ (_ : nat). λ (inst : (G5 (R6) (R2) (R1) (R0))). \nmatch (P:3) R0 return λ (_ : nat). λ (inst : (G5 (R8) (R4) (R3) (R0))). (R8 (R5) (R4) (R1) (R0)) with\n | (1) λ (_ : ((eq (bool) ((R7 (R3))) (false))) -> (G5 (R8) ((S (R4))) ((Coq.Init.Nat.add ((S ((S (O))))) (R3))) ((S (O))))). (R6 (R4) (R3) (R0) (λ (_ : (eq (bool) ((R9 (R4))) (false))). (R6 ((S (R5))) ((Coq.Init.Nat.add ((S ((S (O))))) (R4))) ((S (O))) ((R1 (R0))))))\n                                                   !\nend)\n*)\n(* MetaCoq Run (create G5 true true). *)\n\n\n\n\n\n\n\nInductive indexIndTest : nat -> Type :=\n  | Ct0 : indexIndTest 0 -> indexIndTest 1.\n(* MetaCoq Run (create indexIndTest true). *)\n(* Print indexIndTest_case_MC. *)\n(* Print indexIndTest_ind. *)\n\nMetaCoq Quote Definition EindexIndTest :=\n  (fun (p:forall n, indexIndTest n -> Type)\n    HCt0 =>\n    (* (HCt0: forall (H:indexIndTest 0), p 0 H -> p 1 (Ct0 H)) => *)\n    fix f (n:nat) (x:indexIndTest n) :=\n    match x in indexIndTest m return p m x with\n      Ct0 H => HCt0 H (f 0 H)\n    end).\n\n(* MetaCoq Run (bruijn_print EindexIndTest). *)\n(*\nλ (p : ∀ (n : nat), ((indexIndTest (R0))) -> LTop.415).\nλ (HCt0 : ∀ (x : (indexIndTest (O))), ∀ (x0 : (R1 (O) (R0))), (R2 ((S (O))) ((Ct0 (R1))))).\n(fix f : ∀ (n : nat), ∀ (x : (indexIndTest (R0))), (R3 (R1) (R0)) :=\nλ (n : nat). λ (x : (indexIndTest (R0))).\nmatch R0 return λ (m : nat). λ (x : (indexIndTest (R0))). (R6 (R1) (R0)) with\n | λ (H : (indexIndTest (O))). (R4 (R0) ((R3 (O) (R0))))\nend)\n *)\nMetaCoq Run (create indexIndTest true true).\nPrint indexIndTest_ind_MC.\nPrint indexIndTest_ind_MC.\n\n(*\nλ (p : (nat) -> ∀ (inst : (indexIndTest (R0))), LTop.2303).\nλ (H_Ct0 : ((indexIndTest (O))) -> ∀ (IH : (R1 (O) (R0))), (R2 ((S (O))) ((Ct0 (R1))))).\n(fix f : (nat) -> ∀ (inst : (indexIndTest (R0))), (R3 (R1) (R0)) :=\nλ (_ : nat). λ (inst : (indexIndTest (R0))).\nmatch R0 return λ (_ : nat). λ (inst : (indexIndTest (R0))). (R6 (R1) (R0)) with\n | λ (_ : (indexIndTest (O))). (R4 (R0) ((R3 (O) (R0))))\nend) *)\n\n(** Tests **)\n(** Complex with Universes **)\n\nMetaCoq Run (create term false true).\nPrint term_case_MC.\nPrint TemplateMonad.\nMetaCoq Run(tmPrint <% nat %>).\nMetaCoq Run(tmQuote nat >>= tmPrint).\nMetaCoq Run(tmQuoteRec nat >>= tmPrint).\nMetaCoq Run(tmQuoteInductive \"nat\" >>= tmPrint).\nMetaCoq Run(tmQuoteRec TemplateMonad >>= tmPrint).\nMetaCoq Run(tmQuoteInductive \"TemplateMonad\" >>= tmPrint).\n(* MetaCoq Run (create TemplateMonad true). *)\n\n\nPrint term_ind.\n(* MetaCoq Quote Definition E_term := *)\n(* (fun (P : term -> Prop) (f : forall n : nat, P (tRel n)) (f0 : forall id : ident, P (tVar id)) *)\n(*   (f1 : forall (ev : nat) (args : list term), P (tEvar ev args)) (f2 : forall s : universe, P (tSort s)) *)\n(*   (f3 : forall t : term, P t -> forall (kind : cast_kind) (v : term), P v -> P (tCast t kind v)) *)\n(*   (f4 : forall (na : name) (ty : term), P ty -> forall body : term, P body -> P (tProd na ty body)) *)\n(*   (f5 : forall (na : name) (ty : term), P ty -> forall body : term, P body -> P (tLambda na ty body)) *)\n(*   (f6 : forall (na : name) (def : term), *)\n(*         P def -> forall def_ty : term, P def_ty -> forall body : term, P body -> P (tLetIn na def def_ty body)) *)\n(*   (f7 : forall f7 : term, P f7 -> forall args : list term, P (tApp f7 args)) *)\n(*   (f8 : forall (c : kername) (u : universe_instance), P (tConst c u)) *)\n(*   (f9 : forall (ind : inductive) (u : universe_instance), P (tInd ind u)) *)\n(*   (f10 : forall (ind : inductive) (idx : nat) (u : universe_instance), P (tConstruct ind idx u)) *)\n(*   (f11 : forall (ind_and_nbparams : inductive × nat) (type_info : term), *)\n(*          P type_info -> *)\n(*          forall discr : term, *)\n(*          P discr -> forall branches : list (nat × term), P (tCase ind_and_nbparams type_info discr branches)) *)\n(*   (f12 : forall (proj : projection) (t : term), P t -> P (tProj proj t)) *)\n(*   (f13 : forall (mfix : mfixpoint term) (idx : nat), P (tFix mfix idx)) *)\n(*   (f14 : forall (mfix : mfixpoint term) (idx : nat), P (tCoFix mfix idx)) => *)\n(* fix F (t : term) : P t := *)\n(*   match t as t0 return (P t0) with *)\n(*   | tRel n => f n *)\n(*   | tVar id => f0 id *)\n(*   | tEvar ev args => f1 ev args *)\n(*   | tSort s => f2 s *)\n(*   | tCast t0 kind v => f3 t0 (F t0) kind v (F v) *)\n(*   | tProd na ty body => f4 na ty (F ty) body (F body) *)\n(*   | tLambda na ty body => f5 na ty (F ty) body (F body) *)\n(*   | tLetIn na def def_ty body => f6 na def (F def) def_ty (F def_ty) body (F body) *)\n(*   | tApp f15 args => f7 f15 (F f15) args *)\n(*   | tConst c u => f8 c u *)\n(*   | tInd ind u => f9 ind u *)\n(*   | tConstruct ind idx u => f10 ind idx u *)\n(*   | tCase ind_and_nbparams type_info discr branches => *)\n(*       f11 ind_and_nbparams type_info (F type_info) discr (F discr) branches *)\n(*   | tProj proj t0 => f12 proj t0 (F t0) *)\n(*   | tFix mfix idx => f13 mfix idx *)\n(*   | tCoFix mfix idx => f14 mfix idx *)\n(*   end *)\n(* ). *)\n(* MetaCoq Run (bruijn_print E_term). *)\n(*\nλ (P : (term) -> Prop).\nλ (f : ∀ (n : nat), (R1 ((tRel (R0))))).\nλ (f0 : ∀ (id : MetaCoq.Template.BasicAst.ident), (R2 ((tVar (R0))))).\nλ (f1 : ∀ (ev : nat), ∀ (args : (list (term))), (R4 ((tEvar (R1) (R0))))).\nλ (f2 : ∀ (s : MetaCoq.Template.Universes.universe), (R4 ((tSort (R0))))).\nλ (f3 : ∀ (t : term), ((R5 (R0))) -> ∀ (kind : cast_kind), ∀ (v : term), ((R8 (R0))) -> (R9 ((tCast (R4) (R2) (R1))))).\nλ (f4 : ∀ (na : name), ∀ (ty : term), ((R7 (R0))) -> ∀ (body : term), ((R9 (R0))) -> (R10 ((tProd (R4) (R3) (R1))))).\nλ (f5 : ∀ (na : name), ∀ (ty : term), ((R8 (R0))) -> ∀ (body : term), ((R10 (R0))) -> (R11 ((tLambda (R4) (R3) (R1))))).\nλ (f6 : ∀ (na : name), ∀ (def : term), ((R9 (R0))) -> ∀ (def_ty : term), ((R11 (R0))) -> ∀ (body : term), ((R13 (R0))) -> (R14 ((tLetIn (R6) (R5) (R3) (R1))))).\nλ (f7 : ∀ (f7 : term), ((R9 (R0))) -> ∀ (args : (list (term))), (R11 ((tApp (R2) (R0))))).\nλ (f8 : ∀ (c : MetaCoq.Template.BasicAst.kername), ∀ (u : MetaCoq.Template.Universes.universe_instance), (R11 ((tConst (R1) (R0))))).\nλ (f9 : ∀ (ind : inductive), ∀ (u : MetaCoq.Template.Universes.universe_instance), (R12 ((tInd (R1) (R0))))).\nλ (f10 : ∀ (ind : inductive), ∀ (idx : nat), ∀ (u : MetaCoq.Template.Universes.universe_instance), (R14 ((tConstruct (R2) (R1) (R0))))).\nλ (f11 : ∀ (ind_and_nbparams : (prod (inductive) (nat))), ∀ (type_info : term), ((R14 (R0))) -> ∀ (discr : term), ((R16 (R0))) -> ∀ (branches : (list ((prod (nat) (term))))), (R18 ((tCase (R5) (R4) (R2) (R0))))).\nλ (f12 : ∀ (proj : MetaCoq.Template.BasicAst.projection), ∀ (t : term), ((R15 (R0))) -> (R16 ((tProj (R2) (R1))))).\nλ (f13 : ∀ (mfix : (MetaCoq.Template.BasicAst.mfixpoint (term))), ∀ (idx : nat), (R16 ((tFix (R1) (R0))))). λ (f14 : ∀ (mfix : (MetaCoq.Template.BasicAst.mfixpoint (term))), ∀ (idx : nat), (R17 ((tCoFix (R1) (R0))))).\n(fix F : ∀ (t : term), (R17 (R0)) :=\nλ (t : term).\nmatch R0 return λ (t0 : term). (R19 (R0)) with\n | λ (n : nat). (R18 (R0))\n | λ (id : MetaCoq.Template.BasicAst.ident). (R17 (R0))\n | λ (ev : nat). λ (args : (list (term))). (R17 (R1) (R0))\n | λ (s : MetaCoq.Template.Universes.universe). (R15 (R0))\n | λ (t0 : term). λ (kind : cast_kind). λ (v : term). (R16 (R2) ((R4 (R2))) (R1) (R0) ((R4 (R0))))\n | λ (na : name). λ (ty : term). λ (body : term). (R15 (R2) (R1) ((R4 (R1))) (R0) ((R4 (R0))))\n | λ (na : name). λ (ty : term). λ (body : term). (R14 (R2) (R1) ((R4 (R1))) (R0) ((R4 (R0))))\n | λ (na : name). λ (def : term). λ (def_ty : term). λ (body : term). (R14 (R3) (R2) ((R5 (R2))) (R1) ((R5 (R1))) (R0) ((R5 (R0))))\n | λ (f15 : term). λ (args : (list (term))). (R11 (R1) ((R3 (R1))) (R0))\n | λ (c : MetaCoq.Template.BasicAst.kername). λ (u : MetaCoq.Template.Universes.universe_instance). (R10 (R1) (R0))\n | λ (ind : inductive). λ (u : MetaCoq.Template.Universes.universe_instance). (R9 (R1) (R0))\n | λ (ind : inductive). λ (idx : nat). λ (u : MetaCoq.Template.Universes.universe_instance). (R9 (R2) (R1) (R0))\n | λ (ind_and_nbparams : (prod (inductive) (nat))). λ (type_info : term). λ (discr : term). λ (branches : (list ((prod (nat) (term))))). (R9 (R3) (R2) ((R5 (R2))) (R1) ((R5 (R1))) (R0))\n | λ (proj : MetaCoq.Template.BasicAst.projection). λ (t0 : term). (R6 (R1) (R0) ((R3 (R0))))\n | λ (mfix : (MetaCoq.Template.BasicAst.mfixpoint (term))). λ (idx : nat). (R5 (R1) (R0))\n | λ (mfix : (MetaCoq.Template.BasicAst.mfixpoint (term))). λ (idx : nat). (R4 (R1) (R0))\nend)\n*)\nMetaCoq Run (create term true false).\n(*\nλ (p : ∀ (inst : term), LTop.2491).\nλ (H_tRel : ∀ (n : nat), (R1 ((tRel (R0))))).\nλ (H_tVar : ∀ (id : MetaCoq.Template.BasicAst.ident), (R2 ((tVar (R0))))).\nλ (H_tEvar : ∀ (ev : nat), ∀ (args : (list (term))), ∀ (IH_args : (R4 (R5) (R0))), (R5 ((tEvar (R2) (R1))))).\nλ (H_tSort : ∀ (s : MetaCoq.Template.Universes.universe), (R4 ((tSort (R0))))).\nλ (H_tCast : ∀ (t : term), ∀ (kind : cast_kind), ∀ (v : term), ∀ (IH_t : (R7 (R2))), ∀ (IH_v : (R8 (R1))), (R9 ((tCast (R4) (R3) (R2))))).\nλ (H_tProd : ∀ (na : name), ∀ (ty : term), ∀ (body : term), ∀ (IH_ty : (R8 (R1))), ∀ (IH_body : (R9 (R1))), (R10 ((tProd (R4) (R3) (R2))))).\nλ (H_tLambda : ∀ (na : name), ∀ (ty : term), ∀ (body : term), ∀ (IH_ty : (R9 (R1))), ∀ (IH_body : (R10 (R1))), (R11 ((tLambda (R4) (R3) (R2))))).\nλ (H_tLetIn : ∀ (na : name), ∀ (def : term), ∀ (def_ty : term), ∀ (body : term), ∀ (IH_def : (R11 (R2))), ∀ (IH_def_ty : (R12 (R2))), ∀ (IH_body : (R13 (R2))), (R14 ((tLetIn (R6) (R5) (R4) (R3))))).\nλ (H_tApp : ∀ (f : term), ∀ (args : (list (term))), ∀ (IH_f : (R10 (R1))), ∀ (IH_args : (R11 (R12) (R1))), (R12 ((tApp (R3) (R2))))).\nλ (H_tConst : ∀ (c : MetaCoq.Template.BasicAst.kername), ∀ (u : MetaCoq.Template.Universes.universe_instance), (R11 ((tConst (R1) (R0))))).\nλ (H_tInd : ∀ (ind : inductive), ∀ (u : MetaCoq.Template.Universes.universe_instance), (R12 ((tInd (R1) (R0))))).\nλ (H_tConstruct : ∀ (ind : inductive), ∀ (idx : nat), ∀ (u : MetaCoq.Template.Universes.universe_instance), (R14 ((tConstruct (R2) (R1) (R0))))).\nλ (H_tCase : ∀ (ind_and_nbparams : (prod (inductive) (nat))), ∀ (type_info : term), ∀ (discr : term), ∀ (branches : (list ((prod (nat) (term))))), ∀ (IH_type_info : (R16 (R2))), ∀ (IH_discr : (R17 (R2))), ∀ (IH_branches : (R18 ((prod (nat) (R19))) (R2))), (R19 ((tCase (R6) (R5) (R4) (R3))))). λ (H_tProj : ∀ (proj : MetaCoq.Template.BasicAst.projection), ∀ (t : term), ∀ (IH_t : (R15 (R0))), (R16 ((tProj (R2) (R1))))). λ (H_tFix : ∀ (mfix : (MetaCoq.Template.BasicAst.mfixpoint (term))), ∀ (idx : nat), ∀ (IH_mfix : (R16 (R17) (R1))), (R17 ((tFix (R2) (R1))))). λ (H_tCoFix : ∀ (mfix : (MetaCoq.Template.BasicAst.mfixpoint (term))), ∀ (idx : nat), ∀ (IH_mfix : (R17 (R18) (R1))), (R18 ((tCoFix (R2) (R1))))).\n(fix f : ∀ (inst : term), (R17 (R0)) :=\nλ (inst : term).\nmatch R0 return λ (inst : term). (R19 (R0)) with\n | λ (n : nat). (R18 (R0))\n | λ (id : MetaCoq.Template.BasicAst.ident). (R17 (R0))\n | λ (ev : nat). λ (args : (list (term))). (R17 (R1) (R0) ((R3 (R21) (R0))))\n | λ (s : MetaCoq.Template.Universes.universe). (R15 (R0))\n | λ (t : term). λ (kind : cast_kind). λ (v : term). (R16 (R2) (R1) (R0) ((R4 (R2))) ((R4 (R0))))\n | λ (na : name). λ (ty : term). λ (body : term). (R15 (R2) (R1) (R0) ((R4 (R1))) ((R4 (R0))))\n | λ (na : name). λ (ty : term). λ (body : term). (R14 (R2) (R1) (R0) ((R4 (R1))) ((R4 (R0))))\n | λ (na : name). λ (def : term). λ (def_ty : term). λ (body : term). (R14 (R3) (R2) (R1) (R0) ((R5 (R2))) ((R5 (R1))) ((R5 (R0))))\n | λ (f : term). λ (args : (list (term))). (R11 (R1) (R0) ((R3 (R1))) ((R3 (R21) (R0))))\n | λ (c : MetaCoq.Template.BasicAst.kername). λ (u : MetaCoq.Template.Universes.universe_instance). (R10 (R1) (R0))\n | λ (ind : inductive). λ (u : MetaCoq.Template.Universes.universe_instance). (R9 (R1) (R0))\n | λ (ind : inductive). λ (idx : nat). λ (u : MetaCoq.Template.Universes.universe_instance). (R9 (R2) (R1) (R0))\n | λ (ind_and_nbparams : (prod (inductive) (nat))). λ (type_info : term). λ (discr : term). λ (branches : (list ((prod (nat) (term))))). (R9 (R3) (R2) (R1) (R0) ((R5 (R2))) ((R5 (R1))) ((R5 ((prod (nat) (R23))) (R0))))\n | λ (proj : MetaCoq.Template.BasicAst.projection). λ (t : term). (R6 (R1) (R0) ((R3 (R0))))\n | λ (mfix : (MetaCoq.Template.BasicAst.mfixpoint (term))). λ (idx : nat). (R5 (R1) (R0) ((R3 (R21) (R1))))\n | λ (mfix : (MetaCoq.Template.BasicAst.mfixpoint (term))). λ (idx : nat). (R4 (R1) (R0) ((R3 (R21) (R1))))\nend) \n *)\n\n(* MetaCoq Run (create term true true). *)\n(* Print term_ind_MC. *)\n\n\n\n\n(* Inductive rtree A : Type := *)\n(* | Leaf (a:A) *)\n(* | Node (l:list (rtree A)). *)\n\n(* MetaCoq Run (create rtree false true). *)\n(* Print rtree_case_MC. *)\n(* MetaCoq Run (create rtree true true). *)\n(* Print rtree_ind_MC. *)\n(* Print rtree_ind. *)\n\n\n\n(* Inductive listᵗ (A : Type) (Aᵗ : A -> Type) : list A -> Type := *)\n(*     nilᵗ : listᵗ A Aᵗ [] | consᵗ : forall H : A, Aᵗ H -> forall H0 : list A, listᵗ A Aᵗ H0 -> listᵗ A Aᵗ (H :: H0). *)\n\n(* Inductive rtreeᵗ (A : Type) (Aᵗ : A -> Type) : rtree A -> Type := *)\n(*     Leafᵗ : forall a : A, Aᵗ a -> rtreeᵗ A Aᵗ (Leaf A a) *)\n(*   | Nodeᵗ : forall l : list (rtree A), listᵗ (rtree A) (rtreeᵗ A Aᵗ) l -> rtreeᵗ A Aᵗ (Node A l). *)\n\n(* MetaCoq Run (create rtreeᵗ true true). *)\n(* Print rtreeᵗ_ind_MC. *)\n\n\n(* here are nested *)\n\n\n\n\n(** dependent indices **)\n\nLemma eqIsEq X (a:X) : a=a.\nProof.\n  exact(Logic.eq_refl).\nQed.\n\nInductive dep (X:Type) : nat -> forall (x:X), x=x -> Prop :=\n| dep0 y : dep X 0 y (@Coq.Init.Logic.eq_refl _ y).\n\nMetaCoq Quote Definition Edep :=\n  (\n    fun (X:Type) (p:forall n x h, dep X n x h -> Prop) =>\n      fun Hdep0 =>\n        fix f m x h (i:dep X m x h) :=\n      match i in dep _ m' x' h' return p m' x' h' i with\n        dep0 y => Hdep0 y\n      end\n  ).\n(* MetaCoq Run (bruijn_print Edep). *)\n(*\nλ (X : LTop.658).\nλ (p : ∀ (n : nat), ∀ (x : R1), ∀ (h : (eq (R2) (R0) (R0))), ((dep (R3) (R2) (R1) (R0))) -> Prop).\n  λ (Hdep0 : ∀ (x : R1), (R1 (O) (R0) ((eq_refl (R2) (R0))) ((dep0 (R2) (R0))))).\n  (fix f : ∀ (m : nat), ∀ (x : R3), ∀ (h : (eq (R4) (R0) (R0))), ∀ (i : (dep (R5) (R2) (R1) (R0))), (R5 (R3) (R2) (R1) (R0)) :=\n       λ (m : nat). λ (x : R4). λ (h : (eq (R5) (R0) (R0))). λ (i : (dep (R6) (R2) (R1) (R0))).\n       match R0 return λ (m' : nat). λ (x' : R8). λ (h' : (eq (R9) (R0) (R0))). λ (i : (dep (R01) (R2) (R1) (R0))). (R01 (R3) (R2) (R1) (R0)) with\n       | λ (y : R7). (R6 (R0))\n       end\n  )\n *)\nMetaCoq Run (create dep false false).\nMetaCoq Run (create dep false true).\nPrint dep_case_MC.\nMetaCoq Run (create dep true true).\nPrint dep_ind_MC.\n\n(** indices **)\n\nInductive indTest (X:Type) : nat -> Prop :=\n  | indC0 : indTest X 0.\n\nPrint indTest.\nMetaCoq Run (create indTest false false).\nMetaCoq Run (create indTest false true).\nPrint indTest_case_MC.\nMetaCoq Run (create indTest true true).\nPrint indTest_ind_MC.\n\nPrint le_n.\nCheck le_n.\nCheck le_S.\nMetaCoq Run (create Peano.le false true).\nMetaCoq Quote Definition leElimType := (\nforall (n : nat) (p : forall H : nat, n <= H -> Prop),\n             p n (le_n n) ->\n             (forall (m : nat) (H : n <= m), p (S m) (le_S n m H)) -> forall (H : nat) (inst : n <= H), p H inst\n                                      ).\nPrint leElimType.\n\nPrint le_case_MC.\nMetaCoq Run (create Peano.le true true).\nPrint le_ind_MC.\n\nInductive eqT (X:Type) (x:X) : X -> Prop := Qcon : eqT X x x.\n\nMetaCoq Run (create eqT false false).\nMetaCoq Run (create eqT false true).\nPrint eqT_case_MC.\nMetaCoq Run (create eqT true true).\nPrint eqT_ind_MC.\n\nInductive double : nat -> nat -> Prop :=\n| d0 : double 0 0\n| dS x y : double x y -> double (S x) (S(S y)).\n\nMetaCoq Run (create double false true).\nPrint double_case_MC.\nMetaCoq Run (create double true true).\nPrint double_ind_MC.\n\nInductive addition : nat -> nat -> nat -> Prop :=\n| add0 x : addition 0 x x\n| addS x y z : addition x y z -> addition (S x) y (S z).\n\nMetaCoq Run (create addition false true).\nPrint addition_case_MC.\nMetaCoq Run (create addition true true).\nPrint addition_ind_MC.\n\n\nPrint Peano.le.\nPrint Peano.le_ind.\nMetaCoq Quote Definition Ele :=\n  (fun n (p:forall m, n<=m -> Prop) Hn Hs =>\n    fix f m (x:n<=m) :=\n    match x in (_ <= m2) return p m2 x with\n    | le_n => Hn\n    | le_S k H => Hs k H\n    end).\nPrint Ele.\n(* MetaCoq Run (bruijn_print Ele). *)\n(*\nλ (n : nat). λ (p : ∀ (m : nat), ((le (R1) (R0))) -> Prop).\n   λ (Hn : (R0 (R1) ((le_n (R1))))).\n   λ (Hs : ∀ (x : nat), ∀ (x0 : (le (R3) (R0))), (R3 ((S (R1))) ((le_S (R4) (R1) (R0))))).\n   (fix f : ∀ (m : nat), ∀ (x : (le (R4) (R0))), (R4 (R1) (R0)) :=\n        λ (m : nat). λ (x : (le (R5) (R0))).\n        match R0 return λ (m2 : nat). λ (x : (le (R7) (R0))). (R7 (R1) (R0)) with\n        | R4\n        | λ (k : nat). λ (H : (le (R7) (R0))). (R5 (R1) (R0))\n        end\n   )\n *)\n\n\n\n\n(** Parameter **)\n\nMetaCoq Quote Definition qElist := (fun X (p:list X -> Prop) Hnil Hcons =>\n              fix f xs :=\n              match xs return p xs with\n                | nil => Hnil\n                | y::ys => Hcons y ys\n              end\n                           ).\nPrint qElist.\n(* MetaCoq Run (bruijn_print qElist). *)\n(*\nλ (X : LTop.793). λ (p : ((list (R0))) -> Prop).\n  λ (Hnil : (R0 ((nil (R1))))).\n  λ (Hcons : ∀ (x : R2), ∀ (x0 : (list (R3))), (R3 ((cons (R4) (R1) (R0))))).\n  (fix f : ∀ (xs : (list (R3))), (R3 (R0)) := λ (xs : (list (R4))).\n       match R0 return λ (xs : (list (R5))). (R5 (R0)) with\n             | R3\n             | λ (y : R5). λ (ys : (list (R6))). (R4 (R1) (R0))\n       end\n  )\n *)\n\nMetaCoq Run (create list false false).\nMetaCoq Run (create list false true).\nPrint list_case_MC.\nPrint list_ind.\nMetaCoq Quote Definition E_list :=\n(fun (A : Type) (P : list A -> Prop) (f : P []) (f0 : forall (a : A) (l : list A), P l -> P (a :: l)) =>\nfix F (l : list A) : P l := match l as l0 return (P l0) with\n                            | [] => f\n                            | y :: l0 => f0 y l0 (F l0)\n                            end\n).\n(* MetaCoq Run (bruijn_print E_list). *)\n(*\nλ (A : LTop.1687).\nλ (P : ((list (R0))) -> Prop).\nλ (f : (R0 ((nil (R1))))).\nλ (f0 : ∀ (a : R2), ∀ (l : (list (R3))), ((R3 (R0))) -> (R4 ((cons (R5) (R2) (R1))))).\n(fix F : ∀ (l : (list (R3))), (R3 (R0)) :=\nλ (l : (list (R4))).\nmatch R0 return λ (l0 : (list (R5))). (R5 (R0)) with\n | R3\n | λ (y : R5). λ (l0 : (list (R6))). (R4 (R1) (R0) ((R3 (R0))))\nend)\n *)\nMetaCoq Run (create list true false).\n(*\nλ (A : LCoq.Init.Datatypes.44).\nλ (p : ∀ (inst : (list (R0))), LTop.1260).\nλ (H_nil : (R0 ((nil (R1))))).\nλ (H_cons : (R2) -> ((list (R3))) -> (R3 ((cons (R4) (R1) (R0))))).\n(fix f : ∀ (inst : (list (R3))), (R3 (R0)) :=\nλ (inst : (list (R4))).\nmatch R0 return λ (inst : (list (R5))). (R5 (R0)) with\n | R3\n | λ (_ : R5). λ (_ : (list (R6))). (R4 (R1) (R0) ((R3 (R0))))\nend)\n*)\nMetaCoq Run (create list true true).\nPrint list_ind_MC.\n\nInductive mutParam (X:Type) (f:X->bool) : Type :=\n  | mP : mutParam X f.\n\nMetaCoq Run (create mutParam false true).\nPrint mutParam.\nPrint mutParam_case_MC.\nMetaCoq Run (create mutParam true true).\nPrint mutParam_ind_MC.\n\nMetaCoq Run (create and false true).\nPrint and_case_MC.\nMetaCoq Run (create and true true).\nPrint and_ind_MC.\nMetaCoq Run (create or false false).\nMetaCoq Run (create or false true).\nPrint or_case_MC.\nMetaCoq Run (create or true true).\nPrint or_ind_MC.\nMetaCoq Run (create ex false true).\nPrint ex_case_MC.\nPrint ex.\nScheme Induction for ex Sort Prop.\nPrint ex_ind_dep.\nPrint ex_case_MC.\nMetaCoq Run (create ex false false).\n(*\nλ (A : LCoq.Init.Logic.4).\nλ (P : (R0) -> Prop).\nλ (p : ∀ (inst : (ex (R1) (R0))), Prop).\nλ (H_ex_intro : ∀ (x : R2), ((R2 (R0))) -> (R2 ((ex_intro (R4) (R3) (R1) (R0))))).\n(fix f : ∀ (inst : (ex (R3) (R2))), (R2 (R0)) :=\nλ (inst : (ex (R4) (R3))).\nmatch R0 return λ (inst : (ex (R5) (R4))). (R4 (R0)) with\n | λ (x : R5). λ (_ : (R5 (R0))). (R4 (R1) (R0))\nend)\n*)\nMetaCoq Run (create ex true false).\nMetaCoq Run (create ex true true).\nPrint ex_ind_MC.\n\n\n\nInductive G (f:nat->bool) : nat -> Prop :=\n  GI : forall n, (f n = false -> G f (S n)) -> G f n.\n\n\nPrint G_ind.\nMetaCoq Quote Definition E_G := (fun (f : nat -> bool) (P : forall n, G f n -> Prop)\n  (f0 : forall (n : nat) (h:f n = false -> G f (S n)), (forall (h2:f n = false), P (S n) (h h2)) -> P n (GI f n h)) =>\nfix F (n : nat) (g : G f n) {struct g} : P n g :=\n  match g in (G _ n0) return (P n0 g) with\n  | @GI _ n0 g0 => f0 n0 g0 (fun e : f n0 = false => F (S n0) (g0 e))\n  end).\n(* MetaCoq Run(bruijn_print E_G). *)\n(*\nλ (f : (nat) -> bool).\nλ (P : ∀ (n : nat), ((G (R1) (R0))) -> Prop).\nλ (f0 : ∀ (n : nat), ∀ (h : ((eq (bool) ((R2 (R0))) (false))) -> (G (R3) ((S (R1))))), (∀ (h2 : (eq (bool) ((R3 (R1))) (false))), (R3 ((S (R2))) ((R1 (R0))))) -> (R3 (R2) ((GI (R4) (R2) (R1))))).\n(fix F : ∀ (n : nat), ∀ (g : (G (R3) (R0))), (R3 (R1) (R0)) :=\nλ (n : nat). λ (g : (G (R4) (R0))).\nmatch R0 return λ (n0 : nat). λ (g : (G (R6) (R0))). (R6 (R1) (R0)) with\n | λ (n0 : nat). λ (g0 : ((eq (bool) ((R6 (R0))) (false))) -> (G (R7) ((S (R1))))). (R5 (R1) (R0) (λ (e : (eq (bool) ((R7 (R1))) (false))). (R5 ((S (R2))) ((R1 (R0))))))\nend) *)\nMetaCoq Run (create G false false).\nMetaCoq Run (create G false true).\nPrint G_case_MC.\n(*\nλ (f : (nat) -> bool).\nλ (p : (nat) -> ∀ (inst : (G (R1) (R0))), Prop).\nλ (H_GI : ∀ (n : nat), (((eq (bool) ((R2 (R0))) (false))) -> (G (R3) ((S (R1))))) -> (R2 (R1) ((GI (R3) (R1) (R0))))).\n(fix f : (nat) -> ∀ (inst : (G (R3) (R0))), (R3 (R1) (R0)) := \nλ (_ : nat). λ (inst : (G (R4) (R0))). \nmatch R0 return λ (_ : nat). λ (inst : (G (R6) (R0))). (R6 (R1) (R0)) with\n | λ (n : nat). λ (_ : ((eq (bool) ((R6 (R0))) (false))) -> (G (R7) ((S (R1))))). (R5 (R1) (R0))\nend)\n *)\n\nPrint G.\nMetaCoq Run (create G true false).\n(*\nλ (f : (nat) -> bool).\nλ (p : (nat) -> ∀ (inst : (G (R1) (R0))), Prop).\nλ (H_GI : ∀ (n : nat), (((eq (bool) ((R2 (R0))) (false))) -> (G (R3) ((S (R1))))) -> ∀ (IH : ((eq (bool) ((R3 (R1))) (false))) -> (R3 ((S (R2))) ((R1 (R0))))), (R3 (R2) ((GI (R4) (R2) (R1))))).\n(fix f : (nat) -> ∀ (inst : (G (R3) (R0))), (R3 (R1) (R0)) :=\nλ (_ : nat). λ (inst : (G (R4) (R0))).\nmatch (P:1) R0 return λ (_ : nat). λ (inst : (G (R6) (R0))). (R6 (R1) (R0)) with\n | (2) λ (n : nat). λ (_ : ((eq (bool) ((R6 (R0))) (false))) -> (G (R7) ((S (R1))))). (R5 (R1) (R0) (λ (_ : (eq (bool) ((R6 (R1))) (false))). (R5 ((S (R2))) ((R1 (R0))))))\nend)\n*)\n\nPrint G.\nMetaCoq Run (create G true true).\nPrint G_ind_MC.\nPrint G.\nPrint Acc.\nMetaCoq Run (create Acc true false).\n(* Print Acc_ind_MC. *) (* after move to test *)\n\n(* Inductive G3 (f:nat->bool) (n:nat) : Prop := *)\n(*   G3I : (f n = false -> G3 f (S n)) -> G3 f n. *)\n\n(* Scheme Induction for G3 Sort Type. *)\n(* Print G3_rect_dep. *)\n\n(* Quote Definition E_G3 := (fun (f : nat -> bool) (p : forall n : nat, G3 f n -> Type) *)\n(*   (HG3I : forall (n : nat) (h : f n = false -> G3 f (S n)), *)\n(*         p n (G3I f n h)) => *)\n(* fix F (n : nat) (g : G3 f n) {struct g} : p n g := *)\n(*   match g as g0 return (p n g0) with *)\n(*   | @G3I _ _ h => HG3I n h *)\n(*   end). *)\n\n(* MetaCoq Run (bruijn_print E_G3). *)\n\n\n(*\nλ (f : (nat) -> bool).\nλ (p : ∀ (n : nat), ((G3 (R1) (R0))) -> LTop.654).\nλ (HG3I : ∀ (n : nat), ∀ (h : ((eq (bool) ((R2 (R0))) (false))) -> (G3 (R3) ((S (R1))))), (R2 (R1) ((G3I (R3) (R1) (R0))))).\n(fix F : ∀ (n : nat), ∀ (g : (G3 (R3) (R0))), (R3 (R1) (R0)) :=\nλ (n : nat). λ (g : (G3 (R4) (R0))).\nmatch R0 return λ (g0 : (G3 (R5) (R1))). (R5 (R2) (R0)) with\n | λ (h : ((eq (bool) ((R5 (R1))) (false))) -> (G3 (R6) ((S (R2))))). (R4 (R2) (R0))\nend)\n *)\n\n\n(*\nλ (f : (nat) -> bool).\nλ (P : ∀ (n : nat), ((G3 (R1) (R0))) -> LTop.2540).\nλ (f0 : ∀ (n : nat), ∀ (g : ((eq (bool) ((R2 (R0))) (false))) -> (G3 (R3) ((S (R1))))), (R2 (R1) ((G3I (R3) (R1) (R0))))).\n(fix F : ∀ (n : nat), ∀ (g : (G3 (R3) (R0))), (R3 (R1) (R0)) := \nλ (n : nat). λ (g : (G3 (R4) (R0))). \nmatch R0 return λ (g0 : (G3 (R5) (R1))). (R5 (R2) (R0)) with\n | λ (g0 : ((eq (bool) ((R5 (R1))) (false))) -> (G3 (R6) ((S (R2))))). (R4 (R2) (R0))\nend)\n *)\n\nMetaCoq Run (create G3 false false).\n(*\n\n *)\n(* MetaCoq Run (create G3 false true). *)\n(* Print G3_case_MC. *)\n(* MetaCoq Run (create G3 true true). *)\n(* Print G3_ind_MC. *)\n\nPrint Acc.\nMetaCoq Run (create Acc false true).\nPrint Acc_case_MC.\n(* Print Acc_ind_MC. *) (* after move to test *)\n\n(* Quote Definition E_Acc := *)\n(*   fun (A:Type) (R:A->A->Prop) (p:forall (x:A), ) *)\n\n(* MetaCoq Run (create Acc true true). *)\n(* Print Acc_ind_MC. *)\n\n\nInductive G2 (f:nat->bool) : nat -> Prop :=\n  G2I1 : forall n, (f n = false -> G2 f (S n)) -> (f n = true -> G2 f (S (S n))) -> G2 f n\n| G2I2 : forall n, (f n = false -> G2 f (S n)) -> G2 f n.\n\nMetaCoq Run (create G2 false true).\nPrint G2_case_MC.\nMetaCoq Run (create G2 true true).\nPrint G2_ind_MC.\n\n(** without params, indices **)\n\nInductive pfree : Type :=\n  | p0 : pfree\n  | p1 : pfree\n  | p2 (n:nat) : pfree\n  | p3 : pfree -> pfree\n  | p4 (b:bool) (p:pfree) (n:nat) : pfree.\n\nMetaCoq Run (create pfree false true).\nPrint pfree_case_MC.\nMetaCoq Run (create pfree true true).\nPrint pfree_ind_MC.\n\nMetaCoq Run (create bool false true).\nPrint bool_case_MC.\nMetaCoq Run (create bool true true).\nPrint bool_ind_MC.\n\nMetaCoq Run (create True false true).\nPrint True_case_MC.\nMetaCoq Run (create True true true).\nPrint True_ind_MC.\n\nMetaCoq Run (create False false true).\nPrint False_case_MC.\nMetaCoq Run (create False true true).\nPrint False_ind_MC.\n\nMetaCoq Run (create nat false false).\n(* MetaCoq Run (create nat false true). *)\n(* Print nat_case_MC. *) (* after move to test *)\nDefinition Enat :=\nfun (p : nat -> Type) (H_O : p 0) (H_S : forall H : nat, p (S H)) =>\nfix f (inst : nat) : p inst := match inst as inst0 return (p inst0) with\n                               | 0 => H_O\n                               | S x => H_S x\n                               end.\n\n\n(* MetaCoq Run (create nat true true). *)\n(* Print nat_ind_MC. *) (* after move to test *)\n\n\n\n\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/nested_induction/test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.28390411580912817}}
{"text": "Require Import Logic.GeneralLogic.Base.\nRequire Import Logic.MinimumLogic.Syntax.\nRequire Import Logic.MinimumLogic.ProofTheory.Minimum.\nRequire Import Logic.MinimumLogic.ProofTheory.RewriteClass.\nRequire Import Logic.MinimumLogic.ProofTheory.ProofTheoryPatterns.\nRequire Import Logic.PropositionalLogic.Syntax.\nRequire Import Logic.PropositionalLogic.ProofTheory.Intuitionistic.\nRequire Import Logic.PropositionalLogic.ProofTheory.RewriteClass.\nRequire Import Logic.PropositionalLogic.ProofTheory.ProofTheoryPatterns.\nRequire Import Logic.PropositionalLogic.ProofTheory.TheoryOfIteratedConnectives.\n\nRequire Logic.PropositionalLogic.DeepEmbedded.Deep.\n\nLocal Open Scope list_scope.\n\nLtac length_cont ls k :=\n  match ls with\n  | nil => k O\n  | _ :: ?ls' => length_cont ls' ltac:(fun n => k (S n))\n  end.\nLtac length ls := length_cont ls ltac:(fun l => l).\n\nDefinition rev (l: list nat): list nat :=\n  (fix rev (l: list nat) (cont: list nat -> list nat): list nat :=\n    match l with\n    | nil => cont nil\n    | a :: l0 => rev l0 (fun l => a :: cont l)\n    end) l (fun l => l).\n\nLtac reverse_cont l k :=\n  match l with\n  | @nil ?T => k (@nil T)\n  | @cons _ ?h ?t =>\n    let k' l :=\n        let t' := k l in\n        constr:(cons h t')\n    in reverse_cont t k'\n  end.\nLtac reverse l := reverse_cont l ltac:(fun l => l).\n\nLtac pred n :=\n  match n with\n  | O => O\n  | S ?m => m\n  end.\n\nLtac search_expr' n i l l0 :=\n  match l with\n  | nil => let len := length l0 in constr:((S len, n :: l0))\n  | n :: ?t => constr:((i, l0))\n  | _ :: ?t => let pi := pred i in search_expr' n pi t l0\n  end.\nLtac search_expr n l := let len := length l in search_expr' n len l l.\n\nSection Temp.\n  Context {L : Language}\n          {minL : MinimumLanguage L}\n          {andpL : AndLanguage L}\n          (default: Base.expr)\n          (tbl : list Base.expr).\n\n  Fixpoint reflect (e : Deep.expr) : Base.expr :=\n    match e with\n    | Deep.varp n => List.nth (pred n) tbl default\n    | Deep.andp e1 e2 => Syntax.andp (reflect e1) (reflect e2)\n    | Deep.impp e1 e2 => Syntax.impp (reflect e1) (reflect e2)\n    end.\nEnd Temp.\n\nLtac shallowToDeep' se l0 :=\n  match se with\n  | Syntax.andp ?sp ?sq =>\n    match shallowToDeep' sp l0 with\n    | (?dp, ?l1) =>\n      match shallowToDeep' sq l1 with\n      | (?dq, ?l2) => constr:((Deep.andp dp dq, l2))\n      end\n    end\n  | Syntax.impp ?sp ?sq =>\n    match shallowToDeep' sp l0 with\n    | (?dp, ?l1) =>\n      match shallowToDeep' sq l1 with\n      | (?dq, ?l2) => constr:((Deep.impp dp dq, l2))\n      end\n    end\n  | ?sp => match search_expr sp l0 with\n          | (?i, ?l1) => constr:((Deep.varp i, l1))\n          end\n  end.\n\nLtac shallowToDeep se :=\n  match shallowToDeep' se constr:(@nil Base.expr) with\n  | (?de, ?tbl) =>\n    let tbl' := reverse tbl in\n    assert (reflect se tbl' de = se) by reflexivity\n  end.\n\nSection Temp.\n  Context (L : Base.Language)\n          (minL : Syntax.MinimumLanguage L)\n          (andL : Syntax.AndLanguage L).\n  Context (P Q R : Base.expr).\n  Goal False.\n    let n := search_expr 1 (1 :: 2 :: 3 :: 4 :: nil) in pose n.\n    let n := search_expr 5 (1 :: 2 :: 3 :: 4 :: nil) in pose n.\n    shallowToDeep (Syntax.impp (Syntax.andp P Q) (Syntax.andp Q P)).\n  Abort.\nEnd Temp.\n\nSection Temp.\n  Context {L: Language}\n          {minL: MinimumLanguage L}\n          {andpL: AndLanguage L}\n          {GammaP: Provable L}\n          {minAX: MinimumAxiomatization L GammaP}\n          {andpAX: AndAxiomatization L GammaP}.\n\n  Theorem reify_sound :\n    forall table (default: Base.expr) (e : Deep.expr),\n      Deep.provable e -> provable (reflect default table e).\n  Proof.\n    induction 1.\n    - apply (modus_ponens (reflect default table x) (reflect default table y)); assumption.\n    - apply (axiom1 (reflect default table x) (reflect default table y)); assumption.\n    - apply (axiom2 (reflect default table x) (reflect default table y)); assumption.\n    - apply (andp_intros (reflect default table x) (reflect default table y)); assumption.\n    - apply (andp_elim1 (reflect default table x) (reflect default table y)); assumption.\n    - apply (andp_elim2 (reflect default table x) (reflect default table y)); assumption.\n  Qed.\nEnd Temp.\n\nModule DSolver.\n  Local Existing Instances Deep.L Deep.minL Deep.andpL Deep.truepL Deep.iffpL Deep.iter_andp_L Deep.iter_andp_DL Deep.GP Deep.minAX Deep.andpAX Deep.truepAX Deep.iffpAX Deep.iter_andp_AXL.\n\n  Instance Adj : P.Adjointness _ _ andp impp.\n  Proof.\n    constructor. split; intros.\n    - rewrite <- impp_uncurry. auto.\n    - rewrite <- impp_curry. auto.\n  Qed.\n\n  Instance Comm : P.Commutativity _ _ andp.\n  Proof.\n    apply andp_Comm.\n  Qed.\n\n  Instance Mono : P.Monotonicity _ _ andp.\n  Proof.\n    apply andp_Mono.\n  Qed.\n\n  Instance Assoc : P.Associativity _ _ andp.\n  Proof.\n    apply andp_Assoc.\n  Qed.\n\n  Instance LUnit : P.LeftUnit _ _ truep andp.\n  Proof.\n    constructor; intros; rewrite truep_andp; apply provable_impp_refl.\n  Qed.\n\n  Instance RUnit : P.RightUnit _ _ truep andp.\n  Proof.\n    constructor; intros; rewrite andp_truep; apply provable_impp_refl.\n  Qed.\n\n  Fixpoint flatten_imp (e : expr) : list expr * expr :=\n    match e with\n    | Deep.impp p q => let (cxt, fq) := flatten_imp q in (p :: cxt, fq)\n    | _ => (nil, e)\n    end.\n\n  Definition flatten_imp_inv (p : list Deep.expr * Deep.expr) :=\n    let (ctx, r) := p in multi_imp ctx r.\n\n  Lemma flatten_imp_sound :\n    forall e, e = flatten_imp_inv (flatten_imp e).\n  Proof.\n    intros. induction e; auto.\n    simpl.\n    destruct (flatten_imp e2) as [ctx fq].\n    simpl. rewrite IHe2. auto.\n  Qed.\n\n  Fixpoint flatten_and (e : expr) : list expr :=\n    match e with\n    | Deep.andp p q => (flatten_and p ++ flatten_and q)\n    | s => s :: nil\n    end.\n\n  Lemma flatten_and_sound :\n    forall e, provable (iffp e (iter_andp (flatten_and e))).\n  Proof.\n    intros.\n    rewrite iter_andp_def_l.\n    induction e; simpl flatten_and\n        (*;\n      [ change (flatten_and_inv _) with (fold_left andp (flatten_and e1 ++ flatten_and e2) truep)\n      | change (flatten_and_inv _) with (andp truep (orp e1 e2))\n      | change (flatten_and_inv _) with (andp truep (impp e1 e2))\n      | change (flatten_and_inv _) with (andp truep falsep)\n      | change (flatten_and_inv _) with (andp truep (Deep.varp n))\n      ]*).\n    {\n      apply solve_iffp_intros. \n      {\n        rewrite <- P.assoc_prodp_fold_left.\n        rewrite iffp_elim1 in IHe1.\n        rewrite iffp_elim1 in IHe2.\n        apply P.prodp_mono; auto.\n      }\n      {\n        rewrite P.assoc_fold_left_app.\n        rewrite iffp_elim2 in IHe1.\n        rewrite iffp_elim2 in IHe2.\n        apply P.prodp_mono; auto.\n      }\n    }\n    all: apply solve_iffp_intros;\n      cbv [fold_left];\n      [rewrite <- P.left_unit2 | rewrite P.left_unit1];\n      apply provable_impp_refl.\n  Qed.\n\n  Definition flatten (e : expr) : list expr * list expr :=\n    let (ctx, r) := flatten_imp e in\n    (List.flat_map flatten_and ctx, flatten_and r).\n\n  Definition AllInContext (es1 es2 : list expr) : Prop :=\n    Forall (fun e => In e es1) es2.\n\n  Lemma multi_imp_weaken :\n    forall x y xs, provable (impp x y) -> provable (impp x (multi_imp xs y)).\n  Proof.\n    induction xs; intros.\n    - auto.\n    - change (multi_imp _ _) with (impp a (multi_imp xs y)).\n      rewrite <- aux_minimun_theorem01. auto.\n  Qed.\n\n  Lemma flatten_imp_inv_In : forall es r, In r es -> provable (flatten_imp_inv (es,r)).\n  Proof.\n    intros. induction es.\n    - contradiction.\n    - inversion H; subst.\n      + change (flatten_imp_inv _) with (impp r (multi_imp es r)).\n        apply multi_imp_weaken. apply provable_impp_refl.\n      + change (flatten_imp_inv _) with (impp a (multi_imp es r)).\n        apply aux_minimun_rule00. auto.\n  Qed.\n\n  Lemma multi_imp_andp_intros :\n    forall es x y, provable (multi_imp es x) ->\n              provable (multi_imp es y) ->\n              provable (multi_imp es (andp x y)).\n  Proof.\n    intros es x y Hx Hy.\n    pose proof provable_multi_imp_weaken es x (impp y (andp x y)) (andp_intros x y).\n    pose proof modus_ponens _ _ H Hx.\n    pose proof provable_multi_imp_modus_ponens es y (andp x y).\n    pose proof modus_ponens _ _ H1 Hy.\n    pose proof modus_ponens _ _ H2 H0.\n    exact H3.\n  Qed.\n\n  Lemma flatten_inv_left_In :\n    forall es r, In r (List.flat_map flatten_and es) -> provable (flatten_imp_inv (es, r)).\n  Proof.\n    intros.\n    induction es; [contradiction|].\n    simpl in H.\n    apply in_app_or in H.\n    destruct H.\n    + clear IHes.\n      apply flatten_imp_inv_In in H.\n      change (flatten_imp_inv _) with (multi_imp (flatten_and a) r) in H.\n      rewrite <- iter_andp_multi_imp in H.\n      pose proof flatten_and_sound a.\n      change (flatten_imp_inv _) with (impp a (multi_imp es r)).\n      apply multi_imp_weaken.\n      apply solve_iffp_elim1 in H0.\n      eapply aux_minimun_rule02; eauto.\n    + apply aux_minimun_rule00, IHes, H.\n  Qed.\n\n  Lemma flatten_inv_All :\n    forall es r, AllInContext (List.flat_map flatten_and es) (flatten_and r) ->\n            provable (flatten_imp_inv (es, r)).\n  Proof.\n    intros.\n    assert (Forall (fun e => provable (flatten_imp_inv (es, e)))\n                   (flatten_and r)).\n    { unfold AllInContext in H. rewrite Forall_forall in *. intros e ?.\n      specialize (H e H0). clear H0.\n      apply flatten_inv_left_In, H.\n    } clear H. rename H0 into H.\n    induction r; try apply (Forall_inv H).\n    simpl in H; apply Coqlib.Forall_app_iff in H; destruct H as [H1 H2].\n    apply IHr1 in H1. apply IHr2 in H2.\n    apply multi_imp_andp_intros; auto.\n  Qed.\n  \n  Lemma flatten_sound :\n    forall es rs e, (es, rs) = flatten e -> AllInContext es rs -> provable e.\n  Proof.\n    unfold flatten. intros.\n    pose proof flatten_imp_sound e.\n    rewrite H1. destruct (flatten_imp e) as [es' r].\n    inversion H. clear H. subst. apply flatten_inv_All, H0.\n  Qed.\n\n  Definition all_in_context e :=\n    let (es, rs) := flatten e in forallb (fun r => existsb (Deep.beq r) es) rs.\n\n  Lemma all_in_AllIn :\n    forall es rs e, (es, rs) = flatten e -> all_in_context e = true -> AllInContext es rs.\n  Proof.\n    intros. unfold all_in_context in H0.\n    rewrite <- H in H0. clear H. rename H0 into H.\n    rewrite forallb_forall in H.\n    unfold AllInContext. rewrite Forall_forall.\n    intros. apply H in H0. clear H.\n    apply existsb_exists in H0. destruct H0 as [y [H1 H2]].\n    apply Deep.beq_eq in H2. subst y. exact H1.\n  Qed.\n\n  Lemma all_in_provable :\n    forall e, all_in_context e = true -> provable e.\n  Proof.\n    intros. remember (flatten e) as fe.\n    destruct fe as [es rs].\n    pose proof all_in_AllIn _ _ _ Heqfe H.\n    eapply flatten_sound; eauto.\n  Qed.\nEnd DSolver.\n\nModule SolverSound.\n  Ltac ipSolver' L se :=\n    match shallowToDeep' se constr:(@nil Base.expr) with\n    | (?de, ?tbl) =>\n      let tbl' := reverse tbl in\n      let b := eval hnf in (DSolver.all_in_context de) in\n      assert (DSolver.all_in_context de = b) by reflexivity;\n      assert (@eq (@Base.expr L) (reflect se tbl' de) (se)) by reflexivity;\n      apply (@reify_sound L _ _ _ _ _ tbl' se de);\n      apply DSolver.all_in_provable;\n      match goal with\n      | [H : DSolver.all_in_context _ = true |- _] => apply H\n      end\n    end.\n\n  Ltac ipSolver :=\n    match goal with\n    | [|- @Base.provable ?L ?GammaP ?e] => ipSolver' L e\n    end.\n\n  Section Temp.\n    Context {L: Language}\n            {minL: MinimumLanguage L}\n            {andpL: AndLanguage L}\n            {GammaP: Provable L}\n            {minAX: MinimumAxiomatization L GammaP}\n            {andpAX: AndAxiomatization L GammaP}.\n    Parameter (P Q R : expr).\n    Goal (provable (impp (andp P Q) (andp Q P))).\n      ipSolver.\n    Qed.\n  End Temp.\nEnd SolverSound.\n", "meta": {"author": "QinxiangCao", "repo": "LOGIC", "sha": "d1476d57345c87447ea500b3d5ea99ee6d0f6863", "save_path": "github-repos/coq/QinxiangCao-LOGIC", "path": "github-repos/coq/QinxiangCao-LOGIC/LOGIC-d1476d57345c87447ea500b3d5ea99ee6d0f6863/PropositionalLogic/DeepEmbedded/Solver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.2839041152170704}}
{"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 Coq Require Import Logic.FunctionalExtensionality.\nFrom Coq Require Import Lia.\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 Induction_Expr.\nFrom PFPL Require Import Lemmas_AlphaEquiv.\n\nLemma alpha_equiv_renamed_1 : forall e e' x z,\n  free_vars e z = false -> all_vars e' z = false ->\n  alpha_equiv_rel e (rename e' x z) ->\n  e' = (rename e' x z).\nProof.\n  intros e e'.\n  induction e, e' using expr_pair_ind; intros.\n  - simpl. simpl in H1.\n    destruct (x0 =? x').\n    inversion H1. subst.\n    simpl in H. unfold singletonSet in H.\n    rewrite Nat.eqb_refl in H. discriminate.\n    reflexivity.\n  - simpl. simpl in H3.\n    simpl in H1. unfold unionSet in H1.\n    apply orb_false_iff in H1. destruct H1.\n    unfold removeFromSet in H4.\n    simpl in H2. unfold unionSet in H2.\n    apply orb_false_iff in H2. destruct H2.\n    unfold updateSet in H5.\n    case_eq (x' =? z); intros X'Z.\n    rewrite X'Z in H5. discriminate.\n    case_eq (x0 =? x'); intros.\n    + rewrite H6 in H3.\n      apply Nat.eqb_eq in H6. subst.\n      inversion H3. subst.\n      assert (T :=\n        H e'1 e'3\n        (same_structure_refl e'1)\n        (same_structure_refl e'3)\n        x' z H1 H2 H8\n      ).\n      rewrite <- T. reflexivity.\n    + rewrite H6 in H3. rewrite X'Z in H5.\n      inversion H3. subst.\n      assert (T :=\n        H e'1 e'3\n        (same_structure_refl e'1)\n        (same_structure_refl e'3)\n        x0 z H1 H2 H9\n      ).\n      rewrite <- T.\n      remember (max (get_fresh_var e'2) (get_fresh_var (rename e'4 x0 z))) as newX.\n      remember (max (S z) newX) as newX2.\n      assert (T2 : (z =? newX2) = false).\n      { apply Nat.eqb_neq. lia. }\n      assert (T3 : alpha_equiv_rel (rename e'2 x newX2) (rename (rename e'4 x0 z) x' newX2)).\n      {\n        assert (T3 := max_id (S z)).\n        apply H14.\n        apply fresh_var_not_in_all_vars. lia.\n        apply fresh_var_not_in_all_vars. lia.\n      }\n      assert (T4 := alpha_equiv_same_free_vars (rename e'2 x newX2) (rename (rename e'4 x0 z) x' newX2) T3).\n      assert (T5 : free_vars e'4 x0 = false).\n      {\n        case_eq (free_vars e'4 x0); intros.\n        assert (T5 := rename_the_free_var e'4 x0 z H7 H5).\n        rewrite Nat.eqb_sym in X'Z.\n        assert (T6 := rename_keeps_other_free_vars (rename e'4 x0 z) x' newX2 z X'Z).\n        assert (T6 := T6 T2).\n        rewrite <- T4 in T6.\n        rewrite T5 in T6.\n        case_eq (x =? z); intros XZ.\n        apply Nat.eqb_eq in XZ. rewrite XZ in T6.\n        assert (T7 := rename_removes_free_vars e'2 z newX2 T2).\n        rewrite T7 in T6. discriminate.\n        rewrite XZ in H4.\n        rewrite Nat.eqb_sym in XZ.\n        assert (T7 := rename_keeps_other_free_vars e'2 x newX2 z XZ T2).\n        rewrite <- T6 in T7.\n        rewrite H4 in T7. discriminate.\n        reflexivity.\n      }\n      f_equal.\n      apply rename_non_existant_free.\n      assumption.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\n  - simpl. simpl in H3.\n    inversion H3. subst.\n    simpl in H1. unfold unionSet in H1.\n    apply orb_false_iff in H1. destruct H1.\n    simpl in H2. unfold unionSet in H2.\n    apply orb_false_iff in H2. destruct H2.\n    f_equal.\n    apply (H e'1 e'3\n      (same_structure_refl e'1)\n      (same_structure_refl e'3)\n      x z H1 H2 H7\n    ).\n    apply (H0 e'2 e'4\n      (same_structure_refl e'2)\n      (same_structure_refl e'4)\n      x z H4 H5 H9\n    ).\n  - simpl. simpl in H3.\n    inversion H3. subst.\n    simpl in H1. unfold unionSet in H1.\n    apply orb_false_iff in H1. destruct H1.\n    simpl in H2. unfold unionSet in H2.\n    apply orb_false_iff in H2. destruct H2.\n    f_equal.\n    apply (H e'1 e'3\n      (same_structure_refl e'1)\n      (same_structure_refl e'3)\n      x z H1 H2 H7\n    ).\n    apply (H0 e'2 e'4\n      (same_structure_refl e'2)\n      (same_structure_refl e'4)\n      x z H4 H5 H9\n    ).\n  - simpl. simpl in H3.\n    inversion H3. subst.\n    simpl in H1. unfold unionSet in H1.\n    apply orb_false_iff in H1. destruct H1.\n    simpl in H2. unfold unionSet in H2.\n    apply orb_false_iff in H2. destruct H2.\n    f_equal.\n    apply (H e'1 e'3\n      (same_structure_refl e'1)\n      (same_structure_refl e'3)\n      x z H1 H2 H7\n    ).\n    apply (H0 e'2 e'4\n      (same_structure_refl e'2)\n      (same_structure_refl e'4)\n      x z H4 H5 H9\n    ).\n  - simpl. simpl in H2.\n    inversion H2. subst.\n    simpl in H0.\n    simpl in H1.\n    f_equal.\n    apply (H e'1 e'2\n      (same_structure_refl e'1)\n      (same_structure_refl e'2)\n      x z H0 H1 H5\n    ).\n  - destruct e'1.\n    all: destruct e'2.\n    all: simpl in H; try contradiction.\n    all: simpl in H2.\n    all: inversion H2; subst.\n    all: destruct (x =? x0).\n    all: inversion H2.\n    all: destruct (x =? x1).\n    all: inversion H2.\nQed.\n\nLemma complex : forall e e' x x' x'' z,\n  all_vars e z = false ->\n  all_vars e' z = false ->\n  (x' =? z) = false ->\n  (x'' =? x') = false ->\n  (forall newX : nat,\n    all_vars e newX = false ->\n    all_vars (rename e' x'' z) newX = false ->\n    alpha_equiv_rel (rename e x newX) (rename (rename e' x'' z) x' newX)\n  ) ->\n  free_vars e' x'' = false.\nProof.\n  intros.\n  case_eq (x'' =? z); intros X''Z.\n\n  apply Nat.eqb_eq in X''Z. subst x''.\n  apply not_in_expr_not_free; assumption.\n\n  case_eq (x' =? z); intro X'Z.\n  rewrite X'Z in H1. symmetry in H1.\n  apply Nat.eqb_eq in X'Z. subst.\n  discriminate.\n\n  remember (max\n    (max (get_fresh_var e) (get_fresh_var e'))\n    (max (max (S x'') (S 0)) (max (S z) (S z)))\n  ) as newX.\n  assert (T := complex_max e e' x'' 0 z z newX HeqnewX).\n  destruct T as [T' [_ [T'' [_ [T''' T'''']]]]].\n  assert (T3 : free_vars (rename e x newX) z = false). {\n    case_eq (x =? z); intros.\n    apply Nat.eqb_eq in H4. rewrite H4.\n    apply rename_removes_free_vars.\n    assumption.\n    rewrite Nat.eqb_sym in H4.\n    assert (T3 := rename_keeps_other_free_vars e x newX z H4 T'').\n    rewrite <- T3. apply not_in_expr_not_free. assumption.\n  }\n  assert (T4 : all_vars (rename e' x' newX) z = false). {\n    rewrite Nat.eqb_sym in X'Z.\n    assert (T4 := rename_keeps_other_vars e' x' newX z X'Z T'').\n    rewrite H0 in T4. symmetry. assumption.\n  }\n  assert (T6 : all_vars (rename e' x'' newX) z = false). {\n    case_eq (x'' =? z); intros.\n    apply Nat.eqb_eq in H4. rewrite H4.\n    assert (T6 := rename_non_existant e' z newX H0).\n    rewrite <- T6. assumption.\n    rewrite Nat.eqb_sym in H4.\n    assert (T6 := rename_keeps_other_vars e' x'' newX z H4 T'').\n    rewrite H0 in T6. symmetry. assumption.\n  }\n  assert (T8 : all_vars (rename e' x'' z) newX = false). {\n    rewrite Nat.eqb_sym in T'.\n    rewrite Nat.eqb_sym in T''.\n    assert (T8 := rename_keeps_other_vars e' x'' z newX T' T'').\n    rewrite <- T8.\n    assumption.\n  }\n  assert (T9 := H3 newX T''' T8).\n  assert (C : (rename (rename e' x'' z) x' newX) = (rename (rename e' x' newX) x'' z)).\n  {\n    apply rename_commu. assumption.\n    assumption. rewrite Nat.eqb_sym.\n    assumption. assumption.\n  }\n  assert (T10 := T9).\n  rewrite C in T10.\n  assert (T11 := alpha_equiv_renamed_1\n    (rename e x newX)\n    (rename e' x' newX)\n    x'' z T3 T4 T10\n  ).\n  assert (T12 := rename_non_existant_free_2\n    (rename e' x' newX)\n    x'' z X''Z T11\n  ).\n  rewrite X'Z in H1. symmetry in H1.\n  assert (T13 := rename_keeps_other_free_vars e' x' newX x'' H2 T').\n  rewrite <- T13 in T12.\n  assumption.\nQed.\n\nLemma alpha_equiv_renamed : forall e e' x x' z z',\n  all_vars e z = false -> all_vars e' z = false ->\n  all_vars e z' = false -> all_vars e' z' = false ->\n  alpha_equiv_rel (rename e x z) (rename e' x' z) ->\n  alpha_equiv_rel (rename e x z') (rename e' x' z').\nProof.\n  intros e e'.\n  induction e, e' using expr_pair_ind;\n  intros y y' z z' C1 C2 C3 C4 A1; simpl in A1; simpl.\n  - case_eq (y =? x); case_eq (y' =? x'); intros X X';\n    rewrite X in A1; rewrite X' in A1.\n    constructor.\n    apply Nat.eqb_eq in X'. inversion A1. subst.\n    simpl in C2. unfold singletonSet in C2.\n    rewrite Nat.eqb_refl in C2. discriminate.\n    apply Nat.eqb_eq in X. inversion A1. subst.\n    simpl in C1. unfold singletonSet in C1.\n    rewrite Nat.eqb_refl in C1. discriminate.\n    assumption.\n  - simpl in C1. unfold unionSet in C1.\n    rewrite orb_false_iff in C1. destruct C1 as [C1 C1'].\n    simpl in C2. unfold unionSet in C2.\n    rewrite orb_false_iff in C2. destruct C2 as [C2 C2'].\n    simpl in C3. unfold unionSet in C3.\n    rewrite orb_false_iff in C3. destruct C3 as [C3 C3'].\n    simpl in C4. unfold unionSet in C4.\n    rewrite orb_false_iff in C4. destruct C4 as [C4 C4'].\n    unfold updateSet in C1'.\n    case_eq (x =? z); intro XZ; rewrite XZ in C1'. discriminate.\n    unfold updateSet in C2'.\n    case_eq (x' =? z); intro X'Z; rewrite X'Z in C2'. discriminate.\n    unfold updateSet in C3'.\n    case_eq (x =? z'); intro XZ'; rewrite XZ' in C3'. discriminate.\n    unfold updateSet in C4'.\n    case_eq (x' =? z'); intro X'Z'; rewrite X'Z' in C4'. discriminate.\n    case_eq (y =? x); case_eq (y' =? x'); intros Y'X' YX;\n    rewrite YX in A1; rewrite Y'X' in A1.\n    + apply Nat.eqb_eq in YX. apply Nat.eqb_eq in Y'X'.\n      inversion A1. subst. constructor.\n      apply (H _ _ (same_structure_refl e'1) (same_structure_refl e'3) x x' z).\n      all: assumption.\n    + apply Nat.eqb_eq in YX.\n      inversion A1. subst. constructor.\n      apply (H _ _ (same_structure_refl e'1) (same_structure_refl e'3) x y' z).\n      all: try assumption.\n      intros.\n      assert (T := complex e'2 e'4 x x' y' z C1' C2' X'Z Y'X' H8).\n      rewrite <- (rename_non_existant_free e'4 y' z' T).\n      rewrite <- (rename_non_existant_free e'4 y' z' T) in H2.\n      rewrite <- (rename_non_existant_free e'4 y' z T) in H8.\n      apply (H8 z0 H1 H2).\n    + apply Nat.eqb_eq in Y'X'.\n      inversion A1. subst. constructor.\n      apply (H _ _ (same_structure_refl e'1) (same_structure_refl e'3) y x' z).\n      all: try assumption.\n      assert (H8' : (forall z0 : nat,\n        all_vars e'4 z0 = false ->\n        all_vars (rename e'2 y z) z0 = false ->\n        alpha_equiv_rel (rename e'4 x' z0) (rename (rename e'2 y z) x z0))\n      ). {\n        intros. apply alpha_equiv_sym. apply H8; assumption.\n      }\n      intros.\n      apply alpha_equiv_sym.\n      assert (T := complex e'4 e'2 x' x y z C2' C1' XZ YX H8').\n      rewrite <- (rename_non_existant_free e'2 y z' T).\n      rewrite <- (rename_non_existant_free e'2 y z' T) in H1.\n      rewrite <- (rename_non_existant_free e'2 y z T) in H8'.\n      apply (H8' z0 H2 H1).\n    + inversion A1. subst. constructor.\n      apply (H _ _ (same_structure_refl e'1) (same_structure_refl e'3) y y' z).\n      all: try assumption.\n      intros.\n      remember (max (max\n        (max (get_fresh_var (rename e'2 y z)) (get_fresh_var (rename e'4 y' z)))\n        (max (get_fresh_var (rename e'2 y z')) (get_fresh_var (rename e'4 y' z')))\n      ) (max (max (S y) (S y')) (max (S z) (S z')))) as newX.\n      assert (T1 := complex_max_2\n        (rename e'2 y z) (rename e'4 y' z)\n        (rename e'2 y z') (rename e'4 y' z')\n        y y' z z' newX HeqnewX\n      ).\n      destruct T1 as [YnewX [Y'newX [ZnewX [Z'newX [T1 [T2 [T3 T4]]]]]]].\n      clear HeqnewX.\n      assert (T5 := H8 newX T1 T2).\n      rewrite Nat.eqb_sym in XZ.\n      rewrite (rename_commu e'2 y z x newX YX YnewX XZ ZnewX) in T5.\n      rewrite Nat.eqb_sym in X'Z.\n      rewrite (rename_commu e'4 y' z x' newX Y'X' Y'newX X'Z ZnewX) in T5.\n      assert (T6 : all_vars (rename e'2 x newX) z = false). {\n        assert (T6 := rename_keeps_other_vars e'2 x newX z XZ ZnewX).\n        rewrite <- T6. assumption.\n      }\n      assert (T7 : all_vars (rename e'4 x' newX) z = false). {\n        assert (T7 := rename_keeps_other_vars e'4 x' newX z X'Z ZnewX).\n        rewrite <- T7. assumption.\n      }\n      assert (T8 : all_vars (rename e'2 x newX) z' = false). {\n        rewrite Nat.eqb_sym in XZ'.\n        assert (T8 := rename_keeps_other_vars e'2 x newX z' XZ' Z'newX).\n        rewrite <- T8. assumption.\n      }\n      assert (T9 : all_vars (rename e'4 x' newX) z' = false). {\n        rewrite Nat.eqb_sym in X'Z'.\n        assert (T9 := rename_keeps_other_vars e'4 x' newX z' X'Z' Z'newX).\n        rewrite <- T9. assumption.\n      }\n      assert (T10 := H0 (rename e'2 x newX) (rename e'4 x' newX)\n        (rename_keeps_structure e'2 x newX)\n        (rename_keeps_structure e'4 x' newX)\n        y y' z z' T6 T7 T8 T9 T5\n      ).\n      rewrite Nat.eqb_sym in YX.\n      rewrite Nat.eqb_sym in YnewX.\n      rewrite Nat.eqb_sym in Z'newX.\n      rewrite (rename_commu e'2 x newX y z' YX XZ' YnewX Z'newX) in T10.\n      rewrite Nat.eqb_sym in Y'X'.\n      rewrite Nat.eqb_sym in Y'newX.\n      rewrite (rename_commu e'4 x' newX y' z' Y'X' X'Z' Y'newX Z'newX) in T10.\n      apply (H0\n        (rename e'2 y z')\n        (rename e'4 y' z')\n        (rename_keeps_structure e'2 y z')\n        (rename_keeps_structure e'4 y' z')\n        x x' newX z0 T3 T4 H1 H2 T10\n      ).\n  - assumption.\n  - assumption.\n  - simpl in C1. unfold unionSet in C1.\n    rewrite orb_false_iff in C1. destruct C1 as [C1 C1'].\n    simpl in C2. unfold unionSet in C2.\n    rewrite orb_false_iff in C2. destruct C2 as [C2 C2'].\n    simpl in C3. unfold unionSet in C3.\n    rewrite orb_false_iff in C3. destruct C3 as [C3 C3'].\n    simpl in C4. unfold unionSet in C4.\n    rewrite orb_false_iff in C4. destruct C4 as [C4 C4'].\n    inversion A1. subst.\n    constructor.\n    apply (H e'1 e'3 (same_structure_refl e'1) (same_structure_refl e'3) y y' z).\n    all: try assumption.\n    apply (H0 e'2 e'4 (same_structure_refl e'2) (same_structure_refl e'4) y y' z).\n    all: assumption.\n  - simpl in C1. unfold unionSet in C1.\n    rewrite orb_false_iff in C1. destruct C1 as [C1 C1'].\n    simpl in C2. unfold unionSet in C2.\n    rewrite orb_false_iff in C2. destruct C2 as [C2 C2'].\n    simpl in C3. unfold unionSet in C3.\n    rewrite orb_false_iff in C3. destruct C3 as [C3 C3'].\n    simpl in C4. unfold unionSet in C4.\n    rewrite orb_false_iff in C4. destruct C4 as [C4 C4'].\n    inversion A1. subst.\n    constructor.\n    apply (H e'1 e'3 (same_structure_refl e'1) (same_structure_refl e'3) y y' z).\n    all: try assumption.\n    apply (H0 e'2 e'4 (same_structure_refl e'2) (same_structure_refl e'4) y y' z).\n    all: assumption.\n  - simpl in C1. unfold unionSet in C1.\n    rewrite orb_false_iff in C1. destruct C1 as [C1 C1'].\n    simpl in C2. unfold unionSet in C2.\n    rewrite orb_false_iff in C2. destruct C2 as [C2 C2'].\n    simpl in C3. unfold unionSet in C3.\n    rewrite orb_false_iff in C3. destruct C3 as [C3 C3'].\n    simpl in C4. unfold unionSet in C4.\n    rewrite orb_false_iff in C4. destruct C4 as [C4 C4'].\n    inversion A1. subst.\n    constructor.\n    apply (H e'1 e'3 (same_structure_refl e'1) (same_structure_refl e'3) y y' z).\n    all: try assumption.\n    apply (H0 e'2 e'4 (same_structure_refl e'2) (same_structure_refl e'4) y y' z).\n    all: assumption.\n  - simpl in C1.\n    simpl in C2.\n    simpl in C3.\n    simpl in C4.\n    inversion A1. subst.\n    constructor.\n    apply (H e'1 e'2 (same_structure_refl e'1) (same_structure_refl e'2) y y' z).\n    all: assumption.\n  - assert (T := diff_constructor_not_alpha e'1 e'2 H\n      (rename e'1 y z) (rename e'2 y' z)\n      (rename_keeps_structure e'1 y z)\n      (rename_keeps_structure e'2 y' z)\n      A1\n    ).\n    contradiction.\nQed.\n\nLemma rename_keeps_alpha_equiv : forall e e' x z,\n  all_vars e z = false -> all_vars e' z = false ->\n  alpha_equiv_rel e e' ->\n  alpha_equiv_rel (rename e x z) (rename e' x z).\nProof.\n  intros.\n  generalize dependent H0.\n  generalize dependent H.\n  generalize dependent z.\n  generalize dependent x.\n  induction H1; intros; simpl.\n  - apply alpha_equiv_refl.\n  - simpl in H2. unfold unionSet in H2.\n    apply orb_false_iff in H2. destruct H2 as [H2 H2'].\n    unfold updateSet in H2'. case_eq (x =? z); intro XZ.\n    all: rewrite XZ in H2'. discriminate.\n    simpl in H3. unfold unionSet in H3.\n    apply orb_false_iff in H3. destruct H3 as [H3 H3'].\n    unfold updateSet in H3'. case_eq (x' =? z); intro X'Z.\n    all: rewrite X'Z in H3'. discriminate.\n    case_eq (x0 =? x); intro X0X;\n    case_eq (x0 =? x'); intro X0X'.\n    + apply Nat.eqb_eq in X0X. apply Nat.eqb_eq in X0X'. subst.\n      apply alpha_equiv_rel_let.\n      apply IHalpha_equiv_rel; assumption.\n      assumption.\n    + apply Nat.eqb_eq in X0X. subst.\n      apply alpha_equiv_rel_let.\n      apply IHalpha_equiv_rel; assumption.\n      intros.\n      remember (max\n        (max\n          (max (get_fresh_var e2) (get_fresh_var e2'))\n          (max (get_fresh_var e2) (get_fresh_var (rename e2' x z)))\n        )\n        (max (max (S x) (S x')) (max (S z) (S z0)))) as newX.\n      assert (M := complex_max_2 e2 e2' e2 (rename e2' x z)\n        x x' z z0 newX HeqnewX\n      ).\n      destruct M as [M1 [M2 [M3 [M4 [M5 [M6 [M7 M8]]]]]]].\n      apply (alpha_equiv_renamed e2 (rename e2' x z)\n        x x' newX z0 M5 M8 H4 H5\n      ).\n      rewrite Nat.eqb_sym in X'Z.\n      rewrite (rename_commu _ _ _ _ _ X0X' M1 X'Z M3).\n      rewrite (rename_twice e2 x newX z M1 M5).\n      apply H0; try assumption.\n      apply rename_does_not_add_new_var.\n      rewrite Nat.eqb_sym. assumption. assumption.\n      apply rename_does_not_add_new_var.\n      rewrite Nat.eqb_sym. assumption. assumption.\n    + apply Nat.eqb_eq in X0X'. subst.\n      apply alpha_equiv_rel_let.\n      apply IHalpha_equiv_rel; assumption.\n      intros.\n      remember (max\n        (max\n          (max (get_fresh_var e2) (get_fresh_var e2'))\n          (max (get_fresh_var (rename e2 x' z)) (get_fresh_var e2'))\n        )\n        (max (max (S x) (S x')) (max (S z) (S z0)))) as newX.\n      assert (M := complex_max_2 e2 e2' (rename e2 x' z) e2'\n        x x' z z0 newX HeqnewX\n      ).\n      destruct M as [M1 [M2 [M3 [M4 [M5 [M6 [M7 M8]]]]]]].\n      apply (alpha_equiv_renamed (rename e2 x' z) e2'\n        x x' newX z0 M7 M8 H4 H5\n      ).\n      rewrite Nat.eqb_sym in XZ.\n      rewrite (rename_commu _ _ _ _ _ X0X M2 XZ M3).\n      rewrite (rename_twice e2' x' newX z M2 M6).\n      apply H0; try assumption.\n      apply rename_does_not_add_new_var.\n      rewrite Nat.eqb_sym. assumption. assumption.\n      apply rename_does_not_add_new_var.\n      rewrite Nat.eqb_sym. assumption. assumption.\n    + apply alpha_equiv_rel_let.\n      apply IHalpha_equiv_rel; assumption.\n      intros.\n      remember (max\n        (max\n          (max (get_fresh_var e2) (get_fresh_var e2'))\n          (max (get_fresh_var (rename e2 x0 z)) (get_fresh_var (rename e2' x0 z)))\n        )\n        (max (max (S x0) (S x')) (max (S z) (S z0)))) as newX.\n      assert (M := complex_max_2 e2 e2' (rename e2 x0 z) (rename e2' x0 z)\n        x0 x' z z0 newX HeqnewX\n      ).\n      destruct M as [M1 [M2 [M3 [M4 [M5 [M6 [M7 M8]]]]]]].\n      apply (alpha_equiv_renamed (rename e2 x0 z) (rename e2' x0 z)\n        x x' newX z0 M7 M8 H4 H5\n      ).\n      rewrite Nat.eqb_sym in XZ.\n      rewrite (rename_commu e2 _ _ _ _ X0X M1 XZ M3).\n      rewrite Nat.eqb_sym in X'Z.\n      rewrite (rename_commu e2' _ _ _ _ X0X' M1 X'Z M3).\n      apply H0; try assumption.\n      apply rename_does_not_add_new_var.\n      rewrite Nat.eqb_sym. assumption. assumption.\n      apply rename_does_not_add_new_var.\n      rewrite Nat.eqb_sym. assumption. assumption.\n  - apply alpha_equiv_rel_num.\n  - apply alpha_equiv_rel_str. assumption.\n  - simpl in H. unfold unionSet in H.\n    apply orb_false_iff in H. destruct H as [H H'].\n    simpl in H0. unfold unionSet in H0.\n    apply orb_false_iff in H0. destruct H0 as [H0 H0'].\n    apply alpha_equiv_rel_plus; [apply IHalpha_equiv_rel1 | apply IHalpha_equiv_rel2].\n    all: assumption.\n  - simpl in H. unfold unionSet in H.\n    apply orb_false_iff in H. destruct H as [H H'].\n    simpl in H0. unfold unionSet in H0.\n    apply orb_false_iff in H0. destruct H0 as [H0 H0'].\n    apply alpha_equiv_rel_times; [apply IHalpha_equiv_rel1 | apply IHalpha_equiv_rel2].\n    all: assumption.\n  - simpl in H. unfold unionSet in H.\n    apply orb_false_iff in H. destruct H as [H H'].\n    simpl in H0. unfold unionSet in H0.\n    apply orb_false_iff in H0. destruct H0 as [H0 H0'].\n    apply alpha_equiv_rel_cat; [apply IHalpha_equiv_rel1 | apply IHalpha_equiv_rel2].\n    all: assumption.\n  - simpl in H. simpl in H0.\n    apply alpha_equiv_rel_len. apply IHalpha_equiv_rel.\n    all: assumption.\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_AlphaEquiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.28384065387937446}}
{"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 library.\nRequire Export alphaeq.\nRequire Export computation3.\nRequire Export list_tacs.\nRequire Export substitution2.\nRequire Export alphaeq2.\nRequire Export atoms2.\n\n\nDefinition soswapping := list ((NVar # NVar) # nat).\n\nDefinition onesoswapvar (a : NVar) (b : NVar) (n : nat) (v : sovar_sig) : sovar_sig :=\n  if sovar_sig_dec v (a,n) then (b,n)\n  else if sovar_sig_dec v (b,n) then (a,n)\n       else v.\n\nFixpoint soswapvar (l : soswapping) (v : sovar_sig) : sovar_sig :=\n  match l with\n    | [] => v\n    | ((a,b),n) :: rest => soswapvar rest (onesoswapvar a b n v)\n  end.\n\nDefinition soswapbvars (l : soswapping) (vs : list NVar) :=\n  map (fun v => sovar2var (soswapvar l (var2sovar v))) vs.\n\nFixpoint soswap {p} (l : soswapping) (t : @SOTerm p) :=\n  match t with\n    | sovar v ts => sovar (sovar2var (soswapvar l (v,length ts))) (map (soswap l) ts)\n    | soterm op bts => soterm op (map (soswapbt l) bts)\n  end\nwith soswapbt {p} (l : soswapping) (bt : SOBTerm) :=\n  match bt with\n    | sobterm vs t => sobterm (soswapbvars l vs) (soswap l t)\n  end.\n\n\nFixpoint mk_soswapping (vs1 : list sovar_sig) (vs2 : list NVar) : soswapping :=\n  match vs1, vs2 with\n    | [],[] => []\n    | (v1,n) :: vs1, v2 :: vs2 => ((v1,v2),n) :: mk_soswapping vs1 vs2\n    | _, _ => []\n  end.\n\nDefinition matching_sovars (vars1 vars2 : list sovar_sig) :=\n  map (fun v => snd v) vars1 = map (fun v => snd v) vars2.\n\nLemma matching_sovars_sym :\n  forall vars1 vars2,\n    matching_sovars vars1 vars2 -> matching_sovars vars2 vars1.\nProof.\n  unfold matching_sovars; introv e; rw e; auto.\nQed.\n\nInductive alpha_eq_entry {o} : @library_entry o -> @library_entry o -> Type :=\n| aeq_lib_entry :\n    forall vs\n           opabs\n           vars1 rhs1 correct1\n           vars2 rhs2 correct2,\n      length vs = length vars1\n      -> length vs = length vars2\n      -> disjoint vs (sovars2vars vars1 ++ sovars2vars vars2 ++ all_fo_vars rhs1 ++ all_fo_vars rhs2)\n      -> no_repeats vs\n      -> matching_sovars vars1 vars2\n      -> so_alphaeq (soswap (mk_soswapping vars1 vs) rhs1)\n                    (soswap (mk_soswapping vars2 vs) rhs2)\n      -> alpha_eq_entry (lib_abs opabs vars1 rhs1 correct1)\n                        (lib_abs opabs vars2 rhs2 correct2).\n\nInductive alpha_eq_lib {o} : @library o -> @library o -> Type :=\n| aeq_lib_nil : alpha_eq_lib [] []\n| aeq_lib_cons :\n    forall entry1 entry2 lib1 lib2,\n      alpha_eq_entry entry1 entry2\n      -> alpha_eq_lib lib1 lib2\n      -> alpha_eq_lib (entry1 :: lib1) (entry2 :: lib2).\n\nLemma dom_sub_var_ren {o} :\n  forall vs1 vs2,\n    length vs1 = length vs2\n    -> dom_sub (@var_ren o vs1 vs2) = vs1.\nProof.\n  induction vs1; introv len; auto.\n  destruct vs2; cpx.\n  simpl; apply eq_cons; auto.\n  apply IHvs1; auto.\nQed.\n\nLemma matching_bterms_change_vs {o} :\n  forall vars2 vars1 (bs : list (@BTerm o)),\n    matching_bterms vars1 bs\n    -> matching_sovars vars1 vars2\n    -> matching_bterms vars2 bs.\nProof.\n  introv m e; allunfold @matching_bterms.\n  rw <- m; auto.\nQed.\n\nLemma matching_entry_change_vs {o} :\n  forall vars2 oa1 oa2 vars1 (bs : list (@BTerm o)),\n    matching_entry oa1 oa2 vars1 bs\n    -> matching_sovars vars1 vars2\n    -> matching_entry oa1 oa2 vars2 bs.\nProof.\n  introv m e; allunfold @matching_entry; repnd; dands; auto.\n  eapply matching_bterms_change_vs; eauto.\nQed.\n\nLemma found_entry_alpha_eq_lib {o} :\n  forall (lib1 lib2 : @library o) oa1 bs oa2 vars rhs correct,\n    found_entry lib1 oa1 bs oa2 vars rhs correct\n    -> alpha_eq_lib lib1 lib2\n    -> {vars2 : list sovar_sig\n        & {rhs2 : SOTerm\n        & {correct2 : correct_abs oa2 vars2 rhs2\n        & {vs : list NVar\n        & found_entry lib2 oa1 bs oa2 vars2 rhs2 correct2\n        # length vs = length vars\n        # length vs = length vars2\n        # disjoint vs (sovars2vars vars ++ sovars2vars vars2 ++ all_fo_vars rhs ++ all_fo_vars rhs2)\n        # no_repeats vs\n        # matching_sovars vars vars2\n        # so_alphaeq (soswap (mk_soswapping vars vs) rhs)\n                     (soswap (mk_soswapping vars2 vs) rhs2) }}}}.\nProof.\n  induction lib1; introv fe aeq.\n  - inversion fe.\n  - inversion aeq as [|? ? ? ? aeqe aeql]; subst; clear aeq.\n    allunfold @found_entry; allsimpl.\n    destruct a.\n    destruct (matching_entry_deq oa1 opabs vars0 bs).\n    + inversion fe; subst.\n      assert (correct0 = correct) by eauto with pi; subst; GC.\n      inversion aeqe as [? ? ? ? ? ? ? ? len1 len2 disj norep msv aeqb]; subst; GC.\n      exists vars2 rhs2 correct2 vs; dands; auto.\n      destruct (matching_entry_deq oa1 oa2 vars2 bs); auto.\n      apply not_matching_entry_iff in n.\n      apply (matching_entry_change_vs vars2) in m; tcsp.\n    + eapply IHlib1 in fe; eauto.\n      exrepnd.\n      inversion aeqe as [? ? ? ? ? ? ? ? len1 len2 disj norep msv aeqb]; subst; GC; clear aeqe.\n      exists vars2 rhs2 correct2 vs; dands; auto.\n      destruct (matching_entry_deq oa1 opabs vars3 bs); auto.\n      apply not_matching_entry_iff in n.\n      apply (matching_entry_change_vs vars0) in m; tcsp.\n      apply matching_sovars_sym; auto.\nQed.\n\nLemma matching_bterms_implies_length {o} :\n  forall vars (bs : list (@BTerm o)),\n    matching_bterms vars bs -> length vars = length bs.\nProof.\n   unfold matching_bterms; introv e.\n   apply map_eq_length_eq in e; auto.\nQed.\n\nInductive alphaeq_sosub_range {o} : @SOSub o -> @SOSub o -> Type :=\n  | aeqsosub_nil : alphaeq_sosub_range [] []\n  | aeqsosub_cons :\n      forall v1 v2 sk1 sk2 sub1 sub2,\n        alphaeq_sk sk1 sk2\n        -> alphaeq_sosub_range sub1 sub2\n        -> alphaeq_sosub_range ((v1,sk1) :: sub1) ((v2,sk2) :: sub2).\nHint Constructors alphaeq_sosub_range.\n\nLemma onesoswapvar_eq :\n  forall v1 v2 n,\n    onesoswapvar v1 v2 n (v1,n) = (v2,n).\nProof.\n  introv; unfold onesoswapvar; boolvar; cpx.\nQed.\n\nLemma onesoswapvar_not_in :\n  forall v1 v2 v n m,\n    v1 <> v\n    -> v2 <> v\n    -> onesoswapvar v1 v2 n (v,m) = (v,m).\nProof.\n  introv; unfold onesoswapvar; boolvar; cpx.\nQed.\n\nLemma onesoswapvar_not_in2 :\n  forall v1 v2 v n,\n    v <> (v1,n)\n    -> v <> (v2,n)\n    -> onesoswapvar v1 v2 n v = v.\nProof.\n  introv; unfold onesoswapvar; boolvar; cpx.\nQed.\n\nLemma soswapvar_not_in :\n  forall (vs1 : list sovar_sig) (vs2 : list NVar) v n,\n    !LIn v (sovars2vars vs1)\n    -> !LIn v vs2\n    -> soswapvar (mk_soswapping vs1 vs2) (v,n) = (v,n).\nProof.\n  induction vs1; destruct vs2; introv ni1 ni2; allsimpl; tcsp; GC.\n  - destruct a; simpl; auto.\n  - destruct a; allrw not_over_or; repnd; allsimpl.\n    rw onesoswapvar_not_in; auto.\nQed.\n\nLemma soswapvar_not_in2 :\n  forall (vs1 : list sovar_sig) (vs2 : list NVar) v,\n    !LIn v vs1\n    -> !LIn (sovar2var v) vs2\n    -> soswapvar (mk_soswapping vs1 vs2) v = v.\nProof.\n  induction vs1; destruct vs2; introv ni1 ni2; allsimpl; tcsp; GC.\n  - destruct a; simpl; auto.\n  - destruct a; allrw not_over_or; repnd; allsimpl.\n    destruct v; allsimpl.\n    unfold onesoswapvar; boolvar; cpx.\nQed.\n\nLemma soswapvar_in :\n  forall vs1 vs2 v,\n    LIn v vs1\n    -> length vs1 = length vs2\n    -> disjoint vs2 (sovars2vars vs1)\n    -> no_repeats vs2\n    -> LIn (sovar2var (soswapvar (mk_soswapping vs1 vs2) v)) vs2.\nProof.\n  induction vs1; destruct vs2; introv i len disj norep; allsimpl; tcsp.\n  destruct a; allsimpl; cpx.\n  allrw disjoint_cons_l; allrw disjoint_cons_r; repnd.\n  allrw no_repeats_cons; repnd.\n  allsimpl; allrw not_over_or; repnd.\n  dorn i; subst.\n  - left.\n    rw onesoswapvar_eq.\n    rw soswapvar_not_in; simpl; sp.\n  - unfold onesoswapvar; destruct v; boolvar; cpx.\n    + left; rw soswapvar_not_in; auto.\n    + destruct (in_deq sovar_sig sovar_sig_dec (n0,n1) vs1) as [k|k].\n      * right; apply IHvs1; auto.\n      * provefalse; destruct disj.\n        rw in_sovars2vars; eexists; eauto.\nQed.\n\nLemma length_sodom {o} :\n  forall (sub : @SOSub o),\n    length (sodom sub) = length sub.\nProof.\n  induction sub; allsimpl; sp.\nQed.\n\nLemma alphaeq_sosub_range_implies_eq_length {o} :\n  forall (sub1 sub2 : @SOSub o),\n    alphaeq_sosub_range sub1 sub2 -> length sub1 = length sub2.\nProof.\n  induction sub1; destruct sub2; introv aeq; allsimpl; auto;\n  inversion aeq; subst; sp.\nQed.\n\nLemma sosub_find_some_eq_sovar2var {o} :\n  forall (sub1 sub2 : @SOSub o) v1 v2 sk1 sk2 vs,\n    !LIn (sovar2var v1) vs\n    -> !LIn (sovar2var v2) vs\n    -> disjoint vs (so_dom sub1)\n    -> disjoint vs (so_dom sub2)\n    -> length vs = length sub1\n    -> no_repeats vs\n    -> sosub_find sub1 v1 = Some sk1\n    -> sosub_find sub2 v2 = Some sk2\n    -> sovar2var (soswapvar (mk_soswapping (sodom sub1) vs) v1)\n       = sovar2var (soswapvar (mk_soswapping (sodom sub2) vs) v2)\n    -> alphaeq_sosub_range sub1 sub2\n    -> alphaeq_sk sk1 sk2.\nProof.\n  induction sub1; destruct sub2, vs;\n  introv ni1 ni2 disj1 disj2 len norep f1 f2 e aeq;\n  allsimpl; ginv; GC.\n  destruct a, p; destruct s, s0.\n  boolvar; allsimpl; subst; 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  inversion aeq as [|? ? ? ? ? ? aeqsk aeqsub]; subst; auto; clear aeq;\n  allrw onesoswapvar_eq.\n\n  - provefalse.\n\n    rw (soswapvar_not_in (sodom sub2) vs n) in e; auto;\n    [|rw @sovars2vars_sodom_is_so_dom; complete auto]; allsimpl.\n\n    rw onesoswapvar_not_in2 in e; auto;\n    [|destruct v1 as [v m]; allsimpl; intro k; inversion k; subst v; complete sp].\n\n    pose proof (soswapvar_in (sodom sub1) vs v1) as h.\n    destruct sk1, v1.\n    apply sosub_find_some in f1; repnd.\n    eapply in_sodom_if in f0; eauto;[].\n    rewrite f1 in f0.\n    repeat (autodimp h hyp);\n      [ rw @length_sodom; auto\n      | rw @sovars2vars_sodom_is_so_dom; auto\n      |].\n    rw e in h; sp.\n\n  - provefalse.\n\n    rw (soswapvar_not_in (sodom sub1) vs n) in e; auto;\n    [|rw @sovars2vars_sodom_is_so_dom; complete auto]; allsimpl.\n\n    rw onesoswapvar_not_in2 in e; auto;\n    [|destruct v2 as [v m]; allsimpl; intro k; inversion k; subst v; complete sp].\n\n    applydup @alphaeq_sosub_range_implies_eq_length in aeqsub.\n\n    pose proof (soswapvar_in (sodom sub2) vs v2) as h.\n    destruct sk2, v2.\n    apply sosub_find_some in f2; repnd.\n    eapply in_sodom_if in f0; eauto;[].\n    rewrite f2 in f0.\n    repeat (autodimp h hyp);\n      [ rw @length_sodom; auto; omega\n      | rw @sovars2vars_sodom_is_so_dom; auto\n      |].\n    rw <- e in h; sp.\n\n  - rw onesoswapvar_not_in2 in e; auto;\n    [|destruct v1 as [v m]; allsimpl; intro k; inversion k; subst v; complete sp].\n\n    rw onesoswapvar_not_in2 in e; auto;\n    [|destruct v2 as [v m]; allsimpl; intro k; inversion k; subst v; complete sp].\n\n    eapply IHsub1 in e; eauto.\nQed.\n\nLemma map_nth2 :\n  forall (A B : tuniv) d (f : A -> B) (l : list A) (n : nat) b,\n    b = f d -> nth n (map f l) b = f (nth n l d).\nProof.\n  introv e; subst.\n  apply map_nth.\nQed.\n\nLemma bin_rel_nterm_map {o} :\n  forall A (d : A) f1 f2 (l1 l2 : list A) R,\n    length l1 = length l2\n    -> (forall a1 a2, LIn (a1,a2) (combine l1 l2) -> R (f1 a1) (f2 a2))\n    -> f1 d = default_nterm\n    -> f2 d = default_nterm\n    -> @bin_rel_nterm o R (map f1 l1) (map f2 l2).\nProof.\n  introv len imp e1 e2.\n  unfold bin_rel_nterm, binrel_list.\n  allrw map_length; dands; auto.\n  introv i.\n  repeat (rewrite (map_nth2 _ _ d); auto).\n  apply imp.\n  apply in_combine_sel_iff.\n  exists n; dands; auto; try omega;\n  rw <- @nth_select1; auto; try omega.\nQed.\n\n(* !! MOVE to sovar *)\nLemma fo_bound_vars_subvars_all_fo_vars {o} :\n  forall (t : @SOTerm o),\n    subvars (fo_bound_vars t) (all_fo_vars t).\nProof.\n  soterm_ind t as [v ts ind|op bs ind] Case; introv; allsimpl.\n\n  - Case \"sovar\".\n    apply subvars_flat_map; introv i.\n    applydup ind in i.\n    apply subvars_cons_r.\n    eapply implies_subvars_flat_map_r; eauto.\n\n  - Case \"soterm\".\n    apply subvars_flat_map; introv i.\n    destruct x as [l t]; simpl.\n    eapply implies_subvars_flat_map_r; eauto; simpl.\n    apply subvars_app_lr; auto.\n    eapply ind; eauto.\nQed.\n\n(* !! MOVE to sovar *)\nHint Resolve fovars_subvars_all_fo_vars : slow.\n\nLemma disjoint_bound_vars_prop4 {o} :\n  forall (sub : @SOSub o) v vs t ts,\n    disjoint (bound_vars_sosub sub) (free_vars_sosub sub)\n    -> disjoint (bound_vars_sosub sub) (flat_map all_fo_vars ts)\n    -> LIn (v, sosk vs t) sub\n    -> (forall u, LIn u ts -> cover_so_vars u sub)\n    -> disjoint (bound_vars t) (flat_map (fun x => free_vars (sosub_aux sub x)) ts).\nProof.\n  introv disj1 disj2 insub cov.\n  eapply disjoint_bound_vars_prop3; eauto.\n  eapply subvars_disjoint_r;[|exact disj2].\n  apply subvars_flat_map; introv i.\n  eapply implies_subvars_flat_map_r; eauto with slow.\nQed.\n\nLemma sosub_find_some_none_eq_sovar2var {o} :\n  forall (sub1 sub2 : @SOSub o) vs v1 v2 sk,\n    !LIn (sovar2var v1) vs\n    -> !LIn (sovar2var v2) vs\n    -> disjoint vs (so_dom sub1)\n    -> length vs = length sub1\n    -> no_repeats vs\n    -> sosub_find sub1 v1 = Some sk\n    -> sosub_find sub2 v2 = None\n    -> sovar2var (soswapvar (mk_soswapping (sodom sub1) vs) v1)\n       = sovar2var (soswapvar (mk_soswapping (sodom sub2) vs) v2)\n    -> False.\nProof.\n  induction sub1; destruct sub2, vs;\n  introv ni1 ni2 disj len norep f1 f2 e; allsimpl; cpx;\n  allrw disjoint_cons_l; allsimpl; repnd;\n  allrw disjoint_cons_r; allsimpl; repnd;\n  allrw no_repeats_cons; repnd;\n  allrw not_over_or; repnd.\n\n  - destruct s; allsimpl; boolvar; ginv; allsimpl.\n\n    + rw onesoswapvar_eq in e.\n      rw soswapvar_not_in in e; auto.\n      rw @sovars2vars_sodom_is_so_dom; auto.\n\n    + rw onesoswapvar_not_in2 in e; auto;\n      [|destruct v1 as [v m]; allsimpl; intro k; inversion k; subst v; complete sp].\n\n      pose proof (soswapvar_in (sodom sub1) vs v1) as h.\n      destruct sk, v1.\n      apply sosub_find_some in f1; repnd.\n      eapply in_sodom_if in f0; eauto;[].\n      rewrite f1 in f0.\n      repeat (autodimp h hyp);\n        [ rw @length_sodom; auto\n        | rw @sovars2vars_sodom_is_so_dom; auto\n        |].\n      rw e in h; sp.\n\n  - destruct s, s0; allsimpl.\n    boolvar; cpx;\n    allrw onesoswapvar_eq.\n\n    + rw (soswapvar_not_in (sodom sub1) vs n) in e; auto;\n      [|rw @sovars2vars_sodom_is_so_dom; complete auto]; allsimpl.\n\n      rw onesoswapvar_not_in2 in e; auto;\n      [|destruct v2 as [v m]; allsimpl; intro k; inversion k; subst v; complete sp].\n\n      destruct v2 as [x m]; allsimpl.\n      apply sosub_find_none in f2.\n      rw soswapvar_not_in2 in e; auto.\n\n    + rw onesoswapvar_not_in2 in e; auto;\n      [|destruct v1 as [v m]; allsimpl; intro k; inversion k; subst v; complete sp].\n\n      rw onesoswapvar_not_in2 in e; auto;\n      [|destruct v2 as [v m]; allsimpl; intro k; inversion k; subst v; complete sp].\n\n      destruct v1 as [x1 m1].\n      destruct v2 as [x2 m2].\n      allsimpl.\n      destruct sk as [lv t].\n      apply sosub_find_some in f1; repnd.\n      apply sosub_find_none in f2.\n\n      pose proof (soswapvar_in (sodom sub1) vs (x1,m1)) as h.\n      eapply in_sodom_if in f0; eauto;[].\n      rewrite f1 in f0.\n      repeat (autodimp h hyp);\n        [ rw @length_sodom; auto\n        | rw @sovars2vars_sodom_is_so_dom; auto\n        |].\n      rw e in h; clear e.\n\n      rw soswapvar_not_in2 in h; auto.\nQed.\n\nLemma sosub_find_none_eq_sovar2var {o} :\n  forall (sub1 sub2 : @SOSub o) vs v1 v2,\n    !LIn (sovar2var v1) vs\n    -> !LIn (sovar2var v2) vs\n    -> length vs = length sub1\n    -> sosub_find sub1 v1 = None\n    -> sosub_find sub2 v2 = None\n    -> sovar2var (soswapvar (mk_soswapping (sodom sub1) vs) v1)\n       = sovar2var (soswapvar (mk_soswapping (sodom sub2) vs) v2)\n    -> sovar2var v1 = sovar2var v2.\nProof.\n  induction sub1; destruct sub2, vs;\n  introv ni1 ni2 len f1 f2 e; allsimpl; cpx; GC.\n\n  - destruct p; destruct s; allsimpl; auto.\n\n  - destruct s; allsimpl.\n    allrw not_over_or; repnd.\n    boolvar; ginv.\n    rw onesoswapvar_not_in2 in e; auto;\n    [|destruct v1 as [v m]; allsimpl; intro k; inversion k; subst v; complete sp].\n    destruct v1 as [x1 m1]; allsimpl.\n    apply sosub_find_none in f1.\n    rw soswapvar_not_in2 in e; auto.\n\n  - destruct s, s0; allsimpl.\n    allrw not_over_or; repnd.\n    boolvar; ginv.\n    destruct v1 as [x1 m1].\n    destruct v2 as [x2 m2].\n    allsimpl.\n\n    apply sosub_find_none in f1.\n    apply sosub_find_none in f2.\n\n    rw onesoswapvar_not_in2 in e; auto;\n    [|intro k; inversion k; subst; complete sp].\n\n    rw onesoswapvar_not_in2 in e; auto;\n    [|intro k; inversion k; subst; complete sp].\n\n    rw soswapvar_not_in2 in e; auto.\n    rw soswapvar_not_in2 in e; auto.\nQed.\n\nLemma length_soswapbvars :\n  forall s l,\n    length (soswapbvars s l) = length l.\nProof.\n  induction l; allsimpl; sp.\nQed.\n\nLemma soswapbvars_nil :\n  forall l,\n    soswapbvars [] l = l.\nProof.\n  induction l; allsimpl; sp.\n  f_equal; auto.\nQed.\n\nLemma length_swap_range_sosub {o} :\n  forall sw (sub : @SOSub o),\n    length (swap_range_sosub sw sub) = length sub.\nProof.\n  induction sub; simpl; sp.\nQed.\n\nLemma length_cswap_range_sosub {o} :\n  forall sw (sub : @SOSub o),\n    length (cswap_range_sosub sw sub) = length sub.\nProof.\n  induction sub; simpl; sp.\nQed.\n\nLemma sodom_swap_range_sosub {o} :\n  forall sw (sub : @SOSub o),\n    sodom (swap_range_sosub sw sub) = sodom sub.\nProof.\n  induction sub; simpl; sp.\n  destruct a; simpl.\n  rw IHsub; rw length_swapbvars; auto.\nQed.\n\nLemma sodom_cswap_range_sosub {o} :\n  forall sw (sub : @SOSub o),\n    sodom (cswap_range_sosub sw sub) = sodom sub.\nProof.\n  induction sub; simpl; sp.\n  destruct a; simpl.\n  rw IHsub; rw length_swapbvars; auto.\nQed.\n\nLemma oneswapvar_eq :\n  forall v1 v2, oneswapvar v1 v2 v1 = v2.\nProof.\n  introv; unfold oneswapvar; boolvar; sp.\nQed.\n\nLemma oneswapvar_not_in :\n  forall v1 v2 v, v <> v1 -> v <> v2 -> oneswapvar v1 v2 v = v.\nProof.\n  introv n1 n2; unfold oneswapvar; boolvar; sp.\nQed.\n\nLemma in_soswapbvars :\n  forall (v : NVar) (sw : soswapping) (vs : list NVar),\n    LIn v (soswapbvars sw vs)\n    <=> {v' : NVar $ LIn v' vs # v = sovar2var (soswapvar sw (var2sovar v'))}.\nProof.\n  introv.\n  rw in_map_iff; sp.\nQed.\n\nLemma in_soswapbvars_implies :\n  forall v vs1 vs2 l,\n    LIn v (soswapbvars (mk_soswapping vs1 vs2) l)\n    -> (LIn v (sovars2vars vs1) [+] LIn v vs2 [+] LIn v l).\nProof.\n  induction l; introv i; allsimpl; tcsp.\n  dorn i; tcsp.\n  clear IHl.\n  revert vs2 a v i l.\n  induction vs1; introv i; introv; allsimpl.\n  - destruct vs2; allsimpl; subst; sp.\n  - destruct a; destruct vs2; allsimpl.\n    + subst; sp.\n    + unfold onesoswapvar in i; boolvar; cpx.\n      * unfold var2sovar in e.\n        apply pair_inj in e; repnd; subst n0 a0.\n        apply IHvs1 with (l := l) in i; auto.\n        dorn i; tcsp.\n      * unfold var2sovar in e.\n        apply pair_inj in e; repnd.\n        subst n0 a0.\n        apply IHvs1 with (l := l) in i; auto.\n        dorn i; tcsp.\n      * apply IHvs1 with (l := l) in i; auto.\n        dorn i; tcsp.\nQed.\n\nLemma swapvar_soswapvar :\n  forall (vs1 : list sovar_sig) (vs2 l1 l2 : list NVar) v,\n    disjoint l2 vs2\n    -> disjoint l2 (sovars2vars vs1)\n    -> disjoint l2 l1\n    -> disjoint vs2 (sovars2vars vs1)\n    -> no_repeats vs2\n    -> no_repeats l2\n    -> !LIn v vs2\n    -> !LIn v l2\n    -> swapvar (mk_swapping (soswapbvars (mk_soswapping vs1 vs2) l1) l2)\n               (sovar2var (soswapvar (mk_soswapping vs1 vs2) (v, 0)))\n       = sovar2var\n           (soswapvar (mk_soswapping vs1 vs2) (swapvar (mk_swapping l1 l2) v, 0)).\nProof.\n  induction l1 as [|x1 l1];\n  introv disj1 disj2 disj3 disj4 norep1 norep2 ni1 ni2; allsimpl; auto.\n  destruct l2 as [|x2 l2]; allsimpl; auto.\n  allrw disjoint_cons_l; repnd.\n  allrw disjoint_cons_r; repnd.\n  allsimpl.\n  allrw no_repeats_cons; repnd.\n  allrw not_over_or; repnd.\n\n  destruct (deq_nvar x1 v); subst.\n\n  - repeat (rw oneswapvar_eq).\n    rw (swapvar_not_in x2 l1 l2); auto.\n    rw soswapvar_not_in; auto; simpl.\n    rw swapvar_not_in; auto.\n    intro k.\n    apply in_soswapbvars_implies in k.\n    dorn k;[|dorn k]; tcsp.\n\n  - rw (oneswapvar_not_in x1 x2 v); auto.\n    rw <- IHl1; auto; clear IHl1.\n    f_equal.\n    clear dependent l1.\n    clear dependent l2.\n    revert dependent v.\n    revert dependent x2.\n    revert dependent x1.\n    revert dependent vs2.\n    revert dependent vs1.\n    induction vs1; destruct vs2;\n    introv norep disj ni1 ni2 ne1 ni3 ne2 ne3;\n    allsimpl; GC.\n    + rw oneswapvar_not_in; auto.\n    + rw oneswapvar_not_in; auto.\n    + allrw not_over_or; repnd.\n      destruct a; allsimpl.\n      rw oneswapvar_not_in; auto.\n    + allrw not_over_or; repnd.\n      destruct a; allsimpl.\n      allrw disjoint_cons_l; allrw disjoint_cons_r; repnd.\n      allrw no_repeats_cons; repnd.\n      allsimpl; allrw not_over_or; repnd.\n      unfold onesoswapvar; boolvar; allunfold var2sovar; cpx.\n      * apply IHvs1; sp.\n      * apply IHvs1; sp.\n        destruct n3; f_equal; sp.\n      * apply IHvs1; sp.\n        destruct n3; f_equal; sp.\nQed.\n\nLemma swapbvars_soswapbvars :\n  forall l vs1 vs2 l1 l2,\n    disjoint l2 vs2\n    -> disjoint l2 (sovars2vars vs1)\n    -> disjoint l2 l1\n    -> disjoint vs2 (sovars2vars vs1)\n    -> no_repeats vs2\n    -> no_repeats l2\n    -> disjoint l vs2\n    -> disjoint l l2\n    -> swapbvars (mk_swapping (soswapbvars (mk_soswapping vs1 vs2) l1) l2)\n                 (soswapbvars (mk_soswapping vs1 vs2) l)\n       = soswapbvars (mk_soswapping vs1 vs2) (swapbvars (mk_swapping l1 l2) l).\nProof.\n  induction l;\n  introv disj1 disj2 disj3 disj4 norep1 norep2 disj5 disj6;\n  allsimpl; auto.\n  allrw disjoint_cons_l; repnd.\n  f_equal.\n  - apply swapvar_soswapvar; auto.\n  - apply IHl; auto.\nQed.\n\nLemma so_swap_soswap {o} :\n  forall (t : @SOTerm o) (vs1 : list sovar_sig) (vs2 l1 l2 : list NVar),\n    disjoint l2 (all_fo_vars t)\n    -> disjoint vs2 (all_fo_vars t)\n    -> disjoint l2 vs2\n    -> disjoint l2 (sovars2vars vs1)\n    -> disjoint l2 l1\n    -> disjoint vs2 (sovars2vars vs1)\n    -> no_repeats vs2\n    -> no_repeats l2\n    -> so_swap\n         (mk_swapping (soswapbvars (mk_soswapping vs1 vs2) l1) l2)\n         (soswap (mk_soswapping vs1 vs2) t)\n       = soswap (mk_soswapping vs1 vs2) (so_swap (mk_swapping l1 l2) t).\nProof.\n  soterm_ind t as [v ts ind|op bs ind] Case;\n  introv disj1 disj2 disj3 disj4 disj5 disj6 norep1 norep2;\n  allsimpl.\n\n  - Case \"sovar\".\n    allrw disjoint_cons_r; repnd.\n    boolvar; allsimpl; subst; allsimpl; cpx; GC;\n    try (complete (allapply map_eq_nil; tcsp));\n    allrw map_length; allrw map_map; unfold compose;\n    f_equal;\n    [|apply eq_maps; introv i; disj_flat_map; apply ind; auto ].\n\n    clear ind.\n    apply swapvar_soswapvar; auto.\n\n  - Case \"soterm\".\n    f_equal.\n    allrw map_map; unfold compose.\n    apply eq_maps; introv i.\n    destruct x as [l t]; simpl.\n    disj_flat_map.\n    allsimpl.\n    allrw disjoint_app_r; repnd.\n    rw swapbvars_soswapbvars; eauto with slow.\n    f_equal.\n    eapply ind; eauto.\nQed.\n\nLemma subvars_swapbvars :\n  forall l vs1 vs2 vs,\n    disjoint vs2 vs1\n    -> no_repeats vs2\n    -> disjoint vs2 l\n    -> length vs1 = length vs2\n    -> subvars l vs\n    -> subvars (swapbvars (mk_swapping vs1 vs2) l) (vs2 ++ remove_nvars vs1 vs).\nProof.\n  induction l; introv disj1 norep disj2 len sv; allsimpl; auto.\n  allrw subvars_cons_l; repnd.\n  allrw disjoint_cons_r; repnd.\n  dands.\n\n  - destruct (in_deq NVar deq_nvar a vs1).\n\n    + pose proof (swapvar_implies3 vs1 vs2 a) as h.\n      repeat (autodimp h hyp); eauto with slow.\n      rw in_app_iff; sp.\n\n    + rw swapvar_not_in; auto.\n      rw in_app_iff; rw in_remove_nvars; sp.\n\n  - apply IHl; sp.\nQed.\n\nLemma subvars_fo_bound_vars_so_swap {o} :\n  forall (t : @SOTerm o) vs1 vs2,\n    disjoint vs2 vs1\n    -> disjoint vs2 (all_fo_vars t)\n    -> no_repeats vs2\n    -> length vs1 = length vs2\n    -> subvars\n         (fo_bound_vars (so_swap (mk_swapping vs1 vs2) t))\n         (vs2 ++ remove_nvars vs1 (fo_bound_vars t)).\nProof.\n  soterm_ind t as [v ts ind|op bs ind] Case;\n  introv disj1 disj2 norep len; allsimpl.\n\n  - Case \"sovar\".\n    allrw disjoint_cons_r; repnd.\n    boolvar; subst; allsimpl; auto.\n    rw subvars_flat_map; introv i.\n    allrw in_map_iff; exrepnd; subst.\n    disj_flat_map.\n    pose proof (ind a i1 vs1 vs2) as h; repeat (autodimp h hyp).\n    eapply subvars_trans;[exact h|].\n    apply subvars_app_lr; auto.\n    rw subvars_prop; introv k.\n    allrw in_remove_nvars; repnd; dands; auto.\n    rw lin_flat_map; eexists; eauto.\n\n  - Case \"soterm\".\n    rw flat_map_map; unfold compose.\n    apply subvars_flat_map; introv i.\n    destruct x as [l t]; simpl.\n    disj_flat_map; allsimpl.\n    allrw disjoint_app_r; repnd.\n    apply subvars_app_l; dands.\n\n    + assert (subvars l (flat_map fo_bound_vars_bterm bs)) as sv.\n      { eapply implies_subvars_flat_map_r; eauto.\n        simpl; apply subvars_app_weak_l; auto. }\n\n      apply subvars_swapbvars; auto.\n\n    + pose proof (ind t l i vs1 vs2) as h; repeat (autodimp h hyp).\n      eapply subvars_trans;[exact h|].\n      apply subvars_app_lr; auto.\n      rw subvars_prop; introv k.\n      allrw in_remove_nvars; repnd; dands; auto.\n      rw lin_flat_map.\n      exists (sobterm l t); sp.\n      simpl.\n      rw in_app_iff; sp.\nQed.\n\nLemma cswap_range_sosub_trivial {o} :\n  forall (sub : @SOSub o) vs1 vs2,\n    disjoint vs1 (free_vars_sosub sub)\n    -> disjoint vs2 (free_vars_sosub sub)\n    -> disjoint vs1 (bound_vars_sosub sub)\n    -> disjoint vs2 (bound_vars_sosub sub)\n    -> disjoint vs1 vs2\n    -> no_repeats vs2\n    -> cswap_range_sosub (mk_swapping vs1 vs2) sub = sub.\nProof.\n  induction sub; introv disj1 disj2 disj3 disj4 disj5 norep; simpl; auto.\n  destruct a; allsimpl.\n  allrw disjoint_app_r; repnd.\n  rw IHsub; auto.\n  f_equal; f_equal.\n  apply cswapsk_trivial; eauto with slow.\nQed.\n\nLemma cover_so_vars_so_swap_swap_range_sosub {o} :\n  forall (t : @SOTerm o) (vs1 vs2 : list NVar) (sub : SOSub),\n    cover_so_vars t sub\n    -> cover_so_vars\n         (so_swap (mk_swapping vs1 vs2) t)\n         (swap_range_sosub (mk_swapping vs1 vs2) sub).\nProof.\n  introv cov.\n  pose proof (cover_so_vars_so_swap t vs1 vs2 (so_dom sub) (so_range sub)) as h.\n  rw <- @swap_range_sosub_combine in h.\n  rw <- @sosub_as_combine in h.\n  auto.\nQed.\n\nLemma implies_cover_so_vars_so_swap {o} :\n  forall (t : @SOTerm o) vs1 vs2 sub,\n    cover_so_vars t sub\n    -> cover_so_vars (so_swap (mk_swapping vs1 vs2) t) sub.\nProof.\n  soterm_ind1s t as [ v ts ind | op lbt ind ] Case; simpl; introv cov.\n\n  - Case \"sovar\".\n    boolvar; subst; allsimpl; auto;\n    allrw @cover_so_vars_sovar; repnd; dands; allsimpl; tcsp; introv k.\n\n    + rw null_map in k.\n      apply cov0 in k; clear cov0.\n      rw map_length; auto.\n\n    + rw in_map_iff in k; exrepnd; subst.\n      applydup cov in k1.\n      apply ind; auto.\n\n  - Case \"soterm\".\n    allrw @cover_so_vars_soterm; introv i.\n    rw in_map_iff in i; exrepnd.\n    destruct a; allsimpl; ginv.\n    applydup cov in i1.\n    eapply ind; eauto.\nQed.\n\nLemma alpha_eq_sosub_aux_if_soswap {o} :\n  forall (t1 t2 : @SOTerm o) sub1 sub2 vs,\n    let vars1 := sodom sub1 in\n    let vars2 := sodom sub2 in\n    length vs = length vars1\n    -> length vs = length vars2\n    -> disjoint vs (sovars2vars vars1 ++ sovars2vars vars2 ++ all_fo_vars t1 ++ all_fo_vars t2)\n    -> no_repeats vs\n    -> disjoint (fo_bound_vars t1) (free_vars_sosub sub1)\n    -> disjoint (free_vars_sosub sub1) (bound_vars_sosub sub1)\n    -> disjoint (all_fo_vars t1) (bound_vars_sosub sub1)\n    -> disjoint (fo_bound_vars t2) (free_vars_sosub sub2)\n    -> disjoint (free_vars_sosub sub2) (bound_vars_sosub sub2)\n    -> disjoint (all_fo_vars t2) (bound_vars_sosub sub2)\n    -> cover_so_vars t1 sub1\n    -> cover_so_vars t2 sub2\n    -> alphaeq_sosub_range sub1 sub2\n    -> so_alphaeq (soswap (mk_soswapping vars1 vs) t1)\n                  (soswap (mk_soswapping vars2 vs) t2)\n    -> alpha_eq (sosub_aux sub1 t1) (sosub_aux sub2 t2).\nProof.\n  soterm_ind1s t1 as [v1 ts1 ind1|op1 bs1 ind1] Case;\n  introv len1 len2 disj norep;\n  introv disj1 disj2 disj3 disj4 disj5 disj6;\n  introv cov1 cov2 aeqsub soaeq;\n  allsimpl;\n  destruct t2; allsimpl; try (complete (inversion soaeq)).\n\n  - Case \"sovar\".\n    inversion soaeq as [? ? ? len imp x e|]; subst; clear soaeq.\n    allrw map_length.\n    allrw disjoint_app_r.\n    allrw disjoint_cons_r.\n    allrw disjoint_app_r.\n    allrw disjoint_cons_r.\n    repnd.\n\n    allrw @sovars2vars_sodom_is_so_dom.\n    allrw @length_sodom.\n    allrw @cover_so_vars_sovar; repnd.\n\n    remember (sosub_find sub1 (v1, length ts1)) as f1; symmetry in Heqf1; destruct f1;\n    remember (sosub_find sub2 (n, length l)) as g1; symmetry in Heqg1; destruct g1;\n    try (destruct s); try (destruct s0).\n\n    + pose proof (sosub_find_some_eq_sovar2var\n                    sub1 sub2 (v1,length ts1) (n,length l)\n                    (sosk l0 n0) (sosk l1 n1) vs) as h; allsimpl.\n      repeat (autodimp h hyp); try omega.\n\n      apply alphaeq_sk_iff_alphaeq_bterm2 in h; simpl in h.\n\n      pose proof (apply_bterm_alpha_congr\n                    (bterm l0 n0) (bterm l1 n1)\n                    (map (sosub_aux sub1) ts1)\n                    (map (sosub_aux sub2) l)) as k.\n      repeat (autodimp k hyp).\n\n      * apply (bin_rel_nterm_map _ default_soterm); auto.\n        introv i.\n        applydup in_combine in i; repnd.\n        allrw disjoint_cons_l; repnd.\n        disj_flat_map.\n        pose proof (fo_bound_vars_subvars_all_fo_vars a1) as sv1.\n        pose proof (fo_bound_vars_subvars_all_fo_vars a2) as sv2.\n        apply ind1 with (vs := vs); auto;\n        allrw @length_sodom; allrw @sovars2vars_sodom_is_so_dom; auto.\n\n        { allrw disjoint_app_r; dands; auto. }\n\n        { apply imp.\n          rw <- @map_combine.\n          rw in_map_iff.\n          exists (a1,a2); dands; auto. }\n\n      * allrw map_length.\n        unfold num_bvars; simpl.\n        apply sosub_find_some in Heqf1; sp.\n\n      * unfold apply_bterm in k; simpl in k.\n        applydup @sosub_find_some in Heqf1; repnd.\n        applydup @sosub_find_some in Heqg1; repnd.\n        revert k.\n        change_to_lsubst_aux4; tcsp;\n        rw flat_map_map; unfold compose;\n        eapply disjoint_bound_vars_prop4; eauto with slow.\n\n    + pose proof (sosub_find_some_none_eq_sovar2var\n                    sub1 sub2 vs\n                    (v1, length ts1) (n, length l)\n                    (sosk l0 n0)) as h.\n      repeat (autodimp h hyp); sp.\n\n    + pose proof (sosub_find_some_none_eq_sovar2var\n                    sub2 sub1 vs\n                    (n, length l) (v1, length ts1)\n                    (sosk l0 n0)) as h.\n      repeat (autodimp h hyp); sp.\n\n    + pose proof (sosub_find_none_eq_sovar2var\n                    sub1 sub2 vs (v1, length ts1) (n, length l)) as h.\n      repeat (autodimp h hyp); sp.\n      allsimpl; subst.\n\n      apply alphaeq_eq.\n      apply alphaeq_apply_list; eauto with slow.\n\n      apply (bin_rel_nterm_map _ default_soterm); auto.\n      introv i.\n      applydup in_combine in i; repnd.\n      allrw disjoint_cons_l; repnd.\n      disj_flat_map.\n      pose proof (fo_bound_vars_subvars_all_fo_vars a1) as sv1.\n      pose proof (fo_bound_vars_subvars_all_fo_vars a2) as sv2.\n      apply ind1 with (vs := vs); auto;\n      allrw @length_sodom; allrw @sovars2vars_sodom_is_so_dom; auto.\n\n      { allrw disjoint_app_r; dands; auto. }\n\n      { apply imp.\n        rw <- @map_combine.\n        rw in_map_iff.\n        exists (a1,a2); dands; auto. }\n\n  - Case \"soterm\".\n\n    allrw @cover_so_vars_soterm.\n    allrw disjoint_app_r; repnd.\n    allrw @sovars2vars_sodom_is_so_dom.\n    allrw @length_sodom.\n\n    inversion soaeq as [| ? ? ? len imp]; subst; clear soaeq.\n    allrw map_length.\n\n    apply alpha_eq_oterm_combine; allrw map_length; dands; auto;[].\n\n    introv i.\n    rw <- @map_combine in i.\n    rw in_map_iff in i; exrepnd; allsimpl; cpx.\n    destruct a0 as [l1 t1].\n    destruct a as [l2 t2].\n    simpl.\n\n    applydup in_combine in i1; repnd.\n    applydup cov1 in i2.\n    applydup cov2 in i0.\n\n    pose proof (imp\n                  (soswapbt (mk_soswapping (sodom sub1) vs) (sobterm l1 t1))\n                  (soswapbt (mk_soswapping (sodom sub2) vs) (sobterm l2 t2)))\n      as soaeqb.\n    autodimp soaeqb hyp;[rw <- @map_combine; rw in_map_iff; eexists; complete eauto|].\n    simpl in soaeqb.\n    apply (so_alphaeqbt_vs_implies_more\n             _ _ _ (vs\n                      ++ l1\n                      ++ l2\n                      ++ all_fo_vars t1\n                      ++ all_fo_vars t2\n                      ++ sovars2vars (sodom sub1)\n                      ++ sovars2vars (sodom sub2)\n                      ++ allvars (sosub_aux (sosub_filter sub1 (vars2sovars l1)) t1)\n                      ++ allvars (sosub_aux (sosub_filter sub2 (vars2sovars l2)) t2)\n                      ++ get_fo_vars (sodom (sosub_filter sub1 (vars2sovars l1)))\n                      ++ get_fo_vars (sodom (sosub_filter sub2 (vars2sovars l2)))\n                      ++ free_vars_sosub sub1\n                      ++ bound_vars_sosub sub1\n                      ++ free_vars_sosub sub2\n                      ++ bound_vars_sosub sub2\n          )) in soaeqb; auto.\n    (* vs0 can be disjoint from whatever we want using so_alphaeq_vs_implies_more *)\n    inversion soaeqb as [? ? ? ? ? el1 el2 d nr soaeq]; subst; allsimpl; clear soaeqb.\n    allrw disjoint_app_r; repnd.\n    allrw length_soswapbvars.\n\n    disj_flat_map.\n    allsimpl; allrw disjoint_app_r; allrw disjoint_app_l; repnd.\n\n    pose proof (so_swap_soswap t1 (sodom sub1) vs l1 vs0)\n      as e1.\n    repeat (autodimp e1 hyp); allrw @sovars2vars_sodom_is_so_dom; auto.\n\n    pose proof (so_swap_soswap t2 (sodom sub2) vs l2 vs0)\n      as e2.\n    repeat (autodimp e2 hyp); allrw @sovars2vars_sodom_is_so_dom; auto.\n\n    rw e1 in soaeq.\n    rw e2 in soaeq.\n\n    apply (so_alphaeq_vs_implies_less _ _ _ []) in soaeq; auto.\n\n    apply alphaeqbt_eq.\n    apply (aeqbt _ vs0); auto; try omega.\n\n    { allrw disjoint_app_r; sp. }\n\n    pose proof (sosub_aux_cswap_cswap3\n                  t1 (sosub_filter sub1 (vars2sovars l1))\n                  l1 vs0) as h1.\n    repeat (autodimp h1 hyp).\n    { rw disjoint_app_r; sp. }\n    { rw @sodom_sosub_filter.\n      rw get_fo_vars_remove_so_vars.\n      apply disjoint_remove_nvars_l.\n      rw remove_nvars_eq; auto. }\n    { apply cover_so_vars_sosub_filter; auto. }\n\n    pose proof (sosub_aux_cswap_cswap3\n                  t2 (sosub_filter sub2 (vars2sovars l2))\n                  l2 vs0) as h2.\n    repeat (autodimp h2 hyp).\n    { rw disjoint_app_r; sp. }\n    { rw @sodom_sosub_filter.\n      rw get_fo_vars_remove_so_vars.\n      apply disjoint_remove_nvars_l.\n      rw remove_nvars_eq; auto. }\n    { apply cover_so_vars_sosub_filter; auto. }\n\n    rw h1; rw h2.\n    clear h1 h2.\n\n    repeat (rw <- @sosub_filter_cswap_range_sosub; auto).\n    repeat (rw @sosub_aux_sosub_filter; auto);\n      try (complete (apply disjoint_fovars_so_swap; eauto with slow; try omega)).\n\n    pose proof (ind1\n                  t1\n                  (so_swap (mk_swapping l1 vs0) t1)\n                  l1\n                  i2\n                  (sosize_so_swap_le t1 (mk_swapping l1 vs0))\n                  (so_swap (mk_swapping l2 vs0) t2)\n                  (cswap_range_sosub (mk_swapping l1 vs0) sub1)\n                  (cswap_range_sosub (mk_swapping l2 vs0) sub2)\n                  vs\n               ) as h.\n    allrw @length_sodom.\n    allrw @length_cswap_range_sosub.\n    allrw @sodom_cswap_range_sosub.\n    allrw @sovars2vars_sodom_is_so_dom.\n    repeat (rw @cswap_range_sosub_trivial in h; eauto with slow).\n    repeat (rw @cswap_range_sosub_trivial; eauto with slow).\n\n    repeat (autodimp h hyp); try omega.\n\n    { allrw disjoint_app_r; dands; eauto 3 with slow.\n      - apply disjoint_all_fo_vars_so_swap; eauto 3 with slow.\n      - apply disjoint_all_fo_vars_so_swap; eauto 3 with slow. }\n\n    { pose proof (subvars_fo_bound_vars_so_swap t1 l1 vs0) as sv1.\n      repeat (autodimp sv1 hyp).\n      eapply subvars_disjoint_l;[exact sv1|].\n      apply disjoint_app_l; dands; eauto 4 with slow. }\n\n    { apply disjoint_sym.\n      apply disjoint_all_fo_vars_so_swap; eauto 3 with slow. }\n\n    { pose proof (subvars_fo_bound_vars_so_swap t2 l2 vs0) as sv1.\n      repeat (autodimp sv1 hyp).\n      eapply subvars_disjoint_l;[exact sv1|].\n      apply disjoint_app_l; dands; eauto 4 with slow. }\n\n    { apply disjoint_sym.\n      apply disjoint_all_fo_vars_so_swap; eauto 3 with slow. }\n\n    { apply implies_cover_so_vars_so_swap; auto. }\n\n    { apply implies_cover_so_vars_so_swap; auto. }\n\n    { apply alphaeq_eq; auto. }\nQed.\n\nLemma sovar2var_soswapvar_more :\n  forall vs1 vs2 vs vs' v1 v2 n1 n2,\n    disjoint vs (sovars2vars vs1)\n    -> disjoint vs (sovars2vars vs2)\n    -> no_repeats vs\n    -> !LIn v1 vs\n    -> !LIn v2 vs\n    -> disjoint vs' (sovars2vars vs1)\n    -> disjoint vs' (sovars2vars vs2)\n    -> no_repeats vs'\n    -> !LIn v1 vs'\n    -> !LIn v2 vs'\n    -> length vs1 = length vs\n    -> length vs2 = length vs\n    -> length vs' = length vs\n    -> sovar2var (soswapvar (mk_soswapping vs1 vs) (v1, n1))\n       = sovar2var (soswapvar (mk_soswapping vs2 vs) (v2, n2))\n    -> sovar2var (soswapvar (mk_soswapping vs1 vs') (v1, n1))\n       = sovar2var (soswapvar (mk_soswapping vs2 vs') (v2, n2)).\nProof.\n  induction vs1;\n  introv disj1 disj2 norep1 ni1 ni2;\n  introv disj3 disj4 norep2 ni3 ni4;\n  introv len1 len2 len3 e; allsimpl.\n  - destruct vs; allsimpl; cpx.\n  - destruct a.\n    destruct vs; allsimpl; cpx.\n    destruct vs'; allsimpl; cpx.\n    destruct vs2; allsimpl; cpx.\n    destruct s; allsimpl.\n    allrw disjoint_cons_l; allrw disjoint_cons_r; allsimpl; repnd.\n    allrw not_over_or; repnd.\n    allrw no_repeats_cons; repnd.\n    allunfold onesoswapvar; boolvar; auto; cpx.\n    + rw soswapvar_not_in; auto.\n      rw soswapvar_not_in; auto.\n    + provefalse.\n      rw soswapvar_not_in in e; auto; allsimpl.\n      pose proof (in_deq sovar_sig sovar_sig_dec (v2,n2) vs2) as [i|i].\n      * pose proof (soswapvar_in vs2 vs (v2,n2)) as h.\n        repeat (autodimp h hyp).\n        rw <- e in h; sp.\n      * rw soswapvar_not_in2 in e; sp.\n    + provefalse.\n      rw (soswapvar_not_in vs2 vs) in e; auto; allsimpl.\n      pose proof (in_deq sovar_sig sovar_sig_dec (v1,n1) vs1) as [i|i].\n      * pose proof (soswapvar_in vs1 vs (v1,n1)) as h.\n        repeat (autodimp h hyp).\n        rw e in h; sp.\n      * rw soswapvar_not_in2 in e; sp.\n    + eapply IHvs1; eauto; try omega.\nQed.\n\nLemma so_alphaeq_soswap_more {o} :\n  forall (t1 t2 : @SOTerm o) vs1 vs2 vs vs',\n    disjoint vs (sovars2vars vs1)\n    -> disjoint vs (sovars2vars vs2)\n    -> disjoint vs (all_fo_vars t1)\n    -> disjoint vs (all_fo_vars t2)\n    -> no_repeats vs\n    -> disjoint vs' (sovars2vars vs1)\n    -> disjoint vs' (sovars2vars vs2)\n    -> disjoint vs' (all_fo_vars t1)\n    -> disjoint vs' (all_fo_vars t2)\n    -> no_repeats vs'\n    -> length vs1 = length vs\n    -> length vs2 = length vs\n    -> length vs' = length vs\n    -> so_alphaeq (soswap (mk_soswapping vs1 vs) t1)\n                  (soswap (mk_soswapping vs2 vs) t2)\n    -> so_alphaeq (soswap (mk_soswapping vs1 vs') t1)\n                  (soswap (mk_soswapping vs2 vs') t2).\nProof.\n  soterm_ind1s t1 as [v1 ts1 ind1|op1 bs1 ind1] Case;\n  introv disj1 disj2 disj3 disj4 norep1;\n  introv disj5 disj6 disj7 disj8 norep2;\n  introv len1 len2 len3 aeq;\n  allsimpl.\n\n  - Case \"sovar\".\n    destruct t2 as [v2 ts2|op2 bs2]; allsimpl;\n    try (complete (inversion aeq)).\n    allrw disjoint_cons_r; repnd.\n    inversion aeq as [? ? ? len imp x e|]; subst; clear aeq.\n    allrw map_length.\n    pose proof (sovar2var_soswapvar_more vs1 vs2 vs vs' v1 v2 (length ts1) (length ts2)) as h.\n    repeat (autodimp h hyp).\n    rw h.\n    constructor.\n    + allrw map_length; auto.\n    + introv i.\n      rw <- @map_combine in i.\n      rw in_map_iff in i; exrepnd; allsimpl; cpx.\n      applydup in_combine in i1; repnd.\n      disj_flat_map.\n      apply ind1 with (vs := vs); auto; try omega.\n      apply imp.\n      rw <- @map_combine.\n      apply in_map_iff.\n      exists (a0,a); simpl; sp.\n\n  - Case \"soterm\".\n    destruct t2 as [|op2 bs2]; try (complete (inversion aeq)).\n    inversion aeq as [|? ? ? len imp x]; subst; clear aeq.\n    allrw map_length; allsimpl.\n    constructor; allrw map_length; auto.\n\n    introv i.\n    rw <- @map_combine in i.\n    rw in_map_iff in i; exrepnd.\n    destruct a0 as [l1 t1].\n    destruct a as [l2 t2].\n    cpx.\n    applydup in_combine in i1; repnd.\n    disj_flat_map.\n    allsimpl; allrw disjoint_app_r; repnd.\n\n    pose proof (imp (soswapbt (mk_soswapping vs1 vs) (sobterm l1 t1))\n                    (soswapbt (mk_soswapping vs2 vs) (sobterm l2 t2))) as h.\n    autodimp h hyp.\n    { rw <- @map_combine; rw in_map_iff; eexists; eauto. }\n\n    simpl in h.\n    apply (so_alphaeqbt_vs_implies_more\n             _ _ _ (vs\n                      ++ vs'\n                      ++ l1\n                      ++ l2\n                      ++ all_fo_vars t1\n                      ++ all_fo_vars t2\n                      ++ soswapbvars (mk_soswapping vs1 vs') l1\n                      ++ soswapbvars (mk_soswapping vs2 vs') l2\n                      ++ all_fo_vars (soswap (mk_soswapping vs1 vs') t1)\n                      ++ all_fo_vars (soswap (mk_soswapping vs2 vs') t2)\n                      ++ sovars2vars vs1\n                      ++ sovars2vars vs2\n          )) in h; auto.\n    inversion h as [? ? ? ? ? el1 el2 disj norep aeq]; subst; allsimpl; clear h.\n    allrw disjoint_app_r; repnd.\n    apply (so_alphaeq_vs_implies_less _ _ _ []) in aeq; auto.\n    apply (soaeqbt _ vs0); allsimpl; allrw length_soswapbvars; auto.\n\n    { allrw disjoint_app_r; dands; eauto with slow. }\n\n    pose proof (so_swap_soswap t1 vs1 vs' l1 vs0) as e1.\n    repeat (autodimp e1 hyp).\n\n    pose proof (so_swap_soswap t2 vs2 vs' l2 vs0) as e2.\n    repeat (autodimp e2 hyp).\n\n    rw e1; rw e2; clear e1 e2.\n\n    pose proof (so_swap_soswap t1 vs1 vs l1 vs0) as e1.\n    repeat (autodimp e1 hyp).\n\n    pose proof (so_swap_soswap t2 vs2 vs l2 vs0) as e2.\n    repeat (autodimp e2 hyp).\n\n    rw e1 in aeq; rw e2 in aeq; clear e1 e2.\n\n    pose proof (ind1\n                  t1\n                  (so_swap (mk_swapping l1 vs0) t1)\n                  l1\n                  i2\n                  (sosize_so_swap_le t1 (mk_swapping l1 vs0))\n                  (so_swap (mk_swapping l2 vs0) t2)\n                  vs1 vs2\n                  vs vs'\n               ) as h.\n    repeat (autodimp h hyp).\n\n    { apply disjoint_all_fo_vars_so_swap; eauto with slow. }\n\n    { apply disjoint_all_fo_vars_so_swap; eauto with slow. }\n\n    { apply disjoint_all_fo_vars_so_swap; eauto with slow. }\n\n    { apply disjoint_all_fo_vars_so_swap; eauto with slow. }\nQed.\n\nLemma alphaeq_sosub_implies_alphaeq_sosub_range {o} :\n    forall (sub1 sub2 : @SOSub o),\n      alphaeq_sosub sub1 sub2\n      -> alphaeq_sosub_range sub1 sub2.\nProof.\n  induction sub1; destruct sub2; introv aeq; auto;\n  inversion aeq; subst.\n  constructor; auto.\nQed.\nHint Resolve alphaeq_sosub_implies_alphaeq_sosub_range : slow.\n\nLemma alphaeq_sosub_range_trans {o} :\n  forall (sub1 sub2 sub3 : @SOSub o),\n    alphaeq_sosub_range sub1 sub2\n    -> alphaeq_sosub_range sub2 sub3\n    -> alphaeq_sosub_range sub1 sub3.\nProof.\n  induction sub1; destruct sub2, sub3; introv aeq1 aeq2; tcsp;\n  inversion aeq1; inversion aeq2; subst; cpx; clear aeq1 aeq2.\n  constructor; eauto.\n  eapply alphaeq_sk_trans; eauto.\nQed.\nHint Resolve alphaeq_sosub_range_trans : slow.\n\nLemma alphaeq_sosub_range_sym {o} :\n  forall (sub1 sub2 : @SOSub o),\n    alphaeq_sosub_range sub1 sub2\n    -> alphaeq_sosub_range sub2 sub1.\nProof.\n  induction sub1; destruct sub2; introv aeq; tcsp;\n  inversion aeq; subst; cpx; clear aeq.\n  constructor; eauto.\n  eapply alphaeq_sk_sym; eauto.\nQed.\nHint Resolve alphaeq_sosub_range_sym : slow.\n\nLemma alphaeq_sosub_range_refl {o} :\n  forall (sub :@SOSub o),\n    alphaeq_sosub_range sub sub.\nProof.\n  induction sub; auto.\n  destruct a.\n  constructor; auto.\n  apply alphaeq_sk_refl.\nQed.\nHint Resolve alphaeq_sosub_range_refl : slow.\n\nLemma so_alphaeq_soswap {o} :\n  forall (t1 t2 : @SOTerm o) vs1 vs2,\n    disjoint vs2 (all_fo_vars t1)\n    -> disjoint vs2 (all_fo_vars t2)\n    -> disjoint vs2 (sovars2vars vs1)\n    -> no_repeats vs2\n    -> so_alphaeq t1 t2\n    -> so_alphaeq (soswap (mk_soswapping vs1 vs2) t1)\n                  (soswap (mk_soswapping vs1 vs2) t2).\nProof.\n  soterm_ind1s t1 as [v1 ts1 ind1|op1 bs1 ind1] Case;\n  introv disj1 disj2 disj3 norep aeq; allsimpl;\n  destruct t2 as [v2 ts2|op2 bs2];\n  inversion aeq as [? ? ? len imp|? ? ? len imp]; subst; clear aeq;\n  allsimpl.\n\n  - Case \"sovar\".\n    rw len.\n    constructor; allrw map_length; auto.\n    introv i.\n    rw <- @map_combine in i; rw in_map_iff in i; exrepnd; cpx; allsimpl.\n    applydup in_combine in i1; repnd.\n    allrw disjoint_cons_r; repnd.\n    disj_flat_map.\n    apply ind1; auto.\n    apply imp; auto.\n\n  - Case \"soterm\".\n    constructor; allrw map_length; auto.\n    introv i.\n    rw <- @map_combine in i; rw in_map_iff in i; exrepnd; cpx; allsimpl.\n    destruct a0 as [l1 t1].\n    destruct a as [l2 t2].\n    applydup in_combine in i1; repnd.\n    allsimpl.\n    applydup imp in i1.\n\n    apply (so_alphaeqbt_vs_implies_more\n             _ _ _ (soswapbvars (mk_soswapping vs1 vs2) l1\n                                ++ soswapbvars (mk_soswapping vs1 vs2) l2\n                                ++ all_fo_vars (soswap (mk_soswapping vs1 vs2) t1)\n                                ++ all_fo_vars (soswap (mk_soswapping vs1 vs2) t2)\n                                ++ all_fo_vars t1\n                                ++ all_fo_vars t2\n                                ++ vs2\n                                ++ sovars2vars vs1\n          )) in i3; auto.\n    inversion i3 as [? ? ? ? ? el1 el2 disj norep2 aeq]; subst; allsimpl; clear i3.\n    allrw disjoint_app_r; repnd.\n    apply (so_alphaeq_vs_implies_less _ _ _ []) in aeq; auto.\n\n    apply (soaeqbt _ vs); allrw length_soswapbvars; allsimpl; auto; try omega.\n\n    { allrw disjoint_app_r; dands; eauto with slow. }\n\n    disj_flat_map.\n    allsimpl.\n    allrw disjoint_app_r; repnd.\n\n    pose proof (so_swap_soswap t1 vs1 vs2 l1 vs) as e1.\n    repeat (autodimp e1 hyp).\n\n    pose proof (so_swap_soswap t2 vs1 vs2 l2 vs) as e2.\n    repeat (autodimp e2 hyp).\n\n    rw e1; rw e2; clear e1 e2.\n\n    pose proof (ind1\n                  t1\n                  (so_swap (mk_swapping l1 vs) t1)\n                  l1\n                  i2\n                  (sosize_so_swap_le t1 (mk_swapping l1 vs))\n                  (so_swap (mk_swapping l2 vs) t2)\n                  vs1 vs2\n               ) as h.\n    repeat (autodimp h hyp).\n\n    apply disjoint_all_fo_vars_so_swap; eauto with slow.\n\n    apply disjoint_all_fo_vars_so_swap; eauto with slow.\nQed.\n\nLemma alpha_eq_sosub_if_soswap {o} :\n  forall vs (t1 t2 : @SOTerm o) sub1 sub2,\n    let vars1 := sodom sub1 in\n    let vars2 := sodom sub2 in\n    length vs = length vars1\n    -> length vs = length vars2\n    -> disjoint vs (sovars2vars vars1 ++ sovars2vars vars2 ++ all_fo_vars t1 ++ all_fo_vars t2)\n    -> no_repeats vs\n    -> cover_so_vars t1 sub1\n    -> cover_so_vars t2 sub2\n    -> alphaeq_sosub_range sub1 sub2\n    -> so_alphaeq (soswap (mk_soswapping vars1 vs) t1)\n                  (soswap (mk_soswapping vars2 vs) t2)\n    -> alpha_eq (sosub sub1 t1) (sosub sub2 t2).\nProof.\n  introv len1 len2 disj norep cov1 cov2 aeqsub soaeq.\n  pose proof (unfold_sosub sub1 t1) as h1.\n  pose proof (unfold_sosub sub2 t2) as k1.\n  destruct h1 as [sub1' h1].\n  destruct h1 as [t1' h1]; repnd.\n  destruct k1 as [sub2' k1].\n  destruct k1 as [t2' k1]; repnd.\n  rw h1; rw k1.\n\n  applydup @alphaeq_sosub_implies_eq_lengths in h0.\n  applydup @alphaeq_sosub_implies_eq_lengths in k0.\n\n  pose proof (cover_so_vars_if_so_alphaeq t1 t1' sub1 cov1 h2) as cov1'.\n  pose proof (cover_so_vars_if_alphaeq_sosub t1' sub1 sub1' cov1' h0) as cov1''.\n\n  pose proof (cover_so_vars_if_so_alphaeq t2 t2' sub2 cov2 k2) as cov2'.\n  pose proof (cover_so_vars_if_alphaeq_sosub t2' sub2 sub2' cov2' k0) as cov2''.\n\n  pose proof (fresh_vars\n                (length vs)\n                (vs\n                   ++ sovars2vars (sodom sub1)\n                   ++ sovars2vars (sodom sub2)\n                   ++ all_fo_vars t1\n                   ++ all_fo_vars t2\n                   ++ all_fo_vars t1'\n                   ++ all_fo_vars t2'\n             )) as fv.\n  exrepnd.\n  allrw disjoint_app_r; repnd.\n\n  pose proof (so_alphaeq_soswap_more t1 t2 (sodom sub1) (sodom sub2) vs lvn) as h.\n  repeat (autodimp h hyp).\n\n  pose proof (alphaeq_sosub_implies_eq_sodoms sub1 sub1' h0) as ed1.\n  applydup @eq_sodoms_implies_eq_so_doms in ed1 as ed1'.\n  pose proof (alphaeq_sosub_implies_eq_sodoms sub2 sub2' k0) as ed2.\n  applydup @eq_sodoms_implies_eq_so_doms in ed2 as ed2'.\n\n  apply (alpha_eq_sosub_aux_if_soswap _ _ _ _ lvn);\n    eauto;\n    allrw @length_sodom; auto; try omega;\n    allrw @sovars2vars_sodom_is_so_dom.\n\n  { allrw disjoint_app_r.\n    rw <- ed1'.\n    rw <- ed2'.\n    dands; auto. }\n\n  { allapply @alphaeq_sosub_implies_alphaeq_sosub_range.\n    eauto with slow. }\n\n  { rw <- ed1.\n    rw <- ed2.\n    apply (so_alphaeq_soswap _ _ (sodom sub1) lvn) in h2; auto;\n    allrw @sovars2vars_sodom_is_so_dom; auto.\n    apply (so_alphaeq_soswap _ _ (sodom sub2) lvn) in k2; auto;\n    allrw @sovars2vars_sodom_is_so_dom; auto.\n    eauto with slow. }\nQed.\n\nLemma matching_sovars_cons :\n  forall v1 v2 vs1 vs2,\n    matching_sovars (v1 :: vs1) (v2 :: vs2)\n    <=> (snd v1 = snd v2 # matching_sovars vs1 vs2).\nProof.\n  introv; unfold matching_sovars; simpl; split; intro k; cpx; repnd.\n  f_equal; auto.\nQed.\n\nLemma alphaeq_sosub_range_mk_abs_subst {o} :\n  forall vars1 vars2 (bs : list (@BTerm o)),\n    matching_bterms vars1 bs\n    -> matching_bterms vars2 bs\n    -> matching_sovars vars1 vars2\n    -> alphaeq_sosub_range (mk_abs_subst vars1 bs) (mk_abs_subst vars2 bs).\nProof.\n  induction vars1; destruct vars2, bs; introv m1 m2 m; allsimpl; tcsp;\n  try (complete (inversion m));\n  try (complete (inversion m1));\n  try (complete (inversion m2)).\n\n  destruct a, s.\n  destruct b; allsimpl.\n  allrw @matching_bterms_cons; repnd; allsimpl; subst.\n  allunfold @num_bvars; allsimpl.\n  allrw matching_sovars_cons; allsimpl; repnd.\n  boolvar; auto.\n  constructor; auto.\n  apply alphaeq_sk_refl.\nQed.\n\nLemma alpha_eq_mk_abs_subst_if_bterm {o} :\n  forall vs vars1 vars2 (t1 t2 : @SOTerm o) bs,\n    matching_bterms vars1 bs\n    -> matching_bterms vars2 bs\n    -> length vs = length vars1\n    -> length vs = length vars2\n    -> disjoint vs (sovars2vars vars1 ++ sovars2vars vars2 ++ all_fo_vars t1 ++ all_fo_vars t2)\n    -> no_repeats vs\n    -> matching_sovars vars1 vars2\n    -> socovered t1 vars1\n    -> socovered t2 vars2\n    -> so_alphaeq (soswap (mk_soswapping vars1 vs) t1)\n                  (soswap (mk_soswapping vars2 vs) t2)\n    -> alpha_eq (mk_instance vars1 bs t1)\n                (mk_instance vars2 bs t2).\nProof.\n  introv m1 m2 len1 len2 disj norep msv cov1 cov2 aeq.\n  unfold mk_instance.\n  apply (alpha_eq_sosub_if_soswap vs); auto;\n  try (complete (allrw <- @mk_abs_subst_some_prop2; auto));\n  try (complete (apply socovered_implies_cover_so_vars; auto)).\n  apply alphaeq_sosub_range_mk_abs_subst; auto.\nQed.\n\nLemma eapply_wf_def_lam {o} :\n  forall v (b : @NTerm o), eapply_wf_def (mk_lam v b).\nProof.\n  introv; right; eexists; eexists; eauto.\nQed.\nHint Resolve eapply_wf_def_lam : slow.\n\nLemma compute_step_alpha_lib {p} :\n  forall lib1 lib2 t1 t2,\n    alpha_eq_lib lib1 lib2\n    -> compute_step lib1 t1 = csuccess t2\n    -> {t2' : @NTerm p\n        & compute_step lib2 t1 = csuccess t2'\n        # alpha_eq t2 t2'}.\nProof.\n  nterm_ind1s t1 as [v1|f1|o1 lbt1 IHind] Case; introv Hal Hcomp;\n  duplicate Hal as backup;\n  [ subst;\n    invertsn Hal;\n    invertsn Hcomp\n  | |].\n\n  { Case \"sterm\".\n    csunf Hcomp; allsimpl; ginv.\n    csunf; simpl.\n    exists (sterm f1); dands; eauto. }\n\n  Case \"oterm\".\n  dopid o1 as [c1 | nc1 | exc1 | abs1] SCase.\n\n  - SCase \"Can\".\n    inverts Hcomp; auto.\n    exists (oterm (Can c1) lbt1); simpl; auto.\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    {\n    SSSCase \"nilcase\".\n    destruct arg1nt as [v89|f| arg1o arg1bts];\n      [inverts Hcomp| |];\n      [|].\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.\n        csunf; simpl; eexists; dands; eauto.\n\n      - SSSSCase \"NEApply\".\n        apply compute_step_eapply_success in Hcomp; exrepnd; subst.\n        repndors; exrepnd; subst; allsimpl.\n\n        + apply compute_step_eapply2_success in Hcomp1; repnd; subst.\n          repndors; exrepnd; ginv.\n          csunf; simpl.\n          dcwf h; simpl.\n          boolvar; try omega.\n          rw Znat.Nat2Z.id; eexists; dands; eauto.\n\n        + fold_terms; unfold mk_eapply.\n          rw @compute_step_eapply_iscan_isexc; eauto 3 with slow.\n\n        + pose proof (IHind arg2 arg2 []) as h; clear IHind.\n          repeat (autodimp h hyp); eauto 3 with slow.\n          pose proof (h x) as ih; clear h.\n          repeat (autodimp ih hyp); exrepnd.\n          fold_terms; unfold mk_eapply.\n          rw @compute_step_eapply_iscan_isnoncan_like; eauto 3 with slow.\n          rw ih1; eexists; dands; eauto.\n          prove_alpha_eq2.\n\n      - SSSSCase \"NFix\".\n        apply compute_step_fix_success in Hcomp; repnd; subst.\n        csunf; simpl; eexists; dands; eauto.\n\n      - SSSSCase \"NCbv\".\n        apply compute_step_cbv_success in Hcomp; exrepnd; subst.\n        csunf; simpl; eexists; dands; eauto.\n\n      - SSSSCase \"NTryCatch\".\n        apply compute_step_try_success in Hcomp; exrepnd; subst.\n        csunf; simpl; eexists; dands; eauto.\n\n      - SSSSCase \"NCanTest\".\n        apply compute_step_seq_can_test_success in Hcomp; exrepnd; subst.\n        csunf; simpl; eexists; dands; eauto.\n    }\n\n    dopid arg1o as [arg1c | arg1nc | arg1exc | arg1abs] SSSSCase;\n      try (complete (exists t2; auto)).\n\n    + SSSSCase \"Can\". GC.\n      dopid_noncan nc1 SSSSSCase; try (complete (exists t2; auto)).\n\n      * SSSSSCase \"NEApply\".\n\n        csunf Hcomp; allsimpl.\n        apply compute_step_eapply_success in Hcomp; exrepnd; subst.\n        repndors; exrepnd; subst; allsimpl.\n\n        { apply compute_step_eapply2_success in Hcomp1; repnd; subst.\n          repndors; exrepnd; subst; ginv.\n          allunfold @mk_lam; ginv; fold_terms; unfold mk_eapply.\n          rw @compute_step_eapply_lam_iscan; auto.\n          eexists; dands; eauto. }\n\n        { unfold eapply_wf_def in Hcomp2; repndors; exrepnd; ginv.\n          allunfold @mk_lam; ginv.\n          fold_terms; unfold mk_eapply.\n          rw @compute_step_eapply_iscan_isexc; simpl; eauto 3 with slow.  }\n\n        { pose proof (IHind arg2 arg2 []) as h; clear IHind.\n          repeat (autodimp h hyp); eauto 3 with slow.\n          pose proof (h x) as ih; clear h.\n          repeat (autodimp ih hyp); exrepnd.\n          fold_terms; unfold mk_eapply.\n          rw @compute_step_eapply_iscan_isnoncan_like; eauto 3 with slow.\n          rw ih1; eexists; dands; eauto.\n          prove_alpha_eq2. }\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           *)\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]; try (complete (csunf Hcomp; allsimpl; dcwf h)).\n\n        dopid arg2o as [arg2c| arg2nc | arg2exc | arg2abs] SSSSSSCase;\n          try (complete (simpl in Hcomp; exists t2; auto)).\n\n        { SSSSSSCase \"NCan\".\n          csunf Hcomp; allsimpl.\n          dcwf h.\n          unfold on_success in Hcomp.\n          remember (compute_step lib1 ((oterm (NCan arg2nc) arg2bts))) as rec.\n          destruct rec as [csuccrec | cfail]; inverts Hcomp as Hcomp.\n          symmetry in Heqrec.\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) arg1bts)\n                               :: bterm [] t2'\n                               :: lbt1)).\n          csunf; simpl.\n          dcwf h;[].\n          rewrite Heqrec1. split; [refl|].\n          prove_alpha_eq2. }\n\n        { SSSSSSCase \"Abs\".\n          csunf Hcomp; allsimpl; csunf Hcomp; allsimpl.\n          dcwf h.\n          unfold on_success in Hcomp.\n          remember (compute_step_lib lib1 arg2abs arg2bts) as csl.\n          destruct csl; inversion Hcomp; subst; GC.\n          symmetry in Heqcsl.\n\n          pose proof (compute_step_lib_success lib1 arg2abs arg2bts n Heqcsl) as h.\n          exrepnd; subst.\n          duplicate h0 as fe1.\n          eapply found_entry_alpha_eq_lib in h0; eauto; exrepnd.\n          csunf; simpl; unfold on_success.\n          csunf; simpl.\n          dcwf h;[].\n          exists (oterm (NCan (NCompOp c))\n                        (bterm [] (oterm (Can arg1c) arg1bts)\n                               :: bterm [] (mk_instance vars2 arg2bts rhs2)\n                               :: lbt1)).\n          duplicate h1 as fe2.\n          apply found_entry_implies_compute_step_lib_success in h1; rw h1; dands; auto.\n          prove_alpha_eq2.\n          destruct XXn; auto.\n          apply alphaeqbt_nilv2.\n\n          apply found_entry_implies_matching_entry in fe1.\n          apply found_entry_implies_matching_entry in fe2.\n          unfold matching_entry in fe1; repnd.\n          unfold matching_entry in fe2; repnd.\n\n          allunfold @correct_abs; repnd.\n\n          apply (alpha_eq_mk_abs_subst_if_bterm vs); auto. }\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]; try (complete (csunf Hcomp; allsimpl; dcwf h)).\n\n        dopid arg2o as [arg2c| arg2nc | arg2exc | arg2abs] SSSSSSCase;\n          try (complete (simpl in Hcomp; exists t2; auto)).\n\n        { SSSSSSCase \"NCan\".\n          csunf Hcomp; allsimpl.\n          dcwf h.\n          unfold on_success in Hcomp.\n          remember (compute_step lib1 ((oterm (NCan arg2nc) arg2bts))) as rec.\n          destruct rec as [csuccrec | cfail]; inverts Hcomp as Hcomp.\n          symmetry in Heqrec.\n          eapply IHind with (lv:=[]) in Heqrec; eauto 3 with slow; tcsp; [].\n          exrepnd; subst.\n          exists (oterm (NCan (NArithOp a))\n                        (bterm [] (oterm (Can arg1c) arg1bts)\n                               :: bterm [] t2'\n                               :: lbt1)).\n          csunf; simpl.\n          dcwf h.\n          rewrite Heqrec1. split; [refl|].\n          prove_alpha_eq2. }\n\n        { SSSSSSCase \"Abs\".\n          csunf Hcomp; allsimpl.\n          dcwf h;[].\n          unfold on_success in Hcomp.\n          csunf Hcomp; allsimpl.\n          remember (compute_step_lib lib1 arg2abs arg2bts) as csl.\n          destruct csl; inversion Hcomp; subst; GC.\n          symmetry in Heqcsl.\n\n          pose proof (compute_step_lib_success lib1 arg2abs arg2bts n Heqcsl) as h.\n          exrepnd; subst.\n          duplicate h0 as fe1.\n          eapply found_entry_alpha_eq_lib in h0; eauto; exrepnd.\n          csunf; simpl; unfold on_success.\n          csunf; simpl.\n          dcwf h;[].\n          exists (oterm (NCan (NArithOp a))\n                        (bterm [] (oterm (Can arg1c) arg1bts)\n                               :: bterm [] (mk_instance vars2 arg2bts rhs2)\n                               :: lbt1)).\n          duplicate h1 as fe2.\n          apply found_entry_implies_compute_step_lib_success in h1; rw h1; dands; auto.\n          prove_alpha_eq2.\n          destruct XXn; auto.\n          apply alphaeqbt_nilv2.\n\n          apply found_entry_implies_matching_entry in fe1.\n          apply found_entry_implies_matching_entry in fe2.\n          unfold matching_entry in fe1; repnd.\n          unfold matching_entry in fe2; repnd.\n\n          allunfold @correct_abs; repnd.\n\n          apply (alpha_eq_mk_abs_subst_if_bterm vs); auto. }\n\n    + SSSSCase \"NCan\". GC.\n      csunf Hcomp; allsimpl.\n      remember (compute_step lib1 (oterm (NCan arg1nc) arg1bts)) as crt2s.\n      symmetry in Heqcrt2s.\n      destruct crt2s as [csucct2s | cfail];\n        try (complete (inversion Hcomp)).\n      inverts Hcomp.\n\n      eapply IHind with (lv:=[]) in Heqcrt2s; eauto 3 with slow; try(simpl; left; auto); exrepnd.\n      exists ((oterm (NCan nc1) (bterm [] t2' :: lbt1))).\n      rename Heqcrt2s1 into Hcomp.\n      rename Heqcrt2s0 into H1alcarg.\n      csunf; simpl.\n      rw Hcomp. split; [refl|].\n      constructor; auto.\n      simpl. introv Hlt.\n      destruct n; tcsp; unfold selectbt; simpl.\n      apply alphaeqbt_nilv2; trivial.\n\n    + SSSSCase \"Abs\".\n\n      clear IHind.\n      csunf Hcomp; simpl in Hcomp.\n      csunf Hcomp; allsimpl.\n      unfold on_success in Hcomp.\n      remember (compute_step_lib lib1 arg1abs arg1bts) as c.\n      destruct c; inversion Hcomp; subst; GC; symmetry in Heqc.\n      pose proof (compute_step_lib_success lib1 arg1abs arg1bts n Heqc) as h.\n      exrepnd; subst.\n\n      csunf; simpl; unfold on_success.\n      csunf; simpl.\n      duplicate h0 as fe1.\n      eapply found_entry_alpha_eq_lib in h0; eauto; exrepnd.\n      duplicate h1 as fe2.\n      apply found_entry_implies_compute_step_lib_success in h1; rw h1; dands; auto.\n      eexists; dands; eauto.\n      prove_alpha_eq2.\n      destruct XXn; auto.\n      apply alphaeqbt_nilv2.\n\n      apply found_entry_implies_matching_entry in fe1.\n      apply found_entry_implies_matching_entry in fe2.\n      unfold matching_entry in fe1; repnd.\n      unfold matching_entry in fe2; repnd.\n\n      allunfold @correct_abs; repnd.\n\n      apply (alpha_eq_mk_abs_subst_if_bterm vs); auto.\n    }\n\n    { (* fresh case *)\n      csunf Hcomp; allsimpl.\n      apply compute_step_fresh_success in Hcomp; repnd; subst; allsimpl.\n      repndors; exrepnd; subst.\n\n      - csunf; simpl; boolvar.\n        eexists; dands; eauto.\n\n      - rw @compute_step_fresh_if_isvalue_like2; auto.\n        eexists; dands; eauto.\n\n      - rw @compute_step_fresh_if_isnoncan_like; auto.\n        pose proof (IHind\n                      arg1nt\n                      (subst arg1nt arg1v1 (mk_utoken (get_fresh_atom arg1nt)))\n                      [arg1v1])\n          as ih; clear IHind.\n        repeat (autodimp ih hyp).\n        { rw @simple_osize_subst; eauto 3 with slow. }\n        pose proof (ih x) as h; clear ih; repeat (autodimp h hyp).\n        exrepnd.\n        rw h1; simpl.\n        eexists; dands; eauto.\n        apply implies_alpha_eq_mk_fresh.\n        apply alpha_eq_subst_utokens; eauto with slow.\n    }\n\n  - SCase \"Exc\".\n    csunf Hcomp; allsimpl; ginv.\n    exists (oterm Exc lbt1); simpl; auto.\n\n  - SCase \"Abs\".\n\n    clear IHind.\n    csunf Hcomp; simpl in Hcomp.\n    pose proof (compute_step_lib_success lib1 abs1 lbt1 t2 Hcomp) as h.\n    exrepnd; subst.\n\n    simpl.\n    duplicate h0 as fe1.\n    eapply found_entry_alpha_eq_lib in h0; eauto; exrepnd.\n    duplicate h1 as fe2.\n    csunf; simpl.\n    apply found_entry_implies_compute_step_lib_success in h1; rw h1; dands; auto.\n    eexists; dands; eauto.\n\n    apply found_entry_implies_matching_entry in fe1.\n    apply found_entry_implies_matching_entry in fe2.\n    unfold matching_entry in fe1; repnd.\n    unfold matching_entry in fe2; repnd.\n\n    allunfold @correct_abs; repnd.\n\n    apply (alpha_eq_mk_abs_subst_if_bterm vs); auto.\nQed.\n\nLemma compute_1step_alpha_lib {p} :\n  forall lib1 lib2 (t1 t2 : @NTerm p),\n    alpha_eq_lib lib1 lib2\n    -> computes_in_1step lib1 t1 t2\n    -> {t2' : @NTerm p & computes_in_1step lib2 t1 t2' # alpha_eq t2 t2'}.\nProof.\n  introv Hal Hc.\n  invertsn Hc;\n    eapply compute_step_alpha_lib in Hc; eauto; exrepnd;\n    exists t2'; dands; auto;\n    constructor; auto.\nQed.\n\nLemma computes_in_1step_alpha_lib {o} :\n  forall (lib1 lib2 : @library o) t1 t2,\n    computes_in_1step_alpha lib1 t1 t2\n    -> alpha_eq_lib lib1 lib2\n    -> computes_in_1step_alpha lib2 t1 t2.\nProof.\n  introv comp aeq.\n  allunfold @computes_in_1step_alpha; exrepnd.\n  eapply compute_1step_alpha_lib in comp1; eauto; exrepnd.\n  exists t2'; dands; eauto with slow.\nQed.\n\nLemma alpha_eq_entry_sym {o} :\n  forall (entry1 entry2 : @library_entry o),\n    alpha_eq_entry entry1 entry2 -> alpha_eq_entry entry2 entry1.\nProof.\n  introv aeq.\n  inversion aeq as [? ? ? ? ? ? ? ? len1 len2 disj norep m a l1 l2]; subst; clear aeq.\n  apply (aeq_lib_entry vs); eauto with slow.\n  - allrw disjoint_app_r; sp.\n  - apply matching_sovars_sym; auto.\nQed.\nHint Resolve alpha_eq_entry_sym : slow.\n\nLemma alpha_eq_lib_sym {o} :\n  forall (lib1 lib2 : @library o),\n    alpha_eq_lib lib1 lib2 -> alpha_eq_lib lib2 lib1.\nProof.\n  induction lib1; introv aeq; inversion aeq; subst; auto.\n  constructor; eauto with slow.\nQed.\nHint Resolve alpha_eq_lib_sym : slow.\n\n\nDefinition change_bvars_sobvars (vars : list sovar_sig) (vs : list NVar) : list sovar_sig :=\n  map (fun x => match x with\n                  | ((v1,n),v2) => (v2,n)\n                end)\n      (combine vars vs).\n\nDefinition change_bvars_abs {o} (disj : list NVar) (vars : list sovar_sig) (rhs : @SOTerm o) :=\n  let vs := fresh_distinct_vars (length vars) (disj ++ sovars2vars vars ++ all_fo_vars rhs) in\n  let vars' := change_bvars_sobvars vars vs in\n  let rhs' := soswap (mk_soswapping vars vs) rhs in\n  (vars', fo_change_bvars_alpha disj [] rhs').\n\nLemma rename_so_vars_mk_soren_spec1 :\n  forall vs1 vs2 v n,\n    length vs1 = length vs2 ->\n    {v' : NVar & rename_sovar (mk_soren vs1 vs2) (v, n) = (v',n)\n               # ((LIn (v,n) vs1\n                   # LIn v' vs2\n                   # LIn ((v,n),v') (mk_soren vs1 vs2))\n                  [+]\n                  (!LIn (v,n) vs1\n                   # v = v'))}.\nProof.\n  induction vs1; destruct vs2; introv len; allsimpl; cpx.\n  - exists v; simpl; sp; right; sp.\n  - destruct a.\n    rw rename_sovar_cons; boolvar; cpx.\n    + exists n; sp.\n    + pose proof (IHvs1 vs2 v n0 len) as h; exrepnd.\n      exists v'; dands; auto.\n      dorn h0; repnd; subst.\n      * left; dands; tcsp.\n      * right; rw not_over_or; sp.\nQed.\n\nLemma wf_soterm_soswap {o} :\n  forall (t : @SOTerm o) sw,\n    wf_soterm t <=> wf_soterm (soswap sw t).\nProof.\n  soterm_ind t as [v ts ind|op bs ind] Case;\n  introv; allsimpl.\n\n  - Case \"sovar\".\n    allrw @wf_sovar; split; intro k; introv i.\n    + allrw in_map_iff; exrepnd; subst.\n      apply ind; auto.\n    + pose proof (k (soswap sw t)) as h.\n      autodimp h hyp.\n      { rw in_map_iff; eexists; eauto. }\n      apply ind in h; auto.\n\n  - Case \"soterm\".\n    allrw @wf_soterm_iff; allrw map_map; unfold compose.\n    split; intro k; repnd; dands; auto.\n\n    + rw <- k0.\n      apply eq_maps; introv i.\n      destruct x; simpl.\n      rw length_soswapbvars; auto.\n\n    + introv i; allrw in_map_iff; exrepnd; subst.\n      destruct a; allsimpl; ginv.\n      applydup k in i1.\n      eapply ind in i1; apply i1; auto.\n\n    + rw <- k0.\n      apply eq_maps; introv i.\n      destruct x; simpl.\n      rw length_soswapbvars; auto.\n\n    + introv i.\n      pose proof (k (soswapbvars sw vs) (soswap sw t)) as h.\n      autodimp h hyp.\n      { rw in_map_iff; eexists; eauto. }\n      eapply ind in i; apply i in h; auto.\nQed.\n\nLemma soswapvar_eta :\n  forall sw v n,\n    (sovar2var (soswapvar sw (v, n)), n)\n    = soswapvar sw (v, n).\nProof.\n  induction sw; introv; simpl; auto.\n  destruct a.\n  destruct p; simpl.\n  unfold onesoswapvar; boolvar; cpx.\nQed.\n\nLemma sovar2var_soswapvars_eq :\n  forall vs1 vs2 (v1 v2 : NVar),\n    !LIn v1 vs2\n    -> !LIn v2 vs2\n    -> no_repeats vs2\n    -> sovar2var (soswapvar (mk_soswapping vs1 vs2) (var2sovar v1))\n       = sovar2var (soswapvar (mk_soswapping vs1 vs2) (var2sovar v2))\n    -> v1 = v2.\nProof.\n  induction vs1; destruct vs2; introv ni1 ni2 norep e;\n  allsimpl; tcsp; GC.\n  - destruct a; allsimpl; auto.\n  - destruct a; allsimpl.\n    allrw no_repeats_cons; repnd.\n    allrw not_over_or; repnd.\n    unfold onesoswapvar in e; boolvar; allunfold var2sovar; cpx;\n    apply IHvs1 in e; auto; subst; sp.\nQed.\n\nLemma so_free_vars_soswap {o} :\n  forall (t : @SOTerm o) vs1 vs2,\n    disjoint vs2 (sovars2vars vs1)\n    -> disjoint vs2 (all_fo_vars t)\n    -> no_repeats vs2\n    -> so_free_vars (soswap (mk_soswapping vs1 vs2) t)\n       = map (soswapvar (mk_soswapping vs1 vs2)) (so_free_vars t).\nProof.\n  soterm_ind t as [v ts ind|op bs ind] Case;\n  introv disj1 disj2 norep; allsimpl.\n\n  - Case \"sovar\".\n    allrw map_length.\n    allrw map_flat_map.\n    allrw flat_map_map; unfold compose.\n    rw soswapvar_eta.\n    f_equal.\n    apply eq_flat_maps; auto.\n    allrw disjoint_cons_r; repnd.\n    introv i.\n    disj_flat_map.\n    apply ind; auto.\n\n  - Case \"soterm\".\n    rw flat_map_map; rw map_flat_map; unfold compose.\n    apply eq_flat_maps; introv i.\n    destruct x as [l t]; simpl.\n    disj_flat_map; allsimpl.\n    allrw disjoint_app_r; repnd.\n    erewrite ind; eauto.\n    pose proof (sovars2vars_so_free_vars_subvars_all_fo_vars t) as sv.\n    pose proof (subvars_disjoint_r\n                  (sovars2vars (so_free_vars t))\n                  (all_fo_vars t)\n                  vs2) as d.\n    repeat (autodimp d hyp).\n    remember (so_free_vars t) as fv.\n\n    clear ind i op.\n    clear dependent t.\n    clear dependent bs.\n    induction fv; simpl.\n    + allrw remove_so_vars_nil_r; auto.\n    + allsimpl; allrw disjoint_cons_r; repnd.\n      allrw remove_so_vars_cons_r; simpl; rw IHfv; auto; clear IHfv.\n      boolvar; allsimpl; tcsp; provefalse.\n      * destruct a as [v m].\n        rw <- soswapvar_eta in l0.\n        allrw in_vars2sovars; repnd; subst; allsimpl.\n        allrw in_soswapbvars; exrepnd.\n        apply disjoint_sym in i1.\n        applydup i1 in l1.\n        apply sovar2var_soswapvars_eq in l0; auto; subst; sp.\n      * destruct a as [v m].\n        rw <- soswapvar_eta in n.\n        allrw in_vars2sovars; repnd; subst; allsimpl.\n        destruct n; dands; auto.\n        rw in_soswapbvars.\n        exists v; auto.\nQed.\n\nLemma rename_sovar_is_soswapvar :\n  forall vs1 vs2 v,\n    disjoint vs2 (sovars2vars vs1)\n    -> no_repeats vs2\n    -> !LIn (sovar2var v) vs2\n    -> rename_sovar (mk_soren vs1 vs2) v\n       = soswapvar (mk_soswapping vs1 vs2) v.\nProof.\n  induction vs1; destruct vs2; introv disj norep ni; allsimpl; tcsp; GC.\n  - destruct a; auto.\n  - destruct a; simpl.\n    rw rename_sovar_cons.\n    allrw not_over_or; repnd.\n    allrw disjoint_cons_l; allrw disjoint_cons_r; repnd.\n    allrw no_repeats_cons; repnd.\n    allsimpl; allrw not_over_or; repnd.\n    unfold onesoswapvar.\n    boolvar; subst; cpx.\n    rw soswapvar_not_in; auto.\nQed.\n\nLemma get_utokens_soswap {o} :\n  forall s (t : @SOTerm o),\n    get_utokens_so (soswap s t) = get_utokens_so t.\nProof.\n  soterm_ind t as [v ts ind|op bs ind] Case; introv; allsimpl.\n\n  - Case \"sovar\".\n    rw flat_map_map; unfold compose.\n    apply eq_flat_maps; auto.\n\n  - Case \"soterm\".\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.\nQed.\n\nLemma correct_change_bvars_entry {o} :\n  forall (disj    : list NVar)\n         (opabs   : opabs)\n         (vars    : list sovar_sig)\n         (rhs     : @SOTerm o)\n         (correct : correct_abs opabs vars rhs),\n    match change_bvars_abs disj vars rhs with\n      | (vars', rhs') => correct_abs opabs vars' rhs'\n    end.\nProof.\n  introv correct.\n  simpl.\n\n  pose proof (fresh_distinct_vars_spec\n                (length vars)\n                (disj ++ sovars2vars vars ++ all_fo_vars rhs))\n    as h; simpl in h; repnd.\n  remember (fresh_distinct_vars\n              (length vars)\n              (disj ++ sovars2vars vars ++ all_fo_vars rhs))\n    as fv; clear Heqfv.\n  allrw disjoint_app_r; repnd.\n\n  allunfold @correct_abs; repnd; dands; auto.\n\n  - apply wf_soterm_fo_change_bvars_alpha; auto.\n    apply wf_soterm_soswap; auto.\n\n  - allunfold @socovered.\n    rw @so_free_vars_fo_change_bvars_alpha; simpl.\n    rw map_rename_sovar_nil.\n    rw @so_free_vars_soswap; auto.\n    unfold change_bvars_sobvars.\n    allrw subsovars_prop; introv i.\n    allrw in_map_iff; exrepnd; subst.\n    applydup correct1 in i1 as j.\n    destruct a as [v n].\n    exists ((v,n),fst (soswapvar (mk_soswapping vars fv) (v,n))); simpl.\n\n    pose proof (rename_so_vars_mk_soren_spec1 vars fv v n) as s.\n    autodimp s hyp; exrepnd.\n    rw rename_sovar_is_soswapvar in s1; allsimpl; auto.\n    + rw s1; simpl; dands; auto.\n      dorn s0; tcsp.\n    + intro k.\n      apply h3 in k; destruct k.\n      rw in_sovars2vars.\n      eexists; eauto.\n\n  - pose proof (fo_change_bvars_alpha_spec\n                  disj (soswap (mk_soswapping vars fv) rhs)) as k.\n    simpl in k; repnd.\n    unfold no_utokens.\n    apply get_utokens_so_soalphaeq in k; rw <- k.\n    rw @get_utokens_soswap; auto.\nDefined.\n\nDefinition change_bvars_alpha_entry {o} (disj : list NVar) (entry : @library_entry o) : @library_entry o.\nProof.\n  destruct entry.\n  pose proof (correct_change_bvars_entry disj opabs vars rhs correct) as h.\n  destruct (change_bvars_abs disj vars rhs).\n  exact (lib_abs opabs l s h).\nDefined.\n\n(*\nDefinition change_bvars_alpha_entry {o} (lv : list NVar) (entry : @library_entry o) :=\n  match entry with\n    | lib_abs opabs vars rhs correct =>\n      match change_bvars_alphabt lv (bterm vars rhs) with\n        | bterm vars' rhs' =>\n          lib_abs\n            opabs\n            vars'\n            rhs'\n            (correct_change_bvars_entry lv opabs vars rhs correct)\n      end\n  end.\n*)\n\nFixpoint change_bvars_alpha_lib {o} (lv : list NVar) (lib : @library o) :=\n  match lib with\n    | [] => []\n    | entry :: lib =>\n      change_bvars_alpha_entry lv entry\n      :: change_bvars_alpha_lib lv lib\n  end.\n\nLemma sovars2vars_change_bvars_sobvars :\n  forall vs1 vs2,\n    length vs1 = length vs2\n    -> sovars2vars (change_bvars_sobvars vs1 vs2) = vs2.\nProof.\n  induction vs1; destruct vs2; introv len; allsimpl; cpx.\n  destruct a; simpl.\n  f_equal.\n  fold (change_bvars_sobvars vs1 vs2); auto.\nQed.\n\nDefinition soren_range (ren : soren) : list NVar := map (fun v => snd v) ren.\n\nLemma soren_range_app :\n  forall ren1 ren2,\n    soren_range (ren1 ++ ren2) = soren_range ren1 ++ soren_range ren2.\nProof.\n  introv; unfold soren_range; rw map_app; auto.\nQed.\n\nLemma soren_range_mk_soren :\n  forall vs1 vs2,\n    length vs1 = length vs2\n    -> soren_range (mk_soren vs1 vs2) = vs2.\nProof.\n  induction vs1; destruct vs2; introv len; allsimpl; cpx.\n  rw IHvs1; auto.\nQed.\n\nDefinition foren_range (ren : foren) : list NVar := map (fun v => snd v) ren.\n\nLemma foren_range_app :\n  forall ren1 ren2,\n    foren_range (ren1 ++ ren2) = foren_range ren1 ++ foren_range ren2.\nProof.\n  introv; unfold foren_range; rw map_app; auto.\nQed.\n\nLemma foren_range_mk_foren :\n  forall vs1 vs2,\n    length vs1 = length vs2\n    -> foren_range (mk_foren vs1 vs2) = vs2.\nProof.\n  induction vs1; destruct vs2; introv len; allsimpl; cpx.\n  rw IHvs1; auto.\nQed.\n\nLemma disjoint_fo_bound_vars_so_change_bvars_alpha {o} :\n  forall (t : @SOTerm o) ren d,\n    disjoint d (soren_range ren)\n    -> disjoint d (fo_bound_vars (so_change_bvars_alpha d ren t)).\nProof.\n  soterm_ind t as [v ts ind|op bs ind] Case; introv disj;\n  allsimpl; allrw flat_map_map; unfold compose;\n  rw disjoint_flat_map_r; introv i.\n\n  - Case \"sovar\".\n    apply ind; auto.\n\n  - Case \"soterm\".\n    destruct x as [l t]; simpl.\n    pose proof (fresh_distinct_vars_spec\n                  (length l)\n                  (d ++ all_fo_vars t ++ soren_vars ren))\n         as h; simpl in h; repnd.\n    remember (fresh_distinct_vars\n                (length l)\n                (d ++ all_fo_vars t ++ soren_vars ren))\n      as fv; clear Heqfv.\n    allrw disjoint_app_r; repnd; dands; eauto with slow.\n\n    eapply ind; eauto.\n    rw soren_range_app.\n    rw disjoint_app_r; dands; auto.\n    rw soren_range_mk_soren; eauto with slow.\n    rw length_vars2sovars; auto.\nQed.\n\nLemma disjoint_fo_bound_vars_fo_change_bvars_alpha {o} :\n  forall (t : @SOTerm o) ren d,\n    disjoint d (foren_range ren)\n    -> disjoint d (fo_bound_vars (fo_change_bvars_alpha d ren t)).\nProof.\n  soterm_ind t as [v ts ind|op bs ind] Case; introv disj;\n  allsimpl; allrw flat_map_map; unfold compose.\n\n  - Case \"sovar\".\n    boolvar; subst; allsimpl; auto.\n    rw disjoint_flat_map_r; introv i.\n    allrw in_map_iff; exrepnd; subst.\n    apply ind; auto.\n\n  - Case \"soterm\".\n    rw disjoint_flat_map_r; introv i.\n    destruct x as [l t]; simpl.\n    pose proof (fresh_distinct_vars_spec\n                  (length l)\n                  (l ++ d ++ all_fo_vars t ++ foren_vars ren))\n         as h; simpl in h; repnd.\n    remember (fresh_distinct_vars\n                (length l)\n                (l ++ d ++ all_fo_vars t ++ foren_vars ren))\n      as fv; clear Heqfv.\n    allrw disjoint_app_r; repnd; dands; eauto with slow.\n\n    eapply ind; eauto.\n    rw foren_range_app.\n    rw disjoint_app_r; dands; auto.\n    rw foren_range_mk_foren; eauto with slow.\nQed.\n\nLemma length_change_bvars_sobvars :\n  forall vs1 vs2,\n    length vs1 = length vs2\n    -> length (change_bvars_sobvars vs1 vs2) = length vs1.\nProof.\n  introv len.\n  unfold change_bvars_sobvars.\n  rw map_length.\n  rw @length_combine_eq; auto.\nQed.\n\nLemma matching_sovars_change_bvars_sobvars :\n  forall vars vs,\n    length vars = length vs\n    -> matching_sovars vars (change_bvars_sobvars vars vs).\nProof.\n  induction vars; destruct vs; introv len; allsimpl; cpx.\n  destruct a.\n  unfold change_bvars_sobvars; simpl.\n  fold (change_bvars_sobvars vars vs).\n  unfold matching_sovars; simpl.\n  f_equal.\n  apply IHvars; auto.\nQed.\nHint Resolve matching_sovars_change_bvars_sobvars : slow.\n\nTactic Notation \"arw\" constr(T) := repeat (onerw T; auto).\n\nLemma soswapvar_soswapvar :\n  forall vs1 vs2 vs v,\n    disjoint vs2 vs\n    -> disjoint vs2 (sovars2vars vs1)\n    -> disjoint vs (sovars2vars vs1)\n    -> no_repeats vs2\n    -> no_repeats vs\n    -> !LIn (sovar2var v) vs\n    -> !LIn (sovar2var v) vs2\n    -> length vs1 = length vs2\n    -> length vs1 = length vs\n    -> soswapvar (mk_soswapping vs1 vs2) v\n       = soswapvar (mk_soswapping (change_bvars_sobvars vs1 vs) vs2)\n                   (soswapvar (mk_soswapping vs1 vs) v).\nProof.\n  induction vs1; destruct vs2, vs;\n  introv disj1 disj2 disj3 norep1 norep2 ni1 ni2 len1 len2;\n  allsimpl; cpx.\n  allrw disjoint_cons_r; allrw disjoint_cons_l; repnd; allsimpl.\n  allrw no_repeats_cons; repnd.\n  allrw not_over_or; repnd.\n  destruct a as [x m]; allsimpl.\n  destruct v as [y k]; allsimpl.\n  try (fold (change_bvars_sobvars vs1 vs)).\n  destruct (sovar_sig_dec (x,m) (y,k)) as [i|i]; cpx.\n  - allrw onesoswapvar_eq.\n    rw soswapvar_not_in; auto.\n    rw soswapvar_not_in; auto.\n    rw onesoswapvar_eq.\n    rw soswapvar_not_in; auto.\n    rw sovars2vars_change_bvars_sobvars; auto.\n  - rw (onesoswapvar_not_in2 x n); auto; try (complete (sp; cpx)).\n    rw (onesoswapvar_not_in2 x n0); auto; try (complete (sp; cpx)).\n    rw onesoswapvar_not_in2; auto.\n    + intro h.\n      destruct (in_deq sovar_sig sovar_sig_dec (y,k) vs1) as [j|j].\n      * pose proof (soswapvar_in vs1 vs (y,k)) as ivs;\n        repeat (autodimp ivs hyp).\n        rw h in ivs; allsimpl; sp.\n      * rw soswapvar_not_in2 in h; auto; cpx.\n    + intro h.\n      destruct (in_deq sovar_sig sovar_sig_dec (y,k) vs1) as [j|j].\n      * pose proof (soswapvar_in vs1 vs (y,k)) as ivs;\n        repeat (autodimp ivs hyp).\n        rw h in ivs; allsimpl; sp.\n      * rw soswapvar_not_in2 in h; auto; cpx.\nQed.\n\nLemma soswapbvars_soswapbvars :\n  forall vs1 vs2 vs l,\n    disjoint vs2 vs\n    -> disjoint vs2 (sovars2vars vs1)\n    -> disjoint vs (sovars2vars vs1)\n    -> disjoint vs2 l\n    -> disjoint vs l\n    -> no_repeats vs2\n    -> no_repeats vs\n    -> length vs1 = length vs2\n    -> length vs1 = length vs\n    -> soswapbvars (mk_soswapping (change_bvars_sobvars vs1 vs) vs2)\n                   (soswapbvars (mk_soswapping vs1 vs) l)\n       = soswapbvars (mk_soswapping vs1 vs2) l.\nProof.\n  induction l;\n  introv disj1 disj2 disj3 disj4 disj5 norep1 norep2 len1 len2;\n  allsimpl; auto.\n  destruct a as [v n].\n  unfold var2sovar; simpl.\n  rw soswapvar_eta.\n  allrw disjoint_cons_r; repnd.\n  rw <- soswapvar_soswapvar; allsimpl; auto.\n  rw IHl; auto.\nQed.\n\nLemma so_alphaeq_soswap_so_change_bvars_alpha {o} :\n  forall (t : @SOTerm o) vs1 vs2 vs,\n    disjoint vs2 vs\n    -> disjoint vs2 (sovars2vars vs1)\n    -> disjoint vs (sovars2vars vs1)\n    -> disjoint vs2 (all_fo_vars t)\n    -> disjoint vs (all_fo_vars t)\n    -> no_repeats vs2\n    -> no_repeats vs\n    -> length vs1 = length vs2\n    -> length vs1 = length vs\n    -> so_alphaeq (soswap (mk_soswapping vs1 vs2) t)\n                  (soswap (mk_soswapping (change_bvars_sobvars vs1 vs) vs2)\n                          (soswap (mk_soswapping vs1 vs) t)).\nProof.\n  soterm_ind1s t as [v ts ind|op bs ind] Case;\n  introv disj1 disj2 disj3 disj4 disj5;\n  introv norep1 norep2 len1 len2;\n  allsimpl.\n\n  - Case \"sovar\".\n    allrw disjoint_cons_r; repnd.\n    allrw map_length.\n    allrw map_map; unfold compose.\n    rw soswapvar_eta.\n    rw <- soswapvar_soswapvar; auto.\n    constructor; allrw map_length; auto.\n    introv i.\n    allrw <- @map_combine; allrw in_map_iff; exrepnd; cpx.\n    allrw in_combine_same; repnd; subst; allsimpl.\n    disj_flat_map; allsimpl.\n    apply ind; auto.\n\n  - Case \"soterm\".\n    constructor; allrw map_length; 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    rw combine_map_l in i1.\n    rw in_map_iff in i1; exrepnd; cpx; allsimpl.\n    ginv.\n    disj_flat_map; allsimpl; allrw disjoint_app_r; repnd.\n\n    pose proof (fresh_vars\n                  (length l1)\n                  (l1\n                     ++ vs2\n                     ++ sovars2vars vs1\n                     ++ all_fo_vars t1\n                     ++ all_fo_vars (soswap (mk_soswapping vs1 vs) t1)\n                     ++ sovars2vars (change_bvars_sobvars vs1 vs)\n                     ++ soswapbvars (mk_soswapping vs1 vs) l1\n                     ++ soswapbvars (mk_soswapping vs1 vs2) l1\n                     ++ soswapbvars (mk_soswapping (change_bvars_sobvars vs1 vs) vs2) (soswapbvars (mk_soswapping vs1 vs) l1)\n                     ++ all_fo_vars (soswap (mk_soswapping vs1 vs2) t1)\n                     ++ all_fo_vars (soswap (mk_soswapping (change_bvars_sobvars vs1 vs) vs2)\n                                            (soswap (mk_soswapping vs1 vs) t1))\n               )) as fv; exrepnd.\n    allrw disjoint_app_r; repnd.\n\n    apply (soaeqbt _ lvn); allsimpl; allrw length_soswapbvars; auto; try omega.\n\n    + allrw disjoint_app_r; dands; auto.\n\n    + rw @so_swap_soswap; auto.\n      rw soswapbvars_soswapbvars; auto.\n\n      pose proof (ind\n                    t1 t1\n                    l1\n                    i1\n                    (le_refl (sosize t1))\n                    vs1 vs2 vs\n                 ) as h.\n      repeat (autodimp h hyp).\n\n      apply (so_alphaeq_add_so_swap2\n               (soswapbvars (mk_soswapping vs1 vs2) l1)\n               lvn) in h;\n        auto; allsimpl; allrw length_soswapbvars; auto; try omega;\n        try (complete (allrw disjoint_app_r; dands; auto)).\n\n      eapply so_alphaeq_trans;[|exact h]; clear h.\n\n      rw @so_swap_soswap; auto.\nQed.\n\nLemma change_bvars_alpha_entry_spec {p} :\n  forall (lv : list NVar) (entry : @library_entry p),\n    let entry' := change_bvars_alpha_entry lv entry in\n    disjoint lv (sovars2vars (bound_vars_entry entry'))\n    # alpha_eq_entry entry entry'.\nProof.\n  introv; simpl.\n  destruct entry; simpl.\n  rw sovars2vars_app.\n  rw disjoint_app_r.\n  unfold so_bound_vars.\n  rw sovars2vars_vars2sovars.\n  pose proof (fresh_distinct_vars_spec\n                (length vars)\n                (lv ++ sovars2vars vars ++ all_fo_vars rhs))\n    as h; simpl in h; repnd.\n  dands; auto.\n\n  - remember (fresh_distinct_vars\n                (length vars)\n                (lv ++ sovars2vars vars ++ all_fo_vars rhs)) as fv;\n    clear Heqfv.\n    allrw disjoint_app_r; repnd.\n    rw sovars2vars_change_bvars_sobvars; eauto with slow.\n\n  - remember (fresh_distinct_vars\n                (length vars)\n                (lv ++ sovars2vars vars ++ all_fo_vars rhs)) as fv;\n    clear Heqfv.\n    allrw disjoint_app_r; repnd.\n    apply disjoint_fo_bound_vars_fo_change_bvars_alpha; simpl; auto.\n\n  - pose proof (fresh_vars\n                  (length vars)\n                  (sovars2vars vars\n                               ++ sovars2vars (change_bvars_sobvars vars\n                                                                    (fresh_distinct_vars\n                                                                       (length vars)\n                                                                       (lv ++ sovars2vars vars ++ all_fo_vars rhs)))\n                               ++ all_fo_vars rhs\n                               ++ all_fo_vars (fo_change_bvars_alpha\n                                                 lv []\n                                                 (soswap\n                                                    (mk_soswapping\n                                                       vars\n                                                       (fresh_distinct_vars\n                                                          (length vars)\n                                                          (lv ++ sovars2vars vars ++ all_fo_vars rhs)))\n                                                    rhs))\n                               ++ all_fo_vars (soswap (mk_soswapping vars (fresh_distinct_vars\n                                                                             (length vars)\n                                                                             (lv ++ sovars2vars vars ++ all_fo_vars rhs)))\n                                                      rhs)\n               )) as fv.\n    exrepnd.\n    allrw disjoint_app_r; repnd.\n    apply (aeq_lib_entry lvn); eauto with slow.\n\n    + remember (fresh_distinct_vars\n                  (length vars)\n                  (lv ++ sovars2vars vars ++ all_fo_vars rhs)) as fv;\n      clear Heqfv.\n      rw length_change_bvars_sobvars; auto.\n\n    + allrw disjoint_app_r; dands; auto.\n\n    + remember (fresh_distinct_vars\n                  (length vars)\n                  (lv ++ sovars2vars vars ++ all_fo_vars rhs)) as fv;\n      clear Heqfv.\n      arw sovars2vars_change_bvars_sobvars.\n\n      pose proof (so_alphaeq_fo_change_bvars_alpha2\n                    (soswap (mk_soswapping vars fv) rhs)\n                    lv) as aeq.\n      apply (so_alphaeq_soswap _ _ (change_bvars_sobvars vars fv) lvn) in aeq;\n        auto; arw sovars2vars_change_bvars_sobvars; auto.\n      eapply so_alphaeq_trans;[|exact aeq]; clear aeq.\n      apply so_alphaeq_soswap_so_change_bvars_alpha; auto.\nQed.\n\nLemma change_bvars_alpha_lib_spec {p} :\n  forall lv (lib : @library p),\n    let lib' := change_bvars_alpha_lib lv lib in\n    disjoint lv (sovars2vars (bound_vars_lib lib')) # alpha_eq_lib lib lib'.\nProof.\n  induction lib; simpl; tcsp; allsimpl; repnd.\n  pose proof (change_bvars_alpha_entry_spec lv a) as h; simpl in h; repnd.\n  allrw sovars2vars_app.\n  rw disjoint_app_r; dands; auto.\n  constructor; auto.\nQed.\n\nLemma change_bvars_alpha_eq_lib {o} :\n  forall lv lib,\n    {lib' : @library o\n     & disjoint lv (sovars2vars (bound_vars_lib lib'))\n     # alpha_eq_lib lib lib'}.\nProof.\n  introv.\n  exists (change_bvars_alpha_lib lv lib).\n  apply change_bvars_alpha_lib_spec.\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/library_alpha.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.28384064679576765}}
{"text": "Require Import AutoSep Malloc Sets.\nRequire Import TimeAbstract.\n\nSet Implicit Arguments.\n\n\nLocal Hint Extern 3 (himp _ _) => apply himp_star_frame.\nLocal Hint Extern 3 (himp _ _) => apply himp_star_frame_comm.\n\nModule Type USL. (* For \"unsorted list\" *)\n\n  Parameter usl' : set -> nat -> W -> HProp.\n  Parameter usl : set -> W -> HProp.\n\n  Axiom usl'_extensional : forall s n p, HProp_extensional (usl' s n p).\n  Axiom usl_extensional : forall s p, HProp_extensional (usl s p).\n\n  Axiom usl'_set_extensional : forall n s s' p, s %= s' -> usl' s n p ===> usl' s' n p.\n\n  Axiom usl_fwd : forall s p, usl s p ===> [| freeable p 2 |]\n    * Ex n, Ex r, Ex junk, p =*> r * (p ^+ $4) =*> junk * usl' s n r.\n  Axiom usl_bwd : forall s p, ([| freeable p 2 |]\n    * Ex n, Ex r, Ex junk, p =*> r * (p ^+ $4) =*> junk * usl' s n r) ===> usl s p.\n\n  Axiom nil_fwd : forall s n (p : W), p = 0 -> usl' s n p ===> [| s %= empty /\\ n = O |].\n  Axiom nil_bwd : forall s n (p : W), p = 0 -> [| s %= empty /\\ n = O |] ===> usl' s n p.\n\n  Axiom cons_fwd : forall s n (p : W), p <> 0 -> usl' s n p ===>\n    Ex n', Ex v, Ex p', (p ==*> v, p') * usl' (s %- v) n' p'\n    * [| freeable p 2 /\\ n = S n' /\\ v %in s |].\n\n  Axiom cons_bwd : forall s n (p : W), p <> 0 ->\n    (Ex n', Ex v, Ex p', (p ==*> v, p') * usl' (s %- v) n' p'\n      * [| freeable p 2 /\\ n = S n' /\\ v %in s |]) ===> usl' s n p.\nEnd USL.\n\nModule Usl : USL.\n  Open Scope Sep_scope.\n\n  Fixpoint usl' (s : set) (n : nat) (p : W) : HProp :=\n    match n with\n      | O => [| p = 0 /\\ s %= empty |]\n      | S n' => [| p <> 0 /\\ freeable p 2 |] * Ex v, Ex p', (p ==*> v, p')\n        * usl' (s %- v) n' p' * [| v %in s |]\n    end.\n\n  Definition usl (s : set) (p : W) := [| freeable p 2 |]\n    * Ex n, Ex r, Ex junk, p =*> r * (p ^+ $4) =*> junk * usl' s n r.\n\n  Theorem usl'_extensional : forall s n p, HProp_extensional (usl' s n p).\n    destruct n; reflexivity.\n  Qed.\n\n  Theorem usl_extensional : forall s p, HProp_extensional (usl s p).\n    reflexivity.\n  Qed.\n\n  Theorem usl'_set_extensional : forall n s s' p, s %= s' -> usl' s n p ===> usl' s' n p.\n    induction n; sepLemma.\n  Qed.\n\n  Theorem usl_fwd : forall s p, usl s p ===> [| freeable p 2 |]\n    * Ex n, Ex r, Ex junk, p =*> r * (p ^+ $4) =*> junk * usl' s n r.\n    unfold usl; sepLemma.\n  Qed.\n\n  Theorem usl_bwd : forall s p, ([| freeable p 2 |]\n    * Ex n, Ex r, Ex junk, p =*> r * (p ^+ $4) =*> junk * usl' s n r) ===> usl s p.\n    unfold usl; sepLemma.\n  Qed.\n\n  Theorem nil_fwd : forall s n (p : W), p = 0 -> usl' s n p ===> [| s %= empty /\\ n = O |].\n    destruct n; sepLemma.\n  Qed.\n\n  Theorem nil_bwd : forall s n (p : W), p = 0 -> [| s %= empty /\\ n = O |] ===> usl' s n p.\n    destruct n; sepLemma.\n  Qed.\n\n  Theorem cons_fwd : forall s n (p : W), p <> 0 -> usl' s n p ===>\n    Ex n', Ex v, Ex p', (p ==*> v, p') * usl' (s %- v) n' p'\n    * [| freeable p 2 /\\ n = S n' /\\ v %in s |].\n    destruct n; sepLemma.\n  Qed.\n\n  Theorem cons_bwd : forall s n (p : W), p <> 0 ->\n    (Ex n', Ex v, Ex p', (p ==*> v, p') * usl' (s %- v) n' p'\n      * [| freeable p 2 /\\ n = S n' /\\ v %in s |]) ===> usl' s n p.\n    destruct n; sepLemma;\n      match goal with\n        | [ H : S _ = S _ |- _ ] => injection H; sepLemma\n      end.\n  Qed.\nEnd Usl.\n\nImport Usl.\nExport Usl.\nHint Immediate usl_extensional usl'_extensional.\n\n(*TIME Clear Timing Profile. *)\n\nDefinition hints : TacPackage.\n(*TIME idtac \"tree-set:prepare1\". Time *)\n  prepare (usl_fwd, nil_fwd, cons_fwd) (usl_bwd, nil_bwd, cons_bwd).\n(*TIME Time *)Defined.\n\nDefinition initS := initS usl 7.\nDefinition lookupS := lookupS usl 1.\nDefinition addS := addS usl 8.\nDefinition removeS := removeS usl 6.\n\nDefinition uslM := bimport [[ \"malloc\"!\"malloc\" @ [mallocS], \"malloc\"!\"free\" @ [freeS] ]]\n  bmodule \"usl\" {{\n  bfunction \"init\"(\"r\") [initS]\n    \"r\" <-- Call \"malloc\"!\"malloc\"(0)\n    [PRE[_, R] R =?> 2 * [| freeable R 2 |]\n     POST[R'] [| R' = R |] * usl empty R ];;\n    \"r\" *<- 0;;\n    Return \"r\"\n  end with bfunction \"lookup\"(\"s\", \"k\", \"tmp\") [lookupS]\n    \"s\" <-* \"s\";;\n\n    [Al s, Al n,\n      PRE[V] usl' s n (V \"s\")\n      POST[R] [| (V \"k\" %in s) \\is R |] * usl' s n (V \"s\")]\n    While (\"s\" <> 0) {\n      \"tmp\" <-* \"s\";;\n      If (\"tmp\" = \"k\") {\n        Return 1\n      } else {\n        \"s\" <- \"s\" + 4;;\n        \"s\" <-* \"s\"\n      }\n    };;\n\n    Return 0\n  end with bfunction \"add\"(\"s\", \"k\", \"tmp\", \"tmp2\") [addS]\n    \"tmp\" <-- Call \"usl\"!\"lookup\"(\"s\", \"k\")\n    [Al s,\n      PRE[V, R] [| (V \"k\" %in s) \\is R |] * usl s (V \"s\") * mallocHeap\n      POST[R'] usl (s %+ V \"k\") (V \"s\") * mallocHeap];;\n\n    If (\"tmp\" = 1) {\n      Return 0\n    } else {\n      \"tmp\" <-- Call \"malloc\"!\"malloc\"(0)\n      [Al p,\n        PRE[V, R] V \"s\" =*> p * R =?> 2\n        POST[_] V \"s\" =*> R * (R ==*> V \"k\", p) ];;\n\n      \"tmp\" *<- \"k\";;\n      \"k\" <- \"tmp\" + 4;;\n      \"tmp2\" <-* \"s\";;\n      \"k\" *<- \"tmp2\";;\n      \"s\" *<- \"tmp\";;\n      Return 0\n    }\n  end with bfunction \"remove\"(\"s\", \"k\", \"prev\", \"tmp\") [removeS]\n    \"prev\" <- \"s\";;\n    \"s\" <-* \"prev\";;\n\n    [Al s, Al n,\n      PRE[V] V \"prev\" =*> V \"s\" * usl' s n (V \"s\") * mallocHeap\n      POST[R] Ex p, Ex n', V \"prev\" =*> p * usl' (s %- V \"k\") n' p * mallocHeap]\n    While (\"s\" <> 0) {\n      \"tmp\" <-* \"s\";;\n      If (\"tmp\" = \"k\") {\n        \"tmp\" <- \"s\" + 4;;\n        \"tmp\" <-* \"tmp\";;\n        \"prev\" *<- \"tmp\";;\n\n        Call \"malloc\"!\"free\"(\"s\", 0)\n        [PRE[_] Emp\n         POST[_] Emp];;\n        Return 0\n      } else {\n        \"prev\" <- \"s\" + 4;;\n        \"s\" <-* \"prev\"\n      }\n    };;\n\n    Return 0\n  end\n}}.\n\nLocal Hint Extern 5 (@eq W _ _) => words.\nLocal Hint Extern 5 (@eq (word _) _ _) => words.\nLocal Hint Extern 3 (himp _ _) => apply usl'_set_extensional.\n\nLemma contradictory_membership : forall (s : set) v x,\n  x = natToW 1\n  -> x = natToW 0\n  -> s v.\n  intros; subst; discriminate.\nQed.\n\nHint Extern 1 => eapply contradictory_membership; eassumption.\n\nTheorem uslMOk : moduleOk uslM.\n(*TIME idtac \"tree-set:verify\". Time *)\n(*TIME  (time \"vcgen:all\" *) vcgen\n(*TIME ) *); time_abstract ltac:(sep hints; auto).\n(*TIME Time *)Qed.\n\n(*TIME Print Timing Profile. *)", "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/examples/ListSet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030761371502, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2838406397121607}}
{"text": "From iris.proofmode Require Import tactics.\nFrom iris Require Import base_logic.lib.invariants.\n\n(** if the goal [Q] can be duplicated out of an invariant, we can access it\nconveniently with this theorem (which weakens the normal invariant opening by\nhiding the ability to open further invariants) *)\nTheorem inv_dup_acc {Σ} `{!invGS Σ} (Q: iProp Σ) N E (P: iProp Σ) :\n  ↑N ⊆ E →\n  inv N P -∗\n  (P -∗ P ∗ Q) -∗\n  |={E}=> ▷ Q.\nProof.\n  iIntros (Hsub) \"Hinv HPtoQ\".\n  iInv \"Hinv\" as \"HP\" \"Hclose\".\n  iDestruct (\"HPtoQ\" with \"HP\") as \"[HP HQ]\".\n  iMod (\"Hclose\" with \"HP\") as \"_\".\n  iIntros \"!> !>\".\n  iFrame.\nQed.\n\n(** If the goal [Q] is persistent, we can derive it under a fupd by opening an\ninvariant and using the contents of the invariant without putting them back. In\npractice this only works for the timeless part of P, which is expressed by\ngiving the assumption [▷P] but also providing an \"except-0\" modality ◇ around\nthe goal (the later can be stripped from [P] for any timeless components).\n\n The reason this is sound is informally because [P -∗ Q] can be upgraded to\n [P -∗ P ∗ Q] because [Q] is persistent. *)\nLemma inv_open_persistent `{!invGS Σ} N E (P Q: iProp Σ) `{!Persistent Q} :\n  ↑N ⊆ E →\n  inv N P -∗\n  (▷ P -∗ ◇ Q) -∗\n  |={E}=> Q.\nProof.\n  iIntros (?) \"#Hinv HPQ\".\n  iInv \"Hinv\" as \"HP\".\n  iModIntro.\n  rewrite -fupd_except_0 -fupd_intro.\n  iSplit; [done|].\n  iApply (\"HPQ\" with \"[$]\").\nQed.\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/Helpers/iris.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2838160398109954}}
{"text": "Require Import DataTypes Coq.Lists.Streams Coq.Logic.Classical_Prop Tree List MsiState Coq.Relations.Relation_Operators.\n\nRecord BaseMesg :=\n  { fromB: State;\n    toB: State;\n    addrB: Addr;\n    dataBM: Data;\n    type: ChannelType\n  }.\n\nRecord GlobalState :=\n  { dt: Cache -> Addr -> Data;\n    ch: ChannelType -> Cache -> Cache -> list BaseMesg;\n    st: Cache -> Addr -> State;\n    dirSt: Cache -> Cache -> Addr -> State;\n    wt: Cache -> Addr -> bool;\n    wtS: Cache -> Addr -> State;\n    dirWt: Cache -> Cache -> Addr -> bool;\n    dirWtS: Cache -> Cache -> Addr -> State;\n    req: Addr -> Cache -> nat\n  }.\n\nDefinition dmy := Build_BaseMesg In In zero (initData zero) mch.\n\nInductive Transition (s: GlobalState) : GlobalState -> Set :=\n| LoadReq: forall {c a}, defined c -> leaf c -> desc (reqFn a c (req s a c)) = Ld ->\n                       sle Sh (st s c a) -> \n                       Transition s {|\n                                    dt := dt s;\n                                    ch := ch s;\n                                    st := st s;\n                                    dirSt := dirSt s;\n                                    wt := wt s;\n                                    wtS := wtS s;\n                                    dirWt := dirWt s;\n                                    dirWtS := dirWtS s;\n                                    req := fun w t => \n                                             match decAddr w a with\n                                               | left _ =>\n                                                   match decTree t c with\n                                                     | left _ => S (req s w t)\n                                                     | _ => req s w t\n                                                   end\n                                               | right _ => req s w t\n                                             end\n                                  |}\n| StoreReq: forall {c a}, defined c -> leaf c -> desc (reqFn a c (req s a c)) = St ->\n                        (st s c a = Mo) ->\n                        Transition s {|\n                                     dt := fun t w => match decTree t c with\n                                                      | left _ => match decAddr w a with\n                                                                    | left _ => dataQ (reqFn a t (req s w t))\n                                                                    | right _ => dt s t w\n                                                                  end\n                                                      | right _ => dt s t w\n                                                      end;\n                                     ch := ch s;\n                                     st := st s;\n                                     dirSt := dirSt s;\n                                     wt := wt s;\n                                     wtS := wtS s;\n                                     dirWt := dirWt s;\n                                     dirWtS := dirWtS s;\n                                     req := fun w t => \n                                             match decAddr w a with\n                                               | left _ =>\n                                                   match decTree t c with\n                                                     | left _ => S (req s w t)\n                                                     | _ => req s w t\n                                                   end\n                                               | right _ => req s w t\n                                             end\n                                   |}\n| ChildSendReq: forall {p c}, defined p -> defined c -> parent c p ->\n                              forall {x a}, slt (st s c a) x -> wt s c a = false ->\n                                            Transition s {|\n                                                         dt := dt s;\n                                                         ch := fun t w z =>\n                                                                 match t, decTree w c,\n                                                                       decTree z p with\n                                                                   | rch, left _, left _ =>\n                                                                       (Build_BaseMesg\n                                                                          (st s w a)\n                                                                          x a (initData zero) rch)\n                                                                         :: ch s t w z\n                                                                   | _, _, _ => ch s t w z\n                                                                 end;\n                                                         st := st s;\n                                                         dirSt := dirSt s;\n                                                         wt := fun t w => match decTree t c, decAddr w a with\n                                                                            | left _, left _ => true\n                                                                            | _, _ => wt s t w\n                                                                          end;\n                                                         wtS := fun t w => match decTree t c, decAddr w a with\n                                                                             | left _, left _ => x\n                                                                             | _, _ => wtS s t w\n                                                                           end;\n                                                         dirWt := dirWt s;\n                                                         dirWtS := dirWtS s;\n                                                         req := req s\n                                                       |}\n| ParentRecvReq: forall {p c}, defined p -> defined c -> parent c p ->\n                               ch s rch c p <> nil -> let r := last (ch s rch c p) dmy in\n                                                        let fromR := fromB r in\n                                                          let toR := toB r in\n                                                            let a := addrB r in\n                                                              sle toR (st s p a) ->\n                               (forall i, defined i -> i <> c -> parent i p ->\n                                          sle (dirSt s p i a)\n                                              match toR with\n                                                | Mo => In\n                                                | Sh => Sh\n                                                | In => Mo\n                                              end) ->\n                               dirWt s p c a = false ->\n                               sle (dirSt s p c a) fromR ->\n                               Transition s {| ch := fun t w z =>\n                                                       match t with\n                                                         | mch => match decTree w p,\n                                                                        decTree z c with\n                                                         | left _, left _ =>\n                                                             (Build_BaseMesg\n                                                                (dirSt s w z a) toR a (dt s w a) mch)\n                                                               :: ch s t w z\n                                                         | _, _ => ch s t w z\n                                                                  end\n                                                         | rch =>\n                                                             match decTree w c,\n                                                                   decTree z p with\n                                                               | left _, left _ => removelast\n                                                                                          (ch s t w z)\n                                                               | _, _ => ch s t w z\n                                                             end\n                                                       end;\n                                               dt := dt s;\n                                               st := st s;\n                                               dirSt := fun t w z => match decTree t p, decTree w c,\n                                                                           decAddr z a with\n                                                                       | left _, left _, left _ => toR\n                                                                       | _, _, _ => dirSt s t w z\n                                                                     end;\n                                               wt := wt s;\n                                               wtS := wtS s;\n                                               dirWt := dirWt s;\n                                               dirWtS := dirWtS s;\n                                               req := req s\n                                            |}\n| ChildRecvResp: forall {p c}, defined p -> defined c -> parent c p ->\n                               ch s mch p c <> nil ->\n                               let m := last (ch s mch p c) dmy in\n                                 let fromM := fromB m in\n                                   let toM := toB m in\n                                     let a := addrB m in\n                                       let d := dataBM m in\n                                       type m = mch ->\n                                         Transition s {| dt := fun t w =>\n                                                                 match decTree t c,\n                                                                       decAddr w a with\n                                                                   | left _, left _ =>\n                                                                     match fromB m with\n                                                                       | In => d\n                                                                       | _ => dt s t w\n                                                                     end\n                                                                   | _, _ => dt s t w\n                                                                 end;\n                                                         ch := fun t w z =>\n                                                                 match t, decTree w p,\n                                                                       decTree z c with\n                                                                   | mch, left _, left _ => removelast (ch s t w z)\n                                                                   | _, _, _ => ch s t w z\n                                                                 end;\n                                                         st := fun t w => match decTree t c, decAddr w a with\n                                                                            | left _, left _ => toM\n                                                                            | _, _ => st s t w\n                                                                          end;\n                                                         dirSt := dirSt s;\n                                                         wt := fun t w => match decTree t c, decAddr w a with\n                                                                            | left _, left _ =>\n                                                                                match decSle (wtS s t w) toM with\n                                                                                  | true => false\n                                                                                  | _ => wt s t w\n                                                                                end\n                                                                            | _, _ => wt s t w\n                                                                          end;\n                                                         wtS := wtS s;\n                                                         dirWt := dirWt s;\n                                                         dirWtS := dirWtS s;\n                                                         req := req s\n                                                      |}\n| ParentSendReq: forall {p c}, defined p -> defined c -> parent c p ->\n                               forall {x a}, slt x (dirSt s p c a) -> dirWt s p c a = false ->\n                                             Transition s {|\n                                                          dt := dt s;\n                                                          ch := fun t w z =>\n                                                                  match t, decTree w p,\n                                                                        decTree z c with\n                                                                    | mch, left _, left _ =>\n                                                                        (Build_BaseMesg\n                                                                           (dirSt s w z a)\n                                                                           x a (initData zero) rch)\n                                                                          :: ch s t w z\n                                                                    | _, _, _ => ch s t w z\n                                                                  end;\n                                                          st := st s;\n                                                          dirSt := dirSt s;\n                                                          wt := wt s;\n                                                          wtS := wtS s;\n                                                          dirWt := fun t w z => match decTree t p, decTree w c,\n                                                                                      decAddr z a\n                                                                                with\n                                                                                  | left _, left _, left _ =>\n                                                                                      true\n                                                                                  | _, _, _ => dirWt s t w z\n                                                                                end;\n                                                          dirWtS := fun t w z => match decTree t p, decTree w c,\n                                                                                       decAddr z a with\n                                                                                   | left _, left _, left _ => x\n                                                                                   | _, _, _ => dirWtS s t w z\n                                                                                 end;\n                                                          req := req s\n\n                                                        |}\n| ChildRecvReq: forall {p c}, defined p -> defined c -> parent c p ->\n                              ch s mch p c <> nil ->\n                              let r := last (ch s mch p c) dmy in\n                                let fromR := fromB r in\n                                  let toR := toB r in\n                                    let a := addrB r in\n                                      let d := dataBM r in\n                                      type r = rch ->\n                                        slt toR (st s c a) ->\n                              (forall {i}, defined i -> parent i c -> sle (dirSt s c i a) toR) ->\n                              Transition s {| ch := fun t w z =>\n                                                      match t with\n                                                        | mch =>\n                                                          match decTree w c, decTree z p with\n                                                            | left _, left _ =>\n                                                              (Build_BaseMesg (st s w a) toR a\n                                                                              (dt s w a) mch)\n                                                                :: ch s t w z\n                                                            | left _, _ => ch s t w z\n                                                            | _, _ => match decTree w p,\n                                                                           decTree z c with\n                                                                       | left _, left _ =>\n                                                                         removelast (ch s t w z)\n                                                                       | _, _ => ch s t w z\n                                                                     end\n                                                          end\n                                                        | _ => ch s t w z\n                                                      end;\n                                              dt := dt s;\n                                              st := fun t w => match decTree t c, decAddr w a with\n                                                                 | left _, left _ => toR\n                                                                 | _, _ => st s t w\n                                                               end;\n                                              dirSt := dirSt s;\n                                              wt := wt s;\n                                              wtS := wtS s;\n                                              dirWt := dirWt s;\n                                              dirWtS := dirWtS s;\n                                              req := req s\n                                           |}\n| ParentRecvResp: forall {p c}, defined p -> defined c -> parent c p ->\n                                ch s mch c p <> nil ->\n                                let m := last (ch s mch c p) dmy in\n                                  let fromM := fromB m in\n                                    let toM := toB m in\n                                      let a := addrB m in\n                                        let d := dataBM m in\n                                        fromM = dirSt s p c a ->\n                                          Transition s {| dt := fun t w => match decTree t p, decAddr w a with\n                                                                             | left _, left _ =>\n                                                                                 match fromB m with\n                                                                                   | Mo => d\n                                                                                   | _ => dt s t w\n                                                                                 end\n                                                                             | _, _ => dt s t w\n                                                                           end;\n                                                          ch := fun t w z =>\n                                                                  match t, decTree w c,\n                                                                        decTree z p with\n                                                                    | mch, left _, left _ => removelast (ch s t w z)\n                                                                    | _, _, _ => ch s t w z\n                                                                  end;\n                                                          st := st s;\n                                                          dirSt := fun t w z => match decTree t p, decTree w c,\n                                                                                      decAddr z a with\n                                                                                  | left _, left _, left _ => toM\n                                                                                  | _, _, _ => dirSt s t w z\n                                                                                end;\n                                                          wt := wt s;\n                                                          wtS := wtS s;\n                                                          dirWt := fun t w z => match decTree t p, decTree w c,\n                                                                                      decAddr z a with\n                                                                                  | left _, left _, left _ =>\n                                                                                      match decSle toM (dirWtS s t w z)\n                                                                                      with\n                                                                                        | true => false\n                                                                                        | _ => dirWt s t w z\n                                                                                      end\n                                                                                  | _, _, _ => dirWt s t w z\n                                                                                end;\n                                                          dirWtS := dirWtS s;\n                                                          req := req s\n                                                       |}\n\n| ChildVolResp: forall {p c}, defined p -> defined c -> parent c p ->\n                              forall {x a},\n                                slt x (st s c a) ->\n                                (forall {i}, defined i -> parent i c -> sle (dirSt s c i a) x) ->\n                                wt s c a = false ->\n                                Transition s {| ch := fun t w z =>\n                                                        match t, decTree w c,\n                                                              decTree z p with\n                                                          | mch, left _, left _ =>\n                                                              (Build_BaseMesg\n                                                                 (st s w a) x a (dt s w a) mch)\n                                                                :: ch s t w z\n                                                          | _, _, _ => ch s t w z\n                                                        end;\n                                                dt := dt s;\n                                                st := fun t w => match decTree t c, decAddr w a with\n                                                                   | left _, left _ => x\n                                                                   | _, _ => st s t w\n                                                                 end;\n                                                dirSt := dirSt s;\n                                                wt := wt s;\n                                                wtS := wtS s;\n                                                dirWt := dirWt s;\n                                                dirWtS := dirWtS s;\n                                                req := req s\n                                             |}\n| ChildDropReq: forall {p c}, defined p -> defined c -> parent c p ->\n                              ch s mch p c <> nil ->\n                              let r := last (ch s mch p c) dmy in\n                                let fromR := fromB r in\n                                  let toR := toB r in\n                                    let a := addrB r in\n                                      let d := dataBM r in\n                                      type r = rch ->\n                                        sle (st s c a) toR ->\n                              Transition s {| ch := fun t w z =>\n                                                      match t, decTree w p,\n                                                            decTree z c with\n                                                        | mch, left _, left _ => removelast\n                                                                                   (ch s t w z)\n                                                        | _, _, _ => ch s t w z\n                                                      end;\n                                              dt := dt s;\n                                              st := st s;\n                                              dirSt := dirSt s;\n                                              wt := wt s;\n                                              wtS := wtS s;\n                                              dirWt := dirWt s;\n                                              dirWtS := dirWtS s;\n                                              req := req s\n                                           |}.\n\nDefinition initGlobalState :=\n  {| dt := fun t w => if (decTree t hier) then initData w else initData zero;\n     ch := fun t w z => nil;\n     st := fun t w => match decTree t hier with\n                        | left _ => Mo\n                        | right _ => In\n                      end;\n     dirSt := fun t w z => In;\n     wt := fun t w => false;\n     wtS := fun t w => In;\n     dirWt := fun t w z => false;\n     dirWtS := fun t w z => In;\n     req := fun t w => 0\n  |}.\n\nRecord Behavior := {\n                    sys: Time -> GlobalState;\n                    init: sys 0 = initGlobalState;\n                    trans: forall t, Transition (sys t) (sys (S t))\n                  }.\n\nParameter oneBeh: Behavior.\n\nFixpoint labelCh t ch src dst :=\n  match t with\n    | 0 => nil\n    | S t => match (trans oneBeh) t with\n               | ChildSendReq p c _ _ _ _ _ _ _ =>\n                 match ch with\n                   | rch =>\n                     if (decTree src c)\n                     then if (decTree dst p)\n                          then t :: labelCh t ch src dst\n                          else labelCh t ch src dst\n                     else labelCh t ch src dst\n                   | mch => labelCh t ch src dst\n                 end\n               | ParentRecvReq p c _ _ _ _ _ _ _ _ =>\n                 match ch with\n                   | rch =>\n                     if (decTree dst p)\n                     then if (decTree src c)\n                          then removelast (labelCh t ch src dst)\n                          else labelCh t ch src dst\n                     else labelCh t ch src dst\n                   | mch =>\n                     if (decTree dst c)\n                     then if (decTree src p)\n                          then t :: labelCh t ch src dst\n                          else labelCh t ch src dst\n                     else labelCh t ch src dst\n                 end\n               | ChildRecvResp p c _ _ _ _ _ =>\n                 match ch with\n                   | mch =>\n                     if (decTree src p)\n                     then if (decTree dst c)\n                          then removelast (labelCh t ch src dst)\n                          else labelCh t ch src dst\n                     else labelCh t ch src dst\n                   | rch => labelCh t ch src dst\n                 end\n               | ParentSendReq p c _ _ _ _ _ _ _ =>\n                 match ch with\n                   | mch =>\n                     if (decTree src p)\n                     then if (decTree dst c)\n                          then t :: labelCh t ch src dst\n                          else labelCh t ch src dst\n                     else labelCh t ch src dst\n                   | rch => labelCh t ch src dst\n                 end\n               | ChildRecvReq p c _ _ _ _ _ _ _ =>\n                 match ch with\n                   | mch =>\n                     match decTree dst p, decTree src c with\n                       | left _, left _ => t :: labelCh t ch src dst\n                       | left _, _ => labelCh t ch src dst\n                       | _, _ =>\n                         match decTree dst c, decTree src p with\n                                   | left _, left _ => \n                                                         removelast (labelCh t ch src dst)\n                                   | _, _ => labelCh t ch src dst\n                                 end\n                     end\n                   | rch => labelCh t ch src dst\n                 end\n               | ParentRecvResp p c _ _ _ _ _ =>\n                 match ch with\n                   | mch =>\n                     if (decTree src c)\n                     then if (decTree dst p)\n                          then removelast (labelCh t ch src dst)\n                          else labelCh t ch src dst\n                     else labelCh t ch src dst\n                   | rch => labelCh t ch src dst\n                 end\n               | ChildVolResp p c _ _ _ _ _ _ _ _ =>\n                 match ch with\n                   | mch =>\n                     if (decTree src c)\n                     then if (decTree dst p)\n                          then t :: labelCh t ch src dst\n                          else labelCh t ch src dst\n                     else labelCh t ch src dst\n                   | rch => labelCh t ch src dst\n                 end\n               | ChildDropReq p c _ _ _ _ _ _ =>\n                 match ch with\n                   | mch =>\n                     if (decTree src p)\n                     then if (decTree dst c)\n                          then removelast (labelCh t ch src dst)\n                          else labelCh t ch src dst\n                     else labelCh t ch src dst\n                   | rch => labelCh t ch src dst\n                 end\n               | _ => labelCh t ch src dst\n             end\n  end.\n\nModule mkDataTypes <: DataTypes.\n\n  Definition state c a t := st ((sys oneBeh) t) c a.\n  Definition dir p c a t := dirSt ((sys oneBeh) t) p c a.\n  Definition wait c a t := wt ((sys oneBeh) t) c a.\n  Definition waitS c a t := wtS ((sys oneBeh) t) c a.\n  Definition dwait p c a t := dirWt ((sys oneBeh) t) p c a.\n  Definition dwaitS p c a t := dirWtS ((sys oneBeh) t) p c a.\n  Definition data c a t := dt ((sys oneBeh) t) c a.\n\n  \n  Definition mark chn src dst t m := match ((trans oneBeh) t) with\n                                       | ChildSendReq p c _ _ _ x a _ _ =>\n                                         c = src /\\ p = dst /\\ chn = rch /\\\n                                         from m = (st ((sys oneBeh) t) c a) /\\\n                                         to m = x /\\ addr m = a /\\\n                                         dataM m = initData zero /\\\n                                         msgId m = t\n                                       | ParentRecvReq p c _ _ _ _ _ _ _ _ =>\n                                         p = src /\\ c = dst /\\ chn = mch /\\\n                                         let r := last (ch ((sys oneBeh) t) rch c p) dmy in\n                                         let a := addrB r in\n                                         from m = (dirSt ((sys oneBeh) t) p c a) /\\\n                                         to m = toB r /\\\n                                         addr m = a /\\\n                                         dataM m = dt ((sys oneBeh) t) p a /\\\n                                         msgId m = t\n                                       | ParentSendReq p c _ _ _ x a _ _ =>\n                                         p = src /\\ c = dst /\\ chn = rch /\\\n                                         from m = (dirSt ((sys oneBeh) t) p c a) /\\\n                                         to m = x /\\ addr m = a /\\\n                                         dataM m = initData zero /\\\n                                         msgId m = t\n                                       | ChildRecvReq p c _ _ _ _ _ _ _ =>\n                                         c = src /\\ p = dst /\\ chn = mch /\\\n                                         let r := last (ch ((sys oneBeh) t) mch p c) dmy in\n                                         let a := addrB r in\n                                         from m = (st ((sys oneBeh) t) c a) /\\\n                                         to m = toB r /\\\n                                         addr m = a /\\\n                                         dataM m = dt ((sys oneBeh) t) c a /\\\n                                         msgId m = t\n                                       | ChildVolResp p c _ _ _ x a _ _ _ =>\n                                         c = src /\\ p = dst /\\ chn = mch /\\\n                                         from m = (st ((sys oneBeh) t) c a) /\\\n                                         to m = x /\\ addr m = a /\\\n                                         dataM m = dt (sys oneBeh t) c a /\\\n                                         msgId m = t\n                                       | _ => False\n                                     end.\n\n  Definition recv chn src dst t m := match ((trans oneBeh) t) with\n                                       | ParentRecvReq p c _ _ _ _ _ _ _ _ =>\n                                         c = src /\\ p = dst /\\\n                                         let r := last (ch ((sys oneBeh) t) rch c p) dmy in\n                                         chn = type r /\\\n                                         from m = fromB r /\\\n                                         to m = toB r /\\ addr m = addrB r /\\\n                                         dataM m = dataBM r /\\\n                                         msgId m = last (labelCh t rch c p) 0\n                                       | ChildRecvResp p c _ _ _ _ _ =>\n                                         p = src /\\ c = dst /\\\n                                         let r := last (ch ((sys oneBeh) t) mch p c) dmy in\n                                         chn = type r /\\\n                                         from m = fromB r /\\\n                                         to m = toB r /\\ addr m = addrB r /\\\n                                         dataM m = dataBM r /\\\n                                         msgId m = last (labelCh t mch p c) 0\n                                       | ChildRecvReq p c _ _ _ _ _ _ _ =>\n                                         p = src /\\ c = dst /\\\n                                         let r := last (ch ((sys oneBeh) t) mch p c) dmy in\n                                         chn = type r /\\\n                                         from m = fromB r /\\\n                                         to m = toB r /\\ addr m = addrB r /\\\n                                         dataM m = dataBM r /\\\n                                         msgId m = last (labelCh t mch p c) 0\n                                       | ParentRecvResp p c _ _ _ _ _ =>\n                                         c = src /\\ p = dst /\\\n                                         let r := last (ch ((sys oneBeh) t) mch c p) dmy in\n                                         chn = type r /\\\n                                         from m = fromB r /\\\n                                         to m = toB r /\\ addr m = addrB r /\\\n                                         dataM m = dataBM r /\\\n                                         msgId m = last (labelCh t mch c p) 0\n                                       | ChildDropReq p c _ _ _ _ _ _ =>\n                                         p = src /\\ c = dst /\\\n                                         let r := last (ch ((sys oneBeh) t) mch p c) dmy in\n                                         chn = type r /\\\n                                         from m = fromB r /\\\n                                         to m = toB r /\\ addr m = addrB r /\\\n                                         dataM m = dataBM r /\\\n                                         msgId m = last (labelCh t mch p c) 0\n                                       | _ => False\n                                     end.\n  Definition markc t :=\n    match (trans oneBeh t) with\n      | ChildSendReq _ _ _ _ _ _ _ _ _ => rch\n      | _ => mch\n    end.\n\n  Definition recvc t :=\n    match (trans oneBeh t) with\n      | ParentRecvReq _ _ _ _ _ _ _ _ _ _ => rch\n      | _ => mch\n    end.\n\n  Definition invmark t :=\n    match trans oneBeh t with\n      | ChildSendReq _ _ _ _ _ _ _ _ _ => rch\n      | ParentSendReq _ _ _ _ _ _ _ _ _ => rch\n      | _ => mch\n    end.\n\n  Definition invrecv t :=\n    match trans oneBeh t with\n      | ParentRecvReq _ _ _ _ _ _ _ _ _ _ => rch\n      | ChildRecvReq _ _ _ _ _ _ _ _ _ => rch\n      | ChildDropReq _ _ _ _ _ _ _ _ => rch\n      | _ => mch\n    end.\n  \n  Definition send := mark.\n  Definition proc := recv.\n  Definition deq := recv.\n\n  Definition deqR a c i t := match (trans oneBeh) t with\n                                   | LoadReq ca aa _ _ _ _ =>\n                                     aa = a /\\ ca = c /\\ req (sys oneBeh t) a c = i\n                                   | StoreReq ca aa _ _ _ _ =>\n                                     aa = a /\\ ca = c /\\ req (sys oneBeh t) a c = i\n                                   | _ => False\n                                 end.\nEnd mkDataTypes.\n", "meta": {"author": "vmurali", "repo": "CacheProofBetter", "sha": "e00bb4a4f1677c69969797c25ab9ef4bb8a213a0", "save_path": "github-repos/coq/vmurali-CacheProofBetter", "path": "github-repos/coq/vmurali-CacheProofBetter/CacheProofBetter-e00bb4a4f1677c69969797c25ab9ef4bb8a213a0/Rules.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.28381603367073477}}
{"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_Ф_ticktock (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\nOpaque DePoolContract_Ф_updateRounds \n       DePoolContract_Ф_checkPureDePoolBalance \n       DePoolContract_Ф__returnChange.\n\nOpaque DePoolFuncs.DePoolContract_Ф_updateRounds \n       DePoolFuncs.DePoolContract_Ф_checkPureDePoolBalance \n       DePoolFuncs.DePoolContract_Ф__returnChange.       \n\n(* Definition DePoolContract_Ф_ticktock' :  LedgerT ( XErrorValue True XInteger ) :=\n Require2 {{ msg_sender () ?!= $xInt0, $ Errors_ι_IS_EXT_MSG }} ;  \n If! (DePoolContract_Ф_checkPureDePoolBalance () ) then \n { U0! _ ?:= DePoolContract_Ф_updateRounds () ; $I } ;\n (If (msg_sender () ?!= tvm_address () ) then {\n    DePoolContract_Ф__returnChange ()\n }).    *)    \n\n\n Definition DePoolContract_Ф_ticktock_tailer: LedgerT True :=\n  If (msg_sender () ?!= tvm_address () ) then {\n     DePoolContract_Ф__returnChange ()\n  }.  \n\nDefinition DePoolContract_Ф_ticktock_header :  LedgerT ( XErrorValue True XInteger ) :=\n Require2 {{ msg_sender () ?!= $ xInt0, $ Errors_ι_IS_EXT_MSG }} ;  \n If! (DePoolContract_Ф_checkPureDePoolBalance () ) then \n { U0! _ ?:= DePoolContract_Ф_updateRounds () ; $I } ; DePoolContract_Ф_ticktock_tailer.\n \n Lemma DePoolContract_Ф_ticktock_header_eq: \n  DePoolContract_Ф_ticktock = DePoolContract_Ф_ticktock_header .\n Proof.\n   intros. auto.\n Qed.      \n\n\nLemma DePoolContract_Ф_ticktock_tailer_exec : forall (l: Ledger),\nlet if1 : bool := negb ( eval_state msg_sender l =? eval_state tvm_address l) in\n\nexec_state DePoolContract_Ф_ticktock_tailer l =\nif if1 then exec_state (↓ DePoolContract_Ф__returnChange) l else l.\nProof.\n\nintros. \n  \n  destructLedger l. \n  compute. idtac.\n  repeat destructIf_solve. \nQed.\n\n\nOpaque DePoolContract_Ф_ticktock_tailer.\n\nLemma DePoolContract_Ф_ticktock_header_exec : forall  (l: Ledger) , \nlet req : bool := negb (eval_state msg_sender l =? 0)  in\nlet (if1, l_checkPureDePoolBalance) := run ( ↓ DePoolContract_Ф_checkPureDePoolBalance ) l in\nlet (r, l_updateRounds) := run ( ↓ DePoolContract_Ф_updateRounds ) l_checkPureDePoolBalance in\nlet l' := if if1 then l_updateRounds else l_checkPureDePoolBalance in\nexec_state DePoolContract_Ф_ticktock_header l = \nif req then \nif if1 then errorMapDefaultF (fun _ =>  exec_state DePoolContract_Ф_ticktock_tailer l') r (fun _ => l')\n       else exec_state DePoolContract_Ф_ticktock_tailer l_checkPureDePoolBalance\nelse l .\nProof. \n\n  intros. \n  \n  destructLedger l. \n  compute. idtac.\n\n  destructFunction0 DePoolContract_Ф_checkPureDePoolBalance; auto. idtac.\n  destructFunction0 DePoolContract_Ф_updateRounds; auto. idtac.\n  repeat destructIf_solve. idtac.\n  all: try rewrite <- Heqr; auto. idtac.\n  all: try rewrite H0; auto. idtac.\n  all: try rewrite <- Heqr0; auto. idtac.\n  all: try rewrite H1; auto. idtac.\n  all: try destructFunction0 DePoolContract_Ф_ticktock_tailer; auto. \n Qed.\n\n\nLemma DePoolContract_Ф_ticktock_header_eval : forall  (l: Ledger) , \nlet req : bool := negb (eval_state msg_sender l =? 0)  in\nlet (if1, l_checkPureDePoolBalance) := run ( ↓ DePoolContract_Ф_checkPureDePoolBalance ) l in\nlet (r, l_updateRounds) := run ( ↓ DePoolContract_Ф_updateRounds ) l_checkPureDePoolBalance in\nlet l' := if if1 then l_updateRounds else l_checkPureDePoolBalance in\neval_state DePoolContract_Ф_ticktock_header  l = \nif req then \nif if1 then errorMapDefaultF (fun _ =>  Value (eval_state DePoolContract_Ф_ticktock_tailer l')) r (fun e => Error e)\n       else Value (eval_state DePoolContract_Ф_ticktock_tailer l_checkPureDePoolBalance)\nelse Error Errors_ι_IS_EXT_MSG .\nProof.\n  intros.\n\n  destructLedger l. \n  compute. idtac.\n\n  destructFunction0 DePoolContract_Ф_checkPureDePoolBalance; auto. idtac.\n  destructFunction0 DePoolContract_Ф_updateRounds; auto. idtac.\n\n  repeat destructIf_solve. idtac.\n  all: try rewrite <- Heqr; auto. idtac.\n  all: try rewrite H0; auto. idtac.\n  all: try rewrite <- Heqr0; auto. idtac.\n  all: try destructFunction0 DePoolContract_Ф_ticktock_tailer; auto. \n\n  destruct x0; auto. idtac.\n  rewrite <- Heqr1.\n  auto.\nQed.  \n\nTransparent  DePoolContract_Ф_ticktock_tailer.\nLemma DePoolContract_Ф_ticktock_tailer_eval : forall (l: Ledger),\nlet if1 : bool := negb ( eval_state msg_sender l =? eval_state tvm_address l) in\n\neval_state DePoolContract_Ф_ticktock_tailer l = I.\nProof.\nintros.   \n  destructLedger l. \n  compute. idtac.\n  repeat destructIf_solve. \nQed.\n\n(*good sample how to transform partial proofs to full one*)\nOpaque exec_state eval_state run.\nOpaque DePoolContract_Ф_ticktock_header DePoolContract_Ф_ticktock_tailer.\n\nLemma DePoolContract_Ф_ticktock_exec : forall (l: Ledger), \nlet req : bool := negb (eval_state msg_sender l =? 0)  in\nlet (if1, l_checkPureDePoolBalance) := run ( ↓ DePoolContract_Ф_checkPureDePoolBalance ) l in\nlet (r, l_updateRounds) := run ( ↓ DePoolContract_Ф_updateRounds ) l_checkPureDePoolBalance in\nlet l' := if if1 then l_updateRounds else l_checkPureDePoolBalance in\n\nlet if2' : bool := negb ( eval_state msg_sender l' =? eval_state tvm_address l') in\nlet l'' := if if2' then exec_state (↓ DePoolContract_Ф__returnChange) l' else l' in\n\nlet if2'' : bool := negb ( eval_state msg_sender l_checkPureDePoolBalance =? eval_state tvm_address l_checkPureDePoolBalance) in\nlet l''' := if if2'' then exec_state (↓ DePoolContract_Ф__returnChange) l_checkPureDePoolBalance else l_checkPureDePoolBalance in\n\nexec_state DePoolContract_Ф_ticktock l = \nif req then \nif if1 then errorMapDefaultF (fun _ => l'') r (fun _ => l')\n       else l'''\nelse l .\n\nProof.\n  intros.\n  rewrite DePoolContract_Ф_ticktock_header_eq.\n  remember (run (↓ DePoolContract_Ф_checkPureDePoolBalance) l).\n  destruct p.\n  remember (run (↓ DePoolContract_Ф_updateRounds) l0).\n  destruct p.\n  intros.\n\n  remember (DePoolContract_Ф_ticktock_header_exec l).\n  clear Heqy.\n  rewrite <- Heqp in y.\n  compute in y. compute in Heqp0. \n  rewrite <- Heqp0 in y. \n  rewrite ?DePoolContract_Ф_ticktock_tailer_exec in y.\n\n  setoid_rewrite y.  auto.\nQed.  \n\n\nLemma DePoolContract_Ф_ticktock_eval : forall (l: Ledger), \nlet req : bool := negb (eval_state msg_sender l =? 0)  in\nlet (if1, l_checkPureDePoolBalance) := run ( ↓ DePoolContract_Ф_checkPureDePoolBalance ) l in\nlet (r, l_updateRounds) := run ( ↓ DePoolContract_Ф_updateRounds ) l_checkPureDePoolBalance in\nlet l' := if if1 then l_updateRounds else l_checkPureDePoolBalance in\n\neval_state DePoolContract_Ф_ticktock l = \n\nif req then \nif if1 then errorMapDefaultF (fun _ =>  Value I) r (fun e => Error e)\n       else Value I\nelse Error Errors_ι_IS_EXT_MSG .\n\nProof.\n  intros.\n  rewrite DePoolContract_Ф_ticktock_header_eq.\n  remember (run (↓ DePoolContract_Ф_checkPureDePoolBalance) l).\n  destruct p.\n  remember (run (↓ DePoolContract_Ф_updateRounds) l0).\n  destruct p.\n  intros.\n\n  remember (DePoolContract_Ф_ticktock_header_eval l).\n  clear Heqy.\n  rewrite <- Heqp in y.\n  compute in y. compute in Heqp0. \n  rewrite <- Heqp0 in y. \n  rewrite ?DePoolContract_Ф_ticktock_tailer_eval in y.\n\n  setoid_rewrite y. auto.\nQed.  \n\nEnd DePoolContract_Ф_ticktock.", "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_ticktock.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.28379820165761394}}
{"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 O B A0 A1 C Cprime P Q R Aprime A Pprime Qprime Rprime Aprimeprime : Universe, ((wd_ O A0 /\\ (wd_ B A0 /\\ (wd_ A0 A1 /\\ (wd_ O A1 /\\ (wd_ O B /\\ (wd_ A0 Aprime /\\ (wd_ C Cprime /\\ (wd_ A0 Cprime /\\ (wd_ A Aprime /\\ (wd_ A O /\\ (wd_ P Q /\\ (wd_ Aprime O /\\ (wd_ R Q /\\ (wd_ O Aprimeprime /\\ (wd_ Aprime Aprimeprime /\\ (wd_ A0 Aprimeprime /\\ (wd_ Pprime Qprime /\\ (wd_ Rprime Qprime /\\ (col_ A0 O Aprimeprime /\\ (col_ A0 Aprimeprime B /\\ (col_ A0 A1 Aprimeprime /\\ (col_ A0 A Aprime /\\ (col_ A0 Aprime B /\\ (col_ A0 A1 Aprime /\\ (col_ A0 C Cprime /\\ col_ A0 A1 B))))))))))))))))))))))))) -> col_ Aprime O Aprimeprime)).\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_0570.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.28374113364649983}}
{"text": "From OGS Require Import Utils EventD ITreeD CatD AngelicD.\n\nDefinition iter {I} {E : event I I} {X Y : I -> Type} (body : X ⇒ᵢ itree E (X +ᵢ Y))\n  : X ⇒ᵢ itree E Y :=\n  cofix _iter i x :=\n    bind (body i x) (fun _ y => match y with\n                            | inl x' => Tau (_iter _ x')\n                            | inr y => Ret y\n                            end).\n\nInstance ITreeMonadIter {I} (E : event I I) : MonadIter (itree E) :=\n  Build_MonadIter _ (fun X Y => @iter I E X Y).\n\nDefinition translate {I} {E F : event I I} (f : E ⇒ₑ F) : itree E ⇒f itree F :=\n  fun _ => cofix _translate _ u :=\n    match (observe u) with\n    | RetF x => Ret x\n    | TauF t => Tau (_translate _ t)\n    | VisF e k => let (e1, k1) := f _ e in\n                 Vis e1 (fun r => match k1 r with Fib a => _translate _ (k a) end)\n     end.\n\nDefinition translate_fwd {I J} {E : event I I} {F : event J J} (f0 : I -> J)\n           (f : (f0 >ₑ E) ⇒ₑ (F <ₑ f0))\n           X : (itree E (X ∘ f0)) ⇒ᵢ (itree F X ∘ f0) :=\n  cofix _translate i u :=\n    match (observe u) with\n    | RetF x => @ITreeD.ret _ _ _ (f0 i) x\n    | TauF t => @ITreeD.tau _ _ _ (f0 i) (_translate _ t)\n    | VisF e k => let (e1, k1) := f _ e in\n                 Vis e1 (fun r => fiber_rect _ _ _ (fun i _ => itree _ _ i)\n                                 (fun a => _translate _ (k a)) _ (k1 r))\n    end.\n\nDefinition translate_bwd {I J} {E : event I I} {F : event J J} (f0 : J -> I)\n           (f : (E <ₑ f0) ⇒ₑ (f0 >ₑ F))\n           X : (itree E X ∘ f0) ⇒ᵢ (itree F (X ∘ f0)) :=\n  cofix _translate i u :=\n    match (observe u) with\n    | RetF x => Ret x\n    | TauF t => Tau (_translate _ t)\n    | VisF e k => let (e1, k1) := f _ e in\n                 Vis e1 (fun r => _translate _ (fiber_rect _ _ _ (fun i _ => itree _ _ i)\n                                                        k _ (k1 r)))\n    end.\n\nDefinition comp (X : Type) : Type := itree₀ ∅ₑ X.\nDefinition emb_comp {I} {E : event I I} X i : comp X -> itree E (X @ i) i.\n  refine (fun t => translate_fwd (fun _ => i) (fun _ (i : qry (_ >ₑ ∅ₑ) _) => ex_falso i)\n                              (X @ i) t1_0 (t >>= _)).\n  refine (fun 't1_0 '(Fib a) => Ret (Fib a)).\nDefined.\n\nDefinition interp {I} {E : event I I}\n           {M : psh I -> psh I} {MF : Functor M} {MM : Monad M} {MI : MonadIter M}\n           (h : E ₑ⇒ M)\n           : itree E ⇒f M :=\n  fun _ => CatD.iter (fun i x => match (observe x) with\n            | RetF x => CatD.ret _ (inr x)\n            | TauF t => CatD.ret _ (inl t)\n            | VisF e k => CatD.fmap (fun _ => inl) _ (e_arrow_eval h _ _ (existT _ e k))\n            end).\n\n\nDefinition interp_mrec {I} {E F : event I I}\n           (body : E ₑ⇒ itree (esum E F))\n           : itree (esum E F) ⇒f itree F :=\n  fun _ => iter (fun _ (t : itree (esum E F) _ _) => match (observe t) with\n              | RetF r => Ret (inr r)\n              | TauF t => Ret (inl t)\n              | VisF (inl q) k => Ret (inl (body _ q >>= fiber_into _ k))\n              | VisF (inr q) k => Vis q (fun r => Ret (inl (k r)))\n              end).\n\nDefinition mrec {I} {E F : event I I} (body : E ₑ⇒ itree (esum E F)) : E ₑ⇒ itree F :=\n  fun _ q => interp_mrec body _ _ (body _ q).\n\nDefinition trigger {I} {E : event I I} : E ₑ⇒ itree E :=\n  fun _ q => Vis q (fun r => Ret (Fib r)).\n\nDefinition trigger₀ {E : event₀} (q : qry₀ E) : itree₀ E (rsp₀ E q) := vis₀ q ret₀.\n\nDefinition ecall (A : Type) (B : A -> Type) : event₀ := Event₀ A B.\nDefinition call {A B} : forall a, itree₀ (ecall A B) (B a) := @trigger₀ (ecall A B).\nDefinition rec {A B} (body : forall a, itree₀ (ecall A B) (B a)) : forall a, itree₀ ∅ₑ (B a) :=\n  mrec (fun 't1_0 (a : qry₀ (ecall A B)) => translate inlₑ (B a @ _) _ (body a)) _.\n", "meta": {"author": "Lapin0t", "repo": "ogs-coq", "sha": "135bfbad0204571b45c7ecc212d904e73507f157", "save_path": "github-repos/coq/Lapin0t-ogs-coq", "path": "github-repos/coq/Lapin0t-ogs-coq/ogs-coq-135bfbad0204571b45c7ecc212d904e73507f157/theories/RecD.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.28373175127296485}}
{"text": "Require Import FunctionalExtensionality.\nRequire Import Vector_of_tuple.\n\nLtac functional_extensionality_pair_l :=\n  match goal with\n    | [ |- context[(?f, ?b) = (?g, ?b)]] =>\n      rewrite (functional_extensionality f g ); reflexivity\n    | [ |- context[(?a, ?f) = (?a, ?g)]] =>\n      rewrite (functional_extensionality f g ); reflexivity\n    | _ => idtac\n  end.\nLtac functional_extensionality_pair_r :=\n  match goal with\n    | [ |- context[(?f, ?b) = (?g, ?b)]] =>\n      rewrite <- (functional_extensionality f g); try reflexivity\n    | [ |- context[(?a, ?f) = (?a, ?g)]] =>\n      rewrite <- (functional_extensionality f g); try reflexivity\n    | _ => idtac\n  end.\nLtac functional_extensionality_dep_pair_l :=\n  match goal with\n    | [ |- context[(?f, ?b) = (?g, ?b)]] =>\n      rewrite (functional_extensionality_dep f g ); reflexivity\n    | [ |- context[(?a, ?f) = (?a, ?g)]] =>\n      rewrite (functional_extensionality_dep f g ); reflexivity\n    | _ => idtac\n  end.\nLtac functional_extensionality_dep_pair_r :=\n  match goal with\n    | [ |- context[(?f, ?b) = (?g, ?b)]] =>\n      rewrite <- (functional_extensionality_dep f g); try reflexivity\n    | [ |- context[(?a, ?f) = (?a, ?g)]] =>\n      rewrite <- (functional_extensionality_dep f g); try reflexivity\n    | _ => idtac\n  end.\n\nDefinition Vector_of_tuple := Vector_of_tuple.Vector_of_tuple.\nDefinition tuple_of_Vector := Vector_of_tuple.tuple_of_Vector.\n", "meta": {"author": "OKU1987", "repo": "SIMTHoare", "sha": "9854b4f154ac9e8744902395ed373cef41bf498b", "save_path": "github-repos/coq/OKU1987-SIMTHoare", "path": "github-repos/coq/OKU1987-SIMTHoare/SIMTHoare-9854b4f154ac9e8744902395ed373cef41bf498b/SIMT_util.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.28373174373828974}}
{"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(** Additional operations and proofs about IEEE-754 binary\n    floating-point numbers, on top of the Flocq library. *)\n\nRequire Import Psatz.\nRequire Import Bool.\nRequire Import Eqdep_dec.\nRequire Import Flocq.Core.Core.\nRequire Import Flocq.Core.Digits.\nRequire Import Flocq.Core.Digits.\nRequire Import Flocq.Core.Raux.\nRequire Import Flocq.Calc.Operations.\nRequire Import Flocq.Calc.Round.\nRequire Import Flocq.Core.Float_prop.\nRequire Import Flocq.Calc.Bracket.\nRequire Import Flocq.Prop.Sterbenz.\nRequire Import Flocq.IEEE754.Binary.\nRequire Import Flocq.IEEE754.Bits.\nRequire Import Flocq.Prop.Round_odd.\n\nRequire Import Archi.\n\nLocal Open Scope Z_scope.\n\nSection Extra_ops.\n\n(** [prec] is the number of bits of the mantissa including the implicit one.\n    [emax] is the exponent of the infinities.\n    Typically p=24 and emax = 128 in single precision. *)\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(** Remarks on [is_finite] *)\n\nRemark is_finite_not_is_nan:\n  forall (f: binary_float), is_finite _ _ f = true -> is_nan _ _ f = false.\nProof.\n  destruct f; reflexivity || discriminate.\nQed.\n\nRemark is_finite_strict_finite:\n  forall (f: binary_float), is_finite_strict _ _ f = true -> is_finite _ _ f = true.\nProof.\n  destruct f; reflexivity || discriminate.\nQed.\n\n(** Digression on FP numbers that cannot be [-0.0]. *)\n\nDefinition is_finite_pos0 (f: binary_float) : bool :=\n  match f with\n  | B754_zero _ _ s => negb s\n  | B754_infinity _ _ _ => false\n  | B754_nan _ _ _ _ _ => false\n  | B754_finite _ _ _ _ _ _ => true\n  end.\n\nLemma Bsign_pos0:\n  forall x, is_finite_pos0 x = true -> Bsign _ _ x = Rlt_bool (B2R _ _ x) 0%R.\nProof.\n  intros. 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.\n  assert ((F2R (Float radix2 (Z.pos ex) mx) > 0)%R) by\n    ( apply F2R_gt_0; compute; auto ).\n  lra.\nQed.\n\nTheorem B2R_inj_pos0:\n  forall x y,\n  is_finite_pos0 x = true -> is_finite_pos0 y = true ->\n  B2R _ _ x = B2R _ _ y ->\n  x = y.\nProof.\n  intros. apply B2R_Bsign_inj.\n  destruct x; reflexivity||discriminate.\n  destruct y; reflexivity||discriminate.\n  auto.\n  rewrite ! Bsign_pos0 by auto. rewrite H1; auto.\nQed.\n\n(** ** Decidable equality *)\n\nDefinition Beq_dec: forall (f1 f2: binary_float), {f1 = f2} + {f1 <> f2}.\nProof.\n  assert (UIP_bool: forall (b1 b2: bool) (e e': b1 = b2), e = e').\n  { intros. apply UIP_dec. decide equality. }\n  Ltac try_not_eq := try solve [right; congruence].\n  destruct f1 as [| |? []|], f2 as [| |? []|];\n    try destruct s; try destruct s0;\n      try solve [left; auto]; try_not_eq.\n  - destruct (Pos.eq_dec p p0); try_not_eq;\n      subst; left; f_equal; f_equal; apply UIP_bool.\n  - destruct (Pos.eq_dec p p0); try_not_eq;\n      subst; left; f_equal; f_equal; apply UIP_bool.\n  - destruct (Pos.eq_dec p p0); try_not_eq;\n      subst; left; f_equal; f_equal; apply UIP_bool.\n  - destruct (Pos.eq_dec p p0); try_not_eq;\n      subst; left; f_equal; f_equal; apply UIP_bool.\n  -\n    left; f_equal; apply UIP_bool.\n  -\n    left; f_equal; apply UIP_bool.\n  -\n    destruct (Pos.eq_dec m m0); try_not_eq;\n      destruct (Z.eq_dec e e1); try solve [right; intro H; inversion H; congruence];\n        subst; left; f_equal; apply UIP_bool.\n  -\n    destruct (Pos.eq_dec m m0); try_not_eq;\n      destruct (Z.eq_dec e e1); try solve [right; intro H; inversion H; congruence];\n        subst; left; f_equal; apply UIP_bool.\nDefined.\n\n(** ** Conversion from an integer to a FP number *)\n\n(** Integers that can be represented exactly as FP numbers. *)\n\nDefinition integer_representable (n: Z): Prop :=\n  Z.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.\n  red in prec_gt_0_.\n  ring_simplify. rewrite <- (Zpower_plus radix2) by omega. f_equal. f_equal. omega.\nQed.\n\nLemma integer_representable_n2p:\n  forall n p,\n  -2^prec < n < 2^prec -> 0 <= p -> p <= emax - prec ->\n  integer_representable (n * 2^p).\nProof.\n  intros; split.\n- red in prec_gt_0_. replace (Z.abs (n * 2^p)) with (Z.abs n * 2^p).\n  rewrite int_upper_bound_eq.\n  apply Zmult_le_compat. zify; omega. apply (Zpower_le radix2); omega.\n  zify; omega. apply (Zpower_ge_0 radix2).\n  rewrite 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).\n  unfold F2R; simpl.\n  rewrite <- IZR_Zpower by auto. apply mult_IZR.\n  zify. simpl in *. omega.\n  unfold Fexp, emin; red in prec_gt_0_; omega.\nQed.\n\nLemma integer_representable_2p:\n  forall p,\n  0 <= p <= emax - 1 ->\n  integer_representable (2^p).\nProof.\n  intros; split.\n- red in prec_gt_0_.\n  rewrite Z.abs_eq by (apply (Zpower_ge_0 radix2)).\n  apply Z.le_trans with (2^(emax-1)).\n  apply (Zpower_le radix2); omega.\n  assert (2^emax = 2^(emax-1)*2).\n  { change 2 with (2^1) at 3. rewrite <- (Zpower_plus radix2) by omega.\n    f_equal. omega. }\n  assert (2^(emax - prec) <= 2^(emax - 1)).\n  { apply (Zpower_le radix2). omega. }\n  omega.\n- red in prec_gt_0_.\n  apply generic_format_FLT. exists (Float radix2 1 p).\n  unfold F2R; simpl.\n  rewrite Rmult_1_l. rewrite <- IZR_Zpower. auto. omega.\n  unfold Fnum.  simpl . change 1 with (2^0). apply (Zpower_lt radix2). omega. auto.\n  unfold Fexp, emin; omega.\nQed.\n\nLemma integer_representable_opp:\n  forall n, integer_representable n -> integer_representable (-n).\nProof.\n  intros n (A & B); split. rewrite Z.abs_opp. auto.\n  rewrite opp_IZR. apply generic_format_opp; auto.\nQed.\n\nLemma integer_representable_n2p_wide:\n  forall n p,\n  -2^prec <= n <= 2^prec -> 0 <= p -> p < emax - prec ->\n  integer_representable (n * 2^p).\nProof.\n  intros. red in prec_gt_0_.\n  destruct (Z.eq_dec n (2^prec)); [idtac | destruct (Z.eq_dec n (-2^prec))].\n- rewrite e. rewrite <- (Zpower_plus radix2) by omega.\n  apply integer_representable_2p. omega.\n- rewrite e. rewrite <- Zopp_mult_distr_l. apply integer_representable_opp.\n  rewrite <- (Zpower_plus radix2) by omega.\n  apply integer_representable_2p. omega.\n- apply integer_representable_n2p; omega.\nQed.\n\nLemma integer_representable_n:\n  forall n, -2^prec <= n <= 2^prec -> integer_representable n.\nProof.\n  red in prec_gt_0_. intros.\n  replace n with (n * 2^0) by (change (2^0) with 1; ring).\n  apply integer_representable_n2p_wide. auto. omega. omega.\nQed.\n\nLemma round_int_no_overflow:\n  forall n,\n  Z.abs n <= 2^emax - 2^(emax-prec) ->\n  (Rabs (round radix2 fexp (round_mode mode_NE) (IZR n)) < bpow radix2 emax)%R.\nProof.\n  intros. red in prec_gt_0_.\n  rewrite <- round_NE_abs.\n  apply Rle_lt_trans with (IZR (2^emax - 2^(emax-prec))).\n  apply round_le_generic. apply fexp_correct; auto. apply valid_rnd_N.\n  apply generic_format_FLT. exists (Float radix2 (2^prec-1) (emax-prec)).\n  rewrite int_upper_bound_eq. unfold F2R; simpl.\n  rewrite <- IZR_Zpower by omega. rewrite <- mult_IZR. auto.\n  unfold Fnum. assert (0 < 2^prec) by (apply (Zpower_gt_0 radix2); omega). simpl. zify; omega.\n  unfold Fexp, emin; omega.\n  rewrite <- abs_IZR. apply IZR_le. auto.\n  rewrite <- IZR_Zpower by omega. apply IZR_lt. simpl.\n  assert (0 < 2^(emax-prec)) by (apply (Zpower_gt_0 radix2); omega).\n  omega.\n  apply fexp_correct. auto.\nQed.\n\n(** Conversion from an integer.  Round to nearest. *)\n\nDefinition BofZ (n: Z) : binary_float :=\n  binary_normalize prec emax prec_gt_0_ Hmax mode_NE n 0 false.\n\nTheorem BofZ_correct:\n  forall n,\n  if Rlt_bool (Rabs (round radix2 fexp (round_mode mode_NE) (IZR n))) (bpow radix2 emax)\n  then\n    B2R prec emax (BofZ n) = round radix2 fexp (round_mode mode_NE) (IZR n) /\\\n    is_finite _ _ (BofZ n) = true /\\\n    Bsign prec emax (BofZ n) = Z.ltb n 0\n  else\n    B2FF prec emax (BofZ n) = binary_overflow prec emax mode_NE (Z.ltb n 0).\nProof.\n  intros.\n  generalize (binary_normalize_correct prec emax prec_gt_0_ Hmax mode_NE n 0 false).\n  fold emin; fold fexp; fold (BofZ n).\n  replace (F2R {| Fnum := n; Fexp := 0 |}) with (IZR n).\n  destruct Rlt_bool.\n- intros (A & B & C). split; [|split].\n  + auto.\n  + auto.\n  + rewrite C. change 0%R with (IZR 0). rewrite Rcompare_IZR.\n    unfold Z.ltb. auto.\n- intros A; rewrite A. f_equal. change 0%R with (IZR 0).\n  generalize (Z.ltb_spec n 0); intros SPEC; inversion SPEC.\n  apply Rlt_bool_true; apply IZR_lt; auto.\n  apply Rlt_bool_false; apply IZR_le; auto.\n- unfold F2R; simpl. ring.\nQed.\n\nTheorem BofZ_finite:\n  forall n,\n  Z.abs n <= 2^emax - 2^(emax-prec) ->\n  B2R _ _ (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.\n  intros.\n  generalize (BofZ_correct n). rewrite Rlt_bool_true. auto.\n  apply round_int_no_overflow; auto.\nQed.\n\nTheorem BofZ_representable:\n  forall n,\n  integer_representable n ->\n  B2R _ _ (BofZ n) = IZR n\n  /\\ is_finite _ _ (BofZ n) = true\n  /\\ Bsign _ _ (BofZ n) = (n <? 0).\nProof.\n  intros. destruct H as (P & Q). destruct (BofZ_finite n) as (A & B & C). auto.\n  intuition. rewrite A. apply round_generic. apply valid_rnd_round_mode. auto.\nQed.\n\nTheorem BofZ_exact:\n  forall n,\n  -2^prec <= n <= 2^prec ->\n  B2R _ _ (BofZ n) = IZR n\n  /\\ is_finite _ _ (BofZ n) = true\n  /\\ Bsign _ _ (BofZ n) = Z.ltb n 0%Z.\nProof.\n  intros. apply BofZ_representable. apply integer_representable_n; auto.\nQed.\n\nLemma BofZ_finite_pos0:\n  forall n,\n  Z.abs n <= 2^emax - 2^(emax-prec) -> is_finite_pos0 (BofZ n) = true.\nProof.\n  intros.\n  generalize (binary_normalize_correct prec emax prec_gt_0_ Hmax mode_NE n 0 false).\n  fold emin; fold fexp; fold (BofZ n).\n  replace (F2R {| Fnum := n; Fexp := 0 |}) with (IZR n) by\n    (unfold F2R; simpl; ring).\n  rewrite Rlt_bool_true by (apply round_int_no_overflow; auto).\n  intros (A & B & C).\n  destruct (BofZ n); auto; try discriminate.\n  simpl in *. rewrite C. change 0%R with (IZR 0). rewrite Rcompare_IZR.\n  generalize (Zcompare_spec n 0); intros SPEC; inversion SPEC; auto.\n  assert ((round radix2 fexp ZnearestE (IZR n) <= -1)%R).\n  { change (-1)%R with (IZR (-1)).\n    apply round_le_generic. apply fexp_correct. auto. apply valid_rnd_N.\n    apply (integer_representable_opp 1).\n    apply (integer_representable_2p 0).\n    red in prec_gt_0_; omega.\n    apply IZR_le; omega.\n  }\n  lra.\nQed.\n\nLemma BofZ_finite_equal:\n  forall x y,\n  Z.abs x <= 2^emax - 2^(emax-prec) ->\n  Z.abs y <= 2^emax - 2^(emax-prec) ->\n  B2R _ _ (BofZ x) = B2R _ _ (BofZ y) ->\n  BofZ x = BofZ y.\nProof.\n  intros. apply B2R_inj_pos0; auto; apply BofZ_finite_pos0; auto.\nQed.\n\n(** Commutation properties with addition, subtraction, multiplication. *)\n\nTheorem BofZ_plus:\n  forall nan p q,\n  integer_representable p -> integer_representable q ->\n  Bplus _ _ _ Hmax nan mode_NE (BofZ p) (BofZ q) = BofZ (p + q).\nProof.\n  intros.\n  destruct (BofZ_representable p) as (A & B & C); auto.\n  destruct (BofZ_representable q) as (D & E & F); auto.\n  generalize (Bplus_correct _ _ _ Hmax nan mode_NE (BofZ p) (BofZ q) B E).\n  fold emin; fold fexp.\n  rewrite A, D. rewrite <- plus_IZR.\n  generalize (BofZ_correct (p + q)). destruct Rlt_bool.\n- intros (P & Q & R) (U & V & W).\n  apply B2R_Bsign_inj; auto.\n  rewrite P, U; auto.\n  rewrite R, W, C, F.\n  change 0%R with (IZR 0). rewrite Rcompare_IZR. unfold Z.ltb at 3.\n  generalize (Zcompare_spec (p + q) 0); intros SPEC; inversion SPEC; auto.\n  assert (EITHER: 0 <= p \\/ 0 <= q) by omega.\n  destruct EITHER; [apply andb_false_intro1 | apply andb_false_intro2];\n  apply Zlt_bool_false; auto.\n- intros P (U & V).\n  apply B2FF_inj.\n  rewrite P, U, C. f_equal. rewrite C, F in V.\n  generalize (Zlt_bool_spec p 0) (Zlt_bool_spec q 0). rewrite <- V.\n  intros SPEC1 SPEC2; inversion SPEC1; inversion SPEC2; try congruence; symmetry.\n  apply Zlt_bool_true; omega.\n  apply Zlt_bool_false; omega.\nQed.\n\nTheorem BofZ_minus:\n  forall nan p q,\n  integer_representable p -> integer_representable q ->\n  Bminus _ _ _ Hmax nan mode_NE (BofZ p) (BofZ q) = BofZ (p - q).\nProof.\n  intros.\n  destruct (BofZ_representable p) as (A & B & C); auto.\n  destruct (BofZ_representable q) as (D & E & F); auto.\n  generalize (Bminus_correct _ _ _ Hmax nan mode_NE (BofZ p) (BofZ q) B E).\n  fold emin; fold fexp.\n  rewrite A, D. rewrite <- minus_IZR.\n  generalize (BofZ_correct (p - q)). destruct Rlt_bool.\n- intros (P & Q & R) (U & V & W).\n  apply B2R_Bsign_inj; auto.\n  rewrite P, U; auto.\n  rewrite R, W, C, F.\n  change 0%R with (IZR 0). rewrite Rcompare_IZR. unfold Z.ltb at 3.\n  generalize (Zcompare_spec (p - q) 0); intros SPEC; inversion SPEC; auto.\n  assert (EITHER: 0 <= p \\/ q < 0) by omega.\n  destruct EITHER; [apply andb_false_intro1 | apply andb_false_intro2].\n  rewrite Zlt_bool_false; auto.\n  rewrite Zlt_bool_true; auto.\n- intros P (U & V).\n  apply B2FF_inj.\n  rewrite P, U, C. f_equal. rewrite C, F in V.\n  generalize (Zlt_bool_spec p 0) (Zlt_bool_spec q 0). rewrite V.\n  intros SPEC1 SPEC2; inversion SPEC1; inversion SPEC2; symmetry.\n  rewrite <- H3 in H1; discriminate.\n  apply Zlt_bool_true; omega.\n  apply Zlt_bool_false; omega.\n  rewrite <- H3 in H1; discriminate.\nQed.\n\nTheorem BofZ_mult:\n  forall nan p q,\n  integer_representable p -> integer_representable q ->\n  0 < q ->\n  Bmult _ _ _ Hmax nan mode_NE (BofZ p) (BofZ q) = BofZ (p * q).\nProof.\n  intros.\n  assert (SIGN: xorb (p <? 0) (q <? 0) = (p * q <? 0)).\n  {\n    rewrite (Zlt_bool_false q) by omega.\n    generalize (Zlt_bool_spec p 0); intros SPEC; inversion SPEC; simpl; symmetry.\n    apply Zlt_bool_true. rewrite Z.mul_comm. apply Z.mul_pos_neg; omega.\n    apply Zlt_bool_false. apply Zsame_sign_imp; omega.\n  }\n  destruct (BofZ_representable p) as (A & B & C); auto.\n  destruct (BofZ_representable q) as (D & E & F); auto.\n  generalize (Bmult_correct _ _ _ Hmax nan mode_NE (BofZ p) (BofZ q)).\n  fold emin; fold fexp.\n  rewrite A, B, C, D, E, F. rewrite <- mult_IZR.\n  generalize (BofZ_correct (p * q)). destruct Rlt_bool.\n- intros (P & Q & R) (U & V & W).\n  apply B2R_Bsign_inj; auto.\n  rewrite P, U; auto.\n  rewrite R, W; auto.\n  apply is_finite_not_is_nan; auto.\n- intros P U.\n  apply B2FF_inj. rewrite P, U. f_equal. auto.\nQed.\n\nTheorem BofZ_mult_2p:\n  forall nan x p,\n  Z.abs x <= 2^emax - 2^(emax-prec) ->\n  2^prec <= Z.abs x ->\n  0 <= p <= emax - 1 ->\n  Bmult _ _ _ Hmax nan mode_NE (BofZ x) (BofZ (2^p)) = BofZ (x * 2^p).\nProof.\n  intros.\n  destruct (Z.eq_dec x 0).\n- subst x. apply BofZ_mult.\n    apply integer_representable_n.\n    generalize (Zpower_ge_0 radix2 prec). simpl; omega.\n    apply integer_representable_2p. auto.\n    apply (Zpower_gt_0 radix2).\n    omega.\n- assert (IZR x <> 0%R) by (apply (IZR_neq _ _ n)).\n  destruct (BofZ_finite x H) as (A & B & C).\n  destruct (BofZ_representable (2^p)) as (D & E & F).\n    apply integer_representable_2p. auto.\n  assert (cexp radix2 fexp (IZR (x * 2^p)) =\n          cexp radix2 fexp (IZR x) + p).\n  {\n    unfold cexp, fexp. rewrite mult_IZR.\n    change (2^p) with (radix2^p). rewrite IZR_Zpower by omega.\n    rewrite mag_mult_bpow by auto.\n    assert (prec + 1 <= mag radix2 (IZR x)).\n    { rewrite <- (mag_abs radix2 (IZR x)).\n      rewrite <- (mag_bpow radix2 prec).\n      apply mag_le.\n      apply bpow_gt_0. rewrite <- IZR_Zpower by (red in prec_gt_0_;omega).\n      rewrite <- abs_IZR. apply IZR_le; auto. }\n    unfold FLT_exp.\n    unfold emin; red in prec_gt_0_; zify; omega.\n  }\n  assert (forall m, round radix2 fexp m (IZR x) * IZR (2^p) =\n                    round radix2 fexp m (IZR (x * 2^p)))%R.\n  {\n    intros. unfold round, scaled_mantissa. rewrite H3.\n    rewrite mult_IZR. rewrite Z.opp_add_distr. rewrite bpow_plus.\n    set (a := IZR x); set (b := bpow radix2 (- cexp radix2 fexp a)).\n    replace (a * IZR (2^p) * (b * bpow radix2 (-p)))%R with (a * b)%R.\n    unfold F2R; simpl. rewrite Rmult_assoc. f_equal.\n    rewrite bpow_plus.  f_equal. apply (IZR_Zpower radix2). omega.\n    transitivity ((a * b) * (IZR (2^p) * bpow radix2 (-p)))%R.\n    rewrite (IZR_Zpower radix2). rewrite <- bpow_plus.\n    replace (p + -p) with 0 by omega. change (bpow radix2 0) with 1%R. ring.\n    omega.\n    ring.\n  }\n  assert (forall m x,\n    round radix2 fexp (round_mode m) (round radix2 fexp (round_mode m) x) =\n    round radix2 fexp (round_mode m) x).\n  {\n    intros. apply round_generic. apply valid_rnd_round_mode.\n    apply generic_format_round.  apply fexp_correct; auto.\n    apply valid_rnd_round_mode.\n  }\n  assert (xorb (x <? 0) (2^p <? 0) = (x * 2^p <? 0)).\n  {\n    assert (0 < 2^p) by (apply (Zpower_gt_0 radix2); omega).\n    rewrite (Zlt_bool_false (2^p)) by omega. rewrite xorb_false_r.\n    symmetry. generalize (Zlt_bool_spec x 0); intros SPEC; inversion SPEC.\n    apply Zlt_bool_true. apply Z.mul_neg_pos; auto.\n    apply Zlt_bool_false. apply Z.mul_nonneg_nonneg; omega.\n  }\n  generalize (Bmult_correct _ _ _ Hmax nan mode_NE (BofZ x) (BofZ (2^p)))\n             (BofZ_correct (x * 2^p)).\n  fold emin; fold fexp. rewrite A, B, C, D, E, F, H4, H5.\n  destruct Rlt_bool.\n+ intros (P & Q & R) (U & V & W).\n  apply B2R_Bsign_inj; auto.\n  rewrite P, U. auto.\n  rewrite R, W. auto.\n  apply is_finite_not_is_nan; auto.\n+ intros P U.\n  apply B2FF_inj. rewrite P, U. f_equal; auto.\nQed.\n\n(** Rounding to odd the argument of [BofZ]. *)\n\nLemma round_odd_flt:\n  forall prec' emin' x choice,\n  prec > 1 -> prec' > 1 -> prec' >= prec + 2 -> emin' <= emin - 2 ->\n  round radix2 fexp (Znearest choice) (round radix2 (FLT_exp emin' prec') Zrnd_odd x) =\n  round radix2 fexp (Znearest choice) x.\nProof.\n  intros. apply round_N_odd. auto. apply fexp_correct; auto.\n  apply exists_NE_FLT. right; omega.\n  apply FLT_exp_valid. red; omega.\n  apply exists_NE_FLT. right; omega.\n  unfold fexp, FLT_exp; intros. zify; omega.\nQed.\n\nCorollary round_odd_fix:\n  forall x p choice,\n  prec > 1 ->\n  0 <= p ->\n  (bpow radix2 (prec + p + 1) <= Rabs x)%R ->\n  round radix2 fexp (Znearest choice) (round radix2 (FIX_exp p) Zrnd_odd x) =\n  round radix2 fexp (Znearest choice) x.\nProof.\n  intros. 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).\n  set (emin' := emin - 2).\n  assert (PREC: mag radix2 (bpow radix2 (prec + p + 1)) <= mag radix2 x).\n  { rewrite <- (mag_abs radix2 x).\n    apply mag_le; auto. apply bpow_gt_0. }\n  rewrite mag_bpow in PREC.\n  assert (CANON: cexp radix2 (FLT_exp emin' prec') x =\n                 cexp radix2 (FIX_exp p) x).\n  {\n    unfold cexp, FLT_exp, FIX_exp.\n    replace (mag radix2 x - prec') with p by (unfold prec'; omega).\n    apply Z.max_l. unfold emin', emin. red in prec_gt_0_; omega.\n  }\n  assert (RND: round radix2 (FIX_exp p) Zrnd_odd x =\n               round radix2 (FLT_exp emin' prec') Zrnd_odd x).\n  {\n    unfold round, scaled_mantissa. rewrite CANON. auto.\n  }\n  rewrite RND.\n  apply round_odd_flt. auto.\n  unfold prec'. red in prec_gt_0_; omega.\n  unfold prec'. omega.\n  unfold 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:\n  forall n p, 0 <= p ->\n  Zrnd_odd (IZR n * bpow radix2 (-p)) * 2^p =\n  int_round_odd n p.\nProof.\n  intros.\n  assert (0 < 2^p) by (apply (Zpower_gt_0 radix2); omega).\n  assert (n = (n / 2^p) * 2^p + n mod 2^p) by (rewrite Z.mul_comm; apply Z.div_mod; omega).\n  assert (0 <= n mod 2^p < 2^p) by (apply Z_mod_lt; omega).\n  unfold int_round_odd. set (q := n / 2^p) in *; set (r := n mod 2^p) in *.\n  f_equal.\n  pose proof (bpow_gt_0 radix2 (-p)).\n  assert (bpow radix2 p * bpow radix2 (-p) = 1)%R.\n  { rewrite <- bpow_plus. replace (p + -p) with 0 by omega. auto. }\n  assert (IZR n * bpow radix2 (-p) = IZR q + IZR r * bpow radix2 (-p))%R.\n  { rewrite H1. rewrite plus_IZR, mult_IZR.\n    change (IZR (2^p)) with (IZR (radix2^p)).\n    rewrite IZR_Zpower by omega. ring_simplify.\n    rewrite Rmult_assoc. rewrite H4. ring. }\n  assert (0 <= IZR r < bpow radix2 p)%R.\n  { split. change 0%R with (IZR 0). apply IZR_le; omega.\n    rewrite <- IZR_Zpower by omega. apply IZR_lt; tauto. }\n  assert (0 <= IZR r * bpow radix2 (-p) < 1)%R.\n  { generalize (bpow_gt_0 radix2 (-p)). intros.\n    split. apply Rmult_le_pos; lra.\n    rewrite <- H4. apply Rmult_lt_compat_r. auto. tauto. }\n  assert (Zfloor (IZR n * bpow radix2 (-p)) = q).\n  { apply Zfloor_imp. rewrite H5. rewrite plus_IZR. change (IZR 1) with 1%R. lra. }\n  unfold 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. }\n  apply Rmult_integral in H9. destruct H9; [ | lra ].\n  apply (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. }\n  destruct (Z.eqb r 0) eqn:RZ.\n  apply Z.eqb_eq in RZ. rewrite RZ in H9. change (IZR 0) with 0%R in H9.\n  rewrite Rmult_0_l in H9. congruence.\n  rewrite Zceil_floor_neq by lra. rewrite H8.\n  change Zeven with Z.even. rewrite Zodd_even_bool. destruct (Z.even q); auto.\nQed.\n\nLemma int_round_odd_le:\n  forall p x y, 0 <= p ->\n  x <= y -> int_round_odd x p <= int_round_odd y p.\nProof.\n  intros.\n  assert (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.\n    apply IZR_le; auto. }\n  rewrite <- ! Zrnd_odd_int by auto.\n  apply Zmult_le_compat_r. auto. apply (Zpower_ge_0 radix2).\nQed.\n\nLemma int_round_odd_exact:\n  forall p x, 0 <= p ->\n  (2^p | x) -> int_round_odd x p = x.\nProof.\n  intros. unfold int_round_odd. apply Znumtheory.Zdivide_mod in H0.\n  rewrite H0. simpl. rewrite Z.mul_comm. symmetry. apply Z_div_exact_2.\n  apply Z.lt_gt. apply (Zpower_gt_0 radix2). auto. auto.\nQed.\n\nTheorem BofZ_round_odd:\n  forall x p,\n  prec > 1 ->\n  Z.abs x <= 2^emax - 2^(emax-prec) ->\n  0 <= p <= emax - prec ->\n  2^(prec + p + 1) <= Z.abs x ->\n  BofZ x = BofZ (int_round_odd x p).\nProof.\n  intros x p PREC XRANGE PRANGE XGE.\n  assert (DIV: (2^p | 2^emax - 2^(emax - prec))).\n  { rewrite int_upper_bound_eq. apply Z.divide_mul_r.\n    exists (2^(emax - prec - p)). red in prec_gt_0_.\n    rewrite <- (Zpower_plus radix2) by omega. f_equal; omega. }\n  assert (YRANGE: Z.abs (int_round_odd x p) <= 2^emax - 2^(emax-prec)).\n  { apply Z.abs_le. split.\n    replace (-(2^emax - 2^(emax-prec))) with (int_round_odd (-(2^emax - 2^(emax-prec))) p).\n    apply int_round_odd_le; zify; omega.\n    apply int_round_odd_exact. omega. apply Z.divide_opp_r. auto.\n    replace (2^emax - 2^(emax-prec)) with (int_round_odd (2^emax - 2^(emax-prec)) p).\n    apply int_round_odd_le; zify; omega.\n    apply int_round_odd_exact. omega. auto. }\n  destruct (BofZ_finite x XRANGE) as (X1 & X2 & X3).\n  destruct (BofZ_finite (int_round_odd x p) YRANGE) as (Y1 & Y2 & Y3).\n  apply BofZ_finite_equal; auto.\n  rewrite X1, Y1.\n  assert (IZR (int_round_odd x p) = round radix2 (FIX_exp p) Zrnd_odd (IZR x)).\n  {\n     unfold round, scaled_mantissa, cexp, FIX_exp.\n     rewrite <- Zrnd_odd_int by omega.\n     unfold F2R; simpl. rewrite mult_IZR. f_equal. apply (IZR_Zpower radix2). omega.\n  }\n  rewrite H. symmetry. apply round_odd_fix. auto. omega.\n  rewrite <- IZR_Zpower. rewrite <- abs_IZR. apply IZR_le; auto.\n  red in prec_gt_0_; omega.\nQed.\n\nLemma int_round_odd_shifts:\n  forall x p, 0 <= p ->\n  int_round_odd x p =\n  Z.shiftl (if Z.eqb (x mod 2^p) 0 then Z.shiftr x p else Z.lor (Z.shiftr x p) 1) p.\nProof.\n  intros.\n  unfold int_round_odd. rewrite Z.shiftl_mul_pow2 by auto. f_equal.\n  rewrite Z.shiftr_div_pow2 by auto.\n  destruct (x mod 2^p =? 0) eqn:E. auto.\n  assert (forall n, (if Z.odd n then n else n + 1) = Z.lor n 1).\n  { destruct n; simpl; auto.\n    destruct p0; auto.\n    destruct p0; auto. induction p0; auto. }\n  simpl. apply H0.\nQed.\n\nLemma int_round_odd_bits:\n  forall x y p, 0 <= p ->\n  (forall i, 0 <= i < p -> Z.testbit y i = false) ->\n  Z.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) ->\n  int_round_odd x p = y.\nProof.\n  intros until p; intros PPOS BELOW AT ABOVE.\n  rewrite int_round_odd_shifts by auto.\n  apply Z.bits_inj'. intros.\n  generalize (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.\n  replace (p - p) with 0 by omega.\n  destruct (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.\n  destruct (x mod 2^p =? 0).\n  rewrite Z.shiftr_spec by omega. f_equal; omega.\n  rewrite Z.lor_spec, Z.shiftr_spec by omega.\n  change 1 with (Z.ones 1). rewrite Z.ones_spec_high by omega. rewrite orb_false_r.\n  f_equal; omega.\nQed.\n\n(** ** Conversion from a FP number to an integer *)\n\n(** Always rounds toward zero. *)\n\nDefinition ZofB (f: binary_float): option Z :=\n  match 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\n  end.\n\nTheorem ZofB_correct:\n  forall f,\n  ZofB f = if is_finite _ _ f then Some (Ztrunc (B2R _ _ f)) else None.\nProof.\n  destruct f; 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.\n    assert (EQ: forall x, Ztrunc (cond_Ropp s x) = cond_Zopp s (Ztrunc x)).\n    {\n      intros. destruct s; simpl; auto. apply Ztrunc_opp.\n    }\n    rewrite EQ. f_equal.\n    generalize (Zpower_pos_gt_0 2 p (eq_refl _)); intros.\n    rewrite Ztrunc_floor. symmetry. apply Zfloor_div. omega.\n    apply Rmult_le_pos. apply (IZR_le 0). compute; congruence.\n    apply Rlt_le. apply Rinv_0_lt_compat. apply (IZR_lt 0). auto.\nQed.\n\n(** Interval properties. *)\n\nRemark Ztrunc_range_pos:\n  forall x, 0 < Ztrunc x -> (IZR (Ztrunc x) <= x < IZR (Ztrunc x + 1)%Z)%R.\nProof.\n  intros.\n  rewrite Ztrunc_floor. split. apply Zfloor_lb. rewrite plus_IZR. apply Zfloor_ub.\n  generalize (Rle_bool_spec 0%R x). intros RLE; inversion RLE; subst; clear RLE.\n  auto.\n  rewrite Ztrunc_ceil in H by lra. unfold Zceil in H.\n  assert (-x < 0)%R.\n  { apply Rlt_le_trans with (IZR (Zfloor (-x)) + 1)%R. apply Zfloor_ub.\n    change 0%R with (IZR 0). change 1%R with (IZR 1). rewrite <- plus_IZR.\n    apply IZR_le. omega. }\n  lra.\nQed.\n\nRemark Ztrunc_range_zero:\n  forall x, Ztrunc x = 0 -> (-1 < x < 1)%R.\nProof.\n  intros; 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.\n    replace 1%R with (IZR (Zfloor (-x)) + 1)%R. apply Zfloor_ub.\n    unfold 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:\n  forall f n, ZofB f = Some n -> 0 < n -> (IZR n <= B2R _ _ f < IZR (n + 1)%Z)%R.\nProof.\n  intros. rewrite ZofB_correct in H. destruct (is_finite prec emax f) eqn:FIN; inversion H.\n  apply Ztrunc_range_pos. congruence.\nQed.\n\nTheorem ZofB_range_neg:\n  forall f n, ZofB f = Some n -> n < 0 -> (IZR (n - 1)%Z < B2R _ _ f <= IZR n)%R.\nProof.\n  intros. rewrite ZofB_correct in H. destruct (is_finite prec emax f) eqn:FIN; inversion H.\n  set (x := B2R prec emax f) in *. set (y := (-x)%R).\n  assert (A: (IZR (Ztrunc y) <= y < IZR (Ztrunc y + 1)%Z)%R).\n  { apply Ztrunc_range_pos. unfold y. rewrite Ztrunc_opp. omega. }\n  destruct A as [B C].\n  unfold y in B, C. rewrite Ztrunc_opp in B, C.\n  replace (- Ztrunc x + 1) with (- (Ztrunc x - 1)) in C by omega.\n  rewrite opp_IZR in B, C. lra.\nQed.\n\nTheorem ZofB_range_zero:\n  forall f, ZofB f = Some 0 -> (-1 < B2R _ _ f < 1)%R.\nProof.\n  intros. rewrite ZofB_correct in H. destruct (is_finite prec emax f) eqn:FIN; inversion H.\n  apply Ztrunc_range_zero. auto.\nQed.\n\nTheorem ZofB_range_nonneg:\n  forall f n, ZofB f = Some n -> 0 <= n -> (-1 < B2R _ _ f < IZR (n + 1)%Z)%R.\nProof.\n  intros. 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.\n  split; auto. apply Rlt_le_trans with (IZR 0). simpl; lra.\n  apply Rle_trans with (IZR n); auto. apply IZR_le; auto.\nQed.\n\n(** For representable integers, [ZofB] is left inverse of [BofZ]. *)\n\nTheorem ZofBofZ_exact:\n  forall n, integer_representable n -> ZofB (BofZ n) = Some n.\nProof.\n  intros. destruct (BofZ_representable n H) as (A & B & C).\n  rewrite ZofB_correct. rewrite A, B. f_equal. apply Ztrunc_IZR.\nQed.\n\n(** Compatibility with subtraction *)\n\nRemark Zfloor_minus:\n  forall x n, Zfloor (x - IZR n) = Zfloor x - n.\nProof.\n  intros. apply Zfloor_imp. replace (Zfloor x - n + 1) with ((Zfloor x + 1) - n) by omega.\n  rewrite ! minus_IZR. unfold Rminus. split.\n  apply Rplus_le_compat_r. apply Zfloor_lb.\n  apply Rplus_lt_compat_r. rewrite plus_IZR. apply Zfloor_ub.\nQed.\n\nTheorem ZofB_minus:\n  forall minus_nan m f p q,\n  ZofB f = Some p -> 0 <= p < 2*q -> q <= 2^prec -> (IZR q <= B2R _ _ f)%R ->\n  ZofB (Bminus _ _ _ Hmax minus_nan m f (BofZ q)) = Some (p - q).\nProof.\n  intros.\n  assert (Q: -2^prec <= q <= 2^prec).\n  { split; auto.  generalize (Zpower_ge_0 radix2 prec); simpl; omega. }\n  assert (RANGE: (-1 < B2R _ _ f < IZR (p + 1)%Z)%R) by (apply ZofB_range_nonneg; auto; omega).\n  rewrite ZofB_correct in H. destruct (is_finite prec emax f) eqn:FIN; try discriminate.\n  assert (PQ2: (IZR (p + 1) <= IZR q * 2)%R).\n  { change 2%R with (IZR 2). rewrite <- mult_IZR. apply IZR_le. omega. }\n  assert (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.\n    apply sterbenz_aux. apply FLT_exp_valid. auto.\n    apply FLT_exp_monotone. apply generic_format_B2R.\n    apply integer_representable_n. auto. lra. }\n  destruct (BofZ_exact q Q) as (A & B & C).\n  generalize (Bminus_correct _ _ _ Hmax minus_nan m f (BofZ q) FIN B).\n  rewrite Rlt_bool_true.\n- fold emin; fold fexp. intros (D & E & F).\n  rewrite ZofB_correct. rewrite E. rewrite D. rewrite A. rewrite EXACT.\n  inversion H. f_equal. rewrite ! Ztrunc_floor. apply Zfloor_minus.\n  lra. lra.\n- rewrite A. fold emin; fold fexp. rewrite EXACT.\n  apply Rle_lt_trans with (bpow radix2 prec).\n  apply Rle_trans with (IZR q). apply Rabs_le. lra.\n  rewrite <- IZR_Zpower. apply IZR_le; auto. red in prec_gt_0_; omega.\n  apply bpow_lt. auto.\nQed.\n\n(** A variant of [ZofB] that bounds the range of representable integers. *)\n\nDefinition ZofB_range (f: binary_float) (zmin zmax: Z): option Z :=\n  match ZofB f with\n  | None => None\n  | Some z => if Z.leb zmin z && Z.leb z zmax then Some z else None\n  end.\n\nTheorem ZofB_range_correct:\n  forall f min max,\n  let n := Ztrunc (B2R _ _ f) in\n  ZofB_range f min max =\n  if is_finite _ _ f && Z.leb min n && Z.leb n max then Some n else None.\nProof.\n  intros. unfold ZofB_range. rewrite ZofB_correct. fold n.\n  destruct (is_finite prec emax f); auto.\nQed.\n\nLemma ZofB_range_inversion:\n  forall f min max n,\n  ZofB_range f min max = Some n ->\n  min <= n /\\ n <= max /\\ ZofB f = Some n.\nProof.\n  intros. rewrite ZofB_range_correct in H. rewrite ZofB_correct.\n  destruct (is_finite prec emax f); try discriminate.\n  set (n1 := Ztrunc (B2R _ _ f)) in *.\n  destruct (min <=? n1) eqn:MIN; try discriminate.\n  destruct (n1 <=? max) eqn:MAX; try discriminate.\n  simpl in H. inversion H. subst n.\n  split. apply Zle_bool_imp_le; auto.\n  split. apply Zle_bool_imp_le; auto.\n  auto.\nQed.\n\nTheorem ZofB_range_minus:\n  forall minus_nan m f p q,\n  ZofB_range f 0 (2 * q - 1) = Some p -> q <= 2^prec -> (IZR q <= B2R _ _ f)%R ->\n  ZofB_range (Bminus _ _ _ Hmax minus_nan m f (BofZ q)) (-q) (q - 1) = Some (p - q).\nProof.\n  intros. destruct (ZofB_range_inversion _ _ _ _ H) as (A & B & C).\n  set (f' := Bminus prec emax prec_gt_0_ Hmax minus_nan m f (BofZ q)).\n  assert (D: ZofB f' = Some (p - q)).\n  { apply ZofB_minus. auto. omega. auto. auto. }\n  unfold ZofB_range. rewrite D. rewrite Zle_bool_true by omega. rewrite Zle_bool_true by omega. auto.\nQed.\n\n(** ** Algebraic identities *)\n\n(** Commutativity of addition and multiplication *)\n\nTheorem Bplus_commut:\n  forall plus_nan mode (x y: binary_float),\n  plus_nan x y = plus_nan y x ->\n  Bplus _ _ _ Hmax plus_nan mode x y = Bplus _ _ _ Hmax plus_nan mode y x.\nProof.\n  intros until y; intros NAN.\n  pose proof (Bplus_correct _ _ _ Hmax plus_nan mode x y).\n  pose proof (Bplus_correct _ _ _ Hmax plus_nan mode y x).\n  unfold Bplus in *; destruct x; destruct y; auto.\n- rewrite (eqb_sym s0 s). destruct (eqb s s0) eqn:EQB; auto.\n  f_equal; apply eqb_prop; auto.\n- rewrite NAN; auto.\n- rewrite (eqb_sym s0 s). destruct (eqb s s0) eqn:EQB.\n  f_equal; apply eqb_prop; 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- rewrite NAN; auto.\n- generalize (H (eq_refl _) (eq_refl _)); clear H.\n  generalize (H0 (eq_refl _) (eq_refl _)); clear H0.\n  fold emin. fold fexp.\n  set (x := B754_finite prec emax s0 m0 e1 e2). set (rx := B2R _ _ x).\n  set (y := B754_finite prec emax s m e e0). set (ry := B2R _ _ 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 Bmult_commut:\n  forall mult_nan mode (x y: binary_float),\n  mult_nan x y = mult_nan y x ->\n  Bmult _ _ _ Hmax mult_nan mode x y = Bmult _ _ _ Hmax mult_nan mode y x.\nProof.\n  intros until y; intros NAN.\n  pose proof (Bmult_correct _ _ _ Hmax mult_nan mode x y).\n  pose proof (Bmult_correct _ _ _ Hmax mult_nan mode y x).\n  unfold Bmult in *; destruct x; destruct y; auto.\n- rewrite (xorb_comm s0 s); auto.\n- rewrite NAN; auto.\n- rewrite NAN; auto.\n- rewrite (xorb_comm s0 s); auto.\n- rewrite NAN; auto.\n- rewrite (xorb_comm s0 s); auto.\n- rewrite NAN; auto.\n- rewrite (xorb_comm s0 s); auto.\n- rewrite NAN; auto.\n- rewrite NAN; auto.\n- rewrite NAN; auto.\n- rewrite NAN; auto.\n- rewrite (xorb_comm s0 s); auto.\n- rewrite (xorb_comm s0 s); auto.\n- rewrite NAN; auto.\n- revert H H0. fold emin. fold fexp.\n  set (x := B754_finite prec emax s0 m0 e1 e2). set (rx := B2R _ _ x).\n  set (y := B754_finite prec emax s m e e0). set (ry := B2R _ _ y).\n  rewrite (Rmult_comm ry rx).\n  destruct (Rlt_bool (Rabs (round radix2 fexp (round_mode mode) (rx * ry)))\n                     (bpow radix2 emax)).\n  + intros (A1 & A2 & A3) (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.\n    zify. apply Z.mul_comm. apply Z.add_comm.\n  + intros A B. apply B2FF_inj. etransitivity. eapply A. rewrite xorb_comm. auto.\nQed.\n\n(** Multiplication by 2 is diagonal addition. *)\n\nTheorem Bmult2_Bplus:\n  forall plus_nan mult_nan mode (f: binary_float),\n  (forall (x y: binary_float),\n   is_nan _ _ x = true -> is_finite _ _ y = true -> plus_nan x x = mult_nan x y) ->\n  Bplus _ _ _ Hmax plus_nan mode f f = Bmult _ _ _ Hmax mult_nan mode f (BofZ 2%Z).\nProof.\n  intros until f; intros NAN.\n  destruct (BofZ_representable 2) as (A & B & C).\n  apply (integer_representable_2p 1). red in prec_gt_0_; omega.\n  pose proof (Bmult_correct _ _ _ Hmax mult_nan mode f (BofZ 2%Z)). fold emin in H.\n  rewrite A, B, C in H. rewrite xorb_false_r in H.\n  destruct (is_finite _ _ f) eqn:FIN.\n- pose proof (Bplus_correct _ _ _ Hmax plus_nan mode f f FIN FIN). fold emin in H0.\n  assert (EQ: (B2R prec emax f * IZR 2%Z = B2R prec emax f + B2R prec emax f)%R).\n  { change (IZR 2%Z) with 2%R. ring. }\n  rewrite <- EQ in H0. destruct Rlt_bool.\n  + destruct H0 as (P & Q & R). destruct H as (S & T & U).\n    apply B2R_Bsign_inj; auto.\n    rewrite P, S. auto.\n    rewrite R, U.\n    replace 0%R with (0 * IZR 2%Z)%R by ring. rewrite Rcompare_mult_r.\n    rewrite andb_diag, orb_diag. destruct f; try discriminate; simpl.\n    rewrite Rcompare_Eq by auto. destruct mode; auto.\n    replace 0%R with (@F2R radix2 {| Fnum := 0%Z; Fexp := e |}).\n    rewrite Rcompare_F2R. destruct s; auto.\n    unfold F2R. simpl. ring.\n    change 0%R with (IZR 0%Z). apply IZR_lt. omega.\n    destruct (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; try discriminate.\n  + simpl Bplus. rewrite eqb_true. destruct (BofZ 2) eqn:B2; try discriminate; simpl in *.\n    assert ((0 = 2)%Z) by (apply eq_IZR; auto). discriminate.\n    subst s0. rewrite xorb_false_r. auto.\n    auto.\n  + unfold Bplus, Bmult. rewrite <- NAN by auto. auto.\nQed.\n\n(** Divisions that can be turned into multiplications by an inverse *)\n\nDefinition Bexact_inverse_mantissa := Z.iter (prec - 1) xO xH.\n\nRemark Bexact_inverse_mantissa_value:\n  Zpos Bexact_inverse_mantissa = 2 ^ (prec - 1).\nProof.\n  assert (REC: forall n, Z.pos (nat_rect _ xH (fun _ => xO) n) = 2 ^ (Z.of_nat n)).\n  { induction n. reflexivity.\n    simpl nat_rect. transitivity (2 * Z.pos (nat_rect _ xH (fun _ => xO) n)). reflexivity.\n    rewrite Nat2Z.inj_succ. rewrite IHn. unfold Z.succ. rewrite Zpower_plus by omega.\n    change (2 ^ 1) with 2. ring. }\n  red in prec_gt_0_.\n  unfold Bexact_inverse_mantissa. rewrite iter_nat_of_Z by omega. rewrite REC.\n  rewrite Zabs2Nat.id_abs. rewrite Z.abs_eq by omega. auto.\nQed.\n\nRemark Bexact_inverse_mantissa_digits2_pos:\n  Z.pos (digits2_pos Bexact_inverse_mantissa) = prec.\nProof.\n  assert (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. }\n  red in prec_gt_0_.\n  unfold Bexact_inverse_mantissa. rewrite iter_nat_of_Z by omega. rewrite DIGITS.\n  rewrite Zabs2Nat.abs_nat_nonneg, Z2Nat.inj_sub by omega.\n  destruct prec; try  discriminate. rewrite Nat.sub_add.\n  simpl. rewrite Pos2Nat.id. auto.\n  simpl. zify; omega.\nQed.\n\nRemark bounded_Bexact_inverse:\n  forall e,\n  emin <= e <= emax - prec <-> bounded prec emax Bexact_inverse_mantissa e = true.\nProof.\n  intros. unfold bounded, canonical_mantissa. rewrite andb_true_iff.\n  rewrite <- Zeq_is_eq_bool. rewrite <- Zle_is_le_bool.\n  rewrite Bexact_inverse_mantissa_digits2_pos.\n  split.\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 :=\n  match f with\n  | B754_finite _ _ s m e B =>\n      if Pos.eq_dec m Bexact_inverse_mantissa then\n      let e' := -e - (prec - 1) * 2 in\n      if Z_le_dec emin e' then\n      if Z_le_dec e' emax then\n        Some(B754_finite _ _ s m e' _)\n      else None else None else None\n  | _ => None\n  end.\nNext Obligation.\n  rewrite <- bounded_Bexact_inverse in B. rewrite <- bounded_Bexact_inverse.\n  unfold emin in *. omega.\nQed.\n\nLemma Bexact_inverse_correct:\n  forall f f', Bexact_inverse f = Some f' ->\n  is_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).\n  intros f f' EI. unfold Bexact_inverse in EI. destruct f...\n  destruct (Pos.eq_dec m Bexact_inverse_mantissa)...\n  set (e' := -e - (prec - 1) * 2) in *.\n  destruct (Z_le_dec emin e')...\n  destruct (Z_le_dec e' emax)...\n  inversion EI; clear EI; subst f' m.\n  split. auto. split. auto. split. unfold B2R. rewrite Bexact_inverse_mantissa_value.\n  unfold F2R; simpl. rewrite IZR_cond_Zopp.\n  rewrite <- ! cond_Ropp_mult_l.\n  red in prec_gt_0_.\n  replace (IZR (2 ^ (prec - 1))) with (bpow radix2 (prec - 1))\n  by (symmetry; apply (IZR_Zpower radix2); omega).\n  rewrite <- ! bpow_plus.\n  replace (prec - 1 + e') with (- (prec - 1 + e)) by (unfold e'; omega).\n  rewrite bpow_opp. unfold cond_Ropp; destruct s; auto.\n  rewrite Ropp_inv_permute. auto. apply Rgt_not_eq. apply bpow_gt_0.\n  split. simpl. red; intros. apply eq_0_F2R in H. destruct s; simpl in H; discriminate.\n  auto.\nQed.\n\nTheorem Bdiv_mult_inverse:\n  forall div_nan mult_nan mode x y z,\n  (forall (x y z: binary_float),\n   is_nan _ _ x = true -> is_finite _ _ y = true -> is_finite _ _ z = true ->\n   div_nan x y = mult_nan x z) ->\n  Bexact_inverse y = Some z ->\n  Bdiv _ _ _ Hmax div_nan mode x y = Bmult _ _ _ Hmax mult_nan mode x z.\nProof.\n  intros until z; intros NAN; intros. destruct (Bexact_inverse_correct _ _ H) as (A & B & C & D & E).\n  pose proof (Bmult_correct _ _ _ Hmax mult_nan mode x z).\n  fold emin in H0. fold fexp in H0.\n  pose proof (Bdiv_correct _ _ _ Hmax div_nan mode x y D).\n  fold emin in H1. fold fexp in H1.\n  unfold Rdiv in H1. rewrite <- C in H1.\n  destruct (is_finite _ _ x) eqn:FINX.\n- destruct Rlt_bool.\n  + destruct H0 as (P & Q & R). destruct H1 as (S & T & U).\n    apply B2R_Bsign_inj; auto.\n    rewrite Q. simpl. apply is_finite_strict_finite; auto.\n    rewrite P, S. auto.\n    rewrite R, U, E. auto.\n    apply is_finite_not_is_nan; auto.\n    apply 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.\n  destruct x; try discriminate; simpl.\n  + simpl in E; congruence.\n  + erewrite NAN; eauto.\nQed.\n\n(** ** Conversion from scientific notation *)\n\n(** Russian peasant exponentiation *)\n\nFixpoint pos_pow (x y: positive) : positive :=\n  match 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))\n  end.\n\nLemma pos_pow_spec:\n  forall x y, Z.pos (pos_pow x y) = Z.pos x ^ Z.pos y.\nProof.\n  intros x.\n  assert (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  }\n  intros. simpl. rewrite <- Pos2Z.inj_pow_pos. unfold Pos.pow. rewrite REC. rewrite Pos.mul_1_r. auto.\nQed.\n\n(** Given a base [base], a mantissa [m] and an exponent [e], the following function\n  computes the FP number closest to [m * base ^ e], using round to odd, ties break to even.\n  The algorithm is naive, computing [base ^ |e|] exactly before doing a multiplication or\n  division with [m].  However, we treat specially very large or very small values of [e],\n  when the result is known to be [+infinity] or [0.0] respectively. *)\n\nDefinition Bparse (base: positive) (m: positive) (e: Z): binary_float :=\n  match e with\n  | Z0 =>\n     BofZ (Zpos m)\n  | Zpos p =>\n     if e * Z.log2 (Zpos base) <? emax\n     then BofZ (Zpos m * Zpos (pos_pow base p))\n     else B754_infinity _ _ false\n  | Zneg p =>\n     if e * Z.log2 (Zpos base) + Z.log2_up (Zpos m) <? emin\n     then B754_zero _ _ false\n     else FF2B prec emax _ (proj1 (Bdiv_correct_aux prec emax prec_gt_0_ Hmax mode_NE\n                                     false m Z0 false (pos_pow base p) Z0))\n  end.\n\n(** Properties of [Z.log2] and [Z.log2_up]. *)\n\nLemma Zpower_log:\n  forall (base: radix) n,\n  0 < n ->\n  2 ^ (n * Z.log2 base) <= base ^ n <= 2 ^ (n * Z.log2_up base).\nProof.\n  intros.\n  assert (A: 0 < base) by apply radix_gt_0.\n  assert (B: 0 <= Z.log2 base) by apply Z.log2_nonneg.\n  assert (C: 0 <= Z.log2_up base) by apply Z.log2_up_nonneg.\n  destruct (Z.log2_spec base) as [D E]; auto.\n  destruct (Z.log2_up_spec base) as [F G]. apply radix_gt_1.\n  assert (K: 0 <= 2 ^ Z.log2 base) by (apply Z.pow_nonneg; omega).\n  rewrite ! (Z.mul_comm n). rewrite ! Z.pow_mul_r by omega.\n  split; apply Z.pow_le_mono_l; omega.\nQed.\n\nLemma bpow_log_pos:\n  forall (base: radix) n,\n  0 < n ->\n  (bpow radix2 (n * Z.log2 base)%Z <= bpow base n)%R.\nProof.\n  intros. rewrite <- ! IZR_Zpower. apply IZR_le; apply Zpower_log; auto.\n  omega.\n  rewrite Z.mul_comm; apply Zmult_gt_0_le_0_compat. omega. apply Z.log2_nonneg.\nQed.\n\nLemma bpow_log_neg:\n  forall (base: radix) n,\n  n < 0 ->\n  (bpow base n <= bpow radix2 (n * Z.log2 base)%Z)%R.\nProof.\n  intros. set (m := -n). replace n with (-m) by (unfold m; omega).\n  rewrite ! Z.mul_opp_l, ! bpow_opp. apply Rinv_le.\n  apply bpow_gt_0.\n  apply bpow_log_pos. unfold m; omega.\nQed.\n\n(** Overflow and underflow conditions. *)\n\nLemma round_integer_overflow:\n  forall (base: radix) e m,\n  0 < e ->\n  emax <= e * Z.log2 base ->\n  (bpow radix2 emax <= round radix2 fexp (round_mode mode_NE) (IZR (Zpos m) * bpow base e))%R.\nProof.\n  intros.\n  rewrite <- (round_generic radix2 fexp (round_mode mode_NE) (bpow radix2 emax)); auto.\n  apply round_le; auto. apply fexp_correct; auto. apply valid_rnd_round_mode.\n  rewrite <- (Rmult_1_l (bpow radix2 emax)). apply Rmult_le_compat.\n  apply Rle_0_1.\n  apply bpow_ge_0.\n  apply (IZR_le 1). zify; omega.\n  eapply Rle_trans. eapply bpow_le. eassumption. apply bpow_log_pos; auto.\n  apply generic_format_FLT. exists (Float radix2 1 emax).\n  unfold F2R; simpl. ring.\n  simpl. apply (Zpower_gt_1 radix2); auto.\n  simpl. unfold emin; red in prec_gt_0_; omega.\nQed.\n\nLemma round_NE_underflows:\n  forall x,\n  (0 <= x <= bpow radix2 (emin - 1))%R ->\n  round radix2 fexp (round_mode mode_NE) x = 0%R.\nProof.\n  intros.\n  set (eps := bpow radix2 (emin - 1)) in *.\n  assert (A: round radix2 fexp (round_mode mode_NE) eps = 0%R).\n  { unfold round. simpl.\n    assert (E: cexp radix2 fexp eps = emin).\n    { unfold cexp, eps. rewrite mag_bpow. unfold fexp, FLT_exp. zify; red in prec_gt_0_; omega. }\n    unfold scaled_mantissa; rewrite E.\n    assert (P: (eps * bpow radix2 (-emin) = / 2)%R).\n    { unfold eps. rewrite <- bpow_plus. replace (emin - 1 + -emin) with (-1) by omega. auto. }\n    rewrite P. unfold Znearest.\n    assert (F: Zfloor (/ 2)%R = 0).\n    { apply Zfloor_imp. simpl. lra. }\n    rewrite F. change (IZR 0) with 0%R. rewrite Rminus_0_r. rewrite Rcompare_Eq by auto.\n    simpl. unfold F2R; simpl. apply Rmult_0_l.\n  }\n  apply 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)).\n  apply round_le. apply fexp_correct; auto. apply valid_rnd_round_mode. tauto.\nQed.\n\nLemma round_integer_underflow:\n  forall (base: radix) e m,\n  e < 0 ->\n  e * Z.log2 base + Z.log2_up (Zpos m) < emin ->\n  round radix2 fexp (round_mode mode_NE) (IZR (Zpos m) * bpow base e) = 0%R.\nProof.\n  intros. apply round_NE_underflows. split.\n- apply Rmult_le_pos. apply (IZR_le 0). 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.\n  apply (IZR_le 0); zify; omega.\n  apply bpow_ge_0.\n  rewrite <- IZR_Zpower. apply IZR_le.\n  destruct (Z.eq_dec (Z.pos m) 1).\n  rewrite e0. simpl. omega.\n  apply Z.log2_up_spec. zify; omega.\n  apply Z.log2_up_nonneg.\n  apply bpow_log_neg. auto.\n+ apply bpow_le. omega.\nQed.\n\n(** Correctness of Bparse *)\n\nTheorem Bparse_correct:\n  forall b m e (BASE: 2 <= Zpos b),\n  let base := {| radix_val := Zpos b; radix_prop := Zle_imp_le_bool _ _ BASE |} in\n  let r := round radix2 fexp (round_mode mode_NE) (IZR (Zpos m) * bpow base e) in\n  if Rlt_bool (Rabs r) (bpow radix2 emax) then\n     B2R _ _ (Bparse b m e) = r\n  /\\ is_finite _ _ (Bparse b m e) = true\n  /\\ Bsign _ _ (Bparse b m e) = false\n  else\n    B2FF _ _ (Bparse b m e) = F754_infinity false.\nProof.\n  intros.\n  assert (A: forall x, @F2R radix2 {| Fnum := x; Fexp := 0 |} = IZR x).\n  { intros. unfold F2R, Fnum; simpl. ring. }\n  unfold Bparse, r. destruct e as [ | e | e].\n- (* e = Z0 *)\n  change (bpow base 0) with 1%R. rewrite Rmult_1_r.\n  exact (BofZ_correct (Z.pos m)).\n- (* e = Zpos e *)\n  destruct (Z.ltb_spec (Z.pos e * Z.log2 (Z.pos b)) emax).\n+ (* no overflow *)\n  rewrite pos_pow_spec. rewrite <- IZR_Zpower by (zify; omega). rewrite <- mult_IZR.\n  replace false with (Z.pos m * Z.pos b ^ Z.pos e <? 0).\n  exact (BofZ_correct (Z.pos m * Z.pos b ^ Z.pos e)).\n  rewrite Z.ltb_ge. rewrite Z.mul_comm. apply Zmult_gt_0_le_0_compat. zify; omega.  apply (Zpower_ge_0 base).\n+ (* overflow *)\n  rewrite Rlt_bool_false. auto. eapply Rle_trans; [idtac|apply Rle_abs].\n  apply (round_integer_overflow base). zify; omega. auto.\n- (* e = Zneg e *)\n  destruct (Z.ltb_spec (Z.neg e * Z.log2 (Z.pos b) + Z.log2_up (Z.pos m)) emin).\n+ (* undeflow *)\n  rewrite round_integer_underflow; auto.\n  rewrite Rlt_bool_true. auto.\n  replace (Rabs 0)%R with 0%R. apply bpow_gt_0. apply (abs_IZR 0).\n  zify; omega.\n+ (* no underflow *)\n  generalize (Bdiv_correct_aux prec emax prec_gt_0_ Hmax mode_NE false m 0 false (pos_pow b e) 0).\n  set (f := match Fdiv_core_binary prec emax (Z.pos m) 0 (Z.pos (pos_pow b e)) 0 with\n      | (0, _, _) => F754_nan false 1\n      | (Z.pos mz0, ez, lz) =>\n          binary_round_aux prec emax mode_NE (xorb false false) (Z.pos mz0) ez lz\n      | (Z.neg _, _, _) => F754_nan false 1\n      end).\n  fold emin; fold fexp. rewrite ! A. unfold cond_Zopp. rewrite pos_pow_spec.\n  assert (B: (IZR (Z.pos m) / IZR (Z.pos b ^ Z.pos e) =\n              IZR (Z.pos m) * bpow base (Z.neg e))%R).\n  { change (Z.neg e) with (- (Z.pos e)). rewrite bpow_opp. auto. }\n  rewrite B. intros [P Q].\n  destruct (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).\n  split. rewrite B2R_FF2B, Q1. auto.\n  split. rewrite is_finite_FF2B. auto.\n  rewrite Bsign_FF2B. auto.\n* rewrite B2FF_FF2B. auto.\nQed.\n\nEnd Extra_ops.\n\n(** ** Conversions between two FP formats *)\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: bool -> x_nan_pl prec1 -> bool * x_nan_pl prec2) (md: mode) (f: binary_float1) : binary_float2 :=\n  match f with\n    | B754_nan _ _ s pl1 pl1S => let '(s, pl) := conv_nan s (mk_x_nan_pl pl1S) in B754_nan _ _ s (proj1_sig pl) (proj2_sig pl)\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\n  end.\n\nTheorem Bconv_correct:\n  forall conv_nan m f,\n  is_finite _ _ f = true ->\n  if Rlt_bool (Rabs (round radix2 fexp2 (round_mode m) (B2R _ _ f))) (bpow radix2 emax2)\n  then\n     B2R _ _ (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\n  else\n     B2FF _ _ (Bconv conv_nan m f) = binary_overflow prec2 emax2 m (Bsign _ _ f).\nProof.\n  intros. destruct f; try discriminate.\n- simpl. rewrite round_0. rewrite Rabs_R0. rewrite Rlt_bool_true. auto.\n  apply bpow_gt_0. apply valid_rnd_round_mode.\n- generalize (binary_normalize_correct _ _ _ Hmax2 m (cond_Zopp s (Zpos m0)) e s).\n  fold emin2; fold fexp2. simpl. destruct Rlt_bool.\n  + intros (A & B & C). split. auto. split. auto. rewrite C.\n    destruct s; simpl.\n    rewrite Rcompare_Lt. auto. apply F2R_lt_0. simpl. compute; auto.\n    rewrite Rcompare_Gt. auto. apply F2R_gt_0. simpl. compute; auto.\n  + intros A. rewrite A. f_equal. destruct s.\n    apply Rlt_bool_true. apply F2R_lt_0. simpl. compute; auto.\n    apply Rlt_bool_false. apply Rlt_le. apply Rgt_lt. apply F2R_gt_0. simpl. compute; auto.\nQed.\n\n(** Converting a finite FP number to higher or equal precision preserves its value. *)\n\nTheorem Bconv_widen_exact:\n  (prec2 >= prec1)%Z -> (emax2 >= emax1)%Z ->\n  forall conv_nan m f,\n  is_finite _ _ f = true ->\n     B2R _ _ (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.\n  intros PREC EMAX; intros. generalize (Bconv_correct conv_nan m f H).\n  assert (LT: (Rabs (B2R _ _ f) < bpow radix2 emax2)%R).\n  {\n    destruct f; try discriminate; simpl.\n    rewrite Rabs_R0. apply bpow_gt_0.\n    apply Rlt_le_trans with (bpow radix2 emax1).\n    rewrite F2R_cond_Zopp. rewrite abs_cond_Ropp. rewrite <- F2R_Zabs. simpl Z.abs.\n    eapply bounded_lt_emax; eauto.\n    apply bpow_le. omega.\n  }\n  assert (EQ: round radix2 fexp2 (round_mode m) (B2R prec1 emax1 f) = B2R prec1 emax1 f).\n  {\n    apply round_generic. apply valid_rnd_round_mode. eapply generic_inclusion_le.\n    5: apply generic_format_B2R. apply fexp_correct; auto. apply fexp_correct; auto.\n    instantiate (1 := emax2). intros. unfold fexp2, FLT_exp. unfold emin2. zify; omega.\n    apply Rlt_le; auto.\n  }\n  rewrite EQ. rewrite Rlt_bool_true by auto. auto.\nQed.\n\n(** Conversion from integers and change of format *)\n\nTheorem Bconv_BofZ:\n  forall conv_nan n,\n  integer_representable prec1 emax1 n ->\n  Bconv conv_nan mode_NE (BofZ prec1 emax1 _ Hmax1 n) = BofZ prec2 emax2 _ Hmax2 n.\nProof.\n  intros.\n  destruct (BofZ_representable _ _ _ Hmax1 n H) as (A & B & C).\n  set (f := BofZ prec1 emax1 prec1_gt_0_ Hmax1 n) in *.\n  generalize (Bconv_correct conv_nan mode_NE f B).\n  unfold BofZ.\n  generalize (binary_normalize_correct _ _ _ Hmax2 mode_NE n 0 false).\n  fold emin2; fold fexp2. rewrite A.\n  replace (F2R {| Fnum := n; Fexp := 0 |}) with (IZR n).\n  destruct Rlt_bool.\n- intros (P & Q & R) (D & E & F). apply B2R_Bsign_inj; auto.\n  congruence. rewrite F, C, R. change 0%R with (IZR 0). rewrite Rcompare_IZR.\n  unfold Z.ltb. auto.\n- intros P Q. apply B2FF_inj. rewrite P, Q. rewrite C. f_equal. change 0%R with (IZR 0).\n  generalize (Zlt_bool_spec n 0); intros LT; inversion LT.\n  rewrite Rlt_bool_true; auto. apply IZR_lt; auto.\n  rewrite Rlt_bool_false; auto. apply IZR_le; auto.\n- unfold F2R; simpl. rewrite Rmult_1_r. auto.\nQed.\n\n(** Change of format (to higher precision) and conversion to integer. *)\n\nTheorem ZofB_Bconv:\n  prec2 >= prec1 -> emax2 >= emax1 ->\n  forall conv_nan m f n,\n  ZofB _ _ f = Some n -> ZofB _ _ (Bconv conv_nan m f) = Some n.\nProof.\n  intros. rewrite ZofB_correct in H1. destruct (is_finite _ _ f) eqn:FIN; inversion H1.\n  destruct (Bconv_widen_exact H H0 conv_nan m f) as (A & B & C). auto.\n  rewrite ZofB_correct. rewrite B. rewrite A. auto.\nQed.\n\nTheorem ZofB_range_Bconv:\n  forall min1 max1 min2 max2,\n  prec2 >= prec1 -> emax2 >= emax1 -> min2 <= min1 -> max1 <= max2 ->\n  forall conv_nan m f n,\n  ZofB_range _ _ f min1 max1 = Some n ->\n  ZofB_range _ _ (Bconv conv_nan m f) min2 max2 = Some n.\nProof.\n  intros.\n  destruct (ZofB_range_inversion _ _ _ _ _ _ H3) as (A & B & C).\n  unfold ZofB_range. erewrite ZofB_Bconv by eauto.\n  rewrite ! Zle_bool_true by omega. auto.\nQed.\n\n(** Change of format (to higher precision) and comparison. *)\n\nTheorem Bcompare_Bconv_widen:\n  prec2 >= prec1 -> emax2 >= emax1 ->\n  forall conv_nan m x y,\n  Bcompare _ _ (Bconv conv_nan m x) (Bconv conv_nan m y) = Bcompare _ _ x y.\nProof.\n  intros. destruct (is_finite _ _ x && is_finite _ _ y) eqn:FIN.\n- apply andb_true_iff in FIN. destruct FIN.\n  destruct (Bconv_widen_exact H H0 conv_nan m x H1) as (A & B & C).\n  destruct (Bconv_widen_exact H H0 conv_nan m y H2) as (D & E & F).\n  rewrite ! 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.\n  destruct x, y; try discriminate; simpl in P, Q; simpl;\n  repeat (match goal with |- context [conv_nan ?b ?pl] => destruct (conv_nan b pl) end);\n  auto.\n  destruct Q as (D & E & F); auto.\n  destruct (binary_normalize prec2 emax2 prec2_gt_0_ Hmax2 m (cond_Zopp s0 (Z.pos m0)) e s0);\n  discriminate || reflexivity.\n  destruct P as (A & B & C); auto.\n  destruct (binary_normalize prec2 emax2 prec2_gt_0_ Hmax2 m (cond_Zopp s (Z.pos m0)) e s);\n  try discriminate; simpl. destruct s; auto. destruct s, s1; auto.\n  destruct P as (A & B & C); auto.\n  destruct (binary_normalize prec2 emax2 prec2_gt_0_ Hmax2 m (cond_Zopp s (Z.pos m0)) e s);\n  try discriminate; simpl. destruct s; auto.\n  destruct s, s1; auto.\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(** Converting to a higher precision then down to the original format\n    is the identity. *)\nTheorem Bconv_narrow_widen:\n  prec2 >= prec1 -> emax2 >= emax1 ->\n  forall narrow_nan widen_nan m f,\n  is_nan _ _ f = false ->\n  Bconv prec2 emax2 prec1 emax1 _ Hmax1 narrow_nan m (Bconv prec1 emax1 prec2 emax2 _ Hmax2 widen_nan m f) = f.\nProof.\n  intros. 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. }\n  generalize (Bconv_widen_exact _ _ _ _ _ _ Hmax2 H H0 widen_nan m f FIN).\n  set (f' := Bconv prec1 emax1 prec2 emax2 _ Hmax2 widen_nan m f).\n  intros (A & B & C).\n  generalize (Bconv_correct _ _ _ _ _ Hmax1 narrow_nan m f' B).\n  fold emin1. fold fexp1. rewrite A, C, EQ. rewrite Rlt_bool_true.\n  intros (D & E & F).\n  apply B2R_Bsign_inj; auto.\n  destruct f; try discriminate; simpl.\n  rewrite Rabs_R0. apply bpow_gt_0.\n  rewrite F2R_cond_Zopp. rewrite abs_cond_Ropp. rewrite <- F2R_Zabs. simpl Z.abs.\n  eapply bounded_lt_emax; eauto.\n- destruct f; try discriminate. simpl. auto.\nQed.\n\nEnd Compose_Conversions.\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/Numeric/Fappli_IEEE_extra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.28373174373828974}}
{"text": "Require Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Integers.\nRequire Import compcert.common.Values.\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Memtype.\nRequire Import compcert.cfrontend.Ctypes.\nRequire Export liblayers.lib.OptionMonad.\n\n(** * Generic semantics from abstract functions *)\n\nInductive Z64 := VZ64 (z: Z).\n\nFunction Z642Z (z: Z64) :=\n  match z with\n    | VZ64 z' => z'\n  end.\n\nInductive Zsign := VZS (z: Z).\n\nFunction Zsign2Z (z: Zsign) :=\n  match z with\n    | VZS z' => z'\n  end.\n\nClass Semof (data: Type) T (targs: typelist) (tres: type) :=\n  semof : T -> (list val -> data -> val -> data -> Prop).\n\nClass Semprops {data} T `{Tsemof: Semof data T} :=\n{\n  semprops_well_typed f vargs d vres d':\n    semof f vargs d vres d' ->\n    Val.has_type vres (typ_of_type tres);\n\n  semprops_arity f vargs d vres d':\n    semof f vargs d vres d' ->\n    length vargs = length (typlist_of_typelist targs);\n\n  semprops_lessdef f vargs vargs' d vres d':\n    semof f vargs d vres d' ->\n    Val.lessdef_list vargs vargs' ->\n    vargs' = vargs;\n\n  semprops_inject_neutral f vargs d vres d' j:\n    semof f vargs d vres d' ->\n    Val.inject j vres vres;\n\n  semprops_determ f vargs d vres1 vres2 d1 d2:\n    semof f vargs d vres1 d1 ->\n    semof f vargs d vres2 d2 ->\n    vres1 = vres2 /\\ d1 = d2;\n\n  semprops_inject f ι vargs vargs' d vres d':\n    semof f vargs d vres d' ->\n    Val.inject_list ι vargs vargs' ->\n    vargs' = vargs\n}.\n\n(** ** Basic instances *)\n\nSection INSTANCES.\n  Context {data : Type}.\n\n  Notation type_int32 := (Tint I32 Signed noattr).\n  Notation type_int32u := (Tint I32 Unsigned noattr).\n  Notation type_int64u := (Tlong Unsigned noattr).\n\n  Inductive semof_nil_void: Semof data (data -> option data) Tnil Tvoid :=\n    | semof_nil_void_intro f d d':\n        f d = ret d' ->\n        semof f nil d Vundef d'.\n\n  Global Existing Instance semof_nil_void.\n\n  Global Instance semof_nil_void_props: Semprops (data -> option data).\n  Proof.\n    split.\n    + (* semprops_well_typed *)\n      intros ? ? ? ? ? H.\n      inv H.\n      simpl.\n      tauto.\n    + (* semprops_arity *)\n      intros ? ? ? ? ? H.\n      inv H;\n      reflexivity.\n    + (* semprops_lessdef *)\n      intros ? ? ? ? ? ? H Hl.\n      inv H;\n      inv Hl;\n      reflexivity.\n    + (* semprops_inject_neutral *)\n      inversion 1; subst.\n      constructor.\n    + (* semprops_determ *)\n      inversion 1.\n      inversion 1.\n      unfold bind, ret in *; simpl in *.\n      split; congruence.\n    + (* semprops_inject *)\n      inversion 1.\n      inversion 1.\n      reflexivity.\n  Qed.\n\n  (* Special case for total void functions. *)\n\n  Local Notation lift_nil_void_total f :=\n    (fun d => ret (f d)).\n\n  Global Instance semof_nil_void_total: Semof data (data -> data) Tnil Tvoid :=\n    fun f => semof (lift_nil_void_total f).\n\n  Global Instance semof_nil_void_total_props: Semprops (data -> data).\n  Proof.\n    split; intro f.\n    + exact (semprops_well_typed (lift_nil_void_total f)).\n    + exact (semprops_arity (lift_nil_void_total f)).\n    + exact (semprops_lessdef (lift_nil_void_total f)).\n    + exact (semprops_inject_neutral (lift_nil_void_total f)).\n    + exact (semprops_determ (lift_nil_void_total f)).\n    + exact (semprops_inject (lift_nil_void_total f)).\n  Qed.\n\n  Inductive semof_nil_int: Semof data (data -> option (data * Z)) Tnil type_int32u :=\n    | semof_nil_int_intro f d z d':\n        f d = ret (d', Int.unsigned z) ->\n        semof f nil d (Vint z) d'.\n\n  Global Existing Instance semof_nil_int.\n\n  Global Instance semof_nil_int_props: Semprops (data -> option (data * Z)).\n  Proof.\n    split.\n    + (* semprops_well_typed *)\n      intros ? ? ? ? ? H.\n      inv H.\n      simpl.\n      tauto.\n    + (* semprops_arity *)\n      intros ? ? ? ? ? H.\n      inv H;\n      reflexivity.\n    + (* semprops_lessdef *)\n      intros ? ? ? ? ? ? H Hl.\n      inv H;\n      inv Hl;\n      reflexivity.\n    + (* semprops_inject_neutral *)\n      inversion 1; subst.\n      constructor.\n    + (* semprops_determ *)\n      inversion 1.\n      inversion 1.\n      unfold bind, ret in *; simpl in *.\n      split; try congruence.\n      rewrite H0 in H7.\n      inv H7.\n      rewrite <- Int.repr_unsigned with z.\n      rewrite <- Int.repr_unsigned with z0.\n      congruence.\n    + (* semprops_inject *)\n      inversion 1.\n      inversion 1.\n      reflexivity.\n  Qed.\n\n  Inductive semof_nil_nat: Semof data (data -> (data * nat)) Tnil type_int32u :=\n    | semof_nil_nat_intro f d z d':\n        f d = (d', Z.to_nat (Int.unsigned z)) ->\n        semof f nil d (Vint z) d'.\n\n  Global Existing Instance semof_nil_nat.\n\n  Global Instance semof_nil_nat_props: Semprops (data -> data * nat).\n  Proof.\n    split.\n    + (* semprops_well_typed *)\n      intros ? ? ? ? ? H.\n      inv H.\n      simpl.\n      tauto.\n    + (* semprops_arity *)\n      intros ? ? ? ? ? H.\n      inv H;\n      reflexivity.\n    + (* semprops_lessdef *)\n      intros ? ? ? ? ? ? H Hl.\n      inv H;\n      inv Hl;\n      reflexivity.\n    + (* semprops_inject_neutral *)\n      inversion 1; subst.\n      constructor.\n    + (* semprops_determ *)\n      inversion 1.\n      inversion 1.\n      unfold bind, ret in *; simpl in *.\n      split; try congruence.\n      rewrite H0 in H7.\n      inv H7.\n      apply Z2Nat.inj in H14.\n      rewrite <- Int.repr_unsigned with z.\n      rewrite <- Int.repr_unsigned with z0.\n      congruence.\n      apply Int.unsigned_range.\n      apply Int.unsigned_range.\n    + (* semprops_inject *)\n      inversion 1.\n      inversion 1.\n      reflexivity.\n  Qed.\n\n  Inductive semof_opt_nil_nat: Semof data (data -> option (data * nat)) Tnil type_int32u :=\n    | semof_opt_nil_nat_intro f d z d':\n        f d = ret (d', Z.to_nat (Int.unsigned z)) ->\n        semof f nil d (Vint z) d'.\n\n  Global Existing Instance semof_opt_nil_nat.\n\n  Global Instance semof_opt_nil_nat_props: Semprops (data -> option (data * nat)).\n  Proof.\n    split.\n    + (* semprops_well_typed *)\n      intros ? ? ? ? ? H.\n      inv H.\n      simpl.\n      tauto.\n    + (* semprops_arity *)\n      intros ? ? ? ? ? H.\n      inv H;\n      reflexivity.\n    + (* semprops_lessdef *)\n      intros ? ? ? ? ? ? H Hl.\n      inv H;\n      inv Hl;\n      reflexivity.\n    + (* semprops_inject_neutral *)\n      inversion 1; subst.\n      constructor.\n    + (* semprops_determ *)\n      inversion 1.\n      inversion 1.\n      unfold bind, ret in *; simpl in *.\n      split; try congruence.\n      rewrite H0 in H7.\n      inv H7.\n      apply Z2Nat.inj in H14.\n      rewrite <- Int.repr_unsigned with z.\n      rewrite <- Int.repr_unsigned with z0.\n      congruence.\n      apply Int.unsigned_range.\n      apply Int.unsigned_range.\n    + (* semprops_inject *)\n      inversion 1.\n      inversion 1.\n      reflexivity.\n  Qed.\n\n  (* Special case for pure functions *)\n\n  Local Notation lift_nil_int_pure f :=\n    (fun d => z <- f d; ret (d, z)).\n\n  Global Instance semof_nil_int_pure: Semof data (data -> option Z) Tnil type_int32u :=\n    fun f => semof (lift_nil_int_pure f).\n\n  Global Instance semof_nil_nat_pure: Semof data (data -> option nat) Tnil type_int32u :=\n    fun f => semof (lift_nil_int_pure f).\n\n  Global Instance semof_nil_int_pure_props: Semprops (data -> option Z).\n  Proof.\n    split; intro f.\n    + exact (semprops_well_typed (lift_nil_int_pure f)).\n    + exact (semprops_arity (lift_nil_int_pure f)).\n    + exact (semprops_lessdef (lift_nil_int_pure f)).\n    + exact (semprops_inject_neutral (lift_nil_int_pure f)).\n    + exact (semprops_determ (lift_nil_int_pure f)).\n    + exact (semprops_inject (lift_nil_int_pure f)).\n  Qed.\n\n  Global Instance semof_nil_nat_pure_props: Semprops (data -> option nat).\n  Proof.\n    split; intro f.\n    + exact (semprops_well_typed (lift_nil_int_pure f)).\n    + exact (semprops_arity (lift_nil_int_pure f)).\n    + exact (semprops_lessdef (lift_nil_int_pure f)).\n    + exact (semprops_inject_neutral (lift_nil_int_pure f)).\n    + exact (semprops_determ (lift_nil_int_pure f)).\n    + exact (semprops_inject (lift_nil_int_pure f)).\n  Qed.\n\n  (* Special case for pure total functions *)\n\n  Local Notation lift_nil_int_pure_total f :=\n    (fun d => ret (f d)).\n\n  Global Instance semof_nil_int_pure_total: Semof data (data -> Z) Tnil type_int32u :=\n    fun f => semof (lift_nil_int_pure_total f).\n\n  Global Instance semof_nil_nat_pure_total: Semof data (data -> nat) Tnil type_int32u :=\n    fun f => semof (lift_nil_int_pure_total f).\n\n  Global Instance semof_nil_int_pure_total_props: Semprops (data -> Z).\n  Proof.\n    split; intro f.\n    + exact (semprops_well_typed (lift_nil_int_pure_total f)).\n    + exact (semprops_arity (lift_nil_int_pure_total f)).\n    + exact (semprops_lessdef (lift_nil_int_pure_total f)).\n    + exact (semprops_inject_neutral (lift_nil_int_pure_total f)).\n    + exact (semprops_determ (lift_nil_int_pure_total f)).\n    + exact (semprops_inject (lift_nil_int_pure_total f)).\n  Qed.\n\n  Global Instance semof_nil_nat_pure_total_props: Semprops (data -> nat).\n  Proof.\n    split; intro f.\n    + exact (semprops_well_typed (lift_nil_int_pure_total f)).\n    + exact (semprops_arity (lift_nil_int_pure_total f)).\n    + exact (semprops_lessdef (lift_nil_int_pure_total f)).\n    + exact (semprops_inject_neutral (lift_nil_int_pure_total f)).\n    + exact (semprops_determ (lift_nil_int_pure_total f)).\n    + exact (semprops_inject (lift_nil_int_pure_total f)).\n  Qed.\n\n  Inductive semof_cons `{Semof data}: Semof data (Z -> T) (Tcons type_int32u targs) tres :=\n    semof_cons_intro f (i: int) l d v d':\n      semof (f (Int.unsigned i)) l d v d' ->\n      semof f (Vint i :: l) d v d'.\n\n  Global Existing Instance semof_cons.\n\n  Global Instance semof_cons_props {T} `(HT: Semprops data T): Semprops (Z -> T).\n  Proof.\n    split.\n    + (* semprops_well_typed *)\n      intros ? ? ? ? ? H.\n      inv H.\n      apply (semprops_well_typed (targs := targs) (f (Int.unsigned i)) l d vres d').\n      eassumption.\n    + (* semprops_arity *)\n      intros ? ? ? ? ? H.\n      inv H.\n      simpl.\n      f_equal.\n      eapply semprops_arity.\n      eassumption.\n    + (* semprops_lessdef *)\n      intros until d'.\n      intros H Hl.\n      inv H.\n      inv Hl.\n      inv H2.\n      f_equal.\n      eapply semprops_lessdef;\n      eassumption.\n    + (* semprops_inject_neutral *)\n      inversion 1; subst.\n      eapply semprops_inject_neutral.\n      eassumption.\n    + (* semprops_determ *)\n      inversion 1.\n      inversion 1.\n      eapply semprops_determ; eassumption.\n    + (* semprops_inject *)\n      intros.\n      inv H.\n      inv H0.\n      inv H3.\n      f_equal.\n      eapply semprops_inject; eassumption.\n  Qed.\n\n  Inductive semof_nil_intsigned: Semof data (data -> option (data * Zsign)) Tnil type_int32 :=\n    | semof_nil_intsigned_intro f d z d':\n        f d = ret (d', VZS (Int.signed z)) ->\n        semof f nil d (Vint z) d'.\n\n  Global Existing Instance semof_nil_intsigned.\n\n  Global Instance semof_nil_intsigned_props: Semprops (data -> option (data * Zsign)).\n  Proof.\n    split.\n    + (* semprops_well_typed *)\n      intros ? ? ? ? ? H.\n      inv H.\n      cbn; trivial.\n    + (* semprops_arity *)\n      intros ? ? ? ? ? H.\n      inv H;\n      reflexivity.\n    + (* semprops_lessdef *)\n      intros ? ? ? ? ? ? H Hl.\n      inv H;\n      inv Hl;\n      reflexivity.\n    + (* semprops_inject_neutral *)\n      inversion 1; subst.\n      constructor.\n    + (* semprops_determ *)\n      inversion 1.\n      inversion 1.\n      cbn in *; subst.\n      rewrite H0 in H7.\n      inv H7.\n      rewrite <- (Int.repr_signed z).\n      rewrite <- (Int.repr_signed z0).\n      rewrite H3.\n      auto.\n    + (* semprops_inject *)\n      inversion 1.\n      inversion 1.\n      reflexivity.\n  Qed.\n\n  (* Special case for pure functions *)\n  Global Instance semof_nil_intsigned_pure: Semof data (data -> option Zsign) Tnil type_int32 :=\n    fun f => semof (lift_nil_int_pure f).\n\n  Global Instance semof_nil_intsigned_pure_props: Semprops (data -> option Zsign).\n  Proof.\n    split; intro f.\n    + exact (semprops_well_typed (lift_nil_int_pure f)).\n    + exact (semprops_arity (lift_nil_int_pure f)).\n    + exact (semprops_lessdef (lift_nil_int_pure f)).\n    + exact (semprops_inject_neutral (lift_nil_int_pure f)).\n    + exact (semprops_determ (lift_nil_int_pure f)).\n    + exact (semprops_inject (lift_nil_int_pure f)).\n  Qed.\n\n  (* Special case for pure total functions *)\n  Global Instance semof_nil_intsigned_pure_total: Semof data (data -> Zsign) Tnil type_int32 :=\n    fun f => semof (lift_nil_int_pure_total f).\n\n  Global Instance semof_nil_intsigned_pure_total_props: Semprops (data -> Zsign).\n  Proof.\n    split; intro f.\n    + exact (semprops_well_typed (lift_nil_int_pure_total f)).\n    + exact (semprops_arity (lift_nil_int_pure_total f)).\n    + exact (semprops_lessdef (lift_nil_int_pure_total f)).\n    + exact (semprops_inject_neutral (lift_nil_int_pure_total f)).\n    + exact (semprops_determ (lift_nil_int_pure_total f)).\n    + exact (semprops_inject (lift_nil_int_pure_total f)).\n  Qed.\n\n  Inductive semof_cons_signed `{Semof data}: Semof data (Zsign -> T) (Tcons type_int32 targs) tres :=\n    semof_cons_signed_intro f (i: int) l d v d':\n      semof (f (VZS (Int.signed i))) l d v d' ->\n      semof f (Vint i :: l) d v d'.\n\n  Global Existing Instance semof_cons_signed.\n\n  Global Instance semof_cons_signed_props {T} `(HT: Semprops data T): Semprops (Zsign -> T).\n  Proof.\n    split.\n    + (* semprops_well_typed *)\n      intros ? ? ? ? ? H.\n      inv H.\n      apply (semprops_well_typed (targs := targs) (f (VZS (Int.signed i))) l d vres d').\n      eassumption.\n    + (* semprops_arity *)\n      intros ? ? ? ? ? H.\n      inv H.\n      simpl.\n      f_equal.\n      eapply semprops_arity.\n      eassumption.\n    + (* semprops_lessdef *)\n      intros until d'.\n      intros H Hl.\n      inv H.\n      inv Hl.\n      inv H2.\n      f_equal.\n      eapply semprops_lessdef;\n      eassumption.\n    + (* semprops_inject_neutral *)\n      inversion 1; subst.\n      eapply semprops_inject_neutral.\n      eassumption.\n    + (* semprops_determ *)\n      inversion 1.\n      inversion 1.\n      eapply semprops_determ; eassumption.\n    + (* semprops_inject *)\n      intros.\n      inv H.\n      inv H0.\n      inv H3.\n      f_equal.\n      eapply semprops_inject; eassumption.\n  Qed.\n\n  Inductive semof_nil_int64: Semof data (data -> option (data * Z64)) Tnil type_int64u :=\n    | semof_nil_int64_intro f d z d':\n        f d = ret (d', VZ64 (Int64.unsigned z)) ->\n        semof f nil d (Vlong z) d'.\n\n  Global Existing Instance semof_nil_int64.\n\n  Global Instance semof_nil_int64_props: Semprops (data -> option (data * Z64)).\n  Proof.\n    split.\n    + (* semprops_well_typed *)\n      intros ? ? ? ? ? H.\n      inv H.\n      simpl.\n      tauto.\n    + (* semprops_arity *)\n      intros ? ? ? ? ? H.\n      inv H;\n      reflexivity.\n    + (* semprops_lessdef *)\n      intros ? ? ? ? ? ? H Hl.\n      inv H;\n      inv Hl;\n      reflexivity.\n    + (* semprops_inject_neutral *)\n      inversion 1; subst.\n      constructor.\n    + (* semprops_determ *)\n      inversion 1.\n      inversion 1.\n      unfold bind, ret in *; simpl in *.\n      split; try congruence.\n      rewrite H0 in H7.\n      inv H7.\n      rewrite <- Int64.repr_unsigned with z.\n      rewrite <- Int64.repr_unsigned with z0.\n      congruence.\n    + (* semprops_inject *)\n      inversion 1.\n      inversion 1.\n      reflexivity.\n  Qed.\n\n  (* Special case for pure functions *)\n  Global Instance semof_nil_int64_pure: Semof data (data -> option Z64) Tnil type_int64u :=\n    fun f => semof (lift_nil_int_pure f).\n\n  Global Instance semof_nil_int64_pure_props: Semprops (data -> option Z64).\n  Proof.\n    split; intro f.\n    + exact (semprops_well_typed (lift_nil_int_pure f)).\n    + exact (semprops_arity (lift_nil_int_pure f)).\n    + exact (semprops_lessdef (lift_nil_int_pure f)).\n    + exact (semprops_inject_neutral (lift_nil_int_pure f)).\n    + exact (semprops_determ (lift_nil_int_pure f)).\n    + exact (semprops_inject (lift_nil_int_pure f)).\n  Qed.\n\n  (* Special case for pure total functions *)\n  Global Instance semof_nil_int64_pure_total: Semof data (data -> Z64) Tnil type_int64u :=\n    fun f => semof (lift_nil_int_pure_total f).\n\n  Global Instance semof_nil_int64_pure_total_props: Semprops (data -> Z64).\n  Proof.\n    split; intro f.\n    + exact (semprops_well_typed (lift_nil_int_pure_total f)).\n    + exact (semprops_arity (lift_nil_int_pure_total f)).\n    + exact (semprops_lessdef (lift_nil_int_pure_total f)).\n    + exact (semprops_inject_neutral (lift_nil_int_pure_total f)).\n    + exact (semprops_determ (lift_nil_int_pure_total f)).\n    + exact (semprops_inject (lift_nil_int_pure_total f)).\n  Qed.\n\n  Inductive semof_cons64 `{Semof data}: Semof data (Z64 -> T) (Tcons type_int64u targs) tres :=\n    semof_cons64_intro f (i: int64) l d v d':\n      semof (f (VZ64 (Int64.unsigned i))) l d v d' ->\n      semof f (Vlong i :: l) d v d'.\n\n  Global Existing Instance semof_cons64.\n\n  Global Instance semof_cons64_props {T} `(HT: Semprops data T): Semprops (Z64 -> T).\n  Proof.\n    split.\n    + (* semprops_well_typed *)\n      intros ? ? ? ? ? H.\n      inv H.\n      apply (semprops_well_typed (targs := targs) (f (VZ64 (Int64.unsigned i))) l d vres d').\n      eassumption.\n    + (* semprops_arity *)\n      intros ? ? ? ? ? H.\n      inv H.\n      simpl.\n      f_equal.\n      eapply semprops_arity.\n      eassumption.\n    + (* semprops_lessdef *)\n      intros until d'.\n      intros H Hl.\n      inv H.\n      inv Hl.\n      inv H2.\n      f_equal.\n      eapply semprops_lessdef;\n      eassumption.\n    + (* semprops_inject_neutral *)\n      inversion 1; subst.\n      eapply semprops_inject_neutral.\n      eassumption.\n    + (* semprops_determ *)\n      inversion 1.\n      inversion 1.\n      eapply semprops_determ; eassumption.\n    + (* semprops_inject *)\n      intros.\n      inv H.\n      inv H0.\n      inv H3.\n      f_equal.\n      eapply semprops_inject; eassumption.\n  Qed.\n\n  Inductive semof_nil_bool: Semof data (data -> option (data * bool)) Tnil type_int32u :=\n    | semof_nil_bool_intro f d b d':\n        f d = ret (d', b) ->\n        semof f nil d (Val.of_bool b) d'.\n\n  Global Existing Instance semof_nil_bool.\n\n  Global Instance semof_nil_bool_props: Semprops (data -> option (data * bool)).\n  Proof.\n    split.\n    + (* semprops_well_typed *)\n      intros ? ? ? ? ? H.\n      inv H.\n      destruct b; cbn; tauto.\n    + (* semprops_arity *)\n      intros ? ? ? ? ? H.\n      inv H; reflexivity.\n    + (* semprops_lessdef *)\n      intros ? ? ? ? ? ? H Hl.\n      inv H; inv Hl; reflexivity.\n    + (* semprops_inject_neutral *)\n      inversion 1; subst.\n      destruct b; constructor.\n    + (* semprops_determ *)\n      inversion 1.\n      inversion 1.\n      subst.\n      rewrite H0 in H7; inv H7.\n      tauto.\n    + (* semprops_inject *)\n      inversion 1.\n      inversion 1.\n      reflexivity.\n  Qed.\n\n  (* Special case for pure functions *)\n  Global Instance semof_nil_bool_pure: Semof data (data -> option bool) Tnil type_int32u :=\n    fun f => semof (lift_nil_int_pure f).\n\n  Global Instance semof_nil_bool_pure_props: Semprops (data -> option bool).\n  Proof.\n    split; intro f.\n    + exact (semprops_well_typed (lift_nil_int_pure f)).\n    + exact (semprops_arity (lift_nil_int_pure f)).\n    + exact (semprops_lessdef (lift_nil_int_pure f)).\n    + exact (semprops_inject_neutral (lift_nil_int_pure f)).\n    + exact (semprops_determ (lift_nil_int_pure f)).\n    + exact (semprops_inject (lift_nil_int_pure f)).\n  Qed.\n\n  (* Special case for pure total functions *)\n  Global Instance semof_nil_bool_pure_total: Semof data (data -> bool) Tnil type_int32u :=\n    fun f => semof (lift_nil_int_pure_total f).\n\n  Global Instance semof_nil_bool_pure_total_props: Semprops (data -> bool).\n  Proof.\n    split; intro f.\n    + exact (semprops_well_typed (lift_nil_int_pure_total f)).\n    + exact (semprops_arity (lift_nil_int_pure_total f)).\n    + exact (semprops_lessdef (lift_nil_int_pure_total f)).\n    + exact (semprops_inject_neutral (lift_nil_int_pure_total f)).\n    + exact (semprops_determ (lift_nil_int_pure_total f)).\n    + exact (semprops_inject (lift_nil_int_pure_total f)).\n  Qed.\n\nEnd INSTANCES.\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/GenSem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604272, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2837317437382897}}
{"text": "(** STG in COQ by Maciej Piróg, University of Wrocław, 2010 *)\n\n(** This is an additional semantics, which was not described in the paper.\nIts sole puropse is to make some Coq proofs easier. *)\n\nRequire Export Sem03.\n\n(** * Explicit Environment Semantics Prime *)\n\nReserved Notation \"($ a $ b $ g $ e ↓↓↓↓ c $ d $ h $ f )\"\n  (at level 70, no associativity).\n\nInductive EES_Prime : heapB -> expr -> env -> vars -> heapB -> expr -> env ->\n  vars -> Prop :=\n\n| P_Con : forall Gamma C pi sigma,\n  ($ Gamma $ Constr C pi $ sigma $ nil ↓↓↓↓ Gamma $ Constr C pi $ sigma $ nil)\n\n| P_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| P_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| P_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| P_App4 : forall Gamma Delta sigma tau rho e p x C xs Theta w nu rs,\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  ($ setB Delta p (Lf_n 0 (Constr C xs), trim rho xs) $ Constr C xs $ rho $ nil ↓↓↓↓ Theta $ w $ nu $ rs) ->\n  ($ Gamma $ App x nil $ sigma $ nil ↓↓↓↓ Theta $ w $ nu $ rs)\n\n| P_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| P_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| P_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 )\" :=\n  (EES_Prime a b g e c d h f).\n\nHint Constructors EES_Prime.\n\n(** * Completeness and soundness *)\n\nProposition EES_Prime_complete :\nforall Gamma Delta e f theta rho ps qs,\n  ($ Gamma $ e $ theta $ ps ↓↓↓ Delta $ f $ rho $ qs) ->\n  ($ Gamma $ e $ theta $ ps ↓↓↓↓ Delta $ f $ rho $ qs).\nProof with eauto.\nintros...\ninduction H...\nQed.\n\nProposition EES_Prime_sound :\nforall Gamma Delta e f theta rho ps qs,\n  ($ Gamma $ e $ theta $ ps ↓↓↓↓ Delta $ f $ rho $ qs) ->\n  ($ Gamma $ e $ theta $ ps ↓↓↓ Delta $ f $ rho $ qs).\nProof with eauto.\nintros.\ninduction H...\ninversion H2; subst...\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/Sem04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.28373173620361464}}
{"text": "Require Import OptionSumbool.\nRequire Import AccessRights.\nRequire Import References.\nRequire Import Capabilities.\nRequire Import Indices.\nRequire Import Objects.\nRequire Import ObjectLabels.\nRequire Import SystemState.\nRequire Import SemanticsDefinitions.\nRequire Import Semantics.\nRequire Import Semantics_Conv.\nRequire Import AccessRightSets.\nRequire Import Execution.\nRequire Import RefSets.\nRequire Import Iff_Equiv.\nRequire Import AccessGraphs.\nRequire Import AccessEdge.\nRequire Import SequentialAccess.\nRequire Import Mutability.\nRequire Import Mutation.\nRequire Import AccessExecutionImpl.\nRequire Import Morphisms.\nRequire Import Basics.\nRequire Import Sumbool_dec.\nRequire Import MutableSubsetImpl.\nRequire Import CapSets.\nRequire Import Subsystem.\nRequire Import Decidable.\nRequire Import Irrelevance.\n\n\n(* type_remove *)\n Require Import Confinement.\n\nModule MakeConfinement (Ref:ReferenceType) (RefS: RefSetType Ref) (Edges: AccessEdgeType Ref) (AccessGraph:AccessGraphType Ref Edges) (Seq:SeqAccType Ref RefS Edges AccessGraph) (Cap:CapabilityType Ref) (CapS: CapSetType Ref Cap) (Ind:IndexType) (Obj:ObjectType Ref Cap Ind) (Sys:SystemStateType Ref Cap Ind Obj) (SemDefns: SemanticsDefinitionsType Ref Cap Ind Obj Sys) (Sem: SemanticsType Ref RefS Cap Ind Obj Sys SemDefns) (Exe: ExecutionType Ref RefS Cap Ind Obj Sys SemDefns Sem) (Mut: MutationType Ref RefS Cap Ind Obj Sys SemDefns Sem Exe) (Sub: SubsystemType Ref RefS Edges AccessGraph Seq Cap CapS Ind Obj Sys SemDefns Sem Exe) : ConfinementType Ref RefS Edges AccessGraph Seq Cap CapS Ind Obj Sys SemDefns Sem Exe Mut Sub.\n\nModule MSub := MakeMutableSubset Ref RefS Edges AccessGraph Seq Cap Ind Obj Sys SemDefns Sem Exe Mut.\n\nImport MSub.\nImport Mut.\nImport AE.\nImport RefS.\nImport Mutable.\n\n\n\n\n    Theorem dirAcc_rmCap_monotonic : forall S D, dirAcc_spec S D ->\n      forall i o S',  Sys.eq (SC.rmCap i o S) S' ->\n        forall D', dirAcc_spec S' D' ->\n          AG.Subset D' D.\n    Proof.\n      intros S D Hda i o S' Hs D' Hda'.\n      unfold SC.rmCap in *.\n      unfold OC.rmCap in *.\n      unfold SC.getObj in *.\n      unfold SC.updateObj in *.      \n      case (option_sumbool (SC.getObjTuple o S)); intros Hopt';\n        [|destruct Hopt' as [[[[Eobj Elbl] Etyp] Esch] Hopt']]; rewrite Hopt' in *; simpl in *;\n          (* solve None case *)\n          [ solve [eapply AGProps.subset_equal; eapply AG.eq_sym ; eapply dirAcc_spec_eq; eauto]|].\n      unfold SC.addObjTuple in *.\n\n      generalize Hs; intros Hda'2; apply Sys.eq_sym in Hda'2.\n      eapply dirAcc_spec_if in Hda'2; [| apply AG.eq_refl\n        | apply Hda'\n          ].\n\n      intros edge Hin.\n      eapply Hda' in Hin.\n\n      (* I would think the cases of this are to instantiate all lookups required by dirAcc_spec S D\n         and eliminate contradicitons.  Then case on (source edge) [=|<>] o .\n         Then case on (target edge) [=|<>] (target (find i Eobj)), though this might want to be a \n         separate theorem. *)\n\n      destruct_dirAcc Hin s1' HeqS src_ref1 src1 lbl1 type1 sched1 HmapS src1' \n      lbl1' type1' sched1' HeqP HaliveL ind1 cap1 Hmap0 cap_obj cap_lbl cap_type cap_sched HmapScap\n      cap_obj' cap_lbl' cap_type' cap_sched' HeqPcap HaliveCap rgt1 HinR HeqEdge.    \n\n    (* This code is largely hauled in from DirAccessSemanticsImpl.v and should probably be generalized.\n       If this works, go back and generalize theorems which rely on SC.rmCap to reuse this general theorem\n       The right starting point is below*)\n\n    (* we should now know enough to apply H. *)\n    (* the case analysis is as follows *)\n    (* when (target cap) [<>] src_refl1, we can determine (MapsTo src_ref1 (src1, lbl1, type1, sched1) s),\n       since do_revoke did not modify src1 under src_refl1, and use H to show (In x ag) *)\n    (* when (target cap) [=] src_refl1 /\\  c [<>] ind1,  we can determine \n       (MapsTo ind1 cap1 src1'), and use H to show (In x ag) *)\n    (* when (target cap) [=] src_refl1 /\\ c [=] ind1, there is one remaining case:\n       Either there is some other cap that could contribute edge from s, for which we use it; \n       or this is not, and we have a contradiction with H *)\n    destruct_tuple HeqP HeqSrc HeqLbl HeqSch HeqTyp; simpl in *.\n    destruct_tuple HeqPcap HeqCapSrc1 HeqCapLbl1 HeqCapType1 HeqCapSched1; simpl in *.\n\n    generalize Hs; intros Hs'; eapply Sys.eq_sym in Hs'. \n    eapply Sys.eq_trans in Hs'; [apply Sys.eq_sym in Hs' | apply Sys.eq_sym; apply HeqS].\n\n\n    case (Ref.eq_dec o src_ref1); intros HeqA.\n\n    (* case where o [=] src_ref1 *)\n    (* find src_ref1 in S *)\n    generalize Hopt'; intros Hopt1'.\n    unfold SC.getObjTuple in Hopt1';\n      apply Sys.MapS.find_2 in Hopt1';\n        apply Sys.MapS.MapsTo_1 with (y:=src_ref1) in Hopt1'; auto.\n\n    (* at this point, we should know that Elbl [=] lbl1, by Hs*)   \n\n    generalize (Sys_MapEquiv.mapsTo_eq _ _ _ _ _ _  HeqA Hs' (Sys.MapS.add_1 _ _ (eq_refl _)) HmapS);\n      intros [[[EobjEq ElblEq] EtypEq] EschEq]; simpl in *.\n\n    (* no case analysis needed, we infer that i [<>] ind1 from remove_mapsoto_iff and Hmap0 *)\n\n    generalize Hmap0; intros Hmap0'.\n    eapply Obj_MapEquiv.exists_mapsTo_eq in Hmap0'; [ |\n      eapply Obj.eq_trans; [apply Obj.eq_sym; apply HeqSrc | apply Obj.eq_sym; apply EobjEq] |\n        eapply Ind.eq_refl].\n    destruct Hmap0' as [cap1' [HeqCap1' Hmap0']].\n    eapply Obj_Facts.remove_mapsto_iff in Hmap0'; destruct Hmap0' as [Hneq' Hmap0'].\n\n    (* show Elbl = alive *)\n    rewrite HeqLbl in ElblEq; rewrite <- HaliveL in ElblEq.\n    rewrite <- HaliveCap in HeqCapLbl1.\n\n    (* at this point, the cases are either (target cap1) [=|<>] o *)\n    case (Ref.eq_dec o (Cap.target cap1)); intros HtargetEq.\n\n    (* case where o = target cap1 *)\n    (* apply dirAcc and instantiate *)\n    apply Hda;\n      apply_ex_intro_dirAcc S S src_ref1 Eobj Elbl Etyp Esch Eobj Elbl Etyp Esch ind1 cap1' \n      Eobj Elbl Etyp Esch Eobj Elbl Etyp Esch rgt1;\n      try apply Sys.eq_refl; try apply Sys.P.eq_refl;\n          try apply ObjectLabels.ObjectLabel.eq_sym; auto.\n\n    apply Sys.MapS.MapsTo_1 with src_ref1; auto.\n    rewrite <- HeqA; rewrite HtargetEq; apply Cap.target_eq; apply HeqCap1'.\n\n    eapply Cap.rights_eq;\n      [apply Cap.eq_sym; apply HeqCap1'| auto].\n\n    eapply Edge.eq_trans; try apply HeqEdge;\n      eapply Edges.edge_equal; try apply Cap.target_eq; try apply AccessRight.eq_refl; try apply Ref.eq_refl; auto.\n\n    (* case where o <> target cap1 *)\n    (* find target cap in S *)\n    generalize HmapScap; intros Hadd.\n    eapply Sys_MapEquiv.exists_mapsTo_eq in Hadd;\n    [destruct Hadd as [[[[cap_obj2 cap_lbl2] cap_typ2] cap_sch2] [[[[HcapObjeq HcapLblEq] HcapTypEq] HcapSchEq] Hadd]]; simpl in *\n      | apply Sys.eq_sym; apply Hs'\n        | apply Ref.eq_refl].\n    eapply Sys.MapS.add_3 in Hadd; [| apply HtargetEq].\n\n    (* apply dirAcc and instantiate *)\n    apply Hda;\n      apply_ex_intro_dirAcc S S src_ref1 Eobj Elbl Etyp Esch Eobj Elbl Etyp Esch ind1 cap1' \n      cap_obj2 cap_lbl2 cap_type2 cap_sched2 cap_obj cap_lbl cap_type cap_sched rgt1;\n      try apply Sys.eq_refl; try apply Sys.P.eq_refl;\n          try apply ObjectLabels.ObjectLabel.eq_sym; auto.\n\n    rewrite HcapTypEq; rewrite HcapSchEq; auto.\n    eapply Sys.MapS.MapsTo_1;\n      [apply Cap.target_eq; apply HeqCap1'\n        | auto].\n\n    rewrite HcapTypEq; rewrite HcapSchEq; rewrite HcapLblEq; auto.\n    do 3 (split; simpl; auto); apply Obj.eq_sym; auto.\n    \n    eapply Cap.rights_eq;\n      [apply Cap.eq_sym; apply HeqCap1'| auto].\n\n    eapply Edge.eq_trans; try apply HeqEdge;\n      eapply Edges.edge_equal; try apply Cap.target_eq; try apply AccessRight.eq_refl; try apply Ref.eq_refl; auto.\n\n    (* case where o [<>] src_ref1 *)\n    \n    (* find src_ref1 in S *)\n    generalize HmapS; intros HmapS'.\n    eapply Sys_MapEquiv.exists_mapsTo_eq in HmapS';\n      [ destruct HmapS' as [[[[src2 lbl2] type2] sched2] [[[[HObjEq HLblEq] HTypEq] HSchEq] HmapS']]; simpl in *\n        | apply Sys.eq_sym; apply Hs'\n        | apply Ref.eq_refl].\n    apply Sys.MapS.add_3 in HmapS'; [| auto].\n\n    (* find target cap in (add o  ... S) *)\n    generalize HmapScap; intros Hadd.\n    eapply Sys_MapEquiv.exists_mapsTo_eq in Hadd;\n    [destruct Hadd as [[[[cap_obj2 cap_lbl2] cap_typ2] cap_sch2] [[[[HcapObjeq HcapLblEq] HcapTypEq] HcapSchEq] Hadd]]; simpl in *\n      | apply Sys.eq_sym; apply Hs'\n        | apply Ref.eq_refl].\n\n\n    (* demonstrate lbl2 is alive *)\n    rewrite <- HeqLbl in HaliveL;\n    rewrite HLblEq in HaliveL;\n    eapply ObjectLabel.eq_sym in HaliveL.\n\n    (* find cap1 in src2 *)\n    eapply Obj_MapEquiv.exists_mapsTo_eq in Hmap0;\n      [destruct Hmap0 as [cap1' [HcapEq' Hmap0]]\n        |  eapply Obj.eq_trans;\n          [apply Obj.eq_sym; apply HeqSrc \n            | apply HObjEq]\n        | apply Ind.eq_refl ].\n\n   (* at this point, the cases are either (target cap1) [=|<>] o *)\n    eapply Sys_Facts.add_mapsto_iff in Hadd.\n    destruct Hadd as [[HeqO Htuple]| [HneqO HmapStarget]].\n\n    (* case where o = target cap1 *)\n\n    inversion Htuple as [[HtargetObj  HtargetLbl HtargetType HtargetSched]]; clear Htuple.\n    unfold SC.getObjTuple in Hopt'; eapply Sys_Facts.find_mapsto_iff in Hopt'.\n\n    (* show Elbl = alive *)\n    rewrite <- HcapLblEq in HtargetLbl;\n    rewrite HeqCapLbl1 in HtargetLbl;\n    rewrite <- HaliveCap in HtargetLbl.\n\n    (* apply dirAcc and instantiate *)\n    apply Hda;\n      apply_ex_intro_dirAcc S S src_ref1 src2 lbl2 type2 sched2 src2 lbl2 type2 sched2 ind1 cap1'\n      Eobj Elbl Etyp Esch Eobj Elbl Etyp Esch rgt1;\n      try apply Sys.eq_refl; try apply Sys.P.eq_refl;\n          try apply ObjectLabels.ObjectLabel.eq_sym; auto.\n\n    rewrite Cap.target_eq; [| apply Cap.eq_sym; apply HcapEq'].\n    rewrite <- HeqO; auto.\n\n    eapply Cap.rights_eq;\n      [apply Cap.eq_sym; apply HcapEq'| auto].\n\n    eapply Edge.eq_trans; try apply HeqEdge;\n      eapply Edges.edge_equal; try apply Cap.target_eq; try apply AccessRight.eq_refl; try apply Ref.eq_refl; auto.\n\n    (* case where o <> target cap1 *)\n    (* show cap_lbl2 = alive *)\n    rewrite HeqCapLbl1 in HcapLblEq.\n    rewrite <- HaliveCap in HcapLblEq.\n    apply eq_sym in HcapLblEq.\n    \n\n    (* apply dirAcc and instantiate *)\n    apply Hda;\n      apply_ex_intro_dirAcc S S src_ref1 src2 lbl2 type2 sched2 src2 lbl2 type2 sched2 ind1 cap1'\n      cap_obj2 cap_lbl2 cap_typ2 cap_sch2 cap_obj2 cap_lbl2 cap_typ2 cap_sch2 rgt1;\n      try apply Sys.eq_refl; try apply Sys.P.eq_refl;\n          try apply ObjectLabels.ObjectLabel.eq_sym; auto.\n\n    rewrite Cap.target_eq; [| apply Cap.eq_sym; apply HcapEq']; auto.\n\n    eapply Cap.rights_eq;\n      [apply Cap.eq_sym; apply HcapEq'| auto].\n\n    eapply Edge.eq_trans; try apply HeqEdge;\n      eapply Edges.edge_equal; try apply Cap.target_eq; try apply AccessRight.eq_refl; try apply Ref.eq_refl; auto.\n\n\n  Qed.\n\n(* DirAcc is unchanged by removing an empty cap or invalid cap*)\n  Theorem void_dirAcc_unchanged: \n    forall S D, DA.dirAcc_spec S D ->\n    forall i e cap, SC.getCap i e S = Some cap ->\n      ARSet.Empty (Cap.rights cap) ->\n    forall S', Sys.eq (SC.rmCap i e S) S' ->\n    forall D', DA.dirAcc_spec S' D' ->\n    AG.Equal D D'.\n  Proof.\n    intros S D Hda i e cap Hcap Hrights S' HS' D' Hda'.\n    intros x; split; intros Hin.\n\n    eapply Hda in Hin.\n    destruct_dirAcc Hin s'' HeqS src_ref src lbl srcType srcSched HmapS \n    src' lbl' srcType' srcSched' HeqP Halive ind1 cap1 HmapSrc'\n    cap_obj cap_lbl cap_type cap_sched HmapScap cap_obj' cap_lbl' cap_type' cap_sched' \n    HeqPcap HaliveCap rgt HinR HeqEdge.\n\n    destruct_tuple HeqP HeqSrc HeqLbl HeqType HeqSched; simpl in *.\n\n    (* cases on e [=|<>] src_ref \n       e [=] src_ref => further cases.\n       e [<>] src_ref => all other mappings in S' are identical to S.*)\n\n    case (Ref.eq_dec e src_ref); intros Hcase1.\n\n    (* cases on i [=|<>] ind1.\n       i [=] ind1 => cap [=] cap1 => Empty (Cap.rights cap1) => contradiction\n       i [<>] ind1 => all other mappings in S' identical to S \n          Should have a theorem somewhere for this*)\n\n    case (Ind.eq_dec i ind1); intros Hcase2.\n\n    generalize( SC.getCap_eq  _ _ _ _ _ _ (Sys.eq_refl S) Hcase2 Hcase1); intros Heq.\n    rewrite Hcap in Heq.\n    unfold SC.getCap in Heq.\n    unfold OC.getCap in Heq.\n    unfold SC.getObj in Heq.\n    unfold SC.getObjTuple in Heq.\n    generalize (Sys_MapEquiv.exists_mapsTo_eq  _ _ (Sys.eq_sym HeqS) _ _ HmapS _ (Ref.eq_refl _));\n       intros [[[[obj2 lbl2] typ2] sched2] [[[[Hobj2 Hlbl2] Htyp2] Hsched2] Hmap2]]; simpl in *.\n    eapply Sys_Facts.find_mapsto_iff in Hmap2; rewrite Hmap2 in Heq; simpl in *.\n\n    rewrite Hobj2 in HeqSrc.\n    generalize (Obj_MapEquiv.exists_mapsTo_eq  _ _ (Obj.eq_sym HeqSrc) _ _ HmapSrc' _ (Ind.eq_refl _));\n      intros [cap2 [Hcap2eq Hcap2Map]]; simpl in *.\n    \n    eapply Obj_Facts.find_mapsto_iff in Hcap2Map; rewrite Hcap2Map in Heq; simpl in *.\n    rewrite <- Hcap2eq in Heq.\n\n    eapply Cap.rights_eq in Heq.\n    eapply Heq in HinR.\n    eapply Hrights in HinR. contradiction.\n\n    (* The next two cases should be nearly identical.\n       As the capability motivating the addition of an edge has not been removed,\n       the edge must still exist in the access graph *)\n\n    (* first demonstrate that there is a label to our cap target, regardless of the object *)\n    generalize (is_label_rmCap _ _ _ _ HS' (Cap.target cap1) cap_lbl); intros Hlabel.\n    unfold SC.is_label in Hlabel.\n    unfold SC.getLabel in Hlabel.\n    generalize (Sys_MapEquiv.exists_mapsTo_eq  _ _ (Sys.eq_sym HeqS) _ _ HmapScap _ (Ref.eq_refl _));\n      intros [[[[obj3 lbl3] typ3] sched3] [[[[Hobj3 Hlbl3] Htyp3] Hsched3] Hmap3]]; simpl in *.\n    eapply Sys_Facts.find_mapsto_iff in Hmap3; simpl in *.\n    unfold SC.getObjTuple in Hlabel.\n    rewrite Hmap3 in Hlabel; simpl in Hlabel.\n    eapply eq_sym in Hlbl3.\n    destruct Hlabel as [Hlabel' _].\n    generalize Hlbl3; intros Hlabel.\n    eapply Hlabel' in Hlabel.\n    clear Hlabel'.\n    case (option_sumbool (Sys.MapS.find (Cap.target cap1) S')); intros HtargetObj;\n      [|destruct HtargetObj as [[[[tobj tlbl] ttyp] tsched]  HtargetObj]]; rewrite HtargetObj in *; simpl in *; try contradiction.\n\n    (* use our knowledge of e maping to src ... in s'' to reduce HS' *)\n    unfold SC.rmCap in *.\n    unfold SC.updateObj in HS'.\n    unfold SC.addObjTuple in HS'.\n    unfold SC.getObj in HS'.\n    unfold SC.getObjTuple in HS'.\n    generalize (Sys_MapEquiv.exists_mapsTo_eq  _ _ (Sys.eq_sym HeqS) _ _ HmapS _ (Ref.eq_sym Hcase1));\n      intros [[[[obj2 lbl2] typ2] sched2] [[[[Hobj2 Hlbl2] Htyp2] Hsched2] Hmap2]]; simpl in *.\n    eapply Sys_Facts.find_mapsto_iff in Hmap2; simpl in *.\n    rewrite Hmap2 in HS'; simpl in HS'.\n\n    (* generate an equivalent OC.rmCap i obj2 for the value of e in S'.*)\n\n    generalize (Sys_MapEquiv.exists_mapsTo_eq _ _ HS'); intros HeqMap.\n    generalize Sys.MapS.add_1; intros Hadd.\n    eapply HeqMap in Hadd; try solve [apply eq_refl].\n    destruct Hadd as [[[[obj2' lbl2'] typ2'] sched2'] [[[[Hobj2' Hlbl2'] Htyp2'] Hsched2'] HmapS']]; simpl in *.\n    clear HeqMap.\n\n    (* generate an equivalent cap1 in src *)\n    edestruct (Obj_MapEquiv.exists_mapsTo_eq _ _ (Obj.eq_sym HeqSrc)) as [cap1' [HCapEq HmapSrc]];\n      [apply HmapSrc' |  apply Ind.eq_refl | ].\n\n\n    apply Hda'.\n    apply_ex_intro_dirAcc S' S' e obj2' lbl2' typ2' sched2'  (OC.rmCap i src) lbl2 typ2 sched2 \n    ind1 cap1' tobj tlbl ttyp tsched tobj tlbl ttyp tsched rgt;\n    try solve [apply Sys.eq_refl | apply Sys.P.eq_refl| auto].\n\n    do 3 (split; simpl; auto).\n    apply Obj.eq_sym. eapply Obj.eq_trans. 2: apply Hobj2'.\n\n    (* This has moved *)\n    apply OC.removeCap_eq; auto.\n\n\n    (* moving on to easy goals, top goal should go through by equivalence *)\n    (* 2: do 3 (split; simpl; auto). *)\n    (* 2: unfold OC.rmCap; *)\n    (*   eapply Obj_MapEquiv.remove_m;  *)\n    (*     solve [ eauto *)\n    (*       | apply Obj.eq_sym; auto *)\n    (*       | rewrite <- Hlbl2; rewrite HeqLbl; eauto]. *)\n\n    rewrite <- Hlbl2.\n    rewrite HeqLbl.\n    rewrite <- Halive.\n    eapply ObjectLabel.eq_refl.\n\n    unfold OC.rmCap.\n    eapply Obj_Facts.remove_neq_mapsto_iff; auto.\n\n\n    eapply Sys_Facts.find_mapsto_iff in HtargetObj.\n    eapply Sys_Facts.MapsTo_iff; [| apply HtargetObj].\n    eapply Cap.target_eq; auto.\n\n    rewrite Hlabel.\n    destruct HeqPcap as [[[_ HeqCapLbl] _] _]; simpl in HeqCapLbl.\n    rewrite HeqCapLbl.\n    rewrite HaliveCap.\n    apply ObjectLabel.eq_refl.\n\n    eapply ARSet.eq_trans;\n      [apply ARSet.eq_refl |\n        apply Cap.rights_eq; apply Cap.eq_sym; apply HCapEq|\n          auto].\n\n    rewrite <- HeqEdge.\n    eapply Edges.edge_equal; try solve[ apply Ref.eq_refl | apply AccessRight.eq_refl | apply Cap.target_eq; auto | auto] .\n\n    (* Second similar case, a few steps will be skipped. *)\n\n\n    (* first demonstrate that there is a label to our cap target, regardless of the object *)\n    generalize (is_label_rmCap _ _ _ _ HS' (Cap.target cap1) cap_lbl); intros Hlabel.\n    unfold SC.is_label in Hlabel.\n    unfold SC.getLabel in Hlabel.\n    generalize (Sys_MapEquiv.exists_mapsTo_eq  _ _ (Sys.eq_sym HeqS) _ _ HmapScap _ (Ref.eq_refl _));\n      intros [[[[obj3 lbl3] typ3] sched3] [[[[Hobj3 Hlbl3] Htyp3] Hsched3] Hmap3]]; simpl in *.\n    eapply Sys_Facts.find_mapsto_iff in Hmap3; simpl in *.\n    unfold SC.getObjTuple in Hlabel.\n    rewrite Hmap3 in Hlabel; simpl in Hlabel.\n    eapply eq_sym in Hlbl3.\n    destruct Hlabel as [Hlabel' _].\n    generalize Hlbl3; intros Hlabel.\n    eapply Hlabel' in Hlabel.\n    clear Hlabel'.\n    case (option_sumbool (Sys.MapS.find (Cap.target cap1) S')); intros HtargetObj;\n      [|destruct HtargetObj as [[[[tobj tlbl] ttyp] tsched]  HtargetObj]]; rewrite HtargetObj in *; simpl in *; try contradiction.\n\n\n\n    (* find the object i e in S *)\n    case (option_sumbool (SC.getObjTuple e S)); intros HcaseT;\n      [|destruct HcaseT as [[[[obj2 lbl2] typ2] sched2] HcaseT]];\n        try solve [unfold SC.getCap in Hcap; unfold SC.getObj in Hcap; \n          rewrite HcaseT in Hcap; simpl in *; discriminate Hcap].\n    \n    (* reduce HS' *)\n    unfold SC.rmCap in *.\n    unfold SC.updateObj in HS'.\n    unfold SC.addObjTuple in HS'.\n    unfold SC.getObj in HS'.\n    rewrite HcaseT in HS'; simpl in *.\n    \n    (* generate an equivalent obj2 for the value of src_ref in S'.*)\n\n    generalize (Sys_MapEquiv.exists_mapsTo_eq _ _ (Sys.eq_sym HeqS) _ _ HmapS _ (eq_refl _)); \n      intros [[[[obj2'' lbl2''] typ2''] sched2''] [[[[Hobj2'' Hlbl2''] Htyp2''] Hsched2''] HeqSMap]]; simpl in *.\n    generalize (Sys_MapEquiv.exists_mapsTo_eq _ _ HS'); intros HeqMap.\n    generalize Sys.MapS.add_2; intros Hadd.\n    eapply HeqMap in Hadd; [ clear HeqMap HeqSMap | eapply Hcase1 | apply HeqSMap| apply eq_refl].\n    destruct Hadd as [[[[obj2' lbl2'] typ2'] sched2'] [[[[Hobj2' Hlbl2'] Htyp2'] Hsched2'] HmapS']]; simpl in *.\n    \n\n    (* generate an equivalent cap1 in src *)\n    edestruct (Obj_MapEquiv.exists_mapsTo_eq _ _ (Obj.eq_sym HeqSrc)) as [cap1' [HCapEq HmapSrc]];\n      [apply HmapSrc' |  apply Ind.eq_refl | ].\n\n    apply Hda'.\n    apply_ex_intro_dirAcc S' S' src_ref obj2' lbl2' typ2' sched2' src lbl srcType srcSched\n    ind1 cap1' tobj tlbl ttyp tsched tobj tlbl ttyp tsched rgt;\n    try solve [apply Sys.eq_refl | apply Sys.P.eq_refl| auto].\n\n    do 3 (split; simpl; eauto).\n    apply Obj.eq_sym. eapply Obj.eq_trans; [eauto | apply Hobj2'].\n    \n\n\n\n    \n    rewrite HeqLbl.\n    rewrite <- Halive.\n    eapply ObjectLabel.eq_refl.\n\n    eapply Sys_Facts.find_mapsto_iff in HtargetObj.\n    eapply Sys_Facts.MapsTo_iff; [| apply HtargetObj].\n    eapply Cap.target_eq; auto.\n\n    rewrite Hlabel.\n    destruct HeqPcap as [[[_ HeqCapLbl] _] _]; simpl in HeqCapLbl.\n    rewrite HeqCapLbl.\n    rewrite HaliveCap.\n    apply ObjectLabel.eq_refl.\n\n    eapply ARSet.eq_trans;\n      [apply ARSet.eq_refl |\n        apply Cap.rights_eq; apply Cap.eq_sym; apply HCapEq|\n          auto].\n\n    rewrite <- HeqEdge.\n    eapply Edges.edge_equal; try solve[ apply Ref.eq_refl | apply AccessRight.eq_refl | apply Cap.target_eq; auto | auto] .\n\n    (* I think the second half of this should be proved from rmCap is monotonic and dirAcc is monotonic.  \n       This should exist in some form somewhere *)\n\n  eapply dirAcc_rmCap_monotonic; eauto.\n\n  Qed.\n\n  Hint Resolve void_dirAcc_unchanged.\n\n\n(* removing a void capability to any object does not alter any mutation *)\n  Theorem void_irrelevant: \n    forall S D, DA.dirAcc_spec S D ->\n    forall P, Seq.potAcc D P ->\n    forall E M, mutable_spec P E M ->\n    forall i o cap, SC.getCap i o S = Some cap ->\n      ARSet.Empty (Cap.rights cap) ->\n    forall S', Sys.eq (SC.rmCap i o S) S' ->\n    forall D', DA.dirAcc_spec S' D' ->\n    forall P', Seq.potAcc D' P' ->\n    forall M', mutable_spec P' E M' ->\n    RefSet.Equal M' M.\n  Proof.\n    intros S D Hda P Hpa E M Hm i o cap Hcap Hempty S' Hs' D' Hda' P' Hpa' M' Hm'.\n    eapply mutable_spec_eq_iff; eauto; try apply RefSet.eq_refl.\n    eapply potAcc_eq_iff; eauto; try apply AG.eq_refl.\n  Qed.\n\n\n\n\n\n\n\n\n\n\n\n\n  (* At this point, we focus on the notions of simply confined access grapns *)\n\n  Definition subset_pred P A B := forall x, P A B x -> AG.In x A -> AG.In x B.\n\n  Theorem subset_pred_subset :\n    Proper ( (AG.Subset ==> AG.Subset --> Edge.eq ==> impl) --> AG.Subset --> AG.Subset ==> impl) subset_pred.\n  Proof.\n    unfold Proper; unfold respectful; unfold flip; unfold impl; unfold subset_pred.\n    intros P P' Pimpl x0 y0 Hsub0 x1 y1 Hsub1 Hpred x2 P2' Hin.\n    eapply Hsub1.\n    eapply Hpred; [|apply Hsub0; auto].\n    eapply Pimpl; eauto.\n  Qed.\n\n  Theorem Proper_subset_pred_P : forall f, Proper (AG.Subset ==> AG.Subset --> Edge.eq ==> impl) f -> \n    Proper (AG.eq ==> AG.eq ==> Edge.eq ==> iff) f.\n  Proof.\n    unfold Proper; unfold respectful; unfold impl.\n    intros f P x y Heq x0 y0 Heq0 x1 y1 Heq1.\n    split; intros Hf; eapply P; unfold flip.\n    apply AGProps.subset_equal; eauto.\n    apply AGProps.subset_equal; apply AG.eq_sym; eauto.\n    eauto.\n    apply Hf.\n    apply AGProps.subset_equal; apply AG.eq_sym; eauto.\n    apply AGProps.subset_equal; eauto.\n    apply Edge.eq_sym; eauto.\n    apply Hf.\n  Qed.\n  Hint Resolve Proper_subset_pred_P.\n\n  Theorem subset_pred_eq : Proper ( (AG.eq ==> AG.eq ==> Edge.eq ==> iff) ==> AG.eq ==> AG.eq ==> iff) subset_pred.\n  Proof.\n    unfold Proper; unfold respectful; unfold subset_pred.\n    intros P P' Peq x0 y0 Heq0 x1 y1 Heq1; split; \n      (intros Hsub x2 Hpred Hin;\n        eapply Heq1; eapply Hsub; [eapply Peq; eauto| apply Heq0; auto]).\n  Qed.\n  Hint Resolve subset_pred_eq.\n\n  Definition subset_eq_pred P A B := AG.Subset A B /\\ subset_pred (fun B A => P A B) B A.\n\n  Theorem subset_eq_pred_eq : \n    Proper ( (AG.eq ==> AG.eq ==> Edge.eq ==> iff ) ==> AG.eq ==> AG.eq ==> iff) subset_eq_pred.\n  Proof.\n    unfold Proper; unfold respectful.\n    intros P P' Peq x0 y0 Heq0 x1 y1 Heq1.\n\n\n    Ltac solve_tac Heq Heq' Heq2 :=  \n      solve [apply Heq | apply AG.eq_sym; apply Heq \n        | apply Heq' | apply AG.eq_sym; apply Heq' \n        | apply Heq2 | apply Edge.eq_sym; apply Heq2].\n\n    split; (intros [Hsub HP]; split;\n      [rewrite Heq0 in *; rewrite Heq1 in *; auto\n        | eapply subset_pred_eq;\n          [ unfold respectful; intros x y Heq x' y' Heq' x2 y2 Heq2;\n            solve [apply iff_sym; eapply Peq; solve_tac Heq Heq' Heq2 | eapply Peq; solve_tac Heq Heq' Heq2]\n            | solve [apply AG.eq_sym ; eauto | eauto]\n            | solve [apply AG.eq_sym ; eauto | eauto]\n            | eauto ]]).\n  Qed.\n\n\n(* I find that we are trying to reason about mutability pointwise when describing Confinement. \n   TODO: consider going back to mutable and adding pointwise support *)\n\n  Definition ag_ex_flow' A E o := RefSet.In o (mutable A E).\n\n  Definition ag_flow' A e o :=\n    Ref.eq e o \\/\n    AG.In (Edges.mkEdge e o tx) A \\/\n    AG.In (Edges.mkEdge e o wr) A \\/\n    AG.In (Edges.mkEdge o e wk) A \\/\n    AG.In (Edges.mkEdge o e rd) A.\n   \n\n Theorem Proper_ag_flow'_eq :\n    Proper (AG.eq ==> Ref.eq ==> Ref.eq ==> iff) ag_flow'.\n  Proof.\n    unfold Proper; unfold respectful; unfold ag_flow'.\n    intros A A' HeqE e1 e1' Heq1 e2 e2' Heq2.\n    try rewrite (Edges.eq_source _ _ Heq2); \n    try rewrite (Edges.eq_target _ _ Heq2);\n    try rewrite (Edges.eq_right _ _ Heq2).\n    try rewrite HeqE;\n      try rewrite Heq1;\n        try rewrite Heq2.\n    intuition auto.\n  Qed.\n\n  Hint Resolve Proper_ag_flow'_eq.\n\n  Theorem ag_flow'_dec : forall E x x',\n    {ag_flow' E x x'} + {~ ag_flow' E x x'}.\n  Proof.\n    unfold ag_flow'.\n    intros E x x'.\n    Sumbool_decide; solve [eapply Ref.eq_dec | eapply AGProps.In_dec].\n  Qed.\n\n  Hint Resolve ag_flow'_dec.\n\n  Theorem compat_P_ag_flow' : forall A x, SetoidList.compat_P Ref.eq ((fun e => ag_flow' A e x)).\n  Proof.\n    unfold SetoidList.compat_P.\n    unfold Proper; unfold respectful; unfold impl. intros.\n    eapply Proper_ag_flow'_eq;\n      [eapply AG.eq_refl\n        |eapply Ref.eq_sym; eauto\n        |eapply Ref.eq_refl\n        |eauto].\n  Qed.\n\n   Inductive ag_flow P a b : Prop := \n     | ag_flow_refl : Ref.eq a b -> ag_flow P a b\n     | ag_flow_tx : AG.In (Edges.mkEdge a b tx) P -> ag_flow P a b\n     | ag_flow_wr : AG.In (Edges.mkEdge a b wr) P -> ag_flow P a b\n     | ag_flow_wk : AG.In (Edges.mkEdge b a wk) P -> ag_flow P a b\n     | ag_flow_rd : AG.In (Edges.mkEdge b a rd) P -> ag_flow P a b.\n\n   Hint Constructors ag_flow.\n\n   Theorem ag_flow_iff_ag_flow' : forall P a b ,\n     ag_flow' P a b <-> ag_flow P a b.\n   Proof.\n     unfold ag_flow'.\n     split; [intuition auto| intro H; destruct H; intuition].\n   Qed.\n\n   Hint Immediate ag_flow_iff_ag_flow'.\n\n   Theorem ag_flow_dec : forall P a b ,\n     {ag_flow P a b} + {~ ag_flow P a b}.\n   Proof.\n     intros; eapply Sumbool_dec_iff_imp; eauto.\n   Qed.\n\n   Hint Resolve ag_flow_dec.\n\n   (* This is basically mutable_maximal, phrased pointwise. *)\n   Theorem maxTransfer_ag_flow_trans : forall P a b c ,\n     Seq.maxTransfer P -> ag_flow P a b -> ag_flow P b c -> ag_flow P a c.\n   Proof.\n     intros P a b c Hmax Hab Hbc.\n     destruct Hab as [Hab | Hab | Hab | Hab | Hab];\n       destruct Hbc as [Hbc | Hbc | Hbc | Hbc | Hbc];\n     eapply ag_flow_iff_ag_flow';\n       try solve [try rewrite Hab in *; try rewrite Hbc in *; unfold ag_flow'; intuition].\n\n\n     Ltac reduce_maxTrans Hmax trans_op :=\n       eapply Hmax; [|eapply AGProps.Add_add; left; apply Edge.eq_refl];\n         eapply trans_op; auto.\n     \n     (* send *)\n     right; left.\n     reduce_maxTrans Hmax Seq.transfer_send; [| apply Hbc].\n     reduce_maxTrans Hmax Seq.transfer_send_reply; apply Hab.\n     do 2 right; left.\n     reduce_maxTrans Hmax Seq.transfer_send; [| apply Hbc].\n     reduce_maxTrans Hmax Seq.transfer_send_reply; apply Hab.\n     do 3 right; left.\n     reduce_maxTrans Hmax Seq.transfer_weak; [ apply Hbc|].\n     reduce_maxTrans Hmax Seq.transfer_send; [apply Hab |].\n     reduce_maxTrans Hmax Seq.transfer_self_src; apply Hab.\n     do 4 right.\n     reduce_maxTrans Hmax Seq.transfer_read; [ apply Hbc|].\n     reduce_maxTrans Hmax Seq.transfer_send; [apply Hab |].\n     reduce_maxTrans Hmax Seq.transfer_self_src; apply Hab.\n     \n     (* write *)\n     do 1 right; left.\n     reduce_maxTrans Hmax Seq.transfer_write; [ | apply Hbc].\n     reduce_maxTrans Hmax Seq.transfer_write; [ apply Hab| ].\n     reduce_maxTrans Hmax Seq.transfer_self_src; apply Hab.\n     do 2 right; left.\n     reduce_maxTrans Hmax Seq.transfer_write; [ | apply Hbc].\n     reduce_maxTrans Hmax Seq.transfer_write; [ apply Hab| ].\n     reduce_maxTrans Hmax Seq.transfer_self_src; apply Hab.\n     do 3 right; left.\n     reduce_maxTrans Hmax Seq.transfer_weak; [ apply Hbc|].\n     reduce_maxTrans Hmax Seq.transfer_write; [apply Hab |].\n     reduce_maxTrans Hmax Seq.transfer_self_src; apply Hab.\n     do 4 right.\n     reduce_maxTrans Hmax Seq.transfer_read; [ apply Hbc|].\n     reduce_maxTrans Hmax Seq.transfer_write; [apply Hab |].\n     reduce_maxTrans Hmax Seq.transfer_self_src; apply Hab.\n\n     (* weak *)\n     do 3 right; left.\n     reduce_maxTrans Hmax Seq.transfer_weak; [|apply Hab].\n     reduce_maxTrans Hmax Seq.transfer_send; [apply Hbc|].\n     reduce_maxTrans Hmax Seq.transfer_self_src; apply Hbc.\n     do 3 right; left.\n     reduce_maxTrans Hmax Seq.transfer_weak; [|apply Hab].\n     reduce_maxTrans Hmax Seq.transfer_write; [apply Hbc|].\n     reduce_maxTrans Hmax Seq.transfer_self_src; apply Hbc.\n     do 3 right; left.\n     reduce_maxTrans Hmax Seq.transfer_weak; [apply Hbc|apply Hab].\n     do 3 right; left.\n     reduce_maxTrans Hmax Seq.transfer_read; [apply Hbc|apply Hab].\n\n     (* read *)\n     do 4 right.\n     reduce_maxTrans Hmax Seq.transfer_send; [apply Hbc|apply Hab].\n     do 4 right.\n     reduce_maxTrans Hmax Seq.transfer_write; [apply Hbc|apply Hab].\n     do 3 right; left.\n     eapply Hmax; [|eapply AGProps.Add_add; left; apply Edge.eq_refl];\n         eapply Seq.transfer_weak;\n           [apply Hbc\n             |apply Hab\n             |intuition\n             |auto].\n     do 4 right.\n     reduce_maxTrans Hmax Seq.transfer_read; [apply Hbc|apply Hab].\n\n   Qed.\n\n   Hint Resolve maxTransfer_ag_flow_trans.\n\n Theorem Proper_ag_flow_eq :\n    Proper (AG.eq ==> Ref.eq ==> Ref.eq ==> iff) ag_flow.\n  Proof.\n    unfold Proper; unfold respectful; intros.\n    repeat progress rewrite <- ag_flow_iff_ag_flow'.\n    eapply Proper_ag_flow'_eq; eauto; try apply Ref.eq_refl.\n  Qed.\n\n  Hint Resolve Proper_ag_flow_eq.\n\n  (* Note, we can't use this form with generated code *)\n\n  Theorem compat_P_ag_flow : forall A x, SetoidList.compat_P Ref.eq ((fun e => ag_flow A e x)).\n  Proof.\n    unfold SetoidList.compat_P.\n    unfold Proper; unfold respectful; unfold impl; intros.\n    rewrite <-  ag_flow_iff_ag_flow' in *.\n    eapply compat_P_ag_flow'; eauto.\n  Qed.\n\n  Implicit Arguments compat_P_ag_flow [A x].\n\n  Definition ag_ex_flow E A o := RefSet.Exists ((fun e => ag_flow A e o)) E.\n\n  Theorem Proper_ag_ex_flow_eq : Proper (RefSet.eq ==> AG.eq ==> Ref.eq ==> iff) ag_ex_flow.\n  Proof.\n    unfold Proper; unfold respectful; unfold ag_ex_flow; unfold AG.Exists.\n    intros x y H x0 y0 H0 x1 y1 H1.\n    split;\n    (intros [x2 [Hin Hconf]]; eapply ex_intro with x2; split; \n      [ rewrite H in *; eauto\n        | generalize (AG.eq_sym H0) (Ref.eq_sym H1) (RefSet.eq_sym H); intros;\n          eapply Proper_ag_flow_eq; eauto; try apply Ref.eq_refl]).\n  Qed.\n  Hint Resolve Proper_ag_ex_flow_eq.\n\n  Theorem ag_ex_flow_dec : forall E A x, {ag_ex_flow E A x} + {~ ag_ex_flow E A x}.\n  Proof.\n    intros E A x. unfold ag_ex_flow.\n    apply RefSetExists.exists_'; [intros x'; eapply ag_flow_dec|apply compat_P_ag_flow].\n  Qed.\n  Hint Resolve ag_ex_flow_dec.\n\n  Definition ag_simply_confined E x :=\n    ~ (Ref.eq (Edges.source x) (Edges.target x)) /\\\n    \n    ~(RefSet.In (Edges.source x) E /\\\n      ~ RefSet.In (Edges.target x) E /\\\n      AccessRight.eq (Edges.right x) wk).\n\n  Theorem Proper_ag_simply_confined_eq : Proper (RefSet.eq ==> Edge.eq ==> iff) ag_simply_confined.\n  Proof.\n    unfold Proper; unfold respectful; unfold flip; unfold impl;\n      unfold ag_simply_confined.\n    intros E E' HeqE edge edge' Heqe;\n    rewrite (Edges.eq_source _ _ Heqe);\n    rewrite (Edges.eq_target _ _ Heqe);\n    rewrite (Edges.eq_right _ _ Heqe).\n\n    generalize (RefSet.eq_sym HeqE) (Edge.eq_sym Heqe); intros HeqE' Heqe'.\n    \n    (* TODO: LTAC this *)\n\n    split; intros [H1 H2].\n    \n    split; [try rewrite <- HeqE; eauto|].\n    intros [Hnot1 Hnot2];\n    apply H2; clear H2.\n    rewrite HeqE; auto.\n\n    split; [try rewrite <- HeqE; eauto|].\n    intros [Hnot1 Hnot2];\n    apply H2; clear H2.\n    rewrite HeqE in *; auto.\n  Qed.\n  Hint Resolve Proper_ag_simply_confined_eq.\n\n\n  Theorem ag_simply_confined_dec : forall E x, {ag_simply_confined E x} + {~ ag_simply_confined E x}.\n  Proof.\n    intros E x; unfold ag_simply_confined; Sumbool_decide; \n      try apply RefSetProps.In_dec; try apply Ref.eq_dec; try apply AccessRight.eq_dec; eauto.\n  Qed.\n  Hint Resolve ag_simply_confined_dec.\n\n  Definition ag_confined E P x := \n    ~ (Ref.eq (Edges.source x) (Edges.target x)) /\\\n\n    ~(AccessRight.eq (Edges.right x) wk /\\\n      ( ag_ex_flow E P (Edges.source x) \\/ ~ ag_ex_flow E P (Edges.target x))).\n\n\n  Theorem Proper_ag_confined_eq : Proper (RefSet.eq ==> AG.eq ==> Edge.eq ==> iff) ag_confined.\n  Proof.\n    unfold Proper; unfold respectful; unfold flip; unfold impl;\n      unfold ag_confined; unfold ag_simply_confined.\n    intros E E' HeqE P P' HeqP edge edge' Heqe;\n    rewrite (Edges.eq_source _ _ Heqe);\n    rewrite (Edges.eq_target _ _ Heqe);\n    rewrite (Edges.eq_right _ _ Heqe).\n\n    generalize (RefSet.eq_sym HeqE) (AG.eq_sym HeqP) (Edge.eq_sym Heqe); intros HeqE' HeqP' Heqe'.\n    \n    (* TODO: LTAC this *)\n\n    split; intros [H1 H2].\n    \n    split; [try rewrite <- HeqE; eauto|].\n    intros [Hnot1 Hnot2];\n    apply H2; clear H2.\n    split; [auto|].\n    destruct Hnot2 as [Hnot2 | Hnot2]; [left|right; intros Hnot2'; apply Hnot2];\n       eapply Proper_ag_ex_flow_eq; eauto; apply Ref.eq_refl.\n\n    split; [try rewrite <- HeqE; eauto|].\n    intros [Hnot1 Hnot2];\n    apply H2; clear H2.\n    split; [auto|].\n    destruct Hnot2 as [Hnot2 | Hnot2]; [left|right; intros Hnot2'; apply Hnot2];\n       eapply Proper_ag_ex_flow_eq; eauto; apply Ref.eq_refl.\n  Qed.\n  Hint Resolve Proper_ag_confined_eq.\n\n  Theorem ag_confined_dec : forall E P x, {ag_confined E P x} + {~ ag_confined E P x}.\n  Proof.\n    intros E P x; unfold ag_confined; Sumbool_decide; \n      try apply RefSetProps.In_dec; try apply Ref.eq_dec; try apply AccessRight.eq_dec; eauto.\n  Qed.\n  Hint Resolve ag_confined_dec.\n\n\n(* The above decidability rules require interesting predicates *)\n(* In particular, (exists y, P y) and (exists y, ~ P y) must both be decidable in set *)\n(* This is true for FSets, but may not hold for other all structures. *)\n\n  Definition ag_confined' E P x := \n    ~ (Ref.eq (Edges.source x) (Edges.target x)) /\\\n    (~ AccessRight.eq (Edges.right x) wk \\/\n      (~ ag_ex_flow E P (Edges.source x) /\\ ag_ex_flow E P (Edges.target x))).\n\nTheorem ag_confined_iff_ag_confined' : forall E A x,\n  ag_confined E A x <-> ag_confined' E A x.\nProof.\n  intros E A x.\n  unfold ag_confined; unfold ag_confined'.\n  \n\n  generalize (RefSetProps.In_dec (Edges.source x) E); intros Pdec.\n  (* AccessRight.eq_dec is automatically unfolding when we didn't ask it to. This is an inelegant fix*)\n  unfold AccessRight.eq in *.\n  generalize (AccessRight.eq_dec (Edges.right x) wk);\n      intros Qdec.\n  generalize (RefSetProps.In_dec (Edges.target x) E); intros Rdec.\n  generalize (ag_ex_flow_dec E A (Edges.source x)); intros Sdec.\n  generalize (ag_ex_flow_dec E A (Edges.target x)); intros Tdec.\n\n  repeat progress (rewrite Sumbool_not_and; Sumbool_decide; eauto).\n  repeat progress (rewrite <- Sumbool_dec_not_not_iff; Sumbool_decide; eauto).\n  intuition.\n  Qed.\n\n  Definition subset_eq_ag_confined E A B:= subset_eq_pred (fun P _ => (ag_confined E P)) A B.\n\n  Theorem subset_eq_ag_confined_eq :\n    Proper (RefSet.eq ==> AG.eq ==> AG.eq ==> iff) subset_eq_ag_confined.\n  Proof.\n    unfold Proper; unfold respectful.\n    intros x y Heq x0 y0 Heq0 x1 y1 Heq1.\n    eapply subset_eq_pred_eq; eauto.\n    unfold respectful.\n    intros x2 y2 Heq2 x3 y3 Heq3 x4 y4 Heq4.\n    eapply Proper_ag_confined_eq; eauto.\n  Qed.\n\n  Hint Resolve subset_eq_ag_confined_eq.\n\n  Definition subset_eq_ag_simply_confined E A B := subset_eq_pred (fun _ _ => ag_simply_confined E) A B.\n\n  Theorem subset_eq_ag_simply_confined_eq :\n    Proper (RefSet.eq ==> AG.eq ==> AG.eq ==> iff) subset_eq_ag_simply_confined.\n  Proof.\n    unfold Proper; unfold respectful.\n    intros x y Heq x0 y0 Heq0 x1 y1 Heq1.\n    eapply subset_eq_pred_eq; eauto.\n    unfold respectful.\n    intros x2 y2 Heq2 x3 y3 Heq3 x4 y4 Heq4.\n    eapply Proper_ag_simply_confined_eq; eauto.\n  Qed.\n  Hint Resolve subset_eq_ag_simply_confined_eq.\n\n\n  Theorem ag_ex_flow_in : forall e E, RefSet.In e E -> forall A, ag_ex_flow E A e.\n  Proof.\n    intros.\n    eapply ex_intro.\n    split; eauto; apply ag_flow_refl; apply Ref.eq_refl.\n  Qed.\n\n  Hint Resolve ag_ex_flow_in.\n\n  Theorem ag_confined_ag_simply_confined : forall E P x, ag_confined E P x -> ag_simply_confined E x.\n  Proof.\n    unfold ag_confined; unfold ag_simply_confined.\n    intros E P x [Heq Hflow].\n    split; auto.\n    intros [Hs [Ht Hr]].\n    apply Hflow.\n    split; [auto| left].\n    eauto.\n  Qed.\n  Hint Resolve ag_confined_ag_simply_confined.\n\n  Theorem subset_eq_ag_simply_confined_ag_confined : forall E A B,\n    subset_eq_ag_simply_confined E A B -> subset_eq_ag_confined E A B.\n  Proof.\n    unfold subset_eq_ag_simply_confined; unfold subset_eq_ag_confined; unfold subset_eq_pred.\n    intros E A P [Hsub HsubP].\n    split; auto.\n    unfold subset_pred in *.\n    intros x Hconf Hin.\n    eapply HsubP; eauto.\n  Qed.\n  Hint Resolve subset_eq_ag_simply_confined_ag_confined.\n\n  Theorem subset_eq_ag_confined_mutable:\n    forall P P' E, subset_eq_ag_confined E P' P ->\n    forall M, mutable_spec P E M ->\n    forall M', mutable_spec P' E M' ->\n      RefSet.Equal M M'.\n  Proof.\n    intros P P' E Hwkeq M Hm M' Hm' x.\n    eapply iff_trans; [eapply Hm|clear Hm].\n    eapply iff_sym; eapply iff_trans; [eapply Hm'|clear Hm'].\n    destruct Hwkeq as [Hsub Hwksub].\n\n    unfold ag_confined in *; unfold subset_pred in *.\n    case (RefSetProps.In_dec x E); intros Hcase;\n      (* If x in E, then we have one of our assumptions *)\n      [split; intro H; left; assumption | ].\n    (* solve when ~ x in E , remember to place x in E for a contradiction later.*)\n    split;\n      (intro H; destruct H as [H|H]; \n        [left; assumption \n          | right; destruct H as [e [Hin HinP]]]).\n    (* solve P' -> P *)\n    eapply ex_intro; split; [apply Hin|intuition].\n    (* solve P -> P' *)\n\n    destruct HinP as [HinP | [HinP | [HinP | HinP]]];\n      try solve \n        [case (ag_ex_flow_dec E P' x); intros Hflow;\n          [ destruct Hflow as [e' [Hin'  [Hflow' | Hflow' | Hflow' | Hflow' | Hflow']]];\n            solve [rewrite Hflow' in *; contradiction\n              | eapply ex_intro; intuition (solve [eapply Hin' | eapply Hflow'])]\n            | eapply Hwksub in HinP;\n              [eapply ex_intro; split; [eauto | intuition]\n                | try rewrite Edges.source_rewrite in *;\n                  try rewrite Edges.target_rewrite in *;\n                    try rewrite Edges.right_rewrite in *;\n                      split; \n                        [ intros Hneq; apply Hcase; first [rewrite Hneq | rewrite <- Hneq]; auto\n                          | try solve [intros [Hneq1 Hneq2]; solve [discriminate| intuition eauto]]]]]].\n  Qed.\n\n\n  (* TODO: Some of these properties probably should live in Sequential Access \n     as they are more general than this proof *)\n\n  Theorem add_potTrans_fn : forall A B x, AGProps.Add x A B ->\n    exists Fadd, AG.Equal B (Fadd A) /\\ Seq.ag_potTransfer_fn_req Fadd.\n  Proof.\n    intros.\n    eapply ex_intro.\n    split; [eapply AG.eq_sym; eapply AGAddEq.Add_add; eauto|].\n    split; [eapply Seq.add_add_commute|].\n    split; [unfold ag_nondecr; intros; eapply AGProps.subset_add_2; eauto|].\n     unfold Seq.ag_equiv; intros; eapply AGFacts.add_m; eauto.\n   Qed.\n\n   (* NOTE:  subset_union_diff has moved to FSetAddEq *)\n\n   Hint Resolve AGAddEq.subset_union_diff.\n\n   (* TODO: Move to sequential access *)\n   Theorem subset_potTransfer_fn_union_diff: forall A B, AG.Subset A B ->\n     Seq.ag_potTransfer_fn_req (fun Z => (AG.union Z (AG.diff B A))).\n   Proof.\n     intros A B H.\n     split.\n     unfold Seq.ag_add_commute; intros ag ag' x Hedge.\n     intros y.\n     generalize (Hedge y); clear Hedge; intros Hedge.\n     generalize (H y); intros Hy.\n     generalize (H x); intros Hx.\n       Ltac simple_solver_7 H1 :=      \n         eapply AGFacts.union_iff in H1; destruct H1 as [H1 | H1]; [| apply AGFacts.diff_iff in H1]; \n           intuition; AGFacts.set_iff; auto.\n     case (Edge.eq_dec x y); intros Heq;\n     intuition (AGFacts.set_iff; auto); \n       solve [simple_solver_7 H1 | simple_solver_7 H4].\n\n     split.\n     unfold ag_nondecr; intros ag ag' Hsub.\n     intros x Hin.\n     generalize (Hsub x Hin); intros Hin'.\n     AGFacts.set_iff; intuition.\n\n     unfold Seq.ag_equiv; intros ag ag' Heq.\n     rewrite Heq. auto.\n   Qed.\n\n   Hint Resolve subset_potTransfer_fn_union_diff.\n\n\n   (* TODO: Move to sequential access *)\n   Theorem subset_potTransfer_fn_union_diff2: forall A B, AG.Subset A B ->\n     Seq.ag_potTransfer_fn_req (fun A => (AG.union A (AG.diff B A))).\n   Proof.\n     intros A B H.\n     split.\n     unfold Seq.ag_add_commute; intros ag ag' x Hedge.\n     intros y.\n     generalize (Hedge y); clear Hedge; intros Hedge.\n     generalize (H y); intros Hy.\n     generalize (H x); intros Hx.\n     case (Edge.eq_dec x y); intros Heq;\n     intuition (AGFacts.set_iff; auto); \n       solve [simple_solver_7 H1 | simple_solver_7 H4].\n\n     split.\n     unfold ag_nondecr; intros ag ag' Hsub.\n     intros x Hin.\n     generalize (Hsub x Hin); intros Hin'.\n     AGFacts.set_iff; intuition.\n\n     unfold Seq.ag_equiv; intros ag ag' Heq.\n     rewrite Heq. auto.\n   Qed.\n\n   Hint Resolve subset_potTransfer_fn_union_diff2.\n\n\n   (* TODO: Place in Sequential Access *)\n   Theorem subset_potTrans_fn: forall A B, AG.Subset A B -> \n     exists Fadd, AG.Equal B (Fadd A) /\\ Seq.ag_potTransfer_fn_req Fadd.\n   Proof.\n     intros.\n     eapply ex_intro with (fun Z => (AG.union Z (AG.diff B A))); eauto.\n   Qed.\n     \n   (* This theorem obviates a lot of others *)\n   (* TODO: move to SequentialAccessImpl.v *)\n   Theorem ag_potTransfer_fn_req_empty :\n     forall Fa, Seq.ag_add_commute Fa -> Seq.ag_equiv Fa ->\n       forall A, AG.Equal (Fa A) (AG.union A (Fa AG.empty)).\n   Proof.\n     intros Fa HaddComm Hequiv.\n     eapply AGProps.set_induction.\n     (* base *)\n     intros s Hempty.\n     eapply AGProps.empty_is_empty_1 in Hempty.\n     intros x.\n     generalize (Hequiv _ _ Hempty x); intros Heq.\n     generalize (Hempty x).\n     revert Heq.\n     intuition (AGFacts.set_iff; auto).\n     apply AGFacts.union_iff in H; intuition.\n     eapply AGFacts.empty_iff in H; contradiction.\n     (* step *)\n     intros s s' IH x HninX Hadd.\n     generalize (HaddComm _ _ _ Hadd); intros Hadd'.\n     intros y.\n     eapply iff_sym.\n     eapply iff_trans.\n     eapply AGFacts.union_iff.\n     generalize (IH y); intros IHy.\n     eapply iff_sym in IHy.\n     eapply iff_trans in IHy; [| eapply iff_sym; eapply AGFacts.union_iff].\n     generalize (Hadd y); clear Hadd; intros Hadd.\n     generalize (Hadd' y); clear Hadd'; intros Hadd'.\n     intuition auto.\n   Qed.\n\n   (* TODO: This obviates the need for ag_nondecr as a fn req. *)\n   (* Fix in Sequential Access *)\n   Theorem ag_add_commute_equiv_impl_monotonic :\n     forall Fa, Seq.ag_add_commute Fa -> Seq.ag_equiv Fa ->\n       ag_nondecr Fa.\n   Proof.\n     unfold ag_nondecr. intros Fa Hcomm Hequiv ag ag' Hsub.\n     intros x Hin.\n     eapply ag_potTransfer_fn_req_empty; [eauto | eauto |].\n     AGFacts.set_iff.\n     intuition eauto.\n   Qed.\n\n\n   (* Note the signature here on P has different variance from above.  P\n      must consider this argument irrelevant to apply both rules *)\n   (*  *)\n   Theorem subset_pred_add_commute: forall Fadd, Seq.ag_add_commute Fadd -> Seq.ag_equiv Fadd ->\n     forall P, Proper (AG.Subset --> AG.Subset --> Edge.eq ==> impl) P ->\n     forall A B, subset_pred P A B -> \n       subset_pred P (Fadd A) (Fadd B).\n   Proof.\n     unfold subset_pred in *.\n     intros Fa Hcomm Hequiv P Pproper A B Hpred x Px HinX.\n     eapply ag_potTransfer_fn_req_empty; auto.\n     eapply ag_potTransfer_fn_req_empty in HinX; auto.\n     eapply AGFacts.union_iff.\n     eapply AGFacts.union_iff in HinX.\n     intuition auto.\n     left.\n     unfold Proper in *; unfold respectful in *; unfold flip in *; unfold impl in *.\n     eapply Hpred; [|apply H].\n     eapply Pproper; [| | apply Edge.eq_refl \n         | apply Px]; apply ag_add_commute_equiv_impl_monotonic; auto.\n   Qed.\n\n   Hint Resolve subset_pred_add_commute.\n\n   Theorem subset_eq_pred_add_commute: forall Fadd, Seq.ag_add_commute Fadd -> Seq.ag_equiv Fadd ->\n     forall P, Proper (AG.Subset --> AG.Subset --> Edge.eq ==> impl) P ->\n     forall A B, subset_eq_pred P A B -> \n       subset_eq_pred P (Fadd A) (Fadd B).\n   Proof.\n     intros.\n     destruct H2.\n     unfold Proper in *; unfold respectful in *; unfold flip in *.\n     split;\n       solve [ eapply Seq.ag_subset_add_commute; eauto\n         | eapply subset_pred_add_commute; eauto].\n   Qed.\n\n\n(*\n   Theorem weak_subset_add_commute: forall Fadd, Seq.ag_add_commute Fadd -> Seq.ag_equiv Fadd ->\n     forall A B E, weak_subset A E B -> weak_subset (Fadd A) E (Fadd B).\n   Proof.\n     unfold weak_subset; intros; auto.\n   Qed.\n\n   Hint Resolve weak_subset_add_commute.\n*)\n\n\n   (* Theorem subset_eq_ag_confined_add_commute: forall Fadd,  Seq.ag_add_commute Fadd -> Seq.ag_equiv Fadd -> *)\n   (*   forall A B E, subset_eq_ag_confined E A B -> *)\n   (*     subset_eq_ag_confined E (Fadd A) (Fadd B). *)\n   (* Proof. *)\n   (*   intros Fadd Hcomm Hequiv A B E [Hsub Hwksub]. *)\n   (*   generalize (Seq.ag_subset_add_commute Hcomm Hequiv); intros Hsubcomm. *)\n   (*   split; eauto. *)\n   (*   eapply subset_pred_add_commute; eauto. *)\n   (*   eapply Proper_irrel_subst_contravariant; *)\n   (*   eapply Proper_irrel_ignore_contravariant. *)\n   (*   apply ag_confined_sub; *)\n   (*   apply RefSetProps.subset_equal; apply RefSet.eq_refl. *)\n   (* Qed. *)\n\n   (* Hint Resolve subset_eq_ag_confined_add_commute. *)\n\n\n  (* This relies on the fact that potTrans commutes with Add \n     We might need to prove subset_eq_ag_confined has the ag_fn_req properties.*)\n\n   (* Theorem subset_eq_ag_confined_potTrans_func : *)\n   (*   forall Fa, Seq.ag_potTransfer_fn_req Fa -> *)\n   (*   forall Fa', Seq.ag_potTransfer_fn_req Fa' -> *)\n   (*   forall A, Seq.potTrans A (Fa A) -> *)\n   (*   forall E, subset_eq_ag_confined E A (Fa' A) -> *)\n   (*   Seq.potTrans (Fa' A) (Fa (Fa' A)) /\\ subset_eq_ag_confined E (Fa A) (Fa (Fa' A)). *)\n   (* Proof. *)\n   (*   intros Fa Freq Fa' Freq' A Htrans E Hwkeq. *)\n   (*   split; *)\n   (*     solve [ *)\n   (*       eapply Seq.potTrans_eq; *)\n   (*         [eapply AG.eq_refl *)\n   (*           | apply add_commute_increasing_transpose; unfold Seq.ag_potTransfer_fn_req in *; intuition *)\n   (*           | apply Seq.potTrans_commute_monotonic; unfold Seq.ag_potTransfer_fn_req in *; intuition] *)\n   (*       | eapply subset_eq_ag_confined_add_commute; unfold Seq.ag_potTransfer_fn_req in *; intuition]. *)\n   (* Qed. *)\n\n  (* This theorem, subset_eq_ag_confined_potTrans, could be formulated over a single A,\n     and two functions Fa and Fa' satisfying ag_potTransfer_fn_req :\n     (A':=A) (B' := (Fa A)) and (A := (Fa' A)) and (B := (Fa' (Fa A))). *)\n\n  (* Theorem subset_eq_ag_confined_potTrans: *)\n  (*   forall A' B', Seq.potTrans A' B' -> *)\n  (*   forall A E, subset_eq_ag_confined E A' A -> *)\n  (*   exists B, Seq.potTrans A B /\\ subset_eq_ag_confined E B' B. *)\n  (* Proof. *)\n  (*   intros A' B' Htrans A E Hwkeq. *)\n\n  (*   (* Find Fa and Fa' *) *)\n  (*   generalize Hwkeq; intros [Hsub _]. *)\n  (*   eapply subset_potTrans_fn in Hsub; destruct Hsub as [Fa' [Hequiv' Freq']]. *)\n  (*   generalize (subset_potTrans_fn _ _ (Seq.potTrans_subset Htrans)); intros [Fa [Hequiv Freq]]. *)\n    \n  (*   (* solve for weak_eq_subset_potTrans_func *) *)\n  (*   eapply Seq.potTrans_eq in Htrans; [ *)\n  (*     | eapply AG.eq_refl *)\n  (*     | eapply Hequiv]. *)\n  (*   eapply subset_eq_ag_confined_eq in Hwkeq; [ *)\n  (*     | apply RefSet.eq_refl *)\n  (*     | apply AG.eq_refl *)\n  (*     | apply AG.eq_sym; apply Hequiv']. *)\n    \n  (*   generalize (subset_eq_ag_confined_potTrans_func _ Freq _ Freq' _ Htrans _ Hwkeq). *)\n  (*   intros [Htrans' Hwkeq']. *)\n\n  (*   (* instantiate and solve *) *)\n  (*   eapply ex_intro; split. *)\n  (*   eapply Seq.potTrans_eq. *)\n  (*   apply AG.eq_sym; apply Hequiv'. *)\n  (*   apply AG.eq_refl. *)\n  (*   apply Htrans'. *)\n    \n  (*   eapply subset_eq_ag_confined_eq. *)\n  (*   apply RefSet.eq_refl. *)\n  (*   apply Hequiv. *)\n  (*   apply AG.eq_refl. *)\n  (*   apply Hwkeq'. *)\n  (* Qed. *)\n\n\n      Ltac destruct_ag_confined Px := \n        let Px1 := fresh \"Px1\" in\n          let Px2 := fresh \"Px2\" in\n            destruct Px as [Px1 Px2].\n      \n      Ltac destruct_ag_confined' Px := \n        let Px1 := fresh \"Px1\" in\n          let Px2 := fresh \"Px2\" in\n              destruct Px as [Px1 Px2].\n\n      Ltac edge_simpl := \n        try rewrite Edges.source_rewrite in *; try rewrite Edges.target_rewrite in *; \n          try rewrite Edges.right_rewrite in *.\n      \n      Ltac predicate_simpl Heq := \n        generalize (Edges.eq_source _ _ Heq) (Edges.eq_target _ _ Heq) (Edges.eq_right _ _ Heq); \n          let HeqS := fresh \"HeqS\" in let HeqR := fresh \"HeqR\" in let HeqT := fresh \"HeqT\" in \n            intros HeqS HeqT HeqR; try rewrite <- HeqS in *; try rewrite <- HeqT in *; try rewrite <- HeqR in *;\n              edge_simpl; clear HeqS HeqR HeqT.\n\n\n    Theorem subset_eq_ag_confined_trans_max:\n      forall A B, Seq.transfer A B ->\n        forall P, Seq.maxTransfer P ->\n          forall E, subset_eq_ag_confined E P A ->\n            subset_eq_ag_confined E P B.\n    Proof.\n      intros A B Htrans P Hmax E Hwkeq.\n      destruct Hwkeq as [Hsub Hwksub].\n      split.\n      eapply AGProps.subset_trans;\n        [apply Hsub\n          | eapply Seq.transfer_subset; auto].\n\n      unfold subset_pred in *. (* unfold ag_confined in *. *)\n      intros x Px Hin.\n      generalize (Hwksub _ Px); intros HwksubPx.\n        (* destruct Px as [Px1 [Px2 [Px3 Px4]]]. *)\n\n      destruct Htrans.\n      \n      (* src self *)\n      destruct (H0 x) as [Hadd _].\n      apply Hadd in Hin; clear Hadd; destruct Hin as [Heq|Hin]; try solve [intuition];\n        destruct_ag_confined Px; predicate_simpl Heq.\n      generalize (Px1 (Ref.eq_refl _)); contradiction.\n\n      (* src tgt, same *)\n      destruct (H0 x) as [Hadd _].\n      apply Hadd in Hin; clear Hadd; destruct Hin as [Heq|Hin]; try solve [intuition];\n        destruct_ag_confined Px; predicate_simpl Heq.\n      generalize (Px1 (Ref.eq_refl _)); contradiction.\n\n      (* read *)\n      Ltac preamble H1 x Hin Px :=\n        let Hadd := fresh \"Hadd\" in\n        let Heq := fresh \"Heq\" in \n      destruct (H1 x) as [Hadd _];\n      apply Hadd in Hin; clear Hadd;\n      destruct Hin as [Heq|Hin]; try solve [intuition];\n\n      rewrite ag_confined_iff_ag_confined' in Px;\n      unfold ag_confined' in Px;\n      destruct_ag_confined' Px;\n      predicate_simpl Heq.\n\n      preamble H1 x Hin Px.\n      \n\n      (* if src = tgt, then we are reading from ourself, and the edge we read is already in A placing it in P *)\n         \n      case (Ref.eq_dec src tgt); intros Hcase1; \n        [rewrite Hcase1 in *;eapply HwksubPx; eapply AGFacts.In_eq_iff; [apply Edge.eq_sym; apply Heq | auto]|].\n      (* We know src <> tgt *)\n\n      (* place (src tgt read) in P *)\n\n      eapply Hwksub in H; [|\n        rewrite ag_confined_iff_ag_confined'; unfold ag_confined'; predicate_simpl Heq;\n          split; [eauto | solve [intuition discriminate]]].\n\n      (* if tgt = tgt', then we are reading a reflexive edge. \n         By H, this edge must be in P, and so too must (tgt tgt' rgt) *)\n\n      case (Ref.eq_dec tgt tgt'); intros Hcase2.\n      rewrite Hcase2 in *;\n      eapply Hmax;\n        [ eapply Seq.transfer_read;\n          [ apply H\n            | eapply Hmax;\n              [eapply Seq.transfer_self_tgt;\n                [ apply H\n                  | apply AGProps.Add_add]\n                | apply AGProps.Add_add; eauto]\n            | apply AGProps.Add_add]\n          | apply AGProps.Add_add; eauto].\n      (* tgt <> tgt' *)\n\n      Ltac solution_1 Hwksub H0 Heq Hmax H trans_op:=\n      eapply Hwksub in H0; [\n      | rewrite ag_confined_iff_ag_confined';\n        unfold ag_confined'; unfold ag_ex_flow; unfold AG.Exists;\n          predicate_simpl Heq; split; intuition eauto];\n\n      (* place the edge in P by trans_op *)\n      eapply Hmax;\n        [ eapply trans_op;\n          [ apply H\n            | apply H0\n            | apply AGProps.Add_add]\n          | apply AGProps.Add_add; eauto].\n\n      (* By cases on access right.  If it is not weak, (tgt tgt' rgt) in P*)\n      case (AccessRight.eq_dec rgt wk); intros HcaseRight;\n        [rewrite HcaseRight in *;\n          destruct Px2 as [Px2 | Px2]; try solve [contradict Px2; apply AccessRight.eq_refl] |\n            solution_1 Hwksub H0 Heq Hmax H Seq.transfer_read].\n\n      (* rgt= wk *)\n      destruct Px2 as [Pxsrc Pxtgt'].\n\n\n      (* there must also not be a flow from E to tgt.  If there were, this would violate the lack of flow to src.*)\n      case (ag_ex_flow_dec E P tgt) as [[e [HinE Hflow]] | Hflow];\n        [ contradict Pxsrc; eapply ex_intro; split; eauto\n          | solution_1 Hwksub H0 Heq Hmax H Seq.transfer_read].\n\n      (* write *)\n      preamble H1 x Hin Px.\n\n      (* if src = tgt, then we are writing to ourself, and the edge we write is already in A placing it in P *)\n         \n      case (Ref.eq_dec src tgt); intros Hcase1; \n        [rewrite Hcase1 in *;eapply HwksubPx; eapply AGFacts.In_eq_iff; [apply Edge.eq_sym; apply Heq | auto]|].\n      (* We know src <> tgt *)\n\n      (* place (src tgt write) in P *)\n\n      eapply Hwksub in H; [|\n        rewrite ag_confined_iff_ag_confined'; unfold ag_confined'; predicate_simpl Heq;\n          split; [eauto | solve [intuition discriminate]]].\n\n      (* if src = tgt', then we are creating a reflexive edge. \n         By H, this edge must be in P, and so too must (tgt tgt' rgt) *)\n\n      case (Ref.eq_dec src tgt'); intros Hcase2.\n      rewrite Hcase2 in *.\n\n      eapply Hmax;\n        [ eapply Seq.transfer_write;\n          [ apply H\n            | eapply Hmax;\n              [eapply Seq.transfer_self_src;\n                [ apply H\n                  | apply AGProps.Add_add]\n                | apply AGProps.Add_add; eauto]\n            | apply AGProps.Add_add]\n          | apply AGProps.Add_add; eauto].\n      \n      (* src <> tgt' *)\n\n      (* By cases on access right.  If it is not weak, (tgt tgt' rgt) in P*)\n      case (AccessRight.eq_dec rgt wk); intros HcaseRight;\n        [rewrite HcaseRight in *;\n          destruct Px2 as [Px2 | Px2]; try solve [contradict Px2; apply AccessRight.eq_refl] |\n            solution_1 Hwksub H0 Heq Hmax H Seq.transfer_write].\n\n      (* rgt = wk *)\n      destruct Px2 as [Pxtgt Pxtgt'].\n\n      (* there must also not be a flow from E to tgt.  If there were, this would violate the lack of flow to src.*)\n      case (ag_ex_flow_dec E P src) as [[e [HinE Hflow]] | Hflow];\n        [ contradict Pxtgt; eapply ex_intro; split; eauto\n          | solution_1 Hwksub H0 Heq Hmax H Seq.transfer_write].\n\n      (* send *)\n      preamble H1 x Hin Px.\n\n      (* if src = tgt, then we are writing to ourself, and the edge we write is already in A placing it in P *)\n         \n      case (Ref.eq_dec src tgt); intros Hcase1; \n        [rewrite Hcase1 in *;eapply HwksubPx; eapply AGFacts.In_eq_iff; [apply Edge.eq_sym; apply Heq | auto]|].\n      (* We know src <> tgt *)\n\n      (* place (src tgt read) in P *)\n\n      eapply Hwksub in H; [|\n        rewrite ag_confined_iff_ag_confined'; unfold ag_confined'; predicate_simpl Heq;\n          split; [eauto | solve [intuition discriminate]]].\n\n      (* if src = tgt', then we are creating a reflexive edge. \n         By H, this edge must be in P, and so too must (tgt tgt' rgt) *)\n\n      case (Ref.eq_dec src tgt'); intros Hcase2.\n      rewrite Hcase2 in *.\n\n      eapply Hmax;\n        [ eapply Seq.transfer_send;\n          [ apply H\n            | eapply Hmax;\n              [eapply Seq.transfer_self_src;\n                [ apply H\n                  | apply AGProps.Add_add]\n                | apply AGProps.Add_add; eauto]\n            | apply AGProps.Add_add]\n          | apply AGProps.Add_add; eauto].\n      \n\n      (* src <> tgt' *)\n\n      (* By cases on access right.  If it is not weak, (tgt tgt' rgt) in P*)\n      case (AccessRight.eq_dec rgt wk); intros HcaseRight;\n        [rewrite HcaseRight in *;\n          destruct Px2 as [Px2 | Px2]; try solve [contradict Px2; apply AccessRight.eq_refl] |\n            solution_1 Hwksub H0 Heq Hmax H Seq.transfer_send].\n\n      (* rgt = wk *)\n      destruct Px2 as [Pxtgt Pxtgt'].\n\n      (* there must also not be a flow from E to tgt.  If there were, this would violate the lack of flow to src.*)\n      case (ag_ex_flow_dec E P src) as [[e [HinE Hflow]] | Hflow];\n        [ contradict Pxtgt; eapply ex_intro; split; eauto\n          | solution_1 Hwksub H0 Heq Hmax H Seq.transfer_send].\n \n      (* send self *)\n      preamble H0 x Hin Px.\n\n      (* if src = tgt, then we are writing to ourself, and the edge we write is already in A placing it in P *)\n         \n      case (Ref.eq_dec src tgt); intros Hcase1; \n        [rewrite Hcase1 in *;eapply HwksubPx; eapply AGFacts.In_eq_iff; [apply Edge.eq_sym; apply Heq | auto]|].\n      (* We know src <> tgt *)\n\n      (* place (src tgt read) in P *)\n\n      eapply Hwksub in H; [|\n        rewrite ag_confined_iff_ag_confined'; unfold ag_confined'; predicate_simpl Heq;\n          split; [eauto | solve [intuition discriminate]]].\n\n      (* Apply maxTransfer and trans_send_self to show (src tgt' rgt) in P *)\n      eapply Hmax;\n        [ eapply Seq.transfer_send_reply;\n          [ apply H\n            | apply AGProps.Add_add]\n          | apply AGProps.Add_add; eauto].\n\n      (* weak *)\n\n      preamble H2 x Hin Px.\n\n      (* if tgt = tgt', we are reading from a reflexive edge, which is already in A placing it in P. *)\n      case (Ref.eq_dec tgt tgt'); intros Hcase2;\n        [rewrite Hcase2 in *;eapply HwksubPx; eapply AGFacts.In_eq_iff; [apply Edge.eq_sym; apply Heq | auto]|].\n\n      (* tgt [<>] tgt' *)\n\n      (* eliminate nonsensical case. *)\n      destruct Px2 as [Px2 | [Pxsrc Pxtgt']]; [contradict Px2; apply AccessRight.eq_refl|].\n\n\n      (* first by cases on (ag_ex_flow E P tgt) *)\n\n      case (ag_ex_flow_dec E P tgt); intros HflowTgt.\n      (* we can show a flow contradiction if src [=] tgt *)\n      case (Ref.eq_dec src tgt); intros Hcase1; [rewrite Hcase1 in *; contradict Pxsrc; eauto|].\n\n      (* This places (src tgt weak) In P. *)\n      eapply Hwksub in H; [|\n        rewrite ag_confined_iff_ag_confined'; unfold ag_confined'; predicate_simpl Heq;\n          split; [eauto | solve [intuition discriminate]]].\n\n      (* we now have a flow contradiction.  There is a flow to src in P, which can not happen *)\n      destruct HflowTgt as [e [HinE Hflow]]; contradict Pxsrc; eapply ex_intro; eauto.\n\n      (* ~ ag_ex_flow E P tgt *)\n\n      (* we can place (tgt tgt' rgt) In P *)\n      eapply Hwksub in H0; [|\n        rewrite ag_confined_iff_ag_confined'; unfold ag_confined'; predicate_simpl Heq;\n          split; [eauto | solve [intuition discriminate]]].\n\n      (* However this forms another flow contradiction, because there is a flow to tgt' *)\n      destruct Pxtgt' as [e [HinE Hflow]].\n      contradict HflowTgt.\n      destruct H1; rewrite H1 in *;\n        (eapply ex_intro; split; [apply HinE| eapply maxTransfer_ag_flow_trans; [auto| apply Hflow| eauto]]).\n    Qed.\n\n\n  (* The trouble with subset_eq_ag_confined_potTrans_func is, while it identifies\n     the element that we can potTrans to, we do not yet know that that value is maximal. \n     This covers the other half of the problem. *)\n\n  Theorem subset_eq_ag_confined_potTransfer_max:\n    forall B D, Seq.potTransfer B D ->\n    forall P, Seq.maxPotTransfer P ->\n    forall E, subset_eq_ag_confined E P B ->\n      subset_eq_ag_confined E P D.\n  Proof.\n    intros B D Htrans P Hmax E Hwkeq.\n    induction Htrans as [C Heq | D C Htrans IH Htrans'].\n    (* base *)\n    eapply subset_eq_ag_confined_eq;\n      [ eapply RefSet.eq_refl\n        | eapply AG.eq_refl\n        | eapply AG.eq_sym; apply Heq\n        | auto].\n    (* step *)\n    clear Hwkeq Htrans B.\n    eapply Seq.maxTransfer_maxPotTransfer in Hmax.\n\n    eapply subset_eq_ag_confined_trans_max; eauto.\n  Qed.\n    \n  (* \n     Here, D is the maximally authorized access graph, and D' is the \n     union of the confined access graph and the maximal one.\n     *)\n  Theorem dirAcc_confined : \n    forall E D D', subset_eq_ag_simply_confined E D D' ->\n    forall P, Seq.potAcc D P ->\n    forall P', Seq.potAcc D' P' ->\n    forall M, mutable_spec P E M ->\n    forall M', mutable_spec P' E M' ->\n    RefSet.eq M M'.\n  Proof.\n    intros E D D' Hsc P Hp P' Hp' M Hm M' Hm'.\n    (* Apply subset_eq_ag_confined_mutable to reduce the problem to potential access *)\n    eapply RefSet.eq_sym.\n    eapply subset_eq_ag_confined_mutable; [| eauto | eauto].\n    (* Break apart the potential access definitions*)\n    destruct Hp as [HpTrans HpMax]; destruct Hp' as [Hp'Trans Hp'Max].\n    (* use Hsc to show that D [<=] D', and introduce I as an intermediate to P' using potTransfer_subset_lub *)\n\n    generalize Hsc; intros [Hd'Eq _];\n      generalize (subset_potTransfer_fn_union_diff _ _ Hd'Eq); intros Hd'Fadd;\n      eapply AGAddEq.subset_union_diff in Hd'Eq;  set (Dx := (AG.diff D' D)) in *.\n    generalize HpTrans; intros HpEq; eapply Seq.potTransfer_subset in HpEq;\n      generalize (subset_potTransfer_fn_union_diff _ _ HpEq); intros HpFadd;\n      eapply AGAddEq.subset_union_diff in HpEq; set (Px := (AG.diff P D)) in *.\n    set (I := AG.union (AG.union D Px) Dx).\n\n\n\n    (* use subset_eq_ag_confined_potTransfer_max to reduce from P' to I *)\n    apply subset_eq_ag_confined_potTransfer_max with (B:=I); [|eauto|].\n\n    eapply Seq.potTransfer_lub with (a:=I) in Hp'Trans. \n\n\n      destruct Hp'Trans as [P'2 [Hp'2TransP Hp'2TransI]];\n        eapply Hp'Max in Hp'2TransP;\n          eapply Seq.potTransfer_eq;\n            [apply AG.eq_refl\n              | apply AG.eq_sym; eauto\n              | eauto].\n\n      unfold I; eapply Seq.potTransfer_eq;\n      [ apply AG.eq_sym; apply Hd'Eq\n        | apply AG.eq_refl\n        | eapply (Seq.potTransfer_commute_monotonic Hd'Fadd); eapply Seq.potTransfer_eq; eauto\n      ].\n\n    (* Reduce the complexity to ag_simply_confined *)\n    Ltac respectful_covariant_ag_simply_confined :=\n      do 2 (eapply Proper_irrel_subst_covariant; eapply Proper_irrel_ignore_covariant); eauto;\n        eapply Proper_ag_simply_confined_eq; apply RefSet.eq_refl.\n    Ltac respectful_contravariant_ag_simply_confined :=\n      do 2 (eapply Proper_irrel_subst_contravariant; eapply Proper_irrel_ignore_contravariant); eauto;\n        eapply Proper_ag_simply_confined_eq; apply RefSet.eq_refl.\n\n    eapply subset_eq_ag_simply_confined_ag_confined.\n    unfold I.\n    eapply subset_eq_pred_eq; \n      [ respectful_covariant_ag_simply_confined\n        | eapply HpEq\n        | rewrite AGProps.union_assoc; rewrite (AGProps.union_sym Px); \n          rewrite <- AGProps.union_assoc; apply AG.eq_refl\n        | \n      ].\n\n    eapply subset_eq_pred_add_commute with (Fadd := (fun Z => AG.union Z Px));\n      [eapply HpFadd\n        | eapply HpFadd\n        | do 2 (eapply Proper_irrel_subst_contravariant; eapply Proper_irrel_ignore_contravariant); eauto;\n          unfold Proper; unfold respectful; unfold impl; intros;\n            eapply Proper_ag_simply_confined_eq;\n              [ apply RefSet.eq_refl\n                | apply Edge.eq_sym; apply H\n                | auto]\n        | ].\n    \n    eapply subset_eq_pred_eq; \n      [ respectful_covariant_ag_simply_confined\n        | apply AG.eq_refl\n        | apply AG.eq_sym; apply Hd'Eq\n        | apply Hsc \n      ].\n  Qed.\n\n\n  (* We now turn our attention to comparing defining the notion of a fully authorized accessgraph and\n     demonstrating that the union of this graph and the confined graph is simply confined over the \n     fully authorized access graph. *)\n\n Import CapS.\n\n  Definition ag_authorized_src C src acc := CapSet.fold (ag_add_cap src) C acc.\n  Definition ag_authorized E C := RefSet.fold (ag_authorized_src C) E AG.empty.\n\n  Definition excluded_edge E edge := ~ RefSet.In (Edges.source edge) E /\\ ~ RefSet.In (Edges.target edge) E.\n  \n  Theorem excluded_edge_dec: forall E edge, {excluded_edge E edge} + {~ excluded_edge E edge}.\n    Proof.\n      intros.\n      unfold excluded_edge.\n      Sumbool_decide; apply RefSetProps.In_dec.\n    Qed.\n\n    Hint Resolve excluded_edge_dec.\n\n    Theorem Proper_excluded_edge: Proper (RefSet.eq ==> Edge.eq ==> iff) excluded_edge.\n    Proof.\n      unfold excluded_edge; unfold Proper; unfold respectful; intros; split; intros H';\n        (rewrite H in *; rewrite (Edges.eq_source _ _ H0) in *; rewrite (Edges.eq_target _ _ H0) in *; auto).\n    Qed.\n\n  Definition ag_remainder I E := AG.filter (fun edge => true_bool_of_sumbool (excluded_edge_dec E edge)) I.\n\n  Definition ag_fully_authorized I E C :=\n    AG.union \n    (AG.union \n      (Seq.complete_ag E)\n      (ag_authorized E C))\n    (ag_remainder I E).\n\n  Definition cap_edge tgt rgt cap := \n    Ref.eq (Cap.target cap) tgt /\\ \n    ARSet.In rgt (Cap.rights cap).\n\n  Definition exists_cap_edge tgt rgt C:= \n    (CapSet.Exists (cap_edge tgt rgt) C).\n\n  Definition ag_fully_authorized_spec I E C A := forall edge,\n    AG.In edge A <-> \n    ((RefSet.In (Edges.source edge) E /\\ RefSet.In (Edges.target edge) E) \\/ \n      (RefSet.In (Edges.source edge) E /\\\n        exists_cap_edge (Edges.target edge) (Edges.right edge) C) \\/\n      AG.In edge I /\\ excluded_edge E edge ).\n    \n  Definition ag_authorized_spec E C A := forall edge, \n    AG.In edge A <-> \n    RefSet.In (Edges.source edge) E /\\\n    exists_cap_edge (Edges.target edge) (Edges.right edge) C.\n  \n  Definition ag_authorized_src_spec C src I A := forall edge, \n    AG.In edge A <-> \n    AG.In edge I \\/\n    (Ref.eq src (Edges.source edge) /\\\n      exists_cap_edge (Edges.target edge) (Edges.right edge) C).\n      \n    Theorem ag_authorized_src_spec_iff : forall C src I, \n      ag_authorized_src_spec C src I (ag_authorized_src C src I).\n    Proof.\n      intros C src I; unfold ag_authorized_src_spec; unfold ag_authorized_src;\n        unfold exists_cap_edge; unfold cap_edge; unfold CapSet.Exists; intros edge.\n      eapply CapSetProps.fold_rec_bis.\n      (* equiv *)\n      intros s s' a Heq H.\n      eapply iff_trans; [ apply H|].\n      split; (intros H'; destruct H' as [HinI | [HeqSrc [cap [HinCap [HeqTgt HinRgt]]]]];\n        [left;auto\n          |right; split; [auto| eapply ex_intro with cap]; intuition; rewrite Heq in *; auto]).\n      (* base *)\n      split; intros H; try solve [intuition].\n      destruct H as [HinI | [HeqSrc [cap [HinCap [HeqTgt HinRgt]]]]]; \n        solve [intuition | apply CapSetFacts.empty_iff in HinCap; contradiction].\n      (* step *)\n      intros cap A' C' HcapIn HcapNin IH.\n      eapply iff_trans. eapply ag_add_cap_spec. apply AG.eq_refl.\n      rewrite IH; clear IH.\n      split; intros H.\n      Ltac ag_authorized_src_solve_cap_in_case cap := \n        split; [intuition|eapply ex_intro with cap; intuition (try solve [eapply CapSetProps.Add_add; auto])].\n      destruct H as [[HeqSrc [HeqTgt HinRgt]] | [HinI | [HeqSrc [cap' [HeqTgt' HinRgt']]]]]; \n        [right ; ag_authorized_src_solve_cap_in_case cap\n          |intuition|right ;  ag_authorized_src_solve_cap_in_case cap'].\n      destruct H as [HinI | [HeqSrc [cap' [HinCap' [HeqTgt' HinRgt']]]]]; [intuition |].\n      case (Cap.eq_dec cap cap'); intros Hcase;\n       [rewrite Hcase in *; rewrite (Cap.target_eq _ _ Hcase) in *; rewrite (Cap.rights_eq _ _ Hcase) in *;\n         intuition\n           | do 2 right; ag_authorized_src_solve_cap_in_case cap'; apply CapSetProps.Add_add in HinCap';\n             intuition].\n    Qed.\n\n  Theorem ag_authorized_spec_iff : forall E C, ag_authorized_spec E C (ag_authorized E C).\n  Proof.\n    unfold ag_authorized_spec; unfold ag_authorized; \n      unfold exists_cap_edge; unfold CapSet.Exists; unfold cap_edge;  \n        intros E C edge.\n    eapply RefSetProps.fold_rec_bis.\n    (* equiv *)\n    intros refset refset' acc Heq H.\n    eapply iff_trans; [apply H| clear H].\n    split; (intros H'; destruct H' as [HinSrc [cap [HinCap [HeqTgt HinRgt]]]];\n      rewrite Heq in *; split; [auto|apply ex_intro with cap; intuition auto]).\n    (* base *)\n    split; intros Hnot;\n    solve [apply AGFacts.empty_iff in Hnot; contradiction \n      | destruct Hnot as [Hnot _]; apply RefSetFacts.empty_iff in Hnot; contradiction].\n    (* step *)\n    intros src acc E' HinE HninE' IH.\n    eapply iff_trans; [apply ag_authorized_src_spec_iff |].\n    rewrite IH; clear IH.\n    intuition; try solve [ apply RefSetProps.Add_add; auto ].\n    apply RefSetProps.Add_add in H0; intuition.\n  Qed.\n\n  Definition ag_remainder_spec I E A := forall edge, AG.In edge A <->\n    AG.In edge I /\\ excluded_edge E edge.\n\n  Theorem ag_remainder_spec_iff : forall I E,\n    ag_remainder_spec I E (ag_remainder I E).\n  Proof.\n    unfold ag_remainder_spec; intros I E edge.\n    unfold ag_remainder; rewrite AGFacts.filter_iff.\n    intuition.\n    apply true_bool_of_sumbool_l in H1; auto.\n    unfold true_bool_of_sumbool; apply proof_r_true_bool_of_sumbool; auto.\n    eapply compat_P_compat_bool_true_bool_of_sumbool.\n    split; \n      [unfold Reflexive; eapply Edge.eq_refl\n        | unfold Symmetric; eapply Edge.eq_sym\n        | unfold Transitive; eapply Edge.eq_trans].\n    unfold SetoidList.compat_P; unfold Proper; unfold respectful; unfold impl; intros;\n      eapply Proper_excluded_edge; [| | apply H0]; try apply RefSet.eq_refl; eauto.\n\n  Qed.\n\n  Theorem ag_fully_authorized_spec_iff :forall I E C,\n    ag_fully_authorized_spec I E C (ag_fully_authorized I E C).\n  Proof.\n    unfold ag_fully_authorized_spec; intros I E C edge.\n    unfold ag_fully_authorized.\n    AGFacts.set_iff.\n    rewrite (ag_remainder_spec_iff I E edge).\n    rewrite (ag_authorized_spec_iff E C edge).\n    rewrite (Seq.complete_ag_spec_complete_ag E edge).\n    intuition.\n  Qed.\n\n\n  (* \n     Like an constructive subsystem, an constructive access graph is one where\n     all edges targeting E are elements of E.\n     *)\n     \n  Definition ag_constructive_P E edge := \n    ~ RefSet.In (Edges.source edge) E /\\ \n    RefSet.In (Edges.target edge) E.\n\n  Theorem ag_constructive_P_dec : forall E edge, {ag_constructive_P E edge} + {~ ag_constructive_P E edge}.\n  Proof.\n    unfold ag_constructive_P; intros E edge.\n    Sumbool_decide; eauto; eapply RefSetProps.In_dec.\n  Qed.\n\n  Theorem Proper_ag_constructive_P: Proper (RefSet.eq ==> Edge.eq ==> iff) ag_constructive_P.\n  Proof.\n    unfold Proper; unfold respectful; unfold ag_constructive_P; intros.\n    split; intros;\n    rewrite H in *; rewrite (Edges.eq_source _ _ H0) in *; rewrite (Edges.eq_target _ _ H0) in *;  intuition eauto.\n  Qed.\n\n  Definition ag_constructive E A : Prop := ~ AG.Exists (ag_constructive_P E) A.\n\n  Theorem ag_constructive_dec : forall E A, {ag_constructive E A} + {~ ag_constructive E A}.\n  Proof.\n    unfold ag_constructive. intros E A.\n    Sumbool_decide.\n    edestruct AGDep.exists_ as [H|H]; [eapply ag_constructive_P_dec| left|right];\n      (eapply H; unfold SetoidList.compat_P;\n        unfold Proper; unfold respectful; unfold impl; intros; eapply Proper_ag_constructive_P; \n          [ apply RefSet.eq_refl | apply Edge.eq_sym; eauto | apply H1]).\nQed.\n\n  Hint Resolve ag_constructive_dec.\n\n\n  Theorem constructive_subsystem_impl_ag : \n    forall E S, Sub.constructive_subsystem E S -> \n    forall D, dirAcc_spec S D ->\n      ag_constructive E D.\n  Proof.\n    unfold ag_constructive; unfold AG.Exists; unfold ag_constructive_P;\n      unfold Sub.constructive_subsystem; unfold RefSet.For_all. \n    intros E S Hsub D Hda.\n    rewrite not_exists_iff. intros edge.\n    eapply Sumbool_not_and; Sumbool_decide; eauto; try apply AGProps.In_dec; try apply RefSetProps.In_dec. \n    rewrite Sumbool_not_and; Sumbool_decide; eauto; try apply RefSetProps.In_dec.\n    rewrite <- (Edges.edge_rewrite edge);\n    generalize (Edges.source edge) (Edges.target edge) (Edges.right edge); intros src tgt rgt; clear edge.\n    rewrite Edges.source_rewrite; rewrite Edges.target_rewrite.\n    case (RefSetProps.In_dec src E); intros HinSrc; [ intuition eauto|].\n    case (RefSetProps.In_dec tgt E); intros HinTgt; [| intuition eauto].\n    left.\n\n    generalize (Hsub _ HinTgt); intros [Hextant Hauto]; clear Hsub.\n    unfold Sub.extant_test in *.\n    rewrite Sub.constructive_test_iff' in *; unfold Sub.constructive_test' in *.\n    intros Hin; apply Hauto; clear Hauto.\n    apply Hda in Hin.\n    destruct_dirAcc Hin s' HeqS src_ref1 src1 lbl1 srcType1 srcSched1 HmapS1 \n    src1' lbl1' srcType1' srcSched1' HeqP Halive ind cap HmapSrc'\n    cap_obj cap_lbl cap_type cap_sched HmapScap cap_obj' cap_lbl' cap_type' cap_sched'\n    HeqPcap HaliveCap rgt1 HdaR HeqEdge.\n    destructEdgeEq HeqEdge (Edges.mkEdge src tgt rgt) HeqS' HeqT' HeqR'.\n    apply ex_intro with src.\n    \n    eapply Sys_MapEquiv.exists_mapsTo_eq in HmapS1;\n      [| eapply Sys.eq_sym; apply HeqS | apply HeqS'].\n    destruct HmapS1 as [tuple [Heq Hmap]].\n    destruct_tuple tuple src'' lbl'' typ'' sch''; simpl in *.\n    destruct_tuple Heq HsrcEq HlblEq HtypEq HschEq.\n    eapply Sys.MapS.find_1 in Hmap. \n    destruct_tuple HeqP HeqSrc1 HeqLbl1 HeqTyp1 HeqSch1; simpl in *.\n    eapply Obj_MapEquiv.exists_mapsTo_eq in HmapSrc';\n      [ |\n        eapply Obj.eq_trans;\n        [apply Obj.eq_sym; apply HeqSrc1 | apply HsrcEq]\n        | apply Ind.eq_refl].\n    destruct HmapSrc' as [cap' [HcapEq HcapMap]].\n\n\n\n    do 2 eapply ex_intro.\n    split.\n    unfold SC.getCap; unfold SC.getObj;unfold SC.getObjTuple.\n\n    erewrite Hmap; simpl.\n    unfold OC.getCap.\n    eapply Obj.MapS.find_1.\n    apply HcapMap.\n\n    split.\n    unfold SC.is_alive; unfold SC.is_label; unfold SC.getLabel; unfold SC.getObjTuple.\n    rewrite Hmap; simpl.\n    rewrite <- HlblEq.\n    rewrite HeqLbl1.\n    rewrite <- Halive; apply ObjectLabel.eq_refl.\n\n    split.\n    auto.\n    eapply Ref.eq_trans.\n    eapply Ref.eq_sym; apply HeqT'.\n    apply Cap.target_eq.\n    auto.\nQed.\n\n\n  (* TODO: Move all complete_AG_dec material to Sequential Access *)\n\n  Definition complete_AG'_tgt A src tgt := \n    ARSet.Exists (fun rgt => ~ AG.In (Edges.mkEdge src tgt rgt) A) all_rights.\n\n  Theorem Proper_complete_AG'_tgt : Proper (AG.eq ==> Ref.eq ==> Ref.eq ==> iff) complete_AG'_tgt.\n  Proof.\n    unfold Proper; unfold respectful; unfold complete_AG'_tgt; unfold ARSet.Exists; \n      intros; split; intros [z [Hin Hp]];\n        (eapply ex_intro with z; split; try tauto;\n          rewrite H in *; rewrite H0 in *; rewrite H1 in *; tauto).\n  Qed.\n\n  Hint Resolve Proper_complete_AG'_tgt.\n\n  Theorem complete_AG'_tgt_dec: forall A src tgt, {complete_AG'_tgt A src tgt} + {~complete_AG'_tgt A src tgt}.\n  Proof.\n    intros. unfold complete_AG'_tgt.\n    ecase ARSetDep.exists_; intros H; [eapply Sumbool_dec_not; eapply AGProps.In_dec | left | right];\n      (eapply H; clear H;\n    unfold SetoidList.compat_P; unfold Proper; unfold respectful; unfold impl; intros; rewrite H in *; tauto).\n  Qed.\n\n  Hint Resolve  complete_AG'_tgt_dec.\n\n  Definition complete_AG'_src E A src := \n    RefSet.Exists (complete_AG'_tgt A src) E.\n\n  Theorem Proper_complete_AG'_src : Proper (RefSet.eq ==> AG.eq ==> Ref.eq ==> iff) complete_AG'_src.\n  Proof.\n    unfold Proper; unfold respectful; unfold complete_AG'_src; unfold RefSet.Exists;\n      intros; split; intros [z [Hin Hp]];\n        (eapply ex_intro with z; rewrite H in *; split; try tauto;\n          eapply Proper_complete_AG'_tgt; [| | | apply Hp];\n    solve [apply H0|apply AG.eq_sym; apply H0 | apply H1|apply Ref.eq_sym; apply H1 |  apply Ref.eq_refl]).\n  Qed.\n\n  Hint Resolve Proper_complete_AG'_src.\n  \n  Theorem complete_AG'_src_dec: forall E A src, {complete_AG'_src E A src} + {~ complete_AG'_src E A src}.\n  Proof.\n    intros.\n    ecase (RefSetDep.exists_ (complete_AG'_tgt_dec A src)); intros H; [left|right]; apply H; clear H;\n    unfold SetoidList.compat_P; unfold Proper; unfold respectful; unfold impl; intros; rewrite H in *; intuition.\n  Qed.\n\n  Hint Resolve complete_AG'_src_dec.\n      \n  Definition complete_AG' E A :=\n    ~ RefSet.Exists (complete_AG'_src E A) E.\n\n  Theorem Proper_complete_AG': Proper (RefSet.eq ==> AG.eq ==> iff) complete_AG'.\n  Proof.\n    unfold Proper; unfold respectful; unfold complete_AG'; unfold RefSet.Exists;\n      intros; split; intros Hneg [z [Hin Hp]]; apply Hneg; clear Hneg;\n        (eapply ex_intro with z; split; [rewrite H in *; tauto|];\n          eapply Proper_complete_AG'_src; [| | | apply Hp];\n    solve [apply H0 | apply AG.eq_sym; apply H0 | apply H | apply RefSet.eq_sym; apply H | apply Ref.eq_refl]).\n  Qed.\n\n  Hint Resolve Proper_complete_AG'.\n\n  Theorem complete_AG'_dec : forall E A, {complete_AG' E A} + {~ complete_AG' E A}.\n  Proof.\n    intros; unfold complete_AG'.\n    Sumbool_decide; eauto.\n    ecase (RefSetDep.exists_ (complete_AG'_src_dec E A)); intros H; [left|right]; eapply H; clear H;\n    unfold SetoidList.compat_P; unfold Proper; unfold respectful; unfold impl; intros; rewrite H in *; intuition.\n  Qed.\n\n  Hint Resolve complete_AG'_dec.\n\n  Theorem complete_AG_iff': forall E A, Seq.complete_AG E A <-> complete_AG' E A.\n  Proof.\n    intros E A; unfold complete_AG'; unfold complete_AG'_src; unfold complete_AG'_tgt;\n      unfold Seq.complete_AG; unfold RefSet.Exists; unfold ARSet.Exists;\n      split; intros H.\n    intros [src [Hsrc [tgt [Htgt [rgt [Hrgt Hin]]]]]]; apply Hin; clear Hin.\n    apply H; tauto.\n    intros src tgt rgt Hsrc Htgt.\n    rewrite not_exists_iff in H; generalize (H src); clear H; intros H.\n    rewrite Sumbool_not_and in H; Sumbool_decide; auto.\n    destruct H as [H|H]; [contradiction|].\n    rewrite not_exists_iff in H; generalize (H tgt); clear H; intros H.\n    rewrite Sumbool_not_and in H; Sumbool_decide; auto.\n    destruct H as [H|H]; [contradiction|].\n    rewrite not_exists_iff in H; generalize (H rgt); clear H; intros H.\n    rewrite Sumbool_not_and in H; Sumbool_decide; auto; try apply AGProps.In_dec.\n    destruct H as [H|H].\n    contradiction (in_all_rights rgt).\n    apply Sumbool_dec_not_not_iff in H; try apply AGProps.In_dec; auto.\n  Qed.\n\n  Theorem complete_AG_dec : forall E A, {Seq.complete_AG E A} + {~ Seq.complete_AG E A}.\n  Proof.\n    intros.\n    eapply Sumbool_dec_iff_imp; [|apply iff_sym;  apply complete_AG_iff']; eauto.\n  Qed.\n\n\n  Theorem cap_edge_dec : forall tgt rgt cap, {cap_edge tgt rgt cap } + {~ cap_edge tgt rgt cap}.\n  Proof.\n    intros tgt rgt cap.\n    unfold cap_edge; Sumbool_decide; solve [ apply Ref.eq_dec | apply ARSetProps.In_dec].\n  Qed.\n\n  Theorem Proper_cap_edge: Proper (Ref.eq ==> AccessRight.eq ==> Cap.eq ==> iff) cap_edge.\n  Proof.\n    unfold Proper; unfold respectful; unfold cap_edge; intros; split; intros [H'1 H'2];\n      (rewrite H in *; rewrite H0 in *; \n        rewrite (Cap.rights_eq _ _ H1) in *; rewrite (Cap.target_eq _ _ H1) in *;\n          intuition).\n  Qed.\n\n  Theorem Proper_exists_cap_edge : \n    Proper (Ref.eq ==> AccessRight.eq ==> CapSet.eq ==> iff) exists_cap_edge.\n  Proof.\n    unfold Proper; unfold respectful; intros; split; intros H';\n      (destruct H' as [cap [H'1 [H'2 H'3]]]; eapply ex_intro with cap;\n        rewrite H0 in *; rewrite H in *; rewrite H1 in *; unfold cap_edge; intuition).\n  Qed.\n\n\n  Theorem exists_cap_edge_dec : forall tgt rgt C, {exists_cap_edge tgt rgt C} + {~exists_cap_edge tgt rgt C}.\n  Proof.\n    unfold exists_cap_edge; intros tgt rgt C.\n    ecase (CapSetDep.exists_ (cap_edge_dec tgt rgt)); intros H; [left|right]; apply H;\n    (unfold SetoidList.compat_P; unfold Proper; unfold respectful; unfold impl;\n      intros x y Heq Hcapedge;\n        eapply Proper_cap_edge; [ apply Ref.eq_refl | apply AccessRight.eq_refl| | eapply Hcapedge]; eauto).\n  Qed.\n\n  Hint Resolve exists_cap_edge_dec.\n\n  Theorem ag_constructive_fully_authorized : forall I E C A, ag_fully_authorized_spec I E C A -> ag_constructive E A.\n  Proof.\n    intros I E C A H Hnot. \n    destruct Hnot as [edge [Hin [Hsrc Htgt]]].\n    eapply H in Hin; clear H.\n    unfold excluded_edge in *; intuition.\n  Qed.\n\n  Theorem confined_subsystem_outward_edge_ag_simply_confined : \n    forall C E S, Sub.confined_subsystem C E S ->\n      forall D, dirAcc_spec S D ->\n        forall A, ag_fully_authorized_spec D E C A ->\n          forall edge, ag_simply_confined E edge ->\n            ~ AG.In edge A ->\n            AG.In edge D -> \n            RefSet.In (Edges.source edge) E ->\n            ~ RefSet.In (Edges.target edge) E ->\n            False.\n  Proof.\n    intros C E S HsubConf D Hda A Ha edge HsimpConf HinA HinD HsrcIn HtgtIn.\n    destruct HsimpConf as [Hneq Hrgt].\n    do 2 (rewrite Sumbool_not_and in Hrgt; Sumbool_decide; auto; try apply AccessRight.eq_dec;\n      destruct Hrgt as [Hrgt | Hrgt]; [contradiction|]).\n    unfold Sub.confined_subsystem in *.\n    generalize (HsubConf (Edges.source edge) HsrcIn); intros [Hextant [Hauto Hconf]]; clear HsubConf.\n    rewrite Sub.confinement_test_iff' in Hconf; unfold Sub.confinement_test' in *.\n      (* rewrite HinA using Ha and simplify *)\n    erewrite (Ha edge) in HinA; clear Ha.\n    rewrite Sumbool_not_or in HinA; Sumbool_decide; eauto.\n      (* The first clause of HinA is redundant information *)\n    destruct HinA as [_ HinA].\n    rewrite Sumbool_not_or in HinA; Sumbool_decide; eauto.\n      (* The last clause of HinA is not applicable as we are an outward edge *)\n    destruct HinA as [Hauth _].\n      (* simplify Hauth *)\n    rewrite Sumbool_not_and in Hauth; Sumbool_decide; eauto.\n    destruct Hauth as [Hauth | Hauth]; [contradiction|].\n    unfold exists_cap_edge in Hauth; unfold CapSet.Exists in Hauth.\n    rewrite not_exists_iff in Hauth; simpl in *.\n    unfold cap_edge in *.\n    \n      (* destruct dirAcc *)\n    eapply Hda in HinD.\n    destruct_dirAcc HinD s'' HeqS src_ref src lbl srcType srcSched HmapS \n    src' lbl' srcType' srcSched' HeqP Halive ind cap HmapSrc'\n    cap_obj cap_lbl cap_type cap_sched HmapScap cap_obj' cap_lbl' cap_type' cap_sched' \n    HeqPcap HaliveCap rgt HinR HeqEdge.\n    unfold Sub.confinement_pred in *.\n\n    generalize (Hauth cap); clear Hauth; intros Hauth.\n\n      (* at this point, we know (source edge) [=] src_ref /\\\n         (target edge) [=] (target cap) /\\\n         getCap i src_ref S = Some cap /\\\n         rgt [=] (right edge) /\\\n         In rgt (rights cap) /\\\n         right edge) [<>] weak \n\n         instantiating o := src_ref, i := ind, cap := cap,\n         \n         *)\n\n\n      (* Find the tuple for getcap *)\n    generalize (Sys_MapEquiv.exists_mapsTo_eq _ _ (Sys.eq_sym HeqS) _ _ HmapS _ (Ref.eq_refl _));\n      intros [tuple [HtupleEq HtupleMap]].\n    destruct_tuple tuple src2 lbl2 typ2 sch2; simpl in *.\n    destruct_tuple HtupleEq HeqObj2 HeqLbl2 HeqTyp2 HeqSch2.\n    eapply Sys.MapS.find_1 in HtupleMap.\n      (* find the cap for getcap *)\n    destruct_tuple HeqP HeqSrc HeqLbl HeqTyp HeqSch; simpl in *.\n    rewrite HeqSrc in HeqObj2.\n    generalize (Obj_MapEquiv.exists_mapsTo_eq _ _ HeqObj2 _ _ HmapSrc' _ (Ind.eq_refl _));\n      intros [cap' [Hcap'Eq Hcap'Map]].\n    eapply Obj.MapS.find_1 in Hcap'Map.\n\n    apply Hconf.\n    eapply ex_intro with src_ref;\n      eapply ex_intro with ind;\n        eapply ex_intro with cap'.\n\n    split.\n    unfold SC.getCap.\n    unfold SC.getObj.\n    unfold SC.getObjTuple.\n    unfold OC.getCap. \n    rewrite HtupleMap; simpl; rewrite Hcap'Map; simpl; auto.\n\n    generalize (Edges.eq_source _ _ HeqEdge); rewrite Edges.source_rewrite; intros HsrcEdge.\n    generalize (Edges.eq_right _ _ HeqEdge); rewrite Edges.right_rewrite; intros HedgeRgt.\n    generalize (Edges.eq_target _ _ HeqEdge); rewrite Edges.target_rewrite; intros HedgeTgt.\n\n    split; [ auto |].\n    intros Hnot.\n      (* This is cases on Hnot.\n         (rights cap') [=] (singleton weak) /\\ in (target ca') E:\n           we know cap [=] cap' and In rgt (rights cap) making rgt [=] weak.\n           But we have assumed ~ rgt [=] weak.\n         Empty (rights cap'):\n           we know cap [=] cap' and In rgt (rights cap), making this impossible.\n         In (target cap') E:\n           we know (target cap') [=] (target cap) and (target cap) [=] (target edge) and\n           ~ RefSet.In (Edges.target edge) E, making this impossible.\n         In cap' C:\n           cap [=] cap' -> In cap C and\n           rgt [=] (right edge) -> In (right edge) (rights cap) and\n           (target cap') [=] (target cap)\n           solving our 3 requirements. *)\n\n    destruct Hnot as [HcapIn | [HtargetIn | [Hempty | [HisAlive | [HeqRights HinTgt]]]]].\n    apply Hauth.\n    rewrite <- Hcap'Eq in HcapIn.\n    split; [auto| split; [auto|rewrite <- HedgeRgt; auto]].\n    \n    apply HtgtIn; rewrite <- HedgeTgt;\n      rewrite (Cap.target_eq _ _ Hcap'Eq); auto.\n    \n    eapply Hempty; rewrite <- (Cap.rights_eq _ _ Hcap'Eq); apply HinR.\n\n    apply HisAlive.\n    eapply SC.isLabel_eq.\n    eapply Cap.target_eq; eapply Hcap'Eq.\n    eapply ObjectLabel.eq_sym; eapply ObjectLabel.eq_trans;\n      [eapply HaliveCap \n        | destruct_tuple HeqPcap HeqPcapObj HeqPcapLbl HeqPcapTyp HeqPcapSch; simpl in *;\n          eapply ObjectLabel.eq_sym; eapply HeqPcapLbl].\n    eapply Sys.eq_sym; apply HeqS.\n    eapply Sys.MapS.find_1 in HmapScap; \n      unfold SC.is_alive; unfold SC.is_label; unfold SC.getLabel; unfold SC.getObjTuple; \n        rewrite HmapScap; simpl; apply ObjectLabel.eq_refl.\n\n    apply Hrgt.\n    rewrite <- HedgeRgt.\n    rewrite <- (Cap.rights_eq _ _ Hcap'Eq) in HeqRights.\n    rewrite HeqRights in HinR.\n    eapply ARSetFacts.singleton_iff in HinR.\n    rewrite <- HinR.\n    apply AccessRight.eq_refl.\n  Qed.\n\n  Hint Resolve confined_subsystem_outward_edge_ag_simply_confined.\n\n    Theorem constructive_confined_subsystem:\n      forall C E S, Sub.confined_subsystem C E S -> Sub.constructive_subsystem E S.\n    Proof.\n      unfold Sub.confined_subsystem; unfold Sub.constructive_subsystem; unfold RefSet.For_all; intros C E S H x Hin.\n      generalize (H _ Hin); clear H; intros H.\n      intuition.\n    Qed.\n\n    Hint Resolve constructive_confined_subsystem.\n\n    Theorem inner_edge_ag_simply_confined : \n      forall D E C A, ag_fully_authorized_spec D E C A ->\n        forall edge,\n          RefSet.In (Edges.source edge) E ->\n          RefSet.In (Edges.target edge) E ->\n          AG.In edge A.\n    Proof.\n      intros D E C A Ha edge HsrcIn HtgtIn.\n      eapply Ha; clear Ha; intuition.\n    Qed.\n\n    Hint Resolve inner_edge_ag_simply_confined.\n\n  Theorem confined_subsystem_inward_edge_ag_simply_confined : \n    forall C E S, Sub.confined_subsystem C E S ->\n      forall D, dirAcc_spec S D ->\n          forall edge, AG.In edge D ->\n            ~ RefSet.In (Edges.source edge) E ->\n            RefSet.In (Edges.target edge) E ->\n            False.\n  Proof.\n    intros C E S HsubConf D Hda edge HinD HsrcIn HtgtIn.\n    eapply constructive_subsystem_impl_ag in Hda; [|eauto].\n    unfold ag_constructive in *; unfold ag_constructive_P in *.\n    apply Hda; apply ex_intro with edge; intuition.\n  Qed.\n\n  Hint Resolve confined_subsystem_inward_edge_ag_simply_confined.\n\n  Theorem confined_subsystem_outter_edge_ag_simply_confined : \n    forall D E C A, ag_fully_authorized_spec D E C A ->\n      forall edge,  AG.In edge D -> \n        ~ RefSet.In (Edges.source edge) E ->\n        ~ RefSet.In (Edges.target edge) E ->\n        AG.In edge A.\n  Proof.\n    intros D E C A Ha edge HinD Hsrc Htgt.\n    eapply Ha. clear Ha.\n    unfold excluded_edge; intuition.\n  Qed.\n\n  Hint Resolve confined_subsystem_outter_edge_ag_simply_confined.\n\n  Theorem confined_subsystem_impl_ag_subset_simply_confined :\n    forall C E S, Sub.confined_subsystem C E S ->\n    forall D, dirAcc_spec S D ->\n    forall A, ag_fully_authorized_spec D E C A ->\n    subset_eq_ag_simply_confined E A (AG.union D A).\n  Proof.\n    intros C E S HsubConf D Hda A Ha.\n    unfold subset_eq_ag_simply_confined. unfold subset_eq_pred.\n    split.\n    unfold AG.Subset; intros.\n    AGFacts.set_iff; intuition.\n    unfold subset_pred; simpl; intros edge Hconf.\n    AGFacts.set_iff. \n    case (AGProps.In_dec edge A); intros HinA; try solve [intuition].\n    intros [Hin|Hin]; try solve [intuition].\n    (* At this point, we break the proof into 4 cases based on:\n       (In_dec (source edge) E) and (In_dec (target edge) E).\n       Inner   : by Ha being complete.\n       Outward : Main Proof: Confinement test\n       Inward  : A and D are ag_constructive over E, no such edge exists.\n       Outter  : By Ha preserving remainder.\n       *)\n\n    case (RefSetProps.In_dec (Edges.source edge) E); intros Hsrc;\n      (case (RefSetProps.In_dec (Edges.target edge) E); intros Htgt);\n      [eauto | assert False; [eauto | contradiction] | assert False; [eauto | contradiction] | eauto].\n\n  Qed.\n\n  Theorem confined_subsystem_mutable:\n    forall C E S, Sub.confined_subsystem C E S ->\n    forall D, dirAcc_spec S D ->\n    forall A, ag_fully_authorized_spec D E C A ->\n    forall P, Seq.potAcc D P ->\n    forall P', Seq.potAcc A P' ->\n    forall M, mutable_spec P E M ->\n    forall M', mutable_spec P' E M' ->\n    RefSet.Subset M M'.\n  Proof.\n    intros C E S HsubConf D Hda A Ha P Hpa P' Hpa' M Hm M' Hm'.\n    generalize (Seq.exists_potAcc (AG.union D A)); intros [P2 Hpa2].\n    generalize (confined_subsystem_impl_ag_subset_simply_confined _ _ _ HsubConf _ Hda _ Ha); intros HsimpConf.\n    generalize (mutable_spec_mutable P2 E); generalize (mutable P2 E); intros M2 Hm2.\n    generalize (dirAcc_confined _ _ _ HsimpConf _ Hpa' _ Hpa2 _ Hm' _ Hm2); intros Heq2.\n    rewrite Heq2.\n    eapply mutable_spec_subset;\n      [apply RefSetProps.subset_refl | | apply Hm2 |  apply Hm].\n    eapply Seq.potAcc_monotonic;\n      [ | apply Hpa | apply Hpa2].\n    eapply AGProps.union_subset_1.\n  Qed.\n\n  Theorem test : forall (A B C:Prop), {A} + {~A} -> (((A /\\ B) <-> (A /\\ C)) <-> (~ A \\/ (B <-> C))).\n  Proof.\n    intros; destruct H;  tauto.\n  Qed.\n \n  Theorem Sumbool_dec_not_iff_pos : forall A B (HdecA : {A}+{~A}) (HdecB: {B}+{~B}), (A <-> B) -> (~A <-> ~ B).\n  Proof.\n    intros; tauto.\n  Qed.\n\n  Theorem Sumbool_dec_not_iff_neg : forall A B (HdecA : {A}+{~A}) (HdecB: {B}+{~B}), (~A <-> ~B) -> (A <-> B).\n  Proof.\n    intros; tauto.\n  Qed.\n\n  Theorem Sumbool_dec_not_iff_iff : forall A B (HdecA : {A}+{~A}) (HdecB: {B}+{~B}), (A <-> B) <-> (~A <-> ~B).\n  Proof.\n    intros; tauto.\n  Qed.\n\n\n (* \n     Finally, all fully authorized subsystems are mutably equal.\n     The only difference between fully authorized subsystems of shape E are elements of E.\n\n\n\nTheorem mutable_project_in:\nforall p, Seq.maxTransfer p ->\nforall objs, Seq.ag_objs_spec p objs ->\nforall N, RefSet.Subset objs N ->\nforall E, RefSet.Subset E N ->\nforall a, RefSet.In a N ->\nforall o, ~ RefSet.In o N -> \nforall p', AG_project a o p p' ->\nforall m, mutable_spec p E m -> RefSet.In a m ->\nforall m', mutable_spec p' m m' -> \nforall E', RefSetProps.Add o m E' ->\nRefSet.Subset m' E'.\n\nThis definition of mutable_project_in may not be strong enough to prove equality.\nActually, it might.  We know: m' [<=] m + o /\\ m [<=] m' \nThis doesn't ensure that o is in m', only that it might be.\n\n     The goal is to say (fully quantified):\n     ag_objs_spec D N ->\n     N [<=] N' ->\n     ~ Empty E ->\n     E [<=] N' ->\n     ~ Empty E' ->\n     E' [<=] N' ->\n     N - E [=] N - E' ->\n     ag_fully_authorized D E' C A' ->\n     ag_fully_authorized D E C A ->\n     potAcc A P ->\n     potAcc A' P' ->\n     mutable_spec P E M ->\n     mutable_spec P' E' M' ->\n     M - E [=] M' - E'.\n\n     Given these constraints, we can always select N' [=] (union N (union E E')).\n     \n     We will probably need to show :\n     forall D E C A, ag_fully_authorized D E C A -> (ag_objs A) [=] union (ag_objs D) E.\n\n     This is what is really drinving the selection of N' as (union N (union E E').\n\n     This proof probably wants to be in three parts.  Induction from E down to a singleton, singletone\n     substitution, and then induction back to E' from that singleton.  The inductions are the same theorem,\n     instantiated with different instances of Subset.  The singleton swap is proabably different.\n\n     Both Inductions, instantiate E with any singleton:\n     ag_objs_spec D N ->\n     N [<=] N' ->\n     E' [<=] N' ->\n     E [<=] E' ->\n     ~ Empty E ->\n     N - E [=] N - E' ->\n     ag_fully_authorized D E' C A' ->\n     ag_fully_authorized D E C A ->\n     potAcc A P ->\n     potAcc A' P' ->\n     mutable_spec P E M ->\n     mutable_spec P' E' M' ->\n     M - E [=] M' - E'.\n\n     Singleton swap, initial rewrite:\n     ag_objs_spec D N ->\n     N [<=] N' ->\n     In e N' ->\n     In e' N' ->\n     N - (singleton e) [=] N - (singleton e') ->\n     ag_fully_authorized D (singleton e) C A' ->\n     ag_fully_authorized D (singleton e') C A ->\n     potAcc A P ->\n     potAcc A' P' ->\n     mutable_spec P E M ->\n     mutable_spec P' E' M' ->\n     M - (singleton e) [=] M' - (singleton e').\n\n     forall o, In o (N - {e}) <-> In o (N - {e'})\n     forall o, (In o N /\\ ~ In o {e}) <-> (In o N /\\ ~ In o {e'})\n     forall o, (In o N /\\ ~ o [=] e) <-> (In o N /\\ ~ o [=] e')\n     \n     Because (In o N) is decidable in Set, we know the following rewrite holds\n     forall o, ~ In o N \\/ (~ o [=] e <-> ~ o [=] e)\n\n     Singleton swap, final version:\n     ag_objs_spec D N ->\n     N [<=] N' ->\n     In e N' ->\n     In e' N' ->\n     (forall n, ~In n N \\/ (~ n [=] e <-> ~ n [=] e' )) ->\n     ag_fully_authorized D (singleton e) C A' ->\n     ag_fully_authorized D (singleton e') C A ->\n     potAcc A P ->\n     potAcc A' P' ->\n     mutable_spec P E M ->\n     mutable_spec P' E' M' ->\n     forall m, ((In m M /\\ ~ m [=] e) <-> (In m M' /\\ ~ m [=] e'))\n\n     Since all operations are symmetric, we can prove the helper function using -> and apply it twice.\n     We can simplify the final goal as:\n     forall m, In m M -> ~ m [=] e -> In m M' /\\ ~ m [=] e'\n\n     This breaks into two very simple proofs by (Ref.eq_dec e e')\n     If e [=] e', then the proof is solved by reflexivity as all judgments are equivalence preserving.\n\n     If ~ e [=] e, it must be the case that they are also ~ In N.  \n     The only difference in the ag_objs of A and A' is e and e'.\n     Therefore, when ~ m [=] e, we know there must be an edge defining a flow in P.\n     The definition of ag_fully_authorized preserves all objects outside of E.\n     The complete accessgraph of a singleton is covered by reflexivity of trans and may be ignored.\n     This means that the difference between A' and A is a substitution of e for e'.\n     This substituion is preserved by potAcc, and therefore must cause this edge to exist for e'.\n     \n     What we are really after is a notion of substituion for access graphs and proofs\n     that this substitution is preserved for mutability and potAcc.\n     \n     \n\n\n     \n     We do not ensure that we are not projecting into the dead space as it is irrelevant for the problem.\n     We only ensure that we are not expanding into already existing objs.\n\n     The induction for this is over the elements of (E' - E).  \n     For each of these, there is obviously AG_project e e' p p' forming a lineage from P to P'.\n     By mutable_project, or mutable_project_in, these are clearly the same thing.\n\n     The various setoid_* tactics will not operate on dependent instances of respectful_hetero, so there\n     is little reason to attept to craft one by hand.\n\n     *)\n\nTheorem ag_ex_flow_iff_ag_ex_flow' : forall E P o, ag_ex_flow E P o <-> ag_ex_flow' P E o.\nProof.\n  intros E P o.\n  unfold ag_ex_flow; unfold ag_ex_flow'; unfold RefSet.Exists.\n  generalize (mutable_spec_mutable P E); intros Hm;\n  unfold mutable_spec in *; rewrite Hm in *; clear Hm.\n  split; intros H.\n\n  destruct H as [x [HinE Hflow]].\n  eapply ag_flow_iff_ag_flow' in Hflow.\n  unfold ag_flow' in *.\n  intuition eauto;\n    solve [rewrite H in *; auto | right; apply ex_intro with x; intuition].\n\n  destruct H as [H | H].\n  eapply ex_intro.\n  rewrite <- ag_flow_iff_ag_flow'; unfold ag_flow'.\n  split; [apply H|left; apply Ref.eq_refl].\n\n  destruct H as [x [HinE Hedge]].\n  eapply ex_intro. \n  rewrite <- ag_flow_iff_ag_flow'; unfold ag_flow'.\n  split; eauto. \n\nQed.\n\nLtac edge_destruct edge src tgt rgt:=\n  rewrite <- (Edges.edge_rewrite edge) in *;\n  generalize (Edges.source edge) (Edges.target edge) (Edges.right edge); intros src tgt rgt; clear edge;\n  edge_simpl.\n\n\n \n(* This is a more general proof of mutable maximal, which relies heavily on the pointwise notion of ag_flow *)\n\nTheorem mutable_maximal_inclusive :\nforall P', Seq.maxTransfer P' ->\nforall E Me', mutable_spec P' E Me' ->\nforall M, RefSet.Subset E M -> RefSet.Subset M Me' ->\nforall Mm', mutable_spec P' M Mm' ->\n  RefSet.eq Mm' Me'.\nProof.\n  intros P' HP' E Me' HMe' M Hsub1 Hsub2 Mm' HMm'.\n  intros x.\n\n  eapply mutable_spec_eq_mutable in HMe'.\n  eapply mutable_spec_eq_mutable in HMm'.\n\n  rewrite HMe' in *; clear Me' HMe'.\n  rewrite HMm' in *; clear Mm' HMm'.\n\n  (* These are exactly ag_ex_fold', convert to ag_ex_flow *)\n  eapply iff_trans; [eapply iff_sym; apply ag_ex_flow_iff_ag_ex_flow'|].\n  eapply iff_trans; [| apply ag_ex_flow_iff_ag_ex_flow'].\n\n  unfold ag_ex_flow; unfold RefSet.Exists.\n  split; intros [x' [HinX' HflowX']].\n\n  eapply Hsub2 in HinX'.\n  eapply iff_sym in HinX'; [|apply iff_sym; apply ag_ex_flow_iff_ag_ex_flow'].\n  unfold ag_ex_flow in *; unfold RefSet.Exists in *.\n  destruct HinX' as [e [HinE HflowE]].\n\n  eapply ex_intro; split; [apply HinE| eauto].\n\n\n  eapply Hsub1 in HinX'.\n  eapply ex_intro; split; [apply HinX'| eauto].\n\nQed.\n\nImplicit Arguments mutable_maximal_inclusive [P' E Me' M Mm'].\n\n\n(* \n   TODO: Clean this up,\n   eliminate all unnecessary mutable_spec, attempt to reduce complexity and perform backchaining \n   This is a more general version of mutable_project_in_eq, but it falls out as a corrolary.\n   Remember, by mutable_nondec (In a E) -> (In a M) \n\n   This should form the foundaiton for induciton which will allow us to grow a singleton\n   subsystem E in the fully authorized access graph into any arbitrary size via AG_project\n   forming a lineage for all objects in the set.\n\n   If (mutable_spec P E M) and (AG_project a o P P') where \"o is novel\" and (In a M)\n   then (mutable_spec P' (add o E) (add o M)).\n*)\nTheorem mutable_spec_project_add_eq:\nforall P, Seq.maxTransfer P ->\nforall objs, Seq.ag_objs_spec P objs ->\nforall N, RefSet.Subset objs N ->\nforall E, RefSet.Subset E N ->\nforall o, ~ RefSet.In o N ->\nforall M, mutable_spec P E M -> \nforall a, RefSet.In a M ->\nforall P', AG_project a o P P' ->\nforall oE, RefSetProps.Add o E oE ->\nforall MoE', mutable_spec P' oE MoE' ->\nforall oM, RefSetProps.Add o M oM ->\nRefSet.eq oM MoE'.\nProof.\n  intros P Hmax objs Hobjs N Hn E He o Ho M Hm a HinM P' Hproj oE Hoe MoE' Hmoe' oM Hom.\n\n  assert (exists Me', mutable_spec P' E Me') as [Me' Hme'] by\n    (eapply ex_intro; apply mutable_spec_mutable).\n  assert (exists MoM', mutable_spec P' oM MoM') as [MoM' Hmom'] by\n    (eapply ex_intro; apply mutable_spec_mutable).\n  assert (exists Mm', mutable_spec P' M Mm') as [Mm' Hmm'] by\n    (eapply ex_intro; apply mutable_spec_mutable).\n\n  assert (RefSet.In a N) as HinN by\n  (eapply mutable_subset_objs;\n    [apply Hobjs\n      | auto\n      | apply He\n      | apply Hm\n      | apply HinM]).\n  generalize (mutable_project_in_eq Hmax Hobjs Hn He HinN Ho Hproj Hm HinM Hmm' Hom); intros Heq_Mm'_oM.\n  assert (Seq.maxTransfer P') as Hmax' by (eapply AG_project_maximal; eauto).\n  assert (RefSet.Subset E M) as Hsub_E_M by (eapply mutable_nondec; eauto).\n  assert (RefSet.Subset M Me') as Hsub_M_Me'.\n  eapply mutable_spec_subset; \n    [ apply RefSetProps.subset_refl\n      | (* defer for existentials *)\n      | apply Hme'\n      | apply Hm\n    ]; intros edge; edge_destruct edge src tgt rgt;\n        intros HinP; unfold AG_project in *; rewrite Hproj; intuition eauto.\n  generalize (mutable_maximal_inclusive Hmax' Hme' Hsub_E_M Hsub_M_Me' Hmm'); intros Heq_Mm'_Me'.\n  assert (RefSet.Subset M oM) as Hsub_M_oM by (intros o'; rewrite (Hom o'); intuition).\n  assert (RefSet.Subset E oE) as Hsub_E_oE by (intros o'; rewrite (Hoe o'); intuition).\n  assert (RefSet.Subset oE oM) as Hsub_oE_oM by (intros o'; rewrite (Hom o'); rewrite (Hoe o'); intuition).\n  (* because mutable is maximal, we can show MoM [=] Mm' ([=] Me' [=] oM) *)\n  generalize (RefSetProps.subset_equal (RefSet.eq_sym Heq_Mm'_oM)); intros Hsub_oM_Mm'.\n  generalize (mutable_maximal_inclusive Hmax' Hmm' Hsub_M_oM Hsub_oM_Mm' Hmom'); intros Heq_MoM'_Mm'.\n\n(* by mutable_spec_subset, oE [<=] oM -> MoE' [<=] MoM'.\n   by mutable_spec_subset,  e [<=] oE -> Me' [<=] MoE'\n   because Me' [=] MoM', MoE' [=] MoM'\n   because MoM' [=] Mm', qed *)\n\n\n  assert (RefSet.Subset MoE' MoM') as Hsub_MoE'_MoM' by\n    (eapply mutable_spec_subset;\n      [apply Hsub_oE_oM\n        | apply AGProps.subset_refl\n        | apply Hmom'\n        | apply Hmoe'\n    ]).\n  assert (RefSet.Subset Me' MoE') as Hsub_Me'_MoE'.\n  eapply mutable_spec_subset;\n    [ apply Hsub_E_oE\n      | apply AGProps.subset_refl\n      | apply Hmoe'\n      | apply Hme'\n    ].\n\n  assert (RefSet.eq Mm' MoE') as Heq_Mm'_MoE' by\n    (intros o'; split;\n      [rewrite Heq_Mm'_Me'; eapply Hsub_Me'_MoE'\n        | rewrite <- Heq_MoM'_Mm'; eapply Hsub_MoE'_MoM']).\n  \n  rewrite <- Heq_Mm'_MoE'; apply RefSet.eq_sym; auto.\nQed.\n\n\n\n  (* TODO move to sumbool_dec *)\n  Theorem true_bool_of_sumbool_iff_true : forall A (SB:{A}+{~A}),\n    true_bool_of_sumbool SB = true <-> A.\n  Proof.\n    intros; unfold true_bool_of_sumbool.\n    split; [ eapply true_bool_of_sumbool_l | eapply proof_r_true_bool_of_sumbool]; eauto.\n  Qed.\n  Theorem true_bool_of_sumbool_iff_false : forall A (SB:{A}+{~A}),\n    true_bool_of_sumbool SB = false <-> ~ A.\n  Proof.\n    intros; unfold true_bool_of_sumbool.\n    split; [ eapply true_bool_of_sumbool_r | eapply proof_l_true_bool_of_sumbool]; eauto.\n  Qed.\n\nDefinition filtered_subset_eq' E E' N :=\n  forall e, ~ RefSet.In e N \\/ (RefSet.In e N /\\ (RefSet.In e E <-> RefSet.In e E')).\n\nDefinition filtered_subset_eq E E' N :=\n  RefSet.eq \n  (RefSet.filter (fun x => true_bool_of_sumbool (RefSetProps.In_dec x N)) E)\n  (RefSet.filter (fun x => true_bool_of_sumbool (RefSetProps.In_dec x N)) E').\n\nTheorem filtered_subset_eq_iff_filtered_subset_eq' :\n  forall E E' N, filtered_subset_eq E E' N <-> filtered_subset_eq' E E' N.\nProof.\n  unfold filtered_subset_eq; unfold filtered_subset_eq'.\n  intros; split; intros H.\n\n  intros e; generalize (H e); clear H; intros H.\n  do 2 (rewrite RefSetFacts.filter_iff in H;\n    [| unfold SetoidList.compat_bool; unfold Proper; unfold respectful; intros x y Heq; rewrite Heq; auto]).\n  rewrite true_bool_of_sumbool_iff_true in H.\n  case (RefSetProps.In_dec e N); intros Hcase; intuition.\n\n  intros e.\n  do 2 (rewrite RefSetFacts.filter_iff;\n    [| unfold SetoidList.compat_bool; unfold Proper; unfold respectful; intros x y Heq; rewrite Heq; auto]).\n  rewrite true_bool_of_sumbool_iff_true.\n  generalize (H e); clear H; intros H.\n  case (RefSetProps.In_dec e N); intros Hcase; intuition.\n  \nQed.\n\nTheorem filtered_subset_eq_dec : forall E E' N, {filtered_subset_eq E E' N} + {~ filtered_subset_eq E E' N}.\nProof.\n  intros; unfold filtered_subset_eq; eapply RefSet.eq_dec.\nQed.\n\nTheorem filtered_subset_eq'_dec : forall E E' N, {filtered_subset_eq' E E' N} + {~ filtered_subset_eq' E E' N}.\nProof.\n  intros; case (filtered_subset_eq_dec E E' N); intros Hcase;\n    rewrite filtered_subset_eq_iff_filtered_subset_eq' in Hcase; \n      intuition auto.\nQed.\n\nTheorem filtered_subset_eq'_sym: forall E E' N, filtered_subset_eq E E' N <-> filtered_subset_eq E' E N.\nProof.\n  intros E E' N.\n  do 2 rewrite filtered_subset_eq_iff_filtered_subset_eq'.\n  unfold filtered_subset_eq'; split; intros H e; generalize (H e); intuition.\nQed.\n\nTheorem filtered_subset_eq_Empty :\n  forall E, RefSet.Empty E ->\n  forall E' N, filtered_subset_eq E E' N -> \n  RefSet.For_all (fun e' => ~ RefSet.In e' N) E'.\nProof.\n  intros E Hempty E' N Hfilt e HinE.\n  rewrite filtered_subset_eq_iff_filtered_subset_eq' in Hfilt.\n  generalize (Hempty e) (Hfilt e); clear Hempty Hfilt; intros Hempty Hfilt.\n  intuition.\nQed.\n\n(*\n\nFold mutable_spec_project_add_eq over an AG_lineage to produce equality,\n\nConsider rewriting this with hypotheses\nforall N', AG_lineage N P N' P' \nrewriting E' [=] (diff N' N)\n\nThe intersection of N and N' is guaranteed to be disjoint\n\nWe can't prove this with AG_lineage as we can not guarantee all elements in (N' - N) to be in E, \nonly projected from N.\n\nWe will need to prove this directly.\n\n*)\n\n(* Theorem mutable_spec_ag_lineage_union_eq : *)\n(*   forall P, Seq.maxTransfer P -> *)\n(*   forall objs, Seq.ag_objs_spec P objs -> *)\n(*   forall N, RefSet.Subset objs N -> *)\n(*   forall E, RefSet.Subset E N -> *)\n(*     ~ RefSet.Empty E -> *)\n(*   forall M, mutable_spec P E M -> *)\n(*   forall N' P', AG_lineage N P N' P' -> *)\n(*   forall M', mutable_spec P' (RefSet.union E (RefSet.diff N' N)) M' -> *)\n(*     RefSet.eq M' (RefSet.union M E'). *)\n(* Proof. *)\n(*   intros P Hmax objs Hobjs N Hn E HE Hnonempty E' Hdisj P' Hlin M HM M' HM' *)\n(* Qed. *)\n\n\n\n\n\n(* Note: N are the objs we do not wish to extend into *)\n\n\nDefinition insert_spec a o D D' := \n  forall src tgt rgt, AG.In (Edges.mkEdge src tgt rgt) D' <-> \n    (AG.In (Edges.mkEdge src tgt rgt) D \\/\n      Ref.eq src a /\\ Ref.eq tgt o \\/\n      Ref.eq src o /\\ Ref.eq tgt a).\n\nTheorem Proper_insert_spec_impl : Proper (Ref.eq ==> Ref.eq ==> AG.eq ==> AG.eq ==> impl) insert_spec.\nProof.\n  unfold insert_spec; unfold Proper; unfold respectful; unfold impl;\n    intros; generalize (H3 src tgt rgt); clear H3; intros H3;\n      rewrite H in *; rewrite H0 in*; rewrite H1 in *; rewrite H2 in *; trivial.\nQed.\n\nTheorem insert_spec_insert : \n  forall a o D, insert_spec a o D (insert a o D).\nProof.\n  unfold insert_spec; unfold insert.\n  intros a o D src tgt rgt.\n  rewrite ag_add_cap_spec; [| apply AG.eq_refl].\n  rewrite ag_add_cap_spec; [| apply AG.eq_refl].\n  edge_simpl.\n  repeat progress rewrite CC.mkCap_rights.\n  repeat progress rewrite CC.mkCap_target.\n  intuition.\nQed.\n\n\n\nTheorem insert_spec_eq_insert :\n  forall a o D D', insert_spec a o D D' -> AG.eq D' (insert a o D).\nProof.\n  unfold insert_spec.\n  intros a o D D' Hinsert edge.\n  edge_destruct edge src tgt rgt.\n  rewrite Hinsert. clear Hinsert D'.\n  eapply iff_sym.\n  eapply insert_spec_insert.\nQed.\n\nTheorem insert_spec_insert_iff :\n  forall a o D D', insert_spec a o D D' <-> AG.eq D' (insert a o D).\nProof.\n  intros a o D D'.\n  split; intros H.\n  eapply insert_spec_eq_insert; auto.\n  eapply Proper_insert_spec_impl;\n    [apply Ref.eq_refl\n      | apply Ref.eq_refl\n      | apply AG.eq_refl\n      | apply AG.eq_sym; apply H\n      | apply insert_spec_insert\n    ].\nQed.\n\n\n  Theorem ag_fully_authorized_insert_subset :\n    forall D objs, Seq.ag_objs_spec D objs ->\n    forall E C A, ag_fully_authorized_spec D E C A ->\n    forall o, ~ RefSet.In o objs ->\n    forall E', RefSetProps.Add o E E' ->\n    forall A', ag_fully_authorized_spec D E' C A' ->\n    forall a, RefSet.In a E ->\n    forall I, AG.eq I (insert a o A) ->\n      AG.Subset I A'.\n    Proof.\n      intros D objs Hobjs E C A Hauth o Ho E' Hadd A' Hauth' a HinE I HI i.\n      (* pay attention to which theorems you use. *)\n      rewrite HI. clear I HI.\n      edge_destruct i src tgt rgt.\n      intros HinI; eapply insert_spec_insert in HinI.\n      generalize (Hauth' (Edges.mkEdge src tgt rgt)) (Hauth (Edges.mkEdge src tgt rgt)); \n        clear Hauth' Hauth; intros Hauth' Hauth.\n      rewrite Hauth'; clear A' Hauth'.\n      rewrite Hauth in HinI; clear A Hauth.\n      unfold excluded_edge in *.\n      revert HinI; edge_simpl; intros HinI.\n      generalize (Hadd src) (Hadd tgt); intros HaddSrc HaddTgt; clear Hadd.\n      rewrite HaddSrc; rewrite HaddTgt; clear HaddSrc HaddTgt.\n      do 2 (rewrite Sumbool_not_or; Sumbool_decide; try solve [apply Ref.eq_dec| apply RefSetProps.In_dec]).\n      (* Reduce to eq built-in as tactics are much faster *)\n      unfold Ref.eq in *.\n\n      Ltac HinI_solver HinI:=       \n        destruct HinI as [[HinI |[HinI | HinI]] | [HinI | HinI]];\n          let HeqSrc:= fresh \"HeqSrc\" in\n            let HeqTgt := fresh \"HeqTgt\" in\n              solve [ destruct HinI as [HeqSrc HeqTgt]; \n                try rewrite HeqSrc in *; try rewrite HeqTgt in *; intuition \n                | intuition].\n      \n      Ltac HinI_no_edge_solver  src tgt rgt D Ho Hobjs HinI := \n        let Hnot := fresh \"Hnot\" in\n          let HnotIn := fresh \"HnotIn\" in\n      try (assert (~ AG.In (Edges.mkEdge src tgt rgt) D) as HnotIn by \n        (intros Hnot; apply Ho; apply Hobjs;\n          do 2 eapply ex_intro; eauto)); HinI_solver HinI.\n\n\n\n\n      case (RefSetProps.In_dec src E); intros HcaseSrcE;\n        (case (RefSetProps.In_dec tgt E); intros HcaseTgtE);\n        solve [ HinI_no_edge_solver src tgt rgt D Ho Hobjs HinI\n          | case (Ref.eq_dec o src); intros Hsrc; \n            (case (Ref.eq_dec o tgt); intros Htgt);\n            unfold Ref.eq in *;  try rewrite Hsrc in *; try rewrite Htgt in *;\n              HinI_no_edge_solver src tgt rgt D Ho Hobjs HinI].\n    Qed.\n\n    Implicit Arguments ag_fully_authorized_insert_subset [D objs E C A o E' A' a I].\n\n\n(* TODO: Move to Set library *)\n  Theorem diff_empty : forall A B, AG.Empty (AG.diff A B) -> AG.Subset A B.\n  Proof.\n    intros A B H x Hin.\n    unfold AG.Empty in H.\n    generalize (H x); clear H; intros H.\n    rewrite AGFacts.diff_iff in H;\n    rewrite Sumbool_not_and in H; try (Sumbool_decide; eapply AGProps.In_dec).\n    destruct H; [contradiction\n      |rewrite <- Sumbool_dec_not_not_iff in H; try (Sumbool_decide; eapply AGProps.In_dec); auto].\n  Qed.\n\n\nTheorem ag_fully_authorized_insert_def : \n  forall D E C A, ag_fully_authorized_spec D E C A ->\n  forall a o I, insert_spec a o A I ->\n  forall src tgt rgt, \n    (AG.In (Edges.mkEdge src tgt rgt) I <->\n      (RefSet.In src E /\\ RefSet.In tgt E \\/\n        RefSet.In src E /\\ exists_cap_edge tgt rgt C \\/\n        AG.In (Edges.mkEdge src tgt rgt) D /\\ ~ RefSet.In src E /\\ ~ RefSet.In tgt E \\/\n        Ref.eq src a /\\ Ref.eq tgt o \\/\n        Ref.eq src o /\\ Ref.eq tgt a)).\nProof.\n  intros D E C A Hauth a o I HI src' tgt' rgt'.\n  unfold insert_spec in *; unfold ag_fully_authorized_spec in *;\n    unfold excluded_edge in *.\n  generalize (HI src' tgt' rgt'); clear HI; intros HI.\n  generalize (Hauth (Edges.mkEdge src' tgt' rgt')); clear Hauth; intros Hauth.\n  edge_simpl.\n  rewrite Hauth in HI; clear Hauth.\n  intuition.\nQed.\n\nImplicit Arguments ag_fully_authorized_insert_def [D E C A a o I].\n\n(* \n\n   This theorem is proved by induction over (AG.diff A' I). \n\n   This theorem will rely on sufficient conditions to cause (AG.Subset (insert a o A) A'),\n   most likely from ag_fully_authorized_insert_subset.\n\n*)\n\nTheorem ag_fully_authorized_over_insert:\nforall D E C A, ag_fully_authorized_spec D E C A ->\nforall o E', RefSetProps.Add o E E' ->\nforall A', ag_fully_authorized_spec D E' C A' ->\nforall a, RefSet.In a E -> AG.Subset (insert a o A) A' ->\n  Seq.potTransfer (insert a o A) A'.\nProof.\n  intros D E C A Hauth o E' Hadd A' Hauth' a HinE HIsubA'.\n\n  eapply Seq.potTransfer_eq.\n  eapply AGProps.union_subset_equal.\n  assert (forall S S', AG.Subset (AG.diff S S) S') as Hdiff by\n    (intros S S' x; AGFacts.set_iff; intros; intuition);\n    apply (Hdiff (AG.diff A' (insert a o A))).\n  apply AG.eq_refl.\n\n  generalize (@AGProps.subset_refl (AG.diff A' (insert a o A))).\n\neapply AGProps.set_induction with (P:= \n(fun S => AG.Subset S (AG.diff A' (insert a o A)) ->\n     Seq.potTransfer (AG.union (AG.diff (AG.diff A' (insert a o A)) S) (insert a o A)) A')).\n\n\n\n(* base *)\n\nintros S Hempty Hsub.\n(* This is simply that A' [=] A' *)\n(* (AG.union (AG.diff (AG.diff A' (insert a o A)) S) (insert a o A)) *)\n(* [=] (AG.union (AG.diff (AG.diff A' (insert a o A)) AG.empty) (insert a o A)) *)\n(* [=] (AG.union (AG.diff A' (insert a o A))) (insert a o A)) *)\n(* [=] A' *)\n\neapply Seq.potTransfer_eq;\n[apply AG.eq_refl\n| \n| apply Seq.potTransfer_base; apply AG.eq_refl].\n\nrewrite (AGProps.empty_diff_2 _ Hempty).\nassert (forall s s', AG.Subset s s' -> AG.eq (AG.union (AG.diff s' s) s) s') as Hdiffeq.\nintros s s' Hsub'; eapply AG.eq_sym.\neapply AG.eq_trans; [ eapply AG.eq_sym; apply AGProps.diff_inter_all | ].\nrewrite AGProps.inter_sym;\n  rewrite AGProps.inter_subset_equal; [|apply Hsub'];\n      apply AG.eq_refl.\nrewrite Hdiffeq; eauto.\n\n\n(*step*)\nintros S S' IH edge Hedge HS' HsubS'.\n(* \n   * S [<=] S' by AGProps.Add\n   * AG.Subset S (AG.diff A' (insert a o A)) by AGProps.subset_trans with S'\n   * Seq.potTransfer\n         (AG.union (AG.diff (AG.diff A' (insert a o A)) S) (insert a o A)) A'\n   * In x A' /\\ ~ In x (insert a o A) by diff and A'.\n   * By adding this element to A', we know that it is no longer in\n       (AG.diff (AG.diff A' (insert a o A)) S')\n   * To prove the goal:\n        Seq.potTransfer\n             (AG.union (AG.diff (AG.diff A' (insert a o A)) S') (insert a o A)) \n             A'\n     We must show:\n        Seq.potTransfer\n             (AG.union (AG.diff (AG.diff A' (insert a o A)) S') (insert a o A))\n             (AG.union (AG.diff (AG.diff A' (insert a o A)) S) (insert a o A))\n   * The difference of these is only x.\n   * Because potTransfer respects add_commutative functions, we can model this as:\n        Seq.potTransfer\n             (insert a o A)\n             (AG.add x (insert a o A))\n   * Every edge in A' can be resolved using a single transitive step, so we use trans.\n        Seq.transfer\n             (insert a o A)\n             (AG.add x (insert a o A))\n   * We can perform this by case analysis on the conditions of ag_fully_authorized_spec in A' and  insert_spec.\n   * keep in mind that ~ In x (insert a o A), which is critical for eliminating most nonsensical cases of x.\n*)\n\n\n(*\n   \n   reduce AGProps.Add edge S S' and AG.Subset S' (AG.diff A' (insert a o A)) into parts:\n\n   AG.In edge (AG.diff A' (insert a o A)) /\\\n   AG.Subset S (AG.diff A' (insert a o A))\n\n   as they will be needed in the future.\n*)\n\ngeneralize HsubS'; intros HsubS;\n  eapply AGProps.subset_trans in HsubS;\n    [| eapply AGAddEq.Add_Subset; apply HS'].\nassert (AG.In edge (AG.diff A' (insert a o A))) as HinEdge by\n  (eapply HsubS'; eapply HS'; auto).\n\n(*\n   Rewrite S' as (AG.add edge S) and clear S'.\n*)\ngeneralize (AGAddEq.Add_add edge S S'); intros [Hrw _].\neapply Seq.potTransfer_eq;\n  [ rewrite <- (Hrw HS'); apply AG.eq_refl\n    | apply AG.eq_refl\n    |rewrite <- (Hrw HS') in *; clear S' HS' Hrw HsubS'].\n\n(* \n   start by reducing the problem to :\n        Seq.potTransfer\n             (AG.union (AG.diff (AG.diff A' (insert a o A)) S') (insert a o A))\n             (AG.union (AG.diff (AG.diff A' (insert a o A)) S) (insert a o A)) \n\n*)\n\neapply Seq.potTransfer_transitive; [| apply IH; auto].\nclear IH.\n\nassert (forall x' s s' s2, \n  AG.In x' s2 ->\n  ~ AG.In x' s ->\n  AGProps.Add x' s s' -> \n  AG.eq (AG.diff s2 s) (AG.add x' (AG.diff s2 s'))) as Hunion_diff_add.\nintros x' s s' s2 s3 H0 H1;\nintros y'; generalize (H1 y'); clear H1; intros H1;\nAGFacts.set_iff;\nrewrite H1; clear H1;\ngeneralize (Edge.eq_dec x' y'); intros [Hcase|Hcase];\nintuition auto; try solve [rewrite <- Hcase in *; auto].\n(*\n   Use Hunion_diff_add to move edge to the outside.\n   Also use AGProps.union_sym to swap the union order for the next step.\n*)\n\neapply Seq.potTransfer_eq;\n  [ eapply AG.eq_sym; apply AGProps.union_sym\n    | \n    | ].\neapply AG.eq_sym; \nrewrite (Hunion_diff_add edge); try solve[auto].\nrewrite AGProps.union_add; rewrite AGProps.union_sym; rewrite <- AGProps.union_add; eapply AG.eq_refl.\nclear Hunion_diff_add.\n\n(* Use potTransfer_commute_monotonic to eliminate the common union and reduce to only the (insert a o A) condition *)\neapply Seq.potTransfer_commute_monotonic with (Fa:=(fun s => AG.union s _)); try solve [eapply union_diff_fn_req].\n\n(* eliminate S *)\nclear S Hedge HsubS.\n\n(* destruct edge *)\nrevert HinEdge; AGFacts.set_iff.\nedge_destruct edge src tgt rgt.\nintros [HedgeA' HedgeInsert].\n\n(* simplify the properties of HedgeA' and eliminate Hauth' and A' *)\neapply Hauth' in HedgeA'; edge_simpl; clear A' Hauth' HIsubA'.\n\n(* simplify the properties of HedgeInsert and eliminate insert over edge *)\nrevert HedgeInsert.\ngeneralize (insert_spec_insert a o A).\ngeneralize (insert a o A).\nintros I HI HedgeI.\n\n(* At this point, begin eliminating A and Hauth *)\ngeneralize (ag_fully_authorized_insert_def Hauth HI); clear HI; intros HI.\nclear A Hauth.\n\nrewrite Sumbool_dec_not_iff_pos in HedgeI;\n  [ \n    | eapply AGProps.In_dec\n    | \n    | eapply HI].\n(* We can't branch again, and we rely on the fourth goal to solve our existentials. \nSolve goal 2 manually now *)\n2: solve [Sumbool_decide; \n  try solve \n    [apply AGProps.In_dec \n      | apply Ref.eq_dec\n      | apply RefSetProps.In_dec \n      | apply exists_cap_edge_dec \n      | apply excluded_edge_dec]].\nrepeat progress (rewrite Sumbool_not_or in HedgeI; Sumbool_decide;\n try solve \n    [apply AGProps.In_dec \n      | apply Ref.eq_dec\n      | apply RefSetProps.In_dec \n      | apply exists_cap_edge_dec \n      | apply excluded_edge_dec]).\nrepeat progress (rewrite Sumbool_not_and in HedgeI; Sumbool_decide; \n  try solve [apply Ref.eq_dec | apply RefSetProps.In_dec | apply exists_cap_edge_dec | apply AGProps.In_dec]).\nrepeat progress (rewrite <- Sumbool_dec_not_not_iff in HedgeI; try solve [apply RefSetProps.In_dec]).\ndestruct HedgeI as [HreflE [HoutE [HremE [HinterA HinterO]]]].\nunfold excluded_edge in *; edge_simpl.\n\n(* reduce to trans *)\n\neapply Seq.potTransfer_trans; [apply Seq.potTransfer_base; apply AG.eq_refl|].\n\n(* \n   The 3 cases of HedgeA' give us the definitional cases of exclusion we are looking for.\n   \n   The first case examines an internal edge that isn't already an internal edge of E\n   Since the subsystem is fully connected, we can use send between a and o to recover any other permission.\n\n   The second case examines an authorized edge that wasn't authorized in E.\n   Clearly src [=] o, and we can read any such edge from the parent.\n   \n   The last case examines all remainder edges in D that have source and target not in E'.\n   This is impossible.  If the src and tgt are not in E', they are also not in E by subset properties.\n   This contradicts 2 of the 3 cases of HremE, the remaining case claims that the edge was not in D.\n   However, we also assumed that the edge was in D, so this third case is completely contradictory.\n   \n   *)\n\ndestruct HedgeA' as [HreflE' | [HoutE' | HremE']].\n\n(* Case: fully connected edges in E' *)\ndestruct HreflE' as [HinSrcE' HinTgtE'].\neapply Hadd in HinSrcE'; eapply Hadd in HinTgtE'.\n(* This is by case analysis on which elements are in E *)\ncase (RefSetProps.In_dec src E); intros HinSrcE;\n  (case (RefSetProps.In_dec tgt E); intros HinTgtE);\n  try solve [intuition].\n(* Sub-Case:   In src E  /\\ ~ In tgt E  -> o = tgt *) \ndestruct HinTgtE' as [HinTgtE' | HinTgtE']; try contradiction; rewrite HinTgtE' in *; clear HinTgtE'.\neapply Seq.transfer_send.\n3: eapply AGProps.Add_add.\neapply (HI a); intuition.\neapply HI; intuition.\n(* Sub-Case: ~ In src E  /\\   In tgt E  *) \ndestruct HinSrcE' as [HinSrcE' | HinSrcE']; try contradiction; rewrite HinSrcE' in *; clear HinSrcE'.\neapply Seq.transfer_send.\n3: eapply AGProps.Add_add.\neapply (HI a); intuition.\neapply HI; intuition.\n(* Sub-Case: ~ In src E  /\\ ~ In tgt E  *) \ndestruct HinSrcE' as [HinSrcE' | HinSrcE']; try contradiction; rewrite HinSrcE' in *; clear HinSrcE'.\ndestruct HinTgtE' as [HinTgtE' | HinTgtE']; try contradiction; rewrite HinTgtE' in *; clear HinTgtE'.\neapply Seq.transfer_self_tgt.\n2: eapply AGProps.Add_add.\neapply (HI a _ tx); intuition.\n\n(* Case: authorized edges in E' *)\ndestruct HoutE' as [HinSrcE' HcapEdgeE'].\neapply Hadd in HinSrcE'.\n(* This is by case analysis on which elements are in E *)\ncase (RefSetProps.In_dec src E); intros HinSrcE; try solve [intuition].\ndestruct HinSrcE' as [HinSrcE' | HinSrcE']; try contradiction; rewrite HinSrcE' in *; clear HinSrcE'.\neapply Seq.transfer_send.\n3: eapply AGProps.Add_add.\neapply (HI a); intuition.\neapply HI; intuition.\n\n(* Case: remainder edges in E', impossible *)\ndestruct HremE' as [HinD [HinSrcE' HinTgtE']].\n\neapply RefSetAddEq.Add_Subset in Hadd.\ndestruct HremE as [HninD | [Hin | Hin]]; try apply Hadd in Hin; contradiction.\n\nQed.\n\nImplicit Arguments ag_fully_authorized_over_insert [D E C A o E' A' a].\n\nTheorem ag_fully_authorized_insert_project:\nforall D E C A, ag_fully_authorized_spec D E C A ->\nforall o E', RefSetProps.Add o E E' ->\nforall A', ag_fully_authorized_spec D E' C A' ->\nforall a, RefSet.In a E -> AG.Subset (insert a o A) A' ->\nforall P, Seq.potAcc A P ->\nforall N, Seq.ag_objs_spec P N -> ~ RefSet.In o N ->\nforall P', Seq.potAcc A' P' ->\n  AG_project a o P P'.\nProof.\n  intros D E C A HA o E' HE' A' HA' a Ha HIsubA' P HP N HN HOinN P' HP'.\n\n  generalize (ag_fully_authorized_over_insert HA HE' HA' Ha HIsubA'); intros HinsertTrans.\n  generalize HP'; intros [Htrans' Hmax'].\n  generalize (Seq.potTransfer_transitive HinsertTrans Htrans'); intros HinsertPotTransfer.\n  (* we need to prove that potTransfer A P -> potTransfer (insert a o A) (insert a o P) \n     I'm certain this is hiding somewhere in the commutativity laws.\n     Once we know that, we can show potAcc (insert a o P) P' *)\n  assert (Seq.potTransfer (insert a o A) (insert a o P)).\n\n  unfold insert.\n  do 2 (eapply Seq.potTransfer_commute_monotonic;\n    [ split; [eauto\n      | split; \n        [unfold ag_nondecr; eapply ag_add_cap_nondecr\n          |unfold Seq.ag_equiv; intros; eapply ag_add_cap_equiv; eauto; try apply Ref.eq_refl]] | ]);\n  apply HP.\n\n\n  generalize (Seq.exists_potAcc (insert a o P)); intros [P'2 HP'2].\n  eapply Seq.potAcc_potTransfer in H; [| apply HP'2].\n  eapply Seq.potAcc_potTransfer in HinsertTrans; [| apply HP'].\n  eapply potAcc_equiv in HinsertTrans; \n    [ \n      | apply AG.eq_refl\n      | apply H];\n    eapply AG_project_endow;\n      [apply HP\n        | apply HN\n        | apply HOinN\n        | apply AG.eq_refl\n        | eapply potAcc_eq_iff;\n          [apply HP'2 | apply AG.eq_refl | apply HinsertTrans]].\nQed.\n\nImplicit Arguments ag_fully_authorized_insert_project [D E C A o E' A' a P N P'].\n\n\n\n(* \n   At this point, please take note:\n   The objs of D and the objs of A are not necessarily related.\n\n   D may admit objs not in A because of outward weak edges to unestablished objs.\n   A may admit objs not in D because of novel elements of E or C.\n\n   For this proof to succeed, o must be novel to both D and A.\n*)\n\n\nTheorem ag_fully_authorized_project :\n  forall D E C A, ag_fully_authorized_spec D E C A ->\n  forall objs, Seq.ag_objs_spec D objs ->\n  forall objs', Seq.ag_objs_spec A objs' ->\n  forall a, RefSet.In a E ->\n  forall o, ~ RefSet.In o objs -> ~ RefSet.In o objs' ->\n  forall E', RefSetProps.Add o E E' ->\n  forall A', ag_fully_authorized_spec D E' C A' ->\n  forall P, Seq.potAcc A P ->\n  forall P', Seq.potAcc A' P' ->\n    AG_project a o P P'.\nProof.\n  intros D E C A Hauth objs Hobjs objs' Hobjs' a Ha o HoInNodes HoInNodes' E' HE' A' Hauth' P Hpa P' Hpa'.\n  \n  eapply ag_fully_authorized_insert_project.\n  apply Hauth.\n  apply HE'.\n  apply Hauth'.\n  apply Ha.\n  \n  eapply ag_fully_authorized_insert_subset;\n    [apply Hobjs\n      | apply Hauth\n      | apply HoInNodes\n      | apply HE'\n      | apply Hauth'\n      | apply Ha\n      | apply AG.eq_refl].\n\n  apply Hpa.\n  eapply ag_objs_spec_potTransfer;\n    [apply Hobjs' | apply Hpa].\n  apply HoInNodes'.\n  apply Hpa'.\nQed.\n\nImplicit Arguments ag_fully_authorized_project [D E C A objs objs' a o E' A' P P'].\n\n(* TODO: Move to FSetAddEq or another set library *)\n\n  Theorem RefSetAddEq_nonempty_exists : forall E, ~ RefSet.Empty E <-> exists a, RefSet.In a E.\n  Proof.\n    intros E; split; intros H.\n\n    unfold RefSet.Empty in *.\n\n    rewrite <- Sumbool_dec_exists_not_iff in H; simpl in *.\n    eauto.\n    clear H.\n\n    assert (forall A, SetoidList.compat_P (@eq A) (fun _ => True)) as HP by\n      (intros A; unfold SetoidList.compat_P; unfold Proper; unfold respectful; unfold impl; intros; auto).\n    assert (forall A, let P := (fun (a:A) => True) in forall (a:A), {P a} + {~ P a}) as Hdec by\n      (intros A P a; unfold P; intuition).\n\n    ecase (RefSetDep.exists_ (Hdec Ref.t) E);\n    try solve [tauto]; intros H'; eapply H' in HP; clear H'; unfold RefSet.Exists in *.\n    \n    left; destruct HP as [x [HP _]]; eauto.\n    right; intros Hnot; eapply HP; destruct Hnot as [x Hnot]; eauto.\n\n\n    destruct H as [a H]; unfold RefSet.Empty; intros Hnot; eapply Hnot; eauto.\n  Qed.\n\n  Theorem ARSetAddEq_nonempty_exists : forall E, ~ ARSet.Empty E <-> exists a, ARSet.In a E.\n  Proof.\n    intros E; split; intros H.\n\n    unfold ARSet.Empty in *.\n\n    rewrite <- Sumbool_dec_exists_not_iff in H; simpl in *.\n    eauto.\n    clear H.\n\n    assert (forall A, SetoidList.compat_P (@eq A) (fun _ => True)) as HP by\n      (intros A; unfold SetoidList.compat_P; unfold Proper; unfold respectful; unfold impl; intros; auto).\n    assert (forall A, let P := (fun (a:A) => True) in forall (a:A), {P a} + {~ P a}) as Hdec by\n      (intros A P a; unfold P; intuition).\n\n    ecase (ARSetDep.exists_ (Hdec AccessRight.t) E);\n    try solve [tauto]; intros H'; eapply H' in HP; clear H'; unfold ARSet.Exists in *.\n    \n    left; destruct HP as [x [HP _]]; eauto.\n    right; intros Hnot; eapply HP; destruct Hnot as [x Hnot]; eauto.\n\n\n    destruct H as [a H]; unfold ARSet.Empty; intros Hnot; eapply Hnot; eauto.\n  Qed.\n\n(* If we have a projection from any element of E, then by mutable_spec_project_eq, the resulting\n   mutability must be increased by exactly o . *)\n  Theorem ag_fully_authorized_add_mutable_eq :\n    forall D objs, Seq.ag_objs_spec D objs ->\n    forall N, RefSet.Subset objs N ->\n    forall E, RefSet.Subset E N ->\n      ~ RefSet.Empty E ->\n    forall o, ~ RefSet.In o N ->\n    forall E', RefSetProps.Add o E E' ->\n    forall C A, ag_fully_authorized_spec D E C A ->\n    forall objs', Seq.ag_objs_spec A objs' ->\n      RefSet.Subset objs' N ->\n    forall A', ag_fully_authorized_spec D E' C A' ->\n    forall P, Seq.potAcc A P ->\n    forall P', Seq.potAcc A' P' ->\n    forall M, mutable_spec P E M ->\n    forall M', mutable_spec P' E' M' ->\n    forall oM, RefSetProps.Add o M oM ->\n      RefSet.eq M' oM.\nProof.\n  intros D objs Hobjs N HN E HE Hnonempty o Ho E' HaddE C A Hauth \n    objs' Hobjs' HN' A' Hauth' P HP P' HP' M HM M' HM' om HaddM.\n\n  (* first, find a in E *)\n  eapply RefSetAddEq_nonempty_exists in Hnonempty.\n  destruct Hnonempty as [a Ha].\n\n  eapply RefSet.eq_sym.\n  eapply mutable_spec_project_add_eq;\n    [ apply Seq.maxTransfer_maxPotTransfer; apply HP\n      | eapply ag_objs_spec_potTransfer; [apply Hobjs' | apply HP]\n      | apply HN'\n      | apply HE\n      | apply Ho\n      | apply HM\n      |   eapply mutable_nondec; [apply HM | apply Ha]\n      | \n      | apply HaddE\n      | apply HM'\n      | apply HaddM].\n  \n  (* at this point, we must show the projection *)\n  eapply ag_fully_authorized_project;\n    [apply Hauth\n      | apply Hobjs\n      | apply Hobjs'\n      | apply Ha\n      | intros Hnot; apply HN in Hnot; contradiction\n      | intros Hnot; apply HN' in Hnot; contradiction\n      | apply HaddE\n      | apply Hauth'\n      | apply HP\n      | apply HP'].\nQed.\n\nImplicit Arguments ag_fully_authorized_add_mutable_eq [D objs N E o E' C A objs' A' P P' M M' oM].\n\n\nDefinition capset_targets C T := forall t, RefSet.In t T <->\n  CapSet.Exists (fun cap => ~ ARSet.Empty (Cap.rights cap) /\\ (Ref.eq (Cap.target cap) t)) C.\n\nTheorem capset_targets_eq : forall C C', \n  CapSet.eq C C' -> \n  forall T, capset_targets C T ->\n  forall T', capset_targets C' T' ->\n  RefSet.eq T T'.\nProof.\n  intros C C' Heq T HT T' HT' x.\n  rewrite (HT x); rewrite (HT' x); clear T T' HT HT'.\n  unfold CapSet.Exists.\n  split; (intros [cap [Hin HeqT]];\n  eapply ex_intro; intuition eauto;\n  eapply Heq; eauto).\nQed.\n\nDefinition capset_targets_f C := CapSet.fold (fun cap acc => \n  if ARSet.is_empty (Cap.rights cap) \n    then acc\n    else (RefSet.add (Cap.target cap) acc)\n) C RefSet.empty.\n\nTheorem capset_targets_iff_f : forall C, capset_targets C (capset_targets_f C).\nProof.\n  intros C x. unfold capset_targets_f; unfold CapSet.Exists.\n  eapply CapSetProps.fold_rec.\n  (* base *)\n  intros C1 Hempty.\n  split; intros H;\n    [eapply RefSetFacts.empty_iff in H; contradiction\n      | destruct H as [x' [H _]]; eapply Hempty in H; contradiction].\n  (* step *)\n  intros cap R C1 C2 HinC HninC1 Hadd IH.\n  split; intros H.\n  revert H.\n  generalize (ARSetFacts.is_empty_iff (Cap.rights cap)).\n  case (ARSet.is_empty (Cap.rights cap)); intros Hempty H.\n\n  eapply IH in H; destruct H as [cap' H]; apply ex_intro with cap';\n    unfold CapSetProps.Add in Hadd; rewrite Hadd; intuition.\n  \n  assert (~ARSet.Empty (Cap.rights cap)) as Hempty' by\n    (intros Hnot; eapply Hempty in Hnot; discriminate Hnot).\n\n  case (Ref.eq_dec (Cap.target cap) x); intros Heq.\n  eapply ex_intro with cap; unfold CapSetProps.Add in Hadd; rewrite Hadd; intuition.\n\n  eapply RefSetProps.Add_add in H; destruct H as [H|H]; try contradiction.\n  eapply IH in H; destruct H as [cap' H]; apply ex_intro with cap';\n    unfold CapSetProps.Add in Hadd; rewrite Hadd; intuition.\n\n  (* other side *)\n\n  destruct H as [cap' [Hcap' [Hnonempty HeqTgt]]].\n\n  case (Cap.eq_dec cap cap'); intros HeqCap.\n  generalize (ARSetFacts.is_empty_iff (Cap.rights cap)).\n\n  case (ARSet.is_empty (Cap.rights cap)); intros Hempty.\n  rewrite Cap.rights_eq in Hnonempty; [ | apply Cap.eq_sym; apply HeqCap].\n  rewrite Hempty in Hnonempty; contradict Hnonempty; tauto.\n\n  eapply RefSetProps.Add_add; left; rewrite <- HeqTgt; eapply Cap.target_eq; auto.\n  \n\n  generalize (ARSetFacts.is_empty_iff (Cap.rights cap)).\n  case (ARSet.is_empty (Cap.rights cap)); intros Hempty.\n\n  eapply IH. eapply ex_intro with cap'. split; [ |intuition eauto].\n  eapply Hadd in Hcap'; destruct Hcap' as [Hcap' | Hcap']; eauto; contradiction.\n\n  assert (~ARSet.Empty (Cap.rights cap)) as Hempty' by\n    (intros Hnot; eapply Hempty in Hnot; discriminate Hnot).\n\n  eapply RefSetProps.Add_add.\n  case (Ref.eq_dec (Cap.target cap) x); intros Heq; try solve [intuition].\n  right; eapply IH.\n  apply ex_intro with cap'.\n  apply Hadd in Hcap'; intuition.\nQed.\n\nTheorem Proper_capset_targets: Proper (CapSet.eq ==> RefSet.eq ==> impl) capset_targets.\nProof.\n  unfold Proper; unfold respectful; unfold impl.\n  intros C C' HeqC T T' HeqT HCT x.\n  generalize (HCT x); clear HCT.\n  rewrite HeqT.\n  intros H; rewrite H; clear H.\n  unfold CapSet.Exists.\n  split; (intros [cap [Hin Heq]];\n  eapply ex_intro; intuition eauto;\n  eapply HeqC; eauto).\nQed.\n\n(* All of this, and capset_targets* need to move to SubsystemImpl.v *)\n\nDefinition novel_capabilities_obj C e := ~ CapSet.Exists (fun cap => Ref.eq (Cap.target cap) e) C.\n\nTheorem Proper_novel_capabilities_obj_impl: \n  Proper (CapSet.eq ==> Ref.eq ==> impl) novel_capabilities_obj.\nProof.\n  unfold Proper; unfold respectful; unfold impl; unfold novel_capabilities_obj; unfold CapSet.Exists; intros.\n  intros [cap [Hin Heq]]; apply H1; eapply ex_intro.\n  rewrite H in *; rewrite H0 in *; eauto.\nQed.\n\nHint Rewrite Proper_novel_capabilities_obj_impl.\n\nTheorem Proper_novel_capabilities_obj_iff: \n  Proper (CapSet.eq ==> Ref.eq ==> iff) novel_capabilities_obj.\nProof.\n  split; eapply Proper_novel_capabilities_obj_impl; eauto.\n  apply CapSet.eq_sym; auto.\n  apply Ref.eq_sym; auto.\nQed.\n\nHint Rewrite Proper_novel_capabilities_obj_iff.\n\nTheorem novel_capabilities_obj_dec : forall C e, {novel_capabilities_obj C e} + {~novel_capabilities_obj C e}.\nProof.\n  intros C e; unfold novel_capabilities_obj.\n  Sumbool_decide.\n  ecase (CapSetDep.exists_); \n  [|intros H; left; eapply H |intros H; right; eapply H];\n  [intros cap; case (Ref.eq_dec (Cap.target cap) e); intros Hcap; [left|right]; apply Hcap| | ];\n  (unfold SetoidList.compat_P; unfold Proper; unfold respectful; unfold impl;\n    intros; rewrite <- H1; apply Cap.target_eq; apply Cap.eq_sym; auto).\nQed.\n\nHint Rewrite novel_capabilities_obj_dec.\n\n  Definition novel_capabilities C E := \n    RefSet.For_all (novel_capabilities_obj C) E.\n\nTheorem Proper_novel_capabilities_impl : Proper (CapSet.eq ==> RefSet.eq ==> impl) novel_capabilities.\nProof.\n  unfold Proper; unfold respectful; unfold impl; unfold novel_capabilities; unfold RefSet.For_all; intros.\n  rewrite <- H0 in *. apply H1 in H2. \n  eapply Proper_novel_capabilities_obj_impl; eauto; try apply Ref.eq_refl.\nQed.\n\nHint Rewrite Proper_novel_capabilities_impl.\n\nTheorem Proper_novel_capabilities_iff: \n  Proper (CapSet.eq ==> RefSet.eq ==> iff) novel_capabilities.\nProof.\n  split; eapply Proper_novel_capabilities_impl; eauto.\n  apply CapSet.eq_sym; auto.\n  apply RefSet.eq_sym; auto.\nQed.\n\nHint Rewrite Proper_novel_capabilities_obj_iff.\n\n  Theorem novel_capabilities_dec: forall C E, {novel_capabilities C E} + {~ novel_capabilities C E}.\n  Proof.\n    intros C E; unfold novel_capabilities.\n    ecase (RefSetDep.for_all (novel_capabilities_obj_dec C)); intros H ; [left|right]; eapply H;\n    unfold SetoidList.compat_P; unfold Proper; unfold respectful; unfold impl;\n      intros x y Heq; rewrite Heq in *; eauto.\n  Qed.\n\nDefinition extant_capabilities C S := Sub.extant_subsystem (capset_targets_f C) S.\n\nDefinition authorized_confined_subsystem C E S := \n  novel_capabilities C E /\\ extant_capabilities C S /\\ Sub.confined_subsystem C E S.\n\n  Theorem novel_capabilities_inter_empty': \n    forall C E, novel_capabilities C E ->\n    forall T, capset_targets C T ->\n    forall x, RefSet.In x T -> ~ RefSet.In x E.\n  Proof.\n    intros C E HauthSet T HT x Hin Hnot.\n    unfold capset_targets in *; rewrite HT in Hin; clear HT.\n    eapply HauthSet; eauto.\n    destruct Hin as [cap [Hin [Hnonempty Heq]]].\n    eapply ex_intro; eauto.\n  Qed.\n\n  Theorem novel_capabilities_inter_empty: \n    forall C E, novel_capabilities C E ->\n    forall T, capset_targets C T ->\n      RefSet.Empty (RefSet.inter E T).\n  Proof.\n    intros C E HauthSet T HT x.\n    RefSetFacts.set_iff.\n    intros [HinE HinT].\n    eapply novel_capabilities_inter_empty' in HauthSet; \n      [ | eauto 1 | eauto 1 ].\n    apply HauthSet; auto.\n  Qed.\n\n\n  Theorem ag_remainder_inter_refl :\n    forall D objs, Seq.ag_objs_spec D objs ->\n    forall E, RefSet.Empty (RefSet.inter E objs) ->\n    forall R, ag_remainder_spec D E R ->\n      AG.eq D R.\n  Proof.\n    intros D objs Hobjs E HE R HR x.\n    rewrite (HR x); clear R HR.\n    intuition.\n    eapply Seq.ag_objs_spec_AG_all_objs in Hobjs.\n    revert H.\n    edge_destruct x src tgt rgt.\n    intros HinD.\n    eapply Hobjs in HinD; destruct HinD as [HsrcNodes HtgtNodes].\n    generalize (HE src) (HE tgt); clear HE; RefSetFacts.set_iff.\n    split; edge_simpl; intuition.\n  Qed.\n\n  (* This is probably not necessary given ag_remainder_inter_refl, but\n     I'm rephrasing it and keeping it for reference *)\n  Theorem ag_remainder_inter_eq :\n    forall D objs, Seq.ag_objs_spec D objs ->\n    forall E, RefSet.Empty (RefSet.inter E objs) ->\n    forall E', RefSet.Empty (RefSet.inter E' objs) ->\n    forall R, ag_remainder_spec D E R ->\n    forall R', ag_remainder_spec D E' R' ->\n      AG.eq R R'.\n  Proof.\n    intros D objs Hobjs E HE E' HE' R HR R' HR'.\n    eapply AG.eq_trans.\n    eapply AG.eq_sym; eapply ag_remainder_inter_refl; [ | | apply HR]; eauto.\n    eapply ag_remainder_inter_refl; eauto.\n  Qed.\n\n\n  Theorem ag_authorized_remainder:\n    forall D E C A, ag_fully_authorized_spec D E C A ->\n    forall A', ag_fully_authorized_spec (ag_remainder D E) E C A' ->\n      AG.eq A A'.\n  Proof.\n    unfold ag_fully_authorized_spec.\n    intros D E C A Hauth A' Hauth' x.\n    rewrite Hauth; rewrite Hauth'; clear Hauth Hauth' A A'.\n\n    generalize (ag_remainder_spec_iff D E x); intros H'.\n    rewrite H'; intuition.\n  Qed.\n\n  Theorem ag_remainder_empty_inter:\n    forall D E R, ag_remainder_spec D E R ->\n    forall N, Seq.ag_objs_spec R N ->\n      RefSet.Empty (RefSet.inter E N).\n  Proof.\n    intros D E R Hrem N Hobjs.\n    unfold RefSet.Empty; intros a.\n    RefSetFacts.set_iff.\n    unfold Seq.ag_objs_spec in *; unfold ag_remainder_spec in *; unfold excluded_edge in *.\n    eapply Sumbool_not_and; Sumbool_decide; try apply RefSetProps.In_dec.\n    case (RefSetProps.In_dec a E); intros H; auto.\n    right; rewrite Hobjs; clear N Hobjs.\n    intros [obj [rgt [H'|H']]];\n    eapply Hrem in H'; edge_simpl; intuition.\n  Qed.    \n\n\n\n\n    Theorem ag_fully_authorized_spec_eq:\n      forall D D', AG.eq D D' ->\n      forall E E', RefSet.eq E E' ->\n      forall C C', CapSet.eq C C' ->\n      forall A, ag_fully_authorized_spec D E C A ->\n      forall A', ag_fully_authorized_spec D' E' C' A' ->\n        AG.eq A A'.\n      Proof.\n        unfold ag_fully_authorized_spec.\n        intros D D' HeqD E E' HeqE C C' HeqC A Hauth A' Hauth'.\n        intros x.\n        rewrite Hauth; rewrite Hauth'; clear A Hauth A' Hauth'.\n        rewrite HeqD.\n        unfold excluded_edge in *.\n        rewrite HeqE.\n        intuition;\n          (eapply Proper_exists_cap_edge in H1;\n            solve [apply Ref.eq_refl | apply AccessRight.eq_refl | apply CapSet.eq_sym; auto | eauto]).\n      Qed.\n\n    Theorem Proper_ag_fully_authorized_spec_impl:\n      Proper (AG.eq ==> RefSet.eq ==> CapSet.eq ==> AG.eq ==> impl) ag_fully_authorized_spec.\n    Proof.\n      unfold Proper; unfold respectful; unfold impl; unfold ag_fully_authorized_spec; \n        unfold exists_cap_edge; unfold CapSet.Exists; unfold excluded_edge; unfold cap_edge; intros.\n      rewrite <- H2; clear y2 H2.\n      rewrite H3; clear x2 H3.\n      rewrite H; clear x H.\n      rewrite H0; clear x0 H0.\n      intuition;\n      (destruct H2 as [cap Hcap];\n      right; left; split; [auto|apply ex_intro with cap; rewrite H1 in *; clear H1; auto]).\n    Qed.\n\n    Theorem Proper_ag_fully_authorized_spec:\n      Proper (AG.eq ==> RefSet.eq ==> CapSet.eq ==> AG.eq ==> iff) ag_fully_authorized_spec.\n    Proof.\n      split.\n      eapply Proper_ag_fully_authorized_spec_impl; eauto.\n      eapply Proper_ag_fully_authorized_spec_impl; eauto.\n      apply AG.eq_sym; auto.\n      apply RefSet.eq_sym; auto.\n      apply CapSet.eq_sym; auto.\n      apply AG.eq_sym; auto.\n    Qed.\n\n    Theorem Proper_filtered_subset_eq'_impl : \n      Proper (RefSet.eq ==> RefSet.eq ==> RefSet.eq ==> impl) filtered_subset_eq'.\n    Proof.\n      unfold Proper; unfold respectful; unfold impl. intros.\n      unfold filtered_subset_eq' in *.\n      intros e; generalize (H2 e); clear H2; intros H2.\n      rewrite H1 in *. clear x1 H1.\n      rewrite H in *; clear x H.\n      rewrite H0 in *; clear x0 H0.\n      intuition.\n    Qed.\n    \n    Theorem Proper_filtered_subset_eq' : \n      Proper (RefSet.eq ==> RefSet.eq ==> RefSet.eq ==> iff) filtered_subset_eq'.\n    Proof.\n      split; intros;  eapply Proper_filtered_subset_eq'_impl; eauto; solve [ eapply RefSet.eq_sym; eauto].\n    Qed.\n\n    Theorem ag_remainder_spec_eq: \n      forall D D', AG.eq D D' -> forall E E', RefSet.eq E E' ->\n      forall R, ag_remainder_spec D E R ->\n      forall R', ag_remainder_spec D' E' R' ->\n        AG.eq R R'.\n    Proof.\n      intros D D' HeqD E E' HeqE R HR R' HR'.\n      intros x; rewrite (HR x); rewrite (HR' x); clear R HR R' HR'.\n      rewrite HeqD; clear D HeqD.\n      unfold excluded_edge; rewrite HeqE; clear E HeqE.\n      intuition.\n    Qed.\n\n  Theorem ag_objs_ag_fully_authorized :\n    forall C Ctargets, capset_targets C Ctargets ->\n    forall E, ~ RefSet.Empty E ->\n    forall D R, ag_remainder_spec D E R ->\n    forall Robjs, Seq.ag_objs_spec R Robjs ->\n    forall A, ag_fully_authorized_spec D E C A ->\n    forall Aobjs, Seq.ag_objs_spec A Aobjs ->\n      RefSet.eq Aobjs (RefSet.union Robjs (RefSet.union E Ctargets)).\n  Proof.\n    intros C Ctargets HCtargets E Hnonempty D R HR Robjs HRobjs A Hauth Aobjs HAobjs n.\n    RefSetFacts.set_iff.\n    eapply ag_fully_authorized_spec_eq in Hauth;\n      [ | apply AG.eq_refl | apply RefSet.eq_refl | apply CapSet.eq_refl | apply ag_fully_authorized_spec_iff ].\n    rewrite (HAobjs n); clear Aobjs HAobjs.\n\n    (* Let's do easy cases *)\n    (* Is n in E?? *)\n    case (RefSetProps.In_dec n E); intros HinE.\n    split; intros; [right; left; auto|].\n    apply ex_intro with n; apply ex_intro with wk; left; apply Hauth;\n      unfold ag_fully_authorized; AGFacts.set_iff; do 2 left;\n        apply Seq.fold_AG_complete_ag; auto.\n    \n    (* Is n in capset_targets ? *)\n    case (RefSetProps.In_dec n Ctargets); intros HinCtargets.\n    split; intros; [intuition|].\n    eapply RefSetAddEq_nonempty_exists in Hnonempty.\n    destruct Hnonempty as [a Ha].\n    eapply HCtargets in HinCtargets.\n    destruct HinCtargets as [cap [Hin [Hnonempty Heq]]].\n    eapply ARSetAddEq_nonempty_exists in Hnonempty.\n    destruct Hnonempty as [rgt HinRgt].\n    do 2 eapply ex_intro; right.\n    apply Hauth; unfold ag_fully_authorized; AGFacts.set_iff.\n    left;right.\n    eapply ag_authorized_spec_iff; edge_simpl.\n    split; [eauto|eapply ex_intro; unfold cap_edge; intuition eauto].\n\n    (* Is n in remainder objs ? *)\n    case (RefSetProps.In_dec n Robjs); intros HinRobjs.\n    split; intros H; [intuition|].\n    eapply HRobjs in HinRobjs; destruct HinRobjs as [obj [rgt Hin]];\n    apply ex_intro with obj; apply ex_intro with rgt.\n    destruct Hin as [Hin | Hin]; [left|right];\n    (rewrite <- Hauth; unfold ag_fully_authorized; AGFacts.set_iff; \n      right; eapply ag_remainder_spec_iff; eapply HR; auto).\n\n    (* This last case must be impossible *)\n    split; intros H; [|intuition].\n    destruct H as [obj [rgt [Hin|Hin]]];\n      (eapply Hauth in Hin; revert Hin; unfold ag_fully_authorized; AGFacts.set_iff;\n        intros [[H | H] | H];\n          [ eapply Seq.complete_AG_conv_complete_ag in H; destruct H; contradiction\n            | eapply ag_authorized_spec_iff in H; edge_simpl; \n                solve [destruct H; contradiction \n                  | destruct H as [H [cap [Hin [H' H2]]]]; try contradiction;\n                    do 2 right; eapply HCtargets;\n                      eapply ex_intro; split; [eauto| split ; [intro Hnot; eapply Hnot; eauto|auto]]]\n            | rewrite ag_remainder_spec_eq in H; \n              [ | apply AG.eq_refl | apply RefSet.eq_refl | apply ag_remainder_spec_iff | apply HR ];\n              eapply Seq.ag_objs_spec_AG_all_objs in H; [| apply HRobjs]; destruct H; contradiction]).\n  Qed.\n\n  Theorem disjoint_helper:\n    forall objs N, RefSet.Subset objs N ->\n    forall E, RefSet.Subset E N -> RefSet.Empty (RefSet.inter E objs) ->\n    forall E', RefSet.Subset E E' -> filtered_subset_eq' E E' N ->\n    RefSet.Empty (RefSet.inter (RefSet.diff E' E) objs).\n  Proof.\n    intros objs N HN E HE Hdisj E' HE' Hfilter e.\n    generalize (Hdisj e) (Hfilter e) (HE e) (HE' e) (HN e); RefSetFacts.set_iff.\n    clear Hdisj Hfilter HE HE' HN. \n    intuition.\n  Qed.\n\n  Implicit Arguments disjoint_helper [objs N E E'].\n\n\n    (* Therefore, if we perform induction on (diff E' E), we can precisely describe mutability over\n       an appropriate subset. \n\n       Please note that we restricted E to contain only things not in objs, but still be a subset of N.\n       If we have some D containig E in objs, we can use the remainder to produce a D' that is dijoint from E.\n       Since this works for any N, N such that E is not empty, this will unify with a singleton.\n       As long as we choose N to be large enough to include E, we should be okay.\n\n       The expectation is that N are the off-limits objs.  Normally, we think of these objs as the\n       existed objs from our set.  However, the theorems are more general.\n\n       Our base case will simply require that two singletons have identical mutability\n       if neither element are in the objs of D.  This extends to supersets of the objs of D.\n       If we kick off this theorem with E = {e} and N = union objs E, we should be set.\n\n*)\n  Theorem ag_fully_authorized_subset_mutable_eq :\n    forall D objs, Seq.ag_objs_spec D objs ->\n    forall N, RefSet.Subset objs N ->\n    forall E, ~ RefSet.Empty E ->\n      RefSet.Empty (RefSet.inter E objs) ->\n      RefSet.Subset E N ->\n    forall E', RefSet.Subset E E' ->\n      filtered_subset_eq E E' N ->\n\n    forall C T, capset_targets C T -> \n      RefSet.Subset T N ->\n    forall A, ag_fully_authorized_spec D E C A ->\n    forall objs', Seq.ag_objs_spec A objs' ->\n      RefSet.Subset objs' N ->\n    forall A', ag_fully_authorized_spec D E' C A' ->\n    forall P, Seq.potAcc A P ->\n    forall P', Seq.potAcc A' P' ->\n    forall M, mutable_spec P E M ->\n    forall M', mutable_spec P' E' M' ->\n     RefSet.eq M' (RefSet.union M (RefSet.diff E' E)).\n  Proof.\n    intros D objs Hobjs N HN E Hnonempty Hdisj HE E' HE' Hfilter C T HT HTsub A Hauth\n      objs' Hobjs' HN' A' Hauth' P HP P' HP' M HM M' HM'.\n\n    (* \n       We need to induct on E' from E to E'.\n       Everywhere we use E', we need to rewrite it as (union E (diff E' E)).\n\n       Next, we need to assume Subset (diff E' E) (diff E' E).\n       This will unify with our induction hypothesis\n\n      (P:= (fun S =>  \n        RefSet.Subset S (RefSet.diff E' E) ->\n        ... ->\n        RefSet.eq M' (RefSet.union M S)\n\n       *)\n\n    assert (RefSet.eq E' (RefSet.union E (RefSet.diff E' E))) as Hdiff.\n    intros x.\n    generalize (HE' x).\n    RefSetFacts.set_iff.\n    case (RefSetProps.In_dec x E); intros Hcase;    \n    intuition.\n\n    eapply Proper_ag_fully_authorized_spec in Hauth';\n      [ | apply AG.eq_refl\n        | apply RefSet.eq_sym; apply Hdiff\n        | apply CapSet.eq_refl\n        | apply AG.eq_refl\n      ].\n\n    eapply Proper_mutable_spec in HM';\n      [ | apply AG.eq_refl\n        | apply Hdiff\n        | apply RefSet.eq_refl\n      ].\n\n\n\n    rewrite filtered_subset_eq_iff_filtered_subset_eq' in Hfilter.\n    assert (forall e, RefSet.In e (RefSet.diff E' E) -> ~ RefSet.In e N) as Hfiltersub by\n      (intros e;\n    RefSetFacts.set_iff;\n    intros Hindiff HinN;\n    destruct (Hfilter e) as [H | [H Heq]]; try contradiction;\n    rewrite Heq in Hindiff;\n    intuition contradiction).\n\n    clear Hdiff.\n    revert A' Hauth' P' HP' M' HM'.\n\n    (* While inducting on Hfiltersub isn't strictly necessary, it should make things easier *)\n    generalize (RefSetProps.subset_equal (RefSet.eq_refl (RefSet.diff E' E))) Hfiltersub.\n\n    eapply RefSetProps.set_induction with \n      (P:= (fun S =>  \n        RefSet.Subset S (RefSet.diff E' E) ->\n        (forall e : RefSet.elt, RefSet.In e S -> ~ RefSet.In e N) ->\n        forall A' : AG.t,\n          ag_fully_authorized_spec D (RefSet.union E S) C A' ->\n        forall P' : AG.t,\n          Seq.potAcc A' P' ->\n        forall M' : RefSet.t,\n          mutable_spec P' (RefSet.union E S) M' ->\n          RefSet.eq M' (RefSet.union M S)\n      )).\n    (* base *)\n    intros S Hempty Hsub Hfiltersub' A' Hauth' P' HP' M' HM'.\n\n    assert (RefSet.eq (RefSet.union E S) E) as HunionS by\n      (rewrite RefSetProps.union_sym; rewrite (RefSetProps.empty_is_empty_1 Hempty);\n        rewrite RefSetProps.union_subset_equal; [apply RefSet.eq_refl| eapply RefSetProps.subset_empty]).\n\n    rewrite (RefSetProps.empty_is_empty_1 Hempty); rewrite RefSetProps.union_sym;\n    rewrite RefSetProps.union_subset_equal; [ | apply RefSetProps.subset_empty].\n    \n    eapply mutable_spec_eq_iff;\n      [apply HM'\n        |\n        | apply HunionS\n        | apply HM].\n\n    \n    eapply potAcc_equiv;\n      [ | apply HP'\n        | apply HP].\n    \n    eapply ag_fully_authorized_spec_eq;\n      [apply AG.eq_refl\n        | apply HunionS\n        | apply CapSet.eq_refl\n        | apply Hauth'\n        | apply Hauth].\n    \n  (* step *)\n  intros S S' IH x HinX HaddX HsubS' HfiltersubS' A' Hauth' P' HP' M' HM'.\n  (* Begin instantiating the induction hypothesis *)\n  assert (RefSet.Subset S (RefSet.diff E' E)) as HsubS by\n    (eapply RefSetProps.subset_trans; [eapply RefSetAddEq.Add_Subset; apply HaddX | auto]).\n  assert (forall e, RefSet.In e S -> ~ RefSet.In e N) as HfiltersubS by\n    (intros e HeinS; eapply HfiltersubS'; eapply RefSetAddEq.Add_Subset; eauto).\n  assert (exists A2, ag_fully_authorized_spec D (RefSet.union E S) C A2) as [A2 Hauth2] by\n    (eapply ex_intro; eapply ag_fully_authorized_spec_iff).\n  generalize (Seq.exists_potAcc A2); intros [P2 HP2].\n  assert (exists M2, mutable_spec P2 (RefSet.union E S) M2) as [M2 HM2] by\n    (eapply ex_intro; eapply mutable_spec_mutable).\n  generalize (IH HsubS HfiltersubS _ Hauth2 _ HP2 _ HM2); intros HeqM2. clear IH.\n\n  (*\n     remember, \n     RefSet.union E S' [=] RefSet.add x (RefSet.union E S) and\n     RefSet.union M S' [=] RefSet.add x (RefSet.union M S)\n     *)\n\n  assert (forall M, RefSetProps.Add x (RefSet.union M S) (RefSet.union M S')) as HaddS' by\n    (intros Q e; RefSetFacts.set_iff; rewrite (HaddX e); intuition).\n\n  assert (exists objs2, Seq.ag_objs_spec A2 objs2) as [objs2 Hobjs2] by\n    (eapply ex_intro; eapply Seq.ag_objs_spec_ag_objs).\n  assert (~ RefSet.Empty (RefSet.union E S)) as Hnonemptyunion by\n    (intro Hnot; apply Hnonempty; intros e HinE; apply Hnot with e; RefSetFacts.set_iff; auto).\n\n  eapply ag_fully_authorized_add_mutable_eq.\n  14: apply HM'.\n  13: apply HM2.\n  12: apply HP'.\n  11: apply HP2.\n  10: apply Hauth'.\n  7: apply Hauth2.\n  apply Hobjs.\n  eapply RefSetProps.subset_trans; [apply HN | apply RefSetProps.union_subset_1 with (s':=S)].\n  intros e; RefSetFacts.set_iff; intuition.\n  auto.\n  2: apply HaddS'.\n  4: eapply RefSetAddEq.Add_eq_complete; \n    [ apply Ref.eq_refl | apply RefSet.eq_sym; apply HeqM2 | apply RefSet.eq_refl| apply HaddS'].\n  RefSetFacts.set_iff.\n  eapply Sumbool_not_or; Sumbool_decide; try apply RefSetProps.In_dec; split;\n    [eapply HfiltersubS'; apply HaddX; auto | auto].\n  apply Hobjs2.\n  \n (* This is a statement saying that the objs of A2 grew at most by S,\n     This should be obvious or we have a theorem, but it's probably buried somewhere *)\n  (* In fact objs2 [=] (RefSet.union objs' S) *)\n  (* We may need a general theorem about this and probably need to fold it into the IH *)\n\n\n  assert (exists R, ag_remainder_spec D (RefSet.union E S) R) as [R HR] by\n    (eapply ex_intro; apply ag_remainder_spec_iff).\n\n  assert (exists Robjs, Seq.ag_objs_spec R Robjs) as [Robjs HRobjs] by\n    (eapply ex_intro; apply Seq.ag_objs_spec_ag_objs).\n\n\n  rewrite ag_objs_ag_fully_authorized with (Aobjs:=objs2);\n    [ | apply HT | apply Hnonemptyunion | apply HR | apply HRobjs| apply Hauth2 | apply Hobjs2 ].\n\n\n  (* We actually know that the objs of D contain no elements of S or E\n     This makes the remainder of D simply D and allows us to substitue objs for Robjs.\n     E is a subset of N and objs are a subset of N.\n     However, the elements of T must also be a subset of N, which we forgot to assume.\n     Do all these things, and this becimes simple subset inclusion.\n     *)\n\n  assert (RefSet.Empty (RefSet.inter S objs)) as Hdisj2.\n  intros e.\n  generalize (disjoint_helper HN HE Hdisj HE' Hfilter e).\n  eapply RefSetAddEq.Add_Subset in HaddX.\n  rewrite <- HaddX in HsubS'.\n  rewrite <- HsubS'.\n  auto.\n  \n\n\n  assert (RefSet.Empty (RefSet.inter (RefSet.union E S) objs)) as Hdisj'.\n  intros e.\n  generalize (Hdisj2 e) (Hdisj e).\n  RefSetFacts.set_iff.\n  intuition.\n\n  assert (RefSet.eq Robjs objs) as HeqRobjs.\n  eapply ag_objs_spec_equiv.\n  apply HRobjs.\n  apply Hobjs.\n  eapply AG.eq_sym.\n  eapply ag_remainder_inter_refl.\n  apply Hobjs.\n  apply Hdisj'.\n  apply HR.\n  \n  rewrite HeqRobjs.\n  intros e.\n  generalize (Hdisj' e) (Hdisj e) (HTsub e).\n  RefSetFacts.set_iff.\n  intuition.\n  Qed.\n\n\n\n\n(* I'm taking a break for the singleton case *)\n\n(* edge' [=] [e->e'] edge *)\n\nDefinition edge_subst_spec e e' edge edge' :=\n  ( (Ref.eq (Edges.source edge) e /\\ Ref.eq (Edges.source edge') e')\n    \\/ ~ Ref.eq (Edges.source edge) e /\\ Ref.eq (Edges.source edge) (Edges.source edge') ) /\\\n  ( (Ref.eq (Edges.target edge) e /\\ Ref.eq (Edges.target edge') e')\n    \\/ ~ Ref.eq (Edges.target edge) e /\\ Ref.eq (Edges.target edge) (Edges.target edge') ) /\\\n  AccessRight.eq (Edges.right edge) (Edges.right edge').\n\nTheorem Proper_edge_subst_spec_impl : Proper (Ref.eq ==> Ref.eq ==> Edge.eq ==> Edge.eq ==> impl) edge_subst_spec.\nProof.\n  unfold Proper; unfold respectful; unfold impl; unfold edge_subst_spec.\n  intros.\n  rewrite H in *; rewrite H0 in *. \n  rewrite (Edges.eq_source _ _ H1) in *;  rewrite (Edges.eq_source _ _ H2) in *;\n  rewrite (Edges.eq_target _ _ H1) in *;  rewrite (Edges.eq_target _ _ H2) in *;\n  rewrite (Edges.eq_right _ _ H1) in *;  rewrite (Edges.eq_right _ _ H2) in *.\n  intuition.\nQed.\n\nHint Resolve Proper_edge_subst_spec_impl.\n\nTheorem Proper_edge_subst_spec_iff : Proper (Ref.eq ==> Ref.eq ==> Edge.eq ==> Edge.eq ==> iff) edge_subst_spec.\nProof.\n  unfold Proper; unfold respectful; unfold edge_subst_spec; intros.\n  split; eapply Proper_edge_subst_spec_impl; eauto; try (eapply Ref.eq_sym; auto).\nQed.\n\nHint Resolve Proper_edge_subst_spec_iff.\n\nTheorem edge_subst_spec_eq : forall e e', Ref.eq e e' ->\n  forall e2 e2', Ref.eq e2 e2' -> forall edge edge', Edge.eq edge edge' ->\n  forall edge2, edge_subst_spec e e2 edge edge2 ->\n  forall edge2', edge_subst_spec e' e2' edge' edge2' ->\n    Edge.eq edge2 edge2'.\nProof.\n  intros e e' He e2 e2' He2 edge edge' Hedge edge2 Hedge2 edge2'; revert Hedge2.\n  unfold edge_subst_spec in *.\n  generalize (Edges.eq_source _ _ Hedge).\n  generalize (Edges.eq_target _ _ Hedge).\n  generalize (Edges.eq_right _ _ Hedge).\n  clear Hedge.\n  edge_destruct edge src tgt rgt.\n  edge_destruct edge' src' tgt' rgt'.\n  edge_destruct edge2 src2 tgt2 rgt2.\n  edge_destruct edge2' src2' tgt2' rgt2'.\n  rewrite He; rewrite He2.\n  do 3 (intros Heq; rewrite Heq; clear Heq); clear src tgt rgt.\n  intros Hedge2 Hedge2'.\n  destruct Hedge2 as [Hsrc2 [Htgt2 Hrgt2]].\n  destruct Hedge2' as [Hsrc2' [Htgt2' Hrgt2']].\n  rewrite <- Hrgt2; rewrite <- Hrgt2'; clear rgt2' rgt2 Hrgt2 Hrgt2'.\n  unfold Ref.eq in *.\n  intuition (eapply Edges.edge_equal; unfold Ref.eq; eauto; try apply AccessRight.eq_refl) .\nQed.  \n\nHint Resolve edge_subst_spec_eq.\n\nDefinition edge_subst e e' edge := \n  let src := if Ref.eq_dec (Edges.source edge) e then e' else Edges.source edge in\n  let tgt := if Ref.eq_dec (Edges.target edge) e then e' else Edges.target edge in\n  (Edges.mkEdge src tgt (Edges.right edge)).\n\nTheorem edge_subst_spec_edge_subst : forall e e' edge, edge_subst_spec e e' edge (edge_subst e e' edge).\nProof.\n  unfold edge_subst_spec; unfold edge_subst; intros e e' edge.\n  case (Ref.eq_dec (Edges.source edge) e); intros HeqSrc ; [rewrite HeqSrc in *|];\n    (case (Ref.eq_dec (Edges.target edge) e) ; intros HeqTgt ; [rewrite HeqTgt in *|]); edge_simpl;\n  intuition (try solve [apply Ref.eq_refl | apply AccessRight.eq_refl]).\nQed.\n\nHint Resolve edge_subst_spec_edge_subst.\n\nTheorem edge_subst_spec_dec: forall e e' edge edge', \n  {edge_subst_spec e e' edge edge'} + { ~ edge_subst_spec e e' edge edge'}.\nProof.\n  intros.\n  case (Edge.eq_dec edge' (edge_subst e e' edge)); intros Hcase; [left|right; intros Hspec; eapply Hcase].\n  eapply Proper_edge_subst_spec_impl; \n    [eapply Ref.eq_refl\n      | eapply Ref.eq_refl\n      | eapply Edge.eq_refl\n      | eapply Edge.eq_sym; apply Hcase\n      | eapply edge_subst_spec_edge_subst].\n  eapply edge_subst_spec_eq;\n    [apply Ref.eq_refl\n      | apply Ref.eq_refl\n      | apply Edge.eq_refl\n      | apply Hspec\n      | apply edge_subst_spec_edge_subst].\nQed.\n\nDefinition ag_subst_spec e e' ag ag' :=\n  forall edge', AG.In edge' ag' <-> AG.Exists (fun edge => edge_subst_spec e e' edge edge') ag.\n  \nTheorem Proper_ag_subst_spec_impl : Proper (Ref.eq ==> Ref.eq ==> AG.eq ==> AG.eq ==> impl) ag_subst_spec.\nProof.\n  unfold Proper; unfold respectful; unfold impl; unfold ag_subst_spec; unfold AG.Exists; intros.\n  rewrite H in *; rewrite H0 in *; clear x x0 H H0.\n  eapply iff_trans; [eapply iff_sym; apply H2| clear H2].\n  eapply iff_trans; [eapply H3| clear x2 H3].\n  split; (intros [edge [H H']]; eapply ex_intro; split; [eapply H1; eauto | eapply H']).\nQed.\n\nHint Resolve Proper_ag_subst_spec_impl.\n\nTheorem Proper_ag_subst_spec_iff : Proper (Ref.eq ==> Ref.eq ==> AG.eq ==> AG.eq ==> iff) ag_subst_spec.\nProof.\n  unfold Proper; unfold respectful; unfold ag_subst_spec; intros.\n  split; apply Proper_ag_subst_spec_impl; eauto; try (eapply Ref.eq_sym; auto); try (eapply AG.eq_sym; auto).\nQed.\n\nHint Resolve Proper_ag_subst_spec_iff.\n\nTheorem ag_subst_spec_eq : forall e e', Ref.eq e e' ->\n  forall e2 e2', Ref.eq e2 e2' -> forall ag ag', AG.eq ag ag' ->\n  forall ag2, ag_subst_spec e e2 ag ag2 ->\n  forall ag2', ag_subst_spec e' e2' ag' ag2' ->\n    AG.eq ag2 ag2'.\nProof.\n  intros e e' He e2 e2' He2 ag ag' Hag ag2 Hag2 ag2'; revert Hag2.\n  unfold ag_subst_spec in *; unfold AG.Exists.\n  rewrite He in *; clear e He.\n  rewrite He2 in *; clear e2 He2.\n  intros Hag2 Hag2' edge.\n  eapply iff_trans; [eapply Hag2|clear Hag2].\n  eapply iff_trans; [clear Hag2'|eapply iff_sym; apply Hag2'].\n  split; intros [edge' [H H']]; eauto.\nQed.  \n\nHint Resolve ag_subst_spec_eq.\n\nDefinition ag_subst e e' ag := AG.fold (fun edge acc => AG.add (edge_subst e e' edge) acc) ag AG.empty.\n\nTheorem ag_subst_spec_ag_subst : forall e e' ag, ag_subst_spec e e' ag (ag_subst e e' ag).\nProof.\n  unfold ag_subst_spec; unfold ag_subst; unfold AG.Exists; intros e e' ag.\n  eapply AGProps.fold_rec.\n  (* base *)\n  intros s Hempty edge.\n  split.\n  intros Hempty'; eapply AGFacts.empty_iff in Hempty'; contradiction.\n  intros [edge' [Hempty' Hsubst]].  eapply Hempty in Hempty'; contradiction.\n  (* step *)\n  intros edge ag' s s' HinX HinS Hadd IH edge'.\n  split; intros Hin.\n  (* left *)\n  eapply AGProps.Add_add in Hin.\n  destruct Hin as [Hsubst | Hag'].\n  eapply ex_intro; split;\n    [eapply Hadd; left; eapply Edge.eq_refl\n    | eapply Proper_edge_subst_spec_impl; eauto; try apply Ref.eq_refl].\n  eapply IH in Hag'; destruct Hag' as [edge2 [Hin Hsubst]].\n  eapply ex_intro; split; [ eapply AGAddEq.Add_Subset; [apply Hadd| apply Hin]| auto].\n  (* right *)\n  destruct Hin as [edge2 [Hin Hsubst]].\n  eapply AGProps.Add_add.\n  eapply Hadd in Hin.\n  destruct Hin as [Heq | Hag']; [left|right].\n  eapply edge_subst_spec_eq; eauto; try apply Ref.eq_refl.\n  eapply IH; eapply ex_intro; eauto.\nQed.\n\nHint Resolve edge_subst_spec_edge_subst.\n\nTheorem ag_subst_spec_dec: forall e e' ag ag',\n  {ag_subst_spec e e' ag ag'} + {~ ag_subst_spec e e' ag ag'}.\nProof.\n  intros e e' ag ag'.\n  case (AG.eq_dec ag' (ag_subst e e' ag)); intros Hcase ;[left|right].\n  eapply Proper_ag_subst_spec_impl;\n    [ apply Ref.eq_refl | apply Ref.eq_refl \n      | apply AG.eq_refl | apply AG.eq_sym; apply Hcase \n      | apply ag_subst_spec_ag_subst].\n  intros Hspec; apply Hcase; clear Hcase.\n  eapply ag_subst_spec_eq;\n    [ apply Ref.eq_refl | apply Ref.eq_refl \n      | apply AG.eq_refl | apply Hspec \n      | apply ag_subst_spec_ag_subst].  \nQed.\n        Theorem exists_cap_edge_capset_targets: forall C T, capset_targets C T ->\n          forall tgt, (exists rgt, exists_cap_edge tgt rgt C) <-> RefSet.In tgt T.\n        Proof.\n          intros C T HT tgt; split; [intros [rgt [cap [Hin [Htgt Hrgt]]]] |intros Hin].\n          eapply HT; clear HT; unfold exists_cap_edge in *.\n          eapply ex_intro.\n          split; [eauto|split; [intro Hempty; eapply Hempty; eauto| auto]].\n          eapply HT in Hin; destruct Hin as [cap [Hin [Hnonempty Heq]]].\n          eapply ARSetAddEq_nonempty_exists in Hnonempty; destruct Hnonempty as [rgt HinRgt].\n          do 2 eapply ex_intro; unfold cap_edge; intuition eauto.\n        Qed.\n\n        Hint Resolve exists_cap_edge_capset_targets.\n\n\n      Theorem ag_fully_authorized_spec_singleton_ag_subst_spec:\n        forall D objs, Seq.ag_objs_spec D objs ->\n        forall C T, capset_targets C T ->\n        forall e, ~ RefSet.In e objs -> ~ RefSet.In e T ->\n        forall e', ~ RefSet.In e' objs -> ~ RefSet.In e' T ->\n          ~ Ref.eq e e' ->\n        forall A, ag_fully_authorized_spec D (RefSet.singleton e) C A ->\n        forall A', ag_fully_authorized_spec D (RefSet.singleton e') C A' ->\n          ag_subst_spec e e' A A'.\n      Proof.\n        intros D objs Hobjs C T HT e He HeT e' He' HeT' Hneq A Hauth A' Hauth' edge'.\n        unfold AG.Exists.\n        eapply iff_trans; [apply Hauth'|].\n        unfold excluded_edge.\n        edge_destruct edge' src' tgt' rgt'.\n        repeat progress (rewrite RefSetFacts.singleton_iff).\n        split; intros Hedge'.\n        destruct Hedge' as [Hedge' | [Hedge' | Hedge']].\n        (* refl case *)\n        destruct Hedge' as [Hsrc' Htgt']; rewrite <- Hsrc' in *; rewrite <- Htgt' in *.\n        apply ex_intro with (Edges.mkEdge e e rgt'); split.\n        eapply Hauth; edge_simpl; repeat progress (rewrite RefSetFacts.singleton_iff); intuition.\n        unfold edge_subst_spec; repeat progress edge_simpl; intuition.\n        (* auth case *)\n        destruct Hedge' as [Hsrc' Hcapedge].\n        rewrite <- Hsrc'.\n        apply ex_intro with (Edges.mkEdge e tgt' rgt'); split.\n        eapply Hauth; repeat progress edge_simpl; repeat progress rewrite RefSetFacts.singleton_iff; intuition.\n        assert (~ Ref.eq tgt' e) as HneqTgt' by \n          (intros Hnot; eapply HeT; eapply exists_cap_edge_capset_targets; \n            [eapply HT \n              | eapply ex_intro; rewrite <- Hnot; eauto]).\n        unfold edge_subst_spec; repeat progress edge_simpl;\n          intuition (try solve [auto | apply Ref.eq_refl | apply AccessRight.eq_refl]).\n        (* remainder case *)\n        destruct Hedge' as [HinD [HneqSrc HneqTgt]].\n        assert (~ Ref.eq e src') as HneqSrc' by\n          (intros Hnot; apply He; eapply Hobjs; do 2 eapply ex_intro; rewrite Hnot; eauto).\n        assert (~ Ref.eq e tgt') as HneqTgt' by\n          (intros Hnot; apply He; eapply Hobjs; do 2 eapply ex_intro; rewrite Hnot; eauto).\n        apply ex_intro with (Edges.mkEdge src' tgt' rgt'); split.\n        eapply Hauth; unfold excluded_edge;\n          repeat progress edge_simpl; repeat progress rewrite RefSetFacts.singleton_iff; intuition.\n        unfold edge_subst_spec; repeat progress edge_simpl.\n        unfold Ref.eq in *; intuition (try solve [auto  | apply AccessRight.eq_refl]).\n        \n        (* flip *)\n        destruct Hedge' as [edge [HinA Hsubst]].\n        eapply Hauth in HinA.\n        revert HinA Hsubst; \n        unfold excluded_edge; unfold edge_subst_spec;\n          edge_destruct edge src tgt rgt;\n          repeat progress edge_simpl; repeat progress rewrite RefSetFacts.singleton_iff;\n            intros HinA Hsubst.\n        destruct Hsubst as [Hsrc [Htgt Hrgt]].\n        rewrite Hrgt in *.\n        destruct HinA as [Hrefl | [Hcap | Hrem]].\n        (* refl case *)\n        unfold Ref.eq in *.\n        destruct Hrefl as [HsrcE HtgtE]; rewrite <- HsrcE in *; rewrite <- HtgtE in *.\n        destruct Hsrc as [[HsrcE2 HsrcE'] |[HsrcE2 HsrcE'2]] ;[rewrite HsrcE' | contradict HsrcE2; auto].\n        destruct Htgt as [[HtgtE2 HtgtE'] |[HtgtE2 HtgtE'2]] ;[rewrite HtgtE' | contradict HtgtE2; auto].\n        intuition.\n        (* auth case *)\n        destruct Hcap as [HeqSrc Hcapedge].\n        rewrite <- HeqSrc in *.\n        unfold Ref.eq in *.\n        destruct Hsrc as [[HsrcE2 HsrcE'] |[HsrcE2 HsrcE'2]] ;[rewrite HsrcE' | contradict HsrcE2; auto].\n        destruct Htgt as [[HtgtE2 HtgtE'] |[HtgtE2 HtgtE'2]];\n          [rewrite <- HtgtE' | rewrite <- HtgtE'2 ]; intuition.\n        (* rem case *)\n        destruct Hrem as [HinD [HneqSrc HneqTgt]].\n        unfold Ref.eq in *.\n        destruct Hsrc as [[HsrcE2 HsrcE'] |[HsrcE2 HsrcE'2]];[contradict HsrcE2; auto | rewrite <- HsrcE'2 ].\n        destruct Htgt as [[HtgtE2 HtgtE'] |[HtgtE2 HtgtE'2]];[contradict HtgtE2; auto | rewrite <- HtgtE'2 ].\n        assert (~ Ref.eq src e') as HneqSrc' by\n          (intros Hnot; eapply Ref.eq_sym in Hnot; \n            apply He'; eapply Hobjs; do 2 eapply ex_intro; rewrite Hnot; eauto).\n        assert (~ Ref.eq tgt e') as HneqTgt' by\n          (intros Hnot; eapply Ref.eq_sym in Hnot;\n            apply He'; eapply Hobjs; do 2 eapply ex_intro; rewrite Hnot; eauto).\n        intuition.\n      Qed.\n\n          Theorem edge_subst_spec_refl: forall e e', Ref.eq e e' -> \n            forall edge edge', (edge_subst_spec e e' edge edge' <-> Edge.eq edge edge').\n          Proof.\n            unfold edge_subst_spec.\n            intros e e' Heq. \n            rewrite Heq; clear e Heq.\n            intros edge edge'. \n            edge_destruct edge src tgt rgt; edge_destruct edge' src' tgt' rgt'.\n            split.\n            intros [Hsrc [Htgt Hrgt]].\n            eapply Edges.edge_equal.\n            destruct Hsrc as [[Hsrc Hsrc'] | [ _ Hsrc]]; \n              rewrite Hsrc in *; try rewrite Hsrc' in *; apply Ref.eq_refl.\n            destruct Htgt as [[Htgt Htgt'] | [ _ Htgt]]; \n              rewrite Htgt in *; try rewrite Htgt' in *; apply Ref.eq_refl.\n            auto.\n            intros HeqEdge.\n            (* stolen from destructEqEdge, consider generalizing *)\n            generalize (Edges.eq_source _ _ HeqEdge); intros HeqEdgeS; \n              repeat progress rewrite Edges.source_rewrite in HeqEdgeS;\n                generalize (Edges.eq_target _ _ HeqEdge); intros HeqEdgeT; \n                  repeat progress rewrite Edges.target_rewrite in HeqEdgeT;\n                    generalize (Edges.eq_right _ _ HeqEdge); intros HeqEdgeR; \n                      repeat progress rewrite Edges.right_rewrite in HeqEdgeR.\n            rewrite HeqEdgeS; rewrite HeqEdgeT; rewrite HeqEdgeR.\n            generalize (Ref.eq_dec src' e') (Ref.eq_dec tgt' e'); intros Hcase Hcase'; intuition.\n          Qed.\n\n\n        Theorem ag_subst_spec_refl: forall e e', Ref.eq e e' -> forall D D', ag_subst_spec e e' D D' <->\n          AG.eq D D'.\n        Proof.\n          unfold ag_subst_spec. \n          intros e e' Heq D D'. \n          rewrite Heq. clear e Heq.\n\n          split; \n            [intros Hsubst edge; rewrite Hsubst; clear Hsubst | intros Heq edge ];\n            (split; intros H;\n              [eapply ex_intro;\n                split; [eauto|eapply edge_subst_spec_refl; auto; solve [apply Ref.eq_refl]]\n                | destruct H as [edge' [Hin Hsubst]];\n                  eapply edge_subst_spec_refl in Hsubst; [| apply Ref.eq_refl]; rewrite <- Hsubst in *; eauto]).\n        Qed.\n\n\n\n        Definition edge_free e edge := ~ Ref.eq (Edges.source edge) e /\\ ~ Ref.eq (Edges.target edge) e.\n\n        Theorem edge_subst_spec_free:\n          forall e2 edge, edge_free e2 edge ->\n            forall e1 edge', edge_subst_spec e1 e2 edge edge' ->\n              edge_free e1 edge'.\n        Proof.\n          intros e2 edge [Hneq1 Hneq2] e1 edge' Hsubst.\n          unfold edge_free.\n          case (Ref.eq_dec e1 e2); intros Hneq; unfold edge_subst_spec in *.\n          rewrite Hneq in *.\n          destruct Hsubst as [[[HsrcE1 HsrcE2] | [HsrcE1 Hsrc']] [[[HtgtE1 HtgtE2] | [HtgtE1 Htgt']] Hrgt]];\n            solve [contradiction | rewrite Hsrc' in *; rewrite Htgt' in *; split; eauto].\n\n          destruct Hsubst as [[[HsrcE1 HsrcE2] | [HsrcE1 Hsrc']] [[[HtgtE1 HtgtE2] | [HtgtE1 Htgt']] Hrgt]];\n          try rewrite HsrcE1 in *; try rewrite HsrcE2 in *; try rewrite Hsrc' in *;\n          try rewrite HtgtE1 in *; try rewrite HtgtE2 in *; try rewrite Htgt' in *;\n          unfold Ref.eq in *; intuition eauto.\n        Qed.\n\n\n        (* This was writtine before edge_subst_spec_free, you may wish to alter it later *)\n        Theorem ag_subst_spec_free : \n        forall D Dobjs, Seq.ag_objs_spec D Dobjs ->\n        forall D' D'objs, Seq.ag_objs_spec D' D'objs ->\n        forall e', ~ RefSet.In e' Dobjs ->\n        forall e, ag_subst_spec e e' D D' ->\n          ~ RefSet.In e D'objs.\n        Proof.\n          intros D Dobjs HDobjs D' D'objs HD'objs e' He' e Hsubst Hnot.\n          eapply He'; clear He'; eapply HDobjs; clear Dobjs HDobjs.\n\n          eapply HD'objs in Hnot; clear D'objs HD'objs.\n\n          destruct Hnot as [obj [rgt' [Hnot | Hnot]]];\n            (eapply Hsubst in Hnot; clear D' Hsubst;\n            destruct Hnot as [edge Hin];\n            revert Hin;\n            edge_destruct edge src tgt rgt;\n            intros [Hin [[[Hsrc HeqSrc]|[HneqSrc Hsrc]] [[[Htgt HeqTgt]|[HneqTgt Htgt]] Hrgt]]];\n            repeat progress edge_simpl;\n              solve [ contradiction \n                | rewrite Hsrc in Hin; try rewrite HeqSrc in Hin;\n                  rewrite Htgt in Hin; try rewrite HeqTgt in Hin;\n                    do 2 eapply ex_intro; eauto\n               ]).\n        Qed.\n\n        Theorem ag_free_edge_free :\n          forall D Dobjs, Seq.ag_objs_spec D Dobjs ->\n            forall e, ~ RefSet.In e Dobjs ->\n              AG.For_all (fun edge => edge_free e edge) D.\n        Proof.\n          unfold AG.For_all.\n          intros D Dobjs HDobjs e Hfree edge.\n          edge_destruct edge src tgt rgt; intros HinD.\n          split; (edge_simpl; intros Heq; apply Hfree;\n            apply HDobjs; rewrite Heq in *;\n              do 2 eapply ex_intro; eauto 2).\n        Qed.\n\n        Theorem edge_subst_free_sym:\n          forall e2 edge1, edge_free e2 edge1 ->\n          forall e1 edge2, edge_subst_spec e1 e2 edge1 edge2 ->\n          edge_subst_spec e2 e1 edge2 edge1.\n          Proof.\n            intros e2 edge1 He2Free e1 edge2 Hsubst.\n            destruct He2Free as [He2FreeSrc He2FreeTgt].\n            unfold edge_subst_spec in *.\n            destruct Hsubst as [[[HsrcE1 HsrcE2] | [HsrcE1 Hsrc']] [[[HtgtE1 HtgtE2] | [HtgtE1 Htgt']] Hrgt]];\n            unfold Ref.eq in *;\n            try rewrite Hsrc' in *; try rewrite HsrcE1 in *; try rewrite HsrcE2 in *;\n            try rewrite Htgt' in *; try rewrite HtgtE1 in *; try rewrite HtgtE2 in *;\n              (intuition auto; try (apply AccessRight.eq_sym; auto)).\n          Qed.\n\n          Theorem Proper_edge_free_impl: Proper (Ref.eq ==> Edge.eq ==> impl) edge_free.\n          Proof.\n            unfold Proper; unfold respectful; unfold impl; unfold edge_free.\n            intros x y H x0 y0 H0; rewrite H;\n            rewrite (Edges.eq_source _ _ H0);\n            rewrite (Edges.eq_target _ _ H0).\n            auto.            \n          Qed.\n\n\n\nTheorem edge_subst_spec_eq_l : \n  forall e e2 edge edge2, edge_subst_spec e e2 edge edge2 ->\n    edge_free e2 edge -> \n  forall edge', edge_subst_spec e e2 edge' edge2 ->\n    edge_free e2 edge' ->\n    Edge.eq edge edge'.\nProof.\n  intros e e2 edge edge2 Hsubst [HneqSrc HneqTgt] edge';\n    revert Hsubst HneqSrc HneqTgt.\n  unfold edge_subst_spec in *;   unfold edge_free.\n  edge_destruct edge src tgt rgt.\n  edge_destruct edge' src' tgt' rgt'.\n  edge_destruct edge2 src2 tgt2 rgt2.\n  intros [Hsrc [Htgt Hrgt]] HneqSrc HneqTgt [Hsrc' [Htgt' Hrgt']] [HneqSrc' HneqTgt'].\n  rewrite Hrgt; rewrite Hrgt'. clear rgt' rgt Hrgt Hrgt'.\n  unfold Ref.eq in *.\n  intuition; try solve [repeat progress ( try rewrite He in *; try rewrite He2 in *;\n    try rewrite H0 in *; try rewrite H1 in *; try rewrite H2 in *; try rewrite H3 in *;\n      try rewrite H4 in *; try rewrite H5 in *; try rewrite H6 in *; try rewrite H7 in *);\n  solve [contradiction HneqSrc; eauto 2\n| contradiction HneqTgt; eauto 2\n| contradiction HneqSrc'; eauto 2 \n| contradiction HneqTgt'; eauto 2 ]\n| eapply Edges.edge_equal; unfold Ref.eq; eauto 2; try apply AccessRight.eq_refl].\nQed.  \n\nHint Resolve edge_subst_spec_eq_l.\n\n\n      Theorem ag_subst_free_sym:\n        forall A Aobjs, Seq.ag_objs_spec A Aobjs ->\n        forall e2, ~ RefSet.In e2 Aobjs ->\n        forall e1 B, ag_subst_spec e1 e2 A B ->\n          ag_subst_spec e2 e1 B A.\n      Proof.\n        intros A Aobjs HAobjs e2 He2Free e1 B Hsubst.\n        generalize (Seq.ag_objs_spec_ag_objs B) He2Free; generalize (Seq.ag_objs B);\n          intros Bobjs HBobjs He1Free.\n        eapply ag_subst_spec_free in He1Free;\n          [ | apply HAobjs | apply HBobjs | apply Hsubst ].\n        intros edge.\n\n        split; [intros Hin| intros [edge' [HinB Hexcluded]]].\n        eapply ex_intro.\n        split; [|\n          eapply edge_subst_free_sym;\n            [eapply ag_free_edge_free with (Dobjs:=Aobjs); eauto 1 | eauto 1]].\n        eapply Hsubst; eapply ex_intro; split; eauto.\n\n        generalize HinB; intros HedgeFree.\n        eapply ag_free_edge_free in HedgeFree;\n           [ | apply HBobjs |  apply He1Free].\n        eapply edge_subst_spec_free in HedgeFree; [| eapply Hexcluded].\n\n        eapply edge_subst_free_sym in Hexcluded; \n          [ | eapply ag_free_edge_free with (Dobjs:=Bobjs); eauto 1].\n        generalize HinB; intros HinA; eapply Hsubst in HinA.\n        destruct HinA as [edge2 [HinA Hedge_subst2]].\n\n        rewrite edge_subst_spec_eq_l.\n        apply HinA.\n        eauto 1.\n        eauto 1.\n        eauto 1.\n        eapply ag_free_edge_free; [apply HAobjs | apply He2Free | apply HinA].\n      Qed.\n\n      \n\n      (* Now show that an ag_subst has the same mutability for free objs*)\n      Theorem mutable_ag_subst_spec :\n        forall D Dobjs, Seq.ag_objs_spec D Dobjs ->\n        forall D' D'objs, Seq.ag_objs_spec D' D'objs ->\n        forall e', ~ RefSet.In e' Dobjs ->\n        forall e, ag_subst_spec e e' D D' ->\n        forall M, mutable_spec D (RefSet.singleton e) M ->\n        forall M', mutable_spec D' (RefSet.singleton e') M' ->\n          RefSet.eq M' (RefSet.add e' (RefSet.remove e M)).\n      Proof.\n        intros D Dobjs HDobjs D' D'objs HD'objs e' He'Free e Hsubst M HM M' HM'.\n        case (Ref.eq_dec e e'); intros Hcase.\n        rewrite <- Hcase.\n        rewrite RefSetProps.add_remove; \n          [| eapply mutable_nondec; [apply HM| eapply RefSetFacts.singleton_iff; auto]].\n        eapply mutable_spec_eq_iff;\n          [eapply HM'\n            | \n            | apply RefSet.eq_refl\n            | eapply Proper_mutable_spec; \n              [apply AG.eq_refl | rewrite <- Hcase; apply RefSet.eq_refl | apply RefSet.eq_refl| apply HM]].\n        eapply AG.eq_sym; eapply ag_subst_spec_refl; eauto.\n\n        (* now e <> e' *)\n        intros m'.\n        RefSetFacts.set_iff.\n        rewrite (HM' m'); rewrite (HM m'); clear M M' HM HM'.\n        repeat progress rewrite RefSetFacts.singleton_iff.\n        case (Ref.eq_dec e' m'); intros Hcase'; try solve [intuition].\n        split; intros Hiff.\n        destruct Hiff as [Heq | [e0 [Heq Hin]]]; try contradiction.\n        rewrite RefSetFacts.singleton_iff in Heq; rewrite <- Heq in *; clear e0 Heq.\n        (* we know that e [<>] m', as ~ In e D'objs and In m' D'objs *)\n        generalize He'Free; intros HeFree.\n        eapply ag_subst_spec_free in HeFree; [\n          | eauto 1\n          | apply HD'objs\n          | eauto 1].\n        assert (~ Ref.eq e m') as Hneq by\n          (intros Hnot; rewrite Hnot in *; apply HeFree; apply HD'objs; \n            destruct Hin as [Hin | [Hin | [Hin | Hin]]]; do 2 eapply ex_intro; eauto).\n        unfold Ref.eq in *.\n        right; split; [right|auto].\n        apply ex_intro with e.\n        split ; [apply RefSetFacts.singleton_iff; auto|].\n\n        Ltac assert_neq_helper He'Free HDobjs :=\n          let Hnot := fresh \"Hnot\" in\n          intros Hnot; rewrite Hnot in *; apply He'Free; apply HDobjs; do 2 eapply ex_intro; eauto.\n\n        Ltac case_neq_helper H :=\n          destruct H as [[_ H] | H];\n            [apply Ref.eq_sym in H; contradiction H |intuition].\n\n        Ltac case_D'_impl_D Hsubst Hin e' He'Free HDobjs:=\n        eapply Hsubst in Hin;\n        destruct Hin as [edge Hin];\n        revert Hin;\n        let src := fresh \"src\" in let tgt := fresh \"tgt\" in let rgt := fresh \"rgt\" in\n        edge_destruct edge src tgt rgt;\n        let Hin := fresh \"Hin\" in let Hsrc := fresh \"Hsrc\" in\n        let Htgt := fresh \"Htgt\" in let Hrgt := fresh \"Hrgt\" in \n        intros [Hin [Hsrc [Htgt Hrgt]]];\n        repeat progress edge_simpl;\n        eapply AGFacts.In_eq_iff; [| apply Hin];\n        eapply Edges.edge_equal;\n          solve\n          [assert (~ Ref.eq src e') by (assert_neq_helper He'Free HDobjs); intuition\n            | assert (~ Ref.eq tgt e') by (assert_neq_helper He'Free HDobjs); intuition\n            | eapply Ref.eq_sym; solve[case_neq_helper Htgt|case_neq_helper Hsrc]\n            | apply AccessRight.eq_sym; auto].\n\n        do 3 (destruct Hin as [Hin | Hin]; [left; case_D'_impl_D Hsubst Hin e' He'Free HDobjs |right]);\n          case_D'_impl_D Hsubst Hin e' He'Free HDobjs.\n\n        (* flip *)\n        destruct Hiff as [Hnot | [[Hnot | [e0 [Heq Hin]]] Hneq]]; try contradiction.\n        eapply RefSetFacts.singleton_iff in Heq; rewrite <- Heq in *; clear e0 Heq.\n        right; apply ex_intro with e'; split; [eapply RefSetFacts.singleton_iff; auto |].\n\n        Ltac case_D_impl_D' Hsubst:= \n        eapply Hsubst;\n        eapply ex_intro; split; try solve [eauto];\n        split; repeat progress edge_simpl; [|split;[|apply AccessRight.eq_refl]]; try solve [intuition].\n\n        do 3 (destruct Hin as [Hin | Hin]; [left; case_D_impl_D' Hsubst |right]); case_D_impl_D' Hsubst.\n      Qed.\n\n      Theorem mutable_subset_objs :\n        forall D objs,  Seq.ag_objs_spec D objs ->\n          forall E M, mutable_spec D E M ->\n            RefSet.Subset M (RefSet.union E objs).\n      Proof.\n        intros D objs Hobjs E M HM x Hin.\n        apply HM in Hin.\n        RefSetFacts.set_iff.\n        destruct Hin as [Hin | Hin]; [left;auto|right].\n        destruct Hin as [e [HinE HinD]].\n        apply Hobjs.\n        destruct HinD as [HinD | [HinD | [HinD | HinD]]];\n        do 2 eapply ex_intro; eauto.\n      Qed.\n        \n\n\n\n      Theorem ag_subst_split:\n        forall A Aobjs, Seq.ag_objs_spec A Aobjs ->\n        forall e2, ~ RefSet.In e2 Aobjs ->\n        forall e1 B, ag_subst_spec e1 e2 A B -> \n        forall A', AG.Subset A' A ->\n        exists B', AG.Subset B' B /\\\n          ag_subst_spec e1 e2 A' B' /\\ \n          ag_subst_spec e1 e2 (AG.diff A A') (AG.diff B B').\n      Proof.\n        intros A Aobjs HAobjs e2 He2Free e1 B Hsubst A' Hsub.\n        eapply ex_intro.\n        split;[|split;[eapply ag_subst_spec_ag_subst|]].\n        intros edge. \n        edge_destruct edge src tgt rgt.\n        intros HinE.\n        eapply Hsubst.\n        eapply ag_subst_spec_ag_subst in HinE.\n        destruct HinE as [edge' HinA'].\n        revert HinA'; edge_destruct edge' src' tgt' rgt'; intros [HinA' Hsubst']; \n          repeat progress edge_simpl.\n        eapply Hsub in HinA'.\n        eapply ex_intro; split; eauto 1.\n\n        intros edge.\n        edge_destruct edge src tgt rgt.\n        split; AGFacts.set_iff; intros H.\n\n        destruct H as [HinB HninSubst].\n        eapply Hsubst in HinB.\n        destruct HinB as [edge HinA].\n        revert HinA; edge_destruct edge src' tgt' rgt'; intros [HinA Hsubst'].\n        eapply ex_intro; AGFacts.set_iff; split;[|eauto 1].\n        split; [eauto 1|].\n        intros Hnot; apply HninSubst.\n        eapply ag_subst_spec_ag_subst.\n        eapply ex_intro; eauto.\n\n        destruct H as [edge' HinA]; revert HinA; edge_destruct edge' src' tgt' rgt'; \n          AGFacts.set_iff; intros [[HinA HninA'] Hsubst'].\n        split.\n        eapply Hsubst; eapply ex_intro; eauto.\n        intros Hnot; apply HninA'.\n        eapply ag_subst_spec_ag_subst in Hnot.\n        destruct Hnot as [edge2 Hnot]; revert Hnot; edge_destruct edge2 src2 tgt2 rgt2.\n        intros [HinA' Hsubst2].\n\n        Ltac solve_eq_edge_l He2Free HAobjs := let Hnot := fresh \"Hnot\" in \n          intros Hnot; apply He2Free;\n            eapply HAobjs;\n              do 2 eapply ex_intro; rewrite Hnot; eauto 2.\n\n        rewrite edge_subst_spec_eq_l;\n          [apply HinA'\n            | eauto 1\n            | eapply ag_free_edge_free; [apply HAobjs | apply He2Free | apply HinA]\n            | eauto 1\n            | eapply ag_free_edge_free; [apply HAobjs | apply He2Free | apply Hsub; apply HinA']].\n      Qed.\n\n\n\n\n      Theorem ag_subst_union:\n        forall e1 e2 A B, ag_subst_spec e1 e2 A B -> \n        forall A' B', ag_subst_spec e1 e2 A' B' -> \n          ag_subst_spec e1 e2 (AG.union A A') (AG.union B B').\n      Proof.\n        intros e1 e2 A B Hsubst A' B' Hsubst'.\n        intros edge.\n        AGFacts.set_iff.\n        split; intros H.\n        destruct H as [H | H];\n        [eapply Hsubst in H | eapply Hsubst' in H];\n        (destruct H as [edge' [HinEdge' HsubstEdge']];\n          eapply ex_intro; AGFacts.set_iff; eauto).\n\n        destruct H as [edge' [HinEdge' HsubstEdge']]; \n          revert HinEdge'; AGFacts.set_iff; intros [HinEdge' | HinEdge'];\n            [left; eapply Hsubst |right; eapply Hsubst'];\n            (eapply ex_intro; eauto).\n      Qed.\n\n        Theorem edge_subst_ag_subst_singleton:\n          forall e1 e2 a b, edge_subst_spec e1 e2 a b <-> ag_subst_spec e1 e2 (AG.singleton a) (AG.singleton b).\n        Proof.\n          intros e1 e2 a b.\n          split; intros H.\n          intros edge; split; intros H'.\n          eapply AGFacts.singleton_iff in H'.\n          eapply ex_intro.\n          split; [eapply AGFacts.singleton_iff; apply Edge.eq_refl|].\n          eapply Proper_edge_subst_spec_iff;\n            [ apply Ref.eq_refl | apply Ref.eq_refl | apply Edge.eq_refl | apply Edge.eq_sym; apply H' | apply H].\n          destruct H' as [edge' [HinA Hedge']].\n          eapply AGFacts.singleton_iff in HinA.\n          rewrite AGFacts.singleton_iff.\n          eapply edge_subst_spec_eq;\n            [eapply Ref.eq_refl | apply Ref.eq_refl | apply HinA | apply H | apply Hedge'].\n\n          generalize (H b); clear H; intros [H _].\n          rewrite AGFacts.singleton_iff in H.\n          generalize (H (Edge.eq_refl _)); clear H; intros [edge [HinA Hedge]].\n          rewrite AGFacts.singleton_iff in HinA.\n          eapply Proper_edge_subst_spec_iff;\n            [ apply Ref.eq_refl | apply Ref.eq_refl | apply HinA | apply Edge.eq_refl | apply Hedge ].\n        Qed.\n\n        Hint Resolve edge_subst_ag_subst_singleton.\n\n      Theorem ag_subst_add:\n        forall e1 e2 A B, ag_subst_spec e1 e2 A B -> \n        forall a b, edge_subst_spec e1 e2 a b ->\n          ag_subst_spec e1 e2 (AG.add a A) (AG.add b B).\n      Proof.\n        intros e1 e2 A B Hsubst a b Hedge.\n        eapply Proper_ag_subst_spec_impl;\n          [apply Ref.eq_refl | apply Ref.eq_refl |\n            apply AG.eq_sym; eapply AGProps.add_union_singleton |\n              apply AG.eq_sym; eapply AGProps.add_union_singleton | ].\n        eapply ag_subst_union; eauto.\n        eapply edge_subst_ag_subst_singleton; auto.\n      Qed.\n\n      (* This combines the previous theorem and equality to help for trans *)\n      Theorem ag_subst_Add_eq:\n        forall e1 e2 A B, ag_subst_spec e1 e2 A B -> \n        forall a b, edge_subst_spec e1 e2 a b ->\n        forall A', AGProps.Add a A A' ->\n        forall B', ag_subst_spec e1 e2 A' B' ->\n          AGProps.Add b B B'.\n      Proof.\n        intros e1 e2 A B Hsubst a b Hedge A' HaddA' B' Hsubst'.\n        eapply ag_subst_add in Hsubst; [|eauto 1].\n        eapply ag_subst_spec_eq in Hsubst;\n          [ | apply Ref.eq_refl | apply Ref.eq_refl | | apply Hsubst'].\n        eapply AGAddEq.Add_eq_complete;\n          [apply Edge.eq_refl |  apply AG.eq_refl | apply AG.eq_sym; apply Hsubst | apply AGProps.Add_add ].\n        apply AG.eq_sym;\n        eapply AGAddEq.Eq_Add_complete;\n          [apply Edge.eq_refl |  apply AG.eq_refl | apply AGProps.Add_add | apply HaddA'].\n      Qed.\n\n      Theorem trans_ag_subst :\n        forall D Dobjs, Seq.ag_objs_spec D Dobjs ->\n        forall e', ~ RefSet.In e' Dobjs ->\n        forall e D', ag_subst_spec e e' D D' ->\n        forall D2, Seq.transfer D D2 ->\n        forall D2', ag_subst_spec e e' D2 D2' ->\n          Seq.transfer D' D2'.\n      Proof.\n        intros D Dobjs HDobjs e' He'free e D' Hsubst D2 Htrans D2' Hsubst2.\n        destruct Htrans.\n        (* self src *)\n        generalize H0; intros H0'.\n        eapply ag_subst_Add_eq in H0';\n          [ | apply Hsubst | apply edge_subst_spec_edge_subst | apply Hsubst2 ].\n        eapply Seq.transfer_self_src.\n        eapply Hsubst.\n        eapply ex_intro; split; [ apply H|].\n        eapply edge_subst_spec_edge_subst.\n        edge_simpl.\n        eapply H0'.\n        (* self tgt *)\n        generalize H0; intros H0'.\n        eapply ag_subst_Add_eq in H0;\n          [ | apply Hsubst | apply edge_subst_spec_edge_subst | apply Hsubst2 ].\n        eapply Seq.transfer_self_tgt.\n        eapply Hsubst.\n        eapply ex_intro; split; [ apply H|].\n        eapply edge_subst_spec_edge_subst.\n        edge_simpl.\n        eapply H0.\n        (* read *)\n        Ltac generalize_ag_subst_Add HAdd HAdd' Hsubst Hsubst2:=\n        generalize HAdd; intros HAdd';\n        eapply ag_subst_Add_eq in HAdd';\n          [ | apply Hsubst | apply edge_subst_spec_edge_subst | apply Hsubst2 ].\n        generalize_ag_subst_Add H1 HAdd' Hsubst Hsubst2.\n        Ltac solve_with_edge_subst Hsubst HinD :=\n        eapply Hsubst; eapply ex_intro; split; [ eapply HinD|eapply edge_subst_spec_edge_subst].\n        eapply Seq.transfer_read;\n          [ solve_with_edge_subst Hsubst H \n            | solve_with_edge_subst Hsubst H0\n            | eapply HAdd'].\n        (* write *)\n        generalize_ag_subst_Add H1 HAdd' Hsubst Hsubst2.\n        eapply Seq.transfer_write.\n        solve_with_edge_subst Hsubst H .\n        2: eapply HAdd'.\n        solve_with_edge_subst Hsubst H0.\n        (* send *)\n        generalize_ag_subst_Add H1 HAdd' Hsubst Hsubst2.\n        eapply Seq.transfer_send.\n        3: eapply HAdd'.\n        solve_with_edge_subst Hsubst H .\n        solve_with_edge_subst Hsubst H0.\n        (* reply *)\n        generalize_ag_subst_Add H0 HAdd' Hsubst Hsubst2.\n        eapply Seq.transfer_send_reply.\n        2: eapply HAdd'.\n        solve_with_edge_subst Hsubst H .\n        (* weak *)\n        generalize_ag_subst_Add H2 HAdd' Hsubst Hsubst2.\n        destruct H1 as [Hrgt | Hrgt]; rewrite Hrgt in *.\n        eapply Seq.transfer_weak.\n        4: eapply HAdd'.\n        3: intuition (eapply Hrgt).\n        edge_simpl; solve_with_edge_subst Hsubst H .\n        edge_simpl; solve_with_edge_subst Hsubst H0 .\n        eapply Seq.transfer_weak.\n        4: eapply HAdd'.\n        3: right; apply Hrgt.\n        edge_simpl; solve_with_edge_subst Hsubst H .\n        repeat progress (edge_simpl). rewrite Hrgt. solve_with_edge_subst Hsubst H0 .\n      Qed.\n\n\n      (* *)\n\nTheorem ag_subst_spec_free_eq : \n  forall A Aobjs, Seq.ag_objs_spec A Aobjs ->\n  forall e2, ~ RefSet.In e2 Aobjs ->\n  forall A' A'objs, Seq.ag_objs_spec A' A'objs ->\n    ~ RefSet.In e2 A'objs ->\n  forall e1 B, ag_subst_spec e1 e2 A B ->\n  forall B', ag_subst_spec e1 e2 A' B' ->\n    (AG.eq A A' <-> AG.eq B B').\nProof.\n  intros A Aobjs HAobjs e2 He2Free A' A'objs HA'objs He2Free' e1 B Hsubst B' Hsubst'.\n  split; intros H.\n  eapply ag_subst_spec_eq; eauto; solve [apply Ref.eq_refl].\n\n  generalize (Seq.ag_objs_spec_ag_objs B); generalize (Seq.ag_objs B); intros Bobjs HBobjs.\n  generalize Hsubst; intros He1Free.\n  eapply ag_subst_spec_free in He1Free; eauto 1.\n\n  eapply ag_subst_free_sym in Hsubst; eauto 1.\n  eapply ag_subst_free_sym in Hsubst'; eauto 1.\n\n  eapply ag_subst_spec_eq; eauto; solve [apply Ref.eq_refl].\nQed.\n\n\n      Theorem potTransfer_ag_subst :\n        forall D Dobjs, Seq.ag_objs_spec D Dobjs ->\n        forall e', ~ RefSet.In e' Dobjs ->\n        forall e D', ag_subst_spec e e' D D' ->\n        forall D2, Seq.potTransfer D D2 ->\n        forall D2', ag_subst_spec e e' D2 D2' ->\n          Seq.potTransfer D' D2'.\n      Proof.\n        intros D Dobjs HDobjs e' He'Free e D' Hsubst D2 HpotTransfer.\n        induction HpotTransfer as [C H | C B HpotTransfer IH Htrans]; intros D2' Hsubst2. \n        eapply ag_subst_spec_eq in Hsubst;\n          [eapply Seq.potTransfer_base; apply AG.eq_sym; apply Hsubst\n            | apply Ref.eq_refl\n            | apply Ref.eq_refl\n            | apply AG.eq_sym; apply H\n            | apply Hsubst2].\n        generalize (IH _ (ag_subst_spec_ag_subst _ _ _)); clear IH; intros IH.\n        eapply trans_ag_subst in Htrans;\n          [ \n            | eapply ag_objs_spec_potTransfer; [apply HDobjs | apply HpotTransfer]\n            | apply He'Free\n            | eapply ag_subst_spec_ag_subst\n            | eapply Hsubst2].\n        eapply Seq.potTransfer_trans; eauto.\n      Qed.\n\n        Theorem maxTransfer_ag_subst_spec :\n          forall P, Seq.maxTransfer P ->\n          forall Pobjs, Seq.ag_objs_spec P Pobjs ->\n          forall e', ~ RefSet.In e' Pobjs ->\n          forall e P', ag_subst_spec e e' P P' ->\n            Seq.maxTransfer P'.\n          Proof.\n            intros P HP Pobjs HPobjs e' He'Free e P' Hsubst D Htrans.\n            generalize (Seq.ag_objs_spec_ag_objs P'); generalize (Seq.ag_objs P'); intros P'objs HP'objs.\n            generalize HP'objs; intros HeFree.\n            eapply ag_subst_spec_free in HeFree;\n              [ | apply HPobjs | apply He'Free | apply Hsubst].\n            \n            generalize Htrans; intros HDobjs.\n            eapply ag_objs_spec_transfer in HDobjs; [|apply HP'objs].\n\n            generalize Hsubst; intros HsubstRev;\n            eapply ag_subst_free_sym in HsubstRev; eauto 1.\n            \n            eapply trans_ag_subst in Htrans;\n            [ | apply HP'objs | apply HeFree | apply HsubstRev | apply ag_subst_spec_ag_subst ].\n            \n            eapply HP in Htrans.\n            eapply Proper_ag_subst_spec_impl in HsubstRev;\n              [ | apply Ref.eq_refl | apply Ref.eq_refl | apply AG.eq_refl | apply Htrans].\n\n            eapply Proper_ag_objs_spec in HPobjs;\n            [ | apply AG.eq_sym; apply Htrans | apply RefSet.eq_refl].\n            \n            generalize (ag_subst_spec_ag_subst e' e D); intros HsubstRev'.\n\n            eapply ag_subst_free_sym in HsubstRev; eauto 1.\n            eapply ag_subst_free_sym in HsubstRev';\n              [ | apply HDobjs | apply HeFree].\n\n            eapply ag_subst_spec_eq;\n              [ apply Ref.eq_refl| apply Ref.eq_refl| apply AG.eq_refl| eauto 1 | eauto 1].\n\n          Qed.\n\n\n\n      Theorem ag_subst_potAcc:\n        forall D Dobjs, Seq.ag_objs_spec D Dobjs ->\n        forall e', ~ RefSet.In e' Dobjs ->\n        forall D' e, ag_subst_spec e e' D D' -> \n        forall P, Seq.potAcc D P ->\n        forall P', Seq.potAcc D' P' ->\n          ag_subst_spec e e' P P'.\n      Proof.\n        intros D Dobjs HDobjs e' He'Free D' e Hsubst P HP P' HP'.\n\n        generalize (Seq.ag_objs_spec_ag_objs D'); generalize (Seq.ag_objs D'); intros D'objs HD'objs.\n        generalize He'Free; intros HeFree;\n        eapply ag_subst_spec_free in HeFree; [\n          | eauto 1\n          | apply HD'objs\n          | eauto 1].\n\n        destruct HP as [Htrans Hmax]; destruct HP' as [Htrans' Hmax'].\n\n\n(* \nThis should work.\n\nBy ag_objs_spec_potTransfer : Seq.ag_objs_spec P Dobjs /\\ Seq.ag_objs_spec P' D'objs.\nBy ag_subst_spec_ag_subst : ag_subst_spec e e' P (ag_subst e e' P)\nBy potTransfer_ag_subst: potTransfer D' (ag_subst e e' P).\nTherefore: Seq.maxPotTransfer P' -> Seq.potTransfer D' P' -> Seq.potTransfer D' (ag_subst e e' P) ->\n    P' [=] (ag_subst e e' P)\nBy ag_subst_spec_eq, the goal becomes ag_subst_spec e e' P (ag_subst e e' P) which is of course\nag_subst_spec_ag_subst.\n\n*)\n\n        generalize Htrans; intros HPobjs; eapply ag_objs_spec_potTransfer in HPobjs; [|eapply HDobjs].\n        generalize Htrans'; intros HP'objs; eapply ag_objs_spec_potTransfer in HP'objs; [|eapply HD'objs].\n        generalize (ag_subst_spec_ag_subst e e' P); intros HPsubst.\n        generalize HPsubst; intros HPsubst'.\n        eapply maxTransfer_ag_subst_spec in HPsubst';\n          [ | apply Seq.maxTransfer_maxPotTransfer; eauto | eauto |  eauto].\n\n        eapply potTransfer_ag_subst in HPsubst;\n          [ | apply HDobjs | apply He'Free | apply Hsubst | apply Htrans].\n        \n        eapply Proper_ag_subst_spec_impl;\n          [ eapply Ref.eq_refl | eapply Ref.eq_refl | eapply AG.eq_refl | | apply ag_subst_spec_ag_subst].\n\n        eapply potAcc_equiv;\n          [apply AG.eq_refl | split; [apply HPsubst | apply Seq.maxTransfer_maxPotTransfer; eauto] | split; eauto].\n      Qed.\n\n      Theorem mutable_ag_subst_spec_diff :\n        forall D Dobjs, Seq.ag_objs_spec D Dobjs ->\n        forall D' D'objs, Seq.ag_objs_spec D' D'objs ->\n        forall e, ~ RefSet.In e D'objs ->\n        forall e', ~ RefSet.In e' Dobjs ->\n          ag_subst_spec e e' D D' ->\n        forall P, Seq.potAcc D P ->\n        forall P', Seq.potAcc D' P' ->\n        forall M, mutable_spec P (RefSet.singleton e) M ->\n        forall M', mutable_spec P' (RefSet.singleton e') M' ->\n          RefSet.eq (RefSet.diff M (RefSet.singleton e)) (RefSet.diff M' (RefSet.singleton e')).\n      Proof.\n        intros D Dobjs HDobjs D' D'objs HD'objs e HeFree e' He'Free Hsubst P HP P' HP' M HM M' HM'.\n        repeat progress rewrite <- RefSetProps.remove_diff_singleton.\n        rewrite mutable_ag_subst_spec with (D:=P) (D':=P') (M:=M) (M':=M');\n          try solve [eapply ag_objs_spec_potTransfer; [apply HDobjs|apply HP]\n            | eapply ag_objs_spec_potTransfer; [apply HD'objs|apply HP']\n              | eapply ag_subst_potAcc; eauto 2\n              | eauto 2].\n        rewrite RefSetProps.remove_add; [apply RefSet.eq_refl|].\n        RefSetFacts.set_iff.\n        intros [HinM Hneq].\n        eapply mutable_subset_objs in HinM;\n          [ | eapply ag_objs_spec_potTransfer; [apply HDobjs|apply HP] | apply HM].\n        revert HinM; RefSetFacts.set_iff; intros [HinM | HinM]; contradiction.\n        eapply ag_subst_potAcc;\n        [ apply HDobjs | apply He'Free | apply Hsubst | apply HP | apply HP'].\n      Qed.\n\n      Theorem mutable_ag_fully_authorized_singleton:\n        forall D objs, Seq.ag_objs_spec D objs ->\n        forall C T, capset_targets C T ->\n        forall e, ~ RefSet.In e objs -> ~ RefSet.In e T ->\n        forall e', ~ RefSet.In e' objs -> ~ RefSet.In e' T ->\n        forall A, ag_fully_authorized_spec D (RefSet.singleton e) C A ->\n        forall A', ag_fully_authorized_spec D (RefSet.singleton e') C A' ->\n        forall P, Seq.potAcc A P ->\n        forall P', Seq.potAcc A' P' ->\n        forall M, mutable_spec P (RefSet.singleton e) M ->\n        forall M', mutable_spec P' (RefSet.singleton e') M' ->\n          RefSet.eq (RefSet.diff M (RefSet.singleton e)) (RefSet.diff M' (RefSet.singleton e')).\n        Proof.\n          intros D objs Hobjs C T HT e HeNodes HeTargets e' HeNodes' HeTargets' A Hauth A' Hauth'\n            P HP P' HP' M HM M' HM'.\n          (* first by eq_dec e e' cases *)\n          case (Ref.eq_dec e e'); intros Hcase; [rewrite <- Hcase in *|].\n          rewrite mutable_spec_eq_iff with (m := M');\n            [apply RefSet.eq_refl\n              | eauto 1\n              | eapply potAcc_equiv; try solve [apply HP | apply HP'];\n                eapply ag_fully_authorized_spec_eq; \n                  solve [apply AG.eq_refl | apply RefSet.eq_refl | apply CapSet.eq_refl | eauto 1]\n              | apply RefSet.eq_refl\n              | apply HM ].\n\n          (* e [<>] e' *)\n\n          Ltac not_in_ag_objs_ag_fully_authorized Hauth' HeNodes Hobjs:=\n            let Hnot := fresh \"Hnot\" in \n          intros Hnot;\n          rewrite ag_objs_ag_fully_authorized in Hnot;\n            [ \n              | eauto 1\n              | let Hnot := fresh \"Hnot\" in \n                intros Hnot; eapply Hnot; apply RefSetFacts.singleton_iff; apply Ref.eq_refl\n              | apply ag_remainder_spec_iff\n              | apply Seq.ag_objs_spec_ag_objs\n              | apply Hauth'\n              | apply Seq.ag_objs_spec_ag_objs];\n           revert Hnot; RefSetFacts.set_iff; intros Hnot;\n              destruct Hnot as [Hnot | [Hnot | Hnot]]; try solve [contradict Hnot; eauto];\n              apply HeNodes; apply Hobjs;\n              apply Seq.ag_objs_spec_ag_objs in Hnot;\n              let obj := fresh \"obj\" in let rgt := fresh \"rgt\" in\n              destruct Hnot as [obj [rgt [Hnot|Hnot]]];\n              eapply ag_remainder_spec_iff in Hnot;\n              destruct Hnot as [Hnot _];\n              do 2 eapply ex_intro; eauto.\n\n          eapply mutable_ag_subst_spec_diff;\n            [ eapply Seq.ag_objs_spec_ag_objs\n              | eapply Seq.ag_objs_spec_ag_objs\n              | not_in_ag_objs_ag_fully_authorized Hauth' HeNodes Hobjs\n              | not_in_ag_objs_ag_fully_authorized Hauth HeNodes' Hobjs\n              | eapply ag_fully_authorized_spec_singleton_ag_subst_spec; eauto 1\n              | eauto 1\n              | eauto 1\n              | eauto 1\n              | eauto 1\n            ]. \n        Qed.\n\n    Theorem ag_objs_ag_remainder_subset:\n      forall D Nd, Seq.ag_objs_spec D Nd ->\n      forall E R, ag_remainder_spec D E R ->\n      forall Nr, Seq.ag_objs_spec R Nr ->\n        RefSet.Subset Nr (RefSet.diff Nd E).\n    Proof.\n      intros D Nd HNd E R HR Nr HNr x.\n      RefSetFacts.set_iff.\n      rewrite (HNr x); rewrite (HNd x); \n      intros [obj [rgt [HinR | HinR]]];\n      (eapply HR in HinR;\n      destruct HinR as [HinD [HninS HninT]]; edge_simpl;\n      split; [do 2 eapply ex_intro; eauto | eauto]).\n    Qed.\n\n\n\n    (* Since we know M' [=] (union M (diff E' E)) ,\n       Our goal is:\n         (M + (E' - E)) - E' [=] M - E\n         ((E' - E) + M) - E' [=] M - E)\n       We know:\n         E [<=] M and E [<=] E'.\n       This means:\n         E [<=] M -> M [=] ((M - E) + E)\n       By subst, our goal is:\n         ((E' - E) + M) - E' [=] M - E)\n         ((E' - E) + (M - E) + E) - E' [=] M - E.\n       Notice that we are unioning 3 disjoint sets: (diff E' E) (diff M E) and E, and subtracting E' from all.\n       By subset replacement\n         E [<=] E' -> E' [=] (E' - E) + E\n       By subst:\n         ((E' - E) + (M - E) + E) - ((E' - E) + E) [=] M - E.\n         ((M - E) + (E' - E) + E) - ((E' - E) + E) [=] M - E.\n         ((M - E) + ((E' - E) + E)) - ((E' - E) + E) [=] M - E.\n       Because of disjointness, the common factors cancel out:\n         ((M - E) + ((E' - E) + E)) - ((E' - E) + E) [=] M - E.\n         M - E [=] M - E\n         Refl.\n        *)\n\n\n    (* The constraint (RefSet.Empty (RefSet.inter E objs)) will evaporate by using the remainder *)\n  Theorem ag_fully_authorized_mutable_subset_eq_diff :\n    forall D objs, Seq.ag_objs_spec D objs ->\n    forall N, RefSet.Subset objs N ->\n    forall E, ~ RefSet.Empty E ->\n      RefSet.Empty (RefSet.inter E objs) ->\n      RefSet.Subset E N ->\n    forall E', RefSet.Subset E E' ->\n      filtered_subset_eq E E' N ->\n    forall C T, capset_targets C T -> \n      RefSet.Subset T N ->\n    forall A, ag_fully_authorized_spec D E C A ->\n    forall A', ag_fully_authorized_spec D E' C A' ->\n    forall P, Seq.potAcc A P ->\n    forall P', Seq.potAcc A' P' ->\n    forall M, mutable_spec P E M ->\n    forall M', mutable_spec P' E' M' ->\n    RefSet.eq (RefSet.diff M' E') (RefSet.diff M E).\n  Proof.\n    intros D objs Hobjs N HN E Hnonempty Hdisj HE E' HE' Hfilt \n      C T HT HsubT A Hauth A' Hauth' P HP P' HP' M HM M' HM'.\n    rewrite ag_fully_authorized_subset_mutable_eq with (M':=M'). \n\n    2: eauto 1.\n    2: eauto 1.\n    2: eauto 1.\n    2: eauto 1.\n    2: eauto 1.\n    2: eauto 1.\n    2: eauto 1.\n    2: eauto 1.\n    2: eauto 1.\n    2: eauto 1.\n    2: apply Seq.ag_objs_spec_ag_objs.\n    3: eauto 1.\n    3: eauto 1.\n    3: eauto 1.\n    3: eauto 1.\n    3: eauto 1.\n\n    2: rewrite ag_objs_ag_fully_authorized.\n    3: eauto 1.\n    3: eauto 1.\n    3: eapply ag_remainder_spec_iff.\n    3: eapply Seq.ag_objs_spec_ag_objs.\n    3: eauto 1.\n    3: eapply Seq.ag_objs_spec_ag_objs.\n\n    2: intros n; RefSetFacts.set_iff; intros Hn;\n    destruct Hn as [Hn | [Hn | Hn]]; try solve [eauto 2];\n    eapply HN; eapply Hobjs;\n    eapply Seq.ag_objs_spec_ag_objs in Hn; destruct Hn as [obj [rgt [HinD | HinD]]];\n    eapply ag_remainder_spec_iff in HinD; destruct HinD as [HinD _];\n    do 2 eapply ex_intro; eauto 2.\n\n    intros a.\n    RefSetFacts.set_iff.\n    split; intros H; [intuition|].\n    destruct H as [HinM HninE].\n    case (RefSetProps.In_dec a E'); intros HinE'; [| intuition].\n    eapply filtered_subset_eq_iff_filtered_subset_eq' in Hfilt.\n    edestruct (Hfilt a) as [H | H]; [|destruct H as [HinN Heq]; eapply Heq in HinE'; contradiction].\n    (* a must be in N,\n       M is a subset of (union E (ag_objs P))\n       ~ In a E, so this reduces to In a (ag_objs P)\n       By potAcc_objs , we can reduce to In a (ag_objs A)\n       We know the objs of A, which are the objs of the remainder, E, and T.\n       T is a subset of N, E is a subset of N, and objs is a subset of N.\n       the remainder objs are a subset of objs, so we are good.\n       *)\n\n    contradict H.\n\n    eapply mutable_subset_objs in HinM;\n      [ | eapply ag_objs_spec_potTransfer; [eapply Seq.ag_objs_spec_ag_objs| apply HP] | eapply HM].\n\n\n    rewrite ag_objs_ag_fully_authorized with (Aobjs:=(Seq.ag_objs A)) in HinM; \n      try solve [eauto 1 | eapply ag_remainder_spec_iff].\n\n    revert HinM; RefSetFacts.set_iff.\n    intros [H | [H | H]]; try solve [intuition].\n    idtac.\n    eapply ag_objs_ag_remainder_subset in H; try solve [eauto 1 | apply ag_remainder_spec_iff].\n    revert H; RefSetFacts.set_iff; intros [H H']; auto.\nQed.\n\n\n\n(*\n\n   For reference, here are the current signatures:\n\n      Theorem mutable_ag_fully_authorized_singleton:\n        forall D objs, Seq.ag_objs_spec D objs ->\n        forall C T, capset_targets C T ->\n        forall e, ~ RefSet.In e objs -> ~ RefSet.In e T ->\n        forall e', ~ RefSet.In e' objs -> ~ RefSet.In e' T ->\n        forall A, ag_fully_authorized_spec D (RefSet.singleton e) C A ->\n        forall A', ag_fully_authorized_spec D (RefSet.singleton e') C A' ->\n        forall P, Seq.potAcc A P ->\n        forall P', Seq.potAcc A' P' ->\n        forall M, mutable_spec P (RefSet.singleton e) M ->\n        forall M', mutable_spec P' (RefSet.singleton e') M' ->\n          RefSet.eq (RefSet.diff M (RefSet.singleton e)) (RefSet.diff M' (RefSet.singleton e')).\n\n  Theorem ag_fully_authorized_mutable_subset_eq_diff :\n    forall D objs, Seq.ag_objs_spec D objs ->\n    forall N, RefSet.Subset objs N ->\n    forall E, ~ RefSet.Empty E ->\n      RefSet.Empty (RefSet.inter E objs) ->\n      RefSet.Subset E N ->\n    forall E', RefSet.Subset E E' ->\n      filtered_subset_eq E E' N ->\n    forall C T, capset_targets C T -> \n      RefSet.Subset T N ->\n    forall A, ag_fully_authorized_spec D E C A ->\n    forall A', ag_fully_authorized_spec D E' C A' ->\n    forall P, Seq.potAcc A P ->\n    forall P', Seq.potAcc A' P' ->\n    forall M, mutable_spec P E M ->\n    forall M', mutable_spec P' E' M' ->\n    RefSet.eq (RefSet.diff M' E') (RefSet.diff M E).\n\nWe know that:\n  exists e, In e E /\\ exists e', In e' E'.\nBy disjoint intersection,\n  ~ In e objs /\\ ~ In e' objs /\\ ~ In e T /\\ ~ In e' T.\nWe can instantiate mutable_ag_fully_auhorized_singleton.\n  (mutable (potAcc (ag_fully_authorized D {e} C)) {e}) - {e}\n    [=]\n  (mutable (potAcc (ag_fully_authorized D {e'} C))) {e'}) - {e'}\n\nBecause {e} [<=] E, we can instantiate ag_fully_authorizeed_mutable_subst_eq_diff.\nPlease note that choosing the correct N is essential.\nChoose N := (N - E + {e})\nSuch an N is always a superset of T, as we have assumed it E and E' are disjoint from T,\nso there is no need to worry about the ~ In e T /\\ ~ In e' T assumptions in earlier theorems.\nThis satisfies the appropriate properties and is disjoint and filtered in the correct ways.\n\n  (mutable (potAcc (ag_fully_authorized D E C)) E) - E\n    [=] \n  (mutable (potAcc (ag_fully_authorized D {e} C)) {e}) - {e}\n\nRun this again for {e'} [<=] E':\n\n  (mutable (potAcc (ag_fully_authorized D E C)) E') - E'\n    [=] \n  (mutable (potAcc (ag_fully_authorized D {e'} C)) {e'}) - {e'}\n\nBy transitivity:\n\n  (mutable (potAcc (ag_fully_authorized D E C)) E') - E'\n    [=] \n  (mutable (potAcc (ag_fully_authorized D {e'} C)) {e'}) - {e'}\n    [=]\n  (mutable (potAcc (ag_fully_authorized D {e} C)) {e}) - {e}\n    [=] \n  (mutable (potAcc (ag_fully_authorized D E C)) E) - E\n\nWhich yields our main result!\n\n*)\n\n  Theorem ag_fully_authorized_mutable_eq_diff :\n    forall D objs, Seq.ag_objs_spec D objs ->\n    forall N, RefSet.Subset objs N ->\n    forall E, ~ RefSet.Empty E ->\n      RefSet.Empty (RefSet.inter E objs) ->\n    forall E', ~ RefSet.Empty E' ->\n      RefSet.Empty (RefSet.inter E' objs) ->\n      filtered_subset_eq E E' N ->\n    forall C T, capset_targets C T -> \n      RefSet.Subset T N ->\n      RefSet.Empty (RefSet.inter E T) ->\n      RefSet.Empty (RefSet.inter E' T) ->\n    forall A, ag_fully_authorized_spec D E C A ->\n    forall A', ag_fully_authorized_spec D E' C A' ->\n    forall P, Seq.potAcc A P ->\n    forall P', Seq.potAcc A' P' ->\n    forall M, mutable_spec P E M ->\n    forall M', mutable_spec P' E' M' ->\n    RefSet.eq (RefSet.diff M' E') (RefSet.diff M E).\n  Proof.\n    intros D objs Hobjs N HN E HE HdisjE E' HE' HdisjE' Hfilt C T HT HsubT HdisjE2 HdisjE2' A Hauth A' Hauth'\n      P HP P' HP' M HM M' HM'.\n\n    generalize HE HE'; intros HE2 HE'2;\n      eapply RefSetAddEq_nonempty_exists in HE2;\n        eapply RefSetAddEq_nonempty_exists in HE'2;\n          destruct HE2 as [e HeinE]; destruct HE'2 as [e' He'inE].\n\n    eapply RefSet.eq_trans.\n    eapply ag_fully_authorized_mutable_subset_eq_diff with \n      (N := (RefSet.add e' (RefSet.diff N E'))) (E:= (RefSet.singleton e')).\n    15: apply HM'.\n    13: apply HP'.\n    11: apply Hauth'.\n    8: apply HT.\n    11: apply mutable_spec_mutable.\n    10: apply Seq.potAcc_potAcc_fun.\n    9: apply ag_fully_authorized_spec_iff.\n    3: intros Hnot; eapply Hnot; apply RefSetFacts.singleton_iff; apply Ref.eq_refl.\n    apply Hobjs.\n    intros n HinNodes; RefSetFacts.set_iff;\n      right; split; [eapply HN; auto | intros Hnot; eapply HdisjE'; RefSetFacts.set_iff; eauto 2].\n    intros n; RefSetFacts.set_iff;\n      intros [Heq HinN]; rewrite Heq in He'inE; eapply HdisjE'; RefSetFacts.set_iff; eauto 2. \n    intros n Hin; apply RefSetFacts.singleton_iff in Hin; rewrite <- Hin;\n      apply RefSetFacts.add_iff; auto.\n    intros n Hin; apply RefSetFacts.singleton_iff in Hin; rewrite <- Hin; auto.\n\n    2: intros n Hin; generalize (HsubT n) (HdisjE2 n) (HdisjE2' n); RefSetFacts.set_iff;\n      do 2 (rewrite Sumbool_not_and; Sumbool_decide; try apply RefSetProps.In_dec); tauto.\n\n    eapply filtered_subset_eq_iff_filtered_subset_eq'.\n    eapply filtered_subset_eq_iff_filtered_subset_eq' in Hfilt.\n    intros n; RefSetFacts.set_iff.\n    case (Ref.eq_dec e' n); intros HcaseEq; [rewrite <- HcaseEq; tauto|].\n    generalize (Hfilt n); intros [HninN | [HinN Hiff]];\n      (rewrite Sumbool_not_or; Sumbool_decide; try solve [auto | apply RefSetProps.In_dec];\n        rewrite Sumbool_not_and; Sumbool_decide; try solve [auto | apply RefSetProps.In_dec]).\n    rewrite <- Sumbool_dec_not_not_iff; Sumbool_decide; try solve [auto | apply RefSetProps.In_dec].\n    case (RefSetProps.In_dec n E'); intros HcaseE; try tauto.\n\n    (* This concludes one equivdlance *)\n\n    eapply RefSet.eq_sym; eapply RefSet.eq_trans.\n    eapply ag_fully_authorized_mutable_subset_eq_diff with \n      (N := (RefSet.add e (RefSet.diff N E))) (E:= (RefSet.singleton e)).\n\n    15: apply HM.\n    13: apply HP.\n    11: apply Hauth.\n    8: apply HT.\n    11: apply mutable_spec_mutable.\n    10: apply Seq.potAcc_potAcc_fun.\n    9: apply ag_fully_authorized_spec_iff.\n    3: intros Hnot; eapply Hnot; apply RefSetFacts.singleton_iff; apply Ref.eq_refl.\n    apply Hobjs.\n    intros n HinNodes; RefSetFacts.set_iff;\n      right; split; [eapply HN; auto | intros Hnot; eapply HdisjE; RefSetFacts.set_iff; eauto 2].\n    intros n; RefSetFacts.set_iff;\n      intros [Heq HinN]; rewrite Heq in HeinE; eapply HdisjE; RefSetFacts.set_iff; eauto 2. \n    intros n Hin; apply RefSetFacts.singleton_iff in Hin; rewrite <- Hin;\n      apply RefSetFacts.add_iff; auto.\n    intros n Hin; apply RefSetFacts.singleton_iff in Hin; rewrite <- Hin; auto.\n\n    2: intros n Hin; generalize (HsubT n) (HdisjE2 n) (HdisjE2' n); RefSetFacts.set_iff;\n      do 2 (rewrite Sumbool_not_and; Sumbool_decide; try apply RefSetProps.In_dec); tauto.\n\n    eapply filtered_subset_eq_iff_filtered_subset_eq'.\n    eapply filtered_subset_eq_iff_filtered_subset_eq' in Hfilt.\n    intros n; RefSetFacts.set_iff.\n    case (Ref.eq_dec e n); intros HcaseEq; [rewrite <- HcaseEq; tauto|].\n    generalize (Hfilt n); intros [HninN | [HinN Hiff]];\n      (rewrite Sumbool_not_or; Sumbool_decide; try solve [auto | apply RefSetProps.In_dec];\n        rewrite Sumbool_not_and; Sumbool_decide; try solve [auto | apply RefSetProps.In_dec]).\n    rewrite <- Sumbool_dec_not_not_iff; Sumbool_decide; try solve [auto | apply RefSetProps.In_dec].\n    case (RefSetProps.In_dec n E); intros HcaseE; try tauto.\n\n    (* We are now down to the singleton case *)\n\n    eapply mutable_ag_fully_authorized_singleton.\n    apply Hobjs.\n    apply HT.\n    intros Hnot; eapply HdisjE; RefSetFacts.set_iff; eauto.\n    intros Hnot; eapply HdisjE2; RefSetFacts.set_iff; eauto.\n    intros Hnot; eapply HdisjE'; RefSetFacts.set_iff; eauto.\n    intros Hnot; eapply HdisjE2'; RefSetFacts.set_iff; eauto.\n    eapply ag_fully_authorized_spec_iff.\n    eapply ag_fully_authorized_spec_iff.\n    eapply Seq.potAcc_potAcc_fun.\n    eapply Seq.potAcc_potAcc_fun.\n    eapply mutable_spec_mutable.\n    eapply mutable_spec_mutable.\n  Qed.\n\nTheorem Proper_ag_remainder_spec_impl: Proper (AG.eq ==> RefSet.eq ==> AG.eq ==> impl) ag_remainder_spec.\nProof.\n  unfold Proper; unfold respectful; unfold impl; unfold ag_remainder_spec; intros.\n  eapply iff_trans.\n  eapply iff_sym; eapply H1; clear H1.\n  eapply iff_trans; [eapply H2|clear H2].\n  rewrite (H edge); clear H.\n  split; intros [Hedge Hexclude]; (split ; [apply Hedge|eapply Proper_excluded_edge; eauto;\n    solve [ apply H0 |apply RefSet.eq_sym; apply H0]]).\nQed.\n\n\nTheorem Proper_ag_remainder_spec_iff: Proper (AG.eq ==> RefSet.eq ==> AG.eq ==> iff) ag_remainder_spec.\nProof.\n  split; eapply Proper_ag_remainder_spec_impl; eauto;\n  solve [apply AG.eq_sym; auto | apply RefSet.eq_sym; auto].\nQed.\n\n      Theorem ag_authorized_remainder_eq_simpl :\n        forall D E C A, ag_fully_authorized_spec D E C A ->\n          forall D', ag_remainder_spec D E D' ->\n            ag_fully_authorized_spec D' E C A.\n      Proof.\n        intros D E C A Hauth D' Hrem.\n        eapply ag_authorized_remainder in Hauth.\n        2: apply ag_fully_authorized_spec_iff.\n        eapply Proper_ag_fully_authorized_spec.\n        4: apply Hauth.\n        4: apply ag_fully_authorized_spec_iff.\n        2: apply RefSet.eq_refl.\n        2: apply CapSet.eq_refl.\n        apply AG.eq_sym. eapply ag_remainder_spec_eq in Hrem.\n        apply Hrem.\n        apply AG.eq_refl.\n        apply RefSet.eq_refl.\n        apply ag_remainder_spec_iff.\n \n      Qed.\n\n\n      Theorem extant_capabilities_targets:\n        forall C S, extant_capabilities C S ->\n        forall T, capset_targets C T ->\n        forall Ex, obj_existed Ex S ->\n          RefSet.Subset T Ex.\n        Proof.\n          intros C S Hextant T HT Ex HEx x HinT.\n          eapply HEx.\n          eapply Hextant.\n          eapply capset_targets_eq;\n            [apply CapSet.eq_refl\n              | apply capset_targets_iff_f\n              | apply HT\n              | apply HinT].\n        Qed.\n\n  (* \n     This isn't quite right.  ag_fully_authorized adds all caps of C to A', but we've lost the ability to know\n     if they are invalid.  This doesn't invalidate the result, because the confinement is still an upper bound.\n     We should restrict the confinement question to be only those capabilities that are currently valid.\n     The problem with this restriction is that the test will not pass as those invalid caps are not approved.\n     We can't form an equivalence of confinement, and we can't form an equivalence of fully authorized ag.\n     We need to redefine one of these.\n     We need to modify the confinement test to ignore the other forms of non-mutating capabilities, namely\n     those referenceing objects that are not alive.\n     \n     *)\n  Theorem confined_subsystem_mutability_subset_any_fully_authroized_mutability:\n    forall E, ~ RefSet.Empty E ->\n    forall C S, authorized_confined_subsystem C E S ->\n    forall D, dirAcc_spec S D ->\n    forall Ex, obj_existed Ex S ->\n    forall E', ~ RefSet.Empty E' ->\n    novel_capabilities C E' ->\n    RefSet.Empty (RefSet.inter E' (RefSet.diff Ex E)) ->\n    forall R, ag_remainder_spec D E R ->\n    forall A', ag_fully_authorized_spec R E' C A' ->\n    forall P, Seq.potAcc D P ->\n    forall P', Seq.potAcc A' P' ->\n    forall M, mutable_spec P E M ->\n    forall M', mutable_spec P' E' M' ->\n    RefSet.Subset (RefSet.diff M E) (RefSet.diff M' E').\n    Proof.\n      intros E Hnonempty C S [Hnovel [Hextant Hconf]] D Hda Ex HEx E' Hnonempty' Hnovel'\n        Hfilter R Hrem A' Hauth' P Hpa P' Hpa' M Hmut M' Hmut'.\n\n      generalize (ag_fully_authorized_spec_iff D E C); generalize (ag_fully_authorized D E C); intros A2 Hauth2.\n      generalize (Seq.potAcc_potAcc_fun A2); generalize (Seq.potAcc_fun A2); intros P2 Hpa2.\n      generalize (mutable_spec_mutable P2 E); generalize (mutable P2 E); intros M2 Hmut2.\n\n      generalize (confined_subsystem_mutable _ _ _ Hconf _ Hda _ Hauth2 _ Hpa _ Hpa2 _ Hmut _ Hmut2 );\n        intros HmutSub.\n\n      assert (RefSet.Subset (RefSet.diff M E) (RefSet.diff M2 E)) as Hsubdiff by\n      (intros x; RefSetFacts.set_iff; intros [HinM HninE]; eapply HmutSub in HinM; auto).\n\n      eapply RefSetProps.subset_trans; [apply Hsubdiff|].\n\n      (* At this point, we have eliminated the confinement test.  \n         We're now down to discharging hypotheses of ag_fully_authorized_mutable_eq_diff \n         Take a moment to clean up the variables here *)\n      clear M P Hsubdiff HmutSub Hmut Hpa Hconf.\n      rename P2 into P; rename A2 into A; rename M2 into M.\n      rename Hauth2 into Hauth; rename Hpa2 into Hpa; rename Hmut2 into Hmut.\n\n      eapply ag_authorized_remainder_eq_simpl in Hauth; [|eauto 1].\n\n      eapply RefSetProps.subset_equal.\n\n      generalize (Seq.ag_objs_spec_ag_objs R); generalize (Seq.ag_objs R); intros Robjs HRobjs.\n      generalize (capset_targets_iff_f C); generalize (capset_targets_f C); intros T HT.\n      generalize (Seq.ag_objs_spec_ag_objs D); generalize (Seq.ag_objs D); intros Dobjs HDobjs.\n\n      eapply novel_capabilities_inter_empty in Hnovel; [|apply HT].\n      eapply novel_capabilities_inter_empty in Hnovel'; [|apply HT].\n\n      generalize (ag_remainder_empty_inter _ _ _ Hrem _ HRobjs); intros HemptyRem.\n\n      eapply ag_fully_authorized_mutable_eq_diff with (N:= (RefSet.diff Ex E)).\n      apply HRobjs.\n      2: auto.\n      3: auto.\n      5: apply HT.\n      6: apply Hnovel'.\n      6: apply Hnovel.\n      6: apply Hauth'.\n      6: apply Hauth.\n      6: apply Hpa'.\n      6: apply Hpa.\n      6: apply Hmut'.\n      6: apply Hmut.\n\n      eapply RefSetProps.subset_trans;\n        [ eapply ag_objs_ag_remainder_subset; [apply HDobjs | apply Hrem | apply HRobjs]\n          | intros x; RefSetFacts.set_iff; intros [HinDobjs HninE]; split; [|auto];\n            eapply ag_objs_spec_subset_existed; eauto 1].\n      2: apply HemptyRem.\n\n      3: intros x HinT; RefSetFacts.set_iff.\n      3: split;\n        [eapply extant_capabilities_targets; eauto 1\n          | intros Hnot; eapply Hnovel; RefSetFacts.set_iff; split; eauto 1].\n\n      2: eapply filtered_subset_eq_iff_filtered_subset_eq'; intros x;\n        case (RefSetProps.In_dec x (RefSet.diff Ex E)); intros Hcase; \n          [right; split; \n            [ auto\n              | generalize (Hfilter x); revert Hcase; RefSetFacts.set_iff; tauto]\n            | left; auto] .\n\n      intros x; RefSetFacts.set_iff; intros [HinE HinRobjs].\n      eapply ag_objs_ag_remainder_subset in HinRobjs;\n        [ | apply HDobjs | apply Hrem | apply HRobjs].\n      revert HinRobjs; RefSetFacts.set_iff; intros [HinDobjs HninE].\n      eapply Hfilter. RefSetFacts.set_iff.\n      eapply ag_objs_spec_subset_existed in HEx;\n        [ |apply Hda | apply HDobjs].\n      eapply HEx in HinDobjs.\n      eauto.\n    Qed.\n    \n  (* TODO: We need to know we can instantiate all of the inputs.\n     In particular, we need to know that AG.Subset (ag_objs A) (union (ag_objs D) (union E (cap_targets C))). \n     Subset (cap_targets C) (ag_objs D) /\\ (Subset (ag_objs D) N) /\\ (Subset E N) -> (Subset (ag_objs A) N)\n     If a subsystem is confined, the first condition is true and we have already assumed the others\n     This allows us to ignore the constraint that Subset (ag_objs A) N \n     This pattern matches our other assumptions about mutation.\n     We can instantiate with the obj_existed Ex S to produce the other constraints.\n     *)\n\n\nEnd MakeConfinement.", "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/ConfinementImpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.2837013609030461}}
{"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 Equivalence.\nRequire Import Morphisms.\nRequire Import Setoid.\nRequire Import EquivDec.\nRequire Import Program.\nRequire Import List.\nRequire Import Utils.\nRequire Import DataSystem.\nRequire Import NRA.\nRequire Import NRAExt.\nRequire Import NRAEq.\nRequire Import NRARewrite.\nRequire Import TNRA.\nRequire Import TNRAEq.\nRequire Import Program.\n  \nSection TNRARewrite.\n  Local Open Scope nra_scope.\n\n  (* An attempt at proving some of the relational algebra's\n     TYPE-DEPENDENT algebraic equivalences. *)\n\n  (* P1 ∧ P2 == P2 ∧ P1 *)\n\n  Context {m:basic_model}.\n  \n  Lemma tand_comm {τc} {τin} (op1 op2 opl opr: τin ⇝ Bool ⊣ τc) :\n    (`opl = `op2 ∧ `op1) ->\n    (`opr = `op2 ∧ `op1) ->\n    opl ≡τ opr.\n  Proof.\n    intros.\n    apply nra_eq_impl_tnra_eq.\n    rewrite H; rewrite H0.\n    rewrite and_comm.\n    reflexivity.\n  Qed.\n\n  Lemma tand_comm_arrow {τc} {τin} (op1 op2:nra) :\n    m ⊢ₐ τin ↦ Bool ⊣ τc ⊧ (op1 ∧ op2) ⇒ (op2 ∧ op1).\n  Proof.\n    intros.\n    split.\n    - inversion H; clear H; try eauto; subst.\n      inversion H3; clear H3; subst.\n      eapply type_NRABinop; try eauto.\n      eapply type_OpAnd; assumption.\n    - intros; rewrite and_comm; qeauto.\n  Qed.\n\n  (* σ{P1}(σ{P2}(P3)) == σ{P2 ∧ P1}(P3)) *)\n\n  Lemma tselect_and_aux (x: data) c τc τin τ (op op1 op2:nra) :\n    op ▷ τin >=> (Coll τ) ⊣ τc ->\n    op1 ▷ τ >=> Bool ⊣ τc ->\n    op2 ▷ τ >=> Bool ⊣ τc ->\n    bindings_type c τc ->\n    x ▹ τin ->\n    brand_relation_brands ⊢ (σ⟨ op1 ⟩(σ⟨ op2 ⟩(op))) @ₐ x  ⊣ c =\n    brand_relation_brands ⊢ (σ⟨ op2 ∧ op1 ⟩(op)) @ₐ x ⊣ c.\n  Proof.\n    intros ? ? ? Hcenv; intros; simpl.\n    assert (exists d, (brand_relation_brands ⊢ op@ₐx ⊣ c = Some d /\\ (d ▹ (Coll τ))))\n      by (apply (@typed_nra_yields_typed_data m τc τin); assumption).\n    elim H3; clear H3; intros.\n    elim H3; clear H3; intros.\n    rewrite H3; clear H3; simpl.\n    invcs H4.\n    rtype_equalizer.\n    subst.\n    autorewrite with alg.\n    apply lift_dcoll_inversion.\n    induction dl; try reflexivity.\n    simpl.\n    assert (Forall (fun d : data => data_type d τ) dl)\n      by (clear IHdl; rewrite Forall_forall in *; intros;\n          simpl in *; intuition).\n    specialize (IHdl H3); clear H3.\n    rewrite <- IHdl; clear IHdl.\n    rewrite Forall_forall in H6; simpl in H6.\n    assert (data_type a τ)\n      by intuition.\n    assert (exists d, (brand_relation_brands ⊢ op2@ₐa ⊣ c = Some d /\\ (d ▹ Bool)))\n      by (apply (@typed_nra_yields_typed_data m τc τ); assumption).\n    destruct H4 as [? [eqq dt]].\n    rewrite eqq; clear eqq.\n    dtype_inverter.\n    unfold olift.\n    destruct (       lift_filter\n         (fun x' : data =>\n          match brand_relation_brands ⊢ op2 @ₐ x' ⊣ c with\n          | Some (dbool b0) => Some b0\n          | _ => None\n          end) dl).\n    - destruct x1.\n      + simpl.\n        assert (exists d, (brand_relation_brands ⊢ op1@ₐa ⊣ c = Some d /\\ (d ▹ Bool)))\n          by (apply (@typed_nra_yields_typed_data m τc τ); assumption).\n        destruct H4 as [? [eqq dt]].\n        rewrite eqq; clear eqq.\n        dtype_inverter.\n        reflexivity.\n      + assert (exists d, (brand_relation_brands ⊢ op1@ₐa ⊣ c = Some d /\\ (d ▹ Bool)))\n          by (apply (@typed_nra_yields_typed_data m τc τ); assumption).\n        destruct H4 as [? [eqq dt]].\n        rewrite eqq; clear eqq.\n        dtype_inverter.\n        destruct (lift_filter\n     (fun x' : data =>\n      match brand_relation_brands ⊢ op1 @ₐ x' ⊣ c with\n      | Some (dbool b0) => Some b0\n      | _ => None\n      end) l); reflexivity.\n    - destruct (brand_relation_brands ⊢ op1@ₐa ⊣ c); try reflexivity.\n      destruct d; reflexivity.\n  Qed.      \n\n  Lemma tselect_and {τc} {τin τ} (op opl opr: τin ⇝ (Coll τ) ⊣ τc) (op1 op2:τ ⇝ Bool ⊣ τc) :\n    (`opl = σ⟨ `op1 ⟩(σ⟨ `op2 ⟩(`op))) ->\n    (`opr = σ⟨ `op2 ∧ `op1 ⟩(`op)) ->\n    (opl ≡τ opr).\n  Proof.\n    unfold tnra_eq; intros.\n    rewrite H; rewrite H0.\n    rewrite (tselect_and_aux x c τc τin τ).\n    reflexivity.\n    apply (proj2_sig op).\n    apply (proj2_sig op1).\n    apply (proj2_sig op2).\n    assumption.\n    assumption.\n  Qed.\n\n  (* σ⟨ P1 ⟩(σ⟨ P2 ⟩(P3)) == σ⟨ P2 ⟩(σ⟨ P1 ⟩(P3)) *)\n\n  (* This is the first rewrite done at algebra level, using nra_eq. *)\n  Lemma tselect_comm_nra {τc} {τin τ} (op1 op2:τ ⇝ Bool ⊣ τc) (op opl opr: τin ⇝ (Coll τ) ⊣ τc) :\n    (`opl = σ⟨ `op1 ⟩(σ⟨ `op2 ⟩(`op))) ->\n    (`opr = σ⟨ `op2 ⟩(σ⟨ `op1 ⟩(`op))) ->\n    opl ≡τ opr.\n  Proof.\n    intros.\n    unfold tnra_eq; intros.\n    rewrite H; rewrite H0.\n    rewrite (tselect_and_aux x c τc τin τ); try assumption.\n    rewrite (tselect_and_aux x c τc τin τ); try assumption.\n    generalize and_comm; intros.\n    assert ((σ⟨ ` op2 ∧ ` op1 ⟩( ` op)) ≡ₐ (σ⟨ ` op1 ∧ ` op2 ⟩( ` op))).\n    rewrite (H1 (`op1) (`op2)).\n    reflexivity.\n    rewrite H2 by qeauto.\n    reflexivity.\n    apply (proj2_sig op).\n    apply (proj2_sig op2).\n    apply (proj2_sig op1).\n    apply (proj2_sig op).\n    apply (proj2_sig op1).\n    apply (proj2_sig op2).\n  Qed.\n\n  Lemma tselect_comm {τc} {τin τ} c x (op: τin ⇝ (Coll τ) ⊣ τc) (op1 op2:τ ⇝ Bool ⊣ τc) :\n    bindings_type c τc ->\n    x ▹ τin ->\n    (brand_relation_brands ⊢ σ⟨ `op1 ⟩(σ⟨ `op2 ⟩(`op)) @ₐ x ⊣ c) = (brand_relation_brands ⊢ σ⟨ `op2 ⟩(σ⟨ `op1 ⟩(`op)) @ₐ x ⊣ c).\n  Proof.\n    generalize (@tselect_comm_nra τc τin); intros.\n    unfold tnra_eq in H.\n    specialize (H τ op1 op2 op).\n    assert (σ⟨ `op1 ⟩( σ⟨ `op2 ⟩( ` op)) ▷ τin >=> Coll τ ⊣ τc).\n    apply type_NRASelect.\n    apply (proj2_sig op1).\n    apply type_NRASelect.\n    apply (proj2_sig op2).\n    apply (proj2_sig op).\n    assert (σ⟨ `op2 ⟩( σ⟨ `op1 ⟩( ` op)) ▷ τin >=> Coll τ ⊣ τc).\n    apply type_NRASelect.\n    apply (proj2_sig op2).\n    apply type_NRASelect.\n    apply (proj2_sig op1).\n    apply (proj2_sig op).\n    assert (exists opl:τin ⇝ Coll τ ⊣ τc, `opl = σ⟨ `op1 ⟩( σ⟨ `op2 ⟩(`op))).\n    revert H2.\n    generalize (σ⟨ `op1 ⟩( σ⟨ `op2 ⟩( `op))); intros.\n    exists (exist (fun op => nra_type τc op τin (Coll τ)) n H2).\n    reflexivity.\n    assert (exists opr:τin ⇝ Coll τ ⊣ τc, `opr = σ⟨ `op2 ⟩( σ⟨ `op1 ⟩(`op))).\n    revert H3.\n    generalize (σ⟨ `op2 ⟩( σ⟨ `op1 ⟩(`op))); intros.\n    exists (exist (fun op => nra_type τc op τin (Coll τ)) n H3).\n    reflexivity.\n    elim H4; elim H5; intros.\n    rewrite <- H6.\n    rewrite <- H7.\n    apply (H x1 x0).\n    assumption.\n    assumption.\n    assumption.\n    assumption.\n  Qed.\n\n  (* σ⟨P⟩(P1 − P2) == σ⟨P⟩(P1) − σ⟨P⟩(P2) *)\n\n  Definition tunbox_bool (y:{ x:data | x ▹ Bool }) : bool.\n  Proof.\n    elim y; clear y.\n    intros.\n    destruct x; try (assert False by (inversion p; contradiction) ; contradiction).\n    exact b.\n  Defined.\n\n  Definition typed_nra_total_bool {τc} {τ} c (op:τ ⇝ Bool ⊣ τc):\n    bindings_type c τc ->\n    {x:data|(x ▹ τ)} -> bool.\n  Proof.\n    intros.\n    apply tunbox_bool.\n    apply (@typed_nra_total m τc τ Bool (`op) (proj2_sig op) c (`H0) H).\n    elim H0; intros.\n    exact p.\n  Defined.\n\n  Lemma typed_nra_total_bool_consistent {τc} {τ} c (op:τ ⇝ Bool ⊣ τc) (d: {x:data|(x ▹ τ)}) (Hcenv:bindings_type c τc) :\n    match (brand_relation_brands ⊢ `op@ₐ`d ⊣ c) with\n      | Some (dbool b) => Some b\n      | _ => None\n    end = Some (typed_nra_total_bool c op Hcenv d).\n  Proof.\n    unfold typed_nra_total_bool.\n    unfold typed_nra_total.\n    generalize (typed_nra_yields_typed_data c (`d) (`op) Hcenv (sig_ind (fun H : {x : data | x ▹ τ} => ` H ▹ τ)\n                 (fun (x : data) (p : x ▹ τ) => p) d) \n                                            (proj2_sig op)); intros.\n    destruct e; simpl.\n    destruct a; simpl.\n    rewrite e; clear e.\n    destruct x; try (assert False by (inversion d0; contradiction) ; contradiction).\n    reflexivity.\n  Qed.\n\n  Lemma typed_nra_total_bool_consistent2 {τc} {τ} c (op:τ ⇝ Bool ⊣ τc) (x:data) (pf:(x ▹ τ)) (Hcenv:bindings_type c τc) :\n    match (brand_relation_brands ⊢ `op@ₐx ⊣ c) with\n      | Some (dbool b) => Some b\n      | _ => None\n    end = Some (typed_nra_total_bool c op Hcenv (exist _ x pf)).\n  Proof.\n    apply (typed_nra_total_bool_consistent c op (exist _ x pf)).\n  Qed.\n  \n  Lemma typed_lifted_predicate {τc} {τ} (op:τ ⇝ Bool ⊣ τc) c (d:data):\n    bindings_type c τc ->\n    data_type d τ ->\n    exists b' : bool,\n      (fun x' : data =>\n         match brand_relation_brands ⊢ (`op)@ₐ x' ⊣ c with\n           | Some (dbool b) => Some b\n           | _ => None\n         end) d = Some b'.\n  Proof.\n    intros.\n    exists (typed_nra_total_bool c op H (exist _ d H0)).\n    apply typed_nra_total_bool_consistent2.\n  Qed.\n\n  Lemma lift_filter_remove_one_false (l:list data) (f:data -> option bool) (a:data) :\n    f a = Some false ->\n    (lift_filter f (remove_one a l)) = lift_filter f l.\n  Proof.\n    intros.\n    induction l; simpl; try reflexivity.\n    destruct (equiv_dec a a0); simpl.\n    - rewrite e in *; clear e.\n      rewrite H; simpl; clear H.\n      destruct (lift_filter f l); reflexivity.\n    - destruct (f a0); try reflexivity.\n      rewrite IHl; reflexivity.\n  Qed.\n  \n  Lemma lift_filter_remove_one {τ} (l:list data) (f:data -> option bool) (a:data) :\n    Forall (fun d : data => data_type d τ) l ->\n    data_type a τ ->\n    (forall d : data, data_type d τ -> exists b' : bool, f d = Some b') ->\n    (lift_filter f (remove_one a l)) = lift (remove_one a) (lift_filter f l).\n  Proof.\n    intros.\n    induction l; simpl; try reflexivity.\n    destruct (equiv_dec a a0); intros; simpl.\n    - rewrite e in *; clear e.\n      case_eq (f a0); try reflexivity; simpl; intros.\n      + inversion H; clear H. specialize (IHl H6).\n        case_eq b; simpl; intros.\n        * revert IHl.\n          destruct (lift_filter f l); try reflexivity; intros; simpl.\n          destruct (equiv_dec a0 a0); try congruence.\n        * rewrite H in *; clear H.\n          rewrite lift_filter_remove_one_false in IHl; try assumption.\n          rewrite IHl at 1.\n          destruct (lift_filter f l); reflexivity.\n      + inversion H; clear H; elim (H1 a0 H0); intros; congruence.\n    - destruct (f a0); try reflexivity.\n      inversion H; clear H. specialize (IHl H5); clear H5 H2 H3.\n      rewrite IHl.\n      destruct (lift_filter f l); try reflexivity.\n      destruct b; try reflexivity.\n      simpl.\n      destruct (equiv_dec a a0); congruence.\n  Qed.\n\n  Lemma remove_still_well_typed {τ} (l:list data) (a:data) :\n    Forall (fun d : data => data_type d τ) l ->\n    Forall (fun d : data => data_type d τ) (remove_one a l).\n  Proof.\n    intros.\n    induction l.\n    - simpl; apply Forall_nil.\n    - simpl in *.\n      inversion H; clear H.\n      destruct (equiv_dec a a0).\n      + assumption.\n      + apply Forall_cons; auto.\n  Qed.\n\n  Lemma lift_filter_over_bminus {τ} (l1 l2 : list data) (f:data -> option bool):\n    Forall (fun d : data => data_type d τ) l1 ->\n    Forall (fun d : data => data_type d τ) l2 ->\n    Forall (fun d : data => data_type d τ) (bminus l1 l2) ->\n    (forall d : data, data_type d τ -> exists b' : bool, f d = Some b') ->\n    lift dcoll (lift_filter f (bminus l1 l2)) =\n    match lift dcoll (lift_filter f l2) with\n      | Some d2 =>\n        match lift dcoll (lift_filter f l1) with\n          | Some d1 => rondcoll2 bminus d1 d2\n          | None => None\n        end\n      | None => None\n    end.\n  Proof.\n    intros.\n    revert l2 H0 H1.\n    induction l1; simpl; try reflexivity; intros.\n    - destruct (lift_filter f l2); reflexivity.\n    - inversion H; clear H x H3 H4.\n      specialize (IHl1 H6); clear H6.\n      case_eq (f a).\n      + intros b eqf; simpl.\n        case_eq b; intros; rewrite H in *; clear H.\n        (* true *)\n        * rewrite IHl1; simpl; try assumption.\n          case_eq (lift_filter f l1); intros; try reflexivity; simpl.\n          unfold lift; simpl.\n          rewrite (lift_filter_remove_one l2 f a H0 H5 H2); simpl.\n          destruct (lift_filter f l2); try reflexivity.\n          rewrite (lift_filter_remove_one l2 f a H0 H5 H2); simpl.\n          destruct (lift_filter f l2); try reflexivity.\n          apply remove_still_well_typed; assumption.\n        (* false *)\n        * rewrite IHl1; simpl; try assumption.\n          destruct (lift_filter f l1); try reflexivity; simpl.\n          rewrite (lift_filter_remove_one_false); simpl.\n          destruct (lift_filter f l2); try reflexivity.\n          assumption.\n          rewrite (lift_filter_remove_one_false); simpl.\n          destruct (lift_filter f l2); try reflexivity.\n          assumption.\n          apply remove_still_well_typed; assumption.\n      + intros.\n        elim (H2 a); try assumption; intros.\n        congruence.\n  Qed.\n\n  Lemma minus_select_distr {τc} {τin τ} (op:τ ⇝ Bool ⊣ τc) (op1 op2 opl opr: τin ⇝ (Coll τ) ⊣ τc) :\n    (`opl = σ⟨`op⟩(`op1 − `op2)) ->\n    (`opr = σ⟨`op⟩(`op1) − σ⟨`op⟩(`op2)) ->\n    opl ≡τ opr.\n  Proof.\n    unfold tnra_eq.\n    intros ? ? x c ? Hcenv.\n    rewrite H; rewrite H0; clear H H0 opl opr; simpl.\n    assert (exists d1, (brand_relation_brands ⊢ `op1@ₐx ⊣ c = Some d1 /\\ (d1 ▹ (Coll τ))))\n      by (apply (@typed_nra_yields_typed_data m τc τin); [assumption|assumption|apply (proj2_sig op1)]).\n    assert (exists d2, (brand_relation_brands ⊢ `op2@ₐx ⊣ c = Some d2 /\\ (d2 ▹ (Coll τ))))\n      by (apply (@typed_nra_yields_typed_data m τc τin); [assumption|assumption|apply (proj2_sig op2)]).\n    elim H; elim H0; clear H H0; intros.\n    elim H; elim H0; clear H H0; intros.\n    rewrite H; rewrite H1; clear H H1.\n    simpl.\n    invcs H0; invcs H2.\n    rtype_equalizer.\n    subst.\n    simpl.\n    assert (Forall (fun d : data => data_type d τ) (bminus dl0 dl))\n      by (apply bminus_Forall; assumption).\n    assert (exists f, (forall d : data,\n                         data_type d τ ->\n                         exists b' : bool,\n                           f d = Some b') /\\ f = ((fun x' : data =>\n         match brand_relation_brands ⊢ (` op) @ₐ x' ⊣ c with\n         | Some (dbool b) => Some b\n         | _ => None\n         end))).\n    exists  ((fun x' : data =>\n         match brand_relation_brands ⊢ (` op) @ₐ x' ⊣ c with\n         | Some (dbool b) => Some b\n         | _ => None\n         end));\n      split. intros. apply typed_lifted_predicate; try assumption. reflexivity.\n    destruct H0 as [? [eqq dt]].\n    revert dt.\n    generalize ((fun x' : data =>\n       match brand_relation_brands ⊢ (` op) @ₐ x' ⊣ c with\n       | Some (dbool b) => Some b\n       | _ => None\n       end)); intros.\n    subst.\n    unfold olift2.\n    eapply lift_filter_over_bminus; eauto.\n  Qed.\n \nEnd TNRARewrite.\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/Optim/TNRARewrite.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.28369912704295597}}
{"text": "Require Import Bool List String PeanoNat.\nRequire Import Common IndexSupport FMap.\nRequire Import Syntax Semantics SemFacts StepM Serial Invariant.\n\nRequire Import Lia.\nRequire Import Program.Equality.\n\nSet Implicit Arguments.\n\nLocal Open Scope list.\nLocal Open Scope fmap.\n\nSection MsgParam.\n  Context `{dv: DecValue}.\n\n  Lemma atomic_emptyILabel_not_in:\n    forall inits ins hst outs eouts,\n      Atomic inits ins hst outs eouts ->\n      ~ In RlblEmpty hst.\n  Proof.\n    induction 1; simpl; intros.\n    - intro Hx; destruct Hx; [discriminate|auto].\n    - intro Hx; destruct Hx; subst; [discriminate|auto].\n  Qed.\n\n  Lemma atomic_iLblIn_not_in:\n    forall inits ins hst outs eouts,\n      Atomic inits ins hst outs eouts ->\n      forall msg, ~ In (RlblIns [msg]) hst.\n  Proof.\n    induction 1; simpl; intros; [auto|];\n      try (intro Hx; destruct Hx;\n           [discriminate|firstorder]).\n  Qed.\n\n  Fixpoint insOfA (hst: History) :=\n    match hst with\n    | nil => nil\n    | lbl :: hst' =>\n      match lbl with\n      | RlblInt _ _ ins _ => insOfA hst' ++ ins\n      | _ => nil\n      end\n    end.\n\n  Fixpoint outsOfA (hst: History) :=\n    match hst with\n    | nil => nil\n    | lbl :: hst' =>\n      match lbl with\n      | RlblInt _ _ _ outs => outsOfA hst' ++ outs\n      | _ => nil\n      end\n    end.\n\n  Lemma atomic_lastOIdxOf:\n    forall inits ins hst outs eouts,\n      Atomic inits ins hst outs eouts ->\n      exists loidx,\n        lastOIdxOf hst = Some loidx.\n  Proof.\n    induction 1; simpl; intros; eauto.\n  Qed.\n\n  Lemma atomic_ins:\n    forall (hst: History) inits ins outs eouts,\n      Atomic inits ins hst outs eouts ->\n      ins = insOfA hst.\n  Proof.\n    induction 1; simpl; intros; subst; reflexivity.\n  Qed.\n\n  Lemma atomic_outs:\n    forall (hst: History) inits ins outs eouts,\n      Atomic inits ins hst outs eouts ->\n      outs = outsOfA hst.\n  Proof.\n    induction 1; simpl; intros; subst; reflexivity.\n  Qed.\n\n  Lemma atomic_unique:\n    forall (hst: History) inits1 ins1 outs1 eouts1,\n      Atomic inits1 ins1 hst outs1 eouts1 ->\n      forall inits2 ins2 outs2 eouts2,\n        Atomic inits2 ins2 hst outs2 eouts2 ->\n        inits1 = inits2 /\\ ins1 = ins2 /\\\n        outs1 = outs2 /\\ eouts1 = eouts2.\n  Proof.\n    induction 1; simpl; intros; subst.\n    - inv H; [auto|inv H5].\n    - inv H5; [inv H|].\n      specialize (IHAtomic _ _ _ _ H8).\n      dest; subst; auto.\n  Qed.\n\n  Lemma atomic_messages_spec_ValidDeqs:\n    forall inits ins hst outs eouts,\n      Atomic inits ins hst outs eouts ->\n      forall `{oifc: OStateIfc} (sys: System) st1 st2,\n        steps step_m sys st1 hst st2 ->\n        st_msgs st2 = deqMsgs (idsOf ins) (enqMsgs outs (st_msgs st1)) /\\\n        ValidDeqs (enqMsgs outs (st_msgs st1)) (idsOf ins).\n  Proof.\n    induction 1; simpl; intros; subst.\n    - inv H; inv H3; inv H5; simpl; split.\n      + apply enqMsgs_deqMsgs_comm; auto.\n      + apply ValidDeqs_enqMsgs.\n        destruct H10.\n        apply FirstMPI_Forall_NoDup_ValidDeqs; auto.\n\n    - inv H5.\n      specialize (IHAtomic _ _ _ _ H6); dest.\n      inv H8; simpl in *; subst.\n      repeat rewrite idsOf_app, deqMsgs_app, enqMsgs_app.\n      split.\n      + rewrite enqMsgs_deqMsgs_comm with (minds1:= idsOf rins) by assumption.\n        rewrite enqMsgs_deqMsgs_ValidDeqs_comm\n          with (minds:= idsOf ins) (nmsgs:= routs) by assumption.\n        reflexivity.\n      + apply ValidDeqs_app.\n        * apply ValidDeqs_enqMsgs; auto.\n        * rewrite <-enqMsgs_deqMsgs_ValidDeqs_comm\n            with (minds:= idsOf ins) (nmsgs:= routs) by assumption.\n          destruct H16.\n          apply ValidDeqs_enqMsgs; auto.\n          apply FirstMPI_Forall_NoDup_ValidDeqs; auto.\n  Qed.\n\n  Corollary atomic_messages_spec:\n    forall inits ins hst outs eouts,\n      Atomic inits ins hst outs eouts ->\n      forall `{oifc: OStateIfc} (sys: System) st1 st2,\n        steps step_m sys st1 hst st2 ->\n        st_msgs st2 = deqMsgs (idsOf ins) (enqMsgs outs (st_msgs st1)).\n  Proof.\n    intros; eapply atomic_messages_spec_ValidDeqs; eauto.\n  Qed.\n\n  Lemma atomic_messages_inits_valid:\n    forall inits ins hst outs eouts,\n      Atomic inits ins hst outs eouts ->\n      forall `{oifc: OStateIfc} (sys: System) st1 st2,\n        steps step_m sys st1 hst st2 ->\n        ValidMsgsIn sys inits.\n  Proof.\n    induction 1; simpl; intros; subst.\n    - inv_steps; inv_step; assumption.\n    - inv_steps; eauto.\n  Qed.\n\n  Lemma atomic_messages_ins_outs:\n    forall inits ins hst outs eouts,\n      Atomic inits ins hst outs eouts ->\n      EquivList (inits ++ outs) (ins ++ eouts).\n  Proof.\n    induction 1; simpl; intros; subst;\n      [apply EquivList_refl|].\n\n    destruct IHAtomic; split.\n    - repeat rewrite app_assoc.\n      apply SubList_app_6; [|apply SubList_refl].\n      eapply SubList_trans; [eassumption|].\n      rewrite <-app_assoc.\n      apply SubList_app_6; [apply SubList_refl|].\n      apply removeL_SubList_3.\n    - repeat rewrite app_assoc.\n      apply SubList_app_6; [|apply SubList_refl].\n      eapply SubList_trans; [|eassumption].\n      rewrite <-app_assoc.\n      apply SubList_app_6; [apply SubList_refl|].\n      apply SubList_app_3; [assumption|].\n      apply removeL_SubList_2.\n  Qed.\n\n  Lemma atomic_behavior_nil:\n    forall (hst: History) inits ins outs eouts,\n      Atomic inits ins hst outs eouts ->\n      behaviorOf hst = nil.\n  Proof.\n    induction 1; simpl; intros; auto.\n  Qed.\n\n  Lemma atomic_singleton:\n    forall oidx ridx ins outs,\n      Atomic ins ins [RlblInt oidx ridx ins outs] outs outs.\n  Proof.\n    intros; constructor.\n  Qed.\n\n  Lemma extAtomic_unique:\n    forall `{oifc: OStateIfc} (sys: System) inits1 hst eouts1,\n      ExtAtomic sys inits1 hst eouts1 ->\n      forall inits2 eouts2,\n        ExtAtomic sys inits2 hst eouts2 ->\n        inits1 = inits2 /\\ eouts1 = eouts2.\n  Proof.\n    intros.\n    inv H; inv H0.\n    pose proof (atomic_unique H2 H3); dest; subst; auto.\n  Qed.\n\n  Lemma extAtomic_preserved:\n    forall `{oifc: OStateIfc} (impl1: System) inits hst eouts,\n      ExtAtomic impl1 inits hst eouts ->\n      forall (impl2: System),\n        sys_merqs impl1 = sys_merqs impl2 ->\n        ExtAtomic impl2 inits hst eouts.\n  Proof.\n    intros.\n    inv H.\n    econstructor; eauto.\n    rewrite <-H0; assumption.\n  Qed.\n\n  Lemma atomic_split_each:\n    forall inits ins hst outs eouts,\n      Atomic inits ins hst outs eouts ->\n      Forall AtomicEx (lift_each hst).\n  Proof.\n    induction 1; simpl; intros; [repeat econstructor|].\n    repeat econstructor.\n    assumption.\n  Qed.\n\n  Lemma atomicEx_split_each:\n    forall hst,\n      AtomicEx hst ->\n      Forall AtomicEx (lift_each hst).\n  Proof.\n    unfold AtomicEx; intros; dest.\n    eapply atomic_split_each; eauto.\n  Qed.\n\n  Definition InternalLbl (lbl: RLabel) :=\n    match lbl with\n    | RlblInt _ _ _ _ => True\n    | _ => False\n    end.\n\n  Definition InsLbl (lbl: RLabel) :=\n    match lbl with\n    | RlblIns _ => True\n    | _ => False\n    end.\n\n  Definition OutsLbl (lbl: RLabel) :=\n    match lbl with\n    | RlblOuts _ => True\n    | _ => False\n    end.\n\n  Definition NonInsLbl (lbl: RLabel) :=\n    match lbl with\n    | RlblIns _ => False\n    | _ => True\n    end.\n\n  Definition NonOutsLbl (lbl: RLabel) :=\n    match lbl with\n    | RlblOuts _ => False\n    | _ => True\n    end.\n\n  Definition HistoryP (P: RLabel -> Prop) (hst: History) :=\n    Forall (fun lbl => P lbl) hst.\n\n  Definition InternalHistory := HistoryP InternalLbl.\n  Definition InsHistory := HistoryP InsLbl.\n  Definition OutsHistory := HistoryP OutsLbl.\n  Definition NonInsHistory := HistoryP NonInsLbl.\n  Definition NonOutsHistory := HistoryP NonOutsLbl.\n\n  Lemma atomic_internal_history:\n    forall inits ins hst outs eouts,\n      Atomic inits ins hst outs eouts ->\n      InternalHistory hst.\n  Proof.\n    induction 1; simpl; intros.\n    - repeat constructor.\n    - repeat constructor; auto.\n  Qed.\n\n  Lemma atomicEx_internal_history:\n    forall hst,\n      AtomicEx hst ->\n      InternalHistory hst.\n  Proof.\n    unfold AtomicEx; intros; dest.\n    eapply atomic_internal_history; eauto.\n  Qed.\n\n  Lemma sequential_nil:\n    forall `{oifc: OStateIfc} (sys: System), Sequential sys nil nil.\n  Proof.\n    intros; hnf; intros.\n    split.\n    - constructor.\n    - reflexivity.\n  Qed.\n\n  Lemma sequential_cons:\n    forall `{oifc: OStateIfc} (sys: System) ll trss,\n      Sequential sys ll trss ->\n      forall trs,\n        Transactional sys trs ->\n        Sequential sys (trs ++ ll) (trs :: trss).\n  Proof.\n    intros.\n    inv H.\n    constructor; auto.\n  Qed.\n\n  Lemma sequential_silent:\n    forall `{oifc: OStateIfc} (sys: System) ll trss,\n      Sequential sys ll trss ->\n      Sequential sys (RlblEmpty :: ll) ([RlblEmpty] :: trss).\n  Proof.\n    intros.\n    hnf; hnf in H; dest.\n    split.\n    - constructor; [|eassumption].\n      constructor.\n    - subst; reflexivity.\n  Qed.\n\n  Lemma sequential_msg_ins:\n    forall `{oifc: OStateIfc} (sys: System) ll trss eins,\n      Sequential sys ll trss ->\n      Sequential sys (RlblIns eins :: ll) ([RlblIns eins] :: trss).\n  Proof.\n    intros.\n    hnf; hnf in H; dest.\n    split.\n    - constructor; [|eassumption].\n      eapply TrsIns; reflexivity.\n    - subst; reflexivity.\n  Qed.\n\n  Lemma sequential_msg_outs:\n    forall `{oifc: OStateIfc} (sys: System) ll trss eouts,\n      Sequential sys ll trss ->\n      Sequential sys (RlblOuts eouts :: ll) ([RlblOuts eouts] :: trss).\n  Proof.\n    intros.\n    hnf; hnf in H; dest.\n    split.\n    - constructor; [|eassumption].\n      eapply TrsOuts; reflexivity.\n    - subst; reflexivity.\n  Qed.\n\n  Lemma sequential_insHistory:\n    forall `{oifc: OStateIfc} (sys: System) ins,\n      InsHistory ins ->\n      Sequential sys ins (lift_each ins).\n  Proof.\n    induction ins; simpl; intros; [constructor; auto|].\n    inv H; destruct a; try (intuition; fail).\n    specialize (IHins H3); destruct IHins.\n    split.\n    - constructor; auto.\n      eapply TrsIns; eauto.\n    - simpl; rewrite H0 at 1; reflexivity.\n  Qed.\n\n  Lemma sequential_outsHistory:\n    forall `{oifc: OStateIfc} (sys: System) outs,\n      OutsHistory outs ->\n      Sequential sys outs (lift_each outs).\n  Proof.\n    induction outs; simpl; intros; [constructor; auto|].\n    inv H; destruct a; try (intuition; fail).\n    specialize (IHouts H3); destruct IHouts.\n    split.\n    - constructor; auto.\n      eapply TrsOuts; eauto.\n    - simpl; rewrite H0 at 1; reflexivity.\n  Qed.\n\n  Lemma ssequential_insHistory:\n    forall `{oifc: OStateIfc} (sys: System) ins,\n      InsHistory ins ->\n      SSequential sys (lift_each ins) 0.\n  Proof.\n    induction ins; simpl; intros.\n    - apply SSeqNil.\n    - inv H; destruct a; try (intuition; fail).\n      specialize (IHins H3).\n      econstructor; eauto.\n      eapply STrsIns; reflexivity.\n  Qed.\n\n  Lemma ssequential_outsHistory:\n    forall `{oifc: OStateIfc} (sys: System) outs,\n      OutsHistory outs ->\n      SSequential sys (lift_each outs) 0.\n  Proof.\n    induction outs; simpl; intros.\n    - apply SSeqNil.\n    - inv H; destruct a; try (intuition; fail).\n      specialize (IHouts H3).\n      econstructor; eauto.\n      eapply STrsOuts; reflexivity.\n  Qed.\n\n  Lemma sequential_app:\n    forall `{oifc: OStateIfc} (sys: System) ll1 trss1 ll2 trss2,\n      Sequential sys ll1 trss1 ->\n      Sequential sys ll2 trss2 ->\n      Sequential sys (ll1 ++ ll2) (trss1 ++ trss2).\n  Proof.\n    unfold Sequential; intros.\n    destruct H, H0; subst.\n    split.\n    - apply Forall_app; auto.\n    - apply eq_sym, concat_app.\n  Qed.\n\n  Lemma sequential_serializable:\n    forall `{oifc: OStateIfc} (sys: System) hst trss st,\n      steps step_m sys (initsOf sys) hst st ->\n      Sequential sys hst trss ->\n      Serializable sys st.\n  Proof.\n    intros; red; intros.\n    eexists; split; eauto.\n  Qed.\n\n  Lemma stransactional_default:\n    forall `{oifc: OStateIfc} (sys: System) lbl,\n      exists n,\n        STransactional sys [lbl] n.\n  Proof.\n    destruct lbl; intros; eexists.\n    - eapply STrsSlt.\n    - eapply STrsIns; eauto.\n    - instantiate\n        (1:= if subList_dec idx_dec (idsOf mins) sys.(sys_merqs)\n             then _ else _).\n      destruct (subList_dec idx_dec (idsOf mins) sys.(sys_merqs)).\n      + eapply STrsExtAtomic.\n        econstructor; eauto.\n        econstructor.\n      + eapply STrsIntAtomic.\n        econstructor; eauto.\n        econstructor.\n    - eapply STrsOuts; eauto.\n  Qed.\n\n  Lemma ssequential_default:\n    forall `{oifc: OStateIfc} (sys: System) hst,\n    exists n trss,\n      SSequential sys trss n /\\ hst = List.concat trss.\n  Proof.\n    induction hst as [|l hst]; simpl; intros; [repeat econstructor; eauto|].\n    destruct IHhst as [n [trss ?]]; dest; subst.\n    pose proof (stransactional_default sys l).\n    destruct H0 as [ln ?].\n    exists (ln + n), ([l] :: trss).\n    split.\n    - econstructor; eauto.\n    - reflexivity.\n  Qed.\n\n  Lemma ssequential_add:\n    forall `{oifc: OStateIfc} (sys: System) ll1 ll2 n,\n      SSequential sys (ll1 ++ ll2) n ->\n      forall trs tn,\n        STransactional sys trs tn ->\n        SSequential sys (ll1 ++ trs :: ll2) (tn + n).\n  Proof.\n    induction ll1; simpl; intros; [econstructor; eauto|].\n    inv H; inv H3.\n    specialize (IHll1 _ _ H1 _ _ H0).\n    econstructor.\n    - exact IHll1.\n    - exact H2.\n    - reflexivity.\n    - lia.\n  Qed.\n\n  Lemma ssequential_app:\n    forall `{oifc: OStateIfc} (sys: System) ll1 n1 ll2 n2,\n      SSequential sys ll1 n1 ->\n      SSequential sys ll2 n2 ->\n      SSequential sys (ll1 ++ ll2) (n1 + n2).\n  Proof.\n    induction 1; simpl; intros; subst; simpl; auto.\n    econstructor.\n    - exact (IHSSequential H3).\n    - eassumption.\n    - reflexivity.\n    - lia.\n  Qed.\n\n  Lemma ssequential_app_inv:\n    forall `{oifc: OStateIfc} (sys: System) ll1 ll2 n,\n      SSequential sys (ll1 ++ ll2) n ->\n      exists n1 n2,\n        SSequential sys ll1 n1 /\\\n        SSequential sys ll2 n2 /\\\n        n = n1 + n2.\n  Proof.\n    induction ll1; simpl; intros.\n    - exists 0, n; repeat split; [constructor|assumption].\n    - inv H; inv H2.\n      specialize (IHll1 _ _ H0).\n      destruct IHll1 as [n1 [n2 ?]]; dest; subst.\n      exists (tn + n1), n2; repeat split.\n      + econstructor.\n        * exact H.\n        * exact H1.\n        * reflexivity.\n        * reflexivity.\n      + assumption.\n      + lia.\n  Qed.\n\n  Lemma ssequential_distr_inv:\n    forall `{oifc: OStateIfc} (sys: System) ll ll1 ll2,\n      Distribution ll ll1 ll2 ->\n      forall n,\n        SSequential sys ll n ->\n        exists n1 n2,\n          SSequential sys ll1 n1 /\\\n          SSequential sys ll2 n2 /\\\n          n = n1 + n2.\n  Proof.\n    induction 1; simpl; intros.\n    - inv H; try discriminate.\n      exists 0, 0; repeat split; constructor.\n    - inv H0; inv H3.\n      specialize (IHDistribution _ H1).\n      destruct IHDistribution as [n1 [n2 ?]]; dest; subst.\n      apply ssequential_app_inv in H0.\n      destruct H0 as [n11 [n12 ?]]; dest; subst.\n      exists (n11 + (tn + n12)), n2; repeat split.\n      + apply ssequential_app; auto.\n        econstructor; try reflexivity; auto.\n      + assumption.\n      + lia.\n    - inv H0; inv H3.\n      specialize (IHDistribution _ H1).\n      destruct IHDistribution as [n1 [n2 ?]]; dest; subst.\n      apply ssequential_app_inv in H3.\n      destruct H3 as [n21 [n22 ?]]; dest; subst.\n      exists n1, (n21 + (tn + n22)); repeat split.\n      + assumption.\n      + apply ssequential_app; auto.\n        econstructor; try reflexivity; auto.\n      + lia.\n  Qed.\n\n  Lemma intAtomic_stransactional_split_each:\n    forall `{oifc: OStateIfc} (sys: System) inits ins trs outs eouts,\n      ~ SubList (idsOf inits) (sys_merqs sys) ->\n      Atomic inits ins trs outs eouts ->\n      exists sn,\n        SSequential sys (lift_each trs) sn /\\\n        sn <= List.length trs.\n  Proof.\n    induction 2; simpl; intros; subst.\n    - eexists; split.\n      + econstructor; try reflexivity.\n        * eapply SSeqNil.\n        * eapply STrsIntAtomic.\n          econstructor; eauto.\n          econstructor.\n      + simpl; lia.\n    - specialize (IHAtomic H).\n      destruct IHAtomic as [sn [? ?]].\n      destruct (subList_dec idx_dec (idsOf rins) (sys_merqs sys)).\n      + eexists; split.\n        * econstructor; try reflexivity.\n          { eassumption. }\n          { eapply STrsExtAtomic.\n            econstructor; eauto.\n            econstructor.\n          }\n        * lia.\n      + eexists; split.\n        * econstructor; try reflexivity.\n          { eassumption. }\n          { eapply STrsIntAtomic.\n            econstructor; eauto.\n            econstructor.\n          }\n        * simpl; lia.\n  Qed.\n\n  Corollary internal_stransactional_split_each:\n    forall `{oifc: OStateIfc} (sys: System) inits ins trs outs eouts tn,\n      ~ SubList (idsOf inits) (sys_merqs sys) ->\n      Atomic inits ins trs outs eouts ->\n      STransactional sys trs tn ->\n      exists sn,\n        SSequential sys (lift_each trs) sn /\\\n        sn <= tn.\n  Proof.\n    intros.\n    inv H1; try (inv H0; fail).\n    - eapply intAtomic_stransactional_split_each; eauto.\n    - exfalso; inv H2.\n      pose proof (atomic_unique H0 H3); dest; subst.\n      auto.\n  Qed.\n\nEnd MsgParam.\n\nLemma atomic_Transactional_ExtAtomic:\n  forall `{dv: DecValue} `{oifc: OStateIfc} (sys: System) trs,\n    AtomicEx trs ->\n    Transactional sys trs ->\n    exists einits eouts,\n      ExtAtomic sys einits trs eouts.\nProof.\n  intros.\n  destruct H as [inits [ins [outs [eouts ?]]]].\n  inv H0; try (inv H; fail).\n  eauto.\nQed.\n\nLemma sequential_transactional_Forall:\n  forall `{dv: DecValue} `{oifc: OStateIfc} (sys: System) st1 trss st2,\n    steps step_m sys st1 (List.concat trss) st2 ->\n    Forall (Transactional sys) trss ->\n    Sequential sys (List.concat trss) trss.\nProof.\n  induction trss; simpl; intros; [repeat constructor|].\n  eapply steps_split in H; [|reflexivity].\n  destruct H as [sti [? ?]].\n  inv H0.\n  eapply sequential_cons; eauto.\nQed.\n\nLemma atomic_messages_eouts_count_le:\n  forall `{dv: DecValue} inits ins hst outs eouts,\n    Atomic inits ins hst outs eouts ->\n    forall `{oifc: OStateIfc} (sys: System) st1 st2,\n      steps step_m sys st1 hst st2 ->\n      forall idm,\n        count_occ (id_dec msg_dec) eouts idm <=\n        countMsg msg_dec idm st2.(st_msgs).\nProof.\n  induction 1; simpl; intros; subst.\n  - inv_steps; inv_step; simpl.\n    rewrite countMsg_enqMsgs; lia.\n  - inv_steps; inv_step; simpl.\n    rewrite count_occ_app, countMsg_enqMsgs.\n    specialize (IHAtomic _ _ _ _ H6 idm); simpl in IHAtomic.\n    destruct H14.\n    assert (NoDup rins) by (apply idsOf_NoDup in H3; auto).\n    pose proof (countMsg_deqMsgs msg_dec idm H3 H13).\n    pose proof (count_occ_removeL (id_dec msg_dec) idm H1 H4).\n    lia.\nQed.\n\nLemma atomic_messages_eouts_in:\n  forall `{dv: DecValue} inits ins hst outs eouts,\n    Atomic inits ins hst outs eouts ->\n    forall `{oifc: OStateIfc} (sys: System) st1 st2,\n      steps step_m sys st1 hst st2 ->\n      Forall (InMPI st2.(st_msgs)) eouts.\nProof.\n  intros.\n  apply Forall_forall; intros idm ?.\n  apply (countMsg_InMPI msg_dec).\n  eapply atomic_messages_eouts_count_le with (idm0:= idm) in H; eauto.\n  apply (count_occ_In (id_dec msg_dec)) in H1.\n  lia.\nQed.\n\nLemma atomic_messages_non_inits_count_eq:\n  forall `{dv: DecValue} inits ins hst outs eouts,\n    Atomic inits ins hst outs eouts ->\n    forall `{oifc: OStateIfc} (sys: System) st1 st2,\n      steps step_m sys st1 hst st2 ->\n      forall idm,\n        ~ In idm inits ->\n        countMsg msg_dec idm (st_msgs st1) +\n        count_occ (id_dec msg_dec) eouts idm =\n        countMsg msg_dec idm (st_msgs st2).\nProof.\n  induction 1; simpl; intros; subst.\n  - inv_steps; inv_step; simpl.\n    rewrite countMsg_enqMsgs.\n    destruct H11.\n    pose proof (countMsg_deqMsgs msg_dec idm H1 H10).\n    rewrite (count_occ_not_In (id_dec msg_dec)) in H0.\n    lia.\n  - inv_steps; inv_step; simpl.\n    rewrite count_occ_app, countMsg_enqMsgs.\n    rewrite Nat.add_assoc.\n    specialize (IHAtomic _ _ _ _ H7 _ H6); simpl in IHAtomic.\n    destruct H15.\n    assert (NoDup rins) by (apply idsOf_NoDup in H3; auto).\n    pose proof (countMsg_deqMsgs msg_dec idm H3 H14).\n    pose proof (count_occ_removeL (id_dec msg_dec) idm H1 H4).\n    lia.\nQed.\n\nLemma atomic_messages_in_in:\n  forall `{dv: DecValue} inits ins hst outs eouts,\n    Atomic inits ins hst outs eouts ->\n    forall `{oifc: OStateIfc} (sys: System) st1 st2,\n      steps step_m sys st1 hst st2 ->\n      forall idm,\n        InMPI (st_msgs st1) idm ->\n        ~ In idm inits ->\n        InMPI (st_msgs st2) idm.\nProof.\n  intros.\n  apply (countMsg_InMPI msg_dec) in H1.\n  apply (countMsg_InMPI msg_dec).\n  pose proof (atomic_messages_non_inits_count_eq H H0 _ H2).\n  lia.\nQed.\n\nCorollary atomic_messages_ins_ins:\n  forall `{dv: DecValue} inits ins hst outs eouts,\n    Atomic inits ins hst outs eouts ->\n    forall `{oifc: OStateIfc} (sys: System) st1 st2,\n      steps step_m sys st1 hst st2 ->\n      forall msgs,\n        Forall (InMPI (st_msgs st1)) msgs ->\n        DisjList inits msgs ->\n        Forall (InMPI (st_msgs st2)) msgs.\nProof.\n  intros.\n  rewrite Forall_forall in H1.\n  apply Forall_forall; intros idm ?.\n  eapply atomic_messages_in_in; eauto.\n  destruct (H2 idm); auto.\nQed.\n\nLemma atomic_non_inits_InMPI_or:\n  forall `{dv: DecValue} inits ins hst outs eouts,\n    Atomic inits ins hst outs eouts ->\n    forall `{oifc: OStateIfc} (sys: System) st1 st2,\n      steps step_m sys st1 hst st2 ->\n      forall idm,\n        ~ In idm inits ->\n        InMPI st2.(st_msgs) idm ->\n        InMPI st1.(st_msgs) idm \\/ In idm eouts.\nProof.\n  intros.\n  eapply atomic_messages_non_inits_count_eq in H; [|eassumption..].\n  apply (countMsg_InMPI msg_dec) in H2.\n  assert (countMsg msg_dec idm st1.(st_msgs) > 0 \\/\n          count_occ (id_dec msg_dec) eouts idm > 0) by lia.\n  destruct H3.\n  - left; apply (countMsg_InMPI msg_dec); assumption.\n  - right; apply (count_occ_In (id_dec msg_dec)); assumption.\nQed.\n\nLemma extAtomic_non_inits_InMPI_or:\n  forall `{dv: DecValue} `{oifc: OStateIfc} (sys: System) inits hst eouts,\n    ExtAtomic sys inits hst eouts ->\n    forall st1 st2,\n      steps step_m sys st1 hst st2 ->\n      forall idm,\n        ~ In (idOf idm) (sys_merqs sys) ->\n        InMPI st2.(st_msgs) idm ->\n        InMPI st1.(st_msgs) idm \\/ In idm eouts.\nProof.\n  intros.\n  inv H.\n  eapply atomic_non_inits_InMPI_or; try eassumption.\n  intro Hx.\n  apply in_map with (f:= idOf) in Hx.\n  apply H3 in Hx; auto.\nQed.\n\nLemma extAtomic_multi_non_inits_InMPI_or:\n  forall `{dv: DecValue} `{oifc: OStateIfc} (sys: System) st1,\n    Reachable (steps step_m) sys st1 ->\n    forall trss st2,\n      steps step_m sys st1 (List.concat trss) st2 ->\n      Forall AtomicEx trss ->\n      Forall (Transactional sys) trss ->\n      forall idm,\n        ~ In (idOf idm) (sys_merqs sys) ->\n        InMPI st2.(st_msgs) idm ->\n        InMPI st1.(st_msgs) idm \\/\n        exists einits trs eouts,\n          In trs trss /\\\n          ExtAtomic sys einits trs eouts /\\\n          In idm eouts.\nProof.\n  induction trss as [|trs trss]; simpl; intros; [inv_steps; auto|].\n\n  eapply steps_split in H0; [|reflexivity].\n  destruct H0 as [sti [? ?]].\n  inv H1; inv H2.\n  pose proof (atomic_Transactional_ExtAtomic H8 H7).\n  destruct H1 as [einits [eouts ?]].\n\n  eapply extAtomic_non_inits_InMPI_or in H5; try eassumption.\n  destruct H5; [|eauto 8].\n\n  specialize (IHtrss _ H0 H9 H10 _ H3 H2).\n  destruct IHtrss; [auto|].\n  destruct H5 as [teinits [ttrs [teouts ?]]]; dest.\n  right; eauto 7.\nQed.\n\nCorollary extAtomic_multi_IntMsgsEmpty_non_inits_InMPI:\n  forall `{dv: DecValue} `{oifc: OStateIfc} (sys: System) st1,\n    Reachable (steps step_m) sys st1 ->\n    IntMsgsEmpty sys st1.(st_msgs) ->\n    forall trss st2,\n      steps step_m sys st1 (List.concat trss) st2 ->\n      Forall AtomicEx trss ->\n      Forall (Transactional sys) trss ->\n      forall idm,\n        In (idOf idm) (sys_minds sys) ->\n        InMPI st2.(st_msgs) idm ->\n        exists einits trs eouts,\n          In trs trss /\\\n          ExtAtomic sys einits trs eouts /\\\n          In idm eouts.\nProof.\n  intros.\n  eapply extAtomic_multi_non_inits_InMPI_or in H1; try eassumption.\n  - destruct H1; [|assumption].\n    exfalso.\n    specialize (H0 _ H4).\n    apply findQ_length_ge_one in H1.\n    rewrite H0 in H1; simpl in H1; lia.\n  - eapply DisjList_In_2.\n    + eapply sys_minds_sys_merqs_DisjList.\n    + assumption.\nQed.\n\nLemma insLbl_IntMsgsEmpty:\n  forall `{dv: DecValue} `{oifc: OStateIfc} (sys: System) st1 lbl st2,\n    step_m sys st1 lbl st2 ->\n    IntMsgsEmpty sys st1.(st_msgs) ->\n    InsLbl lbl ->\n    IntMsgsEmpty sys st2.(st_msgs).\nProof.\n  intros; red in H1.\n  inv H; try (exfalso; auto; fail).\n  simpl in *.\n  red in H3; dest.\n  red in H0; red; intros.\n  specialize (H0 _ H4).\n  rewrite findQ_not_In_enqMsgs.\n  - assumption.\n  - intro Hx; apply H in Hx.\n    destruct (sys_minds_sys_merqs_DisjList sys midx); auto.\nQed.\n\nLemma insHistory_IntMsgsEmpty:\n  forall `{dv: DecValue} `{oifc: OStateIfc} (sys: System) st1 hst st2,\n    steps step_m sys st1 hst st2 ->\n    IntMsgsEmpty sys st1.(st_msgs) ->\n    InsHistory hst ->\n    IntMsgsEmpty sys st2.(st_msgs).\nProof.\n  induction 1; simpl; intros; auto.\n  inv H2.\n  eapply insLbl_IntMsgsEmpty; eauto.\nQed.\n\nLemma atomic_legal_eouts:\n  forall `{dv: DecValue} (hst: History) inits ins outs eouts,\n    Atomic inits ins hst outs eouts ->\n    forall `{oifc: OStateIfc} (sys: System) st1 st2,\n      steps step_m sys st1 hst st2 ->\n      (forall nouts,\n          removeL (id_dec msg_dec) (inits ++ outs ++ nouts) ins =\n          removeL (id_dec msg_dec) (inits ++ outs) ins ++ nouts) /\\\n      eouts = removeL (id_dec msg_dec) (inits ++ outs) ins.\nProof.\n  induction 1; simpl; intros; subst.\n  - split.\n    + intros.\n      do 2 rewrite removeL_app_2.\n      reflexivity.\n    + rewrite removeL_app_2; reflexivity.\n  - inv H5.\n    specialize (IHAtomic _ _ _ _ H6).\n    assert (NoDup rins) by (inv H8; destruct H14; apply idsOf_NoDup; auto).\n    dest; subst; split.\n    + intros.\n      do 2 rewrite removeL_app_1.\n      rewrite <-app_assoc.\n      do 2 rewrite H3.\n      do 2 (rewrite removeL_app_3 with (l3:= rins) by assumption).\n      apply app_assoc.\n    + rewrite removeL_app_1.\n      rewrite H3.\n      rewrite removeL_app_3 with (l3:= rins) by assumption.\n      reflexivity.\nQed.\n\nLemma atomic_eouts_not_erqs:\n  forall `{dv: DecValue} inits ins hst outs eouts,\n    Atomic inits ins hst outs eouts ->\n    forall `{oifc: OStateIfc} (sys: System) st1 st2,\n      steps step_m sys st1 hst st2 ->\n      Forall (fun eout => ~ In (idOf eout) sys.(sys_merqs)) eouts.\nProof.\n  induction 1; simpl; intros; subst.\n  - inv_steps; inv_step.\n    destruct H14.\n    apply Forall_forall; intros [midx msg] ?.\n    apply in_map with (f:= idOf) in H1.\n    simpl in *.\n    apply H in H1.\n    eapply DisjList_In_2; [|eassumption].\n    apply DisjList_app_4.\n    + apply sys_minds_sys_merqs_DisjList.\n    + apply DisjList_comm, sys_merqs_sys_merss_DisjList.\n  - inv_steps.\n    apply Forall_app; [apply forall_removeL; eauto|].\n    inv_step.\n    destruct H18.\n    apply Forall_forall; intros [midx msg] ?.\n    apply in_map with (f:= idOf) in H4.\n    simpl in *.\n    apply H2 in H4.\n    eapply DisjList_In_2; [|eassumption].\n    apply DisjList_app_4.\n    + apply sys_minds_sys_merqs_DisjList.\n    + apply DisjList_comm, sys_merqs_sys_merss_DisjList.\nQed.\n\nLemma atomic_inits_in:\n  forall `{dv: DecValue} inits ins hst outs eouts,\n    Atomic inits ins hst outs eouts ->\n    SubList inits ins.\nProof.\n  induction 1; simpl; intros; subst;\n    [apply SubList_refl|].\n  apply SubList_app_1; auto.\nQed.\n\nLemma atomic_eouts_in:\n  forall `{dv: DecValue} inits ins hst outs eouts,\n    Atomic inits ins hst outs eouts ->\n    SubList eouts outs.\nProof.\n  induction 1; simpl; intros; subst;\n    [apply SubList_refl|].\n  apply SubList_app_3.\n  - eapply SubList_trans.\n    + apply removeL_SubList_2.\n    + apply SubList_app_1; auto.\n  - apply SubList_app_2, SubList_refl.\nQed.\n\nLemma atomic_outs_cases:\n  forall `{dv: DecValue} inits ins hst outs eouts,\n    Atomic inits ins hst outs eouts ->\n    forall msg,\n      In msg outs -> In msg eouts \\/ In msg ins.\nProof.\n  induction 1; simpl; intros; subst; auto.\n\n  apply in_app_or in H5; destruct H5.\n  - specialize (IHAtomic _ H2); destruct IHAtomic.\n    + destruct (in_dec (id_dec msg_dec) msg rins).\n      * right; apply in_or_app; auto.\n      * left; apply in_or_app; left.\n        apply removeL_In_1; auto.\n    + right; apply in_or_app; auto.\n  - left; apply in_or_app; auto.\nQed.\n\nLemma atomic_ins_cases:\n  forall `{dv: DecValue} inits ins hst outs eouts,\n    Atomic inits ins hst outs eouts ->\n    forall msg,\n      In msg ins -> In msg inits \\/ In msg outs.\nProof.\n  induction 1; simpl; intros; subst; auto.\n\n  apply in_app_or in H5; destruct H5.\n  - specialize (IHAtomic _ H2); destruct IHAtomic; auto.\n    right; apply in_or_app; auto.\n  - apply H1 in H2.\n    pose proof (atomic_eouts_in H).\n    apply H3 in H2.\n    right; apply in_or_app; auto.\nQed.\n\nLemma atomic_app_SSubList:\n  forall `{dv: DecValue} (hst1: History) inits1 ins1 outs1 eouts1,\n    Atomic inits1 ins1 hst1 outs1 eouts1 ->\n    forall hst2 inits2 ins2 outs2 eouts2,\n      inits2 <> nil ->\n      Atomic inits2 ins2 hst2 outs2 eouts2 ->\n      SubList inits2 eouts1 ->\n      exists eouts,\n        SSubList eouts2 eouts /\\\n        Atomic inits1 (ins1 ++ ins2)\n               (hst2 ++ hst1)\n               (outs1 ++ outs2)\n               eouts.\nProof.\n  induction 3; simpl; intros.\n  - eexists; split; [|econstructor; eauto].\n    apply SSubList_app_1.\n  - subst.\n    specialize (IHAtomic H0 H7).\n    destruct IHAtomic as [peouts [? ?]].\n\n    eexists; split;\n      [|apply SSubList_SubList in H4;\n        do 2 rewrite app_assoc;\n        econstructor; eauto;\n        eapply SubList_trans; eauto].\n\n    apply SSubList_app_2.\n    apply SSubList_removeL_2; auto.\nQed.\n\nCorollary atomic_app:\n  forall `{dv: DecValue} (hst1: History) inits1 ins1 outs1 eouts1,\n    Atomic inits1 ins1 hst1 outs1 eouts1 ->\n    forall hst2 inits2 ins2 outs2 eouts2,\n      inits2 <> nil ->\n      Atomic inits2 ins2 hst2 outs2 eouts2 ->\n      SubList inits2 eouts1 ->\n      exists eouts,\n        Atomic inits1 (ins1 ++ ins2)\n               (hst2 ++ hst1)\n               (outs1 ++ outs2)\n               eouts.\nProof.\n  intros.\n  pose proof (atomic_app_SSubList H H0 H1 H2).\n  dest; eauto.\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/SerialFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883592602051, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2836991202822271}}
{"text": "Require Import Extraction.\nRequire ExtrHaskellBasic.\nRequire ExtrHaskellNatInteger.\nRequire ExtrHaskellZInteger.\nExtraction Language Haskell.\nUnset Extraction SafeImplicits.\n\nRequire Import ZArith_base.\n\nExtract Inlined Constant Z.of_nat => \"\".\nExtract Inlined Constant Z.add => \"(Prelude.+)\".\nExtract Inlined Constant Z.sub => \"(Prelude.-)\".\nExtract Inlined Constant Z.succ => \"(Prelude.+ 1)\".\nExtract Inlined Constant Z.opp => \"Prelude.negate\".\n\nRequire Import Base.\n\nExtract Inlined Constant projP1 => \"\".\n\nRequire Import Kleene.\n\n(* Declare the existence of Kleeneans *)\nParameter K : Set.\nAxiom K_LazyBool : LazyBool K.\n\n(* interpreting Kleeneans *)\nExtract Inlined Constant K => \"AERN2.CKleenean\".\n\n(* Erase the type class parameter and map to concrete types in Haskell. *)\nExtraction Implicit lazy_bool_true [ LB ].\nExtract Constant lazy_bool_true => \"AERN2.ckleenean Prelude.True\".\n\nExtraction Implicit lazy_bool_false [ LB ].\nExtract Constant lazy_bool_false => \"AERN2.ckleenean Prelude.False\".\n\nExtraction Implicit lazy_bool_neg [ LB ].\nExtract Constant lazy_bool_neg => \"\\x -> __uc (OGB.not (__K x))\".\n\nExtraction Implicit lazy_bool_or [ LB ].\nExtract Constant lazy_bool_or => \"\\x y -> __uc ((__K x) OGB.|| (__K y))\".\n\nExtraction Implicit lazy_bool_and [ LB ].\nExtract Constant lazy_bool_and => \"\\x y -> __uc ((__K x) OGB.&& (__K y))\".\n\nExtraction Implicit lazy_bool_defined_is_bool [ LB ].\nExtract Inlined Constant lazy_bool_defined_is_bool => \"Prelude.error \"\"UNREALIZED lazy_bool_defined_is_bool\"\" \".\n\n(* Test extraction of Kleeneans *)\n\nSection K_Dummy_Defs.\n  Generalizable Variable K.\n  Context `(klb : LazyBool K).\n  Definition k_test := lazy_bool_and lazy_bool_true lazy_bool_false.\nEnd K_Dummy_Defs.\n\n(* Extraction Implicit k_test [ 1 ]. *)\n(* Extraction \"K_Test\" k_test. *)\n\nRequire Import Monad.\nRequire Import ClassicalMonads.\nRequire Import MultivalueMonad.\n\n(* Declare the existence of multivaluemonad *)\nParameter M : Type -> Type.\nAxiom M_Monad : Monad M.\nAxiom MultivalueMonad_description : Monoid_hom M_Monad NPset_Monad.\nAxiom M_MultivalueMonad : @MultivalueMonad _ K_LazyBool _ _ MultivalueMonad_description.\n\n(* interpreting multivaluemonad *)\nExtract Constant M \"a\" => \"a\".\n\nExtraction Implicit Monad_fun_map [ Monad ].\nExtract Inlined Constant Monad_fun_map => \"__uc\".\n\nExtraction Implicit Monad_unit [ Monad ].\nExtract Inlined Constant Monad_unit => \"__uc\".\n\nExtraction Implicit Monad_mult [ Monad ].\nExtract Inlined Constant Monad_mult => \"__uc\".\n\nExtract Constant MultivalueMonad_description => \"(Prelude.error \"\"UNREALIZED MultivalueMonad_description\"\")\".\n\n\n(* Shortcut extractions for improved readability. *)\nExtraction Implicit M_unit [ M_Monad ].\nExtract Inlined Constant M_unit => \"__uc\".\nExtraction Implicit M_mult [ M_Monad ].\nExtract Inlined Constant M_mult => \"__uc\".\nExtraction Implicit M_lift [ M_Monad ].\nExtract Inlined Constant M_lift => \"__uc\".\nExtraction Implicit M_lift_dom [ M_Monad ].\nExtract Inlined Constant M_lift_dom => \"__uc\".\nExtraction Implicit mjoin [ M_Monad ].\nExtract Inlined Constant mjoin => \"__uc\".\n\nExtraction Implicit MultivalueMonad_base_monad_traces_lift [ klb M_Monad MultivalueMonad_description MultivalueMonad ].\nExtract Constant MultivalueMonad_base_monad_traces_lift => \"(\\ x0 f -> __uc (\\n -> Prelude.foldl (Prelude.flip (__uc f)) (x0) [0 .. ((n :: Prelude.Integer) Prelude.- 1)]))\".\n\nExtraction Implicit MultivalueMonad_base_monad_hprop_elim [ klb M_Monad MultivalueMonad_description MultivalueMonad ].\nExtract Inlined Constant MultivalueMonad_base_monad_hprop_elim => \"__uc\".\n\nExtraction Implicit multivalued_choice [ klb M_Monad MultivalueMonad_description MultivalueMonad ].\nExtract Constant multivalued_choice => \"(\\k1 k2 -> __uc (AERN2.select (__K k1) (__K k2)))\".\n\nExtraction Implicit M_hprop_elim_f [ klb M_Monad MultivalueMonad_description M_MultivalueMonad ].\nExtract Inlined Constant M_hprop_elim_f => \"__uc\".\n\nExtraction Implicit choose [ klb M_Monad MultivalueMonad_description M_MultivalueMonad ].\n\nExtraction Implicit M_paths [ klb M_Monad MultivalueMonad_description M_MultivalueMonad ].\n\nExtraction Implicit semidec_or [ klb ].\nExtraction Implicit semidec_and [ klb ].\n\n\n(* (\\ _ m -> m)  *)\n\n(* MultivalueMonad_destruct *)\n(* (\\ _ m -> m) *)\n\nExtraction Implicit select [ klb M_Monad MultivalueMonad_description M_MultivalueMonad ].\n\n(* Some shortcuts for efficiency. *)\nExtraction Implicit M_countable_lift [ klb M_Monad MultivalueMonad_description M_MultivalueMonad ].\nExtract Inlined Constant M_countable_lift => \"__uc\". \n\n(* Test extraction of multivaluemonad *)\nDefinition m_test := @select _ _ _ _ _ M_MultivalueMonad.\n(* Extraction \"M_Test\" m_test. *)\n\nRequire Import Real.\n\n(* Assume that there is R*)\nParameter R : Set.\nAxiom R_SemiDecOrderedField : @SemiDecOrderedField  _ K_LazyBool R.\nAxiom R_ComplArchiSemiDecOrderedField : @ComplArchiSemiDecOrderedField _ _ _ R_SemiDecOrderedField.\n\nExtract Inlined Constant R => \"AERN2.CReal\".\n\nExtraction Implicit real_0 [ klb SemiDecOrderedField ].\nExtract Constant real_0 => \"(__uc (0 :: AERN2.CReal))\".\n\nExtraction Implicit real_1 [ klb SemiDecOrderedField ].\nExtract Constant real_1 => \"(__uc (1 :: AERN2.CReal))\".\n\nExtraction Implicit real_2 [ klb SemiDecOrderedField_Real ].\nExtract Constant real_2 => \"(__uc (2 :: AERN2.CReal))\".\n\n(* Extraction Implicit real_3 [ klb SemiDecOrderedField_Real ]. *)\n(* Extract Constant real_3 => \"(__uc (3 :: AERN2.CReal))\". *)\n\nExtraction Implicit real_plus [ klb SemiDecOrderedField ].\nExtract Constant real_plus => \"(\\x y -> __uc (((__R x) Prelude.+ (__R y))))\".\n\nExtraction Implicit real_mult [ klb SemiDecOrderedField ].\nExtract Constant real_mult => \"(\\x y -> __uc (((__R x) Prelude.* (__R y))))\".\n\nExtraction Implicit real_opp [ klb SemiDecOrderedField ].\nExtract Constant real_opp => \"(\\x -> __uc (Prelude.negate (__R x)))\".\n\nExtraction Implicit real_inv [ klb SemiDecOrderedField ].\nExtract Constant real_inv => \"(\\x -> __uc (Prelude.recip (__R x)))\".\n\nExtraction Implicit real_lt_semidec [ klb SemiDecOrderedField ].\nExtract Constant real_lt_semidec => \"(\\ x y -> __uc ((__R x) OGB.< (__R y)))\".\n\nExtraction Implicit real_limit_p [ klb SemiDecOrderedField_Real ComplArchiSemiDecOrderedField ].\nExtract Constant real_limit_p => \"(\\ f -> __uc (AERN2.limit (__seqR f)))\".\n\nExtraction Implicit real_limit [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real ].\nExtraction Implicit real_limit_P [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real ].\nExtraction Implicit real_limit_P_p [ klb SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real ].\nExtraction Implicit real_limit_P_lt [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real ].\nExtraction Implicit real_limit_P_lt_p [ klb SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real ].\nExtraction Implicit real_mslimit_P [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real ].\nExtraction Implicit real_mslimit_P_p [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real ].\nExtraction Implicit real_mslimit_P_lt [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real ].\nExtraction Implicit real_mslimit_P_lt_p [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real ].\n\nExtraction Implicit M_split [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ].\n\n(* Some optional shortcuts for increased efficiency. *)\nExtraction Implicit IZreal [ klb SemiDecOrderedField_Real ].\nExtract Constant IZreal => \"(\\z -> __uc (AERN2.creal z))\".\nExtraction Implicit real_minus [ klb SemiDecOrderedField_Real ].\nExtract Constant real_minus => \"(\\x y -> __uc (((__R x) Prelude.- (__R y))))\".\nExtraction Implicit real_div [ klb SemiDecOrderedField_Real ].\nExtract Constant real_div => \"(\\x y -> __uc (((__R x) Prelude./ (__R y))))\".\nExtraction Implicit prec [ klb SemiDecOrderedField_Real ].\nExtract Constant prec => \"(\\n -> __uc ((0.5 :: AERN2.CReal) Prelude.^ n))\".\n\nExtraction Implicit abs [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real ].\n\nExtraction Implicit abs_prop [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real ].\n\n(* Test extraction of R *)\nSection Real_tests.\n  Local Open Scope Real_scope.\n\n  Generalizable Variables K M R.\n\n  Context `{klb : LazyBool K} `{M_Monad : Monad M}\n    {MultivalueMonad_description : Monoid_hom M_Monad NPset_Monad} \n    {M_MultivalueMonad : MultivalueMonad}\n    {R : Type}\n    {R_OF : SemiDecOrderedField R}.\n  \n  Definition real_test1 := (- real_1) + (IZreal 2) - (prec 2).\nEnd Real_tests.\n\nExtraction Implicit real_test1 [ klb R_OF ].\nDefinition R_test1 := @real_test1 _ _ R_SemiDecOrderedField.\n(* Extraction \"R_Test1\" R_test1. *)\n\nDefinition R_test2 := @real_limit_p _ _ _ _ R_ComplArchiSemiDecOrderedField.\n(* Extraction \"R_Test2\" R_test2. *)\n\nExtract Inductive bool => \"Prelude.Bool\" [ \"Prelude.True\" \"Prelude.False\" ].\nExtract Inductive sumbool => \"Prelude.Bool\" [ \"Prelude.True\" \"Prelude.False\" ].\n\nExtract Inductive sigT => \"(,)\" [\"(,)\"].\nExtract Inductive prod => \"(,)\"  [ \"(,)\" ].\n\nExtract Inlined Constant Nat.log2 => \"(MNP.integer Prelude.. Logs.integerLog2)\".\n\n(* Sewon's lab seminar talk material*)\n(* Maximum *)\n\n(* root finding function *)\nRequire Import IVT.\n\nExtraction Implicit real_3 [ klb SemiDecOrderedField_Real ].\nExtract Constant real_3 => \"(__uc (3 :: AERN2.CReal))\".\n\nExtraction Implicit CIVT [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real ].\nExtraction Implicit root_approx [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real ].\nExtraction Implicit halving [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real ].\nExtraction Implicit trisect [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real ].\nExtraction Implicit M_uniq_pick [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real ].\n\nDefinition R_CIVT := @CIVT _ _ _ _ _ M_MultivalueMonad _ _ R_ComplArchiSemiDecOrderedField.\n\nExtraction \"IVT\" R_CIVT.\n\n(* maximum *)\nRequire Import Minmax.\n\nExtraction Implicit real_max_prop [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real ].\nExtraction Implicit real_max [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real ].\n\nDefinition R_real_max := @real_max _ _ _ _ _ M_MultivalueMonad _ _ R_ComplArchiSemiDecOrderedField.\nExtraction \"Max\" R_real_max.\n\n(* magnitude *)\nRequire Import testsearch.\n\nExtraction Implicit weaken_orM_r [ M_Monad ].\n\nExtraction Implicit epsilon_smallest_choose_M [ klb M_Monad MultivalueMonad_description M_MultivalueMonad ].\n\nExtraction Implicit epsilon_smallest_PQ_M [ klb M_Monad MultivalueMonad_description M_MultivalueMonad ].\n\nRequire Import magnitude.\n\nExtraction Implicit magnitude [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ].\nExtraction Implicit magnitude1 [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ].\nExtraction Implicit magnitude2 [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ].\nExtraction Implicit dec_x_lt_2 [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ].\n\nExtraction Implicit Zpow [ klb SemiDecOrderedField_Real ].\n\nDefinition R_magnitude := @magnitude _ _ _ _ _ M_MultivalueMonad _ R_SemiDecOrderedField.\nExtraction \"Magnitude\" R_magnitude.\n\nRequire Import RealRing.\n\nExtraction Implicit pow [ klb SemiDecOrderedField_Real ].\n\nRequire Import Complex.\n\nExtraction Implicit complex0 [ klb SemiDecOrderedField_Real ].\n\nRequire Import Euclidean.\n\nExtraction Implicit euclidean_max_dist [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real].\n\nExtraction Implicit euclidean_mlimit_PQ [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real].\n\nExtraction Implicit euclidean_max_norm [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real].\n\nExtraction Implicit euclidean_limit [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real].\n\nExtraction Implicit euclidean_zero [ klb SemiDecOrderedField_Real].\n\nExtraction Implicit euclidean_opp [ klb SemiDecOrderedField_Real].\n\nExtraction Implicit euclidean_plus [ klb SemiDecOrderedField_Real].\n\nExtraction Implicit euclidean_minus [ klb SemiDecOrderedField_Real].\n\n(* sqrt *)\nRequire Import sqrt.\n\nExtraction Implicit sqrt [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real ].\n\nExtraction Implicit sqrt_pos [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real ].\n\nExtraction Implicit scale [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ].\n\nExtraction Implicit restr_sqrt [ klb SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real ].\n\nExtraction Implicit sqrt_approx_fast [ klb SemiDecOrderedField_Real ].\n\nExtraction Implicit sqrt_approx [ klb SemiDecOrderedField_Real ].\n\n\nDefinition R_sqrt2 := @sqrt _ _ _ _ _ M_MultivalueMonad _ _ R_ComplArchiSemiDecOrderedField.\nExtraction \"Sqrt\" R_sqrt2.\n\nExtraction Implicit csqrt [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real ].\n\nExtraction Implicit csqrt_neq0 [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ComplArchiSemiDecOrderedField_Real ].\n\nExtraction Implicit complex_nonzero_cases [ klb M_Monad MultivalueMonad_description M_MultivalueMonad SemiDecOrderedField_Real ].\n\nDefinition C_sqrt2 := @csqrt _ _ _ _ _ M_MultivalueMonad _ _ R_ComplArchiSemiDecOrderedField.\nExtraction \"CSqrt\" C_sqrt2.\n\n(* Require Import Nabla. *)\n\n(* Require Import Coq.Reals.Abstract.ConstructiveMinMax. *)\n\n(* Recursive Extraction CRmin. *)\n\n(*\n\nThe Haskell module will require the following packages:\n- cdar-mBound >= 0.1.0.1\n- collect-errors >= 0.1.4\n- mixed-types-num >= 0.5.3\n- aern2-mp >= 0.2.1\n- aern2-real >= 0.2.1\n- integer-logarithms\n\nIn the generated Haskell files, add the following imports and definitions:\n\nimport MixedTypesNumPrelude (ifThenElse)\nimport qualified Numeric.OrdGenericBool as OGB\nimport qualified Unsafe.Coerce as UC\nimport qualified Control.Monad\nimport qualified Data.Functor\nimport qualified MixedTypesNumPrelude as MNP\nimport qualified Math.NumberTheory.Logarithms as Logs\nimport qualified AERN2.Real as AERN2\n\n__uc :: a -> b\n__uc = UC.unsafeCoerce\n__K :: a -> AERN2.CKleenean\n__K = UC.unsafeCoerce\n__R :: a -> AERN2.CReal\n__R = UC.unsafeCoerce\n__seqR :: a -> (Prelude.Integer -> AERN2.CReal)\n__seqR = UC.unsafeCoerce\n\n*)\n", "meta": {"author": "holgerthies", "repo": "coq-aern", "sha": "c7a154fe814f008674a66c3df69b7b97b6c3961b", "save_path": "github-repos/coq/holgerthies-coq-aern", "path": "github-repos/coq/holgerthies-coq-aern/coq-aern-c7a154fe814f008674a66c3df69b7b97b6c3961b/formalization/extract.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.28369912028222705}}
{"text": "Add LoadPath \"../..\".\nRequire Import HybND_Substitution.\nRequire Import Setoid.\nRequire Import LibList.\nRequire Import PermutLib.\nRequire Import HybND_PPermutLib.\nRequire Import HybND_OkLib.\nRequire Import HybND_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\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.\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_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\nwhere \" M |-> N \" := (step_Hyb M N ) : hybrid_is5_scope.\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\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.\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.\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.\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.\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.\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.\nQed.\n\n(*\n   Proof sketch: double induction on typing and making a step\n   * FIXME: eauto takes ages :(\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.\nQed.\n\nLemma lc_t_step_Hyb:\nforall M N w,\n  lc_t_Hyb M ->\n  (M, w) |-> (N, w) ->\n  lc_t_Hyb N.\ninduction M; intros; inversion H0; subst.\napply lc_t_subst_Hyb; auto.\nconstructor; eauto. apply IHM1 with w; auto.\napply lc_t_subst_w_Hyb; auto.\nconstructor; apply IHM with v; auto.\nQed.\n\nLemma lc_w_step_Hyb:\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.\napply lc_w_subst_t_Hyb; auto.\nconstructor; eauto. apply IHM1 with w; auto.\napply lc_w_subst_Hyb; auto.\ninversion H; subst; try omega; constructor; apply IHM with w0; auto.\nQed.\n\nLemma value_no_step:\nforall M,\n  value_Hyb M ->\n  forall N w, (M,  w) |-> (N, w) ->\n             False.\ninduction M; intros;\ntry inversion H; subst;\ninversion H0; subst;\nrewrite IHM; eauto.\nQed.\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.\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.\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/NoDiamond/HybND_Semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.28369912028222705}}
{"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\nRequire Import Values. (*for me\nminj, compose_meminj,...*)\n\nSet Implicit Arguments.\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        Eqfsim_match_start_stacks:\n          forall s1 f arg m0, start_stack L1 m0 s1 f arg  ->\n                         exists i s2, start_stack L2 m0 s2 f arg /\\ Eqmatch_states i s1 s2;\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    Extfsim_match_start_stacks:\n      forall s1 f arg m0, start_stack L1 m0 s1 f arg  ->\n                     exists i s2, start_stack L2 m0 s2 f arg /\\ Extmatch_states i s1 s2;\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  (** *Extension 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,\n            Injmatch_states i f s1 s2 ->\n            injection_full f (get_mem1 s1);\n        Injfsim_match_start_stacks:\n          forall s1 f arg m0, start_stack L1 m0 s1 f arg  ->\n                         exists i j s2, start_stack L2 m0 s2 f arg /\\ Injmatch_states i j s1 s2;\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- (* entry point *)\n  intros. exploit (Injfsim_match_start_stacks SIM12); eauto. intros [i [ j [s2 [A B]]]].\n  exploit (Extfsim_match_start_stacks SIM23); eauto. intros [i' [s3 [C D]]].\n  exists (i', i); exists j; exists s3; split; auto. exists s2; auto.\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- (* entry points *)\n  intros. exploit (Extfsim_match_start_stacks SIM12); eauto. intros [i [s2 [A B]]].\n  exploit (Injfsim_match_start_stacks SIM23); eauto. intros [i' [j [s3 [C D]]]].\n  exists (i', i); exists j; exists s3; split; auto. exists s2; auto.\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- (* entry points *)\n  intros. exploit (Injfsim_match_start_stacks SIM12); eauto.\n  intros [i [ f12 [s2 [A B]]]].\n  exploit (Injfsim_match_start_stacks 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- (* 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  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/ExposedSimulations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.283699113521498}}
{"text": "From iris.algebra Require Export auth excl updates.\nFrom iris.algebra Require Import local_updates.\nFrom iris.base_logic Require Import base_logic.\nFrom iris Require Import options.\n\n(** Authoritative CMRA where the fragment is exclusively owned.\nThis is effectively a single \"ghost variable\" with two views, the frament [◯E a]\nand the authority [●E a]. *)\n\nDefinition excl_authR (A : ofeT) : cmraT :=\n  authR (optionUR (exclR A)).\nDefinition excl_authUR (A : ofeT) : ucmraT :=\n  authUR (optionUR (exclR A)).\n\nDefinition excl_auth_auth {A : ofeT} (a : A) : excl_authR A :=\n  ● (Some (Excl a)).\nDefinition excl_auth_frag {A : ofeT} (a : A) : excl_authR A :=\n  ◯ (Some (Excl a)).\n\nTypeclasses Opaque excl_auth_auth excl_auth_frag.\n\nInstance: Params (@excl_auth_auth) 1 := {}.\nInstance: Params (@excl_auth_frag) 2 := {}.\n\nNotation \"●E a\" := (excl_auth_auth a) (at level 10).\nNotation \"◯E a\" := (excl_auth_frag a) (at level 10).\n\nSection excl_auth.\n  Context {A : ofeT}.\n  Implicit Types a b : A.\n\n  Global Instance excl_auth_auth_ne : NonExpansive (@excl_auth_auth A).\n  Proof. solve_proper. Qed.\n  Global Instance excl_auth_auth_proper : Proper ((≡) ==> (≡)) (@excl_auth_auth A).\n  Proof. solve_proper. Qed.\n  Global Instance excl_auth_frag_ne : NonExpansive (@excl_auth_frag A).\n  Proof. solve_proper. Qed.\n  Global Instance excl_auth_frag_proper : Proper ((≡) ==> (≡)) (@excl_auth_frag A).\n  Proof. solve_proper. Qed.\n\n  Global Instance excl_auth_auth_discrete a : Discrete a → Discrete (●E a).\n  Proof. intros; apply auth_auth_discrete; [apply Some_discrete|]; apply _. Qed.\n  Global Instance excl_auth_frag_discrete a : Discrete a → Discrete (◯E a).\n  Proof. intros; apply auth_frag_discrete, Some_discrete; apply _. Qed.\n\n  Lemma excl_auth_validN n a : ✓{n} (●E a ⋅ ◯E a).\n  Proof. by rewrite auth_both_validN. Qed.\n  Lemma excl_auth_valid a : ✓ (●E a ⋅ ◯E a).\n  Proof. intros. by apply auth_both_valid_2. Qed.\n\n  Lemma excl_auth_agreeN n a b : ✓{n} (●E a ⋅ ◯E b) → a ≡{n}≡ b.\n  Proof.\n    rewrite auth_both_validN /= => -[Hincl Hvalid].\n    move: Hincl=> /Some_includedN_exclusive /(_ I) ?. by apply (inj Excl).\n  Qed.\n  Lemma excl_auth_agree a b : ✓ (●E a ⋅ ◯E b) → a ≡ b.\n  Proof.\n    intros. apply equiv_dist=> n. by apply excl_auth_agreeN, cmra_valid_validN.\n  Qed.\n  Lemma excl_auth_agree_L `{!LeibnizEquiv A} a b : ✓ (●E a ⋅ ◯E b) → a = b.\n  Proof. intros. by apply leibniz_equiv, excl_auth_agree. Qed.\n\n  Lemma excl_auth_agreeI {M} a b : ✓ (●E a ⋅ ◯E b) ⊢@{uPredI M} (a ≡ b).\n  Proof.\n    rewrite auth_both_validI bi.and_elim_l.\n    apply bi.exist_elim=> -[[c|]|];\n      by rewrite option_equivI /= excl_equivI //= bi.False_elim.\n  Qed.\n\n  Lemma excl_auth_frag_validN_op_1_l n a b : ✓{n} (◯E a ⋅ ◯E b) → False.\n  Proof. by rewrite -auth_frag_op auth_frag_validN. Qed.\n  Lemma excl_auth_frag_valid_op_1_l a b : ✓ (◯E a ⋅ ◯E b) → False.\n  Proof. by rewrite -auth_frag_op auth_frag_valid. Qed.\n\n  Lemma excl_auth_update a b a' : ●E a ⋅ ◯E b ~~> ●E a' ⋅ ◯E a'.\n  Proof.\n    intros. by apply auth_update, option_local_update, exclusive_local_update.\n  Qed.\nEnd excl_auth.\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/excl_auth.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.28369911352149796}}
{"text": "(**\nThis file is part of the Flocq formalization of floating-point\narithmetic in Coq: http://flocq.gforge.inria.fr/\n\nCopyright (C) 2010-2011 Sylvie Boldo\n#<br />#\nCopyright (C) 2010-2011 Guillaume Melquiond\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 3 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nCOPYING file for more details.\n*)\n\n(** * Remainder of the division and square root are in the FLX format *)\nRequire Import Fcore.\nRequire Import Fcalc_ops.\nRequire Import Fprop_relative.\n\nSection Fprop_divsqrt_error.\n\nVariable beta : radix.\nNotation bpow e := (bpow beta e).\n\nVariable prec : Z.\n\nTheorem generic_format_plus_prec:\n  forall fexp, (forall e, (fexp e  <= e - prec)%Z) ->\n  forall x y (fx fy: float beta),\n  (x = F2R fx)%R -> (y = F2R fy)%R -> (Rabs (x+y) < bpow (prec+Fexp fx))%R -> (Rabs (x+y) < bpow (prec+Fexp fy))%R\n  -> generic_format beta fexp (x+y)%R.\nintros fexp Hfexp x y fx fy Hx Hy H1 H2.\ncase (Req_dec (x+y) 0); intros H.\nrewrite H; apply generic_format_0.\nrewrite Hx, Hy, <- F2R_plus.\napply generic_format_F2R.\nintros _.\ncase_eq (Fplus beta fx fy).\nintros mz ez Hz.\nrewrite <- Hz.\napply Zle_trans with (Zmin (Fexp fx) (Fexp fy)).\nrewrite F2R_plus, <- Hx, <- Hy.\nunfold canonic_exp.\napply Zle_trans with (1:=Hfexp _).\napply Zplus_le_reg_l with prec; ring_simplify.\napply ln_beta_le_bpow with (1 := H).\nnow apply Zmin_case.\nrewrite <- Fexp_Fplus, Hz.\napply Zle_refl.\nQed.\n\nTheorem ex_Fexp_canonic: forall fexp, forall x, generic_format beta fexp x\n  -> exists fx:float beta, (x=F2R fx)%R /\\ Fexp fx = canonic_exp beta fexp x.\nintros fexp x; unfold generic_format.\nexists (Float beta (Ztrunc (scaled_mantissa beta fexp x)) (canonic_exp beta fexp x)).\nsplit; auto.\nQed.\n\nContext { prec_gt_0_ : Prec_gt_0 prec }.\n\nNotation format := (generic_format beta (FLX_exp prec)).\nNotation cexp := (canonic_exp beta (FLX_exp prec)).\n\nVariable choice : Z -> bool.\n\n(** Remainder of the division in FLX *)\nTheorem div_error_FLX :\n  forall rnd { Zrnd : Valid_rnd rnd } x y,\n  format x -> format y ->\n  format (x - round beta (FLX_exp prec) rnd (x/y) * y)%R.\nProof with auto with typeclass_instances.\nintros rnd Zrnd x y Hx Hy.\ndestruct (Req_dec y 0) as [Zy|Zy].\nnow rewrite Zy, Rmult_0_r, Rminus_0_r.\ndestruct (Req_dec (round beta (FLX_exp prec) rnd (x/y)) 0) as [Hr|Hr].\nrewrite Hr; ring_simplify (x-0*y)%R; assumption.\nassert (Zx: x <> R0).\ncontradict Hr.\nrewrite Hr.\nunfold Rdiv.\nnow rewrite Rmult_0_l, round_0.\ndestruct (ex_Fexp_canonic _ x Hx) as (fx,(Hx1,Hx2)).\ndestruct (ex_Fexp_canonic _ y Hy) as (fy,(Hy1,Hy2)).\ndestruct (ex_Fexp_canonic (FLX_exp prec) (round beta (FLX_exp prec) rnd (x / y))) as (fr,(Hr1,Hr2)).\napply generic_format_round...\nunfold Rminus; apply generic_format_plus_prec with fx (Fopp beta (Fmult beta fr fy)); trivial.\nintros e; apply Zle_refl.\nnow rewrite F2R_opp, F2R_mult, <- Hr1, <- Hy1.\n(* *)\ndestruct (relative_error_FLX_ex beta prec (prec_gt_0 prec) rnd (x / y)%R) as (eps,(Heps1,Heps2)).\napply Rmult_integral_contrapositive_currified.\nexact Zx.\nnow apply Rinv_neq_0_compat.\nrewrite Heps2.\nrewrite <- Rabs_Ropp.\nreplace (-(x + - (x / y * (1 + eps) * y)))%R with (x * eps)%R by now field.\nrewrite Rabs_mult.\napply Rlt_le_trans with (Rabs x * 1)%R.\napply Rmult_lt_compat_l.\nnow apply Rabs_pos_lt.\napply Rlt_le_trans with (1 := Heps1).\nchange R1 with (bpow 0).\napply bpow_le.\ngeneralize (prec_gt_0 prec).\nclear ; omega.\nrewrite Rmult_1_r.\nrewrite Hx2.\nunfold canonic_exp.\ndestruct (ln_beta beta x) as (ex, Hex).\nsimpl.\nspecialize (Hex Zx).\napply Rlt_le.\napply Rlt_le_trans with (1 := proj2 Hex).\napply bpow_le.\nunfold FLX_exp.\nring_simplify.\napply Zle_refl.\n(* *)\nreplace (Fexp (Fopp beta (Fmult beta fr fy))) with (Fexp fr + Fexp fy)%Z.\n2: unfold Fopp, Fmult; destruct fr; destruct fy; now simpl.\nreplace (x + - (round beta (FLX_exp prec) rnd (x / y) * y))%R with\n  (y * (-(round beta (FLX_exp prec) rnd (x / y) - x/y)))%R.\n2: field; assumption.\nrewrite Rabs_mult.\napply Rlt_le_trans with (Rabs y * bpow (Fexp fr))%R.\napply Rmult_lt_compat_l.\nnow apply Rabs_pos_lt.\nrewrite Rabs_Ropp.\nreplace (bpow (Fexp fr)) with (ulp beta (FLX_exp prec) (F2R fr)).\nrewrite <- Hr1.\napply ulp_error_f...\nunfold ulp; apply f_equal.\nnow rewrite Hr2, <- Hr1.\nreplace (prec+(Fexp fr+Fexp fy))%Z with ((prec+Fexp fy)+Fexp fr)%Z by ring.\nrewrite bpow_plus.\napply Rmult_le_compat_r.\napply bpow_ge_0.\nrewrite Hy2; unfold canonic_exp, FLX_exp.\nring_simplify (prec + (ln_beta beta y - prec))%Z.\ndestruct (ln_beta beta y); simpl.\nleft; now apply a.\nQed.\n\n(** Remainder of the square in FLX (with p>1) and rounding to nearest *)\nVariable Hp1 : Zlt 1 prec.\n\nTheorem sqrt_error_FLX_N :\n  forall x, format x ->\n  format (x - Rsqr (round beta (FLX_exp prec) (Znearest choice) (sqrt x)))%R.\nProof with auto with typeclass_instances.\nintros x Hx.\ndestruct (total_order_T x 0) as [[Hxz|Hxz]|Hxz].\nunfold sqrt.\ndestruct (Rcase_abs x).\nrewrite round_0...\nunfold Rsqr.\nnow rewrite Rmult_0_l, Rminus_0_r.\nelim (Rlt_irrefl 0).\nnow apply Rgt_ge_trans with x.\nrewrite Hxz, sqrt_0, round_0...\nunfold Rsqr.\nrewrite Rmult_0_l, Rminus_0_r.\napply generic_format_0.\ncase (Req_dec (round beta (FLX_exp prec) (Znearest choice) (sqrt x)) 0); intros Hr.\nrewrite Hr; unfold Rsqr; ring_simplify (x-0*0)%R; assumption.\ndestruct (ex_Fexp_canonic _ x Hx) as (fx,(Hx1,Hx2)).\ndestruct (ex_Fexp_canonic (FLX_exp prec) (round beta (FLX_exp prec) (Znearest choice) (sqrt x))) as (fr,(Hr1,Hr2)).\napply generic_format_round...\nunfold Rminus; apply generic_format_plus_prec with fx (Fopp beta (Fmult beta fr fr)); trivial.\nintros e; apply Zle_refl.\nunfold Rsqr; now rewrite F2R_opp,F2R_mult, <- Hr1.\n(* *)\napply Rle_lt_trans with x.\napply Rabs_minus_le.\napply Rle_0_sqr.\ndestruct (relative_error_N_FLX_ex beta prec (prec_gt_0 prec) choice (sqrt x)) as (eps,(Heps1,Heps2)).\nrewrite Heps2.\nrewrite Rsqr_mult, Rsqr_sqrt, Rmult_comm. 2: now apply Rlt_le.\napply Rmult_le_compat_r.\nnow apply Rlt_le.\napply Rle_trans with (5²/4²)%R.\nrewrite <- Rsqr_div.\napply Rsqr_le_abs_1.\napply Rle_trans with (1 := Rabs_triang _ _).\nrewrite Rabs_R1.\napply Rplus_le_reg_l with (-1)%R.\nrewrite <- Rplus_assoc, Rplus_opp_l, Rplus_0_l.\napply Rle_trans with (1 := Heps1).\nrewrite Rabs_pos_eq.\napply Rmult_le_reg_l with 2%R.\nnow apply (Z2R_lt 0 2).\nrewrite <- Rmult_assoc, Rinv_r, Rmult_1_l.\napply Rle_trans with (bpow (-1)).\napply bpow_le.\nomega.\nreplace (2 * (-1 + 5 / 4))%R with (/2)%R by field.\napply Rinv_le.\nnow apply (Z2R_lt 0 2).\napply (Z2R_le 2).\nunfold Zpower_pos. simpl.\nrewrite Zmult_1_r.\napply Zle_bool_imp_le.\napply beta.\napply Rgt_not_eq.\nnow apply (Z2R_lt 0 2).\nunfold Rdiv.\napply Rmult_le_pos.\nnow apply (Z2R_le 0 5).\napply Rlt_le.\napply Rinv_0_lt_compat.\nnow apply (Z2R_lt 0 4).\napply Rgt_not_eq.\nnow apply (Z2R_lt 0 4).\nunfold Rsqr.\nreplace (5 * 5 / (4 * 4))%R with (25 * /16)%R by field.\napply Rmult_le_reg_r with 16%R.\nnow apply (Z2R_lt 0 16).\nrewrite Rmult_assoc, Rinv_l, Rmult_1_r.\nnow apply (Z2R_le 25 32).\napply Rgt_not_eq.\nnow apply (Z2R_lt 0 16).\nrewrite Hx2; unfold canonic_exp, FLX_exp.\nring_simplify (prec + (ln_beta beta x - prec))%Z.\ndestruct (ln_beta beta x); simpl.\nrewrite <- (Rabs_right x).\napply a.\nnow apply Rgt_not_eq.\nnow apply Rgt_ge.\n(* *)\nreplace (Fexp (Fopp beta (Fmult beta fr fr))) with (Fexp fr + Fexp fr)%Z.\n2: unfold Fopp, Fmult; destruct fr; now simpl.\nrewrite Hr1.\nreplace (x + - Rsqr (F2R fr))%R with (-((F2R fr - sqrt x)*(F2R fr + sqrt x)))%R.\n2: rewrite <- (sqrt_sqrt x) at 3; auto.\n2: unfold Rsqr; ring.\nrewrite Rabs_Ropp, Rabs_mult.\napply Rle_lt_trans with ((/2*bpow (Fexp fr))* Rabs (F2R fr + sqrt x))%R.\napply Rmult_le_compat_r.\napply Rabs_pos.\napply Rle_trans with (/2*ulp beta  (FLX_exp prec) (F2R fr))%R.\nrewrite <- Hr1.\napply ulp_half_error_f...\nright; unfold ulp; apply f_equal.\nrewrite Hr2, <- Hr1; trivial.\nrewrite Rmult_assoc, Rmult_comm.\nreplace (prec+(Fexp fr+Fexp fr))%Z with (Fexp fr + (prec+Fexp fr))%Z by ring.\nrewrite bpow_plus, Rmult_assoc.\napply Rmult_lt_compat_l.\napply bpow_gt_0.\napply Rmult_lt_reg_l with 2%R.\nauto with real.\napply Rle_lt_trans with (Rabs (F2R fr + sqrt x)).\nright; field.\napply Rle_lt_trans with (1:=Rabs_triang _ _).\n(* . *)\nassert (Rabs (F2R fr) < bpow (prec + Fexp fr))%R.\nrewrite Hr2; unfold canonic_exp; rewrite Hr1.\nunfold FLX_exp.\nring_simplify (prec + (ln_beta beta (F2R fr) - prec))%Z.\ndestruct (ln_beta beta (F2R fr)); simpl.\napply a.\nrewrite <- Hr1; auto.\n(* . *)\napply Rlt_le_trans with (bpow (prec + Fexp fr)+ Rabs (sqrt x))%R.\nnow apply Rplus_lt_compat_r.\n(* . *)\nrewrite Rmult_plus_distr_r, Rmult_1_l.\napply Rplus_le_compat_l.\nassert (sqrt x <> 0)%R.\napply Rgt_not_eq.\nnow apply sqrt_lt_R0.\ndestruct (ln_beta beta (sqrt x)) as (es,Es).\nspecialize (Es H0).\napply Rle_trans with (bpow es).\nnow apply Rlt_le.\napply bpow_le.\ncase (Zle_or_lt es (prec + Fexp fr)) ; trivial.\nintros H1.\nabsurd (Rabs (F2R fr) < bpow (es - 1))%R.\napply Rle_not_lt.\nrewrite <- Hr1.\napply abs_round_ge_generic...\napply generic_format_bpow.\nunfold FLX_exp; omega.\napply Es.\napply Rlt_le_trans with (1:=H).\napply bpow_le.\nomega.\nnow apply Rlt_le.\nQed.\n\nEnd Fprop_divsqrt_error.\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/flocq/Prop/Fprop_div_sqrt_error.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.28369911352149796}}
{"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.concurrency.common.core_semantics.\n\nRequire Import VST.msl.Coqlib2.\n\n(********************* Lemmas and definitions related to mem_step ********)\n\nLemma mem_step_refl m: mem_step m m.\n  apply (mem_step_freelist _ _ nil); trivial.\nQed.\n\nLemma mem_step_free:\n      forall m b lo hi m', Mem.free m b lo hi = Some m' -> mem_step m m'.\nProof.\n intros. eapply (mem_step_freelist _ _ ((b,lo,hi)::nil)).\n simpl. rewrite H; reflexivity.\nQed.\n\nLemma mem_step_store:\n      forall m ch b a v m', Mem.store ch m b a v = Some m' -> mem_step m m'.\nProof.\n intros. eapply mem_step_storebytes. eapply Mem.store_storebytes; eassumption.\nQed.\n\nRecord memstep_preserve (P:mem -> mem -> Prop) :=\n  {\n    preserve_trans: forall m1 m2 m3, P m1 m2 -> P m2 m3 -> P m1 m3;\n    preserve_mem: forall m m', mem_step m m' -> P m m'\n  }.\n\nLemma preserve_refl {P} (HP: memstep_preserve P): forall m, P m m.\nProof. intros. eapply (preserve_mem _ HP). apply mem_step_refl. Qed.\n\nLemma preserve_free {P} (HP: memstep_preserve P):\n      forall m b lo hi m', Mem.free m b lo hi = Some m' -> P m m'.\nProof.\n intros. eapply (preserve_mem _ HP). eapply mem_step_free; eauto. Qed.\n\nTheorem preserve_conj {P Q} (HP:memstep_preserve P) (HQ: memstep_preserve Q):\n        memstep_preserve (fun m m' => P m m' /\\ Q m m').\nProof.\nintros. constructor.\n+ intros. destruct H; destruct H0. split. eapply HP; eauto. eapply HQ; eauto.\n+ intros; split. apply HP; trivial. apply HQ; trivial.\nQed.\n\n(*opposite direction appears not to hold*)\nTheorem preserve_impl {A} (P:A -> mem -> mem -> Prop) (Q:A->Prop):\n        (forall a, Q a -> memstep_preserve (P a)) -> memstep_preserve (fun m m' => forall a, Q a -> P a m m').\nProof.\nintros.\nconstructor; intros.\n+ eapply H; eauto.\n+ apply H; eauto.\nQed.\n\nLemma preserve_exensional {P Q} (HP:memstep_preserve P) (PQ:P=Q): memstep_preserve Q.\nsubst; trivial. Qed.\n\n(*opposite direction appears not to hold*)\nTheorem preserve_univ {A} (P:A -> mem -> mem -> Prop):\n        (forall a, memstep_preserve (P a)) -> memstep_preserve (fun m m' => forall a, P a m m').\nProof. intros.\neapply preserve_exensional.\neapply (@preserve_impl A (fun a m m'=> P a m m') (fun a=>True)).\nintros. apply H. extensionality m. extensionality m'. apply prop_ext. intuition.\nQed.\n\nTheorem mem_forward_preserve: memstep_preserve mem_forward.\nProof.\nconstructor.\n+ apply mem_forward_trans.\n+ intros. induction H.\n  eapply storebytes_forward; eassumption.\n  eapply alloc_forward; eassumption.\n  eapply freelist_forward; eassumption.\n  eapply mem_forward_trans; eassumption.\nQed.\n\nTheorem readonly_preserve b: memstep_preserve (fun m m' => mem_forward m m' /\\ (Mem.valid_block m b -> readonly m b m')).\nProof.\nconstructor.\n+ intros. destruct H; destruct H0.\n  split; intros. eapply mem_forward_trans; eassumption.\n  eapply readonly_trans; eauto. apply H2. apply H. eassumption.\n+ intros; induction H.\n  - split; intros. eapply storebytes_forward; eassumption.\n    eapply storebytes_readonly; eassumption.\n  - intros.\n    split; intros. eapply alloc_forward; eassumption.\n    eapply alloc_readonly; eassumption.\n  - intros.\n    split; intros. eapply freelist_forward; eassumption.\n    eapply freelist_readonly; eassumption.\n  - destruct IHmem_step1; destruct IHmem_step2.\n    split. eapply mem_forward_trans; eassumption.\n    intros. eapply readonly_trans. eauto. apply H4. apply H1; eassumption.\nQed.\n\nTheorem readonly_preserve':\n   memstep_preserve (fun m m' => mem_forward m m' /\\ (forall b, Mem.valid_block m b -> readonly m b m')).\nProof.\neapply preserve_exensional.\neapply preserve_univ; intros. apply (readonly_preserve a).\n  extensionality m. extensionality m'. apply prop_ext.\n  split; intros. split. eapply H. apply xH. intros. eapply (H b). trivial.\n  destruct H. split; eauto.\nQed.\n\nLemma storebytes_unch_loc_unwritable b ofs: forall l m m' (L: Mem.storebytes m b ofs l = Some m'),\n      Mem.unchanged_on (loc_not_writable m) m m'.\nProof.\nintros.\nsplit; intros.\n+ rewrite (Mem.nextblock_storebytes _ _ _ _ _ L); apply Pos.le_refl.\n+ split; intros.\n  eapply Mem.perm_storebytes_1; eassumption.\n  eapply Mem.perm_storebytes_2; eassumption.\n+ rewrite (Mem.storebytes_mem_contents _ _ _ _ _ L).\n  apply Mem.storebytes_range_perm in L.\n  destruct (eq_block b0 b); subst.\n  - destruct (zle ofs ofs0).\n      destruct (zlt ofs0 (ofs + Z.of_nat (length l))).\n        elim H. eapply Mem.perm_max. apply L. omega.\n      rewrite PMap.gss. apply Mem.setN_other. intros. omega.\n    rewrite PMap.gss. apply Mem.setN_other. intros. omega.\n  - rewrite PMap.gso; trivial.\nQed.\n\nLemma unch_on_loc_not_writable_trans m1 m2 m3\n        (Q : Mem.unchanged_on (loc_not_writable m1) m1 m2)\n        (W : Mem.unchanged_on (loc_not_writable m2) m2 m3)\n        (F:mem_forward m1 m2):\n     Mem.unchanged_on (loc_not_writable m1) m1 m3.\nProof.\n  destruct Q as [Q0 Q1 Q2]. destruct W as [W0 W1 W2].\n  split; intros.\n  - eapply Ple_trans; eassumption.\n  - cut (Mem.perm m2 b ofs k p <-> Mem.perm m3 b ofs k p).\n      specialize (Q1 _ _ k p H H0). intuition.\n    apply W1; clear W1. intros N. apply H. apply Q1; trivial. apply F; trivial.\n  -  rewrite W2; clear W2.\n       apply Q2; trivial.\n     intros N; apply H. apply F; trivial. eapply Mem.perm_valid_block; eassumption.\n     apply Q1; trivial. eapply Mem.perm_valid_block; eassumption.\nQed.\n\nTheorem loc_not_writable_preserve:\n   memstep_preserve (fun m m' => mem_forward m m' /\\ Mem.unchanged_on (loc_not_writable m) m m').\nProof.\nconstructor.\n+ intros. destruct H as [F1 Q]; destruct H0 as [F2 W].\n  split; intros. eapply mem_forward_trans; eassumption. clear F2.\n  eapply unch_on_loc_not_writable_trans; eassumption.\n+ intros; induction H.\n  - split; intros. eapply storebytes_forward; eassumption.\n    eapply storebytes_unch_loc_unwritable; eassumption.\n  - split; intros. eapply alloc_forward; eassumption.\n    eapply Mem.alloc_unchanged_on; eassumption.\n  - split; intros. eapply freelist_forward; eassumption.\n    generalize dependent m.\n    induction l; simpl; intros. inv H. apply Mem.unchanged_on_refl.\n    destruct a. destruct p.\n    remember (Mem.free m b z0 z) as w. destruct w; inv H. symmetry in Heqw.\n    eapply unch_on_loc_not_writable_trans.\n      eapply Mem.free_unchanged_on. eassumption.\n        intros i I N. elim N; clear N.\n        eapply Mem.perm_max. eapply Mem.perm_implies. eapply Mem.free_range_perm; eassumption. constructor.\n      apply IHl; eassumption.\n      eapply free_forward; eassumption.\n  - destruct IHmem_step1; destruct IHmem_step2.\n    split. eapply mem_forward_trans; eassumption.\n    intros. clear H H0 H3. eapply unch_on_loc_not_writable_trans; eassumption.\nQed.\n\nLemma freelist_perm: forall l m m' (L : Mem.free_list m l = Some m') b (B: Mem.valid_block m b)\n      ofs (P': Mem.perm m' b ofs Max Nonempty) k p,\n      Mem.perm m b ofs k p <-> Mem.perm m' b ofs k p.\nProof. induction l; simpl; intros.\n+ inv L; split; trivial.\n+ destruct a. destruct p0.\n  remember (Mem.free m b0 z0 z) as w. symmetry in Heqw.\n  destruct w; inv L.\n  specialize (IHl _ _  H0 _ (Mem.valid_block_free_1 _ _ _ _ _ Heqw _ B) _ P' k p).\n  assert (P: Mem.perm m b ofs k p <-> Mem.perm m0 b ofs k p).\n  { clear IHl. destruct (Mem.perm_free_list _ _ _ _ _ _ _ H0 P') as [P ?]; clear H0 P'.\n    destruct (eq_block b0 b); subst.\n    - destruct (zlt ofs z0).\n      * split; intros. apply (Mem.perm_free_1 _ _ _ _ _ Heqw) in H0; eauto.\n        eapply Mem.perm_free_3; eassumption.\n      * destruct (zle z ofs).\n        split; intros. apply (Mem.perm_free_1 _ _ _ _ _ Heqw) in H0; eauto.\n                       eapply Mem.perm_free_3; eassumption.\n        split; intros.\n          eelim (Mem.perm_free_2 _ _ _ _ _ Heqw ofs Max Nonempty); clear Heqw; trivial. omega.\n        eelim (Mem.perm_free_2 _ _ _ _ _ Heqw ofs Max Nonempty); clear Heqw. omega.\n          eapply Mem.perm_implies. eapply Mem.perm_max. eassumption. constructor.\n    - split; intros.\n      * eapply (Mem.perm_free_1 _ _ _ _ _ Heqw); trivial. intuition.\n      * eapply (Mem.perm_free_3 _ _ _ _ _ Heqw); trivial.\n  }\n  intuition.\nQed.\n\nTheorem perm_preserve:\n   memstep_preserve (fun m m' =>  mem_forward m m' /\\ forall b, Mem.valid_block m b -> forall ofs, Mem.perm m' b ofs Max Nonempty ->\n                                  forall k p, Mem.perm m b ofs k p <-> Mem.perm m' b ofs k p).\nProof.\nconstructor.\n+ intros; split. eapply mem_forward_trans. apply H. apply H0.\n  destruct H; destruct H0. intros.\n  assert (M: Mem.perm m1 b ofs k p <-> Mem.perm m2 b ofs k p).\n  - clear H2. apply H1; trivial. apply H0; trivial. apply H; trivial.\n  - clear H1.\n    assert (VB2: Mem.valid_block m2 b). apply H; trivial.\n    destruct (H2 _ VB2 _ H4 k p); destruct M. split; intros; eauto.\n+ intros; induction H.\n  - split; intros. eapply storebytes_forward; eassumption.\n    split; intros. eapply Mem.perm_storebytes_1; eassumption.\n    eapply Mem.perm_storebytes_2; eassumption.\n  - split; intros. eapply alloc_forward; eassumption.\n    split; intros. eapply Mem.perm_alloc_1; eassumption.\n    eapply Mem.perm_alloc_4; try eassumption.\n    intros N; subst b'. elim (Mem.fresh_block_alloc _ _ _ _ _ H H0).\n  - intros; split. eapply freelist_forward; eassumption.\n    apply (freelist_perm _ _ _ H).\n  - clear H H0. destruct IHmem_step1; destruct IHmem_step2.\n    split. eapply mem_forward_trans; eassumption.\n    intros.\n    assert (M: Mem.perm m b ofs k p <-> Mem.perm m'' b ofs k p).\n    * clear H2. apply H0; trivial. apply H1; trivial. apply H; trivial.\n    * clear H0.\n      assert (VB2: Mem.valid_block m'' b). apply H; trivial.\n      destruct (H2 _ VB2 _ H4 k p); destruct M. split; intros; eauto.\nQed.\n\nLemma mem_step_forward m m': mem_step m m' -> mem_forward m m'.\nintros. apply preserve_mem; trivial.\neapply mem_forward_preserve; trivial.\nQed.\n\nLemma freelist_perm_inv: forall l m m' (L : Mem.free_list m l = Some m') b (B: Mem.valid_block m b)\n      ofs k p (P: Mem.perm m b ofs k p),\n      Mem.perm m b ofs Max Freeable \\/ Mem.perm m' b ofs k p.\nProof. induction l; simpl; intros.\n+ inv L. right; trivial.\n+ destruct a. destruct p0.\n  remember (Mem.free m b0 z0 z) as w. symmetry in Heqw.\n  destruct w; inv L.\n  exploit Mem.perm_free_inv; eauto. intros [[HHx HH] | HH]; try subst b0.\n  - left. eapply Mem.perm_max.  eapply Mem.free_range_perm; eassumption.\n  - destruct (IHl _ _  H0 _ (Mem.valid_block_free_1 _ _ _ _ _ Heqw _ B) _ _ _ HH); clear IHl.\n    2: right; trivial.\n    left. eapply Mem.perm_free_3; eauto.\nQed.\n\nTheorem preserves_max_eq_or_free:\n   memstep_preserve (fun m m' =>  mem_forward m m' /\\\n                                  forall b (VB: Mem.valid_block m b) ofs,\n                                   (forall k p, Mem.perm m b ofs k p <-> Mem.perm m' b ofs k p) \\/\n                                   (Mem.perm m b ofs Max Freeable /\\\n                                    Mem.perm_order'' None ((Mem.mem_access m') !! b ofs Max))).\nProof.\nconstructor.\n+ intros; split. eapply mem_forward_trans. apply H. apply H0.\n  destruct H; destruct H0. intros.\n  assert (VB2: Mem.valid_block m2 b). { apply H; trivial. }\n  destruct (H1 _ VB ofs) as [K1 | [K1 L1]]; destruct (H2 _ VB2 ofs) as [K2 | [K2 L2]]; clear H1 H2.\n  - left; intros. specialize (K1 k p); specialize (K2 k p). intuition.\n  - right; split; trivial. apply K1; trivial.\n  - right; split; trivial. simpl in *. specialize (K2 Max).\n    unfold Mem.perm in *.\n    remember ((Mem.mem_access m3) !! b ofs Max) as w; destruct w; trivial.\n    destruct ((Mem.mem_access m2) !! b ofs Max); try contradiction.\n    destruct (K2 p); simpl in *. apply H2. apply perm_refl.\n  - right; split; trivial.\n+ intros; induction H.\n  - split; intros. eapply storebytes_forward; eassumption.\n    left; intros. split; intros.\n    * eapply Mem.perm_storebytes_1; eassumption.\n    * eapply Mem.perm_storebytes_2; eassumption.\n  - split; intros. eapply alloc_forward; eassumption.\n    left; intros. split; intros.\n    * eapply Mem.perm_alloc_1; eassumption.\n    * eapply Mem.perm_alloc_4; try eassumption.\n      intros N; subst. eapply Mem.fresh_block_alloc; eassumption.\n  - split; intros. eapply freelist_forward; eassumption.\n    destruct (Mem.perm_dec m' b ofs Max Nonempty).\n    * left; intros. eapply freelist_perm; eassumption.\n    * destruct (Mem.perm_dec m b ofs Max Freeable); trivial.\n       right; split; trivial. unfold Mem.perm in n; simpl in *.\n       destruct ((Mem.mem_access m') !! b ofs Max); trivial.\n       elim n; clear n. constructor.\n      left; intros.\n      split; intros. 2: eapply perm_freelist; eassumption.\n      exploit freelist_perm_inv; eauto. intros [X | X]; trivial; contradiction.\n  - clear H H0. destruct IHmem_step1; destruct IHmem_step2.\n    split. eapply mem_forward_trans; eassumption.\n    intros.\n    assert (VB2 : Mem.valid_block m'' b). { apply H; trivial. }\n    specialize (H0 _ VB ofs). specialize (H2 _ VB2 ofs).\n    destruct H0 as [K | [K1 K2]]; destruct H2 as [L | [L1 L2]].\n    * left; intros. split; intros. apply L. apply K; trivial.\n      apply K. apply L; trivial.\n    * right. split; trivial. apply K; trivial.\n    * right. split; trivial.\n      clear K1. unfold Mem.perm in *. simpl in *. specialize (L Max).\n      remember ((Mem.mem_access m') !! b ofs Max) as d; destruct d; trivial.\n      destruct ((Mem.mem_access m'') !! b ofs Max); try contradiction.\n      specialize (L p); simpl in *. apply L. apply perm_refl.\n    * right. split; trivial.\nQed.\n\nTheorem mem_step_max_eq_or_free m m' (STEP: mem_step m m') b (VB: Mem.valid_block m b) ofs:\n       (forall k p, Mem.perm m b ofs k p <-> Mem.perm m' b ofs k p) \\/\n       (Mem.perm m b ofs Max Freeable /\\ None = ((Mem.mem_access m') !! b ofs Max)).\nProof. intros.\nexploit preserve_mem. apply preserves_max_eq_or_free. eassumption.\nsimpl; intros [A B]. destruct (B _ VB ofs). left; trivial. right.\n  destruct H; split; trivial.\n  destruct ((Mem.mem_access m') !! b ofs Max); trivial; contradiction.\nQed.\n\nLemma memsem_preserves {C} (s: @MemSem C) P (HP:memstep_preserve P):\n      forall c m c' m', corestep s c m c' m'-> P m m'.\nProof. intros.\n  apply corestep_mem in H.\n  eapply preserve_mem; eassumption.\nQed.\n\nLemma corestep_fwd {C} (s:@MemSem C) c m c' m'\n   (CS:corestep s c m c' m' ): mem_forward m m'.\nProof.\neapply memsem_preserves; try eassumption. apply mem_forward_preserve.\nQed.\n\nLemma corestep_rdonly {C} (s:@MemSem C) c m c' m'\n   (CS:corestep s c m c' m') b (VB:Mem.valid_block m b): readonly m b m'.\nProof.\neapply (memsem_preserves s _ readonly_preserve'); eassumption.\nQed.\n\nLemma mem_step_nextblock:  memstep_preserve (fun m m' => Mem.nextblock m <= Mem.nextblock m')%positive.\nconstructor.\n+ intros. xomega.\n+ induction 1.\n - apply Mem.nextblock_storebytes in H;\n   rewrite H; xomega.\n - apply Mem.nextblock_alloc in H.\n   rewrite H. clear. xomega.\n - apply nextblock_freelist in H.\n   rewrite H; xomega.\n - xomega.\nQed.\n\nLemma mem_step_nextblock':\n  forall m m',\n     mem_step m m' ->\n   (Mem.nextblock m <= Mem.nextblock m')%positive.\nProof. apply mem_step_nextblock. Qed.\n\n(*E-step: Axiomatization of external steps - potentially useful when Memory interface is hardened\nInductive e_step m m' : Prop :=\n    mem_step_estep: mem_step m m' -> e_step m m'\n  | drop_perm_estep: forall b lo hi p,\n      Mem.drop_perm m b lo hi p = Some m' -> e_step m m'\n  | change_cur_estep:\n      (forall b ofs, (Mem.mem_access m) !! b ofs Max = (Mem.mem_access m') !! b ofs Max) ->\n      Mem.unchanged_on (loc_not_writable m) m m' ->\n      (Mem.mem_contents m = Mem.mem_contents m') ->\n      Mem.nextblock m = Mem.nextblock m' -> e_step m m'\n  | estep_trans: forall m'',\n       e_step m m'' -> e_step m'' m' -> e_step m m'.\n\nLemma e_step_refl m: e_step m m.\nProof. apply mem_step_estep. apply mem_step_refl. Qed.\n\nLemma estep_forward m m' (E:e_step m m'): mem_forward m m'.\nProof.\ninduction E.\napply mem_forward_preserve; eassumption.\n+ split; intros.\n    eapply Mem.drop_perm_valid_block_1; eassumption.\n    eapply Mem.perm_drop_4; eassumption.\n+ split; intros.\n  unfold Mem.valid_block in *. rewrite H2 in *; assumption.\n  unfold Mem.perm. rewrite H. apply H4.\n+ eapply mem_forward_trans; eassumption.\nQed.\n\nLemma estep_unch_on_loc_not_writable m m' (E:e_step m m'): Mem.unchanged_on (loc_not_writable m) m m'.\nProof.\ninduction E.\n+ apply loc_not_writable_preserve in H. apply H.\n+ unfold Mem.drop_perm in H.\n  destruct (Mem.range_perm_dec m b lo hi Cur Freeable); inv H; simpl in *.\n  split; simpl; trivial.\n  intros. red in H.\n  unfold Mem.perm; simpl. rewrite PMap.gsspec.\n  destruct (peq b0 b); subst; simpl. 2: intuition.\n  destruct (zle lo ofs); simpl. 2: intuition.\n  destruct (zlt ofs hi); simpl. 2: intuition.\n  elim H. eapply Mem.perm_max. eapply Mem.perm_implies. apply r. omega. constructor.\n+ trivial.\n+ eapply unch_on_loc_not_writable_trans; try eassumption. eapply estep_forward; eassumption.\nQed.\n*)\n(*\nTheorem loadbytes_drop m b lo hi p m' (D:Mem.drop_perm m b lo hi p = Some m'):\n  forall b' ofs,\n  b' <> b \\/ ofs < lo \\/ hi <= ofs \\/ perm_order p Readable ->\n  Mem.loadbytes m' b' ofs 1 = Mem.loadbytes m b' ofs 1.\nProof.\n  intros.\nTransparent Mem.loadbytes.\n  unfold Mem.loadbytes.\n  destruct (Mem.range_perm_dec m b' ofs (ofs + 1) Cur Readable).\n  rewrite pred_dec_true.\n  unfold Mem.drop_perm in D. destruct (Mem.range_perm_dec m b lo hi Cur Freeable); inv D. simpl. auto.\n  red; intros. specialize (Mem.perm_drop_1 _ _ _ _ _ _ D ofs0 Cur); intros.\n    destruct (eq_block b' b); subst.\n      destruct H. eapply Mem.perm_drop_3. eassumption. left; trivial. apply r. trivial.\n      destruct (zlt ofs lo). eapply Mem.perm_drop_3. eassumption. right. omega. apply r. trivial.\n      destruct H. omega.\n      destruct (zle hi ofs). eapply Mem.perm_drop_3. eassumption. right. omega. apply r. trivial.\n      destruct H. omega.\n      eapply Mem.perm_implies. apply H1. omega. trivial.\n   eapply Mem.perm_drop_3. eassumption. left; trivial. apply r. omega.\n\n  destruct (Mem.range_perm_dec m' b' ofs (ofs + 1) Cur Readable); trivial.\n  elim n; clear n. red; intros. eapply Mem.perm_drop_4. eassumption. apply r. trivial.\nQed.\n*)\n\nLemma mem_step_obeys_cur_write:\n  forall m b ofs m',\n    Mem.valid_block m b ->\n   ~ Mem.perm m b ofs Cur Writable ->\n   mem_step m m' ->\n ZMap.get ofs (PMap.get b (Mem.mem_contents m)) =\n ZMap.get ofs (PMap.get b (Mem.mem_contents m')).\nProof.\n intros.\n induction H1.\n* revert m ofs0 H H0 H1; induction bytes; intros.\n Transparent Mem.storebytes.\n unfold Mem.storebytes in H1.\n destruct (Mem.range_perm_dec m b0 ofs0\n         (ofs0 + Z.of_nat (length nil)) Cur Writable);\n  inv H1; simpl.\n destruct (peq b b0). subst b0.\n rewrite PMap.gss. auto.\n rewrite PMap.gso; auto.\n change (a::bytes) with ((a::nil)++bytes) in H1.\n apply Mem.storebytes_split in H1.\n destruct H1 as [m1 [? ?]].\n etransitivity.\n 2: eapply IHbytes; try apply H2.\n clear H2 IHbytes.\n unfold Mem.storebytes in H1.\nOpaque Mem.storebytes.\n destruct (Mem.range_perm_dec m b0 ofs0\n         (ofs0 + Z.of_nat (length (a :: nil))) Cur Writable);\n inv H1; simpl.\n destruct (peq b b0). subst b0.\n rewrite PMap.gss.\n destruct (zeq ofs0 ofs). subst.\n contradiction H0. apply r. simpl. omega.\n rewrite ZMap.gso; auto.\n rewrite PMap.gso; auto.\n clear - H H1.\n eapply Mem.storebytes_valid_block_1; eauto.\n contradict H0. clear - H1 H0.\n eapply Mem.perm_storebytes_2; eauto.\n*\n apply AllocContentsOther with (b':=b) in H1.\n rewrite H1. auto. intro; subst.\n apply Mem.alloc_result in H1; unfold Mem.valid_block in H.\n subst. apply Plt_strict in H; auto.\n*\n revert m H H0 H1; induction l; simpl; intros.\n inv H1; auto.\n destruct a. destruct p.\n destruct (Mem.free m b0 z0 z) eqn:?; inv H1.\n rewrite <- (IHl m0); auto.\n eapply free_contents; eauto.\n intros [? ?]. subst b0. apply H0.\n apply Mem.free_range_perm in Heqo.\n   specialize (Heqo ofs).\n   eapply Mem.perm_implies. apply Heqo. omega. constructor.\n clear - H Heqo.\n unfold Mem.valid_block in *.\n apply Mem.nextblock_free in Heqo. rewrite Heqo.\n auto.\n clear - H0 Heqo.\n contradict H0.\n eapply Mem.perm_free_3; eauto.\n*\n assert (Mem.valid_block m'' b). {\n   apply mem_step_nextblock in H1_.\n   unfold Mem.valid_block in *.\n   eapply Pos.lt_le_trans; eauto.\n }\n erewrite IHmem_step1 by auto. apply IHmem_step2; auto.\n contradict H0.\n clear - H H1_ H0.\n revert H H0; induction H1_; intros.\n eapply Mem.perm_storebytes_2; eauto.\n pose proof (Mem.perm_alloc_inv _ _ _ _ _ H _ _ _ _ H1).\n destruct (eq_block b b'); subst; trivial.\n - pose proof (Mem.alloc_result _ _ _ _ _ H).\n   subst. apply Plt_strict in H0. contradiction.\n - eapply Mem.perm_free_list in H; try apply H1.\n   destruct H; auto.\n - eapply IHH1_1; auto. eapply IHH1_2; eauto.\n   apply mem_step_nextblock in H1_1.\n   unfold Mem.valid_block in *.\n   eapply Pos.lt_le_trans; eauto.\nQed.\n\nLemma ple_load m ch a v\n            (LD: Mem.loadv ch m a = Some v)\n            m1 (PLE: perm_lesseq m m1):\n           Mem.loadv ch m1 a = Some v.\nProof.\nunfold Mem.loadv in *.\ndestruct a; auto.\nTransparent Mem.load.\nunfold Mem.load in *.\nOpaque Mem.load.\ndestruct PLE.\nif_tac in LD; [ | inv LD].\nrewrite if_true.\nrewrite <- LD; clear LD.\nf_equal. f_equal.\ndestruct H.\nrewrite size_chunk_conv in H.\nclear - H perm_le_cont.\nforget (size_chunk_nat ch) as n.\nforget (Ptrofs.unsigned i) as j.\nrevert j H; induction n; intros; simpl; f_equal.\napply perm_le_cont.\napply (H j).\nrewrite inj_S.\nomega.\napply IHn.\nrewrite inj_S in H.\nintros ofs ?; apply H. omega.\nclear - H perm_le_Cur.\ndestruct H; split; auto.\nintros ? ?. specialize (H ofs H1).\nhnf in H|-*.\nspecialize (perm_le_Cur b ofs).\ndestruct ((Mem.mem_access m) !! b ofs Cur); try contradiction.\ndestruct ((Mem.mem_access m1) !! b ofs Cur);\ninv perm_le_Cur; auto; try constructor; try inv H.\nQed.\n\nLemma ple_store:\n  forall ch m v1 v2 m' m1\n   (PLE: perm_lesseq m m1),\n   Mem.storev ch m v1 v2 = Some m' ->\n   exists m1', perm_lesseq m' m1' /\\ Mem.storev ch m1 v1 v2 = Some m1'.\nProof.\nintros.\nunfold Mem.storev in *.\ndestruct v1; try discriminate.\nTransparent Mem.store.\nunfold Mem.store in *.\nOpaque Mem.store.\ndestruct (Mem.valid_access_dec m ch b (Ptrofs.unsigned i)  Writable); inv H.\ndestruct (Mem.valid_access_dec m1 ch b (Ptrofs.unsigned i)\n      Writable).\n*\neexists; split; [ | reflexivity].\ndestruct PLE.\nconstructor; simpl; auto.\nintros. unfold Mem.perm in H. simpl in H.\nforget (Ptrofs.unsigned i) as z.\ndestruct (eq_block b0 b). subst.\nrewrite !PMap.gss.\nforget (encode_val ch v2) as vl.\nassert (z <= ofs < z + Z.of_nat (length vl) \\/ ~ (z <= ofs < z + Z.of_nat (length vl))) by omega.\ndestruct H0.\nclear - H0.\nforget ((Mem.mem_contents m1) !! b) as mA.\nforget ((Mem.mem_contents m) !! b) as mB.\nrevert z mA mB H0; induction vl; intros; simpl.\nsimpl in H0; omega.\nsimpl length in H0; rewrite inj_S in H0.\ndestruct (zeq z ofs).\nsubst ofs.\nrewrite !Mem.setN_outside by omega. rewrite !ZMap.gss; auto.\napply IHvl; omega.\nrewrite !Mem.setN_outside by omega.\napply perm_le_cont. auto.\nrewrite !PMap.gso by auto.\napply perm_le_cont. auto.\n*\ncontradiction n; clear n.\ndestruct PLE.\nunfold Mem.valid_access in *.\ndestruct v; split; auto.\nhnf in H|-*; intros.\nspecialize (H _ H1).\nclear - H perm_le_Cur.\nspecialize (perm_le_Cur b ofs).\nhnf in H|-*.\ndestruct ((Mem.mem_access m) !! b ofs Cur); try contradiction.\ninv H;\ndestruct ((Mem.mem_access m1) !! b ofs Cur);\ninv perm_le_Cur; auto; try constructor; try inv H.\nQed.\n\nLemma free_access_inv m b lo hi m' (FR: Mem.free m b lo hi = Some m') b' ofs k p\n  (P: (Mem.mem_access m') !! b' ofs k = Some p):  (Mem.mem_access m) !! b' ofs k = Some p.\nProof.\napply Mem.free_result in FR; subst. simpl in *.\nrewrite PMap.gsspec in P.\ndestruct (peq b' b); subst; trivial.\ndestruct (zle lo ofs && zlt ofs hi); inv P; trivial.\nQed.\n\nLemma free_access_inv_None m b lo hi m' (FR: Mem.free m b lo hi = Some m') b' ofs k\n  (P: (Mem.mem_access m') !! b' ofs k = None):\n  (b' = b /\\ Z.le lo ofs /\\ Z.lt ofs hi /\\  (Mem.mem_access m) !! b' ofs k = Some Freeable) \\/\n  ((b' <> b \\/ Z.lt ofs lo \\/ Z.le hi ofs) /\\ (Mem.mem_access m) !! b' ofs k = None).\nProof.\nspecialize (Mem.free_result _ _ _ _ _ FR). intros; subst. simpl in *.\nrewrite PMap.gsspec in P.\ndestruct (peq b' b); subst.\n+ remember (zle lo ofs && zlt ofs hi) as q.\n  destruct q; inv P.\n  - left. split; trivial. destruct (zle lo ofs); simpl in *; try discriminate.\n    split; trivial. destruct (zlt ofs hi); simpl in *; try discriminate.\n    split; trivial.\n    assert (RP: Mem.perm m b ofs Cur Freeable). apply (Mem.free_range_perm _ _ _ _ _ FR ofs); omega.\n    destruct k.\n    * eapply Mem.perm_max in RP.\n      unfold Mem.perm in RP. destruct ((Mem.mem_access m) !! b ofs Max); simpl in *; try discriminate.\n      destruct p; simpl in *; try inv RP; simpl; trivial. contradiction.\n    * unfold Mem.perm in RP. destruct ((Mem.mem_access m) !! b ofs Cur); simpl in *; try discriminate.\n      destruct p; simpl in *; try inv RP; simpl; trivial. contradiction.\n  - right; split; trivial. right.\n    destruct (zle lo ofs); destruct (zlt ofs hi); simpl in *; try discriminate; try omega.\n+ right; split; trivial. left; trivial.\nQed.\n\nLemma ple_free: forall m m' b lo hi (FL: Mem.free m b lo hi = Some m') m1 (PLE:perm_lesseq m m1),\n      exists m1', Mem.free m1 b lo hi = Some m1' /\\ perm_lesseq m' m1'.\nProof. intros.\n  specialize (Mem.free_range_perm _ _ _ _ _ FL). intros.\n  assert (RF: Mem.range_perm m1 b lo hi Cur Freeable).\n  { destruct PLE. red; intros.\n    specialize (perm_le_Cur b ofs). specialize (H _ H0). unfold Mem.perm in *.\n    destruct ((Mem.mem_access m) !! b ofs Cur); simpl in *; try contradiction.\n    destruct ((Mem.mem_access m1) !! b ofs Cur); simpl in *; try contradiction.\n    eapply perm_order_trans; eassumption.\n  }\n  destruct (Mem.range_perm_free m1 b lo hi RF) as [mm MM].\n  exists mm; split; trivial.\n  destruct PLE.\n  split; intros.\n  - specialize (perm_le_Cur b0 ofs); clear perm_le_Max perm_le_cont.\n    remember ((Mem.mem_access mm) !! b0 ofs Cur) as q; symmetry in Heqq.\n      destruct q; simpl in *.\n      * rewrite (free_access_inv _ _ _ _ _ MM _ _ _ _ Heqq) in *.\n        remember ((Mem.mem_access m') !! b0 ofs Cur) as w; symmetry in Heqw.\n         destruct w; trivial.\n         rewrite (free_access_inv _ _ _ _ _ FL _ _ _ _ Heqw) in *. simpl in *; trivial.\n      * remember ((Mem.mem_access m') !! b0 ofs Cur) as w; symmetry in Heqw.\n        destruct w; trivial.\n        rewrite (free_access_inv _ _ _ _ _ FL _ _ _ _ Heqw) in *.\n        destruct (free_access_inv_None _ _ _ _ _ MM _ _ _ Heqq).\n        ++ destruct H0 as [? [? [? ?]]]; subst.\n           rewrite (Mem.free_result _ _ _ _ _ FL) in *. simpl in *.\n           rewrite PMap.gss in Heqw.\n           remember (zle lo ofs&& zlt ofs hi ) as t; destruct t; simpl in *; try discriminate.\n           destruct (zle lo ofs); destruct (zlt ofs hi); simpl in *; try discriminate; omega.\n        ++ destruct H0 as [? ?]. rewrite H1 in *; simpl in *; contradiction.\n  - specialize (perm_le_Max b0 ofs); clear perm_le_Cur perm_le_cont.\n    remember ((Mem.mem_access mm) !! b0 ofs Max) as q; symmetry in Heqq.\n      destruct q; simpl in *.\n      * rewrite (free_access_inv _ _ _ _ _ MM _ _ _ _ Heqq) in *.\n        remember ((Mem.mem_access m') !! b0 ofs Max) as w; symmetry in Heqw.\n         destruct w; trivial.\n         rewrite (free_access_inv _ _ _ _ _ FL _ _ _ _ Heqw) in *. simpl in *; trivial.\n      * remember ((Mem.mem_access m') !! b0 ofs Max) as w; symmetry in Heqw.\n        destruct w; trivial.\n        rewrite (free_access_inv _ _ _ _ _ FL _ _ _ _ Heqw) in *.\n        destruct (free_access_inv_None _ _ _ _ _ MM _ _ _ Heqq).\n        ++ destruct H0 as [? [? [? ?]]]; subst.\n           rewrite (Mem.free_result _ _ _ _ _ FL) in *. simpl in *.\n           rewrite PMap.gss in Heqw.\n           remember (zle lo ofs&& zlt ofs hi ) as t; destruct t; simpl in *; try discriminate.\n           destruct (zle lo ofs); destruct (zlt ofs hi); simpl in *; try discriminate; omega.\n        ++ destruct H0 as [? ?]. rewrite H1 in *; simpl in *; contradiction.\n  - rewrite (Mem.free_result _ _ _ _ _ FL). rewrite (Mem.free_result _ _ _ _ _ MM).\n    simpl. apply perm_le_cont. eapply Mem.perm_free_3; eassumption.\n  - rewrite (Mem.free_result _ _ _ _ _ FL). rewrite (Mem.free_result _ _ _ _ _ MM).\n    simpl; trivial.\nQed.\n\nLemma ple_freelist: forall l m m' (FL: Mem.free_list m l = Some m') m1 (PLE:perm_lesseq m m1),\n      exists m1', Mem.free_list m1 l = Some m1' /\\ perm_lesseq m' m1'.\nProof. induction l; simpl; intros.\n+ inv FL;  exists m1; split; trivial.\n+ destruct a as [[b lo] hi]. remember (Mem.free m b lo hi) as q. destruct q; inv FL.\n  symmetry in Heqq.\n  destruct (ple_free _ _ _ _ _ Heqq _ PLE) as [mm [MMF MM]]. rewrite MMF. eauto.\nQed.\n\nLemma ple_storebytes:\n  forall m b ofs bytes m' m1\n   (PLE: perm_lesseq m m1),\n   Mem.storebytes m b ofs bytes = Some m' ->\n   exists m1', perm_lesseq m' m1' /\\ Mem.storebytes m1 b ofs bytes = Some m1'.\nProof.\nintros. Transparent Mem.storebytes. unfold Mem.storebytes in *. Opaque Mem.storebytes.\nremember (Mem.range_perm_dec m b ofs (ofs + Z.of_nat (length bytes)) Cur Writable ) as d.\ndestruct d; inv H.\ndestruct (Mem.range_perm_dec m1 b ofs (ofs + Z.of_nat (length bytes)) Cur Writable).\n+ clear Heqd.\n  eexists; split. 2: reflexivity.\n  destruct PLE.\n  split; intros; simpl.\n  - simpl. apply perm_le_Cur.\n  - simpl. apply perm_le_Max.\n  - simpl in *. rewrite PMap.gsspec. rewrite PMap.gsspec.\n    destruct (peq b0 b); subst.\n    * destruct (zlt ofs0 ofs).\n      ++ rewrite Mem.setN_outside. 2: left; trivial.  rewrite Mem.setN_outside. 2: left; trivial.  apply perm_le_cont. apply H.\n      ++ destruct (zle (ofs+Z.of_nat (length bytes)) ofs0).\n         rewrite Mem.setN_outside. 2: right; xomega.  rewrite Mem.setN_outside. 2: right; xomega.  apply perm_le_cont. apply H.\n         clear - g g0.\n         remember ((Mem.mem_contents m1) !! b) as mA. clear HeqmA.\n         remember ((Mem.mem_contents m) !! b) as mB. clear HeqmB.\n         revert ofs mA mB g g0; induction bytes; intros; simpl.\n         -- simpl in *; omega.\n         -- simpl length in g0; rewrite inj_S in g0.\n            destruct (zeq ofs ofs0).\n            ** subst ofs0. rewrite !Mem.setN_outside by omega. rewrite !ZMap.gss; auto.\n            ** apply IHbytes; omega.\n    * apply perm_le_cont. apply H.\n  - assumption .\n+ elim n; clear - PLE r. destruct PLE.\n  red; intros. specialize (r _ H). specialize (perm_le_Cur b ofs0).\n  unfold Mem.perm in *.\n  destruct ((Mem.mem_access m1) !! b ofs0 Cur).\n  destruct ((Mem.mem_access m) !! b ofs0 Cur). simpl in *. eapply perm_order_trans; eassumption.\n  inv r.\n  destruct ((Mem.mem_access m) !! b ofs0 Cur); inv perm_le_Cur. inv r.\nQed.\n\nLemma ple_loadbytes m b ofs n bytes\n            (LD: Mem.loadbytes m b ofs n = Some bytes)\n            m1 (PLE: perm_lesseq m m1) (N: 0 <= n):\n            Mem.loadbytes m1 b ofs n = Some bytes.\nProof.\nTransparent Mem.loadbytes.\nunfold Mem.loadbytes.\nOpaque Mem.loadbytes.\napply loadbytes_D in LD. destruct LD as [RP1 CONT].\ndestruct PLE.\ndestruct (Mem.range_perm_dec m1 b ofs (ofs + n) Cur Readable).\n+ rewrite CONT; f_equal. eapply Mem.getN_exten.\n  intros. apply perm_le_cont. apply RP1. rewrite Z2Nat.id in H; omega.\n+ elim n0; clear - RP1 perm_le_Cur.\n  red; intros. specialize (RP1 _ H). specialize (perm_le_Cur b ofs0).\n  unfold Mem.perm in *.\n  destruct ((Mem.mem_access m1) !! b ofs0 Cur).\n  destruct ((Mem.mem_access m) !! b ofs0 Cur). simpl in *. eapply perm_order_trans; eassumption.\n  inv RP1.\n  destruct ((Mem.mem_access m) !! b ofs0 Cur); inv perm_le_Cur. inv RP1.\nQed.\n\nLemma alloc_access_inv m b lo hi m' (ALLOC: Mem.alloc m lo hi = (m', b)) b' ofs k p\n  (P: (Mem.mem_access m') !! b' ofs k = Some p):\n  (b'=b /\\ Z.le lo ofs /\\ Z.lt ofs hi) \\/\n  (b' <> b /\\ (Mem.mem_access m) !! b' ofs k = Some p).\nProof.\nTransparent Mem.alloc. unfold Mem.alloc in ALLOC. Opaque Mem.alloc. inv ALLOC; simpl in *.\nrewrite PMap.gsspec in P.\ndestruct (peq b' (Mem.nextblock m)); subst; trivial.\n+ left; split; trivial.\n  remember (zle lo ofs && zlt ofs hi) as q. destruct q; inv P; trivial.\n  destruct (zle lo ofs); destruct (zlt ofs hi); simpl in *; try discriminate; omega.\n+ right; split; trivial.\nQed.\n\nLemma alloc_access_inv_None m b lo hi m' (ALLOC: Mem.alloc m lo hi = (m', b)) b' ofs k\n  (P: (Mem.mem_access m') !! b' ofs k = None): (Mem.mem_access m) !! b' ofs k = None.\nProof.\nTransparent Mem.alloc. unfold Mem.alloc in ALLOC. Opaque Mem.alloc. inv ALLOC; simpl in *.\nrewrite PMap.gsspec in P.\ndestruct (peq b' (Mem.nextblock m)); subst; trivial.\napply Mem.nextblock_noaccess. xomega.\nQed.\n\nLemma alloc_inc_perm: forall m lo hi m' b\n      (M: Mem.alloc m lo hi = (m',b)) m1 (PLE: perm_lesseq m m1),\n      exists m1' : mem, Mem.alloc m1 lo hi =(m1',b) /\\ perm_lesseq m' m1'.\nProof. intros.\n  remember (Mem.alloc m1 lo hi). destruct p; symmetry in Heqp.\n  assert (B: b0=b).\n     apply Mem.alloc_result  in M. apply Mem.alloc_result  in Heqp.\n     destruct PLE. rewrite perm_le_nb in *; subst. trivial.\n  subst b0.\n  eexists m0; split; trivial.\n  Transparent Mem.alloc. unfold Mem.alloc in *. Opaque Mem.alloc. inv M; inv Heqp. simpl in *.\n  destruct PLE.\n  split; simpl; intros.\n  + specialize (perm_le_Cur b ofs); clear perm_le_Max perm_le_cont.\n    rewrite perm_le_nb, PMap.gsspec.  rewrite PMap.gsspec.\n    destruct (peq b (Mem.nextblock m1)); subst; trivial.\n    destruct (if zle lo ofs && zlt ofs hi then Some Freeable else None); simpl; trivial. apply perm_refl.\n  + specialize (perm_le_Max b ofs); clear perm_le_Cur perm_le_cont.\n    rewrite perm_le_nb, PMap.gsspec.  rewrite PMap.gsspec.\n    destruct (peq b (Mem.nextblock m1)); subst; trivial.\n    destruct (if zle lo ofs && zlt ofs hi then Some Freeable else None); simpl; trivial. apply perm_refl.\n  + unfold Mem.perm in H; simpl in H.\n    rewrite PMap.gsspec in H.\n    destruct (peq b (Mem.nextblock m)); subst.\n    - rewrite perm_le_nb. do 2 rewrite PMap.gss. trivial.\n    - rewrite PMap.gso; try rewrite H1; trivial. rewrite PMap.gso; trivial. apply perm_le_cont. apply H.\n  + rewrite H1; trivial.\nQed.\n\nLemma perm_lesseq_refl:\n  forall m, perm_lesseq m m.\nProof.\nintros.\n constructor; intros; auto.\n match goal with |- Mem.perm_order'' ?A _ => destruct A; constructor end.\n match goal with |- Mem.perm_order'' ?A _ => destruct A; constructor end.\nQed.\n\n(*************************************************************************)\n\nDefinition corestep_fun {C M : Type} (sem : @CoreSemantics C M) :=\n  forall (m m' m'' : M) c c' c'',\n  corestep sem c m c' m' ->\n  corestep sem c m c'' m'' ->\n  c'=c'' /\\ m'=m''.\n\n(**  Multistepping *)\n\nSection corestepN.\n  Context {C M E:Type} (Sem:@CoreSemantics C M).\n\n  Fixpoint corestepN (n:nat) : C -> M -> C -> M -> Prop :=\n    match n with\n      | O => fun c m c' m' => (c,m) = (c',m')\n      | S k => fun c1 m1 c3 m3 => exists c2, exists m2,\n        corestep Sem c1 m1 c2 m2 /\\\n        corestepN k c2 m2 c3 m3\n    end.\n\n  Lemma corestepN_add : forall n m c1 m1 c3 m3,\n    corestepN (n+m) c1 m1 c3 m3 <->\n    exists c2, exists m2,\n      corestepN n c1 m1 c2 m2 /\\\n      corestepN m 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 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 x1 x2 c3 m3).\n    eauto.\n  Qed.\n\n  Definition corestep_plus c m c' m' :=\n    exists n, corestepN (S n) c m c' m'.\n\n  Definition corestep_star c m c' m' :=\n    exists n, corestepN n c m c' m'.\n\n  Lemma corestep_plus_star : forall c1 c2 m1 m2,\n    corestep_plus c1 m1 c2 m2 -> corestep_star c1 m1 c2 m2.\n  Proof. intros. destruct H as [n1 H1]. eexists. apply H1. Qed.\n\n  Lemma corestep_plus_trans : forall c1 c2 c3 m1 m2 m3,\n    corestep_plus c1 m1 c2 m2 -> corestep_plus c2 m2 c3 m3 ->\n    corestep_plus c1 m1 c3 m3.\n  Proof. intros. destruct H as [n1 H1]. destruct H0 as [n2 H2].\n    destruct (corestepN_add (S n1) (S n2) c1 m1 c3 m3) as [_ H].\n    eexists. apply H. exists c2. exists m2. split; assumption.\n  Qed.\n\n  Lemma corestep_star_plus_trans : forall c1 c2 c3 m1 m2 m3,\n    corestep_star c1 m1 c2 m2 -> corestep_plus c2 m2 c3 m3 ->\n    corestep_plus c1 m1 c3 m3.\n  Proof. intros. destruct H as [n1 H1]. destruct H0 as [n2 H2].\n    destruct (corestepN_add n1 (S n2) 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 corestep_plus_star_trans: forall c1 c2 c3 m1 m2 m3,\n    corestep_plus c1 m1 c2 m2 -> corestep_star c2 m2 c3 m3 ->\n    corestep_plus c1 m1 c3 m3.\n  Proof. intros. destruct H as [n1 H1]. destruct H0 as [n2 H2].\n    destruct (corestepN_add (S n1) n2 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 corestep_star_trans: forall c1 c2 c3 m1 m2 m3,\n    corestep_star c1 m1 c2 m2 -> corestep_star c2 m2 c3 m3 ->\n    corestep_star c1 m1 c3 m3.\n  Proof. intros. destruct H as [n1 H1]. destruct H0 as [n2 H2].\n    destruct (corestepN_add n1 n2 c1 m1 c3 m3) as [_ H].\n    eexists. apply H.  exists c2. exists m2.  split; assumption.\n  Qed.\n\n  Lemma corestep_plus_one: forall c m c' m',\n    corestep Sem c m c' m' -> corestep_plus c m c' m'.\n  Proof. intros. unfold corestep_plus, corestepN. simpl.\n    exists O. exists c'. exists m'. eauto.\n  Qed.\n\n  Lemma corestep_plus_two: forall c m c' m' c'' m'',\n    corestep Sem c m c' m' -> corestep Sem c' m' c'' m'' ->\n    corestep_plus 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 corestep_star_zero: forall c m, corestep_star  c m c m.\n  Proof. intros. exists O. reflexivity. Qed.\n\n  Lemma corestep_star_one: forall c m c' m',\n    corestep  Sem c m c' m' -> corestep_star c m c' m'.\n  Proof. intros.\n    exists (S O). exists c'. exists m'. split; trivial. reflexivity.\n  Qed.\n\n  Lemma corestep_plus_split: forall c m c' m',\n    corestep_plus c m c' m' ->\n    exists c'', exists m'', corestep  Sem c m c'' m'' /\\\n      corestep_star 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 corestepN.\n\nSection memstepN.\n  Context {C:Type} (M:@MemSem C).\n\nLemma corestepN_mem n: forall c m c' m', corestepN M n c m c' m' -> mem_step m m'.\ninduction n; intros; inv H.\n  apply mem_step_refl.\n  destruct H0 as [m'' [CS CSN]]. eapply mem_step_trans.\n  eapply corestep_mem; eassumption.\n  eapply IHn; eassumption.\nQed.\n\nLemma corestep_plus_mem c m c' m' (H:corestep_plus M c m c' m'): mem_step m m'.\ndestruct H as [n H]. eapply corestepN_mem; eassumption. Qed.\n\nLemma corestep_star_mem c m c' m' (H:corestep_star M c m c' m'): mem_step m m'.\ndestruct H as [n H]. eapply corestepN_mem; eassumption. Qed.\n\nLemma memsem_preservesN P (HP: memstep_preserve P)\n      n c m c' m' (H: corestepN M n c m c' m'): P m m'.\napply corestepN_mem in H. apply HP; trivial. Qed.\n\nLemma memsem_preserves_plus P (HP:memstep_preserve P)\n      c m c' m' (H: corestep_plus M c m c' m'): P m m'.\ndestruct H. apply (memsem_preservesN _ HP) in H; trivial. Qed.\n\nLemma memsem_preserves_star P (HP:memstep_preserve P)\n      c m c' m' (H: corestep_star M c m c' m'): P m m'.\ndestruct H. apply (memsem_preservesN _ HP) in H; trivial. Qed.\n\nLemma corestepN_fwd n  c m c' m'\n   (CS:corestepN M n c m c' m'): mem_forward m m'.\nProof.\neapply memsem_preservesN; try eassumption. apply mem_forward_preserve.\nQed.\n\nLemma corestep_plus_fwd c m c' m'\n   (CS:corestep_plus M c m c' m'): mem_forward m m'.\nProof.\ndestruct CS. eapply corestepN_fwd; eassumption.\nQed.\n\nLemma corestep_star_fwd c m c' m'\n   (CS:corestep_star M c m c' m'): mem_forward m m'.\nProof.\ndestruct CS. eapply corestepN_fwd; eassumption.\nQed.\n\nLemma corestepN_rdonly n c m c' m'\n    (CS:corestepN M n c m c' m') b (VB:Mem.valid_block m b): readonly m b m'.\nProof.\neapply (memsem_preservesN _ readonly_preserve'); eassumption.\nQed.\n\nLemma corestep_plus_rdonly c m c' m'\n   (CS:corestep_plus M c m c' m') b (VB:Mem.valid_block m b): readonly m b m'.\nProof.\ndestruct CS. eapply corestepN_rdonly; eassumption.\nQed.\n\nLemma corestep_star_rdonly c m c' m'\n   (CS:corestep_star M c m c' m')b (VB:Mem.valid_block m b): readonly m b m'.\nProof.\ndestruct CS. eapply corestepN_rdonly; eassumption.\nQed.\n\nEnd memstepN.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/concurrency/memsem_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2836212765497148}}
{"text": "(* ------------------------------------------------------- *)\n(** #<hr> <center> <h1>#\n        The double time redundancy (DTR) transformation   \n#</h1>#    \n-   states transitions without any glitches for memoty block\n\n          Dmitry Burlyaev - Pascal Fradet - 2015\n#</center> <hr>#                                           *)\n(* ------------------------------------------------------- *)\n\nAdd LoadPath \"..\\..\\Common\\\".\nAdd LoadPath \"..\\..\\TMRProof\\\".\nAdd LoadPath \"..\\Transf\\\".\n\nRequire Import dtrTransform relationPred leftStep rightStep leftStepg.\n\nSet Implicit Arguments.\n\n(* ##################################################################### *)\n(** Properties of Memory Block w/o Glitches for both cycles              *)\n(* ##################################################################### *)\n\n(** Basic properties of evaluation of DTR circuits without faults  *)\n\n(*Odd cycles when all control signals (save, fail, rollBack) are zeros*)\nLemma step0_mb: forall S T (c c' c'':circuit S T) c2 c2' t2 s t, \n                pure_bset s -> dtrs0 c c' c2 \n             -> step c' s t c''\n             -> step c2 {s,{~0,~0,~0}} t2 c2'\n             -> t2 = {t,{~0,~0,~0}} /\\ dtrs1 c c' c'' c2'.\nProof.\nintrov P R H HT. induction H; unfold dtrs1.\n- Inverts R. Invstep HT. Simpl.\n- Inverts R. Invstep HT. Simpl.\n- destruct c; Inverts R; Inverts HT; Simpl.\n  Apply IHstep1 in H6; Simpl.\n  Apply IHstep2 in H12; Simpl.\n- Dd_buset t2. Inverts R. \n  unfold SWAP_LS in HT. unfold SWAP_LR in HT.\n  Invstep HT. SimpS.\n  Apply IHstep1 in H0; Simpl.\n  Apply IHstep2 in H11; Simpl.\n  repeat constructor; easy.\n- Dd_buset t2. Inverts R. Inverts H8.\n  unfold memBlock in HT. unfold lhsMB in HT. unfold rhsMB in HT.\n  Invstep HT. SimpS.\n  Apply step_rhs in H16. SimpS.\n  apply step_lhs with (d:=r) (r:=r) (sav:=false) (rol:=false) (fai:=false) in H19; Simpl.\n  unfold bool2bset in H2. repeat rewrite eqb_reflx in H2. cbn in H2.\n  Apply IHstep in H2; Simpl. cbn in H1.\n  rewrite s2bob2s in H1.\n  repeat constructor; Simpl. cbn. constructor.\nQed.\n\n(*Even cycles when the control signals (save, fail, rollBack) = {1,0, unknown not glitched}*)\nLemma step1_mb : forall S T (c c' c'':circuit S T) c2 c2' t2 s t f, \n                    pure_bset s ->  pure_bset f -> dtrs1 c c' c'' c2 \n                    -> step c' s t c''\n                    -> step c2 {s,{~1,~0,f}} t2 c2'\n                    -> (exists b, t2 = {t,{~1,~0,bool2bset b}}) /\\ dtrs0 c' c'' c2'.\nProof.\nintros S T c. \ninduction c; introv P1 P2 R H HT; unfold dtrs1; Inverts R.\n- Invstep HT. Invstep H1. split; Simpl; try constructor.\n  exists (fbset2bool f). rewrite rew_bool2bsetf; easy.\n- Invstep HT. Invstep H1. split; Simpl; try constructor.\n  exists (fbset2bool f). rewrite rew_bool2bsetf; easy.\n- Inverts H. Invstep HT. Simpl.\n  apply IHc1 with (c':=c1') (c'':= c1'') (t:=t0) in H; Simpl.\n  apply IHc2 with (c':=c2'0) (c'':=c2'') (t:=t) in H0; Simpl.\n  split; Simpl. constructor; easy.\n- unfold  SWAP_LR in HT. unfold  SWAP_LS in HT.\n  Invstep HT. SimpS. Inverts H13.\n  Apply IHc1 with H H0 H1 H2 in H3. SimpS.\n  Apply IHc2 with H1 H10 H11 in H9.\n  split; Simpl. constructor; easy.\n- Inverts H8. unfold memBlock in HT. unfold lhsMB in HT.\n  unfold rhsMB in HT. Invstep HT.\n  Inverts H20. SimpS.\n  Apply step_rhs in H15.\n  apply step_lhs with (fai:= fbset2bool f) (sav:=true) \n                      (rol:= false) (d:= x87) (r:= r) in H18; try rewrite rew_bool2bsetf; try easy.\n  SimpS. cbn in H1.\n  rewrite eqb_reflx in H2. unfold bool2bset in H2. cbn in H2.\n  Apply  IHc with H4 H7 in H2.\n  destruct H2; Simpl. split.\n  + exists x. easy.\n  + cbn. repeat constructor; easy.\nQed.\n", "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/newmemoryStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878696277512, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2835658286498595}}
{"text": "From iris.proofmode Require Import tactics.\nFrom mwp Require Import mwp_adequacy.\nFrom logrel_ifc.lambda_sec Require Export lang typing fundamental_binary.\nFrom logrel_ifc.lambda_sec Require Import lattice.\n\nSection soundness.\n\n  Class lambdasecPreG Σ := LambdaSecPreG {\n    lambdasec_preG_iris :> invPreG Σ;\n    secGpre_gen_heapG_left :> gen_heapPreG loc val Σ;\n    secGpre_gen_heapG_right :> gen_heapPreG loc val Σ;\n  }.\n\n  Context `{SecurityLattice label}.\n\n  Definition secΣ : gFunctors :=\n    #[invΣ; gen_heapΣ loc val; gen_heapΣ loc val].\n\n  Definition SI_init Σ (x : gen_heapG loc val Σ) := gen_heap_interp (hG := x) ∅.\n\n  Instance SI_left_init_data `{!gen_heapPreG loc val Σ} : InitData (SI_init Σ).\n  Proof.\n    rewrite /InitData; iMod gen_heap_init as (?) \"(?&?)\"; eauto. \n  Qed.\n\n  Definition SI Σ (x : gen_heapG loc val Σ) (σ : state) := gen_heap_interp σ.\n\n  Theorem soundness_semantic Σ `{lambdasecPreG Σ} e (b1 b2 : bool) (ℓ ℓ' : label)\n          (rd  : Reds (e.[# (BoolV b1)/]) ∅)\n          (rd' : Reds (e.[# (BoolV b2)/]) ∅)\n          (flow1 : ℓ' ⋢ ζ)\n          (flow2 : ℓ  ⊑ ζ) :\n    (∀ (Hcnd : secG Σ), [ TBool @ (LLabel ℓ') ] ⊨ e ≤ₗ e : TBool @ (LLabel ℓ)) →\n    end_val rd = end_val rd'.\n  Proof.\n    intros Hlog.\n    eapply (mwp_left_adequacy\n              (SI Σ) (SI Σ) (SI_init Σ) (SI_init Σ) _ _ _ _ _ (λ x _ y _, x = y)).\n    iIntros ([? [leftG rightG]]).\n    rewrite /SI_init /SI /=.\n    iIntros \"[Hl Hr]\".\n    iModIntro. iFrame.\n    iApply (mwp_wand_r with \"[-]\"); iSplitL.\n    { iApply (Hlog (SecG _ _ leftG rightG) [] [] [(BoolV b1, BoolV b2)] with \"[]\").\n      iSplit; first rewrite /env_coherent //.\n      iApply interp_env_cons.\n      iSplit; last by iApply interp_env_nil.\n      rewrite interp_sec_def interp_bool_def /=.\n      rewrite bool_decide_eq_false_2 //.\n      rewrite !interp_un_sec_def !interp_un_bool_def; auto. }\n    iIntros (? ? ?) \"H /=\".\n    rewrite interp_sec_def interp_bool_def bool_decide_eq_true_2 //=.\n    by iDestruct \"H\" as (c1 c2) \"(->&->&->)\".\n  Qed.\n\n  Theorem soundness_tini (e : expr) v1 v2 v1' v2' ℓ ℓ' :\n    ℓ' ⋢ ζ →\n    ℓ  ⊑ ζ →\n    [TBool @ (LLabel ℓ')] # (LLabel ℓ) ⊢ₜ e : TBool @ (LLabel ℓ) →\n    [] # (LLabel ℓ) ⊢ₜ #v1 : TBool @ (LLabel ℓ') →\n    [] # (LLabel ℓ) ⊢ₜ #v2 : TBool @ (LLabel ℓ') →\n    ((∃ σ1, rtc pstep (e.[# v1/], ∅) (# v1', σ1)) ∧\n     (∃ σ2, rtc pstep (e.[# v2/], ∅) (# v2', σ2))) →\n    v1' = v2'.\n  Proof.\n    intros Hflow1 Hflow2 Htpe Htp1 Htp2 [Hrd1 Hrd2].\n    destruct (bool_val_typed _ _ _ _ v1 _ Htp1);\n      eauto using to_of_val; [simplify_eq].\n    destruct (bool_val_typed _ _ _ _ v2 _ Htp2);\n      eauto using to_of_val; [simplify_eq].\n    destruct Hrd1 as [σ1 Hrd1].\n    destruct Hrd2 as [σ2 Hrd2].\n    destruct (rtc_nsteps _ _ Hrd1) as [n1 Hrd1'].\n    destruct (rtc_nsteps _ _ Hrd2) as [n2 Hrd2'].\n    assert (lambdasecPreG #[secΣ]) as HPG.\n    { constructor; apply _. }\n     set (Hrd1'' := {| reds := Hrd1' |}).\n    set (Hrd2'' := {| reds := Hrd2' |}).\n    apply (soundness_semantic #[secΣ] _ _ _ ℓ ℓ' Hrd1'' Hrd2''); [done..|].\n    intros ?.\n    by eapply binary_fundamental.\n  Qed.\n\nEnd soundness.\n\nSection soundness_tp.\n\n  Instance tpSecurityLattice : SecurityLattice tplabel := { ζ := L }.\n  Notation H := (LLabel H).\n  Notation L := (LLabel L).\n\n  Theorem soundness_tini_tp (e : expr) v1 v2 v1' v2' :\n    [TBool @ H] # L ⊢ₜ e : TBool @ L →\n    [] # L ⊢ₜ #v1 : TBool @ H →\n    [] # L ⊢ₜ #v2 : TBool @ H →\n    ((∃ σ1, rtc pstep (e.[# v1/], ∅) (# v1', σ1)) ∧\n     (∃ σ2, rtc pstep (e.[# v2/], ∅) (# v2', σ2))) →\n    v1' = v2'.\n  Proof. by apply soundness_tini. Qed.\n\nEnd soundness_tp.\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/noninterference.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160664, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.283565822144136}}
{"text": "(** \n_AUTHOR_\n\n<<\nZhi Zhang\nDepartment of Computer and Information Sciences\nKansas State University\nzhangzhi@ksu.edu\n>>\n*)\n\nRequire Export rt_gen.\nRequire Export rt_opt_util.\nRequire Export well_typed_util.\n\n\nScheme expression_ind := Induction for exp Sort Prop \n                         with name_ind := Induction for name Sort Prop.\n\nScheme expression_x_ind := Induction for expRT Sort Prop \n                         with name_x_ind := Induction for nameRT Sort Prop.\n\n\n(** * Eval Expr Value In Bound *)\n\nLemma eval_expr_value_in_bound: forall e st st' s e' v e'' eBound,\n  toExpRT st e e' ->\n    toSymTabRT st st' ->\n      well_typed_stack st' s ->\n        well_typed_exp_x st' e' ->\n          evalExpRT st' s e' (OK (Int v)) ->\n            optExp st' e' (e'', eBound) ->\n              in_bound v eBound true.\nProof.\n  apply (expression_ind\n    (fun e: exp =>\n       forall (st : symTab) (st' : symTabRT) (s : STACK.state) \n              (e' : expRT) (v : Z) (e'' : expRT) eBound,\n         toExpRT st e e' ->\n         toSymTabRT st st' ->\n         well_typed_stack st' s ->\n         well_typed_exp_x st' e' ->\n         evalExpRT st' s e' (OK (Int v)) ->\n         optExp st' e' (e'', eBound) ->\n         in_bound v eBound true)\n    (fun n: name =>\n       forall (st : symTab) (st' : symTabRT) (s : STACK.state) \n              (n' : nameRT) (v : Z) (n'' : nameRT) eBound,\n         toNameRT st n n' ->\n         toSymTabRT st st' ->\n         well_typed_stack st' s ->\n         well_typed_name_x st' n' ->\n         evalNameRT st' s n' (OK (Int v)) ->\n         optName st' n' (n'', eBound) ->\n         in_bound v eBound true)\n    ); intros.\n- inversion H; subst;\n  inversion H3; subst;\n  inversion H4; subst.\n  + inversion H12; subst.\n  + inversion H13; subst.\n    inversion H8; subst.\n    inversion H7; subst.\n    inversion H11; subst.\n    apply In_Bound_Refl; auto.\n    apply In_Bound_Two; auto. \n    apply In_Bound_Refl; auto.\n  + inversion H13; subst.\n    inversion H8; subst.\n    inversion H5; subst.\n    apply_in_bound_conflict; smack.\n- inversion H0; subst;\n  inversion H3; subst;\n  inversion H4; subst;\n  inversion H5; subst.\n  specialize (H _ _ _ _ _ _ _ H10 H1 H2 H11 H14 H8); assumption.\n- inversion H1; subst;\n  inversion H4; subst;\n  inversion H5; subst;\n  inversion H6; subst.\n  \n  + (** b = Plus \\/ b = Minus \\/ b = Multiply *)\n    apply_binop_arithm_operand_format; subst.\n    specialize (H _ _ _ _ _ _ _ H14 H2 H3 H17 H25 H11).\n    specialize (H0 _ _ _ _ _ _ _ H15 H2 H3 H18 H26 H29).\n    apply_plus_result_in_bound; auto.\n  + (** Divide *)\n    apply_binop_arithm_operand_format; subst.\n    specialize (H _ _ _ _ _ _ _ H14 H2 H3 H16 H24 H11).\n    specialize (H0 _ _ _ _ _ _ _ H15 H2 H3 H17 H25 H28).\n    match goal with\n    | [H1: evalBinOpRTS (DivCheck :: _) _ _ _ _ |- _] => inversion H1; subst\n    end;\n    repeat progress match goal with\n    | [H1: evalBinOpRT DivCheck _ _ _ _ |- _] => inversion H1; subst; clear H1\n    | [H1: divCheck ?op ?v0 ?v3 (OK ?v4) |- _ ] => inversion H1; subst; clear H1\n    end.\n    apply_divide_result_in_bound; auto.\n  + (** Modulus *)\n    apply_binop_arithm_operand_format; subst.\n    specialize (H _ _ _ _ _ _ _ H14 H2 H3 H16 H24 H11).\n    specialize (H0 _ _ _ _ _ _ _ H15 H2 H3 H17 H25 H28).\n    match goal with\n    | [H1: evalBinOpRTS (DivCheck :: _) _ _ _ _ |- _] => inversion H1; subst\n    end;\n    repeat progress match goal with\n    | [H1: evalBinOpRT DivCheck _ _ _ _ |- _] => inversion H1; subst; clear H1\n    | [H1: divCheck ?op ?v0 ?v3 (OK ?v4) |- _ ] => inversion H1; subst; clear H1\n    end.\n    apply_modulus_result_in_bound; auto.\n  + inversion H31; subst.\n    clear - H11 H12 H13 H15 H17 H8.\n    destruct b; smack;\n    destruct v1, v2; inversion H8.\n- inversion H0; subst;\n  inversion H3; subst;\n  inversion H4; subst;\n  inversion H5; subst.\n  + apply_unop_arithm_operand_format; subst.\n    specialize (H _ _ _ _ _ _ _ H12 H1 H2 H11 H19 H9).\n    apply_unop_arithm_in_bound; auto.\n  + inversion H21; subst.\n    destruct u; destruct v0; inversion H7; smack.\n- inversion H; subst;\n  inversion H1; subst;\n  inversion H2; subst;\n  inversion H3; subst;\n  inversion H4; subst.\n  specialize (H5 _ _ H10).\n  destruct H5 as [md' [t' [HZ1 HZ2]]].\n  rewrite HZ1 in H11; inversion H11; subst.\n  rewrite H12 in H9; inversion H9; subst.\n  inversion HZ2; subst;\n  inversion H16; smack;\n  [inversion H5; subst; inversion H13 | | | ];\n  apply_extract_subtype_range_unique; smack.\n- apply_eval_name_well_typed_value.\n  inversion H1; subst;\n  inversion H4; subst;\n  inversion H6; subst.\n  smack.\n  rewrite H23 in H17; inversion H17; subst.\n  rewrite H16 in HZ0; inversion HZ0; subst.\n  inversion H26; subst.\n  rewrite H7 in H18; inversion H18; subst.\n\n  inversion HZ1; subst;  \n  inversion H8; smack;\n  [inversion H9; subst; inversion H20 | | | ];\n  apply_extract_subtype_range_unique; smack.\n- apply_eval_name_well_typed_value.\n  inversion H0; subst;\n  inversion H3; subst;\n  inversion H5; smack.\n  rewrite H20 in H14; inversion H14; subst.\n  rewrite H13 in HZ0; inversion HZ0; subst.\n  inversion H21; subst.\n  rewrite H6 in H15; inversion H15; subst.\n  rewrite H7 in H16; inversion H16; subst.\n  \n  inversion HZ1; subst;\n  inversion H8; smack;\n  [ inversion H9; subst; inversion H22 | | | ];\n  apply_extract_subtype_range_unique; smack.  \nQed.\n\nLtac apply_eval_expr_value_in_bound :=\n  match goal with\n  | [H1: toExpRT ?st ?e ?e',\n     H2: toSymTabRT ?st ?st',\n     H3: well_typed_stack ?st' ?s,\n     H4: well_typed_exp_x ?st' ?e',\n     H5: evalExpRT ?st' ?s ?e' (OK (Int ?v)),\n     H6: optExp ?st' ?e' _ |- _] =>\n      specialize (eval_expr_value_in_bound _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6);\n      let HZ := fresh \"HZ\" in intros HZ\n  end.\n\n(** * Eval Name Value In Bound *)\nLemma eval_name_value_in_bound: forall n st st' s n' v n'' nBound,\n  toNameRT st n n' ->\n    toSymTabRT st st' ->\n      well_typed_stack st' s ->\n        well_typed_name_x st' n' ->\n          evalNameRT st' s n' (OK (Int v)) ->\n            optName st' n' (n'', nBound) ->\n              in_bound v nBound true.\nProof.\n  induction n; intros.\n- inversion H; subst;\n  inversion H2; subst;\n  inversion H3; subst;\n  inversion H4; subst.\n  \n  apply_eval_name_well_typed_value. simpl in HZ0.\n  repeat progress match goal with\n  | [H1: fetch_exp_type_rt ?x ?st = _,\n     H2: fetch_exp_type_rt ?x ?st = _ |- _] => rewrite H1 in H2; inversion H2; subst\n  | _ => idtac\n  end.\n  apply_typed_value_in_bound; auto.\n- apply_eval_name_well_typed_value.\n  inversion H; subst;\n  inversion H2; subst;\n  inversion H3; subst;\n  inversion H4; subst.\n  \n  simpl in HZ0.\n  clear H H2 H3 H4 IHn.\n  repeat progress match goal with\n  | [H1: fetch_exp_type_rt ?x ?st = _,\n     H2: fetch_exp_type_rt ?x ?st = _ |- _] => rewrite H1 in H2; inversion H2; subst\n  | _ => idtac\n  end.\n  clear - H30 H16 HZ1. (* H30: bound_of_array_component_type st' t2 nBound*)\n  inversion H30; subst.\n  match goal with\n  | [H1: fetch_type_rt ?x ?st = _,\n     H2: fetch_type_rt ?x ?st = _ |- _] => rewrite H1 in H2; inversion H2; subst\n  end.\n  apply_typed_value_in_bound; auto.\n- apply_eval_name_well_typed_value.\n  inversion H; subst;\n  inversion H2; subst;\n  inversion H3; subst;\n  inversion H4; smack.\n\n  repeat progress match goal with\n  | [H1: fetch_exp_type_rt ?x ?st = _,\n     H2: fetch_exp_type_rt ?x ?st = _ |- _] => rewrite H1 in H2; inversion H2; subst\n  | _ => idtac\n  end.\n  clear - H22 H14 H15 HZ1.\n  inversion H22; subst.\n  repeat progress match goal with\n  | [H1: fetch_type_rt ?x ?st = _,\n     H2: fetch_type_rt ?x ?st = _ |- _] => rewrite H1 in H2; inversion H2; subst\n  | [H1: record_field_type _ _ = _,\n     H2: record_field_type _ _ = _ |- _] => rewrite H1 in H2; inversion H2; subst\n  end.\n  apply_typed_value_in_bound; auto.\nQed.\n\nLtac apply_eval_name_value_in_bound :=\n  match goal with\n  | [H1: toNameRT ?st ?n ?n',\n     H2: toSymTabRT ?st ?st',\n     H3: well_typed_stack ?st' ?s,\n     H4: well_typed_name_x ?st' ?n',\n     H5: evalNameRT ?st' ?s ?n' (OK (Int ?v)),\n     H6: optName ?st' ?n' (?n'', ?nBound) |- _] =>\n      specialize (eval_name_value_in_bound _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6);\n      let HZ := fresh \"HZ\" in intros HZ\n  end.\n\n(** * Soundness of RT-OPT Specification *)\n\n(** ** Helper Lemmas *)\n\nLemma binop_int_operant_exists: forall op cks v1 v2 v, \n  (op = Plus \\/ op = Minus \\/ op = Multiply) \\/ (op = Divide \\/ op = Modulus) ->\n    evalBinOpRTS cks op v1 v2 v ->\n      exists v1' v2', v1 = (Int v1') /\\ v2 = (Int v2').\nProof.\n  intros.\n  destruct H as [[HZ1 | [HZ2 | HZ3]] | [HZ4 | HZ5]]; subst;\n  destruct v1, v2;\n  inversion H0;\n  match goal with\n  | [|- exists v1' v2', Int ?n = Int v1' /\\ Int ?n0 = Int v2'] => exists n, n0; auto \n  | [H: Math.binary_operation _ _ _ = _ |- _] => inversion H; subst\n  | _ => idtac\n  end;\n  match goal with\n  | [H: evalBinOpRT _ _ _ _ _ |- _] => inversion H; subst\n  | _ => idtac\n  end;\n  match goal with\n  | [|- exists v1' v2', Int ?n = Int v1' /\\ Int ?n0 = Int v2'] => exists n, n0; auto \n  | [H: Math.binary_operation _ _ _ = _ |- _] => inversion H; subst\n  | _ => idtac\n  end.\nQed.\n\nLtac apply_binop_int_operant_exists :=\n  match goal with\n  | [H1: (?op = Plus \\/ ?op = Minus \\/ ?op = Multiply) |- _] =>\n      let HA := fresh \"HA\" in\n      assert (HA: (op = Plus \\/ op = Minus \\/ op = Multiply) \\/ (op = Divide \\/ op = Modulus))\n  | [H1: evalBinOpRTS _ Divide _ _ _ |- _] =>\n      let HA := fresh \"HA\" in\n      assert (HA: (Divide = Plus \\/ Divide = Minus \\/ Divide = Multiply) \\/ (Divide = Divide \\/ Divide = Modulus))\n  | [H1: evalBinOpRTS _ Modulus _ _ _ |- _] =>\n      let HA := fresh \"HA\" in\n      assert (HA: (Modulus = Plus \\/ Modulus = Minus \\/ Modulus = Multiply) \\/ (Modulus = Divide \\/ Modulus = Modulus))\n  end; auto;\n  match goal with\n  | [H1: (?op = Plus \\/ ?op = Minus \\/ ?op = Multiply) \\/ (?op = Divide \\/ ?op = Modulus),\n     H2: evalBinOpRTS ?cks ?op ?v1 ?v2 ?v |- _] =>\n      specialize (binop_int_operant_exists _ _ _ _ _ H1 H2);\n      let HZ := fresh \"HZ\" in intros HZ\n  end.\n\nLemma optimize_range_check_reserve_storeUpdate: forall st s n v s' u l u' l' n' ast_num ast_num',\n  storeUpdateRT st s n v s' ->\n    optimize_range_check (NameRT ast_num n) (Interval l u) (Interval l' u') (NameRT ast_num' n') ->\n      storeUpdateRT st s n' v s'.\nProof.\n  intros.\n  inversion H0; smack.\n  apply_store_update_ex_cks_added; auto.  \nQed.\n\nLtac apply_optimize_range_check_reserve_storeUpdate :=\n  match goal with\n  | [H1: storeUpdateRT ?st ?s ?n ?v ?s',\n     H2: optimize_range_check (NameRT ?ast_num ?n) (Interval ?l ?u) (Interval ?l' ?u') (NameRT ?ast_num' ?n') |- _] =>\n    specialize (optimize_range_check_reserve_storeUpdate _ _ _ _ _ _ _ _ _ _ _ _ H1 H2);\n    let HZ := fresh \"HZ\" in intro HZ  \n  end.\n\nLemma optimize_range_check_reserve_storeUpdate_backward: forall st s n v s' u l u' l' n' ast_num ast_num',\n  storeUpdateRT st s n' v s' ->\n    optimize_range_check (NameRT ast_num n) (Interval l u) (Interval l' u') (NameRT ast_num' n') ->\n      storeUpdateRT st s n v s'.\nProof.\n  intros.\n  inversion H0; smack.\n  apply_store_update_ex_cks_stripped; auto.  \nQed.\n\nLtac apply_optimize_range_check_reserve_storeUpdate_backward :=\n  match goal with\n  | [H1: storeUpdateRT ?st ?s ?n' ?v ?s',\n     H2: optimize_range_check (NameRT ?ast_num ?n) (Interval ?l ?u) (Interval ?l' ?u') (NameRT ?ast_num' ?n') |- _] =>\n    specialize (optimize_range_check_reserve_storeUpdate_backward _ _ _ _ _ _ _ _ _ _ _ _ H1 H2);\n    let HZ := fresh \"HZ\" in intro HZ  \n  end.\n\nLemma optimize_range_check_on_copy_out_reserve_storeUpdate: forall st s n v s' u l u' l' n' ast_num ast_num',\n  storeUpdateRT st s n v s' ->\n    optimize_range_check_on_copy_out (NameRT ast_num n) (Interval u l) (Interval u' l') (NameRT ast_num' n') ->\n      storeUpdateRT st s n' v s'.\nProof.\n  intros.\n  inversion H0; smack.\n  apply_store_update_ex_cks_added; auto.  \nQed.\n\nLtac apply_optimize_range_check_on_copy_out_reserve_storeUpdate :=\n  match goal with\n  | [H1: storeUpdateRT ?st ?s ?n ?v ?s',\n     H2: optimize_range_check_on_copy_out (NameRT ?ast_num ?n) (Interval ?l ?u) (Interval ?l' ?u') (NameRT ?ast_num' ?n') |- _] =>\n    specialize (optimize_range_check_on_copy_out_reserve_storeUpdate _ _ _ _ _ _ _ _ _ _ _ _ H1 H2);\n    let HZ := fresh \"HZ\" in intro HZ  \n  end.\n\nLemma optimize_range_check_on_copy_out_reserve_storeUpdate_backward: forall st s n v s' u l u' l' n' ast_num ast_num',\n  storeUpdateRT st s n' v s' ->\n    optimize_range_check_on_copy_out (NameRT ast_num n) (Interval u l) (Interval u' l') (NameRT ast_num' n') ->\n      storeUpdateRT st s n v s'.\nProof.\n  intros.\n  inversion H0; smack.\n  apply_store_update_ex_cks_stripped; auto.  \nQed.\n\nLtac apply_optimize_range_check_on_copy_out_reserve_storeUpdate_backward :=\n  match goal with\n  | [H1: storeUpdateRT ?st ?s ?n' ?v ?s',\n     H2: optimize_range_check_on_copy_out (NameRT ?ast_num ?n) (Interval ?l ?u) (Interval ?l' ?u') (NameRT ?ast_num' ?n') |- _] =>\n    specialize (optimize_range_check_on_copy_out_reserve_storeUpdate_backward _ _ _ _ _ _ _ _ _ _ _ _ H1 H2);\n    let HZ := fresh \"HZ\" in intro HZ  \n  end.\n\nLemma optimize_range_check_both_reserve_storeUpdate: forall st s n v s' u l u' l' n' n'' u1 l1 u1' l1' ast_num ast_num' ast_num'',\n  storeUpdateRT st s n v s' ->\n    optimize_range_check (NameRT ast_num n) (Interval u l) (Interval u' l') (NameRT ast_num' n') ->\n      optimize_range_check_on_copy_out (NameRT ast_num' n') (Interval u1 l1) (Interval u1' l1') (NameRT ast_num'' n'') ->\n        storeUpdateRT st s n'' v s'.\nProof.\n  intros.\n  specialize (optimize_range_check_reserve_storeUpdate _ _ _ _ _ _ _ _ _ _ _ _ H H0); intro.\n  specialize (optimize_range_check_on_copy_out_reserve_storeUpdate _ _ _ _ _ _ _ _ _ _ _ _ H2 H1); auto.\nQed.\n\nLtac apply_optimize_range_check_both_reserve_storeUpdate :=\n  match goal with\n  | [H1: storeUpdateRT ?st ?s ?n ?v ?s',\n     H2: optimize_range_check (NameRT _ ?n) (Interval ?u ?l) (Interval ?u' ?l') (NameRT _ ?n'),\n     H3: optimize_range_check_on_copy_out (NameRT _ ?n') (Interval ?u1 ?l1) (Interval ?u1' ?l1') (NameRT _ ?n'')  |- _] =>\n    specialize (optimize_range_check_both_reserve_storeUpdate _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H1 H2 H3);\n    let HZ := fresh \"HZ\" in intro HZ  \n  end.\n\nLemma optimize_range_check_both_reserve_storeUpdate_backward: forall st s n v s' u l u' l' n' n'' u1 l1 u1' l1' ast_num ast_num' ast_num'',\n  storeUpdateRT st s n'' v s' ->\n    optimize_range_check (NameRT ast_num n) (Interval u l) (Interval u' l') (NameRT ast_num' n') ->\n      optimize_range_check_on_copy_out (NameRT ast_num' n') (Interval u1 l1) (Interval u1' l1') (NameRT ast_num'' n'') ->\n        storeUpdateRT st s n v s'.\nProof.\n  intros.\n  specialize (optimize_range_check_on_copy_out_reserve_storeUpdate_backward _ _ _ _ _ _ _ _ _ _ _ _ H H1); intro.\n  specialize (optimize_range_check_reserve_storeUpdate_backward _ _ _ _ _ _ _ _ _ _ _ _ H2 H0); auto.\nQed.\n\nLtac apply_optimize_range_check_both_reserve_storeUpdate_backward :=\n  match goal with\n  | [H1: storeUpdateRT ?st ?s ?n'' ?v ?s',\n     H2: optimize_range_check (NameRT _ ?n) (Interval ?u ?l) (Interval ?u' ?l') (NameRT _ ?n'),\n     H3: optimize_range_check_on_copy_out (NameRT _ ?n') (Interval ?u1 ?l1) (Interval ?u1' ?l1') (NameRT _ ?n'')  |- _] =>\n    specialize (optimize_range_check_both_reserve_storeUpdate_backward _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H1 H2 H3);\n    let HZ := fresh \"HZ\" in intro HZ  \n  end.\n  \n(* toExpRT st0 e0 e: make sure that e is decorated with correct run time checks,\n   which is required to call the lemma: eval_expr_well_typed_value, that make sure the the \n   evaluation value of e is well-typed with respect to its type;\n   e.g. eval_expr s (Literal 10^100) in_cks out_cks, if in_cks is empty, then its value\n        is not well-typed with reespect to integer;\n *)\nLemma optimize_expression_exist_int_value: forall e e0 e' st0 st s v l u,\n  toExpRT st0 e0 e ->\n    toSymTabRT st0 st ->\n      well_typed_stack_and_symboltable st s ->\n        well_typed_exp_x st e ->\n          evalExpRT st s e (OK v) ->\n            v <> Undefined ->\n              optExp st e (e', Interval l u) ->\n                exists n, v = Int n.\nProof.\n  induction e; intros;\n  apply_eval_expr_well_typed_value;\n  destruct HZ as [t' [HZ1 HZ2]];\n  inversion H3; subst; clear H3;\n  inversion H5; smack; clear H5.\n  - inversion H13; smack.    \n    inversion H7; smack.\n    inversion H13; smack.\n    inversion H8; smack.\n    inversion H8; smack. inversion H6; smack.\n  - match goal with\n    | [H: well_typed_stack_and_symboltable ?st ?s |- _] => destruct H as [st s HStack HSymb]\n    end;\n    apply_well_typed_stack_infer.\n    inversion H; subst;\n    inversion HZ; subst;\n    inversion H2; smack;\n    apply_eval_name_well_typed_value.\n    (* inversion H11; smack; *)\n    inversion H7; smack.\n    (* E_Identifier_X *)\n    rewrite H13 in HZ3; inversion HZ3; subst.\n    apply_well_typed_int_value_exists; smack.\n    (* E_Indexed_Component_X *)\n    match goal with\n    | [H: well_typed_name_x _ _ |- _] => inversion H; subst\n    end.\n    match goal with\n    | [H: bound_of_array_component_type _ ?t _ |- _] => inversion H; subst\n    end.\n    repeat progress match goal with\n    | [H1: fetch_exp_type_rt ?a ?st = Some ?t1, H2: fetch_exp_type_rt ?a ?st = Some ?t2 |- _]\n        => rewrite H1 in H2; inversion H2; subst\n    | [H1: fetch_type_rt ?t ?st = Some ?t1, H2: fetch_type_rt ?t ?st = Some ?t2 |- _] \n        => rewrite H1 in H2; inversion H2; subst\n    end.\n    clear - H5 HZ4 H4.\n    apply_well_typed_int_value_exists; smack.\n    (* E_Selected_Component_X *)\n    match goal with\n    | [H: well_typed_name_x _ _ |- _] => inversion H; subst\n    end.\n    match goal with\n    | [H: bound_of_record_field_type _ ?t ?f _ |- _] => inversion H; smack\n    end.\n    repeat progress match goal with\n    | [H1: fetch_exp_type_rt ?a ?st = Some ?t1, H2: fetch_exp_type_rt ?a ?st = Some ?t2 |- _]\n        => rewrite H1 in H2; inversion H2; subst\n    | [H1: fetch_type_rt ?t ?st = Some ?t1, H2: fetch_type_rt ?t ?st = Some ?t2 |- _] \n        => rewrite H1 in H2; inversion H2; subst\n    | [H1: record_field_type ?fields ?f = Some ?t1, H2: record_field_type ?fields ?f = Some ?t2 |- _] \n        => rewrite H1 in H2; inversion H2; subst\n    end.\n    apply_well_typed_int_value_exists; smack.\n  - inversion H2; subst;\n    inversion H; subst.\n    (* add/minus/multiply *)\n    clear - H4 H10 H17 H19.\n    repeat progress match goal with\n    | [H: evalBinOpRTS _ ?op ?v1 ?v2 (OK ?v) |- _] => inversion H; clear H; smack\n    end;\n    destruct v1, v2;\n    match goal with\n    | [H: _ ?v1 ?v2 = Some ?v |- _] => inversion H; smack\n    end.\n    (* divide *)\n    clear - H4 H17 H19.\n    repeat progress match goal with\n    | [H: evalBinOpRTS _ ?op ?v1 ?v2 (OK ?v) |- _] => inversion H; clear H; smack\n    end;\n    destruct v1, v2;\n    match goal with\n    | [H: _ ?v1 ?v2 = Some ?v |- _] => inversion H; smack\n    end.\n    (* modulus *)\n    clear - H4 H17 H19.\n    repeat progress match goal with\n    | [H: evalBinOpRTS _ ?op ?v1 ?v2 (OK ?v) |- _] => inversion H; clear H; smack\n    end;\n    destruct v1, v2;\n    match goal with\n    | [H: _ ?v1 ?v2 = Some ?v |- _] => inversion H; smack\n    end.\n    (* and/or/... *)\n    match goal with\n    | [H: optimize_rtc_binop ?op ?bound1 ?bound2 _ _ |- _] => inversion H; smack\n    end.\n  - inversion H2; subst;\n    inversion H; subst.\n    (* unary_minus *)\n    clear - H15.\n    repeat progress match goal with\n    | [H: evalUnOpRTS _ ?op ?v (OK ?v') |- _] => inversion H; clear H; smack\n    end.\n    destruct v0;\n    match goal with\n    | [H: Math.unary_minus ?v = Some ?v' |- _] => inversion H; smack\n    end.\n    (* <> Unary_Minus *)\n    match goal with\n    | [H: evalUnOpRTS _ ?op ?v (OK ?v') |- _] => inversion H; smack\n    end.\n    destruct u, v0;\n    match goal with\n    | [H: Math.unary_operation ?op ?v = Some ?v' |- _] => inversion H; smack\n    end.\n    clear - H9 H15 H16.\n    inversion H16; smack.\nQed.\n\nLtac apply_optimize_expression_exist_int_value :=\n  match goal with\n  | [H1: toExpRT ?st0 ?e0 ?e,\n     H2: toSymTabRT ?st0 ?st,\n     H3: well_typed_stack_and_symboltable ?st ?s,\n     H4: well_typed_exp_x ?st ?e,\n     H5: evalExpRT ?st ?s ?e (OK ?v),\n     H6: ?v <> Undefined,\n     H7: optExp ?st ?e (?e', Interval ?l ?u) |- _] =>\n    specialize (optimize_expression_exist_int_value _ _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6 H7);\n    let HZ := fresh \"HZ\" in \n    let v := fresh \"v0\" in\n    intro HZ; destruct HZ as [v HZ]; subst\n  | [H1: toExpRT ?st0 ?e0 ?e,\n     H2: toSymTabRT ?st0 ?st,\n     H3: well_typed_stack_and_symboltable ?st ?s,\n     H4: well_typed_exp_x ?st ?e,\n     H5: evalExpRT ?st ?s ?e (OK ?v),\n     H6: ?v = Undefined -> False,\n     H7: optExp ?st ?e (?e', Interval ?l ?u) |- _] =>\n    specialize (optimize_expression_exist_int_value _ _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6 H7);\n    let HZ := fresh \"HZ\" in\n    let v := fresh \"v0\" in\n    intro HZ; destruct HZ as [v HZ]; subst\n  end.\n\nLemma optimize_name_exist_int_value: forall n n0 n' st0 st s v l u,\n  toNameRT st0 n0 n ->\n    toSymTabRT st0 st ->\n      well_typed_stack st s ->\n        well_typed_name_x st n ->\n          evalNameRT st s n (OK v) ->\n            v <> Undefined ->\n              optName st n (n', Interval l u) ->\n                exists n, v = Int n.\nProof.\n  induction n; intros;\n  apply_eval_name_well_typed_value;\n  inversion H3; subst; clear H3;\n  inversion H5; smack; clear H5;\n  inversion H; subst;\n  inversion H1; subst;\n  inversion H2; smack.\n  (* E_Identifier_X *)\n  rewrite H8 in HZ0; inversion HZ0; subst.\n  apply_well_typed_int_value_exists; smack.\n  (* E_Indexed_Component_X *)\n  match goal with\n  | [H: bound_of_array_component_type _ ?t _ |- _] => inversion H; subst\n  end.\n  repeat progress match goal with\n  | [H1: fetch_exp_type_rt ?a ?st = Some ?t1, H2: fetch_exp_type_rt ?a ?st = Some ?t2 |- _]\n      => rewrite H1 in H2; inversion H2; subst\n  | [H1: fetch_type_rt t' st = Some ?t1, H2: fetch_type_rt t' st = Some ?t2 |- _] \n      => rewrite H1 in H2; inversion H2; subst\n  end.\n  clear - H4 HZ1 H6.\n  apply_well_typed_int_value_exists; smack.\n  (* E_Selected_Component_X *)\n  match goal with\n  | [H: bound_of_record_field_type _ ?t ?f _ |- _] => inversion H; smack\n  end.\n  repeat progress match goal with\n  | [H1: fetch_exp_type_rt ?a ?st = Some ?t1, H2: fetch_exp_type_rt ?a ?st = Some ?t2 |- _]\n        => rewrite H1 in H2; inversion H2; subst\n  | [H1: fetch_type_rt ?t ?st = Some ?t1, H2: fetch_type_rt ?t ?st = Some ?t2 |- _] \n        => rewrite H1 in H2; inversion H2; subst\n  | [H1: record_field_type ?fields ?f = Some ?t1, H2: record_field_type ?fields ?f = Some ?t2 |- _] \n        => rewrite H1 in H2; inversion H2; subst\n    end.\n  apply_well_typed_int_value_exists; smack.\nQed.\n\nLtac apply_optimize_name_exist_int_value :=\n  match goal with\n  | [H1: toNameRT ?st0 ?n0 ?n,\n     H2: toSymTabRT ?st0 ?st,\n     H3: well_typed_stack ?st ?s,\n     H4: well_typed_name_x ?st ?n,\n     H5: evalNameRT ?st ?s ?n (OK ?v),\n     H6: ?v <> Undefined,\n     H7: optName ?st ?n (?n', Interval ?l ?u) |- _] =>\n    specialize (optimize_name_exist_int_value _ _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6 H7);\n    let HZ := fresh \"HZ\" in\n    let v := fresh \"v0\" in\n    intro HZ; destruct HZ as [v HZ]; subst    \n  | [H1: toNameRT ?st0 ?n0 ?n,\n     H2: toSymTabRT ?st0 ?st,\n     H3: well_typed_stack ?st ?s,\n     H4: well_typed_name_x ?st ?n,\n     H5: evalNameRT ?st ?s ?n (OK ?v),\n     H6: ?v = Undefined -> False,\n     H7: optName ?st ?n (?n', Interval ?l ?u) |- _] =>\n    specialize (optimize_name_exist_int_value _ _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6 H7);\n    let HZ := fresh \"HZ\" in\n    let v := fresh \"v0\" in\n    intro HZ; destruct HZ as [v HZ]; subst\n  end.\n\n\n(** ** optExp_soundness *)\nLemma optExp_soundness: forall e st st' s e' e'' eBound v, \n  toExpRT st e e' ->\n    toSymTabRT st st' ->\n      well_typed_stack st' s ->\n        well_typed_exp_x st' e' ->\n          optExp st' e' (e'', eBound) ->\n            evalExpRT st' s e'' v ->\n              evalExpRT st' s e' v.\nProof.\n  apply (expression_ind\n    (fun e: exp =>\n       forall (st : symTab) (st' : symTabRT) (s : STACK.state)\n              (e': expRT) (e'': expRT) (eBound: bound) (v : Ret value),\n      toExpRT st e e' ->\n      toSymTabRT st st' ->\n      well_typed_stack st' s ->\n      well_typed_exp_x st' e' ->\n      optExp st' e' (e'', eBound) ->\n      evalExpRT st' s e'' v ->\n      evalExpRT st' s e' v)\n    (fun n: name =>\n       forall (st : symTab) (st' : symTabRT) (s : STACK.state)\n              (n': nameRT) (n'': nameRT) (nBound: bound) (v : Ret value),\n      toNameRT st n n' ->\n      toSymTabRT st st' ->\n      well_typed_stack st' s ->\n      well_typed_name_x st' n' ->\n      optName st' n' (n'', nBound) ->\n      evalNameRT st' s n'' v ->\n      evalNameRT st' s n' v)\n    ); intros.\n- (** E_Literal_X *)  \n  inversion H; subst;\n  inversion H3; subst;\n  inversion H4; subst;\n  inversion H7; subst; auto;\n  constructor; smack;\n  inversion H10; smack.\n  inversion H12; subst. \n  apply_in_bound_conflict; smack.\n- (** E_Name_X *)\n  inversion H0; subst;\n  inversion H3; subst;\n  inversion H4; subst;\n  inversion H5; subst.\n  specialize (H _ _ _ _ _ _ _ H10 H1 H2 H11 H8 H15). \n  constructor; auto.\n- (** E_Binary_Operation_X *)\n  inversion H1; subst;\n  inversion H4; subst;\n  inversion H5; subst;\n  inversion H6; subst;\n  repeat progress match goal with\n  | [H: forall (st : symTab) (st' : symTabRT) \n        (s : STACK.state) (e' e'' : expRT) (eBound : bound)\n        (v : Ret value),\n      toExpRT st ?e e' ->\n      toSymTabRT st st' ->\n      well_typed_stack st' s ->\n      well_typed_exp_x st' e' ->\n      optExp st' e' (e'', eBound) ->\n      evalExpRT st' s e'' v -> evalExpRT st' s e' v,\n     H1: toExpRT ?st ?e ?e',\n     H2: toSymTabRT ?st ?st',\n     H3: well_typed_stack ?st' ?s,\n     H4: well_typed_exp_x ?st' ?e',\n     H5: optExp ?st' ?e' (?e'', ?eBound),\n     H6: evalExpRT ?st' ?s ?e'' ?v |- _] => specialize (H _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6)\n  end;\n  [apply EvalBinOpRTE1_RTE; auto | | | apply EvalBinOpRTE1_RTE; auto | | | apply EvalBinOpRTE1_RTE; auto | | |\n   apply EvalBinOpRTE1_RTE; auto | | ];\n  [apply EvalBinOpRTE2_RTE with (v1:=v1); auto | | \n   apply EvalBinOpRTE2_RTE with (v1:=v1); auto | |\n   apply EvalBinOpRTE2_RTE with (v1:=v1); auto | |\n   apply EvalBinOpRTE2_RTE with (v1:=v1); auto | ];\n  apply EvalBinOpRT with (v1:=v1) (v2:=v2); auto.\n  + (* Plus | Minus | Multiply *)\n    apply_binop_int_operant_exists.\n    destruct HZ; subst. destruct H7; subst. destruct H7; subst.\n    apply_eval_expr_value_in_bound.\n    specialize (eval_expr_value_in_bound _ _ _ _ _ _ _ _ H14 H2 H3 H17 H H11); intros.\n    apply_plus_result_in_bound_backward; auto.\n  + (* Divide *)\n    apply_binop_int_operant_exists.\n    destruct HZ; subst. destruct H7; subst. destruct H7; subst.\n    apply_eval_expr_value_in_bound.\n    specialize (eval_expr_value_in_bound _ _ _ _ _ _ _ _ H14 H2 H3 H16 H H11); intros.\n    apply_divide_result_in_bound_backward; auto.\n  + (* Modulus *)\n    apply_binop_int_operant_exists.\n    destruct HZ; subst. destruct H7; subst. destruct H7; subst.\n    apply_eval_expr_value_in_bound.\n    specialize (eval_expr_value_in_bound _ _ _ _ _ _ _ _ H14 H2 H3 H16 H H11); intros.\n    apply_modulus_result_in_bound_backward; auto.\n  + (* Logic Operator *)\n  inversion H31; smack.\n- (** E_Unary_Operation_X *)\n  inversion H0; subst;\n  inversion H3; subst;\n  inversion H4; subst;\n  inversion H5; subst;\n  match goal with\n  | [H: forall (st : symTab) (st' : symTabRT) \n        (s : STACK.state) (e' e'' : expRT) (eBound : bound)\n        (v : Ret value),\n      toExpRT st ?e e' ->\n      toSymTabRT st st' ->\n      well_typed_stack st' s ->\n      well_typed_exp_x st' e' ->\n      optExp st' e' (e'', eBound) ->\n      evalExpRT st' s e'' v -> evalExpRT st' s e' v,\n     H1: toExpRT ?st ?e ?e',\n     H2: toSymTabRT ?st ?st',\n     H3: well_typed_stack ?st' ?s,\n     H4: well_typed_exp_x ?st' ?e',\n     H5: optExp ?st' _ (?e'', _),\n     H6: evalExpRT ?st' ?s ?e'' ?v |- _] => specialize (H _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6)\n  end;\n  [ apply EvalUnOpRT_RTE; auto | |\n    apply EvalUnOpRT_RTE; auto | ];\n  apply EvalUnOpRT with (v:=v0); auto.\n  + \n    inversion H20; smack.\n    inversion H18; smack.\n    destruct v0; inversion H22; smack.\n    apply_eval_expr_value_in_bound.\n    specialize (In_Bound_Unary_Minus_Compat _ _ _ HZ); intro.\n    apply_In_Bound_SubBound_Trans; auto.\n    apply Do_Checks_Unop with (v':=(Int (- n))); auto.\n    eapply OverflowCheckUnop; smack. \n    constructor; auto.\n  + inversion H21; smack.  \n- (** E_Identifier_X *)\n  inversion H; subst;\n  inversion H3; subst;\n  inversion H4; subst. assumption.\n- (** E_Indexed_Component_X *)\n  inversion H1; subst;\n  inversion H4; subst;\n  inversion H5; subst;\n  inversion H6; subst;\n  match goal with\n  | [H: forall (st : symTab) (st' : symTabRT) \n        (s : STACK.state) (n' n'' : nameRT) (nBound : bound)\n        (v : Ret value),\n      toNameRT st ?n n' ->\n      toSymTabRT st st' ->\n      well_typed_stack st' s ->\n      well_typed_name_x st' n' ->\n      optName st' n' (n'', nBound) ->\n      evalNameRT st' s n'' v -> evalNameRT st' s n' v,\n    H1: toNameRT ?st ?n ?n',\n    H2: toSymTabRT ?st ?st',\n    H3: well_typed_stack ?st' ?s,\n    H4: well_typed_name_x ?st' ?n',\n    H5: optName ?st' ?n' (?n'', _),\n    H6: evalNameRT ?st' ?s ?n'' ?v |- _] => \n      specialize (H _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6)\n  end;\n  match goal with\n  | [H: forall (st : symTab) (st' : symTabRT) \n        (s : STACK.state) (e' e'' : expRT) (eBound : bound)\n        (v : Ret value),\n      toExpRT st ?e e' ->\n      toSymTabRT st st' ->\n      well_typed_stack st' s ->\n      well_typed_exp_x st' e' ->\n      optExp st' e' (e'', eBound) ->\n      evalExpRT st' s e'' v -> evalExpRT st' s e' v,\n     H1: toExpRT ?st ?e ?e',\n     H2: toSymTabRT ?st ?st',\n     H3: well_typed_stack ?st' ?s,\n     H4: well_typed_exp_x ?st' ?e',\n     H5: optExp ?st' ?e' (?e'', _),\n     H6: evalExpRT ?st' ?s ?e'' ?v |- _] => specialize (H _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6)\n  | _ => idtac\n  end.\n  + apply EvalIndexedComponentRTX_RTE; auto.\n  + apply EvalIndexedComponentRTE_RTE with (a:=a0); auto.\n    apply_well_typed_exp_preserve.\n    apply_eval_expr_value_reserve_backward.\n    specialize (optimize_exp_ex_cks_stripped _ _ _ _ _ H22); intro HZ1.\n    apply eval_exp_ex_cks_added. \n    apply H0 with (st:=st) \n                  (e'':=update_exterior_checks_exp e' (exp_exterior_checks eRT)) \n                  (eBound:=Interval u v0); smack.\n    apply eval_exp_ex_cks_added; auto.\n  + apply_well_typed_exp_preserve.\n    apply_eval_expr_value_reserve_backward.\n    specialize (optimize_exp_ex_cks_stripped _ _ _ _ _ H22); intro HZ1.\n    apply EvalIndexedComponentRT_Range_RTE with (a:=a0) (i:=i) (t:=t0) (l:=l) (u:=u0); auto.\n    apply eval_exp_ex_cks_added; smack.\n    apply H0 with (st:=st) \n                  (e'':=update_exterior_checks_exp e' (exp_exterior_checks eRT)) \n                  (eBound:=Interval u v0); smack.\n    apply eval_exp_ex_cks_added; auto.\n    specialize (optimize_name_ast_num_eq _ _ _ _ H21); smack.\n    rewrite exp_updated_exterior_checks.\n    clear - H31.\n    inversion H31; subst.\n    constructor; auto.\n  + apply_well_typed_exp_preserve.\n    apply_eval_expr_value_reserve_backward.\n    specialize (optimize_exp_ex_cks_stripped _ _ _ _ _ H22); intro HZ1.\n    apply EvalIndexedComponentRT with (a:=a0) (i:=i) (t:=t0) (l:=l) (u:=u0); auto.\n    apply eval_exp_ex_cks_added; smack.\n    apply H0 with (st:=st) \n                  (e'':=update_exterior_checks_exp e' (exp_exterior_checks eRT)) \n                  (eBound:=Interval u v0); smack.    \n    apply eval_exp_ex_cks_added; auto.\n    specialize (optimize_name_ast_num_eq _ _ _ _ H21); smack.\n    rewrite exp_updated_exterior_checks.\n    specialize (optimize_exp_ex_cks_eq _ _ _ _ H22); intro HZZ1.\n    rewrite exp_updated_exterior_checks in HZZ1.\n    inversion H25; smack.\n    specialize (optimize_name_ast_num_eq _ _ _ _ H21); smack.\n    match goal with\n    | [H1: fetch_exp_type_rt ?x1 _ = fetch_exp_type_rt ?x2 _,\n       H2: fetch_exp_type_rt ?x1 _ = Some _,\n       H3: fetch_exp_type_rt ?x2 _ = Some _ |- _ ] => rewrite H2 in H1; rewrite H3 in H1; inversion H1; subst\n    end.\n    apply_extract_array_index_range_rt_unique; subst.\n    assert(HZZ2: evalExpRT st' s (update_exterior_checks_exp e' (exp_exterior_checks eRT)) (OK (Int i))). \n    apply eval_exp_ex_cks_added; auto.\n    specialize (H0 _ _ _ _ _ _ _ H12 H2 H3 HZ HZ1 HZZ2). \n    apply_eval_expr_value_in_bound.\n    apply_optimize_range_check_backward; auto.\n- (** E_Selected_Component_X *)\n  inversion H0; subst;\n  inversion H3; subst;\n  inversion H4; subst;\n  inversion H5; subst;\n  match goal with\n  | [H: forall (st : symTab) (st' : symTabRT) \n        (s : STACK.state) (n' n'' : nameRT) (nBound : bound)\n        (v : Ret value),\n      toNameRT st ?n n' ->\n      toSymTabRT st st' ->\n      well_typed_stack st' s ->\n      well_typed_name_x st' n' ->\n      optName st' n' (n'', nBound) ->\n      evalNameRT st' s n'' v -> evalNameRT st' s n' v,\n    H1: toNameRT ?st ?n ?n',\n    H2: toSymTabRT ?st ?st',\n    H3: well_typed_stack ?st' ?s,\n    H4: well_typed_name_x ?st' ?n',\n    H5: optName ?st' ?n' (?n'', _),\n    H6: evalNameRT ?st' ?s ?n'' ?v |- _] => \n      specialize (H _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6)\n  end.\n  + apply EvalSelectedComponentRTX_RTE; auto.\n  + apply EvalSelectedComponentRT with (r:=r); auto.    \nQed.  \n\nLtac apply_optExp_soundness :=\n  match goal with\n  | [H1: toExpRT ?st ?e ?e',\n     H2: toSymTabRT ?st ?st',\n     H3: well_typed_stack ?st' ?s,\n     H4: well_typed_exp_x ?st' ?e',\n     H5: optExp ?st' ?e' (?e'', _),\n     H6: evalExpRT ?st' ?s ?e'' ?v |- _] => \n      specialize (optExp_soundness _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6);\n      let HZ := fresh \"HZ\" in\n      intro HZ\n  | [H1: well_typed_stack_and_symboltable ?st' ?s |- _] => \n      inversion H1; subst; apply_well_typed_stack_infer;\n      match goal with\n      | [H1: toExpRT ?st ?e ?e',\n         H2: toSymTabRT ?st ?st',\n         H3: well_typed_stack ?st' ?s,\n         H4: well_typed_exp_x ?st' ?e',\n         H5: optExp ?st' ?e' (?e'', _),\n         H6: evalExpRT ?st' ?s ?e'' ?v |- _] => \n          specialize (optExp_soundness _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6);\n      let HZ := fresh \"HZ\" in\n      intro HZ\n      end\n  end.\n\n\n(** ** optName_soundness *)\n\nLemma optName_soundness: forall n st st' s n' n'' nBound v, \n  toNameRT st n n' ->\n    toSymTabRT st st' ->\n      well_typed_stack st' s ->\n        well_typed_name_x st' n' ->\n          optName st' n' (n'', nBound) ->\n            evalNameRT st' s n'' v ->\n              evalNameRT st' s n' v.\nProof.\n  induction n; intros.\n- (** E_Identifier_X *)\n  inversion H; subst;\n  inversion H3; subst;\n  inversion H4; subst. assumption.\n- (** E_Indexed_Component_X *)\n  inversion H; subst;\n  inversion H2; subst;\n  inversion H3; subst;\n  inversion H4; subst;\n  match goal with\n  | [H: forall (st : symTab) (st' : symTabRT) \n        (s : STACK.state) (n' n'' : nameRT) (nBound : bound)\n        (v : Ret value),\n      toNameRT st ?n n' ->\n      toSymTabRT st st' ->\n      well_typed_stack st' s ->\n      well_typed_name_x st' n' ->\n      optName st' n' (n'', nBound) ->\n      evalNameRT st' s n'' v -> evalNameRT st' s n' v,\n    H1: toNameRT ?st ?n ?n',\n    H2: toSymTabRT ?st ?st',\n    H3: well_typed_stack ?st' ?s,\n    H4: well_typed_name_x ?st' ?n',\n    H5: optName ?st' ?n' (?n'', _),\n    H6: evalNameRT ?st' ?s ?n'' ?v |- _] => \n      specialize (H _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6)\n  end.\n  + apply EvalIndexedComponentRTX_RTE; auto.\n  + apply EvalIndexedComponentRTE_RTE with (a:=a0); auto.\n    apply_well_typed_exp_preserve.\n    apply_eval_expr_value_reserve_backward.\n    specialize (optimize_exp_ex_cks_stripped _ _ _ _ _ H20); intro HZ1.\n    apply eval_exp_ex_cks_added. \n    apply optExp_soundness with (e:=e) (st:=st) \n        (e'':=update_exterior_checks_exp e' (exp_exterior_checks eRT)) (eBound:=Interval u v0); auto.\n    apply eval_exp_ex_cks_added; auto.\n  + apply_well_typed_exp_preserve.\n    apply_eval_expr_value_reserve_backward.\n    specialize (optimize_exp_ex_cks_stripped _ _ _ _ _ H20); intro HZ1.\n    apply EvalIndexedComponentRT_Range_RTE with (a:=a0) (i:=i) (t:=t0) (l:=l) (u:=u0); auto.\n    apply eval_exp_ex_cks_added; smack.\n    apply optExp_soundness with (e:=e) (st:=st) \n        (e'':=update_exterior_checks_exp e' (exp_exterior_checks eRT)) (eBound:=Interval u v0); auto.\n    apply eval_exp_ex_cks_added; auto.\n    specialize (optimize_name_ast_num_eq _ _ _ _ H19); smack.\n    rewrite exp_updated_exterior_checks.\n    clear - H29.\n    inversion H29; subst.\n    constructor; auto.\n  + apply_well_typed_exp_preserve.\n    apply_eval_expr_value_reserve_backward.\n    specialize (optimize_exp_ex_cks_stripped _ _ _ _ _ H20); intro HZ1.\n    apply EvalIndexedComponentRT with (a:=a0) (i:=i) (t:=t0) (l:=l) (u:=u0); auto.\n    apply eval_exp_ex_cks_added; smack.\n    apply optExp_soundness with (e:=e) (st:=st) \n        (e'':=update_exterior_checks_exp e' (exp_exterior_checks eRT)) (eBound:=Interval u v0); auto.\n    apply eval_exp_ex_cks_added; auto.\n    specialize (optimize_name_ast_num_eq _ _ _ _ H19); smack.\n    rewrite exp_updated_exterior_checks.\n    specialize (optimize_exp_ex_cks_eq _ _ _ _ H20); intro HZZ1.\n    rewrite exp_updated_exterior_checks in HZZ1.\n    inversion H23; smack.\n    specialize (optimize_name_ast_num_eq _ _ _ _ H19); smack.\n    match goal with\n    | [H1: fetch_exp_type_rt ?x1 _ = fetch_exp_type_rt ?x2 _,\n       H2: fetch_exp_type_rt ?x1 _ = Some _,\n       H3: fetch_exp_type_rt ?x2 _ = Some _ |- _ ] => rewrite H2 in H1; rewrite H3 in H1; inversion H1; subst\n    end.\n    apply_extract_array_index_range_rt_unique; subst.\n    assert(HZZ2: evalExpRT st' s (update_exterior_checks_exp e' (exp_exterior_checks eRT)) (OK (Int i))). \n    apply eval_exp_ex_cks_added; auto.\n    apply_optExp_soundness.\n    apply_eval_expr_value_in_bound.\n    apply_optimize_range_check_backward; auto.\n- (** E_Selected_Component_X *)\n  inversion H; subst;\n  inversion H2; subst;\n  inversion H3; subst;\n  inversion H4; subst;\n  match goal with\n  | [H: forall (st : symTab) (st' : symTabRT) \n        (s : STACK.state) (n' n'' : nameRT) (nBound : bound)\n        (v : Ret value),\n      toNameRT st ?n n' ->\n      toSymTabRT st st' ->\n      well_typed_stack st' s ->\n      well_typed_name_x st' n' ->\n      optName st' n' (n'', nBound) ->\n      evalNameRT st' s n'' v -> evalNameRT st' s n' v,\n    H1: toNameRT ?st ?n ?n',\n    H2: toSymTabRT ?st ?st',\n    H3: well_typed_stack ?st' ?s,\n    H4: well_typed_name_x ?st' ?n',\n    H5: optName ?st' ?n' (?n'', _),\n    H6: evalNameRT ?st' ?s ?n'' ?v |- _] => \n      specialize (H _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6)\n  end.\n  + apply EvalSelectedComponentRTX_RTE; auto.\n  + apply EvalSelectedComponentRT with (r:=r); auto.   \nQed.\n\nLtac apply_optName_soundness := \n  match goal with\n  | [H1: toNameRT ?st ?n ?n',\n     H2: toSymTabRT ?st ?st',\n     H3: well_typed_stack ?st' ?s,\n     H4: well_typed_name_x ?st' ?n',\n     H5: optName ?st' ?n' (?n'', _),\n     H6: evalNameRT ?st' ?s ?n'' ?v |- _] =>\n      specialize (optName_soundness _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6);\n      let HZ := fresh \"HZ\" in\n      intro HZ\n  | [H1: well_typed_stack_and_symboltable ?st' ?s |- _] => \n      inversion H1; subst; apply_well_typed_stack_infer;\n      match goal with\n      | [H1: toNameRT ?st ?n ?n',\n         H2: toSymTabRT ?st ?st',\n         H3: well_typed_stack ?st' ?s,\n         H4: well_typed_name_x ?st' ?n',\n         H5: optName ?st' ?n' (?n'', _),\n         H6: evalNameRT ?st' ?s ?n'' ?v |- _] =>\n           specialize (optName_soundness _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6);\n           let HZ := fresh \"HZ\" in\n           intro HZ\n      end\n  end.\n\n(** ** storeUpdateRT_opt_soundness *)\nLemma storeUpdateRT_opt_soundness: forall n st st' s s' n' n'' nBound v, \n  toNameRT st n n' ->\n    toSymTabRT st st' ->\n      well_typed_stack st' s ->\n        well_typed_name_x st' n' ->\n          optName st' n' (n'', nBound) ->\n            storeUpdateRT st' s n'' v s' ->\n              storeUpdateRT st' s n' v s'.\nProof.\n  induction n; intros.\n- inversion H; subst;\n  inversion H3; smack.\n- inversion H; subst;\n  inversion H2; subst;\n  inversion H3; subst;\n  inversion H4; subst.\n  + apply SU_Indexed_Component_xRTE_X; auto.\n    apply_optName_soundness; auto.\n  + apply SU_Indexed_Component_eRTE_X with (a:=a0); auto.\n    destruct H26; apply_optName_soundness; auto.\n    apply_eval_expr_value_reserve_backward.\n    apply_well_typed_exp_preserve.\n    specialize (optimize_exp_ex_cks_stripped _ _ _ _ _ H20); intro HZ1.\n    apply eval_exp_ex_cks_added.\n    apply optExp_soundness with (e:=e) (st:=st) \n        (e'':=update_exterior_checks_exp e' (exp_exterior_checks eRT)) (eBound:=Interval u v0); auto.\n    apply eval_exp_ex_cks_added; auto.\n  + apply_well_typed_exp_preserve.\n    apply_eval_expr_value_reserve_backward.\n    specialize (optimize_exp_ex_cks_stripped _ _ _ _ _ H20); intro HZ1.\n    apply SU_Indexed_Component_Range_RTE_X with (a:=a0) (i:=i) (t:=t1) (l:=l) (u:=u0); auto.\n    destruct H12; apply_optName_soundness; auto.\n    apply eval_exp_ex_cks_added; auto.\n    apply optExp_soundness with (e:=e) (st:=st) \n        (e'':=update_exterior_checks_exp e' (exp_exterior_checks eRT)) (eBound:=Interval u v0); auto.\n    apply eval_exp_ex_cks_added; auto.    \n    specialize (optimize_name_ast_num_eq _ _ _ _ H19); smack.\n    rewrite exp_updated_exterior_checks.\n    inversion H30; smack.   \n  + apply_well_typed_exp_preserve.\n    apply_eval_expr_value_reserve_backward.\n    specialize (optimize_exp_ex_cks_stripped _ _ _ _ _ H20); intro HZ1.\n    apply_optName_soundness; auto.\n    assert(HZZ1: evalExpRT st' s (update_exterior_checks_exp e' (exp_exterior_checks eRT)) (OK (Int i))). apply eval_exp_ex_cks_added; auto.\n    apply_optExp_soundness.\n    specialize (optimize_name_ast_num_eq _ _ _ _ H19); intro HZ5.\n    match goal with\n    | [H1: fetch_exp_type_rt ?x1 _ = fetch_exp_type_rt ?x2 _,\n       H2: fetch_exp_type_rt ?x1 _ = Some _,\n       H3: fetch_exp_type_rt ?x2 _ = Some _ |- _ ] => rewrite H2 in H1; rewrite H3 in H1; inversion H1; subst\n    end.\n    apply_extract_array_index_range_rt_unique; subst.\n    specialize (optimize_exp_ex_cks_eq _ _ _ _ H20); intros HZ7.\n    rewrite exp_updated_exterior_checks in *.\n    rewrite <- HZ7 in *.\n\n    destruct H17; subst;\n    [ apply SU_Indexed_Component_X with \n        (arrObj:=(ArrayV a0)) (a:=a0) (i:=i) (l:=l) (u:=u0) (t:=t1) (a1:=a1); smack | \n      apply SU_Indexed_Component_X with \n        (arrObj:=Undefined) (i:=i) (a:=nil) (l:=l) (u:=u0) (t:=t1) (a1:=a1); smack\n    ];\n    [apply eval_exp_ex_cks_added; auto | | apply eval_exp_ex_cks_added; auto | ];\n    rewrite exp_updated_exterior_checks;\n    apply_eval_expr_value_in_bound;\n    apply_optimize_range_check_backward; auto.\n- inversion H; subst;\n  inversion H2; subst;\n  inversion H3; subst;\n  inversion H4; subst.\n  + apply_optName_soundness;\n    apply SU_Selected_Component_xRTE_X; smack.\n  + destruct H23;\n    [ apply SU_Selected_Component_X with \n        (recObj:=(RecordV r)) (r:=r) (r1:=(updateSelectedComp r i v)); smack |\n      apply SU_Selected_Component_X with \n        (recObj:=Undefined) (r:=nil) (r1:=((i, v) :: nil)); smack\n    ];\n    apply_optName_soundness; auto.\nQed.\n \nLtac apply_storeUpdateRT_opt_soundness := \n  match goal with\n  | [H1: toNameRT ?st ?n ?n' ,\n     H2: toSymTabRT ?st ?st' ,\n     H3: well_typed_stack ?st' ?s ,\n     H4: well_typed_name_x ?st' ?n' ,\n     H5: optName ?st' ?n' (?n'', _) ,\n     H6: storeUpdateRT ?st' ?s ?n'' ?v ?s' |- _] =>\n      specialize (storeUpdateRT_opt_soundness _ _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6);\n      let HZ := fresh \"HZ\" in\n      intro HZ\n  | [H1: well_typed_stack_and_symboltable ?st' ?s |- _] => \n      inversion H1; subst; apply_well_typed_stack_infer;\n      match goal with\n      | [H1: toNameRT ?st ?n ?n' ,\n         H2: toSymTabRT ?st ?st' ,\n         H3: well_typed_stack ?st' ?s ,\n         H4: well_typed_name_x ?st' ?n' ,\n         H5: optName ?st' ?n' (?n'', _) ,\n         H6: storeUpdateRT ?st' ?s ?n'' ?v ?s' |- _] =>\n            specialize (storeUpdateRT_opt_soundness _ _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6);\n            let HZ := fresh \"HZ\" in\n            intro HZ\n        end\n  end.\n\n(** ** optArgs_copyin_soundness *)\nLemma optArgs_copyin_soundness: forall st params args args' st' s f f' params' args'',\n  toArgsRT st params args args' ->\n  toSymTabRT st st' ->\n  toParamSpecsRT params params' ->\n  well_typed_stack_and_symboltable st' s ->\n  well_typed_exps_x st' args' ->\n  optArgs st' params' args' args'' ->\n  copyInRT st' s f params' args'' f' ->\n  copyInRT st' s f params' args' f'.\nProof.\n intros st params args args' st' s f f' params' args'' H.\n revert st' s f f' params' args''.\n induction H; intros.\n- (* C2_Flagged_Args_Null *)\n inversion H0; subst.\n inversion H3; subst; auto.\n- (* C2_Flagged_Args_In *)\n inversion H4; subst;\n inversion H6; subst.\n assert(HZ: param.(parameter_mode) = paramRT.(parameter_mode_rt)).\n  clear - H11. inversion H11; smack.\n assert(HZ1: (parameter_subtype_mark param) = (parameter_subtype_mark_rt paramRT)).\n  clear - H11. inversion H11; smack.\n\n inversion H7; subst;\n inversion H8; subst;\n  match goal with\n  | [H1: parameter_mode ?p = parameter_mode_rt ?a,\n     H2: parameter_mode ?p = _ ,\n     H3: parameter_mode_rt ?a = _,\n     H4: parameter_mode_rt ?a = _ |- _] => \n      rewrite H2 in H1; rewrite H3 in H1; inversion H1; rewrite H3 in H4; inversion H4\n  end;\n  match goal with\n  | [H: extract_subtype_range_rt _ _ (RangeRT _ _) |- _] => \n      specialize (range_constrainted_type_true _ _ _ _ H);\n      let HZ := fresh \"HZ\" in intros HZ\n  | _ => idtac\n  end;\n  match goal with\n  | [H1: is_range_constrainted_type ?x = false, \n     H2: is_range_constrainted_type ?y = true,\n     H3: ?x = ?y |- _] => \n      rewrite H3 in H1; rewrite H1 in H2; inversion H2\n  | _ => idtac\n  end;\n apply_optExp_soundness; auto.\n apply CopyIn_Mode_In_eRTE_X; auto.\n\n apply CopyIn_Mode_In_NoRangeCheck_X \n   with (v:=v) (f':=(STACK.push f (parameter_nameRT paramRT) v)); smack.\n apply exp_exterior_checks_beq_nil with (st:=st) (e:=arg); auto.\n- (* C2_Flagged_Args_In_RangeCheck *)\n inversion H4; subst;\n inversion H6; subst.\n assert(HZ: param.(parameter_mode) = paramRT.(parameter_mode_rt)).\n  clear - H11. inversion H11; smack.\n assert(HZ1: (parameter_subtype_mark param) = (parameter_subtype_mark_rt paramRT)).\n  clear - H11. inversion H11; smack.\n apply_well_typed_exp_preserve.\n inversion H7; subst;\n inversion H8; subst;\n  match goal with\n  | [H1: parameter_mode ?p = parameter_mode_rt ?a,\n     H2: parameter_mode ?p = _ ,\n     H3: parameter_mode_rt ?a = _,\n     H4: parameter_mode_rt ?a = _ |- _] => \n      rewrite H2 in H1; rewrite H3 in H1; inversion H1; rewrite H3 in H4; inversion H4\n  end;\n  match goal with\n  | [H: extract_subtype_range_rt _ _ (RangeRT _ _) |- _] => \n      specialize (range_constrainted_type_true _ _ _ _ H);\n      let HZ := fresh \"HZ\" in intros HZ\n  | _ => idtac\n  end;\n  match goal with\n  | [H1: is_range_constrainted_type ?x = false, \n     H2: is_range_constrainted_type ?x = true |- _] => \n      rewrite H2 in H1; inversion H1\n  | _ => idtac\n  end;\n  smack.\n (* case: CopyIn_Mode_In_eRTE_X: eval arg => RTE *)\n apply CopyIn_Mode_In_eRTE_X; auto.\n apply eval_exp_ex_cks_added; auto.\n apply_eval_expr_value_reserve_backward.\n specialize (optimize_exp_ex_cks_stripped _ _ _ _ _ H20); intro HZ4.\n specialize (eval_exp_ex_cks_added _ _ _ _ (exp_exterior_checks argRT) HZ3); intros HZ5.\n \n apply_optExp_soundness; auto.\n (* case: CopyIn_Mode_In_NoRangeCheck_X: eval arg => OK v, optimize the range check *)\n apply_eval_expr_value_reserve_backward.\n specialize (optimize_exp_ex_cks_stripped _ _ _ _ _ H20); intro HZ4.\n specialize (eval_exp_ex_cks_added _ _ _ _ (exp_exterior_checks argRT) HZ3); intros HZ5.\n apply_optExp_soundness; auto.\n apply_optimize_expression_exist_int_value.\n apply CopyIn_Mode_In_Range_X \n   with (v:=v1) (l:=u) (u:=v) (f':=(STACK.push f (parameter_nameRT paramRT) (Int v1))); smack.\n apply eval_exp_ex_cks_added; auto. \n rewrite exp_updated_exterior_checks; auto.\n apply_eval_expr_value_in_bound.\n specialize (optimize_exp_ex_cks_eq _ _ _ _ H20); let HZ := fresh \"HZ\" in intro HZ.\n rewrite exp_updated_exterior_checks in HZ9.\n inversion H22; smack.\n apply_In_Bound_SubBound_Trans. constructor; auto.\n (* case:  CopyIn_Mode_In_Range_RTE_X *)\n apply_eval_expr_value_reserve_backward.\n specialize (optimize_exp_ex_cks_stripped _ _ _ _ _ H20); intro HZ4.\n specialize (eval_exp_ex_cks_added _ _ _ _ (exp_exterior_checks argRT) HZ3); intros HZ5.\n apply_optExp_soundness; auto.\n apply CopyIn_Mode_In_Range_RTE_X with (v:=v0) (l:=u) (u:=v); smack.\n apply eval_exp_ex_cks_added; auto. \n rewrite exp_updated_exterior_checks; auto.\n apply_extract_subtype_range_unique; subst. auto.\n (* case:  CopyIn_Mode_In_Range_X *)\n apply_eval_expr_value_reserve_backward.\n specialize (optimize_exp_ex_cks_stripped _ _ _ _ _ H20); intro HZ4.\n specialize (eval_exp_ex_cks_added _ _ _ _ (exp_exterior_checks argRT) HZ3); intros HZ5.\n apply_optExp_soundness; auto.\n apply CopyIn_Mode_In_Range_X \n   with (v:=v0) (l:=u) (u:=v) (f':=(STACK.push f (parameter_nameRT paramRT) (Int v0))); smack.\n apply eval_exp_ex_cks_added; auto. \n rewrite exp_updated_exterior_checks; auto.\n apply_extract_subtype_range_unique; subst. auto. \n-(* C2_Flagged_Args_Out *)\n inversion H5; subst;\n inversion H7; subst.\n assert(HZ: param.(parameter_mode) = paramRT.(parameter_mode_rt)).\n  clear - H12. inversion H12; smack.\n assert(HZ1: (parameter_subtype_mark param) = (parameter_subtype_mark_rt paramRT)).\n  clear - H12. inversion H12; smack.\n inversion H8; subst;\n inversion H9; subst;\n  match goal with\n  | [H1: parameter_mode ?p = parameter_mode_rt ?a,\n     H2: parameter_mode ?p = _ ,\n     H3: parameter_mode_rt ?a = _,\n     H4: parameter_mode_rt ?a = _ |- _] => \n      rewrite H2 in H1; rewrite H3 in H1; inversion H1; rewrite H3 in H4; inversion H4\n  end;\n  match goal with\n  | [H: extract_subtype_range_rt _ _ (RangeRT _ _) |- _] => \n      specialize (range_constrainted_type_true _ _ _ _ H);\n      let HZ := fresh \"HZ\" in intros HZ\n  | _ => idtac\n  end;\n  match goal with\n  | [H1: is_range_constrainted_type ?x = false, \n     H2: is_range_constrainted_type ?y = true,\n     H3: ?x = ?y |- _] => \n      rewrite H3 in H1; rewrite H1 in H2; inversion H2\n  | _ => idtac\n  end;\n apply CopyIn_Mode_Out_X with (f' := (STACK.push f (parameter_nameRT paramRT) Undefined)); auto;\n apply IHtoArgsRT with (args'' := args'); smack. \n-(* C2_Flagged_Args_Out_RangeCheck, the proof is the same as C2_Flagged_Args_Out, \n    as the mode is out, so copyInRT is the same constructor: CopyIn_Mode_Out_X. *)\n inversion H5; subst;\n inversion H7; subst.\n assert(HZ: param.(parameter_mode) = paramRT.(parameter_mode_rt)).\n  clear - H12. inversion H12; smack.\n assert(HZ1: (parameter_subtype_mark param) = (parameter_subtype_mark_rt paramRT)).\n  clear - H12. inversion H12; smack.\n inversion H8; subst;\n inversion H9; subst;\n  match goal with\n  | [H1: parameter_mode ?p = parameter_mode_rt ?a,\n     H2: parameter_mode ?p = _ ,\n     H3: parameter_mode_rt ?a = _,\n     H4: parameter_mode_rt ?a = _ |- _] => \n      rewrite H2 in H1; rewrite H3 in H1; inversion H1; rewrite H3 in H4; inversion H4\n  end;\n  match goal with\n  | [H: extract_subtype_range_rt _ _ (RangeRT _ _) |- _] => \n      specialize (range_constrainted_type_true _ _ _ _ H);\n      let HZ := fresh \"HZ\" in intros HZ\n  | _ => idtac\n  end;\n  match goal with\n  | [H1: is_range_constrainted_type ?x = false, \n     H2: is_range_constrainted_type ?y = true,\n     H3: ?x = ?y |- _] => \n      rewrite H3 in H1; rewrite H1 in H2; inversion H2\n  | _ => idtac\n  end;\n apply CopyIn_Mode_Out_X with (f' := (STACK.push f (parameter_nameRT paramRT) Undefined)); auto;\n apply IHtoArgsRT with (args'' := args'); smack. \n-(* C2_Flagged_Args_InOut *)\n inversion H6; subst;\n inversion H8; subst.\n assert(HZ: param.(parameter_mode) = paramRT.(parameter_mode_rt)).\n  clear - H13. inversion H13; smack.\n assert(HZ1: (parameter_subtype_mark param) = (parameter_subtype_mark_rt paramRT)).\n  clear - H13. inversion H13; smack.\n assert (HA1: name_exterior_checks nRT = nil).\n   apply name_exterior_checks_beq_nil with (st:=st) (n:=nm); auto. \n match goal with\n | [H: well_typed_exp_x _ (NameRT _ _) |- _] => inversion H; subst\n end;\n inversion H9; subst;\n inversion H10; subst;\n  match goal with\n  | [H1: parameter_mode ?p = parameter_mode_rt ?a,\n     H2: parameter_mode ?p = _ ,\n     H3: parameter_mode_rt ?a = _,\n     H4: parameter_mode_rt ?a = _ |- _] => \n      rewrite H2 in H1; rewrite H3 in H1; inversion H1; rewrite H3 in H4; inversion H4\n  end;\n  match goal with\n  | [H: extract_subtype_range_rt _ _ (RangeRT _ _) |- _] => \n      specialize (range_constrainted_type_true _ _ _ _ H);\n      let HZ := fresh \"HZ\" in intros HZ\n  | _ => idtac\n  end;\n  match goal with\n  | [H1: is_range_constrainted_type ?x = false, \n     H2: is_range_constrainted_type ?y = true,\n     H3: ?x = ?y |- _] => \n      rewrite H3 in H1; rewrite H1 in H2; inversion H2\n  | _ => idtac\n  end;\n  (* conflict: range constraint is both true and false for argument type *)\n  match goal with\n  | [H1: toSymTabRT ?st ?st',\n     H2: fetch_exp_type _ ?st = _ |- _ ] => \n      specialize (symbol_table_exp_type_rel _ _ _ _ H1 H2);\n      let HZ := fresh \"HZ\" in intros HZ\n  | _ => idtac\n  end;\n  match goal with\n  | [H1: fetch_exp_type_rt ?x ?st = Some _, \n     H2: fetch_exp_type_rt ?x ?st = Some _ |- _] => rewrite H1 in H2; inversion H2; subst\n  | _ => idtac\n  end;\n  match goal with\n  | [H1: is_range_constrainted_type ?x = false, \n     H2: is_range_constrainted_type ?x = true |- _] => \n      rewrite H1 in H2; inversion H2\n  | _ => idtac\n  end;\n apply_optName_soundness; auto;\n [apply CopyIn_Mode_InOut_eRTE_X; auto | \n  apply CopyIn_Mode_InOut_NoRange_X with (v := v) (f' := (STACK.push f (parameter_nameRT paramRT) v)); auto;\n  [ clear - HA1; destruct (name_exterior_checks nRT); smack | \n    apply IHtoArgsRT with (args'' := args'); smack]].\n-(* C2_Flagged_Args_InOut_In_RangeCheck *)\n inversion H6; subst;\n inversion H8; subst.\n assert(HZ: param.(parameter_mode) = paramRT.(parameter_mode_rt)).\n  clear - H13. inversion H13; smack.\n assert(HZ1: (parameter_subtype_mark param) = (parameter_subtype_mark_rt paramRT)).\n  clear - H13. inversion H13; smack.\n assert (HA1: name_exterior_checks nRT = nil). \n   apply name_exterior_checks_beq_nil with (st:=st) (n:=nm); auto. \n match goal with\n | [H: well_typed_exp_x _ (NameRT _ _) |- _] => inversion H; subst\n end;\n (* apply_well_typed_name_preserve. *)\n inversion H9; subst;\n inversion H10; subst;\n  match goal with\n  | [H1: parameter_mode ?p = parameter_mode_rt ?a,\n     H2: parameter_mode ?p = _ ,\n     H3: parameter_mode_rt ?a = _,\n     H4: parameter_mode_rt ?a = _ |- _] => \n      rewrite H2 in H1; rewrite H3 in H1; inversion H1; rewrite H3 in H4; inversion H4\n  end;\n  match goal with\n  | [H: extract_subtype_range_rt _ _ (RangeRT _ _) |- _] => \n      specialize (range_constrainted_type_true _ _ _ _ H);\n      let HZ := fresh \"HZ\" in intros HZ\n  | _ => idtac\n  end;\n  match goal with\n  | [H1: is_range_constrainted_type ?x = false, \n     H2: is_range_constrainted_type ?x = true |- _] => \n      rewrite H2 in H1; inversion H1; auto\n  | _ => idtac\n  end;\n  (* conflict: range constraint is both true and false for argument type *)\n  match goal with\n  | [H1: toSymTabRT ?st ?st',\n     H2: fetch_exp_type _ ?st = _ |- _ ] => \n      specialize (symbol_table_exp_type_rel _ _ _ _ H1 H2);\n      let HZ := fresh \"HZ\" in intros HZ\n  | _ => idtac\n  end;\n  match goal with\n  | [H1: fetch_exp_type_rt ?x ?st = Some _, \n     H2: fetch_exp_type_rt ?x ?st = Some _ |- _] => rewrite H1 in H2; inversion H2; subst\n  | _ => idtac\n  end;\n  match goal with\n  | [H1: fetch_exp_type_rt ?astnum ?st' = Some ?t0,\n     H2: extract_subtype_range_rt _ ?t0 (RangeRT _ _) |- _] => \n      specialize (range_constrainted_type_true _ _ _ _ H2);\n      let HZ := fresh \"HZ\" in intros HZ\n  | _ => idtac\n  end;\n  match goal with\n  | [H1: is_range_constrainted_type ?x = false, \n     H2: is_range_constrainted_type ?x = true |- _] => \n      rewrite H1 in H2; inversion H2\n  | _ => idtac\n  end.\n (* case: CopyIn_Mode_InOut_eRTE_X: eval arg => RTE *)\n apply CopyIn_Mode_InOut_eRTE_X; auto.\n apply eval_name_ex_cks_added; auto.\n apply_well_typed_name_preserve.\n match goal with\n | [H: optName _ (update_exterior_checks_name _ _) _ |- _] =>\n     specialize (optimize_name_ex_cks_stripped _ _ _ _ _ H); \n     let HZ := fresh \"HZ\" in intros HZ\n | _ => idtac\n end.\n apply optName_soundness \n    with (n:=nm) (st:=st) (n'':=update_exterior_checks_name n' (name_exterior_checks nRT)) (nBound:=nBound); auto.\n inversion H7; subst; apply_well_typed_stack_infer; auto.\n apply eval_name_ex_cks_added; auto.   \n (* case: CopyIn_Mode_InOut_NoRange_X: eval arg => OK v, optimize the range check *)\n (* conflict: n' has Do_Range_Check and n' has no range check *)\n apply_optimize_name_ex_cks_eq.\n rewrite name_updated_exterior_checks in HZ2.\n match goal with\n | [H1: ~ List.In RangeCheck (name_exterior_checks ?n'),\n    H2: name_exterior_checks ?n' = RangeCheck :: nil |- _] => rewrite H2 in H1; clear -H1; smack\n end.\n (* case: CopyIn_Mode_InOut_Range_RTE_X *)\n apply_well_typed_name_preserve.\n specialize (optimize_name_ex_cks_stripped _ _ _ _ _ H27); intro HZ4.\n specialize (eval_name_ex_cks_added _ _ _ _ (name_exterior_checks nRT) H31); intros HZ5.\n apply_optName_soundness; auto.\n apply CopyIn_Mode_InOut_Range_RTE_X with (v:=v) (l:=l) (u:=u); auto.\n apply eval_name_ex_cks_added; auto.\n rewrite name_updated_exterior_checks; smack.\n (* case: CopyIn_Mode_InOut_Range_X *)\n apply_well_typed_name_preserve.\n specialize (optimize_name_ex_cks_stripped _ _ _ _ _ H27); intro HZ4.\n specialize (eval_name_ex_cks_added _ _ _ _ (name_exterior_checks nRT) H25); intros HZ5.\n apply_optName_soundness; auto.\n apply CopyIn_Mode_InOut_Range_X with (v:=v) (l:=l) (u:=u) (f':=(STACK.push f (parameter_nameRT paramRT) (Int v))); auto.\n apply eval_name_ex_cks_added; auto.\n rewrite name_updated_exterior_checks; smack.\n apply IHtoArgsRT with (args'' := args'); smack.\n-(* C2_Flagged_Args_InOut_Out_RangeCheck *)\n inversion H6; subst;\n inversion H8; subst.\n assert(HZ: param.(parameter_mode) = paramRT.(parameter_mode_rt)).\n  clear - H13. inversion H13; smack.\n assert(HZ1: (parameter_subtype_mark param) = (parameter_subtype_mark_rt paramRT)).\n  clear - H13. inversion H13; smack.\n match goal with\n | [H: well_typed_exp_x _ (NameRT _ _) |- _] => inversion H; subst\n end;\n inversion H9; subst;\n inversion H10; subst;\n  match goal with\n  | [H1: parameter_mode ?p = parameter_mode_rt ?a,\n     H2: parameter_mode ?p = _ ,\n     H3: parameter_mode_rt ?a = _,\n     H4: parameter_mode_rt ?a = _ |- _] => \n      rewrite H2 in H1; rewrite H3 in H1; inversion H1; rewrite H3 in H4; inversion H4\n  end;\n  match goal with\n  | [H: extract_subtype_range_rt _ (parameter_subtype_mark_rt _) (RangeRT _ _) |- _] => \n      specialize (range_constrainted_type_true _ _ _ _ H);\n      let HZ := fresh \"HZ\" in intros HZ\n  | _ => idtac\n  end;\n  match goal with\n  | [H1: is_range_constrainted_type ?x = false, \n     H2: is_range_constrainted_type ?y = true,\n     H3: ?x = ?y |- _] => \n      rewrite H3 in H1; rewrite H1 in H2; inversion H2\n  | _ => idtac\n  end;\n apply_well_typed_name_preserve;\n specialize (optimize_name_ex_cks_stripped _ _ _ _ _ H27); intro HZ4.\n (* case 1: CopyIn_Mode_InOut_eRTE_X, where eval argument to error *)\n apply CopyIn_Mode_InOut_eRTE_X; auto.\n apply eval_name_ex_cks_added; auto.\n apply optName_soundness\n    with (n:=nm) (st:=st) (n'':=update_exterior_checks_name n' (name_exterior_checks nRT)) (nBound:=nBound); auto.\n inversion H7; subst; apply_well_typed_stack_infer; auto.\n apply eval_name_ex_cks_added; auto.\n (* case 2: CopyIn_Mode_InOut_NoRange_X *)\n apply CopyIn_Mode_InOut_NoRange_X with (v := v) (f' := (STACK.push f (parameter_nameRT paramRT) v)); auto.\n apply eval_name_ex_cks_added; auto.\n apply optName_soundness\n    with (n:=nm) (st:=st) (n'':=update_exterior_checks_name n' (name_exterior_checks nRT)) (nBound:=nBound); auto.\n inversion H7; subst; apply_well_typed_stack_infer; auto.\n apply eval_name_ex_cks_added; auto.\n rewrite name_updated_exterior_checks. smack.\n apply IHtoArgsRT with (args'' := args'); smack.\n-(* C2_Flagged_Args_InOut_RangeCheck *)\n inversion H6; subst;\n inversion H8; subst.\n assert(HZ: param.(parameter_mode) = paramRT.(parameter_mode_rt)).\n  clear - H13. inversion H13; smack.\n assert(HZ1: (parameter_subtype_mark param) = (parameter_subtype_mark_rt paramRT)).\n  clear - H13. inversion H13; smack.\n assert (HA1: name_exterior_checks nRT = nil). \n   apply name_exterior_checks_beq_nil with (st:=st) (n:=nm); auto. \n match goal with\n | [H: well_typed_exp_x _ (NameRT _ _) |- _] => inversion H; subst\n end;\n (* apply_well_typed_name_preserve. *)\n inversion H9; subst;\n inversion H10; subst;\n  match goal with\n  | [H1: parameter_mode ?p = parameter_mode_rt ?a,\n     H2: parameter_mode ?p = _ ,\n     H3: parameter_mode_rt ?a = _,\n     H4: parameter_mode_rt ?a = _ |- _] => \n      rewrite H2 in H1; rewrite H3 in H1; inversion H1; rewrite H3 in H4; inversion H4\n  end;\n  (* conflict: range constraint is both true and false for argument type *)\n  match goal with\n  | [H1: toSymTabRT ?st ?st',\n     H2: fetch_exp_type _ ?st = _ |- _ ] => \n      specialize (symbol_table_exp_type_rel _ _ _ _ H1 H2);\n      let HZ := fresh \"HZ\" in intros HZ\n  | _ => idtac\n  end;\n  match goal with\n  | [H1: fetch_exp_type_rt ?x ?st = Some _, \n     H2: fetch_exp_type_rt ?x ?st = Some _ |- _] => rewrite H1 in H2; inversion H2; subst\n  | _ => idtac\n  end;\n  match goal with\n  | [H1: is_range_constrainted_type ?param = true, \n     H2: is_range_constrainted_type ?t = true,\n     H3: ?param = ?paramRT,\n     H4: is_range_constrainted_type ?t = false \\/\n         is_range_constrainted_type ?paramRT = false |- _] => \n      rewrite H2 in H4; rewrite H3 in H1; rewrite H1 in H4; clear - H4; smack\n  | _ => idtac\n  end;\n match goal with\n | [H: optExp _ (NameRT _ _) _ |- _] => inversion H; subst\n end;\n apply_well_typed_name_preserve;\n specialize (optimize_name_ex_cks_stripped _ _ _ _ _ H14); intro HZ4.\n (* case: CopyIn_Mode_InOut_eRTE_X: eval arg => RTE *)\n apply CopyIn_Mode_InOut_eRTE_X; auto.\n apply eval_name_ex_cks_added; auto.\n assert(HA2: evalExpRT st' s  (NameRT n0 nm0) (RTE msg)). constructor; auto.\n apply_optimize_range_check_preserve_backward.\n apply optName_soundness\n    with (n:=nm) (st:=st) (n'':=update_exterior_checks_name n' (name_exterior_checks nRT)) (nBound:=Interval v1 v2); auto.\n inversion H7; subst; apply_well_typed_stack_infer; auto.\n apply eval_name_ex_cks_added; auto.\n (* case: CopyIn_Mode_InOut_NoRange_X: eval arg => OK v, optimize the range check *)\n assert(HA2: evalExpRT st' s  (NameRT n0 nm0) (OK v0)). constructor; auto.\n apply_optimize_range_check_preserve_backward.\n specialize (eval_name_ex_cks_added _ _ _ _ (name_exterior_checks nRT) HA0); intros HZ5.\n apply_optName_soundness; auto.\n apply_optimize_name_exist_int_value.\n match goal with\n | [H: optimize_range_check _ _ _ _ |- _] => inversion H; subst \n end.\n (* - subcase 1: optmize the range check *)\n apply CopyIn_Mode_InOut_Range_X with (v:=v3) (l:=u) (u:=v) (f':=(STACK.push f (parameter_nameRT paramRT) (Int v3))); auto.\n apply eval_name_ex_cks_added; auto.\n rewrite name_updated_exterior_checks; smack.\n apply_eval_name_value_in_bound.\n apply_eval_expr_value_copy_out_opt_reserve_backward.\n apply_In_Bound_SubBound_Trans. constructor; auto.\n apply IHtoArgsRT with (args'' := args'); smack.\n (* - subcase 2: not optmize the range check *)\n (* conflict: do_range_check is both in and not in the final optimized name n0 *)\n specialize (optimize_name_ex_cks_eq _ _ _ _ H14). intros HZ7.\n rewrite name_updated_exterior_checks in HZ7.\n match goal with\n | [H1: optimize_range_check_on_copy_out (NameRT n ?n') _ _ (NameRT _ ?n0),\n    H2: name_exterior_checks ?n' = RangeCheck :: _,\n    H3: ~ List.In RangeCheck (name_exterior_checks ?n0) |- _] => \n     clear - H1 H2 H3; inversion H1; subst; simpl in *; rewrite H2 in *; smack\n end.\n rewrite name_updated_exterior_checks in H35; clear - H35; smack.\n (* case: CopyIn_Mode_InOut_Range_RTE_X *)  \n assert(HA2: evalExpRT st' s  (NameRT n0 nm0) (OK (Int v0))). constructor; auto.\n apply_optimize_range_check_preserve_backward.\n specialize (eval_name_ex_cks_added _ _ _ _ (name_exterior_checks nRT) HA0); intros HZ5.\n apply_optName_soundness; auto.\n match goal with\n | [H: optimize_range_check _ _ _ _ |- _] => inversion H; subst \n end.\n (* - subcase 1: optmize the range check *)\n (* conflict: do_range_check is both in and not in the final optimized name n0 *)\n specialize (optimize_name_ex_cks_eq _ _ _ _ H14). intros HZ7.\n rewrite name_updated_exterior_checks in HZ7.\n match goal with\n | [H1: optimize_range_check_on_copy_out \n          (update_exterior_checks_exp (NameRT n n') _) _ _ (NameRT _ ?n0),\n    H2: name_exterior_checks ?n' = RangeCheck :: _,\n    H3: List.In RangeCheck (name_exterior_checks ?n0) |- _] => \n     clear - H1 H2 H3; simpl in *; rewrite H2 in H1;\n     inversion H30; smack\n end;\n match goal with\n | [H: List.In _ (name_exterior_checks _) |- _] =>\n     repeat progress rewrite name_updated_exterior_checks in H; simpl in H; smack\n end.\n (* - subcase 2: not optmize the range check *)\n  apply CopyIn_Mode_InOut_Range_RTE_X with (v:=v0) (l:=l) (u:=u0); auto.\n apply eval_name_ex_cks_added; auto.\n rewrite name_updated_exterior_checks; smack.\n (* case: CopyIn_Mode_InOut_Range_X *)\n assert(HA2: evalExpRT st' s  (NameRT n0 nm0) (OK (Int v0))). constructor; auto.\n apply_optimize_range_check_preserve_backward.\n specialize (eval_name_ex_cks_added _ _ _ _ (name_exterior_checks nRT) HA0); intros HZ5.\n apply_optName_soundness; auto.\n match goal with\n | [H: optimize_range_check _ _ _ _ |- _] => inversion H; subst \n end.\n (* - subcase 1: optmize the range check *)\n (* conflict: do_range_check is both in and not in the final optimized name n0 *)\n specialize (optimize_name_ex_cks_eq _ _ _ _ H14). intros HZ7.\n rewrite name_updated_exterior_checks in HZ7.\n match goal with\n | [H1: optimize_range_check_on_copy_out \n          (update_exterior_checks_exp (NameRT n n') _) _ _ (NameRT _ ?n0),\n    H2: name_exterior_checks ?n' = RangeCheck :: _,\n    H3: List.In RangeCheck (name_exterior_checks ?n0) |- _] => \n     clear - H1 H2 H3; simpl in *; rewrite H2 in H1;\n     inversion H30; smack\n end;\n match goal with\n | [H: List.In _ (name_exterior_checks _) |- _] =>\n     repeat progress rewrite name_updated_exterior_checks in H; simpl in H; smack\n end.\n (* - subcase 2: not optmize the range check *)\n apply CopyIn_Mode_InOut_Range_X with \n   (v:=v0) (l:=l) (u:=u0) (f':=(STACK.push f (parameter_nameRT paramRT) (Int v0))); auto.\n apply eval_name_ex_cks_added; auto.\n rewrite name_updated_exterior_checks; smack.\n apply IHtoArgsRT with (args'' := args'); smack.\nQed.\n\nLtac apply_optArgs_copyin_soundness :=\n  match goal with\n  | [H1: toArgsRT ?st ?params ?args ?args',\n     H2: toSymTabRT ?st ?st',\n     H3: toParamSpecsRT ?params ?params',\n     H4: well_typed_stack_and_symboltable ?st' ?s,\n     H5: well_typed_exps_x ?st' ?args',\n     H6: optArgs ?st' ?params' ?args' ?args'',\n     H7: copyInRT ?st' ?s ?f ?params' ?args'' ?f' |- _ ] =>\n      specialize (optArgs_copyin_soundness _ _ _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6 H7);\n      let HZ := fresh \"HZ\" in intro HZ\n  end.\n\n\n(** * Completeness of RT-OPT Specification *)\n\n(** ** optExp_completeness *)\nLemma optExp_completeness: forall e st st' s e' e'' eBound v, \n  toExpRT st e e' ->\n    toSymTabRT st st' ->\n      well_typed_stack st' s ->\n        well_typed_exp_x st' e' ->\n          optExp st' e' (e'', eBound) ->\n            evalExpRT st' s e' v ->\n              evalExpRT st' s e'' v.\nProof.\n  apply (expression_ind\n    (fun e: exp =>\n       forall (st : symTab) (st' : symTabRT) (s : STACK.state)\n              (e': expRT) (e'': expRT) (eBound: bound) (v : Ret value),\n      toExpRT st e e' ->\n      toSymTabRT st st' ->\n      well_typed_stack st' s ->\n      well_typed_exp_x st' e' ->\n      optExp st' e' (e'', eBound) ->\n      evalExpRT st' s e' v ->\n      evalExpRT st' s e'' v)\n    (fun n: name =>\n       forall (st : symTab) (st' : symTabRT) (s : STACK.state)\n              (n': nameRT) (n'': nameRT) (nBound: bound) (v : Ret value),\n      toNameRT st n n' ->\n      toSymTabRT st st' ->\n      well_typed_stack st' s ->\n      well_typed_name_x st' n' ->\n      optName st' n' (n'', nBound) ->\n      evalNameRT st' s n' v ->\n      evalNameRT st' s n'' v)\n    ); intros.\n- (** E_Literal_X *)\n  inversion H; subst;\n  inversion H3; subst;\n  inversion H4; subst;\n  constructor;\n  apply_literal_checks_optimization_soundness.\n- (** E_Name_X *)\n  inversion H0; subst;\n  inversion H3; subst;\n  inversion H4; subst;\n  inversion H5; subst.\n  specialize (H _ _ _ _ _ _ _ H10 H1 H2 H11 H8 H15). \n  constructor; auto.\n- (** E_Binary_Operation_X *)\n  inversion H1; subst;\n  inversion H4; subst;\n  inversion H5; subst;\n  inversion H6; subst;\n\n  repeat progress match goal with\n  | [H: forall (st : symTab) (st' : symTabRT) \n        (s : STACK.state) (e' e'' : expRT) (eBound : bound)\n        (v : Ret value),\n      toExpRT st ?e e' ->\n      toSymTabRT st st' ->\n      well_typed_stack st' s ->\n      well_typed_exp_x st' e' ->\n      optExp st' e' (e'', eBound) ->\n      evalExpRT st' s e' v -> evalExpRT st' s e'' v,\n     H1: toExpRT ?st ?e ?e',\n     H2: toSymTabRT ?st ?st',\n     H3: well_typed_stack ?st' ?s,\n     H4: well_typed_exp_x ?st' ?e',\n     H5: optExp ?st' ?e' _,\n     H6: evalExpRT ?st' ?s ?e' ?v |- _] => specialize (H _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6)\n  end;\n  [apply EvalBinOpRTE1_RTE; auto | | | apply EvalBinOpRTE1_RTE; auto | | | apply EvalBinOpRTE1_RTE; auto | | |\n   apply EvalBinOpRTE1_RTE; auto | | ];\n  [apply EvalBinOpRTE2_RTE with (v1:=v1); auto | | \n   apply EvalBinOpRTE2_RTE with (v1:=v1); auto | |\n   apply EvalBinOpRTE2_RTE with (v1:=v1); auto | |\n   apply EvalBinOpRTE2_RTE with (v1:=v1); auto | ];\n  apply EvalBinOpRT with (v1:=v1) (v2:=v2); auto.\n  + (* Plus | Minus | Multiply *)    \n    match goal with\n    | [H: evalBinOpRTS _ _ _ _ _ |- _] => inversion H; smack\n    end;\n    match goal with\n    | [H: evalBinOpRT _ _ _ _ _ |- _] => inversion H; smack\n    | _ => idtac\n    end;\n    destruct v1, v2; inversion H8;\n    specialize (eval_expr_value_in_bound _ _ _ _ _ _ _ _ H14 H2 H3 H17 H28 H11);\n    apply_eval_expr_value_in_bound; intros;\n    apply do_flagged_checks_on_plus_reserve with \n        (v1Bound:=e1Bound) (v2Bound:=e2Bound) (bound1:=eBound); auto.\n  + (* Divide *)\n    match goal with\n    | [H: evalBinOpRTS _ _ _ _ _ |- _] => inversion H; smack\n    end;\n    match goal with\n    | [H: evalBinOpRT _ _ _ _ _ |- _] => inversion H; smack\n    | _ => idtac\n    end;\n    specialize (eval_expr_value_in_bound _ _ _ _ _ _ _ _ H14 H2 H3 H16 H27 H11);\n    apply_eval_expr_value_in_bound; intros;\n    apply_do_flagged_checks_on_divide_reserve; auto. \n  + (* Modulus *)\n    match goal with\n    | [H: evalBinOpRTS _ _ _ _ _ |- _] => inversion H; smack\n    end;\n    match goal with\n    | [H: evalBinOpRT _ _ _ _ _ |- _] => inversion H; smack\n    | _ => idtac\n    end;\n    specialize (eval_expr_value_in_bound _ _ _ _ _ _ _ _ H14 H2 H3 H16 H27 H11);\n    apply_eval_expr_value_in_bound; intros;\n    apply_do_flagged_checks_on_modulus_reserve; auto. \n  + (* Logic Operator *)\n  inversion H31; smack.\n- (** E_Unary_Operation_X *)\n  inversion H0; subst;\n  inversion H3; subst;\n  inversion H4; subst;\n  inversion H5; subst;\n  match goal with\n  | [H: forall (st : symTab) (st' : symTabRT) \n        (s : STACK.state) (e' e'' : expRT) (eBound : bound)\n        (v : Ret value),\n      toExpRT st ?e e' ->\n      toSymTabRT st st' ->\n      well_typed_stack st' s ->\n      well_typed_exp_x st' e' ->\n      optExp st' e' (e'', eBound) ->\n      evalExpRT st' s e' v -> evalExpRT st' s e'' v,\n     H1: toExpRT ?st ?e ?e',\n     H2: toSymTabRT ?st ?st',\n     H3: well_typed_stack ?st' ?s,\n     H4: well_typed_exp_x ?st' ?e',\n     H5: optExp ?st' ?e' _,\n     H6: evalExpRT ?st' ?s ?e' ?v |- _] => specialize (H _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6)\n  end;\n  [ apply EvalUnOpRT_RTE; auto | |\n    apply EvalUnOpRT_RTE; auto | ];\n  apply EvalUnOpRT with (v:=v0); auto.\n  + match goal with\n    | [H: evalUnOpRTS _ _ _ _ |- _] => inversion H; smack\n    end;\n    match goal with\n    | [H: evalUnOpRT _ _ _ _ |- _] => inversion H; smack\n    | _ => idtac\n    end;\n    destruct v0; inversion H6;\n    apply_eval_expr_value_in_bound; intros;\n    apply_evalUnOpRTS_reserve; auto.\n  + inversion H21; smack.  \n- (** E_Identifier_X *)\n  inversion H; subst;\n  inversion H3; subst;\n  inversion H4; subst. assumption.\n- (** E_Indexed_Component_X *)\n  inversion H1; subst;\n  inversion H4; subst;\n  inversion H5; subst;\n  inversion H6; subst;\n  match goal with\n  | [H: forall (st : symTab) (st' : symTabRT) \n        (s : STACK.state) (n' n'' : nameRT) (nBound : bound)\n        (v : Ret value),\n      toNameRT st ?n n' ->\n      toSymTabRT st st' ->\n      well_typed_stack st' s ->\n      well_typed_name_x st' n' ->\n      optName st' n' (n'', nBound) ->\n      evalNameRT st' s n' v -> evalNameRT st' s n'' v,\n    H1: toNameRT ?st ?n ?n',\n    H2: toSymTabRT ?st ?st',\n    H3: well_typed_stack ?st' ?s,\n    H4: well_typed_name_x ?st' ?n',\n    H5: optName ?st' ?n' _,\n    H6: evalNameRT ?st' ?s ?n' ?v |- _] => \n      specialize (H _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6)\n  end;\n  match goal with\n  | [H: forall (st : symTab) (st' : symTabRT) \n        (s : STACK.state) (e' e'' : expRT) (eBound : bound)\n        (v : Ret value),\n      toExpRT st ?e e' ->\n      toSymTabRT st st' ->\n      well_typed_stack st' s ->\n      well_typed_exp_x st' e' ->\n      optExp st' e' (e'', eBound) ->\n      evalExpRT st' s e' v -> evalExpRT st' s e'' v,\n     H1: toExpRT ?st ?e ?e',\n     H2: toSymTabRT ?st ?st',\n     H3: well_typed_stack ?st' ?s,\n     H4: well_typed_exp_x ?st' ?e',\n     H5: optExp ?st' ?e' _,\n     H6: evalExpRT ?st' ?s ?e' ?v |- _] => specialize (H _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6)\n  | _ => idtac\n  end.\n  + apply EvalIndexedComponentRTX_RTE; auto.\n  + apply EvalIndexedComponentRTE_RTE with (a:=a0); auto.\n    apply eval_expr_value_reserve with (e := e') (eBound := Interval u v0) (rBound := Interval u' v'); auto.\n    apply_well_typed_exp_preserve.\n    specialize (optimize_exp_ex_cks_stripped _ _ _ _ _ H22); intro HZ1.\n    specialize (eval_exp_ex_cks_stripped _ _ _ _ _ H28); intros HZ2.\n    specialize (H0 _ _ _ _ _ _ _ H12 H2 H3 HZ HZ1 HZ2).\n    specialize (eval_exp_ex_cks_stripped _ _ _ _ _ H0); auto.\n  + apply_well_typed_exp_preserve.\n    specialize (optimize_exp_ex_cks_stripped _ _ _ _ _ H22); intro HZ1.\n    specialize (eval_exp_ex_cks_stripped _ _ _ _ _ H27); intros HZ2.\n    specialize (H0 _ _ _ _ _ _ _ H12 H2 H3 HZ HZ1 HZ2).\n    apply EvalIndexedComponentRT_Range_RTE with (a:=a0) (i:=i) (t:=t0) (l:=l) (u:=u0); auto.\n    apply eval_expr_value_reserve with (e := e') (eBound := Interval u v0) (rBound := Interval u' v'); auto.\n    specialize (eval_exp_ex_cks_stripped _ _ _ _ _ H0); auto.\n    specialize (optimize_name_ast_num_eq _ _ _ _ H21); smack.\n    rewrite H29 in H23; inversion H23; subst; assumption.\n    rewrite H29 in H23; inversion H23; subst.\n    apply_extract_array_index_range_rt_unique; subst.\n    apply_eval_expr_value_in_bound.\n    clear - H12 H22 H25 H29 H30 H31 HZ3.\n    \n    apply_optimize_exp_ex_cks_eq.\n    rewrite exp_updated_exterior_checks in *.\n    inversion H31; subst. inversion H; subst.\n    apply_optimize_range_check_reserve; smack.\n  + apply_well_typed_exp_preserve.\n    specialize (optimize_exp_ex_cks_stripped _ _ _ _ _ H22); intro HZ1.\n    specialize (eval_exp_ex_cks_stripped _ _ _ _ _ H19); intros HZ2.\n    specialize (H0 _ _ _ _ _ _ _ H12 H2 H3 HZ HZ1 HZ2).\n    apply EvalIndexedComponentRT with (a:=a0) (i:=i) (t:=t0) (l:=l) (u:=u0); auto.\n    apply eval_expr_value_reserve with (e := e') (eBound := Interval u v0) (rBound := Interval u' v'); auto.\n    specialize (eval_exp_ex_cks_stripped _ _ _ _ _ H0); auto.\n    specialize (optimize_name_ast_num_eq _ _ _ _ H21); smack.\n    rewrite H28 in H23; inversion H23; subst; assumption.\n    rewrite H28 in H23; inversion H23; subst.\n    apply_extract_array_index_range_rt_unique; subst.\n    clear - H12 H22 H25 H28 H30 H31.\n    \n    apply_optimize_exp_ex_cks_eq.\n    rewrite exp_updated_exterior_checks in *.\n    rewrite <- HZ in H31;\n    apply_do_range_check_same_result; auto.\n- (** E_Selected_Component_X *)\n  inversion H0; subst;\n  inversion H3; subst;\n  inversion H4; subst;\n  inversion H5; subst;\n  match goal with\n  | [H: forall (st : symTab) (st' : symTabRT) \n        (s : STACK.state) (n' n'' : nameRT) (nBound : bound)\n        (v : Ret value),\n      toNameRT st ?n n' ->\n      toSymTabRT st st' ->\n      well_typed_stack st' s ->\n      well_typed_name_x st' n' ->\n      optName st' n' (n'', nBound) ->\n      evalNameRT st' s n' v -> evalNameRT st' s n'' v,\n    H1: toNameRT ?st ?n ?n',\n    H2: toSymTabRT ?st ?st',\n    H3: well_typed_stack ?st' ?s,\n    H4: well_typed_name_x ?st' ?n',\n    H5: optName ?st' ?n' _,\n    H6: evalNameRT ?st' ?s ?n' ?v |- _] => \n      specialize (H _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6)\n  end.\n  + apply EvalSelectedComponentRTX_RTE; auto.\n  + apply EvalSelectedComponentRT with (r:=r); auto.    \nQed.\n\nLtac apply_optExp_completeness :=\n  match goal with\n  | [H1: toExpRT ?st ?e ?e',\n     H2: toSymTabRT ?st ?st',\n     H3: well_typed_stack ?st' ?s,\n     H4: well_typed_exp_x ?st' ?e',\n     H5: optExp ?st' ?e' _,\n     H6: evalExpRT ?st' ?s ?e' ?v |- _] => \n      specialize (optExp_completeness _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6);\n      let HZ := fresh \"HZ\" in\n      intro HZ\n  | [H1: well_typed_stack_and_symboltable ?st' ?s |- _] => \n      inversion H1; subst; apply_well_typed_stack_infer;\n      match goal with\n     | [H1: toExpRT ?st ?e ?e',\n        H2: toSymTabRT ?st ?st',\n        H3: well_typed_stack ?st' ?s,\n        H4: well_typed_exp_x ?st' ?e',\n        H5: optExp ?st' ?e' _,\n        H6: evalExpRT ?st' ?s ?e' ?v |- _] => \n          specialize (optExp_completeness _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6);\n          let HZ := fresh \"HZ\" in\n          intro HZ\n      end\n  end.\n\n(** ** optName_completeness *)\nLemma optName_completeness: forall n st st' s n' n'' nBound v, \n  toNameRT st n n' ->\n    toSymTabRT st st' ->\n      well_typed_stack st' s ->\n        well_typed_name_x st' n' ->\n          optName st' n' (n'', nBound) ->\n            evalNameRT st' s n' v ->\n              evalNameRT st' s n'' v.\nProof.\n  induction n; intros.\n- (** E_Identifier_X *)\n  inversion H; subst;\n  inversion H3; subst;\n  inversion H4; subst. assumption.\n- (** E_Indexed_Component_X *)\n  inversion H; subst;\n  inversion H2; subst;\n  inversion H3; subst;\n  inversion H4; subst;\n  match goal with\n  | [H: forall (st : symTab) (st' : symTabRT) \n        (s : STACK.state) (n' n'' : nameRT) (nBound : bound)\n        (v : Ret value),\n      toNameRT st ?n n' ->\n      toSymTabRT st st' ->\n      well_typed_stack st' s ->\n      well_typed_name_x st' n' ->\n      optName st' n' (n'', nBound) ->\n      evalNameRT st' s n' v -> evalNameRT st' s n'' v,\n    H1: toNameRT ?st ?n ?n',\n    H2: toSymTabRT ?st ?st',\n    H3: well_typed_stack ?st' ?s,\n    H4: well_typed_name_x ?st' ?n',\n    H5: optName ?st' ?n' _,\n    H6: evalNameRT ?st' ?s ?n' ?v |- _] => \n      specialize (H _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6)\n  end.\n  + apply EvalIndexedComponentRTX_RTE; auto.\n  + apply EvalIndexedComponentRTE_RTE with (a:=a0); auto.\n    apply eval_expr_value_reserve with (e := e') (eBound := Interval u v0) (rBound := Interval u' v'); auto.\n    apply_well_typed_exp_preserve.\n    specialize (optimize_exp_ex_cks_stripped _ _ _ _ _ H20); intro HZ1.\n    specialize (eval_exp_ex_cks_stripped _ _ _ _ _ H26); intros HZ2.\n    apply_optExp_completeness.\n    specialize (eval_exp_ex_cks_stripped _ _ _ _ _ HZ0); auto.\n  + apply_well_typed_exp_preserve.\n    specialize (optimize_exp_ex_cks_stripped _ _ _ _ _ H20); intro HZ1.\n    specialize (eval_exp_ex_cks_stripped _ _ _ _ _ H25); intros HZ2.\n    apply EvalIndexedComponentRT_Range_RTE with (a:=a0) (i:=i) (t:=t0) (l:=l) (u:=u0); auto.\n    apply eval_expr_value_reserve with (e := e') (eBound := Interval u v0) (rBound := Interval u' v'); auto.\n    apply_optExp_completeness.\n    specialize (eval_exp_ex_cks_stripped _ _ _ _ _ HZ0); auto.\n    \n    specialize (optimize_name_ast_num_eq _ _ _ _ H19); smack.\n    rewrite H27 in H21; inversion H21; subst; assumption.\n    rewrite H27 in H21; inversion H21; subst.\n    apply_extract_array_index_range_rt_unique; subst.\n    apply_eval_expr_value_in_bound.\n    clear - H10 H20 H23 H27 H28 H29 HZ3.\n    \n    apply_optimize_exp_ex_cks_eq.\n    rewrite exp_updated_exterior_checks in *.\n    inversion H29; subst. inversion H; subst.\n    apply_optimize_range_check_reserve; smack.\n  + apply_well_typed_exp_preserve.\n    specialize (optimize_exp_ex_cks_stripped _ _ _ _ _ H20); intro HZ1.\n    specialize (eval_exp_ex_cks_stripped _ _ _ _ _ H17); intros HZ2.\n    apply EvalIndexedComponentRT with (a:=a0) (i:=i) (t:=t0) (l:=l) (u:=u0); auto.\n    apply eval_expr_value_reserve with (e := e') (eBound := Interval u v0) (rBound := Interval u' v'); auto.\n    apply_optExp_completeness.\n    specialize (eval_exp_ex_cks_stripped _ _ _ _ _ HZ0); auto.\n\n    specialize (optimize_name_ast_num_eq _ _ _ _ H19); smack.\n    rewrite H26 in H21; inversion H21; subst; assumption.\n    rewrite H26 in H21; inversion H21; subst.\n    apply_extract_array_index_range_rt_unique; subst.\n    clear - H10 H20 H23 H26 H28 H29.\n    \n    apply_optimize_exp_ex_cks_eq.\n    rewrite exp_updated_exterior_checks in *.\n    rewrite <- HZ in H29;\n    apply_do_range_check_same_result; auto.\n- (** E_Selected_Component_X *)\n  inversion H; subst;\n  inversion H2; subst;\n  inversion H3; subst;\n  inversion H4; subst;\n  match goal with\n  | [H: forall (st : symTab) (st' : symTabRT) \n        (s : STACK.state) (n' n'' : nameRT) (nBound : bound)\n        (v : Ret value),\n      toNameRT st ?n n' ->\n      toSymTabRT st st' ->\n      well_typed_stack st' s ->\n      well_typed_name_x st' n' ->\n      optName st' n' (n'', nBound) ->\n      evalNameRT st' s n' v -> evalNameRT st' s n'' v,\n    H1: toNameRT ?st ?n ?n',\n    H2: toSymTabRT ?st ?st',\n    H3: well_typed_stack ?st' ?s,\n    H4: well_typed_name_x ?st' ?n',\n    H5: optName ?st' ?n' _,\n    H6: evalNameRT ?st' ?s ?n' ?v |- _] => \n      specialize (H _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6)\n  end.\n  + apply EvalSelectedComponentRTX_RTE; auto.\n  + apply EvalSelectedComponentRT with (r:=r); auto.    \nQed.\n\nLtac apply_optName_completeness := \n  match goal with\n  | [H1: toNameRT ?st ?n ?n',\n     H2: toSymTabRT ?st ?st',\n     H3: well_typed_stack ?st' ?s,\n     H4: well_typed_name_x ?st' ?n',\n     H5: optName ?st' ?n' _,\n     H6: evalNameRT ?st' ?s ?n' ?v |- _] =>\n      specialize (optName_completeness _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6);\n      let HZ := fresh \"HZ\" in\n      intro HZ\n  | [H1: well_typed_stack_and_symboltable ?st' ?s |- _] => \n      inversion H1; subst; apply_well_typed_stack_infer;\n      match goal with\n     | [H1: toNameRT ?st ?n ?n',\n        H2: toSymTabRT ?st ?st',\n        H3: well_typed_stack ?st' ?s,\n        H4: well_typed_name_x ?st' ?n',\n        H5: optName ?st' ?n' _,\n        H6: evalNameRT ?st' ?s ?n' ?v |- _] =>\n          specialize (optName_completeness _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6);\n          let HZ := fresh \"HZ\" in\n          intro HZ\n      end    \n  end.\n\n\n(** ** storeUpdateRT_opt_completeness *)\n\nLemma storeUpdateRT_opt_completeness: forall n st st' s s' n' n'' nBound v, \n  toNameRT st n n' ->\n    toSymTabRT st st' ->\n      well_typed_stack st' s ->\n        well_typed_name_x st' n' ->\n          optName st' n' (n'', nBound) ->\n            storeUpdateRT st' s n' v s' ->\n              storeUpdateRT st' s n'' v s'.\nProof.\n  induction n; intros.\n- inversion H; subst;\n  inversion H3; smack.\n- inversion H; subst;\n  inversion H2; subst;\n  inversion H3; subst;\n  inversion H4; subst.\n  + apply SU_Indexed_Component_xRTE_X; auto.\n    apply_optName_completeness; auto.\n  + apply SU_Indexed_Component_eRTE_X with (a:=a0); auto.\n    destruct H26; apply_optName_completeness; auto.\n    apply eval_expr_value_reserve with (e := e') (eBound := Interval u v0) (rBound := Interval u' v'); auto.\n    apply_well_typed_exp_preserve.\n    specialize (optimize_exp_ex_cks_stripped _ _ _ _ _ H20); intro HZ1.\n    specialize (eval_exp_ex_cks_stripped _ _ _ _ _ H27); intros HZ2.\n    apply_optExp_completeness.\n    specialize (eval_exp_ex_cks_stripped _ _ _ _ _ HZ0); auto.\n  + apply_well_typed_exp_preserve.\n    specialize (optimize_exp_ex_cks_stripped _ _ _ _ _ H20); intro HZ1.\n    specialize (eval_exp_ex_cks_stripped _ _ _ _ _ H25); intros HZ2.\n    apply SU_Indexed_Component_Range_RTE_X with (a:=a0) (i:=i) (t:=t1) (l:=l) (u:=u0); auto.\n    destruct H12; apply_optName_completeness; auto.\n    apply eval_expr_value_reserve with (e := e') (eBound := Interval u v0) (rBound := Interval u' v'); auto.\n    apply_optExp_completeness.\n    specialize (eval_exp_ex_cks_stripped _ _ _ _ _ HZ0); auto.\n    \n    specialize (optimize_name_ast_num_eq _ _ _ _ H19); smack.\n    rewrite H28 in H21; inversion H21; subst.\n    apply_extract_array_index_range_rt_unique; subst.\n    apply_eval_expr_value_in_bound.\n    clear - H10 H20 H23 H28 H29 H30 HZ3.\n    \n    apply_optimize_exp_ex_cks_eq.\n    rewrite exp_updated_exterior_checks in *.\n    inversion H30; subst. inversion H; subst.\n    apply_optimize_range_check_reserve; smack.    \n  + apply_well_typed_exp_preserve.\n    specialize (optimize_exp_ex_cks_stripped _ _ _ _ _ H20); intro HZ1.\n    specialize (eval_exp_ex_cks_stripped _ _ _ _ _ H18); intros HZ2.\n    apply_optName_completeness; auto.\n    apply_optExp_completeness.\n    specialize (eval_exp_ex_cks_stripped _ _ _ _ _ HZ3); intro HZ4.\n    specialize (optimize_name_ast_num_eq _ _ _ _ H19); intro HZ5.\n    rewrite H25 in H21; inversion H21; subst.\n    apply_extract_array_index_range_rt_unique; subst.\n    specialize (optimize_exp_ex_cks_eq _ _ _ _ H20); intros HZ7.\n    rewrite exp_updated_exterior_checks in *.\n    rewrite <- HZ7 in *.\n\n    destruct H17; subst.\n \n    apply SU_Indexed_Component_X with \n      (arrObj:=(ArrayV a0)) (a:=a0) (i:=i) (l:=l) (u:=u0) (t:=t0) (a1:=(updateIndexedComp a0 i v)); smack.\n    apply eval_expr_value_reserve with (e := e') (eBound := Interval u v0) (rBound := Interval l u0); auto.\n    apply_do_range_check_same_result; auto.\n\n    apply SU_Indexed_Component_X with \n      (arrObj:=Undefined) (i:=i) (a:=nil) (l:=l) (u:=u0) (t:=t0) (a1:=((i, v) :: nil)); smack.\n    apply eval_expr_value_reserve with (e := e') (eBound := Interval u v0) (rBound := Interval l u0); auto.\n    apply_do_range_check_same_result; auto.\n- inversion H; subst;\n  inversion H2; subst;\n  inversion H3; subst;\n  inversion H4; subst.\n  + apply_optName_completeness;\n    apply SU_Selected_Component_xRTE_X; smack.\n  + destruct H23;\n    [ apply SU_Selected_Component_X with \n        (recObj:=(RecordV r)) (r:=r) (r1:=(updateSelectedComp r i v)); smack |\n      apply SU_Selected_Component_X with \n        (recObj:=Undefined) (r:=nil) (r1:=((i, v) :: nil)); smack\n    ];\n    apply_optName_completeness; auto.\nQed.\n \nLtac apply_storeUpdateRT_opt_completeness := \n  match goal with\n  | [H1: toNameRT ?st ?n ?n' ,\n     H2: toSymTabRT ?st ?st' ,\n     H3: well_typed_stack ?st' ?s ,\n     H4: well_typed_name_x ?st' ?n' ,\n     H5: optName ?st' ?n' _ ,\n     H6: storeUpdateRT ?st' ?s ?n' ?v ?s' |- _] =>\n      specialize (storeUpdateRT_opt_completeness _ _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6);\n      let HZ := fresh \"HZ\" in\n      intro HZ\n  | [H1: well_typed_stack_and_symboltable ?st' ?s |- _] => \n      inversion H1; subst; apply_well_typed_stack_infer;\n      match goal with\n      | [H1: toNameRT ?st ?n ?n' ,\n         H2: toSymTabRT ?st ?st' ,\n         H3: well_typed_stack ?st' ?s ,\n         H4: well_typed_name_x ?st' ?n' ,\n         H5: optName ?st' ?n' _ ,\n         H6: storeUpdateRT ?st' ?s ?n' ?v ?s' |- _] =>\n           specialize (storeUpdateRT_opt_completeness _ _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6);\n           let HZ := fresh \"HZ\" in\n           intro HZ\n       end\n  end.\n\n(** ** optArgs_copyin_completeness *)\nLemma optArgs_copyin_completeness: forall params' st st' s f f' params args args' args'',\n  toArgsRT st params args args' ->\n  toSymTabRT st st' ->\n  toParamSpecsRT params params' ->\n  well_typed_stack st' s ->\n  well_typed_exps_x st' args' ->\n  optArgs st' params' args' args'' ->\n  copyInRT st' s f params' args' f' ->\n  copyInRT st' s f params' args'' f'.\nProof.\n induction params'; intros.\n-inversion H4; subst.\n inversion H5; subst; auto.\n- destruct args', args'', params, args;\n  match goal with \n  | [H: copyInRT _ _ _ (?a :: ?al) nil _ |- _] => inversion H\n  | [H: optArgs _ (?a :: ?al) (?e :: ?el) nil |- _] => inversion H\n  | [H: toParamSpecsRT nil (?param :: ?params) |- _] => inversion H\n  | [H: toArgsRT _ (?param :: ?params) nil _ |- _] => inversion H\n  | _ => idtac\n  end.\n  inversion H1; subst;\n  inversion H3; subst.\n  assert(HZ: p.(parameter_mode) = a.(parameter_mode_rt)).\n  clear - H9. inversion H9; smack.\n  assert(HZ1: (parameter_subtype_mark p) = (parameter_subtype_mark_rt a)).\n  clear - H9. inversion H9; smack.\n  (*******)\n  inversion H; subst;\n  inversion H4; subst;\n  match goal with\n  | [H1: parameter_mode ?p = parameter_mode_rt ?a,\n     H2: parameter_mode ?p = _ ,\n     H3: parameter_mode_rt ?a = _ |- _] => \n      rewrite H2 in H1; rewrite H3 in H1; inversion H1\n  | [H1: parameter_mode_rt ?a = _ ,\n     H2: parameter_mode_rt ?a = _ |- _] => rewrite H2 in H1; inversion H1\n  end;\n  match goal with\n  | [H: extract_subtype_range_rt _ _ (RangeRT _ _) |- _] => \n      specialize (range_constrainted_type_true _ _ _ _ H);\n      let HZ := fresh \"HZ\" in intros HZ\n  | _ => idtac\n  end;\n  match goal with\n  | [H1: is_range_constrainted_type ?x = false, \n     H2: is_range_constrainted_type ?y = true,\n     H3: ?x = ?y |- _] => \n      rewrite H3 in H1; rewrite H1 in H2; inversion H2\n  | _ => idtac\n  end;\n  (*******)\n  inversion H5; subst;\n  match goal with\n  | [H1: parameter_mode_rt ?a = _ ,\n     H2: parameter_mode_rt ?a = _ |- _] => rewrite H2 in H1; inversion H1\n  end;\n  match goal with\n  | [H: extract_subtype_range_rt _ _ (RangeRT _ _) |- _] => \n      specialize (range_constrainted_type_true _ _ _ _ H);\n      let HZ := fresh \"HZ\" in intros HZ\n  | _ => idtac\n  end;\n\n  match goal with\n  | [H1: toSymTabRT ?st ?st',\n     H2: fetch_exp_type _ ?st = _ |- _ ] => \n      specialize (symbol_table_exp_type_rel _ _ _ _ H1 H2);\n      let HZ := fresh \"HZ\" in intros HZ\n  | _ => idtac\n  end;\n  match goal with\n  | [H1: fetch_exp_type_rt ?x ?st = _, \n     H2: fetch_exp_type_rt ?x ?st = _ |- _] => rewrite H1 in H2; inversion H2; subst\n  | _ => idtac\n  end;\n\n  match goal with\n  | [H1: is_range_constrainted_type ?x = false, \n     H2: is_range_constrainted_type ?x = true |- _] => \n      rewrite H1 in H2; inversion H2\n  | [H1: is_range_constrainted_type ?x = false, \n     H2: is_range_constrainted_type ?y = true,\n     H3: ?x = ?y |- _] => \n      rewrite H3 in H1; rewrite H1 in H2; inversion H2\n  | _ => idtac\n  end;\n  match goal with\n  | [H1: ?x = true,\n     H2: ?y = true,\n     H3: ?x = false \\/ ?y = false |- _] => rewrite H1 in H3; rewrite H2 in H3; clear - H3; smack\n  | [H: ~ List.In ?x (name_exterior_checks (update_exterior_checks_name _ (?x :: _))) |- _] =>\n      rewrite name_updated_exterior_checks in H; clear - H; smack\n  | [H: ~ List.In ?x (name_exterior_checks (update_exterior_checks_name _ (_ :: ?x :: _))) |- _] =>\n      rewrite name_updated_exterior_checks in H; clear - H; smack\n  | _ => idtac\n  end;\n  (*-------------*)\n  match goal with\n  | [H: optName _ _ _ |- _] => \n      specialize (optimize_name_ex_cks_eq _ _ _ _ H);\n      let HZ := fresh \"HZ\" in intro HZ\n  | _ => idtac\n  end;\n  match goal with\n  | [H: optExp _ _ _ |- _] => \n      specialize (optimize_exp_ex_cks_stripped _ _ _ _ _ H);\n      let HZ := fresh \"HZ\" in intro HZ\n  | _ => idtac\n  end;\n  match goal with\n  | [H: evalNameRT _ _ (update_exterior_checks_name _ _) _ |- _] => \n      specialize (eval_name_ex_cks_stripped _ _ _ _ _ H);\n      let HZ := fresh \"HZ\" in intro HZ\n  | _ => idtac\n  end;\n  match goal with\n  | [H: evalExpRT _ _ (update_exterior_checks_exp _ _) _ |- _] => \n      specialize (eval_exp_ex_cks_stripped _ _ _ _ _ H);\n      let HZ := fresh \"HZ\" in intro HZ\n  | _ => idtac\n  end;\n  match goal with\n  | [H: well_typed_exp_x _ (NameRT _ _) |- _] => inversion H; subst\n  | _ => idtac\n  end;\n  match goal with\n  | [H: well_typed_name_x ?st (update_exterior_checks_name ?n ?cks) |- _] =>\n      specialize (well_typed_name_preserve _ _ _ H);\n      let HZ := fresh \"HZ\" in intro HZ\n  | _ => idtac\n  end;\n  match goal with\n  | [H: well_typed_exp_x ?st (update_exterior_checks_exp ?e ?cks) |- _] =>\n      specialize (well_typed_exp_preserve _ _ _ H);\n      let HZ := fresh \"HZ\" in intro HZ\n  | _ => idtac\n  end;\n\n  match goal with\n  | [H: storeUpdateRT _ _ (update_exterior_checks_name _ _) _ _ |- _] =>\n      specialize (store_update_ex_cks_stripped _ _ _ _ _ _ H);\n      let HZ := fresh \"HZ\" in intro HZ\n  | _ => idtac\n  end;\n  match goal with\n  | [H: optName _ (update_exterior_checks_name _ _) _ |- _] =>\n      specialize (optimize_name_ex_cks_stripped _ _ _ _ _ H); \n      let HZ := fresh \"HZ\" in intros HZ\n  | _ => idtac\n  end;\n  match goal with\n  | [H: optExp _ (update_exterior_checks_exp _ _) _ |- _] =>\n      specialize (optimize_exp_ex_cks_stripped _ _ _ _ _ H); \n      let HZ := fresh \"HZ\" in intros HZ\n  | _ => idtac\n  end;\n  (*---------------*)\n  match goal with\n  | [H1: forall (st : symTab) (st' : symTabRT)\n                (s : STACK.state) (f : STACK.frame) \n                (f' : Ret STACK.frame)\n                (params : list paramSpec)\n                (args : list exp) (args' args'' : list expRT),\n              toArgsRT st params args args' ->\n              toSymTabRT st st' ->\n              toParamSpecsRT params ?params' ->\n              well_typed_stack st' s ->\n              well_typed_exps_x st' args' ->\n              optArgs st' ?params' args' args'' ->\n              copyInRT st' s f ?params' args' f' ->\n              copyInRT st' s f ?params' args'' f',\n     H2: toArgsRT ?st ?params ?args ?args', \n     H3: toSymTabRT ?st ?st',\n     H4: toParamSpecsRT ?params ?params',\n     H5: well_typed_stack ?st' ?s,\n     H6: well_typed_exps_x ?st' ?args',\n     H7: optArgs ?st' ?params' ?args' ?args'',\n     H8: copyInRT ?st' ?s ?f ?params' ?args' ?f' |- _ ] =>\n      specialize (H1 _ _ _ _ _ _ _ _ _ H2 H3 H4 H5 H6 H7 H8)\n  | _ => idtac\n  end.\n  + apply CopyIn_Mode_In_eRTE_X; auto.\n    apply_optExp_completeness; auto.\n  + apply CopyIn_Mode_In_NoRangeCheck_X with (v := v) (f' := (STACK.push f (parameter_nameRT a) v)); auto.\n    apply_optExp_completeness; auto.\n    apply_optimize_exp_ex_cks_eq; smack.\n  + apply CopyIn_Mode_In_eRTE_X; auto.\n    apply_optExp_completeness; auto.\n    apply eval_exp_ex_cks_stripped with (cks := (exp_exterior_checks argRT)); auto.\n  + rewrite exp_updated_exterior_checks in H28. inversion H28.\n  + apply CopyIn_Mode_In_eRTE_X; auto.\n    apply eval_expr_value_reserve with (e:=arg') (eBound:=(Interval u' v')) (rBound:=(Interval u v)); auto.\n    apply_optExp_completeness; auto.\n    apply eval_exp_ex_cks_stripped with (cks := (exp_exterior_checks argRT)); auto.\n  + rewrite exp_updated_exterior_checks in H29. inversion H29.\n  + apply CopyIn_Mode_In_Range_RTE_X with (v:=v0) (l:=l) (u:=u0); auto.\n    apply eval_expr_value_reserve with (e:=arg') (eBound:=(Interval u' v')) (rBound:=(Interval u v)); auto.\n\n    apply_optExp_completeness; auto.\n    apply eval_exp_ex_cks_stripped with (cks := (exp_exterior_checks argRT)); auto.\n    \n    apply_extract_subtype_range_unique; subst. \n    specialize (optimize_exp_ex_cks_eq _ _ _ _ H23); intros HZ7.\n    rewrite exp_updated_exterior_checks in HZ7.\n    apply_eval_expr_value_in_bound. \n    inversion H31; subst.\n    apply_optimize_range_check_reserve. smack. \n\n  + inversion H24; subst. (*H24: optimize_range_check arg' (Interval u' v') (Interval u v) e0*)\n  * specialize (optimize_exp_ex_cks_eq _ _ _ _ H23); intros HZ7.\n    rewrite exp_updated_exterior_checks in HZ7. rewrite HZ7; smack.\n    apply CopyIn_Mode_In_NoRangeCheck_X with (v := Int v0) (f' := (STACK.push f (parameter_nameRT a) (Int v0))); auto.\n    apply_optExp_completeness.\n    specialize (exp_exterior_checks_beq_nil _ _ _ H19); intros HZ9. rewrite HZ9 in HZ8; assumption.\n    smack.\n    rewrite exp_updated_exterior_checks; auto.\n  * apply CopyIn_Mode_In_Range_X with (v := v0) (l := l) (u := u0) \n                                       (f' := (STACK.push f (parameter_nameRT a) (Int v0))); auto.\n    apply_optExp_completeness.\n    specialize (eval_exp_ex_cks_stripped _ _ _ _ _ HZ7); auto.\n    specialize (optimize_exp_ex_cks_eq _ _ _ _ H23); intros HZ7.\n    rewrite exp_updated_exterior_checks in HZ7; auto.\n  + apply CopyIn_Mode_Out_X with (f' := (STACK.push f (parameter_nameRT a) Undefined)); auto.\n  + assert (HZ7: exists n1, e0 = NameRT n n1).\n      clear - H28. inversion H28; subst.\n      exists (update_exterior_checks_name n' (remove_check_flag RangeCheckOnReturn (exp_exterior_checks (NameRT n n')))).\n      simpl; auto. exists n'; auto.\n    inversion HZ7; subst.\n    apply CopyIn_Mode_Out_X with (f' := (STACK.push f (parameter_nameRT a) Undefined)); auto.\n  + apply CopyIn_Mode_InOut_eRTE_X; auto.\n    apply_optName_completeness; auto.\n  + apply CopyIn_Mode_InOut_NoRange_X with (v := v) (f' := (STACK.push f (parameter_nameRT a) v)); auto.\n    apply_optName_completeness; auto.\n    rewrite HZ2; assumption.\n  + apply CopyIn_Mode_InOut_eRTE_X; auto.\n    apply_optName_completeness.\n    apply eval_name_ex_cks_stripped with (cks := (name_exterior_checks nRT)); auto.      \n  + apply CopyIn_Mode_InOut_Range_RTE_X with (v:=v) (l:=l) (u:=u); auto.\n    apply_optName_completeness.\n    apply eval_name_ex_cks_stripped with (cks := (name_exterior_checks nRT)); auto. \n    rewrite name_updated_exterior_checks in HZ3.\n    clear - HZ3. smack.\n  + apply CopyIn_Mode_InOut_Range_X with (v:=v) (l:=l) (u:=u) (f':=(STACK.push f (parameter_nameRT a) (Int v))); auto.\n    apply_optName_completeness.\n    apply eval_name_ex_cks_stripped with (cks := (name_exterior_checks nRT)); auto. \n    rewrite name_updated_exterior_checks in HZ3.\n    clear - HZ3. smack.\n  + apply CopyIn_Mode_InOut_eRTE_X; auto.\n    apply_optName_completeness.\n    apply eval_name_ex_cks_stripped with (cks := (name_exterior_checks nRT)); auto.\n  + apply CopyIn_Mode_InOut_NoRange_X with (v := v) (f' := (STACK.push f (parameter_nameRT a) v)); auto.\n    apply_optName_completeness.\n    apply eval_name_ex_cks_stripped with (cks := (name_exterior_checks nRT)); auto. \n    rewrite name_updated_exterior_checks in HZ2.\n    clear - HZ2. rewrite HZ2; smack.\n  (*******)\n  (* the following two are the cases where do optimization on range check and range check on copy out,\n     and prove that the evaluation results are the same after these optimization. \n     n' has checks: (RangeCheckOnReturn :: nil)\n  *)\n  + clear H H3 H4.\n    inversion H28; subst. (* optExp st' (NameRT _ _ _) (NameRT _ _ n', _)*)\n    match goal with\n    | [H: optName _ (update_exterior_checks_name _ _) _ |- _] =>\n        specialize (optimize_name_ex_cks_stripped _ _ _ _ _ H); \n        let HZ := fresh \"HZ\" in intros HZ\n    end.\n    apply_optName_completeness.\n    match goal with\n    | [H: evalNameRT _ _ (update_exterior_checks_name _ _) _ |- _] => \n        specialize (eval_name_ex_cks_stripped _ _ _ _ _ H);\n        let HZ := fresh \"HZ\" in intro HZ\n    end.\n    \n    apply_optimize_range_check_preserve.\n    apply CopyIn_Mode_InOut_eRTE_X; auto.\n    inversion HA0; auto.\n  + clear H H3 H4 H5 H10.\n    inversion H28; subst.\n    match goal with\n    | [H: optName _ (update_exterior_checks_name _ _) _ |- _] =>\n        specialize (optimize_name_ex_cks_stripped _ _ _ _ _ H); \n        let HZ := fresh \"HZ\" in intros HZ\n    end.\n    apply_optName_completeness.\n    match goal with\n    | [H: evalNameRT _ _ (update_exterior_checks_name _ _) _ |- _] => \n        specialize (eval_name_ex_cks_stripped _ _ _ _ _ H);\n        let HZ := fresh \"HZ\" in intro HZ\n    end.\n    apply_optimize_range_check_preserve.\n    apply CopyIn_Mode_InOut_NoRange_X with (v:=v0) (f':=(STACK.push f (parameter_nameRT a) v0)); auto.\n    inversion HA0; auto.\n    specialize (optimize_exp_ex_cks_eq _ _ _ _ H28); intros HZ9. \n    simpl in HZ9. rewrite name_updated_exterior_checks in HZ9.\n    clear - H29 H30 HZ9.\n      inversion H29; subst; inversion H30; subst; simpl in *; rewrite HZ9 in *;\n      match goal with\n      | [H: NameRT _ _ = NameRT _ _ |- _] => clear - H; inversion H; subst\n      | _ => idtac\n      end;\n      repeat progress rewrite name_updated_exterior_checks; smack.\n  + apply CopyIn_Mode_InOut_eRTE_X; auto.\n    apply_optName_completeness.\n    apply eval_name_ex_cks_stripped with (cks := (name_exterior_checks nRT)); auto.    \n  (*******)\n  (* the following four are the cases where do optimization on range check and range check on copy out,\n     and prove that the evaluation results are the same after these optimization. \n     n' has checks: (Do_Range_Check :: RangeCheckOnReturn :: nil)\n  *)\n  + clear H H3 H4.\n    inversion H28; subst. (* optExp st' (NameRT _ _ _) (NameRT _ _ n', _)*)\n    match goal with\n    | [H: optName _ (update_exterior_checks_name _ _) _ |- _] =>\n        specialize (optimize_name_ex_cks_stripped _ _ _ _ _ H); \n        let HZ := fresh \"HZ\" in intros HZ\n    end.\n    apply_optName_completeness.\n    match goal with\n    | [H: evalNameRT _ _ (update_exterior_checks_name _ _) _ |- _] => \n        specialize (eval_name_ex_cks_stripped _ _ _ _ _ H);\n        let HZ := fresh \"HZ\" in intro HZ\n    end.\n    apply_optimize_range_check_preserve.    \n    apply CopyIn_Mode_InOut_eRTE_X; auto.\n    inversion HA0; auto.\n  + clear H H3 H4.\n    apply_extract_subtype_range_unique.\n    inversion H28; subst. (* optExp st' (NameRT _ _ _) (NameRT _ _ n', _)*)\n    match goal with\n    | [H: optName _ (update_exterior_checks_name _ _) _ |- _] =>\n        specialize (optimize_name_ex_cks_stripped _ _ _ _ _ H); \n        let HZ := fresh \"HZ\" in intros HZ\n    end.\n    apply_optName_completeness.\n    match goal with\n    | [H: evalNameRT _ _ (update_exterior_checks_name _ _) _ |- _] => \n        specialize (eval_name_ex_cks_stripped _ _ _ _ _ H);\n        let HZ := fresh \"HZ\" in intro HZ\n    end.\n    apply_optimize_range_check_preserve. \n    apply CopyIn_Mode_InOut_Range_RTE_X with (v:=v0) (l:=l) (u:=u0); auto.\n    inversion HA0; auto.\n    specialize (optimize_exp_ex_cks_eq _ _ _ _ H28); intros HZ9. \n    simpl in HZ9. rewrite name_updated_exterior_checks in HZ9.\n    apply_eval_name_value_in_bound. \n    inversion H37; subst.\n    apply_optimize_range_check_reserve.\n    clear - H30 HZ11 HZ9.\n    inversion H30; smack.\n    rewrite name_updated_exterior_checks; smack.\n  + clear H H3 H4.\n    apply_extract_subtype_range_unique.\n    inversion H28; subst.\n    match goal with\n    | [H: optName _ (update_exterior_checks_name _ _) _ |- _] =>\n        specialize (optimize_name_ex_cks_stripped _ _ _ _ _ H); \n        let HZ := fresh \"HZ\" in intros HZ\n    end.\n    apply_optName_completeness.\n    match goal with\n    | [H: evalNameRT _ _ (update_exterior_checks_name _ _) _ |- _] => \n        specialize (eval_name_ex_cks_stripped _ _ _ _ _ H);\n        let HZ := fresh \"HZ\" in intro HZ\n    end.\n    apply_optimize_range_check_preserve.\n    specialize (optimize_exp_ex_cks_eq _ _ _ _ H28); intros HZ9.\n    simpl in HZ9. rewrite name_updated_exterior_checks in HZ9.\n    inversion H29; subst.\n    * apply CopyIn_Mode_InOut_NoRange_X with (v:=Int v0) (f':=(STACK.push f (parameter_nameRT a) (Int v0))); auto.\n      inversion HA0; auto.\n      smack.\n      inversion H30; subst; simpl in *; rewrite HZ9 in *;\n      match goal with\n      | [H: NameRT _ _ = NameRT _ _ |- _] => clear - H; inversion H; subst\n      | _ => idtac\n      end;\n      repeat progress rewrite name_updated_exterior_checks; smack.\n    * apply CopyIn_Mode_InOut_Range_X with (v:=v0) (l:=l) (u:=u0) (f':=(STACK.push f (parameter_nameRT a) (Int v0))); auto.\n      inversion HA0; auto.\n      inversion H30; subst; simpl in *; rewrite HZ9 in *;\n      match goal with\n      | [H: NameRT _ _ = NameRT _ _ |- _] => clear - H; inversion H; subst\n      | _ => idtac\n      end;\n      repeat progress rewrite name_updated_exterior_checks; smack.\nQed.\n\nLtac apply_optArgs_copyin_completeness :=\n  match goal with\n  | [H1: toArgsRT ?st ?params ?args ?args',\n     H2: toSymTabRT ?st ?st',\n     H3: toParamSpecsRT ?params ?params',\n     H4: well_typed_stack ?st' ?s,\n     H5: well_typed_exps_x ?st' ?args',\n     H6: optArgs ?st' ?params' ?args' ?args'',\n     H7: copyInRT ?st' ?s ?f ?params' ?args' ?f' |- _ ] =>\n      specialize (optArgs_copyin_completeness _ _ _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6 H7);\n      let HZ := fresh \"HZ\" in intro HZ\n  end.\n  \n  \n(*---------------------------------------------------------------------------------*)\n(*---------------------------------------------------------------------------------*)\n\n(** * help version with well_typed_value_in_stack and well_typed_value_in_store *)\n\nLemma eval_expr_value_in_bound': forall e st st' s e' v e'' eBound,\n  toExpRT st e e' ->\n    toSymTabRT st st' ->\n      well_typed_value_in_stack st' s ->\n        well_typed_exp_x st' e' ->\n          evalExpRT st' s e' (OK (Int v)) ->\n            optExp st' e' (e'', eBound) ->\n              in_bound v eBound true.\nProof.\n  intros;\n  apply_well_typed_stack_infer;\n  apply_eval_expr_value_in_bound; auto.\nQed.\n\nLtac apply_eval_expr_value_in_bound' :=\n  match goal with\n  | [H1: toExpRT ?st ?e ?e',\n     H2: toSymTabRT ?st ?st',\n     H3: well_typed_value_in_stack ?st' ?s,\n     H4: well_typed_exp_x ?st' ?e',\n     H5: evalExpRT ?st' ?s ?e' (OK (Int ?v)),\n     H6: optExp ?st' ?e' _ |- _] =>\n      specialize (eval_expr_value_in_bound' _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6);\n      let HZ := fresh \"HZ\" in intros HZ\n  end.\n\nLemma eval_name_value_in_bound': forall n st st' s n' v n'' nBound,\n  toNameRT st n n' ->\n    toSymTabRT st st' ->\n      well_typed_value_in_stack st' s ->\n        well_typed_name_x st' n' ->\n          evalNameRT st' s n' (OK (Int v)) ->\n            optName st' n' (n'', nBound) ->\n              in_bound v nBound true.\nProof.\n  intros;\n  apply_well_typed_stack_infer;\n  apply_eval_name_value_in_bound; auto.\nQed.\n\nLtac apply_eval_name_value_in_bound' :=\n  match goal with\n  | [H1: toNameRT ?st ?n ?n',\n     H2: toSymTabRT ?st ?st',\n     H3: well_typed_value_in_stack ?st' ?s,\n     H4: well_typed_name_x ?st' ?n',\n     H5: evalNameRT ?st' ?s ?n' (OK (Int ?v)),\n     H6: optName ?st' ?n' (?n'', ?nBound) |- _] =>\n      specialize (eval_name_value_in_bound' _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6);\n      let HZ := fresh \"HZ\" in intros HZ\n  end.\n\nLemma optExp_completeness': forall e st st' s e' e'' eBound v, \n  toExpRT st e e' ->\n    toSymTabRT st st' ->\n      well_typed_value_in_stack st' s ->\n        well_typed_exp_x st' e' ->\n          optExp st' e' (e'', eBound) ->\n            evalExpRT st' s e' v ->\n              evalExpRT st' s e'' v.\nProof.\n  intros;\n  apply_well_typed_stack_infer;\n  apply_optExp_completeness; auto.\nQed.\n\nLtac apply_optExp_completeness' :=\n  match goal with\n  | [H1: toExpRT ?st ?e ?e',\n     H2: toSymTabRT ?st ?st',\n     H3: well_typed_value_in_stack ?st' ?s,\n     H4: well_typed_exp_x ?st' ?e',\n     H5: optExp ?st' ?e' _,\n     H6: evalExpRT ?st' ?s ?e' ?v |- _] => \n      specialize (optExp_completeness' _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6);\n      let HZ := fresh \"HZ\" in\n      intro HZ\n  end.\n\nLemma optExp_soundness': forall e st st' s e' e'' eBound v, \n  toExpRT st e e' ->\n    toSymTabRT st st' ->\n      well_typed_value_in_stack st' s ->\n        well_typed_exp_x st' e' ->\n          optExp st' e' (e'', eBound) ->\n            evalExpRT st' s e'' v ->\n              evalExpRT st' s e' v.\nProof.\n  intros;\n  apply_well_typed_stack_infer;\n  apply_optExp_soundness; auto.\nQed.\n\nLtac apply_optExp_soundness' :=\n  match goal with\n  | [H1: toExpRT ?st ?e ?e',\n     H2: toSymTabRT ?st ?st',\n     H3: well_typed_value_in_stack ?st' ?s,\n     H4: well_typed_exp_x ?st' ?e',\n     H5: optExp ?st' ?e' (?e'', _),\n     H6: evalExpRT ?st' ?s ?e'' ?v |- _] => \n      specialize (optExp_soundness' _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6);\n      let HZ := fresh \"HZ\" in\n      intro HZ\n  end.\n\nLemma optName_completeness': forall n st st' s n' n'' nBound v, \n  toNameRT st n n' ->\n    toSymTabRT st st' ->\n      well_typed_value_in_stack st' s ->\n        well_typed_name_x st' n' ->\n          optName st' n' (n'', nBound) ->\n            evalNameRT st' s n' v ->\n              evalNameRT st' s n'' v.\nProof.\n  intros;\n  apply_well_typed_stack_infer;\n  apply_optName_completeness; auto.\nQed.\n\nLtac apply_optName_completeness' := \n  match goal with\n  | [H1: toNameRT ?st ?n ?n',\n     H2: toSymTabRT ?st ?st',\n     H3: well_typed_value_in_stack ?st' ?s,\n     H4: well_typed_name_x ?st' ?n',\n     H5: optName ?st' ?n' _,\n     H6: evalNameRT ?st' ?s ?n' ?v |- _] =>\n      specialize (optName_completeness' _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6);\n      let HZ := fresh \"HZ\" in\n      intro HZ\n  end.\n\nLemma optName_soundness': forall n st st' s n' n'' nBound v, \n  toNameRT st n n' ->\n    toSymTabRT st st' ->\n      well_typed_value_in_stack st' s ->\n        well_typed_name_x st' n' ->\n          optName st' n' (n'', nBound) ->\n            evalNameRT st' s n'' v ->\n              evalNameRT st' s n' v.\nProof.\n  intros;\n  apply_well_typed_stack_infer;\n  apply_optName_soundness; auto.\nQed.\n\nLtac apply_optName_soundness' := \n  match goal with\n  | [H1: toNameRT ?st ?n ?n',\n     H2: toSymTabRT ?st ?st',\n     H3: well_typed_value_in_stack ?st' ?s,\n     H4: well_typed_name_x ?st' ?n',\n     H5: optName ?st' ?n' (?n'', _),\n     H6: evalNameRT ?st' ?s ?n'' ?v |- _] =>\n      specialize (optName_soundness' _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6);\n      let HZ := fresh \"HZ\" in\n      intro HZ\n  end.\n\nLemma storeUpdateRT_opt_completeness': forall n st st' s s' n' n'' nBound v, \n  toNameRT st n n' ->\n    toSymTabRT st st' ->\n      well_typed_value_in_stack st' s ->\n        well_typed_name_x st' n' ->\n          optName st' n' (n'', nBound) ->\n            storeUpdateRT st' s n' v s' ->\n              storeUpdateRT st' s n'' v s'.\nProof.\n  intros;\n  apply_well_typed_stack_infer;\n  apply_storeUpdateRT_opt_completeness; auto.\nQed.\n\nLtac apply_storeUpdateRT_opt_completeness' := \n  match goal with\n  | [H1: toNameRT ?st ?n ?n' ,\n     H2: toSymTabRT ?st ?st' ,\n     H3: well_typed_value_in_stack ?st' ?s ,\n     H4: well_typed_name_x ?st' ?n' ,\n     H5: optName ?st' ?n' _ ,\n     H6: storeUpdateRT ?st' ?s ?n' ?v ?s' |- _] =>\n      specialize (storeUpdateRT_opt_completeness' _ _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6);\n      let HZ := fresh \"HZ\" in\n      intro HZ\n  end.\n\nLemma storeUpdateRT_opt_soundness': forall n st st' s s' n' n'' nBound v, \n  toNameRT st n n' ->\n    toSymTabRT st st' ->\n      well_typed_value_in_stack st' s ->\n        well_typed_name_x st' n' ->\n          optName st' n' (n'', nBound) ->\n            storeUpdateRT st' s n'' v s' ->\n              storeUpdateRT st' s n' v s'.\nProof.\n  intros;\n  apply_well_typed_stack_infer;\n  apply_storeUpdateRT_opt_soundness; auto.\nQed.\n\nLtac apply_storeUpdateRT_opt_soundness' := \n  match goal with\n  | [H1: toNameRT ?st ?n ?n' ,\n     H2: toSymTabRT ?st ?st' ,\n     H3: well_typed_value_in_stack ?st' ?s ,\n     H4: well_typed_name_x ?st' ?n' ,\n     H5: optName ?st' ?n' (?n'', _) ,\n     H6: storeUpdateRT ?st' ?s ?n'' ?v ?s' |- _] =>\n      specialize (storeUpdateRT_opt_soundness' _ _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6);\n      let HZ := fresh \"HZ\" in\n      intro HZ\n  end.\n\nLemma optArgs_copyin_completeness': forall params' st st' s f f' params args args' args'',\n  toArgsRT st params args args' ->\n  toSymTabRT st st' ->\n  toParamSpecsRT params params' ->\n  well_typed_value_in_stack st' s ->\n  well_typed_exps_x st' args' ->\n  optArgs st' params' args' args'' ->\n  copyInRT st' s f params' args' f' ->\n  copyInRT st' s f params' args'' f'.\nProof.\n  intros;\n  apply_well_typed_stack_infer;\n  apply_optArgs_copyin_completeness; auto.\nQed.\n\nLtac apply_optArgs_copyin_completeness' :=\n  match goal with\n  | [H1: toArgsRT ?st ?params ?args ?args',\n     H2: toSymTabRT ?st ?st',\n     H3: toParamSpecsRT ?params ?params',\n     H4: well_typed_value_in_stack ?st' ?s,\n     H5: well_typed_exps_x ?st' ?args',\n     H6: optArgs ?st' ?params' ?args' ?args'',\n     H7: copyInRT ?st' ?s ?f ?params' ?args' ?f' |- _ ] =>\n      specialize (optArgs_copyin_completeness' _ _ _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H6 H7);\n      let HZ := fresh \"HZ\" in intro HZ\n  end.\n\nLemma optArgs_copyin_soundness': forall params' st st' s f f' params args args' args'',\n  toArgsRT st params args args' ->\n  toSymTabRT st st' ->\n  toParamSpecsRT params params' ->\n  well_typed_value_in_stack st' s -> well_typed_symbol_table st' ->\n  well_typed_exps_x st' args' ->\n  optArgs st' params' args' args'' ->\n  copyInRT st' s f params' args'' f' ->\n  copyInRT st' s f params' args' f'.\nProof.\n  intros;\n  apply_well_typed_stack_infer.\n  assert(HA: well_typed_stack_and_symboltable st' s). constructor; auto.\n  apply_optArgs_copyin_soundness; auto.\nQed.\n\nLtac apply_optArgs_copyin_soundness' :=\n  match goal with\n  | [H1: toArgsRT ?st ?params ?args ?args',\n     H2: toSymTabRT ?st ?st',\n     H3: toParamSpecsRT ?params ?params',\n     H4: well_typed_value_in_stack ?st' ?s,\n     H4b: well_typed_symbol_table ?st',\n     H5: well_typed_exps_x ?st' ?args',\n     H6: optArgs ?st' ?params' ?args' ?args'',\n     H7: copyInRT ?st' ?s ?f ?params' ?args'' ?f' |- _ ] =>\n      specialize (optArgs_copyin_soundness' _ _ _ _ _ _ _ _ _ _ H1 H2 H3 H4 H4b H5 H6 H7);\n      let HZ := fresh \"HZ\" in intro HZ\n  end.\n\n(*---------------------------------------------------------------------------------*)\n(*---------------------------------------------------------------------------------*)\n(*---------------------------------  END !  ---------------------------------------*)\n(*---------------------------------------------------------------------------------*)\n(*---------------------------------------------------------------------------------*)\n\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_opt_consistent_util.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.5078118642792046, "lm_q1q2_score": 0.2835250793348651}}
{"text": "From Coq Require Import Ascii.\nFrom Coq Require Import NArith PArith ZArith.\nFrom Coq Require Import Int63.\nFrom Coq Require Import Lia.\nFrom Coq Require String Ascii.\n\nFrom Vyper Require Import UInt63 Arith2.\n\nInductive nibble := Nibble (x3 x2 x1 x0: bool).\nInductive hex_digit :=\n| x0 | x1 | x2 | x3\n| x4 | x5 | x6 | x7\n| x8 | x9 | xA | xB\n| xC | xD | xE | xF.\n\nDefinition ascii_of_hex_digit (digit: hex_digit) (lower: bool)\n: ascii\n:= match digit with\n   | x0 => \"0\"\n   | x1 => \"1\"\n   | x2 => \"2\"\n   | x3 => \"3\"\n   | x4 => \"4\"\n   | x5 => \"5\"\n   | x6 => \"6\"\n   | x7 => \"7\"\n   | x8 => \"8\"\n   | x9 => \"9\"\n   | xA => if lower then \"a\" else \"A\"\n   | xB => if lower then \"b\" else \"B\"\n   | xC => if lower then \"c\" else \"C\"\n   | xD => if lower then \"d\" else \"D\"\n   | xE => if lower then \"e\" else \"E\"\n   | xF => if lower then \"f\" else \"F\"\n   end.\n\nDefinition hex_digit_of_ascii (a: ascii)\n: option hex_digit\n:= match a with\n   | \"0\" => Some x0\n   | \"1\" => Some x1\n   | \"2\" => Some x2\n   | \"3\" => Some x3\n   | \"4\" => Some x4\n   | \"5\" => Some x5\n   | \"6\" => Some x6\n   | \"7\" => Some x7\n   | \"8\" => Some x8\n   | \"9\" => Some x9\n   | \"a\" | \"A\" => Some xA\n   | \"b\" | \"B\" => Some xB\n   | \"c\" | \"C\" => Some xC\n   | \"d\" | \"D\" => Some xD\n   | \"e\" | \"E\" => Some xE\n   | \"f\" | \"F\" => Some xF\n   | _ => None\n   end%char.\n\nDefinition is_hex_digit (a: ascii)\n:= match hex_digit_of_ascii a with\n   | Some _ => true\n   | None => false\n   end.\n\nLemma hex_digit_of_ascii_of_hex_digit (h: hex_digit) (lower: bool):\n  hex_digit_of_ascii (ascii_of_hex_digit h lower) = Some h.\nProof.\ndestruct lower; destruct h; trivial.\nQed.\n\nLemma is_hex_digit_true (a: ascii):\n  is_hex_digit a = true  ->  hex_digit_of_ascii a <> None.\nProof.\nunfold is_hex_digit. now destruct hex_digit_of_ascii.\nQed.\n\nDefinition hex_digit_of_ascii' (a: ascii) (ok: is_hex_digit a = true)\n: hex_digit\n:= match hex_digit_of_ascii a as h return _ = h -> _ with\n   | Some x => fun _ => x\n   | None => fun E => False_rect _ (is_hex_digit_true a ok E)\n   end eq_refl.\n\nLemma hex_digit_of_ascii_of_hex_digit' (h: hex_digit) (lower: bool)\n                                       (ok: is_hex_digit (ascii_of_hex_digit h lower) = true):\n  hex_digit_of_ascii' (ascii_of_hex_digit h lower) ok = h.\nProof.\ndestruct lower; destruct h; trivial.\nQed.\n\nDefinition nibble_of_hex_digit (digit: hex_digit)\n: nibble\n:= match digit with\n   | x0 => Nibble false false false false\n   | x1 => Nibble false false false true\n   | x2 => Nibble false false true  false\n   | x3 => Nibble false false true  true\n   | x4 => Nibble false true  false false\n   | x5 => Nibble false true  false true\n   | x6 => Nibble false true  true  false\n   | x7 => Nibble false true  true  true\n   | x8 => Nibble true  false false false\n   | x9 => Nibble true  false false true\n   | xA => Nibble true  false true  false\n   | xB => Nibble true  false true  true\n   | xC => Nibble true  true  false false\n   | xD => Nibble true  true  false true\n   | xE => Nibble true  true  true  false\n   | xF => Nibble true  true  true  true\n   end.\n\nDefinition hex_digit_of_nibble (n: nibble)\n: hex_digit\n:= match n with\n   | Nibble false false false false => x0\n   | Nibble false false false true  => x1\n   | Nibble false false true  false => x2\n   | Nibble false false true  true  => x3\n   | Nibble false true  false false => x4\n   | Nibble false true  false true  => x5\n   | Nibble false true  true  false => x6\n   | Nibble false true  true  true  => x7\n   | Nibble true  false false false => x8\n   | Nibble true  false false true  => x9\n   | Nibble true  false true  false => xA\n   | Nibble true  false true  true  => xB\n   | Nibble true  true  false false => xC\n   | Nibble true  true  false true  => xD\n   | Nibble true  true  true  false => xE\n   | Nibble true  true  true  true  => xF\n   end.\n\nLemma hex_digit_of_nibble_of_hex_digit (d: hex_digit):\n  hex_digit_of_nibble (nibble_of_hex_digit d) = d.\nProof.\ndestruct d; easy.\nQed.\n\nLemma nibble_of_hex_digit_of_nibble (n: nibble):\n  nibble_of_hex_digit (hex_digit_of_nibble n) = n.\nProof.\ndestruct n as (a3, a2, a1, a0).\ndestruct a3; destruct a2; destruct a1; destruct a0; easy.\nQed.\n\nDefinition N_of_hex_digit (digit: hex_digit)\n: N \n:= match digit with\n   | x0 =>  0\n   | x1 =>  1\n   | x2 =>  2\n   | x3 =>  3\n   | x4 =>  4\n   | x5 =>  5\n   | x6 =>  6\n   | x7 =>  7\n   | x8 =>  8\n   | x9 =>  9\n   | xA => 10\n   | xB => 11\n   | xC => 12\n   | xD => 13\n   | xE => 14\n   | xF => 15\n   end.\n\nLemma N_of_hex_digit_ub (digit: hex_digit):\n  (N_of_hex_digit digit < 16)%N.\nProof.\n  destruct digit; cbn; rewrite<- N.ltb_lt; trivial.\nQed.\n\nDefinition N_of_nibble (n: nibble)\n: N\n:= let f (a: bool) := if a then xI else xO in\n   match n with\n   | Nibble true a2 a1 a0 => Npos (f a0 (f a1 (f a2 xH)))\n   | Nibble false true a1 a0 => Npos (f a0 (f a1 xH))\n   | Nibble false false true a0 => Npos (f a0 xH)\n   | Nibble false false false true => Npos xH\n   | Nibble false false false false => N0\n   end.\n\nLemma N_of_nibble_bound (n: nibble):\n  (N_of_nibble n < 16)%N.\nProof.\n  destruct n as (a3, a2, a1, a0); destruct a3; destruct a2; destruct a1; destruct a0; easy.\nQed.\n\nLemma hex_digit_to_N_via_nibble (d: hex_digit):\n  N_of_nibble (nibble_of_hex_digit d) = N_of_hex_digit d.\nProof.\n  destruct d; easy.\nQed.\n\nLemma nibble_to_N_via_hex_digit (n: nibble):\n  N_of_hex_digit (hex_digit_of_nibble n) = N_of_nibble n.\nProof.\n  destruct n as (a3, a2, a1, a0); destruct a3; destruct a2; destruct a1; destruct a0; easy.\nQed.\n\nDefinition push_bit (n: N) (bit: bool)\n: N\n:= match n with\n   | N0 => if bit then 1 else 0\n   | Npos p => Npos ((if bit then xI else xO) p)\n   end.\n\nLemma push_bit_arith (n: N) (bit: bool):\n  push_bit n bit = (2 * n + if bit then 1 else 0)%N.\nProof.\ndestruct bit; now destruct n.\nQed.\n\nDefinition last_bit (n: N)\n: bool\n:= match n with\n   | N0      | Npos (xO _) => false\n   | Npos xH | Npos (xI _) => true\n   end.\n\nLemma last_bit_odd (n: N):\n  last_bit n = N.odd n.\nProof.\ndestruct n. { trivial. }\ndestruct p; easy.\nQed.\n\nLemma push_bit_then_shr1 (n: N) (bit: bool):\n  N.div2 (push_bit n bit) = n.\nProof.\n  destruct n; destruct bit; easy.\nQed.\n\nLemma last_of_push_bit (n: N) (bit: bool):\n  last_bit (push_bit n bit) = bit.\nProof.\n  destruct n; destruct bit; easy.\nQed.\n\nLemma push_last_bit (n: N):\n  push_bit (N.div2 n) (last_bit n) = n.\nProof.\n  destruct n. easy.\n  destruct p; easy.\nQed.\n\nDefinition push_nibble (n: N) (nib: nibble)\n: N\n:= match nib with\n   | Nibble a3 a2 a1 a0 => push_bit (push_bit (push_bit (push_bit n a3) a2) a1) a0\n   end.\n\nLemma push_nibble_arith (n: N) (nib: nibble):\n  push_nibble n nib = (16 * n + N_of_nibble nib)%N.\nProof.\ndestruct nib as (a3, a2, a1, a0).\nunfold push_nibble.\nrepeat rewrite push_bit_arith.\nrepeat rewrite N.mul_add_distr_l.\nrepeat rewrite<- N.add_assoc.\nf_equal.\n{ now repeat rewrite N.mul_assoc. }\ndestruct a3; destruct a2; destruct a1; destruct a0; easy.\nQed.\n\nDefinition pop_nibble (n: N)\n: N * nibble\n:= let a0 := last_bit n in\n   let n1 := N.div2 n in\n   let a1 := last_bit n1 in\n   let n2 := N.div2 n1 in\n   let a2 := last_bit n2 in\n   let n3 := N.div2 n2 in\n   let a3 := last_bit n3 in\n   let n4 := N.div2 n3 in\n     (n4, Nibble a3 a2 a1 a0).\n\nDefinition pop_hex_digit_pos (p: positive)\n: N * hex_digit\n:= (match p with\n    |  1 => (0%N, x1)\n    |  2 => (0%N, x2)\n    |  3 => (0%N, x3)\n    |  4 => (0%N, x4)\n    |  5 => (0%N, x5)\n    |  6 => (0%N, x6)\n    |  7 => (0%N, x7)\n    |  8 => (0%N, x8)\n    |  9 => (0%N, x9)\n    | 10 => (0%N, xA)\n    | 11 => (0%N, xB)\n    | 12 => (0%N, xC)\n    | 13 => (0%N, xD)\n    | 14 => (0%N, xE)\n    | 15 => (0%N, xF)\n    | q~0~0~0~0 => (N.pos q, x0)\n    | q~0~0~0~1 => (N.pos q, x1)\n    | q~0~0~1~0 => (N.pos q, x2)\n    | q~0~0~1~1 => (N.pos q, x3)\n    | q~0~1~0~0 => (N.pos q, x4)\n    | q~0~1~0~1 => (N.pos q, x5)\n    | q~0~1~1~0 => (N.pos q, x6)\n    | q~0~1~1~1 => (N.pos q, x7)\n    | q~1~0~0~0 => (N.pos q, x8)\n    | q~1~0~0~1 => (N.pos q, x9)\n    | q~1~0~1~0 => (N.pos q, xA)\n    | q~1~0~1~1 => (N.pos q, xB)\n    | q~1~1~0~0 => (N.pos q, xC)\n    | q~1~1~0~1 => (N.pos q, xD)\n    | q~1~1~1~0 => (N.pos q, xE)\n    | q~1~1~1~1 => (N.pos q, xF)\n    end)%positive.\n\nDefinition pop_hex_digit (n: N)\n: N * hex_digit\n:= match n with\n   | 0%N => (0%N, x0)\n   | N.pos p => pop_hex_digit_pos p\n   end.\n\nLemma pop_hex_digit_of_nibble (n: N):\n  pop_hex_digit n = let '(q, nib) := pop_nibble n in (q, hex_digit_of_nibble nib).\nProof.\ndestruct n. { easy. }\ndestruct p; try destruct p; try destruct p; try destruct p; easy.\nQed.\n\nLemma push_nibble_then_pop (n: N) (nib: nibble):\n  pop_nibble (push_nibble n nib) = (n, nib).\nProof.\n  destruct nib as (a3, a2, a1, a0). unfold pop_nibble. cbn.\n  repeat rewrite push_bit_then_shr1.\n  now repeat rewrite last_of_push_bit. \nQed.\n\nLemma pop_nibble_then_push (n: N):\n  push_nibble (fst (pop_nibble n)) (snd (pop_nibble n)) = n.\nProof.\n  destruct n. easy.\n  unfold pop_nibble. unfold fst. unfold snd.\n  unfold push_nibble.\n  now repeat rewrite push_last_bit.\nQed.\n\nDefinition nibble_of_N (n: N)\n: nibble\n:= snd (pop_nibble n).\n\nLemma N_of_nibble_of_N (n: N) (B: (n < 16)%N):\n  N_of_nibble (nibble_of_N n) = n.\nProof.\nassert(P := pop_nibble_then_push n).\nrewrite push_nibble_arith in P.\nunfold nibble_of_N.\nremember (N_of_nibble _) as k. clear Heqk.\nremember (fst _) as z. clear Heqz.\nlia.\nQed.\n\nDefinition pop_nibble_arith (a b: N) (B: (b < 16)%N):\n  pop_nibble (16 * a + b) = (a, nibble_of_N b).\nProof.\nenough (E: push_nibble a (nibble_of_N b) = (16 * a + b)%N).\n{ rewrite<- E. apply push_nibble_then_pop. }\nrewrite push_nibble_arith.\nf_equal. apply N_of_nibble_of_N.\nassumption.\nQed.\n\nDefinition pop_nibble_arith_small (b: N) (B: (b < 16)%N):\n  pop_nibble b = (0%N, nibble_of_N b).\nProof.\nrewrite<- (pop_nibble_arith _ _ B).\nf_equal.\nQed.\n\nDefinition nibble_of_uint63 (i: int)\n:= Nibble (0 <? (i land 8))%int63\n          (0 <? (i land 4))%int63\n          (0 <? (i land 2))%int63\n          (0 <? (i land 1))%int63.\n\nDefinition uint63_of_nibble (n: nibble)\n:= match n with\n   | Nibble a8 a4 a2 a1 =>\n       ((if a8 then 8%int63 else 0%int63)\n         lor\n        (if a4 then 4%int63 else 0%int63)\n         lor\n        (if a2 then 2%int63 else 0%int63)\n         lor\n        (if a1 then 1%int63 else 0%int63))%int63\n   end.\n\nLemma nibble_of_uint63_of_nibble (n: nibble):\n  nibble_of_uint63 (uint63_of_nibble n) = n.\nProof.\ndestruct n as (a3, a2, a1, a0).\ndestruct a3; destruct a2; destruct a1; destruct a0; easy.\nQed.\n\n(** A direct conversion from a native int to a hex digit via an if cascade. *)\nDefinition hex_digit_of_uint63 (i: int)\n:= if (0 <? (i land 8))%int63 then\n     if (0 <? (i land 4))%int63 then\n       if (0 <? (i land 2))%int63 then\n         if (0 <? (i land 1))%int63 then xF else xE\n       else\n         if (0 <? (i land 1))%int63 then xD else xC\n     else\n       if (0 <? (i land 2))%int63 then\n         if (0 <? (i land 1))%int63 then xB else xA\n       else\n         if (0 <? (i land 1))%int63 then x9 else x8\n   else\n     if (0 <? (i land 4))%int63 then\n       if (0 <? (i land 2))%int63 then\n         if (0 <? (i land 1))%int63 then x7 else x6\n       else\n         if (0 <? (i land 1))%int63 then x5 else x4\n     else\n       if (0 <? (i land 2))%int63 then\n         if (0 <? (i land 1))%int63 then x3 else x2\n       else\n         if (0 <? (i land 1))%int63 then x1 else x0.\n\nLemma hex_digit_of_nibble_of_uint63 (i: int):\n  hex_digit_of_nibble (nibble_of_uint63 i) = hex_digit_of_uint63 i.\nProof.\nunfold hex_digit_of_nibble. unfold nibble_of_uint63. unfold hex_digit_of_uint63.\ndestruct (0 <? i land 8)%int63;\n  destruct (0 <? i land 4)%int63;\n  destruct (0 <? i land 2)%int63;\n  destruct (0 <? i land 1)%int63; easy.\nQed.\n\nLemma nibble_of_uint63_of_N (n: N):\n  nibble_of_uint63 (uint63_of_N n) = nibble_of_N n.\nProof.\nunfold nibble_of_N. unfold pop_nibble. cbn.\nremember (uint63_of_N n) as i.\nunfold nibble_of_uint63.\nrepeat rewrite last_bit_odd.\nrepeat rewrite N.div2_spec.\nrepeat rewrite N.shiftr_shiftr.\nrepeat rewrite<- N.testbit_odd.\nrewrite<- N.bit0_odd.\nrepeat rewrite uint63_testbit_N_low_digit; try lia.\nunfold get_digit. rewrite<- Heqi. cbn.\nf_equal; trivial.\nQed.\n\nLemma N_of_hex_digit_of_nibble (nib: nibble):\n  N_of_hex_digit (hex_digit_of_nibble nib) = N_of_nibble nib.\nProof.\ndestruct nib as (a, b, c, d).\ndestruct a; destruct b; destruct c; destruct d; trivial.\nQed.\n\n(***************************************************************************************)\n\n(* This is basically the standard Ascii thing except that bits are ordered MSB-to-LSB. *)\nInductive byte := Byte (a7 a6 a5 a4 a3 a2 a1 a0: bool).\n\nDefinition low_nibble (b: byte)\n: nibble\n:= match b with\n   | Byte _ _ _ _ a3 a2 a1 a0 => Nibble a3 a2 a1 a0\n   end.\n\nDefinition high_nibble (b: byte)\n: nibble\n:= match b with\n   | Byte a7 a6 a5 a4 _ _ _ _ => Nibble a7 a6 a5 a4\n   end.\n\nDefinition byte_of_nibbles (high low: nibble)\n: byte\n:= match high with\n   | Nibble a7 a6 a5 a4 =>\n      match low with\n      | Nibble a3 a2 a1 a0 =>\n         Byte a7 a6 a5 a4 a3 a2 a1 a0\n      end\n   end.\n\nLemma low_nibble_ok (high low: nibble):\n  low_nibble (byte_of_nibbles high low) = low.\nProof.\n  destruct low. destruct high. easy.\nQed.\n\nLemma high_nibble_ok (high low: nibble):\n  high_nibble (byte_of_nibbles high low) = high.\nProof.\n  destruct low. destruct high. easy.\nQed.\n\nLemma byte_of_nibbles_ok (b: byte):\n  byte_of_nibbles (high_nibble b) (low_nibble b) = b.\nProof.\n  now destruct b.\nQed.\n\nDefinition byte_of_hex_digits (high low: hex_digit)\n: byte\n:= byte_of_nibbles (nibble_of_hex_digit high) (nibble_of_hex_digit low).\n\nDefinition hex_digits_of_byte (b: byte)\n: hex_digit * hex_digit\n:= (hex_digit_of_nibble (high_nibble b),\n    hex_digit_of_nibble (low_nibble b)).\n\nDefinition N_of_byte (b: byte)\n: N\n:= let f (a: bool) := if a then xI else xO in\n   match b with\n   | Byte true a6 a5 a4 a3 a2 a1 a0 => Npos (f a0 (f a1 (f a2 (f a3 (f a4 (f a5 (f a6 xH)))))))\n   | Byte false true a5 a4 a3 a2 a1 a0 => Npos (f a0 (f a1 (f a2 (f a3 (f a4 (f a5 xH))))))\n   | Byte false false true a4 a3 a2 a1 a0 => Npos (f a0 (f a1 (f a2 (f a3 (f a4 xH)))))\n   | Byte false false false true a3 a2 a1 a0 => Npos (f a0 (f a1 (f a2 (f a3 xH))))\n   | Byte false false false false true a2 a1 a0 => Npos (f a0 (f a1 (f a2 xH)))\n   | Byte false false false false false true a1 a0 => Npos (f a0 (f a1 xH))\n   | Byte false false false false false false true a0 => Npos (f a0 xH)\n   | Byte false false false false false false false true => Npos xH\n   | Byte false false false false false false false false => N0\n   end.\n\nDefinition pop_byte (n: N)\n: N * byte\n:= let (n1, x) := pop_nibble n in\n   let (n2, y) := pop_nibble n1 in\n     (n2, byte_of_nibbles y x).\n\nDefinition byte_of_N (n: N)\n: byte\n:= snd (pop_byte n).\n\nLemma byte_of_N_arith (high low: N)\n                       (H16: (high < 16)%N)\n                       (L16: (low < 16)%N):\n  byte_of_N (16 * high + low) = byte_of_nibbles (nibble_of_N high) (nibble_of_N low).\nProof.\nunfold byte_of_N. unfold pop_byte.\nrewrite (pop_nibble_arith _ _ L16).\nremember (nibble_of_N low) as nib. clear Heqnib low L16.\nrewrite (pop_nibble_arith_small _ H16).\ntrivial.\nQed.\n\nLemma byte_of_N_of_byte (b: byte):\n  byte_of_N (N_of_byte b) = b.\nProof.\ndestruct b as (a7, a6, a5, a4, a3, a2, a1, a0).\ndestruct a7; destruct a6; destruct a5; destruct a4;\ndestruct a3; destruct a2; destruct a1; destruct a0; trivial.\nQed.\n\nDefinition byte_of_int (i: int)\n:= Byte (0 <? (i land 128))%int63\n        (0 <? (i land 64))%int63\n        (0 <? (i land 32))%int63\n        (0 <? (i land 16))%int63\n        (0 <? (i land 8))%int63\n        (0 <? (i land 4))%int63\n        (0 <? (i land 2))%int63\n        (0 <? (i land 1))%int63.\n\nDefinition int_of_byte (b: byte)\n:= match b with\n   | Byte b7 b6 b5 b4 b3 b2 b1 b0 =>\n     (let a7 := if b7 then 128 else 0 in\n      let a6 := if b6 then  64 lor a7 else a7 in\n      let a5 := if b5 then  32 lor a6 else a6 in\n      let a4 := if b4 then  16 lor a5 else a5 in\n      let a3 := if b3 then   8 lor a4 else a4 in\n      let a2 := if b2 then   4 lor a3 else a3 in\n      let a1 := if b1 then   2 lor a2 else a2 in\n                if b0 then   1 lor a1 else a1)%int63\n   end.\n\nLemma byte_of_int_of_byte (b: byte):\n  byte_of_int (int_of_byte b) = b.\nProof.\ndestruct b as (a7, a6, a5, a4, a3, a2, a1, a0).\ndestruct a7; destruct a6; destruct a5; destruct a4;\ndestruct a3; destruct a2; destruct a1; destruct a0; trivial.\nQed.\n\nFixpoint hex_of_bytes (b: list byte) (lower: bool)\n: String.string\n:= match b with\n   | nil => String.EmptyString\n   | (h :: t)%list =>\n        let (hi, lo) := hex_digits_of_byte h in\n          String.String (ascii_of_hex_digit hi lower)\n                        (String.String (ascii_of_hex_digit lo lower)\n                                       (hex_of_bytes t lower))\n   end.\n\nDefinition byte_of_ascii (a: ascii)\n:= let (b0, b1, b2, b3, b4, b5, b6, b7) := a in Byte b7 b6 b5 b4 b3 b2 b1 b0.\n\nFixpoint bytes_of_string (s: String.string)\n: list byte\n:= match s with\n   | String.EmptyString => nil\n   | String.String h t => byte_of_ascii h :: bytes_of_string t\n   end.\n\n(* TODO: to Str *)\nFixpoint string_forallb (f: ascii -> bool) (s: String.string)\n: bool\n:= match s with\n   | String.EmptyString => true\n   | String.String h t => f h && string_forallb f t\n   end.\n\nLemma string_forallb_iff (f: ascii -> bool) (s: String.string):\n  string_forallb f s = List.forallb f (String.list_ascii_of_string s).\nProof.\ninduction s; cbn. { trivial. }\nf_equal. exact IHs.\nQed.\n\nDefinition is_hex_string (s: String.string)\n: bool\n:= Nat.even (String.length s) \n    &&\n   string_forallb is_hex_digit s.\n\nFixpoint bytes_of_hex (s: String.string)\n                       (ok: is_hex_string s = true)\n: list byte.\nProof.\nrefine(match s as s' return s = s' -> _ with\n       | String.EmptyString => fun _ => nil\n       | String.String h String.EmptyString => fun E => _\n       | String.String hi (String.String lo rest) => fun E =>\n           (byte_of_hex_digits (hex_digit_of_ascii' hi _) (hex_digit_of_ascii' lo _)\n            ::\n            bytes_of_hex rest _)%list\n       end eq_refl); \n  unfold is_hex_string in ok; unfold string_forallb in ok; subst; cbn in *;\n  repeat (rewrite Bool.andb_true_iff in *); try easy.\nfold string_forallb in ok. unfold is_hex_string.\nrewrite Bool.andb_true_iff.\ntauto.\nDefined.\n\nLemma ascii_of_hex_digit_is_hex_digit (h: hex_digit) (lower: bool):\n  is_hex_digit (ascii_of_hex_digit h lower) = true.\nProof.\nunfold is_hex_digit. now rewrite hex_digit_of_ascii_of_hex_digit.\nQed.\n\nLemma hex_of_bytes_is_hex_string (b: list byte) (lower: bool)\n: is_hex_string (hex_of_bytes b lower) = true.\nProof.\nunfold is_hex_string. repeat (rewrite Bool.andb_true_iff).\nsplit; induction b; try easy.\ncbn. repeat rewrite ascii_of_hex_digit_is_hex_digit.\nrewrite IHb. trivial.\nQed.\n\nLemma bytes_of_hex_of_bytes (b: list byte) (lower: bool):\n  let hex := hex_of_bytes b lower in\n  forall ok: is_hex_string hex = true,\n    bytes_of_hex hex ok = b.\nProof.\ninduction b. { easy. }\ncbn zeta in *. intro ok.\ncbn. f_equal.\n{\n  unfold byte_of_hex_digits.\n  repeat rewrite hex_digit_of_ascii_of_hex_digit'.\n  repeat rewrite nibble_of_hex_digit_of_nibble.\n  apply byte_of_nibbles_ok.\n}\napply IHb.\nQed.\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/Hash/Nibble.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.28352507187085135}}
{"text": "(***\n *** A version of the computation monad using the option-set monad\n ***)\n\nFrom Coq Require Export Morphisms Setoid Program.Equality.\nFrom ITree Require Export ITree ITreeFacts Eq.Rutt Eq.EqAxiom.\nFrom Paco Require Import paco.\nFrom Coq Require Export Eqdep EqdepFacts.\n\nRequire Export HeterogeneousEventRelations Padded.\n\nInfix \">>=\" := ITree.bind (at level 58, left associativity).\nNotation \"m1 >> m2\" := (m1 >>= fun _ => m2) (at level 58, left associativity).\n\n\n(** * `itree_spec` **)\n\nVariant SpecEvent (E:Type -> Type) (A:Type) : Type :=\n| Spec_vis : E A -> SpecEvent E A\n| Spec_forall : SpecEvent E A\n| Spec_exists : SpecEvent E A\n.\n\nArguments Spec_vis {E A}.\nArguments Spec_forall {E A}.\nArguments Spec_exists {E A}.\n\n(* An ITree that defines a set of ITrees *)\nNotation itree_spec E := (itree (SpecEvent E)).\n\n(* The body of an itree_spec, inside the observe projection *)\nNotation itree_spec' E A := (itree' (SpecEvent E) A).\n\n\n(***\n *** Satisfaction of itree specs\n ***)\n\n(* An itree satisfies an itree_spec iff it is eutt to an itree that satisfies\nall the quantifiers in the itree_spec *)\nInductive satisfiesF {E R1 R2} (RR : R1 -> R2 -> Prop) (F : itree E R1 -> itree_spec E R2 -> Prop) :\n  itree' E R1 -> itree_spec' E R2 -> Prop :=\n  | satisfies_Ret r1 r2 : RR r1 r2 -> satisfiesF RR F (RetF r1) (RetF r2)\n  | satisfies_TauLR phi1 (phi2 : itree_spec E R2) :\n      F phi1 phi2 -> satisfiesF RR F (TauF phi1) (TauF phi2)\n  | satisfies_TauL phi ophi :\n      satisfiesF RR F (observe phi) ophi -> satisfiesF RR F (TauF phi) ophi\n  | satisfies_TauR ophi phi :\n      satisfiesF RR F ophi (observe phi) -> satisfiesF RR F ophi (TauF phi)\n  | satisfies_VisLR A e kphi1 kphi2 :\n      (forall a : A, F (kphi1 a) (kphi2 a)) ->\n      satisfiesF RR F (VisF e kphi1) (VisF (Spec_vis e) kphi2)\n  | satisfies_forallR A kphi phi :\n      (forall a : A, satisfiesF RR F phi (observe (kphi a))) ->\n      satisfiesF RR F phi (VisF Spec_forall kphi)\n  | satisfies_existsR A kphi phi (a : A) :\n      (satisfiesF RR F phi (observe (kphi a))) ->\n      satisfiesF RR F phi (VisF Spec_exists kphi)\n.\nHint Constructors satisfiesF.\nDefinition satisfies_ {E R1 R2} (RR : R1 -> R2 -> Prop) F t1 t2 : Prop :=\n  @satisfiesF E R1 R2 RR F (observe t1) (observe t2).\n\nLemma monotone_satisfiesF {E R1 R2} (RR : R1 -> R2 -> Prop) ot1 (ot2 : itree_spec' E R2) sim sim'\n  (LE : sim <2= sim')\n  (IN : satisfiesF RR sim ot1 ot2) :\n  satisfiesF RR sim' ot1 ot2.\nProof.\n  induction IN; eauto.\nQed.\n\nLemma monotone_satisfies_ {E R1 R2} RR : monotone2 (@satisfies_ E R1 R2 RR).\nProof. red. intros. eapply monotone_satisfiesF; eauto. Qed.\n\nHint Resolve monotone_satisfies_ : paco.\n(*\nInstance Proper_upaco2_satisfies_ {E R} :\n  Proper ((eq ==> eq ==> impl) ==> eq ==> eq ==> impl) (upaco2 (@satisfies_ E R)).\nProof.\n  intros r1 r2 prp_r t1 t2 e12 t3 t4 e34 r13.\n  rewrite <- e12. rewrite <- e34.\n  destruct r13.\n  - left. eapply (paco2_mon _ H).\n    intros x y. apply (prp_r x x eq_refl y y eq_refl).\n  - right. apply (prp_r _ _ eq_refl _ _ eq_refl H).\nQed.\n*)\nDefinition satisfies {E R1 R2} RR : itree E R1 -> itree_spec E R2 -> Prop :=\n  paco2 (satisfies_ RR) bot2.\n\nSection satisfies_test.\n\n  CoFixpoint cphi1 {E} (A R : Type) : itree_spec E R := Vis (Spec_forall) (fun _ : A => cphi1 A R).\n\n  CoFixpoint cphi2 {E} (A R : Type) : itree_spec E R := Tau (Vis Spec_forall (fun _ :A => cphi2 A R)).\n\n  Lemma phi1_empty : forall E R1 R2 (RR : R1 -> R2 -> Prop) (t : itree E R1), ~ satisfies RR t (cphi1 nat R2).\n  Proof.\n    intros. intro Hcontra. punfold Hcontra. red in Hcontra.\n    remember (observe t) as ot.\n    cbn in Hcontra. remember (VisF Spec_forall (fun _ : nat => cphi1 nat R2)) as y.\n    hinduction Hcontra before RR; intros; inv Heqy; inj_existT; eauto.\n    eapply H0; eauto. subst. cbn. auto. Unshelve. apply 0.\n  Qed.\n\n  Lemma phi2_nempty : forall E A R1 R2 (RR : R1 -> R2 -> Prop), satisfies RR (@ITree.spin E R1) (cphi2 A R2).\n  Proof.\n    intros. pcofix CIH. pstep. red. cbn. constructor. left.\n    pcofix CIH'. pstep. constructor. intros. cbn. constructor.\n    right. eauto.\n  Qed.\n\n  Lemma phi1_phi2_eutt : forall E R, (@cphi1 E nat R) ≈ (cphi2 nat R).\n  Proof.\n    intros E R. pcofix CIH. pstep. red. cbn.\n    constructor; auto. constructor. intros. right. eauto.\n  Qed.\n(* this shows that satisfies does not respect eutt\n   maybe it respects eutt on the left? I was only able to construct this counter example doing weird stuff on the right\n   this raises the question of if the trim normal form stuff will still be useful\n*)\nEnd satisfies_test.\n\nLemma not_Proper_eutt_satisfies_impl {E R1 R2} RR :\n  ~ Proper (eutt eq ==> eutt eq ==> impl) (@satisfies E R1 R2 RR).\nProof.\n  intro Hcon. eapply phi1_empty. rewrite phi1_phi2_eutt.\n  apply phi2_nempty.\nQed.\n\nLemma satisfies_TauL_inv:\n  forall (E : Type -> Type) (R2 R1 : Type) (RR : R1 -> R2 -> Prop) (m1 : itree E R1)\n    (phi2 : itree_spec E R2),\n    satisfiesF RR (upaco2 (satisfies_ RR) bot2) (TauF m1) (observe phi2) -> satisfies RR m1 phi2.\nProof.\n  intros E R2 R1 RR m1 phi2 H.\n  remember (TauF m1) as x. pstep. red.\n  hinduction H before RR; intros; inv Heqx; eauto.\n  pclearbot. constructor. pstep_reverse.\nQed.\n\nInstance Proper_eutt_satisfies_impl_l {E R1 R2} RR :\n  Proper (eutt eq ==> eq ==> impl) (@satisfies E R1 R2 RR).\nProof.\n  intros t1 t2 Ht12 t3 t4 Ht34. subst t4. intros Ht13.\n  generalize dependent t3. generalize dependent t2. revert t1.\n  pcofix CIH. intros t1 t2 Ht12 t3 Ht13.\n  pstep. red. punfold Ht12. red in Ht12.\n  punfold Ht13. red in Ht13.\n  hinduction Ht13 before r; intros; eauto.\n  - remember (RetF r1) as x. hinduction Ht12 before r; intros; inv Heqx; eauto.\n  - pclearbot. assert (phi1 ≈ t2). rewrite <- (tau_eutt phi1). pstep. auto.\n    clear Ht12. rename H0 into Ht12. punfold H. red in H.\n    punfold Ht12. red in Ht12.\n    hinduction Ht12 before r; intros; subst; eauto.\n    + constructor. rewrite itree_eta' at 1. pstep_reverse.\n      eapply paco2_mon with (r := bot2). pstep. auto. intros; contradiction.\n    + constructor. right. pclearbot. eapply CIH; eauto. revert H.\n      apply satisfies_TauL_inv.\n    + pclearbot. constructor.\n      remember (VisF e k1) as x. hinduction H before r; intros; inv Heqx; inj_existT; subst; eauto.\n      econstructor. right. pclearbot. eapply CIH; eauto. apply REL. apply H.\n    + eapply IHHt12; eauto. pstep_reverse. apply satisfies_TauL_inv. auto.\n  -  eapply IHHt13; eauto. pstep_reverse. rewrite <- (tau_eutt phi). pstep. auto.\n  - pclearbot. remember (VisF e kphi1) as x.\n    hinduction Ht12 before r; intros; subst; try inv Heqx; eauto.\n    inj_existT. subst. pclearbot. constructor. right. eapply CIH; eauto. apply REL. apply H.\nQed.\n\nSection Refines.\n(***\n *** Refinement of itree specs\n ***)\n\nContext {E1 E2 : Type -> Type} {R1 R2 : Type}.\nContext (RPre : PreRel E1 E2) (RPost : PostRel E1 E2) (RR : R1 -> R2 -> Prop).\n\n(* One itree_spec refines another iff, after turning finitely many quantifier\nevents to actual quantifiers, they have the same constructor with continuations\nsuch that the first continuation coinductively refines the second *)\nInductive refinesF  (F : itree_spec E1 R1 -> itree_spec E2 R2 -> Prop) :\n  itree_spec' E1 R1 -> itree_spec' E2 R2 -> Prop :=\n  | refines_Ret r1 r2 : RR r1 r2 -> refinesF F (RetF r1) (RetF r2)\n  | refines_TauLR phi1 phi2 :\n      F phi1 phi2 -> refinesF F (TauF phi1) (TauF phi2)\n  | refines_TauL phi ophi :\n      refinesF F (observe phi) ophi -> refinesF F (TauF phi) ophi\n  | refines_TauR ophi phi :\n      refinesF F ophi (observe phi) -> refinesF F ophi (TauF phi)\n  | refines_VisLR A B e1 e2 kphi1 kphi2 :\n      RPre A B e1 e2 ->\n      (forall a b, RPost A B e1 e2 a b -> F (kphi1 a) (kphi2 b)) ->\n      refinesF F (VisF (Spec_vis e1) kphi1) (VisF (Spec_vis e2) kphi2)\n  | refines_forallR A kphi phi :\n      (forall a : A, refinesF F phi (observe (kphi a))) ->\n      refinesF F phi (VisF Spec_forall kphi)\n  | refines_forallL A kphi phi (a : A) :\n      (refinesF F (observe (kphi a)) phi) ->\n      refinesF F (VisF Spec_forall kphi) phi\n  | refines_existsR A kphi phi (a : A) :\n      (refinesF F phi (observe (kphi a))) ->\n      refinesF F phi (VisF Spec_exists kphi)\n  | refines_existsL A kphi phi :\n      (forall a : A, refinesF F (observe (kphi a)) phi) ->\n      refinesF F (VisF Spec_exists kphi) phi\n.\nHint Constructors refinesF.\nDefinition refines_  F (t1 : itree_spec E1 R1) (t2 : itree_spec E2 R2) : Prop :=\n  refinesF F (observe t1) (observe t2).\n\nLemma monotone_refinesF ot1 ot2 sim sim'\n  (LE : sim <2= sim')\n  (IN : refinesF sim ot1 ot2) :\n  refinesF sim' ot1 ot2.\nProof.\n  induction IN; eauto.\nQed.\n\nLemma monotone_refines_ : monotone2 refines_.\nProof. red. intros. eapply monotone_refinesF; eauto. Qed.\n\n\n(*\nInstance Proper_upaco2_refines_ {E R} :\n  Proper ((eq ==> eq ==> impl) ==> eq ==> eq ==> impl) (upaco2 (@refines_ E R)).\nProof.\n  intros r1 r2 prp_r t1 t2 e12 t3 t4 e34 r13.\n  rewrite <- e12. rewrite <- e34.\n  destruct r13.\n  - left. eapply (paco2_mon _ H).\n    intros x y. apply (prp_r x x eq_refl y y eq_refl).\n  - right. apply (prp_r _ _ eq_refl _ _ eq_refl H).\nQed.\n\nLemma bot2_least {T0 T1} (r: rel2 T0 T1) : bot2 <2= r.\nProof.\n  intros _ _ [].\nQed.\n\n(* FIXME: there must be a better way to get this result... *)\nLemma upaco2_refinesF_bot_r {E R} r t1 t2 :\n  upaco2\n    (fun (F : itree_spec E R -> itree_spec E R -> Prop) (t4 t5 : itree_spec E R) =>\n     refinesF F (observe t4) (observe t5)) bot2 t1 t2 ->\n  upaco2\n    (fun (F : itree_spec E R -> itree_spec E R -> Prop) (t0 t4 : itree_spec E R) =>\n     refinesF F (observe t0) (observe t4)) r t1 t2.\nProof.\n  intro H.\n  eapply (Proper_upaco2_refines_ _ _ _ t1 t1 eq_refl t2 t2 eq_refl H). Unshelve.\n  intros _ _ _ _ _ _ [].\nQed.\n*)\n\nDefinition refines : itree_spec E1 R1 -> itree_spec E2 R2 -> Prop :=\n  paco2 refines_ bot2.\n\nEnd Refines.\n\n#[global] Hint Resolve monotone_refines_ : paco.\n\n#[global] Hint Constructors refinesF.\n\n(* need a little library of heterogeneous event relations to express theorems  *)\n\n(* Reflexivity of refinement *)\nLemma refl_refines {E R} RPre RPost RR :\n  ReflexivePreRel RPre -> ReflexivePostRel RPost -> Reflexive RR ->\n  forall t, padded t -> (@refines E E R R RPre RPost RR t t).\nProof.\n  intros HRPre HRPost HRR. pcofix CIH.\n  intros. pstep. red. punfold H0. red in H0.\n  inv H0; inj_existT; pclearbot; subst; try destruct e.\n  - constructor. reflexivity.\n  - constructor. right. eapply CIH; eauto.\n  - constructor. auto. left. pstep. constructor.\n    apply HRPost in H0. subst. right. eapply CIH; eauto. apply H1.\n  - apply refines_forallR. intro a0. apply refines_forallL with (a := a0).\n    constructor. right. eapply CIH; eauto. apply H1.\n  - apply refines_existsL. intro a0. apply refines_existsR with (a := a0).\n    constructor. right. eapply CIH; apply H1.\nQed.\n\n(*  red. pcofix CIH. intros HRR HRPre HRPost t. pfold. red.\n  destruct (observe t); try destruct e; econstructor; eauto.\n  intros. right. apply HRPre in H. subst. eauto.\nQed. *)\n\n  (* this exposes a flaw in current definition, could fix by adding restrictions to return values of events like I do in rutt, in the mrec rule it seems like that would be neccesary\n\n  when I make a two related recursive calls, I feel like I need to know that the call events return related\n  values otherwise how would I deal with any code that could make a recursive call and then\n  use its value to compute something more\n\n  I was confused by something Eddy said before, but now I think I get what was going on,\n  in their current setup recursive calls are represented as functions, so a relation over them\n  already has the ability to relate inputs and outputs\n\n  in the itrees setting things are more separate, recursive calls are inert events\n  a relation over events  cannot on its own impose restrictions on return,\n  we will need to impose that separately\n\n  this all seems to come back to the fact that I was right originally\n\n  perhaps the solution should be to have another relation hrefines that is really just for\n  mrec, then can show that hrefines eq eq is the same thing as refines?\n\n  although maybe it is simpler to define refines as hrefines eq eq\n*)\n\nLemma refines_Vis_forallR : forall (E1 E2 : Type -> Type) (R1 R2 A : Type) RPre RPost RR\n                              (t : itree_spec E1 R1) (k : A -> itree_spec E2 R2),\n         refines RPre RPost RR t (Vis Spec_forall k) ->\n         forall a : A, refines RPre RPost RR t (k a).\nProof.\n  intros E1 E2 R1 R2 A RPre RAns RR. pcofix CIH. intros t k Href a.\n  pfold. revert a. red. punfold Href. red in Href.\n  cbn in *. remember (observe t) as ot. clear Heqot.\n  remember (VisF Spec_forall k) as x.\n  hinduction Href before r; intros; inv Heqx; inj_existT; subst; pclearbot; eauto.\n  - clear H0. assert (refines RPre RAns RR (go phi) (k a)).\n    { pstep. apply H. }\n    enough (paco2 (refines_ RPre RAns RR) r (go phi) (k a)).\n    { punfold H1. }\n    eapply paco2_mon; eauto. intros; contradiction.\nQed.\n\nLemma refines_Vis_existsL : forall (E1 E2 : Type -> Type) (R1 R2 A : Type) RPre RPost RR\n                              (t : itree_spec E1 R1) (k : A -> itree_spec E2 R2),\n         refines RPre RPost RR (Vis Spec_exists k) t ->\n         forall a : A, refines RPre RPost RR (k a) t.\nProof.\n  intros E1 E2 R1 R2 A RPre RPost RR. intros t k Href.\n  intros. pfold. red. punfold Href. red in Href.\n  remember (observe t) as ot. clear Heqot. cbn in *.\n  remember (VisF Spec_exists k) as x.\n  hinduction Href before A; intros; inv Heqx; inj_existT; subst; eauto.\nQed.\n(* my next task is to understand this forallRefinesF predicate,\n   and replicate it for exists  *)\n\n(* A version of refinesF specialized to a forall on the left *)\nInductive forallRefinesF {E1 E2 R1 R2} RPre RAns (RR : R1 -> R2 -> Prop) (F : itree_spec E1 R1 -> itree_spec E2 R2 -> Prop)\n          {A} (kphi1: A -> itree_spec E1 R1)\n  : itree_spec' E2 R2 -> Prop :=\n  | forallRefines_forallR B kphi2 :\n      (forall b : B, forallRefinesF RPre RAns RR F kphi1 (observe (kphi2 b))) ->\n      forallRefinesF RPre RAns RR F kphi1 (VisF Spec_forall kphi2)\n  | forallRefines_forallL phi (a : A) :\n      refinesF RPre RAns RR F (observe (kphi1 a)) phi ->\n      forallRefinesF RPre RAns RR F kphi1 phi\n  | forallRefines_existsR B kphi2 (b : B) :\n      (forallRefinesF RPre RAns RR F kphi1 (observe (kphi2 b))) ->\n      forallRefinesF RPre RAns RR F kphi1 (VisF Spec_exists kphi2)\n  | forallRefines_TauR phi2 :\n    forallRefinesF RPre RAns RR F kphi1 (observe phi2) ->\n    forallRefinesF RPre RAns RR F kphi1 (TauF phi2)\n\n.\n\n(* not 100% sure I did this right*)\nInductive existsRefinesF {E1 E2 R1 R2} RPre RAns (RR : R1 -> R2 -> Prop) (F : itree_spec E1 R1 -> itree_spec E2 R2 -> Prop)\n          {A} (kphi2 : A -> itree_spec E2 R2)\n  : itree_spec' E1 R1 -> Prop :=\n  | existsRefines_existsR phi a :\n    refinesF RPre RAns RR F phi (observe (kphi2 a)) ->\n    existsRefinesF RPre RAns RR F kphi2 phi\n  | existsRefines_forallL B (kphi1 : B -> itree_spec E1 R1) (b : B):\n    existsRefinesF RPre RAns RR F kphi2 (observe (kphi1 b)) ->\n    existsRefinesF RPre RAns RR F kphi2 (VisF Spec_forall kphi1)\n  | existsRefines_existsL B (kphi1 : B -> itree_spec E1 R1) :\n    (forall b, existsRefinesF RPre RAns RR F kphi2 (observe (kphi1 b))) ->\n    existsRefinesF RPre RAns RR F kphi2 (VisF Spec_exists kphi1)\n  | existsRefines_TauL phi1 :\n    existsRefinesF RPre RAns RR F kphi2 (observe phi1) ->\n    existsRefinesF RPre RAns RR F kphi2 (TauF phi1)\n.\n\n(* FIXME: should we replace the recursive call to refinesF in the above with\njust a refines? *)\n\nLemma refinesF_Vis_forallL : forall (E1 E2 : Type -> Type) (R1 R2 A : Type) RPre RAns RR F\n                                   (t : itree_spec' E2 R2) (k : A -> itree_spec E1 R1),\n    refinesF RPre RAns RR F (VisF Spec_forall k) t ->\n    @forallRefinesF E1 E2 R1 R2 RPre RAns RR F A k t.\nProof.\n  intros. remember (VisF Spec_forall k) as t1. induction H; try discriminate.\n  - constructor. eauto.\n  - inversion Heqt1. subst. inj_existT. subst.\n    constructor. auto.\n  - inversion Heqt1. subst. inj_existT. subst. econstructor; eauto.\n  - eapply forallRefines_existsR. eauto.\nQed.\n\nLemma refinesF_Vis_existsR : forall E1 E2 R1 R2 A RPre RAns RR F\n                               (t : itree_spec' E1 R1) (k : A -> itree_spec E2 R2),\n    refinesF RPre RAns RR F t (VisF Spec_exists k) ->\n    existsRefinesF RPre RAns RR F k t.\nProof.\n  intros. remember (VisF Spec_exists k) as y.\n  hinduction H before A; intros; inv Heqy; inj_existT; subst.\n  - constructor. auto.\n  - eapply existsRefines_forallL. eapply IHrefinesF; eauto.\n  - econstructor. eauto.\n  - apply existsRefines_existsL. intros. eauto.\nQed.\n\n\nLemma refines_TauL_inv : forall (E1 E2 : Type -> Type) (R1 R2: Type) RPre RAns RR\n                                   (phi1 : itree_spec E1 R1) (phi2 : itree_spec E2 R2),\n      refines RPre RAns RR (Tau phi1) phi2 -> refines RPre RAns RR phi1 phi2.\nProof.\n  intros E1 E2 R1 R2 RPre RAns RR. pcofix CIH.\n  intros. pstep. punfold H0. red in H0. red. cbn in *. remember (TauF phi1) as x.\n  hinduction H0 before r; intros; inv Heqx; pclearbot; eauto.\n  - constructor. pstep_reverse. eapply paco2_mon; eauto. intros; contradiction.\n  - rewrite itree_eta'. pstep_reverse.\n    apply paco2_mon with (r := bot2). pstep. auto. intros. contradiction.\nQed.\n\nLemma refines_TauR_inv : forall (E1 E2 : Type -> Type) (R1 R2: Type) RPre RAns RR\n                                   (phi1 : itree_spec E1 R1) (phi2 : itree_spec E2 R2),\n      refines RPre RAns RR phi1 (Tau phi2) -> refines RPre RAns RR phi1 phi2.\nProof.\n  intros E1 E2 R1 R2 RPre RAns RR.\n  intros. pstep. punfold H. red in H. red. cbn in *. remember (TauF phi2) as x.\n  hinduction H before RPre; intros; inv Heqx; pclearbot; eauto.\n  constructor. pstep_reverse.\nQed.\n\nLemma refinesF_TauR_inv : forall (E1 E2 : Type -> Type) (R1 R2: Type) RPre RAns RR\n                                   (phi1 : itree_spec E1 R1) (phi2 : itree_spec E2 R2),\n      refinesF RPre RAns RR (upaco2 (refines_ RPre RAns RR) bot2) (observe phi1) (TauF phi2) ->\n      refinesF RPre RAns RR (upaco2 (refines_ RPre RAns RR) bot2) (observe phi1) (observe phi2).\nProof.\n  intros. remember (TauF phi2) as y.\n  hinduction H before RPre; intros; inv Heqy; pclearbot; eauto.\n  constructor. pstep_reverse.\nQed.\n\nLemma refinesF_TauL_inv : forall (E1 E2 : Type -> Type) (R1 R2: Type) RPre RAns RR\n                                   (phi1 : itree_spec E1 R1) (phi2 : itree_spec E2 R2),\n      refinesF RPre RAns RR (upaco2 (refines_ RPre RAns RR) bot2) (TauF phi1) (observe phi2) ->\n      refinesF RPre RAns RR (upaco2 (refines_ RPre RAns RR) bot2) (observe phi1) (observe phi2).\nProof.\n  intros. remember (TauF phi1) as y.\n  hinduction H before RPre; intros; inv Heqy; pclearbot; eauto.\n  constructor. pstep_reverse.\nQed.\n\nLemma refinesF_Vis_existsR_Tau_inv : forall E1 E2 R1 R2 A RPre RAns RR\n                               (t : itree_spec E1 R1) (k : A -> itree_spec E2 R2),\n    existsRefinesF RPre RAns RR (upaco2 (refines_ RPre RAns RR) bot2) k (TauF t) ->\n    existsRefinesF RPre RAns RR (upaco2 (refines_ RPre RAns RR) bot2) k (observe t).\nProof.\n  intros. inv H; auto.\n  apply refinesF_Vis_existsR. econstructor. Unshelve. all : auto. pstep_reverse.\n  apply refines_TauL_inv. pstep. auto.\nQed.\n\n\n\nCreate HintDb solve_padded.\n\n(*\n(* it would be a good idea to try to understand if there are other non-trim based counterexamples*)\n\n(*hopefully this should be able to go away now *)\n(* A version of refinesF specialized to a Tau on the left *)\nInductive tauRefinesF {E1 E2 R1 R2} (RR : R1 -> R2 -> Prop) (F : itree_spec E1 R1 -> itree_spec E2 R2 -> Prop)\n          (phi1: itree_spec E1 R1)\n  : itree_spec' E2 R2 -> Prop :=\n  | tauRefines_VisLR phi2 : F phi1 phi2 -> tauRefinesF RR F phi1 (TauF phi2)\n  | tauRefines_forallR B kphi2 :\n      (forall b : B, tauRefinesF  RR F phi1 (observe (kphi2 b))) ->\n      tauRefinesF  RR F phi1 (VisF Spec_forall kphi2)\n  | tauRefines_existsR B kphi2 (b : B) :\n      tauRefinesF RR F phi1 (observe (kphi2 b)) ->\n      tauRefinesF RR F phi1 (VisF Spec_exists kphi2)\n.\n\nLemma refinesF_Tau : forall (E1 E2 : Type -> Type) (R1 R2 : Type) RPre RPost RR F\n                            t1 (t2 : itree_spec' E2 R2),\n    refinesF RPre RPost RR F (TauF t1) t2 ->\n    @tauRefinesF E1 E2 R1 R2 RR F t1 t2.\nProof.\n  intros. remember (TauF t1) as t. induction H; inversion Heqt.\n  - rewrite <- H1. constructor. assumption.\n  - subst. econstructor. intro b. apply H0. assumption.\n  - econstructor. apply IHrefinesF. assumption.\nQed.\n*)\n\nInductive isConcreteF {E R} (F : itree_spec E R -> Prop) :\n  itree_spec' E R -> Prop :=\n  | isConcrete_Ret (r : R) : isConcreteF F (RetF r)\n  | isConcrete_Tau (phi : itree_spec E R) :\n      F phi -> isConcreteF F (TauF phi)\n  | isConcrete_Vis A e kphi :\n      (forall a:A, F (kphi a)) -> isConcreteF F (VisF (Spec_vis e) kphi).\n\nHint Constructors isConcreteF.\nDefinition isConcrete_ {E R} F (t: itree_spec E R) : Prop :=\n  isConcreteF F (observe t).\n\nLemma monotone_isConcreteF {E R} (ot : itree_spec' E R) sim sim'\n  (LE : sim <1= sim')\n  (IN : isConcreteF sim ot) :\n  isConcreteF sim' ot.\nProof.\n  induction IN; eauto.\nQed.\n\nLemma monotone_isConcrete_ {E R} : monotone1 (@isConcrete_ E R).\nProof. red. intros. eapply monotone_isConcreteF; eauto. Qed.\n\nHint Resolve monotone_isConcrete_ : paco.\n\nDefinition isConcrete {E R} : itree_spec E R -> Prop := paco1 isConcrete_ bot1.\n\nLemma isConcreteVisInv {E R A} e (k : A -> itree_spec E R) a :\n  isConcrete (Vis (Spec_vis e) k) -> isConcrete (k a).\nProof.\n  intro isc; punfold isc. inversion isc.\n  assert (kphi0 = k); [ inj_existT; assumption | ].\n  rewrite H3 in H0. pclearbot. apply H0.\nQed.\n\nLemma refines_Vis_existsR:\n  forall (E1 : Type -> Type) (R1 : Type) (E2 : Type -> Type) (R2 : Type)\n    (RPre1 : PreRel E1 E2) (RPost1 : PostRel E1 E2) (RR1 : R1 -> R2 -> Prop)\n    (A : Type) (kphi : A -> itree_spec E2 R2) (phi1 : itree_spec E1 R1),\n    refines RPre1 RPost1 RR1 phi1\n             (Vis Spec_exists kphi) ->\n    isConcrete phi1 -> exists a : A, refines RPre1 RPost1 RR1 phi1 (kphi a).\nProof.\n  intros E1 R1 E2 R2 RPre1 RPost1 RR1 A kphi phi1 Href.\n  punfold Href. red in Href.\n  cbn in *. intros. punfold H. red in H.\n  enough (exists a, refinesF RPre1 RPost1 RR1 (upaco2 (refines_ RPre1 RPost1 RR1) bot2)\n           (observe phi1) (observe (kphi a))).\n  destruct H0. eexists. pstep. eauto.\n  remember (VisF Spec_exists kphi) as y.\n  hinduction Href before RPre1; intros; inv Heqy; eauto.\n  - inv H. pclearbot. punfold H1. eapply IHHref in H1; eauto.\n    destruct H1. eexists. constructor. eauto.\n  - inv H.\n  - inv H1.\nQed.\n\nLemma paddedF_TauF_hint:\n  forall (E1 : Type -> Type) (R1 : Type) (phi1 : itree_spec E1 R1), paddedF (upaco1 padded_ bot1) (TauF phi1) -> padded phi1.\nProof.\n  intros E1 R1 phi1. intros. inv H. pclearbot. auto.\nQed.\n\nLemma paddedF_TauF_hint':\n  forall (E1 : Type -> Type) (R1 : Type) (phi1 : itree_spec E1 R1), paddedF (upaco1 padded_ bot1) (TauF phi1) -> paddedF (upaco1 padded_ bot1) (observe phi1).\nProof.\n  intros. pstep_reverse. apply paddedF_TauF_hint. auto.\nQed.\n\nLemma paddedF_VisF_hint:\n  forall (E1 : Type -> Type) (R1 A : Type) (kphi : A -> itree E1 R1)\n     (e : E1 A) ,\n    paddedF (upaco1 padded_ bot1) (VisF e kphi) -> forall a, padded (kphi a).\nProof.\n  intros. pstep. red.\n  inv H. inj_existT. subst. constructor. auto.\nQed.\n\nLemma paddedF_VisF_hint':\n  forall (E1 : Type -> Type) (R1 A : Type) (kphi : A -> itree E1 R1)\n     (e : E1 A) ,\n    paddedF (upaco1 padded_ bot1) (VisF e kphi) -> forall a, paddedF (upaco1 padded_ bot1) (observe (kphi a)).\nProof.\n  pstep_reverse. apply paddedF_VisF_hint.\nQed.\n\nLemma padded_Tau_hint:\n  forall (E3 : Type -> Type) (R3 X : Type) (k1 : X -> itree_spec E3 R3) (b : X), (forall a : X, paco1 padded_ bot1 (k1 a)) -> padded (Tau (k1 b)).\nProof.\n  intros E3 R3 X k1 b.\n  intros. pstep. constructor. left. auto.\nQed.\n\nLemma paddedF_Tau_inv_hint:\n  forall (E1 : Type -> Type) (R1 : Type) (phi1 : itree_spec E1 R1),\n    paddedF (upaco1 padded_ bot1) (observe phi1) -> paddedF (upaco1 padded_ bot1) (TauF phi1).\nProof.\n  intros. constructor. left. pstep. auto.\nQed.\n\nLemma paddedF_Tau_Vis_hint:\n  forall (E2 : Type -> Type) (R2 A0 : Type) (a : A0) (kphi0 : A0 -> itree E2 R2) (phi2 : itree E2 R2)\n   (e : E2 A0)\n\n  ,\n    paddedF (upaco1 padded_ bot1) (TauF phi2) -> VisF e kphi0 = observe phi2 -> paddedF (upaco1 padded_ bot1) (TauF (kphi0 a)).\nProof.\n  intros. inv H. pclearbot. punfold H2. red in H2. rewrite <- H0 in H2.\n  inv H2. inj_existT. subst. constructor. left. pstep. constructor. auto.\nQed.\n\nLemma paddedF_TauF_TauF_hint:\n  forall (E1 : Type -> Type) (R1 : Type) (phi phi1 : itree_spec E1 R1),\n    paddedF (upaco1 padded_ bot1) (TauF phi1) -> TauF phi = observe phi1 -> paddedF (upaco1 padded_ bot1) (TauF phi).\nProof.\n  intros. inv H. constructor. left. pclearbot. punfold H2. red in H2.\n  rewrite <- H0 in H2. inv H2. pclearbot. auto.\nQed.\n#[local] Hint Resolve paddedF_TauF_hint : solve_padded.\n#[local] Hint Resolve paddedF_TauF_hint' : solve_padded.\n#[local] Hint Resolve paddedF_VisF_hint : solve_padded.\n#[local] Hint Resolve paddedF_VisF_hint' : solve_padded.\n#[local] Hint Constructors rcompose : solve_padded.\n#[local] Hint Resolve padded_Tau_hint : solve_padded.\n#[local] Hint Unfold padded : solve_padded.\n#[local] Hint Unfold padded_ : solve_padded.\n#[local] Hint Resolve paddedF_Tau_inv_hint : solve_padded.\n#[local] Hint Resolve paddedF_Tau_Vis_hint : solve_padded.\n#[local] Hint Resolve  paddedF_TauF_TauF_hint : solve_padded.\n\n\nLemma refines_eutt_padded_l_tau_aux:\n  forall (E2 : Type -> Type) (R2 : Type) (E1 : Type -> Type)\n    (R1 : Type) (RPre : PreRel E1 E2)\n    (RPost : PostRel E1 E2) (RR : R1 -> R2 -> Prop)\n    (r : itree_spec E1 R1 -> itree_spec E2 R2 -> Prop)\n    (m1 m2 : itree_spec E1 R1) (t3 : itree_spec E2 R2),\n    (forall (t1 t2 : itree_spec E1 R1) (t4 : itree_spec E2 R2),\n        padded t2 ->\n        padded t4 -> t1 ≈ t2 -> refines RPre RPost RR t1 t4 -> r t2 t4) ->\n    paco2 (eqit_ eq true true id) bot2 m1 m2 ->\n    paddedF (upaco1 padded_ bot1) (TauF m2) ->\n    paddedF (upaco1 padded_ bot1) (observe t3) ->\n    refinesF RPre RPost RR (upaco2 (refines_ RPre RPost RR) bot2)\n             (TauF m1) (observe t3) ->\n    refinesF RPre RPost RR (upaco2 (refines_ RPre RPost RR) r)\n             (TauF m2) (observe t3).\nProof.\n  intros E2 R2 E1 R1 RPre RPost RR r m1 m2 t3.\n  intros CIH REL Hpad2 Hpad3 Href.\n  remember (observe t3) as ot3. clear Heqot3 t3.\n  assert (HDEC : (exists t4, ot3 = TauF t4) \\/ (forall t4, ot3 <> TauF t4)).\n  { destruct ot3; eauto; right; repeat intro; discriminate. }\n  destruct HDEC as [ [t4 Ht4] |  Ht3]; subst.\n  {\n    constructor. right. eapply CIH; eauto. inv Hpad2. pclearbot. auto.\n    inv Hpad3. pclearbot. auto.\n    apply refines_TauL_inv. apply refines_TauR_inv. pstep. auto.\n  }\n  destruct ot3; try (exfalso; eapply Ht3; eauto; fail); try destruct e.\n  + inv Href. constructor. punfold REL. red in REL.\n    remember (RetF r0) as y. hinduction H0 before r; intros; inv Heqy; subst; eauto.\n    * remember (RetF r1) as x. hinduction REL before r; intros; inv Heqx; subst; eauto.\n    * eapply IHrefinesF; eauto. pstep_reverse. setoid_rewrite <- (tau_eutt phi).\n      pstep. auto.\n    * inv Hpad2. pclearbot. punfold H1. red in H1.\n      remember (VisF Spec_forall kphi) as x. hinduction REL before r; intros; inv Heqx; inj_existT; subst; eauto.\n      econstructor. eapply IHrefinesF; eauto. pclearbot. pstep_reverse.\n      constructor. inv H1. inj_existT. subst. left. pstep. constructor. auto.\n      constructor. eapply  IHREL; eauto. inv H1. pclearbot. pstep_reverse.\n    * inv Hpad2. pclearbot. punfold H2. red in H2.\n      remember (VisF Spec_exists kphi) as x. hinduction REL before r; intros; inv Heqx; inj_existT; subst; eauto.\n      econstructor. intros. eapply H0; eauto. pclearbot. pstep_reverse.\n      inv H2. inj_existT. subst. constructor. left. pstep. constructor. auto.\n      constructor. eapply IHREL; eauto. inv H2. pclearbot. pstep_reverse.\n  + inv Href. constructor.\n    inv Hpad2. pclearbot. punfold H1. red in H1. punfold REL. red in REL.\n    inv Hpad3. inj_existT. subst.\n    remember (VisF (Spec_vis e) (fun a : X => Tau (k1 a))) as y.\n    hinduction H0 before r; intros; inv Heqy; inj_existT; subst.\n    * eapply IHrefinesF; eauto. pstep_reverse. rewrite <- (tau_eutt phi). pstep. auto.\n    * remember (VisF (Spec_vis e1) kphi1) as y.\n      hinduction REL before r; intros; inv Heqy; inj_existT; subst.\n      -- pclearbot. constructor; auto. intros. eapply H0 in H3.\n         right. eapply CIH; eauto. inv H1. inj_existT. subst. pstep. constructor. auto.\n         pstep. constructor. left. auto.\n         apply REL. destruct H3; auto. contradiction.\n      -- constructor. eapply IHREL; eauto.\n         inv H1. pclearbot. pstep_reverse.\n    * remember (VisF Spec_forall kphi) as x.\n      hinduction REL before r; intros; inv Heqx; inj_existT; subst.\n      -- econstructor. eapply IHrefinesF; eauto. pclearbot. pstep_reverse.\n         inv H1; inj_existT; subst. constructor. auto.\n      -- constructor. eapply IHREL; eauto. inv H1. pclearbot. pstep_reverse.\n    * remember (VisF Spec_exists kphi) as x.\n      hinduction REL before r; intros; inv Heqx; inj_existT; subst.\n      -- econstructor. intros. eapply H0; eauto. pclearbot. pstep_reverse.\n         inv H1; inj_existT; subst. constructor. auto.\n      -- constructor. eapply IHREL; eauto. inv H1. pclearbot. pstep_reverse.\n  + inv Hpad3. inj_existT. subst. apply refines_forallR. intros. constructor.\n    right. eapply CIH; pclearbot; eauto.\n    inv Hpad2. pclearbot. auto. apply H0.\n    assert (refines RPre RPost RR (Tau m1) (Vis Spec_forall (fun a => Tau (k1 a)))).\n    pstep. auto. apply refines_TauL_inv in H. eapply refines_Vis_forallR in H.\n    apply refines_TauR_inv. eauto.\n  + inv Hpad3. inj_existT. subst.\n    assert ( refinesF RPre RPost RR\n                      (upaco2 (refines_ RPre RPost RR) bot2)\n                      (observe m1)\n                      (VisF Spec_exists (fun a : X => Tau (k1 a))) ).\n    { rewrite itree_eta'. pstep_reverse. apply refines_TauL_inv. pstep. auto. }\n    clear Href. rename H into Href. pclearbot.\n    eapply refinesF_Vis_existsR in Href. punfold REL. red in REL.\n    hinduction Href before r; intros; eauto.\n    * eapply refines_existsR. constructor. right.\n      eapply CIH; eauto. inv Hpad2. pclearbot. auto.\n      Unshelve. all : try apply a; try apply (go phi).\n      apply H0. pstep. auto. apply refines_TauR_inv. pstep. auto.\n    * inv Hpad2. pclearbot. punfold H1. red in H1.\n      remember (VisF Spec_forall kphi1) as x. remember (observe m2) as om2.\n      hinduction REL before r; intros; inv Heqx; inj_existT; subst.\n      -- inv H1. inj_existT. subst. constructor. rewrite <- Heqom2.\n         econstructor. Unshelve. all : auto. cbn. eapply IHHref; eauto.\n         pclearbot. setoid_rewrite tau_eutt in REL. pstep_reverse.\n         constructor. auto.\n      -- constructor. rewrite <- Heqom2. inv H1. pclearbot. punfold H2.\n    * inv Hpad2. pclearbot. punfold H3. red in H3.\n      remember (VisF Spec_exists kphi1) as x. remember (observe m2) as om2.\n      hinduction REL before r; intros; inv Heqx; inj_existT; subst.\n      -- inv H3. inj_existT. subst. constructor. intros.\n         rewrite <- Heqom2. constructor. intros. eapply H0; eauto. Unshelve. all : auto.\n         pclearbot. pstep_reverse.  setoid_rewrite tau_eutt in REL. auto.\n         constructor. auto.\n      -- constructor. rewrite <- Heqom2.\n         eapply IHREL; eauto. inv H3. pclearbot. pstep_reverse.\n    * eapply IHHref; eauto. pstep_reverse. rewrite <- (tau_eutt phi1). pstep. auto.\nQed.\n\n(* Print Assumptions refines_eutt_padded_l_tau_aux. *)\n\nLemma refines_eutt_padded_l E1 E2 R1 R2 RPre RPost RR :\n  forall (t1 t2 : itree_spec E1 R1) (t3 : itree_spec E2 R2),\n    padded t2 -> padded t3 -> t1 ≈ t2 ->\n    refines RPre RPost RR t1 t3 -> refines RPre RPost RR t2 t3.\nProof.\n  pcofix CIH. intros t1 t2 t3 Hpad2 Hpad3 Heutt Href.\n  punfold Hpad2. red in Hpad2.\n  punfold Hpad3. red in Hpad3.\n  punfold Heutt. red in Heutt.\n  punfold Href. red in Href. pstep.\n  red.\n  hinduction Heutt before r; intros; pclearbot; eauto.\n  - subst. rewrite itree_eta' at 1. pstep_reverse.\n    eapply paco2_mon; [ pstep; eapply Href | intros; contradiction].\n  - eapply refines_eutt_padded_l_tau_aux; eauto.\n  - destruct e.\n    + remember (VisF (Spec_vis e) k1) as x.\n      hinduction Href before r; intros; inv Heqx; inj_existT; subst; eauto.\n      * constructor. eapply IHHref; eauto. inv Hpad3. pclearbot. pstep_reverse.\n      * constructor; auto. intros. eapply H0 in H1.\n        right. eapply CIH; eauto. inv Hpad2. inj_existT. subst.\n        pstep. constructor. auto.\n        inv Hpad3. inj_existT. subst. pstep. constructor. auto.\n        pclearbot. apply REL. destruct H1; auto. contradiction.\n      * constructor. intros. eapply H0; eauto.\n        inv Hpad3. inj_existT. subst. constructor. auto.\n      * econstructor. eapply IHHref; eauto.\n        inv Hpad3. inj_existT. subst. constructor. auto.\n    + inv Hpad2. inj_existT. subst. pclearbot.\n      eapply refinesF_Vis_forallL in Href.\n      induction Href.\n      * constructor. intros. eapply H1.\n        inv Hpad3. inj_existT. subst. constructor. auto.\n      * econstructor. Unshelve. all : auto.\n        rewrite itree_eta'.\n        eapply refines_eutt_padded_l_tau_aux; eauto.\n        setoid_rewrite tau_eutt in REL. auto. constructor. left. auto.\n\n      * eapply refines_existsR. eapply IHHref; eauto. inv Hpad3.\n        inj_existT. subst. constructor. auto.\n      * constructor. eapply IHHref. inv Hpad3. pclearbot. pstep_reverse.\n    + inv Hpad2. inj_existT. subst.\n      (* this should be fine, exists L is invertible and then I just\n         further invert Href until I learn more about t3\n       *)\n      constructor. intros.\n      assert (forall a, refinesF RPre RPost RR (upaco2 (refines_ RPre RPost RR) bot2) (observe (k1 a)) (observe t3)).\n      intros. pstep_reverse. eapply refines_Vis_existsL. pstep. auto.\n      clear Href. rename H into Href. specialize (Href a).\n      eapply refines_eutt_padded_l_tau_aux; eauto.\n      setoid_rewrite tau_eutt in REL. auto.\n      constructor. auto.\n  - eapply IHHeutt; eauto.\n    pstep_reverse. apply refines_TauL_inv. pstep. auto.\n  - constructor. eapply IHHeutt; eauto. inv Hpad2. pclearbot. pstep_reverse.\nQed.\n\n\nLemma refines_eutt_padded_r_tau_aux:\n  forall (E2 : Type -> Type) (R2 : Type) (E1 : Type -> Type)\n    (R1 : Type) (RPre : PreRel E1 E2)\n    (RPost : PostRel E1 E2) (RR : R1 -> R2 -> Prop)\n    (r : itree_spec E1 R1 -> itree_spec E2 R2 -> Prop)\n    (m1 m2 : itree_spec E2 R2) (t1 : itree_spec E1 R1),\n    refinesF RPre RPost RR (upaco2 (refines_ RPre RPost RR) bot2)\n             (observe t1) (TauF m1) ->\n    paddedF (upaco1 padded_ bot1) (TauF m2) ->\n    paddedF (upaco1 padded_ bot1) (observe t1) ->\n    paco2 (eqit_ eq true true id) bot2 m1 m2 ->\n    (forall (t2 : itree_spec E1 R1) (t3 t4 : itree_spec E2 R2),\n        padded t2 ->\n        padded t4 -> t3 ≈ t4 -> refines RPre RPost RR t2 t3 -> r t2 t4) ->\n    refinesF RPre RPost RR (upaco2 (refines_ RPre RPost RR) r)\n             (observe t1) (TauF m2).\nProof.\n  intros E2 R2 E1 R1 RPre RPost RR r m1 m2 t1.\n  intros Href Hpad3 Hpad1 REL CIH.\n  remember (observe t1) as ot1. clear Heqot1 t1.\n  assert (HDEC : (exists t4, ot1 = TauF t4) \\/ (forall t4, ot1 <> TauF t4)).\n  { destruct ot1; eauto; right; repeat intro; discriminate. }\n  destruct HDEC as [ [t4 Ht4] | Ht1]; subst.\n  { constructor. right. eapply CIH; eauto. inv Hpad1. pclearbot. auto.\n    inv Hpad3. pclearbot. auto. apply refines_TauL_inv.\n    apply refines_TauR_inv. pstep. auto. }\n  destruct ot1; try (exfalso; eapply Ht1; eauto; fail); try destruct e.\n  - inv Href. constructor. remember (RetF r0) as x.\n    punfold REL. red in REL. hinduction H1 before r; intros; inv Heqx; subst; eauto.\n    + remember (RetF r2) as x. hinduction REL before r; intros; inv Heqx; subst; eauto.\n    + eapply IHrefinesF; eauto. pstep_reverse. rewrite <- (tau_eutt phi).\n      pstep. auto.\n    + inv Hpad3. pclearbot. punfold H2. red in H2.\n      remember (VisF Spec_forall kphi) as x.\n      hinduction REL before r; intros; inv Heqx; inj_existT; subst; pclearbot.\n      constructor. intros. eapply H0; eauto.  inv H2. inj_existT.\n      subst. constructor. left. pstep. constructor. auto.\n      pstep_reverse. constructor. eapply IHREL; eauto. inv H2. pclearbot. punfold H3.\n    + inv Hpad3. pclearbot. punfold H0. red in H0.\n      remember (VisF Spec_exists kphi) as x.\n      hinduction REL before r; intros; inv Heqx; inj_existT; subst; pclearbot.\n      econstructor. Unshelve. all : auto. intros. eapply IHrefinesF; eauto.  inv H0. inj_existT.\n      subst. constructor. left. pstep. constructor. auto.\n      pstep_reverse. constructor. eapply IHREL; eauto. inv H0. pclearbot. pstep_reverse.\n  - inv Href. constructor. remember (VisF (Spec_vis e) k) as x.\n    inv Hpad3. pclearbot. punfold H0. red in H0. punfold REL. red in REL.\n    remember (VisF (Spec_vis e) k) as x.\n    hinduction H1 before r; intros; inv Heqx; inj_existT; subst.\n    + eapply IHrefinesF; eauto. pstep_reverse. setoid_rewrite <- (tau_eutt phi).\n      pstep. auto.\n    + remember (VisF (Spec_vis e2) kphi2) as x.\n      hinduction REL before r; intros; inv Heqx; inj_existT; subst.\n      * constructor; auto. intros. eapply H0 in H2. right.\n        eapply CIH; eauto. inv Hpad1. inj_existT. subst. pstep.\n        constructor. auto. inv H1. inj_existT. subst. pstep. constructor.\n        auto. pclearbot. apply REL. destruct H2; auto. contradiction.\n      * constructor. eapply IHREL; eauto. inv H1. pclearbot. pstep_reverse.\n   + remember (VisF Spec_forall kphi) as x.\n     hinduction REL before r; intros; inv Heqx; inj_existT; subst.\n     * constructor; intros. eapply H0; eauto. pclearbot. pstep_reverse.\n       inv H1. inj_existT. subst. constructor. auto.\n     * constructor. eapply IHREL; eauto. inv H1. pclearbot. pstep_reverse.\n   + remember (VisF Spec_exists kphi) as x.\n     hinduction REL before r; intros; inv Heqx; inj_existT; subst.\n     * econstructor; intros. Unshelve. all : auto. eapply IHrefinesF; eauto. pclearbot. pstep_reverse.\n       inv H0. inj_existT. subst. constructor. auto.\n     * constructor. eapply IHREL; eauto. inv H0. pclearbot. pstep_reverse.\n  - inv Hpad1. inj_existT. subst.\n    assert (refines RPre RPost RR (Vis Spec_forall (fun a => Tau (k1 a))) m1).\n    { apply refines_TauR_inv. pstep. auto. }\n    clear Href. rename H into Href.\n    punfold Href. red in Href. inv Hpad3. pclearbot. punfold H1. red in H1.\n    apply refinesF_Vis_forallL in Href. punfold REL. red in REL.\n    hinduction Href before r; intros; pclearbot.\n    + constructor. remember (VisF Spec_forall kphi2) as x.\n      hinduction REL before r; intros; inv Heqx; inj_existT; subst.\n      * inv H2. inj_existT. subst. constructor. intros. eapply H0; auto.\n        Unshelve. all : auto. pclearbot. setoid_rewrite tau_eutt in REL. pstep_reverse.\n        pclearbot. pstep_reverse.\n      * constructor. eapply IHREL; eauto. inv H2. pclearbot. pstep_reverse.\n    + eapply refines_forallL. Unshelve. all : auto. constructor.\n      right. eapply CIH; eauto. apply H0. pstep. auto.\n      rewrite (itree_eta' phi) in REL. pstep. eauto.\n      apply refines_TauL_inv. pstep. auto.\n    + constructor. remember (VisF Spec_exists kphi2) as x.\n      hinduction REL before r; intros; inv Heqx; inj_existT; subst.\n      * inv H1. inj_existT. subst. eapply refines_existsR.\n        Unshelve. all : auto. cbn. eapply IHHref; eauto.\n        pclearbot. setoid_rewrite tau_eutt in REL.\n        pstep_reverse. pclearbot. pstep_reverse.\n      * constructor. eapply IHREL; eauto. inv H1. pclearbot.\n        pstep_reverse.\n    + eapply IHHref; eauto. pstep_reverse. setoid_rewrite <- (tau_eutt phi2).\n      pstep. auto.\n  - inv Hpad1. inj_existT. subst.\n    apply refines_existsL. intros. constructor. right. eapply CIH; eauto.\n    pclearbot. apply H0. inv Hpad3. pclearbot. auto.\n    assert (refines RPre RPost RR (Vis Spec_exists (fun a => Tau (k1 a))) (Tau m1)).\n    pstep. auto.\n    eapply refines_Vis_existsL in H. apply refines_TauL_inv. apply refines_TauR_inv.\n    eauto.\nQed.\n\n\nLemma refines_eutt_padded_r E1 E2 R1 R2 RPre RPost RR :\n  forall (t1 : itree_spec E1 R1) (t2 t3 : itree_spec E2 R2),\n    padded t1 -> padded t3 -> t2 ≈ t3 ->\n    refines RPre RPost RR t1 t2 -> refines RPre RPost RR t1 t3.\nProof.\n  pcofix CIH. intros t1 t2 t3 Hpad1 Hpad3 Heutt Href.\n  punfold Href. punfold Heutt. red in Heutt. red in Href.\n  punfold Hpad1. red in Hpad1. punfold Hpad3. red in Hpad3.\n  pstep. red. hinduction Heutt before r; intros; pclearbot.\n  - subst. rewrite itree_eta'. pstep_reverse.\n    eapply paco2_mon; [ pstep; eapply Href | intros; contradiction].\n  - eapply refines_eutt_padded_r_tau_aux; eauto.\n  - destruct e.\n    + remember (VisF (Spec_vis e) k1) as y.\n      hinduction Href before r; intros; inv Heqy; inj_existT; subst; eauto.\n      * constructor. eapply IHHref; eauto. inv Hpad1. pstep_reverse.\n        pclearbot. auto.\n      * constructor; auto. intros. eapply H0 in H1.\n        right. eapply CIH; eauto.\n        inv Hpad1. inj_existT. subst. pstep. constructor. auto.\n        inversion Hpad3. inj_existT. subst. pstep. constructor. auto.\n        apply REL. destruct H1; auto. contradiction.\n      * econstructor. eapply IHHref; eauto.\n        inv Hpad1. inj_existT. subst. constructor. auto.\n      * constructor. intros. eapply H0; eauto.\n        inv Hpad1. inj_existT. subst. constructor. auto.\n    + inv Hpad3. inj_existT. subst.\n      constructor. intros.\n      eapply refines_eutt_padded_r_tau_aux with (m1 := k1 a); auto.\n      constructor. pstep_reverse. apply refines_Vis_forallR. pstep. auto.\n      constructor. auto. setoid_rewrite tau_eutt in REL. auto.\n    + eapply refinesF_Vis_existsR in Href.\n      hinduction Href before r; intros; eauto.\n      * econstructor. inv Hpad3. inj_existT. subst.\n        Unshelve. all : auto. cbn.\n        rewrite itree_eta' at 1.\n        eapply refines_eutt_padded_r_tau_aux; auto. eauto.\n        constructor. auto. setoid_rewrite tau_eutt in REL. auto.\n      * eapply refines_forallL. eapply IHHref; eauto.\n        inv Hpad1. inj_existT. subst. constructor. auto.\n      * apply refines_existsL. intros. eapply H0; eauto.\n        inv Hpad1. inj_existT. subst. constructor. auto.\n      * constructor. eapply IHHref; eauto. inv Hpad1. pclearbot. pstep_reverse.\n  - eapply IHHeutt; eauto. pstep_reverse. apply refines_TauR_inv. pstep. auto.\n  - constructor. eapply IHHeutt; eauto. inv Hpad3. pclearbot. pstep_reverse.\nQed.\n\n\n(* so whats next, *)\n(* Transitivity of refinement if the LHS is concrete *)\nTheorem refinesTrans {E1 E2 E3 R1 R2 R3} RPre1 RPre2 RPost1 RPost2\n        (RR1 : R1 -> R2 -> Prop) (RR2 : R2 -> R3 -> Prop)\n        (t1 : itree_spec E1 R1) (t2 : itree_spec E2 R2) (t3 : itree_spec E3 R3):\n  padded t1 -> padded t2 -> padded t3 ->\n  refines RPre1 RPost1 RR1 t1 t2 -> refines RPre2 RPost2 RR2 t2 t3 ->\n  refines (rcomposePreRel RPre1 RPre2) (rcomposePostRel RPost1 RPost2\n                                  (fun A B C e1 e2 e3 => RPre1 A B e1 e2 /\\ RPre2 B C e2 e3))\n          (rcompose RR1 RR2) t1 t3.\nProof.\n  revert t1 t2 t3; pcofix CIH.\n  intros t1 t2 t3  Ht1 Ht2 Ht3 Ht12 Ht23.\n  pfold. red. punfold Ht12. red in Ht12.\n  punfold Ht23. red in Ht23. punfold Ht3. red in Ht3.\n  punfold Ht2. red in Ht2.\n  punfold Ht1. red in Ht1.\n  remember (observe t3) as ot3.  clear t3 Heqot3.\n  remember (observe t1) as ot1. clear t1 Heqot1.\n  hinduction Ht12 before r; intros.\n  - remember (RetF r2) as x. clear Ht2 Ht3.\n    hinduction Ht23 before r; intros; inv Heqx; eauto.\n    constructor. econstructor; eauto.\n  - pclearbot.\n    assert (Hdec : (exists t4, ot3 = TauF t4) \\/ (forall t4, ot3 <> TauF t4)).\n    { destruct ot3; eauto; right; repeat intro; discriminate. }\n    destruct Hdec as [ [t4 Ht4] | Ht4 ]; subst.\n    + constructor. right. eapply CIH; eauto with solve_padded.\n      apply refines_TauL_inv. apply refines_TauR_inv. pstep. auto.\n    + destruct ot3; try (exfalso; eapply Ht4; eauto; fail).\n      * constructor. inv Ht23. clear Ht2 Ht3.\n        inv Ht1. pclearbot. punfold H2.\n        red in H2.\n        punfold H. red in H. remember (RetF r0) as y.\n        remember (observe phi2) as ophi2.\n        hinduction H1 before r; intros; inv Heqy; eauto with solve_padded.\n        -- remember (RetF r1) as y.\n           remember (observe phi1) as ophi1. clear Heqophi1.\n           hinduction H0 before r; intros; inv Heqy; eauto with solve_padded.\n        -- eapply IHrefinesF; eauto.\n           pstep_reverse. apply refines_TauR_inv. pstep. auto.\n        -- eapply IHrefinesF; eauto. pstep_reverse.\n           eapply refines_Vis_forallR. pstep. auto.\n        -- eapply refinesF_Vis_existsR in H1.\n           induction H1; eauto with solve_padded.\n           rewrite itree_eta' at 1. eapply H0; eauto with solve_padded.\n      * inv Ht3. inj_existT. subst.\n        {\n          destruct e; pclearbot.\n          - inv Ht23. constructor.\n            punfold H. red in H.\n            pclearbot.\n            remember ((VisF (Spec_vis e) (fun a : X => Tau (k1 a)))) as y.\n            remember (observe phi2) as ophi2.\n            remember (observe phi1) as ophi1.\n            hinduction H2 before r; intros; inv Heqy; inj_existT; subst; eauto.\n            + eapply IHrefinesF; eauto. pstep_reverse.\n              apply refines_TauR_inv. pstep. auto.\n              inv Ht2. rewrite Heqophi2. pclearbot. pstep_reverse.\n            +  assert (Hkphi1 : forall a, padded (kphi1 a)).\n              {\n                inv Ht2. pclearbot. punfold H4. red in H4. rewrite <- Heqophi2 in H4.\n                inv H4. inj_existT. subst. intros. pstep. constructor. auto.\n              }\n              inv Ht1. pclearbot. punfold H4. red in H4.\n              remember (VisF (Spec_vis e1) kphi1) as y.\n              assert (Hk1 : forall (a : A) (b : X),\n                         RPost2 A X e1 e a b ->\n                         upaco2 (refines_ RPre2 RPost2 RR2) bot2 (kphi1 a) ((k1 b))).\n              intros. apply H0 in H3. clear - H3. pclearbot. left.\n              apply refines_TauR_inv. auto.\n              remember (observe phi1) as ophi1.\n              clear H0 Ht4.\n              hinduction H1 before r; intros; inv Heqy; inj_existT; subst;\n                eauto with solve_padded.\n              constructor. econstructor; eauto.\n              intros a b Hab. inv Hab. inj_existT. subst.\n              specialize (H10 A0 e0 (conj H H1)) as [b' [ Hb1 Hb2 ] ].\n              specialize (H0 _ _ Hb1). pclearbot.\n              specialize (Hk1 _ _ Hb2). pclearbot.\n              right.\n              eapply CIH; eauto with solve_padded.\n              clear - Hk1. pclearbot. pstep. constructor. pstep_reverse.\n           + eapply IHrefinesF; eauto. pstep_reverse. eapply refines_Vis_forallR.\n             pstep. auto. inv Ht2. pclearbot.\n             constructor; auto. punfold H3. red in H3. rewrite <- Heqophi2 in H3.\n             inv H3. inj_existT. subst. left. pstep. constructor. auto.\n           + inv Ht1. pclearbot. punfold H4. red in H4.\n             remember (observe phi1) as ophi1.\n             remember (VisF Spec_exists kphi) as y.\n             hinduction H1 before r; intros; inv Heqy; inj_existT; subst.\n             * constructor. eapply IHrefinesF; eauto with solve_padded.\n             * econstructor. Unshelve. all : auto. eauto with solve_padded.\n             * eapply H0; eauto with solve_padded.\n             * constructor. intros. eauto with solve_padded.\n          - assert (refines RPre2 RPost2 RR2 (Tau phi2) (Vis Spec_forall (fun a => Tau (k1 a)))).\n            pstep. auto.\n            apply refines_forallR. intros. constructor. right.\n            eapply CIH; eauto with solve_padded.\n            apply refines_TauL_inv. apply refines_TauR_inv.\n            eapply refines_Vis_forallR in H0. eauto.\n          - assert (Ht23' : refines RPre2 RPost2 RR2 (Tau phi2) (Vis Spec_exists (fun a => Tau (k1 a)))).\n            pstep. auto. clear Ht23. rename Ht23' into Ht23.\n            apply refines_TauL_inv in Ht23.\n            punfold H. red in H.\n            punfold Ht23. red in Ht23.\n            inv Ht1. pclearbot. punfold H2. red in H2.\n            inv Ht2. pclearbot. punfold H3. red in H3.\n            eapply refinesF_Vis_existsR in Ht23.\n            remember (observe phi1) as ophi1. remember (observe phi2) as ophi2.\n            clear Ht4 t2.\n            remember ((fun a : X => Tau (k1 a))) as k1'.\n            hinduction Ht23 before r; intros; subst.\n            + eapply refines_existsR. Unshelve. all : auto.\n              constructor. right. eapply CIH; eauto with solve_padded.\n              pstep. auto. apply refines_TauR_inv. pstep. auto.\n            + inv H3. inj_existT. subst. pclearbot. cbn in Ht23.\n              assert (Hk0 : forall a, refinesF RPre1 RPost1 RR1 (upaco2 (refines_ RPre1 RPost1 RR1) bot2)\n                                          (observe phi1) (observe (k0 a))).\n              { assert (refines RPre1 RPost1 RR1 phi1 (Vis Spec_forall (fun a => Tau (k0 a)))).\n                pstep. auto. intros. eapply refines_Vis_forallR in H0.\n                apply refines_TauR_inv in H0. pstep_reverse. }\n              clear H. apply refinesF_Vis_existsR_Tau_inv in Ht23.\n              (* I am not sure I got everything right yet but this feels like progress*)\n\n              specialize (Hk0 b). specialize (H4 b). punfold H4. red in H4.\n              clear Heqophi2 phi2. remember (k0 b) as phi2. clear Heqphi2 k0 b.\n              eapply IHHt23; eauto with solve_padded. constructor. auto.\n            + (*phi2 is an exists*) inv H4. inj_existT. subst.\n              (* I need an element of B in order to apply H0, I can potentially get one by inducting on\n                 H1*)\n              apply refinesF_Vis_existsR in H1. clear Heqophi2 phi2.\n              assert (Hk0 : forall b, existsRefinesF RPre2 RPost2 RR2 (upaco2 (refines_ RPre2 RPost2 RR2) bot2)\n                                          (fun a : X => Tau (k1 a)) (observe ((k0 b)))).\n              { intros. apply refinesF_Vis_existsR_Tau_inv. apply H. }\n              clear H.\n              remember (observe phi1) as ophi1. pclearbot.\n              remember (fun a => Tau (k0 a)) as k'.\n              assert (go ophi1 ≈ phi1). subst. rewrite <- itree_eta. reflexivity.\n              assert (Hphi1 : padded phi1).\n              pstep. red. rewrite <- Heqophi1. auto.\n              clear Heqophi1.\n              hinduction H1 before r; intros; subst.\n              * eapply H0; eauto with solve_padded. Unshelve. all : auto.\n                pstep_reverse.\n                eapply refines_eutt_padded_l; eauto with solve_padded.\n                pstep. auto. pstep_reverse. constructor. left. auto.\n              * inv H3. inj_existT. subst.\n                constructor. punfold H. red in H.\n                cbn in H.\n                punfold Hphi1. red in Hphi1.\n                remember (VisF Spec_forall (fun a : B0 => Tau (k2 a))) as x.\n                remember (observe phi1) as ophi1.\n                clear Heqophi1 phi1. pclearbot.\n                remember ((fun a : B0 => Tau (k2 a))) as k2'.\n                hinduction H before r; intros; try (exfalso; inv Heqx; fail).\n                -- pclearbot. subst. inv Heqx. inj_existT. subst.\n                   inv Hphi1. inj_existT. subst.\n                   eapply refines_forallL. Unshelve. all : auto.\n                   eapply IHexistsRefinesF; eauto with solve_padded.\n                   constructor. left. auto. rewrite <- itree_eta.\n                   rewrite REL, tau_eutt. reflexivity. pclearbot. apply H3.\n                -- constructor. eapply IHeqitF; eauto.\n                   inv Hphi1. pclearbot. pstep_reverse.\n              * inv H3. inj_existT. subst. constructor.\n                punfold H4. red in H4. cbn in H4. punfold Hphi1. red in Hphi1.\n                remember ((VisF Spec_exists (fun a : B0 => Tau (k2 a)))) as x.\n                remember ((fun a : B0 => Tau (k2 a))) as k2'.\n                hinduction H4 before r; intros; inv Heqx; inj_existT; subst.\n                -- inv Hphi1. inj_existT. subst. constructor. intros.\n                   cbn. eapply H0; eauto with solve_padded. Unshelve. all : auto.\n                   constructor. auto. rewrite <- itree_eta.\n                   pclearbot. rewrite REL, tau_eutt. reflexivity. pclearbot. apply H4.\n                -- constructor. eapply IHeqitF; eauto with solve_padded. auto.\n              * eapply IHexistsRefinesF; eauto with solve_padded.\n                rewrite <- itree_eta. rewrite <- H. rewrite tau_eutt. reflexivity.\n            + eapply IHHt23; eauto with solve_padded. pstep_reverse.\n              apply refines_TauR_inv. pstep. auto.\n           }\n  - constructor. eapply IHHt12; eauto with solve_padded.\n  - eapply IHHt12; eauto with solve_padded.\n    rewrite itree_eta'. pstep_reverse. apply refines_TauL_inv. pstep. auto.\n  - remember (VisF (Spec_vis e2) kphi2) as x.\n    hinduction Ht23 before r; intros; inv Heqx; inj_existT; subst; eauto.\n    + constructor. eapply IHHt23; eauto. inv Ht3. pclearbot. punfold H2.\n    + pclearbot. constructor; eauto. econstructor; eauto.\n      intros. right.\n      inv H3. inj_existT. subst.\n      assert (exists b0 : B0, RPost1 A0 B0 e0 e3 a b0 /\\ RPost2 B0 B e3 e2 b0 b).\n      eapply H10; eauto. destruct H3 as [b0 [Hb01 Hb02] ]. pclearbot.\n      eapply CIH with (t2 := kphi3 b0); eauto with solve_padded.\n      * apply H2 in Hb01. clear - Hb01. pclearbot. auto.\n      * eapply H0 in Hb02. clear - Hb02. pclearbot. auto.\n    + constructor. intros. eapply H0; eauto. inv Ht3. inj_existT.\n      subst. constructor. left. pclearbot. auto.\n    + econstructor. eapply IHHt23; eauto. inv Ht3. inj_existT. subst.\n      constructor. auto.\n  - remember (refinesF_Vis_forallL _ _ _ _ _ _ _ _ _ _ _ Ht23) as Ht23'.\n    clear HeqHt23' Ht23. induction Ht23'; pclearbot.\n    * apply refines_forallR. intro b. apply H2.\n      inv Ht3. inj_existT. subst. constructor. auto.\n    * eapply H0; eauto. inv Ht2. inj_existT. subst. constructor. auto.\n    * econstructor. eapply IHHt23'; eauto. inv Ht3. inj_existT. subst. constructor.\n      auto.\n    * constructor. eapply IHHt23'; eauto. inv Ht3. pclearbot. pstep_reverse.\n  - econstructor. Unshelve. all : auto. eapply IHHt12; eauto with solve_padded.\n  - eapply IHHt12; eauto. inv Ht2. inj_existT. subst. constructor. auto.\n    rewrite itree_eta'.\n    pstep_reverse. apply refines_Vis_existsL. pstep. auto.\n  - constructor. intros. eapply H0; eauto with solve_padded.\nQed.\n\nLemma refines_monot E1 E2 R1 R2 RPre1 RPre2 RPost1 RPost2 RR1 RR2 :\n  (forall A B, RPre1 A B <2= RPre2 A B) ->\n  (forall A B (ea : E1 A) (eb : E2 B), RPost2 A B ea eb <2= RPost1 A B ea eb) ->\n  RR1 <2= RR2 ->\n  forall (phi1 : itree_spec E1 R1) (phi2 : itree_spec E2 R2),\n    refines RPre1 RPost1 RR1 phi1 phi2 ->\n    refines RPre2 RPost2 RR2 phi1 phi2.\nProof.\n  intros HRe HReAns HRR. pcofix CIH. intros phi1 phi2 Hphi.\n  pstep. red. punfold Hphi. red in Hphi. hinduction Hphi before r; intros; pclearbot; eauto.\n  constructor; auto. intros a b Heab.\n  apply HReAns in Heab. apply H0 in Heab. pclearbot.\n  right. auto.\nQed.\n\n\n\nDefinition padded_refines {E1 E2 R1 R2} RPre RPost RR (phi1 : itree_spec E1 R1) (phi2 : itree_spec E2 R2) :=\n  refines RPre RPost RR (pad phi1) (pad phi2).\n\nLemma padded_refines_monot E1 E2 R1 R2 RPre1 RPre2 RPost1 RPost2 RR1 RR2 :\n  (forall A B, RPre1 A B <2= RPre2 A B) ->\n  (forall A B (ea : E1 A) (eb : E2 B), RPost2 A B ea eb <2= RPost1 A B ea eb) ->\n  RR1 <2= RR2 ->\n  forall (phi1 : itree_spec E1 R1) (phi2 : itree_spec E2 R2),\n    padded_refines RPre1 RPost1 RR1 phi1 phi2 ->\n    padded_refines RPre2 RPost2 RR2 phi1 phi2.\nProof.\n  intros. eapply refines_monot; eauto.\nQed.\n\nGlobal Instance padded_refines_proper_eutt {E1 E2 R1 R2} RPre RPost RR : Proper (eutt eq ==> eutt eq ==> flip impl)  (@padded_refines E1 E2 R1 R2 RPre RPost RR).\nProof.\n  intros t1 t2 Ht12 t3 t4 Ht34 Href. red. red in Href.\n  eapply refines_eutt_padded_r; try apply pad_is_padded.\n  setoid_rewrite pad_eutt in Ht34.\n  symmetry. eauto.\n  eapply refines_eutt_padded_l; try apply pad_is_padded.\n  setoid_rewrite pad_eutt in Ht12.\n  symmetry. eauto. auto.\nQed.\n\nLtac use_simpobs := repeat match goal with\n                           | H : RetF _ = observe ?t |- _ => apply simpobs in H\n                           | H : TauF _ = observe ?t |- _ => apply simpobs in H\n                           | H : VisF _ _ = observe ?t |- _ => apply simpobs in H\n                           end.\n\nInstance eq_itree_refines_Proper1 {E1 E2 R1 R2 RPre RPost RR r} : Proper (eq_itree eq ==> eq_itree eq ==> flip impl)\n                                                           (@refines_ E1 E2 R1 R2 RPre RPost RR (upaco2 (refines_ RPre RPost RR) r)).\nProof.\n  repeat intro. apply bisimulation_is_eq in H. apply bisimulation_is_eq in H0.\n  subst. auto.\nQed.\n\nInstance eq_itree_refines_Proper2 {E1 E2 R1 R2 RPre RPost RR r} : Proper (eq_itree eq ==> eq_itree eq ==> flip impl)\n                                                           (paco2 (@refines_ E1 E2 R1 R2 RPre RPost RR) r).\nProof.\n  repeat intro. apply bisimulation_is_eq in H. apply bisimulation_is_eq in H0.\n  subst. auto.\nQed.\n\nTheorem refines_bind {E1 E2 R1 R2 S1 S2} RPre RPost RR RS\n        (t1 : itree_spec E1 R1) (t2 : itree_spec E2 R2)\n        (k1 : R1 -> itree_spec E1 S1)\n        (k2 : R2 -> itree_spec E2 S2) :\n  refines RPre RPost RR t1 t2 -> (forall r1 r2, RR r1 r2 -> refines RPre RPost RS (k1 r1) (k2 r2)) ->\n  refines RPre RPost RS (ITree.bind t1 k1) (ITree.bind t2 k2).\nProof.\n  revert t1 t2. pcofix CIH.\n  intros t1 t2 Ht12 Hk12. punfold Ht12. red in Ht12.\n  remember (observe t1) as ot1. remember (observe t2) as ot2.\n  hinduction Ht12 before r; intros; use_simpobs.\n  - cbn. rewrite Heqot1, Heqot2. setoid_rewrite bind_ret_l.\n    eapply paco2_mon; [apply Hk12; auto | intros; contradiction] .\n  - rewrite Heqot1, Heqot2. repeat rewrite bind_tau. pstep. constructor.\n    right. pclearbot. eapply CIH; eauto.\n  - rewrite Heqot1, bind_tau. pstep. constructor.\n    pstep_reverse.\n  - rewrite Heqot2, bind_tau. pstep. constructor. pstep_reverse.\n  - pclearbot. rewrite Heqot1, Heqot2. repeat rewrite bind_vis.\n    pstep. constructor; auto. intros. right. eapply CIH; eauto.\n\n    apply H0 in H1. pclearbot. auto.\n (* - rewrite Heqot1, Heqot2. repeat rewrite bind_vis. pstep. constructor.\n    right. eapply CIH; eauto. pclearbot. apply H.\n  - rewrite Heqot1, Heqot2. repeat rewrite bind_vis. pstep. constructor.\n    right. eapply CIH; eauto. pclearbot. apply H. *)\n  - rewrite Heqot2. rewrite bind_vis. pstep. constructor. intros.\n    pstep_reverse.\n  - rewrite Heqot1. rewrite bind_vis. pstep. econstructor.\n    pstep_reverse.\n  - rewrite Heqot2. rewrite bind_vis. pstep. econstructor. pstep_reverse.\n  - rewrite Heqot1. rewrite bind_vis. pstep. econstructor.\n    pstep_reverse.\nQed.\n\nTheorem padded_refines_bind {E1 E2 R1 R2 S1 S2} RPre RPost RR RS\n        (t1 : itree_spec E1 R1) (t2 : itree_spec E2 R2)\n        (k1 : R1 -> itree_spec E1 S1)\n        (k2 : R2 -> itree_spec E2 S2) :\n  padded_refines RPre RPost RR t1 t2 -> (forall r1 r2, RR r1 r2 -> padded_refines RPre RPost RS (k1 r1) (k2 r2)) ->\n  padded_refines RPre RPost RS (ITree.bind t1 k1) (ITree.bind t2 k2).\nProof.\n  unfold padded_refines.\n  setoid_rewrite pad_bind. intros. eapply refines_bind; eauto.\nQed.\n\n\n(*key lemma for iter here *)\nLemma refines_iter_bind_aux:\n  forall (E1 E2 : Type -> Type) (S2 S1 R1 R2 : Type)\n    RPre RPost\n    (RR : R1 -> R2 -> Prop) (RS : S1 -> S2 -> Prop)\n    (k1 : R1 -> itree_spec E1 (R1 + S1))\n    (k2 : R2 -> itree_spec E2 (R2 + S2))\n    (r : itree_spec E1 S1 -> itree_spec E2 S2 -> Prop),\n    (forall (r1 : R1) (r2 : R2),\n        RR r1 r2 -> r (ITree.iter k1 r1) (ITree.iter k2 r2)) ->\n    forall (phi1 : itree_spec E1 (R1 + S1)) (phi2 : itree_spec E2 (R2 + S2)),\n      refines RPre RPost (HeterogeneousRelations.sum_rel RR RS) phi1 phi2 ->\n      paco2 (refines_ RPre RPost RS) r\n            (phi1 >>=\n                  (fun lr : R1 + S1 =>\n                     match lr with\n                     | inl l => Tau (ITree.iter k1 l)\n                     | inr r0 => Ret r0\n                     end))\n            (phi2 >>=\n                  (fun lr : R2 + S2 =>\n                     match lr with\n                     | inl l => Tau (ITree.iter k2 l)\n                     | inr r0 => Ret r0\n                     end)).\nProof.\n  intros E1 E2 S2 S1 R1 R2 RPre RPost RR RS k1 k2 r CIH.\n  pcofix CIH'. intros phi1 phi2 Hphi.\n  punfold Hphi. red in Hphi.\n  remember (observe phi1) as ophi1.\n  remember (observe phi2) as ophi2.\n  hinduction Hphi before r; intros; use_simpobs; try rewrite Heqophi1; try rewrite Heqophi2; pclearbot.\n  - setoid_rewrite bind_ret_l. inv H.\n    + pstep. constructor. right. eapply CIH; eauto.\n    + pstep. constructor; auto.\n  - setoid_rewrite bind_tau. pstep. constructor. right. eapply CIH'; eauto.\n  - rewrite bind_tau. pstep. constructor. pstep_reverse.\n  - rewrite bind_tau. pstep. constructor. pstep_reverse.\n  - setoid_rewrite bind_vis. pstep. constructor; auto. right. eapply CIH'; eauto.\n    apply H0 in H1; pclearbot; eauto.\n  (*\n  - repeat rewrite bind_vis. pstep. constructor. right. eapply CIH'; eauto.\n    apply H.\n  - repeat rewrite bind_vis. pstep. constructor. right. eapply CIH'; eauto.\n    apply H. *)\n  - rewrite bind_vis. pstep. constructor. intros. pstep_reverse.\n  - rewrite bind_vis. pstep. econstructor. pstep_reverse.\n  - rewrite bind_vis. pstep. econstructor. pstep_reverse.\n  - rewrite bind_vis. pstep. econstructor. pstep_reverse.\nQed.\n\n(*this one is going to be rougher going to require some nested coinduction, but should be manageable *)\nTheorem refines_iter {E1 E2 R1 R2 S1 S2} RPre RPost (RR : R1 -> R2 -> Prop) (RS : S1 -> S2 -> Prop)\n        (k1 : R1 -> itree_spec E1 (R1 + S1)) (k2 : R2 -> itree_spec E2 (R2 + S2)) :\n  (forall r1 r2, RR r1 r2 -> refines RPre RPost (sum_rel RR RS) (k1 r1) (k2 r2)) ->\n  forall r1 r2, RR r1 r2 ->  refines RPre RPost RS (ITree.iter k1 r1) (ITree.iter k2 r2).\nProof.\n  intros Hk. pcofix CIH. intros r1 r2 Hr12.\n  rewrite unfold_iter. rewrite unfold_iter.\n  specialize (Hk r1 r2 Hr12) as Hkr12.\n  punfold Hkr12. red in Hkr12.\n  remember (observe (k1 r1)) as ok1. remember (observe (k2 r2)) as ok2.\n  hinduction Hkr12 before r; intros; use_simpobs; try rewrite Heqok1; try rewrite Heqok2.\n  - setoid_rewrite bind_ret_l. inv H.\n    + pstep. constructor. right. eapply CIH; eauto.\n    + pstep. constructor. auto.\n  - setoid_rewrite bind_tau. pstep. constructor. left. pclearbot.\n    eapply refines_iter_bind_aux; eauto.\n  - rewrite bind_tau. pstep. constructor. pstep_reverse.\n    eapply refines_iter_bind_aux; eauto.\n    apply Hk in Hr12. rewrite Heqok1 in Hr12.\n    apply refines_TauL_inv in Hr12. auto.\n  - rewrite bind_tau. pstep. constructor. pstep_reverse.\n    eapply refines_iter_bind_aux; eauto.\n    apply Hk in Hr12. rewrite Heqok2 in Hr12.\n    apply refines_TauR_inv in Hr12. auto.\n(*  - setoid_rewrite bind_vis. pstep. constructor; auto. left. pclearbot.\n    eapply refines_iter_bind_aux; eauto. apply H0 in H1; pclearbot; eauto.\n  - setoid_rewrite bind_vis. pstep. constructor; auto. left. pclearbot.\n    eapply refines_iter_bind_aux; eauto. apply H. *)\n  - setoid_rewrite bind_vis. pstep. constructor; auto. left. pclearbot.\n    eapply refines_iter_bind_aux; eauto.\n    eapply H0 in H1. pclearbot. auto.\n  - rewrite bind_vis. pstep. constructor. intros. pstep_reverse.\n    eapply refines_iter_bind_aux; eauto; subst. all : pstep; apply H; auto.\n  - rewrite bind_vis. pstep. econstructor. Unshelve. all : auto. subst.\n    pstep_reverse. eapply refines_iter_bind_aux; eauto. pstep. auto.\n  - rewrite bind_vis. pstep. econstructor. Unshelve. all : auto.\n    pstep_reverse. subst. eapply refines_iter_bind_aux; eauto. pstep. auto.\n  - rewrite bind_vis. pstep. constructor. intros. pstep_reverse. subst.\n    eapply refines_iter_bind_aux; eauto. pstep. apply H.\nQed.\n\nTheorem padded_refines_iter {E1 E2 R1 R2 S1 S2} RPre RPost (RR : R1 -> R2 -> Prop) (RS : S1 -> S2 -> Prop)\n        (k1 : R1 -> itree_spec E1 (R1 + S1)) (k2 : R2 -> itree_spec E2 (R2 + S2)) :\n  (forall r1 r2, RR r1 r2 -> padded_refines RPre RPost (sum_rel RR RS) (k1 r1) (k2 r2)) ->\n  forall r1 r2, RR r1 r2 ->  padded_refines RPre RPost RS (ITree.iter k1 r1) (ITree.iter k2 r2).\nProof.\n  unfold padded_refines. setoid_rewrite pad_iter.\n  intros. eapply refines_iter; eauto.\nQed.\n\nDefinition and_spec {E R} (phi1 phi2 : itree_spec E R) : itree_spec E R :=\n  Vis Spec_forall (fun b : bool => if b then phi1 else phi2).\n\nDefinition or_spec {E R} (phi1 phi2 : itree_spec E R) : itree_spec E R :=\n  Vis Spec_exists (fun b : bool => if b then phi1 else phi2).\n\nLemma and_spec_correct : forall E R1 R2 (RR : R1 -> R2 -> Prop) (t : itree E R1) (phi1 phi2 : itree_spec E R2),\n    satisfies RR t (and_spec phi1 phi2) <-> (satisfies RR t phi1 /\\ satisfies RR t phi2).\nProof.\n  split; intros.\n  - unfold and_spec in H. punfold H. red in H. cbn in *.\n    remember ((VisF Spec_forall (fun b : bool => if b then phi1 else phi2))) as y.\n    split; pfold; red; hinduction H before RR; intros; inv Heqy; eauto;\n    inj_existT; subst.\n    specialize (H true). eauto.\n    specialize (H false). eauto.\n  - pstep. destruct H. red. cbn. constructor. intros [ | ]; cbn; pstep_reverse.\nQed.\n\nLemma or_spec_correct : forall E R1 R2 (RR : R1 -> R2 -> Prop) (t : itree E R1) (phi1 phi2 : itree_spec E R2),\n    satisfies RR t (or_spec phi1 phi2) <-> (satisfies RR t phi1 \\/ satisfies RR t phi2).\nProof.\n  split; intros.\n  - unfold or_spec in H. punfold H. red in H. cbn in *.\n    remember ((VisF Spec_exists (fun b : bool => if b then phi1 else phi2))) as y.\n    remember (observe t) as ot. hinduction H before RR; intros; inv Heqy; eauto.\n    + use_simpobs.\n      assert (t ≈ phi). rewrite Heqot. rewrite tau_eutt. reflexivity. rewrite H0.\n      eapply IHsatisfiesF; eauto.\n    + inj_existT. subst. destruct a.\n      left. pstep. auto.\n      right. pstep. auto.\n  - pstep. destruct H.\n    + econstructor. Unshelve. 2 : apply true. pstep_reverse.\n    + econstructor. Unshelve. 2 : apply false. pstep_reverse.\nQed.\n\nLemma and_spec_bind : forall E R S (phi1 phi2 : itree_spec E R) (kphi : R -> itree_spec E S),\n    (and_spec phi1 phi2) >>= kphi ≈ and_spec (phi1 >>= kphi) (phi2 >>= kphi).\nProof.\n  intros.\n  setoid_rewrite bind_vis. apply eqit_Vis. intros [ | ]; reflexivity.\nQed.\n\nLemma or_spec_bind : forall E R S (phi1 phi2 : itree_spec E R) (kphi : R -> itree_spec E S),\n    (or_spec phi1 phi2) >>= kphi ≈ or_spec (phi1 >>= kphi) (phi2 >>= kphi).\nProof.\n  intros.\n  setoid_rewrite bind_vis. apply eqit_Vis. intros [ | ]; reflexivity.\nQed.\n\nCoFixpoint interp_mrec_spec' {D E : Type -> Type}\n           (ctx : D ~> itree_spec (D +' E)) {R} (ot : itree_spec' (D +' E) R)\n  : itree_spec E R :=\n  match ot with\n  | RetF r => Ret r\n  | TauF t' => Tau (interp_mrec_spec' ctx (observe t'))\n  | VisF Spec_forall k => Vis Spec_forall (fun x => interp_mrec_spec' ctx (observe (k x)))\n  | VisF Spec_exists k => Vis Spec_exists (fun x => interp_mrec_spec' ctx (observe (k x)))\n  | VisF (Spec_vis (inl1 d)) k => Tau (interp_mrec_spec' ctx (observe (ctx _ d >>= k)))\n  | VisF (Spec_vis (inr1 e)) k =>\n    Vis (Spec_vis e) (fun x => interp_mrec_spec' ctx (observe (k x)))\n  end.\n\nDefinition interp_mrec_spec {D E : Type -> Type}\n           (ctx : D ~> itree_spec (D +' E)) {R} (t : itree_spec (D +' E) R) :=\n  interp_mrec_spec' ctx (observe t).\n\nLemma interp_mrec_spec'_forall:\n  forall (E : Type -> Type) (R : Type) (D : Type -> Type)\n    (ctx : forall T : Type, D T -> itree_spec (D +' E) T)\n    (u : Type) (k1 : u -> itree_spec (D +' E) R),\n    interp_mrec_spec' ctx (VisF Spec_forall k1)\n                      ≅ Vis Spec_forall\n                      (fun x : u => interp_mrec_spec' ctx (observe (k1 x))).\nProof.\n  intros E R D ctx u k1.\n  pstep. red. cbn. constructor. left.\n  enough ((interp_mrec_spec' ctx (observe (k1 v))) ≅ (interp_mrec_spec' ctx (observe (k1 v)))); eauto.\n  reflexivity.\nQed.\n\nLemma interp_mrec_spec'_exists:\n  forall (E : Type -> Type) (R : Type) (D : Type -> Type)\n    (ctx : forall T : Type, D T -> itree_spec (D +' E) T)\n    (u : Type) (k1 : u -> itree_spec (D +' E) R),\n    interp_mrec_spec' ctx (VisF Spec_exists k1)\n                      ≅ Vis Spec_exists\n                      (fun x : u => interp_mrec_spec' ctx (observe (k1 x))).\nProof.\n  intros E R D ctx u k1.\n  pstep. red. cbn. constructor. left.\n  enough ((interp_mrec_spec' ctx (observe (k1 v))) ≅ (interp_mrec_spec' ctx (observe (k1 v)))); eauto.\n  reflexivity.\nQed.\n\nLemma interp_mrec_spec'_inl:\n  forall (E : Type -> Type) (R : Type)\n    (D : Type -> Type)\n    (ctx : forall T : Type,\n        D T -> itree_spec (D +' E) T)\n    (u : Type) (d : D u)\n    (k1 : u -> itree_spec (D +' E) R),\n    interp_mrec_spec' ctx\n                      (VisF (Spec_vis (inl1 d)) k1)\n                      ≅ Tau\n                      (interp_mrec_spec' ctx\n                                         (observe (ctx u d >>= k1))).\nProof.\n  intros E R D ctx u d k1. pstep. red. cbn. constructor.\n  left. assert ((interp_mrec_spec' ctx\n       (observe (ctx u d >>= k1))) ≅ (interp_mrec_spec' ctx\n       (observe (ctx u d >>= k1)))); auto. reflexivity.\nQed.\n\nLemma interp_mrec_spec'_inr:\n  forall (E : Type -> Type) (R : Type)\n    (D : Type -> Type)\n    (ctx : forall T : Type,\n        D T -> itree_spec (D +' E) T)\n    (u : Type) (e : E u)\n    (k1 : u -> itree_spec (D +' E) R),\n    interp_mrec_spec' ctx\n                      (VisF (Spec_vis (inr1 e)) k1)\n                      ≅ Vis (Spec_vis e)\n                      (fun x : u =>\n                         interp_mrec_spec' ctx\n                                           (observe (k1 x))).\nProof.\n  intros E R D ctx u e k1.\n  pstep. red. cbn. constructor. left.\n  assert ((interp_mrec_spec' ctx (observe (k1 v))) ≅ (interp_mrec_spec' ctx (observe (k1 v)))); auto; reflexivity.\nQed.\n\nLemma interp_mrec_spec'_tau:\n  forall (E : Type -> Type) (R : Type) (D : Type -> Type)\n    (ctx : forall T : Type, D T -> itree_spec (D +' E) T)\n    (t : itree_spec (D +' E) R),\n    interp_mrec_spec' ctx (TauF t)\n                      ≅ Tau (interp_mrec_spec' ctx (observe t)).\nProof.\n  intros. pstep. red. cbn. constructor.\n  left. assert ((interp_mrec_spec' ctx (observe t)) ≅ (interp_mrec_spec' ctx (observe t))); auto; reflexivity.\nQed.\n\n(*make a pull request to add this to library *)\n#[global] Instance geuttge_cong_euttger {E R1 R2 RR1 RR2 RS} r rg\n       (LERR1: forall x x' y, (RR1 x x': Prop) -> (RS x' y: Prop) -> RS x y)\n       (LERR2: forall x y y', (RR2 y y': Prop) -> RS x y' -> RS x y):\n  Proper (eq_itree RR1 ==> euttge RR2 ==> flip impl)\n         (gpaco2 (@eqit_ E R1 R2 RS false true id) (eqitC RS false true) r rg).\nProof.\n  repeat intro. guclo eqit_clo_trans. eauto with itree.\nQed.\n\n\n#[global] Instance geuttge_cong_euttger_eq {E R1 R2 RS} r rg:\n  Proper (eq_itree eq ==> euttge eq ==> flip impl)\n         (gpaco2 (@eqit_ E R1 R2 RS false true id) (eqitC RS false true) r rg).\nProof.\n  eapply geuttge_cong_euttger; intros; subst; eauto.\nQed.\n\nGlobal Instance interp_mrec_spec_Proper b1 b2 {D E : Type -> Type} {R}  (ctx : D ~> itree_spec (D +' E)) :\n  Proper (eqit eq b1 b2 ==> eqit eq b1 b2) (@interp_mrec_spec D E ctx R).\nProof.\n  ginit. gcofix CIH. intros.\n  unfold interp_mrec_spec. punfold H0. red in H0.\n  hinduction H0 before r; intros; try inv CHECK; pclearbot; use_simpobs.\n  - gstep. red. cbn. constructor. auto.\n  - gstep. red. cbn. constructor. gfinal. left. eapply CIH; eauto.\n  - destruct e; try destruct s; cbn.\n    + setoid_rewrite interp_mrec_spec'_inl. gstep. constructor.\n      gfinal. left. eapply CIH; eauto.\n      eapply eqit_bind; eauto. assert (ctx _ d ≅ ctx _ d); auto; reflexivity.\n    + setoid_rewrite interp_mrec_spec'_inr. gstep. constructor.\n      gfinal. left. eapply CIH; eauto. apply REL.\n    + setoid_rewrite interp_mrec_spec'_forall. gstep. constructor. gfinal.\n      left. eapply CIH; eauto. apply REL.\n    + setoid_rewrite interp_mrec_spec'_exists. gstep. constructor. gfinal.\n      left. eapply CIH; eauto. apply REL.\n  - rewrite interp_mrec_spec'_tau.  destruct b2; setoid_rewrite tau_euttge; eauto.\n  - rewrite interp_mrec_spec'_tau. destruct b1; setoid_rewrite tau_euttge; eauto.\nQed.\n\n\n\nDefinition mrec_spec {D E : Type -> Type}\n           (ctx : D ~> itree_spec (D +' E)) : D ~> itree_spec E :=\n  fun R d => interp_mrec_spec ctx (ctx _ d).\n\nArguments mrec_spec {D E} & ctx [T].\n\nTheorem padded_interp_mrec_spec_eutt D E R (bodies : D ~> itree_spec (D +' E)) :\n  forall t1 t2 : itree_spec (D +' E) R,\n    t1 ≈ t2 ->\n    pad (interp_mrec_spec bodies t1)\n        ≈ interp_mrec_spec\n        (fun (R0 : Type) (d : D R0) =>\n           pad (bodies R0 d)) t2.\nProof.\n  ginit. gcofix CIH.\n  intros t1 t2 Ht12. unfold interp_mrec_spec. punfold Ht12. red in Ht12.\n  remember (observe t1) as ot1. remember (observe t2) as ot2. clear Heqot1 Heqot2.\n  hinduction Ht12 before r; intros; pclearbot; eauto.\n  - gstep. red. cbn. constructor. auto.\n  - gstep. red. cbn. constructor. gfinal. left. eauto.\n  - destruct e; try destruct s.\n    + repeat rewrite interp_mrec_spec'_inl. rewrite pad_tau. gstep. constructor.\n      gfinal. left. eapply CIH. eapply eqit_bind; auto. apply pad_eutt.\n    + repeat rewrite interp_mrec_spec'_inr. rewrite pad_vis.\n      setoid_rewrite tau_euttge. gstep. constructor. intros. gfinal.\n      left. eauto. eapply CIH. apply REL.\n    + repeat rewrite interp_mrec_spec'_forall. rewrite pad_vis.\n      setoid_rewrite tau_euttge. gstep. constructor. gfinal. left. eapply CIH. apply REL.\n    + repeat rewrite interp_mrec_spec'_exists. rewrite pad_vis. setoid_rewrite tau_euttge.\n      gstep. constructor. intros. gfinal. left. eapply CIH. apply REL.\n  - rewrite interp_mrec_spec'_tau. rewrite pad_tau, tau_euttge. eauto.\n  - rewrite interp_mrec_spec'_tau. rewrite tau_euttge. eauto.\nQed.\n\nTheorem padded_interp_mrec_spec D E R (bodies : D ~> itree_spec (D +' E)) :\n  forall (t : itree_spec (D +' E) R),\n  pad (interp_mrec_spec bodies t) ≈ interp_mrec_spec (fun R d => pad (bodies _ d)) (pad t).\nProof.\n  intros. eapply padded_interp_mrec_spec_eutt. rewrite <- pad_eutt. reflexivity.\nQed.\n\nTheorem padded_mrec_spec D E R (bodies : D ~> itree_spec (D +' E)) :\n  forall (d1 : D R),\n  pad (mrec_spec bodies d1) ≈ mrec_spec (fun R d => pad (bodies _ d)) d1.\nProof.\n  intros. apply padded_interp_mrec_spec.\nQed.\n\nVariant padded2F {E} (F : forall R, itree E R -> Prop) : forall R, itree' E R -> Prop :=\n  | padded2F_Ret R r : padded2F F R (RetF r)\n  | padded2F_Tau R t : (F R t) -> padded2F F R (TauF t)\n  | padded2F_VisTau R A e k : (forall a : A, F R (k a)) -> padded2F F R (VisF e (fun x=> Tau (k x)))\n.\n\nDefinition padded2_ {E} F R (t : itree E R) : Prop :=\n  padded2F F R (observe t).\n\nLemma padded2_monot E : monotone2 (@padded2_ E).\nProof. unfold padded2_. repeat intro. induction IN; econstructor; eauto. Qed.\n\nDefinition padded2 {E} := paco2 (@padded2_ E) bot2.\n\n#[local] Hint Resolve padded2_monot : paco.\n\nLemma padded2_to_padded E R :\n  forall (t : itree E R), padded2 R t -> padded t.\nProof.\n  pcofix CIH. intros. punfold H0. red in H0.\n  pstep. red. inv H0; inj_existT; subst; pclearbot.\n  - rewrite <- H2. constructor.\n  - rewrite <- H. constructor. right. eapply CIH; eauto.\n  - rewrite <- H. constructor. right. eapply CIH; eauto. apply H2.\nQed.\n\nInstance padded_eq_itree_proper_r {E R r} : Proper (@eq_itree E R R eq ==> flip impl) (paco1 (padded_) r).\nProof.\n  repeat intro. eapply bisimulation_is_eq in H. subst. auto.\nQed.\n\nInstance padded2_eq_itree_proper_r {E R r} : Proper (@eq_itree E R R eq ==> flip impl) (paco2 (padded2_) r R).\nProof.\n  repeat intro. eapply bisimulation_is_eq in H. subst. auto.\nQed.\n\nLemma padded_bind E R S (k : R -> itree E S) : (forall r, padded (k r)) -> forall t, padded t -> padded (ITree.bind t k).\nProof.\n  intros Hk. pcofix CIH.\n  intros t Ht. pstep. red. unfold observe. cbn.\n  punfold Ht. red in Ht. inv Ht.\n  - pstep_reverse. eapply paco1_mon; try eapply Hk. intros. contradiction.\n  - cbn. constructor. pclearbot. right. eapply CIH; eauto.\n  - cbn. rewrite itree_eta'. pstep_reverse. setoid_rewrite bind_tau. pstep. constructor.\n    right. pclearbot. eapply CIH; apply H0.\nQed.\n\n(* this is a tad too frustrating to do right now *)\nLemma padded_interp_mrec_spec_padded :\n  forall D E (A : Type) (t : itree_spec (D +' E) A) (bodies : forall T : Type, D T -> itree_spec (D +' E) T),\n    padded t ->\n    (forall T d, padded (bodies T d)) ->\n    padded (interp_mrec_spec bodies t).\nProof.\n  intros. apply padded2_to_padded. generalize dependent A.\n  pcofix CIH. intros A t Ht. unfold interp_mrec_spec.\n  punfold Ht. red in Ht. remember (observe t) as ot. clear Heqot.\n  hinduction Ht before r; intros; pclearbot; eauto.\n  - pstep. red. cbn. constructor.\n  - pstep. red. cbn. constructor. eauto.\n  - destruct e; try destruct s.\n    + pstep. red. cbn. constructor. right. eapply CIH.\n      apply padded_bind; auto. intros. pstep. constructor. left. auto.\n    + pstep. red. cbn. rewrite itree_eta'. pstep_reverse. setoid_rewrite interp_mrec_spec'_tau.\n      pstep. constructor. right. eapply CIH; eauto. apply H.\n    + pstep. red. cbn. rewrite itree_eta'. pstep_reverse. setoid_rewrite interp_mrec_spec'_tau.\n      pstep. constructor. right. eapply CIH; eauto. apply H.\n    + pstep. red. cbn. rewrite itree_eta'. pstep_reverse. setoid_rewrite interp_mrec_spec'_tau.\n      pstep. constructor. right. eapply CIH; eauto. apply H.\nQed.\n\nLemma padded_mrec_spec_pad:\n  forall D E (A : Type) (init : D A) (bodies : forall T : Type, D T -> itree_spec (D +' E) T),\n    padded (mrec_spec (fun (R : Type) (d : D R) => pad (bodies R d)) init).\nProof.\n  intros. apply padded_interp_mrec_spec_padded; intros; apply pad_is_padded.\nQed.\n\nSection Refines5.\n  Context {E1 E2 : Type -> Type}.\n  Context (RPre : PreRel E1 E2) (RPost : PostRel E1 E2).\n\n  Inductive refines5F (F : forall R1 R2, (R1 -> R2 -> Prop) -> itree_spec E1 R1 -> itree_spec E2 R2 -> Prop) :\n     forall R1 R2, (R1 -> R2 -> Prop) -> itree_spec' E1 R1 -> itree_spec' E2 R2 -> Prop :=\n  | refines5F_Ret R1 R2 (RR : R1 -> R2 -> Prop) r1 r2 : RR r1 r2 -> refines5F F _ _ RR (RetF r1) (RetF r2)\n  | refine5F_Tau R1 R2 RR t1 t2 : F R1 R2 RR t1 t2 -> refines5F F _ _ RR (TauF t1) (TauF t2)\n  | refines5F_SpecVis R1 R2 (RR : R1 -> R2 -> Prop) A B (e1 : E1 A) (e2 : E2 B) k1 k2 :\n    RPre A B e1 e2 ->\n    (forall a b, RPost A B e1 e2 a b -> F R1 R2 RR (k1 a) (k2 b)) ->\n    refines5F F R1 R2 RR (VisF (Spec_vis e1) k1) (VisF (Spec_vis e2) k2)\n(*  | refines5F_Forall R1 R2 (RR : R1 -> R2 -> Prop) A\n                     (k1 : A -> itree_spec E1 R1) (k2 : A -> itree_spec E2 R2) :\n    (forall a, F R1 R2 RR (k1 a) (k2 a)) -> refines5F F _ _ RR\n                                              (VisF Spec_forall k1) (VisF Spec_forall k2)\n  | refines5F_Exists R1 R2 (RR : R1 -> R2 -> Prop) A\n                     (k1 : A -> itree_spec E1 R1) (k2 : A -> itree_spec E2 R2) :\n    (forall a, F R1 R2 RR (k1 a) (k2 a)) -> refines5F F _ _ RR\n                                              (VisF Spec_exists k1) (VisF Spec_exists k2) *)\n  | refines5F_TauL R1 R2 (RR : R1 -> R2 -> Prop) t1 ot2 :\n    refines5F F R1 R2 RR (observe t1) ot2 ->\n    refines5F F R1 R2 RR (TauF t1) ot2\n  | refines5F_TauR R1 R2 (RR : R1 -> R2 -> Prop) ot1 t2 :\n    refines5F F R1 R2 RR ot1 (observe t2) ->\n    refines5F F R1 R2 RR ot1 (TauF t2)\n  | refines5F_ForallL R1 R2 (RR : R1 -> R2 -> Prop) A\n                      (k1 : A -> itree_spec E1 R1) ot (a : A) :\n    refines5F F R1 R2 RR (observe (k1 a)) ot ->\n    refines5F F R1 R2 RR (VisF Spec_forall k1) ot\n  | refines5F_ForallR R1 R2 (RR : R1 -> R2 -> Prop) A\n                      ot (k2 : A -> itree_spec E2 R2) :\n    (forall a, refines5F F R1 R2 RR ot (observe (k2 a))) ->\n    refines5F F R1 R2 RR ot (VisF Spec_forall k2)\n  | refines5F_ExistL R1 R2 (RR : R1 -> R2 -> Prop) A\n                      (k1 : A -> itree_spec E1 R1) ot :\n    (forall a, refines5F F R1 R2 RR (observe (k1 a)) ot) ->\n    refines5F F R1 R2 RR (VisF Spec_exists k1) ot\n  | refines5F_ExistR R1 R2 (RR : R1 -> R2 -> Prop) A\n                      ot (k2 : A -> itree_spec E2 R2) a:\n    refines5F F R1 R2 RR ot (observe (k2 a)) ->\n    refines5F F R1 R2 RR ot (VisF Spec_exists k2)\n.\n\n  Hint Constructors refines5F.\n\n  Definition refines5_ F R1 R2 RR t1 t2 :=\n    refines5F F R1 R2 RR (observe t1) (observe t2).\n\n  Lemma refines5_monot : monotone5 refines5_.\n  Proof.\n    unfold refines5_. red. intros.\n    induction IN; eauto.\n  Qed.\n\n  Definition refines5 := paco5 refines5_ bot5.\n\nEnd Refines5.\n\n#[global] Hint Resolve refines5_monot : paco.\n\n#[local] Hint Constructors refines5F.\n\nLemma refines_to_refines5 (E1 E2 : Type -> Type) (R1 R2 : Type)\n      RPre RPost (RR : R1 -> R2 -> Prop) :\n  forall (t1 : itree_spec E1 R1) (t2 : itree_spec E2 R2),\n    refines RPre RPost RR t1 t2 -> refines5 RPre RPost R1 R2 RR t1 t2.\nProof.\n  pcofix CIH. intros. pstep. red.\n  punfold H0. red in H0.\n  hinduction H0 before r; intros; pclearbot; eauto.\n  constructor; auto. intros. eapply H0 in H1. pclearbot.\n  right. eapply CIH; eauto.\nQed.\n\nLemma refines5_to_refines (E1 E2 : Type -> Type) (R1 R2 : Type)\n      RPre RPost (RR : R1 -> R2 -> Prop) :\n  forall (t1 : itree_spec E1 R1) (t2 : itree_spec E2 R2),\n    refines5 RPre RPost R1 R2 RR t1 t2 -> refines RPre RPost RR t1 t2.\nProof.\n  pcofix CIH. intros. pstep. red.\n  punfold H0. red in H0.\n  hinduction H0 before r; intros; pclearbot; eauto.\n  constructor; auto. intros. eapply H0 in H1. pclearbot.\n  right. eapply CIH; eauto.\nQed.\n\nLemma interp_mrec_spec_ret  D E R (ctx : forall T, D T -> itree_spec (D +' E) T)\n      (r : R) : interp_mrec_spec ctx (Ret r) ≅ Ret r.\nProof.\n  pstep. red. cbn. constructor. auto.\nQed.\n\nLemma interp_mrec_spec_tau  D E R (ctx : forall T, D T -> itree_spec (D +' E) T)\n      (t : itree_spec _ R) : interp_mrec_spec ctx (Tau t) ≅ Tau (interp_mrec_spec ctx t) .\nProof.\n  setoid_rewrite interp_mrec_spec'_tau. reflexivity.\nQed.\n\nLemma interp_mrec_spec_inl :\nforall (E : Type -> Type) (R : Type) (D : Type -> Type)\n  (ctx : forall T : Type, D T -> itree_spec (D +' E) T) (u : Type) (d : D u)\n  (k1 : u -> itree_spec (D +' E) R),\n  interp_mrec_spec ctx (Vis (Spec_vis (inl1 d)) k1)\n                   ≅ Tau (interp_mrec_spec ctx (ctx u d >>= k1)).\nProof.\n  intros. setoid_rewrite interp_mrec_spec'_inl. reflexivity.\nQed.\n\nLemma interp_mrec_spec_inr :\nforall (E : Type -> Type) (R : Type) (D : Type -> Type)\n  (ctx : forall T : Type, D T -> itree_spec (D +' E) T) (u : Type) (e : E u)\n  (k1 : u -> itree_spec (D +' E) R),\n  interp_mrec_spec ctx (Vis (Spec_vis (inr1 e)) k1)\n                    ≅ Vis (Spec_vis e) (fun x : u => interp_mrec_spec ctx ((k1 x))).\nProof.\n  intros. setoid_rewrite interp_mrec_spec'_inr. reflexivity.\nQed.\n\nLemma interp_mrec_spec_bind D E U T (ctx : forall T, D T -> itree_spec (D +' E) T)\n      (t : itree_spec (D +' E) U) (k : U -> itree_spec (D +' E) T) :\n  interp_mrec_spec ctx (t >>= k) ≅ interp_mrec_spec ctx t >>= (fun x => interp_mrec_spec ctx (k x)).\nProof.\n  revert t. ginit. gcofix CIH.\n  intros t. destruct (observe t) eqn : Ht; symmetry in Ht; use_simpobs; rewrite Ht.\n  -  rewrite bind_ret_l, interp_mrec_spec_ret, bind_ret_l.\n     gfinal. right. assert ((interp_mrec_spec ctx (k r0)) ≅ (interp_mrec_spec ctx (k r0))).\n     reflexivity.\n     eapply paco2_mon; eauto. intros. contradiction.\n  - setoid_rewrite bind_tau. setoid_rewrite interp_mrec_spec'_tau. rewrite bind_tau. gstep.\n    constructor. gfinal. left. eauto.\n  - rewrite bind_vis. destruct e; try destruct s.\n    + setoid_rewrite interp_mrec_spec_inl. rewrite bind_tau. setoid_rewrite <- bind_bind.\n      gstep. constructor. gfinal. left. eauto.\n    + setoid_rewrite interp_mrec_spec_inr. rewrite bind_vis.\n      gstep. constructor. intros. gfinal. left. eauto.\n    + setoid_rewrite interp_mrec_spec'_forall. rewrite bind_vis. gstep. constructor.\n      gfinal. left. eauto.\n    + setoid_rewrite interp_mrec_spec'_exists. rewrite bind_vis. gstep. constructor.\n      gfinal. left. eauto.\nQed.\n\nLemma interp_mrec_spec_trigger D E T (ctx : forall T, D T -> itree_spec (D +' E) T)\n      (d : D T) : interp_mrec_spec ctx (trigger (Spec_vis (inl1 d))) ≈ interp_mrec_spec ctx (ctx _ d).\nProof.\n   unfold trigger. setoid_rewrite interp_mrec_spec_inl. rewrite tau_eutt. rewrite bind_ret_r.\n   reflexivity.\nQed.\n\n\nSection MRecSpec.\n\n\nContext (D1 D2 E1 E2 : Type -> Type).\n\nContext (bodies1 : D1 ~> itree_spec (D1 +' E1)) (bodies2 : D2 ~> itree_spec (D2 +' E2)).\n\nContext (RPre : PreRel E1 E2) (RPost : PostRel E1 E2).\nContext (RPreInv : PreRel D1 D2) (RPostInv : PostRel D1 D2).\n\nContext (Hbodies : forall A B (d1 : D1 A) (d2 : D2 B),\n            RPreInv A B d1 d2 -> refines (sumPreRel RPreInv RPre) (sumPostRel RPostInv RPost)\n                                 (RPostInv A B d1 d2) (bodies1 A d1) (bodies2 B d2)).\n\n(*         (forall (phi2 : itree_spec (D2 +' E2) B) (phi1 : itree_spec (D1 +' E1) A),\n            paco2 (refines_ (sumPreRel RPreInv RPre) (sumPostRel RPostInv RPost) (RPostInv A B d1 d2)) bot2 phi1\n                  phi2 ->\n            r A B (RPostInv A B d1 d2) (interp_mrec_spec' bodies1 (observe phi1))\n              (interp_mrec_spec' bodies2 (observe phi2))) *)\n\nTheorem refines_interp_mrec : forall A B RR (t1 : itree_spec (D1 +' E1) A) (t2 : itree_spec (D2 +' E2) B),\n                                refines (sumPreRel RPreInv RPre) (sumPostRel RPostInv RPost) RR t1 t2 ->\n                                refines RPre RPost RR (interp_mrec_spec bodies1 t1) (interp_mrec_spec bodies2 t2).\nProof.\n  intros. apply refines5_to_refines. generalize dependent B.\n  generalize dependent A. pcofix CIH. intros A t1 B RR t2 Ht12. unfold interp_mrec_spec.\n  pstep. red. punfold Ht12. red in Ht12. hinduction Ht12 before r; intros; pclearbot; eauto;\n    try (cbn; econstructor; eauto; fail).\n  destruct H.\n  - cbn. constructor. right. eapply CIH. eapply refines_bind; eauto.\n    intros. eapply sumPostRel_inl in H1. eapply H0 in H1. pclearbot. auto.\n  - cbn. constructor; auto. intros. right. eapply CIH; eauto.\n    eapply sumPostRel_inr in H1. eapply H0 in H1. pclearbot. auto.\nQed.\n\nTheorem refines_mrec : forall A B (init1 : D1 A) (init2 : D2 B),\n    RPreInv A B init1 init2 -> refines RPre RPost (RPostInv A B init1 init2)\n                                    (mrec_spec bodies1 init1) (mrec_spec bodies2 init2).\nProof.\n  unfold mrec_spec. intros. eapply refines_interp_mrec; eauto.\nQed.\n\nEnd MRecSpec.\n\nSection PaddedMRecSpec.\n\nContext (D1 D2 E1 E2 : Type -> Type).\n\nContext (bodies1 : D1 ~> itree_spec (D1 +' E1)) (bodies2 : D2 ~> itree_spec (D2 +' E2)).\n\nContext (RPre : PreRel E1 E2) (RPost : PostRel E1 E2).\nContext (RPreInv : PreRel D1 D2) (RPostInv : PostRel D1 D2).\n\nContext (Hbodies : forall A B (d1 : D1 A) (d2 : D2 B),\n            RPreInv A B d1 d2 -> padded_refines (sumPreRel RPreInv RPre)\n                                             (sumPostRel RPostInv RPost)\n                                 (RPostInv A B d1 d2) (bodies1 A d1) (bodies2 B d2)).\n\nTheorem padded_refines_mrec : forall A B (init1 : D1 A) (init2 : D2 B),\n    RPreInv A B init1 init2 -> padded_refines RPre RPost (RPostInv A B init1 init2)\n                                    (mrec_spec bodies1 init1) (mrec_spec bodies2 init2).\nProof.\n  unfold padded_refines in *.\n  intros. eapply refines_eutt_padded_l; try apply pad_is_padded.\n  symmetry. apply padded_mrec_spec.\n  eapply refines_eutt_padded_r; try apply pad_is_padded.\n  apply padded_mrec_spec_pad.\n  symmetry. apply padded_mrec_spec.\n  eapply refines_mrec; eauto.\nQed.\n\nTheorem padded_refines_interp_mrec : forall A B RR (t1 : itree_spec (D1 +' E1) A) (t2 : itree_spec (D2 +' E2) B),\n                                padded_refines (sumPreRel RPreInv RPre) (sumPostRel RPostInv RPost) RR t1 t2 ->\n                                padded_refines RPre RPost RR (interp_mrec_spec bodies1 t1) (interp_mrec_spec bodies2 t2).\nProof.\n  intros. unfold padded_refines in *.\n  intros. eapply refines_eutt_padded_l; try apply pad_is_padded.\n  symmetry. eapply padded_interp_mrec_spec.\n  eapply refines_eutt_padded_r; try apply pad_is_padded.\n  apply padded_interp_mrec_spec_padded; intros; try apply pad_is_padded.\n  symmetry. eapply padded_interp_mrec_spec.\n  eapply refines_interp_mrec; eauto.\nQed.\n\nEnd PaddedMRecSpec.\n\nLemma refines_spin E1 E2 R1 R2 RPre RPost RR :\n  @refines E1 E2 R1 R2 RPre RPost RR ITree.spin ITree.spin.\nProof.\n  pcofix CIH.\n  pstep. red. cbn. constructor. eauto.\nQed.\n\nLemma padded_refines_spin E1 E2 R1 R2 RPre RPost RR :\n  @padded_refines E1 E2 R1 R2 RPre RPost RR ITree.spin ITree.spin.\nProof.\n  pcofix CIH.\n  pstep. red. cbn. constructor. eauto.\nQed.\n\nGlobal Instance padded_refines_subEqRel E R (RR : R -> R -> Prop) (P1 : forall A, E A -> Prop) (P2 : forall A, E A -> A -> Prop) :\n  Transitive RR ->\n  Transitive (padded_refines (subEqPreRel P1) (subEqPostRel P2) RR).\nProof.\n  intros HRR t1 t2 t3 Ht12 Ht23. unfold padded_refines in *.\n  eapply refines_monot; try eapply refinesTrans; eauto with solve_padded; try apply pad_is_padded.\n  - intros A B ea eb PR. inv PR. inj_existT. subst. subEqPreRel_inv H3. auto.\n  - intros. subEqPostRel_inv  PR. constructor. intros. destruct H. subEqPreRel_inv H.\n    exists x1. split; constructor; auto.\n  - intros. inv PR. etransitivity; eauto.\nQed.\n\nGlobal Instance padded_refines_eq_itree E1 E2 R1 R2 RPre RPost RR\n  : Proper (eq_itree eq ==> eq_itree eq ==> impl)\n           (@padded_refines E1 E2 R1 R2 RPre RPost RR).\nProof.\n  repeat intro. assert (x ≈ y). rewrite H. reflexivity.\n  rewrite <- H2. assert (x0 ≈ y0). rewrite H0. reflexivity.\n  rewrite <- H3. auto.\nQed.\n", "meta": {"author": "GaloisInc", "repo": "itree-refinement", "sha": "fb8bdd270bf5fd616bb9512a5d894a0236304dca", "save_path": "github-repos/coq/GaloisInc-itree-refinement", "path": "github-repos/coq/GaloisInc-itree-refinement/itree-refinement-fb8bdd270bf5fd616bb9512a5d894a0236304dca/theories/Refinement.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.28352507187085135}}
{"text": "(*****************************************************************************)\n(** The FSC memory model splits memory into non-atomic and atomic locations. *)\n(** Every location can be accessed only with corresponding mode.             *)\n(** FSC's memory access instructions are compiled into IMM as follows:       *)\n(** +----------------+-----------------------+----------+                    *)\n(** |FSC             |IMM                    |Hypotheses|                    *)\n(** +----------------+-----------------------+----------+                    *)\n(** |r := [x]^{na};  | r := [x]^{rlx};       |  -       |                    *)\n(** |                |                       |          |                    *)\n(** +----------------+-----------------------+----------+                    *)\n(** |[x]^{na} := v;  | fence(acqrel);        | WNAF     |                    *)\n(** |                | [x]^{rlx} := v;       |          |                    *)\n(** +----------------+-----------------------+----------+                    *)\n(** |r := [x]^{at};  | fence(sc);            | RATF1,   |                    *)\n(** |                | r := [x]^{rlx};       | RATF2    |                    *)\n(** |                | fence(sc);            |          |                    *)\n(** +----------------+-----------------------+----------+                    *)\n(** |[x]^{at} := v;  | fence(sc);            | WATF1,   |                    *)\n(** |                | [x]^{rlx} := v;       | WATF2    |                    *)\n(** |                | fence(sc);            |          |                    *)\n(** +----------------+-----------------------+----------+                    *)\n(*****************************************************************************)\nRequire Import Classical Peano_dec.\nFrom hahn Require Import Hahn.\nRequire Import IfThen.\n\nRequire Import Events.\nRequire Import Execution.\nRequire Import Execution_eco.\nRequire Import imm_bob imm_ppo.\nRequire Import imm_hb.\nRequire Import imm.\n\nSet Implicit Arguments.\nRemove Hints plus_n_O.\n\nSection LDRF_Fsc.\n\n\nVariable G : execution.\nHypothesis WF: Wf G.\nHypothesis IC : imm.imm_consistent G. \n           \nNotation \"'E'\" := G.(acts_set).\nNotation \"'Init'\" := (is_init).\nNotation \"'NInit'\" := (set_compl Init).\nNotation \"'sb'\" := G.(sb).\nNotation \"'rf'\" := G.(rf).\nNotation \"'co'\" := G.(co).\nNotation \"'rmw'\" := G.(rmw).\nNotation \"'data'\" := G.(data).\nNotation \"'addr'\" := G.(addr).\nNotation \"'ctrl'\" := G.(ctrl).\nNotation \"'rmw_dep'\" := G.(rmw_dep).\n\nNotation \"'fr'\" := G.(fr).\nNotation \"'eco'\" := G.(eco).\nNotation \"'coe'\" := G.(coe).\nNotation \"'coi'\" := G.(coi).\nNotation \"'deps'\" := G.(deps).\nNotation \"'rfi'\" := G.(rfi).\nNotation \"'rfe'\" := G.(rfe).\n\nNotation \"'detour'\" := G.(detour).\n\nNotation \"'rs'\" := G.(rs).\nNotation \"'release'\" := G.(release).\nNotation \"'sw'\" := G.(sw).\nNotation \"'hb'\" := G.(imm_hb.hb).\n\nNotation \"'ar_int'\" := G.(ar_int).\nNotation \"'ppo'\" := G.(ppo).\nNotation \"'bob'\" := G.(bob).\n\nNotation \"'ar'\" := G.(ar).\n\n\nNotation \"'lab'\" := G.(lab).\nNotation \"'loc'\" := (loc lab).\nNotation \"'val'\" := (val lab).\nNotation \"'mod'\" := (mod lab).\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 \"'RW'\" := (R ∪₁ W).\nNotation \"'F'\" := (fun a => is_true (is_f lab a)).\nNotation \"'ORlx'\" := (fun a => is_true (is_only_rlx lab a)).\nNotation \"'Rlx'\" := (fun a => is_true (is_rlx lab a)).\nNotation \"'Acq'\" := (fun a => is_true (is_acq lab a)).\nNotation \"'Rel'\" := (fun a => is_true (is_rel 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 \"'Loc_' l\" := (fun x => loc x = Some l) (at level 1).\n\nVariable NA AT: actid -> Prop. \nHypothesis LOCMODE: forall l, <<LM: Loc_ l ⊆₁ NA>> \\/ <<LM: Loc_ l ⊆₁ AT>>.\nHypothesis DIFMODE: AT ∩₁ NA ≡₁ ∅.\nHypothesis RWMODE: AT ∪₁ NA ≡₁ RW.\n\nHypothesis WNAF : W ∩₁ NA ⊆₁ codom_rel (⦗F∩₁Acqrel⦘ ⨾ immediate sb) ∪₁ Init.\nHypothesis RATF1 : R ∩₁ AT ⊆₁ codom_rel (⦗F ∩₁ Sc⦘ ⨾ immediate sb).\nHypothesis RATF2 : R ∩₁ AT ⊆₁ dom_rel (immediate sb ⨾ ⦗F ∩₁ Sc⦘).\nHypothesis WATF1: W ∩₁ AT ⊆₁ codom_rel (⦗F ∩₁ Sc⦘ ⨾ immediate sb) ∪₁ Init.\nHypothesis WATF2: W ∩₁ AT ⊆₁ dom_rel (immediate sb ⨾ ⦗F ∩₁ Sc⦘) ∪₁ Init.\n\n\nLemma mode_split (S: actid -> Prop) (HASLOC: forall x, S x -> exists l, loc x = Some l):\n  S ≡₁ (S ∩₁ NA) ∪₁ (S ∩₁ AT).\nProof using.\n  red. split; [| basic_solver].\n  rewrite <- set_inter_union_r.\n  apply set_subset_inter_r. split; [basic_solver| ]. \n  red. intros x Sx. red.\n  specialize (HASLOC x). apply HASLOC in Sx. \n  destruct Sx as [l Lx]. specialize (LOCMODE l).\n  destruct LOCMODE; specialize (H x); auto. \nQed.\n\n    \nLemma sb_f_helper T M (TF: T ⊆₁ codom_rel (⦗F ∩₁ M⦘ ⨾ immediate sb)):\n  ⦗RW⦘ ⨾ sb ⨾ ⦗T⦘ ⊆ ⦗RW⦘ ⨾ sb ⨾ ⦗F ∩₁ M⦘ ⨾ sb ⨾ ⦗T⦘.\nProof using.\n  unfolder. intros e a H. destruct H as [RWe [SBew Ta]]. split; auto.\n  red in TF. specialize (@TF a).\n  pose proof (TF Ta) as [f HH].\n  apply seq_eqv_l in HH. destruct HH as [[Ff Mf] [SBfw IMMfw]].\n  exists f.\n  assert (NIf: NInit f).\n  { specialize (read_or_fence_is_not_init WF). intros RFNI.\n    specialize (RFNI f). basic_solver 10. }\n  assert (NEQef: e <> f).\n  { destruct RWe; red; intros; type_solver. }\n  assert (SBef: sb e f).    \n  { pose (sb_semi_total_r WF NIf NEQef SBew SBfw) as SB2. \n    destruct SB2; auto. exfalso. specialize (IMMfw e). auto. }\n  basic_solver.  \nQed. \n\n\nLemma sb_f_w:\n  ⦗RW⦘ ⨾ sb ⨾ ⦗W⦘ ⊆ ⦗RW⦘ ⨾ sb ⨾ ⦗F ∩₁ Sc⦘ ⨾ sb ⨾ ⦗W ∩₁ AT⦘ ∪ ⦗RW⦘ ⨾ sb ⨾ ⦗F ∩₁ Acqrel⦘ ⨾ sb ⨾ ⦗W ∩₁ NA⦘.\nProof using.\n  assert (FENCE: forall MW MF (COMP: W ∩₁ MW\n          ⊆₁ codom_rel (⦗F ∩₁ MF⦘ ⨾ immediate sb) ∪₁ Init),\n             ⦗RW⦘ ⨾ sb ⨾ ⦗W ∩₁ MW⦘ ⊆ ⦗RW⦘ ⨾ sb ⨾ ⦗F ∩₁ MF⦘ ⨾ sb ⨾ ⦗W ∩₁ MW⦘). \n  { ins.\n    rewrite (no_sb_to_init G) at 3. rewrite seqA, <- id_inter. \n    assert (TMP: NInit ∩₁ (W ∩₁ MW) ⊆₁ codom_rel (⦗F ∩₁ MF⦘ ⨾ immediate sb)).\n    { rewrite COMP. rewrite set_inter_union_r.\n      apply set_subset_union_l. split; [basic_solver 10 | basic_solver]. }\n    rewrite (no_sb_to_init G) at 1. rewrite seqA, <- id_inter. \n    apply (sb_f_helper TMP). }\n    \n  rewrite (mode_split W) at 2; [| apply is_w_loc].  \n  rewrite (id_union (W ∩₁ NA) _). do 2 rewrite seq_union_r.\n  unionL; [unionR right;apply (FENCE NA Acqrel WNAF)\n          | unionR left; apply (FENCE AT Sc WATF1)]. \nQed. \n  \nLemma sb_rf_acyclic: acyclic (sb ⨾ rfe).\nProof using.\n  rewrite (WF.(wf_rfeD)). arewrite (R ⊆₁ RW).\n  rewrite <- !seqA, acyclic_rotl, !seqA.\n  sin_rewrite sb_f_w.\n  cdes IC. cdes Cext.\n  arewrite (F ∩₁ Sc ⊆₁ F ∩₁ Acq/Rel) by mode_solver.\n  arewrite (F ∩₁ Acqrel ⊆₁ F ∩₁ Acq/Rel) by mode_solver.\n  assert (FBOB: sb ⨾ ⦗F ∩₁ Acq/Rel⦘ ⨾ sb ⊆ bob ⨾ bob).\n  { seq_rewrite <- seq_eqvK. rewrite seqA.\n    sin_rewrite sb_to_f_in_bob. sin_rewrite sb_from_f_in_bob. basic_solver. }\n  do 2 sin_rewrite FBOB.\n  rewrite !inclusion_seq_eqv_r, !inclusion_seq_eqv_l.\n  arewrite (rfe ⊆ ar). arewrite (bob ⊆ ar).\n  rewrite unionK, seqA.\n  red.\n  red in Cext0.\n  arewrite (ar ⨾ ar ⨾ ar ⊆ ar^+).\n  { do 2 rewrite <- ct_unit. rewrite seqA. basic_solver 10. }\n  rewrite ct_of_ct. auto.\nQed.\n\n\nLemma sb_rfe_crt_hb: (⦗RW⦘ ⨾ sb ⨾ rfe)^* ⨾ sb ⨾ ⦗F ∩₁ Sc⦘ ⊆ hb.\nProof using.\n  rewrite (dom_l WF.(wf_rfeD)).\n  sin_rewrite sb_f_w.  \n  arewrite (F ∩₁ Sc ⊆₁ F ∩₁ Acqrel) by mode_solver.\n  do 2 rewrite inclusion_seq_eqv_r. rewrite unionK.\n  rewrite inclusion_seq_eqv_l. \n  rewrite !seqA.\n  rewrite rtE, seq_union_l. unionL.\n  { rewrite sb_in_hb. basic_solver. }\n  arewrite ((sb ⨾ ⦗F ∩₁ Acqrel⦘ ⨾ sb ⨾ rfe)⁺ ⊆ sb ⨾ ⦗F ∩₁ Acqrel⦘ ⨾ (⦗F ∩₁ Acqrel⦘ ⨾ sb ⨾ rfe ⨾ sb ⨾ ⦗F ∩₁ Acqrel⦘)^* ⨾ ⦗F ∩₁ Acqrel⦘ ⨾ sb ⨾ rfe).\n  { rewrite <- seq_eqvK at 1. rewrite seqA.\n    rewrite <- seqA with (r2:=⦗F ∩₁ Acqrel⦘). rewrite ct_rotl.\n    basic_solver. }\n  arewrite ((⦗F ∩₁ Acqrel⦘ ⨾ sb ⨾ rfe ⨾ sb ⨾ ⦗F ∩₁ Acqrel⦘) ⊆ hb).\n  { seq_rewrite (dom_l (wf_rfeD WF)). rewrite seqA. \n    arewrite (⦗F ∩₁ Acqrel⦘ ⨾ sb ⨾ ⦗W⦘ ⊆ imm_hb.release G).\n    { unfold imm_hb.release. \n      arewrite (⦗W⦘ ⊆ imm_hb.rs G).\n      { unfold imm_hb.rs. rewrite seq_union_r. unionR right.\n        basic_solver. }\n      hahn_frame_r. \n      mode_solver 10. }\n    rewrite <- sw_in_hb. unfold imm_hb.sw.\n    rewrite id_inter. arewrite (Acqrel ⊆₁ Acq) by mode_solver.\n    arewrite ((sb ⨾ ⦗F⦘) ⊆ (sb ⨾ ⦗F⦘)^?). hahn_frame.\n    unionR right. basic_solver. }\n  rewrite sb_in_hb. \n  rewrite inclusion_seq_eqv_l. \n  seq_rewrite <- ct_begin. sin_rewrite ct_unit.\n  rewrite (ct_of_trans (@hb_trans G)).\n  basic_solver. \nQed. \n\nLemma sl_mode r (SL: r ⊆ same_loc):\n  ⦗RW⦘ ⨾ r ⨾ ⦗RW⦘ ⊆ restr_rel NA r ∪ restr_rel AT r.\nProof using.\n  unfolder. ins. destruct H as [RWx [RELxy RWy]].\n  assert (exists l, Loc_ l x) as [l Lx].\n  { unfold Events.loc. unfold is_f in *.\n    destruct (lab x) eqn:AA; simpls.\n    all: eauto.\n    type_solver. }\n  specialize (LOCMODE l).\n  red in SL.\n  pose proof (SL x y RELxy) as SLxy. red in SLxy.\n  rewrite Lx in SLxy. \n  destruct LOCMODE; splits; auto.\nQed.\n\nLemma sb_f_at: RW ∩₁ AT ∩₁ NInit ⊆₁ codom_rel (⦗F ∩₁ Sc⦘ ⨾ immediate sb).\nProof using.\n  do 2 rewrite set_inter_union_l.\n  apply set_subset_union_l.\n  split.\n  { arewrite (R ∩₁ AT ∩₁ NInit ⊆₁ R ∩₁ AT) by basic_solver. } \n  rewrite WATF1. rewrite set_inter_union_l. apply set_subset_union_l.\n  split; [basic_solver 10 | basic_solver]. \nQed.\n\n  \nLemma f_sb_at: RW ∩₁ AT ∩₁ NInit  ⊆₁ dom_rel (immediate sb ⨾ ⦗F ∩₁ Sc⦘).\nProof using.   \n  do 2 rewrite set_inter_union_l.\n  apply set_subset_union_l.\n  split.\n  { arewrite (R ∩₁ AT ∩₁ NInit ⊆₁ R ∩₁ AT) by basic_solver. } \n  rewrite WATF2. rewrite set_inter_union_l. apply set_subset_union_l.\n  split; [basic_solver 10 | basic_solver]. \nQed.\n\n\nLemma ct_dom_start: forall (A: Type) (r: relation A) (dom: A -> Prop), \n    ⦗dom⦘ ⨾ (r ⨾ ⦗dom⦘)^+ ≡ (⦗dom⦘ ⨾ r ⨾ ⦗dom⦘)^+.\nProof using.\n  intros A r dom. \n  rewrite ct_rotl.\n  rewrite <- (seqA ⦗dom⦘ r ⦗dom⦘). rewrite ct_rotl.\n  rewrite !seqA.\n  seq_rewrite seq_eqvK.\n  basic_solver. \nQed.\n\nLemma acyclic_empty: forall (A: Type), @acyclic A ∅₂.\nProof using.\n  intros A. red.\n  rewrite ct_of_trans; [| basic_solver]. \n  basic_solver.\nQed. \n\nLemma sb_eco_sb_psc: ⦗F ∩₁ Sc⦘ ⨾ sb ⨾ eco ⨾ sb ⨾ ⦗F ∩₁ Sc⦘ ⊆ psc G.\nProof using. unfold psc. rewrite sb_in_hb. basic_solver 10. Qed. \n\nLemma RFE1: rfe^+ ≡ rfe.\nProof using.  apply ct_no_step. rewrite WF.(wf_rfeD). type_solver. Qed. \n\nLemma no_eco_to_init: eco ≡ eco ⨾ ⦗NInit⦘. \nProof using.\n  split; [| basic_solver].\n  arewrite (eco ≡ eco ⨾ ⦗codom_rel eco⦘) at 1 by basic_solver.\n  apply seq_mori; [basic_solver|]. \n  rewrite (eco_alt3 WF).\n  cdes IC. \n  rewrite (no_rf_to_init WF), (no_co_to_init WF (coherence_sc_per_loc Cint)).\n  rewrite (no_fr_to_init WF (coherence_sc_per_loc Cint)). \n  do 2 rewrite <- seq_union_l.\n  rewrite inclusion_ct_seq_eqv_r. rewrite codom_seq.\n  basic_solver.\nQed. \n\nLemma acyclic_sb_rf_eco: acyclic (sb ∪ restr_rel NA rf ∪ restr_rel AT eco). \nProof using.\n  rewrite rfi_union_rfe, <- union_restr, <- unionA.\n  arewrite (restr_rel NA rfi ⊆ sb). rewrite unionK. \n  assert (na_at_rels_empty: restr_rel NA rfe ⨾ restr_rel AT eco ≡ ∅₂).\n  { generalize DIFMODE. basic_solver. }\n  rewrite unionA. apply acyclic_union1; [apply Execution.sb_acyclic | |].\n  { cdes IC. cdes Cint. \n    apply acyclic_union1.    \n    { rewrite inclusion_restr. \n      rewrite WF.(wf_rfeD). apply acyclic_disj. type_solver. }\n    { rewrite inclusion_restr. \n      red. rewrite (ct_of_trans (eco_trans WF)).\n      apply (eco_irr WF). }\n    rewrite ct_end, ct_begin, seqA.\n    seq_rewrite na_at_rels_empty.\n    rewrite seq_false_l, seq_false_r. apply acyclic_empty. }\n  rewrite (ct_of_trans (@sb_trans G)).\n  arewrite ((restr_rel NA rfe ∪ restr_rel AT eco)⁺ ⊆ (restr_rel NA rfe)⁺ ∪ (restr_rel AT eco)⁺).\n  { rewrite path_union. apply union_mori; [basic_solver| ]. \n    rewrite rtE. rewrite seq_union_l.\n    rewrite (ct_end (restr_rel NA rfe)) at 1. rewrite seqA.\n    rewrite na_at_rels_empty. \n    rewrite !seq_false_r, union_false_r. rewrite seq_id_l at 1. \n    rewrite seq_union_r. unionL; [basic_solver| ].\n    rewrite ct_end, ct_begin, seqA at 1.\n    assert (restr_rel AT eco ⨾ restr_rel NA rfe ≡ ∅₂).\n    { do 2 rewrite restr_relE, seqA.\n      seq_rewrite <- id_inter. rewrite DIFMODE. basic_solver. } \n    seq_rewrite H. basic_solver. }\n  rewrite seq_union_r.\n  \n  apply acyclic_union1.\n  { rewrite inclusion_restr. \n    rewrite RFE1. apply sb_rf_acyclic. }\n  { rewrite restr_relE. \n    rewrite inclusion_ct_seq_eqv_l, inclusion_seq_eqv_r. \n    rewrite (ct_of_trans (eco_trans WF)). \n    rewrite (wf_ecoD WF). seq_rewrite <- id_inter. \n    rewrite <- seqA with (r3:=⦗RW⦘), <- seqA. rewrite acyclic_rotl.\n    rewrite set_interC. \n    rewrite no_sb_to_init, seqA. seq_rewrite <- id_inter. rewrite set_interC. \n    sin_rewrite (sb_f_helper sb_f_at).\n    rewrite inclusion_seq_eqv_r,  inclusion_seq_eqv_l. \n    rewrite !seqA.\n    rewrite <- (seq_eqvK (F ∩₁ Sc)), seqA.\n    rewrite <- seqA with (r2:=⦗F ∩₁ Sc⦘). \n    apply acyclic_rotl. rewrite !seqA.\n    rewrite sb_eco_sb_psc. arewrite (psc G ⊆ ar). \n    cdes IC. cdes Cext. auto. }\n  rewrite inclusion_restr, RFE1. \n  rewrite restr_relE, inclusion_seq_eqv_r. \n  rewrite acyclic_rotl.\n  rewrite inclusion_ct_seq_eqv_l. \n  rewrite (ct_of_trans (eco_trans WF)).\n  rewrite (dom_r (wf_rfeD WF)) at 1. arewrite (R ⊆₁ RW) at 1.\n  rewrite <- seqA with (r3:=⦗RW⦘). \n  rewrite (@inclusion_ct_seq_eqv_r _ RW _). \n  rewrite <- seqA, acyclic_rotl.\n  arewrite (⦗RW⦘ ⨾ (sb ⨾ ⦗AT⦘ ⨾ eco)⁺ ⊆ (⦗RW⦘ ⨾ sb ⨾ ⦗RW ∩₁ AT⦘ ⨾ eco)⁺).\n  { rewrite (wf_ecoD WF) at 1. \n    rewrite <- !seqA.\n    rewrite ct_dom_start, !seqA.\n    apply clos_trans_mori.\n    hahn_frame. basic_solver. }\n  rewrite no_sb_to_init, seqA. seq_rewrite <- id_inter. rewrite set_interC. \n  sin_rewrite (sb_f_helper sb_f_at).\n  do 2 rewrite inclusion_seq_eqv_r. \n  rewrite <- (seq_eqvK (F ∩₁ Sc)), !seqA.\n  rewrite <- seqA with (r2:=⦗F ∩₁ Sc⦘). rewrite <- seqA with (r1:=⦗RW⦘).\n  rewrite inclusion_seq_eqv_l. \n  rewrite ct_rotl, !seqA. \n  rewrite sb_eco_sb_psc.\n\n  rewrite <- seqA. rewrite acyclic_rotl. \n  rewrite !seqA.\n  \n  arewrite (eco ⨾ (sb ⨾ rfe)⁺ ⊆ eco ⨾ (⦗RW⦘ ⨾ sb ⨾ rfe)⁺).\n  { rewrite (dom_r (wf_ecoD WF)) at 1. rewrite !seqA. hahn_frame_l.\n    rewrite (dom_r (wf_rfeD WF)) at 1. \n    arewrite (R ⊆₁ RW) at 2. rewrite <- seqA. \n    rewrite ct_dom_start.\n    rewrite inclusion_seq_eqv_r. basic_solver. }\n\n  rewrite <- (seq_eqvK (F ∩₁ Sc)) at 2.\n  rewrite inclusion_t_rt. sin_rewrite sb_rfe_crt_hb.\n  arewrite ((⦗F ∩₁ Sc⦘ ⨾ sb ⨾ eco ⨾ hb ⨾ ⦗F ∩₁ Sc⦘) ⊆ psc G). \n  rewrite <- ct_end. arewrite (psc G ⊆ ar). \n  red. rewrite ct_of_ct. \n  cdes IC. cdes Cext. auto. \nQed.   \n  \nLemma imm_to_ocaml_causal:\n  acyclic (sb ∪ rfe ∪ restr_rel AT (coe ∪ fre G)).\nProof using.\n  arewrite (rfe ⊆ rf). \n  arewrite (rf ⊆ restr_rel NA rf ∪ restr_rel AT rf).\n  { rewrite (wf_rfD WF) at 1. arewrite (R ⊆₁ RW). arewrite (W ⊆₁ RW) at 1.  \n    rewrite sl_mode; [basic_solver | apply (wf_rfl WF)]. }\n\n  do 2 rewrite unionA.\n  rewrite union_restr. \n  arewrite ((rf ∪ (coe ∪ fre G)) ⊆ eco).\n  { unfold Execution_eco.eco, Execution.rf, Execution.coe, Execution.fre. basic_solver 10. }\n  rewrite <- unionA. apply acyclic_sb_rf_eco. \nQed.\n\n\nLemma f_sb_helper T M (TF: T ⊆₁ dom_rel (immediate sb ⨾ ⦗F ∩₁ M⦘))\n  (NIT: T ∩₁ is_init ≡₁ ∅):\n  ⦗T⦘ ⨾ sb ⨾ ⦗RW⦘ ⊆ ⦗T⦘ ⨾ sb ⨾ ⦗F ∩₁ M⦘ ⨾ sb ⨾ ⦗RW⦘.\nProof using.\n  unfolder. intros a e [Ta [SBae RWe]]. split; auto. \n  red in TF. specialize (@TF a).\n  pose proof (TF Ta) as [f HH].\n  apply seq_eqv_r in HH. destruct HH as [[SBaf IMMfw] [Ff Mf]].\n  exists f.\n  assert (NIa: ~is_init a).\n  { red in NIT. destruct NIT as [NIT _]. red in NIT.\n    specialize (NIT a).\n    red. intros contra.\n    destruct NIT. red. split; auto. }\n  assert (NEQef: e <> f).\n  { destruct RWe; red; intros; type_solver. }\n  assert (SBfe: sb f e).    \n  { pose (sb_semi_total_l WF NIa NEQef SBae SBaf) as SB2. \n    destruct SB2; auto. exfalso. specialize (IMMfw e). auto. }\n  basic_solver.  \nQed.\n  \nLemma ac_irr: forall A (r: relation A), acyclic r <-> irreflexive r^+.\nProof using. intros A r. basic_solver. Qed. \n\nDefinition ae := (⦗AT⦘ ⨾ (rfe ∪ co) ⨾ ⦗AT⦘).\n\n\nLemma imm_to_ocaml_coherent: irreflexive ((sb ∪ ae)^+ ⨾ (co ∪ fr)).\nProof using.\n  arewrite (co ∪ fr ⊆ eco) by unfold Execution_eco.eco; basic_solver 10. \n  rewrite ct_unionE.\n  assert (ae_in_eco: ae ⊆ eco).\n  { unfold Execution_eco.eco, ae.\n    rewrite inclusion_seq_eqv_l, inclusion_seq_eqv_r.\n    unfold Execution.rfe. \n    basic_solver 10. }\n  rewrite seq_union_l. apply irreflexive_union. split.\n  { rewrite ae_in_eco. \n    rewrite ct_unit.\n    rewrite (ct_of_trans (eco_trans WF)). \n    apply (eco_irr WF). }\n  rewrite seqA.\n  rewrite irreflexive_seqC, seqA.\n  arewrite (eco ⨾ ae＊ ⊆ eco).\n  { rewrite ae_in_eco. rewrite <- ct_begin.\n    apply (ct_of_trans (eco_trans WF)). }\n  rewrite rtE, seq_union_r, seq_id_r.\n  rewrite unionC, path_absorb2.\n  2: { sin_rewrite (rewrite_trans (@sb_trans G)). basic_solver. }\n  do 2 rewrite seq_union_l. rewrite unionA. apply irreflexive_union. split.\n  { arewrite (ae ⊆ ⦗AT⦘ ⨾ eco ⨾ ⦗AT⦘).\n    { unfold ae, Execution_eco.eco, Execution.rfe. basic_solver 10. }\n    rewrite <- restr_relE.     \n    rewrite (ct_of_trans (transitive_restr (eco_trans WF))).\n    assert (eco_sl: eco ⊆ same_loc).\n    { rewrite (eco_alt3 WF).\n      rewrite (wf_rfl WF), (wf_col WF), (wf_frl WF).\n      do 2 rewrite unionK. apply (ct_of_trans (@same_loc_trans _ lab)). }\n    rewrite (wf_ecoD WF) at 2. \n    rewrite (sl_mode eco_sl). \n    rewrite seq_union_r.\n    apply irreflexive_union. split. \n    { rewrite ct_end, seqA, seqA.\n      arewrite (restr_rel AT eco ⨾ restr_rel NA eco ⊆ ∅₂).\n      { do 2 rewrite restr_relE. generalize DIFMODE. basic_solver. }\n      rewrite !seq_false_r. basic_solver. }\n    rewrite ct_rotl, !seqA.\n    rewrite (rewrite_trans (transitive_restr (eco_trans WF))).\n    rewrite <- ct_rotl. \n    rewrite <- ac_irr. apply acyclic_seq_from_union. \n    arewrite (sb ∪ restr_rel AT eco ⊆ sb ∪ restr_rel NA rf ∪ restr_rel AT eco) by basic_solver 10.\n    apply acyclic_sb_rf_eco. }\n      \n  rewrite (ct_of_trans (@sb_trans G)).\n  apply irreflexive_union. split.\n  { rewrite sb_in_hb.\n    cdes IC. cdes Cint. auto. }\n  rewrite (dom_r (wf_ecoD WF)), <- seqA.\n  rewrite irreflexive_seqC, seqA. \n  arewrite (⦗RW⦘ ⨾ (sb ⨾ ae⁺)⁺ ⊆  sb ⨾ ⦗F ∩₁ Sc⦘ ⨾ (psc G)^* ⨾ ⦗F ∩₁ Sc⦘ ⨾ sb ⨾ ae⁺).\n  { \n    arewrite (ae⁺ ⊆ ⦗RW ∩₁ AT⦘ ⨾ ae⁺ ⨾ ⦗RW⦘) at 1. \n    { rewrite <- inclusion_ct_seq_eqv_r, <- inclusion_ct_seq_eqv_l.\n      apply clos_trans_mori. \n      unfold ae. rewrite !seqA.\n      rewrite id_inter, seqA. seq_rewrite seq_eqvK.\n      seq_rewrite (seq_eqvC (RW) (AT)). rewrite seqA. \n      rewrite (seq_eqvC (AT) (RW)).\n      hahn_frame.\n      rewrite ((wf_rfeD WF)), ((wf_coD WF)) at 1.\n      basic_solver. }\n    do 2 rewrite <- seqA. rewrite ct_dom_start, seqA, seqA.     \n    rewrite no_sb_to_init at 1. rewrite seqA.\n    seq_rewrite <- id_inter. rewrite set_interC. \n    sin_rewrite (sb_f_helper sb_f_at). do 2 rewrite inclusion_seq_eqv_r. \n    rewrite !seqA.\n    rewrite inclusion_seq_eqv_l.\n    rewrite <- seq_eqvK at 1. rewrite seqA.\n    rewrite <- seqA with (r2:=⦗F ∩₁ Sc⦘). rewrite ct_rotl, seqA.\n    hahn_frame. repeat hahn_frame_r. \n    apply clos_refl_trans_mori.\n    rewrite ae_in_eco. rewrite (ct_of_trans (eco_trans WF)).\n    rewrite sb_in_hb. \n    unfold psc. basic_solver 10. }\n  arewrite (ae⁺ ⊆ eco ⨾ ⦗RW ∩₁ AT⦘).\n  { unfold ae. rewrite <- seqA, inclusion_ct_seq_eqv_r.\n    rewrite id_inter. hahn_frame.\n    rewrite inclusion_seq_eqv_l.\n    arewrite (rfe ∪ co ⊆ eco) by unfold Execution_eco.eco, Execution.rfe; basic_solver 10.\n    rewrite (ct_of_trans (eco_trans WF)).\n    apply (dom_r (wf_ecoD WF)). }\n  \n  rewrite (dom_l (wf_ecoD WF)) at 2.  \n  rewrite no_eco_to_init. rewrite seqA.\n  seq_rewrite <- id_inter. rewrite (set_interC _ (RW ∩₁ AT)). \n  assert (NINIT: RW ∩₁ AT ∩₁ NInit ∩₁ Init ≡₁ ∅) by basic_solver. \n  sin_rewrite (f_sb_helper f_sb_at NINIT). \n  rewrite !seqA. \n  sin_rewrite (@inclusion_seq_eqv_r _ eco _).\n  rewrite <- seq_eqvK at 3. rewrite seqA.\n  arewrite (⦗RW ∩₁ AT ∩₁ NInit⦘ ⨾ sb ⊆ sb). \n  sin_rewrite sb_eco_sb_psc. \n  rewrite <- seqA with (r2:=psc G). rewrite <- seqA with (r1:=sb).\n  rewrite irreflexive_seqC, !seqA.\n  sin_rewrite (@inclusion_seq_eqv_l _ eco _). \n  sin_rewrite sb_eco_sb_psc. \n  seq_rewrite <- ct_end. rewrite ct_unit. \n  arewrite (psc G ⊆ ar). \n  cdes IC. cdes Cext. auto.\nQed.\n\nTheorem ldrf_condition_ext:\n  acyclic(sb ∪ rf ∪ ⦗F ∩₁ Sc⦘ ⨾ sb ⨾ eco ⨾ sb ⨾ ⦗F ∩₁ Sc⦘). \nProof using.\n  apply acyclic_union1.\n  { rewrite (wf_rfD WF). arewrite (W ⊆₁ RW). arewrite (R ⊆₁ RW) at 2 .\n    rewrite (sl_mode); [| apply (wf_rfl WF)].\n    rewrite rf_in_eco at 2. rewrite <- unionA.\n    apply acyclic_sb_rf_eco. }\n  { sin_rewrite sb_eco_sb_psc. arewrite (psc G ⊆ ar). \n    cdes IC. cdes Cext. auto. }\n  rewrite rfi_union_rfe, (rfi_in_sbloc' WF), inclusion_inter_l1. \n  rewrite <- unionA, unionK. \n  rewrite <- seq_eqvK. rewrite !seqA.\n  sin_rewrite sb_eco_sb_psc.\n  rewrite unionC. rewrite path_ut2; [| apply (@sb_trans G)].\n  rewrite RFE1. arewrite (rfe^* ≡ rfe^?).\n  { rewrite rtE, RFE1. basic_solver. }\n  rewrite <- seqA with (r3:=⦗F ∩₁ Sc⦘). rewrite inclusion_ct_seq_eqv_r.\n  rewrite <- seqA. rewrite acyclic_rotl.\n  seq_rewrite seq_union_r.\n  arewrite (⦗F ∩₁ Sc⦘ ⨾ rfe ≡ ∅₂) by rewrite (wf_rfeD WF); type_solver. \n  rewrite union_false_l. \n  arewrite (⦗F ∩₁ Sc⦘ ⨾ rfe^? ≡ ⦗F ∩₁ Sc⦘) by rewrite (wf_rfeD WF); type_solver. \n  rewrite inclusion_ct_seq_eqv_l.\n  arewrite (rfe^? ⨾ ⦗F ∩₁ Sc⦘ ≡ ⦗F ∩₁ Sc⦘) by rewrite (wf_rfeD WF); type_solver. \n  rewrite rtE. repeat case_union _ _.\n  arewrite (⦗F ∩₁ Sc⦘ ⨾ ⦗fun _ : actid => True⦘ ⨾ sb ⨾ ⦗F ∩₁ Sc⦘ ⊆ ar).\n  { arewrite (sb ⨾ ⦗F ∩₁ Sc⦘ ⊆ bob).\n    { unfold imm_bob.bob, imm_bob.fwbob.\n      arewrite (Sc ⊆₁ Acq/Rel) by mode_solver. \n      basic_solver 10. }\n    unfold imm.ar, imm_ppo.ar_int. basic_solver 10. }\n  rewrite ct_begin with (r:=(sb ⨾ rfe)).\n  rewrite !seqA.\n  rewrite (dom_r (wf_rfeD WF)), seqA.\n  arewrite (⦗R⦘ ⨾ (sb ⨾ rfe ⨾ ⦗R⦘)＊ ⊆ (⦗RW⦘ ⨾ sb ⨾ rfe)＊).\n  { rewrite rtE, seq_union_r. unionL; [basic_solver| ].\n    arewrite (⦗R⦘ ⊆ ⦗RW⦘). rewrite <- seqA, ct_dom_start.\n    rewrite inclusion_seq_eqv_r. basic_solver. }\n  sin_rewrite sb_rfe_crt_hb.\n  arewrite (rfe ⊆ eco) by unfold Execution_eco.eco, Execution.rfe; basic_solver.\n  arewrite ((psc G)⁺ ⊆ ⦗F ∩₁ Sc⦘ ⨾ (psc G)⁺).\n  { unfold psc. rewrite <- seq_eqvK at 1. rewrite seqA.\n    rewrite inclusion_ct_seq_eqv_l at 1. basic_solver. }\n  arewrite (⦗F ∩₁ Sc⦘ ⨾ sb ⨾ eco ⨾ hb ⨾ ⦗F ∩₁ Sc⦘ ⊆ psc G).\n  arewrite (psc G ⊆ ar).\n  rewrite inclusion_seq_eqv_l, unionK. \n  rewrite acyclic_rotl, ct_unit. \n  red. rewrite ct_of_ct.\n  cdes IC. cdes Cext. auto.   \nQed.\n\nTheorem ldrf_condition: acyclic(sb ∪ rf ∪ ⦗AT⦘ ⨾ sb ⨾ eco ⨾ sb ⨾ ⦗AT⦘).\nProof using. \n  arewrite (sb ∪ rf ∪ ⦗AT⦘ ⨾ sb ⨾ eco ⨾ sb ⨾ ⦗AT⦘ ⊆ (sb ∪ rf ∪ ⦗AT⦘ ⨾ sb ⨾ eco ⨾ sb ⨾ ⦗AT⦘) ⨾ ⦗NInit⦘).\n  { rewrite (no_sb_to_init G) at 1. rewrite (no_sb_to_init G) at 3.\n    rewrite (no_rf_to_init WF) at 1. \n    rewrite seqA. rewrite seq_eqvC. \n    rewrite <- !seqA. do 2 rewrite <- seq_union_l.\n    hahn_frame. basic_solver. }\n\n  rewrite acyclic_rotl, seq_union_r.\n  arewrite (AT ⊆₁ RW ∩₁ AT).\n  { apply set_subset_inter_r. split; auto. generalize RWMODE. basic_solver. }\n  arewrite (⦗NInit⦘ ⨾ ⦗RW ∩₁ AT⦘ ⨾ sb ⨾ eco ⨾ sb ⨾ ⦗RW ∩₁ AT⦘ ⊆ ⦗RW ∩₁ AT⦘ ⨾ sb ⨾ ⦗F ∩₁ Sc⦘ ⨾ sb ⨾ eco ⨾ sb ⨾ ⦗F ∩₁ Sc⦘ ⨾ sb). \n  { seq_rewrite <- id_inter. rewrite set_interC.\n    rewrite (wf_ecoD WF), !seqA.\n    rewrite no_sb_to_init at 2. rewrite seqA, <- id_inter. rewrite (set_interC NInit _).  \n    rewrite (sb_f_helper sb_f_at). rewrite inclusion_seq_eqv_r. \n    do 5 hahn_frame_r. \n    assert (ninit': (RW ∩₁ AT ∩₁ NInit) ∩₁ is_init ≡₁ ∅) by basic_solver.\n    sin_rewrite (f_sb_helper f_sb_at ninit').\n    hahn_frame. basic_solver. }\n  do 2 rewrite inclusion_seq_eqv_l. \n  red.\n  assert (ct_spec: forall (x y z: relation actid), (x ∪ y ∪ x ⨾ z ⨾ x)⁺ ⊆ (x ∪ y ∪ z)⁺).\n  { intros x y z.\n    assert (inclusion_ext: x ∪ y ∪ x ⨾ z ⨾ x ⊆ (x ∪ y ∪ z)⁺). \n    { apply inclusion_union_l.\n      { rewrite <- ct_step. basic_solver. }\n      do 2 rewrite <- ct_unit. \n      rewrite <- seqA.\n      apply seq_mori; [| basic_solver]. apply seq_mori; [| basic_solver].\n      rewrite <- ct_step. basic_solver. }\n    apply inclusion_t_ind_right; [apply inclusion_ext| ]. \n    rewrite <- ct_ct with (r:=(x ∪ y ∪ z)) at 2.\n    apply seq_mori; [basic_solver | apply inclusion_ext]. }\n  do 4 rewrite <- seqA with (r3:=sb). \n  rewrite ct_spec.\n  apply -> ac_irr. apply ldrf_condition_ext. \nQed. \n  \nEnd LDRF_Fsc.\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/ldrf/LDRF_Fsc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.28351784491751514}}
{"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 A B C P D0 D1 A0 D A0prime D0prime Pprime : Universe, ((wd_ A B /\\ (wd_ B C /\\ (wd_ A C /\\ (wd_ P D0 /\\ (wd_ A A0 /\\ (wd_ B A0 /\\ (wd_ D0 A0 /\\ (wd_ D D0 /\\ (wd_ B D1 /\\ (wd_ A D1 /\\ (wd_ D0 D0prime /\\ (wd_ D D0prime /\\ (wd_ D A0 /\\ (wd_ A0 A0prime /\\ (wd_ D A0prime /\\ (wd_ P A0 /\\ (wd_ D0 D1 /\\ (wd_ P D /\\ (wd_ P Pprime /\\ (wd_ D Pprime /\\ (col_ A B D0 /\\ (col_ A B A0 /\\ (col_ D0 D1 D /\\ (col_ P D D0 /\\ (col_ D P Pprime /\\ (col_ D D0 D0prime /\\ col_ D A0 A0prime)))))))))))))))))))))))))) -> col_ D1 P D0)).\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_0104.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.28351783989057633}}
{"text": "Require Import msl.Coqlib2.\nRequire Import msl.eq_dec.\nRequire Import msl.seplog.\nRequire Import veric.compcert_rmaps.\nRequire Import veric.tycontext.\nRequire Import veric.res_predicates.\nRequire Import concurrency.lksize.\nRequire Import concurrency.addressFiniteMap.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\n(* Those were overwritten in structured_injections *)\nNotation join := sepalg.join.\nNotation join_assoc := sepalg.join_assoc.\n\nDefinition islock_pred (R: pred rmap) r := exists sh sh' z, r = YES sh sh' (LK z) (SomeP rmaps.Mpred (fun _ => R)).\n\nLemma islock_pred_join_sub {r1 r2 R} : join_sub r1 r2 -> islock_pred R r1  -> islock_pred R r2.\nProof.\n  intros [r0 J] [x [sh' [z ->]]].\n  inversion J; subst; eexists; eauto.\nQed.\n\nDefinition LKspec_ext (R: pred rmap) : spec :=\n   fun (rsh sh: Share.t) (l: AV.address)  =>\n     allp\n       (jam\n          (adr_range_dec l LKSIZE)\n          (jam (eq_dec l)\n               (yesat (SomeP rmaps.Mpred (fun _ => R)) (LK LKSIZE) rsh sh)\n               (CTat l rsh sh))\n          (fun _ => TT)).\n\nDefinition LK_at R sh :=\n  LKspec_ext R (Share.unrel Share.Lsh sh) (Share.unrel Share.Rsh sh).\n\n(* We used LK_at in lock_coherence before, but we it requires that all\nthe LK, CT, ... have the same share, which might not be true. The\nfollowing definition has the same structure as rmap_makelock in\nrmap_locking *)\n\nDefinition pack_res_inv (R: pred rmap) := SomeP rmaps.Mpred (fun _ => R).\n\nDefinition lkat (R : mpred) loc phi :=\n  (forall x,\n      adr_range loc LKSIZE x ->\n      exists sh rsh,\n        phi @ x =\n        if eq_dec x loc then\n          YES sh rsh (LK LKSIZE) (pack_res_inv (approx (level phi) R))\n        else\n          YES sh rsh (CT (snd x - snd loc)) NoneP).\n\nDefinition isLK (r : resource) := exists sh sh' z P, r = YES sh sh' (LK z) P.\n\nDefinition isCT (r : resource) := exists sh sh' z P, r = YES sh sh' (CT z) P.\n\nDefinition resource_is_lock r := exists rsh sh n pp, r = YES rsh sh (LK n) pp.\n\nDefinition same_locks phi1 phi2 :=\n  forall loc, resource_is_lock (phi1 @ loc) <-> resource_is_lock (phi2 @ loc).\n\nDefinition resource_is_lock_sized n r := exists rsh sh pp, r = YES rsh sh (LK n) pp.\n\nDefinition same_locks_sized phi1 phi2 :=\n  forall loc n, resource_is_lock_sized n (phi1 @ loc) <-> resource_is_lock_sized n (phi2 @ loc).\n\nDefinition lockSet_block_bound lset b :=\n  forall loc, isSome (AMap.find (elt:=option rmap) loc lset) -> (fst loc < b)%positive.\n\nDefinition predat phi loc (R: pred rmap) :=\n  exists sh sh' z, phi @ loc = YES sh sh' (LK z) (SomeP rmaps.Mpred (fun _ => R)).\n\nDefinition rmap_bound b phi :=\n  (forall loc, (fst loc >= b)%positive -> phi @ loc = NO Share.bot).\n\n(* Constructive version of resource_decay (equivalent to the\nnon-constructive version, see resource_decay_join.v) *)\nDefinition resource_decay_aux (nextb: block) (phi1 phi2: rmap) : Type :=\n  prod (level phi1 >= level phi2)%nat\n  (forall l: address,\n\n  ((fst l >= nextb)%positive -> phi1 @ l = NO Share.bot) *\n  ( (resource_fmap (approx (level phi2)) (approx (level phi2)) (phi1 @ l) = (phi2 @ l))\n\n  + { rsh : _ & { v : _ & { v' : _ |\n       resource_fmap (approx (level phi2)) (approx (level phi2)) (phi1 @ l) = YES rsh pfullshare (VAL v) NoneP /\\\n       phi2 @ l = YES rsh pfullshare (VAL v') NoneP }}}\n\n  + (fst l >= nextb)%positive * { v | phi2 @ l = YES Share.top pfullshare (VAL v) NoneP }\n\n  + { v : _ & { pp : _ | phi1 @ l = YES Share.top pfullshare (VAL v) pp /\\ phi2 @ l = NO Share.bot } })).\n\nLtac breakhyps :=\n  repeat\n    match goal with\n      H : _ \\/ _  |- _ => destruct H\n    | H : _ /\\ _  |- _ => destruct H\n    | H : prod _ _  |- _ => destruct H\n    | H : sum _ _  |- _ => destruct H\n    | H : sumbool _ _  |- _ => destruct H\n    | H : sumor _ _  |- _ => destruct H\n    | H : ex _  |- _ => destruct H\n    | H : sig _  |- _ => destruct H\n    | H : sigT _  |- _ => destruct H\n    | H : sigT2 _  |- _ => destruct H\n    end;\n  discriminate || congruence || tauto || auto.\n\nLtac check_false P :=\n  let F := fresh \"false\" in\n  assert (F : P -> False) by (intro; breakhyps);\n  clear F.\n\nLtac sumsimpl :=\n  match goal with\n    |- sum ?A ?B => check_false A; right\n  | |- sum ?A ?B => check_false B; left\n  | |- sumor ?A ?B => check_false A; right\n  | |- sumor ?A ?B => check_false B; left\n  | |- sumbool ?A ?B => check_false A; right\n  | |- sumbool ?A ?B => check_false B; left\n  end.\n\nDefinition resource_decay_at (nextb: block) n (r1 r2 : resource) b :=\n  ((b >= nextb)%positive -> r1 = NO Share.bot) /\\\n  (resource_fmap (approx (n)) (approx (n)) (r1) = (r2) \\/\n  (exists rsh, exists v, exists v',\n       resource_fmap (approx (n)) (approx (n)) (r1) = YES rsh pfullshare (VAL v) NoneP /\\\n       r2 = YES rsh pfullshare (VAL v') NoneP)\n  \\/ ((b >= nextb)%positive /\\ exists v, r2 = YES Share.top pfullshare (VAL v) NoneP)\n  \\/ (exists v, exists pp, r1 = YES Share.top pfullshare (VAL v) pp /\\ r2 = NO Share.bot)).\n\nLtac range_tac :=\n  match goal with\n  | H : ~ adr_range (?b, _) _ (?b, _) |- _ =>\n    exfalso; apply H;\n    repeat split; auto;\n    try unfold Int.unsigned;\n    unfold LKSIZE;\n    omega\n  | H : ~ adr_range ?l _ ?l |- _ =>\n    destruct l;\n    exfalso; apply H;\n    repeat split; auto;\n    try unfold Int.unsigned;\n    unfold LKSIZE;\n    omega\n  end.\n\nLtac eassert :=\n  let mp := fresh \"mp\" in\n  pose (mp := fun {goal Q : Type} (x : goal) (y : goal -> Q) => y x);\n  eapply mp; clear mp.\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/sync_preds_defs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2834870708261469}}
{"text": "(*******************************************************************\n * Este archivo especifica las acciones\n * (Como transformadores de estado)\n ******************************************************************)\n\nLoad State.\n\n(* Contexto global *)\nParameter contexto : context. \n\n(********************** Predicados útiles ******************************)\nDefinition trusted_os (o : os_ident) : Prop :=\n  contexto.(ctxt_oss) o = true.\n\n(* Esto es que la current page table del so mapee la va con ma. *)\nDefinition va_mapped_to_ma (s : State) (v: vadd) (m : madd) : Prop :=\n  exists osi : os, s.(oss) s.(active_os) = Some osi\n  /\\ exists p_to_m : padd -> option madd,\n     s.(hypervisor) s.(active_os) = Some p_to_m\n  /\\ exists m2 : madd, p_to_m osi.(curr_page) = Some m2\n  /\\ exists pg : page, s.(memory) m2 = Some pg\n  /\\ exists v_to_m : vadd -> option madd, \n     pg.(page_content) = (PT v_to_m)\n  /\\ v_to_m v = Some m.\n\nDefinition os_accessible (va : vadd) : Prop :=\n  contexto.(ctxt_vadd_accessible) va = true.\n\nDefinition change_function (X Y : Set) (F : X -> option Y)\n                           (G : forall m n : X, {m = n} + {m <> n})\n                           (x:X) (y:Y) : X -> option Y :=\n  fun (a : X) => if G a x then Some y\n                          else F a.\n\nImplicit Arguments change_function [X Y].\n\n\n(*************** Acciones ***********************)\nInductive Action :=\n| read : vadd -> Action\n| write : vadd -> value -> Action\n| chmod : Action.\n\n(************** Pre y Post **********************)\nInductive Pre : State -> Action -> Prop :=\n  PreRead : forall (s : State) (va : vadd),\n            os_accessible va ->\n            s.(aos_activity) = running \n            -> (exists ma : madd, va_mapped_to_ma s va ma \n                /\\ exists pg : page, (s.(memory)) ma = Some pg\n                /\\ is_RW pg.(page_content))\n            ->  Pre s (read va)\n| PreWrite : forall (s : State) (va : vadd) (val : value),\n            os_accessible va\n            ->  s.(aos_activity) = running\n            -> (exists ma : madd, va_mapped_to_ma s va ma \n            /\\ exists pg : page, (s.(memory)) ma = Some pg\n            /\\ is_RW pg.(page_content)) \n            ->  Pre s (write va val)\n| PreChmod : forall (s : State) (va : vadd),\n             s.(aos_activity) = waiting\n             -> (exists o:os, s.(oss) s.(active_os) = Some o\n                 /\\ o.(hcall) = None)\n             -> Pre s (chmod).\n\nInductive Post : State -> Action -> State -> Prop :=\n  PostRead : forall (s : State) (va : vadd),\n             Post s (read va) s\n| PostWrite : forall (s s2 : State) (va : vadd) (val : value),\n              (exists ma : madd, va_mapped_to_ma s va ma \n              /\\ s2.(memory) = \n              change_function (s.(memory)) madd_eq ma (Page (RW (Some val)) (Os (s.(active_os))))\n              /\\ differ_memory s ma s2)\n              -> Post s (write va val) s2\n| PostChmod : forall (s s2 : State),\n              (trusted_os (s.(active_os)) \n                /\\ s2 = St s.(active_os) svc running s.(oss) s.(hypervisor) s.(memory))\n              \\/ (~trusted_os (s.(active_os)) \n                /\\ s2 = St s.(active_os) usr running s.(oss) s.(hypervisor) s.(memory))\n              -> Post s chmod s2.\n\n(************************* Valid State ******************************)\nDefinition valid_state_3 (s: State) : Prop :=\n  ((s.(aos_activity) = running /\\ trusted_os s.(active_os))  \n  \\/ s.(aos_activity) = waiting)\n  -> s.(aos_exec_mode) = svc.\n\nDefinition valid_state_5 (s : State) : Prop :=\n  forall (pa : padd) (osi : os_ident) (p_to_m : padd -> option madd),\n          Some p_to_m = s.(hypervisor) osi\n          -> exists ma : madd, p_to_m pa = Some ma\n             /\\ (exists pag : page, s.(memory) ma = Some pag\n             /\\ pag.(page_owned_by) = Os osi)\n             /\\ (forall pa2 : padd, pa <> pa2 \n                -> exists ma2 : madd, p_to_m pa2 = Some ma2\n                /\\ ma <> ma2).\n\nDefinition valid_state_6 (s : State) : Prop :=\n  forall (p : page) (osi : os_ident) (v_to_m : vadd -> option madd),\n           p.(page_owned_by) = Os osi\n           -> p.(page_content) = PT v_to_m\n           -> (exists ma : madd,\n              s.(memory) ma = Some p)\n           -> forall va: vadd, (os_accessible va -> \n                                   (exists ma1 : madd, v_to_m va = Some ma1\n                                 /\\ exists pg1 : page, s.(memory) ma1 = Some pg1\n                                 /\\ pg1.(page_owned_by) = Os osi))\n                            /\\ (~os_accessible va -> \n                                    (exists ma1 : madd, v_to_m va = Some ma1\n                                  /\\ exists pg1 : page, s.(memory) ma1 = Some pg1\n                                  /\\ pg1.(page_owned_by) = Hyp)).\n\nInductive valid_state : State -> Prop :=\n  v_st : forall (s: State),\n         valid_state_3 s\n         -> valid_state_5 s\n         -> valid_state_6 s\n         -> valid_state s.\n\nInductive OneStepExec : State -> Action -> State -> Prop :=\n  OneStepExec_intro : forall (s s2 : State) (a : Action),\n                      valid_state s\n                      -> Pre s a\n                      -> Post s a s2\n                      -> OneStepExec s a s2.\n\n(* Ej. 7.6 *)\nLemma valid_state_3_invariant : forall (s s2 : State) (a : Action),\n              OneStepExec s a s2\n              -> valid_state_3 s2.\nProof.\n  intros.\n  inversion_clear H.\n  inversion_clear H0.\n  destruct a.\n    inversion H2.\n    rewrite <- H5.\n    assumption.\n\n    inversion_clear H2.\n    inversion_clear H0.\n    inversion_clear H2.\n    inversion_clear H5.\n    inversion_clear H6.\n    unfold valid_state_3 in *.\n    rewrite H8.\n    rewrite H5.\n    rewrite H7.\n    assumption.\n    \n    inversion_clear H2.\n    unfold valid_state_3 in *.\n    inversion_clear H0;\n    inversion_clear H2;\n    inversion_clear H5;\n    simpl;\n    intro.\n      reflexivity.\n\n      inversion_clear H2.\n        inversion_clear H5.\n        elim H0.\n        assumption.\n        \n        discriminate.\nQed.\n\n(* Ej. 7.7 *)\nLemma Read_Isolation : forall (s1 s2 : State) (va : vadd),\n                       OneStepExec s1 (read va) s2\n                       -> exists ma : madd, va_mapped_to_ma s1 va ma \n                       /\\ exists pg : page, Some pg = s1.(memory) ma \n                       /\\ pg.(page_owned_by) = Os s1.(active_os).\nProof.\n  intros.\n  inversion_clear H.\n  inversion_clear H0.\n  inversion_clear H1.\n  inversion_clear H6.\n  exists x.\n  inversion_clear H1.\n  split.\n    assumption.\n    \n    (* Paso 1 *)\n    clear H7.\n    inversion_clear H6.\n    inversion_clear H1.\n    inversion_clear H7.\n    inversion_clear H1.\n    inversion_clear H8.\n    inversion_clear H1.\n    inversion_clear H9.\n    inversion_clear H1.\n    inversion_clear H10.\n    inversion_clear H1.\n\n    (* Paso 2 *)\n    unfold valid_state_5 in *.\n    pose proof (H3 x0.(curr_page) s1.(active_os) x1). clear H3.\n    symmetry in H7.\n    pose proof (H1 H7). clear H1.\n    inversion_clear H3.\n    inversion_clear H1.\n    inversion_clear H12. clear H13.\n    inversion_clear H1.\n    inversion_clear H12.\n    rewrite H8 in H3.\n    inversion H3. clear H3.\n    rewrite <- H14 in H1. clear H14 x5.\n    rewrite H9 in H1.\n    inversion H1. clear H1.\n    rewrite <- H12 in H13. clear H12 x6.\n\n    (* Paso 3 *)\n    unfold valid_state_6 in *.\n    pose proof (H4 x3 s1.(active_os) x4). clear H4.\n    assert (exists ma: madd, memory s1 ma = Some x3).\n    exists x2. assumption.\n    pose proof (H1 H13 H10 H3 va). clear H1 H13 H10 H3.\n    inversion_clear H4. clear H3.\n    pose proof (H1 H0). clear H1 H0.\n    inversion_clear H3.\n    inversion_clear H0.\n    inversion_clear H3.\n    inversion_clear H0.\n    rewrite H11 in H1.\n    inversion H1. clear H1.\n    rewrite <- H10 in *.\n    exists x6.\n    symmetry in H3.\n    split; assumption.\nQed.", "meta": {"author": "adrielulanovsky", "repo": "Coq", "sha": "f75a35e28d171239ec6c8af3f24b64dc04628202", "save_path": "github-repos/coq/adrielulanovsky-Coq", "path": "github-repos/coq/adrielulanovsky-Coq/Coq-f75a35e28d171239ec6c8af3f24b64dc04628202/TP7/bibliotecas/V_Final/Actions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.40733340004593016, "lm_q1q2_score": 0.2834870708261468}}
{"text": "Require Export ParDB.Spec.\nRequire Export ParDB.Lemmas.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Export Coq.Program.Equality.\nRequire Export Coq.Program.Tactics.\n\nModule Type Kit.\n\n  Parameter TM: Type.\n  Parameter inst_vr: Vr TM.\n  Parameter inst_ap: ∀ Y {vrY: Vr Y} {wkY: Wk Y} {liftY: Lift Y TM}, Ap TM Y.\n\n  Parameter inst_ap_inj: LemApInj TM Ix.\n  Parameter inst_ap_vr:\n    ∀ Y {vrY: Vr Y} {wkY: Wk Y} {liftY: Lift Y TM}, LemApVr TM Y.\n  Parameter inst_ap_comp:\n    ∀ Y Z {vrY: Vr Y} {wkY: Wk Y} {liftY: Lift Y TM} {vrZ: Vr Z} {wkZ: Wk Z}\n      {liftZ: Lift Z TM} {apYZ: Ap Y Z} {compUpYZ: LemCompUp Y Z}\n      {apLiftYZTM: LemApLift Y Z TM}, LemApComp TM Y Z.\n  Parameter inst_ap_liftSub:\n    ∀ Y {vrY: Vr Y} {wkY: Wk Y} {liftY: Lift Y TM}, LemApLiftSub TM Y.\n  Parameter inst_ap_ixComp:\n    ∀ (t: TM) (ξ: Sub Ix) (ζ: Sub TM), t[ξ][ζ] = t[⌈ξ⌉ >=> ζ].\n\nEnd Kit.\n\nModule Inst (kit: Kit).\n\n  Local Ltac crush :=\n    intros; cbn in * |-;\n    repeat\n      (cbn;\n       repeat crushDbSyntaxMatchH;\n       rewrite ?ap_vr, ?ap_comp);\n    auto.\n\n  Import kit.\n\n  Instance inst_apTMZTM {Z} {vrZ: Vr Z} {apTMZ: Ap TM Z} :\n    LemApLift TM Z TM := λ _ _, eq_refl.\n  Instance inst_apLiftIxIx: LemApLift Ix Ix TM := ap_vr.\n\n  Instance compUpTMIx: LemCompUp TM Ix := {}.\n  Proof. intros; extensionality i; destruct i; crush. Qed.\n\n  Instance inst_wkApIx: LemApWk TM Ix := λ _, eq_refl.\n\n  Instance compUpTM: LemCompUp TM TM := {}.\n  Proof.\n    intros; extensionality i; destruct i; crush.\n    rewrite inst_ap_ixComp; f_equal.\n    extensionality j; destruct j; crush.\n  Qed.\n\n  Instance wkApTM: LemApWk TM TM := {}.\n  Proof.\n    crush.\n    rewrite  <- ap_liftSub.\n    f_equal.\n    extensionality i; crush.\n  Qed.\n\n  (* Instance sbTM: Subst TM := {}. *)\n\n  (* Automatically populate the infrastructure database for type TM with lemmas\n     for which the rewrite direction is certain. *)\n  (* Hint Rewrite (apply_wkm_comm TM Ix) : infrastructure. *)\n  (* Hint Rewrite (apply_wkm_beta1_cancel TM TM) : infrastructure. *)\n  (* Hint Rewrite (apply_beta1_comm TM TM) : infrastructure. *)\n\n  (* Hint Rewrite (apply_wkm_up_comm TM Ix) : infrastructure. *)\n  (* Hint Rewrite (apply_wkm_beta1_up_cancel TM TM) : infrastructure. *)\n  (* Hint Rewrite (apply_beta1_up_comm TM TM) : infrastructure. *)\n\n  (* Hint Rewrite (apply_wkm_up2_comm TM Ix) : infrastructure. *)\n  (* Hint Rewrite (apply_wkm_beta1_up2_cancel TM TM) : infrastructure. *)\n  (* Hint Rewrite (apply_beta1_up2_comm TM TM) : infrastructure. *)\n\n  (* Hint Rewrite (apply_wkm_ups_comm TM Ix) : infrastructure. *)\n  (* Hint Rewrite (apply_wkm_beta1_ups_cancel TM TM) : infrastructure. *)\n  (* Hint Rewrite (apply_beta1_ups_comm TM TM) : infrastructure. *)\n\n  (* Hint Rewrite (ap_liftSub' TM TM) : infrastructure. *)\n  (* Hint Rewrite (up_liftSub TM) : infrastructure. *)\n  (* Hint Rewrite (liftSub_wkm TM) : infrastructure. *)\n  (* Hint Rewrite (liftSub_wkms TM) : infrastructure. *)\n\n  (* Hint Rewrite (up_wk TM) : infrastructure. *)\n  (* Hint Rewrite (wk_ap TM) : infrastructure. *)\n\n  (* Set Printing  Implicit. *)\n  (* Unset Printing Notations. *)\n  (* Print Rewrite HintDb infrastructure. *)\n\n\nEnd Inst.\n", "meta": {"author": "skeuchel", "repo": "fomegac", "sha": "7a654d7c91d76caea9505090052046a51fbe9f3f", "save_path": "github-repos/coq/skeuchel-fomegac", "path": "github-repos/coq/skeuchel-fomegac/fomegac-7a654d7c91d76caea9505090052046a51fbe9f3f/ParDB/Inst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.28341135339225565}}
{"text": "Require Import Equations.Equations.\nRequire Import Equations.Prop.Subterm. (* lexicographic ordering *)\n\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nRequire Import PeanoNat.\nRequire Import Psatz. (* lia tactic for linear integer arithmetic *)\n\nRequire Export Parser.HList.\nRequire Export Parser.Lexicographic.\nRequire Export Parser.Option.\n\nRecord Cell: Type := mkCell {\n  (** when building networks from syntaxes, we use the field `main_type` to\n      store the type of the syntax node corresponding to this cell *)\n  main_type: Type;\n  cell_type: Type;\n  input_types: list Type;\n  update: hlist input_types -> cell_type;\n  measure: cell_type -> nat;\n  state: cell_type;\n}.\n\nArguments mkCell main_type { cell_type } { input_types }.\n\nRecord Network: Type := mkNetwork {\n  cells: nat -> Cell;\n  inputs: nat -> list nat;\n  registered: nat -> list nat;\n}.\n\nDefinition set_cell (N: Network) (k: nat) (cell: Cell): Network := {|\n  cells := fun k' => if Nat.eq_dec k k' then cell else cells N k';\n  inputs := inputs N;\n  registered := registered N;\n|}.\n\nDefinition io_types (N: Network): Prop :=\n  forall k, map (fun k' => cell_type (cells N k')) (inputs N k) = input_types (cells N k).\n\nDefinition io_types_instantiate:\n  forall N k,\n    io_types N ->\n    map (fun k' => cell_type (cells N k')) (inputs N k) = input_types (cells N k).\nProof.\n  unfold io_types; lights.\nQed.\n\nLtac io_types_instantiate :=\n  match goal with\n  | H: io_types ?N, k: nat |- _ =>\n    poseNew (Mark (k, N) \"io_types_instantiate\");\n    pose proof (io_types_instantiate N k H)\n  end.\n\nDefinition max_pointer (num_cells: nat) (N: Network): Prop :=\n  forall k,\n    k < num_cells ->\n    forall k', In k' (registered N k) -> k' < num_cells.\n\nLtac rewrite_cell :=\n  match goal with\n  | H: cells _ _ = mkCell _ _ _ |- _ => rewrite H in *\n  end.\n\nDefinition io_types_set_cell:\n  forall N k cell,\n    io_types N ->\n    input_types (cells N k) = input_types cell ->\n    cell_type (cells N k) = cell_type cell ->\n    io_types (set_cell N k cell).\nProof.\n  unfold set_cell;\n    repeat match goal with\n    | H: map _ _ = input_types _ |- _ => rewrite <- H in *\n    | _ => light || unfold io_types || io_types_instantiate || destruct_match || apply map_ext\n    end.\nQed.\n\nDefinition set_cell_with_inputs (N: Network) (k: nat) (cell: Cell) (ks: list nat): Network := {|\n  cells := fun k' => if Nat.eq_dec k k' then cell else cells N k';\n  inputs := fun k' => if Nat.eq_dec k k' then ks else inputs N k';\n  registered := fun k' => if in_dec Nat.eq_dec k' ks then k :: registered N k' else registered N k';\n|}.\n\nDefinition io_types_set_cell_with_inputs:\n  forall N k cell ks,\n    io_types N ->\n    ~ In k ks ->\n    (forall k', ~ In k (inputs N k')) ->\n    map (fun k' => cell_type (cells N k')) ks = input_types cell ->\n    io_types (set_cell_with_inputs N k cell ks).\nProof.\n  unfold set_cell_with_inputs;\n    repeat match goal with\n    | H: map _ _ = input_types _ |- _ => rewrite <- H in *\n    | _ => light || unfold io_types || io_types_instantiate || destruct_match || apply map_ext_in\n    end;\n    eauto with exfalso.\nQed.\n\nLemma max_pointer_set_cell:\n  forall N k cell num_cells,\n    max_pointer num_cells N ->\n    max_pointer num_cells (set_cell N k cell).\nProof.\n  unfold max_pointer; lights.\nQed.\n\nDefinition get_measure (cell: Cell): nat := measure cell (state cell).\n\nFixpoint sum_measures (num_cells: nat) (N: Network): nat :=\n  match num_cells return nat with\n  | 0 => 0\n  | S k => sum_measures k N + get_measure (cells N k)\n  end.\n\n(* Update the state of cell `k`. Returns `None` if there is nothing to do *)\nProgram Definition compute_cell (N: Network) (k: nat) (pre: io_types N): option Network :=\n  let cell: Cell := cells N k in\n  let inputs: hlist (input_types cell) :=\n    h_map (fun k' => state (cells N k')) (inputs N k) in\n  let q': cell_type cell := update cell inputs in\n  if (Compare_dec.lt_dec (measure cell q') (measure cell (state cell)))\n  then Some (set_cell N k (mkCell (main_type cell) (update cell) (measure cell) q'))\n  else None.\n\nFail Next Obligation. (* no more obligations for compute_cell *)\n\nLemma io_types_compute_cell:\n  forall N k pre N',\n    compute_cell N k pre = Some N' ->\n    io_types N ->\n    io_types N'.\nProof.\n  unfold compute_cell;\n    repeat light || destruct_match || apply io_types_set_cell || invert_constructor_equalities.\nQed.\n\nOpaque io_types.\n\nLemma max_pointer_compute_cell:\n  forall num_cells N k pre N',\n    compute_cell N k pre = Some N' ->\n    max_pointer num_cells N ->\n    max_pointer num_cells N'.\nProof.\n  unfold compute_cell;\n    repeat light || destruct_match || invert_constructor_equalities.\nQed.\n\nLemma set_cell_different:\n  forall N k k' cell,\n    k <> k' ->\n    cells (set_cell N k cell) k' = cells N k'.\nProof.\n  unfold set_cell;\n    repeat light || destruct_match.\nQed.\n\nLemma set_cell_same:\n  forall N k cell,\n    cells (set_cell N k cell) k = cell.\nProof.\n  unfold set_cell;\n    repeat light || destruct_match.\nQed.\n\nLemma sum_measure_set_cell_1:\n  forall (num_cells: nat) (N: Network) (k: nat) cell,\n    k >= num_cells ->\n    sum_measures num_cells (set_cell N k cell) = sum_measures num_cells N.\nProof.\n  induction num_cells; repeat light || destruct_match; eauto with lia.\nQed.\n\nOpaque set_cell.\n\nLemma sum_measure_set_cell_2:\n  forall (num_cells: nat) (N: Network) (k: nat) (cell: Cell),\n    k < num_cells ->\n    get_measure cell < get_measure (cells N k) ->\n    sum_measures num_cells (set_cell N k cell) < sum_measures num_cells N.\nProof.\n  induction num_cells; lights; eauto with lia.\n  destruct (Nat.eq_dec k num_cells); lights.\n\n  - rewrite sum_measure_set_cell_1; lights; eauto with lia.\n    apply Nat.add_lt_mono_l.\n    rewrite set_cell_same; auto.\n\n  - rewrite set_cell_different; lights.\n    apply Nat.add_lt_mono_r.\n    eauto with lia.\nQed.\n\nLemma compute_cell_size:\n  forall num_cells N k pre N',\n    compute_cell N k pre = Some N' ->\n    k < num_cells ->\n    sum_measures num_cells N' < sum_measures num_cells N.\nProof.\n  unfold compute_cell;\n    repeat light || destruct_match || apply sum_measure_set_cell_2 || invert_constructor_equalities.\nQed.\n\nEquations (noind) compute_cells (num_cells: nat) (N: Network) (ks: list nat)\n  (pre:\n     io_types N /\\\n     max_pointer num_cells N /\\\n     (forall k, In k ks -> k < num_cells)\n  ): Network\n  by wf (sum_measures num_cells N, length ks) lt_lex :=\n\n  compute_cells num_cells N [] _ := N;\n  compute_cells num_cells N (k :: ks) _ :=\n    let opt := compute_cell N k _ in\n    if (is_some_dec opt)\n    then compute_cells num_cells (get_option opt _) (ks ++ registered N k) _\n    else compute_cells num_cells N ks _.\n\nNext Obligation.\n  repeat light || lists || options || destruct_match;\n    eauto using max_pointer_compute_cell;\n    eauto using io_types_compute_cell.\nQed.\n\nNext Obligation.\n  apply left_lex;\n    repeat light || options || destruct_match;\n    eauto using compute_cell_size.\nQed.\n\nNext Obligation.\n  apply right_lex; auto.\nQed.\n\nFail Next Obligation. (* No more obligations for compute_cells *)\n\nLtac compute_cells_def :=\n  rewrite compute_cells_equation_1 in * ||\n  rewrite compute_cells_equation_2 in *.\n\nLtac rewrite_known_states :=\n  match goal with\n  | H1: state _ = eq_rect _ _ (_, ?opt) _ _,\n    H2: opt_forall ?opt _ |- _ =>\n    rewrite H1\n  end.\n\nLtac rewrite_known_cell_types :=\n  match goal with\n  | H: cell_type _ = _ |- _ => rewrite H in *\n  end.\n\nLtac rewrite_known_updates :=\n  match goal with\n  | H: update _ = _ |- _ => rewrite H in *\n  end.\n\nLtac rewrite_known_inputs2 :=\n  match goal with\n  | H:inputs _ _ = [] |- _ => rewrite H in *\n  | H:inputs _ _ = _ :: _ |- _ => rewrite H in *\n  end.\n\nLtac rewrite_known_states2 :=\n  match goal with\n  | H: state _ = _ |- _ => rewrite H in *\n  end.\n\nLtac rewrite_known_inputs :=\n  match goal with\n  | H: inputs _ _ = [] |- _ => rewrite H in *; clear H\n  | H: inputs _ _ = _ :: _ |- _ => rewrite H in *; clear H\n  end.\n\nLtac rewrite_known_cells :=\n  match goal with\n  | H: cells _ _ = _ |- _ => rewrite H in *; clear H\n  end.\n\nLtac rewrite_known_input_types :=\n  match goal with\n  | H: input_types _ = _ |- _ => rewrite H in *\n  end.\n\nLtac rewrite_known_measures :=\n  match goal with\n  | H: measure _ = _ |- _ => rewrite H in *\n  end.\n", "meta": {"author": "epfl-lara", "repo": "scallion-proofs", "sha": "3f048aabee5c961446d9993a70355eff510a2ddb", "save_path": "github-repos/coq/epfl-lara-scallion-proofs", "path": "github-repos/coq/epfl-lara-scallion-proofs/scallion-proofs-3f048aabee5c961446d9993a70355eff510a2ddb/PropagatorNetwork.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032313, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.283411346383522}}
{"text": "From stdpp Require Import gmap.\nFrom cap_machine Require Import stdpp_extra.\nFrom iris.proofmode Require Import proofmode.\nFrom Equations Require Import Equations.\n\nSection simpl_gmap.\n\n  Variable K: Type.\n  Hypothesis HeqdecK: EqDecision K.\n  Hypothesis HcountK: Countable K.\n\n  (* reified gmap *)\n  Inductive rgmap {A: Type}: Type :=\n  | Ins (k: nat) (a: A) (m: rgmap)\n  | Del (k: nat) (m: rgmap)\n  | Symb.\n\n  Fixpoint denote {A: Type} (rm: @rgmap A) (fm: nat -> option K) (m: gmap K A): gmap K A :=\n    match rm with\n    | Ins k a rm =>\n      match fm k with\n      | Some k => <[k := a]> (denote rm fm m)\n      | None => denote rm fm m\n      end\n    | Del k rm =>\n      match fm k with\n      | Some k => delete k (denote rm fm m)\n      | None => denote rm fm m\n      end\n    | Symb => m\n    end.\n\n  Fixpoint rlength {A: Type} (rm: @rgmap A): nat :=\n    match rm with\n    | Ins _ _ rm => S (rlength rm)\n    | Del _ rm => S (rlength rm)\n    | Symb => O\n    end.\n\n  Fixpoint remove_key {A: Type} k (rm: @rgmap A) :=\n    match rm with\n    | Ins k' a rm => if decide (k = k') then remove_key k rm else Ins k' a (remove_key k rm)\n    | Del k' rm => if decide (k = k') then remove_key k rm else Del k' (remove_key k rm)\n    | Symb => Symb\n    end.\n\n  Lemma rlength_remove_key:\n    forall A k (rm: @rgmap A), rlength (remove_key k rm) <= rlength rm.\n  Proof.\n    induction rm; simpl; auto.\n    - destruct (decide (k = k0)); simpl; lia.\n    - destruct (decide (k = k0)); simpl; lia.\n  Qed.\n\n  Equations simpl_rmap {A: Type} (rm: @rgmap A): @rgmap A by wf (rlength rm) lt :=\n    simpl_rmap (Ins k a rm) := Ins k a (simpl_rmap (remove_key k rm));\n    simpl_rmap (Del k rm) := Del k (simpl_rmap (remove_key k rm));\n    simpl_rmap (Symb) := Symb.\n  Next Obligation.\n    generalize (rlength_remove_key _ k rm). lia. Qed.\n  Next Obligation.\n    generalize (rlength_remove_key _ k rm). lia. Qed.\n\n  Lemma denote_remove_key_ins:\n    forall A fm (rm: @rgmap A) k k' a (m: gmap K A),\n      fm k = Some k' ->\n      <[k':=a]> (denote rm fm m) = <[k':=a]> (denote (remove_key k rm) fm m).\n  Proof.\n    induction rm; simpl; auto.\n    - intros. destruct (decide (k0 = k)).\n      + subst k0. rewrite H.\n        rewrite insert_insert.\n        eapply IHrm; eauto.\n      + case_eq (fm k); intros.\n        * cbn. destruct (decide (k1 = k')).\n          { subst k1. rewrite insert_insert H0.\n            rewrite insert_insert.\n            eapply IHrm. auto.\n          }\n          { simpl. rewrite insert_commute; auto.\n            rewrite H0.\n            erewrite IHrm; eauto.\n            rewrite insert_commute; eauto. }\n        * simpl. rewrite H0. eauto.\n    - intros. destruct (decide (k0 = k)).\n      + subst k0; rewrite H. rewrite insert_delete_insert. eapply IHrm; eauto.\n      + simpl. case_eq (fm k); intros.\n        * destruct (decide (k1 = k')).\n          { subst k1. rewrite !insert_delete_insert.\n            eapply IHrm; eauto. }\n          { erewrite <- delete_insert_ne; auto.\n            erewrite IHrm, delete_insert_ne; eauto. }\n        * eauto.\n  Qed.\n\n  Lemma denote_remove_key_del:\n    forall A fm (rm: @rgmap A) k k' (m: gmap K A),\n      fm k = Some k' ->\n      delete k' (denote rm fm m) = delete k' (denote (remove_key k rm) fm m).\n  Proof.\n    induction rm; simpl; auto.\n    - intros. destruct (decide (k0 = k)).\n      + subst k0. rewrite H. rewrite delete_insert_delete. eauto.\n      + simpl. case_eq (fm k); intros.\n        * destruct (decide (k1 = k')).\n          { subst k1. rewrite !delete_insert_delete.\n            eapply IHrm; eauto. }\n          { rewrite delete_insert_ne; auto.\n            erewrite IHrm, <- delete_insert_ne; eauto. }\n        * eauto.\n    - intros. destruct (decide (k0 = k)).\n      + subst k0; rewrite H delete_idemp. eauto.\n      + simpl. case_eq (fm k); intros.\n        * destruct (decide (k1 = k')).\n          { subst k1. rewrite !delete_idemp.\n            eapply IHrm; eauto. }\n          { rewrite delete_commute; auto.\n            erewrite IHrm, delete_commute; eauto. }\n        * eauto.\n  Qed.\n\n  Lemma denote_remove_key_none:\n    forall A fm (rm: @rgmap A) k (m: gmap K A),\n      fm k = None ->\n      denote rm fm m = denote (remove_key k rm) fm m.\n  Proof.\n    induction rm; simpl; auto.\n    - intros. destruct (decide (k0 = k)).\n      + subst k0. rewrite H. auto.\n      + simpl. destruct (fm k); auto.\n        erewrite IHrm; eauto.\n    - intros. destruct (decide (k0 = k)).\n      + subst k0. rewrite H. auto.\n      + simpl. destruct (fm k); auto.\n        erewrite IHrm; eauto.\n  Qed.\n\n  Lemma simpl_rmap_correct':\n    forall A fm n (rm: @rgmap A) (m: gmap K A),\n      rlength rm <= n ->\n      denote rm fm m = denote (simpl_rmap rm) fm m.\n  Proof.\n    induction n; intros.\n    - destruct rm; simpl in H; try lia.\n      reflexivity.\n    - destruct rm; [| | reflexivity].\n      + rewrite simpl_rmap_equation_1; simpl.\n        rewrite <- (IHn (remove_key k rm)).\n        * case_eq (fm k); intros.\n          { apply denote_remove_key_ins; auto. }\n          { apply denote_remove_key_none; auto. }\n        * generalize (rlength_remove_key _ k rm). simpl in H; lia.\n      + rewrite simpl_rmap_equation_2; simpl.\n        rewrite <- (IHn (remove_key k rm)).\n        * case_eq (fm k); intros.\n          { apply denote_remove_key_del; auto. }\n          { apply denote_remove_key_none; auto. }\n        * generalize (rlength_remove_key _ k rm). simpl in H; lia.\n  Qed.\n\n  Lemma simpl_rmap_correct:\n    forall A fm (rm rm': @rgmap A) (m: gmap K A),\n      simpl_rmap rm = rm' ->\n      denote rm fm m = denote rm' fm m.\n  Proof.\n    intros. subst rm'. apply (simpl_rmap_correct' _ fm (rlength rm)); auto; lia.\n  Qed.\n\nEnd simpl_gmap.\n\nFrom Ltac2 Require Import Ltac2 Option Constr.\n\nLtac2 rec add_key (l: constr list) (k: constr) (n: constr) :=\n  match l with\n  | [] => (k::l, n)\n  | c :: ll => match Constr.equal c k with\n                | false => let (lll, nn) := add_key ll k '(S $n) in\n                          ((c :: lll), nn)\n                | _ => (l, n)\n                end\n  end.\n\nLtac2 rec make_list (l: constr list) :=\n  match l with\n  | [] => '[]\n  | c :: ll => let k := make_list ll in\n              '($c :: $k)\n  end.\n\nLtac2 rec reify_helper kk aa term fm :=\n  lazy_match! term with\n  | <[?k := ?a]> ?m =>\n    let (env, k') := add_key fm k 'O in\n    let (rm, h, fm'') := reify_helper kk aa m env in\n    (constr:(@Ins $aa $k' $a $rm), h, fm'')\n  | delete ?k ?m =>\n    let (env, k') := add_key fm k 'O in\n    let (rm, h, fm'') := reify_helper kk aa m env in\n    (constr:(@Del $aa $k' $rm), h, fm'')\n  | ?m => (constr:(@Symb $aa), m, fm)\n  end.\n\nLocal Ltac2 replace_with (lhs: constr) (rhs: constr) :=\n  ltac1:(lhs rhs |- replace lhs with rhs) (Ltac1.of_constr lhs) (Ltac1.of_constr rhs).\n\n(* Debug test *)\n(* Goal <[5 := 2]> (<[5 := 2]> (<[5 := 2]> (<[5 := 2]> (<[5 := 2]> (<[5 := 2]> (<[5 := 2]> (<[6 := 3]> (∅: gmap nat nat)))))))) = <[5 := 2]> (<[6 := 3]> (∅: gmap nat nat)). *)\n(*   lazy_match! goal with *)\n(*   | [|- ?x = _] => let (x', m, fm) := reify_helper 'nat 'nat x [] in *)\n(*                  let env := make_list fm in *)\n(*                  replace_with x '(@denote _ _ _ _ $x' (fun n => @list_lookup _ n $env) $m) > [() | reflexivity]; *)\n(*                  erewrite (@simpl_rmap_correct nat _ _ nat (fun n => @list_lookup _ n $env)) > [() | vm_compute; reflexivity] *)\n(*   end. time (cbn [denote list_lookup lookup]). *)\n(*   reflexivity. *)\n(* Qed. *)\n\nLtac2 rec make_list_from_unions h x :=\n  match! x with\n  | union ?a (singleton ?b) =>\n    ltac1:(h b |- try (rewrite (delete_notin _ b); [|simplify_map_eq; rewrite -not_elem_of_dom h; set_solver; fail])) (Ltac1.of_constr h) (Ltac1.of_constr b);\n    make_list_from_unions h a\n  | singleton ?x => ltac1:(h x |- try (rewrite (delete_notin _ x); [|simplify_map_eq; rewrite -not_elem_of_dom h; set_solver+; fail])) (Ltac1.of_constr h) (Ltac1.of_constr x)\n  end.\n\nLtac2 post_process k m :=\n  ltac1:(k m |- match goal with\n               | [h : dom (gset k) m = _ ∖ ?x |- _ ] =>\n                 let f := ltac2:(h x |- make_list_from_unions (Option.get (Ltac1.to_constr h)) (Option.get (Ltac1.to_constr x)))\n                 in f h x\n               | _ => idtac\n               end) (Ltac1.of_constr k) (Ltac1.of_constr m).\n\n\n(* vm_compute does not work here, as it does to much calculation, so we come up with a more refined way of simplifying `simpl_rmap` expressions *)\n\n(* Clear all hypothesis that do not explicitly feature in the goal, to avoid incorrect substitutions later. *)\nLocal Ltac clear_all :=\n  repeat (match goal with\n        | H : _ |- _ => clear H end ).\n\nDefinition boxed {A} (P: A): A := P.\nTheorem boxed_eq `(P : A): (boxed P) = P. Proof. auto. Qed.\nLocal Ltac box_all := repeat (match goal with\n      |  |- context [Ins ?k ?v] => lazymatch v with\n                                 | boxed _ => fail | _ => let name := fresh \"name\" in remember v as name in * at 1; rewrite -{1}(boxed_eq name) end end).\n\nLtac simpl_rmap_compute :=\n  clear_all; box_all; vm_compute simpl_rmap; subst.\n\nLtac2 map_simpl_aux k a x encode :=\n  let (x', m, fm) := (reify_helper k a x []) in\n  let env := make_list fm in\n  replace_with x '(@denote _ _ _ _ $x' (fun n => @list_lookup _ n $env) $m) > [() | reflexivity];\n  (erewrite (@simpl_rmap_correct _ _ _ _ (fun n => @list_lookup _ n $env))) > [() | ltac1:(simpl_rmap_compute); reflexivity];\n  cbn [denote list_lookup lookup];\n  post_process k m.\n\nLtac2 map_simpl_aux_debug k a x encode :=\n  let (x', m, fm) := (reify_helper k a x []) in\n  let env := make_list fm in\n  replace_with x '(@denote _ _ _ _ $x' (fun n => @list_lookup _ n $env) $m) > [() | reflexivity];\n  (erewrite (@simpl_rmap_correct _ _ _ _ (fun n => @list_lookup _ n $env))) > [() | ltac1:(simpl_rmap_compute); reflexivity];\n  time (cbn [denote list_lookup lookup]);\n  time (post_process k m).\n\nFrom iris.proofmode Require Import environments.\n\nSet Default Proof Mode \"Classic\".\n\nLtac map_simpl name :=\n  match goal with\n  | |- context [ Esnoc _ (base.ident.INamed name) ([∗ map] _↦_ ∈ ?m, _)%I ] =>\n    match type of m with\n\n    | ?t => match eval compute in t with (* type will not compute for very large maps *)\n      | gmap ?K ?A =>\n        let f := ltac2:(k a m encode |- map_simpl_aux (Option.get (Ltac1.to_constr k)) (Option.get (Ltac1.to_constr a)) (Option.get (Ltac1.to_constr m)) (Option.get (Ltac1.to_constr encode))) in\n        f K A m (@encode K _ _)\n      end\n    end\n  end.\n\nLtac map_simpl_debug name :=\n  match goal with\n  | |- context [ Esnoc _ (base.ident.INamed name) ([∗ map] _↦_ ∈ ?m, _)%I ] =>\n    match type of m with\n    | gmap ?K ?A =>\n      let f := ltac2:(k a m encode |- map_simpl_aux_debug (Option.get (Ltac1.to_constr k)) (Option.get (Ltac1.to_constr a)) (Option.get (Ltac1.to_constr m)) (Option.get (Ltac1.to_constr encode))) in\n      f K A m (@encode K _ _)\n    end\n  end.\n\nFrom iris.proofmode Require Import reduction proofmode.\n\nLtac disjunct_cases m i :=\n  match m with\n  | <[?k := _]> ?m' => destruct (decide (k = i)); disjunct_cases m' i\n  | delete ?k ?m' => destruct (decide (k = i)); disjunct_cases m' i\n  | _ => try subst i; try discriminate; simplify_map_eq; try reflexivity\n  end.\n\nLtac solve_map_eq :=\n  match goal with\n  | |- ?m !! ?i = ?m' !! ?i => disjunct_cases m i\n  end.\n\nLtac iFrameMapSolve' name :=\n  lazymatch goal with\n  | |- envs_entails ?H ([∗ map] _↦_ ∈ ?m, _)%I =>\n    lazymatch pm_eval (envs_lookup name H) with\n    | Some (_, ?X) =>\n      lazymatch X with\n      | ([∗ map] _↦_ ∈ ?m', _)%I =>\n        match type of m' with\n        | ?t => match eval compute in t with (* type will not compute for very large maps *)\n          | gmap ?K ?A =>\n            replace m' with m; [iFrame name| apply map_eq_iff; intros; solve_map_eq]\n          end\n        end\n      | _ => idtac \"The given hypothesis is not of the form ([∗ map] _↦_ ∈ _, _)\"; idtac X\n      end\n    | _ => idtac \"Can't find the given hypothesis\"\n    end\n  | _ => idtac \"The goal is not of the form ([∗ map] _↦_ ∈ _, _)\"\n  end.\n\nLtac iFrameMapSolve name :=\n  map_simpl name; iFrameMapSolve' name.\n\nTactic Notation \"iFrameMapSolve\" \"+\" hyp_list(Hs) constr(name) := clear -Hs; iFrameMapSolve name.\n\n(* From cap_machine Require Import rules logrel addr_reg_sample. *)\n\n(* Section test. *)\n(*   Context {Σ:gFunctors} {memg:memG Σ} {regg:regG Σ} *)\n(*           {nainv: logrel_na_invs Σ} *)\n(*           `{MP: MachineParameters}. *)\n\n(*   Lemma test pc_p pc_b pc_e a_first: *)\n(*     forall (rmap: gmap RegName Word), *)\n(*       dom (gset RegName) rmap = all_registers_s ∖ {[PC; r_env; r_t0; r_t1]} -> *)\n(*       a_first = 0%a → *)\n(*       (([∗ map] k↦y ∈ <[r_t6:=WInt 0%Z]> *)\n(*         (delete r_t1 *)\n(*                 (<[r_t4:=WInt 0%Z]> *)\n(*                  (<[r_t2:=WInt 0%Z]> *)\n(*                   (<[r_t3:=WCap pc_p pc_b pc_e (a_first ^+ 0)%a]> (<[r_env:=WInt 42%Z]> (<[r_t5:=WInt 0%Z]> rmap)))))), *)\n(*         k ↦ᵣ y)) -∗ *)\n(*            ([∗ map] r↦w0 ∈ <[r_t3:=WInt 0%Z]> *)\n(*             (<[r_t2:=WInt 0%Z]> (<[r_t4:=WInt 0%Z]> (<[r_t6:=WInt 0%Z]> (<[r_t5:=WInt 0%Z]> rmap)))), *)\n(*             r ↦ᵣ w0). *)\n(*   Proof. *)\n(*     iIntros (rmap Hdom Heq) \"Hregs\". *)\n(*     map_simpl_debug \"Hregs\". *)\n(*  Abort. *)\n\n(* End test. *)\n", "meta": {"author": "logsem", "repo": "cerise", "sha": "a578f42e55e6beafdcdde27b533db6eaaef32920", "save_path": "github-repos/coq/logsem-cerise", "path": "github-repos/coq/logsem-cerise/cerise-a578f42e55e6beafdcdde27b533db6eaaef32920/theories/map_simpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.28341133937478813}}
{"text": "From stdpp Require Import prelude sorting finite.\nFrom Coq Require Import ssreflect.\nFrom LS2NF Require Import grammar util ambiguity acyclic sub_derive slice derivation witness.\n\nSection encoding.\n\n  Context {Σ N : Type} `{!EqDecision Σ} `{!Inhabited Σ} `{!EqDecision N} `{!Finite N}.\n  Context (G : grammar Σ N) `{!acyclic G}.\n\n  Open Scope grammar_scope.\n\n  (* sat model *)\n\n  Record model := {\n    term : nat → Σ;\n    line : nat → nat;\n    col : nat → nat;\n    line_col i := (line i, col i);\n    can_derive : N → nat (* start (inclusive) *) → nat (* length, positive *) → Prop;\n    can_reach_from : N → nat (* start (inclusive) *) → nat (* length, positive *) → Prop;\n    ε_can_reach_from : N → Prop;\n  }.\n\n  (* decode *)\n\n  Definition decode m k : sentence Σ :=\n    (λ i, term m i @ (line m i, col m i)) <$> (index_range k).\n\n  Lemma decode_length m k :\n    length (decode m k) = k.\n  Proof.\n    by rewrite fmap_length index_range_length.\n  Qed.\n\n  Lemma decode_lookup m k i :\n    i < k → (decode m k) !! i = Some (term m i @ (line m i, col m i)).\n  Proof.\n    intros. rewrite list_lookup_fmap index_range_lookup //.\n  Qed.\n\n  Definition encode S (w : sentence Σ) : model := {|\n    term i :=\n      match w !! i with\n      | Some (a @ _) => a\n      | None => inhabitant\n      end;\n    line i :=\n      match w !! i with\n      | Some (_ @ (x, _)) => x\n      | None => 0\n      end;\n    col i :=\n      match w !! i with\n      | Some (_ @ (_, y)) => y\n      | None => 0\n      end;\n    can_derive A x δ := (G ⊨ A => slice w x δ);\n    can_reach_from A x δ := (reachable G (S, w) (A, slice w x δ));\n    ε_can_reach_from A := (reachable G (S, w) (A, []));\n  |}.\n\n  Lemma decode_encode S w :\n    decode (encode S w) (length w) = w.\n  Proof.\n    apply list_eq_same_length with (n := length w) => //.\n    { by rewrite decode_length. }\n    intros i x y ?. rewrite decode_lookup //=. repeat case_match.\n    all: intros ?; match goal with\n    | H : ?x = _ |- ?x = _ → _ => rewrite H\n    end => //.\n    congruence.\n  Qed.\n\n  Implicit Type w : sentence Σ.\n  Implicit Type x δ : nat.\n\n  (* formula: a predicate over a bounded model *)\n\n  Definition formula : Type := nat → model → Prop.\n\n  (* encoding predicate *)\n\n  Variable Φ_app₁ : (unary_predicate Σ) → nat → nat → formula.\n  Variable Φ_app₁_spec : ∀ φ x δ k m,\n    Φ_app₁ φ x δ k m ↔ app₁ φ (slice (decode m k) x δ) = true.\n\n  Variable Φ_app₂ : (binary_predicate Σ) → nat → nat → nat → nat → formula.\n  Variable Φ_app₂_spec : ∀ φ x1 δ1 x2 δ2 k m,\n    Φ_app₂ φ x1 δ1 x2 δ2 k m ↔\n      app₂ φ (slice (decode m k) x1 δ1) (slice (decode m k) x2 δ2) = true.\n\n  (* encoding sentence well-formed-ness *)\n\n  Definition Φ_well_formed : formula := λ k m,\n    ∀ i, 0 ≤ i < k - 1 →\n      line m i < line m (i + 1) ∨ (line m i = line m (i + 1) ∧ col m i < col m (i + 1)).\n\n  Local Hint Resolve pos_token_lt_trans : core.\n  Local Hint Unfold pos_token_lt : core.\n\n  Lemma Φ_well_formed_sat X w :\n    well_formed w →\n    Φ_well_formed (length w) (encode X w).\n  Proof.\n    intros Hw i ?. apply Sorted_monotone in Hw; eauto.\n    have [[a [l1 c1]] Ha] : is_Some (w !! i) by apply lookup_lt_is_Some; lia.\n    have [[b [l2 c2]] Hb] : is_Some (w !! (i + 1)) by apply lookup_lt_is_Some; lia.\n    specialize (Hw _ _ _ _ Ha Hb (ltac:(lia))).\n    simpl in *. by rewrite Ha Hb.\n  Qed.\n\n  Lemma Φ_well_formed_spec k m :\n    Φ_well_formed k m → well_formed (decode m k).\n  Proof.\n    intros HΦ. apply Sorted_monotone; eauto.\n    apply monotone_trans_alt_spec; eauto.\n    intros i [a [l1 c1]] [b [l2 c2]] Hi Ha Hb.\n    rewrite decode_length in Hi.\n    rewrite decode_lookup in Ha; [lia|]. invert Ha.\n    rewrite decode_lookup in Hb; [lia|]. invert Hb.\n    apply HΦ. lia.\n  Qed.\n\n  Lemma well_formed_no_dup w : well_formed w → NoDup w.\n  Proof.\n    induction w as [|a w IHw] => Hwf; constructor.\n    - apply Sorted_extends in Hwf; last apply pos_token_lt_trans.\n      rewrite ->Forall_forall in Hwf.\n      intros Hin. specialize (Hwf _ Hin). destruct a as [? [x y]].\n      unfold pos_token_lt in Hwf. simpl in Hwf. lia.\n    - invert Hwf. eauto.\n  Qed.\n  \n  Local Hint Resolve Φ_well_formed_spec well_formed_no_dup : core.\n\n  (* encoding derivation *)\n\n  Definition Φ_derive : formula := λ k m,\n    ∀ A x δ, 0 < δ (* nonempty *) → x + δ ≤ k →\n      can_derive m A x δ ↔ (\n        False ∨\n        (∃ a, A ↦ atom a ∈ G ∧ δ = 1 ∧ term m x = a) ∨\n        (∃ B φ, A ↦ unary B φ ∈ G ∧ Φ_app₁ φ x δ k m ∧ can_derive m B x δ) ∨\n        (∃ Bl Br φ, A ↦ binary Bl Br φ ∈ G ∧ (\n          (G ⊨ Bl => [] ∧ can_derive m Br x δ) ∨\n          (G ⊨ Br => [] ∧ can_derive m Bl x δ) ∨\n          (∃ δ', 0 < δ' < δ ∧\n            can_derive m Bl x δ' ∧ can_derive m Br (x + δ') (δ - δ') ∧\n            Φ_app₂ φ x δ' (x + δ') (δ - δ') k m)\n        ))\n      ).\n\n  Lemma Φ_derive_sat X w :\n    well_formed w →\n    Φ_derive (length w) (encode X w).\n  Proof.\n    intros ? A x δ ? ?.\n    have Heq : can_derive (encode X w) A x δ ↔ check_derive G A (slice w x δ).\n    { rewrite check_derive_spec derivation_spec //. }\n    rewrite Heq.\n    unfold check_derive. setoid_rewrite derivation_spec.\n    simpl can_derive.\n    setoid_rewrite Φ_app₁_spec. setoid_rewrite Φ_app₂_spec.\n    setoid_rewrite decode_encode.\n    repeat apply ZifyClasses.or_morph.\n    - rewrite slice_nil_iff; lia.\n    - split.\n      + intros [a [p [Hw ?]]]. exists a.\n        apply slice_singleton_iff in Hw as [-> Hw] => //.\n        repeat split => //=. by rewrite Hw.\n      + intros [a [? [? Hw]]].\n        have [? Hx] : is_Some (w !! x) by apply lookup_lt_is_Some; lia.\n        simpl in Hw. rewrite Hx in Hw. case_match; subst.\n        exists a. eexists. rewrite slice_singleton_iff //.\n        repeat split; eauto.\n    - done.\n    - split.\n      + intros [Bl [Br [φ [? [w1 [w2 [Hw [Hφ [HBl HBr]]]]]]]]].\n        have Hl : length (w1 ++ w2) = δ.\n        { apply (f_equal length) in Hw. by rewrite slice_length in Hw. }\n        exists Bl, Br, φ. split; first done.\n        destruct w1 as [|tk1 w1]; last destruct w2.\n        * left. rewrite app_nil_l in Hw. by rewrite Hw.\n        * right; left. rewrite app_nil_r in Hw. by rewrite Hw.\n        * right; right. apply slice_app_inv_NoDup in Hw as [Hw1 Hw2]; eauto.\n          rewrite app_length !cons_length in Hl.\n          exists (length (tk1 :: w1)). rewrite -Hw1 -Hw2.\n          repeat split => //. all: rewrite cons_length; lia.\n      + intros [Bl [Br [φ [? [Hd|[Hd|Hd]]]]]].\n        * destruct Hd as [? ?].\n          exists Bl, Br, φ. split; first done.\n          exists [], (slice w x δ). rewrite app_nil_l.\n          repeat split => //. destruct φ as [φ Hφ]; apply Hφ; by left.\n        * destruct Hd as [? ?].\n          exists Bl, Br, φ. split; first done.\n          exists (slice w x δ), []. rewrite app_nil_r.\n          repeat split => //. destruct φ as [φ Hφ]; apply Hφ; by right.\n        * destruct Hd as [δ' [? [? [? ?]]]].\n          exists Bl, Br, φ. split; first done.\n          exists (slice w x δ'), (slice w (x + δ') (δ - δ')).\n          rewrite slice_app_1. have -> : δ' + (δ - δ') = δ by lia.\n          repeat split => //.\n  Qed.\n\n  Lemma list_nonempty_length {A} (l : list A) :\n    l ≠ [] ↔ 0 < length l.\n  Proof.\n    have -> : 0 < length l ↔ 0 ≠ length l by split; [apply lt_0_neq | apply neq_0_lt].\n    apply not_iff_compat.\n    have ? := length_zero_iff_nil.\n    naive_solver.\n  Qed.\n  \n  Lemma Φ_derive_spec k m :\n    Φ_well_formed k m →\n    Φ_derive k m →\n    ∀ A x δ, 0 < δ → x + δ ≤ k →\n      can_derive m A x δ ↔ G ⊨ A => slice (decode m k) x δ.\n  Proof.\n    intros ? HΦ A x δ ? ?.\n    (* induction on range length *)\n    generalize dependent A.\n    generalize dependent x.\n    induction δ as [δ IHδ] using lt_wf_ind => x Hk A.\n    (* induction on nonterminal *)\n    have Hwf : wf (flip (succ G)) by apply acyclic_prec_wf.\n    induction A as [A IHA] using (well_founded_induction Hwf).\n    (* rewrite definition *)\n    rewrite HΦ; [|done..]. setoid_rewrite Φ_app₁_spec. setoid_rewrite Φ_app₂_spec.\n    rewrite -derivation_spec -check_derive_spec /check_derive. setoid_rewrite derivation_spec.\n    repeat apply ZifyClasses.or_morph.\n    - rewrite slice_nil_iff ?decode_length; lia.\n    - split.\n      + intros [a [? [-> ?]]]. exists a, (line m x, col m x).\n        rewrite slice_singleton_iff ?decode_length //.\n        rewrite decode_lookup; [lia|].\n        naive_solver.\n      + intros [a [p [Hw ?]]]. exists a.\n        apply slice_singleton_iff in Hw as [-> Hw]; last by rewrite decode_length.\n        rewrite decode_lookup in Hw; [lia|].\n        naive_solver.\n    - split.\n      + intros [B [φ [? [? ?]]]]. exists B, φ.\n        repeat split => //. apply IHA => //. eapply succ_unary; eauto.\n      + intros [B [φ [? [? ?]]]]. exists B, φ.\n        repeat split => //. apply IHA => //. eapply succ_unary; eauto.\n    - split.\n      + intros [Bl [Br [φ [? [Hd|[Hd|Hd]]]]]].\n        * destruct Hd as [? ?].\n          exists Bl, Br, φ. split; first done.\n          exists []. eexists. rewrite app_nil_l.\n          repeat split => //; first by destruct φ as [φ Hφ]; apply Hφ; by left.\n          apply IHA => //. eapply succ_right; eauto.\n        * destruct Hd as [? ?].\n          exists Bl, Br, φ. split; first done.\n          eexists. exists []. rewrite app_nil_r.\n          repeat split => //; first by destruct φ as [φ Hφ]; apply Hφ; by right.\n          apply IHA => //. eapply succ_left; eauto.\n        * destruct Hd as [δ' [? [? [? ?]]]].\n          exists Bl, Br, φ. split; first done.\n          do 2 eexists. repeat split; eauto.\n          { rewrite -slice_split; [lia | done]. }\n          all: apply IHδ => //; lia.\n      + intros [Bl [Br [φ [? [w1 [w2 [Hw [Hφ [HBl HBr]]]]]]]]].\n        have Hl : length (w1 ++ w2) = δ.\n        { apply (f_equal length) in Hw. rewrite slice_length in Hw; [rewrite decode_length; lia | done]. }\n        exists Bl, Br, φ. split; first done.\n        destruct w1 as [|tk1 w1]; last destruct w2.\n        * left. rewrite app_nil_l in Hw. split => //. \n          apply IHA => //. eapply succ_right; eauto. by rewrite Hw.\n        * right; left. rewrite app_nil_r in Hw. split => //.\n          apply IHA => //. eapply succ_left; eauto. by rewrite Hw.\n        * right; right. apply slice_app_inv_NoDup in Hw as [Hw1 Hw2]; eauto.\n          all: rewrite ?decode_length //.\n          rewrite Hw1 in HBl, Hφ. rewrite Hw2 in HBr, Hφ.\n          rewrite app_length !cons_length in Hl.\n          exists (length (tk1 :: w1)). repeat split => //.\n          all: try apply IHδ => //.\n          all: rewrite cons_length; lia.\n  Qed.\n\n  (* encoding reachable from (S, [0..k]) *)\n  Definition Φ_reach_nonempty S : formula := λ k m,\n    ∀ B x δ, 0 < δ → x + δ ≤ k →\n      can_reach_from m B x δ ↔ (\n        (B = S ∧ x = 0 ∧ δ = k) ∨\n        (∃ A φ, A ↦ unary B φ ∈ G ∧ can_reach_from m A x δ ∧ Φ_app₁ φ x δ k m) ∨\n        (∃ A B' φ δ', x + δ + δ' ≤ k ∧ A ↦ binary B B' φ ∈ G ∧ can_reach_from m A x (δ + δ') ∧\n          (if bool_decide (δ' = 0) then G ⊨ B' => [] else can_derive m B' (x + δ) δ') ∧\n          Φ_app₂ φ x δ (x + δ) δ' k m) ∨\n        (∃ A B' φ δ', δ' ≤ x ∧ A ↦ binary B' B φ ∈ G ∧ can_reach_from m A (x - δ') (δ' + δ) ∧\n          (if bool_decide (δ' = 0) then G ⊨ B' => [] else can_derive m B' (x - δ') δ') ∧\n          Φ_app₂ φ (x - δ') δ' x δ k m)\n      ).\n\n  Definition Φ_reach_empty S : formula := λ k m,\n    ∀ B, ε_can_reach_from m B ↔ (\n      (B = S ∧ k = 0) ∨\n      (∃ A φ, A ↦ unary B φ ∈ G ∧ ε_can_reach_from m A) ∨\n      (∃ A B' φ, A ↦ binary B B' φ ∈ G ∧ (\n        (ε_can_reach_from m A ∧ G ⊨ B' => []) ∨\n        (∃ x δ, 0 < δ ∧ x + δ ≤ k ∧\n          can_reach_from m A x δ ∧ can_derive m B' x δ))) ∨\n      (∃ A B' φ, A ↦ binary B' B φ ∈ G ∧ (\n        (ε_can_reach_from m A ∧ G ⊨ B' => []) ∨\n        (∃ x δ, 0 < δ ∧ x + δ ≤ k ∧\n          can_reach_from m A x δ ∧ can_derive m B' x δ)))\n    ).\n\n  Definition Φ_reach S : formula := λ k m,\n    Φ_reach_nonempty S k m ∧ Φ_reach_empty S k m.\n\n  Lemma Φ_reach_nonempty_sat X w k :\n    well_formed w →\n    length w = k →\n    Φ_reach_nonempty X k (encode X w).\n  Proof.\n    intros ? <- B x δ ? ?.\n    have Heq : can_reach_from (encode X w) B x δ ↔ check_reachable_from G (X, w) (B, slice w x δ).\n    { rewrite check_reachable_from_spec reachable_from_spec //. }\n    rewrite Heq /=.\n    setoid_rewrite reachable_from_spec.\n    setoid_rewrite Φ_app₁_spec. setoid_rewrite Φ_app₂_spec.\n    setoid_rewrite decode_encode.\n    repeat apply ZifyClasses.or_morph.\n    - rewrite slice_full_iff //. apply list_nonempty_length; lia.\n    - done.\n    - split.\n      + intros [A [B' [φ [wr [? [Hr [? ?]]]]]]].\n        exists A, B', φ, (length wr).\n        destruct wr as [|tk l].\n        * rewrite /= slice_nil !Nat.add_0_r.\n          rewrite app_nil_r in Hr.\n          repeat split => //.\n        * case_bool_decide => //. \n          have Hsub : sublist (slice w x δ ++ tk :: l) w by eapply reachable_sublist; eauto.\n          apply sublist_app_slice_NoDup in Hsub as [x' [Hlen [Hx' Hl]]];\n            [| eauto | rewrite slice_length; lia | lia].\n          rewrite slice_length in Hlen => //.\n          apply slice_eq_inv_NoDup in Hx' as [? Hδ]; eauto; [|rewrite slice_length; lia..].\n          subst. rewrite Hδ in Hl. rewrite -slice_app_1 -Hl.\n          repeat split => //.\n      + intros [A [B' [φ [δ' [? [? [Hr [Hd Hφ]]]]]]]].\n        exists A, B', φ, (slice w (x + δ) δ').\n        rewrite slice_app_1.\n        repeat split => //.\n        case_bool_decide; [by subst | done].\n    - split.\n      + intros [A [B' [φ [wl [? [Hr [? ?]]]]]]].\n        exists A, B', φ, (length wl).\n        destruct wl as [|tk l].\n        * rewrite /= slice_nil !Nat.sub_0_r.\n          rewrite app_nil_l in Hr.\n          repeat split => //. lia.\n        * case_bool_decide => //. \n          have Hsub : sublist ((tk :: l) ++ slice w x δ) w by eapply reachable_sublist; eauto.\n          apply sublist_app_slice_NoDup in Hsub as [x' [Hlen [Hx' Hl]]];\n            [| eauto | rewrite cons_length; lia | rewrite slice_length; lia].\n          rewrite slice_length in Hlen => //. rewrite slice_length in Hl => //.\n          apply slice_eq_inv_NoDup in Hl as [? Hδ]; eauto; [|rewrite slice_length; lia..].\n          subst. rewrite Nat.add_sub -slice_app_1 -Hx'.\n          repeat split => //. lia.\n      + intros [A [B' [φ [δ' [? [? [Hr [Hd Hφ]]]]]]]].\n        exists A, B', φ, (slice w (x - δ') δ').\n        rewrite slice_app_2; [lia|].\n        repeat split => //.\n        case_bool_decide; [by subst | done].\n  Qed.\n\n  Lemma apply_unary_nil (φ : unary_predicate Σ) :\n    app₁ φ [] = true.\n  Proof. by destruct φ. Qed.\n\n  Lemma apply_binary_nil_l (φ : binary_predicate Σ) w :\n    app₂ φ [] w = true.\n  Proof. destruct φ; naive_solver. Qed.\n\n  Lemma apply_binary_nil_r (φ : binary_predicate Σ) w :\n    app₂ φ w [] = true.\n  Proof. destruct φ; naive_solver. Qed.\n\n  Lemma Φ_reach_empty_sat k X w :\n    length w = k →\n    Φ_reach_empty X k (encode X w).\n  Proof.\n    intros <- B.\n    have Heq : ε_can_reach_from (encode X w) B ↔ check_reachable_from G (X, w) (B, []).\n    { rewrite check_reachable_from_spec reachable_from_spec //. }\n    rewrite Heq /=.\n    setoid_rewrite reachable_from_spec.\n    repeat apply ZifyClasses.or_morph.\n    - rewrite length_zero_iff_nil. naive_solver.\n    - setoid_rewrite apply_unary_nil. naive_solver.\n    - setoid_rewrite apply_binary_nil_l. split.\n      + intros [A [B' [φ [w' [? [Hr [? ?]]]]]]].\n        exists A, B', φ. split; first done.\n        destruct w' as [|t w']; [by left | right].\n        have Hsub : sublist (t :: w') w by eapply reachable_sublist; eauto.\n        apply sublist_slice in Hsub as [a [? Hw]].\n        exists a, (length (t :: w')).\n        rewrite -Hw. repeat split => //. rewrite cons_length; lia.\n      + intros [A [B' [φ [? [Hr|Hr]]]]].\n        * destruct Hr as [? ?].\n          exists A, B', φ, [].\n          repeat split => //.\n        * destruct Hr as [x [δ [? [? [? ?]]]]].\n          exists A, B', φ, (slice w x δ).\n          repeat split => //.\n    - setoid_rewrite apply_binary_nil_r.\n      setoid_rewrite app_nil_r. split.\n      + intros [A [B' [φ [w' [? [Hr [? ?]]]]]]].\n        exists A, B', φ. split; first done.\n        destruct w' as [|t w']; [by left | right].\n        have Hsub : sublist (t :: w') w by eapply reachable_sublist; eauto.\n        apply sublist_slice in Hsub as [a [? Hw]].\n        exists a, (length (t :: w')).\n        rewrite -Hw. repeat split => //. rewrite cons_length; lia.\n      + intros [A [B' [φ [? [Hr|Hr]]]]].\n        * destruct Hr as [? ?].\n          exists A, B', φ, [].\n          repeat split => //.\n        * destruct Hr as [x [δ [? [? [? ?]]]]].\n          exists A, B', φ, (slice w x δ).\n          repeat split => //.\n  Qed.\n\n  Lemma Φ_reach_sat k X w :\n    well_formed w →\n    length w = k →\n    Φ_reach X k (encode X w).\n  Proof.\n    intros ? <-. split; by [apply Φ_reach_nonempty_sat | apply Φ_reach_empty_sat].\n  Qed.\n\n  Lemma Φ_reach_nonempty_spec k S m :\n    Φ_well_formed k m →\n    Φ_derive k m →\n    Φ_reach_nonempty S k m →\n    ∀ B x δ, 0 < δ → x + δ ≤ k →\n      can_reach_from m B x δ → (* only this direction is needed *)\n      reachable G (S, decode m k) (B, slice (decode m k) x δ).\n  Proof.\n    intros ? HΦ' HΦ B x δ ? ? ?. rewrite -reachable_from_spec.\n    (* induction on range length *)\n    generalize dependent B.\n    generalize dependent x.\n    induction δ as [δ IHδ] using (induction_ltof1 _ (λ δ, k - δ)) => x Hk B.\n    unfold ltof in IHδ.\n    (* induction on nonterminal *)\n    have Hwf : wf (succ G) by apply acyclic_succ_wf.\n    induction B as [B IHB] using (well_founded_induction Hwf).\n    rewrite HΦ //.\n    setoid_rewrite Φ_app₁_spec. setoid_rewrite Φ_app₂_spec.\n    intros [Hr|[Hr|[Hr|Hr]]].\n    - destruct Hr as [-> [-> ->]].\n      rewrite slice_full ?decode_length //.\n      constructor.\n    - destruct Hr as [A [φ [? [? ?]]]].\n      eapply reachable_from_unary; eauto.\n      apply IHB => //. eapply succ_unary; eauto.\n    - destruct Hr as [A [B' [φ [δ' [? [? [? [? ?]]]]]]]].\n      case_bool_decide; subst.\n      * eapply reachable_from_left; eauto.\n        rewrite app_nil_r. apply IHB.\n        { eapply succ_left; eauto. }\n        have -> : δ = δ + 0 by lia. done.\n      * eapply reachable_from_left; eauto.\n        rewrite slice_app_1. apply IHδ => //; lia.\n        { eapply Φ_derive_spec; eauto; lia. }\n    - destruct Hr as [A [B' [φ [δ' [? [? [Hr [? ?]]]]]]]].\n      case_bool_decide; subst; eapply reachable_from_right; eauto.\n      * rewrite Nat.sub_0_r Nat.add_0_l in Hr. rewrite app_nil_l.\n        apply IHB => //. eapply succ_right; eauto.\n      * rewrite slice_app_2 //. apply IHδ => //; lia.\n      * eapply Φ_derive_spec; eauto; lia.\n  Qed.\n\n  Lemma Φ_reach_empty_spec S k m :\n    Φ_well_formed k m →\n    Φ_derive k m →\n    Φ_reach_nonempty S k m →\n    Φ_reach_empty S k m →\n    ∀ B,\n      ε_can_reach_from m B → (* only this direction is needed *)\n      reachable G (S, decode m k) (B, []).\n  Proof.\n    intros ? ? ? HΦ B. rewrite -reachable_from_spec.\n    (* induction on nonterminal *)\n    have Hwf : wf (succ G) by apply acyclic_succ_wf.\n    induction B as [B IHB] using (well_founded_induction Hwf).\n    rewrite HΦ //. intros [Hr|[Hr|[Hr|Hr]]].\n      + destruct Hr as [<- ->]. constructor.\n      + destruct Hr as [A [φ [Hp ?]]].\n        eapply reachable_from_unary; [apply Hp | | apply apply_unary_nil].\n        apply IHB => //. eapply succ_unary; eauto.\n      + destruct Hr as [A [B' [φ [Hp [Hr|Hr]]]]].\n        * destruct Hr as [? ?].\n          eapply reachable_from_left; [apply Hp | | eauto | apply apply_binary_nil_l].\n          rewrite app_nil_l. apply IHB => //. eapply succ_left; eauto.\n        * destruct Hr as [x [δ [? [? [Hr Hd]]]]].\n          eapply Φ_derive_spec in Hd; eauto.\n          eapply reachable_from_left; [apply Hp | | eauto | apply apply_binary_nil_l].\n          rewrite app_nil_l. apply reachable_from_spec, Φ_reach_nonempty_spec; eauto.\n      + destruct Hr as [A [B' [φ [Hp [Hr|Hr]]]]].\n        * destruct Hr as [? ?].\n          eapply reachable_from_right; [apply Hp | | eauto | apply apply_binary_nil_r].\n          rewrite app_nil_r. apply IHB => //. eapply succ_right; eauto.\n        * destruct Hr as [x [δ [? [? [Hr Hd]]]]].\n          eapply Φ_derive_spec in Hd; eauto.\n          eapply reachable_from_right; [apply Hp | | eauto | apply apply_binary_nil_r].\n          rewrite app_nil_r. apply reachable_from_spec, Φ_reach_nonempty_spec; eauto.\n  Qed.\n\n  (* encoding derivations using different productions *)\n\n  Inductive using_clause : Type :=\n  | using_ε : using_clause\n  | using_atom : Σ → using_clause\n  | using_unary : N → unary_predicate Σ → using_clause\n  | using_binary : N → N → binary_predicate Σ → nat (* length of first part *) → using_clause\n  .\n\n  Definition usable_clauses A δ : list using_clause :=\n    clauses G A ≫= (λ α, match α with\n    | ε => [using_ε]\n    | atom a => [using_atom a]\n    | unary B φ => [using_unary B φ]\n    | binary Bl Br φ => (λ δ', using_binary Bl Br φ δ') <$> (index_range δ ++ [δ])\n    end).\n\n  Lemma elem_of_usable_clauses ψ A δ :\n    ψ ∈ usable_clauses A δ ↔ match ψ with\n    | using_ε => A ↦ ε ∈ G\n    | using_atom a => A ↦ atom a ∈ G\n    | using_unary B φ => A ↦ unary B φ ∈ G\n    | using_binary Bl Br φ δ' => A ↦ binary Bl Br φ ∈ G ∧ δ' ≤ δ\n    end.\n  Proof.\n    rewrite /usable_clauses elem_of_list_bind. split.\n    - (* -> *)\n      intros [α [Hin ?]]. repeat case_match => //.\n      all: repeat match goal with\n      | [H : _ ∈ [_] |- _ ] => apply elem_of_list_singleton in H; invert H\n      | [H : _ ∈ _ <$> _ |- _ ] => apply elem_of_list_fmap in H as [x [H Hx]]; invert H\n      end => //.\n      split => //. apply elem_of_app in Hx as [|Hx].\n      * suff : x < δ by lia. by apply index_range_elem_of.\n      * suff : x = δ by lia. by apply elem_of_list_singleton in Hx.\n    - (* <- *)\n      destruct ψ as [| a | B φ | Bl Br φ δ'] => Hp.\n      * exists ε. split => //. by apply elem_of_list_singleton.\n      * exists (atom a). split => //. by apply elem_of_list_singleton.\n      * exists (unary B φ). split => //. by apply elem_of_list_singleton.\n      * exists (binary Bl Br φ). destruct Hp as [? Hδ']. split => //. apply elem_of_list_fmap.\n        exists δ'. split => //. apply Nat.le_lteq in Hδ' as [?|?]; apply elem_of_app; by\n          [left; apply index_range_elem_of | right; apply elem_of_list_singleton].\n  Qed.\n  \n  Definition Φ_using_derive ψ x δ : formula :=\n    match ψ with\n    | using_ε => λ k m, δ = 0\n    | using_atom a => λ k m, δ = 1 ∧ term m x = a\n    | using_unary B φ => λ k m,\n      if bool_decide (δ = 0) then G ⊨ B => []\n      else Φ_app₁ φ x δ k m ∧ can_derive m B x δ\n    | using_binary Bl Br φ δ' => λ k m,\n      (if bool_decide (δ' = 0) then G ⊨ Bl => [] else can_derive m Bl x δ') ∧\n      (if bool_decide (δ - δ' = 0) then G ⊨ Br => [] else can_derive m Br (x + δ') (δ - δ')) ∧\n      Φ_app₂ φ x δ' (x + δ') (δ - δ') k m\n    end.\n\n  Lemma Φ_using_derive_witness k m x δ A ψ :\n    Φ_well_formed k m →\n    Φ_derive k m →\n    x + δ ≤ k →\n    ψ ∈ usable_clauses A δ →\n    Φ_using_derive ψ x δ k m ↔ match ψ with\n    | using_ε => δ = 0 ∧ ε_tree A ▷ A ={G}=> slice (decode m k) x δ\n    | using_atom a => δ = 1 ∧ a = term m x ∧ let p := (line m x, col m x) in\n      (token_tree A (a @ p)) ▷ A ={G}=> slice (decode m k) x δ\n    | using_unary B _ => ∃ t, root t = B ∧ (unary_tree A t) ▷ A ={G}=> slice (decode m k) x δ\n    | using_binary Bl Br _ δ' => ∃ t1 t2, root t1 = Bl ∧ root t2 = Br ∧\n      word t1 = slice (decode m k) x δ' ∧ (binary_tree A t1 t2) ▷ A ={G}=> slice (decode m k) x δ\n    end.\n  Proof.\n    intros ? ? ? Hψ. destruct ψ as [| a | B φ | Bl Br φ δ'] => /=.\n    all: apply elem_of_usable_clauses in Hψ.\n    - split; last naive_solver.\n      intros ->. split; first done. by apply witness_ε.\n    - split; last naive_solver.\n      intros [-> Hx]. split; first done.\n      erewrite slice_singleton; last by rewrite decode_lookup; [lia|eauto].\n      rewrite Hx. split; first done. by apply witness_atom.\n    - unfold derive. case_bool_decide.\n      + subst. rewrite slice_nil. split.\n        * intros [t [? [? ?]]]. subst. exists t.\n          rewrite witness_unary; eauto. repeat split => //. apply apply_unary_nil.\n        * intros [t [? Ht]]. subst. eapply witness_unary in Ht; eauto. naive_solver.\n      + rewrite Φ_app₁_spec.\n        rewrite Φ_derive_spec; eauto; [|lia]. unfold derive.\n        split.\n        * intros [? [t [? [? ?]]]]. subst. exists t.\n          rewrite witness_unary; eauto. repeat split => //.\n        * intros [t [? Ht]]. subst. eapply witness_unary in Ht; eauto. naive_solver.\n    - destruct Hψ as [Hψ ?]. unfold derive. rewrite Φ_app₂_spec. repeat case_bool_decide.\n      Ltac finish := split;\n        [ intros [[t1 [? [Hw1 ?]]] [[t2 [? [? ?]]] ?]]; subst; exists t1, t2;\n          rewrite -{2}Hw1 witness_binary ?Hw1; eauto; repeat split => //\n        | intros [t1 [t2 [? [? [Hw1 Ht]]]]]; subst;\n          rewrite -{1}Hw1 in Ht; eapply witness_binary in Ht; eauto; rewrite Hw1 in Ht; naive_solver \n        ].\n      + have -> : δ = 0 by lia.\n        have -> : slice (decode m k) x 0 = [] ++ [] by rewrite slice_nil.\n        have -> : δ' = 0 by lia. rewrite slice_nil.\n        finish.\n      + have -> : slice (decode m k) x δ = [] ++ slice (decode m k) x δ by rewrite app_nil_l.\n        subst. rewrite Nat.add_0_r Nat.sub_0_r slice_nil.\n        rewrite Φ_derive_spec; eauto; [|lia]. unfold derive.\n        finish.\n      + have -> : slice (decode m k) x δ = slice (decode m k) x δ ++ [] by rewrite app_nil_r.\n        have -> : δ' = δ by lia. rewrite Nat.sub_diag slice_nil.\n        rewrite Φ_derive_spec; eauto; [|lia]. unfold derive.\n        finish.\n      + have -> : slice (decode m k) x δ = slice (decode m k) x δ' ++ slice (decode m k) (x + δ') (δ - δ')\n          by rewrite -slice_split.\n        rewrite !Φ_derive_spec; eauto; [|lia..]. unfold derive.\n        finish.\n  Qed.\n\n  Definition Φ_multi_usable (A : N) (x δ : nat) : formula := λ k m,\n    ∃ ψ1, ψ1 ∈ usable_clauses A δ ∧\n      ∃ ψ2, ψ2 ∈ usable_clauses A δ ∧\n        ψ1 ≠ ψ2 ∧ Φ_using_derive ψ1 x δ k m ∧ Φ_using_derive ψ2 x δ k m.\n\n  Lemma app_length_le_l {A} (l1 l2 l : list A) :\n    l1 ++ l2 = l →\n    length l1 ≤ length l.\n  Proof.\n    intros Hl. apply (f_equal length) in Hl. rewrite app_length in Hl. lia.\n  Qed.\n\n  Local Lemma wrap_with_id (P : Prop) :\n    P ↔ id P.\n  Proof. done. Qed.\n\n  Local Ltac wrap H := apply ->wrap_with_id in H.\n\n  Local Ltac congruence_by H :=\n    match goal with\n    | H1 : ?x = ?z1, H2 : ?y = ?z2, H : ?x = ?y |- _ =>\n      rewrite H1 in H; rewrite H2 in H\n    end.\n\n  Lemma Φ_multi_usable_spec k m x δ A :\n    Φ_well_formed k m →\n    Φ_derive k m →\n    x + δ ≤ k →\n    Φ_multi_usable A x δ k m ↔ ∃ t1, t1 ▷ A ={G}=> slice (decode m k) x δ ∧\n      ∃ t2, t2 ▷ A ={G}=> slice (decode m k) x δ ∧ ¬ similar t1 t2.\n  Proof.\n    intros ? ?. split.\n    - (* -> *)\n      intros [ψ1 [Hψ1 [ψ2 [Hψ2 [Hne [HΦ1 HΦ2]]]]]].\n      eapply Φ_using_derive_witness in HΦ1; eauto.\n      eapply Φ_using_derive_witness in HΦ2; eauto.\n      repeat case_match.\n      all: apply elem_of_usable_clauses in Hψ1, Hψ2.\n      all: repeat match goal with\n      | [ H : _ ∧ _ |- _ ] => destruct H as [H ?]\n      | [ H : ∃ _, _ |- _ ] => destruct H as [? H]\n      end.\n      all: simpl in *; try congruence.\n      all: repeat match goal with\n      | [ H : ?t ▷ ?A ={?G}=> ?w |- ∃ t, t ▷ ?A ={?G}=> ?w ∧ _ ] =>\n        exists t; split; [by apply H|]; clear H\n      end => //=.\n      * intros Heq. subst. rewrite Heq in Hψ2.\n        eapply unary_clause_predicate_unique in Hψ1; [|exact Hψ2].\n        subst. congruence.\n      * intros [Heq1 [Heq2 Heqw]]. subst. rewrite Heq1 Heq2 in Hψ2.\n        eapply binary_clause_predicate_unique in Hψ1; [|exact Hψ2].\n        subst. congruence_by Heqw.\n        apply slice_eq_inv in Heqw. 2-3: rewrite decode_length; lia.\n        congruence.\n    - (* <- *)\n      intros [t1 [[? [? Ht1]] [t2 [[? [? Ht2]] ?]]]].\n      destruct t1 as [?|??|??|? t11 t12]; destruct t2 as [?|??|??|? t21 t22].\n      all: simpl in *; try done; try congruence.\n      all: invert Ht1.\n      all: invert Ht2.\n      all: unfold Φ_multi_usable.\n      all: repeat match goal with\n      | [ H : ?A ↦ ε ∈ _ |- ∃ ψ, ψ ∈ usable_clauses ?A ?δ ∧ _ ] =>\n        assert (using_ε ∈ usable_clauses A δ) by (by apply elem_of_usable_clauses);\n        eexists; split; [eauto|]; wrap H\n      | [ H : ?A ↦ atom ?a ∈ _ |- ∃ ψ, ψ ∈ usable_clauses ?A ?δ ∧ _ ] =>\n        assert (using_atom a ∈ usable_clauses A δ) by (by apply elem_of_usable_clauses);\n        eexists; split; [eauto|]; wrap H\n      | [ H : ?A ↦ unary ?B ?φ ∈ _ |- ∃ ψ, ψ ∈ usable_clauses ?A ?δ ∧ _ ] =>\n        assert (using_unary B φ ∈ usable_clauses A δ) by (by apply elem_of_usable_clauses);\n        eexists; split; [eauto|]; wrap H\n      | [ H : ?A ↦ binary (root ?t1) (root ?t2) ?φ ∈ _ |- ∃ ψ, ψ ∈ usable_clauses ?A ?δ ∧ _ ] =>\n        assert (using_binary (root t1) (root t2) φ (length (word t1)) ∈ usable_clauses A δ) by\n          (apply elem_of_usable_clauses; split; [done \n            | erewrite <-slice_length; [ eapply app_length_le_l; eauto | by rewrite decode_length ]\n          ]);\n        eexists; split; [eauto|]; wrap H\n      end.\n      all: split; first try congruence.\n      12: {\n        intros Heq. invert Heq.\n        have Hw : word t11 ++ word t12 = word t21 ++ word t22 by congruence.\n        apply app_inj_1 in Hw => //. naive_solver.\n      }\n      all: try (split; eapply Φ_using_derive_witness; simpl; eauto).\n      all: repeat match goal with\n      | [ |- _ ▷ _ ={ _ }=> _ ] =>\n        repeat split; simpl; try done; try congruence; econstructor; eauto\n      | [ H : [] = slice (decode _ _) _ ?δ |- ?δ = 0 ∧ _ ] =>\n        rewrite -H; symmetry in H; apply slice_nil_iff in H; [|by rewrite decode_length]; split; first done\n      | [ H : [_] = slice (decode _ _) _ ?δ |- ?δ = 1 ∧ _ = term _ _ ∧ _ ] =>\n        rewrite -H; symmetry in H; apply slice_singleton_iff in H; [|by rewrite decode_length];\n        let H' := fresh in destruct H as [-> H']; rewrite decode_lookup in H'; [lia|];\n        invert H'; do 2 (split; first done)\n      | [ |- ∃ t, root t = root ?t' ∧ _ ] =>\n        exists t'; split; first done\n      | [ |- ∃ t1 t2, root t1 = root ?t1' ∧ root t2 = root ?t2' ∧ _ ] =>\n        exists t1', t2'; do 2 (split; first done)\n      | [ |- word ?t = slice (decode _ _) _ _ ∧ _ ] =>\n        split; first by (eapply slice_app_inv_NoDup; eauto; rewrite decode_length; lia)\n      end.\n  Qed.\n\n  (* Main theorems *)\n\n  Definition Φ_amb A : formula := λ k m,\n    Φ_well_formed k m ∧ Φ_derive k m ∧ Φ_reach A k m ∧ ∃ H,\n     (ε_can_reach_from m H ∧ Φ_multi_usable H 0 0 k m) ∨\n     (∃ x δ, 0 < δ ∧ x + δ ≤ k ∧ can_reach_from m H x δ ∧ Φ_multi_usable H x δ k m).\n\n  Theorem Φ_amb_sound A k m :\n    Φ_amb A k m → derive_amb G A (decode m k).\n  Proof.\n    intros [? [? [[? ?] [X HX]]]].\n    apply derive_amb_iff_local_amb => //.\n    destruct HX as [[? Hm]|[x [δ [? [? [? Hm]]]]]].\n    - exists X, []; split; first by apply Φ_reach_empty_spec.\n      eapply Φ_multi_usable_spec in Hm; eauto; last lia.\n      simpl in Hm. naive_solver.\n    - exists X, (slice (decode m k) x δ); split; first by apply Φ_reach_nonempty_spec.\n      eapply Φ_multi_usable_spec in Hm; eauto. naive_solver.\n  Qed.\n\n  Theorem Φ_amb_complete X k w :\n    well_formed w → length w = k → derive_amb G X w → ∃ m, Φ_amb X k m.\n  Proof.\n    intros ? <- Hamb.\n    apply derive_amb_iff_local_amb in Hamb; eauto.\n    destruct Hamb as [C [h [Hr [t1 [t2 [Ht1 [Ht2 Hne]]]]]]].\n    exists (encode X w).\n    have ? : Φ_well_formed (length w) (encode X w) by apply Φ_well_formed_sat.\n    have ? : Φ_derive (length w) (encode X w) by apply Φ_derive_sat.\n    have ? : Φ_reach X (length w) (encode X w) by apply Φ_reach_sat.\n    do 3 (split; first done). exists C.\n    destruct h as [|tk h].\n    - left. split; first done.\n      eapply Φ_multi_usable_spec; eauto; lia.\n    - right.\n      have Hsub : sublist (tk :: h) w by eapply reachable_sublist; eauto.\n      apply sublist_slice in Hsub as [x [? Hh]].\n      exists x, (length (tk :: h)).\n      simpl can_reach_from. rewrite -Hh. repeat split => //.\n      { rewrite cons_length; lia. }\n      eapply Φ_multi_usable_spec; eauto.\n      rewrite decode_encode -Hh; eauto.\n  Qed.\n\nEnd encoding.", "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/encoding.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.28341133937478813}}
{"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 Language.\nFrom PromisingLib Require Import Loc.\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 Pred.\nRequire Import Trace.\n\nRequire Import MemoryMerge.\nRequire Import PromiseConsistent.\nRequire Import PFConsistent.\nRequire Import ReorderCancel.\nRequire Import MemoryProps.\nRequire Import OrderedTimes.\n\nRequire Import Mapping.\nRequire Import CapFlex.\nRequire Import GoodFuture.\nRequire Import Cover.\nRequire Import PFConsistentStrong.\n\nSet Implicit Arguments.\n\nFixpoint times_join (ts: list Time.t): Time.t :=\n  match ts with\n  | [] => Time.bot\n  | thd::ttl => Time.join thd (times_join ttl)\n  end.\n\nLemma times_join_max ts t (IN: List.In t ts):\n  Time.le t (times_join ts).\nProof.\n  revert t IN. induction ts; ss.\n  i. des; subst.\n  - eapply Time.join_l.\n  - eapply IHts in IN. etransitivity; eauto. eapply Time.join_r.\nQed.\n\nVariant sim_event: ThreadEvent.t -> ThreadEvent.t -> Prop :=\n| sim_event_promise\n    loc from to msg kind\n  :\n    sim_event\n      (ThreadEvent.promise loc from to msg kind)\n      (ThreadEvent.promise loc from to msg kind)\n| sim_event_read\n    loc to val released released' ordr\n    (RELEASEDLE: View.opt_le released released')\n  :\n    sim_event\n      (ThreadEvent.read loc to val released ordr)\n      (ThreadEvent.read loc to val released' ordr)\n| sim_event_write\n    loc from to val released released' ordw\n    (RELEASEDLE: View.opt_le released released')\n  :\n    sim_event\n      (ThreadEvent.write loc from to val released ordw)\n      (ThreadEvent.write loc from to val released' ordw)\n| sim_event_update\n    loc from to valr valw releasedr releasedr'\n    releasedw releasedw' ordr ordw\n    (RELEASEDRLE: View.opt_le releasedr releasedr')\n    (RELEASEDWLE: View.opt_le releasedw releasedw')\n  :\n    sim_event\n      (ThreadEvent.update loc from to valr valw releasedr releasedw ordr ordw)\n      (ThreadEvent.update loc from to valr valw releasedr' releasedw' ordr ordw)\n| sim_event_fence\n    or ow\n  :\n    sim_event\n      (ThreadEvent.fence or ow)\n      (ThreadEvent.fence or ow)\n| sim_event_syscall\n    e\n  :\n    sim_event\n      (ThreadEvent.syscall e)\n      (ThreadEvent.syscall e)\n| sim_event_silent\n  :\n    sim_event\n      (ThreadEvent.silent)\n      (ThreadEvent.silent)\n| sim_event_failure\n  :\n    sim_event\n      (ThreadEvent.failure)\n      (ThreadEvent.failure)\n.\n\nLemma ident_map_sim_event (f: Loc.t -> Time.t -> Time.t -> Prop)\n      (IDENT: forall loc to fto (MAP: f loc to fto), to = fto)\n      e fe\n      (EVENT: tevent_map f e fe)\n  :\n    sim_event e fe.\nProof.\n  assert (MSG: forall msg fmsg, msg_map f msg fmsg -> msg = fmsg).\n  { i. inv H; auto. eapply opt_view_ident_map in MAP; auto.\n    subst. auto. }\n  inv EVENT.\n  - eapply IDENT in FROM. eapply IDENT in TO.\n    eapply MSG in MSG0. subst. inv KIND.\n    + econs; eauto.\n    + apply IDENT in TO. eapply MSG in MSG0. subst.\n      econs; eauto.\n    + eapply MSG in MSG0. subst.\n      econs; eauto.\n    + econs; eauto.\n  - eapply IDENT in TO.\n    eapply opt_view_ident_map in RELEASED; auto. subst. econs; eauto.\n  - eapply IDENT in FROM. eapply IDENT in TO.\n    eapply opt_view_ident_map in RELEASED; auto. subst. econs; eauto.\n  - eapply IDENT in FROM. eapply IDENT in TO.\n    eapply opt_view_ident_map in RELEASEDR; auto. eapply opt_view_ident_map in RELEASEDW; auto.\n    subst. econs; eauto.\n  - econs; eauto.\n  - econs; eauto.\n  - econs; eauto.\n  - econs; eauto.\nQed.\n\n\nLemma promise_monotonicity lang0 lang1 st0 st1 st2 lc0 lc1 lc2 sc0 sc2 mem0 mem2 loc to tr0\n      (CONSISTENT: Thread.consistent (@Thread.mk lang0 st0 lc0 sc0 mem0))\n      (LOCAL0: Local.wf lc0 mem0)\n      (LOCAL1: Local.wf lc1 mem0)\n      (DISJOINT: Local.disjoint lc0 lc1)\n      (SC: Memory.closed_timemap sc0 mem0)\n      (MEM: Memory.closed mem0)\n      (PROMISE: concrete_promised (Local.promises lc0) loc to)\n      (STEPS0: Trace.steps tr0 (@Thread.mk lang1 st1 lc1 sc0 mem0) (@Thread.mk _ st2 lc2 sc2 mem2))\n  :\n    (exists tr1 st0' lc0' sc0' mem0' we tr0' val lc2' sc2' mem2',\n        (<<STEPS1: Trace.steps tr1 (@Thread.mk _ st0 lc0 sc0 mem0) (@Thread.mk _ st0' lc0' sc0' mem0')>>) /\\\n        (<<CONSISTENT: Thread.consistent (@Thread.mk _ st0' lc0' sc0' mem0')>>) /\\\n        (<<FINAL: final_event_trace we tr1>>) /\\\n        (<<WRITE: relaxed_writing_event loc to val we>>) /\\\n        (<<STEPS0: Trace.steps tr0' (@Thread.mk lang1 st1 lc1 sc0' mem0') (@Thread.mk _ st2 lc2' sc2' mem2')>>) /\\\n        (<<TRACE: List.Forall2 (fun '(_, e0) '(_, e1) => sim_event e1 e0) tr0 tr0'>>)) \\/\n    (Thread.steps_failure (@Thread.mk _ st0 lc0 sc0 mem0)).\nProof.\n  inv PROMISE.\n  hexploit consistent_pf_consistent_super_strong; eauto; ss. i. des.\n  hexploit (memory_times_wf_exists mem0). i. des.\n  hexploit (@trace_times_list_exists tr0). i. des.\n  set (tm := fun loc => Time.incr (Time.join (times_join (times loc)) (Memory.max_ts loc mem0))).\n  set (f := (fun loc ts fts => ts = fts /\\ Time.lt ts (tm loc))).\n  assert (MAPLT: mapping_map_lt f).\n  { unfold f. ii. des; subst; auto. }\n  assert (IDENT: map_ident_in_memory f mem0).\n  { ii. split; auto. eapply TimeFacts.le_lt_lt; eauto.\n    eapply TimeFacts.le_lt_lt.\n    { eapply Time.join_r. }\n    { eapply Time.incr_spec. }\n  }\n  hexploit concrete_promise_max_timemap_exists.\n  { eapply MEM. } i. des.\n  eapply pf_consistent_super_strong_mon\n    with (certimes1 := certimes \\2/ times_mem \\2/ fun _ ts => exists n, incr_time_seq n = ts) in CONSISTENT0; eauto.\n  hexploit pf_consistent_super_strong_promises_list_exists; eauto.\n  { i. right. eauto. }\n  i. des. unfold pf_consistent_super_strong_promises_list in *. des. ss.\n  hexploit COMPLETE; eauto. i. eapply List.in_split in H. des. subst.\n  hexploit CONSISTENT1; eauto.\n  { refl. }\n  { ii. exploit MWF; eauto.  i. des. splits; eauto. }\n  i. clear CONSISTENT1. des.\n  - left. eapply max_good_future_map in GOOD; eauto; cycle 1.\n    { i. eapply TimeFacts.le_lt_lt.\n      - eapply Time.join_r.\n      - eapply Time.incr_spec. }\n    hexploit Trace.steps_future; eauto. i. des. ss.\n    hexploit Trace.steps_disjoint; eauto. i. des.\n    hexploit (@trace_steps_map f).\n    { unfold f. ii. des; subst; auto. }\n    { unfold f. ii. split; auto. eapply TimeFacts.le_lt_lt.\n      - eapply Time.bot_spec.\n      - eapply Time.incr_spec.\n    }\n    { unfold f. ii. des; subst; auto. }\n    { instantiate (1:=tr0). eapply wf_time_mapped_mappable.\n      { instantiate (1:=fun loc to => List.In to (times loc)).\n        - eapply List.Forall_impl; eauto. ss. }\n      { i. ss. exists to0. split; auto. eapply TimeFacts.le_lt_lt.\n        { eapply times_join_max; eauto. }\n        { eapply TimeFacts.le_lt_lt.\n          { eapply Time.join_l. }\n          { eapply Time.incr_spec. }\n        }\n      }\n    }\n    { eapply STEPS0. }\n    { ss. }\n    { ss. }\n    { ss. }\n    { eapply LOCAL1. }\n    { eapply WF. }\n    { eauto. }\n    { eauto. }\n    { eauto. }\n    { eauto. }\n    { eapply map_ident_in_memory_local; eauto. }\n    { eauto. }\n    { eapply mapping_map_lt_collapsable_unwritable; eauto. }\n    { eapply map_ident_in_memory_closed_timemap; eauto. }\n    { rewrite SC0. refl. }\n    i. des. destruct e1. ss. esplits; try eassumption.\n    { eapply pf_consistent_super_strong_consistent; eauto. }\n    eapply list_Forall2_impl; eauto. i. ss. des; auto.\n    { clear - EVENT. destruct a, b. ss. eapply ident_map_sim_event; eauto.\n      i. eapply MAP. }\n  - right. unfold Thread.steps_failure.\n    unguard. des. destruct e1. ss. esplits.\n    { eapply Trace.silent_steps_tau_steps; eauto.\n      eapply List.Forall_impl; eauto. i. ss. des; auto. }\n    { econs 2. 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/prop/Monotonicity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.283356670118408}}
{"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 A B C D M N Aprime Bprime Cprime Dprime Mprime Nprime H G : Universe, ((wd_ A B /\\ (wd_ B C /\\ (wd_ C D /\\ (wd_ A D /\\ (wd_ A C /\\ (wd_ B D /\\ (wd_ Aprime Bprime /\\ (wd_ Bprime Cprime /\\ (wd_ Cprime Dprime /\\ (wd_ Aprime Dprime /\\ (wd_ Aprime Cprime /\\ (wd_ Bprime Dprime /\\ (wd_ Nprime Aprime /\\ (wd_ Nprime Dprime /\\ (wd_ Mprime Bprime /\\ (wd_ Mprime Cprime /\\ (wd_ N A /\\ (wd_ N D /\\ (wd_ M B /\\ (wd_ M C /\\ (wd_ N H /\\ (wd_ H G /\\ (wd_ M N /\\ (wd_ N G /\\ (wd_ M G /\\ (wd_ M H /\\ (wd_ Mprime Nprime /\\ (wd_ N C /\\ (wd_ D G /\\ (wd_ A H /\\ (col_ A D H /\\ (col_ Nprime Aprime Dprime /\\ (col_ N A D /\\ (col_ Mprime Bprime Cprime /\\ (col_ M B C /\\ col_ N D H))))))))))))))))))))))))))))))))))) -> col_ H A N)).\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_0435.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.38121957328625583, "lm_q1q2_score": 0.28331018678622655}}
{"text": "(*******************************************************************************)\n(*  © Université de Lille, The Pip Development Team (2015-2021)                *)\n(*                                                                             *)\n(*  This software is a computer program whose purpose is to run a minimal,     *)\n(*  hypervisor relying on proven properties such as memory isolation.          *)\n(*                                                                             *)\n(*  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(*******************************************************************************)\nRequire Import Pip.Model.ADT.\nRequire Import List PeanoNat Lt Lia Coq.Logic.Classical_Prop Bool Coq.Program.Tactics.\nImport List.ListNotations.\n\n\n(** * Summary \n    This file contains required functions to manipulate an association list *) \nFixpoint eqList {A : Type} (l1 l2 : list A) (eq : A -> A -> bool) : bool := \n match l1, l2 with \n |nil,nil => true\n |a::l1' , b::l2' => if  eq a b then eqList l1' l2' eq else false\n |_ , _ => false\nend.\n\nDefinition beqPairs {A B: Type} (a : (A*B)) (b : (A*B)) (eqA : A -> A -> bool) (eqB : B -> B -> bool) :=\nif (eqA (fst a) (fst b)) && (eqB (snd a) (snd b))  then true else false.\n\nFixpoint lookup {A B C: Type} (k : A) (i : B)  (assoc : list ((A * B)*C))  (eqA : A -> A -> bool) (eqB : B -> B -> bool) :=\n  match assoc with\n    | nil => None  \n    | (a, b) :: assoc' => if beqPairs a (k,i) eqA eqB then Some b else lookup k i assoc' eqA eqB\n  end. \n \nFixpoint removeDup {A B C: Type} (k : A) (i : B) (assoc : list ((A * B)*C) )(eqA : A -> A -> bool) (eqB : B -> B -> bool)   :=\n  match assoc with\n    | nil => nil\n    | (a, b) :: assoc' => if beqPairs a (k,i) eqA eqB then removeDup k i assoc' eqA eqB else (a, b) :: (removeDup k i assoc' eqA eqB)\n  end.\n\nDefinition add {A B C: Type} (k : A) (i : B) (v : C) (assoc : list ((A * B)*C) ) (eqA : A -> A -> bool) (eqB : B -> B -> bool)  :=\n  (k,i,v) :: removeDup k i assoc eqA eqB.\n\nProgram Fixpoint getNextVaddrAux (indexList : list index) : bool * (list index) :=\nmatch indexList with\n| nil   =>  (true, nil)\n| h::t  =>  if (fst (getNextVaddrAux t)) then\n              if (Nat.eq_dec (h+1) tableSize) then\n                (true, (Build_index 0 _)::(snd (getNextVaddrAux t)))\n              else\n                (false, (Build_index (h+1) _::(snd (getNextVaddrAux t))))\n            else\n                (false, (Build_index h _::(snd (getNextVaddrAux t))))\nend.\n\nNext Obligation.\ndestruct tableSizeBigEnough.\nunfold tableSizeLowerBound.\napply neq_0_lt.\ntrivial.\nunfold tableSizeLowerBound in g.\napply Nat.lt_0_succ.\nQed.\n\nNext Obligation.\nassert(i h < tableSize) by (apply (ADT.Hi h)).\ndestruct h.\nsimpl in *.\nlia.\nQed.\n\nNext Obligation.\napply (ADT.Hi h).\nQed.\n\nDefinition getNextVaddr (va : vaddr) : vaddr :=\nCVaddr (snd (getNextVaddrAux va)).\n\nFixpoint getNthVAddrFromAux (start : vaddr) (range : nat) : vaddr :=\nmatch range with\n| 0   => start\n| S n => getNthVAddrFromAux (getNextVaddr start) n\nend.\n\n\nObligation Tactic := idtac.\n\nProgram Fixpoint firstVAddrGreaterThanSecondAux (firstIndexList secondIndexList : list index)\n(HlenVAddr   : length firstIndexList = length secondIndexList)\n: bool :=\nmatch (firstIndexList, secondIndexList) with\n| (nil, nil) => true\n| (hf::tf, hs::ts) => let hs_le_hf := Nat.leb hs hf in\n                      if (hs_le_hf) then\n                        true\n                      else\n                      let differentHeads := negb (Nat.eqb hf hs) in\n                      if (differentHeads) then\n                        false\n                      else\n                        firstVAddrGreaterThanSecondAux tf ts _\n| (_,_) => False_rect _ _\nend.\n\nNext Obligation.\ncbn.\nintros firstIndexList secondIndexList HlenVAddr hf tf hs ts [=Hfirst Hsecond].\nsubst.\ninjection HlenVAddr.\ntrivial.\nQed.\n\nNext Obligation.\ncbn.\nintros firstIndexList secondIndexList HlenVAddr someIndexList someIndexList2.\ncase_eq someIndexList.\n- case_eq someIndexList2.\n  * intros.\n    destruct H1.\n    contradict H2.\n    reflexivity.\n  * intros.\n    injection Heq_anonymous.\n    intros.\n    subst.\n    contradict HlenVAddr.\n    unfold length.\n    trivial.\n- case_eq someIndexList2.\n  * intros.\n    injection Heq_anonymous.\n    intros.\n    subst.\n    contradict HlenVAddr.\n    unfold length.\n    apply Nat.neq_succ_0.\n  * intros.\n    destruct H1.\n    apply (H1 i0 l0 i l).\n    trivial.\nQed.\n\nNext Obligation.\ncbn.\nintros.\nsplit; intros; unfold not; intro; inversion H1.\nQed.\n\nNext Obligation.\ncbn.\nintros.\nsplit; intros; unfold not; intro; inversion H1.\nQed.\n\nObligation Tactic := program_simpl.", "meta": {"author": "2xs", "repo": "pipcore", "sha": "436a5995dd0d60d8bd8866c1ed5cecabe031727f", "save_path": "github-repos/coq/2xs-pipcore", "path": "github-repos/coq/2xs-pipcore/pipcore-436a5995dd0d60d8bd8866c1ed5cecabe031727f/src/model/Lib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2832842077228007}}
{"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.\n\nFrom CertiGraph Require Import graph.graph_gen.\nFrom CertiGraph Require Import graph.graph_model.\n\nFrom CertiGC Require Import model.constants.\nFrom CertiGC Require Import model.heap.heap.\nFrom CertiGC Require Import model.heapgraph.generation.generation.\nFrom CertiGC Require Import model.heapgraph.graph.\nFrom CertiGC Require Import model.heapgraph.mark.\nFrom CertiGC Require Import model.heapgraph.roots.\nFrom CertiGC Require Import model.util.\nFrom CertiGC Require Import vst.cmodel.constants. (* uses WORD_SIZE *)\n\n\nRecord thread_info: Type := {\n    ti_heap_p: val;\n    ti_heap: Heap;\n    ti_args: list val;\n    arg_size: Zlength ti_args = MAX_ARGS;\n}.\n\nDefinition ti_add_new_space (ti: thread_info) (sp: Space) i\n           (Hs: 0 <= i < MAX_SPACES): thread_info :=\n  Build_thread_info (ti_heap_p ti) (add_new_space (ti_heap ti) sp i Hs)\n                    (ti_args ti) (arg_size ti).\n\n\nDefinition nth_space (t_info: thread_info) (n: nat): Space :=\n  nth n t_info.(ti_heap).(heap_spaces) null_space.\n\nLemma nth_space_Znth: forall t n,\n    nth_space t n = Znth (Z.of_nat n) (heap_spaces (ti_heap t)).\nProof.\n  intros. unfold nth_space, Znth. rewrite if_false. 2: lia.\n  rewrite Nat2Z.id. reflexivity.\nQed.\n\nLemma ans_nth_new: forall ti sp i (Hs: 0 <= i < MAX_SPACES),\n    nth_space (ti_add_new_space ti sp i Hs) (Z.to_nat i) = sp.\nProof.\n  intros. rewrite nth_space_Znth. simpl. rewrite Z2Nat.id by lia.\n  rewrite upd_Znth_same; [reflexivity | rewrite heap_spaces__size; assumption].\nQed.\n\nLemma ans_nth_old: forall ti sp i (Hs: 0 <= i < MAX_SPACES) gen,\n    gen <> Z.to_nat i -> nth_space (ti_add_new_space ti sp i Hs) gen =\n                         nth_space ti gen.\nProof.\n  intros. rewrite !nth_space_Znth. simpl. rewrite upd_Znth_diff_strong.\n  - reflexivity.\n  - rewrite heap_spaces__size. assumption.\n  - intro. apply H. subst. rewrite Nat2Z.id. reflexivity.\nQed.\n\n\nDefinition gen_size t_info n := space_capacity (nth_space t_info n).\n\nDefinition rest_gen_size (t_info: thread_info) (gen: nat): Z :=\n  space_capacity (nth_space t_info gen) - space_allocated (nth_space t_info gen) - space_remembered (nth_space t_info gen).\n\nDefinition enough_space_to_copy g t_info from to: Prop :=\n  (unmarked_gen_size g from <= rest_gen_size t_info to)%Z.\n\nLemma lgd_enough_space_to_copy: forall g e v' t_info gen sp,\n    enough_space_to_copy g t_info gen sp ->\n    enough_space_to_copy (labeledgraph_gen_dst g e v') t_info gen sp.\nProof.\n  intros. unfold enough_space_to_copy in *. intuition. Qed.\n\nDefinition space_address (t_info: thread_info) (gen: nat) :=\n  offset_val (SPACE_STRUCT_SIZE * Z.of_nat gen) (ti_heap_p t_info).\n\nDefinition enough_space_to_have_g g t_info from to: Prop :=\n  (heapgraph_generation_size g from <= rest_gen_size t_info to)%Z.\n\n\n\nRecord thread_info_relation t t' :=\n{\n  thread_info_relation__ti_heap: ti_heap_p t = ti_heap_p t';\n  thread_info_relation__gen_size (n: nat): gen_size t n = gen_size t' n;\n  thread_info_relation__space_base (n: nat): space_base (nth_space t n) = space_base (nth_space t' n);\n}.\n\nArguments thread_info_relation__ti_heap [_] [_].\nArguments thread_info_relation__gen_size [_] [_].\nArguments thread_info_relation__space_base [_] [_].\n\nDefinition thread_info__remembered_invariant t t' := forall (n: nat), space_remembered (nth_space t n) = space_remembered (nth_space t' n).\n\n\nLemma tir_id: forall t, thread_info_relation t t.\nProof.\n  dintuition idtac.\nQed.\n\nLemma tir_trans: forall t1 t2 t3,\n    thread_info_relation t1 t2 -> thread_info_relation t2 t3 ->\n    thread_info_relation t1 t3.\nProof.\n  dintuition congruence.\nQed.\n\n\nDefinition generation_size_spec (tinfo: thread_info) (n: nat): Prop :=\n  if Val.eq (nth_space tinfo n).(space_base) nullval\n  then True\n  else gen_size tinfo n = generation_size n.\n\nDefinition ti_size_spec (tinfo: thread_info): Prop :=\n  Forall (generation_size_spec tinfo) (nat_inc_list (Z.to_nat MAX_SPACES)).\n\nLemma ti_size_spec_add: forall ti sp i (Hs: 0 <= i < MAX_SPACES),\n    space_capacity sp = generation_size (Z.to_nat i) -> ti_size_spec ti ->\n    ti_size_spec (ti_add_new_space ti sp i Hs).\nProof.\n  intros. unfold ti_size_spec in *. rewrite Forall_forall in *. intros.\n  specialize (H0 _ H1). unfold generation_size_spec in *.\n  destruct (Nat.eq_dec x (Z.to_nat i)); unfold gen_size.\n  - subst x. rewrite !ans_nth_new. if_tac; auto.\n  - rewrite !ans_nth_old; assumption.\nQed.\n\nLemma ti_relation_size_spec: forall t_info1 t_info2 : thread_info,\n    thread_info_relation t_info1 t_info2 ->\n    ti_size_spec t_info1 -> ti_size_spec t_info2.\nProof.\n  intros.\n  unfold ti_size_spec in *.\n  rewrite Forall_forall in *.\n  intros.\n  specialize (H0 _ H1). unfold generation_size_spec in *.\n  pose proof (thread_info_relation__gen_size H) as H2.\n  pose proof (thread_info_relation__space_base H) as H3.\n  now rewrite <- H2, <- H3.\nQed.\n\n\nLemma ans_space_address: forall ti sp i (Hs: 0 <= i < MAX_SPACES) j,\n    space_address (ti_add_new_space ti sp i Hs) (Z.to_nat j) =\n    space_address ti (Z.to_nat j).\nProof. intros. unfold space_address. simpl. reflexivity. Qed.\n\n\n\nLemma ngs_range: forall i,\n    0 <= i < MAX_SPACES -> 0 <= generation_size (Z.to_nat i) < MAX_SPACE_SIZE.\nProof.\n  intros. unfold generation_size. rewrite MAX_SPACES_eq in H.\n  rewrite Z2Nat.id, NURSERY_SIZE_eq, Zbits.Zshiftl_mul_two_p,\n  Z.mul_1_l, <- two_p_is_exp by lia. split.\n  - cut (two_p (16 + i) > 0). 1: intros; lia. apply two_p_gt_ZERO. lia.\n  - try (assert (E: MAX_SPACE_SIZE = two_p 28) by easy ; rewrite E ; clear E ; apply two_p_monotone_strict ; lia) ;\n    try (transitivity (two_p 28) ; try easy ; apply two_p_monotone_strict ; lia).\nQed.\n\nLemma ngs_int_singed_range: forall i,\n    0 <= i < MAX_SPACES ->\n    (if Archi.ptr64 then Int64.min_signed else Int.min_signed) <=\n    generation_size (Z.to_nat i) <=\n    (if Archi.ptr64 then Int64.max_signed else Int.max_signed).\nProof.\n  intros. apply ngs_range in H. destruct H. split.\n  - transitivity 0. 2: assumption. vm_compute. intro HS; inversion HS.\n  - apply Z.lt_le_incl. transitivity MAX_SPACE_SIZE. 1: assumption.\n    unfold MAX_SPACE_SIZE. vm_compute. reflexivity.\nQed.\n\nLemma ngs_S: forall i,\n    0 <= i -> 2 * generation_size (Z.to_nat i) = generation_size (Z.to_nat (i + 1)).\nProof.\n  intros. unfold generation_size. rewrite !Z2Nat.id by lia.\n  rewrite Z.mul_comm, <- Z.mul_assoc, (Z.mul_comm (two_p i)), <- two_p_S by assumption.\n  reflexivity.\nQed.\n\n\nRecord fun_info : Type := {\n    fun_word_size: Z;\n    live_roots_indices: list Z;\n    fi_index_range: forall i, In i live_roots_indices -> (0 <= i < MAX_ARGS)%Z;\n    lri_range: (Zlength (live_roots_indices) <= MAX_UINT - 2)%Z;\n    word_size_range: (0 <= fun_word_size <= MAX_UINT)%Z;\n}.\n\nDefinition null_fun_info: fun_info.\nProof.\n  apply (Build_fun_info 0 nil).\n  - intros. inversion H.\n  - rewrite Zlength_nil.\n    unfold MAX_UINT. rep_lia.\n  - unfold MAX_UINT. rep_lia.\nQed.\n\nDefinition np_roots_rel from f_info (roots roots': roots_t) (l: list Z) : Prop :=\n  let lri := live_roots_indices f_info in\n  let maped_lri := (map ((fun x y => Znth y x) lri) l) in\n  forall v j, Znth j roots' = inr v ->\n              (In (Znth j lri) maped_lri -> addr_gen v <> from) /\\\n              (~ In (Znth j lri) maped_lri -> Znth j roots = inr v).\n\nLemma np_roots_rel_cons: forall roots1 roots2 roots3 from f_info i l,\n    np_roots_rel from f_info roots1 roots2 [i] ->\n    np_roots_rel from f_info roots2 roots3 l ->\n    np_roots_rel from f_info roots1 roots3 (i :: l).\nProof.\n  intros. unfold np_roots_rel in *. intros. simpl. specialize (H0 _ _ H1).\n  destruct H0. split; intros.\n  - destruct (in_dec Z.eq_dec (Znth j (live_roots_indices f_info))\n                     (map ((fun x y => Znth y x) (live_roots_indices f_info)) l)).\n    1: apply H0; assumption. destruct H3. 2: contradiction.\n    specialize (H2 n). specialize (H _ _ H2). destruct H. apply H. simpl.\n    left; assumption.\n  - apply Decidable.not_or in H3. destruct H3.\n    specialize (H2 H4). specialize (H _ _ H2). destruct H. apply H5. simpl. tauto.\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/thread_info/thread_info.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.28319905993701217}}
{"text": "Require Import extraInv.\nRequire Import verif_cond_5.\nLocal Open Scope Z.\n\nTheorem extra5: (commonStartnewloop hands0 hands1 dryer0 dryer1 ctrlState0 ctrlState1 ctrlTimer0 ctrlTimer1 timer0 timer1) /\\ \n cond5 -> (extraInv hands1 dryer1 ctrlState2 ctrlTimer2 timer1).\n\nProof.\nintros.\ninversion_clear H.\ninversion_clear H1.\ninversion_clear H2.\ninversion_clear H3.\ninversion_clear H4.\ninversion_clear H5.\ninversion_clear H0.\ninversion_clear H7.\ninversion_clear H8.\ninversion_clear H9.\ninversion_clear H10.\n(*ctrlState0[i]=ctrlState2[i]*)\nassert (HctrlState0_ctrlState2_same : (forall i, (0<=i /\\ i<=timer0  -> ctrlState0.[of_Z i]=ctrlState2.[of_Z i]))).\nintros.\nreplace ctrlState2.[of_Z i] with ctrlState1.[of_Z i].\napply arr_same_before_upd  with ctrlState0.[of_Z (timer1-1)] timer1.\nsplit.\nauto with zarith.\nassumption.\napply arr_same_before_upd with ctrlDrying timer1.\nsplit.\nauto with zarith.\nassumption.\n(*split extraInv in the hypothesis*)\ninversion_clear H5.\ninversion_clear H12.\ninversion_clear H13.\ninversion_clear H14.\ninversion_clear H15.\ninversion_clear H16.\ninversion_clear H17.\ninversion_clear H18.\ninversion_clear H19.\nsplit.\nreflexivity.\nsplit.\nreflexivity.\nsplit.\nreflexivity.\nsplit.\nreflexivity.\nsplit.\nreflexivity.\nsplit.\nreflexivity.\nsplit.\nauto with zarith.\nsplit.\nauto with zarith.\nsplit.\n(*ctrlState[i]=ctrlWaiting \\/ ctrlState[i]=ctrlDrying*)\nintros.\nelim Zle_lt_or_eq with i timer1.\n(*case i<timer1*)\nintros.\nrewrite <- HctrlState0_ctrlState2_same.\napply H18.\nauto with zarith.\nauto with zarith.\n(*case i=timer1*)\nintros.\nrewrite H21.\nright.\nrewrite H4.\napply get_set_same.\nrewrite H8.\nrewrite length_set.\napply ctrlState_inf.\ninversion_clear H19.\nassumption.\n(*ctrlState[timer]=ctrlDrying -> ...*)\nintros.\nsplit.\nassumption. (*ctrlTimer<10*)\n(*hands [timer-ctrlTimer]=ON*)\nsplit.\nrewrite H3.\nrewrite Z.sub_0_r.\nassumption.\n(*dryer [timer-ctrlTimer]=ON*)\nsplit.\nrewrite H3.\nrewrite Z.sub_0_r.\nrewrite H9.\nrewrite get_set_same.\nrewrite H8 in H1.\nrewrite get_set_same in H1.\nassert (Htimer0_timer1_1: timer0=timer1-1).\napply Zeq_plus_swap.\nrewrite H0.\nreflexivity.\nrewrite <- Htimer0_timer1_1.\nrewrite <- Htimer0_timer1_1 in H1.\napply H20 in H1.\ninversion_clear H1.\ninversion_clear H22.\ninversion_clear H23.\napply Zcase_sign with ctrlTimer0.\nintros.\nrewrite H23 in H22.\nrewrite Z.sub_0_r in H22.\nassumption.\nintros.\napply H24.\nauto with zarith.\nintros.\nelimtype False.\nauto with zarith.\napply ctrlState_inf.\napply dryer_inf.\n(*hands[i]=OFF /\\ dryer[i]=ON*)\nintros.\nelimtype False.\nauto with zarith.\nQed.\n\n\n\n\n\n", "meta": {"author": "ivchernenko", "repo": "HandDryerController-proofs", "sha": "4c23c419584b9a9e148853a80a4b8af8df686c8c", "save_path": "github-repos/coq/ivchernenko-HandDryerController-proofs", "path": "github-repos/coq/ivchernenko-HandDryerController-proofs/HandDryerController-proofs-4c23c419584b9a9e148853a80a4b8af8df686c8c/extra5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2831990545788635}}
{"text": "From iris.base_logic Require Export invariants.\nFrom iris.algebra Require Import auth frac agree gmap.\nFrom iris.proofmode Require Import tactics.\nFrom iris_io Require Import lang rules list.\nFrom iris.program_logic Require Import weakestpre lifting.\n\nClass channelIG Σ := ChannelIG {\n   stream_inG :> inG Σ (prodR (fracR) (agreeR (leibnizC (Stream val))));\n   streams_inG :> inG Σ (prodR (fracR) (agreeR (leibnizC ((Stream val) → Prop))))\n}.\n\nDefinition channelΣ :=\n  #[GFunctor (prodR (fracR) (agreeR (leibnizC (Stream val))));\n      GFunctor (prodR (fracR) (agreeR (leibnizC ((Stream val) → Prop))))].\n\nGlobal Instance subG_channelΣ Σ : subG channelΣ Σ → channelIG Σ.\nProof. solve_inG. Qed.\n\nSection channels.\n\n  Context `{!channelIG Σ, !heapIG Σ}.\n\n  Definition own_stream γ q μ :=\n    own γ (q, to_agree μ : (agreeR (leibnizC (Stream val)))).\n\n  Definition own_streams γ q M :=\n    own γ (q, to_agree M : (agreeR (leibnizC ((Stream val) → Prop)))).\n\n  Definition channel_inv chan γs1 γs2 γR : iProp Σ :=\n        (∃ vs (μ1 μ2 : Stream val) M queue l,\n            ⌜chan = (PairV (PrV l) (LocV queue))⌝ ∗\n            queue ↦ (of_list vs) ∗\n            own_stream γs1 (1/2)%Qp μ1 ∗\n            own_stream γs2 (1/2)%Qp μ2 ∗\n            own_streams γR (1/2)%Qp M ∗\n            ⌜∀ μ', interleaving μ1 μ2 μ' → M (append_l_s vs μ')⌝\n        )%I.\n\n  Definition sender chan μ :=\n    (∃ γs γs1 γs2 γR,\n        inv (nroot .@ \"channel\") (channel_inv chan γs1 γs2 γR) ∗\n            own_stream γs (1/2)%Qp μ ∗ ⌜γs = γs1 ∨ γs = γs2⌝)%I.\n\n  Definition receiver chan μ :=\n    (∃ γs1 γs2 γR M queue l,\n        ⌜chan = (PairV (PrV l) (LocV queue))⌝ ∗\n        inv (nroot .@ \"channel\") (channel_inv chan γs1 γs2 γR)\n            ∗ own_streams γR (1/2)%Qp M ∗ cpvar l M μ)%I.\n\n  Definition new_channel :=\n    Lam (Pair Create_Pr (Alloc (InjL Plang.Unit))).\n\n  Lemma wp_new_channel μ1 μ2 :\n    {{{True}}}\n      App new_channel Plang.Unit\n    {{{w, RET w;\n       sender w μ1 ∗ sender w μ2 ∗\n              ∃ μ, ⌜interleaving μ1 μ2 μ⌝ ∗ receiver w μ\n    }}}.\n  Proof.\n    iIntros (Φ) \"_ HΦ\".\n    iApply wp_pure_step_later; auto.\n    iNext. asimpl.\n    iApply (wp_bind (fill [PairLCtx _])); simpl.\n    iApply (wp_create_pr _ (interleaving μ1 μ2)); eauto using interleaving_inh.\n    iNext.\n    iIntros (l); iDestruct 1 as (μ) \"Hμ\".\n    iApply (wp_bind (fill [PairRCtx _])); simpl.\n    iApply wp_alloc; auto.\n    iNext. iIntros (q) \"Hq\".\n    iApply wp_value_fupd.\n    iMod (own_alloc (1%Qp, to_agree μ1 : (agreeR (leibnizC (Stream val)))))\n      as (γs1) \"[Hμ11 Hμ12]\";\n      first done.\n    iMod (own_alloc (1%Qp, to_agree μ2 : (agreeR (leibnizC (Stream val)))))\n      as (γs2) \"[Hμ21 Hμ22]\";\n      first done.\n    iMod (own_alloc (1%Qp, to_agree (interleaving μ1 μ2)\n                     : (agreeR (leibnizC (Stream val → Prop)))))\n      as (γR) \"[HM1 HM2]\";\n      first done.\n    iMod (inv_alloc (nroot .@ \"channel\") _\n                    (channel_inv (PairV (PrV l) (LocV q)) γs1 γs2 γR)\n            with \"[Hμ11 Hμ21 HM1 Hq]\") as \"#Hinv\".\n    { iNext. unfold channel_inv.\n      iExists [], _, _, _, _, _; iFrame; eauto. }\n    iModIntro.\n    iApply \"HΦ\".\n    iSplitL \"Hμ12\"; first by iExists _, _, _, _; iFrame; iFrame \"#\"; eauto.\n    iSplitL \"Hμ22\"; first by iExists _, _, _, _; iFrame; iFrame \"#\"; eauto.\n    iExists μ; iSplit; first by iApply cpvar_contains.\n    iExists _, _, _, _, _, _; iFrame \"#\"; iFrame; eauto.\n  Qed.\n\n  Definition send :=\n    Lam\n      (Rec\n         (LetIn\n            (Snd (Var 2))\n            (LetIn\n               (Load (Var 0))\n               (If\n                  (CAS (Var 1) (Var 0)\n                       (App (App append.[ren (+5)]\n                                          (Var 0))\n                            (InjR (Pair (Var 3) (InjL Unit)))))\n                  Unit\n                  (App (Var 2) (Var 3))\n               )\n            )\n         )\n      ).\n\n  Lemma send_closed f : send.[f] = send.\n  Proof. by asimpl. Qed.\n\n  Hint Rewrite send_closed : autosubst.\n\n  Lemma wp_send chan v μ :\n    {{{sender chan {| Shead := v; Stail := μ|} }}}\n      App (App send (of_val chan)) (of_val v)\n      {{{RET UnitV;  sender chan μ }}}.\n  Proof.\n    iIntros (Φ) \"HP HΦ\".\n    iDestruct \"HP\" as (γs γs1 γs2 γR) \"(#chinv & Hγs & #Hγseq)\".\n    iApply fupd_wp.\n    iInv (nroot.@\"channel\") as \"Hinv\" \"Hcl\".\n    iDestruct \"Hinv\" as (ws μ1 μ2 M queue l) \"(>% & ? & ? & ? & ? & ?)\";\n      simplify_eq.\n    iMod (\"Hcl\" with \"[- Hγs HΦ]\") as \"_\";\n      first by iExists _, _, _, _, _, _; iNext; iFrame.\n    iModIntro.\n    clear ws μ1 μ2 M.\n    iApply (wp_bind (fill [AppLCtx _])).\n    iApply wp_pure_step_later; trivial.\n    iNext. asimpl.\n    iApply wp_value; simpl.\n    iLöb as \"IH\".\n    iApply wp_pure_step_later; trivial.\n    iNext. asimpl.\n    iApply (wp_bind (fill [LetInCtx _])).\n    iApply wp_pure_step_later; trivial.\n    iNext; iApply wp_value; simpl.\n    iApply wp_pure_step_later; trivial.\n    iNext; asimpl.\n    iApply (wp_bind (fill [LetInCtx _])).\n    iInv (nroot.@\"channel\") as \"Hinv\" \"Hcl\".\n    iDestruct \"Hinv\" as (ws μ1 μ2 M queue' l') \"(>% & Hq & ? & ? & ? & ?)\";\n      simplify_eq.\n    iApply (wp_load with \"Hq\"); first iFrame.\n    iNext. iIntros \"Hq\".\n    iMod (\"Hcl\" with \"[- Hγs HΦ]\") as \"_\";\n      first by iExists _, _, _, _, _, _; iNext; iFrame.\n    clear μ1 μ2 M.\n    iModIntro.\n    iApply wp_pure_step_later; trivial.\n    iNext. asimpl.\n    iApply (wp_bind (fill [IfCtx _ _])).\n    iApply (wp_bind (fill [CasRCtx (LocV _) _])); simpl.\n    iApply (wp_append _ [v]); trivial.\n    iNext; simpl.\n    iIntros (w ?); subst w.\n    iInv (nroot.@\"channel\") as \"Hinv\" \"Hcl\".\n    iDestruct \"Hinv\" as (ws' μ1 μ2 M queue l)\n                          \"(>% & Hq & Hγs1 & Hγs2 & HγR & >Hintr)\"; simplify_eq.\n    iDestruct \"Hintr\" as %Hintr.\n    destruct (decide (ws' = ws)) as [|Hneq]; first subst ws'.\n    - iApply (wp_cas_suc with \"Hq\").\n      iNext. iIntros \"Hq\".\n      iAssert (|={⊤ ∖ ↑nroot.@\"channel\",⊤}=>\n              own_stream γs (1 / 2)%Qp μ)%I with \"[-HΦ]\" as \"Hcl\".\n      { iDestruct \"Hγseq\" as %[]; subst γs.\n        - iDestruct (own_valid_2 with \"Hγs Hγs1\") as %[_ ?%agree_op_invL'];\n          simpl in *; simplify_eq.\n          iCombine \"Hγs\" \"Hγs1\" as \"Hγs\".\n          iMod (own_update _ _ ((1%Qp, to_agree μ : agreeR (leibnizC _)))\n                  with \"Hγs\") as \"[Hγs Hγys1]\".\n          { by apply cmra_update_exclusive. }\n          iMod (\"Hcl\" with \"[- Hγs]\") as \"_\"; last by iFrame.\n          { iExists _, _, _, _, _, _; iNext; iFrame.\n            iSplit; first by eauto.\n            iPureIntro. intros; rewrite append_l_s_app.\n            apply Hintr; by apply interR. }\n        - iDestruct (own_valid_2 with \"Hγs Hγs2\") as %[_ ?%agree_op_invL'];\n          simpl in *; simplify_eq.\n          iCombine \"Hγs\" \"Hγs2\" as \"Hγs\".\n          iMod (own_update _ _ ((1%Qp, to_agree μ : agreeR (leibnizC _)))\n                  with \"Hγs\") as \"[Hγs Hγs2]\".\n          { by apply cmra_update_exclusive. }\n          iMod (\"Hcl\" with \"[- Hγs]\") as \"_\"; last by iFrame.\n          { iExists _, _, _, _, _, _; iNext; iFrame.\n            iSplit; first by eauto.\n            iPureIntro. intros; rewrite append_l_s_app.\n            apply Hintr; by apply interL. }\n      }\n      iMod \"Hcl\" as \"Hγs\".\n      iModIntro.\n      iApply wp_pure_step_later; trivial.\n      iNext. asimpl.\n      iApply wp_value.\n      iApply \"HΦ\".\n      iExists _, _, _, _; iFrame \"#\"; iFrame.\n    - iApply (wp_cas_fail with \"Hq\").\n      { intros ?; apply Hneq; eapply (@inj _ _ eq eq of_list _); eauto. }\n      iNext. iIntros \"Hq\".\n      iMod (\"Hcl\" with \"[- Hγs HΦ]\") as \"_\";\n      first by iExists _, _, _, _, _, _; iNext; iFrame.\n      iModIntro.\n      iApply wp_pure_step_later; trivial.\n      iNext. by iApply (\"IH\" with \"Hγs\").\n  Qed.\n\n  Typeclasses Opaque send.\n  Global Opaque send.\n\n  Definition receive :=\n    Lam\n      (LetIn\n         (Fst (Var 0))\n         (LetIn\n            (Snd (Var 1))\n            (App\n               (Rec\n                  (LetIn\n                     (Load (Var 2))\n                     (Case\n                        (Var 0)\n                        (App (Var 2) Unit)\n                        (If\n                           (CAS (Var 4) (Var 1) (Snd (Var 0)))\n                           (LetIn\n                              (Fst (Var 0))\n                              (Seq\n                                 (Assign_Pr (Var 6) (Var 0))\n                                 (Var 0)\n                              )\n                           )\n                           (App (Var 2) Unit)\n                        )\n                     )\n                  )\n               )\n               Unit\n            )\n         )\n      ).\n\n  Lemma receive_closed f : receive.[f] = receive.\n  Proof. by asimpl. Qed.\n\n  Hint Rewrite receive_closed : autosubst.\n\n  Lemma wp_receive chan v μ :\n    {{{receiver chan {| Shead := v; Stail := μ|} }}}\n      App receive (of_val chan)\n      {{{RET v;  receiver chan μ }}}.\n  Proof.\n    iIntros (Φ) \"HP HΦ\".\n    iDestruct \"HP\" as (γs1 γs2 γR M q l Hcn) \"(#chinv & HR & Hpr)\"; subst.\n    iApply wp_pure_step_later; trivial.\n    iNext. asimpl.\n    iApply (wp_bind (fill [LetInCtx _])).\n    iApply wp_pure_step_later; trivial.\n    iNext; iApply wp_value; simpl.\n    iApply wp_pure_step_later; trivial.\n    iNext. asimpl.\n    iApply (wp_bind (fill [LetInCtx _])).\n    iApply wp_pure_step_later; trivial.\n    iNext; iApply wp_value; simpl.\n    iApply wp_pure_step_later; trivial.\n    iNext. asimpl.\n    iLöb as \"IH\".\n    iApply wp_pure_step_later; trivial.\n    iNext. asimpl.\n    iApply (wp_bind (fill [LetInCtx _])).\n    iInv (nroot.@\"channel\") as \"Hinv\" \"Hcl\".\n    iDestruct \"Hinv\" as (ws μ1 μ2 M' queue' l') \"(>% & Hq & ? & ? & ? & ?)\";\n      simplify_eq.\n    iApply (wp_load with \"Hq\"); first iFrame.\n    iNext. iIntros \"Hq\".\n    iMod (\"Hcl\" with \"[- HR Hpr HΦ]\") as \"_\";\n      first by iExists _, _, _, _, _, _; iNext; iFrame.\n    clear μ1 μ2 M'.\n    iModIntro.\n    iApply wp_pure_step_later; trivial.\n    iNext. asimpl.\n    destruct ws as [|w ws]; simpl.\n    { iApply wp_pure_step_later; trivial.\n      iNext. asimpl.\n      by iApply (\"IH\" with \"HR Hpr\"). }\n    iApply wp_pure_step_later; trivial.\n    iNext. asimpl.\n    iApply (wp_bind (fill [IfCtx _ _])).\n    iApply (wp_bind (fill [CasRCtx (LocV _) (InjRV (PairV _ _))])); simpl.\n    iApply wp_pure_step_later; trivial.\n    iNext; iApply wp_value; simpl.\n    iInv (nroot.@\"channel\") as \"Hinv\" \"Hcl\".\n    iDestruct \"Hinv\" as (ws' μ1 μ2 M' queue l)\n                          \"(>% & Hq & Hγs1 & Hγs2 & HγR & >Hintr)\"; simplify_eq.\n    iDestruct \"Hintr\" as %Hintr.\n    destruct (decide (ws' = w :: ws)) as [|Hneq]; first subst ws'.\n    - iApply (wp_cas_suc with \"Hq\").\n      iNext. iIntros \"Hq\".\n      iDestruct (own_valid_2 with \"HR HγR\") as %[_ ?%agree_op_invL'];\n        simpl in *; simplify_eq.\n      iCombine \"HR\" \"HγR\" as \"HR\".\n      iMod (own_update\n              _ _\n              ((1%Qp, to_agree (λ μ, M' {| Shead := w; Stail := μ |})\n                : agreeR (leibnizC _)))\n              with \"HR\") as \"[HR HγR]\".\n      { by apply cmra_update_exclusive. }\n      iMod (\"Hcl\" with \"[- HR Hpr HΦ]\") as \"_\".\n      { iExists _, _, _, _, _, _; iNext; iFrame; eauto. }\n      iModIntro.\n      iApply wp_pure_step_later; trivial.\n      iNext.\n      iApply (wp_bind (fill [LetInCtx _])).\n      iApply wp_pure_step_later; trivial.\n      iNext; iApply wp_value; simpl.\n      iApply wp_pure_step_later; trivial.\n      iNext. asimpl.\n      iApply (wp_bind (fill [SeqCtx _])).\n      iApply (wp_assign_pr with \"[$Hpr]\").\n      { iExists (append_l_s ws _); iPureIntro.\n        eapply Hintr, interleaving_inh. }\n      iNext. iIntros \"[% Hpr]\"; subst; simpl.\n      iApply wp_pure_step_later; trivial.\n      iNext; iApply wp_value.\n      iApply \"HΦ\".\n      iExists _, _, _, _, _, _; iFrame \"#\"; iFrame; eauto.\n    - iApply (wp_cas_fail with \"Hq\").\n      { intros ?; apply Hneq; eapply (@inj _ _ eq eq of_list _); eauto. }\n      iNext. iIntros \"Hq\".\n      iMod (\"Hcl\" with \"[- HR Hpr HΦ]\") as \"_\";\n      first by iExists _, _, _, _, _, _; iNext; iFrame.\n      iModIntro.\n      iApply wp_pure_step_later; trivial.\n      iNext. by iApply (\"IH\" with \"HR Hpr\").\n  Qed.\n\n  Typeclasses Opaque receive.\n  Global Opaque receive.\n\nEnd channels.\n\n\nHint Rewrite append_closed : autosubst.\nHint Rewrite send_closed : autosubst.\nHint Rewrite receive_closed : autosubst.\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/channel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2831175894556274}}
{"text": "Require Import Category.Lib.\nRequire Import Category.Theory.Category.\nRequire Import Category.Structure.Terminal.\nRequire Import Category.Construction.Opposite.\n\nGeneralizable All Variables.\n\n(* To be initial is just to be terminal in the opposite category; but to avoid\n   confusion, we'd like a set of notations specific to categories with initial\n   objects. *)\n\nNotation \"'Initial' C\" := (@Terminal (C^op))\n  (at level 9) : category_theory_scope.\nNotation \"@Initial C\" := (@Terminal (C^op))\n  (at level 9) : category_theory_scope.\n\nSection Initial_.\n\nContext `{I : @Initial C}.\n\nDefinition initial_obj : C := @terminal_obj _ I.\nDefinition zero {x} : initial_obj ~{C}~> x := @one _ I _.\n\nDefinition zero_unique {x} (f g : initial_obj ~{C}~> x) : f ≈ g :=\n  @one_unique _ I _ _ _.\n\nEnd Initial_.\n\nNotation \"0\" := initial_obj : object_scope.\n\nNotation \"zero[ C ]\" := (@zero _ _ C)\n  (at level 9, format \"zero[ C ]\") : morphism_scope.\n\nCorollary zero_comp `{T : @Initial C} {x y : C} {f : x ~> y} :\n  f ∘ zero ≈ zero.\nProof. apply (@one_comp _ T). Qed.\n", "meta": {"author": "jwiegley", "repo": "category-theory", "sha": "5376e32a4eeace4a84674820083bc2985a2a593f", "save_path": "github-repos/coq/jwiegley-category-theory", "path": "github-repos/coq/jwiegley-category-theory/category-theory-5376e32a4eeace4a84674820083bc2985a2a593f/Structure/Initial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.28311758277192844}}
{"text": "From Undecidability.TM Require Import TM ProgrammingTools.\nFrom Complexity.TM Require Import Code.Decode.\n\nFrom Complexity.TM Require Single.EncodeTapesInvariants .\nRequire Import FunInd Lia Ring Arith Program.Wf.\nImport EncodeTapes EncodeTapesInvariants.\nFrom Undecidability.Shared.Libs.PSL Require Import BaseLists.\n\nLemma tape_encode_injective sig (t t' : tape sig): encode_tape t = encode_tape t' -> t = t'.\nProof.\n  intros H. specialize (f_equal (fun l => hd_error (rev l)) H ) as Hlast. cbn in Hlast.\n  destruct t;destruct t';cbn in H,Hlast|-*;inv H;repeat (autorewrite with list in Hlast;cbn in Hlast);inv Hlast.\n  -easy. \n  -eapply app_inv_tail in H2. apply map_injective in H2. congruence. now intros ? ? [=]. \n  -apply (f_equal (@rev _)) in H1. autorewrite with list in H1. cbn in H1.\n   rewrite !map_rev,!rev_involutive in H1. inv H1. apply map_injective in H2. congruence. now intros ? ? [=]. \n  -rewrite <- (rev_involutive l), <- (rev_involutive l1);revert H1.\n   generalize (rev l1), (rev l);clear l l1;intros t t' Heq.\n   induction t in t',Heq|-*. all:destruct t';cbn in Heq;revert Heq. 2,3:now intros [=].\n   +intros [= -> Heq].\n    eapply app_inv_tail in Heq. apply map_injective in Heq. congruence. now intros ? ? [=].\n   +intros [= ->  Heq]. cbn. apply IHt in Heq as [= <- <- <-]. easy.\nQed.\n\nLemma tape_encode_prefixInjective sig: prefixInjective (Encode_tape sig).\nProof.\n  unfold encode;cbn.\n  enough (H:(forall x x' : tape sig,\n            | encode_tape x | <= | encode_tape x' | ->\n                                                   forall t t' : list (sigTape sig), encode_tape x ++ t = encode_tape x' ++ t' -> x = x')).\n  {intros x x'. decide (length (encode_tape x) <= length (encode_tape x')). now apply H.\n   intros. symmetry. eapply H. nia. now setoid_rewrite H0. } \n  intros x x' Hle t t' H.\n  specialize encode_tape_invariants with (t0:=x) as [-> | (b__L&b__R&t__x&Hx&Hsymb__x&Hmark__x&neq__x)]. now destruct x';inv H.\n  specialize encode_tape_invariants with (t0:=x') as [-> | (b__L'&b__R'&t__x'&Hx'&Hsymb__x'&Hmark__x'&neq__x')]. now destruct x;inv H.\n  assert (Hl_eq:| encode_tape x | = | encode_tape x' |).\n  { decide (| encode_tape x | < | encode_tape x' |) as [Hlt | Hlt]. 2:nia. exfalso.\n    rewrite Hx, Hx' in Hlt. cbn in Hlt. apply Nat.succ_lt_mono in Hlt. autorewrite with list in Hlt. apply Nat.add_lt_mono_r in Hlt.\n    assert (Hlast:nth_error (encode_tape x ++ t) (1 +  | t__x |) = Some (RightBlank b__R)).\n    { rewrite Hx. rewrite nth_error_app1. 2:now cbn;autorewrite with list;cbn;nia.\n      setoid_rewrite (nth_error_app2 (LeftBlank b__L :: t__x)). 2:cbn;nia.\n      replace ((1 + (| t__x |) - (| LeftBlank b__L :: t__x |))) with 0 by (cbn;nia). easy.\n    }\n    rewrite H, Hx' in Hlast.\n    rewrite nth_error_app1 in Hlast. 2:now cbn;autorewrite with list;cbn;nia.\n    cbn in Hlast. setoid_rewrite nth_error_app1 in Hlast. 2:nia.\n    ediscriminate (Hsymb__x' (RightBlank _)). eapply nth_error_In;eassumption.\n  }\n  specialize (f_equal (firstn (| encode_tape x |)) H) as Heq. rewrite Hl_eq in Heq at 2.\n  rewrite !firstn_app , !Nat.sub_diag, !firstn_all in Heq. apply app_inv_tail in Heq.\n  rewrite <- Heq in *. clear Hle Hl_eq Hmark__x'.\n  now apply tape_encode_injective.\nQed.\n\nModule CheckEncodesTape.\n  Section checkEncodesTape.\n\n    Import Mono Multi Copy Switch If Combinators.\n    \n    Context (sig : Type) (tau:finType) {I : Retract (sigTape sig) tau}.\n\n    Local Remove Hints Retract_id : typeclass_instances.\n    \n    Notation sig__M := (sigTape sig).\n\n    Let Rel : pRel tau bool 1 := ContainsEncoding.Rel (Encode_tape sig) Retr_f.\n\n    Definition M__step : bool*bool -> pTM tau ((bool*bool) + bool) 1 :=\n      fun '(haveSeenMark,haveSeenSymbol) =>\n        Switch\n          ReadChar\n          (fun x =>\n             match Option.bind Retr_g x with\n               None => Return Nop (inr false)\n             | Some c =>\n               if (isMarked c && haveSeenMark) || isNilBlank c || isLeftBlank c || isVoidBlank c\n               then Return Nop (inr (isVoidBlank c && (xorb haveSeenMark (isMarked c)) && haveSeenSymbol))\n               else Return (Move Rmove) (inl (haveSeenMark || isMarked c,haveSeenSymbol || isSymbol c))\n             end).\n\n    (** We can do it as function here, althought that is not the prefered way. Instead, just define a \"pretty\" version o the relation you realise, then you don;t have to worry about termination *)\n    Definition f__step bs t : (bool * bool + bool) * tape tau :=\n      let (haveSeenMark,haveSeenSymbol) := (fst bs,snd bs) in\n      match Option.bind Retr_g (current t) with\n        None => (inr false,t)\n      | Some c =>\n        if (isMarked c && haveSeenMark) || isNilBlank c || isLeftBlank c || isVoidBlank c\n        then (inr (isVoidBlank c && (xorb haveSeenMark (isMarked c)) && haveSeenSymbol),t)\n        else (inl (haveSeenMark || isMarked c,haveSeenSymbol || isSymbol c),tape_move_right t)\n      end.\n\n    Definition M' (bs : bool*bool) := \n      StateWhile M__step bs.\n\n    (* Program Fixpoint f' bs (t : tape tau) { measure (rlength t) } : (bool * tape tau)  :=\n      let r := f__step bs t in\n      match fst r with \n        inl bs' => f' bs' (snd r)\n      | inr b => (b,(snd r))\n      end.\n    Local Obligation Tactic := idtac.\n    Next Obligation. cbn.\n      intros [haveSeenMark haveSeenSymbol] [ | | | ? c' t__R] _ ?;cbn.\n      1-3:now intros [=].\n      destruct (Retr_g c') as [ c | ]. 2:now intros [= <-].\n      destruct c as [ [] | [] | | | ];cbn. all:try solve [inversion 1].\n      1-4:destruct haveSeenMark;cbn.\n      all:intros [= ->]. all:destruct t__R;cbn. all:nia.\n    Qed. *)\n    \n    Function f' bs (t : tape tau) { measure rlength t } : (bool * tape tau)  :=\n      let r := f__step bs t in\n      match fst r with \n        inl bs' => f' bs' (snd r)\n      | inr b => (b,(snd r))\n      end.\n    Proof.\n      unfold f__step. intros [haveSeenMark haveSeenSymbol] [ | | | ? c' t__R] ?;cbn.\n      1-3:now intros [=].\n      destruct (Retr_g c') as [ c | ]. 2:now intros [= <-].\n      destruct c as [ [] | [] | | | ];cbn. all:try solve [inversion 1].\n      1-4:destruct haveSeenMark;cbn.\n      all:intros [= <-]. all:destruct t__R;cbn. all:nia.\n    Qed.\n    \n    Definition M : pTM tau bool 1:=\n      If (Relabel ReadChar (fun c => Option.apply isLeftBlank false (Option.bind Retr_g c)))\n         (Switch ReadChar (fun c => Move Rmove;; M' (Option.apply (@isMarked _) false (Option.bind Retr_g c),false)))\n         (Relabel ReadChar (fun c => Option.apply isNilBlank false (Option.bind Retr_g c))).\n\n    Definition f (t : tape tau) : (bool*tape tau) :=\n      match Option.bind Retr_g (current t) with\n        None => (false,t)\n      | Some c =>\n        if isLeftBlank c then  f' (isMarked c,false) (tape_move_right t)\n        else (isNilBlank c, t)\n      end.\n\n    (** Verification*)\n\n    Lemma Realises__step bs : M__step bs ⊨ (fun t '(y,t')=> f__step bs t[@Fin0] = (y,t'[@Fin0])).\n    Proof.\n      destruct bs as (seenMark, seenSymbol). eapply Realise_monotone.\n      { unfold M__step;cbn. apply Switch_Realise. now TM_Correct.\n        introsSwitch c'. destructBoth (Option.bind Retr_g (rT:=sig__M) c') as [c | ]. 2:now TM_Correct.\n        destructBoth (isMarked c && seenMark || isNilBlank c || isLeftBlank c || isVoidBlank c). all:TM_Correct.\n      }\n      hnf;cbn. intros t (y&t') (?&?&[-> -> ]&H);revert H.\n      destruct Option.bind. 2:{ cbn. now intros (->&_&->). }\n      destruct _. all:cbn. all:intros (->&_&->). all:easy.\n    Qed.\n\n    \n    Lemma Terminates__step bs : projT1 (M__step bs) ↓ (fun _ k => 3 <= k).\n    Proof.\n      destruct bs as (seenMark, seenSymbol). eapply TerminatesIn_monotone.\n      { unfold M__step;cbn. apply Switch_TerminatesIn. 1,2:now TM_Correct.\n        introsSwitch c'. destructBoth (Option.bind Retr_g (rT:=sig__M) c') as [c | ]. 2:now TM_Correct.\n        destructBoth (isMarked c && seenMark || isNilBlank c || isLeftBlank c || isVoidBlank c). all:TM_Correct.\n      }\n      hnf;cbn. intros t y Hy. infTer 3. rewrite <- Hy.\n      2:{ intros ? ? [-> ->]. destruct Option.bind. 2:lia. destruct _. 2:reflexivity. nia. }\n      nia.\n    Qed.\n    \n    Lemma Realises_intern : M ⊨ (fun tin '(b,tout) => f tin[@Fin0] = (b,tout[@Fin0])).\n    Proof.\n      eapply Realise_monotone.\n      { unfold M. TM_Correct_step. 1,3:now TM_Correct.\n        apply Switch_Realise. now TM_Correct.\n        cbn;intros c. TM_Correct_step. now TM_Correct.\n        unfold M'.\n        eapply Realise_monotone with\n            (R:= fun t '(y,t')=> f' (Option.apply (@isMarked _) false (Option.bind Retr_g (rT:=sig__M) c), false) t[@Fin0] = (y,t'[@Fin0])).\n        { eapply StateWhile_Realise. now eapply Realises__step. }\n        generalize (Option.apply (@isMarked _) false (Option.bind Retr_g c), false) as bs. clear c.\n        apply StateWhileInduction. all:cbn - [f__step].\n        -intros t bs b' t'. rewrite f'_equation. intros ->. reflexivity. \n        -intros t bs bs' t' t'' v'. rewrite f'_equation with (t:=t[@Fin0]). intros -> <-. reflexivity.\n      }\n      hnf;cbn.\n      intros t (y&t1) [H |H];revert H.\n      all:intros (?&(?&H1&->&->)&H);revert H.\n      -intros (?&?&[-> ->]&_&t2&Ht2&<-).\n       unfold f. destruct Option.bind . 2:now inv H1.\n       cbn in H1. rewrite <- H1. cbn. congruence.\n      -intros (?&->&->&->). unfold f.\n       destruct Option.bind . 2:easy.\n       cbn in *. now rewrite <- H1. \n    Qed.\n\n    \n    Definition Ter : tRel tau 1:=\n      fun t k => 4 * (| right (t[@Fin0]) |) + 9 <= k.\n\n    Lemma Terminates : projT1 M ↓ Ter.\n    Proof.\n      eapply TerminatesIn_monotone.\n      { unfold M. TM_Correct_step. 1,2,4:TM_Correct.\n        apply Switch_TerminatesIn. 1,2:TM_Correct.\n        cbn;intros c. TM_Correct_step. 1,2:now TM_Correct.\n        unfold M'.\n        eapply TerminatesIn_monotone. 1:{ TM_Correct_step. now eapply Realises__step. now apply Terminates__step. }\n        evar (c0:nat).\n        evar (time : nat -> nat). [time]:intros n0.\n        apply StateWhileCoInduction with (T:= fun _ t k => time (| right (t[@Fin0]) | + Option.apply (fun _ => 1) 0 (current (t[@Fin0]))) +c0 <= k). all:cbn - [f__step].\n        -intros l t k Hk. infTer 2. intros y' t'.\n         unfold f__step. destruct Option.bind eqn:Hc.\n         2:{intros [= <- _]; rewrite <- Hk. enough (3 <= c0). now nia. shelve. }\n         destruct _ eqn:Hs. all: intros [= <- Ht']. 1:{ enough (3 <= c0). now nia. shelve. }\n         rewrite <- Ht'. infTer 2. rewrite <- Hk.\n         destruct t[@Fin0] as [ | | | ? ? t__R]. 1-3:easy. destruct t__R;cbn - [plus mult];ring_simplify.\n         [time]:refine (n0*4). all:unfold time. all:ring_simplify. all: nia.\n      } Unshelve. [c0]:exact 3. 2-3:subst c0;nia.\n      cbn. intros ? ? HT. infTer 5.\n      2:{ intros t ? (?&->&->&<-). destruct _.\n          { infTer 5. intros ? ? [-> ->]. infTer 5. intros ? ? ->. reflexivity. }\n          nia.\n      }\n      ring_simplify. hnf in HT.  rewrite <- HT.\n      destruct (x[@Fin0]) as [ | | | ? ? t__R];cbn - [plus mult];ring_simplify. 1-3:nia.\n      destruct t__R;cbn - [plus mult];nia. \n    Qed.\n    \n    Lemma f'_spec (seenMark seenSymbol b : bool) (c:tau) t__L' t__L t__R res tin:\n      (length (filter (@isMarked _) (t__L'++[LeftBlank b])) = if seenMark then 1 else 0)\n      -> (forall x, x el t__L' -> isSymbol x = true)\n      -> reflect (t__L' <> []) seenSymbol\n      -> tin = (midtape (map Retr_f (t__L'++[LeftBlank b])++t__L) c t__R)\n      -> res = f' (seenMark,seenSymbol) tin \n      ->  (if fst res then\n           exists (x:tape sig) t__R1 (t__R2 : list tau) c',\n             t__R = map Retr_f t__R1++t__R2\n             /\\ c = Retr_f c'\n             /\\ encode_tape x = LeftBlank b :: rev t__L'++c'::t__R1\n             /\\ snd res = midtape (tail (rev (map Retr_f t__R1)++[c])++map Retr_f (t__L'++[LeftBlank b])++t__L) (hd c (rev (map Retr_f t__R1)++[c])) t__R2\n         else\n           (forall x t__R1 (t__R2 : list tau) c',\n             t__R = map Retr_f t__R1++t__R2 ->\n             c = Retr_f c' ->\n             encode_tape x <> LeftBlank b :: rev t__L'++c'::t__R1)) /\\ exists k, snd res = nat_rect _ tin (fun _ => @tape_move_right _) k.\n    Proof.\n      rewrite map_app;cbn.\n      remember (length t__R) as n0 eqn: Hn0. revert tin t__R Hn0 t__L' c res seenMark seenSymbol.\n      induction n0 as [n0 IH] using lt_wf_ind. intros ? ? -> ? ? res ? ?;cbn in *.\n      intros H__seenMark H__symbs H__seenSymbol -> Hres. \n      rewrite f'_equation in Hres. remember (f__step _ _) as f eqn:Hf. unfold f__step in Hf;cbn in Hf.\n      destruct (Retr_g c) as [ [] | ] eqn:Hgc ;cbn. 1-3,6:clear IH.\n      -cbn in Hf. rewrite orb_true_r in Hf;cbn in Hf. subst f;cbn in Hres;subst res. cbn.\n       split. 2:exists 0;now auto.\n       intros ? ? ? ? -> [= ->] ((init__R&b__R&H__R&Hsym)&Hmarks&Hlength)%encode_tape_invariants_partial;cbn in *. 2:now setoid_rewrite <- in_rev.\n       retract_adjoint. inv Hgc. destruct init__R;inv H__R.  ediscriminate (Hsym (LeftBlank _)). easy.     \n      -cbn in Hf. rewrite !orb_true_r in Hf. subst f. revert Hres. cbn.\n       destruct marked;cbn in *. destruct seenMark;cbn in *. all:intros ->;cbn. 3:destruct seenMark;cbn. 2,3:destruct seenSymbol;cbn.\n       +split. 2:exists 0;split;now auto.\n        intros ? ? ? ? -> [= ->] ((init__R&b__R&H__R&Hsym)&Hmarks&Hlength)%encode_tape_invariants_partial;cbn in *. 2:now setoid_rewrite <- in_rev.\n        retract_adjoint. inv Hgc. cbn in Hmarks;autorewrite with list in *. nia.\n       +edestruct invert_symbols_0_marked with (t:= t__L') as (t__R2&->).\n        1,2:autorewrite with list in *. now nia. now intros;eapply H__symbs.\n        destruct b. 1:{exfalso. autorewrite with list in H__seenMark. now cbn in H__seenMark;nia. } \n        destruct t__R2 as [ | c' cs] eqn:Htp. 1:{exfalso. inversion H__seenSymbol. easy. }\n        apply retract_g_inv in Hgc as ->.\n        split. 2:exists 0;split;now auto.\n        eexists (rightof _ _),[],_,_. repeat eapply conj. 1,2,4:reflexivity. cbn.\n        autorewrite with list;cbn.  setoid_rewrite <- map_rev with (l:=cs) at 2. easy.\n       +split. 2:exists 0;split;now auto.\n        intros ? ? ? ? -> [= ->] ((init__R&b__R&H__R&Hsym)&Hmarks&Hlength)%encode_tape_invariants_partial;cbn in *. 2:now setoid_rewrite <- in_rev.\n        retract_adjoint. inv Hgc.\n        destruct t__L'. all:inv H__seenSymbol. 2:now apply H. cbn in *;autorewrite with list in *.\n        destruct init__R;inv H__R. 2:{ ediscriminate (Hsym (RightBlank _)). easy. }\n        cbn in *. nia.\n       +destruct b.\n        *edestruct invert_symbols_0_marked with (t:= t__L') as (t__R2&->).\n         1,2:autorewrite with list in *;cbn in *. now nia. now intros;eapply H__symbs.\n         destruct t__R2 eqn:?. 1:{exfalso. inversion H__seenSymbol. easy. }\n         destruct (rev t__R2) eqn:Htp. 1:{exfalso. subst. revert Htp. length_not_eq. }\n         apply retract_g_inv in Hgc as ->.\n         split. 2:exists 0;split;now auto.\n         eexists (leftof _ _),[],_,_. repeat eapply conj. 1,2,4:reflexivity. rewrite <- Heql. cbn.\n         setoid_rewrite <- map_rev with (l:=t__R2). now rewrite Htp.\n        *edestruct @invert_symbols_1_marked with (t:= t__L') as (?&?&?&->).\n         1,2:autorewrite with list in *;cbn in *. now nia. now intros;eapply H__symbs.\n         apply retract_g_inv in Hgc as ->.\n         split. 2:exists 0;split;now auto.\n         eexists (midtape _ _ _),[],_,_. repeat eapply conj. 1,2,4:reflexivity. cbn.\n         repeat (autorewrite with list;cbn).  setoid_rewrite map_rev. easy.\n       +split. 2:exists 0;split;now auto. intros ? ? ? ? -> [= -> ] ((init__R&b__R&H__R&Hsym)&Hmarks&Hlength)%encode_tape_invariants_partial;cbn in *.\n        2:now setoid_rewrite <- in_rev. retract_adjoint. inv Hgc.\n        destruct init__R;inv H__R. 2:{ ediscriminate (Hsym (RightBlank _)). easy. }\n        cbn in *. assert (t__L' = []) as ->. 1:{ destruct t__L'. easy. inversion H__seenSymbol. destruct H. easy. }\n        cbn in *;nia.\n       +split. 2:exists 0;split;now auto. intros ? ? ? ? -> [= ->] ((init__R&b__R&H__R&Hsym)&Hmarks&Hlength)%encode_tape_invariants_partial;cbn in *.\n        2:now setoid_rewrite <- in_rev. retract_adjoint. inv Hgc. \n        destruct init__R;inv H__R. 2:{ ediscriminate (Hsym (RightBlank _)). easy. }\n        cbn in *. autorewrite with list in *. nia.\n      -cbn in Hf; rewrite orb_true_r in Hf; cbn in Hf. subst f;cbn in Hres;subst res;cbn.\n       split. 2:exists 0;split;now auto.\n       intros ? ? ? ? -> [= ->]((init__R&b__R&H__R&Hsym)&Hmarks&Hlength)%encode_tape_invariants_partial;cbn in *. 2:now setoid_rewrite <- in_rev.\n        retract_adjoint. inv Hgc.\n       destruct init__R;inv H__R. discriminate (Hsym (NilBlank)). easy.   \n      -subst f res;cbn. split. 2:exists 0;split;now auto. intros ? ? ? ? _ ->. edestruct (retract_g_None Hgc). easy.\n      -revert Hf Hres. cbn. destruct seenMark;cbn.\n       {clear IH. intros -> ->;cbn.\n        split. 2:exists 0;split;now auto. \n        intros ? ? ? ? -> [= ->]((init__R&b__R&H__R&Hsym)&Hmarks&Hlength)%encode_tape_invariants_partial;cbn in *. 2:now setoid_rewrite <- in_rev.\n        retract_adjoint. inv Hgc. cbn in *.\n        autorewrite with list in *. nia.\n       } intros ->;cbn.\n       destruct t__R.\n       { clear IH. cbn. rewrite f'_equation;cbn.  \n         intros ->;cbn. split. 2:exists 1;split;now auto.\n         intros ? ? ? ? Hnil [= ->] ((init__R&b__R&H__R&Hsym)&Hmarks&Hlength)%encode_tape_invariants_partial;cbn in *.\n         2:now setoid_rewrite <- in_rev. retract_adjoint. inv Hgc.\n         destruct init__R;inv H__R. length_not_eq in Hnil. \n       }\n       cbn. intros H.\n       autorewrite with list in H__seenMark. destruct b;cbn in H__seenMark. now nia. \n       specialize IH with (t__L' := MarkedSymbol s :: t__L');cbn in IH. erewrite <- !(retract_g_inv Hgc) in IH.\n       pose (H' := H);eapply IH in H';clear IH.\n       3,7:reflexivity. 2:nia. 2:now autorewrite with list in *;nia. 2:now intros ? [<- | ];eauto.\n       2:now rewrite orb_true_r;constructor.\n       destruct res as [[] t'];cbn in *.\n       +destruct H' as [(x&t__R1&t__R2&c'&->&->&Hx&->) Hres].\n        split. 2:{ destruct Hres as (k&->). exists (S k). now rewrite nat_rect_succ_r. } clear Hres.\n        eexists x,(_::t__R1),t__R2,_.\n        repeat (cbn in Hx|-*;autorewrite with list in Hx|-* ).\n        apply retract_g_inv in Hgc as ->.\n        split. 2:split. 3:split.\n        1,2:reflexivity. easy.\n        destruct (rev (map Retr_f t__R1));cbn;now autorewrite with list.\n       +split. 2:{ destruct H' as [_ [k H']]. exists (S k). now rewrite nat_rect_succ_r. }\n        intros x ? ? ? H__R [= ->] Hx. specialize encode_tape_invariants_partial with (1:=Hx) as ((init__R&b__R&H__R'&Hsym)&Hmarks&Hlength);cbn in *. now setoid_rewrite <- in_rev.\n        retract_adjoint. inv Hgc.\n        destruct init__R;inv H__R'.\n        destruct (init__R ++ [RightBlank b__R]) eqn:eq. now length_not_eq in eq. revert H__R;intros [= -> ->].\n        eapply H'. 1,2:easy. rewrite Hx;cbn;autorewrite with list;cbn. reflexivity.\n      -revert Hf Hres. cbn. intros ->;cbn.\n       destruct t__R.\n       { clear IH. cbn. rewrite f'_equation;cbn.  \n         intros ->;cbn. split. 2:{ cbn. now exists 1. }\n         intros ? ? ? ? Hnil [= ->] ((init__R&b__R&H__R&Hsym)&Hmarks&Hlength)%encode_tape_invariants_partial;cbn in *.\n         retract_adjoint. inv Hgc. \n         2:now setoid_rewrite <- in_rev.  destruct t__R1. 2:easy. destruct init__R.  2:length_not_eq in H__R. inv H__R. \n       }\n       cbn;intros H.\n       specialize IH with (t__L' := UnmarkedSymbol s :: t__L');cbn in IH. erewrite <- !(retract_g_inv Hgc) in IH.\n       pose (H' := H);eapply IH in H';clear IH.\n       3,7:reflexivity. 2:lia. 3:now intros ? [<- | ];eauto. 3:now rewrite orb_true_r;constructor.\n       2:{ autorewrite with list in *. destruct seenMark;cbn in *;nia. }\n       destruct H' as [H' Hres].\n       split. 2:{ destruct Hres as (k&->). exists (S k). now rewrite nat_rect_succ_r. } clear Hres.\n       destruct res as [[] t'];cbn in *.\n       +destruct H' as (x&t__R1&t__R2&c'&->&->&Hx&->).\n        apply retract_g_inv in Hgc as ->. \n        eexists x,(_::t__R1),t__R2,_. cbn.\n        repeat (cbn in Hx|-*;autorewrite with list in Hx|-* ). split. 2:split. 3:split. 1,2:reflexivity. easy.\n        destruct (rev (map Retr_f t__R1));cbn;now autorewrite with list.\n       +intros x ? ? ? H__R [= ->] Hx. specialize encode_tape_invariants_partial with (1:=Hx) as ((init__R&b__R&H__R'&Hsym)&Hmarks&Hlength);cbn in *. now setoid_rewrite <- in_rev.\n        retract_adjoint. inv Hgc.\n        setoid_rewrite <- app_assoc in H'. cbn in H'.\n        destruct t__R1;inv H__R. 1:{ destruct init__R. easy. length_not_eq in H__R'. }\n        eapply H'. 1,2:reflexivity. now rewrite Hx.\n    Qed.\n\n    Lemma f_spec t b t':\n      f t = (b,t')\n      -> Rel [|t|] (b,[|t'|]).\n    Proof.\n      unfold f,Rel;cbn. rewrite ContainsEncoding.legacy_iff. 2:now intros []. destruct Option.bind eqn:Hcur.\n      2:{ intros [= <- <-];cbn;split. 2:now exists 0. intros ? ? ?. destruct x;cbn;eexists _,_;(split;[reflexivity| ]). all:intros ->;cbn in Hcur. all:now rewrite retract_g_adjoint in Hcur. }\n      destruct t as [ | | | t__L s' t__R];cbn in *. 1-3:now inversion Hcur.\n      apply retract_g_inv in Hcur as ->.\n      unfold ContainsEncoding.Rel. cbn. \n      destruct isLeftBlank eqn:H__LB.\n      2:destruct isNilBlank eqn:H__NB.\n      2:{ intros [= <- <- ]. destruct s;inv H__NB. split. 2:now eexists 0. eexists (@niltape _),t__L,t__R;cbn.\n          split. eexists _, nil;cbn. easy. eexists nil,_;cbn. easy. }\n      2:{ intros [= <- <- ]. split. 2:now eexists 0. intros ? x ?. destruct x;cbn;eexists _,_;(split;[reflexivity | ]).\n          all:intros [= <- ->%retract_f_injective ->]. all:easy. }\n      destruct s;inv H__LB.\n      destruct t__R. 1:{ cbn. rewrite f'_equation. cbn. intros [= <- <-]. split. 2:{now exists 1. } intros ? x ?.\n                       destruct x;cbn;eexists _,_;(split;[reflexivity | ]). all:intros [= <- ?%retract_f_injective HH]. easy. all:revert HH.\n                       all:length_not_eq. }\n      intros H';symmetry in H'. assert (H:=H'). revert H. eintros [H Hres]%(f'_spec (t__L':=[])). 5:reflexivity. \n      2:now destruct marked;cbn;nia. 2:easy. 2:now constructor.\n        split. 2:{ cbn in Hres;destruct Hres as (k&->). exists (S k). now rewrite nat_rect_succ_r. } clear Hres.\n      destruct b;cbn  in H.\n      -destruct H as (x&t__R1&t__R2&c'&->& -> &Hx&->).\n       eexists _,_,_;split.\n       +rewrite Hx;cbn. do 3 eexists. easy. cbn. eauto.\n       +destruct (exists_last (l:=encode_tape x)) as (?&?&eqx). congruence. rewrite eqx in *.\n        repeat eexists.\n        apply (f_equal (fun t => rev (map (Retr_f (Y:=tau)) t))) in Hx. cbn in  Hx.\n        autorewrite with list in Hx;cbn in Hx. f_equal.\n        \n        *rewrite (app_comm_cons' _ _ (Retr_f (LeftBlank marked))). rewrite <- tl_app. 2: length_not_eq.\n         rewrite <- app_assoc. cbn. rewrite <- Hx. cbn. now rewrite map_rev.\n        *apply (f_equal (hd (Retr_f c'))) in Hx. destruct rev;cbn in *. all: easy.\n      -hnf. intros ? x ?.\n       destruct encode_tape eqn:eqx. now destruct x.\n       do 3 eexists. cbn. easy. intros [= <- <-%retract_f_injective H''].\n       destruct l. 1:{ destruct x;cbn in eqx;try now inv eqx. all:length_not_eq in eqx. }\n       inv H''. eapply H. 1,2:reflexivity. eassumption.\n    Qed.\n\n    Lemma Realise : M ⊨ Rel.\n    Proof.\n      eapply Realise_monotone. now apply Realises_intern. intros t [? t'] ?%f_spec.\n      unfold tapes in *. \n      destruct_vector. easy.\n    Qed.\n\n  End checkEncodesTape.\nEnd CheckEncodesTape.\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/TM/Single/DecodeTape.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318194686359, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.28311757608822935}}
{"text": "(* -------------------------------------------------------------------- *)\n(* ------- *) Require Import Setoid Morphisms.\nFrom mathcomp Require Import all_ssreflect all_algebra.\nFrom mathcomp.analysis\n  Require Import boolp reals realseq realsum distr.\nFrom xhl.pwhile\n  Require Import notations inhabited pwhile psemantic passn range.\n(* ------- *) Require Import range ellora.\n\nSet   Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nUnset SsrOldRewriteGoalsOrder.\n\nImport GRing.Theory Num.Theory.\n\nLocal Open Scope ring_scope.\nLocal Open Scope syn_scope.\nLocal Open Scope sem_scope.\nLocal Open Scope mem_scope.\n\n(* -------------------------------------------------------------------- *)\nLocal Notation dmem  := (Distr cmem).\nLocal Notation dassn := (pred  dmem).\n\nImplicit Types P Q S : dassn.\nImplicit Types c : cmd.\nImplicit Types mu : dmem.\n\n(* -------------------------------------------------------------------- *)\nLocal Notation iwhilen k b c := (iterc k (IfT b then c)).\n\n(* -------------------------------------------------------------------- *)\nInductive sellora : dassn -> dassn -> cmd -> Prop :=\n| ESkip P : sellora P P skip\n\n| EAbort P : sellora P (□ pred0) abort\n\n| ESeq S P Q c1 c2 :\n    sellora P S c1 -> sellora S Q c2 -> sellora P Q (c1 ;; c2)\n\n| EConseq P' Q' P Q c :\n       (forall mu, mu \\in P  -> mu \\in P')\n    -> (forall mu, mu \\in Q' -> mu \\in Q )\n    -> sellora P' Q' c\n    -> sellora P  Q  c\n\n| ESem c1 P Q c2 :\n       (forall mu, mu \\in P -> dssem c1 mu = dssem c2 mu)\n    -> sellora P Q c1 -> sellora P Q c2\n\n| ESemCond P Q (e : expr bool) c1 c2 :\n       (forall mu, mu \\in P -> forall m, m \\in dinsupp mu -> `[{ e }] m)\n    -> sellora P Q c1 -> sellora P Q (If e then c1 else c2)\n\n| ESemCondF P Q (e : expr bool) c1 c2 :\n       (forall mu, mu \\in P -> forall m, m \\in dinsupp mu -> `[{ ~~ e }] m)\n    -> sellora P Q c2 -> sellora P Q (If e then c1 else c2)\n\n| EDframe P c :\n    separated (mod c) P -> lossless predT c -> sellora P P c\n\n| EAnd P Q1 Q2 c :\n    sellora P Q1 c -> sellora P Q2 c -> sellora P (Q1 /\\ Q2)%A c\n\n| EOr P1 P2 c Q :\n    sellora P1 Q c -> sellora P2 Q c -> sellora (P1 \\/ P2)%A Q c\n\n| EAssign {t : ihbType} P (x : vars t) (e : expr t) :\n    sellora (P.[fun mu => dssem (x <<- e) mu])%A P (x <<- e)\n  \n| ESample {t : ihbType} P (x : vars t) (d : dexpr t) :\n    sellora (P.[fun mu => dssem (x <$- d) mu])%A P (x <$- d)\n\n| ECond P P' Q Q' e c1 c2 :\n    let SP := (P /\\ □ [pred m | `[{    e }] m])%A in\n    let SQ := (Q /\\ □ [pred m | `[{ ~~ e }] m])%A in\n  \n       sellora SP P' c1\n    -> sellora SQ Q' c2\n    -> sellora (SP ⊕ SQ) (P' ⊕ Q') (If e then c1 else c2)\n\n| EWhileDClosed P b c :\n       dclosed P -> sellora P P (IfT b then c)\n    -> sellora P (P /\\ □ `[{~~ b}])%A (While b Do c)\n\n| EWhileTClosed (P Q : nat -> dassn) Qinf b c :\n       (forall n, sellora (P n) (P n.+1) (IfT b then c))\n    -> (forall n, sellora (P n) (Q n) (IfT b then abort))\n    -> tclosed Q Qinf\n    -> sellora (P 0%N) (Qinf /\\ □ `[{~~ b}])%A (While b Do c)\n\n| EWhileUClosed (P Q : nat -> dassn) Qinf b c :\n       (forall n, sellora (P n) (P n.+1) (IfT b then c))\n    -> (forall n, sellora (P n) (Q n) (IfT b then abort))\n    -> uclosed Q Qinf\n    -> sellora (P 0%N) (Qinf /\\ □ `[{~~ b}])%A (While b Do c)\n\n| EWhileCertainCT P b c :\n    (forall mu, mu \\in P -> exists k,\n       \\P_[dssem (iwhilen k b c) mu] [eta `[{ b }]] = 0)\n  -> sellora P P (IfT b then c)\n  -> sellora P (P /\\ □ `[{ ~~ b}])%A (While b Do c)\n\n| EWhileCertain (P : nat -> dassn) k e c :\n     (forall n, sellora (P n) (P n.+1) (IfT e then c))\n  -> (forall mu, P 0%N mu -> dssem (While e Do c) =\n                             dssem (iterc k (IfT e then c)))\n  -> sellora (P 0%N) (P k /\\ □ `[{~~ e}])%A (While e Do c)\n\n| ESplit P P' Q Q' c :\n    sellora P Q c -> sellora P' Q' c -> sellora (P) (Q) c.\n\n(* -------------------------------------------------------------------- *)\nLemma sound P Q c : sellora P Q c -> ellora P Q c.\nProof. by elim=> {P Q c}; eauto 2 using ellora_cond with ellora. Qed.\n", "meta": {"author": "strub", "repo": "xhl", "sha": "5c4a4c0691438a2be9b650372ba95aca09ba3c56", "save_path": "github-repos/coq/strub-xhl", "path": "github-repos/coq/strub-xhl/xhl-5c4a4c0691438a2be9b650372ba95aca09ba3c56/ellora/sound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.629774621301746, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.28301607618583796}}
{"text": "Require Import Ssreflect.ssreflect Ssreflect.ssrbool Ssreflect.ssrnat Ssreflect.eqtype Ssreflect.seq Ssreflect.fintype.\nRequire Import x86proved.x86.procstate x86proved.x86.procstatemonad x86proved.bitsops x86proved.bitsprops x86proved.bitsopsprops.\nRequire Import x86proved.spred x86proved.septac x86proved.spec x86proved.spectac x86proved.x86.basic x86proved.x86.program x86proved.x86.macros.\nRequire Import x86proved.x86.instr x86proved.x86.instrsyntax x86proved.x86.instrcodec x86proved.x86.instrrules x86proved.reader x86proved.pointsto x86proved.cursor.\nRequire Import x86proved.chargetac x86proved.latertac.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLocal Open Scope instr_scope.\n(* Allocation invariant:\n     infoBlock points to a pair of DWORDs:\n       base, a pointer to the current available heap\n       count, the number of bytes currently available\n   Furthermore, \"count\" bytes of memory starting at \"base\" is defined\n*)\nDefinition allocInv (infoBlock: DWORD) :=\n  Exists base: DWORD,\n  Exists count: DWORD,\n  infoBlock :-> base **\n  infoBlock +#4 :-> count **\n  memAny base count.\n\n(* Allocate memory.\n     infoBlock: Src  is pointer to two-word heap information block\n     n: nat representing number of bytes to be allocated\n     failed: DWORD is label to branch to on failure\n   If successful, EDI contains pointer to byte just beyond allocated block.\n*)\nDefinition allocImp (infoBlock:DWORD) (n: nat) (failed: DWORD) : program :=\n  MOV EDI, [infoBlock];;\n  ADD EDI, n;;\n  JC  failed;;  (* A carry indicates unsigned overflow *)\n  CMP [infoBlock+#4:DWORD], EDI;;\n  JC  failed;;  (* A carry indicates unsigned underflow *)\n  MOV [infoBlock], EDI.\n\nDefinition allocSpec n (fail:DWORD) inv code :=\n  Forall i j : DWORD, (\n      safe @ (EIP ~= fail ** EDI?) //\\\\\n      safe @ (EIP ~= j ** Exists p, EDI ~= p +# n ** memAny p (p +# n))\n    -->>\n      safe @ (EIP ~= i ** EDI?)\n    )\n    @ (OSZCP? ** inv)\n    c@ (i -- j :-> code).\n\nHint Unfold allocSpec : specapply.\n\n(* Perhaps put a |> on the failLabel case *)\nRequire Import x86proved.basicspectac.\nLemma inlineAlloc_correct n failed infoBlock : |-- allocSpec n failed (allocInv infoBlock) (allocImp infoBlock n failed).\nProof.\n  rewrite /allocSpec/allocImp.\n  specintros => *. \n  unfold_program. specintros => *.\n  (* Push invariant under implication so that we can instantiate existential pre and post *)\n  rewrite spec_at_impl. rewrite /allocInv. specintros => base limit. \n\n  (* MOV EDI, [infoBlock] *)  \n  superspecapply MOV_RanyInd_rule. \n\n  (* ADD EDI, bytes *)\n  superspecapply *. \n\n  (* JC failed *)\n  rewrite /OSZCP. \n  superspecapply JC_rule. \n\n  specsplit.\n  simpllater. (*rewrite <- spec_frame. *) finish_logic_with sbazooka.\n\n  (* CMP [infoBlock+#4], EDI *)\n  specintro => /eqP => Hcarry. \n\n  specapply CMP_IndR_ZC_rule; rewrite /stateIsAny; sbazooka. \n\n  (* JC failed *)\n  superspecapply JC_rule. \n  specsplit.\n  - simpllater. (*rewrite <- spec_frame. *) finish_logic_with sbazooka.\n\n  (* MOV [infoBlock], EDI *)\n  superspecapply MOV_IndR_rule. \n\n  specintro => /eqP LT.\n\n  { (*rewrite <- spec_frame. *) rewrite /stateIsAny/natAsDWORD. finish_logic. (*apply limplValid.\n    autorewrite with push_at. *) apply landL2. finish_logic_with sbazooka.  \n\n    apply memAnySplit.\n    { apply: addB_leB.\n      apply injective_projections; [ by rewrite Hcarry\n                                   | by generalize @adcB ]. }\n    { simpl. rewrite ltBNle /natAsDWORD in LT. rewrite -> Bool.negb_false_iff in LT. by rewrite LT. } }\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/inlinealloc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.28301607618583796}}
{"text": "From iVM Require Import DSet Mono Cert0 Cert1.\nImport DSetNotations.\n\nUnset Suggest Proof Using.\n\n(* TODO: Place inside section or module. *)\nImport OpCodes.\n\nLocal Notation not_terminated := (ret true) (only parsing).\nLocal Notation terminated := (ret false) (only parsing).\n\n(*****************)\n\n(* TODO: Move *)\nProposition get_mem''_spec a {X} (f: (available a -> option Cell) -> M X) :\n  let* x := get' (MEM'' a) in\n  f x =\n    let* mem := get' MEM in\n    f (mem a).\nProof.\n  unfold MEM''.\n  setoid_rewrite get_spec.\n  smon_rewrite.\nQed.\n\n(* TODO: Move *)\nProposition pointLens_restrLens\n  {A : Type} {F : A -> Type}\n  {H_eqdec: EqDec A} (a : A) :\n  pointLens (F:=F) a ≃ restrLens !{a}.\nProof.\n  intros f g.\n  cbn.\n  extensionality x.\n  destruct (decide (x ∈ !{a})) as [Hx|Hx].\n  - rewrite singleton_spec in Hx.\n    symmetry in Hx.\n    decided Hx.\n    destruct H.\n    reflexivity.\n  - rewrite singleton_spec in Hx.\n    assert (a <> x) as H; [ congruence | ].\n    undecided H.\n    reflexivity.\nQed.\n\nProposition not_member_independent\n  {A : Type} {F : A -> Type}\n  {H_eqdec: EqDec A} (a : A) (u: DSet A) (Ha: ~ (a ∈ u)) :\n  Independent (pointLens (F:=F) a) (restrLens u).\nProof.\n  intros f g h.\n  cbn.\n  extensionality x.\n  destruct (decide (x ∈ u)) as [Hxu|Hxu]; [ | reflexivity ].\n  assert (a <> x) as Hax; [ congruence | ].\n  now undecided Hax.\nQed.\n\n(* TODO: Move *)\nArguments confined_neutral {_ _ _ _} _ _ {_ _} _.\n\nInstance lens_semiNeutral\n{S M} {SM: SMonad S M}\n{X A} (LA: Lens S A) (mx: M X)\n(Hmx: mx =\n  let* a := get' LA in\n  let* x := mx in\n  put' LA a;;\n  ret x) : SemiNeutral LA mx.\nProof.\n  unfold SemiNeutral.\n  rewrite -> Hmx at 1.\n  rewrite get_spec, put_spec, putM_spec.\n  smon_rewrite.\nQed.\n\nInstance semiNeutral_popMany n : SemiNeutral MEM (popMany n).\nProof.\n  induction n;\n    apply lens_semiNeutral;\n    simp popMany;\n    [ smon_rewrite | ].\n  setoid_rewrite (semiNeutral_get_put MEM pop).\n  setoid_rewrite (semiNeutral_get_put MEM (popMany n)) at 1.\n  smon_rewrite.\nQed.\n\nLemma popMany_pushMany n :\n  let* u := popMany n in\n  pushMany u =\n    let* sp := get' SP in\n    sDefined (nAfter n sp).\nProof.\n  rewrite popMany_defined.\n  rewrite sDefined_spec.\n  repeat setoid_rewrite bind_assoc.\n  smon_ext' SP sp.\n  setoid_rewrite lens_put_get.\n  setoid_rewrite (confined_get MEM);\n  [ | typeclasses eauto .. ].\n  smon_ext' MEM mem.\n  setoid_rewrite lens_put_get.\n  destruct (decide _) as [H|H];\n  [ | now smon_rewrite01 ].\n  smon_rewrite2.\n  revert sp mem H;\n    induction n;\n    intros sp mem H.\n  - simp popMany.\n    setoid_rewrite ret_bind.\n    simp to_list.\n    rewrite pushMany_empty.\n    now smon_rewrite2.\n  - rewrite popMany_S.\n    setoid_rewrite to_list_action.\n    setoid_rewrite pushMany_action.\n    setoid_rewrite pushMany_one.\n    setoid_rewrite (collapse_bind_lift pop_push).\n    setoid_rewrite bind_assoc.\n    setoid_rewrite popMany_getSP.\n    setoid_rewrite lens_put_get.\n\n    rewrite defined_spec.\n    smon_rewrite01.\n    set (a := offset n sp).\n    assert (a ∈ nAfter (S n) sp) as Hin.\n    + rewrite nAfter_nonempty.\n      rewrite union_spec.\n      right.\n      rewrite singleton_spec.\n      reflexivity.\n    + destruct (H a Hin) as [Ha Hm].\n      decided Ha.\n      setoid_rewrite ret_bind.\n      setoid_rewrite (semiNeutral_get_put MEM (popMany n)).\n      setoid_rewrite <- (confined_put SP); [ | typeclasses eauto ].\n      repeat setoid_rewrite lens_put_get.\n      decided Hm.\n      setoid_rewrite ret_tt_bind.\n      setoid_rewrite (confined_put SP); [ | typeclasses eauto ].\n      setoid_rewrite <- (semiNeutral_put_put MEM (popMany n)).\n      setoid_rewrite <- (confined_put SP); [ | typeclasses eauto ].\n      apply IHn.\n      clear a Hin Ha Hm.\n      intros a Hin.\n      apply (H a).\n      rewrite nAfter_nonempty.\n      rewrite union_spec.\n      now left.\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/Cert2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.28301606994047906}}
{"text": "Require Import POCS.\n\nModule BadSectorDisk.\n\n  Inductive Op : Type -> Type :=\n  | BadRead (a:addr) : Op block\n  | BadWrite (a:addr) (b:block) : Op unit\n  | GetBadSector : Op addr\n  | BadDiskSize : Op nat.\n\n  Record State :=\n    mkState {\n      stateDisk : disk;\n      stateBadSector : addr;\n    }.\n\n  (* help out type inference *)\n  Implicit Type (state:State).\n\n  Inductive op_step : forall `(op: Op T), Semantics State T :=\n  | step_read : forall a r (d : disk) bs,\n      a <> bs -> d a = Some r ->\n      op_step (BadRead a) (mkState d bs) r (mkState d bs)\n  | step_read_oob : forall a r (d : disk) bs,\n      a <> bs -> d a = None ->\n      op_step (BadRead a) (mkState d bs) r (mkState d bs)\n  | step_read_bad : forall a r (d : disk) bs,\n      a = bs ->\n      op_step (BadRead a) (mkState d bs) r (mkState d bs)\n  | step_write : forall a b (d : disk) bs,\n      op_step (BadWrite a b) (mkState d bs) tt (mkState (diskUpd d a b) bs)\n  | step_get_bs : forall d bs,\n      op_step GetBadSector (mkState d bs) bs (mkState d bs)\n  | step_size : forall d bs,\n      op_step BadDiskSize (mkState d bs) (size d) (mkState d bs).\n\n  Definition crash_relation state state' := False.\n  Definition inited state := True.\n\n  Definition API : InterfaceAPI Op State :=\n    {|\n      op_sem := @op_step;\n      crash_effect := crash_relation;\n      init_sem := inited;\n    |}.\n\n  Ltac inv_step :=\n    idtac;  (* Ltac evaluation order issue when passing tactics *)\n    match goal with\n    | [ H: op_step _ _ _ _ |- _ ] =>\n      inversion H; subst; clear H;\n      repeat sigT_eq;\n      safe_intuition\n    end.\n\nEnd BadSectorDisk.\n", "meta": {"author": "mit-pdos", "repo": "deepspec-pocs", "sha": "699767342c0daf4657f03ef8f7a7a3ba91e79a6e", "save_path": "github-repos/coq/mit-pdos-deepspec-pocs", "path": "github-repos/coq/mit-pdos-deepspec-pocs/deepspec-pocs-699767342c0daf4657f03ef8f7a7a3ba91e79a6e/src/BadSectorDisk/BadSectorAPI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.5, "lm_q1q2_score": 0.28300927491873945}}
{"text": "Require compcert.backend.CleanupLabelsproof.\nRequire LinearX.\n\nImport Coqlib.\nImport Globalenvs.\nImport Events.\nImport Smallstep.\nImport LinearX.\nImport CleanupLabels.\nExport CleanupLabelsproof.\n\nSection WITHCONFIG.\n  Context `{external_calls_prf: ExternalCalls}.\n\n  Variable prog: program.\n  Let tprog := transf_program prog.\n  Let ge := Genv.globalenv prog.\n  Let tge := Genv.globalenv tprog.\n\n  Let MATCH_PROG: match_prog prog tprog.\n  Proof.\n    apply transf_program_match.\n  Qed.\n\n  Lemma transf_initial_states:\n    forall init_ls i sg args m,\n    forall st1, initial_state init_ls prog i sg args m st1 ->\n           exists st2, initial_state init_ls tprog i sg args m st2 /\\ match_states st1 st2.\n  Proof.\n    intros. inv H.\n    econstructor; split.\n    eapply initial_state_intro with (f0 := transf_fundef f).\n    unfold tprog. erewrite symbols_preserved; eauto.\n    eapply function_ptr_translated; eauto.\n    erewrite sig_function_translated. auto.\n    reflexivity.\n    constructor; auto. constructor.\n  Qed.\n\n  Lemma transf_final_states:\n    forall init_ls,\n    forall sg,\n    forall st1 st2 r, \n      match_states st1 st2 -> final_state init_ls sg st1 r -> final_state init_ls sg st2 r.\n  Proof.\n    intros. inv H0. inv H. inv H4. econstructor; eauto.\n  Qed.\n\n  Theorem transf_program_correct:\n    forall init_ls i sg args m,\n      forward_simulation (semantics init_ls prog i sg args m) (semantics init_ls tprog i sg args m).\n  Proof.\n    intros.\n    eapply forward_simulation_opt.\n    apply senv_preserved; auto.\n    apply transf_initial_states.\n    apply transf_final_states.\n    apply transf_step_correct; auto.\n  Qed.\n\nEnd WITHCONFIG.\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/CleanupLabelsproofX.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961013, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2830092675980507}}
{"text": "Require Import language.\nRequire Import msl.base.\nRequire Import msl.seplog.\nRequire Import msl.alg_seplog.\n\nLocal Open Scope logic.\n\nModule Type SEMAX.\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_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, fun s => allocpool (eval (Var 0) s)).\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 (fun s => cont P (eval x s) && call P (eval_list ys s)) (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 (fun s => |> subst x (eval y s) P s) (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 (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).\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 (fun s => (mapsto (eval y s) z * TT) && |> subst x z P s)\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 (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).\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 (fun s => EX v:A, (P v s)) 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 (fun s => EX v:A, (P v s)) 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 (fun s => !! R && P s) c.\n\nAxiom semax_G:\n   forall vars G P c, semax vars G (fun s => P s && funassert G) c -> semax vars G P c.\n\n\nEnd SEMAX.\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/examples/cont/seplogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6406358685621719, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.28295156960442247}}
{"text": "Require Import Verdi.Verdi.\nRequire Import Verdi.HandlerMonad.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nClass PrimaryBackupParams (base_params : BaseParams) :=\n  {\n    input_eq_dec : forall x y : input, {x = y} + {x <> y}\n  }.\n\nSection PrimaryBackup.\n  Context {base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams base_params}.\n  Context {pb_params : PrimaryBackupParams base_params}.\n\n  Inductive name := Primary | Backup.\n\n  Lemma name_eq_dec : forall x y : name, {x = y} + {x <> y}.\n  Proof using.\n    decide equality.\n  Qed.\n\n  Inductive msg :=\n  | BackItUp : input -> msg\n  | Ack : msg.\n\n  Lemma msg_eq_dec : forall x y : msg, {x = y} + {x <> y}.\n  Proof using pb_params.\n    decide equality.\n    apply input_eq_dec.\n  Qed.\n\n  Inductive PB_input :=\n  | Request : input -> PB_input\n  | Read : PB_input.\n\n  Inductive PB_output :=\n  | RequestResponse : input -> output -> PB_output\n  | ReadResponse : data -> PB_output.\n\n  Record PB_data :=\n    {\n      queue : list input;\n      state : data\n    }.\n\n  Definition all_nodes : list name := [Primary; Backup].\n\n  Lemma all_nodes_all :\n    forall x,\n      In x all_nodes.\n  Proof using.\n    unfold all_nodes.\n    destruct x; intuition.\n  Qed.\n\n  Lemma NoDup_all_nodes :\n    NoDup all_nodes.\n  Proof using.\n    unfold all_nodes.\n    repeat constructor; intuition. simpl in *. intuition. congruence.\n  Qed.\n\n  Definition PB_init (n : name) :=\n    Build_PB_data [] init.\n\n  Definition set_queue {W O} (l : list input) :=\n    modify (W := W)(O := O) (fun d => Build_PB_data l (state d)).\n\n  Definition set_state {W O} (st : data) :=\n    modify (W := W)(O := O) (fun d => Build_PB_data (queue d) st).\n\n  Ltac pb_unfold := unfold set_queue, set_state in *; monad_unfold.\n\n  Definition PB_input_handler (h : name) (i : PB_input) (d : PB_data) :\n    list PB_output * PB_data * list (name * msg) :=\n    runGenHandler_ignore d (\n      match h, i with\n        | Primary, Request r =>\n          d <- get ;;\n          when (null (queue d)) (send (Backup, BackItUp r)) ;;\n          set_queue (queue d ++ [r])\n        | _, Read =>\n          d <- get ;;\n          write_output (ReadResponse (state d))\n        | _, _ => nop\n      end).\n\n  Lemma PB_input_handler_defn :\n    forall h i d os d' ms,\n      PB_input_handler h i d = (os, d', ms) ->\n      (h = Primary /\\\n       state d' = state d /\\\n       os = [] /\\\n       exists r,\n         i = Request r /\\\n         queue d' = queue d ++ [r] /\\\n         (ms = [] \\/ (ms = [(Backup, BackItUp r)] /\\ queue d = []))) \\/\n      (i = Read /\\\n       d = d' /\\\n       os = [ReadResponse (state d)] /\\\n       ms = []) \\/\n      (h = Backup /\\\n       d = d' /\\\n       ms = [] /\\\n       os = []).\n  Proof using.\n    unfold PB_input_handler. intros.\n    pb_unfold.\n    repeat break_match; repeat find_inversion; intuition eauto.\n    rewrite app_nil_r. simpl. find_apply_lem_hyp null_sound. find_rewrite.\n    simpl. left. intuition. eexists. eauto.\n  Qed.\n\n  Definition PB_net (dst src : name) (m : msg) : PB_data ->\n    list PB_output * PB_data * list (name * msg) :=\n    fun x => runGenHandler_ignore x (\n        match dst, m with\n          | Primary, Ack => d <- get ;;\n                            match queue d with\n                              | [] => nop\n                              | x :: xs => match xs with\n                                             | [] => nop\n                                             | y :: ys =>\n                                               send (Backup, BackItUp y)\n                                           end ;;\n                                               let (os, st') := handler x (state d) in\n                                               write_output (RequestResponse x os) ;;\n                                               set_state st' ;;\n                                               set_queue xs\n                            end\n          | Backup, BackItUp i => d <- get ;;\n                                  set_state (snd (handler i (state d))) ;;\n                                  send (Primary, Ack)\n          | _, _ => nop\n        end).\n\n  Lemma PB_net_defn :\n    forall dst src m d os d' ms,\n      PB_net dst src m d = (os, d', ms) ->\n      (os = [] /\\ d' = d /\\ ms = []) \\/\n      (dst = Primary /\\ m = Ack /\\ (\n         (queue d = [] /\\ os = [] /\\ ms = [] /\\ d' = d) \\/\n         (exists h t, queue d = h :: t /\\\n                      queue d' = t /\\\n                      ((t = [] /\\ ms = []) \\/\n                       (exists y ys,\n                          t = y :: ys /\\\n                          ms = [(Backup, BackItUp y)])) /\\\n                      let (us, st') := handler h (state d) in\n                      os = [RequestResponse h us] /\\\n                      state d' = st'))) \\/\n      (dst = Backup /\\ ms = [(Primary, Ack)] /\\ queue d' = queue d /\\ os = [] /\\\n       (exists i, m = BackItUp i /\\\n                  state d' = snd (handler i (state d)))).\n  Proof using.\n    unfold PB_net. intros.\n    pb_unfold. repeat (first [break_let | break_match]); repeat find_inversion; auto.\n    - right. left. intuition. right. eexists. eexists. intuition eauto.\n      find_rewrite. auto.\n    - right. left. intuition. right. eexists. eexists. intuition eauto.\n      find_rewrite. auto.\n    - right. right. intuition. eexists. eauto.\n  Qed.\n\n  Lemma PB_net_defn' :\n    forall dst src m d os d' ms,\n      PB_net dst src m d = (os, d', ms) ->\n      (os = [] /\\ d' = d /\\ ms = [] /\\\n       ((dst = Primary /\\ exists i, m = BackItUp i) \\/\n        (dst = Backup /\\ m = Ack))) \\/\n      (dst = Primary /\\ m = Ack /\\ (\n         (queue d = [] /\\ os = [] /\\ ms = [] /\\ d' = d) \\/\n         (exists h t, queue d = h :: t /\\\n                      queue d' = t /\\\n                      ((t = [] /\\ ms = []) \\/\n                       (exists y ys,\n                          t = y :: ys /\\\n                          ms = [(Backup, BackItUp y)])) /\\\n                      let (us, st') := handler h (state d) in\n                      os = [RequestResponse h us] /\\\n                      state d' = st'))) \\/\n      (dst = Backup /\\ ms = [(Primary, Ack)] /\\ queue d' = queue d /\\ os = [] /\\\n       (exists i, m = BackItUp i /\\\n                  state d' = snd (handler i (state d)))).\n  Proof using.\n    unfold PB_net. intros.\n    pb_unfold. repeat (first [break_let | break_match]); repeat find_inversion; auto; simpl.\n    - left. intuition. left. eauto.\n    - right. left. intuition.\n    - right. left. intuition. right. eexists. eexists. intuition eauto.\n      find_rewrite. auto.\n    - right. left. intuition. right. eexists. eexists. intuition eauto.\n      find_rewrite. auto.\n    - right. right. intuition. eauto.\n    - left. intuition.\n  Qed.\n\n  Instance PB_base_params : BaseParams :=\n    Build_BaseParams\n      PB_data\n      PB_input\n      PB_output.\n\n  Instance PB_multi_params : MultiParams PB_base_params :=\n    Build_MultiParams\n      PB_base_params\n      msg_eq_dec\n      name_eq_dec\n      all_nodes_all\n      NoDup_all_nodes\n      PB_init\n      PB_net\n      PB_input_handler.\n\n  Definition inputs_1 (tr : list ((@input base_params) * (@output base_params))) :\n      list (@input base_params) :=\n    map (@fst _ _) tr.\n\n  Definition inputs_m (tr : list (name * (@input PB_base_params + list (@output PB_base_params)))) :\n    list (@input base_params) :=\n    filterMap (fun x => match x with\n                          | (Primary, inl (Request i)) => Some i\n                          | _ => None\n                        end)\n              tr.\n\n  Definition outputs_1 (tr : list ((@input base_params) * (@output base_params))) :\n    list (@output base_params) :=\n    map (@snd _ _) tr.\n\n  Fixpoint outputs_m (tr : list (name * (@input PB_base_params + list (@output PB_base_params)))) :\n    list (@output base_params) :=\n    match tr with\n      | [] => []\n      | (Primary, inr l) :: tr' => filterMap (fun x => match x with\n                                                         | RequestResponse i os => Some os\n                                                         | _ => None\n                                                       end) l ++ outputs_m tr'\n      | _ :: tr' => outputs_m tr'\n    end.\n\n  Fixpoint processInputs (d : @data base_params) (l : list (@input base_params)) :\n      (@data base_params * list (@output base_params)) :=\n    match l with\n      | [] => (d, [])\n      | i :: l' => let (os, d') := @handler _ one_node_params i d in\n                   let (d'', os') := processInputs d' l' in\n                   (d'', os :: os')\n    end.\n\n  Definition correspond (st : @data base_params) (sigma : name -> @data PB_base_params) tr_1 tr_m :=\n    let (d, os) := processInputs (state (sigma Primary)) (queue (sigma Primary)) in\n    outputs_m tr_m ++ os = outputs_1 tr_1 /\\\n    d = st.\n\n  Lemma inputs_1_nil_outputs_1_nil :\n    forall tr,\n      inputs_1 tr = [] ->\n      outputs_1 tr = [].\n  Proof using.\n    destruct tr; auto.\n    intros. simpl in *. discriminate.\n  Qed.\n\n  Lemma inputs_m_app :\n    forall l1 l2,\n      inputs_m (l1 ++ l2) = inputs_m l1 ++ inputs_m l2.\n  Proof using.\n    unfold inputs_m.\n    intros.\n    induction l1; simpl; repeat break_match; subst; simpl in *; auto using f_equal.\n  Qed.\n\n  Lemma inputs_m_inr :\n    forall h t tr,\n      inputs_m ((h, inr t) :: tr) = inputs_m tr.\n  Proof using.\n    unfold inputs_m.\n    intros.\n    simpl.\n    repeat break_match; auto; discriminate.\n  Qed.\n\n  Lemma PB_net_out_case :\n    forall dst src m d os d' ms,\n      PB_net dst src m d = (os, d', ms) ->\n      (dst = Backup /\\ os = [] /\\ queue d' = queue d) \\/\n      (dst = Primary /\\ os = [] /\\ d' = d) \\/\n      (dst = Primary /\\ exists h t, queue d = h :: t /\\ queue d' = t /\\\n                                    (let (us, st') := handler h (state d) in\n                                     os = [RequestResponse h us] /\\ state d' = st')).\n  Proof using.\n    intros.\n    find_apply_lem_hyp PB_net_defn.\n    intuition.\n    - destruct dst; subst; intuition.\n    - subst. right. right.\n      intuition. break_exists. intuition eauto.\n  Qed.\n\n  Lemma outputs_m_app :\n    forall tr1 tr2,\n      outputs_m (tr1 ++ tr2) = outputs_m tr1 ++ outputs_m tr2.\n  Proof using.\n    intros. induction tr1; simpl.\n    - auto.\n    - repeat break_match; subst; auto.\n      rewrite app_ass. auto using f_equal.\n  Qed.\n\n  Lemma correspond_preserved_primary_same_no_outputs :\n    forall sigma sigma' st tr_1 tr_m tr_m',\n      correspond st sigma tr_1 tr_m ->\n      sigma' Primary = sigma Primary ->\n      outputs_m tr_m' = [] ->\n      correspond st sigma' tr_1 (tr_m ++ tr_m').\n  Proof using.\n    unfold correspond.\n    intros.\n    rewrite outputs_m_app.\n    repeat find_rewrite.\n    rewrite app_nil_r.\n    auto.\n  Qed.\n\n  Lemma outputs_m_inr_nil :\n    forall h l,\n      outputs_m ((h,inr []) :: l) = outputs_m l.\n  Proof using.\n    destruct h; auto.\n  Qed.\n\n  Lemma outputs_m_inr_nil_singleton :\n    forall h,\n      outputs_m [(h,inr [])] = [].\n  Proof using.\n    intros.\n    apply outputs_m_inr_nil.\n  Qed.\n\n  Lemma outputs_m_inl_read_singleton :\n    forall h,\n      outputs_m [(h, inl Read)] = [].\n  Proof using.\n    destruct h; auto.\n  Qed.\n\n  Lemma outputs_m_inr_primary_singleton :\n    forall h i l,\n      h = Primary ->\n      outputs_m [(h, inr [RequestResponse i l])] = [l].\n  Proof using.\n    unfold outputs_m.\n    intros.\n    break_match; auto; congruence.\n  Qed.\n\n  Hint Extern 4 => congruence.\n\n  Lemma correspond_preserved_primary_apply_entry :\n    forall sigma sigma' st tr_1 tr_m tr_m' i l d h,\n      correspond st sigma tr_1 tr_m ->\n      handler i (state (sigma h)) = (l, state d) ->\n      sigma' Primary = d ->\n      outputs_m tr_m' = [l] ->\n      h = Primary ->\n      queue (sigma h) = i :: queue d ->\n      correspond st sigma' tr_1 (tr_m ++ tr_m').\n  Proof using.\n    unfold correspond.\n    intros.\n    subst.\n    rewrite outputs_m_app.\n    repeat find_rewrite.\n    simpl in *.\n    repeat break_match. repeat find_inversion.\n    find_rewrite. find_inversion.\n    rewrite app_ass. auto.\n  Qed.\n\n  Lemma inputs_m_inr_singleton :\n    forall h l,\n      inputs_m [(h, inr l)] = [].\n  Proof using.\n    intros.\n    rewrite inputs_m_inr.\n    auto.\n  Qed.\n\n  Lemma inputs_m_app_inr_singleton :\n    forall tr h l,\n      inputs_m (tr ++ [(h, inr l)]) = inputs_m tr.\n  Proof using.\n    intros.\n    rewrite inputs_m_app in *.\n    rewrite inputs_m_inr_singleton in *.\n    rewrite app_nil_r in *.\n    auto.\n  Qed.\n\n  Lemma inputs_m_primary_inl :\n    forall i l,\n      inputs_m ((Primary, inl (Request i)) :: l) = i :: inputs_m l.\n  Proof using.\n    auto.\n  Qed.\n\n  Lemma inputs_m_primary_inl_request_singleton :\n    forall i,\n      inputs_m [(Primary, inl (Request i))] = [i].\n  Proof using.\n    auto.\n  Qed.\n\n  Lemma inputs_m_inl_read_singleton :\n    forall h,\n      inputs_m [(h, inl Read)] = [].\n  Proof using.\n    intros. destruct h; auto.\n  Qed.\n\n  Lemma inputs_m_inl_read :\n    forall h l,\n      inputs_m ((h, inl Read) :: l) = inputs_m l.\n  Proof using.\n    intros. destruct h; auto.\n  Qed.\n\n  Lemma list_destruct_last :\n    forall A (l : list A),\n      l = [] \\/ exists l' x, l = l' ++ [x].\n  Proof using.\n    induction l; intuition.\n    - subst. right. exists nil. simpl. eauto.\n    - break_exists. subst. right. eexists. eexists.\n      rewrite app_comm_cons. eauto.\n  Qed.\n\n  Lemma inputs_1_app :\n    forall tr1 tr2,\n      inputs_1 (tr1 ++ tr2) = inputs_1 tr1 ++ inputs_1 tr2.\n  Proof using.\n    unfold inputs_1. auto using map_app.\n  Qed.\n\n  Lemma outputs_1_app :\n    forall tr1 tr2,\n      outputs_1 (tr1 ++ tr2) = outputs_1 tr1 ++ outputs_1 tr2.\n  Proof using.\n    unfold outputs_1. auto using map_app.\n  Qed.\n\n  Lemma processInputs_app :\n    forall l1 l2 d,\n      processInputs d (l1 ++ l2) = let (d', os) := processInputs d l1 in\n                                   let (d'', os') := processInputs d' l2 in\n                                   (d'', os ++ os').\n  Proof using.\n    induction l1; intros; simpl in *; repeat break_match.\n    - auto.\n    - find_inversion. find_higher_order_rewrite.\n      repeat break_match. repeat find_inversion.\n      repeat find_rewrite. find_inversion.\n      auto.\n  Qed.\n\n  Lemma correspond_preserved_snoc :\n    forall sigma tr_1 tr_m st sigma' st' i l,\n      correspond st sigma tr_1 tr_m ->\n      handler i st = (l, st') ->\n      state (sigma' Primary) = state (sigma Primary) ->\n      queue (sigma' Primary) = queue (sigma Primary) ++ [i] ->\n      correspond st' sigma' (tr_1 ++ [(i,l)]) (tr_m ++ [(Primary, inl (Request i))]).\n  Proof using.\n    unfold correspond.\n    intros.\n    rewrite outputs_m_app, outputs_1_app in *.\n    repeat break_match.\n    rewrite app_ass.\n    simpl.\n    repeat find_rewrite.\n    rewrite processInputs_app in *.\n    repeat break_match.\n    repeat tuple_inversion.\n    simpl in *. break_match. tuple_inversion.\n    break_and. subst.\n    find_rewrite. tuple_inversion.\n    rewrite <- app_ass.\n    find_rewrite.\n    auto.\n  Qed.\n\n  Lemma inputs_m_backup_singleton :\n    forall i,\n      inputs_m [(Backup, inl i)] = [].\n  Proof using.\n    auto.\n  Qed.\n\n  Lemma inputs_m_backup :\n    forall i l,\n      inputs_m ((Backup, inl i) :: l) = inputs_m l.\n  Proof using.\n    auto.\n  Qed.\n\n  Lemma step_1_star_no_trace_no_step :\n    forall st st' tr,\n      step_1_star st st' tr ->\n      tr = [] ->\n      st = st'.\n  Proof using.\n    intros.\n    invc H; auto.\n    invc H1. discriminate.\n  Qed.\n\n  Lemma inputs_1_nil_is_nil :\n    forall tr,\n      inputs_1 tr = nil ->\n      tr = nil.\n  Proof using.\n    intros.\n    destruct tr; auto.\n    discriminate.\n  Qed.\n\n  Lemma outputs_m_on_nil :\n    outputs_m [] = [].\n  Proof using.\n    auto.\n  Qed.\n\n  Lemma outputs_1_on_nil :\n    outputs_1 (@nil ((@input base_params) * ((@output base_params)))) = [].\n  Proof using.\n    auto.\n  Qed.\n\n  Lemma inputs_m_on_nil :\n    inputs_m [] = [].\n  Proof using.\n    auto.\n  Qed.\n\n  Lemma processInputs_cons_defn :\n    forall (st : @data base_params) (x : @input base_params) l,\n      processInputs st (x :: l) = let (os, d') := handler x st in\n                                  let (d'', os') := processInputs d' l in\n                                  (d'', os :: os').\n  Proof using.\n    auto.\n  Qed.\n\n  Lemma processInputs_nil_defn :\n    forall st,\n      processInputs st [] = (st, []).\n  Proof using.\n    auto.\n  Qed.\n\n  Lemma outputs_m_inl_singleton :\n    forall h i,\n      outputs_m [(h, inl i)] = [].\n  Proof using.\n    destruct h; auto.\n  Qed.\n\n  Lemma inputs_1_singleton :\n    forall l i,\n      inputs_1 l = [i] ->\n      exists os,\n        l = [(i, os)].\n  Proof using.\n    intros.\n    destruct l; simpl in *.\n    - discriminate.\n    - find_inversion. find_apply_lem_hyp inputs_1_nil_is_nil. subst.\n      destruct p. eauto.\n  Qed.\n\n  Lemma step_1_star_singleton_trace :\n    forall st st' i os,\n      step_1_star st st' [(i, os)] ->\n      step_1 st st' [(i, os)].\n  Proof using.\n    intros.\n    invc H.\n    invc H4.\n    - rewrite app_nil_r in *. subst. auto.\n    - invc H1. invc H. discriminate.\n  Qed.\n\n  Lemma step_1_singleton_inversion :\n    forall st st' i os,\n      step_1 st st' [(i, os)] ->\n      handler i st = (os, st').\n  Proof using.\n    intros.\n    invc H.\n    auto.\n  Qed.\n\n  Lemma inputs_m_on_nil' :\n    inputs_m (@nil (name * (PB_input + (list PB_output)))) = [].\n  Proof using.\n    unfold inputs_m. auto.\n  Qed.\n\n  Lemma correspond_init :\n    correspond init PB_init [] [].\n  Proof using.\n    unfold correspond.\n    break_let.\n    simpl in *. tuple_inversion. auto.\n  Qed.\n\n  Lemma inputs_1_invert_app :\n    forall tr tr' x,\n      inputs_1 tr = tr' ++ [x] ->\n      exists y z,\n        tr = y ++ [z] /\\\n        inputs_1 y = tr' /\\\n        inputs_1 [z] = [x].\n  Proof using.\n    intros tr.\n    pose proof list_destruct_last _ tr.\n    intuition.\n    - subst. destruct tr'; discriminate.\n    - break_exists. subst.\n      rewrite inputs_1_app in *.\n      simpl in *.\n      find_apply_lem_hyp app_inj_tail. intuition eauto.\n  Qed.\n\n  Lemma step_1_snoc_inv :\n    forall st st' tr t,\n      step_1_star st st' (tr ++ [t]) ->\n      exists st2,\n        step_1_star st st2 tr /\\\n        step_1 st2 st' [t].\n  Proof using.\n    intros.\n    find_apply_lem_hyp refl_trans_1n_n1_trace.\n    invc H.\n    - destruct tr; discriminate.\n    - invc H4. exists x'.\n      find_apply_lem_hyp app_inj_tail.\n      intuition. subst.\n      + apply refl_trans_n1_1n_trace. auto.\n      + subst. constructor. auto.\n  Qed.\n\n  Lemma outputs_m_read_response_singleton  :\n    forall h o,\n      outputs_m [(h, inr [ReadResponse o])] = [].\n  Proof using.\n    intros.\n    simpl in *.\n    break_match; auto.\n  Qed.\n\n  Lemma correspond_reachable :\n    forall net tr_m,\n      step_async_star step_async_init net tr_m ->\n      forall st tr_1,\n        step_1_star init st tr_1 ->\n        inputs_1 tr_1 = inputs_m tr_m ->\n        correspond st (nwState net) tr_1 tr_m.\n  Proof using.\n    intros net tr_m H.\n    find_apply_lem_hyp refl_trans_1n_n1_trace.\n    prep_induction H.\n    induction H; intros; subst.\n    - simpl in *. rewrite inputs_m_on_nil' in H3.\n      destruct tr_1; try discriminate.\n      invc H.\n      + simpl. apply correspond_init.\n      + invc H1. discriminate.\n    - repeat concludes.\n      invc H1; simpl in *.\n      + find_apply_lem_hyp PB_net_defn.\n        intuition; subst;\n        try rewrite inputs_m_app in *;\n        try rewrite inputs_m_inr_singleton in *;\n        try rewrite app_nil_r in *;\n        try break_exists;\n        try break_let;\n        try break_and;\n        subst; repeat find_rewrite;\n        eauto using\n              correspond_preserved_primary_same_no_outputs,\n        correspond_preserved_primary_apply_entry,\n        update_nop,\n        update_eq,\n        update_diff,\n        outputs_m_inr_nil_singleton.\n      + find_apply_lem_hyp PB_input_handler_defn.\n        intuition; subst;\n        repeat rewrite snoc_assoc in *;\n        repeat rewrite inputs_m_app in *.\n        * break_exists. break_and. subst.\n          rewrite inputs_m_inr_singleton in *. rewrite app_nil_r in *.\n          rewrite inputs_m_primary_inl_request_singleton in *.\n          find_apply_lem_hyp inputs_1_invert_app. break_exists. break_and.\n          subst. simpl in *. find_inversion. destruct x1.\n          find_apply_lem_hyp step_1_snoc_inv. break_exists. break_and.\n          { eapply correspond_preserved_primary_same_no_outputs; eauto.\n            eapply correspond_preserved_snoc; eauto.\n            - eauto using step_1_singleton_inversion.\n            - rewrite update_eq by auto. auto.\n            - rewrite update_eq by auto. auto.\n          }\n        * rewrite inputs_m_inr_singleton in *. rewrite app_nil_r in *.\n          rewrite inputs_m_inl_read_singleton in *. rewrite app_nil_r in *.\n          eauto using\n                correspond_preserved_primary_same_no_outputs,\n          update_nop,\n          outputs_m_inl_read_singleton,\n          outputs_m_read_response_singleton.\n        * rewrite inputs_m_inr_singleton in *.\n          rewrite inputs_m_backup_singleton in *. repeat rewrite app_nil_r in *.\n          eauto using correspond_preserved_primary_same_no_outputs, update_diff.\n  Qed.\n\n  Lemma correspond_inductive :\n    forall net net' tr_m',\n      step_async net net' tr_m' ->\n      forall st st' tr_m tr_1 tr_1',\n        correspond st (nwState net) tr_1 tr_m ->\n        step_1_star st st' tr_1' ->\n        inputs_1 tr_1' = inputs_m tr_m' ->\n        correspond st' (nwState net') (tr_1 ++ tr_1') (tr_m ++ tr_m').\n  Proof using.\n    intros.\n    invc H; repeat break_let; simpl in *;\n    repeat match goal with\n          | [ H : context [ inputs_m [(_, inr _)] ] |- _ ] =>\n            rewrite inputs_m_inr_singleton in H\n          | [ H : context [ inputs_m [(Primary, inl (Request _))] ] |- _ ] =>\n            rewrite inputs_m_primary_inl_request_singleton in H\n          | [ H : context [ inputs_m ((Primary, inl (Request _)) :: _) ] |- _ ] =>\n            rewrite inputs_m_primary_inl in H\n          | [ H : context [ inputs_m [(_, inl Read)] ] |- _ ] =>\n            rewrite inputs_m_inl_read_singleton in H\n          | [ H : context [ inputs_m ((_, inl Read) :: _) ] |- _ ] =>\n            rewrite inputs_m_inl_read in H\n          | [ H : context [ inputs_1 _ = [] ] |- _ ] =>\n            apply inputs_1_nil_is_nil in H; subst\n          | [ H : context [ inputs_m [_] ] |- _ ] =>\n            rewrite inputs_m_backup_singleton in H\n          | [ H : context [ inputs_m (_ :: _) ] |- _ ] =>\n            rewrite inputs_m_backup in H\n          | [ H : step_1_star _ _ [] |- _ ] =>\n            apply step_1_star_no_trace_no_step in H; [|solve [auto]]; subst\n          | [ H : step_1_star _ _ [_] |- _ ] =>\n            apply step_1_star_singleton_trace in H\n          | [ H : step_1 _ _ [_] |- _ ] =>\n            apply step_1_singleton_inversion in H\n          | [ |- context [ _ ++ [] ] ] =>\n            repeat rewrite app_nil_r\n          | [ H : context [ _ ++ [] ] |- _ ] =>\n            repeat rewrite app_nil_r in *\n          | [ H : context [ [] ++ _ ] |- _ ] =>\n            repeat rewrite app_nil_l in *\n          | [ H : context [PB_net _ _ _ _] |- _ ] => apply PB_net_defn in H\n          | [ H : context [PB_input_handler _ _ _] |- _ ] => apply PB_input_handler_defn in H\n          | [ H : context [inputs_1 _ = [_]] |- _ ] => apply inputs_1_singleton in H\n\n          | [ H : _ /\\ _ |- _ ] => break_and\n          | [ H : exists _, _ |- _ ] => break_exists\n          | [ H : _ \\/ _ |- _ ] => break_or_hyp\n          | _ => repeat break_let; repeat find_rewrite; repeat tuple_inversion; subst; auto\n        end; repeat rewrite snoc_assoc;\n      eauto using\n              correspond_preserved_primary_same_no_outputs,\n              update_nop,\n              update_diff,\n              outputs_m_inr_nil_singleton,\n              outputs_m_inl_read_singleton,\n              outputs_m_read_response_singleton.\n    - eapply correspond_preserved_primary_apply_entry; eauto using update_eq.\n    - eapply correspond_preserved_primary_apply_entry; eauto using update_eq.\n    - eapply correspond_preserved_primary_same_no_outputs; eauto.\n      eapply correspond_preserved_snoc; eauto; rewrite update_eq by auto; repeat find_rewrite; auto.\n    - eapply correspond_preserved_primary_same_no_outputs; eauto.\n      eapply correspond_preserved_snoc; eauto; rewrite update_eq by auto; repeat find_rewrite; auto.\n  Qed.\n\n  Lemma step_async_outputs_m :\n    forall net net' tr,\n      step_async net net' tr ->\n      (inputs_m tr = [] /\\ (outputs_m tr = [] /\\ nwState net Primary = nwState net' Primary)) \\/\n      (inputs_m tr = [] /\\ exists os, outputs_m tr = [os]) \\/\n      (exists i, inputs_m tr = [i]).\n  Proof using.\n    intros.\n    invc H; simpl; break_match; auto;\n    repeat rewrite app_nil_r in *;\n    simpl in *;\n    try find_apply_lem_hyp PB_net_defn;\n    try find_apply_lem_hyp PB_input_handler_defn;\n    intuition; subst.\n    - rewrite inputs_m_inr_singleton.\n      rewrite update_eq by auto.\n      auto.\n    - rewrite inputs_m_inr_singleton.\n      rewrite update_eq by auto.\n      auto.\n    - break_exists. intuition; break_match.\n      + intuition. subst.\n        rewrite inputs_m_inr_singleton. simpl. eauto.\n      + break_exists.  intuition. subst.\n        rewrite inputs_m_inr_singleton. simpl. eauto.\n    - rewrite inputs_m_inr_singleton.\n      rewrite update_diff by auto. auto.\n    - rewrite inputs_m_inr_singleton.\n      rewrite update_diff by auto. auto.\n    - break_exists. intuition; subst; rewrite inputs_m_primary_inl; eauto.\n    - rewrite inputs_m_inl_read. rewrite update_eq by auto. auto.\n    - rewrite inputs_m_inl_read. rewrite update_diff by auto. auto.\n    - rewrite inputs_m_backup.\n      rewrite update_diff by auto. auto.\n  Qed.\n\n  Definition network_invariant (net : @network _ PB_multi_params) : Prop :=\n    (nwPackets net = [] /\\ state (nwState net Primary) = state (nwState net Backup)) \\/\n    (exists i is, nwPackets net = [mkPacket Primary Backup (BackItUp i)] /\\\n               queue (nwState net Primary) = i :: is /\\\n               state (nwState net Primary) = state (nwState net Backup)) \\/\n    (nwPackets net = [mkPacket Backup Primary Ack] /\\\n     exists i is, queue (nwState net Primary) = i :: is /\\\n                  snd (handler i (state (nwState net Primary))) = state (nwState net Backup)).\n\n  Ltac prep := subst; simpl in *; try find_inversion; repeat find_rewrite; simpl in *.\n\n  Ltac workhorse :=\n    repeat (prep;\n            match goal with\n             | [ H : _ /\\ _ |- _ ] => break_and\n             | [ H : exists _, _ |- _ ] => break_exists\n             | [ H : _ ++ _ :: _ = [] |- _ ] => solve [exfalso; eapply app_cons_not_nil; eauto]\n             | [ H : _ ++ _ :: _ = [ _ ] |- _ ] => apply app_cons_singleton_inv in H\n             | [ H : context [ let (_,_) := ?X in _ ] |- _ ] => destruct X eqn:?\n             | [ |- context [ let (_,_) := ?X in _ ] ] => destruct X eqn:?\n             | [ |- context [ update _ (nwState ?net) ?x (nwState ?net ?x) _ ] ] => rewrite update_nop\n             | [ |- context [ update _ _ ?x _ ?x ] ] => rewrite update_eq by auto\n             | [ |- context [ update _ _ ?x _ ?y ] ] => rewrite update_diff by auto\n\n             | [ H : _ \\/ _ |- _ ] => invc H\n           end); prep.\n\n  Lemma network_invariant_inductive :\n    forall net net' tr,\n      step_async net net' tr ->\n      network_invariant net ->\n      network_invariant net'.\n  Proof using.\n    intros.\n    invc H; simpl in *.\n    - unfold network_invariant in *. simpl.\n      find_apply_lem_hyp PB_net_defn'.\n      workhorse; auto; intuition eauto.\n    - unfold network_invariant in *. simpl.\n      find_apply_lem_hyp PB_input_handler_defn.\n      workhorse; auto; intuition eauto.\n  Qed.\n\n  Lemma network_invariant_init :\n    network_invariant step_async_init.\n  Proof using.\n    unfold network_invariant. simpl. auto.\n  Qed.\n\n  Lemma correspond_Prefix :\n    forall st net tr_1 tr_m,\n      correspond st (nwState net) tr_1 tr_m ->\n      Prefix (outputs_m tr_m) (outputs_1 tr_1).\n  Proof using.\n    unfold correspond.\n    intros. break_let. intuition. subst.\n    eauto using app_Prefix.\n  Qed.\n\n  Fixpoint revert_trace (tr : list (name * ((@input PB_base_params) + list (@output PB_base_params)))) :\n    list (@input base_params * (@output base_params)) :=\n    match tr with\n      | [] => []\n      | (h, t) :: tr' => match t with\n                           | inr l => filterMap (fun x => match x with\n                                                            | RequestResponse i os => Some (i, os)\n                                                            | _ => None\n                                                          end) l\n                           | _ => []\n                         end ++ revert_trace tr'\n    end.\n\n  Definition revert_state (net : network) : @data base_params := state (nwState net Primary).\n\n  Lemma revert_state_defn :\n    forall net,\n      revert_state net = state (nwState net Primary).\n  Proof using.\n    unfold revert_state. auto.\n  Qed.\n\n  Lemma inductive_simulation :\n    forall net net' tr,\n      step_async net net' tr ->\n      step_1_star (revert_state net) (revert_state net') (revert_trace tr).\n  Proof using.\n    intros.\n    invc H.\n    - repeat rewrite revert_state_defn. simpl. rewrite app_nil_r.\n      simpl in *.\n      find_apply_lem_hyp PB_net_defn.\n      intuition; subst.\n      + rewrite update_nop. constructor.\n      + rewrite update_nop. constructor.\n      + break_exists. intuition; break_let.\n        * intuition. subst.\n          rewrite <- app_nil_r. econstructor; constructor. repeat find_rewrite.\n          rewrite update_eq by auto. auto.\n        * break_exists. intuition. subst. simpl in *.\n          rewrite <- app_nil_r. econstructor; constructor. repeat find_rewrite.\n          rewrite update_eq by auto. auto.\n      + repeat find_rewrite.\n        rewrite update_diff by auto. constructor.\n    - repeat rewrite revert_state_defn. simpl in *.\n      find_apply_lem_hyp PB_input_handler_defn.\n      intuition; subst.\n      + rewrite update_eq by auto. repeat find_rewrite. constructor.\n      + rewrite update_nop. constructor.\n      + rewrite update_diff by auto. constructor.\n  Qed.\n\n  Lemma revert_trace_app :\n    forall tr1 tr2,\n      revert_trace (tr1 ++ tr2) = revert_trace tr1 ++ revert_trace tr2.\n  Proof using.\n    induction tr1; intros; simpl.\n    - auto.\n    - rewrite IHtr1.\n      repeat break_match; subst.\n      + auto.\n      + rewrite app_ass. auto.\n  Qed.\n\n  Lemma simulation :\n    forall net tr,\n      step_async_star step_async_init net tr ->\n      step_1_star init (revert_state net) (revert_trace tr).\n  Proof using.\n    intros.\n    apply refl_trans_1n_n1_trace in H.\n    prep_induction H.\n    induction H; intros; subst.\n    - unfold step_async_init, revert_state. constructor.\n    - repeat concludes. rewrite revert_trace_app.\n      unfold step_1_star.\n      find_apply_lem_hyp inductive_simulation.\n      simpl in *.\n      unfold step_1_star in *.\n      eauto using refl_trans_1n_trace_trans.\n  Qed.\n\n  Theorem transformer :\n    forall (P : list (input * output) -> Prop),\n      (forall st tr,\n         step_1_star init st tr ->\n         P tr) ->\n      (forall net tr,\n         step_async_star step_async_init net tr ->\n         P (revert_trace tr)).\n  Proof using.\n    intros.\n    find_apply_lem_hyp simulation.\n    eauto.\n  Qed.\n\n  Lemma inputs_m_on_cons :\n    forall t tr,\n      inputs_m (t :: tr) = match t with\n                             | (Primary, inl (Request i)) => i :: inputs_m tr\n                             | _ => inputs_m tr\n                           end.\n  Proof using.\n    unfold inputs_m.\n    intros. simpl.\n    repeat break_match; repeat find_inversion; auto; try discriminate.\n  Qed.\n\n  Definition no_output_at_backup {A} x := forall y, snd x = @inr A _ y ->\n                                                      fst x = Primary \\/\n                                                      match y with\n                                                        | [] => True\n                                                        | [ReadResponse _] => True\n                                                        | _ => False\n                                                      end.\n\n  Definition no_output_at_backup_trace {A} tr := (forall x, In x tr -> @no_output_at_backup A x).\n\n  Lemma NOABT_tail :\n    forall A x y,\n      @no_output_at_backup_trace A (x :: y) ->\n      no_output_at_backup_trace y.\n  Proof using.\n    unfold no_output_at_backup_trace.\n    intros. simpl in *. eauto.\n  Qed.\n\n  Lemma NOABT_contra :\n    forall A l tr,\n      @no_output_at_backup_trace A ((Backup, inr l) :: tr) ->\n      l = [] \\/\n      exists d,\n        l = [ReadResponse d].\n  Proof using.\n    unfold no_output_at_backup_trace, no_output_at_backup.\n    intros. simpl in *.\n    find_insterU.\n    econcludes.\n    find_insterU.\n    simpl in *.\n    econcludes.\n    intuition.\n    repeat break_match; intuition eauto.\n  Qed.\n\n  Lemma outputs_m_revert_trace :\n    forall tr,\n      no_output_at_backup_trace tr ->\n      outputs_m tr = outputs_1 (revert_trace tr).\n  Proof using.\n    unfold outputs_1.\n    induction tr; simpl; intros.\n    - auto.\n    - repeat break_match; subst.\n      + eauto using NOABT_tail.\n      + rewrite IHtr by eauto using NOABT_tail.\n        rewrite map_app. rewrite map_of_filterMap.\n        f_equal. apply filterMap_ext. intros.\n        repeat break_match; auto.\n      + rewrite IHtr by eauto using NOABT_tail. auto.\n      + find_copy_apply_lem_hyp NOABT_tail.\n        find_apply_lem_hyp NOABT_contra. intuition; break_exists;\n        subst; simpl; auto.\n  Qed.\n\n  Lemma NOABT_nil :\n    forall A,\n      @no_output_at_backup_trace A [].\n  Proof using.\n    unfold no_output_at_backup_trace.\n    simpl. intuition.\n  Qed.\n\n  Lemma NOABT_cons :\n    forall A x y,\n      no_output_at_backup x ->\n      @no_output_at_backup_trace A y ->\n      no_output_at_backup_trace (x :: y).\n  Proof using.\n    unfold no_output_at_backup_trace, no_output_at_backup.\n    simpl. intros. intuition; subst; eauto.\n  Qed.\n\n  Lemma NOABT_head :\n    forall A x y,\n      @no_output_at_backup_trace A (x :: y) ->\n      no_output_at_backup x.\n  Proof using.\n    unfold no_output_at_backup_trace, no_output_at_backup.\n    simpl. intuition.\n  Qed.\n\n  Lemma NOABT_app :\n    forall A xs ys,\n      @no_output_at_backup_trace A xs ->\n      no_output_at_backup_trace ys ->\n      no_output_at_backup_trace (xs ++ ys).\n  Proof using.\n    induction xs; intros; simpl in *; auto.\n    eauto using NOABT_cons,\n    NOABT_head,\n    NOABT_tail.\n  Qed.\n\n  Lemma NOABT_singleton_inr_nil :\n    forall A h,\n      @no_output_at_backup_trace A [(h, inr [])].\n  Proof using.\n    unfold no_output_at_backup_trace, no_output_at_backup.\n    simpl. intros. intuition. subst. simpl in *. find_inversion. auto.\n  Qed.\n\n  Lemma NOABT_singleton_inr_read_response :\n    forall A h d,\n      @no_output_at_backup_trace A [(h, inr [ReadResponse d])].\n  Proof using.\n    unfold no_output_at_backup_trace, no_output_at_backup.\n    simpl. intros. intuition. subst. simpl in *. find_inversion. auto.\n  Qed.\n\n  Lemma NOABT_singleton_primary :\n    forall A out,\n      no_output_at_backup_trace [(Primary, @inr A _ out)].\n  Proof using.\n    unfold no_output_at_backup_trace, no_output_at_backup.\n    simpl.\n    intuition.  subst. simpl in *. find_inversion. auto.\n  Qed.\n\n  Lemma NOABT_singleton_inl :\n    forall A h r,\n      @no_output_at_backup_trace A [(h, inl r)].\n  Proof using.\n    unfold no_output_at_backup_trace, no_output_at_backup.\n    simpl. intuition. subst. simpl in *. discriminate.\n  Qed.\n\n  Theorem pbj_NOABT :\n    forall net tr,\n      step_async_star (params:=PB_multi_params) step_async_init net tr ->\n      no_output_at_backup_trace tr.\n  Proof using.\n    intros.\n    find_apply_lem_hyp refl_trans_1n_n1_trace.\n    prep_induction H.\n    induction H; intros.\n    - auto using NOABT_nil.\n    - subst. repeat concludes.\n      apply NOABT_app; auto.\n      invc H1; simpl in *.\n      + find_apply_lem_hyp PB_net_defn'.\n        intuition; subst; repeat find_rewrite;\n        auto using NOABT_singleton_inr_nil, NOABT_singleton_primary.\n      + rewrite cons_cons_app. apply NOABT_app.\n        * auto using NOABT_singleton_inl.\n        * find_apply_lem_hyp PB_input_handler_defn.\n          intuition; break_exists; intuition; subst;\n          auto using NOABT_singleton_inr_nil, NOABT_singleton_inr_read_response.\n  Qed.\n\n  Definition zero_or_one_outputs_per_step {A B C} t :=\n    forall y, @snd A _  t = @inr B _ y -> y = [] \\/ exists z : C, y = [z].\n\n  Definition zero_or_one_outputs_per_step_trace {A B C} tr :=\n    forall x, In x tr -> @zero_or_one_outputs_per_step A B C x.\n\n  Lemma ZOOOPST_nil :\n    forall A B C,\n      @zero_or_one_outputs_per_step_trace A B C [].\n  Proof using.\n    unfold zero_or_one_outputs_per_step_trace, zero_or_one_outputs_per_step.\n    simpl. intuition.\n  Qed.\n\n  Lemma ZOOOPST_head :\n    forall A B C x y,\n      @zero_or_one_outputs_per_step_trace A B C (x :: y) ->\n      zero_or_one_outputs_per_step x.\n  Proof using.\n    unfold zero_or_one_outputs_per_step_trace, zero_or_one_outputs_per_step.\n    simpl.\n    eauto.\n  Qed.\n\n  Lemma ZOOOPST_tail :\n    forall A B C x y,\n      @zero_or_one_outputs_per_step_trace A B C (x :: y) ->\n      zero_or_one_outputs_per_step_trace y.\n  Proof using.\n    unfold zero_or_one_outputs_per_step_trace, zero_or_one_outputs_per_step.\n    simpl.\n    eauto.\n  Qed.\n\n  Lemma ZOOOPST_cons_elim :\n    forall A B C x y,\n      @zero_or_one_outputs_per_step_trace A B C (x :: y) ->\n      zero_or_one_outputs_per_step x /\\\n      zero_or_one_outputs_per_step_trace y.\n  Proof using.\n    intuition eauto using ZOOOPST_head, ZOOOPST_tail.\n  Qed.\n\n  Lemma ZOOOPST_cons_intro :\n    forall A B C x y,\n      @zero_or_one_outputs_per_step A B C x ->\n      zero_or_one_outputs_per_step_trace y ->\n      zero_or_one_outputs_per_step_trace (x :: y).\n  Proof using.\n    unfold zero_or_one_outputs_per_step_trace, zero_or_one_outputs_per_step.\n    simpl.\n    intuition; subst; simpl in *; try discriminate; eauto.\n  Qed.\n\n  Lemma ZOOOPST_app :\n    forall A B C xs ys,\n      @zero_or_one_outputs_per_step_trace A B C xs ->\n      zero_or_one_outputs_per_step_trace ys ->\n      zero_or_one_outputs_per_step_trace (xs ++ ys).\n  Proof using.\n    induction xs; intros.\n    - auto.\n    - eauto using ZOOOPST_cons_intro, ZOOOPST_head, ZOOOPST_tail.\n  Qed.\n\n  Lemma ZOOOPST_singleton_nil :\n    forall A B C h,\n      @zero_or_one_outputs_per_step_trace A B C [(h, inr [])].\n  Proof using.\n    unfold zero_or_one_outputs_per_step_trace, zero_or_one_outputs_per_step.\n    simpl in *.\n    intuition. subst. simpl in *. find_inversion. auto.\n  Qed.\n\n  Lemma ZOOOPST_singleton_singleton :\n    forall A B C h x,\n      @zero_or_one_outputs_per_step_trace A B C [(h, inr [x])].\n  Proof using.\n    unfold zero_or_one_outputs_per_step_trace, zero_or_one_outputs_per_step.\n    simpl. intuition. subst. simpl in *. find_inversion. eauto.\n  Qed.\n\n  Lemma ZOOOPST_singleton_inl :\n    forall A B C h i,\n      @zero_or_one_outputs_per_step_trace A B C [(h, inl i)].\n  Proof using.\n    unfold zero_or_one_outputs_per_step_trace, zero_or_one_outputs_per_step.\n    simpl. intuition. subst. discriminate.\n  Qed.\n\n  Theorem pbj_0_or_1 :\n    forall net tr,\n      step_async_star (params:=PB_multi_params) step_async_init net tr ->\n      zero_or_one_outputs_per_step_trace tr.\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    - auto using ZOOOPST_nil.\n    - repeat concludes.\n      apply ZOOOPST_app; auto.\n      invc H1; simpl in *.\n      + find_apply_lem_hyp PB_net_defn.\n        intuition; subst; auto using ZOOOPST_singleton_nil.\n        break_exists. break_and. break_match.\n        intuition; subst; auto using ZOOOPST_singleton_singleton.\n      + rewrite cons_cons_app.\n        apply ZOOOPST_app.\n        * auto using ZOOOPST_singleton_inl.\n        * find_apply_lem_hyp PB_input_handler_defn; intuition; subst;\n          auto using ZOOOPST_singleton_nil, ZOOOPST_singleton_singleton.\n  Qed.\n\n  Lemma inputs_1_m_revert :\n    forall net tr,\n      step_async_star (params := PB_multi_params) step_async_init net tr ->\n      inputs_m tr = inputs_1 (revert_trace tr) ++ queue (nwState net Primary).\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    - simpl. auto.\n    - repeat concludes.\n      rewrite inputs_m_app.\n      rewrite revert_trace_app.\n      rewrite inputs_1_app.\n      rewrite IHrefl_trans_n1_trace.\n      repeat rewrite app_ass.\n      f_equal.\n      invc H1; simpl in *.\n      + find_apply_lem_hyp PB_net_defn.\n        intuition; subst; simpl in *; rewrite (inputs_m_inr_singleton);\n        rewrite app_nil_r.\n        * rewrite update_nop. auto.\n        * repeat find_rewrite. rewrite update_nop. auto.\n        * break_exists. break_let.\n          { intuition; subst.\n            - repeat find_rewrite. rewrite app_nil_r. simpl. rewrite update_eq by auto. auto.\n            - break_exists. intuition. subst. repeat find_rewrite.\n              simpl. rewrite update_eq by auto. auto.\n          }\n        * break_exists.  intuition. repeat find_rewrite. rewrite update_diff by auto. auto.\n      + find_apply_lem_hyp PB_input_handler_defn.\n        intuition; subst; simpl in *.\n        * break_exists.\n          intuition; subst;\n          rewrite (inputs_m_primary_inl); rewrite update_eq; auto.\n        * rewrite (inputs_m_inl_read).\n          rewrite inputs_m_inr_singleton.\n          rewrite app_nil_r. rewrite update_nop. auto.\n        * rewrite (inputs_m_backup).\n          rewrite inputs_m_inr_singleton.\n          rewrite app_nil_r. rewrite update_nop. auto.\n  Qed.\nEnd PrimaryBackup.\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/PrimaryBackup.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.282948671068109}}
{"text": "(* Sanity theorems for ptt. *)\n\nRequire config.\nRequire Import config_tactics.\n\nRequire Import syntax.\nRequire Import tt.\nRequire Import checking_tactics ptt_admissible.\n\nSection PttSanity.\n\nLocal Instance havePrecondition : config.Precondition := {| config.flagPrecondition := config.Yes |}.\nContext `{configReflection : config.Reflection}.\nContext `{configBinaryProdType : config.BinaryProdType}.\nContext `{configProdEta : config.ProdEta}.\nContext `{configUniverses : config.Universes}.\nContext `{configPropType : config.PropType}.\nContext `{configIdType : config.IdType}.\nContext `{configIdEliminator : config.IdEliminator}.\nContext `{configEmptyType : config.EmptyType}.\nContext `{configUnitType : config.UnitType}.\nContext `{configBoolType : config.BoolType}.\nContext `{configProdType : config.ProdType}.\nContext `{configSyntax : syntax.Syntax}.\n\nAxiom cheating : forall A, A.\n\nDefinition sane_issubst sbs G D :\n  issubst sbs G D -> isctx G * isctx D.\nProof.\n  intro H ; destruct H ; doConfig.\n\n  (* SubstZero *)\n  { split.\n\n    - assumption.\n    - now capply CtxExtend.\n  }\n\n  (* SubstWeak *)\n  { split.\n\n    - now capply CtxExtend.\n    - assumption.\n  }\n\n  (* SubstShift *)\n  { split.\n\n    - magic.\n    - magic.\n  }\n\n  (* SubstId *)\n  { split.\n    - assumption.\n    - assumption.\n  }\n\n  (* SubstComp *)\n  { split.\n    - assumption.\n    - assumption.\n  }\n\n  (* SubstTerminal *)\n  { split.\n    - assumption.\n    - magic.\n  }\n\n  (* SubstCtxConv *)\n  { split.\n    - assumption.\n    - assumption.\n  }\nQed.\n\nDefinition sane_istype G A :\n  istype G A -> isctx G.\nProof.\n  intro H; destruct H ; config assumption.\nQed.\n\nDefinition sane_isterm' G u A :\n  isterm G u A -> istype G A.\nProof.\n  intro H ; destruct H.\n\n  (* TermTyConv *)\n  { config assumption. }\n\n  (* TermCtxConv *)\n  { magic. }\n\n  (* TermSubst *)\n  { magic. }\n\n  (* TermVarZero *)\n  { ceapply TySubst.\n    - now ceapply SubstWeak.\n    - assumption.\n    - magic.\n    - eassumption.\n  }\n\n  (* TermVarSucc *)\n  { magic. }\n\n  (* TermAbs *)\n  { now capply (@TyProd). }\n\n  (* TermApp *)\n  { magic. }\n\n  (* TermRefl *)\n  { now capply TyId. }\n\n  (* TermJ *)\n  { magic. Unshelve. all:strictmagic. }\n\n  (* TermExfalso *)\n  { assumption. }\n\n  (* TermUnit *)\n  { now capply TyUnit. }\n\n  (* TermTrue *)\n  { now capply TyBool. }\n\n  (* TermFalse *)\n  { now capply TyBool. }\n\n  (* TermCond *)\n  { magic. }\n\n  (* TermPair *)\n  { magic. }\n\n  (* TermProjOne *)\n  { magic. }\n\n  (* TermProjTwo *)\n  { magic. }\n\n  (* TermUniProd *)\n  { magic. }\n\n  (* TermUniProdProp *)\n  { magic. }\n\n  (* TermUniId *)\n  { magic. }\n\n  (* TermUniEmpty *)\n  { magic. }\n\n  (* TermUniUnit *)\n  { magic. }\n\n  (* TermUniBool *)\n  { magic. }\n\n  (* TermUniBinaryProd *)\n  { magic. }\n\n  (* TermUniBinaryProdProp *)\n  { magic. }\n\n  (* TermUniUni *)\n  { magic. }\n\n  (* TermUniProp *)\n  { magic. }\nQed.\n\n\nDefinition sane_isterm G u A :\n  isterm G u A -> isctx G * istype G A.\nProof.\n  intro H.\n  pose (K := sane_isterm' G u A H).\n  split ; [now apply (@sane_istype G A) | assumption].\nQed.\n\nDefinition sane_eqtype' G A B :\n  eqtype G A B -> istype G A * istype G B.\nProof.\n  intro H ; destruct H ; doConfig.\n\n  (* EqTyCtxConv *)\n  { split.\n    - magic.\n    - magic.\n  }\n\n  (* EqTyRefl*)\n  { split ; assumption. }\n\n  (* EqTySym *)\n  { split ; assumption. }\n\n  (* EqTyTrans *)\n  { split ; assumption. }\n\n  (* EqTyIdSubst *)\n  { split.\n    - ceapply TySubst.\n      + now capply SubstId.\n      + assumption.\n      + assumption.\n      + eassumption.\n    - assumption.\n  }\n\n  (* EqTySubstComp *)\n  { split.\n    - magic.\n    - magic.\n  }\n\n  (* EqTySubstProd *)\n  { split.\n    - magic.\n    - magic.\n  }\n\n  (* EqTySubstId *)\n  { split.\n    - magic.\n    - magic.\n  }\n\n  (* EqTySubstEmpty *)\n  { split.\n    - magic.\n    - magic.\n  }\n\n  (* EqTySubstUnit *)\n  { split.\n    - magic.\n    - magic.\n  }\n\n  (* EqTySubstBool *)\n  { split.\n    - magic.\n    - magic.\n  }\n\n  (* EqTyExfalso *)\n  { split ; assumption. }\n\n  (* CongProd *)\n  { split.\n    - { now capply TyProd. }\n    - magic.\n  }\n\n  (* CongId *)\n  { split.\n    - { now capply TyId. }\n    - magic.\n  }\n\n  (* CongTySubst *)\n  { split.\n    - magic.\n    - magic.\n  }\n\n  (* CongBinaryProd *)\n  { split.\n    - magic.\n    - magic.\n  }\n\n  (* EqTySubstBinaryProd *)\n  { split.\n    - magic.\n    - magic.\n  }\n\n  (* EqTySubstUni *)\n  { split.\n    - magic.\n    - magic.\n  }\n\n  (* ElProd *)\n  { split.\n    - magic.\n    - magic.\n  }\n\n  (* ElProdProp *)\n  { split.\n    - magic.\n    - magic.\n  }\n\n  (* ElId *)\n  { split.\n    - magic.\n    - magic.\n  }\n\n  (* ElSubst *)\n  { split.\n    - magic.\n    - magic.\n  }\n\n  (* ElEmpty *)\n  { split.\n    - magic.\n    - magic.\n  }\n\n  (* ElUnit *)\n  { split.\n    - magic.\n    - magic.\n  }\n\n  (* ElBool *)\n  { split.\n    - magic.\n    - magic.\n  }\n\n  (* ElBinaryProd *)\n  { split.\n    - magic.\n    - magic.\n  }\n\n  (* ElBinaryProdProp *)\n  { split.\n    - magic.\n    - magic.\n  }\n\n  (* ElUni *)\n  { split.\n    - magic.\n    - magic.\n  }\n\n  (* ElProp *)\n  { split.\n    - magic.\n    - magic.\n  }\n\n  (* CongEl *)\n  { split.\n    - magic.\n    - magic.\n  }\n\nQed.\n\nTheorem sane_eqctx G D :\n  eqctx G D -> isctx G * isctx D.\nProof.\n  intro H ; destruct H ; doConfig.\n\n  (* CtxRefl *)\n  { split.\n    - assumption.\n    - assumption.\n  }\n\n  (* CtxSym *)\n  { split.\n    - assumption.\n    - assumption.\n  }\n\n  (* CtxTrans *)\n  { split.\n    - assumption.\n    - assumption.\n  }\n\n  (* EqCtxEmpty *)\n  { split.\n    - now capply CtxEmpty.\n    - now capply CtxEmpty.\n  }\n\n  (* EqCtxExtend *)\n  { split.\n    - now capply CtxExtend.\n    - magic.\n  }\n\nQed.\n\n\nTheorem sane_eqtype G A B :\n  eqtype G A B -> isctx G * istype G A * istype G B.\nProof.\n  intro H.\n  destruct (sane_eqtype' G A B H).\n  auto using (sane_istype G A).\nQed.\n\nTheorem sane_eqsubst' sbs sbt G D :\n  eqsubst sbs sbt G D -> issubst sbs G D * issubst sbt G D.\nProof.\n  intro H ; destruct H ; doConfig.\n\n  (* SubstRefl *)\n  - { split.\n      - assumption.\n      - assumption.\n    }\n\n  (* SubstSym *)\n  - { split.\n      - assumption.\n      - assumption.\n    }\n\n  (* SubstTrans *)\n  - { split.\n      - assumption.\n      - assumption.\n    }\n\n  (* CongSubstZero *)\n  - { split.\n      - now capply SubstZero.\n      - magic.\n    }\n\n  (* CongSubstWeak *)\n  - { split ; magic. }\n\n  (* CongSubstShift *)\n  - { split ; magic. }\n\n  (* CongSubstComp *)\n  - { split.\n      - magic.\n      - magic.\n    }\n\n  (* EqSubstCtxConv *)\n  - { split.\n      - magic.\n      - magic.\n    }\n\n  (* CompAssoc *)\n  - { split.\n      - magic.\n      - magic.\n    }\n\n  (* WeakNat *)\n  - { split.\n      - magic.\n      - magic.\n    }\n\n  (* WeakZero *)\n  - { split.\n      - magic.\n      - magic.\n    }\n\n  (* ShiftZero *)\n  - { split.\n      - magic.\n      - magic.\n    }\n\n  (* CompShift *)\n  - { split.\n      - magic. Unshelve. all:magic. Unshelve. all:strictmagic.\n      - magic.\n    }\n\n  (* CompIdRight *)\n  - { split.\n      - magic.\n      - assumption.\n    }\n\n  (* CompIdLeft *)\n  - { split.\n      - magic.\n      - assumption.\n    }\nQed.\n\nTheorem sane_eqsubst sbs sbt G D :\n  eqsubst sbs sbt G D -> isctx G * isctx D * issubst sbs G D * issubst sbt G D.\nProof.\n  intro H.\n  destruct (sane_eqsubst' sbs sbt G D H).\n  auto using (sane_issubst sbs G D).\nQed.\n\nTheorem sane_eqterm' G u v A :\n  eqterm G u v A -> isterm G u A * isterm G v A.\nProof.\n  intro H ; destruct H ; doConfig.\n\n  (* EqTyConv *)\n  - { split.\n      - magic.\n      - magic.\n    }\n\n  (* EqCtxConv *)\n  - { split.\n      - magic.\n      - magic.\n    }\n\n  (* EqRefl *)\n  - { split.\n      - { assumption. }\n      - { assumption. }\n    }\n\n  (* EqSym *)\n  - { split.\n      - { assumption. }\n      - { assumption. }\n    }\n\n  (* EqTrans *)\n  - { split.\n      - { assumption. }\n      - { assumption. }\n    }\n\n  (* EqIdSubst *)\n  - { split.\n      - magic.\n      - { assumption. }\n    }\n\n  (* EqSubstComp *)\n  - { split.\n      - magic. Unshelve. all:strictmagic.\n      - magic.\n    }\n\n  (* EqSubstWeak *)\n  - { split.\n      - magic.\n      - { now capply TermVarSucc. }\n    }\n\n\n  (* EqSubstZeroZero *)\n  - { split.\n      - magic.\n      - { assumption. }\n    }\n\n  (* EqSubstZeroSucc *)\n  - { split.\n      - magic.\n        Unshelve. all:strictmagic.\n      - { assumption. }\n    }\n\n  (* EqSubstShiftZero *)\n  - { split.\n      - { ceapply TermTyConv.\n          - ceapply TermSubst.\n            + ceapply SubstShift ; eassumption.\n            + magic.\n            + config constructor.\n              * assumption.\n              * ceapply TySubst ; eassumption.\n            + ceapply TySubst ; try eassumption ; magic.\n            + magic.\n          - magic.\n          - config constructor.\n            + assumption.\n            + ceapply TySubst ; eassumption.\n          - ceapply TySubst.\n            + ceapply SubstShift ; eassumption.\n            + ceapply TySubst ; magic.\n            + config constructor.\n              * assumption.\n              * ceapply TySubst ; eassumption.\n            + magic.\n          - ceapply TySubst.\n            + ceapply SubstWeak.\n              * ceapply TySubst ; eassumption.\n              * assumption.\n            + ceapply TySubst ; eassumption.\n            + config constructor. (* There may be room for maigc improvement here *)\n              * assumption.\n              * ceapply TySubst ; eassumption.\n            + magic.\n        }\n      - { magic. }\n    }\n\n  (* EqSubstShiftSucc *)\n  - { split.\n      - { magic. Unshelve. all:strictmagic. }\n      - { magic. }\n    }\n\n  (* EqSubstAbs *)\n  - { split.\n      - { magic. Unshelve. all:strictmagic. }\n      - { magic. }\n    }\n\n  (* EqSubstApp *)\n  - { split.\n      - { magic. }\n      - { magic. Unshelve. all:strictmagic. }\n    }\n\n  (* EqSubstRefl *)\n  - { split.\n      - { magic. Unshelve. all:strictmagic. }\n      - { magic. }\n    }\n\n  (* EqSubstJ *)\n  - { split.\n      - { magic. Unshelve. all:strictmagic. }\n      - { apply cheating.\n          (* SLOW:\n             magic.\n             Unshelve. all:try okmagic.\n             Unshelve. all:strictmagic.\n         *)\n        }\n    }\n\n  (* EqSubstExfalso *)\n  - { split.\n      - { magic. }\n      - { magic. }\n    }\n\n  (* EqSubstUnit *)\n  - { split.\n      - { magic. }\n      - { magic. }\n    }\n\n  (* EqSubstTrue *)\n  - { split.\n      - { magic. }\n      - { magic. }\n    }\n\n  (* EqSubstFalse *)\n  - { split.\n      - { magic. }\n      - { magic. }\n    }\n\n  (* EqSubstCond *)\n  - { split.\n      - { magic. }\n      - { magic.\n          Unshelve. all:strictmagic.\n        }\n    }\n\n  (* EqTermExfalso *)\n  - { split.\n      - { assumption. }\n      - { assumption. }\n    }\n\n  (* UnitEta *)\n  - { split.\n      - { assumption. }\n      - { magic. }\n    }\n\n  (* EqReflection *)\n  - { split.\n      - { assumption. }\n      - { magic. }\n    }\n\n  (* ProdBeta *)\n  - { split.\n      - { magic. }\n      - { magic. }\n    }\n\n  (* CondTrue *)\n  - { split.\n      - { magic. }\n      - { magic. }\n    }\n\n  (* CondFalse *)\n  - { split.\n      - { magic. }\n      - { magic. }\n    }\n\n  (* ProdEta *)\n  - { split.\n      - { magic. }\n      - { magic. }\n    }\n\n  (* JRefl *)\n  - { split.\n      - { magic. }\n      - { magic. }\n    }\n\n  (* CongAbs *)\n  - { split.\n      - { magic. }\n      - { magic. }\n    }\n\n  (* CongApp *)\n  - { split.\n      - { magic. }\n      - { magic. }\n    }\n\n  (* CongRefl *)\n  - { split.\n      - { magic. }\n      - { magic. }\n    }\n\n  (* CongJ *)\n  - { split.\n      - { magic. }\n      - { apply cheating.\n          (* SLOW:\n          magic.\n          Unshelve. all:magic.\n          Unshelve. all:strictmagic.\n          *)\n        }\n    }\n\n  (* CongCond *)\n  - { split.\n      - { magic. }\n      - { magic. }\n    }\n\n  (* CongTermSubst *)\n  - { split.\n      - { magic. }\n      - { magic. }\n    }\n\n  (* CongPair *)\n  - { split.\n      - magic.\n      - magic.\n    }\n\n  (* CongProjOne *)\n  - { split.\n      - magic.\n      - magic.\n    }\n\n  (* CongProjTwo *)\n  - { split.\n      - magic.\n      - magic.\n    }\n\n  (* EqSubstPair *)\n  - { split.\n      - magic. Unshelve. all:strictmagic.\n      - magic.\n    }\n\n  (* EqSubstProjOne *)\n  - { split.\n      - magic.\n      - magic. Unshelve. all:strictmagic.\n    }\n\n  (* EqSubstProjTwo *)\n  - { split.\n      - magic.\n      - magic. Unshelve. all:strictmagic.\n    }\n\n  (* ProjOnePair *)\n  - { split.\n      - magic.\n      - magic.\n    }\n\n  (* ProjTwoPair *)\n  - { split.\n      - magic.\n      - magic.\n    }\n\n  (* PairEta *)\n  - { split.\n      - magic.\n      - magic.\n    }\n\n  (* EqSubstUniProd *)\n  - { split.\n      - magic.\n      - magic.\n        Unshelve. all: try apply CtxRefl. all:strictmagic.\n    }\n\n  (* EqSubstUniProdProp *)\n  - { split.\n      - magic.\n      - magic.\n        Unshelve. all: try apply CtxRefl. all:strictmagic.\n    }\n\n  (* EqSubstUniId *)\n  - { split.\n      - magic.\n      - magic.\n        Unshelve. all:strictmagic.\n    }\n\n  (* EqSubstUniEmpty *)\n  - { split.\n      - magic.\n      - magic.\n    }\n\n  (* EqSubstUniUnit *)\n  - { split.\n      - magic.\n      - magic.\n    }\n\n  (* EqSubstUniBool *)\n  - { split.\n      - magic.\n      - magic.\n    }\n\n  (* EqSubstUniBinaryProd *)\n  - { split.\n      - magic.\n      - magic.\n    }\n\n  (* EqSubstUniBinaryProdProp *)\n  - { split.\n      - magic.\n      - magic.\n    }\n\n  (* EqSubstUniUni *)\n  - { split.\n      - magic.\n      - magic.\n    }\n\n  (* EqSubstUniProp *)\n  - { split.\n      - magic.\n      - magic.\n    }\n\n  (* CongUniProd *)\n  - { split.\n      - magic.\n      - magic.\n    }\n\n  (* CongUniProdProp *)\n  - { split.\n      - magic.\n      - magic.\n    }\n\n  (* CongUniId *)\n  - { split.\n      - magic.\n      - magic.\n    }\n\n  (* CongUniBinaryProd *)\n  - { split.\n      - magic.\n      - magic.\n    }\n\n  (* CongUniBinaryProdProp *)\n  - { split.\n      - magic.\n      - magic.\n    }\nQed.\n\nTheorem sane_eqterm G u v A :\n  eqterm G u v A -> isctx G * istype G A * isterm G u A * isterm G v A.\nProof.\n  intro H.\n  destruct (sane_eqterm' G u v A H).\n  auto using (@sane_isterm G u A).\nQed.\n\nEnd PttSanity.", "meta": {"author": "TheoWinterhalter", "repo": "formal-type-theory", "sha": "93ac197dfde912d77af9b0f4fd9f7d2422ba7dfc", "save_path": "github-repos/coq/TheoWinterhalter-formal-type-theory", "path": "github-repos/coq/TheoWinterhalter-formal-type-theory/formal-type-theory-93ac197dfde912d77af9b0f4fd9f7d2422ba7dfc/src/ptt_sanity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.28294867106810895}}
{"text": "From iris_logrel.F_mu_ref_conc Require Export fundamental_unary.\nFrom iris.proofmode Require Import tactics.\nFrom iris.program_logic Require Import adequacy.\nFrom iris.base_logic Require Import auth.\n\n\nTheorem soundness Σ `{irisPreG lang Σ, authG Σ heapUR} e τ e' thp σ σ' :\n  (∀ `{heapIG Σ}, log_typed [] e τ) →\n  rtc step ([e], σ) (thp, σ') → e' ∈ thp →\n  is_Some (to_val e') ∨ reducible e' σ'.\nProof.\n  intros Hlog ??. cut (adequate e σ (λ _, True)); first (intros [_ ?]; eauto).\n  eapply (wp_adequacy Σ); iIntros (?) \"Hσ\". rewrite -(empty_env_subst e).\n  iMod (auth_alloc to_heap ownP heapN _ σ with \"[Hσ]\") as (γ) \"[??]\"; auto.\n  - auto using to_heap_valid.\n  - iApply wp_wand_l; iSplitR; [|iApply (Hlog (HeapIG _ _ _ γ))]; eauto.\n    iSplit. by rewrite /heapI_ctx. iApply (@interp_env_nil _ (HeapIG _ _ _ γ)).\nQed.\n\nCorollary type_soundness e τ e' thp σ σ' :\n  [] ⊢ₜ e : τ →\n  rtc step ([e], σ) (thp, σ') → e' ∈ thp →\n  is_Some (to_val e') ∨ reducible e' σ'.\nProof.\n  intros ??. set (Σ := #[irisΣ state ; authΣ heapUR ]).\n  eapply (soundness Σ); eauto using fundamental.\nQed.\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/soundness_unary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.28294054989865397}}
{"text": "(* Using the construction to derive state *)\n\nFrom Coq Require Import Utf8 RelationClasses FunctionalExtensionality.\nFrom PDM Require Import util structures guarded PURE PDM DM4Free.\n\nSet Default Goal Selector \"!\".\nSet Printing Projections.\nSet Universe Polymorphism.\nUnset Universe Minimization ToSet.\n\nSection State.\n\n  Context (state : Type).\n\n  Definition StT (M : Type → Type) (A : Type) :=\n    state → M (state * A)%type.\n\n  Instance MonadTransformer_StT : MonadTransformer StT := {|\n    liftᵀ M hM A c := λ s₀, bind c (λ x, ret (s₀, x)) ;\n    mapᵀ M N f hM hN hf A c := λ s₀, f _ (c s₀)\n  |}.\n\n  Instance MonadTransformerLaws_StT : MonadTransformerLaws StT.\n  Proof.\n    unshelve econstructor.\n    - intros M hM.\n      refine {|\n        ret A x := λ s₀, ret (s₀, x) ;\n        bind A B c f := λ s₀, bind (c s₀) (λ '(s₁, x), f x s₁)\n      |}.\n    - intros M hM lM A x.\n      simpl. extensionality s₀.\n      rewrite structures.left_id. reflexivity.\n    - intros M hM lM A B c f.\n      simpl. extensionality s₀.\n      rewrite !structures.assoc. f_equal.\n      extensionality x. rewrite structures.left_id. reflexivity.\n    - intros M N f hM hN hf.\n      constructor.\n      + intros A x. simpl.\n        extensionality s₀.\n        apply morph_ret.\n      + intros A B c k.\n        simpl. extensionality s₀.\n        rewrite morph_bind. apply (f_equal (bind _)).\n        apply functional_extensionality. intros [s₁ x].\n        reflexivity.\n    - intros M N f hM hN hf A c.\n      simpl. extensionality s₀.\n      rewrite morph_bind. apply (f_equal (bind _)).\n      extensionality x. apply morph_ret.\n  Defined.\n\n  #[refine] Instance Order_W : Order (W StT) := {|\n    wle A (w w' : W StT A) := ∀ post s, val (w' s) post → val (w s) post\n  |}.\n  Proof.\n    intros A x y z h1 h2.\n    intros post s h.\n    apply h1. apply h2. assumption.\n  Defined.\n\n  Instance MonoSpec_W : MonoSpec (W StT).\n  Proof.\n    constructor.\n    intros A B w w' wf wf' hw hwf.\n    intros post s h.\n    simpl. apply hw.\n    simpl in h.\n    destruct w' as [w'' hm].\n    eapply hm. 2: exact h.\n    intros [s₁ x]. apply hwf.\n  Qed.\n\n  Lemma wle_liftᵀ :\n    ∀ A (w w' : pure_wp A), w ≤ᵂ w' → liftᵀ w ≤ᵂ liftᵀ w'.\n  Proof.\n    intros A w w' hw.\n    simpl. intros post s h.\n    apply hw. assumption.\n  Qed.\n\n  Instance Reflexive_wle : ∀ A, Reflexive (wle (W := W StT) (A := A)).\n  Proof.\n    intros A x. intros post s. auto.\n  Qed.\n\n  Definition D A w : Type :=\n    DM4Free.D StT Order_W A w.\n\n  Instance DijkstraMonad_D : DijkstraMonad (Word := Order_W) D := _.\n\n  Definition liftᴾ [A w] (f : PURE A w) : D A (liftᵂ StT _ w) :=\n    DM4Free.liftᴾ StT _ _ wle_liftᵀ _ w f.\n\nEnd State.", "meta": {"author": "TheoWinterhalter", "repo": "pdm4all", "sha": "570868f2e395bada6e3dc0462d7e9af065289461", "save_path": "github-repos/coq/TheoWinterhalter-pdm4all", "path": "github-repos/coq/TheoWinterhalter-pdm4all/pdm4all-570868f2e395bada6e3dc0462d7e9af065289461/theories/DM4FreeState.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.28286725591875683}}
{"text": "From iris.base_logic.lib Require Export invariants.\nFrom iris.algebra Require Export auth.\nFrom iris.algebra Require Import gmap.\nFrom iris.proofmode Require Import tactics.\nSet Default Proof Using \"Type\".\nImport uPred.\n\n(* The CMRA we need. *)\nClass authG Σ (A : ucmraT) := AuthG {\n  auth_inG :> inG Σ (authR A);\n  auth_cmra_discrete :> CmraDiscrete A;\n}.\nDefinition authΣ (A : ucmraT) : gFunctors := #[ GFunctor (authR A) ].\n\nInstance subG_authΣ Σ A : subG (authΣ A) Σ → CmraDiscrete A → authG Σ A.\nProof. solve_inG. Qed.\n\nSection definitions.\n  Context `{invG Σ, authG Σ A} {T : Type} (γ : gname).\n\n  Definition auth_own (a : A) : iProp Σ :=\n    own γ (◯ a).\n  Definition auth_inv (f : T → A) (φ : T → iProp Σ) : iProp Σ :=\n    (∃ t, own γ (● f t) ∗ φ t)%I.\n  Definition auth_ctx (N : namespace) (f : T → A) (φ : T → iProp Σ) : iProp Σ :=\n    inv N (auth_inv f φ).\n\n  Global Instance auth_own_ne : NonExpansive auth_own.\n  Proof. solve_proper. Qed.\n  Global Instance auth_own_proper : Proper ((≡) ==> (⊣⊢)) auth_own.\n  Proof. solve_proper. Qed.\n  Global Instance auth_own_timeless a : Timeless (auth_own a).\n  Proof. apply _. Qed.\n  Global Instance auth_own_core_id a : CoreId a → Persistent (auth_own a).\n  Proof. apply _. Qed.\n\n  Global Instance auth_inv_ne n :\n    Proper (pointwise_relation T (dist n) ==>\n            pointwise_relation T (dist n) ==> dist n) auth_inv.\n  Proof. solve_proper. Qed.\n  Global Instance auth_inv_proper :\n    Proper (pointwise_relation T (≡) ==>\n            pointwise_relation T (⊣⊢) ==> (⊣⊢)) auth_inv.\n  Proof. solve_proper. Qed.\n  Global Instance auth_ctx_ne N n :\n    Proper (pointwise_relation T (dist n) ==>\n            pointwise_relation T (dist n) ==> dist n) (auth_ctx N).\n  Proof. solve_proper. Qed.\n  Global Instance auth_ctx_proper N :\n    Proper (pointwise_relation T (≡) ==>\n            pointwise_relation T (⊣⊢) ==> (⊣⊢)) (auth_ctx N).\n  Proof. solve_proper. Qed.\n  Global Instance auth_ctx_persistent N f φ : Persistent (auth_ctx N f φ).\n  Proof. apply _. Qed.\nEnd definitions.\n\nTypeclasses Opaque auth_own auth_inv auth_ctx.\nInstance: Params (@auth_own) 4.\nInstance: Params (@auth_inv) 5.\nInstance: Params (@auth_ctx) 7.\n\nSection auth.\n  Context `{invG Σ, authG Σ A}.\n  Context {T : Type} `{!Inhabited T}.\n  Context (f : T → A) (φ : T → iProp Σ).\n  Implicit Types N : namespace.\n  Implicit Types P Q R : iProp Σ.\n  Implicit Types a b : A.\n  Implicit Types t u : T.\n  Implicit Types γ : gname.\n\n  Lemma auth_own_op γ a b : auth_own γ (a ⋅ b) ⊣⊢ auth_own γ a ∗ auth_own γ b.\n  Proof. by rewrite /auth_own -own_op auth_frag_op. Qed.\n\n(*\n  Global Instance from_and_auth_own γ a b1 b2 :\n    IsOp a b1 b2 →\n    FromAnd false (auth_own γ a) (auth_own γ b1) (auth_own γ b2) | 90.\n  Proof. rewrite /IsOp /FromAnd=> ->. by rewrite auth_own_op. Qed.\n  Global Instance from_and_auth_own_persistent γ a b1 b2 :\n    IsOp a b1 b2 → Or (CoreId b1) (CoreId b2) →\n    FromAnd true (auth_own γ a) (auth_own γ b1) (auth_own γ b2) | 91.\n  Proof.\n    intros ? Hper; apply mk_from_and_persistent; [destruct Hper; apply _|].\n    by rewrite -auth_own_op -is_op.\n  Qed.\n\n  Global Instance into_and_auth_own p γ a b1 b2 :\n    IsOp a b1 b2 →\n    IntoAnd p (auth_own γ a) (auth_own γ b1) (auth_own γ b2) | 90.\n  Proof. intros. apply mk_into_and_sep. by rewrite (is_op a) auth_own_op. Qed.\n*)\n\n  Lemma auth_own_mono γ a b : a ≼ b → auth_own γ b ⊢ auth_own γ a.\n  Proof. intros [? ->]. by rewrite auth_own_op sep_elim_l. Qed.\n  Lemma auth_own_valid γ a : auth_own γ a ⊢ ✓ a.\n  Proof. by rewrite /auth_own own_valid auth_validI. Qed.\n  Global Instance auth_own_sep_homomorphism γ :\n    WeakMonoidHomomorphism op uPred_sep (≡) (auth_own γ).\n  Proof. split; try apply _. apply auth_own_op. Qed.\n\n  Global Instance own_mono' γ : Proper (flip (≼) ==> (⊢)) (auth_own γ).\n  Proof. intros a1 a2. apply auth_own_mono. Qed.\n\n  Lemma auth_alloc_strong N E t (G : gset gname) :\n    ✓ (f t) → ▷ φ t ={E}=∗ ∃ γ, ⌜γ ∉ G⌝ ∧ auth_ctx γ N f φ ∧ auth_own γ (f t).\n  Proof.\n    iIntros (?) \"Hφ\". rewrite /auth_own /auth_ctx.\n    iMod (own_alloc_strong (Auth (Excl' (f t)) (f t)) G) as (γ) \"[% Hγ]\"; first done.\n    iRevert \"Hγ\"; rewrite auth_both_op; iIntros \"[Hγ Hγ']\".\n    iMod (inv_alloc N _ (auth_inv γ f φ) with \"[-Hγ']\") as \"#?\".\n    { iNext. rewrite /auth_inv. iExists t. by iFrame. }\n    eauto.\n  Qed.\n\n  Lemma auth_alloc N E t :\n    ✓ (f t) → ▷ φ t ={E}=∗ ∃ γ, auth_ctx γ N f φ ∧ auth_own γ (f t).\n  Proof.\n    iIntros (?) \"Hφ\".\n    iMod (auth_alloc_strong N E t ∅ with \"Hφ\") as (γ) \"[_ ?]\"; eauto.\n  Qed.\n\n  Lemma auth_empty γ : (|==> auth_own γ ε)%I.\n  Proof. by rewrite /auth_own -own_unit. Qed.\n\n  Lemma auth_acc E γ a :\n    ▷ auth_inv γ f φ ∗ auth_own γ a ={E}=∗ ∃ t,\n      ⌜a ≼ f t⌝ ∗ ▷ φ t ∗ ∀ u b,\n      ⌜(f t, a) ~l~> (f u, b)⌝ ∗ ▷ φ u ={E}=∗ ▷ auth_inv γ f φ ∗ auth_own γ b.\n  Proof using Type*.\n    iIntros \"[Hinv Hγf]\". rewrite /auth_inv /auth_own.\n    iDestruct \"Hinv\" as (t) \"[>Hγa Hφ]\".\n    iModIntro. iExists t.\n    iDestruct (own_valid_2 with \"Hγa Hγf\") as % [? ?]%auth_valid_discrete_2.\n    iSplit; first done. iFrame. iIntros (u b) \"[% Hφ]\".\n    iMod (own_update_2 with \"Hγa Hγf\") as \"[Hγa Hγf]\".\n    { eapply auth_update; eassumption. }\n    iModIntro. iFrame. iExists u. iFrame.\n  Qed.\n\n  Lemma auth_open E N γ a :\n    ↑N ⊆ E →\n    auth_ctx γ N f φ ∗ auth_own γ a ={E,E∖↑N}=∗ ∃ t,\n      ⌜a ≼ f t⌝ ∗ ▷ φ t ∗ ∀ u b,\n      ⌜(f t, a) ~l~> (f u, b)⌝ ∗ ▷ φ u ={E∖↑N,E}=∗ auth_own γ b.\n  Proof using Type*.\n    iIntros (?) \"[#? Hγf]\". rewrite /auth_ctx. iInv N as \"Hinv\" \"Hclose\".\n    (* The following is essentially a very trivial composition of the accessors\n       [auth_acc] and [inv_open] -- but since we don't have any good support\n       for that currently, this gets more tedious than it should, with us having\n       to unpack and repack various proofs.\n       TODO: Make this mostly automatic, by supporting \"opening accessors\n       around accessors\". *)\n    iMod (auth_acc with \"[$Hinv $Hγf]\") as (t) \"(?&?&HclAuth)\".\n    iModIntro. iExists t. iFrame. iIntros (u b) \"H\".\n    iMod (\"HclAuth\" $! u b with \"H\") as \"(Hinv & ?)\". by iMod (\"Hclose\" with \"Hinv\").\n  Qed.\nEnd auth.\n\nArguments auth_open {_ _ _} [_] {_} [_] _ _ _ _ _ _ _.\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/auth.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.49609382947091957, "lm_q1q2_score": 0.2827003840742062}}
{"text": "\nRequire Export Iron.Language.SystemF2Effect.Step.Frame.\nRequire Export Iron.Language.SystemF2Effect.Store.Bind.\n\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\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/Store/LiveE.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.2827003840742062}}
{"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 rules_useful.\nRequire Export per_props_equality.\nRequire Export per_props_union.\nRequire Export subst_tacs.\n\n\n(** printing |- $\\vdash$ *)\n(** printing ->  $\\rightarrow$ *)\n\n\nDefinition rule_equality_to_extract {o}\n           (T t : @NTerm o)\n           (H : barehypotheses) :=\n    mk_rule\n      (mk_baresequent H (mk_conclax (mk_member t T)))\n      [ mk_baresequent H (mk_concl T t) ]\n      [].\n\nLemma rule_equality_to_extract_true {p} :\n  forall lib\n         (T t : NTerm)\n         (H : @barehypotheses p),\n    rule_true lib (rule_equality_to_extract T t H).\nProof.\n  unfold rule_equality_to_extract, 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  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  lsubst_tac.\n\n  allrw @tequality_mkc_member_sp.\n  allrw @equality_in_member.\n\n  dands; auto; spcast;\n  try (apply computes_to_valc_refl; eauto 3 with slow).\n  apply equality_refl in h1; auto.\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/rules_equality2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.2827003840742062}}
{"text": "Require Import Prog.\nRequire Import Pred.\nRequire Import Hoare.\nRequire Import Word.\nRequire Import SepAuto.\nRequire Import BasicProg.\nRequire Import Log.\nRequire Import Bool.\nRequire Import GenSep.\nRequire Import Idempotent.\nRequire Import FSLayout.\nRequire Import Cache.\nRequire Import FS.\n\nSet Implicit Arguments.\n\nDefinition inc_two T s0 s1 rx : prog T :=\n  v0 <- Read s0 ;\n  Write s0 (v0 ^+ $1) ;;\n  v1 <- Read s1 ;\n  Write s1 (v1 ^+ $1) ;;\n  rx tt.\n\nTheorem inc_two_ok: forall s0 s1,\n  {< v0 v1,\n  PRE    s0 |~> v0 * s1 |~> v1\n  POST RET:r\n         s0 |~> (v0 ^+ $1) * s1 |~> (v1 ^+ $1)\n  CRASH  s0 |~> v0 * s1 |~> v1 \\/\n         s0 |~> (v0 ^+ $1) * s1 |~> v1 \\/\n         s0 |~> (v0 ^+ $1) * s1 |~> (v1 ^+ $1)\n  >} inc_two s0 s1.\nProof.\n  unfold inc_two.\n  hoare.\nQed.\n\nDefinition log_inc_two_body T xp s0 s1 mscs rx : prog T :=\n  let^ (mscs, v0) <- LOG.read xp s0 mscs;\n  mscs <- LOG.write xp s0 (v0 ^+ $1) mscs;\n  let^ (mscs, v1) <- LOG.read xp s1 mscs;\n  mscs <- LOG.write xp s1 (v1 ^+ $1) mscs;\n  rx mscs.\n\nTheorem log_inc_two_body_ok: forall xp s0 s1 mscs,\n  {< mbase m v0 v1 F Fm,\n  PRE             LOG.rep xp Fm (ActiveTxn mbase m) mscs * \n                  [[ (s0 |-> v0 * s1 |-> v1 * F)%pred (list2mem m)]]\n  POST RET:mscs   exists m', LOG.rep xp Fm (ActiveTxn mbase m') mscs *\n                  [[ (s0 |-> (v0 ^+ $1) * s1 |-> (v1 ^+ $1) * F)%pred (list2mem m') ]]\n  CRASH           LOG.would_recover_old xp Fm mbase\n  >} log_inc_two_body xp s0 s1 mscs.\nProof.\n  unfold log_inc_two_body.\n  hoare; apply LOG.activetxn_would_recover_old.\nQed.\n\nHint Extern 1 ({{_}} progseq (log_inc_two_body _ _ _ _) _) => apply log_inc_two_body_ok : prog.\n\nDefinition log_inc_two T xp s0 s1 cs rx : prog T :=\n  mscs <- LOG.begin xp cs;\n  mscs <- log_inc_two_body xp s0 s1 mscs;\n  let^ (mscs, ok) <- LOG.commit xp mscs;\n  If (bool_dec ok true) {\n    rx ^(mscs, ok)\n  } else {\n    rx ^(mscs, false)\n  }.\n\nTheorem log_inc_two_ok: forall xp s0 s1 mscs,\n  {< mbase v0 v1 F Fm,\n  PRE             LOG.rep xp Fm (NoTransaction mbase) mscs * \n                  [[ (s0 |-> v0 * s1 |-> v1 * F)%pred (list2mem mbase)]]\n  POST RET:^(mscs, r)\n                  [[ r = false ]] * LOG.rep xp Fm (NoTransaction mbase) mscs \\/\n                  [[ r = true ]] * exists m', LOG.rep xp Fm (NoTransaction m') mscs *\n                  [[ (s0 |-> (v0 ^+ $1) * s1 |-> (v1 ^+ $1) * F)%pred (list2mem m') ]]\n  CRASH           LOG.would_recover_old xp Fm mbase \\/\n                  exists m', LOG.would_recover_either xp Fm mbase m' *\n                  [[ (s0 |-> (v0 ^+ $1) * s1 |-> (v1 ^+ $1) * F)%pred (list2mem m') ]]\n  >} log_inc_two xp s0 s1 mscs.\nProof.\n  unfold log_inc_two.\n  hoare.\n  rewrite LOG.notxn_would_recover_old.\n  cancel.\n  rewrite LOG.activetxn_would_recover_old.\n  cancel.\nQed.\n\nHint Extern 1 ({{_}} progseq (log_inc_two _ _ _ _) _) => apply log_inc_two_ok : prog.\n\nHint Rewrite crash_xform_sep_star_dist crash_xform_or_dist crash_xform_exists_comm : crash_xform.\n\nDefinition i2 xp s0 s1 T := @log_inc_two T xp s0 s1.\n\nTheorem log_inc_two_recover_ok: forall xp s0 s1 mscs,\n  {<< v0 v1 F Fm mbase,\n  PRE\n    LOG.rep xp Fm (NoTransaction mbase) mscs *\n    [[ (s0 |-> v0 * s1 |-> v1 * F)%pred (list2mem mbase)]]\n  POST RET:^(mscs, r)\n    [[ r = false ]] * LOG.rep xp Fm (NoTransaction mbase) mscs \\/\n    [[ r = true ]] * exists m', LOG.rep xp Fm (NoTransaction m') mscs *\n    [[ (s0 |-> (v0 ^+ $1) * s1 |-> (v1 ^+ $1) * F)%pred (list2mem m') ]]\n  REC RET:^(mscs, xp)\n    LOG.rep xp Fm (NoTransaction mbase) mscs \\/\n    exists m', LOG.rep xp Fm (NoTransaction m') mscs *\n               [[ (s0 |-> (v0 ^+ $1) * s1 |-> (v1 ^+ $1) * F)%pred (list2mem m') ]]\n  >>} log_inc_two xp s0 s1 mscs >> LOG.recover.\nProof.\n  intros.\n  unfold forall_helper at 1 2; intros v0 v1 F.\n\n  eapply pimpl_ok3.\n  eapply corr3_from_corr2_rx; eauto with prog.\n  \n  eapply (LOG.recover_corr2_to_corr3 (i2 xp s0 s1)).\n  unfold i2.\n  intros.\n  eapply pimpl_ok2.\n  eapply log_inc_two_ok.\n  cancel.\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/ExampleMemLog.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.28270038407420617}}
{"text": "Lemma LP4P13 : forall P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13 P14 P15 ,\nrk(P3 :: P8 :: P10 ::  nil) = 2 -> rk(P6 :: P11 :: P12 ::  nil) = 2 -> rk(P1 :: P2 :: P3 :: P13 ::  nil) = 2 ->\nrk(P4 :: P5 :: P6 :: P13 ::  nil) = 2 -> rk(P3 :: P4 :: P5 :: P6 :: P8 :: P10 :: P13 ::  nil) = 4 -> rk(P1 :: P2 :: P3 :: P6 :: P11 :: P12 :: P13 ::  nil) = 4 ->\nrk(P4 :: P7 :: P8 :: P14 ::  nil) = 2 -> rk(P1 :: P9 :: P11 :: P14 ::  nil) = 2 -> rk(P1 :: P3 :: P8 :: P9 :: P10 :: P11 :: P14 ::  nil) = 4 ->\nrk(P4 :: P6 :: P7 :: P8 :: P11 :: P12 :: P14 ::  nil) = 4 -> rk(P1 :: P2 :: P3 :: P4 :: P7 :: P8 :: P13 :: P14 ::  nil) = 4 -> rk(P1 :: P4 :: P5 :: P6 :: P9 :: P11 :: P13 :: P14 ::  nil) = 4 ->\nrk(P5 :: P9 :: P10 :: P15 ::  nil) = 2 -> rk(P2 :: P7 :: P12 :: P15 ::  nil) = 2 -> rk(P2 :: P3 :: P7 :: P8 :: P10 :: P12 :: P15 ::  nil) = 4 ->\nrk(P5 :: P6 :: P9 :: P10 :: P11 :: P12 :: P15 ::  nil) = 4 -> rk(P1 :: P2 :: P3 :: P5 :: P9 :: P10 :: P13 :: P15 ::  nil) = 4 -> rk(P2 :: P4 :: P5 :: P6 :: P7 :: P12 :: P13 :: P15 ::  nil) = 4 ->\nrk(P4 :: P5 :: P7 :: P8 :: P9 :: P10 :: P14 :: P15 ::  nil) = 4 -> rk(P1 :: P2 :: P7 :: P9 :: P11 :: P12 :: P14 :: P15 ::  nil) = 4 -> rk(P4 :: P13 ::  nil) = 2.\nProof.\n\nintros P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13 P14 P15 \nHP3P8P10eq HP6P11P12eq HP1P2P3P13eq HP4P5P6P13eq HP3P4P5P6P8P10P13eq HP1P2P3P6P11P12P13eq HP4P7P8P14eq HP1P9P11P14eq HP1P3P8P9P10P11P14eq HP4P6P7P8P11P12P14eq\nHP1P2P3P4P7P8P13P14eq HP1P4P5P6P9P11P13P14eq HP5P9P10P15eq HP2P7P12P15eq HP2P3P7P8P10P12P15eq HP5P6P9P10P11P12P15eq HP1P2P3P5P9P10P13P15eq HP2P4P5P6P7P12P13P15eq HP4P5P7P8P9P10P14P15eq HP1P2P7P9P11P12P14P15eq\n.\n\nassert(HP4P7P8P13P14M3 : rk(P4 :: P7 :: P8 :: P13 :: P14 :: nil) <= 3).\n{\n\ttry assert(HP13eq : rk(P13 :: nil) = 1) by (apply LP13 with (P1 := P1) (P2 := P2) (P3 := P3) (P4 := P4) (P5 := P5) (P6 := P6) (P7 := P7) (P8 := P8) (P9 := P9) (P10 := P10) (P11 := P11) (P12 := P12) (P13 := P13) (P14 := P14) (P15 := P15) ;try assumption).\n\tassert(HP13Mtmp : rk(P13 :: nil) <= 1) by (solve_hyps_max HP13eq HP13M1).\n\ttry assert(HP4P7P8P14eq : rk(P4 :: P7 :: P8 :: P14 :: nil) = 2) by (apply LP4P7P8P14 with (P1 := P1) (P2 := P2) (P3 := P3) (P4 := P4) (P5 := P5) (P6 := P6) (P7 := P7) (P8 := P8) (P9 := P9) (P10 := P10) (P11 := P11) (P12 := P12) (P13 := P13) (P14 := P14) (P15 := P15) ;try assumption).\n\tassert(HP4P7P8P14Mtmp : rk(P4 :: P7 :: P8 :: P14 :: nil) <= 2) by (solve_hyps_max HP4P7P8P14eq HP4P7P8P14M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P13 :: nil) (P4 :: P7 :: P8 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P4 :: P7 :: P8 :: P13 :: P14 :: nil) (P13 :: P4 :: P7 :: P8 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P13 :: P4 :: P7 :: P8 :: P14 :: nil) ((P13 :: nil) ++ (P4 :: P7 :: P8 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P13 :: nil) (P4 :: P7 :: P8 :: P14 :: nil) (nil) 1 2 0 HP13Mtmp HP4P7P8P14Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n\nassert(HP4P7P8P13P14m3 : rk(P4 :: P7 :: P8 :: P13 :: P14 :: nil) >= 3).\n{\n\ttry assert(HP1P2P3P13eq : rk(P1 :: P2 :: P3 :: P13 :: nil) = 2) by (apply LP1P2P3P13 with (P1 := P1) (P2 := P2) (P3 := P3) (P4 := P4) (P5 := P5) (P6 := P6) (P7 := P7) (P8 := P8) (P9 := P9) (P10 := P10) (P11 := P11) (P12 := P12) (P13 := P13) (P14 := P14) (P15 := P15) ;try assumption).\n\tassert(HP1P2P3P13Mtmp : rk(P1 :: P2 :: P3 :: P13 :: nil) <= 2) by (solve_hyps_max HP1P2P3P13eq HP1P2P3P13M2).\n\ttry assert(HP1P2P3P4P7P8P13P14eq : rk(P1 :: P2 :: P3 :: P4 :: P7 :: P8 :: P13 :: P14 :: nil) = 4) by (apply LP1P2P3P4P7P8P13P14 with (P1 := P1) (P2 := P2) (P3 := P3) (P4 := P4) (P5 := P5) (P6 := P6) (P7 := P7) (P8 := P8) (P9 := P9) (P10 := P10) (P11 := P11) (P12 := P12) (P13 := P13) (P14 := P14) (P15 := P15) ;try assumption).\n\tassert(HP1P2P3P4P7P8P13P14mtmp : rk(P1 :: P2 :: P3 :: P4 :: P7 :: P8 :: P13 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P2P3P4P7P8P13P14eq HP1P2P3P4P7P8P13P14m4).\n\ttry assert(HP13eq : rk(P13 :: nil) = 1) by (apply LP13 with (P1 := P1) (P2 := P2) (P3 := P3) (P4 := P4) (P5 := P5) (P6 := P6) (P7 := P7) (P8 := P8) (P9 := P9) (P10 := P10) (P11 := P11) (P12 := P12) (P13 := P13) (P14 := P14) (P15 := P15) ;try assumption).\n\tassert(HP13mtmp : rk(P13 :: nil) >= 1) by (solve_hyps_min HP13eq HP13m1).\n\tassert(Hincl : incl (P13 :: nil) (list_inter (P1 :: P2 :: P3 :: P13 :: nil) (P4 :: P7 :: P8 :: P13 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P4 :: P7 :: P8 :: P13 :: P14 :: nil) (P1 :: P2 :: P3 :: P13 :: P4 :: P7 :: P8 :: P13 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P3 :: P13 :: P4 :: P7 :: P8 :: P13 :: P14 :: nil) ((P1 :: P2 :: P3 :: P13 :: nil) ++ (P4 :: P7 :: P8 :: P13 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P3P4P7P8P13P14mtmp;try rewrite HT2 in HP1P2P3P4P7P8P13P14mtmp.\n\tassert(HT := rule_4 (P1 :: P2 :: P3 :: P13 :: nil) (P4 :: P7 :: P8 :: P13 :: P14 :: nil) (P13 :: nil) 4 1 2 HP1P2P3P4P7P8P13P14mtmp HP13mtmp HP1P2P3P13Mtmp Hincl); apply HT.\n}\ntry clear HP1P2P3P13M1. try clear HP1P2P3P13M2. try clear HP1P2P3P13M3. try clear HP1P2P3P13m4. try clear HP1P2P3P13m3. try clear HP1P2P3P13m2. try clear HP1P2P3P13m1. try clear HP13M1. try clear HP13M2. try clear HP13M3. try clear HP13m4. try clear HP13m3. try clear HP13m2. try clear HP13m1. try clear HP1P2P3P4P7P8P13P14M1. try clear HP1P2P3P4P7P8P13P14M2. try clear HP1P2P3P4P7P8P13P14M3. try clear HP1P2P3P4P7P8P13P14m4. try clear HP1P2P3P4P7P8P13P14m3. try clear HP1P2P3P4P7P8P13P14m2. try clear HP1P2P3P4P7P8P13P14m1. \n\nassert(HP4P13m2 : rk(P4 :: P13 :: nil) >= 2).\n{\n\ttry assert(HP4P7P8P14eq : rk(P4 :: P7 :: P8 :: P14 :: nil) = 2) by (apply LP4P7P8P14 with (P1 := P1) (P2 := P2) (P3 := P3) (P4 := P4) (P5 := P5) (P6 := P6) (P7 := P7) (P8 := P8) (P9 := P9) (P10 := P10) (P11 := P11) (P12 := P12) (P13 := P13) (P14 := P14) (P15 := P15) ;try assumption).\n\tassert(HP4P7P8P14Mtmp : rk(P4 :: P7 :: P8 :: P14 :: nil) <= 2) by (solve_hyps_max HP4P7P8P14eq HP4P7P8P14M2).\n\ttry assert(HP4P7P8P13P14eq : rk(P4 :: P7 :: P8 :: P13 :: P14 :: nil) = 3) by (apply LP4P7P8P13P14 with (P1 := P1) (P2 := P2) (P3 := P3) (P4 := P4) (P5 := P5) (P6 := P6) (P7 := P7) (P8 := P8) (P9 := P9) (P10 := P10) (P11 := P11) (P12 := P12) (P13 := P13) (P14 := P14) (P15 := P15) ;try assumption).\n\tassert(HP4P7P8P13P14mtmp : rk(P4 :: P7 :: P8 :: P13 :: P14 :: nil) >= 3) by (solve_hyps_min HP4P7P8P13P14eq HP4P7P8P13P14m3).\n\ttry assert(HP4eq : rk(P4 :: nil) = 1) by (apply LP4 with (P1 := P1) (P2 := P2) (P3 := P3) (P4 := P4) (P5 := P5) (P6 := P6) (P7 := P7) (P8 := P8) (P9 := P9) (P10 := P10) (P11 := P11) (P12 := P12) (P13 := P13) (P14 := P14) (P15 := P15) ;try assumption).\n\tassert(HP4mtmp : rk(P4 :: nil) >= 1) by (solve_hyps_min HP4eq HP4m1).\n\tassert(Hincl : incl (P4 :: nil) (list_inter (P4 :: P13 :: nil) (P4 :: P7 :: P8 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P4 :: P7 :: P8 :: P13 :: P14 :: nil) (P4 :: P13 :: P4 :: P7 :: P8 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P4 :: P13 :: P4 :: P7 :: P8 :: P14 :: nil) ((P4 :: P13 :: nil) ++ (P4 :: P7 :: P8 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP4P7P8P13P14mtmp;try rewrite HT2 in HP4P7P8P13P14mtmp.\n\tassert(HT := rule_2 (P4 :: P13 :: nil) (P4 :: P7 :: P8 :: P14 :: nil) (P4 :: nil) 3 1 2 HP4P7P8P13P14mtmp HP4mtmp HP4P7P8P14Mtmp Hincl);apply HT.\n}\ntry clear HP4P7P8P14M1. try clear HP4P7P8P14M2. try clear HP4P7P8P14M3. try clear HP4P7P8P14m4. try clear HP4P7P8P14m3. try clear HP4P7P8P14m2. try clear HP4P7P8P14m1. try clear HP4M1. try clear HP4M2. try clear HP4M3. try clear HP4m4. try clear HP4m3. try clear HP4m2. try clear HP4m1. try clear HP4P7P8P13P14M1. try clear HP4P7P8P13P14M2. try clear HP4P7P8P13P14M3. try clear HP4P7P8P13P14m4. try clear HP4P7P8P13P14m3. try clear HP4P7P8P13P14m2. try clear HP4P7P8P13P14m1. \n\nassert(HP4P13M : rk(P4 :: P13 ::  nil) <= 2) by (solve_hyps_max HP4P13eq HP4P13M2).\nassert(HP4P13m : rk(P4 :: P13 ::  nil) >= 1) by (solve_hyps_min HP4P13eq HP4P13m1).\nintuition.\nQed.\n\n", "meta": {"author": "pascalschreck", "repo": "MatroidIncidenceProver", "sha": "e492d375a2264e6c908c9c47fe719c39e3f847f8", "save_path": "github-repos/coq/pascalschreck-MatroidIncidenceProver", "path": "github-repos/coq/pascalschreck-MatroidIncidenceProver/MatroidIncidenceProver-e492d375a2264e6c908c9c47fe719c39e3f847f8/matroidbasedIGprover/matroid_C_Coq/DevC/exemples/ExemplesSimples3D/testconfigDG.stat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.282675944149171}}
{"text": "From mathcomp Require Import ssreflect.all_ssreflect eqtype.\nFrom mathcomp Require Import algebra.ssrint.\n\nImport intZmod.\n \nRequire Import Common Types Memory.\nRequire Import Coq.Strings.String UtilString SSet.\n\nInductive BinOpKind :=| Add | Sub | Mul | Div | LAnd | LOr. Scheme Equality for BinOpKind.\n\n          Definition binop_eqP := reflect_from_dec BinOpKind_eq_dec.\n    \n          Canonical BinOpKind_eqMixin := EqMixin binop_eqP.\n          Canonical BinOpKind_eqType := EqType BinOpKind BinOpKind_eqMixin.\n\nInductive UnOpKind := | Neg | Invert | Not | Convert (to:ctype) | Amp | Asterisk .\n\n          Definition UnOpKind_beq (x y : UnOpKind) : bool :=\n            match x, y with\n              | Neg, Neg  |Invert, Invert | Not, Not | Amp, Amp | Asterisk, Asterisk => true\n              | Convert t1, Convert t2 => t1 == t2\n              | _, _ => false\n            end.\n\n          Lemma UnOpKind_eqP: Equality.axiom UnOpKind_beq.\n            - move=> x y.\n              case Heq: (UnOpKind_beq _ _); move: Heq. \n              case x; case y =>//=; try by constructor.\n              move=> t0 t1. by move /eqP =>->; constructor.\n              case x; case y => //=; try by constructor.\n              move=> t0 t1  /eqP => Hneq. constructor. by case.\n          Qed.\n          Canonical UnOpKind_eqMixin := EqMixin UnOpKind_eqP.\n          Canonical UnOpKind_eqType := EqType UnOpKind UnOpKind_eqMixin.\n          Definition UnOpKind_eq_dec := dec_from_reflect UnOpKind_eqP.\n          \nInductive expr :=\n| Assign: expr -> expr -> expr\n| Binop: BinOpKind -> expr -> expr -> expr\n| UnOp: UnOpKind -> expr -> expr\n| Var: string -> expr\n| Lit: forall t:ctype, coq_type t -> expr\n| Call: string -> seq expr -> expr.\n\nInductive statement :=\n| Sexpr : expr -> statement\n| If: expr -> statement -> statement -> statement\n| While : expr -> statement -> statement\n| Return: expr -> statement\n| Alloc: storage -> ctype -> option string -> nat -> statement\n| Sequence: seq statement -> statement\n.\nRecord var_descr := declare_var { var_name: string; var_type: ctype; location: nat }.\n           Theorem var_descr_eq_dec: eq_dec var_descr.\n             rewrite /eq_dec. decide equality. decide equality. apply ctype_eq_dec. apply string_eq_dec.\n           Qed.\n           \n           Definition var_descr_eqP := reflect_from_dec var_descr_eq_dec.\n           Canonical var_descr_eqMixin := EqMixin var_descr_eqP.\n           Canonical var_descr_eqType := EqType var_descr var_descr_eqMixin.\n\n\nRecord function := mk_fun {\n                       fun_id: nat;\n                       fun_name: string;\n                       fun_args: seq ctype;\n                       fun_returns: ctype;\n                       fun_body: statement;\n                     }.\n\nRecord static_ctx : Set := mk_stat_ctx {\n                        functions: seq function;\n                        variables: seq ( seq var_descr );\n                             }.\n\nDefinition static_ctx_empty:= mk_stat_ctx [::] [::].\n\nInductive deref :Set := | Deref : forall t:ctype,  ptr t -> deref.\n           Theorem deref_eq_dec: eq_dec deref.\n             rewrite /eq_dec. move => [t p [t' p']].\n             move: (ctype_eq_dec t t') =>[].\n             - move => Ht. subst. move: (ptr_eq_dec t' p p') =>[]. move=>->; by left.\n             - move => Hneq; right. case => H. by depcomp H.\n             - move => Hneq; right. by case.\n           Defined.\n           Definition deref_eqP := reflect_from_dec deref_eq_dec.\n           Canonical deref_eqMixin := EqMixin deref_eqP.\n           Canonical deref_eqType := EqType deref deref_eqMixin.\n\n           \nRecord dynamic_ctx : Type := mk_dyn_ctx { memory: seq block; reads: sset deref_eqType; writes: sset deref_eqType }.\n(* 0th block for Unit? NO we dont need that\n1-N blocks for functions*)\n\nProgram Definition dynamic_ctx_empty := mk_dyn_ctx [::] ( SSet _ [::] _ ) (SSet  _ [::] _) .\n\nInductive prog_state :=\n| Good: static_ctx -> dynamic_ctx -> prog_state\n| Bad :static_ctx -> dynamic_ctx -> statement -> prog_state.\n\nDefinition state_init := Good (mk_stat_ctx nil [:: [:: declare_var \"Unit\" Unit 0 ] ]) \n                              dynamic_ctx_empty.\n\nDefinition get_stat p := match p with | Good stat _ | Bad stat _ _ => stat end.\nDefinition get_dyn  p := match p with | Good _ dyn  | Bad _  dyn _ => dyn  end.\n\nDefinition get_var (sc:static_ctx) (name:string) : option var_descr :=\n  option_find (fun p: var_descr => var_name p == name) (flatten (variables sc)).\n\nDefinition get_fun (sc:static_ctx) (name:string) : option function :=\n  option_find (fun p: function => fun_name p == name) (functions sc).\n\nDefinition find_block (m: dynamic_ctx) (i: nat)  : option block :=\n  option_find (fun b=> block_id b == i) $ memory m.\n\n\nDefinition fmap_or {T R} (f: T-> R)  (orelse: R)  (x:option T) := match x with | Some x => f x | None => orelse end.\n(* Add address shit*)\n  \nFixpoint type_solver {sc: static_ctx} (e: expr) : ctype:=\n  let type := @type_solver sc  in\n  match e with\n    | Assign lhs rhs => Unit \n    | Binop code l r => eq_value_or_error_proved_arith (type l) (type r) (fun H x y => x) Bot\n    | UnOp Asterisk op => match type op with\n                            | Pointer t => t\n                            | _ => Bot\n                          end\n    | UnOp _ o => type o\n    | Var name => fmap_or (Pointer \\o var_type) ErrorType $ get_var sc name\n    | Lit t x => Unit\n    | Call name cargs => fmap_or (fun f => if map type cargs == fun_args f then fun_returns f else Bot) ErrorType $ get_fun sc name \n  end.\n\nInductive ContElem:=\n| Cstatement : statement -> ContElem\n| Pushctx\n| Popctx\n| FunEnd.\n       \n\nProgram Definition binop_interp (t:ctype) (op: BinOpKind) : int -> int -> value t :=\n  match t with |\n            Int kind =>\n            match op with\n              |Add => fun x y=> @Value t t _ $ cast (addz x y ) _\n              | _ => (fun _ _ => Error _)\n            end\n            | _ => (fun _ _ => Error _)\n  end\n.\n\nProgram Definition unop_interp (t:ctype) (op: UnOpKind) : int -> value t :=\n  match t with |\n            Int kind =>\n            match op with\n              |Neg => fun x => @Value t t _ $ cast (oppz x) _\n              | _ => fun _ => Error _\n            end\n            | _ => fun _ => Error _\n  end\n.\n\n\nProgram Definition dereference (tp:ctype) (v: value (Pointer tp)) (dyn:dynamic_ctx) : value tp :=\n  let ret_type := value tp in\n  match v as vo return v = vo -> ret_type with\n    | Value (Pointer tp) _  (Goodptr i o) as vo => fun Hto: v = vo =>\n      match find_block dyn i  as fb with\n        | Some ( mk_block loc _i sz block_type cnt ) =>\n          match block_type == tp with\n            | true =>  nth (Error _) cnt o\n            | false => Error _\n          end\n            \n        | None => Error _\n      end\n    | _ => fun _ => Error _\n  end _.\nNext Obligation.  \n    by apply /eqP.\nDefined.\n\n\nDefinition option_nth {T:eqType} (s:seq T) (n: nat) := nth None (map (@Some T) s) n.\nDefinition block_mod (b: block) (idx: nat) (e: value (el_type b)) : option block :=\n  if idx * ( SizeOf (el_type b)) >= block_size b then None\n  else @Some _ $ mk_block\n         (region b)\n         (block_id b)\n         (block_size b)\n         (el_type b)\n         (set_nth (Error _) (contents b) idx e).\nDefinition ErrorBlock := mk_block Data 0 0 ErrorType [::].\n\nProgram Definition mem_write (t: ctype) (id: nat) (pos: nat) (dyn: dynamic_ctx) (val: value t) : option dynamic_ctx :=\n  let m := memory dyn in\n  let oldblock := option_nth m id in\n  match oldblock with\n    | Some _oldblock =>\n      match ctype_beq t (el_type _oldblock) as Ht with\n        | true => let p := Deref t $ Goodptr t id pos in\n                  let newwrites := union (mk_set p) (writes dyn) in\n                  match block_mod _oldblock pos (cast val _) with\n                            | Some newblock => @Some _ $ mk_dyn_ctx ( set_nth ErrorBlock m id newblock ) (reads dyn) newwrites\n                            | _ => None\n                  end\n        | _ => None\n      end\n    | None => None\n  end.\nNext Obligation.\n  symmetry in Heq_Ht.\n  move /eqP in Heq_Ht.\n    by rewrite Heq_Ht.\nDefined.\n\n\n(* None if UB *) (*\nFixpoint flush_effects (dyn: dynamic_ctx) : option dynamic_ctx :=\n  let: mk_dyn_ctx eff mem := dyn in\n  match eff with\n    | nil => Some dyn\n    | (Effect t (Goodptr b off) v)::es => mem_write t b off (mk_dyn_ctx es mem) v\n    | _ => None\n  end.*)\n\n(*Fixpoint concat_effects (x y: dynamic_ctx) : (seq effect) ? :=\n  match  let: mk_dyn_ctx eff mem := dyn in\n  match eff with\n    | nil => Some dyn\n    | (Effect t (Goodptr b off) v)::es => mem_write t b off (mk_dyn_ctx es mem) v\n    | _ => None\n  end.\n*)\nInductive sexpr  : Set :=\n| SPush t: value t -> sexpr\n| SBinOp: BinOpKind -> sexpr\n| SUnOp: UnOpKind -> sexpr\n| SCall: string -> sexpr\n| SAssign\n| SRead: string -> sexpr\n.\n\nFixpoint unsome {T} (s:seq (option T)) :=\n  match s with\n    | x::xs => match x with\n                 | Some x => Some [::x] /++/ unsome xs\n                 | None => None\n               end\n    | nil => Some nil\n  end.\n\nFixpoint to_stack_code (c:static_ctx) (e: expr): seq sexpr ? :=\n  let f := to_stack_code c in\n  match e with\n    | Assign l r => f l /++/ f r /++/ Some [:: SAssign]\n    | Binop c l r => f l /++/ f r /++/ Some [:: SBinOp c]\n    | UnOp c o => f o /++/ Some [:: SUnOp c]\n    | Var x => Some [:: SRead x ]\n    | Lit t x => Some [:: @SPush t (Value t t Logic.eq_refl x) ]\n    | Call name args => option_map flatten ( unsome (map f args)) /++/ Some [::SCall name ]\n  end.\n\nDefinition Plus := Binop Add.\nDefinition Int := Lit Int32.\n\nLet ex_expr := Plus (Int 1) $ Plus (Int 9) $ Plus (Call \"f\" [::Var \"x\"]) $ Call \"g\" [:: Call \"h\" [:: Var \"x\"]; Call \"k\" [::Var \"x\"]].\n\n\nPrint mk_fun.\nDefinition Ff := mk_fun 1 \"f\" [:: Int64] Int64 $ Sequence nil.\nDefinition Fg := mk_fun 2 \"g\" [:: Int64; Int64] Int64 $ Sequence nil.\nDefinition Fh := mk_fun 3 \"h\" [:: Int64] Int64 $ Sequence nil.\nDefinition Fk := mk_fun 4 \"k\" [:: Int64] Int64 $ Sequence nil.\nDefinition dummy_stat_ctx := mk_stat_ctx [:: Ff; Fg; Fh; Fk] [::[:: declare_var \"x\" Int64 5]].\n\nImport Types.\nCompute to_stack_code dummy_stat_ctx ex_expr.\n\nInductive stack_elem := | mk_stack_elem: forall t, value t -> dynamic_ctx -> stack_elem.\n\n(* Todo: need to copy all values*)\n(* Maybe we need an implicit CONSISTENCY term? *)\nDefinition apply_writes (from to: dynamic_ctx)  :=\n  let wrs := writes from in\n  let folder (c: dynamic_ctx?) (d:deref) :=\n      match c with\n          | Some c => \n      match d with\n        | Deref t (Goodptr b o) as p =>\n          match dereference t (Value (Pointer t) (Pointer t) Logic.eq_refl (Goodptr _ b o) ) from with\n            | Value _ x _  as val => mem_write t b o to val\n            | _ => None\n          end\n        | _ => None\n      end\n          | None => None\n      end\n  in\n\n  foldl folder (Some to) wrs.\n\n                    \nFixpoint merge_dyn_ctx (x y: dynamic_ctx) : dynamic_ctx? :=\n  match x,y with\n    | mk_dyn_ctx  mx rx wx,\n      mk_dyn_ctx  my ry wy =>\n      match size $ intersect wx wy, size $ intersect rx wy, size $ intersect wx ry with\n        | 0,0,0 =>\n          match apply_writes x y with\n            | Some (mk_dyn_ctx mn rn wn) => @Some _ $ mk_dyn_ctx mn  (union rx ry) (union wx wy)\n            | None => None\n          end\n        | _, _, _ => None\n      end\n  end.\n\n\nFixpoint isexpr (stat: static_ctx) (dyn: dynamic_ctx) (e:sexpr) (s: seq stack_elem) : seq stack_elem ?:=\n  match e with\n    | SPush t x => @Some _ $ mk_stack_elem t x dyn :: s\n    | SUnOp x => _\n\n    | SBinOp op =>\n      match s with\n        | mk_stack_elem tx vx dx  :: mk_stack_elem ty vy dy :: ss =>\n          match mergectx dx dy with\n            | Some m=>\n              eq_value_or_error_proved_arith tx ty\n                                             (fun _ _ => Some ( pair ( binop_interp tx op (cast vx _) (cast vy _) ) m::ss) )\n                                             None\n            | None => None\n          end\n        | _ => None \n      end\n    | SCall x => _\n    | SAssign => _\n    | SRead x => _\n  end\n.\n\n      match s with\n        | (mk_elem (Int _) (Value (Int kx) _ x) dx) ::\n          (mk_elem (Int _) (Value (Int ky) _ y)  dy) :: ss =>\n          @Some _ $ mk_elem (Int kx)\n          ( eq_value_or_error_proved_arith (Int kx) (Int ky)  \n                                          (fun _ _ =>  binop_interp (Int kx) op (cast x _) (cast y _) ) (Error _)\n                                          )  :: ss\n        | _ =>  None\n      end\n\nFixpoint iexpr (stat: static_ctx) (dyn: dynamic_ctx) (e:expr): value (@type_solver stat e) ? * seq ContElem  \n      :=\n  let interp := iexpr stat dyn in\n  let type := @type_solver $ stat in\n  let ret_type := value $ type e in\n  let vars := flatten $ variables stat in\n  let blocks := memory dyn in\n  match e as e' return e = e' -> value (@type_solver stat e' ) with\n    | Lit t v as e' => fun Heq: e = e' => /! Value t t _ v \n    | Var name as e' => fun Heq: e = e' =>\n                    match get_var stat name with\n                    | Some (declare_var n t i) => match find_block dyn i with\n                                                    | Some b => match el_type b == t with\n                                                                  | true => /! Value (Pointer t) (Pointer t) _ ( Goodptr t i 0) \n                                                                  | _ => Error _ end\n                                                    | None => Error _\n                                                  end\n                    | None => Error _\n                  end\n    | Unop opcode op as e' => fun Heq: e = e' =>\n      match opcode as code return opcode = code -> value ( type e')  with\n        | Asterisk as code =>\n          fun Hc: opcode = code =>\n            match interp op with\n              | Value (Pointer pt) Heq p =>  @dereference pt (/! (interp op))   dyn \n              | _ => Error _\n            end \n        | code  =>\n          fun Hc : opcode = code =>\n          match interp op with\n                      | Value (Int kind) _ v  => unop_interp (type e') opcode (/! v )\n                      | _ => Error _\n                    end\n      end _\n    | Binop opcode l r as e' =>\n      fun Heq: e = e' =>\n        match interp l, interp r return value ( type e' ) with\n          | Value (Int kx) _ x, Value (Int ky) _ y =>\n            @eq_value_or_error (value ( type e') ) (Int kx) (Int ky)\n                               (fun _ _ => binop_interp (type e') opcode (cast x _) (cast y _) ) (Error _)\n          | _, _ => Error _\n        end \n    | Call _ _ => fun _ => Error _ \n  end _\n.\nNext Obligation.\n  rewrite /_dollar. simpl. by rewrite -Heq.  Defined.\n\nDefinition alloc {dc: dynamic_ctx} (b:block) : dynamic_ctx := mk_dyn_ctx ( (memory dc) ++ [:: b] ).\n\nDefinition next_block_id (s:dynamic_ctx) : nat := size $ memory $ s.\nFixpoint garbage_values {t:ctype} (sz: nat) : seq (value t) :=\n  match sz with | n .+1 => (Garbage t) :: (garbage_values n) | 0 => [::] end.\n\nDefinition bind_var (v:var_descr) (i:nat) (ctx:static_ctx) :=\n  let rec := (v,i) in\n  mk_stat_ctx (functions ctx) $ match variables ctx with\n                                    | [::] => [:: [:: rec] ]\n                                    | cons x xs => cons (cons rec x) xs\n                                  end\n.\n\nDefinition add_static_ctx (s:prog_state) :=\n  match s with\n    | Good stat dyn => Good (mk_stat_ctx (functions stat) ( [::] :: variables stat) ) dyn\n    | Bad _ _ _ as s => s\n  end.\n\nDefinition remove_static_ctx (s:prog_state) :=\n  match s with | Good stat dyn =>\n                match variables stat with\n                  | [::] => s\n                  | vs::vvs => Good (mk_stat_ctx (functions stat) vvs) dyn\n                end\n                  | s => s\n  end.\n\n\nDefinition ex_block := mk_block Stack 0 64 Int64 (garbage_values 8).\nEval compute in block_mod ex_block 1 (Value Int64 Int64 _ 3).\n\n\nDefinition add_var (vd:var_descr) (c: static_ctx) (i:nat) :=\n  mk_stat_ctx\n    (functions c)\n    match variables c with\n      | [::] => [:: [:: (vd,i) ]]\n      | cons x xs => cons (cons (vd,i) x) xs\n    end\n.\n\nProgram Definition is_value_true {t} {c:static_ctx} (v: value t) : option bool:=\n  match v as v0 return v = v0 -> option bool with\n    | Value (Int kind) _ z as v0 => fun H: v = v0 => Some (@sgz int_numDomainType z != 0)\n    | Value (Pointer _) _ Nullptr as v0 => fun H: v = v0=> Some false\n    | _ => fun _ => None \n  end _.\n\n\n Definition eval ps e: value ( @type_solver ( get_stat ps) e ) :=\n iexpr (get_stat ps) (get_dyn ps) e.\n\n Print expr.\n (***! Do canonical instances need to be exported? *)\n Print eq_value_or_error.\n Print coq_type.\n\n Print ctype_beq.\n\n\n Fixpoint expr_beq (l r:expr) : bool :=\n   let fix process (xs ys: seq expr) := match xs,ys with\n                                        | nil, nil => true\n                                        | x::xs, y::ys => expr_beq x y && process xs ys\n                                        | _, nil\n                                        | nil, _ => false\n                                      end in\n   match l,r with\n     | Lit x vx, Lit y vy =>\n       for_eq_carriers x y false\n                       (fun a b=> a == b)\n                       (fun pt px py => px == py)\n                       (fun sx sy => sx == sy)\n                       (fun _=> true)\n                       (fun _=> true) vx vy\n     | Var x, Var y => x == y\n     | Binop x x0 x1 , Binop y y0 y1 => (x == y) && expr_beq x0  y0 && expr_beq x1 y1\n     | Unop x x0, Unop y y0 => (x == y) && expr_beq x0 y0\n     | Call x x0 , Call y y0 => (x == y) && process x0 y0\n     | _,_ => false\n   end.\n\n Theorem carrier_eq_dec: forall t, eq_dec (coq_type t).\n   rewrite /eq_dec.\n   case.\n   - case; apply int_eq_dec.\n   - apply ptr_eq_dec.\n   - decide equality. decide equality.\n   - decide equality.\n   - decide equality.\n   - decide equality.\n Qed.\n\n\n   \n Theorem expr_eq_dec : eq_dec expr.\n   Local Lemma Hlst {A} (a:A) l : a :: l = l -> False. by  elim l =>//=; move=> a0 l0 IH [] =><-. Qed.\n   rewrite /eq_dec.\n   fix 1.\n   move => x y.\n   case x; case y; try by right.\n   - move => t c t0 c0.\n     case Ht:(t == t0).\n     + move /eqP in Ht; subst.\n       move: (carrier_eq_dec t0 c0 c).\n       case; [by left; subst\n             | by right; move =>[]=> H; depcomp H].\n     + by move /eqP in Ht; right; case; move=> He; symmetry in He.\n   - by move=> s0 s; move: (string_eq_dec s s0) => []; by[left; subst| right; case]. \n   - move=> op2 x2 y2 op1 x1 y1.\n     move: (binop_eq_dec op1 op2) => [Hop|Hop]; \n     move: (expr_eq_dec x1 x2) => [Hx|Hx];\n       move: (expr_eq_dec y1 y2) => [Hy|Hy]; try by right;case.\n     by rewrite Hx Hy Hop; left. \n   - move=> op1 x1  op2 x2.\n     move:(expr_eq_dec x2 x1) => [Hx|Hx]; move:(unop_eq_dec op2 op1) => [Hop|Hop]; subst; try by [right;case].\n     by left.\n   - move=> sy ly sx lx. \n     move: (string_eq_dec sx sy) => [Hs|Hs]; last by [right;case];subst.\n     elim: lx ly.\n     + elim; by [left| right ; discriminate].\n       move => a l IH [].\n       * by right; discriminate. \n       * clear x y. move=> y ys.\n         move: (expr_eq_dec a y) => [Ha|Ha]; move: (IH ys) => [Hy|Hy].\n         ** inversion Hy; subst; by left.\n         ** by right; case=> * *; subst. \n         ** by right; case. \n         ** by right; case.\nQed.\n\nDefinition expr_eqP := reflect_from_dec expr_eq_dec.\n  \nCanonical expr_eqMixin := EqMixin expr_eqP.\nCanonical expr_eqType := EqType expr expr_eqMixin.\n\nTheorem statement_eq_dec: eq_dec statement.\n   rewrite /eq_dec.   \nfix 1.\n   decide equality; try apply expr_eq_dec.\n   decide equality.\n   decide equality.\n   decide equality.\n   decide equality.\n   decide equality.\n   decide equality.\n   decide equality.\n   decide equality.\n   decide equality.\n   decide equality.\n   decide equality.\n   decide equality.\n   decide equality.\n   decide equality.\n   apply (seq_eq_dec _ ctype_eq_dec).\n   decide equality.\n   decide equality.\nDefined.\n\nDefinition statement_eqP := reflect_from_dec statement_eq_dec.\n\nCanonical statement_eqMixin := EqMixin statement_eqP.\nCanonical statement_eqType := EqType statement statement_eqMixin.\n\nProgram Fixpoint interpreter_step (st:statement) (s:prog_state) (cont: seq statement ):  prog_state * seq statement:=\n  match s with\n    |Good stat dyn =>\n     let type := @type_solver stat in\n     let bad := pair (Bad stat dyn st) nil in\n     match st with\n       | Skip => (s, cont)\n       | Assign w val  =>\n         match eval s w, eval s val with\n           | Value (Pointer t) _ vp, Value vtype _ v =>                           \n             match vtype == t with | true =>  match vp with\n                            | Goodptr to off =>\n                              match mem_write t to off dyn (Value t t _  (cast v _) ) with\n                                | Some d => (Good stat d, cont)\n                                | None => bad\n                              end\n                            | Nullptr => bad\n                          end\n               | _ => bad\n             end\n           | _, _ => bad\n         end                      \n     | Alloc loc type o_name sz =>\n         let block_id := next_block_id dyn in\n         let newdyn := mk_dyn_ctx (memory dyn ++  [:: mk_block loc block_id (sz* SizeOf type) type (garbage_values sz)])  in\n         match o_name with\n           | None => (Good stat newdyn, cont)\n           | Some name => (Good (add_var (declare_var name type block_id) stat block_id ) newdyn, cont)\n         end\n     | If cond _then _else => interpreter_step (\n                                  if @is_value_true _ stat $ @eval s cond\n                                  then  _then else _else ) s cont\n     | For prest cond postst body => (s, cont)\n     | While cond body => (s, cont)\n     | CodeBlock ss => (s, (Enter::ss) ++ (Leave :: cont))\n     | Enter => (add_static_ctx s, cont)\n     | Leave => (remove_static_ctx s, cont)\n     end\n       | s => (s, nil)\n  end . \n\n Next Obligation. by rewrite (eqP $ Logic.eq_sym Heq_anonymous). Defined.   \n\n \nDefinition LocVar t name := Alloc Stack t (Some name%string) 1. \n\nNotation \"{  x1 ; .. ; xn }\" := (CodeBlock(  cons x1  .. (cons xn nil) ..) ) (at level 35, left associativity) : c. \nNotation \"'int8 x \" := (LocVar Int8 x) (at level 200, no associativity) :c.\nNotation \"'uint8 x \" := (LocVar UInt8 x) (at level 200, no associativity) :c.\nNotation \"'int16 x \" := (LocVar Int16 x) (at level 200, no associativity) :c.\nNotation \"'uint16 x \" := (LocVar UInt16 x) (at level 200, no associativity) :c.\nCheck Assign (Var \"x\") (Lit Int64 4).\n\nNotation \"' v := value\" := (Assign (Var v) (value) ) (at level 200, no associativity) :c.\nDelimit Scope c with c.\nDefinition sample_prog := {\n                           {\n                             'int8 \"x\";\n                             'int8 \"y\";\n                             ' \"x\" := Lit Int8 4 ;\n                             ' \"y\" := Lit Int8 (Negz 9)\n                           } ;\n                           {\n                             'int16 \"x\";\n                             'int16 \"y\";\n                             ' \"x\" := Lit Int16 2\n                           }\n                         }%c .\n\nCompute interpreter_step sample_prog state_init nil .\n\nFixpoint interpret (steps: nat) (state: prog_state) (cont: seq statement): prog_state * seq statement :=\n  match steps, cont with\n    | S steps_left, s::ss =>\n      match interpreter_step s  state ss with\n        | (Good stat dyn as newstate, newcont) => interpret steps_left newstate newcont\n        | (Bad _ _ _ as bs, _) => (bs, cont)\n      end\n    | _, _ => (state, cont)\n  end\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/coq/CoreWithComplexExpr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2826759382749193}}
{"text": "\nRequire Import Coq.Lists.List.\nImport ListNotations.\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.\nRequire Import Defined.\nRequire Import Dots.\n\n\nDefinition ctx := @context Rules.obj.\n\n\nLemma deq_intro :\n  forall G a m n p q,\n    tr G (deq p q (equal a m n))\n    -> tr G (deq m n a).\nProof.\nintros G a m n p q H.\napply tr_equal_elim.\napply (tr_transitivity _ _ p).\n  {\n  apply tr_symmetry.\n  apply tr_equal_eta.\n  apply (tr_transitivity _ _ q); auto.\n  apply tr_symmetry; auto.\n  }\n\n  {\n  apply tr_equal_eta.\n  apply (tr_transitivity _ _ q); auto.\n  apply tr_symmetry; auto.\n  }\nQed.\n\n\n\nHint Rewrite def_istp def_of def_eqtp def_eq def_level def_subtype def_univ def_kind : prepare.\n\n\nLtac prepare :=\n  try unfoldtop;\n  unfold Defs.dof;\n  intros;\n  autorewrite with prepare in * |- *;\n  unfold Defs.triv;\n  repeat\n    (match goal with\n     | |- tr _ (deq triv triv (eqtype ?X ?Y)) => fold (deqtype X Y)\n\n     | H : tr _ (deq _ _ (eqtype ?X ?Y)) |- _ => let H' := fresh in so (tr_eqtype_eta2 _#5 H) as H'; fold (deqtype X Y) in H'; move H' before H; clear H\n\n     | |- tr _ (deq triv triv (subtype ?X ?Y)) => fold (dsubtype X Y)\n\n     | H : tr _ (deq _ _ (subtype ?X ?Y)) |- _ => let H' := fresh in so (tr_subtype_eta2 _#5 H) as H'; fold (dsubtype X Y) in H'; move H' before H; clear H\n\n     | |- tr _ (deq triv triv (equal _ _ _)) => apply tr_equal_intro\n\n     | H : tr _ (deq _ _ (equal _ _ _)) |- _ => let H' := fresh in so (tr_equal_elim _#4 (tr_equal_eta2 _#6 H)) as H'; move H' before H; clear H\n\n     end);\n  revert_all.\n\n\n\n(* This is from before we worked out the current system.  Now deprecated. *)\n\nHint Unfold Defs.dof Defs.triv Defs.level Defs.void Defs.bool\n  Defs.false Defs.true Defs.unit Defs.zero Defs.nat: valid_hint.\n\n\nLtac valid_rewrite := repeat (try rewrite -> def_of in * |- *;\n                                try rewrite -> def_arrow in * |- *;\n                                try rewrite -> def_kind in * |- *;\n                                try rewrite -> def_univ in * |- *;\n                                try rewrite -> def_kind in * |- *;\n                                try rewrite -> def_pi in * |- *;\n                                try rewrite -> def_eq in * |- *;\n                                try rewrite -> def_eqtp in * |- *;\n                                try rewrite -> def_istp in * |- *;\n                                try rewrite -> def_sigma in * |- *;\n                                try rewrite -> def_prod in * |- *;\n                                try rewrite -> def_fut in * |- *;\n                                try rewrite -> def_rec in * |- *;\n                                try rewrite -> def_ite in * |- *;\n                                try rewrite -> def_tarrow in * |- *\n                               ).\n\n", "meta": {"author": "kcrary", "repo": "istari", "sha": "42e71bc3bfba08542d005f27d100aa7537b1012b", "save_path": "github-repos/coq/kcrary-istari", "path": "github-repos/coq/kcrary-istari/istari-42e71bc3bfba08542d005f27d100aa7537b1012b/coq/ValidationUtil.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2826759382749193}}
{"text": "Require Import Coq.Logic.Classical.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Sets.Ensembles.\nRequire Import CertiGraph.lib.Coqlib.\nRequire Import CertiGraph.lib.Ensembles_ext.\nRequire Import CertiGraph.lib.EquivDec_ext.\nRequire Import CertiGraph.lib.Relation_ext.\nRequire Import CertiGraph.lib.List_ext.\nRequire Import CertiGraph.graph.graph_model.\nRequire Import CertiGraph.graph.weak_mark_lemmas.\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_computable.\nRequire Export CertiGraph.graph.FiniteGraph.\nRequire Export CertiGraph.graph.MathGraph.\nRequire Export CertiGraph.graph.LstGraph.\nRequire Export CertiGraph.graph.UnionFind.\nRequire Import CertiGraph.msl_application.Graph.\nRequire Import CertiGraph.msl_application.UnionFindGraph.\n\nLocal Open Scope logic.\n\nClass pPointwiseGraph_GList: Type :=\n  {\n    addr: Type;\n    null: addr;\n    SGBA: PointwiseGraphBasicAssum addr (addr * unit)\n  }.\n\nExisting Instance SGBA.\n\nDefinition is_null_SGBA {pSGG: pPointwiseGraph_GList} : DecidablePred addr := (existT (fun P => forall a, {P a} + {~ P a}) (fun x => x = null) (fun x => SGBA_VE x null)).\n\nClass sPointwiseGraph_GList {pSGG_Bi: pPointwiseGraph_GList} (DV DE: Type): Type :=\n  {\n    pred: Type;\n    SGP: PointwiseGraphPred addr (addr * unit) (DV * addr) unit pred;\n    SGA: PointwiseGraphAssum SGP;\n    SGAvs: PointwiseGraphAssum_vs SGP;\n    SGAvn: PointwiseGraphAssum_vn SGP null\n  }.\n\nExisting Instances SGP SGA SGAvs.\n\nSection GRAPH_GList.\n\n  Context {pSGG: pPointwiseGraph_GList}.\n  Context {DV DE DG: Type}.\n\n  Instance SGC_GList: PointwiseGraphConstructor addr (addr * unit) DV DE DG (DV * addr) unit.\n  Proof.\n    refine (Build_PointwiseGraphConstructor _ _ _ _ _ _ _ SGBA _ _).\n    + exact (@vgamma addr (addr * unit) SGBA_VE SGBA_EE is_null_SGBA (fun x => (x, tt)) DV DE DG).\n    + exact (fun _ _ => tt).\n  Defined.\n\n  Instance L_SGC_GList: Local_PointwiseGraphConstructor addr (addr * unit) DV DE DG (DV * addr) unit.\n  Proof.\n    refine (Build_Local_PointwiseGraphConstructor\n              _ _ _ _ _ _ _ SGBA SGC_GList\n              (fun G v => evalid (pg_lg G) (v, tt) /\\ src (pg_lg G) (v, tt) = v) _\n              (fun _ _ => True) _).\n    - intros. simpl. unfold vgamma.  simpl. destruct H as [? ?], H0 as [? ?]. f_equal; auto. pose proof (H3 _ H H5 H0 H6). rewrite <- !H7. clear H7.\n      destruct (SGBA_VE (dst (pg_lg G1) (x, tt)) null); auto.\n    - intros; simpl. auto.\n  Defined.\n\n  Global Existing Instances SGC_GList L_SGC_GList.\n\n  Local Coercion UFGraph_LGraph: UFGraph >-> LGraph.\n  Local Identity Coercion LGraph_LabeledGraph: LGraph >-> LabeledGraph.\n  Local Coercion pg_lg: LabeledGraph >-> PreGraph.\n\n  Notation UFGraph := (@UFGraph addr (addr * unit) _ _ is_null_SGBA (fun x => (x, tt)) DV DE DG).\n  Notation LGraph := (@LGraph addr (addr * unit) _ _ DV DE DG).\n\n  Instance RGF (G: UFGraph): ReachableFiniteGraph G.\n  Proof.\n    apply Build_ReachableFiniteGraph.\n    intros.\n    apply finite_reachable_computable with (is_null := is_null_SGBA) in H.\n    - destruct H as [l [? ?]]. exists l; auto.\n    - apply maGraph.\n    - apply (LocalFiniteGraph_FiniteGraph G), finGraph.\n    - apply (FiniteGraph_EnumCovered G), finGraph.\n  Defined.\n\n  Definition make_set_pregraph (v: addr) (g: PreGraph addr (addr * unit)) := pregraph_add_edge (pregraph_add_vertex g v) (v, tt) v null.\n\n  Lemma is_partial_make_set_pregraph: forall x (g: UFGraph), ~ vvalid g x -> is_partial_graph g (make_set_pregraph x g).\n  Proof.\n    intros. hnf. simpl. unfold addValidFunc, updateEdgeFunc. split; [|split; [|split]]; intros; [left; auto..| |].\n    - destruct (equiv_dec (x, tt) e); auto. hnf in e0. subst e. pose proof (@only_one_edge _ _ _ _ g _ (liGraph g) (src g (x, tt)) (x, tt) H1). simpl in H2.\n      assert (src g (x, tt) = src g (x, tt) /\\ evalid g (x, tt)) by (split; auto). rewrite H2 in H3. inversion H3. exfalso. rewrite H5 in H. intuition.\n    - destruct (equiv_dec (x, tt) e); auto. hnf in e0. subst e. destruct (@valid_graph _ _ _ _ g _ (maGraph g) _ H0) as [? _].\n      pose proof (@only_one_edge _ _ _ _ g _ (liGraph g) (src g (x, tt)) (x, tt) H2). assert (src g (x, tt) = src g (x, tt) /\\ evalid g (x, tt)) by (split; auto).\n      rewrite H3 in H4. inversion H4. exfalso. rewrite H6 in H. intuition.\n  Qed.\n\n  Definition make_set_LabeledGraph (v: addr) (g: LabeledGraph addr (addr * unit) DV DE DG) (default_dv: DV) (default_de: DE) (default_dg: DG) : LGraph :=\n    Build_LabeledGraph _ _ _ (make_set_pregraph v g) (fun x => if SGBA_VE x v then default_dv else vlabel g x) (fun e => default_de) default_dg.\n\n  Definition make_set_MathGraph (v: addr) (g: PreGraph addr (addr * unit)) (H: v <> null) (Hm: MathGraph g is_null_SGBA): MathGraph (make_set_pregraph v g) is_null_SGBA.\n  Proof.\n    apply (Build_MathGraph _ is_null_SGBA).\n    - intros. simpl. unfold updateEdgeFunc, addValidFunc. destruct (equiv_dec (v, tt) e). 1: intuition. simpl in H0. unfold addValidFunc in H0. destruct H0.\n      + destruct Hm. apply valid_graph in H0. destruct H0. split. 1: left; auto. hnf in H1. simpl in H1. destruct H1; [left | right; left]; auto.\n      + compute in c. exfalso; intuition.\n    - intros. hnf in H0. simpl in H1. destruct H0.\n      + subst x. destruct Hm. apply valid_not_null in H0; auto. simpl. auto.\n      + subst v. auto.\n  Defined.\n\n  Definition make_set_FiniteGraph (v: addr) (g: PreGraph addr (addr * unit)) (Hf: FiniteGraph g): FiniteGraph (make_set_pregraph v g).\n  Proof.\n    destruct Hf. unfold EnumEnsembles.Enumerable in *. destruct finiteV as [vl [? ?]]. destruct finiteE as [el [? ?]]. constructor; hnf; simpl; unfold addValidFunc.\n    - destruct (in_dec SGBA_VE v vl).\n      + exists vl. split; auto. intros. unfold In in H0 |-* . rewrite H0. intuition. subst v. rewrite H0 in i. auto.\n      + exists (v :: vl). split; [constructor; auto|]. intros. simpl. unfold In in H0 |-* . rewrite H0. intuition.\n    - unfold In in H2 |-* . destruct (in_dec SGBA_EE (v, tt) el).\n      + exists el. split; auto. intros. rewrite H2. intuition. inversion H4. rewrite H2 in i. auto.\n      + exists ((v, tt) :: el). split; [constructor; auto|]. intros. simpl. rewrite H2. intuition.\n  Defined.\n\n  Lemma make_set_valid_path_pfoot: forall (v: addr) (g: PreGraph addr (addr * unit)) x p (Hn: v <> null) (Hi: ~ vvalid g v) (Hm: MathGraph g is_null_SGBA),\n      x <> v -> pfoot (make_set_pregraph v g) p = x -> valid_path (make_set_pregraph v g) p -> pfoot g p = x /\\ valid_path g p.\n  Proof.\n    intros. destruct p as [p l]. assert (forall e, List.In e l -> e <> (v, tt)). {\n      intros. apply (valid_path_strong_evalid _ _ _ e) in H1; auto. hnf in H1. simpl in H1. unfold addValidFunc, updateEdgeFunc in H1.\n      destruct H1 as [? [? ?]]. intro. destruct (equiv_dec (v, tt) e). 2: compute in c; auto. destruct H4; auto. destruct Hm. apply valid_not_null in H4; simpl; auto.\n    } split.\n    - clear H1. revert p H0. induction l; intros. 1: simpl in H0 |-* ; auto.\n      assert (forall e : addr * unit, List.In e l -> e <> (v, tt)) by (intros; apply H2; right; auto). specialize (IHl H1). clear H1.\n      rewrite pfoot_cons in H0 |-* . simpl dst in H0. unfold updateEdgeFunc in H0. destruct (equiv_dec (v, tt) a).\n      + hnf in e. assert (a <> (v, tt)) by (apply H2; left; auto). exfalso; auto.\n      + apply IHl; auto.\n    - assert (p <> v). {\n        intro. subst p. destruct l. 1: simpl in H0; auto. simpl in H1. destruct H1. assert (strong_evalid (make_set_pregraph v g) p) by (destruct l; [|destruct H3]; auto).\n        clear H3. hnf in H4. simpl in H4. unfold addValidFunc, updateEdgeFunc in H1, H4. destruct H4 as [? _]. assert (p <> (v, tt)) by (apply H2; left; auto).\n        destruct (equiv_dec (v, tt) p). 1: hnf in e; auto. destruct H3; auto. destruct Hm. apply valid_graph in H3. destruct H3 as [? _]. rewrite <- H1 in H3. auto.\n      } clear H0. revert p H1 H3. induction l; intros.\n      + simpl in H1. unfold addValidFunc in H1. simpl. destruct H1; [|exfalso]; auto.\n      + assert (forall e : addr * unit, List.In e l -> e <> (v, tt)) by (intros; apply H2; right; auto). specialize (IHl H0). clear H0.\n        assert (a <> (v, tt)) by (apply H2; left; auto). rewrite valid_path_cons_iff in H1 |-* . destruct H1 as [? [? ?]]. split; [|split].\n        * simpl in H1. unfold updateEdgeFunc in H1. destruct (equiv_dec (v, tt) a); [exfalso|]; auto.\n        * hnf in H4. simpl in H4. unfold addValidFunc, updateEdgeFunc in H4. destruct H4 as [? [? ?]].\n          destruct (equiv_dec (v, tt) a); [hnf in e; exfalso|]; auto. destruct H4; [|exfalso]; auto. clear c.\n          destruct H6. 2: destruct Hm; apply valid_graph in H4; destruct H4; rewrite H6 in H4; exfalso; auto.\n          destruct H7. 2: destruct Hm; apply valid_graph in H4; destruct H4; hnf in H8; simpl in H8; rewrite H7 in H8; exfalso; destruct H8; auto. hnf. split; auto.\n        * simpl dst in H5. unfold updateEdgeFunc in H5. destruct (equiv_dec (v, tt) a); [hnf in e; exfalso|]; auto. apply IHl; auto.\n          destruct H4 as [? _]. simpl in H4. unfold addValidFunc in H4. destruct H4; [|exfalso]; auto. destruct Hm. apply valid_graph in H4. destruct H4 as [_ ?].\n          hnf in H4. simpl in H4. intro. rewrite H6 in H4. destruct H4; auto.\n  Qed.\n\n  Definition make_set_LstGraph (v: addr) (g: PreGraph addr (addr * unit)) (Hn: v <> null) (Hi: ~ vvalid g v) (Hm: MathGraph g is_null_SGBA)\n             (Hl: LstGraph g (fun x => (x, tt))): LstGraph (make_set_pregraph v g) (fun x => (x, tt)).\n  Proof.\n    constructor; simpl.\n    - unfold addValidFunc, updateEdgeFunc. intros. destruct H.\n      + destruct Hl. specialize (only_one_edge x e H). destruct (equiv_dec (v, tt) e).\n        * hnf in e0. subst e. rewrite <- only_one_edge. split; intros.\n          -- destruct H0. subst v. rewrite only_one_edge. auto.\n          -- rewrite only_one_edge in H0. inversion H0. subst v. split; auto.\n        * compute in c. rewrite <- only_one_edge. split; intros.\n          -- destruct H0. split; auto. destruct H1; auto. exfalso; auto.\n          -- destruct H0. split; auto.\n      + subst v. split; intros.\n        * destruct H. destruct H0; auto. destruct (equiv_dec (x, tt) e).\n          -- hnf in e0; auto.\n          -- destruct Hm. specialize (valid_graph _ H0). destruct valid_graph. rewrite H in H1. exfalso; auto.\n        * destruct (equiv_dec (x, tt) e).\n          -- hnf in e0. split; auto.\n          -- compute in c. exfalso; auto.\n    - intros. destruct_eq_dec x v.\n      + subst x. destruct p as [p l]. destruct H as [[? ?] [? _]]. simpl in H. subst p. simpl in H1. destruct l; auto. unfold updateEdgeFunc in H1. destruct H1.\n        assert (strong_evalid (make_set_pregraph v g) p) by (simpl in H1; destruct l; [|destruct H1]; auto). hnf in H2. simpl in H2. unfold addValidFunc, updateEdgeFunc in H2.\n        destruct H2 as [? [? ?]]. destruct (equiv_dec (v, tt) p).\n        * exfalso. destruct H4; auto. destruct Hm. apply valid_not_null in H4; simpl; auto.\n        * compute in c. exfalso. destruct H2; auto. destruct Hm. apply valid_graph in H2. destruct H2. subst v. auto.\n      + destruct Hl. apply no_loop_path. destruct H as [[? ?] [? ?]]. assert (pfoot g p = x /\\ valid_path g p) by (apply (make_set_valid_path_pfoot v); auto).\n        destruct H4. split; split; auto.\n  Defined.\n\n  Definition make_set_sound (v: addr)  (g: PreGraph addr (addr * unit)) (Hn: v <> null) (Hi: ~ vvalid g v) (Hlmf: LiMaFin g) : LiMaFin (make_set_pregraph v g) :=\n    Build_LiMaFin _ (make_set_LstGraph v g Hn Hi ma li) (make_set_MathGraph v g Hn ma) (make_set_FiniteGraph v g fin).\n\n  Definition make_set_Graph (default_dv: DV) (default_de: DE) (default_dg: DG) (v: addr) (g: UFGraph) (Hn: v <> null) (Hi: ~ vvalid g v) : UFGraph :=\n    Build_GeneralGraph _ _ _ _ (make_set_LabeledGraph v g default_dv default_de default_dg) (make_set_sound v g Hn Hi (sound_gg g)).\n\n  Lemma uf_under_bound_make_set_graph: forall (default_dv: DV) (default_de: DE) (default_dg: DG) (v: addr) (g: UFGraph) (Hn: v <> null) (Hi: ~ vvalid g v) (extract: DV -> nat),\n      extract default_dv = O -> uf_under_bound extract g -> uf_under_bound extract (make_set_Graph default_dv default_de default_dg v g Hn Hi).\n  Proof.\n    intros. hnf in H0 |-* . simpl. intro x; intros. unfold addValidFunc in H1. destruct (SGBA_VE x v).\n    - hnf in e. subst v. destruct H1; [exfalso; auto |]. clear H1. hnf. intros. rewrite H. destruct p as [p l]. destruct l; simpl; auto. exfalso.\n      apply pfoot_in_cons in H2. destruct H2 as [e [? ?]]. simpl in H3. unfold updateEdgeFunc in H3. pose proof (valid_path_strong_evalid _ _ _ _ H1 H2). hnf in H4.\n      simpl in H4. unfold addValidFunc, updateEdgeFunc in H4. destruct H4 as [? [? ?]]. destruct (equiv_dec (x, tt) e). 1: exfalso; auto. compute in c.\n      destruct H4; auto. destruct (@valid_graph _ _ _ _ g _ (maGraph g) _ H4) as [_ ?]. rewrite H3 in H7. destruct H7; auto.\n    - compute in c. destruct H1; [|exfalso; auto]. hnf. intros. assert (pfoot g p = x /\\ valid_path g p) by (apply (make_set_valid_path_pfoot v); auto; exact (maGraph g)).\n      destruct H4. unfold uf_bound in H0. apply H0; auto.\n  Qed.\n\n  Definition single_uf_pregraph (v: addr) : PreGraph addr (addr * unit) :=\n    pregraph_add_edge (single_vertex_pregraph v) (v, tt) v null.\n\n  Lemma reachabel_single_uf: forall x y, x <> null -> reachable (single_uf_pregraph x) x y <-> x = y.\n  Proof.\n    intros. split; intros.\n    - destruct H0 as [[? ?] [[? ?] [? _]]]. simpl in H0. subst a. destruct l.\n      + simpl in H1. auto.\n      + destruct H2. simpl in H2. assert (strong_evalid (single_uf_pregraph x) p) by (destruct l; intuition). clear H2. exfalso.\n        hnf in H3. simpl in H3. unfold updateEdgeFunc in H3. destruct H3 as [? [_ ?]]. unfold addValidFunc in H2. destruct H2; auto. subst p.\n        destruct (equiv_dec (x, tt) (x, tt)); [|compute in c]; auto.\n    - subst y. apply reachable_refl. simpl. auto.\n  Qed.\n\n  Definition single_uf_LabeledGraph (v: addr) (default_dv: DV) (default_de: DE) (default_dg: DG) : LGraph :=\n    Build_LabeledGraph _ _ _ (single_uf_pregraph v) (fun v => default_dv) (fun e => default_de) default_dg.\n\n  Definition single_uf_MathGraph (v: addr) (H: v <> null): MathGraph (single_uf_pregraph v) is_null_SGBA.\n  Proof.\n    apply (Build_MathGraph _ is_null_SGBA).\n    - intros. simpl. unfold updateEdgeFunc.\n      destruct (equiv_dec (v, tt) e); intuition.\n    - intros. hnf in *. subst v. intuition.\n  Defined.\n\n  Definition single_uf_FiniteGraph (v: addr): FiniteGraph (single_uf_pregraph v).\n  Proof.\n    constructor; hnf.\n    - exists (v :: nil). split.\n      + constructor. intro. inversion H. constructor.\n      + intros. simpl. unfold In. intuition.\n    - exists ((v, tt) :: nil). split.\n      + constructor. intro. inversion H. constructor.\n      + intros. simpl. unfold In, addValidFunc. intuition.\n  Defined.\n\n  Definition single_uf_LstGraph (v: addr) (H: v <> null): LstGraph (single_uf_pregraph v) (fun x => (x, tt)).\n  Proof.\n    constructor; simpl; intros; unfold updateEdgeFunc.\n    - unfold addValidFunc. subst. destruct (equiv_dec (x, tt) e); intuition.\n    - destruct H0 as [[? _] [? _]]. destruct p as [p l]. simpl in *. subst p.\n      destruct l; auto. destruct H1. clear H0. simpl in H1. assert (strong_evalid (single_uf_pregraph v) p) by (destruct l; [|destruct H1]; auto). clear H1.\n      hnf in H0. simpl in H0. unfold addValidFunc, updateEdgeFunc in H0. destruct H0 as [? [_ ?]]. exfalso. destruct H0; auto. subst p.\n      destruct (equiv_dec (v, tt) (v, tt)); auto. compute in c. apply c; auto.\n  Defined.\n\n  Definition single_sound (v: addr) (H: v <> null) : LiMaFin (single_uf_pregraph v) :=\n    Build_LiMaFin _ (single_uf_LstGraph v H) (single_uf_MathGraph v H) (single_uf_FiniteGraph v).\n\n  Definition single_Graph (v: addr) (H: v <> null) (default_dv: DV) (default_de: DE) (default_dg: DG): UFGraph :=\n    Build_GeneralGraph _ _ _ _ (single_uf_LabeledGraph v default_dv default_de default_dg) (single_sound v H).\n\nEnd GRAPH_GList.\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/GList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.28267593827491927}}
{"text": "Require Setoid.\nRequire ZArith.\nImport ZArith.\n\nInductive Erasable(A : Set) : Prop :=\n  erasable: A -> Erasable A.\n\nArguments erasable [A] _.\n\nHint Constructors Erasable.\n\nScheme Erasable_elim := Induction for Erasable Sort Prop.\n\nNotation \"## T\" := (Erasable T) (at level 1, format \"## T\") : Erasable_scope.\nNotation \"# x\" := (erasable x) (at level 1, format \"# x\") : Erasable_scope.\nOpen Scope Erasable_scope.\n\nAxiom Erasable_inj : forall {A : Set}{a b : A}, #a=#b -> a=b.\n\nLemma Erasable_rw : forall (A: Set)(a b : A), (#a=#b) <-> (a=b).\nProof.\n  intros A a b.\n  split.\n  - apply Erasable_inj.\n  - congruence.\nQed.\n\nOpen Scope Z_scope.\nOpaque Z.mul.\n\nInfix \"^\" := Zpower_nat : Z_scope.\n\nNotation \"f ; v <- x\" := (let (v) := x in f)\n                            (at level 199, left associativity) : Erasable_scope.\nNotation \"f ; < v\" := (f ; v <- v)\n                         (at level 199, left associativity) : Erasable_scope.\nNotation \"f |# v <- x\" := (#f ; v <- x)\n                          (at level 199, left associativity) : Erasable_scope.\nNotation \"f |# < v\" := (#f ; < v)\n                          (at level 199, left associativity) : Erasable_scope.\n\nLtac name_evars id := \n  repeat match goal with |- context[?V] => \n                         is_evar V; let H := fresh id in set (H:=V) in * end.\n\nLemma Twoto0 : 2^0 = 1.\nProof. compute. reflexivity. Qed.\n\nLtac ring_simplify' := rewrite ?Twoto0; ring_simplify.\n\nDefinition mp2a1s(x : Z)(n : nat) := x * 2^n + (2^n-1).\n\nHint Unfold mp2a1s.\n\nDefinition zotval(n1s : nat)(is2 : bool)(next_value : Z) : Z :=\n  2 * mp2a1s next_value n1s + if is2 then 2 else 0.\n\nInductive zot'(eis2 : ##bool)(value : ##Z) : Set :=\n| Zot'(is2 : bool)\n      (iseq : eis2=#is2)\n      {next_is2 : ##bool}\n      (ok : is2=true -> next_is2=#false)\n      {next_value : ##Z}\n      (n1s : nat)\n      (veq : value = (zotval n1s is2 next_value |#<next_value))\n      (next : zot' next_is2 next_value)\n  : zot' eis2 value.\n\nDefinition de2{eis2 value}(z : zot' eis2 value) : zot' #false value.\nProof.\n  case z.\n  intros is2 iseq next_is2 ok next_value n1s veq next. \n  subst.\n  destruct is2.\n  2:trivial.\n  clear z.\n  specialize (ok eq_refl). subst.\n  destruct n1s.\n  - refine (Zot' _ _ _ _ _ _ _ _).\n    all:shelve_unifiable.\n    reflexivity.\n    discriminate.\n    name_evars e.\n    case_eq next_value. intros next_valueU next_valueEU.\n    case_eq e. intros eU eEU.\n    f_equal.\n    unfold zotval.\n    unfold mp2a1s.\n    ring_simplify'.\n    replace 2 with (2*1) at 2 7 by omega.\n    rewrite <-?Z.mul_assoc.\n    rewrite <-?Z.mul_add_distr_l.\n    rewrite <-Z.mul_sub_distr_l.\n    rewrite Z.mul_cancel_l by omega.\n    replace 1 with (2-1) at 1 by omega.\n    rewrite Z.add_sub_assoc.\n    rewrite Z.sub_cancel_r.\n    Unshelve.\n    all:case_eq next.\nAbort.\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/3652.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.28260501014247214}}
{"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 O E Eprime Eprimeprime A B C Bprime : Universe, ((wd_ O E /\\ (wd_ O Eprime /\\ (wd_ E Eprime /\\ (wd_ B O /\\ (wd_ A O /\\ (wd_ C O /\\ (wd_ O Eprimeprime /\\ (wd_ E Eprimeprime /\\ (wd_ B E /\\ (wd_ A E /\\ (wd_ Bprime O /\\ (wd_ Eprime Eprimeprime /\\ (wd_ Eprimeprime A /\\ (wd_ Eprime A /\\ (wd_ Eprime Bprime /\\ (wd_ Eprime C /\\ (wd_ A Bprime /\\ (wd_ A C /\\ (wd_ Bprime C /\\ (wd_ E Bprime /\\ (wd_ Eprime B /\\ (wd_ B Bprime /\\ (wd_ B Eprimeprime /\\ (wd_ Bprime Eprimeprime /\\ (col_ O E A /\\ (col_ O E B /\\ (col_ O E C /\\ (col_ O Eprime Bprime /\\ (col_ O Eprimeprime Bprime /\\ (col_ E Eprime Eprimeprime /\\ col_ O Eprime B)))))))))))))))))))))))))))))) -> col_ O E Eprime)).\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_1215.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.28257152588479195}}
{"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 A B C X1 X2 X3 D F : Universe, ((wd_ A B /\\ (wd_ B C /\\ (wd_ A C /\\ (wd_ A F /\\ (wd_ A F /\\ (wd_ B D /\\ (wd_ B F /\\ (wd_ C D /\\ (wd_ C F /\\ (wd_ A X3 /\\ (wd_ B X2 /\\ (wd_ C X1 /\\ (wd_ D F /\\ (col_ D B X2 /\\ (col_ D C X1 /\\ (col_ F C X1 /\\ (col_ F A X3 /\\ (col_ F A X3 /\\ col_ F B X2)))))))))))))))))) -> col_ C D B)).\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_1059.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.2825715214066802}}
{"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 Import ZArith.\nRequire Import DecidableType.\n\nRequire Import Mapping.\nRequire Import ElemTypes.\nRequire Import Types.\n\nModule AA_as_DT := DecidableTypeEx.PairDecidableType (Address_as_DT) (Address_as_DT).\n\nModule AA2V := Mapping (AA_as_DT) (ValElem).\nDefinition aa2v := AA2V.t.\n\nNotation \"$0\" := (AA2V.empty) (only parsing) : aa2v_scope.\n\nNotation \"m '$' '[' k0 ',' k1 ']'\" :=\n  (AA2V.get m (k0, k1))\n    (at level 50, left associativity, only parsing) : aa2v_scope.\n\nNotation \"m '$' '{' k0 ',' k1 '<~' v '}'\" :=\n  (AA2V.upd m (k0, k1) v)\n    (at level 50, left associativity, only parsing) : aa2v_scope.\n\nNotation \"m '$' '{' k0 ',' k1  '<+~' v '}'\" :=\n  (AA2V.upd_inc m (k0, k1) v)\n    (at level 50, left associativity, only parsing) : aa2v_scope.\n\nNotation \"m '$' '{' k0 ',' k1 '<-~' v '}'\" :=\n  (AA2V.upd_dec m (k0, k1) v)\n    (at level 50, left associativity, only parsing) : aa2v_scope.\n\nNotation \"m '~' m'\" :=\n  (AA2V.equal m m')\n    (at level 70, no associativity, only parsing) : aa2v_scope.\n\nOpen Scope aa2v_scope.\n\nSection EqDec.\n  Lemma aa_eqdec:\n    forall (k k': address * address),\n      { (fun x y : nat * nat => fst x = fst y /\\ snd x = snd y) k k' } +\n      { ~ (fun x y : nat * nat => fst x = fst y /\\ snd x = snd y) k k' }.\n  Proof.\n    intros.\n    destruct k as [a0 a1].\n    destruct k' as [a0' a1'].\n    destruct (Nat.eq_dec a0 a0'); destruct (Nat.eq_dec a1 a1');\n      solve [ left; auto |\n              right;\n              intros Heq; inversion Heq;\n              apply n; auto\n            ].\n  Qed.\nEnd EqDec.\n\nSection Range.\n  Lemma upd_in_range:\n    forall (m: aa2v) lo hi,\n      (forall k, lo <= AA2V.get m k <= hi) ->\n      forall v,\n        lo <= v <= hi ->\n        forall k k',\n          lo <= AA2V.get (AA2V.upd m k v) k' <= hi.\n  Proof.\n    intros.\n\n    destruct (aa_eqdec k' k).\n    - rewrite (AA2V.get_upd_eq); auto.\n    - rewrite (AA2V.get_upd_neq); auto.\n  Qed.\n\n  Lemma upd_inc_in_range:\n    forall (m: aa2v) lo hi,\n      (forall k, lo <= AA2V.get m k <= hi) ->\n      forall k v,\n        AA2V.get m k + v <= hi ->\n        forall k',\n          lo <= AA2V.get (AA2V.upd m k (AA2V.get m k + v)) k' <= hi.\n  Proof.\n    intros.\n\n    destruct (aa_eqdec k' k).\n    - rewrite (AA2V.get_upd_eq); auto.\n      generalize (H k); clear H; intros H.\n      omega.\n    - rewrite (AA2V.get_upd_neq); auto.\n  Qed.\n\n  Lemma upd_dec_in_range:\n    forall (m: aa2v) lo hi,\n      (forall k, lo <= AA2V.get m k <= hi) ->\n      forall k v,\n        AA2V.get m k - lo >= v ->\n        forall k',\n          lo <= AA2V.get (AA2V.upd m k (AA2V.get m k - v)) k' <= hi.\n  Proof.\n    intros.\n\n    destruct (aa_eqdec k' k).\n    - rewrite (AA2V.get_upd_eq); auto.\n      generalize (H k); clear H; intros H.\n      omega.\n    - rewrite (AA2V.get_upd_neq); auto.\n  Qed.\n\nEnd Range.\n\nClose Scope aa2v_scope.\n\nHint Resolve\n     upd_in_range\n     upd_inc_in_range\n     upd_dec_in_range.", "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/libs/wip/AA2V.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2825035625210455}}
{"text": "(** The Wasm type checker reflects typing (soundness and completeness) **)\n(* (C) J. Pichon - see LICENSE.txt *)\n\nFrom mathcomp Require Import ssreflect ssrfun ssrnat ssrbool eqtype seq.\n\nFrom Coq Require Import Program.\nFrom StrongInduction Require Import StrongInduction Inductions.\n\nRequire Import Lia.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nFrom Wasm Require Import common operations typing type_checker properties.\n\nSection Host.\n\nVariable host_function : eqType.\n\nLemma result_typingP : forall r ts,\n  reflect (result_typing r ts) (result_types_agree ts r).\nProof.\n  move=> + ts. case.\n  - move=> l /=. apply: iffP.\n    + rewrite all2_swap. by apply: all2_mapP.\n    + move=> ?. subst. by constructor.\n    + move=> T. by inversion_clear T.\n  - apply: Bool.ReflectT. by constructor.\nQed.\n\nLemma nth_error_ssr: forall {T: Type} (l: list T) n (x x0:T),\n  List.nth_error l n = Some x -> nth x0 l n = x.\nProof.\n  induction l => //=; destruct n => //=; intros; first by inversion H.\n  by apply IHl.\nQed.\n\nLemma size_ct_list: forall l,\n  size (to_ct_list l) = size l.\nProof.\n  unfold to_ct_list. by apply size_map.\nQed.\n  \nLemma ssr_nth_error: forall {T: Type} (l: list T) n (x x0:T),\n  nth x0 l n = x ->\n  n < size l ->\n  List.nth_error l n = Some x.\nProof.\n  induction l; destruct n => //=; intros; subst => //=.\n  eapply IHl; eauto; by lias.\nQed.\n\nLemma ct_compat_symmetry: forall c1 c2,\n  ct_compat c1 c2 ->\n  ct_compat c2 c1.\nProof.\n  intros.\n  destruct c1, c2 => //=.\n  simpl in H.\n  move/eqP in H.\n  subst.\n  by apply/eqP.\nQed.\n\nLemma ct_list_compat_rcons_bool: forall l1 l2 x1 x2,\n  ct_list_compat (rcons l1 x1) (rcons l2 x2) =\n  ct_compat x1 x2 && ct_list_compat l1 l2.\nProof.\n  induction l1; intros; destruct l2 => //=.\n  - destruct l2 => //=; by lias.\n  - destruct l1 => //=; by lias.\n  - rewrite IHl1. by lias.\nQed.\n    \nLemma ct_list_compat_rcons: forall l1 l2 x1 x2,\n  ct_list_compat (rcons l1 x1) (rcons l2 x2) <->\n  ct_compat x1 x2 /\\ ct_list_compat l1 l2.\nProof.\n  split; intros.\n  - rewrite ct_list_compat_rcons_bool in H.\n    by move/andP in H.\n  - move/andP in H.\n    by rewrite ct_list_compat_rcons_bool.\nQed.\n\nLemma ct_suffix_rcons: forall l1 l2 x1 x2,\n  ct_suffix (rcons l1 x1) (rcons l2 x2) <->\n  ct_compat x1 x2 /\\ ct_suffix l1 l2.\nProof.\n  unfold ct_suffix.\n  intros.\n  split; move => H.\n  - move/andP in H; destruct H.\n    repeat rewrite size_rcons in H.\n    rewrite drop_rcons in H0; last by repeat rewrite size_rcons; lias.\n    apply ct_list_compat_rcons in H0.\n    destruct H0.\n    split => //; first by apply ct_compat_symmetry.\n    apply/andP; split; first by lias.\n    repeat rewrite size_rcons in H1.\n    by replace (_-_) with (size l2 - size l1) in H1; last by lias.\n  - destruct H.\n    move/andP in H0; destruct H0.\n    repeat rewrite size_rcons.\n    apply/andP; split; first by lias.\n    rewrite drop_rcons; last by lias.\n    replace (_-_) with (size l2 - size l1); last by lias.\n    apply ct_list_compat_rcons.\n    split => //.\n    by apply ct_compat_symmetry.\nQed.\n    \nLemma ct_suffix_empty: forall l,\n  ct_suffix [::] l.\nProof.\n  move => l. unfold ct_suffix => /=.\n  rewrite subn0. apply/eqP.\n  by rewrite drop_size.\nQed.\n\nLemma ct_suffix_any_grow: forall l1 l2,\n  ct_suffix l1 l2 ->\n  size l1 < size l2 ->\n  ct_suffix [::CTA_any & l1] l2.\nProof.\n  unfold ct_suffix => /=.\n  move => l1 l2 Hsuf Hsize.\n  move/andP in Hsuf; destruct Hsuf as [_ Hcompat].\n  apply/andP; split => //=.\n  move: l1 l2 Hsize Hcompat.\n  induction l1 using last_ind => //=; move => l2; case/lastP: l2 => [|l2 x']; intros => //.\n  - rewrite -> size_rcons in *.\n    replace (_-_) with (size l2); last by lias.\n    remember (drop (size l2) _) as tail.\n    assert (size tail = 1).\n    { subst. rewrite size_drop size_rcons. by lias. }\n    do 2 destruct tail => //=.\n    by destruct c.\n  - repeat rewrite size_rcons in Hsize.\n    rewrite drop_rcons in Hcompat; last by repeat rewrite size_rcons; lias.\n    rewrite drop_rcons; last by repeat rewrite size_rcons; lias.\n    apply ct_list_compat_rcons in Hcompat.\n    destruct Hcompat.\n    repeat rewrite size_rcons in H0.\n    replace (_-_) with (size l2 - size l1) in H0; last by lias.\n    apply IHl1 in H0; eauto.\n    repeat rewrite size_rcons.\n    rewrite - rcons_cons.\n    by apply ct_list_compat_rcons.\nQed.\n    \nLemma ct_suffix_any_1: forall l,\n  size l > 0 ->\n  ct_suffix [::CTA_any] l.\nProof.\n  move => l H.\n  destruct l => //=.\n  unfold ct_suffix, ct_list_compat => /=.\n  destruct (_ -1) eqn: Hsize => //.\n  - destruct l => //=. apply/andP.\n    split => //. by destruct c.\n  - assert (size (drop n l) = 1).\n    { rewrite size_drop. by lias. }\n    simpl. remember (drop n l) as l'.\n    do 2 destruct l' => //=.\n    by destruct c0.\nQed.\n\nLemma ct_list_compat_self: forall l,\n  ct_list_compat l l.\nProof.\n  induction l => //.\n  unfold all2.\n  apply/andP; split => //.\n  by destruct a => //=.\nQed.\n\nLemma ct_suffix_self: forall l,\n  ct_suffix l l.\nProof.\n  move => l.\n  unfold ct_suffix => /=.\n  apply/andP; split => //.\n  rewrite subnn.\n  rewrite drop0.\n  by apply ct_list_compat_self.\nQed.\n\nLemma ct_suffix_suffix: forall l1 l2,\n  ct_suffix (to_ct_list l2) (to_ct_list (l1 ++ l2)).\nProof.\n  move => l1 l2.\n  unfold ct_suffix.\n  apply/andP; split => //; repeat rewrite size_map; rewrite size_cat => //.\n  - by lias.\n  - unfold to_ct_list. rewrite map_cat.\n    replace (size l1 + size l2 - size l2) with (size l1); last by lias.\n    rewrite drop_size_cat; last by rewrite size_map.\n    by apply ct_list_compat_self.\nQed.\n\nLemma ct_suffix_prefix: forall l1 l2 l3,\n  ct_suffix (l1 ++ l2) l3 ->\n  ct_suffix l2 l3.\nProof.\n  unfold ct_suffix; intros.\n  move/andP in H; rewrite size_cat in H; destruct H.\n  apply/andP; split; first by lias.\n  unfold ct_list_compat in *.\n  move : l2 l3 H H0.\n  induction l1 => //; intros.\n  destruct l3 => //.\n  simpl in H.\n  apply IHl1; first by lias.\n  rewrite -> drop_nth with (x0 := a) in H0; last by lias.\n  simpl in H0.\n  move/andP in H0; destruct H0.\n  replace (_-_) with (size l3 - (size l1 + size l2)) in H1; last by lias.\n  simpl.\n  by replace (_-_) with ((size l3 - (size l1 + size l2)).+1); last by lias.\nQed.\n  \nLemma ct_suffix_extend: forall l1 l2 l3,\n  ct_suffix l1 l2 ->\n  ct_suffix l1 (l3 ++ l2).\nProof.\n  unfold ct_suffix.\n  move => l1 l2 l3 H.\n  move/andP in H; destruct H as [H1 H2].\n  apply/andP; split; first by rewrite size_cat; lias.\n  rewrite size_cat.\n  rewrite drop_cat.\n  replace (size l3 + size l2 - size l1 < size l3) with false; last by lias.\n  replace (size l3 + size l2 - size l1 - size l3) with (size l2 - size l1); last by lias.\n  assumption.\nQed.\n\nLemma ct_suffix_size: forall ct1 ct2,\n  ct_suffix ct1 ct2 ->\n  size ct1 <= size ct2.\nProof.\n  move => ct1 ct2.\n  unfold ct_suffix.\n  move => H.\n  move/andP in H; destruct H as [H _].\n  by repeat rewrite size_map in H.\nQed.\n\nLemma upd_label_overwrite: forall C loc lab ret lab',\n  upd_label (upd_local_label_return C loc lab ret) lab'\n  = upd_local_label_return C loc lab' ret.\nProof.\n  move => C loc lab ret lab'.\n  unfold upd_label.\n  unfold upd_local_label_return. by auto.\nQed.\n\nLemma consume_empty: forall l,\n  consume l [::] = l.\nProof.\n  move => l.\n  by destruct l => //=; rewrite ct_suffix_empty; rewrite subn0; rewrite take_size.\nQed.\n\nLemma produce_empty: forall l,\n  produce l (CT_type [::]) = l.\nProof.\n  move => l.\n  unfold produce.\n  by destruct l => //=; rewrite cats0.\nQed.\n\nLemma produce_empty_top: forall l,\n  l <> CT_bot ->\n  produce l (CT_top_type [::]) = CT_top_type [::].\nProof.\n  move => l.\n  unfold produce.\n  by destruct l.\nQed.\n\nLemma type_update_empty_cons: forall l ct,\n  type_update l [::] ct = produce l ct.\nProof.\n  move => l.\n  unfold type_update. by rewrite consume_empty.\nQed.\n\nLemma type_update_empty_prod: forall l ts,\n  type_update l ts (CT_type [::]) = consume l ts.\nProof.\n  move => l ts.\n  unfold type_update. by rewrite produce_empty.\nQed.\n  \nLtac simplify_hypothesis Hb :=\n  repeat match type of Hb with\n  | is_true (es_is_trap _) => move/es_is_trapP: Hb => Hb\n  | ?b = true => fold (is_true b) in Hb\n  | (_ == _) = false => move/eqP in Hb\n  | context C [size (rev _)] => rewrite size_rev in Hb\n  | context C [take _ (rev _)] => rewrite take_rev in Hb\n  | context C [rev (rev _)] => rewrite revK in Hb\n  | context C [true && _] => rewrite Bool.andb_true_l in Hb\n  | context C [_ && true] => rewrite Bool.andb_true_r in Hb\n  | context C [false || _] => rewrite Bool.orb_false_l in Hb\n  | context C [_ || false] => rewrite Bool.orb_false_r in Hb\n  (* It looks really like a bad idea to unfold type_update in general. *)\n(*  | context C [type_update _ _] => unfold type_update in Hb; try simpl in Hb*)\n  | context C [ct_suffix [::] _] => rewrite ct_suffix_empty in Hb; try simpl in Hb\n  | context C [ct_suffix [::CTA_any] (_::_)] => rewrite ct_suffix_any_1 in Hb => //; try simpl in Hb\n  | context C [ct_suffix ?l ?l] => rewrite ct_suffix_self in Hb => //; try simpl in Hb\n  | context C [size (map _ _)] => rewrite size_map in Hb\n  | context C [size (_ ++ _)] => rewrite size_cat in Hb\n  | context C [size (to_ct_list _)] => rewrite size_ct_list in Hb\n  | context C [?x - 0] => rewrite subn0 in Hb; simpl in Hb\n  | context C [?x - ?x] => rewrite subnn in Hb; simpl in Hb\n  | context C [take (size ?x) ?x] => rewrite take_size in Hb; simpl in Hb\n  | context C [drop (size ?x) ?x] => rewrite drop_size in Hb; simpl in Hb\n  | context C [take 0 ?x] => rewrite take0 in Hb; simpl in Hb\n  | context C [drop 0 ?x] => rewrite drop0 in Hb; simpl in Hb\n  | context C [produce _ _] => unfold produce in Hb; simpl in Hb\n  | context C [ match ?u with | Unop_i _ => _ | Unop_f _ => _ end ] => destruct u => //=\n  | context C [ match ?b with | Binop_i _ => _ | Binop_f _ => _ end ] => destruct b => //=\n  | context C [ match ?r with | Relop_i _ => _ | Relop_f _ => _ end ] => destruct r => //=\n  | context C [ match ?c with | CVO_convert => _ | _ => _ end ] => destruct c => //=\n  | context C [ if ?expr then _ else _ ] => let if_expr := fresh \"if_expr\" in destruct expr eqn:if_expr => //=; simpl in Hb => //=\n  | context C [ match ?expr with | Some _ => _ | None => _ end ] => let match_expr := fresh \"match_expr\" in destruct expr eqn:match_expr => //=; simpl in Hb => //=\n  | exists _, _ /\\ _ => let tx := fresh \"tx\" in\n                        let Hsuffix := fresh \"Hsuffix\" in\n                        let Hbet := fresh \"Hbet\" in\n                        destruct Hb as [tx [Hsuffix Hbet]]\n  | is_true true => clear Hb\n  | is_true false => exfalso; apply: notF; apply: Hb\n  | is_true (_ == _) => move/eqP in Hb\n  | is_true (_ && _) => move/andP in Hb; destruct Hb\n  | is_true (_ || _) => move/orP in Hb; destruct Hb\n  | ?x = ?x => clear Hb\n  | _ = _ => rewrite Hb in *; subst => //=\n  | _ => simpl in Hb => /=\n         end.\n\nLtac simplify_goal :=\n  repeat match goal with H: _ |- _ => progress simplify_hypothesis H end.\n\nLemma CT_top_empty_consume: forall tf,\n  consume (CT_top_type [::]) tf = CT_top_type [::].\nProof.\n  move => tf. unfold consume.\n  destruct tf => //=.\n  by rewrite ct_suffix_empty.\nQed.\n\nDefinition populate_ct_aux_single (cta: checker_type_aux): value_type :=\n  match cta with\n  | CTA_any => T_i32\n  | CTA_some vt => vt\n  end.\n\nDefinition populate_ct_aux (l: list checker_type_aux): list value_type :=\n  map populate_ct_aux_single l.\n\nDefinition populate_ct (ct: checker_type) : list value_type :=\n  match ct with\n  | CT_type tn => tn\n  | CT_top_type tn => populate_ct_aux tn\n  | CT_bot => [::]\n  end.\n\nLtac resolve_bet:=\n  repeat match goal with\n         | |- be_typing _ [::] (Tf ?tx ?tx) =>\n           apply bet_weakening_empty_both; apply bet_empty => //\n         | H: be_typing ?C ?bes (Tf ?tn ?tm) |- be_typing ?C (_ :: ?bes) (Tf _ ?tm) =>\n           eapply bet_composition_front; last by apply H\n         | H: is_true ?expr |- context C [ if ?expr then _ else _ ] =>\n           idtac H; rewrite H => //=\n         end.\n\nLtac auto_rewrite_cond:=\n  repeat match goal with\n         | H: is_true ?expr |- context C [ ?expr ] =>\n           rewrite H => //=\n         | H: ?x <> ?y |- context C [?x != ?y ] =>\n           move/eqP in H; rewrite H => //=\n         | H: is_true (Nat.eqb ?x ?y) |- _ =>\n           move/eqP in H; rewrite H => //=\n         | H: is_true (b_e_type_checker _ _ _) |- _ => simpl in H => //=\n         | |- context C [ ?x == ?x ] =>\n           rewrite eq_refl => //=\n         | |- context C [ true && true ] =>\n           unfold andb => //=\n         | |- context C [ct_suffix [::] _] => rewrite ct_suffix_empty => //=\n         | |- context C [ct_suffix [::CTA_any] (_::_)] => rewrite ct_suffix_any_1 => //=\n         | |- context C [ct_suffix ?l ?l] => rewrite ct_suffix_self => //=\n         | |- context C [ct_suffix ?l (?l)%list] => rewrite ct_suffix_self => //=\n         | |- context C [size (to_ct_list _)] => rewrite size_ct_list => //=\n         | |- context C [?x - ?x] => rewrite subnn => //=\n         | |- context C [?x - 0] => rewrite subn0 => //=\n         | |- context C [take 0 _] => rewrite take0 => //=\n         | |- context C [take (size ?x) ?x] => rewrite take_size => //=\n         | |- context C [drop 0 _] => rewrite drop0 => //=\n         | |- context C [take (drop ?x) ?x] => rewrite drop_size => //=\n         | |- context C [_ :: (tc_label _)] => rewrite - cat1s => //=\n         | |- context C [_ ++ [::]] => rewrite cats0 => //=\n         | |- context C [size (_ ++ _)] => rewrite size_cat => //=\n         | |- context C [size (_ ++ _)%list] => rewrite size_cat => //=\n         | |- context C [?x + ?n - ?n] => replace (x + n - n) with x; last by lias => //=\n         | |- context C [match ?f with | (Tf _ _) => _ end ] => destruct f => //=\n(*         | |- context C [type_update _ _] => unfold type_update => //=*)\n         | H: match ?expr with | _ => _ end = CT_type _ |- _ => let Hexpr := fresh \"Hexpr\" in destruct expr eqn: Hexpr => //=\n         | H: match ?expr with | _ => _ end = CT_top_type _ |- _ => let Hexpr := fresh \"Hexpr\" in destruct expr eqn: Hexpr => //=\n         | H: option_map _ _ = _ |- _ => unfold option_map in H\n         | H: Some _ = Some _ |- _ => inversion H; subst; clear H => //=\n         | H: CT_type _ = CT_type _ |- _ => inversion H; subst; clear H => //=\n         | H: is_true (plop2 _ _ _) |- _ => unfold plop2 in H => //=\n         | H: is_true (List.nth_error _ _ == _) |- _ => move/eqP in H; rewrite H => //=\n         | H: is_true (_ == _) |- _ => move/eqP in H\n         | H: ?x = ?x |- _ => clear H\n         | H: _ = _ |- _=> progress (rewrite H; subst => //=)\n         | _ => simplify_goal => //=; (try rewrite ct_suffix_suffix => //=); (try rewrite ct_suffix_self => //=); (try subst => //=)\n         end.\n\nLemma populate_ct_aux_suffix: forall l,\n  ct_suffix l (to_ct_list (populate_ct_aux l)).\nProof with auto_rewrite_cond.\n  induction l => //=.\n  unfold ct_suffix => /=.\n  apply/andP; split.\n  - repeat rewrite size_map. by lias.\n  - unfold ct_list_compat.\n    unfold ct_suffix, ct_list_compat, to_ct_list, populate_ct_aux in IHl...\n    repeat rewrite size_map.\n    rewrite subnn.\n    simpl.\n    destruct a => //=.\n    by apply/andP.\nQed.\n\nLemma populate_ct_agree: forall l,\n  l <> CT_bot ->\n  c_types_agree l (populate_ct l).\nProof.\n  intros.\n  destruct l => //=.\n  by apply populate_ct_aux_suffix.\nQed.\n\nLemma type_update_prefix: forall l1 l2 l3 cons prod,\n  type_update (CT_type l1) cons prod = CT_type l2 ->\n  type_update (CT_type (l3 ++ l1)) cons prod = CT_type (l3 ++ l2).\nProof.\n  unfold type_update, produce, consume.\n  move => l1 l2 l3 cons prod H.\n  auto_rewrite_cond.\n  unfold to_ct_list.\n  rewrite map_cat.\n  rewrite ct_suffix_extend => //.\n  rewrite take_cat.\n  assert (size cons <= size l1); first by apply ct_suffix_size in Hexpr1; rewrite size_map in Hexpr1.\n  replace (_ < _) with false; last by lias.\n  replace (_ + _ - _ - _) with (size l1 - size cons); last by lias.\n  by rewrite catA.\nQed.\n\nLemma type_update_prefix_top: forall l1 l2 l3 cons prod,\n  type_update (CT_type l1) cons prod = CT_top_type l2 ->\n  type_update (CT_type (l3 ++ l1)) cons prod = CT_top_type l2.\nProof.\n  unfold type_update, produce, consume.\n  move => l1 l2 l3 cons prod H.\n  auto_rewrite_cond.\n  unfold to_ct_list.\n  rewrite map_cat.\n  by rewrite ct_suffix_extend => //.\nQed.\n\nLemma check_rcons: forall es e C ts,\n  check C (es ++ [::e]) ts = check_single C (check C es ts) e.\nProof.\n  by induction es => //=.\nQed.\n    \nLemma check_single_notop: forall C ct ts e,\n  check_single C ct e = CT_type ts ->\n  exists ts', ct = CT_type ts'.\nProof with auto_rewrite_cond.\n  move => C ct ts e.\n  move : C ct ts.\n  induction e; move => C ct ts Htc; destruct ct; auto_rewrite_cond; try (unfold type_update in Htc); try by eexists...\nQed.\n  \nLemma check_single_bot: forall C e,\n  check_single C CT_bot e = CT_bot.\nProof.\n  move => C e.\n  by destruct e => //=.\nQed.\n  \nLemma check_single_weaken: forall C e ts ts2 ts0,\n  check_single C (CT_type ts) e = CT_type ts0 ->\n  check_single C (CT_type (ts2 ++ ts)) e = CT_type (ts2 ++ ts0).\nProof with auto_rewrite_cond.\n  move => C e.\n  move : C.\n  induction e; move => C ts ts2 ts0 Htc; simpl in Htc => //=; simplify_goal; auto_rewrite_cond; simplify_goal; subst => //=; try by apply type_update_prefix...\n  - do 3 destruct ts => //=; clear H.\n    (* Numerical disaster *)\n    rewrite length_is_size; rewrite size_cat.\n    replace (_ < _) with true => /=; last by lias.\n    repeat (rewrite List.nth_error_app2; last by rewrite length_is_size; lias).\n    repeat rewrite length_is_size.\n    replace (_ + _ - 2 - _) with (size ts + 1); last by lias.\n    replace (_ + _ - 3 - _) with (size ts); last by lias.\n    replace (_ - 2) with (length ts + 1) in H0; last by lias.\n    replace (_ - 3) with (length ts) in H0; last by lias.\n    rewrite length_is_size in H0.\n    rewrite H0.\n    rewrite eq_refl.\n    unfold to_ct_list.\n    rewrite map_cat.\n    rewrite ct_suffix_extend => //.\n    rewrite take_cat.\n    replace (_ < _) with false; last by lias.\n    replace (_ + _ - _ - _) with (size ts + 1); last by lias.\n    repeat f_equal => //=.\n    replace (size ts + 1) with (1 + size ts); last by lias.\n    simpl.\n    by f_equal.\n  - destruct f => //=.\n    simplify_goal.\n    by apply type_update_prefix.\nQed.\n    \nLemma check_single_weaken_top: forall C e ts ts2 ts0,\n  check_single C (CT_type ts) e = CT_top_type ts0 ->\n  check_single C (CT_type (ts2 ++ ts)) e = CT_top_type ts0.\nProof with auto_rewrite_cond.\n  move => C e.\n  move : C.\n  induction e; move => C ts ts2 ts0 Htc; simpl in Htc => //=; simplify_goal; auto_rewrite_cond => //=; try (destruct f); simplify_goal; by erewrite type_update_prefix_top; eauto...\nQed.\n    \nLemma check_weaken: forall C es ts ts2 ts0,\n  check C es (CT_type ts) = CT_type ts0 ->\n  check C es (CT_type (ts2 ++ ts)) = CT_type (ts2 ++ ts0).\nProof.\n  move => C es.\n  move: C.\n  (* It's much easier to do induction from the right side due to how check works. *)\n  induction es using List.rev_ind => //=; move => C ts ts2 ts0 Htc; first by inversion Htc.\n  rewrite check_rcons in Htc.\n  rewrite check_rcons.\n  assert (exists ts', (check C es (CT_type ts)) = CT_type ts') as [ts3 Htc2]; first by eapply check_single_notop; eauto.\n  rewrite Htc2 in Htc.\n  erewrite IHes; eauto.\n  by apply check_single_weaken.\nQed.\n  \nLemma check_weaken_top: forall C es ts ts2 ts0,\n  check C es (CT_type ts) = CT_top_type ts0 ->\n  check C es (CT_type (ts2 ++ ts)) = CT_top_type ts0.\nProof.\n  move => C es.\n  move: C.\n  induction es using List.rev_ind => //=; move => C ts ts2 ts0 Htc.\n  rewrite check_rcons in Htc.\n  rewrite check_rcons.\n  destruct (check C es (CT_type ts)) eqn:Htc2; simpl in Htc => //=.\n  - by erewrite IHes; eauto.\n  - erewrite check_weaken; eauto.\n    by erewrite check_single_weaken_top; eauto.\n  - by rewrite check_single_bot in Htc.\nQed.\n    \nLemma same_lab_h_condition: forall C ts l,\n  all (fun i: nat => (i < length (tc_label C)) && plop2 C i ts) l ->\n  same_lab_h l (tc_label C) ts = Some ts.\nProof.\n  move => C ts l.\n  move: C ts.\n  induction l => //=.\n  move => C ts H.\n  move/andP in H; destruct H as [H1 H2].\n  move/andP in H1; destruct H1 as [H1 H3].\n  replace (length (tc_label C) <= a) with false; last by lias.\n  move/ltP in H1.\n  unfold plop2 in H3.\n  move/eqP in H3.\n  rewrite H3.\n  rewrite eq_refl.\n  by apply IHl.\nQed.\n\nLemma same_lab_h_all: forall C ts l,\n  same_lab_h l (tc_label C) ts = Some ts ->\n  all (fun i: nat => (i < length (tc_label C)) && plop2 C i ts) l.\nProof.\n  move => C ts l.\n  move: C ts.\n  induction l => //=.\n  move => C ts H.\n  destruct (length (tc_label C) <= a) eqn:Hsize => //=.\n  destruct (List.nth_error (tc_label C)) eqn:Hnth => //=.\n  destruct (l0 == ts) eqn:Heq => //=.\n  move/eqP in Heq; subst.\n  apply/andP; split; last by apply IHl.\n  apply/andP; split; first by lias.\n  unfold plop2.\n  by rewrite Hnth.\nQed.\n  \nLemma same_lab_h_rec: forall x l C ts,\n  same_lab_h (x :: l) (tc_label C) ts = Some ts ->\n  same_lab_h l (tc_label C) ts = Some ts.\nProof.\n  move => x l C ts H.\n  simpl in H.\n  destruct (length (tc_label C) <= x) => //=.\n  destruct (List.nth_error (tc_label C) x) => //=.\n  destruct (l0 == ts) eqn:Heq => //=.\n  move/eqP in Heq. by subst.\nQed.\n\nLemma same_lab_h_consistent: forall l lab ts ts',\n  same_lab_h l lab ts' = Some ts ->\n  ts = ts'.\nProof.\n  induction l => //=; intros; first by inversion H.\n  destruct (length lab <= a) => //=.\n  destruct (List.nth_error lab a) => //=.\n  destruct (l0 == ts') eqn:Heq => //=.\n  move/eqP in Heq; subst.\n  by apply IHl in H.\nQed.\n\nLemma same_lab_same_lab_h: forall l lab ts,\n  same_lab l lab = Some ts ->\n  same_lab_h l lab ts = Some ts.\nProof.\n  move => l lab ts H.\n  unfold same_lab in H.\n  destruct l => //=.\n  destruct (length lab <= n) eqn:Hsize => //=.\n  destruct (List.nth_error lab n) eqn: Hnth => //=.\n  rewrite H.\n  replace l0 with ts => //=; first by rewrite eq_refl.\n  by apply same_lab_h_consistent in H.\nQed.\n\nLemma ct_list_compat_trans: forall ts1 ts2 ts,\n  ct_list_compat (to_ct_list ts) ts1 ->\n  ct_list_compat (to_ct_list ts) ts2 ->\n  ct_list_compat ts1 ts2.\nProof.\n  move => ts1.\n  induction ts1; move => ts2 ts H1 H2; destruct ts2, ts => //=.\n  simpl in *.\n  move/andP in H1; destruct H1.\n  move/andP in H2; destruct H2.\n  apply/andP; split.\n  - destruct c, a => //=.\n    move/eqP in H; move/eqP in H1.\n    subst.\n    by apply/eqP.\n  by eapply IHts1; eauto.\nQed.\n\nLemma ct_suffix_take: forall l1 l2 n,\n  ct_suffix l1 l2 ->\n  n <= size l1 ->\n  ct_suffix (take (size l1 - n) l1) (take (size l2 - n) l2).\nProof with auto_rewrite_cond.\n  induction l1 using last_ind; case/lastP => [|l2' x'] => //=; intros.\n  - by apply ct_suffix_empty.\n  - by destruct l1 => //=.\n  - rewrite size_rcons in H0.\n    destruct n => //=.\n    + repeat rewrite subn0.\n      by repeat rewrite take_size.\n    + repeat rewrite size_rcons.\n      repeat rewrite subSS.\n      apply ct_suffix_rcons in H; destruct H.\n      repeat rewrite - cats1.\n      repeat rewrite take_cat.\n      destruct n => //=...\n      * by destruct (size l1 < size l1), (size l2' < size l2') => //=.\n      * assert (size l1 - n.+1 < size l1); first by lias...\n        assert (size l1 <= size l2'); first by unfold ct_suffix in H1; move/andP in H1; destruct H1.\n        assert (size l2' - n.+1 < size l2'); first by lias...\n        by apply IHl1.\nQed.\n\nLemma ct_list_compat_cat: forall l1 l2 l3 l4,\n  ct_list_compat l1 l2 ->\n  ct_list_compat l3 l4 ->\n  ct_list_compat (l1 ++ l3) (l2 ++ l4).\nProof.\n  move => l1.\n  induction l1 => //=; move => l2 l3 l4 Hct1 Hct2; destruct l2 => //=.\n  move/andP in Hct1; destruct Hct1 as [H ?].\n  rewrite H => /=.\n  by apply IHl1.\nQed.\n          \nLemma ct_list_compat_extend: forall l1 l2 l3,\n  ct_list_compat l1 l2 ->\n  ct_list_compat (l1 ++ l3) (l2 ++ l3).\nProof.\n  intros.\n  apply ct_list_compat_cat => //.\n  by apply ct_list_compat_self.\nQed.\n\nLemma ct_list_compat_take: forall l1 l2 n,\n  ct_list_compat l1 l2 ->\n  ct_list_compat (take n l1) (take n l2).\nProof.\n  move => l1.\n  induction l1 => //=; move => l2 n H; destruct l2 => //=.\n  move/andP in H; destruct H as [H1 H2].\n  destruct n => //=.\n  apply/andP; split => //.\n  by apply IHl1.\nQed.\n\nLemma ct_list_compat_drop: forall l1 l2 n,\n  ct_list_compat l1 l2 ->\n  ct_list_compat (drop n l1) (drop n l2).\nProof.\n  move => l1.\n  induction l1 => //=; move => l2 n H; destruct l2 => //=.\n  move/andP in H; destruct H as [H1 H2].\n  destruct n => //=.\n  apply/andP; split => //.\n  by apply IHl1.\nQed.\n\nLemma ct_list_compat_drop_shift: forall l1 l2 n a b c1 c2,\n  ct_list_compat (drop n l1) l2 ->\n  a < size l1 ->\n  b < size l2 ->\n  a = b + n ->\n  ct_compat (nth c1 l1 a) (nth c2 l2 b).\nProof.\n  induction l1 as [| x l1'] => //=; move => l2 n a b c1 c2 Hcompat Hs1 Hs2 Hsum; destruct l2, a, b => //=.\n  - destruct n => //. simpl in Hcompat.\n    move/andP in Hcompat. by destruct Hcompat.\n  - rewrite add0n in Hsum.\n    subst.\n    replace c with (nth c1 (c :: l2) 0) => //.\n    by eapply IHl1'; eauto.\n  - eapply IHl1'; eauto.\n    destruct n => //=.\n    + simpl in Hcompat.\n      move/andP in Hcompat.\n      destruct Hcompat.\n      by rewrite drop0.\n    + rewrite -> drop_nth with (x0 := CTA_any) in Hcompat; last by lias.\n      simpl in Hcompat.\n      move/andP in Hcompat.\n      by destruct Hcompat.\nQed.\n\nLemma ct_list_nth_type: forall l c n,\n  n < size l ->\n  exists t, nth c (to_ct_list l) n = CTA_some t.\nProof.\n  induction l; destruct n => //=; move => Hsize.\n  - by eexists.\n  - by eapply IHl; eauto.\nQed.\n\n(*\n  We need the mutual ct type to be from ct_list, since CTA_any destroys transitivity. \n*)\nLemma ct_compat_mutual: forall ts1 ts2 ts_mutual ts,\n  ts_mutual = to_ct_list ts ->\n  size ts1 <= size ts_mutual ->\n  size ts2 <= size ts_mutual ->\n  ct_list_compat (drop (size ts_mutual - size ts1) ts_mutual) ts1 ->\n  ct_list_compat (drop (size ts_mutual - size ts2) ts_mutual) ts2 ->\n  size ts1 <= size ts2 ->\n  ct_list_compat (drop (size ts2 - size ts1) ts2) ts1.\nProof.\n  move => ts1.\n  induction ts1; move => ts2 ts_mutual ts Hnany Hs1 Hs2 Hct1 Hct2 Hsize => //=.\n  - rewrite subn0. by rewrite drop_size.\n  - destruct ts2 => //=.\n    destruct ts_mutual, ts => //=.\n    simpl in *.\n    inversion Hnany; subst; clear Hnany.\n    destruct (size ts2 == size ts1) eqn: Heq1 => //=; move/eqP in Heq1.\n    + rewrite Heq1.\n      rewrite Heq1 in Hct2.\n      rewrite subnn.\n      destruct (size (to_ct_list ts) == size ts1) eqn: Heq2 => //=; move/eqP in Heq2.\n      * rewrite Heq2 in Hct1, Hct2.\n        rewrite subnn in Hct1, Hct2.\n        replace (CTA_some v :: to_ct_list ts) with (to_ct_list (v :: ts)) in * => //=.\n        rewrite drop0 in Hct1, Hct2.\n        eapply ct_list_compat_trans in Hct1; eauto.\n        by simpl in Hct1.\n      * destruct (_-_) eqn:Hsub.\n        -- assert ((size (to_ct_list ts)).+1 <= (size ts1).+1); first by lias.\n           simpl in *. by lias.\n        -- unfold to_ct_list in Hct1, Hct2.\n           simpl in Hct1, Hct2.\n           rewrite - map_drop in Hct1, Hct2.\n           eapply ct_list_compat_trans in Hct1; eauto.\n           by simpl in Hct1.\n    + destruct ((size ts2).+1-(size ts1).+1) eqn:Hsub.\n      * assert ((size ts2).+1 <= (size ts1).+1); first by lias.\n        simpl in *. by lias.\n      * assert (size ts1 < size (to_ct_list ts)); first by lias.\n        destruct (_ - _) eqn:Hsub2; first by lias.\n        destruct (size (to_ct_list ts) == size ts2) eqn: Heq3 => //=; move/eqP in Heq3.\n        -- rewrite Heq3 in Hct2.\n           rewrite subnn in Hct2.\n           rewrite Heq3 in Hsub2.\n           assert (n0 = n); first by lias.\n           subst.\n           simpl in Hct2.\n           move/andP in Hct2; destruct Hct2 as [_ Hct2].\n           eapply ct_list_compat_drop in Hct2.\n           unfold to_ct_list in Hct1, Hct2.\n           simpl in Hct1, Hct2.\n           rewrite - map_drop in Hct1.\n           rewrite - map_drop in Hct2.\n           by eapply ct_list_compat_trans in Hct1; eauto.\n        -- destruct ((size (to_ct_list ts)).+1 - (size ts2).+1) eqn:Hsub4.\n           ++ assert ((size (to_ct_list ts)).+1 <= (size ts2).+1); first by lias.\n              simpl in *. by lias.\n           ++ assert (n < size ts2); first by lias.\n              assert (n0 < size (to_ct_list ts)); first by lias.\n              assert (n1 < size (to_ct_list ts)); first by lias.\n              eapply drop_nth with (x0 := CTA_any) in H0.\n              eapply drop_nth with (x0 := CTA_any) in H1.\n              eapply drop_nth with (x0 := CTA_any) in H2.\n              rewrite - Hsub in H0.\n              rewrite - Hsub2 in H1.\n              rewrite - Hsub4 in H2.\n              rewrite H0.\n              simpl in Hct1.\n              rewrite H1 in Hct1.\n              simpl in Hct2.\n              rewrite H2 in Hct2.\n              simpl in *.\n              rewrite -> subSS in *.\n              move/andP in Hct1; destruct Hct1 as [Hcs1 Hct1].\n              move/andP in Hct2; destruct Hct2 as [Hcs2 Hct2].\n              apply/andP; split.\n              ** assert (ct_compat (nth CTA_any (to_ct_list ts) n0) (nth CTA_any ts2 n)) as Hcs3.\n                 eapply ct_list_compat_drop_shift; eauto; by lias.\n                 destruct (nth CTA_any ts2 n), a => //=.\n                 assert (exists v, nth CTA_any (to_ct_list ts) n0 = CTA_some v) as Hv; first eapply ct_list_nth_type; eauto; first by unfold to_ct_list in Hsub2; rewrite size_map in Hsub2; lias.\n                 destruct Hv as [vt Hv].\n                 rewrite -> Hv in *.\n                 simpl in *.\n                 move/eqP in Hcs1.\n                 move/eqP in Hcs3.\n                 subst.\n                 by apply/eqP.\n              (* Finally the IH applies here... *)\n              ** eapply IHts1; by eauto.\nQed.\n\nLemma ct_suffix_mutual_compat: forall ts1 ts2 ts_mutual ts,\n  ts_mutual = to_ct_list ts ->\n  ct_suffix ts1 ts_mutual ->\n  ct_suffix ts2 ts_mutual ->\n  size ts1 <= size ts2 ->\n  ct_list_compat (drop (size ts2 - size ts1) ts2) ts1.\nProof with auto_rewrite_cond.\n  move => ts1 ts2 ts_mutual ts Hnany Hsuffix1 Hsuffix2 Hsize.\n  subst.\n  unfold ct_suffix in *...\n  by eapply ct_compat_mutual; auto_rewrite_cond; eauto.\nQed.\n\nLemma ct_suffix_mutual_suffix: forall ts1 ts2 ts_mutual ts,\n  ts_mutual = to_ct_list ts ->\n  ct_suffix ts1 ts_mutual ->\n  ct_suffix ts2 ts_mutual ->\n  size ts1 <= size ts2 ->\n  ct_suffix ts1 ts2.\nProof with auto_rewrite_cond.\n  move => ts1 ts2 ts_mutual ts Hnany Hsuffix1 Hsuffix2 Hsize.\n  subst.\n  unfold ct_suffix in *...\n  by eapply ct_compat_mutual; auto_rewrite_cond; eauto.\nQed.\n\nLemma le_neq_lt: forall a b,\n    a <= b ->\n    a <> b ->\n    a < b.\nProof.\n  by lias.\nQed.\n\nLemma sub_if: forall a b,\n  (if a-b < a then a-b else a) = a-b.\nProof.\n  move => a b.\n  destruct (a-b<a) eqn:H; by lias.\nQed.\n  \nLemma type_update_agree_suffix: forall ts cons prod ts2 topt,\n  c_types_agree (type_update (CT_type ts) cons prod) ts2 ->\n  ct_suffix topt (to_ct_list ts) ->\n  c_types_agree (type_update (CT_top_type topt) cons prod) ts2.\nProof with auto_rewrite_cond.\n  move => ts cons prod ts2 topt Hct Hsuffix.\n  unfold type_update, c_types_agree, produce, consume, ct_suffix, to_ct_list in * => /=...\n  destruct (size cons <= size topt) eqn:Hsize => //=.\n  - remember Hsize as Hsize_ct; clear HeqHsize_ct.\n    apply ct_compat_mutual with (ts := ts) (ts_mutual := to_ct_list ts) in Hsize; eauto...\n    rewrite size_map.\n    destruct prod => //=...\n    apply/andP; split.\n    + repeat rewrite size_take.\n      rewrite size_map.\n      repeat rewrite sub_if.\n      by lias.\n    + repeat rewrite size_take.\n      repeat rewrite size_map.\n      repeat rewrite sub_if.\n      rewrite - map_drop.\n      rewrite drop_cat.\n      rewrite size_take.\n      rewrite sub_if.\n      replace (_ - _ + _ - _) with (size ts - size topt); last by lias.\n      move/leP in Hsize_ct.\n      destruct (size ts - size topt == size ts - size cons) eqn:Heq.\n      * replace (_ - _ < _ - _) with false => //=; last by lias.\n        replace (_ - _ - _) with 0; last by lias.\n        rewrite drop0.\n        assert (size topt = size cons); first by lias.\n        rewrite -> H3 in *.\n        rewrite subnn.\n        rewrite take0 => //=.\n        by apply ct_list_compat_self.\n      * assert (size ts - size topt <= size ts - size cons); first by lias.\n        move/eqP in Heq.\n        apply le_neq_lt in H3 => //.\n        rewrite H3.\n        rewrite map_cat.\n        apply ct_list_compat_extend.\n        replace (size ts - size cons) with ((size topt - size cons) + (size ts - size topt)); last by lias.\n        rewrite - take_drop.\n        rewrite map_take.\n        apply ct_list_compat_take.\n        by rewrite map_drop.\n  - assert (size topt <= size cons) as Hsize2; first by lias.\n    rewrite Hsize2.\n    apply ct_compat_mutual with (ts := ts) (ts_mutual := to_ct_list ts) in Hsize2 => //...\n    rewrite size_map.\n    destruct prod => //=...\n    repeat rewrite size_map.\n    rewrite size_take.\n    rewrite sub_if.\n    apply/andP; split; first by lias.\n    rewrite map_cat map_take.\n    replace (_ - _ + _ - _) with (size ts - size cons); last by lias.\n    rewrite drop_cat.\n    rewrite size_take size_map.\n    rewrite sub_if => /=.\n    replace (_ < _) with false; last by lias.\n    rewrite subnn drop0.\n    by apply ct_list_compat_self.\nQed.\n\nLemma ct_suffix_any_take_2: forall ts,\n  2 < size ts ->\n  ct_suffix [::CTA_any] (to_ct_list (take (size ts - 2) ts)).\nProof.\n  move => ts H.\n  apply ct_suffix_any_1.\n  rewrite size_ct_list size_take sub_if.\n  by lias.\nQed.\n\nLemma ct_suffix_compat_index: forall l1 l2 n t1 t2,\n  ct_suffix l1 l2 ->\n  n >= 1 ->\n  n <= size l1 ->\n  List.nth_error l1 (length l1 - n) = Some t1 ->\n  List.nth_error l2 (length l2 - n) = Some t2 ->\n  ct_compat t1 t2.\nProof.\n  move => l1 l2 n t1 t2 Hsuf Hn Hsize Hn1 Hn2.\n  unfold ct_suffix in Hsuf.\n  move/andP in Hsuf; destruct Hsuf as [Hsize2 Hcompat].\n  rewrite length_is_size in Hn1.\n  rewrite length_is_size in Hn2.\n  apply nth_error_ssr with (x0 := t1) in Hn1.\n  apply nth_error_ssr with (x0 := t2) in Hn2.\n  apply ct_list_compat_drop_shift with (a := size l2 - n) (b := size l1 - n) (c1 := t2) (c2 := t1) in Hcompat; by [rewrite Hn1 Hn2 in Hcompat; apply ct_compat_symmetry | lias | lias | lias].\nQed.\n\nLemma ct_suffix_append_compat: forall l1 l2 l3 l4,\n  ct_suffix l1 l2 ->\n  ct_list_compat l3 l4 ->\n  ct_suffix (l1 ++ l3) (l2 ++ l4).\nProof with auto_rewrite_cond.\n  move => l1 l2 l3.\n  move : l1 l2.\n  induction l3 using last_ind; move => l1 l2 l4; case/lastP : l4 => [|l4 x'] => //=; move => Hsuf H...\n  - by destruct l4 => //=.\n  - by destruct l3 => //=.\n  - apply ct_list_compat_rcons in H.\n    destruct H.\n    repeat rewrite - rcons_cat.\n    apply ct_suffix_rcons; split => //.\n    by apply IHl3.\nQed.\n  \nLemma nth_to_ct_list: forall ts n x,\n  List.nth_error ts n = Some x ->\n  List.nth_error (to_ct_list ts) n = Some (CTA_some x).\nProof.\n  intros.\n  assert (n < length ts)%coq_nat as Hsize; first by rewrite - List.nth_error_Some; rewrite H.\n  apply nth_error_ssr with (x1 := x) in H.\n  assert (nth (CTA_some x) (to_ct_list ts) n = CTA_some x) as Hssr.\n  { unfold to_ct_list. rewrite -> nth_map with (x1 := x); last by lias. by rewrite H. }\n  by apply ssr_nth_error in Hssr; last by unfold to_ct_list; rewrite size_map; lias.\nQed.\n\nLemma select_return_top_suffix: forall c2 c3 ts topt topts,\n  select_return_top topt c2 c3 = CT_top_type topts ->\n  ct_suffix topt (to_ct_list ts) ->  \n  List.nth_error topt (length topt - 2) = Some c2 ->\n  List.nth_error topt (length topt - 3) = Some c3 ->\n  List.nth_error ts (length ts - 2) = List.nth_error ts (length ts - 3) ->\n  2 < length topt ->\n  2 < size ts ->\n  ct_suffix topts (to_ct_list (take (size ts - 2) ts)).\nProof with auto_rewrite_cond.\n  move => c2 c3 ts topt topts Hselect Hsuffix Hn2 Hn3 Hts3 Hsize1 Hsize2.\n  unfold select_return_top in Hselect.\n  destruct (List.nth_error ts (length ts-2)) eqn:Hts2; last by apply List.nth_error_None in Hts2; rewrite length_is_size in Hts2; lias.\n  symmetry in Hts3.\n  remember Hts3 as Hts3'; clear HeqHts3'.\n  apply nth_error_ssr with (x0 := v) in Hts3'.\n  apply nth_to_ct_list in Hts2.\n  apply nth_to_ct_list in Hts3.\n  replace (length ts) with (length (to_ct_list ts)) in Hts2; last by repeat rewrite length_is_size; unfold to_ct_list; rewrite size_map.\n  replace (length ts) with (length (to_ct_list ts)) in Hts3; last by repeat rewrite length_is_size; unfold to_ct_list; rewrite size_map.\n  eapply ct_suffix_compat_index in Hts2; eauto.\n  eapply ct_suffix_compat_index in Hts3; eauto.\n  assert (ct_suffix (take (size topt - 3) topt) (take (size (to_ct_list ts) - 3) (to_ct_list ts)))as Hsuffixm3; first by apply ct_suffix_take.\n  replace (size ts - 2) with ((size ts - 3).+1); last by lias.\n  rewrite -> take_nth with (x0 := v); last by lias.\n  replace (size (to_ct_list ts)) with (size ts) in Hsuffixm3; last by unfold to_ct_list; rewrite size_map.\n  destruct c2, c3 => //=; auto_rewrite_cond; inversion Hselect; subst; clear Hselect; repeat rewrite length_is_size; unfold to_ct_list; rewrite map_rcons; rewrite cats1; rewrite ct_suffix_rcons; rewrite map_take; split => //; by unfold ct_compat.\nQed.\n  \n(*\n  This seems to be a rather tedious single case.\n*)\nLemma type_update_select_agree: forall topt ts,\n  ct_suffix [::CTA_any; CTA_some T_i32] (to_ct_list ts) ->\n  ct_suffix topt (to_ct_list ts) ->\n  2 < length ts ->\n  List.nth_error ts (length ts-2) = List.nth_error ts (length ts-3) ->\n  c_types_agree (type_update_select (CT_top_type topt)) (take (size ts-2) ts).\nProof with auto_rewrite_cond.\n  move => topt ts Hs1 Hs2 Hsize Htype.\n  rewrite length_is_size in Hsize.\n  destruct topt => //=; first by apply ct_suffix_any_take_2...\n  destruct topt => //=...\n  - (* 1 *)\n    eapply ct_suffix_mutual_compat with (ts1 := [::c]) in Hs1...\n    destruct c => //=; auto_rewrite_cond; by apply ct_suffix_any_take_2...\n  - destruct topt => //=...\n    + (* 2 *)\n      eapply ct_suffix_mutual_compat with (ts1 := [::c; c0]) in Hs1...\n      assert (ct_suffix [::CTA_some T_i32] [::c; c0] = true) as H; first destruct c0 => //=...\n      unfold ct_suffix.\n      assert (ts = take (size ts - 3) ts ++ drop (size ts - 3) ts) as H2; first by rewrite cat_take_drop.\n      remember (drop (size ts-3) ts) as tail.\n      assert (size tail = 3) as Hsizetail.\n      { subst. rewrite size_drop. by lias. }\n      repeat destruct tail as [|? tail] => //=. clear Hsizetail.\n      apply/andP; split => //=.\n      * unfold to_ct_list.\n        rewrite size_map size_take sub_if.\n        by lias.\n      * rewrite -> H2 in *.\n        unfold to_ct_list.\n        rewrite size_map size_take sub_if size_cat size_take sub_if => //=.\n        rewrite map_take.\n        replace (size ts - 3 + 3 - 2 - 1) with (size ts - 3); last by lias.\n        replace (size ts - 3 + 3 - 2) with (1 + (size ts - 3)); last by lias.\n        rewrite - take_drop.\n        rewrite map_cat.\n        assert (size ts - 3 = size (to_ct_list (take (size ts - 3) ts))) as Hsize2.\n        { unfold to_ct_list. by rewrite size_map size_take sub_if. }\n        rewrite drop_size_cat => //.\n        simpl.\n        apply/andP; split => //.\n        destruct c => //=.\n        repeat rewrite length_is_size size_cat size_take sub_if in Htype.\n        simpl in Htype.\n        repeat (rewrite List.nth_error_app2 in Htype; last by (rewrite length_is_size size_take sub_if; lias)).\n        repeat rewrite length_is_size size_take sub_if in Htype.\n        replace (size ts - 3 + 3 - 2 - (size ts - 3))%coq_nat with 1 in Htype; last by lias.\n        replace (size ts - 3 + 3 - 3 - (size ts - 3))%coq_nat with 0 in Htype; last by lias.\n        simpl in Htype.\n        inversion Htype; subst; clear Htype.\n        unfold ct_suffix, to_ct_list in Hs2...\n        rewrite size_take sub_if in H1...\n        replace (size ts - 3 + 3 - 2) with (1 + (size ts - 3)) in H1; last by lias.\n        rewrite map_cat map_take in H1. simpl in H1.\n        rewrite drop_cat in H1.\n        repeat rewrite size_take size_map sub_if in H1.\n        replace (_ < _) with false in H1; last by lias.\n        replace (1+_-_) with 1 in H1; last by lias.\n        simpl in H1.\n        by auto_rewrite_cond.\n    + (* 3 *)\n      replace ((length topt).+3-3) with (length topt); last by lias.\n      destruct (List.nth_error [::c0, c1 & topt] (length topt)) eqn: Hl2; last by apply List.nth_error_None in Hl2; simpl in Hl2; lias.\n      destruct (List.nth_error [::c, c0, c1 & topt] (length topt)) eqn: Hl3; last by apply List.nth_error_None in Hl3; simpl in Hl3; lias.\n      assert (exists topts, select_return_top [::c, c0, c1 & topt] c2 c3 = CT_top_type topts) as Htopts.\n      { unfold select_return_top.\n        destruct c2, c3 => //=; try by eexists.\n        replace v with v0 => //=; first by rewrite eq_refl; eexists.\n        \n        destruct (List.nth_error ts (length ts-2)) eqn:Hts1; last by apply List.nth_error_None in Hts1; rewrite length_is_size in Hts1; lias.\n        symmetry in Htype.\n        \n        replace (length topt) with (length [::c, c0, c1 & topt] - 3) in Hl3; last by lias.\n        apply nth_error_ssr with (x0 := v1) in Htype.\n        repeat rewrite length_is_size in Htype.\n        assert (nth (CTA_some v1) (to_ct_list ts) (size ts - 3) = CTA_some v1) as Hts3ssr.\n        { unfold to_ct_list. rewrite -> nth_map with (x1 := v1); last by lias. by rewrite Htype. }\n        apply ssr_nth_error in Hts3ssr; last by unfold to_ct_list; rewrite size_map; lias.\n        eapply ct_suffix_compat_index with (l2 := to_ct_list ts) in Hl3; eauto; last by rewrite length_is_size; unfold to_ct_list; rewrite size_map; apply Hts3ssr.\n\n        replace (length topt) with (length [::c0, c1 & topt] - 2) in Hl2; last by lias.\n        apply nth_error_ssr with (x0 := v1) in Hts1.\n        repeat rewrite length_is_size in Hts1.\n        assert (nth (CTA_some v1) (to_ct_list ts) (size ts - 2) = CTA_some v1) as Hts2ssr.\n        { unfold to_ct_list. rewrite -> nth_map with (x1 := v1); last by lias. by rewrite Hts1. }\n        apply ssr_nth_error in Hts2ssr; last by unfold to_ct_list; rewrite size_map; lias.\n        eapply ct_suffix_compat_index with (l2 := to_ct_list ts) in Hl2; eauto.\n        2: { by apply ct_suffix_prefix with (l1 := [::c]). }\n        2: { rewrite length_is_size; unfold to_ct_list; rewrite size_map; apply Hts2ssr. }\n        simpl in *.\n\n        by auto_rewrite_cond.\n        }\n      destruct Htopts as [topts Htopts].\n      rewrite Htopts.\n      unfold type_update, produce...\n      replace (ct_suffix _ _) with true...\n      * eapply select_return_top_suffix; eauto.\n        simpl.\n        by replace (_-_) with (length topt); last by lias.\n      * eapply ct_suffix_mutual_suffix with (ts2 := [::c, c0, c1 & topt]) in Hs1; eauto.\n        by rewrite ct_suffix_any_grow => //.\nQed.\n\nLemma c_types_agree_suffix_single: forall l C ts ts2 e,\n  c_types_agree (check_single C (CT_type ts) e) ts2 ->\n  ct_suffix l (to_ct_list ts) ->\n  c_types_agree (check_single C (CT_top_type l) e) ts2.\nProof with auto_rewrite_cond.\n  move => l C ts ts2 e.\n  move: l C ts ts2.\n  induction e; move => topt C ts ts2 H Hsuffix; simpl in H => //=; auto_rewrite_cond; simplify_goal; (try destruct f); (try destruct c); (try by eapply type_update_agree_suffix; eauto) => //=...\n  - by apply type_update_select_agree.\n  - simplify_goal.\n    by eapply type_update_agree_suffix; eauto.\nQed.\n    \nLemma c_types_agree_weakening: forall C es ts ts' ts2,\n  c_types_agree (check C es (CT_type ts)) ts2 ->\n  c_types_agree (check C es (CT_type (ts' ++ ts))) (ts' ++ ts2).\nProof.\n  unfold c_types_agree.\n  move => C es ts ts' ts2.\n  destruct (check C es (CT_type ts)) eqn:Htc => //=; move => H.\n  - erewrite check_weaken_top; eauto.\n    unfold to_ct_list.\n    rewrite map_cat.\n    by rewrite ct_suffix_extend.\n  - move/eqP in H. subst.\n    erewrite check_weaken; by eauto.\nQed.\n\nLemma ct_list_compat_to_ct: forall tn tm,\n  ct_list_compat (to_ct_list tn) (to_ct_list tm) ->\n  tn = tm.\nProof with auto_rewrite_cond.\n  induction tn; destruct tm; move => H => //=...\n  f_equal. by apply IHtn.\nQed.\n\nLemma ct_list_compat_symmetry: forall l1 l2,\n  ct_list_compat l1 l2 ->\n  ct_list_compat l2 l1.\nProof with auto_rewrite_cond.\n  induction l1; destruct l2; move => H => //=...\n  apply ct_compat_symmetry in H.\n  rewrite H => /=.\n  by apply IHl1.\nQed.\n  \n\nLemma ct_list_compat_cat1: forall l1 l2 l3,\n  ct_list_compat (l2 ++ l3) l1 <->\n  ct_list_compat l2 (take (size l2) l1) /\\ ct_list_compat l3 (drop (size l2) l1).\nProof with auto_rewrite_cond.\n  move => l1 l2.\n  move : l1.\n  induction l2 => //=; move => l1 l3.\n  - rewrite take0 drop0.\n    split => //=.\n    by move => [_ ?].\n  - destruct l1 => //=; first by split => //=; move => [? _].\n    split; move => Hct...\n    + by apply IHl2.\n    + destruct Hct...\n      by apply IHl2.\nQed.\n\nLemma ct_list_compat_cat2: forall l1 l2 l3,\n  ct_list_compat l1 (l2 ++ l3) <->\n  ct_list_compat (take (size l2) l1) l2 /\\ ct_list_compat (drop (size l2) l1) l3.\nProof.\n  move => l1 l2 l3.\n  split; move => Hct.\n  - apply ct_list_compat_symmetry in Hct.\n    apply ct_list_compat_cat1 in Hct; destruct Hct.\n    apply ct_list_compat_symmetry in H.\n    apply ct_list_compat_symmetry in H0.\n    by split.\n  - destruct Hct.\n    apply ct_list_compat_symmetry in H.\n    apply ct_list_compat_symmetry in H0.\n    apply ct_list_compat_symmetry.\n    by apply ct_list_compat_cat1.\nQed.\n\nLemma consume_top_not_bot: forall cts tn,\n  size cts >= size tn ->\n  consume (CT_top_type cts) tn <> CT_bot ->\n  ct_list_compat (drop (size cts - size tn) cts) tn.\nProof with auto_rewrite_cond.\n  move => cts tn Hsize H.\n  unfold consume in H...\n  - unfold ct_suffix in *...\n  - unfold ct_suffix in *...\n    assert (size tn = size cts) as Hsizeeq; first by lias.\n    rewrite -> Hsizeeq, subnn, drop0 in *.\n    by apply ct_list_compat_symmetry.\nQed.\n\nLemma consume_top_not_bot_short: forall cts tn,\n  size cts <= size tn ->\n  consume (CT_top_type cts) tn <> CT_bot ->\n  ct_list_compat cts (drop (size tn - size cts) tn).\nProof with auto_rewrite_cond. \n  move => cts tn Hsize H.\n  unfold consume in H...\n  - unfold ct_suffix in *...\n    assert (size tn = size cts) as Hsizeeq; first by lias.\n    by rewrite -> Hsizeeq, subnn, drop0 in *.\n  - unfold ct_suffix in *...\n    by apply ct_list_compat_symmetry.\nQed.\n\nLemma consume_type_not_bot: forall cts tn,\n  consume (CT_type cts) tn <> CT_bot ->\n  ct_list_compat (drop (size cts - size tn) (to_ct_list cts)) tn.\nProof with auto_rewrite_cond.\n  move => cts tn H.\n  unfold consume in H...\n  unfold ct_suffix in *...\nQed.\n\nLemma type_update_type_agree: forall tm tn' tm' cts,\n  c_types_agree (type_update cts (to_ct_list tn') (CT_type tm')) tm ->\n  exists lp, c_types_agree cts (lp ++ tn') /\\ tm = lp ++ tm'.\nProof with auto_rewrite_cond.\n  move => tm tn' tm' cts H.\n  exists (take (size tm - size tm') tm).\n  destruct cts as [ctst | cts | ] => //=...\n  - unfold type_update in *; auto_rewrite_cond; unfold ct_suffix in * => //=...\n    + rewrite -> size_take, sub_if in *.\n      remember (size tm - size tm') as x.\n      remember (size ctst - size tn') as y.\n      apply ct_list_compat_cat2 in H0.\n      rewrite size_take Heqy sub_if in H0.\n      rewrite -Heqy in H0.\n      destruct H0 as [Hct1 Hct2].\n      unfold to_ct_list in Hct2.\n      repeat rewrite - map_drop in Hct2.\n      apply ct_list_compat_to_ct in Hct2.\n      rewrite drop_drop in Hct2.\n      replace (_+(_-_)) with x in Hct2; last by lias.\n      split; last by rewrite - Hct2; rewrite cat_take_drop.\n      apply/andP; split; first by lias.\n      unfold to_ct_list.\n      rewrite map_cat.\n      rewrite drop_cat size_map size_take Heqx sub_if.\n      rewrite - Heqx.\n      destruct y. (* if it's non-zero, then we have x + size tn' - size csts < x *)\n      * assert (size ctst = size tn') as Hsize; first by lias.\n        rewrite -> Hsize in *; simpl in *.\n        replace (_ < _) with false; last by lias.\n        repeat rewrite take0 in Hct1.\n        replace (x + size tn' - size tn' - x) with 0; last by lias.\n        rewrite -> drop0 in *.\n        by apply ct_list_compat_symmetry.\n      * replace (_ < _) with true; last by lias.\n        apply ct_list_compat_symmetry in H2.\n        apply ct_list_compat_cat1.\n        rewrite size_drop size_map size_take Heqx sub_if.\n        rewrite - Heqx.\n        replace (x - (x + size tn' - size ctst)) with (y.+1); last by lias.\n        split => //.\n        unfold to_ct_list in Hct1.\n        rewrite take_drop in Hct1.\n        replace (_ + (_ - (_ + _))) with x in Hct1; last by lias.\n        rewrite map_take.\n        replace (x + size tn' - size ctst) with (size tm - (y.+1 + size tm')) => //.\n        by lias.\n    + unfold to_ct_list in H0; rewrite - map_drop in H0.\n      apply ct_list_compat_to_ct in H0.\n      remember (size tm - size tm') as x.\n      split; last by rewrite - H0; rewrite cat_take_drop.\n      rewrite Heqx.\n      rewrite size_take sub_if.\n      apply/andP; split; first by lias.\n      remember (size tn' - size ctst) as y.\n      rewrite - Heqx.\n      replace (x + size tn' - size ctst) with (x+y); last by lias.\n      unfold to_ct_list in *.\n      rewrite - map_drop in H2.\n      rewrite - map_drop.\n      rewrite drop_cat size_take Heqx sub_if.\n      replace (_<_) with false; last by lias.\n      by replace (size tm - _ + _ - _) with y; last by lias.\n  - unfold type_update in *...\n    unfold ct_suffix in *...\n    unfold to_ct_list in H0; rewrite - map_drop in H0.\n    apply ct_list_compat_to_ct in H0.\n    remember (size cts - size tn') as x.\n    rewrite size_take Heqx sub_if.\n    split.\n    + rewrite take_cat size_take sub_if.\n      replace (_ < _) with false; last by lias.\n      rewrite subnn take0 cats0.\n      rewrite - Heqx -H0; by rewrite cat_take_drop.\n    + rewrite take_cat size_take sub_if.\n      replace (_ < _) with false; last by lias.\n      by rewrite subnn take0 cats0.\nQed.\n\nLemma consume_type_agree: forall tm tn' cts,\n  c_types_agree (consume cts (to_ct_list tn')) tm ->\n  c_types_agree cts (tm ++ tn').\nProof.\n  move => tm tn' cts Hct.\n  rewrite - type_update_empty_prod in Hct.\n  apply type_update_type_agree in Hct; destruct Hct as [tn [H1 H2]].\n  by rewrite cats0 in H2; subst.\nQed.\n        \nLtac simplify_type_update :=\n  (try rewrite -> type_update_empty_cons in * );\n  (try rewrite -> type_update_empty_prod in * );\n  (try rewrite -> consume_empty in * );\n  (try rewrite -> produce_empty in * );\n  (try rewrite -> produce_empty_top in * ).\n\nLemma check_single_top_top: forall C cts e,\n  check_single C (CT_top_type cts) e <> CT_bot ->\n  exists cts', check_single C (CT_top_type cts) e = CT_top_type cts'.\nProof with auto_rewrite_cond.\n  move => C cts e H.\n  remember (check_single C (CT_top_type cts) e) as cts'.\n  destruct cts' => //; first by eexists.\n  symmetry in Heqcts'.\n  apply check_single_notop in Heqcts'.\n  by destruct Heqcts'.\nQed.\n\nLemma ct_suffix_1_impl: forall tm,\n  ct_suffix [::CTA_any] (to_ct_list tm) ->\n  exists v tm', tm = tm' ++ [::v].\nProof.\n  move => tm.\n  case/lastP: tm => [|tm x] => //=.\n  move => H.\n  exists x, tm.\n  by rewrite cats1.\nQed.\n  \nLemma type_update_select_agree_bet: forall C cts tm,\n  c_types_agree (type_update_select cts) tm ->\n  exists tn, c_types_agree cts tn /\\ be_typing C [::BI_select] (Tf tn tm).\nProof with auto_rewrite_cond.\n  move => C cts tm Hct.\n  unfold type_update_select in Hct...\n  destruct cts => //.\n  - move:Hct.\n    rewrite length_is_size.\n    case/lastP : l => [|l x1] => //=.\n    + move => Hct.\n      apply ct_suffix_1_impl in Hct.\n      destruct Hct as [v [tm' ?]]; subst.\n      exists (tm' ++ [::v; v; T_i32]); split; first by apply ct_suffix_empty.\n      apply bet_weakening.\n      by apply bet_select.\n    + rewrite size_rcons.\n      case/lastP : l => [|l x2] => //=.\n      * move => Hct.\n        unfold type_update, produce, consume in Hct.\n        destruct x1; simpl in Hct.\n        {\n          apply ct_suffix_1_impl in Hct.\n          destruct Hct as [v [tm' ?]]; subst.\n          exists (tm' ++ [::v; v; T_i32]); split; first by apply ct_suffix_any_1; rewrite size_ct_list size_cat; lias.\n          apply bet_weakening.\n          by apply bet_select.\n        }\n        { destruct v => //=.\n          simpl in Hct.\n          apply ct_suffix_1_impl in Hct.\n          destruct Hct as [v [tm' ?]]; subst.\n          exists (tm' ++ [::v; v; T_i32]); split.\n          - unfold ct_suffix...\n            apply/andP; split; first by lias.\n            unfold to_ct_list.\n            rewrite map_cat drop_cat size_map.\n            replace (_<_) with false; last by lias.\n            by replace (_+_-_-_) with 2; last by lias.\n          - apply bet_weakening.\n            by apply bet_select.\n        }\n      * rewrite size_rcons.\n        case/lastP : l => [|l x3] => //=.\n        {\n          move => H...\n          unfold ct_suffix in *...\n          clear H1.\n          move : H H0.\n          case/lastP : tm => [|tm x'] => //=.\n          rewrite size_rcons.\n          rewrite - cats1.\n          move => _ Hct.\n          replace (_-_) with (size tm) in Hct; last by lias.\n          unfold to_ct_list in Hct.\n          rewrite map_cat drop_cat size_map subnn drop0 in Hct.\n          replace (_<_) with false in Hct; last by lias.\n          simpl in Hct.\n          exists (tm ++ [::x'; x'; T_i32]).\n          rewrite size_ct_list size_cat.\n          split.\n          - apply/andP; split => /=; first by simpl; lias.\n            unfold to_ct_list.\n            rewrite map_cat drop_cat size_map.\n            replace (_<_) with false; last by lias.\n            replace (_+_-_-_) with 1; last by lias.\n            simpl.\n            destruct x2, x1 => //=...\n          - apply bet_weakening.\n            by apply bet_select.\n        }\n        {\n          rewrite size_rcons.\n          repeat rewrite -cats1.\n          repeat rewrite -catA.\n          intros...\n          assert (List.nth_error (l ++ [::x3;x2;x1]) (1+size l) = Some c) as Hnth => //.\n          clear match_expr.\n          apply nth_error_ssr with (x0 := c) in Hnth.\n          apply nth_error_ssr with (x0 := c) in match_expr0.\n          replace (_-_) with (size l) in match_expr0; last by lias.\n          rewrite nth_cat subnn in match_expr0.\n          replace (_<_) with false in match_expr0; last by lias.\n          simpl in match_expr0; subst.\n          rewrite nth_cat in Hnth.\n          replace (_<_) with false in Hnth; last by lias.\n          replace (_-_) with 1 in Hnth; last by lias.\n          simpl in Hnth; subst.\n          unfold select_return_top, type_update in Hct...\n          - repeat rewrite length_is_size size_cat in Hct.\n            replace (size l + size _ - 3) with (size l) in Hct; last by simpl; lias.\n            rewrite take_cat subnn take0 cats0 take_size in Hct.\n            replace (_<_) with false in Hct; last by lias.\n            unfold ct_suffix in if_expr...\n            replace (size l + 3 - 3) with (size l) in H0; last by lias.\n            rewrite drop_cat subnn drop0 in H0.\n            replace (_<_) with false in H0; last by lias.\n            auto_rewrite_cond.\n            move : Hct.\n            case/lastP: tm => [|tm x] => //=; move => Hct.\n            + destruct c, c0; unfold c_types_agree, ct_suffix; auto_rewrite_cond; by destruct l => //=.\n            + replace (_+_-_) with (size l) in Hct; last by lias.\n              rewrite take_cat subnn take0 cats0 in Hct.\n              replace (_<_) with false in Hct; last by lias.\n              exists (tm ++ [::x; x; T_i32]).\n              repeat rewrite cats1 in Hct.\n              split; last by rewrite - cats1; apply bet_weakening; apply bet_select.\n              destruct c , c0 => //=; auto_rewrite_cond; unfold to_ct_list in Hct; rewrite map_rcons in Hct; (try rewrite cats1 in Hct); apply ct_suffix_rcons in Hct; destruct Hct; unfold to_ct_list; rewrite map_cat; apply ct_suffix_append_compat => //=...\n          - unfold ct_suffix in *; destruct l; auto_rewrite_cond; last by lias.\n            replace (ct_compat c0 CTA_any) with true in if_expr; last by destruct c0.\n            replace (ct_compat c CTA_any) with true in if_expr; last by destruct c.\n            simpl in if_expr.\n            destruct x1 => //=...\n        }\n  - move: Hct.\n    case/lastP : l => [|l x1] => //=.\n    case/lastP : l => [|l x2] => //=.\n    case/lastP : l => [|l x3] => //=.\n    move => Hct...\n    repeat rewrite length_is_size in H0.\n    repeat rewrite length_is_size in H.\n    repeat rewrite size_rcons in H0.\n    repeat rewrite size_rcons in H.\n    destruct (List.nth_error _ ((size l).+3 - 2)) eqn:Hnth => //=; last by apply List.nth_error_None in Hnth; rewrite length_is_size in Hnth; repeat rewrite size_rcons in Hnth; lias.\n    symmetry in H0.\n    apply nth_error_ssr with (x0 := v) in Hnth.\n    apply nth_error_ssr with (x0 := v) in H0.\n    repeat rewrite nth_rcons in Hnth.\n    repeat rewrite size_rcons in Hnth.\n    replace ((size l).+3 - 2 < (size l).+2) with true in Hnth; last by lias.\n    replace ((size l).+3 - 2 < (size l).+1) with false in Hnth; last by lias.\n    replace (_ == _) with true in Hnth; last by lias.\n    subst.\n    repeat rewrite - cats1.\n    repeat rewrite -catA. simpl.\n    exists (l ++ [::x3; v; x1]).\n    split => //.\n    rewrite take_cat size_cat.\n    replace (_ < size l) with false; last by simpl; lias.\n    apply bet_weakening.\n    replace (_ + _ - _ - _) with 1; last by simpl; lias.\n    simpl.\n    repeat rewrite nth_rcons in H0.\n    repeat rewrite size_rcons in H0.\n    replace ((size l).+3 - 3 < (size l).+2) with true in H0; last by lias.\n    replace ((size l).+3 - 3 < (size l).+1) with true in H0; last by lias.\n    replace ((size l).+3 - 3 < (size l)) with false in H0; last by lias.\n    replace ((size l).+3 - 3 == (size l)) with true in H0; last by lias.\n    subst.\n    repeat rewrite - cats1 in if_expr0.\n    repeat rewrite - catA in if_expr0.\n    simpl in if_expr0.\n    unfold ct_suffix in if_expr0...\n    unfold to_ct_list in H1.\n    rewrite map_cat in H1...\n    rewrite drop_cat size_map in H1.\n    replace (_<_) with false in H1; last by lias.\n    replace (_+_-_-_) with 1 in H1; last by lias.\n    simpl in H1...\n    apply bet_select.\nQed.\n    \nLemma tc_to_bet_br: forall cts l,\n  consume cts (to_ct_list l) <> CT_bot ->\n  exists tn, c_types_agree cts (tn ++ l).\nProof with auto_rewrite_cond.\n  move => cts l Hconsume.\n  destruct cts as [ctst | cts | ]=> //.\n  - destruct (size ctst <= size l) eqn:Hsize.\n    + apply consume_top_not_bot_short in Hconsume; last by rewrite size_ct_list.\n      rewrite size_ct_list in Hconsume.\n      exists [::] => //=.\n      unfold ct_suffix...\n      by apply ct_list_compat_symmetry.\n    + apply consume_top_not_bot in Hconsume; last by rewrite size_ct_list; lias.\n      rewrite size_ct_list in Hconsume.\n      exists (populate_ct_aux (take (size ctst - size l) ctst))...\n      unfold ct_suffix...\n      unfold populate_ct_aux; rewrite size_map size_take sub_if.\n      apply/andP; split; first by lias.\n      replace (_ - _ + _ - _) with 0; last by lias.\n      rewrite drop0.\n      unfold to_ct_list.\n      rewrite map_cat.\n      rewrite - map_comp.\n      remember (take _ ctst) as cl.\n      rewrite - (cat_take_drop (size ctst - size l) ctst).\n      subst.\n      apply ct_list_compat_cat; last by apply ct_list_compat_symmetry.\n      apply ct_list_compat_symmetry.\n      remember (take _ _) as cl.\n      clear.\n      induction cl => //=; destruct a...\n    + apply consume_type_not_bot in Hconsume.\n      rewrite size_ct_list in Hconsume.\n      exists (take (size cts - size l) cts)...\n      unfold to_ct_list in Hconsume.\n      rewrite - map_drop in Hconsume.\n      apply ct_list_compat_to_ct in Hconsume...\n      remember (size cts - size l) as x.\n      rewrite - Hconsume.\n      by rewrite cat_take_drop.\nQed.\n\nLtac fold_remember_check :=\n  repeat match goal with\n         | H: context C [List.fold_left (check_single ?C) ?l ?ct] |- _ =>\n              fold (check C l ct) in H; let res_check := fresh \"res_check\" in remember (check C l ct) as res_check\n         end.\n\n(* Measure for induction on basic_instruction *)\nFixpoint be_size_single (be: basic_instruction): nat :=\n  match be with\n  | BI_block _ l => 1 + (List.fold_left addn (map be_size_single l)) 1 + size l\n  | BI_loop _ l => 1 + (List.fold_left addn (map be_size_single l)) 1 + size l\n  | BI_if _ l1 l2 => 1 + ((List.fold_left addn (map be_size_single l1) 1) + size l1) + ((List.fold_left addn (map be_size_single l2) 1) + size l2)\n  | _ => 1\n  end.\n\nDefinition be_size_list (bes: list basic_instruction) :=\n  (List.fold_left addn (map be_size_single bes) 1) + size bes.\n\nLemma fold_left_rcons {A B: Type} (f: A -> B -> A) (l: list B) (x: B) (acc: A):\n  List.fold_left f (rcons l x) acc = f (List.fold_left f l acc) x.\nProof.\n  move: f l x acc.\n  by induction l => //=.\nQed.\n  \nLemma be_size_list_rcons bes e:\n  be_size_list (rcons bes e) = be_size_single e + (be_size_list bes) + 1.\nProof.\n  unfold be_size_list.\n  rewrite map_rcons size_rcons.\n  rewrite fold_left_rcons.\n  by lias.\nQed.\n\n(*\n  The first part of the conjunction is what is required, but we need to prove it by simultaneous\n  induction on the following two lemmas.\n  Coq is reluctant to accept that the mutual recursive proof actually terminates, so we use the\n  meausre we defined above for that purpose.\n*)\nLemma tc_to_bet_conj d:\n  ( forall C cts bes tm cts',\n  be_size_list bes <= d ->\n  check C bes cts = cts' ->\n  c_types_agree cts' tm ->\n  exists tn, c_types_agree cts tn /\\ be_typing C bes (Tf tn tm)) /\\\n  ( forall C cts tm e cts',\n  be_size_single e <= d ->\n  check_single C cts e = cts' ->\n  c_types_agree cts' tm ->\n  exists tn, c_types_agree cts tn /\\ be_typing C ([:: e]) (Tf tn tm)).\nProof with auto_rewrite_cond.\n  strong induction d => //=.\n  split.\n  (* List *) \n  - move => c cts bes.\n    move: c cts.\n    induction bes as [| bes e] using last_ind => //=; move => C cts tm cts' Hs Hct1 Hbetc.\n    + exists tm.\n      split => //...\n      by resolve_bet.\n    + rewrite be_size_list_rcons in Hs.\n      rewrite <- Hct1 in *.\n      rewrite - cats1 in Hbetc.\n      rewrite - cats1.\n      rewrite check_rcons in Hbetc.\n      remember (check C bes cts) as besct.\n      remember (check_single C besct e) as ect.\n      symmetry in Heqect.\n      symmetry in Heqbesct.\n      assert (be_size_single e < d)%coq_nat as Hmeasure; first by lias.\n      assert (be_size_list bes < d)%coq_nat as Hmeasure2; first by lias.\n      specialize H with (be_size_single e) as Hs1.\n      apply Hs1 in Hmeasure.\n      destruct Hmeasure as [_ Hmeasure].\n      eapply Hmeasure in Heqect => //; last by apply Hbetc.\n      destruct Heqect as [tn' [Hct Hbet]].\n      eapply IHbes in Heqbesct => //; (try apply Hct); last by apply/leP; lias.\n      destruct Heqbesct as [tn'' [Hcts Hbets]].\n      exists tn''; split => //.\n      eapply bet_composition; last by apply Hbet.\n      by apply Hbets.\n  (* Single *)\n  - destruct e => //=; (try destruct f as [tn' tm']); auto_rewrite_cond; move => ? Hs Hct Hct2; simplify_type_update => //...\n    + exists (populate_ct cts); split; by [apply populate_ct_agree | apply bet_unreachable].\n    + exists tm; split => //.\n      apply bet_weakening_empty_both.\n      by apply bet_nop.\n    + destruct cts => //=; clear if_expr.\n      * move: Hct2. case/lastP : l => [| l x] => //=; move => Hsuf.\n        { exists (tm ++ [::T_i32]); split; first by apply ct_suffix_empty.\n          apply bet_weakening_empty_2.\n          by apply bet_drop.\n        }\n        { exists (tm ++ [::populate_ct_aux_single x]).\n          split; last by apply bet_weakening_empty_2; apply bet_drop.\n          rewrite cats1.\n          unfold to_ct_list.\n          rewrite map_rcons.\n          apply ct_suffix_rcons.\n          split; first by destruct x => //=.\n          rewrite ct_suffix_any_1 in Hsuf; last by rewrite size_rcons.\n          rewrite - cats1 in Hsuf.\n          simpl in Hsuf.\n          rewrite size_cat take_cat in Hsuf.\n          simpl in Hsuf.\n          replace (size l + 1 - 1) with (size l) in Hsuf; last by lias.\n          rewrite subnn take_size cats0 in Hsuf.\n          by destruct (size l < size l) => //=.\n        }\n      * simpl in Hct2...\n        exists l; split => //.\n        move: if_expr. case/lastP: l => [|l x] => //=; move => _.\n        rewrite - cats1.\n        rewrite size_cat take_cat => /=.\n        replace (size l + 1 - 1) with (size l); last by lias.\n        rewrite take_size subnn cats0.\n        replace (size l < size l) with false; last by clear H; lias.\n        apply bet_weakening_empty_2.\n        by apply bet_drop.\n    + by apply type_update_select_agree_bet.\n    + fold_remember_check.\n      assert (be_size_list l < d)%coq_nat as Hmeasure; first by unfold be_size_list; lias.\n      apply H in Hmeasure.\n      destruct Hmeasure as [IH _].\n      eapply IH in if_expr0 => //; last by rewrite Heqres_check.\n      destruct if_expr0 as [tn'' [Hct1 Hbet]].\n      simpl in Hct1.\n      move/eqP in Hct1; subst.\n      apply bet_block in Hbet.\n      apply type_update_type_agree in Hct2.\n      destruct Hct2 as [lp [Hct1 Heq]]; subst.\n      exists (lp ++ tn''); split => //.\n      by apply bet_weakening.\n    + fold_remember_check.\n      assert (be_size_list l < d)%coq_nat as Hmeasure; first by unfold be_size_list; lias.\n      apply H in Hmeasure.\n      destruct Hmeasure as [IH _].\n      eapply IH in if_expr0 => //; last by rewrite Heqres_check.\n      destruct if_expr0 as [tn'' [Hct1 Hbet]].\n      simpl in Hct1.\n      move/eqP in Hct1; subst.\n      apply bet_loop in Hbet.\n      apply type_update_type_agree in Hct2.\n      destruct Hct2 as [lp [Hct1 Heq]]; subst.\n      exists (lp ++ tn''); split => //.\n      by apply bet_weakening.\n    + fold_remember_check.\n      fold (be_size_list l) in Hs.\n      fold (be_size_list l0) in Hs.\n      assert (be_size_list l < d)%coq_nat as Hmeasure1; first by lias.\n      assert (be_size_list l0 < d)%coq_nat as Hmeasure2; first by lias.\n      apply H in Hmeasure1.\n      destruct Hmeasure1 as [IH1 _].\n      apply H in Hmeasure2.\n      destruct Hmeasure2 as [IH2 _].\n      eapply IH1 in H0 => //; last by rewrite Heqres_check0.\n      eapply IH2 in H1 => //; last by rewrite Heqres_check.\n      destruct H0 as [tn1'' [Hctif1 Hbet1]].\n      destruct H1 as [tn2'' [Hctif2 Hbet2]].\n      simpl in *.\n      move/eqP in Hctif1; subst.\n      move/eqP in Hctif2; subst.\n      apply bet_if_wasm with (es1 := l) in Hbet2 => //.\n      apply type_update_type_agree in Hct2.\n      destruct Hct2 as [lp [Hct1 Heq]]; subst.\n      exists (lp ++ tn2'' ++ [::T_i32]); split => //.\n      by apply bet_weakening.\n    + unfold type_update in Hct2.\n      assert (consume cts (to_ct_list l) <> CT_bot) as Hconsume; first by destruct (consume _ _).\n      apply tc_to_bet_br in Hconsume.\n      destruct Hconsume as [tn Hcts].\n      exists (tn ++ l); split => //.\n      apply bet_br => //; by unfold plop2; rewrite match_expr.\n    + apply type_update_type_agree in Hct2.\n      destruct Hct2 as [tn' [Hctif Hbet]]. subst.\n      exists (tn' ++ l ++ [::T_i32]); split => //.\n      apply bet_weakening.\n      apply bet_br_if => //; by unfold plop2; rewrite match_expr.\n    + unfold type_update in Hct2.\n      assert (consume cts (to_ct_list (l0 ++ [::T_i32])) <> CT_bot) as Hconsume; first by destruct (consume _ _).\n      apply tc_to_bet_br in Hconsume.\n      destruct Hconsume as [tn Hcts].\n      exists (tn ++ l0 ++ [::T_i32]); split => //.\n      apply bet_br_table.\n      apply same_lab_h_all.\n      by apply same_lab_same_lab_h.\n    + unfold type_update in Hct2.\n      assert (consume cts (to_ct_list l) <> CT_bot) as Hconsume; first by destruct (consume _ _).\n      apply tc_to_bet_br in Hconsume.\n      destruct Hconsume as [tn Hcts].\n      exists (tn ++ l); split => //.\n      by apply bet_return.\n    + destruct f...\n      apply type_update_type_agree in Hct2.\n      destruct Hct2 as [tn' [Hct Hbet]]; subst.\n      exists (tn' ++ r); split => //=.\n      apply bet_weakening.\n      by apply bet_call.\n    + destruct f...\n      apply type_update_type_agree in Hct2.\n      destruct Hct2 as [tn' [Hct Hbet]]; subst.\n      exists (tn' ++ r ++ [::T_i32]); split => //=.\n      apply bet_weakening.\n      apply bet_call_indirect => //=.\n      by destruct (tc_table C) => //=.\n    + replace ([::]) with (to_ct_list [::]) in Hct2 => //=.\n      apply type_update_type_agree in Hct2.\n      destruct Hct2 as [tn' [Hct bet]]; subst.\n      rewrite cats0 in Hct.\n      exists tn'; split => //=.\n      apply bet_weakening_empty_1.\n      by apply bet_get_local.\n    + replace ([::CTA_some v]) with (to_ct_list [::v]) in Hct2 => //=.\n      apply type_update_type_agree in Hct2.\n      destruct Hct2 as [tn' [Hct bet]]; subst.\n      exists (tn' ++ [::v]); split => //.\n      apply bet_weakening.\n      by apply bet_set_local.\n    + replace ([::CTA_some v]) with (to_ct_list [::v]) in Hct2 => //=.\n      apply type_update_type_agree in Hct2.\n      destruct Hct2 as [tn' [Hct bet]]; subst.\n      exists (tn' ++ [::v]); split => //.\n      apply bet_weakening.\n      by apply bet_tee_local.\n    + replace ([::]) with (to_ct_list [::]) in Hct2 => //=.\n      apply type_update_type_agree in Hct2.\n      destruct Hct2 as [tn' [Hct bet]]; subst.\n      rewrite cats0 in Hct.\n      exists tn'; split => //=.\n      apply bet_weakening_empty_1.\n      apply bet_get_global => //=; by auto_rewrite_cond.\n    + replace ([::CTA_some (tg_t g)]) with (to_ct_list [::tg_t g]) in Hct2 => //=.\n      apply type_update_type_agree in Hct2.\n      destruct Hct2 as [tn' [Hct bet]]; subst.\n      exists (tn' ++ [::tg_t g]); split => //.\n      apply bet_weakening.\n      by eapply bet_set_global; eauto.\n    + replace ([::CTA_some T_i32]) with (to_ct_list [::T_i32]) in Hct2 => //=.\n      apply type_update_type_agree in Hct2.\n      destruct Hct2 as [tn' [Hct bet]]; subst.\n      exists (tn' ++ [::T_i32]); split => //.\n      apply bet_weakening.\n      apply bet_load => //; by destruct C.(tc_memory) => //=.\n    + replace ([::CTA_some T_i32; CTA_some v]) with (to_ct_list [::T_i32; v]) in Hct2 => //.\n      apply consume_type_agree in Hct2.\n      exists (tm ++ [::T_i32; v]); split => //.\n      apply bet_weakening_empty_2.\n      apply bet_store => //; by destruct C.(tc_memory) => //=.\n    + assert (c_types_agree (type_update cts (to_ct_list [::]) (CT_type [::T_i32])) tm) as Hct3.\n      * simplify_type_update.\n        by unfold produce => //=.\n      * apply type_update_type_agree in Hct3.\n        destruct Hct3 as [tn' [Hct bet]]; subst.\n        rewrite cats0 in Hct.\n        exists tn'; split => //.\n        apply bet_weakening_empty_1.\n        apply bet_current_memory => //; by destruct C.(tc_memory) => //=.\n    + replace ([::CTA_some T_i32]) with (to_ct_list [::T_i32]) in Hct2 => //=.\n      apply type_update_type_agree in Hct2.\n      destruct Hct2 as [tn' [Hct bet]]; subst.\n      exists (tn' ++ [::T_i32]); split => //.\n      apply bet_weakening.\n      apply bet_grow_memory => //; by destruct C.(tc_memory) => //=.\n    + assert (c_types_agree (type_update cts (to_ct_list [::]) (CT_type [::typeof v])) tm) as Hct3.\n      * simplify_type_update.\n        by unfold produce => //=.\n      * apply type_update_type_agree in Hct3.\n        destruct Hct3 as [tn' [Hct bet]]; subst.\n        rewrite cats0 in Hct.\n        exists tn'; split => //.\n        apply bet_weakening_empty_1.\n        by apply bet_const.\n    + replace ([::CTA_some v]) with (to_ct_list [::v]) in Hct2 => //=.\n      apply type_update_type_agree in Hct2.\n      destruct Hct2 as [tn' [Hct bet]]; subst.\n      exists (tn' ++ [::v]); split => //.\n      apply bet_weakening.\n      apply bet_unop.\n      destruct v => //=; by [apply Unop_i32_agree | apply Unop_i64_agree].\n    + replace ([::CTA_some v]) with (to_ct_list [::v]) in Hct2 => //=.\n      apply type_update_type_agree in Hct2.\n      destruct Hct2 as [tn' [Hct bet]]; subst.\n      exists (tn' ++ [::v]); split => //.\n      apply bet_weakening.\n      apply bet_unop.\n      destruct v => //=; by [apply Unop_f32_agree | apply Unop_f64_agree].\n    + replace ([::CTA_some v; CTA_some v]) with (to_ct_list [::v; v]) in Hct2 => //=.\n      apply type_update_type_agree in Hct2.\n      destruct Hct2 as [tn' [Hct bet]]; subst.\n      exists (tn' ++ [::v; v]); split => //.\n      apply bet_weakening.\n      apply bet_binop.\n      destruct v => //=; by [apply Binop_i32_agree | apply Binop_i64_agree].\n    + replace ([::CTA_some v; CTA_some v]) with (to_ct_list [::v; v]) in Hct2 => //=.\n      apply type_update_type_agree in Hct2.\n      destruct Hct2 as [tn' [Hct bet]]; subst.\n      exists (tn' ++ [::v; v]); split => //.\n      apply bet_weakening.\n      apply bet_binop.\n      destruct v => //=; by [apply Binop_f32_agree | apply Binop_f64_agree].\n    + replace ([::CTA_some v]) with (to_ct_list [::v]) in Hct2 => //=.\n      apply type_update_type_agree in Hct2.\n      destruct Hct2 as [tn' [Hct bet]]; subst.\n      exists (tn' ++ [::v]); split => //.\n      apply bet_weakening.\n      by apply bet_testop.\n    + replace ([::CTA_some v; CTA_some v]) with (to_ct_list [::v; v]) in Hct2 => //=.\n      apply type_update_type_agree in Hct2.\n      destruct Hct2 as [tn' [Hct bet]]; subst.\n      exists (tn' ++ [::v; v]); split => //.\n      apply bet_weakening.\n      apply bet_relop.\n      destruct v => //=; by [apply Relop_i32_agree | apply Relop_i64_agree].\n    + replace ([::CTA_some v; CTA_some v]) with (to_ct_list [::v; v]) in Hct2 => //=.\n      apply type_update_type_agree in Hct2.\n      destruct Hct2 as [tn' [Hct bet]]; subst.\n      exists (tn' ++ [::v; v]); split => //.\n      apply bet_weakening.\n      apply bet_relop.\n      destruct v => //=; by [apply Relop_f32_agree | apply Relop_f64_agree].\n    + replace ([::CTA_some v0]) with (to_ct_list [::v0]) in Hct2 => //=.\n      apply type_update_type_agree in Hct2.\n      destruct Hct2 as [tn' [Hct bet]]; subst.\n      exists (tn' ++ [::v0]); split => //.\n      apply bet_weakening.\n      unfold convert_cond in if_expr0...\n      apply bet_convert => //.\n      by move/eqP in H0.\n    + replace ([::CTA_some v0]) with (to_ct_list [::v0]) in Hct2 => //=.\n      apply type_update_type_agree in Hct2.\n      destruct Hct2 as [tn' [Hct bet]]; subst.\n      exists (tn' ++ [::v0]); split => //.\n      apply bet_weakening.\n      apply bet_reinterpret => //; by [ move/eqP in H0 | rewrite H2; apply/eqP].\nQed.\n\nLemma tc_to_bet_list: forall C cts bes tm cts',\n  check C bes cts = cts' ->\n  c_types_agree cts' tm ->\n  exists tn, c_types_agree cts tn /\\ be_typing C bes (Tf tn tm).\nProof.\n  intros.\n  specialize tc_to_bet_conj with (be_size_list bes).\n  move => H1.\n  destruct H1 as [H1 _].\n  by eapply H1; eauto.\nQed.\n\nLemma b_e_type_checker_reflects_typing:\n  forall C bes tf,\n    reflect (be_typing C bes tf) (b_e_type_checker C bes tf).\nProof with auto_rewrite_cond.\n  move => C bes tf.\n  destruct tf as [tn tm].\n  destruct (b_e_type_checker C bes (Tf tn tm)) eqn: Htc_bool.\n  - apply ReflectT.\n    unfold b_e_type_checker in Htc_bool.\n    fold (check C bes (CT_type tn)) in Htc_bool.\n    eapply tc_to_bet_list in Htc_bool; eauto.\n    by destruct Htc_bool as [x [Hagree Hbet]]; auto_rewrite_cond.\n  - apply ReflectF.\n    move => Hbet.\n    assert (b_e_type_checker C bes (Tf tn tm)) as H; (try by rewrite H in Htc_bool); clear Htc_bool.\n    induction Hbet; subst => //=; unfold type_update => //=; try destruct t, op; try by inversion H...\n    + unfold convert_cond...\n    + unfold same_lab => //=.\n      remember (ins ++ [::i]) as l.\n      rewrite - Heql.\n      destruct l => //=; first by destruct ins.\n      remember H as H2; clear HeqH2.\n      move/allP in H2.\n      assert (n \\in (ins ++ [::i])) as Hn; first by rewrite - Heql; rewrite mem_head.\n      apply H2 in Hn.\n      move/andP in Hn; destruct Hn as [H3 H4].\n      unfold plop2 in H4.\n      replace (length (tc_label C) <= n) with false; last by lias.\n      move/eqP in H4.\n      rewrite H4.\n      apply same_lab_h_condition in H.\n      replace (ins ++ [::i])%list with (ins ++ [::i]) in H; last by lias.\n      rewrite - Heql in H.\n      apply same_lab_h_rec in H.\n      rewrite H.\n      rewrite ct_suffix_suffix...\n    + destruct tf as [t1 t2] => //=...\n    + destruct (List.nth_error (tc_global C) i) => //=...\n    + unfold type_update => //=...\n    + unfold type_update => //=...\n    + by destruct (tc_table C) eqn:Hctable => //=.\n    + rewrite List.fold_left_app => //=.\n      unfold c_types_agree in IHHbet1.\n      destruct (List.fold_left _ es _) eqn:Htc => //=.\n      * by eapply c_types_agree_suffix_single; eauto.\n      * move/eqP in IHHbet1. by subst.\n    + by apply c_types_agree_weakening.\nQed.\n\nEnd Host.\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/type_checker_reflects_typing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2825035625210455}}
{"text": "From Coq Require Export Morphisms RelationClasses Setoid Program.Equality.\nFrom ITree Require Export ITree ITreeFacts Eq.Rutt Props.Finite.\nFrom Paco Require Import paco.\nFrom Coq Require Export Eqdep EqdepFacts.\nRequire Import Lia.\nRequire Export Refinement.\n\nImport Monads.\nImport MonadNotation.\nLocal Open Scope monad_scope.\n\nVariant conv_refF {E : Type -> Type} {R : Type} (F : itree_spec E R -> Prop) : itree_spec' E R -> Prop :=\n  | conv_ref_RetF r : conv_refF F (RetF r)\n  | conv_ref_TauF t : F t -> conv_refF F (TauF t)\n  | conv_ref_existsF (A : Type) (k : A -> itree_spec E R) :\n    (forall a, F (k a)) -> conv_refF F (VisF Spec_exists k)\n  | conv_ref_forallF (A : Type) (k : A -> itree_spec E R) :\n    A -> (forall a, F (k a)) -> conv_refF F (VisF Spec_forall k)\n.\n\nDefinition conv_ref_ {E : Type -> Type} {R : Type} (F : itree_spec E R -> Prop) (t : itree_spec E R) :=\n  conv_refF F (observe t).\n\nLemma monotone_conv_refF {E R} (ot : itree_spec' E R) sim sim'\n      (LE : sim <1= sim')\n      (IN : conv_refF sim ot) :\n  conv_refF sim' ot.\nProof. induction IN; constructor; auto. Qed.\n\nLemma monotone_conv_ref_ {E R} : monotone1 (@conv_ref_ E R).\nProof. red. intros. eapply monotone_conv_refF; eauto. Qed.\n\nHint Resolve monotone_conv_ref_ : paco.\n\nDefinition conv_ref {E R} : itree_spec E R -> Prop := paco1 conv_ref_ bot1.\n\n\nLemma conv_ref_ret_bind E1 E2 R1 S R2 RPre RPost RR r (t2 : itree_spec E2 R2) :\n  forall (t1 : itree_spec E2 S),\n    conv_ref t1 ->\n    @refines E1 E2 R1 R2 RPre RPost RR (Ret r) (t1 >> t2) ->\n    refines RPre RPost RR (Ret r) t2.\nProof.\n  intros t1 Ht1 Href. punfold Href. red in Href. cbn in Href.\n  punfold Ht1. red in Ht1. pstep. red. cbn.\n  remember (RetF r) as x. remember (t1 >> t2) as tbind.\n  assert (Htbind : tbind ≅ t1 >> t2). subst. reflexivity.\n  clear Heqtbind. punfold Htbind. red in Htbind.\n  hinduction Href before RR; intros; inv Heqx; use_simpobs.\n  - unfold observe in Htbind. cbn in Htbind. destruct (observe t1) eqn : Ht1';\n      inv Htbind; try inv CHECK.\n    setoid_rewrite <- H2. constructor. auto.\n  - assert (HDEC: (exists t1', observe t1 = TauF t1') \\/ (exists r', observe t1 = RetF r')).\n    { unfold observe in Htbind. cbn in Htbind. destruct (observe t1); eauto.\n      inv Htbind; inv CHECK. }\n    destruct HDEC as [[t1' Ht1']  | [r' Hr'] ].\n    + eapply IHHref with (t1 := t1'); eauto.\n      rewrite Ht1' in Ht1. inv Ht1. pclearbot. pstep_reverse.\n      assert (Tau phi ≅ t1 >> t2). pstep. auto.\n      symmetry in Ht1'. use_simpobs. rewrite Ht1' in H. rewrite bind_tau in H.\n      pinversion H; try inv CHECK. pclearbot. subst.\n      clear - REL. pclearbot. pstep_reverse.\n    + assert (Tau phi ≅ t1 >> t2). pstep. auto.\n      symmetry in Hr'. use_simpobs. rewrite Hr' in H.\n      rewrite bind_ret_l in H.\n      punfold H. red in H. cbn in H. inv H; try inv CHECK.\n      constructor. pclearbot. eapply IHHref; eauto.\n      pstep_reverse. rewrite Hr', bind_ret_l. clear - REL. pclearbot. auto.\n  - assert (HDEC : (exists k : A -> _, observe t1 = VisF Spec_forall k) \\/ (exists r', observe t1 = RetF r')).\n    {\n      unfold observe in Htbind. cbn in Htbind. destruct (observe t1); eauto.\n      inv Htbind; inv CHECK.\n      cbn in Htbind. inv Htbind. inj_existT. subst. eauto. }\n    destruct HDEC as [ [k Hk] | [r' Hr'] ].\n    + rewrite Hk in Ht1. inv Ht1. inj_existT. subst. pclearbot. rename X into a.\n      eapply H0 with (t1 := k a); eauto. pstep_reverse. Unshelve. all : auto.\n      assert (Vis Spec_forall kphi ≅ t1 >> t2). pstep. auto.\n      symmetry in Hk. use_simpobs. rewrite Hk in H1. rewrite bind_vis in H1.\n      pinversion H1. inj_existT. subst. clear - REL. pclearbot.\n      pstep_reverse.\n    + symmetry in Hr'. use_simpobs.\n      assert (Vis Spec_forall kphi ≅ t1 >> t2). pstep. auto.\n      rewrite Hr' in H1. rewrite bind_ret_l in H1.\n      pinversion H1; try inv CHECK. inj_existT. subst.\n      constructor. intros. clear - H REL. pclearbot.\n      rewrite itree_eta' at 1. pstep_reverse. rewrite <- REL. pstep. apply H.\n  -  assert (HDEC : (exists k : A -> _, observe t1 = VisF Spec_exists k) \\/ (exists r', observe t1 = RetF r')).\n    {\n      unfold observe in Htbind. cbn in Htbind. destruct (observe t1); eauto.\n      inv Htbind; inv CHECK.\n      cbn in Htbind. inv Htbind. inj_existT. subst. eauto. }\n    destruct HDEC as [ [k Hk] | [r' Hr'] ].\n    + rewrite Hk in Ht1. inv Ht1. inj_existT. subst. pclearbot.\n      eapply IHHref with (t1 := k a); eauto. pstep_reverse.\n      assert (Vis Spec_exists kphi ≅ t1 >> t2). pstep. auto.\n      symmetry in Hk. use_simpobs. rewrite Hk in H. rewrite bind_vis in H.\n      pinversion H. inj_existT. subst. clear - REL. pclearbot.\n      pstep_reverse.\n    + symmetry in Hr'. use_simpobs.\n      assert (Vis Spec_exists kphi ≅ t1 >> t2). pstep. auto.\n      rewrite Hr' in H. rewrite bind_ret_l in H.\n      pinversion H; try inv CHECK. inj_existT. subst. econstructor.\n      Unshelve. all : auto. clear - REL Href. pclearbot.\n      rewrite itree_eta' at 1. pstep_reverse. rewrite <- REL. pstep. apply Href.\nQed.\n\nGlobal Instance conv_ref_eqit_proper E R b1 b2 :\n  Proper (@eqit (SpecEvent E) R R eq b1 b2 ==> flip impl) conv_ref.\nProof.\n  pcofix CIH.\n  intros t1 t2 Ht Ht2. pstep. red. punfold Ht2. red in Ht2.\n  punfold Ht. red in Ht.\n  hinduction Ht before R; intros; pclearbot; try (constructor; eauto).\n  - right. eapply CIH; eauto. inv Ht2. pclearbot. auto.\n  - inv Ht2. inj_existT. subst. constructor. right. pclearbot. eapply CIH; eauto.\n    apply REL. apply H0.\n    inj_existT. subst. constructor; auto. pclearbot. right. eapply CIH; eauto.\n    apply REL. apply H0.\n  - left. pstep. red. eapply IHHt; eauto.\n  - inv Ht2. pclearbot. punfold H0.\nQed.\n\nLemma padded_conv_ref_ret_bind E1 E2 R1 S R2 RPre RPost RR r (t2 : itree_spec E2 R2) :\n  forall (t1 : itree_spec E2 S),\n    conv_ref t1 ->\n    @padded_refines E1 E2 R1 R2 RPre RPost RR (Ret r) (t1 >> t2) ->\n    padded_refines RPre RPost RR (Ret r) t2.\nProof.\n  intros t1 Ht1. unfold padded_refines. setoid_rewrite pad_ret.\n  setoid_rewrite pad_bind. intros. rewrite pad_eutt in Ht1. eapply conv_ref_ret_bind; eauto.\nQed.\n\nLemma conv_ref_bind E R S (k : R -> itree_spec E S) :\n  forall t, conv_ref t ->\n  (forall r, conv_ref (k r)) ->\n   conv_ref (ITree.bind t k).\nProof.\n  intros t Ht Hk. generalize dependent t. pcofix CIH. intros t Ht. punfold Ht. red in Ht.\n  pstep. red. unfold observe. cbn. inv Ht.\n  - pstep_reverse. eapply paco1_mon; try eapply Hk. intros. contradiction.\n  - constructor. right. pclearbot. eapply CIH; eauto.\n  - constructor. right. pclearbot. eapply CIH; apply H0.\n  - constructor; auto. right. pclearbot. eapply CIH; apply H0.\nQed.\n\nLemma conv_ref_ret E R (r : R) :\n  @conv_ref E R (Ret r).\nProof.\n  pstep. red. constructor.\nQed.\n\nVariant conv_ref_mrecF {E D : Type -> Type} {R : Type} (P : forall A, D A -> Prop)\n        (F : itree_spec (D +' E) R -> Prop) :\n  itree_spec' (D +' E) R -> Prop :=\n  | conv_ref_mrec_RetF r : conv_ref_mrecF P F (RetF r)\n  | conv_ref_mrec_TauF t : F t -> conv_ref_mrecF P F (TauF t)\n  | conv_ref_mrec_existsF (A : Type) (k : A -> itree_spec _ R) :\n    (forall a, F (k a)) -> conv_ref_mrecF P F (VisF Spec_exists k)\n  | conv_ref_mrec_forallF (A : Type) (k : A -> itree_spec _ R) :\n    A -> (forall a, F (k a)) -> conv_ref_mrecF P F (VisF Spec_forall k)\n  | conv_ref_mrec_inlF (A : Type) (d : D A) (k : A -> itree_spec _ R) :\n    P A d ->\n    (forall a, F (k a)) -> conv_ref_mrecF P F (VisF (Spec_vis (inl1 d)) k)\n.\n\nDefinition conv_ref_mrec_ {E D: Type -> Type} {R : Type} P (F : itree_spec (D +' E) R -> Prop)\n           (t : itree_spec (D +' E) R) :=\n  conv_ref_mrecF P F (observe t).\n\nLemma monotone_conv_ref_mrecF {E D R} P (ot : itree_spec' (D +' E) R) sim sim'\n      (LE : sim <1= sim')\n      (IN : conv_ref_mrecF P sim ot) :\n  conv_ref_mrecF P sim' ot.\nProof. induction IN; constructor; auto. Qed.\n\nLemma monotone_conv_ref_mrec_ {E D R} P : monotone1 (@conv_ref_mrec_ E D R P).\nProof. red. intros. eapply monotone_conv_ref_mrecF; eauto. Qed.\n\nHint Resolve monotone_conv_ref_mrec_ : paco.\n\nDefinition conv_ref_mrec {E D R} P : itree_spec (D +' E) R -> Prop := paco1 (conv_ref_mrec_ P) bot1.\n\nLemma conv_ref_mrec_bind E D R S P (k : R -> itree_spec (D +' E) S) :\n  forall t, conv_ref_mrec P t ->\n  (forall r, conv_ref_mrec P (k r)) ->\n   conv_ref_mrec P (ITree.bind t k).\nProof.\n  intros t Ht Hk. generalize dependent t. pcofix CIH. intros t Ht.\n  pstep. red. unfold observe. cbn. punfold Ht. red in Ht.\n  inv Ht.\n  - pstep_reverse. eapply paco1_mon; try apply Hk. intros. contradiction.\n  - constructor. right. pclearbot. eapply CIH; eauto.\n  - constructor. right. pclearbot. eapply CIH; eauto. apply H0.\n  - constructor; auto. right. pclearbot. eapply CIH. apply H0.\n  - constructor. auto. pclearbot. right. eapply CIH. apply H1.\nQed.\n\n(*may need a more general induction hype *)\n\nSection ConvRefMRec.\nContext (E D : Type -> Type).\nContext (Pre : forall A, D A -> Prop).\nContext (bodies : D ~> itree_spec (D +' E)).\nContext (A : Type) (init : D A) (Hinit : Pre A init).\nContext (Hconv : forall A (d : D A), Pre A d -> conv_ref_mrec Pre (bodies A d)).\n\nLemma conv_ref_interp_mrec_conv_ref:\n    forall t : itree_spec (D +' E) A, conv_ref_mrec Pre t -> conv_ref (interp_mrec_spec bodies t).\nProof.\n  pcofix CIH. intros t Ht. punfold Ht. red in Ht.\n  pstep. red. unfold observe. cbn. inv Ht.\n  - constructor.\n  - constructor. right. eapply CIH; eauto. pclearbot. auto.\n  - constructor. pclearbot. right. eapply CIH; eauto. apply H0.\n  - constructor; auto. right. pclearbot. eapply CIH; eauto.\n    apply H0.\n  - constructor. right. eapply CIH. pclearbot. apply conv_ref_mrec_bind; auto.\nQed.\n\nLemma conv_ref_mrec_conv_ref : conv_ref (mrec_spec bodies init).\nProof.\n  eapply conv_ref_interp_mrec_conv_ref. auto.\nQed.\n\n\n\nEnd ConvRefMRec.\n\nGlobal Instance conv_ref_mrec_eqit_proper E D R b1 b2 P :\n  Proper (@eqit (SpecEvent (D +' E)) R R eq b1 b2 ==> flip impl) (conv_ref_mrec P).\nProof.\n  pcofix CIH.\n  intros t1 t2 Ht Ht2. pstep. red. punfold Ht2. red in Ht2.\n  punfold Ht. red in Ht.\n  hinduction Ht before R; intros; pclearbot; try (constructor; eauto).\n  - right. eapply CIH; eauto. inv Ht2. pclearbot. auto.\n  - inv Ht2; inj_existT; subst; pclearbot.\n    + constructor. right. eapply CIH; eauto. apply REL. apply H0.\n    + constructor; auto. right. eapply CIH. apply REL. apply H0.\n    + constructor; auto. right. eapply CIH. apply REL. apply H3.\n  - left. pstep. red. eapply IHHt; eauto.\n  - inv Ht2. pclearbot. punfold H0.\nQed.\n\nLemma conv_ref_mrec_spin (E D : Type -> Type) (R : Type) (P : forall A : Type, D A -> Prop) :\n  @conv_ref_mrec E D R P ITree.spin.\nProof.\n  pcofix CIH. pstep. red. cbn. constructor.\n  eauto.\nQed.\n\nLemma conv_ref_mrec_ret (E D : Type -> Type) (R : Type) (P : forall A : Type, D A -> Prop) r:\n  @conv_ref_mrec E D R P (Ret r).\nProof.\n  pstep. constructor.\nQed.\n\nLemma conv_ref_mrec_forall E D R P A k :\n  A ->\n  (forall a : A, @conv_ref_mrec E D R P (k a)) ->\n  conv_ref_mrec P (Vis Spec_forall k).\nProof.\n  intros. pstep. constructor. auto. left. apply H.\nQed.\n\nLemma conv_ref_mrec_exists E D R P A k :\n  (forall a : A, @conv_ref_mrec E D R P (k a)) ->\n  conv_ref_mrec P (Vis Spec_exists k).\nProof.\n  intros. pstep. constructor. left. apply H.\nQed.\n\nLemma conv_ref_mrec_inl E D R P A k (d : D A) :\n  (P A d : Prop) ->\n  (forall a : A, @conv_ref_mrec E D R P (k a)) ->\n  conv_ref_mrec P (Vis (Spec_vis (inl1 d)) k).\nProof.\n  intros. pstep. constructor. auto. left. apply H0.\nQed.\n(*now I want a good reasoning principle for finding conv_ref*)\n\n    (*can infer *)\n  (* shouldn't need coinduction *)\n\n\n\n(*\n\nLemma monotone_satisfiesF {E R1 R2} (RR : R1 -> R2 -> Prop) ot1 (ot2 : itree_spec' E R2) sim sim'\n  (LE : sim <2= sim')\n  (IN : satisfiesF RR sim ot1 ot2) :\n  satisfiesF RR sim' ot1 ot2.\nProof.\n  induction IN; eauto.\nQed.\n\nLemma monotone_satisfies_ {E R1 R2} RR : monotone2 (@satisfies_ E R1 R2 RR).\nProof. red. intros. eapply monotone_satisfiesF; eauto. Qed.\n\nHint Resolve monotone_satisfies_ : paco.\n*)\n", "meta": {"author": "GaloisInc", "repo": "itree-refinement", "sha": "fb8bdd270bf5fd616bb9512a5d894a0236304dca", "save_path": "github-repos/coq/GaloisInc-itree-refinement", "path": "github-repos/coq/GaloisInc-itree-refinement/itree-refinement-fb8bdd270bf5fd616bb9512a5d894a0236304dca/theories/ConvergentRefinement.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.4649015713733884, "lm_q1q2_score": 0.28250356252104547}}
{"text": "(** * Linearize: Place all and only operations in let binders *)\nRequire Import Crypto.Reflection.Syntax.\nRequire Import Crypto.Reflection.Wf.\nRequire Import Crypto.Reflection.WfProofs.\nRequire Import Crypto.Reflection.Linearize.\nRequire Import Crypto.Util.Tactics Crypto.Util.Sigma.\n\nLocal Open Scope ctype_scope.\nSection language.\n  Context {base_type_code : Type}\n          {op : flat_type base_type_code -> flat_type 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 Tbase := (@Tbase base_type_code).\n  Local Notation exprf := (@exprf base_type_code op).\n  Local Notation expr := (@expr base_type_code op).\n  Local Notation Expr := (@Expr base_type_code op).\n  Local Notation wff := (@wff base_type_code op).\n  Local Notation wf := (@wf base_type_code op).\n\n  Section with_var.\n    Context {var1 var2 : base_type_code -> Type}.\n\n    Local Ltac t_fin_step tac :=\n      match goal with\n      | _ => assumption\n      | _ => progress simpl in *\n      | _ => progress subst\n      | _ => progress inversion_sigma\n      | _ => setoid_rewrite List.in_app_iff\n      | [ H : context[List.In _ (_ ++ _)] |- _ ] => setoid_rewrite List.in_app_iff in H\n      | _ => progress intros\n      | _ => solve [ eauto ]\n      | _ => solve [ intuition (subst; eauto) ]\n      | [ H : forall (x : prod _ _) (y : prod _ _), _ |- _ ] => specialize (fun x x' y y' => H (x, x') (y, y'))\n      | _ => rewrite !List.app_assoc\n      | [ H : _ \\/ _ |- _ ] => destruct H\n      | [ H : _ |- _ ] => apply H\n      | _ => eapply wff_in_impl_Proper; [ solve [ eauto ] | ]\n      | _ => progress tac\n      | [ |- wff _ _ _ ] => constructor\n      | [ |- wf _ _ _ ] => constructor\n      end.\n    Local Ltac t_fin tac := repeat t_fin_step tac.\n\n    Local Hint Constructors Wf.wff.\n    Local Hint Resolve List.in_app_or List.in_or_app.\n\n    Local Ltac small_inversion_helper wf G0 e2 :=\n      let t0 := match type of wf with wff (t:=?t0) _ _ _ => t0 end in\n      let e1 := match goal with\n                | |- context[wff G0 (under_letsf ?e1 _) (under_letsf e2 _)] => e1\n                end in\n      pattern G0, t0, e1, e2;\n      lazymatch goal with\n      | [ |- ?retP _ _ _ _ ]\n        => first [ refine (match wf in @Wf.wff _ _ _ _ G t v1 v2\n                                return match v1 return Prop with\n                                       | TT => retP G t v1 v2\n                                       | _ => forall P : Prop, P -> P\n                                       end with\n                          | WfTT _ => _\n                          | _ => fun _ p => p\n                          end)\n                | refine (match wf in @Wf.wff _ _ _ _ G t v1 v2\n                                return match v1 return Prop with\n                                       | Var _ _ => retP G t v1 v2\n                                       | _ => forall P : Prop, P -> P\n                                       end with\n                          | WfVar _ _ _ _ _ => _\n                          | _ => fun _ p => p\n                          end)\n                | refine (match wf in @Wf.wff _ _ _ _ G t v1 v2\n                                return match v1 return Prop with\n                                       | Op _ _ _ _ => retP G t v1 v2\n                                       | _ => forall P : Prop, P -> P\n                                       end with\n                          | WfOp _ _ _ _ _ _ _ => _\n                          | _ => fun _ p => p\n                          end)\n                | refine (match wf in @Wf.wff _ _ _ _ G t v1 v2\n                                return match v1 return Prop with\n                                       | LetIn _ _ _ _ => retP G t v1 v2\n                                       | _ => forall P : Prop, P -> P\n                                       end with\n                          | WfLetIn _ _ _ _ _ _ _ _ _ => _\n                          | _ => fun _ p => p\n                          end)\n                | refine (match wf in @Wf.wff _ _ _ _ G t v1 v2\n                                return match v1 return Prop with\n                                       | Pair _ _ _ _ => retP G t v1 v2\n                                       | _ => forall P : Prop, P -> P\n                                       end with\n                          | WfPair _ _ _ _ _ _ _ _ _ => _\n                          | _ => fun _ p => p\n                          end) ]\n      end.\n    Fixpoint wff_under_letsf G {t} e1 e2 {tC} eC1 eC2\n             (wf : @wff var1 var2 G t e1 e2)\n             (H : forall (x1 : interp_flat_type var1 t) (x2 : interp_flat_type var2 t),\n                 wff (flatten_binding_list x1 x2 ++ G) (eC1 x1) (eC2 x2))\n             {struct e1}\n      : @wff var1 var2 G tC (under_letsf e1 eC1) (under_letsf e2 eC2).\n    Proof.\n      revert H.\n      set (e1v := e1) in *.\n      destruct e1 as [ | | ? ? ? args | tx ex tC0 eC0 | ? ex ? ey ];\n        [ clear wff_under_letsf\n        | clear wff_under_letsf\n        | clear wff_under_letsf\n        | generalize (fun G => match e1v return match e1v with LetIn _ _ _ _ => _ | _ => _ end with\n                            | LetIn _ ex _ eC => wff_under_letsf G _ ex\n                            | _ => I\n                            end);\n          generalize (fun G => match e1v return match e1v with\n                                                | LetIn tx0 _ tC1 e0 => (* 8.4's type inferencer is broken, so we copy/paste the term from 8.5.  This entire clause could just be [_], if Coq 8.4 worked *)\n                                                  forall (x : @interp_flat_type base_type_code var1 tx0) (e3 : exprf tC1)\n                                                         (tC2 : flat_type) (eC3 : @interp_flat_type base_type_code var1 tC1 -> exprf tC2)\n                                                         (eC4 : @interp_flat_type base_type_code var2 tC1 -> exprf tC2),\n                                                    wff G (e0 x) e3 ->\n                                                    (forall (x1 : @interp_flat_type base_type_code var1 tC1)\n                                                            (x2 : @interp_flat_type base_type_code var2 tC1),\n                                                        wff (@flatten_binding_list base_type_code var1 var2 tC1 x1 x2 ++ G) (eC3 x1) (eC4 x2)) ->\n                                                    wff G (@under_letsf base_type_code op var1 tC1 (e0 x) tC2 eC3)\n                                                        (@under_letsf base_type_code op var2 tC1 e3 tC2 eC4)\n                                                | _ => _ end with\n                               | LetIn _ ex tC' eC => fun x => wff_under_letsf G tC' (eC x)\n                               | _ => I\n                               end);\n          clear wff_under_letsf\n        | generalize (fun G => match e1v return match e1v with Pair _ _ _ _ => _ | _ => _ end with\n                            | Pair _ ex _ ey => wff_under_letsf G _ ex\n                            | _ => I\n                            end);\n          generalize (fun G => match e1v return match e1v with Pair _ _ _ _ => _ | _ => _ end with\n                            | Pair _ ex _ ey => wff_under_letsf G _ ey\n                            | _ => I\n                            end);\n          clear wff_under_letsf ];\n        revert eC1 eC2;\n        (* alas, Coq's refiner isn't smart enough to figure out these small inversions for us *)\n        small_inversion_helper wf G e2;\n        t_fin idtac.\n    Qed.\n\n    Local Hint Resolve wff_under_letsf.\n    Local Hint Constructors or.\n    Local Hint Extern 1 => progress unfold List.In in *.\n    Local Hint Resolve wff_in_impl_Proper.\n    Local Hint Resolve wff_SmartVarf.\n\n    Lemma wff_linearizef G {t} e1 e2\n      : @wff var1 var2 G t e1 e2\n        -> @wff var1 var2 G t (linearizef e1) (linearizef e2).\n    Proof.\n      induction 1; t_fin ltac:(apply wff_under_letsf).\n    Qed.\n\n    Local Hint Resolve wff_linearizef.\n\n    Lemma wf_linearize {t} e1 e2\n      : @wf var1 var2 t e1 e2\n        -> @wf var1 var2 t (linearize e1) (linearize e2).\n    Proof.\n      destruct 1; constructor; auto.\n    Qed.\n  End with_var.\n\n  Lemma Wf_Linearize {t} (e : Expr t) : Wf e -> Wf (Linearize e).\n  Proof.\n    intros wf var1 var2; apply wf_linearize, wf.\n  Qed.\nEnd language.\n\nHint Resolve Wf_Linearize : wf.\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/LinearizeWf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.2824528414032058}}
{"text": "From Undecidability Require Import Synthetic.DecidabilityFacts Synthetic.SemiDecidabilityFacts Synthetic.EnumerabilityFacts Synthetic.ListEnumerabilityFacts reductions partial embed_nat ReducibilityFacts truthtables bestaxioms.\nRequire Import Setoid Program Lia List.\n\nAxiom EA : EA.\n\nNotation φ := (proj1_sig EA).\nNotation EAP := (proj2_sig EA).\n\nLemma EAS : forall p : nat -> nat -> Prop, enumerable (uncurry p) -> exists γ, forall x, enumerator (φ (γ x)) (p x).\nProof.\n  intros p [γ H] % penumerable_iff % EAP; firstorder; eauto.\n  eapply discrete_nat.\nQed.\n\nDefinition W c x := exists n, φ c n = Some x.\n\nLemma W_spec : forall p, enumerable p <-> exists c, forall x, p x <-> W c x.\nProof.\n  intros p.\n  split.\n  - intros [f Hf].\n    destruct (EAP (fun _ => p)) as [γ H].\n    + exists (fun _ => f). firstorder.\n    + exists (γ 0). firstorder.\n  - intros [c H]. exists (φ c). firstorder.\nQed.\n\nLemma do_EA p : enumerable p -> exists c, forall x, p x <-> W c x.\nProof.\n  eapply W_spec.\nQed.\n\nHint Resolve discrete_nat : core.\n\nLemma EAS' :\n  forall p : nat -> nat -> Prop, enumerable (fun! ⟨x,y⟩ => p x y) ->\n                                        exists c : nat -> nat, forall x y, p x y <-> W (c x) y.\nProof.\n  intros p Hp.\n  eapply EAS, enumerable_red; eauto.\n  exists embed. red. intros [x y]. now rewrite embedP.\nQed.\n\nLemma EAS_datatype X (p : X -> nat -> Prop) (x0 : X) :\n  datatype X ->\n  enumerable (uncurry p) ->\n  exists c : X -> nat, forall x y, p x y <-> W (c x) y.\nProof.\n  intros (I & R & HIR) Ep.\n  destruct (EAS (fun x y => if R x is Some l then p l y else p x0 y)) as [c Hc].\n  - eapply enumerable_red.\n    4: eapply Ep.\n    + exists (fun '(x, y) => if R x is Some l then (l,y) else (x0, y)).\n      intros [x y]. cbn.\n      destruct (R x); reflexivity.\n    + eauto.\n    + eapply discrete_prod. eapply datatype_discrete. now exists I, R.\n      eapply discrete_nat.\n  - exists (fun l => c (I l)). intros. \n    now rewrite <- (Hc (I x) y), HIR.\nQed.\n\nLemma EAS_list (p : list nat -> nat -> Prop) : enumerable (uncurry p) ->\n                                      exists c : list nat -> nat, forall x y, W (c x) y <-> p x y.\nProof.\n  intros.\n  edestruct EAS_datatype with (p := p) as [c Hc]; eauto.\n  - exact nil.\n  - eapply enumerable_discrete_datatype.\n    eapply discrete_list, discrete_nat.\n    eauto.\n  - exists c. firstorder.\nQed.\n\nLemma List_id : exists c_l, forall (l : list nat), forall x, W (c_l l) x <-> List.In x l.\nProof.\n  eapply EAS_list. \n  eapply decidable_enumerable. 2:eauto.\n  eapply decidable_iff. econstructor.\n  intros [x y]. cbn. exact _. \nQed.\n\nNotation π1 := (fun! ⟨x, y⟩ => x).\nNotation π2 := (fun! ⟨x, y⟩ => y).\n\nLemma enumerable_W : enumerable (fun '(x, y) => W x y).\nProof.\n  exists (fun p => let (n,m) := unembed p in if φ n m is Some m then Some (n, m) else None).\n  intros [n m].\n  split.\n  - intros H. destruct H as [n' H].\n    exists (embed (n, n')). rewrite embedP. cbn. now rewrite H.\n  - unfold W.\n    intros [p H].\n    destruct (unembed p) as [n' m'].\n    exists m'.\n    destruct (φ n' m') eqn:E; inversion H; now subst.\nQed.\n\nLemma W_maximal (p : nat -> Prop) :\n  enumerable p -> p ⪯ₘ uncurry W.\nProof.\n  intros Hp.\n  destruct (do_EA p Hp) as [c Hc].\n  exists (fun x => (c, x)). exact Hc.\nQed.\n\nLemma SMN' : forall f, exists k, forall c x, W c (f x) <-> W (k c) x.\nProof.\n  intros f.\n  eapply EAS.\n  eapply enumerable_red with (q := uncurry W).\n  - exists (fun '(x,y) => (x, f y)). now intros [x y].\n  - eauto.\n  - eapply discrete_prod; now eapply discrete_nat.\n  - eapply enumerable_W.\nQed.\n\nLemma TT : \n  forall f : nat -> { Q : list nat & truthtable}, \n    exists c : list nat -> nat, forall l x, W (c l) x <-> eval_tt (projT2 (f x)) (List.map (fun x => negb (inb (uncurry Nat.eqb) x l)) (projT1 (f x))) = false.\nProof.\n  intros f.\n  eapply EAS_list.\n  eapply decidable_enumerable. 2:eauto.\n  eapply decidable_iff. econstructor.\n  intros [x y]. cbn. exact _. \nQed.\n\nTactic Notation \"intros\" \"⟨\" ident(n) \",\" ident(m) \"⟩\" :=\n  let nm := fresh \"nm\" in\n  let E := fresh \"E\" in\n  intros nm; destruct (unembed nm) as [n m] eqn:E.\n\nDefinition K0 c := W c c.\n\nLemma K0_not_enumerable : ~ enumerable (compl K0).\nProof.\n  intros [c Hc] % do_EA. specialize (Hc c).\n  unfold K0, compl in Hc. tauto.\nQed.\n\nLemma K0_undecidable : ~ decidable (compl K0).\nProof.\n  intros Hf % decidable_enumerable; eauto.\n  now eapply K0_not_enumerable.\nQed.\n\nLemma W_uncurry_red:\n  (fun! ⟨ n, m ⟩ => W n m) ⪯ₘ uncurry W.\nProof.\n  exists (fun! ⟨n,m⟩ => (n,m)). intros nm. destruct (unembed nm) as [n m]. reflexivity.\nQed.\n\nLemma K0_red:\n  K0 ⪯ₘ uncurry W.\nProof.\n  exists (fun n => (n,n)). intros n. reflexivity.\nQed.\n\nLemma W_uncurry_red':\n  uncurry W ⪯ₘ (fun! ⟨ n, m ⟩ => W n m).\nProof.\n  exists (fun '(n,m) => ⟨n,m⟩). intros [n m]. now rewrite embedP.\nQed.\n\nGlobal Hint Resolve discrete_prod discrete_nat : core.\n\nLemma W_not_enumerable : ~ enumerable (compl (uncurry W)).\nProof.\n  eapply not_coenumerable; eauto.\n  - eapply K0_red.\n  - eapply K0_not_enumerable. \nQed.\n\nLemma K0_enum : enumerable K0.\nProof.\n  eapply enumerable_red with (q := uncurry W).\n  eapply K0_red. all:eauto.\n  eapply enumerable_W.\nQed.\n\nLemma red_tt_not_red_m :\n  compl K0 ⪯ₜₜ K0 /\\ ~ compl K0 ⪯ₘ K0.\nProof.\n  split.\n  - eapply red_tt_complement.\n  - intros H % enumerable_red.\n    + now eapply K0_not_enumerable.\n    + eauto.\n    + eapply discrete_nat.\n    + eapply K0_enum.\nQed.\n\nNotation \"m-complete p\" := (forall q : nat -> Prop, enumerable q -> q ⪯ₘ p) (at level 10).\n\nLemma m_complete_W :\n  m-complete (fun! ⟨n,m⟩ =>  W n m).\nProof.\n  intros q [c Hc] % do_EA.\n  exists (fun x => ⟨c,x⟩). intros x.\n  now rewrite embedP.\nQed.\n\nLemma W_red_K0 : (fun! ⟨n,m⟩ =>  W n m) ⪯ₘ K0.\nProof.\n  edestruct EAS with (p := fun! ⟨x,y⟩ => fun (z : nat) => W x y) as [c Hc].\n  - eapply ReducibilityFacts.enumerable_red with (q := uncurry W); eauto.\n    2: eapply enumerable_W. all:eauto.\n    exists (fun '(xy,z) => (fun! ⟨x,y⟩ => (x,y)) xy). intros [xy z].\n    cbn. now destruct (unembed xy) as [x y]. \n  - exists c. intros xy. unfold K0. rewrite <- (Hc xy (c xy)).\n    now destruct (unembed xy) as [x y].\nQed.\n\nLemma m_complete_K0 : m-complete K0.\nProof.\n  intros q Hq % m_complete_W.\n  eapply red_m_transitive. exact Hq. exact W_red_K0.\nQed.\n\nLemma enum_iff (p : nat -> Prop) : enumerable p <-> semi_decidable p.\nProof.\n  split.\n  - intros H. eapply enumerable_semi_decidable. eapply discrete_nat. eassumption.\n  - intros H. eapply semi_decidable_enumerable. eauto. eauto.\nQed.\n\nLemma generative_W :   generative (fun! ⟨ n, m ⟩ => W n m).\nProof.\n  eapply unbounded_generative. \n  intros x y; destruct (numbers.nat_eq_dec x y); eauto.\n  destruct (do_EA (fun _ => True)) as [c_top H_top]. {\n    eapply decidable_enumerable. 2:eauto. exists (fun _ => true). firstorder.\n  }\n  intros n. exists (map (fun m => ⟨c_top,m⟩) (seq 0 n)). split.\n  now rewrite map_length, seq_length. split.\n  eapply NoDup_map. intros ? ? E % (f_equal unembed). rewrite !embedP in E. congruence. eapply seq_NoDup.\n  intros ? (? & <- & ?) % in_map_iff. rewrite embedP. firstorder.\nQed.", "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/Axioms/EA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2824528345455438}}
{"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 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 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 : IntWord.Int :=\n  #63.\n\nDefinition suffixOf : IntWord.Int -> IntWord.Int :=\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 -> 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 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\nDefinition prefixBitMask : IntWord.Int :=\n  Data.Bits.complement suffixBitMask.\n\nDefinition prefixOf : IntWord.Int -> Prefix :=\n  fun x => x Data.Bits..&.(**) prefixBitMask.\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 natFromInt :=\n  IntWord.wordFromInt.\n\nDefinition shorter : Mask -> Mask -> bool :=\n  fun m1 m2 => (natFromInt m1) GHC.Base.> (natFromInt m2).\n\nDefinition zero : IntWord.Int -> Mask -> bool :=\n  fun i m => ((natFromInt i) Data.Bits..&.(**) (natFromInt m)) GHC.Base.== #0.\n\nDefinition lowestBitMask : Nat -> Nat :=\n  fun x => x Data.Bits..&.(**) GHC.Num.negate x.\n\nDefinition intFromNat :=\n  IntWord.intFromWord.\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 match_ : IntWord.Int -> Prefix -> Mask -> bool :=\n  fun i p m => (mask i m) GHC.Base.== p.\n\nDefinition nomatch : IntWord.Int -> Prefix -> Mask -> bool :=\n  fun i p m => (mask i m) GHC.Base./= p.\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) ((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\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 (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 indexOfTheOnlyBit :=\n  IntWord.indexOfTheOnlyBit.\n\nDefinition lowestBitSet : Nat -> IntWord.Int :=\n  fun x => indexOfTheOnlyBit (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 -> IntWord.Int :=\n  fun x => indexOfTheOnlyBit (IntWord.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\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\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\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           : 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\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\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    intFromNat (IntWord.highestBitMask (Data.Bits.xor (natFromInt p1) (natFromInt\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 : IntWord.Int -> BitMap :=\n  fun s => IntWord.shiftLWord #1 s.\n\nDefinition bitmapOf : IntWord.Int -> 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 := (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 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 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 := 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 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 (bm' Data.Bits..&.(**) Data.Bits.complement 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 (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\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 (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 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 (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\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.InternalWord.NFData__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 `GHC.Show.Show', including\n   `Data.IntSet.InternalWord.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.InternalWord.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.InternalWord.IsList__IntSet' *)\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": "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/InternalWord.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.28235771304224594}}
{"text": "(** Monadic Parser Combinators *)\n(** モナディック パーサー コンビネータ *)\n\n(* @suharahiromichi 2014_01_08 *)\n\n(** paeser T の定義は sf/ImpParser_J を使用した。\n    コンビネータの型は pcl.pdf、処理の内容は ocamlAda を参考にした。*)\n\n(* http://proofcafe.org/sf/ImpParser_J.html *)\n(* https://github.com/yoshihiro503/ocamlAda/blob/master/src/parserMonad.ml *)\n(* https://ocaml.janestreet.com/files/pcl.pdf *)\n\nRequire Import ssreflect ssrbool ssrnat seq eqtype.\nRequire Import ssrfun.\nRequire Import String.\nRequire Import Ascii.\n\n(** (1) 字句解析 *)\nDefinition isWhite (c : ascii) : bool :=\n  let n := nat_of_ascii c in\n  (n == 32) ||                              (* space *)\n            (n ==  9) ||                    (* tab *)\n            (n == 10) ||                    (* linefeed *)\n            (n == 13).                      (* Carriage return. *)\n\nDefinition isLowerAlpha (c : ascii) : bool :=\n  let n := nat_of_ascii c in\n  (97 <= n) && (n <= 122).\n\nDefinition isAlpha (c : ascii) : bool :=\n  let n := nat_of_ascii c in\n  (65 <= n) && (n <= 90) ||\n            (97 <= n) && (n <= 122).\n\nDefinition isDigit (c : ascii) : bool :=\n  let n := nat_of_ascii c in\n  (48 <= n) && (n <= 57).\n\nInductive chartype := white | alpha | digit | other.\n\nDefinition classifyChar (c : ascii) : chartype :=\n  if isWhite c then\n    white\n  else if isAlpha c then\n    alpha\n  else if isDigit c then\n    digit\n  else\n    other.\n\nFixpoint list_of_string (s : string) : list ascii :=\n  match s with\n  | EmptyString => [::]\n  | String c s => c :: (list_of_string s)\n  end.\n\nFixpoint string_of_list (xs : list ascii) : string :=\n  foldr String EmptyString xs.\n\nDefinition token := string.\n\nFixpoint tokenize_helper (cls : chartype) (acc xs : list ascii)\n                       : list (list ascii) :=\n  let tk :=\n      match acc with\n        | [::] => [::]\n        | _::_ => (rev acc) :: [::]\n      end in\n  match xs with\n    | [::] => tk\n    | (x::xs') =>\n      match cls, classifyChar x, x with\n        | _, _, \"(\"      => tk ++ [:: \"(\"] :: (tokenize_helper other [::] xs')\n        | _, _, \")\"      => tk ++ [:: \")\"] :: (tokenize_helper other [::] xs')\n        | _, white, _    => tk ++ (tokenize_helper white [::] xs')\n        | alpha,alpha,x  => tokenize_helper alpha (x::acc) xs'\n        | digit,digit,x  => tokenize_helper digit (x::acc) xs'\n        | other,other,x  => tokenize_helper other (x::acc) xs'\n        | _,tp,x         => tk ++ (tokenize_helper tp [:: x] xs')\n      end\n  end %char.\n(* \"(\"と\")\"だけ別になっているのは、\"(\"と\")\"の前後にはスペースがなくても、\n トークンの区切りと解釈するため。　他の記号はスペースが必要。\n つまり、\"--\" は\"-\"ふたつとは解釈されないが、\"-(\"は、\"-\"と\"(\"と区別される。 *)\n\n(* ***トークンのパースのメイン*** *)\nDefinition tokenize (s : string) : list string :=\n  map string_of_list (tokenize_helper white [::] (list_of_string s)).\n\nExample tokenize_ex1 :\n  tokenize \"abc12==3  223*(3+(a+c))\"%string\n  = [:: \"abc\"; \"12\"; \"==\"; \"3\"; \"223\";\n       \"*\"; \"(\"; \"3\"; \"+\"; \"(\";\n       \"a\"; \"+\"; \"c\"; \")\"; \")\" ]%string.\nProof. reflexivity. Qed.\n\n(** Option と Error *)\nInductive optionE (T : Type) : Type :=\n  | SomeE : T -> optionE T\n  | NoneE : string -> optionE T.\n\nImplicit Arguments SomeE [[T]].\nImplicit Arguments NoneE [[T]].\n\n(** (2) Symbol Table *)\nFixpoint forallb {A} f (l:list A) : bool :=\n  match l with\n    | nil => true\n    | a::l => f a && forallb f l\n  end.\n\nFixpoint build_symtable (xs : list token) (n : nat) : (token -> nat) :=\n  match xs with\n  | [::] => (fun s => n)\n  | x::xs =>\n    if (forallb isLowerAlpha (list_of_string x)) then\n      (fun s => if string_dec s x then n else (build_symtable xs (S n) s))\n     else\n       build_symtable xs n\n  end.\n\nEval compute in build_symtable [::] 0.      (* 空のシンボルテーブル *)\nEval compute in build_symtable [:: \"aaa\"; \"+\"; \"bbb\"; \"+\"; \"ccc\"]%string\n                               0 \"aaa\"%string . (* 0 *)\nEval compute in build_symtable [:: \"aaa\"; \"+\"; \"bbb\"; \"+\"; \"ccc\"]%string\n                               0 \"bbb\"%string. (* 1 *)\nEval compute in build_symtable [:: \"aaa\"; \"+\"; \"bbb\"; \"+\"; \"ccc\"]%string\n                               0 \"ccc\"%string. (* 2 *)\nEval compute in build_symtable [:: \"aaa\"; \"+\"; \"bbb\"; \"+\"; \"ccc\"]%string\n                               0 \"xxx\"%string. (* 3 *)\n\n(** (3) パーサ コンビネータ *)\nDefinition parser (T : Type) :=\n  list token -> optionE (T * list token).\n(* Tとしてとるものは、unit(予約語)、id、nat、bexp、aexp、com\n   bexpがどこからくるのかは、自明ではない。 *)\nPrint unit.\nCheck unit.\nCheck (parser unit).\nCheck (parser nat).\n\n(* ret : T -> parser T *)\nDefinition ret {T : Type} (t : T) : parser T :=\n  fun (xs : list token) => SomeE (t, xs).\nCheck ret.\n\n(* bind : parser T -> (T -> parser S) -> parser S *)\nDefinition bind_ {T S : Type} (p : parser T) (f : T -> parser S) : parser S :=\n  fun (xs : list token) =>\n    match p xs with\n      | SomeE (t, xs') => f t xs'\n      | NoneE err => NoneE err\n    end.\nInfix \">>=\" := bind_ (left associativity, at level 71).\n(* OCamlにあわせて、>,<から始まる演算子は、すべて左結合で同一優先順位とする。\n実際は、右結合のほうが使いやすいとおもう。 *)\n\n(* bind2 : parser T -> parser S -> parser S *)\nDefinition bind2_ {T S : Type} (p1 : parser T) (p2 : parser S) : parser S :=\n  p1 >>= fun _ => p2.\nInfix \">>>\" := bind2_ (left associativity, at level 71).\n\n(* bind1 : parser T -> parser S -> parser T *)\nDefinition bind1_ {T S : Type} (p1 : parser T) (p2 : parser S) : parser T :=\n  p1 >>= fun x => p2 >>> ret x.\nInfix \"<<<\" := bind1_ (left associativity, at level 71).\n\n(* or : parser T -> parser T -> parser T *)\nDefinition or_ {T : Type} (p1 p2 : parser T) : parser T :=\n  fun (xs : list token) =>\n    match p1 xs with\n      | SomeE (t, xs') => SomeE (t, xs')\n      | NoneE err1 =>\n        match p2 xs with\n          | SomeE (t, xs') => SomeE (t, xs')\n          | NoneE err2 => NoneE (err1 ++ err2) (* エラー文字列の連結 *)\n        end\n    end.\nInfix \"<|>\" := or_ (left associativity, at level 71).\n\n(* and : parser T -> parser S -> parser (T * S) *)\nDefinition and_ {T S : Type} (p1 : parser T) (p2 : parser S) : parser (T * S) :=\n  p1\n    >>= fun x => p2\n                   >>= fun y => ret (x, y).\nInfix \">*<\" := and_ (left associativity, at level 71).\n\n(* many : parser T -> parser (list T) *)\nFixpoint many {T : Type} (steps : nat) (p : parser T) : parser (list T) :=\n  match steps with\n    | 0 => \n      fun _ => NoneE \"Too_many_recursive_calls\"\n    | S steps' =>\n      (p                                    (* ここの括弧は必要！ *)\n         >>= fun x => many steps' p\n                           >>= fun xs => ret (x :: xs))\n      <|>\n      ret [::]\n  end.\n\n(* A parser which expects a given token, followed by p *)\n(* pの前のトークン（補足例：\"IF\"、\"(\"、\"*\"など）を引数とするパーサ *)\nDefinition firstExpect {T} (t : token) (p : parser T) : parser T :=\n  fun xs =>\n    match xs with\n      | x::xs' =>\n        if string_dec x t then\n          p xs'\n        else\n          NoneE (\"expected '\" ++ t ++ \"'.\")\n      | [::] =>\n        NoneE (\"expected '\" ++ t ++ \"'.\")\n    end.\n\n(* A parser which expects a particular token *)\n(* 特定のトークンを引数とするパーサ *)\n(* T = unit\n   補足：parse reserved word とおもってよい。 *)\nDefinition expect (t : token) : parser unit :=\n  firstExpect t (fun xs => SomeE (tt, xs)).\nCheck tt.                                   (* unit *)\nCheck (expect \")\"%string).                  (* parser unit *)\nCheck (expect \")\"%string [::]).             (* optionE (unit * list token) *)\nCheck (expect \"true\"%string).               (* parser unit *)\n\n(** 抽象構文 *)\nInductive id : Type :=\n  Id : nat -> id.\n\nInductive aexp : Type :=\n  | ANum : nat -> aexp\n  | AId : id -> aexp\n  | APlus : aexp -> aexp -> aexp\n  | AMinus : aexp -> aexp -> aexp\n  | AMult : aexp -> aexp -> aexp.\n\nInductive bexp : Type :=\n  | BTrue : bexp\n  | BFalse : bexp\n  | BEq : aexp -> aexp -> bexp\n  | BLe : aexp -> aexp -> bexp\n  | BNot : bexp -> bexp\n  | BAnd : bexp -> bexp -> bexp.\n\nInductive com : Type :=\n  | CSkip : com\n  | CAss : id -> aexp -> com\n  | CSeq : com -> com -> com\n  | CIf : bexp -> com -> com -> com\n  | CWhile : bexp -> com -> com.\n\n(*\nNotation \"'SKIP'\" :=\n  CSkip.\nNotation \"X '::=' a\" :=\n  (CAss X a) (at level 60).\nNotation \"c1 ; c2\" :=\n  (CSeq c1 c2) (at level 80, right associativity).\nNotation \"'WHILE' b 'DO' c 'END'\" :=\n  (CWhile b c) (at level 80, right associativity).\nNotation \"'IFB' e1 'THEN' e2 'ELSE' e3 'FI'\" :=\n  (CIf e1 e2 e3) (at level 80, right associativity).\n*)\n\n(** Impの再帰下降パーサ を「モナディック パーサー コンビネータ」で書き換えた。 *)\n\n(* Identifiers *)\n(* 識別子 *)\nDefinition parseIdentifier symtable (xs : list token) : optionE (id * list token) :=\n    match xs with\n      | [::] =>\n        NoneE \"Expected identifier\"\n      | x::xs' =>\n        if forallb isLowerAlpha (list_of_string x) then\n          SomeE (Id (symtable x), xs')\n        else\n          NoneE (\"Illegal identifier:'\" ++ x ++ \"'\")\n    end.\n(* Numbers *)\n(* 数値 *)\nDefinition parseNumber (xs : list token) : optionE (nat * list token) :=\n    match xs with\n      | [::] =>\n        NoneE \"Expected number\"\n      | x::xs' =>\n        if forallb isDigit (list_of_string x) then\n          SomeE (foldl (fun n d => 10 * n + (nat_of_ascii d - nat_of_ascii \"0\"%char))\n                       0\n                       (list_of_string x),\n                 xs')\n        else\n          NoneE \"Expected number\"\n    end.\n\n(* parser (seq T) を parser T に変換するユーティリティ *)\nDefinition foldlParser {T : Type}\n           (f : T -> T -> T) (e : T) (p : parser (seq T)) : parser T :=\n  fun (xs : list token) =>\n    match p xs with\n      | SomeE (es, rest') =>\n        SomeE (foldl f e es, rest')         (* T * token list *)\n      | NoneE err =>\n        NoneE err\n    end.\n\n(* Parse arithmetic expressions *)\n(* 算術式の構文解析 *)\nFixpoint parsePrimaryExp (steps : nat) symtable : parser aexp :=\n  match steps with\n    | 0 =>\n      fun _ => NoneE \"Too_many_recursive_calls\"\n    | S steps' =>\n      (parseIdentifier symtable >>= fun x => ret (AId x))\n                      <|>\n                      (parseNumber >>= fun x => ret (ANum x))\n                      <|>\n                      (expect \"(\"%string\n                              >>>\n                              parseSumExp steps' symtable\n                              <<<\n                              expect \")\"%string)\n  end\nwith parseProductExp (steps : nat) symtable : parser aexp :=\n  match steps with\n    | 0 =>\n      fun _ => NoneE \"Too_many_recursive_calls\"\n    | S steps' =>\n      parsePrimaryExp steps' symtable\n                      >>=\n                      fun (x : aexp) =>\n                        foldlParser AMult\n                                    x\n                                    (many steps' (expect \"*\"%string\n                                                         >>>\n                                                         parsePrimaryExp steps' symtable))\n  end\nwith parseSumExp (steps : nat) symtable : parser aexp :=\n  match steps with\n    | 0 =>\n      fun _ => NoneE \"Too_many_recursive_calls\"\n    | S steps' =>\n      parseProductExp steps' symtable\n                      >>=\n                      fun (x : aexp) =>\n                        foldlParser APlus\n                                    x\n                                    (many steps' (expect \"+\"%string\n                                                         >>>\n                                                         parseProductExp steps' symtable))\n  (* AMinus (\"-\") は、未実装。foldlParser で挿入するコンストラクタをどう選べばよいのか。 *)\n  end.\n\nDefinition parseAExp := parseSumExp.\n\nFixpoint parseAtomicExp (steps : nat) symtable : parser bexp :=\n  match steps with\n    | 0 =>\n      fun _ => NoneE \"Too_many_recursive_calls\"\n    | S steps' =>\n      (expect \"true\"%string\n              >>>\n              ret BTrue)\n        <|>\n        (expect \"false\"%string\n                >>>\n                ret BFalse)\n        <|>\n        (expect \"not\"%string\n                >>>\n                parseAtomicExp steps' symtable)\n        <|>\n        (expect \"(\"%string\n                >>>\n                parseConjunctionExp steps' symtable\n                <<<\n                expect \")\"%string)\n        <|>\n        (parseProductExp steps' symtable\n                         >>=\n                         fun x =>\n                           (expect \"==\"%string\n                                   >>>\n                                   (parseAExp steps' symtable)\n                                   >>=\n                                   fun x' => ret (BEq x x'))\n                             <|>\n                             (expect \"<=\"%string\n                                     >>>\n                                     (parseAExp steps' symtable)\n                                     >>=\n                                     fun x' => ret (BLe x x')))\n  end\nwith parseConjunctionExp (steps : nat) symtable : parser bexp :=\n  match steps with\n    | 0 =>\n      fun _ => NoneE \"Too_many_recursive_calls\"\n    | S steps' =>\n      parseAtomicExp steps' symtable\n                     >>=\n                     fun (x : bexp) =>\n                       foldlParser BAnd\n                                    x\n                                    (many steps' (expect \"&&\"%string\n                                                         >>>\n                                                         parseAtomicExp steps' symtable))\n  end.\n\nDefinition parseBExp := parseConjunctionExp.\n\nFixpoint parseSimpleCommand (steps : nat) symtable : parser com :=\n  match steps with\n    | 0 =>\n      fun _ => NoneE \"Too_many_recursive_calls\"\n    | S steps' =>\n      (expect \"SKIP\"%string\n              >>>\n              ret CSkip)\n        <|>\n        (expect \"IF\"%string\n                >>>\n                (parseBExp steps' symtable\n                           >>=\n                           fun x =>\n                             expect \"THEN\"%string\n                                    >>>\n                                    (parseSequencedCommand steps' symtable\n                                                           >>=\n                                                        fun x' =>\n                                                          expect \"ELSE\"%string\n                                                                 >>>\n                                                                 (parseSequencedCommand steps' symtable\n                                                                                     >>=\n                                                                                     fun x'' =>\n                                                                                       expect \"END\"%string\n                                                                                              >>>\n                                                                                              ret (CIf x x' x'')))))\n        <|>\n        (expect \"WHILE\"%string\n                >>>\n                (parseBExp steps' symtable\n                           >>=\n                           fun x =>\n                             expect \"DO\"%string\n                                    >>>\n                                    (parseSequencedCommand steps' symtable\n                                                        >>=\n                                                        fun x' =>\n                                                          expect \"END\"%string\n                                                                 >>>\n                                                                 ret (CWhile x x'))))\n        <|>\n        (parseIdentifier symtable\n                         >>=\n                         fun x =>\n                           expect \":=\"%string\n                                  >>>\n                                  (parseAExp steps' symtable\n                                             >>=\n                                             fun x' => ret (CAss x x')))\n  end\nwith parseSequencedCommand (steps : nat) symtable : parser com :=\n  match steps with\n    | 0 =>\n      fun _ => NoneE \"Too_many_recursive_calls\"\n    | S steps' =>\n      (parseSimpleCommand steps' symtable\n                          >>=\n                          fun x =>\n                            (expect \";\"%string\n                                    >>> \n                                    (parseSequencedCommand steps' symtable\n                                                           >>=\n                                                           fun x' => ret (CSeq x x')))\n                              <|>\n                              ret x)\n        \n  end.\n\nDefinition parse (str : string) : optionE (com * list token) :=\n  let tokens := tokenize str in             (* (1) *)\n    parseSequencedCommand 20                (* (3) *)\n    (build_symtable tokens 0)               (* (2) *)\n    tokens.\n\n(* Sample *)\nEval compute in build_symtable [:: \"a\"; \"+\"; \"b\"]%string.\nEval compute in build_symtable [:: \"a\"; \"+\"; \"b\"]%string 0 \"a\"%string. (* 0 *)\nEval compute in build_symtable [:: \"a\"; \"+\"; \"b\"]%string 0 \"b\"%string. (* 1 *)\n\nEval compute in parseNumber [:: \"123\"]%string.\nEval compute in parseIdentifier (build_symtable [:: \"a\"]%string 0)\n                                [:: \"a\"]%string.\nEval compute in parsePrimaryExp 1000 (build_symtable [::] 0)\n                                [:: \"123\"]%string.\nEval compute in parsePrimaryExp 1000 (build_symtable [::] 0)\n                                [:: \"(\"; \"123\"; \")\" ]%string.\nEval compute in parseProductExp 1000 (build_symtable [::] 0)\n                                [:: \"123\" ]%string.\nEval compute in parseProductExp 1000 (build_symtable [::] 0) (* 左結合になっている。 *)\n                                [:: \"123\"; \"*\"; \"456\"; \"*\"; \"789\"]%string.\nEval compute in parseSumExp 1000 (build_symtable [::] 0) (* 左結合になっている。 *)\n                            [:: \"123\"; \"+\"; \"456\"; \"+\"; \"789\"]%string.\nEval compute in parseAExp 1000 (build_symtable [::] 0)\n                          [:: \"(\"; \"123\"; \"+\"; \"345\"; \")\"; \"*\"; \"679\" ]%string.\nEval compute in parseAExp 1000 (build_symtable [::] 0)\n                          [:: \"123\"; \"+\"; \"345\"; \"*\"; \"679\" ]%string.\n\nEval compute in parseBExp 10 (build_symtable [::] 0)\n                          [:: \"123\"; \"==\"; \"345\" ]%string.\nEval compute in parseBExp 10 (build_symtable [::] 0)\n                          [:: \"123\"; \"==\"; \"345\"; \"&&\"; \"321\"; \"==\"; \"543\"]%string.\nEval compute in parseBExp 10 (build_symtable [::] 0) (* 左結合になっている。 *)\n                          [:: \"1\"; \"==\"; \"2\"; \"&&\"; \"3\"; \"<=\"; \"4\"; \"&&\";\n                           \"5\"; \"<=\"; \"6\"; \"&&\"; \"7\"; \"==\"; \"8\"]%string.\n\nEval compute in parseSimpleCommand 10 (build_symtable [::] 0)\n                                   [:: \"IF\"; \"1\"; \"==\"; \"1\"; \"THEN\"; \"SKIP\"; \"ELSE\"; \"SKIP\"; \"END\"]%string.\nEval compute in parseSimpleCommand 10 (build_symtable [::] 0)\n                                   [:: \"WHILE\"; \"1\"; \"==\"; \"1\"; \"DO\"; \"SKIP\"; \"END\"]%string.\nEval compute in parseSimpleCommand 10 (build_symtable [:: \"a\"; \"=\"; \"1\"]%string 0)\n                                   [:: \"a\"; \":=\"; \"1\"]%string.\nEval compute in parseSequencedCommand 10 (build_symtable [::] 0) (* 右結合になっている。 *)\n                                      [:: \"SKIP\"; \";\"; \"SKIP\"; \";\"; \"SKIP\"]%string.\n\nEval compute in parse \"\n    IF x == y + 1 + 2 + y * 6 + 3 THEN\n      x := x * 1;\n      y := 0\n    ELSE\n      SKIP\n    END  \".\n\nEval compute in parse \"\n    SKIP;\n    z:=x*y*(x*x);\n    WHILE x==x DO\n      IF z <= z*z && not x == 2 THEN\n        x := z;\n        y := z\n      ELSE\n        SKIP\n      END;\n      SKIP\n    END;\n    x:=z  \".\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/ssr/ssr_mpc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.28235771304224594}}
{"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 Goal Selector \"!\".\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    - apply Nop_Sem.\n    - apply Write_Sem.\n    - change (WriteString (s :: s' :: str')) with (WriteMove s D;; WriteString (s' :: str')).\n      eapply RealiseIn_monotone.\n      { apply Seq_RealiseIn.\n        - apply WriteMove_Sem.\n        - 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\n#[export] Hint Extern 1 (WriteString _ _ ⊨ _) => eapply RealiseIn_Realise; eapply WriteString_Sem : TMdb.\n#[export] Hint Extern 1 (WriteString _ _ ⊨c(_) _) => eapply WriteString_Sem : TMdb.\n#[export] Hint Extern 1 (projT1 (WriteString _ _) ↓ _) => eapply RealiseIn_TerminatesIn; eapply WriteString_Sem : TMdb.\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/TM/Compound/WriteString.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784220301064, "lm_q2_score": 0.4921881357207955, "lm_q1q2_score": 0.28235771304224583}}
{"text": "Require Import Hask.Data.Functor.\nRequire Import Hask.Control.Applicative.\nRequire Import Hask.Control.Monad.\n\nGeneralizable All Variables.\nSet Primitive Projections.\nSet Universe Polymorphism.\nUnset Transparent Obligations.\n\n#[export]\nInstance Compose_Functor `{Functor F} `{Functor G} : Functor (F \\o G) :=\n{ fmap := fun A B => @fmap F _ (G A) (G B) \\o @fmap G _ A B\n}.\n\n#[export]\nInstance Compose_Applicative (F : Type -> Type) (G : Type -> Type)\n  `{Applicative F} `{Applicative G} : Applicative (F \\o G)  :=\n{ is_functor := Compose_Functor (F:=F) (G:=G)\n; pure := fun A   => @pure F _ (G A) \\o @pure G _ A\n; ap   := fun A B => ap \\o fmap (@ap G _ A B)\n}.\n\n#[export]\nInstance Compose_Alternative\n  `{Alternative F} `{Alternative G} : Alternative (F \\o G) :=\n{ empty  := fun A => @empty F _ (G A)\n; choose := fun A => @choose F _ (G A) (* jww (2016-01-28): correct? *)\n}.\n\n#[export]\nInstance Compose_Monad `{Monad_Distributes M N}\n  : Monad (M \\o N) :=\n{ is_applicative := Compose_Applicative M N\n; join := fun A => join[M] \\o fmap[M] (prod M N A)\n}.\n\nRequire Import FunctionalExtensionality.\n\nModule ComposeMonadLaws.\n\nImport MonadLaws.\n\nCorollary fmap_compose  `{Functor F} `{Functor G} : forall {X Y} (f : X -> Y),\n  @fmap F _ (G X) (G Y) (@fmap G _ X Y f) = @fmap (F \\o G) _ X Y f.\nProof. reflexivity. Qed.\n\n#[export]\nProgram Instance Compose_FunctorLaws `{FunctorLaws F} `{FunctorLaws G} :\n  FunctorLaws (F \\o G).\nObligation 1. (* fmap_id *)\n  extensionality x.\n  do 2 rewrite fmap_id.\n  reflexivity.\nQed.\nObligation 2. (* fmap_comp *)\n  extensionality x.\n  do 2 rewrite fmap_comp.\n  reflexivity.\nQed.\n\nLocal Obligation Tactic := intros; simpl; apply_applicative_laws.\n\n#[export]\nProgram Instance Compose_ApplicativeLaws\n  `{ApplicativeLaws F} `{ApplicativeLaws G} : ApplicativeLaws (F \\o G).\nObligation 2. (* ap_composition *)\n  (* Discharge w *)\n  rewrite <- ap_comp; f_equal.\n  (* Discharge v *)\n  rewrite <- !ap_fmap, <- ap_comp.\n  symmetry.\n  rewrite <- ap_comp; f_equal.\n  (* Discharge u *)\n  apply_applicative_laws.\n  f_equal.\n  extensionality y.\n  extensionality x.\n  extensionality x0.\n  rewrite <- ap_comp, ap_fmap.\n  reflexivity.\nQed.\n\n#[export]\nProgram Instance Compose_MonadLaws\n        `{Monad_DistributesLaws M N (H:=Compose_Applicative M N)} :\n  MonadLaws (M \\o N).\nObligation 1. (* monad_law_1 *)\n  intros.\n  rewrite <- comp_assoc with (f := join[M]).\n  rewrite <- comp_assoc with (f := join[M]).\n  rewrite comp_assoc with (f := fmap[M] (prod M N a)).\n  rewrite <- join_fmap_fmap.\n  rewrite <- comp_assoc.\n  rewrite comp_assoc with (f := join[M]).\n  rewrite comp_assoc with (f := join[M]).\n  rewrite <- join_fmap_join.\n  repeat (rewrite <- comp_assoc).\n  repeat (rewrite fmap_comp).\n  repeat (rewrite comp_assoc).\n  rewrite <- prod_fmap_join_fmap_prod.\n  reflexivity.\nQed.\nObligation 2. (* monad_law_2 *)\n  intros.\n  rewrite <- join_fmap_pure.\n  repeat (rewrite <- comp_assoc).\n  repeat (rewrite fmap_comp).\n  repeat f_equal.\n  pose proof (@prod_fmap_pure M N _ _ _ _ _ a).\n  simpl in H3.\n  rewrite H3.\n  reflexivity.\nQed.\nObligation 3. (* monad_law_3 *)\n  intros.\n  rewrite <- prod_pure.\n  rewrite <- comp_id_left.\n  rewrite <- (@join_pure M _ _ (N a)).\n  rewrite <- comp_assoc.\n  rewrite <- comp_assoc.\n  f_equal.\n  rewrite comp_assoc.\n  rewrite comp_assoc.\n  f_equal.\n  rewrite <- fmap_pure.\n  reflexivity.\nQed.\nObligation 4. (* monad_law_4 *)\n  intros.\n  unfold comp at 2.\n  rewrite comp_assoc.\n  rewrite <- join_fmap_fmap.\n  rewrite <- comp_assoc.\n  rewrite fmap_comp.\n  pose proof (@prod_fmap_fmap M N _ _ _ _ _ a).\n  simpl in H3.\n  rewrite <- H3.\n  rewrite <- fmap_comp.\n  reflexivity.\nQed.\n\nEnd ComposeMonadLaws.\n", "meta": {"author": "jwiegley", "repo": "coq-haskell", "sha": "56a185af5767177d410113a03bd765135e07c9ca", "save_path": "github-repos/coq/jwiegley-coq-haskell", "path": "github-repos/coq/jwiegley-coq-haskell/coq-haskell-56a185af5767177d410113a03bd765135e07c9ca/src/Control/Compose.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.2823577058673257}}
{"text": "(** * Definition of minimal parse trees *)\nRequire Import Coq.Strings.String Coq.Lists.List.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.BaseTypes.\n\nLocal Coercion is_true : bool >-> Sortclass.\n\nSet Implicit Arguments.\nLocal Open Scope string_like_scope.\n\nSection cfg.\n  Context {Char} {HSLM : StringLikeMin Char} {G : grammar Char}.\n  Context {predata : @parser_computational_predataT Char}\n          {rdata' : @parser_removal_dataT' _ G predata}.\n\n  Inductive minimal_maybe_empty_productions : nonterminals_listT -> productions Char -> Type :=\n  | MinMaybeEmptyHead : forall valid pat pats, minimal_maybe_empty_production valid pat\n                                               -> minimal_maybe_empty_productions valid (pat::pats)\n  | MinMaybeEmptyTail : forall valid pat pats, minimal_maybe_empty_productions valid pats\n                                               -> minimal_maybe_empty_productions valid (pat::pats)\n  with minimal_maybe_empty_production : nonterminals_listT -> production Char -> Type :=\n  | MinMaybeEmptyProductionNil : forall valid, minimal_maybe_empty_production valid nil\n  | MinMaybeEmptyProductionCons : forall valid it its, minimal_maybe_empty_item valid it\n                                                       -> minimal_maybe_empty_production valid its\n                                                       -> minimal_maybe_empty_production valid (it::its)\n  with minimal_maybe_empty_item : nonterminals_listT -> item Char -> Type :=\n  | MinMaybeEmptyNonTerminal : forall valid nt, is_valid_nonterminal valid (of_nonterminal nt)\n                                                -> minimal_maybe_empty_productions (remove_nonterminal valid (of_nonterminal nt)) (Lookup G nt)\n                                                -> minimal_maybe_empty_item valid (NonTerminal nt).\n\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/Minimal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.28235770586732567}}
{"text": "Require Import ssreflect ssrnat ssrbool seq Ssromega OtDef Commons.\n\nLemma ltnSn n: n < S n. ssromega. Qed.\nLemma list_const: forall X X' (l : list X') (x : X), match l with nil => x | _ :: _ => x end = x.\nProof. intros. destruct l; reflexivity. Qed.\n\nLemma tstab {cmd} t: forall n k (op1 op2 op1' op2' : list cmd),\ntransform t op1 op2 n = Some (op2', op1') -> transform t op1 op2 (n + k) = Some (op2', op1').\nProof. elim => [|n IHn] k [|o1 op1] [|o2 op2] op1' op2' //=.\nmove A1: (transform t _ _ n) => [[x y]|] //; move A2: (transform t _ _ n) => [[x' y']|] // h.\nby rewrite (IHn k _ _ _ _ A1) (IHn k _ _ _ _ A2) h. Qed.\n\n(* =============================================== *)\n\nSection OTCorrectness.\n\nContext {X cmd : Type} (ot : OTBase X cmd) (comp : @OTComp X cmd ot).\n\nLemma sz_nil: sz nil = 0. by rewrite /sz. Qed.\nLemma si_nil: si nil = 0. by rewrite /si. Qed.\n\nLemma cats_sz (l1 l2 : list cmd): sz (l1 ++ l2) = sz l1 + sz l2.\nelim: l1 l2 => [| l ls IHl] l2. by rewrite cat0s sz_nil add0n. rewrite /sz /= in IHl.\nby rewrite cat_cons /sz /= ?add0n fadd (fadd (cmdsz l)) IHl addnA. Qed.\n\nLemma cats_si (l1 l2 : list cmd): si (l1 ++ l2) = si l1 + si l2.\nelim: l1 l2 => [| l ls IHl] l2. by rewrite cat0s si_nil add0n. rewrite /si /= in IHl.\nby rewrite cat_cons /si /= ?add0n fadd (fadd (cmdsi l)) IHl addnA. Qed.\n\nLemma execute_app: forall (op1 op2 : list cmd) (m : option X),\n(exec_all interp) m (op1 ++ op2) = (exec_all interp) (exec_all interp m op1) op2.\nelim => [| x xs IHx] op2 m //. rewrite cat_cons /= IHx //. Qed.\n\nLemma execute_none op: exec_all interp None op = None. \nby elim: op => [|x xs IHx] //=. Qed.\n\nLemma transform_ind: \nforall (op1 op2 : list cmd) n, transform it op1 op2 (S n) = \n  match op1, op2 with\n    | nil, _ | _, nil => Some (op2, op1)\n    | x :: xs, y :: ys => \n       match transform it xs (it y x false) n with\n         Some (y'', xs') => \n          match transform it ((it x y true) ++ xs') ys n with\n            Some (ys', x'') => Some (y'' ++ ys', x'') \n            | _ => None\n          end\n         | _ => None\n       end\n  end. done. Qed.\n\nTheorem ot_computability': forall n m (op1 op2 : list cmd), \n(sz op1 + sz op2 < n) -> (si op1 + si op2 < m) ->\n (exists n, exists op1', exists op2', transform it op1 op2 n = Some (op2', op1') /\\\n (sz op1' + sz op2' <= sz op1 + sz op2) /\\ \n (si op1' + si op2' <= si op1 + si op2) /\\ \n   (((sz op1' <= sz op1) /\\ (sz op2' <= sz op2)) \\/\n    (si op1' + si op2' < si op1 + si op2))).\n elim => [|n IHn].\n + move => m op1 op2 h. by have: False by ssromega.\n + elim => [|m IHm] // op1 op2.\n  case: op1 => [*|x xs].\n  + exists 1. exists (@nil cmd). exists op2. \n    rewrite ?sz_nil ?si_nil ?add0n /=. split. done.\n    split. ssromega. split. ssromega. left. split; ssromega.\n  + case: op2 => [*|y ys].\n    + exists 1. exists (x :: xs). exists (@nil cmd).\n    rewrite ?sz_nil ?si_nil ?add0n ?addn0 /=. split. done.\n    split. ssromega. split. ssromega. left. split; ssromega.\n      replace (x :: xs) with ([::x] ++ xs); [| by simpl].\n      replace (y :: ys) with ([::y] ++ ys); [| by simpl].\n    + rewrite ?cats_sz ?cats_si.\n      move => h h'. assert (AA := comp_corr x y false). rewrite /computability /= in AA.\n      rewrite /cat. assert (E0 := sz_nondg x). assert (E1 := sz_nondg y).\n      assert (E0': sz [::x] > 0). by rewrite /sz.\n      assert (E1': sz [::y] > 0). by rewrite /sz. clear E0 E1.\n      move Heqy': (@it _ _ ot x y true) => x'.\n      move Heqx': (@it _ _ ot y x false) => y'.\n      rewrite Heqx' Heqy' in AA.\n      move: AA => /= [B1[B2[[B0 B0']|B0 {B2}]]];\n      [assert (A0: sz xs + sz y' < n) by ssromega;\n       move: (IHn (S (si xs + si y')) xs y' A0 (ltnSn _)) |\n       assert (A0: sz xs + sz y' < n.+1) by ssromega;\n       assert (A0': si xs + si y' < m) by ssromega;\n       move: (IHm xs y' A0 A0') ];\n      move => [n'1 [xs' [y'' [C1 [C2 [C3 C4]]]]]] {A0};\n      [move: C4 => [[C01 C02]|C0];\n        [ assert (A0: sz (x' ++ xs') + sz ys < n) by (rewrite cats_sz; ssromega);\n          move: (IHn (S (si (x' ++ xs') + si ys)) (x' ++ xs') ys A0 (ltnSn _)) => A1| \n          assert (A0: sz (x' ++ xs') + sz ys < S n) by (rewrite cats_sz; ssromega);\n          assert (A0': si (x' ++ xs') + si ys < m) by (rewrite cats_si; ssromega);\n          move: (IHm (x' ++ xs') ys A0 A0') => A1] |\n        assert (A0: sz (x' ++ xs') + sz ys < S n) by (rewrite cats_sz; ssromega);\n        clear A0'; assert (A0': si (x' ++ xs') + si ys < m) by (rewrite cats_si; ssromega);\n        move: (IHm (x' ++ xs') ys A0 A0') => A1];\n       rewrite cats_sz cats_si in A1;\n       move: A1 => [n'2 [op1' [ys' [D1 [D2 [D3 D4]]]]]];\n       apply (tstab _ _ n'2) in C1; apply (tstab _ _ n'1) in D1; rewrite addnC in D1;\n       exists (S (n'1 + n'2));\n       rewrite transform_ind Heqy' Heqx' C1 D1;\n       exists op1'; exists (y'' ++ ys'); rewrite ?cats_sz ?cats_si;\n       (split; [done|split;[ssromega|split;[ssromega|]]]).\n\n       + move: D4 => [[D41 D42]| D4];[left; split |right]; ssromega.\n       + right; ssromega.\n       + right; ssromega. Qed.\n \nCorollary ot_computability'' op1 op2: \n (exists n, exists op1', exists op2', transform it op1 op2 n = Some (op2', op1') /\\\n (sz op1' + sz op2' <= sz op1 + sz op2) /\\ \n (si op1' + si op2' <= si op1 + si op2) /\\ \n   (((sz op1' <= sz op1) /\\ (sz op2' <= sz op2)) \\/\n    (si op1' + si op2' < si op1 + si op2))).\nby apply (ot_computability' (S (sz op1 + sz op2)) (S (si op1 + si op2)) op1 op2 (ltnSn _) (ltnSn _)). Qed.\n\nCorollary ot_computable: forall (op1 op2 : list cmd), exists nSteps op1' op2', transform it op1 op2 nSteps = Some (op2', op1').\nmove => op1 op2. move: (ot_computability'' op1 op2). move => [n [op1' [op2' [A B]]]]. exists n. exists op1'. exists op2'. done. Qed.\n\nTheorem ot_execution: forall nSteps op1 op2 op1' op2' m (m1 m2 : X), exec_all interp m op1 = Some m1 /\\ exec_all interp m op2 = Some m2 ->\ntransform it op1 op2 nSteps = Some (op2', op1') ->\nexec_all interp (Some m1) op2' = exec_all interp (Some m2) op1' /\\ exists m3, exec_all interp (Some m1) op2' = Some m3.\nelim => [|n IHn] op1 op2 op1' op2' m m1 m2 [h h'] H0 //. rewrite transform_ind in H0.\ncase: op1 H0 h => [[H0 H1] [h]| x xs H0 h].\n  + rewrite -H0 -H1 -h /= h'. by eauto.\n  + case: op2 H0 h' h => [[H0 H1] [h']| y ys].\n    * rewrite -H0 -H1 -h' /=. eauto.\n    * move A0: (it y x false) => y'. move A1: (transform it xs y' n) => [[y'' xs']|] //.\n      move A2: (it x y true) => x'.  move A3: (transform it (x' ++ xs') ys n) => [[ys' x'']|] //= [H0 H1].\n      rewrite -H0 -H1 execute_app {H0 H1}.\n      case: m => [m|]; [|rewrite exec_all_none //]. rewrite /Basics.flip /=.\n      move M1: (interp x m) => [t1|]; [|rewrite execute_none]; rewrite //.\n      move M2: (interp y m) => [t2|]; [|rewrite execute_none]; move => // h h'.\n      move: (it_c1 _ _ true _ _ _ M1 M2). rewrite A0 A2. move => /= [B1 [s1 B2]]. rewrite B1 in B2.\n    \n      move: (IHn _ _ _ _ _ _ _ (conj h' B2) A1) => /= [C1 [s2 C2]].\n      assert (D1: exec_all interp (Some t2) (x' ++ xs') = Some s2). by rewrite execute_app B1 B2 -C1 C2.\n      move: (IHn _ _ _ _ _ _ _ (conj D1 h) A3) => /= [E1 [s3 E2]]. rewrite -E1 C2 E2. by eauto. Qed.\n\nCorollary ot_correctness: forall op1 op2 m (m1 m2 : X), \nexec_all interp m op1 = Some m1 /\\ exec_all interp m op2 = Some m2 ->\nexists nSteps op1' op2', transform it op1 op2 nSteps = Some (op2', op1') /\\\nexec_all interp (Some m1) op2' = exec_all interp (Some m2) op1' /\\ exists m3, exec_all interp (Some m1) op2' = Some m3.\nmove => op1 op2 m m1 m2 H. move: (ot_computable op1 op2) => [n [op1' [op2' A0]]].\nexists n. exists op1'. exists op2'. split. done. by move: (ot_execution _ _ _ _ _ _ _ _ H A0). Qed.\n\nEnd OTCorrectness.\n\n(* =============================================== *)\n\nModule TransformApp.\nRequire Import ssreflect ssrbool ssrfun ssrnat.\n\nCorollary tstab1 {cmd} t: forall n (op1 op2 op1' op2' : list cmd),\ntransform t op1 op2 n = Some (op2', op1') -> transform t op1 op2 (n.+1) = Some (op2', op1').\nintros. apply tstab with (k:=1) in H. by rewrite -addn1. Qed.\n\nLemma tr_through_nil {cmd} t (l : list cmd) n: \ntransform t l nil n.+1 = Some (nil, l). by rewrite /= list_const. Qed.\n\nLemma tr_nil {cmd} t (l : list cmd) n:\ntransform t nil l n.+1 = Some (l, nil). done. Qed.\n\nLemma part_lemma {cmd} t n: forall (y : cmd) x ys y' x',\ntransform t x (y :: ys) n = Some (y', x') ->\nmatch transform t x [:: y] n with \n  Some (y', x') => match transform t x' ys n with \n                     Some (ys', x'') => Some (y' ++ ys', x'')\n                     | _ => None\n                   end\n  | _ => None\nend = Some (y', x').\nintros. case: n x H => [|n] [|x xs] // H. simpl in H.\ncase A0: (transform t xs (t y x false) n) H => [[a b]|] // H.\ncase A1: (transform t (t x y true ++ b) ys n) H => [[c d]|] // [A2 A3].\nremember (n.+1) as n1. rewrite {1}Heqn1 /= A0. destruct n. inversion A0.\nrewrite tr_through_nil cats0. subst. apply tstab1 in A1. rewrite A1. done. Qed.\n\nLemma part_lemma2 {cmd} t x (y : cmd) ys y' x' y1' x'' n:\ntransform t x [:: y] n = Some (y', x') ->\ntransform t x' ys n = Some (y1', x'') ->\ntransform t x (y :: ys) n.+1 = Some (y' ++ y1', x'').\ncase A1: n => [|n1] // H H0.\nsimpl in H. case: x H => [|x xs] //. simpl.\n + move => [*]. subst. by case: n1 H0 => [|n1] [H0 H1]; rewrite -H0 -H1.\n + case A0: transform => [[y''0 xs']|]//. destruct n1; [inversion A0|].\n   rewrite tr_through_nil cats0. move => [A2 A3]. subst.\n   remember (n1.+2) as n2. apply tstab1 in A0. rewrite -Heqn2 in A0. simpl. by rewrite A0 H0. Qed.\n\nLemma vpart1inv {cmd} t: forall y1 (x : list cmd) y2 k,\ntransform t x y1 k = None -> transform t x (y1 ++ y2) k = None.\nelim => [|y1 y1s IHy1]; intros. by case: k x H => [|k] [|a l].\ncase: k H => [|k] //. rewrite cat_cons. remember (k.+1) as k1. rewrite {1}Heqk1 /=.\ndestruct x. done. case A1: transform => [[y'' xs']|];[| by subst; rewrite /= A1].\ncase A2: transform => [[ys' x'']|] // A3 {A3}. subst. simpl. rewrite A1.\nby rewrite (IHy1 _ y2 _ A2). Qed.\n\nTheorem vpart1 {cmd} t: forall (y1 : list cmd) n x y2 y' x' y1' x'',\ntransform t x  y1 n = Some (y', x') ->\ntransform t x' y2 n = Some (y1', x'') ->\nexists k, transform t x (y1 ++ y2) k = Some (y' ++ y1', x'').\nelim => [|y y1s IHy] [|n] //; intros.\n + rewrite tr_through_nil in H. inversion H. subst. by exists n.+1.\n + move: (part_lemma _ _ _ _ _ _ _ H).\n   case A0: transform => [[y'0 x'0]|]//.\n   case A1: transform => [[ys' x''0]|]// [A2 A3].\n   rewrite A3 {A3 x''0} in A1. rewrite -A2. rewrite -A2 {A2 y'} in H.\n   move: (IHy _ _ _ _ _ _ _ A1 H0) => [k' A2]. apply (tstab _ _ (n.+1)) in A2.\n   apply (tstab _ _ k') in A0. rewrite addSn in A0. rewrite addnS addnC in A2. \n   exists (n + k').+2. by rewrite cat_cons (part_lemma2 _ _ _ _ _ _ _ _ _ A0 A2) catA. Qed. \n\nTheorem vpart2 {cmd} t: forall (y1 y2 x : list cmd) y' x' n,\ntransform t x (y1 ++ y2) n = Some (y', x') ->\nmatch transform t x y1 n with\n  Some (y1', x') => match transform t x' y2 n with\n                     Some (y2', x'') => Some (y1' ++ y2', x'')\n                     | _ => None\n                   end\n  | _ => None\nend = Some (y', x').\nelim => [|y y1s IHy1] y2 x Y' X' [|n] H //.\n + rewrite /= list_const. case: x y2 H => [|a b] [|c d] //= H. by rewrite H.\n + remember (n.+1) as n1. rewrite cat_cons in H. move: (part_lemma _ _ _ _ _ _ _ H).\n   case A0: transform => [[y' x']|] //. case A1: transform => [[ys' x'']|] // [B0 B1].\n   rewrite -B1 -B0. rewrite -B1 -B0 {B0 B1 X' Y'} in H.\n   move: (IHy1 _ _ _ _ _ A1).\n   case A2: transform => [[y1' x'0]|] //.\n   case A3: transform => [[y2' x''0]|] // [B2 B3].\n   rewrite B3 {B3 x''0 }in A3. rewrite -B2. rewrite -B2 {B2 ys'} in H A1.\n   destruct n1; [inversion A0|].\n   case A4: transform => [[y1'0 x'1]|];[|by rewrite -cat_cons (vpart1inv t (y::y1s) x y2 (n1.+1) A4) in H].\n   move: (part_lemma2 _ _ _ _ _ _ _ _ _ A0 A2) => H0. apply tstab1 in A4. rewrite A4 in H0. inversion H0. subst.\n   by rewrite A3 catA. Qed. \n\nTheorem hpart2 {cmd} t n: forall (x1 x2 y y' x': list cmd),\ntransform t (x1 ++ x2) y n = Some (y', x') ->\nexists k,\nmatch transform t x1 y k with\n  Some (y', x1') => \n   match transform t x2 y' k with\n    Some (y'', x2') => Some (y'', x1' ++ x2')\n    | _ => None\n   end\n  | _ => None\nend = Some (y', x').\nelim: n => [|n IHn]. done. remember (n.+1) as n1.\ncase => [|x1 x1s] x2 y Y' X'; intros.\n + rewrite /= in H. exists n1.+1. by rewrite tr_nil (tstab1 _ _ _ _ _ _ H).\n + case: y H => [|y ys] H.\n  + rewrite Heqn1 tr_through_nil in H. move: H => [A0 A1].\n    exists n1. by rewrite Heqn1 2!tr_through_nil -A0 -A1 -cat_cons.\n  + move: H. rewrite {1}Heqn1 /=.\n    case A0: transform => [[y'' xs']|] //.\n    case A1: transform => [[ys' X'2]|] // [A2 A3].\n    move: (IHn _ _ _ _ _ A0) => [k1].\n    case A4: transform => [[y' x1s']|] //.\n    case A5: transform => [[y''1 x2']|] // [A6 A7].\n    rewrite -A7 {A7 xs'} in A1 A0. rewrite A3 {A3 X'2} catA in A1. \n    rewrite A6 {A6 y''1} in A5. rewrite -A2 {A2 Y'}.\n    move: (IHn _ _ _ _ _ A1) => [k2].\n    case A6: transform => [[ys0' x1'']|] //.\n    case A7: transform => [[y''0 x2'']|] // [A8 A9].\n    rewrite -A9. rewrite -A9 {X' A9} in A1. rewrite A8 {A8 y''0} in A7.\n    apply (tstab _ _ k2) in A5. apply (tstab _ _ k1) in A7.\n    apply (tstab _ _ k2) in A4. apply (tstab _ _ k1) in A6.\n    rewrite addnC in A6 A7.\n    move: (vpart1 _ _ _ _ _ _ _ _ _ A5 A7) => [k'' B].\n    exists (k1+k2+k'').+1. remember (k1+k2+k'').+1 as k. rewrite {1}Heqk /=.\n    apply (tstab _ _ k'') in A4. apply (tstab _ _ k'') in A6.\n    apply (tstab _ _ (k1+k2)) in B. rewrite addnC in B.    \n    by rewrite A4 A6 Heqk (tstab1 _ _ _ _ _ _ B). Qed.\n\nEnd TransformApp. \n\n(* =============================================== *)\n\nModule Transform2.\n\nFixpoint transform2 {cmd} (t : cmd -> cmd -> bool -> list cmd) (op1 op2 : list cmd) (nSteps : nat) : option ((list cmd) * (list cmd)) :=\nmatch nSteps with 0 => None | S nSteps' =>\n  match op1, op2 with\n    | nil, _ | _, nil => Some (op2, op1)\n    | x :: xs, y :: ys => let y' := t y x false in let x' := t x y true in\n       match transform2 t xs y' nSteps', transform2 t x' ys nSteps' with\n         Some (y'', xs'), Some (ys', x'') => \n          match transform2 t xs' ys' nSteps' with\n            Some (ys'', xs'') => Some (y'' ++ ys'', x'' ++ xs'') \n            | _ => None\n          end\n         | _, _ => None\n       end\n  end\nend.\n\nLemma tstab2 {cmd} t: forall n k (op1 op2 op1' op2' : list cmd),\ntransform2 t op1 op2 n = Some (op2', op1') -> \ntransform2 t op1 op2 (n + k) = Some (op2', op1').\nelim => [|n IHn] k [|o1 op1] [|o2 op2] op1' op2' //=.\ncase A1: transform2 => [[y'' xs']|] //. case A2: transform2 => [[ys' x'']|] //.\ncase A3: transform2 => [[ys'' xs'']|] // [B0 B1]. subst.\nby rewrite (IHn k _ _ _ _ A1) (IHn k _ _ _ _ A2) (IHn k _ _ _ _ A3). Qed.\n\nCorollary tstab12 {cmd} t: forall n (op1 op2 op1' op2' : list cmd),\ntransform2 t op1 op2 n = Some (op2', op1') -> transform2 t op1 op2 (n.+1) = Some (op2', op1').\nintros. apply tstab2 with (k:=1) in H. by rewrite -addn1. Qed.\n\nLemma tr2_through_nil {cmd} t (l : list cmd) n: \ntransform2 t l nil n.+1 = Some (nil, l). by rewrite /= list_const. Qed.\n\nLemma tr2_nil {cmd} t (l : list cmd) n:\ntransform2 t nil l n.+1 = Some (l, nil). done. Qed.\n\nEnd Transform2.\n", "meta": {"author": "JetBrains", "repo": "ot-coq", "sha": "8228355a42bdbc51d0824c2fa4f1569dc182d11e", "save_path": "github-repos/coq/JetBrains-ot-coq", "path": "github-repos/coq/JetBrains-ot-coq/ot-coq-8228355a42bdbc51d0824c2fa4f1569dc182d11e/Comp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.28235770586732567}}
{"text": "From Tweetnacl Require Import Libs.Export.\nFrom Tweetnacl Require Import ListsOp.Export.\nFrom Tweetnacl Require Import Low.Z.\nFrom Tweetnacl Require Import Low.Reduce_by_P_compose_step.\nFrom Tweetnacl Require Import Low.Reduce_by_P_compose_1.\nFrom Tweetnacl Require Import Low.Reduce_by_P_compose_2.\nFrom Tweetnacl Require Import Low.Reduce_by_P_compose.\nFrom stdpp Require Import list.\nRequire Import Recdef.\nRequire Import ssreflect.\nOpen Scope Z.\n\n\nLemma bound_a_subst_step_2 : forall a m,\n  0 < a < 15 ->\n  Zlength m = 16 ->\n  Forall (fun x => -2^16 < x <= 0) (take (Z.to_nat (a + 1)) m) ->\n  - 2 ^ 16 ≤ nth (Z.to_nat a) (sub_fn_rev_s 1 sub_step_2 (a + 1) m) 0 ∧ nth (Z.to_nat a) (sub_fn_rev_s 1 sub_step_2 (a + 1) m) 0 ≤ 0.\nProof.\nintros.\n  rewrite sub_fn_rev_s_n.\n  2: omega.\n  remember (sub_fn_rev_s 1 sub_step_2 (a + 1 - 1) m) as m'.\n  replace (a + 1 - 1) with a by omega.\n  rewrite /sub_step_2.\n  rewrite upd_nth_diff_Zlength.\n  4: intro Ha; apply (f_equal Z.of_nat) in Ha ; repeat rewrite Z2Nat.id in Ha ; omega.\n  rewrite upd_nth_same_Zlength.\n  2,3,4: subst m' ; rewrite ?upd_nth_Zlength ?Z2Nat.id ?sub_fn_rev_s_sub_step_2_Zlength ; omega.\n  rewrite /subst_c.\n  assert(Handb:= and_0_or_1 (nth (Z.to_nat (a - 1)) m' 0 ≫ 16)).\n  assert(Handbb: Z.land (nth (Z.to_nat (a - 1)) m' 0 ≫ 16) 1 = 0 \\/ Z.land (nth (Z.to_nat (a - 1)) m' 0 ≫ 16) 1 = 1) by omega.\n  clear Handb.\n  assert(- 2 ^ 16 < nth (Z.to_nat a) m' 0 ∧ nth (Z.to_nat a) m' 0 ≤ 0).\n  replace (a + 1 - 1) with a in Heqm' by omega.\n  {\n  rewrite nth_drop_2.\n  subst m'.\n  rewrite sub_fn_rev_f_skip.\n  2: rewrite Zlength_correct in H0.\n  2: omega.\n  2: omega.\n  2: {\n  replace (length m')%nat with (Z.to_nat (Z.of_nat (length m')))%nat by (apply Nat2Z.id).\n  all: rewrite -Z2Nat.inj_le ; subst.\n  all: rewrite -?Zlength_correct.\n  all: rewrite ?sub_fn_rev_s_sub_step_2_Zlength ; omega.\n  }\n  rewrite -nth_drop_2.\n  2: {\n  replace (length m)%nat with (Z.to_nat (Z.of_nat (length m)))%nat by (apply Nat2Z.id).\n  all: rewrite -Z2Nat.inj_le -?Zlength_correct ; omega.\n  }\n  rewrite -(nth_take_full _ (Z.to_nat (a + 1))).\n  2: rewrite -Z2Nat.inj_lt ; omega.\n  apply Forall_nth_d.\n  compute ; split ; [reflexivity | intros; discriminate].\n  change_Z_to_nat.\n  assumption.\n  }\n  destruct Handbb as [Handbb|Handbb] ; rewrite Handbb ;  try omega.\nQed.\n\n\n\n\n\n\nLemma bound_a_subst_step_2_lss : forall a m,\n  0 < a < 15 ->\n  Zlength m = 16 ->\n  Forall (fun x => -2^16 < x < 2^16) (take (Z.to_nat (a + 1)) m) ->\n  - 2 ^ 16 ≤ nth (Z.to_nat a) (sub_fn_rev_s 1 sub_step_2 (a + 1) m) 0 ∧ nth (Z.to_nat a) (sub_fn_rev_s 1 sub_step_2 (a + 1) m) 0 < 2^16.\nProof.\nintros.\n  rewrite sub_fn_rev_s_n.\n  2: omega.\n  remember (sub_fn_rev_s 1 sub_step_2 (a + 1 - 1) m) as m'.\n  replace (a + 1 - 1) with a by omega.\n  rewrite /sub_step_2.\n  rewrite upd_nth_diff_Zlength.\n  4: intro Ha; apply (f_equal Z.of_nat) in Ha ; repeat rewrite Z2Nat.id in Ha ; omega.\n  rewrite upd_nth_same_Zlength.\n  2,3,4: subst m' ; rewrite ?upd_nth_Zlength ?Z2Nat.id ?sub_fn_rev_s_sub_step_2_Zlength ; omega.\n  rewrite /subst_c.\n  assert(Handb:= and_0_or_1 (nth (Z.to_nat (a - 1)) m' 0 ≫ 16)).\n  assert(Handbb: Z.land (nth (Z.to_nat (a - 1)) m' 0 ≫ 16) 1 = 0 \\/ Z.land (nth (Z.to_nat (a - 1)) m' 0 ≫ 16) 1 = 1) by omega.\n  clear Handb.\n  assert(- 2 ^ 16 < nth (Z.to_nat a) m' 0 ∧ nth (Z.to_nat a) m' 0 < 2^16).\n  replace (a + 1 - 1) with a in Heqm' by omega.\n  {\n  rewrite nth_drop_2.\n  subst m'.\n  rewrite sub_fn_rev_f_skip.\n  2: rewrite Zlength_correct in H0.\n  2: omega.\n  2: omega.\n  2: {\n  replace (length m')%nat with (Z.to_nat (Z.of_nat (length m')))%nat by (apply Nat2Z.id).\n  all: rewrite -Z2Nat.inj_le ; subst.\n  all: rewrite -?Zlength_correct.\n  all: rewrite ?sub_fn_rev_s_sub_step_2_Zlength ; omega.\n  }\n  rewrite -nth_drop_2.\n  2: {\n  replace (length m)%nat with (Z.to_nat (Z.of_nat (length m)))%nat by (apply Nat2Z.id).\n  all: rewrite -Z2Nat.inj_le -?Zlength_correct ; omega.\n  }\n  rewrite -(nth_take_full _ (Z.to_nat (a + 1))).\n  2: rewrite -Z2Nat.inj_lt ; omega.\n  apply Forall_nth_d.\n  compute ; split ; reflexivity.\n  change_Z_to_nat.\n  assumption.\n  }\n  destruct Handbb as [Handbb|Handbb] ; rewrite Handbb ;  try omega.\nQed.\n\nLocal Ltac solve_this_assert :=\n  rewrite sub_fn_rev_s_n; try omega;\n  rewrite sub_step_2_Z_inv_lss; Grind_add_Z; try assumption;\n  rewrite ?sub_fn_rev_s_sub_step_2_Zlength ; try omega;\n  apply bound_a_subst_step_2_lss ; auto ; try omega;\n  eapply Forall_take_n_m ; [| eauto];\n  Grind_add_Z ; change_Z_to_nat ; omega.\n\nLocal Ltac gen_goals P j n := match n with\n  | 0 => idtac\n  | n =>\n    let n'' := (eval compute in (j - n)) in\n    assert(P n'');\n    [simpl ; solve_this_assert|];\n   let n' := (eval compute in (n - 1)) in\n   gen_goals P j n'\n  end.\n\nLemma sub_fn_rev_s_sub_step_2_inv : forall a m,\n  0 < a < 16 ->\n  Zlength m = 16 ->\n  Forall (fun x => - 2^16 < x < 2^16) (take 15 m) ->\n  ZofList 16 (sub_fn_rev_s 1 sub_step_2 a m) = ZofList 16 m.\nProof.\nintros a m Ha Hm Hb.\nassert(Hbound: forall a, 0 < a /\\ a < 16 -> - 2^16 < nth (Z.to_nat (a - 1)) m 0 < 2^16).\n{\n  intros x Hx.\n  replace(nth (Z.to_nat (x - 1)) m 0) with (nth (Z.to_nat (x - 1)) (take 15 m) 0).\n  apply Forall_nth_d.\n  compute ; split ; reflexivity.\n  assumption.\n  apply nth_take_full.\n  change 15%nat with (Z.to_nat 15).\n  apply Z2Nat.inj_lt ; omega.\n}\nassert(H1: ℤ16.lst sub_fn_rev_s 1 sub_step_2 1 m = ℤ16.lst m).\n  rewrite sub_fn_rev_s_1 ; reflexivity.\nassert(H2: ℤ16.lst sub_fn_rev_s 1 sub_step_2 2 m = ℤ16.lst m).\n  rewrite sub_fn_rev_s_n ; try apply sub_step_2_Z_inv_lss; [omega | | omega].\n  assert(Haspe: 0 < 2 - 1 /\\ 2 - 1 < 16) by omega.\n  apply Hbound in Haspe; omega.\ngen_goals (fun x => (ℤ16.lst sub_fn_rev_s 1 sub_step_2 x m = ℤ16.lst m)) 16 13.\nassert_gen_hyp_ Hadec a 15 14 ; try omega.\nrepeat match goal with\n  | _ => assumption\n  | _ => progress subst\n  | [ H : _ \\/ _ |- _ ] => destruct H\nend.\nQed.\n\nClose Scope Z.\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/proofs/spec/Low/Reduce_by_P_compose_2b.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.282195906667234}}
{"text": "Require Import Framework.\nRequire Import String.\nRequire Import Common.\n\nRequire Import Src.\nRequire Import Trg.\nRequire Import ASrc.\nRequire Import ATrg.\n\nRequire Import TrgAnalysis.\n\nModule CFFramework := Framework CFObs.\n\nModule CaseStudy.\n  Definition src :=\n    CFFramework.Build_language\n      Src.configuration (* Whole__S *)\n      Src.partial (* Partial__S *)\n      Src.ctx (* Context__S *)\n      (fun C P => Src.initial_cfg (Src.link C P)) (* Linking *)\n      Src.step. (* SOS semantics with observables *)\n\n  Definition trg :=\n    CFFramework.Build_language\n      Trg.configuration\n      Trg.partial\n      Trg.ctx\n      (fun C P => Trg.initial_cfg (Trg.link C P))\n      Trg.step.\n\n  (* The abstract source language is just src with a \"testing\" semantics *)\n  Axiom k : nat. (* The maximum number of steps allowed by testing *)\n  Axiom TestList : list Src.buf_contents. (* This is the set of inputs *)\n\n  Definition asrc :=\n    CFFramework.Build_language\n      ASrc.configuration (* Whole__S *)\n      Src.partial (* Partial__S *)\n      Src.ctx (* Context__S *)\n      (fun C P => ASrc.initial_cfg k (Src.initial_cfg (Src.link C P))) (* Linking *)\n      (ASrc.step TestList). (* SOS semantics with observables *)\n\n  (* The source analysis is trivial *)\n  Definition α__src :=\n    (CFFramework.Build_analysis src asrc)\n      (fun P => P)\n      (fun C => C)\n      (fun W => ASrc.initial_cfg k W).\n\n  (* This proof is done pencil and paper in the attached README.org file *)\n  Theorem completeness_α__src : CFFramework.complete α__src.\n  Proof. Admitted.\n\n  (* The abstract target language is that of history expressions *)\n  Definition atrg :=\n    CFFramework.Build_language\n      ATrg.configuration\n      ATrg.partial\n      ATrg.ctx\n      (fun C P => ATrg.initial_cfg (ATrg.link C P))\n      ATrg.step.\n\n  (* The source analysis is a simple type and effect system *)\n\n  Definition trgwhole_of_config (cfg : Trg.configuration) :=\n    match cfg with\n    | (b, W, T, M, u, f, ς, m, R, pc) => W\n    end.\n\n  Definition α__trg :=\n    (CFFramework.Build_analysis trg atrg)\n      TrgAnalysis.α__partial\n      TrgAnalysis.α__ctx\n      (fun trgcfg => ATrg.initial_cfg (TrgAnalysis.α__whole (trgwhole_of_config trgcfg))).\n\n  (* This proof is done pencil and paper in the attached README.org file *)\n  Theorem linearity_α__trg : CFFramework.llinear α__trg.\n  Proof. Admitted.\n\n  Theorem soundness_α__trg : CFFramework.sound α__trg.\n  Proof. Admitted.\nEnd CaseStudy.\n", "meta": {"author": "matteobusi", "repo": "stv", "sha": "dbe11dace0353b185d7aba84788d440e1ac05f39", "save_path": "github-repos/coq/matteobusi-stv", "path": "github-repos/coq/matteobusi-stv/stv-dbe11dace0353b185d7aba84788d440e1ac05f39/example/CaseStudy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.28219201457598425}}
{"text": "Require Import VST.msl.seplog.\nRequire Import VST.msl.base.\nRequire Import VST.msl.ageable.\nRequire Import VST.msl.sepalg.\nRequire Import VST.msl.age_sepalg.\nRequire Import VST.msl.predicates_hered.\nRequire Import VST.msl.predicates_sl.\nRequire Import VST.msl.subtypes.\nRequire Import VST.msl.subtypes_sl.\nRequire Import VST.msl.predicates_rec.\nRequire Import VST.msl.contractive.\nRequire VST.msl.normalize.\n\nLocal Open Scope logic.\n\nInstance algNatDed (T: Type){agT: ageable T} : NatDed (pred T).\n  apply (mkNatDed _\n                    predicates_hered.andp\n                    predicates_hered.orp\n                    (@predicates_hered.exp _ _)\n                    (@predicates_hered.allp _ _)\n                    predicates_hered.imp predicates_hered.prop\n                    (@predicates_hered.derives _ _)).\n apply pred_ext.\n apply derives_refl.\n apply derives_trans.\n apply andp_right.\n apply andp_left1.\n apply andp_left2.\n apply orp_left.\n apply orp_right1.\n apply orp_right2.\n intros ? ?; apply @exp_right.\n intros ? ?; apply @exp_left.\n intros ? ?; apply @allp_left.\n intros ? ?; apply @allp_right.\n apply imp_andp_adjoint.\n repeat intro. eapply H; eauto. hnf; auto.\n repeat intro. hnf; auto.\n repeat intro. specialize (H a (necR_refl _)). simpl in H. auto.\n repeat intro. specialize (H b). simpl in H. auto.\nDefined.\n\nInstance algSepLog (T: Type) {agT: ageable T}{JoinT: Join T}{PermT: Perm_alg T}{SepT: Sep_alg T}{AgeT: Age_alg T} :\n      @SepLog (pred T) (algNatDed T).\n apply (mkSepLog _ (algNatDed T) predicates_sl.emp predicates_sl.sepcon\n            predicates_sl.wand predicates_sl.ewand).\n apply sepcon_assoc.\n apply sepcon_comm.\n intros. pose proof (wand_sepcon_adjoint P Q R). simpl. rewrite H; split; auto.\n intros; simpl. apply predicates_hered.pred_ext; simpl.\n          intros ? [w1 [w2 [? [? [? ?]]]]];  split; auto. exists w1; exists w2; repeat split; auto.\n          intros ? [? [w1 [w2 [? [? ?]]]]];  exists w1; exists w2; repeat split; auto.\n intros; intro; apply sepcon_derives; auto.\n intros; simpl; apply ewand_sepcon; auto.\n intros; simpl. apply ewand_TT_sepcon; auto.\n intros; simpl. intros w [w1 [w2 [? [? ?]]]]. exists w1,w2; repeat split; auto. exists w2; exists w; repeat split; auto.\n  intros; simpl. apply ewand_conflict; auto.\nDefined.\n\nInstance algClassicalSep (T: Type) {agT: ageable T}{JoinT: Join T}{PermT: Perm_alg T}{SepT: Sep_alg T}{AgeT: Age_alg T}:\n     @ClassicalSep (pred T) (algNatDed T)(algSepLog T).\n constructor; intros. simpl. apply predicates_sl.sepcon_emp.\nQed.\n\nDefinition Triv := predicates_hered.pred nat.\nInstance TrivNatDed: NatDed Triv := algNatDed nat.\nInstance TrivSeplog: SepLog Triv := @algSepLog nat _ _ _ _ (asa_nat).\nInstance TrivClassical: ClassicalSep Triv := @algClassicalSep _ _ _ _ _ asa_nat.\nInstance TrivIntuitionistic: IntuitionisticSep Triv.\n constructor. intros. hnf. intros. destruct H as [w1 [w2 [? [? _]]]].\n destruct H; subst; auto.\nQed.\n\nInstance algIndir (T: Type) {agT: ageable T}{JoinT: Join T}{PermT: Perm_alg T}{SepT: Sep_alg T}\n                {AgeT: Age_alg T}:\n         @Indir (pred T) (algNatDed T).\n apply (mkIndir _ _ (box laterM)); intros; simpl in *.\n apply @predicates_hered.now_later.\n apply @predicates_hered.axiomK.\n apply @predicates_hered.later_allp.\n simpl. intros; apply @box_ex.\n simpl. intros; apply @later_ex; auto.\n simpl. intros; apply @later_ex''.\n apply @predicates_hered.later_imp.\n apply @predicates_hered.later_prop.\n apply @predicates_hered.loeb; auto.\nDefined.\n\nInstance TrivIndir: Indir Triv := @algIndir nat _ _ _ _ asa_nat.\n\nSection SL2. Import VST.msl.seplog.\n\nClass RecIndir (A: Type) {NA: NatDed A}{IA: Indir A} := mkRecIndir {\n  fash : A -> Triv;\n  unfash : Triv -> A;\n  HORec : forall {X} (f: (X -> A) -> (X -> A)), X -> A;\n  unfash_fash:  forall P: A, unfash (fash P) |-- P;\n  fash_K: forall P Q, fash (P --> Q) |-- fash P --> fash Q;\n  fash_derives: forall P Q, P |-- Q -> fash P |-- fash Q;\n  unfash_derives:  forall P Q,  P |-- Q -> unfash P |-- unfash Q;\n  later_fash:  forall P, later (fash P) = fash (later P);\n  later_unfash:  forall P, later (unfash P) = unfash (later P);\n  fash_andp: forall P Q, fash (P && Q) = fash P && fash Q;\n  unfash_allp:  forall {B} (P: B -> Triv), unfash (allp P) = ALL x:B, unfash (P x);  subp_allp: forall G B (X Y:B -> A),  (forall x:B, G |-- fash (imp (X x) (Y x))) ->  G |-- fash (imp (allp X) (allp Y));\n  subp_exp: forall G B (X Y:B -> A),  (forall x:B, G |-- fash (imp (X x) (Y x))) ->  G |-- fash (imp (exp X) (exp Y));\n  subp_e: forall (P Q : A), TT |-- fash (P --> Q) -> P |-- Q;\n  subp_i1: forall P (Q R: A), unfash P && Q |-- R -> P |-- fash (Q --> R);\n fash_TT: forall G, G |-- fash TT;\n  HOcontractive: forall {X: Type} (f: (X -> A) -> (X -> A)), Prop :=\n         fun {X} f => forall P Q,  (ALL x:X, later (fash (P x <--> Q x))) |-- (ALL x:X, fash (f P x <--> f Q x));\n  HORec_fold_unfold : forall X (f: (X -> A) -> (X -> A)) (H: HOcontractive f), HORec f = f (HORec f)\n}.\n\nDefinition HOnonexpansive {A}{NA: NatDed A}{IA: Indir A}{RA: RecIndir A}\n        {X: Type} (f: (X -> A) -> (X -> A)) :=\n         forall P Q: X -> A,  (ALL x:X, fash (P x <--> Q x)) |-- (ALL x:X, fash (f P x <--> f Q x)).\nEnd SL2.\n\n\nNotation \"'#' e\" := (fash e) (at level 30, right associativity): logic.\nNotation \"'!' e\" := (unfash e) (at level 30, right associativity): logic.\nNotation \"P '>=>' Q\" := (# (P --> Q)) (at level 55, right associativity) : logic.\nNotation \"P '<=>' Q\" := (# (P <--> Q)) (at level 57, no associativity) : logic.\n\nDefinition algRecIndir (T: Type) {agT: ageable T}{JoinT: Join T}{PermT: Perm_alg T}{SepT: Sep_alg T}{AgeT: Age_alg T} :\n         @RecIndir (pred T) (algNatDed T) (algIndir T).\n apply (mkRecIndir _ _ _ subtypes.fash subtypes.unfash HoRec.HORec); intros; simpl.\n repeat intro. do 3 red in H. apply H; auto.\n apply @subtypes.fash_K.\n apply @subtypes.fash_derives; auto.\n intros ? ?. do 3 red in H0. apply H in H0. apply H0.\n apply @subtypes.later_fash; auto.\n apply @subtypes.later_unfash.\n apply @subtypes.fash_and.\n apply pred_ext; repeat intro; do 3 red in H; apply (H b); auto.\n apply @subtypes.subp_allp; auto.\n eapply @subtypes.subp_exp; auto.\n eapply @subtypes.subp_e; eauto.\n eapply @subtypes.subp_i1; eauto.\n repeat intro; hnf; auto.\n intros. apply HoRec.HORec_fold_unfold; auto.\nDefined.\n\nInstance TrivRecIndir: RecIndir Triv := algRecIndir nat.\n\nSection SL3. Import VST.msl.seplog.\n\nLemma fash_triv: forall P: Triv, fash P = P.\nProof.\n intros.\n apply pred_ext; intros ? ?.\n eapply H. unfold level; simpl.  unfold natLevel; auto.\n hnf; intros. eapply pred_nec_hereditary; try eapply H.\n apply nec_nat. auto.\nQed.\n\nClass SepRec  (A: Type) {NA: NatDed A}{SA: SepLog A}{IA: Indir A}{RA: RecIndir A} := mkSepRec {\n  unfash_sepcon_distrib: forall (P: Triv) (Q R: A),\n                 andp (unfash P) (sepcon Q R) = sepcon (andp (unfash P) Q) (andp (unfash P) R)\n}.\n\nEnd SL3.\n\nInstance algSepIndir (T: Type) {agT: ageable T}{JoinT: Join T}{PermT: Perm_alg T}{SepT: Sep_alg T}{AgeT: Age_alg T} :\n         @SepIndir (pred T) (algNatDed T) (algSepLog T) (algIndir T).\n apply mkSepIndir; simpl.\n apply @predicates_sl.later_sepcon; auto.\n apply @predicates_sl.later_wand; auto.\n apply @predicates_sl.later_ewand; auto.\nQed.\n\nInstance algSepRec (T: Type) {agT: ageable T}{JoinT: Join T}{PermT: Perm_alg T}{SepT: Sep_alg T}{AgeT: Age_alg T} :\n         @SepRec (pred T) (algNatDed T) (algSepLog T) (algIndir T)(algRecIndir T).\nconstructor.\n intros; simpl. apply subtypes_sl.unfash_sepcon_distrib.\nQed.\n\nInstance algCorableSepLog (T: Type) {agT: ageable T}{JoinT: Join T}{PermT: Perm_alg T}{SepT: Sep_alg T}{AgeT: Age_alg T} :\n         @CorableSepLog (pred T) (algNatDed T) (algSepLog T).\n  apply mkCorableSepLog with (corable := corable.corable).\n  + apply corable.corable_prop.\n  + apply corable.corable_andp.\n  + apply corable.corable_orp.\n  + apply corable.corable_imp.\n  + intros; apply corable.corable_allp; auto.\n  + intros; apply corable.corable_exp; auto.\n  + apply corable.corable_sepcon.\n  + apply corable.corable_wand.\n  + intros; simpl.\n    apply corable.corable_andp_sepcon1; auto.\nDefined.\n\nInstance algCorableIndir (T: Type) {agT: ageable T}{JoinT: Join T}{PermT: Perm_alg T}{SepT: Sep_alg T}{AgeT: Age_alg T} :\n         @CorableIndir (pred T) (algNatDed T) (algSepLog T) (algCorableSepLog T) (algIndir T).\n  unfold CorableIndir; simpl.\n  apply corable.corable_later.\nDefined.", "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/alg_seplog.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.28219201457598425}}
{"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: Assembly Verification for Lemmas            *)\n(*                                                                     *)\n(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)\n(*                                                                     *)\n(*          Yale Flint Group                                           *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** This file provide the contextual refinement proof between MPTInit layer and MPTBit layer*)\nRequire Import Coqlib.\nRequire Import Asm.\nRequire Import Values.\nRequire Import Integers.\nRequire Import CommonTactic.\nRequire Import AST.\nRequire Import Smallstep.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import LAsm.\n(*Require Import LoadStoreSem.*)\nRequire Import FunctionalExtensionality.\nRequire Import AsmImplLemma.\nRequire Import LRegSet.\nRequire Import Conventions.\nRequire Import AuxLemma.\n\nLocal Open Scope string_scope.\nLocal Open Scope error_monad_scope.\n\n(*\n Definition n_instr (n: int) (rs: regset) := rs # PC <- (Val.add (rs PC) (Vint n)).\n\n Definition n_instr_nf (n: int) (rs: regset) := \n   (undef_regs (CR ZF :: CR CF :: CR PF :: CR SF :: CR OF :: nil) rs) # PC <- (Val.add (rs PC) (Vint n)).\n\n Lemma nextinstr_n_instr:\n   forall rs,\n     nextinstr rs = n_instr Int.one rs.\n Proof.\n   unfold nextinstr, n_instr. \n   reflexivity.\n Qed.\n\n Lemma nextinstr_nf_n_instr_nf:\n   forall rs,\n     nextinstr_nf rs = n_instr_nf Int.one rs.\n Proof.\n   unfold nextinstr_nf, n_instr_nf. \n   reflexivity.\n Qed.\n\n Lemma regset_equal:\n   forall (rs1 rs2: regset),\n     (forall r, Pregmap.get r rs1 = Pregmap.get r rs2) ->\n     rs1 = rs2.\n Proof.\n   unfold Pregmap.get.\n   intros.\n   apply functional_extensionality.\n   trivial.\n Qed.\n\n Lemma n_instr_nf_n_instr:\n   forall rs n1 n2,\n     n_instr_nf n1 (n_instr n2 rs) = n_instr_nf (Int.add n2 n1) rs.\n Proof.\n   unfold n_instr, n_instr_nf. intros.\n   unfold undef_regs.\n   apply regset_equal.\n   intros reg.\n   repeat simpl_Pregmap.\n   repeat (rewrite Pregmap.gsspec).\n   simpl_destruct_reg; trivial.\n   destruct (rs PC); simpl; try reflexivity;\n   Int_Add_Simpl.\n Qed.\n\n Lemma n_instr_n_instr_nf:\n   forall rs n1 n2,\n     n_instr n1 (n_instr_nf n2 rs) = n_instr_nf (Int.add n2 n1) rs.\n Proof.\n   unfold n_instr, n_instr_nf. intros.\n   unfold undef_regs.\n   apply regset_equal.\n   intros reg.\n   repeat simpl_Pregmap.\n   repeat (rewrite Pregmap.gsspec).\n   simpl_destruct_reg; trivial.\n   destruct (rs PC); simpl; try reflexivity;\n   Int_Add_Simpl.\n Qed.\n\n Lemma n_instr_n_instr:\n   forall rs n1 n2,\n     n_instr n1 (n_instr n2 rs) = n_instr (Int.add n2 n1) rs.\n Proof.\n   unfold n_instr. intros.\n   apply regset_equal.\n   intros reg.\n   repeat simpl_Pregmap.\n   repeat (rewrite Pregmap.gsspec).\n   simpl_destruct_reg; trivial.\n   destruct (rs PC); simpl; try reflexivity;\n   Int_Add_Simpl.\n Qed.\n\n Lemma n_instr_nf_n_instr_nf:\n   forall rs n1 n2,\n     n_instr_nf n1 (n_instr_nf n2 rs) = n_instr_nf (Int.add n2 n1) rs.\n Proof.\n   unfold n_instr_nf. intros.\n   unfold undef_regs.\n   apply regset_equal.\n   intros reg.\n   repeat simpl_Pregmap.\n   repeat (rewrite Pregmap.gsspec).\n   simpl_destruct_reg; trivial.\n   destruct (rs PC); simpl; try reflexivity;\n   Int_Add_Simpl.\n Qed.\n\n Lemma n_instr_ireg_set:\n   forall rs n i v,\n     (n_instr n rs) # (IR i) <- v = n_instr n (rs # (IR i) <- v).\n Proof.\n   unfold n_instr. intros.\n   apply regset_equal.\n   intros reg.\n   repeat simpl_Pregmap.\n   repeat (rewrite Pregmap.gsspec).\n   simpl_destruct_reg; trivial.\n Qed.\n\n Lemma n_instr_nf_ireg_set:\n   forall rs n i v,\n     (n_instr_nf n rs) # (IR i) <- v = n_instr_nf n (rs # (IR i) <- v).\n Proof.\n   unfold n_instr_nf. intros.\n   unfold undef_regs.\n   apply regset_equal.\n   intros reg.\n   repeat simpl_Pregmap.\n   repeat (rewrite Pregmap.gsspec).\n   simpl_destruct_reg; trivial.\n Qed.\n\n Lemma n_instr_RA_set:\n   forall rs n v,\n     (n_instr n rs) # RA <- v = n_instr n (rs # RA <- v).\n Proof.\n   unfold n_instr. intros.\n   apply regset_equal.\n   intros reg.\n   repeat simpl_Pregmap.\n   repeat (rewrite Pregmap.gsspec).\n   simpl_destruct_reg; trivial.\n Qed.\n\n Lemma n_instr_nf_RA_set:\n   forall rs n v,\n     (n_instr_nf n rs) # RA <- v = n_instr_nf n (rs # RA <- v).\n Proof.\n   unfold n_instr_nf. intros.\n   unfold undef_regs.\n   apply regset_equal.\n   intros reg.\n   repeat simpl_Pregmap.\n   repeat (rewrite Pregmap.gsspec).\n   simpl_destruct_reg; trivial.\n Qed.\n\n Lemma n_instr_PC_set:\n   forall rs n v,\n     (n_instr n rs) # PC <- v = rs # PC <- v.\n Proof.\n   unfold n_instr. intros.\n   apply regset_equal.\n   intros reg.\n   repeat simpl_Pregmap.\n   repeat (rewrite Pregmap.gsspec).\n   simpl_destruct_reg; trivial.\n Qed.\n\n Lemma n_instr_nf_PC_set:\n   forall rs n b ofs,\n     (n_instr_nf n rs) # PC <- (Vptr b ofs) = (n_instr_nf Int.zero rs # PC <- (Vptr b ofs)).\n Proof.\n   unfold n_instr_nf. intros.\n   unfold undef_regs.\n   apply regset_equal.\n   intros reg.\n   repeat simpl_Pregmap.\n   repeat (rewrite Pregmap.gsspec).\n   simpl_destruct_reg; trivial.\n   rewrite Int.add_zero.\n   reflexivity.\n Qed.\n\n Lemma n_instr_ireg:\n   forall rs n i,\n     (n_instr n rs) (IR i) = rs # (IR i).\n Proof.\n   unfold n_instr. intros.\n   repeat simpl_Pregmap. trivial.\n Qed.\n\n Lemma n_instr_nf_ireg:\n   forall rs n i,\n     (n_instr_nf n rs) (IR i) = rs # (IR i).\n Proof.\n   unfold n_instr_nf. intros.\n   unfold undef_regs.\n   repeat simpl_Pregmap.\n   trivial.\n Qed.\n\n Lemma n_instr_RA:\n   forall rs n,\n     (n_instr n rs) RA = rs # RA.\n Proof.\n   unfold n_instr. intros.\n   repeat simpl_Pregmap. trivial.\n Qed.\n\n Lemma n_instr_nf_RA:\n   forall rs n,\n     (n_instr_nf n rs) RA = rs # RA.\n Proof.\n   unfold n_instr_nf. intros.\n   unfold undef_regs.\n   repeat simpl_Pregmap.\n   trivial.\n Qed.\n\n Lemma n_instr_PC:\n   forall rs n b ofs,\n     rs PC = Vptr b ofs ->\n     (n_instr n rs) PC = Vptr b (Int.add ofs n).\n Proof.\n   unfold n_instr. intros.\n   rewrite H.\n   repeat simpl_Pregmap. trivial.\n Qed.\n\n Lemma n_instr_nf_PC:\n   forall rs n b ofs,\n     rs PC = Vptr b ofs ->\n     (n_instr_nf n rs) PC = Vptr b (Int.add ofs n).\n Proof.\n   unfold n_instr_nf. intros.\n   unfold undef_regs.\n   repeat simpl_Pregmap.\n   rewrite H. trivial.\n Qed.\n\n Lemma n_instr_freg_set:\n   forall rs n i v,\n     (n_instr n rs) # (FR i) <- v = n_instr n (rs # (FR i) <- v).\n Proof.\n   unfold n_instr. intros.\n   apply regset_equal.\n   intros reg.\n   repeat simpl_Pregmap.\n   repeat (rewrite Pregmap.gsspec).\n   simpl_destruct_reg; trivial.\n Qed.\n\n Lemma n_instr_nf_freg_set:\n   forall rs n i v,\n     (n_instr_nf n rs) # (FR i) <- v = n_instr_nf n (rs # (FR i) <- v).\n Proof.\n   unfold n_instr_nf. intros.\n   unfold undef_regs.\n   apply regset_equal.\n   intros reg.\n   repeat simpl_Pregmap.\n   repeat (rewrite Pregmap.gsspec).\n   simpl_destruct_reg; trivial.\n Qed.\n\n Lemma n_instr_ST0_set:\n   forall rs n v,\n     (n_instr n rs) # ST0 <- v = n_instr n (rs # ST0 <- v).\n Proof.\n   unfold n_instr. intros.\n   apply regset_equal.\n   intros reg.\n   repeat simpl_Pregmap.\n   repeat (rewrite Pregmap.gsspec).\n   simpl_destruct_reg; trivial.\n Qed.\n\n Lemma n_instr_nf_ST0_set:\n   forall rs n v,\n     (n_instr_nf n rs) # ST0 <- v = n_instr_nf n (rs # ST0 <- v).\n Proof.\n   unfold n_instr_nf. intros.\n   unfold undef_regs.\n   apply regset_equal.\n   intros reg.\n   repeat simpl_Pregmap.\n   repeat (rewrite Pregmap.gsspec).\n   simpl_destruct_reg; trivial.\n Qed.\n\n Lemma n_instr_freg:\n   forall rs n i,\n     (n_instr n rs) (FR i) = rs # (FR i).\n Proof.\n   unfold n_instr. intros.\n   repeat simpl_Pregmap. trivial.\n Qed.\n\n Lemma n_instr_nf_freg:\n   forall rs n i,\n     (n_instr_nf n rs) (FR i) = rs # (FR i).\n Proof.\n   unfold n_instr_nf. intros.\n   unfold undef_regs.\n   repeat simpl_Pregmap.\n   trivial.\n Qed.\n\n Lemma n_instr_ST0:\n   forall rs n,\n     (n_instr n rs) ST0 = rs # ST0.\n Proof.\n   unfold n_instr. intros.\n   repeat simpl_Pregmap. trivial.\n Qed.\n\n Lemma n_instr_nf_ST0:\n   forall rs n,\n     (n_instr_nf n rs) ST0 = rs # ST0.\n Proof.\n   unfold n_instr_nf. intros.\n   unfold undef_regs.\n   repeat simpl_Pregmap.\n   trivial.\n Qed.\n\n Ltac regset_simpl_tac :=\n   match goal with\n     | |- context[(n_instr_nf _ _) # _ <- _] =>\n       match goal with\n         | |- context[(n_instr_nf _ _) # (_:ireg) <- _] => rewrite n_instr_nf_ireg_set\n         | |- context[(n_instr_nf _ _) # RA <- _] => rewrite n_instr_nf_RA_set\n         | |- context[(n_instr_nf _ _) # PC <- (Vptr _ _)] => rewrite n_instr_nf_PC_set\n         | |- context[(n_instr_nf _ _) # (_:freg) <- _] => rewrite n_instr_nf_freg_set\n         | |- context[(n_instr_nf _ _) # ST0 <- _] => rewrite n_instr_nf_ST0_set\n       end\n     | |- context[(n_instr _ _) # _ <- _] => \n       match goal with\n         | |- context[(n_instr _ _) # (_:ireg) <- _] => rewrite n_instr_ireg_set\n         | |- context[(n_instr _ _) # RA <- _] => rewrite n_instr_RA_set\n         | |- context[(n_instr _ _) # PC <- _] => rewrite n_instr_PC_set\n         | |- context[(n_instr _ _) # (_:freg) <- _] => rewrite n_instr_freg_set\n         | |- context[(n_instr _ _) # ST0 <- _] => rewrite n_instr_ST0_set\n       end\n     | |- context[(n_instr_nf _ _) _] => \n       match goal with\n         | |- context[(n_instr_nf _ _) (_:ireg)] => rewrite n_instr_nf_ireg\n         | |- context[(n_instr_nf _ _) RA] => rewrite n_instr_nf_RA\n         | |- context[(n_instr_nf _ _) PC] => erewrite n_instr_nf_PC\n         | |- context[(n_instr_nf _ _) (_:freg)] => rewrite n_instr_nf_freg\n         | |- context[(n_instr_nf _ _) ST0] => rewrite n_instr_nf_ST0\n       end\n     | |- context[(n_instr _ _) _] => \n       match goal with\n         | |- context[(n_instr _ _) (_:ireg)] => rewrite n_instr_ireg\n         | |- context[(n_instr _ _) RA] => rewrite n_instr_RA\n         | |- context[(n_instr _ _) PC] => erewrite n_instr_PC\n         | |- context[(n_instr _ _) (_:freg)] => rewrite n_instr_freg\n         | |- context[(n_instr _ _) ST0] => rewrite n_instr_ST0\n       end\n     | |- context[n_instr_nf _ (n_instr_nf _ _)] => rewrite n_instr_nf_n_instr_nf\n     | |- context[n_instr_nf _ (n_instr _ _)] => rewrite n_instr_nf_n_instr\n     | |- context[n_instr _ (n_instr_nf _ _)] => rewrite n_instr_n_instr_nf\n     | |- context[n_instr _ (n_instr _ _)] => rewrite n_instr_n_instr\n\n     | |- context[?m # ?i <- ?x ?i] => rewrite Pregmap.gss\n     | |- context[?m # ?i <- ?x ?j] => rewrite Pregmap.gso; [|discriminate]\n     | |- context[nextinstr] => rewrite nextinstr_n_instr\n     | |- context[nextinstr_nf] => rewrite nextinstr_nf_n_instr_nf\n   end; simpl.\n\n(* Ltac regset_simpl_tac :=\n   match goal with\n     | |- context[?m # ?i <- ?x ?i] => rewrite Pregmap.gss\n     | |- context[?m # ?i <- ?x ?j] => rewrite Pregmap.gso; [|discriminate]\n     | |- context[nextinstr] => rewrite nextinstr_n_instr\n     | |- context[nextinstr_nf] => rewrite nextinstr_nf_n_instr_nf\n     | |- context[n_instr_nf _ (n_instr _ _)] => rewrite n_instr_nf_n_instr\n     | |- context[n_instr _ (n_instr_nf _ _)] => rewrite n_instr_n_instr_nf\n     | |- context[n_instr _ (n_instr _ _)] => rewrite n_instr_n_instr\n     | |- context[n_instr_nf _ (n_instr_nf _ _)] => rewrite n_instr_nf_n_instr_nf\n     | |- context[(n_instr_nf _ _) # (_:ireg) <- _] => rewrite n_instr_nf_ireg_set\n     | |- context[(n_instr _ _) # (_:ireg) <- _] => rewrite n_instr_ireg_set\n     | |- context[(n_instr_nf _ _) # RA <- _] => rewrite n_instr_nf_RA_set\n     | |- context[(n_instr _ _) # RA <- _] => rewrite n_instr_RA_set\n     | |- context[(n_instr_nf _ _) # PC <- (Vptr _ _)] => rewrite n_instr_nf_PC_set\n     | |- context[(n_instr _ _) # PC <- _] => rewrite n_instr_PC_set\n     | |- context[(n_instr_nf _ _) (_:ireg)] => rewrite n_instr_nf_ireg\n     | |- context[(n_instr _ _) (_:ireg)] => rewrite n_instr_ireg\n     | |- context[(n_instr_nf _ _) RA] => rewrite n_instr_nf_RA\n     | |- context[(n_instr _ _) RA] => rewrite n_instr_RA\n     | |- context[(n_instr_nf _ _) PC] => erewrite n_instr_nf_PC\n     | |- context[(n_instr _ _) PC] => erewrite n_instr_PC\n   end; simpl.*)\n\n Ltac one_step_forward n:=\n   match goal with\n     | |- star _ _ _ _ _ =>\n       eapply star_left; try reflexivity\n     | |- plus _ _ _ _ _ =>\n       econstructor\n   end;\n   match goal with\n     | |- step _ _ _ _ =>\n       econstructor; try eassumption;\n       match goal with\n         | H: _ PC = Vptr ?b _ |- _ = Vptr ?b _ => \n           repeat regset_simpl_tac; try reflexivity; eassumption\n         | |- find_instr ?num _ = _ =>\n           replace num with n;\n             [pc_add_simpl; simpl| try reflexivity]\n         | _ => simpl\n       end\n     | _ => idtac\n   end.*)\n\n(*Ltac lens_norm_ortho_trivial :=\n  repeat progress\n    match goal with\n      | |- context [set ?β ?v (set ?α ?u ?s)] =>\n        rewrite (lens_ortho_setr_setl u v s)\n      | |- context [?α (set ?β ?v ?s)] =>\n        rewrite (lens_ortho_getl_setr α β s v)\n      | |- context [?β (set ?α ?u ?s)] =>\n        rewrite (lens_ortho_getr_setl α β s u)\n    end.\n\nLtac lens_norm_trivial :=\n  repeat progress (simpl; lens_norm_ortho_trivial;\n                   autorewrite with lens).\n\nLtac lens_simpl_trivial :=\n  repeat progress (lens_norm_trivial; autorewrite with lens_simpl_trivial).\n\nLtac lens_unfold_trivial :=\n  repeat progress (lens_simpl_trivial; unfold set).\n\nLtac lift_trivial :=\n  unfold lift; lens_unfold_trivial; simpl.*)\n\n(* Ltac regset_simpl_tac_n n:=\n   repeat regset_simpl_tac;\n   match goal with\n     | |- context [n_instr ?a _] =>\n       replace a with (Int.repr n); [| try reflexivity]\n     | |- context [n_instr_nf ?a _] =>\n       replace a with (Int.repr n); [| try reflexivity]\n   end.*)\n\n Ltac store_split:=\n   repeat match goal with\n            | H: _ /\\ _ = _ |- _ => destruct H as [H ?]; subst\n          end.\n\n Ltac one_step_forward':=\n   match goal with\n     | |- star _ _ _ _ _ =>\n       eapply star_left; try reflexivity\n     | |- plus _ _ _ _ _ =>\n       econstructor\n   end;\n   match goal with\n     | |- step _ _ _ _ =>\n       econstructor; try eassumption;\n       try reflexivity\n     | _ => idtac\n   end; simpl; [auto; discriminate|..].\n\n Ltac one_step_forward n:=\n   match goal with\n     | |- star _ _ _ _ _ =>\n       eapply star_left; try reflexivity\n     | |- plus _ _ _ _ _ =>\n       econstructor\n   end;\n   match goal with\n     | |- step _ _ _ _ =>\n       econstructor; try eassumption;\n       match goal with\n         | H: _ PC = Vptr ?b _ |- _ = Vptr ?b _ => \n           try reflexivity\n         | |- find_instr ?num _ = _ =>\n           replace num with n;\n             [pc_add_simpl; simpl| try reflexivity]\n         | _ => simpl\n       end\n     | _ => idtac\n   end; [auto; discriminate|..].\n\n Lemma val_add_vptr:\n   forall n b ofs,\n     Int.repr n = Int.add ofs Int.one ->\n     Val.add (Vptr b ofs) Vone = Vptr b (Int.repr n).\n Proof.\n   simpl. intros.\n   congruence.\n Qed.\n\n Ltac Lregset_simpl_tac:=\n   repeat match goal with\n            | |- context [undef_regs (map _ destroyed_at_call) (Lregset_fold _)] =>\n              rewrite Lregset_fold_destroyed\n            | |- context[(Lregset_fold _) _] => \n              rewrite Lregset_fold_get; simpl\n            | |- context [nextinstr (Lregset_fold _)] =>\n              rewrite Lregset_fold_nextinstr\n            | |- context [nextinstr_nf (Lregset_fold _)] =>\n              rewrite Lregset_fold_nextinstr_nf\n            | |- context[(Lregset_fold _) # RA <- _ ] =>\n              rewrite Lregset_fold_ra\n            | |- context[(Lregset_fold _) # PC <- _ ] =>\n              rewrite Lregset_fold_pc\n            | |- context[(Lregset_fold _) # ST0 <- _ ] =>\n              rewrite Lregset_fold_st0\n            | |- context[(Lregset_fold _) # (IR ?i) <- _ ] =>\n              match i with\n                | EAX => rewrite Lregset_fold_eax\n                | EDX => rewrite Lregset_fold_edx\n                | ESP => rewrite Lregset_fold_esp\n                | ECX => rewrite Lregset_fold_ecx\n                | EDI => rewrite Lregset_fold_edi\n                | ESI => rewrite Lregset_fold_esi\n                | EBX => rewrite Lregset_fold_ebx\n                | EBP => rewrite Lregset_fold_ebp\n              end\n            | |- context[(Lregset_fold _) # (CR ?i) <- _ ] =>\n              match i with\n                | ZF => rewrite Lregset_fold_zf\n                | CF => rewrite Lregset_fold_cf\n                | PF => rewrite Lregset_fold_pf\n                | SF => rewrite Lregset_fold_sf\n                | OF => rewrite Lregset_fold_of\n              end\n            | |- context[(Lregset_fold _) # (FR ?i) <- _ ] =>\n              match i with\n                | XMM0 => rewrite Lregset_fold_xmm0\n                | XMM1 => rewrite Lregset_fold_xmm1\n                | XMM2 => rewrite Lregset_fold_xmm2\n                | XMM3 => rewrite Lregset_fold_xmm3\n                | XMM4 => rewrite Lregset_fold_xmm4\n                | XMM5 => rewrite Lregset_fold_xmm5\n                | XMM6 => rewrite Lregset_fold_xmm6\n                | XMM7 => rewrite Lregset_fold_xmm7\n              end\n          end.\n\n Ltac Lregset_simpl_tac' n :=\n   Lregset_simpl_tac;\n   match goal with\n     | |- context [Val.add (Vptr ?b ?ofs) Vone] =>\n       rewrite (val_add_vptr n b ofs); [| try reflexivity]\n   end. \n\n Lemma reg_false:\n   forall reg: preg,\n     reg <> PC ->\n     reg <> EBP ->\n     reg <> EBX ->\n     reg <> ESI ->\n     reg <> EDI ->\n     reg <> ESP ->\n     reg <> RA ->\n     reg <> EAX ->\n     reg <> ECX ->\n     reg <> EDX ->\n     reg <> OF ->\n     reg <> SF ->\n     reg <> PF ->\n     reg <> CF ->\n     reg <> ZF ->\n     reg <> XMM7 ->\n     reg <> XMM6 ->\n     reg <> XMM5 ->\n     reg <> XMM4 ->\n     reg <> XMM3 ->\n     reg <> XMM2 ->\n     reg <> XMM1 ->\n     reg <> XMM0 ->\n     reg <> ST0 ->\n     False.\n Proof.\n   intros.\n   destruct reg; try congruence.\n   destruct i; try congruence.\n   destruct f; try congruence.\n   destruct c; try congruence.\n Qed.\n\n Ltac link_nextblock_asm :=\n   repeat match goal with\n            | Hstore: Mem.store _ _ _ _ _ = Some ?fm |- context[Mem.nextblock ?fm] =>\n              rewrite (Mem.nextblock_store _ _ _ _ _ _ Hstore)\n          end; try reflexivity.\n\n Ltac link_inject_neutral_asm :=\n   repeat match goal with\n            | Hstore: Mem.store _ _ _ _ _ = Some ?fm |- Mem.inject_neutral _ ?fm =>\n              eapply Mem.store_inject_neutral; eauto 1\n          end.\n\n\n Lemma inv_reg_le:\n   forall (rs: regset) a b,        \n     (forall r,\n        val_inject (Mem.flat_inj a) \n                   (rs r) (rs r)) ->\n     (a <= b)%positive ->\n     (forall r,\n        val_inject (Mem.flat_inj b) \n                   (rs r) (rs r)).\n Proof.\n   intros. eapply val_inject_incr; [|eauto].\n   eapply flat_inj_inject_incr; assumption.\n Qed.\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/AsmImplTactic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.42632159254749025, "lm_q1q2_score": 0.2821920088895422}}
{"text": "From iris.algebra Require Import monoid.\nFrom iris.bi Require Export interface.\nFrom iris.prelude Require Import options.\n\nDefinition bi_iff {PROP : bi} (P Q : PROP) : PROP := ((P → Q) ∧ (Q → P))%I.\nGlobal Arguments bi_iff {_} _%I _%I : simpl never.\nGlobal Instance: Params (@bi_iff) 1 := {}.\nInfix \"↔\" := bi_iff : bi_scope.\n\nDefinition bi_wand_iff {PROP : bi} (P Q : PROP) : PROP :=\n  ((P -∗ Q) ∧ (Q -∗ P))%I.\nGlobal Arguments bi_wand_iff {_} _%I _%I : simpl never.\nGlobal Instance: Params (@bi_wand_iff) 1 := {}.\nInfix \"∗-∗\" := bi_wand_iff : bi_scope.\n\nClass Persistent {PROP : bi} (P : PROP) := persistent : P ⊢ <pers> P.\nGlobal Arguments Persistent {_} _%I : simpl never.\nGlobal Arguments persistent {_} _%I {_}.\nGlobal Hint Mode Persistent + ! : typeclass_instances.\nGlobal Instance: Params (@Persistent) 1 := {}.\n\nDefinition bi_affinely {PROP : bi} (P : PROP) : PROP := (emp ∧ P)%I.\nGlobal Arguments bi_affinely {_} _%I : simpl never.\nGlobal Instance: Params (@bi_affinely) 1 := {}.\nTypeclasses Opaque bi_affinely.\nNotation \"'<affine>' P\" := (bi_affinely P) : bi_scope.\n\nClass Affine {PROP : bi} (Q : PROP) := affine : Q ⊢ emp.\nGlobal Arguments Affine {_} _%I : simpl never.\nGlobal Arguments affine {_} _%I {_}.\nGlobal Hint Mode Affine + ! : typeclass_instances.\n\nClass BiAffine (PROP : bi) := absorbing_bi (Q : PROP) : Affine Q.\nGlobal Hint Mode BiAffine ! : typeclass_instances.\nExisting Instance absorbing_bi | 0.\n\nClass BiPositive (PROP : bi) :=\n  bi_positive (P Q : PROP) : <affine> (P ∗ Q) ⊢ <affine> P ∗ Q.\nGlobal Hint Mode BiPositive ! : typeclass_instances.\n\nDefinition bi_absorbingly {PROP : bi} (P : PROP) : PROP := (True ∗ P)%I.\nGlobal Arguments bi_absorbingly {_} _%I : simpl never.\nGlobal Instance: Params (@bi_absorbingly) 1 := {}.\nTypeclasses Opaque bi_absorbingly.\nNotation \"'<absorb>' P\" := (bi_absorbingly P) : bi_scope.\n\nClass Absorbing {PROP : bi} (P : PROP) := absorbing : <absorb> P ⊢ P.\nGlobal Arguments Absorbing {_} _%I : simpl never.\nGlobal Arguments absorbing {_} _%I.\nGlobal Hint Mode Absorbing + ! : typeclass_instances.\n\nDefinition bi_persistently_if {PROP : bi} (p : bool) (P : PROP) : PROP :=\n  (if p then <pers> P else P)%I.\nGlobal Arguments bi_persistently_if {_} !_ _%I /.\nGlobal Instance: Params (@bi_persistently_if) 2 := {}.\nTypeclasses Opaque bi_persistently_if.\nNotation \"'<pers>?' p P\" := (bi_persistently_if p P) : bi_scope.\n\nDefinition bi_affinely_if {PROP : bi} (p : bool) (P : PROP) : PROP :=\n  (if p then <affine> P else P)%I.\nGlobal Arguments bi_affinely_if {_} !_ _%I /.\nGlobal Instance: Params (@bi_affinely_if) 2 := {}.\nTypeclasses Opaque bi_affinely_if.\nNotation \"'<affine>?' p P\" := (bi_affinely_if p P) : bi_scope.\n\nDefinition bi_absorbingly_if {PROP : bi} (p : bool) (P : PROP) : PROP :=\n  (if p then <absorb> P else P)%I.\nGlobal Arguments bi_absorbingly_if {_} !_ _%I /.\nGlobal Instance: Params (@bi_absorbingly_if) 2 := {}.\nTypeclasses Opaque bi_absorbingly_if.\nNotation \"'<absorb>?' p P\" := (bi_absorbingly_if p P) : bi_scope.\n\nDefinition bi_intuitionistically {PROP : bi} (P : PROP) : PROP :=\n  (<affine> <pers> P)%I.\nGlobal Arguments bi_intuitionistically {_} _%I : simpl never.\nGlobal Instance: Params (@bi_intuitionistically) 1 := {}.\nTypeclasses Opaque bi_intuitionistically.\nNotation \"□ P\" := (bi_intuitionistically P) : bi_scope.\n\nDefinition bi_intuitionistically_if {PROP : bi} (p : bool) (P : PROP) : PROP :=\n  (if p then □ P else P)%I.\nGlobal Arguments bi_intuitionistically_if {_} !_ _%I /.\nGlobal Instance: Params (@bi_intuitionistically_if) 2 := {}.\nTypeclasses Opaque bi_intuitionistically_if.\nNotation \"'□?' p P\" := (bi_intuitionistically_if p P) : bi_scope.\n\nFixpoint bi_laterN {PROP : bi} (n : nat) (P : PROP) : PROP :=\n  match n with\n  | O => P\n  | S n' => ▷ ▷^n' P\n  end%I\nwhere \"▷^ n P\" := (bi_laterN n P) : bi_scope.\nGlobal Arguments bi_laterN {_} !_%nat_scope _%I.\nGlobal Instance: Params (@bi_laterN) 2 := {}.\nNotation \"▷? p P\" := (bi_laterN (Nat.b2n p) P) : bi_scope.\n\nDefinition bi_except_0 {PROP : bi} (P : PROP) : PROP := (▷ False ∨ P)%I.\nGlobal Arguments bi_except_0 {_} _%I : simpl never.\nNotation \"◇ P\" := (bi_except_0 P) : bi_scope.\nGlobal Instance: Params (@bi_except_0) 1 := {}.\nTypeclasses Opaque bi_except_0.\n\nClass Timeless {PROP : bi} (P : PROP) := timeless : ▷ P ⊢ ◇ P.\nGlobal Arguments Timeless {_} _%I : simpl never.\nGlobal Arguments timeless {_} _%I {_}.\nGlobal Hint Mode Timeless + ! : typeclass_instances.\nGlobal Instance: Params (@Timeless) 1 := {}.\n\n(** An optional precondition [mP] to [Q].\n    TODO: We may actually consider generalizing this to a list of preconditions,\n    and e.g. also using it for texan triples. *)\nDefinition bi_wandM {PROP : bi} (mP : option PROP) (Q : PROP) : PROP :=\n  match mP with\n  | None => Q\n  | Some P => (P -∗ Q)%I\n  end.\nGlobal Arguments bi_wandM {_} !_%I _%I /.\nNotation \"mP -∗? Q\" := (bi_wandM mP Q)\n  (at level 99, Q at level 200, right associativity) : bi_scope.\n\n(** The class [BiLöb] is required for the [iLöb] tactic. However, for most BI\nlogics [BiLaterContractive] should be used, which gives an instance of [BiLöb]\nautomatically (see [derived_laws_later]). A direct instance of [BiLöb] is useful\nwhen considering a BI logic with a discrete OFE, instead of an OFE that takes\nstep-indexing of the logic in account.\n\nThe internal/\"strong\" version of Löb [(▷ P → P) ⊢ P] is derivable from [BiLöb].\nIt is provided by the lemma [löb] in [derived_laws_later]. *)\nClass BiLöb (PROP : bi) :=\n  löb_weak (P : PROP) : (▷ P ⊢ P) → (True ⊢ P).\nGlobal Hint Mode BiLöb ! : typeclass_instances.\nGlobal Arguments löb_weak {_ _} _ _.\n\nNotation BiLaterContractive PROP :=\n  (Contractive (bi_later (PROP:=PROP))) (only parsing).\n\n(** The class [BiPureForall] states that universal quantification commutes with\nthe embedding of pure propositions. The reverse direction of the entailment\ndescribed by this type class is derivable, so it is not included.\n\nAn instance of [BiPureForall] itself is derivable if we assume excluded middle\nin Coq, see the lemma [bi_pure_forall_em] in [derived_laws]. *)\nClass BiPureForall (PROP : bi) :=\n  pure_forall_2 : ∀ {A} (φ : A → Prop), (∀ a, ⌜ φ a ⌝) ⊢@{PROP} ⌜ ∀ a, φ a ⌝.\n", "meta": {"author": "jtassarotti", "repo": "iris-inv-hierarchy", "sha": "b25fe890d72ecb5bafa9db422ece3939d99882ab", "save_path": "github-repos/coq/jtassarotti-iris-inv-hierarchy", "path": "github-repos/coq/jtassarotti-iris-inv-hierarchy/iris-inv-hierarchy-b25fe890d72ecb5bafa9db422ece3939d99882ab/iris/bi/derived_connectives.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.28218339836013884}}
{"text": "Require 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 Label Language.\n\nInductive funTy : Type :=\n  | ArrowTy : ty -> ty -> funTy. \n\nDefinition typing_context := id -> (option ty).\nDefinition empty_context : typing_context := fun _ => None.\n\nDefinition update_typing (gamma : typing_context) (x:id) (T : ty) : typing_context :=\n      fun x' => if beq_id x x' then (Some T) else gamma x. \n\n\nDefinition empty_heap : heap := nil.\n\n\nInductive tm_has_type : Class_table -> typing_context -> heap -> tm -> ty -> Prop :=\n(*variable *)\n  | T_Var : forall Gamma x T CT h , \n      Gamma x = Some T ->\n      tm_has_type CT Gamma h (Tvar x) T\n  | T_EqCmp : forall Gamma e1 e2 clsT h CT,\n      tm_has_type CT Gamma h e1 (classTy clsT) ->\n      tm_has_type CT Gamma h e2 (classTy clsT) ->\n      (exists cls_def field_defs method_defs, CT clsT = Some cls_def /\\\n              cls_def = class_def clsT field_defs method_defs) ->\n      tm_has_type CT Gamma h (EqCmp e1 e2) boolTy\n(* null *)\n  | T_null : forall Gamma h cls CT, \n      tm_has_type CT Gamma h null (classTy cls)\n(* Field read *)\n  | T_FieldAccess : forall Gamma e f cls_def CT clsT cls' h fields_def,\n      tm_has_type CT Gamma h e (classTy clsT) ->\n      Some cls_def = CT(clsT) ->\n      fields_def = (find_fields cls_def) ->\n      type_of_field fields_def f = Some cls' ->\n      tm_has_type CT Gamma h (FieldAccess e f) (classTy cls')\n(* method call *)\n  | T_MethodCall : forall Gamma  e meth argu CT h T returnT cls_def body arg_id arguT,\n      tm_has_type CT Gamma h e (classTy T) ->\n      tm_has_type CT Gamma h argu arguT ->\n      Some cls_def = CT(T) ->\n      find_method cls_def meth = Some (m_def returnT meth arguT arg_id  body)  ->\n      surface_syntax body = true ->\n      tm_has_type CT Gamma h (MethodCall e meth argu) returnT\n(* new exp *)\n  | T_NewExp : forall h Gamma cls_name CT, \n      (exists cls_def field_defs method_defs, CT cls_name = Some cls_def /\\\n              cls_def = class_def cls_name field_defs method_defs) ->\n      tm_has_type CT Gamma h (NewExp cls_name) (classTy cls_name)\n\n(* booleans  *)                         \n  | T_true : forall h Gamma CT,\n      tm_has_type CT Gamma h B_true boolTy\n  | T_false : forall h Gamma CT,\n      tm_has_type CT Gamma h B_false boolTy                 \n(* label *)\n  | T_label : forall h Gamma lb CT,\n      tm_has_type CT Gamma h (l lb) LabelTy\n(* label data *)\n  | T_labelData : forall h Gamma  CT e1 e2 T,\n      tm_has_type CT Gamma h e2 LabelTy ->\n      tm_has_type CT Gamma h e1 T ->\n      tm_has_type CT Gamma h (labelData e1 e2) (LabelelTy T)\n(* unlabel *)\n  | T_unlabel : forall h Gamma CT e T,\n      tm_has_type CT Gamma h e (LabelelTy T) ->\n      tm_has_type CT Gamma h (unlabel e) T\n(* labelOf *)\n  | T_labelOf : forall h Gamma CT e T,\n      tm_has_type CT Gamma h e (LabelelTy T) ->\n      tm_has_type CT Gamma h (labelOf e) LabelTy\n\n\n(* objectLabelOf *)\n  | T_objectLabelOf : forall h Gamma CT e clsT,\n      tm_has_type CT Gamma h e  (classTy clsT)  ->\n      (exists cls_def field_defs method_defs, CT clsT = Some cls_def /\\\n              cls_def = class_def clsT field_defs method_defs) ->\n      tm_has_type CT Gamma h (objectLabelOf e) LabelTy\n                  \n(* raise label *)\n  | T_raiseLabel : forall h Gamma CT e1 e2 clsT,\n      tm_has_type CT Gamma h e2 LabelTy ->\n      tm_has_type CT Gamma h e1 (classTy clsT) ->\n      (exists cls_def field_defs method_defs, CT clsT = Some cls_def /\\\n              cls_def = class_def clsT field_defs method_defs) ->\n      tm_has_type CT Gamma h (raiseLabel e1 e2) (classTy clsT)\n(* toLabeled *)\n  | T_toLabeled : forall h Gamma v CT e T,\n      tm_has_type CT Gamma h v LabelTy ->\n      tm_has_type CT Gamma h e T ->\n      tm_has_type CT Gamma h (toLabeled e v) (LabelelTy T)\n(* getCurrentLevel *)\n  | T_getCurrentLevel : forall h Gamma CT,\n      tm_has_type CT Gamma h (getCurrentLevel) LabelTy                  \n(* assignment *)\n  | T_assignment : forall h Gamma CT e T x, \n      Gamma x = Some T ->\n      tm_has_type CT Gamma h e T ->\n      tm_has_type CT Gamma h (Assignment x e) T\n(* Field Write *)\n  | T_FieldWrite : forall h Gamma x f cls_def CT clsT cls' e,\n      tm_has_type CT Gamma h x (classTy clsT) ->\n      tm_has_type CT Gamma h e (classTy cls') ->\n      Some cls_def = CT(clsT) ->\n      type_of_field (find_fields cls_def) f = Some cls' ->\n      tm_has_type CT Gamma h (FieldWrite x f e)  (classTy cls')\n(* if *)\n  | T_if : forall Gamma h CT guard s1 s2 T' ,\n      tm_has_type CT Gamma h guard boolTy ->\n      tm_has_type CT Gamma h s1 T' ->\n      tm_has_type CT Gamma h s2 T' ->\n      tm_has_type CT Gamma h (If guard s1 s2) T'\n(* sequence *)\n  | T_sequence : forall h Gamma CT e1 e2 T T',\n      tm_has_type CT Gamma h e1 T ->\n      tm_has_type CT Gamma h e2 T' ->\n      tm_has_type CT Gamma h (Sequence e1 e2) T'\n\n(* ObjId *)\n  | T_ObjId : forall h Gamma CT o cls_name cls_def,\n      Some cls_def = CT(cls_name) ->\n      (exists field_defs method_defs, cls_def = (class_def cls_name field_defs method_defs)) ->\n      (exists F lo ll, lookup_heap_obj h o = Some (Heap_OBJ cls_def F lo ll)) ->\n      tm_has_type CT Gamma h (ObjId o) (classTy cls_name)\n(* runtime labeled data *)\n  | T_v_l : forall h Gamma lb CT v T,\n      tm_has_type CT Gamma h (l lb)  LabelTy ->\n      tm_has_type CT Gamma h v  T ->\n      value v ->\n      tm_has_type CT Gamma h (v_l v lb) (LabelelTy T)\n(* runtime labeled data *)\n  | T_v_opa_l : forall h Gamma lb CT v T,\n      tm_has_type CT Gamma h (l lb)  LabelTy ->\n      tm_has_type CT Gamma h v  T ->\n      value  v  ->\n      (forall v0 lb0, v <> v_opa_l v0 lb0 ) ->\n      tm_has_type CT Gamma h (v_opa_l v lb)  T.\n(* hole *)\n(*  | T_hole : forall h Gamma CT T,\n      tm_has_type CT Gamma h hole T.\n *)\nHint Constructors tm_has_type.\n\nInductive tm_hole_has_type : Class_table -> typing_context -> heap -> tm -> funTy -> Prop :=\n                       \n  | T_EqCmp1 : forall e1 e2 Gamma clsT CT h,\n      tm_has_type CT Gamma h e1 (classTy clsT) ->\n      tm_has_type CT Gamma h e2 (classTy clsT) ->\n      (exists cls_def field_defs method_defs, CT clsT = Some cls_def /\\\n              cls_def = class_def clsT field_defs method_defs) ->\n      tm_has_type CT Gamma h (EqCmp e1 e2) boolTy ->\n      tm_hole_has_type CT Gamma h (EqCmp hole e2) (ArrowTy (classTy clsT) boolTy) \n  | T_EqCmp2 : forall e1 e2 Gamma clsT CT h,\n      tm_has_type CT Gamma h e1 (classTy clsT) ->\n      tm_has_type CT Gamma h e2 (classTy clsT) ->\n      (exists cls_def field_defs method_defs, CT clsT = Some cls_def /\\\n              cls_def = class_def clsT field_defs method_defs) ->\n      tm_has_type CT Gamma h (EqCmp e1 e2) boolTy ->\n      tm_hole_has_type CT Gamma h (EqCmp e1 hole) (ArrowTy (classTy clsT) boolTy)\n                       \n  | T_hole_FieldAccess : forall  Gamma f cls_def CT clsT cls' h fields_def,\n      (*\n      tm_has_type CT Gamma h (FieldAccess e f) (classTy cls') ->\n      tm_has_type CT Gamma h e (classTy clsT) ->\n       *)\n      Some cls_def = CT(clsT) ->\n      fields_def = (find_fields cls_def) ->\n      type_of_field fields_def f = Some cls' ->\n      tm_hole_has_type CT Gamma h (FieldAccess hole f) (ArrowTy (classTy clsT) (classTy cls'))\n                  \n  | T_hole_MethodCall1 : forall Gamma  meth argu CT h T returnT cls_def body arg_id arguT,\n      (* tm_has_type CT Gamma h (MethodCall e meth argu) (OpaqueLabeledTy (classTy returnT)) ->\n      tm_has_type CT Gamma h e (classTy T) ->  *)\n      tm_has_type CT Gamma h argu arguT ->\n      Some cls_def = CT(T) ->\n      find_method cls_def meth = Some (m_def returnT meth arguT arg_id  body)  ->\n      surface_syntax body = true ->\n      tm_hole_has_type CT Gamma h (MethodCall hole meth argu) (ArrowTy (classTy T)\n                                                                       returnT)\n                  \n  | T_hole_MethodCall2 : forall Gamma  e meth CT h T returnT cls_def body arg_id arguT,\n      (* tm_has_type CT Gamma h (MethodCall e meth argu) (OpaqueLabeledTy (classTy returnT)) ->\n      tm_has_type CT Gamma h argu (classTy arguT) -> *)\n      tm_has_type CT Gamma h e (classTy T) ->\n      Some cls_def = CT(T) ->\n      find_method cls_def meth = Some (m_def returnT meth arguT arg_id  body)  ->\n      surface_syntax body = true ->\n      tm_hole_has_type CT Gamma h (MethodCall e meth hole) (ArrowTy (arguT)\n                                                                    ( returnT))\n\n\n  | T_hole_labelData1 : forall h Gamma CT T e2 , \n      (* tm_has_type CT Gamma h (labelData e lb) (LabelelTy T) -> *)\n      tm_has_type CT Gamma h e2 LabelTy ->\n      tm_hole_has_type CT Gamma h (labelData hole e2) (ArrowTy T (LabelelTy T))\n\n  | T_hole_labelData2 : forall h Gamma CT T v,\n      value v ->\n      tm_has_type CT Gamma h v T ->\n      tm_hole_has_type CT Gamma h (labelData v hole) (ArrowTy LabelTy (LabelelTy T))\n\n  (*unlabel data*)\n  | T_hole_unlabel : forall h Gamma CT T, \n      (* tm_has_type CT Gamma h (unlabel e) T -> *)\n      tm_hole_has_type CT Gamma h (unlabel hole) (ArrowTy (LabelelTy T) T)\n  (*labelOf data*)\n  | T_hole_labelOf : forall h Gamma CT  T, \n      (* tm_has_type CT Gamma h (labelOf e) LabelTy -> *)\n      tm_hole_has_type CT Gamma h (labelOf hole) (ArrowTy ( (LabelelTy T)) LabelTy)\n\n  (* objectLabelOf *)\n  | T_hole_objectLabelOf : forall h Gamma CT  clsT, \n      (exists cls_def field_defs method_defs, CT clsT = Some cls_def /\\\n              cls_def = class_def clsT field_defs method_defs) ->\n      tm_hole_has_type CT Gamma h (objectLabelOf hole) (ArrowTy (classTy clsT) LabelTy)\n                       \n  | T_hole_raiseLabel1 : forall  Gamma e2  CT clsT h,\n      tm_has_type CT Gamma h e2 LabelTy ->\n      (exists cls_def field_defs method_defs, CT clsT = Some cls_def /\\\n              cls_def = class_def clsT field_defs method_defs) ->\n      tm_hole_has_type CT Gamma h (raiseLabel hole e2) (ArrowTy (classTy clsT) (classTy clsT))\n\n  | T_hole_raiseLabel2 : forall  Gamma e1  CT clsT h,\n      tm_has_type CT Gamma h e1 (classTy clsT) ->\n       (exists cls_def field_defs method_defs, CT clsT = Some cls_def /\\\n              cls_def = class_def clsT field_defs method_defs) ->\n      tm_hole_has_type CT Gamma h (raiseLabel e1 hole) (ArrowTy LabelTy (classTy clsT))\n\n  | T_hole_toLabeled : forall h Gamma CT T e ,\n      tm_has_type CT Gamma h e T ->\n      tm_hole_has_type CT Gamma h (toLabeled e hole) (ArrowTy LabelTy (LabelelTy T))\n                       \n(* assignment *)\n  | T_hole_assignment : forall h Gamma CT  T x , \n      (* tm_has_type CT Gamma h (Assignment x e) voidTy -> *)\n      Gamma x = Some T ->\n      tm_hole_has_type CT Gamma h (Assignment x hole) (ArrowTy T T)\n\n  (* sequence *)\n  | T_hole_sequence : forall h Gamma CT  T T' s2, \n      tm_has_type CT Gamma h s2 T ->\n      tm_hole_has_type CT Gamma h (Sequence hole s2) (ArrowTy T' T)\n\n(* if *)\n  | T_hole_if : forall h Gamma CT s1 s2 T,\n      tm_has_type CT Gamma h s1 T ->\n      tm_has_type CT Gamma h s2 T ->\n      tm_hole_has_type CT Gamma h (If hole s1 s2) (ArrowTy boolTy T)\n \n                  \n(* Field Write *)\n  | T_hole_FieldWrite1 : forall  h Gamma f cls_def CT clsT cls' e,\n      (*tm_has_type CT Gamma h (FieldWrite x f e) voidTy ->\n       tm_has_type CT Gamma h x (classTy clsT) -> *)\n      tm_has_type CT Gamma h e (classTy cls') ->\n      Some cls_def = CT(clsT) ->\n      type_of_field (find_fields cls_def) f = Some cls' ->\n      tm_hole_has_type CT Gamma h (FieldWrite hole f e) (ArrowTy (classTy clsT) (classTy cls'))\n  | T_hole_FieldWrite2 : forall  h Gamma x f cls_def CT clsT cls',\n      tm_has_type CT Gamma h x (classTy clsT) ->\n      Some cls_def = CT(clsT) ->\n      type_of_field (find_fields cls_def) f = Some cls' ->\n      tm_hole_has_type CT Gamma h (FieldWrite x f hole) (ArrowTy (classTy cls') (classTy cls') ).                 \nHint Constructors tm_hole_has_type. \n\nInductive fs_has_type : Class_table -> typing_context -> heap -> list tm -> funTy -> Prop :=\n  | T_fs_nil : forall h Gamma CT T, \n      fs_has_type CT Gamma h nil (ArrowTy T T)\n  | T_fs_hole : forall h Gamma CT T T' top fs T1,  \n      hole_free top  = false ->\n      tm_hole_has_type CT Gamma h top ((ArrowTy T T')) ->\n      fs_has_type CT Gamma h (fs) (ArrowTy T' T1) ->\n      fs_has_type CT Gamma h (top :: fs) (ArrowTy T T1).\n\n  (*\n  | T_fs_one : forall h Gamma CT T top,  \n      hole_free top = true ->\n      tm_has_type CT Gamma h top T ->\n      fs_has_type CT Gamma h (top :: nil) (ArrowTy T T) \n\n  | T_fs_hole : forall h Gamma CT T T' top fs p,  \n      hole_free top = true ->\n      hole_free p  = false ->\n      tm_has_type CT Gamma h top T ->\n      fs_has_type CT Gamma h (p :: fs) (ArrowTy T T') ->\n      fs_has_type CT Gamma h (top :: p :: fs) (ArrowTy T T') \n  | T_fs_no_hole : forall h Gamma CT T T' T0 top fs p,  \n      hole_free p  = true ->\n      hole_free top = true ->\n      tm_has_type CT Gamma h top T ->\n      fs_has_type CT Gamma h (p :: fs) (ArrowTy T0 T') ->\n      fs_has_type CT Gamma h (top :: p :: fs) (ArrowTy T T')\n*) \nHint Constructors fs_has_type.\n\nInductive well_typed_stack_frame : Class_table -> typing_context ->\n                           stack_frame -> heap -> Prop :=\n| well_typed_sf : forall ct gamma sf  h,\n    (forall x T, gamma x = Some T ->\n    exists v, sf x = Some v /\\\n    tm_has_type ct gamma h v T) ->\n    well_typed_stack_frame ct gamma sf h.\nHint Constructors well_typed_stack_frame.\n\nInductive ctn_has_type : Class_table -> typing_context -> heap -> container -> funTy -> Prop :=\n    | T_ctn_type : forall h Gamma CT T lb fs open_t sf T', \n        tm_has_type CT Gamma h open_t T ->\n        well_typed_stack_frame CT Gamma sf h ->\n        fs_has_type CT Gamma h fs (ArrowTy T T')  ->\n        ctn_has_type CT Gamma h (Container open_t fs lb sf) (ArrowTy T T').\nHint Constructors ctn_has_type. \n\n\nInductive ctn_list_has_type : Class_table -> typing_context -> heap -> list container -> funTy -> Prop := \n  | T_ctn_nil : forall h Gamma CT T , \n      ctn_list_has_type CT Gamma h nil (ArrowTy T T)\n  | T_ctn_list : forall h Gamma CT T0 T1 T' Gamma' ctn ctns', \n      ctn_has_type CT Gamma' h ctn (ArrowTy T0 T1) ->\n      ctn_list_has_type CT Gamma h ctns' (ArrowTy  T1 T') ->\n      ctn_list_has_type CT Gamma h (ctn :: ctns')  (ArrowTy T0 T').                        \nHint Constructors ctn_list_has_type. \n\n  Inductive well_typed_class_table : Class_table -> Prop :=\n  | well_typed_CT : forall CT, \n      (forall clsT cls_def field_defs method_defs,\n      CT clsT = Some cls_def -> \n      cls_def = class_def clsT field_defs method_defs ->\n      (forall gamma h returnT meth arguT arg_id  body ,\n          Some (m_def returnT meth arguT arg_id body) = find_method cls_def meth -> \n          (gamma = update_typing empty_context arg_id arguT) ->\n          (tm_has_type CT gamma h body returnT)\n      )) ->\n      well_typed_class_table CT.\n  Hint Constructors well_typed_class_table. \n\nInductive config_has_type : Class_table -> typing_context -> config -> ty -> Prop :=\n  | T_config_ctns : forall h Gamma CT T T' T0 ctn ctns Gamma', \n      ctn_has_type CT Gamma' h ctn (ArrowTy T0 T) ->\n      ctn_list_has_type CT Gamma h ctns (ArrowTy T T') ->\n      well_typed_class_table CT ->\n      config_has_type CT Gamma (Config CT ctn ctns h) T'.\nHint Constructors config_has_type. \n\nHint Constructors ctn_list_has_type. \nHint Constructors ctn_has_type.\nHint Constructors fs_has_type.\n", "meta": {"author": "HarvardPL", "repo": "CIFC", "sha": "39a86edcfc25f26d9698026fec5beafd4d87c7da", "save_path": "github-repos/coq/HarvardPL-CIFC", "path": "github-repos/coq/HarvardPL-CIFC/CIFC-39a86edcfc25f26d9698026fec5beafd4d87c7da/coinflow/Types.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.28218106998909737}}
{"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 atoms2.\nRequire Export computation_seq.\nRequire Export continuity_defs.\n\n\nInductive differ3 {o} (b : nat) (f g : NTerm)\n: @NTerm o -> @NTerm o -> Type :=\n| differ3_force_int :\n    forall t1 t2 v fa ga,\n      !LIn v (free_vars f)\n      -> !LIn v (free_vars g)\n      -> differ3 b f g t1 t2\n      -> alpha_eq f fa\n      -> alpha_eq g ga\n      -> differ3\n           b f g\n           (force_int_bound_app v b t1 fa (mk_vbot v))\n           (force_int_bound_app v b t2 ga (mk_vbot v))\n| differ3_var :\n    forall v, differ3 b f g (mk_var v) (mk_var v)\n| differ3_sterm :\n    forall s, differ3 b f g (sterm s) (sterm s)\n| differ3_oterm :\n    forall op bs1 bs2,\n      length bs1 = length bs2\n      -> (forall b1 b2, LIn (b1,b2) (combine bs1 bs2) -> differ3_b b f g b1 b2)\n      -> differ3 b f g (oterm op bs1) (oterm op bs2)\nwith differ3_b {o} (b : nat) (f g : NTerm)\n     : @BTerm o -> @BTerm o -> Type :=\n     | differ3_bterm :\n         forall vs t1 t2,\n           disjoint vs (free_vars f)\n           -> disjoint vs (free_vars g)\n           -> differ3 b f g t1 t2\n           -> differ3_b b f g (bterm vs t1) (bterm vs t2).\nHint Constructors differ3 differ3_b.\n\nDefinition differ3_alpha {o} b f g (t1 t2 : @NTerm o) :=\n  {u1 : NTerm\n   & {u2 : NTerm\n      & alpha_eq t1 u1\n      # alpha_eq t2 u2\n      # differ3 b f g u1 u2}}.\n\nDefinition differ3_implies_differ3_alpha {o} :\n  forall b f g (t1 t2 : @NTerm o),\n    differ3 b f g t1 t2 -> differ3_alpha b f g t1 t2.\nProof.\n  introv d.\n  exists t1 t2; auto.\nQed.\nHint Resolve differ3_implies_differ3_alpha : slow.\n\nInductive differ3_subs {o} b f g : @Sub o -> @Sub o -> Type :=\n| dsub3_nil : differ3_subs b f g [] []\n| dsub3_cons :\n    forall v t1 t2 sub1 sub2,\n      differ3 b f g t1 t2\n      -> differ3_subs b f g sub1 sub2\n      -> differ3_subs b f g ((v,t1) :: sub1) ((v,t2) :: sub2).\nHint Constructors differ3_subs.\n\nDefinition differ3_bterms {o} b f g (bs1 bs2 : list (@BTerm o)) :=\n  br_bterms (differ3_b b f g) bs1 bs2.\n\nLemma differ3_subs_sub_find_some {o} :\n  forall b f g (sub1 sub2 : @Sub o) v t,\n    differ3_subs b f g sub1 sub2\n    -> sub_find sub1 v = Some t\n    -> {u : NTerm & sub_find sub2 v = Some u # differ3 b f g t u}.\nProof.\n  induction sub1; destruct sub2; introv d fs; allsimpl; tcsp;\n  inversion d; subst.\n  boolvar; cpx.\n  eexists; eauto.\nQed.\n\nLemma differ3_subs_sub_find_none {o} :\n  forall b f g (sub1 sub2 : @Sub o) v,\n    differ3_subs b f g sub1 sub2\n    -> sub_find sub1 v = None\n    -> sub_find sub2 v = None.\nProof.\n  induction sub1; destruct sub2; introv d fn; allsimpl; tcsp;\n  inversion d; subst.\n  boolvar; cpx.\nQed.\n\nLemma differ3_subs_filter {o} :\n  forall b f g (sub1 sub2 : @Sub o) l,\n    differ3_subs b f g sub1 sub2\n    -> differ3_subs b f g (sub_filter sub1 l) (sub_filter sub2 l).\nProof.\n  induction sub1; destruct sub2; introv d; allsimpl; inversion d; auto.\n  boolvar; sp.\nQed.\n\nLemma differ3_force_int_bound {o} :\n  forall b f g v b' (t1 t2 : @NTerm o) e1 e2,\n    !LIn v (free_vars f)\n    -> !LIn v (free_vars g)\n    -> differ3 b f g t1 t2\n    -> differ3 b f g e1 e2\n    -> differ3 b f g\n               (force_int_bound v b' t1 e1)\n               (force_int_bound v b' t2 e2).\nProof.\n  introv nif nig d1 d2.\n  apply differ3_oterm; simpl; tcsp.\n  introv i; repndors; cpx; tcsp.\n  - constructor; auto.\n  - constructor; allrw disjoint_singleton_l; auto.\n    constructor; simpl; tcsp.\n    introv i; repndors; cpx; tcsp.\n    + constructor; allsimpl; auto.\n      constructor; simpl; tcsp.\n      introv i; repndors; cpx; tcsp.\n      * constructor; auto.\n      * constructor; auto.\n        constructor; simpl; tcsp.\n      * constructor; auto.\n        constructor; simpl; tcsp.\n        introv i; repndors; cpx; tcsp.\n        constructor; auto; constructor.\n      * constructor; auto; constructor.\n    + constructor; auto; constructor; simpl; tcsp.\n    + constructor; auto; constructor.\n    + constructor; auto.\nQed.\nHint Resolve differ3_force_int_bound : slow.\n\nLemma alpha_eq_force_int_bound_app {o} :\n  forall b v1 v2 (t1 t2 f1 f2 e1 e2 : @NTerm o),\n    !LIn v1 (free_vars e1)\n    -> !LIn v2 (free_vars e2)\n    -> !LIn v1 (free_vars f1)\n    -> !LIn v2 (free_vars f2)\n    -> alpha_eq t1 t2\n    -> alpha_eq e1 e2\n    -> alpha_eq f1 f2\n    -> alpha_eq\n         (force_int_bound_app v1 b t1 f1 e1)\n         (force_int_bound_app v2 b t2 f2 e2).\nProof.\n  introv ni1 ni2 ni3 ni4 aeq1 aeq2 aeq3.\n  unfold force_int_bound_app, mk_cbv, mk_less.\n  prove_alpha_eq4.\n  introv i.\n  destruct n;[|destruct n]; try omega.\n\n  - apply alphaeqbt_nilv2; auto.\n    apply alpha_eq_force_int_bound; auto.\n\n  - pose proof (ex_fresh_var\n                  ([v1,v2]\n                     ++ all_vars f1\n                     ++ all_vars f2\n               )) as h; exrepnd.\n    allunfold @all_vars; allsimpl.\n    allsimpl; allrw app_nil_r; allrw remove_nvars_nil_l.\n    allrw in_app_iff; allsimpl; allrw in_app_iff.\n    allrw not_over_or; repnd; GC.\n\n    apply (al_bterm _ _ [v]); simpl; auto.\n\n    + unfold all_vars; simpl.\n      allrw remove_nvars_nil_l; allrw app_nil_r.\n      rw disjoint_singleton_l; simpl.\n      allrw in_app_iff; simpl; allrw in_app_iff; sp.\n\n    + unfold lsubst; simpl; boolvar; allrw app_nil_r;\n      allrw disjoint_singleton_r; tcsp.\n      prove_alpha_eq4.\n      introv j.\n      destruct n;[|destruct n;[|destruct n;[|destruct n]]];\n      try omega; eauto 3 with slow.\n\n      apply alphaeqbt_nilv2; auto.\n      repeat (rw @lsubst_aux_trivial_cl_term); auto; simpl;\n      allrw disjoint_singleton_r; auto.\nQed.\n\nLemma differ3_lsubst_aux {o} :\n  forall b f g (t1 t2 : @NTerm o) sub1 sub2,\n    disjoint (free_vars f) (dom_sub sub1)\n    -> disjoint (free_vars g) (dom_sub sub2)\n    -> differ3 b f g t1 t2\n    -> differ3_subs b f g sub1 sub2\n    -> disjoint (bound_vars t1) (sub_free_vars sub1)\n    -> disjoint (bound_vars t2) (sub_free_vars sub2)\n    -> differ3 b f g (lsubst_aux t1 sub1) (lsubst_aux t2 sub2).\nProof.\n  nterm_ind1s t1 as [v|s|op bs ind] Case;\n  introv clf clg dt ds disj1 disj2; allsimpl.\n\n  - Case \"vterm\".\n    inversion dt; subst; allsimpl.\n    remember (sub_find sub1 v) as f1; symmetry in Heqf1; destruct f1.\n\n    + applydup (differ3_subs_sub_find_some b f g sub1 sub2) in Heqf1; auto.\n      exrepnd; allrw; auto.\n\n    + applydup (differ3_subs_sub_find_none b f g sub1 sub2) in Heqf1; auto.\n      allrw; auto.\n\n  - Case \"sterm\".\n    inversion dt; subst; clear dt; allsimpl; auto.\n\n  - Case \"oterm\".\n    inversion dt as [? ? ? ? ? ni1 ni2 d1 aeq1 aeq2|?|?|? ? ? len imp]; subst; allsimpl.\n\n    + allrw @sub_filter_nil_r.\n      allrw app_nil_r.\n      allrw disjoint_app_l; allrw disjoint_cons_l; allrw disjoint_app_l; repnd; GC.\n      allrw @sub_find_sub_filter; tcsp.\n      fold_terms.\n      apply differ3_force_int; auto.\n\n      * apply (ind (force_int_bound v b t1 (mk_vbot v)) t1 []);\n        simpl; auto; try omega; eauto 3 with slow.\n        eapply ord_le_trans;[|apply ord_le_OS].\n        apply ord_le_oadd_l.\n\n      * rw @lsubst_aux_trivial_cl_term; auto.\n        apply alphaeq_preserves_free_vars in aeq1; rw <- aeq1; auto.\n        rw <- @dom_sub_sub_filter.\n        eapply subvars_disjoint_r;[|exact clf].\n        apply subvars_remove_nvars; apply subvars_app_weak_l; auto.\n\n      * rw @lsubst_aux_trivial_cl_term; auto.\n        apply alphaeq_preserves_free_vars in aeq2; rw <- aeq2; auto.\n        rw <- @dom_sub_sub_filter.\n        eapply subvars_disjoint_r;[|exact clg].\n        apply subvars_remove_nvars; apply subvars_app_weak_l; auto.\n\n    + apply differ3_oterm; allrw map_length; auto.\n\n      introv i.\n      rw <- @map_combine in i.\n      rw in_map_iff in i; exrepnd; cpx; allsimpl.\n      applydup imp in i1.\n      destruct a0 as [l1 t1].\n      destruct a as [l2 t2].\n      applydup in_combine in i1; repnd.\n      allsimpl.\n      inversion i0 as [? ? ? df dg d]; subst; clear i0.\n      constructor; auto.\n      apply (ind t1 t1 l2); eauto 3 with slow.\n\n      * rw <- @dom_sub_sub_filter.\n        eapply subvars_disjoint_r;[|exact clf].\n        apply subvars_remove_nvars; apply subvars_app_weak_l; auto.\n\n      * rw <- @dom_sub_sub_filter.\n        eapply subvars_disjoint_r;[|exact clg].\n        apply subvars_remove_nvars; apply subvars_app_weak_l; auto.\n\n      * apply differ3_subs_filter; auto.\n\n      * pose proof (subvars_sub_free_vars_sub_filter sub1 l2) as sv.\n        disj_flat_map.\n        allsimpl; allrw disjoint_app_l; repnd.\n        eapply subvars_disjoint_r; eauto.\n\n      * pose proof (subvars_sub_free_vars_sub_filter sub2 l2) as sv.\n        disj_flat_map.\n        allsimpl; allrw disjoint_app_l; repnd.\n        eapply subvars_disjoint_r; eauto.\nQed.\n\nLemma differ3_refl {o} :\n  forall b f g (t : @NTerm o),\n    disjoint (bound_vars t) (free_vars f)\n    -> disjoint (bound_vars t) (free_vars g)\n    -> differ3 b f g t t.\nProof.\n  nterm_ind t as [v|s ind|op bs ind] Case; introv df dg; allsimpl; auto.\n\n  Case \"oterm\".\n  allrw in_app_iff; allrw not_over_or; repnd.\n  apply differ3_oterm; auto.\n  introv i.\n  rw in_combine_same in i; repnd; subst.\n  destruct b2 as [l t].\n  disj_flat_map; allsimpl; allrw disjoint_app_l; repnd.\n  constructor; auto.\n  eapply ind; eauto.\nQed.\nHint Resolve differ3_refl : slow.\n\nLemma differ3_subs_refl {o} :\n  forall b f g (sub : @Sub o),\n    disjoint (sub_bound_vars sub) (free_vars f)\n    -> disjoint (sub_bound_vars sub) (free_vars g)\n    -> differ3_subs b f g sub sub.\nProof.\n  induction sub; introv df dg; allsimpl; auto.\n  destruct a; allrw @get_utokens_sub_cons; allrw in_app_iff; allrw not_over_or; repnd.\n  allrw disjoint_app_l; repnd.\n  constructor; eauto 3 with slow.\nQed.\nHint Resolve differ3_subs_refl : slow.\n\nLemma differ3_change_bound_vars {o} :\n  forall b f g vs (t1 t2 : @NTerm o),\n    differ3 b f g t1 t2\n    -> {u1 : NTerm\n        & {u2 : NTerm\n           & differ3 b f g u1 u2\n           # alpha_eq t1 u1\n           # alpha_eq t2 u2\n           # disjoint (bound_vars u1) vs\n           # disjoint (bound_vars u2) vs}}.\nProof.\n  nterm_ind1s t1 as [v|s ind|op bs ind] Case; introv (*clf clg*) d.\n\n  - Case \"vterm\".\n    inversion d; subst.\n    exists (@mk_var o v) (@mk_var o v); simpl; dands; eauto 3 with slow.\n\n  - Case \"sterm\".\n    inversion d; subst; clear d.\n    exists (sterm s) (sterm s); dands; simpl; auto.\n\n  - Case \"oterm\".\n    inversion d as [? ? ? ? ? ni1 ni2 d1 a1 a2|?|?|? ? ? len imp]; subst; simphyps; cpx; ginv; clear d.\n\n    + pose proof (ex_fresh_var (vs ++ free_vars f ++ free_vars g)) as h; exrepnd.\n      allsimpl; allrw in_app_iff; allrw not_over_or; repnd.\n      pose proof (ind (force_int_bound v b t1 (mk_vbot v)) t1 []) as h; clear ind.\n      repeat (autodimp h hyp).\n      { simpl; try omega.\n        eapply ord_le_trans;[|apply ord_le_OS].\n        apply ord_le_oadd_l. }\n      pose proof (h t0 (*clf clg*) d1) as k; clear h.\n      exrepnd.\n\n      fold_terms.\n\n      pose proof (change_bvars_alpha_spec fa vs) as p1.\n      remember (change_bvars_alpha vs fa) as fa1; clear Heqfa1; simpl in p1.\n      pose proof (change_bvars_alpha_spec ga vs) as p2.\n      remember (change_bvars_alpha vs ga) as ga1; clear Heqga1; simpl in p2.\n      repnd.\n\n      exists\n        (force_int_bound_app v0 b u1 fa1 (mk_vbot v0))\n        (force_int_bound_app v0 b u2 ga1 (mk_vbot v0)).\n      dands; eauto 4 with slow.\n\n      * apply alpha_eq_force_int_bound_app; simpl; tcsp;\n        allrw remove_nvars_nil_l; allrw app_nil_r; allrw remove_nvars_eq;\n        tcsp; eauto 3 with slow.\n        { apply alphaeq_preserves_free_vars in a1; rw <- a1; auto. }\n        { apply alphaeq_preserves_free_vars in p1; rw <- p1; auto.\n          apply alphaeq_preserves_free_vars in a1; rw <- a1; auto. }\n\n      * apply alpha_eq_force_int_bound_app; simpl; tcsp;\n        allrw remove_nvars_nil_l; allrw app_nil_r; allrw remove_nvars_eq;\n        tcsp; eauto 3 with slow.\n        { apply alphaeq_preserves_free_vars in a2; rw <- a2; auto. }\n        { apply alphaeq_preserves_free_vars in p2; rw <- p2; auto.\n          apply alphaeq_preserves_free_vars in a2; rw <- a2; auto. }\n\n      * simpl; allrw app_nil_r.\n        allrw disjoint_app_l; allrw disjoint_cons_l;\n        allrw disjoint_app_l; allrw disjoint_singleton_l.\n        dands; eauto 3 with slow.\n\n      * simpl; allrw app_nil_r.\n        allrw disjoint_app_l; allrw disjoint_cons_l;\n        allrw disjoint_app_l; allrw disjoint_singleton_l.\n        dands; eauto 3 with slow.\n\n    + assert ({bs' : list BTerm\n               & {bs2' : list BTerm\n                  & alpha_eq_bterms bs bs'\n                  # alpha_eq_bterms bs2 bs2'\n                  # differ3_bterms b f g bs' bs2'\n                  # disjoint (flat_map bound_vars_bterm bs') vs\n                  # disjoint (flat_map bound_vars_bterm bs2') vs}}) as h.\n\n      { revert dependent bs2.\n        induction bs; destruct bs2; introv len imp; allsimpl; ginv.\n        - exists ([] : list (@BTerm o)) ([] : list (@BTerm o));\n            dands; simpl; eauto 3 with slow; try (apply br_bterms_nil).\n        - cpx.\n          destruct a as [l1 t1].\n          destruct b0 as [l2 t2].\n          pose proof (imp (bterm l1 t1) (bterm l2 t2)) as h; autodimp h hyp.\n          inversion h as [? ? ? df dg d1]; subst; clear h.\n          pose proof (ind t1 t1 l2) as h; repeat (autodimp h hyp); eauto 3 with slow.\n          pose proof (h t2 (*clf clg*) d1) as k; clear h.\n          exrepnd.\n\n          autodimp IHbs hyp.\n          { introv i d; eapply ind; eauto. }\n          pose proof (IHbs bs2) as k.\n          repeat (autodimp k hyp).\n          exrepnd.\n\n          pose proof (fresh_vars\n                        (length l2)\n                        (vs\n                           ++ l2\n                           ++ all_vars t1\n                           ++ all_vars t2\n                           ++ all_vars u1\n                           ++ all_vars u2\n                           ++ all_vars f\n                           ++ all_vars g\n                        )) as fv; exrepnd.\n          allrw disjoint_app_r; repnd.\n\n          exists ((bterm lvn (lsubst_aux u1 (var_ren l2 lvn))) :: bs')\n                 ((bterm lvn (lsubst_aux u2 (var_ren l2 lvn))) :: bs2');\n            dands; simpl;\n            try (apply br_bterms_cons);\n            try (apply alpha_eq_bterm_congr);\n            tcsp.\n          { apply alpha_bterm_change_aux; eauto 3 with slow.\n            allrw disjoint_app_l; dands; eauto 3 with slow. }\n          { apply alpha_bterm_change_aux; eauto 3 with slow.\n            allrw disjoint_app_l; dands; eauto 3 with slow. }\n          { apply differ3_bterm; auto.\n            apply differ3_lsubst_aux; eauto 3 with slow;\n            try (rw @sub_free_vars_var_ren; eauto 3 with slow);\n            try (rw @dom_sub_var_ren; eauto 3 with slow).\n            apply differ3_subs_refl; simpl;\n            try (rw @sub_bound_vars_var_ren; auto). }\n          { allrw disjoint_app_l; dands; eauto 3 with slow.\n            pose proof (subvars_bound_vars_lsubst_aux\n                          u1 (var_ren l2 lvn)) as sv.\n            eapply subvars_disjoint_l;[exact sv|].\n            apply disjoint_app_l; dands; auto.\n            rw @sub_bound_vars_var_ren; auto. }\n          { allrw disjoint_app_l; dands; eauto 3 with slow.\n            pose proof (subvars_bound_vars_lsubst_aux\n                          u2 (var_ren l2 lvn)) as sv.\n            eapply subvars_disjoint_l;[exact sv|].\n            apply disjoint_app_l; dands; auto.\n            rw @sub_bound_vars_var_ren; auto. }\n      }\n\n      exrepnd.\n      allunfold @alpha_eq_bterms.\n      allunfold @differ3_bterms.\n      allunfold @br_bterms.\n      allunfold @br_list; repnd.\n      exists (oterm op bs') (oterm op bs2'); dands; eauto 3 with slow.\n\n      * apply alpha_eq_oterm_combine; dands; auto.\n\n      * apply alpha_eq_oterm_combine; dands; auto.\nQed.\n\nLemma differ3_subst {o} :\n  forall b f g (t1 t2 : @NTerm o) sub1 sub2,\n    disjoint (free_vars f) (dom_sub sub1)\n    -> disjoint (free_vars g) (dom_sub sub2)\n    -> differ3 b f g t1 t2\n    -> differ3_subs b f g sub1 sub2\n    -> differ3_alpha b f g (lsubst t1 sub1) (lsubst t2 sub2).\nProof.\n  introv clf clg dt ds.\n\n  pose proof (unfold_lsubst sub1 t1) as h; exrepnd.\n  pose proof (unfold_lsubst sub2 t2) as k; exrepnd.\n  rw h0; rw k0.\n\n  pose proof (differ3_change_bound_vars\n                b f g (sub_free_vars sub1 ++ sub_free_vars sub2)\n                t1 t2 dt) as d; exrepnd.\n  allrw disjoint_app_r; repnd.\n\n  exists (lsubst_aux u1 sub1) (lsubst_aux u2 sub2); dands; auto.\n\n  - apply lsubst_aux_alpha_congr2; eauto 3 with slow.\n\n  - apply lsubst_aux_alpha_congr2; eauto 3 with slow.\n\n  - apply differ3_lsubst_aux; auto.\nQed.\nHint Resolve differ3_subst : slow.\n\nLemma differ3_bterms_implies_eq_map_num_bvars {o} :\n  forall b f g (bs1 bs2 : list (@BTerm o)),\n    differ3_bterms b f g bs1 bs2\n    -> map num_bvars bs1 = map num_bvars bs2.\nProof.\n  induction bs1; destruct bs2; introv d; allsimpl; auto;\n  allunfold @differ3_bterms; allunfold @br_bterms; allunfold @br_list;\n  allsimpl; repnd; cpx.\n  pose proof (d a b0) as h; autodimp h hyp.\n  inversion h; subst.\n  f_equal.\n  unfold num_bvars; simpl; auto.\nQed.\n\nDefinition differ3_sk {o} b f g (sk1 sk2 : @sosub_kind o) :=\n  differ3_b b f g (sk2bterm sk1) (sk2bterm sk2).\n\nInductive differ3_sosubs {o} b f g : @SOSub o -> @SOSub o -> Type :=\n| dsosub3_nil : differ3_sosubs b f g [] []\n| dsosub3_cons :\n    forall v sk1 sk2 sub1 sub2,\n      differ3_sk b f g sk1 sk2\n      -> differ3_sosubs b f g sub1 sub2\n      -> differ3_sosubs b f g ((v,sk1) :: sub1) ((v,sk2) :: sub2).\nHint Constructors differ3_sosubs.\n\nLemma differ3_bterms_cons {o} :\n  forall b f g (b1 b2 : @BTerm o) bs1 bs2,\n    differ3_bterms b f g (b1 :: bs1) (b2 :: bs2)\n    <=> (differ3_b b f g b1 b2 # differ3_bterms b f g bs1 bs2).\nProof.\n  unfold differ3_bterms; introv.\n  rw @br_bterms_cons_iff; sp.\nQed.\n\nLemma differ3_mk_abs_substs {o} :\n  forall b f g (bs1 bs2 : list (@BTerm o)) vars,\n    differ3_bterms b f g bs1 bs2\n    -> length vars = length bs1\n    -> differ3_sosubs b f g (mk_abs_subst vars bs1) (mk_abs_subst vars bs2).\nProof.\n  induction bs1; destruct bs2; destruct vars; introv d m; allsimpl; cpx; tcsp.\n  - provefalse.\n    apply differ3_bterms_implies_eq_map_num_bvars in d; allsimpl; cpx.\n  - apply differ3_bterms_cons in d; repnd.\n    destruct s, a, b0.\n    inversion d0; subst.\n    boolvar; auto.\nQed.\n\nLemma differ3_b_change_bound_vars {o} :\n  forall b f g vs (b1 b2 : @BTerm o),\n    differ3_b b f g b1 b2\n    -> {u1 : BTerm\n        & {u2 : BTerm\n           & differ3_b b f g u1 u2\n           # alpha_eq_bterm b1 u1\n           # alpha_eq_bterm b2 u2\n           # disjoint (bound_vars_bterm u1) vs\n           # disjoint (bound_vars_bterm u2) vs}}.\nProof.\n  introv d.\n  pose proof (differ3_change_bound_vars\n                b f g vs (oterm Exc [b1]) (oterm Exc [b2])) as h.\n  repeat (autodimp h hyp).\n  - apply differ3_oterm; simpl; tcsp.\n    introv i; dorn i; tcsp; cpx.\n  - exrepnd.\n    inversion h2 as [|?|? ? ? len1 imp1]; subst; allsimpl; cpx.\n    inversion h3 as [|?|? ? ? len2 imp2]; subst; allsimpl; cpx.\n    pose proof (imp1 0) as k1; autodimp k1 hyp; allsimpl; clear imp1.\n    pose proof (imp2 0) as k2; autodimp k2 hyp; allsimpl; clear imp2.\n    allunfold @selectbt; allsimpl.\n    allrw app_nil_r.\n    exists x x0; dands; auto.\n    inversion h0 as [|?|?|? ? ? ? i]; subst; allsimpl; GC.\n    apply i; sp.\nQed.\n\nLemma differ3_sk_change_bound_vars {o} :\n  forall b f g vs (sk1 sk2 : @sosub_kind o),\n    differ3_sk b f g sk1 sk2\n    -> {u1 : sosub_kind\n        & {u2 : sosub_kind\n           & differ3_sk b f g u1 u2\n           # alphaeq_sk sk1 u1\n           # alphaeq_sk sk2 u2\n           # disjoint (bound_vars_sk u1) vs\n           # disjoint (bound_vars_sk u2) vs}}.\nProof.\n  introv d.\n  unfold differ3_sk in d.\n  apply (differ3_b_change_bound_vars b f g vs) in d; exrepnd; allsimpl; auto.\n  exists (bterm2sk u1) (bterm2sk u2).\n  destruct u1, u2, sk1, sk2; allsimpl; dands; auto;\n  apply alphaeq_sk_iff_alphaeq_bterm2; simpl; auto.\nQed.\n\nLemma differ3_sosubs_change_bound_vars {o} :\n  forall b f g vs (sub1 sub2 : @SOSub o),\n    differ3_sosubs b f g sub1 sub2\n    -> {sub1' : SOSub\n        & {sub2' : SOSub\n           & differ3_sosubs b f g sub1' sub2'\n           # alphaeq_sosub sub1 sub1'\n           # alphaeq_sosub sub2 sub2'\n           # disjoint (bound_vars_sosub sub1') vs\n           # disjoint (bound_vars_sosub sub2') vs}}.\nProof.\n  induction sub1; destruct sub2; introv d.\n  - exists ([] : @SOSub o) ([] : @SOSub o); dands; simpl; tcsp.\n  - inversion d.\n  - inversion d.\n  - inversion d as [|? ? ? ? ? dsk dso]; subst; clear d.\n    apply IHsub1 in dso; exrepnd; auto.\n    apply (differ3_sk_change_bound_vars b f g vs) in dsk; exrepnd; auto.\n    exists ((v,u1) :: sub1') ((v,u2) :: sub2'); dands; simpl; auto;\n    allrw disjoint_app_l; dands; eauto 3 with slow.\nQed.\n\nLemma sosub_find_some_if_differ3_sosubs {o} :\n  forall b f g (sub1 sub2 : @SOSub o) v sk,\n    differ3_sosubs b f g sub1 sub2\n    -> sosub_find sub1 v = Some sk\n    -> {sk' : sosub_kind\n        & differ3_sk b f g sk sk'\n        # sosub_find sub2 v = Some sk'}.\nProof.\n  induction sub1; destruct sub2; introv aeq sf; allsimpl; tcsp.\n  - inversion aeq.\n  - destruct a, p; destruct s, s0.\n    inversion aeq as [|? ? ? ? ? dsk dso]; subst; clear aeq.\n    boolvar; subst; cpx; tcsp.\n    + eexists; dands; eauto.\n    + inversion dsk; subst; tcsp.\n    + inversion dsk; subst; tcsp.\nQed.\n\nLemma sosub_find_none_if_differ3_sosubs {o} :\n  forall b f g (sub1 sub2 : @SOSub o) v,\n    differ3_sosubs b f g sub1 sub2\n    -> sosub_find sub1 v = None\n    -> sosub_find sub2 v = None.\nProof.\n  induction sub1; destruct sub2; introv aeq sf; allsimpl; tcsp.\n  - inversion aeq.\n  - destruct a, p; destruct s, s0.\n    inversion aeq as [|? ? ? ? ? dsk dso]; subst; clear aeq.\n    boolvar; subst; cpx; tcsp.\n    inversion dsk; subst; tcsp.\nQed.\n\nLemma differ3_subs_combine {o} :\n  forall b f g (ts1 ts2 : list (@NTerm o)) vs,\n    length ts1 = length ts2\n    -> (forall t1 t2,\n          LIn (t1,t2) (combine ts1 ts2)\n          -> differ3 b f g t1 t2)\n    -> differ3_subs b f g (combine vs ts1) (combine vs ts2).\nProof.\n  induction ts1; destruct ts2; destruct vs; introv len imp; allsimpl; cpx; tcsp.\nQed.\n\nLemma differ3_apply_list {o} :\n  forall b f g (ts1 ts2 : list (@NTerm o)) t1 t2,\n    differ3 b f g t1 t2\n    -> length ts1 = length ts2\n    -> (forall x y, LIn (x,y) (combine ts1 ts2) -> differ3 b f g x y)\n    -> differ3 b f g (apply_list t1 ts1) (apply_list t2 ts2).\nProof.\n  induction ts1; destruct ts2; introv d l i; allsimpl; cpx.\n  apply IHts1; auto.\n  apply differ3_oterm; simpl; auto; tcsp.\n  introv k; repndors; cpx; tcsp; constructor; auto.\nQed.\n\nLemma differ3_sosub_filter {o} :\n  forall b f g (sub1 sub2 : @SOSub o) vs,\n    differ3_sosubs b f g sub1 sub2\n    -> differ3_sosubs b f g (sosub_filter sub1 vs) (sosub_filter sub2 vs).\nProof.\n  induction sub1; destruct sub2; introv d;\n  inversion d as [|? ? ? ? ? dsk dso]; subst; auto.\n  destruct sk1, sk2; allsimpl.\n  inversion dsk; subst.\n  boolvar; tcsp.\nQed.\nHint Resolve differ3_sosub_filter : slow.\n\nLemma no_utokens_sovar {o} :\n  forall v (ts : list (@SOTerm o)),\n    no_utokens (sovar v ts) <=> (forall t, LIn t ts -> no_utokens t).\nProof.\n  introv.\n  unfold no_utokens; simpl.\n  induction ts; simpl; split; intro k; tcsp.\n  - introv i; repndors; subst; tcsp.\n    + rw app_eq_nil_iff in k; sp.\n    + rw app_eq_nil_iff in k; repnd.\n      rw IHts in k; sp.\n  - rw app_eq_nil_iff; dands; tcsp.\n    apply IHts; tcsp.\nQed.\n\nDefinition no_utokens_op {o} (op : @Opid o) :=\n  get_utokens_o op = [].\n\nLemma no_utokens_soterm {o} :\n  forall op (bs : list (@SOBTerm o)),\n    no_utokens (soterm op bs)\n    <=>\n    (no_utokens_op op # (forall vs t, LIn (sobterm vs t) bs -> no_utokens t)).\nProof.\n  introv; unfold cover_so_vars; simpl; split; intro k; repnd; dands; tcsp.\n  - allunfold @no_utokens; allsimpl.\n    rw app_eq_nil_iff in k; repnd; auto.\n  - introv i.\n    allunfold @no_utokens; allsimpl.\n    rw app_eq_nil_iff in k; repnd; auto.\n    rw flat_map_empty in k.\n    apply k in i; allsimpl; auto.\n  - allunfold @no_utokens; simpl.\n    rw app_eq_nil_iff; dands; auto.\n    rw flat_map_empty; introv i.\n    destruct a; apply k in i; allsimpl; auto.\nQed.\n\nLemma differ3_sosub_aux {o} :\n  forall b f g (t : @SOTerm o) sub1 sub2,\n    no_utokens t\n    -> disjoint (fo_bound_vars t) (free_vars f)\n    -> disjoint (fo_bound_vars t) (free_vars g)\n    -> differ3_sosubs b f g sub1 sub2\n    -> disjoint (fo_bound_vars t) (free_vars_sosub sub1)\n    -> disjoint (free_vars_sosub sub1) (bound_vars_sosub sub1)\n    -> disjoint (all_fo_vars t) (bound_vars_sosub sub1)\n    -> disjoint (fo_bound_vars t) (free_vars_sosub sub2)\n    -> disjoint (free_vars_sosub sub2) (bound_vars_sosub sub2)\n    -> disjoint (all_fo_vars t) (bound_vars_sosub sub2)\n    -> cover_so_vars t sub1\n    -> cover_so_vars t sub2\n    -> differ3 b f g (sosub_aux sub1 t) (sosub_aux sub2 t).\nProof.\n  soterm_ind t as [v ts ind| |op bs ind] Case;\n  introv nut df dg ds;\n  introv disj1 disj2 disj3 disj4 disj5 disj6 cov1 cov2; allsimpl; auto.\n\n  - Case \"sovar\".\n    allrw @cover_so_vars_sovar; repnd.\n    allrw @no_utokens_sovar.\n    allrw disjoint_cons_l; repnd.\n    remember (sosub_find sub1 (v, length ts)) as f1; symmetry in Heqf1.\n    destruct f1.\n\n    + applydup (sosub_find_some_if_differ3_sosubs b f g sub1 sub2) in Heqf1; auto.\n      exrepnd.\n      rw Heqf2.\n      destruct s as [l1 t1].\n      destruct sk' as [l2 t2].\n      inversion Heqf0; subst.\n      apply differ3_lsubst_aux; auto.\n\n      * apply sosub_find_some in Heqf2; repnd.\n        rw @dom_sub_combine; allrw map_length; eauto 3 with slow.\n\n      * apply sosub_find_some in Heqf2; repnd.\n        rw @dom_sub_combine; allrw map_length; eauto 3 with slow.\n\n      * apply differ3_subs_combine; allrw map_length; 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; allsimpl.\n        disj_flat_map.\n        apply ind; auto.\n\n      * apply sosub_find_some in Heqf1; repnd.\n        rw @sub_free_vars_combine; allrw map_length; auto.\n        rw flat_map_map; unfold compose.\n        eapply disjoint_bound_vars_prop3; eauto 3 with slow.\n        eapply subvars_disjoint_r;[|apply disjoint_sym;eauto].\n        apply subvars_flat_map2; introv i.\n        apply fovars_subvars_all_fo_vars.\n\n      * apply sosub_find_some in Heqf2; repnd.\n        rw @sub_free_vars_combine; allrw map_length; auto.\n        rw flat_map_map; unfold compose.\n        eapply disjoint_bound_vars_prop3; eauto 3 with slow.\n        eapply subvars_disjoint_r;[|apply disjoint_sym;eauto].\n        apply subvars_flat_map2; introv i.\n        apply fovars_subvars_all_fo_vars.\n\n    + applydup (sosub_find_none_if_differ3_sosubs b f g sub1 sub2) in Heqf1; auto.\n      rw Heqf0.\n      apply differ3_apply_list; allrw map_length; auto.\n      introv i.\n      rw <- @map_combine in i; rw in_map_iff in i; exrepnd; cpx.\n      apply in_combine_same in i1; repnd; subst; allsimpl.\n      disj_flat_map.\n      apply ind; auto.\n\n  - Case \"soterm\".\n    allrw @cover_so_vars_soterm.\n    allrw @no_utokens_soterm; repnd.\n    apply differ3_oterm; allrw map_length; tcsp; try (complete (rw nut0; sp)).\n    introv i.\n    rw <- @map_combine in i; rw in_map_iff in i; exrepnd; cpx.\n    apply in_combine_same in i1; repnd; subst; allsimpl.\n    destruct a as [l t].\n    disj_flat_map.\n    allsimpl; allrw disjoint_app_l; repnd.\n    disj_flat_map; allsimpl; allrw disjoint_app_l; repnd.\n    constructor; auto.\n    eapply ind; eauto 3 with slow.\n\n    + pose proof (subvars_free_vars_sosub_sosub_filter sub1 (vars2sovars l)) as sv.\n      eapply subvars_disjoint_r;[exact sv|]; auto.\n\n    + pose proof (subvars_free_vars_sosub_sosub_filter sub1 (vars2sovars l)) as sv1.\n      pose proof (subvars_bound_vars_sosub_filter sub1 (vars2sovars l)) as sv2.\n      eapply subvars_disjoint_r;[exact sv2|]; auto.\n      eapply subvars_disjoint_l;[exact sv1|]; auto.\n\n    + pose proof (subvars_bound_vars_sosub_filter sub1 (vars2sovars l)) as sv1.\n      eapply subvars_disjoint_r;[exact sv1|]; auto.\n\n    + pose proof (subvars_free_vars_sosub_sosub_filter sub2 (vars2sovars l)) as sv1.\n      eapply subvars_disjoint_r;[exact sv1|]; auto.\n\n    + pose proof (subvars_free_vars_sosub_sosub_filter sub2 (vars2sovars l)) as sv1.\n      pose proof (subvars_bound_vars_sosub_filter sub2 (vars2sovars l)) as sv2.\n      eapply subvars_disjoint_r;[exact sv2|]; auto.\n      eapply subvars_disjoint_l;[exact sv1|]; auto.\n\n    + pose proof (subvars_bound_vars_sosub_filter sub2 (vars2sovars l)) as sv1.\n      eapply subvars_disjoint_r;[exact sv1|]; auto.\n\n    + discover.\n      apply cover_so_vars_sosub_filter; auto.\n\n    + discover.\n      apply cover_so_vars_sosub_filter; auto.\nQed.\n\nLemma differ3_sosub {o} :\n  forall b f g (t : @SOTerm o) (sub1 sub2 : SOSub),\n    no_utokens t\n    -> differ3_sosubs b f g sub1 sub2\n    -> cover_so_vars t sub1\n    -> cover_so_vars t sub2\n    -> differ3_alpha b f g (sosub sub1 t) (sosub sub2 t).\nProof.\n  introv nut d c1 c2.\n  pose proof (unfold_sosub sub1 t) as h.\n  destruct h as [sub1' h]; destruct h as [t1 h]; repnd; rw h.\n  pose proof (unfold_sosub sub2 t) as k.\n  destruct k as [sub2' k]; destruct k as [t2 k]; repnd; rw k.\n\n  pose proof (differ3_sosubs_change_bound_vars\n                b\n                f g\n                (all_fo_vars t1\n                             ++ all_fo_vars t2\n                             ++ free_vars_sosub sub1\n                             ++ free_vars_sosub sub2\n                )\n                sub1 sub2\n                d) as e.\n  destruct e as [sub1'' e]; destruct e as [sub2'' e]; repnd.\n\n  pose proof (fo_change_bvars_alpha_spec\n                (free_vars_sosub sub1''\n                                 ++ free_vars_sosub sub2''\n                                 ++ bound_vars_sosub sub1''\n                                 ++ bound_vars_sosub sub2''\n                                 ++ free_vars f\n                                 ++ free_vars g\n                )\n                t) as q.\n  revert q.\n  fo_change t0; simpl; intro q; repnd; GC.\n\n  allrw disjoint_app_l; allrw disjoint_app_r; repnd.\n\n  assert (so_alphaeq t1 t0) as a1 by eauto 3 with slow.\n  assert (so_alphaeq t2 t0) as a2 by eauto 3 with slow.\n\n  pose proof (fovars_subvars_all_fo_vars t1) as sv1.\n  pose proof (fovars_subvars_all_fo_vars t2) as sv2.\n  pose proof (alphaeq_sosub_preserves_free_vars sub1 sub1'') as ev1; autodimp ev1 hyp.\n  pose proof (alphaeq_sosub_preserves_free_vars sub2 sub2'') as ev2; autodimp ev2 hyp.\n  pose proof (fovars_subvars_all_fo_vars t0) as sv3.\n  pose proof (all_fo_vars_eqvars t0) as ev3.\n  pose proof (all_fo_vars_eqvars t1) as ev4.\n  pose proof (so_alphaeq_preserves_free_vars t1 t0 a1) as efv1.\n  pose proof (so_alphaeq_preserves_free_vars t2 t0 a2) as efv2.\n  applydup eqvars_app_r_implies_subvars in ev4 as ev; destruct ev as [ev5 ev6].\n\n  assert (disjoint (fo_bound_vars t0) (free_vars_sosub sub1'')\n          # disjoint (free_vars_sosub sub1'') (bound_vars_sosub sub1'')\n          # disjoint (all_fo_vars t0) (bound_vars_sosub sub1'')\n          # disjoint (fo_bound_vars t0) (free_vars_sosub sub2'')\n          # disjoint (free_vars_sosub sub2'') (bound_vars_sosub sub2'')\n          # disjoint (all_fo_vars t0) (bound_vars_sosub sub2'')) as disj.\n\n  { dands; eauto 3 with slow.\n    - rw <- ev1; eauto 3 with slow.\n    - eapply eqvars_disjoint;[apply eqvars_sym; exact ev3|].\n      apply disjoint_app_l; dands; eauto 3 with slow.\n      rw <- efv1.\n      eapply subvars_disjoint_l;[exact ev6|]; eauto 3 with slow.\n    - rw <- ev2; eauto 3 with slow.\n    - eapply eqvars_disjoint;[apply eqvars_sym; exact ev3|].\n      apply disjoint_app_l; dands; eauto 3 with slow.\n      rw <- efv1.\n      eapply subvars_disjoint_l;[exact ev6|]; eauto 3 with slow. }\n\n  repnd.\n\n  pose proof (sosub_aux_alpha_congr2\n                t1 t0 sub1' sub1'') as aeq1.\n  repeat (autodimp aeq1 hyp); eauto 3 with slow.\n\n  { rw disjoint_app_r; dands; eauto 3 with slow. }\n\n  { rw disjoint_app_r; dands; eauto 3 with slow. }\n\n  pose proof (sosub_aux_alpha_congr2\n                t2 t0 sub2' sub2'') as aeq2.\n  repeat (autodimp aeq2 hyp); eauto 3 with slow.\n\n  { rw disjoint_app_r; dands; eauto 3 with slow. }\n\n  { rw disjoint_app_r; dands; eauto 3 with slow. }\n\n  exists (sosub_aux sub1'' t0) (sosub_aux sub2'' t0); dands;\n  try (apply alphaeq_eq; complete auto).\n\n  apply differ3_sosub_aux; eauto 3 with slow.\n\n  { allapply @get_utokens_so_soalphaeq.\n    unfold no_utokens; rw <- h5; auto. }\nQed.\n\nLemma differ3_mk_instance {o} :\n  forall b f g (t : @SOTerm o) vars bs1 bs2,\n    no_utokens t\n    -> matching_bterms vars bs1\n    -> matching_bterms vars bs2\n    -> socovered t vars\n    -> socovered t vars\n    -> differ3_bterms b f g bs1 bs2\n    -> differ3_alpha b f g (mk_instance vars bs1 t) (mk_instance vars bs2 t).\nProof.\n  introv nut m1 m2 sc1 sc2 dbs.\n  unfold mk_instance.\n  applydup @matching_bterms_implies_eq_length in m1.\n  applydup (@differ3_mk_abs_substs o b f g bs1 bs2 vars) in dbs; auto.\n\n  apply differ3_sosub; auto;\n  apply socovered_implies_cover_so_vars; auto.\nQed.\n\nLemma exists_compute_step_if_reduces_to {o} :\n  forall lib (t1 t2 : @NTerm o),\n    reduces_to lib t1 t2\n    -> isvalue_like t2\n    -> {u : NTerm\n        & compute_step lib t1 = csuccess u\n        # reduces_to lib u t2}.\nProof.\n  introv r isv.\n  unfold reduces_to in r; exrepnd.\n  destruct k.\n  - allrw @reduces_in_atmost_k_steps_0; subst.\n    unfold isvalue_like in isv; repndors.\n    + apply iscan_implies in isv; repndors; exrepnd; subst; simpl;\n      csunf; simpl; eexists; dands; eauto 3 with slow.\n    + apply isexc_implies2 in isv; exrepnd; subst; simpl.\n      csunf; simpl.\n      eexists; eauto 3 with slow.\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    eexists; dands; eauto 3 with slow.\nQed.\n\nDefinition red_to_can {p} lib (t : @NTerm p) :=\n  {u : NTerm\n   & reduces_to lib t u\n   # iscan u}.\n\nLemma if_red_to_can_ncompop_can1 {o} :\n  forall lib c can bs (t : @NTerm o) l,\n    red_to_can\n      lib\n      (oterm (NCan (NCompOp c))\n             (bterm [] (oterm (Can can) bs)\n                    :: bterm [] t\n                    :: l))\n    -> red_to_can lib t.\nProof.\n  introv hv.\n  unfold red_to_can in hv; exrepnd.\n\n  pose proof (converges_to_value_like_ncompop lib c can bs t l) as h.\n  autodimp h hyp.\n\n  { unfold converges_to_value_like; exists u; sp. }\n\n  repndors; exrepnd.\n\n  - exists (pk2term pk); dands; eauto 3 with slow.\n\n  - provefalse.\n    apply isexc_implies2 in h0; exrepnd; subst.\n    pose proof (compose_reduces_to_primarg_ncompop\n                  lib c can bs t (oterm Exc l0) u l) as h.\n    repeat (autodimp h hyp); tcsp.\n\n    apply iscan_implies in hv0; repndors; exrepnd; subst;\n    apply reduces_to_split2 in h; dorn h; simpl in h; ginv;\n    exrepnd; ginv;\n    csunf h2; allsimpl; ginv;\n    dcwf q; ginv;\n    apply reduces_to_if_isvalue_like in h0; tcsp; ginv.\nQed.\n\nLemma if_red_to_can_narithop_can1 {o} :\n  forall lib c can bs (t : @NTerm o) l,\n    red_to_can\n      lib\n      (oterm (NCan (NArithOp c))\n             (bterm [] (oterm (Can can) bs)\n                    :: bterm [] t\n                    :: l))\n    -> red_to_can lib t.\nProof.\n  introv hv.\n  unfold red_to_can in hv; exrepnd.\n\n  pose proof (converges_to_value_like_narithop lib c can bs t l) as h.\n  autodimp h hyp.\n\n  { unfold converges_to_value_like; exists u; sp. }\n\n  repndors; exrepnd.\n\n  - exists (@mk_integer o i); dands.\n    + unfold computes_to_value in h0; sp.\n    + unfold isvalue_like; simpl; sp.\n\n  - provefalse.\n    apply isexc_implies2 in h0; exrepnd; subst.\n    pose proof (compose_reduces_to_primarg_arithop\n                  lib c can bs t (oterm Exc l0) u l) as h.\n    repeat (autodimp h hyp); tcsp.\n\n    apply iscan_implies in hv0; repndors; exrepnd; subst;\n    apply reduces_to_split2 in h; dorn h; simpl in h; ginv;\n    exrepnd; ginv;\n    csunf h2; allsimpl; ginv;\n    dcwf q; ginv;\n    apply reduces_to_if_isvalue_like in h0; tcsp; ginv.\nQed.\n\nDefinition red_to_can_k {p} lib k (t : @NTerm p) :=\n  {u : NTerm\n   & reduces_in_atmost_k_steps lib t u k\n   # iscan u}.\n\nLemma red_to_can_0 {o} :\n  forall lib (t : @NTerm o),\n    red_to_can_k lib 0 t <=> iscan t.\nProof.\n  introv; unfold red_to_can_k; split; intro k; exrepnd.\n  - allrw @reduces_in_atmost_k_steps_0; subst; auto.\n  - exists t; allrw @reduces_in_atmost_k_steps_0; auto.\nQed.\n\nLemma red_to_can_S {o} :\n  forall lib k (t : @NTerm o),\n    red_to_can_k lib (S k) t\n    <=> {u : NTerm\n         & compute_step lib t = csuccess u\n         # red_to_can_k lib k u}.\nProof.\n  introv; unfold red_to_can_k; split; intro h; exrepnd.\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    eexists; eauto.\n  - exists u0; dands; auto.\n    allrw @reduces_in_atmost_k_steps_S.\n    eexists; eauto.\nQed.\n\nLemma if_red_to_can_k_ncompop_can1 {o} :\n  forall lib c can bs k (t : @NTerm o) l,\n    red_to_can_k\n      lib k\n      (oterm (NCan (NCompOp c))\n             (bterm [] (oterm (Can can) bs)\n                    :: bterm [] t\n                    :: l))\n    -> {j : nat & j < k # red_to_can_k lib j t}.\nProof.\n  induction k; introv r.\n  - allrw @red_to_can_0; inversion r.\n  - allrw @red_to_can_S; exrepnd.\n    destruct t as [v|f|op bs1]; try (complete (csunf r1; allsimpl; dcwf h));[].\n    dopid op as [can2|ncan2|exc2|abs2] Case.\n    + exists 0; dands; try omega.\n      rw @red_to_can_0; auto.\n    + rw @compute_step_ncompop_ncan2 in r1.\n      dcwf h.\n      remember (compute_step lib (oterm (NCan ncan2) bs1)) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @red_to_can_S.\n      exists n; tcsp.\n    + csunf r1; simpl in r1; ginv.\n      dcwf h; ginv.\n      provefalse.\n      unfold red_to_can_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in r0; subst; tcsp.\n    + csunf r1; simpl in r1; csunf r1; simpl in r1.\n      dcwf h.\n      unfold on_success in r1.\n      remember (compute_step_lib lib abs2 bs1) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @red_to_can_S.\n      exists n; tcsp.\nQed.\n\nLemma if_red_to_can_k_narithop_can1 {o} :\n  forall lib c can bs k (t : @NTerm o) l,\n    red_to_can_k\n      lib k\n      (oterm (NCan (NArithOp c))\n             (bterm [] (oterm (Can can) bs)\n                    :: bterm [] t\n                    :: l))\n    -> {j : nat & j < k # red_to_can_k lib j t}.\nProof.\n  induction k; introv r.\n  - allrw @red_to_can_0; inversion r.\n  - allrw @red_to_can_S; exrepnd.\n    destruct t as [v|f|op bs1]; try (complete (csunf r1; allsimpl; dcwf h));[].\n    dopid op as [can2|ncan2|exc2|abs2] Case.\n    + exists 0; dands; try omega.\n      rw @red_to_can_0; auto.\n    + rw @compute_step_narithop_ncan2 in r1.\n      dcwf h.\n      remember (compute_step lib (oterm (NCan ncan2) bs1)) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @red_to_can_S.\n      exists n; tcsp.\n    + csunf r1; simpl in r1; ginv.\n      dcwf h; ginv.\n      provefalse.\n      unfold red_to_can_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in r0; subst; tcsp.\n    + csunf r1; simpl in r1; csunf r1; simpl in r1.\n      dcwf h.\n      unfold on_success in r1.\n      remember (compute_step_lib lib abs2 bs1) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @red_to_can_S.\n      exists n; tcsp.\nQed.\n\nLemma red_to_can_k_lt {o} :\n  forall lib k1 k2 (t : @NTerm o),\n    red_to_can_k lib k1 t\n    -> k1 < k2\n    -> red_to_can_k lib k2 t.\nProof.\n  unfold red_to_can_k; introv r l; exrepnd.\n  exists u; dands; auto.\n  pose proof (no_change_after_value_like lib t k1 u) as h.\n  repeat (autodimp h hyp); tcsp.\n  pose proof (h (k2 - k1)) as hh.\n  assert (k2 - k1 + k1 = k2) as e by omega.\n  rw e in hh; auto.\nQed.\n\nLemma if_red_to_can_k_cbv_primarg {o} :\n  forall lib k (t : @NTerm o) bs,\n    red_to_can_k lib k (oterm (NCan NCbv) (bterm [] t :: bs))\n    -> {j : nat & j < k # red_to_can_k lib j t}.\nProof.\n  induction k; introv r.\n\n  - allrw @red_to_can_0; subst.\n    inversion r.\n\n  - allrw @red_to_can_S; exrepnd.\n    destruct t as [v|f|op l].\n\n    { simpl in r1; ginv. }\n\n    { exists 0; dands; try omega.\n      apply red_to_can_0; simpl; auto. }\n\n    dopid op as [can1|ncan1|exc1|abs1] Case.\n\n    + Case \"Can\".\n      exists 0; dands; try omega.\n      rw @red_to_can_0; auto.\n\n    + Case \"NCan\".\n      rw @compute_step_ncan_ncan in r1.\n      remember (compute_step lib (oterm (NCan ncan1) l)) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @red_to_can_S; exists n; sp.\n\n    + Case \"Exc\".\n      csunf r1; allsimpl; ginv.\n      unfold red_to_can_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in r0; subst; tcsp.\n      inversion r1.\n\n    + Case \"Abs\".\n      csunf r1; allsimpl; csunf r1; allsimpl.\n      unfold on_success in r1.\n      remember (compute_step_lib lib abs1 l) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @red_to_can_S; exists n; sp.\nQed.\n\nLemma if_red_to_can_k_force_int_bound {o} :\n  forall lib a v b k (t : @NTerm o),\n    red_to_can_k\n      lib k\n      (force_int_bound v b t (uexc a))\n    -> {j : nat\n        & {z : Z\n        & reduces_in_atmost_k_steps lib t (mk_integer z) j\n        # S (S j) < k\n        # Z.abs_nat z < b}}.\nProof.\n  induction k; introv r.\n\n  - allrw @red_to_can_0; inversion r.\n\n  - allrw @red_to_can_S; exrepnd.\n    destruct t as [v1|f1|op1 bs1].\n\n    { simpl in r1; ginv. }\n\n    { csunf r1; allsimpl; ginv.\n      allunfold @apply_bterm; allsimpl; allrw @fold_subst.\n      pose proof (hasvalue_like_subst_less_bound_seq lib b v (uexc a) f1) as h.\n      autodimp h hyp; tcsp.\n      unfold red_to_can_k in r0; exrepnd.\n      exists u; dands; eauto 3 with slow. }\n\n    dopid op1 as [can1|ncan1|exc1|abs1] Case.\n\n    + Case \"Can\".\n      csunf r1; simpl in r1; ginv.\n      unfold apply_bterm, lsubst in r0; allsimpl.\n      boolvar; fold_terms.\n      destruct k.\n\n      { allrw @red_to_can_0; inversion r0. }\n\n      allrw @red_to_can_S; exrepnd; allsimpl.\n      csunf r0; allsimpl; csunf r0; allsimpl.\n      dcwf h; allsimpl.\n      unfold on_success in r0.\n      fold_terms.\n      match goal with\n        | [ H : context[compute_step_comp ?a1 ?a2 ?a3 ?a4 ?a5 ?a6 ?a7] |- _ ] =>\n          remember (compute_step_comp a1 a2 a3 a4 a5 a6 a7)  as comp\n      end.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply compute_step_compop_success_can_can in Heqcomp.\n      exrepnd; subst; allsimpl; cpx; GC.\n      repndors; exrepnd; ginv.\n      allapply @get_param_from_cop_pki; subst.\n\n      destruct k.\n\n      { allrw @red_to_can_0; inversion r1. }\n\n      allrw @red_to_can_S; exrepnd.\n      csunf r1; allsimpl.\n      boolvar; allsimpl; ginv.\n\n      * destruct k.\n\n        { allrw @red_to_can_0; inversion r0. }\n\n        allrw @red_to_can_S; exrepnd.\n        csunf r0; allsimpl.\n        dcwf h; allsimpl.\n        unfold compute_step_comp in r0; allsimpl; boolvar; ginv.\n\n        { exists 0 n1; dands; try omega; eauto 3 with slow.\n          - rw @reduces_in_atmost_k_steps_0; auto.\n          - apply abs_of_neg; auto. }\n\n        { unfold red_to_can_k in r1; exrepnd.\n          apply reduces_in_atmost_k_steps_if_isvalue_like in r1; subst; tcsp; eauto 2 with slow.\n          inversion r0. }\n\n      * dcwf h; allsimpl.\n        unfold compute_step_comp in r1; allsimpl; boolvar; ginv.\n\n        { exists 0 n1; dands; try omega; eauto 3 with slow.\n          - rw @reduces_in_atmost_k_steps_0; auto.\n          - apply abs_of_pos; auto. }\n\n        { unfold red_to_can_k in r0; exrepnd.\n          apply reduces_in_atmost_k_steps_if_isvalue_like in r0; subst; tcsp; eauto 2 with slow.\n          inversion r1. }\n\n    + Case \"NCan\".\n      unfold force_int_bound in r1.\n      rw @compute_step_mk_cbv_ncan in r1.\n      remember (compute_step lib (oterm (NCan ncan1) bs1)) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n\n      apply IHk in r0; auto; exrepnd.\n\n      exists (S j) z; dands; auto; try omega.\n      rw @reduces_in_atmost_k_steps_S; eexists; eauto.\n\n    + Case \"Exc\".\n      csunf r1; allsimpl; ginv.\n      unfold red_to_can_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in r0; subst; tcsp.\n      inversion r1.\n\n    + Case \"Abs\".\n      simpl in r1; unfold on_success in r1; csunf r1; allsimpl; csunf r1; allsimpl.\n      remember (compute_step_lib lib abs1 bs1) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n\n      apply IHk in r0; auto; exrepnd.\n\n      exists (S j) z; dands; auto; try omega.\n      rw @reduces_in_atmost_k_steps_S; eexists; eauto.\nQed.\n\n(*\nDefinition isvalue_like_except {o} a (t : @NTerm o) :=\n  isvalue_like t # !isnexc (Some a) t.\n\nDefinition has_value_like_except_k {p} lib a k (t : @NTerm p) :=\n  {u : NTerm\n   & reduces_in_atmost_k_steps lib t u k\n   # isvalue_like_except a u}.\n\nLemma has_value_like_except_0 {o} :\n  forall lib a (t : @NTerm o),\n    has_value_like_except_k lib a 0 t <=> isvalue_like_except a t.\nProof.\n  introv; unfold has_value_like_except_k; split; intro k; exrepnd.\n  - allrw @reduces_in_atmost_k_steps_0; subst; auto.\n  - exists t; allrw @reduces_in_atmost_k_steps_0; auto.\nQed.\n\nLemma has_value_like_except_S {o} :\n  forall lib k a (t : @NTerm o),\n    has_value_like_except_k lib a (S k) t\n    <=> {u : NTerm\n         & compute_step lib t = csuccess u\n         # has_value_like_except_k lib a k u}.\nProof.\n  introv; unfold has_value_like_except_k; split; intro h; exrepnd.\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    eexists; eauto.\n  - exists u0; dands; auto.\n    allrw @reduces_in_atmost_k_steps_S.\n    eexists; eauto.\nQed.\n\nLemma if_has_value_like_except_k_ncompop_can1 {o} :\n  forall lib c can bs a k (t : @NTerm o) l,\n    has_value_like_except_k\n      lib a k\n      (oterm (NCan (NCompOp c))\n             (bterm [] (oterm (Can can) bs)\n                    :: bterm [] t\n                    :: l))\n    -> {j : nat & j < k # has_value_like_except_k lib a j t}.\nProof.\n  induction k; introv r.\n  - allrw @has_value_like_except_0; repnd.\n    unfold isvalue_like_except in r; repnd.\n    inversion r0; sp.\n  - allrw @has_value_like_except_S; exrepnd.\n    destruct t as [v|op bs1]; try (complete (allsimpl; ginv)).\n    dopid op as [can2|ncan2|exc2|mrk2|abs2] Case.\n    + exists 0; dands; try omega.\n      rw @has_value_like_except_0; dands; eauto 3 with slow.\n      unfold isvalue_like_except; simpl; sp.\n    + rw @compute_step_ncompop_ncan2 in r1.\n      remember (compute_step lib (oterm (NCan ncan2) bs1)) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @has_value_like_except_S.\n      exists n; tcsp.\n    + simpl in r1; ginv.\n      exists k; sp.\n    + allsimpl; ginv.\n    + simpl in r1.\n      unfold on_success in r1.\n      remember (compute_step_lib lib abs2 bs1) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @has_value_like_except_S.\n      exists n; tcsp.\nQed.\n\nLemma if_has_value_like_except_k_narithop_can1 {o} :\n  forall lib c can bs a k (t : @NTerm o) l,\n    has_value_like_except_k\n      lib a k\n      (oterm (NCan (NArithOp c))\n             (bterm [] (oterm (Can can) bs)\n                    :: bterm [] t\n                    :: l))\n    -> {j : nat & j < k # has_value_like_except_k lib a j t}.\nProof.\n  induction k; introv r.\n  - allrw @has_value_like_except_0; repnd.\n    unfold isvalue_like_except in r; repnd.\n    inversion r0; sp.\n  - allrw @has_value_like_except_S; exrepnd.\n    destruct t as [v|op bs1]; try (complete (allsimpl; ginv)).\n    dopid op as [can2|ncan2|exc2|mrk2|abs2] Case.\n    + exists 0; dands; try omega.\n      rw @has_value_like_except_0; dands; eauto 3 with slow.\n      unfold isvalue_like_except; simpl; sp.\n    + rw @compute_step_narithop_ncan2 in r1.\n      remember (compute_step lib (oterm (NCan ncan2) bs1)) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @has_value_like_except_S.\n      exists n; tcsp.\n    + simpl in r1; ginv.\n      exists k; sp.\n    + allsimpl; ginv.\n    + simpl in r1.\n      unfold on_success in r1.\n      remember (compute_step_lib lib abs2 bs1) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @has_value_like_except_S.\n      exists n; tcsp.\nQed.\n\nLemma has_value_like_except_k_lt {o} :\n  forall lib a k1 k2 (t : @NTerm o),\n    has_value_like_except_k lib a k1 t\n    -> k1 < k2\n    -> has_value_like_except_k lib a k2 t.\nProof.\n  unfold has_value_like_except_k; introv r l; exrepnd.\n  exists u; dands; auto.\n  pose proof (no_change_after_value_like lib t k1 u) as h.\n  repeat (autodimp h hyp); tcsp.\n  { unfold isvalue_like_except in r0; sp. }\n  pose proof (h (k2 - k1)) as hh.\n  assert (k2 - k1 + k1 = k2) as e by omega.\n  rw e in hh; auto.\nQed.\n\nLemma if_has_value_like_except_k_cbv_primarg {o} :\n  forall lib a k (t : @NTerm o) bs,\n    has_value_like_except_k lib a k (oterm (NCan NCbv) (bterm [] t :: bs))\n    -> {j : nat & j < k # has_value_like_except_k lib a j t}.\nProof.\n  induction k; introv r.\n\n  - allrw @has_value_like_except_0; repnd.\n    unfold isvalue_like_except in r; repnd.\n    inversion r0; sp.\n\n  - allrw @has_value_like_except_S; exrepnd.\n    destruct t as [v|op l].\n\n    { simpl in r1; ginv. }\n\n    dopid op as [can1|ncan1|exc1|mrk1|abs1] Case.\n\n    + Case \"Can\".\n      exists 0; dands; try omega.\n      rw @has_value_like_except_0; dands; eauto 3 with slow; simpl; sp.\n      unfold isvalue_like_except; simpl; dands; eauto 3 with slow; sp.\n\n    + Case \"NCan\".\n      rw @compute_step_ncan_ncan in r1.\n      remember (compute_step lib (oterm (NCan ncan1) l)) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @has_value_like_except_S; exists n; sp.\n\n    + Case \"Exc\".\n      allsimpl; ginv.\n      unfold has_value_like_except_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in r0; subst; tcsp.\n      exists 0; dands; try omega.\n      rw @has_value_like_except_0; dands; eauto 3 with slow.\n\n    + Case \"Mrk\".\n      allsimpl; ginv.\n      unfold has_value_like_except_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_primarg_marker in r0; subst.\n      unfold isvalue_like_except in r1; repnd.\n      inversion r0; tcsp.\n\n    + Case \"Abs\".\n      allsimpl.\n      unfold on_success in r1.\n      remember (compute_step_lib lib abs1 l) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @has_value_like_except_S; exists n; sp.\nQed.\n*)\n\n(*\nLemma isvalue_like_except_integer {o} :\n  forall a z, @isvalue_like_except o a (mk_integer z).\nProof.\n  introv; unfold isvalue_like_except; simpl; sp; eauto 3 with slow.\nQed.\nHint Resolve isvalue_like_except_integer : slow.\n\nLemma isvalue_like_except_uni {o} :\n  forall a n, @isvalue_like_except o a (mk_uni n).\nProof.\n  introv; unfold isvalue_like_except; simpl; sp; eauto 3 with slow.\nQed.\nHint Resolve isvalue_like_except_uni : slow.\n\nLemma if_has_value_like_except_k_force_int_bound {o} :\n  forall lib a v b k (t : @NTerm o),\n    has_value_like_except_k\n      lib a k\n      (force_int_bound v b t (uexc a))\n    -> {j : nat\n        & {u : NTerm\n           & reduces_in_atmost_k_steps lib t u j\n           # j < k\n           # isvalue_like_except a u\n           # ({z : Z & u = mk_integer z # Z.abs_nat z < b}[+]isexc u)\n       }}.\nProof.\n  induction k; introv r.\n\n  - allrw @has_value_like_except_0; repnd.\n    unfold isvalue_like_except in r; repnd.\n    inversion r0; sp.\n\n  - allrw @has_value_like_except_S; exrepnd.\n    destruct t as [v1|op1 bs1].\n    { simpl in r1; ginv. }\n    dopid op1 as [can1|ncan1|exc1|mrk1|abs1] Case.\n\n    + Case \"Can\".\n      simpl in r1; ginv.\n      unfold apply_bterm, lsubst in r0; allsimpl.\n      boolvar; fold_terms.\n      destruct k.\n\n      { allrw @has_value_like_except_0; repnd.\n        unfold isvalue_like_except in r0; repnd.\n        inversion r1; sp. }\n\n      allrw @has_value_like_except_S; exrepnd; allsimpl.\n      unfold on_success in r0.\n      fold_terms.\n      match goal with\n        | [ H : context[compute_step_comp ?a1 ?a2 ?a3 ?a4 ?a5 ?a6 ?a7] |- _ ] =>\n          remember (compute_step_comp a1 a2 a3 a4 a5 a6 a7)  as comp\n      end.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply compute_step_compop_success_can_can in Heqcomp.\n      exrepnd; subst; allsimpl; cpx; GC.\n      repndors; exrepnd; ginv.\n      allapply @get_int_from_cop_some; subst.\n\n      destruct k.\n\n      { allrw @has_value_like_except_0; repnd.\n        unfold isvalue_like_except in r1; repnd.\n        inversion r0; sp. }\n\n      allrw @has_value_like_except_S; exrepnd.\n      boolvar; allsimpl; ginv.\n\n      * destruct k.\n\n        { allrw @has_value_like_except_0; repnd.\n          unfold isvalue_like_except in r0; repnd.\n          inversion r1; sp. }\n\n        allrw @has_value_like_except_S; exrepnd.\n        allsimpl.\n        unfold compute_step_comp in r0; allsimpl; boolvar; ginv.\n\n        { exists 0 (@mk_integer o n1); dands; try omega; eauto 3 with slow.\n          - rw @reduces_in_atmost_k_steps_0; auto.\n          - left; exists n1; dands; auto; apply abs_of_neg; auto. }\n\n        { unfold has_value_like_except_k in r1; exrepnd.\n          apply reduces_in_atmost_k_steps_if_isvalue_like in r1; subst; tcsp.\n          unfold isvalue_like_except in r0; repnd; allsimpl; boolvar; allsimpl; ginv; tcsp.\n          destruct r0; sp. }\n\n      * unfold compute_step_comp in r1; allsimpl; boolvar; ginv.\n\n        { exists 0 (@mk_integer o n1); dands; try omega; eauto 3 with slow.\n          - rw @reduces_in_atmost_k_steps_0; auto.\n          - left; exists n1; dands; auto; apply abs_of_pos; auto. }\n\n        { unfold has_value_like_except_k in r0; exrepnd.\n          apply reduces_in_atmost_k_steps_if_isvalue_like in r0; subst; tcsp.\n          unfold isvalue_like_except in r1; repnd; allsimpl; boolvar; allsimpl; ginv; tcsp.\n          destruct r1; sp. }\n\n    + Case \"NCan\".\n      unfold force_int_bound in r1.\n      rw @compute_step_mk_cbv_ncan in r1.\n      remember (compute_step lib (oterm (NCan ncan1) bs1)) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n\n      apply IHk in r0; auto; exrepnd.\n\n      exists (S j) u; dands; auto; try omega.\n      rw @reduces_in_atmost_k_steps_S; eexists; eauto.\n\n    + Case \"Exc\".\n      allsimpl; ginv.\n      unfold has_value_like_except_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in r0; subst; tcsp.\n      allsimpl; boolvar; subst; try (complete (destruct r1; sp)); GC.\n      exists 0 (oterm (Exc exc1) bs1); dands; eauto 3 with slow; try omega.\n      rw @reduces_in_atmost_k_steps_0; auto.\n\n    + Case \"Mrk\".\n      allsimpl; ginv.\n      unfold has_value_like_except_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_primarg_marker in r0; subst.\n      unfold isvalue_like_except in r1; repnd.\n      inversion r0; sp.\n\n    + Case \"Abs\".\n      simpl in r1; unfold on_success in r1.\n      remember (compute_step_lib lib abs1 bs1) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n\n      apply IHk in r0; auto; exrepnd.\n      exists (S j) u; dands; auto; try omega.\n      rw @reduces_in_atmost_k_steps_S; eexists; eauto.\nQed.\n*)\n\nLemma if_has_value_like_k_force_int_bound {o} :\n  forall lib v b k (t : @NTerm o),\n    has_value_like_k\n      lib k\n      (force_int_bound v b t (mk_vbot v))\n    -> {j : nat\n        & {u : NTerm\n           & reduces_in_atmost_k_steps lib t u j\n           # j < k\n           # isvalue_like u\n           # ({z : Z & u = mk_integer z # Z.abs_nat z < b}[+]isexc u)\n       }}.\nProof.\n  induction k; introv r.\n\n  - allrw @has_value_like_0; repnd.\n    unfold isvalue_like in r; allsimpl; sp.\n\n  - allrw @has_value_like_S; exrepnd.\n    destruct t as [v1|f1|op1 bs1].\n\n    { simpl in r1; ginv. }\n\n    { csunf r1; allsimpl; ginv.\n      allunfold @apply_bterm; allsimpl; allrw @fold_subst.\n      pose proof (hasvalue_like_subst_less_bound_seq lib b v (mk_vbot v) f1) as h.\n      autodimp h hyp; tcsp.\n      unfold has_value_like_k, computes_to_val_like_in_max_k_steps in r0; exrepnd.\n      exists u; dands; eauto 3 with slow. }\n\n    dopid op1 as [can1|ncan1|exc1|abs1] Case.\n\n    + Case \"Can\".\n      csunf r1; simpl in r1; ginv.\n      unfold apply_bterm, lsubst in r0; allsimpl.\n      boolvar; fold_terms; repndors; tcsp;\n      allrw app_nil_r;\n      try (complete (match goal with\n                       | [ H : context[fresh_var ?l] |- _ ] =>\n                         let h := fresh \"h\" in\n                         pose proof (fresh_var_not_in l) as h;\n                       unfold all_vars in h;\n                       simpl in h;\n                       repeat (rw in_app_iff in h);\n                       repeat (rw not_over_or in h);\n                       repnd; allsimpl; tcsp\n                     end));\n      GC; allrw not_over_or; repnd; allsimpl; boolvar; tcsp; GC;\n      fold_terms.\n\n      { destruct k.\n\n        { allrw @has_value_like_0; repnd.\n          unfold isvalue_like in r0; allsimpl; sp. }\n\n        allrw @has_value_like_S; exrepnd; allsimpl.\n        csunf r0; allsimpl; unfold on_success in r0.\n        csunf r0; allsimpl.\n        dcwf h; allsimpl.\n        fold_terms.\n        match goal with\n          | [ H : context[compute_step_comp ?a1 ?a2 ?a3 ?a4 ?a5 ?a6 ?a7] |- _ ] =>\n            remember (compute_step_comp a1 a2 a3 a4 a5 a6 a7)  as comp\n        end.\n        symmetry in Heqcomp; destruct comp; ginv.\n        apply compute_step_compop_success_can_can in Heqcomp.\n        exrepnd; subst; allsimpl; cpx; GC.\n        allunfold @all_vars; allsimpl.\n        repndors; exrepnd; tcsp; GC; ginv.\n        allapply @get_param_from_cop_pki; subst.\n\n        destruct k.\n\n        { allrw @has_value_like_0; repnd.\n          unfold isvalue_like in r1; allsimpl; sp. }\n\n        allrw @has_value_like_S; exrepnd.\n        csunf r1; allsimpl.\n        boolvar; allsimpl; ginv.\n\n        * destruct k.\n\n          { allrw @has_value_like_0; repnd.\n            unfold isvalue_like in r0; allsimpl; sp. }\n\n          allrw @has_value_like_S; exrepnd.\n          allsimpl.\n          csunf r0; allsimpl.\n          dcwf h; allsimpl.\n          unfold compute_step_comp in r0; allsimpl; boolvar; ginv.\n\n          { exists 0 (@mk_integer o n1); dands; try omega; eauto 3 with slow.\n            - rw @reduces_in_atmost_k_steps_0; auto.\n            - left; exists n1; dands; auto; apply abs_of_neg; auto. }\n\n          { apply has_value_like_k_vbot in r1; tcsp. }\n\n        * dcwf h; allsimpl.\n          unfold compute_step_comp in r1; allsimpl; boolvar; ginv.\n\n        { exists 0 (@mk_integer o n1); dands; try omega; eauto 3 with slow.\n          - rw @reduces_in_atmost_k_steps_0; auto.\n          - left; exists n1; dands; auto; apply abs_of_pos; auto. }\n\n        { apply has_value_like_k_vbot in r0; tcsp. }\n      }\n\n      { destruct k.\n\n        { allrw @has_value_like_0; repnd.\n          unfold isvalue_like in r0; allsimpl; sp. }\n\n        allrw @has_value_like_S; exrepnd; allsimpl.\n        csunf r0; allsimpl; csunf r0; allsimpl.\n        dcwf h; allsimpl.\n        unfold on_success in r0.\n        fold_terms.\n        match goal with\n          | [ H : context[compute_step_comp ?a1 ?a2 ?a3 ?a4 ?a5 ?a6 ?a7] |- _ ] =>\n            remember (compute_step_comp a1 a2 a3 a4 a5 a6 a7)  as comp\n        end.\n        symmetry in Heqcomp; destruct comp; ginv.\n        apply compute_step_compop_success_can_can in Heqcomp.\n        exrepnd; subst; allsimpl; cpx; GC.\n        allunfold @all_vars; allsimpl.\n        repndors; exrepnd; tcsp; GC; ginv.\n        allapply @get_param_from_cop_pki; subst.\n\n        destruct k.\n\n        { allrw @has_value_like_0; repnd.\n          unfold isvalue_like in r1; allsimpl; sp. }\n\n        allrw @has_value_like_S; exrepnd.\n        csunf r1; allsimpl.\n        boolvar; allsimpl; ginv.\n\n        * destruct k.\n\n          { allrw @has_value_like_0; repnd.\n            unfold isvalue_like in r0; allsimpl; sp. }\n\n          allrw @has_value_like_S; exrepnd.\n          allsimpl.\n          csunf r0; allsimpl.\n          dcwf h; allsimpl.\n          unfold compute_step_comp in r0; allsimpl; boolvar; ginv.\n\n          { exists 0 (@mk_integer o n1); dands; try omega; eauto 3 with slow.\n            - rw @reduces_in_atmost_k_steps_0; auto.\n            - left; exists n1; dands; auto; apply abs_of_neg; auto. }\n\n          { apply has_value_like_k_vbot in r1; tcsp. }\n\n        * dcwf h; allsimpl.\n          unfold compute_step_comp in r1; allsimpl; boolvar; ginv.\n\n        { exists 0 (@mk_integer o n1); dands; try omega; eauto 3 with slow.\n          - rw @reduces_in_atmost_k_steps_0; auto.\n          - left; exists n1; dands; auto; apply abs_of_pos; auto. }\n\n        { apply has_value_like_k_vbot in r0; tcsp. }\n      }\n\n    + Case \"NCan\".\n      unfold force_int_bound in r1.\n      rw @compute_step_mk_cbv_ncan in r1.\n      remember (compute_step lib (oterm (NCan ncan1) bs1)) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n\n      apply IHk in r0; auto; exrepnd.\n\n      exists (S j) u; dands; auto; try omega.\n      rw @reduces_in_atmost_k_steps_S; eexists; eauto.\n\n    + Case \"Exc\".\n      csunf r1; allsimpl; ginv.\n      exists 0 (oterm Exc bs1); dands; eauto 3 with slow; try omega.\n      rw @reduces_in_atmost_k_steps_0; auto.\n\n    + Case \"Abs\".\n      csunf r1; simpl in r1; unfold on_success in r1; csunf r1; allsimpl.\n      remember (compute_step_lib lib abs1 bs1) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n\n      apply IHk in r0; auto; exrepnd.\n      exists (S j) u; dands; auto; try omega.\n      rw @reduces_in_atmost_k_steps_S; eexists; eauto.\nQed.\n\nLemma compute_step_force_int_bound {o} :\n  forall lib v b e z k (t u : @NTerm o),\n    closed e\n    -> compute_step lib (force_int_bound v b t e) = csuccess u\n    -> reduces_in_atmost_k_steps lib t (mk_integer z) k\n    -> Z.abs_nat z < b\n    -> reduces_to lib u (mk_integer z).\nProof.\n  destruct t as [v1|f1|op1 bs1];[allsimpl; ginv| |];\n  introv cl comp r l; ginv.\n\n  { apply computation3.reduces_in_atmost_k_steps_if_isvalue_like in r; eauto 3 with slow; ginv. }\n\n  dopid op1 as [can1|ncan2|exc1|abs1] Case.\n\n  - Case \"Can\".\n    simpl in comp; ginv.\n    apply reduces_in_atmost_k_steps_if_isvalue_like in r; tcsp.\n    inversion r; subst.\n    csunf comp; allsimpl; ginv.\n    unfold apply_bterm, lsubst; simpl; boolvar; fold_terms; GC;\n    try (complete (provefalse; sp)).\n    destruct (Z_lt_le_dec z 0) as [i|i].\n    + apply (reduces_to_if_split2\n               _ _ (mk_less\n                      (mk_minus (mk_integer z))\n                      (mk_nat b)\n                      (mk_integer z)\n                      e));\n      try csunf; simpl; boolvar; tcsp; try omega;\n      try (rw @lsubst_aux_trivial_cl_term2; auto).\n      apply (reduces_to_if_split2\n               _ _ (mk_less\n                      (mk_integer (- z))\n                      (mk_nat b)\n                      (mk_integer z)\n                      e));\n        try csunf; simpl; boolvar; tcsp; try omega.\n      apply reduces_to_if_step.\n      csunf; simpl.\n      dcwf h; allsimpl.\n      unfold compute_step_comp; simpl; boolvar; auto.\n      provefalse.\n      pose proof (Zabs.Zabs_nat_le (Z.of_nat b) (-z)) as kk.\n      autodimp kk hyp; try omega.\n      allrw Znat.Zabs2Nat.id.\n      destruct z; allsimpl; try omega.\n    + apply (reduces_to_if_split2\n               _ _ (mk_less\n                      (mk_integer z)\n                      (mk_nat b)\n                      (mk_integer z)\n                      e));\n      try csunf; simpl; boolvar; tcsp; try omega;\n      try (rw @lsubst_aux_trivial_cl_term2; auto).\n      apply reduces_to_if_step.\n      csunf; simpl.\n      dcwf h; allsimpl.\n      unfold compute_step_comp; simpl; boolvar; auto.\n      provefalse.\n      pose proof (Zabs.Zabs_nat_le (Z.of_nat b) z) as kk.\n      autodimp kk hyp; try omega.\n      allrw Znat.Zabs2Nat.id.\n      destruct z; allsimpl; try omega.\n\n  - Case \"NCan\".\n    destruct k.\n    + allrw @reduces_in_atmost_k_steps_0; ginv.\n    + allrw @reduces_in_atmost_k_steps_S; exrepnd.\n      unfold force_int_bound in comp.\n      rw @compute_step_mk_cbv_ncan in comp.\n      rw r1 in comp; ginv; clear r1.\n      pose proof (reduces_to_prinarg\n                    lib NCbv u0 (mk_integer z)\n                    [bterm [v] (less_bound b (mk_var v) e)]) as h.\n      repeat (autodimp h hyp); eauto 3 with slow.\n      eapply reduces_to_trans;[exact h|].\n      apply (reduces_to_if_split2\n               _ _ (less_bound b (mk_integer z) e)).\n      { csunf; simpl; unfold apply_bterm, lsubst; simpl; boolvar; tcsp;\n        try (complete (provefalse; sp));\n        repeat (rw @lsubst_aux_trivial_cl_term2; auto). }\n      destruct (Z_lt_le_dec z 0) as [i|i].\n      * apply (reduces_to_if_split2\n                 _ _ (mk_less\n                        (mk_minus (mk_integer z))\n                        (mk_nat b)\n                        (mk_integer z)\n                        e));\n        try csunf; simpl; boolvar; tcsp; try omega.\n        apply (reduces_to_if_split2\n                 _ _ (mk_less\n                        (mk_integer (- z))\n                        (mk_nat b)\n                        (mk_integer z)\n                        e));\n          try csunf; simpl; boolvar; tcsp; try omega.\n        apply reduces_to_if_step.\n        csunf; simpl.\n        dcwf q; allsimpl.\n        unfold compute_step_comp; simpl; boolvar; auto.\n        provefalse.\n        pose proof (Zabs.Zabs_nat_le (Z.of_nat b) (-z)) as kk.\n        autodimp kk hyp; try omega.\n        allrw Znat.Zabs2Nat.id.\n        destruct z; allsimpl; try omega.\n      * apply (reduces_to_if_split2\n                 _ _ (mk_less\n                        (mk_integer z)\n                        (mk_nat b)\n                        (mk_integer z)\n                        e));\n        try csunf; simpl; boolvar; tcsp; try omega.\n        apply reduces_to_if_step.\n        csunf; simpl.\n        dcwf q; allsimpl.\n        unfold compute_step_comp; simpl; boolvar; auto.\n        provefalse.\n        pose proof (Zabs.Zabs_nat_le (Z.of_nat b) z) as kk.\n        autodimp kk hyp; try omega.\n        allrw Znat.Zabs2Nat.id.\n        destruct z; allsimpl; try omega.\n\n  - Case \"Exc\".\n    csunf comp; allsimpl; ginv.\n    apply reduces_in_atmost_k_steps_if_isvalue_like in r; tcsp; ginv.\n\n  - Case \"Abs\".\n    destruct k.\n    + allrw @reduces_in_atmost_k_steps_0; ginv.\n    + allrw @reduces_in_atmost_k_steps_S; exrepnd.\n      unfold force_int_bound in comp.\n      rw @compute_step_mk_cbv_abs in comp.\n      csunf r1; allsimpl.\n      rw r1 in comp; ginv; clear r1.\n      pose proof (reduces_to_prinarg\n                    lib NCbv u0 (mk_integer z)\n                    [bterm [v] (less_bound b (mk_var v) e)]) as h.\n      repeat (autodimp h hyp); eauto 3 with slow.\n      eapply reduces_to_trans;[exact h|].\n      apply (reduces_to_if_split2\n               _ _ (less_bound b (mk_integer z) e)).\n      { csunf; simpl; unfold apply_bterm, lsubst; simpl; boolvar; tcsp;\n        try (complete (provefalse; sp));\n        repeat (rw @lsubst_aux_trivial_cl_term2; auto). }\n      destruct (Z_lt_le_dec z 0) as [i|i].\n      * apply (reduces_to_if_split2\n                 _ _ (mk_less\n                        (mk_minus (mk_integer z))\n                        (mk_nat b)\n                        (mk_integer z)\n                        e));\n        try csunf; simpl; boolvar; tcsp; try omega.\n        apply (reduces_to_if_split2\n                 _ _ (mk_less\n                        (mk_integer (- z))\n                        (mk_nat b)\n                        (mk_integer z)\n                        e));\n          try csunf; simpl; boolvar; tcsp; try omega.\n        apply reduces_to_if_step.\n        csunf; simpl.\n        dcwf q; allsimpl.\n        unfold compute_step_comp; simpl; boolvar; auto.\n        provefalse.\n        pose proof (Zabs.Zabs_nat_le (Z.of_nat b) (-z)) as kk.\n        autodimp kk hyp; try omega.\n        allrw Znat.Zabs2Nat.id.\n        destruct z; allsimpl; try omega.\n      * apply (reduces_to_if_split2\n                 _ _ (mk_less\n                        (mk_integer z)\n                        (mk_nat b)\n                        (mk_integer z)\n                        e));\n        try csunf; simpl; boolvar; tcsp; try omega.\n        apply reduces_to_if_step.\n        csunf; simpl.\n        dcwf q; allsimpl.\n        unfold compute_step_comp; simpl; boolvar; auto.\n        provefalse.\n        pose proof (Zabs.Zabs_nat_le (Z.of_nat b) z) as kk.\n        autodimp kk hyp; try omega.\n        allrw Znat.Zabs2Nat.id.\n        destruct z; allsimpl; try omega.\nQed.\n\nLemma compute_step_force_int_bound_exc {o} :\n  forall lib v b a (t u e : @NTerm o),\n    compute_step lib (force_int_bound v b t a) = csuccess u\n    -> reduces_to lib t e\n    -> isexc e\n    -> reduces_to lib u e.\nProof.\n  destruct t as [v1|f1|op1 bs1];[allsimpl; ginv| |];\n  introv comp r l; ginv.\n\n  { apply reduces_to_if_isvalue_like in r; eauto 3 with slow; subst; allsimpl; tcsp. }\n\n  dopid op1 as [can1|ncan2|exc1|abs1] Case.\n\n  - Case \"Can\".\n    apply reduces_to_if_isvalue_like in r; eauto 3 with slow; subst.\n    inversion l.\n\n  - Case \"NCan\".\n    apply reduces_to_split2 in r; dorn r; subst.\n    + inversion l.\n    + exrepnd.\n      unfold force_int_bound in comp.\n      rw @compute_step_mk_cbv_ncan in comp.\n      rw r1 in comp; ginv; clear r1.\n      pose proof (reduces_to_prinarg\n                    lib NCbv v0 e\n                    [bterm [v] (less_bound b (mk_var v) a)]) as h.\n      repeat (autodimp h hyp); eauto 3 with slow.\n      eapply reduces_to_trans;[exact h|].\n      apply isexc_implies2 in l; exrepnd; subst; eauto 3 with slow.\n\n  - Case \"Exc\".\n    csunf comp; allsimpl; ginv; auto.\n\n  - Case \"Abs\".\n    apply reduces_to_split2 in r; dorn r; subst.\n    + inversion l.\n    + exrepnd.\n      unfold force_int_bound in comp.\n      rw @compute_step_mk_cbv_abs in comp.\n      csunf r1; allsimpl; rw r1 in comp; ginv; clear r1.\n      pose proof (reduces_to_prinarg\n                    lib NCbv v0 e\n                    [bterm [v] (less_bound b (mk_var v) a)]) as h.\n      repeat (autodimp h hyp); eauto 3 with slow.\n      eapply reduces_to_trans;[exact h|].\n      apply isexc_implies2 in l; exrepnd; subst; eauto 3 with slow.\nQed.\n\nLemma lsubst_aux_vterm_single {o} :\n  forall v (t : @NTerm o),\n    lsubst_aux (vterm v) [(v, t)] = t.\nProof.\n  introv; simpl; boolvar; auto.\nQed.\n\n(*\nLemma compute_step_lsubst_aux_int {o} :\n  forall lib (t u : @NTerm o) v arg z,\n    reduces_to lib arg (mk_integer z)\n    -> compute_step lib (lsubst_aux t [(v, arg)]) = csuccess u\n    -> red_to_can lib u\n    -> {t' : NTerm\n        & {x : NVar\n        & !LIn x (bound_vars t)\n        # alpha_eq t (lsubst_aux t' [(x,mk_var v)])\n        # reduces_to\n            lib u\n            (lsubst_aux (lsubst_aux t' [(x,mk_integer z)]) [(v,arg)]) }}.\nProof.\n  nterm_ind t as [y|op bs ind] Case; introv r comp rtc.\n\n  - Case \"vterm\".\n    allsimpl; boolvar; allsimpl; ginv.\n    apply reduces_to_split2 in r; dorn r; subst; allsimpl; ginv.\n\n    + exists (@mk_var o y) y; dands; simpl; boolvar; simpl; eauto 3 with slow; tcsp.\n\n    + exrepnd.\n      rw r1 in comp; ginv.\n      exists (@mk_var o y) y; dands; simpl; boolvar; simpl; eauto 3 with slow; tcsp.\n\n  - Case \"oterm\".\n    dopid op as [can|ncan|exc|mrk|abs] SCase.\n\n    + SCase \"Can\".\n      allsimpl; ginv.\n      pose proof (ex_fresh_var (all_vars (oterm (Can can) bs))) as f; exrepnd.\n      unfold all_vars in f0; allsimpl; allrw in_app_iff; allrw not_over_or; repnd.\n      exists (oterm (Can can) bs) v0; dands; auto.\n\n      * rw @lsubst_aux_trivial_cl_term; auto; simpl.\n        rw disjoint_singleton_r; auto.\n\n      * rw (lsubst_aux_trivial_cl_term (oterm (Can can) bs)); eauto 3 with slow; simpl.\n        rw disjoint_singleton_r; auto.\n\n    + SCase \"NCan\".\n      destruct bs as [|b bs]; try (complete (allsimpl; ginv)).\n      destruct b as [l t].\n      destruct l; try (complete (allsimpl; ginv)).\n      destruct t as [v1|op1 bs1]; try (complete (allsimpl; ginv)).\n\n      * destruct (deq_nvar v1 v) as [i|i]; subst;\n        [|simpl in comp; boolvar; tcsp; ginv].\n        allrw @lsubst_aux_oterm.\n        allrw map_cons.\n        allrw @lsubst_aux_bterm_nil.\n        allrw @lsubst_aux_vterm_single.\n\n        destruct arg as [va|opa bsa]; try (complete (allsimpl; ginv)).\n        dopid opa as [cana|ncana|exca|mrka|absa] SSCase.\n\n        { SSCase \"Can\".\n          apply reduces_to_if_isvalue_like in r; eauto 3 with slow.\n          inversion r; subst; fold_terms; GC.\n          dopid_noncan ncan SSSCase; try (complete (allsimpl; ginv)).\n\n          - SSSCase \"NFix\".\n            allsimpl.\n            apply compute_step_fix_success in comp; repnd; subst.\n            unfold red_to_can in rtc; exrepnd.\n            apply iscan_implies in rtc0; exrepnd; subst.\n            apply reduces_to_split2 in rtc1; dorn rtc1; exrepnd; allsimpl; ginv.\n\n          - SSSCase \"NCbv\".\n            allsimpl.\n            apply compute_step_cbv_success in comp; exrepnd; subst.\n            destruct bs; allsimpl; ginv; boolvar.\n            destruct bs; allsimpl; ginv; boolvar.\n            destruct b as [l t]; allsimpl; boolvar; ginv; allsimpl; repdors; tcsp; subst.\n\n            * pose proof (ex_fresh_var (v :: bound_vars t ++ free_vars t)) as h; exrepnd.\n              allsimpl; allrw app_nil_r; allrw in_app_iff; allrw not_over_or; repnd.\n              exists (oterm (NCan NCbv) [nobnd (mk_var v0), bterm [v] t]) v0; dands; auto.\n\n              { allrw not_over_or; sp. }\n\n              { simpl; boolvar; repndors; tcsp; subst.\n                allrw not_over_or; repnd; GC.\n                rw @lsubst_aux_trivial_cl_term; auto; simpl.\n                rw disjoint_singleton_r; auto. }\n\n              { simpl; boolvar; repndors; tcsp; subst; GC; allrw not_over_or; repnd; tcsp; GC.\n                allsimpl.\n                rw (lsubst_aux_trivial_cl_term t); simpl; tcsp.\n                rw (lsubst_aux_trivial_cl_term t); simpl; tcsp;\n                [|allrw disjoint_singleton_r; auto].\n\n            *\nAbort.\n*)\n\nLemma reduces_to_lsubst_aux_int {o} :\n  forall lib z1 z2 (b : @NTerm o) v arg,\n    disjoint (bound_vars b) (free_vars arg)\n    -> reduces_to lib arg (mk_integer z1)\n    -> reduces_to lib (lsubst_aux b [(v,arg)]) (mk_integer z2)\n    -> reduces_to lib (lsubst_aux b [(v,mk_integer z1)]) (mk_integer z2).\nProof.\n  introv d r1 r2.\n  unfold reduces_to in r2; exrepnd.\n  revert dependent arg.\n  revert dependent v.\n  revert dependent b.\n  induction k; introv d compa compf.\n\n  - allrw @reduces_in_atmost_k_steps_0; ginv.\n    destruct b as [x|f|op bs]; allsimpl; ginv.\n\n    + boolvar; ginv.\n      apply reduces_to_if_isvalue_like in compa; eauto 3 with slow; ginv; eauto 3 with slow.\n\n    + boolvar; inversion compf;\n      subst; destruct bs; allsimpl; ginv; fold_terms; GC;\n      eauto 3 with slow.\n\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n\n(*\n    nterm_ind b as [x|op bs indb] Case; ginv.\n\n    + allsimpl; boolvar; allsimpl;\n      unfold subst, lsubst; simpl; boolvar; ginv.\n      assert (reduces_to lib arg (mk_integer z2)) as r.\n      { eapply reduces_to_if_split2; eauto 3 with slow. }\n      pose proof (reduces_to_eq_val_like lib arg (mk_integer z1) (mk_integer z2)) as h.\n      repeat (autodimp h hyp); eauto 3 with slow; ginv; eauto 3 with slow.\n\n    + dopid op as [can|ncan|exc|mrk|abs] Case.\n\n      * Case \"Can\".\n        allsimpl; ginv.\n        apply reduces_in_atmost_k_steps_if_isvalue_like in compf0; eauto 3 with slow.\n        inversion compf0; subst; destruct bs; allsimpl; ginv; eauto 3 with slow.\n\n      * Case \"NCan\".\n        destruct bs as [|b bs]; try (complete (allsimpl; ginv)).\n        destruct b as [l t].\n        destruct l; try (complete (allsimpl; ginv)).\n\n        destruct t as [x|op1 bs1]; try (complete (allsimpl; ginv)).\n\n        { destruct (deq_nvar x v) as [i|i]; subst;\n          [|simpl in compf1; boolvar; tcsp; ginv].\n          rw @lsubst_aux_oterm in compf1.\n          rw map_cons in compf1.\n          rw @lsubst_aux_bterm_nil in compf1.\n          rw @lsubst_aux_vterm_single in compf1.\n\n          destruct arg as [y|opa bsa]; try (complete (allsimpl; ginv)).\n          dopid opa as [cana|ncana|exca|mrka|absa] SCase.\n\n          - SCase \"Can\".\n            apply reduces_to_if_isvalue_like in compa; eauto 3 with slow.\n            inversion compa; subst; fold_terms; GC.\n            dopid_noncan ncan SSCase; try (complete (allsimpl; ginv)).\n\n            + SSCase \"NFix\".\n              allsimpl.\n              apply compute_step_fix_success in compf1; repnd; subst.\n              provefalse.\n              apply reduces_in_atmost_k_steps_implies_reduces_to in compf0.\n              apply reduces_to_split2 in compf0; dorn compf0; exrepnd; allsimpl; ginv.\n\n            + SSCase \"NCbv\".\n              simpl in compf1.\n              apply compute_step_cbv_success in compf1; exrepnd; subst.\n              destruct bs; allsimpl; ginv; boolvar.\n              destruct bs; allsimpl; ginv; boolvar.\n              destruct b as [l t]; allsimpl; boolvar; ginv; allsimpl; repdors; tcsp; subst.\n\n              * apply (reduces_to_if_split2\n                         _ _ (subst (lsubst_aux t []) v (mk_integer z1)));\n                eauto 3 with slow.\n\n              * allrw not_over_or; repnd; GC.\n                apply (reduces_to_if_split2\n                         _ _ (subst (lsubst_aux t [(v, mk_integer z1)]) v0 (mk_integer z1)));\n                  eauto 3 with slow.\n\n            + SSCase \"NSleep\".\n              allsimpl.\n              apply compute_step_sleep_success in compf1; exrepnd; subst.\n              apply reduces_in_atmost_k_steps_implies_reduces_to in compf0.\n              apply reduces_to_if_isvalue_like in compf0; eauto 3 with slow; ginv.\n\n            + SSCase \"NTUni\".\n              allsimpl.\n              apply compute_step_tuni_success in compf1; exrepnd; subst.\n              apply reduces_in_atmost_k_steps_implies_reduces_to in compf0.\n              apply reduces_to_if_isvalue_like in compf0; eauto 3 with slow; ginv.\n\n            + SSCase \"NMinus\".\n              allsimpl.\n              apply compute_step_minus_success in compf1; exrepnd; subst; ginv.\n              apply reduces_in_atmost_k_steps_implies_reduces_to in compf0.\n              apply reduces_to_if_isvalue_like in compf0; eauto 3 with slow; ginv.\n              destruct bs; allsimpl; ginv; fold_terms; GC; ginv.\n              boolvar; eauto 3 with slow.\n\n            + SSCase \"NTryCatch\".\n              allsimpl.\n              apply compute_step_try_success in compf1; exrepnd; subst; allsimpl.\n              apply reduces_in_atmost_k_steps_implies_reduces_to in compf0.\n              apply reduces_to_if_isvalue_like in compf0; eauto 3 with slow; ginv.\n              inversion compf0; subst; fold_terms; GC.\n              boolvar.\n              destruct bs; allsimpl; ginv.\n              destruct bs; allsimpl; ginv.\n              destruct b; allsimpl.\n              destruct l; allsimpl; cpx; allsimpl.\n              boolvar; allsimpl; ginv; repndors; tcsp; subst; eauto 3 with slow.\n\n            + SSCase \"NCompOp\".\n              destruct bs; try (complete (allsimpl; ginv)).\n              destruct b as [l t].\n              destruct l; destruct t as [v1|op1 bs1]; try (complete (allsimpl; ginv)).\n\n              * destruct (deq_nvar v1 v) as [i|i]; subst;\n                [|allsimpl; boolvar; tcsp; complete ginv].\n                rw map_cons in compf1.\n                rw @lsubst_aux_bterm_nil in compf1.\n                rw @lsubst_aux_vterm_single in compf1.\n                simpl in compf1.\n                apply compute_step_compop_success_can_can in compf1; exrepnd; GC.\n                destruct bs; try (complete (allsimpl; ginv)).\n                destruct bs; try (complete (allsimpl; ginv)).\n                destruct bs; try (complete (allsimpl; ginv)).\n                allsimpl; cpx; boolvar.\n                destruct b as [l3 t3]; allsimpl; ginv.\n                destruct l3; allsimpl; ginv.\n                destruct b0 as [l4 t4]; allsimpl; ginv.\n                destruct l4; allsimpl; ginv.\n                cpx; fold_terms; GC.\n                apply reduces_in_atmost_k_steps_implies_reduces_to in compf0.\n                repndors; exrepnd; subst; ginv; eauto 3 with slow.\n\n                { eapply reduces_to_if_split2; eauto; simpl.\n                  unfold compute_step_comp; simpl; auto. }\n\n                { eapply reduces_to_if_split2; eauto; simpl.\n                  unfold compute_step_comp; simpl; auto. }\n\n              * allrw map_cons.\n                allrw @lsubst_aux_bterm_nil.\n                dopid op1 as [can1|ncan1|exc1|mrk1|abs1] SSSSCase.\n\n                { SSSSCase \"Can\".\n                  simpl in compf1.\n                  apply compute_step_compop_success_can_can in compf1; exrepnd; GC.\n                  destruct bs1; allsimpl; cpx; GC.\n                  destruct bs; allsimpl; cpx; GC.\n                  destruct bs; allsimpl; cpx; GC.\n                  destruct bs; allsimpl; cpx; GC.\n                  allsimpl; cpx; boolvar.\n                  destruct b as [l3 t3]; allsimpl; ginv.\n                  destruct l3; allsimpl; ginv.\n                  destruct b0 as [l4 t4]; allsimpl; ginv.\n                  destruct l4; allsimpl; ginv.\n                  cpx; fold_terms; ginv; GC.\n                  apply reduces_in_atmost_k_steps_implies_reduces_to in compf0.\n                  repndors; exrepnd; subst; ginv; eauto 3 with slow.\n\n                  { eapply reduces_to_if_split2; eauto; simpl.\n                    allapply @get_int_from_cop_some; subst; allsimpl.\n                    unfold compute_step_comp; simpl; auto. }\n\n                  { eapply reduces_to_if_split2; eauto; simpl.\n                    allapply @get_int_from_cop_some; subst; allsimpl.\n                    unfold compute_step_comp; simpl; auto. }\n                }\n\n                { SSSSCase \"NCan\".\n                  rw @lsubst_aux_oterm in compf1.\n                  unfold_all_mk; allunfold @mk_integer.\n                  rw @compute_step_ncompop_ncan2 in compf1.\n                  match goal with\n                    | [ H : context[compute_step ?a1 ?a2] |- _ ] =>\n                      remember (compute_step a1 a2) as comp\n                  end.\n                  symmetry in Heqcomp; destruct comp; ginv.\n*)\n\nAbort.\n\n(*\nLemma reduces_to_apply_int {o} :\n  forall lib z1 z2 (f arg : @NTerm o),\n    reduces_to lib arg (mk_integer z1)\n    -> reduces_to lib (mk_apply f arg) (mk_integer z2)\n    -> reduces_to lib (mk_apply f (mk_integer z1)) (mk_integer z2).\nProof.\n  introv r1 r2.\n  unfold reduces_to in r2; exrepnd.\n  revert dependent arg.\n  revert dependent f.\n  induction k; introv compa compf.\n\n  - allrw @reduces_in_atmost_k_steps_0; ginv.\n\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    simpl in compf1.\n    destruct f as [v|f|op bs]; ginv.\n\n    { csunf compf1; allsimpl; ginv.\n\nXXXXXXXXXX\n\n      eapply reduces_to_trans;[|eauto].\n      eapply reduces_to_if_split2;[csunf; simpl; eauto|].\n      apply implies_eapply_red_aux; eauto 3 with slow.\n    }\n\n    dopid op as [can|ncan|exc|abs] Case.\n\n    + Case \"Can\".\n      csunf compf1; allsimpl.\n      apply compute_step_apply_success in compf1; exrepnd; subst.\n      fold_terms; ginv.\n\nAbort.\n*)\n\nLemma reduces_to_force_int_bound_app_z {o} :\n  forall lib v b e z (t f : @NTerm o),\n    closed e\n    -> !LIn v (free_vars f)\n    -> Z.abs_nat z < b\n    -> reduces_to lib t (mk_integer z)\n    -> reduces_to lib (force_int_bound_app v b t f e)\n                  (mk_apply f (mk_integer z)).\nProof.\n  introv cl ni l r.\n  pose proof (reduces_to_prinarg\n                lib NCbv\n                (force_int_bound v b t e)\n                (mk_integer z)\n                [bterm [v] (mk_apply f (mk_var v))]) as h.\n  fold_terms.\n  autodimp h hyp.\n\n  - pose proof (reduces_to_prinarg\n                  lib NCbv\n                  t\n                  (mk_integer z)\n                  [bterm [v] (less_bound b (mk_var v) e)]) as h.\n    fold_terms.\n    autodimp h hyp.\n\n    + eapply reduces_to_trans; eauto.\n      apply (reduces_to_if_split2\n               _ _ (less_bound b (mk_integer z) e)).\n\n      * csunf; simpl; unfold apply_bterm, lsubst; simpl; boolvar; auto;\n        try (complete (provefalse; sp));\n        repeat (rw @lsubst_aux_trivial_cl_term2; auto).\n\n      * destruct (Z_lt_le_dec z 0).\n\n        { apply (reduces_to_if_split2\n                   _ _ (mk_less (mk_minus (mk_integer z))\n                                (mk_nat b)\n                                (mk_integer z)\n                                e)); auto;\n          [csunf; simpl; boolvar; tcsp; try omega|].\n\n          apply (reduces_to_if_split2\n                   _ _ (mk_less (mk_integer (- z))\n                                (mk_nat b)\n                                (mk_integer z)\n                                e)); try csunf; auto.\n          apply reduces_to_if_step; simpl.\n          csunf; simpl.\n          dcwf q; allsimpl.\n          unfold compute_step_comp; simpl; boolvar; tcsp.\n          pose proof (Zabs.Zabs_nat_le (Z.of_nat b) (- z)) as k.\n          autodimp k hyp; try omega.\n          allrw Znat.Zabs2Nat.id.\n          destruct z; allsimpl; try omega. }\n\n        { apply (reduces_to_if_split2\n                   _ _ (mk_less (mk_integer z)\n                                (mk_nat b)\n                                (mk_integer z)\n                                e)); auto;\n          [csunf; simpl; boolvar; tcsp; try omega|].\n          apply reduces_to_if_step; simpl.\n          csunf; simpl.\n          dcwf q; allsimpl.\n          unfold compute_step_comp; simpl; boolvar; tcsp.\n          pose proof (Zabs.Zabs_nat_le (Z.of_nat b) z) as k.\n          autodimp k hyp; try omega.\n          allrw Znat.Zabs2Nat.id.\n          destruct z; allsimpl; try omega. }\n\n  - eapply reduces_to_trans; eauto.\n    apply reduces_to_if_step; simpl.\n    csunf; simpl.\n    unfold apply_bterm, lsubst; simpl; boolvar; tcsp;\n    try (complete (provefalse; sp)).\n\n    rw @lsubst_aux_trivial_cl_term; auto; simpl.\n    rw disjoint_singleton_r; auto.\nQed.\n\nLemma differ3_alpha_integer {o} :\n  forall b f g z (t : @NTerm o),\n    differ3_alpha b f g (mk_integer z) t\n    -> t = mk_integer z.\nProof.\n  introv d.\n  unfold differ3_alpha in d; exrepnd.\n  inversion d0; subst; allsimpl; cpx; fold_terms.\n  inversion d1; subst; allsimpl; cpx.\n  inversion d2; allsimpl; cpx.\nQed.\n\nLemma differ3_alpha_exc {o} :\n  forall b f g (e t : @NTerm o),\n    differ3_alpha b f g e t\n    -> isexc e\n    -> isexc t.\nProof.\n  introv d i.\n  unfold differ3_alpha in d; exrepnd.\n  apply isexc_implies2 in i; exrepnd; subst.\n  inversion d0; subst; allsimpl; cpx; fold_terms.\n  inversion d1; subst; allsimpl; cpx.\n  inversion d2; allsimpl; subst; boolvar; subst; tcsp.\nQed.\n\n(*\nLemma differ3_alpha_exc {o} :\n  forall x b f g (e t : @NTerm o),\n    differ3_alpha b f g e t\n    -> isnexc x e\n    -> isnexc x t.\nProof.\n  introv d i.\n  unfold differ3_alpha in d; exrepnd.\n  apply isnexc_implies in i; exrepnd; subst.\n  inversion d0; subst; allsimpl; cpx; fold_terms.\n  inversion d1; subst; allsimpl; cpx.\n  inversion d2; allsimpl; subst; boolvar; subst; tcsp.\nQed.\n*)\n\n(*\nLemma isvalue_like_except_can {o} :\n  forall a c (bs : list (@BTerm o)), @isvalue_like_except o a (oterm (Can c) bs).\nProof.\n  introv; unfold isvalue_like_except; simpl; sp; eauto 3 with slow.\nQed.\nHint Resolve isvalue_like_except_can : slow.\n*)\n\n(*\nLemma isvalue_like_except_exc {o} :\n  forall a e (bs : list (@BTerm o)),\n    !LIn a (get_utokens_en e)\n    -> isvalue_like_except a (oterm (Exc e) bs).\nProof.\n  introv; unfold isvalue_like_except; simpl; sp; eauto 3 with slow.\n  boolvar; tcsp.\n  destruct e; ginv; allsimpl; tcsp.\nQed.\nHint Resolve isvalue_like_except_exc : slow.\n*)\n\n(*\nLemma if_has_value_like_except_k_ncan_primarg {o} :\n  forall lib a ncan k (t : @NTerm o) bs,\n    !LIn a (get_utokens_nc ncan)\n    -> has_value_like_except_k lib a k (oterm (NCan ncan) (bterm [] t :: bs))\n    -> {j : nat & j < k # has_value_like_except_k lib a j t}.\nProof.\n  induction k; introv ni r.\n\n  - allrw @has_value_like_except_0.\n    unfold isvalue_like_except in r; repnd.\n    inversion r0; tcsp.\n\n  - allrw @has_value_like_except_S; exrepnd.\n    destruct t as [v|op l].\n\n    { simpl in r1; ginv. }\n\n    dopid op as [can1|ncan1|exc1|mrk1|abs1] Case.\n\n    + Case \"Can\".\n      exists 0; dands; try omega.\n      rw @has_value_like_except_0; eauto 3 with slow.\n\n    + Case \"NCan\".\n      rw @compute_step_ncan_ncan in r1.\n      remember (compute_step lib (oterm (NCan ncan1) l)) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply IHk in r0; exrepnd; auto.\n      exists (S j); dands; try omega.\n      rw @has_value_like_except_S.\n      exists n; sp.\n\n    + Case \"Exc\".\n      allsimpl.\n      apply compute_step_catch_success in r1.\n      dorn r1; exrepnd; subst; allsimpl.\n\n      * exists 0; dands; try omega.\n        rw @has_value_like_except_0; eauto 3 with slow.\n\n      * exists 0; dands; try omega.\n        unfold has_value_like_except_k in r0; exrepnd.\n        apply reduces_in_atmost_k_steps_if_isvalue_like in r0; eauto 3 with slow; subst.\n        unfold isvalue_like_except in r1; repnd; allsimpl; boolvar; tcsp;\n        try (complete (destruct r1; sp)); GC.\n        rw @has_value_like_except_0; eauto 3 with slow.\n        apply isvalue_like_except_exc; simpl.\n        destruct exc1; allsimpl; tcsp.\n        intro j; dorn j; tcsp; subst; sp.\n\n    + Case \"Mrk\".\n      allsimpl; ginv.\n      unfold has_value_like_except_k in r0; exrepnd.\n      apply reduces_in_atmost_k_steps_primarg_marker in r0; subst.\n      unfold isvalue_like_except in r1; repnd.\n      inversion r0; sp.\n\n    + Case \"Abs\".\n      allsimpl.\n      unfold on_success in r1.\n      remember (compute_step_lib lib abs1 l) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply IHk in r0; exrepnd; auto.\n      exists (S j); dands; try omega.\n      rw @has_value_like_except_S.\n      exists n; sp.\nQed.\n*)\n\nLemma differ3_alpha_mk_atom_eq {o} :\n  forall b f g (a1 a2 b1 b2 c1 c2 d1 d2 : @NTerm o),\n    differ3_alpha b f g a1 a2\n    -> differ3_alpha b f g b1 b2\n    -> differ3_alpha b f g c1 c2\n    -> differ3_alpha b f g d1 d2\n    -> differ3_alpha b f g (mk_atom_eq a1 b1 c1 d1) (mk_atom_eq a2 b2 c2 d2).\nProof.\n  introv da1 da2 da3 da4.\n  allunfold @differ3_alpha; exrepnd.\n  exists (mk_atom_eq u6 u4 u0 u1) (mk_atom_eq u7 u5 u3 u2); dands; auto.\n  - apply alpha_eq_oterm_combine; simpl; dands; auto.\n    introv i; repndors; cpx; auto; apply alphaeqbt_nilv2; auto.\n  - apply alpha_eq_oterm_combine; simpl; dands; auto.\n    introv i; repndors; cpx; auto; apply alphaeqbt_nilv2; auto.\n  - constructor; simpl; auto.\n    introv i; repndors; cpx; constructor; auto.\nQed.\nHint Resolve differ3_alpha_mk_atom_eq : slow.\n\nLemma differ3_alpha_mk_exception {o} :\n  forall b f g (a1 a2 b1 b2 : @NTerm o),\n    differ3_alpha b f g a1 a2\n    -> differ3_alpha b f g b1 b2\n    -> differ3_alpha b f g (mk_exception a1 b1) (mk_exception a2 b2).\nProof.\n  introv da1 da2.\n  allunfold @differ3_alpha; exrepnd.\n  exists (mk_exception u0 u1) (mk_exception u3 u2); dands; auto.\n  - apply alpha_eq_oterm_combine; simpl; dands; auto.\n    introv i; repndors; cpx; auto; apply alphaeqbt_nilv2; auto.\n  - apply alpha_eq_oterm_combine; simpl; dands; auto.\n    introv i; repndors; cpx; auto; apply alphaeqbt_nilv2; auto.\n  - constructor; simpl; auto.\n    introv i; repndors; cpx; constructor; auto.\nQed.\nHint Resolve differ3_alpha_mk_exception : slow.\n\nLemma differ3_preserves_isvalue_like {o} :\n  forall b f g (t1 t2 : @NTerm o),\n    differ3 b f g t1 t2\n    -> isvalue_like t1\n    -> isvalue_like t2.\nProof.\n  introv d ivl.\n  allunfold @isvalue_like; exrepnd.\n  repndors;[left|right].\n  - apply iscan_implies in ivl; repndors; exrepnd; subst;\n    inversion d; subst; eauto 3 with slow.\n  - apply isexc_implies2 in ivl; exrepnd; subst.\n    inversion d; subst; eauto 3 with slow.\nQed.\n\nLemma differ3_alpha_mk_fresh {o} :\n  forall b f g v (t1 t2 : @NTerm o),\n    !LIn v (free_vars f)\n    -> !LIn v (free_vars g)\n    -> differ3_alpha b f g t1 t2\n    -> differ3_alpha b f g (mk_fresh v t1) (mk_fresh v t2).\nProof.\n  introv ni1 ni2 d.\n  allunfold @differ3_alpha; exrepnd.\n  exists (mk_fresh v u1) (mk_fresh v u2); dands;\n  try (apply implies_alpha_eq_mk_fresh; eauto 3 with slow).\n  constructor; simpl; auto; introv i; repndors; cpx.\n  constructor; auto; apply disjoint_singleton_l; auto.\nQed.\nHint Resolve differ3_alpha_mk_fresh : slow.\n\nDefinition differ3_b_alpha {o} (b : nat) f g (b1 b2 : @BTerm o) :=\n  {u1 : BTerm\n   & {u2 : BTerm\n      & alpha_eq_bterm b1 u1\n      # alpha_eq_bterm b2 u2\n      # differ3_b b f g u1 u2}}.\n\nDefinition differ3_bs_alpha {o} b f g (bs1 bs2 : list (@BTerm o)) :=\n  br_bterms (differ3_b_alpha b f g) bs1 bs2.\n\nLemma differ3_bterms_nil {o} :\n  forall b f g, @differ3_bterms o b f g [] [].\nProof.\n  unfold differ3_bterms, br_bterms, br_list; simpl; sp.\nQed.\nHint Resolve differ3_bterms_nil : slow.\n\nLemma differ3_bterms_cons_if {o} :\n  forall b f g (b1 b2 : @BTerm o) bs1 bs2,\n    differ3_b b f g b1 b2\n    -> differ3_bterms b f g bs1 bs2\n    -> differ3_bterms b f g (b1 :: bs1) (b2 :: bs2).\nProof.\n  introv d1 d2; apply differ3_bterms_cons; sp.\nQed.\nHint Resolve differ3_bterms_cons_if : slow.\n\nLemma implies_differ3_alpha_oterm {o} :\n  forall b f g op (bs1 bs2 : list (@BTerm o)),\n    differ3_bs_alpha b f g bs1 bs2\n    -> differ3_alpha b f g (oterm op bs1) (oterm op bs2).\nProof.\n  introv diff.\n  unfold differ3_bs_alpha, br_bterms, br_list in diff; repnd.\n\n  assert {bs1' : list BTerm\n          & {bs2' : list BTerm\n          & alpha_eq_bterms bs1 bs1'\n          # alpha_eq_bterms bs2 bs2'\n          # differ3_bterms b f g bs1' bs2'}} as hbs.\n  { revert dependent bs2.\n    induction bs1; introv len imp; destruct bs2; allsimpl; cpx; GC.\n    - exists ([] : list (@BTerm o)) ([] : list (@BTerm o)); dands; eauto 3 with slow.\n    - pose proof (imp a b0) as h; autodimp h hyp.\n      pose proof (IHbs1 bs2) as k; repeat (autodimp k hyp).\n      exrepnd.\n      unfold differ3_b_alpha in h; exrepnd.\n      exists (u1 :: bs1') (u2 :: bs2'); dands; eauto 3 with slow. }\n\n  exrepnd.\n  applydup @alpha_eq_bterms_implies_same_length in hbs0.\n  applydup @alpha_eq_bterms_implies_same_length in hbs2.\n  exists (oterm op bs1') (oterm op bs2'); dands; auto.\n\n  - apply alpha_eq_oterm_combine; dands; tcsp.\n    introv i; apply hbs0; auto.\n\n  - apply alpha_eq_oterm_combine; dands; tcsp.\n    introv i; apply hbs2; auto.\n\n  - constructor; try omega.\n    introv i; apply hbs1; auto.\nQed.\n\nLemma differ3_alpha_pushdown_fresh_isvalue_like {o} :\n  forall b f g v (t1 t2 : @NTerm o),\n    !LIn v (free_vars f)\n    -> !LIn v (free_vars g)\n    -> isvalue_like t1\n    -> differ3 b f g t1 t2\n    -> differ3_alpha b f g (pushdown_fresh v t1) (pushdown_fresh v t2).\nProof.\n  introv nif nig ivl d.\n  destruct t1 as [v1|f1|op1 bs1].\n  - inversion d; allsimpl; subst; allsimpl; eauto 3 with slow.\n  - inversion d; allsimpl; subst; allsimpl; eauto 3 with slow.\n  - inversion d as [? ? d1 d2|?|?|? ? ? len imp d1]; subst; allsimpl; fold_terms; clear d.\n    + unfold isvalue_like in ivl; repndors; inversion ivl.\n    + apply implies_differ3_alpha_oterm.\n      unfold differ3_bs_alpha, br_bterms, br_list.\n      allrw @length_mk_fresh_bterms; dands; auto.\n      introv i.\n      unfold mk_fresh_bterms in i; allrw <- @map_combine; allrw in_map_iff; exrepnd; cpx; allsimpl.\n      applydup imp in i1.\n      destruct a0 as [l1 t1].\n      destruct a as [l2 t2].\n      inversion i0 as [? ? ? d]; subst; clear i0.\n      simpl.\n      unfold maybe_new_var; boolvar.\n\n      * pose proof (ex_fresh_var (all_vars t1 ++ all_vars t2 ++ all_vars f ++ all_vars g)) as fv; exrepnd.\n        allrw in_app_iff; allrw not_over_or; repnd.\n        exists (bterm l2 (mk_fresh v0 t1)) (bterm l2 (mk_fresh v0 t2)).\n        dands; auto.\n\n        { apply alpha_eq_bterm_congr.\n          apply (implies_alpha_eq_mk_fresh_sub v0); allrw in_app_iff; tcsp.\n          repeat (rw @lsubst_trivial3); allsimpl; auto.\n          - introv i; repndors; tcsp; cpx; allsimpl; allrw disjoint_singleton_l.\n            dands; auto.\n          - introv i; repndors; tcsp; cpx; allsimpl; allrw disjoint_singleton_l.\n            dands; auto.\n            apply newvar_prop. }\n\n        { apply alpha_eq_bterm_congr.\n          apply (implies_alpha_eq_mk_fresh_sub v0); allrw in_app_iff; tcsp.\n          repeat (rw @lsubst_trivial3); allsimpl; auto.\n          - introv i; repndors; tcsp; cpx; allsimpl; allrw disjoint_singleton_l.\n            dands; auto.\n          - introv i; repndors; tcsp; cpx; allsimpl; allrw disjoint_singleton_l.\n            dands; auto.\n            apply newvar_prop. }\n\n        { constructor; auto; constructor; simpl; auto.\n          introv i; repndors; cpx.\n          constructor; allrw disjoint_singleton_l; auto. }\n\n      * exists (bterm l2 (mk_fresh v t1)) (bterm l2 (mk_fresh v t2)).\n        dands; auto.\n        constructor; auto; constructor; auto.\n        introv i; allsimpl; repndors; cpx.\n        constructor; allrw disjoint_singleton_l; auto.\nQed.\n\nLemma differ3_preserves_isnoncan_like {o} :\n  forall (b : nat) f g (t1 t2 : @NTerm o),\n    differ3 b f g t1 t2\n    -> isnoncan_like t1\n    -> isnoncan_like t2.\nProof.\n  introv d isn.\n  allunfold @isnoncan_like; exrepnd.\n  repndors;[left|right].\n  - apply isnoncan_implies in isn; exrepnd; subst.\n    inversion d; subst; eauto 3 with slow.\n    unfold force_int_bound_app, mk_cbv; eauto 3 with slow.\n  - apply isabs_implies in isn; exrepnd; subst.\n    inversion d; subst; eauto 3 with slow.\nQed.\n\nLemma differ3_alpha_l {o} :\n  forall b f g (t1 t2 t3 : @NTerm o),\n    alpha_eq t1 t2\n    -> differ3_alpha b f g t2 t3\n    -> differ3_alpha b f g t1 t3.\nProof.\n  introv aeq d.\n  allunfold @differ3_alpha; exrepnd.\n  exists u1 u2; dands; eauto 3 with slow.\nQed.\n\nLemma differ3_alpha_r {o} :\n  forall b f g (t1 t2 t3 : @NTerm o),\n    differ3_alpha b f g t1 t2\n    -> alpha_eq t2 t3\n    -> differ3_alpha b f g t1 t3.\nProof.\n  introv aeq d.\n  allunfold @differ3_alpha; exrepnd.\n  exists u1 u2; dands; eauto 3 with slow.\nQed.\n\nLemma in_bound_vars_utok_sub {o} :\n  forall v (t : @NTerm o) sub,\n    LIn (v,t) sub\n    -> subset (bound_vars t) (bound_vars_utok_sub sub).\nProof.\n  induction sub; introv i; allsimpl; tcsp.\n  destruct a; repndors; cpx; eauto 3 with slow.\nQed.\n\nLemma in_free_vars_utok_sub {o} :\n  forall v (t : @NTerm o) sub,\n    LIn (v,t) sub\n    -> subset (free_vars t) (free_vars_utok_sub sub).\nProof.\n  induction sub; introv i; allsimpl; tcsp.\n  destruct a; repndors; cpx; eauto 3 with slow.\nQed.\n\nLemma differ3_subst_utokens_aux {o} :\n  forall b f g (t1 t2 : @NTerm o) sub,\n    disjoint (bound_vars t1) (free_vars_utok_sub sub)\n    -> disjoint (bound_vars t2) (free_vars_utok_sub sub)\n    -> disjoint (free_vars f) (bound_vars_utok_sub sub)\n    -> disjoint (free_vars g) (bound_vars_utok_sub sub)\n    -> disjoint (get_utokens f) (utok_sub_dom sub)\n    -> disjoint (get_utokens g) (utok_sub_dom sub)\n    -> differ3 b f g t1 t2\n    -> differ3 b f g (subst_utokens_aux t1 sub) (subst_utokens_aux t2 sub).\nProof.\n  nterm_ind t1 as [v1|f1|op1 bs1 ind1] Case; introv disj1 disj2 dff dfg duf dug d.\n\n  - Case \"vterm\".\n    inversion d; subst; allsimpl; eauto 3 with slow.\n\n  - Case \"sterm\".\n    inversion d; subst; allsimpl; eauto 3 with slow.\n\n  - Case \"oterm\".\n    inversion d as [? ? ? ? ? ni1 ni2 d1 a1 a2|?|?|? ? ? len1 imp1]; subst; clear d.\n\n    + allsimpl; allrw app_nil_r; fold_terms.\n      allrw disjoint_app_l; allrw disjoint_cons_l; repnd.\n      constructor; auto.\n\n      * pose proof (ind1 (force_int_bound v b t1 (mk_vbot v)) []) as q; clear ind1; autodimp q hyp.\n        pose proof (q (force_int_bound v b t0 (mk_vbot v)) sub) as ih; clear q; allsimpl.\n        allrw disjoint_app_l; allrw disjoint_cons_l.\n        repeat (autodimp ih hyp).\n\n        { constructor; simpl; auto.\n          introv i; repndors; cpx; tcsp.\n          - constructor; auto.\n          - constructor; allrw disjoint_singleton_l; auto.\n            constructor; simpl; auto.\n            introv i; repndors; cpx; tcsp; constructor; auto; constructor; simpl; auto;\n            introv i; repndors; cpx; tcsp; constructor; auto; constructor; simpl; auto;\n            introv i; repndors; cpx; tcsp; constructor; auto; allrw disjoint_singleton_l; auto.\n        }\n\n        { inversion ih as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear ih.\n          pose proof (imp (bterm [] (subst_utokens_aux t1 sub)) (bterm [] (subst_utokens_aux t0 sub))) as q.\n          autodimp q hyp.\n          inversion q; auto.\n        }\n\n      * rw @trivial_subst_utokens_aux; auto.\n        apply alphaeq_preserves_utokens in a1; rw <- a1; auto.\n\n      * rw @trivial_subst_utokens_aux; auto.\n        apply alphaeq_preserves_utokens in a2; rw <- a2; auto.\n\n    + allrw @subst_utokens_aux_oterm; allsimpl.\n      remember (get_utok op1) as guo1; symmetry in Heqguo1; destruct guo1.\n\n      * unfold subst_utok.\n        remember (utok_sub_find sub g0) as sf; symmetry in Heqsf; destruct sf; eauto 3 with slow.\n        { apply utok_sub_find_some in Heqsf.\n          apply differ3_refl; auto; apply in_bound_vars_utok_sub in Heqsf; eauto 3 with slow. }\n        constructor; allrw map_length; auto.\n        introv i; allrw <- @map_combine; allrw in_map_iff; exrepnd; cpx; allsimpl.\n        applydup imp1 in i1; applydup in_combine in i1; repnd.\n        disj_flat_map.\n        destruct a0 as [l1 u1].\n        destruct a as [l2 u2].\n        allsimpl; allrw disjoint_app_l; repnd.\n        inversion i0 as [? ? ? d1]; subst; clear i0.\n        constructor; auto.\n\n        pose proof (ind1 u1 l2) as q; autodimp q hyp.\n\n      * constructor; allrw map_length; auto.\n        introv i; allrw <- @map_combine; allrw in_map_iff; exrepnd; cpx; allsimpl.\n        applydup imp1 in i1; applydup in_combine in i1; repnd.\n        disj_flat_map.\n        destruct a0 as [l1 u1].\n        destruct a as [l2 u2].\n        allsimpl; allrw disjoint_app_l; repnd.\n        inversion i0 as [? ? ? d1]; subst; clear i0.\n        constructor; auto.\n\n        pose proof (ind1 u1 l2) as q; autodimp q hyp.\nQed.\n\nLemma differ3_alpha_subst_utokens {o} :\n  forall b f g (t1 t2 : @NTerm o) sub,\n    disjoint (free_vars f) (bound_vars_utok_sub sub)\n    -> disjoint (free_vars g) (bound_vars_utok_sub sub)\n    -> disjoint (get_utokens f) (utok_sub_dom sub)\n    -> disjoint (get_utokens g) (utok_sub_dom sub)\n    -> differ3_alpha b f g t1 t2\n    -> differ3_alpha b f g (subst_utokens t1 sub) (subst_utokens t2 sub).\nProof.\n  introv disj1 disj2 disj3 disj4 d.\n  unfold differ3_alpha in d; exrepnd.\n\n  eapply differ3_alpha_l;[eapply alpha_eq_subst_utokens_same;exact d0|].\n  eapply differ3_alpha_r;[|apply alpha_eq_sym;eapply alpha_eq_subst_utokens_same;exact d2].\n  clear dependent t1.\n  clear dependent t2.\n\n  pose proof (differ3_change_bound_vars\n                b f g (free_vars_utok_sub sub)\n                u1 u2 d1) as d; exrepnd.\n  rename u0 into t1.\n  rename u3 into t2.\n\n  eapply differ3_alpha_l;[eapply alpha_eq_subst_utokens_same;exact d3|].\n  eapply differ3_alpha_r;[|apply alpha_eq_sym;eapply alpha_eq_subst_utokens_same;exact d4].\n  clear dependent u1.\n  clear dependent u2.\n\n  pose proof (unfold_subst_utokens sub t1) as h; exrepnd.\n  pose proof (unfold_subst_utokens sub t2) as k; exrepnd.\n  rename t' into u1.\n  rename t'0 into u2.\n  rw h0; rw k0.\n\n  eapply differ3_alpha_l;[apply (alpha_eq_subst_utokens_aux u1 t1 sub sub); eauto 3 with slow|].\n  eapply differ3_alpha_r;[|apply alpha_eq_sym;apply (alpha_eq_subst_utokens_aux u2 t2 sub sub); eauto 3 with slow].\n\n  apply differ3_implies_differ3_alpha.\n  apply differ3_subst_utokens_aux; auto.\nQed.\n\nLemma wf_force_int_bound_app {o} :\n  forall v b (t : @NTerm o) g u,\n    wf_term (force_int_bound_app v b t g u)\n            <=> (wf_term t # wf_term g # wf_term u).\nProof.\n  introv.\n  unfold force_int_bound_app.\n  rw <- @wf_cbv_iff.\n  rw @wf_force_int_bound.\n  rw <- @wf_apply_iff.\n  split; sp.\nQed.\n\nLemma differ3_alpha_mk_eapply {o} :\n  forall b f g (a1 a2 b1 b2 : @NTerm o),\n    differ3_alpha b f g a1 a2\n    -> differ3_alpha b f g b1 b2\n    -> differ3_alpha b f g (mk_eapply a1 b1) (mk_eapply a2 b2).\nProof.\n  introv da1 da2.\n  allunfold @differ3_alpha; exrepnd.\n  exists (mk_eapply u0 u1) (mk_eapply u3 u2); dands; auto.\n  - apply alpha_eq_oterm_combine; simpl; dands; auto.\n    introv i; repndors; cpx; auto; apply alphaeqbt_nilv2; auto.\n  - apply alpha_eq_oterm_combine; simpl; dands; auto.\n    introv i; repndors; cpx; auto; apply alphaeqbt_nilv2; auto.\n  - constructor; simpl; auto.\n    introv i; repndors; cpx; constructor; auto.\nQed.\n\nLemma differ3_mk_eapply {o} :\n  forall b f g (a1 a2 b1 b2 : @NTerm o),\n    differ3 b f g a1 a2\n    -> differ3 b f g b1 b2\n    -> differ3 b f g (mk_eapply a1 b1) (mk_eapply a2 b2).\nProof.\n  introv da1 da2.\n  constructor; simpl; auto.\n  introv i; repndors; cpx; constructor; auto.\nQed.\n\nLemma differ3_preserves_iscan {o} :\n  forall b f g (t1 t2 : @NTerm o),\n    differ3 b f g t1 t2\n    -> iscan t1\n    -> iscan t2.\nProof.\n  introv diff isc.\n  apply iscan_implies in isc; repndors; exrepnd; subst;\n  inversion diff; subst; simpl; auto.\nQed.\n\nLemma differ3_exception_implies {o} :\n  forall b f g (a e t : @NTerm o),\n    differ3 b f g (mk_exception a e) t\n    -> {a' : NTerm\n        & {e' : NTerm\n        & t = mk_exception a' e'\n        # differ3 b f g a a'\n        # differ3 b f g e e' }}.\nProof.\n  introv d.\n  inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; cpx; clear d; allsimpl.\n\n  pose proof (imp (nobnd a) x) as d1; autodimp d1 hyp.\n  pose proof (imp (nobnd e) y) as d2; autodimp d2 hyp.\n  clear imp.\n\n  inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n  inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n  fold_terms.\n\n  eexists; eexists; dands; eauto.\nQed.\n\nLemma differ3_lam_implies {o} :\n  forall b f g v a (t : @NTerm o),\n    differ3 b f g (mk_lam v a) t\n    -> {a' : NTerm\n        & t = mk_lam v a'\n        # differ3 b f g a a' }.\nProof.\n  introv d.\n  inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; cpx; clear d; allsimpl.\n\n  pose proof (imp (bterm [v] a) x) as d1; autodimp d1 hyp.\n  clear imp.\n\n  inversion d1 as [? ? ? df2 dg2 d2]; subst; clear d1.\n  fold_terms.\n\n  eexists; eexists; dands; eauto.\nQed.\n\nLemma differ3_alpha_mk_lam {o} :\n  forall b f g v (t1 t2 : @NTerm o),\n    !LIn v (free_vars f)\n    -> !LIn v (free_vars g)\n    -> differ3_alpha b f g t1 t2\n    -> differ3_alpha b f g (mk_lam v t1) (mk_lam v t2).\nProof.\n  introv ni1 ni2 d.\n  allunfold @differ3_alpha; exrepnd.\n  exists (mk_lam v u1) (mk_lam v u2); dands;\n  try (apply implies_alpha_eq_mk_lam; eauto with slow).\n  constructor; simpl; auto; introv i; repndors; cpx.\n  constructor; simpl; auto; allrw disjoint_singleton_l; auto.\nQed.\n\nLemma comp_force_int_step3 {o} :\n  forall lib b f g (t1 t2 : @NTerm o) kk u,\n    isprog f\n    -> isprog g\n    -> wf_term t1\n    -> wf_term t2\n    -> agree_upto_b lib b f g\n    -> differ3 b f g t1 t2\n    -> compute_step lib t1 = csuccess u\n    -> has_value_like_k lib kk u\n    -> (forall t1 t2 v m, (* induction hypothesis *)\n          m < S kk\n          -> wf_term t1\n          -> wf_term t2\n          -> isvalue_like v\n          -> reduces_in_atmost_k_steps lib t1 v m\n          -> differ3 b f g t1 t2\n          -> {v' : NTerm & reduces_to lib t2 v' # differ3_alpha b f g v v'})\n    -> {t : NTerm\n        & {u' : NTerm\n           & reduces_to lib t2 t\n           # reduces_to lib u u'\n           # differ3_alpha b f g u' t}}.\nProof.\n  nterm_ind1s t1 as [v|s ind|op bs ind] Case;\n  introv ispf ispg wt1 wt2 agree d comp hv compind.\n\n  - Case \"vterm\".\n    simpl.\n    inversion d; subst; allsimpl; ginv.\n\n  - Case \"sterm\".\n    csunf comp; allsimpl; ginv.\n    inversion d; subst; allsimpl; ginv; clear d.\n    exists (sterm s) (sterm s); dands; eauto 3 with slow.\n\n  - Case \"oterm\".\n    dopid op as [can|ncan|exc|abs] SCase; ginv.\n\n    + SCase \"Can\".\n      inversion d; subst.\n      csunf comp; allsimpl; ginv.\n      exists (oterm (Can can) bs2) (oterm (Can can) bs); dands; eauto 3 with slow.\n\n    + SCase \"NCan\".\n      destruct bs as [|b1 bs];\n        try (complete (allsimpl; ginv));[].\n\n      destruct b1 as [l1 t1].\n      destruct l1; try (complete (csunf comp; simpl in comp; ginv));[|].\n\n      {\n      destruct t1 as [v1|f1|op1 bs1].\n\n      * destruct t2 as [v2|f2|op2 bs2]; try (complete (inversion d));[].\n\n        inversion d as [? ? ? ? d1|?|?|? ? ? len imp]; subst; simphyps; cpx; ginv.\n\n      * destruct t2 as [v2|f2|op2 bs2]; try (complete (inversion d));[].\n        csunf comp; allsimpl.\n        dopid_noncan ncan SSCase; allsimpl; ginv.\n\n        { SSCase \"NApply\".\n          apply compute_step_seq_apply_success in comp; exrepnd; subst; allsimpl.\n          inversion d as [? ? ? ? d1|?|?|? ? ? len imp]; subst; simphyps; cpx; ginv; clear d.\n          allsimpl.\n\n          pose proof (imp (nobnd (sterm f1)) x) as d1; autodimp d1 hyp.\n          pose proof (imp (nobnd arg) y) as d2; autodimp d2 hyp.\n          clear imp.\n\n          inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n          inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n          inversion d3; subst; clear d3.\n          fold_terms.\n\n          exists (mk_eapply (sterm f1) t0)\n                 (mk_eapply (sterm f1) arg).\n          dands; eauto 3 with slow.\n          apply differ3_implies_differ3_alpha.\n          apply differ3_mk_eapply; auto.\n        }\n\n        { SSCase \"NEApply\".\n          apply compute_step_eapply_success in comp; exrepnd; subst; allsimpl.\n          inversion d as [? ? ? ? d1|?|?|? ? ? len imp]; subst; simphyps; cpx; ginv; clear d.\n          rw @wf_term_eq in wt1; rw @nt_wf_eapply_iff in wt1; exrepnd; allunfold @nobnd; subst; ginv.\n          simpl in len; repeat cpx.\n          simpl in imp.\n\n          pose proof (imp (nobnd (sterm f1)) x) as d1; autodimp d1 hyp.\n          pose proof (imp (nobnd b0) y) as d2; autodimp d2 hyp.\n          clear imp.\n\n          inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n          inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n          inversion d3; subst; clear d3.\n          fold_terms.\n          allrw <- @wf_eapply_iff; repnd.\n\n          repndors; exrepnd; subst.\n\n          - apply compute_step_eapply2_success in comp1; repnd; GC.\n            repndors; exrepnd; subst; ginv; allsimpl; GC.\n            inversion d4 as [?|?|?|? ? ? len1 imp1]; subst; allsimpl;\n            clear d4; cpx; clear imp1; fold_terms.\n\n            exists (f0 n) (f0 n); dands; eauto 3 with slow.\n            { apply reduces_to_if_step.\n              csunf; simpl.\n              dcwf h; simpl; boolvar; try omega.\n              rw @Znat.Nat2Z.id; auto. }\n            { apply differ3_implies_differ3_alpha.\n              allapply @closed_if_isprog.\n              apply differ3_refl; simpl; try (rw ispf); try (rw ispg); auto. }\n\n          - apply isexc_implies2 in comp0; exrepnd; subst.\n            inversion d4 as [?|?|?|? ? ? len1 imp1]; subst; allsimpl; clear d4.\n            exists (oterm Exc bs2) (oterm Exc l); dands; eauto 3 with slow.\n\n          - pose proof (ind b0 b0 []) as h; clear ind.\n            repeat (autodimp h hyp); eauto 3 with slow.\n            pose proof (h t0 kk x) as ih; clear h.\n            applydup @preserve_nt_wf_compute_step in comp1; eauto 3 with slow.\n            allsimpl; autorewrite with slow in *; auto.\n            repeat (autodimp ih hyp); eauto 3 with slow.\n\n            { eapply has_value_k_like_eapply_sterm_implies in hv; auto; exrepnd.\n              eapply has_value_like_k_lt; eauto. }\n\n            exrepnd.\n\n            exists (mk_eapply (sterm f1) t) (mk_eapply (sterm f1) u'); dands; eauto 3 with slow.\n            { apply implies_eapply_red_aux; eauto 3 with slow. }\n            { apply implies_eapply_red_aux; eauto 3 with slow. }\n            { apply differ3_alpha_mk_eapply; eauto 3 with slow. }\n        }\n\n        { SSCase \"NFix\".\n          apply compute_step_fix_success in comp; repnd; subst; allsimpl.\n          inversion d as [? ? ? ? d1|?|?|? ? ? len imp]; subst; simphyps; cpx; ginv; clear d; allsimpl.\n\n          pose proof (imp (nobnd (sterm f1)) x) as d1; autodimp d1 hyp.\n          clear imp.\n\n          inversion d1 as [? ? ? df2 dg2 d2]; subst; clear d1.\n          inversion d2; subst; clear d2.\n          fold_terms.\n\n          exists (mk_apply (sterm f1) (mk_fix (sterm f1)))\n                 (mk_apply (sterm f1) (mk_fix (sterm f1))).\n          dands; eauto 3 with slow.\n        }\n\n        { SSCase \"NCbv\".\n          apply compute_step_cbv_success in comp; exrepnd; subst; allsimpl.\n          inversion d as [? ? ? d1|?|? xxx|? ? ? len imp]; subst; simphyps; cpx; ginv; clear d; allsimpl; fold_terms.\n\n          pose proof (imp (nobnd (sterm f1)) x0) as d1; autodimp d1 hyp.\n          pose proof (imp (bterm [v] x) y) as d2; autodimp d2 hyp.\n          clear imp.\n\n          inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n          inversion d3; subst; clear d3.\n          inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n          fold_terms.\n\n          exists (subst t2 v (sterm f1))\n                 (subst x v (sterm f1)).\n          dands; eauto 3 with slow.\n          allapply @closed_if_isprog.\n          apply differ3_subst; simpl; try (rw ispf); try (rw ispg); simpl; tcsp.\n        }\n\n        { SSCase \"NTryCatch\".\n          apply compute_step_try_success in comp; exrepnd; subst; allsimpl.\n          inversion d as [? ? ? d1|?|? xxx|? ? ? len imp]; subst; simphyps; cpx; ginv; clear d; allsimpl; fold_terms.\n\n          pose proof (imp (nobnd (sterm f1)) x0) as d1; autodimp d1 hyp.\n          pose proof (imp (nobnd a) y) as d2; autodimp d2 hyp.\n          pose proof (imp (bterm [v] x) z) as d3; autodimp d3 hyp.\n          clear imp.\n\n          inversion d1 as [? ? ? dfx dgx d4]; subst; clear d1.\n          inversion d4; subst; clear d4.\n          inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n          inversion d3 as [? ? ? df5 dg5 d5]; subst; clear d3.\n          fold_terms.\n\n          exists (mk_atom_eq t2 t2 (sterm f1) mk_bot)\n                 (mk_atom_eq a a (sterm f1) mk_bot).\n          dands; eauto 3 with slow.\n          apply differ3_alpha_mk_atom_eq; eauto 3 with slow.\n          apply differ3_implies_differ3_alpha.\n          allapply @closed_if_isprog.\n          apply differ3_refl; simpl; try (rw ispf); try (rw ispg); auto.\n        }\n\n        { SSCase \"NCanTest\".\n          apply compute_step_seq_can_test_success in comp; exrepnd; subst; allsimpl.\n          inversion d as [? ? ? d1|?|? xxx|? ? ? len imp]; subst; simphyps; cpx; ginv; clear d; allsimpl; fold_terms.\n\n          pose proof (imp (nobnd (sterm f1)) x) as d1; autodimp d1 hyp.\n          pose proof (imp (nobnd a) y) as d2; autodimp d2 hyp.\n          pose proof (imp (nobnd b0) z) as d3; autodimp d3 hyp.\n          clear imp.\n\n          inversion d1 as [? ? ? dfx dgx d4]; subst; clear d1.\n          inversion d4; subst; clear d4.\n          inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n          inversion d3 as [? ? ? df5 dg5 d5]; subst; clear d3.\n          fold_terms.\n\n          exists t0 b0.\n          dands; eauto 3 with slow.\n        }\n\n      * (* Now destruct op2 *)\n        dopid op1 as [can1|ncan1|exc1|abs1] SSCase; ginv.\n\n        { SSCase \"Can\".\n\n          (* Because the principal argument is canonical we can destruct ncan *)\n          dopid_noncan ncan SSSCase.\n\n          - SSSCase \"NApply\".\n            clear ind compind.\n            csunf comp; allsimpl.\n            apply compute_step_apply_success in comp; repndors; exrepnd; subst; allsimpl.\n\n            { inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear d.\n              destruct bs2; allsimpl; cpx.\n              cpx; allsimpl.\n\n              pose proof (imp (bterm [] (oterm (Can NLambda) [bterm [v] b0])) b1) as d1.\n              autodimp d1 hyp.\n              pose proof (imp (bterm [] arg) x) as d2.\n              autodimp d2 hyp.\n              clear imp.\n\n              inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n              inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n\n              inversion d3 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; GC; clear d3.\n              destruct bs2; allsimpl; cpx.\n              cpx.\n\n              pose proof (imp1 (bterm [v] b0) b1) as d1.\n              autodimp d1 hyp.\n              clear imp1.\n              inversion d1 as [? ? ? df2 dg2 d2]; subst; clear d1.\n\n              exists (subst t2 v t0) (subst b0 v arg); dands; eauto 3 with slow.\n\n              apply differ3_subst; simpl; eauto 3 with slow.\n            }\n\n            { inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear d; cpx.\n              allsimpl; fold_terms.\n\n              pose proof (imp (nobnd (mk_nseq f0)) x) as d1.\n              autodimp d1 hyp.\n              pose proof (imp (nobnd arg) y) as d2.\n              autodimp d2 hyp.\n              clear imp.\n\n              inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n              inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n              GC.\n\n              inversion d3 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; GC; clear d3.\n              cpx; clear imp1; fold_terms.\n\n              exists (mk_eapply (mk_nseq f0) t0) (mk_eapply (mk_nseq f0) arg); dands; eauto 3 with slow.\n\n              apply differ3_implies_differ3_alpha.\n              apply differ3_oterm; simpl; tcsp.\n              introv j; repndors; cpx; repeat (constructor; auto).\n              simpl; tcsp.\n            }\n\n          - SSSCase \"NEApply\".\n            csunf comp; allsimpl.\n            apply compute_step_eapply_success in comp; exrepnd; subst.\n            rw @wf_term_eq in wt1; rw @nt_wf_eapply_iff in wt1; exrepnd; allunfold @nobnd; ginv.\n\n            inversion d as [? ? ? ? d1|?|?|? ? ? len imp]; subst; clear d.\n            simpl in len; cpx; simpl in imp.\n\n            pose proof (imp (nobnd (oterm (Can can1) bs1)) x) as d1; autodimp d1 hyp.\n            pose proof (imp (nobnd b0) y) as d2; autodimp d2 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n            inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n            fold_terms.\n            allrw <- @wf_eapply_iff; repnd.\n            apply eapply_wf_def_oterm_implies in comp2; exrepnd; ginv; fold_terms.\n            destruct comp2 as [comp2|comp2]; exrepnd; ginv; fold_terms.\n\n            { apply differ3_lam_implies in d3; exrepnd; subst; fold_terms.\n\n              repndors; exrepnd; subst.\n\n              + apply compute_step_eapply2_success in comp1; repnd; GC.\n                repndors; exrepnd; subst; ginv; allsimpl; GC.\n                allunfold @apply_bterm; allsimpl; allrw @fold_subst.\n\n                exists (subst a' v0 t0) (subst b1 v0 b0); dands; eauto 3 with slow.\n                { apply eapply_lam_can_implies.\n                  apply differ3_preserves_iscan in d4; auto.\n                  unfold computes_to_can; dands; eauto 3 with slow. }\n                { apply differ3_subst; auto; simpl;\n                  allapply @closed_if_isprog; try (rw ispf); try (rw ispg); auto. }\n\n              + apply wf_isexc_implies in comp0; auto; exrepnd; subst; allsimpl.\n                apply differ3_exception_implies in d4; exrepnd; subst.\n                exists (mk_exception a'0 e') (mk_exception a e); dands; eauto 3 with slow.\n                apply differ3_alpha_mk_exception; eauto 3 with slow.\n\n              + pose proof (ind b0 b0 []) as h; clear ind.\n                repeat (autodimp h hyp); eauto 3 with slow.\n                pose proof (h t0 kk x) as ih; clear h.\n                applydup @preserve_nt_wf_compute_step in comp1; auto.\n                repeat (autodimp ih hyp); eauto 3 with slow.\n                { apply has_value_like_k_eapply_lam_implies in hv; auto.\n                  exrepnd.\n                  eapply has_value_like_k_lt; eauto. }\n                exrepnd.\n\n                exists (mk_eapply (mk_lam v a') t1) (mk_eapply (mk_lam v t) u'); dands; eauto 3 with slow.\n                { apply implies_eapply_red_aux; eauto 3 with slow. }\n                { apply implies_eapply_red_aux; eauto 3 with slow. }\n                { apply differ3_alpha_mk_eapply; eauto 3 with slow.\n                  apply differ3_alpha_mk_lam; eauto 3 with slow;\n                  allapply @closed_if_isprog; try (rw ispf); try (rw ispg); simpl; tcsp. }\n            }\n\n            { inversion d3 as [|?|?|? ? ? len imp]; subst; simphyps; clear d3.\n              clear imp.\n              allsimpl; cpx; allsimpl; fold_terms.\n              repndors; exrepnd; subst; allsimpl.\n\n              - destruct b0 as [v|f'|op bs]; ginv;[].\n                dopid op as [can|ncan|exc|abs] SSSSCase; ginv;[].\n                destruct can; ginv;[].\n                destruct bs; allsimpl; ginv; GC.\n                boolvar; ginv; try omega; fold_terms.\n                inversion d4 as [|?|?|? ? ? len imp]; subst; simphyps; clear d4.\n                allsimpl; cpx; fold_terms; allsimpl.\n                clear imp.\n\n                exists (@mk_nat o (s (Z.to_nat z))) (@mk_nat o (s (Z.to_nat z))); dands; eauto 3 with slow.\n                apply reduces_to_if_step; csunf; simpl; dcwf h; simpl.\n                boolvar; try omega; auto.\n\n              - apply wf_isexc_implies in comp0; auto; exrepnd; subst; allsimpl.\n                apply differ3_exception_implies in d4; exrepnd; subst.\n                exists (mk_exception a' e') (mk_exception a e); dands; eauto 3 with slow.\n                apply differ3_alpha_mk_exception; eauto 3 with slow.\n\n              - pose proof (ind b0 b0 []) as h; clear ind.\n                repeat (autodimp h hyp); eauto 3 with slow.\n                pose proof (h t0 kk x) as ih; clear h.\n                applydup @preserve_nt_wf_compute_step in comp1; auto.\n                allsimpl; autorewrite with slow in *.\n                repeat (autodimp ih hyp); eauto 3 with slow.\n                { apply has_value_like_k_eapply_nseq_implies in hv; auto.\n                  exrepnd.\n                  eapply has_value_like_k_lt; eauto. }\n                exrepnd.\n\n                exists (mk_eapply (mk_nseq s) t) (mk_eapply (mk_nseq s) u'); dands; eauto 3 with slow.\n                { apply implies_eapply_red_aux; eauto 3 with slow. }\n                { apply implies_eapply_red_aux; eauto 3 with slow. }\n                { apply differ3_alpha_mk_eapply; eauto 3 with slow. }\n            }\n\n(*          - SSSCase \"NApseq\".\n            clear ind compind.\n            csunf comp; allsimpl.\n            apply compute_step_apseq_success in comp; exrepnd; subst; allsimpl.\n            fold_terms.\n\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear d.\n            cpx; allsimpl.\n\n            pose proof (imp (nobnd (mk_nat n0)) x) as d1.\n            autodimp d1 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n\n            inversion d3 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; GC; clear d3.\n            cpx; clear imp1; fold_terms.\n\n            exists (@mk_nat o (n n0)) (@mk_nat o (n n0)); dands; eauto 3 with slow.\n            apply reduces_to_if_step; csunf; simpl.\n            rw @Znat.Nat2Z.id.\n            boolvar; try omega; auto. *)\n\n          - SSSCase \"NFix\".\n            csunf comp; allsimpl.\n            apply compute_step_fix_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear d.\n            destruct bs2; allsimpl; cpx.\n            destruct bs2; allsimpl; cpx.\n            cpx; GC.\n\n            pose proof (imp (bterm [] (oterm (Can can1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n\n            inversion d3 as [|?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; GC; clear d3.\n\n            exists (mk_apply (oterm (Can can1) bs2)\n                             (mk_fix (oterm (Can can1) bs2)))\n                   (mk_apply (oterm (Can can1) bs1)\n                             (mk_fix (oterm (Can can1) bs1))).\n            dands; eauto 3 with slow.\n\n            apply differ3_implies_differ3_alpha.\n            apply differ3_oterm; simpl; tcsp.\n            introv j; repndors; cpx; tcsp.\n\n            { constructor; auto ; constructor; allsimpl; auto. }\n\n            { constructor; auto; constructor; simpl; tcsp.\n              introv j; repndors; cpx; tcsp. }\n\n          - SSSCase \"NSpread\".\n            csunf comp; allsimpl.\n            apply compute_step_spread_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear d.\n            destruct bs2; allsimpl; cpx.\n            cpx; allsimpl.\n\n            pose proof (imp (bterm [] (oterm (Can NPair) [bterm [] a, bterm [] b0])) b1) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [va,vb] arg) x) as d2.\n            autodimp d2 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n            inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n\n            inversion d3 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; GC; clear d3.\n            destruct bs2; allsimpl; cpx.\n            cpx; allsimpl.\n\n            pose proof (imp1 (bterm [] a) b1) as d1.\n            autodimp d1 hyp.\n            pose proof (imp1 (bterm [] b0) x) as d2.\n            autodimp d2 hyp.\n            clear imp1.\n            inversion d1 as [? ? ? df5 dg5 d5]; subst; clear d1.\n            inversion d2 as [? ? ? df6 dg6 d6]; subst; clear d2.\n\n            exists (lsubst t0 [(va,t2),(vb,t3)]) (lsubst arg [(va,a),(vb,b0)]); dands; eauto 3 with slow.\n            apply differ3_subst; simpl; eauto 3 with slow.\n\n          - SSSCase \"NDsup\".\n            csunf comp; allsimpl.\n            apply compute_step_dsup_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear d.\n            destruct bs2; allsimpl; cpx.\n            cpx; allsimpl.\n\n            pose proof (imp (bterm [] (oterm (Can NSup) [bterm [] a, bterm [] b0])) b1) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [va,vb] arg) x) as d2.\n            autodimp d2 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n            inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n\n            inversion d3 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; GC; clear d3.\n            destruct bs2; allsimpl; cpx.\n            cpx; allsimpl.\n\n            pose proof (imp1 (bterm [] a) b1) as d1.\n            autodimp d1 hyp.\n            pose proof (imp1 (bterm [] b0) x) as d2.\n            autodimp d2 hyp.\n            clear imp1.\n            inversion d1 as [? ? ? df5 dg5 d5]; subst; clear d1.\n            inversion d2 as [? ? ? df6 dg6 d6]; subst; clear d2.\n\n            exists (lsubst t0 [(va,t2),(vb,t3)]) (lsubst arg [(va,a),(vb,b0)]); dands; eauto 3 with slow.\n            apply differ3_subst; simpl; eauto 3 with slow.\n\n          - SSSCase \"NDecide\".\n            csunf comp; allsimpl.\n            apply compute_step_decide_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear d.\n            destruct bs2; allsimpl; cpx.\n            destruct bs2; allsimpl; cpx.\n            cpx; allsimpl.\n\n            pose proof (imp (bterm [] (oterm (Can can1) [bterm [] d0])) b0) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [v1] t1) b1) as d2.\n            autodimp d2 hyp.\n            pose proof (imp (bterm [v2] t0) x) as d3.\n            autodimp d3 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df4 dg4 d4]; subst; clear d1.\n            inversion d2 as [? ? ? df5 dg5 d5]; subst; clear d2.\n            inversion d3 as [? ? ? df6 dg6 d6]; subst; clear d3.\n\n            inversion d4 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; GC; clear d4.\n            cpx; allsimpl.\n\n            pose proof (imp1 (bterm [] d0) x) as d1.\n            autodimp d1 hyp.\n            clear imp1.\n            inversion d1 as [? ? ? df2 dg2 d2]; subst; clear d1.\n\n            dorn comp0; repnd; subst.\n\n            + exists (subst t4 v1 t3) (subst t1 v1 d0); dands; eauto 3 with slow.\n              apply differ3_subst; simpl; eauto 3 with slow.\n\n            + exists (subst t5 v2 t3) (subst t0 v2 d0); dands; eauto 3 with slow.\n              apply differ3_subst; simpl; eauto 3 with slow.\n\n          - SSSCase \"NCbv\".\n            csunf comp; allsimpl.\n            apply compute_step_cbv_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear d.\n            destruct bs2; allsimpl; cpx.\n            cpx; allsimpl.\n\n            pose proof (imp (bterm [] (oterm (Can can1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [v] x) x0) as d2.\n            autodimp d2 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n            inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n\n            inversion d3 as [|?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; GC; clear d3.\n\n            exists (subst t0 v (oterm (Can can1) bs2))\n                   (subst x v (oterm (Can can1) bs1)); dands; eauto 3 with slow.\n            apply differ3_subst; simpl; eauto 3 with slow.\n\n          - SSSCase \"NSleep\".\n            csunf comp; allsimpl.\n            apply compute_step_sleep_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear d.\n            cpx; allsimpl.\n\n            pose proof (imp (bterm [] (oterm (Can (Nint z)) [])) x) as d1.\n            autodimp d1 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df2 sg2 d2]; subst; clear d1.\n\n            inversion d2 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; GC; clear d2.\n            cpx; allsimpl.\n\n            exists (@mk_axiom o)\n                   (@mk_axiom o).\n            dands; eauto 3 with slow.\n\n          - SSSCase \"NTUni\".\n            csunf comp; allsimpl.\n            apply compute_step_tuni_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear d.\n            cpx; allsimpl.\n\n            pose proof (imp (bterm [] (oterm (Can (Nint (Z.of_nat n))) [])) x) as d1.\n            autodimp d1 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df2 dg2 d2]; subst; clear d1.\n\n            inversion d2 as [|?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; GC; clear d2.\n            cpx; allsimpl.\n\n            exists (@mk_uni o n)\n                   (@mk_uni o n).\n            dands; eauto 3 with slow.\n            { apply reduces_to_if_step; simpl.\n              csunf; simpl; unfold compute_step_tuni; simpl; boolvar; try omega.\n              rw Znat.Nat2Z.id; auto. }\n\n          - SSSCase \"NMinus\".\n            csunf comp; allsimpl.\n            apply compute_step_minus_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear d.\n            cpx; allsimpl.\n\n            pose proof (imp (bterm [] (oterm (Can (Nint z)) [])) x) as d1.\n            autodimp d1 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df2 dg2 d2]; subst; clear d1.\n\n            inversion d2 as [|?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; GC; clear d2.\n            cpx; allsimpl.\n\n            exists (@mk_integer o (- z))\n                   (@mk_integer o (- z)).\n            dands; eauto 3 with slow.\n\n          - SSSCase \"NFresh\".\n            csunf comp; allsimpl; ginv.\n\n          - SSSCase \"NTryCatch\".\n            csunf comp; allsimpl.\n            apply compute_step_try_success in comp; exrepnd; subst; allsimpl.\n\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear d.\n            destruct bs2; allsimpl; cpx.\n            cpx; allsimpl.\n\n            pose proof (imp (bterm [] (oterm (Can can1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [] a) x0) as d2.\n            autodimp d2 hyp.\n            pose proof (imp (bterm [v] x) y) as d3.\n            autodimp d3 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df4 dg4 d4]; subst; clear d1.\n            inversion d2 as [? ? ? df5 dg5 d5]; subst; clear d2.\n            inversion d3 as [? ? ? df6 dg6 d6]; subst; clear d3.\n            allrw disjoint_singleton_l.\n\n            inversion d4 as [|?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; GC; clear d4.\n\n            exists (mk_atom_eq t0 t0 (oterm (Can can1) bs2) mk_bot)\n                   (mk_atom_eq a a (oterm (Can can1) bs1) mk_bot);\n              dands; eauto 3 with slow.\n\n            apply differ3_implies_differ3_alpha.\n            constructor; simpl; auto.\n            introv i; repndors; ginv; tcsp; constructor; eauto 3 with slow.\n            apply differ3_refl; simpl; allrw disjoint_singleton_l;\n            try (rw @isprog_eq in ispf; destruct ispf as [c w]; rw c; simpl; tcsp);\n            try (rw @isprog_eq in ispg; destruct ispg as [c w]; rw c; simpl; tcsp).\n\n          - SSSCase \"NParallel\".\n            csunf comp; allsimpl.\n            apply compute_step_parallel_success in comp; subst; allsimpl.\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; GC; clear d.\n            destruct bs2; allsimpl; cpx.\n\n            pose proof (imp (bterm [] (oterm (Can can1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            inversion d1 as [? ? ? df2 dg2 d2]; subst; clear d1.\n            inversion d2 as [|?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; GC; clear d2.\n\n            exists (@mk_axiom o) (@mk_axiom o); dands; eauto 3 with slow.\n\n          - SSSCase \"NCompOp\".\n            destruct bs; try (complete (csunf comp; allsimpl; dcwf h));[].\n            destruct b0 as [l t].\n            destruct l; destruct t as [v|s|op bs2]; try (complete (csunf comp; allsimpl; dcwf h));[].\n\n            inversion d as [|?|?|? ? ? len imp]; subst; clear d.\n            allsimpl.\n            destruct bs3; allsimpl; cpx.\n            destruct bs3; allsimpl; cpx.\n\n            pose proof (imp (bterm [] (oterm (Can can1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [] (oterm op bs2)) b1) as d2.\n            autodimp d2 hyp.\n\n            inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n            inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n\n            inversion d3 as [|?|?|? ? ? ni1 len1 imp1]; subst; clear d3; cpx.\n\n            dopid op as [can3|ncan3|exc3|abs3] SSSSCase.\n\n            + SSSSCase \"Can\".\n              csunf comp; allsimpl.\n              dcwf h.\n\n              inversion d4 as [|?|?|? ? ? len2 imp2]; subst; clear d4; cpx.\n\n              apply compute_step_compop_success_can_can in comp.\n              exrepnd; subst.\n\n              allsimpl; cpx.\n              clear df3 dg3 df4 dg4 len1 imp2.\n              allsimpl.\n\n              pose proof (imp (nobnd t1) x) as d1.\n              autodimp d1 hyp.\n              pose proof (imp (nobnd t2) y) as d2.\n              autodimp d2 hyp.\n              clear imp.\n\n              inversion d1 as [? ? ? df33 dg33 d3]; subst; clear d1.\n              inversion d2 as [? ? ? df44 dg44 d4]; subst; clear d2.\n\n              repndors; exrepnd; subst.\n\n              * allapply @get_param_from_cop_pki; subst; allsimpl.\n                exists (if Z_lt_le_dec n1 n2 then t3 else t4)\n                       (if Z_lt_le_dec n1 n2 then t1 else t2);\n                  dands; eauto 3 with slow.\n                boolvar; eauto 3 with slow.\n\n              * allrw @get_param_from_cop_some; subst; allsimpl.\n                exists (if param_kind_deq pk1 pk2 then t3 else t4)\n                       (if param_kind_deq pk1 pk2 then t1 else t2);\n                  dands; eauto 3 with slow.\n\n                { apply reduces_to_if_step; csunf; simpl.\n                  dcwf h; allsimpl.\n                  unfold compute_step_comp; allrw @get_param_from_cop_pk2can; auto. }\n\n                boolvar; eauto 3 with slow.\n\n            + SSSSCase \"NCan\".\n              rw @compute_step_ncompop_ncan2 in comp.\n              dcwf h; allsimpl.\n              remember (compute_step lib (oterm (NCan ncan3) bs2)) as comp1;\n                symmetry in Heqcomp1.\n              destruct comp1; ginv.\n\n              pose proof (ind (oterm (NCan ncan3) bs2) (oterm (NCan ncan3) bs2) []) as h; clear ind.\n              repeat (autodimp h hyp); tcsp; eauto 3 with slow.\n\n              pose proof (h t0 kk n) as k; clear h.\n              repeat (autodimp k hyp).\n\n              { apply wf_oterm_iff in wt1; allsimpl; repnd.\n                pose proof (wt1 (bterm [] (oterm (NCan ncan3) bs2))) as h.\n                autodimp h hyp. }\n\n              { apply wf_oterm_iff in wt2; allsimpl; repnd.\n                pose proof (wt2 (bterm [] t0)) as h.\n                autodimp h hyp. }\n\n              { apply if_has_value_like_k_ncompop_can1 in hv; exrepnd.\n                apply (has_value_like_k_lt lib j kk) in hv0; auto. }\n\n              exrepnd.\n\n              exists (oterm (NCan (NCompOp c))\n                            (bterm [] (oterm (Can can1) bs4)\n                                   :: bterm [] t\n                                   :: bs3))\n                     (oterm (NCan (NCompOp c))\n                            (bterm [] (oterm (Can can1) bs1)\n                                   :: bterm [] u'\n                                   :: bs)).\n              dands; eauto 3 with slow.\n\n              * apply reduce_to_prinargs_comp2; eauto 3 with slow; sp.\n                apply co_wf_def_implies_iswfpk.\n                eapply co_wf_def_len_implies;[|eauto];auto.\n\n              * apply reduce_to_prinargs_comp2; eauto 3 with slow; sp.\n\n              * unfold differ3_alpha in k1; exrepnd.\n                exists (oterm (NCan (NCompOp c))\n                              (bterm [] (oterm (Can can1) bs1)\n                                     :: bterm [] u1\n                                     :: bs))\n                       (oterm (NCan (NCompOp c))\n                              (bterm [] (oterm (Can can1) bs4)\n                                     :: bterm [] u2\n                                     :: bs3)).\n                dands.\n\n                { prove_alpha_eq4.\n                  introv j; destruct n0;[|destruct n0]; try omega; cpx.\n                  apply alphaeqbt_nilv2; auto. }\n\n                { prove_alpha_eq4.\n                  introv j; destruct n0;[|destruct n0]; try omega; cpx.\n                  apply alphaeqbt_nilv2; auto. }\n\n                { apply differ3_oterm; simpl; tcsp.\n                  introv j; repndors; cpx. }\n\n            + SSSSCase \"Exc\".\n              csunf comp; allsimpl; ginv.\n              dcwf h; ginv; allsimpl.\n              inversion d4 as [|?|?|? ? ? len2 imp2]; subst; clear d4; cpx.\n              exists (oterm Exc bs5) (oterm Exc bs2); dands; eauto 3 with slow.\n              apply reduces_to_if_step; csunf; allsimpl; dcwf h.\n\n            + SSSSCase \"Abs\".\n              csunf comp; allsimpl; csunf comp; allsimpl.\n              dcwf h.\n              unfold on_success in comp.\n              remember (compute_step_lib lib abs3 bs2) as comp1.\n              symmetry in Heqcomp1; destruct comp1; ginv.\n              apply compute_step_lib_success in Heqcomp1; exrepnd; subst.\n\n              inversion d4 as [|?|?|? ? ? ni2 len2 imp2]; subst; simphyps; clear d4.\n\n              assert (differ3_bterms b f g bs2 bs5) as dbs.\n              { unfold differ3_bterms, br_bterms, br_list; auto. }\n\n              pose proof (found_entry_change_bs abs3 oa2 vars rhs lib bs2 correct bs5) as fe2.\n              repeat (autodimp fe2 hyp).\n\n              { apply differ3_bterms_implies_eq_map_num_bvars in dbs; auto. }\n\n              exists (oterm (NCan (NCompOp c))\n                            (bterm [] (oterm (Can can1) bs4)\n                                   :: bterm [] (mk_instance vars bs5 rhs)\n                                   :: bs3))\n              (oterm (NCan (NCompOp c))\n                     (bterm [] (oterm (Can can1) bs1)\n                            :: bterm [] (mk_instance vars bs2 rhs)\n                            :: bs)).\n\n             dands; eauto 3 with slow.\n\n             * apply reduces_to_if_step.\n               csunf; simpl; csunf; simpl.\n               dcwf h.\n               applydup @compute_step_lib_if_found_entry in fe2.\n               rw fe0; auto.\n\n             * pose proof (differ3_mk_instance b f g rhs vars bs2 bs5) as h.\n               repeat (autodimp h hyp); tcsp; GC.\n               { unfold correct_abs in correct; sp. }\n               { allapply @found_entry_implies_matching_entry.\n                 allunfold @matching_entry; sp. }\n               { allapply @found_entry_implies_matching_entry.\n                 allunfold @matching_entry; sp. }\n               { allunfold @correct_abs; sp. }\n               { allunfold @correct_abs; sp. }\n               unfold differ3_alpha in h.\n               exrepnd.\n\n               exists\n                 (oterm (NCan (NCompOp c))\n                        (bterm [] (oterm (Can can1) bs1)\n                               :: bterm [] u1\n                               :: bs))\n                 (oterm (NCan (NCompOp c))\n                        (bterm [] (oterm (Can can1) bs4)\n                               :: bterm [] u2\n                               :: bs3)).\n               dands.\n\n               { prove_alpha_eq4.\n                 introv j; destruct n;[|destruct n]; try omega; cpx.\n                 apply alphaeqbt_nilv2; auto. }\n\n               { prove_alpha_eq4.\n                 introv j; destruct n;[|destruct n]; try omega; cpx.\n                 apply alphaeqbt_nilv2; auto. }\n\n               { apply differ3_oterm; allsimpl; tcsp.\n                 introv j; repndors; cpx. }\n\n          - SSSCase \"NArithOp\".\n            destruct bs; try (complete (csunf comp; allsimpl; dcwf h));[].\n            destruct b0 as [l t].\n            destruct l; destruct t as [v|s|op bs2]; try (complete (csunf comp; allsimpl; dcwf h));[].\n\n            inversion d as [|?|?|? ? ? len imp]; subst; clear d.\n            simpl in len; GC.\n\n            destruct bs3; simpl in len; cpx.\n            destruct bs3; simpl in len; cpx.\n            simpl in imp.\n\n            pose proof (imp (bterm [] (oterm (Can can1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [] (oterm op bs2)) b1) as d2.\n            autodimp d2 hyp.\n\n            inversion d1 as [? ? ? df3 dg3 d3]; subst; clear d1.\n            inversion d2 as [? ? ? df4 dg4 d4]; subst; clear d2.\n\n            inversion d3 as [|?|?|? ? ? ni1 len1 imp1]; subst; clear d3; cpx.\n\n            dopid op as [can3|ncan3|exc3|abs3] SSSSCase.\n\n            + SSSSCase \"Can\".\n              csunf comp; simpl in comp.\n              dcwf h; allsimpl.\n\n              inversion d4 as [|?|?|? ? ? ni2 len2 imp2]; subst; clear d4; cpx.\n\n              apply compute_step_arithop_success_can_can in comp.\n              exrepnd; subst.\n\n              allsimpl; cpx.\n\n              allapply @get_param_from_cop_pki; subst; allsimpl; GC.\n              exists (@oterm o (Can (Nint (get_arith_op a n1 n2))) [])\n                     (@oterm o (Can (Nint (get_arith_op a n1 n2))) []);\n                dands; eauto 3 with slow.\n\n            + SSSSCase \"NCan\".\n              rw @compute_step_narithop_ncan2 in comp.\n              dcwf h; allsimpl.\n              remember (compute_step lib (oterm (NCan ncan3) bs2)) as comp1;\n                symmetry in Heqcomp1.\n              destruct comp1; ginv.\n\n              pose proof (ind (oterm (NCan ncan3) bs2) (oterm (NCan ncan3) bs2) []) as h; clear ind.\n              repeat (autodimp h hyp); tcsp; eauto 3 with slow.\n\n              pose proof (h t0 kk n) as k; clear h.\n              repeat (autodimp k hyp).\n\n              { rw @wf_oterm_iff in wt1; allsimpl; repnd.\n                pose proof (wt1 (bterm [] (oterm (NCan ncan3) bs2))) as h.\n                autodimp h hyp. }\n\n              { rw @wf_oterm_iff in wt2; allsimpl; repnd.\n                pose proof (wt2 (bterm [] t0)) as h.\n                autodimp h hyp. }\n\n              { apply if_has_value_like_k_narithop_can1 in hv; exrepnd.\n                apply (has_value_like_k_lt lib j kk) in hv0; auto. }\n\n              exrepnd.\n\n              exists (oterm (NCan (NArithOp a))\n                            (bterm [] (oterm (Can can1) bs4)\n                                   :: bterm [] t\n                                   :: bs3))\n                     (oterm (NCan (NArithOp a))\n                            (bterm [] (oterm (Can can1) bs1)\n                                   :: bterm [] u'\n                                   :: bs)).\n              dands; eauto 3 with slow.\n\n              * apply reduce_to_prinargs_arith2; eauto 3 with slow; sp.\n                allunfold @ca_wf_def; exrepnd; subst; allsimpl; cpx; fold_terms; eauto 3 with slow.\n\n              * apply reduce_to_prinargs_arith2; eauto 3 with slow; sp.\n\n              * unfold differ3_alpha in k1; exrepnd.\n                exists (oterm (NCan (NArithOp a))\n                              (bterm [] (oterm (Can can1) bs1)\n                                     :: bterm [] u1\n                                     :: bs))\n                       (oterm (NCan (NArithOp a))\n                              (bterm [] (oterm (Can can1) bs4)\n                                     :: bterm [] u2\n                                     :: bs3)).\n                dands.\n\n                { prove_alpha_eq4.\n                  introv j; destruct n0;[|destruct n0]; try omega; cpx.\n                  apply alphaeqbt_nilv2; auto. }\n\n                { prove_alpha_eq4.\n                  introv j; destruct n0;[|destruct n0]; try omega; cpx.\n                  apply alphaeqbt_nilv2; auto. }\n\n                { apply differ3_oterm; simpl; tcsp.\n                  introv j; repndors; cpx. }\n\n            + SSSSCase \"Exc\".\n              csunf comp; allsimpl; ginv.\n              dcwf h; allsimpl; ginv.\n              inversion d4 as [|?|?|? ? ? len2 imp2]; subst; clear d4; cpx.\n              exists (oterm Exc bs5) (oterm Exc bs2); dands; eauto 3 with slow.\n              apply reduces_to_if_step; csunf; simpl; dcwf h.\n\n            + SSSSCase \"Abs\".\n              csunf comp; allsimpl; csunf comp; allsimpl.\n              dcwf h.\n              remember (compute_step_lib lib abs3 bs2) as comp1.\n              symmetry in Heqcomp1; destruct comp1; ginv.\n              apply compute_step_lib_success in Heqcomp1; exrepnd; subst.\n\n              inversion d4 as [|?|?|? ? ? ni2 len2 imp2]; subst; simphyps; clear d4.\n\n              assert (differ3_bterms b f g bs2 bs5) as dbs.\n              { unfold differ3_bterms, br_bterms, br_list; auto. }\n\n              pose proof (found_entry_change_bs abs3 oa2 vars rhs lib bs2 correct bs5) as fe2.\n              repeat (autodimp fe2 hyp).\n\n              { apply differ3_bterms_implies_eq_map_num_bvars in dbs; auto. }\n\n              exists (oterm (NCan (NArithOp a))\n                            (bterm [] (oterm (Can can1) bs4)\n                                   :: bterm [] (mk_instance vars bs5 rhs)\n                                   :: bs3))\n              (oterm (NCan (NArithOp a))\n                     (bterm [] (oterm (Can can1) bs1)\n                            :: bterm [] (mk_instance vars bs2 rhs)\n                            :: bs)).\n\n             dands; eauto 3 with slow.\n\n             * apply reduces_to_if_step.\n               csunf; simpl; csunf; simpl.\n               dcwf h; allsimpl.\n               applydup @compute_step_lib_if_found_entry in fe2.\n               rw fe0; auto.\n\n             * pose proof (differ3_mk_instance b f g rhs vars bs2 bs5) as h.\n               repeat (autodimp h hyp); tcsp; GC.\n               { unfold correct_abs in correct; sp. }\n               { allapply @found_entry_implies_matching_entry.\n                 allunfold @matching_entry; sp. }\n               { allapply @found_entry_implies_matching_entry.\n                 allunfold @matching_entry; sp. }\n               { allunfold @correct_abs; sp. }\n               { allunfold @correct_abs; sp. }\n               unfold differ3_alpha in h.\n               exrepnd.\n\n               exists\n                 (oterm (NCan (NArithOp a))\n                        (bterm [] (oterm (Can can1) bs1)\n                               :: bterm [] u1\n                               :: bs))\n                 (oterm (NCan (NArithOp a))\n                        (bterm [] (oterm (Can can1) bs4)\n                               :: bterm [] u2\n                               :: bs3)).\n               dands.\n\n               { prove_alpha_eq4.\n                 introv j; destruct n;[|destruct n]; try omega; cpx.\n                 apply alphaeqbt_nilv2; auto. }\n\n               { prove_alpha_eq4.\n                 introv j; destruct n;[|destruct n]; try omega; cpx.\n                 apply alphaeqbt_nilv2; auto. }\n\n               { apply differ3_oterm; allsimpl; tcsp.\n                 introv j; repndors; cpx. }\n\n          - SSSCase \"NCanTest\".\n            csunf comp; allsimpl.\n            apply compute_step_can_test_success in comp; exrepnd; subst; allsimpl.\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; clear d.\n            destruct bs2; allsimpl; cpx.\n            destruct bs2; allsimpl; cpx.\n            cpx; allsimpl; GC.\n\n            pose proof (imp (bterm [] (oterm (Can can1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [] arg2nt) b1) as d2.\n            autodimp d2 hyp.\n            pose proof (imp (bterm [] arg3nt) x) as d3.\n            autodimp d3 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? df4 dg4 d4]; subst; clear d1.\n            inversion d2 as [? ? ? df5 dg5 d5]; subst; clear d2.\n            inversion d3 as [? ? ? df6 dg6 d6]; subst; clear d3.\n\n            inversion d4 as [|?|?|? ? ? ni1 len1 imp1]; subst; allsimpl; clear d4.\n\n            exists (if canonical_form_test_for c can1 then t0 else t3)\n                   (if canonical_form_test_for c can1 then arg2nt else arg3nt).\n            dands; eauto 3 with slow.\n            destruct (canonical_form_test_for c can1); eauto 3 with slow.\n        }\n\n        { SSCase \"NCan\".\n          rw @compute_step_ncan_ncan in comp.\n          remember (compute_step lib (oterm (NCan ncan1) bs1)) as comp1;\n            symmetry in Heqcomp1.\n          destruct comp1; ginv.\n\n          inversion d as [? ? ? ? ? ni1 ni2 d1 aeq1 aeq2|?|?|? ? ? len imp];\n            subst; clear d.\n\n          - (* let's prove that t1 computes to an integer in less than kk steps *)\n            fold_terms; fold (force_int_bound v b t1 (mk_vbot v)) in Heqcomp1.\n            applydup @if_has_value_like_k_cbv_primarg in hv; simpl; tcsp; exrepnd.\n            assert (has_value_like_k lib (S j) (force_int_bound v b t1 (mk_vbot v))) as hvf.\n            { rw @has_value_like_S; eexists; eauto. }\n            apply if_has_value_like_k_force_int_bound in hvf; exrepnd.\n\n            pose proof (compind t1 t0 u j0) as r.\n            repeat (autodimp r hyp); try omega; exrepnd.\n\n            { allrw <- @wf_cbv_iff; repnd; auto. }\n\n            { apply wf_force_int_bound_app in wt2; sp. }\n\n            repndors; exrepnd; subst.\n\n            { apply differ3_alpha_integer in r0; subst.\n              pose proof (agree z) as ag.\n              repeat (autodimp ag hyp); eauto 3 with slow.\n              exrepnd.\n\n              pose proof (compute_step_force_int_bound lib v b (mk_vbot v) z j0 t1 n) as rz.\n              repeat (autodimp rz hyp); eauto 3 with slow.\n\n              exists (@mk_integer o z0) (@mk_integer o z0); dands.\n\n              + pose proof (reduces_to_force_int_bound_app_z\n                              lib v b (mk_vbot v) z t0 ga) as h.\n                repeat (autodimp h hyp); tcsp; eauto 3 with slow.\n                { apply alphaeq_preserves_free_vars in aeq2; rw <- aeq2; auto. }\n                eapply reduces_to_trans;[exact h|].\n\n                pose proof (reduces_to_alpha\n                              lib\n                              (mk_apply g (mk_integer z))\n                              (mk_apply ga (mk_integer z))\n                              (mk_integer z0)) as k.\n                repeat (autodimp k hyp); eauto 3 with slow.\n\n                { apply nt_wf_eq; apply wf_apply; eauto 3 with slow. }\n\n                { prove_alpha_eq4.\n                  introv q; destruct n0;[|destruct n0]; cpx.\n                  apply alphaeqbt_nilv2; auto. }\n\n                exrepnd.\n                inversion k0; subst; allsimpl; cpx.\n\n              + pose proof (reduces_to_prinarg\n                              lib NCbv\n                              n\n                              (mk_integer z)\n                              [bterm [v] (mk_apply fa (mk_var v))]) as h.\n                fold_terms.\n                autodimp h hyp.\n                eapply reduces_to_trans;[exact h|].\n                apply (reduces_to_if_split2\n                         _ _ (mk_apply fa (mk_integer z))).\n\n                { csunf; simpl; unfold apply_bterm, lsubst; simpl; boolvar;\n                  try (complete (provefalse; sp)).\n                  rw @lsubst_aux_trivial_cl_term; auto; simpl.\n                  rw disjoint_singleton_r; auto.\n                  apply alphaeq_preserves_free_vars in aeq1; rw <- aeq1; auto. }\n\n                pose proof (reduces_to_alpha\n                              lib\n                              (mk_apply f (mk_integer z))\n                              (mk_apply fa (mk_integer z))\n                              (mk_integer z0)) as k.\n                repeat (autodimp k hyp).\n\n                { apply nt_wf_eq; apply wf_apply; eauto 3 with slow. }\n\n                { prove_alpha_eq4.\n                  introv q; destruct n0;[|destruct n0]; cpx.\n                  apply alphaeqbt_nilv2; auto. }\n\n                exrepnd.\n                inversion k0; subst; allsimpl; cpx.\n\n              + apply differ3_implies_differ3_alpha.\n                apply differ3_refl; simpl; tcsp.\n            }\n\n            { apply isexc_implies2 in hvf1; exrepnd; subst.\n              applydup @differ3_alpha_exc in r0; eauto 3 with slow;\n              try (complete (simpl; boolvar; tcsp)).\n              apply isexc_implies2 in r2; exrepnd; subst.\n\n              pose proof (compute_step_force_int_bound_exc\n                            lib v b (mk_vbot v) t1 n (oterm Exc l)) as r.\n              repeat (autodimp r hyp); eauto 3 with slow.\n\n              exists (oterm Exc l0) (oterm Exc l); dands; auto.\n\n              - pose proof (reduces_to_prinarg\n                              lib NCbv\n                              (force_int_bound v b t0 (mk_vbot v))\n                              (oterm Exc l0)\n                              [bterm [v] (mk_apply ga (mk_var v))]) as h.\n                fold_terms.\n                autodimp h hyp.\n                { pose proof (reduces_to_prinarg\n                              lib NCbv\n                              t0\n                              (oterm Exc l0)\n                              [bterm [v] (less_bound b (mk_var v) (mk_vbot v))]) as h.\n                  fold_terms.\n                  autodimp h hyp.\n                  eapply reduces_to_trans; eauto 3 with slow. }\n                eapply reduces_to_trans; eauto 3 with slow.\n\n              - pose proof (reduces_to_prinarg\n                              lib NCbv\n                              n\n                              (oterm Exc l)\n                              [bterm [v] (mk_apply fa (mk_var v))]) as h.\n                fold_terms.\n                autodimp h hyp.\n                eapply reduces_to_trans; eauto 3 with slow.\n            }\n\n          - simpl in len.\n            destruct bs2; simpl in len; cpx.\n            simpl in imp.\n            pose proof (imp (bterm [] (oterm (NCan ncan1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            inversion d1 as [? ? ? df2 dg2 d2]; subst; clear d1.\n\n            pose proof (ind (oterm (NCan ncan1) bs1) (oterm (NCan ncan1) bs1) []) as h; clear ind.\n            repeat (autodimp h hyp); tcsp; eauto 3 with slow.\n\n            pose proof (h t2 kk n) as k; clear h.\n            repeat (autodimp k hyp); tcsp.\n\n            { rw @wf_oterm_iff in wt1; allsimpl; repnd.\n              pose proof (wt1 (bterm [] (oterm (NCan ncan1) bs1))) as h.\n              autodimp h hyp. }\n\n            { rw @wf_oterm_iff in wt2; allsimpl; repnd.\n              pose proof (wt2 (bterm [] t2)) as h.\n              autodimp h hyp. }\n\n            { apply if_has_value_like_k_ncan_primarg in hv; auto.\n              exrepnd.\n              apply (has_value_like_k_lt lib j kk); auto. }\n\n            exrepnd.\n\n            exists (oterm (NCan ncan) (bterm [] t :: bs2))\n                   (oterm (NCan ncan) (bterm [] u' :: bs));\n              dands; eauto 3 with slow.\n\n            + apply reduces_to_prinarg; auto.\n            + apply reduces_to_prinarg; auto.\n\n            + unfold differ3_alpha in k1; exrepnd.\n              exists (oterm (NCan ncan) (bterm [] u1 :: bs))\n                     (oterm (NCan ncan) (bterm [] u2 :: bs2));\n                dands.\n\n              * prove_alpha_eq4.\n                introv j; destruct n0; eauto 3 with slow.\n\n              * prove_alpha_eq4.\n                introv j; destruct n0; eauto 3 with slow.\n\n              * apply differ3_oterm; simpl; auto.\n                introv j; dorn j; cpx.\n        }\n\n        { SSCase \"Exc\".\n          csunf comp; allsimpl.\n          apply compute_step_catch_success in comp.\n\n          inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; cpx; clear d.\n          destruct bs2; allsimpl; cpx.\n          pose proof (imp (bterm [] (oterm Exc bs1)) b0) as d1.\n          autodimp d1 hyp.\n          inversion d1 as [? ? ? df2 dg2 d2]; subst; clear d1.\n          inversion d2 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; cpx; clear d2.\n\n          repndors; exrepnd; subst; allsimpl; cpx; allsimpl.\n\n          - pose proof (imp (bterm [] (oterm Exc [bterm [] a', bterm [] e]))\n                            (bterm [] (oterm Exc [x, y]))) as d1; autodimp d1 hyp.\n            pose proof (imp (bterm [] a) x0) as d2; autodimp d2 hyp.\n            pose proof (imp (bterm [v] b0) y0) as d3; autodimp d3 hyp.\n            pose proof (imp1 (bterm [] a') x) as d4; autodimp d4 hyp.\n            pose proof (imp1 (bterm [] e) y) as d5; autodimp d5 hyp.\n            clear imp imp1.\n\n            inversion d1 as [? ? ? df66 dg66 d6]; subst; clear d1.\n            inversion d2 as [? ? ? df77 dg77 d7]; subst; clear d2.\n            inversion d3 as [? ? ? df88 dg88 d8]; subst; clear d3.\n            inversion d4 as [? ? ? df99 dg99 d9]; subst; clear d4.\n            inversion d5 as [? ? ? df10 dg10 d10]; subst; clear d5.\n            repeat match goal with\n                     | [ H : disjoint [] _ |- _ ] => clear H\n                   end.\n\n            inversion d6 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; cpx; clear d6.\n            pose proof (imp1 (bterm [] a') (bterm [] t3)) as d1; autodimp d1 hyp.\n            pose proof (imp1 (bterm [] e) (bterm [] t4)) as d2; autodimp d2 hyp.\n            clear imp1.\n\n            inversion d1 as [? ? ? df33 dg33 d3]; subst; clear d1.\n            inversion d2 as [? ? ? df44 dg44 d4]; subst; clear d2.\n            repeat match goal with\n                     | [ H : disjoint [] _ |- _ ] => clear H\n                   end.\n\n            exists (mk_atom_eq t2 t3 (subst t0 v t4) (mk_exception t3 t4))\n                   (mk_atom_eq a a' (subst b0 v e) (mk_exception a' e));\n              dands; eauto 3 with slow.\n\n            apply differ3_alpha_mk_atom_eq; eauto 4 with slow.\n\n            apply differ3_subst; simpl; eauto 3 with slow.\n\n          - exists (oterm Exc bs3) (oterm Exc bs1); dands; eauto 3 with slow.\n\n            apply reduces_to_if_step; csunf; simpl.\n            unfold compute_step_catch; destruct ncan; tcsp.\n        }\n\n        { SSCase \"Abs\".\n          csunf comp; allsimpl; csunf comp; allsimpl.\n          remember (compute_step_lib lib abs1 bs1) as comp1;\n            symmetry in Heqcomp1.\n          destruct comp1; ginv.\n\n          inversion d as [|?|?|? ? ? len imp]; subst; clear d.\n          destruct bs2; allsimpl; cpx.\n          pose proof (imp (bterm [] (oterm (Abs abs1) bs1)) b0) as d1.\n          autodimp d1 hyp.\n          inversion d1 as [? ? ? df2 sg2 d2]; subst; clear d1.\n          inversion d2 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; cpx; clear d2.\n\n          apply compute_step_lib_success in Heqcomp1; exrepnd; subst.\n\n          assert (differ3_bterms b f g bs1 bs3) as dbs.\n          { unfold differ3_bterms, br_bterms, br_list; auto. }\n\n          pose proof (found_entry_change_bs abs1 oa2 vars rhs lib bs1 correct bs3) as fe2.\n          repeat (autodimp fe2 hyp).\n\n          { apply differ3_bterms_implies_eq_map_num_bvars in dbs; auto. }\n\n          exists\n          (oterm (NCan ncan)\n                 (bterm [] (mk_instance vars bs3 rhs)\n                        :: bs2))\n          (oterm (NCan ncan)\n                 (bterm [] (mk_instance vars bs1 rhs)\n                        :: bs)).\n\n          dands; eauto 3 with slow.\n\n          * apply reduces_to_prinarg.\n            apply reduces_to_if_step.\n            csunf; simpl; unfold on_success.\n            applydup @compute_step_lib_if_found_entry in fe2.\n            rw fe0; auto.\n\n          * pose proof (differ3_mk_instance b f g rhs vars bs1 bs3) as h.\n            repeat (autodimp h hyp); tcsp; GC.\n            { unfold correct_abs in correct; sp. }\n            { allapply @found_entry_implies_matching_entry.\n              allunfold @matching_entry; sp. }\n            { allapply @found_entry_implies_matching_entry.\n              allunfold @matching_entry; sp. }\n            { allunfold @correct_abs; sp. }\n            { allunfold @correct_abs; sp. }\n            unfold differ3_alpha in h.\n            exrepnd.\n\n            exists\n              (oterm (NCan ncan) (bterm [] u1 :: bs))\n              (oterm (NCan ncan) (bterm [] u2 :: bs2)).\n            dands.\n\n            { prove_alpha_eq4.\n              introv j; destruct n;[|destruct n]; try omega; cpx.\n              apply alphaeqbt_nilv2; auto. }\n\n            { prove_alpha_eq4.\n              introv j; destruct n;[|destruct n]; try omega; cpx.\n              apply alphaeqbt_nilv2; auto. }\n\n            { apply differ3_oterm; allsimpl; tcsp.\n              introv j; repndors; cpx. }\n        }\n      }\n\n      { (* fresh case *)\n        csunf comp; allsimpl.\n        apply compute_step_fresh_success in comp; repnd; subst; allsimpl.\n\n        inversion d as [|?|?|? ? ? len1 imp1]; subst; clear d.\n        allsimpl; cpx; allsimpl.\n        pose proof (imp1 (bterm [n] t1) x) as d1; autodimp d1 hyp.\n        clear imp1.\n        inversion d1 as [? ? ? disj11 disj12 d2]; subst; clear d1.\n        allrw disjoint_singleton_l.\n\n        repndors; exrepnd; subst; fold_terms.\n\n        - inversion d2; subst.\n          apply has_value_like_k_fresh_id in hv; sp.\n\n        - applydup @differ3_preserves_isvalue_like in d2; auto.\n          exists (pushdown_fresh n t2) (pushdown_fresh n t1); dands; eauto 3 with slow.\n          { apply reduces_to_if_step.\n            apply compute_step_fresh_if_isvalue_like; auto. }\n          { apply differ3_alpha_pushdown_fresh_isvalue_like; auto. }\n\n        - applydup @differ3_preserves_isnoncan_like in d2; auto;[].\n          allrw app_nil_r.\n\n          pose proof (fresh_atom o (get_utokens t1 ++ get_utokens t2 ++ get_utokens f ++ get_utokens g)) as fa; exrepnd.\n          allrw in_app_iff; allrw not_over_or; repnd.\n          rename x0 into a.\n\n          pose proof (compute_step_subst_utoken lib t1 x [(n,mk_utoken (get_fresh_atom t1))]) as comp'.\n          allrw @get_utokens_sub_cons; allrw @get_utokens_sub_nil; allsimpl.\n          allrw disjoint_singleton_l.\n\n          allrw @wf_fresh_iff.\n\n          repeat (autodimp comp' hyp); try (apply get_fresh_atom_prop); eauto 3 with slow.\n          { apply nr_ut_sub_cons; eauto 3 with slow.\n            intro j; apply get_fresh_atom_prop. }\n          exrepnd.\n          pose proof (comp'0 [(n,mk_utoken a)]) as comp''; clear comp'0.\n          allsimpl.\n          allrw @get_utokens_sub_cons; allrw @get_utokens_sub_nil; allsimpl.\n          allrw disjoint_singleton_l.\n          repeat (autodimp comp'' hyp); exrepnd.\n\n          pose proof (differ3_subst b f g t1 t2 [(n, mk_utoken a)] [(n, mk_utoken a)]) as daeq.\n          repeat (autodimp daeq hyp);\n            try (complete (simpl; apply disjoint_singleton_r; auto));\n            try (complete (apply differ3_subs_refl; simpl; auto));\n            eauto 3 with slow.\n\n          unfold differ3_alpha in daeq; exrepnd.\n\n          pose proof (compute_step_alpha lib (lsubst t1 [(n, mk_utoken a)]) u1 s) as comp'''.\n          repeat (autodimp comp''' hyp); exrepnd; eauto 4 with slow.\n          rename t2' into s'.\n\n          assert (wf_term x) as wfx.\n          { eapply compute_step_preserves_wf;[exact comp2|].\n            allrw @wf_fresh_iff.\n            apply wf_term_subst; eauto 3 with slow. }\n\n          assert (!LIn n (free_vars x)) as ninx.\n          { intro i; apply compute_step_preserves in comp2; repnd; eauto 4 with slow.\n            rw subvars_prop in comp0; apply comp0 in i; clear comp0.\n            apply eqset_free_vars_disjoint in i; allsimpl.\n            allrw in_app_iff; allrw in_remove_nvars; allsimpl; boolvar; allsimpl; tcsp. }\n\n          applydup @alphaeq_preserves_wf_term in daeq0; auto;\n          [|apply lsubst_preserves_wf_term; eauto 3 with slow];[].\n          applydup @alphaeq_preserves_wf_term in daeq2; auto;\n          [|apply lsubst_preserves_wf_term; eauto 3 with slow];[].\n          applydup @compute_step_preserves_wf in comp'''1; auto;[].\n          applydup @alphaeq_preserves_wf_term_inv in comp'''0; auto;[].\n\n          pose proof (ind t1 u1 [n]) as q; clear ind.\n          repeat (autodimp q hyp).\n          { apply alpha_eq_preserves_osize in daeq0; rw <- daeq0; allrw @fold_subst.\n            rw @simple_osize_subst; eauto 3 with slow. }\n          pose proof (q u2 kk s') as ih; clear q.\n          repeat (autodimp ih hyp); fold_terms.\n          { eapply alphaeq_preserves_has_value_like_k;[|exact comp'''0|]; eauto 3 with slow.\n            eapply alphaeq_preserves_has_value_like_k;[|apply alpha_eq_sym;exact comp''0|]; eauto 4 with slow.\n            pose proof (has_value_like_k_ren_utokens\n                          lib\n                          kk\n                          (lsubst w [(n, mk_utoken (get_fresh_atom t1))])\n                          [(get_fresh_atom t1,a)]) as hvl.\n            allsimpl.\n            allrw disjoint_singleton_l; allrw in_remove.\n            repeat (autodimp hvl hyp); eauto 3 with slow.\n            { intro k; repnd.\n              apply get_utokens_lsubst_subset in k; unfold get_utokens_sub in k; allsimpl.\n              allrw in_app_iff; allsimpl; repndors; tcsp. }\n            { eapply alphaeq_preserves_has_value_like_k;[|exact comp'1|]; eauto 3 with slow.\n              apply (has_value_like_k_fresh_implies lib kk (get_fresh_atom t1)) in hv; auto;\n              [|apply wf_subst_utokens; eauto 3 with slow\n               |intro i; apply get_utokens_subst_utokens_subset in i; allsimpl;\n                unfold get_utokens_utok_ren in i; allsimpl; allrw app_nil_r;\n                rw in_remove in i; repnd;\n                apply compute_step_preserves_utokens in comp2; eauto 3 with slow; apply comp2 in i;\n                apply get_utokens_subst in i; allsimpl; boolvar; tcsp].\n              pose proof (simple_subst_subst_utokens_aeq x (get_fresh_atom t1) n) as h.\n              repeat (autodimp h hyp).\n              eapply alphaeq_preserves_has_value_like_k in h;[exact h| |]; eauto 4 with slow.\n            }\n            rw @lsubst_ren_utokens in hvl; allsimpl; fold_terms.\n            unfold ren_atom in hvl; allsimpl; boolvar; tcsp.\n            rw @ren_utokens_trivial in hvl; simpl; auto.\n            apply disjoint_singleton_l; intro i; apply comp'4 in i; apply get_fresh_atom_prop in i; sp.\n          }\n          exrepnd.\n\n          pose proof (reduces_to_alpha lib u2 (lsubst t2 [(n, mk_utoken a)]) t) as r1.\n          repeat (autodimp r1 hyp); eauto 3 with slow.\n          exrepnd.\n\n          pose proof (reduces_to_change_utok_sub\n                        lib t2 t2' [(n,mk_utoken a)] [(n,mk_utoken (get_fresh_atom t2))]) as r1'.\n          allrw @get_utokens_sub_cons; allrw @get_utokens_sub_nil; allsimpl.\n          allrw disjoint_singleton_l.\n          repeat (autodimp r1' hyp); try (apply get_fresh_atom_prop); eauto 3 with slow.\n          { apply nr_ut_sub_cons; eauto 3 with slow.\n            intro j; apply get_fresh_atom_prop. }\n          exrepnd.\n          allrw disjoint_singleton_l.\n          fold_terms; allrw @fold_subst.\n\n          pose proof (reduces_to_fresh lib t2 s0 n) as q; simpl in q.\n          repeat (autodimp q hyp).\n          exrepnd.\n\n          (* 1st exists *)\n          exists (mk_fresh n z).\n\n          assert (!LIn a (get_utokens w)) as niaw.\n          { intro k; apply comp'4 in k; sp. }\n\n          pose proof (alpha_eq_subst_utokens\n                        x (subst w n (mk_utoken (get_fresh_atom t1)))\n                        [(get_fresh_atom t1, mk_var n)]\n                        [(get_fresh_atom t1, mk_var n)]) as aeqs.\n          repeat (autodimp aeqs hyp); eauto 3 with slow.\n          pose proof (simple_alphaeq_subst_utokens_subst\n                        w n (get_fresh_atom t1)) as aeqs1.\n          autodimp aeqs1 hyp.\n          eapply alpha_eq_trans in aeqs1;[|exact aeqs]; clear aeqs.\n\n          pose proof (reduces_to_alpha lib s' (subst w n (mk_utoken a)) u') as raeq.\n          repeat (autodimp raeq hyp); eauto 3 with slow; exrepnd;[].\n          rename t2'0 into u''.\n\n          assert (wf_term w) as wfw.\n          { allrw @wf_fresh_iff.\n            apply compute_step_preserves_wf in comp2;\n              [|apply wf_term_subst;eauto 3 with slow].\n            apply alphaeq_preserves_wf_term in comp'1; auto.\n            apply lsubst_wf_term in comp'1; auto.\n          }\n\n          pose proof (reduces_to_fresh2 lib w u'' n a) as rf.\n          repeat (autodimp rf hyp); exrepnd.\n\n          pose proof (reduces_to_alpha\n                        lib\n                        (mk_fresh n w)\n                        (mk_fresh n (subst_utokens x [(get_fresh_atom t1, mk_var n)]))\n                        (mk_fresh n z0)) as r'.\n          repeat (autodimp r' hyp).\n          { apply nt_wf_fresh; eauto 3 with slow. }\n          { apply implies_alpha_eq_mk_fresh; eauto 3 with slow. }\n          exrepnd.\n          rename t2'0 into f'.\n\n          (* 2nd exists *)\n          exists f'; dands; auto.\n          eapply differ3_alpha_l;[apply alpha_eq_sym; exact r'0|].\n          apply differ3_alpha_mk_fresh; auto.\n          eapply differ3_alpha_l;[exact rf0|].\n          eapply differ3_alpha_r;[|apply alpha_eq_sym; exact q0].\n          eapply differ3_alpha_l;[apply alpha_eq_sym;apply alpha_eq_subst_utokens_same;exact raeq0|].\n          eapply differ3_alpha_r;[|apply alpha_eq_sym;apply alpha_eq_subst_utokens_same;exact r1'1].\n\n          pose proof (simple_alphaeq_subst_utokens_subst w0 n (get_fresh_atom t2)) as aeqsu.\n          autodimp aeqsu hyp.\n          { intro j; apply r1'4 in j; apply get_fresh_atom_prop in j; sp. }\n\n          eapply differ3_alpha_r;[|apply alpha_eq_sym;exact aeqsu];clear aeqsu.\n\n          apply (alpha_eq_subst_utokens_same _ _ [(a, mk_var n)]) in r1'0.\n          pose proof (simple_alphaeq_subst_utokens_subst w0 n a) as aeqsu.\n          autodimp aeqsu hyp.\n\n          eapply differ3_alpha_r;[|exact aeqsu];clear aeqsu.\n          eapply differ3_alpha_r;[|exact r1'0].\n          eapply differ3_alpha_r;[|apply alpha_eq_subst_utokens_same; exact r0].\n          apply differ3_alpha_subst_utokens; simpl; auto; allrw disjoint_singleton_r; auto.\n      }\n\n    + SCase \"Exc\".\n      csunf comp; allsimpl; ginv.\n\n      inversion d as [|?|?|? ? ? ni len imp]; subst; allsimpl; cpx; clear d.\n\n      exists (oterm Exc bs2) (oterm Exc bs); dands; eauto 3 with slow.\n\n    + SCase \"Abs\".\n      csunf comp; allsimpl.\n\n      inversion d as [|?|?|? ? ? ni len imp]; subst; clear d.\n\n      apply compute_step_lib_success in comp; exrepnd; subst.\n\n      assert (differ3_bterms b f g bs bs2) as dbs.\n      { unfold differ3_bterms, br_bterms, br_list; auto. }\n\n      pose proof (found_entry_change_bs abs oa2 vars rhs lib bs correct bs2) as fe2.\n      repeat (autodimp fe2 hyp).\n\n      { apply differ3_bterms_implies_eq_map_num_bvars in dbs; auto. }\n\n      exists (mk_instance vars bs2 rhs) (mk_instance vars bs rhs).\n\n      dands; eauto 3 with slow.\n\n      * apply reduces_to_if_step.\n        csunf; simpl; unfold on_success.\n        applydup @compute_step_lib_if_found_entry in fe2.\n        rw fe0; auto.\n\n      * pose proof (differ3_mk_instance b f g rhs vars bs bs2) as h.\n        repeat (autodimp h hyp); tcsp; GC.\n        { unfold correct_abs in correct; sp. }\n        { allapply @found_entry_implies_matching_entry.\n          allunfold @matching_entry; sp. }\n        { allapply @found_entry_implies_matching_entry.\n          allunfold @matching_entry; sp. }\n        { allunfold @correct_abs; sp. }\n        { allunfold @correct_abs; sp. }\nQed.\n\n(*\nLemma isvalue_like_except_implies_isvalue_like {o} :\n  forall a (t : @NTerm o),\n    isvalue_like_except a t\n    -> isvalue_like t.\nProof.\n  introv isv.\n  unfold isvalue_like_except in isv; sp.\nQed.\nHint Resolve isvalue_like_except_implies_isvalue_like : slow.\n\nLemma alpha_eq_preserves_isvalue_like_except {o} :\n  forall a (t1 t2 : @NTerm o),\n    alpha_eq t1 t2\n    -> isvalue_like_except a t1\n    -> isvalue_like_except a t2.\nProof.\n  introv aeq isv.\n  allunfold @isvalue_like_except; repnd.\n  applydup @alpha_eq_preserves_isvalue_like in aeq; auto.\n  dands; auto.\n  intro k.\n  apply isnexc_implies in k; exrepnd; subst.\n  inversion aeq; subst; allsimpl; boolvar; ginv; tcsp.\nQed.\n*)\n\nLemma comp_force_int3_aux {o} :\n  forall lib f g (t1 t2 : @NTerm o) b u,\n    isprog f\n    -> isprog g\n    -> wf_term t1\n    -> wf_term t2\n    -> agree_upto_b lib b f g\n    -> differ3 b f g t1 t2\n    -> isvalue_like u\n    -> reduces_to lib t1 u\n    -> {v : NTerm & reduces_to lib t2 v # differ3_alpha b f g u v}.\nProof.\n  introv ispf ispg wt1 wt2 agree d isv comp.\n  unfold reduces_to in comp; exrepnd.\n  revert t1 t2 u wt1 wt2 d isv comp0.\n  induction k as [n ind] using comp_ind_type; introv wt1 wt2 d isv r.\n  destruct n as [|k]; allsimpl.\n\n  - allrw @reduces_in_atmost_k_steps_0; subst.\n    exists t2; dands; eauto 3 with slow.\n\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n\n    pose proof (comp_force_int_step3 lib b f g t1 t2 k u0) as h.\n    repeat (autodimp h hyp).\n\n    { exists u; unfold computes_to_val_like_in_max_k_steps; sp. }\n\n    { introv l' w1 w2 i' r' d'.\n      apply (ind m l' t0 t3); auto. }\n\n    exrepnd.\n\n    pose proof (reduces_in_atmost_k_steps_if_reduces_to\n                  lib k u0 u' u) as h'.\n    repeat (autodimp h' hyp); eauto 3 with slow.\n    exrepnd.\n\n    unfold differ3_alpha in h1; exrepnd.\n\n    applydup @preserve_nt_wf_compute_step in r1; eauto 3 with slow.\n    applydup @reduces_to_preserves_wf in h2; eauto 3 with slow.\n    applydup @reduces_to_preserves_wf in h0; eauto 3 with slow.\n    applydup @alphaeq_preserves_wf_term in h4; eauto 3 with slow.\n\n    pose proof (reduces_in_atmost_k_steps_alpha\n                  lib u' u1) as h''.\n    repeat (autodimp h'' hyp); eauto 3 with slow.\n\n    pose proof (h'' k' u) as h'''; clear h''.\n    autodimp h''' hyp; exrepnd.\n\n    pose proof (ind k') as h.\n    autodimp h hyp;[omega|].\n    pose proof (h u1 u2 t2') as r'; clear h.\n    repeat (autodimp r' hyp); eauto 3 with slow.\n\n    exrepnd.\n\n    pose proof (reduces_to_steps_alpha lib u2 t v) as r'.\n    repeat (autodimp r' hyp); eauto 3 with slow.\n    exrepnd.\n    exists u3; dands; eauto 3 with slow.\n\n    { eapply reduces_to_trans; eauto. }\n\n    { allunfold @differ3_alpha; exrepnd.\n      exists u4 u5; dands; eauto 3 with slow. }\nQed.\n\nLemma comp_force_int3 {o} :\n  forall lib f g (t1 t2 : @NTerm o) b z,\n    isprog f\n    -> isprog g\n    -> wf_term t1\n    -> wf_term t2\n    -> agree_upto_b lib b f g\n    -> differ3 b f g t1 t2\n    -> reduces_to lib t1 (mk_integer z)\n    -> reduces_to lib t2 (mk_integer z).\nProof.\n  introv ispf ispg wt1 wt2 agree d comp.\n  pose proof (comp_force_int3_aux lib f g t1 t2 b (mk_integer z)) as h.\n  repeat (autodimp h hyp); eauto 3 with slow.\n\n  exrepnd.\n  apply differ3_alpha_integer in h0; subst; auto.\nQed.\n\nLemma differ_app_F3 {o} :\n  forall b (F : @NTerm o) x f g,\n    !LIn x (free_vars f)\n    -> !LIn x (free_vars g)\n    -> disjoint (bound_vars F) (free_vars f)\n    -> disjoint (bound_vars F) (free_vars g)\n    -> differ3\n         b\n         f g\n         (force_int_bound_F x b F f (mk_vbot x))\n         (force_int_bound_F x b F g (mk_vbot x)).\nProof.\n  introv ni1 ni2 df dg.\n  constructor; simpl; tcsp.\n  introv i; dorn i;[|dorn i]; cpx.\n  - constructor; eauto 3 with slow.\n  - constructor; auto; constructor; simpl; tcsp.\n    introv i; dorn i; cpx.\n    constructor; allrw disjoint_singleton_l; auto; constructor; simpl; auto.\nQed.\n\nLemma comp_force_int_app_F3 {o} :\n  forall lib (F f g : @NTerm o) x z b,\n    wf_term F\n    -> isprog f\n    -> isprog g\n    -> !LIn x (free_vars f)\n    -> !LIn x (free_vars g)\n    -> disjoint (bound_vars F) (free_vars f)\n    -> disjoint (bound_vars F) (free_vars g)\n    -> agree_upto_b lib b f g\n    -> reduces_to\n         lib\n         (force_int_bound_F x b F f (mk_vbot x))\n         (mk_integer z)\n    -> reduces_to\n         lib\n         (force_int_bound_F x b F g (mk_vbot x))\n         (mk_integer z).\nProof.\n  introv wF wf wg ni1 ni2 df dg agree r.\n\n  apply (comp_force_int3 _ f g (force_int_bound_F x b F f (mk_vbot x)) _ b); eauto 4 with slow.\n\n  apply differ_app_F3; auto; allrw; 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/continuity3_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.2821662430492542}}
{"text": "From CertiCoq.Plugin Require Import CertiCoq.\n\nRequire Import ExtLib.Structures.Monad.\nRequire Import String.\n\nInductive itree (E : Type -> Type) (R : Type) : Type :=\n| Ret (r : R)\n| Vis {X : Type} (e : E X) (k : X -> itree E R)\n| Tau (t : itree E R).\n\nArguments Ret [E R].\nArguments Vis [E R] {X}.\nArguments Tau [E R].\n\nDefinition trigger {E : Type -> Type} {A : Type} (e : E A) : itree E A :=\n  Vis e (fun x => Ret x).\n\nFixpoint ibind {E : Type -> Type} {A B : Type}\n               (t : itree E A) (k : A -> itree E B) : itree E B :=\n  match t with\n  | Ret r => k r\n  | Vis _ e h => Vis e (fun x => ibind (h x) k)\n  | Tau t' => Tau (ibind t' k)\n  end.\n\nInstance Monad_itree {E} : Monad (itree E) :=\n  {| ret := fun _ x => Ret x ; bind := @ibind _ |}.\n\nInductive console : Type -> Type :=\n| print_string : string -> console unit\n| scan_string : console string.\n\nImport MonadNotation.\nOpen Scope monad_scope.\n\nDefinition prog : itree console unit :=\n  trigger (print_string \"What's your name?\") ;;\n  name <- trigger scan_string ;;\n  trigger (print_string (\"Hello \" ++ name ++ \"!\")).\n\nCertiCoq Generate Glue -file \"glue\" [itree, console, string, unit].\nCertiCoq Compile prog.\n", "meta": {"author": "CertiCoq", "repo": "VeriFFI", "sha": "ebbb54ef79805ab47af1898fb33ccc58c3890614", "save_path": "github-repos/coq/CertiCoq-VeriFFI", "path": "github-repos/coq/CertiCoq-VeriFFI/VeriFFI-ebbb54ef79805ab47af1898fb33ccc58c3890614/examples/incomplete/io/tests.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2821370667749739}}
{"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\n(** This proof uses the\n    #<a href=\"http://www.chargueraud.org/softs/tlc/\">TLC</a>#\n    Coq library by Arthur Chargueraud. *)\n\nSet Implicit Arguments.\n\nRequire Import TLC.LibLN.\nRequire Import String.\n\nRequire Export TLC.LibLN.\n\nParameter typ_label: Set.\nParameter trm_label: Set.\n\n(** * Abstract Syntax *)\n\n(** *** Variables ([x], [y], [z])\n    The proof represents variables using the\n    #<a href=\"http://www.chargueraud.org/softs/ln/\">locally nameless representation</a>#:\n    - [avar_b n] represents a variable using the de Bruijn index [n];\n    - [avar_f x] represents a free variable with name [x].\n    de Bruijn-indexed variables represent bound variables, whereas named variables represent free variables\n    that are in the evaluation context/type environment.  *)\nInductive avar : Set :=\n  | avar_b : nat -> avar\n  | avar_f : var -> avar.\n\n(** *** Term and type members\n        Type member labels ([A], [B], [C]) and term (field) member labels ([a], [b], [c]).  *)\nInductive label: Set :=\n| label_typ: typ_label -> label\n| label_trm: trm_label -> label.\n\n(** *** Types\n    Types ([typ], [S], [T], [U]) and type declarations ([dec], [D]):\n    - [typ_top] represents [top];\n    - [typ_bot] represents [bottom];\n    - [typ_rcd d] represents a record type [d], where [d] is either a type or field declaration;\n    - [typ_and T U] represents an intersection type [T /\\ U];\n    - [typ_sel x A] represents type selection [x.A];\n    - [typ_bnd T] represents a recursive type [mu(x: T)]; however, since [x] is bound in the recursive type,\n      it is referred to in [T] using the de Bruijn index 0, and is therefore omitted from the type representation;\n      we will denote recursive types as [mu(T)];\n    - [typ_all T U] represents the dependent function type [forall(x: T)U]; as in the previous case,\n      [x] represents a variable bound in [U], and is therefore omitted from the representation;\n      we will denote function types as [forall(T)U]. *)\nInductive typ : Set :=\n  | typ_top  : typ\n  | typ_bot  : typ\n  | typ_rcd  : dec -> typ\n  | typ_and  : typ -> typ -> typ\n  | typ_sel  : avar -> typ_label -> typ\n  | typ_bnd  : typ -> typ\n  | typ_all  : typ -> typ -> typ\n(**\n  - [dec_typ A S T] represents a type declaraion [{A: S..T}];\n  - [dec_trm a T] represents a field declaration [{a: T}] . *)\nwith dec : Set :=\n  | dec_typ  : typ_label -> typ -> typ -> dec\n  | dec_trm  : trm_label -> typ -> dec.\n\n(** *** Terms\n  Terms ([trm], [t], [u]), values ([val], [v]),\n   member definitions ([def], [d] and [defs], [ds]):\n  - [trm_var x] represents a variable [x];\n  - [trm_val v] represents a value [v];\n  - [trm_sel x a] represents a field selection [x.a];\n  - [trm_app x y] represents a function application [x y];\n  - [trm_let t u] represents a let binding [let x = t in u]; since x is bound in [u],\n    it is referred to in [u] using the de Bruijn index 0, and is therefore omitted from\n    the let-term representation; we will denote let terms as [let t in u]. *)\nInductive trm : Set :=\n  | trm_var  : avar -> trm\n  | trm_val  : val -> trm\n  | trm_sel  : avar -> trm_label -> trm\n  | trm_app  : avar -> avar -> trm\n  | trm_let  : trm -> trm -> trm\n(**\n  - [val_new T ds] represents the object [nu(x: T)ds]; the variable [x] is bound in [T]\n    and [ds] and is omitted from the representation;\n    we will denote new object definitions as [nu(T)ds];\n  - [val_lambda T t] represents a function [lambda(x: T)t]; again, [x] is bound in [t]\n    and is omitted;\n    we will denote lambda terms as [lambda(T)t. *)\nwith val : Set :=\n  | val_new  : typ -> defs -> val\n  | val_lambda : typ -> trm -> val\n(**\n  - [def_typ A T] represents a type-member definition [{A = T}];\n  - [def_trm a t] represents a field definition [{a = t}]; *)\nwith def : Set :=\n  | def_typ  : typ_label -> typ -> def\n  | def_trm  : trm_label -> trm -> def\n(**\n  [defs] represents a list of definitions that are part of an intersection\n  - [defs_nil] represents the empty list;\n  - [defs_cons d ds] represents a concatenation of the definition [d] to the definitions [ds]. *)\nwith defs : Set :=\n  | defs_nil : defs\n  | defs_cons : defs -> def -> defs.\n\n(** Helper functions to retrieve labels of declarations and definitions *)\n\nDefinition label_of_def(d: def): label := match d with\n| def_typ L _ => label_typ L\n| def_trm m _ => label_trm m\nend.\n\nDefinition label_of_dec(D: dec): label := match D with\n| dec_typ L _ _ => label_typ L\n| dec_trm m _   => label_trm m\nend.\n\nFixpoint get_def(l: label)(ds: defs): option def :=\nmatch ds with\n| defs_nil => None\n| defs_cons ds' d => If label_of_def d = l then Some d else get_def l ds'\nend.\n\nDefinition defs_has(ds: defs)(d: def) := get_def (label_of_def d) ds = Some d.\n\nDefinition defs_hasnt(ds: defs)(l: label) := get_def l ds = None.\n\n(** Typing environment ([G]) *)\nDefinition ctx := env typ.\n\n(** A stack, represented as the sequence of variable-to-value\n    let bindings, [(let x = v in)*], that is represented as a value environment\n    which maps variables to values.\n    The operational semantics will be defined in terms of pairs [(s, t)] where\n    [s] is a stack and [t] is a term.\n    For example, the term [let x1 = v1 in let x2 = v2 in t] is represented as\n    [({(x1 = v1), (x2 = v2)}, t)].\n    *)\nDefinition sta := env val.\n\n(** * Opening *)\n(** Opening takes a bound variable that is represented with a de Bruijn index [k]\n    and replaces it by a named variable [u].\n    The following functions define opening on variables, types, declarations, terms,\n    values, and definitions.\n\n    We will denote an identifier [X] opened with a variable [y] as [X^y]. *)\n\nDefinition open_rec_avar (k: nat) (u: var) (a: avar) : avar :=\n  match a with\n  | avar_b i => If k = i then avar_f u else avar_b i\n  | avar_f x => avar_f x\n  end.\n\n\nFixpoint open_rec_typ (k: nat) (u: var) (T: typ): typ :=\n  match T with\n  | typ_top        => typ_top\n  | typ_bot        => typ_bot\n  | typ_rcd D      => typ_rcd (open_rec_dec k u D)\n  | typ_and T1 T2  => typ_and (open_rec_typ k u T1) (open_rec_typ k u T2)\n  | typ_sel x L    => typ_sel (open_rec_avar k u x) L\n  | typ_bnd T      => typ_bnd (open_rec_typ (S k) u T)\n  | typ_all T1 T2  => typ_all (open_rec_typ k u T1) (open_rec_typ (S k) u T2)\n  end\nwith open_rec_dec (k: nat) (u: var) (D: dec): dec :=\n  match D with\n  | dec_typ L T U => dec_typ L (open_rec_typ k u T) (open_rec_typ k u U)\n  | dec_trm m T   => dec_trm m (open_rec_typ k u T)\n  end.\n\nFixpoint open_rec_trm (k: nat) (u: var) (t: trm): trm :=\n  match t with\n  | trm_var a      => trm_var (open_rec_avar k u a)\n  | trm_val v      => trm_val (open_rec_val k u v)\n  | trm_sel v m    => trm_sel (open_rec_avar k u v) m\n  | trm_app f a    => trm_app (open_rec_avar k u f) (open_rec_avar k u a)\n  | trm_let t1 t2  => trm_let (open_rec_trm k u t1) (open_rec_trm (S k) u t2)\n  end\nwith open_rec_val (k: nat) (u: var) (v: val): val :=\n  match v with\n  | val_new T ds   => val_new (open_rec_typ (S k) u T) (open_rec_defs (S k) u ds)\n  | val_lambda T e => val_lambda (open_rec_typ k u T) (open_rec_trm (S k) u e)\n  end\nwith open_rec_def (k: nat) (u: var) (d: def): def :=\n  match d with\n  | def_typ L T => def_typ L (open_rec_typ k u T)\n  | def_trm m e => def_trm m (open_rec_trm k u e)\n  end\nwith open_rec_defs (k: nat) (u: var) (ds: defs): defs :=\n  match ds with\n  | defs_nil       => defs_nil\n  | defs_cons tl d => defs_cons (open_rec_defs k u tl) (open_rec_def k u d)\n  end.\n\nDefinition open_avar u a := open_rec_avar  0 u a.\nDefinition open_typ  u T := open_rec_typ   0 u T.\nDefinition open_dec  u D := open_rec_dec   0 u D.\nDefinition open_trm  u e := open_rec_trm   0 u e.\nDefinition open_val  u v := open_rec_val   0 u v.\nDefinition open_def  u d := open_rec_def   0 u d.\nDefinition open_defs u l := open_rec_defs  0 u l.\nHint Unfold open_avar open_typ open_dec open_trm open_val open_def open_defs.\n\n(** * Free variables\n      Functions that retrieve the free variables of a symbol. *)\n\n(** Free variable in a variable. *)\nDefinition fv_avar (a: avar) : vars :=\n  match a with\n  | avar_b i => \\{}\n  | avar_f x => \\{x}\n  end.\n\n(** Free variables in a type or declaration. *)\nFixpoint fv_typ (T: typ) : vars :=\n  match T with\n  | typ_top        => \\{}\n  | typ_bot        => \\{}\n  | typ_rcd D      => (fv_dec D)\n  | typ_and T U    => (fv_typ T) \\u (fv_typ U)\n  | typ_sel x L    => (fv_avar x)\n  | typ_bnd T      => (fv_typ T)\n  | typ_all T1 T2  => (fv_typ T1) \\u (fv_typ T2)\n  end\nwith fv_dec (D: dec) : vars :=\n  match D with\n  | dec_typ L T U => (fv_typ T) \\u (fv_typ U)\n  | dec_trm m T   => (fv_typ T)\n  end.\n\n(** Free variables in a term, value, or definition. *)\nFixpoint fv_trm (t: trm) : vars :=\n  match t with\n  | trm_var a       => (fv_avar a)\n  | trm_val v        => (fv_val v)\n  | trm_sel x m      => (fv_avar x)\n  | trm_app f a      => (fv_avar f) \\u (fv_avar a)\n  | trm_let t1 t2    => (fv_trm t1) \\u (fv_trm t2)\n  end\nwith fv_val (v: val) : vars :=\n  match v with\n  | val_new T ds    => (fv_typ T) \\u (fv_defs ds)\n  | val_lambda T e  => (fv_typ T) \\u (fv_trm e)\n  end\nwith fv_def (d: def) : vars :=\n  match d with\n  | def_typ _ T     => (fv_typ T)\n  | def_trm _ t     => (fv_trm t)\n  end\nwith fv_defs(ds: defs) : vars :=\n  match ds with\n  | defs_nil         => \\{}\n  | defs_cons tl d   => (fv_defs tl) \\u (fv_def d)\n  end.\n\n(** Free variables in the range (types) of a context *)\nDefinition fv_ctx_types(G: ctx): vars := (fv_in_values (fun T => fv_typ T) G).\nDefinition fv_sta_vals(s: sta): vars := (fv_in_values (fun v => fv_val v) s).\n\n(** * Typing Rules *)\n\nReserved Notation \"G '⊢' t ':' T\" (at level 40, t at level 59).\nReserved Notation \"G '⊢' T '<:' U\" (at level 40, T at level 59).\nReserved Notation \"G '/-' d : D\" (at level 40, d at level 59).\nReserved Notation \"G '/-' ds :: D\" (at level 40, ds at level 59).\n\n(** ** Term typing [G ⊢ t: T] *)\nInductive ty_trm : ctx -> trm -> typ -> Prop :=\n\n(** [G(x) = T]  #<br>#\n    [――――――――]  #<br>#\n    [G ⊢ x: T]  *)\n| ty_var : forall G x T,\n    binds x T G ->\n    G ⊢ trm_var (avar_f x) : T\n\n(** [G, x: T ⊢ t^x: U^x]     #<br>#\n    [x fresh]                #<br>#\n    [――――――――――――――――――――――] #<br>#\n    [G ⊢ lambda(T)t: forall(T)U]      *)\n| ty_all_intro : forall L G T t U,\n    (forall x, x \\notin L ->\n      G & x ~ T ⊢ open_trm x t : open_typ x U) ->\n    G ⊢ trm_val (val_lambda T t) : typ_all T U\n\n(** [G ⊢ x: forall(S)T] #<br>#\n    [G ⊢ z: S]     #<br>#\n    [――――――――――――] #<br>#\n    [G ⊢ x z: T^z]     *)\n| ty_all_elim : forall G x z S T,\n    G ⊢ trm_var (avar_f x) : typ_all S T ->\n    G ⊢ trm_var (avar_f z) : S ->\n    G ⊢ trm_app (avar_f x) (avar_f z) : open_typ z T\n\n(** [G, x: T^x ⊢ ds^x :: T^x]  #<br>#\n    [x fresh]                  #<br>#\n    [―――――――――――――――――――――――]  #<br>#\n    [G ⊢ nu(T)ds :: mu(T)]          *)\n| ty_new_intro : forall L G T ds,\n    (forall x, x \\notin L ->\n      G & (x ~ open_typ x T) /- open_defs x ds :: open_typ x T) ->\n    G ⊢ trm_val (val_new T ds) : typ_bnd T\n\n(** [G ⊢ x: {a: T}] #<br>#\n    [―――――――――――――] #<br>#\n    [G ⊢ x.a: T]        *)\n| ty_new_elim : forall G x a T,\n    G ⊢ trm_var (avar_f x) : typ_rcd (dec_trm a T) ->\n    G ⊢ trm_sel (avar_f x) a : T\n\n(** [G ⊢ t: T]          #<br>#\n    [G, x: T ⊢ u^x: U]  #<br>#\n    [x fresh]           #<br>#\n    [―――――――――――――――――] #<br>#\n    [G ⊢ let t in u: U]     *)\n| ty_let : forall L G t u T U,\n    G ⊢ t : T ->\n    (forall x, x \\notin L ->\n      G & x ~ T ⊢ open_trm x u : U) ->\n    G ⊢ trm_let t u : U\n\n(** [G ⊢ x: T^x]   #<br>#\n    [――――――――――――] #<br>#\n    [G ⊢ x: mu(T)]     *)\n| ty_rec_intro : forall G x T,\n    G ⊢ trm_var (avar_f x) : open_typ x T ->\n    G ⊢ trm_var (avar_f x) : typ_bnd T\n\n(** [G ⊢ x: mu(T)] #<br>#\n    [――――――――――――] #<br>#\n    [G ⊢ x: T^x]   *)\n| ty_rec_elim : forall G x T,\n    G ⊢ trm_var (avar_f x) : typ_bnd T ->\n    G ⊢ trm_var (avar_f x) : open_typ x T\n\n(** [G ⊢ x: T]     #<br>#\n    [G ⊢ x: U]     #<br>#\n    [――――――――――――] #<br>#\n    [G ⊢ x: T /\\ U]     *)\n| ty_and_intro : forall G x T U,\n    G ⊢ trm_var (avar_f x) : T ->\n    G ⊢ trm_var (avar_f x) : U ->\n    G ⊢ trm_var (avar_f x) : typ_and T U\n\n(** [G ⊢ t: T]   #<br>#\n    [G ⊢ T <: U] #<br>#\n    [――――――――――] #<br>#\n    [G ⊢ t: U]   *)\n| ty_sub : forall G t T U,\n    G ⊢ t : T ->\n    G ⊢ T <: U ->\n    G ⊢ t : U\nwhere \"G '⊢' t ':' T\" := (ty_trm G t T)\n\n(** ** Single-definition typing [G ⊢ d: D] *)\nwith ty_def : ctx -> def -> dec -> Prop :=\n(** [G ⊢ {A = T}: {A: T..T}]   *)\n| ty_def_typ : forall G A T,\n    G /- def_typ A T : dec_typ A T T\n\n(** [G ⊢ t: T]            #<br>#\n    [―――――――――――――――――――] #<br>#\n    [G ⊢ {a = t}: {a: T}] *)\n| ty_def_trm : forall G a t T,\n    G ⊢ t : T ->\n    G /- def_trm a t : dec_trm a T\nwhere \"G '/-' d ':' D\" := (ty_def G d D)\n\n(** ** Multiple-definition typing [G ⊢ ds :: T] *)\nwith ty_defs : ctx -> defs -> typ -> Prop :=\n(** [G ⊢ d: D]              #<br>#\n    [―――――――――――――――――――――] #<br>#\n    [G ⊢ d ++ defs_nil : D] *)\n| ty_defs_one : forall G d D,\n    G /- d : D ->\n    G /- defs_cons defs_nil d :: typ_rcd D\n\n(** [G ⊢ ds :: T]         #<br>#\n    [G ⊢ d: D]            #<br>#\n    [d \\notin ds]         #<br>#\n    [―――――――――――――――――――] #<br>#\n    [G ⊢ ds ++ d : T /\\ D] *)\n| ty_defs_cons : forall G ds d T D,\n    G /- ds :: T ->\n    G /- d : D ->\n    defs_hasnt ds (label_of_def d) ->\n    G /- defs_cons ds d :: typ_and T (typ_rcd D)\nwhere \"G '/-' ds '::' T\" := (ty_defs G ds T)\n\n(** ** Subtyping [G ⊢ T <: U] *)\nwith subtyp : ctx -> typ -> typ -> Prop :=\n\n(** [G ⊢ T <: top] *)\n| subtyp_top: forall G T,\n    G ⊢ T <: typ_top\n\n(** [G ⊢ bot <: T] *)\n| subtyp_bot: forall G T,\n    G ⊢ typ_bot <: T\n\n(** [G ⊢ T <: T] *)\n| subtyp_refl: forall G T,\n    G ⊢ T <: T\n\n(** [G ⊢ S <: T]     #<br>#\n    [G ⊢ T <: U]     #<br>#\n    [――――――――――]     #<br>#\n    [G ⊢ S <: U]         *)\n| subtyp_trans: forall G S T U,\n    G ⊢ S <: T ->\n    G ⊢ T <: U ->\n    G ⊢ S <: U\n\n(** [G ⊢ T /\\ U <: T] *)\n| subtyp_and11: forall G T U,\n    G ⊢ typ_and T U <: T\n\n(** [G ⊢ T /\\ U <: U] *)\n| subtyp_and12: forall G T U,\n    G ⊢ typ_and T U <: U\n\n(** [G ⊢ S <: T]       #<br>#\n    [G ⊢ S <: U]       #<br>#\n    [――――――――――――――]   #<br>#\n    [G ⊢ S <: T /\\ U]          *)\n| subtyp_and2: forall G S T U,\n    G ⊢ S <: T ->\n    G ⊢ S <: U ->\n    G ⊢ S <: typ_and T U\n\n(** [G ⊢ T <: U]           #<br>#\n    [――――――――――――――――――――] #<br>#\n    [G ⊢ {a: T} <: {a: U}] *)\n| subtyp_fld: forall G a T U,\n    G ⊢ T <: U ->\n    G ⊢ typ_rcd (dec_trm a T) <: typ_rcd (dec_trm a U)\n\n(** [G ⊢ S2 <: S1]                   #<br>#\n    [G ⊢ T1 <: T2]                   #<br>#\n    [――――――――――――――――――――――――――――――] #<br>#\n    [G ⊢ {A: S1..T1} <: {A: S2..T2}]     *)\n| subtyp_typ: forall G A S1 T1 S2 T2,\n    G ⊢ S2 <: S1 ->\n    G ⊢ T1 <: T2 ->\n    G ⊢ typ_rcd (dec_typ A S1 T1) <: typ_rcd (dec_typ A S2 T2)\n\n(** [G ⊢ x: {A: S..T}] #<br>#\n    [――――――――――――――――] #<br>#\n    [G ⊢ S <: x.A]     *)\n| subtyp_sel2: forall G x A S T,\n    G ⊢ trm_var (avar_f x) : typ_rcd (dec_typ A S T) ->\n    G ⊢ S <: typ_sel (avar_f x) A\n\n(** [G ⊢ x: {A: S..T}] #<br>#\n    [――――――――――――――――] #<br>#\n    [G ⊢ x.A <: T]     *)\n| subtyp_sel1: forall G x A S T,\n    G ⊢ trm_var (avar_f x) : typ_rcd (dec_typ A S T) ->\n    G ⊢ typ_sel (avar_f x) A <: T\n\n(** [G ⊢ S2 <: S1]                #<br>#\n    [G, x: S2 ⊢ T1^x <: T2^x]     #<br>#\n    [x fresh]                     #<br>#\n    [―――――――――――――――――――――――]     #<br>#\n    [G ⊢ forall(S1)T1 <: forall(S2)T2]      *)\n| subtyp_all: forall L G S1 T1 S2 T2,\n    G ⊢ S2 <: S1 ->\n    (forall x, x \\notin L ->\n       G & x ~ S2 ⊢ open_typ x T1 <: open_typ x T2) ->\n    G ⊢ typ_all S1 T1 <: typ_all S2 T2\nwhere \"G '⊢' T '<:' U\" := (subtyp G T U).\n\n(** * Well-typed stacks *)\n\n(** The operational semantics is defined in terms of pairs [(s, t)], where\n    [s] is a stack and [t] is a term.\n    Given a typing [G ⊢ (s, t): T], [well_typed] establishes a correspondence\n    between [G] and the stack [s].\n\n    We say that [s] is well-typed with respect to [G] if\n    - [G = {(xi mapsto Ti) | i = 1, ..., n}]\n    - [s = {(xi mapsto vi) | i = 1, ..., n}]\n    - [G ⊢ vi: Ti].\n\n    We say that [s] is well-typed with respect to [G], denoted as [s: G]. *)\n\nDefinition well_typed (G : ctx) (s : sta) : Prop :=\n  ok G /\\\n  ok s /\\\n  (dom G = dom s) /\\\n  (forall x T v, binds x T G ->\n            binds x v s ->\n            G ⊢ trm_val v : T).\n\n(** * Infrastructure *)\n\nHint Unfold well_typed.\nHint Constructors\n     ty_trm ty_def ty_defs subtyp.\n\n(** ** Mutual Induction Principles *)\n\nScheme typ_mut := Induction for typ Sort Prop\nwith   dec_mut := Induction for dec Sort Prop.\nCombined Scheme typ_mutind from typ_mut, dec_mut.\n\nScheme trm_mut  := Induction for trm  Sort Prop\nwith   val_mut  := Induction for val Sort Prop\nwith   def_mut  := Induction for def  Sort Prop\nwith   defs_mut := Induction for defs Sort Prop.\nCombined Scheme trm_mutind from trm_mut, val_mut, def_mut, defs_mut.\n\nScheme ts_ty_trm_mut := Induction for ty_trm Sort Prop\nwith   ts_subtyp     := Induction for subtyp Sort Prop.\nCombined Scheme ts_mutind from ts_ty_trm_mut, ts_subtyp.\n\nScheme rules_trm_mut    := Induction for ty_trm Sort Prop\nwith   rules_def_mut    := Induction for ty_def Sort Prop\nwith   rules_defs_mut   := Induction for ty_defs Sort Prop\nwith   rules_subtyp     := Induction for subtyp Sort Prop.\nCombined Scheme rules_mutind from rules_trm_mut, rules_def_mut, rules_defs_mut, rules_subtyp.\n\n\n(** ** Tactics *)\n\n(** Tactics for generating fresh variables. *)\n\nLtac gather_vars :=\n  let A := gather_vars_with (fun x : vars      => x         ) in\n  let B := gather_vars_with (fun x : var       => \\{ x }    ) in\n  let C := gather_vars_with (fun x : ctx       => (dom x) \\u (fv_ctx_types x)) in\n  let D := gather_vars_with (fun x : sta       => dom x \\u fv_sta_vals x) in\n  let E := gather_vars_with (fun x : avar      => fv_avar  x) in\n  let F := gather_vars_with (fun x : trm       => fv_trm   x) in\n  let G := gather_vars_with (fun x : val       => fv_val   x) in\n  let H := gather_vars_with (fun x : def       => fv_def   x) in\n  let I := gather_vars_with (fun x : defs      => fv_defs  x) in\n  let J := gather_vars_with (fun x : typ       => fv_typ   x) in\n  constr:(A \\u B \\u C \\u D \\u E \\u F \\u G \\u H \\u I \\u J).\n\nLtac pick_fresh x :=\n  let L := gather_vars in (pick_fresh_gen L x).\n\nTactic Notation \"apply_fresh\" constr(T) \"as\" ident(x) :=\n  apply_fresh_base T gather_vars x.\n\nLtac fresh_constructor :=\n  match goal with\n  | [ |- _ ⊢ trm_val (val_new _ _) : typ_bnd _ ] =>\n    apply_fresh ty_new_intro as z\n  | [ |- _ ⊢ trm_val (val_lambda _ _) : typ_all _ _ ] =>\n    apply_fresh ty_all_intro as z\n  | [ |- _ ⊢ trm_let _ _ : _ ] =>\n    apply_fresh ty_let as z\n  | [ |- _ ⊢ typ_all _ _ <: typ_all _ _ ] =>\n    apply_fresh subtyp_all as z\n  end; auto.\n\n(** Tactics for naming cases in case analysis. *)\n\nOpen Scope string_scope.\n\nLtac move_to_top x :=\n  match reverse goal with\n  | H : _ |- _ => try move x after H\n  end.\n\nTactic Notation \"assert_eq\" ident(x) constr(v) :=\n  let H := fresh in\n  assert (x = v) as H by reflexivity;\n  clear H.\n\nTactic Notation \"Case_aux\" ident(x) constr(name) :=\n  first [\n    set (x := name); move_to_top x\n  | assert_eq x name; move_to_top x\n  | fail 1 \"because we are working on a different case\" ].\n\nTactic Notation \"Case\" constr(name) := Case_aux Case name.\nTactic Notation \"SCase\" constr(name) := Case_aux SCase name.\nTactic Notation \"SSCase\" constr(name) := Case_aux SSCase name.\nTactic Notation \"SSSCase\" constr(name) := Case_aux SSSCase name.\nTactic Notation \"SSSSCase\" constr(name) := Case_aux SSSSCase name.\nTactic Notation \"SSSSSCase\" constr(name) := Case_aux SSSSSCase name.\n\n(** Automatically destruct premises *)\nLtac destruct_all :=\n  repeat match goal with\n  | [ H : exists x, _ |- _ ]  => destruct H\n  | [ H : ?A /\\ ?B |- _ ] => destruct H\n  | [ H : ?A \\/ ?B |- _ ] => destruct H\n  end.\n\nLtac repeat_split_right :=\n  match goal with\n  | |- ?A /\\ ?B => split; repeat_split_right\n  | _ => idtac\n  end.\n\nLtac omega := Coq.omega.Omega.omega.\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/Definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.28213706677497385}}
{"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 cvterm4.\nRequire Export cequiv_bind.\nRequire Export csubst7.\nRequire Export cnterm.\nRequire Export continuity_defs_ceq.\n\n\nLemma free_vars_mk_natk2nat {o} :\n  forall v, @free_vars o (mk_natk2nat (mk_var v)) = [v].\nProof.\n  introv; simpl.\n  allrw remove_nvars_nil_l.\n  allrw app_nil_r.\n  allrw remove_nvars_cons.\n  allrw remove_nvars_nil_l.\n\n  pose proof (@newvar_prop o (mk_var v)) as nvp.\n  remember (newvar (mk_var v)) as nv.\n  clear Heqnv; simphyps.\n  allrw not_over_or; repnd; GC.\n\n  pose proof (@newvar_prop o (mk_less_than (mk_var nv) (mk_var v))) as nvp'.\n  remember (newvar (mk_less_than (mk_var nv) (mk_var v))) as nv'.\n  clear Heqnv'; simphyps.\n  allrw not_over_or; repnd; GC.\n\n  allsimpl; boolvar; tcsp.\n  simpl.\n  boolvar; tcsp.\nQed.\n\nLemma lsubstc_mk_natk2nat_sp1 {o} :\n  forall v (t : @CTerm o) w s c,\n    alphaeqc\n      (lsubstc (mk_natk2nat (mk_var v)) w ((v,t) :: s) c)\n      (natk2nat t).\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  prove_alpha_eq4.\n\n  introv j.\n  repeat (destruct n; tcsp; try omega); clear j;[].\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  Opaque beq_var.\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  }\nQed.\n\nLemma lsubstc_mk_natk2nat_sp2 {o} :\n  forall v (t : @CTerm o) w s c,\n    !LIn v (dom_csub s)\n    -> alphaeqc\n         (lsubstc (mk_natk2nat (mk_var v)) w (snoc s (v,t)) c)\n         (natk2nat t).\nProof.\n  introv niv.\n\n  assert (cover_vars (mk_natk2nat (mk_var v)) ((v, t) :: s)) as cv.\n  { allrw @cover_vars_mk_natk2nat.\n    allrw @cover_vars_var_iff.\n    allsimpl.\n    allrw @dom_csub_snoc; allsimpl.\n    allrw in_snoc; sp. }\n\n  pose proof (lsubstc_mk_natk2nat_sp1 v t w s cv) as h.\n  eapply alphaeqc_trans;[|exact h].\n\n  unfold alphaeqc; simpl.\n  apply alpha_eq_lsubst_if_ext_eq; auto.\n  unfold ext_alpha_eq_subs.\n  rw @free_vars_mk_natk2nat; simpl.\n  introv e; repndors; tcsp; subst.\n  boolvar; tcsp.\n  rw @csub2sub_snoc.\n  rw @sub_find_snoc.\n  boolvar.\n  rw @sub_find_none_if; eauto 3 with slow.\n  rw @dom_csub_eq; auto.\nQed.\n\nLemma mkc_nat_eq_implies {o} :\n  forall n m, @mkc_nat o n = mkc_nat m -> n = m.\nProof.\n  introv h.\n  inversion h as [q].\n  apply Znat.Nat2Z.inj in q; auto.\nQed.\n\nLemma wf_or {o} :\n  forall (a b : @NTerm o),\n    wf_term (mk_or a b) <=> (wf_term a # wf_term b).\nProof.\n  introv.\n  unfold mk_or.\n  rw @wf_union; sp.\nQed.\n\nLemma wf_dec {o} :\n  forall (a : @NTerm o),\n    wf_term (mk_dec a) <=> wf_term a.\nProof.\n  introv.\n  unfold mk_dec.\n  rw @wf_or.\n  rw @wf_not.\n  split; sp.\nQed.\n\nLemma cover_vars_union {o} :\n  forall (a b : @NTerm o) s,\n    cover_vars (mk_union a b) s <=> (cover_vars a s # cover_vars b s).\nProof.\n  introv.\n  allrw @cover_vars_eq; simpl.\n  allrw remove_nvars_nil_l.\n  allrw app_nil_r.\n  allrw subvars_app_l; sp.\nQed.\n\nLemma cover_vars_or {o} :\n  forall (a b : @NTerm o) s,\n    cover_vars (mk_or a b) s <=> (cover_vars a s # cover_vars b s).\nProof.\n  introv.\n  unfold mk_or.\n  rw @cover_vars_union; sp.\nQed.\n\nLemma cover_vars_dec {o} :\n  forall (a : @NTerm o) s,\n    cover_vars (mk_dec a) s <=> cover_vars a s.\nProof.\n  introv.\n  unfold mk_dec.\n  rw @cover_vars_or.\n  rw @cover_vars_not.\n  split; sp.\nQed.\n\nLemma covered_union {o} :\n  forall (a b : @NTerm o) vs,\n    covered (mk_union a b) vs <=> (covered a vs # covered b vs).\nProof.\n  introv.\n  unfold covered; simpl.\n  allrw remove_nvars_nil_l.\n  allrw app_nil_r.\n  allrw subvars_app_l; sp.\nQed.\n\nLemma covered_or {o} :\n  forall (a b : @NTerm o) vs,\n    covered (mk_or a b) vs <=> (covered a vs # covered b vs).\nProof.\n  introv.\n  unfold mk_or.\n  rw @covered_union; sp.\nQed.\n\nLemma covered_not {o} :\n  forall (a : @NTerm o) vs,\n    covered (mk_not a) vs <=> covered a vs.\nProof.\n  introv.\n  unfold mk_not.\n  rw @covered_fun.\n  split; sp.\nQed.\n\nLemma covered_dec {o} :\n  forall (a : @NTerm o) vs,\n    covered (mk_dec a) vs <=> covered a vs.\nProof.\n  introv.\n  unfold mk_dec.\n  rw @covered_or.\n  rw @covered_not.\n  split; sp.\nQed.\n\nLemma covered_snoc_implies {o} :\n  forall (t : @NTerm o) (v : NVar) (vs : list NVar),\n    !LIn v (free_vars t)\n    -> covered t (snoc vs v)\n    -> covered t vs.\nProof.\n  introv ni cov.\n  allunfold @covered; allsimpl.\n  allrw subvars_eq.\n  introv i.\n  applydup cov in i.\n  allrw in_snoc.\n  repndors; subst; tcsp.\nQed.\n\nLemma wf_term_mk_nat2nat {o} : @wf_term o mk_nat2nat.\nProof.\n  introv.\n  unfold mk_nat2nat.\n  apply wf_fun; dands; apply wf_tnat.\nQed.\n\nLemma cover_vars_mk_nat2nat {o} :\n  forall (s : @CSub o), cover_vars mk_nat2nat s.\nProof.\n  introv.\n  unfold mk_nat2nat.\n  apply cover_vars_fun; dands; apply cover_vars_mk_tnat.\nQed.\n\nDefinition mk_update_seq {o} (s n m : @NTerm o) v :=\n  mk_lam v (mk_int_eq (mk_var v) n m (mk_apply s (mk_var v))).\n\nDefinition mk_seq2kseq {o} (s n : @NTerm o) (v : NVar) : NTerm :=\n  mk_lam\n    v\n    (mk_less\n       (mk_var v)\n       mk_zero\n       mk_bot\n       (mk_less\n          (mk_var v)\n          n\n          (mk_apply s (mk_var v))\n          mk_bot)).\n\nLemma wf_seq2kseq {o} :\n  forall (t : @NTerm o) n v,\n    wf_term (mk_seq2kseq t n v) <=> (wf_term t # wf_term n).\nProof.\n  introv.\n  unfold mk_seq2kseq.\n  rw <- @wf_lam_iff.\n  allrw <- @wf_less_iff.\n  rw <- @wf_apply_iff.\n  split; intro h; repnd; dands; eauto 3 with slow.\nQed.\n\nLemma cover_vars_upto_mk_nat {o} :\n  forall n (s : @CSub o) vs,\n    cover_vars_upto (mk_nat n) s vs.\nProof.\n  introv.\n  unfold cover_vars_upto; simpl; sp.\nQed.\nHint Resolve cover_vars_upto_mk_nat : slow.\n\nLemma cover_vars_seq2kseq {o} :\n  forall (t : @NTerm o) n v s,\n    !LIn v (free_vars t)\n    -> !LIn v (free_vars n)\n    -> (cover_vars (mk_seq2kseq t n v) s <=> (cover_vars t s # cover_vars n s)).\nProof.\n  introv nit niv.\n  unfold mk_seq2kseq.\n  rw @cover_vars_lam.\n  allrw @cover_vars_upto_less.\n  allrw @cover_vars_upto_apply.\n  allrw @cover_vars_upto_var.\n  allsimpl.\n  split; intro h; repnd; dands; eauto 3 with slow.\n  - apply cover_vars_upto_csub_filter_disjoint in h6; auto.\n    apply disjoint_singleton_r; auto.\n  - apply cover_vars_upto_csub_filter_disjoint in h4; auto.\n    apply disjoint_singleton_r; auto.\n  - apply cover_vars_upto_csub_filter_disjoint; auto.\n    apply disjoint_singleton_r; auto.\n  - apply cover_vars_upto_csub_filter_disjoint; auto.\n    apply disjoint_singleton_r; auto.\nQed.\n\nLemma csubst_mk_less {o} :\n  forall (a b c d : @NTerm o) s,\n    csubst (mk_less a b c d) s\n    = mk_less (csubst a s) (csubst b s) (csubst c s) (csubst d s).\nProof.\n  introv.\n  unfold csubst; simpl.\n  change_to_lsubst_aux4; simpl.\n  rw @sub_filter_nil_r; allrw @fold_nobnd. sp.\nQed.\n\nLemma csubst_mk_bot {o} :\n  forall (sub : @CSub o), csubst mk_bot sub = mk_bot.\nProof.\n  introv.\n  rw @csubst_trivial; auto.\n  simpl; auto.\nQed.\n\nLemma csubst_mk_nat {o} :\n  forall n (sub : @CSub o), csubst (mk_nat n) sub = mk_nat n.\nProof.\n  introv.\n  rw @csubst_trivial; auto.\n  simpl; auto.\nQed.\n\nDefinition seq2kseq2 {o} (s n : @CTerm o) (v : NVar) : CTerm :=\n  mkc_lam\n    v\n    (mkcv_less\n       [v]\n       (mkc_var v)\n       (mkcv_zero [v])\n       (mkcv_bot [v])\n       (mkcv_less\n          [v]\n          (mkc_var v)\n          (mk_cv [v] n)\n          (mkcv_apply [v] (mk_cv [v] s) (mkc_var v))\n          (mkcv_bot [v]))).\n\nDefinition seq2kseq {o} (s : @CTerm o) (n : nat) (v : NVar) : CTerm :=\n  mkc_lam\n    v\n    (mkcv_less\n       [v]\n       (mkc_var v)\n       (mkcv_zero [v])\n       (mkcv_bot [v])\n       (mkcv_less\n          [v]\n          (mkc_var v)\n          (mkcv_nat [v] n)\n          (mkcv_apply [v] (mk_cv [v] s) (mkc_var v))\n          (mkcv_bot [v]))).\n\nLemma isprog_vars_mk_less {p} :\n  forall (a b c d : @NTerm p) vs,\n    isprog_vars vs (mk_less a b c d)\n    <=> (isprog_vars vs a\n         # isprog_vars vs b\n         # isprog_vars vs c\n         # isprog_vars vs d).\nProof.\n  introv.\n  repeat (rw @isprog_vars_eq; simpl).\n  repeat (rw remove_nvars_nil_l).\n  repeat (rw app_nil_r).\n  repeat (rw subvars_app_l).\n  repeat (rw <- @wf_term_eq).\n  allrw <- @wf_less_iff; split; sp.\nQed.\n\nLemma isprogram_mk_less {p} :\n  forall (a b c d : @NTerm p),\n    isprogram (mk_less a b c d)\n    <=> (isprogram a\n         # isprogram b\n         # isprogram c\n         # isprogram d).\nProof.\n  introv.\n  pose proof (isprog_vars_mk_less a b c d []) as h.\n  allrw <- @isprog_vars_nil_iff_isprog.\n  allrw @isprogram_eq; auto.\nQed.\n\nLemma implies_approxc_mkc_less1 {o} :\n  forall lib (a b c d e f g : @CTerm o),\n    (forall i : Z,\n       computes_to_valc lib a (mkc_integer i)\n       -> cequivc lib (mkc_less (mkc_integer i) b c d) (mkc_less (mkc_integer i) e f g))\n    -> approxc lib (mkc_less a b c d) (mkc_less a e f g).\nProof.\n  introv imp.\n  destruct_cterms.\n  allunfold @cequivc; allsimpl.\n  allunfold @computes_to_valc; allsimpl.\n\n  constructor.\n  unfold close_comput; dands; auto;\n  try (apply isprogram_mk_less; dands; eauto 3 with slow).\n\n  + introv comp.\n    apply computes_to_value_mk_less in comp; eauto 3 with slow; exrepnd.\n\n    pose proof (imp k1) as h; clear imp.\n    autodimp h hyp.\n    { split; eauto 3 with slow. }\n    destruct h as [h1 h2]; clear h2.\n    inversion h1 as [cl]; clear h1.\n    unfold close_comput in cl; repnd.\n\n    pose proof (cl2 c tl_subterms) as h.\n    autodimp h hyp.\n\n    * split;[|allunfold @computes_to_value; sp];[].\n      eapply reduces_to_trans;\n        [apply reduce_to_prinargs_comp;\n          [apply computes_to_value_isvalue_refl;eauto 3 with slow\n          |eauto 3 with slow\n          |exact comp2]\n        |].\n      repndors; repnd; allunfold @computes_to_value; repnd.\n\n      { eapply reduces_to_if_split2;[|exact comp4].\n        csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl.\n        boolvar;try omega;auto. }\n\n      { eapply reduces_to_if_split2;[|exact comp4].\n        csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl.\n        boolvar;try omega;auto. }\n\n    * exrepnd.\n      exists tr_subterms; dands; auto.\n\n      allunfold @computes_to_value; repnd.\n      split; tcsp.\n      eapply reduces_to_trans;[apply reduces_to_prinarg;exact comp0|].\n      auto.\n\n  + introv comp.\n    apply computes_to_exception_mk_less in comp; eauto 3 with slow.\n    repndors; exrepnd.\n\n    * pose proof (imp k1) as h; clear imp.\n      autodimp h hyp.\n      { split; eauto 3 with slow. }\n      destruct h as [h1 h2]; clear h2.\n      inversion h1 as [cl]; clear h1.\n      unfold close_comput in cl; repnd.\n\n      pose proof (cl3 a e) as h.\n      autodimp h hyp.\n\n      { eapply reduces_to_trans;\n        [apply reduce_to_prinargs_comp;\n          [apply computes_to_value_isvalue_refl;eauto 3 with slow\n          |eauto 3 with slow\n          |exact comp2]\n        |].\n        repndors; repnd.\n\n        { eapply reduces_to_if_split2;[|exact comp1].\n          csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl.\n          boolvar;try omega;auto. }\n\n        { eapply reduces_to_if_split2;[|exact comp1].\n          csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl.\n          boolvar;try omega;auto. }\n      }\n\n      { exrepnd.\n        exists a' e'; dands; auto.\n\n        eapply reduces_to_trans;[apply reduces_to_prinarg;exact comp0|].\n        auto.\n      }\n\n    * applydup @preserve_program_exc2 in comp; eauto 3 with slow; repnd.\n      exists a e; dands; eauto 3 with slow;\n      try (left; apply approx_refl; eauto 3 with slow).\n      eapply reduces_to_trans;[apply reduces_to_prinarg;exact comp|].\n      apply reduces_to_if_step.\n      csunf; simpl; auto.\n\n    * applydup @preserve_program_exc2 in comp0; eauto 3 with slow; repnd.\n\n      pose proof (imp z) as h; clear imp.\n      autodimp h hyp.\n      { split; eauto 3 with slow. }\n      destruct h as [h1 h2]; clear h2.\n      inversion h1 as [cl]; clear h1.\n      unfold close_comput in cl; repnd.\n\n      pose proof (cl3 a e) as h.\n      autodimp h hyp.\n\n      { eapply reduces_to_trans;\n        [apply reduce_to_prinargs_comp;\n          [apply computes_to_value_isvalue_refl;eauto 3 with slow\n          |eauto 3 with slow\n          |exact comp0]\n        |]; fold_terms.\n        apply reduces_to_if_step.\n        csunf; simpl; dcwf h; simpl; auto.\n      }\n\n      { exrepnd.\n        exists a' e'; dands; auto.\n\n        eapply reduces_to_trans;[apply reduces_to_prinarg;exact comp1|].\n        auto.\n      }\n\n  + introv comp; allsimpl.\n    apply computes_to_seq_implies_computes_to_value in comp;\n      [|apply isprogram_mk_less; dands; eauto 3 with slow].\n    applydup @computes_to_value_mk_less in comp; exrepnd; eauto 3 with slow.\n\n    pose proof (imp k1) as h; autodimp h hyp.\n    { split; dands; eauto 3 with slow. }\n\n    destruct h as [h1 h2]; clear h2.\n    inversion h1 as [cl]; clear h1.\n    unfold close_comput in cl; repnd; GC.\n    clear cl2 cl3.\n\n    pose proof (cl4 f) as h.\n    autodimp h hyp.\n\n    * eapply reduces_to_trans;\n        [apply reduce_to_prinargs_comp;\n          [apply computes_to_value_isvalue_refl;eauto 3 with slow\n          |eauto 3 with slow\n          |exact comp2]\n        |].\n      repndors; repnd; allunfold @computes_to_value; repnd.\n\n      { eapply reduces_to_if_split2;[|exact comp4].\n        csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl.\n        boolvar;try omega;auto. }\n\n      { eapply reduces_to_if_split2;[|exact comp4].\n        csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl.\n        boolvar;try omega;auto. }\n\n    * exrepnd.\n      exists f'; dands; auto.\n\n      eapply reduces_to_trans;[apply reduces_to_prinarg;exact comp1|].\n      auto.\nQed.\n\nLemma implies_cequivc_mkc_less1 {o} :\n  forall lib (a b c d e f g : @CTerm o),\n    (forall i : Z,\n       computes_to_valc lib a (mkc_integer i)\n       -> cequivc lib (mkc_less (mkc_integer i) b c d) (mkc_less (mkc_integer i) e f g))\n    -> cequivc lib (mkc_less a b c d) (mkc_less a e f g).\nProof.\n  introv imp.\n  apply cequivc_iff_approxc; dands.\n  - apply implies_approxc_mkc_less1; auto.\n  - apply implies_approxc_mkc_less1; auto.\n    introv comp.\n    apply cequivc_sym; auto.\nQed.\n\nLemma mkcv_nat_substc {o} :\n  forall v (t : @CTerm o) n,\n    substc t v (mkcv_nat [v] n) = mkc_nat n.\nProof.\n  introv.\n  destruct_cterms.\n  apply cterm_eq; simpl.\n  repeat unfsubst.\nQed.\n\nLemma seq2kseq2_as_seq2kseq {o} :\n  forall lib (s : @CTerm o) n m v,\n    computes_to_valc lib n (mkc_nat m)\n    -> cequivc lib (seq2kseq2 s n v) (seq2kseq s m v).\nProof.\n  introv comp.\n  unfold seq2kseq, seq2kseq2.\n  apply implies_cequivc_lam; introv.\n  allrw @mkcv_less_substc.\n  allrw @mkcv_apply_substc.\n  allrw @mkc_var_substc.\n  allrw @mkcv_bot_substc.\n  allrw @csubst_mk_cv.\n  allrw @mkcv_nat_substc.\n  allrw @mkcv_zero_substc.\n  allrw @mkc_zero_eq.\n  eapply cequivc_mkc_less;\n    [apply cequivc_refl\n    |apply cequivc_refl\n    |apply cequivc_refl\n    |eapply cequivc_mkc_less;\n      [apply cequivc_refl\n      |apply computes_to_valc_implies_cequivc; auto\n      |apply cequivc_refl\n      |apply cequivc_refl]\n    ].\nQed.\n\nLemma seq2kseq2_as_seq2kseq2 {o} :\n  forall (s : @CTerm o) n v,\n   seq2kseq2 s (mkc_nat n) v = seq2kseq s n v.\nProof.\n  introv.\n  apply cterm_eq; simpl; auto.\nQed.\n\nLemma lsubstc_mk_seq2kseq2 {o} :\n  forall (t : @NTerm o) n v w s c,\n    !LIn v (free_vars t)\n    -> !LIn v (free_vars n)\n    -> {wt : wf_term t\n        & {ct : cover_vars t s\n        & {wn : wf_term n\n        & {cn : cover_vars n s\n        & lsubstc (mk_seq2kseq t n v) w s c\n          = seq2kseq2 (lsubstc t wt s ct) (lsubstc n wn s cn) v }}}}.\nProof.\n  introv nit nin.\n\n  assert (wf_term t) as wt.\n  { apply wf_seq2kseq in w; sp. }\n\n  assert (cover_vars t s) as ct.\n  { apply cover_vars_seq2kseq in c; sp. }\n\n  assert (wf_term n) as wn.\n  { apply wf_seq2kseq in w; sp. }\n\n  assert (cover_vars n s) as cn.\n  { apply cover_vars_seq2kseq in c; sp. }\n\n  exists wt ct wn cn.\n  apply cterm_eq; simpl.\n  unfold mk_seq2kseq.\n  rw @csubst_mk_lam.\n  allrw @csubst_mk_less.\n  allrw @csubst_mk_apply.\n  allrw @csubst_mk_zero.\n  allrw @csubst_mk_bot.\n  allrw @csubst_mk_nat.\n  repeat (rw @csubst_var_not_in;\n          [|rw @dom_csub_csub_filter;rw in_remove_nvars;rw in_single_iff;sp]).\n  allrw @csubst_csub_filter; auto; apply disjoint_singleton_r; auto.\nQed.\n\nLemma lsubstc_mk_nat {o} :\n  forall n w (s : @CSub o) c,\n    lsubstc (mk_nat n) w s c = mkc_nat n.\nProof.\n  unfold lsubstc, mkc_axiom; sp.\n  apply cterm_eq; sp.\nQed.\n\nLemma lsubstc_mk_seq2kseq {o} :\n  forall (t : @NTerm o) n v w s c,\n    !LIn v (free_vars t)\n    -> {wt : wf_term t\n        & {ct : cover_vars t s\n        & lsubstc (mk_seq2kseq t (mk_nat n) v) w s c\n          = seq2kseq (lsubstc t wt s ct) n v }}.\nProof.\n  introv nit.\n  pose proof (lsubstc_mk_seq2kseq2 t (mk_nat n) v w s c) as h.\n  simpl in h.\n  repeat (autodimp h hyp); tcsp; exrepnd.\n  allrw @lsubstc_mk_nat.\n  exists wt ct; auto.\n  rw @seq2kseq2_as_seq2kseq2 in h1; auto.\nQed.\n\nLemma implies_cequivc_seq2kseq2 {o} :\n  forall lib (v : NVar) (s1 s2 n1 n2 : @CTerm o),\n    cequivc lib s1 s2\n    -> cequivc lib n1 n2\n    -> cequivc lib (seq2kseq2 s1 n1 v) (seq2kseq2 s2 n2 v).\nProof.\n  introv ceq1 ceq2.\n  unfold seq2kseq2.\n  apply implies_cequivc_lam; introv.\n  allrw @mkcv_less_substc.\n  allrw @mkcv_apply_substc.\n  allrw @mkc_var_substc.\n  allrw @csubst_mk_cv.\n  allrw @mkcv_bot_substc.\n  allrw @mkcv_nat_substc.\n  allrw @mkcv_zero_substc.\n\n  eapply cequivc_mkc_less;\n    [apply cequivc_refl\n    |apply cequivc_refl\n    |apply cequivc_refl\n    |eapply cequivc_mkc_less;\n      [apply cequivc_refl\n      |auto\n      |apply sp_implies_cequivc_apply;auto\n      |apply cequivc_refl]\n    ].\nQed.\n\nLemma implies_cequivc_natk2nat {o} :\n  forall lib (t1 t2 : @CTerm o),\n    cequivc lib t1 t2\n    -> cequivc lib (natk2nat t1) (natk2nat t2).\nProof.\n  introv ceq.\n  unfold natk2nat.\n  apply cequivc_mkc_fun;[|apply cequivc_refl].\n  apply cequivc_mkc_natk; auto.\nQed.\n\nLemma cequivc_lsubstc_mk_plus1 {o} :\n  forall lib n (w : @wf_term o (mk_plus1 (mk_var n))) m a (sub : @CSub o) n k s t c,\n    m <> n\n    -> !LIn n (dom_csub sub)\n    -> cequivc\n         lib\n         (lsubstc (mk_plus1 (mk_var n)) w\n                  ((m, a) :: snoc (snoc sub (n, mkc_nat k)) (s, t)) c)\n         (mkc_nat (S k)).\nProof.\n  introv d1 ni.\n  unfold cequivc; simpl.\n  unfold csubst, mk_plus1.\n  rw @cl_lsubst_lsubst_aux; eauto 3 with slow; simpl.\n  boolvar; simpl; tcsp.\n  allrw @sub_filter_nil_r.\n  allrw @csub2sub_snoc.\n  allrw @sub_find_snoc.\n  rw @sub_find_none_if; auto; try (rw @dom_csub_eq;auto).\n  boolvar; tcsp; fold_terms.\n  apply reduces_to_implies_cequiv;\n    [rw @isprogram_eq; apply isprog_add_implies;eauto 3 with slow|].\n  apply reduces_to_if_step; csunf; simpl; dcwf h; simpl; auto.\n  unfold mk_nat, mk_integer.\n\n  assert (1%Z = Z.of_nat 1) as e by (simpl; auto).\n  rw e.\n  rw <- @Znat.Nat2Z.inj_add.\n  rw plus_comm; auto.\nQed.\n\nLemma implies_cequivc_mkc_image {o} :\n  forall lib (a b c d : @CTerm o),\n    cequivc lib a c\n    -> cequivc lib b d\n    -> cequivc lib (mkc_image a b) (mkc_image c d).\nProof.\n  introv ceq1 ceq2.\n  destruct_cterms; allunfold @cequivc; allsimpl.\n  destruct ceq1, ceq2.\n  split; repeat prove_approx; eauto 3 with slow.\nQed.\n\nLemma implies_cequivc_mkc_squash {o} :\n  forall lib (t u : @CTerm o),\n    cequivc lib t u\n    -> cequivc lib (mkc_squash t) (mkc_squash u).\nProof.\n  introv c.\n  unfold mkc_squash.\n  apply implies_cequivc_mkc_image; auto.\nQed.\n\nLemma cequivc_lsubstc_mk_plus1_sp1 {o} :\n  forall lib n w (sub : @CSub o) k c,\n    !LIn n (dom_csub sub)\n    -> cequivc\n         lib\n         (lsubstc (mk_plus1 (mk_var n)) w\n                  (snoc sub (n, mkc_nat k)) c)\n         (mkc_nat (S k)).\nProof.\n  introv ni.\n  unfold cequivc; simpl.\n  unfold csubst, mk_plus1.\n  rw @cl_lsubst_lsubst_aux; eauto 3 with slow; simpl.\n  boolvar; simpl; tcsp.\n  allrw @sub_filter_nil_r.\n  allrw @csub2sub_snoc.\n  allrw @sub_find_snoc.\n  rw @sub_find_none_if; auto; try (rw @dom_csub_eq;auto).\n  boolvar; tcsp; fold_terms.\n  apply reduces_to_implies_cequiv;\n    [rw @isprogram_eq; apply isprog_add_implies;eauto 3 with slow|].\n  apply reduces_to_if_step; csunf; simpl; dcwf h; simpl; auto.\n  unfold mk_nat, mk_integer.\n\n  assert (1%Z = Z.of_nat 1) as e by (simpl; auto).\n  rw e.\n  rw <- @Znat.Nat2Z.inj_add.\n  rw plus_comm; auto.\nQed.\n\nLemma implies_cequiv_mk_add {o} :\n  forall lib (a b c d : @NTerm o),\n    cequiv lib a c\n    -> cequiv lib b d\n    -> cequiv lib (mk_add a b) (mk_add c d).\nProof.\n  introv ceq1 ceq2.\n  destruct ceq1, ceq2.\n  unfold mk_add.\n  applydup @approx_relates_only_progs in a0.\n  applydup @approx_relates_only_progs in a2.\n  repnd.\n  split; repeat prove_approx; eauto 3 with slow.\nQed.\n\nLemma implies_cequivc_mkc_add {o} :\n  forall lib (a b c d : @CTerm o),\n    cequivc lib a c\n    -> cequivc lib b d\n    -> cequivc lib (mkc_add a b) (mkc_add c d).\nProof.\n  introv ceq1 ceq2.\n  destruct_cterms; allunfold @cequivc; allsimpl.\n  apply implies_cequiv_mk_add; auto.\nQed.\n\nLemma cequivc_lsubstc_mk_plus1_sp2 {o} :\n  forall lib n w (sub : @CSub o) t k c,\n    !LIn n (dom_csub sub)\n    -> cequivc lib t (mkc_nat k)\n    -> cequivc\n         lib\n         (lsubstc (mk_plus1 (mk_var n)) w\n                  (snoc sub (n,t)) c)\n         (mkc_nat (S k)).\nProof.\n  introv ni ceq.\n  allunfold @cequivc; simpl.\n  unfold csubst, mk_plus1.\n  rw @cl_lsubst_lsubst_aux; eauto 3 with slow; simpl.\n  boolvar; simpl; tcsp.\n  allrw @sub_filter_nil_r.\n  allrw @csub2sub_snoc.\n  allrw @sub_find_snoc.\n  rw @sub_find_none_if; auto; try (rw @dom_csub_eq;auto).\n  boolvar; tcsp; fold_terms.\n  eapply cequiv_trans;\n    [apply implies_cequiv_mk_add;\n      [exact ceq\n      |apply cequiv_refl;eauto 3 with slow]\n    |].\n\n  apply reduces_to_implies_cequiv;\n    [rw @isprogram_eq; apply isprog_add_implies;eauto 3 with slow|].\n  apply reduces_to_if_step; csunf; simpl; dcwf h; simpl; auto.\n  unfold mk_nat, mk_integer.\n\n  assert (1%Z = Z.of_nat 1) as e by (simpl; auto).\n  rw e.\n  rw <- @Znat.Nat2Z.inj_add.\n  rw plus_comm; auto.\nQed.\n\nLemma implies_approx_lam {o} :\n  forall lib v (t1 t2 : @NTerm o),\n    isprog_vars [v] t1\n    -> isprog_vars [v] t2\n    -> (forall u : NTerm, isprog u -> cequiv lib (subst t1 v u) (subst t2 v u))\n    -> approx lib (mk_lam v t1) (mk_lam v t2).\nProof.\n  introv isp1 isp2 imp.\n\n  constructor.\n  unfold close_comput; dands;\n  try (apply isprogram_lam);\n  eauto 3 with slow.\n\n  + introv comp.\n    apply computes_to_value_isvalue_eq in comp;\n      try (apply isvalue_mk_lam); eauto 3 with slow.\n    unfold mk_lam in comp; ginv; fold_terms.\n    exists [bterm [v] t2]; fold_terms.\n    dands.\n    { apply computes_to_value_isvalue_refl;\n      try (apply isvalue_mk_lam); eauto 3 with slow. }\n\n    unfold lblift; simpl; dands; auto.\n    introv ltn.\n    destruct n; try omega; clear ltn.\n    unfold selectbt; simpl.\n    unfold blift.\n    exists [v] t1 t2; dands; eauto 3 with slow.\n    apply clearbots_olift.\n    apply cl_olift_implies_olift; eauto 3 with slow.\n\n    pose proof (cl_olift_iff_pv_olift (approx lib) t1 t2 [v]) as xx.\n    repeat (autodimp xx hyp).\n    apply xx; clear xx.\n    introv ps e.\n    destruct sub as [|p s]; allsimpl; ginv.\n    destruct s; ginv.\n    destruct p as [z u]; allsimpl.\n    allrw @fold_subst.\n    allrw @prog_sub_cons; repnd.\n    pose proof (imp u) as h; clear imp; allsimpl.\n    destruct h; eauto 3 with slow.\n\n  + introv comp.\n    apply can_doesnt_raise_an_exception in comp; sp.\n\n  + introv comp.\n    apply reduces_to_if_isvalue_like in comp; eauto 3 with slow; ginv.\nQed.\n\nLemma implies_cequiv_lam {o} :\n  forall lib v (t1 t2 : @NTerm o),\n    isprog_vars [v] t1\n    -> isprog_vars [v] t2\n    -> (forall u : NTerm, isprog u -> cequiv lib (subst t1 v u) (subst t2 v u))\n    -> cequiv lib (mk_lam v t1) (mk_lam v t2).\nProof.\n  introv isp1 isp2 imp.\n  split.\n  - apply implies_approx_lam; auto.\n  - apply implies_approx_lam; auto.\n    introv ispu.\n    apply cequiv_sym; auto.\nQed.\n\nLemma lsubst_aux_get_cterm {o} :\n  forall (t : @CTerm o) sub,\n    lsubst_aux (get_cterm t) sub = get_cterm t.\nProof.\n  introv.\n  apply lsubst_aux_trivial_cl_term2; eauto 3 with slow.\nQed.\n\nHint Resolve isprogram_mk_nat : slow.\n\n\nLemma cequivc_nat_implies_computes_to_valc {o} :\n  forall lib (t : @CTerm o) (n : nat),\n    cequivc lib t (mkc_nat n)\n    -> computes_to_valc lib t (mkc_nat n).\nProof.\n  introv ceq.\n  pose proof (cequivc_integer lib (mkc_nat n) t (Z.of_nat n)) as h.\n  repeat (autodimp h hyp); eauto 3 with slow.\n\n  { apply computes_to_valc_refl; eauto 3 with slow. }\n\n  apply cequivc_sym; auto.\nQed.\n\nLemma computes_to_value_mk_int_eq {o} :\n  forall lib (a b c d v : @NTerm o),\n    wf_term a\n    -> wf_term b\n    -> wf_term c\n    -> wf_term d\n    -> computes_to_value lib (mk_int_eq a b c d) v\n    -> {pk1 : param_kind\n        & {pk2 : param_kind\n        & reduces_to lib a (pk2term pk1)\n        # reduces_to lib b (pk2term pk2)\n        # ((pk1 = pk2 # computes_to_value lib c v)\n           [+]\n           (pk1 <> pk2 # computes_to_value lib d v)\n          )}}.\nProof.\n  introv wfa wfb wfc wfd hv.\n  unfold computes_to_value in hv; repnd.\n  unfold reduces_to in hv0; exrepnd.\n  pose proof (computes_to_val_like_in_max_k_steps_comp_implies\n                lib k CompOpEq a b c d v) as h.\n  repeat (autodimp h hyp).\n  { unfold computes_to_val_like_in_max_k_steps; dands; eauto with slow. }\n\n  repndors; exrepnd; repndors; exrepnd; ginv.\n\n  - allunfold @spcan; fold_terms.\n    allunfold @computes_to_can_in_max_k_steps; repnd.\n    exists pk1 pk2; dands; eauto with slow.\n    boolvar; subst.\n    + left; dands; auto.\n      allunfold @computes_to_val_like_in_max_k_steps; repnd.\n      unfold computes_to_value; dands; auto.\n      exists (k - (k1 + k2 + 1)); auto.\n    + right; dands; auto.\n      allunfold @computes_to_val_like_in_max_k_steps; repnd.\n      unfold computes_to_value; dands; auto.\n      exists (k - (k1 + k2 + 1)); auto.\n\n  - provefalse; subst; inversion hv; allsimpl; tcsp.\n\n  - provefalse; subst; inversion hv; allsimpl; tcsp.\nQed.\n\nLemma approx_pk2term_implies_reduces_to {o} :\n  forall lib pk (t : @NTerm o),\n    approx lib (pk2term pk) t\n    -> reduces_to lib t (pk2term pk).\nProof.\n  introv ap.\n  destruct ap as [c].\n  unfold close_comput in c; repnd.\n  destruct pk; allsimpl.\n\n  - pose proof (c2 (NTok s) []) as h; fold_terms.\n    autodimp h hyp.\n    { apply computes_to_value_isvalue_refl; eauto with slow. }\n    exrepnd.\n    unfold lblift in h0; allsimpl; repnd; cpx; fold_terms.\n    unfold computes_to_value in h1; repnd; auto.\n\n  - pose proof (c2 (NUTok g) []) as h; fold_terms.\n    autodimp h hyp.\n    { apply computes_to_value_isvalue_refl; eauto with slow. }\n    exrepnd.\n    unfold lblift in h0; allsimpl; repnd; cpx; fold_terms.\n    unfold computes_to_value in h1; repnd; auto.\n\n  - pose proof (c2 (Nint z) []) as h; fold_terms.\n    autodimp h hyp.\n    { apply computes_to_value_isvalue_refl; eauto with slow. }\n    exrepnd.\n    unfold lblift in h0; allsimpl; repnd; cpx; fold_terms.\n    unfold computes_to_value in h1; repnd; auto.\nQed.\n\nLemma computes_to_exception_mk_int_eq {o} :\n  forall lib (a b c d : @NTerm o) n e,\n    wf_term a\n    -> wf_term b\n    -> wf_term c\n    -> wf_term d\n    -> computes_to_exception lib n (mk_int_eq a b c d) e\n    -> {pk1 : param_kind\n        & {pk2 : param_kind\n        & reduces_to lib a (pk2term pk1)\n        # reduces_to lib b (pk2term pk2)\n        # ((pk1 = pk2 # computes_to_exception lib n c e)\n           [+]\n           (pk2 <> pk1 # computes_to_exception lib n d e)\n          )}}\n       [+] computes_to_exception lib n a e\n       [+] {pk : param_kind\n            & reduces_to lib a (pk2term pk)\n            # computes_to_exception lib n b e}.\nProof.\n  introv wfa wfb wfc wfd comp.\n  unfold computes_to_exception, reduces_to in comp; exrepnd.\n  pose proof (computes_to_val_like_in_max_k_steps_comp_implies\n                lib k CompOpEq a b c d (mk_exception n e)) as h.\n  repeat (autodimp h hyp).\n  { unfold computes_to_val_like_in_max_k_steps; dands; eauto 3 with slow. }\n\n  repndors; exrepnd; repndors; exrepnd; ginv.\n\n  - left.\n    allunfold @computes_to_can_in_max_k_steps; repnd.\n    allunfold @spcan; fold_terms.\n    exists pk1 pk2; dands; eauto with slow.\n    boolvar;[left|right]; dands; auto;\n    allunfold @computes_to_val_like_in_max_k_steps; repnd;\n    exists (k - (k1 + k2 + 1)); auto.\n\n  - right; left.\n    exists k1; auto.\n\n  - right; right; allsimpl.\n    exists pk; dands; auto.\n    + allunfold @computes_to_can_in_max_k_steps; repnd.\n      unfold computes_to_can; dands; eauto with slow.\n    + exists k2; auto.\nQed.\n\nLemma approx_open_mk_int_eq {o} :\n  forall lib (a1 a2 b1 b2 c1 c2 d1 d2 : @NTerm o),\n    approx_open lib a1 a2\n    -> approx_open lib b1 b2\n    -> approx_open lib c1 c2\n    -> approx_open lib d1 d2\n    -> approx_open lib (mk_int_eq a1 b1 c1 d1) (mk_int_eq a2 b2 c2 d2).\nProof.\n  introv apro1 apro2 apro3 apro4.\n\n  allrw <- @approx_open_simpler_equiv.\n  allunfold @simpl_olift; repnd.\n  allrw @nt_wf_eq.\n  dands; try (apply wf_int_eq; auto).\n  introv prs ispl1 ispl2.\n\n  repeat (rw @cl_lsubst_lsubst_aux; eauto 3 with slow).\n  repeat (rw @cl_lsubst_lsubst_aux in ispl1; eauto 3 with slow).\n  repeat (rw @cl_lsubst_lsubst_aux in ispl2; eauto 3 with slow).\n  allsimpl; fold_terms; allrw @sub_filter_nil_r.\n\n  allrw @isprogram_eq.\n  allrw @isprog_inteq; repnd.\n\n  pose proof (apro1 sub) as h1.\n  repeat (rw @cl_lsubst_lsubst_aux in h1; eauto 3 with slow).\n  allrw @isprogram_eq.\n  repeat (autodimp h1 hyp);[].\n\n  pose proof (apro2 sub) as h2.\n  repeat (rw @cl_lsubst_lsubst_aux in h2; eauto 3 with slow).\n  allrw @isprogram_eq.\n  repeat (autodimp h2 hyp);[].\n\n  pose proof (apro3 sub) as h3.\n  repeat (rw @cl_lsubst_lsubst_aux in h3; eauto 3 with slow).\n  allrw @isprogram_eq.\n  repeat (autodimp h3 hyp);[].\n\n  pose proof (apro4 sub) as h4.\n  repeat (rw @cl_lsubst_lsubst_aux in h4; eauto 3 with slow).\n  allrw @isprogram_eq.\n  repeat (autodimp h4 hyp);[].\n\n  constructor.\n  unfold close_comput.\n  allrw @isprogram_eq; allrw @isprog_inteq; dands; auto;[| |].\n\n  - introv comp.\n    apply computes_to_value_mk_int_eq in comp; exrepnd;\n    try (apply lsubst_aux_preserves_wf_term2; eauto 3 with slow);[].\n\n    eapply approx_comput_functionality_left in h1;[|exact comp0].\n    eapply approx_comput_functionality_left in h2;[|exact comp2].\n    allapply @approx_pk2term_implies_reduces_to.\n\n    repndors; repnd; subst;[|].\n\n    + eapply approx_canonical_form in h3;[|exact comp1].\n      destruct h3 as [tr_subterms apr]; repnd.\n      exists tr_subterms; dands; try (apply clearbot_relbt2); auto.\n      allunfold @computes_to_value; repnd; dands; tcsp.\n      eapply reduces_to_trans;\n        [apply reduce_to_prinargs_comp2;[exact h1|idtac|]; eauto 3 with slow|];[].\n      eapply reduces_to_if_split2;\n        [csunf; simpl; allrw @pk2term_eq; dcwf h;\n         allsimpl; unfold compute_step_comp; simpl;\n         allrw @get_param_from_cop_pk2can; auto;\n         allrw @co_wf_pk2can;ginv|];[].\n      boolvar;tcsp;try omega.\n\n    + eapply approx_canonical_form in h4;[|exact comp1].\n      destruct h4 as [tr_subterms apr]; repnd.\n      exists tr_subterms; dands; try (apply clearbot_relbt2); auto.\n      allunfold @computes_to_value; repnd; dands; tcsp.\n      eapply reduces_to_trans;\n        [apply reduce_to_prinargs_comp2;[exact h1|idtac|]; eauto 3 with slow|];[].\n      eapply reduces_to_if_split2;\n        [csunf; simpl; allrw @pk2term_eq; dcwf h;\n         allsimpl; unfold compute_step_comp; simpl;\n         allrw @get_param_from_cop_pk2can; auto;\n         allrw @co_wf_pk2can;ginv|];[].\n      boolvar;tcsp;try omega.\n\n  - introv comp.\n    apply computes_to_exception_mk_int_eq in comp; repndors; exrepnd;\n    try (apply lsubst_aux_preserves_wf_term2; eauto 3 with slow);[|idtac|].\n\n    + eapply approx_comput_functionality_left in h1;[|exact comp0].\n      eapply approx_comput_functionality_left in h2;[|exact comp2].\n      allapply @approx_pk2term_implies_reduces_to.\n\n      repndors; repnd;[|].\n\n      * apply computes_to_exception_implies_approx in comp1; eauto 3 with slow;[]; repnd.\n        eapply approx_trans in h3;[|exact comp4].\n        apply approx_exception in h3; exrepnd.\n        exists x c; dands; tcsp.\n        allunfold @computes_to_exception.\n        eapply reduces_to_trans;\n          [apply reduce_to_prinargs_comp2;[exact h1|idtac|]; eauto 3 with slow|];[].\n        eapply reduces_to_if_split2;\n          [csunf; simpl; allrw @pk2term_eq; dcwf h;\n           allsimpl; unfold compute_step_comp; simpl;\n           allrw @get_param_from_cop_pk2can; auto;\n           allrw @co_wf_pk2can;ginv|];[].\n        boolvar;tcsp;try omega.\n\n      * apply computes_to_exception_implies_approx in comp1; eauto 3 with slow;[]; repnd.\n        eapply approx_trans in h4;[|exact comp4].\n        apply approx_exception in h4; exrepnd.\n        exists x c; dands; tcsp.\n        allunfold @computes_to_exception.\n        eapply reduces_to_trans;\n          [apply reduce_to_prinargs_comp2;[exact h1|idtac|]; eauto 3 with slow|];[].\n        eapply reduces_to_if_split2;\n          [csunf; simpl; allrw @pk2term_eq; dcwf h;\n           allsimpl; unfold compute_step_comp; simpl;\n           allrw @get_param_from_cop_pk2can; auto;\n           allrw @co_wf_pk2can;ginv|];[].\n        boolvar;tcsp;try omega.\n\n    + apply computes_to_exception_implies_approx in comp; eauto 3 with slow;[]; repnd.\n      eapply approx_trans in h1;[|exact comp0].\n      apply approx_exception in h1; exrepnd.\n      exists x c; dands; tcsp;[].\n      allunfold @computes_to_exception.\n      unfold mk_less, nobnd.\n      eapply reduces_to_trans;[eapply reduces_to_prinarg;exact h0|].\n      apply reduces_to_if_step.\n      csunf; simpl; auto.\n\n    + apply computes_to_exception_implies_approx in comp0; eauto 3 with slow;[]; repnd.\n      eapply approx_trans in h2;[|exact comp2].\n      apply approx_exception in h2; exrepnd.\n\n      exists x c; dands; tcsp;[].\n      apply reduces_to_implies_approx1 in comp1; eauto 3 with slow;[].\n      eapply approx_trans in h1;[|exact comp1].\n      apply approx_pk2term_implies_reduces_to in h1.\n      allunfold @computes_to_exception.\n      eapply reduces_to_trans;\n        [apply reduce_to_prinargs_comp2;[exact h1|idtac|exact h0] |]; eauto 3 with slow.\n      apply reduces_to_if_step.\n      csunf; simpl.\n      allrw @pk2term_eq.\n      dcwf h; try (complete (allrw @co_wf_pk2can;ginv));[].\n      simpl; auto.\n\n  - introv comp.\n    apply computes_to_seq_implies_computes_to_value in comp;\n      [|apply isprogram_compop_iff;eexists; eexists; eexists; eexists;\n        unfold nobnd; dands; eauto 3 with slow];[].\n\n    apply computes_to_value_mk_int_eq in comp; exrepnd;\n    try (apply lsubst_aux_preserves_wf_term2; eauto 3 with slow);[].\n\n    eapply approx_comput_functionality_left in h1;[|exact comp0].\n    eapply approx_comput_functionality_left in h2;[|exact comp2].\n    allapply @approx_pk2term_implies_reduces_to.\n\n    repndors; repnd; subst;[|].\n\n    + eapply approx_sterm in h3;[|eauto]; exrepnd.\n      exists f'; dands; auto;[|introv; left; apply h0].\n      eapply reduces_to_trans;\n        [apply reduce_to_prinargs_comp2;[exact h1|idtac|]; eauto 3 with slow|];[].\n      eapply reduces_to_if_split2;\n        [csunf; simpl; allrw @pk2term_eq; dcwf h;\n         allsimpl; unfold compute_step_comp; simpl;\n         allrw @get_param_from_cop_pk2can; auto;\n         allrw @co_wf_pk2can;ginv|];[].\n      boolvar;tcsp;try omega.\n      allunfold @computes_to_value; sp.\n\n    + eapply approx_sterm in h4;[|eauto]; exrepnd.\n      exists f'; dands; auto;[|introv; left; apply h0].\n      eapply reduces_to_trans;\n        [apply reduce_to_prinargs_comp2;[exact h1|idtac|]; eauto 3 with slow|];[].\n      eapply reduces_to_if_split2;\n        [csunf; simpl; allrw @pk2term_eq; dcwf h;\n         allsimpl; unfold compute_step_comp; simpl;\n         allrw @get_param_from_cop_pk2can; auto;\n         allrw @co_wf_pk2can;ginv|];[].\n      boolvar;tcsp;try omega.\n      allunfold @computes_to_value; sp.\nQed.\n\nLemma approx_mk_int_eq {o} :\n  forall lib (a1 a2 b1 b2 c1 c2 d1 d2 : @NTerm o),\n    approx lib a1 a2\n    -> approx lib b1 b2\n    -> approx lib c1 c2\n    -> approx lib d1 d2\n    -> approx lib (mk_int_eq a1 b1 c1 d1) (mk_int_eq a2 b2 c2 d2).\nProof.\n  introv apra aprb aprc aprd.\n\n  applydup @approx_isprog in apra.\n  applydup @approx_isprog in aprb.\n  applydup @approx_isprog in aprc.\n  applydup @approx_isprog in aprd.\n  repnd.\n\n  apply approx_open_approx; allrw @isprogram_eq; try (apply isprog_inteq_implies); auto.\n  apply approx_open_mk_int_eq; apply approx_implies_approx_open; auto.\nQed.\n\nLemma cequiv_mk_int_eq {o} :\n  forall lib (a1 a2 b1 b2 c1 c2 d1 d2 : @NTerm o),\n    cequiv lib a1 a2\n    -> cequiv lib b1 b2\n    -> cequiv lib c1 c2\n    -> cequiv lib d1 d2\n    -> cequiv lib (mk_int_eq a1 b1 c1 d1) (mk_int_eq a2 b2 c2 d2).\nProof.\n  introv ceqa ceqb ceqc ceqd.\n  allunfold @cequiv; repnd; dands; apply approx_mk_int_eq; auto.\nQed.\n\nLemma cequivc_mkc_inteq {o} :\n  forall lib (a1 a2 b1 b2 c1 c2 d1 d2 : @CTerm o),\n    cequivc lib a1 a2\n    -> cequivc lib b1 b2\n    -> cequivc lib c1 c2\n    -> cequivc lib d1 d2\n    -> cequivc lib (mkc_inteq a1 b1 c1 d1) (mkc_inteq a2 b2 c2 d2).\nProof.\n  introv ceqa ceqb ceqc ceqd.\n  destruct_cterms.\n  allunfold @cequivc; allsimpl.\n  apply cequiv_mk_int_eq; auto.\nQed.\n\nLemma isprog_vars_mk_int_eq {p} :\n  forall (a b c d : @NTerm p) vs,\n    isprog_vars vs (mk_int_eq a b c d)\n    <=> (isprog_vars vs a\n         # isprog_vars vs b\n         # isprog_vars vs c\n         # isprog_vars vs d).\nProof.\n  introv.\n  repeat (rw @isprog_vars_eq; simpl).\n  repeat (rw remove_nvars_nil_l).\n  repeat (rw app_nil_r).\n  repeat (rw subvars_app_l).\n  repeat (rw <- @wf_term_eq).\n  allrw <- @wf_inteq_iff; split; sp.\nQed.\n\nLemma isprogram_mk_int_eq {p} :\n  forall (a b c d : @NTerm p),\n    isprogram (mk_int_eq a b c d)\n    <=> (isprogram a\n         # isprogram b\n         # isprogram c\n         # isprogram d).\nProof.\n  introv.\n  pose proof (isprog_vars_mk_int_eq a b c d []) as h.\n  allrw <- @isprog_vars_nil_iff_isprog.\n  allrw @isprogram_eq; auto.\nQed.\n\nLemma approx_bts_refl {o} :\n  forall lib (bs : list (@BTerm o)),\n    (forall b, LIn b bs -> bt_wf b)\n    -> approx_bts lib bs bs.\nProof.\n  introv imp.\n  unfold approx_bts, lblift.\n  dands; auto.\n  introv i.\n  unfold blift.\n  remember (selectbt bs n) as b.\n  destruct b as [l t].\n  exists l t t; dands; eauto 3 with slow.\n  apply approx_open_refl.\n  pose proof (imp (bterm l t)) as h.\n  autodimp h hyp.\n  { rw Heqb; apply selectbt_in; auto. }\n  allrw @bt_wf_iff; auto.\nQed.\n\nLemma isprogram_bt_implies_bt_wf {o} :\n  forall (b : @BTerm o), isprogram_bt b -> bt_wf b.\nProof.\n  introv isp.\n  destruct b.\n  apply isprogam_bt_nt_wf_eauto in isp.\n  apply wfbt; auto.\nQed.\nHint Resolve isprogram_bt_implies_bt_wf : slow.\n\nLemma approx_inteq_less_swap1 {o} :\n  forall lib (t : @NTerm o) n m u v w,\n    m <= n\n    -> isprog t\n    -> isprog u\n    -> isprog v\n    -> isprog w\n    -> approx\n         lib\n         (mk_int_eq t (mk_nat n) u (mk_less t (mk_nat m) v w))\n         (mk_less t (mk_nat m) v (mk_int_eq t (mk_nat n) u w)).\nProof.\n  introv ltm ispt ispu ispv ispw.\n  constructor.\n  unfold close_comput.\n  dands; auto;\n    repeat (try (apply isprogram_mk_int_eq; dands; eauto 3 with slow);\n            try (apply isprogram_mk_less; dands; eauto 3 with slow)).\n\n  - introv comp.\n    apply computes_to_value_mk_int_eq in comp;\n      try (apply wf_less); eauto 3 with slow.\n    exrepnd.\n    apply reduces_to_if_isvalue_like in comp2; eauto 3 with slow.\n    destruct pk2; allsimpl; ginv.\n    unfold mk_nat in comp2; ginv; fold_terms.\n    repndors; repnd; subst.\n\n    + exists tl_subterms.\n      dands; auto.\n\n      * allunfold @computes_to_value; repnd; dands; auto.\n        eapply reduces_to_trans;\n          [apply reduces_to_prinarg;exact comp0|].\n        eapply reduces_to_if_split2;\n          [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n        boolvar; try omega.\n        eapply reduces_to_trans;\n          [apply reduces_to_prinarg;exact comp0|].\n        eapply reduces_to_if_split2;\n          [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n        boolvar; tcsp.\n\n      * apply clearbot_relbt2.\n        fold (approx_open lib).\n        fold (approx_bts lib).\n        apply approx_bts_refl.\n        allunfold @computes_to_value; repnd.\n        apply compute_max_steps_eauto2 in comp1.\n        apply isprogram_ot_iff in comp1; repnd.\n        introv j; apply comp1 in j; eauto 3 with slow.\n\n    + apply computes_to_value_mk_less in comp1; eauto 3 with slow.\n      exrepnd.\n      apply reduces_to_if_isvalue_like in comp4; eauto 3 with slow.\n      unfold mk_nat in comp4; ginv; fold_terms.\n      eapply reduces_to_eq_val_like in comp0;\n        [|exact comp3\n         |eauto 3 with slow\n         |eauto 3 with slow].\n      destruct pk1; allsimpl; ginv.\n      repndors; repnd; subst.\n\n      * exists tl_subterms.\n        dands; auto.\n\n        { allunfold @computes_to_value; repnd; dands; auto.\n          eapply reduces_to_trans;\n            [apply reduces_to_prinarg;exact comp3|].\n          eapply reduces_to_if_split2;\n            [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n          boolvar; try omega; auto. }\n\n        { apply clearbot_relbt2.\n          fold (approx_open lib).\n          fold (approx_bts lib).\n          apply approx_bts_refl.\n          allunfold @computes_to_value; repnd.\n          apply compute_max_steps_eauto2 in comp1.\n          apply isprogram_ot_iff in comp1; repnd.\n          introv j; apply comp1 in j; eauto 3 with slow. }\n\n      * exists tl_subterms.\n        dands; auto.\n\n        { allunfold @computes_to_value; repnd; dands; auto.\n          eapply reduces_to_trans;\n            [apply reduces_to_prinarg;exact comp3|].\n          eapply reduces_to_if_split2;\n            [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n          boolvar; try omega; auto.\n          eapply reduces_to_trans;\n            [apply reduces_to_prinarg;exact comp3|].\n          eapply reduces_to_if_split2;\n            [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n          boolvar;tcsp. }\n\n        { apply clearbot_relbt2.\n          fold (approx_open lib).\n          fold (approx_bts lib).\n          apply approx_bts_refl.\n          allunfold @computes_to_value; repnd.\n          apply compute_max_steps_eauto2 in comp1.\n          apply isprogram_ot_iff in comp1; repnd.\n          introv j; apply comp1 in j; eauto 3 with slow. }\n\n  - introv comp.\n    apply computes_to_exception_mk_int_eq in comp;\n      try (apply wf_less); eauto 3 with slow.\n    repndors; exrepnd.\n\n    + apply reduces_to_if_isvalue_like in comp2; eauto 3 with slow.\n      destruct pk2; allsimpl; ginv.\n      unfold mk_nat in comp2; ginv; fold_terms.\n      repndors; repnd; subst.\n\n      * exists a e.\n        applydup @preserve_program_exc2 in comp1; eauto 3 with slow; repnd.\n        dands; try (complete (left; apply approx_refl; eauto with slow)).\n\n        eapply reduces_to_trans;\n          [apply reduces_to_prinarg;exact comp0|].\n        eapply reduces_to_if_split2;\n          [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n        boolvar; try omega.\n        eapply reduces_to_trans;\n          [apply reduces_to_prinarg;exact comp0|].\n        eapply reduces_to_if_split2;\n          [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n        boolvar; tcsp.\n\n      * apply computes_to_exception_mk_less in comp1; eauto 3 with slow.\n        repndors; exrepnd.\n\n        { apply reduces_to_if_isvalue_like in comp4; eauto 3 with slow.\n          unfold mk_nat in comp4; ginv; fold_terms.\n          eapply reduces_to_eq_val_like in comp0;\n            [|exact comp3\n             |eauto 3 with slow\n             |eauto 3 with slow].\n          destruct pk1; allsimpl; ginv.\n          repndors; repnd; subst.\n\n          - exists a e.\n            applydup @preserve_program_exc2 in comp1; eauto 3 with slow; repnd.\n            dands; try (complete (left; apply approx_refl; eauto with slow)).\n\n            eapply reduces_to_trans;\n              [apply reduces_to_prinarg;exact comp3|].\n            eapply reduces_to_if_split2;\n              [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n            boolvar; try omega; auto.\n\n          - exists a e.\n            applydup @preserve_program_exc2 in comp1; eauto 3 with slow; repnd.\n            dands; try (complete (left; apply approx_refl; eauto with slow)).\n\n            eapply reduces_to_trans;\n              [apply reduces_to_prinarg;exact comp3|].\n            eapply reduces_to_if_split2;\n              [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n            boolvar; try omega; auto.\n\n            eapply reduces_to_trans;\n              [apply reduces_to_prinarg;exact comp3|].\n            eapply reduces_to_if_split2;\n              [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n            boolvar; try omega; ginv; tcsp.\n        }\n\n        { exists a e.\n          applydup @preserve_program_exc2 in comp1; eauto 3 with slow; repnd.\n          dands; try (complete (left; apply approx_refl; eauto with slow)).\n\n          eapply reduces_to_trans;\n            [apply reduces_to_prinarg;exact comp1|].\n          apply reduces_to_if_step; csunf; simpl; auto.\n        }\n\n        { apply can_doesnt_raise_an_exception in comp3; sp. }\n\n    + exists a e.\n      applydup @preserve_program_exc2 in comp; eauto 3 with slow; repnd.\n      dands; try (complete (left; apply approx_refl; eauto with slow)).\n\n      eapply reduces_to_trans;\n        [apply reduces_to_prinarg;exact comp|].\n      apply reduces_to_if_step; csunf; simpl; auto.\n\n    + apply can_doesnt_raise_an_exception in comp0; sp.\n\n  - introv comp.\n    apply computes_to_seq_implies_computes_to_value in comp;\n      [|apply isprogram_mk_int_eq; dands; eauto 3 with slow;\n        apply isprogram_mk_less; dands; eauto 3 with slow].\n\n    apply computes_to_value_mk_int_eq in comp;\n      try (apply wf_less); eauto 3 with slow.\n    exrepnd.\n    apply reduces_to_if_isvalue_like in comp2; eauto 3 with slow.\n    destruct pk2; allsimpl; ginv.\n    unfold mk_nat in comp2; ginv; fold_terms.\n    repndors; repnd; subst.\n\n    + exists f.\n      dands; auto;\n      [|introv; left; apply approx_refl;\n        destruct comp1 as [comp isv];\n        inversion isv; eauto 3 with slow].\n\n      allunfold @computes_to_value; repnd; dands; auto.\n      eapply reduces_to_trans;\n        [apply reduces_to_prinarg;exact comp0|].\n      eapply reduces_to_if_split2;\n        [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n      boolvar; try omega.\n      eapply reduces_to_trans;\n        [apply reduces_to_prinarg;exact comp0|].\n      eapply reduces_to_if_split2;\n        [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n      boolvar; tcsp.\n\n    + apply computes_to_value_mk_less in comp1; eauto 3 with slow.\n      exrepnd.\n      apply reduces_to_if_isvalue_like in comp4; eauto 3 with slow.\n      unfold mk_nat in comp4; ginv; fold_terms.\n      eapply reduces_to_eq_val_like in comp0;\n        [|exact comp3\n         |eauto 3 with slow\n         |eauto 3 with slow].\n      destruct pk1; allsimpl; ginv.\n      repndors; repnd; subst.\n\n      * exists f.\n        dands; auto;\n        [|introv; left; apply approx_refl;\n          destruct comp1 as [comp isv];\n          inversion isv; eauto 3 with slow].\n\n        allunfold @computes_to_value; repnd; dands; auto.\n        eapply reduces_to_trans;\n          [apply reduces_to_prinarg;exact comp3|].\n        eapply reduces_to_if_split2;\n          [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n        boolvar; try omega; auto.\n\n      * exists f.\n        dands; auto;\n        [|introv; left; apply approx_refl;\n          destruct comp1 as [comp isv];\n          inversion isv; eauto 3 with slow].\n\n        allunfold @computes_to_value; repnd; dands; auto.\n        eapply reduces_to_trans;\n          [apply reduces_to_prinarg;exact comp3|].\n        eapply reduces_to_if_split2;\n          [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n        boolvar; try omega; auto.\n        eapply reduces_to_trans;\n          [apply reduces_to_prinarg;exact comp3|].\n        eapply reduces_to_if_split2;\n          [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n        boolvar;tcsp.\nQed.\n\nLemma approx_less_inteq_swap1 {o} :\n  forall lib (t : @NTerm o) n m u v w,\n    m <= n\n    -> isprog t\n    -> isprog u\n    -> isprog v\n    -> isprog w\n    -> approx\n         lib\n         (mk_less t (mk_nat m) v (mk_int_eq t (mk_nat n) u w))\n         (mk_int_eq t (mk_nat n) u (mk_less t (mk_nat m) v w)).\nProof.\n  introv ltm ispt ispu ispv ispw.\n  constructor.\n  unfold close_comput.\n  dands; auto;\n    repeat (try (apply isprogram_mk_int_eq; dands; eauto 3 with slow);\n            try (apply isprogram_mk_less; dands; eauto 3 with slow)).\n\n  - introv comp.\n    apply computes_to_value_mk_less in comp;\n      try (apply wf_less); eauto 3 with slow.\n    exrepnd.\n    apply reduces_to_if_isvalue_like in comp2; eauto 3 with slow.\n    unfold mk_nat in comp2; ginv; fold_terms.\n    repndors; repnd; subst.\n\n    + exists tl_subterms.\n      dands; auto.\n\n      * allunfold @computes_to_value; repnd; dands; auto.\n        eapply reduces_to_trans;\n          [apply reduces_to_prinarg;exact comp0|].\n        eapply reduces_to_if_split2;\n          [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n        boolvar; ginv; try omega.\n        eapply reduces_to_trans;\n          [apply reduces_to_prinarg;exact comp0|].\n        eapply reduces_to_if_split2;\n          [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n        boolvar; tcsp; try omega.\n\n      * apply clearbot_relbt2.\n        fold (approx_open lib).\n        fold (approx_bts lib).\n        apply approx_bts_refl.\n        allunfold @computes_to_value; repnd.\n        apply compute_max_steps_eauto2 in comp1.\n        apply isprogram_ot_iff in comp1; repnd.\n        introv j; apply comp1 in j; eauto 3 with slow.\n\n    + apply computes_to_value_mk_int_eq in comp1; eauto 3 with slow.\n      exrepnd.\n      apply reduces_to_if_isvalue_like in comp4; eauto 3 with slow.\n      destruct pk2; allsimpl; ginv.\n      unfold mk_nat in comp4; ginv; fold_terms.\n      eapply reduces_to_eq_val_like in comp0;\n        [|exact comp3\n         |eauto 3 with slow\n         |eauto 3 with slow].\n      destruct pk1; allsimpl; ginv.\n      repndors; repnd; subst; ginv.\n\n      * exists tl_subterms.\n        dands; auto.\n\n        { allunfold @computes_to_value; repnd; dands; auto.\n          eapply reduces_to_trans;\n            [apply reduces_to_prinarg;exact comp3|].\n          eapply reduces_to_if_split2;\n            [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n          boolvar; try omega; tcsp. }\n\n        { apply clearbot_relbt2.\n          fold (approx_open lib).\n          fold (approx_bts lib).\n          apply approx_bts_refl.\n          allunfold @computes_to_value; repnd.\n          apply compute_max_steps_eauto2 in comp1.\n          apply isprogram_ot_iff in comp1; repnd.\n          introv j; apply comp1 in j; eauto 3 with slow. }\n\n      * exists tl_subterms.\n        dands; auto.\n\n        { allunfold @computes_to_value; repnd; dands; auto.\n          eapply reduces_to_trans;\n            [apply reduces_to_prinarg;exact comp3|].\n          eapply reduces_to_if_split2;\n            [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n          boolvar; ginv; try omega; tcsp.\n          eapply reduces_to_trans;\n            [apply reduces_to_prinarg;exact comp3|].\n          eapply reduces_to_if_split2;\n            [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n          boolvar;tcsp;try omega. }\n\n        { apply clearbot_relbt2.\n          fold (approx_open lib).\n          fold (approx_bts lib).\n          apply approx_bts_refl.\n          allunfold @computes_to_value; repnd.\n          apply compute_max_steps_eauto2 in comp1.\n          apply isprogram_ot_iff in comp1; repnd.\n          introv j; apply comp1 in j; eauto 3 with slow. }\n\n  - introv comp.\n    apply computes_to_exception_mk_less in comp;\n      try (apply wf_less); eauto 3 with slow.\n    repndors; exrepnd.\n\n    + apply reduces_to_if_isvalue_like in comp2; eauto 3 with slow.\n      unfold mk_nat in comp2; ginv; fold_terms.\n      repndors; repnd; subst.\n\n      * exists a e.\n        applydup @preserve_program_exc2 in comp1; eauto 3 with slow; repnd.\n        dands; try (complete (left; apply approx_refl; eauto with slow)).\n\n        eapply reduces_to_trans;\n          [apply reduces_to_prinarg;exact comp0|].\n        eapply reduces_to_if_split2;\n          [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n        boolvar; ginv; try omega.\n        eapply reduces_to_trans;\n          [apply reduces_to_prinarg;exact comp0|].\n        eapply reduces_to_if_split2;\n          [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n        boolvar; tcsp; try omega.\n\n      * apply computes_to_exception_mk_int_eq in comp1; eauto 3 with slow.\n        repndors; exrepnd.\n\n        { apply reduces_to_if_isvalue_like in comp4; eauto 3 with slow.\n          destruct pk2; allsimpl; ginv.\n          unfold mk_nat in comp4; ginv; fold_terms.\n          eapply reduces_to_eq_val_like in comp0;\n            [|exact comp3\n             |eauto 3 with slow\n             |eauto 3 with slow].\n          destruct pk1; allsimpl; ginv.\n          repndors; repnd; subst; ginv.\n\n          - exists a e.\n            applydup @preserve_program_exc2 in comp1; eauto 3 with slow; repnd.\n            dands; try (complete (left; apply approx_refl; eauto with slow)).\n\n            eapply reduces_to_trans;\n              [apply reduces_to_prinarg;exact comp3|].\n            eapply reduces_to_if_split2;\n              [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n            boolvar; try omega; tcsp.\n\n          - exists a e.\n            applydup @preserve_program_exc2 in comp1; eauto 3 with slow; repnd.\n            dands; try (complete (left; apply approx_refl; eauto with slow)).\n\n            eapply reduces_to_trans;\n              [apply reduces_to_prinarg;exact comp3|].\n            eapply reduces_to_if_split2;\n              [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n            boolvar; try omega; tcsp.\n\n            eapply reduces_to_trans;\n              [apply reduces_to_prinarg;exact comp3|].\n            eapply reduces_to_if_split2;\n              [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n            boolvar; try omega; ginv; tcsp.\n        }\n\n        { exists a e.\n          applydup @preserve_program_exc2 in comp1; eauto 3 with slow; repnd.\n          dands; try (complete (left; apply approx_refl; eauto with slow)).\n\n          eapply reduces_to_trans;\n            [apply reduces_to_prinarg;exact comp1|].\n          apply reduces_to_if_step; csunf; simpl; auto.\n        }\n\n        { apply can_doesnt_raise_an_exception in comp3; sp. }\n\n    + exists a e.\n      applydup @preserve_program_exc2 in comp; eauto 3 with slow; repnd.\n      dands; try (complete (left; apply approx_refl; eauto with slow)).\n\n      eapply reduces_to_trans;\n        [apply reduces_to_prinarg;exact comp|].\n      apply reduces_to_if_step; csunf; simpl; auto.\n\n    + apply can_doesnt_raise_an_exception in comp0; sp.\n\n  - introv comp.\n    apply computes_to_seq_implies_computes_to_value in comp;\n      [|apply isprogram_mk_less; dands; eauto 3 with slow;\n        apply isprogram_mk_int_eq; dands; eauto 3 with slow].\n\n    apply computes_to_value_mk_less in comp;\n      try (apply wf_less); eauto 3 with slow.\n    exrepnd.\n    apply reduces_to_if_isvalue_like in comp2; eauto 3 with slow.\n    unfold mk_nat in comp2; ginv; fold_terms.\n    repndors; repnd; subst.\n\n    + exists f.\n      dands; auto;\n      [|introv; left; apply approx_refl;\n        destruct comp1 as [comp isv];\n        inversion isv; eauto 3 with slow].\n\n      allunfold @computes_to_value; repnd; dands; auto.\n      eapply reduces_to_trans;\n        [apply reduces_to_prinarg;exact comp0|].\n      eapply reduces_to_if_split2;\n        [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n      boolvar; ginv; try omega.\n      eapply reduces_to_trans;\n        [apply reduces_to_prinarg;exact comp0|].\n      eapply reduces_to_if_split2;\n        [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n      boolvar; tcsp; try omega.\n\n    + apply computes_to_value_mk_int_eq in comp1; eauto 3 with slow.\n      exrepnd.\n      apply reduces_to_if_isvalue_like in comp4; eauto 3 with slow.\n      destruct pk2; allsimpl; ginv.\n      unfold mk_nat in comp4; ginv; fold_terms.\n      eapply reduces_to_eq_val_like in comp0;\n        [|exact comp3\n         |eauto 3 with slow\n         |eauto 3 with slow].\n      destruct pk1; allsimpl; ginv.\n      repndors; repnd; subst; ginv.\n\n      * exists f.\n        dands; auto;\n        [|introv; left; apply approx_refl;\n          destruct comp1 as [comp isv];\n          inversion isv; eauto 3 with slow].\n\n        allunfold @computes_to_value; repnd; dands; auto.\n        eapply reduces_to_trans;\n          [apply reduces_to_prinarg;exact comp3|].\n        eapply reduces_to_if_split2;\n          [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n        boolvar; try omega; tcsp.\n\n      * exists f.\n        dands; auto;\n        [|introv; left; apply approx_refl;\n          destruct comp1 as [comp isv];\n          inversion isv; eauto 3 with slow].\n\n        allunfold @computes_to_value; repnd; dands; auto.\n        eapply reduces_to_trans;\n          [apply reduces_to_prinarg;exact comp3|].\n        eapply reduces_to_if_split2;\n          [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n        boolvar; ginv; try omega; tcsp.\n        eapply reduces_to_trans;\n          [apply reduces_to_prinarg;exact comp3|].\n        eapply reduces_to_if_split2;\n          [csunf;simpl;dcwf h;simpl;unfold compute_step_comp;simpl;auto|].\n        boolvar;tcsp;try omega.\nQed.\n\nLemma cequivc_inteq_less_swap1 {o} :\n  forall lib (t : @CTerm o) n m u v w,\n    m <= n\n    -> cequivc\n         lib\n         (mkc_inteq t (mkc_nat n) u (mkc_less t (mkc_nat m) v w))\n         (mkc_less t (mkc_nat m) v (mkc_inteq t (mkc_nat n) u w)).\nProof.\n  introv ltm.\n  destruct_cterms.\n  unfold cequivc; simpl.\n  split.\n  - apply approx_inteq_less_swap1; auto.\n  - apply approx_less_inteq_swap1; auto.\nQed.\n\nDefinition update_seq {o} (s : @CTerm o) (n m : nat) (v : NVar) :=\n  mkc_lam\n    v\n    (mkcv_inteq\n       [v]\n       (mkc_var v)\n       (mk_cv [v] (mkc_nat n))\n       (mk_cv [v] (mkc_nat m))\n       (mkcv_apply [v] (mk_cv [v] s) (mkc_var v))).\n\nDefinition update_seq_nout {o} (s : @CTerm o) (n : nat) (u : CTerm) (v : NVar) :=\n  mkc_lam\n    v\n    (mkcv_inteq\n       [v]\n       (mkc_var v)\n       (mk_cv [v] (mkc_nat n))\n       (mk_cv [v] u)\n       (mkcv_apply [v] (mk_cv [v] s) (mkc_var v))).\n\nLemma cequivc_lsubstc_mk_update_seq_sp0 {o} :\n  forall lib s n m v w (sub : @CSub o) a b k t c,\n    n <> m\n    -> s <> n\n    -> s <> m\n    -> n <> v\n    -> s <> v\n    -> m <> v\n    -> !LIn n (dom_csub sub)\n    -> !LIn s (dom_csub sub)\n    -> cequivc lib a b\n    -> cequivc\n         lib\n         (lsubstc (mk_update_seq (mk_var s) (mk_var n) (mk_var m) v) w\n                  ((m,a) :: snoc (snoc sub (n,mkc_nat k)) (s,t)) c)\n         (update_seq_nout t k b v).\nProof.\n  introv d1 d2 d3 d4 d5 d6 ni1 ni2 ceq.\n  allunfold @cequivc; simpl.\n  unfold csubst, mk_update_seq.\n  rw @cl_lsubst_lsubst_aux; eauto 3 with slow; simpl.\n  allrw memvar_singleton.\n\n  repeat (boolvar; simpl; tcsp;[]).\n  allrw @sub_filter_nil_r.\n  allrw @csub2sub_snoc.\n  allrw @sub_find_sub_filter_eq.\n  allrw memvar_singleton.\n  repeat (boolvar; simpl; tcsp;[]).\n  allrw @sub_find_snoc.\n  repeat (rw @sub_find_none_if; auto; try (rw @dom_csub_eq;auto);[]).\n  repeat (boolvar; simpl; tcsp; fold_terms;[]).\n\n  apply implies_cequiv_lam;\n    try (apply isprog_vars_mk_int_eq; dands);\n    try (apply isprog_vars_apply_implies);\n    try (apply mk_cv_pf);\n    eauto 2 with slow.\n\n  introv ispu.\n  unfold subst.\n  repeat (rw @cl_lsubst_lsubst_aux; eauto 3 with slow;[]).\n  simpl; boolvar; tcsp.\n  allrw @lsubst_aux_get_cterm.\n\n  apply cequiv_mk_int_eq;\n    [apply cequiv_refl;fold_terms;eauto 3 with slow\n    |apply cequiv_refl;fold_terms;eauto 3 with slow\n    |\n    |apply cequiv_refl;apply isprogram_apply;eauto 3 with slow].\n\n  auto.\nQed.\n\nLemma cequivc_lsubstc_mk_update_seq_sp1 {o} :\n  forall lib s n m v w (sub : @CSub o) a k j t c,\n    n <> m\n    -> s <> n\n    -> s <> m\n    -> n <> v\n    -> s <> v\n    -> m <> v\n    -> !LIn n (dom_csub sub)\n    -> !LIn s (dom_csub sub)\n    -> computes_to_valc lib a (mkc_nat j)\n    -> cequivc\n         lib\n         (lsubstc (mk_update_seq (mk_var s) (mk_var n) (mk_var m) v) w\n                  ((m,a) :: snoc (snoc sub (n,mkc_nat k)) (s,t)) c)\n         (update_seq t k j v).\nProof.\n  introv d1 d2 d3 d4 d5 d6 ni1 ni2 comp.\n  unfold cequivc; simpl.\n  unfold csubst, mk_update_seq.\n  rw @cl_lsubst_lsubst_aux; eauto 3 with slow; simpl.\n  allrw memvar_singleton.\n\n  repeat (boolvar; simpl; tcsp;[]).\n  allrw @sub_filter_nil_r.\n  allrw @csub2sub_snoc.\n  allrw @sub_find_sub_filter_eq.\n  allrw memvar_singleton.\n  repeat (boolvar; simpl; tcsp;[]).\n  allrw @sub_find_snoc.\n  repeat (rw @sub_find_none_if; auto; try (rw @dom_csub_eq;auto);[]).\n  repeat (boolvar; simpl; tcsp; fold_terms;[]).\n\n  apply implies_cequiv_lam;\n    try (apply isprog_vars_mk_int_eq; dands);\n    try (apply isprog_vars_apply_implies);\n    try (apply mk_cv_pf);\n    eauto 2 with slow.\n\n  introv ispu.\n  unfold subst.\n  repeat (rw @cl_lsubst_lsubst_aux; eauto 3 with slow;[]).\n  simpl; boolvar; tcsp.\n  allrw @lsubst_aux_get_cterm.\n\n  apply cequiv_mk_int_eq;\n    [apply cequiv_refl;fold_terms;eauto 3 with slow\n    |apply cequiv_refl;fold_terms;eauto 3 with slow\n    |\n    |apply cequiv_refl;apply isprogram_apply;eauto 3 with slow].\n\n  apply reduces_to_implies_cequiv; eauto 3 with slow.\nQed.\n\nLemma cequivc_lsubstc_mk_update_seq_sp2 {o} :\n  forall lib s n m v w (sub : @CSub o) a k j t u c,\n    n <> m\n    -> s <> n\n    -> s <> m\n    -> n <> v\n    -> s <> v\n    -> m <> v\n    -> !LIn n (dom_csub sub)\n    -> !LIn s (dom_csub sub)\n    -> computes_to_valc lib a (mkc_nat j)\n    -> computes_to_valc lib u (mkc_nat k)\n    -> cequivc\n         lib\n         (lsubstc (mk_update_seq (mk_var s) (mk_var n) (mk_var m) v) w\n                  ((m,a) :: snoc (snoc sub (n,u)) (s,t)) c)\n         (update_seq t k j v).\nProof.\n  introv d1 d2 d3 d4 d5 d6 ni1 ni2 comp1 comp2.\n  unfold cequivc; simpl.\n  unfold csubst, mk_update_seq.\n  rw @cl_lsubst_lsubst_aux; eauto 3 with slow; simpl.\n  allrw memvar_singleton.\n\n  repeat (boolvar; simpl; tcsp;[]).\n  allrw @sub_filter_nil_r.\n  allrw @csub2sub_snoc.\n  allrw @sub_find_sub_filter_eq.\n  allrw memvar_singleton.\n  repeat (boolvar; simpl; tcsp;[]).\n  allrw @sub_find_snoc.\n  repeat (rw @sub_find_none_if; auto; try (rw @dom_csub_eq;auto);[]).\n  repeat (boolvar; simpl; tcsp; fold_terms;[]).\n\n  apply implies_cequiv_lam;\n    try (apply isprog_vars_mk_int_eq; dands);\n    try (apply isprog_vars_apply_implies);\n    try (apply mk_cv_pf);\n    eauto 2 with slow.\n\n  introv ispu.\n  unfold subst.\n  repeat (rw @cl_lsubst_lsubst_aux; eauto 3 with slow;[]).\n  simpl; boolvar; tcsp.\n  allrw @lsubst_aux_get_cterm.\n\n  allunfold @computes_to_valc.\n  allunfold @computes_to_value; repnd.\n\n  apply cequiv_mk_int_eq;\n    [apply cequiv_refl;eauto 3 with slow\n    |apply reduces_to_implies_cequiv;eauto\n    |\n    |apply cequiv_refl;apply isprogram_apply;eauto 3 with slow].\n\n  apply reduces_to_implies_cequiv; eauto 3 with slow.\nQed.\n\nLemma cequivc_lsubstc_mk_update_seq_sp3 {o} :\n  forall lib s n m v w (sub : @CSub o) a b k t u c,\n    n <> m\n    -> s <> n\n    -> s <> m\n    -> n <> v\n    -> s <> v\n    -> m <> v\n    -> !LIn n (dom_csub sub)\n    -> !LIn s (dom_csub sub)\n    -> cequivc lib a b\n    -> cequivc lib u (mkc_nat k)\n    -> cequivc\n         lib\n         (lsubstc (mk_update_seq (mk_var s) (mk_var n) (mk_var m) v) w\n                  ((m,a) :: snoc (snoc sub (n,u)) (s,t)) c)\n         (update_seq_nout t k b v).\nProof.\n  introv d1 d2 d3 d4 d5 d6 ni1 ni2 comp1 comp2.\n  unfold cequivc; simpl.\n  unfold csubst, mk_update_seq.\n  rw @cl_lsubst_lsubst_aux; eauto 3 with slow; simpl.\n  allrw memvar_singleton.\n\n  repeat (boolvar; simpl; tcsp;[]).\n  allrw @sub_filter_nil_r.\n  allrw @csub2sub_snoc.\n  allrw @sub_find_sub_filter_eq.\n  allrw memvar_singleton.\n  repeat (boolvar; simpl; tcsp;[]).\n  allrw @sub_find_snoc.\n  repeat (rw @sub_find_none_if; auto; try (rw @dom_csub_eq;auto);[]).\n  repeat (boolvar; simpl; tcsp; fold_terms;[]).\n\n  apply implies_cequiv_lam;\n    try (apply isprog_vars_mk_int_eq; dands);\n    try (apply isprog_vars_apply_implies);\n    try (apply mk_cv_pf);\n    eauto 2 with slow.\n\n  introv ispu.\n  unfold subst.\n  repeat (rw @cl_lsubst_lsubst_aux; eauto 3 with slow;[]).\n  simpl; boolvar; tcsp.\n  allrw @lsubst_aux_get_cterm.\n\n  allunfold @cequivc.\n\n  apply cequiv_mk_int_eq;\n    [apply cequiv_refl;eauto 3 with slow\n    |auto\n    |auto\n    |apply cequiv_refl;apply isprogram_apply;eauto 3 with slow].\nQed.\n\nLemma cover_vars_upto_add {o} :\n  forall (a b : @NTerm o) sub vs,\n    cover_vars_upto (mk_add a b) sub vs\n    <=> cover_vars_upto a sub vs\n        # cover_vars_upto b sub vs.\nProof.\n  unfold cover_vars_upto; introv; simpl.\n  rw app_nil_r.\n  allrw remove_nvars_nil_l.\n  rw subvars_app_l; sp.\nQed.\n\nLemma cover_vars_upto_one {o} :\n  forall (sub : @CSub o) vs,\n    cover_vars_upto mk_one sub vs.\nProof.\n  unfold cover_vars_upto; introv; simpl; auto.\nQed.\nHint Resolve cover_vars_upto_one : slow.\n\nLemma cover_vars_upto_int_eq {o} :\n  forall vs (a b c d : @NTerm o) sub,\n    cover_vars_upto (mk_int_eq a b c d) sub vs\n    <=> cover_vars_upto a sub vs\n        # cover_vars_upto b sub vs\n        # cover_vars_upto c sub vs\n        # cover_vars_upto d sub vs.\nProof.\n  introv.\n  unfold cover_vars_upto; simpl.\n  allrw remove_nvars_nil_l.\n  allrw app_nil_r.\n  allrw subvars_app_l.\n  sp.\nQed.\n\nLemma cequivc_mkc_apply_lam_axiom {o} :\n  forall lib (a : @CTerm o),\n    cequivc lib (mkc_apply lam_axiom a) mkc_axiom.\nProof.\n  introv.\n  unfold lam_axiom.\n  eapply cequivc_trans;[apply cequivc_beta|].\n  autorewrite with slow; auto.\nQed.\n\nLtac clear_wf_hyps :=\n  repeat match goal with\n           | [ H : cover_vars _ _ |- _ ] => clear H\n           | [ H : wf_term _ |- _ ] => clear H\n         end.\n\nDefinition seq_normalizable {o} lib (s : @CTerm o) n v :=\n  cequivc lib s (seq2kseq s n v).\n\nLemma cequivc_seq2kseq_twice {o} :\n  forall lib (s : @CTerm o) n v,\n    cequivc lib (seq2kseq s n v) (seq2kseq (seq2kseq s n v) n v).\nProof.\n  introv.\n  unfold seq2kseq.\n\n  apply implies_cequivc_lam.\n  introv.\n  allrw @mkcv_less_substc.\n  allrw @mkcv_apply_substc.\n  allrw @mkc_var_substc.\n  allrw @mkcv_bot_substc.\n  allrw @csubst_mk_cv.\n  allrw @mkcv_nat_substc.\n  allrw @mkcv_zero_substc.\n\n  apply implies_cequivc_mkc_less1.\n  introv compu.\n  allrw @mkc_zero_eq.\n  allrw (@mkc_nat_eq o 0).\n\n  eapply cequivc_trans;[apply cequivc_mkc_less_int|].\n  eapply cequivc_trans;[|apply cequivc_sym;apply cequivc_mkc_less_int].\n  boolvar; auto.\n\n  eapply cequivc_trans;\n    [apply cequivc_mkc_less;\n      [apply computes_to_valc_implies_cequivc;exact compu\n      |apply cequivc_refl\n      |apply cequivc_refl\n      |apply cequivc_refl]\n    |].\n\n  eapply cequivc_trans;\n    [|apply cequivc_sym;apply cequivc_mkc_less;\n      [apply computes_to_valc_implies_cequivc;exact compu\n      |apply cequivc_refl\n      |apply cequivc_refl\n      |apply cequivc_refl]\n    ].\n\n  apply Wf_Z.Z_of_nat_complete_inf in l; exrepnd; subst; fold_terms.\n  allrw <- @mkc_nat_eq.\n\n  eapply cequivc_trans;[apply cequivc_mkc_less_nat|].\n  eapply cequivc_trans;[|apply cequivc_sym;apply cequivc_mkc_less_nat].\n\n  boolvar; auto.\n\n  eapply cequivc_trans;\n    [apply implies_cequivc_apply;\n      [apply cequivc_refl\n      |apply computes_to_valc_implies_cequivc;exact compu]\n    |].\n\n  eapply cequivc_trans;\n    [|apply cequivc_sym;apply cequivc_beta].\n  allrw @mkcv_less_substc.\n  allrw @mkcv_apply_substc.\n  allrw @mkc_var_substc.\n  allrw @mkcv_bot_substc.\n  allrw @csubst_mk_cv.\n  allrw @mkcv_nat_substc.\n  allrw @mkcv_zero_substc.\n\n  eapply cequivc_trans;\n    [|apply cequivc_sym;apply cequivc_mkc_less;\n      [apply computes_to_valc_implies_cequivc;exact compu\n      |apply cequivc_refl\n      |apply cequivc_refl\n      |apply cequivc_mkc_less;\n        [apply computes_to_valc_implies_cequivc;exact compu\n        |apply cequivc_refl\n        |apply cequivc_refl\n        |apply cequivc_refl]\n      ]\n    ].\n\n  allrw @mkc_zero_eq.\n\n  eapply cequivc_trans;[|apply cequivc_sym;apply cequivc_mkc_less_nat].\n  boolvar; auto; try omega.\n  eapply cequivc_trans;[|apply cequivc_sym;apply cequivc_mkc_less_nat].\n  boolvar; auto; try omega.\n\n  eapply cequivc_trans;\n    [|apply cequivc_sym;apply implies_cequivc_apply;\n      [apply cequivc_refl\n      |apply computes_to_valc_implies_cequivc;exact compu]\n    ].\n  auto.\nQed.\n\nLemma seq_normalizable_seq2kseq {o} :\n  forall lib (s : @CTerm o) n v,\n    seq_normalizable lib (seq2kseq s n v) n v.\nProof.\n  introv.\n  apply cequivc_seq2kseq_twice.\nQed.\n\nLemma implies_cequivc_natk2nout {o} :\n  forall lib (t1 t2 : @CTerm o),\n    cequivc lib t1 t2\n    -> cequivc lib (natk2nout t1) (natk2nout t2).\nProof.\n  introv ceq.\n  unfold natk2nout.\n  apply cequivc_mkc_fun;[|apply cequivc_refl].\n  apply cequivc_mkc_natk; auto.\nQed.\n\nLemma covered_member {o} :\n  forall (a b : @NTerm o)s,\n    covered (mk_member a b) s <=> (covered a s # covered b s).\nProof.\n  introv; unfold covered; simpl; autorewrite with slow.\n  allrw subvars_app_l; split; 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/cequiv/cequiv_seq_util.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.28211478544317137}}
{"text": "From MetaCoq.Template Require Import config utils.\nFrom MetaCoq.PCUIC Require Import PCUICAst PCUICAstUtils\n  PCUICLiftSubst PCUICUnivSubst PCUICEquality PCUICUtils PCUICPosition.\nFrom MetaCoq.PCUIC Require Export PCUICCumulativitySpec.\nFrom MetaCoq.PCUIC Require Export PCUICCases PCUICNormal.\nRequire Import MLTTTyping LogicalRelation.\n\nFixpoint LR_rec0\n  (c : context) (t : term) (rEq rTe : term -> Type)\n  (rTeEq  : term -> term -> Type) (lr : LR rec0 c t rEq rTe rTeEq ) : \n  forall \n  (P0 : forall {c t rEq rTe rTeEq} ,\n   @LR zero rec0 c t rEq rTe rTeEq  -> Type),\n  (forall (Γ : context) (A : term) (neA : [Γ ||-ne A]),\n    P0 (LRne rec0 neA))\n  ->\n  (forall (Γ : context) (A : term) (H0 : [ Γ ||-0Π A ]) (H1 : [ LR rec0 ||-1Π H0 ]),\n    (forall {Δ} (h : [ |- Δ]),\n      P0(H1.(_F1) h)) ->\n    (forall {Δ a} (h1 : [ |- Δ ]) \n      (h2 : [ Δ ||-1 a ::: F H0 | {|valid := H1.(_F1) h1|} ]),\n      P0 (_G1 H1 h1 h2)) ->\n    P0 (LRPi rec0 H0 H1))\n  ->\n   P0 lr.\nProof.   \n   intros.\n   destruct lr.\n   1,4 : inversion l_.\n   eapply X; try eassumption.\n   eapply X0; try eassumption;\n   destruct H1; destruct H0;\n   intros;\n   apply LR_rec0; try assumption.\nDefined.\n\n(*TODO : get a good induction principle*)\n(*Scheme LR_rect := Induction for LR Sort Type.*)\nFixpoint LR_rec1 \n  (c : context) (t : term) (rEq rTe : term -> Type)\n  (rTeEq  : term -> term -> Type) (lr : LR rec1 c t rEq rTe rTeEq ) : \n  forall \n  (P0 : forall {c t rEq rTe rTeEq} ,\n   @LR zero rec0 c t rEq rTe rTeEq  -> Type)\n  (P1 : forall {c t rEq rTe rTeEq} ,\n   @LR one rec1 c t rEq rTe rTeEq  -> Type),\n  (forall (Γ : context) (A : term) (neA : [Γ ||-ne A]),\n    P0 (LRne rec0 neA)) \n  ->\n  (forall (Γ : context) (A : term) (H0 : [ Γ ||-0Π A ]) (H1 : [ LR rec0 ||-1Π H0 ]),\n    (forall {Δ} (h : [ |- Δ]),\n      P0 (H1.(_F1) h)) ->\n    (forall {Δ a} (h1 : [ |- Δ ]) \n      (h2 : [ Δ ||-1 a ::: F H0 | {|valid := H1.(_F1) h1|} ]),\n      P0 (_G1 H1 h1 h2)) ->\n    P0 (LRPi rec0 H0 H1)) \n  ->\n\n  (forall (Γ : context) (h : [  |- Γ]) {l' l_},\n    P1 (LRU rec1 h l' l_)) \n  ->\n  (forall (Γ : context) (A : term) (neA : [Γ ||-ne A]),\n    P1 (LRne rec1 neA)) \n  ->\n  (forall (Γ : context) (A : term) (H0 : [ Γ ||-0Π A ]) (H1 : [ LR rec1 ||-1Π H0 ]),\n  (forall {Δ} (h : [ |- Δ]),\n    P1 (H1.(_F1) h)) ->\n  (forall {Δ a} (h1 : [ |- Δ ]) \n    (h2 : [ Δ ||-1 a ::: F H0 | {|valid := H1.(_F1) h1|} ]),\n    P1 (_G1 H1 h1 h2)) ->\n  P1 (LRPi rec1 H0 H1)) \n  ->\n\n  (forall (Γ : context) (A : term) {l' l_}\n    (H : [kit0 | Γ ||- A]),\n    \n    P0 H.(valid) ->\n    P1 (@LRemb _ _ _ _ l' l_ H)) ->\n\n    P1 lr.\nProof.\n  intros.\n  destruct lr.\n  eapply X1; try eassumption.\n  eapply X2; try eassumption.\n  destruct H1;destruct H0.\n  eapply X3;\n  intros;\n  eapply LR_rec1; try eassumption.\n  eapply X4.\n  destruct H.\n  inversion valid.\n  1, 4 : inversion l_0.\n  all : eapply LR_rec0; assumption.\nDefined.\n\nDefinition LR_rect0 : forall\n  (P0 : forall {c t rEq rTe rTeEq} ,\n   @LR zero rec0 c t rEq rTe rTeEq  -> Type),\n  (forall (Γ : context) (A : term) (neA : [Γ ||-ne A]),\n    P0 (LRne rec0 neA))\n  ->\n  (forall (Γ : context) (A : term) (H0 : [ Γ ||-0Π A ]) (H1 : [ LR rec0 ||-1Π H0 ]),\n    (forall {Δ} (h : [ |- Δ]),\n      P0(H1.(_F1) h)) ->\n    (forall {Δ a} (h1 : [ |- Δ ]) \n      (h2 : [ Δ ||-1 a ::: F H0 | {|valid := H1.(_F1) h1|} ]),\n      P0 (_G1 H1 h1 h2)) ->\n    P0 (LRPi rec0 H0 H1)) \n  ->\n   forall(c : context) (t : term) (rEq rTe : term -> Type)\n  (rTeEq  : term -> term -> Type) (lr : LR rec0 c t rEq rTe rTeEq ),\n   P0 lr.\nProof.\n  intros.\n  eapply LR_rec0; eassumption.\nDefined.\n\nDefinition LR_rect1 : \n  forall \n  (P0 : forall {c t rEq rTe rTeEq} ,\n   @LR zero rec0 c t rEq rTe rTeEq  -> Type)\n  (P1 : forall {c t rEq rTe rTeEq} ,\n   @LR one rec1 c t rEq rTe rTeEq  -> Type),\n  (forall (Γ : context) (A : term) (neA : [Γ ||-ne A]),\n    P0 (LRne rec0 neA)) \n  ->\n  (forall (Γ : context) (A : term) (H0 : [ Γ ||-0Π A ]) (H1 : [ LR rec0 ||-1Π H0 ]),\n    (forall {Δ} (h : [ |- Δ]),\n      P0 (H1.(_F1) h)) ->\n    (forall {Δ a} (h1 : [ |- Δ ]) \n      (h2 : [ Δ ||-1 a ::: F H0 | {|valid := H1.(_F1) h1|} ]),\n      P0 (_G1 H1 h1 h2)) ->\n    P0 (LRPi rec0 H0 H1)) \n  ->\n\n\n  (forall (Γ : context) (h : [  |- Γ]) {l' l_},\n    P1 (LRU rec1 h l' l_)) \n  ->\n  (forall (Γ : context) (A : term) (neA : [Γ ||-ne A]),\n    P1 (LRne rec1 neA)) \n  ->\n  (forall (Γ : context) (A : term) (H0 : [ Γ ||-0Π A ]) (H1 : [ LR rec1 ||-1Π H0 ]),\n  (forall {Δ} (h : [ |- Δ]),\n    P1 (H1.(_F1) h)) ->\n  (forall {Δ a} (h1 : [ |- Δ ]) \n    (h2 : [ Δ ||-1 a ::: F H0 | {|valid := H1.(_F1) h1|} ]),\n    P1 (_G1 H1 h1 h2)) ->\n  P1 (LRPi rec1 H0 H1)) \n  ->\n\n\n  (forall (Γ : context) (A : term) {l' l_}\n    (H : [kit0 | Γ ||- A]),\n    \n    P0 H.(valid) ->\n    P1 (@LRemb _ _ _ _ l' l_ H)) ->\n  forall (c : context) (t : term) (rEq rTe : term -> Type)\n  (rTeEq  : term -> term -> Type) (lr : LR rec1 c t rEq rTe rTeEq ),\n    P1 lr.\nProof.\n  intros.\n  eapply LR_rec1; eassumption.\nDefined.\n", "meta": {"author": "arthur-adjedj", "repo": "logrel", "sha": "e79e98dc8dfe6628f7870da1952f319a82a8ed71", "save_path": "github-repos/coq/arthur-adjedj-logrel", "path": "github-repos/coq/arthur-adjedj-logrel/logrel-e79e98dc8dfe6628f7870da1952f319a82a8ed71/LRInduction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.28211478544317137}}
{"text": "From Autosubst Require Export Autosubst.\nFrom iris.program_logic Require Export language ectx_language ectxi_language.\n\n(** Expressions *)\nInductive expr :=\n| Var (x : var)\n| Lam (e : {bind 1 of expr})\n| App (e1 e2 : expr)\n(* Base types *)\n| Unit\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 : {bind expr}) (e2 : {bind expr})\n(* Recursive Types *)\n| Fold (e : expr)\n| Unfold (e : expr).\n\nCoercion App : expr >-> Funclass.\n\nInstance Ids_expr : Ids expr. derive. Defined.\nInstance Rename_expr : Rename expr. derive. Defined.\nInstance Subst_expr : Subst expr. derive. Defined.\nInstance SubstLemmas_expr : SubstLemmas expr. derive. Qed.\n\n(** Values *)\nInductive val :=\n| LamV (e : {bind 1 of expr})\n| UnitV\n| PairV (v1 v2 : val)\n| InjLV (v : val)\n| InjRV (v : val)\n| FoldV (v : val).\n\nFixpoint of_val (v : val) : expr :=\n  match v with\n  | LamV e => Lam e\n  | UnitV => Unit\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  | FoldV v => Fold (of_val v)\n  end.\n(* Notation \"# v\" := (of_val v) (at level 20). *)\n\nCoercion of_val : val >-> expr.\n\nFixpoint to_val (e : expr) : option val :=\n  match e with\n  | Lam e => Some (LamV e)\n  | Unit => Some UnitV\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  | Fold e => v ← to_val e; Some (FoldV v)\n  | _ => None\n  end.\n\n(** Evaluation contexts of depth 1 *)\n(** General evalution contexts are represented by `list ectx_item` *)\nInductive ectx_item :=\n| AppLCtx (e2 : expr)\n| AppRCtx (v1 : val)\n| PairLCtx (e2 : expr)\n| PairRCtx (v1 : val)\n| FstCtx\n| SndCtx\n| InjLCtx\n| InjRCtx\n| CaseCtx (e1 : {bind expr}) (e2 : {bind expr})\n| FoldCtx\n| UnfoldCtx.\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  | 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  | FoldCtx => Fold e\n  | UnfoldCtx => Unfold e\n  end.\n\nDefinition state : Type := ().\n\n(** Head steps *)\nInductive head_step : expr → state → list Empty_set → expr → state → list expr → Prop :=\n(* β *)\n| BetaS e1 e2 v2 σ :\n    to_val e2 = Some v2 →\n    head_step (App (Lam e1) e2) σ [] e1.[e2/] σ []\n(* Products *)\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 σ []\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 σ []\n(* Sums *)\n| CaseLS e0 v0 e1 e2 σ :\n    to_val e0 = Some v0 →\n    head_step (Case (InjL e0) e1 e2) σ [] e1.[e0/] σ []\n| CaseRS e0 v0 e1 e2 σ :\n    to_val e0 = Some v0 →\n    head_step (Case (InjR e0) e1 e2) σ [] e2.[e0/] σ []\n(* Recursive Types *)\n| Unfold_Fold e v σ :\n    to_val e = Some v →\n    head_step (Unfold (Fold e)) σ [] e σ [].\n\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 v; induction e; intros; simplify_option_eq; auto with f_equal.\nQed.\n\nInstance of_val_inj : Inj (=) (=) of_val.\nProof. by intros ?? Hv; apply (inj Some); rewrite -!to_of_val Hv. 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\nInstance fill_item_inj Ki : Inj (=) (=) (fill_item Ki).\nProof. destruct Ki; intros ???; simplify_eq; auto with f_equal. Qed.\n\nLemma val_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 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\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 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.\n\nCanonical Structure stateO := leibnizO state.\nCanonical Structure valO := leibnizO val.\nCanonical Structure exprO := leibnizO expr.\n\n(** `EctxiLanguage` naturally extents our evaluation contexts of depth 1, and it naturally defines our total reduction relation *)\nCanonical Structure ectxi_lang := EctxiLanguage lang_mixin.\nCanonical Structure ectx_lang := EctxLanguageOfEctxi ectxi_lang.\nCanonical Structure lang := LanguageOfEctx ectx_lang.\n\nHint Extern 20 (PureExec _ _ _) => progress simpl : typeclass_instances.\n\nHint Extern 5 (IntoVal _ _) => eapply of_to_val; fast_done : typeclass_instances.\nHint Extern 10 (IntoVal _ _) =>\n  rewrite /IntoVal; eapply of_to_val; rewrite /= !to_of_val /=; solve [ eauto ] : typeclass_instances.\n\nHint Extern 5 (AsVal _) => eexists; eapply of_to_val; fast_done : typeclass_instances.\nHint Extern 10 (AsVal _) =>\n  eexists; rewrite /IntoVal; eapply of_to_val; rewrite /= !to_of_val /=; solve [ eauto ] : typeclass_instances.\n\n(** Definition of halting *)\nDefinition Halts (e : expr) :=\n  ∃ v, rtc erased_step ([e], tt) ([of_val v], tt).\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/stlc_mu/lang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.28211478544317137}}
{"text": "(*\n  vim: filetype=coq\n*)\n(*\nCopyright (C) 2016-2018 Philip H. Smith\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n*)\n\nRequire Import Way.Tactics.\n\nRequire Import Way.List.\nRequire Import Way.Nat.\n\nLemma has_le_fold_max : forall (n : nat) (l : list nat), has n l -> n <= fold max 0 l.\nProof.\n  intro n;\n  induction l;\n  [ infer\n  | infer from eq_nat_dec le_max_l (le_trans n (fold max 0 l)) le_max_r ].\nDefined.\n\nLemma fold_max_lt_not_has :\n  forall (n : nat) (l : list nat), fold max 0 l < n -> ~ has n l.\nProof.\n  intros n l;\n  infer from has_le_fold_max (le_lt_trans n (fold max 0 l)) (lt_irrefl n).\nDefined.\n\nLemma fresh_nat : forall (l : list nat), {n : nat | ~ has n l}.\nProof.\n  intro l;\n  exists (S (fold max 0 l));\n  infer from fold_max_lt_not_has.\nDefined.\n", "meta": {"author": "waylang", "repo": "metatheory", "sha": "dccc759ebd029c7a1d77a53eb74cb2e36e22fd37", "save_path": "github-repos/coq/waylang-metatheory", "path": "github-repos/coq/waylang-metatheory/metatheory-dccc759ebd029c7a1d77a53eb74cb2e36e22fd37/metatheory/Way/ListNat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.5234203489363239, "lm_q1q2_score": 0.28211477769101206}}
{"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 dummyRequest : UpdateRequestLRecord := Eval compute in default. \n\nDefinition REU_1 l id (codeHash :  option uint256) (owners :  optional (listArray uint256)) (reqConfirms : optional uint8) (lifetime :  optional   uint32) : Prop := \n  let m_lifetime := uint2N (toValue (eval_state (sRReader (m_lifetime_right rec def) ) l)) in (* TODO *)\n  let tvm_now := uint2N (toValue (eval_state (sRReader || now ||) l)) in\n  let l' := exec_state (Uinterpreter (_removeExpiredTransactions rec def)) l in \n  let ret_l := exec_state (Uinterpreter (_removeExpiredUpdateRequests rec def)) l in \n  let m_updateRequests := toValue (eval_state (sRReader (m_updateRequests_right rec def) ) l) in\n  let m_updateRequests' := toValue (eval_state (sRReader (m_updateRequests_right rec def) ) ret_l) in\n  let m_updateRequestsMask := toValue (eval_state (sRReader (m_updateRequestsMask_right rec def) ) ret_l) in\n  isError (eval_state (Uinterpreter (submitUpdate rec def codeHash owners reqConfirms lifetime)) l) = false -> \n  hmapIsMember id m_updateRequests = true ->\n  N.shiftr 32 (uint2N id) + m_lifetime <= tvm_now <->\n  hmapIsMember id m_updateRequests = true /\\\n  hmapIsMember id m_updateRequests' = false /\\\n  N.shiftl (uint2N id) (uint2N m_updateRequestsMask) = 0.\n\n\nDefinition CUE_1 l (updateId :  uint64) (code : optional cell_) : Prop :=\n  let msgPubkey := toValue (eval_state (sRReader || msg->pubkey() || ) l) in\n  let custodians := toValue (eval_state (sRReader (m_custodians_right rec def) ) l) in\n  isError (eval_state (Uinterpreter (executeUpdate rec def updateId code)) l) = false -> \n  hmapIsMember msgPubkey custodians = true.\n\nDefinition CUE_2 l id (updateId :  uint64) (code : optional cell_) (custodianIndex :  uint8) (codeHash : optional uint256) (owners : optional (listArray uint256)) (reqConfirms : optional uint8) (lifetime :  optional   uint32) : Prop := \n  let custodians := toValue (eval_state (sRReader (m_custodians_right rec def) ) l) in\n  let msgPubkey := toValue (eval_state (sRReader || msg->pubkey() ||) l) in\n  let l' := exec_state (Uinterpreter (_confirmUpdate rec def updateId custodianIndex)) l in\n  let transactions := toValue (eval_state (sRReader (m_transactions_right rec def) ) l') in\n  correctState l ->\n  isError (eval_state (Uinterpreter (executeUpdate rec def updateId code)) l) = false -> \n  hmapIsMember msgPubkey custodians = true ->\n  REU_1 l' id codeHash owners reqConfirms lifetime.\n\nDefinition CUE_3 l id (updateId :  uint64) (code : optional cell_) (codeHash : optional uint256) (owners : optional (listArray uint256)) (reqConfirms : optional uint8) (lifetime :  optional   uint32) : Prop := \n  let l' := exec_state (Uinterpreter (executeUpdate rec def updateId code)) l in\n  let m_updateRequests := toValue (eval_state (sRReader (m_updateRequests_right rec def) ) l') in\n  let u := xMaybeMapDefault (fun x => x) (hmapLookup id m_updateRequests) dummyRequest  in\n  let tr_id := getPruvendoRecord UpdateRequest_ι_id u in \n  correctState l ->\n  isError (eval_state (Uinterpreter (executeUpdate rec def updateId code)) l) = false -> \n  hmapIsMember id m_updateRequests = true ->\n  REU_1 l' id codeHash owners reqConfirms lifetime ->\n  tr_id = id.  \n\n\nDefinition CUE_4 l id (updateId :  uint64)  (code : optional cell_) (codeHash : optional uint256) (owners : optional (listArray uint256)) (reqConfirms : optional uint8) (lifetime :  optional   uint32) : Prop := \n  let l' := exec_state (Uinterpreter (executeUpdate rec def updateId code)) l in\n  let m_updateRequests := toValue (eval_state (sRReader (m_updateRequests_right rec def) ) l') in\n  let m_custodians := toValue (eval_state (sRReader (m_custodians_right rec def) ) l') in\n  let u := xMaybeMapDefault (fun x => x) (hmapLookup id m_updateRequests) dummyRequest  in\n  let tr_id := getPruvendoRecord UpdateRequest_ι_id u in \n  let signs := uint2N (getPruvendoRecord UpdateRequest_ι_signs u) in \n  correctState l ->\n  isError (eval_state (Uinterpreter (executeUpdate rec def updateId code)) l) = false -> \n  hmapIsMember id m_updateRequests = true ->\n  REU_1 l' id codeHash owners reqConfirms lifetime ->\n  tr_id = id -> 3 * signs >= 2 * (length_ m_custodians)\n  .\n\nDefinition CUE_6_2 l (updateId :  uint64)  (code : optional cell_) : Prop := \n  let l' := exec_state (Uinterpreter (executeUpdate rec def updateId code)) l in\n  let m_updateRequests := toValue (eval_state (sRReader (m_updateRequests_right rec def) ) l') in\n  let m_updateRequests_old := toValue (eval_state (sRReader (m_updateRequests_right rec def) ) l) in\n  let m_lifetime := toValue (eval_state (sRReader (m_lifetime_right rec def) ) l') in\n  let m_lifetime_old := toValue (eval_state (sRReader (m_lifetime_right rec def) ) l) in\n  let tvm_now := uint2N (toValue (eval_state (sRReader || now ||) l)) in\n  let expiredRequests := xHMapFilter (fun k v =>\n    N.leb ((N.shiftr (uint2N k) 32) + uint2N m_lifetime_old) tvm_now\n  ) m_updateRequests_old in\n  let commonRequests := xHMapFilter (fun k v => \n    andb (hmapIsMember k m_updateRequests_old)\n    (Common.eqb v (hmapFindWithDefault dummyRequest k m_updateRequests_old))) m_updateRequests in\n  let ur := xMaybeMapDefault (fun x => x) (hmapLookup updateId m_updateRequests_old) dummyRequest  in\n  let owners := getPruvendoRecord UpdateRequest_ι_custodians ur in \n  let reqConfirms := getPruvendoRecord UpdateRequest_ι_reqConfirms ur in \n  let lifetime := getPruvendoRecord UpdateRequest_ι_lifetime ur in\n  let ecode := (toValue (eval_state (sRReader || tvm->code() ||) l')) in\n  let ecode_old := (toValue (eval_state (sRReader || tvm->code() ||) l)) in\n  let ccode := (toValue (eval_state (sRReader || tvm->currentCode() ||) l')) in\n  let ccode_old := (toValue (eval_state (sRReader || tvm->currentCode() ||) l)) in\n  let m_custodians := toValue (eval_state (sRReader (m_custodians_right rec def) ) l') in\n  let m_custodians_old := toValue (eval_state (sRReader (m_custodians_right rec def) ) l) in\n  let m_ownerKey_old := toValue (eval_state (sRReader (m_ownerKey_right rec def) ) l) in\n  let m_ownerKey := toValue (eval_state (sRReader (m_ownerKey_right rec def) ) l') in\n  let m_defaultRequiredConfirmations := toValue (eval_state (sRReader (m_defaultRequiredConfirmations_right rec def) ) l') in\n  let m_defaultRequiredConfirmations_old := toValue (eval_state (sRReader (m_defaultRequiredConfirmations_right rec def) ) l) in\n  let DEFAULT_LIFETIME := toValue (eval_state (sRReader (DEFAULT_LIFETIME_right rec def) ) l) in\n  let m_requestsMask := toValue (eval_state (sRReader (m_requestsMask_right rec def) ) l') in\n  let m_updateRequestsMask := toValue (eval_state (sRReader (m_updateRequestsMask_right rec def) ) l') in\n  let m_transactions := toValue (eval_state (sRReader (m_transactions_right rec def) ) l') in\n  correctState l ->\n  isError (eval_state (Uinterpreter (executeUpdate rec def updateId code)) l) = false -> \n  length_ m_updateRequests_old - length_ expiredRequests - 1 = length_ m_updateRequests /\\\n  length_ commonRequests = length_ m_updateRequests_old /\\\n  (xMaybeIsSome code = true -> \n        ccode = xMaybeMapDefault Datatypes.id code default /\\\n        ecode = xMaybeMapDefault Datatypes.id code default\n  ) /\\\n  (xMaybeIsSome code = false ->\n        ccode = ccode_old /\\ ecode = ecode_old) /\\\n  (xMaybeIsSome owners = true -> length_ (xMaybeMapDefault Datatypes.id owners default) >= length_ m_custodians ) /\\\n  (xMaybeIsSome owners = true -> checkMap1 m_custodians = true) /\\\n  checkMap2 m_custodians (N.to_nat (length_ (xMaybeMapDefault Datatypes.id owners default))) (xMaybeMapDefault Datatypes.id owners default) = true /\\\n  (xMaybeIsSome owners = false -> m_custodians = m_custodians_old /\\ m_ownerKey = m_ownerKey_old) /\\\n  (xMaybeIsSome reqConfirms = true -> uint2N m_defaultRequiredConfirmations = N.min (length_ m_custodians) (uint2N (xMaybeMapDefault Datatypes.id reqConfirms default))) /\\\n  (xMaybeIsSome reqConfirms = false -> m_defaultRequiredConfirmations = m_defaultRequiredConfirmations_old) /\\\n  (xMaybeIsSome lifetime = false -> m_lifetime = m_lifetime_old) /\\\n  (xMaybeIsSome lifetime = true -> uint2N (xMaybeMapDefault Datatypes.id lifetime default) > 0 -> m_lifetime = (xMaybeMapDefault Datatypes.id lifetime default)) /\\\n  (xMaybeIsSome lifetime = true -> uint2N (xMaybeMapDefault Datatypes.id lifetime default) = 0 -> m_lifetime = DEFAULT_LIFETIME) /\\\n  N.land (uint2N m_updateRequestsMask) (0xFFFFFFFF) = 0 /\\\n  m_transactions = default /\\\n  m_updateRequests = default /\\\n  uint2N m_requestsMask = 0.", "meta": {"author": "Pruvendo", "repo": "multisig2", "sha": "d4f8242ecfb79b9f8f61dcbc9d19f889c7051d6c", "save_path": "github-repos/coq/Pruvendo-multisig2", "path": "github-repos/coq/Pruvendo-multisig2/multisig2-d4f8242ecfb79b9f8f61dcbc9d19f889c7051d6c/src/ursus/CUE/Props.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.28209250001140973}}
{"text": "From mathcomp Require Import ssreflect ssrbool ssrfun ssrnat eqtype seq fintype ssrint.\nFrom extructures Require Import ord fmap.\nFrom CoqUtils Require Import hseq word.\n\nRequire Import lib.utils.\nRequire Import common.types.\nRequire Import concrete.concrete.\nRequire Import concrete.int_32.\nRequire Import symbolic.symbolic.\nRequire Import symbolic.int_32.\nRequire Import symbolic.refinement_common.\nRequire Import symbolic.backward.\nRequire Import symbolic.rules.\nRequire Import cfi.classes.\nRequire Import cfi.rules.\nRequire Import cfi.symbolic.\nRequire Import cfi.abstract.\nRequire Import cfi.refinementAS.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nModule CFIInstances.\n\nSection WithClasses.\n\n(* ---------------------------------------------------------------- *)\n(* int32 instance *)\n\nDefinition mt := concrete_int_32_mt.\nInstance ops : machine_ops mt := concrete_int_32_ops.\n\nDefinition id_size := word 28.\nDefinition id := [eqType of id_size].\nDefinition bound := 2 ^ 28.\n\nDefinition word_to_id (w : mword mt) : option id_size :=\n  if ord_of_word w < bound then Some (as_word (ord_of_word w))\n  else None.\n\nDefinition id_to_word (x : id) : mword mt :=\n  as_word (ord_of_word x).\n\nLemma id_to_wordK : pcancel id_to_word word_to_id.\nProof.\nmove=> x; rewrite /word_to_id /id_to_word.\nhave hx := valP (ord_of_word x) : ord_of_word x < bound.\nby rewrite !as_wordK ?[in LHS]hx ?valwK ?(ltn_trans hx) /bound ?ltn_exp2l.\nQed.\n\nLemma word_to_idK : ocancel word_to_id id_to_word.\nProof.\nmove=> w; rewrite /word_to_id /id_to_word.\nhave [hb|] // := boolP (_ < 2 ^ 28).\nby rewrite [in X in Some X](lock as_word) /= -lock as_wordK // valwK.\nQed.\n\nInstance ids : cfi_id mt := {\n id := id;\n word_to_id := word_to_id;\n id_to_word := id_to_word\n}.\nProof.\n  - by apply id_to_wordK.\n  - by move=> w x h; move: (word_to_idK w); rewrite h.\nDefined.\n\n(* Encoding of tags:\n      DATA           --> 0\n      INSTR None     --> 1\n      INSTR (Some x) --> x*4+2\n*)\n\nDefinition encode_cfi_tag (t : cfi_tag) : word 30 :=\n match t with\n   DATA => @wpack [:: 28; 2] [hseq 0; 0]%w\n | INSTR None => @wpack [:: 28; 2] [hseq 0; 1]%w\n | INSTR (Some x) => @wpack [:: 28; 2] [hseq x; as_word 2]%w\n end.\n\nDefinition decode_cfi_tag (t : word 30) : option cfi_tag :=\n  let: [hseq k; t] := @wunpack [:: 28; 2] t in\n  if t == 0%w then\n    if k == 0%w then Some DATA\n    else None\n  else if t == 1%w then\n    if k == 0%w then Some (INSTR None)\n    else None\n  else if t == as_word 2 then\n    Some (INSTR (Some (k : @classes.id _ ids)))\n  else None.\n\nLemma encode_cfi_tagK : pcancel encode_cfi_tag decode_cfi_tag.\nProof.\nby case=> [[k|]|] /=; rewrite /decode_cfi_tag wpackK.\nQed.\n\nLemma decode_cfi_tagK : ocancel decode_cfi_tag encode_cfi_tag.\nProof.\nmove=> w; rewrite /decode_cfi_tag.\ncase E: (wunpack _) => [k [t []]]; move: E.\nhave [{t}->|] := altP (t =P _).\n  have [{k}->|hk] //= := altP (k =P _).\n  by move=> <-; rewrite wunpackK.\nhave [{t}-> _|] := altP (t =P 1%w).\n  have [{k}->|hk] //= := altP (k =P _).\n  by move=> <-; rewrite wunpackK.\nhave [{t}-> _ _|] //= := altP (t =P as_word 2).\nby move=> <-; rewrite wunpackK.\nQed.\n\nImport DoNotation.\n\nInstance encodable_tag : encodable mt cfi_tags := {\n  decode k m := fun (w : mword mt) =>\n    let: [hseq ut; w'] := @wunpack [:: 30; 2] w in\n    if w' == 0%w then None\n    else\n      match k return option (wtag cfi_tags k) with\n      | Symbolic.M =>\n        if w' == 1%w then\n          do! ut <- decode_cfi_tag ut;\n          Some (@User cfi_tags ut)\n        else if w' == as_word 2 then\n          do! ut <- decode_cfi_tag ut;\n          Some (@Entry cfi_tags ut)\n        else None\n      | Symbolic.P =>\n        if w' == 1%w then\n          do! ut <- decode_cfi_tag ut;\n          Some ut\n        else None\n      | Symbolic.R =>\n        if w' == 1%w then\n          do! ut <- decode_cfi_tag ut;\n          Some ut\n        else None\n      end\n}.\nProof.\n  - by eauto.\n  - by move=> tk _; rewrite 2!wunpackS.\nQed.\n\nSection Refinement.\n\nVariable cfg : id -> id -> bool.\n\n(* XXX: Removing the explicit argument here causes Coq to throw a\nNot_found when closing the Refinement section below, probably a bug to\nbe reported. *)\n\nInstance sp : Symbolic.params := Sym.sym_cfi cfg.\n\nVariable mi : refinement_common.monitor_invariant.\nVariable stable : Symbolic.syscall_table mt.\nVariable atable : Abs.syscall_table mt.\n\nInductive refine_state (ast : Abs.state mt) (cst : Concrete.state mt) : Prop :=\n| rs_intro : forall (sst : Symbolic.state mt),\n               refinement_common.refine_state mi stable sst cst ->\n               RefinementAS.refine_state stable ast sst ->\n               refine_state ast cst.\nHint Constructors refine_state.\n\nHypothesis implementation_correct :\n  monitor_code_bwd_correctness mi stable.\n\nHypothesis refine_syscalls_correct : RefinementAS.refine_syscalls stable atable stable.\n\nHypothesis syscall_sem :\n  forall ac ast ast',\n    @Abs.sem mt ac ast = Some ast' ->\n       let '(Abs.State imem _ _ _ b) := ast in\n       let '(Abs.State imem' _ _ _ b') := ast' in\n         imem = imem' /\\ b' = b.\n\nHypothesis syscall_preserves_instruction_tags :\n  forall sc st st',\n    Sym.instructions_tagged (cfg := cfg) (Symbolic.mem st) ->\n    Symbolic.sem sc st = Some st' ->\n    Sym.instructions_tagged (cfg := cfg) (Symbolic.mem st').\n\nHypothesis syscall_preserves_valid_jmp_tags :\n  forall sc st st',\n    Sym.valid_jmp_tagged stable (Symbolic.mem st) ->\n    Symbolic.sem sc st = Some st' ->\n    Sym.valid_jmp_tagged stable (Symbolic.mem st').\n\nHypothesis syscall_preserves_entry_tags :\n  forall sc st st',\n    Sym.entry_points_tagged stable (Symbolic.mem st) ->\n    Symbolic.sem sc st = Some st' ->\n    Sym.entry_points_tagged stable (Symbolic.mem st').\n\nHypothesis syscall_preserves_register_tags :\n  forall sc st st',\n    Sym.registers_tagged (cfg:=cfg) (Symbolic.regs st) ->\n    Symbolic.sem sc st = Some st' ->\n    Sym.registers_tagged (Symbolic.regs st').\n\nHypothesis syscall_preserves_jump_tags :\n  forall sc st st',\n    Sym.jumps_tagged (cfg:=cfg) (Symbolic.mem st) ->\n    Symbolic.sem sc st = Some st' ->\n    Sym.jumps_tagged (Symbolic.mem st').\n\nHypothesis syscall_preserves_jal_tags :\n  forall sc st st',\n    Sym.jals_tagged (cfg:=cfg) (Symbolic.mem st) ->\n    Symbolic.sem sc st = Some st' ->\n    Sym.jals_tagged (Symbolic.mem st').\n\nLemma backwards_refinement_as ast sst sst' :\n  RefinementAS.refine_state stable ast sst ->\n  exec (Symbolic.step stable) sst sst' ->\n  exists ast',\n    exec (fun ast ast' => Abs.step atable cfg ast ast') ast ast' /\\\n    RefinementAS.refine_state stable ast' sst'.\nProof.\nmove => REF EXEC.\nelim: EXEC ast REF=> {sst sst'} [sst _|sst sst' sst'' _ STEPS EXEC IH] ast REF.\n  by eauto 7.\nhave [ast' [STEPA REF']] :=\n  RefinementAS.backwards_simulation refine_syscalls_correct syscall_sem\n                                    syscall_preserves_instruction_tags\n                                    syscall_preserves_valid_jmp_tags\n                                    syscall_preserves_entry_tags\n                                    syscall_preserves_register_tags\n                                    syscall_preserves_jump_tags\n                                    syscall_preserves_jal_tags\n                                    REF STEPS.\nby have [ast'' [EXECA REF'']] := IH ast' REF'; eauto 7.\nQed.\n\nLemma backwards_refinement (ast : Abs.state mt) (cst cst' : Concrete.state mt) :\n  refine_state ast cst ->\n  exec (Concrete.step _ masks) cst cst' ->\n  in_user cst' ->\n  exists ast',\n    exec (fun ast ast' => Abs.step atable cfg ast ast') ast ast' /\\\n    refine_state ast' cst'.\nProof.\nmove => [sst SC AS] EXECC INUSER.\nhave [sst' EXECS SC'] := backward.backwards_refinement SC EXECC INUSER.\nby have [ast' [EXECA AS']] := backwards_refinement_as AS EXECS; eauto.\nQed.\n\nEnd Refinement.\n\nEnd WithClasses.\n\nEnd CFIInstances.\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/main.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.28209249517287516}}
{"text": " Require Export voting. \n\nTheorem frame4ind: (phi4 0 1) ~ (phi4 1 0).\nProof.  \nunfold phi4, phi3, phi2, phi1.\nunfold t1, t2, t3, t4.\nsimpl.\napply IFBRANCH_M4 with (ml1:= phi0) (ml2:= phi0).\nsimpl. unfold Avote. \napply IFBRANCH_M3 with (ml1:= (phi0 ++ [bol (theta x1 A), msg (tr 0 0 3 5 9)]))(ml2:= (phi0 ++ [bol (theta x1 A), msg (tr 0 1 3 5 9)])). \napply IFBRANCH_M2 with (ml1:= (phi0 ++ [bol (theta x1 A), msg (tr 0 0 3 5 9), bol (theta (x2t 0) B), msg (tr 1 1 4 6 10)]))(ml2:= (phi0 ++ [bol (theta x1 A), msg (tr 0 1 3 5 9), bol (theta (x2t 1) B), msg (tr 1 0 4 6 10)])).\n\n \napply IFBRANCH_M2 with (ml1:= (phi0 ++ [bol (theta x1 A), msg (tr 0 0 3 5 9), bol (theta (x2t 0) B), msg (tr 1 1 4 6 10), bol (to (x3tt 0 1)) #? A]))(ml2:= (phi0 ++ [bol (theta x1 A), msg (tr 0 1 3 5 9), bol (theta (x2t 1) B), msg (tr 1 0 4 6 10), bol (to (x3tt 1 0)) #? A])).\n \napply IFBRANCH_M1 with (ml1:= (phi0 ++ [bol (theta x1 A), msg (tr 0 0 3 5 9), bol (theta (x2t 0) B), msg (tr 1 1 4 6 10), bol (to (x3tt 0 1)) #? A, bol (acpt 0 3 5 (x3tt 0 1)), msg (e 0 3 5 (x3tt 0 1) TWO 11)]))(ml2:= (phi0 ++ [bol (theta x1 A), msg (tr 0 1 3 5 9), bol (theta (x2t 1) B), msg (tr 1 0 4 6 10), bol (to (x3tt 1 0)) #? A, bol (acpt 1 3 5 (x3tt 1 0)), msg (e 1 3 5 (x3tt 1 0) TWO 11)])).\n\napply IFBRANCH_M1 with (ml1:= (phi0 ++ [bol (theta x1 A), msg (tr 0 0 3 5 9), bol (theta (x2t 0) B), msg (tr 1 1 4 6 10), bol (to (x3tt 0 1)) #? A, bol (acpt 0 3 5 (x3tt 0 1)), msg (e 0 3 5 (x3tt 0 1) TWO 11), bol (to (x4ttt 0 1)) #? B]))(ml2:= (phi0 ++ [bol (theta x1 A), msg (tr 0 1 3 5 9), bol (theta (x2t 1) B), msg (tr 1 0 4 6 10), bol (to (x3tt 1 0)) #? A, bol (acpt 1 3 5 (x3tt 1 0)), msg (e 1 3 5 (x3tt 1 0) TWO 11), bol (to (x4ttt 1 0)) #? B])).\nsimpl. unfold theta, tr, e.\napply frame4goal1.\n(** first goal end **)   \n(** Goal: 2**)\nsimpl.\npose proof(frame4goal1).\nfunappmconst O H; auto.\nrestrsublis H; simpl; auto.\n                         \n(** Goal: 3**)\n\nsimpl.\npose proof(frame4goal1).\nfunappmconst O H; auto.\nrestrsublis H; simpl; auto.\n(** Goal: 4**)\nsimpl.\npose proof(frame4goal1).\nfunappmconst O H; auto.\nrestrsublis H; simpl; auto.\n\n(** Goal: 5**)\nsimpl.\npose proof(frame4goal1).\nfunappmconst O H; auto.\nrestrsublis H; simpl; auto.\n\n(** Goal: 6 *)\n\nsimpl.\npose proof(frame4goal1).\nfunappmconst O H; auto.\nrestrsublis H; simpl; auto.\n\n(** First [else] Branch *)\nsimpl.\napply IFBRANCH_M4 with (ml1:= phi0++[ bol (theta x1 A)]) (ml2:= phi0 ++ [  bol (theta x1 A)]).\nunfold Bvote.\napply IFBRANCH_M3 with (ml1:= phi0++[ bol (theta x1 A), bol (theta x1 B), msg (tr 1 1 4 6 10) ]) (ml2:= phi0 ++ [  bol (theta x1 A), bol (theta x1 B), msg (tr 1 0 4 6 10)]).\n\napply IFBRANCH_M2 with (ml1:= phi0++[bol (theta x1 A), bol (theta x1 B), msg (tr 1 1 4 6 10), bol (theta (x2ft 1) A), msg (tr 0 0 3 5 9)]) (ml2:= phi0 ++ [bol (theta x1 A), bol (theta x1 B), msg (tr 1 0 4 6 10), bol (theta (x2ft 0) A), msg (tr 0 1 3 5 9)]).\nsimpl.\n\napply IFBRANCH_M2 with (ml1:= phi0++[bol (theta x1 A), bol (theta x1 B), msg (tr 1 1 4 6 10), bol (theta (x2ft 1) A), msg (tr 0 0 3 5 9), bol (to (x3ftt 0 1)) #? B]) (ml2:= phi0 ++ [bol (theta x1 A), bol (theta x1 B), msg (tr 1 0 4 6 10), bol (theta (x2ft 0) A), msg (tr 0 1 3 5 9), bol (to (x3ftt 1 0)) #? B]).\n\napply IFBRANCH_M1 with (ml1:= phi0++[bol (theta x1 A), bol (theta x1 B), msg (tr 1 1 4 6 10), bol (theta (x2ft 1) A), msg (tr 0 0 3 5 9), bol (to (x3ftt 0 1)) #? B, bol (acpt 1 4 6 (x3ftt 0 1)), msg (e 1 4 6 (x3ftt 0 1) TWO 11)]) (ml2:= phi0 ++ [bol (theta x1 A), bol (theta x1 B), msg (tr 1 0 4 6 10), bol (theta (x2ft 0) A), msg (tr 0 1 3 5 9), bol (to (x3ftt 1 0)) #? B, bol (acpt 0 4 6 (x3ftt 1 0)), msg (e 0 4 6 (x3ftt 1 0) TWO 11)]).\n\napply IFBRANCH_M1 with (ml1:= phi0++[bol (theta x1 A), bol (theta x1 B), msg (tr 1 1 4 6 10), bol (theta (x2ft 1) A), msg (tr 0 0 3 5 9), bol (to (x3ftt 0 1)) #? B, bol (acpt 1 4 6 (x3ftt 0 1)), msg (e 1 4 6 (x3ftt 0 1) TWO 11), bol (to (x4fttt 0 1)) #? A]) (ml2:= phi0 ++ [bol (theta x1 A), bol (theta x1 B), msg (tr 1 0 4 6 10), bol (theta (x2ft 0) A), msg (tr 0 1 3 5 9), bol (to (x3ftt 1 0)) #? B, bol (acpt 0 4 6 (x3ftt 1 0)), msg (e 0 4 6 (x3ftt 1 0) TWO 11), bol (to (x4fttt 1 0)) #? A]).\n (** similarly we can prove this branch *)\nAdmitted.\n\n\n\n\n                Theorem frame5TraceInd:\n                let u:= (c 0 3, (ub (c 0 3) pk (bk 5) (x3tt 0 1), TWO)) in\n                let u':= (c 1 3, (ub (c 1 3) pk (bk 5) (x3tt 1 0), TWO)) in\n                let v:= (c 1 4, (ub (c 1 4) pk (bk 6) (x3tt 0 1), TWO)) in\n                let v':= (c 0 4, (ub (c 0 4) pk (bk 6) (x3tt 1 0), TWO)) in\n   [msg A, msg B, msg M, msg C1, msg C2, msg C3, msg ONE, msg TWO, msg THREE, msg (vk 0), msg (vk 1), \n   msg (pke 2), bol (theta x1 A), msg (tr 0 0 3 5 9), bol (theta (x2t 0) B), msg (tr 1 1 4 6 10), \n   bol (to (x3tt 0 1)) #? A, bol (acpt 0 3 5 (x3tt 0 1)),\n   msg {u}_ 2 ^^ 11, bol (to (x4ttt 0 1)) #? B,\n   bol (acpt 1 4 6 (x3tt 0 1)), msg {v}_ 2 ^^ 12,\n   bol (to (x5t 0 1)) #? M, bol (tau 1 (x5t 0 1)) #? {u}_ 2 ^^ 11,\n   bol (tau 2 (x5t 0 1)) #? {v}_ 2 ^^ 12,\n   bol (!((tau 3 (x5t 0 1)) #? {u}_ 2 ^^ 11)) & (!((tau 3 (x5t 0 1)) #? {v}_ 2 ^^ 12)),\n   bol ((tau 3 u)#? TWO) & ((tau 3 v) #? TWO) & ((tau 3 (dec (tau 3 (x5t 0 1)) (ske 2))) #? TWO), msg (shufl ((tau 1 u), (tau 2 u)) ((tau 1 v), (tau 2 v)) ((tau 1 (dec (tau 3 (x5t 0 1)) (ske 2))),  (tau 2 (dec (tau 3 (x5t 0 1)) (ske 2)))))] ~\n\n[msg A, msg B, msg M, msg C1, msg C2, msg C3, msg ONE, msg TWO, msg THREE, msg (vk 0), msg (vk 1), \n   msg (pke 2), bol (theta x1 A), msg (tr 0 1 3 5 9), bol (theta (x2t 1) B), msg (tr 1 0 4 6 10), \n   bol (to (x3tt 1 0)) #? A, bol (acpt 1 3 5 (x3tt 1 0)),\n   msg {u'}_2 ^^ 11, bol (to (x4ttt 1 0)) #? B,\n   bol (acpt 0 4 6 (x3tt 1 0)), msg {v'}_ 2 ^^ 12,\n   bol (to (x5t 1 0)) #? M, bol (tau 1 (x5t 1 0)) #? {u'}_ 2 ^^ 11,\n   bol (tau 2 (x5t 1 0)) #? {v'}_ 2 ^^ 12,\n   bol (!((tau 3 (x5t 1 0)) #? {u'}_ 2 ^^ 11)) & (! ((tau 3 (x5t 1 0)) #? {v'}_ 2 ^^ 12)),\n   bol ((tau 3 u')#? TWO) & ((tau 3 v') #? TWO) & ((tau 3 (dec (tau 3 (x5t 1 0)) (ske 2))) #? TWO), msg (shufl ((tau 1 u'), (tau 2 u')) ((tau 1 v'), (tau 2 v')) ((tau 1 (dec (tau 3 (x5t 1 0)) (ske 2))),  (tau 2 (dec (tau 3 (x5t 1 0)) (ske 2)))))].\nProof. simpl. repeat rewrite proj1, proj2.\nAxiom eqmref: forall m, m#?m ## TRue.\nrepeat rewrite eqmref.\nrepeat rewrite andB_TRue_l.\n(*Eval compute in x4ttt 0 1. *)\n(*Eval compute in (tr 0 0 3  5 9). *)\nDefinition tr03x := ((vk 0), ((Mvar 5), (sign (Mvar 5) (ssk 0) (rs (nonce 9))))).\nDefinition tr14x :=  ((vk 1), ((Mvar 6), (sign (Mvar 6) (ssk 1) (rs (nonce 10))))).\nDefinition x4tttex := (f (toListm (phi0 ++ [msg (tr 0 0 3  5 9), msg (tr 1 1 4 6 10), msg (Mvar 0) ]))).\n\nDefinition x5tex := f (toListm (phi0 ++ [msg (tr 0 0 3  5 9), msg (tr 1 1 4 6 10), msg (Mvar 0), msg (Mvar 1) ])).\n\npose proof(EXTENCCCA2 (tau 1 (x5t 0 1)) (c 0 3, (ub (c 0 3) pk (bk 5) (x3tt 0 1), TWO)) (z (c 0 3, (ub (c 0 3) pk (bk 5) (x3tt 0 1), TWO))) O (c 1 4, (ub (c 1 4) pk (bk 6) (x3tt 0 1), TWO)) (z (c 1 4, (ub (c 1 4) pk (bk 6) (x3tt 0 1), TWO))) O 0 1 2 11 12 13 14 \n[ msg (dec (pi2 (pi2 x5tex)) (ske 2)), msg (c 0 3, ub (c 0 3) pk (bk 5) (x3tt 0 1)), msg (c 1 4, ub (c 1 4) pk (bk 6) (x3tt 0 1)), msg A, msg B, msg M, msg C1, msg C2, msg C3, msg ONE, \n msg TWO, msg THREE, msg (vk 0), msg (vk 1), msg (pke 2),\n msg (Mvar 0), msg (Mvar 1), msg (ssk 0), msg (ssk 1), msg (sr 9), msg (sr 10), \n msg (tr 0 0 3 5 9), \n   msg (tr 1 1 4 6 10), msg (x3tt 0 1), msg x4tttex, msg x5tex,  bol (acpt 0 3 5 (x3tt 0 1)),\n   bol (acpt 1 4 6 (x3tt 0 1)) ]).\nsimpl in H. \ndo 2  rewrite zeroEql1 in H; try rewrite refEql.\nsimpl.  do 4 rewrite IFTRUE_M in H. simpl.\n\n\n(** Substitution: x <- s in l, x is of type variable, l is of type [mylist] *)\n\nDefinition submsg_mylist (n:nat)(s:message) {m} (l:mylist m):mylist m :=\n  match l with\n  | [] => []\n  | a : h =>  (submsg_os n s a) : (submsg_mylist n s h)\n  end.\n\nAxiom gen_prop4:  forall {n m} (n1 n2 n3 n4:nat) (t t0 t1: message) (z: mylist n) (z1:mylist m), let v0 := (V0 (f (toListm z))) in\n                                                                                                      let v1 := (V1 (f (toListm z))) in\n                                                                                                      (|v0|#?|v1|) ## TRue ->  (Fresh [n1; n2; n3; n4] (z++ z1++[msg t, msg t0, msg t1])  = true) ->  closMylist (z++[msg t]) = true -> ((length (distMvars [msg t0, msg t1]))=?  2)%nat = true -> bVarMylist [msg t0, msg t1] = nil  ->\n    let mvl:= [5; 6] in  (distMvars [msg t0]) = mvl /\\ (distMvars [msg t1]) = mvl ->\n                 let r0 := (r n1) in\n                 let r1 := (r n2) in\n                 let k0 := (kc (nonce n3)) in\n                 let k1 := (kc (nonce n4)) in\n                 let c00 := (comm v0 k0) in\n                 let c01 := (comm v0 k1) in\n                 let c10 := (comm v1 k0) in\n                 let c11 := (comm v1 k1) in\n                 let t2 := ({{ 5 := (bl c00 t r0) }} ({{ 6:=(bl c11 t r1) }} t0)) in\n                 let t3 := ({{ 5 := (bl c00 t r0) }} ({{ 6:=(bl c11 t r1) }} t1)) in\n                 let t4 := ({{ 5 := (bl c10 t r0) }} ({{ 6:=(bl c01 t r1) }} t0)) in\n                 let t5 := ({{ 5 := (bl c10 t r0) }} ({{ 6:=(bl c01 t r1) }} t1)) in\n                 let lt1 := (((ub c00 t r0 t2), (c00, k0)), ((ub c11 t r1 t2), (c11, k1)) ) in\n                 let lt2 := ((ub c00 t r0 t2), (c00, |_)) in\n                 let lt3 := (|_, ((ub c11 t r1 t3), c11)) in\n                 let rt1 := (((ub c10 t r0 t5), (c10, k0)), ((ub c01 t r1 t4), (c01, k1))) in\n                 let rt2 := ((ub c10 t r0 t4), (c10, |_)) in \n                 let rt3 := (|_, ((ub c01 t r1 t5), c01)) in\n                 let lz1 := (submsg_mylist 5 (bl c00 t r0) (submsg_mylist 6 (bl c11 t r1) z1)) in\n                 let rz1 := (submsg_mylist 5 (bl c10 t r0) (submsg_mylist 6 (bl c01 t r1) z1)) in\n                \n                 \n                 (z++ lz1++[msg (bl c00 t r0), msg (bl c11 t r1), bol (acc c00 t r0 t2)& (acc c11 t r1 t3), bol (acc c00 t r0 t2), bol (acc c11 t r1 t3), msg lt1])\n                      \n                    ~\n                   \n                    (z++rz1++[msg (bl c10 t r0), msg (bl c01 t r1), bol (acc c10 t r0 t4)& (acc c01 t r1 t5), bol (acc c10 t r0 t4), bol (acc c01 t r1 t5), msg rt1]).\nDefinition x4tttbx := (f (toListm (phi0 ++ [msg tr03x, msg tr14x, msg {(z (c 0 3, (ub (c 0 3) pk (bk 5) x3ttx, TWO)))}_ 2 ^^ 13 ]))).\n\nDefinition x5tbx := f (toListm (phi0 ++ [msg tr03x, msg tr14x, msg {(z (c 0 3, (ub (c 0 3) pk (bk 5) x3ttx, TWO)))}_ 2 ^^ 13,  msg {z (c 1 4, (ub (c 1 4) pk (bk 6) x3ttx, TWO)) }_ 2 ^^ 14])).\n\npose proof (gen_prop4 5 6 3 4 (pubkey x1) (x3ttx) (x3ttx) phi0 [msg {(z (c 0 3, (ub (c 0 3) pk (bk 5) (x3tt 0 1), TWO)))}_ 2 ^^ 13,  msg {z (c 1 4, (ub (c 1 4) pk (bk 6) (x3tt 0 1), TWO)) }_ 2 ^^ 14, msg (ssk 0), msg (ssk 1), msg (sr 9), msg (sr 10), msg (ske 2), msg tr03x, msg tr14x, msg x3ttx, msg x4tttbx, msg x5tbx]). unfold distMvars in H0. \n simpl in H0. \n unfold Fresh in H0; simpl in H0.\n rewrite voteEql in H0.\nrestr_proj_in 27 H0; simpl; try split; auto.\nfunappf1 pi1 29 H0.\nfunappf1 pi2 30 H0.\nrewrite proj1, proj2 in H0.\ndropLast_in H0.\nfunappf1 (tau 1) 1 H0.\nfunappf1 (tau 2) 2 H0.\nfunappf1 (tau 3) 3 H0.\nrepeat rewrite proj1, proj2 in H0.\ndropone_in H0.\n\nfunappf2m pair 1 2 H0.\ndo 3 restrproj_in 2 H0.\n\nfunappf1 (tau 1) 2 H0.\nfunappf1 (tau 2) 3 H0.\nfunappf1 (tau 3) 4 H0.\nrepeat rewrite proj1, proj2 in H0.\ndropone_in H0.\n\nfunappf2m pair 1 2 H0.\ndo 2 restrproj_in 2 H0.\n\nrestrproj_in 3 H0.\n\n(** constructing dec term *) \nfunappf1 pi2 26 H0. \nfunappf1 pi2 1 H0; restrproj_in 2 H0.\nfunappf2m dec 1 22 H0.\nrestrproj_in 2 H0.\n(** delete the secret key from clear*)\nrestrproj_in 22 H0. \nrestrproj_in 28 H0.\nrestrproj_in 27 H0.\n\n\n(** l1 ++[e1]++[e2] ~ l1 ++ [z(e1)]++[z(e2)] /\\  l1 ++ [z(e1)]++[z(e2)]~l2++[z(e1)]++[z(e2)] *)\nsimpl.\n \n\n\n(*Eval compute in (submsg_msg 1 {(c 1 4, (ub (c 1 4) pk (bk 6) (x3tt 0 1), TWO)) }_ 2 ^^ 12 (submsg_msg 0 {( (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) , ((ub (c 0 3) pk (bk 5) (x3tt 0 1)), TWO)) }_ 2 ^^ 11 x5tex)). *)\n \nassert( (x5t 0 1) # (submsg_msg 1 {(c 1 4, (ub (c 1 4) pk (bk 6) (x3tt 0 1), TWO)) }_ 2 ^^ 12 (submsg_msg 0 {( (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) , ((ub (c 0 3) pk (bk 5) (x3tt 0 1)), TWO)) }_ 2 ^^ 11 x5tex))).\nsimpl. reflexivity. \nrewrite <- H1 in H.\n\nassert( (x4ttt 0 1) # (submsg_msg 1 {(c 1 4, (ub (c 1 4) pk (bk 6) (x3tt 0 1), TWO)) }_ 2 ^^ 12 (submsg_msg 0 {( (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) , ((ub (c 0 3) pk (bk 5) (x3tt 0 1)), TWO)) }_ 2 ^^ 11 x4tttex))).\nsimpl. reflexivity. \nrewrite <- H2 in H.\nclear H1 H2.\n\nsimpl.\n\nassert ( (submsg_msg 0 {( (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) , ((ub (c 0 3) pk (bk 5) (x3tt 0 1)), TWO)) }_ 2 ^^ 11 (Mvar 0)) # (submsg_msg 0 {( (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) , ((ub (c 0 3) pk (bk 5) (x3tt 0 1)), TWO)) }_ 2 ^^ 11 (Mvar 0))).\nreflexivity.\nrewrite H1 in H.\nclear H1.\n\n\n\n\n\n                            (** apply ENCCCA2 axiom 2nd time *)\nDefinition x4tttex' := (f (toListm (phi0 ++ [msg (tr 0 1 3  5 9), msg (tr 1 0 4 6 10), msg (Mvar 0) ]))).\n\nDefinition x5tex' := f (toListm (phi0 ++ [msg (tr 0 1 3  5 9), msg (tr 1 0 4 6 10), msg (Mvar 0), msg (Mvar 1) ])).\nsimpl.\npose proof(EXTENCCCA2 (tau 1 (x5t 0 1)) (z (c 0 3, (ub (c 0 3) pk (bk 5) (x3tt 0 1), TWO))) (c 1 3, (ub (c 1 3) pk (bk 5) (x3tt 1 0), TWO)) O (z (c 1 4, (ub (c 1 4) pk (bk 6) (x3tt 0 1), TWO))) (c 0 4, (ub (c 0 4) pk (bk 6) (x3tt 1 0), TWO))  O 0 1 2 13 14 11 12 \n[msg (dec (pi2 (pi2 x5tex')) (ske 2)), msg ((c 1 3), (ub (c 1 3) pk (r 5) (x3tt 1 0))),\n msg ((c 0 4), (ub (c 0 4) pk (r 6) (x3tt 1 0))), msg A, msg B, msg M, msg C1, msg C2, msg C3, \n msg ONE, msg TWO, msg THREE, msg (vk 0), msg (vk 1), msg (pke 2), msg (Mvar 0), msg (Mvar 1), msg (ssk 0), msg (ssk 1), msg (sr 9), msg (sr 10),  msg (tr 0 1 3 5 9), \n   msg (tr 1 0 4 6 10), msg (x3tt 1 0), msg x4tttex', msg x5tex', bol (acc (c 1 3) pk (r 5) (x3tt 1 0)), bol (acc (c 0 4) pk (r 6) (x3tt 1 0))]).\n\nsimpl in H. \n \nassert( (| z (c 1 4, (ub (c 1 4) pk (bk 6) (x3tt 0 1), TWO)) |) #? (| (c 0 4, (ub (c 0 4) pk (bk 6) (x3tt 1 0), TWO)) |) ## TRue).\nrewrite symEql.\napply zeroEql1. apply len_reg. \n\n   \npose proof (commEql 4 4 (V1 x1) (V0 x1)). \nrewrite symEql in H2. rewrite voteEql in H2. rewrite IFTRUE_B in H2.\nrewrite symEql.\napply H2.\n\nrepeat (try split; try unfold Fresh; try auto). auto. auto. \napply len_reg.\n\n\napply ubEql.\n\npose proof (commEql 4 4 (V1 x1) (V0 x1)).\nrewrite symEql in H2. rewrite voteEql in H2. rewrite IFTRUE_B in H2.\nrewrite symEql.\napply H2.\n\ntry split; try unfold Fresh; simpl; try auto. reflexivity.\nsimpl.\nreflexivity; try apply refEql; auto.\n apply refEql.\napply refEql.\napply len_prev_comp.\napply refEql.\nrewrite H2 in H1.\n\nassert ( (|z (c 0 3, (ub (c 0 3) pk (bk 5) (x3tt 0 1), TWO))|#? |(c 1 3, (ub (c 1 3) pk (bk 5) (x3tt 1 0), TWO))|) ## TRue).\n\nrewrite symEql. \napply zeroEql1. apply len_reg. \n    \npose proof (commEql 3 3 (V1 x1) (V0 x1)).\nrewrite symEql, voteEql, IFTRUE_B in H3. apply H3.\n\ntry split; try unfold Fresh; simpl; try reflexivity. auto.\nreflexivity.\napply len_reg.\napply ubEql.\n\npose proof (commEql 3 3 (V1 x1) (V0 x1)).\nrewrite symEql, voteEql, IFTRUE_B in H3. \napply H3.\n\ntry split; try reflexivity. unfold Fresh. simpl. reflexivity.\nsimpl.\nreflexivity.\napply refEql. apply refEql.\napply len_prev_comp.\napply refEql. repeat rewrite IFTRUE_M in H1. simpl in H1.\nrepeat rewrite H3 in H1.\nclear H3 H2.\n\nrepeat rewrite IFTRUE_M in H1.  \n \n\n \n\n(** l1 ++ [e1]++[e2] ~ l1 ++ [z(e1)]++[z(e2)]~l2 ++ [z(e1)]++[z(e2)]~ l2 ++ [e1']++[e2'] *)\n\n\n\n\nassert(ftran: [msg (dec (pi2 (pi2 (x5t 0 1))) (pi2 (ke (nonce 2)))),\n       msg\n         (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)),\n         ub (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n           (rb (nonce 5))\n           (f\n              [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n              (pi1 (ks (nonce 0)),\n              (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                 (rb (nonce 5)),\n              sign\n                (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                   (rb (nonce 5))) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n              (pi1 (ks (nonce 1)),\n              (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                 (rb (nonce 6)),\n              sign\n                (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                   (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))])),\n       msg\n         (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)),\n         ub (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n           (rb (nonce 6))\n           (f\n              [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n              (pi1 (ks (nonce 0)),\n              (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                 (rb (nonce 5)),\n              sign\n                (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                   (rb (nonce 5))) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n              (pi1 (ks (nonce 1)),\n              (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                 (rb (nonce 6)),\n              sign\n                (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                   (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))])), msg A, msg B, msg M, msg C1, msg C2, msg C3, msg ONE, msg TWO, msg THREE, msg (pi1 (ks (nonce 0))), msg (pi1 (ks (nonce 1))), msg (pi1 (ke (nonce 2))),\n       msg {(comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)), (ub (c 0 3) pk (bk 5) (x3tt 0 1), TWO)) }_ 2 ^^ 11,\n       msg {(c 1 4, (ub (c 1 4) pk (bk 6) (x3tt 0 1), TWO)) }_ 2 ^^ 12, msg (pi2 (ks (nonce 0))), msg (pi2 (ks (nonce 1))), msg (rs (nonce 9)), msg (rs (nonce 10)),\n       msg\n         (pi1 (ks (nonce 0)),\n         (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n            (rb (nonce 5)),\n         sign\n           (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n              (rb (nonce 5))) (pi2 (ks (nonce 0))) (rs (nonce 9)))),\n       msg\n         (pi1 (ks (nonce 1)),\n         (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n            (rb (nonce 6)),\n         sign\n           (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n              (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10)))),\n       msg\n         (f\n            [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n            (pi1 (ks (nonce 0)),\n            (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n               (rb (nonce 5)),\n            sign\n              (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                 (rb (nonce 5))) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n            (pi1 (ks (nonce 1)),\n            (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n               (rb (nonce 6)),\n            sign\n              (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                 (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))]), msg (x4ttt 0 1), msg (x5t 0 1),\n       bol\n         (acc (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n            (rb (nonce 5))\n            (f\n               [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n               (pi1 (ks (nonce 0)),\n               (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                  (rb (nonce 5)),\n               sign\n                 (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                    (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 5))) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n               (pi1 (ks (nonce 1)),\n               (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                  (rb (nonce 6)),\n               sign\n                 (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                    (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))])),\n       bol\n         (acc (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n            (rb (nonce 6))\n            (f\n               [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n               (pi1 (ks (nonce 0)),\n               (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                  (rb (nonce 5)),\n               sign\n                 (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                    (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 5))) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n               (pi1 (ks (nonce 1)),\n               (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                  (rb (nonce 6)),\n               sign\n                 (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                    (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))]))] ~ [msg\n          (dec\n             (pi2\n                (pi2\n                   (f\n                      [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n                      (pi1 (ks (nonce 0)),\n                      (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5),\n                      sign (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5)) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n                      (pi1 (ks (nonce 1)),\n                      (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                         (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6)),\n                      sign\n                        (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                           (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))));\n                      {z\n                         (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)),\n                         (ub (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                            (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 5))\n                            (f\n                               [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n                               (pi1 (ks (nonce 0)),\n                               (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5),\n                               sign (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5)) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n                               (pi1 (ks (nonce 1)),\n                               (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                                  (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6)),\n                               sign\n                                 (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                                    (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))]), TWO)) }_ 2 ^^ \n                      13;\n                      {z\n                         (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)),\n                         (ub (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                            (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6))\n                            (f\n                               [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n                               (pi1 (ks (nonce 0)),\n                               (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5),\n                               sign (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5)) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n                               (pi1 (ks (nonce 1)),\n                               (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                                  (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6)),\n                               sign\n                                 (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                                    (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))]), TWO)) }_ 2 ^^ \n                      14]))) (pi2 (ke (nonce 2)))),\n       msg\n         (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3)),\n         ub (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5)\n           (f\n              [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n              (pi1 (ks (nonce 0)),\n              (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5),\n              sign (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5)) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n              (pi1 (ks (nonce 1)),\n              (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                 (rb (nonce 6)),\n              sign\n                (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                   (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))])),\n       msg\n         (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 4)),\n         ub (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 4))) (pubkey x1) (r 6)\n           (f\n              [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n              (pi1 (ks (nonce 0)),\n              (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5),\n              sign (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5)) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n              (pi1 (ks (nonce 1)),\n              (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                 (rb (nonce 6)),\n              sign\n                (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                   (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))])), msg A, msg B, msg M, msg C1, msg C2, msg C3, msg ONE, msg TWO, msg THREE, msg (vk 0), msg (vk 1), msg (pke 2),\n       msg\n         {z\n            (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)),\n            (ub (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n               (rb (nonce 5))\n               (f\n                  [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n                  (pi1 (ks (nonce 0)),\n                  (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                     (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 5)),\n                  sign\n                    (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                       (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 5))) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n                  (pi1 (ks (nonce 1)),\n                  (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                     (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6)),\n                  sign\n                    (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                       (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))]), TWO)) }_ 2 ^^ 13,\n       msg\n         {z\n            (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)),\n            (ub (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n               (rb (nonce 6))\n               (f\n                  [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n                  (pi1 (ks (nonce 0)),\n                  (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                     (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 5)),\n                  sign\n                    (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                       (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 5))) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n                  (pi1 (ks (nonce 1)),\n                  (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                     (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6)),\n                  sign\n                    (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                       (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))]), TWO)) }_ 2 ^^ 14, \n       msg (pi2 (ks (nonce 0))), msg (pi2 (ks (nonce 1))), msg (rs (nonce 9)), msg (rs (nonce 10)),\n       msg\n         (pi1 (ks (nonce 0)),\n         (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5),\n         sign (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5)) (pi2 (ks (nonce 0))) (rs (nonce 9)))),\n       msg\n         (pi1 (ks (nonce 1)),\n         (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n            (rb (nonce 6)),\n         sign\n           (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n              (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10)))),\n       msg\n         (f\n            [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n            (pi1 (ks (nonce 0)),\n            (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5),\n            sign (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5)) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n            (pi1 (ks (nonce 1)),\n            (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n               (rb (nonce 6)),\n            sign\n              (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                 (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))]),\n       msg\n         (f\n            [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n            (pi1 (ks (nonce 0)),\n            (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5),\n            sign (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5)) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n            (pi1 (ks (nonce 1)),\n            (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n               (rb (nonce 6)),\n            sign\n              (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                 (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))));\n            {z\n               (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)),\n               (ub (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                  (rb (nonce 5))\n                  (f\n                     [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n                     (pi1 (ks (nonce 0)),\n                     (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5),\n                     sign (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5)) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n                     (pi1 (ks (nonce 1)),\n                     (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                        (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6)),\n                     sign\n                       (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                          (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))]), TWO)) }_ 2 ^^ 13]),\n       msg\n         (f\n            [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n            (pi1 (ks (nonce 0)),\n            (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5),\n            sign (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5)) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n            (pi1 (ks (nonce 1)),\n            (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n               (rb (nonce 6)),\n            sign\n              (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                 (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))));\n            {z\n               (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)),\n               (ub (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                  (rb (nonce 5))\n                  (f\n                     [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n                     (pi1 (ks (nonce 0)),\n                     (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5),\n                     sign (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5)) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n                     (pi1 (ks (nonce 1)),\n                     (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                        (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6)),\n                     sign\n                       (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                          (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))]), TWO)) }_ 2 ^^ 13;\n            {z\n               (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)),\n               (ub (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                  (rb (nonce 6))\n                  (f\n                     [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n                     (pi1 (ks (nonce 0)),\n                     (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5),\n                     sign (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5)) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n                     (pi1 (ks (nonce 1)),\n                     (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                        (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6)),\n                     sign\n                       (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                          (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))]), TWO)) }_ 2 ^^ 14]),\n       bol\n         (acc (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5)\n            (f\n               [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n               (pi1 (ks (nonce 0)),\n               (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5),\n               sign (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5)) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n               (pi1 (ks (nonce 1)),\n               (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                  (rb (nonce 6)),\n               sign\n                 (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                    (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))])),\n       bol\n         (acc (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 4))) (pubkey x1) (r 6)\n            (f\n               [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n               (pi1 (ks (nonce 0)),\n               (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5),\n               sign (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5)) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n               (pi1 (ks (nonce 1)),\n               (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                  (rb (nonce 6)),\n               sign\n                 (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                    (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))]))]).\napply EQI_trans with (ml2:= [msg\n         (dec\n            (pi2\n               (pi2\n                  (f\n                     [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n                     (pi1 (ks (nonce 0)),\n                     (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                        (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 5)),\n                     sign\n                       (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                          (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 5))) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n                     (pi1 (ks (nonce 1)),\n                     (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                        (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6)),\n                     sign\n                       (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                          (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))));\n                     {z\n                        (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)),\n                        (ub (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                           (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 5))\n                           (f\n                              [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n                              (pi1 (ks (nonce 0)),\n                              (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                                 (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 5)),\n                              sign\n                                (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                                   (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 5))) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n                              (pi1 (ks (nonce 1)),\n                              (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                                 (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6)),\n                              sign\n                                (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                                   (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))]), TWO)) }_ 2 ^^ \n                     13; {z (c 1 4, (ub (c 1 4) pk (bk 6) (x3tt 0 1), TWO)) }_ 2 ^^ 14]))) (pi2 (ke (nonce 2)))),\n      msg\n        (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)),\n        ub (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n          (rb (nonce 5))\n          (f\n             [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n             (pi1 (ks (nonce 0)),\n             (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                (rb (nonce 5)),\n             sign\n               (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                  (rb (nonce 5))) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n             (pi1 (ks (nonce 1)),\n             (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                (rb (nonce 6)),\n             sign\n               (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                  (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))])),\n      msg\n        (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)),\n        ub (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n          (rb (nonce 6))\n          (f\n             [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n             (pi1 (ks (nonce 0)),\n             (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                (rb (nonce 5)),\n             sign\n               (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                  (rb (nonce 5))) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n             (pi1 (ks (nonce 1)),\n             (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                (rb (nonce 6)),\n             sign\n               (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                  (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))])), msg A, msg B, msg M, msg C1, msg C2, msg C3, msg ONE, msg TWO, msg THREE, msg (pi1 (ks (nonce 0))), msg (pi1 (ks (nonce 1))), msg (pi1 (ke (nonce 2))),\n      msg\n        {z\n           (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)),\n           (ub (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n              (rb (nonce 5))\n              (f\n                 [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n                 (pi1 (ks (nonce 0)),\n                 (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                    (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 5)),\n                 sign\n                   (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                      (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 5))) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n                 (pi1 (ks (nonce 1)),\n                 (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                    (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6)),\n                 sign\n                   (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                      (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))]), TWO)) }_ 2 ^^ 13,\n      msg {z (c 1 4, (ub (c 1 4) pk (bk 6) (x3tt 0 1), TWO)) }_ 2 ^^ 14, msg (pi2 (ks (nonce 0))), msg (pi2 (ks (nonce 1))), msg (rs (nonce 9)), msg (rs (nonce 10)),\n      msg\n        (pi1 (ks (nonce 0)),\n        (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n           (rb (nonce 5)),\n        sign\n          (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n             (rb (nonce 5))) (pi2 (ks (nonce 0))) (rs (nonce 9)))),\n      msg\n        (pi1 (ks (nonce 1)),\n        (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n           (rb (nonce 6)),\n        sign\n          (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n             (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10)))),\n      msg\n        (f\n           [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n           (pi1 (ks (nonce 0)),\n           (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n              (rb (nonce 5)),\n           sign\n             (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                (rb (nonce 5))) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n           (pi1 (ks (nonce 1)),\n           (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n              (rb (nonce 6)),\n           sign\n             (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))]),\n      msg\n        (f\n           [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n           (pi1 (ks (nonce 0)),\n           (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n              (rb (nonce 5)),\n           sign\n             (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                (rb (nonce 5))) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n           (pi1 (ks (nonce 1)),\n           (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n              (rb (nonce 6)),\n           sign\n             (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))));\n           {z\n              (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)),\n              (ub (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                 (rb (nonce 5))\n                 (f\n                    [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n                    (pi1 (ks (nonce 0)),\n                    (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                       (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 5)),\n                    sign\n                      (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                         (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 5))) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n                    (pi1 (ks (nonce 1)),\n                    (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                       (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6)),\n                    sign\n                      (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                         (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))]), TWO)) }_ 2 ^^ 13]),\n      msg\n        (f\n           [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n           (pi1 (ks (nonce 0)),\n           (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n              (rb (nonce 5)),\n           sign\n             (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                (rb (nonce 5))) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n           (pi1 (ks (nonce 1)),\n           (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n              (rb (nonce 6)),\n           sign\n             (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))));\n           {z\n              (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)),\n              (ub (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                 (rb (nonce 5))\n                 (f\n                    [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n                    (pi1 (ks (nonce 0)),\n                    (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                       (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 5)),\n                    sign\n                      (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                         (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 5))) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n                    (pi1 (ks (nonce 1)),\n                    (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                       (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6)),\n                    sign\n                      (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                         (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))]), TWO)) }_ 2 ^^ 13;\n           {z (c 1 4, (ub (c 1 4) pk (bk 6) (x3tt 0 1), TWO)) }_ 2 ^^ 14]),\n      bol\n        (acc (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n           (rb (nonce 5))\n           (f\n              [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n              (pi1 (ks (nonce 0)),\n              (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                 (rb (nonce 5)),\n              sign\n                (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                   (rb (nonce 5))) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n              (pi1 (ks (nonce 1)),\n              (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                 (rb (nonce 6)),\n              sign\n                (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                   (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))])),\n      bol\n        (acc (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n           (rb (nonce 6))\n           (f\n              [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n              (pi1 (ks (nonce 0)),\n              (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                 (rb (nonce 5)),\n              sign\n                (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                   (rb (nonce 5))) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n              (pi1 (ks (nonce 1)),\n              (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                 (rb (nonce 6)),\n              sign\n                (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4))) (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                   (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))]))]).\napply H; try split; auto.\n\n\napply H0.\n\nclear H. clear H0.\n\n\n\n(** apply transition again *)\n\nassert ( (x5t 1 0) # (submsg_msg 0 {(c 1 3, (ub (c 1 3) pk (bk 5) (x3tt 1 0), TWO)) }_ 2 ^^ 11 (submsg_msg 1 {(c 0 4, (ub (c 0 4) pk (bk 6) (x3tt 1 0), TWO)) }_ 2 ^^ 12 (x5tex')))).\nreflexivity.\nrewrite <- H in H1.\n\nsimpl.  \n\nassert (   {z\n                          (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)),\n                          (ub (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                             (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 5))\n                             (f\n                                [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n                                (pi1 (ks (nonce 0)),\n                                (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                                   (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 5)),\n                                sign\n                                  (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                                     (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 5))) \n                                  (pi2 (ks (nonce 0))) (rs (nonce 9))));\n                                (pi1 (ks (nonce 1)),\n                                (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                                   (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6)),\n                                sign\n                                  (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                                     (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6))) \n                                  (pi2 (ks (nonce 1))) (rs (nonce 10))))]), TWO)) }_ 2 ^^ 13 # {z\n                            (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)),\n                            (ub (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                               (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 5))\n                               (f\n                                  [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n                                  (pi1 (ks (nonce 0)),\n                                  (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5),\n                                  sign (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5)) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n                                  (pi1 (ks (nonce 1)),\n                                  (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                                     (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6)),\n                                  sign\n                                    (bl (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                                       (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (rb (nonce 6))) \n                                    (pi2 (ks (nonce 1))) (rs (nonce 10))))]), TWO)) }_ 2 ^^ 13).\nAxiom zeroEqlxy: forall x y,  (z x) # (z y).\nrewrite zeroEqlxy with (x:= (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)),\n     (ub\n        (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)))\n        (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) \n        (rb (nonce 5))\n        (f\n           [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n           (pi1 (ks (nonce 0)),\n           (bl\n              (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                 (kc (nonce 3)))\n              (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n              (rb (nonce 5)),\n           sign\n             (bl\n                (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                   (kc (nonce 3)))\n                (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                (rb (nonce 5))) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n           (pi1 (ks (nonce 1)),\n           (bl\n              (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                 (kc (nonce 4)))\n              (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n              (rb (nonce 6)),\n           sign\n             (bl\n                (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                   (kc (nonce 4)))\n                (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))]), TWO))) (y:= (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) (kc (nonce 3)),\n       (ub\n          (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n             (kc (nonce 3)))\n          (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))])) \n          (rb (nonce 5))\n          (f\n             [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n             (pi1 (ks (nonce 0)),\n             (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) (pubkey x1) (r 5),\n             sign\n               (bl (comm (V1 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; vk 0; vk 1; pke 2])) (kc (nonce 3))) \n                  (pubkey x1) (r 5)) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n             (pi1 (ks (nonce 1)),\n             (bl\n                (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                   (kc (nonce 4)))\n                (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                (rb (nonce 6)),\n             sign\n               (bl\n                  (comm (V0 (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                     (kc (nonce 4)))\n                  (pubkey (f [A; B; M; C1; C2; C3; ONE; TWO; THREE; pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n                  (rb (nonce 6))) (pi2 (ks (nonce 1))) (rs (nonce 10))))]), TWO))).\n\nreflexivity.\n\nrewrite H0 in H1.\nrewrite H0 in ftran. clear H H0.\nassert ({z (c 1 4, (ub (c 1 4) pk (bk 6) (x3tt 0 1), TWO)) }_ 2 ^^ 14 # {z (c 1 4, (ub (c 1 4) pk (bk 6) (x3tt 1 0), TWO)) }_ 2 ^^ 14 ).\nrewrite zeroEqlxy. reflexivity. rewrite H in ftran.\nrewrite H in H1.\nclear H. \n\nassert ( (x4ttt 1 0) # (submsg_msg 0  {(c 1 3, (ub (c 1 3) pk (bk 5) (x3tt 1 0), TWO)) }_ 2 ^^ 11 (submsg_msg 1 {(c 0 4, (ub (c 0 4) pk (bk 6) (x3tt 1 0), TWO)) }_ 2 ^^ 12 x4tttex'))).\nreflexivity.\nrewrite <- H in H1.\n\nclear H.\n\nassert ( [msg (dec (pi2 (pi2 (x5t 0 1))) (pi2 (ke (nonce 2)))),\n           msg\n             (comm\n                (V0\n                   (f\n                      [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                      pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                      pi1 (ke (nonce 2))])) (kc (nonce 3)),\n             ub\n               (comm\n                  (V0\n                     (f\n                        [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                        pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                        pi1 (ke (nonce 2))])) (kc (nonce 3)))\n               (pubkey\n                  (f\n                     [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                     pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                     pi1 (ke (nonce 2))])) (rb (nonce 5))\n               (f\n                  [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                  pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                  pi1 (ke (nonce 2));\n                  (pi1 (ks (nonce 0)),\n                  (bl\n                     (comm\n                        (V0\n                           (f\n                              [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                              pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                              pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                     (pubkey\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (rb (nonce 5)),\n                  sign\n                    (bl\n                       (comm\n                          (V0\n                             (f\n                                [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                                pi1 (ke (nonce 2))])) \n                          (kc (nonce 3)))\n                       (pubkey\n                          (f\n                             [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                             pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                             pi1 (ke (nonce 2))])) (rb (nonce 5))) \n                    (pi2 (ks (nonce 0))) (rs (nonce 9))));\n                  (pi1 (ks (nonce 1)),\n                  (bl\n                     (comm\n                        (V1\n                           (f\n                              [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                              pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                              pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                     (pubkey\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (rb (nonce 6)),\n                  sign\n                    (bl\n                       (comm\n                          (V1\n                             (f\n                                [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                                pi1 (ke (nonce 2))])) \n                          (kc (nonce 4)))\n                       (pubkey\n                          (f\n                             [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                             pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                             pi1 (ke (nonce 2))])) (rb (nonce 6))) \n                    (pi2 (ks (nonce 1))) (rs (nonce 10))))])),\n           msg\n             (comm\n                (V1\n                   (f\n                      [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                      pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                      pi1 (ke (nonce 2))])) (kc (nonce 4)),\n             ub\n               (comm\n                  (V1\n                     (f\n                        [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                        pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                        pi1 (ke (nonce 2))])) (kc (nonce 4)))\n               (pubkey\n                  (f\n                     [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                     pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                     pi1 (ke (nonce 2))])) (rb (nonce 6))\n               (f\n                  [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                  pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                  pi1 (ke (nonce 2));\n                  (pi1 (ks (nonce 0)),\n                  (bl\n                     (comm\n                        (V0\n                           (f\n                              [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                              pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                              pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                     (pubkey\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (rb (nonce 5)),\n                  sign\n                    (bl\n                       (comm\n                          (V0\n                             (f\n                                [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                                pi1 (ke (nonce 2))])) \n                          (kc (nonce 3)))\n                       (pubkey\n                          (f\n                             [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                             pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                             pi1 (ke (nonce 2))])) (rb (nonce 5))) \n                    (pi2 (ks (nonce 0))) (rs (nonce 9))));\n                  (pi1 (ks (nonce 1)),\n                  (bl\n                     (comm\n                        (V1\n                           (f\n                              [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                              pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                              pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                     (pubkey\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (rb (nonce 6)),\n                  sign\n                    (bl\n                       (comm\n                          (V1\n                             (f\n                                [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                                pi1 (ke (nonce 2))])) \n                          (kc (nonce 4)))\n                       (pubkey\n                          (f\n                             [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                             pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                             pi1 (ke (nonce 2))])) (rb (nonce 6))) \n                    (pi2 (ks (nonce 1))) (rs (nonce 10))))])), \n           msg A, msg B, msg M, msg C1, msg C2, msg C3, \n           msg ONE, msg TWO, msg THREE, msg (pi1 (ks (nonce 0))),\n           msg (pi1 (ks (nonce 1))), msg (pi1 (ke (nonce 2))),\n           msg\n             {(comm\n                 (V0\n                    (f\n                       [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                       pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                       pi1 (ke (nonce 2))])) (kc (nonce 3)),\n              (ub (c 0 3) pk (bk 5) (x3tt 0 1), TWO)) }_ 2 ^^ 11,\n           msg {(c 1 4, (ub (c 1 4) pk (bk 6) (x3tt 0 1), TWO)) }_ 2 ^^ 12,\n           msg (pi2 (ks (nonce 0))), msg (pi2 (ks (nonce 1))), \n           msg (rs (nonce 9)), msg (rs (nonce 10)),\n           msg\n             (pi1 (ks (nonce 0)),\n             (bl\n                (comm\n                   (V0\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                (pubkey\n                   (f\n                      [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                      pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                      pi1 (ke (nonce 2))])) (rb (nonce 5)),\n             sign\n               (bl\n                  (comm\n                     (V0\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                  (pubkey\n                     (f\n                        [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                        pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                        pi1 (ke (nonce 2))])) (rb (nonce 5))) \n               (pi2 (ks (nonce 0))) (rs (nonce 9)))),\n           msg\n             (pi1 (ks (nonce 1)),\n             (bl\n                (comm\n                   (V1\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                (pubkey\n                   (f\n                      [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                      pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                      pi1 (ke (nonce 2))])) (rb (nonce 6)),\n             sign\n               (bl\n                  (comm\n                     (V1\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                  (pubkey\n                     (f\n                        [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                        pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                        pi1 (ke (nonce 2))])) (rb (nonce 6))) \n               (pi2 (ks (nonce 1))) (rs (nonce 10)))),\n           msg\n             (f\n                [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n                (pi1 (ks (nonce 0)),\n                (bl\n                   (comm\n                      (V0\n                         (f\n                            [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                            pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                            pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                   (pubkey\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (rb (nonce 5)),\n                sign\n                  (bl\n                     (comm\n                        (V0\n                           (f\n                              [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                              pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                              pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                     (pubkey\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (rb (nonce 5))) \n                  (pi2 (ks (nonce 0))) (rs (nonce 9))));\n                (pi1 (ks (nonce 1)),\n                (bl\n                   (comm\n                      (V1\n                         (f\n                            [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                            pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                            pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                   (pubkey\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (rb (nonce 6)),\n                sign\n                  (bl\n                     (comm\n                        (V1\n                           (f\n                              [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                              pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                              pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                     (pubkey\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (rb (nonce 6))) \n                  (pi2 (ks (nonce 1))) (rs (nonce 10))))]), \n           msg (x4ttt 0 1), msg (x5t 0 1),\n           bol\n             (acc\n                (comm\n                   (V0\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                (pubkey\n                   (f\n                      [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                      pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                      pi1 (ke (nonce 2))])) (rb (nonce 5))\n                (f\n                   [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                   pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                   pi1 (ke (nonce 2));\n                   (pi1 (ks (nonce 0)),\n                   (bl\n                      (comm\n                         (V0\n                            (f\n                               [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                               pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                               pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                      (pubkey\n                         (f\n                            [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                            pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                            pi1 (ke (nonce 2))])) (rb (nonce 5)),\n                   sign\n                     (bl\n                        (comm\n                           (V0\n                              (f\n                                 [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                 pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                                 pi1 (ke (nonce 2))])) \n                           (kc (nonce 3)))\n                        (pubkey\n                           (f\n                              [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                              pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                              pi1 (ke (nonce 2))])) (rb (nonce 5))) \n                     (pi2 (ks (nonce 0))) (rs (nonce 9))));\n                   (pi1 (ks (nonce 1)),\n                   (bl\n                      (comm\n                         (V1\n                            (f\n                               [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                               pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                               pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                      (pubkey\n                         (f\n                            [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                            pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                            pi1 (ke (nonce 2))])) (rb (nonce 6)),\n                   sign\n                     (bl\n                        (comm\n                           (V1\n                              (f\n                                 [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                 pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                                 pi1 (ke (nonce 2))])) \n                           (kc (nonce 4)))\n                        (pubkey\n                           (f\n                              [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                              pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                              pi1 (ke (nonce 2))])) (rb (nonce 6))) \n                     (pi2 (ks (nonce 1))) (rs (nonce 10))))])),\n           bol\n             (acc\n                (comm\n                   (V1\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                (pubkey\n                   (f\n                      [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                      pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                      pi1 (ke (nonce 2))])) (rb (nonce 6))\n                (f\n                   [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                   pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                   pi1 (ke (nonce 2));\n                   (pi1 (ks (nonce 0)),\n                   (bl\n                      (comm\n                         (V0\n                            (f\n                               [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                               pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                               pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                      (pubkey\n                         (f\n                            [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                            pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                            pi1 (ke (nonce 2))])) (rb (nonce 5)),\n                   sign\n                     (bl\n                        (comm\n                           (V0\n                              (f\n                                 [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                 pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                                 pi1 (ke (nonce 2))])) \n                           (kc (nonce 3)))\n                        (pubkey\n                           (f\n                              [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                              pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                              pi1 (ke (nonce 2))])) (rb (nonce 5))) \n                     (pi2 (ks (nonce 0))) (rs (nonce 9))));\n                   (pi1 (ks (nonce 1)),\n                   (bl\n                      (comm\n                         (V1\n                            (f\n                               [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                               pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                               pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                      (pubkey\n                         (f\n                            [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                            pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                            pi1 (ke (nonce 2))])) (rb (nonce 6)),\n                   sign\n                     (bl\n                        (comm\n                           (V1\n                              (f\n                                 [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                 pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                                 pi1 (ke (nonce 2))])) \n                           (kc (nonce 4)))\n                        (pubkey\n                           (f\n                              [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                              pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                              pi1 (ke (nonce 2))])) (rb (nonce 6))) \n                     (pi2 (ks (nonce 1))) (rs (nonce 10))))]))] ~ [msg (dec (pi2 (pi2 (x5t 1 0))) (pi2 (ke (nonce 2)))),\n       msg\n         (comm\n            (V1\n               (f\n                  [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                  pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                  pi1 (ke (nonce 2))])) (kc (nonce 3)),\n         ub\n           (comm\n              (V1\n                 (f\n                    [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                    pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                    pi1 (ke (nonce 2))])) (kc (nonce 3)))\n           (pubkey\n              (f\n                 [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                 pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n           (rb (nonce 5))\n           (f\n              [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n              pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n              (pi1 (ks (nonce 0)),\n              (bl\n                 (comm\n                    (V1\n                       (f\n                          [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                          pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                          pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                 (pubkey\n                    (f\n                       [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                       pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                       pi1 (ke (nonce 2))])) (rb (nonce 5)),\n              sign\n                (bl\n                   (comm\n                      (V1\n                         (f\n                            [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                            pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                            pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                   (pubkey\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (rb (nonce 5))) \n                (pi2 (ks (nonce 0))) (rs (nonce 9))));\n              (pi1 (ks (nonce 1)),\n              (bl\n                 (comm\n                    (V0\n                       (f\n                          [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                          pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                          pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                 (pubkey\n                    (f\n                       [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                       pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                       pi1 (ke (nonce 2))])) (rb (nonce 6)),\n              sign\n                (bl\n                   (comm\n                      (V0\n                         (f\n                            [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                            pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                            pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                   (pubkey\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (rb (nonce 6))) \n                (pi2 (ks (nonce 1))) (rs (nonce 10))))])),\n       msg\n         (comm\n            (V0\n               (f\n                  [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                  pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                  pi1 (ke (nonce 2))])) (kc (nonce 4)),\n         ub\n           (comm\n              (V0\n                 (f\n                    [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                    pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                    pi1 (ke (nonce 2))])) (kc (nonce 4)))\n           (pubkey\n              (f\n                 [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                 pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2))]))\n           (rb (nonce 6))\n           (f\n              [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n              pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n              (pi1 (ks (nonce 0)),\n              (bl\n                 (comm\n                    (V1\n                       (f\n                          [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                          pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                          pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                 (pubkey\n                    (f\n                       [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                       pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                       pi1 (ke (nonce 2))])) (rb (nonce 5)),\n              sign\n                (bl\n                   (comm\n                      (V1\n                         (f\n                            [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                            pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                            pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                   (pubkey\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (rb (nonce 5))) \n                (pi2 (ks (nonce 0))) (rs (nonce 9))));\n              (pi1 (ks (nonce 1)),\n              (bl\n                 (comm\n                    (V0\n                       (f\n                          [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                          pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                          pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                 (pubkey\n                    (f\n                       [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                       pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                       pi1 (ke (nonce 2))])) (rb (nonce 6)),\n              sign\n                (bl\n                   (comm\n                      (V0\n                         (f\n                            [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                            pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                            pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                   (pubkey\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (rb (nonce 6))) \n                (pi2 (ks (nonce 1))) (rs (nonce 10))))])), \n       msg A, msg B, msg M, msg C1, msg C2, msg C3, \n       msg ONE, msg TWO, msg THREE, msg (pi1 (ks (nonce 0))),\n       msg (pi1 (ks (nonce 1))), msg (pi1 (ke (nonce 2))),\n       msg\n         {(comm\n             (V1\n                (f\n                   [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                   pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                   pi1 (ke (nonce 2))])) (kc (nonce 3)),\n          (ub\n             (comm\n                (V1\n                   (f\n                      [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                      pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                      pi1 (ke (nonce 2))])) (kc (nonce 3)))\n             (pubkey\n                (f\n                   [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                   pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                   pi1 (ke (nonce 2))])) (rb (nonce 5))\n             (f\n                [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n                (pi1 (ks (nonce 0)),\n                (bl\n                   (comm\n                      (V1\n                         (f\n                            [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                            pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                            pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                   (pubkey\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (rb (nonce 5)),\n                sign\n                  (bl\n                     (comm\n                        (V1\n                           (f\n                              [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                              pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                              pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                     (pubkey\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (rb (nonce 5))) \n                  (pi2 (ks (nonce 0))) (rs (nonce 9))));\n                (pi1 (ks (nonce 1)),\n                (bl\n                   (comm\n                      (V0\n                         (f\n                            [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                            pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                            pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                   (pubkey\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (rb (nonce 6)),\n                sign\n                  (bl\n                     (comm\n                        (V0\n                           (f\n                              [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                              pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                              pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                     (pubkey\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (rb (nonce 6))) \n                  (pi2 (ks (nonce 1))) (rs (nonce 10))))]), TWO)) }_ 2 ^^ 11,\n       msg {(c 0 4, (ub (c 0 4) pk (bk 6) (x3tt 1 0), TWO)) }_ 2 ^^ 12,\n       msg (pi2 (ks (nonce 0))), msg (pi2 (ks (nonce 1))), \n       msg (rs (nonce 9)), msg (rs (nonce 10)),\n       msg\n         (pi1 (ks (nonce 0)),\n         (bl\n            (comm\n               (V1\n                  (f\n                     [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                     pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                     pi1 (ke (nonce 2))])) (kc (nonce 3)))\n            (pubkey\n               (f\n                  [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                  pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                  pi1 (ke (nonce 2))])) (rb (nonce 5)),\n         sign\n           (bl\n              (comm\n                 (V1\n                    (f\n                       [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                       pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                       pi1 (ke (nonce 2))])) (kc (nonce 3)))\n              (pubkey\n                 (f\n                    [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                    pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                    pi1 (ke (nonce 2))])) (rb (nonce 5))) \n           (pi2 (ks (nonce 0))) (rs (nonce 9)))),\n       msg\n         (pi1 (ks (nonce 1)),\n         (bl\n            (comm\n               (V0\n                  (f\n                     [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                     pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                     pi1 (ke (nonce 2))])) (kc (nonce 4)))\n            (pubkey\n               (f\n                  [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                  pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                  pi1 (ke (nonce 2))])) (rb (nonce 6)),\n         sign\n           (bl\n              (comm\n                 (V0\n                    (f\n                       [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                       pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                       pi1 (ke (nonce 2))])) (kc (nonce 4)))\n              (pubkey\n                 (f\n                    [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                    pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                    pi1 (ke (nonce 2))])) (rb (nonce 6))) \n           (pi2 (ks (nonce 1))) (rs (nonce 10)))),\n       msg\n         (f\n            [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n            pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n            (pi1 (ks (nonce 0)),\n            (bl\n               (comm\n                  (V1\n                     (f\n                        [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                        pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                        pi1 (ke (nonce 2))])) (kc (nonce 3)))\n               (pubkey\n                  (f\n                     [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                     pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                     pi1 (ke (nonce 2))])) (rb (nonce 5)),\n            sign\n              (bl\n                 (comm\n                    (V1\n                       (f\n                          [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                          pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                          pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                 (pubkey\n                    (f\n                       [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                       pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                       pi1 (ke (nonce 2))])) (rb (nonce 5))) \n              (pi2 (ks (nonce 0))) (rs (nonce 9))));\n            (pi1 (ks (nonce 1)),\n            (bl\n               (comm\n                  (V0\n                     (f\n                        [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                        pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                        pi1 (ke (nonce 2))])) (kc (nonce 4)))\n               (pubkey\n                  (f\n                     [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                     pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                     pi1 (ke (nonce 2))])) (rb (nonce 6)),\n            sign\n              (bl\n                 (comm\n                    (V0\n                       (f\n                          [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                          pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                          pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                 (pubkey\n                    (f\n                       [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                       pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                       pi1 (ke (nonce 2))])) (rb (nonce 6))) \n              (pi2 (ks (nonce 1))) (rs (nonce 10))))]),\n       msg (x4ttt 1 0),\n          msg (x5t 1 0),\n       bol\n         (acc\n            (comm\n               (V1\n                  (f\n                     [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                     pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                     pi1 (ke (nonce 2))])) (kc (nonce 3)))\n            (pubkey\n               (f\n                  [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                  pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                  pi1 (ke (nonce 2))])) (rb (nonce 5))\n            (f\n               [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n               pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n               (pi1 (ks (nonce 0)),\n               (bl\n                  (comm\n                     (V1\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                  (pubkey\n                     (f\n                        [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                        pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                        pi1 (ke (nonce 2))])) (rb (nonce 5)),\n               sign\n                 (bl\n                    (comm\n                       (V1\n                          (f\n                             [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                             pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                             pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                    (pubkey\n                       (f\n                          [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                          pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                          pi1 (ke (nonce 2))])) (rb (nonce 5))) \n                 (pi2 (ks (nonce 0))) (rs (nonce 9))));\n               (pi1 (ks (nonce 1)),\n               (bl\n                  (comm\n                     (V0\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                  (pubkey\n                     (f\n                        [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                        pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                        pi1 (ke (nonce 2))])) (rb (nonce 6)),\n               sign\n                 (bl\n                    (comm\n                       (V0\n                          (f\n                             [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                             pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                             pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                    (pubkey\n                       (f\n                          [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                          pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                          pi1 (ke (nonce 2))])) (rb (nonce 6))) \n                 (pi2 (ks (nonce 1))) (rs (nonce 10))))])),\n       bol\n         (acc\n            (comm\n               (V0\n                  (f\n                     [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                     pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                     pi1 (ke (nonce 2))])) (kc (nonce 4)))\n            (pubkey\n               (f\n                  [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                  pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                  pi1 (ke (nonce 2))])) (rb (nonce 6))\n            (f\n               [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n               pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n               (pi1 (ks (nonce 0)),\n               (bl\n                  (comm\n                     (V1\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                  (pubkey\n                     (f\n                        [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                        pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                        pi1 (ke (nonce 2))])) (rb (nonce 5)),\n               sign\n                 (bl\n                    (comm\n                       (V1\n                          (f\n                             [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                             pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                             pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                    (pubkey\n                       (f\n                          [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                          pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                          pi1 (ke (nonce 2))])) (rb (nonce 5))) \n                 (pi2 (ks (nonce 0))) (rs (nonce 9))));\n               (pi1 (ks (nonce 1)),\n               (bl\n                  (comm\n                     (V0\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                  (pubkey\n                     (f\n                        [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                        pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                        pi1 (ke (nonce 2))])) (rb (nonce 6)),\n               sign\n                 (bl\n                    (comm\n                       (V0\n                          (f\n                             [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                             pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                             pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                    (pubkey\n                       (f\n                          [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                          pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                          pi1 (ke (nonce 2))])) (rb (nonce 6))) \n                 (pi2 (ks (nonce 1))) (rs (nonce 10))))]))]).\n\n\napply EQI_trans with (ml2:= [msg\n           (dec\n              (pi2\n                 (pi2\n                    (f\n                       [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                       pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                       pi1 (ke (nonce 2));\n                       (pi1 (ks (nonce 0)),\n                       (bl\n                          (comm\n                             (V1\n                                (f\n                                   [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                   pi1 (ks (nonce 0)); \n                                   pi1 (ks (nonce 1)); \n                                   pi1 (ke (nonce 2))])) \n                             (kc (nonce 3)))\n                          (pubkey\n                             (f\n                                [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                                pi1 (ke (nonce 2))])) \n                          (rb (nonce 5)),\n                       sign\n                         (bl\n                            (comm\n                               (V1\n                                  (f\n                                     [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                     pi1 (ks (nonce 0)); \n                                     pi1 (ks (nonce 1)); \n                                     pi1 (ke (nonce 2))])) \n                               (kc (nonce 3)))\n                            (pubkey\n                               (f\n                                  [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                  pi1 (ks (nonce 0)); \n                                  pi1 (ks (nonce 1)); \n                                  pi1 (ke (nonce 2))])) \n                            (rb (nonce 5))) (pi2 (ks (nonce 0))) \n                         (rs (nonce 9))));\n                       (pi1 (ks (nonce 1)),\n                       (bl\n                          (comm\n                             (V0\n                                (f\n                                   [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                   pi1 (ks (nonce 0)); \n                                   pi1 (ks (nonce 1)); \n                                   pi1 (ke (nonce 2))])) \n                             (kc (nonce 4)))\n                          (pubkey\n                             (f\n                                [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                                pi1 (ke (nonce 2))])) \n                          (rb (nonce 6)),\n                       sign\n                         (bl\n                            (comm\n                               (V0\n                                  (f\n                                     [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                     pi1 (ks (nonce 0)); \n                                     pi1 (ks (nonce 1)); \n                                     pi1 (ke (nonce 2))])) \n                               (kc (nonce 4)))\n                            (pubkey\n                               (f\n                                  [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                  pi1 (ks (nonce 0)); \n                                  pi1 (ks (nonce 1)); \n                                  pi1 (ke (nonce 2))])) \n                            (rb (nonce 6))) (pi2 (ks (nonce 1))) \n                         (rs (nonce 10))));\n                       {z\n                          (comm\n                             (V0\n                                (f\n                                   [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                   pi1 (ks (nonce 0)); \n                                   pi1 (ks (nonce 1)); \n                                   pi1 (ke (nonce 2))])) \n                             (kc (nonce 3)),\n                          (ub\n                             (comm\n                                (V0\n                                   (f\n                                      [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                      pi1 (ks (nonce 0)); \n                                      pi1 (ks (nonce 1)); \n                                      pi1 (ke (nonce 2))])) \n                                (kc (nonce 3)))\n                             (pubkey\n                                (f\n                                   [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                   pi1 (ks (nonce 0)); \n                                   pi1 (ks (nonce 1)); \n                                   pi1 (ke (nonce 2))])) \n                             (rb (nonce 5))\n                             (f\n                                [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                                pi1 (ke (nonce 2));\n                                (pi1 (ks (nonce 0)),\n                                (bl\n                                   (comm\n                                      (V1\n                                         (f\n                                            [A; B; M; C1; C2; C3; ONE; TWO;\n                                            THREE; \n                                            vk 0; \n                                            vk 1; \n                                            pke 2])) \n                                      (kc (nonce 3))) \n                                   (pubkey x1) (r 5),\n                                sign\n                                  (bl\n                                     (comm\n                                        (V1\n                                           (f\n                                              [A; B; M; C1; C2; C3; ONE;\n                                              TWO; THREE; \n                                              vk 0; \n                                              vk 1; \n                                              pke 2])) \n                                        (kc (nonce 3))) \n                                     (pubkey x1) (r 5)) \n                                  (pi2 (ks (nonce 0))) \n                                  (rs (nonce 9))));\n                                (pi1 (ks (nonce 1)),\n                                (bl\n                                   (comm\n                                      (V0\n                                         (f\n                                            [A; B; M; C1; C2; C3; ONE; TWO;\n                                            THREE; \n                                            pi1 (ks (nonce 0)); \n                                            pi1 (ks (nonce 1)); \n                                            pi1 (ke (nonce 2))])) \n                                      (kc (nonce 4)))\n                                   (pubkey\n                                      (f\n                                         [A; B; M; C1; C2; C3; ONE; TWO;\n                                         THREE; pi1 (ks (nonce 0));\n                                         pi1 (ks (nonce 1)); \n                                         pi1 (ke (nonce 2))])) \n                                   (rb (nonce 6)),\n                                sign\n                                  (bl\n                                     (comm\n                                        (V0\n                                           (f\n                                              [A; B; M; C1; C2; C3; ONE;\n                                              TWO; THREE; \n                                              pi1 (ks (nonce 0));\n                                              pi1 (ks (nonce 1));\n                                              pi1 (ke (nonce 2))])) \n                                        (kc (nonce 4)))\n                                     (pubkey\n                                        (f\n                                           [A; B; M; C1; C2; C3; ONE; TWO;\n                                           THREE; \n                                           pi1 (ks (nonce 0)); \n                                           pi1 (ks (nonce 1)); \n                                           pi1 (ke (nonce 2))])) \n                                     (rb (nonce 6))) (pi2 (ks (nonce 1)))\n                                  (rs (nonce 10))))]), TWO)) }_ 2 ^^ 13;\n                       {z (c 1 4, (ub (c 1 4) pk (bk 6) (x3tt 1 0), TWO))\n                       }_ 2 ^^ 14]))) (pi2 (ke (nonce 2)))),\n        msg\n          (comm\n             (V1\n                (f\n                   [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                   pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                   pi1 (ke (nonce 2))])) (kc (nonce 3)),\n          ub\n            (comm\n               (V1\n                  (f\n                     [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                     pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                     pi1 (ke (nonce 2))])) (kc (nonce 3)))\n            (pubkey\n               (f\n                  [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                  pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                  pi1 (ke (nonce 2))])) (rb (nonce 5))\n            (f\n               [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n               pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n               (pi1 (ks (nonce 0)),\n               (bl\n                  (comm\n                     (V1\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                  (pubkey\n                     (f\n                        [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                        pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                        pi1 (ke (nonce 2))])) (rb (nonce 5)),\n               sign\n                 (bl\n                    (comm\n                       (V1\n                          (f\n                             [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                             pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                             pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                    (pubkey\n                       (f\n                          [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                          pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                          pi1 (ke (nonce 2))])) (rb (nonce 5))) \n                 (pi2 (ks (nonce 0))) (rs (nonce 9))));\n               (pi1 (ks (nonce 1)),\n               (bl\n                  (comm\n                     (V0\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                  (pubkey\n                     (f\n                        [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                        pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                        pi1 (ke (nonce 2))])) (rb (nonce 6)),\n               sign\n                 (bl\n                    (comm\n                       (V0\n                          (f\n                             [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                             pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                             pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                    (pubkey\n                       (f\n                          [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                          pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                          pi1 (ke (nonce 2))])) (rb (nonce 6))) \n                 (pi2 (ks (nonce 1))) (rs (nonce 10))))])),\n        msg\n          (comm\n             (V0\n                (f\n                   [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                   pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                   pi1 (ke (nonce 2))])) (kc (nonce 4)),\n          ub\n            (comm\n               (V0\n                  (f\n                     [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                     pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                     pi1 (ke (nonce 2))])) (kc (nonce 4)))\n            (pubkey\n               (f\n                  [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                  pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                  pi1 (ke (nonce 2))])) (rb (nonce 6))\n            (f\n               [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n               pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n               (pi1 (ks (nonce 0)),\n               (bl\n                  (comm\n                     (V1\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                  (pubkey\n                     (f\n                        [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                        pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                        pi1 (ke (nonce 2))])) (rb (nonce 5)),\n               sign\n                 (bl\n                    (comm\n                       (V1\n                          (f\n                             [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                             pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                             pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                    (pubkey\n                       (f\n                          [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                          pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                          pi1 (ke (nonce 2))])) (rb (nonce 5))) \n                 (pi2 (ks (nonce 0))) (rs (nonce 9))));\n               (pi1 (ks (nonce 1)),\n               (bl\n                  (comm\n                     (V0\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                  (pubkey\n                     (f\n                        [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                        pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                        pi1 (ke (nonce 2))])) (rb (nonce 6)),\n               sign\n                 (bl\n                    (comm\n                       (V0\n                          (f\n                             [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                             pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                             pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                    (pubkey\n                       (f\n                          [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                          pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                          pi1 (ke (nonce 2))])) (rb (nonce 6))) \n                 (pi2 (ks (nonce 1))) (rs (nonce 10))))])), \n        msg A, msg B, msg M, msg C1, msg C2, msg C3, \n        msg ONE, msg TWO, msg THREE, msg (pi1 (ks (nonce 0))),\n        msg (pi1 (ks (nonce 1))), msg (pi1 (ke (nonce 2))),\n        msg\n          {z\n             (comm\n                (V0\n                   (f\n                      [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                      pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                      pi1 (ke (nonce 2))])) (kc (nonce 3)),\n             (ub\n                (comm\n                   (V0\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                (pubkey\n                   (f\n                      [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                      pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                      pi1 (ke (nonce 2))])) (rb (nonce 5))\n                (f\n                   [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                   pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                   pi1 (ke (nonce 2));\n                   (pi1 (ks (nonce 0)),\n                   (bl\n                      (comm\n                         (V1\n                            (f\n                               [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                               vk 0; vk 1; pke 2])) \n                         (kc (nonce 3))) (pubkey x1) (r 5),\n                   sign\n                     (bl\n                        (comm\n                           (V1\n                              (f\n                                 [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                 vk 0; vk 1; pke 2])) \n                           (kc (nonce 3))) (pubkey x1) \n                        (r 5)) (pi2 (ks (nonce 0))) (rs (nonce 9))));\n                   (pi1 (ks (nonce 1)),\n                   (bl\n                      (comm\n                         (V0\n                            (f\n                               [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                               pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                               pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                      (pubkey\n                         (f\n                            [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                            pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                            pi1 (ke (nonce 2))])) (rb (nonce 6)),\n                   sign\n                     (bl\n                        (comm\n                           (V0\n                              (f\n                                 [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                 pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                                 pi1 (ke (nonce 2))])) \n                           (kc (nonce 4)))\n                        (pubkey\n                           (f\n                              [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                              pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                              pi1 (ke (nonce 2))])) (rb (nonce 6))) \n                     (pi2 (ks (nonce 1))) (rs (nonce 10))))]), TWO)) }_ 2 ^^ 13,\n        msg {z (c 1 4, (ub (c 1 4) pk (bk 6) (x3tt 1 0), TWO)) }_ 2 ^^ 14,\n        msg (pi2 (ks (nonce 0))), msg (pi2 (ks (nonce 1))), \n        msg (rs (nonce 9)), msg (rs (nonce 10)),\n        msg\n          (pi1 (ks (nonce 0)),\n          (bl\n             (comm\n                (V1\n                   (f\n                      [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                      pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                      pi1 (ke (nonce 2))])) (kc (nonce 3)))\n             (pubkey\n                (f\n                   [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                   pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                   pi1 (ke (nonce 2))])) (rb (nonce 5)),\n          sign\n            (bl\n               (comm\n                  (V1\n                     (f\n                        [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                        pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                        pi1 (ke (nonce 2))])) (kc (nonce 3)))\n               (pubkey\n                  (f\n                     [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                     pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                     pi1 (ke (nonce 2))])) (rb (nonce 5))) \n            (pi2 (ks (nonce 0))) (rs (nonce 9)))),\n        msg\n          (pi1 (ks (nonce 1)),\n          (bl\n             (comm\n                (V0\n                   (f\n                      [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                      pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                      pi1 (ke (nonce 2))])) (kc (nonce 4)))\n             (pubkey\n                (f\n                   [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                   pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                   pi1 (ke (nonce 2))])) (rb (nonce 6)),\n          sign\n            (bl\n               (comm\n                  (V0\n                     (f\n                        [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                        pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                        pi1 (ke (nonce 2))])) (kc (nonce 4)))\n               (pubkey\n                  (f\n                     [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                     pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                     pi1 (ke (nonce 2))])) (rb (nonce 6))) \n            (pi2 (ks (nonce 1))) (rs (nonce 10)))),\n        msg\n          (f\n             [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n             pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n             (pi1 (ks (nonce 0)),\n             (bl\n                (comm\n                   (V1\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                (pubkey\n                   (f\n                      [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                      pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                      pi1 (ke (nonce 2))])) (rb (nonce 5)),\n             sign\n               (bl\n                  (comm\n                     (V1\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                  (pubkey\n                     (f\n                        [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                        pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                        pi1 (ke (nonce 2))])) (rb (nonce 5))) \n               (pi2 (ks (nonce 0))) (rs (nonce 9))));\n             (pi1 (ks (nonce 1)),\n             (bl\n                (comm\n                   (V0\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                (pubkey\n                   (f\n                      [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                      pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                      pi1 (ke (nonce 2))])) (rb (nonce 6)),\n             sign\n               (bl\n                  (comm\n                     (V0\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                  (pubkey\n                     (f\n                        [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                        pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                        pi1 (ke (nonce 2))])) (rb (nonce 6))) \n               (pi2 (ks (nonce 1))) (rs (nonce 10))))]),\n        msg\n          (f\n             [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n             pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n             (pi1 (ks (nonce 0)),\n             (bl\n                (comm\n                   (V1\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                (pubkey\n                   (f\n                      [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                      pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                      pi1 (ke (nonce 2))])) (rb (nonce 5)),\n             sign\n               (bl\n                  (comm\n                     (V1\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                  (pubkey\n                     (f\n                        [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                        pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                        pi1 (ke (nonce 2))])) (rb (nonce 5))) \n               (pi2 (ks (nonce 0))) (rs (nonce 9))));\n             (pi1 (ks (nonce 1)),\n             (bl\n                (comm\n                   (V0\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                (pubkey\n                   (f\n                      [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                      pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                      pi1 (ke (nonce 2))])) (rb (nonce 6)),\n             sign\n               (bl\n                  (comm\n                     (V0\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                  (pubkey\n                     (f\n                        [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                        pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                        pi1 (ke (nonce 2))])) (rb (nonce 6))) \n               (pi2 (ks (nonce 1))) (rs (nonce 10))));\n             {z\n                (comm\n                   (V0\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (kc (nonce 3)),\n                (ub\n                   (comm\n                      (V0\n                         (f\n                            [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                            pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                            pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                   (pubkey\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (rb (nonce 5))\n                   (f\n                      [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                      pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                      pi1 (ke (nonce 2));\n                      (pi1 (ks (nonce 0)),\n                      (bl\n                         (comm\n                            (V1\n                               (f\n                                  [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                  vk 0; vk 1; pke 2])) \n                            (kc (nonce 3))) (pubkey x1) \n                         (r 5),\n                      sign\n                        (bl\n                           (comm\n                              (V1\n                                 (f\n                                    [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                    vk 0; vk 1; pke 2])) \n                              (kc (nonce 3))) (pubkey x1) \n                           (r 5)) (pi2 (ks (nonce 0))) \n                        (rs (nonce 9))));\n                      (pi1 (ks (nonce 1)),\n                      (bl\n                         (comm\n                            (V0\n                               (f\n                                  [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                  pi1 (ks (nonce 0)); \n                                  pi1 (ks (nonce 1)); \n                                  pi1 (ke (nonce 2))])) \n                            (kc (nonce 4)))\n                         (pubkey\n                            (f\n                               [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                               pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                               pi1 (ke (nonce 2))])) (rb (nonce 6)),\n                      sign\n                        (bl\n                           (comm\n                              (V0\n                                 (f\n                                    [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                    pi1 (ks (nonce 0)); \n                                    pi1 (ks (nonce 1)); \n                                    pi1 (ke (nonce 2))])) \n                              (kc (nonce 4)))\n                           (pubkey\n                              (f\n                                 [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                 pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                                 pi1 (ke (nonce 2))])) \n                           (rb (nonce 6))) (pi2 (ks (nonce 1))) \n                        (rs (nonce 10))))]), TWO)) }_ 2 ^^ 13]),\n        msg\n          (f\n             [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n             pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n             (pi1 (ks (nonce 0)),\n             (bl\n                (comm\n                   (V1\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                (pubkey\n                   (f\n                      [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                      pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                      pi1 (ke (nonce 2))])) (rb (nonce 5)),\n             sign\n               (bl\n                  (comm\n                     (V1\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                  (pubkey\n                     (f\n                        [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                        pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                        pi1 (ke (nonce 2))])) (rb (nonce 5))) \n               (pi2 (ks (nonce 0))) (rs (nonce 9))));\n             (pi1 (ks (nonce 1)),\n             (bl\n                (comm\n                   (V0\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                (pubkey\n                   (f\n                      [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                      pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                      pi1 (ke (nonce 2))])) (rb (nonce 6)),\n             sign\n               (bl\n                  (comm\n                     (V0\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                  (pubkey\n                     (f\n                        [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                        pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                        pi1 (ke (nonce 2))])) (rb (nonce 6))) \n               (pi2 (ks (nonce 1))) (rs (nonce 10))));\n             {z\n                (comm\n                   (V0\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (kc (nonce 3)),\n                (ub\n                   (comm\n                      (V0\n                         (f\n                            [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                            pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                            pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                   (pubkey\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (rb (nonce 5))\n                   (f\n                      [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                      pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                      pi1 (ke (nonce 2));\n                      (pi1 (ks (nonce 0)),\n                      (bl\n                         (comm\n                            (V1\n                               (f\n                                  [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                  vk 0; vk 1; pke 2])) \n                            (kc (nonce 3))) (pubkey x1) \n                         (r 5),\n                      sign\n                        (bl\n                           (comm\n                              (V1\n                                 (f\n                                    [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                    vk 0; vk 1; pke 2])) \n                              (kc (nonce 3))) (pubkey x1) \n                           (r 5)) (pi2 (ks (nonce 0))) \n                        (rs (nonce 9))));\n                      (pi1 (ks (nonce 1)),\n                      (bl\n                         (comm\n                            (V0\n                               (f\n                                  [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                  pi1 (ks (nonce 0)); \n                                  pi1 (ks (nonce 1)); \n                                  pi1 (ke (nonce 2))])) \n                            (kc (nonce 4)))\n                         (pubkey\n                            (f\n                               [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                               pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                               pi1 (ke (nonce 2))])) (rb (nonce 6)),\n                      sign\n                        (bl\n                           (comm\n                              (V0\n                                 (f\n                                    [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                    pi1 (ks (nonce 0)); \n                                    pi1 (ks (nonce 1)); \n                                    pi1 (ke (nonce 2))])) \n                              (kc (nonce 4)))\n                           (pubkey\n                              (f\n                                 [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                                 pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                                 pi1 (ke (nonce 2))])) \n                           (rb (nonce 6))) (pi2 (ks (nonce 1))) \n                        (rs (nonce 10))))]), TWO)) }_ 2 ^^ 13;\n             {z (c 1 4, (ub (c 1 4) pk (bk 6) (x3tt 1 0), TWO)) }_ 2 ^^ 14]),\n        bol\n          (acc\n             (comm\n                (V1\n                   (f\n                      [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                      pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                      pi1 (ke (nonce 2))])) (kc (nonce 3)))\n             (pubkey\n                (f\n                   [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                   pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                   pi1 (ke (nonce 2))])) (rb (nonce 5))\n             (f\n                [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n                (pi1 (ks (nonce 0)),\n                (bl\n                   (comm\n                      (V1\n                         (f\n                            [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                            pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                            pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                   (pubkey\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (rb (nonce 5)),\n                sign\n                  (bl\n                     (comm\n                        (V1\n                           (f\n                              [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                              pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                              pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                     (pubkey\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (rb (nonce 5))) \n                  (pi2 (ks (nonce 0))) (rs (nonce 9))));\n                (pi1 (ks (nonce 1)),\n                (bl\n                   (comm\n                      (V0\n                         (f\n                            [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                            pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                            pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                   (pubkey\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (rb (nonce 6)),\n                sign\n                  (bl\n                     (comm\n                        (V0\n                           (f\n                              [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                              pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                              pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                     (pubkey\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (rb (nonce 6))) \n                  (pi2 (ks (nonce 1))) (rs (nonce 10))))])),\n        bol\n          (acc\n             (comm\n                (V0\n                   (f\n                      [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                      pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                      pi1 (ke (nonce 2))])) (kc (nonce 4)))\n             (pubkey\n                (f\n                   [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                   pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                   pi1 (ke (nonce 2))])) (rb (nonce 6))\n             (f\n                [A; B; M; C1; C2; C3; ONE; TWO; THREE; \n                pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); pi1 (ke (nonce 2));\n                (pi1 (ks (nonce 0)),\n                (bl\n                   (comm\n                      (V1\n                         (f\n                            [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                            pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                            pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                   (pubkey\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (rb (nonce 5)),\n                sign\n                  (bl\n                     (comm\n                        (V1\n                           (f\n                              [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                              pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                              pi1 (ke (nonce 2))])) (kc (nonce 3)))\n                     (pubkey\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (rb (nonce 5))) \n                  (pi2 (ks (nonce 0))) (rs (nonce 9))));\n                (pi1 (ks (nonce 1)),\n                (bl\n                   (comm\n                      (V0\n                         (f\n                            [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                            pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                            pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                   (pubkey\n                      (f\n                         [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                         pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                         pi1 (ke (nonce 2))])) (rb (nonce 6)),\n                sign\n                  (bl\n                     (comm\n                        (V0\n                           (f\n                              [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                              pi1 (ks (nonce 0)); pi1 (ks (nonce 1));\n                              pi1 (ke (nonce 2))])) (kc (nonce 4)))\n                     (pubkey\n                        (f\n                           [A; B; M; C1; C2; C3; ONE; TWO; THREE;\n                           pi1 (ks (nonce 0)); pi1 (ks (nonce 1)); \n                           pi1 (ke (nonce 2))])) (rb (nonce 6))) \n                  (pi2 (ks (nonce 1))) (rs (nonce 10))))]))]).\napply ftran.\napply H1; try split; auto. simpl.\nclear ftran.\nclear H1.\n\nunfold theta.\nunfold vcheck. unfold tr.\n restrsublis H; simpl;auto.\nreflexivity.\nrepeat try auto. reflexivity.\nreflexivity.\nreflexivity.\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(** Indistinguishability proof of shuffling step *)\nTheorem frame5ind: (phi5 0 1) ~ (phi5 1 0).\nProof.  unfold phi5, phi4, phi3, phi2, phi1. simpl. unfold t1, t2, t3, t4, t4s.\n        apply IFBRANCH_M5 with (ml1:= phi0) (ml2:= phi0). unfold Avote. \n        apply IFBRANCH_M4 with (ml1:= phi0 ++ [ bol (theta x1 A), msg (tr 0 0 3 5 9)]) (ml2:= phi0 ++ [bol (theta x1 A), msg (tr 0 1 3 5 9)]).\n        apply IFBRANCH_M3 with (ml1:= phi0 ++ [ bol (theta x1 A), msg (tr 0 0 3 5 9), bol (theta (x2t 0) B), msg (tr 1 1 4 6 10)]) (ml2:= phi0 ++ [bol (theta x1 A), msg (tr 0 1 3 5 9), bol (theta (x2t 1) B), msg (tr 1 0 4 6 10)]).\n\n        apply IFBRANCH_M3 with (ml1:= phi0 ++ [ bol (theta x1 A), msg (tr 0 0 3 5 9), bol (theta (x2t 0) B), msg (tr 1 1 4 6 10), bol (to (x3tt 0 1)) #? A]) (ml2:= phi0 ++ [bol (theta x1 A), msg (tr 0 1 3 5 9), bol (theta (x2t 1) B), msg (tr 1 0 4 6 10), bol (to (x3tt 1 0)) #? A]).\n\n        apply IFBRANCH_M2 with (ml1:= phi0 ++ [ bol (theta x1 A), msg (tr 0 0 3 5 9), bol (theta (x2t 0) B), msg (tr 1 1 4 6 10), bol (to (x3tt 0 1)) #? A, bol (acpt 0 3 5 (x3tt 0 1)), msg (e 0 3 5 (x3tt 0 1) TWO 11)]) (ml2:= phi0 ++ [bol (theta x1 A), msg (tr 0 1 3 5 9), bol (theta (x2t 1) B), msg (tr 1 0 4 6 10), bol (to (x3tt 1 0)) #? A, bol (acpt 1 3 5 (x3tt 1 0)), msg (e 1 3 5 (x3tt 1 0) TWO 11)]).\n        apply IFBRANCH_M2 with (ml1:= phi0 ++ [ bol (theta x1 A), msg (tr 0 0 3 5 9), bol (theta (x2t 0) B), msg (tr 1 1 4 6 10), bol (to (x3tt 0 1)) #? A, bol (acpt 0 3 5 (x3tt 0 1)), msg (e 0 3 5 (x3tt 0 1) TWO 11), bol (to (x4ttt 0 1)) #? B]) (ml2:= phi0 ++ [bol (theta x1 A), msg (tr 0 1 3 5 9), bol (theta (x2t 1) B), msg (tr 1 0 4 6 10), bol (to (x3tt 1 0)) #? A, bol (acpt 1 3 5 (x3tt 1 0)), msg (e 1 3 5 (x3tt 1 0) TWO 11), bol (to (x4ttt 1 0)) #? B]). simpl. unfold t5, mchecks, strm.\n\n        apply IFBRANCH_M1 with (ml1:= phi0 ++ [ bol (theta x1 A), msg (tr 0 0 3 5 9), bol (theta (x2t 0) B), msg (tr 1 1 4 6 10), bol (to (x3tt 0 1)) #? A, bol (acpt 0 3 5 (x3tt 0 1)), msg (e 0 3 5 (x3tt 0 1) TWO 11), bol (to (x4ttt 0 1)) #? B, bol (acpt 1 4 6 (x3tt 0 1)),\n   msg (e 1 4 6 (x3tt 0 1) TWO 12)]) (ml2:= phi0 ++ [bol (theta x1 A), msg (tr 0 1 3 5 9), bol (theta (x2t 1) B), msg (tr 1 0 4 6 10), bol (to (x3tt 1 0)) #? A, bol (acpt 1 3 5 (x3tt 1 0)), msg (e 1 3 5 (x3tt 1 0) TWO 11), bol (to (x4ttt 1 0)) #? B, bol (acpt 0 4 6 (x3tt 1 0)),\n                                                     msg (e 0 4 6 (x3tt 1 0) TWO 12)]). simpl.\n        unfold p, e, d, negb, pchecks, dist. \n        pose proof(tempax (tau 1 (x5t 0 1)) 2 11 12 (c 0 3, (ub (c 0 3) pk (bk 5) (x3tt 0 1), TWO)) (c 1 4, (ub (c 1 4) pk (bk 6) (x3tt 0 1), TWO))) as tau1.\n        pose proof(tempax (tau 2 (x5t 0 1)) 2 11 12 (c 0 3, (ub (c 0 3) pk (bk 5) (x3tt 0 1), TWO)) (c 1 4, (ub (c 1 4) pk (bk 6) (x3tt 0 1), TWO))) as tau2.\n        pose proof(tempax (tau 3 (x5t 0 1)) 2 11 12 (c 0 3, (ub (c 0 3) pk (bk 5) (x3tt 0 1), TWO)) (c 1 4, (ub (c 1 4) pk (bk 6) (x3tt 0 1), TWO))) as tau3. repeat unfold d, dist, p, negb, pchecks.  rewrite tau1, tau2, tau3.\n\n\npose proof(tempax (tau 1 (x5t 1 0)) 2 11 12 (c 1 3, (ub (c 1 3) pk (bk 5) (x3tt 1 0), TWO)) (c 0 4, (ub (c 0 4) pk (bk 6) (x3tt 1 0), TWO))) as tau1'.\n        pose proof(tempax (tau 2 (x5t 1 0)) 2 11 12 (c 1 3, (ub (c 1 3) pk (bk 5) (x3tt 1 0), TWO)) (c 0 4, (ub (c 0 4) pk (bk 6) (x3tt 1 0), TWO))) as tau2'.\n                pose proof(tempax (tau 3 (x5t 1 0)) 2 11 12 (c 1 3, (ub (c 1 3) pk (bk 5) (x3tt 1 0), TWO)) (c 0 4, (ub (c 0 4) pk (bk 6) (x3tt 1 0), TWO))) as tau3'.\nAdmitted.\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/votingShuf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2820568903390817}}
{"text": "Require Import Hask.Data.Tuple.\nRequire Import Hask.Control.Monad.\nRequire Import Hask.Data.Functor.Identity.\nRequire Import Hask.Control.Monad.Cont.\nRequire Import Coq.Unicode.Utf8.\nRequire Import FunctionalExtensionality.\nRequire Import Pact.Data.Monoid.\nRequire Import Pact.Data.Either.\n\nGeneralizable All Variables.\nSet Primitive Projections.\n\n(******************************************************************************\n * The RWSET Monad transformer\n *)\n\nLtac rwse :=\n  let r := fresh \"r\" in extensionality r;\n  let s := fresh \"s\" in extensionality s.\n\nSection RWSET.\n\nContext {r w s e : Type}.\nContext {m : Type → Type}.\n\nDefinition RWSET `{Monad m} `{Monoid w} (a : Type) : Type :=\n  r → s → m (e + (a * (s * w)))%type.\n\nContext `{Monad m}.\nContext `{Monoid w}.\n\nDefinition ask : RWSET r :=\n  λ r s, pure (inr (r, (s, mempty))).\nDefinition asks {a : Type} (f : r → a) : RWSET a :=\n  λ r s, pure (inr (f r, (s, mempty))).\nDefinition local (f : r → r) `(x : RWSET a) : RWSET a :=\n  λ r s, x (f r) s.\nDefinition get : RWSET s :=\n  λ _ s, pure (inr (s, (s, mempty))).\nDefinition gets {a : Type} (f : s → a) : RWSET a :=\n  λ _ s, pure (inr (f s, (s, mempty))).\nDefinition put (x : s) : RWSET unit :=\n  λ _ _, pure (inr (tt, (x, mempty))).\nDefinition modify (f : s → s) : RWSET unit :=\n  λ _ s, pure (inr (tt, (f s, mempty))).\nDefinition tell (v : w) : RWSET unit :=\n  λ _ s, pure (inr (tt, (s, v))).\nDefinition throw {a : Type} (err : e) : RWSET a :=\n  λ _ _, pure (inl err).\n\n#[export]\nInstance RWSET_Functor : Functor RWSET := {\n  fmap := λ a _ f (x : RWSET a), λ r s,\n    fmap[m] (fmap (first f)) (x r s)\n}.\n\nDefinition RWSET_ap `(f : RWSET (a → b)) (x : RWSET a) :\n  RWSET b := λ r s,\n    f' <- f r s ;\n    match f' with\n    | inl e => pure (inl e)\n    | inr (f'', (s', w')) =>\n        x' <- fmap f'' x r s' ;\n        pure (match x' with\n              | inl e => inl e\n              | inr (x'', (s'', w'')) =>\n                  inr (x'', (s'', w' ⨂ w''))\n              end)\n    end.\n\n#[export]\nInstance RWSET_Applicative : Applicative RWSET := {\n  is_functor := RWSET_Functor;\n  pure := λ _ x, λ _ s, pure (inr (x, (s, mempty)));\n  ap   := λ _ _, RWSET_ap\n}.\n\nDefinition RWSET_join `(x : RWSET (RWSET a)) :\n  RWSET a := λ r s,\n    x' <- x r s ;\n    match x' with\n    | inl e => pure (inl e)\n    | inr (y, (s', w')) =>\n        y' <- y r s' ;\n        pure (match y' with\n              | inl e => inl e\n              | inr (z, (s'', w'')) =>\n                  inr (z, (s'', w' ⨂ w''))\n              end)\n    end.\n\n#[export]\nInstance RWSET_Monad : Monad RWSET | 1 := {\n  is_applicative := RWSET_Applicative;\n  join := λ _, RWSET_join\n}.\n\nEnd RWSET.\n\nArguments RWSET r w s e m {_ _}.\nArguments RWSET_ap {r w s e m _ _ a b} f x _ _ /.\nArguments RWSET_join {r w s e m _ _ a} x _ _ /.\n\n#[export] Hint Unfold RWSET_ap : core.\n#[export] Hint Unfold RWSET_join : core.\n#[export] Hint Unfold Either_map : core.\n#[export] Hint Unfold Tuple.first : core.\n#[export] Hint Unfold id : core.\n\nDefinition RWSE r w s e `{Monoid w} := RWSET r w s e Identity.\n\nDefinition RWSEP r w s e `{Monoid w} := RWSET r w s e (Cont Prop).\n\nModule RWSETLaws.\n\nModule Import EL := EitherLaws.\nInclude MonadLaws.\n\nLemma first_id a z : first (a:=a) (b:=a) (z:=z) id = id.\nProof.\n  unfold first.\n  extensionality x.\n  now destruct x.\nQed.\n\nLemma first_comp `(f : b → c) `(g : a → b) z x :\n  first f (first g x) = first (z:=z) (f \\o g) x.\nProof.\n  unfold first.\n  now destruct x.\nQed.\n\nSection RWSETLaws.\n\nContext {r w s e : Type}.\nContext `{MonoidLaws w}.\nContext `{MonadLaws m}.\n\n#[global]\nProgram Instance RWSET_FunctorLaws :\n  FunctorLaws (RWSET r w s e m).\nNext Obligation.\n  extensionality x.\n  rwse.\n  rewrite first_id.\n  rewrite (fmap_id (FunctorLaws:=Either_FunctorLaws (e:=e))).\n  now rewrite fmap_id.\nQed.\nNext Obligation.\n  extensionality x.\n  rwse; simpl.\n  rewrite fmap_comp_x.\n  pose proof (fmap_comp (FunctorLaws:=Either_FunctorLaws (e:=e))).\n  simpl in H3.\n  unfold comp in H3.\n  rewrite H3.\n  repeat f_equal.\n  extensionality x0.\n  now apply first_comp.\nQed.\n\n#[global]\nProgram Instance RWSET_ApplicativeLaws :\n  ApplicativeLaws (RWSET r w s e m).\nNext Obligation.\n  extensionality x.\n  rwse.\n  unfold RWSET_ap.\n  unfold bind, comp; simpl.\n  rewrite fmap_pure_x.\n  rewrite join_pure_x.\n  rewrite fmap_comp_x.\n  rewrite first_id; simpl.\n  rewrite (fmap_id (FunctorLaws:=Either_FunctorLaws (e:=e))).\n  unfold id.\n  rewrite <- fmap_comp_x.\n  rewrite join_fmap_pure_x.\n  rewrite <- fmap_id_x.\n  f_equal.\n  extensionality y.\n  destruct y; auto.\n  destruct p; auto.\n  destruct p; auto.\n  now rewrite mempty_left.\nQed.\nNext Obligation.\nAdmitted.\nNext Obligation.\nAdmitted.\nNext Obligation.\nAdmitted.\nNext Obligation.\nAdmitted.\n\n#[global]\nProgram Instance RWSET_MonadLaws :\n  MonadLaws (RWSET r w s e m) := {|\n    has_applicative_laws := RWSET_ApplicativeLaws\n|}.\nNext Obligation.\n  unfold comp.\n  extensionality x.\nAdmitted.\nNext Obligation.\nAdmitted.\nNext Obligation.\nAdmitted.\nNext Obligation.\nAdmitted.\n\nNotation \"a >>[ H ] b\" :=\n  (bind (H:=H) (fun _ => b) a) (at level 90, right associativity) : monad_scope.\n\nLemma put_getM `(x : s) :\n  (put x >> get (r:=r) (e:=e)) =\n  (put x >> pure x).\nProof.\n  simpl.\n  rwse.\n  unfold put, RWSET_join, bind, comp.\n  now rewrite !fmap_comp_x, !fmap_pure_x.\nQed.\n\nEnd RWSETLaws.\n\nEnd RWSETLaws.\n\n\nRequire Import Coq.Arith.Arith.\n\n#[export] Program Instance Unit_Semigroup : Semigroup unit.\n#[export] Program Instance Unit_Monoid : Monoid unit.\nNext Obligation. exact tt. Defined.\n\nDefinition sample {m : Type → Type} `{Monad m} :\n  RWSET nat unit nat nat m nat :=\n  x <- get ;\n  put (x + 1) ;;\n  if x <? 20\n  then throw 100\n  else pure 50.\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/old/RWSET.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.28202905858999583}}
{"text": "(*\n * This is not in the Coq library, as far as I can tell.\n *\n * Some of this (without the typeclassery) was taken from\n * https://pdp7.org/blog/2011/01/the-maybe-monad-in-coq/\n *)\n\nClass Monad (M : Type -> Type): Type := {\n   ret {a : Type}: a -> M a;\n   bind {a b : Type}: M a -> (a -> M b) -> M b;\n\n   left_id: forall (a b : Type), forall (x : a) (f : a -> M b),\n      bind (ret x) f = f x;\n   right_id {a: Type}: forall (m : M a),\n      bind m (fun (x : a) => ret x) = m;\n   assoc {a b c: Type}: forall (m : M a) (n: a -> M b) (o : b -> M c),\n      bind (bind m n) o = bind m (fun x => bind (n x) o);\n}.\n \nNotation \"M >>= N\" := (bind M N)\n\t(at level 42, left associativity).\n\nNotation \"'do' X <- M ; N\" := (bind M (fun X => N))\n\t(at level 200, X ident, M at level 100, N at level 200).\n\nNotation \"'do' M ; N\" := (bind M (fun _ => N))\n\t(at level 200, M at level 100, N at level 200).\n\nInstance option_is_monad: Monad option := {\n   (* It isn't clear to me why the implicit args need to be explicit. *)\n   ret a x := Some x;\n   bind a b ma fmb := match ma with\n   | Some x => fmb x\n   | None => None\n   end;\n}.\nProof.\n   - intros. auto.\n   - intros. destruct m; auto.\n   - intros. destruct m; 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/vfs/monad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.2820290505130333}}
{"text": "Require Import Fiat.QueryStructure.Automation.MasterPlan.\nRequire Import Bedrock.Memory.\nDefinition boolToWord (b : bool) : W :=\n  if b then Word.natToWord _ 1 else Word.natToWord _ 0.\n\nInstance : Query_eq (Word.word n) :=\n  { A_eq_dec := @Word.weq n }.\nOpaque Word.weq.\nOpaque Word.natToWord.\n(* Our bookstore has two relations (tables):\n   - The [Books] relation contains the books in the\n     inventory, represented as a tuple with\n     [Author], [Title], and [ISBN] attributes.\n     The [ISBN] attribute is a key for the relation,\n     specified by the [where attributes .. depend on ..]\n     constraint.\n   - The [Orders] relation contains the orders that\n     have been placed, represented as a tuple with the\n     [ISBN] and [Date] attributes.\n\n   The schema for the entire query structure specifies that\n   the [ISBN] attribute of [Orders] is a foreign key into\n   [Books], specified by the [attribute .. of .. references ..]\n   constraint.\n *)\n\n(* Let's define some synonyms for strings we'll need,\n * to save on type-checking time. *)\nDefinition sBOOKS := \"Books\".\nDefinition sAUTHOR := \"Authors\".\nDefinition sTITLE := \"Title\".\nDefinition sISBN := \"ISBN\".\nDefinition sORDERS := \"Orders\".\nDefinition sDATE := \"Date\".\n\n(* Now here's the actual schema, in the usual sense. *)\nDefinition BookStoreSchema :=\n  Query Structure Schema\n    [ relation sBOOKS has\n              schema <sAUTHOR :: W,\n                      sTITLE :: W,\n                      sISBN :: W>\n                      where UniqueAttribute ``sISBN;\n      relation sORDERS has\n              schema <sISBN :: W,\n                      sDATE :: W> ]\n    enforcing [attribute sISBN for sORDERS references sBOOKS].\n\n(* Aliases for the tuples contained in Books and Orders, respectively. *)\nDefinition Book := TupleDef BookStoreSchema sBOOKS.\nDefinition Order := TupleDef BookStoreSchema sORDERS.\n\n(* Our bookstore has two mutators:\n   - [PlaceOrder] : Place an order into the 'Orders' table\n   - [AddBook] : Add a book to the inventory\n\n   Our bookstore has two observers:\n   - [GetTitles] : The titles of books written by a given author\n   - [NumOrders] : The number of orders for a given author\n *)\n\n(* Now we write what the methods should actually do. *)\n\nDefinition BookStoreSpec : ADT _ :=\n  Def ADT {\n    rep := QueryStructure BookStoreSchema,\n\n    Def Constructor0 \"Init\" : rep := empty,,\n\n    Def Method1 \"PlaceOrder\" ( r : rep) (o : Order) : rep * bool :=\n        Insert o into r!sORDERS,\n\n    Def Method1 \"AddBook\" (r : rep) (b : Book) : rep * bool :=\n        Insert b into r!sBOOKS ,\n\n    Def Method1 \"GetTitles\" (r : rep) (author : W) : rep * list W :=\n        titles <- For (b in r ! sBOOKS)\n               Where (author = b!sAUTHOR)\n               Return (b!sTITLE);\n    ret (r, titles),\n\n    Def Method1 \"NumOrders\" (r : rep) (author : W ) : rep * W :=\n      count <- Count (For (o in r!sORDERS) (b in r!sBOOKS)\n                              Where (author = b!sAUTHOR)\n                              Where (o!sISBN = b!sISBN)\n                              Return ());\n      ret (r, Word.natToWord 32 count)\n}%methDefParsing.\n\nTheorem SharpenedBookStore :\n  MostlySharpened BookStoreSpec.\nProof.\n\n  start sharpening ADT.\n  simpl; pose_string_hyps; pose_heading_hyps.\n  start_honing_QueryStructure'.\n  hone method \"AddBook\".\n  { setoid_rewrite UniqueAttribute_symmetry.\n    setoid_rewrite (@refine_uniqueness_check_into_query' BookStoreSchema Fin.F1 _ _ _ _).\n    setoid_rewrite refine_For_rev.\n    setoid_rewrite refine_Count.\n    simplify with monad laws; simpl in *; subst.\n    setoid_rewrite refine_pick_eq'.\n    setoid_rewrite refine_bind_unit.\n    setoid_rewrite refine_If_Then_Else_Duplicate.\n    finish honing. }\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  + 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  + setoid_rewrite refine_For_rev; simplify with monad laws.\n    plan EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n         EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep.\n  + hone method \"PlaceOrder\".\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 \"AddBook\".\n    { simpl in *; subst; simplify with monad laws.\n      setoid_rewrite app_nil_r;\n        setoid_rewrite map_map; simpl.\n      unfold ilist2_hd at 1; simpl.\n      repeat 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; eapply refine_under_bind; intros; set_evars.\n      rewrite (CallBagFind_fst H0); simpl.\n      finish honing.\n    }\n    hone method \"GetTitles\".\n    { simpl in *; subst; simplify with monad laws.\n      setoid_rewrite refine_pick_eq'; simplify with monad laws.\n      simpl.\n      unfold H1; eapply refine_under_bind; intros; set_evars.\n      rewrite app_nil_r, map_map; unfold ilist2_hd; simpl.\n      rewrite (CallBagFind_fst H0); simpl.\n      finish honing.\n    }\n    hone method \"NumOrders\".\n    { simpl in *; subst.\n      setoid_rewrite refine_Count; simplify with monad laws.\n      setoid_rewrite refine_pick_eq'; simplify with monad laws.\n      simpl.\n      unfold H1; eapply refine_under_bind; intros; set_evars.\n      setoid_rewrite app_nil_r.\n      rewrite (CallBagEnumerate_fst H0); simpl.\n      etransitivity.\n      eapply refine_under_bind_both.\n      refine (@Join_Comp_Lists_eq BookStoreSchema Index Fin.F1 _ _ _ _ _).\n      intros; finish honing.\n      simplify with monad laws.\n      unfold H2; apply refine_under_bind.\n      intros.\n      apply Join_Comp_Lists_eq' in H3; rewrite H3.\n      finish honing.\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\n    Time Defined.\n\nTime Definition BookstoreImpl :=\n  Eval simpl in (fst (projT1 SharpenedBookStore)).\n\nPrint BookstoreImpl.\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/BookstoreFacade.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.28198140478174094}}
{"text": "(* Full safety for DOT *)\n\n(* copied from dot22.v *)\n(* based on that, it removes the 2nd level of pushback,\n   and performs the necessary translation while going\n   from stp to stp2 *)\n(* copied from dot24.v *)\n(* based on that, it adds internal support for \n   non-variable path expressions *)\n\nRequire Export SfLib.\n\nRequire Export Arith.EqNat.\nRequire Export Arith.Le.\nRequire Import Coq.Program.Equality.\n\nModule FSUB.\n\nDefinition id := nat.\n\nInductive var : Type :=\n  | varF   : tm -> var (* was: id -> var *)\n  | varH   : id -> var\n  | varB   : id -> var\n\nwith ty : Type :=\n  | TBool  : ty\n  | TBot   : ty\n  | TTop   : ty\n  | TMem   : id -> ty -> ty -> ty\n  | TSel   : var -> id -> ty\n  | TAll   : id -> ty -> ty -> ty\n  | TBind  : ty -> ty\n  | TAnd   : ty -> ty -> ty\n  | TOr    : ty -> ty -> ty\n\nwith tm : Type :=\n  | ttrue  : tm\n  | tfalse : tm\n  | tvar   : id -> tm\n  | tapp   : tm -> id -> tm -> tm (* \\o.m(x) *)\n  | tobj   : id -> list (id * def) -> tm (* \\o {d} *)\n  | tlet   : id -> tm -> tm -> tm (* let \\x = t1 in t2 *)\n with def : Type :=\n  | dfun   : id -> tm -> def\n  | dmem   : ty -> def                              \n.\n\nInductive vl : Type :=\n| vbool : bool -> vl\n| vobj  : list (id*vl) -> id -> list (id * def) -> 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 tail {X : Type} (n : id) (l : list (id * X)) : list (id * X) :=\n  match l with\n    | [] => []\n    | (n',a) :: l'  => (* DeBrujin *)\n      if (beq_nat n (fresh l)) then l else tail n l' (* XXX use < ? *)\n  end.\n\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\nFixpoint tailr {X : Type} (n : id) (l : list (id * X)) : list (id * X) :=\n  match l with\n    | [] => []\n    | (n',a) :: l'  => (* DeBrujin *)\n      if (beq_nat n (length l)) then l else tailr n l'\n  end.\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_mem: forall k l m T1 T2,\n    closed_rec k l T1 ->\n    closed_rec k l T2 ->\n    closed_rec k l (TMem m T1 T2)\n| cl_all: forall k l m T1 T2,\n    closed_rec k l T1 ->\n    closed_rec (S k) l T2 ->\n    closed_rec k l (TAll m 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 m,\n    closed_rec k l (TSel (varF x) m)\n| cl_and: forall k l T1 T2,\n    closed_rec k l T1 ->\n    closed_rec k l T2 ->\n    closed_rec k l (TAnd T1 T2)\n| cl_or: forall k l T1 T2,\n    closed_rec k l T1 ->\n    closed_rec k l T2 ->\n    closed_rec k l (TOr T1 T2)\n| cl_selh: forall k l x m,\n    l > x ->\n    closed_rec k l (TSel (varH x) m)\n| cl_selb: forall k l i m,\n    k > i ->\n    closed_rec k l (TSel (varB i) m)\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: var) (T: ty) { struct T }: ty :=\n  match T with\n    | TSel (varF x) m => TSel (varF x) m (* free var remains free. functional, so we can't check for conflict *)\n    | TSel (varH i) m => TSel (varH i) m\n    | TSel (varB i) m => TSel (if beq_nat k i then u else varB i) m\n    | TAll m T1 T2  => TAll m (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 m T1 T2  => TMem m (open_rec k u T1) (open_rec k u T2)\n    | TAnd T1 T2  => TAnd (open_rec k u T1) (open_rec k u T2)\n    | TOr  T1 T2  => TOr  (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 (varF (tvar 9)) (TAll 0 TBool (TAll 0 (TSel (varB 1) 0) (TSel (varB 1) 0))) =\n                      (TAll 0 TBool (TAll 0 (TSel (varF (tvar 9)) 0) (TSel (varB 1) 0))).\nProof. compute. eauto. Qed.\n\n\nFixpoint subst (U : var) (T : ty) {struct T} : ty :=\n  match T with\n    | TTop         => TTop\n    | TBot         => TBot\n    | TBool        => TBool\n    | TMem m T1 T2   => TMem m (subst U T1) (subst U T2)\n    | TSel (varB i) m => TSel (varB i) m\n    | TSel (varF i) m => TSel (varF i) m\n    | TSel (varH i) m => TSel (if beq_nat i 0 then U else varH (i-1)) m\n    | TAll m T1 T2   => TAll m (subst U T1) (subst U T2)\n    | TBind T2     => TBind (subst U T2)\n    | TAnd T1 T2   => TAnd (subst U T1) (subst U T2)\n    | TOr  T1 T2   => TOr  (subst U T1) (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 m T1 T2   => nosubst T1 /\\ nosubst T2\n    | TSel (varB i) m => True\n    | TSel (varF i) m => True\n    | TSel (varH i) m => i <> 0\n    | TAll m T1 T2   => nosubst T1 /\\ nosubst T2\n    | TBind T2     => nosubst T2\n    | TAnd T1 T2   => nosubst T1 /\\ nosubst T2\n    | TOr  T1 T2   => nosubst T1 /\\ nosubst T2\n  end.\n\n\nHint Unfold open.\nHint Unfold closed.\n\n(* TODO: var *)\n(* QUESTION: include trans rule or not? sela1 rules use restricted GL now, so trans seems useful *)\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_mem: forall G1 GH m T1 T2 T3 T4,\n    stp G1 GH T3 T1 ->\n    stp G1 GH T2 T4 ->\n    stp G1 GH (TMem m T1 T2) (TMem m T3 T4)\n| stp_sel1: forall G1 GH TX m T2 x,\n    index x G1 = Some TX ->\n    closed 0 0 TX ->\n    stp G1 [] TX (TMem m TBot T2) ->\n    stp G1 GH T2 T2 -> (* regularity of stp2 *)\n    stp G1 GH (TSel (varF (tvar x)) m) T2\n| stp_sel2: forall G1 GH TX m T1 x,\n    index x G1 = Some TX ->\n    closed 0 0 TX ->\n    stp G1 [] TX (TMem m T1 TTop) ->\n    stp G1 GH T1 T1 -> (* regularity of stp2 *)\n    stp G1 GH T1 (TSel (varF (tvar x)) m)\n| stp_selb1: forall G1 GH TX m T2 x,\n    index x G1 = Some TX ->\n    stp G1 [] TX (TBind (TMem m TBot T2)) ->   (* Note GH = [] *)\n    stp G1 GH (open (varF (tvar x)) T2) (open (varF (tvar x)) T2) -> (* regularity *)\n    stp G1 GH (TSel (varF (tvar x)) m) (open (varF (tvar x)) T2)\n| stp_selb2: forall G1 GH TX m T1 x,\n    index x G1 = Some TX ->\n    stp G1 [] TX (TBind (TMem m T1 TTop)) ->   (* Note GH = [] *)\n    stp G1 GH (open (varF (tvar x)) T1) (open (varF (tvar x)) T1) -> (* regularity *)\n    stp G1 GH (open (varF (tvar x)) T1) (TSel (varF (tvar x)) m)\n| stp_selx: forall G1 GH TX x m,\n    index x G1 = Some TX ->\n    stp G1 GH (TSel (varF (tvar x)) m) (TSel (varF (tvar x)) m)\n| stp_sela1: forall G1 GH GL TX m T2 x,\n    tailr (S x) GH = (0,TX)::GL ->\n    stp G1 ((0,TX)::GL) TX (TMem m TBot T2) ->\n    stp G1 GH T2 T2 -> (* regularity *)\n    stp G1 GH (TSel (varH x) m) T2\n| stp_sela2: forall G1 GH GL TX m T1 x,\n    tailr (S x) GH = (0,TX)::GL ->\n    stp G1 ((0,TX)::GL) TX (TMem m T1 TTop) ->   (* not using self name for now *)\n    stp G1 GH T1 T1 -> (* regularity of stp2 *)\n    stp G1 GH T1 (TSel (varH x) m)\n| stp_selab1: forall G1 GH GL TX m T2 T2' x,\n    tailr (S x) GH = (0,TX)::GL ->\n    closed 0 x (TBind (TMem m TBot T2)) ->\n    stp G1 ((0,TX)::GL) TX (TBind (TMem m TBot T2)) ->\n    T2' = (open (varH x) T2) ->\n    stp G1 GH T2' T2' -> (* regularity *)\n    stp G1 GH (TSel (varH x) m) T2'\n| stp_selab2: forall G1 GH GL TX m T1 T1' x,\n    tailr (S x) GH = (0,TX)::GL ->\n    closed 0 x (TBind (TMem m T1 TTop)) ->\n    stp G1 ((0,TX)::GL) TX (TBind (TMem m T1 TTop)) ->\n    T1' = (open (varH x) T1) ->\n    stp G1 GH T1' T1' -> (* regularity *)\n    stp G1 GH T1' (TSel (varH x) m)\n| stp_selax: forall G1 GH TX x m,\n    indexr x GH = Some TX  ->\n    stp G1 GH (TSel (varH x) m) (TSel (varH x) m)\n| stp_all: forall G1 GH m 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 (varH x) T2) (open (varH x) T2) -> (* regularity *)\n    stp G1 ((0,T3)::GH) (open (varH x) T2) (open (varH x) T4) ->\n    stp G1 GH (TAll m T1 T2) (TAll m 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 (varH x) T2)::GH) (open (varH x) T2) (open (varH x) T2) -> (* regularity *)\n    stp G1 ((0,open (varH x) T1)::GH) (open (varH x) T1) (open (varH x) T2) ->\n    stp G1 GH (TBind T1) (TBind T2)\n| stp_bind1: forall G1 GH T1 T2 x,\n    x = length GH ->\n    closed 1 (length GH) T1 -> (* must not accidentally bind x *)\n    closed 0 (length GH) T2 ->\n    stp G1 GH T2 T2 ->\n    stp G1 ((0,open (varH x) T1)::GH) (open (varH x) T1) T2 ->\n    stp G1 GH (TBind T1) T2\n| stp_and11: forall G GH T1 T2 T,\n    stp G GH T1 T ->\n    stp G GH T2 T2 -> (* regularity *)\n    stp G GH (TAnd T1 T2) T\n| stp_and12: forall G GH T1 T2 T,\n    stp G GH T2 T ->\n    stp G GH T1 T1 -> (* regularity *)\n    stp G GH (TAnd T1 T2) T\n| stp_and2: forall G GH T1 T2 T,\n    stp G GH T T1 ->\n    stp G GH T T2 ->\n    stp G GH T (TAnd T1 T2)\n| stp_or21: forall G GH T1 T2 T,\n    stp G GH T T1 ->\n    stp G GH T2 T2 -> (* regularity *)\n    stp G GH T (TOr T1 T2)\n| stp_or22: forall G GH T1 T2 T,\n    stp G GH T T2 ->\n    stp G GH T1 T1 -> (* regularity *)\n    stp G GH T (TOr T1 T2)\n| stp_or1: forall G GH T1 T2 T,\n    stp G GH T1 T ->\n    stp G GH T2 T ->\n    stp G GH (TOr T1 T2) T\n.\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\nFunction tand (t1: ty) (t2: ty) :=\n  match t2 with\n    | TTop => t1\n    | _ => TAnd t1 t2\n  end.\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           stp env [] T1 T1 ->\n           has_type env (tvar x) T1\n| t_var_pack: forall x env T1,\n           has_type env (tvar x) (open (varF (tvar x)) T1) ->\n           stp env [] (TBind T1) (TBind 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           stp env [] (open (varF (tvar x)) T1) (open (varF (tvar x)) T1) ->\n           has_type env (tvar x) (open (varF (tvar x)) T1)\n| t_obj: forall env f ds T TX,\n           fresh env = f ->\n           open (varF (tvar f)) T = TX ->\n           dcs_has_type ((f, TX)::env) f ds T ->\n           stp ((f, TX)::env) [] TX TX ->\n           stp env [] (TBind T) (TBind T) ->\n           has_type env (tobj f ds) (TBind T)\n| t_app: forall env f l x T1 T2,\n           has_type env f (TAll l T1 T2) ->\n           has_type env x T1 ->\n           stp env [] T2 T2 ->\n           has_type env (tapp f l x) T2\n| t_app_var: forall env f l x T1 T2 T2X,\n           has_type env f (TAll l T1 T2) ->\n           has_type env (tvar x) T1 ->\n           open (varF (tvar x)) T2 = T2X ->\n           stp env [] T2X T2X ->\n           has_type env (tapp f l (tvar x)) T2X\n| t_let: forall env x ex e Tx T,\n           has_type env ex Tx ->\n           fresh env <= x ->\n           has_type ((x, Tx)::env) e T ->\n           stp env [] T T ->\n           has_type env (tlet x ex e) T\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\nwith dcs_has_type: tenv -> id -> list (id * def) -> ty -> Prop :=\n| dt_nil: forall env f,\n            dcs_has_type env f nil TTop\n| dt_fun: forall env f x y m T1 T2 dcs TS T,\n            has_type ((x,open (varF (tvar f)) T1)::env) y (open (varF (tvar x)) (open_rec 1 (varF (tvar f)) T2)) ->\n            dcs_has_type env f dcs TS ->\n            fresh env = x ->\n            m = length dcs ->\n            T = tand (TAll m T1 T2) TS ->\n            dcs_has_type env f ((m, dfun x y)::dcs) T\n| dt_mem: forall env f m T1 dcs TS T,\n            dcs_has_type env f dcs TS ->\n            m = length dcs ->\n            T = tand (TMem m T1 T1) TS ->\n            dcs_has_type env f ((m, dmem T1)::dcs) T\n.\n\n\n\n\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        | tobj f ds => Some (Some (vobj env f ds)) (* TODO: take subenv < f, also in has_type *)\n        | tapp ef m 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 (vobj env2 f ds)) =>\n                  match index m ds with\n                    | None => Some None\n                    | Some (dmem _) => Some None\n                    | Some (dfun x ey) =>\n                      teval n ((x,vx)::(f,vobj env2 f ds)::env2) ey\n                  end\n              end\n          end\n        | tlet x ex ey =>\n          match teval n env ex with\n            | None => None\n            | Some None => Some None\n            | Some (Some vx) => teval n ((x,vx)::env) ey\n          end\n      end\n  end.\n\n\n(* In dynamic subtyping, we generalize type selections from\n   x.T to t.T, i.e. from concrete variables x to t, where t \n   is any term that evaluates in the given G. \n\n   index x G = Some v becomes peval (tvar x) G v\n\n   The proofs require that G can be extended to G' without changing\n   the result of evaluation v. But if v is an object, the captured\n   environment will be G' instead of G. Therefore, we evaluate t \n   in a environment just large enough (tail (fresh_in_term t) G),\n   which is a sub environment of both G and G'.\n\n   Note that so far, this additional flexibility is not \n   exposed to the static type assignment / subtyping relations.\n\n   On the static side, it should be possible to use any reduction / \n   normalization relation or procedure that is consistent with teval.\n\n   For example:\n   - syntactic restriction to paths / field selections\n   - normalization of arbitrary terms if calculus is total\n     (see e.g. nano0-total.v)\n   - semantic restriction to total terms based on effect system\n   - arbitrary terms if we don't care if typing is decidable\n*)\n   \nFixpoint fresh_in_term (t:tm): nat :=\n  match t with\n    | ttrue => 0\n    | tfalse => 0\n    | tvar n => 1 + n\n    | tapp f l x => max (fresh_in_term f) (fresh_in_term x)\n    | tobj n ds => n\n    | tlet n x y => n\n  end.\n\nDefinition peval (t:tm) (G:venv) r :=\n  fresh_in_term t <= fresh G /\\\n  exists nm, forall n, n > nm ->\n    teval n (tail (fresh_in_term t) G) t = Some (Some r).\n\n\n\n\nDefinition MAX := 1.\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_mem: forall G1 G2 l 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 l T1 T2) G2 (TMem l T3 T4) GH (S (n1+n2))\n\n| stp2_mem2: forall m G1 G2 l 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 l T1 T2) G2 (TMem l T3 T4) GH (S (n1+n2))\n\n\n(* strong version, with precise/invertible bounds *)\n| stp2_strong_sel1: forall G1 G2 GX l f ds TX x T2 GH GX' TX' n1 n2,\n    peval x G1 (vobj GX f ds) ->\n    val_type GX' (vobj GX f ds) TX' 1 -> (* for downgrade *)\n    stp2 0 false GX' TX' G2 (TMem l TBot T2) GH n2 -> (* for downgrade *)\n    index l ds = Some (dmem TX) ->\n    closed 1 0 TX ->\n    stp2 0 true ((f, vobj GX f ds)::GX) (open (varF (tvar f)) TX) G2 T2 GH n1 ->\n    stp2 0 true G1 (TSel (varF x) l) G2 T2 GH (S (n1+n2))\n\n| stp2_strong_sel2: forall G1 G2 GX l f ds TX x T1 GH GX' TX' n1 n2,\n    peval x G2 (vobj GX f ds) ->\n    val_type GX' (vobj GX f ds) TX' 1 -> (* for downgrade *)\n    stp2 0 false GX' TX' G1 (TMem l T1 TTop) GH n2 -> (* for downgrade *)\n    index l ds = Some (dmem TX) ->\n    closed 1 0 TX ->\n    stp2 0 false G1 T1 ((f, vobj GX f ds)::GX) (open (varF (tvar f)) TX) GH n1 ->\n    stp2 0 true G1 T1 G2 (TSel (varF x) l) GH (S (n1+n2))\n\n| stp2_strong_selx: forall G1 G2 l v x1 x2 GH n1,\n    peval x1 G1 v ->\n    peval x2 G2 v ->\n    stp2 0 true G1 (TSel (varF x1) l) G2 (TSel (varF x2) l) GH n1\n\n\n(* existing object, but imprecise type *)\n| stp2_sel1: forall m G1 G2 GX l TX x T2 GH n1 n2 v,\n    peval x G1 v ->\n    val_type GX v TX 1 ->\n    closed 0 0 TX ->\n    stp2 (S m) false GX TX G2 (TMem l TBot T2) GH n1 ->\n    stp2 (S m) true G2 T2 G2 T2 GH n2 -> (* regularity *)\n    stp2 (S m) true G1 (TSel (varF x) l) G2 T2 GH (S (n1+n2))\n\n(*         \n| stp2_selb1: forall m G1 G2 GX l TX x x' T2 GH n1 n2 v nv,\n    index x G1 = Some v -> (index x' G2 = Some v \\/ closed 0 0 T2) ->\n    val_type GX v TX nv ->\n    closed 0 0 TX ->\n    stp2 (S ( m)) false GX TX G2 (TBind (TMem l TBot T2)) [] n1 -> (* Note GH = [] *)\n    stp2 (S ( m)) true G2 (open (varF x') T2) G2 (open (varF x') T2) GH n2 -> (* regularity *)\n    stp2 (S ( m)) true G1 (TSel (varF x) l) G2 (open (varF x') T2) GH (S (n1+n2))\n*)\n\n| stp2_sel2: forall m G1 G2 GX l TX x T1 GH n1 n2 v,\n    peval x G2 v -> \n    val_type GX v TX 1 ->\n    closed 0 0 TX ->\n    stp2 (S m) false GX TX G1 (TMem l 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 (varF x) l) GH (S (n1+n2))\n\n(*         \n| stp2_selb2: forall m G1 G2 GX l TX x x' T1 GH n1 n2 v nv,\n    index x G2 = Some v -> (index x' G1 = Some v \\/ closed 0 0 T1) ->\n    val_type GX v TX nv ->\n    closed 0 0 TX ->\n    stp2 (S ( m)) false GX TX G1 (TBind (TMem l T1 TTop)) [] n1 -> (* Note GH = [] *)\n    stp2 (S ( m)) true G1 (open (varF x') T1) G1 (open (varF x') T1) GH n2 -> (* regularity *)\n    stp2 (S ( m)) true G1 (open (varF x') T1) G2 (TSel (varF x) l) GH (S (n1+n2))\n *)\n         \n| stp2_selx: forall m G1 G2 l v x1 x2 GH n1,\n    peval x1 G1 v -> \n    peval x2 G2 v ->\n    stp2 (S m) true G1 (TSel (varF x1) l) G2 (TSel (varF x2) l) GH (S n1)\n\n(* hypothetical object *)\n(*| stp2_sela1: forall m G1 G2 GX l TX x T2 GH n1 n2,\n    indexr x GH = Some (GX, TX) ->\n    closed 0 (S x) TX ->\n    stp2 (S m) false GX TX G2 (TMem l TBot T2) GH n1 ->\n    stp2 (S m) true G2 T2 G2 T2 GH n2 -> (* regularity *)\n    stp2 (S m) true G1 (TSel (varH x) l) G2 T2 GH (S (n1+n2))\n *)\n         \n| stp2_sela1: forall m G1 G2 GX l TX x T2 GH GU GL n1 n2,\n    indexr x GH = Some (GX, TX) ->\n    closed 0 (S x) TX ->\n    length GL = (S x) ->\n    GH = GU ++ GL ->\n    stp2 (S m) false GX TX G2 (TMem l TBot T2) GL n1 ->\n    stp2 (S m) true G2 T2 G2 T2 GH n2 -> (* regularity *)\n    stp2 (S m) true G1 (TSel (varH x) l) G2 T2 GH (S (n1+n2))\n\n| stp2_sela2: forall m G1 G2 GX l TX x T1 GH GU GL n1 n2,\n    indexr x GH = Some (GX, TX) ->\n    closed 0 (S x) TX ->\n    length GL = (S x) ->\n    GH = GU ++ GL ->\n    stp2 (S m) false GX TX G1 (TMem l T1 TTop) GL n1 ->\n    stp2 (S m) true G1 T1 G1 T1 GH n2 -> (* regularity *)\n    stp2 (S m) true G1 T1 G2 (TSel (varH x) l) GH (S (n1+n2))\n\n| stp2_selab1: forall m G1 G2 GX l TX x T2 T2' GH GU GL n1 n2,\n    indexr x GH = Some (GX, TX) ->\n    closed 1 x T2 -> (* < x required in substitute *)\n    length GL = (S x) ->\n    GH = GU ++ GL ->\n    stp2 (S m) false GX TX G2 (TBind (TMem l TBot T2)) GL n1 ->\n    T2' = (open (varH x) T2) ->\n    stp2 (S m) true G2 T2' G2 T2' GH n2 -> (* regularity *)\n    stp2 (S m) true G1 (TSel (varH x) l) G2 T2' GH (S (n1+n2))\n\n| stp2_selab2: forall m G1 G2 GX l TX x T1 T1' GH GU GL n1 n2,\n    indexr x GH = Some (GX, TX) ->\n    closed 1 x T1 -> (* < x required in substitute *)\n    length GL = (S x) ->\n    GH = GU ++ GL ->\n    stp2 (S m) false GX TX G1 (TBind (TMem l T1 TTop)) GL n1 ->\n    T1' = (open (varH x) T1) ->\n    stp2 (S m) true G1 T1' G1 T1' GH n2 -> (* regularity *)\n    stp2 (S m) true G1 T1' G2 (TSel (varH x) l) GH (S (n1+n2))\n\n\n\n| stp2_selax: forall m G1 G2 GX l TX x GH n1,\n    indexr x GH = Some (GX, TX) ->\n    stp2 (S m) true G1 (TSel (varH x) l) G2 (TSel (varH x) l) GH (S n1)\n\n\n| stp2_all: forall m G1 G2 l T1 T2 T3 T4 GH n1 n1' n2,\n    stp2 1 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 1 false G1 (open (varH (length GH)) T2) G1 (open (varH (length GH)) T2) ((0,(G1, T1))::GH) n1' -> (* regularity *)\n    stp2 1 false G1 (open (varH (length GH)) T2) G2 (open (varH (length GH)) T4) ((0,(G2, T3))::GH) n2 ->\n    stp2 m true G1 (TAll l T1 T2) G2 (TAll l T3 T4) GH (S (n1+n1'+n2))\n\n| stp2_bind: 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 1 false G2 (open (varH (length GH)) T2) G2 (open (varH (length GH)) T2) ((0,(G2, open (varH (length GH)) T2))::GH) n2 -> (* regularity *)\n    stp2 1 false G1 (open (varH (length GH)) T1) G2 (open (varH (length GH)) T2) ((0,(G1, open (varH (length GH)) T1))::GH) n1 ->\n    stp2 m true G1 (TBind T1) G2 (TBind T2) GH (S (n1+n2))\n\n| stp2_bind1: forall m G1 G2 T1 T2 GH n1 n2,\n    closed 1 (length GH) T1 -> (* must not accidentally bind x *)\n    closed 0 (length GH) T2 ->\n    stp2 m false G2 T2 G2 T2 GH n2 -> (* regularity *)\n    stp2 1 false G1 (open (varH (length GH)) T1) G2 T2 ((0,(G1, open (varH (length GH)) T1))::GH) n1 ->\n    stp2 m true G1 (TBind T1) G2 T2 GH (S (n1+n2))\n\n         \n| stp2_and11: forall m n1 n2 G1 G2 GH T1 T2 T,\n    stp2 m true G1 T1 G2 T GH n1 ->\n    stp2 m true G1 T2 G1 T2 GH n2 -> (* regularity *)\n    stp2 m true G1 (TAnd T1 T2) G2 T GH (S (n1+n2))\n| stp2_and12: forall m n1 n2 G1 G2 GH T1 T2 T,\n    stp2 m true G1 T2 G2 T GH n1 ->\n    stp2 m true G1 T1 G1 T1 GH n2 -> (* regularity *)\n    stp2 m true G1 (TAnd T1 T2) G2 T GH (S (n1+n2))\n| stp2_and2: forall m n1 n2 G1 G2 GH T1 T2 T,\n    stp2 m false G1 T G2 T1 GH n1 ->\n    stp2 m false G1 T G2 T2 GH n2 ->\n    stp2 m true G1 T G2 (TAnd T1 T2) GH (S (n1+n2))\n\n| stp2_or21: forall m n1 n2 G1 G2 GH T1 T2 T,\n    stp2 m false G1 T G2 T1 GH n1 ->\n    stp2 m true G2 T2 G2 T2 GH n2 -> (* regularity *)\n    stp2 m true G1 T G2 (TOr T1 T2) GH (S (n1+n2))\n| stp2_or22: forall m n1 n2 G1 G2 GH T1 T2 T,\n    stp2 m false G1 T G2 T2 GH n1 ->\n    stp2 m true G2 T1 G2 T1 GH n2 -> (* regularity *)\n    stp2 m true G1 T G2 (TOr T1 T2) GH (S (n1+n2))\n| stp2_or1: forall m n1 n2 G1 G2 GH T1 T2 T,\n    stp2 m true G1 T1 G2 T GH n1 ->\n    stp2 m true G1 T2 G2 T GH n2 ->\n    stp2 m true G1 (TOr T1 T2) G2 T GH (S (n1+n2))\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 nv,\n    val_type ((n,v)::vs) v t nv ->\n    wf_env vs ts ->\n    wf_env (cons (n,v) vs) (cons (n,t) ts)\n\nwith val_type : venv -> vl -> ty -> nat -> Prop :=\n| v_bool: forall venv b TE,\n    (exists n, stp2 0 true [] TBool venv TE [] n) ->\n    val_type venv (vbool b) TE 1\n| v_obj: forall env venv tenv f ds T TX TE,\n    wf_env venv tenv ->\n    open (varF (tvar f)) T = TX ->\n    dcs_has_type ((f,TX)::tenv) f ds T ->\n    fresh venv = f ->\n    (exists n, stp2 0 true ((f, vobj venv f ds)::venv) TX env TE [] n)->\n    val_type env (vobj venv f ds) TE 1\n| v_pack: forall venv venv3 x v T T2 T3 n,\n    peval x venv v -> \n    val_type venv v T n ->\n    open (varF x) T2 = T ->\n    (exists n, stp2 0 true venv (TBind T2) venv3 T3 [] n) ->\n    val_type venv3 v T3 (S n)\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 sstpd2 b G1 T1 G2 T2 GH := exists n, stp2 0 b G1 T1 G2 T2 GH n.\n\nDefinition valtpd G v T := exists n, val_type G v T 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: 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_mem: forall G1 G2 GH l 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 l T11 T12) G2 (TMem l T21 T22) GH.\nProof. intros. repeat eu. eauto. unfold stpd2. eexists. eapply stp2_mem2; eauto. Qed.\n\nLemma stpd2_sel1: forall G1 G2 GX l TX x T2 GH v,\n    peval x G1 v -> \n    val_type GX v TX 1 ->\n    closed 0 0 TX ->\n    stpd2 false GX TX G2 (TMem l TBot T2) GH ->\n    stpd2 true G2 T2 G2 T2 GH ->\n    stpd2 true G1 (TSel (varF x) l) G2 T2 GH.\nProof. intros. repeat eu. eexists. eapply stp2_sel1; eauto. Qed.\n\n(*\nLemma stpd2_selb1: forall G1 G2 GX l TX x x' T2 GH v nv,\n    index x G1 = Some v -> (index x' G2 = Some v \\/ closed 0 0 T2) ->\n    val_type GX v TX nv ->\n    closed 0 0 TX ->\n    stpd2 false GX TX G2 (TBind (TMem l TBot T2)) [] -> (* Note GH = [] *)\n    stpd2 true G2 (open (varF x') T2) G2 (open (varF x') T2) GH ->\n    stpd2 true G1 (TSel (varF x) l) G2 (open (varF x') T2) GH.\nProof. intros. repeat eu. eexists. eapply stp2_selb1; eauto. Qed.\n *)\n\nLemma stpd2_sel2: forall G1 G2 GX l TX x T1 GH v,\n    peval x G2 v ->\n    val_type GX v TX 1 ->\n    closed 0 0 TX ->\n    stpd2 false GX TX G1 (TMem l T1 TTop) GH ->\n    stpd2 true G1 T1 G1 T1 GH ->\n    stpd2 true G1 T1 G2 (TSel (varF x) l) GH.\nProof. intros. repeat eu. eexists. eapply stp2_sel2; eauto. Qed.\n\n(*\nLemma stpd2_selb2: forall G1 G2 GX l TX x x' T1 GH v nv,\n    index x G2 = Some v -> (index x' G1 = Some v \\/ closed 0 0 T1) ->\n    val_type GX v TX nv ->\n    closed 0 0 TX ->\n    stpd2 false GX TX G1 (TBind (TMem l T1 TTop)) [] -> (* Note GH = [] *)\n    stpd2 true G1 (open (varF x') T1) G1 (open (varF x') T1) GH ->\n    stpd2 true G1 (open (varF x') T1) G2 (TSel (varF x) l) GH.\nProof. intros. repeat eu. eexists. eapply stp2_selb2; eauto. Qed.\n *)\n\nLemma stpd2_selx: forall G1 G2 l x1 x2 GH v,\n    peval x1 G1 v ->\n    peval x2 G2 v ->\n    stpd2 true G1 (TSel (varF x1) l) G2 (TSel (varF x2) l) GH.\nProof. intros. eauto. exists (S 0). eapply stp2_selx; eauto. Qed.\n\nLemma stpd2_sela1: forall G1 G2 GX l TX x T2 GH GU GL,\n    indexr x GH = Some (GX, TX) ->\n    closed 0 (S x) TX ->\n    length GL = (S x) ->\n    GH = GU ++ GL ->\n    stpd2 false GX TX G2 (TMem l TBot T2) GL ->\n    stpd2 true G2 T2 G2 T2 GH ->\n    stpd2 true G1 (TSel (varH x) l) G2 T2 GH.\nProof. intros. repeat eu. eauto. eexists. eapply stp2_sela1; eauto. Qed.\n\nLemma stpd2_sela2: forall G1 G2 GX l TX x T1 GH GU GL,\n    indexr x GH = Some (GX, TX) ->\n    closed 0 (S x) TX ->\n    length GL = (S x) ->\n    GH = GU ++ GL ->\n    stpd2 false GX TX G1 (TMem l T1 TTop) GL ->\n    stpd2 true G1 T1 G1 T1 GH ->\n    stpd2 true G1 T1 G2 (TSel (varH x) l) GH.\nProof. intros. repeat eu. eauto. eexists. eapply stp2_sela2; eauto. Qed.\n\nLemma stpd2_selab1: forall G1 G2 GX l TX x T2 T2' GH GU GL,\n    indexr x GH = Some (GX, TX) ->\n    closed 1 x T2 ->\n    length GL = (S x) ->\n    GH = GU ++ GL ->\n    stpd2 false GX TX G2 (TBind (TMem l TBot T2)) GL ->\n    T2' = (open (varH x) T2) ->\n    stpd2 true G2 T2' G2 T2' GH ->\n    stpd2 true G1 (TSel (varH x) l) G2 T2' GH.\nProof. intros. repeat eu. eauto. eexists. eapply stp2_selab1; eauto. Qed.\n\nLemma stpd2_selab2: forall G1 G2 GX l TX x T1 T1' GH GU GL,\n    indexr x GH = Some (GX, TX) ->\n    closed 1 x T1 ->\n    length GL = (S x) ->\n    GH = GU ++ GL ->\n    stpd2 false GX TX G1 (TBind (TMem l T1 TTop)) GL ->\n    T1' = (open (varH x) T1) ->\n    stpd2 true G1 T1' G1 T1' GH ->\n    stpd2 true G1 T1' G2 (TSel (varH x) l) GH.\nProof. intros. repeat eu. eauto. eexists. eapply stp2_selab2; eauto. Qed.\n\n\nLemma stpd2_selax: forall G1 G2 GX l TX x GH,\n    indexr x GH = Some (GX, TX) ->\n    stpd2 true G1 (TSel (varH x) l) G2 (TSel (varH x) l) GH.\nProof. intros. exists (S 0). eauto. eapply stp2_selax; eauto. Qed.\n\n\nLemma stpd2_all: forall G1 G2 m 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 (varH (length GH)) T2) G1 (open (varH (length GH)) T2) ((0,(G1, T1))::GH) ->\n    stpd2 false G1 (open (varH (length GH)) T2) G2 (open (varH (length GH)) T4) ((0,(G2, T3))::GH) ->\n    stpd2 true G1 (TAll m T1 T2) G2 (TAll m 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 (varH (length GH)) T2) G2 (open (varH (length GH)) T2) ((0,(G2, open (varH (length GH)) T2))::GH) ->\n    stpd2 false G1 (open (varH (length GH)) T1) G2 (open (varH (length GH)) T2) ((0,(G1, open (varH (length GH)) T1))::GH) ->\n    stpd2 true G1 (TBind T1) G2 (TBind T2) GH.\nProof. intros. repeat eu. eauto. Qed.\n\nLemma stpd2_bind1: forall G1 G2 T1 T2 GH,\n    closed 1 (length GH) T1 -> (* must not accidentally bind x *)\n    closed 0 (length GH) T2 ->\n    stpd2 false G2  T2 G2 T2 GH -> (* regularity *)\n    stpd2 false G1 (open (varH (length GH)) T1) G2 T2 ((0,(G1, open (varH (length GH)) T1))::GH) ->\n    stpd2 true G1 (TBind T1) G2 T2 GH.\nProof. intros. repeat eu. eauto. Qed.\n\n\nLemma stpd2_and11: forall G1 G2 GH T1 T2 T,\n    stpd2 true G1 T1 G2 T GH ->\n    stpd2 true G1 T2 G1 T2 GH ->\n    stpd2 true G1 (TAnd T1 T2) G2 T GH.\nProof. intros. repeat eu. eauto. Qed.\nLemma stpd2_and12: forall G1 G2 GH T1 T2 T,\n    stpd2 true G1 T2 G2 T GH ->\n    stpd2 true G1 T1 G1 T1 GH ->\n    stpd2 true G1 (TAnd T1 T2) G2 T GH.\nProof. intros. repeat eu. eauto. Qed.\nLemma stpd2_and2: forall G1 G2 GH T1 T2 T,\n    stpd2 false G1 T G2 T1 GH ->\n    stpd2 false G1 T G2 T2 GH ->\n    stpd2 true G1 T G2 (TAnd T1 T2) GH.\nProof. intros. repeat eu. eauto. Qed.\n\nLemma stpd2_or21: forall G1 G2 GH T1 T2 T,\n    stpd2 false G1 T G2 T1 GH ->\n    stpd2 true G2 T2 G2 T2 GH ->\n    stpd2 true G1 T G2 (TOr T1 T2) GH.\nProof. intros. repeat eu. eauto. Qed.\nLemma stpd2_or22: forall G1 G2 GH T1 T2 T,\n    stpd2 false G1 T G2 T2 GH ->\n    stpd2 true G2 T1 G2 T1 GH ->\n    stpd2 true G1 T G2 (TOr T1 T2) GH.\nProof. intros. repeat eu. eauto. Qed.\nLemma stpd2_or1: forall G1 G2 GH T1 T2 T,\n    stpd2 true G1 T1 G2 T GH ->\n    stpd2 true G1 T2 G2 T GH ->\n    stpd2 true G1 (TOr T1 T2) G2 T GH.\nProof. intros. repeat eu. 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\nHint Constructors ty.\nHint Constructors tm.\nHint Constructors vl.\n\nHint Constructors closed_rec.\nHint Constructors has_type dcs_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 [(eapply stp_and2; [eapply stp_and11; crush2 | eapply stp_and12; crush2])];\n  try solve [(econstructor; compute; eauto; crush2)];\n  try solve [(eapply t_sub; eapply t_var; compute; eauto; crush2)].\n\nLtac crush_cl :=\n  try solve [(econstructor; compute; eauto; crush_cl)].\n\nLtac crush_wf :=\n  try solve [(eapply stp_topx; crush_wf)];\n  try solve [(eapply stp_botx; crush_wf)];\n  try solve [(eapply stp_bool; crush_wf)];\n  try solve [(eapply stp_selx; compute; eauto; crush_wf)];\n  try solve [(eapply stp_selax; compute; eauto; crush_wf)];\n  try solve [(eapply stp_mem; crush_wf)];\n  try solve [(eapply stp_all; [crush_wf | (compute; eauto) | crush_cl | crush_cl | crush_wf | crush_wf])];\n  try solve [(eapply stp_bindx; [(compute; eauto) | crush_cl | crush_cl | crush_wf | crush_wf])];\n  try solve [(eapply stp_and2; [eapply stp_and11; crush_wf | eapply stp_and12; crush_wf])].\n\n(* define polymorphic identity function *)\n\nDefinition polyId := TAll 0 (TMem 0 TBot TTop) (TAll 0 (TSel (varB 0) 0) (TSel (varB 1) 0)).\n\nExample ex1: has_type [] (tobj 0 [(0, dfun 1 (tobj 2 [(0, (dfun 3 (tvar 3)))]))]) polyId.\nProof.\n  eapply t_sub with (T1:=TBind polyId).\n  apply t_obj with (TX:=polyId). eauto. compute. reflexivity.\n  {\n    eapply dt_fun with (T1:=(TMem 0 TBot TTop)) (T2:=TAll 0 (TSel (varB 0) 0) (TSel (varB 1) 0)).\n    unfold open. simpl. \n    eapply t_sub with (T1:=(TBind (TAll 0 (TSel (varF (tvar 1)) 0) (TSel (varF (tvar 1)) 0)))).\n    eapply t_obj with (TX:=(TAll 0 (TSel (varF (tvar 1)) 0) (TSel (varF (tvar 1)) 0))). eauto. compute. reflexivity.\n    { eapply dt_fun with (T1:=(TSel (varF (tvar 1)) 0)) (T2:=(TSel (varF (tvar 1)) 0)). eapply t_var. compute. reflexivity.\n      crush2. crush2. crush2. crush2. simpl. eauto. }\n    crush_wf. crush_wf. { eapply stp_bind1. eauto. crush2. crush2. crush_wf. compute. crush_wf. }\n  eauto. eauto. eauto. simpl. eauto. }\n  crush_wf. crush_wf.\n  eapply stp_bind1. eauto. crush2. crush2. crush_wf. crush_wf. \nQed.\n\n\n(* instantiate it to bool *)\n\nExample ex2: has_type [(0,polyId)] (tapp (tvar 0) 0 (tobj 1 [(0,dmem TBool)])) (TAll 0 TBool TBool).\nProof.\n  eapply t_app. instantiate (1:= (TMem 0 TBool TBool)).\n    { eapply t_sub.\n      { eapply t_var. simpl. eauto. crush2. }\n      { eapply stp_all; eauto. compute. eapply cl_all; eauto. crush_wf. crush2. }\n    }\n    { eapply t_sub. eapply t_obj. eauto. eauto. eauto. crush_wf. crush_wf. eapply stp_bind1; eauto. crush2. crush2. }\n    crush_wf. \nQed.\n\n\n\n(* define brand / unbrand client function *)\n(* TODO: get rid of bind/let *)\nDefinition brandUnbrand :=\n  TAll 0\n       (TBind (TMem 0 TBot TTop))\n       (TBind (TAll 0\n                    (TBind (TAnd\n                              (TAll 1 TBool (TSel (varB 3) 0))  (* brand *)\n                              (TAll 0 (TSel (varB 2) 0) TBool) (* unbrand *)\n                           )\n                    )\n                    TBool)).\n\nExample ex3:\n  has_type []\n           (tlet 0\n                 (tobj 0 [(0, dfun 1\n                  (tobj 2 [(0, dfun 3\n                  (tapp (tvar 3) 0 (tapp (tvar 3) 1 ttrue)))]))])\n                 (tvar 0))\n           brandUnbrand.\nProof.\n  apply t_let with (Tx:=(TBind brandUnbrand)).\n  apply t_obj with (TX:=brandUnbrand).\n  eauto. compute. reflexivity.\n  eapply dt_fun with (T1:=TBind (TMem 0 TBot TTop))\n                     (T2:=       (TBind (TAll 0\n                    (TBind (TAnd\n                              (TAll 1 TBool (TSel (varB 3) 0))  (* brand *)\n                              (TAll 0 (TSel (varB 2) 0) TBool) (* unbrand *)\n                           )\n                    )\n                    TBool))).\n  unfold open. simpl. eapply t_obj.\n  simpl. reflexivity.\n  unfold open. simpl. reflexivity.\n  eapply dt_fun.\n  instantiate (2:=(TBind (TAnd (TAll 1 TBool (TSel (varF (tvar 1)) 0)) (TAll 0 (TSel (varF (tvar 1)) 0) TBool)))). instantiate (1:=TBool).\n  eapply t_app.\n  instantiate (1:=(TSel (varF (tvar 1)) 0)).\n  assert (open (varF (tvar 3)) (TAll 0 (TSel (varF (tvar 1)) 0) TBool)=TAll 0 (TSel (varF (tvar 1)) 0) TBool) as A. { compute. reflexivity. }\n  unfold open. simpl.\n  rewrite <- A. eapply t_var_unpack.\n  eapply t_sub. eapply t_var. compute. reflexivity.\n  crush2.\n  eapply stp_bindx. simpl. reflexivity. crush2. crush2.\n  unfold open. simpl.\n  crush_wf.\n  unfold open. simpl.\n  eapply stp_and12; crush2.\n  unfold open. simpl. crush2.\n  eapply t_app.\n  instantiate (1:=TBool).\n  assert (open (varF (tvar 3)) (TAll 1 TBool (TSel (varF (tvar 1)) 0))=TAll 1 TBool (TSel (varF (tvar 1)) 0) ) as A. { compute. reflexivity. }\n  rewrite <- A. eapply t_var_unpack.\n  eapply t_sub. eapply t_var. compute. reflexivity.\n  crush_wf. crush2. crush_wf. crush2. crush_wf. crush_wf. crush2. crush2. crush2. crush2.\n  crush2. crush_wf. crush2. crush2. crush2. crush2. crush_wf. crush_wf. crush2.\n  assert (open (varF (tvar 0)) brandUnbrand=brandUnbrand) as A. { compute. reflexivity. }\n  rewrite <- A at 2.\n  eapply t_var_unpack. eapply t_var. simpl. reflexivity.\n  crush_wf. crush_wf. crush_wf.\nQed.\n\nExample ex4:\n  has_type [(1,TAll 0 TBool TBool);(0,brandUnbrand)]\n           (tvar 0) (TAll 0 (TBind (TMem 0 TBool TBool)) (TBind (TAll 0 (TBind (TAnd (TAll 1 TBool TBool) (TAll 0 TBool TBool))) TBool))).\nProof.\n  eapply t_sub.\n  eapply t_var. compute. reflexivity.\n  crush_wf.\n  eapply stp_all. crush2. crush2. crush2. crush2. crush_wf.\n  eapply stp_bindx. crush2. crush2. crush2. crush_wf.\n  unfold open. simpl.\n  eapply stp_all. eapply stp_bindx. crush2. crush2. crush2.\n  unfold open. simpl. crush_wf.\n  unfold open. simpl.\n  eapply stp_and2.\n  eapply stp_and11; crush2. eapply stp_and12; crush2. (* eapply stp_all; crush2. *)\n  unfold open. simpl. eauto. eauto. eauto. eauto. eauto. \nQed.\n\nHint Resolve ex4.\n\n(* apply it to identity functions *)\n\nExample ex5:\n  has_type [(1,TAll 0 TBool TBool);(0,brandUnbrand)]\n           (tapp (tlet 2 (tapp (tvar 0) 0 (tobj 2 [(0,dmem TBool)])) (tvar 2)) 0 (tobj 2 [(1, dfun 3 (tapp (tvar 1) 0 (tvar 3))); (0, dfun 3 (tapp (tvar 1) 0 (tvar 3)))])) TBool.\nProof.\n  eapply t_app.\n  eapply t_let.\n  eapply t_app.\n  instantiate (2:=TBind (TMem 0 TBool TBool)).\n  instantiate (1:=(TBind (TAll 0\n                    (TBind (TAnd\n                              (TAll 1 TBool TBool)  (* brand *)\n                              (TAll 0 TBool TBool) (* unbrand *)\n                           )\n                    )\n                    TBool))).\n  eapply t_sub.\n  eapply t_var. compute. reflexivity.\n  crush_wf.\n\n  eapply stp_all.\n  crush2.\n  simpl. reflexivity.\n  crush2. crush2. crush_wf.\n  unfold open. simpl.\n  eapply stp_bindx. simpl. eauto. crush2. crush2. crush_wf.\n  unfold open. simpl.\n  eapply stp_all. eapply stp_bindx. simpl. eauto. crush2. crush2.\n  unfold open. simpl.\n  crush_wf.\n  unfold open. simpl.\n  eapply stp_and2. eapply stp_and11; crush2. (*\n  eapply stp_all.\n  crush_wf. crush2. crush2. crush2. crush_wf.\n  eapply stp_selab2. compute. reflexivity. crush2.\n  instantiate (1:=TBool). crush2.\n  instantiate (1:=[(0, TBind (TMem 0 TBool TBool))]). crush2.\n  instantiate (1:=[(0, TBool); (0, TAnd (TAll 1 TBool TBool) (TAll 0 TBool TBool));\n   (0,\n   TAll 0\n     (TBind\n        (TAnd (TAll 1 TBool (TSel (varH 0) 0))\n              (TAll 0 (TSel (varH 0) 0) TBool))) TBool)]). crush2.\n  crush2. crush2. crush2.*)\n  eapply stp_and12; crush2. (*\n  eapply stp_all. crush2. eapply stp_selab1. compute. reflexivity. crush2.\n  instantiate (1:=TBool). crush2.\n  instantiate (1:=[(0, TBind (TMem 0 TBool TBool))]). crush2.\n  instantiate (1:=[(0, TAnd (TAll 1 TBool TBool) (TAll 0 TBool TBool));\n   (0,\n   TAll 0\n     (TBind\n        (TAnd (TAll 1 TBool (TSel (varH 0) 0))\n              (TAll 0 (TSel (varH 0) 0) TBool))) TBool)]). crush2.\n  crush2. crush2. crush_wf. *)\n  crush2. crush2.\n  crush2. crush_wf. crush_wf. crush2. crush2. crush2. crush_wf. crush_wf.\n\n  crush2.\n\n  crush_wf. crush2.\n\n  instantiate (1:=(TBind (TAnd (TAll 1 TBool TBool) (TAll 0 TBool TBool)))).\n  assert (open (varF (tvar 2)) (TAll 0 (TBind (TAnd (TAll 1 TBool TBool) (TAll 0 TBool TBool))) TBool) = (TAll 0 (TBind (TAnd (TAll 1 TBool TBool) (TAll 0 TBool TBool))) TBool)) as A. {\n    compute. reflexivity.\n  }\n  rewrite <- A. eapply t_var_unpack. eapply t_var. compute. reflexivity.\n\n  crush_wf. crush_wf. crush_wf.\n\n  eapply t_obj. eauto. unfold open. simpl. reflexivity.\n  eapply dt_fun.\n  instantiate (1:=TBool). unfold open. simpl.\n  eapply t_app. eapply t_var. compute. reflexivity.\n  crush_wf.\n  instantiate (1:=TBool). unfold open. simpl. crush2. crush_wf.\n  instantiate (1:=TAll 0 TBool TBool).\n  eapply dt_fun.\n  instantiate (1:=TBool). unfold open. simpl.\n  eapply t_app. eapply t_var. compute. reflexivity.\n  crush_wf.\n  instantiate (1:=TBool). unfold open. simpl. crush2. crush_wf.\n  eapply dt_nil.\n  eauto. eauto. simpl. reflexivity. eauto. eauto. eauto.\n  crush_wf. crush_wf. crush_wf.\nQed.\n\n(* test expansion *)\n\nExample ex6:\n  has_type [(1,TSel (varF (tvar 0)) 0);(0,TMem 0 TBot (TBind (TAll 0 TBool (TSel (varB 1) 0))))]\n           (tvar 1) (TAll 0 TBool (TSel (varF (tvar 1)) 0)).\nProof.\n  remember (TAll 0 TBool (TSel (varF (tvar 1)) 0)) as T.\n  assert (T = open (varF (tvar 1)) (TAll 0 TBool (TSel (varB 1) 0))). compute. eauto.\n  rewrite H.\n  eapply t_var_unpack. eapply t_sub. eapply t_var. compute. eauto. crush_wf. crush2. crush_wf.\nQed.\n\n\nExample ex7:\n  stp [(1,TSel (varF (tvar 0)) 0);(0,TMem 0 TBot (TBind (TMem 0 TBot (TAll 0 TBool (TSel (varB 1) 0)))))] []\n           (TSel (varF (tvar 1)) 0) (TAll 0 TBool (TSel (varF (tvar 1)) 0)).\nProof.\n  remember (TAll 0 TBool (TSel (varF (tvar 1)) 0)) as T.\n  assert (T = open (varF (tvar 1)) (TAll 0 TBool (TSel (varB 1) 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(*\nval listModule = new { m =>\n  type List = { this =>\n    type Elem\n    def head(): this.Elem\n    def tail(): m.List & { type Elem <: this.Elem }\n  }\n  def nil() = new { this =>\n    type Elem = Bot\n    def head() = bot()\n    def tail() = bot()\n  }\n  def cons[T](hd: T)(tl: m.List & { type Elem <: T }) = new { this =>\n    type Elem = T\n    def head() = hd\n    def tail() = tl\n  }\n}\n\ntype ListAPI = { m =>\n  type List <: { this =>\n    type Elem\n    def head(): this.Elem\n    def tail(): m.List & { type Elem <: this.Elem }\n  }\n  def nil(): List & { type Elem = Bot }\n  def cons[T]: T =>\n    m.List & { type Elem <: T } =>\n      m.List & { type Elem <: T }\n}\n\ndef cons(t: { type T }) = new {\n  def apply(hd: t.T) = new {\n    def apply(m.List & { type Elem <: t.T }) = new { this =>\n      type Elem = t.T\n      def head() = hd\n      def tail() = tl\n    }}}\n\n*)\n\nExample paper_list_nil_head:\n  has_type\n    []\n    (tobj 0\n          [(1, dfun 1 (tlet 2 (tobj 2 [(1, dfun 3 (tapp (tvar 2) 1 (tvar 3)));\n                                       (0, dmem TBot)])\n                            (tvar 2)));\n           (0, dmem (TBind (TAnd\n                              (TAll 1 TTop (TSel (varB 1) 0))\n                              (TMem 0 TBot TTop))))\n          ])\n    (TBind (TAnd\n              (TAll 1 TTop (TAnd (TSel (varB 1) 0) (TBind (TMem 0 TBot TBot))))\n              (TMem 0\n                    TBot\n                    (TBind (TAnd\n                              (TAll 1 TTop (TSel (varB 1) 0))\n                              (TMem 0 TBot TTop)))))).\nProof.\n  apply t_sub with (T1:=(TBind (TAnd\n                           (TAll 1 TTop (TAnd (TSel (varB 1) 0) (TBind (TMem 0 TBot TBot))))\n                           (TMem 0\n                                 (TBind (TAnd\n                                           (TAll 1 TTop (TSel (varB 1) 0))\n                                           (TMem 0 TBot TTop)))\n                                 (TBind (TAnd\n                                           (TAll 1 TTop (TSel (varB 1) 0))\n                                           (TMem 0 TBot TTop))))))).\n  eapply t_obj.\n  eauto. compute. reflexivity.\n  eapply dt_fun with (T1:=TTop) (T2:=(TAnd (TSel (varB 1) 0) (TBind (TMem 0 TBot TBot)))).\n  apply t_let with (Tx:=(TBind (TAnd (TAll 1 TTop TBot) (TMem 0 TBot TBot)))).\n  eapply t_obj.\n  eauto. compute. reflexivity.\n  eapply dt_fun with (T1:=TTop) (T2:=TBot).\n  simpl. unfold open at 3. simpl. eapply t_app.\n  eapply t_sub. eapply t_var. compute. reflexivity. crush_wf.\n  apply stp_and11. crush_wf. crush_wf. crush2. crush2.\n  eapply dt_mem. eapply dt_nil. eauto. simpl. reflexivity. eauto. eauto.\n  simpl. reflexivity. crush_wf. crush_wf. eauto.\n  simpl. unfold open at 2. simpl.\n  eapply t_sub. eapply t_var. compute. eauto. crush_wf.\n  eapply stp_and2. eapply stp_sel2. compute. reflexivity. crush2.\n  eapply stp_and12. crush2. crush_wf. crush_wf.\n  eapply stp_bindx. eauto. crush2. crush2. crush_wf.\n  unfold open. simpl. eapply stp_and12. crush_wf. crush_wf.\n  unfold open. simpl. crush_wf.\n\n  eapply dt_mem. eapply dt_nil. eauto. simpl. reflexivity. eauto. eauto.\n  simpl. reflexivity. crush_wf. crush_wf.\n\n  crush2.\nQed.\n\nExample paper_list_nil:\n  has_type\n    []\n    (tobj 0\n          [(1, dfun 1 (tlet 2 (tobj 2 [(2, dfun 3 (tapp (tvar 2) 2 (tvar 3)));\n                                       (1, dfun 3 (tapp (tvar 2) 1 (tvar 3)));\n                                       (0, dmem TBot)])\n                            (tvar 2)));\n           (0, dmem (TBind (TAnd\n                              (TAll 2 TTop (TAnd (TSel (varB 2) 0) (TBind (TMem 0 TBot (TSel (varB 2) 0)))))\n                            (TAnd\n                              (TAll 1 TTop (TSel (varB 1) 0))\n                              (TMem 0 TBot TTop)))))\n          ])\n    (TBind (TAnd\n              (TAll 1 TTop (TAnd (TSel (varB 1) 0) (TBind (TMem 0 TBot TBot))))\n              (TMem 0\n                    TBot\n                    (TBind (TAnd\n                              (TAll 2 TTop (TAnd (TSel (varB 2) 0) (TBind (TMem 0 TBot (TSel (varB 2) 0)))))\n                           (TAnd\n                              (TAll 1 TTop (TSel (varB 1) 0))\n                              (TMem 0 TBot TTop))))))).\nProof.\n  apply t_sub with (T1:=(TBind (TAnd\n                           (TAll 1 TTop (TAnd (TSel (varB 1) 0) (TBind (TMem 0 TBot TBot))))\n                           (TMem 0\n                                 (TBind (TAnd\n                                           (TAll 2 TTop (TAnd (TSel (varB 2) 0) (TBind (TMem 0 TBot (TSel (varB 2) 0)))))\n                                        (TAnd\n                                           (TAll 1 TTop (TSel (varB 1) 0))\n                                           (TMem 0 TBot TTop))))\n                                 (TBind (TAnd\n                                           (TAll 2 TTop (TAnd (TSel (varB 2) 0) (TBind (TMem 0 TBot (TSel (varB 2) 0)))))\n                                        (TAnd\n                                           (TAll 1 TTop (TSel (varB 1) 0))\n                                           (TMem 0 TBot TTop)))))))).\n  eapply t_obj.\n  eauto. compute. reflexivity.\n  eapply dt_fun with (T1:=TTop) (T2:=(TAnd (TSel (varB 1) 0) (TBind (TMem 0 TBot TBot)))).\n  apply t_let with (Tx:=(TBind (TAnd (TAll 2 TTop TBot) (TAnd (TAll 1 TTop TBot) (TMem 0 TBot TBot))))).\n  eapply t_obj.\n  eauto. compute. reflexivity.\n  eapply dt_fun with (T1:=TTop) (T2:=TBot).\n  simpl. unfold open at 3. simpl. eapply t_app.\n  eapply t_sub. eapply t_var. compute. reflexivity. crush_wf.\n  apply stp_and11. crush_wf. crush_wf. crush2. crush2.\n  eapply dt_fun with (T1:=TTop) (T2:=TBot).\n  simpl. unfold open at 3. simpl. eapply t_app.\n  eapply t_sub. eapply t_var. compute. reflexivity. crush_wf.\n  apply stp_and12. apply stp_and11. crush_wf. crush_wf. crush2. crush2. crush2.\n  eapply dt_mem. eapply dt_nil. eauto. simpl. reflexivity. eauto. eauto.\n  simpl. reflexivity. eauto. eauto. simpl. reflexivity.\n  crush_wf. crush_wf. eauto.\n  simpl. unfold open at 2. simpl.\n  eapply t_sub. eapply t_var. compute. eauto. crush_wf.\n  eapply stp_and2. eapply stp_sel2. compute. reflexivity. crush2.\n  eapply stp_and12.\n  eapply stp_mem. eapply stp_bindx. eauto. crush_cl. crush_cl.\n  unfold open. simpl. crush_wf. unfold open. simpl.\n\n  apply stp_and2. eapply stp_and11. eapply stp_all. crush_wf. eauto. crush_cl. crush_cl.\n  unfold open. simpl. crush_wf. unfold open. simpl. eapply stp_bot. crush_wf. crush_wf.\n  eapply stp_and12. eapply stp_and2. eapply stp_and11. eapply stp_all. crush_wf. eauto.\n  crush_cl. crush_cl. unfold open. simpl. crush_wf. unfold open. simpl. eapply stp_bot.\n  crush_wf. crush_wf. eapply stp_and12. eapply stp_mem. crush_wf. crush2. crush_wf.\n  crush_wf. eapply stp_top. crush_wf. crush_wf. crush_wf.\n\n  eapply stp_bindx. eauto. crush2. crush2. crush_wf.\n  unfold open. simpl. eapply stp_and12. eapply stp_and12. crush_wf. crush_wf. crush_wf.\n  unfold open. simpl. crush_wf.\n\n  eapply dt_mem. eapply dt_nil. eauto. simpl. reflexivity. eauto. eauto.\n  simpl. reflexivity. crush_wf. crush_wf.\n\n  eapply stp_bindx. eauto. crush_cl. crush_cl. crush_wf. unfold open. simpl.\n  eapply stp_and2. eapply stp_and11. crush_wf. crush_wf. eapply stp_and12.\n  eapply stp_mem. eapply stp_bot. crush_wf. crush_wf. crush_wf.\nQed.\n\nExample paper_list_cons_head:\n  has_type\n    []\n    (tobj 0\n          [(1, dfun 1(*type T*) (tlet 2 (tobj 2\n          [(0, dfun 3(*hd*) (tlet 4 (tobj 4 [(0, dfun 5(*tl*) (tlet 6 (tobj 6\n          [(1, dfun 7 (tvar 3));\n           (0, dmem (TSel (varF (tvar 1)) 0))]) (tvar 6)))]) (tvar 4)))]) (tvar 2)));\n           (0, dmem (TBind (TAnd\n                              (TAll 1 TTop (TSel (varB 1) 0))\n                              (TMem 0 TBot TTop))))\n          ])\n    (TBind (TAnd\n              (TAll 1 (TMem 0 TBot TTop)\n                    (TAll 0 (TSel (varB 0) 0)\n                          (TAll 0 (TAnd (TSel (varB 2) 0) (TBind (TMem 0 TBot (TSel (varB 2) 0))))\n                                (TAnd (TSel (varB 3) 0) (TBind (TMem 0 TBot (TSel (varB 3) 0)))))))\n              (TMem 0\n                    TBot\n                    (TBind (TAnd\n                              (TAll 1 TTop (TSel (varB 1) 0))\n                              (TMem 0 TBot TTop)))))).\nProof.\n  apply t_sub with (T1:=\n    (TBind (TAnd\n              (TAll 1 (TMem 0 TBot TTop)\n                    (TAll 0 (TSel (varB 0) 0)\n                          (TAll 0 (TAnd (TSel (varB 2) 0) (TBind (TMem 0 TBot (TSel (varB 2) 0))))\n                                (TAnd (TSel (varB 3) 0) (TBind (TMem 0 TBot (TSel (varB 3) 0)))))))\n              (TMem 0\n                    (TBind (TAnd\n                              (TAll 1 TTop (TSel (varB 1) 0))\n                              (TMem 0 TBot TTop)))\n                    (TBind (TAnd\n                              (TAll 1 TTop (TSel (varB 1) 0))\n                              (TMem 0 TBot TTop))))))).\n  eapply t_obj.\n  eauto. compute. reflexivity.\n  eapply dt_fun with (T1:=(TMem 0 TBot TTop))\n                     (T2:=(TAll 0 (TSel (varB 0) 0)\n                          (TAll 0 (TAnd (TSel (varB 2) 0) (TBind (TMem 0 TBot (TSel (varB 2) 0))))\n                                (TAnd (TSel (varB 3) 0) (TBind (TMem 0 TBot (TSel (varB 3) 0))))))).\n  apply t_let with (Tx:=(TBind\n                           (TAll 0 (TSel (varF (tvar 1)) 0)\n                          (TAll 0 (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))\n                                (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0)))))))).\n  eapply t_obj.\n  eauto. compute. reflexivity.\n  eapply dt_fun with (T1:=(TSel (varF (tvar 1)) 0))\n                     (T2:=(TAll 0 (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))\n                                (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0)))))).\n  apply t_let with (Tx:=(TBind (TAll 0 (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))\n                                     (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))))).\n  eapply t_obj.\n  eauto. compute. reflexivity.\n  eapply dt_fun with (T1:=(TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0)))))\n                     (T2:=(TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))).\n  apply t_let with (Tx:=(TBind (TAnd (TAll 1 TTop (TSel (varF (tvar 1)) 0)) (TMem 0 (TSel (varF (tvar 1)) 0) (TSel (varF (tvar 1)) 0))))).\n  eapply t_obj.\n  eauto. compute. reflexivity.\n  eapply dt_fun with (T1:=TTop) (T2:=(TSel (varF (tvar 1)) 0)).\n  simpl. unfold open. simpl. crush2.\n  eapply dt_mem. eapply dt_nil. eauto. simpl. reflexivity. eauto. eauto.\n  simpl. reflexivity. crush_wf. crush_wf. eauto.\n  simpl. unfold open. simpl.\n  eapply t_sub.\n  eapply t_var. compute. eauto. crush_wf.\n  compute.\n  eapply stp_and2. eapply stp_sel2. compute. reflexivity. crush2.\n  eapply stp_and12. eapply stp_mem. eapply stp_bindx.\n  eauto. crush2. crush2.\n  unfold open. simpl. crush_wf.\n  unfold open. simpl.\n  eapply stp_and2. eapply stp_and11.\n  eapply stp_all. crush_wf. eauto. crush2. crush2.\n  unfold open. simpl. crush_wf. unfold open. simpl.\n  eapply stp_sela2. compute. reflexivity. (*compute. eauto.\n    instantiate (1:=[(0, TAnd (TAll 1 TTop (TSel (varF 1) 0)) (TMem 0 (TSel (varF 1) 0) (TSel (varF 1) 0)))]). eauto. \n    instantiate (1:=[(0, TTop)]). eauto. *)\n  eapply stp_and12. crush2. crush2. crush2. crush_wf.\n  eapply stp_and12. crush2. crush_wf. crush2. crush_wf. crush_wf.\n  eapply stp_bindx. eauto. crush2. crush2. crush_wf.\n  unfold open. simpl. eapply stp_and12. crush2. crush_wf. crush_wf.\n  eapply dt_nil. eauto. eauto. simpl. reflexivity. crush_wf. crush_wf.\n  eauto.\n  unfold open. simpl.\n  assert (open (varF (tvar 4))\n               (TAll 0 (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))\n                     (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))) =\n          (TAll 0 (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))\n                (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0)))))) as A. {\n    compute. reflexivity.\n  }\n  rewrite <- A at 3. apply t_var_unpack. apply t_var. compute. reflexivity. crush_wf.\n  crush_wf. unfold open. simpl. crush_wf.\n  eapply dt_nil. eauto. eauto. simpl. reflexivity. crush_wf. crush_wf. crush2.\n\n  unfold open. simpl.\n  assert (open (varF (tvar 2)) (TAll 0 (TSel (varF (tvar 1)) 0)\n        (TAll 0\n           (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))\n           (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0)))))) =\n          (TAll 0 (TSel (varF (tvar 1)) 0)\n        (TAll 0\n           (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))\n           (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))))) as B. {\n    compute. reflexivity.\n  }\n  rewrite <- B at 2. apply t_var_unpack. apply t_var. compute. reflexivity. crush_wf.\n  unfold open. simpl. crush_wf. unfold open. simpl. crush_wf.\n\n  eapply dt_mem. eapply dt_nil. eauto. simpl. reflexivity. eauto. eauto. simpl. reflexivity.\n\n  crush_wf. crush_wf.\n\n  eapply stp_bindx. eauto. crush_cl. crush_cl. crush_wf.\n  unfold open. simpl. eapply stp_and2.\n  eapply stp_and11; crush_wf.\n  eapply stp_and12. eapply stp_mem. eapply stp_bot. crush_wf. crush_wf. crush_wf.\nQed.\n\nExample paper_list_cons:\n  has_type\n    []\n    (tobj 0\n          [(1, dfun 1(*type T*) (tlet 2 (tobj 2\n          [(0, dfun 3(*hd*) (tlet 4 (tobj 4 [(0, dfun 5(*tl*) (tlet 6 (tobj 6\n          [(2, dfun 7 (tvar 5)); (1, dfun 7 (tvar 3));\n           (0, dmem (TSel (varF (tvar 1)) 0))]) (tvar 6)))]) (tvar 4)))]) (tvar 2)));\n           (0, dmem (TBind (TAnd\n                              (TAll 2 TTop (TAnd (TSel (varB 2) 0) (TBind (TMem 0 TBot (TSel (varB 2) 0)))))\n                           (TAnd\n                              (TAll 1 TTop (TSel (varB 1) 0))\n                              (TMem 0 TBot TTop)))))\n          ])\n    (TBind (TAnd\n              (TAll 1 (TMem 0 TBot TTop)\n                    (TAll 0 (TSel (varB 0) 0)\n                          (TAll 0 (TAnd (TSel (varB 2) 0) (TBind (TMem 0 TBot (TSel (varB 2) 0))))\n                                (TAnd (TSel (varB 3) 0) (TBind (TMem 0 TBot (TSel (varB 3) 0)))))))\n              (TMem 0\n                    TBot\n                    (TBind (TAnd\n                              (TAll 2 TTop (TAnd (TSel (varB 2) 0) (TBind (TMem 0 TBot (TSel (varB 2) 0)))))\n                           (TAnd\n                              (TAll 1 TTop (TSel (varB 1) 0))\n                              (TMem 0 TBot TTop))))))).\nProof.\n  apply t_sub with (T1:=\n    (TBind (TAnd\n              (TAll 1 (TMem 0 TBot TTop)\n                    (TAll 0 (TSel (varB 0) 0)\n                          (TAll 0 (TAnd (TSel (varB 2) 0) (TBind (TMem 0 TBot (TSel (varB 2) 0))))\n                                (TAnd (TSel (varB 3) 0) (TBind (TMem 0 TBot (TSel (varB 3) 0)))))))\n              (TMem 0\n                    (TBind (TAnd\n                              (TAll 2 TTop (TAnd (TSel (varB 2) 0) (TBind (TMem 0 TBot (TSel (varB 2) 0)))))\n                           (TAnd\n                              (TAll 1 TTop (TSel (varB 1) 0))\n                              (TMem 0 TBot TTop))))\n                    (TBind (TAnd\n                              (TAll 2 TTop (TAnd (TSel (varB 2) 0) (TBind (TMem 0 TBot (TSel (varB 2) 0)))))\n                           (TAnd\n                              (TAll 1 TTop (TSel (varB 1) 0))\n                              (TMem 0 TBot TTop)))))))).\n  eapply t_obj.\n  eauto. compute. reflexivity.\n  eapply dt_fun with (T1:=(TMem 0 TBot TTop))\n                     (T2:=(TAll 0 (TSel (varB 0) 0)\n                          (TAll 0 (TAnd (TSel (varB 2) 0) (TBind (TMem 0 TBot (TSel (varB 2) 0))))\n                                (TAnd (TSel (varB 3) 0) (TBind (TMem 0 TBot (TSel (varB 3) 0))))))).\n  apply t_let with (Tx:=(TBind\n                           (TAll 0 (TSel (varF (tvar 1)) 0)\n                          (TAll 0 (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))\n                                (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0)))))))).\n  eapply t_obj.\n  eauto. compute. reflexivity.\n  eapply dt_fun with (T1:=(TSel (varF (tvar 1)) 0))\n                     (T2:=(TAll 0 (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))\n                                (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0)))))).\n  apply t_let with (Tx:=(TBind (TAll 0 (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))\n                                     (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))))).\n  eapply t_obj.\n  eauto. compute. reflexivity.\n  eapply dt_fun with (T1:=(TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0)))))\n                     (T2:=(TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))).\n  apply t_let with (Tx:=(TBind (TAnd\n                                  (TAll 2 TTop (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0)))))\n                                  (TAnd (TAll 1 TTop (TSel (varF (tvar 1)) 0)) (TMem 0 (TSel (varF (tvar 1)) 0) (TSel (varF (tvar 1)) 0)))))).\n  eapply t_obj.\n  eauto. compute. reflexivity.\n  eapply dt_fun with (T1:=TTop) (T2:=(TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))).\n  simpl. unfold open. simpl. crush2.\n  eapply dt_fun with (T1:=TTop) (T2:=(TSel (varF (tvar 1)) 0)).\n  simpl. unfold open. simpl. crush2.\n  eapply dt_mem. eapply dt_nil. eauto. simpl. reflexivity. eauto. eauto.\n  simpl. reflexivity. eauto. eauto. simpl. reflexivity. crush_wf. crush_wf. eauto.\n  simpl. unfold open. simpl.\n  eapply t_sub.\n  eapply t_var. compute. eauto. crush_wf.\n\n  eapply stp_and2. eapply stp_sel2. compute. reflexivity. crush_cl.\n  eapply stp_and12. eapply stp_mem. eapply stp_bindx.\n  eauto. crush2. crush2.\n  unfold open. simpl. crush_wf.\n  unfold open. simpl.\n  eapply stp_and2. eapply stp_and11.\n  eapply stp_all. crush_wf. eauto. crush2. crush2.\n  unfold open. simpl. crush_wf. unfold open. simpl.\n  eapply stp_and2. eapply stp_and11. crush_wf. crush_wf. eapply stp_and12.\n  eapply stp_bindx. eauto. crush_cl. crush_cl. crush_wf. unfold open. simpl.\n  eapply stp_mem. crush_wf. unfold open. simpl.\n  eapply stp_sela2. compute. reflexivity. (*crush_cl.\n    instantiate (1:=[(0, TAnd (TAll 2 TTop (TAnd (TSel (varF 0) 0) (TBind (TMem 0 TBot (TSel (varF 1) 0))))) (TAnd (TAll 1 TTop (TSel (varF 1) 0)) (TMem 0 (TSel (varF 1) 0) (TSel (varF 1) 0))))]). eauto. \n    instantiate (1:=[(0, TMem 0 TBot (TSel (varF 1) 0)); (0, TTop)]). eauto. *)\n  eapply stp_and12. eapply stp_and12. crush2. crush_wf. crush_wf. crush_wf. crush_wf.\n  crush_wf.\n  eapply stp_and12. eapply stp_and2. eapply stp_and11. eapply stp_all. crush_wf. eauto.\n  crush_cl. crush_cl. unfold open. simpl. crush_wf. unfold open. simpl.\n  eapply stp_sela2. compute. reflexivity. (*crush_cl.\n    instantiate (1:=[(0, TAnd (TAll 2 TTop (TAnd (TSel (varF 0) 0) (TBind (TMem 0 TBot (TSel (varF 1) 0))))) (TAnd (TAll 1 TTop (TSel (varF 1) 0)) (TMem 0 (TSel (varF 1) 0) (TSel (varF 1) 0))))]). eauto. \n    instantiate (1:=[(0, TTop)]). eauto.*)\n  eapply stp_and12. eapply stp_and12. crush2. crush_wf. crush_wf. crush_wf. crush_wf.\n  eapply stp_and12. crush2. crush_wf. crush_wf. eapply stp_top. crush_wf. crush_wf.\n  crush_wf. eapply stp_bindx. eauto. crush_cl. crush_cl. crush_wf. unfold open. simpl.\n  eapply stp_and12. eapply stp_and12. crush2. crush_wf. crush_wf. crush_wf.\n\n  eapply dt_nil. eauto. eauto. simpl. reflexivity. crush_wf. crush_wf.\n  eauto.\n  unfold open. simpl.\n  assert (open (varF (tvar 4))\n               (TAll 0 (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))\n                     (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))) =\n          (TAll 0 (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))\n                (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0)))))) as A. {\n    compute. reflexivity.\n  }\n  rewrite <- A at 3. apply t_var_unpack. apply t_var. compute. reflexivity. crush_wf.\n  crush_wf. unfold open. simpl. crush_wf.\n  eapply dt_nil. eauto. eauto. simpl. reflexivity. crush_wf. crush_wf. crush2.\n\n  unfold open. simpl.\n  assert (open (varF (tvar 2)) (TAll 0 (TSel (varF (tvar 1)) 0)\n        (TAll 0\n           (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))\n           (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0)))))) =\n          (TAll 0 (TSel (varF (tvar 1)) 0)\n        (TAll 0\n           (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))\n           (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))))) as B. {\n    compute. reflexivity.\n  }\n  rewrite <- B at 2. apply t_var_unpack. apply t_var. compute. reflexivity. crush_wf.\n  unfold open. simpl. crush_wf. unfold open. simpl. crush_wf.\n\n  eapply dt_mem. eapply dt_nil. eauto. simpl. reflexivity. eauto. eauto. simpl. reflexivity.\n\n  crush_wf. crush_wf.\n\n  eapply stp_bindx. eauto. crush_cl. crush_cl. crush_wf.\n  unfold open. simpl. eapply stp_and2.\n  eapply stp_and11; crush_wf.\n  eapply stp_and12. eapply stp_mem. eapply stp_bot. crush_wf. crush_wf. crush_wf.\n\nQed.\n\nExample paper_list:\n  has_type\n    []\n    (tobj 0\n          [(2, dfun 1 (tlet 2 (tobj 2 [(2, dfun 3 (tapp (tvar 2) 2 (tvar 3)));\n                                       (1, dfun 3 (tapp (tvar 2) 1 (tvar 3)));\n                                       (0, dmem TBot)])\n                            (tvar 2)));\n           (1, dfun 1(*type T*) (tlet 2 (tobj 2\n          [(0, dfun 3(*hd*) (tlet 4 (tobj 4 [(0, dfun 5(*tl*) (tlet 6 (tobj 6\n          [(2, dfun 7 (tvar 5)); (1, dfun 7 (tvar 3));\n           (0, dmem (TSel (varF (tvar 1)) 0))]) (tvar 6)))]) (tvar 4)))]) (tvar 2)));\n           (0, dmem (TBind (TAnd\n                              (TAll 2 TTop (TAnd (TSel (varB 2) 0) (TBind (TMem 0 TBot (TSel (varB 2) 0)))))\n                           (TAnd\n                              (TAll 1 TTop (TSel (varB 1) 0))\n                              (TMem 0 TBot TTop)))))\n          ])\n    (TBind (TAnd\n              (TAll 2 TTop (TAnd (TSel (varB 1) 0) (TBind (TMem 0 TBot TBot))))\n           (TAnd\n              (TAll 1 (TMem 0 TBot TTop)\n                    (TAll 0 (TSel (varB 0) 0)\n                          (TAll 0 (TAnd (TSel (varB 2) 0) (TBind (TMem 0 TBot (TSel (varB 2) 0))))\n                                (TAnd (TSel (varB 3) 0) (TBind (TMem 0 TBot (TSel (varB 3) 0)))))))\n              (TMem 0\n                    TBot\n                    (TBind (TAnd\n                              (TAll 2 TTop (TAnd (TSel (varB 2) 0) (TBind (TMem 0 TBot (TSel (varB 2) 0)))))\n                           (TAnd\n                              (TAll 1 TTop (TSel (varB 1) 0))\n                              (TMem 0 TBot TTop)))))))).\nProof.\n  apply t_sub with (T1:=\n    (TBind (TAnd\n              (TAll 2 TTop (TAnd (TSel (varB 1) 0) (TBind (TMem 0 TBot TBot))))\n           (TAnd\n              (TAll 1 (TMem 0 TBot TTop)\n                    (TAll 0 (TSel (varB 0) 0)\n                          (TAll 0 (TAnd (TSel (varB 2) 0) (TBind (TMem 0 TBot (TSel (varB 2) 0))))\n                                (TAnd (TSel (varB 3) 0) (TBind (TMem 0 TBot (TSel (varB 3) 0)))))))\n              (TMem 0\n                    (TBind (TAnd\n                              (TAll 2 TTop (TAnd (TSel (varB 2) 0) (TBind (TMem 0 TBot (TSel (varB 2) 0)))))\n                           (TAnd\n                              (TAll 1 TTop (TSel (varB 1) 0))\n                              (TMem 0 TBot TTop))))\n                    (TBind (TAnd\n                              (TAll 2 TTop (TAnd (TSel (varB 2) 0) (TBind (TMem 0 TBot (TSel (varB 2) 0)))))\n                           (TAnd\n                              (TAll 1 TTop (TSel (varB 1) 0))\n                              (TMem 0 TBot TTop))))))))).\n  eapply t_obj.\n  eauto. compute. reflexivity.\n\n  eapply dt_fun with (T1:=TTop) (T2:=(TAnd (TSel (varB 1) 0) (TBind (TMem 0 TBot TBot)))).\n  apply t_let with (Tx:=(TBind (TAnd (TAll 2 TTop TBot) (TAnd (TAll 1 TTop TBot) (TMem 0 TBot TBot))))).\n  eapply t_obj.\n  eauto. compute. reflexivity.\n  eapply dt_fun with (T1:=TTop) (T2:=TBot).\n  simpl. unfold open at 3. simpl. eapply t_app.\n  eapply t_sub. eapply t_var. compute. reflexivity. crush_wf.\n  apply stp_and11. crush_wf. crush_wf. crush2. crush2.\n  eapply dt_fun with (T1:=TTop) (T2:=TBot).\n  simpl. unfold open at 3. simpl. eapply t_app.\n  eapply t_sub. eapply t_var. compute. reflexivity. crush_wf.\n  apply stp_and12. apply stp_and11. crush_wf. crush_wf. crush2. crush2. crush2.\n  eapply dt_mem. eapply dt_nil. eauto. simpl. reflexivity. eauto. eauto.\n  simpl. reflexivity. eauto. eauto. simpl. reflexivity.\n  crush_wf. crush_wf. eauto.\n  simpl. unfold open at 2. simpl.\n  eapply t_sub. eapply t_var. compute. eauto. crush_wf.\n  eapply stp_and2. eapply stp_sel2. compute. reflexivity. crush2.\n  eapply stp_and12. eapply stp_and12.\n  eapply stp_mem. eapply stp_bindx. eauto. crush_cl. crush_cl.\n  unfold open. simpl. crush_wf. unfold open. simpl.\n\n  apply stp_and2. eapply stp_and11. eapply stp_all. crush_wf. eauto. crush_cl. crush_cl.\n  unfold open. simpl. crush_wf. unfold open. simpl. eapply stp_bot. crush_wf. crush_wf.\n  eapply stp_and12. eapply stp_and2. eapply stp_and11. eapply stp_all. crush_wf. eauto.\n  crush_cl. crush_cl. unfold open. simpl. crush_wf. unfold open. simpl. eapply stp_bot.\n  crush_wf. crush_wf. eapply stp_and12. eapply stp_mem. crush_wf. crush2. crush_wf.\n  crush_wf. eapply stp_top. crush_wf. crush_wf. crush_wf.\n\n  crush_wf.\n\n  eapply stp_bindx. eauto. crush2. crush2. crush_wf.\n  unfold open. simpl. eapply stp_and12. eapply stp_and12. crush_wf. crush_wf. crush_wf.\n  unfold open. simpl. crush_wf.\n\n  eapply dt_fun with (T1:=(TMem 0 TBot TTop))\n                     (T2:=(TAll 0 (TSel (varB 0) 0)\n                          (TAll 0 (TAnd (TSel (varB 2) 0) (TBind (TMem 0 TBot (TSel (varB 2) 0))))\n                                (TAnd (TSel (varB 3) 0) (TBind (TMem 0 TBot (TSel (varB 3) 0))))))).\n  apply t_let with (Tx:=(TBind\n                           (TAll 0 (TSel (varF (tvar 1)) 0)\n                          (TAll 0 (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))\n                                (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0)))))))).\n  eapply t_obj.\n  eauto. compute. reflexivity.\n  eapply dt_fun with (T1:=(TSel (varF (tvar 1)) 0))\n                     (T2:=(TAll 0 (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))\n                                (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0)))))).\n  apply t_let with (Tx:=(TBind (TAll 0 (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))\n                                     (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))))).\n  eapply t_obj.\n  eauto. compute. reflexivity.\n  eapply dt_fun with (T1:=(TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0)))))\n                     (T2:=(TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))).\n  apply t_let with (Tx:=(TBind (TAnd\n                                  (TAll 2 TTop (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0)))))\n                                  (TAnd (TAll 1 TTop (TSel (varF (tvar 1)) 0)) (TMem 0 (TSel (varF (tvar 1)) 0) (TSel (varF (tvar 1)) 0)))))).\n  eapply t_obj.\n  eauto. compute. reflexivity.\n  eapply dt_fun with (T1:=TTop) (T2:=(TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))).\n  simpl. unfold open. simpl. crush2.\n  eapply dt_fun with (T1:=TTop) (T2:=(TSel (varF (tvar 1)) 0)).\n  simpl. unfold open. simpl. crush2.\n  eapply dt_mem. eapply dt_nil. eauto. simpl. reflexivity. eauto. eauto.\n  simpl. reflexivity. eauto. eauto. simpl. reflexivity. crush_wf. crush_wf. eauto.\n  simpl. unfold open. simpl.\n  eapply t_sub.\n  eapply t_var. compute. eauto. crush_wf.\n\n  eapply stp_and2. eapply stp_sel2. compute. reflexivity. crush_cl.\n  eapply stp_and12. eapply stp_and12. eapply stp_mem. eapply stp_bindx.\n  eauto. crush2. crush2.\n  unfold open. simpl. crush_wf.\n  unfold open. simpl.\n  eapply stp_and2. eapply stp_and11.\n  eapply stp_all. crush_wf. eauto. crush2. crush2.\n  unfold open. simpl. crush_wf. unfold open. simpl.\n  eapply stp_and2. eapply stp_and11. crush_wf. crush_wf. eapply stp_and12.\n  eapply stp_bindx. eauto. crush_cl. crush_cl. crush_wf. unfold open. simpl.\n  eapply stp_mem. crush_wf. unfold open. simpl.\n  eapply stp_sela2. compute. reflexivity. (*crush_cl.\n    instantiate (1:=[(0,\n TAnd\n   (TAll 2 TTop\n      (TAnd (TSel (varF 0) 0) (TBind (TMem 0 TBot (TSel (varF 1) 0)))))\n   (TAnd (TAll 1 TTop (TSel (varF 1) 0))\n         (TMem 0 (TSel (varF 1) 0) (TSel (varF 1) 0))))]). eauto.\n    instantiate (1:=[(0, TMem 0 TBot (TSel (varF 1) 0)); (0, TTop)]). eauto.*)\n  eapply stp_and12. eapply stp_and12. crush2. crush_wf. crush_wf. crush_wf. crush_wf.\n  crush_wf.\n  eapply stp_and12. eapply stp_and2. eapply stp_and11. eapply stp_all. crush_wf. eauto.\n  crush_cl. crush_cl. unfold open. simpl. crush_wf. unfold open. simpl.\n  eapply stp_sela2. compute. reflexivity. (*crush_cl.\n    instantiate (1:=[(0,\n TAnd\n   (TAll 2 TTop\n      (TAnd (TSel (varF 0) 0) (TBind (TMem 0 TBot (TSel (varF 1) 0)))))\n   (TAnd (TAll 1 TTop (TSel (varF 1) 0))\n         (TMem 0 (TSel (varF 1) 0) (TSel (varF 1) 0))))]). eauto.\n    instantiate (1:=[(0, TTop)]). eauto.*)\n  eapply stp_and12. eapply stp_and12. crush2. crush_wf. crush_wf. crush_wf. crush_wf.\n  eapply stp_and12. crush2. crush_wf. crush_wf. eapply stp_top. crush_wf. crush_wf.\n  crush_wf. eapply stp_bindx. eauto. crush_cl. crush_cl. crush_wf. unfold open. simpl.\n  crush_wf. eapply stp_bindx. eauto. crush_cl. crush_cl. unfold open. simpl. crush_wf.\n  unfold open. simpl.\n  eapply stp_and12. eapply stp_and12. crush2. crush_wf. crush_wf. crush_wf.\n\n  eapply dt_nil. eauto. eauto. simpl. reflexivity. crush_wf. crush_wf.\n  eauto.\n  unfold open. simpl.\n  assert (open (varF (tvar 4))\n               (TAll 0 (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))\n                     (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))) =\n          (TAll 0 (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))\n                (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0)))))) as A. {\n    compute. reflexivity.\n  }\n  rewrite <- A at 3. apply t_var_unpack. apply t_var. compute. reflexivity. crush_wf.\n  crush_wf. unfold open. simpl. crush_wf.\n  eapply dt_nil. eauto. eauto. simpl. reflexivity. crush_wf. crush_wf. crush2.\n\n  unfold open. simpl.\n  assert (open (varF (tvar 2)) (TAll 0 (TSel (varF (tvar 1)) 0)\n        (TAll 0\n           (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))\n           (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0)))))) =\n          (TAll 0 (TSel (varF (tvar 1)) 0)\n        (TAll 0\n           (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))\n           (TAnd (TSel (varF (tvar 0)) 0) (TBind (TMem 0 TBot (TSel (varF (tvar 1)) 0))))))) as B. {\n    compute. reflexivity.\n  }\n  rewrite <- B at 2. apply t_var_unpack. apply t_var. compute. reflexivity. crush_wf.\n  unfold open. simpl. crush_wf. unfold open. simpl. crush_wf.\n\n  eapply dt_mem. eapply dt_nil. eauto. simpl. reflexivity. eauto. eauto. simpl. reflexivity.\n\n  eauto. eauto. simpl. reflexivity.\n  crush_wf. crush_wf.\n\n  eapply stp_bindx. eauto. crush_cl. crush_cl. crush_wf.\n  unfold open. simpl. eapply stp_and2.\n  eapply stp_and11; crush_wf.\n  eapply stp_and12. eapply stp_and2.\n  eapply stp_and11; crush_wf. eapply stp_and12.\n  eapply stp_mem. eapply stp_bot. crush_wf. crush_wf. crush_wf.\n  crush_wf.\n\nQed.\n\n\n\n(* ############################################################ *)\n(* Proofs *)\n(* ############################################################ *)\n\nLtac ev := repeat match goal with\n                    | H: exists _, _ |- _ => destruct H\n                    | H: _ /\\  _ |- _ => destruct H\n           end.\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\nLemma tailr_max : forall X vs n (T: X) GL,\n                       tailr (S n) vs = (0,T)::GL ->\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\nLemma tailr_to_indexr: forall GH GL x (TX:ty),\n  tailr (S x) GH = (0,TX)::GL ->\n  indexr x GH = Some TX /\\ length GL = x /\\ exists GU, GH = GU ++ ((0,TX)::GL).\nProof.\n  intros GH. induction GH.\n  - intros. inversion H.\n  - intros. case_eq (beq_nat x (length GH)); intros E.\n    + (* hit *) inversion H. destruct a. rewrite E in H1. inversion H1. subst.\n      repeat split; eauto. simpl. rewrite E. eauto. symmetry. eapply beq_nat_true_iff. eauto.\n      rewrite E. eexists. rewrite app_nil_l. eauto.\n    + (* miss *) inversion H. destruct a. rewrite E in H1.\n      repeat split; eauto. simpl. rewrite E. eauto. eapply IHGH. eauto. eapply IHGH. eauto.\n      rewrite E. edestruct IHGH. eauto. ev. eexists. rewrite H1. instantiate (1:= (i,t)::x0). simpl. rewrite <-H3. eauto. \nQed.\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 m T1 T2   => TMem m (splice n T1) (splice n T2)\n    | TSel (varB i) m => TSel (varB i) m\n    | TSel (varF i) m => TSel (varF i) m\n    | TSel (varH i) m => TSel (varH (if le_lt_dec n i  then (i+1) else i)) m\n    | TAll m T1 T2   => TAll m (splice n T1) (splice n T2)\n    | TBind T2   => TBind (splice n T2)\n    | TAnd T1 T2 => TAnd (splice n T1) (splice n T2)\n    | TOr  T1 T2 => TOr  (splice n T1) (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 (varH (n + S k)) (splice (length G) T)) =\n(splice (length G) (open_rec j (varH (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  destruct v; try solve [compute; reflexivity]. simpl.\n  case_eq (beq_nat j i0); intros E; simpl; eauto.\n  case_eq (le_lt_dec (length G) (n+k)); intros E2 LE; simpl; eauto.\n  assert (n + S k=n + k + 1) as R by omega. rewrite R. reflexivity.\n  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. remember H. clear Heqc.\n  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\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\nLemma closed_sel: forall j n V l1 l2, closed j n (TSel V l1) -> closed j n (TSel V l2).\nProof.\n  intros. inversion H; subst; constructor; assumption.\nQed.\n\nLemma closed_open: forall j n V l T, closed (j+1) n T -> closed j n (TSel V l) -> closed j n (open_rec j V 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 i0); intros E. eapply closed_sel. eassumption.\n    econstructor. eapply beq_nat_false_iff in E. omega.\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];\n    try solve [inversion IHstp1 as [IH1 IH2]; inversion IHstp2; split; eauto; eapply cl_selh ; eapply tailr_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];\n    try solve [try inversion IHstp2_1; try inversion IHstp2_2; split; eauto; apply cl_varh; eapply indexr_max; eassumption];\n    try solve [inversion IHstp2 as [IH1 IH2]; inversion IH2; split; eauto; apply cl_varh; 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\n\nLemma valtp_closed: forall G v T n,\n  val_type G v T n -> 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\nLemma concat_same_length: forall {X} (GU: list X) (GL: list X) (GH1: list X) (GH0: list X),\n  GU ++ GL = GH1 ++ GH0 ->\n  length GU = length GH1 ->\n  GU=GH1 /\\ GL=GH0.\nProof.\n  intros. generalize dependent GH1. induction GU; intros.\n  - simpl in H0. induction GH1. rewrite app_nil_l in H. rewrite app_nil_l in H.\n    split. reflexivity. apply H.\n    simpl in H0. omega.\n  - simpl in H0. induction GH1. simpl in H0. omega.\n    simpl in H0. inversion H0. simpl in H. inversion H. specialize (IHGU GH1 H4 H2).\n    destruct IHGU. subst. split; reflexivity.\nQed.\n\nLemma concat_same_length': forall {X} (GU: list X) (GL: list X) (GH1: list X) (GH0: list X),\n  GU ++ GL = GH1 ++ GH0 ->\n  length GL = length GH0 ->\n  GU=GH1 /\\ GL=GH0.\nProof.\n  intros.\n  assert (length (GU ++ GL) = length (GH1 ++ GH0)) as A. {\n    rewrite H. reflexivity.\n  }\n  rewrite app_length in A. rewrite app_length in A.\n  rewrite H0 in A. apply NPeano.Nat.add_cancel_r in A.\n  apply concat_same_length; assumption.\nQed.\n\nLemma exists_GH1L: forall {X} (GU: list X) (GL: list X) (GH1: list X) (GH0: list X) x0,\n  length GL = S x0 ->\n  GU ++ GL = GH1 ++ GH0 ->\n  length GH0 <= x0 ->\n  exists GH1L, GH1 = GU ++ GH1L /\\ GL = GH1L ++ GH0.\nProof.\n  intros X GU. induction GU; intros.\n  - eexists. rewrite app_nil_l. split. reflexivity. simpl in H0. assumption.\n  - induction GH1.\n\n    simpl in H0.\n    assert (length (a :: GU ++ GL) = length GH0) as Contra. {\n      rewrite H0. reflexivity.\n    }\n    simpl in Contra. rewrite app_length in Contra. omega.\n\n    simpl in H0. inversion H0.\n    specialize (IHGU GL GH1 GH0 x0 H H4 H1).\n    destruct IHGU as [GH1L [IHA IHB]].\n    exists GH1L. split. simpl. rewrite IHA. reflexivity. apply IHB.\nQed.\n\nLemma exists_GH0U: forall {X} (GH1: list X) (GH0: list X) (GU: list X) (GL: list X) x0,\n  length GL = S x0 ->\n  GU ++ GL = GH1 ++ GH0 ->\n  x0 < length GH0 ->\n  exists GH0U, GH0 = GH0U ++ GL.\nProof.\n  intros X GH1. induction GH1; intros.\n  - simpl in H0. exists GU. symmetry. assumption.\n  - induction GU.\n\n    simpl in H0.\n    assert (length GL = length (a :: GH1 ++ GH0)) as Contra. {\n      rewrite H0. reflexivity.\n    }\n    simpl in Contra. rewrite app_length in Contra. omega.\n\n    simpl in H0. inversion H0.\n    specialize (IHGH1 GH0 GU GL x0 H H4 H1).\n    destruct IHGH1 as [GH0U IH].\n    exists GH0U. apply IH.\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. eassumption.\n    assert (splice (length GH0) TX' = TX') as B. {\n      eapply closed_splice_idem. eapply valtp_closed. eassumption. omega.\n    }\n    rewrite <- B. simpl in IHstp2_1. eapply IHstp2_1. reflexivity.\n    eassumption. eassumption.\n    assert (splice (length GH0) (open (varF (tvar f)) TX)=(open (varF (tvar f)) TX)) as A.  {\n      eapply closed_splice_idem. eapply closed_open. eassumption. eauto. omega.\n    }\n    rewrite <- A. apply IHstp2_2.\n    reflexivity.\n  - Case \"strong_sel2\".\n    eapply stp2_strong_sel2. apply H. eassumption.\n    assert (splice (length GH0) TX' = TX') as B. {\n      eapply closed_splice_idem. eapply valtp_closed. eassumption. omega.\n    }\n    rewrite <- B. simpl in IHstp2_1. eapply IHstp2_1. reflexivity.\n    eassumption. eassumption.\n    assert (splice (length GH0) (open (varF (tvar f)) TX)=(open (varF (tvar f)) TX)) as A.  {\n      eapply closed_splice_idem. eapply closed_open. eassumption. eauto. omega.\n    }\n    rewrite <- A. apply IHstp2_2.\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  - 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    + assert (S x0 = x0 + 1) as EQ by omega.\n      assert (exists GH1L, GH1 = GU ++ GH1L /\\ GL = GH1L ++ GH0) as EQGH. {\n        eapply exists_GH1L. eassumption. eassumption. eassumption.\n      }\n      destruct EQGH as [GH1L [EQGH1 EQGL]].\n      eapply stp2_sela1.\n      eapply indexr_spliceat_hi; eauto. rewrite <- HeqGH. eassumption.\n      eapply closed_upgrade_free. \n      eapply closed_splice in H0. eapply H0. omega. \n      instantiate (1:=(map (spliceat (length GH0)) GH1L) ++ (x, v1)::GH0).\n      rewrite app_length. simpl.\n      rewrite EQGL in H1. rewrite app_length in H1.\n      rewrite map_length. omega.\n      rewrite EQGH1. rewrite map_app. rewrite app_assoc. reflexivity.\n      eapply IHstp2_1; eauto.\n      apply IHstp2_2; eauto.\n    + assert (splice (length GH0) TX=TX) as A. {\n        eapply closed_splice_idem. eassumption. omega.\n      }\n      assert (splice (length GH0) ((TMem l TBot T2))=((TMem l TBot T2))) as B. {\n        eapply closed_splice_idem. eapply stp2_closed2. eapply H3. rewrite H1. omega.\n      }\n      assert (exists GH0U, GH0 = GH0U ++ GL) as EQGH. {\n        eapply exists_GH0U. eassumption. eassumption. eassumption.\n      }\n      destruct EQGH as [GH0U EQGH].\n      eapply stp2_sela1. eapply indexr_spliceat_lo. rewrite <- HeqGH. apply H. eauto. eauto.\n      instantiate (1:=GL). eassumption.\n      rewrite EQGH. instantiate (1:=map (spliceat (length (GH0U ++ GL))) GH1 ++ (x, v1) :: GH0U). rewrite <- app_assoc. reflexivity.\n      eauto.\n      inversion B. rewrite H5. rewrite H5. eauto.\n      eapply IHstp2_2; eauto.\n  - Case \"sela2\".\n    case_eq (le_lt_dec (length GH0) x0); intros E LE.\n    + assert (S x0 = x0 + 1) as EQ by omega.\n      assert (exists GH1L, GH1 = GU ++ GH1L /\\ GL = GH1L ++ GH0) as EQGH. {\n        eapply exists_GH1L. eassumption. eassumption. eassumption.\n      }\n      destruct EQGH as [GH1L [EQGH1 EQGL]].\n      eapply stp2_sela2.\n      eapply indexr_spliceat_hi; eauto. rewrite <- HeqGH. eassumption.\n      eapply closed_upgrade_free. \n      eapply closed_splice in H0. eapply H0. omega. \n      instantiate (1:=(map (spliceat (length GH0)) GH1L) ++ (x, v1)::GH0).\n      rewrite app_length. simpl.\n      rewrite EQGL in H1. rewrite app_length in H1.\n      rewrite map_length. omega.\n      rewrite EQGH1. rewrite map_app. rewrite app_assoc. reflexivity.\n      eapply IHstp2_1; eauto.\n      apply IHstp2_2; eauto.\n    + assert (splice (length GH0) TX=TX) as A. {\n        eapply closed_splice_idem. eassumption. omega.\n      }\n      assert (splice (length GH0) ((TMem l T1 TTop))=((TMem l T1 TTop))) as B. {\n        eapply closed_splice_idem. eapply stp2_closed2. eapply H3. rewrite H1. omega.\n      }\n      assert (exists GH0U, GH0 = GH0U ++ GL) as EQGH. {\n        eapply exists_GH0U. eassumption. eassumption. eassumption.\n      }\n      destruct EQGH as [GH0U EQGH].\n      eapply stp2_sela2. eapply indexr_spliceat_lo. rewrite <- HeqGH. apply H. eauto. eauto.\n      instantiate (1:=GL). eassumption.\n      rewrite EQGH. instantiate (1:=map (spliceat (length (GH0U ++ GL))) GH1 ++ (x, v1) :: GH0U). rewrite <- app_assoc. reflexivity.\n      eauto.\n      inversion B. rewrite H5. rewrite H5. eauto.\n      eapply IHstp2_2; eauto.\n  - Case \"selab1\". \n    case_eq (le_lt_dec (length GH0) x0); intros E LE.\n    + assert (S x0 = x0 + 1) as EQ by omega.\n      assert (exists GH1L, GH1 = GU ++ GH1L /\\ GL = GH1L ++ GH0) as EQGH. {\n        eapply exists_GH1L. eassumption. eassumption. eassumption.\n      }\n      destruct EQGH as [GH1L [EQGH1 EQGL]].\n      eapply stp2_selab1.\n      eapply indexr_spliceat_hi; eauto. rewrite <- HeqGH. eassumption.\n      eapply closed_upgrade_free. \n      eapply closed_splice in H0. eapply H0. omega. \n      instantiate (1:=(map (spliceat (length GH0)) GH1L) ++ (x, v1)::GH0).\n      rewrite app_length. simpl.\n      rewrite EQGL in H1. rewrite app_length in H1.\n      rewrite map_length. omega.\n      rewrite EQGH1. rewrite map_app. rewrite app_assoc. reflexivity.\n      eapply IHstp2_1. eauto. unfold open. rewrite splice_open_permute. assert (x0+0 = x0) as Z by eauto. rewrite Z. subst T2'. reflexivity. omega.\n      apply IHstp2_2; eauto.\n    + assert (splice (length GH0) TX=TX) as A. {\n        eapply closed_splice_idem. eapply stp2_closed1. eauto. omega.\n      }\n      assert (splice (length GH0) (TBind (TMem l TBot T2))=(TBind (TMem l TBot T2))) as B. {\n        eapply closed_splice_idem. eapply stp2_closed. eauto. omega.\n      }\n      assert (exists GH0U, GH0 = GH0U ++ GL) as EQGH. {\n        eapply exists_GH0U. eassumption. eassumption. eassumption.\n      }\n      destruct EQGH as [GH0U EQGH].\n      eapply stp2_selab1.\n      eapply indexr_spliceat_lo; eauto. rewrite <- HeqGH. eassumption.\n      eassumption. eassumption.\n      rewrite EQGH. instantiate (1:=map (spliceat (length (GH0U ++ GL))) GH1 ++ (x, v1) :: GH0U). rewrite <- app_assoc. reflexivity.\n      eauto.\n      inversion B. rewrite H6. rewrite H4.\n      assert (closed 0 (length GL) (TBind (TMem l TBot T2))) as CB. eapply stp2_closed2; eauto.\n      erewrite closed_splice_idem. reflexivity.\n      inversion CB. inversion H9.\n      eapply closed_open. eapply closed_upgrade_free. eauto. instantiate (1:=(length GH0)). omega. \n      eapply cl_selh. eauto. eauto.\n      apply IHstp2_2; eauto. \n  - Case \"selab2\".\n    case_eq (le_lt_dec (length GH0) x0); intros E LE.\n    + assert (S x0 = x0 + 1) as EQ by omega.\n      assert (exists GH1L, GH1 = GU ++ GH1L /\\ GL = GH1L ++ GH0) as EQGH. {\n        eapply exists_GH1L. eassumption. eassumption. eassumption.\n      }\n      destruct EQGH as [GH1L [EQGH1 EQGL]].\n      eapply stp2_selab2.\n      eapply indexr_spliceat_hi; eauto. rewrite <- HeqGH. eassumption.\n      eapply closed_upgrade_free. \n      eapply closed_splice in H0. eapply H0. omega. \n      instantiate (1:=(map (spliceat (length GH0)) GH1L) ++ (x, v1)::GH0).\n      rewrite app_length. simpl.\n      rewrite EQGL in H1. rewrite app_length in H1.\n      rewrite map_length. omega.\n      rewrite EQGH1. rewrite map_app. rewrite app_assoc. reflexivity.\n      eapply IHstp2_1. eauto. unfold open. rewrite splice_open_permute. assert (x0+0 = x0) as Z by eauto. rewrite Z. subst T1'. reflexivity. omega.\n      apply IHstp2_2; eauto.\n    + assert (splice (length GH0) TX=TX) as A. {\n        eapply closed_splice_idem. eapply stp2_closed1. eauto. omega.\n      }\n      assert (splice (length GH0) (TBind (TMem l T1 TTop))=(TBind (TMem l T1 TTop))) as B. {\n        eapply closed_splice_idem. eapply stp2_closed. eauto. omega.\n      }\n      assert (exists GH0U, GH0 = GH0U ++ GL) as EQGH. {\n        eapply exists_GH0U. eassumption. eassumption. eassumption.\n      }\n      destruct EQGH as [GH0U EQGH].\n      eapply stp2_selab2.\n      eapply indexr_spliceat_lo; eauto. rewrite <- HeqGH. eassumption.\n      eassumption. eassumption.\n      rewrite EQGH. instantiate (1:=map (spliceat (length (GH0U ++ GL))) GH1 ++ (x, v1) :: GH0U). rewrite <- app_assoc. reflexivity.\n      eauto.\n      inversion B. rewrite H6. rewrite H4.\n      assert (closed 0 (length GL) (TBind (TMem l T1 TTop))) as CB. eapply stp2_closed2; eauto.\n      erewrite closed_splice_idem. reflexivity.\n      inversion CB. inversion H9.\n      eapply closed_open. eapply closed_upgrade_free. eauto. instantiate (1:=(length GH0)). omega. \n      eapply cl_selh. eauto. eauto.\n      apply 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 (varH (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 (varH (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 \"bind1\".\n    eapply stp2_bind1.\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    eapply IHstp2_1. eauto. \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 (varH (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. \n\nGrab Existential Variables.\napply 0. apply 0. apply 0. apply 0.\nQed.\n\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 aenv_ext__concat:\n  forall GH GH' GU GL,\n    aenv_ext GH' GH ->\n    GH = GU ++ GL ->\n    exists GU' GL', GH' = GU' ++ GL' /\\ aenv_ext GU' GU /\\ aenv_ext GL' GL.\nProof.\n  intros. generalize dependent GU. generalize dependent GL. induction H.\n  - intros. symmetry in H0. apply app_eq_nil in H0. destruct H0.\n    exists []. exists []. simpl. split; eauto. subst. split. apply aenv_ext_refl. apply aenv_ext_refl.\n  - intros. induction GU. rewrite app_nil_l in H1. subst.\n    exists []. eexists. rewrite app_nil_l. split. reflexivity.\n    split. apply aenv_ext_refl.\n    apply aenv_ext_cons. eassumption. eassumption.\n\n    simpl in H1. inversion H1.\n    specialize (IHaenv_ext GL GU H4).\n    destruct IHaenv_ext as [GU' [GL' [IHA [IHU IHL]]]].\n    exists ((x, (G', T))::GU'). exists GL'.\n    split. simpl. rewrite IHA. reflexivity.\n    split. apply aenv_ext_cons. apply IHU. assumption. apply IHL.\nQed.\n\n Lemma 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\n\nLemma fresh_tail_min: forall t (G:venv), (* not used, but may be helpful *)\n                   fresh (tail t G) <= t.\nProof.\n  intros. induction G.\n  - simpl. omega.\n  - simpl. destruct a. \n    case_eq (beq_nat t (S i)); intros E.\n    + assert (t = (S i)). eapply beq_nat_true_iff. eauto.\n      simpl. omega.\n    + eauto.\nQed.\n\n\nLemma peval_extend : forall vs x n' v' v,\n                       peval x vs v ->\n                       fresh vs <= n' ->\n                       peval x ((n',v')::vs) v.\nProof.\n  intros. destruct H. destruct H1. \n  unfold peval. split. eauto. simpl. omega.\n\n  exists x0. intros. specialize (H1 n H2). simpl. \n  assert (beq_nat (fresh_in_term x) (S n') = false).\n  eapply beq_nat_false_iff. omega. rewrite H3. eauto.\nQed.\n    \nLemma peval_extend_mult : forall G G' x v,\n                       peval x G v ->\n                       venv_ext G' G ->\n                       peval x G' v.\nProof.\n  intros. induction H0. eauto. eapply peval_extend; eauto.\nQed.\n  \nLemma peval_unique: forall x G v1 v2,\n  peval x G v1 -> peval x G v2 -> v1 = v2.\nProof.\n  intros. destruct H. destruct H0. destruct H1. destruct H2.\n  assert (1+x0+x1>x1 /\\ 1+x0+x1>x0) as A. omega. destruct A.\n  specialize (H1 _ H4). specialize (H2 _ H3).\n  rewrite H1 in H2. inversion H2. eauto. \nQed.\n\nLemma index_to_peval: forall x G v,\n  index x G = Some v -> peval (tvar x) G v.\nProof.\n  intros.\n  split. simpl. eapply index_max; eauto.\n  exists 1. intros. simpl. destruct n. omega. simpl.\n  induction G. simpl. inversion H.\n  simpl. destruct a. \n  case_eq (beq_nat x i); intros E. rewrite H. eauto.\n  eapply IHG. simpl in H. rewrite E in H.\n  destruct (le_lt_dec (fresh G) i). eauto.\n  inversion H.\nQed.\n\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 peval_extend_mult. apply H.\n    assumption. eassumption.\n    apply IHstp2_1. assumption. apply venv_ext_refl. assumption.\n    eassumption. assumption.\n    apply IHstp2_2. assumption. apply venv_ext_refl. assumption.\n  - Case \"strong_sel2\".\n    eapply stp2_strong_sel2. eapply peval_extend_mult. apply H.\n    assumption. eassumption.\n    apply IHstp2_1. assumption. apply venv_ext_refl. assumption.\n    eassumption. assumption.\n    apply IHstp2_2. assumption. assumption. apply venv_ext_refl.\n  - Case \"strong_selx\".\n    eapply stp2_strong_selx.\n    eapply peval_extend_mult. apply H. assumption.\n    eapply peval_extend_mult. apply H0. assumption.\n  - Case \"sel1\".\n    eapply stp2_sel1. eapply peval_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 \"sel2\".\n    eapply stp2_sel2. eapply peval_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 peval_extend_mult. apply H. assumption.\n    eapply peval_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    assert (exists GU' GL', GH' = GU' ++ GL' /\\ aenv_ext GU' GU /\\ aenv_ext GL' GL) as B. {\n      eapply aenv_ext__concat. eassumption. eassumption.\n    }\n    destruct B as [GU' [GL' [BEQ [BU BL]]]].\n    apply stp2_sela1 with (GX:=GX') (TX:=TX) (GL:=GL') (GU:=GU').\n    assumption. assumption.\n    rewrite <- H1. symmetry. apply aenv_ext__same_length. eassumption.\n    eassumption.\n    apply IHstp2_1; assumption.\n    apply IHstp2_2; assumption.\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    assert (exists GU' GL', GH' = GU' ++ GL' /\\ aenv_ext GU' GU /\\ aenv_ext GL' GL) as B. {\n      eapply aenv_ext__concat. eassumption. eassumption.\n    }\n    destruct B as [GU' [GL' [BEQ [BU BL]]]].\n    apply stp2_sela2 with (GX:=GX') (TX:=TX) (GL:=GL') (GU:=GU').\n    assumption. assumption.\n    rewrite <- H1. symmetry. apply aenv_ext__same_length. eassumption.\n    eassumption.\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    assert (exists GU' GL', GH' = GU' ++ GL' /\\ aenv_ext GU' GU /\\ aenv_ext GL' GL) as B. {\n      eapply aenv_ext__concat. eassumption. eassumption.\n    }\n    destruct B as [GU' [GL' [BEQ [BU BL]]]].\n    eapply stp2_selab1 with (GX:=GX') (TX:=TX) (GL:=GL') (GU:=GU').\n    assumption. eassumption. \n    rewrite <- H1. symmetry. apply aenv_ext__same_length. eassumption.\n    eassumption.\n    apply IHstp2_1; eauto.\n    eassumption.\n    apply IHstp2_2; eauto.\n  - Case \"selab2\".\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    assert (exists GU' GL', GH' = GU' ++ GL' /\\ aenv_ext GU' GU /\\ aenv_ext GL' GL) as B. {\n      eapply aenv_ext__concat. eassumption. eassumption.\n    }\n    destruct B as [GU' [GL' [BEQ [BU BL]]]].\n    eapply stp2_selab2 with (GX:=GX') (TX:=TX) (GL:=GL') (GU:=GU').\n    assumption. eassumption. \n    rewrite <- H1. symmetry. apply aenv_ext__same_length. eassumption.\n    eassumption.\n    apply IHstp2_1; eauto.\n    eassumption.\n    apply IHstp2_2; eauto.\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 \"bind1\".\n    assert (length GH = length GH') as A. {\n      apply aenv_ext__same_length. assumption.\n    }\n    apply stp2_bind1.\n    subst. rewrite A in H. assumption.\n    subst. rewrite A in H0. assumption.\n    apply IHstp2_1. 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 peval_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_bind1; 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 \"sela1\".\n    eapply stp2_sela1; try eassumption. eapply indexr_extend. eassumption.\n    rewrite H2. instantiate (1:=(x, v1)::GU). simpl. reflexivity.\n  - Case \"sela2\".\n    eapply stp2_sela2; try eassumption. eapply indexr_extend. eassumption.\n    rewrite H2. instantiate (1:=(x, v1)::GU). simpl. reflexivity.\n  - Case \"selab1\".\n    eapply stp2_selab1; try eassumption. eapply indexr_extend. eassumption.\n    rewrite H2. instantiate (1:=(x, v1)::GU). simpl. reflexivity.\n  - Case \"selab2\".\n    eapply stp2_selab2; try eassumption. eapply indexr_extend. eassumption.\n    rewrite H2. instantiate (1:=(x, v1)::GU). simpl. reflexivity.\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  (*\n  assert (TSel (varH (S (length GH))) = splice (length GH) (TSel (varH (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  *)\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 (varH (S (length GH))) with (varH (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 (varH (S (length GH))) with (varH (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 (varH (S (length GH))) with (varH (0 + (S (length GH)))).\n  rewrite -> splice_open_permute. simpl.\n  assert (\n   stp2 1 false G2 (splice (length GH) (open_rec 0 (varH (length GH)) T2))\n     G2 (splice (length GH) (open_rec 0 (varH (length GH)) T2))\n     ((map (spliceat (length GH)) [(0, (G2, open_rec 0 (varH (length GH)) T2))])++((x, v1)::GH))\n      n2\n   ->\n   stp2 1 false G2 (splice (length GH) (open_rec 0 (varH (length GH)) T2))\n     G2 (splice (length GH) (open_rec 0 (varH (length GH)) T2))\n     ((0, (G2, splice (length GH) (open_rec 0 (varH (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 (varH (S (length GH))) with (varH (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 (varH (0 + length GH)) T1)) G2\n     (splice (length GH) (open_rec 0 (varH (0 + length GH)) T2))\n     ((map (spliceat (length GH)) [(0, (G1, (open_rec 0 (varH (0 + length GH)) T1)))])++((x, v1) :: GH)) n1\n      ->\n   stp2 1 false G1\n     (splice (length GH) (open_rec 0 (varH (0 + length GH)) T1)) G2\n     (splice (length GH) (open_rec 0 (varH (0 + length GH)) T2))\n     ((0, (G1, splice (length GH) (open_rec 0 (varH (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  - Case \"bind1\".\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_bind1.\n    apply closed_inc. eauto.\n    apply closed_inc. eauto.\n    assumption.\n    unfold open. simpl. \n    rewrite <- A2. rewrite <- A1. \n    change (varH (S (length GH))) with (varH (0 + (S (length GH)))).\n    rewrite -> splice_open_permute.\n    assert (\n      stp2 1 false G1\n        (splice (length GH) (open_rec 0 (varH (0 + length GH)) T1)) G2\n        (splice (length GH) T2)\n        ((map (spliceat (length GH)) [(0, (G1, (open_rec 0 (varH (0 + length GH)) T1)))])++((x, v1) :: GH)) n1\n      ->\n      stp2 1 false G1\n        (splice (length GH) (open_rec 0 (varH (0 + length GH)) T1)) G2\n        (splice (length GH) T2)\n        ((0, (G1, splice (length GH) (open_rec 0 (varH (0 + length GH)) T1))) :: (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.\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 4].\n  - Case \"all\". repeat ev; split; eexists; eauto.\n  - Case \"and11\".\n    repeat ev; split; eexists.\n    eapply stp2_and2.\n    eapply stp2_wrapf. eapply stp2_and11; eassumption.\n    eapply stp2_wrapf. eapply stp2_and12; eassumption.\n    eassumption.\n  - Case \"and12\".\n    repeat ev; split; eexists.\n    eapply stp2_and2.\n    eapply stp2_wrapf. eapply stp2_and11; eassumption.\n    eapply stp2_wrapf. eapply stp2_and12; eassumption.\n    eassumption.\n  - Case \"and2\".\n    repeat ev; split; eexists.\n    eassumption.\n    eapply stp2_and2.\n    eapply stp2_wrapf. eapply stp2_and11; eassumption.\n    eapply stp2_wrapf. eapply stp2_and12; eassumption.\n  - Case \"or21\".\n    repeat ev; split; eexists.\n    eassumption.\n    eapply stp2_or1.\n    eapply stp2_or21; eauto.\n    eapply stp2_or22; eauto.\n  - Case \"or22\".\n    repeat ev; split; eexists.\n    eassumption.\n    eapply stp2_or1.\n    eapply stp2_or21; eauto.\n    eapply stp2_or22; eauto.\n  - Case \"or1\".\n    repeat ev; split; eexists.\n    eapply stp2_or1.\n    eapply stp2_or21; eauto.\n    eapply stp2_or22; eauto.\n    eassumption.\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\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; try (eapply stp_selax; eapply tailr_to_indexr; eauto)].\nQed.\n\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(* 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,\n                       val_type vs v T n ->\n                       fresh vs <= x ->\n                       val_type ((x,v1)::vs) v T n.\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 n, index i H1 = Some v /\\ val_type H1 v TF n.\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 n0, index i vs = Some v0 /\\ val_type vs v0 TF n0) as HI. eapply IHwf_env. eauto.\n         inversion HI as [v0 [n0 HI1]]. inversion HI1.\n         eexists. 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_exists: forall H1 G1 TF i,\n             wf_env H1 G1 ->\n             index i G1 = Some TF ->\n             exists v, index i H1 = Some v.\nProof.\n  intros.\n  assert (exists v n, index i H1 = Some v /\\ val_type H1 v TF n) as A. {\n    eapply index_safe_ex; eauto.\n  }\n  destruct A as [v [n [A1 A2]]].\n  exists v. apply A1.\nQed.\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\nLemma indexr_exists: forall H1 H2 GH TF i,\n             wf_envh H1 H2 GH ->\n             indexr i GH = Some TF ->\n             exists v, indexr i H2 = Some v.\nProof.\n  intros. induction H.\n  - inversion H0.\n  - unfold indexr.\n    case_eq (beq_nat i (length vs)); intros E.\n    + eexists. reflexivity.\n    + eapply IHwf_envh. unfold indexr in H0.\n      assert (length vs = length ts) as A. {\n        eapply wfh_length. eauto.\n      }\n      rewrite <- A in H0. rewrite E in H0. unfold indexr. apply H0.\nQed.\n\nInductive res_type: venv -> option vl -> ty -> Prop :=\n| not_stuck: forall venv v T n,\n      val_type venv v T n ->\n      res_type venv (Some v) T.\n\nHint Constructors res_type.\nHint Resolve not_stuck.\n\n\nLemma sstpd2_downgrade_true: forall G1 G2 T1 T2 H,\n  sstpd2 true G1 T1 G2 T2 H ->\n  stpd2 true G1 T1 G2 T2 H.\nProof.\n  intros. inversion H0. remember 0 as m. induction H1;\n    try solve [eexists; eauto]; try solve [inversion Heqm].\n  - Case \"top\".\n    eapply stpd2_top. eapply IHstp2. eapply sstpd2_reg1. eassumption. eauto.\n  - Case \"bot\".\n    eapply stpd2_bot. eapply IHstp2. eapply sstpd2_reg2. eassumption. eauto.\n  - Case \"mem\".\n    eapply stpd2_mem.\n    eapply IHstp2_1; eauto. eexists. eassumption.\n    eapply stpd2_wrapf. eapply IHstp2_2; eauto. eexists. eassumption.\n  - Case \"sel1\".\n    eapply stpd2_sel1.\n    eassumption. eassumption. eapply valtp_closed. eassumption.\n    eapply IHstp2_1. eexists. eassumption. eauto.\n    eapply stpd2_reg2. eapply IHstp2_2. eexists. eassumption. eauto.\n  - Case \"sel2\".\n    eapply stpd2_sel2.\n    eassumption. eassumption. eapply valtp_closed. eassumption.\n    eapply IHstp2_1. eexists. eassumption. eauto.\n    eapply stpd2_reg1. eapply IHstp2_2. eexists. eassumption. eauto.\n  - Case \"selx\".\n    eapply stpd2_selx; eauto.\n  - Case \"bind1\".\n    eapply stpd2_bind1; eauto. subst m. eapply IHstp2_1. eexists. eassumption. reflexivity.\n  - Case \"and11\".\n    eapply stpd2_and11; eauto.\n    eapply IHstp2_1; eauto. eexists. rewrite <- Heqm. eassumption.\n    eapply IHstp2_2; eauto. eexists. rewrite <- Heqm. eassumption.\n  - Case \"and12\".\n    eapply stpd2_and12; eauto.\n    eapply IHstp2_1; eauto. eexists. rewrite <- Heqm. eassumption.\n    eapply IHstp2_2; eauto. eexists. rewrite <- Heqm. eassumption.\n  - Case \"and2\".\n    eapply stpd2_and2; eauto.\n    eapply IHstp2_1; eauto. eexists. rewrite <- Heqm. eassumption.\n    eapply IHstp2_2; eauto. eexists. rewrite <- Heqm. eassumption.\n  - Case \"or21\".\n    eapply stpd2_or21; eauto.\n    eapply IHstp2_1; eauto. eexists. rewrite <- Heqm. eassumption.\n    eapply IHstp2_2; eauto. eexists. rewrite <- Heqm. eassumption.\n  - Case \"or22\".\n    eapply stpd2_or22; eauto.\n    eapply IHstp2_1; eauto. eexists. rewrite <- Heqm. eassumption.\n    eapply IHstp2_2; eauto. eexists. rewrite <- Heqm. eassumption.\n  - Case \"or1\".\n    eapply stpd2_or1; eauto.\n    eapply IHstp2_1; eauto. eexists. rewrite <- Heqm. eassumption.\n    eapply IHstp2_2; eauto. eexists. rewrite <- Heqm. eassumption.\n  - Case \"wrap\". destruct m.\n    + eapply stpd2_wrapf. eapply IHstp2. eexists. eassumption. eauto.\n    + inversion Heqm.\n  - Case \"trans\". destruct m.\n    + eapply stpd2_transf. eapply IHstp2_1. eexists; eauto. eauto.\n      eapply IHstp2_2. eexists. eauto. eauto.\n    + inversion Heqm.\n  Grab Existential Variables.\n  apply 0. apply 0. apply 0.\nQed.\n\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  intros. eapply stpd2_wrapf. eapply sstpd2_downgrade_true. eassumption.\nQed.\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 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 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 ([(x,(GX1,TX1))]++GH0) ->\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. \n    + SCase \"top-top\". eauto.\n    + SCase \"bot-bot\". 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 \"bool\". eauto.\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 \"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 (GU ++ GL) = 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        eapply stpd2_closed1 in HX. simpl in HX. eapply beq_nat_true in E. rewrite E. eapply HX.\n        instantiate (1:=([(x0, (GX1, TX1))]++GH0)). simpl. apply beq_nat_true in E. rewrite E. reflexivity.\n        reflexivity.\n        eapply stpd2_trans. eapply HX.\n        eapply IHn; try eassumption. omega. rewrite app_nil_l.\n        eapply proj2. eapply concat_same_length'. eassumption.\n        eapply beq_nat_true in E. subst. eauto.\n        simpl. reflexivity.\n        eapply IHn; try eassumption. omega.\n        reflexivity. \n      * assert (indexr x GH' = Some (GX, TX)) as A. {\n          subst.\n          eapply indexr_same. apply E. rewrite EGH in H1. eassumption.\n        }\n        simpl in EGH. simpl in EGH'. simpl in IHn. simpl in HX.\n        case_eq (le_lt_dec (S (length GH0)) x); intros E' LE'.\n        assert (exists GH1L, GH1 = GU ++ GH1L /\\ GL = GH1L ++ (x0, (GX2, TX2)) :: GH0) as EQGH. {\n          eapply exists_GH1L. eassumption. eassumption. simpl. eassumption.\n        }\n        destruct EQGH as [GH1L [EQGH1 EQGL]].\n        eapply stpd2_sela1 with (GH:=GH'). eapply A.\n        eassumption. \n        instantiate (1:=GH1L ++ (x0, (GX1, TX1)) :: GH0).\n        rewrite app_length. simpl.\n        rewrite EQGL in H3. rewrite app_length in H3. simpl in H3. eassumption.\n        instantiate (1:=GU). rewrite app_assoc. rewrite EQGH1 in EGH'. assumption.\n        eapply IHn; try eassumption. omega. reflexivity.\n        eapply IHn; try eassumption. omega.\n        assert (exists GH0U, (x0, (GX2, TX2))::GH0 = GH0U ++ GL) as EQGH. {\n          eapply exists_GH0U. eassumption. eassumption. simpl. eassumption.\n        }\n        destruct EQGH as [GH0U EQGH].\n        destruct GH0U. simpl in EQGH.\n        assert (length ((x0, (GX2, TX2))::GH0)=length GL) as Contra. {\n          rewrite EQGH. reflexivity.\n        }\n        simpl in Contra. rewrite H3 in Contra. inversion Contra. apply beq_nat_false in E. omega.\n        simpl in EQGH. inversion EQGH.\n        eapply stpd2_sela1 with (GH:=GH'). eapply A.\n        eassumption. eassumption. \n        rewrite H7 in EGH'. simpl in EGH'. instantiate (1:=GH1 ++ (x0, (GX1, TX1)) :: GH0U).\n        rewrite <- app_assoc. simpl. eapply EGH'.\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 (GU ++ GL) = 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        eapply stpd2_closed1 in HX. simpl in HX. eapply beq_nat_true in E. rewrite E. eapply HX.\n        instantiate (1:=([(x0, (GX1, TX1))]++GH0)). simpl. apply beq_nat_true in E. rewrite E. reflexivity.\n        reflexivity.\n        eapply stpd2_trans. eapply HX.\n        eapply IHn; try eassumption. omega. rewrite app_nil_l.\n        eapply proj2. eapply concat_same_length'. eassumption.\n        eapply beq_nat_true in E. subst. eauto.\n        simpl. reflexivity.\n        eapply IHn; try eassumption. omega.\n        reflexivity. \n      * assert (indexr x GH' = Some (GX, TX)) as A. {\n          subst.\n          eapply indexr_same. apply E. rewrite EGH in H1. eassumption.\n        }\n        simpl in EGH. simpl in EGH'. simpl in IHn. simpl in HX.\n        case_eq (le_lt_dec (S (length GH0)) x); intros E' LE'.\n        assert (exists GH1L, GH1 = GU ++ GH1L /\\ GL = GH1L ++ (x0, (GX2, TX2)) :: GH0) as EQGH. {\n          eapply exists_GH1L. eassumption. eassumption. simpl. eassumption.\n        }\n        destruct EQGH as [GH1L [EQGH1 EQGL]].\n        eapply stpd2_sela2 with (GH:=GH'). eapply A.\n        eassumption. \n        instantiate (1:=GH1L ++ (x0, (GX1, TX1)) :: GH0).\n        rewrite app_length. simpl.\n        rewrite EQGL in H3. rewrite app_length in H3. simpl in H3. eassumption.\n        instantiate (1:=GU). rewrite app_assoc. rewrite EQGH1 in EGH'. assumption.\n        eapply IHn; try eassumption. omega. reflexivity.\n        eapply IHn; try eassumption. omega.\n        assert (exists GH0U, (x0, (GX2, TX2))::GH0 = GH0U ++ GL) as EQGH. {\n          eapply exists_GH0U. eassumption. eassumption. simpl. eassumption.\n        }\n        destruct EQGH as [GH0U EQGH].\n        destruct GH0U. simpl in EQGH.\n        assert (length ((x0, (GX2, TX2))::GH0)=length GL) as Contra. {\n          rewrite EQGH. reflexivity.\n        }\n        simpl in Contra. rewrite H3 in Contra. inversion Contra. apply beq_nat_false in E. omega.\n        simpl in EQGH. inversion EQGH.\n        eapply stpd2_sela2 with (GH:=GH'). eapply A.\n        eassumption. eassumption. \n        rewrite H7 in EGH'. simpl in EGH'. instantiate (1:=GH1 ++ (x0, (GX1, TX1)) :: GH0U).\n        rewrite <- app_assoc. simpl. eapply EGH'.\n        eexists. eassumption.\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 (GU ++ GL) = 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        eassumption.\n        instantiate (1:=([(x0, (GX1, TX1))]++GH0)). simpl. apply beq_nat_true in E. rewrite E. reflexivity.\n        reflexivity.\n        eapply stpd2_trans. eapply HX.\n        eapply IHn; try eassumption. omega. rewrite app_nil_l.\n        eapply proj2. eapply concat_same_length'. eassumption.\n        eapply beq_nat_true in E. subst. eauto.\n        simpl. reflexivity. reflexivity.\n        eapply IHn; try eassumption. omega.\n        reflexivity.\n      * assert (indexr x GH' = Some (GX, TX)) as A. {\n          subst.\n          eapply indexr_same. apply E. rewrite EGH in H1. eassumption.\n        }\n        simpl in EGH. simpl in EGH'. simpl in IHn. simpl in HX.\n        case_eq (le_lt_dec (S (length GH0)) x); intros E' LE'.\n        assert (exists GH1L, GH1 = GU ++ GH1L /\\ GL = GH1L ++ (x0, (GX2, TX2)) :: GH0) as EQGH. {\n          eapply exists_GH1L. eassumption. eassumption. simpl. eassumption.\n        }\n        destruct EQGH as [GH1L [EQGH1 EQGL]].\n        eapply stpd2_selab1 with (GH:=GH'). eapply A.\n        eassumption. \n        instantiate (1:=GH1L ++ (x0, (GX1, TX1)) :: GH0).\n        rewrite app_length. simpl.\n        rewrite EQGL in H3. rewrite app_length in H3. simpl in H3. eassumption.\n        instantiate (1:=GU). rewrite app_assoc. rewrite EQGH1 in EGH'. assumption.\n        eapply IHn; try eassumption. omega. reflexivity. reflexivity.\n        eapply IHn; try eassumption. omega.\n        assert (exists GH0U, (x0, (GX2, TX2))::GH0 = GH0U ++ GL) as EQGH. {\n          eapply exists_GH0U. eassumption. eassumption. simpl. eassumption.\n        }\n        destruct EQGH as [GH0U EQGH].\n        destruct GH0U. simpl in EQGH.\n        assert (length ((x0, (GX2, TX2))::GH0)=length GL) as Contra. {\n          rewrite EQGH. reflexivity.\n        }\n        simpl in Contra. rewrite H3 in Contra. inversion Contra. apply beq_nat_false in E. omega.\n        simpl in EQGH. inversion EQGH.\n        eapply stpd2_selab1 with (GH:=GH'). eapply A.\n        eassumption. eassumption. \n        rewrite H6 in EGH'. simpl in EGH'. instantiate (1:=GH1 ++ (x0, (GX1, TX1)) :: GH0U).\n        rewrite <- app_assoc. simpl. eapply EGH'.\n        eexists. eassumption. reflexivity.\n        eapply IHn; try eassumption. omega.\n    + SCase \"selab2\".\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 (GU ++ GL) = 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_selab2.\n        eapply indexr_extend_mult. simpl. rewrite E. reflexivity.\n        eassumption.\n        instantiate (1:=([(x0, (GX1, TX1))]++GH0)). simpl. apply beq_nat_true in E. rewrite E. reflexivity.\n        reflexivity.\n        eapply stpd2_trans. eapply HX.\n        eapply IHn; try eassumption. omega. rewrite app_nil_l.\n        eapply proj2. eapply concat_same_length'. eassumption.\n        eapply beq_nat_true in E. subst. eauto.\n        simpl. reflexivity. reflexivity.\n        eapply IHn; try eassumption. omega.\n        reflexivity.\n      * assert (indexr x GH' = Some (GX, TX)) as A. {\n          subst.\n          eapply indexr_same. apply E. rewrite EGH in H1. eassumption.\n        }\n        simpl in EGH. simpl in EGH'. simpl in IHn. simpl in HX.\n        case_eq (le_lt_dec (S (length GH0)) x); intros E' LE'.\n        assert (exists GH1L, GH1 = GU ++ GH1L /\\ GL = GH1L ++ (x0, (GX2, TX2)) :: GH0) as EQGH. {\n          eapply exists_GH1L. eassumption. eassumption. simpl. eassumption.\n        }\n        destruct EQGH as [GH1L [EQGH1 EQGL]].\n        eapply stpd2_selab2 with (GH:=GH'). eapply A.\n        eassumption. \n        instantiate (1:=GH1L ++ (x0, (GX1, TX1)) :: GH0).\n        rewrite app_length. simpl.\n        rewrite EQGL in H3. rewrite app_length in H3. simpl in H3. eassumption.\n        instantiate (1:=GU). rewrite app_assoc. rewrite EQGH1 in EGH'. assumption.\n        eapply IHn; try eassumption. omega. reflexivity. reflexivity.\n        eapply IHn; try eassumption. omega.\n        assert (exists GH0U, (x0, (GX2, TX2))::GH0 = GH0U ++ GL) as EQGH. {\n          eapply exists_GH0U. eassumption. eassumption. simpl. eassumption.\n        }\n        destruct EQGH as [GH0U EQGH].\n        destruct GH0U. simpl in EQGH.\n        assert (length ((x0, (GX2, TX2))::GH0)=length GL) as Contra. {\n          rewrite EQGH. reflexivity.\n        }\n        simpl in Contra. rewrite H3 in Contra. inversion Contra. apply beq_nat_false in E. omega.\n        simpl in EQGH. inversion EQGH.\n        eapply stpd2_selab2 with (GH:=GH'). eapply A.\n        eassumption. eassumption. \n        rewrite H6 in EGH'. simpl in EGH'. instantiate (1:=GH1 ++ (x0, (GX1, TX1)) :: GH0U).\n        rewrite <- app_assoc. simpl. eapply EGH'.\n        eexists. eassumption. reflexivity.\n        eapply IHn; try eassumption. omega.\n\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 (varH (length GH)) T3) G2\n                (open (varH (length GH)) T3)\n                ((0, (G2, open (varH (length GH)) T3)) :: GH')\n                ->\n          stpd2 false G2 (open (varH (length GH')) T3) G2\n                (open (varH (length GH')) T3)\n                ((0, (G2, open (varH (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 (varH (length GH)) T3)) :: GH1).\n      subst. simpl. reflexivity. subst. simpl. reflexivity.\n      assumption.\n      assert (\n          stpd2 false G1 (open (varH (length GH)) T0) G2\n                (open (varH (length GH)) T3)\n                ((0, (G1, open (varH (length GH)) T0)) :: GH')\n                ->\n          stpd2 false G1 (open (varH (length GH')) T0) G2\n                (open (varH (length GH')) T3)\n                ((0, (G1, open (varH (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 (varH (length GH)) T0)) :: GH1).\n      subst. simpl. reflexivity. subst. simpl. reflexivity.\n      assumption.\n    + SCase \"bind1\".\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_bind1.\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      rewrite <-A. eauto.\n      eapply IHn. eassumption. omega.\n      instantiate (5:=GH1).\n      subst. simpl. reflexivity. subst. simpl. reflexivity.\n      assumption.\n      assert (\n          stpd2 false G1 (open (varH (length GH)) T0) G2 T2\n                ((0, (G1, open (varH (length GH)) T0)) :: GH')\n                ->\n          stpd2 false G1 (open (varH (length GH')) T0) G2 T2\n                ((0, (G1, open (varH (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 (varH (length GH)) T0)) :: GH1).\n      subst. simpl. reflexivity. subst. simpl. reflexivity.\n      assumption.\n\n    + SCase \"and11\".\n      eapply stpd2_and11.\n      eapply IHn; try eassumption. omega.\n      eapply IHn; try eassumption. omega.\n    + SCase \"and12\".\n      eapply stpd2_and12.\n      eapply IHn; try eassumption. omega.\n      eapply IHn; try eassumption. omega.\n    + SCase \"and2\".\n      eapply stpd2_and2.\n      eapply IHn; try eassumption. omega.\n      eapply IHn; try eassumption. omega.\n    + SCase \"or21\".\n      eapply stpd2_or21.\n      eapply IHn; try eassumption. omega.\n      eapply IHn; try eassumption. omega.\n    + SCase \"or22\".\n      eapply stpd2_or22.\n      eapply IHn; try eassumption. omega.\n      eapply IHn; try eassumption. omega.\n    + SCase \"or1\".\n      eapply stpd2_or1.\n      eapply IHn; try eassumption. omega.\n      eapply IHn; try eassumption. omega.\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 GH T1 T2 T3 T4,\n  stpd2 false G1 T1 G2 T2 ((x,(G1,T1))::GH) -> (* careful about H! *)\n  stpd2 false G3 T3 G4 T4 ((x,(G2,T2))::GH) ->\n  stpd2 false G3 T3 G4 T4 ((x,(G1,T1))::GH).\nProof.\n  intros. inversion H0 as [n H'].\n  eapply (stp2_narrow_aux n) with (GH1:=[]). eapply H'. omega.\n  simpl. reflexivity. simpl. reflexivity.\n  assumption.\nQed.\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\". subst.\n      assert (sstpd2 false GX' TX' G1 (TMem l TTop TTop) []) as A. {\n        eapply sstpd2_trans_axiom. eexists. eassumption.\n        eexists. eapply stp2_wrapf. eapply stp2_mem.\n        eapply stp2_wrapf. eapply stp2_topx.\n        eapply stp2_topx.\n      }\n      destruct A as [? A].\n      eexists. eapply stp2_strong_sel2; eauto.\n    + SCase \"and2\". subst. eexists. eapply stp2_and2; eauto.\n    + SCase \"or21\". subst. eexists. eapply stp2_or21; eauto.\n    + SCase \"or22\". subst. eexists. eapply stp2_or22; eauto.\n  - Case \"botx\". subst. inversion H1.\n    + SCase \"botx\". eexists. eauto.\n    + SCase \"top\". eexists. eauto.\n    + SCase \"?\". eexists. eauto.\n    + SCase \"sel2\".\n      assert (sstpd2 false GX' TX' G1 (TMem l TBot TTop) []) as A. {\n        eapply sstpd2_trans_axiom. eexists. eassumption.\n        eexists. eapply stp2_wrapf. eapply stp2_mem.\n        eapply stp2_wrapf; eapply stp2_botx.\n        eapply stp2_topx.\n      }\n      destruct A as [? A].\n      eexists. eapply stp2_strong_sel2; eauto.\n    + SCase \"and2\". subst. eexists. eapply stp2_and2; eauto.\n    + SCase \"or21\". subst. eexists. eapply stp2_or21; eauto.\n    + SCase \"or22\". subst. eexists. eapply stp2_or22; eauto.\n  - Case \"top\". subst. inversion H1.\n    + SCase \"topx\". eexists. eauto.\n    + SCase \"top\". eexists. eauto.\n    + SCase \"sel2\". subst.\n      assert (sstpd2 false GX' TX' G1 (TMem l T1 TTop) []) as A. {\n        eapply sstpd2_trans_axiom. eexists. eassumption.\n        eexists. eapply stp2_wrapf. eapply stp2_mem.\n        eapply stp2_wrapf. eapply stp2_top. eassumption.\n        eapply stp2_topx.\n      }\n      destruct A as [? A].\n      eexists. eapply stp2_strong_sel2; eauto.\n    + SCase \"and2\". subst. eexists. eapply stp2_and2; eauto.\n    + SCase \"or21\". subst. eexists. eapply stp2_or21; eauto.\n    + SCase \"or22\". subst. eexists. eapply stp2_or22; 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\". subst.\n      assert (sstpd2 false GX' TX' G1 (TMem l TBool TTop) []) as A. {\n        eapply sstpd2_trans_axiom. eexists. eassumption.\n        eexists. eapply stp2_wrapf. eapply stp2_mem.\n        eapply stp2_wrapf. eapply stp2_bool.\n        eapply stp2_topx.\n      }\n      destruct A as [? A].\n      eexists. eapply stp2_strong_sel2; eauto.\n    + SCase \"and2\". subst. eexists. eapply stp2_and2; eauto.\n    + SCase \"or21\". subst. eexists. eapply stp2_or21; eauto.\n    + SCase \"or22\". subst. eexists. eapply stp2_or22; 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\". subst.\n      assert (sstpd2 false GX' TX' G1 (TMem l0 (TMem l T0 T4) TTop) []) as A. {\n        eapply sstpd2_trans_axiom. eexists. eassumption.\n        eexists. eapply stp2_wrapf. eapply stp2_mem.\n        eapply stp2_wrapf. eassumption.\n        eapply stp2_topx.\n      }\n      destruct A as [? A].\n      eexists. eapply stp2_strong_sel2; eauto.\n    + SCase \"and2\". subst. eexists. eapply stp2_and2; eauto.\n    + SCase \"or21\". subst. eexists. eapply stp2_or21; eauto.\n    + SCase \"or22\". subst. eexists. eapply stp2_or22; eauto.\n  - Case \"ssel1\". subst.\n    assert (sstpd2 true ((f, vobj GX f ds) :: GX) (open (varF (tvar f)) TX) G3 T3 []). eapply IHn. eauto. omega. eexists. eapply H1.\n    assert (sstpd2 false GX' TX' G3 (TMem l TBot T3) []). {\n      eapply sstpd2_wrapf. eapply IHn. eassumption. omega.\n      eexists. eapply stp2_mem.\n      eapply stp2_wrapf. eapply stp2_botx.\n      eapply H1.\n    }\n    repeat eu.\n    eexists. eapply stp2_strong_sel1; eauto.\n  - Case \"ssel2\". subst. inversion H1.\n    + SCase \"top\". subst.\n      apply stp2_reg1 in H7. inversion H7.\n      eexists. eapply stp2_top. eassumption.\n    + SCase \"ssel1\".  (* interesting one *)\n      specialize (peval_unique _ _ _ _ H2 H10). intros S. inversion S.\n      (* subst. rewrite H10 in H2. inversion H2. *)\n      subst. rewrite H13 in H5. inversion H5.\n      subst.\n      eapply IHn. eapply H7. omega. eexists. eauto.\n    + SCase \"ssel2\". subst.\n      assert (sstpd2 false GX'0 TX'0 G1 (TMem l0 T1 TTop) []) as A. {\n        eapply sstpd2_trans_axiom. eexists. eassumption.\n        eexists. eapply stp2_wrapf. eapply stp2_mem.\n        eapply stp2_wrapf. eassumption.\n        eapply stp2_topx.\n      }\n      destruct A as [? A].\n      eexists. eapply stp2_strong_sel2; eauto.\n    + SCase \"sselx\".\n      specialize (peval_unique _ _ _ _ H2 H10). intros S. inversion S. subst.\n      (* subst. rewrite H2 in H10. inversion H10. subst. *)\n      eexists. eapply stp2_strong_sel2; eauto.\n    + SCase \"and2\". subst. eexists. eapply stp2_and2; eauto.\n    + SCase \"or21\". subst. eexists. eapply stp2_or21; eauto.\n    + SCase \"or22\". subst. eexists. eapply stp2_or22; 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      specialize (peval_unique _ _ _ _ H3 H6). intros S. inversion S. subst.\n      (* subst. rewrite H6 in H3. inversion H3. subst.*)\n      eexists. eapply stp2_strong_sel1; eauto.\n    + SCase \"ssel2\". subst.\n      assert (sstpd2 false GX' TX' G1 (TMem l0 (TSel (varF x1) l) TTop) []) as A. {\n        eapply sstpd2_trans_axiom. eexists. eassumption.\n        eexists. eapply stp2_wrapf. eapply stp2_mem.\n        eapply stp2_wrapf. eassumption.\n        eapply stp2_topx.\n      }\n      destruct A as [? A].\n      eexists. eapply stp2_strong_sel2; eauto.\n    + SCase \"sselx\".\n      specialize (peval_unique _ _ _ _ H3 H6). intros S. inversion S. subst.\n      (* subst. rewrite H6 in H3. inversion H3. subst.*)\n      eexists. eapply stp2_strong_selx. eauto. eauto.\n    + SCase \"and2\". subst. eexists. eapply stp2_and2; eauto.\n    + SCase \"or21\". subst. eexists. eapply stp2_or21; eauto.\n    + SCase \"or22\". subst. eexists. eapply stp2_or22; 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\". subst.\n      assert (sstpd2 false GX' TX' G1 (TMem l0 (TAll l T0 T4) TTop) []) as A. {\n        eapply sstpd2_trans_axiom. eexists. eassumption.\n        eexists. eapply stp2_wrapf. eapply stp2_mem.\n        eapply stp2_wrapf. eassumption.\n        eapply stp2_topx.\n      }\n      destruct A as [? A].\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 (varH (length ([]:aenv))) T4)\n                          G3 (open (varH (length ([]:aenv))) T8)\n                          [(0, (G3, T7))]).\n        eapply stpd2_trans. eapply stpd2_narrow. eexists. eapply stp2_extendH_mult0. eapply H10. eauto. eauto.\n        repeat eu. eexists. eapply stp2_all. eauto. eauto. eauto. eauto. eapply H8.\n    + SCase \"and2\". subst. eexists. eapply stp2_and2; eauto.\n    + SCase \"or21\". subst. eexists. eapply stp2_or21; eauto.\n    + SCase \"or22\". subst. eexists. eapply stp2_or22; eauto.\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\". subst.\n      assert (sstpd2 false GX' TX' G1 (TMem l (TBind T0) TTop) []) as A. {\n        eapply sstpd2_trans_axiom. eexists. eassumption.\n        eexists. eapply stp2_wrapf. eapply stp2_mem.\n        eapply stp2_wrapf. eassumption.\n        eapply stp2_topx.\n      }\n      destruct A as [? A].\n      eexists. eapply stp2_strong_sel2; eauto.\n    + SCase \"bind\".\n      subst.\n      assert (stpd2 false G1 (open (varH 0) T0) G3 (open (varH 0) T2)\n                    [(0, (G1, open (varH 0) T0))]) as A. {\n        simpl in H5. simpl in H9.\n        eapply stpd2_trans.\n        eexists; eauto.\n        change ([(0, (G1, open (varH 0) T0))]) with ((0, (G1, open (varH 0) T0))::[]).\n        eapply stpd2_narrow. eexists. eassumption. eexists. eassumption.\n      }\n      inversion A.\n      eexists. eapply stp2_bind; try eassumption.\n    + SCase \"bind1\".\n      subst.\n      assert (stpd2 false G1 (open (varH 0) T0) G3 T3\n                    [(0, (G1, open (varH 0) T0))]) as A. {\n        simpl in H5. simpl in H9.\n        eapply stpd2_trans.\n        eexists; eauto.\n        change ([(0, (G1, open (varH 0) T0))]) with ((0, (G1, open (varH 0) T0))::[]).\n        eapply stpd2_narrow. eexists. eassumption. eexists. eassumption.\n      }\n      inversion A.\n      eexists. eapply stp2_bind1; try eassumption.\n    + SCase \"and2\". subst. eexists. eapply stp2_and2; eauto.\n    + SCase \"or21\". subst. eexists. eapply stp2_or21; eauto.\n    + SCase \"or22\". subst. eexists. eapply stp2_or22; eauto.\n  - Case \"bind1\". subst.\n    assert (stpd2 false G1 (open (varH (length ([]:aenv))) T0) G3 T3\n                  [(0, (G1, open (varH (length ([]:aenv))) T0))]) as A. {\n      eapply stpd2_trans. eauto. eapply stpd2_extendH_mult0. \n      eapply sstpd2_downgrade. eexists. eauto. \n    }\n    destruct A as [? A]. \n    eapply stp2_reg2 in H1. ev.\n    eexists. eapply stp2_bind1. eauto. eapply stp2_closed. eauto.\n    eapply stp2_wrapf. apply H1. apply A.\n  - Case \"and11\". subst.\n    eapply IHn in H2. destruct H2 as [? H2].\n    eexists. eapply stp2_and11.\n    eassumption. eassumption. omega. eexists. eassumption.\n  - Case \"and12\". subst.\n    eapply IHn in H2. destruct H2 as [? H2].\n    eexists. eapply stp2_and12.\n    eassumption. eassumption. omega. eexists. eassumption.\n  - Case \"and2\". subst. inversion H1; subst.\n    + SCase \"top\". eapply stp2_reg1 in H. inversion H. eexists. eapply stp2_top; eassumption.\n    + SCase \"sel2\".\n      assert (sstpd2 false GX' TX' G1 (TMem l T1 TTop) []) as A. {\n        eapply sstpd2_trans_axiom. eexists. eassumption.\n        eexists. eapply stp2_wrapf. eapply stp2_mem.\n        eapply stp2_wrapf. eassumption.\n        eapply stp2_topx.\n      }\n      destruct A as [? A].\n      eexists. eapply stp2_strong_sel2; eauto.\n    + SCase \"and11\". subst. eapply IHn. apply H2. omega. eexists. eassumption.\n    + SCase \"and12\". subst. eapply IHn. apply H3. omega. eexists. eassumption.\n    + SCase \"and2\". subst. eexists. eapply stp2_and2; eauto.\n    + SCase \"or21\". subst. eexists. eapply stp2_or21; eauto.\n    + SCase \"or22\". subst. eexists. eapply stp2_or22; eauto.\n  - Case \"or21\". subst. inversion H1; subst.\n    + SCase \"top\". eapply stp2_reg1 in H. inversion H. eexists. eapply stp2_top; eassumption.\n    + SCase \"sel2\".\n      assert (sstpd2 false GX' TX' G1 (TMem l T1 TTop) []) as A. {\n        eapply sstpd2_trans_axiom. eexists. eassumption.\n        eexists. eapply stp2_wrapf. eapply stp2_mem.\n        eapply stp2_wrapf. eassumption.\n        eapply stp2_topx.\n      }\n      destruct A as [? A].\n      eexists. eapply stp2_strong_sel2; eauto.\n    + SCase \"and2\". subst. eexists. eapply stp2_and2; eauto.\n    + SCase \"or21\". subst.\n      assert (sstpd2 false G1 T1 G3 T2 []) as A. {\n        eapply sstpd2_trans_axiom.\n        eexists. eapply stp2_wrapf. eapply H.\n        eexists. eassumption.\n      }\n      destruct A as [? A].\n      eexists. eapply stp2_or21. eapply A. eassumption.\n    + SCase \"or22\". subst.\n      assert (sstpd2 false G1 T1 G3 T5 []) as A. {\n        eapply sstpd2_trans_axiom.\n        eexists. eapply stp2_wrapf. eapply H.\n        eexists. eassumption.\n      }\n      destruct A as [? A].\n      eexists. eapply stp2_or22. eapply A. eassumption.\n    + SCase \"or1\". subst. eapply IHn. apply H2. omega. eexists. eassumption.\n  - Case \"or22\". subst. inversion H1; subst.\n    + SCase \"top\". eapply stp2_reg1 in H. inversion H. eexists. eapply stp2_top; eassumption.\n    + SCase \"sel2\".\n      assert (sstpd2 false GX' TX' G1 (TMem l T1 TTop) []) as A. {\n        eapply sstpd2_trans_axiom. eexists. eassumption.\n        eexists. eapply stp2_wrapf. eapply stp2_mem.\n        eapply stp2_wrapf. eassumption.\n        eapply stp2_topx.\n      }\n      destruct A as [? A].\n      eexists. eapply stp2_strong_sel2; eauto.\n    + SCase \"and2\". subst. eexists. eapply stp2_and2; eauto.\n    + SCase \"or21\". subst.\n      assert (sstpd2 false G1 T1 G3 T2 []) as A. {\n        eapply sstpd2_trans_axiom.\n        eexists. eapply stp2_wrapf. eapply H.\n        eexists. eassumption.\n      }\n      destruct A as [? A].\n      eexists. eapply stp2_or21. eapply A. eassumption.\n    + SCase \"or22\". subst.\n      assert (sstpd2 false G1 T1 G3 T5 []) as A. {\n        eapply sstpd2_trans_axiom.\n        eexists. eapply stp2_wrapf. eapply H.\n        eexists. eassumption.\n      }\n      destruct A as [? A].\n      eexists. eapply stp2_or22. eapply A. eassumption.\n    + SCase \"or1\". subst. eapply IHn. apply H2. omega. eexists. eassumption.\n  - Case \"or1\". subst.\n    eapply IHn in H2. destruct H2 as [? H2].\n    eapply IHn in H3. destruct H3 as [? H3].\n    eexists. eapply stp2_or1.\n    eassumption. eassumption. omega. eexists. eassumption. omega. eexists. 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. apply 0. apply 0.\napply 0. apply 0. apply 0. apply 0. apply 0. apply 0. apply 0. apply 0. apply 0.\napply 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,\n  val_type H1 vf T1 n ->\n  sstpd2 true H1 T1 H2 T2 [] ->\n  val_type H2 vf T2 n.\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 tand_shape: forall T1 T2,\n  tand T1 T2 = TAnd T1 T2 \\/ tand T1 T2 = T1.\nProof.\n  intros. destruct T2; eauto.\nQed.\n\nLemma dcs_has_type_shape: forall G f ds T,\n  dcs_has_type G f ds T ->\n  T = TTop \\/\n  ((exists l T1 T2, T = TAll l T1 T2) \\/ (exists l T1, T = TMem l T1 T1)) \\/\n  (exists TA ds' T', T = TAnd TA T' /\\\n   dcs_has_type G f ds' T' /\\\n   ((exists l T1 T2, TA = TAll l T1 T2) \\/ (exists l T1, TA = TMem l T1 T1))).\nProof.\n  intros. induction H.\n  - left. reflexivity.\n  - destruct IHdcs_has_type; subst.\n    + right. left. left. eexists. eexists. eexists.\n      simpl. reflexivity.\n    + right. destruct H4; repeat ev.\n      * right. destruct H1; repeat ev.\n        eexists. eexists. eexists.\n        split. rewrite H1. simpl. reflexivity.\n        split. eassumption.\n        left. eexists. eexists. eexists. reflexivity.\n        eexists. eexists. eexists.\n        split. rewrite H1. simpl. reflexivity.\n        split. eassumption.\n        left. eexists. eexists. eexists. reflexivity.\n      * right. destruct H3; repeat ev.\n        eexists. eexists. eexists.\n        split. rewrite H1. simpl. reflexivity.\n        split. eassumption.\n        left. eexists. eexists. eexists. reflexivity.\n        eexists. eexists. eexists.\n        split. rewrite H1. simpl. reflexivity.\n        split. eassumption.\n        left. eexists. eexists. eexists. reflexivity.\n  - destruct IHdcs_has_type; subst.\n    + right. left. right. eexists. eexists.\n      simpl. reflexivity.\n    + right. destruct H2; repeat ev.\n      * right. destruct H0; repeat ev.\n        eexists. eexists. eexists.\n        split. rewrite H0. simpl. reflexivity.\n        split. eassumption.\n        right. eexists. eexists. reflexivity.\n        eexists. eexists. eexists.\n        split. rewrite H0. simpl. reflexivity.\n        split. eassumption.\n        right. eexists. eexists. reflexivity.\n      * right. destruct H2; repeat ev.\n        eexists. eexists. eexists.\n        split. rewrite H0. simpl. reflexivity.\n        split. eassumption.\n        right. eexists. eexists. reflexivity.\n        eexists. eexists. eexists.\n        split. rewrite H0. simpl. reflexivity.\n        split. eassumption.\n        right. eexists. eexists. reflexivity.\nQed.\n\nLemma dcs_tbind_aux: forall n, forall G f ds venv1 T x venv0 T0 n0,\n  n0 <= n ->\n  dcs_has_type G f ds T ->\n  stp2 0 true venv1 (open (varF x) T) venv0 (TBind T0) [] n0 ->\n  False.\nProof.\n  intros n. induction n.\n  intros. inversion H1; omega.\n  intros. eapply dcs_has_type_shape in H0.\n  destruct H0. subst. inversion H1.\n  destruct H0.\n  destruct H0.\n    repeat ev. subst. inversion H1.\n    repeat ev. subst. inversion H1.\n  destruct H0 as [TA [ds' [T' [A1 [A2 A3]]]]].\n  destruct A3; repeat ev; subst.\n  inversion H1. subst. inversion H4. subst. eapply IHn in A2. inversion A2.\n  instantiate (1:=n1). omega. eassumption.\n  inversion H1. subst. inversion H4. subst. eapply IHn in A2. inversion A2.\n  instantiate (1:=n1). omega. eassumption.\nQed.\n\nLemma dcs_tbind: forall G f ds venv1 T x venv0 T0 n0,\n  dcs_has_type G f ds T ->\n  stp2 0 true venv1 (open (varF x) T) venv0 (TBind T0) [] n0 ->\n  False.\nProof.\n  intros. eapply dcs_tbind_aux. instantiate (1:=n0). eauto. eassumption. eassumption.\nQed.\n\nLemma dcs_mem_has_type_stp: forall G G1 G2 f ds T x T1 T2,\n  dcs_has_type G f ds T ->\n  sstpd2 true G1 (open (varF x) T) G2 (TMem (length ds) T1 T2) [] ->\n  False.\nProof.\n  intros. remember (length ds) as l. assert (l >= length ds) as A by omega. clear Heql.\n  induction H. simpl in H0. destruct H0 as [? H0]. inversion H0.\n  destruct (tand_shape (TAll m T0 T3) TS).\n  rewrite H5 in H4. rewrite H4 in H0. simpl in H0. destruct H0 as [? H0]. inversion H0.\n  subst. inversion H9.\n  subst. eapply IHdcs_has_type. eexists. eapply H9. simpl in A. omega.\n  rewrite H5 in H4. rewrite H4 in H0. destruct H0 as [? H0]. inversion H0.\n  destruct (tand_shape (TMem m T0 T0) TS).\n  rewrite H3 in H2. rewrite H2 in H0. simpl in H0. destruct H0 as [? H0]. inversion H0.\n  subst. inversion H7. subst. simpl in A. omega.\n  apply IHdcs_has_type. eexists. eassumption. simpl in A. omega.\n  rewrite H3 in H2. rewrite H2 in H0. simpl in H0. destruct H0 as [? H0]. inversion H0.\n  simpl in A. omega.\nQed.\n\nLemma invert_typ1: forall venv vx l T1 T2,\n  val_type venv vx (TMem l T1 T2) 1 ->\n  exists GX ds TX,\n    vx = (vobj GX (fresh GX) ds) /\\\n    index l ds = Some (dmem TX) /\\\n    sstpd2 false venv T1 (((fresh GX),vobj GX (fresh GX) ds)::GX) (open (varF (tvar (fresh GX))) TX) [] /\\\n    sstpd2 true (((fresh GX),vobj GX (fresh GX) ds)::GX) (open (varF (tvar (fresh GX))) TX) venv T2 [].\nProof.\n  intros. inversion H; ev; try solve by inversion.\n  (* only mem case! *)\n  subst.\n  exists venv1. exists ds.\n  assert (exists TX, index l ds = Some (dmem TX) /\\ sstpd2 true ((fresh venv1, vobj venv1 (fresh venv1) ds) :: venv1) (TMem l (open (varF (tvar (fresh venv1))) TX) (open (varF (tvar (fresh venv1))) TX)) venv0 (TMem l T1 T2) []) as A. {\n    clear H. clear H0.\n    unfold id in H4.\n    remember (((fresh venv1, vobj venv1 (fresh venv1) ds) :: venv1)) as venv.\n    assert (sstpd2 true venv (open (varF (tvar (fresh venv1))) T) venv0 (TMem l T1 T2) []) as B. {\n      eexists. eassumption.\n    }\n    clear Heqvenv.\n    unfold id in H2.\n    remember ((fresh venv1, open (varF (tvar (fresh venv1))) T) :: tenv0) as tenv.\n    clear Heqtenv. clear H4.\n    induction H2. destruct B as [? B]. inversion B.\n    simpl.\n    case_eq (le_lt_dec (fresh dcs) m); intros LE E1.\n    case_eq (beq_nat l m); intros E2.\n    destruct (tand_shape (TAll m T0 T3) TS).\n    rewrite H4 in H3. rewrite H3 in B. destruct B as [? B]. inversion B. inversion H8.\n    eapply dcs_mem_has_type_stp in H2. inversion H2. rewrite <- H1. eapply beq_nat_true in E2. rewrite <- E2. eexists. eassumption.\n    rewrite H4 in H3. rewrite H3 in B. destruct B as [? B]. inversion B.\n    eapply IHdcs_has_type.  destruct (tand_shape (TAll m T0 T3) TS).\n    rewrite H4 in H3. rewrite H3 in B. destruct B as [? B]. inversion B. inversion H8. eexists. eassumption.\n    rewrite H4 in H3. rewrite H3 in B. destruct B as [? B]. inversion B.\n    inversion H2; subst. simpl in LE. omega. simpl in LE. omega. simpl in LE. omega.\n    simpl.\n    case_eq (le_lt_dec (fresh dcs) m); intros LE E1.\n    case_eq (beq_nat l m); intros E2.\n    exists T0.\n    split. reflexivity.\n    destruct (tand_shape (TMem m T0 T0) TS).\n    rewrite H1 in H0. rewrite H0 in B. destruct B as [? B]. inversion B. eapply beq_nat_true in E2. rewrite E2. rewrite E2 in H6. eexists. eassumption.\n    eapply dcs_mem_has_type_stp in H2. inversion H2. rewrite <- H. eapply beq_nat_true in E2. rewrite <- E2. eexists. unfold open. eassumption.\n    rewrite H1 in H0. rewrite H0 in B. eapply beq_nat_true in E2. rewrite <- E2 in B. apply B.\n    eapply IHdcs_has_type. destruct (tand_shape (TMem m T0 T0) TS).\n    rewrite H1 in H0. rewrite H0 in B. destruct B as [? B]. inversion B. inversion H6. apply beq_nat_false in E2. omega. eexists. eassumption.\n    rewrite H1 in H0. rewrite H0 in B. destruct B as [? B]. inversion B. apply beq_nat_false in E2. omega.\n    inversion H2; subst. simpl in LE. omega. simpl in LE. omega. simpl in LE. omega.\n  }\n  destruct A as [TX [A1 A2]].\n  exists TX.\n  split. reflexivity.\n  split. apply A1.\n  split.\n  destruct A2 as [? A2]. inversion A2. subst. eexists. eassumption.\n  destruct A2 as [? A2]. inversion A2. subst. eexists. eassumption.\nQed.\n\nLemma inv_closed_open0: forall j n x T, closed j n (open_rec j (varH x) T) -> n <= x -> closed (j) n T.\nProof.\n  intros. generalize dependent j. induction T; try solve [\n  intros; inversion H; subst; unfold closed; try econstructor; try eapply IHT1; eauto; try eapply IHT2; eauto; try eapply IHT; eauto].\n\n  - Case \"TSelB\". intros. simpl.\n    unfold open_rec in H.\n    destruct v.\n    eapply closed_upgrade. eauto. omega.\n    eapply closed_upgrade. eauto. omega.\n\n    case_eq (beq_nat j i0); intros E.\n\n    + rewrite E in H. eapply beq_nat_true_iff in E. subst. inversion H. subst. eapply cl_selb. omega.\n\n    + rewrite E in H. eapply closed_upgrade; eauto. \nQed.\n\n\nLemma inv_closed_open: forall j n V l T, closed j n (open_rec j V T) -> closed j n (TSel V l) -> closed (j+1) n T.\nProof.\n  intros. generalize dependent j. induction T; try solve [\n  intros; inversion H; subst; unfold closed; try econstructor; try eapply IHT1; eauto; try eapply IHT2; eauto; try eapply IHT; eauto].\n\n  - Case \"TSelB\". intros. simpl.\n    unfold open_rec in H.\n    destruct v.\n    eapply closed_upgrade. eauto. omega.\n    eapply closed_upgrade. eauto. omega.\n\n    case_eq (beq_nat j i0); intros E.\n\n    + eapply beq_nat_true_iff in E. subst. eapply cl_selb. omega.\n\n    + rewrite E in H. eapply closed_upgrade; eauto. omega.\n\n  - intros. inversion H. subst. eapply cl_all.\n    eapply IHT1. eassumption. eassumption.\n    simpl. change (S (j+1)) with ((S j) + 1). eapply IHT2. eassumption.\n    eapply closed_upgrade; eauto.\n  - intros. inversion H. subst. eapply cl_bind.\n    simpl. change (S (j+1)) with ((S j) + 1). eapply IHT. eassumption.\n    eapply closed_upgrade; eauto.\nQed.\n\n\n(* begin substitute *)\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 V l (n:nat) x j,\nclosed j n (TSel V l) ->\n(open_rec j (varH x) (subst V T2)) =\n(subst V (open_rec j (varH (x+1)) T2)).\nProof.\n  intros T2 V l n. induction T2; intros; eauto.\n  -  simpl. rewrite IHT2_1. rewrite IHT2_2. eauto. eauto. eauto.\n  -  simpl.\n     destruct v; simpl; try reflexivity.\n     + simpl. case_eq (beq_nat i0 0); intros E.\n       destruct V; try reflexivity.\n       inversion H. subst.\n       assert (beq_nat j i1 = false) as A. apply false_beq_nat. omega.\n       rewrite A. reflexivity.\n       reflexivity.\n     + simpl. case_eq (beq_nat j i0); intros E.\n       assert (x+1<>0). omega. eapply beq_nat_false_iff in H0.\n       assert (x=x+1-1) as A. unfold id. omega.\n       rewrite <- A.  rewrite H0. reflexivity.\n       reflexivity.\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.\n  - simpl. rewrite IHT2_1. rewrite IHT2_2. eauto. eauto. eauto.\n  - simpl. rewrite IHT2_1. rewrite IHT2_2. eauto. eauto. eauto.\nQed.\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  subst. omega.\n  subst. eapply closed_upgrade. eassumption. omega.\n  subst. eapply closed_upgrade. eassumption. omega.\nQed.\n\nLemma closed_subst: forall j n V l T, closed j (n+1) T -> closed 0 n (TSel V l) -> closed j (n) (subst V 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 x 0); intros E. eapply closed_upgrade. eapply closed_upgrade_free. eapply closed_sel. eauto. omega. eauto. omega.\n    econstructor. assert (x > 0). eapply beq_nat_false_iff in E. omega. omega.\nQed.\n\n\nLemma subst_open_commute_m: forall j n m V l T2, closed (j+1) (n+1) T2 -> closed 0 m (TSel V l) ->\n    subst V (open_rec j (varH (n+1)) T2) = open_rec j (varH n) (subst V 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  simpl. case_eq (beq_nat x 0); intros E.\n  destruct V; try solve [simpl; reflexivity].\n  unfold closed in H0. inversion H0. subst.\n  case_eq (beq_nat  j i0); intros E2.\n  apply beq_nat_true in E2. subst. omega.\n  reflexivity. reflexivity.\n  \n  simpl. case_eq (beq_nat j i0); 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) as A. omega. rewrite A. eauto.\n  eauto.\nQed.\n\nLemma subst_open_commute: forall j n V l T2, closed (j+1) (n+1) T2 -> closed 0 0 (TSel V l) ->\n    subst V (open_rec j (varH (n+1)) T2) = open_rec j (varH n) (subst V 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 (varH 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\n  case_eq (beq_nat x 0); intros E. omega. omega.\n\n  case_eq (beq_nat j i0); intros E. eauto. eauto.\n\n  eapply closed_upgrade; eauto.\n\n  eapply closed_upgrade; 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 V l T2, nosubst (TSel V l) -> nosubst T2 -> nosubst (open_rec j V T2).\nProof.\n  intros. generalize dependent j. induction T2; intros; try inversion H0; simpl; eauto.\n\n  destruct v; eauto.\n  case_eq (beq_nat j i0); intros E. eauto. eauto.\nQed.\n\nLemma nosubst_open_rev: forall j V l T2, nosubst (open_rec j V T2) -> nosubst (TSel V l) -> nosubst T2.\nProof.\n  intros. generalize dependent j. induction T2; intros; try inversion H; simpl in H; simpl; eauto.\n  destruct v; eauto.\nQed.\n\nLemma nosubst_zero_closed: forall j T2, nosubst (open_rec j (varH 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  destruct v. inversion H1. inversion H1. inversion H1. subst.\n  case_eq (beq_nat j i1); intros E. rewrite E in H. destruct H. eauto.\n  eapply beq_nat_false_iff in E.\n  constructor. omega.\nQed.\n\n\n\n(* ---- two-env substitution. first define what 'compatible' types mean. ---- *)\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\nDefinition compat (GX:venv) (TX: ty) (TX': var) (V: option vl) (G1:venv) (T1:ty) (T1':ty) :=\n  (exists x1 v nv, peval x1 G1 v /\\ V = Some v /\\ GX = GX /\\ val_type GX v (subst TX' TX) nv /\\ T1' = (subst (varF x1) T1)) \\/\n  (closed_rec 0 0 T1 /\\ T1' = T1) \\/ (* this one is for convenience: redundant with next *)\n  (nosubst T1 /\\ T1' = subst (varF (tvar 0)) T1).\n\n\nDefinition compat2 (GX:venv) (TX: ty) (TX': var) (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 TX' V G1 T1 T2\n  end.\n\n\nLemma closed_compat: forall GX TX TX' V GXX TXX TXX' j k,\n  compat GX TX 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 H4. destruct H5. rewrite H6.\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.\n  Grab Existential Variables.\n  apply 0. apply 0.\nQed.\n\nLemma closed_compat': forall GX TX TX' l V GXX TXX TXX' j k,\n  compat GX TX TX' V GXX TXX TXX' ->\n  closed 0 k (TSel TX' l) ->\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 H4. destruct H5. rewrite H6.\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.\n  Grab Existential Variables.\n  apply 0. apply 0.\nQed.\n\nLemma indexr_compat_miss0: forall GH GH' GX TX TX' V (GXX:venv) (TXX:ty) n,\n      Forall2 (compat2 GX TX 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 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 TX' V G1 T1',\n  compat GX TX TX' V G1 TTop T1' -> closed 0 1 TX -> T1' = TTop.\nProof.\n  intros ? ? ? ? ? ? CC CLX. repeat destruct CC as [|CC]; ev; eauto.\nQed.\n\nLemma compat_bot: forall GX TX TX' V G1 T1',\n  compat GX TX TX' V G1 TBot T1' -> closed 0 1 TX -> T1' = TBot.\nProof.\n  intros ? ? ? ? ? ? CC CLX. repeat destruct CC as [|CC]; ev; eauto.\nQed.\n\n\nLemma compat_bool: forall GX TX TX' V G1 T1',\n  compat GX TX TX' V G1 TBool T1' -> closed 0 1 TX -> T1' = TBool.\nProof.\n  intros ? ? ? ? ? ? CC CLX. repeat destruct CC as [|CC]; ev; eauto.\nQed.\n\nLemma compat_mem: forall GX TX TX' V G1 l T1 T2 T1',\n    compat GX TX TX' V G1 (TMem l T1 T2) T1' ->\n    closed 0 1 TX ->\n    exists TA TB, T1' = TMem l TA TB /\\\n                  compat GX TX TX' V G1 T1 TA /\\\n                  compat GX TX TX' V G1 T2 TB.\nProof.\n  intros ? ? ? ? ? ? ? ? ? CC CLX. repeat destruct CC as [|CC].\n  - unfold peval in H.\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 TX' V G1 l T2 T2',\n    compat GX TX TX' V G1 T2 T2' ->\n    compat GX TX TX' V G1 (TMem l TBot T2) (TMem l TBot T2').\nProof.\n  intros. repeat destruct H as [|H].\n  - unfold peval in 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 TX' V G1 l T2 T2',\n    compat GX TX TX' V G1 T2 T2' ->\n    compat GX TX TX' V G1 (TMem l T2 TTop) (TMem l T2' TTop).\nProof.\n  intros. repeat destruct H as [|H].\n  - unfold peval in 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 TX' V G1 l T2 T2',\n    compat GX TX TX' V G1 T2 T2' ->\n    compat GX TX TX' V G1 (TMem l T2 T2) (TMem l T2' T2').\nProof.\n  intros. repeat destruct H as [|H].\n  - unfold peval in 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_and: forall GX TX TX' V G1 T1 T2 T1',\n    compat GX TX TX' V G1 (TAnd T1 T2) T1' ->\n    closed_rec 0 1 TX ->\n    exists TA TB, T1' = TAnd TA TB /\\\n                  compat GX TX TX' V G1 T1 TA /\\\n                  compat GX TX TX' V G1 T2 TB.\nProof.\n  intros ? ? ? ? ? ? ? ? CC CLX. repeat destruct CC as [|CC].\n  - unfold peval in H.\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\nLemma compat_or: forall GX TX TX' V G1 T1 T2 T1',\n    compat GX TX TX' V G1 (TOr T1 T2) T1' ->\n    closed_rec 0 1 TX ->\n    exists TA TB, T1' = TOr TA TB /\\\n                  compat GX TX TX' V G1 T1 TA /\\\n                  compat GX TX TX' V G1 T2 TB.\nProof.\n  intros ? ? ? ? ? ? ? ? CC CLX. repeat destruct CC as [|CC].\n  - unfold peval in H.\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\n\nLemma compat_sel: forall GX TX TX' V G1 T1' (GXX:venv) (TXX:ty) x l v n,\n    compat GX TX TX' V G1 (TSel (varF x) l) T1' ->\n    closed 0 1 TX ->\n    closed 0 0 TXX ->\n    peval x G1 v ->\n    val_type GXX v TXX n ->\n    exists TXX', T1' = (TSel (varF x) l) /\\ TXX' = TXX /\\ compat GX TX 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\nLemma compat_selb: forall GX TX TX' V G1 T1' (GXX:venv) (TXX:ty) x T0 v n,\n    compat GX TX TX' V G1 (open (varF x) T0) T1' ->\n    closed 0 1 TX ->\n    closed 0 0 TXX ->\n    closed 1 0 T0 ->\n    (* index x G1 = Some v -> *)\n    val_type GXX v TXX n ->\n    exists TXX', T1' = (open (varF x) T0) /\\ TXX' = TXX /\\ compat GX TX TX' V GXX TXX TXX'\n.\nProof.\n  intros ? ? ? ? ? ? ? ? ? ? ? ? CC CL CL1. repeat destruct CC as [|CC].\n  - ev. repeat eexists; eauto.\n    erewrite <- closed_no_subst. eassumption.\n    unfold open. eapply closed_open. simpl. eassumption. eauto.\n    + right. left. simpl in H0. eauto.\n  - ev. repeat eexists; eauto. + right. left. simpl in H0. eauto.\n  - ev. repeat eexists; eauto.\n    erewrite <- closed_no_subst. eassumption.\n    unfold open. eapply closed_open. simpl. eassumption. eauto.\n    + right. left. simpl in H0. eauto.\n  Grab Existential Variables.\n  apply 0. apply 0.\nQed.\n\n\nLemma compat_selh: forall GX TX TX' V G1 T1' GH0 GH0' (GXX:venv) (TXX:ty) x l,\n    compat GX TX TX' V G1 (TSel (varH x) l) T1' ->\n    closed 0 1 TX ->\n    indexr x (GH0 ++ [(0, (GX, TX))]) = Some (GXX, TXX) ->\n    Forall2 (compat2 GX TX TX' V) GH0 GH0' ->\n    (x = 0 /\\ GXX = GX /\\ TXX = TX) \\/\n    exists TXX',\n      x > 0 /\\ T1' = TSel (varH (x-1)) l /\\\n      indexr (x-1) GH0' = Some (GXX, TXX') /\\\n      compat GX TX 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 TX' V G1 m T1 T2 T1' n,\n    compat GX TX TX' V G1 (TAll m T1 T2) T1' ->\n    closed 0 1 TX ->\n    closed 1 (n+1) T2 ->\n    exists TA TB, T1' = TAll m TA TB /\\\n                  closed 1 n TB /\\\n                  compat GX TX TX' V G1 T1 TA /\\\n                  compat GX TX TX' V G1 (open_rec 0 (varH (n+1)) T2) (open_rec 0 (varH n) TB).\nProof.\n  intros ? ? ? ? ? ? ? ? ? ? CC CLX CL2. repeat destruct CC as [|CC].\n\n  - unfold peval in H.\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. erewrite 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      * erewrite subst_open_commute.  assert (T2 = subst (varF (tvar 0)) 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      * erewrite subst_open_commute; eauto.\n  Grab Existential Variables.\n  apply 0. apply 0. apply 0. apply 0. apply 0. apply 0. apply 0.\nQed.\n\n\nLemma compat_bind: forall GX TX TX' V G1 T2 T1' n,\n    compat GX TX TX' V G1 (TBind T2) T1' ->\n    closed 0 1 TX ->\n    closed 1 (n+1) T2 ->\n    exists TB, T1' = TBind TB /\\\n                  closed 1 n TB /\\\n                  compat GX TX TX' V G1 (open_rec 0 (varH (n+1)) T2) (open_rec 0 (varH n) TB).\nProof.\n  intros ? ? ? ? ? ? ? ? CC CLX CL2. repeat destruct CC as [|CC].\n\n  - unfold peval in H.\n    ev. simpl in H0. repeat eexists; eauto. eapply closed_subst; eauto.\n    + unfold compat. left. repeat eexists; eauto. erewrite 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      * erewrite subst_open_commute.  assert (T2 = subst (varF (tvar 0)) 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      * erewrite subst_open_commute; eauto.\n  Grab Existential Variables.\n  apply 0. apply 0. apply 0. apply 0. apply 0. apply 0. apply 0.\nQed.\n\n\nLemma subst_open1_aux: forall j x T,\nclosed (j+1) 0 T ->\n(subst (varF x) (open_rec j (varH 0) T)) = (open_rec j (varF x) T).\nProof.\n  intros. generalize dependent j. induction T; intros; eauto.\n  - simpl.\n    rewrite <- IHT1.\n    rewrite <- IHT2.\n    reflexivity.\n    inversion H. eauto.\n    inversion H. eauto.\n  - destruct v.\n    + simpl. reflexivity.\n    + simpl. inversion H. subst. omega.\n    + simpl.\n      case_eq (beq_nat j i0); intros E.\n      * simpl. reflexivity.\n      * reflexivity.\n  - simpl.\n    rewrite <- IHT1.\n    assert (S j = j+1) as A by omega.\n    rewrite A. rewrite <- IHT2.\n    reflexivity.\n    inversion H. subst.\n    assert (j + 1 + 1 = S (j + 1)) as B by omega.\n    rewrite B. eassumption.\n    inversion H. subst. eauto.\n  - simpl.\n    assert (S j = j+1) as A by omega.\n    rewrite A. rewrite <- IHT.\n    reflexivity.\n    inversion H. subst.\n    assert (j + 1 + 1 = S (j + 1)) as B by omega.\n    rewrite B. eassumption.\n  - simpl.\n    rewrite <- IHT1.\n    rewrite <- IHT2.\n    reflexivity.\n    inversion H. eauto.\n    inversion H. eauto.\n  - simpl.\n    rewrite <- IHT1.\n    rewrite <- IHT2.\n    reflexivity.\n    inversion H. eauto.\n    inversion H. eauto.\nQed.\n\nLemma subst_open1: forall x T,\nclosed 1 0 T ->\n(subst (varF x) (open (varH 0) T)) = (open (varF x) T).\nProof.\n  intros. eapply subst_open1_aux. simpl. eassumption.\nQed.\n\nLemma closed_open_tselh: forall j x T,\n                                closed j 0 (open_rec j (varH x) T) ->\n                                closed j 0 T.\nProof.\n  intros. generalize dependent j. induction T; intros; eauto.\n  - simpl in H. inversion H. subst.\n    apply cl_mem. apply IHT1. eassumption. apply IHT2. eassumption.\n  - destruct v.\n    + simpl. eauto.\n    + simpl in H. assumption.\n    + simpl in H.\n      case_eq (beq_nat j i0); intros E.\n      * rewrite E in H. inversion H. subst. omega.\n      * rewrite E in H. assumption.\n  - simpl in H. inversion H. subst.\n    apply cl_all. apply IHT1. eassumption. apply IHT2. eassumption.\n  - simpl in H. inversion H. subst.\n    apply cl_bind. apply IHT. eassumption.\n  - simpl in H. inversion H. subst.\n    apply cl_and. apply IHT1. eassumption. apply IHT2. eassumption.\n  - simpl in H. inversion H. subst.\n    apply cl_or. apply IHT1. eassumption. apply IHT2. eassumption.\nQed.\n\nLemma open_noop : forall i j T1 T0,\n                    closed i j T0 ->\n                    open_rec i T1 T0 = T0.\nProof.\n  intros. induction H; eauto.\n  - simpl. rewrite IHclosed_rec1. rewrite IHclosed_rec2. reflexivity.\n  - simpl. rewrite IHclosed_rec1. rewrite IHclosed_rec2. reflexivity.\n  - simpl. rewrite IHclosed_rec. reflexivity.\n  - simpl. rewrite IHclosed_rec1. rewrite IHclosed_rec2. reflexivity.\n  - simpl. rewrite IHclosed_rec1. rewrite IHclosed_rec2. reflexivity.\n  - simpl. assert (beq_nat k i = false) as E. {\n      apply false_beq_nat. omega.\n    }\n    rewrite E. reflexivity.\nQed.\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 \"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    remember H3 as Hv. clear HeqHv.\n    eapply IHn in H5. eapply sstpd2_untrans in H5. eapply valtp_widen with (2:=H5) in H3.\n    eapply invert_typ1 in H3. ev. repeat eu. subst.\n    assert (closed (0+1) (length ([]:aenv)) x2). eapply inv_closed_open. eapply stp2_closed2; eauto. eauto.\n    eexists. eapply stp2_strong_sel1. eauto.\n    eassumption. eapply stp2_wrapf. eassumption.\n    eauto. eauto. eauto. omega.\n  - Case \"sel2\".\n    remember H3 as Hv. clear HeqHv.\n    eapply IHn in H5. eapply sstpd2_untrans in H5. eapply valtp_widen with (2:=H5) in H3.\n    eapply invert_typ1 in H3. ev. repeat eu. subst.\n    assert (closed (0+1) (length ([]:aenv)) x2). eapply inv_closed_open. eapply stp2_closed2; eauto. eauto. eauto.\n    eexists. eapply stp2_strong_sel2. eauto.\n    eassumption. eapply stp2_wrapf. eassumption.\n    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 \"selab2\". 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 \"bind1\". subst.  eapply IHn in H3. inversion H3.\n    eexists. eapply stp2_bind1; eauto. omega.\n  - Case \"and11\". subst. eapply IHn in H1. inversion H1. eapply IHn in H2. inversion H2.\n    eexists. eapply stp2_and11; eauto. omega. omega.\n  - Case \"and12\". subst. eapply IHn in H1. inversion H1. eapply IHn in H2. inversion H2.\n    eexists. eapply stp2_and12; eauto. omega. omega.\n  - Case \"and2\". subst. eapply IHn in H1. inversion H1. eapply IHn in H2. inversion H2.\n    eexists. eapply stp2_and2; eauto. omega. omega.\n  - Case \"or21\". subst. eapply IHn in H1. inversion H1. eapply IHn in H2. inversion H2.\n    eexists. eapply stp2_or21; eauto. omega. omega.\n  - Case \"or22\". subst. eapply IHn in H1. inversion H1. eapply IHn in H2. inversion H2.\n    eexists. eapply stp2_or22; eauto. omega. omega.\n  - Case \"or1\". subst. eapply IHn in H1. inversion H1. eapply IHn in H2. inversion H2.\n    eexists. eapply stp2_or1; eauto. omega. omega.\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. apply 0. apply 0. \nQed.\n\n\n\n(* invert_typ lemmas are called from subst, so we need to inject subst capability *)\nDefinition can_subst n := forall ni, ni <= n -> forall (nj : nat) (m : bool) (G1 G2 : venv) (T1 T2 : ty)\n   (GH : list (id * (venv * ty))) (n1 : nat),\n stp2 1 m G1 T1 G2 T2 GH n1 ->\n n1 < nj ->\n forall (GH0 : list (nat * (venv * ty))) (GH0' : list (id * (venv * ty)))\n   (GX : venv) (TX : ty) (TX' : var) (l : id) (T1' T2' : ty) \n   (V : vl),\n GH = GH0 ++ [(0, (GX, TX))] ->\n val_type GX V (subst TX' TX) ni ->\n closed 0 1 TX ->\n closed 0 0 (TSel TX' l) ->\n compat GX TX TX' (Some V) G1 T1 T1' ->\n compat GX TX TX' (Some V) G2 T2 T2' ->\n Forall2 (compat2 GX TX TX' (Some V)) GH0 GH0' ->\n compat GX TX TX' (Some V) GX TX (subst TX' TX) ->\n exists n1' : nat, stp2 1 m G1 T1' G2 T2' GH0' n1'.\n\n\nLemma valtp_reg: forall G v T n,\n                   val_type G v T n ->\n                   sstpd2 true G T G T [].\nProof. intros. induction H; eapply sstpd2_reg2; eauto. Qed.\n\n(* TODO: following two lemmas could be generalized *)\n\n(* Hint Unfold peval. *)\n\nLemma invert_typ: forall n, can_subst n -> forall venv vx l G2 TX T1 T2 n1,\n  val_type venv vx TX (S n) -> stp2 0 true venv TX G2 (TMem l T1 T2) [] n1 ->                  \n  exists GY TY,\n    val_type GY vx TY 1 /\\  sstpd2 true GY TY G2 (TMem l T1 T2) [].\nProof.\n  intros n. induction n.\n  (* 1 *) intros CS. intros. eexists. eexists. split. eauto. eexists. eauto. \n  (* n *) intros CS. intros.\n  assert (val_type G2 vx (TMem l T1 T2) (S (S n))) as A. eapply valtp_widen. eauto. eexists. eauto.\n  inversion A. subst. \n\n  unfold peval in H2. ev.\n  inversion H1.\n  assert (stpd2 false venv1 (open (varF x) T0) G2 \n                (TMem l T1 T2) []) as XX.\n  eapply CS. eauto.\n  eapply H10. eauto. rewrite app_nil_l. eauto. simpl. rewrite subst_open1. eauto. eauto. eauto. eapply closed_open. eapply closed_upgrade_free. eauto. eauto. eauto. eauto.\n  \n  left. repeat eexists. eauto. eauto. simpl. rewrite subst_open1. eauto. eauto. rewrite subst_open1. eauto. eauto.\n  right. eauto.\n  eauto.\n  left. repeat eexists. eauto. eauto. simpl. rewrite subst_open1. eauto. eauto.\n  destruct XX.\n  \n  assert (sstpd2 true venv1 (open (varF x) T0) G2 (TMem l T1 T2) []) as YY.\n  eapply sstpd2_untrans. eapply stpd2_to_sstpd2_aux1. eauto. eauto.\n  destruct YY.\n\n  eapply IHn. intros ni no. apply CS. omega. eapply H3. eauto.\nGrab Existential Variables.\napply 0. apply 0.\nQed.\n\nLemma invert_all: forall n, can_subst n -> forall venv vx l G2 TX T1 T2 n1,\n  val_type venv vx TX (S n) -> stp2 0 true venv TX G2 (TAll l T1 T2) [] n1 ->                  \n  exists GY TY,\n    val_type GY vx TY 1 /\\  sstpd2 true GY TY G2 (TAll l T1 T2) [].\nProof.\n  intros n. induction n.\n  (* 1 *) intros CS. intros. eexists. eexists. split. eauto. eexists. eauto. \n  (* n *) intros CS. intros.\n  assert (val_type G2 vx (TAll l T1 T2) (S (S n))) as A. eapply valtp_widen. eauto. eexists. eauto.\n  inversion A. subst. \n\n  unfold peval in H2. ev.\n  inversion H1.\n  assert (stpd2 false venv1 (open (varF x) T0) G2 \n                (TAll l T1 T2) []) as XX.\n  eapply CS. eauto.\n  eapply H10. eauto. rewrite app_nil_l. eauto. simpl. rewrite subst_open1. eauto. eauto. eauto. eapply closed_open. eapply closed_upgrade_free. eauto. eauto. eauto. eauto.\n\n  left. repeat eexists. eauto. eauto. simpl. rewrite subst_open1. eauto. eauto. rewrite subst_open1. eauto. eauto.\n  right. eauto.\n  eauto.\n  left. repeat eexists. eauto. eauto. simpl. rewrite subst_open1. eauto. eauto.\n  destruct XX.\n  \n  assert (sstpd2 true venv1 (open (varF x) T0) G2 (TAll l T1 T2) []) as YY.\n  eapply sstpd2_untrans. eapply stpd2_to_sstpd2_aux1. eauto. eauto.\n  destruct YY.\n\n  eapply IHn. intros ni no. apply CS. omega. eapply H3. eauto.\nGrab Existential Variables.\napply 0. apply 0.\nQed.\n\n\nLemma invert_bind: forall n, can_subst n -> forall venv vx x G2 TX T1 n1,\n  peval x G2 vx ->                                              \n  val_type venv vx TX (S n) -> stp2 0 true venv TX G2 (TBind (T1)) [] n1 ->\n  exists n2, n2 <= n /\\ exists GY TY,\n    val_type GY vx TY n2 /\\  sstpd2 true GY TY G2 (open (varF x) (T1 )) [].\nProof.\n  intros n. induction n.\n  - (* 1 *)\n    intros CS. intros.\n    assert (val_type G2 vx (TBind T1) 1) as A. eapply valtp_widen. eauto. eexists. eauto.\n    inversion A; subst.\n    destruct H2. inversion H2.\n    destruct H6. \n    eapply dcs_tbind in H4. inversion H4. apply H3.\n    inversion H4.\n  - (* n *)\n    intros CS. intros.\n    assert (val_type G2 vx (TBind (T1)) (S (S n))) as A. eapply valtp_widen. eauto. eexists. eauto.\n    inversion A. subst. \n    \n    destruct H9. inversion H2.\n    + (* bindx *)\n      subst. clear A H2 H0 H1. unfold peval in H3. unfold peval in H. ev. \n      assert (stpd2 false venv1 (open (varF x0) T2) G2 (open (varF x) T1) []) as XX. eapply CS. eauto. eauto. eauto. rewrite app_nil_l. eauto. rewrite subst_open1. eauto. eauto. eapply closed_open. eapply closed_upgrade_free. eauto. eauto. eauto. eauto.\n      left. repeat eexists. eauto. eauto. simpl. rewrite subst_open1. eauto. eauto. rewrite subst_open1. eauto. eauto.\n      left. repeat eexists. eauto. eauto. simpl. rewrite subst_open1. eauto. eauto. rewrite subst_open1. eauto. eauto.\n      eauto.\n      left. repeat eexists. eauto. eauto. simpl. rewrite subst_open1. eauto. eauto.\n      destruct XX.\n\n      eexists. split. eauto. eexists. eexists. repeat split. eauto. eauto. eapply sstpd2_untrans. eapply stpd2_to_sstpd2_aux1. eauto. eauto. \n    + (* bind1 *)\n      subst. clear A H2 H0 H1. unfold peval in H3. unfold peval in H. ev. \n      \n    assert (stpd2 false venv1 (open (varF x0) T2) G2 \n                  (TBind T1) []) as XX.\n    eapply CS. eauto.\n    eapply H10. eauto. rewrite app_nil_l. eauto. simpl. rewrite subst_open1. eauto. eauto. eauto. eapply closed_open. eapply closed_upgrade_free. eauto. eauto. eauto. eauto.\n    \n    left. repeat eexists. eauto. eauto. simpl. rewrite subst_open1. eauto. eauto. rewrite subst_open1. eauto. eauto.\n    right. eauto.\n    eauto.\n    left. repeat eexists. eauto. eauto. simpl. rewrite subst_open1. eauto. eauto.\n    destruct XX.\n    \n    assert (sstpd2 true venv1 (open (varF x0) T2) G2 (TBind (T1)) []) as YY.\n    eapply sstpd2_untrans. eapply stpd2_to_sstpd2_aux1. eauto. eauto.\n    destruct YY.\n\n    eapply IHn in H4. destruct H4. destruct H4. exists x5. split. omega. eauto.\n    intros ni no. apply CS. omega. split. eauto. eauto. eauto. \nGrab Existential Variables.\napply 0. apply 0. apply 0. apply 0.\nQed.\n\n\n(* could/should this use invert_bind? *)\nLemma invert_typb: forall n, can_subst n -> forall venv vx x l G2 TX T1 T2 n1,\n  peval x G2 vx \\/ closed 0 0 (TMem l T1 T2) -> \n  val_type venv vx TX (S n) -> stp2 0 true venv TX G2 (TBind (TMem l T1 T2)) [] n1 ->\n  exists GY TY,\n    val_type GY vx TY 1 /\\  sstpd2 true GY TY G2 (open (varF x) (TMem l T1 T2 )) [].\nProof.\n   intros n. induction n.\n   - (* 1 *)\n     intros CS. intros.\n     assert (val_type G2 vx (TBind (TMem l T1 T2)) 1) as A. eapply valtp_widen. eauto. eexists. eauto.\n     inversion A; subst.\n     destruct H2. inversion H2.\n     destruct H6. \n     eapply dcs_tbind in H4. inversion H4. apply H3.\n     inversion H4.\n   - (* n *)\n     intros CS. intros.\n     assert (val_type G2 vx (TBind (TMem l T1 T2)) (S (S n))) as A. eapply valtp_widen. eauto. eexists. eauto.\n     inversion A. subst. \n     \n     destruct H9. inversion H2.\n     + (* bindx *)\n       subst. clear A H2 H0 H1. unfold peval in H3. ev. \n       assert (stpd2 false venv1 (open (varF x0) T0) G2 (open (varF x) (TMem l T1 T2)) []) as XX. eapply CS. eauto. eauto. eauto.\n       simpl. rewrite app_nil_l. eauto. rewrite subst_open1. eauto. eauto. eapply closed_open. eapply closed_upgrade_free. eauto. eauto. eauto. eauto. \n       left. repeat eexists. eauto. eauto. simpl. rewrite subst_open1. eauto. eauto. rewrite subst_open1. eauto. eauto.\n       { destruct H; unfold peval in H; ev. \n       * left. repeat eexists. eauto. eauto. simpl. rewrite subst_open1. eauto. eauto. rewrite subst_open1. eauto. eauto.\n       * right. left. unfold open. repeat erewrite <-closed_no_open. eauto. eauto. eauto.     }\n       eauto.\n       left. repeat eexists. eauto. eauto. simpl. rewrite subst_open1. eauto. eauto.\n       destruct XX.\n       eapply stpd2_to_sstpd2_aux1 in H2. eapply sstpd2_untrans in H2. destruct H2.\n\n       eapply invert_typ. intros ni no. eapply CS. instantiate (1:= n) in no. eauto. eauto. eauto. eauto. \n     + (* bind1 *)\n       subst. clear A H2 H0 H1. unfold peval in H3. ev. \n       \n       assert (stpd2 false venv1 (open (varF x0) T0) G2 \n                     (TBind (TMem l T1 T2)) []) as XX.\n       eapply CS. eauto.\n       eapply H10. eauto. rewrite app_nil_l. eauto. simpl. rewrite subst_open1. eauto. eauto. eauto. eapply closed_open. eapply closed_upgrade_free. eauto. eauto. eauto. eauto.\n                                                                                                            \n       left. repeat eexists. eauto. eauto. simpl. rewrite subst_open1. eauto. eauto. rewrite subst_open1. eauto. eauto.\n       right. eauto.\n       eauto.\n       left. repeat eexists. eauto. eauto. simpl. rewrite subst_open1. eauto. eauto.\n       destruct XX.\n     \n     assert (sstpd2 true venv1 (open (varF x0) T0) G2 (TBind (TMem l T1 T2)) []) as YY.\n     eapply sstpd2_untrans. eapply stpd2_to_sstpd2_aux1. eauto. eauto.\n     destruct YY.\n   \n     eapply IHn. intros ni no. apply CS. omega. eapply H. eauto. eauto.\n Grab Existential Variables.\n apply 0. apply 0. apply 0. apply 0.\nQed.\n\n\nLemma stp2_substitute_aux: forall ni nv, nv <= ni -> forall nj, forall m G1 G2 T1 T2 GH n1,\n   stp2 1 m G1 T1 G2 T2 GH n1 -> n1 < nj ->\n   forall GH0 GH0' GX TX TX' l T1' T2' V,\n     GH = (GH0 ++ [(0,(GX, TX))]) ->\n     val_type GX V (subst TX' TX) nv ->\n     (* When we're replacing binds from a pack/unpack sequence, the\n        type in GH may refer to itself (contain TSelH 0).\n        It should be safe for TX to refer to itself. *)\n     closed 0 1 TX ->\n     closed 0 0 (TSel TX' l) ->\n     compat GX TX TX' (Some V) G1 T1 T1' ->\n     compat GX TX TX' (Some V) G2 T2 T2' ->\n     Forall2 (compat2 GX TX TX' (Some V)) GH0 GH0' ->\n     compat GX TX TX' (Some V) GX TX (subst TX' TX) ->\n     exists n1', stp2 1 m G1 T1' G2 T2' GH0' n1'.\nProof.\n  intros ni. induction ni.\n  intros. inversion H. subst nv. inversion H3. (* ni=0 case: can't happen, invert val_type *)\n  intros nv NVX.\n  intros n. induction n; intros m G1 G2 T1 T2 GH n1 H ?. inversion H0.\n  inversion H; subst.\n  - Case \"topx\".\n    intros GH0 GH0' GXX TXX TXX' lX T1' T2' V ? VS CX ? IX1 IX2 FA IXH.\n    eapply compat_top in IX1.\n    eapply compat_top in IX2.\n    subst. eexists. eapply stp2_topx. eauto. eauto.\n\n  - Case \"botx\".\n    intros GH0 GH0' GXX TXX TXX' lX T1' T2' V ? VS CX ? IX1 IX2 FA IXH.\n    eapply compat_bot in IX1.\n    eapply compat_bot in IX2.\n    subst. eexists. eapply stp2_botx. eauto. eauto.\n\n  - Case \"top\".\n    intros GH0 GH0' GXX TXX TXX' lX T1' T2' V ? VS CX ? IX1 IX2 FA IXH.\n    eapply compat_top in IX2.\n    subst.\n    eapply IHn in H1. destruct H1.\n    eexists. eapply stp2_top. eauto. eauto. omega. \n    eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.\n    eauto.\n\n  - Case \"bot\".\n    intros GH0 GH0' GXX TXX TXX' lX T1' T2' V ? VS CX ? IX1 IX2 FA IXH.\n    eapply compat_bot in IX1.\n    subst.\n    eapply IHn in H1. destruct H1.\n    eexists. eapply stp2_bot. eauto. eauto. omega. \n    eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.\n    eauto.\n\n  - Case \"bool\".\n    intros GH0 GH0' GXX TXX TXX' lX T1' T2' V ? VS CX ? IX1 IX2 FA IXH.\n    eapply compat_bool in IX1.\n    eapply compat_bool in IX2.\n    subst. eexists. eapply stp2_bool; eauto.\n    eauto. eauto.\n\n  - Case \"mem\".\n    intros GH0 GH0' GXX TXX TXX' lX T1' T2' V ? VS CX ? IX1 IX2 FA IXH.\n    eapply compat_mem in IX1. repeat destruct IX1 as [? IX1].\n    eapply compat_mem in IX2. repeat destruct IX2 as [? IX2].\n    subst.\n    eapply IHn in H2. destruct H2.\n    eapply IHn in H3. destruct H3.\n    eexists. eapply stp2_mem2. eauto. eauto.\n    omega. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto. \n    omega. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto. \n    eauto. eauto.\n\n  - Case \"sel1\".\n    intros GH0 GH0' GXX TXX TXX' lX T1' T2' V ? VS CX ? IX1 IX2 FA IXH.\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 TXX' (Some V) G1 T1' GX TX) in IX1. repeat destruct IX1 as [? IX1].\n\n    assert (compat GXX TXX TXX' (Some V) GX TX TX) as CPX. right. left. eauto.\n\n    subst.\n    eapply IHn in H5. destruct H5.\n    eapply IHn in H6. destruct H6.\n    eexists.\n    eapply stp2_sel1. eauto. eauto. eauto.\n    eauto. eauto.\n    omega. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto. \n    omega. eauto. eauto. eauto. eauto. eauto. \n    eapply compat_mem_fwd2. eauto. eauto.\n    eauto.\n    eauto. eauto. eauto. eauto.\n\n  - Case \"sel2\".\n    intros GH0 GH0' GXX TXX TXX' lX T1' T2' V ? VS CX ? IX1 IX2 FA IXH.\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 TXX' (Some V) G2 T2' GX TX) in IX2. repeat destruct IX2 as [? IX2].\n\n    assert (compat GXX TXX TXX' (Some V) GX TX TX) as CPX. right. left. eauto.\n\n    subst.\n    eapply IHn in H5. destruct H5.\n    eapply IHn in H6. destruct H6.\n    eexists.\n    eapply stp2_sel2. eauto. eauto. eauto.\n    eauto. eauto.\n    omega. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto. \n    omega. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.\n    eapply compat_mem_fwd1. eauto. eauto. eauto.\n    eauto. eauto. eauto. eauto.\n\n  - Case \"selx\".\n\n    intros GH0 GH0' GXX TXX TXX' lX T1' T2' V ? VS CX ? IX1 IX2 FA IXH.\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 (varF x1) l). destruct IX1. ev. eauto. destruct H6. ev. auto. ev. eauto.\n    assert (T2' = TSel (varF x2) l). destruct IX2. ev. eauto. destruct H7. ev. auto. ev. eauto.\n\n    subst.\n    eexists.\n    eapply stp2_selx. eauto. eauto.\n\n  - Case \"sela1\". \n    intros GH0 GH0' GXX TXX TXX' lX T1' T2' V ? VS CX ? IX1 IX2 FA IXH.\n\n    assert (length (GU ++ GL) = length GH0 + 1). rewrite H1. eapply app_length.\n    assert (length GH0 = length GH0') as EL. eapply Forall2_length. eauto.\n\n    assert (compat GXX TXX TXX' (Some V) G1 (TSel (varH x) l) T1') as IXX. eauto.\n\n    eapply (compat_selh GXX TXX TXX' (Some V) G1 T1' GH0 GH0' GX TX) in IX1. repeat destruct IX1 as [? IX1].\n    destruct IX1.\n    + SCase \"x = 0\".\n      repeat destruct IXX as [|IXX]; ev.\n      * subst. simpl. inversion H11. subst.\n\n        assert (GL = [(0, (GXX, TXX))]) as EQGL. {\n          eapply proj2. eapply concat_same_length'. eassumption.\n          simpl. eassumption.\n        }\n        eapply IHn in H6. destruct H6.\n        eapply IHn in H7. destruct H7.\n        \n        assert (sstpd2 true GXX (subst TXX' TXX) G2 (TMem l TBot T2') []).\n        eapply sstpd2_untrans. eapply stpd2_to_sstpd2_aux1. eapply H6. eauto.\n        destruct H9.\n        \n        destruct nv. inversion VS. (* no 0 *)\n        eapply invert_typ in VS. destruct VS as [GY [TY [VS SM]]].\n\n        assert (closed 0 (length ([]:aenv)) TY). eapply sstpd2_closed1. apply SM.\n        eapply sstpd2_downgrade in SM. destruct SM as [? SM].\n\n\n        eexists. \n        eapply stp2_sel1. eauto. eauto. eauto. eapply stp2_extendH_mult0. eapply SM.\n        eauto. intros nx ny. apply IHni. omega. eauto.\n        \n        omega. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto. \n        omega. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.\n        erewrite app_nil_l. eauto.\n        eauto. eauto. eauto. eauto.\n        eapply compat_mem_fwd2. eauto.\n        eauto. eauto.\n      * subst. inversion H10. omega.\n      * subst. destruct H10. eauto.\n    + SCase \"x > 0\".\n      ev. subst.\n      assert (exists GH0L, GH0 = GU ++ GH0L /\\ GL = GH0L ++ [(0, (GXX, TXX))]) as EQGH. {\n        eapply exists_GH1L. eassumption. eassumption. simpl. omega.\n      }\n      destruct EQGH as [GH0L [EQGH0 EQGL]].\n      assert (exists GU' GL', GH0' = GU' ++ GL' /\\\n              Forall2 (compat2 GXX TXX TXX' (Some V)) GH0L GL') as EQGH'. {\n        rewrite EQGH0 in FA.\n        eapply Forall2_app_inv_l in FA.\n        destruct FA as [GU' [GL' [FAU [FAL EQFA]]]].\n        exists GU'. exists GL'. split; eassumption.\n      }\n      destruct EQGH' as [GU' [GL' [EQGH0' FAGL']]].\n\n      eapply IHn in H6. destruct H6.\n      eapply IHn in H7. destruct H7.\n      eexists.\n\n\n      assert (S (x - 1) = x) as A. {\n        destruct x. omega. (* contradiction *)\n        simpl. omega.\n      }\n      assert (x + 1 = (S x)) as B by omega. \n\n      eapply stp2_sela1. eauto.\n      rewrite A.\n      eapply closed_compat'. eauto.\n      eapply closed_upgrade_free. eauto. omega.\n      rewrite B. eassumption.\n      rewrite A. instantiate (1:=GL'). \n      assert (length GH0L = length GL') as L1. eapply Forall2_length; eauto.\n      assert (length GL = length GH0L + length [(0, (GXX, TXX))]) as L2.\n      rewrite <-app_length. subst GL. reflexivity. \n      rewrite L1 in L2. simpl in L2. rewrite H4 in L2. omega.\n      \n      eauto.\n      eauto.\n      eauto.\n      omega. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto. \n      omega. eauto. eauto. eauto. eauto. eauto. eapply compat_mem_fwd2. eauto. eauto. eauto.\n    (* remaining obligations *)\n    + eauto. + rewrite <-H1. eauto. + eauto. \n\n  - Case \"sela2\".                                    \n    intros GH0 GH0' GXX TXX TXX' lX T1' T2' V ? VS CX ? IX1 IX2 FA IXH.\n\n    assert (length (GU ++ GL) = length GH0 + 1). rewrite H1. eapply app_length.\n    assert (length GH0 = length GH0') as EL. eapply Forall2_length. eauto.\n\n    assert (compat GXX TXX TXX' (Some V) G2 (TSel (varH x) l) T2') as IXX. eauto.\n\n    eapply (compat_selh GXX TXX TXX' (Some V) G2 T2' GH0 GH0' GX TX) in IX2. repeat destruct IX2 as [? IX2].\n    destruct IX2.\n    + SCase \"x = 0\".\n      repeat destruct IXX as [|IXX]; ev.\n      * subst. simpl. inversion H11. subst.\n\n        assert (GL = [(0, (GXX, TXX))]) as EQGL. {\n          eapply proj2. eapply concat_same_length'. eassumption.\n          simpl. eassumption.\n        }\n        eapply IHn in H6. destruct H6.\n        eapply IHn in H7. destruct H7.\n        \n        assert (sstpd2 true GXX (subst TXX' TXX) G1 (TMem l T1' TTop) []).\n        eapply sstpd2_untrans. eapply stpd2_to_sstpd2_aux1. eapply H6. eauto.\n        destruct H9.\n        \n        destruct nv. inversion VS. (* no 0 *)\n        eapply invert_typ in VS. destruct VS as [GY [TY [VS SM]]].\n\n        assert (closed 0 (length ([]:aenv)) TY). eapply sstpd2_closed1. apply SM.\n        eapply sstpd2_downgrade in SM. destruct SM as [? SM].\n\n        eexists. \n        eapply stp2_sel2. eauto. eauto. eauto. eapply stp2_extendH_mult0. eapply SM.\n        eauto. intros nx ny. apply IHni. omega. eauto.\n        \n        omega. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto. \n        omega. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.\n        erewrite app_nil_l. eauto.\n        eauto. eauto. eauto. eauto.\n        eapply compat_mem_fwd1. eauto.\n        eauto. eauto.\n      * subst. inversion H10. omega.\n      * subst. destruct H10. eauto.\n    + SCase \"x > 0\".\n      ev. subst.\n      assert (exists GH0L, GH0 = GU ++ GH0L /\\ GL = GH0L ++ [(0, (GXX, TXX))]) as EQGH. {\n        eapply exists_GH1L. eassumption. eassumption. simpl. omega.\n      }\n      destruct EQGH as [GH0L [EQGH0 EQGL]].\n      assert (exists GU' GL', GH0' = GU' ++ GL' /\\\n              Forall2 (compat2 GXX TXX TXX' (Some V)) GH0L GL') as EQGH'. {\n        rewrite EQGH0 in FA.\n        eapply Forall2_app_inv_l in FA.\n        destruct FA as [GU' [GL' [FAU [FAL EQFA]]]].\n        exists GU'. exists GL'. split; eassumption.\n      }\n      destruct EQGH' as [GU' [GL' [EQGH0' FAGL']]].\n\n      eapply IHn in H6. destruct H6.\n      eapply IHn in H7. destruct H7.\n      eexists.\n\n\n      assert (S (x - 1) = x) as A. {\n        destruct x. omega. (* contradiction *)\n        simpl. omega.\n      }\n      assert (x + 1 = (S x)) as B by omega. \n\n      eapply stp2_sela2. eauto.\n      rewrite A.\n      eapply closed_compat'. eauto.\n      eapply closed_upgrade_free. eauto. omega.\n      rewrite B. eassumption.\n      rewrite A. instantiate (1:=GL'). \n      assert (length GH0L = length GL') as L1. eapply Forall2_length; eauto.\n      assert (length GL = length GH0L + length [(0, (GXX, TXX))]) as L2.\n      rewrite <-app_length. subst GL. reflexivity. \n      rewrite L1 in L2. simpl in L2. rewrite H4 in L2. omega.\n      \n      eauto.\n      eauto.\n      eauto.\n      omega. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto. \n      omega. eauto. eauto. eauto. eauto. eauto. eapply compat_mem_fwd1. eauto. eauto. eauto.\n    (* remaining obligations *)\n    + eauto. + rewrite <-H1. eauto. + eauto.\n                                      \n  - Case \"selab1\".\n    intros GH0 GH0' GXX TXX TXX' lX T1' T2' V ? VS CX ? IX1 IX2 FA IXH.\n\n    assert (length (GU ++ GL) = length GH0 + 1). rewrite H1. eapply app_length.\n    assert (length GH0 = length GH0') as EL. eapply Forall2_length. eauto.\n\n    assert (compat GXX TXX TXX' (Some V) G1 (TSel (varH x) l) T1') as IXX. eauto.\n\n    eapply (compat_selh GXX TXX TXX' (Some V) G1 T1' GH0 GH0' GX TX) in IX1. repeat destruct IX1 as [? IX1].\n\n    destruct IX1.\n    + SCase \"x = 0\". ev. subst.\n      repeat destruct IXX as [|IXX]; ev.\n      * subst. simpl. inversion H10. subst.\n\n        assert (GL = [(0, (GXX, TXX))]) as EQGL. {\n          eapply proj2. eapply concat_same_length'. eassumption.\n          simpl. eassumption.\n        }\n        assert (closed 0 0 (TBind (TMem l TBot T0))) as CL1. econstructor. econstructor. eauto. eapply closed_upgrade. eauto. eauto.\n\n        assert (stpd2 false GXX (subst TXX' TXX) G2 (TBind (TMem l TBot T0)) []). {\n          eapply IHn. eauto. omega. rewrite app_nil_l. eauto. eauto. eapply CX. eauto.\n          eauto.  right. left. split. eassumption. reflexivity.\n          eauto. eauto. \n        }\n        eu. \n        assert (stpd2 true G2 T2' G2 T2' GH0'). {\n          eapply IHn. apply H8. eauto. omega. eauto. eauto. eauto. eauto. eauto.\n          eauto. eauto. eauto. \n        }\n        eu. \n        assert (sstpd2 true GXX (subst TXX' TXX) G2 (TBind (TMem l TBot T0)) []).\n        eapply sstpd2_untrans. eapply stpd2_to_sstpd2_aux1. apply H13. eauto.\n        eu.\n\n        destruct IX2 as [IX2 | [IX2|IX2]]. (* TODO: clean this up. minimize duplication *)\n        (* 1 - subst *) {\n        repeat ev.\n        \n        destruct nv. inversion VS. (* no 0 *)\n        (* assert (exists GY TY, val_type GY x0 TY /\\ sstpd2 GY TY G2 (open (varF x2 *)\n        eapply invert_typb in VS. destruct VS as [GY [TY [VS SM]]]. \n\n        assert (closed 0 (length ([]:aenv)) TY). eapply sstpd2_closed1. apply SM.\n        eapply sstpd2_downgrade in SM. destruct SM as [? SM]. \n        unfold open in SM. instantiate (2:=TBot) in SM. simpl in SM. \n\n        eexists. \n        eapply stp2_sel1. eauto. eauto. eauto. eapply stp2_extendH_mult0. subst T2'.\n        rewrite subst_open1.\n        apply SM. eauto. eauto. eauto.\n        intros nx ny. apply IHni. omega. inversion H17. subst x6. eauto. eauto.\n        }\n        (* 2 - closed *) {\n        destruct nv. inversion VS. (* no 0 *)\n        (* assert (exists GY TY, val_type GY x0 TY /\\ sstpd2 GY TY G2 (open (varF x2 *)\n        eapply invert_typb in VS. destruct VS as [GY [TY [VS SM]]]. \n\n        assert (closed 0 (length ([]:aenv)) TY). eapply sstpd2_closed1. apply SM.\n        eapply sstpd2_downgrade in SM. destruct SM as [? SM]. \n        unfold open in SM. instantiate (2:=TBot) in SM. simpl in SM. \n\n        destruct IX2. eapply inv_closed_open0 in H17. unfold open in H18. erewrite <-closed_no_open in H18.\n          eexists.\n          eapply stp2_sel1. eauto. eauto. eauto. eapply stp2_extendH_mult0. subst T2'.\n          erewrite <-closed_no_open in SM. apply SM.\n          \n          eauto. eauto. eauto. eauto.\n          intros nx ny. apply IHni. omega. right. repeat econstructor. destruct IX2. eapply inv_closed_open0 in H16. apply H16. eauto. eauto.\n        }\n        (* 3 - nosubst *) {\n        destruct nv. inversion VS. (* no 0 *)\n        (* assert (exists GY TY, val_type GY x0 TY /\\ sstpd2 GY TY G2 (open (varF x2 *)\n        eapply invert_typb in VS. destruct VS as [GY [TY [VS SM]]]. \n\n        assert (closed 0 (length ([]:aenv)) TY). eapply sstpd2_closed1. apply SM.\n        eapply sstpd2_downgrade in SM. destruct SM as [? SM]. \n        unfold open in SM. instantiate (2:=TBot) in SM. simpl in SM. \n          eexists.\n          eapply stp2_sel1. eauto. eauto. eauto. eapply stp2_extendH_mult0. destruct IX2. subst T2'.\n          rewrite subst_open1. apply SM. eauto. eauto. eauto. \n          intros nx ny. apply IHni. omega. eauto. eauto. eauto. right. eauto. repeat econstructor.\n          destruct IX2. unfold open in H16.  eapply nosubst_zero_closed. eauto. eauto.\n          eauto.\n        }\n\n      * subst. inversion H9. omega.\n      * subst. destruct H9. eauto.\n\n    + SCase \"x > 0\".\n      ev. subst.\n      assert (exists GH0L, GH0 = GU ++ GH0L /\\ GL = GH0L ++ [(0, (GXX, TXX))]) as EQGH. {\n        eapply exists_GH1L. eassumption. eassumption. simpl. omega.\n      }\n      destruct EQGH as [GH0L [EQGH0 EQGL]].\n      assert (exists GU' GL', GH0' = GU' ++ GL' /\\\n              Forall2 (compat2 GXX TXX TXX' (Some V)) GH0L GL') as EQGH'. {\n        rewrite EQGH0 in FA.\n        eapply Forall2_app_inv_l in FA.\n        destruct FA as [GU' [GL' [FAU [FAL EQFA]]]].\n        exists GU'. exists GL'. split; eassumption.\n      }\n      destruct EQGH' as [GU' [GL' [EQGH0' FAGL']]].\n\n      remember (x-1) as x_1.\n      assert (S (x - 1) = x) as A. {\n        destruct x. omega. (* contradiction *)\n        simpl. omega.\n      }\n      assert (x + 1 = (S x)) as B by omega.\n      assert (x_1 + 1 = x) as C. {\n        omega.\n      }\n\n      assert (exists T0', T2' = open (varH x_1) T0' /\\ compat GXX TXX TXX' (Some V) G2 T0 T0') as CTO. {\n        destruct IX2 as [IX2 | [IX2 | IX2]].\n        repeat destruct IX2 as [|IX2]; ev.\n        inversion H13. subst x2.\n        eexists. split. unfold open. erewrite open_subst_commute. rewrite C. eauto. eauto.\n        left. eexists. eexists. eexists. repeat (split; eauto). \n        eexists. split. destruct IX2. eapply closed_no_open. subst T2'. eauto.\n        right. left. \n        destruct IX2. unfold open in H13. eapply inv_closed_open0 in H10. eauto. \n        erewrite <-closed_no_open in H13. eauto. eauto. omega.\n        eexists. split. destruct IX2. unfold open in H13. rewrite <- C in H13. erewrite <-open_subst_commute in H13. apply H13. eauto.\n        right. right. split.\n        destruct IX2. unfold open in H10. eapply nosubst_open_rev. eauto. simpl. omega. eauto.\n      }\n      ev.\n    \n      eapply IHn in H6. destruct H6.\n      eapply IHn in H8. destruct H8.\n\n      eexists.\n      eapply stp2_selab1. eauto.\n      eapply closed_compat'. eauto.\n      eapply closed_upgrade_free. eauto. omega.\n      rewrite C. eauto.\n\n      instantiate (1:=GL'). rewrite EQGL in H4. rewrite app_length in H4. simpl in H4.\n      rewrite NPeano.Nat.add_1_r in H4. inversion H4. rewrite Heqx_1.\n      erewrite <- Forall2_length; try eassumption. omega.\n      instantiate (1:=GU'). eassumption.\n\n      apply H6. eauto. eauto. omega. \n      eauto. eauto. eauto. eauto.\n\n      apply IX2. apply IX2. eauto. eauto. omega.\n      eauto. eauto. eauto. eauto. eauto. \n\n      (* compat GXX TXX TXX' (Some V) G2 (TBind (TMem l TBot T0)) (TBind (TMem l TBot x1)) *)\n      { destruct H13.\n      repeat ev. inversion H14. subst V. left. eexists. eexists. eexists. repeat (split; eauto). eauto. simpl. subst x1. eauto.\n      destruct H13. destruct H13. right. left. subst x1. split. repeat econstructor. eapply closed_upgrade. eauto. eauto. eauto.\n      destruct H13. right. right. subst x1. simpl. eauto. }\n\n      eauto. eauto.\n\n    (* remaining obligations *)\n    + eauto. + rewrite <- H1. eauto. + eauto.\n\n  - Case \"selab2\". \n    intros GH0 GH0' GXX TXX TXX' lX T1' T2' V ? VS CX ? IX1 IX2 FA IXH.\n\n    assert (length (GU ++ GL) = length GH0 + 1). rewrite H1. eapply app_length.\n    assert (length GH0 = length GH0') as EL. eapply Forall2_length. eauto.\n\n    assert (compat GXX TXX TXX' (Some V) G2 (TSel (varH x) l) T2') as IXX. eauto.\n\n    eapply (compat_selh GXX TXX TXX' (Some V) G2 T2' GH0 GH0' GX TX) in IX2. repeat destruct IX2 as [? IX2].\n    destruct IX2.\n    + SCase \"x = 0\". ev. subst.\n      repeat destruct IXX as [|IXX]; ev.\n      * subst. simpl. inversion H10. subst.\n\n        assert (GL = [(0, (GXX, TXX))]) as EQGL. {\n          eapply proj2. eapply concat_same_length'. eassumption.\n          simpl. eassumption.\n        }\n        assert (closed 0 0 (TBind (TMem l T0 TTop))) as CL1. econstructor. econstructor. eauto. eapply closed_upgrade. eauto. eauto.\n\n        assert (stpd2 false GXX (subst TXX' TXX) G1 (TBind (TMem l T0 TTop)) []). {\n          eapply IHn. eauto. omega. rewrite app_nil_l. eauto. eauto. eapply CX. eauto.\n          eauto.  right. left. split. eassumption. reflexivity.\n          eauto. eauto. \n        }\n        eu. \n        assert (stpd2 true G1 T1' G1 T1' GH0'). {\n          eapply IHn. apply H8. eauto. omega. eauto. eauto. eauto. eauto. eauto.\n          eauto. eauto. eauto. \n        }\n        eu. \n        assert (sstpd2 true GXX (subst TXX' TXX) G1 (TBind (TMem l T0 TTop)) []).\n        eapply sstpd2_untrans. eapply stpd2_to_sstpd2_aux1. apply H13. eauto.\n        eu.\n\n        destruct IX1 as [IX1 | [IX1|IX1]]. (* TODO: clean this up. minimize duplication *)\n        (* 1 - subst *) {\n        repeat ev.\n        \n        destruct nv. inversion VS. (* no 0 *)\n        (* assert (exists GY TY, val_type GY x0 TY /\\ sstpd2 GY TY G2 (open (varF x2 *)\n        eapply invert_typb in VS. destruct VS as [GY [TY [VS SM]]]. \n\n        assert (closed 0 (length ([]:aenv)) TY). eapply sstpd2_closed1. apply SM.\n        eapply sstpd2_downgrade in SM. destruct SM as [? SM]. \n        unfold open in SM. instantiate (1:=TTop) in SM. simpl in SM. \n\n        eexists. \n        eapply stp2_sel2. eauto. eauto. eauto. eapply stp2_extendH_mult0. subst T1'.\n        rewrite subst_open1.\n        apply SM. eauto. eauto. eauto.\n        intros nx ny. apply IHni. omega. inversion H17. subst x6. eauto. eauto.\n        }\n        (* 2 - closed *) {\n        destruct nv. inversion VS. (* no 0 *)\n        (* assert (exists GY TY, val_type GY x0 TY /\\ sstpd2 GY TY G2 (open (varF x2 *)\n        eapply invert_typb in VS. destruct VS as [GY [TY [VS SM]]]. \n\n        assert (closed 0 (length ([]:aenv)) TY). eapply sstpd2_closed1. apply SM.\n        eapply sstpd2_downgrade in SM. destruct SM as [? SM]. \n        unfold open in SM. instantiate (1:=TTop) in SM. simpl in SM. \n\n        destruct IX1. eapply inv_closed_open0 in H17. unfold open in H18. erewrite <-closed_no_open in H18.\n          eexists.\n          eapply stp2_sel2. eauto. eauto. eauto. eapply stp2_extendH_mult0. subst T1'.\n          erewrite <-closed_no_open in SM. apply SM.\n          \n          eauto. eauto. eauto. eauto.\n          intros nx ny. apply IHni. omega. right. repeat econstructor. destruct IX1. eapply inv_closed_open0 in H16. apply H16. eauto. eauto.\n        }\n        (* 3 - nosubst *) {\n        destruct nv. inversion VS. (* no 0 *)\n        (* assert (exists GY TY, val_type GY x0 TY /\\ sstpd2 GY TY G2 (open (varF x2 *)\n        eapply invert_typb in VS. destruct VS as [GY [TY [VS SM]]]. \n\n        assert (closed 0 (length ([]:aenv)) TY). eapply sstpd2_closed1. apply SM.\n        eapply sstpd2_downgrade in SM. destruct SM as [? SM]. \n        unfold open in SM. instantiate (1:=TTop) in SM. simpl in SM. \n          eexists.\n          eapply stp2_sel2. eauto. eauto. eauto. eapply stp2_extendH_mult0. destruct IX1. subst T1'.\n          rewrite subst_open1. apply SM. eauto. eauto. eauto. \n          intros nx ny. apply IHni. omega. eauto. eauto. eauto. right. eauto. repeat econstructor.\n          destruct IX1. unfold open in H16.  eapply nosubst_zero_closed. eauto. eauto.\n          eauto.\n        }\n\n      * subst. inversion H9. omega.\n      * subst. destruct H9. eauto.\n\n    + SCase \"x > 0\".\n      ev. subst.\n      assert (exists GH0L, GH0 = GU ++ GH0L /\\ GL = GH0L ++ [(0, (GXX, TXX))]) as EQGH. {\n        eapply exists_GH1L. eassumption. eassumption. simpl. omega.\n      }\n      destruct EQGH as [GH0L [EQGH0 EQGL]].\n      assert (exists GU' GL', GH0' = GU' ++ GL' /\\\n              Forall2 (compat2 GXX TXX TXX' (Some V)) GH0L GL') as EQGH'. {\n        rewrite EQGH0 in FA.\n        eapply Forall2_app_inv_l in FA.\n        destruct FA as [GU' [GL' [FAU [FAL EQFA]]]].\n        exists GU'. exists GL'. split; eassumption.\n      }\n      destruct EQGH' as [GU' [GL' [EQGH0' FAGL']]].\n\n      remember (x-1) as x_1.\n      assert (S (x - 1) = x) as A. {\n        destruct x. omega. (* contradiction *)\n        simpl. omega.\n      }\n      assert (x + 1 = (S x)) as B by omega.\n      assert (x_1 + 1 = x) as C. {\n        omega.\n      }\n\n      assert (exists T0', T1' = open (varH x_1) T0' /\\ compat GXX TXX TXX' (Some V) G1 T0 T0') as CTO. {\n        destruct IX1 as [IX1 | [IX1 | IX1]].\n        repeat destruct IX1 as [|IX1]; ev.\n        inversion H13. subst x2.\n        eexists. split. unfold open. erewrite open_subst_commute. rewrite C. eauto. eauto.\n        left. eexists. eexists. eexists. repeat (split; eauto). eauto.\n        eexists. split. destruct IX1. eapply closed_no_open. subst T1'. eauto.\n        right. left. \n        destruct IX1. unfold open in H13. eapply inv_closed_open0 in H10. eauto. \n        erewrite <-closed_no_open in H13. eauto. eauto. omega.\n        eexists. split. destruct IX1. unfold open in H13. rewrite <- C in H13. erewrite <-open_subst_commute in H13. apply H13. eauto.\n        right. right. split.\n        destruct IX1. unfold open in H10. eapply nosubst_open_rev. eauto. simpl. omega. eauto.\n      }\n      ev.\n    \n      eapply IHn in H6. destruct H6.\n      eapply IHn in H8. destruct H8.\n\n      eexists.\n      eapply stp2_selab2. eauto.\n      eapply closed_compat'. eauto.\n      eapply closed_upgrade_free. eauto. omega.\n      rewrite C. eauto.\n\n      instantiate (1:=GL'). rewrite EQGL in H4. rewrite app_length in H4. simpl in H4.\n      rewrite NPeano.Nat.add_1_r in H4. inversion H4. rewrite Heqx_1.\n      erewrite <- Forall2_length; try eassumption. omega.\n      instantiate (1:=GU'). eassumption.\n\n      apply H6. eauto. eauto. omega. \n      eauto. eauto. eauto. eauto.\n\n      apply IX1. apply IX1. eauto. eauto. omega.\n      eauto. eauto. eauto. eauto. eauto. \n\n      (* compat GXX TXX TXX' (Some V) G2 (TBind (TMem l TBot T0)) (TBind (TMem l TBot x1)) *)\n      { destruct H13.\n      repeat ev. inversion H14. subst V. left. eexists. eexists. eexists. repeat (split; eauto). eauto. simpl. subst x1. eauto.\n      destruct H13. destruct H13. right. left. subst x1. split. repeat econstructor. eapply closed_upgrade. eauto. eauto. eauto.\n      destruct H13. right. right. subst x1. simpl. eauto. }\n\n      eauto. eauto.\n\n    (* remaining obligations *)\n  + eauto. + rewrite <- H1. eauto. + eauto.\n\n\n  - Case \"selax\".\n\n    intros GH0 GH0' GXX TXX TXX' lX T1' T2' V ? VS CX ? IX1 IX2 FA IXH.\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 TXX' (Some V) G1 (TSel (varH x) l) T1') as IXX1. eauto.\n    assert (compat GXX TXX TXX' (Some V) G2 (TSel (varH x) l) T2') as IXX2. eauto.\n\n    eapply (compat_selh GXX TXX TXX' (Some V) G1 T1' GH0 GH0' GX TX) in IX1. repeat destruct IX1 as [? IX1].\n    eapply (compat_selh GXX TXX TXX' (Some V) G2 T2' GH0 GH0' GX TX) in IX2. repeat destruct IX2 as [? IX2].\n    assert (not (nosubst (TSel (varH 0) l))). unfold not. intros. simpl in H1. eauto.\n    assert (not (closed 0 0 (TSel (varH 0) l))). unfold not. intros. inversion H6. 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 H16. subst. inversion H8. subst.\n        simpl. eexists. eapply stp2_selx. subst. eauto. eauto.\n    + SCase \"x > 0\".\n      destruct IXX1; destruct IXX2; ev; subst; eexists; 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 TX' lX T1' T2' V ? VS CX ? IX1 IX2 FA IXH.\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 IHn in H1. destruct H1.\n    eapply IHn in H4. destruct H4.\n    eapply IHn in H5. destruct H5.\n    eexists.\n    eapply stp2_all.\n    eauto.\n    eauto.\n    eauto.\n    eauto.\n    eauto.\n    omega. eauto.\n    instantiate (3:= (0, (G2, T4))::GH0). reflexivity.\n    eauto. eapply CX. 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    omega.\n      change ((0, (G1, T0)) :: GH0 ++ [(0, (GX, TX))]) with\n      (((0, (G1, T0)) :: GH0) ++ [(0, (GX, TX))]).\n      reflexivity.\n      eauto. eapply CX. 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.\n    omega.\n      eauto. eauto. eauto. eauto. eauto. eauto. eauto. 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 TX' lX T1' T2' V ? VS CX ? IX1 IX2 FA IXH.\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 IHn in H3. destruct H3.\n    eapply IHn in H4. destruct H4.\n    eexists.\n    eapply stp2_bind.\n    eauto.\n    eauto.\n    eauto.\n    eauto.\n    omega.\n      instantiate (3:=(0, (G1,  open (varH (length (GH0 ++ [(0, (GX, TX))]))) T0))::GH0).\n      reflexivity.\n      eauto. eapply CX. 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    omega.\n      change\n        ((0, (G2, open (varH (length (GH0 ++ [(0, (GX, TX))]))) T3))\n           :: GH0 ++ [(0, (GX, TX))]) with\n      (((0, (G2, open (varH (length (GH0 ++ [(0, (GX, TX))]))) T3))\n          :: GH0) ++ [(0, (GX, TX))]).\n      reflexivity.\n      eauto. eapply CX. 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      eauto.\n    eauto.\n    eauto. subst GH. fold id. rewrite <- EL.\n    eapply closed_upgrade_free. eauto. unfold id in H4.\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 H4.\n      rewrite app_length. simpl. omega.\n\n  - Case \"bind1\".\n    intros GH0 GH0' GX TX TX' lX T1' T2' V ? VS CX ? IX1 IX2 FA IXH.\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 IHn in H3. destruct H3.\n    eapply IHn in H4. destruct H4.\n\n    assert (closed 0 (length GH0') T2'). {\n      eapply stp2_closed1. eapply H3.  \n    }\n    \n    eexists.\n    eapply stp2_bind1.\n    eauto.\n    eauto. \n    eauto.\n    eauto.\n    omega.\n      instantiate (3:=(0, (G1,  open (varH (length (GH0 ++ [(0, (GX, TX))]))) T0))::GH0).\n      reflexivity.\n      eauto. eapply CX. eauto.\n      rewrite app_length. simpl. rewrite EL. eauto.\n      eauto. eauto. \n      eapply Forall2_cons. simpl. eauto. eauto. repeat split. rewrite app_length. simpl. rewrite EL. eapply IX1. eauto.\n      eauto.\n    omega.\n      reflexivity.\n      eauto. eapply CX. eauto.\n      eauto. eauto. eauto. eauto. eauto. \n    eapply closed_upgrade_free. eauto. unfold id in H5. omega. \n      \n  - Case \"and11\".\n    intros GH0 GH0' GXX TXX TXX' lX T1' T2' V ? VS CX ? IX1 IX2 FA IXH.\n    subst. apply compat_and in IX1. repeat destruct IX1 as [? IX1].\n    eapply IHn in H1. destruct H1.\n    eapply IHn in H2. destruct H2.\n    eexists.\n    subst. eapply stp2_and11; eassumption.\n    omega. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.\n    omega. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.\n    eauto.\n  - Case \"and12\".\n    intros GH0 GH0' GXX TXX TXX' lX T1' T2' V ? VS CX ? IX1 IX2 FA IXH.\n    subst. apply compat_and in IX1. repeat destruct IX1 as [? IX1].\n    eapply IHn in H1. destruct H1.\n    eapply IHn in H2. destruct H2.\n    eexists.\n    subst. eapply stp2_and12; eassumption.\n    omega. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.\n    omega. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.\n    eauto.\n  - Case \"and2\".\n    intros GH0 GH0' GXX TXX TXX' lX T1' T2' V ? VS CX ? IX1 IX2 FA IXH.\n    subst. apply compat_and in IX2. repeat destruct IX2 as [? IX2].\n    eapply IHn in H1. destruct H1.\n    eapply IHn in H2. destruct H2.\n    eexists.\n    subst. eapply stp2_and2. eapply H1. eapply H2.\n    omega. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.\n    omega. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.\n    eauto.\n\n  - Case \"or21\".\n    intros GH0 GH0' GXX TXX TXX' lX T1' T2' V ? VS CX ? IX1 IX2 FA IXH.\n    subst. apply compat_or in IX2. repeat destruct IX2 as [? IX2].\n    eapply IHn in H1. destruct H1.\n    eapply IHn in H2. destruct H2.\n    eexists.\n    subst. eapply stp2_or21; eassumption.\n    omega. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.\n    omega. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.\n    eauto.\n  - Case \"or22\".\n    intros GH0 GH0' GXX TXX TXX' lX T1' T2' V ? VS CX ? IX1 IX2 FA IXH.\n    subst. apply compat_or in IX2. repeat destruct IX2 as [? IX2].\n    eapply IHn in H1. destruct H1.\n    eapply IHn in H2. destruct H2.\n    eexists.\n    subst. eapply stp2_or22; eassumption.\n    omega. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.\n    omega. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.\n    eauto.\n  - Case \"or1\".\n    intros GH0 GH0' GXX TXX TXX' lX T1' T2' V ? VS CX ? IX1 IX2 FA IXH.\n    subst. apply compat_or in IX1. repeat destruct IX1 as [? IX1].\n    eapply IHn in H1. destruct H1.\n    eapply IHn in H2. destruct H2.\n    eexists.\n    subst. eapply stp2_or1. eapply H1. eapply H2.\n    omega. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.\n    omega. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.\n    eauto.\n\n  - Case \"wrapf\".\n    intros. subst.\n    eapply IHn in H1. destruct H1.\n    eexists.\n    eapply stp2_wrapf. eauto.\n    omega. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.\n\n  - Case \"transf\".\n    intros. subst.\n\n    assert (exists T3',\n              compat GX TX TX' (Some V) ((fresh G3,V)::G3) T3 T3') as A.\n    {\n      eexists.\n      unfold compat. simpl. left. exists (tvar (fresh G3)). exists V. exists nv.\n      split. eapply index_to_peval. eapply index_hit2; eauto.\n      split; try split; try split; try split; eauto.\n    }\n    destruct A as [T3' A].\n\n    assert (stp2 1 true G1 T1 ((fresh G3,V)::G3) T3 (GH0 ++ [(0, (GX, TX))]) n0) as S1.\n    eapply stp2_extend2; eauto.\n    assert (stp2 1 false ((fresh G3,V)::G3) T3 G2 T2 (GH0 ++ [(0, (GX, TX))]) n2) as S2.\n    eapply stp2_extend1; eauto.\n\n    eapply IHn in S1. destruct S1 as [? S1].\n    eapply IHn in S2. destruct S2 as [? S2].\n    eexists.\n    eapply stp2_transf. eapply S1. eapply S2.\n    omega. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.\n    omega. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.\n\nGrab Existential Variables.\napply 0. apply 0. apply 0. apply 0. apply 0. apply 0. apply 0. apply 0. apply 0. apply 0.\napply tvar. apply 0. apply 0. apply 0. apply 0. apply 0. apply 0.\napply tvar. apply 0. apply 0. apply 0. apply 0. apply 0.\n(*apply 0. apply 0. apply 0. apply 0. apply 0. apply 0.*)\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 TX' l T1' T2' V n,\n     GH = (GH0 ++ [(0,(GX, TX))]) ->\n     val_type GX V (subst TX' TX) n ->\n     closed 0 1 TX ->\n     closed 0 0 (TSel TX' l) ->\n     compat GX TX TX' (Some V) G1 T1 T1' ->\n     compat GX TX TX' (Some V) G2 T2 T2' ->\n     compat GX TX TX' (Some V) GX TX (subst TX' TX) ->\n     Forall2 (compat2 GX TX TX' (Some V)) GH0 GH0' ->\n     stpd2 m G1 T1' G2 T2' GH0'.\nProof. intros. repeat eu. eapply stp2_substitute_aux; eauto. Qed.\n\n(* end substitute *)\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_aux1; 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\n(* --------------------------------- *)\n\nHint Constructors wf_envh.\n\nLemma exists_GYL: forall GX GY GU GL,\n  wf_envh GX GY (GU ++ GL) ->\n  exists GYU GYL, GY = GYU ++ GYL /\\ wf_envh GX GYL GL.\nProof.\n  intros. remember (GU ++ GL) as G. generalize dependent HeqG. generalize dependent GU. generalize dependent GL. induction H; intros.\n  - exists []. exists []. simpl. split. reflexivity. symmetry in HeqG. apply app_eq_nil in HeqG.\n    inversion HeqG. subst. eauto.\n  - induction GU.\n    + rewrite app_nil_l in HeqG.\n      exists []. eexists. rewrite app_nil_l. split. reflexivity.\n      rewrite <- HeqG. eauto.\n    + simpl in HeqG. inversion HeqG.\n      specialize (IHwf_envh GL GU H2). destruct IHwf_envh as [GYU [GYL [IHA IHB]]].\n      exists ((n, (vvs, t))::GYU). exists GYL. split. rewrite IHA. simpl. reflexivity.\n      apply IHB.\nQed.\n\n\n(* TODO: need to revisit if stp includes trans rule.\n   if yes, probably need to return stpd2 false, and\n   call untrans after recursive calls. but need to be\n   careful since we can only untrans with GH=nil  *)\nLemma stp_to_stp2_aux: 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 true GX T1 GX T2 GY.\nProof.\n  intros G1 G2 T1 T2 ST. induction ST; intros GX GY WX WY.\n  - Case \"topx\". eapply stpd2_topx.\n  - Case \"botx\". eapply stpd2_botx.\n  - Case \"top\".\n    eapply stpd2_top.\n    specialize (IHST GX GY WX WY).\n    apply stpd2_reg2 in IHST.\n    apply IHST.\n  - Case \"bot\".\n    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 \"mem\". eapply stpd2_mem; eapply stpd2_wrapf; eauto.\n  - Case \"sel1\".\n    assert (exists (v : vl) n, index x GX = Some v /\\ val_type GX v TX n) as A.\n    eapply index_safe_ex. eauto. eauto.    \n    destruct A as [v [? [IX VT]]].\n    assert (peval (tvar x) GX v) as EV. eapply index_to_peval; eauto.\n    edestruct IHST1; eauto. eapply stpd2_to_sstpd2_aux1 in H1. destruct H1.\n    destruct x0. inversion VT.\n    eapply invert_typ in VT. destruct VT as [GZ [TZ [VT SM]]].\n    eapply stpd2_sel1. eauto. eauto. eapply valtp_closed; eauto.\n    eapply sstpd2_downgrade. eauto. eapply sstpd2_extendH_mult0. apply SM.\n    apply IHST2; eauto.\n    intros n. apply stp2_substitute_aux. eauto. eauto.\n  - Case \"sel2\". \n    assert (exists (v : vl) n, index x GX = Some v /\\ val_type GX v TX n) as A.\n    eapply index_safe_ex. eauto. eauto.\n    destruct A as [v [? [IX VT]]].\n    assert (peval (tvar x) GX v) as EV. eapply index_to_peval; eauto.\n    edestruct IHST1; eauto. eapply stpd2_to_sstpd2_aux1 in H1. destruct H1. \n    destruct x0. inversion VT.\n    eapply invert_typ in VT. destruct VT as [GZ [TZ [VT SM]]].\n    eapply stpd2_sel2. eauto. eauto. eapply valtp_closed; eauto.\n    eapply sstpd2_downgrade. eauto. eapply sstpd2_extendH_mult0. apply SM.\n    apply IHST2; eauto.\n    intros n. apply stp2_substitute_aux. eauto. eauto.\n  - Case \"selb1\". \n    (* replace x: {z => ..U }  U < T2  by x: (.. U)  U < T *)\n    (* previously, there was a separate stp2 level for this *)\n    assert (exists (v : vl) n, index x GX = Some v /\\ val_type GX v TX n) as A.\n    eapply index_safe_ex. eauto. eauto.\n    destruct A as [v [? [IX VT]]].\n    assert (peval (tvar x) GX v) as EV. eapply index_to_peval; eauto.\n    edestruct IHST1; eauto. eapply stpd2_to_sstpd2_aux1 in H0. destruct H0. \n    destruct x0. inversion VT.\n    eapply invert_typb in VT. destruct VT as [GZ [TZ [VT SM]]].\n    eapply stpd2_sel1. eauto. eauto. eapply valtp_closed; eauto.\n    eapply sstpd2_downgrade. eauto. eapply sstpd2_extendH_mult0.\n    instantiate (2:= TBot) in SM. unfold open in SM. simpl in SM. apply SM.\n    apply IHST2; eauto.\n    intros n. apply stp2_substitute_aux. eauto. eauto. eauto.\n  - Case \"selb2\".\n    assert (exists (v : vl) n, index x GX = Some v /\\ val_type GX v TX n) as A.\n    eapply index_safe_ex. eauto. eauto.\n    destruct A as [v [? [IX VT]]].\n    assert (peval (tvar x) GX v) as EV. eapply index_to_peval; eauto.\n    edestruct IHST1; eauto. eapply stpd2_to_sstpd2_aux1 in H0. destruct H0. \n    destruct x0. inversion VT.\n    eapply invert_typb in VT. destruct VT as [GZ [TZ [VT SM]]].\n    eapply stpd2_sel2. eauto. eauto. eapply valtp_closed; eauto.\n    eapply sstpd2_downgrade. eauto. eapply sstpd2_extendH_mult0.\n    instantiate (1:= TTop) in SM. unfold open in SM. simpl in SM. apply SM.\n    apply IHST2; eauto.\n    intros n. apply stp2_substitute_aux. eauto. eauto. eauto.\n  - Case \"selx\".\n    assert (exists (v : vl) n, index x GX = Some v /\\ val_type GX v TX n) as A.\n    eapply index_safe_ex. eauto. eauto.\n    destruct A as [v [? [IX VT]]].\n    assert (peval (tvar x) GX v) as EV. eapply index_to_peval; eauto.\n    eapply stpd2_selx. eauto. eauto.\n  - Case \"sela1\".\n    remember ((0,TX)::GL) as GL1. assert (length GL1 = S (length GL)) as LE. subst GL1. eauto. \n    assert (indexr x GH = Some TX /\\ length GL = x /\\ exists GU, GH = GU ++ GL1). subst GL1. eapply tailr_to_indexr. eauto. ev. \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    remember ((0,TX)::GL) as GL1. \n    assert (exists GYU GYL, GY = GYU ++ GYL /\\ wf_envh GX GYL GL1) as EQG. {\n      eapply exists_GYL. eassumption.\n    }\n    destruct EQG as [GYU [GYL [EQY WYL]]].\n    eapply stpd2_sela1. eauto. rewrite <-LE. eapply (stp_closed _ _ TX (TMem _ _ _)). eauto.\n    instantiate (1:=GYL). erewrite wfh_length. apply LE.  eassumption. eassumption.\n    eapply stpd2_wrapf. eapply IHST1. eauto. eauto.\n    specialize (IHST2 _ _ WX WY).\n    apply stpd2_reg2 in IHST2.\n    apply IHST2.\n  - Case \"sela2\".\n    remember ((0,TX)::GL) as GL1. assert (length GL1 = S (length GL)) as LE. subst GL1. eauto. \n    assert (indexr x GH = Some TX /\\ length GL = x /\\ exists GU, GH = GU ++ GL1). subst GL1. eapply tailr_to_indexr. eauto. ev.\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    remember ((0,TX)::GL) as GL1. \n    assert (exists GYU GYL, GY = GYU ++ GYL /\\ wf_envh GX GYL GL1) as EQG. {\n      eapply exists_GYL. eassumption.\n    }\n    destruct EQG as [GYU [GYL [EQY WYL]]].\n    eapply stpd2_sela2. eauto. eauto. rewrite <-LE. eapply (stp_closed _ _ TX (TMem _ _ _)). eauto.\n    instantiate (1:=GYL). erewrite wfh_length. apply LE. eassumption. eassumption.\n    eapply stpd2_wrapf. eapply IHST1. eauto. eauto.\n    specialize (IHST2 _ _ WX WY).\n    apply stpd2_reg2 in IHST2.\n    apply IHST2.\n  - Case \"selab1\".\n    remember ((0,TX)::GL) as GL1. assert (length GL1 = S (length GL)) as LE. subst GL1. eauto. \n    assert (indexr x GH = Some TX /\\ length GL = x /\\ exists GU, GH = GU ++ GL1). subst GL1. eapply tailr_to_indexr. eauto. ev.\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    remember ((0,TX)::GL) as GL1. \n    assert (exists GYU GYL, GY = GYU ++ GYL /\\ wf_envh GX GYL GL1) as EQG. {\n      eapply exists_GYL. eassumption.\n    }\n    destruct EQG as [GYU [GYL [EQY WYL]]].\n    eapply stpd2_selab1. eauto. instantiate (1:= T2). inversion H0. inversion H6. eauto.\n    instantiate (1:=GYL). erewrite wfh_length. apply LE. eassumption. eassumption.\n    eapply stpd2_wrapf. eapply IHST1. eauto. eauto.\n    specialize (IHST2 _ _ WX WY). reflexivity.\n    apply IHST2; eauto.\n  - Case \"selab2\".\n    remember ((0,TX)::GL) as GL1. assert (length GL1 = S (length GL)) as LE. subst GL1. eauto. \n    assert (indexr x GH = Some TX /\\ length GL = x /\\ exists GU, GH = GU ++ GL1). subst GL1. eapply tailr_to_indexr. eauto. ev.\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    remember ((0,TX)::GL) as GL1. \n    assert (exists GYU GYL, GY = GYU ++ GYL /\\ wf_envh GX GYL GL1) as EQG. {\n      eapply exists_GYL. eassumption.\n    }\n    destruct EQG as [GYU [GYL [EQY WYL]]].\n    eapply stpd2_selab2. eauto. instantiate (1:= T1). inversion H0. inversion H6. eauto.\n    instantiate (1:=GYL). erewrite wfh_length. eassumption. eassumption.\n    eassumption.\n    eapply stpd2_wrapf. eapply IHST1. eauto. eauto.\n    specialize (IHST2 _ _ WX WY). reflexivity.\n    apply IHST2; eauto.\n  - Case \"selax\".\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.\n    eapply stpd2_wrapf. eauto.\n    rewrite H. eauto. rewrite H.  eauto.\n    rewrite H.\n    eapply stpd2_wrapf. eapply IHST2. eauto. eapply wfeh_cons. eauto.\n    rewrite H.\n    eapply stpd2_wrapf. 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 stpd2_wrapf. eapply IHST1. eauto. eapply wfeh_cons. eauto.\n    rewrite H.\n    eapply stpd2_wrapf. eapply IHST2; eauto.\n  - Case \"bind1\".\n    subst x. assert (length GY = length GH). eapply wfh_length; eauto.\n    eapply stpd2_bind1. rewrite H. eauto. rewrite H. eauto.\n    eapply stpd2_wrapf. eapply IHST1. eauto. eauto.\n    rewrite H.\n    eapply stpd2_wrapf. eapply IHST2; eauto.\n    \n  - Case \"and11\".\n    eapply stpd2_and11.\n    eapply IHST1; eauto.\n    eapply IHST2; eauto.\n  - Case \"and12\".\n    eapply stpd2_and12.\n    eapply IHST1; eauto.\n    eapply IHST2; eauto.\n  - Case \"and2\".\n    eapply stpd2_and2.\n    eapply stpd2_wrapf. eapply IHST1; eauto.\n    eapply stpd2_wrapf. eapply IHST2; eauto.\n  - Case \"or21\".\n    eapply stpd2_or21.\n    eapply stpd2_wrapf. eapply IHST1; eauto.\n    eapply IHST2; eauto.\n  - Case \"or22\".\n    eapply stpd2_or22.\n    eapply stpd2_wrapf. eapply IHST1; eauto.\n    eapply IHST2; eauto.\n  - Case \"or1\".\n    eapply stpd2_or1.\n    eapply IHST1; eauto.\n    eapply IHST2; eauto.\nGrab Existential Variables.\n(*apply 0. apply 0. apply 0. apply 0.*)\nQed.\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.\n  intros. eapply stpd2_wrapf. eapply stp_to_stp2_aux; eauto.\nQed.\n\n\nInductive wf_tp: tenv -> tenv -> ty -> Prop :=\n| wf_top: forall G1 GH,\n    wf_tp G1 GH TTop\n| wf_bot: forall G1 GH,\n    wf_tp G1 GH TBot\n| wf_bool: forall G1 GH,\n    wf_tp G1 GH TBool\n| wf_mem: forall G1 GH l T1 T2,\n    wf_tp G1 GH T1 ->\n    wf_tp G1 GH T2 ->\n    wf_tp G1 GH (TMem l T1 T2)\n| wf_sel: forall G1 GH TX x l,\n    index x G1 = Some TX ->\n    wf_tp G1 GH (TSel (varF (tvar x)) l)\n| wf_sela: forall G1 GH TX x l,\n    indexr x GH = Some TX  ->\n    wf_tp G1 GH (TSel (varH x) l)\n| wf_all: forall G1 GH m T1 T2 x,\n    wf_tp G1 GH T1 ->\n    x = length GH ->\n    closed 1 (length GH) T2 ->\n    wf_tp G1 ((0,T1)::GH) (open (varH x) T2) ->\n    wf_tp G1 GH (TAll m T1 T2)\n| wf_bind: forall G1 GH T1 x,\n    x = length GH ->\n    closed 1 (length GH) T1 ->\n    wf_tp G1 ((0,open (varH x) T1)::GH) (open (varH x) T1) ->\n    wf_tp G1 GH (TBind T1)\n| wf_and: forall G1 GH T1 T2,\n    wf_tp G1 GH T1 ->\n    wf_tp G1 GH T2 ->\n    wf_tp G1 GH (TAnd T1 T2)\n| wf_or: forall G1 GH T1 T2,\n    wf_tp G1 GH T1 ->\n    wf_tp G1 GH T2 ->\n    wf_tp G1 GH (TOr T1 T2)\n.\nHint Constructors wf_tp.\n\nLemma stp_to_wf_tp_aux: forall G GH T1 T2,\n                          stp G GH T1 T2 ->\n                          wf_tp G GH T1 /\\ wf_tp G GH T2.\nProof.\n  intros. induction H;\n    try solve [repeat ev; split; eauto; try (eapply wf_sela; eapply tailr_to_indexr; eauto)].\nQed.\n\nLemma stp_to_wf_tp: forall G GH T,\n                      stp G GH T T ->\n                      wf_tp G GH T.\nProof.\n  intros. apply (proj1 (stp_to_wf_tp_aux G GH T T H)).\nQed.\n\nLemma wf_tp_to_stp2_cycle_aux: forall T0 T v G GH,\n  wf_tp ((fresh G, T0) :: G) GH T ->\n  forall GX GY, wf_env GX G -> wf_envh ((fresh G, v)::GX) GY GH ->\n  stpd2 true ((fresh G, v) :: GX) T\n             ((fresh G, v) :: GX) T GY.\nProof.\n  intros T0 T t G GH ST.\n  dependent induction ST; intros GX GY WX WY.\n  - Case \"top\". eapply stpd2_topx.\n  - Case \"bot\". eapply stpd2_botx.\n  - Case \"bool\". eapply stpd2_bool; eauto.\n  - Case \"mem\". eapply stpd2_mem; eapply stpd2_wrapf; eauto.\n  - Case \"selx\".\n    assert (exists v, index x ((fresh G, t) :: GX) = Some v) as A. {\n      simpl. simpl in H.\n      case_eq (le_lt_dec (fresh G) (fresh G)); intros E1 LE1.\n      rewrite (wf_fresh GX G). rewrite LE1. rewrite LE1 in H.\n      case_eq (beq_nat x (fresh G)); intros E2.\n      eexists. reflexivity.\n      eapply index_exists. eapply WX. rewrite E2 in H. eapply H.\n      assumption.\n      omega.\n    }\n    destruct A as [v A].\n    assert (peval (tvar x) ((fresh G, t) :: GX) v) as B. eapply index_to_peval; eauto.\n    eapply stpd2_selx; eapply B.\n  - Case \"selax\".\n    assert (exists v, indexr x GY = Some v) as A. {\n      eapply indexr_exists; eauto.\n    }\n    destruct A as [v A]. destruct v.\n    eapply stpd2_selax. eassumption.\n  - Case \"all\".\n    assert (length GY = length GH) as A. { eapply wfh_length; eauto. }\n    eapply stpd2_all.\n    eapply stpd2_wrapf. eapply IHST1; eauto.\n    rewrite A. eauto.\n    rewrite A. eauto.\n    rewrite A. eapply stpd2_wrapf. eapply IHST2; eauto.\n    rewrite A. eapply stpd2_wrapf. eapply IHST2; eauto.\n  - Case \"bind\".\n    assert (length (GY:aenv) = length GH) as A. { eapply wfh_length; eauto. }\n    assert (closed 1 (length GY) T1) by solve [rewrite A; eauto].\n    eapply stpd2_bind; try eassumption.\n    rewrite <- A in IHST. eapply stpd2_wrapf. eapply IHST; eauto.\n    rewrite <- A in IHST. eapply stpd2_wrapf. eapply IHST; eauto.\n  - Case \"and\".\n    eapply stpd2_and2; eapply stpd2_wrapf.\n    eapply stpd2_and11. eapply IHST1; eauto. eapply IHST2; eauto.\n    eapply stpd2_and12. eapply IHST2; eauto. eapply IHST1; eauto.\n  - Case \"or\".\n    eapply stpd2_or1.\n    eapply stpd2_or21. eapply stpd2_wrapf. eapply IHST1; eauto. eapply IHST2; eauto.\n    eapply stpd2_or22. eapply stpd2_wrapf. eapply IHST2; eauto. eapply IHST1; eauto.\nQed.\n\nLemma stp_to_stp2_cycle: forall venv env T0 T t,\n  wf_env venv env ->\n  stp ((fresh env, T0) :: env) [] T T->\n  stpd2 false ((fresh env, vobj venv (fresh venv) t) :: venv) T\n              ((fresh env, vobj venv (fresh venv) t) :: venv) T [].\nProof.\n  intros. apply stpd2_wrapf.\n  eapply stp_to_wf_tp in H0.\n  eapply wf_tp_to_stp2_cycle_aux; eauto.\nQed.\n\nLemma dcs_has_type_stp: forall G G1 G2 f ds x T T1 T2,\n  dcs_has_type G f ds T ->\n  sstpd2 true G1 (open (varF x) T) G2 (TAll (length ds) T1 T2) [] ->\n  False.\nProof.\n  intros. remember (length ds) as l. assert (l >= length ds) as A by omega. clear Heql.\n  induction H. simpl in H0. destruct H0 as [? H0]. inversion H0.\n  destruct (tand_shape (TAll m T0 T3) TS).\n  rewrite H5 in H4. rewrite H4 in H0. simpl in H0. destruct H0 as [? H0]. inversion H0.\n  subst. inversion H9. subst. simpl in A. omega.\n  apply IHdcs_has_type. eexists. eassumption. simpl in A. omega.\n  rewrite H5 in H4. rewrite H4 in H0. simpl in H0. destruct H0 as [? H0]. inversion H0.\n  simpl in A. omega.\n  destruct (tand_shape (TMem m T0 T0) TS).\n  rewrite H3 in H2. rewrite H2 in H0. simpl in H0. destruct H0 as [? H0]. inversion H0.\n  subst. inversion H7.\n  apply IHdcs_has_type. eexists. eassumption. simpl in A. omega.\n  rewrite H3 in H2. rewrite H2 in H0. simpl in H0. destruct H0 as [? H0]. inversion H0.\nQed.\n\n(* like invert_typ above *)\n\nLemma invert_obj: forall n nx venv vf l T1 T2 vx,\n  val_type venv vf (TAll l T1 T2) n ->\n  val_type venv vx T1 nx ->\n  sstpd2 true venv T2 venv T2 [] ->\n  exists env tenv TF ds x y T3 T4,\n    vf = (vobj env (fresh env) ds) /\\\n    1 + (fresh env) = x /\\\n    index l ds = Some (dfun x y) /\\\n    wf_env env tenv /\\\n    dcs_has_type (((fresh env), (open (varF (tvar (fresh env))) TF))::tenv) (fresh env) ds TF /\\\n    sstpd2 true ((fresh env, vobj env (fresh env) ds) :: env) (open (varF (tvar (fresh env))) TF) ((fresh env, vobj env (fresh env) ds) :: env) (open (varF (tvar (fresh env))) TF) [] /\\\n    has_type ((x,(open (varF (tvar (fresh env))) T3))::((fresh env),(open (varF (tvar (fresh env))) TF))::tenv) y (open (varF (tvar x)) (open_rec 1 (varF (tvar (fresh env))) T4)) /\\\n    sstpd2 true venv T1 (((fresh env), vobj env (fresh env) ds)::env) (open (varF (tvar (fresh env))) T3) [] /\\\n    sstpd2 true ((x, vx)::((fresh env), vobj env (fresh env) ds)::env) (open (varF (tvar x)) (open_rec 1 (varF (tvar (fresh env))) T4)) venv T2 [].\nProof.\n  intros n. destruct n. intros. inversion H.\n  assert (exists ni, n <= ni). exists n. omega. destruct H as [ni ?]. revert n H. induction ni; intros n N.\n  - (* 1 *)\n    inversion N. subst n. intros. inversion H; repeat ev; try solve by inversion.\n    subst.\n    exists venv1. exists tenv0. exists T. exists ds.\n    assert (exists y T3 T4, index l ds = Some (dfun (1 + (fresh venv1))  y) /\\ has_type ((1+(fresh venv1), (open (varF (tvar (fresh venv1))) T3)) :: ((fresh venv1), (open (varF (tvar (fresh venv1))) T)) :: tenv0) y (open (varF (tvar (1 + (fresh venv1)))) (open_rec 1 (varF (tvar (fresh venv1))) T4)) /\\ sstpd2 true (((fresh venv1), vobj venv1 (fresh venv1) ds)::venv1) (open (varF (tvar (fresh venv1))) (TAll l T3 T4)) venv0 (TAll l T1 T2) []) as A. {\n      clear H. clear H0.\n      unfold id in H4.\n      remember ((fresh venv1, (open (varF (tvar (fresh venv1))) T))::tenv0) as tenv.\n      assert (fresh tenv = S (fresh venv1)) as A. { rewrite Heqtenv. simpl. reflexivity. }\n      clear Heqtenv.\n      unfold id in H6.\n      remember ((fresh venv1, vobj venv1 (fresh venv1) ds) :: venv1) as venv.\n      assert (sstpd2 true venv (open (varF (tvar (fresh venv1))) T) venv0 (TAll l T1 T2) []) as B. { eexists; eassumption. }\n      clear H6. clear Heqvenv.\n      induction H4. destruct B as [? B]. inversion B.\n      simpl.\n      case_eq (le_lt_dec (fresh dcs) m); intros LE E1.\n      case_eq (beq_nat l m); intros E2.\n      exists y. eexists. eexists.\n      split. rewrite <- A. rewrite H0. reflexivity.\n      split. rewrite <- A. rewrite H0. eapply H.\n      destruct (tand_shape (TAll m T0 T3) TS).\n      rewrite H6 in H5. rewrite H5 in B. destruct B as [? B]. unfold open in B. simpl in B. inversion B. eapply beq_nat_true in E2. rewrite <- E2 in H10. eexists. eassumption.\n      eapply dcs_has_type_stp in H4. inversion H4. rewrite <- H3. eapply beq_nat_true in E2. rewrite <- E2. eexists. eassumption.\n      rewrite H6 in H5. rewrite H5 in B. eapply beq_nat_true in E2. rewrite <- E2 in B. apply B.\n      eapply IHdcs_has_type. apply A. destruct (tand_shape (TAll m T0 T3) TS).\n      rewrite H6 in H5. rewrite H5 in B. destruct B as [? B]. inversion B. unfold open in H10. simpl in H10. inversion H10. apply beq_nat_false in E2. omega. eexists. eassumption.\n      rewrite H6 in H5. rewrite H5 in B. destruct B as [? B]. inversion B. apply beq_nat_false in E2. omega.\n      inversion H4; subst. simpl in LE. omega. simpl in LE. omega. simpl in LE. omega.\n      simpl.\n      case_eq (le_lt_dec (fresh dcs) m); intros LE E1.\n      case_eq (beq_nat l m); intros E2.\n      destruct (tand_shape (TMem m T0 T0) TS).\n      rewrite H3 in H0. rewrite H0 in B. destruct B as [? B]. unfold open in B. simpl in B. inversion B. eapply beq_nat_true in E2. rewrite <- E2 in H8. inversion H8.\n      eapply dcs_has_type_stp in H4. inversion H4. rewrite <- H. eapply beq_nat_true in E2. rewrite <- E2. eexists. eassumption.\n      rewrite H3 in H0. rewrite H0 in B. eapply beq_nat_true in E2. rewrite <- E2 in B. inversion B.\n      unfold open in H5. simpl in H5. inversion H5.\n      eapply IHdcs_has_type. apply A. destruct (tand_shape (TMem m T0 T0) TS).\n      rewrite H3 in H0. rewrite H0 in B. destruct B as [? B]. inversion B. unfold open in H8. simpl in H8. inversion H8. eexists. eassumption.\n      rewrite H3 in H0. rewrite H0 in B. destruct B as [? B]. inversion B.\n      inversion H4; subst. simpl in LE. omega. simpl in LE. omega. simpl in LE. omega.\n    }\n    destruct A as [y [T3 [T4 [A1 [A2 A3]]]]].\n    exists (1 + (fresh venv1)). exists y. exists T3. exists T4.\n    split. reflexivity. split. reflexivity.\n    split. apply A1.\n    split. assumption. split. assumption.\n    split. eapply sstpd2_reg1. eexists. eassumption.\n    split. apply A2.\n    destruct A3 as [? A3]. inversion A3. subst. split.\n    eapply stpd2_upgrade. eexists. eassumption.\n    \n    assert (stpd2 false venv0 T1\n            ((fresh venv1, vobj venv1 (fresh venv1) ds) :: venv1)\n            (open_rec 0 (varF (tvar (fresh venv1))) T3) []) as ARG. eauto.\n    assert (stpd2 false ((fresh venv1, vobj venv1 (fresh venv1) ds) :: venv1)\n            (open (varH 0) (open_rec 1 (varF (tvar (fresh venv1))) T4))\n            venv0 (open (varH 0) T2) [(0, (venv0, T1))]) as KEY. eauto.\n\n    eapply stpd2_upgrade in ARG.\n\n    assert (stpd2 false venv0 T1 venv0 T1 []) as HR1. eapply stpd2_wrapf. eapply stpd2_reg1. eauto.\n    assert (closed 0 0 T1). eapply stpd2_closed1 in HR1. simpl in HR1. apply HR1.\n\n    assert (stpd2 false ((1 + fresh venv1, vx)::(fresh venv1, vobj venv1 (fresh venv1) ds)::venv1)\n                (open_rec 0 (varF (tvar (1 + fresh venv1))) (open_rec 1 (varF (tvar (fresh venv1))) T4))\n                venv0 T2 []) as HR2. {\n      assert (closed 0 (length ([]:aenv)) T2). eapply sstpd2_closed1; eauto.\n      assert (open (varH 0) T2 = T2) as OP2. symmetry. eapply closed_no_open; eauto.\n\n      eapply stpd2_substitute with (GH0:=nil).\n      eapply stpd2_extend1. eapply KEY.\n      eauto. simpl. eauto.\n      erewrite closed_no_subst. eassumption. eassumption.\n      eapply closed_upgrade_free. eauto. omega. eauto.\n      left. exists (tvar (1 + fresh venv1)). eexists. eexists.\n      split. eapply index_to_peval. eapply index_hit2; eauto. \n      rewrite closed_no_subst with (j:=0). eauto. eauto.\n      rewrite (subst_open_zero 0 1). eauto. eauto. eauto. eauto. \n      right. left. split. rewrite OP2. eauto. eauto.\n      right. left. split. eauto. rewrite closed_no_subst with (j:=0). eauto. eauto.\n      eauto.\n    }\n    eapply stpd2_upgrade in HR2.\n    subst. eauto.\n  - (* n *)\n    intros.\n    assert (sstpd2 true venv0 (TAll l T1 T2) venv0 (TAll l T1 T2) []). eapply valtp_reg; eauto.\n    eu.\n    eapply invert_all in H. destruct H as [GY [TY [VT [? ST]]]].\n    eapply valtp_widen in VT.\n    eapply IHni. instantiate (1:=0). omega. eapply VT. eauto. eauto. eexists. eauto.\n    intros nv. eapply stp2_substitute_aux. eauto.\n    \nGrab Existential Variables.\napply tvar. apply 0. apply 0. \nQed.\n\nLemma invert_obj_var: forall n nx venv vf l T1 T2 vx xarg,\n  val_type venv vf (TAll l T1 T2) n ->\n  val_type venv vx T1 nx ->\n  index xarg venv = Some vx ->\n  sstpd2 true venv (open (varF (tvar xarg)) T2) venv (open (varF (tvar xarg)) T2) [] ->\n  exists env tenv TF ds x y T3 T4,\n    vf = (vobj env (fresh env) ds) /\\\n    1 + (fresh env) = x /\\\n    index l ds = Some (dfun x y) /\\\n    wf_env env tenv /\\\n    dcs_has_type (((fresh env), (open (varF (tvar (fresh env))) TF))::tenv) (fresh env) ds TF /\\\n    sstpd2 true ((fresh env, vobj env (fresh env) ds) :: env) (open (varF (tvar (fresh env))) TF) ((fresh env, vobj env (fresh env) ds) :: env) (open (varF (tvar (fresh env))) TF) [] /\\\n    has_type ((x,(open (varF (tvar (fresh env))) T3))::((fresh env),(open (varF (tvar (fresh env))) TF))::tenv) y (open (varF (tvar x)) (open_rec 1 (varF (tvar (fresh env))) T4)) /\\\n    sstpd2 true venv T1 (((fresh env), vobj env (fresh env) ds)::env) (open (varF (tvar (fresh env))) T3) [] /\\\n    sstpd2 true ((x, vx)::((fresh env), vobj env (fresh env) ds)::env) (open (varF (tvar x)) (open_rec 1 (varF (tvar (fresh env))) T4)) venv (open (varF (tvar xarg)) T2) [].\nProof.\n  intros n. destruct n. intros. inversion H.\n  assert (exists ni, n <= ni). exists n. omega. destruct H as [ni ?]. revert n H. induction ni; intros n N.\n  - (* 1 *)\n    inversion N. subst n. intros. inversion H; repeat ev; try solve by inversion.\n  subst.\n  exists venv1. exists tenv0. exists T. exists ds.\n  assert (exists y T3 T4, index l ds = Some (dfun (1 + (fresh venv1))  y) /\\ has_type ((1+(fresh venv1), (open (varF (tvar (fresh venv1))) T3)) :: ((fresh venv1), (open (varF (tvar (fresh venv1))) T)) :: tenv0) y (open (varF (tvar (1 + (fresh venv1)))) (open_rec 1 (varF (tvar (fresh venv1))) T4)) /\\ sstpd2 true (((fresh venv1), vobj venv1 (fresh venv1) ds)::venv1) (open (varF (tvar (fresh venv1))) (TAll l T3 T4)) venv0 (TAll l T1 T2) []) as A. {\n    clear H. clear H0.\n    unfold id in H5.\n    remember ((fresh venv1, (open (varF (tvar (fresh venv1))) T))::tenv0) as tenv.\n    assert (fresh tenv = S (fresh venv1)) as A. { rewrite Heqtenv. simpl. reflexivity. }\n    clear Heqtenv.\n    unfold id in H7.\n    remember ((fresh venv1, vobj venv1 (fresh venv1) ds) :: venv1) as venv.\n    assert (sstpd2 true venv (open (varF (tvar (fresh venv1))) T) venv0 (TAll l T1 T2) []) as B. { eexists; eassumption. }\n    clear H7. clear Heqvenv.\n    induction H5. destruct B as [? B]. inversion B.\n    simpl.\n    case_eq (le_lt_dec (fresh dcs) m); intros LE E1.\n    case_eq (beq_nat l m); intros E2.\n    exists y. eexists. eexists.\n    split. rewrite <- A. rewrite H0. reflexivity.\n    split. rewrite <- A. rewrite H0. eapply H.\n    destruct (tand_shape (TAll m T0 T3) TS).\n    rewrite H7 in H6. rewrite H6 in B. destruct B as [? B]. unfold open in B. simpl in B. inversion B. eapply beq_nat_true in E2. rewrite <- E2 in H11. eexists. eassumption.\n    eapply dcs_has_type_stp in H5. inversion H5. rewrite <- H4. eapply beq_nat_true in E2. rewrite <- E2. eexists. eassumption.\n    rewrite H7 in H6. rewrite H6 in B. eapply beq_nat_true in E2. rewrite <- E2 in B. apply B.\n    eapply IHdcs_has_type. apply A. destruct (tand_shape (TAll m T0 T3) TS).\n    rewrite H7 in H6. rewrite H6 in B. destruct B as [? B]. inversion B. unfold open in H11. simpl in H11. inversion H11. apply beq_nat_false in E2. omega. eexists. eassumption.\n    rewrite H7 in H6. rewrite H6 in B. destruct B as [? B]. inversion B. apply beq_nat_false in E2. omega.\n    inversion H5; subst. simpl in LE. omega. simpl in LE. omega. simpl in LE. omega.\n    simpl.\n    case_eq (le_lt_dec (fresh dcs) m); intros LE E1.\n    case_eq (beq_nat l m); intros E2.\n    destruct (tand_shape (TMem m T0 T0) TS).\n    rewrite H4 in H0. rewrite H0 in B. destruct B as [? B]. unfold open in B. simpl in B. inversion B. eapply beq_nat_true in E2. rewrite <- E2 in H9. inversion H9.\n    eapply dcs_has_type_stp in H5. inversion H5. rewrite <- H. eapply beq_nat_true in E2. rewrite <- E2. eexists. eassumption.\n    rewrite H4 in H0. rewrite H0 in B. eapply beq_nat_true in E2. rewrite <- E2 in B. inversion B.\n    unfold open in H6. simpl in H6. inversion H6.\n    eapply IHdcs_has_type. apply A. destruct (tand_shape (TMem m T0 T0) TS).\n    rewrite H4 in H0. rewrite H0 in B. destruct B as [? B]. inversion B. unfold open in H9. simpl in H9. inversion H9. eexists. eassumption.\n    rewrite H4 in H0. rewrite H0 in B. destruct B as [? B]. inversion B.\n    inversion H5; subst. simpl in LE. omega. simpl in LE. omega. simpl in LE. omega.\n  }\n  destruct A as [y [T3 [T4 [A1 [A2 A3]]]]].\n  exists (1 + (fresh venv1)). exists y. exists T3. exists T4.\n  split. reflexivity. split. reflexivity.\n  split. apply A1.\n  split. assumption. split. assumption.\n  split. eapply sstpd2_reg1. eexists. eassumption.\n  split. apply A2.\n  destruct A3 as [? A3]. inversion A3. subst. split.\n  eapply stpd2_upgrade. eexists. eassumption.\n\n  assert (stpd2 false venv0 T1\n          ((fresh venv1, vobj venv1 (fresh venv1) ds) :: venv1)\n          (open_rec 0 (varF (tvar (fresh venv1))) T3) []) as ARG. eauto.\n  assert (stpd2 false ((fresh venv1, vobj venv1 (fresh venv1) ds) :: venv1)\n          (open (varH 0) (open_rec 1 (varF (tvar (fresh venv1))) T4))\n          venv0 (open (varH 0) T2) [(0, (venv0, T1))]) as KEY. eauto.\n\n  eapply stpd2_upgrade in ARG.\n\n  assert (stpd2 false venv0 T1 venv0 T1 []) as HR1. eapply stpd2_wrapf. eapply stpd2_reg1. eauto.\n  assert (closed 0 0 T1). eapply stpd2_closed1 in HR1. simpl in HR1. apply HR1.\n\n  assert (stpd2 false ((1 + fresh venv1, vx)::(fresh venv1, vobj venv1 (fresh venv1) ds)::venv1)\n                (open_rec 0 (varF (tvar (1 + fresh venv1))) (open_rec 1 (varF (tvar (fresh venv1))) T4))\n                venv0 (open (varF (tvar xarg)) T2) []) as HR2. {\n    eapply stpd2_substitute with (GH0:=nil).\n    eapply stpd2_extend1. eapply KEY.\n    eauto. simpl. eauto.\n    erewrite closed_no_subst. eassumption. eassumption.\n    eapply closed_upgrade_free. eauto. omega. eauto.\n    left. exists (tvar (1 + fresh venv1)). eexists. eexists. split.\n    eapply index_to_peval. eapply index_hit2; eauto.\n    rewrite closed_no_subst with (j:=0). eauto. eauto.\n    rewrite (subst_open_zero 0 1). eauto. eauto. eauto. \n    left. exists (tvar xarg). eexists. eexists. split.\n    eapply index_to_peval. eauto. \n    rewrite closed_no_subst with (j:=0). eauto. eauto.\n    rewrite (subst_open_zero 0 1). eauto. eauto. eauto. eauto.\n    right. left. split. eauto. rewrite closed_no_subst with (j:=0). eauto. eauto.\n    eauto.\n  }\n  eapply stpd2_upgrade in HR2.\n  subst. eauto.\n  - (* n *)\n    intros.\n    assert (sstpd2 true venv0 (TAll l T1 T2) venv0 (TAll l T1 T2) []). eapply valtp_reg; eauto.\n    eu.\n    eapply invert_all in H. destruct H as [GY [TY [VT [? ST]]]].\n    eapply valtp_widen in VT.\n    eapply IHni. instantiate (1:=0). omega. eapply VT. eauto. eauto. eauto. eexists. apply ST.\n    intros nv. eapply stp2_substitute_aux. eauto.\nGrab Existential Variables.\napply tvar. apply 0. apply 0.\nQed.\n\n\nLemma has_type_wf:\n  forall G t T, has_type G t T -> stp G [] T T.\nProof.\n  intros. induction H; eauto.\n  - eapply stp_reg. eassumption.\n\nQed.\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.\n    assert (stp tenv0 [] T T). eapply has_type_wf. eauto.\n    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\".\n      assert (res_type venv0 (index i venv0) (open (varF (tvar i)) T1)). eapply IHhas_type; eauto. eapply has_type_wf; eauto.\n      inversion H3. subst.\n      eapply not_stuck. eapply (v_pack _ _ (tvar i)). eapply index_to_peval; eauto. eauto. eauto. \n      eapply stpd2_upgrade. eapply stp_to_stp2; eauto.\n\n    + SCase \"unpack\".\n      assert (res_type venv0 (index i venv0) (TBind T1)). eapply IHhas_type; eauto. eapply has_type_wf; eauto.\n      inversion H3. subst.\n      destruct n0. inversion H7. \n      assert (sstpd2 true venv0 (TBind T1) venv0 (TBind T1) []). eapply valtp_reg. eauto. eu.\n      eapply invert_bind in H7. destruct H7. destruct H7. destruct H8. destruct H8. destruct H8.\n      eapply valtp_widen in H8.\n      eapply not_stuck. apply H8. apply H9. intros ni no. eapply stp2_substitute_aux. eauto. eapply index_to_peval. eauto. eauto. \n                    \n    + eapply restp_widen. eapply IHhas_type; eauto. eapply has_type_wf; eauto. eapply stpd2_upgrade. eapply stp_to_stp2; eauto.\n\n(*\n  - Case \"Typ\".\n    remember (ttyp l) as e.\n    induction H0; inversion Heqe; subst.\n    + remember (fresh env) as i.\n      remember (open (varF i) T) as TX.\n      remember ((i,vty venv0 l)::venv0) as venv1.\n      assert (index i venv1 = Some (vty venv0 l)). subst. eapply index_hit2. rewrite wf_fresh with (ts := env). eauto. eauto. eauto. eauto.\n      assert ((open (varF (fresh venv0)) T) = TX). rewrite wf_fresh with (ts:=env). rewrite <-Heqi. eauto. eauto.\n      assert (val_type venv1 (vty venv0 l) TX 1). eapply v_ty. eauto. eauto.\n      eapply H4.\n\n      (* we have everything as stp and 'just' need to convert to stp2. however we're\n      working with an env that has a self binding, and the wf_env evidence needs\n      the very val_tp what we're trying to construct *)\n\n      eapply stpd2_upgrade. rewrite wf_fresh with (ts:=env). subst. eapply stp_to_stp2_cycle. eauto. eauto. eauto.\n\n      eapply not_stuck. eapply v_pack. eapply H0. eapply H3. instantiate (1:=T). simpl. subst TX. eauto. subst venv1. eapply sstpd2_extend1. eapply stpd2_upgrade. eapply stp_to_stp2; eauto. rewrite wf_fresh with (ts:=env). subst i. eauto. eauto.\n\n    + eapply restp_widen. eapply IHhas_type; eauto. eapply stpd2_upgrade. eapply stp_to_stp2; eauto.\n\n*)\n  - Case \"App\".\n    remember (tapp e1 i 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 (TAll i T1 T2)) as HRF. SCase \"HRF\". subst. eapply IHn; eauto.\n      inversion HRF as [? vf].\n\n      destruct (invert_obj n1 n0 venv0 vf i T1 T2 vx) as\n          [env1 [tenv [TF [ds [x0 [y0 [T3 [T4 [EF [FRX [EQDS [WF [HDS [HTF [HTY [STX STY]]]]]]]]]]]]]]]]. eauto. eauto. eapply stpd2_upgrade. eapply stp_to_stp2. eassumption. eauto. eauto.\n      (* now we know it's a closure, and we have has_type evidence *)\n\n      assert (res_type ((x0,vx)::((fresh env1),vf)::env1) res (open (varF (tvar x0)) (open_rec 1 (varF (tvar (fresh env1))) T4))) as HRY.\n        SCase \"HRY\".\n          subst. eapply IHn. rewrite EQDS in H3. eauto. eauto.\n          (* wf_env f x *) econstructor. eapply valtp_widen; eauto. eapply sstpd2_extend2. eauto. eauto.\n          (* wf_env f   *) econstructor. eapply v_obj; eauto.\n          eauto.\n      inversion HRY as [? vy].\n\n      eapply not_stuck. eapply valtp_widen; eauto. rewrite EF. eauto.\n\n    +\n      remember (teval n venv0 e1) as tf.\n      remember (teval n venv0 (tvar x)) 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 (TAll i T1 T2)) as HRF. SCase \"HRF\". subst. eapply IHn; eauto.\n      inversion HRF as [? vf].\n\n      destruct (invert_obj_var n1 n0 venv0 vf i T1 T2 vx x) as\n          [env1 [tenv [TF [ds [x0 [y0 [T3 [T4 [EF [FRX [EQDS [WF [HDS [HTF [HTY [STX STY]]]]]]]]]]]]]]]]. eauto. eauto.\n      destruct n. inversion Heqtx. simpl in Heqtx. inversion Heqtx. reflexivity.\n      eapply stpd2_upgrade. eapply stp_to_stp2. eassumption. eauto. eauto.\n      (* now we know it's a closure, and we have has_type evidence *)\n\n      assert (res_type ((x0,vx)::((fresh env1),vf)::env1) res (open (varF (tvar x0)) (open_rec 1 (varF (tvar (fresh env1))) T4))) as HRY.\n        SCase \"HRY\".\n          subst. eapply IHn. rewrite EQDS in H3. eauto. eauto.\n          (* wf_env f x *) econstructor. eapply valtp_widen; eauto. eapply sstpd2_extend2. eauto. eauto.\n          (* wf_env f   *) econstructor. eapply v_obj; eauto.\n          eauto.\n      inversion HRY as [? vy].\n\n      eapply not_stuck. eapply valtp_widen; eauto. rewrite EF. eauto.\n\n\n    + eapply restp_widen. eapply IHhas_type; eauto. eapply stpd2_upgrade. eapply stp_to_stp2; eauto.\n\n\n  - Case \"Obj\".\n    remember (tobj i l) as xe. induction H0; inversion Heqxe; subst.\n    + remember (open (varF (tvar i)) T) as TX.\n      remember ((i,vobj venv0 i l)::venv0) as venv1.\n      assert (index i venv1 = Some (vobj venv0 i l)). subst. eapply index_hit2. rewrite wf_fresh with (ts := env). eauto. eauto. eauto. eauto.\n      assert ((open (varF (tvar (fresh venv0))) T) = TX). rewrite wf_fresh with (ts:=env). rewrite H8. eauto. eauto.\n      assert (val_type venv1 (vobj venv0 i l) TX 1). eapply v_obj. eauto. eauto.\n      rewrite <- H8. eapply H4.\n\n      rewrite wf_fresh with (ts:=env). assumption. eauto.\n\n      (* we have everything as stp and 'just' need to convert to stp2. however we're\n      working with an env that has a self binding, and the wf_env evidence needs\n      the very val_tp what we're trying to construct *)\n\n      eapply stpd2_upgrade. subst.\n      rewrite <- wf_fresh with (ts:=env) (vs:=venv0).\n      unfold id.\n      rewrite wf_fresh with (ts:=env) (vs:=venv0) at 1.\n      rewrite wf_fresh with (ts:=env) (vs:=venv0) at 3.\n      eapply stp_to_stp2_cycle. eauto.\n      rewrite wf_fresh with (ts:=env) (vs:=venv0).\n      eauto. eauto. eauto. eauto. eauto.\n\n      eapply not_stuck. eapply (v_pack _ _ (tvar i)). eapply index_to_peval. eauto.\n      eauto. instantiate (1:=T). simpl. subst TX. eauto. subst venv1. eapply sstpd2_extend1. eapply stpd2_upgrade. eapply stp_to_stp2; eauto. rewrite wf_fresh with (ts:=env). subst i. eauto. eauto.\n\n    + eapply restp_widen. eapply IHhas_type; eauto. eapply stpd2_upgrade. eapply stp_to_stp2; eauto.\n\n  - Case \"TLet\".\n    remember (tlet i e1 e2) as e. induction H0; inversion Heqe; subst.\n    + remember (teval n venv0 e1) as tx.\n      destruct tx as [rx|]; try solve by inversion.\n      assert (res_type venv0 rx Tx) as HRX. SCase \"HRX\". subst. eapply IHn; eauto.\n      inversion HRX as [? vx]. subst.\n      assert (res_type ((i, vx) :: venv0) res T) as HR. SCase \"HR\". subst. eapply IHn; eauto. econstructor. eapply valtp_widen; eauto. eapply sstpd2_extend2. eapply stpd2_upgrade. eapply stp_to_stp2. eapply has_type_wf. eauto. eauto. eauto. rewrite wf_fresh with (ts:=env). eauto. eauto. eauto.\n      inversion HR as [? v]. subst.\n      eapply not_stuck. eapply valtp_widen. eauto. eapply sstpd2_extend1. eapply stpd2_upgrade. eapply stp_to_stp2. eauto. eauto. eauto. rewrite wf_fresh with (ts:=env). eauto. eauto.\n\n    + eapply restp_widen. eapply IHhas_type; eauto. eapply stpd2_upgrade. eapply stp_to_stp2; eauto.\n\nGrab Existential Variables.\napply 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/dot26.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.28198139768053615}}
{"text": "From Coq Require Logic.Eqdep Sets.Ensembles.\nRequire Import Rupicola.Lib.Api.\nRequire Export Rupicola.Examples.IO.Writer.\n\nOpen Scope list_scope.\n\nSet Implicit Arguments.\nSet Primitive Projections.\n\nModule Observable.\n  Import Writer.\n\n  Section Observable.\n  Context (T: Type).\n\n  Definition M A := Writer.M T A -> Prop.\n\n  Ltac s :=\n    apply Ensembles.Extensionality_Ensembles;\n    unfold Ensembles.Same_set, Ensembles.Included, Ensembles.In;\n    repeat match goal with\n           | _ => reflexivity || eassumption\n           | _ => progress (intros; subst; simpl in * )\n           | [ H: exists _, _ |- _ ] => destruct H\n           | [ H: _ /\\ _ |- _ ] => destruct H\n           | [  |- exists _, _ ] => eexists\n           | [  |- _ /\\ _ ] => split\n           | _ => rewrite ?List.app_nil_r, ?List.app_assoc\n           end.\n\n  Global Program Instance MonadM : Monad M :=\n    {| mret {A} (a: A) := fun r => r = {| val := a; trace := [] |};\n       mbind {A B} (ma: M A) (k: A -> M B) :=\n         fun obs => exists obsA obsB, ma obsA /\\ k obsA.(val) obsB /\\\n                              obs = {| val := obsB.(val);\n                                       trace := obsB.(trace) ++ obsA.(trace) |} |}.\n  Obligation 1. Proof. s. Qed.\n  Obligation 2. Proof. s. Qed.\n  Obligation 3. Proof. s. Qed.\n  End Observable.\nEnd Observable.\n\nModule IO.\n  Import Writer.\n\n  Section IO.\n  Context (T: Type).\n\n  Inductive Action : Type -> Type :=\n  | Read : Action T\n  | Write (w: T) : Action unit.\n\n  Definition M := (@Free.M Action).\n  (* Instance Monad : Monad (@Free.M Action) := @Free.Monad Action. *)\n\n  Inductive Event T := R (t: T) | W (t: T).\n\n  Definition interpAction {A} (rw: Action A) : Observable.M (Event T) A :=\n    match rw with\n    | Read => fun wr => wr.(trace) = [R wr.(val)]\n    | Write w => fun wr => wr.(trace) = [W w]\n    end.\n\n  Definition interp {A} (spec: M A) : Observable.M (Event T) A :=\n    Free.interp (MM' := Observable.MonadM (Event T)) (@interpAction) spec.\n\n  Inductive Valid {A} : IO.M A -> Writer.M (Event T) A -> Prop :=\n    | ValidPure a : Valid (Free.Pure a) {| val := a; trace := [] |}\n    | ValidRead r k a t :\n        Valid (k r) {| val := a; trace := t |} ->\n        Valid (Free.Impure Read k) {| val := a; trace := t ++ [R r] |}\n    | ValidWrite w k a t :\n        Valid (k tt) {| val := a; trace := t |} ->\n        Valid (Free.Impure (Write w) k) {| val := a; trace := t ++ [W w] |}.\n\n  Hint Constructors Valid : io.\n  Lemma interp_Valid {A} (spec: IO.M A):\n    forall obs,\n      Valid spec obs <-> interp spec obs.\n  Proof.\n    induction spec; simpl; unfold mret; intros.\n    - split; inversion 1; subst; simpl; eauto with io.\n    - split.\n      + inversion 1;\n          repeat match goal with\n                 | _ => progress subst\n                 | [ H: existT _ _ _ = _ |- _ ] => apply Eqdep.EqdepTheory.inj_pair2 in H\n                 end.\n        1: exists {| val := r; trace := [R r] |}, {| val := a; trace := t |}.\n        2: exists {| val := tt; trace := [W w] |}, {| val := a; trace := t |}.\n        all: firstorder.\n      + destruct f; unfold mbind;\n          repeat match goal with\n                 | [ H: unit |- _ ] => destruct H\n                 | [ H: exists _: Writer.M _ _, _ |- _ ] => destruct H as [(?&?) ?]\n                 | [ H: _ /\\ _ |- _ ] => destruct H\n                 | _ => intros; subst; simpl in *\n                 end.\n        all: firstorder eauto with io.\n  Qed.\n  End IO.\nEnd IO.\n\nArguments IO.Read {_} : assert.\n\nImport Writer.\n\nSection with_parameters.\n  Context {width: Z} {BW: Bitwidth width} {word: word.word width} {memT: map.map word Byte.byte}.\n  Context {localsT: 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 memT}.\n  Context {locals_ok : map.ok localsT}.\n  Context {env_ok : map.ok env}.\n  Context {ext_spec_ok : Semantics.ext_spec.ok ext_spec}.\n\n  Context {T: Type}.\n  Notation IO := (IO.M T).\n  Notation Event := (IO.Event T).\n  Notation Writer := (Writer.M Event).\n\n  Context (trace_entry_of_event: Event -> trace_entry (width := width)).\n  Notation wrbind_spec := (wrbind_spec trace_entry_of_event).\n  Notation lift_tr := (List.map trace_entry_of_event).\n\n  Definition iobind {A} (io: IO A) (pred: Writer A -> Prop) :=\n    (* NOTE: We do not need to capture the fact that all traces are achievable:\n       Bedrock2 takes care of that for us (the source program has no control on the\n       values returned by \"read\" *)\n    exists wr, IO.Valid io wr /\\ pred wr.\n\n  Definition iobind_spec {A} tr0 (io: IO A) (pred: A -> Semantics.trace -> Prop) : Prop :=\n    iobind io (fun wr => wrbind_spec tr0 wr pred).\n\n  Definition iospec {A} (tr0 tr1: Semantics.trace) (io: IO A) (post: A -> Prop) : Prop :=\n    iobind_spec tr0 io (fun a tr' => tr' = tr1 /\\ post a).\n\n  Definition iospec_k {A} tr0 (pred: A -> pure_predicate) (io: IO A) : predicate :=\n    fun tr1 mem locals => iospec tr0 tr1 io (fun a => pred a mem locals).\n\n  Lemma iobind_spec_bindn {A B} tr0 pred vars io wr (k : A -> IO B):\n      IO.Valid io wr ->\n      iobind_spec (List.map trace_entry_of_event wr.(trace) ++ tr0) (k wr.(val)) pred ->\n      iobind_spec tr0 (mbindn vars io k) pred.\n  Proof.\n    unfold iobind_spec, iobind, wrbind_spec.\n    intros H (wrb & Hb & Hwr).\n    eexists {| val := wrb.(val); trace := wrb.(trace) ++ wr.(trace) |};\n      split.\n    - apply IO.interp_Valid in H, Hb; apply IO.interp_Valid.\n      unfold IO.interp; rewrite <- @Free.interp_mbindn.\n      red; red; red; eauto.\n    - simpl; rewrite map_app, <- app_assoc; eassumption.\n  Qed.\n\n  Lemma WeakestPrecondition_iospec_k_bindn {A B} tr0 funcs prog tr mem locals :\n    forall vars (io : IO A) (k : A -> IO B) wr (pred : B -> pure_predicate),\n    IO.Valid io wr ->\n    (IO.Valid io wr ->\n     WeakestPrecondition.program\n       funcs prog tr mem locals\n       (iospec_k (lift_tr wr.(trace) ++ tr0) pred (k wr.(val)))) ->\n    WeakestPrecondition.program\n      funcs prog tr mem locals\n      (iospec_k tr0 pred (mbindn vars io k)).\n  Proof.\n    intros; eapply WeakestPrecondition_weaken; [ | eauto ].\n    intros; eapply iobind_spec_bindn; eauto.\n  Qed.\n\n  Lemma compile_setup_iospec_k {tr mem locals functions} :\n    forall {A} {pred: A -> _ -> pure_predicate}\n      {spec: IO A} {cmd}\n      retvars,\n\n      (let pred a := wp_pure_bind_retvars retvars (pred a) in\n       <{ Trace := tr;\n          Memory := mem;\n          Locals := locals;\n          Functions := functions }>\n       cmd\n       <{ iospec_k tr 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                 iospec tr tr' spec (fun a => pred a rets mem' locals')))\n           spec }>.\n  Proof.\n    intros; unfold iospec_k, iospec, iobind_spec, wrbind_spec, iobind, wp_bind_retvars, wp_pure_bind_retvars in *.\n    use_hyp_with_matching_cmd; simpl in *.\n    cleanup; subst; eauto 10.\n  Qed.\n\n  (* FIXME can we generalize?  Basically this works with any monad that describes sets of values *)\n  Lemma compile_if : forall {tr mem locals functions} (c: bool) {A} (t f: IO A),\n    let v := if c then t else f in\n    forall {B} {pred: B -> pure_predicate} {val_pred: A -> pure_predicate}\n      {k: A -> IO B} {k_impl t_impl f_impl}\n      c_expr vars,\n\n      WeakestPrecondition.dexpr mem locals c_expr (word.b2w c) ->\n\n      (let val_pred := val_pred in\n       c = true ->\n       <{ Trace := tr;\n          Memory := mem;\n          Locals := locals;\n          Functions := functions }>\n       t_impl\n       <{ iospec_k tr val_pred (mbindn vars t mret) }>) ->\n      (let val_pred := val_pred in\n       c = false ->\n       <{ Trace := tr;\n          Memory := mem;\n          Locals := locals;\n          Functions := functions }>\n       f_impl\n       <{ iospec_k tr val_pred (mbindn vars f mret) }>) ->\n      (forall a mem locals,\n         IO.Valid v a ->\n         val_pred a.(val) mem locals ->\n         let tr := List.map trace_entry_of_event a.(trace) ++ tr in\n       <{ Trace := tr;\n          Memory := mem;\n          Locals := locals;\n          Functions := functions }>\n       k_impl\n       <{ iospec_k tr pred (k a.(val)) }>) ->\n      <{ Trace := tr;\n         Memory := mem;\n         Locals := locals;\n         Functions := functions }>\n      cmd.seq\n        (cmd.cond c_expr t_impl f_impl)\n        k_impl\n      <{ iospec_k tr pred (mbindn vars v k) }>.\n  Proof.\n    intros * Hc Ht Hf Hk.\n    repeat straightline.\n    split_if ltac:(repeat straightline'); subst_lets_in_goal.\n    eassumption.\n    all: rewrite word.unsigned_b2w; cbv [Z.b2z].\n    all: destruct_one_match; try congruence; [ ]; intros.\n    all: eapply compile_seq; [ (eapply Ht + eapply Hf); reflexivity | ].\n    all: intros * (out & Hvalid & <- & Hpred); rewrite mbindn_mret in Hvalid.\n    all: eapply WeakestPrecondition_iospec_k_bindn; intros;\n      try eapply Hk; eauto.\n  Qed.\nEnd with_parameters.\n\nLtac compile_if tr0 :=\n  let vp := infer_val_predicate in\n  eapply compile_if with (val_pred := fun args => vp args tr0).\n\n#[export] Hint Extern 1\n (WeakestPrecondition.cmd _ _ ?tr0 _ _ (_ (mbindn _ (if _ then _ else _) _))) =>\n  compile_if tr0; shelve : compiler.\n\n#[export] Hint Resolve compile_setup_iospec_k : compiler_setup_post.\n#[export] Hint Extern 1 (IO.Valid (mret _) _) => eapply IO.ValidPure : compiler_side_conditions.\n#[export] Hint Unfold iospec_k iospec iobind_spec iobind: compiler_cleanup_post.\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/IO/IO.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.28198139768053615}}
{"text": "\nSet Implicit Arguments.\nUnset Standard Proposition Elimination Names.\n\nRequire Import util.\nRequire Import Le.\nRequire Import EqNat.\nRequire Import Compare_dec.\nRequire Import Bool.\nRequire Import Lt.\nRequire Import list_utils.\nRequire Import List.\nRequire Import Compare_dec.\nRequire Import monads.\nRequire Import monoid_monad_trans.\nRequire Import nat_seqs.\nRequire Import qs_definitions.\nRequire Import monoid_expec.\nRequire qs_parts.\nRequire Import sort_order.\nRequire Import indices.\nRequire Import Arith.\nRequire Import nat_below.\nRequire Vector.\nRequire ne_tree_monad.\n\nImport mon_nondet.\n\nSection contents.\n\n  Variable (e: E) (ol: list e).\n\n  (* todo: use:\n\n  Inductive UnordNatPair: Set := unord_nat_pair (x y: nat): x <= y -> UnordNatPair.\n\n  Definition mk_unord_nat_pair (x y: nat): UnordNatPair :=\n    match le_lt_dec x y with\n    | left p => unord_nat_pair p\n    | right p => unord_nat_pair (lt_le_weak _ _ p)\n    end.\n\n  *)\n\n  Definition monoid := ListMonoid.M (nat * nat).\n\n  Definition M: Monad := MonoidMonadTrans.M monoid ne_tree_monad.ext.\n\n  Lemma Mext: extMonad M.\n  Proof MonoidMonadTrans.Mext monoid ne_tree_monad.ext.\n\n  Definition unordered_nat_pair (x y: nat): nat * nat :=\n    if le_lt_dec x y then (x, y) else (y, x).\n\n  Definition cmp (x y: Index e ol): M comparison\n    := ret (unordered_nat_pair x y :: nil, Ecmp e (subscript x) (subscript y)).\n\n  Definition homo: monoidHomo monoid NatAddMonoid (fun x => length x).\n  Proof with auto. apply Build_monoidHomo... simpl. intros. rewrite app_length... Qed.\n\n  Definition pick := monoid_tree_monad.pick monoid.\n\n  Require Import Rdefinitions.\n\n  Lemma partition d (l: list (Index e ol)):\n    partition M cmp d l =\n    ne_tree.Leaf (map (fun i: Index e ol => unordered_nat_pair i d) l, simplerPartition (UE e ol) d l).\n  Proof with auto. (* todo: rename *)\n    induction l...\n    simpl.\n    rewrite (@mon_assoc (ne_tree_monad.M)).\n    rewrite IHl.\n    simpl.\n    rewrite app_nil_r...\n  Qed.\n\n  Lemma simplePartition_component (ee: E) i cr l:\n    proj1_sig (simplerPartition ee i l) cr =\n      filter (fun f => unsum_bool (cmp_cmp (Ecmp ee f i) cr)) l.\n  Proof with auto.\n    induction l...\n    simpl.\n    rewrite IHl.\n    destruct (Ecmp ee a i); destruct cr...\n  Qed.\n\n  Section Uqs_ind.\n\n    Variable P: list (Index e ol) -> M (list (Index e ol)) -> Prop.\n    Hypothesis Pnil: P nil (ret nil).\n\n    Hypothesis Pcons: forall n (v: Vector.t (Index e ol) (S n)),\n      (forall x0 cr, P (filter (fun f: Index e ol => unsum_bool (cmp_cmp (Ecmp (UE e ol) f (vec.nth v x0)) cr)) (vec.remove v x0)) (qs cmp pick (filter (fun f: Index e ol => unsum_bool (cmp_cmp (Ecmp (UE e ol) f (vec.nth v x0)) cr)) (vec.remove v x0)))) ->\n      P v\n      (ne_tree.Node\n          (ne_list.map\n            (fun x0: natBelow (S n) =>\n              ne_tree.map\n                (map_fst (C:=list (Index e ol)) (app (map (fun i0: Index e ol => unordered_nat_pair i0 (vec.nth v x0)) (vec.remove v x0))))\n                (foo <- qs cmp pick (filter (fun f: Index e ol => unsum_bool (cmp_cmp (Ecmp (UE e ol) f (vec.nth v x0)) Lt)) (vec.remove v x0));\n                bar <- qs cmp pick (filter (fun f: Index e ol => unsum_bool (cmp_cmp (Ecmp (UE e ol) f (vec.nth v x0)) Gt)) (vec.remove v x0));\n                ret (foo ++ (vec.nth v x0 :: filter (fun f0: Index e ol => unsum_bool (cmp_cmp (Ecmp (UE e ol) f0 (vec.nth v x0)) Eq)) (vec.remove v x0)) ++ bar)))\n            (ne_list.from_vec (vec.nats 0 (S n))))).\n\n    Theorem qs_ind: forall l, P l (qs cmp pick l).\n    Proof with auto.\n      apply qs_parts.rect...\n        apply Mext.\n      intros.\n      unfold qs_parts.body.\n      replace (qs_parts.selectPivotPart M pick cmp v) with (ne_tree.Node (ne_list.map (fun x0: natBelow (S n) => ne_tree.map (map_fst (app (map (fun i0: Index e ol => unordered_nat_pair i0 ((vec.nth v x0))) (vec.remove v x0)))) (\n      foo <- qs cmp pick (filter (fun f: Index e ol => unsum_bool (cmp_cmp (Ecmp (UE e ol) f (vec.nth v x0)) Lt)) (vec.remove v x0));\n      bar <- qs cmp pick (filter (fun f: Index e ol => unsum_bool (cmp_cmp (Ecmp (UE e ol) f (vec.nth v x0)) Gt)) (vec.remove v x0));\n      ret (m:=ne_tree_monad.M) (nil, foo ++ (vec.nth v x0 :: filter (fun f0: Index e ol => unsum_bool (cmp_cmp (Ecmp (UE e ol) f0 (vec.nth v x0)) Eq)) (vec.remove v x0)) ++ bar))) (ne_list.from_vec (vec.nats 0 (S n))))).\n        simpl @ret in Pcons.\n        Focus 1.\n        specialize (Pcons v).\n        simpl vec.to_list in Pcons.\n        apply Pcons. clear Pcons.\n        intros.\n        apply H.\n        rewrite length_filter.\n        apply le_lt_trans with (length (vec.to_list (vec.remove v x0))).\n          apply count_le.\n        rewrite vec.length...\n      unfold qs_parts.selectPivotPart.\n      unfold qs_parts.partitionPart.\n      unfold qs_parts.lowRecPart.\n      simpl.\n      f_equal.\n      repeat rewrite ne_list.map_map.\n      apply ne_list.map_ext. intro.\n      unfold compose. simpl.\n      rewrite ne_tree_monad.map_bind.\n      rewrite (@mon_assoc (ne_tree_monad.M)).\n      rewrite partition. simpl.\n      rewrite (@mon_assoc (ne_tree_monad.M)). simpl.\n      rewrite (@mon_assoc (ne_tree_monad.M)). simpl.\n      rewrite (@simplePartition_component (UE e ol)).\n      apply ne_tree_monad.ext. intro.\n      rewrite (@mon_assoc (ne_tree_monad.M)). simpl.\n      rewrite ne_tree_monad.map_bind.\n            rewrite (@mon_assoc (ne_tree_monad.M)). simpl.\n      rewrite (@mon_assoc (ne_tree_monad.M)). simpl.\n      rewrite (@simplePartition_component (UE e ol)).\n      apply ne_tree_monad.ext. intro.\n      unfold compose, map_fst.\n      simpl.\n      rewrite (@simplePartition_component (UE e ol)).\n      reflexivity.\n    Qed.\n\n  End Uqs_ind.\n\n  Lemma UcmpDec (x y: nat * nat): { x = y } + { x <> y }.\n  Proof with auto.\n    intros.\n    destruct x.\n    destruct y.\n    destruct (eq_nat_dec n n1).\n      destruct (eq_nat_dec n0 n2).\n        subst.\n        left...\n      right. intro. inversion H...\n    right. intro. inversion H...\n  Qed.\n\n  Definition UcmpCmp (x y: nat * nat): bool := unsum_bool (UcmpDec x y).\n\n  Definition ijcount (i j: nat): monoid -> nat := count (UcmpCmp (i, j)).\n\n  Lemma ijcount_0 i j l: ~ In (i, j) l -> ijcount i j l = 0.\n  Proof with auto.\n    unfold ijcount.\n    intros.\n    apply count_0.\n    intros.\n    unfold UcmpCmp.\n    case_eq (UcmpDec (i, j) x); intros...\n    elimtype False.\n    apply H.\n    rewrite e0...\n  Qed.\n\n  Lemma hom_ijcount i j: monoidHomo monoid NatAddMonoid (ijcount i j).\n  Proof with auto.\n    unfold ijcount.\n    intros.\n    apply Build_monoidHomo; intros; simpl...\n    apply count_app.\n  Qed.\n\n  Hint Resolve hom_ijcount.\n\n  Lemma ijcount_eq_count i j: ijcount i j = eq_count UcmpDec (i, j).\n  Proof. auto. Qed.\n\n  Definition qs: list (Index e ol) -> M (list (Index e ol)) := qs cmp pick.\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/U.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.28193693196264363}}
{"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(** Type inference for NRA when given the type of the input *)\n\nRequire Import String.\nRequire Import List.\nRequire Import Compare_dec.\nRequire Import Eqdep_dec.\nRequire Import Bool.\nRequire Import EquivDec.\nRequire Import Utils.\nRequire Import DataSystem.\nRequire Import cNRAEnv.\nRequire Import TcNRAEnv.\nRequire Import Program.\nRequire Import TNRAInfer. (* Only for a few auxiliary Lemmas that should probably be moved *)\n\nSection TcNRAEnvInfer.\n  (* Type inference for algebraic expressions *)\n\n  Context {m:basic_model}.\n  Context (τconstants:list (string*rtype)).\n\n  Fixpoint infer_nraenv_core_type (e:nraenv_core) (τenv τin:rtype) : option rtype :=\n    match e with\n    | cNRAEnvGetConstant s =>\n      tdot τconstants s\n    | cNRAEnvID => Some τin\n    | cNRAEnvConst d => infer_data_type (normalize_data brand_relation_brands d)\n    | cNRAEnvBinop b op1 op2 =>\n      let binf (τ₁ τ₂:rtype) := infer_binary_op_type b τ₁ τ₂ in\n      olift2 binf (infer_nraenv_core_type op1 τenv τin) (infer_nraenv_core_type op2 τenv τin)\n    | cNRAEnvUnop u op1 =>\n      let unf (τ₁:rtype) := infer_unary_op_type u τ₁ in\n      olift unf (infer_nraenv_core_type op1 τenv τin)\n    | cNRAEnvMap op1 op2 =>\n      let mapf (τ₁:rtype) :=\n          olift (fun x => lift (fun y => Coll y) (infer_nraenv_core_type op1 τenv x)) (tuncoll τ₁)\n      in\n      olift mapf (infer_nraenv_core_type op2 τenv τin)\n    | cNRAEnvMapProduct op1 op2 =>\n      let mapconcatf (τ₁:list (string*rtype)) :=\n          match RecMaybe Closed τ₁ with\n          | None => None\n          | Some τr₁ =>\n            match olift (tmapConcatOutput τ₁) (infer_nraenv_core_type op1 τenv τr₁) with\n            | None => None\n            | Some τ₂ => Some (Coll τ₂)\n            end\n          end\n      in\n      olift mapconcatf (olift tmapConcatInput (infer_nraenv_core_type op2 τenv τin))\n    | cNRAEnvProduct op1 op2 =>\n      let mapconcatf (τ₁:list (string*rtype)) :=\n          match RecMaybe Closed τ₁ with\n          | None => None\n          | Some τr₁ =>\n            match olift (tmapConcatOutput τ₁) (infer_nraenv_core_type op2 τenv τin) with\n            | None => None\n            | Some τ₂ => Some (Coll τ₂)\n            end\n          end\n      in\n      olift mapconcatf (olift tmapConcatInput (infer_nraenv_core_type op1 τenv τin))\n    | cNRAEnvSelect op1 op2 =>\n      let selectf (τ₁:rtype) :=\n          match tuncoll τ₁ with\n          | Some τ₁' =>\n            match infer_nraenv_core_type op1 τenv τ₁' with\n            | Some τ₂ =>\n              match `τ₂ with\n              | Bool₀ => Some (Coll τ₁')\n              | _ => None\n              end\n            | None => None\n            end\n          | None => None\n          end\n      in\n      olift selectf (infer_nraenv_core_type op2 τenv τin)\n    | cNRAEnvDefault op1 op2 =>\n      match ((infer_nraenv_core_type op1 τenv τin), (infer_nraenv_core_type op2 τenv τin)) with\n      | (Some τ₁', Some τ₂') =>\n        match (tuncoll τ₁', tuncoll τ₂') with\n        | (Some τ₁₀, Some τ₂₀) =>\n          if (`τ₁₀ == `τ₂₀) then Some τ₁' else None\n        | _ => None\n        end\n      | (_, _) => None\n      end\n    | cNRAEnvEither op1 op2 =>\n      match tuneither τin with\n      | Some (τl, τr) =>\n        match ((infer_nraenv_core_type op1 τenv τl), (infer_nraenv_core_type op2 τenv τr)) with\n        | (Some τ₁', Some τ₂') =>\n          if (rtype_eq_dec τ₁' τ₂') (* Probably should be generalized using join... *)\n          then Some τ₁'\n          else None\n        | (_, _) => None\n        end\n      | _ => None\n      end\n    | cNRAEnvEitherConcat op1 op2 =>\n      match (infer_nraenv_core_type op1 τenv τin, infer_nraenv_core_type op2 τenv τin) with\n      | (Some τeither, Some τrecplus) =>          \n        match tuneither τeither with\n        | Some (τl, τr) =>\n          match (trecConcat τl τrecplus, trecConcat τr τrecplus) with\n          | (Some τrecl, Some τrecr) =>\n            Some (Either τrecl τrecr)\n          | (_, _) => None\n          end\n        | None => None\n        end\n      | (_, _) => None\n      end\n    | cNRAEnvApp op1 op2 =>\n      let appf (τ₁:rtype) := infer_nraenv_core_type op1 τenv τ₁ in\n      olift appf (infer_nraenv_core_type op2 τenv τin)\n    | cNRAEnvEnv =>\n      Some τenv\n    | cNRAEnvAppEnv op1 op2 =>\n      let appf (τ₁:rtype) := infer_nraenv_core_type op1 τ₁ τin in\n      olift appf (infer_nraenv_core_type op2 τenv τin)\n    | cNRAEnvMapEnv op1 =>\n      let mapf (τenv':rtype) :=\n          lift Coll (infer_nraenv_core_type op1 τenv' τin)\n      in\n      olift mapf (tuncoll τenv)\n    end.\n\n  Lemma infer_nraenv_core_type_correct (τenv τin τout:rtype) (e:nraenv_core) :\n    infer_nraenv_core_type e τenv τin = Some τout ->\n    nraenv_core_type τconstants e τenv τin τout.\n  Proof.\n    intros.\n    revert τenv τin τout H.\n    nraenv_core_cases (induction e) Case; intros; simpl in H.\n    - Case \"cNRAEnvGetConstant\"%string.\n      apply type_cNRAEnvGetConstant; assumption.\n    - Case \"cNRAEnvID\"%string.\n      inversion H; clear H.\n      apply type_cNRAEnvID.\n    - Case \"cNRAEnvConst\"%string.\n      apply type_cNRAEnvConst.\n      apply infer_data_type_correct. assumption.\n    - Case \"cNRAEnvBinop\"%string.\n      specialize (IHe1 τenv τin); specialize (IHe2 τenv τin).\n      destruct (infer_nraenv_core_type e1 τenv τin);\n        destruct (infer_nraenv_core_type e2 τenv τin); simpl in *;\n      try discriminate.\n      specialize (IHe1 r eq_refl); specialize (IHe2 r0 eq_refl).\n      apply (@type_cNRAEnvBinop m τconstants τenv τin r r0 τout); try assumption.\n      apply infer_binary_op_type_correct; assumption.\n    - Case \"cNRAEnvUnop\"%string.\n      specialize (IHe τenv τin).\n      destruct (infer_nraenv_core_type e τenv τin); simpl in *;\n      try discriminate.\n      specialize (IHe r eq_refl).\n      apply (@type_cNRAEnvUnop m τconstants τenv τin r τout); try assumption.\n      apply infer_unary_op_type_correct; assumption.\n    - Case \"cNRAEnvMap\"%string.\n      case_eq (infer_nraenv_core_type e2 τenv τin); intros; simpl in *.\n      + specialize (IHe2 τenv τin r H0). rewrite H0 in H. simpl in *.\n        unfold lift in H.\n        case_eq (tuncoll r); intros. rewrite H1 in *.\n        inversion H. subst. clear H H0.\n        case_eq (infer_nraenv_core_type e1 τenv r0); intros.\n        specialize (IHe1 τenv r0 r1 H).\n        rewrite H in H3.\n        inversion H3.\n        apply (@type_cNRAEnvMap m τconstants τenv τin r0 r1); try assumption.\n        apply tuncoll_correct in H1.\n        rewrite <- H1; assumption.\n        rewrite H in H3; congruence.\n        rewrite H1 in H; simpl in H; congruence.\n      + rewrite H0 in H. simpl in H; congruence.\n    - Case \"cNRAEnvMapProduct\"%string.\n      case_eq (infer_nraenv_core_type e2 τenv τin); intros.\n      + specialize (IHe2 τenv τin r H0). rewrite H0 in H; simpl in *.\n        unfold tmapConcatInput in H.\n        destruct r; try congruence.\n        destruct x; simpl in H; try congruence.\n        destruct x; simpl in H; try congruence.\n        clear H0.\n        destruct k; simpl in H; [congruence| ].\n        destruct (from_Rec₀ srl e) as [l1' [pf1' [eq11 eq12]]].\n        assert (exist (fun τ₀ : rtype₀ => wf_rtype₀ τ₀ = true) (Coll₀ (Rec₀ Closed srl)) e =\n                Coll (Rec Closed l1' pf1')) by (rewrite eq12; apply rtype_fequal; reflexivity).\n        rewrite H0 in IHe2; clear H0.\n        simpl in H; clear eq12 eq11 e.\n        assert (RecMaybe Closed l1' = Some (Rec Closed l1' pf1')) by apply RecMaybe_pf_some.\n        rewrite H0 in H; clear H0.\n        case_eq (infer_nraenv_core_type e1 τenv (Rec Closed l1' pf1')); intros.\n        * rewrite H0 in H; simpl in H.\n          destruct r; try congruence.\n          destruct x; simpl in H; try congruence.\n          destruct x; simpl in H; try congruence.\n          destruct k; simpl in H; try congruence.\n          destruct (from_Rec₀ srl0 e) as [l2' [pf2' [eq21 eq22]]].\n          assert (exist (fun τ₀ : rtype₀ => wf_rtype₀ τ₀ = true) (Coll₀ (Rec₀ Closed srl0)) e =\n                  Coll (Rec Closed l2' pf2')) by (rewrite eq22; apply rtype_fequal; reflexivity).\n          rewrite H1 in *.\n          specialize (IHe1 τenv (Rec Closed l1' pf1') (Coll (Rec Closed l2' pf2')) H0).\n          assert (is_list_sorted ODT_lt_dec\n                                 (domain (rec_concat_sort l1' l2')) = true)\n            by (apply (rec_concat_sort_sorted l1' l2'); reflexivity).\n          assert (RecMaybe Closed (rec_concat_sort l1' l2') = Some (Rec Closed (rec_concat_sort l1' l2') H2))\n            by apply RecMaybe_pf_some.\n          simpl in H.\n          clear e eq22 H1 eq21 srl0 H0.\n          generalize (@type_cNRAEnvMapProduct m τconstants τenv τin l1' l2' (rec_concat_sort l1' l2')\n                                   e1 e2 pf1' pf2' H2 IHe1 IHe2 eq_refl); intros.\n          assert (τout = (Coll (Rec Closed (rec_concat_sort l1' l2') H2))).\n          assert ((@RecMaybe (@basic_model_foreign_type m)\n            (@brand_model_relation (@basic_model_foreign_type m)\n               (@basic_model_brand_model m)) Closed\n            (@rec_concat_sort string ODT_string\n               (@sig (@rtype₀ (@basic_model_foreign_type m))\n                  (fun τ₀ : @rtype₀ (@basic_model_foreign_type m) =>\n                   @eq bool\n                     (@wf_rtype₀ (@basic_model_foreign_type m)\n                        (@brand_model_relation\n                           (@basic_model_foreign_type m)\n                           (@basic_model_brand_model m)) τ₀) true)) l1'\n               l2')) = \n           (@RecMaybe (@basic_model_foreign_type m)\n            (@brand_model_relation (@basic_model_foreign_type m)\n               (@basic_model_brand_model m)) Closed\n            (@rec_concat_sort string ODT_string\n               (@rtype (@basic_model_foreign_type m)\n                  (@brand_model_relation (@basic_model_foreign_type m)\n                                         (@basic_model_brand_model m))) l1' l2')))\n            by reflexivity.\n          rewrite <- H1 in H.\n          destruct (RecMaybe Closed (rec_concat_sort l1' l2')).\n          inversion H.\n          rewrite H5.\n          inversion H3.\n          rewrite <- H5.\n          rewrite H6; reflexivity.\n          congruence.\n          rewrite H1.\n          assumption.\n        * rewrite H0 in H; simpl in H; congruence.\n      + rewrite H0 in H; simpl in H; congruence.\n    - Case \"cNRAEnvProduct\"%string.\n      case_eq (infer_nraenv_core_type e1 τenv τin); intros.\n      case_eq (infer_nraenv_core_type e2 τenv τin); intros.\n      + specialize (IHe1 τenv τin r H0). rewrite H0 in H; simpl in *.\n        unfold tmapConcatInput in H.\n        destruct r; try congruence.\n        destruct x; simpl in H; try congruence.\n        destruct x; simpl in H; try congruence.\n        destruct k; simpl in H; try congruence.\n        clear H0.\n        rewrite H1 in H; simpl in H.\n        destruct (from_Rec₀ srl e) as [l1' [pf1' [eq11 eq12]]].\n        assert (exist (fun τ₀ : rtype₀ => wf_rtype₀ τ₀ = true) (Coll₀ (Rec₀ Closed srl)) e =\n                Coll (Rec Closed l1' pf1')) by (rewrite eq12; apply rtype_fequal; reflexivity).\n        rewrite H0 in IHe1; clear H0.\n        simpl in H; clear eq12 eq11 e.\n        assert (RecMaybe Closed l1' = Some (Rec Closed l1' pf1')) by apply RecMaybe_pf_some.\n        rewrite H0 in H; clear H0.\n        destruct r0; try congruence.\n        destruct x; simpl in H; try congruence.\n        destruct x; simpl in H; try congruence.\n        destruct k; simpl in H; try congruence.\n        destruct (from_Rec₀ srl0 e) as [l2' [pf2' [eq21 eq22]]].\n        assert (exist (fun τ₀ : rtype₀ => wf_rtype₀ τ₀ = true) (Coll₀ (Rec₀ Closed srl0)) e =\n                Coll (Rec Closed l2' pf2')) by (rewrite eq22; apply rtype_fequal; reflexivity).\n        rewrite H0 in *.\n        specialize (IHe2 τenv τin (Coll (Rec Closed l2' pf2')) H1).\n        assert (is_list_sorted ODT_lt_dec\n                               (domain (rec_concat_sort l1' l2')) = true)\n          by (apply (rec_concat_sort_sorted l1' l2'); reflexivity).\n        assert (RecMaybe Closed (rec_concat_sort l1' l2') = Some (Rec Closed (rec_concat_sort l1' l2') H2))\n          by apply RecMaybe_pf_some.\n        clear e eq22 H1 eq21 srl0 H0.\n        generalize (@type_cNRAEnvProduct m τconstants τenv τin l1' l2' (rec_concat_sort l1' l2')\n                               e1 e2 pf1' pf2' H2 IHe1 IHe2 eq_refl); intros.\n        assert (τout = (Coll (Rec Closed (rec_concat_sort l1' l2') H2))).\n        assert (τout = (Coll (Rec Closed (rec_concat_sort l1' l2') H2))).\n          assert ((@RecMaybe (@basic_model_foreign_type m)\n            (@brand_model_relation (@basic_model_foreign_type m)\n               (@basic_model_brand_model m)) Closed\n            (@rec_concat_sort string ODT_string\n               (@sig (@rtype₀ (@basic_model_foreign_type m))\n                  (fun τ₀ : @rtype₀ (@basic_model_foreign_type m) =>\n                   @eq bool\n                     (@wf_rtype₀ (@basic_model_foreign_type m)\n                        (@brand_model_relation\n                           (@basic_model_foreign_type m)\n                           (@basic_model_brand_model m)) τ₀) true)) l1'\n               l2')) = \n           (@RecMaybe (@basic_model_foreign_type m)\n            (@brand_model_relation (@basic_model_foreign_type m)\n               (@basic_model_brand_model m)) Closed\n            (@rec_concat_sort string ODT_string\n               (@rtype (@basic_model_foreign_type m)\n                       (@brand_model_relation (@basic_model_foreign_type m)\n                                              (@basic_model_brand_model m))) l1' l2')))\n          by reflexivity.\n          rewrite <- H1 in H.\n        destruct (RecMaybe Closed (rec_concat_sort l1' l2')).\n        inversion H.\n        rewrite H5 in *.\n        inversion H3.\n        rewrite <- H6.\n        auto.\n        congruence.\n        assumption.\n        rewrite H1.\n        auto.\n      + rewrite H1 in H. simpl in H.\n        destruct ((olift tmapConcatInput (infer_nraenv_core_type e1 τenv τin))); simpl in H.\n        destruct (RecMaybe Closed l); congruence.\n        congruence.\n      + rewrite H0 in H; simpl in H; congruence.\n    - Case \"cNRAEnvSelect\"%string.\n      simpl.\n      case_eq (infer_nraenv_core_type e2 τenv τin); intros; simpl in *.\n      + specialize (IHe2 τenv τin r H0). rewrite H0 in H. simpl in *.\n        unfold lift in H.\n        case_eq (tuncoll r); intros. rewrite H1 in *.\n        inversion H. subst. clear H H0.\n        case_eq (infer_nraenv_core_type e1 τenv r0); intros.\n        specialize (IHe1 τenv r0 r1 H).\n        rewrite H in H3.\n        destruct r1; try congruence; simpl in *.\n        destruct x; try congruence; simpl in *.\n        inversion H3; clear H3 H2.\n        apply (@type_cNRAEnvSelect m τconstants τenv τin r0); try assumption.\n        assert (exist (fun τ₀ : rtype₀ => wf_rtype₀ τ₀ = true) Bool₀ e = Bool).\n        apply rtype_fequal; reflexivity.\n        rewrite H0 in IHe1. assumption.\n        apply tuncoll_correct in H1.\n        rewrite <- H1; assumption.\n        rewrite H in H3; congruence.\n        rewrite H1 in H; congruence.\n      + rewrite H0 in H. simpl in H; congruence.\n    - Case \"cNRAEnvDefault\"%string.\n      specialize (IHe1 τenv τin); specialize (IHe2 τenv τin).\n      destruct (infer_nraenv_core_type e1 τenv τin); destruct (infer_nraenv_core_type e2 τenv τin); simpl in *;\n      try discriminate.\n      specialize (IHe1 r eq_refl); specialize (IHe2 r0 eq_refl).\n      case_eq r; case_eq r0;intros; subst; simpl in *.\n      destruct x; destruct x0; try (subst; discriminate); simpl in *.\n      destruct (equiv_dec x0 x); try congruence.\n      inversion H; clear H.\n      assert (exist (fun τ₀ : rtype₀ => wf_rtype₀ τ₀ = true) (Coll₀ x0) e0 = exist (fun τ₀ : rtype₀ => wf_rtype₀ τ₀ = true) (Coll₀ x) e).\n      apply rtype_fequal; simpl. subst. rewrite e3; reflexivity.\n      rewrite H in *; clear H1 H e3 x0 e0 τout.\n      assert (exists τ, Coll τ = exist (fun τ₀ : rtype₀ => wf_rtype₀ τ₀ = true) (Coll₀ x) e).\n      exists (exist (fun τ₀ : rtype₀ => wf_rtype₀ τ₀ = true) x e).\n      apply rtype_fequal; simpl; reflexivity.\n      elim H; clear H; intros.\n      rewrite <- H in *.\n      apply type_cNRAEnvDefault; assumption.\n    - Case \"cNRAEnvEither\"%string.\n      unfold tuneither in H.\n      destruct τin.\n      destruct x; simpl in *; try discriminate.\n      match_case_in H; intros; rewrite H0 in H; try discriminate.\n      match_case_in H; intros; rewrite H1 in H; try discriminate.\n      match_destr_in H.\n      red in e0.\n      invcs H; subst.\n      specialize (IHe1 _ _ _ H0).\n      specialize (IHe2 _ _ _ H1).\n      erewrite Either_canon\n      ; eapply type_cNRAEnvEither\n      ; eauto.\n    - Case \"cNRAEnvEitherConcat\"%string.\n      case_eq (infer_nraenv_core_type e1 τenv τin); case_eq (infer_nraenv_core_type e2 τenv τin); simpl in *; intros;\n      rewrite H0 in *; rewrite H1 in *; try discriminate.\n      unfold tuneither in H.\n      destruct r0; simpl in H.\n      destruct x; simpl in H; try discriminate.\n      destruct x1; simpl in H; try discriminate.\n      destruct r; simpl in H; try discriminate.\n      destruct x; simpl in H; try discriminate.\n      match goal with\n      | [H:context [from_Rec₀ _ ?x] |- _ ] => revert H; generalize x;\n                                                let pff := fresh \"pf\" in\n                                                intros pff H\n      end.\n      destruct k; simpl in H; try discriminate\n      ; destruct k0; simpl in H; try (destruct (from_Rec₀ srl pf); destruct (from_Rec₀ srl0 e0); simpl in H; try discriminate).\n      rewrite @RecMaybe_rec_concat_sort in H.\n      destruct x2; simpl in H; try discriminate.\n      match goal with\n      | [H:context [from_Rec₀ _ ?x] |- _ ] => revert H; generalize x;\n                                                let pff := fresh \"pf\" in\n                                                intros pff H\n      end.\n      destruct k; simpl in H; try discriminate\n      ; [ destruct (from_Rec₀ srl1 pf0); try discriminate | ].\n      case_eq (from_Rec₀ (k:=Closed) srl1 pf0); intros.\n      rewrite H2 in H.\n      rewrite @RecMaybe_rec_concat_sort in H.\n      invcs H.\n      specialize (IHe1 _ _ _ H1).\n      specialize (IHe2 _ _ _ H0).\n      destruct e3 as [? [??]].\n      destruct e4 as [? [??]].\n      destruct e5 as [? [??]].\n      subst.\n      destruct (Either_canon_ex _ _ e) as [pfl [pfr eqq]].\n      rewrite eqq in IHe1.\n      clear eqq.\n      destruct (to_Rec _ _ pfl) as [? eqq1].\n      destruct (to_Rec _ _ pfr) as [? eqq2].\n      rewrite eqq1, eqq2 in IHe1.\n      destruct (to_Rec _ _ e0) as [? eqq3].\n      rewrite eqq3 in IHe2.\n      eapply type_cNRAEnvEitherConcat; eauto.\n    - Case \"cNRAEnvApp\"%string.\n      specialize (IHe2 τenv τin).\n      destruct (infer_nraenv_core_type e2 τenv τin).\n      specialize (IHe2 r eq_refl).\n      econstructor; eauto.\n      simpl in *; congruence.\n    - Case \"cNRAEnvEnv\"%string.\n      inversion H; apply type_cNRAEnvEnv.\n    - Case \"cNRAEnvAppEnv\"%string.\n      specialize (IHe2 τenv τin).\n      destruct (infer_nraenv_core_type e2 τenv τin).\n      simpl in H.\n      specialize (IHe2 r eq_refl).\n      specialize (IHe1 r τin τout).\n      econstructor; eauto.\n      econstructor; eauto.\n      simpl in *; congruence.\n    - Case \"cNRAEnvMapEnv\"%string.\n      case_eq (tuncoll τenv); intros.\n      + apply tuncoll_correct in H0.\n        subst.\n        simpl in H.\n        assert (exist (fun τ₀ : rtype₀ => wf_rtype₀ τ₀ = true) \n                      (` r) (proj2_sig r) = r) by (apply rtype_fequal; reflexivity).\n        rewrite H0 in H; clear H0.\n        case_eq (infer_nraenv_core_type e r τin); intros; simpl in *.\n        * unfold lift in H.\n          rewrite H0 in H; simpl in H.\n          inversion H. subst; clear H.\n          specialize (IHe r τin r0 H0).\n          apply (@type_cNRAEnvMapEnv m τconstants r τin r0 e IHe).\n        * rewrite H0 in H; simpl in H; congruence.\n      + rewrite H0 in H; simpl in H; congruence.\n  Qed.\n\n  (* Still should try and prove most specific and completeness theorems ... *)\n  \nEnd TcNRAEnvInfer.\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/cNRAEnv/Typing/TcNRAEnvInfer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.28192409314802624}}
{"text": "(** * Definition of Context Free Grammars *)\nRequire Import Coq.Strings.String Coq.Lists.List Coq.Program.Program.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.BaseTypes.\nRequire Import Fiat.Parsers.Reachable.MaybeEmpty.Core.\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} {HSLM : StringLikeMin Char} {predata : @parser_computational_predataT Char} (G : grammar Char).\n\n  Context (ch : Char) (valid : nonterminals_listT).\n\n  (** Relation defining if a character is reachable *)\n  Inductive reachable_from_productions : productions Char -> Type :=\n  | ReachableHead : forall pat pats, reachable_from_production pat\n                                     -> reachable_from_productions (pat::pats)\n  | ReachableTail : forall pat pats, reachable_from_productions pats\n                                     -> reachable_from_productions (pat::pats)\n  with reachable_from_production : production Char -> Type :=\n  | ReachableProductionHead : forall it its, maybe_empty_production G valid its\n                                             -> reachable_from_item it\n                                             -> reachable_from_production (it::its)\n  | ReachableProductionTail : forall it its, reachable_from_production its\n                                             -> reachable_from_production (it::its)\n  with reachable_from_item : item Char -> Type :=\n  | ReachableTerminal : forall P, is_true (P ch) -> reachable_from_item (Terminal P)\n  | ReachableNonTerminal : forall nt, is_valid_nonterminal valid (of_nonterminal nt)\n                                      -> reachable_from_productions (Lookup G nt)\n                                      -> reachable_from_item (NonTerminal nt).\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/Reachable/OnlyLast/Reachable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.28192408636649474}}
{"text": "(** * SLOT model checker *)\nFrom LibTx Require Import\n     FoldIn\n     Misc\n     EventTrace\n     Permutation\n     SLOT.Zipper\n     SLOT.Hoare\n     SLOT.Ensemble\n     SLOT.Generator.\n\nFrom Coq Require Import\n     List\n     Program\n     Logic.Classical_Prop\n     Logic.Decidable\n     Relations\n     Lia.\n\nImport ListNotations.\n\nFrom Coq Require\n     Vector\n     Fin.\n\nFrom Hammer Require Import\n     Tactics.\n\nModule Z := Zipper.\n\nModule Vec := Vector.\n\nOpen Scope list_scope.\nOpen Scope hoare_scope.\nOpen Scope zipper_scope.\n\nLemma trace_elems_commute_dec `{StateSpace} a b : decidable (trace_elems_commute a b).\nProof.\n  apply classic.\nQed.\n\nSection comm_rel.\n  Class te_commut_rel {A} :=\n    { comm_rel : relation A;\n      comm_rel_symm : symmetric _ comm_rel;\n      comm_rel_dec : forall a b, decidable (comm_rel a b);\n    }.\n\n  Definition always_can_switch {A} (_ _ : A) : Prop := True.\n\n  Program Instance nonCommRel `{StateSpace} : @te_commut_rel TE :=\n    { comm_rel a b := not (trace_elems_commute a b)\n    }.\n  Next Obligation.\n  unfold symmetric. intros x y Hcomm.\n  firstorder. Qed.\n  Next Obligation.\n  unfold decidable. apply classic. Qed.\n\n  Program Instance alwaysCommRel {TE} : @te_commut_rel TE :=\n    { comm_rel := always_can_switch;\n    }.\n  Next Obligation.\n  easy. Qed.\n  Next Obligation.\n  cbv. left. easy. Qed.\nEnd comm_rel.\n\nModule ZipIlv.\n  Section defn.\n    Context `{Hssp : StateSpace} (Hcomm_rel : @te_commut_rel TE).\n\n    Let T := list TE.\n    Let TT := list T.\n\n    Definition Traces := Z.t T.\n\n    Definition clean (l : T) := match l with\n                                | [] => None\n                                | _  => Some l\n                                end.\n\n    Inductive MInt_ : Traces -> @TraceEnsemble TE :=\n    | mint_nil :\n        MInt_ ([], None, []) []\n    | mint_cons : forall te rest l r t,\n        MInt_ (l, clean rest, r) t ->\n        MInt_ (l, Some (te :: rest), r) (te :: t)\n    | mint_cons_l : forall te rest l r zipper t,\n        zipper >z (l, clean rest, r) ->\n        MInt_ zipper t ->\n        MInt_ (l, Some (te :: rest), r) (te :: t)\n    | mint_cons_r : forall te te' rest l r zipper t,\n        zipper <z (l, clean rest, r)->\n        comm_rel te te' ->\n        MInt_ zipper (te' :: t) ->\n        MInt_ (l, Some (te :: rest), r) (te :: te' :: t).\n\n    Inductive MInt tt : @TraceEnsemble TE :=\n      mint : forall z t,\n        Z.zipper_of z tt ->\n        MInt_ z t ->\n        MInt tt t.\n  End defn.\n\n  Section tests.\n    Context `{Hssp : StateSpace} (Hcomm_rel : @te_commut_rel TE).\n\n    Ltac inv H := inversion_ H; clear H.\n\n    Goal forall a b,\n        MInt Hcomm_rel [[a]; [b]] [a; b] /\\\n        (comm_rel a b -> MInt Hcomm_rel [[a]; [b]] [b; a]).\n    Proof.\n      split.\n      { apply mint with (z := ([], Some [a], [[b]])).\n        { constructor. }\n        apply mint_cons_l with (zipper := ([], Some [b], [])); repeat constructor.\n      }\n      { intros Hcomm.\n        apply mint with (z := ([[a]], Some [b], [])).\n        { repeat constructor. }\n        apply mint_cons_r with (zipper := ([], Some [a], [])); repeat constructor.\n        now apply comm_rel_symm.\n      }\n    Qed.\n\n    Goal forall a b t,\n        ~comm_rel a b ->\n        MInt Hcomm_rel [[a]; [b]] t ->\n        t = [a; b].\n      intros a b t Hcomm H. destruct H. cbv in H.\n      inv H.\n      - inv H0.\n        + inv H5.\n        + inv H5. inv H6.\n          * inversion H4. subst. reflexivity.\n          * exfalso. inv H4.\n          * exfalso. inv H4.\n        + exfalso. inv H5.\n      - inv H3.\n        inv H0.\n        + exfalso. inv H5.\n        + exfalso. inv H5.\n        + inv H5. inv H7;\n          apply comm_rel_symm in H6; contradiction.\n    Qed.\n\n    Goal forall a b t,\n        comm_rel a b ->\n        MInt Hcomm_rel [[a]; [b]] t ->\n        t = [a; b] \\/ t = [b; a].\n      intros a b t Hcomm H. destruct H. cbv in H.\n      inv H.\n      - inv H0.\n        + inv H5.\n        + inv H5. inv H6.\n          * inversion H4. subst. left. reflexivity.\n          * exfalso. inv H4.\n          * exfalso. inv H4.\n        + exfalso. inv H5.\n      - inv H3.\n        inv H0.\n        + exfalso. inv H5.\n        + exfalso. inv H5.\n        + inv H5. inv H7.\n          * inversion H0. subst. right. reflexivity.\n          * exfalso. inv H1.\n          * exfalso. inv H2.\n    Qed.\n  End tests.\n\n  Section prune_interleavings.\n    Context `{Hssp : StateSpace}.\n\n    Lemma left_of_self {A} (z1 z2 : Z.t A) :\n            z1 >z z2 ->\n            Z.zipper_of z1 (Z.to_list z2).\n    Admitted.\n\n    Lemma right_of_self {A} (z1 z2 : Z.t A) :\n            z1 <z z2 ->\n            Z.zipper_of z1 (Z.to_list z2).\n    Admitted.\n\n    Fixpoint mint_add z l m r te t\n             (Hz : Z.zipper_of z (Z.to_list (l, clean m, r)))\n             (Ht : MInt_ nonCommRel z t) {struct Ht} :\n      exists t', exists z',\n          Z.zipper_of z'(Z.to_list (l, Some (te :: m), r)) /\\\n          MInt_ nonCommRel z' t' /\\\n          Permutation trace_elems_commute (te :: t) t'.\n    Proof.\n      inversion_ Ht; clear Ht.\n      { exists []. exists ([], None, []). sauto. }\n      { apply mint_add with (l := l0) (m := rest) (r := r0) (te := te) in H.\n        2:{ apply Z.left_eq_self. }\n    Admitted.\n\n    Lemma zipper_of_trans {A} (l : list A) z1 z2 :\n        Z.zipper_of z1 l ->\n        Z.zipper_of z2 (Z.to_list z1) ->\n        Z.zipper_of z2 l.\n    Admitted.\n\n    Fixpoint mint_prune0 traces zipper t\n             (Hz : Z.zipper_of zipper traces)\n             (Ht : MInt_ alwaysCommRel zipper t) {struct Ht} :\n      exists t', exists zipper',\n                Z.zipper_of zipper' traces /\\\n                MInt_ nonCommRel zipper' t' /\\\n                Permutation trace_elems_commute t t'.\n    Proof.\n      destruct Ht as [\n                     |te rest l r t Ht\n                     |te rest l r zipper' t Hz' Ht\n                     |te te' rest l r zipper' t Hz' Hcomm Ht\n                     ].\n      { exists []. sauto. }\n      { apply mint_prune0 with (traces := Z.to_list (l, clean rest, r)) in Ht.\n        2:{ now apply Z.left_eq_self. }\n        destruct Ht as [t' [z' [Hz' [Ht' Htt']]]].\n        apply mint_add with (te := te) (t := t') in Hz'; trivial.\n        destruct Hz' as [t'' [z'' [Hz'' [Ht'' Ht't'']]]].\n        exists t''. exists z''. repeat split; auto.\n        - eapply zipper_of_trans; eauto.\n        - apply permut_cons with (a := te) in Htt'.\n          eapply permut_trans; eauto.\n      }\n      { apply mint_prune0 with (traces := Z.to_list (l, clean rest, r)) in Ht.\n        2:{ now apply left_of_self. }\n        destruct Ht as [t' [z' [Hz_ [Ht' Htt']]]].\n        apply mint_add with (te := te) (t := t') in Hz_; trivial.\n        destruct Hz_ as [t'' [z'' [Hz'' [Ht'' Ht't'']]]].\n        exists t''. exists z''. repeat split; auto.\n        - eapply zipper_of_trans; eauto.\n        - apply permut_cons with (a := te) in Htt'.\n          eapply permut_trans; eauto.\n      }\n      { apply mint_prune0 with (traces := Z.to_list (l, clean rest, r)) in Ht.\n        2:{ now apply right_of_self. }\n        destruct Ht as [t' [z' [Hz_ [Ht' Htt']]]].\n        apply mint_add with (te := te) (t := t') in Hz_; trivial.\n        destruct Hz_ as [t'' [z'' [Hz'' [Ht'' Ht't'']]]].\n        exists t''. exists z''. repeat split; auto.\n        - eapply zipper_of_trans; eauto.\n        - apply permut_cons with (a := te) in Htt'.\n          eapply permut_trans; eauto.\n      }\n    Qed.\n\n    Lemma mint_prune traces t\n             (Ht : MInt alwaysCommRel traces t) :\n      exists t',\n        MInt nonCommRel traces t' /\\\n        Permutation trace_elems_commute t t'.\n    Proof with trivial.\n      destruct Ht as [zipper t Hz Ht].\n      eapply mint_prune0 in Ht; eauto.\n      destruct Ht as [t' [z' [Hz' [Ht Htt']]]].\n      exists t'. split.\n      - apply mint with (z := z'); auto.\n      - assumption.\n    Qed.\n\n    Theorem mint_noncomm_sufficient : forall traces,\n        sufficient_replacement_p (MInt alwaysCommRel traces) (MInt nonCommRel traces).\n    Proof.\n      intros traces t Ht.\n      now apply mint_prune in Ht.\n    Qed.\n  End prune_interleavings.\nEnd ZipIlv.\n\nModule VecIlv.\n  Open Scope vector_scope.\n\n  Section defn.\n    Context `{Hssp : StateSpace} (Hcomm_rel : @te_commut_rel TE).\n\n    Let T := list TE.\n    Let TT := list T.\n\n    Definition Traces := Vec.t T.\n\n    Definition vec_append {N} i te (vec : Vec.t (list TE) N) :=\n      let rest := Vec.nth vec i in\n      Vec.replace vec i (te :: rest).\n\n    Inductive MInt Nelems : forall (start : Fin.t Nelems), Traces Nelems -> @TraceEnsemble TE :=\n    | mint_nil : forall i,\n        MInt Nelems i (vec_same Nelems []) []\n    | mint_cons1 : forall (i j : Fin.t Nelems) vec te t,\n        i <= j ->\n        MInt Nelems j vec t ->\n        MInt Nelems i (vec_append i te vec) (te :: t)\n    | mint_cons2 : forall (i j : Fin.t Nelems) vec te_i te_j t,\n        j < i ->\n        comm_rel te_i te_j ->\n        MInt Nelems j vec (te_j :: t) ->\n        MInt Nelems i (vec_append i te_i vec) (te_i :: te_j :: t).\n\n    Definition MInt_ (tt : TT) : @TraceEnsemble TE :=\n      fun t => exists i, MInt (length tt) i (Vec.of_list tt) t.\n  End defn.\n\n  Section prune_interleavings.\n    Context `{Hssp : StateSpace}.\n\n    Lemma vec_append_swap {N} (i j : Fin.t N) vec (te_i te_j : TE) :\n      i <> j ->\n      vec_append j te_j (vec_append i te_i vec) = vec_append i te_i (vec_append j te_j vec).\n    Admitted.\n\n    Ltac swap_vec_append := rewrite vec_append_swap; [|intros nonsense; subst; lia].\n\n    Fixpoint mint_add0 {N} (i k : Fin.t N) te_i te' t0 vec\n             (Ht : MInt nonCommRel N k vec (te' :: t0))\n             (Hik : k < i)\n             (Hcomm0 : trace_elems_commute te_i te')\n             {struct Ht} :\n      exists t' : list TE,\n          MInt nonCommRel N k (vec_append i te_i vec) (te' :: t') /\\\n          Permutation trace_elems_commute (te_i :: te' :: t0) (te' :: t').\n    Proof with eauto.\n      (* Welcome to the hell proof! *)\n      remember (te' :: t0) as t_.\n      destruct Ht as [k\n                     |k j vec te_k t Hij Ht\n                     |k j vec te_k te_j t Hij Hcomm Ht\n                     ];\n        [discriminate\n        |replace te' with te_k in * by congruence; clear Heqt_..\n        ].\n      2:{ destruct (trace_elems_commute_dec te_i te_j).\n          - apply mint_add0 with (te_i := te_i) (i := i) in Ht; [|lia|assumption].\n            destruct Ht as [t' [Ht' Hperm']].\n            exists (te_j :: t'). split.\n            + swap_vec_append.\n              eapply mint_cons2...\n            + apply permut_cons with (a := te_k) in Hperm'.\n              eapply permut_trans...\n              now apply permut_head'.\n          - exists (te_i :: te_j :: t). split.\n            + swap_vec_append.\n              apply mint_cons1 with (j0 := i); [lia|].\n              apply mint_cons2 with (j0 := j); [lia|auto..].\n            + now apply permut_head'.\n      }\n      { inversion_ Ht.\n        - exists [te_i]. split.\n          + swap_vec_append.\n            apply mint_cons1 with (j0 := i); [lia|].\n            apply mint_cons1 with (j0 := i); [lia|].\n            constructor.\n          + now apply permut_head'.\n        - rename te into te_j.\n          destruct (PeanoNat.Nat.lt_ge_cases j i).\n          2:{ exists (te_i :: te_j :: t1). split.\n              - swap_vec_append.\n                apply mint_cons1 with (j1 := i); [lia|].\n                apply mint_cons1 with (j1 := j); [lia|assumption].\n              - now apply permut_head'.\n          }\n          { destruct (trace_elems_commute_dec te_i te_j) as [Hte_ij|Hte_ij].\n            - apply mint_add0 with (i := i) (te_i := te_i) in Ht; [|lia|assumption].\n              destruct Ht as [t' [Ht' Hperm']].\n              exists (te_j :: t'). split.\n              + swap_vec_append.\n                eapply mint_cons1...\n              + apply permut_cons with (a := te_k) in Hperm'.\n                now apply permut_head.\n            - exists (te_i :: te_j :: t1). split.\n              + swap_vec_append.\n                apply mint_cons1 with (j1 := i); [lia|].\n                apply mint_cons2 with (j1 := j); [lia|assumption..].\n              + apply permut_head; [assumption|constructor].\n          }\n        - rename j0 into i0. cbn in H0.\n          destruct (PeanoNat.Nat.lt_ge_cases j i).\n          2:{ exists (te_i :: te_i0 :: te_j :: t1). split.\n              + swap_vec_append.\n                apply mint_cons1 with (j0 := i); [lia|].\n                apply mint_cons1 with (j0 := j); [lia|assumption].\n              + now apply permut_head'.\n          }\n          { destruct (trace_elems_commute_dec te_i te_i0).\n            - apply mint_add0 with (i := i) (te_i := te_i) in Ht; [|lia|assumption].\n              destruct Ht as [t' [Ht' Hperm']].\n              exists (te_i0 :: t'). split.\n              + swap_vec_append.\n                eapply mint_cons1...\n              + apply permut_cons with (a := te_k) in Hperm'.\n                now apply permut_head.\n            - exists (te_i :: te_i0 :: te_j :: t1). split.\n              + swap_vec_append.\n                apply mint_cons1 with (j0 := i); [lia|].\n                apply mint_cons2 with (j0 := j); [lia|assumption..].\n              + apply permut_head.\n                * assumption.\n                * constructor.\n          }\n      }\n    Qed.\n\n    Lemma mint_add {N} (i k : Fin.t N) t te vec\n          (Ht : MInt nonCommRel N k vec t) :\n      exists t' : list TE, exists (j : Fin.t N),\n          MInt nonCommRel N j (vec_append i te vec) t' /\\\n          Permutation trace_elems_commute (te :: t) t'.\n    Proof.\n      destruct (PeanoNat.Nat.lt_ge_cases k i) as [Hki|Hki].\n      2:{ exists (te :: t). exists i. split.\n          - apply mint_cons1 with (j := k); auto.\n          - constructor.\n      }\n      destruct t as [|te' t].\n      { inversion_ Ht.\n        exists [te]. exists i. split.\n        - eapply mint_cons1; eauto. constructor.\n        - constructor.\n      }\n      destruct (trace_elems_commute_dec te te') as [Hcomm|Hcomm].\n      { eapply mint_add0 in Hcomm; eauto.\n        destruct Hcomm as [t' H].\n        exists (te' :: t'). exists k. assumption.\n      }\n      { exists (te :: te' :: t). exists i. split.\n        - apply mint_cons2 with (j := k); auto.\n        - constructor.\n      }\n    Qed.\n\n    Fixpoint mint_prune N i0 tt_vec t\n      (Ht : MInt alwaysCommRel N i0 tt_vec t) {struct Ht} :\n      exists t' : list TE, exists i : Fin.t N,\n          MInt nonCommRel N i tt_vec t' /\\ Permutation trace_elems_commute t t'.\n    Proof.\n      destruct Ht as [i\n                     |i j vec te t Hij Ht\n                     |i j vec te_i te_j t Hij Hcomm Ht\n                     ].\n      - exists []. exists i. split; constructor.\n      - subst. apply mint_prune in Ht. destruct Ht as [t' [k [Ht' Hperm]]].\n        specialize (mint_add i k t' te vec Ht') as H.\n        destruct H as [t'' [i' [Ht'' Hperm'']]].\n        exists t''. exists i'. split.\n        + assumption.\n        + eapply permut_cons in Hperm;\n            eapply permut_trans; eauto.\n      - subst. apply mint_prune in Ht. destruct Ht as [t' [k [Ht' Hperm]]].\n        specialize (mint_add i k t' te_i vec Ht') as H.\n        destruct H as [t'' [i' [Ht'' Hperm'']]].\n        exists t''. exists i'. split.\n        + assumption.\n        + eapply permut_cons in Hperm;\n            eapply permut_trans; eauto.\n    Qed.\n\n    Theorem mint_noncomm_sufficient tt : sufficient_replacement_p (MInt_ alwaysCommRel tt) (MInt_ nonCommRel tt).\n    Proof.\n      intros t Ht.\n      destruct Ht as [i0 Ht]. unfold MInt_.\n      remember (Vec.of_list tt) as tt_vec.\n      eapply mint_prune in Ht. destruct Ht as [t' [i [Ht Hperm]]].\n      exists t'. split.\n      - now exists i.\n      - assumption.\n    Qed.\n  End prune_interleavings.\n\n  Section pack_interleaving.\n    Context `{Hssp : StateSpace}.\n\n    Lemma shiftin_append_swap {N} t (i : Fin.t N) (te : TE) vec :\n      (Vec.shiftin t (vec_append i te vec)) = vec_append (Fin.L_R 1 i) te (Vec.shiftin t vec).\n    Admitted.\n\n    Lemma shiftin_cons_append {N} (vec : Vec.t (list TE) N) te t :\n      Vec.shiftin (te :: t) vec = vec_append (last_fin N) te (Vec.shiftin t vec).\n    Proof.\n      induction vec.\n      - reflexivity.\n      - simpl. rewrite IHvec. reflexivity.\n    Qed.\n\n    Fixpoint shiftin_interleaving N i (vec : Vec.t (list TE) N) t1 t2 t\n      (HMint : MInt alwaysCommRel N i vec t1)\n      (HIlv : Interleaving t1 t2 t) {struct HIlv} :\n      exists j, MInt alwaysCommRel (S N) j (Vec.shiftin t2 vec) t.\n    Proof.\n      destruct HIlv as [te t1' t2' t' HIlv\n                       |te t1' t2' t' HIlv\n                       |].\n      (* Solve easy cases first: *)\n      3:{ (* Null: *)\n        inversion_ HMint.\n        exists (last_fin N). rewrite shiftin_same. constructor.\n      }\n      2:{ (* t2: *)\n        apply shiftin_interleaving with (t2 := t2') (t := t') in HMint; auto.\n        rewrite shiftin_cons_append.\n        set (k := last_fin N).\n        exists k.\n        destruct HMint as [j Ht'].\n        destruct (last_fin_is_last j).\n        - subst.\n          apply mint_cons1 with (j := k); auto.\n        - destruct t' as [|te' t'].\n          + inversion_ Ht'.\n            apply mint_cons1 with (j0 := last_fin N); constructor.\n          + apply mint_cons2 with (j0 := j); auto.\n            constructor.\n      }\n      set (i' := Fin.L_R 1 i). exists i'.\n      inversion_ HMint.\n      - eapply shiftin_interleaving in H4; eauto. clear HMint.\n        destruct H4 as [k Ht'].\n        rewrite shiftin_append_swap.\n        destruct (PeanoNat.Nat.lt_ge_cases k i').\n        2:{ now apply mint_cons1 with (j0 := k). }\n        { destruct t' as [|te' t'].\n          - inversion_ Ht'.\n            apply mint_cons1 with (j0 := i'); constructor.\n          - apply mint_cons2 with (j0 := k); auto; constructor.\n        }\n      - eapply shiftin_interleaving in H5; eauto. clear HMint.\n        destruct H5 as [k Ht'].\n        rewrite shiftin_append_swap.\n        destruct (PeanoNat.Nat.lt_ge_cases k i').\n        2:{ now apply mint_cons1 with (j0 := k). }\n        { destruct t' as [|te' t'].\n          - inversion_ Ht'.\n            apply mint_cons1 with (j0 := i'); constructor.\n          - apply mint_cons2 with (j0 := k); auto; constructor.\n        }\n    Qed.\n  End pack_interleaving.\nEnd VecIlv.\n\n(* Deeply magical function from here:\nhttp://jamesrwilcox.com/more-cardinality.html. Reproduced with\npermission from the author *)\nDefinition fin_case n x :\n  forall (P : Fin.t (S n) -> Type),\n    P Fin.F1 ->\n    (forall y, P (Fin.FS y)) ->\n    P x :=\n  match x as x0 in Fin.t n0\n     return\n       forall P,\n         match n0 as n0' return (Fin.t n0' -> (Fin.t n0' -> Type) -> Type) with\n           | 0 => fun _ _ => False\n           | S m => fun x P => P Fin.F1 -> (forall x0, P (Fin.FS x0)) -> P x\n         end x0 P\n  with\n  | Fin.F1 => fun _ H1 _ => H1\n  | Fin.FS _ => fun _ _ HS => HS _\n  end.\n\nLtac fin_dep_destruct v :=\n  let v' := fresh v in\n  rename v into v';\n  generalize dependent v'; intros v'; pattern v';\n  apply fin_case; try clear v'; [|intros v].\n\nLtac fin_all_cases v :=\n  repeat fin_dep_destruct v ; [..|exfalso; inversion v].\n\nSection tests.\n  Goal forall (n : Fin.t 3), const True n.\n  Proof.\n    intros.\n    fin_all_cases n.\n    - constructor.\n    - constructor.\n    - constructor.\n  Qed.\n\n  Goal forall (n m : Fin.t 3), n < m -> const False n.\n  Proof.\n    intros.\n    fin_all_cases n; fin_all_cases m; intros Hnm; try (lia || now inversion Hnm); cbv.\n    3:{\n  Abort.\nEnd tests.\n\nCheck VecIlv.MInt.\n\n(* I can't into Ltac, sorry *)\nLtac destruct_mint H :=\n  let H__type := type of H in\n  lazymatch H__type with\n  | VecIlv.MInt _ ?Nelems ?i0 ?vec ?t =>\n    let Hvec := fresh \"Hvec\" in\n    let vec0 := fresh \"vec\" in\n    let vec' := fresh \"vec\" in\n    let i0' := fresh \"pos_\" in\n    let Hi0' := fresh \"Hpos_\" in\n    let i1 := fresh \"pos\" in\n    let i2 := fresh \"pos\" in\n    let Hij := fresh \"H_\" i1 \"_\" i2 in\n    let te := fresh \"te\" in\n    let te2 := fresh \"te\" in\n    let Hcomm := fresh \"Hcomm\" in\n    let t := fresh \"t\" in\n    remember vec as vec0 eqn:Hvec;\n    remember i0 as i0' eqn:Hi0';\n    destruct H as [i1\n                  |i1 i2 vec' te t Hij H\n                  |i1 i2 vec' te te2 t Hij Hcomm H\n                  ];\n    [inversion_clear Hi0';\n     inversion Hvec\n    |fin_all_cases i1;\n     fin_all_cases i2;\n     intros H Hvec Hi0' Hij;\n     ((now inversion Hij) || clear Hij);\n     inversion_clear Hi0'\n     ..\n    ]\n  | _ =>\n    fail 100 \"The argument doesn't look like MInt\"\n  end.\n\nSection tests.\n  Goal forall `{Hssp : StateSpace} i0 vec t, VecIlv.MInt nonCommRel 2 i0 vec t -> const True t -> False.\n  Proof.\n    intros *. intros H Ht.\n    destruct_mint H.\n    5:{ destruct_mint H.\n        3:{\n  Abort.\n\n  Import Vector.VectorNotations.\n\n  Context `{Hssp : StateSpace nat nat}.\n\n  Let vec := [[1; 2]%list; [3; 4]%list]%vector.\n\n  Goal forall i t, VecIlv.MInt nonCommRel 2 i vec t -> const True t -> False.\n  Proof.\n    subst vec.\n    intros *. intros H Ht.\n    destruct_mint H.\n    - (* Hvec : VecIlv.vec_append Fin.F1 te vec0 = [[1; 2]%list; [3; 4]%list] *)\n  Abort.\nEnd tests.\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/Bruteforce.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2819240863664947}}
{"text": "(*\n * Copyright (c) 2009 Robert Dockins and Aquinas Hobor.\n *\n *)\n\nRequire Import msl.msl_standard.\n\nRequire Import lam_ref_tcb.\nRequire Import lam_ref_eval.\nRequire Import lam_ref_mach_defs.\nRequire Import lam_ref_mach_lemmas.\nRequire Import lam_ref_type_defs.\nRequire Import lam_ref_type_safety.\nRequire Import lam_ref_type_rules.\n\nDefinition unary_primop (f:nat -> nat) : expr :=\n  Lam (prim (v_Nat oo f) (Var 0)).\n\nProgram Definition bin_primop (f:nat -> nat -> nat) : expr :=\n  Lam (prim (fun n1 => Lam (prim (fun n2 => v_Nat (f n1 n2)) (Var 0))) (Var 0)).\nNext Obligation.\n  compute; split; auto.\nQed.\n\nLemma unary_primop_typ : forall f,\n  Typ nil (unary_primop f) (ty_lam ty_nat ty_nat).\nProof.\n  intros; unfold unary_primop.\n  apply T_Abs.\n  apply T_Prim.\n  intros.\n  unfold val_to_exp, v_Nat; simpl.\n  eapply T_Nat.\n  apply T_Var; auto.\nQed.\n\nLemma binary_primop_typ : forall (f:nat -> nat -> nat),\n  Typ nil (bin_primop f) (ty_lam ty_nat (ty_lam ty_nat ty_nat)).\nProof.\n  intros.\n  unfold bin_primop.\n  apply T_Abs.\n  apply T_Prim; intros.\n  unfold val_to_exp; simpl.\n  apply T_Abs.\n  apply T_Prim; intros.\n  unfold val_to_exp, v_Nat; simpl.\n  apply T_Nat.\n  apply T_Var; auto.\n  apply T_Var; auto.\nQed.\n\nDefinition ty_bool := ALL a:pred world, ty_lam a (ty_lam a a).\nDefinition e_true := Lam (Lam (Var 1)).\nDefinition e_false := Lam (Lam (Var 0)).\n\nDefinition e_if b t f :=\n  (App (App (App b (Lam t)) (Lam f)) (Nat 0)).\n\nLemma e_true_typ :\n  Typ nil e_true ty_bool.\nProof.\n  unfold e_true, ty_bool.\n  apply T_UnivI; simpl; intros; auto.\n  apply T_Abs.\n  apply T_Abs.\n  apply T_Var; simpl; auto.\nQed.\n\nLemma e_false_typ :\n  Typ nil e_false ty_bool.\nProof.\n  unfold e_false, ty_bool.\n  apply T_UnivI; simpl; intros; auto.\n  apply T_Abs.\n  apply T_Abs.\n  apply T_Var; simpl; auto.\nQed.\n\nLemma T_if : forall G b t f tau,\n  Typ G b ty_bool ->\n  Typ (TT :: G) t tau ->\n  Typ (TT :: G) f tau ->\n  Typ G (e_if b t f) tau.\nProof.\n  intros.\n  unfold e_if.\n  apply T_App with TT.\n  apply T_App with (ty_lam TT tau).\n  apply T_App with (ty_lam TT tau).\n  change (ty_lam (ty_lam TT tau) (ty_lam (ty_lam TT tau) (ty_lam TT tau)))\n    with ((fun t => ty_lam t (ty_lam t t)) (ty_lam TT tau)).\n  apply T_UnivE.\n  apply H.\n  apply T_Abs; auto.\n  apply T_Abs; auto.\n  apply T_weaken_nil.\n  apply T_sub with ty_nat.\n  apply subp_top.\n  apply T_Nat.\nQed.\n\nProgram Definition isZ : expr -> expr :=\n  prim (fun n => if beq_nat n 0 then e_true else e_false).\nSolve Obligations using (compute; split; auto).\n\nLemma T_isZ : forall G e,\n  Typ G e ty_nat ->\n  Typ G (isZ e) ty_bool.\nProof.\n  intros.\n  unfold isZ.\n  apply T_Prim; intros; auto.\n  unfold val_to_exp; simpl.\n  destruct (beq_nat n 0); simpl.\n  apply e_true_typ.\n  apply e_false_typ.\nQed.\n\nDefinition e_let (def body:expr) :=\n  (App (Lam body) def).\n\nDefinition option (a:pred world) :=\n  ALL b:pred world, ty_lam b (ty_lam (ty_lam a b) b).\n\nDefinition none : expr := Lam (Lam (Var 1)).\nDefinition some : expr := Lam (Lam (Lam (App (Var 0) (Var 2)))).\nDefinition out  : expr := Lam (Lam (App (App (Var 0) (Var 1)) (Lam (Var 0)))).\n\nLemma out_typ :\n  Typ nil out (ALL tau:pred world, ty_lam tau (ty_lam (option tau) tau)).\nProof.\n  intros.\n  unfold out.\n  apply T_UnivI; simpl; intros; auto.\n  apply T_Abs.\n  apply T_Abs.\n  eapply T_App with (ty_lam tau tau).\n  2: apply T_Abs.\n  2: apply T_Var; simpl; auto.\n  apply T_App with tau.\n  2: apply T_Var; simpl; auto.\n  unfold option.\n  change (ty_lam tau (ty_lam (ty_lam tau tau) tau))\n    with ((fun b => ty_lam b (ty_lam (ty_lam tau b) b)) tau).\n  apply T_UnivE.\n  apply T_Var; simpl; auto.\nQed.\n\nLemma none_typ :\n  Typ nil none (ALL tau:pred world, option tau).\nProof.\n  intros.\n  unfold none.\n  unfold option.\n  apply T_UnivI.\n  simpl; auto.\n  intros.\n  apply T_UnivI.\n  simpl; auto.\n  intros b.\n  apply T_Abs.\n  apply T_Abs.\n  apply T_Var.\n  simpl; auto.\nQed.\n\nLemma some_typ :\n  Typ nil some (ALL tau:pred world, ty_lam tau (option tau)).\nProof.\n  unfold some.\n  apply T_UnivI; simpl; intros; auto.\n  apply T_Abs.\n  unfold option.\n  apply T_UnivI; simpl; intros; auto.\n  apply T_Abs.\n  apply T_Abs.\n  apply T_App with tau.\n  apply T_Var; simpl; auto.\n  apply T_Var; simpl; auto.\nQed.\n\nDefinition W := (Lam (App (Var 0) (Var 0))).\nDefinition diverge := App W W.\n\nDefinition W_ty Z := fun X => ty_lam X Z.\nLemma W_ty_cont : forall Z, contractive (W_ty Z).\nProof.\n  intros.\n  unfold W_ty.\n  apply ty_lam_contractive.\n  hnf; simpl; intros.\n  hnf; auto.\n  hnf; simpl; repeat intro.\n  split; hnf; eauto.\nQed.\n\nLemma W_typ : forall Z, Typ nil W (Rec (W_ty Z)).\nProof.\n  intros.\n  rewrite Rec_fold_unfold.\n  2: apply W_ty_cont.\n  unfold W.\n  unfold W_ty.\n  apply T_Abs.\n  apply T_App with (Rec (W_ty Z)).\n  rewrite Rec_fold_unfold.\n  2: apply W_ty_cont.\n  apply T_Var; auto.\n  apply T_Var; auto.\nQed.\n\nLemma diverge_typ : forall t,\n  Typ nil diverge t.\nProof.\n  intros.\n  unfold diverge.\n  apply T_App with (Rec (W_ty t)).\n  generalize (W_typ t).\n  rewrite Rec_fold_unfold at 1; auto.\n  apply W_ty_cont.\n  apply W_typ.\nQed.\n\n(* The standard CBV fixpoint combinator *)\nDefinition Wf := (Lam (App (Var 1) (Lam (App (App (Var 1) (Var 1)) (Var 0))))).\nDefinition Y := Lam (App Wf Wf).\n\nDefinition Wf_ty A B := fun X => ty_lam X (ty_lam A B).\nLemma Wf_ty_cont : forall A B, contractive (Wf_ty A B).\nProof.\n  intros.\n  unfold Wf_ty.\n  apply ty_lam_contractive.\n  repeat intro; auto.\n  repeat intro; split; repeat intro; auto.\nQed.\n\nLemma Wf_typ : forall A B,\n  Typ (ty_lam (ty_lam A B) (ty_lam A B) :: nil) Wf (Rec (Wf_ty A B)).\nProof.\n  intros.\n  unfold Wf.\n  rewrite Rec_fold_unfold.\n  2: apply Wf_ty_cont.\n  unfold Wf_ty.\n  apply T_Abs.\n  apply T_App with (ty_lam A B).\n  apply T_Var; simpl; auto.\n  apply T_Abs.\n  apply T_App with A.\n  apply T_App with (Rec (Wf_ty A B)).\n  rewrite Rec_fold_unfold at 1.\n  2: apply (Wf_ty_cont A B).\n  apply T_Var; auto.\n  apply T_Var; auto.\n  apply T_Var; auto.\nQed.\n\nLemma Y_typ : forall A B,\n  Typ nil Y (ty_lam (ty_lam (ty_lam A B) (ty_lam A B)) (ty_lam A B)).\nProof.\n  intros.\n  unfold Y.\n  apply T_Abs.\n  apply T_App with (Rec (Wf_ty A B)).\n  generalize (Wf_typ A B).\n  rewrite Rec_fold_unfold at 1; auto.\n  apply Wf_ty_cont.\n  apply Wf_typ.\nQed.\n\nDefinition e_fix f := App Y (Lam f).\n\nLemma fix_ty : forall A B G f,\n  Typ (ty_lam A B :: G) f (ty_lam A B) ->\n  Typ G (e_fix f) (ty_lam A B).\nProof.\n  intros.\n  unfold e_fix.\n  apply T_App with (ty_lam (ty_lam A B) (ty_lam A B)).\n  apply T_weaken_nil.\n  apply Y_typ.\n  apply T_Abs.\n  auto.\nQed.\n\n(* The \"backpatching\" fixpoint combinator, AKA Landin's knot. *)\nDefinition refY :=\n  Lam (e_let (New (Lam diverge))\n             (Update (Var 0) (Lam (App (App (Var 2) (Deref (Var 1))) (Var 0))) (Deref (Var 0)) )).\n\nLemma refY_typ : forall A B,\n  Typ nil refY (ty_lam (ty_lam (ty_lam A B) (ty_lam A B)) (ty_lam A B)).\nProof.\n  intros.\n  unfold refY.\n  apply T_Abs.\n  unfold e_let.\n  apply T_App with (ty_ref (ty_lam A B)).\n  2: apply T_New.\n  2: apply T_Abs.\n  2: apply T_weaken_nil.\n  2: apply diverge_typ.\n  apply T_Abs.\n  eapply T_Update.\n  apply T_Var; simpl; auto.\n  apply T_Abs.\n  apply T_App with A.\n  apply T_App with (ty_lam A B).\n  apply T_Var; simpl; auto.\n  apply T_Deref.\n  apply T_Var; simpl; auto.\n  apply T_Var; simpl; auto.\n  apply T_Deref.\n  apply T_Var; simpl; auto.\nQed.\n\nDefinition r_fix f := App refY (Lam f).\n\nLemma rfix_ty : forall A B G f,\n  Typ (ty_lam A B :: G) f (ty_lam A B) ->\n  Typ G (r_fix f) (ty_lam A B).\nProof.\n  intros.\n  unfold r_fix.\n  apply T_App with (ty_lam (ty_lam A B) (ty_lam A B)).\n  apply T_weaken_nil.\n  apply refY_typ.\n  apply T_Abs.\n  assumption.\nQed.\n\n\n(* Factorial function\n *)\nDefinition e_fac : expr :=\n  r_fix (Lam\n          (e_if (isZ (Var 0))\n\n            (* base case *)\n            (Nat 1)\n\n            (* recursive case *)\n            (App (App (bin_primop mult) (Var 1))\n                 (App (Var 2) (App (unary_primop Peano.pred) (Var 1)))))).\n\nLemma e_fac_typ :\n  Typ nil e_fac (ty_lam ty_nat ty_nat).\nProof.\n  unfold e_fac.\n  apply rfix_ty.\n  apply T_Abs.\n  apply T_if.\n  apply T_isZ.\n  apply T_Var; auto.\n  apply T_Nat.\n  apply T_App with ty_nat.\n  apply T_App with ty_nat.\n  apply T_weaken_nil.\n  apply binary_primop_typ.\n  apply T_Var; auto.\n  apply T_App with ty_nat.\n  apply T_Var; auto.\n  apply T_App with ty_nat.\n  apply T_weaken_nil.\n  apply unary_primop_typ.\n  apply T_Var; auto.\nQed.\n\n(* Demonstrate an example of the factorial program\n   working correctly.\n *)\nEval vm_compute in (snd (eval 100 empty_mem (App e_fac (Nat 6)))).\n\n\n(* Our typed calculus is turing-complete.\n   We demonstrate this by embedding the\n   \"untyped\" CBV lambda terms.\n   First we define a type U with the characteristic\n   equation U = U -> U, and then we show that all closed\n   terms formed from abstraction, application and\n   variables can be given this type.\n\n   Turing-completeness follows from the fact that\n   untyped CBV l-calc is turing-complete.\n *)\n\nFixpoint isULTerm (e:expr) : Prop :=\n  match e with\n  | Lam e' => isULTerm e'\n  | App e1 e2 => isULTerm e1 /\\ isULTerm e2\n  | Var _ => True\n  | _ => False\n  end.\n\nLemma U_contractive : contractive (fun X => ty_lam X X).\nProof.\n  apply ty_lam_contractive; hnf; repeat intro; auto.\nQed.\n\nDefinition U := Rec (fun X => ty_lam X X).\nLemma U_eqn : U = ty_lam U U.\nProof.\n  unfold U at 1.\n  rewrite Rec_fold_unfold; fold U; auto.\n  apply U_contractive.\nQed.\n\nFixpoint Ulist (n:nat) :=\n  match n with\n  | 0 => nil\n  | S n' => U :: Ulist n'\n  end.\n\nLemma ULTyped' : forall e n,\n  isULTerm e ->\n  closed' n e ->\n  Typ (Ulist n) e U.\nProof.\n  induction e; simpl; intuition.\n\n  apply T_Var.\n  revert n0 H0; induction n; simpl; intros.\n  inv H0; simpl; auto.\n  destruct n0.\n  omegac.\n  simpl; apply IHn; omega.\n\n  rewrite U_eqn.\n  apply T_Abs.\n  apply (IHe (S n)); auto.\n  replace (S n) with (n+1) by omega; auto.\n\n  apply T_App with U.\n  rewrite <- U_eqn.\n  apply IHe1; auto.\n  apply IHe2; auto.\nQed.\n\nTheorem ULTyped : forall e,\n  closed e /\\ isULTerm e ->\n  Typ nil e U.\nProof.\n  intuition; apply (ULTyped' e 0); 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/programs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.2819090798488639}}
{"text": "(** * Chapter 10 - Type Safety for F-Sub *)\n\n(** ** Part 1 : System F *)\n\nRequire Export Coq.Lists.List.\nRequire Import Coq.Program.Equality.\nFrom Chapter10 Require Export sysf.\nRequire Import Coq.Program.Tactics.\nImport CommaNotation.\n\nLtac inv H := inversion H; try clear H; try subst.\n\nLtac autorevert x :=\n  try (match goal with\n    | [y : ?Y |- ?claim] =>\n      try (match x with y => idtac end; fail 1);\n        match goal with [z : _ |- _] =>\n          match claim with context[z] =>\n            first\n              [ match Y with context[z] => revert y; autorevert x end\n              | match y with z => revert y; autorevert x end]\n          end\n        end\n       end).\n\nDefinition ctx n := fin n -> ty n.\n\nReserved Notation \"'SUB' Delta |- A <: B\"\n         (at level 68, A at level 99, no associativity).\n\n(** *** Properties of Subtyping *)\n\nInductive sub {n} (Delta : ctx n) : ty n -> ty n -> Prop :=\n| SA_top A :\n    SUB Delta |- A <: top\n| SA_Refl x :\n    SUB Delta |- var_ty x <: var_ty x\n| SA_Trans x  B :\n     SUB Delta |- (Delta x) <: B ->  SUB Delta |- var_ty x <: B\n| SA_arrow A1 A2 B1 B2 :\n    SUB Delta |- B1 <: A1 -> SUB Delta |- A2 <: B2 ->\n    SUB Delta |- arr A1 A2 <: arr B1 B2\n| SA_all (A1: ty n) (A2: ty (S n)) B1 B2 :\n    SUB Delta |- B1 <: A1 -> @sub (S n) ((B1, Delta) >> ⟨↑⟩) A2 B2 ->\n    SUB Delta |- all A1 A2 <: all B1 B2\nwhere \"'SUB' Delta |- A <: B\" := (sub Delta A B).\n\nHint Constructors sub.\n\nLemma sub_refl n (Delta: ctx n) A : SUB Delta |- A <: A.\nProof. revert Delta. induction A; intuition; constructor; eauto. Qed.\n\nLemma sub_weak m n (Delta1: ctx m) (Delta2: ctx n) A1 A2 A1' A2' (xi: fin m -> fin n) :\n  SUB Delta1 |- A1 <: A2 ->\n (forall x, (Delta1 x)⟨xi⟩ = Delta2 (xi x)) ->\n  A1' = A1⟨xi⟩ -> A2' = A2⟨xi⟩ ->\n  SUB Delta2 |- A1' <: A2' .\nProof.\n  intros H. autorevert H. induction H; intros; subst; asimpl; econstructor; eauto.\n  - eapply IHsub2; try reflexivity.\n    auto_case. rewrite <- H1. now asimpl.\nQed.\n\nLemma sub_weak1 n (Delta : ctx n) A A' B B' C :\n  SUB Delta |- A <: B ->  A' = A⟨↑⟩ ->  B' = B⟨↑⟩ -> SUB ((C, Delta) >> ⟨↑⟩) |- A' <: B'.\nProof. intros. eapply sub_weak;  eauto. intros x. now asimpl. Qed.\n\nDefinition transitivity_at {n} (B: ty n) := forall m Gamma (A : ty m) C  (xi: fin n -> fin m),\n  SUB Gamma |- A <: B⟨xi⟩ -> SUB Gamma |- B⟨ xi⟩ <: C ->  SUB Gamma |- A <: C.\n\n Lemma transitivity_proj n (Gamma: ctx n) A B C :\n  transitivity_at B ->\n  SUB Gamma |- A <: B -> SUB Gamma |- B <: C -> SUB Gamma |- A <: C.\nProof. intros H. specialize (H n Gamma A C id). now asimpl in H. Qed.\nHint Resolve transitivity_proj.\n\nLemma transitivity_ren m n B (xi: fin m -> fin n) : transitivity_at B -> transitivity_at B⟨xi⟩.\nProof. unfold transitivity_at. intros. eapply H; asimpl in H0; asimpl in H1; eauto. Qed.\n\nLemma sub_narrow n (Delta Delta': ctx n) A C :\n  (forall x, SUB Delta' |- Delta' x <: Delta x) ->\n  (forall x, Delta x = Delta' x \\/ transitivity_at (Delta x)) ->\n  SUB Delta |- A <: C -> SUB Delta' |- A <: C.\nProof with asimpl;eauto.\n  intros H H' HH. autorevert HH. induction HH; intros; eauto.\n  - destruct (H' x); eauto. rewrite H0 in *. eauto.\n  - constructor; eauto.\n    eapply IHHH2.\n    + auto_case; try apply sub_refl.\n      eapply sub_weak; try reflexivity. eapply H. now asimpl.\n    + auto_case. destruct (H' f);  eauto using transitivity_ren.\n      rewrite H0. now left.\nQed.\n\nCorollary sub_trans' n (B : ty n): transitivity_at B.\nProof with asimpl;eauto.\n  unfold transitivity_at.\n  autorevert B. induction B; intros...\n  - depind H...\n  - depind H... depind H0...\n  - depind H... depind H1...\n  - depind H... depind H1...\n    econstructor... clear IHsub0 IHsub3 IHsub1 IHsub2.\n    eapply IHB2; eauto.\n    + asimpl in *. eapply sub_narrow; try eapply H0.\n      * auto_case. apply sub_refl.\n        eapply sub_weak with (xi := ↑); try reflexivity; eauto. now asimpl.\n      * intros [x|]; try cbn; eauto. right. apply transitivity_ren. apply transitivity_ren. eauto.\n    + asimpl in H1_0. auto.\nQed.\n\nCorollary sub_trans n (Delta  : ctx n) A B C:\n  SUB Delta |- A <: B -> SUB Delta |- B <: C -> SUB Delta |- A <: C.\nProof. eauto using sub_trans'. Qed.\n\nLemma sub_substitution m m' (sigma : fin m -> ty m') Delta (Delta': ctx m') A B:\n   (forall x ,  SUB Delta' |- sigma x <: (Delta x)[sigma] ) ->\n   SUB Delta |- A <: B -> SUB Delta' |- subst_ty sigma A <: subst_ty sigma B.\nProof.\n    intros eq H. autorevert H. induction H; try now (econstructor; eauto).\n  - intros. asimpl. eapply sub_refl.\n  - intros. asimpl. eauto. cbn in *. eauto using sub_trans.\n  - intros. asimpl. econstructor; eauto.\n    asimpl. eapply IHsub2.\n    auto_case; asimpl; cbn; eauto using sub_refl.\n    eapply sub_weak; try reflexivity. eapply eq.\n    all: now asimpl.\nQed.\n\n(** *** Type Safety *)\n\nInductive value {m n}: tm m n -> Prop :=\n| Value_abs A s : value(abs A s)\n| Value_tabs A s : value(tabs A s).\n\nReserved Notation \"'TY' Delta ; Gamma |- A : B\"\n  (at level 68, A at level 99, no associativity,\n   format \"'TY'  Delta ; Gamma  |-  A  :  B\").\n\nDefinition dctx m n := fin m -> ty n.\n\nInductive has_ty {m n} (Delta : ctx m) (Gamma : dctx  n m) : tm m n -> ty m -> Prop :=\n| T_Var  x :\n    TY Delta;Gamma |- var_tm x : (Gamma x)\n | T_abs (A: ty m) B (s: tm m (S n)):\n    @has_ty m (S n) Delta (A, Gamma) s B   ->\n    TY Delta;Gamma |- abs A s : arr A B\n| T_app A B s t:\n    TY Delta;Gamma |- s : arr A B   ->   TY Delta;Gamma |- t : A   ->\n    TY Delta;Gamma |- app s t : B\n| T_tabs A B s :\n    @has_ty (S m) n ((A, Delta) >> ⟨↑⟩) (Gamma >> ⟨↑⟩) s B ->\n    TY Delta;Gamma |- tabs A s : all A B\n| T_Tapp A B A' s B' :\n    TY Delta;Gamma |- s : all A B ->\n    SUB Delta |- A' <: A -> B' = subst_ty (A'..) B ->\n    TY Delta;Gamma |- tapp s A' : B'\n | T_Sub A B s :\n    TY Delta;Gamma |- s : A   ->   SUB Delta |- A <: B   ->\n    TY Delta;Gamma |- s : B\nwhere \"'TY' Delta ; Gamma |- s : A\" := (has_ty Delta Gamma s A).\n\nHint Constructors has_ty.\n\nReserved Notation \"'EV' s => t\"\n  (at level 68, s at level 80, no associativity, format \"'EV'   s  =>  t\").\nInductive eval {m n} : tm m n -> tm m n -> Prop :=\n| E_appabs A s t : EV app (abs A s) t => s[ids; t..]\n| E_Tapptabs A s B : EV tapp (tabs A s) B => s[B..; ids]\n| E_appFun s s' t :\n     EV s => s' ->\n     EV app s t => app s' t\n| E_appArg s s' v:\n     EV s => s' -> value v ->\n     EV app v s => app v s'\n| E_TyFun s s' A :\n     EV s => s' ->\n     EV tapp s A => tapp s' A\nwhere \"'EV' s => t\" := (eval s t).\n\n\n(** **** Progress *)\n\nDefinition empty {X} : fin 0 -> X :=\n  fun x => match x with end.\n\nLemma can_form_arr {s: tm 0 0} {A B}:\n  TY empty;empty |- s : arr A B -> value s -> exists C t, s = abs C t.\nProof.\n  intros H.\n  depind H; intros; eauto.\n  all: try now (try destruct x0; try inversion H1).\n  inversion H0; subst; eauto. inversion x.\nQed.\n\nLemma can_form_all {s A B}:\n  TY empty;empty |- s : all A B -> value s -> exists C t, s = tabs C t.\nProof.\n  intros H.\n  depind H; intros; eauto.\n  all: try now (try destruct x0; try inversion H1).\n  inv H0; subst; eauto. inversion x.\nQed.\n\nTheorem ev_progress s A:\n  TY empty;empty |- s : A -> value s \\/ exists t,  EV s => t.\nProof.\n  intros. depind H; eauto; try (left; constructor).\n  - inversion x.\n  - right. edestruct IHhas_ty1 as [? | [? ?]]; try reflexivity.\n    + edestruct (can_form_arr H H1) as [? [? ?]]; subst.\n      eexists. econstructor.\n    + eexists. econstructor. eauto.\n  - right. edestruct IHhas_ty as [? | [? ?]]; try reflexivity.\n    + edestruct (can_form_all H H1) as [? [? ?]]; subst. eexists. econstructor.\n    + eexists. econstructor. eauto.\nQed.\n\n(** **** Preservation *)\n\nLemma context_renaming_lemma m m' n n' (Delta: ctx m') (Gamma: dctx n' m')                                                   (s: tm m n) A (sigma : fin m -> fin m') (tau: fin n -> fin n') Delta' (Gamma' : dctx n m):\n  (forall x, (Delta' x)⟨sigma⟩ = Delta (sigma x)) ->\n  (forall (x: fin n) , (Gamma' x)⟨sigma⟩ =  (Gamma (tau x))) ->\n  TY Delta'; Gamma' |- s : A -> TY Delta; Gamma |- s⟨sigma;tau⟩ : A⟨sigma⟩.\nProof.\n  intros H H' ty. autorevert ty.\n  induction ty; intros; asimpl in *; subst; try now (econstructor; eauto).\n  - rewrite H'. constructor.\n  - constructor. apply IHty; eauto. auto_case.\n  - econstructor. apply IHty; eauto.\n    + auto_case; try now asimpl. rewrite <- H. now asimpl.\n    + intros. asimpl. rewrite <- H'. now asimpl.\n  - eapply T_Tapp with (A0 := A⟨sigma⟩) .\n    asimpl in IHty. eapply IHty; eauto.\n    eapply sub_weak; eauto.\n    now asimpl.\n  - econstructor. eauto.\n    eapply sub_weak; eauto.\nQed.\n\nLemma context_morphism_lemma m m' n n' (Delta: ctx m) (Delta': ctx m') (Gamma: dctx n m) (s: tm m n) A (sigma : fin m -> ty m') (tau: fin n -> tm m' n') (Gamma' : dctx n' m'):\n  (forall x, SUB Delta' |- sigma x <: (Delta x)[sigma]) ->\n  (forall (x: fin n) ,  TY Delta'; Gamma' |- tau x : subst_ty sigma (Gamma x)) ->\n  TY Delta; Gamma |- s : A -> TY Delta'; Gamma' |- s[sigma;tau] : A[sigma].\nProof.\n  intros eq1 eq2 ty. autorevert ty.\n  induction ty; intros; subst; asimpl; try now (econstructor; eauto).\n  - eapply eq2.\n  - constructor. eapply IHty; eauto.\n    auto_case; asimpl.\n    +  assert (subst_ty sigma (Gamma f)  = ((Gamma f)[sigma]⟨id⟩)) as -> by (now asimpl) .\n       eapply context_renaming_lemma; eauto; now asimpl.\n    + econstructor.\n  - constructor. eapply IHty; eauto.\n    + auto_case.\n      * asimpl.\n        specialize (eq1 f).\n        eapply sub_weak1 with (C := A[sigma]) in eq1; eauto.  asimpl in eq1. eapply eq1.\n      * asimpl. econstructor. apply sub_refl.\n    + intros x. asimpl.\n      assert ((Gamma x) [sigma >> ⟨↑⟩] = (Gamma x)[sigma]⟨↑⟩) by (now asimpl).\n      auto_unfold in *. rewrite H.\n      eapply context_renaming_lemma; eauto.\n      * intros. now asimpl.\n      * intros. now asimpl.\n  - eapply T_Tapp with (A0 := subst_ty sigma A) .\n    asimpl in IHty. eapply IHty; eauto.\n    eapply sub_substitution; eauto.\n    now asimpl.\n - econstructor.\n    + eapply IHty; eauto.\n    + eapply sub_substitution; eauto.\nQed.\n\n Lemma ty_inv_abs m n Delta Gamma A A' B C (s: tm m (S n)):\n  TY Delta;Gamma |- abs A s : C   ->   SUB Delta |- C <: arr A' B   ->\n  (SUB Delta |- A' <: A /\\\n    exists B', TY Delta; A .: Gamma |- s : B' /\\ SUB Delta |- B' <: B).\nProof.\n  intros H. depind H; intros.\n  - inv H0. split; eauto.\n  - eauto using sub_trans.\nQed.\n\nLemma ty_subst m n (Gamma: dctx m n) (Delta: ctx n) Delta' s A:\n    (forall x, SUB Delta' |- Delta' x <: Delta x) ->\n  TY Delta; Gamma |- s : A -> TY Delta'; Gamma |- s : A.\nProof.\n  intros eq H. autorevert H. induction H; eauto; intros.\n  - econstructor; eauto. asimpl. eapply IHhas_ty. auto_case; eauto using sub_refl.\n    eapply sub_weak; try reflexivity. apply eq. intros x. now asimpl.\n  - econstructor; eauto.\n    replace A with (A[ids]) by (now asimpl). replace A' with (A'[ids]) by (now asimpl).\n    eapply sub_substitution; eauto. intros x.\n    asimpl. econstructor. eauto.\n  - econstructor; eauto. eapply sub_substitution with (sigma := ids) in H0; eauto.\n    asimpl in H0. eapply H0. intros x. econstructor. asimpl. eapply eq.\nQed.\n\nLemma ty_inv_tabs {m n} {Delta Gamma A A' B C} (s : tm (S m) n):\n  TY Delta;Gamma |- tabs A s : C   ->   SUB Delta |- C <: all A' B   ->\n  (SUB Delta |- A' <: A /\\ exists B',\n   TY (A'.:Delta) >> ren_ty ↑; Gamma >> ren_ty ↑ |- s : B' /\\ SUB (A' .: Delta) >> ren_ty ↑ |- B' <: B).\nProof.\n  intros H. depind H; intros.\n  - inv H0. split; eauto.\n    eexists. split; eauto.\n    eapply ty_subst; eauto. auto_case.\n    apply sub_refl. eapply sub_weak; try reflexivity; eauto.\n  - eauto using sub_trans.\nQed.\n\nTheorem preservation m n Delta Gamma (s: tm m n) t A :\n  TY Delta;Gamma |- s : A -> EV s => t ->\n  TY Delta;Gamma |- t : A.\nProof.\n  intros H_ty H_ev. autorevert H_ev.\n  induction H_ev; intros; eauto using ty.\n  all: try (now (depind H_ty; eauto)).\n  - depind H_ty; [|eauto].\n    + depind H_ty1; subst.\n      * replace B with (B[ids]) by (now asimpl).\n        eapply context_morphism_lemma; eauto.\n        -- intros. asimpl. repeat constructor. apply sub_refl.\n        -- intros [|]; intros; cbn; asimpl; eauto.\n      * pose proof (ty_inv_abs _ _ _ _ _ _ _ _ _ H_ty1 H) as (?&?&?&?).\n        eapply T_Sub; eauto.\n        replace x with (x[var_ty]) by (now asimpl).\n        eapply context_morphism_lemma; eauto.\n        -- intros. asimpl. repeat constructor. apply sub_refl.\n        -- intros [|]; intros; cbn; asimpl; eauto.\n  - depind H_ty; eauto.\n    + depind H_ty.\n      * asimpl in H_ty.\n        eapply context_morphism_lemma; try eapply H_ty; eauto.\n        -- auto_case.\n           ++ asimpl. constructor. apply sub_refl.\n           ++ now asimpl.\n        -- intros x. asimpl. constructor.\n      * pose proof (ty_inv_tabs _ H_ty H) as (?&?&?&?).\n        eapply T_Sub; eauto. asimpl in *.\n        eapply context_morphism_lemma; eauto.\n        -- auto_case; asimpl; eauto. asimpl. constructor. apply sub_refl.\n        -- intros z. unfold funcomp. asimpl. constructor.\n        -- eapply sub_substitution; eauto.\n           auto_case; asimpl.\n           constructor. apply sub_refl.\nQed.\n", "meta": {"author": "addap", "repo": "autosubst-ocaml", "sha": "f820bde3c51299b5f54ef21af39ac4654854d124", "save_path": "github-repos/coq/addap-autosubst-ocaml", "path": "github-repos/coq/addap-autosubst-ocaml/autosubst-ocaml-f820bde3c51299b5f54ef21af39ac4654854d124/case-studies/kathrin/coq-submission/Chapter10/POPLMark1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.28190907223266404}}
{"text": "Require Import Fiat.QueryStructure.Automation.MasterPlan.\n\nDefinition Market := string.\nDefinition StockType := nat.\nDefinition StockCode := nat.\nDefinition Date      := nat.\nDefinition Timestamp := nat.\n\nDefinition TYPE := \"TYPE\".\nDefinition MARKET := \"MARKET\".\nDefinition STOCK_CODE := \"STOCK_CODE\".\nDefinition FULL_NAME := \"FULL_NAME\".\n\nDefinition DATE := \"DATE\".\nDefinition TIME := \"TIME\".\nDefinition PRICE := \"PRICE\".\nDefinition VOLUME := \"VOLUME\".\n\nDefinition STOCKS := \"STOCKS\".\nDefinition TRANSACTIONS := \"TRANSACTIONS\".\n\nDefinition StocksSchema :=\n  Query Structure Schema\n    [ relation STOCKS has\n              schema <STOCK_CODE :: StockCode,\n                      FULL_NAME :: string,\n                      MARKET :: Market,\n                      TYPE :: StockType>\n              where attributes [FULL_NAME; MARKET; TYPE] depend on [STOCK_CODE]; (* uniqueness, really *)\n      relation TRANSACTIONS has\n              schema <STOCK_CODE :: nat,\n                      DATE :: Date,\n                      TIME :: Timestamp,\n                      PRICE :: N,\n                      VOLUME :: N>\n              where attributes [PRICE] depend on [STOCK_CODE; TIME] ]\n    enforcing [attribute STOCK_CODE for TRANSACTIONS references STOCKS].\n\nDefinition StocksSig : ADTSig :=\n  ADTsignature {\n      Constructor \"Init\"               : rep,\n      Method \"AddStock\"           : rep * (StocksSchema#STOCKS)       -> rep * bool,\n      Method \"AddTransaction\"     : rep * (StocksSchema#TRANSACTIONS) -> rep * bool,\n      Method \"TotalVolume\"        : rep * StockCode * Date          -> rep * N,\n      Method \"MaxPrice\"           : rep * StockCode * Date          -> rep * (option N),\n      Method \"TotalActivity\"      : rep * StockCode * Date          -> rep * nat,\n      Method \"LargestTransaction\" : rep * StockType * Date          -> rep * (option N)\n    }.\n\nDefinition StocksSpec : ADT StocksSig :=\n  Def ADT {\n    rep := QueryStructure StocksSchema,\n\n    Def Constructor0 \"Init\" : rep := empty,,\n\n    Def Method1 \"AddStock\" (r : rep) (stock: StocksSchema#STOCKS) : rep * bool :=\n        Insert stock into r!STOCKS,\n\n    Def Method1 \"AddTransaction\" (r : rep) (transaction : StocksSchema#TRANSACTIONS) : rep * bool :=\n        Insert transaction into r!TRANSACTIONS,\n\n    Def Method2 \"TotalVolume\" (r : rep) (code : StockCode) (date : Date) : rep * N :=\n          sum <- SumN (For (transaction in r!TRANSACTIONS)\n                           Where (transaction!STOCK_CODE = code)\n                           Where (transaction!DATE = date)\n                           Return transaction!VOLUME);\n    ret (r, sum),\n\n    Def Method2 \"MaxPrice\" (r : rep) (code : StockCode) (date : Date) : rep * option N :=\n      max <- MaxN (For (transaction in r!TRANSACTIONS)\n                       Where (transaction!STOCK_CODE = code)\n                       Where (transaction!DATE = date)\n                       Return transaction!PRICE);\n     ret (r, max),\n\n    Def Method2 \"TotalActivity\" (r : rep) (code : StockCode) (date : Date) : rep * nat :=\n       count <- Count (For (transaction in r!TRANSACTIONS)\n                           Where (transaction!STOCK_CODE = code)\n                           Where (transaction!DATE = date)\n                           Return ());\n     ret (r, count),\n\n    Def Method2 \"LargestTransaction\" (r : rep) (type : StockType) (date : Date) : rep * option N :=\n        max <- MaxN (For (stock in r!STOCKS) (transaction in r!TRANSACTIONS)\n                         Where (stock!TYPE = type)\n                         Where (transaction!DATE = date)\n                         Where (stock!STOCK_CODE = transaction!STOCK_CODE)\n                         Return (N.mul transaction!PRICE transaction!VOLUME));\n     ret (r, max)\n}%methDefParsing.\n\nLtac drop_constraints_from_insert ::=\n  remove trivial insertion checks; rewrite refine_bind;\n   [ \n   | reflexivity\n   | unfold pointwise_relation; intros * *;\n     set_refine_evar;\n     repeat (first\n       [ drop_symmetric_functional_dependencies\n       | remove_trivial_fundep_insertion_constraints\n       | fundepToQuery; try simplify with monad laws\n       | foreignToQuery; try simplify with monad laws\n       | setoid_rewrite refine_trivial_if_then_else; simplify with monad laws ]); pose_string_hyps;\n     pose_heading_hyps; finish honing ]; pose_string_hyps; pose_heading_hyps; finish honing.\n\n    Ltac finish_planning' PickIndex\n     BuildEarlyIndex BuildLastIndex\n     IndexUse createEarlyTerm createLastTerm\n     IndexUse_dep createEarlyTerm_dep createLastTerm_dep\n     BuildEarlyBag BuildLastBag ::=\n  (* Automatically select indexes + data structure. *)\n\n    PickIndex ltac:(fun attrlist =>\n                      make_simple_indexes attrlist BuildEarlyIndex BuildLastIndex).\n  \n\nDefinition SharpenedStocks :\n  FullySharpened StocksSpec.\nProof.\n\n  master_plan EqIndexTactics.\n  plan\n    EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n    EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep.\n  plan\n    EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n    EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep.\n  Focus 5.\n  Focused_refine_Query.\n  Time implement_In_opt. (* 13.076s *)\n  (* This is the optimized version of the first step of refining queries. It takes 13.076s on my machine. *)\n  Undo 1.\n  Time repeat first \n       [setoid_rewrite (@refine_Filtered_Query_In_Enumerate); try eassumption\n       | setoid_rewrite refine_Filtered_Join_Query_In_Enumerate'; try eassumption\n       | setoid_rewrite (refine_List_Query_In_Where _ _ _); try eassumption; simpl\n       | setoid_rewrite <- filter_and\n       | setoid_rewrite andb_true_r].\n  (* The setoid_rewrite version takes 177.104s but is much simpler. *)\n  (* I haven't patched up the rest. *)\n\n\n  \n  implement_In_opt.\n  setoid_rewrite refine_Filtered_Join_Query_In_Enumerate'.\n  \n  start sharpening ADT.\n  start_honing_QueryStructure'.\n  pose_string_hyps.\n\n  master_plan EqIndexTactics.\n\n  (* Uncomment this to see the mostly sharpened implementation *)\n  (* partial_master_plan EqIndexTactics. *)\n  (*master_plan EqIndexTactics. *)\n\nTime Defined.\n(* 2590MB  *)\n\nTime Definition StocksImpl : ComputationalADT.cADT StocksSig :=\n  Eval simpl in projT1 SharpenedStocks.\n(* 3728MB *)\nPrint StocksImpl.\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/Stocks.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.281909072232664}}
{"text": "\nRequire Export Iron.Language.SystemF2Effect.Step.TypeC.\nRequire Export Iron.Language.SystemF2Effect.Store.LiveE.\nRequire Export Iron.Language.SystemF2Effect.Store.LiveS.\n\n\n(* Evaluation is done when the stack is empty and the expression has\n   been reduced to a value. *)\nDefinition done (fs : stack) (x : exp)\n := fs = nil /\\ (exists v, x = XVal v).\n\n\n(* Add condition, e1 does not mention handles of any deleted regions.\n   Also add this condition to preservation to get region deallocation. *)\nLemma progress\n :   forall se ss sp fs x1 t1 e1\n ,   WfFS   se sp ss fs\n ->  LiveS  ss fs -> LiveE fs e1\n ->  TypeC  nil nil se sp fs x1 t1 e1\n ->  done fs x1\n  \\/ (exists ss' sp' fs' x1', StepF ss sp fs x1 ss' sp' fs' x1').\nProof.\n intros se ss sp fs x1 t1 e1 HW HLS HLE HC.\n gen t1 e1.\n induction x1; intros; eauto.\n\n\n (*********************************************************)\n Case \"XVal\".\n { induction fs.\n   - SCase \"fs = nil\".\n     left.\n     unfold done. rip. exists v. auto.\n\n   - SCase \"fs = cons ...\".\n     right.\n     destruct a as [t x | m1 p2].\n     + SSCase \"FLet\".\n       exists ss. exists sp. exists fs. exists (substVX 0 v x).\n       eauto.\n     + destruct m1 as [p1 | ].\n       * SSCase \"FPriv ext\".\n         exists (map (mergeB p1 p2) ss).\n         exists sp. exists fs. exists (XVal (mergeV p1 p2 v)).\n         eauto.\n\n       * SSCase \"FPriv top\".\n         exists (map (deallocRegion p2) ss). \n         exists sp. exists fs. exists (XVal v).\n         eauto.\n }\n\n\n (*********************************************************)\n Case \"XLet\".\n { right.\n   exists ss. exists sp. exists (fs :> FLet t x1_2). exists x1_1.\n   eauto.\n }\n\n\n (*********************************************************)\n Case \"XApp\".\n { right.\n   exists ss. exists sp. exists fs.\n   inverts_typec.\n   destruct v; nope.\n   SCase \"v1 = XLam\".\n    exists (substVX 0 v0 e). eauto.\n   SCase \"v1 = XConst\".\n    destruct c; nope.\n }\n\n\n (*********************************************************)\n Case \"XAPP\".\n { right.  \n   exists ss. exists sp. exists fs.\n   inverts_typec.\n   destruct v; nope.\n   SCase \"v1 = XLAM\".\n    exists (substTX 0 t e). eauto.\n   SCase \"v1 = XConst\".\n    destruct c; nope.\n }\n\n\n (*********************************************************)\n Case \"XOp1\".\n { right.\n   exists ss. exists sp. exists fs.\n   destruct o.\n   SCase \"OSucc\".\n    inverts_typec.\n    snorm. inverts H8.\n    destruct v; nope.\n    destruct c; nope.\n    eauto.\n  SCase \"OIsZero\".\n    inverts_typec.\n    snorm. inverts H8.\n    destruct v; nope.\n    destruct c; nope.\n    eauto.\n }\n\n\n (*********************************************************)\n Case \"XPrivate\".\n { right.\n   exists ss. \n   exists (SRegion (allocRegion sp) <: sp). \n   exists (fs :> FPriv None (allocRegion sp)).\n   eauto.\n }\n\n\n (*********************************************************)\n Case \"XExtend\".\n { right.\n   inverts HC. inverts_type.\n   have HR: (exists n, t = TRgn n).\n   destruct HR as [p]. subst.\n\n   exists ss.\n   exists (SRegion (allocRegion sp) <: sp).\n   exists (fs :> FPriv (Some p) (allocRegion sp)).\n   eauto.\n }\n\n (*********************************************************)\n Case \"XAlloc\".\n { right. \n   inverts_typec. \n   have HR: (exists n, t = TRgn n).\n   destruct HR as [n].\n   exists (StValue n v <: ss).\n   exists sp.\n   exists fs.\n   exists (XVal (VLoc (length ss))).\n   subst. auto.\n }\n\n\n (*********************************************************)\n Case \"XRead\".\n { right.\n   inverts HC. inverts_type.\n   have HR: (exists n, t = TRgn n).\n   destruct HR as [n]. subst.\n\n   assert (exists l, v = VLoc l) as HL.\n    destruct v; burn.\n    destruct c; nope.\n   dest l. subst.\n\n   inverts_type. inverts HW. \n   exists ss. exists sp. exists fs.\n   rip.\n\n   (* There is a binding in the store corresponding\n      to the entry in the store environment. *)\n   have (exists b, get l ss = Some b).\n    dest b.\n\n   unfold StoreT in *.\n\n   destruct b.\n   (* Store binding contains a value. *)\n   - have HB: (TypeB nil nil se sp (StValue n0 v) (TRef (TRgn n) t0))\n      by (eapply Forall2_get_get_same; eauto).\n     inverts HB.\n     exists (XVal v).\n     eauto.\n    \n   (* Store binding is dead, \n      can't happen due to binding liveness constraints LiveE/LiveE *)\n   - have HB: (TypeB nil nil se sp (StDead n0)    (TRef (TRgn n) t0))\n      by (eapply Forall2_get_get_same; eauto).\n     inverts HB.\n\n     remember (TRgn n) as p. \n\n     have (SubsT nil sp e1 (TRead p) KEffect)\n      by  (eapply EqSym in H; eauto).\n\n     have (LiveE fs (TRead p)).\n\n     lets D: liveS_liveE_value ss fs (TRead p) l (StDead n).\n     spec D n. rip. subst p. snorm. rip.\n     have (Some n = Some n). rip.\n     have (n = n). rip. nope.\n }\n\n\n (*********************************************************)\n Case \"XWrite\".\n { right.\n   inverts_typec. inverts HW. rip.\n\n   have HR: (exists n, t = TRgn n).\n    destruct HR as [n]. subst.\n\n   destruct v; burn.\n\n   (* Write to a location. *)\n   - inverts_type. \n\n     exists (update n0 (StValue n v0) ss).\n     exists sp. exists fs. exists (XVal (VConst CUnit)).\n\n     have (exists b, get n0 ss = Some b). \n      dest b.\n\n     destruct b.\n     (* Original binding contains a live value that can be overwritten. *)\n     + have HB: (TypeB nil nil se sp (StValue n1 v) (TRef (TRgn n) t2))\n        by (eapply Forall2_get_get_same; eauto).\n       inverts HB.\n       eauto.\n   \n     (* Original binding is dead,\n        can't happen due to binding liveness constraints. *)\n     + have HB: (TypeB nil nil se sp (StDead n1)    (TRef (TRgn n) t2))\n        by (eapply Forall2_get_get_same; eauto).\n       inverts HB.\n\n       remember (TRgn n) as p.\n\n       have (SubsT nil sp e1 (TWrite p) KEffect)\n         by  (eapply EqSym in H; eauto).\n\n       have (LiveE fs (TWrite p)).\n\n       lets D: liveS_liveE_value ss fs (TWrite p) n0 (StDead n).\n       spec D n. rip. subst p. snorm. \n       have (Some n = Some n). rip.\n       have (n = n). rip. nope.\n\n   (* Write to a constant, can't happen. *)\n   - destruct c; nope.\n }\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/Progress.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819874558604, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.28185735478646345}}
{"text": "Require Import HoareDef OpenDef Open STB.\nRequire Import Add0 Repeat0 Add1 Repeat1 Add01proof Repeat01proof.\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 ProofMode Invariant.\n\nRequire Import Imp.\nRequire Import ImpNotations.\nRequire Import ImpProofs.\n\nSet Implicit Arguments.\n\nLocal Open Scope nat_scope.\n\nSection PROOF.\n  Let Σ: GRA.t := GRA.of_list [].\n  Local Existing Instance Σ.\n\n  Let FunStb: Sk.t -> gname -> option fspec :=\n    fun sk => to_stb [(\"succ\", succ_spec)].\n\n  Let GlobalStb: Sk.t -> gname -> option fspec :=\n    fun sk => to_closed_stb (KMod.get_stb [Add1.KAdd; Repeat1.KRepeat FunStb] sk).\n\n  Let FunStb_incl: forall sk,\n      stb_incl (FunStb sk) (GlobalStb sk).\n  Proof. i. etrans; [|eapply to_closed_stb_weaker]. stb_incl_tac. Qed.\n\n  Let GlobalStb_repeat: forall sk,\n      fn_has_spec (GlobalStb sk) \"repeat\" (Repeat1.repeat_spec FunStb sk).\n  Proof. ii. econs; ss. refl. Qed.\n\n  Let FunStb_succ: forall sk,\n      fn_has_spec (FunStb sk) \"succ\" (Add1.succ_spec).\n  Proof. ii. econs; ss. refl. Qed.\n\n  Let prog_tgt := [Add0.Add; Repeat0.Repeat].\n  Let prog_src := KMod.transl_src_list [Add1.KAdd; Repeat1.KRepeat FunStb].\n\n  Theorem correct: refines2 prog_tgt prog_src.\n  Proof.\n    etrans; cycle 1.\n    { eapply adequacy_open. i. exists ε. splits; ss. g_wf_tac. }\n    eapply refines2_cons.\n    { eapply Add01proof.correct; et. }\n    { eapply Repeat01proof.correct; et. unfold to_closed_stb. ii. des_ifs. }\n  Qed.\nEnd PROOF.\n", "meta": {"author": "alxest", "repo": "CCR", "sha": "edcda8faae6580581e8e5b28050d755bcb29f55f", "save_path": "github-repos/coq/alxest-CCR", "path": "github-repos/coq/alxest-CCR/CCR-edcda8faae6580581e8e5b28050d755bcb29f55f/examples/repeat/RepeatAll.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819874558604, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.28185735478646345}}
{"text": "(** This file implements normalization for separation lgoic formulas.\n ** The normal form is:\n **   (a /\\ b /\\ c) /\\ (P * Q * R [* true]?)\n ** The final [* true] is optional and is likely to never occur in\n ** practice but is necessary to make the algorithm total.\n **\n ** In this format, all of [a], [b], and [c] are pure which means that\n ** the above equation is equivalent to:\n **  Inj a * Inj b * Inj c * P * Q * R [* true]?\n ** where [Inj p = p /\\ emp]\n **)\nRequire Import Coq.Classes.Morphisms.\nRequire Import ExtLib.Data.Positive.\nRequire Import ExtLib.Data.HList.\nRequire Import ExtLib.Tactics.\nRequire Import BILogic ILogic Pure.\nRequire Import MirrorCore.EnvI.\nRequire Import MirrorCore.SymI.\nRequire Import MirrorCore.ExprI.\nRequire Import MirrorCore.TypesI.\nRequire Import MirrorCore.ExprSem.\nRequire Import MirrorCore.Lambda.Expr.\nRequire Import MirrorCore.Lambda.AppN.\nRequire Import MirrorCore.Lambda.TypedFoldApp.\nRequire Import MirrorCharge.Iterated.\nRequire Import MirrorCharge.ILogicFunc MirrorCharge.SepLogFoldEx.\nRequire Import MirrorCharge.SynSepLog.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\n(** TODO: These should really be moved to Charge! **)\nSection lemmas.\n  Variable P : Type.\n  Variable ILogicOps_P : ILogicOps P.\n  Variable ILogic_P : ILogic P.\n  Variable BILOperators_P : BILOperators P.\n  Variable BILogic_P : BILogic P.\n  Variable PureOp_P : @PureOp P.\n  Variable Pure_P : Pure PureOp_P.\n\n  Lemma ltrue_sep : pure ltrue -> ltrue ** ltrue -|- ltrue.\n  Proof.\n    constructor.\n    { apply ltrueR. }\n    { rewrite <- pureandsc by eauto with typeclass_instances.\n      apply landR; reflexivity. }\n  Qed.\n\n  Lemma pure_star_and_true\n  : forall a b,\n      Pure.pure a ->\n      a ** b -|- a //\\\\ b ** ltrue.\n  Proof.\n    intros.\n    rewrite <- (landtrueR a) at 1.\n    rewrite pureandscD by eauto with typeclass_instances.\n    rewrite sepSPC. reflexivity.\n  Qed.\n\n  Lemma lequiv_sep_cancel : forall a b c,\n                              a -|- b -> a ** c -|- b ** c.\n  Proof.\n    split; apply bilsep; eapply H.\n  Qed.\n\n  Lemma land_cancel : forall a b c, b -|- c -> a //\\\\ b -|- a //\\\\ c.\n  Proof.\n    intros. rewrite H. reflexivity.\n  Qed.\nEnd lemmas.\n\nSection conjunctives.\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 Expr_expr : Expr _ (expr typ sym) := Expr_expr.\n  Local Existing Instance Expr_expr.\n\n  Record conjunctives : Type :=\n  { exs : list typ\n  ; spatial : list (expr typ sym * list (expr typ sym))\n  ; star_true : bool\n  ; pure : list (expr typ sym)\n  }.\n\n  Definition mkEmpty : option conjunctives :=\n    Some\n  {| exs := nil\n   ; spatial := nil\n   ; star_true := false\n   ; pure := nil\n   |}.\n\n  Definition mkPure e : option conjunctives :=\n    Some\n  {| exs := nil\n   ; spatial := nil\n   ; star_true := true\n   ; pure := e :: nil\n   |}.\n\n  Definition mkSpatial e es : option conjunctives :=\n    Some\n  {| exs := nil\n   ; spatial := (e,es) :: nil\n   ; star_true := false\n   ; pure := nil\n   |}.\n\n  Require Import MirrorCore.Lambda.ExprLift.\n\n  Definition mkStar (l r : conjunctives) : option conjunctives :=\n    let ll := length l.(exs) in\n    let lr := length r.(exs) in\n    Some\n    {| exs := l.(exs) ++ r.(exs)\n     ; spatial := l.(spatial) ++ map (fun e_es =>\n                                        let '(e,es) := e_es in\n                                        (lift 0 ll e,\n                                         map (lift 0 ll) es)) r.(spatial)\n     ; star_true := orb l.(star_true) r.(star_true)\n     ; pure := l.(pure) ++ map (lift 0 ll) r.(pure)\n     |}.\n\n  Definition mkEx (t : typ) (l : conjunctives) : option conjunctives :=\n    Some\n  {| exs := l.(exs) ++ t :: nil\n   ; spatial := l.(spatial)\n   ; star_true := l.(star_true)\n   ; pure := l.(pure)\n   |}.\n\n  Definition mkAnd (l r : conjunctives) : option conjunctives :=\n    let ll := length l.(exs) in\n    let lr := length r.(exs) in\n    match l.(spatial) with\n      | nil =>\n        Some\n          {| exs := l.(exs) ++ r.(exs)\n           ; spatial := map (fun e_es =>\n                               let '(e,es) := e_es in\n                               (lift 0 ll e,\n                                map (lift 0 ll) es)) r.(spatial)\n           ; star_true := r.(star_true)\n           ; pure := l.(pure) ++ map (lift 0 ll) r.(pure)\n          |}\n      | _ => match r.(spatial) with\n               | nil =>\n                 Some\n                   {| exs := l.(exs) ++ r.(exs)\n                    ; spatial := l.(spatial)\n                    ; star_true := l.(star_true)\n                    ; pure := l.(pure) ++ map (lift 0 ll) r.(pure)\n                   |}\n               | _ => None\n             end\n    end.\n\n  Variable as_ex : expr typ sym -> option typ.\n\n  Definition SepLogArgs_normalize : SepLogArgs typ sym (option conjunctives) :=\n  {| do_emp := mkEmpty\n   ; do_star := fun l r =>\n                  match l , r with\n                    | Some l , Some r => mkStar l r\n                    | _ , _ => None\n                  end\n   ; do_and := fun l r =>\n                 match l , r with\n                    | Some l , Some r => mkAnd l r\n                    | _ , _ => None\n                  end\n   ; do_other := fun f xs => mkSpatial f (List.map fst xs)\n   ; do_ex := fun t e => match e with\n                           | Some e => mkEx t e\n                           | None => None\n                         end\n   ; do_pure := mkPure\n   |}.\n\n  Variable SL : typ.\n\n  Section conjunctivesD.\n    Variable ILO : ILogicOps (typD SL).\n    Variable BILO : BILOperators (typD SL).\n    Variable IL : @ILogic _ ILO.\n    Variable BIL : @BILogic _ ILO BILO.\n\n    Definition well_formed (PO : PureOp)\n               (c : conjunctives) (us vs : env) : Prop :=\n      List.Forall (fun e =>\n                     exists val, exprD us vs e SL  = Some val\n                              /\\ @Pure.pure _ PO val) c.(pure).\n\n    Variable SSL : SynSepLog typ sym.\n    Variable SSLO : @SynSepLogOk typ _ _ sym _ SL _ _ SSL.\n\n    Definition conjunctives_to_expr (c : conjunctives) : expr typ sym :=\n      let spa := iterated_base SSL.(e_emp) SSL.(e_star) (map (fun x => apps (fst x) (snd x)) c.(spatial)) in\n      let pur := iterated_base SSL.(e_true) SSL.(e_and) c.(pure) in\n      SSL.(e_and) pur (SSL.(e_star) spa (if c.(star_true) then SSL.(e_true) else SSL.(e_emp))).\n\n    Definition conjunctives_to_expr_star (c : conjunctives) : expr typ sym :=\n      let spa := iterated_base SSL.(e_emp) SSL.(e_star) (map (fun x => apps (fst x) (snd x)) c.(spatial)) in\n      let pur := iterated_base SSL.(e_emp) SSL.(e_star) (map (SSL.(e_and) SSL.(e_emp)) c.(pure)) in\n      SSL.(e_star) pur (SSL.(e_star) spa (if c.(star_true) then SSL.(e_true) else SSL.(e_emp))).\n\n    Section with_pure.\n\n    Variable PureOp_it : @PureOp (typD SL).\n    Variable Pure_it : @Pure _ _ _ PureOp_it.\n    Hypothesis pure_ltrue : Pure.pure ltrue.\n    Hypothesis pure_land : forall p q, Pure.pure p -> Pure.pure q -> Pure.pure (land p q).\n\n    Lemma iterated_base_true_and_pure\n    : forall us vs ps x1,\n        exprD us vs (iterated_base (e_true SSL) (e_and SSL) ps) SL = Some x1 ->\n        List.Forall\n          (fun e : expr typ sym =>\n             exists val : typD SL,\n               exprD us vs e SL = Some val /\\ Pure.pure val) ps -> Pure.pure x1.\n    Proof.\n(*\n      intros.\n      generalize dependent x1.\n      induction H0; simpl.\n      { unfold iterated_base. simpl. intros.\n        destruct (exprD_e_trueOk SSLO us vs) as [ ? [ ? ? ] ].\n        go_crazy SSL SSLO.\n        inv_all; subst.\n        eapply pure_proper; eauto. }\n      { intros.\n        generalize (@iterated_base_cons _ SSL.(e_true) SSL.(e_and)\n                      (Sem_equiv _ SL lequiv us vs)\n                      (@Reflexive_Sem_equiv _ _ _ _ SL lequiv _ us vs)\n                      (@Transitive_Sem_equiv _ _ _ _ SL lequiv _ us vs)\n                      (@Sem_equiv_e_and_assoc _ _ _ SL _ _ _ SSL SSLO us vs)\n                      (@Sem_equiv_Proper_e_and _ _ _ SL _ _ _ _ SSLO us vs)\n                      (@Sem_equiv_e_true_e_and_unitLL _ _ _ SL _ _ _ _ SSLO us vs)\n                      (@Sem_equiv_e_true_e_and_unitLR _ _ _ SL _ _ _ _ SSLO us vs)\n                      (@Sem_equiv_e_true_e_and_unitRL _ _ _ SL _ _ _ _ SSLO us vs)\n                      (@Sem_equiv_e_true_e_and_unitRR _ _ _ SL _ _ _ _ SSLO us vs)\n                      x l).\n        unfold Sem_equiv. rewrite H1.\n        intros; forward.\n        repeat go_crazy SSL SSLO.\n        destruct H as [ ? [ ? ? ] ].\n        inv_all; subst.\n        specialize (IHForall _ eq_refl).\n        eapply pure_proper. rewrite H5 in H3. apply H3.\n        eapply pure_land; eauto. }\n    Qed.\n*)\n    Admitted.\n\n(*\n    Lemma iterated_base_true_and_star_emp'\n    : forall tus tvs ps,\n        match\n            exprD' tus tvs (iterated_base SSL.(e_true) SSL.(e_and) ps) SL\n          , exprD' tus tvs (iterated_base SSL.(e_emp) SSL.(e_star) (map (SSL.(e_and) SSL.(e_emp)) ps)) SL\n        with\n          | Some x , Some x' =>\n            forall Q us vs,\n              List.Forall\n                (fun e : expr sym =>\n                   exists val : typD nil SL,\n                        exprD (join_env us) (join_env vs) e SL = Some val\n                     /\\ Pure.pure val)\n                ps ->\n              (x us vs //\\\\ Q -|- x' us vs ** Q)\n          | None , None => True\n          | _ , _ => False\n        end.\n    Proof.\n      induction ps; simpl; intros.\n      { unfold iterated_base in *; simpl in *.\n        destruct (SSLO.(e_empOk) tus tvs) as [ ? [ ? ? ] ].\n        destruct (e_trueOk SSLO tus tvs) as [ ? [ ? ? ] ].\n        Cases.rewrite_all_goal; intros.\n        rewrite H0. rewrite H2.\n        rewrite empSPL. rewrite ltrue_unitL; eauto. }\n      { (*\ngeneralize (@iterated_base_cons _ SSL.(e_true) SSL.(e_and)\n                      (Sem_equiv' _ SL lequiv us vs)\n                      (@Reflexive_Sem_equiv' _ _ _ SL lequiv _ us tvs)\n                      (@Transitive_Sem_equiv' _ _ _ SL lequiv _ us tvs)\n                      (@Sem_equiv'_e_and_assoc _ _ _ SL _ _ _ SSL SSLO us tvs)\n                      (@Sem_equiv'_Proper_e_and _ _ _ SL _ _ _ _ SSLO us tvs)\n                      (@Sem_equiv'_e_true_e_and_unitLL _ _ _ SL _ _ _ _ SSLO us tvs)\n                      (@Sem_equiv'_e_true_e_and_unitLR _ _ _ SL _ _ _ _ SSLO us tvs)\n                      (@Sem_equiv'_e_true_e_and_unitRL _ _ _ SL _ _ _ _ SSLO us tvs)\n                      (@Sem_equiv'_e_true_e_and_unitRR _ _ _ SL _ _ _ _ SSLO us tvs)\n                   a ps).\n        generalize (@iterated_base_cons _ SSL.(e_emp) SSL.(e_star)\n                      (Sem_equiv _ SL lequiv us vs)\n                      (@Reflexive_Sem_equiv _ _ _ SL lequiv _ us vs)\n                      (@Transitive_Sem_equiv _ _ _ SL lequiv _ us vs)\n                      (@Sem_equiv_e_star_assoc _ _ _ SL _ _ _ _ SSL SSLO us vs)\n                      (@Sem_equiv_Proper_e_star _ _ _ SL _ _ _ _ _ SSLO us vs)\n                      (@Sem_equiv_e_emp_e_star_unitLL _ _ _ SL _ _ _ _ _ SSLO us vs)\n                      (@Sem_equiv_e_emp_e_star_unitLR _ _ _ SL _ _ _ _ _ SSLO us vs)\n                      (@Sem_equiv_e_emp_e_star_unitRL _ _ _ SL _ _ _ _ _ SSLO us vs)\n                      (@Sem_equiv_e_emp_e_star_unitRR _ _ _ SL _ _ _ _ _ SSLO us vs)\n                   (e_and SSL (e_emp SSL) a) (map (e_and SSL (e_emp SSL)) ps)).\n        unfold Sem_equiv.\n        intros.\n        repeat match goal with\n                 | |- match ?X with _ => _ end =>\n                   consider X; intros\n               end; forward; repeat go_crazy SSL SSLO.\n        { inv_all; subst.\n          rewrite H5; clear H5.\n          rewrite H4; clear H4.\n          rewrite H9; clear H9.\n          rewrite H7; clear H7.\n          rewrite H11; clear H11.\n          inversion H3; subst.\n          specialize (IHps Q H7).\n          destruct (exprD_e_empOk SSLO us vs) as [ ? [ ? ? ] ].\n          rewrite H1 in *. inv_all; subst.\n          rewrite H4.\n          destruct H5. rewrite H10 in *. destruct H2.\n          inv_all; subst.\n          rewrite (landC empSP).\n          rewrite sepSPA.\n          rewrite pureandscD by eauto with typeclass_instances.\n          rewrite empSPL.\n          rewrite landA. rewrite IHps. reflexivity. \n        { destruct (exprD_e_empOk SSLO us vs) as [ ? [ ? ? ] ].\n          congruence. } }\n*) admit. }\n    Qed.\n\n    Lemma iterated_base_true_and_star_emp\n    : forall us vs ps,\n        match\n            exprD us vs (iterated_base SSL.(e_true) SSL.(e_and) ps) SL\n          , exprD us vs (iterated_base SSL.(e_emp) SSL.(e_star) (map (SSL.(e_and) SSL.(e_emp)) ps)) SL\n        with\n          | Some x , Some x' =>\n            forall Q,\n              List.Forall\n                (fun e : expr sym =>\n                   exists val : typD ts nil SL, exprD us vs e SL = Some val /\\ Pure.pure val)\n                ps ->\n              x //\\\\ Q -|- x' ** Q\n          | None , None => True\n          | _ , _ => False\n        end.\n    Proof.\n      induction ps; simpl; intros.\n      { unfold iterated_base in *; simpl in *.\n        destruct (exprD_e_empOk SSLO us vs) as [ ? [ ? ? ] ].\n        destruct (exprD_e_trueOk SSLO us vs) as [ ? [ ? ? ] ].\n        Cases.rewrite_all_goal; intros.\n        rewrite H0. rewrite H2.\n        rewrite empSPL. rewrite ltrue_unitL; eauto. }\n      { generalize (@iterated_base_cons _ SSL.(e_true) SSL.(e_and)\n                      (Sem_equiv _ SL lequiv us vs)\n                      (@Reflexive_Sem_equiv _ _ _ _ SL lequiv _ us vs)\n                      (@Transitive_Sem_equiv _ _ _ _ SL lequiv _ us vs)\n                      (@Sem_equiv_e_and_assoc _ _ _ SL _ _ _ SSL SSLO us vs)\n                      (@Sem_equiv_Proper_e_and _ _ _ SL _ _ _ _ SSLO us vs)\n                      (@Sem_equiv_e_true_e_and_unitLL _ _ _ SL _ _ _ _ SSLO us vs)\n                      (@Sem_equiv_e_true_e_and_unitLR _ _ _ SL _ _ _ _ SSLO us vs)\n                      (@Sem_equiv_e_true_e_and_unitRL _ _ _ SL _ _ _ _ SSLO us vs)\n                      (@Sem_equiv_e_true_e_and_unitRR _ _ _ SL _ _ _ _ SSLO us vs)\n                   a ps).\n        generalize (@iterated_base_cons _ SSL.(e_emp) SSL.(e_star)\n                      (Sem_equiv _ SL lequiv us vs)\n                      (@Reflexive_Sem_equiv _ _ _ _ SL lequiv _ us vs)\n                      (@Transitive_Sem_equiv _ _ _ _ SL lequiv _ us vs)\n                      (@Sem_equiv_e_star_assoc _ _ _ SL _ _ _ _ SSL SSLO us vs)\n                      (@Sem_equiv_Proper_e_star _ _ _ SL _ _ _ _ _ SSLO us vs)\n                      (@Sem_equiv_e_emp_e_star_unitLL _ _ _ SL _ _ _ _ _ SSLO us vs)\n                      (@Sem_equiv_e_emp_e_star_unitLR _ _ _ SL _ _ _ _ _ SSLO us vs)\n                      (@Sem_equiv_e_emp_e_star_unitRL _ _ _ SL _ _ _ _ _ SSLO us vs)\n                      (@Sem_equiv_e_emp_e_star_unitRR _ _ _ SL _ _ _ _ _ SSLO us vs)\n                   (e_and SSL (e_emp SSL) a) (map (e_and SSL (e_emp SSL)) ps)).\n        unfold Sem_equiv.\n        intros.\n        repeat match goal with\n                 | |- match ?X with _ => _ end =>\n                   consider X; intros\n               end; forward; repeat go_crazy SSL SSLO.\n        { inv_all; subst.\n          rewrite H5; clear H5.\n          rewrite H4; clear H4.\n          rewrite H9; clear H9.\n          rewrite H7; clear H7.\n          rewrite H11; clear H11.\n          inversion H3; subst.\n          specialize (IHps Q H7).\n          destruct (exprD_e_empOk SSLO us vs) as [ ? [ ? ? ] ].\n          rewrite H1 in *. inv_all; subst.\n          rewrite H4.\n          destruct H5. rewrite H10 in *. destruct H2.\n          inv_all; subst.\n          rewrite (landC empSP).\n          rewrite sepSPA.\n          rewrite pureandscD by eauto with typeclass_instances.\n          rewrite empSPL.\n          rewrite landA. rewrite IHps. reflexivity. }\n        { destruct (exprD_e_empOk SSLO us vs) as [ ? [ ? ? ] ].\n          congruence. } }\n    Qed.\n*)\n\n(*\n    Lemma iterated_base_true_and_star_emp\n    : forall us vs ps x,\n        exprD us vs (iterated_base SSL.(e_true) SSL.(e_and) ps) SL = Some x ->\n        exists x',\n          exprD us vs (iterated_base SSL.(e_emp) SSL.(e_star) (map (SSL.(e_and) SSL.(e_emp)) ps)) SL = Some x' /\\\n          forall Q,\n            List.Forall\n              (fun e : expr sym =>\n                 exists val : typD ts nil SL, exprD us vs e SL = Some val /\\ Pure.pure val)\n              ps ->\n            x //\\\\ Q -|- x' ** Q.\n    Proof.\n      \n      induction ps; simpl; intros.\n      { unfold iterated_base in *; simpl in *.\n        destruct (exprD_e_empOk SSLO us vs) as [ ? [ ? ? ] ].\n        destruct (exprD_e_trueOk SSLO us vs) as [ ? [ ? ? ] ].\n        eexists; split; eauto. intros.\n        rewrite H1. rewrite H in *. inv_all; subst.\n        rewrite H3. rewrite empSPL. rewrite ltrue_unitL; eauto. }\n      { generalize (@iterated_base_cons _ SSL.(e_true) SSL.(e_and)\n                      (Sem_equiv _ SL lequiv us vs)\n                      (@Reflexive_Sem_equiv _ _ _ SL lequiv _ us vs)\n                      (@Transitive_Sem_equiv _ _ _ SL lequiv _ us vs)\n                      (@Sem_equiv_e_and_assoc _ _ _ SL _ _ _ SSL SSLO us vs)\n                      (@Sem_equiv_Proper_e_and _ _ _ SL _ _ _ _ SSLO us vs)\n                      (@Sem_equiv_e_true_e_and_unitLL _ _ _ SL _ _ _ _ SSLO us vs)\n                      (@Sem_equiv_e_true_e_and_unitLR _ _ _ SL _ _ _ _ SSLO us vs)\n                      (@Sem_equiv_e_true_e_and_unitRL _ _ _ SL _ _ _ _ SSLO us vs)\n                      (@Sem_equiv_e_true_e_and_unitRR _ _ _ SL _ _ _ _ SSLO us vs)\n                   a ps).\n        generalize (@iterated_base_cons _ SSL.(e_emp) SSL.(e_star)\n                      (Sem_equiv _ SL lequiv us vs)\n                      (@Reflexive_Sem_equiv _ _ _ SL lequiv _ us vs)\n                      (@Transitive_Sem_equiv _ _ _ SL lequiv _ us vs)\n                      (@Sem_equiv_e_star_assoc _ _ _ SL _ _ _ _ SSL SSLO us vs)\n                      (@Sem_equiv_Proper_e_star _ _ _ SL _ _ _ _ _ SSLO us vs)\n                      (@Sem_equiv_e_emp_e_star_unitLL _ _ _ SL _ _ _ _ _ SSLO us vs)\n                      (@Sem_equiv_e_emp_e_star_unitLR _ _ _ SL _ _ _ _ _ SSLO us vs)\n                      (@Sem_equiv_e_emp_e_star_unitRL _ _ _ SL _ _ _ _ _ SSLO us vs)\n                      (@Sem_equiv_e_emp_e_star_unitRR _ _ _ SL _ _ _ _ _ SSLO us vs)\n                   (e_and SSL (e_emp SSL) a) (map (e_and SSL (e_emp SSL)) ps)).\n        unfold Sem_equiv.\n        rewrite H. intros; forward.\n        go_crazy SSL SSLO.\n        generalize (iterated_base_true_and_pure _ _ H3); intro.\n        eapply IHps in H3; clear IHps H.\n        destruct H3 as [ ? [ ? ? ] ].\n        consider (exprD us vs\n               (e_star SSL (e_and SSL (e_emp SSL) a)\n                  (iterated_base (e_emp SSL) (e_star SSL)\n                     (map (e_and SSL (e_emp SSL)) ps))) SL).\n        { intros.\n          forward. eexists; split; eauto.\n          intros. specialize (H3 Q).\n          inversion H8. subst.\n          destruct (exprD_e_empOk SSLO us vs) as [ ? [ ? ? ] ].\n          repeat go_crazy SSL SSLO.\n          inv_all; subst.\n          specialize (H5 H12).\n          destruct H11 as [ ? [ ? ? ] ]; inv_all; subst.\n          specialize (H3 H12); clear H6 H12.\n          subst.\n          rewrite H2. rewrite H4. rewrite H7. rewrite H14. rewrite H16. rewrite H10.\n          rewrite (landC empSP).\n          rewrite sepSPA.\n          rewrite pureandscD by eauto with typeclass_instances.\n          rewrite empSPL.\n          rewrite landA. rewrite H3. reflexivity. }\n        { intros. forward.\n          exfalso. repeat go_crazy SSL SSLO.\n          destruct (exprD_e_empOk SSLO us vs) as [ ? [ ? ? ] ].\n          congruence. } }\n    Qed.\n\n    Theorem conjunctives_to_expr_conjunctives_to_expr_star\n    : forall tvs us c cE,\n        exprD' us tvs (conjunctives_to_expr c) SL = Some cE ->\n        exists cE',\n          exprD' us tvs (conjunctives_to_expr_star c) SL = Some cE' /\\\n          forall (vs : hlist (typD ts nil) tvs),\n            well_formed _ c us (join_env vs) ->\n            cE vs -|- cE' vs.\n    Proof.\n      intros.\n      consider (exprD' us tvs (conjunctives_to_expr_star c) SL); intros.\n      { eexists; split; eauto; intros.\n        destruct c.\n        unfold well_formed, conjunctives_to_expr, conjunctives_to_expr_star in *.\n        simpl in *.\n        generalize dependent (e_star SSL\n               (iterated_base (e_emp SSL) (e_star SSL)\n                  (map\n                     (fun x : expr sym * list (expr sym) =>\n                      apps (fst x) (snd x)) spatial0))\n               (if star_true0 then e_true SSL else e_emp SSL)).\n        intros.\n        repeat go_crazy SSL SSLO.\n        generalize (@iterated_base_true_and_star_emp us (join_env vs) pure0).\n        unfold exprD. rewrite split_env_join_env.\n        rewrite H.\n        intro. specialize (H6 _ eq_refl).\n        destruct H6. destruct H6.\n        forward. inv_all; subst.\n        rewrite H3; clear H3.\n        rewrite H5; clear H5.\n        eapply H7; eauto.\n        clear - H1.\n        unfold exprD in H1.\n        rewrite split_env_join_env in H1. assumption. }\n      { exfalso.\n        destruct c.\n        unfold well_formed, conjunctives_to_expr, conjunctives_to_expr_star in *.\n        simpl in *.\n        generalize dependent (e_star SSL\n               (iterated_base (e_emp SSL) (e_star SSL)\n                  (map\n                     (fun x : expr sym * list (expr sym) =>\n                      apps (fst x) (snd x)) spatial0))\n               (if star_true0 then e_true SSL else e_emp SSL)).\n        intros.\n        repeat go_crazy SSL SSLO.\n        clear H2.\n        generalize dependent x.\n        generalize dependent pure0.\n        induction pure0; intros.\n        { unfold iterated_base in *. simpl in *.\n          destruct (SSLO.(e_empOk) us tvs) as [ ? [ ? ? ] ].\n          congruence. }\n        { unfold iterated_base in *.\n          simpl in *.\n          consider ( iterated (e_and SSL) pure0); intros.\n          { consider (iterated (e_star SSL) (map (e_and SSL (e_emp SSL)) pure0)); intros.\n            { repeat go_crazy SSL SSLO.\n              destruct (SSLO.(e_empOk) us tvs) as [ ? [ ? ? ] ].\n              congruence.\n              eapply IHpure0; reflexivity. }\n            { repeat go_crazy SSL SSLO.\n              destruct (SSLO.(e_empOk) us tvs) as [ ? [ ? ? ] ].\n              congruence. } }\n          { consider (iterated (e_star SSL) (map (e_and SSL (e_emp SSL)) pure0)); intros.\n            { repeat go_crazy SSL SSLO.\n              destruct (SSLO.(e_empOk) us tvs) as [ ? [ ? ? ] ].\n              congruence.\n              destruct (SSLO.(e_trueOk) us tvs) as [ ? [ ? ? ] ].\n              eapply H4; eauto. }\n            { repeat go_crazy SSL SSLO.\n              destruct (SSLO.(e_empOk) us tvs) as [ ? [ ? ? ] ].\n              congruence. } } } }\n    Qed.\n*)\n\n    Theorem conjunctives_to_expr_conjunctives_to_expr_star_iff\n    : forall tvs tus c,\n        match\n            exprD' tus tvs SL (conjunctives_to_expr c)\n          , exprD' tus tvs SL (conjunctives_to_expr_star c)\n        with\n          | Some cE , Some cE' =>\n            forall us (vs : hlist typD tvs),\n            well_formed _ c (join_env us) (join_env vs) ->\n            cE us vs -|- cE' us vs\n          | None , None => True\n          | _ , _ => False\n        end.\n    Proof.\n(*\n      intros.\n      unfold conjunctives_to_expr, conjunctives_to_expr_star.\n      generalize (e_star SSL\n                 (iterated_base (e_emp SSL) (e_star SSL)\n                    (map\n                       (fun x : expr sym * list (expr sym) =>\n                        apps (fst x) (snd x)) (spatial c)))\n                 (if star_true c then e_true SSL else e_emp SSL)); intros.\n(*\n      consider (exprD' us tvs (conjunctives_to_expr_star c) SL); intros; forward.\n      { consider (exprD' us tvs (conjunctives_to_expr c) SL); intros.\n        { admit. }\n        { unfold conjunctives_to_expr, conjunctives_to_expr_star in *.\n          generalize dependent ((e_star SSL\n              (iterated_base (e_emp SSL) (e_star SSL)\n                 (map\n                    (fun x : expr sym * list (expr sym) =>\n                     apps (fst x) (snd x)) (spatial c)))\n              (if star_true c then e_true SSL else e_emp SSL))).\n          intros.\n          repeat go_crazy SSL SSLO.\n          destruct c; simpl in *.\n          clear - H H0.\n          generalize dependent x.\n      \n      { eexists; split; eauto; intros.\n        destruct c.\n        unfold well_formed, conjunctives_to_expr, conjunctives_to_expr_star in *.\n        simpl in *.\n        generalize dependent (e_star SSL\n               (iterated_base (e_emp SSL) (e_star SSL)\n                  (map\n                     (fun x : expr sym * list (expr sym) =>\n                      apps (fst x) (snd x)) spatial0))\n               (if star_true0 then e_true SSL else e_emp SSL)).\n        intros.\n        repeat go_crazy SSL SSLO.\n        generalize (@iterated_base_true_and_star_emp us (join_env vs) pure0).\n        unfold exprD. rewrite split_env_join_env.\n        rewrite H.\n        intro. specialize (H6 _ eq_refl).\n        destruct H6. destruct H6.\n        forward. inv_all; subst.\n        rewrite H3; clear H3.\n        rewrite H5; clear H5.\n        eapply H7; eauto.\n        clear - H1.\n        unfold exprD in H1.\n        rewrite split_env_join_env in H1. assumption. }\n      { exfalso.\n        destruct c.\n        unfold well_formed, conjunctives_to_expr, conjunctives_to_expr_star in *.\n        simpl in *.\n        generalize dependent (e_star SSL\n               (iterated_base (e_emp SSL) (e_star SSL)\n                  (map\n                     (fun x : expr sym * list (expr sym) =>\n                      apps (fst x) (snd x)) spatial0))\n               (if star_true0 then e_true SSL else e_emp SSL)).\n        intros.\n        repeat go_crazy SSL SSLO.\n        clear H2.\n        generalize dependent x.\n        generalize dependent pure0.\n        induction pure0; intros.\n        { unfold iterated_base in *. simpl in *.\n          destruct (SSLO.(e_empOk) us tvs) as [ ? [ ? ? ] ].\n          congruence. }\n        { unfold iterated_base in *.\n          simpl in *.\n          consider ( iterated (e_and SSL) pure0); intros.\n          { consider (iterated (e_star SSL) (map (e_and SSL (e_emp SSL)) pure0)); intros.\n            { repeat go_crazy SSL SSLO.\n              destruct (SSLO.(e_empOk) us tvs) as [ ? [ ? ? ] ].\n              congruence.\n              eapply IHpure0; reflexivity. }\n            { repeat go_crazy SSL SSLO.\n              destruct (SSLO.(e_empOk) us tvs) as [ ? [ ? ? ] ].\n              congruence. } }\n          { consider (iterated (e_star SSL) (map (e_and SSL (e_emp SSL)) pure0)); intros.\n            { repeat go_crazy SSL SSLO.\n              destruct (SSLO.(e_empOk) us tvs) as [ ? [ ? ? ] ].\n              congruence.\n              destruct (SSLO.(e_trueOk) us tvs) as [ ? [ ? ? ] ].\n              eapply H4; eauto. }\n            { repeat go_crazy SSL SSLO.\n              destruct (SSLO.(e_empOk) us tvs) as [ ? [ ? ? ] ].\n              congruence. } } } }\n*)\n*)\n    Admitted.\n\n(*\n    Definition conjunctives_to_expr (c : conjunctives) : expr sym :=\n      let ps := iterated e_and c.(pure) in\n      let sp := iterated e_star (map (fun x => apps (fst x) (snd x)) c.(spatial)) in\n      match ps , sp with\n        | None , None => if c.(star_true) then e_true else e_emp\n        | None , Some sp => if c.(star_true) then e_star sp e_true else sp\n        | Some p , None => if c.(star_true) then p else e_and p e_emp\n        | Some p , Some sp =>\n          e_and p (if c.(star_true) then\n                     e_star sp e_true\n                   else\n                     sp)\n      end.\n*)\n\n(*\n    Definition R_conjunctives\n               (e : expr typ sym) (c : conjunctives) (tus tvs : tenv typ) : Prop :=\n      forall val,\n        exprD' (ts := ts) tus tvs e SL = Some val ->\n        exists val',\n             exprD' tus tvs (conjunctives_to_expr c) SL = Some val'\n          /\\ (forall us vs,\n                (val us vs -|- val' us vs) /\\ well_formed _ c (join_env us) (join_env vs)).\n\n    Ltac forward_ex_and :=\n      repeat match goal with\n               | H : exists x, _ |- _ => destruct H\n               | H : _ /\\ _ |- _ => destruct H\n             end.\n\n    Local Instance Reflexive_lentails : Reflexive lentails.\n    Proof.\n      destruct IL. destruct lentailsPre. auto.\n    Qed.\n\n    Lemma something_smart\n    : forall a b c d,\n        Pure.pure a -> Pure.pure b ->\n        (a //\\\\ b) //\\\\ c ** d -|- (a //\\\\ c) ** b //\\\\ d.\n    Proof.\n      clear - BIL IL Pure_it. intros.\n      symmetry.\n      rewrite pureandscD by eauto with typeclass_instances.\n      rewrite sepSPC.\n      rewrite pureandscD by eauto with typeclass_instances.\n      rewrite <- landA.\n      rewrite sepSPC. reflexivity.\n    Qed.\n\n    Lemma well_formed_pure\n    : forall x us vs,\n        well_formed _ x us vs ->\n        forall x7,\n          exprD us vs (iterated_base SSL.(e_true) SSL.(e_and) (pure x)) SL = Some x7 ->\n          Pure.pure x7.\n    Proof.\n      unfold well_formed. destruct x; simpl.\n      induction 1; simpl; intros.\n(*\n      { unfold iterated_base in H. simpl in *.\n        destruct (SSLO.(e_trueOk) us tvs).\n        rewrite H in *. destruct H0.\n        inv_all; subst. eapply Pure.pure_proper. eapply H1.\n        eapply pure_ltrue; eauto with typeclass_instances. }\n      { unfold iterated_base in *. simpl in *.\n        destruct (iterated SSL.(e_and) l); intros.\n        { go_crazy SSL SSLO.\n          eapply Pure.pure_proper. eapply H3.\n          destruct H. destruct H.\n          eapply pure_land; eauto with typeclass_instances.\n          unfold exprD in *. rewrite split_env_join_env in *.\n          rewrite H1 in *. inv_all. rewrite H. auto. }\n        { destruct H. destruct H.\n          unfold exprD in H. rewrite split_env_join_env in *.\n          rewrite H1 in *. inv_all; subst.\n          auto. } }\n    Qed. *)\n    Admitted.\n\n    Lemma Forall_app\n    : forall T (P : T -> Prop) xs ys,\n        List.Forall P (xs ++ ys) <-> (List.Forall P xs /\\ List.Forall P ys).\n    Proof.\n      clear. induction xs; simpl; intros.\n      { intuition. }\n      { split; intros.\n        { inversion H; subst. rewrite IHxs in H3. intuition. }\n        { intuition. inversion H0; subst. constructor; eauto. eapply IHxs. auto. } }\n    Qed.\n\n    Lemma something_smart'\n    : forall a b c d e f g,\n        Pure.pure a -> Pure.pure b ->\n        e -|- f ** g ->\n        (a //\\\\ b) //\\\\ (c ** d) ** e -|-\n                   (a //\\\\ c ** f) ** b //\\\\ d ** g.\n    Proof.\n      clear - BIL pure_land pure_ltrue. intros. rewrite H1. clear H1.\n      transitivity ((a //\\\\ b) //\\\\ (c ** f) ** d ** g).\n      { apply land_cancel; eauto with typeclass_instances.\n        repeat rewrite sepSPA.\n        rewrite (sepSPC c).\n        rewrite (sepSPC c).\n        apply lequiv_sep_cancel; eauto with typeclass_instances.\n        repeat rewrite <- sepSPA.\n        rewrite (sepSPC d f). reflexivity. }\n      { rewrite something_smart by eauto. reflexivity. }\n    Qed.\n\n    Lemma cte_mkStar\n    : forall tus tvs r_res l_res rval lval,\n        exprD' tus tvs (conjunctives_to_expr r_res) SL = Some rval ->\n        exprD' tus tvs (conjunctives_to_expr l_res) SL = Some lval ->\n        exists val,\n          exprD' tus tvs (conjunctives_to_expr (mkStar l_res r_res)) SL = Some val /\\\n          forall us vs,\n            well_formed _ l_res (join_env us) (join_env vs) ->\n            well_formed _ r_res (join_env us) (join_env vs) ->\n            (val us vs -|- lval us vs ** rval us vs) /\\\n            well_formed _ (mkStar l_res r_res) (join_env us) (join_env vs).\n    Proof.\n(*\n      intros.\n      consider (exprD' us tvs (conjunctives_to_expr (mkStar l_res r_res)) SL);\n        intros; unfold conjunctives_to_expr, mkStar in *; simpl in *.\n      { eexists; split; eauto. intros.\n        split.\n        { destruct (SSLO.(e_empOk) us tvs).\n          destruct (SSLO.(e_trueOk) us tvs).\n          rewrite map_app in *.\n          forward_ex_and.\n          generalize (@iterated_base_app _ SSL.(e_true) SSL.(e_and)\n                        (Sem_equiv _ SL lequiv us (join_env vs))\n                 (@Reflexive_Sem_equiv _ _ _ SL lequiv _ us (join_env vs))\n                 (@Transitive_Sem_equiv _ _ _ SL lequiv _ us (join_env vs))\n                 (Sem_equiv_e_and_assoc _ SSLO) Sem_equiv_Proper_e_and\n                 Sem_equiv_e_true_e_and_unitLL\n                 Sem_equiv_e_true_e_and_unitLR\n                 Sem_equiv_e_true_e_and_unitRL\n                 Sem_equiv_e_true_e_and_unitRR r_res.(pure) l_res.(pure) us tvs).\n          generalize (@iterated_base_app _ e_emp e_star (Sem_equiv _ SL lequiv)\n                (@Reflexive_Sem_equiv _ _ _ SL lequiv _)\n                (@Transitive_Sem_equiv _ _ _ SL lequiv _)\n                Sem_equiv_e_star_assoc Sem_equiv_Proper_e_star\n                Sem_equiv_e_emp_e_star_unitLL\n                Sem_equiv_e_emp_e_star_unitLR\n                Sem_equiv_e_emp_e_star_unitRL\n                Sem_equiv_e_emp_e_star_unitRR\n                (map (fun x : expr sym * list (expr sym) => apps (fst x) (snd x)) r_res.(spatial))\n                (map (fun x : expr sym * list (expr sym) => apps (fst x) (snd x)) l_res.(spatial))\n                us tvs).\n          repeat go_crazy.\n          intros; forward.\n          inv_all; subst.\n          repeat match goal with\n                   | H : forall x, _ -|- _ |- _ => rewrite H\n                 end.\n          assert (Pure.pure (x8 vs)).\n          { eapply well_formed_pure; [ | eauto ]; eauto. }\n          assert (Pure.pure (x9 vs)).\n          { eapply well_formed_pure; [ | eauto ]; eauto. }\n          destruct l_res.(star_true); destruct r_res.(star_true);\n          intros; simpl in *; repeat go_crazy; inv_all; subst;\n          repeat match goal with\n                   | H : forall x, _ -|- _ |- _ => rewrite H\n                 end; eapply something_smart'; auto.\n          { rewrite ltrue_sep. reflexivity. }\n          { rewrite empSPR. reflexivity. }\n          { rewrite empSPL. reflexivity. }\n          { rewrite empSPL. reflexivity. } }\n        { red. simpl.\n          apply Forall_app. split; assumption. } }\n      { exfalso.\n        generalize (@iterated_base_app _ e_true e_and (Sem_equiv _ SL lequiv)\n                                     (@Reflexive_Sem_equiv _ _ _ SL lequiv _)\n                                     (@Transitive_Sem_equiv _ _ _ SL lequiv _)\n                                     Sem_equiv_e_and_assoc Sem_equiv_Proper_e_and\n                 Sem_equiv_e_true_e_and_unitLL\n                 Sem_equiv_e_true_e_and_unitLR\n                 Sem_equiv_e_true_e_and_unitRL\n                 Sem_equiv_e_true_e_and_unitRR r_res.(pure) l_res.(pure) us tvs).\n        generalize (@iterated_base_app _ e_emp e_star (Sem_equiv _ SL lequiv)\n           (@Reflexive_Sem_equiv _ _ _ SL lequiv _)\n           (@Transitive_Sem_equiv _ _ _ SL lequiv _)\n           Sem_equiv_e_star_assoc Sem_equiv_Proper_e_star\n           Sem_equiv_e_emp_e_star_unitLL\n           Sem_equiv_e_emp_e_star_unitLR\n           Sem_equiv_e_emp_e_star_unitRL\n           Sem_equiv_e_emp_e_star_unitRR\n           (map (fun x : expr sym * list (expr sym) => apps (fst x) (snd x)) r_res.(spatial))\n           (map (fun x : expr sym * list (expr sym) => apps (fst x) (snd x)) l_res.(spatial))\n           us tvs).\n        rewrite map_app in *.\n        repeat go_crazy.\n        inv_all; subst. intros; forward.\n        destruct l_res.(star_true); destruct r_res.(star_true); simpl in *;\n        repeat go_crazy; congruence. }\n    Qed.\n*) Admitted.\n*)\n    End with_pure.\n(*\n    Variable SLS : SepLogSpec sym.\n    Variable slsok : SepLogSpecOk RSym_sym SL SLS ILO BILO.\n\n(*\n    Theorem SepLogArgsOk_conjunctives\n    : SepLogArgsOk RSym_sym SL SepLogArgs_normalize SLS R_conjunctives.\n    Proof.\n      constructor; unfold R_conjunctives; simpl; intros.\n      { unfold mkSpatial, conjunctives_to_expr. simpl.\n        unfold iterated_base. simpl.\n        consider (exprD' (join_env us) tvs (SSL.(e_and) SSL.(e_true) (SSL.(e_star) (apps e (map fst es)) SSL.(e_emp))) SL); intros;\n        repeat (go_crazy SSL SSLO); inv_all; subst.\n        { eexists; split; eauto.\n          intros.\n          destruct (SSLO.(e_empOk) (join_env us) tvs).\n          destruct (SSLO.(e_trueOk) (join_env us) tvs).\n          forward_ex_and.\n          repeat (go_crazy SSL SSLO).\n          inv_all; subst.\n          repeat match goal with\n                   | H : forall x, _ -|- _ |- _ =>\n                     rewrite H\n                 end.\n          rewrite empSPR; eauto with typeclass_instances.\n          rewrite landtrueL. split.\n          reflexivity. constructor. }\n        { destruct (SSLO.(e_trueOk) (join_env us) tvs) as [ ? [ ? ? ] ]. congruence. }\n        { destruct (SSLO.(e_empOk) (join_env us) tvs) as [ ? [ ? ? ] ]. congruence. } }\n      { unfold conjunctives_to_expr, mkPure; simpl.\n        unfold iterated_base. simpl.\n        destruct (SSLO.(e_empOk) (join_env us) tvs).\n        destruct (SSLO.(e_trueOk) (join_env us) tvs).\n        forward_ex_and.\n        consider (exprD' (join_env us) tvs (SSL.(e_and) e (SSL.(e_star) SSL.(e_emp) SSL.(e_true))) SL);\n          intros; do 5 (go_crazy SSL SSLO); try congruence.\n        { eexists; split; eauto.\n          intros. inv_all; subst.\n          rewrite H8. rewrite H10. rewrite H4. rewrite H5.\n          rewrite empSPL. rewrite landtrueR. split.\n          { reflexivity. }\n          { red. constructor. 2: constructor.\n            unfold exprD. rewrite split_env_join_env. rewrite H1.\n            eexists; split; eauto.\n            eapply His_pure. eassumption.\n            instantiate (1 := join_env vs).\n            instantiate (1 := join_env us).\n            unfold exprD. rewrite split_env_join_env. rewrite H1. reflexivity. } } }\n      { unfold conjunctives_to_expr, mkEmpty; simpl.\n        destruct (SSLO.(e_empOk) (join_env us) tvs).\n        destruct (SSLO.(e_trueOk) (join_env us) tvs).\n        forward_ex_and. unfold iterated_base. simpl.\n        consider (exprD' (join_env us) tvs (SSL.(e_and) SSL.(e_true) (SSL.(e_star) SSL.(e_emp) SSL.(e_emp))) SL); \n          intros; repeat (go_crazy SSL SSLO); try congruence.\n        { eexists; split; eauto.\n          inv_all; subst. intros.\n          split; try solve [ constructor ].\n          eapply His_emp  with (us := join_env us) (vs := join_env vs) in H0; eauto.\n          unfold exprD in *. rewrite split_env_join_env in *.\n          rewrite H1 in *. inv_all; subst. rewrite H0.\n          rewrite H8. rewrite H10. rewrite H4. rewrite H5.\n          rewrite empSPL. rewrite landtrueL. reflexivity. } }\n      { red_exprD.\n        generalize (slsok.(His_star) _ H2 (join_env us)).\n        rewrite H in *.\n        unfold type_of_apply in *.\n        forward.\n        inv_all. subst t. subst t4. subst p. subst val.\n        red_exprD. rewrite H in H8.\n        forward. inv_all.\n        subst p t2.\n        specialize (H3 _ _ H8).\n        subst t0 t1.\n        specialize (H4 _ _ H9).\n        forward_ex_and.\n        specialize (@cte_mkStar (join_env us) tvs _ _ _ _ H4 H3); intros.\n        forward_ex_and.\n        eexists; split; eauto.\n        intros.\n        uip_all'.\n        specialize (H7 (join_env vs)).\n        unfold exprD in *.\n        rewrite split_env_join_env in *.\n        rewrite H5 in *. inv_all; subst.\n        rewrite H7.\n        specialize (H10 vs). specialize (H11 vs).\n        forward_ex_and.\n        specialize (H13 _ H16 H14).\n        forward_ex_and. split; auto.\n        symmetry. rewrite H11. rewrite H10. auto. }\n    Qed.\n*)\n*)\n  End conjunctivesD.\n\n  Definition normalize (sls : SepLogSpec typ sym) (e : expr typ sym) : option conjunctives :=\n    StrongFoldApp.wf_app_fold_args (AppFullFoldArgs_SepLogArgs SepLogArgs_normalize sls) e tt.\n\n(*\n  Theorem normalizeOk\n          (ILO : ILogicOps (typD nil SL))\n          (BILO : BILOperators (typD nil SL))\n          (IL : @ILogic _ ILO)\n          (BIL : @BILogic _ ILO BILO)\n          (sls : SepLogSpec _ sym) (slsOk : SepLogSpecOk _ _ _ sls _ _)\n          (ssl : SynSepLog _ sym) (sslo : SynSepLogOk _ _ _ _ _ ssl)\n  : forall (e : expr typ sym) tus tvs,\n      match exprD' nil tus tvs SL e\n          , exprD' nil tus tvs SL (conjunctives_to_expr ssl (normalize sls nil tus tvs e))\n      with\n        | Some l , Some r =>\n          forall us vs,\n            (l us vs -|- r us vs) /\\\n            well_formed (slsOk.(_PureOp)) (normalize sls e tus tvs) (join_env us) (join_env vs)\n        | None , None => True\n        | _ , _ => False\n      end.\n  Proof.\n  Admitted.\n*)\nEnd conjunctives.\n\n(*\nModule demo.\n  Definition is_emp (i : ilfunc) : bool :=\n    match i with\n      | ilf_true _ => true\n      | _ => false\n    end.\n  Definition is_star (e : ilfunc) : bool :=\n    match e with\n      | fref 1%positive => true\n      | _ => false\n    end.\n\n  Definition SepLogSpec_demo : SepLogSpec ilfunc :=\n    Build_SepLogSpec (fun _ => false) is_emp is_star.\n\n  Definition inj_emp := Inj (ilf_true (tyType 1)).\n  Definition inj_star a b :=\n    Eval compute in apps (Inj (fref 1%positive)) (a :: b :: nil).\n  Definition inj_and a b :=\n    Eval compute in apps (Inj (fref 2%positive)) (a :: b :: nil).\n\n  Definition test := fun x => normalize SepLogSpec_demo x nil nil.\n  Eval compute in  test inj_emp.\n  Eval compute in  test (inj_star inj_emp inj_emp).\n  Eval compute in  test (inj_star (Var 0) (inj_star inj_emp (inj_and (Var 1) (Var 3)))).\nEnd demo.\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/BILNormalizeEx.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.28185734825767783}}
{"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.\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(*\n(*Error: Universe inconsistency.*)\nAdmitted.\n*)\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 : term-equality\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(*\n(*Error: Universe inconsistency.*)\nAdmitted.\n*)\n\nLemma equality_nuprli {p} :\n  forall lib (A B C : @CTerm p) i eq,\n    equality lib A B (mkc_uni i)\n    -> nuprli lib i A C eq\n    -> nuprli lib i A B eq.\nProof.\n  introv e n.\n  unfold equality, nuprl in e; exrepnd.\n  inversion e1; try not_univ.\n  duniv j h.\n  allrw @univi_exists_iff; exrepnd.\n  computes_to_value_isvalue; GC.\n  discover; exrepnd.\n  allfold (@nuprli p lib j0).\n  generalize (nuprli_uniquely_valued lib j0 j0 A A eqa eq); intro k.\n  repeat (autodimp k hyp).\n  apply nuprli_refl in h2; auto.\n  apply nuprli_refl in n; auto.\n  apply (nuprli_ext lib j0 A B eqa eq); auto.\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 : term-equality\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(*\n(*Error: Universe inconsistency.*)\nAdmitted.\n*)\n\nLemma mkc_uni_in_nuprl {p} :\n  forall lib (i : nat),\n    nuprl lib (mkc_uni i)\n          (mkc_uni i)\n          (fun A A' => {eqa : per(p) , close lib (univi lib i) A A' eqa}).\nProof.\n  introv.\n  apply CL_init.\n  exists (S i); simpl.\n  left; sp; spcast; apply computes_to_valc_refl; sp.\nQed.\n\nLemma nuprl_mkc_uni {p} :\n  forall lib (i : nat),\n    {eq : per(p) , nuprl lib (mkc_uni i) (mkc_uni i) eq}.\nProof.\n  intros.\n  exists (fun A A' => {eqa : per(p) , close lib (univi lib i) A A' eqa}).\n  apply mkc_uni_in_nuprl.\nQed.\n\nLemma tequality_mkc_uni {p} :\n  forall lib (i : nat), @tequality p lib (mkc_uni i) (mkc_uni i).\nProof.\n  generalize (@nuprl_mkc_uni p); sp.\nQed.\n(*\n(*Error: Universe inconsistency.*)\nAdmitted.\n*)\n\nLemma mkc_cequiv_equality_in_uni {p} :\n  forall lib (a b c d : @CTerm p) i,\n    equality lib (mkc_cequiv a b) (mkc_cequiv c d) (mkc_uni i)\n    <=>\n    (ccequivc lib a b <=> ccequivc lib c d).\nProof.\n  sp; sp_iff Case; intro e.\n\n  - Case \"->\".\n    unfold equality in e; exrepnd.\n    allunfold @nuprl.\n    inversion e1; try not_univ.\n    duniv j h.\n    allrw @univi_exists_iff; exrepnd.\n    computes_to_value_isvalue; GC.\n    rw h0 in e0; exrepnd.\n    inversion e2; try not_univ.\n\n  - Case \"<-\".\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;\n    spcast; try computes_to_value_refl.\n    exists (fun t t' : @CTerm p => t ===>(lib) mkc_axiom\n                      # t' ===>(lib) mkc_axiom\n                      # ccequivc lib a b).\n    apply CL_cequiv; unfold per_cequiv.\n    exists a b c d; sp; spcast; try computes_to_value_refl.\nQed.\n(*\n(*Error: Universe inconsistency.*)\nAdmitted.\n*)\n\nLemma mkc_approx_equality_in_uni {p} :\n  forall lib (a b c d : @CTerm p) i,\n    equality lib (mkc_approx a b) (mkc_approx c d) (mkc_uni i)\n    <=>\n    (capproxc lib a b <=> capproxc lib c d).\nProof.\n  sp; sp_iff Case; intro e.\n\n  - Case \"->\".\n    unfold equality in e; exrepnd.\n    unfold nuprl in e1.\n    inversion e1; try not_univ.\n    duniv j h.\n    allrw @univi_exists_iff; exrepnd.\n    computes_to_value_isvalue; GC.\n    rw h0 in e0; exrepnd.\n    inversion e2; try not_univ.\n\n  - Case \"<-\".\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;\n    spcast; try computes_to_value_refl.\n    exists (fun t t' : @CTerm p => t ===>(lib) mkc_axiom\n                      # t' ===>(lib) mkc_axiom\n                      # capproxc lib a b).\n    apply CL_approx; unfold per_approx.\n    exists a b c d; sp; spcast; try computes_to_value_refl.\nQed.\n(*\n(*Error: Universe inconsistency.*)\nAdmitted.\n*)\n\n(*\nLemma tequality_in_uni_iff_tequality {p} :\n  forall (T1 T2 : @CTerm p) i,\n    tequality lib (mkc_member T1 (mkc_uni i))\n              (mkc_member T2 (mkc_uni i))\n    <=> equorsq T1 T2 (mkc_uni i).\nProof.\n  introv.\n  allrw <- @fold_mkc_member.\n  rw @tequality_mkc_equality.\n  split; intro k; repnd; try (complete sp).\n\n  dands; try (complete sp).\n  apply tequality_mkc_uni.\n  split; intro e.\n  generalize (cequorsq_equality_trans2 T1 T1 T2 (mkc_uni i)); intro e1.\n  repeat (dest_imp e1 hyp).\n  apply equality_sym in e1.\n  apply equality_refl in e1; sp.\n  generalize (cequorsq_equality_trans1 T1 T2 T2 (mkc_uni i)); intro e1.\n  repeat (dest_imp e1 hyp).\n  apply equality_refl in e1; sp.\nQed.\n*)\n\nLemma equality_in_uni_mkc_halts {p} :\n  forall lib i (a b : @CTerm p),\n    equality lib (mkc_halts a) (mkc_halts b) (mkc_uni i)\n    <=>\n    (chaltsc lib a <=> chaltsc lib b).\nProof.\n  intros; repeat (rewrite <- fold_mkc_halts).\n  rw @mkc_approx_equality_in_uni.\n  allrw @chasvaluec_as_capproxc; sp.\nQed.\n\nLemma cequorsq_mkc_halts_implies {p} :\n  forall lib i (a b : @CTerm p),\n    equorsq lib (mkc_halts a) (mkc_halts b) (mkc_uni i)\n    -> (chaltsc lib a <=> chaltsc lib b).\nProof.\n  unfold equorsq; intros; sp;\n  allrw @equality_in_uni_mkc_halts; sp.\n  uncast; allrw @cequivc_decomp_halts; sp;\n  split; sp; spcast; discover; sp.\nQed.\n\nLemma cequorsq_mkc_halts {p} :\n  forall lib i (a b : @CTerm p),\n    equorsq lib (mkc_halts a) (mkc_halts b) (mkc_uni i)\n    <=>\n    (chaltsc lib a <=> chaltsc lib b).\nProof.\n  unfold equorsq; intros; split; sp; try right;\n  allrw @equality_in_uni_mkc_halts; sp; uncast;\n  allrw @cequivc_decomp_halts; try split; sp; spcast;\n  discover; sp.\nAbort.\n(* This is not true in Prop with Cast around hasvalue *)\n(*Qed.*)\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/per_props_more.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2818573417288922}}
{"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 ast.\n\n(* ************************************************************ *)\n(* ************************************************************ *)\n(*                                                              *)\n(*                          semantics                           *)\n(*                                                              *)\n(* ************************************************************ *)\n(* ************************************************************ *)\n\n(*\n * We define the semantics in terms of an abstract machine, which\n * includes the evaluation state as well as the program.\n *\n * A machine has a heap and a list of threads.\n * A thread is a lits of stack frames.\n * A stack frame is a local store plus a statement to execute.\n *\n * Statements are executed destructively.\n *)\n\n(**************************************************************)\n(* stores *)\n\nSection Stores.\n\nInductive LockState: Set :=\n| LockHeld: LockState (* XXX: keep track of who holds it? *)\n| LockAvailable: LockState\n.\n\n(* old form that used coq types directly\nInductive val: Type := mkval (t: Type) (a : t): val.\n\nDefinition Heap := NatMap.t val.\nDefinition Locals := NatMap.t val.\n*)\n\nInductive Heap :=\n| mkheap (memory: NatMap.t value)\n         (lockenv: NatMap.t LockState)\n         (disks: NatMap.t (NatMap.t value)):\n       Heap\n.\n\nDefinition Locals := NatMap.t value.\n\nDefinition get_locals (rho : Locals) (v : var) : option value :=\n  match v with\n  | mkvar t n => NatMap.find n rho\n  end.\nDefinition set_locals (v : var) (val : value) (rho : Locals) : Locals :=\n  match v with\n  | mkvar t n => NatMap.add n val rho\n  end.\n\nDefinition heap_get_data (whichheap: WhichHeap) (index: nat) (h: Heap):\n                                option value :=\n   match h with\n   | mkheap memory _ disks =>\n        match whichheap with\n        | MemoryHeap => NatMap.find index memory\n        | DiskHeap disknum =>\n             match NatMap.find disknum disks with\n             | Some disk => NatMap.find index disk\n             (* XXX we should have something that prevents getting here *)\n             | None => None\n             end\n        end\n   end.\n\nDefinition heap_set_data (whichheap: WhichHeap) (index: nat)\n                         (val: value) (h: Heap): Heap :=\n   match h with\n   | mkheap memory lockenv disks =>\n        match whichheap with\n        | MemoryHeap =>\n             mkheap (NatMap.add index val memory) lockenv disks\n        | DiskHeap disknum =>\n             match NatMap.find disknum disks with\n             | Some disk =>\n                  let disk' := (NatMap.add index val disk) in\n                  mkheap memory lockenv (NatMap.add disknum disk' disks)\n             | None => mkheap memory lockenv disks\n             end\n        end\n   end.\n\nDefinition get_heap (rho : Heap) (a : addr) : option value :=\n  match a with\n  | mkaddr t n which => heap_get_data which n rho\n  end.\n  (*\n  match rho with\n  | mkheap mem lk disks =>\n    match a with\n    | mkaddr t n which =>\n      match which with\n      | MemoryHeap => NatMap.find n mem\n      | DiskHeap d =>\n        match NatMap.find d disks with\n        | None => None\n        | Some disk => NatMap.find n disk\n        end\n      end\n    end\n  end.*)\n\nDefinition set_heap (a : addr) (val : value) (rho : Heap) : Heap :=\n  match a with\n  | mkaddr t n which => heap_set_data which n val rho\n  end.\n  (*\n  match rho with\n  | mkheap mem lk disks =>\n    match a with\n    | mkaddr t n which =>\n      match which with\n      | MemoryHeap => mkheap (NatMap.add n val mem) lk disks\n      | DiskHeap d =>\n        match NatMap.find d disks with\n        (* XXX write errors for missing disks? *)\n        | None => rho\n        | Some disk => mkheap mem lk (NatMap.add d (NatMap.add n val disk) disks)\n        end\n      end\n    end\n  end.*)\n\nDefinition heap_get_lockstate (index: nat) (h: Heap): option LockState :=\n   match h with\n   | mkheap _ lockenv _ => NatMap.find index lockenv\n   end.\n\nDefinition heap_set_lockstate (index: nat) (val: LockState) (h: Heap): Heap :=\n   match h with\n   | mkheap memory lockenv disks =>\n        mkheap memory (NatMap.add index val lockenv) disks\n   end.\n\nEnd Stores.\n\n(**************************************************************)\n(* expressions *)\n\nSection Expressions.\n\nInductive ExprYields: forall t, Locals -> expr -> value -> Prop :=\n| value_yields: forall loc t a,\n    ExprYields t loc (e_value t a) a\n(* XXX THERE'S NOTHING HERE FOR GETLOCKADDR *)\n| read_yields: forall loc t (x : var) id a,\n    (* XXX tidy this *)\n    type_of_value a = t ->\n    x = mkvar t id -> NatMap.find id loc = Some a ->\n    ExprYields t loc (e_read x) a\n| cond_true_yields: forall t loc e et ef a,\n    ExprYields t_bool loc e v_true ->\n    ExprYields t loc et a ->\n    ExprYields t loc (e_cond t e et ef) a\n| cond_false_yields: forall t loc e et ef a,\n    ExprYields t_bool loc e v_false ->\n    ExprYields t loc ef a ->\n    ExprYields t loc (e_cond t e et ef) a\n| natbinop_yields: forall loc e1 e2 f n1 n2,\n    ExprYields t_nat loc e1 (v_nat n1) ->\n    ExprYields t_nat loc e2 (v_nat n2) ->\n    ExprYields t_nat loc (e_natbinop f e1 e2) (v_nat (f n1 n2))\n.\n\nEnd Expressions.\n\n(**************************************************************)\n(* statements *)\n\nSection Statements.\n\n(* call, return, and start appear at higher levels *)\nInductive StmtSteps: Heap -> Locals -> stmt ->\n                     Heap -> Locals -> stmt -> Prop :=\n| step_in_seq: forall h loc s1 s2 h' loc' s1',\n     StmtSteps h loc s1 h' loc' s1' ->\n     StmtSteps h loc (s_seq s1 s2) h' loc' (s_seq s1' s2)\n| step_next: forall h loc s2,\n     StmtSteps h loc (s_seq s_skip s2) h loc s2\n| step_assign: forall h loc id type e a,\n     ExprYields type loc e a ->\n     StmtSteps h loc (s_assign (mkvar type id) e)\n               h (NatMap.add id a loc) s_skip\n| step_load: forall h loc t lid e heapaddr whichheap a,\n     ExprYields (t_addr t) loc e (v_addr (mkaddr t heapaddr whichheap)) ->\n     heap_get_data whichheap heapaddr h = Some a ->\n     StmtSteps h loc (s_load (mkvar t lid) e)\n               h (NatMap.add lid a loc) s_skip\n| step_store: forall h loc lid hid whichheap e t'a a,\n     ExprYields t'a loc e a ->\n     ExprYields (t_addr t'a) loc (e_read (mkvar (t_addr t'a) lid))\n                                 (v_addr (mkaddr t'a hid whichheap)) ->\n     StmtSteps h loc (s_store (mkvar (t_addr t'a) lid) e)\n               (heap_set_data whichheap hid a h) loc s_skip\n| step_if_true: forall h loc e st sf,\n     ExprYields t_bool loc e v_true ->\n     StmtSteps h loc (s_if e st sf) h loc st\n| step_if_false: forall h loc e st sf,\n     ExprYields t_bool loc e v_false ->\n     StmtSteps h loc (s_if e st sf) h loc sf\n| step_while_true: forall h loc e body,\n     ExprYields t_bool loc e v_true ->\n     StmtSteps h loc (s_while e body)\n               h loc (s_seq body (s_while e body))\n| step_while_false: forall h loc e body,\n     ExprYields t_bool loc e v_false ->\n     StmtSteps h loc (s_while e body) h loc s_skip\n| step_getlock: forall h loc t id heapaddr,\n     NatMap.find id loc = Some (v_lock (mkaddr t heapaddr MemoryHeap)) ->\n     heap_get_lockstate heapaddr h = Some LockAvailable ->\n     StmtSteps h loc (s_getlock (mkvar (t_lock t) id))\n               (heap_set_lockstate heapaddr LockHeld h) loc (s_skip)\n| step_putlock: forall h loc t id heapaddr,\n     NatMap.find id loc = Some (v_lock (mkaddr t heapaddr MemoryHeap)) ->\n     (* XXX shouldn't we require that we hold the lock? *)\n     (* (XXX: maybe we can't; see notes elsewhere *)\n     heap_get_lockstate heapaddr h = Some LockHeld ->\n     StmtSteps h loc (s_putlock (mkvar (t_lock t) id))\n               (heap_set_lockstate heapaddr LockAvailable h) loc (s_skip)\n.\n\nEnd Statements.\n\n(**************************************************************)\n(* vardecls *)\n\nSection Vardecls.\n\nInductive VardeclsSteps: Locals -> list vardecl -> Locals -> Prop :=\n| vardecls_steps_nil: forall loc,\n     VardeclsSteps loc [] loc\n| vardecls_steps_cons: forall loc t id e a decls loc',\n     ExprYields t loc e a ->\n     VardeclsSteps (NatMap.add id a loc) decls loc' ->\n     VardeclsSteps loc ((mkvardecl (mkvar t id) e) :: decls) loc'\n.\n\nEnd Vardecls.\n\n(**************************************************************)\n(* stacks *)\n\nSection Stacks.\n\nInductive Stack: Type :=\n| stack_empty: Stack\n| stack_frame: Locals -> Stack -> stmt -> Stack\n.\n\nInductive StackSteps: Heap -> Stack ->\n                      Heap -> Stack -> Prop :=\n\n| stack_steps_stmt: forall h loc stk s h' loc' s',\n     StmtSteps h loc s\n               h' loc' s' ->\n     StackSteps h (stack_frame loc stk s)\n                h' (stack_frame loc' stk s')\n\n| stack_steps_call_final: forall h loc stk x proc arg,\n     (* gross but avoids duplicating the call frame logic *)\n     StackSteps h (stack_frame loc stk (s_call x proc arg))\n                h (stack_frame loc stk (s_seq (s_call x proc arg) s_skip))\n\n| stack_steps_call_seq: forall\n                            h loc stk s s2\n                            rt retid pt paramid decls body arg argval\n                            s' new'loc,\n     (* restrict the form of the call statement *)\n     s = (s_seq (s_call (mkvar rt retid)\n                    (mkproc rt (mkvar pt paramid) decls body)\n                    arg)\n                 s2) ->\n     (* the new statement for the outer frame *)\n     s' = s_seq (s_assign (mkvar rt retid) (e_value rt v_undef)) s2 ->\n\n     (* evaluate the arg in the outer frame *)\n     ExprYields pt loc arg argval ->\n\n     (* create the locals for the new inner frame *)\n     VardeclsSteps (NatMap.add paramid argval (NatMap.empty value))\n                   decls\n                   new'loc ->\n\n     (* make a new frame to evaluate the procedure body *)\n     StackSteps h (stack_frame loc stk s)\n                h (stack_frame new'loc (stack_frame loc stk s') body)\n\n| stack_steps_return_seq: forall h loc stk e s2,\n     (* return followed by crap is just return *)\n     StackSteps h (stack_frame loc stk (s_seq (s_return e) s2))\n                h (stack_frame loc stk (s_return e))\n\n| stack_steps_return_final: forall h\n                                loc loc' stk' s' s''\n                                rt ret retval\n                                x ejunk,\n     (* evaluate the return expression in the inner frame *)\n     ExprYields rt loc ret retval ->\n\n     (* the statement in the outer frame must be an assignment *)\n     s' = s_assign x ejunk ->\n\n     (* and gets updated with the return value *)\n     s'' = s_assign x (e_value rt retval) ->\n\n     (* pop the frame *)\n     StackSteps h (stack_frame loc (stack_frame loc' stk' s') (s_return ret))\n                h (stack_frame loc' stk' s'')\n.\n\n(* this is its own thing because it needs a different signature *)\n(* XXX make sure the constraint that started procs return unit gets into the types *)\nInductive StackStepsStart: Stack -> Stack -> Stack -> Prop :=\n| stack_steps_start: forall pt loc stk proc arg newloc argval,\n     ExprYields pt loc arg argval ->\n     newloc = NatMap.add 0 v_unit (NatMap.empty value) ->\n     StackStepsStart\n        (stack_frame loc stk (s_start proc arg))\n        (stack_frame loc stk s_skip)\n        (stack_frame newloc stack_empty (s_call (mkvar t_unit 0) proc (e_value pt argval)))\n.\n\nInductive StackDone: Stack -> Prop :=\n| stack_done: forall loc,\n     StackDone (stack_frame loc stack_empty s_skip)\n.\n\nEnd Stacks.\n\n(**************************************************************)\n(* threads *)\n\nSection Threads.\n\nInductive Thread: Type :=\n| thread: Stack -> Thread\n.\n\nInductive ThreadSteps: Heap -> Thread ->\n                       Heap -> Thread -> Prop :=\n| thread_steps: forall h s h' s',\n     StackSteps h s h' s' -> \n     ThreadSteps h (thread s) h' (thread s')\n.\n\nInductive ThreadStepsStart: Thread -> Thread -> Thread -> Prop :=\n| thread_steps_start: forall s s' s2,\n     StackStepsStart s s' s2 -> \n     ThreadStepsStart (thread s) (thread s') (thread s2)\n.\n\nInductive ThreadDone: Thread -> Prop :=\n| thread_done: forall stk,\n     StackDone stk ->\n     ThreadDone (thread stk)\n.\n\nEnd Threads.\n\n(**************************************************************)\n(* machines *)\n\nSection Machines.\n\nInductive Machine: Type :=\n| machine: Heap -> list Thread -> Machine\n.\n\n(*\n * XXX: how do we reason about properties like \"a thread may not exit\n * while it holds locks\"?\n *)\n\nInductive MachineSteps: Machine -> Machine -> Prop :=\n| machine_steps_plain: forall h t h' t' ts1 ts2,\n     ThreadSteps h t h' t' ->\n     MachineSteps (machine h (ts1 ++ [t] ++ ts2))\n                  (machine h' (ts1 ++ [t'] ++ ts2))\n| machine_steps_start: forall h t t1 t2 ts1 ts2,\n     ThreadStepsStart t t1 t2 ->\n     MachineSteps (machine h (ts1 ++ [t] ++ ts2))\n                  (machine h (ts1 ++ [t1; t2] ++ ts2))\n| machine_steps_exit: forall h t ts1 ts2,\n     ThreadDone t ->\n     MachineSteps (machine h (ts1 ++ [t] ++ ts2))\n                  (machine h (ts1 ++ ts2))\n.\n\nEnd Machines.\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/semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2817904583776214}}
{"text": "Require Import Omega.\nFrom Velus Require Import Common.\nFrom Velus Require Import Operators Environment.\nFrom Coq Require Import List. Import List.ListNotations. Open Scope list_scope.\nFrom Velus Require Import Lustre.LSyntax Lustre.LCausality Lustre.LTyping.\nFrom Velus Require Import Lustre.Normalization.Fresh Lustre.Normalization.Normalization.\n\n(** * Preservation of Typing through Normalization *)\n\nModule Type NTYPING\n       (Import Ids : IDS)\n       (Op : OPERATORS)\n       (OpAux : OPERATORS_AUX Op)\n       (Import Syn : LSYNTAX Ids Op)\n       (Caus : LCAUSALITY Ids Op Syn)\n       (Import Typ : LTYPING Ids Op Syn)\n       (Import Norm : NORMALIZATION Ids Op OpAux Syn Caus).\n  Import Fresh Facts Tactics.\n\n  (** ** Preservation of typeof *)\n\n  Fact unnest_noops_exps_typesof: forall cks es es' eqs' st st',\n      length cks = length es ->\n      Forall (fun e => numstreams e = 1) es ->\n      unnest_noops_exps cks es st = (es', eqs', st') ->\n      typesof es' = typesof es.\n  Proof.\n    intros.\n    repeat rewrite typesof_annots.\n    erewrite unnest_noops_exps_annots; eauto.\n  Qed.\n\n  Fact unnest_exp_typeof : forall G e is_control es' eqs' st st',\n      wl_exp G e ->\n      unnest_exp G is_control e st = (es', eqs', st')  ->\n      typesof es' = typeof e.\n  Proof with eauto.\n    intros * Hwl Hnorm.\n    eapply unnest_exp_annot in Hnorm...\n    rewrite typesof_annots, Hnorm, <- typeof_annot...\n  Qed.\n\n  Hint Resolve nth_In.\n  Corollary map_bind2_unnest_exp_typesof' :\n    forall G is_control es es' eqs' st st',\n      Forall (wl_exp G) es ->\n      map_bind2 (unnest_exp G is_control) es st = (es', eqs', st') ->\n      Forall2 (fun es' e => typesof es' = typeof e) es' es.\n  Proof with eauto.\n    intros * Hwl Hmap.\n    eapply map_bind2_unnest_exp_annots' in Hmap...\n    clear Hwl.\n    induction Hmap; constructor; eauto.\n    rewrite typesof_annots, H, <- typeof_annot...\n  Qed.\n\n  Corollary map_bind2_unnest_exp_typesof'' : forall G is_control es es' eqs' st st',\n      Forall (wl_exp G) es ->\n      map_bind2 (unnest_exp G is_control) es st = (es', eqs', st') ->\n      Forall2 (fun e ty => typeof e = [ty]) (concat es') (typesof es).\n  Proof.\n    intros * Hwl Hmap.\n    eapply map_bind2_unnest_exp_annots'' in Hmap; eauto.\n    rewrite typesof_annots, Forall2_map_2.\n    eapply Forall2_impl_In; eauto. intros; simpl in *.\n    rewrite typeof_annot, H1; auto.\n  Qed.\n\n  Corollary map_bind2_unnest_exp_typesof :\n    forall G is_control es es' eqs' st st',\n      Forall (wl_exp G) es ->\n      map_bind2 (unnest_exp G is_control) es st = (es', eqs', st') ->\n      typesof (concat es') = typesof es.\n  Proof.\n    intros * Hwl Hmap.\n    eapply map_bind2_unnest_exp_annots in Hmap; eauto.\n    rewrite typesof_annots, Hmap, <- typesof_annots; eauto.\n  Qed.\n  Hint Resolve map_bind2_unnest_exp_typesof.\n\n  Corollary unnest_exps_typesof : forall G es es' eqs' st st',\n      Forall (wl_exp G) es ->\n      unnest_exps G es st = (es', eqs', st') ->\n      typesof es' = typesof es.\n  Proof.\n    intros * Hwl Hnorm.\n    unfold unnest_exps in Hnorm; repeat inv_bind.\n    eapply map_bind2_unnest_exp_typesof in H; eauto.\n  Qed.\n\n  Fact fby_iteexp_typeof : forall e0 e ann e' eqs' st st',\n      fby_iteexp e0 e ann st = (e', eqs', st') ->\n      typeof e' = [fst ann].\n  Proof.\n    intros e0 e [ty [ck name]] e' eqs' st st' Hfby.\n    unfold fby_iteexp in Hfby.\n    destruct (is_constant e0); repeat inv_bind; try reflexivity.\n  Qed.\n\n  Fact unnest_rhs_typeof : forall G e es' eqs' st st',\n      wl_exp G e ->\n      unnest_rhs G e st = (es', eqs', st') ->\n      typesof es' = typeof e.\n  Proof with eauto.\n    intros * Hwl Hnorm.\n    eapply unnest_rhs_annot in Hnorm...\n    rewrite typesof_annots, Hnorm, <- typeof_annot...\n  Qed.\n\n  Corollary unnest_rhss_typesof : forall G es es' eqs' st st',\n      Forall (wl_exp G) es ->\n      unnest_rhss G es st = (es', eqs', st') ->\n      typesof es' = typesof es.\n  Proof with eauto.\n    intros * Hwl Hnorm.\n    eapply unnest_rhss_annots in Hnorm...\n    rewrite typesof_annots, Hnorm, <- typesof_annots...\n  Qed.\n\n  (** ** A few additional tactics *)\n\n  Definition st_tys (st : fresh_st (Op.type * clock)) := idty (st_anns st).\n  Definition st_tys' (st : fresh_st ((Op.type * clock) * bool)) := idty (idty (st_anns st)).\n\n  Fact st_anns_tys_In : forall st id ty,\n      In (id, ty) (st_tys st) <-> (exists cl, In (id, (ty, cl)) (st_anns st)).\n  Proof.\n    intros st id ty.\n    split; intros; unfold st_tys, idty in *.\n    - repeat simpl_In; simpl in *.\n      inv H.\n      exists c. assumption.\n    - repeat simpl_In; simpl in *.\n      destruct H as [cl Hin].\n      exists (id, (ty, cl)); simpl; split; auto.\n  Qed.\n\n  Fact st_follows_tys_incl : forall st st',\n      st_follows st st' ->\n      incl (st_tys st) (st_tys st').\n  Proof.\n    intros st st' Hfollows.\n    apply st_follows_incl in Hfollows.\n    unfold st_tys, idty.\n    repeat apply incl_map.\n    assumption.\n  Qed.\n\n  Fact idents_for_anns_incl_ty : forall anns ids st st',\n    idents_for_anns anns st = (ids, st') ->\n    incl (idty ids) (st_tys st').\n  Proof.\n    intros anns ids st st' Hids.\n    apply idents_for_anns_incl in Hids.\n    intros [id ty] Hin.\n    unfold st_tys, idty in *.\n    repeat simpl_In. inv H.\n    exists (id, (ty, (fst n))); split; auto.\n    apply Hids. repeat simpl_In.\n    exists (id, (ty, n)). destruct n; auto.\n  Qed.\n\n  Fact idents_for_anns'_incl_ty : forall anns ids st st',\n    idents_for_anns' anns st = (ids, st') ->\n    incl (idty ids) (st_tys st').\n  Proof.\n    intros anns ids st st' Hids.\n    apply idents_for_anns'_incl in Hids.\n    intros [id ty] Hin.\n    unfold st_tys, idty in *.\n    repeat simpl_In. inv H.\n    exists (id, (ty, c)); split; auto.\n    apply Hids. repeat simpl_In.\n    exists (id, (ty, (c, o))); auto.\n  Qed.\n\n  Ltac solve_incl :=\n    match goal with\n    | H : wt_clock ?l1 ?cl |- wt_clock ?l2 ?cl =>\n      eapply wt_clock_incl; [| eauto]\n    | H : wt_nclock ?l1 ?cl |- wt_nclock ?l2 ?cl =>\n      eapply wt_nclock_incl; [| eauto]\n    | H : wt_exp ?G ?l1 ?e |- wt_exp ?G ?l2 ?e =>\n      eapply wt_exp_incl; [| eauto]\n    | H : wt_equation ?G ?l1 ?eq |- wt_equation ?G ?l2 ?eq =>\n      eapply wt_equation_incl; [| eauto]\n    | |- incl ?l1 ?l1 => reflexivity\n    | |- incl ?l1 (?l1 ++ ?l2) =>\n      eapply incl_appl; reflexivity\n    | |- incl (?l1 ++ ?l2) (?l1 ++ ?l3) =>\n      eapply incl_app\n    | |- incl ?l1 (?l2 ++ ?l3) =>\n      eapply incl_appr\n    | |- incl ?l1 (?a::?l2) =>\n      eapply incl_tl\n    | |- incl (st_anns ?st1) (st_anns _) =>\n      eapply st_follows_incl; repeat solve_st_follows\n    | |- incl (st_tys ?st1) (st_tys _) =>\n      eapply st_follows_tys_incl; repeat solve_st_follows\n    | |- incl (st_tys' ?st1) (st_tys' _) =>\n      unfold st_tys', idty; do 2 eapply incl_map; eapply st_follows_incl; repeat solve_st_follows\n    | H : incl ?l1 ?l2 |- incl (idty ?l1) (idty ?l2) =>\n      eapply incl_map; eauto\n    | H : In ?x ?l1 |- In ?x ?l2 =>\n      assert (incl l1 l2); eauto\n    end; auto.\n\n  Hint Resolve in_combine_l in_combine_r.\n  Hint Resolve incl_tl incl_appl incl_appr incl_app incl_refl.\n\n  (** ** Preservation of wt through the first pass *)\n\n  Fact idents_for_anns_wt : forall G vars anns ids st st',\n      idents_for_anns anns st = (ids, st') ->\n      Forall (fun '(ty, cl) => wt_nclock (vars++st_tys st) cl) anns ->\n      Forall (wt_exp G (vars++st_tys st')) (map (fun '(x, ann) => Evar x ann) ids).\n  Proof.\n    induction anns; intros ids st st' Hidents Hf;\n      repeat inv_bind.\n    - constructor.\n    - inv Hf. destruct a as [ty [cl ?]]. repeat inv_bind.\n      assert (Forall (fun '(_, cl) => wt_nclock (vars ++ st_tys x0) cl) anns) as Hanns'.\n      { solve_forall. repeat solve_incl. }\n      rewrite Forall_map.\n      eapply IHanns in Hanns'; eauto.\n      econstructor.\n      + repeat constructor; simpl.\n        * apply in_or_app; right.\n          apply fresh_ident_In in H.\n          rewrite st_anns_tys_In. exists cl.\n          eapply idents_for_anns_st_follows, st_follows_incl in H0; eauto.\n        * inv H1. repeat solve_incl.\n      + simpl_forall.\n  Qed.\n\n  Fact idents_for_anns'_wt : forall G vars anns ids st st',\n      idents_for_anns' anns st = (ids, st') ->\n      Forall (fun '(ty, cl) => wt_nclock (vars++(idty ids)++st_tys st) cl) anns ->\n      Forall (wt_exp G (vars++(idty ids)++st_tys st')) (map (fun '(x, ann) => Evar x ann) ids).\n  Proof.\n    induction anns; intros ids st st' Hidents Hf;\n      repeat inv_bind.\n    - constructor.\n    - inv Hf. destruct a as [ty [cl ?]]. repeat inv_bind.\n      rewrite Forall_map.\n      destruct o; repeat inv_bind; econstructor; eauto.\n      + repeat constructor; simpl.\n        * apply in_or_app. right. constructor; auto.\n        * inv H1. destruct x; simpl in *. solve_incl.\n          eapply incl_appr', incl_tl', incl_appr'. solve_incl.\n      + destruct x. eapply IHanns in H0.\n        * rewrite Forall_map in H0.\n          solve_forall. repeat solve_incl.\n        * solve_forall. solve_incl.\n          rewrite Permutation.Permutation_middle.\n          eapply incl_appr', incl_appr', incl_cons; repeat solve_incl.\n          eapply reuse_ident_In in H. unfold st_tys, idty, idty.\n          rewrite in_map_iff. exists (i, (ty, cl)); split; auto.\n      + repeat constructor; simpl.\n        * apply in_or_app. right. constructor; auto.\n        * inv H1. solve_incl; simpl.\n          eapply incl_appr', incl_tl', incl_appr'. solve_incl.\n      + eapply IHanns in H0.\n        * rewrite Forall_map in H0.\n          solve_forall. repeat solve_incl.\n        * solve_forall. solve_incl.\n          rewrite Permutation.Permutation_middle.\n          eapply incl_appr', incl_appr', incl_cons; try solve_incl.\n          eapply fresh_ident_In in H. unfold st_tys, idty, idty.\n          rewrite in_map_iff. exists (x, (ty, cl)); split; auto.\n  Qed.\n\n  Fact idents_for_anns'_wt_nclock : forall vars anns ids st st',\n      idents_for_anns' anns st = (ids, st') ->\n      Forall (fun '(ty, cl) => wt_nclock (vars++idty (anon_streams anns)++st_tys st) cl) anns ->\n      Forall (wt_nclock (vars++idty (anon_streams (map snd ids))++st_tys st')) (map snd (map snd ids)).\n  Proof with eauto.\n    induction anns; intros ids st st' Hidents Hf;\n      repeat inv_bind; simpl; auto.\n    inv Hf. destruct a as [ty [cl ?]].\n    destruct o; repeat inv_bind; simpl; constructor.\n    - repeat constructor; simpl.\n      inv H1. destruct x; simpl in *. solve_incl.\n      eapply incl_appr', incl_tl', incl_app.\n      + apply incl_appl.\n        eapply idents_for_anns'_anon_streams, incl_map in H0...\n      + apply incl_appr. solve_incl.\n    - eapply IHanns in H0.\n      + solve_forall. repeat solve_incl.\n      + solve_forall. destruct x. solve_incl.\n        rewrite Permutation.Permutation_middle.\n        eapply incl_appr', incl_appr', incl_cons; try solve_incl.\n        eapply reuse_ident_In in H. unfold st_tys, idty, idty.\n        rewrite in_map_iff. exists (i, (ty, cl)); split; auto.\n    - repeat constructor; simpl.\n      inv H1. solve_incl.\n      eapply incl_appr', incl_app.\n      + apply incl_appl.\n        eapply idents_for_anns'_anon_streams, incl_map in H0...\n      + apply incl_appr. solve_incl.\n    - eapply IHanns in H0.\n      + solve_forall.\n      + solve_forall. solve_incl.\n        eapply incl_appr', incl_appr'. solve_incl.\n  Qed.\n\n  Fact hd_default_wt_exp : forall G vars es,\n      Forall (wt_exp G vars) es ->\n      wt_exp G vars (hd_default es).\n  Proof.\n    intros G vars es Hf.\n    destruct es; simpl.\n    - constructor.\n    - inv Hf; auto.\n  Qed.\n\n  Hint Constructors wt_exp.\n\n  Lemma idty_without_names : forall vars,\n      idty (without_names' vars) = idty vars.\n  Proof.\n    intros vars.\n    unfold idty, without_names'.\n    rewrite map_map.\n    eapply map_ext; intros [id [ty [cl n]]]; reflexivity.\n  Qed.\n\n  Definition idck' (vars : list (ident * ann)) : list (ident * clock) :=\n    idck (without_names' vars).\n\n  Fact unnest_fby_wt_exp : forall G vars e0s es anns,\n      Forall (wt_nclock vars) (map snd anns) ->\n      Forall (wt_exp G vars) e0s ->\n      Forall (wt_exp G vars) es ->\n      Forall2 (fun e0 a => typeof e0 = [a]) e0s (map fst anns) ->\n      Forall2 (fun e a => typeof e = [a]) es (map fst anns) ->\n      Forall (wt_exp G vars) (unnest_fby e0s es anns).\n  Proof.\n    intros * Hwtc Hwt1 Hwt2 Hty1 Hty2.\n    unfold unnest_fby.\n    assert (length e0s = length anns) as Hlen1 by (eapply Forall2_length in Hty1; solve_length).\n    assert (length es = length anns) as Hlen2 by (eapply Forall2_length in Hty2; solve_length).\n    solve_forall.\n    constructor; simpl; try rewrite app_nil_r; eauto.\n  Qed.\n\n  Fact unnest_arrow_wt_exp : forall G vars e0s es anns,\n      Forall (wt_nclock vars) (map snd anns) ->\n      Forall (wt_exp G vars) e0s ->\n      Forall (wt_exp G vars) es ->\n      Forall2 (fun e0 a => typeof e0 = [a]) e0s (map fst anns) ->\n      Forall2 (fun e a => typeof e = [a]) es (map fst anns) ->\n      Forall (wt_exp G vars) (unnest_arrow e0s es anns).\n  Proof.\n    intros * Hwtc Hwt1 Hwt2 Hty1 Hty2.\n    unfold unnest_arrow.\n    assert (length e0s = length anns) as Hlen1 by (eapply Forall2_length in Hty1; solve_length).\n    assert (length es = length anns) as Hlen2 by (eapply Forall2_length in Hty2; solve_length).\n    solve_forall.\n    constructor; simpl; try rewrite app_nil_r; eauto.\n  Qed.\n\n  Fact unnest_when_wt_exp : forall G vars b ckid es tys ck,\n      In (ckid, Op.bool_type) vars ->\n      wt_nclock vars ck ->\n      Forall (wt_exp G vars) es ->\n      Forall2 (fun e ty => typeof e = [ty]) es tys ->\n      Forall (wt_exp G vars) (unnest_when ckid b es tys ck).\n  Proof.\n    intros * HIn Hwtck Hwt Htys. unfold unnest_when.\n    assert (length es = length tys) as Hlength by (eapply Forall2_length in Htys; eauto).\n    rewrite Forall_map. apply Forall2_combine'.\n    eapply Forall2_ignore2' with (ys:=tys) in Hwt; eauto.\n    eapply Forall2_Forall2 in Hwt; eauto. clear Htys.\n    eapply Forall2_impl_In; eauto. intros ? ? ? ? [? ?].\n    repeat constructor; simpl; auto.\n    rewrite app_nil_r; auto.\n  Qed.\n\n  Fact unnest_merge_wt_exp : forall G vars ckid ets efs tys ck,\n      In (ckid, Op.bool_type) vars ->\n      wt_nclock vars ck ->\n      Forall (wt_exp G vars) ets ->\n      Forall (wt_exp G vars) efs ->\n      Forall2 (fun e ty => typeof e = [ty]) ets tys ->\n      Forall2 (fun e ty => typeof e = [ty]) efs tys ->\n      Forall (wt_exp G vars) (unnest_merge ckid ets efs tys ck).\n  Proof with eauto.\n    intros * HIn Hwtck Hwt1 Hwt2 Htys1 Htys2. unfold unnest_merge.\n    assert (length ets = length tys) as Hlen1 by (eauto using Forall2_length).\n    assert (length efs = length tys) as Hlen2 by (eauto using Forall2_length).\n    solve_forall.\n    repeat constructor; simpl; auto. 1,2:rewrite app_nil_r; auto.\n  Qed.\n\n  Fact unnest_ite_wt_exp : forall G vars e ets efs tys ck,\n      wt_nclock vars ck ->\n      wt_exp G vars e ->\n      typeof e = [Op.bool_type] ->\n      Forall (wt_exp G vars) ets ->\n      Forall (wt_exp G vars) efs ->\n      Forall2 (fun e ty => typeof e = [ty]) ets tys ->\n      Forall2 (fun e ty => typeof e = [ty]) efs tys ->\n      Forall (wt_exp G vars) (unnest_ite e ets efs tys ck).\n  Proof with eauto.\n    intros * Hwtck Hwt Htye Hwt1 Hwt2 Htys1 Htys2. unfold unnest_ite.\n    assert (length ets = length tys) as Hlen1 by (eauto using Forall2_length).\n    assert (length efs = length tys) as Hlen2 by (eauto using Forall2_length).\n    solve_forall.\n    repeat constructor; simpl; auto. 1,2:rewrite app_nil_r; auto.\n  Qed.\n\n  Lemma unnest_noops_exps_wt : forall G vars cks es es' eqs' st st' ,\n      length es = length cks ->\n      Forall normalized_lexp es ->\n      Forall (fun e => numstreams e = 1) es ->\n      Forall (wt_exp G (vars++st_tys st)) es ->\n      unnest_noops_exps cks es st = (es', eqs', st') ->\n      Forall (wt_exp G (vars++st_tys st')) es' /\\\n      Forall (wt_equation G (vars++st_tys st')) eqs'.\n  Proof.\n    unfold unnest_noops_exps.\n    induction cks; intros * Hlen Hnormed Hnums Hwt Hunt; repeat inv_bind; simpl; auto.\n    destruct es; simpl in *; inv Hlen; repeat inv_bind.\n    inv Hwt. inv Hnums. inv Hnormed.\n    assert (Forall (wt_exp G (vars ++ st_tys x2)) es) as Hes.\n    { solve_forall. repeat solve_incl; eauto. }\n    eapply IHcks in Hes as (Hes'&Heqs'). 2-4:eauto.\n    2:repeat inv_bind; repeat eexists; eauto; inv_bind; eauto.\n    unfold unnest_noops_exp in H.\n    rewrite <-length_annot_numstreams in H6. singleton_length.\n    destruct p as (?&?&?).\n    split; simpl; try constructor; try (rewrite Forall_app; split); auto.\n    1,2:destruct (is_noops_exp); repeat inv_bind; auto.\n    + repeat solve_incl.\n    + constructor. eapply fresh_ident_In in H.\n      eapply in_or_app. right. rewrite st_anns_tys_In.\n      eapply st_follows_incl in H; eauto. repeat solve_st_follows.\n      constructor. eapply wt_exp_clockof in H4.\n      rewrite normalized_lexp_no_fresh in H4; simpl in *; auto. repeat rewrite app_nil_r in H4.\n      rewrite clockof_annot, Hsingl in H4. apply Forall_singl in H4.\n      repeat solve_incl.\n    + repeat constructor; auto; simpl; try rewrite app_nil_r.\n      * repeat solve_incl.\n      * rewrite typeof_annot, Hsingl; simpl.\n        constructor; auto.\n        eapply fresh_ident_In in H.\n        eapply in_or_app. right. rewrite st_anns_tys_In.\n        eapply st_follows_incl in H; eauto. repeat solve_st_follows.\n  Qed.\n\n  Fact map_bind2_wt {A B} :\n    forall G vars (k : A -> Fresh (list exp * list equation) B) a es' eqs' st st',\n      map_bind2 k a st = (es', eqs', st') ->\n      (forall st st' a es eqs', k a st = (es, eqs', st') -> st_follows st st') ->\n      Forall (fun a => forall es' eqs' st0 st0',\n                  k a st0 = (es', eqs', st0') ->\n                  st_follows st st0 ->\n                  st_follows st0' st' ->\n                  Forall (wt_exp G vars) es' /\\\n                  Forall (wt_equation G vars) eqs') a ->\n      Forall (wt_exp G vars) (concat es') /\\\n      Forall (wt_equation G vars) (concat eqs').\n  Proof.\n    intros G vars k a.\n    induction a; intros es' a2s st st' Hmap Hfollows Hforall;\n      repeat inv_bind.\n    - simpl; auto.\n    - simpl. repeat rewrite Forall_app.\n      inv Hforall. assert (Hk:=H). eapply H3 in H as [Hwt1 Hwt1'].\n      2:reflexivity.\n      2:eapply map_bind2_st_follows; eauto; solve_forall.\n      eapply IHa in H0 as [Hwt2 Hwt2']; eauto.\n      solve_forall. eapply H1; eauto.\n      etransitivity; eauto.\n  Qed.\n\n  Import Permutation.\n\n  Fact unnest_reset_wt : forall G vars e e' eqs' st st',\n      LiftO True (fun e => forall es' eqs' st',\n                   unnest_exp G true e st = (es', eqs', st') ->\n                   Forall (wt_exp G (vars++st_tys st')) es' /\\\n                   Forall (wt_equation G (vars++st_tys st')) eqs') e ->\n      LiftO True (fun e => incl (fresh_in e) (st_anns st')) e ->\n      LiftO True (wt_exp G (vars++st_tys st)) e ->\n      LiftO True (fun e => typeof e = [Op.bool_type]) e ->\n      unnest_reset (unnest_exp G true) e st = (e', eqs', st') ->\n      LiftO True (fun e' => typeof e' = [Op.bool_type]) e' /\\\n      LiftO True (wt_exp G (vars++st_tys st')) e' /\\\n      Forall (wt_equation G (vars++st_tys st')) eqs'.\n  Proof.\n    intros * Hunwt Hincl Hwt Hty Hnorm.\n    assert (st_follows st st') as Hfollows.\n    { repeat solve_st_follows; destruct e; simpl; intros; eauto. }\n    unnest_reset_spec; simpl in *; auto.\n    1,2:assert (length l = 1).\n    1,3:(eapply unnest_exp_length in Hk0; eauto;\n         rewrite <- length_typeof_numstreams, Hty in Hk0; auto).\n    1,2:singleton_length.\n    - assert (Hk:=Hk0). eapply unnest_exp_typeof in Hk0; eauto; simpl in Hk0.\n      eapply Hunwt in Hk as [He Heq]; inv He; eauto.\n      repeat split; eauto. congruence.\n    - assert (Hk:=Hk0). eapply unnest_exp_annot in Hk0; eauto. simpl in Hk0. rewrite app_nil_r in Hk0.\n      assert (Hk1:=Hk). eapply unnest_exp_fresh_incl in Hk1.\n      assert (x = Op.bool_type) as Hbool.\n      { rewrite Hk0 in Hhd.\n        rewrite typeof_annot in *.\n        destruct (annot e0); simpl in *. inv Hty.\n        subst; simpl in *. destruct l; try congruence.\n      }\n      eapply Hunwt in Hk as [He Heq]; inv He.\n      repeat constructor.\n      + eapply fresh_ident_In in Hfresh.\n        apply in_or_app; right.\n        rewrite st_anns_tys_In. exists x0. assumption.\n      + apply wt_exp_clockof in Hwt.\n        rewrite Hk0 in Hhd.\n        rewrite clockof_annot in Hwt.\n        rewrite typeof_annot in Hty.\n        destruct (annot e0); simpl in *. inv Hty.\n        inv Hwt; simpl in *. solve_incl.\n        rewrite <- app_assoc. apply incl_appr'.\n        apply incl_app; repeat solve_incl.\n        eapply fresh_ident_st_follows, st_follows_incl in Hfresh.\n        unfold st_tys, idty. apply incl_map. etransitivity; eauto.\n      + repeat solve_incl.\n      + simpl; rewrite app_nil_r, typeof_annot, Hk0, <- typeof_annot, Hty.\n        repeat constructor.\n        eapply fresh_ident_In in Hfresh.\n        apply in_or_app; right.\n        unfold st_tys, idty. simpl_In; eexists; split; eauto. simpl. f_equal.\n      + solve_forall; repeat solve_incl.\n  Qed.\n\n  Lemma unnest_exp_wt : forall G vars e is_control es' eqs' st st',\n      wt_exp G (vars++st_tys st) e ->\n      unnest_exp G is_control e st = (es', eqs', st') ->\n      Forall (wt_exp G (vars++st_tys st')) es' /\\\n      Forall (wt_equation G (vars++st_tys st')) eqs'.\n  Proof with eauto.\n    induction e using exp_ind2; intros * Hwt Hnorm; inv Hwt; simpl in *.\n    - (* const *)\n      repeat inv_bind...\n    - (* var *)\n      repeat inv_bind.\n      repeat constructor...\n    - (* unop *)\n      repeat inv_bind.\n      assert (length x = numstreams e) as Hlen by eauto.\n      rewrite <- length_typeof_numstreams, H3 in Hlen; simpl in Hlen.\n      singleton_length.\n      assert (Hnorm:=H); eapply IHe in H as [Hwt1 Hwt1']; eauto.\n      repeat econstructor...\n      + inv Hwt1; eauto.\n      + eapply unnest_exp_typeof in Hnorm; simpl in Hnorm; eauto.\n        rewrite app_nil_r, H3 in Hnorm...\n      + repeat solve_incl.\n    - (* binop *)\n      repeat inv_bind.\n      assert (length x = numstreams e1) as Hlen1 by eauto.\n      rewrite <- length_typeof_numstreams, H5 in Hlen1; simpl in Hlen1.\n      assert (length x2 = numstreams e2) as Hlen2 by eauto.\n      rewrite <- length_typeof_numstreams, H6 in Hlen2; simpl in Hlen2. repeat singleton_length.\n      assert (Hnorm1:=H); eapply IHe1 in H as [Hwt1 Hwt1']; eauto.\n      assert (Hnorm2:=H0); eapply IHe2 in H0 as [Hwt2 Hwt2']; eauto. 2:repeat solve_incl.\n      repeat econstructor...\n      + inv Hwt1. repeat solve_incl.\n      + inv Hwt2...\n      + eapply unnest_exp_typeof in Hnorm1; simpl in Hnorm1; eauto.\n        rewrite app_nil_r, H5 in Hnorm1...\n      + eapply unnest_exp_typeof in Hnorm2; simpl in Hnorm2; eauto.\n        rewrite app_nil_r, H6 in Hnorm2...\n      + repeat solve_incl.\n      + apply Forall_app; split; auto.\n        solve_forall. repeat solve_incl.\n    - (* fby *)\n      Local Ltac solve_map_bind2 :=\n        solve_forall;\n        match goal with\n        | Hnorm : unnest_exp _ _ _ _ = _, H : context [unnest_exp _ _ _ _ = _ -> _] |- _ =>\n          eapply H in Hnorm as [? ?]; eauto;\n          [split|]; try solve_forall; repeat solve_incl\n        end.\n      repeat inv_bind.\n      assert (Hnorm1:=H1). eapply map_bind2_wt with (G0:=G) (vars0:=vars++st_tys x1) in H1 as [Hwt1 Hwt1']...\n      assert (Hnorm2:=H2). eapply map_bind2_wt with (G0:=G) (vars0:=vars++st_tys x4) in H2 as [Hwt2 Hwt2']...\n      2,3:solve_map_bind2.\n      repeat rewrite Forall_app. repeat split.\n      3,4:solve_forall; repeat solve_incl.\n      + eapply idents_for_anns_wt in H3...\n        solve_forall. repeat solve_incl.\n      + assert (Forall (wt_exp G (vars++st_tys st')) (unnest_fby (concat x2) (concat x6) a)) as Hwcfby.\n        { eapply unnest_fby_wt_exp...\n          1-3:solve_forall; repeat solve_incl.\n          + eapply map_bind2_unnest_exp_typesof'' in Hnorm1... congruence.\n          + eapply map_bind2_unnest_exp_typesof'' in Hnorm2... congruence. }\n        remember (unnest_fby _ _ _) as fby.\n        assert (length (concat x2) = length a) as Hlen1.\n        { eapply map_bind2_unnest_exp_length in Hnorm1...\n          repeat simpl_length. erewrite <- map_length, H7; solve_length. }\n        assert (length (concat x6) = length a) as Hlen2.\n        { eapply map_bind2_unnest_exp_length in Hnorm2...\n          repeat simpl_length. erewrite <- map_length, H6; solve_length. }\n        assert (length fby = length x5).\n        { rewrite Heqfby, unnest_fby_length...\n          eapply idents_for_anns_length in H3... }\n        assert (Forall2 (fun '(ty, _) e => typeof e = [ty]) (map snd x5) fby) as Htys.\n        { eapply idents_for_anns_values in H3; subst.\n          specialize (unnest_fby_annot' _ _ _ Hlen1 Hlen2) as Hanns; eauto. clear - Hanns.\n          eapply Forall2_swap_args. solve_forall.\n          destruct a0 as [ty ck]; simpl in *. rewrite typeof_annot, H1; auto. }\n        solve_forall.\n        repeat constructor; eauto.\n        destruct a0 as [ty ck]; simpl in *. rewrite app_nil_r, H5.\n        constructor; auto. eapply idents_for_anns_incl_ty in H3.\n        apply in_or_app, or_intror, H3. unfold idty; simpl_In. exists (i, (ty, ck)); auto.\n    - (* arrow *)\n      repeat inv_bind.\n      assert (Hnorm1:=H1). eapply map_bind2_wt with (G0:=G) (vars0:=vars++st_tys x1) in H1 as [Hwt1 HWt1']...\n      assert (Hnorm2:=H2). eapply map_bind2_wt with (G0:=G) (vars0:=vars++st_tys x4) in H2 as [Hwt2 Hwt2']...\n      2,3:solve_map_bind2.\n      repeat rewrite Forall_app. repeat split.\n      3,4:solve_forall; repeat solve_incl.\n      + eapply idents_for_anns_wt in H3...\n        solve_forall. repeat solve_incl.\n      + assert (Forall (wt_exp G (vars++st_tys st')) (unnest_arrow (concat x2) (concat x6) a)) as Hwcfby.\n        { eapply unnest_arrow_wt_exp...\n          1-3:solve_forall; repeat solve_incl.\n          + eapply map_bind2_unnest_exp_typesof'' in Hnorm1... congruence.\n          + eapply map_bind2_unnest_exp_typesof'' in Hnorm2... congruence. }\n        remember (unnest_arrow _ _ _) as fby.\n        assert (length (concat x2) = length a) as Hlen1.\n        { eapply map_bind2_unnest_exp_length in Hnorm1...\n          repeat simpl_length. erewrite <- map_length, H7; solve_length. }\n        assert (length (concat x6) = length a) as Hlen2.\n        { eapply map_bind2_unnest_exp_length in Hnorm2...\n          repeat simpl_length. erewrite <- map_length, H6; solve_length. }\n        assert (length fby = length x5).\n        { rewrite Heqfby, unnest_arrow_length...\n          eapply idents_for_anns_length in H3... }\n        assert (Forall2 (fun '(ty, _) e => typeof e = [ty]) (map snd x5) fby) as Htys.\n        { eapply idents_for_anns_values in H3; subst.\n          specialize (unnest_arrow_annot' _ _ _ Hlen1 Hlen2) as Hanns; eauto. clear - Hanns.\n          eapply Forall2_swap_args. solve_forall.\n          destruct a0 as [ty ck]; simpl in *. rewrite typeof_annot, H1; auto. }\n        solve_forall.\n        repeat constructor; eauto.\n        destruct a0 as [ty ck]; simpl in *. rewrite app_nil_r, H5.\n        constructor; auto. eapply idents_for_anns_incl_ty in H3.\n        apply in_or_app, or_intror, H3. unfold idty; simpl_In. exists (i, (ty, ck)); auto.\n    - (* when *)\n      repeat inv_bind.\n      assert (Hnorm:=H0). eapply map_bind2_wt with (G0:=G) (vars0:=vars++st_tys st') in H0 as [Hwt1 Hwt1']; eauto.\n      2:solve_map_bind2.\n      split; eauto.\n      eapply unnest_when_wt_exp; auto.\n      + assert (incl (vars ++ st_tys st) (vars ++ st_tys st')) as Hincl by repeat solve_incl...\n      + repeat solve_incl.\n      + eapply map_bind2_unnest_exp_typesof'' in Hnorm; eauto.\n    - (* merge *)\n      repeat inv_bind.\n      assert (Hnorm1:=H1). eapply map_bind2_wt with (G0:=G) (vars0:=vars++st_tys x2) in H1 as [Hwt1 Hwt1']; eauto.\n      2:solve_map_bind2.\n      assert (Hnorm2:=H2). eapply map_bind2_wt with (G0:=G) (vars0:=vars++st_tys x5) in H2 as [Hwt2 Hwt2']; eauto.\n      2:solve_map_bind2.\n      remember (unnest_merge _ _ _ _ _) as merges.\n      assert (Forall (wt_exp G (vars++st_tys x5)) merges) as Hwt'.\n      { subst. apply unnest_merge_wt_exp; auto.\n        - assert (incl (vars ++ st_tys st) (vars ++ st_tys x5)) by repeat solve_incl; eauto.\n        - repeat solve_incl.\n        - solve_forall. repeat solve_incl.\n        - eapply map_bind2_unnest_exp_typesof'' in Hnorm1...\n        - eapply map_bind2_unnest_exp_typesof'' in Hnorm2... congruence.\n      }\n      destruct is_control; repeat inv_bind; repeat rewrite Forall_app; repeat split.\n      1,2,3,6,7:solve_forall; repeat solve_incl.\n      + specialize (idents_for_anns_incl_ty _ _ _ _ H1) as Hincl.\n        apply idents_for_anns_wt with (G:=G) (vars:=vars) in H1...\n        rewrite Forall_forall; intros.\n        repeat simpl_In. inv H2... repeat solve_incl.\n      + assert (length (concat x3) = length (typesof ets)) as Hlen1.\n        { eapply map_bind2_unnest_exp_length in Hnorm1; eauto; solve_length. }\n        assert (length (concat x6) = length (typesof efs)) as Hlen2.\n        { clear H9. eapply map_bind2_unnest_exp_length in Hnorm2; eauto; solve_length. }\n        remember (unnest_merge _ _ _ _ _) as merges.\n        assert (Forall2 (fun '(ty, _) e => annot e = [(ty, nck)]) (map snd x0) merges) as Htys.\n        { eapply idents_for_anns_values in H1. rewrite H1, Forall2_map_1.\n          subst; eapply unnest_merge_annot; eauto. congruence. } rewrite Forall2_map_1 in Htys.\n        eapply Forall2_ignore1' with (xs:=x0) in Hwt'.\n        2:{ subst. apply idents_for_anns_length in H1. rewrite map_length in H1.\n            rewrite unnest_merge_length... congruence. }\n        solve_forall.\n        repeat constructor... 1:repeat solve_incl.\n        destruct a; simpl in *.\n        rewrite typeof_annot, H4, app_nil_r; simpl.\n        constructor; auto.\n        assert (In (i, t) (idty x0)).\n        { unfold idty. rewrite in_map_iff. exists (i, (t, n)); eauto. }\n        eapply idents_for_anns_incl_ty in H1.\n        eapply in_or_app, or_intror...\n    - (* ite *)\n      repeat inv_bind.\n      assert (length x = 1). 2:singleton_length.\n      { eapply unnest_exp_length in H1; eauto.\n        rewrite <- length_typeof_numstreams, H8 in H1; auto. }\n      assert (Hnorm0:=H1). eapply IHe in H1 as [Hwt0 Hwt0']... clear IHe.\n      assert (Hnorm1:=H2). eapply map_bind2_wt with (G0:=G) (vars0:=vars++st_tys x4) in H2 as [Hwt1 Hwt1']; eauto.\n      2:solve_map_bind2.\n      assert (Hnorm2:=H3). eapply map_bind2_wt with (G0:=G) (vars0:=vars++st_tys x7) in H3 as [Hwt2 Hwt2']; eauto.\n      2:solve_map_bind2. clear H H0.\n      remember (unnest_ite _ _ _ _ _) as ites.\n      assert (Forall (wt_exp G (vars++st_tys x7)) ites) as Hwt'.\n      { subst. apply unnest_ite_wt_exp; auto.\n        - repeat solve_incl.\n        - inv Hwt0. repeat solve_incl.\n        - eapply unnest_exp_typeof in Hnorm0; eauto.\n          simpl in Hnorm0. rewrite app_nil_r in Hnorm0; congruence.\n        - solve_forall. repeat solve_incl.\n        - eapply map_bind2_unnest_exp_typesof'' in Hnorm1...\n        - eapply map_bind2_unnest_exp_typesof'' in Hnorm2... congruence.\n      }\n      destruct is_control; repeat inv_bind; repeat rewrite Forall_app; repeat split.\n      1,2,3,4,7,8,9:solve_forall; repeat solve_incl.\n      + specialize (idents_for_anns_incl_ty _ _ _ _ H) as Hincl.\n        apply idents_for_anns_wt with (G:=G) (vars:=vars) in H...\n        rewrite Forall_forall; intros.\n        repeat simpl_In. inv H0... repeat solve_incl.\n      + assert (length (concat x5) = length (typesof ets)) as Hlen1.\n        { eapply map_bind2_unnest_exp_length in Hnorm1; eauto; solve_length. }\n        assert (length (concat x8) = length (typesof efs)) as Hlen2.\n        { clear H10. eapply map_bind2_unnest_exp_length in Hnorm2; eauto; solve_length. }\n        remember (unnest_ite _ _ _ _ _) as ites.\n        assert (Forall2 (fun '(ty, _) e => annot e = [(ty, nck)]) (map snd x) ites) as Htys.\n        { eapply idents_for_anns_values in H. rewrite H, Forall2_map_1.\n          subst; eapply unnest_ite_annot; eauto. congruence. } rewrite Forall2_map_1 in Htys.\n        eapply Forall2_ignore1' with (xs:=x) in Hwt'.\n        2:{ subst. apply idents_for_anns_length in H. rewrite map_length in H.\n            rewrite unnest_ite_length... congruence. }\n        solve_forall.\n        repeat constructor... 1:repeat solve_incl.\n        destruct a; simpl in *.\n        rewrite typeof_annot, H2, app_nil_r; simpl.\n        constructor; auto.\n        assert (In (i, t) (idty x)).\n        { unfold idty. rewrite in_map_iff. exists (i, (t, n)); eauto. }\n        eapply idents_for_anns_incl_ty in H.\n        eapply in_or_app, or_intror...\n    - (* app *)\n      repeat inv_bind. rewrite app_nil_r.\n      assert (Hnorm:=H1). eapply map_bind2_wt with (G0:=G) (vars0:=vars++st_tys x7) in H1 as [Hwt1 Hwt1']...\n      2:solve_map_bind2.\n      assert (length (find_node_incks G f) = length (concat x5)) as Hlen1.\n      { unfold find_node_incks. rewrite H6.\n        eapply Forall2_length in H7. rewrite map_length.\n        eapply map_bind2_unnest_exp_length in Hnorm; eauto. rewrite length_typesof_annots in H7.\n        congruence. }\n      assert (Forall (fun e : exp => numstreams e = 1) (concat x5)) as Hnum.\n      { eapply map_bind2_unnest_exp_numstreams; eauto. }\n      split; [|constructor]...\n      + specialize (idents_for_anns'_incl_ty _ _ _ _ H3) as Hincl.\n        eapply idents_for_anns'_wt with (G:=G) (vars:=vars) in H3... 1:solve_forall; repeat solve_incl.\n        solve_forall; simpl in *...\n        solve_incl. unfold idty. rewrite map_app, <- app_assoc.\n        apply incl_appr', incl_app; [repeat solve_incl|apply incl_app;[apply incl_appr|apply incl_appl]].\n        * eapply map_bind2_unnest_exp_fresh_incl in Hnorm.\n          unfold st_tys, idty in *. eapply incl_map; eauto. etransitivity; eauto.\n        * eapply idents_for_anns'_anon_streams_incl, incl_map in H3.\n          etransitivity. eapply H3.\n          replace (map _ (without_names' x4)) with (map (fun xtc => (fst xtc, fst (snd xtc))) x4); auto.\n          unfold without_names'; rewrite map_map; simpl.\n          apply map_ext; intros [? [? [? ?]]]; auto.\n      + repeat econstructor; eauto.\n        * eapply unnest_noops_exps_wt with (G:=G) (vars:=vars) in H2 as (?&?); eauto.\n          2:eapply map_bind2_wt in Hnorm as (?&?); eauto; try solve_map_bind2.\n          solve_forall; repeat solve_incl.\n        * erewrite unnest_noops_exps_typesof, map_bind2_unnest_exp_typesof; eauto.\n        * eapply idents_for_anns'_values in H3. congruence.\n        * eapply idents_for_anns'_wt_nclock with (vars:=vars) in H3.\n          -- rewrite Forall_map in H3. solve_forall.\n             solve_incl.\n             rewrite <- app_assoc. apply incl_appr'.\n             rewrite Permutation_app_comm. apply incl_appr'.\n             unfold idty. rewrite map_app. apply incl_appr, incl_refl.\n          -- solve_forall; simpl in *.\n             solve_incl. rewrite <- app_assoc. apply incl_appr'.\n             unfold idty. rewrite map_app. apply incl_app; [repeat solve_incl|].\n             apply incl_app; [apply incl_appr|apply incl_appl]...\n             apply map_bind2_unnest_exp_fresh_incl in Hnorm.\n             assert (incl (fresh_ins es) (st_anns x7)) by (repeat (etransitivity; eauto)).\n             eapply incl_map...\n        * simpl. rewrite app_nil_r.\n          eapply idents_for_anns'_incl_ty in H3.\n          clear - H3. solve_forall; simpl.\n          apply in_or_app, or_intror, H3. unfold idty. simpl_In.\n          exists (i, (t, (c, o))); auto.\n      + apply Forall_app; split. solve_forall; repeat solve_incl.\n        eapply unnest_noops_exps_wt with (G:=G) (vars:=vars) in H2 as (?&?); eauto.\n        2:eapply map_bind2_wt in Hnorm as (?&?); eauto; try solve_map_bind2.\n        solve_forall; repeat solve_incl.\n    - (* app (reset) *)\n      do 6 inv_bind.\n      assert (st_follows x4 x7) as Hfollows.\n      { eapply (unnest_reset_st_follows _ _ (Some r)) in H3; eauto. }\n      assert (Hs:=H3). apply unnest_reset_Some in Hs as [er' ?]; subst.\n      eapply (unnest_reset_wt _ _ (Some r)) in H3 as [Hwt2 [Hwt2' Hwt2'']]; simpl...\n      2:(intros; eapply H in H12; eauto).\n      1,2,4:repeat inv_bind. 2,3:repeat solve_incl.\n      2:(eapply (unnest_reset_fresh_incl _ (Some r)) in H3; simpl; eauto;\n         intros; eapply unnest_exp_fresh_incl; eauto).\n\n      assert (Hnorm:=H1). eapply map_bind2_wt with (G0:=G) (vars0:=vars++st_tys x1) in H1 as [Hwt1 Hwt1']...\n      2:solve_map_bind2. clear H0.\n\n      assert (length (find_node_incks G f) = length (concat x5)) as Hlen1.\n      { unfold find_node_incks. rewrite H6.\n        eapply Forall2_length in H7. rewrite map_length.\n        eapply map_bind2_unnest_exp_length in Hnorm; eauto. rewrite length_typesof_annots in H7.\n        congruence. }\n      assert (Forall (fun e : exp => numstreams e = 1) (concat x5)) as Hnum.\n      { eapply map_bind2_unnest_exp_numstreams; eauto. }\n\n      split; [|constructor]; repeat rewrite Forall_app; repeat split.\n      4,6:solve_forall; repeat solve_incl.\n      + specialize (idents_for_anns'_incl_ty _ _ _ _ H4) as Hincl.\n        eapply idents_for_anns'_wt with (G:=G) (vars:=vars) in H4... 1:solve_forall; repeat solve_incl.\n        solve_forall; simpl in *...\n        solve_incl. unfold idty. rewrite map_app, <- app_assoc.\n        apply incl_appr', incl_app; [repeat solve_incl|apply incl_app;[apply incl_appr|apply incl_appl]].\n        * eapply map_bind2_unnest_exp_fresh_incl in Hnorm.\n          unfold st_tys, idty in *. eapply incl_map; eauto.\n          assert (incl (st_anns x1) (st_anns x4)) by repeat solve_incl.\n          do 2 etransitivity...\n        * eapply idents_for_anns'_anon_streams_incl, incl_map in H4.\n          etransitivity. eapply H4.\n          replace (map _ (without_names' x8)) with (map (fun xtc => (fst xtc, fst (snd xtc))) x8); auto.\n          unfold without_names'; rewrite map_map; simpl.\n          apply map_ext; intros [? [? [? ?]]]; auto.\n      + repeat econstructor; eauto.\n        * eapply unnest_noops_exps_wt with (G:=G) (vars:=vars) in H2 as (?&?); eauto.\n          solve_forall; repeat solve_incl.\n        * erewrite unnest_noops_exps_typesof, map_bind2_unnest_exp_typesof; eauto.\n        * eapply idents_for_anns'_values in H4. congruence.\n        * eapply idents_for_anns'_wt_nclock with (vars:=vars) in H4.\n          -- rewrite Forall_map in H4. solve_forall.\n             solve_incl.\n             rewrite <- app_assoc. apply incl_appr'.\n             rewrite Permutation_app_comm. apply incl_appr'.\n             unfold idty. rewrite map_app. apply incl_appr, incl_refl.\n          -- solve_forall; simpl in *.\n             solve_incl. rewrite <- app_assoc. apply incl_appr'.\n             unfold idty. rewrite map_app. apply incl_app; [repeat solve_incl|].\n             apply incl_app; [apply incl_appr|apply incl_appl]...\n             apply map_bind2_unnest_exp_fresh_incl in Hnorm.\n             eapply incl_map...\n             assert (incl (st_anns x1) (st_anns x4)) by repeat solve_incl.\n             do 2 etransitivity...\n        * repeat solve_incl.\n      + simpl. rewrite app_nil_r.\n        eapply idents_for_anns'_incl_ty in H4.\n        clear - H4. solve_forall; simpl.\n        apply in_or_app, or_intror, H4. unfold idty. simpl_In.\n        exists (i, (t, (c, o))); auto.\n      + eapply unnest_noops_exps_wt with (G:=G) (vars:=vars) in H2 as (?&?); eauto.\n        solve_forall; repeat solve_incl.\n  Qed.\n\n  Corollary map_bind2_unnest_exp_wt : forall G vars is_control es es' eqs' st st',\n      Forall (wt_exp G (vars++st_tys st)) es ->\n      map_bind2 (unnest_exp G is_control) es st = (es', eqs', st') ->\n      Forall (wt_exp G (vars++st_tys st')) (concat es') /\\\n      Forall (wt_equation G (vars++st_tys st')) (concat eqs').\n  Proof.\n    intros * Hwt Hmap.\n    eapply map_bind2_wt in Hmap; solve_forall; eauto.\n    eapply unnest_exp_wt with (G:=G) (vars:=vars) in H1 as [? ?]; eauto.\n    split. 1,2:solve_forall. 1,2,3:repeat solve_incl.\n  Qed.\n\n  Corollary unnest_exps_wt : forall G vars es es' eqs' st st',\n      Forall (wt_exp G (vars++st_tys st)) es ->\n      unnest_exps G es st = (es', eqs', st') ->\n      Forall (wt_exp G (vars++st_tys st')) es' /\\\n      Forall (wt_equation G (vars++st_tys st')) eqs'.\n  Proof.\n    intros * Hwt Hmap.\n    unfold unnest_exps in Hmap; repeat inv_bind.\n    eapply map_bind2_unnest_exp_wt in H; eauto.\n  Qed.\n\n  Fact unnest_rhs_wt : forall G vars e es' eqs' st st',\n      wt_exp G (vars++st_tys st) e ->\n      unnest_rhs G e st = (es', eqs', st') ->\n      Forall (wt_exp G (vars++st_tys st')) es' /\\\n      Forall (wt_equation G (vars++st_tys st')) eqs'.\n  Proof with eauto.\n    intros * Hwt Hnorm.\n    destruct e; unfold unnest_rhs in Hnorm;\n      try (solve [eapply unnest_exp_wt in Hnorm; eauto]); inv Hwt.\n    - (* fby *)\n      repeat inv_bind.\n      assert (Hnorm1:=H). eapply unnest_exps_wt in H as [Hwt1 Hwt1']...\n      assert (Hnorm2:=H0). eapply unnest_exps_wt with (G:=G) (vars:=vars) in H0 as [Hwt2 Hwt2']...\n      2:solve_forall; repeat solve_incl.\n      rewrite Forall_app; repeat split... 2:solve_forall; repeat solve_incl.\n      eapply unnest_fby_wt_exp.\n      1,2,3:solve_forall; repeat solve_incl.\n      + unfold unnest_exps in Hnorm1; repeat inv_bind.\n        eapply map_bind2_unnest_exp_typesof'' in H... congruence.\n      + unfold unnest_exps in Hnorm2; repeat inv_bind.\n        eapply map_bind2_unnest_exp_typesof'' in H... congruence.\n    - (* arrow *)\n      repeat inv_bind.\n      assert (Hnorm1:=H). eapply unnest_exps_wt in H as [Hwt1 Hwt1']...\n      assert (Hnorm2:=H0). eapply unnest_exps_wt with (G:=G) (vars:=vars) in H0 as [Hwt2 Hwt2']...\n      2:solve_forall; repeat solve_incl.\n      rewrite Forall_app; repeat split... 2:solve_forall; repeat solve_incl.\n      eapply unnest_arrow_wt_exp.\n      1,2,3:solve_forall; repeat solve_incl.\n      + unfold unnest_exps in Hnorm1; repeat inv_bind.\n        eapply map_bind2_unnest_exp_typesof'' in H... congruence.\n      + unfold unnest_exps in Hnorm2; repeat inv_bind.\n        eapply map_bind2_unnest_exp_typesof'' in H... congruence.\n    - (* app *)\n      repeat inv_bind.\n      rewrite app_nil_r.\n      assert (Hnorm:=H). eapply unnest_exps_wt with (G:=G) (vars:=vars) in H as [Hwt1 Hwt1']...\n\n      assert (length (find_node_incks G i) = length x) as Hlen1.\n      { unfold find_node_incks. rewrite H4.\n        eapply Forall2_length in H5. rewrite map_length.\n        eapply unnest_exps_length in Hnorm; eauto. rewrite length_typesof_annots in H5.\n        congruence. }\n      assert (Forall (fun e : exp => numstreams e = 1) x) as Hnum.\n      { eapply unnest_exps_numstreams; eauto. }\n\n      split; auto.\n      repeat econstructor; eauto.\n      + eapply unnest_noops_exps_wt; eauto.\n      + erewrite unnest_noops_exps_typesof, unnest_exps_typesof; eauto.\n      + solve_forall; simpl. solve_incl.\n        repeat rewrite <- app_assoc.\n        apply incl_appr', incl_app.\n        * apply incl_appl. repeat solve_incl.\n        * unfold st_tys. rewrite <- idty_app.\n          apply incl_map. apply incl_app; [|repeat solve_incl].\n          apply incl_appl. apply unnest_exps_fresh_incl in Hnorm; eauto.\n          etransitivity; eauto.\n      + rewrite Forall_app; split. solve_forall; repeat solve_incl.\n        eapply unnest_noops_exps_wt; eauto.\n    - (* app (reset) *)\n      do 5 inv_bind.\n      assert (st_follows st x4) as Hfollows1 by repeat solve_st_follows.\n      assert (st_follows x4 st') as Hfollows2.\n      { eapply (unnest_reset_st_follows _ _ (Some r)) in H1; eauto. }\n      assert (Hs:=H1). eapply unnest_reset_Some in Hs as [er' ?]; subst.\n      apply (unnest_reset_wt G vars (Some r)) in H1 as [Hwt2 [Hwt2' Hwt2'']]; simpl...\n      2:(intros; eapply unnest_exp_wt in H2; eauto).\n      1,2,4:repeat inv_bind. 2,3:repeat solve_incl.\n      2:(eapply (unnest_reset_fresh_incl _ (Some r)) in H1; simpl; eauto;\n         intros; eapply unnest_exp_fresh_incl in H2; eauto).\n\n      assert (Hnorm:=H). eapply unnest_exps_wt in H as [Hwt1 Hwt1']; eauto.\n      rewrite Forall_app.\n\n      assert (length (find_node_incks G i) = length x) as Hlen1.\n      { unfold find_node_incks. rewrite H4.\n        eapply Forall2_length in H5. rewrite map_length.\n        eapply unnest_exps_length in Hnorm; eauto. rewrite length_typesof_annots in H5.\n        congruence. }\n      assert (Forall (fun e : exp => numstreams e = 1) x) as Hnum.\n      { eapply unnest_exps_numstreams; eauto. }\n\n      repeat split; auto.\n      2:solve_forall; repeat solve_incl.\n      repeat constructor.\n      repeat econstructor; eauto.\n      + eapply unnest_noops_exps_wt in H0 as (?&?); eauto.\n        solve_forall; repeat solve_incl.\n      + erewrite unnest_noops_exps_typesof, unnest_exps_typesof; eauto.\n      + eapply unnest_exps_fresh_incl in Hnorm.\n        solve_forall; solve_incl.\n        repeat rewrite idty_app; repeat rewrite <- app_assoc.\n        repeat apply incl_app; auto.\n        1,2:apply incl_appr, incl_appl; repeat solve_incl.\n        unfold st_tys, idty; rewrite incl_map; do 2 etransitivity...\n        eapply st_follows_incl; eauto. etransitivity; eauto.\n      + apply Forall_app; split. 2:solve_forall; repeat solve_incl.\n        eapply unnest_noops_exps_wt in H0 as (?&?); eauto.\n        solve_forall; repeat solve_incl.\n  Qed.\n\n  Corollary unnest_rhss_wt : forall G vars es es' eqs' st st',\n      Forall (wt_exp G (vars++st_tys st)) es ->\n      unnest_rhss G es st = (es', eqs', st') ->\n      Forall (wt_exp G (vars++st_tys st')) es' /\\\n      Forall (wt_equation G (vars++st_tys st')) eqs'.\n  Proof with eauto.\n    intros * Hwt Hnorm.\n    unfold unnest_rhss in Hnorm; repeat inv_bind.\n    eapply map_bind2_wt in H...\n    solve_forall.\n    eapply unnest_rhs_wt with (G:=G) (vars:=vars) in H2 as [? ?]...\n    split. 1,2:solve_forall. 1,2,3:repeat solve_incl.\n  Qed.\n\n  Fact unnest_equation_wt_eq : forall G vars eq eqs' st st',\n      wt_equation G (vars++st_tys st) eq ->\n      unnest_equation G eq st = (eqs', st') ->\n      Forall (wt_equation G (vars++st_tys st')) eqs'.\n  Proof with eauto.\n    intros * Hwt Hnorm.\n    destruct eq as [xs es]; simpl in Hnorm.\n    repeat inv_bind. destruct Hwt.\n    assert (Hnorm:=H). eapply unnest_rhss_wt in H as [Hwt Hwt']...\n    apply Forall_app. split; eauto.\n    assert (st_follows st st') as Hfollows by eauto.\n    eapply unnest_rhss_typesof in Hnorm...\n    rewrite <- Hnorm in H1.\n    clear Hnorm. revert xs H1.\n    induction x; intros xs H1; constructor; simpl in H1.\n    + inv Hwt. repeat constructor...\n      simpl. rewrite app_nil_r.\n      repeat rewrite_Forall_forall.\n      * rewrite app_length in H.\n        rewrite firstn_length. rewrite H.\n        rewrite length_typeof_numstreams.\n        apply Nat.min_l. omega.\n      * rewrite firstn_length in H2.\n        rewrite PeanoNat.Nat.min_glb_lt_iff in H2; destruct H2 as [Hlen1 Hlen2].\n        specialize (H1 a0 b _ _ _ Hlen2 eq_refl eq_refl).\n        rewrite app_nth1 in H1. 2: rewrite length_typeof_numstreams.\n        rewrite nth_firstn_1. 2,3:eauto.\n        rewrite in_app_iff in *. destruct H1; auto.\n        right. eapply st_follows_tys_incl...\n    + inv Hwt. apply IHx...\n      repeat rewrite_Forall_forall.\n      * rewrite app_length in H.\n        rewrite skipn_length. rewrite H.\n        rewrite length_typeof_numstreams. omega.\n      * rewrite skipn_length in H2.\n        rewrite nth_skipn.\n        assert (n + numstreams a < length xs) as Hlen by omega.\n        specialize (H1 a0 b _ _ _ Hlen eq_refl eq_refl).\n        rewrite app_nth2 in H1. 2: rewrite length_typeof_numstreams; omega.\n        rewrite length_typeof_numstreams in H1.\n        replace (n + numstreams a - numstreams a) with n in H1 by omega...\n  Qed.\n\n  Corollary unnest_equations_wt_eq : forall G vars eqs eqs' st st',\n      Forall (wt_equation G (vars++st_tys st)) eqs ->\n      unnest_equations G eqs st = (eqs', st') ->\n      Forall (wt_equation G (vars++st_tys st')) eqs'.\n  Proof with eauto.\n    induction eqs; intros * Hwt Hnorm;\n      unfold unnest_equations in Hnorm;\n      repeat inv_bind; auto.\n    inv Hwt. apply Forall_app. split.\n    - eapply unnest_equation_wt_eq in H...\n      solve_forall; repeat solve_incl.\n    - assert (unnest_equations G eqs x1 = (concat x2, st')) as Hnorm.\n      { unfold unnest_equations; repeat inv_bind. repeat eexists; eauto. inv_bind; eauto. }\n      eapply IHeqs in Hnorm...\n      solve_forall; repeat solve_incl.\n  Qed.\n\n  (** ** Preservation of wt_clock *)\n\n  Definition st_clocks (st : fresh_st (Op.type * clock)) : list clock :=\n    map (fun '(_, (_, cl)) => cl) (st_anns st).\n  Definition st_clocks' (st : fresh_st (Op.type * clock * bool)) : list clock :=\n    map (fun '(_, (_, cl, _)) => cl) (st_anns st).\n\n  Fact fresh_ident_wt_clock : forall pref vars ty cl id st st',\n      Forall (wt_clock vars) (st_clocks st) ->\n      wt_clock vars cl ->\n      fresh_ident pref (ty, cl) st = (id, st') ->\n      Forall (wt_clock vars) (st_clocks st').\n  Proof.\n    intros * Hclocks Hwt Hfresh.\n    apply fresh_ident_anns in Hfresh.\n    unfold st_clocks in *. setoid_rewrite Hfresh; simpl.\n    constructor; auto.\n  Qed.\n\n  Corollary idents_for_anns_wt_clock : forall vars anns ids st st',\n      Forall (wt_clock vars) (st_clocks st) ->\n      Forall (wt_nclock vars) (map snd anns) ->\n      idents_for_anns anns st = (ids, st') ->\n      Forall (wt_clock vars) (st_clocks st').\n  Proof.\n    induction anns; intros ids st st' Hclocks Hwt Hidents;\n      repeat inv_bind.\n    - assumption.\n    - inv Hwt. destruct a as [ty [cl ?]]. repeat inv_bind.\n      eapply IHanns in H0; eauto.\n      inv H1.\n      eapply fresh_ident_wt_clock; eauto.\n  Qed.\n\n  Fact reuse_ident_wt_clock : forall vars ty cl id st st',\n      Forall (wt_clock vars) (st_clocks st) ->\n      wt_clock vars cl ->\n      reuse_ident id (ty, cl) st = (tt, st') ->\n      Forall (wt_clock vars) (st_clocks st').\n  Proof.\n    intros * Hclocks Hwt Hfresh.\n    apply reuse_ident_anns in Hfresh.\n    unfold st_clocks in *. setoid_rewrite Hfresh; simpl.\n    constructor; auto.\n  Qed.\n\n  Corollary idents_for_anns'_wt_clock : forall vars anns ids st st',\n      Forall (wt_clock vars) (st_clocks st) ->\n      Forall (wt_nclock vars) (map snd anns) ->\n      idents_for_anns' anns st = (ids, st') ->\n      Forall (wt_clock vars) (st_clocks st').\n  Proof.\n    induction anns; intros ids st st' Hclocks Hwt Hidents;\n      repeat inv_bind.\n    - assumption.\n    - inv Hwt. destruct a as [ty [cl ?]]. destruct o; repeat inv_bind.\n      + eapply IHanns in H0; eauto.\n        inv H1.\n        destruct x. eapply reuse_ident_wt_clock; eauto.\n      + eapply IHanns in H0; eauto.\n        inv H1.\n        eapply fresh_ident_wt_clock; eauto.\n  Qed.\n\n  Fact map_bind2_wt_clock {A A1 A2 : Type} :\n    forall vars (k : A -> Unnesting.FreshAnn (A1 * A2)) a a1s a2s st st',\n      Forall (wt_clock (vars++st_tys st)) (st_clocks st) ->\n      map_bind2 k a st = (a1s, a2s, st') ->\n      (forall st st' a es a2s, k a st = (es, a2s, st') -> st_follows st st') ->\n      Forall (fun a => forall a1s a2s st0 st0',\n                  Forall (wt_clock (vars++st_tys st0)) (st_clocks st0) ->\n                  k a st0 = (a1s, a2s, st0') ->\n                  st_follows st st0 ->\n                  st_follows st0' st' ->\n                  Forall (wt_clock (vars++st_tys st0')) (st_clocks st0')) a ->\n      Forall (wt_clock (vars++st_tys st')) (st_clocks st').\n  Proof with eauto.\n    induction a; intros a1s a2s st st' Hclocks Hmap Hfollows Hf;\n      repeat inv_bind...\n    inv Hf.\n    specialize (H3 _ _ _ _ Hclocks H).\n    eapply IHa in H3...\n    - reflexivity.\n    - eapply map_bind2_st_follows...\n      solve_forall...\n    - solve_forall.\n      eapply H2 in H5...\n      etransitivity...\n  Qed.\n\n  Fact unnest_reset_wt_clock : forall G vars e e' eqs' st st',\n      LiftO True (fun e => forall st' es' eqs',\n                   unnest_exp G true e st = (es', eqs', st') ->\n                   Forall (wt_clock (vars++st_tys st')) (st_clocks st')) e ->\n      LiftO True (wt_exp G (vars++st_tys st)) e ->\n      Forall (wt_clock (vars++st_tys st)) (st_clocks st) ->\n      unnest_reset (unnest_exp G true) e st = (e', eqs', st') ->\n      Forall (wt_clock (vars++st_tys st')) (st_clocks st').\n  Proof with eauto.\n    intros * Hkck Hwt Hclocks Hnorm.\n    unnest_reset_spec; simpl in *; eauto.\n    assert (Forall (wt_clock (vars++st_tys st')) (clockof e0)) as Hwtck.\n    { eapply wt_exp_clockof in Hwt.\n      assert (Hk:=Hk0). eapply unnest_exp_fresh_incl in Hk0.\n      solve_forall; solve_incl. rewrite <- app_assoc.\n      apply incl_app; [repeat solve_incl|apply incl_appr, incl_app].\n      repeat solve_incl. unfold st_tys, idty. apply incl_map.\n      etransitivity; eauto. }\n    eapply fresh_ident_wt_clock in Hfresh...\n    - eapply Hkck in Hk0.\n      solve_forall; repeat solve_incl.\n    - assert (Hk:=Hk0). eapply unnest_exp_annot in Hk0; eauto.\n      rewrite clockof_annot, <- Hk0 in Hwtck.\n      destruct l; simpl in *. 1:inv Hhd; constructor.\n      destruct (annot e); simpl in *. inv Hhd; constructor.\n      subst; simpl in *.\n      inv Hwtck. repeat solve_incl.\n  Qed.\n\n  Lemma unnest_noops_exps_wt_clock : forall G vars cks es es' eqs' st st' ,\n      length es = length cks ->\n      Forall normalized_lexp es ->\n      Forall (fun e => numstreams e = 1) es ->\n      Forall (wt_exp G (vars++st_tys st)) es ->\n      Forall (wt_clock (vars++st_tys st)) (st_clocks st) ->\n      unnest_noops_exps cks es st = (es', eqs', st') ->\n      Forall (wt_clock (vars++st_tys st')) (st_clocks st').\n  Proof.\n    unfold unnest_noops_exps.\n    induction cks; intros * Hlen Hnormed Hnum Hwt1 Hwt2 Hunt; repeat inv_bind; simpl; auto.\n    destruct es; simpl in *; inv Hlen; repeat inv_bind.\n    inv Hnormed. inv Hnum. inv Hwt1.\n    eapply IHcks with (st:=x2); eauto.\n    solve_forall; repeat solve_incl; eapply unnest_noops_exp_st_follows in H; eauto.\n    2:repeat inv_bind; repeat eexists; eauto; inv_bind; eauto.\n    clear H0 H1.\n    rewrite <-length_annot_numstreams in H6. singleton_length. destruct p as (?&?&?).\n    unfold unnest_noops_exp in H. rewrite Hsingl in H; simpl in H.\n    destruct (is_noops_exp a e); simpl in *; repeat inv_bind; auto.\n    eapply fresh_ident_wt_clock; eauto. solve_forall; repeat solve_incl.\n    eapply wt_exp_clockof in H8.\n    rewrite normalized_lexp_no_fresh in H8; auto. simpl in H8; rewrite app_nil_r in H8.\n    rewrite clockof_annot, Hsingl in H8; inv H8.\n    repeat solve_incl.\n  Qed.\n\n  Fact unnest_exp_wt_clock : forall G vars e is_control es' eqs' st st',\n      wt_exp G (vars++st_tys st) e ->\n      Forall (wt_clock (vars++st_tys st)) (st_clocks st) ->\n      unnest_exp G is_control e st = (es', eqs', st') ->\n      Forall (wt_clock (vars++st_tys st')) (st_clocks st').\n  Proof with eauto.\n    induction e using exp_ind2; intros is_control es' eqs' st st' Hwt Hclocks Hnorm;\n      inv Hwt. 1-10: repeat inv_bind; eauto.\n    Ltac solve_map_bind2' :=\n      solve_forall;\n      match goal with\n      | Hnorm : unnest_exp _ _ _ _ = _, Hf : forall (_ : bool), _ |- Forall _ ?l =>\n        eapply Hf in Hnorm; eauto\n      end; repeat solve_incl.\n    - (* binop *)\n      eapply IHe2 in H0...\n      repeat solve_incl.\n    - (* fby *)\n      eapply idents_for_anns_wt_clock in H3... 2:solve_forall; repeat solve_incl.\n      eapply map_bind2_wt_clock with (vars0:=vars) in H2... solve_forall; repeat solve_incl.\n      eapply map_bind2_wt_clock in H1...\n      1,2:solve_map_bind2'.\n    - (* arrow *)\n      eapply idents_for_anns_wt_clock in H3... 2:solve_forall; repeat solve_incl.\n      eapply map_bind2_wt_clock with (vars0:=vars) in H2... solve_forall; repeat solve_incl.\n      eapply map_bind2_wt_clock in H1...\n      1,2:solve_map_bind2'.\n    - (* when *)\n      eapply map_bind2_wt_clock in H0...\n      rewrite Forall_forall in *; intros...\n      eapply H in H3... eapply H4 in H1... repeat solve_incl.\n    - (* merge *)\n      eapply Forall_Forall in H; eauto. clear H5. eapply Forall_Forall in H0; eauto. clear H6.\n      destruct is_control; repeat inv_bind.\n      + eapply map_bind2_wt_clock in H2...\n        eapply map_bind2_wt_clock in H1... 1,2:solve_map_bind2'.\n      + eapply idents_for_anns_wt_clock in H3...\n        2:{ rewrite map_map; simpl. solve_forall. repeat solve_incl. }\n        eapply map_bind2_wt_clock with (vars0:=vars) in H2... 3:solve_map_bind2'. solve_forall; repeat solve_incl.\n        eapply map_bind2_wt_clock in H1... solve_map_bind2'.\n    - (* ite *)\n      eapply Forall_Forall in H; eauto. clear H6. eapply Forall_Forall in H0; eauto. clear H7.\n      destruct is_control; repeat inv_bind.\n      + eapply map_bind2_wt_clock in H3...\n        eapply map_bind2_wt_clock in H2... 1,2:solve_map_bind2'.\n      + eapply idents_for_anns_wt_clock in H4...\n        2:{ rewrite map_map; simpl. solve_forall. repeat solve_incl. }\n        eapply map_bind2_wt_clock with (vars0:=vars) in H3... 3:solve_map_bind2'. solve_forall; repeat solve_incl.\n        eapply map_bind2_wt_clock in H2... solve_map_bind2'.\n    - (* app *)\n      eapply Forall_Forall in H0; eauto.\n      assert (st_follows x1 st') as Hfollows by repeat solve_st_follows.\n      assert (incl (fresh_ins es) (st_anns x1)) as Hincl by (apply map_bind2_unnest_exp_fresh_incl in H1; auto).\n      eapply unnest_noops_exps_wt_clock in H2; eauto.\n      2:{ unfold find_node_incks. rewrite H6.\n          eapply Forall2_length in H7. rewrite map_length.\n          eapply map_bind2_unnest_exp_length in H1; eauto. rewrite length_typesof_annots in H7.\n          congruence. }\n      2:eapply map_bind2_unnest_exp_numstreams; eauto.\n      2:eapply map_bind2_unnest_exp_wt; eauto.\n      2:eapply map_bind2_wt_clock; eauto; solve_map_bind2'.\n      eapply idents_for_anns'_wt_clock in H3...\n      solve_forall; repeat solve_incl.\n      rewrite Forall_map. solve_forall; solve_incl.\n      rewrite <- app_assoc. apply incl_appr', incl_app; repeat solve_incl.\n      unfold st_tys, idty; rewrite map_app; apply incl_app; apply incl_map.\n      + etransitivity...\n      + apply idents_for_anns'_fresh_incl in H3...\n    - (* app (reset) *)\n      do 6 inv_bind.\n      assert (st_follows x4 x7) as Hfollows.\n      { clear - H3. eapply (unnest_reset_st_follows _ _ (Some r)) in H3; eauto. }\n      assert (Forall (wt_clock (vars ++ st_tys x1)) (st_clocks x1)) as Hck1.\n      { repeat inv_bind. eapply map_bind2_wt_clock in H1... solve_map_bind2'. }\n      assert (Forall (wt_clock (vars ++ st_tys x4)) (st_clocks x4)) as Hck2.\n      { clear H3. repeat inv_bind.\n        eapply unnest_noops_exps_wt_clock in H2; eauto.\n        + unfold find_node_incks. rewrite H6.\n          eapply Forall2_length in H7. rewrite map_length.\n          eapply map_bind2_unnest_exp_length in H1; eauto. rewrite length_typesof_annots in H7.\n           congruence.\n        + eapply map_bind2_unnest_exp_numstreams; eauto.\n        + eapply map_bind2_unnest_exp_wt; eauto.\n      }\n\n      eapply (unnest_reset_wt_clock G vars (Some r)) in H3; simpl; eauto.\n      2-4:clear H3. 1-4:repeat inv_bind.\n      2:intros; eapply H in H3; eauto. 2,3:repeat solve_incl.\n      eapply idents_for_anns'_wt_clock in H4...\n      solve_forall; repeat solve_incl.\n      rewrite Forall_map. solve_forall; solve_incl.\n      rewrite <- app_assoc. apply incl_appr', incl_app; repeat solve_incl.\n      unfold st_tys, idty; apply incl_map, incl_app.\n      + eapply map_bind2_unnest_exp_fresh_incl in H1.\n        etransitivity... repeat solve_incl.\n      + apply idents_for_anns'_fresh_incl in H4...\n  Qed.\n\n  Corollary unnest_exps_wt_clock : forall G vars es es' eqs' st st',\n      Forall (wt_exp G (vars++st_tys st)) es ->\n      Forall (wt_clock (vars++st_tys st)) (st_clocks st) ->\n      unnest_exps G es st = (es', eqs', st') ->\n      Forall (wt_clock (vars++st_tys st')) (st_clocks st').\n  Proof.\n    intros G vars es es' eqs' st st' Hwt Hclocks Hnorm.\n    unfold unnest_exps in Hnorm. repeat inv_bind.\n    eapply map_bind2_wt_clock in H; eauto.\n    solve_forall.\n    assert (st_follows st0 st0') by eauto.\n    eapply unnest_exp_wt_clock with (G:=G) (vars:=vars) in H3; repeat solve_incl.\n    - solve_forall; solve_incl.\n    - solve_forall; solve_incl.\n  Qed.\n\n  Corollary unnest_rhs_wt_clock : forall G vars e es' eqs' st st',\n      wt_exp G (vars++st_tys st) e ->\n      Forall (wt_clock (vars++st_tys st)) (st_clocks st) ->\n      unnest_rhs G e st = (es', eqs', st') ->\n      Forall (wt_clock (vars++st_tys st')) (st_clocks st').\n  Proof with eauto.\n    intros * Hwt Hclocks Hnorm.\n    destruct e; unfold unnest_rhs in Hnorm;\n      try eapply unnest_exp_wt_clock in Hnorm; eauto;\n        inv Hwt.\n    - (* fby *)\n      repeat inv_bind.\n      assert (st_follows st x1) by repeat solve_st_follows. assert (st_follows st st') by repeat solve_st_follows.\n      eapply unnest_exps_wt_clock with (G:=G) in H...\n      eapply unnest_exps_wt_clock with (G:=G) in H0...\n      solve_forall; do 3 solve_incl; apply st_follows_tys_incl; auto.\n    - (* arrow *)\n      repeat inv_bind.\n      assert (st_follows st x1) by repeat solve_st_follows. assert (st_follows st st') by repeat solve_st_follows.\n      eapply unnest_exps_wt_clock with (G:=G) in H...\n      eapply unnest_exps_wt_clock with (G:=G) in H0...\n      solve_forall; do 3 solve_incl; apply st_follows_tys_incl; auto.\n    - (* app *)\n      repeat inv_bind.\n      assert (Hnorm:=H). eapply unnest_exps_wt_clock with (G:=G) in H...\n      eapply unnest_noops_exps_wt_clock in H0...\n      + unfold find_node_incks. rewrite H4.\n        eapply Forall2_length in H5. rewrite map_length.\n        eapply unnest_exps_length in Hnorm; eauto. rewrite length_typesof_annots in H5.\n        congruence.\n      + eapply unnest_exps_numstreams; eauto.\n      + eapply unnest_exps_wt; eauto.\n    - (* app (reset) *)\n      do 5 inv_bind.\n      assert (st_follows x4 st') as Hfollows.\n      { clear - H1. eapply (unnest_reset_st_follows _ _ (Some r)) in H1; eauto. }\n      assert (Forall (wt_clock (vars ++ st_tys x1)) (st_clocks x1)) as Hck1.\n      { repeat inv_bind. eapply unnest_exps_wt_clock in H... }\n      assert (Forall (wt_clock (vars ++ st_tys x4)) (st_clocks x4)) as Hck2.\n      { clear H1. repeat inv_bind.\n        eapply unnest_noops_exps_wt_clock in H0; eauto.\n        + unfold find_node_incks. rewrite H4.\n          eapply Forall2_length in H5. rewrite map_length.\n          eapply unnest_exps_length in H; eauto. rewrite length_typesof_annots in H5.\n          congruence.\n        + eapply unnest_exps_numstreams; eauto.\n        + eapply unnest_exps_wt; eauto.\n      }\n      eapply (unnest_reset_wt_clock G vars (Some r)) in H1; simpl; eauto.\n      intros; eapply unnest_exp_wt_clock with (G:=G) in H2; eauto.\n      1,2:repeat solve_incl.\n  Qed.\n\n  Corollary unnest_rhss_wt_clock : forall G vars es es' eqs' st st',\n      Forall (wt_exp G (vars++st_tys st)) es ->\n      Forall (wt_clock (vars++st_tys st)) (st_clocks st) ->\n      unnest_rhss G es st = (es', eqs', st') ->\n      Forall (wt_clock (vars++st_tys st')) (st_clocks st').\n  Proof.\n    intros * Hwt Hclocks Hnorm.\n    unfold unnest_rhss in Hnorm. repeat inv_bind.\n    eapply map_bind2_wt_clock in H; eauto.\n    solve_forall. eapply unnest_rhs_wt_clock with (G:=G) in H3; eauto.\n    repeat solve_incl.\n  Qed.\n\n  Fact unnest_equation_wt_clock : forall G vars eq eqs' st st',\n      wt_equation G (vars++st_tys st) eq ->\n      Forall (wt_clock (vars++st_tys st)) (st_clocks st) ->\n      unnest_equation G eq st = (eqs', st') ->\n      Forall (wt_clock (vars++st_tys st')) (st_clocks st').\n  Proof.\n    intros * Hwt Hclocks Hnorm.\n    destruct eq; repeat inv_bind.\n    destruct Hwt.\n    eapply unnest_rhss_wt_clock in H; eauto.\n  Qed.\n\n  Corollary unnest_equations_wt_clock : forall G vars eqs eqs' st st',\n      Forall (wt_equation G (vars++st_tys st)) eqs ->\n      Forall (wt_clock (vars++st_tys st)) (st_clocks st) ->\n      unnest_equations G eqs st = (eqs', st') ->\n      Forall (wt_clock (vars++st_tys st')) (st_clocks st').\n  Proof.\n    induction eqs; intros * Hwt Hclocks Hnorm;\n      unfold unnest_equations in Hnorm; repeat inv_bind.\n    - assumption.\n    - inv Hwt.\n      assert (st_follows st x1) by repeat solve_st_follows.\n      eapply unnest_equation_wt_clock in H; eauto.\n      assert (unnest_equations G eqs x1 = (concat x2, st')) as Hnorm.\n      { unfold unnest_equations; repeat inv_bind.\n        repeat eexists; eauto. inv_bind; auto. }\n      eapply IHeqs in Hnorm; eauto.\n      solve_forall; repeat solve_incl.\n  Qed.\n\n  Lemma unnest_node_wt : forall G n Hwl Hpref,\n      wt_node G n ->\n      wt_node G (unnest_node G n Hwl Hpref).\n  Proof.\n    intros * [Hclin [Hclout [Hclvars Heq]]].\n    unfold unnest_node.\n    repeat constructor; simpl; auto.\n    - unfold wt_clocks in *.\n      apply Forall_app. split.\n      + solve_forall. unfold idty in *.\n        solve_incl. repeat rewrite map_app. repeat solve_incl.\n      + remember (unnest_equations _ _ _) as res.\n        destruct res as [eqs st']. symmetry in Heqres.\n        eapply unnest_equations_wt_clock with (G:=G) in Heqres; eauto.\n        * simpl. unfold st_clocks in Heqres.\n          unfold idty. solve_forall.\n          repeat solve_incl.\n          repeat rewrite map_app, app_assoc.\n          eapply incl_appr'. reflexivity.\n        * unfold st_clocks. unfold st_tys. rewrite init_st_anns, app_nil_r.\n          repeat rewrite <- app_assoc. repeat rewrite <- map_app.\n          solve_forall; repeat solve_incl. apply incl_map, incl_appr'. rewrite Permutation_app_comm; auto.\n        * unfold st_clocks. rewrite init_st_anns; simpl; constructor.\n    - remember (unnest_equations _ _ _) as res.\n      destruct res as [eqs' st']; simpl.\n      symmetry in Heqres.\n      eapply unnest_equations_wt_eq with (G:=G) (vars:=(idty (n_in n ++ n_vars n ++ n_out n))) in Heqres; eauto.\n      + solve_forall; solve_incl.\n        unfold st_tys; rewrite <- idty_app. apply incl_map.\n        repeat rewrite <- app_assoc. apply incl_appr', incl_appr'.\n        rewrite Permutation_app_comm. reflexivity.\n      + solve_forall; repeat solve_incl.\n  Qed.\n\n  Lemma unnest_global_wt : forall G Hwl Hprefs,\n      wt_global G ->\n      wt_global (unnest_global G Hwl Hprefs).\n  Proof.\n    induction G; intros * Hwt; simpl; inv Hwt.\n    - constructor.\n    - constructor.\n      + eapply IHG; eauto.\n      + remember (unnest_node _ _) as n'. symmetry in Heqn'.\n        subst.\n        eapply iface_eq_wt_node. eapply unnest_global_eq; eauto.\n        eapply unnest_node_wt; eauto.\n      + eapply unnest_global_names; eauto.\n  Qed.\n\n  (** ** Preservation of wt through the second pass *)\n\n  Fact add_whens_typeof : forall e ty cl,\n      typeof e = [ty] ->\n      typeof (add_whens e ty cl) = [ty].\n  Proof.\n    induction cl; intro Hty; simpl; auto.\n  Qed.\n\n  Fact add_whens_wt_exp : forall G vars e ty cl e',\n      wt_exp G vars e ->\n      typeof e = [ty] ->\n      wt_clock vars cl ->\n      add_whens e ty cl = e' ->\n      wt_exp G vars e'.\n  Proof.\n    induction cl; intros e' Hwt Hty Hclock Hwhens; simpl in Hwhens; inv Hclock; subst.\n    - assumption.\n    - repeat constructor; simpl; auto.\n      rewrite app_nil_r.\n      rewrite add_whens_typeof; auto.\n  Qed.\n\n  Fact init_var_for_clock_wt_eq : forall G vars ck id eqs' st st',\n      wt_clock (vars++st_tys' st) ck ->\n      init_var_for_clock ck st = (id, eqs', st') ->\n      Forall (wt_equation G (vars++st_tys' st')) eqs'.\n  Proof with eauto.\n    intros * Hck Hinit.\n    unfold init_var_for_clock in Hinit. destruct (find _ _) eqn:Hfind.\n    - destruct p. inv Hinit. constructor.\n    - destruct (fresh_ident _ _) eqn:Hfresh. inv Hinit.\n      repeat constructor; simpl; repeat rewrite app_nil_r; auto.\n      1,2:eapply add_whens_wt_exp... 2,4,7:repeat solve_incl.\n      3,4:eapply add_whens_typeof.\n      1-4:simpl; f_equal.\n      1,4:rewrite Op.type_true_const. 3,4:rewrite Op.type_false_const. 1-4:reflexivity.\n      eapply fresh_ident_In in Hfresh.\n      eapply in_or_app. right. unfold st_tys', idty. rewrite map_map. simpl_In.\n      exists (id, (Op.bool_type, ck, true))...\n  Qed.\n\n  Fact fby_iteexp_wt_exp : forall G vars e0 e ty ck name e' eqs' st st',\n      wt_clock (vars++st_tys' st) ck ->\n      wt_exp G (vars++st_tys' st) e0 ->\n      wt_exp G (vars++st_tys' st) e ->\n      typeof e0 = [ty] ->\n      typeof e = [ty] ->\n      fby_iteexp e0 e (ty, (ck, name)) st = (e', eqs', st') ->\n      wt_exp G (vars++st_tys' st') e'.\n  Proof.\n    intros * Hwtc Hwt1 Hwt2 Hty1 Hty2 Hfby.\n    unfold fby_iteexp in Hfby; repeat inv_bind.\n    repeat constructor; simpl in *; try rewrite app_nil_r; auto.\n    2,3,5,6:repeat solve_incl; eapply init_var_for_clock_st_follows in H; repeat solve_st_follows.\n    1:(apply init_var_for_clock_In in H;\n         apply in_or_app, or_intror; unfold st_tys', idty;\n         simpl_In; exists (x, (Op.bool_type, ck)); split; auto;\n         simpl_In).\n    simpl in H.\n    exists (x, (Op.bool_type, ck, true)); split; auto.\n    eapply st_follows_incl; eauto.\n    1:(apply fresh_ident_In in H0;\n       apply in_or_app, or_intror; unfold st_tys', idty;\n       simpl_In; exists (x2, (ty, ck)); split; auto;\n       simpl_In; exists (x2, (ty, ck, false)); split; auto).\n  Qed.\n\n  Fact fby_iteexp_wt_eq : forall G vars e0 e ty ck name e' eqs' st st',\n      wt_clock (vars++st_tys' st) ck ->\n      wt_exp G (vars++st_tys' st) e0 ->\n      wt_exp G (vars++st_tys' st) e ->\n      typeof e0 = [ty] ->\n      typeof e = [ty] ->\n      fby_iteexp e0 e (ty, (ck, name)) st = (e', eqs', st') ->\n      Forall (wt_equation G (vars++st_tys' st')) eqs'.\n  Proof.\n    intros * Hwtc Hwt1 Hwt2 Hty1 Hty2 Hfby.\n    unfold fby_iteexp in Hfby; repeat inv_bind.\n    assert (wt_clock (vars ++ st_tys' st') ck) as Hwtck'.\n    { repeat solve_incl; eapply init_var_for_clock_st_follows in H; repeat solve_st_follows. }\n    constructor.\n    - repeat constructor; simpl; try rewrite app_nil_r; auto.\n      2:repeat solve_incl; eapply init_var_for_clock_st_follows in H; repeat solve_st_follows.\n      + eapply add_whens_wt_exp; eauto.\n        simpl. rewrite Op.type_init_type; auto.\n      + eapply add_whens_typeof.\n        simpl. rewrite Op.type_init_type; auto.\n      + apply fresh_ident_In in H0.\n        apply in_or_app, or_intror. unfold st_tys', idty.\n        simpl_In. exists (x2, (ty, ck)); split; auto.\n        simpl_In. exists (x2, (ty, ck, false)); split; auto.\n    - eapply init_var_for_clock_wt_eq with (G:=G) in H; eauto.\n      solve_forall. repeat solve_incl.\n  Qed.\n\n  Fact arrow_iteexp_wt_eq : forall G vars e0 e ty ck name e' eqs' st st',\n      wt_clock (vars++st_tys' st) ck ->\n      arrow_iteexp e0 e (ty, (ck, name)) st = (e', eqs', st') ->\n      Forall (wt_equation G (vars++st_tys' st')) eqs'.\n  Proof.\n    intros * Hwtc Hfby.\n    unfold arrow_iteexp in Hfby. repeat inv_bind.\n    eapply init_var_for_clock_wt_eq with (G:=G) in H; eauto.\n  Qed.\n\n  Fact fby_equation_wt_eq : forall G vars to_cut eq eqs' st st',\n      wt_equation G (vars++st_tys' st) eq ->\n      fby_equation to_cut eq st = (eqs', st') ->\n      Forall (wt_equation G (vars++st_tys' st')) eqs'.\n  Proof.\n    intros * Hwt Hfby.\n    inv_fby_equation Hfby to_cut eq.\n    - (* constant fby *)\n      destruct x2 as (ty&ck&name).\n      destruct (PS.mem x to_cut); repeat inv_bind; auto.\n      destruct Hwt as [Hwt Hin]. apply Forall_singl in Hwt. apply Forall2_singl in Hin.\n      eapply wt_exp_incl with (vars':=vars ++ st_tys' st') in Hwt. 2:repeat solve_incl.\n      repeat (constructor; auto).\n      3:repeat solve_incl.\n      + apply fresh_ident_In in H. apply in_or_app, or_intror.\n        unfold st_tys', idty. repeat simpl_In. exists (x2, (ty, ck)); split; auto.\n        repeat simpl_In. exists (x2, (ty, ck, false)); auto.\n      + inv Hwt.\n        apply Forall_singl in H7. inv H7; repeat solve_incl.\n      + apply fresh_ident_In in H. apply in_or_app, or_intror.\n        unfold st_tys', idty. repeat simpl_In. exists (x2, (ty, ck)); split; auto.\n        repeat simpl_In. exists (x2, (ty, ck, false)); auto.\n    - (* fby *)\n      destruct x2 as (ty&ck&name).\n      assert (st_follows st st') as Hfollows by (eapply fby_iteexp_st_follows with (ann:=(ty, (ck, name))) in H; eauto).\n      destruct Hwt as [Hwt Hins]. apply Forall_singl in Hwt. apply Forall2_singl in Hins.\n      inv Hwt.\n      simpl in *; rewrite app_nil_r in *.\n      apply Forall_singl in H3; apply Forall_singl in H4.\n      apply Forall_singl in H7; inv H7.\n      assert (Hwte:=H). eapply fby_iteexp_wt_exp in Hwte; eauto.\n      assert (Hty:=H). eapply (fby_iteexp_typeof _ _ (ty, (ck, name))) in Hty; eauto.\n      assert (Hwteq:=H). eapply fby_iteexp_wt_eq in Hwteq; eauto.\n      repeat constructor; auto.\n      simpl; rewrite app_nil_r, Hty. repeat constructor. repeat solve_incl.\n    - (* arrow *)\n      destruct x2 as [ty [ck name]].\n      destruct Hwt as [Hwt Hins]. apply Forall_singl in Hwt. apply Forall2_singl in Hins.\n      inv Hwt.\n      simpl in *; rewrite app_nil_r in *.\n      apply Forall_singl in H3; apply Forall_singl in H4.\n      apply Forall_singl in H7; inv H7.\n      assert (Hwte:=H). eapply arrow_iteexp_wt_eq in Hwte; eauto.\n      assert (st_follows st st') as Hfollows.\n      { repeat inv_bind. eapply init_var_for_clock_st_follows; eauto. }\n      repeat inv_bind.\n      repeat constructor; auto. 9:eapply Hwte.\n      2,3,4,7:repeat solve_incl.\n      2,3:simpl; rewrite app_nil_r; auto.\n      + eapply init_var_for_clock_In in H.\n        apply in_or_app, or_intror. unfold st_tys', idty. rewrite map_map.\n        simpl_In. exists (x2, (Op.bool_type, ck, true)); auto.\n      + assert (incl (vars ++ st_tys' st) (vars ++ st_tys' st')) by repeat solve_incl; eauto.\n  Qed.\n\n  Fact fby_equations_wt_eq : forall G vars to_cut eqs eqs' st st',\n      Forall (wt_equation G (vars++st_tys' st)) eqs ->\n      fby_equations to_cut eqs st = (eqs', st') ->\n      Forall (wt_equation G (vars++st_tys' st')) eqs'.\n  Proof.\n    induction eqs; intros * Hwt Hfby;\n      unfold fby_equations in *; repeat inv_bind; simpl; auto.\n    inv Hwt.\n    apply Forall_app; split.\n    - eapply fby_equation_wt_eq in H; eauto. solve_forall; repeat solve_incl.\n    - assert (fby_equations to_cut eqs x1 = (concat x2, st')) as Hnorm.\n      { unfold fby_equations. repeat inv_bind. repeat eexists; eauto.\n        inv_bind; auto. }\n      eapply IHeqs in Hnorm; eauto. solve_forall; repeat solve_incl; eauto.\n  Qed.\n\n  Fact fresh_ident_wt_clock' : forall pref vars ty cl b id st st',\n      Forall (wt_clock vars) (st_clocks' st) ->\n      wt_clock vars cl ->\n      fresh_ident pref (ty, cl, b) st = (id, st') ->\n      Forall (wt_clock vars) (st_clocks' st').\n  Proof.\n    intros * Hclocks Hwt Hfresh.\n    apply fresh_ident_anns in Hfresh.\n    unfold st_clocks' in *. rewrite Hfresh; simpl.\n    constructor; auto.\n  Qed.\n\n  Fact init_var_for_clock_wt_clock : forall vars ck x eqs' st st',\n      wt_clock (vars++st_tys' st) ck ->\n      Forall (wt_clock (vars ++ st_tys' st)) (st_clocks' st) ->\n      init_var_for_clock ck st = (x, eqs', st') ->\n      Forall (wt_clock (vars ++ st_tys' st')) (st_clocks' st').\n  Proof.\n    intros * Hwtc1 Hwtc2 Hfby.\n    unfold init_var_for_clock in Hfby. destruct (find _ _) eqn:Hfind.\n    - destruct p; inv Hfby. auto.\n    - destruct (fresh_ident _ _) eqn:Hfresh.\n      inv Hfby.\n      eapply fresh_ident_wt_clock' in Hfresh; eauto. solve_forall. 1,2:repeat solve_incl.\n  Qed.\n\n  Fact fby_iteexp_wt_clock : forall vars e0 e ty ck name e' eqs' st st',\n      wt_clock (vars++st_tys' st) ck ->\n      Forall (wt_clock (vars ++ st_tys' st)) (st_clocks' st) ->\n      fby_iteexp e0 e (ty, (ck, name)) st = (e', eqs', st') ->\n      Forall (wt_clock (vars ++ st_tys' st')) (st_clocks' st').\n  Proof.\n    intros * Hwtc1 Hwtc2 Hfby.\n    unfold fby_iteexp in Hfby; repeat inv_bind; auto.\n    assert (st_follows st x1) as Hfollows1 by (eapply init_var_for_clock_st_follows in H; eauto).\n    assert (st_follows x1 st') as Hfollows2 by eauto.\n    eapply fresh_ident_wt_clock' in H0; eauto. 2:repeat solve_incl.\n    eapply init_var_for_clock_wt_clock in H; eauto.\n    solve_forall; repeat solve_incl.\n  Qed.\n\n  Fact arrow_iteexp_wt_clock : forall vars e0 e ty ck name e' eqs' st st',\n      wt_clock (vars++st_tys' st) ck ->\n      Forall (wt_clock (vars ++ st_tys' st)) (st_clocks' st) ->\n      arrow_iteexp e0 e (ty, (ck, name)) st = (e', eqs', st') ->\n      Forall (wt_clock (vars ++ st_tys' st')) (st_clocks' st').\n  Proof.\n    intros * Hwtc1 Hwtc2 Hfby.\n    unfold arrow_iteexp in Hfby. repeat inv_bind.\n    eapply init_var_for_clock_wt_clock in H; eauto.\n  Qed.\n\n  Fact fby_equation_wt_clock : forall G vars to_cut eq eqs' st st',\n      wt_equation G (vars++st_tys' st) eq ->\n      Forall (wt_clock (vars ++ st_tys' st)) (st_clocks' st) ->\n      fby_equation to_cut eq st = (eqs', st') ->\n      Forall (wt_clock (vars ++ st_tys' st')) (st_clocks' st').\n  Proof.\n    intros * Hwt Hwtck Hfby.\n    inv_fby_equation Hfby to_cut eq.\n    - (* fby (constant) *)\n      destruct x2 as (ty&ck&name).\n      destruct PS.mem; repeat inv_bind; auto.\n      destruct Hwt as [Hwt _]. apply Forall_singl in Hwt.\n      inv Hwt.\n      apply Forall_singl in H7; inv H7.\n      eapply fresh_ident_wt_clock' in H; eauto.\n      1:solve_forall. 1,2:repeat solve_incl.\n    - (* fby *)\n      destruct x2 as (ty&ck&name).\n      eapply fby_iteexp_wt_clock in H; eauto.\n      destruct Hwt as [Hwt _]. apply Forall_singl in Hwt.\n      inv Hwt. apply Forall_singl in H7; inv H7; auto.\n    - (* arrow *)\n      destruct x2 as [ty [ck name]].\n      destruct Hwt as [Hwt _]. inv Hwt. inv H2. inv H9. inv H2.\n      eapply arrow_iteexp_wt_clock in H; eauto.\n  Qed.\n\n  Fact fby_equations_wt_clock : forall G vars to_cut eqs eqs' st st',\n      Forall (wt_equation G (vars++st_tys' st)) eqs ->\n      Forall (wt_clock (vars ++ st_tys' st)) (st_clocks' st) ->\n      fby_equations to_cut eqs st = (eqs', st') ->\n      Forall (wt_clock (vars ++ st_tys' st')) (st_clocks' st').\n  Proof.\n    induction eqs; intros * Hwt Hwtck Hfby;\n      unfold fby_equations in *; repeat inv_bind; simpl; auto.\n    inv Hwt.\n    assert (H':=H). eapply fby_equation_wt_clock in H; eauto.\n    assert (fby_equations to_cut eqs x1 = (concat x2, st')) as Hnorm.\n    { unfold fby_equations. repeat inv_bind. repeat eexists; eauto.\n      inv_bind; auto. }\n      eapply IHeqs in Hnorm; eauto. solve_forall; repeat solve_incl; eauto.\n  Qed.\n\n  Lemma normfby_node_wt : forall G to_cut n Hunt Hpref,\n      wt_node G n ->\n      wt_node G (normfby_node G to_cut n Hunt Hpref).\n  Proof.\n    intros * [Hclin [Hclout [Hclvars Heq]]].\n    unfold normfby_node.\n    repeat constructor; simpl; auto.\n    - unfold wt_clocks in *.\n      apply Forall_app. split.\n      + solve_forall. unfold idty in *.\n        solve_incl. repeat rewrite map_app. repeat solve_incl.\n      + remember (fby_equations _ _ _) as res. symmetry in Heqres. destruct res as [eqs' st'].\n        eapply fby_equations_wt_clock with (G:=G) in Heqres; eauto.\n        * simpl. unfold st_clocks' in Heqres.\n          unfold idty. solve_forall; simpl.\n          repeat solve_incl.\n          repeat rewrite map_app, app_assoc.\n          eapply incl_appr'. reflexivity.\n        * unfold st_clocks'. unfold st_tys'. rewrite init_st_anns, app_nil_r.\n          repeat rewrite <- app_assoc. repeat rewrite <- map_app.\n          solve_forall; repeat solve_incl. apply incl_map, incl_appr'. rewrite Permutation_app_comm; auto.\n        * unfold st_clocks'. rewrite init_st_anns; simpl; constructor.\n    - remember (fby_equations _ _ _) as res. symmetry in Heqres. destruct res as [eqs' st'].\n      eapply fby_equations_wt_eq with (G:=G) (vars:=(idty (n_in n ++ n_vars n ++ n_out n))) in Heqres; eauto.\n      + solve_forall; solve_incl.\n        unfold st_tys'; repeat rewrite <- idty_app. apply incl_map.\n        repeat rewrite <- app_assoc. apply incl_appr', incl_appr'.\n        rewrite Permutation_app_comm. reflexivity.\n      + solve_forall; repeat solve_incl.\n  Qed.\n\n  Lemma normfby_global_wt : forall G Hunt Hprefs,\n      wt_global G ->\n      wt_global (normfby_global G Hunt Hprefs).\n  Proof.\n    induction G; intros * Hwt; simpl; inv Hwt.\n    - constructor.\n    - constructor.\n      + eapply IHG; eauto.\n      + remember (normfby_node _ _) as n'. symmetry in Heqn'.\n        subst.\n        eapply iface_eq_wt_node. eapply normfby_global_eq.\n        eapply normfby_node_wt; eauto.\n      + eapply normfby_global_names; eauto.\n  Qed.\n\n  (** ** Conclusion *)\n\n  Lemma normalize_global_wt : forall G G' Hwl Hprefs,\n      wt_global G ->\n      normalize_global G Hwl Hprefs = Errors.OK G' ->\n      wt_global G'.\n  Proof.\n    intros * Hwt Hnorm.\n    unfold normalize_global in Hnorm.\n    destruct (Caus.check_causality _); inv Hnorm.\n    eapply normfby_global_wt, unnest_global_wt, Hwt.\n  Qed.\n\nEnd NTYPING.\n\nModule NTypingFun\n       (Ids : IDS)\n       (Op : OPERATORS)\n       (OpAux : OPERATORS_AUX Op)\n       (Syn : LSYNTAX Ids Op)\n       (Caus : LCAUSALITY Ids Op Syn)\n       (Typ : LTYPING Ids Op Syn)\n       (Norm : NORMALIZATION Ids Op OpAux Syn Caus)\n       <: NTYPING Ids Op OpAux Syn Caus Typ Norm.\n  Include NTYPING Ids Op OpAux Syn Caus Typ Norm.\nEnd NTypingFun.\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/Normalization/NTyping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2817549391638546}}
{"text": "(*\n * Vericert: Verified high-level synthesis.\n * Copyright (C) 2020 James Pollard <j@mes.dev>\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 <https://www.gnu.org/licenses/>.\n *)\n\nSet Implicit Arguments.\n\nRequire Import Coq.Init.Datatypes.\nRequire Import Coq.Lists.List.\nRequire Import Coq.micromega.Lia.\n\nRequire Import vericert.common.Vericertlib.\n\nImport ListNotations.\n\nLocal Open Scope nat_scope.\n\nRecord Array (A : Type) : Type :=\n  mk_array\n    { arr_contents : list A\n    ; arr_length : nat\n    ; arr_wf : length arr_contents = arr_length\n    }.\n\nDefinition make_array {A : Type} (l : list A) : Array A :=\n  @mk_array A l (length l) eq_refl.\n\nFixpoint list_set {A : Type} (i : nat) (x : A) (l : list A) {struct l} : list A :=\n  match i, l with\n  | _, nil => nil\n  | S n, h :: t => h :: list_set n x t\n  | O, h :: t => x :: t\n  end.\n\nLemma list_set_spec1 {A : Type} :\n  forall l i (x : A),\n    i < length l -> nth_error (list_set i x l) i = Some x.\nProof.\n  induction l; intros; destruct i; crush; firstorder. intuition.\nQed.\n#[export] Hint Resolve list_set_spec1 : array.\n\nLemma list_set_spec2 {A : Type} :\n  forall l i (x : A) d,\n    i < length l -> nth i (list_set i x l) d = x.\nProof.\n  induction l; intros; destruct i; crush; firstorder. intuition.\nQed.\n#[export] Hint Resolve list_set_spec2 : array.\n\nLemma list_set_spec3 {A : Type} :\n  forall l i1 i2 (x : A),\n    i1 <> i2 ->\n    nth_error (list_set i1 x l) i2 = nth_error l i2.\nProof.\n  induction l; intros; destruct i1; destruct i2; crush; firstorder.\nQed.\n#[export] Hint Resolve list_set_spec3 : array.\n\nLemma array_set_wf {A : Type} :\n  forall l ln i (x : A),\n    length l = ln -> length (list_set i x l) = ln.\nProof.\n  induction l; intros; destruct i; auto.\n\n  invert H; crush.\nQed.\n\nDefinition array_set {A : Type} (i : nat) (x : A) (a : Array A) :=\n  let l := a.(arr_contents) in\n  let ln := a.(arr_length) in\n  let WF := a.(arr_wf) in\n  @mk_array A (list_set i x l) ln (@array_set_wf A l ln i x WF).\n\nLemma array_set_spec1 {A : Type} :\n  forall a i (x : A),\n    i < a.(arr_length) -> nth_error ((array_set i x a).(arr_contents)) i = Some x.\nProof.\n  intros.\n\n  rewrite <- a.(arr_wf) in H.\n  unfold array_set. crush.\n  eauto with array.\nQed.\n#[export] Hint Resolve array_set_spec1 : array.\n\nLemma array_set_spec2 {A : Type} :\n  forall a i (x : A) d,\n    i < a.(arr_length) -> nth i ((array_set i x a).(arr_contents)) d = x.\nProof.\n  intros.\n\n  rewrite <- a.(arr_wf) in H.\n  unfold array_set. crush.\n  eauto with array.\nQed.\n#[export] Hint Resolve array_set_spec2 : array.\n\nLemma array_set_len {A : Type} :\n  forall a i (x : A),\n    a.(arr_length) = (array_set i x a).(arr_length).\nProof.\n  unfold array_set. crush.\nQed.\n\nDefinition array_get_error {A : Type} (i : nat) (a : Array A) : option A :=\n  nth_error a.(arr_contents) i.\n\nLemma array_get_error_equal {A : Type} :\n  forall (a b : Array A) i,\n    a.(arr_contents) = b.(arr_contents) ->\n    array_get_error i a = array_get_error i b.\nProof.\n  unfold array_get_error. crush.\nQed.\n\nLemma array_get_error_bound {A : Type} :\n  forall (a : Array A) i,\n    i < a.(arr_length) -> exists x, array_get_error i a = Some x.\nProof.\n  intros.\n\n  rewrite <- a.(arr_wf) in H.\n  assert (~ length (arr_contents a) <= i) by lia.\n\n  pose proof (nth_error_None a.(arr_contents) i).\n  apply not_iff_compat in H1.\n  apply <- H1 in H0.\n\n  destruct (nth_error (arr_contents a) i) eqn:EQ; try contradiction; eauto.\nQed.\n\nLemma array_get_error_set_bound {A : Type} :\n  forall (a : Array A) i x,\n    i < a.(arr_length) -> array_get_error i (array_set i x a) = Some x.\nProof.\n  intros.\n\n  unfold array_get_error.\n  eauto with array.\nQed.\n\nLemma array_gso {A : Type} :\n  forall (a : Array A) i1 i2 x,\n    i1 <> i2 ->\n    array_get_error i2 (array_set i1 x a) = array_get_error i2 a.\nProof.\n  intros.\n\n  unfold array_get_error.\n  unfold array_set.\n  crush.\n  eauto with array.\nQed.\n\nDefinition array_get {A : Type} (i : nat) (x : A) (a : Array A) : A :=\n  nth i a.(arr_contents) x.\n\nLemma array_get_set_bound {A : Type} :\n  forall (a : Array A) i x d,\n    i < a.(arr_length) -> array_get i d (array_set i x a) = x.\nProof.\n  intros.\n\n  unfold array_get.\n  eauto with array.\nQed.\n\nLemma array_get_get_error {A : Type} :\n  forall (a : Array A) i x d,\n    array_get_error i a = Some x ->\n    array_get i d a = x.\nProof.\n  intros.\n  unfold array_get.\n  unfold array_get_error in H.\n  auto using nth_error_nth.\nQed.\n\n(*|\nTail recursive version of standard library function.\n|*)\n\nFixpoint list_repeat' {A : Type} (acc : list A) (a : A) (n : nat) : list A :=\n  match n with\n  | O => acc\n  | S n => list_repeat' (a::acc) a n\n  end.\n\nLemma list_repeat'_len {A : Type} : forall (a : A) n l,\n    length (list_repeat' l a n) = (n + Datatypes.length l)%nat.\nProof.\n  induction n; intros; crush; try reflexivity.\n\n  specialize (IHn (a :: l)).\n  rewrite IHn.\n  crush.\nQed.\n\nLemma list_repeat'_app {A : Type} : forall (a : A) n l,\n    list_repeat' l a n = list_repeat' [] a n ++ l.\nProof.\n  induction n; intros; crush; try reflexivity.\n\n  pose proof IHn.\n  specialize (H (a :: l)).\n  rewrite H. clear H.\n  specialize (IHn (a :: nil)).\n  rewrite IHn. clear IHn.\n  remember (list_repeat' [] a n) as l0.\n\n  rewrite <- app_assoc.\n  f_equal.\nQed.\n\nLemma list_repeat'_head_tail {A : Type} : forall n (a : A),\n  a :: list_repeat' [] a n = list_repeat' [] a n ++ [a].\nProof.\n  induction n; intros; crush; try reflexivity.\n  rewrite list_repeat'_app.\n\n  replace (a :: list_repeat' [] a n ++ [a]) with (list_repeat' [] a n ++ [a] ++ [a]).\n  2: { rewrite app_comm_cons. rewrite IHn; auto.\n       rewrite app_assoc. reflexivity. }\n  rewrite app_assoc. reflexivity.\nQed.\n\nLemma list_repeat'_cons {A : Type} : forall (a : A) n,\n    list_repeat' [a] a n = a :: list_repeat' [] a n.\nProof.\n  intros.\n\n  rewrite list_repeat'_head_tail; auto.\n  apply list_repeat'_app.\nQed.\n\nDefinition list_repeat {A : Type} : A -> nat -> list A := list_repeat' nil.\n\nLemma list_repeat_len {A : Type} : forall n (a : A), length (list_repeat a n) = n.\nProof.\n  intros.\n  unfold list_repeat.\n  rewrite list_repeat'_len.\n  crush.\nQed.\n\nLemma dec_list_repeat_spec {A : Type} : forall n (a : A) a',\n    (forall x x' : A, {x' = x} + {~ x' = x}) ->\n    In a' (list_repeat a n) -> a' = a.\nProof.\n  induction n; intros; crush.\n\n  unfold list_repeat in *.\n  crush.\n\n  rewrite list_repeat'_app in H.\n  pose proof (X a a').\n  destruct H0; auto.\n\n  (* This is actually a degenerate case, not an unprovable goal. *)\n  pose proof (in_app_or (list_repeat' [] a n) ([a])).\n  apply H0 in H. invert H.\n\n  - eapply IHn in X; eassumption.\n  - invert H1; contradiction.\nQed.\n\nLemma list_repeat_head_tail {A : Type} : forall n (a : A),\n    a :: list_repeat a n = list_repeat a n ++ [a].\nProof.\n  unfold list_repeat. apply list_repeat'_head_tail.\nQed.\n\nLemma list_repeat_cons {A : Type} : forall n (a : A),\n    list_repeat a (S n) = a :: list_repeat a n.\nProof.\n  intros.\n\n  unfold list_repeat.\n  apply list_repeat'_cons.\nQed.\n\nLemma list_repeat_lookup {A : Type} :\n  forall n i (a : A),\n    i < n ->\n    nth_error (list_repeat a n) i = Some a.\nProof.\n  induction n; intros.\n\n  destruct i; crush.\n\n  rewrite list_repeat_cons.\n  destruct i; crush; firstorder. intuition.\nQed.\n\nDefinition arr_repeat {A : Type} (a : A) (n : nat) : Array A := make_array (list_repeat a n).\n\nLemma arr_repeat_length {A : Type} : forall n (a : A), arr_length (arr_repeat a n) = n.\nProof.\n  unfold list_repeat. crush. apply list_repeat_len.\nQed.\n\nFixpoint list_combine {A B C : Type} (f : A -> B -> C) (x : list A) (y : list B) : list C :=\n  match x, y with\n  | a :: t, b :: t' => f a b :: list_combine f t t'\n  | _, _ => nil\n  end.\n\nLemma list_combine_length {A B C : Type} (f : A -> B -> C) : forall (x : list A) (y : list B),\n    length (list_combine f x y) = min (length x) (length y).\nProof.\n  induction x; intros; crush.\n\n  destruct y; crush; auto.\nQed.\n\nDefinition combine {A B C : Type} (f : A -> B -> C) (x : Array A) (y : Array B) : Array C :=\n  make_array (list_combine f x.(arr_contents) y.(arr_contents)).\n\nLemma combine_length {A B C: Type} : forall x y (f : A -> B -> C),\n    x.(arr_length) = y.(arr_length) -> arr_length (combine f x y) = x.(arr_length).\nProof.\n  intros.\n\n  unfold combine.\n  unfold make_array.\n  crush.\n\n  rewrite <- (arr_wf x) in *.\n  rewrite <- (arr_wf y) in *.\n\n  destruct (arr_contents x); destruct (arr_contents y); crush.\n  rewrite list_combine_length.\n  destruct (Min.min_dec (length l) (length l0)); congruence.\nQed.\n\nLtac array :=\n  try match goal with\n      | [ |- context[arr_length (combine _ _ _)] ] =>\n        rewrite combine_length\n      | [ |- context[length (list_repeat _ _)] ] =>\n        rewrite list_repeat_len\n      | |- context[array_get_error _ (arr_repeat ?x _) = Some ?x] =>\n        unfold array_get_error, arr_repeat\n      | |- context[nth_error (list_repeat ?x _) _ = Some ?x] =>\n        apply list_repeat_lookup\n      end.\n", "meta": {"author": "ymherklotz", "repo": "vericert", "sha": "c3de945fa463aa9a2ad0804eb8f67e40f585eb3a", "save_path": "github-repos/coq/ymherklotz-vericert", "path": "github-repos/coq/ymherklotz-vericert/vericert-c3de945fa463aa9a2ad0804eb8f67e40f585eb3a/src/hls/Array.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2817549316167985}}
{"text": "(* Distributed under the terms of the MIT license. *)\nFrom Coq Require Import Morphisms.\nRequire Import ssreflect ssrfun ssrbool.\nFrom MetaCoq.Utils Require Import utils MCPred.\nFrom MetaCoq.Common Require Import config.\nFrom MetaCoq.PCUIC Require Import PCUICAst PCUICAstUtils PCUICCases PCUICInduction\n  PCUICLiftSubst PCUICUnivSubst\n  PCUICEquality PCUICSigmaCalculus PCUICClosed.\n\nRequire Import Equations.Prop.DepElim.\nFrom Equations Require Import Equations.\nSet Equations With UIP.\n\n(** * Preservation of free variables *)\n\nOpen Scope sigma_scope.\nSet Keyed Unification.\n\nSet Default Goal Selector \"!\".\n\n(** Hint database for solving closed/on_free_vars goals *)\nCreate HintDb fvs.\nLtac fvs := eauto with fvs.\n\nImplicit Type (cf : checker_flags).\n\nDefinition shiftnP k p i :=\n  (i <? k) || p (i - k).\n\n#[global]\nInstance shiftnP_ext k : Proper (`=1` ==> `=1`) (shiftnP k).\nProof. intros f g Hfg i. now rewrite /shiftnP Hfg. Qed.\n\nLemma shiftnP0 P : shiftnP 0 P =1 P.\nProof. rewrite /shiftnP. intros i; rewrite Nat.sub_0_r //. Qed.\n\nLemma shiftnP_add n k P : shiftnP n (shiftnP k P) =1 shiftnP (n + k) P.\nProof. rewrite /shiftnP. intros i; repeat nat_compare_specs => // /=. lia_f_equal. Qed.\n\nLemma shiftnP_shiftn P f i : (shiftnP i P) ∘ (shiftn i f) =1 shiftnP i (P ∘ f).\nProof.\n  intros k.\n  rewrite !/shiftnP /shiftn.\n  destruct (Nat.ltb_spec k i) => /=.\n  all: nat_compare_specs => //=.\n  by rewrite Nat.add_comm Nat.add_sub.\nQed.\n\nLemma shiftnP_impl (p q : nat -> bool) : (forall i, p i -> q i) ->\n  forall n i, shiftnP n p i -> shiftnP n q i.\nProof.\n  intros Hi n i. rewrite /shiftnP.\n  nat_compare_specs => //. apply Hi.\nQed.\n\nLemma shiftnP_S P n : shiftnP (S n) P =1 shiftnP 1 (shiftnP n P).\nProof. now rewrite (shiftnP_add 1). Qed.\n\nDefinition closedP (n : nat) (P : nat -> bool) :=\n  fun i => if i <? n then P i else false.\n\n#[global]\nInstance closedP_proper n : Proper (`=1` ==> `=1`) (closedP n).\nProof. intros f g Hfg. intros i; rewrite /closedP. now rewrite Hfg. Qed.\n\nLemma shiftnP_closedP k n P : shiftnP k (closedP n P) =1 closedP (k + n) (shiftnP k P).\nProof.\n  intros i; rewrite /shiftnP /closedP.\n  repeat nat_compare_specs => //.\nQed.\n\nFixpoint on_free_vars (p : nat -> bool) (t : term) : bool :=\n  match t with\n  | tRel i => p i\n  | tEvar ev args => List.forallb (on_free_vars p) args\n  | tLambda _ T M | tProd _ T M => on_free_vars p T && on_free_vars (shiftnP 1 p) M\n  | tApp u v => on_free_vars p u && on_free_vars p v\n  | tLetIn na b t b' => [&& on_free_vars p b, on_free_vars p t & on_free_vars (shiftnP 1 p) b']\n  | tCase ind pred c brs =>\n    [&& forallb (on_free_vars p) pred.(pparams),\n      on_free_vars (shiftnP #|pred.(pcontext)| p) pred.(preturn),\n      test_context_k (fun k => on_free_vars (closedP k xpredT)) #|pred.(pparams)| pred.(pcontext),\n      on_free_vars p c &\n      forallb (fun br =>\n        test_context_k (fun k => on_free_vars (closedP k xpredT)) #|pred.(pparams)| br.(bcontext) &&\n        on_free_vars (shiftnP #|br.(bcontext)| p) br.(bbody)) brs]\n  | tProj _ c => on_free_vars p c\n  | tFix mfix idx | tCoFix mfix idx =>\n    List.forallb (test_def (on_free_vars p) (on_free_vars (shiftnP #|mfix| p))) mfix\n  | tVar _ | tSort _ | tConst _ _ | tInd _ _ | tConstruct _ _ _ => true\n  | tPrim _ => true\n  end.\n\nLemma on_free_vars_ext (p q : nat -> bool) t :\n  p =1 q ->\n  on_free_vars p t = on_free_vars q t.\nProof.\n  revert p q.\n  induction t using PCUICInduction.term_forall_list_ind; simpl => //; intros;\n    unfold test_def;\n    rewrite ?forallb_map; try eapply All_forallb_eq_forallb; tea; eauto 2.\n  all: try now rewrite (IHt1 p q) // ?(IHt2 (shiftnP 1 p) (shiftnP 1 q)) // H.\n  - now rewrite (IHt1 p q) // ?(IHt2 p q) // (IHt3 (shiftnP 1 p) (shiftnP 1 q)) // H.\n  - rewrite (IHt1 p q) // (IHt2 p q) //.\n  - destruct X as [? [? ?]]. red in X0.\n    f_equal.\n    * eapply All_forallb_eq_forallb; tea. solve_all.\n    * f_equal; [eapply e; rewrite H //|].\n      f_equal.\n      f_equal; [eapply IHt; rewrite H //|].\n        eapply All_forallb_eq_forallb; tea. intros.\n        destruct X.\n        f_equal. eapply e0; rewrite H //.\n  - simpl; intuition auto. f_equal; eauto 2.\n    eapply b; rewrite H //.\n  - simpl; intuition auto. f_equal; eauto 2.\n    eapply b; rewrite H //.\nQed.\n\n#[global]\nInstance on_free_vars_proper : Proper (`=1` ==> Logic.eq ==> Logic.eq) on_free_vars.\nProof. intros f g Hfg ? ? ->. now apply on_free_vars_ext. Qed.\n\n#[global]\nInstance on_free_vars_proper_pointwise : Proper (`=1` ==> `=1`) on_free_vars.\nProof. intros f g Hfg x. now apply on_free_vars_ext. Qed.\n\nLemma shiftnP_xpredT n : shiftnP n xpredT =1 xpredT.\nProof. intros i; rewrite /shiftnP. nat_compare_specs => //. Qed.\n\nLemma test_context_k_ctx p k (ctx : context) : test_context_k (fun=> p) k ctx = test_context p ctx.\nProof.\n  induction ctx; simpl; auto.\nQed.\n#[global]\nHint Rewrite test_context_k_ctx : map.\n\n(* (* (* Lemma on_free_vars_true t : on_free_vars xpredT t.\nProof.\n  revert t.\n  induction t using PCUICInduction.term_forall_list_ind; simpl => //; solve_all.\n  all:try (rtoProp; now rewrite ?shiftnP_xpredT ?IHt1 ?IHt2 ?IHt3; eauto 2;\n    try rtoProp; solve_all).\n  - rtoProp. setoid_rewrite shiftnP_xpredT.\n    rewrite test_context_k_ctx.\n    now move/onctxP: a0.\n  - setoid_rewrite shiftnP_xpredT.\n    rewrite test_context_k_ctx.\n    now move/onctxP: a1.\n  - unfold test_def in *. apply /andP. now rewrite shiftnP_xpredT.\n  - unfold test_def in *. apply /andP. now rewrite shiftnP_xpredT.\nQed. *)\n\nLemma on_free_vars_xpredT : on_free_vars xpredT =1 xpredT.\nProof.\n  intros t; apply on_free_vars_true.\nQed. *)\n\nLemma test_context_k_true n ctx : test_context_k (fun=> on_free_vars xpredT) n ctx.\nProof.\n  setoid_rewrite on_free_vars_xpredT.\n  induction ctx; simpl; auto.\n  rewrite /test_decl IHctx /=.\n  destruct a as [na [b|] ty] => /= //.\nQed. *)\n\nLemma on_free_vars_impl (p q : nat -> bool) t :\n  (forall i, p i -> q i) ->\n  on_free_vars p t ->\n  on_free_vars q t.\nProof.\n  unfold pointwise_relation, Basics.impl.\n  intros Himpl onf. revert onf Himpl.\n  revert t p q.\n  induction t using PCUICInduction.term_forall_list_ind; simpl => //; solve_all.\n  all:unfold test_def in *; rtoProp; now (eauto using shiftnP_impl with all).\nQed.\n\nLemma closedP_on_free_vars {n t} : closedn n t = on_free_vars (closedP n xpredT) t.\nProof.\n  revert t n.\n  apply: term_forall_list_ind; simpl => //; intros.\n  all:(rewrite ?shiftnP_closedP ?shiftnP_xpredT).\n  all:try (rtoProp; now rewrite ?H ?H0 ?H1 ?andb_assoc).\n  - rewrite /closedP /=. now nat_compare_specs.\n  - solve_all.\n  - destruct X. rtoProp. rewrite /test_predicate_k /= !andb_assoc.\n    rewrite H /=. f_equal. 2:solve_all.\n    * f_equal. rewrite andb_comm andb_assoc. f_equal; solve_all.\n      rewrite andb_comm. f_equal; solve_all.\n    * rewrite /test_branch_k. f_equal; solve_all.\n      rewrite b0.\n      now rewrite shiftnP_closedP shiftnP_xpredT.\n  - unfold test_def. solve_all.\n    rewrite shiftnP_closedP shiftnP_xpredT.\n    now len in b.\n  - unfold test_def; solve_all.\n    rewrite shiftnP_closedP shiftnP_xpredT.\n    now len in b.\nQed.\n\nLemma closedn_on_free_vars {P n t} : closedn n t -> on_free_vars (shiftnP n P) t.\nProof.\n  rewrite closedP_on_free_vars.\n  eapply on_free_vars_impl.\n  intros i; rewrite /closedP /shiftnP /= //.\n  nat_compare_specs => //.\nQed.\n\n(** Any predicate is admissible as there are no free variables to consider *)\nLemma closed_on_free_vars_none {t} : closed t = on_free_vars xpred0 t.\nProof.\n  now rewrite closedP_on_free_vars /closedP /=.\nQed.\n\nLemma closed_on_free_vars {P t} : closed t -> on_free_vars P t.\nProof.\n  rewrite closedP_on_free_vars /closedP /=.\n  eapply on_free_vars_impl => //.\nQed.\n\nLemma on_free_vars_subst_instance {p u t} : on_free_vars p (subst_instance u t) = on_free_vars p t.\nProof.\n  rewrite /subst_instance /=. revert t p.\n  apply: term_forall_list_ind; simpl => //; intros.\n  all:try (rtoProp; now rewrite -?IHt1 -?IHt2 -?IHt3).\n  - rewrite forallb_map. eapply All_forallb_eq_forallb; eauto.\n  - repeat (solve_all; f_equal).\n  - unfold test_def. solve_all.\n  - unfold test_def; solve_all.\nQed.\n\nDefinition on_free_vars_decl P d :=\n  test_decl (on_free_vars P) d.\n\n#[global]\nInstance on_free_vars_decl_proper : Proper (`=1` ==> Logic.eq ==> Logic.eq) on_free_vars_decl.\nProof. rewrite /on_free_vars_decl => f g Hfg x y <-. now rewrite Hfg. Qed.\n\n#[global]\nInstance on_free_vars_decl_proper_pointwise : Proper (`=1` ==> `=1`) on_free_vars_decl.\nProof. rewrite /on_free_vars_decl => f g Hfg x. now rewrite Hfg. Qed.\n\nDefinition on_free_vars_ctx P ctx :=\n  alli (fun k => (on_free_vars_decl (shiftnP k P))) 0 (List.rev ctx).\n\n#[global]\nInstance on_free_vars_ctx_proper : Proper (`=1` ==> `=1`) on_free_vars_ctx.\nProof.\n  rewrite /on_free_vars_ctx => f g Hfg x.\n  now setoid_rewrite Hfg.\nQed.\n\nNotation is_open_term Γ := (on_free_vars (shiftnP #|Γ| xpred0)).\nNotation is_open_decl Γ := (on_free_vars_decl (shiftnP #|Γ| xpred0)).\nNotation is_closed_context := (on_free_vars_ctx xpred0).\n\n\nLemma on_free_vars_decl_impl (p q : nat -> bool) d :\n  (forall i, p i -> q i) ->\n  on_free_vars_decl p d -> on_free_vars_decl q d.\nProof.\n  intros hpi.\n  apply test_decl_impl. intros t.\n  now apply on_free_vars_impl.\nQed.\n\nLemma on_free_vars_ctx_impl (p q : nat -> bool) ctx :\n  (forall i, p i -> q i) ->\n  on_free_vars_ctx p ctx -> on_free_vars_ctx q ctx.\nProof.\n  intros hpi.\n  eapply alli_impl => i x.\n  apply on_free_vars_decl_impl.\n  intros k; rewrite /shiftnP.\n  now nat_compare_specs.\nQed.\n\nLemma closed_decl_on_free_vars {n d} : closed_decl n d = on_free_vars_decl (closedP n xpredT) d.\nProof.\n  rewrite /on_free_vars_decl /test_decl.\n  rewrite !closedP_on_free_vars /=.\n  destruct (decl_body d) eqn:db => /= //.\n  now rewrite closedP_on_free_vars.\nQed.\n\nLemma closedn_ctx_on_free_vars {n ctx} : closedn_ctx n ctx = on_free_vars_ctx (closedP n xpredT) ctx.\nProof.\n  rewrite /on_free_vars_ctx test_context_k_eq.\n  eapply alli_ext. intros i d.\n  rewrite shiftnP_closedP shiftnP_xpredT Nat.add_comm.\n  apply closed_decl_on_free_vars.\nQed.\n\nLemma closedP_shiftnP (n : nat) : closedP n xpredT =1 shiftnP n xpred0.\nProof.\n  rewrite /closedP /shiftnP => i.\n  destruct Nat.ltb => //.\nQed.\n\nLemma closedP_shiftnP_impl n P i : closedP n xpredT i -> shiftnP n P i.\nProof.\n  rewrite closedP_shiftnP.\n  rewrite /shiftnP.\n  nat_compare_specs => //.\nQed.\n\nLemma closedn_ctx_on_free_vars_shift {n ctx P} :\n  closedn_ctx n ctx ->\n  on_free_vars_ctx (shiftnP n P) ctx.\nProof.\n  rewrite closedn_ctx_on_free_vars.\n  rewrite /on_free_vars_ctx.\n  apply alli_impl => i x.\n  eapply on_free_vars_decl_impl => //.\n  intros k. rewrite shiftnP_add shiftnP_closedP shiftnP_xpredT.\n  apply closedP_shiftnP_impl.\nQed.\n\n(** This uses absurdity elimination as [ctx] can't have any free variable *)\nLemma closed_ctx_on_free_vars P ctx : closed_ctx ctx -> on_free_vars_ctx P ctx.\nProof.\n  rewrite closedn_ctx_on_free_vars => /=.\n  rewrite /closedP /=.\n  eapply on_free_vars_ctx_impl => //.\nQed.\n\nDefinition nocc_betweenp k n i :=\n  (i <? k) || (k + n <=? i).\n\nDefinition nocc_between k n t :=\n  (on_free_vars (nocc_betweenp k n) t).\n\nDefinition noccur_shift p k := fun i => (i <? k) || p (i - k).\n\n#[global] Hint Resolve All_forallb_eq_forallb : all.\n\nDefinition strengthenP k n (p : nat -> bool) :=\n  fun i => if i <? k then p i else\n    if i <? k + n then false\n    else p (i - n).\n\n#[global]\nInstance strengthenP_proper n k : Proper (`=1` ==> `=1`) (strengthenP n k).\nProof.\n  intros f g Hfg i. rewrite /strengthenP. now rewrite (Hfg i) (Hfg (i - k)).\nQed.\n\nLemma shiftnP_strengthenP k' k n p :\n  shiftnP k' (strengthenP k n p) =1 strengthenP (k' + k) n (shiftnP k' p).\nProof.\n  intros i. rewrite /shiftnP /strengthenP.\n  repeat nat_compare_specs => /= //.\n  lia_f_equal.\nQed.\n\nLemma on_free_vars_lift (p : nat -> bool) n k t :\n  on_free_vars (strengthenP k n p) (lift n k t) = on_free_vars p t.\nProof.\n  intros. revert t n k p.\n  induction t using PCUICInduction.term_forall_list_ind; simpl => //; intros;\n    rewrite ?forallb_map; try eapply All_forallb_eq_forallb; tea; simpl.\n  2-6:try now rewrite ?shiftnP_strengthenP ?IHt1 ?IHt2 ?IHt3.\n  - rename n0 into i. rewrite /strengthenP.\n    repeat nat_compare_specs => //.\n    lia_f_equal.\n  - rtoProp; solve_all. len; rewrite !shiftnP_strengthenP e IHt.\n    f_equal; solve_all. f_equal; solve_all. f_equal; solve_all. f_equal.\n    solve_all.\n    f_equal; solve_all.\n    len. now rewrite !shiftnP_strengthenP.\n  - unfold test_def in *. simpl; intros ? [].\n    len; rewrite shiftnP_strengthenP. f_equal; eauto.\n  - unfold test_def in *. simpl; intros ? [].\n    len; rewrite shiftnP_strengthenP. f_equal; eauto.\nQed.\n\nDefinition on_free_vars_terms p s :=\n  forallb (on_free_vars p) s.\n\nDefinition substP (k : nat) n (q p : nat -> bool) : nat -> bool :=\n  fun i =>\n    if i <? k then p i\n    else p (i + n) || strengthenP 0 k q i.\n\nLemma shiftnP_substP k' k n q p :\n  shiftnP k' (substP k n q p) =1 substP (k' + k) n q (shiftnP k' p).\nProof.\n  intros i; rewrite /shiftnP /substP.\n  repeat nat_compare_specs => /= //.\n  f_equal; [f_equal|] => /= //.\n  * lia_f_equal.\n  * rewrite /strengthenP. simpl.\n    repeat nat_compare_specs => //.\n    lia_f_equal.\nQed.\n\nLemma on_free_vars_subst_gen (p q : nat -> bool) s k t :\n  on_free_vars_terms q s ->\n  on_free_vars p t ->\n  on_free_vars (substP k #|s| q p) (subst s k t).\nProof.\n  revert t p k.\n  induction t using PCUICInduction.term_forall_list_ind; simpl => //; intros;\n    simpl.\n  all:try (rtoProp; rewrite ?shiftnP_substP; now rewrite ?IHt1 ?IHt2 ?IHt3).\n  - intros. destruct (Nat.leb_spec k n).\n    * destruct nth_error eqn:eq.\n      + unfold on_free_vars_terms in *. toAll.\n        pose proof (nth_error_Some_length eq).\n        eapply nth_error_all in eq; eauto.\n        simpl in eq. rewrite /substP.\n        eapply on_free_vars_impl.\n        2:now rewrite -> on_free_vars_lift.\n        rewrite /strengthenP. simpl.\n        intros i. nat_compare_specs => //.\n        intros ->. now rewrite orb_true_r.\n      + eapply nth_error_None in eq.\n        simpl. rewrite /substP.\n        replace (n - #|s| + #|s|) with n by lia.\n        nat_compare_specs.\n        now rewrite H0.\n    * simpl. rewrite /substP /strengthenP /=.\n      rewrite H0. now nat_compare_specs.\n  - solve_all.\n  - rtoProp. destruct X. solve_all.\n    * len. rewrite shiftnP_substP. solve_all.\n    * len. rewrite shiftnP_substP; solve_all.\n  - unfold test_def in *; red in X; solve_all.\n    rtoProp. rewrite shiftnP_substP; len. solve_all.\n  - unfold test_def in *; solve_all. rtoProp.\n    rewrite shiftnP_substP; len. solve_all.\nQed.\n\nLemma rshiftk_S x f : S (rshiftk x f) = rshiftk (S x) f.\nProof. reflexivity. Qed.\n\nLemma substP_shiftnP n p :\n  substP 0 n p (shiftnP n p) =1 p.\nProof.\n  intros i; rewrite /shiftnP /substP /= /strengthenP /=.\n  nat_compare_specs.\n  replace (i + n - n) with i by lia.\n  now rewrite Nat.sub_0_r orb_diag.\nQed.\n\nLemma on_free_vars_subst (p : nat -> bool) s t :\n  forallb (on_free_vars p) s ->\n  on_free_vars (shiftnP #|s| p) t ->\n  on_free_vars p (subst s 0 t).\nProof.\n  intros hs ht.\n  epose proof (on_free_vars_subst_gen (shiftnP #|s| p) p s 0 t).\n  rewrite -> substP_shiftnP in H.\n  apply H.\n  - exact hs.\n  - apply ht.\nQed.\n\nLemma on_free_vars_subst1 (p : nat -> bool) s t :\n  on_free_vars p s ->\n  on_free_vars (shiftnP 1 p) t ->\n  on_free_vars p (subst1 s 0 t).\nProof.\n  intros hs ht.\n  rewrite /subst1.\n  epose proof (on_free_vars_subst_gen (shiftnP 1 p) p [s] 0 t).\n  rewrite -> substP_shiftnP in H.\n  apply H.\n  - now rewrite /on_free_vars_terms /= hs.\n  - apply ht.\nQed.\n\nDefinition addnP n (p : nat -> bool) :=\n  fun i => p (n + i).\n\n#[global]\nInstance addnP_proper n : Proper (`=1` ==> Logic.eq ==> Logic.eq) (addnP n).\nProof.\n  intros i f g Hfg; now rewrite /addnP.\nQed.\n\n#[global]\nInstance addnP_proper_pointwise : Proper (Logic.eq ==> `=1` ==> `=1`) addnP.\nProof.\n  intros i f g Hfg; now rewrite /addnP.\nQed.\n\nLemma addnP_add n k p : addnP n (addnP k p) =1 addnP (n + k) p.\nProof.\n  rewrite /addnP => i. lia_f_equal.\nQed.\n\nLemma addnP0 p : addnP 0 p =1 p.\nProof. reflexivity. Qed.\n\nLemma addnP_shiftnP n P : addnP n (shiftnP n P) =1 P.\nProof.\n  intros i; rewrite /addnP /shiftnP /=.\n  nat_compare_specs => /=. lia_f_equal.\nQed.\n\nLemma addnP_orP n p q : addnP n (predU p q) =1 predU (addnP n p) (addnP n q).\nProof. reflexivity. Qed.\n\nDefinition on_ctx_free_vars P ctx :=\n  alli (fun k d => P k ==> (on_free_vars_decl (addnP (S k) P) d)) 0 ctx.\n\n#[global]\nInstance on_ctx_free_vars_proper : Proper (`=1` ==> eq ==> eq) on_ctx_free_vars.\nProof.\n  rewrite /on_ctx_free_vars => f g Hfg x y <-.\n  apply alli_ext => k.\n  now setoid_rewrite Hfg.\nQed.\n\n#[global]\nInstance on_ctx_free_vars_proper_pointwise : Proper (`=1` ==> `=1`) on_ctx_free_vars.\nProof.\n  rewrite /on_ctx_free_vars => f g Hfg x.\n  apply alli_ext => k.\n  now setoid_rewrite Hfg.\nQed.\n\nLemma nth_error_on_free_vars_ctx P n ctx i d :\n  on_ctx_free_vars (addnP n P) ctx ->\n  P (n + i) ->\n  nth_error ctx i = Some d ->\n  test_decl (on_free_vars (addnP (n + S i) P)) d.\nProof.\n  rewrite /on_ctx_free_vars.\n  solve_all.\n  eapply alli_Alli, Alli_nth_error in H; eauto.\n  rewrite /= {1}/addnP H0 /= in H.\n  now rewrite Nat.add_comm -addnP_add.\nQed.\n\nDefinition aboveP k (p : nat -> bool) :=\n  fun i => if i <? k then false else p i.\n\nLemma strengthenP_addn i p : strengthenP 0 i (addnP i p) =1 aboveP i p.\nProof.\n   intros k.\n   rewrite /strengthenP /= /addnP /aboveP.\n   nat_compare_specs => //.\n   lia_f_equal.\nQed.\n\nLemma on_free_vars_lift0 i p t :\n  on_free_vars (addnP i p) t ->\n  on_free_vars p (lift0 i t).\nProof.\n  rewrite -(on_free_vars_lift _ i 0).\n  rewrite /strengthenP /= /aboveP /addnP.\n  unshelve eapply on_free_vars_impl.\n  simpl. intros i'. nat_compare_specs => //.\n  now replace (i + (i' - i)) with i' by lia.\nQed.\n\nLemma on_free_vars_lift0_above i p t :\n  on_free_vars (addnP i p) t = on_free_vars (aboveP i p) (lift0 i t).\nProof.\n  rewrite -(on_free_vars_lift _ i 0).\n  rewrite /strengthenP /= /aboveP /addnP.\n  unshelve eapply on_free_vars_ext.\n  simpl. intros i'. nat_compare_specs => //.\n  now replace (i' - i + i) with i' by lia.\nQed.\n\nLemma on_free_vars_mkApps p f args :\n  on_free_vars p (mkApps f args) = on_free_vars p f && forallb (on_free_vars p) args.\nProof.\n  induction args in f |- * => /=.\n  - now rewrite andb_true_r.\n  - now rewrite IHargs /= andb_assoc.\nQed.\n\nLemma extended_subst_shiftn p ctx n k :\n  forallb (on_free_vars (strengthenP 0 n (shiftnP (k + context_assumptions ctx) p)))\n    (extended_subst ctx (n + k)) =\n  forallb (on_free_vars (shiftnP (k + (context_assumptions ctx)) p))\n    (extended_subst ctx k).\nProof.\n  rewrite lift_extended_subst' forallb_map.\n  eapply forallb_ext => t.\n  rewrite -(on_free_vars_lift _ n 0 t) //.\nQed.\n\nLemma extended_subst_shiftn_aboveP p ctx n k :\n  forallb (on_free_vars (aboveP n p)) (extended_subst ctx (n + k)) =\n  forallb (on_free_vars (addnP n p)) (extended_subst ctx k).\nProof.\n  rewrite lift_extended_subst' forallb_map.\n  eapply forallb_ext => t.\n  rewrite -(on_free_vars_lift0_above) //.\nQed.\n\nLemma extended_subst_shiftn_impl p ctx n k :\n  forallb (on_free_vars (shiftnP (k + (context_assumptions ctx)) p))\n    (extended_subst ctx k) ->\n  forallb (on_free_vars (shiftnP (n + k + context_assumptions ctx) p))\n    (extended_subst ctx (n + k)).\nProof.\n  rewrite lift_extended_subst' forallb_map.\n  eapply forallb_impl => t _.\n  rewrite -(on_free_vars_lift _ n 0 t).\n  rewrite /strengthenP /=.\n  apply on_free_vars_impl => i.\n  rewrite /shiftnP.\n  repeat nat_compare_specs => /= //.\n  intros.\n  red; rewrite -H2. lia_f_equal.\nQed.\n\nDefinition occ_betweenP k n :=\n  fun i => (k <=? i) && (i <? k + n).\n\nLemma on_free_vars_decl_all_term P d s :\n  on_free_vars_decl P d = on_free_vars P (mkProd_or_LetIn d (tSort s)).\nProof.\n  rewrite /on_free_vars_decl /= /test_decl.\n  destruct d as [na [b|] ty] => /= //; now rewrite andb_true_r.\nQed.\n\nLemma on_free_vars_mkProd_or_LetIn P d t :\n  on_free_vars P (mkProd_or_LetIn d t) =\n  on_free_vars_decl P d && on_free_vars (shiftnP 1 P) t.\nProof.\n  destruct d as [na [b|] ty]; rewrite /mkProd_or_LetIn /on_free_vars_decl /test_decl /=\n    ?andb_assoc /foroptb /=; try bool_congr.\nQed.\n\nLemma on_free_vars_ctx_all_term P ctx s :\n  on_free_vars_ctx P ctx = on_free_vars P (it_mkProd_or_LetIn ctx (tSort s)).\nProof.\n  rewrite /on_free_vars_ctx.\n  rewrite -{2}[P](shiftnP0 P).\n  generalize 0 as k.\n  induction ctx using rev_ind; simpl; auto; intros k.\n  rewrite List.rev_app_distr alli_app /= andb_true_r.\n  rewrite IHctx it_mkProd_or_LetIn_app /= on_free_vars_mkProd_or_LetIn.\n  now rewrite shiftnP_add.\nQed.\n\nDefinition on_free_vars_ctx_k P n ctx :=\n  alli (fun k => (on_free_vars_decl (shiftnP k P))) n (List.rev ctx).\n\nDefinition predA {A} (p q : pred A) : simpl_pred A :=\n  [pred i | p i ==> q i].\n\nDefinition eq_simpl_pred {A} (x y : simpl_pred A) :=\n  `=1` x y.\n\n#[global]\nInstance implP_Proper {A} : Proper (`=1` ==> `=1` ==> eq_simpl_pred) (@predA A).\nProof.\n  intros f g Hfg f' g' Hfg' i; rewrite /predA /=.\n  now rewrite Hfg Hfg'.\nQed.\n\nLemma on_free_vars_implP p q t :\n  predA p q =1 xpredT ->\n  on_free_vars p t -> on_free_vars q t.\nProof.\n  rewrite /predA /=. intros Hp.\n  eapply on_free_vars_impl.\n  intros i hp. specialize (Hp i). now rewrite /= hp in Hp.\nQed.\n\nDefinition shiftnP_predU n p q :\n  shiftnP n (predU p q) =1 predU (shiftnP n p) (shiftnP n q).\nProof.\n  intros i.\n  rewrite /shiftnP /predU /=.\n  repeat nat_compare_specs => //.\nQed.\n\n#[global]\nInstance orP_Proper {A} : Proper (`=1` ==> `=1` ==> eq_simpl_pred) (@predU A).\nProof.\n  intros f g Hfg f' g' Hfg' i; rewrite /predU /=.\n  now rewrite Hfg Hfg'.\nQed.\n\n#[global]\nInstance andP_Proper A : Proper (`=1` ==> `=1` ==> eq_simpl_pred) (@predI A).\nProof.\n  intros f g Hfg f' g' Hfg' i; rewrite /predI /=.\n  now rewrite Hfg Hfg'.\nQed.\n\n#[global]\nInstance pred_of_simpl_proper {A} : Proper (eq_simpl_pred ==> `=1`) (@PredOfSimpl.coerce A).\nProof.\n  now move=> f g; rewrite /eq_simpl_pred => Hfg.\nQed.\n\nLemma orPL (p q : pred nat) : (predA p (predU p q)) =1 predT.\nProof.\n  intros i. rewrite /predA /predU /=.\n  rewrite (ssrbool.implybE (p i)).\n  destruct (p i) => //.\nQed.\n\n\nLemma orPR (p q : nat -> bool) i : q i -> (predU p q) i.\nProof.\n  rewrite /predU /= => ->; rewrite orb_true_r //.\nQed.\n\n(** We need a disjunction here as the substitution can be made of\n    expanded lets (properly lifted) or just the variables of\n    [ctx] (lifted by [k]).\n\n    The proof could certainly be simplified using a more high-level handling of\n    free-variables predicate, which form a simple classical algebra.\n    To investigate: does ssr's library support this? *)\n\nLemma on_free_vars_extended_subst p k ctx :\n  on_free_vars_ctx_k p k ctx ->\n  forallb (on_free_vars\n    (predU (strengthenP 0 (context_assumptions ctx + k) (shiftnP k p))\n      (occ_betweenP k (context_assumptions ctx))))\n    (extended_subst ctx k).\nProof.\n  rewrite /on_free_vars_ctx_k.\n  induction ctx as [|[na [b|] ty] ctx] in p, k |- *; auto.\n  - simpl. rewrite alli_app /= andb_true_r => /andP [] hctx.\n    rewrite /on_free_vars_decl /test_decl /=; len => /andP [] hty /= hb.\n    specialize (IHctx _ k hctx).\n    rewrite IHctx // andb_true_r.\n    eapply on_free_vars_subst => //.\n    len. erewrite on_free_vars_implP => //; cycle 1.\n    { erewrite on_free_vars_lift; eauto. }\n    now rewrite shiftnP_predU /= shiftnP_strengthenP Nat.add_0_r shiftnP_add /= orPL.\n  - cbn. rewrite alli_app /= andb_true_r => /andP [] hctx.\n    rewrite /on_free_vars_decl /test_decl /= => hty.\n    len in hty.\n    specialize (IHctx p k).\n    rewrite andb_idl.\n    * move => _. rewrite /occ_betweenP. repeat nat_compare_specs => /= //.\n    * specialize (IHctx hctx).\n      rewrite (lift_extended_subst' _ 1).\n      rewrite forallb_map.\n      solve_all.\n      apply on_free_vars_lift0.\n      rewrite addnP_orP.\n      eapply on_free_vars_implP; eauto.\n      intros i. rewrite /predA /predU /=.\n      rewrite /strengthenP /= /addnP /=.\n      repeat nat_compare_specs => /= //.\n      + rewrite /occ_betweenP /implb => /=.\n        repeat nat_compare_specs => /= //.\n      + rewrite /shiftnP /occ_betweenP /=.\n        repeat nat_compare_specs => /= //.\n        rewrite !orb_false_r.\n        replace (i + 1 - S (context_assumptions ctx + k) - k) with\n          (i - (context_assumptions ctx + k) - k) by lia.\n        rewrite implybE. destruct p; auto.\nQed.\n\nLemma on_free_vars_expand_lets_k P Γ n t :\n  n = context_assumptions Γ ->\n  on_free_vars_ctx P Γ ->\n  on_free_vars (shiftnP #|Γ| P) t ->\n  on_free_vars (shiftnP n P) (expand_lets_k Γ 0 t).\nProof.\n  intros -> HΓ Ht.\n  rewrite /expand_lets_k /=.\n  eapply on_free_vars_impl; cycle 1.\n  - eapply on_free_vars_subst_gen.\n    1:eapply on_free_vars_extended_subst; eauto.\n    rewrite -> on_free_vars_lift. eauto.\n  - len. rewrite /substP /= /strengthenP /=.\n    intros i. simpl. rewrite /shiftnP.\n    repeat nat_compare_specs => /= //.\n    rewrite Nat.sub_0_r. rewrite /orP.\n    replace (i + #|Γ| - context_assumptions Γ - #|Γ|) with (i - context_assumptions Γ) by lia.\n    rewrite /occ_betweenP. repeat nat_compare_specs => /= //.\n    rewrite orb_false_r Nat.sub_0_r.\n    now rewrite orb_diag.\nQed.\n\nLemma on_free_vars_terms_inds P ind puinst bodies :\n  on_free_vars_terms P (inds ind puinst bodies).\nProof.\n  rewrite /inds.\n  induction #|bodies|; simpl; auto.\nQed.\n\nLemma on_free_vars_decl_map P f d :\n  (forall i, on_free_vars P i = on_free_vars P (f i)) ->\n  on_free_vars_decl P d = on_free_vars_decl P (map_decl f d).\nProof.\n  intros Hi.\n  rewrite /on_free_vars_decl /test_decl.\n  rewrite Hi. f_equal.\n  simpl. destruct (decl_body d) => //.\n  now rewrite /foroptb /= (Hi t).\nQed.\n\nLemma on_free_vars_ctx_subst_instance P u Γ :\n  on_free_vars_ctx P (subst_instance u Γ) = on_free_vars_ctx P Γ.\nProof.\n  rewrite /on_free_vars_ctx.\n  rewrite /subst_instance -map_rev alli_map.\n  apply alli_ext => i d.\n  symmetry. apply on_free_vars_decl_map.\n  intros. now rewrite on_free_vars_subst_instance.\nQed.\n\nLemma on_free_vars_map2_cstr_args p bctx ctx :\n  #|bctx| = #|ctx| ->\n  on_free_vars_ctx p ctx =\n  on_free_vars_ctx p (map2 set_binder_name bctx ctx).\nProof.\n  rewrite /on_free_vars_ctx.\n  induction ctx as [|d ctx] in bctx |- *; simpl; auto.\n  - destruct bctx; reflexivity.\n  - destruct bctx => /= //.\n    intros [= hlen].\n    rewrite alli_app (IHctx bctx) // alli_app. f_equal.\n    len. rewrite map2_length // hlen. f_equal.\nQed.\n\n\nLemma on_free_vars_to_extended_list P ctx :\n  forallb (on_free_vars (shiftnP #|ctx| P)) (to_extended_list ctx).\nProof.\n  rewrite /to_extended_list /to_extended_list_k.\n  change #|ctx| with (0 + #|ctx|).\n  have: (forallb (on_free_vars (shiftnP (0 + #|ctx|) P)) []) by easy.\n  generalize (@nil term), 0.\n  induction ctx; intros l n.\n  - simpl; auto.\n  - simpl. intros Hl.\n    destruct a as [? [?|] ?].\n    * rewrite Nat.add_succ_r in Hl.\n      specialize (IHctx _ (S n) Hl).\n      now rewrite Nat.add_succ_r Nat.add_1_r.\n    * rewrite Nat.add_succ_r Nat.add_1_r. eapply (IHctx _ (S n)).\n      rewrite -[_ + _](Nat.add_succ_r n #|ctx|) /= Hl.\n      rewrite /shiftnP.\n      nat_compare_specs => /= //.\nQed.\n\n(** This is less precise than the strengthenP lemma above *)\nLemma on_free_vars_lift_impl (p : nat -> bool) (n k : nat) (t : term) :\n  on_free_vars (shiftnP k p) t ->\n  on_free_vars (shiftnP (n + k) p) (lift n k t).\nProof.\n  rewrite -(on_free_vars_lift _ n k t).\n  eapply on_free_vars_impl.\n  intros i.\n  rewrite /shiftnP /strengthenP.\n  repeat nat_compare_specs => /= //.\n  now replace (i - n - k) with (i - (n + k)) by lia.\nQed.\n\n\nLemma foron_free_vars_extended_subst brctx p :\n  on_free_vars_ctx p brctx ->\n  forallb (on_free_vars (shiftnP (context_assumptions brctx) p))\n    (extended_subst brctx 0).\nProof.\n  move/on_free_vars_extended_subst.\n  eapply forallb_impl.\n  intros x hin.\n  rewrite Nat.add_0_r shiftnP0.\n  eapply on_free_vars_impl.\n  intros i. rewrite /orP /strengthenP /= /occ_betweenP /shiftnP.\n  repeat nat_compare_specs => /= //.\n  now rewrite orb_false_r.\nQed.\n\nLemma on_free_vars_fix_subst P mfix idx :\n  on_free_vars P (tFix mfix idx) ->\n  forallb (on_free_vars P) (fix_subst mfix).\nProof.\n  move=> /=; rewrite /fix_subst.\n  intros hmfix. generalize hmfix.\n  induction mfix at 2 4; simpl; auto.\n  move/andP => [ha hm]. rewrite IHm // andb_true_r //.\nQed.\n\nLemma on_free_vars_unfold_fix P mfix idx narg fn :\n  unfold_fix mfix idx = Some (narg, fn) ->\n  on_free_vars P (tFix mfix idx) ->\n  on_free_vars P fn.\nProof.\n  rewrite /unfold_fix.\n  destruct nth_error eqn:hnth => // [=] _ <- /=.\n  intros hmfix; generalize hmfix.\n  move/forallb_All/(nth_error_all hnth) => /andP [] _ Hbody.\n  eapply on_free_vars_subst; len => //.\n  eapply (on_free_vars_fix_subst _ _ idx) => //.\nQed.\n\nLemma on_free_vars_cofix_subst P mfix idx :\n  on_free_vars P (tCoFix mfix idx) ->\n  forallb (on_free_vars P) (cofix_subst mfix).\nProof.\n  move=> /=; rewrite /cofix_subst.\n  intros hmfix. generalize hmfix.\n  induction mfix at 2 4; simpl; auto.\n  move/andP => [ha hm]. rewrite IHm // andb_true_r //.\nQed.\n\nLemma on_free_vars_unfold_cofix P mfix idx narg fn :\n  unfold_cofix mfix idx = Some (narg, fn) ->\n  on_free_vars P (tCoFix mfix idx) ->\n  on_free_vars P fn.\nProof.\n  rewrite /unfold_cofix.\n  destruct nth_error eqn:hnth => // [=] _ <- /=.\n  intros hmfix; generalize hmfix.\n  move/forallb_All/(nth_error_all hnth) => /andP [] _ Hbody.\n  eapply on_free_vars_subst; len => //.\n  eapply (on_free_vars_cofix_subst _ _ idx) => //.\nQed.\n\nLemma lenm_eq {n m} : n <= m -> n - m = 0.\nProof. lia. Qed.\n\nLemma addnP_shiftnP_comm n (P : nat -> bool) : P 0 -> addnP 1 (shiftnP n P) =1 shiftnP n (addnP 1 P).\nProof.\n  intros p0 i; rewrite /addnP /shiftnP /=.\n  repeat nat_compare_specs => /= //.\n  - now rewrite (lenm_eq H0).\n  - lia_f_equal.\nQed.\n\nLemma on_ctx_free_vars_concat P Γ Δ :\n  on_ctx_free_vars (shiftnP #|Δ| P) (Γ ,,, Δ) =\n  on_ctx_free_vars P Γ && on_ctx_free_vars (shiftnP #|Δ| P) Δ.\nProof.\n  rewrite /on_ctx_free_vars alli_app.\n  rewrite /= alli_shiftn andb_comm; f_equal.\n  eapply alli_ext => i d /=.\n  rewrite {1}/shiftnP. nat_compare_specs.\n  replace (#|Δ| + i - #|Δ|) with i by lia.\n  simpl. f_equal.\n  replace (S (#|Δ| + i)) with (S i + #|Δ|) by lia.\n  now rewrite -addnP_add addnP_shiftnP.\nQed.\n\nLemma on_ctx_free_vars_tip P d : on_ctx_free_vars P [d] = P 0 ==> on_free_vars_decl (addnP 1 P) d.\nProof.\n  now rewrite /on_ctx_free_vars /= /= andb_true_r.\nQed.\n\nLemma shiftnPS n P : shiftnP (S n) P n.\nProof.\n  rewrite /shiftnP /=.\n  now nat_compare_specs.\nQed.\n\nLemma shiftnPSS n i P : shiftnP (S n) P (S i) = shiftnP n P i.\nProof.\n  rewrite /shiftnP /=. lia_f_equal.\nQed.\n\nLemma closedP_xpredT n i : closedP n xpredT i -> xpredT i.\nProof.\n  rewrite /closedP /xpredT. auto.\nQed.\n\nLemma on_free_vars_ctx_on_ctx_free_vars {P Γ} :\n  on_ctx_free_vars (PCUICOnFreeVars.shiftnP #|Γ| P) Γ =\n  on_free_vars_ctx P Γ.\nProof.\n  induction Γ => /= //.\n  rewrite /on_free_vars_ctx /= alli_app /= andb_true_r; len.\n  setoid_rewrite <-(shiftnP_add 1 #|Γ|); rewrite addnP_shiftnP andb_comm.\n  f_equal. rewrite /on_free_vars_ctx in IHΓ. rewrite -IHΓ.\n  rewrite (alli_shift _ _ 1) /=.\n  apply alli_ext => i d /=.\n  now rewrite shiftnPSS -(Nat.add_1_r (S i)) -addnP_add addnP_shiftnP.\nQed.\n\n(* Lemma on_ctx_free_vars_impl {P Q Γ} *)\n\nLemma on_free_vars_ctx_on_ctx_free_vars_xpredT {P Γ} :\n  on_free_vars_ctx P Γ ->\n  on_ctx_free_vars xpredT Γ.\nProof.\n  move/(on_free_vars_ctx_impl _ xpredT _ ltac:(easy)).\n  now rewrite -on_free_vars_ctx_on_ctx_free_vars shiftnP_xpredT.\nQed.\n\nLemma on_ctx_free_vars_extend P Γ Δ :\n  on_ctx_free_vars (shiftnP #|Δ| P) (Γ ,,, Δ) =\n  on_ctx_free_vars P Γ && on_free_vars_ctx P Δ.\nProof.\n  rewrite on_ctx_free_vars_concat => //. f_equal.\n  apply on_free_vars_ctx_on_ctx_free_vars.\nQed.\n\nLemma on_free_vars_fix_context P mfix :\n  All (fun x : def term =>\n      test_def (on_free_vars P) (on_free_vars (shiftnP #|mfix| P)) x)\n      mfix ->\n  on_free_vars_ctx P (fix_context mfix).\nProof.\n  intros a.\n  assert (All (fun x => on_free_vars P x.(dtype)) mfix).\n  { solve_all. now move/andP: H=> []. } clear a.\n  induction mfix using rev_ind; simpl; auto.\n  rewrite /fix_context /= mapi_app List.rev_app_distr /=.\n  rewrite /on_free_vars_ctx /= alli_app. len.\n  rewrite andb_true_r.\n  eapply All_app in X as [X Hx].\n  depelim Hx. clear Hx.\n  specialize (IHmfix X).\n  rewrite /on_free_vars_ctx in IHmfix.\n  rewrite IHmfix /= /on_free_vars_decl /test_decl /= /=.\n  apply on_free_vars_lift0.\n  now rewrite addnP_shiftnP.\nQed.\n\nLemma test_context_k_on_free_vars_ctx P ctx :\n  test_context_k (fun k => on_free_vars (shiftnP k P)) 0 ctx =\n  on_free_vars_ctx P ctx.\nProof.\n  now rewrite test_context_k_eq.\nQed.\n\n(* Not necessary for the above lemma, but still useful at some point presumably,\n   e.g. for strenghtening *)\n(*\nLemma on_free_vars_case_predicate_context {cf} {Σ} {wfΣ : wf Σ} {P ci mdecl idecl p} :\n   let pctx := case_predicate_context ci mdecl idecl p in\n   declared_inductive Σ ci mdecl idecl ->\n   wf_predicate mdecl idecl p ->\n   forallb (on_free_vars P) (pparams p) ->\n   on_free_vars (shiftnP #|pcontext p| P) (preturn p) ->\n   on_free_vars_ctx P pctx.\n Proof.\n   intros pctx decli wfp wfb havp.\n   rewrite /pctx /case_predicate_context /case_predicate_context_gen\n     /pre_case_predicate_context_gen /ind_predicate_context.\n   set (ibinder := {| decl_name := _ |}).\n   rewrite -on_free_vars_map2_cstr_args /=; len.\n   { eapply (wf_predicate_length_pcontext wfp). }\n   rewrite alli_app; len; rewrite andb_true_r.\n   apply andb_true_iff. split.\n   - rewrite -/(on_free_vars_ctx P _).\n     rewrite (on_free_vars_ctx_all_term _ _ Universe.type0).\n     rewrite -(subst_it_mkProd_or_LetIn _ _ _ (tSort _)).\n     apply on_free_vars_subst.\n     { rewrite forallb_rev => //. }\n     rewrite -on_free_vars_ctx_all_term.\n     rewrite on_free_vars_ctx_subst_instance.\n     rewrite (on_free_vars_ctx_all_term _ _ (Universe.type0)).\n     rewrite -(expand_lets_it_mkProd_or_LetIn _ _ 0 (tSort _)).\n     eapply on_free_vars_expand_lets_k; len.\n     * rewrite (wf_predicate_length_pars wfp).\n       apply (declared_minductive_ind_npars decli).\n     * eapply closed_ctx_on_free_vars.\n       apply (declared_inductive_closed_params decli).\n     * eapply on_free_vars_impl; cycle 1.\n       { rewrite <- on_free_vars_ctx_all_term.\n         instantiate (1 := closedP #|mdecl.(ind_params)| xpredT).\n         eapply closedn_ctx_on_free_vars.\n         move: (declared_inductive_closed_pars_indices wfΣ decli).\n         now rewrite closedn_ctx_app => /andP []. }\n        intros i'.\n       rewrite /substP /= /closedP /shiftnP. len.\n       now repeat nat_compare_specs => /= //.\n   - rewrite /on_free_vars_decl /ibinder /test_decl /= /foroptb /=.\n     rewrite on_free_vars_mkApps /= forallb_app /=.\n     rewrite on_free_vars_to_extended_list /= andb_true_r.\n     rewrite -/(is_true _).\n     rewrite forallb_map. unshelve eapply (forallb_impl _ _ _ _ wfb).\n     intros. simpl.\n     eapply on_free_vars_lift0. now rewrite addnP_shiftnP.\n Qed.\n\n Lemma on_free_vars_case_branch_context {cf} {Σ} {wfΣ : wf Σ} {P ci i mdecl idecl p br cdecl} :\n   let brctx := case_branch_context ci mdecl p (forget_types (bcontext br)) cdecl in\n   declared_constructor Σ (ci, i) mdecl idecl cdecl ->\n   wf_predicate mdecl idecl p ->\n   wf_branch cdecl br ->\n   forallb (on_free_vars P) (pparams p) ->\n   on_free_vars_ctx P brctx.\n Proof.\n   intros brctx decli wfp wfb havp.\n   rewrite /brctx /case_branch_context /case_branch_context_gen.\n   rewrite (on_free_vars_ctx_all_term _ _ Universe.type0).\n   rewrite -(subst_it_mkProd_or_LetIn _ _ _ (tSort _)).\n   apply on_free_vars_subst => //.\n   { rewrite forallb_rev //. }\n   rewrite -(expand_lets_it_mkProd_or_LetIn _ _ 0 (tSort _)).\n   eapply on_free_vars_expand_lets_k; len.\n   * rewrite (wf_predicate_length_pars wfp).\n     apply (declared_minductive_ind_npars decli).\n   * eapply closed_ctx_on_free_vars.\n     rewrite closedn_subst_instance_context.\n     apply (declared_inductive_closed_params decli).\n   * rewrite -(subst_it_mkProd_or_LetIn _ _ _ (tSort _)).\n     eapply on_free_vars_impl; cycle 1.\n     + eapply (on_free_vars_subst_gen _ P).\n       { eapply on_free_vars_terms_inds. }\n       rewrite -on_free_vars_ctx_all_term.\n       rewrite on_free_vars_ctx_subst_instance.\n       rewrite -on_free_vars_map2_cstr_args.\n       { len. apply (wf_branch_length wfb). }\n       instantiate (1 := closedP (#|mdecl.(ind_bodies)| + #|mdecl.(ind_params)|) xpredT).\n       eapply closedn_ctx_on_free_vars.\n       now move/andP: (declared_constructor_closed wfΣ decli) => [] /andP [].\n     + intros i'.\n       rewrite /substP /= /closedP /shiftnP. len.\n       now repeat nat_compare_specs => /= //.\n Qed.\n*)\n\nLemma on_free_vars_ctx_inst_case_context P n pars puinst ctx :\n  n = #|pars| ->\n  forallb (on_free_vars P) pars ->\n  test_context_k (fun k => on_free_vars (closedP k xpredT)) n ctx ->\n  on_free_vars_ctx P (inst_case_context pars puinst ctx).\nProof.\n  intros hpars hn.\n  rewrite /inst_case_context.\n  rewrite test_context_k_eq.\n  rewrite (on_free_vars_ctx_all_term _ _ Universe.type0).\n  rewrite -(subst_it_mkProd_or_LetIn _ _ _ (tSort _)).\n  intros a.\n  apply on_free_vars_subst => //.\n  { rewrite forallb_rev //. }\n  rewrite -on_free_vars_ctx_all_term.\n  rewrite on_free_vars_ctx_subst_instance.\n  len. subst n.\n  rewrite /on_free_vars_ctx.\n  setoid_rewrite shiftnP_add.\n  unshelve eapply (alli_impl _ _ _ _ _ a).\n  cbn; intros.\n  rewrite /on_free_vars_decl.\n  eapply test_decl_impl; tea.\n  intros. eapply on_free_vars_impl; tea.\n  intros k. rewrite Nat.add_comm.\n  apply closedP_shiftnP_impl.\nQed.\n\nLemma on_ctx_free_vars_snoc {P Γ d} :\n  on_ctx_free_vars (shiftnP 1 P) (Γ ,, d) =\n  on_ctx_free_vars P Γ && on_free_vars_decl P d.\nProof.\n  rewrite (on_ctx_free_vars_concat _ _ [_]) /=. f_equal.\n  now rewrite on_ctx_free_vars_tip {1}/shiftnP /= addnP_shiftnP.\nQed.\n\n#[global]\nHint Rewrite @on_ctx_free_vars_snoc : fvs.\n\nLemma test_context_k_closed_on_free_vars_ctx k ctx :\n  test_context_k (fun k => on_free_vars (closedP k xpredT)) k ctx =\n  on_free_vars_ctx (closedP k xpredT) ctx.\nProof.\n  rewrite test_context_k_eq /on_free_vars_ctx.\n  now setoid_rewrite shiftnP_closedP; setoid_rewrite shiftnP_xpredT; setoid_rewrite Nat.add_comm at 1.\nQed.\n\nLemma inv_on_free_vars_decl {P d} :\n  on_free_vars_decl P d ->\n  match d with\n  | {| decl_body := None; decl_type := t |} => on_free_vars P t\n  | {| decl_body := Some b; decl_type := t |} => on_free_vars P b /\\ on_free_vars P t\n  end.\nProof.\n  unfold on_free_vars_decl, test_decl; destruct d; cbn => //.\n  move/andP => [] //. destruct decl_body; cbn => //.\nQed.\n\nLtac inv_on_free_vars :=\n  repeat match goal with\n  | [ H : is_true (on_free_vars_decl _ (vass _ _)) |- _ ] => apply inv_on_free_vars_decl in H; cbn in H\n  | [ H : is_true (on_free_vars_decl _ (vdef _ _ _)) |- _ ] => apply inv_on_free_vars_decl in H as []\n  | [ H : is_true (_ && _) |- _ ] =>\n    move/andP: H => []; intros\n  | [ H : is_true (on_free_vars ?P ?t) |- _ ] =>\n    progress (cbn in H || rewrite on_free_vars_mkApps in H);\n    (move/and5P: H => [] || move/and4P: H => [] || move/and3P: H => [] || move/andP: H => [] ||\n      eapply forallb_All in H); intros\n  | [ H : is_true (test_def (on_free_vars ?P) ?Q ?x) |- _ ] =>\n    move/andP: H => []; rewrite ?shiftnP_xpredT; intros\n  | [ H : is_true (test_context_k _ _ _ ) |- _ ] =>\n    rewrite -> test_context_k_closed_on_free_vars_ctx in H\n  end.\n\nNotation byfvs := (ltac:(cbn; eauto with fvs)) (only parsing).\n\nLemma on_free_vars_vass {P na t} :\n  on_free_vars P t ->\n  on_free_vars_decl P (vass na t).\nProof.\n  rewrite /on_free_vars_decl /= /test_decl /=. rtoProp; tauto.\nQed.\n\nLemma on_free_vars_vdef {P na b t} :\n  on_free_vars P b -> on_free_vars P t ->\n  on_free_vars_decl P (vdef na b t).\nProof.\n  rewrite /on_free_vars_decl /= /test_decl /=. rtoProp; tauto.\nQed.\n\n#[global] Hint Resolve on_free_vars_vass on_free_vars_vdef : fvs.\n\nLemma onctx_All_fold P Q (Γ : context) :\n  onctx P Γ ->\n  (forall Γ x, All_fold Q Γ -> ondecl P x -> Q Γ x) ->\n  All_fold Q Γ.\nProof.\n  intros o H; induction o; constructor; auto.\nQed.\n\nLemma substP_shiftnP_gen k n p :\n  substP k n p (shiftnP (k + n) p) =1 shiftnP k p.\nProof.\n  intros i; rewrite /shiftnP /substP /= /strengthenP /=.\n  repeat nat_compare_specs.\n  - cbn.\n    assert (i + n - (k + n) = i - k) by lia.\n    rewrite H1. now rewrite orb_diag.\nQed.\n\nLemma on_free_vars_ctx_subst_context P s k ctx :\n  on_free_vars_ctx (shiftnP (k + #|s|) P) ctx ->\n  forallb (on_free_vars P) s ->\n  on_free_vars_ctx (shiftnP k P) (subst_context s k ctx).\nProof.\n  intros onctx ons.\n  rewrite (on_free_vars_ctx_all_term _ _ Universe.type0).\n  rewrite -(subst_it_mkProd_or_LetIn _ _ _ (tSort _)).\n  eapply on_free_vars_impl; revgoals.\n  - eapply on_free_vars_subst_gen => //; tea.\n    rewrite -on_free_vars_ctx_all_term //. exact onctx.\n  - intros i. rewrite substP_shiftnP_gen //.\nQed.\n\nLemma on_free_vars_ctx_subst_context0 P s ctx :\n  on_free_vars_ctx (shiftnP #|s| P) ctx ->\n  forallb (on_free_vars P) s ->\n  on_free_vars_ctx P (subst_context s 0 ctx).\nProof.\n  intros onctx ons.\n  rewrite -(shiftnP0 P). eapply on_free_vars_ctx_subst_context => /= //.\nQed.\n\nLemma on_free_vars_ctx_lift_context p k n ctx :\n  on_free_vars_ctx p ctx =\n  on_free_vars_ctx (strengthenP k n p) (lift_context n k ctx).\nProof.\n  rewrite !(on_free_vars_ctx_all_term _ _ Universe.type0).\n  rewrite -(lift_it_mkProd_or_LetIn _ _ _ (tSort _)).\n  rewrite on_free_vars_lift => //.\nQed.\n\nLemma on_free_vars_ctx_lift_context0 p n ctx :\n  on_free_vars_ctx (addnP n p) ctx ->\n  on_free_vars_ctx p (lift_context n 0 ctx).\nProof.\n  rewrite {1}(on_free_vars_ctx_lift_context _ 0 n) => h.\n  eapply on_free_vars_ctx_impl; tea.\n  rewrite /strengthenP /= /shiftnP /addnP => i.\n  repeat nat_compare_specs => // /=.\n  now replace (n + (i - n)) with i by lia.\nQed.\n\n\nLemma on_free_vars_ctx_snoc {P Γ d} :\n  on_free_vars_ctx P (Γ ,, d) =\n  on_free_vars_ctx P Γ && on_free_vars_decl (shiftnP #|Γ| P) d.\nProof.\n  rewrite - !on_free_vars_ctx_on_ctx_free_vars /snoc /=.\n  rewrite -(shiftnP_add 1) (on_ctx_free_vars_concat _ _ [_]) /=. f_equal.\n  now rewrite on_ctx_free_vars_tip {1 2}/shiftnP /= addnP_shiftnP.\nQed.\n\nLemma on_free_vars_ctx_snoc_impl {P Γ d} :\n  on_free_vars_ctx P (Γ ,, d) ->\n  on_free_vars_ctx P Γ /\\ on_free_vars_decl (shiftnP #|Γ| P) d.\nProof.\n  now rewrite on_free_vars_ctx_snoc => /andP.\nQed.\n\nLemma on_free_vars_ctx_smash P Γ acc :\n  on_free_vars_ctx P Γ ->\n  on_free_vars_ctx (shiftnP #|Γ| P) acc ->\n  on_free_vars_ctx P (smash_context acc Γ).\nProof.\n  induction Γ in P, acc |- *.\n  - cbn. now rewrite shiftnP0.\n  - destruct a as [na [b|] ty].\n    * rewrite /= on_free_vars_ctx_snoc /= => /andP[] onΓ.\n      rewrite /on_free_vars_decl /test_decl /= /= => /andP[] onb onty onacc.\n      eapply IHΓ => //.\n      eapply on_free_vars_ctx_subst_context0 => /= //.\n      + rewrite shiftnP_add //.\n      + now rewrite onb //.\n    * rewrite /= on_free_vars_ctx_snoc /= => /andP[] onΓ ont onacc.\n      eapply IHΓ => //.\n      rewrite -on_free_vars_ctx_on_ctx_free_vars /=; len.\n      rewrite shiftnP_add -Nat.add_assoc -(shiftnP_add).\n      rewrite on_ctx_free_vars_concat.\n      rewrite on_free_vars_ctx_on_ctx_free_vars onacc /=.\n      now rewrite /on_ctx_free_vars /= ont.\nQed.\n\nLemma on_free_vars_ctx_subst_context_xpredT s ctx :\n  on_free_vars_ctx xpredT ctx ->\n  forallb (on_free_vars xpredT) s ->\n  on_free_vars_ctx xpredT (subst_context s 0 ctx).\nProof.\n  intros onctx ons.\n  apply on_free_vars_ctx_subst_context0 => //.\n  rewrite shiftnP_xpredT //.\nQed.\n\nLemma on_free_vars_ctx_All_fold P Γ :\n  on_free_vars_ctx P Γ <~> All_fold (fun Γ => on_free_vars_decl (shiftnP #|Γ| P)) Γ.\nProof.\n  split.\n  - now move/alli_Alli/Alli_rev_All_fold.\n  - intros a. apply (All_fold_Alli_rev (fun k => on_free_vars_decl (shiftnP k P)) 0) in a.\n    now apply alli_Alli.\nQed.\n\n\nLemma term_on_free_vars_ind :\n  forall (P : (nat -> bool) -> term -> Type),\n    (forall (p : nat -> bool) (i : nat), p i -> P p (tRel i)) ->\n    (forall p (i : ident), P p (tVar i)) ->\n    (forall p (id : nat) (l : list term),\n      All (on_free_vars p) l ->\n      All (P p) l ->\n      P p (tEvar id l)) ->\n    (forall p s, P p (tSort s)) ->\n    (forall p (na : aname) (t : term) dom codom,\n      on_free_vars p dom ->\n      P p dom ->\n      on_free_vars (shiftnP 1 p) codom ->\n      P (shiftnP 1 p) codom ->\n      P p (tProd na dom codom)) ->\n    (forall p (na : aname) (ty : term) (body : term),\n      on_free_vars p ty -> P p ty ->\n      on_free_vars (shiftnP 1 p) body -> P (shiftnP 1 p) body ->\n      P p (tLambda na ty body)) ->\n    (forall p (na : aname) (def : term) (ty : term) body,\n      on_free_vars p def -> P p def ->\n      on_free_vars p ty -> P p ty ->\n      on_free_vars (shiftnP 1 p) body -> P (shiftnP 1 p) body ->\n      P p (tLetIn na def ty body)) ->\n    (forall p (t u : term),\n      on_free_vars p t -> P p t ->\n      on_free_vars p u -> P p u -> P p (tApp t u)) ->\n    (forall p s (u : list Level.t), P p (tConst s u)) ->\n    (forall p (i : inductive) (u : list Level.t), P p (tInd i u)) ->\n    (forall p (i : inductive) (c : nat) (u : list Level.t), P p (tConstruct i c u)) ->\n    (forall p (ci : case_info) (pred : predicate term) discr brs,\n      All (on_free_vars p) pred.(pparams) ->\n      All (P p) pred.(pparams) ->\n      on_free_vars_ctx (closedP #|pred.(pparams)| xpredT) pred.(pcontext) ->\n      All_fold (fun Γ => ondecl (P (closedP (#|Γ| + #|pred.(pparams)|) xpredT))) pred.(pcontext) ->\n      on_free_vars (shiftnP #|pred.(pcontext)| p) pred.(preturn) ->\n      P (shiftnP #|pred.(pcontext)| p) pred.(preturn) ->\n      on_free_vars p discr ->\n      P p discr ->\n      All (fun br =>\n        [× on_free_vars_ctx (closedP #|pred.(pparams)| xpredT) br.(bcontext),\n          All_fold (fun Γ => ondecl (P (closedP (#|Γ| + #|pred.(pparams)|) xpredT))) br.(bcontext),\n          on_free_vars (shiftnP #|br.(bcontext)| p) br.(bbody) &\n          P (shiftnP #|br.(bcontext)| p) br.(bbody)]) brs ->\n      P p (tCase ci pred discr brs)) ->\n    (forall p (s : projection) (t : term),\n      on_free_vars p t -> P p t -> P p (tProj s t)) ->\n    (forall p (m : mfixpoint term) (i : nat),\n      tFixProp (on_free_vars p) (on_free_vars (shiftnP #|fix_context m| p)) m ->\n      tFixProp (P p) (P (shiftnP #|fix_context m| p)) m -> P p (tFix m i)) ->\n    (forall p (m : mfixpoint term) (i : nat),\n      tFixProp (on_free_vars p) (on_free_vars (shiftnP #|fix_context m| p)) m ->\n      tFixProp (P p) (P (shiftnP #|fix_context m| p)) m -> P p (tCoFix m i)) ->\n    (forall p pr, P p (tPrim pr)) ->\n    forall p (t : term), on_free_vars p t -> P p t.\nProof.\n  intros until t. revert p t.\n  fix auxt 2.\n  move auxt at top.\n  intros p t.\n  destruct t; intros clt;  match goal with\n                 H : _ |- _ => apply H\n              end; auto; simpl in clt;\n            try move/andP: clt => [cl1 cl2];\n            try move/andP: cl2 => [cl2 cl3];\n            try move/andP: cl3 => [cl3 cl4];\n            try move/andP: cl4 => [cl4 cl5];\n            try solve[apply auxt; auto]; simpl in *;\n            try inv_on_free_vars; tas.\n\n  - solve_all.\n  - revert l clt.\n    fix auxl' 1.\n    destruct l; constructor; [|apply auxl'].\n    * apply auxt. simpl in clt. now move/andP: clt  => [clt cll].\n    * now move/andP: clt => [clt cll].\n\n  - solve_all.\n  - revert cl1. generalize (pparams p0).\n    fix auxl' 1.\n    case => [|t' ts] /= //; cbn => /andP[] Ht' Hts; constructor; [apply auxt|apply auxl'] => //.\n  - rewrite -test_context_k_closed_on_free_vars_ctx in cl3.\n    revert cl3. clear -auxt.\n    generalize (pcontext p0).\n    fix auxl 1.\n    intros [].\n    * cbn. intros _. constructor.\n    * cbn. move/andP => [] cll clc.\n      constructor.\n      + now apply auxl.\n      + destruct c as [na [b|] ty]; cbn in *; constructor; cbn; apply auxt || exact tt.\n        { now move/andP: clc => []. }\n        { now move/andP: clc => []. }\n        apply clc.\n\n  - rename cl5 into cl. revert brs cl. clear -auxt.\n    fix auxl' 1.\n    destruct brs; [constructor|].\n    move=> /= /andP [/andP [clctx clb] cll].\n    constructor; tas.\n    * split => //.\n      + now rewrite test_context_k_closed_on_free_vars_ctx in clctx.\n      + move: clctx. clear -auxt.\n        generalize (bcontext b).\n        fix auxl 1.\n        { intros [].\n        * cbn. intros _. constructor.\n        * cbn. move/andP => [] cll clc.\n          constructor.\n          + now apply auxl.\n          + destruct c as [na [b'|] ty]; cbn in *; constructor; cbn; apply auxt || exact tt.\n            { now move/andP: clc => []. }\n            { now move/andP: clc => []. }\n            apply clc. }\n      + now apply auxt.\n    * now apply auxl'.\n\n  - red. len; solve_all;\n     now move/andP: H=> [].\n\n  - red.\n    rewrite fix_context_length.\n    revert clt.\n    generalize (#|mfix|).\n    revert mfix.\n    fix auxm 1.\n    destruct mfix; [constructor|].\n    move=> n /= /andP[] /andP[] clb clty clmfix; constructor.\n    * split => //; apply auxt => //.\n    * now apply auxm.\n\n  - red. len; solve_all;\n    now move/andP: H=> [].\n\n  - red.\n    rewrite fix_context_length.\n    revert clt.\n    generalize (#|mfix|).\n    revert mfix.\n    fix auxm 1.\n    destruct mfix; [constructor|].\n    move=> n /= /andP[] /andP[] clb clty clmfix; constructor.\n    * split => //; apply auxt => //.\n    * now apply auxm.\nDefined.\n\nLemma alpha_eq_on_free_vars P (Γ Δ : context) :\n  All2 (PCUICEquality.compare_decls eq eq) Γ Δ ->\n  on_free_vars_ctx P Γ -> on_free_vars_ctx P Δ.\nProof.\n  induction 1; cbn; auto.\n  rewrite !alli_app /= !andb_true_r.\n  move/andP => [] IH hx.\n  specialize (IHX IH).\n  unfold PCUICOnFreeVars.on_free_vars_ctx in IHX.\n  rewrite IHX /=.\n  len in hx. len. rewrite -(All2_length X).\n  destruct r; cbn in *; subst; auto.\nQed.\n\nLemma on_free_vars_ctx_any_xpredT P Γ :\n  on_free_vars_ctx P Γ -> on_free_vars_ctx xpredT Γ.\nProof.\n  intros. eapply on_free_vars_ctx_impl; tea => //.\nQed.\n\nLemma on_free_vars_ctx_on_ctx_free_vars_closedP Γ :\n  on_ctx_free_vars (closedP #|Γ| xpredT) Γ =\n  on_free_vars_ctx xpred0 Γ.\nProof.\n  rewrite closedP_shiftnP on_free_vars_ctx_on_ctx_free_vars //.\nQed.\n\nLemma on_free_vars_ctx_on_ctx_free_vars_closedP_impl Γ :\n  on_free_vars_ctx xpred0 Γ ->\n  on_ctx_free_vars (closedP #|Γ| xpredT) Γ.\nProof.\n  now rewrite on_free_vars_ctx_on_ctx_free_vars_closedP.\nQed.\n\nLemma on_free_vars_ctx_app P Γ Δ :\n  on_free_vars_ctx P (Γ ,,, Δ) =\n  on_free_vars_ctx P Γ && on_free_vars_ctx (shiftnP #|Γ| P) Δ.\nProof.\n  rewrite /on_free_vars_ctx List.rev_app_distr alli_app. f_equal.\n  rewrite List.rev_length alli_shift.\n  setoid_rewrite shiftnP_add.\n  setoid_rewrite Nat.add_comm at 1.\n  now setoid_rewrite Nat.add_0_r.\nQed.\n\n#[global] Hint Extern 4 (is_true (on_free_vars_ctx _ (_ ,,, _))) =>\n  rewrite on_free_vars_ctx_app : fvs.\n\nLemma on_ctx_free_vars_snoc_ass P Γ na ty :\n  on_ctx_free_vars P Γ ->\n  on_free_vars P ty ->\n  on_ctx_free_vars (PCUICOnFreeVars.shiftnP 1 P) (Γ ,, vass na ty).\nProof.\n  now rewrite on_ctx_free_vars_snoc => -> /=; rewrite /on_free_vars_decl /test_decl /=.\nQed.\n\nLemma on_ctx_free_vars_snoc_def P Γ na def ty :\n  on_ctx_free_vars P Γ ->\n  on_free_vars P ty ->\n  on_free_vars P def ->\n  on_ctx_free_vars (PCUICOnFreeVars.shiftnP 1 P) (Γ ,, vdef na def ty).\nProof.\n  now rewrite on_ctx_free_vars_snoc => -> /=; rewrite /on_free_vars_decl /test_decl /= => -> ->.\nQed.\n#[global] Hint Resolve on_ctx_free_vars_snoc_def on_ctx_free_vars_snoc_ass : pcuic.\n\nLemma on_ctx_free_vars_snocS P Γ d :\n  on_ctx_free_vars (PCUICOnFreeVars.shiftnP (S #|Γ|) P) (d :: Γ) =\n  on_ctx_free_vars (PCUICOnFreeVars.shiftnP #|Γ| P) Γ && on_free_vars_decl (PCUICOnFreeVars.shiftnP #|Γ| P) d.\nProof.\n  rewrite -(shiftnP_add 1).\n  now rewrite on_ctx_free_vars_snoc.\nQed.\n\nLemma on_ctx_free_vars_inst_case_context P Γ pars puinst pctx :\n  forallb (on_free_vars P) pars ->\n  test_context_k (fun k : nat => on_free_vars (closedP k xpredT)) #|pars| pctx ->\n  on_ctx_free_vars P Γ ->\n  on_ctx_free_vars (shiftnP #|pctx| P) (Γ ,,, inst_case_context pars puinst pctx).\nProof.\n  intros.\n  relativize #|pctx|; [erewrite on_ctx_free_vars_concat|]; try now len.\n  rewrite H1 /=.\n  rewrite on_free_vars_ctx_on_ctx_free_vars.\n  eapply on_free_vars_ctx_inst_case_context; trea.\nQed.\n#[global] Hint Resolve on_ctx_free_vars_inst_case_context : fvs.\n\nLemma on_free_vars_ctx_inst_case_context_weak P Γ pars puinst pctx :\n  forallb (on_free_vars (shiftnP #|Γ| P)) pars ->\n  test_context_k (fun k : nat => on_free_vars (closedP k xpredT)) #|pars| pctx ->\n  on_free_vars_ctx P Γ ->\n  on_free_vars_ctx P (Γ ,,, inst_case_context pars puinst pctx).\nProof.\n  intros.\n  rewrite on_free_vars_ctx_app H1 /=.\n  eapply on_free_vars_ctx_inst_case_context; trea.\nQed.\n#[global] Hint Resolve on_free_vars_ctx_inst_case_context : fvs.\n\nLemma on_ctx_free_vars_fix_context P Γ mfix :\n  All (fun x : def term => test_def (on_free_vars P) (on_free_vars (shiftnP #|mfix| P)) x) mfix ->\n  on_ctx_free_vars P Γ ->\n  on_ctx_free_vars (shiftnP #|mfix| P) (Γ ,,, fix_context mfix).\nProof.\n  intros.\n  relativize #|mfix|; [erewrite on_ctx_free_vars_concat|].\n  - rewrite H /=.\n    rewrite on_free_vars_ctx_on_ctx_free_vars.\n    eapply on_free_vars_fix_context => //.\n  - now len.\nQed.\n\nLemma on_free_vars_ctx_fix_context_weak P Γ mfix :\n  All (fun x : def term => test_def (on_free_vars (shiftnP #|Γ| P)) (on_free_vars (shiftnP #|mfix| (shiftnP #|Γ| P))) x) mfix ->\n  on_free_vars_ctx P Γ ->\n  on_free_vars_ctx P (Γ ,,, fix_context mfix).\nProof.\n  intros.\n  rewrite -on_free_vars_ctx_on_ctx_free_vars; len.\n  rewrite -shiftnP_add.\n  eapply on_ctx_free_vars_fix_context => //.\n  now rewrite on_free_vars_ctx_on_ctx_free_vars.\nQed.\n\n#[global] Hint Resolve on_ctx_free_vars_fix_context : fvs.\n#[global] Hint Resolve on_free_vars_ctx_fix_context_weak : fvs.\n#[global] Hint Resolve on_ctx_free_vars_snoc_ass on_ctx_free_vars_snoc_def : fvs.\n#[global] Hint Resolve on_ctx_free_vars_inst_case_context : fvs.\n#[global] Hint Extern 3 (is_true (_ && _)) => apply/andP; idtac : fvs.\n#[global] Hint Extern 4 (is_true (on_ctx_free_vars (shiftnP _ xpred0) _)) =>\n  rewrite on_free_vars_ctx_on_ctx_free_vars : fvs.\n\nLemma on_free_vars_ctx_snoc_ass P Γ na t :\n  on_free_vars_ctx P Γ ->\n  on_free_vars (shiftnP #|Γ| P) t ->\n  on_free_vars_ctx P (Γ ,, vass na t).\nProof.\n  intros onΓ ont.\n  rewrite on_free_vars_ctx_snoc onΓ /=; eauto with fvs.\nQed.\n\nLemma on_free_vars_ctx_snoc_def P Γ na b t :\n  on_free_vars_ctx P Γ ->\n  on_free_vars (shiftnP #|Γ| P) b ->\n  on_free_vars (shiftnP #|Γ| P) t ->\n  on_free_vars_ctx P (Γ ,, vdef na b t).\nProof.\n  intros onΓ ont.\n  rewrite on_free_vars_ctx_snoc onΓ /=; eauto with fvs.\nQed.\n\n#[global] Hint Resolve on_free_vars_ctx_snoc_ass on_free_vars_ctx_snoc_def : fvs.\n\nLemma on_free_vars_all_subst P s :\n  All (on_free_vars P) s ->\n  forall x, on_free_vars xpredT ((s ⋅n ids) x).\nProof.\n  induction 1 => n; rewrite /subst_consn /subst_compose /=.\n  - rewrite nth_error_nil //.\n  - destruct n => /=; eauto.\n    now eapply on_free_vars_impl; 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/pcuic/theories/Syntax/PCUICOnFreeVars.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2817549316167985}}
{"text": "Require Import Common. \nRequire TRS. \nNotation type2 := TRS.type2. \nNotation type1 := TRS.type1. \n\nSection expr. \n  (* Environement is the same in the whole expr *)\n  Import TRS. \n  Inductive expr1' : list type2 ->  type1 -> Type :=\n  | Elet : forall E F t t', pattern1 F t -> expr1' E t -> expr1' (E++F) t' -> expr1' E t'\n  | Eprim : forall E args res (f : builtin args res), dlist  (fun t => expr1' E (T01 t)) args -> expr1' E (T01 res) \n  | Econstant : forall E (c : constant), expr1' E (T01 (cst_ty c))\n  (* get a register of level 1 *)\n  | Eget : forall E t (v : var E (Treg t)), expr1' E (t)\n  (* get for input/output  *)\n  | Eget_input  : forall E t (v : var E (Tinput t)), expr1' E (t)\n  | Eget_output : forall E t (v : var E (Toutput t)), expr1' E (t)\n                                                     \n  (* TODO: Use Tenum instead of Tint *)\n  | Eget_regfile : forall E size t (v : var E  (Tregfile size t)) n, expr1' E (T01 (Tint n)) -> expr1' E t\n  | Efirst : forall E n t (v : var E (Tfifo n t)), expr1' E t\n  | Eisfull : forall E n t (v : var E (Tfifo n t)), expr1' E (T01 Tbool)\n  | Eisempty : forall E n t (v : var E (Tfifo n t)), expr1' E (T01 Tbool)\n                                                    \n  | Eunion : forall E {id fl} (case : expr1'_disjunct E fl), expr1' E (Tunion id fl)\n  | Etuple : forall E l (v : dlist (expr1' E) l), expr1' E (Ttuple l)\n  with expr1'_disjunct : list type2 -> list (ident * type1) -> Type :=\n  | expr1'_disjunct_hd:forall E id t q, expr1' E t -> expr1'_disjunct E ((id,t) :: q) \n  | expr1'_disjunct_tl:forall E id t q, expr1'_disjunct E q -> expr1'_disjunct E ((id,t)::q) . \n\n  Inductive expr2 E : type2 -> Type :=\n  | Eset : forall t, expr1' E t ->  expr2 E (Treg t)\n  | Eset_regfile : forall size t n,\n                     expr1' E (T01 (Tint n)) -> expr1' E t -> expr2 E (Tregfile size t) \n  (* operations on fifos *)\n  | Epush : forall n t, expr1' E t -> expr2 E (Tfifo n t)\n  | Epop  : forall n t, expr2 E (Tfifo n t) (* forgets the first element *)\n  | Epushpop : forall n t, expr1' E t -> expr2 E (Tfifo n t)\n  | Eclear : forall n t, expr2 E (Tfifo n t)\n\n  (* set an output *)\n  | Eset_output : forall t, expr1' E t -> expr2 E (Toutput t)\n  (* do nothing *)\n  | Enop : forall t, expr2 E t.\n  \n  Definition expr2_vector (E : list type2) := dlist (@expr2 E). \nEnd expr. \n\nRecord rule mem :=\n  mk_rule \n    {\n      cond: expr1' mem (TRS.T01 Tbool);\n      rhs : expr2_vector mem mem\n    }.\n\nSection i. \n\nDefinition repl E t := match t with\n                         | TRS.Treg t' => expr1' E t'\n                         | _  => var E t\n                       end. \n\n\nFixpoint insert (t : type2) (G : list type2) (n : nat) {struct n} : list type2 :=\n  match n with\n    | O => t :: G\n    | S n' => match G with\n               | nil => t :: G\n               | t' :: G' => t' :: insert t G' n'\n             end\n  end.\n\nFixpoint lift_var t G (x : var G t) t' n : var (insert t' G n) t :=\n  match x with \n    | var_0 G' _ => \n        match n with \n          | 0 => var_S var_0\n          | _ => var_0 \n        end \n    | var_S G' _ t'' x'  => \n        match n with \n          | 0 => var_S (var_S x')\n          | S n' => \n              (var_S (lift_var _ _ x' _ n') : var (insert t' (_ :: G') (S n')) t'')\n        end\n  end.\nEnd i. \n\nDefinition lift_expr1' : forall E t, TRS.expr1 E t -> expr1' E t. Admitted. \n\nSection t. \n  Variable mem : list type2. \n\n  Variable R : TRS.rule mem. \n  \n  Definition S : rule mem.\n  constructor. \n\n  (* map each variable from context G to a replacement that is valid in context G' *)\n  Definition subst G G' := dlist (repl G') G. \n\n  Definition repl_0 E x : repl (x :: E) x. \n  Proof.\n    unfold repl; destruct x; try apply var_0. apply Eget. apply var_0. \n  Defined. \n  \n  Definition lift_expr E x a:   expr1' E x -> expr1' (a :: E) x. \n  Proof. \n  Admitted. \n\n  Definition lift_repl a E x  : repl E x -> repl (a :: E) x. \n  Proof. \n    unfold repl; destruct x; try apply (var_S). apply lift_expr.  \n  Defined. \n  \n  Definition subst_id : forall E, subst E E. \n  Proof. \n    unfold subst. \n    induction E. constructor.\n    constructor.\n    apply repl_0. \n  \n    apply (dlist_map (lift_repl a E ) _ IHE).\n  Defined. \n\n  Definition subst_compose : forall E F G, subst E F -> subst F G -> subst E G.\n  Proof. \n    unfold subst. \n    intros. \n \n  Definition lifting_transformation E F  : (forall t, expr1' E t -> expr1' F t) -> forall t, repl E t -> repl F t. \n  Admitted. \n   \n  eapply dlist_map. \n  2 : apply X. \n  apply lifting_transformation. \n  \n  Definition map_subst t E F (s : subst E F) ( x : expr1' E t) :  expr1' F t. \n  induction x. \n  \n  refine (let f := fix f t E F s x : expr1' F t :=\n  match x with\n    | Elet E F t t' patF expr body => _\n    | Eprim E args res f x => _\n    | Econstant E c =>  _ \n    | Eget E t v => _\n    | Eget_input E t v => _\n    | Eget_output E t v => _\n    | Eget_regfile E size t v n x => _\n    | Efirst E n t v => _\n    | Eisfull E n t v => _\n    | Eisempty E n t v => _\n    | Eunion E id fl case => _\n    | Etuple E l v => _\n  end\n          in f t E F s x). \n  admit. \n  apply Eprim. \n  intros. \n  induction X1. \n  \n  Definition where_to_subst E F : TRS.where_clause E F -> subst F E. \n  induction 1.\n  apply subst_id. \n  eapply subst_compose. apply IHX. \n eapply dlist_map. \n intros. \n eapply lifting_transformation. \n  intros. \neapply Elet.  apply p.\n  apply lift_expr1'. apply e. apply X1. apply X0. apply subst_id. \nDefined. \n  apply lift_expr1'. \n  intros. \n  eapply Elet. \n  apply p. apply lift_expr1'. apply e. \n  auto.\n  Defined.\n\n  Definition abort_pattern2_vector E F :\n    TRS.pattern2_vector E F -> \n    TRS.where_clause E F. \n\n  refine (let f := fix f E F (p : TRS.pattern2_vector E F) : TRS.where_clause E F :=\n              match p with \n                | TRS.pattern2_vector_nil =>  _\n                | TRS.pattern2_vector_cons E' F' t q \n                                       pat pats => \n                    _\n              end\n          in \n            f E F\n              \n         ).\n  constructor. \n  auto. \n  Definition w_append : forall A B C, TRS.where_clause A B -> TRS.where_clause B C -> \n                                 TRS.where_clause A C. \n  Admitted. \n  apply f in pats. \n  \n  Definition test : forall E t, TRS.pattern2 E t -> TRS.where_clause (t :: nil) E.  \n  intros E t. \n  refine (fun X => match X with \n              TRS.Pvar2 t' =>  TRS.where_clause_nil _\n            | TRS.Phole2 t' =>  _ \n            | TRS.Plift E' t'  p =>  _\n          end\n         ). \n  \n  inversion pat;  subst; simpl. \n  \n  \n  simpl. \n\neapply f in pats. \n  eapply w_append. \n  2: apply X. \n\nEnd t. \n  Fixpoint pattern2_vector_match E F (P : pattern2_vector E F ) : \n    eval_type2_list E -> option (eval_env eval_type2 F) :=\n    match P with \n      | pattern2_vector_nil => fun _ => Some tt\n      | pattern2_vector_cons E F t q p2Et p2vFq =>\n          fun X => \n            let (A, B) := X in\n              do X <- pattern2_match E t p2Et A;\n              do Y <- pattern2_vector_match _ _ p2vFq B;\n              Some (append_envs _ _  X Y)\n    end. \n  \n  Fixpoint where_clause_match {E F} (W : where_clause E F) {struct W}: \n    eval_type2_list E -> option (eval_type2_list F) :=\n    match W with \n      | where_clause_nil _ => fun X => Some X\n      | where_clause_cons E F G t pat exp w =>\n          fun x =>\n            do e <- eval_expr1' _ x t exp;\n            do B <- pattern1_match F t pat e;\n            where_clause_match w (append_envs _ _ x B  )\n    end. \n\n  Definition eval_expr2_vector mem env (v : @expr2_vector env mem) : \n    eval_type2_list env -> eval_type2_list mem -> option (eval_type2_list mem) := \n    (fun ENV MEM =>  (dlist_fold _ _ _ (eval_expr2 _ ENV) mem v MEM)). \n\n  Definition eval_rule mem (r : rule mem) : relation (eval_type2_list mem) :=\n    fun M1 M2 => \n      exists E, exists F,  (pattern2_vector_match _ _ (lhs r) M1 = Some E\n           /\\ where_clause_match (where_clauses _ r) E = Some F\n           /\\ eval_expr1' _ F _ (cond r) = Some true\n           /\\ eval_expr2_vector _ _ (rhs r) F M1 = Some M2). \n  \n  Fixpoint eval_rules ty (l : list (rule ty)) : relation (eval_type2_list (ty)) :=\n    match l with\n      | nil => fun _ _ => True\n      | cons t q => union (eval_rule ty t) (eval_rules ty q)\n    end. \n  \n  Definition eval_TRS T := eval_rules _ (trs_rules T). \n  \n  Definition run_rule ty (r : rule ty) : eval_type2_list ty -> option (eval_type2_list ty) :=\n    fun M1 => \n      do E <- pattern2_vector_match _ _ (lhs  r) M1;\n      do F <- where_clause_match (where_clauses _ r) E;\n\n      if (@eval_expr1' (env2  r) F _ (cond  r))\n      then (@eval_expr2_vector _ _  (rhs  r) F M1)\n      else None . \n  \n  \n  Fixpoint iter_option {A} n (f : A -> option A) x :=\n    match n with \n      | 0 => Some x\n      | S n => match f x with | None => Some x | Some x => iter_option n f x end \n    end. \n  \n  Fixpoint first_rule {ty} (l : list (rule ty)) x :=\n    match l with \n      | nil => Some x\n      | cons t q => \n          match run_rule _ t x with \n            | None => first_rule q x\n            | Some x => Some x \n          end\n    end. \n\n  Fixpoint run_unfair n T x :=\n    match n with \n      | 0 => Some x\n    | S n => \n        match first_rule (trs_rules T) x with \n          | None => Some x\n          | Some x => run_unfair n T x\n        end\n  end. \n\n  Notation \"[]\" := nil.\n  Notation \"a :: b\" := (cons a b). \n  Notation \"[ a ; .. ; b ]\" := (a :: .. (b :: []) ..).\n  Open Scope string_scope.\n  \n  Delimit Scope expr_scope with expr. \n  Notation \"[| x , .. , z |]\"  :=  (Etuple _ _ (dlist_cons x .. (dlist_cons z dlist_nil ).. )) (at level  0): expr_scope.\n\n  \n  Notation \"{< f ; x ; y >}\" := (Eprim _ _ _ (f) (dlist_cons  x (dlist_cons y dlist_nil))).\n\n  Notation \"{< f ; x >}\" := (Eprim _ _ _ (f) (dlist_cons x dlist_nil)).\n\n  Notation \"~ x\" :=  ({< BI_negb ; x >}) : expr_scope. \n  Notation \"a || b\" := ({< BI_orb ; a ; b >}) : expr_scope. \n  Notation \"a - b\" := ({< BI_minus _ ; a ; b >}) : expr_scope. \n  Notation \"a + b\" := ({< BI_plus _ ; a ; b >}) : expr_scope. \n  Notation \"a = b\" := ({< BI_eq _ ; a ; b >}) : expr_scope. \n  Notation \"a < b\" := ({< BI_lt _ ; a ; b >}) : expr_scope. \n  Notation \"x <= y\" := ((x < y) || (x = y))%expr : expr_scope. \n  Notation \"x <> y\" := (~(x = y))%expr : expr_scope. \n  Notation \"! x\" := (Eget _ _ x) (at level  10) : expr_scope . \n  Notation \"[| x |]\"  :=  (Etuple _ _ (dlist_cons x dlist_nil )) (at level  0): expr_scope.  \n  Notation \"{< x >}\" := (Econstant _ x): expr_scope. \n  \n  Delimit Scope pattern_scope with pattern.    \n  Notation \"[| x , .. , z |]\" := (Ptuple _ _ (pattern_vector_cons _ _ _ _ x .. (pattern_vector_cons _ _ _ _ z pattern_vector_nil ).. )) (at  level 0): pattern_scope.  \n  \n  Notation \"X 'of' u :: q \" := ((X,u)::q) (at level 60, u at next level,  right associativity). \n\n  (* Notations for expr2 *)\n  Delimit Scope expr2_scope with expr2. \n  Arguments Eset_regfile {E} size t n _%expr _%expr.  \n\n  (* Arguments dlist_cons {T P} t q _ _ .  *)\n  (* Arguments dlist_nil {T P}.  *)\n  Notation \"[| x , .. , z |]\"  :=  ((dlist_cons x .. (dlist_cons  z (dlist_nil ) ).. )) (at level  0): expr2_scope.\n  Notation \"'[' key '<-' v ']' \" := ( Eset_regfile  _ _ _  key v )(at level 0, no associativity) : expr2_scope.\n  Notation \"•\" := (Enop _ _) : expr2_scope. \n  \n  Definition mk_rule' {mem} env pat cond expr : rule mem :=\n    mk_rule mem env env pat (where_clause_nil _ ) cond expr. \n", "meta": {"author": "braibant", "repo": "Synthesis", "sha": "922982aaddb8a7a16101ff304c45d24a6265dc2e", "save_path": "github-repos/coq/braibant-Synthesis", "path": "github-repos/coq/braibant-Synthesis/Synthesis-922982aaddb8a7a16101ff304c45d24a6265dc2e/attic/TRSLET.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2817549316167985}}
{"text": "Require Import Raft.\nRequire Import RaftRefinementInterface.\n\nSection RequestVoteTermSanity.\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\n  Definition requestVote_term_sanity (net : network) : Prop :=\n    forall t h mi mt p,\n      In p (nwPackets net) ->\n      pBody p = RequestVote t h mi mt ->\n      t <= currentTerm (snd (nwState net (pSrc p))).\n\n  Class requestVote_term_sanity_interface : Prop :=\n    {\n      requestVote_term_sanity_invariant :\n        forall net,\n          refined_raft_intermediate_reachable net ->\n          requestVote_term_sanity net\n    }.\nEnd RequestVoteTermSanity.", "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/RequestVoteTermSanityInterface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.28170123130031516}}
{"text": "Require Import Preloaded Coq.Lists.List VST.floyd.proofauto.\n\nLemma bt_invert_involution : forall (A : Type) (tree : bt A),\n  bt_invert (bt_invert tree) = tree.\nProof. intros A tree; induction tree; simpl; congruence. Qed.\n\nLemma bt_invert_inorder : forall (A : Type) (tree : bt A),\n  bt_inorder (bt_invert tree) = rev (bt_inorder tree).\nProof.\n  intros A tree; induction tree; simpl; auto.\n  rewrite IHtree1, IHtree2, rev_app_distr; simpl.\n  now rewrite <- app_assoc.\nQed.\n\nLemma btrep_local_facts: forall sigma p,\n   btrep sigma p |--\n   !! (is_pointer_or_null p /\\ (p=nullval <-> sigma=bt_leaf)).\nProof.\n  induction sigma; intros.\n  - unfold btrep.\n    entailer!.\n    split; auto.\n  - unfold btrep; fold btrep.\n    Intros y z.\n    entailer!.\n    split; intros H3.\n    + subst p.\n      eapply field_compatible_nullval; eauto.\n    + discriminate.\nQed.\n\n#[export] Hint Resolve btrep_local_facts : saturate_local.\n\nLemma btrep_valid_pointer: forall sigma p,\n   btrep sigma p |-- valid_pointer p.\nProof.\n  destruct sigma; intros; unfold btrep; fold btrep.\n  - entailer!.\n  - Intros y z.\n    entailer!.\nQed.\n\n#[export] Hint Resolve btrep_valid_pointer : valid_pointer.\n\nLemma body_invert: semax_body Vprog Gprog f_invert invert_spec.\nProof.\n  start_function.\n  forward_if (PROP (isptr p)  LOCAL (temp _p p)  SEP (btrep sigma p)).\n  - forward.\n    rewrite (proj1 H0) by auto.\n    Exists nullval.\n    entailer!.\n  - forward.\n    entailer!.\n    destruct p; simpl in PNp; try now exfalso; try subst i.\n    now simpl.\n  - destruct sigma; unfold btrep; fold btrep.\n    + Intros; subst p; inversion Pp.\n    + Intros y z.\n      forward.\n      forward_call (sigma1, y).\n      Intros vret.\n      do 2 forward.\n      forward_call (sigma2, z).\n      Intros vret0.\n      do 3 forward.\n      simpl; unfold btrep; fold btrep.\n      Exists p vret0 vret.\n      entailer!.\nQed.", "meta": {"author": "DonaldKellett", "repo": "Verified-C-binary-tree-inversion", "sha": "081efcfa6a3e3156916bbf07fbd6c567a5991430", "save_path": "github-repos/coq/DonaldKellett-Verified-C-binary-tree-inversion", "path": "github-repos/coq/DonaldKellett-Verified-C-binary-tree-inversion/Verified-C-binary-tree-inversion-081efcfa6a3e3156916bbf07fbd6c567a5991430/Solution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.281571640036764}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\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(** THIS FILE IS DEPRECATED. *)\n\nRequire Import BinInt Zcompare Zorder.\n\nLocal Open Scope Z_scope.\n\n(** Definition [Z.min] is now [BinInt.Z.min]. *)\n\n(** Exact compatibility *)\n\nNotation Zmin_case := Z.min_case (compat \"8.6\").\nNotation Zmin_case_strong := Z.min_case_strong (compat \"8.6\").\nNotation Zle_min_l := Z.le_min_l (compat \"8.6\").\nNotation Zle_min_r := Z.le_min_r (compat \"8.6\").\nNotation Zmin_glb := Z.min_glb (compat \"8.6\").\nNotation Zmin_glb_lt := Z.min_glb_lt (compat \"8.6\").\nNotation Zle_min_compat_r := Z.min_le_compat_r (only parsing).\nNotation Zle_min_compat_l := Z.min_le_compat_l (only parsing).\nNotation Zmin_idempotent := Z.min_id (only parsing).\nNotation Zmin_n_n := Z.min_id (only parsing).\nNotation Zmin_comm := Z.min_comm (compat \"8.6\").\nNotation Zmin_assoc := Z.min_assoc (compat \"8.6\").\nNotation Zmin_irreducible_inf := Z.min_dec (only parsing).\nNotation Zsucc_min_distr := Z.succ_min_distr (compat \"8.6\").\nNotation Zmin_SS := Z.succ_min_distr (only parsing).\nNotation Zplus_min_distr_r := Z.add_min_distr_r (only parsing).\nNotation Zmin_plus := Z.add_min_distr_r (only parsing).\nNotation Zpos_min := Pos2Z.inj_min (only parsing).\n\n(** Slightly different lemmas *)\n\nLemma Zmin_spec x y :\n  x <= y /\\ Z.min x y = x  \\/  x > y /\\ Z.min x y = y.\nProof.\n Z.swap_greater. rewrite Z.min_comm. destruct (Z.min_spec y x); auto.\nQed.\n\nLemma Zmin_irreducible n m : Z.min n m = n \\/ Z.min n m = m.\nProof. destruct (Z.min_dec n m); auto. Qed.\n\nNotation Zmin_or := Zmin_irreducible (only parsing).\n\nLemma Zmin_le_prime_inf n m p : Z.min n m <= p -> {n <= p} + {m <= p}.\nProof. apply Z.min_case; auto. Qed.\n\nLemma Zpos_min_1 p : Z.min 1 (Zpos p) = 1.\nProof.\n now destruct p.\nQed.\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/theories/ZArith/Zmin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.28157164003676394}}
{"text": "(* Distributed under the terms of the MIT license. *)\nFrom Coq Require Import CRelationClasses.\nFrom MetaCoq.Utils Require Import utils.\nFrom MetaCoq.Common Require Import config.\nFrom MetaCoq.PCUIC Require Import PCUICAst PCUICAstUtils PCUICLiftSubst\n     PCUICUnivSubst PCUICTyping PCUICInduction PCUICReduction PCUICClosed.\n\nRequire Import ssreflect ssrbool.\nFrom Equations Require Import Equations.\n\n(** * Closed single substitution:\n\n    no lifting involved and one term at a time. *)\n\nLocal Ltac inv H := inversion H; subst.\n\nFixpoint csubst t k u :=\n  match u with\n  | tRel n =>\n     match Nat.compare k n with\n    | Datatypes.Eq => t\n    | Gt => tRel n\n    | Lt => tRel (Nat.pred n)\n    end\n  | tEvar ev args => tEvar ev (List.map (csubst t k) args)\n  | tLambda na T M => tLambda na (csubst t k T) (csubst t (S k) M)\n  | tApp u v => tApp (csubst t k u) (csubst t k v)\n  | tProd na A B => tProd na (csubst t k A) (csubst t (S k) B)\n  | tLetIn na b ty b' => tLetIn na (csubst t k b) (csubst t k ty) (csubst t (S k) b')\n  | tCase ind p c brs =>\n    let brs' := List.map (fun br => map_branch_k (csubst t) id k br) brs in\n    tCase ind (map_predicate_k id (csubst t) k p)\n      (csubst t k c) brs'\n  | tProj p c => tProj p (csubst t k c)\n  | tFix mfix idx =>\n    let k' := List.length mfix + k in\n    let mfix' := List.map (map_def (csubst t k) (csubst t k')) mfix in\n    tFix mfix' idx\n  | tCoFix mfix idx =>\n    let k' := List.length mfix + k in\n    let mfix' := List.map (map_def (csubst t k) (csubst t k')) mfix in\n    tCoFix mfix' idx\n  | x => x\n  end.\n\n(** It is equivalent to general substitution when substituting a closed term *)\nLemma closed_subst t k u : closed t ->\n    csubst t k u = subst [t] k u.\nProof.\n  revert k; induction u using term_forall_list_ind; intros k Hs;\n    simpl; try f_equal; eauto with pcuic; solve_all.\n  - destruct (PeanoNat.Nat.compare_spec k n).\n    + subst k.\n      rewrite PeanoNat.Nat.leb_refl Nat.sub_diag /=.\n      now rewrite lift_closed.\n    + destruct (leb_spec_Set k n); try lia.\n      destruct (nth_error_spec [t] (n - k) ).\n      simpl in l0; lia.\n      now rewrite Nat.sub_1_r.\n    + now destruct (Nat.leb_spec k n); try lia.\nQed.\n\n(** It respects closedness of the substitutend as well. *)\nLemma closed_csubst t k u : closed t -> closedn (S k) u -> closedn k (csubst t 0 u).\nProof.\n  intros.\n  rewrite closed_subst; auto.\n  eapply closedn_subst0. simpl. erewrite closed_upwards; eauto. lia.\n  simpl. now rewrite Nat.add_1_r.\nQed.\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/PCUICCSubst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.28157164003676394}}
{"text": "From stdpp Require Import nat_cancel.\nFrom iris.proofmode Require Import base tactics modality_instances classes.\nFrom iris.bi Require Export derived_laws derived_connectives.\nFrom iris.algebra Require Import monoid cmra.\nFrom Perennial.base_logic Require Import own.\nFrom Perennial.algebra Require Export laterN.\nImport interface.bi.\nImport derived_laws.bi.\nImport derived_laws_later.bi.\n\nSet Default Proof Using \"Type\".\n\nDefinition bi_atleast {PROP : bi} (k : nat) (P : PROP) : PROP := (▷^k False ∨ P)%I.\nArguments bi_atleast {_} _ _%I : simpl never.\nNotation \"◇_ n P\" := (bi_atleast n P) (at level 20, n at level 9, P at level 20,\n   format \"◇_ n  P\").\n#[global]\nInstance: Params (@bi_atleast) 2 := {}.\nTypeclasses Opaque bi_atleast.\n\nClass AbsolutelyTimeless {PROP : bi} (P : PROP) := abs_timeless : ∀ k, ▷^k P ⊢ ◇_k P.\nArguments AbsolutelyTimeless {_} _%I : simpl never.\nArguments abs_timeless {_} _%I {_}.\n#[global]\nHint Mode AbsolutelyTimeless + ! : typeclass_instances.\n#[global]\nInstance: Params (@AbsolutelyTimeless) 1 := {}.\n\nSection PROP_laws.\nContext {PROP : bi}.\nContext {H: BiLöb PROP}.\nImplicit Types φ : Prop.\nImplicit Types P Q R : PROP.\nImplicit Types Ps : list PROP.\nImplicit Types A : Type.\n\nLocal Hint Resolve or_elim or_intro_l' or_intro_r' True_intro False_elim : core.\nLocal Hint Resolve and_elim_l' and_elim_r' and_intro forall_intro : core.\n\n(* Force implicit argument PROP *)\nNotation \"P ⊢ Q\" := (P ⊢@{PROP} Q).\nNotation \"P ⊣⊢ Q\" := (P ⊣⊢@{PROP} Q).\n\nGlobal Instance atleast_ne k : NonExpansive (@bi_atleast PROP k).\nProof. solve_proper. Qed.\nGlobal Instance atleast_proper k : Proper ((⊣⊢) ==> (⊣⊢)) (@bi_atleast PROP k).\nProof. solve_proper. Qed.\nGlobal Instance atleast_mono' k : Proper ((⊢) ==> (⊢)) (@bi_atleast PROP k).\nProof. solve_proper. Qed.\nGlobal Instance atleast_flip_mono' k :\n  Proper (flip (⊢) ==> flip (⊢)) (@bi_atleast PROP k).\nProof. solve_proper. Qed.\n\nSection laws.\nContext (k: nat).\nLemma atleast_intro P : P ⊢ ◇_k P.\nProof. rewrite /bi_atleast; auto. Qed.\nLemma atleast_mono P Q : (P ⊢ Q) → ◇_k P ⊢ ◇_k Q.\nProof. by intros ->. Qed.\nLemma atleast_le k1 k2 P : k1 ≤ k2 → ◇_k1 P ⊢ ◇_k2 P.\nProof.\n  rewrite /bi_atleast. iIntros (?) \"[Hf|HP]\".\n  - iLeft. iApply laterN_le; eauto.\n  - iRight. eauto.\nQed.\nLemma atleast_idemp P : ◇_k ◇_k P ⊣⊢ ◇_k P.\nProof.\n  apply (anti_symm _); rewrite /bi_atleast; auto.\nQed.\n\nLemma except_0_atleast P : ◇ P ⊣⊢ ◇_1 P.\nProof. rewrite /bi_atleast/bi_except_0//=. Qed.\n\nLemma atleast_True : ◇_k True ⊣⊢ True.\nProof using H. rewrite /bi_atleast. apply (anti_symm _); auto. Qed.\nLemma atleast_emp `{!BiAffine PROP} : ◇_k emp ⊣⊢ emp.\nProof using H. by rewrite -True_emp atleast_True. Qed.\nLemma atleast_or P Q : ◇_k (P ∨ Q) ⊣⊢ ◇_k P ∨ ◇_k Q.\nProof.\n  rewrite /bi_atleast. apply (anti_symm _); auto.\nQed.\nLemma atleast_and P Q : ◇_k (P ∧ Q) ⊣⊢ ◇_k P ∧ ◇_k Q.\nProof. by rewrite /bi_atleast or_and_l. Qed.\nLemma atleast_sep P Q : ◇_k (P ∗ Q) ⊣⊢ ◇_k P ∗ ◇_k Q.\nProof.\n  rewrite /bi_atleast. apply (anti_symm _).\n  - apply or_elim; last by auto using sep_mono.\n    by rewrite -!or_intro_l -persistently_pure -laterN_sep -persistently_sep_dup.\n  - rewrite sep_or_r !sep_or_l {1}(later_intro P) {1}(later_intro Q).\n    rewrite -!laterN_sep !left_absorb.\n    iIntros \"[[?|(?&?)]|[(?&?)|?]]\"; eauto.\nQed.\nLemma atleast_exist_2 {A} (Φ : A → PROP) : (∃ a, ◇_k Φ a) ⊢ ◇_k ∃ a, Φ a.\nProof. apply exist_elim=> a. by rewrite (exist_intro a). Qed.\nLemma atleast_exist `{Inhabited A} (Φ : A → PROP) :\n  ◇_k (∃ a, Φ a) ⊣⊢ (∃ a, ◇_k Φ a).\nProof.\n  apply (anti_symm _); [|by apply atleast_exist_2]. apply or_elim.\n  - rewrite -(exist_intro inhabitant). by apply or_intro_l.\n  - apply exist_mono=> a. apply atleast_intro.\nQed.\nLemma atleast_laterN_le P j (Hle: j ≤ k) : ◇_k ▷^j P ⊢ ▷^k P.\nProof. by rewrite /bi_atleast (laterN_le j k) // -laterN_or False_or. Qed.\nLemma atleast_laterN P : ◇_k ▷^k P ⊢ ▷^k P.\nProof. by apply atleast_laterN_le. Qed.\nLemma atleast_later P (Hle: 1 <= k): ◇_k ▷ P ⊢ ▷^k P.\nProof. rewrite (atleast_laterN_le _ 1) //=. Qed.\n(*\nLemma atleast_laterN n P (Hle: 1 ≤ k) : ◇_k ▷^n P ⊢ ▷^n ◇_k P.\nProof. destruct n as [|n]; rewrite //= ?atleast_later //=. -atleast_intro. Qed.\n*)\nLemma atleast_into_later P : ◇_k P ⊢ ▷^k P.\nProof. by rewrite -atleast_laterN -laterN_intro. Qed.\nLemma atleast_persistently P : ◇_k <pers> P ⊣⊢ <pers> ◇_k P.\nProof.\n  by rewrite /bi_atleast persistently_or -laterN_persistently persistently_pure.\nQed.\nLemma atleast_affinely_2 P : <affine> ◇_k P ⊢ ◇_k <affine> P.\nProof. rewrite /bi_affinely atleast_and. auto using atleast_intro. Qed.\nLemma atleast_intuitionistically_2 P : □ ◇_k P ⊢ ◇_k □ P.\nProof. by rewrite /bi_intuitionistically -atleast_persistently atleast_affinely_2. Qed.\nLemma atleast_intuitionistically_if_2 p P : □?p ◇_k P ⊢ ◇_k □?p P.\nProof. destruct p; simpl; auto using atleast_intuitionistically_2. Qed.\nLemma atleast_absorbingly P : ◇_k <absorb> P ⊣⊢ <absorb> ◇_k P.\nProof using H. by rewrite /bi_absorbingly atleast_sep atleast_True. Qed.\n\nLemma atleast_frame_l P Q : P ∗ ◇_k Q ⊢ ◇_k (P ∗ Q).\nProof. by rewrite {1}(atleast_intro P) atleast_sep. Qed.\nLemma atleast_frame_r P Q : ◇_k P ∗ Q ⊢ ◇_k (P ∗ Q).\nProof. by rewrite {1}(atleast_intro Q) atleast_sep. Qed.\n\nLemma later_affinely_1 `{!AbsolutelyTimeless (PROP:=PROP) emp} P : ▷^k <affine> P ⊢ ◇_k <affine> ▷^k P.\nProof.\n  rewrite /bi_affinely laterN_and (abs_timeless emp%I) atleast_and.\n  by apply and_mono, atleast_intro.\nQed.\n\nGlobal Instance atleast_persistent P : Persistent P → Persistent (◇_k P).\nProof. rewrite /bi_atleast; apply _. Qed.\nGlobal Instance atleast_absorbing P : Absorbing P → Absorbing (◇_k P).\nProof. rewrite /bi_atleast; apply _. Qed.\n(* AbsolutelyTimeless instances *)\nGlobal Instance AbsolutelyTimeless_proper : Proper ((≡) ==> iff) (@AbsolutelyTimeless PROP).\nProof.\n  rewrite /AbsolutelyTimeless.\n  intros ?? Heq. split; intros ? k0.\n  * rewrite -Heq; eauto.\n  * rewrite Heq; eauto.\nQed.\n\nLemma atleast_bupd `{!BiBUpd PROP} P : ◇_k (|==> P) ⊢ (|==> ◇_k P).\nProof.\n  rewrite /bi_atleast. apply or_elim; eauto using bupd_mono, or_intro_r.\nQed.\n\nEnd laws.\n\nGlobal Instance and_abs_timeless P Q : AbsolutelyTimeless P → AbsolutelyTimeless Q → AbsolutelyTimeless (P ∧ Q).\nProof. intros ???; rewrite /AbsolutelyTimeless atleast_and laterN_and; auto. Qed.\nGlobal Instance or_abs_timeless P Q : AbsolutelyTimeless P → AbsolutelyTimeless Q → AbsolutelyTimeless (P ∨ Q).\nProof. intros ???; rewrite /AbsolutelyTimeless atleast_or laterN_or; auto. Qed.\n\nGlobal Instance sep_abs_timeless P Q: AbsolutelyTimeless P → AbsolutelyTimeless Q → AbsolutelyTimeless (P ∗ Q).\nProof.\n  intros ???; rewrite /AbsolutelyTimeless atleast_sep laterN_sep; auto using sep_mono.\nQed.\n\nGlobal Instance persistently_abs_timeless P : AbsolutelyTimeless P → AbsolutelyTimeless (<pers> P).\nProof.\n  intros ??. rewrite /AbsolutelyTimeless /bi_atleast laterN_persistently.\n  by rewrite (abs_timeless P) persistently_or {1}persistently_elim.\nQed.\n\nGlobal Instance affinely_abs_timeless P :\n  AbsolutelyTimeless (PROP:=PROP) emp → AbsolutelyTimeless P → AbsolutelyTimeless (<affine> P).\nProof. rewrite /bi_affinely; apply _. Qed.\n(*\nGlobal Instance absorbingly_abs_timeless P : AbsolutelyTimeless P → AbsolutelyTimeless (<absorb> P).\nProof. rewrite /bi_absorbingly; apply _. Qed.\n*)\n\nGlobal Instance intuitionistically_abs_timeless P :\n  AbsolutelyTimeless (PROP:=PROP) emp → AbsolutelyTimeless P → AbsolutelyTimeless (□ P).\nProof. rewrite /bi_intuitionistically; apply _. Qed.\n\nGlobal Instance from_option_abs_timeless {A} P (Ψ : A → PROP) (mx : option A) :\n  (∀ x, AbsolutelyTimeless (Ψ x)) → AbsolutelyTimeless P → AbsolutelyTimeless (from_option Ψ P mx).\nProof. destruct mx; apply _. Qed.\nEnd PROP_laws.\n\nSection uPred_laws.\nContext {M: ucmra}.\nImplicit Types φ : Prop.\nImplicit Types P Q R : (uPred M).\nImplicit Types Ps : list (uPred M).\nImplicit Types A : Type.\n\n\n\nLocal Hint Resolve or_elim or_intro_l' or_intro_r' True_intro False_elim : core.\nLocal Hint Resolve and_elim_l' and_elim_r' and_intro forall_intro : core.\n\n(* TODO: Is there a syntactic proof of this for all BI?\n   The generalization of the syntactic proof for except_0 did not seem to work out. *)\nLemma atleast_forall {A} k (Φ : A → uPred M) : ◇_k (∀ a, Φ a) ⊣⊢ ∀ a, ◇_k Φ a.\nProof.\n  apply (anti_symm _).\n  { apply forall_intro=> a. by rewrite (forall_elim a). }\n  split => n x Hval Hall.\n  destruct (decide (n < k)).\n  - rewrite /bi_atleast/bi_or//=. uPred.unseal. left. apply laterN_small; eauto.\n  - move: Hall. rewrite /bi_atleast/bi_or//=. uPred.unseal. right.\n    intros a. specialize (Hall a) as [Hleft|Hright].\n    * exfalso. eapply (laterN_big n k x); eauto.\n      { lia. }\n      { uPred.unseal; eauto. }\n    * eauto.\nQed.\n\nGlobal Instance pure_abs_timeless φ : AbsolutelyTimeless (PROP:=uPredI M) ⌜φ⌝.\nProof.\n  intros k'. rewrite /bi_atleast pure_alt laterN_exist_false.\n  apply or_mono; first auto.\n  apply exist_elim. intros. eauto.\nQed.\nGlobal Instance emp_abs_timeless `{BiAffine PROP} : AbsolutelyTimeless (PROP:=uPredI M) emp.\nProof. rewrite -True_emp. apply _. Qed.\nGlobal Instance forall_abs_timeless {A} (Ψ : A → uPred M) :\n  (∀ x, AbsolutelyTimeless (Ψ x)) → AbsolutelyTimeless (∀ x, Ψ x).\nProof.\n  rewrite /AbsolutelyTimeless=> HQ k. rewrite atleast_forall laterN_forall.\n  apply forall_mono; auto.\nQed.\nGlobal Instance exist_abs_timeless {A} (Ψ : A → uPred M) :\n  (∀ x, AbsolutelyTimeless (Ψ x)) → AbsolutelyTimeless (∃ x, Ψ x).\nProof.\n  rewrite /AbsolutelyTimeless=> ??. rewrite laterN_exist_false. apply or_elim.\n  - rewrite /bi_atleast; auto.\n  - apply exist_elim=> x. rewrite -(exist_intro x); auto.\nQed.\n\nGlobal Instance eq_abs_timeless {A : ofe} (a b : A) :\n  Discrete a → AbsolutelyTimeless (PROP:=uPredI M) (a ≡ b).\nProof. intros. rewrite /Discrete !discrete_eq => k. apply (abs_timeless _). Qed.\n\n(* These next two instances hold for Timeless, but they appear to not be true for AbsolutelyTimeless.\n\n   However, a quick test suggests that the corresponding Timeless versions are un-used in Perennial,\n   so losing them for AbsolutelyTimeless is not a problem. *)\n\n(*\nGlobal Instance impl_abs_timeless `{!BiLöb PROP} P Q : AbsolutelyTimeless Q → AbsolutelyTimeless (P → Q).\nProof.\n  rewrite /AbsolutelyTimeless=> HQ k.\n  split => n x Hval HPQ.\n  destruct (decide (n < k)).\n  - rewrite /bi_atleast//=. uPred.unseal. left. apply laterN_small; eauto.\n  - move: HQ HPQ. rewrite /bi_atleast//=. uPred.unseal. right.\n    intros n' x' Hincl Hle Hval' HP.\n    assert (HPQ_later: (uPred_impl_def P Q) (n - k) x).\n    assert (HP_later: P (n' - k) x).\nAbort.\n*)\n\n(*\nGlobal Instance wand_abs_timeless `{!BiLöb PROP} P Q : AbsolutelyTimeless Q → AbsolutelyTimeless (P -∗ Q).\nProof.\nAbort.\n*)\n\nImport base_logic.bi.uPred.\nGlobal Instance valid_abs_timeless {A : cmra} `{!CmraDiscrete A} (a : A) :\n  AbsolutelyTimeless (✓ a : uPred M)%I.\nProof. rewrite /AbsolutelyTimeless => k. rewrite !discrete_valid. apply (abs_timeless _). Qed.\n\n\nGlobal Instance ownM_abs_timeless (a : M) : Discrete a → AbsolutelyTimeless (uPred_ownM a).\nProof.\n  intros ? k. rewrite laterN_ownM.\n  apply exist_elim=> b.\n  rewrite (abs_timeless (a≡b)) (atleast_intro k (uPred_ownM b)) -atleast_and.\n  apply atleast_mono. rewrite internal_eq_sym.\n  apply (internal_eq_rewrite' b a (uPred_ownM) _);\n    auto using and_elim_l, and_elim_r.\nQed.\nEnd uPred_laws.\n\nClass IntoAtLeast {PROP : bi} k (P Q : PROP) := into_atleast : P ⊢ ◇_k Q.\nArguments IntoAtLeast {_} _ _%I _%I : simpl never.\nArguments into_atleast {_} _ _%I _%I {_}.\n#[global]\nHint Mode IntoAtLeast + - ! - : typeclass_instances.\n#[global]\nHint Mode IntoAtLeast + - - ! : typeclass_instances.\n\nClass IsAtLeast {PROP : bi} k (Q : PROP) := is_atleast : ◇_k Q ⊢ Q.\nArguments IsAtLeast {_} _ _%I : simpl never.\nArguments is_atleast {_} _ _%I {_}.\n#[global]\nHint Mode IsAtLeast + + ! : typeclass_instances.\n\nClass MakeAtLeast {PROP : bi} k (P Q : PROP) :=\n  make_atleast : ◇_k P ⊣⊢ Q.\nArguments MakeAtLeast {_} _ _%I _%I.\n#[global]\nHint Mode MakeAtLeast + - - - : typeclass_instances.\nClass KnownMakeAtLeast {PROP : bi} k (P Q : PROP) :=\n  known_make_except_0 :> MakeAtLeast k P Q.\nArguments KnownMakeAtLeast {_} _ _%I _%I.\n#[global]\nHint Mode KnownMakeAtLeast + + ! - : typeclass_instances.\n\nSection class_instances_atleast.\nContext {M: ucmra}.\nContext (k: nat).\nImplicit Types P Q R : uPred M.\n\nGlobal Instance from_assumption_atleast p P Q :\n  FromAssumption p P Q → KnownRFromAssumption p P (◇_k Q)%I.\nProof. rewrite /KnownRFromAssumption /FromAssumption=>->. apply atleast_intro. Qed.\n\nGlobal Instance from_pure_atleast a P φ : FromPure a P φ → FromPure a (◇_k P) φ.\nProof. rewrite /FromPure=> ->. apply atleast_intro. Qed.\n\nGlobal Instance from_and_atleast P Q1 Q2 :\n  FromAnd P Q1 Q2 → FromAnd (◇_k P) (◇_k Q1) (◇_k Q2).\nProof. rewrite /FromAnd=><-. by rewrite atleast_and. Qed.\n\nGlobal Instance from_sep_atleast P Q1 Q2 :\n  FromSep P Q1 Q2 → FromSep (◇_k P) (◇_k Q1) (◇_k Q2).\nProof. rewrite /FromSep=><-. by rewrite atleast_sep. Qed.\n\nGlobal Instance into_and_atleast p P Q1 Q2 :\n  IntoAnd p P Q1 Q2 → IntoAnd p (◇_k P) (◇_k Q1) (◇_k Q2).\nProof.\n  rewrite /IntoAnd=> HP. apply intuitionistically_if_intro'.\n  by rewrite atleast_intuitionistically_if_2 HP\n             intuitionistically_if_elim atleast_and.\nQed.\n\nGlobal Instance into_sep_atleast P Q1 Q2 :\n  IntoSep P Q1 Q2 → IntoSep (◇_k P) (◇_k Q1) (◇_k Q2).\nProof. rewrite /IntoSep=> ->. by rewrite atleast_sep. Qed.\n\nGlobal Instance from_or_atleast P Q1 Q2 :\n  FromOr P Q1 Q2 → FromOr (◇_k P) (◇_k Q1) (◇_k Q2).\nProof. rewrite /FromOr=><-. by rewrite atleast_or. Qed.\n\nGlobal Instance into_or_atleast P Q1 Q2 :\n  IntoOr P Q1 Q2 → IntoOr (◇_k P) (◇_k Q1) (◇_k Q2).\nProof. rewrite /IntoOr=>->. by rewrite atleast_or. Qed.\n\nGlobal Instance from_exist_atleast {A} P (Φ : A → uPred M) :\n  FromExist P Φ → FromExist (◇_k P) (λ a, ◇_k (Φ a))%I.\nProof. rewrite /FromExist=> <-. by rewrite atleast_exist_2. Qed.\n\nGlobal Instance into_exist_atleast {A} P (Φ : A → uPred M) i :\n  IntoExist P Φ i → Inhabited A → IntoExist (◇_k P) (λ a, ◇_k (Φ a))%I i.\nProof. rewrite /IntoExist=> HP ?. by rewrite HP atleast_exist. Qed.\n\nGlobal Instance into_forall_atleast {A} P (Φ : A → uPred M) :\n  IntoForall P Φ → IntoForall (◇_k P) (λ a, ◇_k (Φ a))%I.\nProof. rewrite /IntoForall=> HP. by rewrite HP atleast_forall. Qed.\n\nGlobal Instance from_forall_atleast {A} P (Φ : A → uPred M) i :\n  FromForall P Φ i → FromForall (◇_k P)%I (λ a, ◇_k (Φ a))%I i.\nProof. rewrite /FromForall=> <-. by rewrite atleast_forall. Qed.\n\nGlobal Instance from_modal_atleast P : FromModal True modality_id (◇_k P) (◇_k P) P.\nProof. by rewrite /FromModal /= -atleast_intro. Qed.\n\n(** IsAtLeast *)\nGlobal Instance is_atleast_atleast P : IsAtLeast k (◇_k P).\nProof. by rewrite /IsAtLeast atleast_idemp. Qed.\nGlobal Instance is_atleast_later P : IsAtLeast k (▷^k P).\nProof. by rewrite /IsAtLeast atleast_laterN. Qed.\n\n(** IntoAtLeast *)\nGlobal Instance into_atleast_atleast P : IntoAtLeast k (◇_k P) P.\nProof. by rewrite /IntoAtLeast. Qed.\nGlobal Instance into_atleast_later P : AbsolutelyTimeless P → IntoAtLeast k (▷^k P) P.\nProof. by rewrite /IntoAtLeast. Qed.\n\n(* Special instances of above for k=1 and k=2. This could be done more generically, but it seems like\n   we will only use k=1 and k=2 in practice anyway, so for now we just add directly the instances needed. *)\nGlobal Instance into_atleast_later1 P : AbsolutelyTimeless P → IntoAtLeast 1 (▷ P) P.\nProof. rewrite /IntoAtLeast. by replace (▷ P)%I with (▷^1 P)%I by auto. Qed.\nGlobal Instance into_atleast_later2 P : AbsolutelyTimeless P → IntoAtLeast 2 (▷▷ P) P.\nProof. rewrite /IntoAtLeast. by replace (▷▷ P)%I with (▷^2 P)%I by auto. Qed.\nGlobal Instance into_atleast_later2' P : AbsolutelyTimeless P → IntoAtLeast 2 (▷ P) P.\nProof. rewrite /IntoAtLeast => ?. transitivity (▷▷ P)%I; first eauto. by apply into_atleast_later2. Qed.\n\n(* XXX should this be added?\nGlobal Instance into_atleast_later P : Timeless P → IntoAtLeast 1 (▷ P) P.\nProof. by rewrite /IntoAtLeast. Qed.\nGlobal Instance into_atleast_later_if p P : Timeless P → IntoAtLeast (▷?p P) P.\nProof. rewrite /IntoAtLeast. destruct p; auto using atleast_intro. Qed.\n*)\n\nGlobal Instance into_atleast_affinely P Q :\n  IntoAtLeast k P Q → IntoAtLeast k (<affine> P) (<affine> Q).\nProof. rewrite /IntoAtLeast=> ->. by rewrite atleast_affinely_2. Qed.\nGlobal Instance into_atleast_intuitionistically P Q :\n  IntoAtLeast k P Q → IntoAtLeast k (□ P) (□ Q).\nProof. rewrite /IntoAtLeast=> ->. by rewrite atleast_intuitionistically_2. Qed.\nGlobal Instance into_atleast_absorbingly P Q :\n  IntoAtLeast k P Q → IntoAtLeast k (<absorb> P) (<absorb> Q).\nProof. rewrite /IntoAtLeast=> ->. by rewrite atleast_absorbingly. Qed.\nGlobal Instance into_atleast_persistently P Q :\n  IntoAtLeast k P Q → IntoAtLeast k (<pers> P) (<pers> Q).\nProof. rewrite /IntoAtLeast=> ->. by rewrite atleast_persistently. Qed.\n\nGlobal Instance elim_modal_abstimeless p P Q P' :\n  IntoAtLeast k P P' → IsAtLeast k Q → ElimModal True p p P P' Q Q.\nProof.\n  intros. rewrite /ElimModal (atleast_intro k (_ -∗ _)%I) (into_atleast k P).\n  by rewrite atleast_intuitionistically_if_2 -atleast_sep wand_elim_r.\nQed.\n\nGlobal Instance add_modal_atleast P Q : AddModal (◇_k P) P (◇_k Q) | 1.\nProof.\n  intros. rewrite /AddModal (atleast_intro k (_ -∗ _)%I).\n  by rewrite -atleast_sep wand_elim_r atleast_idemp.\nQed.\nGlobal Instance add_modal_atleast_later P Q : AddModal (◇_k P) P (▷^k Q) | 1.\nProof.\n  intros. rewrite /AddModal (atleast_intro k (_ -∗ _)%I).\n  by rewrite -atleast_sep wand_elim_r atleast_laterN.\nQed.\n\nGlobal Instance make_atleast_True : @KnownMakeAtLeast (uPredI M) k True True.\nProof. by rewrite /KnownMakeAtLeast /MakeAtLeast atleast_True. Qed.\nGlobal Instance make_atleast_default P : MakeAtLeast k P (◇_k P) | 100.\nProof. by rewrite /MakeAtLeast. Qed.\n\nGlobal Instance frame_atleast p R P Q Q' :\n  Frame p R P Q → MakeAtLeast k Q Q' → Frame p R (◇_k P) Q'.\nProof.\n  rewrite /Frame /MakeAtLeast=><- <-.\n  by rewrite atleast_sep -(atleast_intro k (□?p R)%I).\nQed.\n\nGlobal Instance is_atleast_bupd P : IsAtLeast k P → IsAtLeast k (|==> P).\nProof.\n  rewrite /IsAtLeast=> HP.\n  by rewrite -{2}HP -(atleast_idemp k P) -atleast_bupd -(atleast_intro k P).\nQed.\n\nEnd class_instances_atleast.\n\nSection iprop_instances.\n\n  Global Instance own_abs_timeless {A: cmra} `{inG Σ A} γ (a: A):\n    Discrete a →\n    AbsolutelyTimeless (own γ a).\n  Proof.\n    intros ?. rewrite own.own_eq /own.own_def.\n    apply ownM_abs_timeless, iRes_singleton_discrete. done.\n  Qed.\n\nEnd iprop_instances.\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/atleast.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2815666804993119}}
{"text": "Load GradVer9Ltac.\nImport Semantics.\n\n\nDefinition A_sSubsts m (A : A_s) : A_s := \n  flat_map (fun p =>\n    match p with\n    | phiAcc x f => [(x, f)]\n    | _ => []\n    end\n  )\n  (phiSubsts m (map (fun a => phiAcc (fst a) (snd a)) A)).\n\n\nDefinition mMapsTo (m : list (x * x)) (x' : x) : Prop :=\n  exists m', In m' m /\\ snd m' = x'.\n\nDefinition mMapsToUnique (m : list (x * x)) (x' : x) : Prop :=\n  forall f1 f2 x1 x2, \n      In (f1, x1) m -> \n      In (f2, x2) m -> \n      x1 = x' -> \n      x2 = x' -> \n      f1 = f2\n.\n\n(* sfrme (A_sSubsts (a => b) (a.f)) (eSubsts (a => b) (b.f)) -> sfrme (a.f) (b.f) *)\nLemma sfrmeSubst : forall m e a,\n      (forall x, mMapsToUnique m x /\\ (mMapsTo m x -> (~ In x (FVe e) /\\ ~ In x (FVA_s a)))) ->\n      sfrme (A_sSubsts m a) (eSubsts m e) ->\n      sfrme a e.\nProof.\n  induction e0; intros; try (constructor; fail).\n  inversionx H1.\n  constructor; try (apply IHe0; auto).\n  generalize a H0 H5. clear.\n\n  induction a; intros; simpl in *; try tauto.\n  inversionx H5.\n  - destruct a. simpl in *.\n    inversionx H1.\n    assert (CL := classic (e0 = e1)).\n    inversionx CL; subst; eauto.\n    contradict H1.\n    generalize e0 e1 H3 H0. clear.\n    induction e0; intros; simpl in *;\n    destruct e1; simpl in *; inversionx H3; try tauto.\n    * unfold mMapsToUnique in *.\n      unfold xSubsts in *.\n      destruct (find (λ r : x * x, x_decb x0 (fst r)) m0) eqn: ff0;\n      destruct (find (λ r : x * x, x_decb x1 (fst r)) m0) eqn: ff1.\n      + destruct p0, p1.\n        subst.\n        apply find_some in ff0. unf.\n        apply find_some in ff1. unf.\n        simpl in *.\n        dec (x_dec x1 x4); inversionx H4.\n        dec (x_dec x0 x2); inversionx H2.\n        specialize (H0 x3).\n        unf.\n        eapply H2 in H1; eauto.\n        subst.\n        tauto.\n      + destruct p0.\n        subst.\n        apply find_some in ff0. unf.\n        eapply find_none in ff1; eauto.\n        simpl in *.\n        dec (x_dec x3 x2); inversionx ff1. rename de2 into asd.\n        dec (x_dec x0 x2); inversionx H2.\n        specialize (H0 x3).\n        unf. assert (mMapsTo m0 x3). eexists; eauto. intuition.\n      + destruct p0.\n        subst.\n        apply find_some in ff1. unf.\n        eapply find_none in ff0; eauto.\n        simpl in *.\n        dec (x_dec x0 x2); inversionx ff0. rename de2 into asd.\n        dec (x_dec x1 x2); inversionx H2.\n        specialize (H0 x0).\n        unf. assert (mMapsTo m0 x0). eexists; eauto. intuition.\n      + subst.\n        tauto.\n    * apply IHe0 in H2; subst; intuition.\n  - apply or_intror.\n    eapply IHa; auto.\n    intros.\n    specialize (H0 x0).\n    unfold FVA_s in *.\n    simpl in *.\n    intuition.\nQed.\n\nLemma sfrmeSubstEmpty : forall m e,\n      sfrme [] (eSubsts m e) -> sfrme [] e.\nProof.\n  intros.\n  induction e0; try constructor;\n  simpl in *;\n  inversionx H0;\n  inversion H4.\nQed.\n\nLemma sfrmphi'Subst : forall m e a,\n     (forall x, mMapsToUnique m x /\\ (mMapsTo m x -> (~ In x (FV' e) /\\ ~ In x (FVA_s a)))) ->\n      sfrmphi' (A_sSubsts m a) (phi'Substs m e)\n      ->\n      sfrmphi' a e.\nProof.\n  intros.\n  destruct e0; constructor;\n  inversionx H1;\n  apply (sfrmeSubst m0); intuition;\n  try apply H0;\n  apply H0 in H1;\n  inversionx H1;\n  intuition;\n  contradict H3;\n  simpl;\n  intuition.\nQed.\n\n(* counter-examples:\nsfrmphi [] (phiSubsts (a => c, b => c) (acc(b.f) * a.f = 3)) ->\nsfrmphi [] (acc(b.f) * a.f = 3)\n\nsfrmphi [] (phiSubsts (a => b) (acc(b.f) * a.f = 3)) ->\nsfrmphi [] (acc(b.f) * a.f = 3)\n\nsfrmphi [] (phiSubsts (b => a) (acc(b.f) * a.f = 3)) ->\nsfrmphi [] (acc(b.f) * a.f = 3)\n*)\n\nLemma sfrmphiSubst : forall e m a,\n     (forall x, mMapsToUnique m x /\\ (mMapsTo m x -> (~ In x (FV e) /\\ ~ In x (FVA_s a)))) ->\n      sfrmphi (A_sSubsts m a) (phiSubsts m e)\n      ->\n      sfrmphi a e.\nProof.\n  induction e0; intros; constructor.\n  - inversionx H1.\n    eapply sfrmphi'Subst; eauto.\n    intros.\n    split; try apply H0.\n    intros.\n    apply H0 in H1.\n    inversionx H1.\n    intuition.\n    contradict H4.\n    simpl.\n    intuition.\n  - inversionx H1.\n    apply (IHe0 m0); intros.\n    * specialize (H0 x0).\n      unf.\n      intuition.\n      + contradict H4.\n        simpl.\n        intuition.\n      + destruct a; simpl in *; intuition.\n        unfold FVA_s in *.\n        apply in_flat_map in H5.\n        unf.\n        apply in_map_iff in H5.\n        unf.\n        subst.\n        inversionx H9; simpl in *; intuition.\n        contradict H6.\n        apply in_flat_map.\n        eexists; split; eauto.\n        apply in_map_iff.\n        eexists; split; eauto.\n    * destruct a; simpl in *; intuition.\nQed.\n", "meta": {"author": "olydis", "repo": "GradVer", "sha": "b7c02206ea47e54975dfbb55ac2e4deed60c5292", "save_path": "github-repos/coq/olydis-GradVer", "path": "github-repos/coq/olydis-GradVer/GradVer-b7c02206ea47e54975dfbb55ac2e4deed60c5292/GradVer10LemmaSfrmSubst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2815666804993119}}
{"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.\nFrom fourcolor Require Import job215to218 job219to222 job223to226.\nFrom fourcolor Require Import job227to230 job231to234.\n\n(******************************************************************************)\n(* Reducibility of configurations number 215 to 234, whose indices in         *)\n(* the_configs range over segment [214, 234).                                 *)\n(******************************************************************************)\n\nLemma red214to234 : reducible_in_range 214 234 the_configs.\nProof.\nCatReducible red214to218 red218to222 red222to226 red226to230 red230to234.\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/task215to234.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.2815666804993119}}
{"text": "(** * Strenghthening \nThe Strenghthening property is about getting rid of useless hypothesis:\n  if [Γ(x:A)Γ' ⊢ M : T] and [x] does not appear in [M] or [T], then \n     [ΓΓ' ⊢ M : T].*)\n(** This is true for all PTS, but the proof is quite subtle. This formalization\nhas been done from a paper for Jutting in 1993.\n\n\nThe following is not usefull for the proof PTS <-> PTSe \nbut it's still an interesting part of the metatheory of PTSs \n\n*)\nRequire Import base.\nRequire Import ut_term.\nRequire Import ut_red.\nRequire Import ut_env.\nRequire Import ut_typ.\nRequire Import ut_sr. \nRequire Import List Le Lt Gt.\nRequire Compare_dec Peano_dec.\n\nUnset Standard Proposition Elimination Names.\n\nModule ut_strengh_mod (X:term_sig) (Y:pts_sig X) (TM:ut_term_mod X) (EM:ut_env_mod X TM) (RM: ut_red_mod X TM).\n Include (ut_sr_mod X Y TM EM RM).\n  Import X Y TM EM RM.\n\nOpen Scope UT_scope.\n\n(**\nTv Ts and Sigma are notation find in Jutting93 \n\n\n We do a partition of [Term] in two families, one build around\nvars and the other around sorts and Pi-types.*)\nInductive Tv : Term -> Prop :=\n | Tv_intro : forall x, Tv #x\n | Tv_la: forall M A, Tv M -> Tv (λ[A],M)\n | Tv_app :forall M N, Tv M -> Tv (M·N)\n.\n\nInductive Ts : Term -> Prop :=\n | Ts_intro : forall s, Ts !s\n | Ts_pi : forall A B, Ts (Π(A),B)\n | Ts_la : forall A M, Ts M -> Ts (λ[A],M)\n | Ts_app : forall M N, Ts M -> Ts (M·N)\n.\n\n(** Telescopes are just a way to talk about n-ary Lam/Pi -terms: *)\n(** Tels (A1,...,An)M ::= Π(A1),...,Π(An),M *)\nFixpoint Tels (Γ : Env) (M : Term) {struct Γ } : Term :=\n match Γ with\n | nil => M\n | cons A Δ => Π(A),(Tels Δ M)\nend.\n\nFixpoint Tels' (Γ : Env) (M : Term) {struct Γ } : Term :=\n match Γ with\n | nil => M\n | cons A Δ => λ[A],(Tels' Δ M)\nend.\n\n\nHint Constructors Tv Ts.\n\nImport Compare_dec Peano_dec.\n(** Some basic properties of [Tv] and [Ts]. *)\nLemma Tv_lift : forall M n m, Tv M <-> Tv (M ↑ n # m).\ninduction M; split; simpl in *; intros; intuition.\ndestruct le_gt_dec; intuition.\ninversion  H; subst; clear H. constructor. eapply IHM1. trivial.\ninversion  H; subst; clear H. constructor. eapply IHM1. apply H1.\ninversion H. inversion H.\ninversion  H; subst; clear H. constructor. eapply IHM2. trivial.\ninversion  H; subst; clear H. constructor. eapply IHM2. apply H1.\nQed.\n\nLemma Ts_lift : forall M n m, Ts M <-> Ts (M ↑ n # m).\ninduction M; split; simpl in *; intros; intuition.\ninversion H. destruct le_gt_dec; inversion H.\ninversion  H; subst; clear H. constructor. eapply IHM1. trivial.\ninversion  H; subst; clear H. constructor. eapply IHM1. apply H1.\ninversion  H; subst; clear H. constructor. eapply IHM2. trivial.\ninversion  H; subst; clear H. constructor. eapply IHM2. apply H1.\nQed.\n\nLemma Tx_ok : forall t, Tv t \\/ Ts t.\ninduction t; intros.\nleft; trivial.\nright; trivial.\ndestruct IHt1.\nleft; constructor; trivial.  right; constructor; trivial.\nright; trivial.\ndestruct IHt2.\nleft; constructor; trivial.  right; constructor; trivial.\nQed.\n\n\nLemma fun_item_lift : forall A A' v Γ , A ↓ v ⊂ Γ -> A' ↓ v ⊂ Γ -> A = A'.\nintros.\ndestruct H as (x & ?& ?). destruct H0 as (x' & ?& ?).\nsubst. replace x' with x. trivial. eapply fun_item. apply H1. apply H2.\nQed.\n\n(** First result: if a term is in [Tv], then all of his types are convertible. *)\nTheorem Shape_of_Type_Tv : forall Γ M A , Γ ⊢ M : A -> forall A',  Γ ⊢ M : A' -> Tv M ->  A ≡ A'.\ninduction 1; intros.\ninversion H2.\n(**)\napply gen_var in H1 as (B & ? &?).\nreplace A with B. intuition. eapply fun_item_lift. apply H3. trivial.\n(**)\ninversion H3; subst; clear H3.\n(**)\ninversion H4; subst; clear H4.\napply gen_la in H3 as (t1 & t2 & t3 & D & h); decompose [and] h;clear h.\neapply Betac_trans. eapply Betac_Pi. apply Betac_refl. eapply IHtyp3. apply H7. trivial.\nintuition.\n(**)\ninversion H2; subst; clear H2.\napply gen_app in H1 as (C & D & ? & ?& ?).\ndestruct (PiInj A B C D). apply IHtyp1. trivial. trivial.\neapply Betac_trans. eapply Betac_subst2. apply H6. intuition.\n(**)\neauto.\nQed.\n\n(** Some properties over [Tels] (reduction, substitutions, ...). *)\nLemma Beta_Tels_inv : forall Γ M N, Tels Γ M  → N -> (exists Γ', N = Tels Γ' M /\\ Γ →e Γ') \\/ \n  (exists M', N = Tels Γ M' /\\ M → M').\ninduction Γ; intros; simpl in *.\nright. exists N; intuition.\ninversion H; subst; clear H.\ndestruct (IHΓ M B' H3). destruct H as (Γ' & -> & ?).\nleft. exists (a::Γ'); intuition.\ndestruct H as (M' & -> & ?).\nright. exists M'; intuition.\n\nleft. exists (A'::Γ); intuition.\nQed.\n\n\nLemma Betas_Tels_inv : forall Γ M N, Tels Γ M →→ N -> exists Γ', exists M', N = Tels Γ' M' /\\ Γ →→e Γ' /\\ M →→ M'.\nintros.\nremember (Tels Γ M) as MM. revert Γ M HeqMM.\ninduction H; intros; subst.\nexists Γ; exists M0; intuition.\napply Beta_Tels_inv in H.\ndestruct H. destruct H as (Γ' & -> & ?).\nexists Γ'; exists M0; intuition.\ndestruct H as (M0' & -> & ?).\nexists Γ; exists M0'; intuition.\ndestruct (IHBetas1 Γ M0) as (Γ' & M' & -> & ?& ?); trivial.\ndestruct (IHBetas2 Γ' M') as (Γ'' & M'' & -> & ?& ?); trivial.\nexists Γ''; exists M''; eauto.\nQed.\n\n\nLemma Betas_Tels : forall Γ Γ' M M', Γ →→e Γ' -> M →→ M' -> Tels Γ M →→ Tels Γ' M'.\nassert (forall l l', l →→e l' -> forall t ,  Tels l t →→ Tels l' t).\ninduction 1; intros; eauto.\ninduction H; simpl; eauto.\nassert (forall t t', t →→ t' -> forall l ,  Tels l t →→ Tels l t').\ninduction 1; intros; eauto.\ninduction l; simpl; eauto.\nintros.\neauto.\nQed.\n\nLemma Betas_not_Pi_to_Sort : forall A B s,  ~ (Π (A), B →→ !s).\nintros; intro. eapply Betac_not_Pi_sort. constructor. apply H.\nQed.\n\n\nFixpoint env_subst Γ n N {struct Γ} := match Γ with\n | nil => nil \n | A::Γ' => (A[n ← N]) :: (env_subst Γ' (S n) N)\nend.\n\nNotation \"E  [[ n ← N ]]\" := (env_subst E n N) (at level 80).\n\nLemma Tels_subst : forall Γ M n N, (Tels Γ M) [n ← N] = Tels (Γ [[n ← N]]) (M [(length Γ + n) ← N]).\ninduction Γ; simpl; intros.\ntrivial.\nrewrite IHΓ.\nrewrite plus_n_Sm. trivial.\nQed.\n\n\nLemma Tels'_subst : forall Γ M n N, (Tels' Γ M) [n ← N] = Tels' (Γ [[n ← N]]) (M [(length Γ + n) ← N]).\ninduction Γ; simpl; intros.\ntrivial.\nrewrite IHΓ.\nrewrite plus_n_Sm. trivial.\nQed.\n\n(** Second Results: if a term is in [Ts], then all of its types are almost\n  convertible: they all reduce to a telescope that ends with a sort, \n  and the body of the telescope is the same for everyone (but not the final\n  sort.*)\nTheorem Shape_of_Type_Ts : forall Γ M T,  Γ ⊢ M : T -> forall T', Γ ⊢ M : T' -> Ts M -> \n  exists s, exists s', exists Γ,  T →→ (Tels Γ !s) /\\ T' →→ (Tels Γ !s').\ninduction 1; intros.\napply gen_sort in H1 as (s' & ?& ?).\napply Betac_sym in H1. apply conv_to_sort in H1.\nexists t; exists s'; exists nil; simpl; intuition.\n(**)\ninversion H2.\n(**)\nclear IHtyp1 IHtyp2.\napply gen_pi in H2 as (s1 & s2 & s3 & h); decompose [and] h; clear h.\napply Betac_sym in H2. apply conv_to_sort in H2.\nexists u; exists s3; exists nil; simpl; intuition.\n(**)\ninversion H4; subst; clear H4.\napply gen_la in H3 as (t1 & t2 & t3 & D & h); decompose [and] h; clear h.\ndestruct (IHtyp3 D H7 H6) as (u & v & l & ?& ?).\napply Betac_confl in H3 as (Z & ? &?).\napply Betas_Pi_inv in H11 as (K & L & -> & ? & ?).\ndestruct (Betas_diamond  D L (Tels l !v)) as ( Z & ?& ?); trivial.\napply Betas_Tels_inv in H14 as (l'' & ? & -> & ? &?).\napply Betas_S in H15; subst.\nexists u; exists v; exists (K::l''); split.\napply Betas_trans with (Tels (A::l) !u). simpl. eauto. simpl.\napply Betas_Pi. trivial. apply Betas_Tels; trivial.\nsimpl. eauto.\n(**)\ninversion H2; subst; clear H2. clear IHtyp2.\napply gen_app in H1 as (C & D & ? & ?&  ?). destruct (IHtyp1 ( Π (C),D) ) as (u & v & l & ? & ?); trivial.\nclear IHtyp1. destruct l; simpl in *. apply Betas_not_Pi_to_Sort in H5; elim H5.\napply Betas_Pi_inv in H5 as (B0 & A0 & ? & ?& ?). injection H5; intros;subst; clear H5.\napply Betas_Pi_inv in H6 as (D0 & C0 & ? & ?& ?). injection H5; intros;subst; clear H5.\napply Betac_confl in H1 as (Z & ?& ?).\ndestruct (Betas_diamond (D[←N]) Z ((Tels l !v)[←N]) H5) as (ZZ & ?& ?).\napply Betas_subst2; trivial.  rewrite Tels_subst in H11. simpl in H11.\napply Betas_Tels_inv in H11. destruct H11 as (l' & x & -> & ?& ?). apply Betas_S in H12. subst.\nexists u ; exists v; exists l'; split. eapply Betas_trans. apply Betas_subst2.  apply H8.\nrewrite Tels_subst. eapply Betas_Tels. trivial. simpl; trivial.\neauto.\n(**)\ndestruct (IHtyp1 T' H2 H3) as (u & v & l & ? & ?).\napply Betac_confl in H as (Z & ? & ?). destruct (Betas_diamond A (Tels l !u) Z H4 H) as (ZZ & ?& ?).\napply Betas_Tels_inv in H7 as (l' & ? & -> & ? & ?). apply Betas_S in H9; subst.\nexists u; exists v; exists l'; split.\napply Betas_trans with Z; trivial. apply Betas_trans with (Tels l !v); trivial.\napply Betas_Tels; trivial.\nQed.\n\n(** Definition of the set [Sigma] for terms in [Ts]. It's almost the set\nof all possible sorts that may appear at the end of the telescope, but \nthat not totally true, just a hint.*)\nInductive Sigma : Env -> Term -> Sorts -> Prop :=\n | Sigma_sorts : forall Γ s s', Ax s s' -> Sigma Γ !s s'\n | Sigma_pi : forall Γ A B s t u, Rel s t u ->\n   ( Tv A -> Γ ⊢ A : !s) -> (Ts A -> Sigma Γ A s) ->\n   ( Tv B -> A::Γ ⊢ B : !t) -> (Ts B -> Sigma (A::Γ) B t) -> Sigma Γ (Π(A),B) u\n | Sigma_la : forall Γ A M s, Sigma (A::Γ) M s -> Sigma Γ (λ[A],M) s\n | Sigma_app : forall Γ M N s, Sigma Γ M s -> Sigma Γ (M· N) s.\n\nHint Constructors Sigma.\n(** Some handy functions.*)\nLemma Tels_tool : forall Γ Γ' s t, Tels Γ !s →→ Tels Γ' !t -> s = t /\\ length Γ = length Γ'.\ninduction Γ; destruct Γ'; simpl in *; intros.\napply Betas_S in H. injection H; intros; subst; intuition.\napply Betas_S in H; discriminate.\napply Betas_not_Pi_to_Sort in H; elim H.\napply Betas_Pi_inv in H as ( C & D & ? & ? & ?). injection H ; intros; subst; clear H.\ndestruct (IHΓ Γ' s t0 H1). subst; intuition. \nQed.\n\nLemma ins_in_env_Sigma : forall a T Δ A n Γ Γ' sa, Γ ⊢ a : T -> Δ ⊢ A : !sa -> Ts a -> ins_in_env Δ A n Γ Γ' -> \n  forall s , Sigma Γ a s <-> Sigma Γ' (a↑1#n) s.\ninduction a; intros; simpl in *.\n(**)\ninversion H1.\n(**)\nsplit; intros. inversion H3; subst; clear H3. intuition. inversion H3; subst; clear H3. intuition.\n(**)\ninversion H1; subst; clear H1. apply gen_app in H  as ( C & D & ? & ?& ?). \ndestruct (IHa1 (Π(C),D) Δ A n Γ Γ' sa H1 H0 H4 H2 s).\nsplit; intros. inversion H7; subst; clear H7. intuition.  inversion H7; subst; clear H7. intuition.\n(**)\napply gen_pi in H as (u & v & w & ? & ? & ? & ?).\nsplit; intros. inversion H6; subst; clear H6. econstructor. apply H9. \nintros. apply Tv_lift in H6. change !s0 with (!s0 ↑ 1 # n). eapply weakening. apply (H10 H6). apply H2. apply H0. \nintros. apply Ts_lift in H6. eapply IHa1. apply H4. apply H0. trivial. apply H2. intuition.\nintros. apply Tv_lift in H6. change !t with (!t ↑ 1 # (S n)). eapply weakening. apply (H13 H6). constructor; apply H2. apply H0.\nintros. apply Ts_lift in H6. eapply IHa2. apply H5. apply H0. trivial. constructor; apply H2. intuition.\n\ninversion H6; subst; clear H6. econstructor. apply H9.\nintros. replace u with s0 in *. trivial. apply conv_sort. eapply Shape_of_Type_Tv. apply H10. apply Tv_lift. trivial. change !u with (!u ↑ 1 # n).\neapply weakening. apply H4. apply H2. apply H0. apply Tv_lift; trivial.\nintros. eapply IHa1. apply H4. apply H0. trivial. apply H2. apply H11. apply Ts_lift; trivial.\nintros. replace v with t in *. trivial. apply conv_sort. eapply Shape_of_Type_Tv. apply H13. apply Tv_lift. trivial. change !v with (!v ↑ 1 # (S n)).\neapply weakening. apply H5. constructor; apply H2. apply H0. apply Tv_lift; trivial.\nintros. eapply IHa2. apply H5. apply H0. trivial. constructor; apply H2. apply H15. apply Ts_lift; trivial.\n(**)\ninversion H1; subst; clear H1. apply gen_la  in H as ( u & v & w &  D & ? & ?& ? & ? & ?). \ndestruct (IHa2 D Δ A (S n) (a1::Γ) (a1↑1#n :: Γ') sa H5 H0 H4) with (s := s). constructor; trivial.\nsplit; intros. inversion H9; subst; clear H9. intuition.  inversion H9; subst; clear H9. intuition.\nQed.\n\nLemma In_Sigma_tool : forall Γ a A, Γ ⊢ a : A -> forall Δ s, Ts a -> A →→ Tels Δ !s -> Sigma Γ a s.\ninduction 1; intros.\n(**)\napply Betas_S in H2. destruct Δ; simpl in H2; try discriminate. injection H2; intros; subst; clear H2.\nintuition.\n(**)\ninversion H1.\n(**)\napply Betas_S in H3. destruct Δ; simpl in H3; try discriminate. injection H3; intros; subst; clear H3.\napply Sigma_pi with s t; intros; trivial.\napply IHtyp1 with nil; simpl; intuition. apply IHtyp2 with nil; simpl; intuition.\n(**)\ninversion H3; subst; clear H3.\napply Betas_Pi_inv in H4 as (A' & ? & ? & ?& ?).\ndestruct Δ; simpl in H3. discriminate. injection H3; intros; subst; clear H3.\nconstructor. apply IHtyp3 with Δ; trivial.\n(**)\ninversion H1; subst; clear H1.\ndestruct (Shape_of_Type_Ts Γ M (Π(A),B) H (Π(A),B) H H4) as (s' & _ & Θ & ? & _ ).\napply Betas_Pi_inv in H1 as (A' & ? & ? & ?& ?).\ndestruct Θ; simpl in H1. discriminate. injection H1; intros; subst; clear H1.\nreplace s with s' in *.\nconstructor. apply IHtyp1 with (A::Θ); simpl; intuition.\ndestruct (Betas_diamond (B[← N]) (Tels Δ !s) (Tels Θ !s')[← N] H2) as (Z & ?& ?).\nintuition. apply Betas_Tels_inv in H1 as (Δ' & ? & -> & ? & ?).\nrewrite Tels_subst in H6. apply Betas_S in H7; subst. simpl in H6.\napply Tels_tool in H6; intuition.\n(**)\ndestruct (Betac_confl A B H) as ( Z  & ?& ?). destruct (Betas_diamond B Z (Tels Δ !s0) H5 H3) as (ZZ & ?& ?).\napply Betas_Tels_inv in H7 as (Θ & ? & -> & ? & ?). apply Betas_S in H8; subst.\neauto.\nQed.\n\nLemma In_Sigma : forall Γ A s, Γ ⊢ A : !s -> Ts A -> Sigma Γ A s.\nintros. apply In_Sigma_tool with !s nil; simpl; trivial.\nQed.\n\n\nLemma env_subst_tool : forall Γ n M, length (Γ[[n ← M]]) = length Γ.\ninduction Γ; simpl in *; intros; intuition.\nQed.\n\n\nFixpoint env_subst_down Γ N n {struct Γ } := match Γ with\n | nil => nil \n | A::Γ' => (A[length Γ' + n ← N]) :: (env_subst_down Γ' N n)\nend.\n\nLemma env_subst_down_app :forall Γ Γ' t n,  env_subst_down (Γ++Γ') t n = (env_subst_down Γ t (length Γ' + n))++(env_subst_down Γ' t n).\ninduction Γ; simpl in *; intros. trivial.\nreplace (length (Γ++Γ')+n) with (length Γ + (length Γ' + n)).\nrewrite IHΓ. trivial. rewrite app_length. intuition.\nQed.\n\nLemma env_subst_down_rev : forall Θ t n, rev (Θ [[n ← t]]) = env_subst_down (rev Θ) t n.\ninduction Θ; simpl in *; intros. trivial.\nrewrite env_subst_down_app. rewrite IHΘ. simpl. trivial.\nQed.\n\nLemma env_subst_down_sub_in_env : forall Θ Γ t A, sub_in_env Γ t A (length Θ) (Θ ++ A :: Γ) (env_subst_down Θ t 0 ++ Γ).\ninduction Θ; simpl in * ;intros. constructor.\nreplace (length Θ+0) with (length Θ) by intuition. apply sub_S. trivial.\nQed.\n\nLemma sub_in_env_rev_append : forall Θ Γ t A ,  sub_in_env Γ t A (length Θ) (rev (A :: Θ) ++ Γ) (rev (Θ [[0 ←t]]) ++ Γ).\nintros. rewrite env_subst_down_rev. simpl. rewrite <- app_assoc;  simpl. rewrite <- rev_length. apply env_subst_down_sub_in_env.\nQed.\n\nLemma Betas_env_length : forall Γ Γ', Γ →→e Γ' -> length Γ = length Γ'.\ninduction 1; intuition. induction H; simpl; intuition.\nrewrite IHBetas_env1. trivial.\nQed.\n\n(** Terms in [Ts] have a particular shape: they are build around sorts and\npi-types, two families of terms that cannot be type by a pi-type. Hence, if an\n  application is in [Ts], it will reduce to some lambda-telescope whose head \nis a sort or a pi-team.*)\n(** (we don't talk of weak head normal form since not all PTS are normalizing\nand we still want to be fully general.*)\nLemma Shape_of_Ts_Term : forall Γ a A, Γ ⊢ a : A -> forall Δ s s1, Ts a -> A →→ Tels Δ !s1 -> Sigma Γ a s -> \n  exists Δ', exists a1, length Δ = length Δ' /\\ a →→ Tels' Δ' a1 /\\ rev Δ'++Γ ⊢ a1 : !s.\ninduction 1; intros.\n(**)\nexists nil; exists !s; simpl; intuition.\ndestruct Δ; simpl in H2. trivial. apply Betas_S in H2; discriminate.\ninversion H3; subst; clear H3. intuition.\n(**)\ninversion H1.\n(**)\nreplace Δ with (@nil Term) in *. simpl in *.\ninversion H4; subst; clear H4.\ndestruct (Tx_ok A).\n  destruct (Tx_ok B).\n    exists nil; exists (Π(A),B); simpl; intuition. econstructor. apply H7. trivial. trivial.\n    \n    destruct (IHtyp2 nil t0 t H5 ) as (Δ' & b & ? & ? & ?). simpl; trivial. intuition.\n    replace Δ' with (@nil Term) in *; simpl in *. exists nil; exists (Π(A), b); simpl; intuition.\n    econstructor. apply H7. trivial. trivial. destruct Δ'. trivial. discriminate.\n  destruct (IHtyp1 nil s2 s) as (Δ' & a & ? & ?& ?). trivial. simpl; trivial. intuition.\n  replace Δ' with (@nil Term) in *; simpl in *. destruct (Tx_ok B).\n    exists nil; exists (Π(a),B); simpl; intuition. econstructor. apply H7. trivial.\n    eapply Betas_env_sound. apply H9. apply Betas_env_comp; intuition.\n\n    destruct (IHtyp2 nil t0 t H12) as (Δ'' & b & ? & ? & ?). simpl; trivial. intuition.\n    replace Δ'' with (@nil Term) in *; simpl in *. exists nil; exists (Π(a),b); simpl; intuition.\n    econstructor. apply H7. trivial. eapply Betas_env_sound. apply H16. apply Betas_env_comp; intuition.\n    destruct Δ''. trivial. discriminate.     destruct Δ'. trivial. discriminate.\n    apply Betas_S in H3. destruct Δ. trivial. discriminate.\n(**)\ninversion H3; subst; clear H3. inversion H5; subst; clear H5. apply Betas_Pi_inv in H4 as (A' & B' & ? & ?& ?).\ndestruct Δ. discriminate. injection H3; intros; subst; clear H3.\ndestruct (IHtyp3 Δ s s0 H7 H5 H10) as (Δ' & b' & ? & ? & ?).\nexists (A::Δ'); exists b'; simpl; intuition. rewrite <- app_assoc. simpl. trivial.\n(**)\ninversion H3; subst; clear H3. inversion H1; subst; clear H1.\ndestruct (Shape_of_Type_Ts Γ M (Π(A),B) H (Π(A),B) H H4) as ( sa & _ & Θ & ? & _ ).\napply Betas_Pi_inv in H1 as (A' & B' & ? & ?& ?). destruct Θ. discriminate.\ninjection H1; intros; subst; clear H1. replace sa with s1 in *.\ndestruct (IHtyp1 (A::Θ) s s1 H4) as ( Θ' & m & ? & ? &?). simpl; intuition. trivial.\ndestruct Θ' as [ | A'' Θ']. discriminate. simpl in H1. injection H1; intros; subst; clear H1.\nexists (Θ'[[ 0 ← N]]); exists (m[ (length Θ' )← N]); repeat split.\nrewrite env_subst_tool.   destruct (Betas_diamond (B[← N]) (Tels Δ !s1) (Tels Θ !s1)[← N] H2 ) as (Z & ?& ?).\nintuition. apply Betas_Tels_inv in H1 as (? & ?& -> & ?& ?).\nrewrite Tels_subst in H10. apply Betas_S in H11; subst.\napply Tels_tool in H10 as ( _ & ?). replace (length Δ) with (length x).\nrewrite env_subst_tool in H10. rewrite <- H9; intuition. apply Betas_env_length in H1. intuition. apply Betas_trans with ((λ[A''],Tels' Θ' m)· N).\nintuition. replace (length Θ') with (length Θ' + 0). rewrite <- Tels'_subst. constructor.\nconstructor. intuition. assert (A≡ A'' /\\ exists s, Γ ⊢ A'' : !s).\nassert ( Γ ⊢ λ[A''],Tels' Θ' m : Π(A),B). eapply SubjectRed. apply H. trivial.\n  apply gen_la in H1 as ( ss & ? & ? & ? & ? & _ & ? & _ ). split.\n  apply PiInj in H1; intuition. exists ss; trivial.\nchange !s with (!s[ (length Θ') ← N]).   destruct H1 as (? & ss & ?). eapply substitution. apply H7.  eapply Cnv. apply H1. apply H0.\napply H10. apply sub_in_env_rev_append. apply wf_typ in H7; trivial.  destruct (Betas_diamond (B[← N]) (Tels Δ !s1) (Tels Θ !sa)[← N] H2) as (Z & ?& ?).\nintuition. apply Betas_Tels_inv in H1 as (Δ' & ? & -> & ? & ?).\nrewrite Tels_subst in H6. apply Betas_S in H7; subst. simpl in H6.\napply Tels_tool in H6; intuition.\n(**)\ndestruct (Betac_confl A B H) as (Z & ? & ?). destruct (Betas_diamond B (Tels Δ !s1) Z H3 H6) as (ZZ & ? &?).\napply Betas_Tels_inv in H7 as (? & ? & -> & ? & ?). apply Betas_S in H9; subst.\ndestruct (IHtyp1 x s0 s1 H2) as ( Δ' & a1 & ? & ? & ?). eauto. trivial.\nexists Δ'; exists a1; intuition. rewrite <- H9. apply Betas_env_length in H7. trivial.\nQed.\n\nLemma Ts_Sigma_Shape : forall Γ A s, Γ ⊢ A : !s -> forall s', Ts A -> Sigma Γ A s' -> exists A', A →→ A' /\\ Γ ⊢ A' : !s'.\nintros.\ndestruct (Shape_of_Ts_Term Γ A !s H nil s' s H0) as ( ? & a & ? & ? & ?). simpl; trivial. trivial.\nreplace x with (@nil Term) in *; simpl in *.\nexists a; intuition. destruct x. trivial. discriminate.\nQed.\n\n(* begin hide *)\nLemma L1 : forall Δ Z n Γ0 Γ, ins_in_env Δ Z n Γ0 Γ -> forall v a, n <= v -> a ↓ S v ∈ Γ ->\n  a ↓ v ∈ Γ0.\ninduction 1; intros. inversion H0; subst; clear H0. trivial.\ninversion H1; subst; clear H1. destruct v. apply le_Sn_O in H0. contradict H0; intuition.\napply le_S_n in H0. constructor. intuition.\nQed.\n\n\nLemma L2 : forall Δ Z n Γ0 Γ, ins_in_env Δ Z n Γ0 Γ -> forall v a, n > v ->  a ↓ v ∈ Γ ->\n exists b, b ↓ v ∈ Γ0 /\\ b↑1# (n-S v) = a.\ninduction 1; intros. unfold gt in H. apply lt_n_O in H; elim H. inversion H1; subst; clear H1.\nexists d; intuition. replace (S n - 1) with n by intuition. trivial.\napply lt_S_n in H0. destruct (IHins_in_env n0 a) as ( b & ? & ?). intuition. trivial.\nexists b; split. intuition. replace (S n - S (S n0)) with (n - S n0) by intuition.\ntrivial.\nQed.\n\n\nLemma ins_in_env_wf : forall Δ A n Γ Γ', ins_in_env Δ A n Γ Γ' -> Γ' ⊣ -> exists s, Δ ⊢ A : !s.\ninduction 1; intros.\ninversion H; subst; clear H. exists s; trivial.\ninversion H0; subst; clear H0. apply wf_typ in H2. intuition.\nQed.\n(* \\end *)\nLemma Beta_lift_inv : forall a b n m , a ↑ n # m → b -> exists a', a → a' /\\  b = a' ↑ n # m .\ninduction a; intros; simpl in *.\ndestruct le_gt_dec. inversion H. inversion H. inversion H.\ninversion H; subst; clear H. destruct a1; simpl in H1; try discriminate. destruct le_gt_dec ; discriminate.\ninjection H1; intros; subst; clear H1. exists (a1_2 [ ← a2]); intuition.\nchange m with (0+m). rewrite <- substP1. simpl; trivial.\napply IHa1 in H3 as ( a' & ?& ->). exists (App a' a2); intuition.\napply IHa2 in H3 as ( a' & ?& ->). exists (App a1 a'); intuition.\ninversion H; subst; clear H. apply IHa2 in H3 as (a' & ? & ->). exists (Pi a1 a'); intuition.\napply IHa1 in H3 as (a' & ? & ->). exists (Pi a' a2); intuition.\ninversion H; subst; clear H. apply IHa2 in H3 as (a' & ? & ->). exists (La a1 a'); intuition.\napply IHa1 in H3 as (a' & ? & ->). exists (La a' a2); intuition.\nQed.\n\nLemma Betas_lift_inv : forall a b n m , a ↑ n # m →→ b -> exists a', a →→ a' /\\  b = a' ↑ n # m .\nintros. remember (lift_rec n m a) as A. revert n m a HeqA.\ninduction H; intros; subst. exists a; intuition.\napply Beta_lift_inv in H as ( b & ? & ->). exists b; intuition.\ndestruct (IHBetas1 n m a) as (b & ? & -> ); trivial.\ndestruct (IHBetas2 n m b) as (c & ? & -> ); trivial.\nexists c; intuition; eauto.\nQed.\n\n(* end hide *)\n(** To prove strenghthening, we will first prove that if the hypothesis is not\n  used in the term, we can safely remove it, but we may need to beta reduce the\nterm in order to be still valid. *)\nTheorem WeakStrenghthening : (forall Γ' M T, Γ' ⊢ M : T -> forall m n Δ A Γ, M = m ↑ 1 # n -> \n  ins_in_env Δ A n Γ Γ' ->  exists T', T →→ T'↑ 1 # n /\\ Γ ⊢ m : T' ) /\\\n  (forall Γ', Γ' ⊣ -> forall n Δ A Γ, ins_in_env Δ A n Γ Γ' -> Γ ⊣).\napply typ_induc; intros.\n(**)\ndestruct m; simpl in H0; try discriminate. destruct le_gt_dec; discriminate. injection H0; intros; subst; clear H0.\nexists !t; split; trivial. constructor. trivial. eauto.\n(**)\ndestruct m; simpl in H0; try discriminate. destruct le_gt_dec; injection H0; intros; subst; clear H0.\ndestruct i as ( a & ? & ?).   exists (a ↑ (S v0)); split. rewrite liftP3; subst; intuition. simpl. constructor; trivial.\nconstructor. eauto. exists a; intuition. eapply L1. apply H1. trivial. trivial.\n\ndestruct i as (a & ? & ?). destruct (L2 Δ A0 n Γ0 Γ H1 v0 a g H2) as ( b& ? & ?). exists (b ↑ (S v0)); split.\nreplace n with (S v0 + (n - S v0)) by intuition. rewrite liftP2; intuition. rewrite H4. rewrite H0. intuition.\nconstructor. eauto. exists b; intuition.\n(**)\ndestruct m; simpl in H1; try discriminate. destruct le_gt_dec; discriminate. injection H1; intros; subst; clear H1.\ndestruct (H m1 n Δ A0 Γ0) as (A' & ? & ?); trivial. replace A' with !s in *. clear H1; simpl in *. clear H.\ndestruct (H0 m2 (S n) Δ A0 (m1::Γ0)) as (B' & ? & ?); trivial. constructor. trivial. replace B' with !t in *. clear H; simpl in *. clear H0.\nexists !u; intuition. apply cPi with s t; trivial.\napply Betas_S in H. destruct B'; try discriminate. unfold lift_rec in H; destruct le_gt_dec; discriminate. intuition.\napply Betas_S in H1. destruct A'; try discriminate. unfold lift_rec in H1; destruct le_gt_dec; discriminate. intuition.\n(**)\ndestruct m; simpl in H2; try discriminate. destruct le_gt_dec; discriminate. injection H2; intros; subst; clear H2.\ndestruct (H m1 n Δ A0 Γ0) as (A' & ? & ?); trivial. replace A' with !s1 in *; simpl in *. clear H2. clear H.\ndestruct (H1 m2 (S n) Δ A0 (m1::Γ0)) as (M & ? & ?); trivial. constructor; trivial. clear H1.\nassert (m1↑1#n::Γ ⊢ M ↑ 1 # (S n) : !s2). eapply SubjectRed. apply t0. trivial.\ndestruct (TypeCorrect (m1::Γ0) m2 M H2) as [ [w ?] | [w ?] ]. \n  subst; simpl in H1. apply gen_sort in H1 as (ss & ?  & ?). assert (m1::Γ0 ⊢ !w : !s2).\n  apply conv_sort in H1. subst. constructor. trivial. apply wf_typ in H2; trivial.\n  exists (Π(m1),!w);simpl; intuition. apply cLa with s1 s2 s3; trivial.\n\n  assert (m1 ↑ 1 # n :: Γ ⊢ M ↑ 1 # (S n) : !w). change !w with (!w↑ 1 # (S n)). destruct (ins_in_env_wf Δ A0 n Γ0 Γ H3) as (a & ? ).\n  apply wf_typ in t; trivial. eapply weakening. apply H5. constructor. apply H3. apply H6.\n  destruct (Tx_ok (M↑ 1 # (S n))). replace w with s2 in *. exists (Π(m1),M); simpl; intuition.\n  apply cLa with s1 s2 s3; trivial. apply conv_sort. eapply Shape_of_Type_Tv. apply H1. trivial. trivial. \n  destruct (Ts_Sigma_Shape (m1::Γ0) M w H5 s2) as ( M' & ? & ?). apply Ts_lift in H7; trivial.\n  destruct (ins_in_env_wf Δ A0 (S n) (m1::Γ0) (m1↑1#n::Γ)) as (d & ?). constructor; trivial. apply wf_typ in H1; trivial.\n  eapply ins_in_env_Sigma. apply H5. apply H8. apply Ts_lift in H7; trivial. constructor. apply H3. apply In_Sigma; trivial.\n  exists (Π(m1),M'); simpl; split. eauto. apply cLa with s1 s2 s3; trivial. eauto.\n  apply Betas_S in H2. destruct A'; try discriminate. unfold lift_rec in H2; destruct le_gt_dec; discriminate. intuition.\n(**)\ndestruct m; simpl in H1; try discriminate. destruct le_gt_dec; discriminate. injection H1; intros; subst; clear H1.\ndestruct (H m1 n Δ A0 Γ0) as (P & ? & ?); trivial. apply Betas_Pi_inv in H1 as (C & D & ? & ?& ?). \ndestruct P; try discriminate. unfold lift_rec in H1; destruct le_gt_dec; discriminate. injection H1; intros; subst; clear H1.\ndestruct (H0 m2 n Δ A0 Γ0) as (A' & ? & ?); trivial. destruct (Betas_diamond A (P1 ↑ 1 # n) (A' ↑ 1 # n) H4 H1) as ( Z & ?& ?).\napply Betas_lift_inv in H7. destruct H7 as (ZZ & ? & -> ).\napply Betas_lift_inv in H8. destruct H8 as (? & ? & ?). apply inv_lift in H9. subst.\nexists (P2 [← m2 ]); split. change n with (0+n). rewrite substP1. intuition. apply cApp with x.\neapply Betas_typ_sound. apply H3. intuition. eapply Betas_typ_sound. apply H6. intuition.\n(**)\ndestruct (H m n Δ A0 Γ0 H1 H2) as (a' & ? & ?).\ndestruct (Betac_confl A B b) as ( Z & ? &?). destruct (Betas_diamond A (a'↑ 1 # n) Z H3 H5) as (ZZ & ?& ?).\napply Betas_lift_inv in H7. destruct H7 as (aa & ? & -> ). exists aa; split. eauto.\neapply Betas_typ_sound. apply H4. trivial.\n(* wf *)\ninversion H.\n(**)\ninversion H0; subst; clear H0.\napply wf_typ in t; trivial.\ndestruct (H d n0 Δ A0 Δ0) as (? & ? & ?); trivial.\napply Betas_S in H0. destruct x; try discriminate. unfold lift_rec in H0; destruct le_gt_dec; discriminate.\neauto.\nQed.\n\n(** With the previous lemma and Type Correctness, we can prove the full lemma:\nif an hypothesis is not used in the term and it's type, we can simply remove\n  it.*)\nTheorem Strenghthening: forall Γ' M n T, Γ' ⊢ M ↑ 1 # n: T ↑ 1 # n -> forall Δ A Γ, ins_in_env Δ A n Γ Γ' ->  \n Γ ⊢ M : T.\nintros. destruct WeakStrenghthening as ( ? & _ ). destruct (H1 Γ' (M↑ 1 # n) (T↑ 1 # n) H M n Δ A Γ) as (T' & ? & ?); trivial.\napply Betas_lift_inv in H2 as ( ? & ?& ?). apply inv_lift in H4; subst.\napply TypeCorrect in H as [ [ w ?]|[ w ?] ]. destruct T ; try discriminate. unfold lift_rec in H; destruct le_gt_dec; discriminate.\napply Betas_S in H2; subst. trivial. destruct (H1 Γ' (T↑1#n) !w H T n Δ A Γ) as (T'' & ? & ?); trivial. apply Betas_S in H4. \ndestruct T'' ; try discriminate. unfold lift_rec in H4; destruct le_gt_dec; discriminate. eauto.\nQed.\n  \n  \nEnd ut_strengh_mod.\n", "meta": {"author": "coq-contribs", "repo": "ptsatr", "sha": "e57ad4552055340ea97bc6a2c61b837c56c11a7d", "save_path": "github-repos/coq/coq-contribs-ptsatr", "path": "github-repos/coq/coq-contribs-ptsatr/ptsatr-e57ad4552055340ea97bc6a2c61b837c56c11a7d/ut_strengh.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.2815666804993119}}
{"text": "Require Import CertiGraph.prim.prim_env.\nRequire Export CertiGraph.priq.priq_arr_specs.\nRequire Import CertiGraph.graph.MathUAdjMatGraph.\nRequire Import CertiGraph.prim.prim_constants.\nRequire Import CertiGraph.graph.SpaceUAdjMatGraph2.\nRequire Export CertiGraph.prim.prim2.\n\nLocal Open Scope Z_scope.\n\nSection PrimSpec.\n  \nContext {Z_EqDec : EquivDec.EqDec Z eq}.\n  \nInstance CompSpecs : compspecs. Proof. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\nGlobal Existing Instance CompSpecs.\n\nDefinition G := @UAdjMatGG size inf.\nIdentity Coercion UAdjMatGG_G: G >-> UAdjMatGG.\n\nDefinition getCell_spec :=\n  DECLARE _getCell\n  WITH g: G,\n       graph_ptr: pointer_val,\n       addresses: list val,\n       u: V,\n       i : V\n  PRE [tptr tint, tint, tint]\n    PROP (0 <= i < size;\n         0 <= u < size;\n         Forall (fun list => Zlength list = size) (@graph_to_mat size g eformat);\n         (size * size <= Int.max_signed))\n    PARAMS (pointer_val_val graph_ptr;\n           Vint (Int.repr u);\n           Vint (Int.repr i))\n    GLOBALS ()\n    SEP (@SpaceAdjMatGraph' size CompSpecs Tsh (@graph_to_list size g eformat) (pointer_val_val graph_ptr))\n  POST [tint]\n    PROP ()\n    RETURN (Vint (Int.repr (Znth i (Znth u (@graph_to_symm_mat size g))))) \n    SEP (@SpaceAdjMatGraph' size CompSpecs Tsh (@graph_to_list size g eformat) (pointer_val_val graph_ptr)).\n\nDefinition initialise_list_spec :=\n  DECLARE _initialise_list\n  WITH arr : val, old_list: list val, a: Z\n  PRE [tptr tint, tint]\n     PROP ( writable_share Tsh;\n            repable_signed a;\n            size <= Int.max_signed\n          )\n     PARAMS ( arr; Vint (Int.repr a) )\n     GLOBALS ()\n     SEP (data_at Tsh (tarray tint size) (old_list) (arr))\n  POST [ tvoid ]\n     PROP ()\n     LOCAL ()\n     SEP (data_at Tsh (tarray tint size) (list_repeat (Z.to_nat size) (Vint (Int.repr a))) arr\n         ).\n\nDefinition initialise_matrix_spec :=\n  DECLARE _initialise_matrix\n  WITH arr : val, old_contents: list Z, a: Z\n  PRE [tptr tint, tint]\n     PROP ( writable_share Tsh;\n            Zlength old_contents = Z.mul size size;\n            repable_signed a;\n            0 < size <= Int.max_signed; (*this is not enough for malloc, requires*)\n            size * (4 * size) <= Ptrofs.max_signed (*you can alloc the entire matrix. Can derive above from here*)\n          )\n     PARAMS ( arr ; Vint (Int.repr a) )\n     GLOBALS ()\n     SEP (@SpaceAdjMatGraph' size CompSpecs Tsh old_contents arr)\n  POST [ tvoid ]\n     PROP ()\n     LOCAL ()\n     SEP (@SpaceAdjMatGraph' size CompSpecs Tsh (list_repeat (Z.to_nat (Z.mul size size)) a) arr).\n\nDefinition prim_spec :=\n  DECLARE _prim\n  WITH g: G, garbage: list V, gptr : pointer_val, r: Z, parent_ptr : pointer_val\n  PRE [tptr tint, tint, tptr tint]\n     PROP ( writable_share Tsh;\n            vvalid g r;\n            size * (4 * size) <= Ptrofs.max_signed;\n            Forall (fun list => Zlength list = size) (@graph_to_mat size g eformat)\n          )\n     PARAMS ( pointer_val_val gptr; (Vint (Int.repr r)); pointer_val_val parent_ptr)\n     GLOBALS ()\n     SEP (@SpaceAdjMatGraph' size CompSpecs Tsh (@graph_to_list size g eformat) (pointer_val_val gptr); \n          data_at Tsh (tarray tint size) (map (fun x => Vint (Int.repr x)) garbage) (pointer_val_val parent_ptr)\n         )\n  POST [ tvoid ]\n     EX mst: G,\n     EX fmst: FiniteGraph mst,\n     EX parents: list V,\n     PROP ( (*connected_graph mst;*)\n            @minimum_spanning_forest size inf mst g;\n            Permutation (EList mst) (map (fun v => eformat (v, Znth v parents))\n              (filter (fun v => Znth v parents <? size) (nat_inc_list (Z.to_nat size))))\n          )\n     RETURN ()\n     SEP (@SpaceAdjMatGraph' size CompSpecs Tsh (@graph_to_list size g eformat) (pointer_val_val gptr);\n          data_at Tsh (tarray tint size) (map (fun x => Vint (Int.repr x)) parents) (pointer_val_val parent_ptr)\n         ).\n\nDefinition Gprog: funspecs :=\n  ltac:(with_library prog\n                     [(@push_spec size inf _);\n                     (@pq_emp_spec size inf _);\n                     (@popMin_spec size inf Z_EqDec _);\n                     (@adjustWeight_spec size inf _);\n                     (@init_spec size _);\n                     freePQ_spec;\n                     getCell_spec;\n                     initialise_list_spec;\n                     initialise_matrix_spec;\n                     prim_spec\n       ]).\n\nEnd PrimSpec.\n", "meta": {"author": "anshumanmohan", "repo": "CertiDPK", "sha": "28afacefb162a27e74d744095229d9e4541e3d79", "save_path": "github-repos/coq/anshumanmohan-CertiDPK", "path": "github-repos/coq/anshumanmohan-CertiDPK/CertiDPK-28afacefb162a27e74d744095229d9e4541e3d79/prim/prim_spec2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2815032045082243}}
{"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 A B C Y P Z Q Qprime Cprime : Universe, ((wd_ A Y /\\ (wd_ P Y /\\ (wd_ Q Y /\\ (wd_ A B /\\ (wd_ B C /\\ (wd_ A C /\\ (wd_ P Q /\\ (wd_ A Z /\\ (wd_ B Y /\\ (wd_ Y Qprime /\\ (wd_ Qprime Cprime /\\ (wd_ Y Z /\\ (wd_ Z Y /\\ (wd_ C Y /\\ (wd_ P C /\\ (wd_ Y Cprime /\\ (wd_ Q C /\\ (wd_ Q Qprime /\\ (wd_ C Cprime /\\ (wd_ Cprime Y /\\ (wd_ P Q /\\ (col_ P Y Q /\\ (col_ P Y C /\\ (col_ P Q C /\\ (col_ Y Q C /\\ (col_ A Y B /\\ (col_ A Y Z /\\ (col_ A B Z /\\ (col_ Y B Z /\\ (col_ Q Y P /\\ (col_ Y Qprime Cprime /\\ (col_ Y Cprime P /\\ (col_ Y P Qprime /\\ (col_ C Y Cprime /\\ col_ Q Z Qprime)))))))))))))))))))))))))))))))))) -> col_ Y Q Qprime)).\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_0018.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.28139332073307194}}
{"text": "From ITree Require Import ITree.\nFrom ITreeTutorial Require Import Imp.\nFrom Coq Require Import NArith String.\n\nLocal Open Scope string_scope.\n\nImport ImpNotations.\n\nDefinition loopy : stmt :=\n  WHILE 1 DO Skip.\n\nFixpoint run {A} (n : nat) (t : itree void1 A) : option A :=\n  match n, observe t with\n  | O, _ => None\n  | S _, RetF a => Some a\n  | S n, TauF t => run n t\n  | S _, VisF e _ => match e with end\n  end.\n\nDefinition run_ (n : N) (s : stmt) : option env :=\n  option_map fst (run (N.to_nat n) (eval_imp s)).\n\nRequire Extraction.\nRequire ExtrOcamlBasic.\nRequire ExtrOcamlString.\nRequire ExtrOcamlNatInt.\n\nParameter io : Type.\nExtract Inlined Constant io => \"(unit -> unit)\".\n\nParameter seq : io -> io -> io.\nExtract Constant seq => \"fun a b () -> a (); b ()\".\n\nParameter print_binding : var -> nat -> io.\nExtract Constant print_binding =>\n  \"fun v n () ->\n     let to_string l =\n       let l_ = ref l in\n       String.init (List.length l) (fun _ ->\n         match !l_ with\n         | h :: t -> l_ := t; h\n         | [] -> assert false) in\n     let v = to_string v in\n     print_string v;\n     print_string \"\":=\"\";\n     print_int n;\n     print_string \"\";\"\"\".\n\nParameter print_newline : io.\nExtract Inlined Constant print_newline => \"print_newline\".\n\nParameter nit : Type.\nExtract Inlined Constant nit => \"unit\".\n\nParameter run_io : io -> nit.\nExtract Constant run_io => \"fun w -> w ()\".\n\nFixpoint print_env (e : env) : io :=\n  match e with\n  | nil => print_newline\n  | cons (v, n) e => seq (print_binding v n) (print_env e)\n  end.\n\nDefinition run' (n : N) (s : stmt) : io :=\n  match run_ n s with\n  | None => print_newline\n  | Some e => print_env e\n  end.\n\nDefinition test : nit :=\n  run_io (\n    seq (run' 100 loopy)\n        (run' 1000 (fact \"X\" \"Y\" 10)%string)\n  ).\n\nExtraction \"imp_test.ml\" test.\n", "meta": {"author": "DeepSpec", "repo": "InteractionTrees", "sha": "8e28e2ee08496c696e03916a22d93c39559a9715", "save_path": "github-repos/coq/DeepSpec-InteractionTrees", "path": "github-repos/coq/DeepSpec-InteractionTrees/InteractionTrees-8e28e2ee08496c696e03916a22d93c39559a9715/tutorial/extract-imptest/ImpTest.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.28136268373641865}}
{"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(** Computation of resource bounds for Linear code. *)\n\nRequire Import Coqlib.\nRequire Import AST.\nRequire Import Op.\nRequire Import Locations.\nRequire Import Linear.\nRequire Import Lineartyping.\nRequire Import Conventions.\n\nSection WITHEF.\nContext `{Hsc: SyntaxConfiguration}.\n\n(** * Resource bounds for a function *)\n\n(** The [bounds] record capture how many local and outgoing stack slots\n  and callee-save registers are used by a function. *)\n\n(** We demand that all bounds are positive or null.\n  These properties are used later to reason about the layout of\n  the activation record. *)\n\nRecord bounds : Type := mkbounds {\n  bound_int_local: Z;\n  bound_float_local: Z;\n  bound_int_callee_save: Z;\n  bound_float_callee_save: Z;\n  bound_outgoing: Z;\n  bound_stack_data: Z;\n  bound_int_local_pos: bound_int_local >= 0;\n  bound_float_local_pos: bound_float_local >= 0;\n  bound_int_callee_save_pos: bound_int_callee_save >= 0;\n  bound_float_callee_save_pos: bound_float_callee_save >= 0;\n  bound_outgoing_pos: bound_outgoing >= 0;\n  bound_stack_data_pos: bound_stack_data >= 0\n}.\n\n(** The following predicates define the correctness of a set of bounds\n    for the code of a function. *)\n\nSection BELOW.\n\nVariable funct: function.\nVariable b: bounds.\n\nDefinition mreg_within_bounds (r: mreg) :=\n  match mreg_type r with\n  | Tint => index_int_callee_save r < bound_int_callee_save b\n  | Tfloat => index_float_callee_save r < bound_float_callee_save b\n  end.\n\nDefinition slot_within_bounds (s: slot) :=\n  match s with\n  | Local ofs Tint => 0 <= ofs < bound_int_local b\n  | Local ofs Tfloat => 0 <= ofs < bound_float_local b\n  | Outgoing ofs ty => 0 <= ofs /\\ ofs + typesize ty <= bound_outgoing b\n  | Incoming ofs ty => In (S s) (loc_parameters funct.(fn_sig))\n  end.\n\nDefinition instr_within_bounds (i: instruction) :=\n  match i with\n  | Lgetstack s r => slot_within_bounds s /\\ mreg_within_bounds r\n  | Lsetstack r s => slot_within_bounds s\n  | Lop op args res => mreg_within_bounds res\n  | Lload chunk addr args dst => mreg_within_bounds dst\n  | Lcall sig ros => size_arguments sig <= bound_outgoing b\n  | Lbuiltin ef args res => mreg_within_bounds res\n  | Lannot ef args => forall s, In (S s) args -> slot_within_bounds s\n  | _ => True\n  end.\n\nEnd BELOW.\n\nDefinition function_within_bounds (f: function) (b: bounds) : Prop :=\n  forall instr, In instr f.(fn_code) -> instr_within_bounds f b instr.\n\n(** * Inference of resource bounds for a function *)\n\n(** The resource bounds for a function are computed by a linear scan\n  of its instructions. *)\n\nSection BOUNDS.\n\nVariable f: function.\n\n(** In the proof of the [Stacking] pass, we only need to bound the\n  registers written by an instruction.  Therefore, this function\n  returns these registers, ignoring registers used only as\n  arguments. *)\n\nDefinition regs_of_instr (i: instruction) : list mreg :=\n  match i with\n  | Lgetstack s r => r :: nil\n  | Lsetstack r s => r :: nil\n  | Lop op args res => res :: nil\n  | Lload chunk addr args dst => dst :: nil\n  | Lstore chunk addr args src => nil\n  | Lcall sig ros => nil\n  | Ltailcall sig ros => nil\n  | Lbuiltin ef args res => res :: nil\n  | Lannot ef args => nil\n  | Llabel lbl => nil\n  | Lgoto lbl => nil\n  | Lcond cond args lbl => nil\n  | Ljumptable arg tbl => nil\n  | Lreturn => nil\n  end.\n\nFixpoint slots_of_locs (l: list loc) : list slot :=\n  match l with\n  | nil => nil\n  | S s :: l' => s :: slots_of_locs l'\n  | R r :: l' => slots_of_locs l'\n  end.\n\nDefinition slots_of_instr (i: instruction) : list slot :=\n  match i with\n  | Lgetstack s r => s :: nil\n  | Lsetstack r s => s :: nil\n  | Lannot ef args => slots_of_locs args\n  | _ => nil\n  end.\n\nDefinition max_over_list (A: Type) (valu: A -> Z) (l: list A) : Z :=\n  List.fold_left (fun m l => Zmax m (valu l)) l 0.\n\nDefinition max_over_instrs (valu: instruction -> Z) : Z :=\n  max_over_list instruction valu f.(fn_code).\n\nDefinition max_over_regs_of_instr (valu: mreg -> Z) (i: instruction) : Z :=\n  max_over_list mreg valu (regs_of_instr i).\n\nDefinition max_over_slots_of_instr (valu: slot -> Z) (i: instruction) : Z :=\n  max_over_list slot valu (slots_of_instr i).\n\nDefinition max_over_regs_of_funct (valu: mreg -> Z) : Z :=\n  max_over_instrs (max_over_regs_of_instr valu).\n\nDefinition max_over_slots_of_funct (valu: slot -> Z) : Z :=\n  max_over_instrs (max_over_slots_of_instr valu).\n\nDefinition int_callee_save (r: mreg) := 1 + index_int_callee_save r.\n\nDefinition float_callee_save (r: mreg) := 1 + index_float_callee_save r.\n\nDefinition int_local (s: slot) :=\n  match s with Local ofs Tint => 1 + ofs | _ => 0 end.\n\nDefinition float_local (s: slot) :=\n  match s with Local ofs Tfloat => 1 + ofs | _ => 0 end.\n\nDefinition outgoing_slot (s: slot) :=\n  match s with Outgoing ofs ty => ofs + typesize ty | _ => 0 end.\n\nDefinition outgoing_space (i: instruction) :=\n  match i with Lcall sig _ => size_arguments sig | _ => 0 end.\n\nLemma max_over_list_pos:\n  forall (A: Type) (valu: A -> Z) (l: list A),\n  max_over_list A valu l >= 0.\nProof.\n  intros until valu. unfold max_over_list.\n  assert (forall l z, fold_left (fun x y => Zmax x (valu y)) l z >= z).\n  induction l; simpl; intros.\n  omega. apply Zge_trans with (Zmax z (valu a)). \n  auto. apply Zle_ge. apply Zmax1. auto.\nQed.\n\nLemma max_over_slots_of_funct_pos:\n  forall (valu: slot -> Z), max_over_slots_of_funct valu >= 0.\nProof.\n  intros. unfold max_over_slots_of_funct.\n  unfold max_over_instrs. apply max_over_list_pos.\nQed.\n\nLemma max_over_regs_of_funct_pos:\n  forall (valu: mreg -> Z), max_over_regs_of_funct valu >= 0.\nProof.\n  intros. unfold max_over_regs_of_funct.\n  unfold max_over_instrs. apply max_over_list_pos.\nQed.\n \nProgram Definition function_bounds :=\n  mkbounds\n    (max_over_slots_of_funct int_local)\n    (max_over_slots_of_funct float_local)\n    (max_over_regs_of_funct int_callee_save)\n    (max_over_regs_of_funct float_callee_save)\n    (Zmax (max_over_instrs outgoing_space)\n          (max_over_slots_of_funct outgoing_slot))\n    (Zmax f.(fn_stacksize) 0)\n    (max_over_slots_of_funct_pos int_local)\n    (max_over_slots_of_funct_pos float_local)\n    (max_over_regs_of_funct_pos int_callee_save)\n    (max_over_regs_of_funct_pos float_callee_save)\n    _ _.\nNext Obligation.\n  apply Zle_ge. eapply Zle_trans. 2: apply Zmax2.\n  apply Zge_le. apply max_over_slots_of_funct_pos.  \nQed.\nNext Obligation.\n  apply Zle_ge. apply Zmax2.\nQed.\n\n(** We now show the correctness of the inferred bounds. *)\n\nLemma max_over_list_bound:\n  forall (A: Type) (valu: A -> Z) (l: list A) (x: A),\n  In x l -> valu x <= max_over_list A valu l.\nProof.\n  intros until x. unfold max_over_list.\n  assert (forall c z,\n            let f := fold_left (fun x y => Zmax x (valu y)) c z in\n            z <= f /\\ (In x c -> valu x <= f)).\n    induction c; simpl; intros.\n    split. omega. tauto.\n    elim (IHc (Zmax z (valu a))); intros. \n    split. apply Zle_trans with (Zmax z (valu a)). apply Zmax1. auto. \n    intro H1; elim H1; intro. \n    subst a. apply Zle_trans with (Zmax z (valu x)). \n    apply Zmax2. auto. auto.\n  intro. elim (H l 0); intros. auto.\nQed.\n\nLemma max_over_instrs_bound:\n  forall (valu: instruction -> Z) i,\n  In i f.(fn_code) -> valu i <= max_over_instrs valu.\nProof.\n  intros. unfold max_over_instrs. apply max_over_list_bound; auto.\nQed.\n\nLemma max_over_regs_of_funct_bound:\n  forall (valu: mreg -> Z) i r,\n  In i f.(fn_code) -> In r (regs_of_instr i) ->\n  valu r <= max_over_regs_of_funct valu.\nProof.\n  intros. unfold max_over_regs_of_funct. \n  apply Zle_trans with (max_over_regs_of_instr valu i).\n  unfold max_over_regs_of_instr. apply max_over_list_bound. auto.\n  apply max_over_instrs_bound. auto.\nQed.\n\nLemma max_over_slots_of_funct_bound:\n  forall (valu: slot -> Z) i s,\n  In i f.(fn_code) -> In s (slots_of_instr i) ->\n  valu s <= max_over_slots_of_funct valu.\nProof.\n  intros. unfold max_over_slots_of_funct. \n  apply Zle_trans with (max_over_slots_of_instr valu i).\n  unfold max_over_slots_of_instr. apply max_over_list_bound. auto.\n  apply max_over_instrs_bound. auto.\nQed.\n\nLemma int_callee_save_bound:\n  forall i r,\n  In i f.(fn_code) -> In r (regs_of_instr i) ->\n  index_int_callee_save r < bound_int_callee_save function_bounds.\nProof.\n  intros. apply Zlt_le_trans with (int_callee_save r).\n  unfold int_callee_save. omega.\n  unfold function_bounds, bound_int_callee_save. \n  eapply max_over_regs_of_funct_bound; eauto.\nQed.\n\nLemma float_callee_save_bound:\n  forall i r,\n  In i f.(fn_code) -> In r (regs_of_instr i) ->\n  index_float_callee_save r < bound_float_callee_save function_bounds.\nProof.\n  intros. apply Zlt_le_trans with (float_callee_save r).\n  unfold float_callee_save. omega.\n  unfold function_bounds, bound_float_callee_save. \n  eapply max_over_regs_of_funct_bound; eauto.\nQed.\n\nLemma int_local_slot_bound:\n  forall i ofs,\n  In i f.(fn_code) -> In (Local ofs Tint) (slots_of_instr i) ->\n  ofs < bound_int_local function_bounds.\nProof.\n  intros. apply Zlt_le_trans with (int_local (Local ofs Tint)).\n  unfold int_local. omega.\n  unfold function_bounds, bound_int_local.\n  eapply max_over_slots_of_funct_bound; eauto.\nQed.\n\nLemma float_local_slot_bound:\n  forall i ofs,\n  In i f.(fn_code) -> In (Local ofs Tfloat) (slots_of_instr i) ->\n  ofs < bound_float_local function_bounds.\nProof.\n  intros. apply Zlt_le_trans with (float_local (Local ofs Tfloat)).\n  unfold float_local. omega.\n  unfold function_bounds, bound_float_local.\n  eapply max_over_slots_of_funct_bound; eauto.\nQed.\n\nLemma outgoing_slot_bound:\n  forall i ofs ty,\n  In i f.(fn_code) -> In (Outgoing ofs ty) (slots_of_instr i) ->\n  ofs + typesize ty <= bound_outgoing function_bounds.\nProof.\n  intros. change (ofs + typesize ty) with (outgoing_slot (Outgoing ofs ty)).\n  unfold function_bounds, bound_outgoing.\n  apply Zmax_bound_r. eapply max_over_slots_of_funct_bound; eauto.\nQed.\n\nLemma size_arguments_bound:\n  forall sig ros,\n  In (Lcall sig ros) f.(fn_code) ->\n  size_arguments sig <= bound_outgoing function_bounds.\nProof.\n  intros. change (size_arguments sig) with (outgoing_space (Lcall sig ros)).\n  unfold function_bounds, bound_outgoing.\n  apply Zmax_bound_l. apply max_over_instrs_bound; auto.\nQed.\n\n(** Consequently, all machine registers or stack slots mentioned by one\n  of the instructions of function [f] are within bounds. *)\n\nLemma mreg_is_within_bounds:\n  forall i, In i f.(fn_code) ->\n  forall r, In r (regs_of_instr i) ->\n  mreg_within_bounds function_bounds r.\nProof.\n  intros. unfold mreg_within_bounds. \n  case (mreg_type r).\n  eapply int_callee_save_bound; eauto.\n  eapply float_callee_save_bound; eauto.\nQed.\n\nLemma slot_is_within_bounds:\n  forall i, In i f.(fn_code) -> \n  forall s, In s (slots_of_instr i) -> Lineartyping.slot_valid f s ->\n  slot_within_bounds f function_bounds s.\nProof.\n  intros. unfold slot_within_bounds. \n  destruct s.\n  destruct t.\n  split. exact H1. eapply int_local_slot_bound; eauto.\n  split. exact H1. eapply float_local_slot_bound; eauto.\n  exact H1.\n  split. simpl in H1. exact H1. eapply outgoing_slot_bound; eauto.\nQed.\n\nLemma slots_of_locs_charact:\n  forall s l, In s (slots_of_locs l) <-> In (S s) l.\nProof.\n  induction l; simpl; intros. \n  tauto.\n  destruct a; simpl; intuition congruence.\nQed.\n\n(** It follows that every instruction in the function is within bounds, \n    in the sense of the [instr_within_bounds] predicate. *)\n\nLemma instr_is_within_bounds:\n  forall i,\n  In i f.(fn_code) ->\n  Lineartyping.wt_instr f i ->\n  instr_within_bounds f function_bounds i.\nProof.\n  intros; \n  destruct i;\n  generalize (mreg_is_within_bounds _ H); generalize (slot_is_within_bounds _ H); \n  simpl; intros; auto.\n(* getstack *)\n  inv H0. split; auto.\n(* setstack *)\n  inv H0; auto.\n(* call *)\n  eapply size_arguments_bound; eauto.\n(* annot *)\n  inv H0. apply H1. rewrite slots_of_locs_charact; auto. \n  generalize (H8 _ H3). unfold loc_acceptable, slot_valid. \n  destruct s; (contradiction || omega).\nQed.\n\nLemma function_is_within_bounds:\n  Lineartyping.wt_code f f.(fn_code) ->\n  function_within_bounds f function_bounds.\nProof.\n  intros; red; intros. apply instr_is_within_bounds; auto.\nQed.\n\nEnd BOUNDS.\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/Bounds.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.28136268373641865}}
{"text": "Require Export SystemFR.ReducibilityDefinition.\nRequire Export SystemFR.TypeErasure.\n\nNotation \"'[[' Θ ';' Γ '⊨' t ':' T ']]'\" := ([ Θ; erase_context Γ ⊨ erase_term t : erase_type T ])\n  (at level 60, Θ at level 60, Γ at level 60, t at level 60).\n\nNotation \"'[[' Θ ';' Γ '⊨' T1 '<:' T2 ']]'\" :=\n  ([ Θ; erase_context Γ ⊨ erase_type T1 <: erase_type T2 ])\n  (at level 60, Θ at level 60, Γ at level 60, T1 at level 60).\n\nNotation \"'[[' Θ ';' Γ '⊨' t1 '≡' t2 ']]'\" :=\n  ([ Θ; erase_context Γ ⊨ erase_term t1 ≡ erase_term t2 ])\n  (at level 60, Θ at level 60, Γ at level 60, t1 at level 60).\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/Judgments.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883592602049, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2813626770313686}}
{"text": "Set Implicit Arguments.\n\nRequire Import Platform.Cito.ADT.\n\nModule Make (Import E : ADT).\n\n  Require Import Platform.Cito.Semantics.\n  Module Import SemanticsMake := Semantics.Make E.\n\n  Section TopSection.\n\n    Local Infix \";;\" := Syntax.Seq (right associativity, at level 95).\n\n    Lemma RunsTo_Seq_Label :\n      forall lbls fs x lbl k vs h v' w,\n        lbls lbl = Some w ->\n        RunsTo (lbls, fs) k (Locals.upd vs x w, h) v' ->\n        RunsTo (lbls, fs) (Syntax.Label x lbl ;; k) (vs, h) v'.\n      intros.\n      econstructor.\n      econstructor; eauto.\n      eauto.\n    Qed.\n\n    Lemma RunsTo_Seq_Assign :\n      forall env x e k vs h v',\n        RunsTo env k (Locals.upd vs x (SemanticsExpr.eval vs e), h) v' ->\n        RunsTo env (Syntax.Assign x e ;; k) (vs, h) v'.\n      intros.\n      econstructor.\n      econstructor; eauto.\n      eauto.\n    Qed.\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/SemanticsFacts3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2813626770313686}}
{"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.\nRequire Import FcEtt.toplevel.\n\nSet Bullet Behavior \"Strict Subproofs\".\nSet Implicit Arguments.\n\n\n(* --------------------------------------------------------------------------- *)\n(* --------------------------------------------------------------------------- *)\n(* --------------------------------------------------------------------------- *)\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\n\n(*\nDefinition tm_context_fv_statement G a A (H: Typing G a A) :=\n\nDefinition PropWff_context_fv_statement G phi (H : PropWff G phi) :=\n  fv_tm_tm_constraint phi [<=] dom G.\nDefinition  Iso_context_fv_statement G D p1 p2 (H : Iso G D p1 p2) :=\n  fv_tm_tm_constraint p1 [<=] dom G /\\\n  fv_tm_tm_constraint p2 [<=] dom G.\nDefinition DefEq_context_fv_statement G D A B T (H : DefEq G D A B T) :=\n  fv_tm_tm_tm A [<=] dom G /\\ fv_tm_tm_tm B [<=] dom G.\nDefinition Ctx_context_fv_statement G (H : Ctx G) :=\n  forall x A, binds x (Tm A) G -> fv_tm_tm_tm A [<=] dom G.\n*)\n\n\n(* FIXME: ? *)\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\n\n(*\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 [<=] dom G /\\\n      fv_tm_tm_tm A [<=] dom G /\\ fv_co_co_tm A [<=] dom G)\n  /\\\n  (forall G phi (H : PropWff G phi),\n      fv_tm_tm_constraint phi [<=] dom G /\\ fv_co_co_constraint phi [<=] dom G)\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 [<=] dom G /\\\n      fv_tm_tm_constraint p2 [<=] dom G /\\ fv_co_co_constraint p2 [<=] dom G)\n  /\\\n  (forall G D A B T (H : DefEq G D A B T),\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      fv_tm_tm_tm T [<=] dom G /\\ fv_co_co_tm T [<=] dom G))\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   [<=] 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 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 [inversion BI].\n  all: try (match goal with |- _ ∧ _ => split end).\n\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 [ apply notin_empty_1 in IN; contradiction].\n  all: try solve [ assert (x = y) by auto; 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; 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  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 (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      [ 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      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.\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\n\n\n(*\nLemma context_fv_mutual2 :\n  (forall G0 (b : tm) B H, @tm_context_fv_statement G0 b B H\n                                               fv_tm_tm_tm a [<=] dom G /\\ fv_tm_tm_tm A [<=] dom G.\n  ) /\\\n    (forall G0 phi H, @PropWff_context_fv_statement G0 phi H) /\\\n    (forall G0 D p1 p2 H,   @Iso_context_fv_statement G0 D p1 p2 H) /\\\n    (forall G0 D A B T H,   @DefEq_context_fv_statement G0 D A B T H) /\\\n    (forall G H, @Ctx_context_fv_statement G H).\nProof.\n  repeat split; intros.\n  all: try eapply (first context_fv_mutual _ _ _ H); eauto.\n  all: try eapply (second context_fv_mutual _ _ H); eauto.\n  all: try eapply (third context_fv_mutual _ _ _ _ H); eauto.\n  - eapply (first (fourth context_fv_mutual _ _ _ _ _ H)); eauto.\n  - eapply (third (fourth context_fv_mutual _ _ _ _ _ H)); eauto.\n  - unfold Ctx_context_fv_statement.\n    intros x A H0.\n    eapply ((fifth context_fv_mutual _ H)); eauto.\nQed.\n\nDefinition typing_context_fv := @first _ _ _ _ _ context_fv_mutual2.\nDefinition ProfWff_context_fv := @second _ _ _ _ _ context_fv_mutual2.\nDefinition iso_context_fv := @third _ _ _ _ _ context_fv_mutual2.\nDefinition defeq_context_fv := @fourth _ _ _ _ _ context_fv_mutual2.\n\nDefinition tm_context_fv_co_statement G a A (H: Typing G a A) :=\n  fv_co_co_tm a [<=] dom G /\\ fv_co_co_tm A [<=] dom G.\nDefinition PropWff_context_fv_co_statement G phi (H : PropWff G phi) :=\n  fv_co_co_constraint phi [<=] dom G.\nDefinition  Iso_context_fv_co_statement G D p1 p2 (H : Iso G D p1 p2) :=\n  fv_co_co_constraint p1 [<=] dom G /\\\n  fv_co_co_constraint p2 [<=] dom G.\nDefinition DefEq_context_fv_co_statement G D A B T (H : DefEq G D A B T) :=\n  fv_co_co_tm A [<=] dom G /\\ fv_co_co_tm B [<=] dom G.\nDefinition Ctx_context_fv_co_statement G (H : Ctx G) := True.\n\n\nLemma context_fv_co_mutual :\n    (forall G0 (b : tm) B H, @tm_context_fv_co_statement G0 b B H) /\\\n    (forall G0 phi H, @PropWff_context_fv_co_statement G0 phi H) /\\\n    (forall G0 D p1 p2 H,   @Iso_context_fv_co_statement G0 D p1 p2 H) /\\\n    (forall G0 D A B T H,   @DefEq_context_fv_co_statement G0 D A B T H) /\\\n    (forall G H, @Ctx_context_fv_co_statement G H).\nProof.\n  repeat split; intros.\n  all: try eapply (first context_fv_mutual _ _ _ H); eauto.\n  all: try eapply (second context_fv_mutual _ _ H); eauto.\n  all: try eapply (third context_fv_mutual _ _ _ _ H); eauto.\n  - eapply (second (fourth context_fv_mutual _ _ _ _ _ H)); eauto.\n  - eapply (fourth (fourth context_fv_mutual _ _ _ _ _ H)); eauto.\nQed.\n\nDefinition typing_context_fv_co := @first _ _ _ _ _ context_fv_co_mutual.\nDefinition ProfWff_context_fv_co := @second _ _ _ _ _ context_fv_co_mutual.\nDefinition iso_context_fv_co := @third _ _ _ _ _ context_fv_co_mutual.\nDefinition defeq_context_fv_co := @fourth _ _ _ _ _ context_fv_co_mutual.\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/corespec/src/FcEtt/ext_context_fv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2813626770313686}}
{"text": "From Coq Require Import ZArith.ZArith MSets.MSetPositive FSets.FMapPositive\n     Strings.String Strings.Ascii Bool.Bool Lists.List Strings.HexString.\nFrom Crypto.Util Require Import\n     ListUtil\n     Strings.String Strings.Decimal Strings.Show\n     ZRange.Operations ZRange.Show\n     Option OptionList Bool.Equality.\n(* Work around COQBUG(https://github.com/coq/coq/issues/12251) *)\nRequire Import Crypto.Util.ZRange.\n\nFrom Crypto Require Import IR Stringification.Language AbstractInterpretation.ZRange.\n\nImport ListNotations.\n\nLocal Open Scope string_scope.\nLocal Open Scope list_scope.\nLocal Open Scope zrange_scope.\nLocal Open Scope Z_scope.\n\nImport IR.Compilers.ToString.\nImport Stringification.Language.Compilers.\nImport Stringification.Language.Compilers.Options.\nImport Stringification.Language.Compilers.ToString.\nImport Stringification.Language.Compilers.ToString.int.Notations.\n\nModule JSON.\n  Definition indent (indent : string) : list string -> list string\n    := List.map (fun s => indent ++ s)%string.\n\n  Definition int_type_to_string (t : ToString.int.type) : string :=\n    ((if ToString.int.is_unsigned t then \"u\" else \"i\")\n       ++ Decimal.Z.to_string (ToString.int.bitwidth_of t))%string.\n\n  Definition primitive_type_to_string (t : IR.type.primitive)\n             (r : option ToString.int.type) : string :=\n    match t with\n    | IR.type.Zptr => \"*\"\n    | IR.type.Z => \"\"\n    end ++ match r with\n           | Some int_t => int_type_to_string int_t\n           | None => \"(auto)\"\n           end.\n\n  Definition int_literal_to_string (t : IR.type.primitive) (v : BinInt.Z) : string :=\n    match t with\n    | IR.type.Z => HexString.of_Z v\n    | IR.type.Zptr => \"#error \"\"literal address \" ++ HexString.of_Z v ++ \"\"\";\"\n    end.\n\n  Import IR.Notations.\n\n  Record op_data :=\n    { datatype : string ; name : list string ; operation : string ; arguments : list (list string) }.\n\n  Definition comma_concat (ls : list (list string)) : list string\n    := let ret := List.flat_map (fun s => match s with\n                                          | [] => []\n                                          | _ => s ++ [\",\"]\n                                          end) ls in\n       (* drop the final , *)\n       List.firstn (List.length ret - 1) ret.\n\n  Definition op_data_to_JSON (v : op_data) : list string\n    := ([\"{\"\n         ; \" \"\"datatype\"\": \"\"\" ++ v.(datatype) ++ \"\"\",\"\n         ; \" \"\"name\"\": [\" ++ String.concat \", \" (List.map (fun n => \"\"\"\" ++ n ++ \"\"\"\")%string v.(name)) ++ \"],\"\n         ; \" \"\"operation\"\": \"\"\" ++ v.(operation) ++ \"\"\",\"\n         ; \" \"\"arguments\"\": [\"]%string)\n         ++ (indent \"  \" (comma_concat v.(arguments)))\n         ++ [\" ]\"\n             ; \"}\"].\n\n  Fixpoint arith_to_string (outargs : list string)\n           {t} (sz : option ToString.int.type)\n           (e : IR.arith_expr t)\n    : list (list string)\n    := let handle_op sz op outargs inargs\n           := [op_data_to_JSON\n                 {| datatype := match sz with None => \"(auto)\" | Some ty => int_type_to_string ty end\n                    ; name := outargs\n                    ; operation := op\n                    ; arguments := inargs |}] in\n       let handle_op1 op {t} inargs\n           := handle_op sz op outargs (@arith_to_string [] t sz inargs) in\n       let wrap_value res\n           := match outargs with\n              | [] => res\n              | _ => handle_op sz \"=\" outargs res\n              end in\n       match e with\n       (* integer literals *)\n       | (IR.literal v @@@ _)\n         => wrap_value [ [\"\"\"\" ++ int_literal_to_string IR.type.Z v ++ \"\"\"\"] ]\n       (* array dereference *)\n       | (IR.List_nth n @@@ IR.Var _ v)\n         => wrap_value [ [\"\"\"\" ++ v ++ \"[\" ++ Decimal.Z.to_string (Z.of_nat n) ++ \"]\"\"\"] ]\n       (* (de)referencing *)\n       | (IR.Addr @@@ IR.Var _ v)\n         => wrap_value [ [\"\"\"&\" ++ v ++ \"\"\"\"] ]\n       | (IR.Dereference @@@ IR.Var _ v)\n         => wrap_value [ [\"\"\"*\" ++ v ++ \"\"\"\"] ]\n       | (IR.Dereference @@@ e)\n         => handle_op sz \"dereference\" [] (arith_to_string [] sz e)\n       (* bitwise operations *)\n       | (IR.Z_shiftr offset @@@ e)\n         => handle_op sz \">>\" outargs\n                      ((arith_to_string [] sz e)\n                         ++ [ [\"\"\"\" ++ Decimal.Z.to_string offset ++ \"\"\"\"]%string ])%list\n       | (IR.Z_shiftl offset @@@ e)\n         => handle_op sz \"<<\" outargs\n                      ((arith_to_string [] sz e)\n                         ++ [ [\"\"\"\" ++ Decimal.Z.to_string offset ++ \"\"\"\"]%string ])%list\n       | (IR.Z_land @@@ args)\n         => handle_op1 \"&\" args\n       | (IR.Z_lor @@@ args)\n         => handle_op1 \"|\" args\n       | (IR.Z_lxor @@@ args)\n         => handle_op1 \"^\" args\n       | (IR.Z_lnot _ @@@ args)\n         => handle_op1 \"~\" args\n       (* arithmetic operations *)\n       | (IR.Z_add @@@ args)\n         => handle_op1 \"+\" args\n       | (IR.Z_mul @@@ args)\n         => handle_op1 \"*\" args\n       | (IR.Z_sub @@@ args)\n         => handle_op1 \"-\" args\n       | (IR.Z_bneg @@@ args)\n         => handle_op1 \"!\" args\n       | (IR.Z_mul_split lg2s @@@ ((IR.Addr @@@ IR.Var _ x1, IR.Addr @@@ IR.Var _ x2), args))\n         => let sz := Some (int.of_bitwidth false lg2s) in\n            wrap_value (handle_op sz \"mulx\" [x1; x2] (arith_to_string [] sz args))\n       | (IR.Z_add_with_get_carry lg2s @@@ ((IR.Addr @@@ IR.Var _ x1, IR.Addr @@@ IR.Var _ x2), args))\n         => let sz := Some (int.of_bitwidth false lg2s) in\n            wrap_value (handle_op sz \"addcarryx\" [x1; x2] (arith_to_string [] sz args))\n       | (IR.Z_sub_with_get_borrow lg2s @@@ ((IR.Addr @@@ IR.Var _ x1, IR.Addr @@@ IR.Var _ x2), args))\n         => let sz := Some (int.of_bitwidth false lg2s) in\n            wrap_value (handle_op sz \"subborrowx\" [x1; x2] (arith_to_string [] sz args))\n       | (IR.Z_value_barrier ty @@@ args) => arith_to_string outargs sz args\n       | (IR.Z_zselect ty @@@ (IR.Addr @@@ IR.Var _ v, args))\n         => wrap_value (handle_op (Some ty) \"cmovznz\" [v] (arith_to_string [] (Some ty) args))\n       | (IR.Z_static_cast int_t @@@ args)\n         => handle_op (Some int_t) \"static_cast\" outargs (arith_to_string [] (Some int_t) args)\n       | IR.Var _ v\n         => wrap_value [ [ \"\"\"\" ++ v ++ \"\"\"\" ] ]\n       | IR.Pair A B a b\n         => wrap_value (arith_to_string [] sz a ++ arith_to_string [] sz b)%list\n       | (IR.Z_add_modulo @@@ _)\n         => wrap_value [ [ \"#error addmodulo\" ] ]\n       | (IR.List_nth _ @@@ _)\n       | (IR.Addr @@@ _)\n       | (IR.Z_mul_split _ @@@ _)\n       | (IR.Z_add_with_get_carry _ @@@ _)\n       | (IR.Z_sub_with_get_borrow _ @@@ _)\n       | (IR.Z_zselect _ @@@ _)\n         => wrap_value [ [ \"#error bad_arg\" ] ]\n       | IR.TT => wrap_value [ [ \"#error tt\" ] ]\n       end%string%Cexpr.\n\n  Definition stmt_to_string (e : IR.stmt) : list string\n    := List.concat\n         match e with\n         | IR.Call val\n           => arith_to_string [] None val\n         | IR.Assign _ _ sz name val\n           => arith_to_string [name] sz val\n         | IR.AssignZPtr name sz val\n           => arith_to_string [name] sz val\n         | IR.AssignNth name n val\n           => let name := (name ++ \"[\" ++ Decimal.Z.to_string (Z.of_nat n) ++ \"]\")%string in\n              arith_to_string [name] None val\n         | IR.DeclareVar _ _ _\n         | IR.Comment _ _\n           => []\n         end.\n\n  Definition to_strings (e : IR.expr) : list string :=\n    comma_concat (List.map stmt_to_string e).\n\n\n  Import Rewriter.Language.Language.Compilers Crypto.Language.API.Compilers IR.OfPHOAS.\n\n  Local Notation tZ := (base.type.type_base base.type.Z).\n  Local Notation None_object := \"null\" (only parsing).\n  Local Notation quote_string s := (\"\"\"\" ++ s ++ \"\"\"\")%string (only parsing).\n\n  Fixpoint to_base_arg_list {t} : base_var_data t -> Compilers.ZRange.type.base.option.interp t -> list (string * string * (string * string))\n    := let show_Z s := quote_string (Hex.show_Z false s) in\n       let opt_to_json T f (b : option T) :=\n           match b with\n           | None => (None_object, None_object)\n           | Some v => f v\n           end in\n       let zrange_to_json b :=\n           (show_Z b.(lower), show_Z b.(upper)) in\n       let opt_zrange_to_json b :=\n           opt_to_json _ zrange_to_json b in\n       let opt_zrange_list_to_json ls :=\n           let ls := List.map opt_zrange_to_json ls in\n           (\"[\" ++ String.concat \", \" (List.map (@fst _ _) ls) ++ \"]\",\n            \"[\" ++ String.concat \", \" (List.map (@snd _ _) ls) ++ \"]\")%string in\n       let opt_opt_zrange_list_to_json ls :=\n           opt_to_json _ opt_zrange_list_to_json ls in\n       match t return base_var_data t -> Compilers.ZRange.type.base.option.interp t -> _ with\n       | tZ\n         => fun '(n, is_ptr, r) b\n            => [(primitive_type_to_string IR.type.Z r, n, opt_zrange_to_json b)]\n       | base.type.prod A B\n         => fun '(va, vb) '(ba, bb) => (@to_base_arg_list A va ba ++ @to_base_arg_list B vb bb)%list\n       | base.type.list tZ\n         => fun '(n, r, len) b\n            => [(primitive_type_to_string IR.type.Z r ++ \"[\" ++ Decimal.Z.to_string (Z.of_nat len) ++ \"]\", n,\n                 opt_opt_zrange_list_to_json b)]\n       | base.type.list _ => fun _ _ => [(\"#error \"\"complex list\"\"\", \"\", (None_object, None_object))]\n       | base.type.option _ => fun _ _ => [(\"#error option\", \"\", (None_object, None_object))]\n       | base.type.unit => fun _ _ => [(\"#error unit\", \"\", (None_object, None_object))]\n       | base.type.type_base t => fun _ _ => [(\"#error \" ++ show false t, \"\", (None_object, None_object))]\n       end%string.\n\n  Definition to_arg_list {t} : var_data t -> Compilers.ZRange.type.option.interp t -> list (string * string * (string * string)) :=\n    match t return var_data t -> Compilers.ZRange.type.option.interp t -> _ with\n    | type.base t => to_base_arg_list\n    | type.arrow _ _ => fun _ _ => [(\"#error arrow\", \"\", (None_object, None_object))]\n    end%string.\n\n  Fixpoint to_arg_list_for_each_lhs_of_arrow {t} : type.for_each_lhs_of_arrow var_data t -> type.for_each_lhs_of_arrow Compilers.ZRange.type.option.interp t -> list (string * string * (string * string))\n    := match t return type.for_each_lhs_of_arrow _ t -> type.for_each_lhs_of_arrow _ t -> _ with\n       | type.base t => fun _ _ => nil\n       | type.arrow s d\n         => fun '(x, xs) '(b, bs)\n            => to_arg_list x b ++ @to_arg_list_for_each_lhs_of_arrow d xs bs\n       end%list.\n\n  (** * Language-specific numeric conversions to be passed to the PHOAS -> IR translation *)\n\n  Definition JSON_bin_op_natural_output\n    : IR.Z_binop -> ToString.int.type * ToString.int.type -> ToString.int.type\n    := fun idc '(t1, t2)\n       => ToString.int.union t1 t2.\n\n  (* Does the binary operation commute with (-- mod 2^bw)? *)\n  Definition bin_op_commutes_with_mod_pow2 (idc : IR.Z_binop)\n    := match idc with\n       | IR.Z_land\n       | IR.Z_lor\n       | IR.Z_lxor\n       | IR.Z_add\n       | IR.Z_mul\n       | IR.Z_sub\n         => true\n       end.\n\n  Definition JSON_bin_op_casts\n    : IR.Z_binop -> option ToString.int.type -> ToString.int.type * ToString.int.type -> option ToString.int.type * (option ToString.int.type * option ToString.int.type)\n    := fun idc desired_type '(t1, t2)\n       => match desired_type with\n          | Some desired_type\n            => let ct := ToString.int.union t1 t2 in\n               if bin_op_commutes_with_mod_pow2 idc\n               then\n                 (* these operations commute with mod, so we just pre-cast them *)\n                 (None, (Some desired_type, Some desired_type))\n               else\n                 let desired_type' := Some (ToString.int.union ct desired_type) in\n                 (desired_type',\n                  (get_Zcast_up_if_needed desired_type' (Some t1),\n                   get_Zcast_up_if_needed desired_type' (Some t2)))\n          | None => (None, (None, None))\n          end.\n\n  Definition JSON_un_op_casts\n    : IR.Z_unop -> option ToString.int.type -> ToString.int.type -> option ToString.int.type * option ToString.int.type\n    := fun idc desired_type t\n       => match idc with\n          | IR.Z_shiftr offset\n            => (** N.B. We must cast the expression up to a large\n                   enough type to fit 2^offset (importantly, not just\n                   2^offset-1), because C considers it to be undefined\n                   behavior to shift >= width of the type.  We should\n                   probably figure out how to not generate these\n                   things in the first place...\n\n                   N.B. We must preserve signedness of the value being\n                   shifted, because shift does not commute with\n                   mod. *)\n            let t' := ToString.int.union_zrange r[0~>2^offset]%zrange t in\n            ((** We cast the result down to the specified type, if needed *)\n              get_Zcast_down_if_needed desired_type (Some t'),\n              (** We cast the argument up to a large enough type *)\n              get_Zcast_up_if_needed (Some t') (Some t))\n          | IR.Z_shiftl offset\n            => (** N.B. We must cast the expression up to a large\n                   enough type to fit 2^offset (importantly, not just\n                   2^offset-1), because C considers it to be undefined\n                   behavior to shift >= width of the type.  We should\n                   probably figure out how to not generate these\n                   things in the first place...\n\n                   N.B. We make sure that we only left-shift unsigned\n                   values, since shifting into the sign bit is\n                   undefined behavior. *)\n            let rpre_out := match desired_type with\n                            | Some rout => Some (ToString.int.union_zrange r[0~>2^offset] (ToString.int.unsigned_counterpart_of rout))\n                            | None => Some (ToString.int.of_zrange_relaxed r[0~>2^offset]%zrange)\n                            end in\n            ((** We cast the result down to the specified type, if needed *)\n              get_Zcast_down_if_needed desired_type rpre_out,\n              (** We cast the argument up to a large enough type *)\n              get_Zcast_up_if_needed rpre_out (Some t))\n          | IR.Z_lnot ty\n            => ((* if the result is too big, we cast it down; we\n                       don't need to upcast it because it'll get\n                       picked up by implicit casts if necessary *)\n              get_Zcast_down_if_needed desired_type (Some ty),\n              (** always cast to the width of the type, unless we are already exactly that type (which the machinery in IR handles *)\n              Some ty)\n          | IR.Z_value_barrier ty\n            => ((* if the result is too big, we cast it down; we\n                       don't need to upcast it because it'll get\n                       picked up by implicit casts if necessary *)\n              get_Zcast_down_if_needed desired_type (Some ty),\n              (** always cast to the width of the type, unless we are already exactly that type (which the machinery in IR handles *)\n              Some ty)\n          | IR.Z_bneg\n            => ((* bneg is !, i.e., takes the argument to 1 if its not zero, and to zero if it is zero; so we don't ever need to cast *)\n              None, None)\n          end.\n\n  Local Instance JSONLanguageCasts : LanguageCasts :=\n    {| bin_op_natural_output := JSON_bin_op_natural_output\n       ; bin_op_casts := JSON_bin_op_casts\n       ; un_op_casts := JSON_un_op_casts\n       ; upcast_on_assignment := true\n       ; upcast_on_funcall := true\n       ; explicit_pointer_variables := false\n    |}.\n\n  Definition to_function_lines (static : bool) (name : string)\n             {t}\n             (inbounds : type.for_each_lhs_of_arrow Compilers.ZRange.type.option.interp t)\n             (outbounds : Compilers.ZRange.type.base.option.interp (type.final_codomain t))\n             (f : type.for_each_lhs_of_arrow var_data t * var_data (type.base (type.final_codomain t)) * IR.expr)\n    : list string :=\n    let '(args, rets, body) := f in\n    let args_list_to_string ls\n        := (\"[\"\n              ++ (String.concat\n                    \", \"\n                    (List.map\n                       (fun '(typ, name, (lbound, ubound)) => \"{\"\"datatype\"\": \"\"\" ++ typ ++ \"\"\", \"\"name\"\": \"\"\" ++ name ++ \"\"\", \"\"lbound\"\": \" ++ lbound ++ \", \"\"ubound\"\": \" ++ ubound ++ \"}\")\n                       ls))\n              ++ \"]\")%string in\n    [\"{\"]\n      ++ ([\"\"\"operation\"\": \"\"\" ++ name ++ \"\"\",\"\n           ; \"\"\"arguments\"\": \" ++ args_list_to_string (to_arg_list_for_each_lhs_of_arrow args inbounds) ++ \",\"\n           ; \"\"\"returns\"\": \" ++ args_list_to_string (to_arg_list rets outbounds) ++ \",\"\n           ; \"\"\"body\"\": [\"]%string)\n      ++ to_strings body\n      ++ [\"]\"\n          ; \"}\"].\n\n  (** We will treat all dead variables as _ *)\n  Local Instance : consider_retargs_live_opt := fun _ _ _ => false.\n  Local Instance : rename_dead_opt := fun s => \"_\".\n  (** No need to lift declarations to the top *)\n  Local Instance : lift_declarations_opt := false.\n\n  Definition ToFunctionLines\n             {relax_zrange : relax_zrange_opt}\n             {language_naming_conventions : language_naming_conventions_opt}\n             (machine_wordsize : Z)\n             (do_bounds_check : bool) (internal_static : bool) (static : bool) (prefix : string) (name : string)\n             {t}\n             (e : API.Expr t)\n             (comment : type.for_each_lhs_of_arrow var_data t -> var_data (type.base (type.final_codomain t)) -> list string)\n             (name_list : option (list string))\n             (inbounds : type.for_each_lhs_of_arrow Compilers.ZRange.type.option.interp t)\n             (outbounds : Compilers.ZRange.type.base.option.interp (type.final_codomain t))\n    : (list string * ToString.ident_infos) + string :=\n    match ExprOfPHOAS do_bounds_check e name_list inbounds with\n    | inl (indata, outdata, f) =>\n      inl (to_function_lines\n             static name\n             inbounds\n             outbounds\n             (indata, outdata, f),\n           IR.ident_infos.collect_infos f)\n    | inr nil =>\n      inr (\"Unknown internal error in converting \" ++ name ++ \" to JSON\")%string\n    | inr [err] =>\n      inr (\"Error in converting \" ++ name ++ \" to JSON:\" ++ String.NewLine ++ err)%string\n    | inr errs =>\n      inr (\"Errors in converting \" ++ name ++ \" to JSON:\" ++ String.NewLine ++ String.concat String.NewLine errs)%string\n    end.\n\n  Definition OutputJSONAPI : ToString.OutputLanguageAPI :=\n    {| ToString.comment_block _ := [];\n       ToString.comment_file_header_block _ := [];\n       ToString.ToFunctionLines := @ToFunctionLines;\n       ToString.header := fun _ _ _ _ _ _ _ _ => [];\n       ToString.footer := fun _ _ _ _ _ _ _ _ => [];\n       (** No special handling for any functions *)\n       ToString.strip_special_infos machine_wordsize infos := infos |}.\n\nEnd JSON.\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/Stringification/JSON.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.28135931178618545}}
{"text": "(** Used to trigger an anomaly with VM compilation *)\n\nSet Universe Polymorphism.\n\nInductive t A : nat -> Type :=\n| nil : t A 0\n| cons : forall (h : A) (n : nat), t A n -> t A (S n).\n\nDefinition case0 {A} (P : t A 0 -> Type) (H : P (nil A)) v : P v :=\nmatch v with\n| nil _ => H\n| _ => fun devil => False_ind (@IDProp) devil\nend.\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/6956.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370308082623216, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2813593117861854}}
{"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 Ex.Mesi.MesiInvB.\nRequire Export Ex.Mesi.MesiInvInv0 Ex.Mesi.MesiInvInv1 Ex.Mesi.MesiInvInv2.\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 NoCohMsgs (oidx: IdxT) (msgs: MessagePool Msg) :=\n  MsgsNotExist [(downTo oidx, (MRs, mesiRsS));\n               (downTo oidx, (MRs, mesiRsE));\n               (downTo oidx, (MRs, mesiRsM));\n               (rsUpFrom oidx, (MRs, mesiDownRsS));\n               (rsUpFrom oidx, (MRs, mesiDownRsIM))] msgs.\n\nDefinition ObjInvalid0 (oidx: IdxT) (ost: OState) (msgs: MessagePool Msg) :=\n  ost#[status] <= mesiI /\\\n  ost#[dir].(dir_st) <> mesiS /\\\n  NoCohMsgs oidx msgs.\n\nDefinition ObjInvalid (oidx: IdxT) (ost: OState) (msgs: MessagePool Msg) :=\n  ObjInvalid0 oidx ost msgs \\/ ObjInvRs oidx msgs.\n\nDefinition ObjsInvalid (inP: IdxT -> Prop) (oss: OStates) (msgs: MessagePool Msg) :=\n  forall oidx,\n    inP oidx ->\n    ost <+- oss@[oidx]; ObjInvalid oidx ost msgs.\n\nDefinition InvObjExcl0 (eidx: IdxT) (ost: OState) (oss: OStates)\n           (msgs: MessagePool Msg) :=\n  ObjExcl0 eidx ost msgs ->\n  ObjsInvalid (fun oidx => eidx <> oidx) oss msgs /\\\n  NoCohMsgs eidx msgs.\n\nDefinition ObjOwned (oidx: IdxT) (ost: OState) (msgs: MessagePool Msg) :=\n  ost#[owned] = true /\\ NoRsI oidx msgs.\n\nDefinition InvObjOwned (topo: DTree) (eidx: IdxT) (eost: OState) (oss: OStates)\n           (msgs: MessagePool Msg) :=\n  ObjOwned eidx eost msgs ->\n  ObjsInvalid (fun oidx => ~ In oidx (subtreeIndsOf topo eidx)) oss msgs /\\\n  NoCohMsgs eidx msgs.\n\nDefinition InvDirInv (topo: DTree) (cifc: CIfc) (eidx: IdxT) (eost: OState) (oss: OStates)\n           (msgs: MessagePool Msg) :=\n  In eidx (c_li_indices cifc) ->\n  forall cidx,\n    parentIdxOf topo cidx = Some eidx ->\n    (getDir cidx eost#[dir] = mesiI ->\n     ObjsInvalid (fun oidx => In oidx (subtreeIndsOf topo cidx)) oss msgs) /\\\n    (mesiE <= getDir cidx eost#[dir] ->\n     ObjsInvalid (fun oidx => ~ In oidx (subtreeIndsOf topo cidx)) oss msgs).\n\nDefinition InvExcl (topo: DTree) (cifc: CIfc) (st: State): Prop :=\n  forall eidx,\n    eost <+- (st_oss st)@[eidx];\n      (InvObjExcl0 eidx eost (st_oss st) (st_msgs st) /\\\n       InvObjOwned topo eidx eost (st_oss st) (st_msgs st) /\\\n       InvDirInv topo cifc eidx eost (st_oss st) (st_msgs st)).\n\nSection Facts.\n\n  (** [ObjExcl0] *)\n\n  Lemma ObjExcl0_enqMP_inv:\n    forall oidx ost msgs midx msg,\n      ObjExcl0 oidx ost (enqMP midx msg msgs) ->\n      ObjExcl0 oidx ost msgs.\n  Proof.\n    unfold ObjExcl0; intros.\n    dest; split; [assumption|].\n    disc_MsgsP H0; assumption.\n  Qed.\n\n  Lemma ObjExcl0_enqMsgs_inv:\n    forall oidx ost msgs nmsgs,\n      ObjExcl0 oidx ost (enqMsgs nmsgs msgs) ->\n      ObjExcl0 oidx ost msgs.\n  Proof.\n    unfold ObjExcl0; intros.\n    dest; split; [assumption|].\n    disc_MsgsP H0; assumption.\n  Qed.\n\n  Lemma ObjExcl0_other_midx_deqMP_inv:\n    forall oidx ost msgs midx,\n      ObjExcl0 oidx ost (deqMP midx msgs) ->\n      midx <> downTo oidx ->\n      ObjExcl0 oidx ost msgs.\n  Proof.\n    unfold ObjExcl0; intros.\n    dest; split; [assumption|].\n    disc_MsgsP H1; assumption.\n  Qed.\n\n  Lemma ObjExcl0_other_midx_deqMsgs_inv:\n    forall oidx ost msgs (rmsgs: list (Id Msg)),\n      ObjExcl0 oidx ost (deqMsgs (idsOf rmsgs) msgs) ->\n      NoDup (idsOf rmsgs) ->\n      Forall (FirstMPI msgs) rmsgs ->\n      Forall (fun midx => midx <> downTo oidx) (idsOf rmsgs) ->\n      ObjExcl0 oidx ost msgs.\n  Proof.\n    unfold ObjExcl0; intros.\n    dest; split; [assumption|].\n    apply MsgsP_other_midx_deqMsgs_inv in H3.\n    - assumption.\n    - simpl.\n      simpl; apply (DisjList_spec_1 idx_dec); intros.\n      rewrite Forall_forall in H2; specialize (H2 _ H4).\n      intro Hx; dest_in; auto.\n  Qed.\n\n  Lemma ObjExcl0_other_msg_id_deqMP_inv:\n    forall oidx ost msgs midx,\n      ObjExcl0 oidx ost (deqMP midx msgs) ->\n      forall msg,\n        FirstMP msgs midx msg ->\n        msg.(msg_id) <> mesiInvRs ->\n        ObjExcl0 oidx ost msgs.\n  Proof.\n    unfold ObjExcl0; intros.\n    dest; split; [assumption|].\n    eapply MsgsP_other_msg_id_deqMP_inv in H2;\n      [|eassumption|simpl; intuition].\n    assumption.\n  Qed.\n\n  Lemma ObjExcl0_other_msg_id_deqMsgs_inv:\n    forall oidx ost msgs rmsgs,\n      ObjExcl0 oidx ost (deqMsgs (idsOf rmsgs) msgs) ->\n      NoDup (idsOf rmsgs) ->\n      Forall (FirstMPI msgs) rmsgs ->\n      Forall (fun idm => (valOf idm).(msg_id) <> mesiInvRs) rmsgs ->\n      ObjExcl0 oidx ost msgs.\n  Proof.\n    unfold ObjExcl0; intros.\n    dest; split; [assumption|].\n    eapply MsgsP_other_msg_id_deqMsgs_inv in H3; try assumption.\n    simpl; apply (DisjList_spec_1 idx_dec); intros.\n    apply in_map_iff in H4; dest; subst.\n    rewrite Forall_forall in H2; specialize (H2 _ H5).\n    intro Hx; dest_in; auto.\n  Qed.\n\n  (** [ObjInvalid] and [ObjsInvalid] *)\n\n  Lemma ObjsInvalid_ObjInvalid:\n    forall inP oss msgs,\n      ObjsInvalid inP oss msgs ->\n      forall oidx ost,\n        inP oidx ->\n        oss@[oidx] = Some ost ->\n        ObjInvalid oidx ost msgs.\n  Proof.\n    intros.\n    specialize (H _ H0).\n    rewrite H1 in H; simpl in H; assumption.\n  Qed.\n\n  Lemma ObjInvalid_NoCohMsgs:\n    forall oidx ost orq msgs,\n      RsDownConflicts oidx orq msgs ->\n      ObjInvalid oidx ost msgs ->\n      NoCohMsgs oidx msgs.\n  Proof.\n    intros.\n    destruct H0; [apply H0|].\n    destruct H0 as [[midx msg] [? ?]]; inv H1.\n    red; intros.\n    specialize (H (downTo oidx, msg) eq_refl H4 H0); dest.\n    apply not_MsgExistsSig_MsgsNotExist; intros.\n    dest_in.\n    - destruct H9 as [[rmidx rmsg] [? ?]]; inv H9.\n      eapply H2 with (rrsDown:= (downTo oidx, rmsg)); eauto.\n      simpl; intro; subst.\n      rewrite H5 in H13; discriminate.\n    - destruct H9 as [[rmidx rmsg] [? ?]]; inv H9.\n      eapply H2 with (rrsDown:= (downTo oidx, rmsg)); eauto.\n      simpl; intro; subst.\n      rewrite H5 in H13; discriminate.\n    - destruct H9 as [[rmidx rmsg] [? ?]]; inv H9.\n      eapply H2 with (rrsDown:= (downTo oidx, rmsg)); eauto.\n      simpl; intro; subst.\n      rewrite H5 in H13; discriminate.\n    - destruct H9 as [[rmidx rmsg] [? ?]]; inv H9.\n      eapply H7 with (rsUp:= (rsUpFrom oidx, rmsg)); eauto.\n    - destruct H9 as [[rmidx rmsg] [? ?]]; inv H9.\n      eapply H7 with (rsUp:= (rsUpFrom oidx, rmsg)); eauto.\n  Qed.\n\n  Lemma ObjsInvalid_impl:\n    forall inP1 oss msgs,\n      ObjsInvalid inP1 oss msgs ->\n      forall (inP2: IdxT -> Prop),\n        (forall oidx, inP2 oidx -> inP1 oidx) ->\n        ObjsInvalid inP2 oss msgs.\n  Proof.\n    unfold ObjsInvalid; intros; auto.\n  Qed.\n\n  Lemma ObjsInvalid_obj_status_false:\n    forall inP oss msgs,\n      ObjsInvalid inP oss msgs ->\n      forall oidx,\n        inP oidx ->\n        NoRsI oidx msgs ->\n        forall ost,\n          oss@[oidx] = Some ost ->\n          mesiS <= ost#[status] ->\n          False.\n  Proof.\n    intros.\n    specialize (H _ H0).\n    rewrite H2 in H; simpl in H.\n    destruct H.\n    - red in H; solve_mesi.\n    - eapply NoRsI_MsgExistsSig_InvRs_false; eauto.\n  Qed.\n\n  Lemma ObjsInvalid_obj_dir_false:\n    forall inP oss msgs,\n      ObjsInvalid inP oss msgs ->\n      forall oidx,\n        inP oidx ->\n        NoRsI oidx msgs ->\n        forall ost,\n          oss@[oidx] = Some ost ->\n          ost#[dir].(dir_st) = mesiS ->\n          False.\n  Proof.\n    intros.\n    specialize (H _ H0).\n    rewrite H2 in H; simpl in H.\n    destruct H.\n    - red in H; solve_mesi.\n    - eapply NoRsI_MsgExistsSig_InvRs_false; eauto.\n  Qed.\n\n  Lemma ObjsInvalid_this_state_silent:\n    forall inP oss msgs,\n      ObjsInvalid inP oss msgs ->\n      forall roidx nost,\n        ~ inP roidx ->\n        ObjsInvalid inP (oss +[roidx <- nost]) msgs.\n  Proof.\n    intros.\n    red; intros.\n    specialize (H _ H1).\n    mred.\n  Qed.\n\n  Lemma ObjsInvalid_this_enqMP_silent:\n    forall inP oss msgs,\n      ObjsInvalid inP oss msgs ->\n      forall roidx,\n        ~ inP roidx ->\n        forall midx msg,\n          In midx [rqUpFrom roidx; rsUpFrom roidx; downTo roidx] ->\n          ObjsInvalid inP oss (enqMP midx msg msgs).\n  Proof.\n    intros.\n    red; intros.\n    specialize (H _ H2).\n    destruct (oss@[oidx]) as [ost|]; simpl in H; simpl; auto.\n    destruct H.\n    - left.\n      destruct H as [? [? ?]].\n      repeat split; [assumption..|dest_in; solve_MsgsP].\n    - right.\n      destruct H as [[rmidx rmsg] [? ?]]; inv H3.\n      exists (downTo oidx, rmsg); split.\n      + apply InMP_or_enqMP; right; assumption.\n      + unfold sigOf; simpl; congruence.\n  Qed.\n\n  Lemma ObjsInvalid_this_deqMP_silent:\n    forall inP oss msgs,\n      ObjsInvalid inP oss msgs ->\n      forall roidx,\n        ~ inP roidx ->\n        forall midx,\n          In midx [rqUpFrom roidx; rsUpFrom roidx; downTo roidx] ->\n          ObjsInvalid inP oss (deqMP midx msgs).\n  Proof.\n    intros.\n    red; intros.\n    specialize (H _ H2).\n    destruct (oss@[oidx]) as [ost|]; simpl in H; simpl; auto.\n    destruct H.\n    - left.\n      destruct H as [? [? ?]].\n      repeat split; [assumption..|dest_in; solve_MsgsP].\n    - right.\n      destruct H as [[rmidx msg] [? ?]]; inv H3.\n      exists (downTo oidx, msg); split.\n      + apply deqMP_InMP_midx; [assumption|].\n        simpl; intro Hx; subst.\n        dest_in; try discriminate.\n        inv H3; auto.\n      + unfold sigOf; simpl; congruence.\n  Qed.\n\n  Lemma ObjsInvalid_rsS_false:\n    forall inP oss msgs,\n      ObjsInvalid inP oss msgs ->\n      forall oidx ost orq,\n        oss@[oidx] = Some ost ->\n        inP oidx ->\n        RsDownConflicts oidx orq msgs ->\n        forall rsdm,\n          InMP (downTo oidx) rsdm msgs ->\n          rsdm.(msg_type) = MRs ->\n          rsdm.(msg_id) = mesiRsS ->\n          False.\n  Proof.\n    intros.\n    specialize (H _ H1).\n    rewrite H0 in H; simpl in H.\n    destruct H.\n    - red in H; dest.\n      specialize (H7 (downTo oidx, rsdm) H3).\n      red in H7; rewrite map_trans, map_cons in H7.\n      rewrite caseDec_head_eq in H7\n        by (unfold sigOf; simpl; congruence).\n      auto.\n    - destruct H as [[midx msg] [? ?]]; simpl in *.\n      unfold sigOf in H6; simpl in H6; inv H6.\n      specialize (H2 (downTo oidx, rsdm) eq_refl H4 H3); dest.\n      eapply (H7 (downTo oidx, msg)); eauto.\n      simpl; intro Hx; subst.\n      rewrite H5 in H10; discriminate.\n  Qed.\n\n  Lemma ObjsInvalid_rsE_false:\n    forall inP oss msgs,\n      ObjsInvalid inP oss msgs ->\n      forall oidx ost orq,\n        oss@[oidx] = Some ost ->\n        inP oidx ->\n        RsDownConflicts oidx orq msgs ->\n        forall rsdm,\n          InMP (downTo oidx) rsdm msgs ->\n          rsdm.(msg_type) = MRs ->\n          rsdm.(msg_id) = mesiRsE ->\n          False.\n  Proof.\n    intros.\n    specialize (H _ H1).\n    rewrite H0 in H; simpl in H.\n    destruct H.\n    - red in H; dest.\n      specialize (H7 (downTo oidx, rsdm) H3).\n      red in H7; rewrite map_trans, map_cons in H7.\n      rewrite caseDec_head_neq in H7\n        by (unfold sigOf; simpl; intro Hx; inv Hx;\n            rewrite H5 in H10; discriminate).\n      rewrite map_cons in H7.\n      rewrite caseDec_head_eq in H7\n        by (unfold sigOf; simpl; congruence).\n      auto.\n    - destruct H as [[midx msg] [? ?]]; simpl in *.\n      unfold sigOf in H6; simpl in H6; inv H6.\n      specialize (H2 (downTo oidx, rsdm) eq_refl H4 H3); dest.\n      eapply (H7 (downTo oidx, msg)); eauto.\n      simpl; intro Hx; subst.\n      rewrite H5 in H10; discriminate.\n  Qed.\n\n  Lemma ObjsInvalid_rsM_false:\n    forall inP oss msgs,\n      ObjsInvalid inP oss msgs ->\n      forall oidx ost orq,\n        oss@[oidx] = Some ost ->\n        inP oidx ->\n        RsDownConflicts oidx orq msgs ->\n        forall rsdm,\n          InMP (downTo oidx) rsdm msgs ->\n          rsdm.(msg_type) = MRs ->\n          rsdm.(msg_id) = mesiRsM ->\n          False.\n  Proof.\n    intros.\n    specialize (H _ H1).\n    rewrite H0 in H; simpl in H.\n    destruct H.\n    - red in H; dest.\n      specialize (H7 (downTo oidx, rsdm) H3).\n      red in H7; rewrite map_trans, map_cons in H7.\n      do 2 (rewrite caseDec_head_neq in H7\n             by (unfold sigOf; simpl; intro Hx; inv Hx;\n                 rewrite H5 in H10; discriminate);\n            rewrite map_cons in H7).\n      rewrite caseDec_head_eq in H7\n        by (unfold sigOf; simpl; congruence).\n      auto.\n    - destruct H as [[midx msg] [? ?]]; simpl in *.\n      unfold sigOf in H6; simpl in H6; inv H6.\n      specialize (H2 (downTo oidx, rsdm) eq_refl H4 H3); dest.\n      eapply (H7 (downTo oidx, msg)); eauto.\n      simpl; intro Hx; subst.\n      rewrite H5 in H10; discriminate.\n  Qed.\n\n  Lemma ObjsInvalid_downRsS_false:\n    forall inP oss msgs,\n      ObjsInvalid inP oss msgs ->\n      forall oidx ost orq,\n        oss@[oidx] = Some ost ->\n        inP oidx ->\n        RsDownConflicts oidx orq msgs ->\n        forall rsum,\n          InMP (rsUpFrom oidx) rsum msgs ->\n          rsum.(msg_type) = MRs ->\n          rsum.(msg_id) = mesiDownRsS ->\n          False.\n  Proof.\n    intros.\n    specialize (H _ H1).\n    rewrite H0 in H; simpl in H.\n    destruct H.\n    - red in H; dest.\n      specialize (H7 (rsUpFrom oidx, rsum) H3).\n      red in H7; rewrite map_trans, map_cons in H7.\n      do 3 (rewrite caseDec_head_neq in H7\n             by (unfold sigOf; simpl; intro Hx; inv Hx;\n                 rewrite H5 in H9; discriminate);\n            rewrite map_cons in H7).\n      rewrite caseDec_head_eq in H7\n        by (unfold sigOf; simpl; congruence).\n      auto.\n    - destruct H as [[midx msg] [? ?]]; simpl in *.\n      unfold sigOf in H6; simpl in H6; inv H6.\n      specialize (H2 (downTo oidx, msg) eq_refl H9 H); dest.\n      eapply (H12 (rsUpFrom oidx, rsum)); eauto.\n  Qed.\n\n  Lemma ObjsInvalid_downRsIM_false:\n    forall inP oss msgs,\n      ObjsInvalid inP oss msgs ->\n      forall oidx ost orq,\n        oss@[oidx] = Some ost ->\n        inP oidx ->\n        RsDownConflicts oidx orq msgs ->\n        forall rsum,\n          InMP (rsUpFrom oidx) rsum msgs ->\n          rsum.(msg_type) = MRs ->\n          rsum.(msg_id) = mesiDownRsIM ->\n          False.\n  Proof.\n    intros.\n    specialize (H _ H1).\n    rewrite H0 in H; simpl in H.\n    destruct H.\n    - red in H; dest.\n      specialize (H7 (rsUpFrom oidx, rsum) H3).\n      red in H7; rewrite map_trans, map_cons in H7.\n      do 4 (rewrite caseDec_head_neq in H7\n             by (unfold sigOf; simpl; intro Hx; inv Hx;\n                 rewrite H5 in H10; discriminate);\n            rewrite map_cons in H7).\n      rewrite caseDec_head_eq in H7\n        by (unfold sigOf; simpl; congruence).\n      auto.\n    - destruct H as [[midx msg] [? ?]]; simpl in *.\n      unfold sigOf in H6; simpl in H6; inv H6.\n      specialize (H2 (downTo oidx, msg) eq_refl H9 H); dest.\n      eapply (H12 (rsUpFrom oidx, rsum)); eauto.\n  Qed.\n\n  Lemma NoCohMsgs_enq:\n    forall msgs oidx,\n      NoCohMsgs oidx msgs ->\n      forall midx msg,\n        ~ In msg.(msg_id) [mesiRsS; mesiRsE; mesiRsM; mesiDownRsS; mesiDownRsIM] ->\n        NoCohMsgs oidx (enqMP midx msg msgs).\n  Proof.\n    intros; apply MsgsP_other_msg_id_enqMP; assumption.\n  Qed.\n\n  Lemma NoCohMsgs_rqDown_deq:\n    forall msgs oidx rmsg,\n      FirstMPI msgs (downTo oidx, rmsg) ->\n      rmsg.(msg_type) = MRq ->\n      forall orq,\n        RsDownConflicts oidx orq msgs ->\n        RqDownConflicts oidx msgs ->\n        NoCohMsgs oidx (deqMP (downTo oidx) msgs).\n  Proof.\n    intros.\n    specialize (H2 (downTo oidx, rmsg) eq_refl H0 (FirstMP_InMP H)); dest.\n    apply not_MsgExistsSig_MsgsNotExist.\n    intros; dest_in.\n    1-3: try (destruct H5 as [[rsDown rsdm] [? ?]]; inv H5;\n              apply InMP_deqMP in H4;\n              specialize (H1 (downTo oidx, rsdm) eq_refl H8 H4); dest;\n              eapply H10 with (rqDown:= (downTo oidx, rmsg)); eauto).\n    all: try (destruct H5 as [rsUp [? ?]]; inv H5;\n              apply H3 with (rsUp:= rsUp); auto;\n              eapply InMP_deqMP; eauto).\n  Qed.\n\n  Lemma NoCohMsgs_rsDown_deq:\n    forall msgs oidx rmsg,\n      FirstMPI msgs (downTo oidx, rmsg) ->\n      rmsg.(msg_type) = MRs ->\n      forall orq,\n        RsDownConflicts oidx orq msgs ->\n        NoCohMsgs oidx (deqMP (downTo oidx) msgs).\n  Proof.\n    intros.\n    specialize (H1 (downTo oidx, rmsg) eq_refl H0 (FirstMP_InMP H)); dest.\n    apply not_MsgExistsSig_MsgsNotExist.\n    intros; dest_in.\n    1-3: try (destruct H8 as [[midx msg] [? ?]]; inv H8;\n              apply H4;\n              eapply rssQ_deq_in_length_two; eauto).\n    all: try (destruct H8 as [rsUp [? ?]]; inv H8;\n              apply H6 with (rsUp:= rsUp); auto;\n              eapply InMP_deqMP; eauto).\n  Qed.\n\n  Lemma NoCohMsgs_rsUp_in:\n    forall oidx msgs rmsg,\n      InMP (rsUpFrom oidx) rmsg msgs ->\n      rmsg.(msg_id) <> mesiDownRsS ->\n      rmsg.(msg_id) <> mesiDownRsIM ->\n      forall orq,\n        RsDownConflicts oidx orq msgs ->\n        RsUpConflicts oidx msgs ->\n        NoCohMsgs oidx msgs.\n  Proof.\n    intros.\n    specialize (H3 (rsUpFrom oidx, rmsg) eq_refl H); dest.\n    apply not_MsgExistsSig_MsgsNotExist.\n    intros; dest_in.\n    all: try (destruct H7 as [[midx msg] [? ?]]; inv H7;\n              specialize (H2 (downTo oidx, msg) eq_refl H10 H6); dest;\n              eapply H13 with (rsUp:= (rsUpFrom oidx, rmsg)); eauto; fail).\n    all: (destruct H7 as [[midx msg] [? ?]]; inv H7;\n          eapply H4;\n          eapply findQ_length_two; [|apply H|apply H6];\n          simpl; intro Hx; subst;\n          congruence).\n  Qed.\n\n  Lemma NoCohMsgs_rsUp_deq:\n    forall msgs oidx rmsg,\n      FirstMPI msgs (rsUpFrom oidx, rmsg) ->\n      forall orq,\n        RsDownConflicts oidx orq msgs ->\n        RsUpConflicts oidx msgs ->\n        NoCohMsgs oidx (deqMP (rsUpFrom oidx) msgs).\n  Proof.\n    intros.\n    specialize (H1 (rsUpFrom oidx, rmsg) eq_refl (FirstMP_InMP H)); dest.\n    apply not_MsgExistsSig_MsgsNotExist.\n    intros; dest_in.\n    1-3: try (destruct H5 as [[midx msg] [? ?]]; inv H5;\n              apply InMP_deqMP in H4;\n              specialize (H0 (downTo oidx, msg) eq_refl H8 H4); dest;\n              eapply H11 with (rsUp:= (rsUpFrom oidx, rmsg)); eauto;\n              apply FirstMP_InMP; assumption).\n    all: try (destruct H5 as [[midx msg] [? ?]]; inv H5;\n              eapply H2;\n              eapply findQ_deq_in_length_two; eauto).\n  Qed.\n\n  Lemma NoCohMsgs_deqMsgs_silent:\n    forall rminds msgs oidx,\n      NoCohMsgs oidx msgs ->\n      NoCohMsgs oidx (deqMsgs rminds msgs).\n  Proof.\n    intros; solve_MsgsP.\n  Qed.\n\n  Lemma NoCohMsgs_rsUps_deq:\n    forall rminds msgs oidx,\n      Forall (fun midx => exists rcidx, midx = rsUpFrom rcidx) rminds ->\n      NoDup rminds ->\n      In (rsUpFrom oidx) rminds ->\n      NoCohMsgs oidx (deqMP (rsUpFrom oidx) msgs) ->\n      NoCohMsgs oidx (deqMsgs rminds msgs).\n  Proof.\n    induction rminds; simpl; intros; [exfalso; auto|].\n    inv H; inv H0.\n    destruct H5 as [rcidx ?]; subst.\n    destruct H1.\n    - apply NoCohMsgs_deqMsgs_silent.\n      rewrite H; assumption.\n    - rewrite <-deqMP_deqMsgs_comm by assumption.\n      apply NoCohMsgs_deqMsgs_silent with (rminds:= [rsUpFrom rcidx]).\n      eapply IHrminds; eauto.\n  Qed.\n\n  Lemma ObjsInvalid_invRs:\n    forall inP oss msgs,\n      ObjsInvalid inP oss msgs ->\n      forall oidx orq,\n        inP oidx ->\n        RsDownConflicts oidx orq msgs ->\n        forall post,\n          oss@[oidx] = Some post ->\n          forall nost: OState,\n            nost#[status] = mesiNP ->\n            nost#[dir].(dir_st) = mesiI -> (* by [InvWBDir] *)\n            nost#[owned] = false ->\n            forall rmsg,\n              FirstMPI msgs (downTo oidx, rmsg) ->\n              rmsg.(msg_type) = MRs ->\n              ObjsInvalid inP (oss +[ oidx <- nost]) (deqMP (downTo oidx) msgs).\n  Proof.\n    intros.\n    red; intros roidx ?.\n    mred; simpl in *.\n    - left; repeat split.\n      + simpl; solve_mesi.\n      + simpl; rewrite H4; discriminate.\n      + eapply NoCohMsgs_rsDown_deq; eauto.\n    - specialize (H _ H8).\n      destruct (oss@[roidx]) as [rost|]; simpl in *; auto.\n      destruct H; [left|right].\n      + destruct H as [? [? ?]]; repeat split; [assumption..|].\n        solve_MsgsP.\n      + destruct H as [[midx msg] [? ?]].\n        exists (midx, msg); split; [|assumption]; inv H9.\n        apply deqMP_InMP_midx; [assumption|].\n        simpl; intro Hx; subst.\n        inv Hx; auto.\n  Qed.\n\n  Section OnTree.\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\n    Lemma ObjsInvalid_shrinked:\n      forall eidx,\n        In eidx (c_l1_indices cifc) ->\n        forall oss msgs,\n          ObjsInvalid (fun oidx => ~ In oidx (subtreeIndsOf topo eidx)) oss msgs ->\n          (forall oidx, _ <+- oss@[oidx]; In oidx (c_li_indices cifc ++ c_l1_indices cifc)) ->\n          ObjsInvalid (fun oidx => eidx <> oidx) oss msgs.\n    Proof.\n      intros.\n      red; intros.\n      destruct (oss@[oidx]) as [ost|] eqn:Host; simpl; [|auto].\n      specialize (H1 oidx); rewrite Host in H1; simpl in H1.\n      specialize (H0 oidx); simpl in H0.\n      rewrite Host in H0; simpl in H0.\n      apply H0.\n      subst topo; rewrite tree2Topo_l1_subtreeIndsOf; [|eassumption].\n      intro Hx; dest_in; [auto|].\n      eapply tree2Topo_l1_child_ext_not_in; eauto.\n    Qed.\n\n    Lemma ObjsInvalid_child_forall:\n      forall oidx oss msgs,\n        (forall cidx,\n            parentIdxOf topo cidx = Some oidx ->\n            ObjsInvalid (fun idx => In idx (subtreeIndsOf topo cidx)) oss msgs) ->\n        ObjsInvalid\n          (fun idx =>\n             exists cidx,\n               parentIdxOf topo cidx = Some oidx /\\\n               In idx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx))\n          oss msgs.\n    Proof.\n      intros.\n      red; intros.\n      destruct H0 as [cidx [? ?]].\n      specialize (H _ H0 _ H1).\n      assumption.\n    Qed.\n\n    Lemma ObjsInvalid_l1_singleton:\n      forall oss orqs msgs,\n        InObjInds tr 0 {| st_oss := oss; st_orqs := orqs; st_msgs := msgs |} ->\n        forall eidx,\n          In eidx (c_l1_indices cifc) ->\n          ObjsInvalid\n            (fun oidx =>\n               exists ecidx,\n                 parentIdxOf topo ecidx = Some eidx /\\\n                 In oidx (subtreeIndsOf topo ecidx)) oss msgs.\n    Proof.\n      intros; subst topo.\n      red; intros.\n      destruct (oss@[oidx]) as [ost|] eqn:Host; simpl; [|auto].\n      assert (oidx <> eidx /\\\n              In oidx (subtreeIndsOf (fst (tree2Topo tr 0)) eidx)).\n      { destruct H1 as [ecidx [? ?]].\n        split.\n        { intro; subst.\n          eapply parent_not_in_subtree; eauto.\n        }\n        { eapply subtreeIndsOf_child_SubList; eauto. }\n      }\n      clear H1; dest.\n\n      rewrite tree2Topo_l1_subtreeIndsOf in H2 by assumption.\n      dest_in; [exfalso; auto|].\n      exfalso.\n      specialize (H (l1ExtOf eidx)); simpl in H.\n      rewrite Host in H; simpl in H.\n      eapply tree2Topo_l1_child_ext_not_in; eauto.\n    Qed.\n\n    Lemma ObjsInvalid_this_rsUps_deqMsgs_silent:\n      forall inP oss msgs,\n        ObjsInvalid inP oss msgs ->\n        forall pidx,\n          ~ inP pidx ->\n          forall rminds,\n            Forall (fun midx =>\n                      exists cidx,\n                        parentIdxOf topo cidx = Some pidx /\\\n                        midx = rsUpFrom cidx) rminds ->\n            ObjsInvalid inP oss (deqMsgs rminds msgs).\n    Proof.\n      intros.\n      red; intros.\n      specialize (H _ H2).\n      destruct (oss@[oidx]) as [ost|]; simpl in H; simpl; auto.\n      destruct H.\n      - left.\n        destruct H as [? [? ?]].\n        repeat split; [assumption..|dest_in; solve_MsgsP].\n      - right.\n        destruct H as [[rmidx msg] [? ?]]; inv H3.\n        exists (downTo oidx, msg); split.\n        + apply deqMsgs_InMP_midx; [assumption|].\n          simpl; intro Hx.\n          rewrite Forall_forall in H1; specialize (H1 _ Hx).\n          dest; discriminate.\n        + unfold sigOf; simpl; congruence.\n    Qed.\n\n    Lemma ObjsInvalid_rsDown_invalidated:\n      forall oss msgs oidx orq,\n        ObjsInvalid (fun idx => oidx <> idx) oss msgs ->\n        RsDownConflicts oidx orq msgs ->\n        forall cidx (nost: OState) rmsg,\n          parentIdxOf topo cidx = Some oidx ->\n          nost#[status] <= mesiI ->\n          nost#[dir].(dir_st) <> mesiS ->\n          FirstMPI msgs (downTo oidx, rmsg) ->\n          rmsg.(msg_type) = MRs ->\n          ObjsInvalid (fun idx => cidx <> idx)\n                      (oss +[oidx <- nost])\n                      (deqMP (downTo oidx) msgs).\n    Proof.\n      intros; subst topo.\n      red; intros; mred.\n      - simpl; left; repeat split.\n        + simpl in *; solve_mesi.\n        + assumption.\n        + eapply NoCohMsgs_rsDown_deq; eauto.\n      - specialize (H _ (neq_sym n)).\n        destruct (oss@[oidx0]) as [ost|]; simpl in *; auto.\n        destruct H; [left|right].\n        + destruct H as [? [? ?]].\n          repeat split; [assumption..|solve_MsgsP].\n        + destruct H as [[midx msg] [? ?]].\n          exists (midx, msg); split; [|assumption]; inv H7.\n          apply deqMP_InMP_midx; [assumption|].\n          simpl; intro Hx; subst.\n          inv Hx; auto.\n    Qed.\n\n    Lemma ObjsInvalid_rsE_generated:\n      forall oss msgs oidx,\n        ObjsInvalid (fun idx => oidx <> idx) oss msgs ->\n        NoCohMsgs oidx msgs ->\n        forall cidx (nost: OState),\n          parentIdxOf topo cidx = Some oidx ->\n          nost#[status] <= mesiI ->\n          nost#[dir].(dir_st) = mesiE ->\n          ObjsInvalid (fun idx => cidx <> idx)\n                      (oss +[oidx <- nost])\n                      msgs.\n    Proof.\n      intros; subst topo.\n      red; intros; mred; auto.\n      simpl; left; repeat split.\n      - simpl in *; solve_mesi.\n      - rewrite H3; discriminate.\n      - assumption.\n    Qed.\n\n    Lemma ObjsInvalid_rsM_consumed:\n      forall oss msgs oidx (ost: OState) orq,\n        In oidx (c_li_indices cifc) ->\n        ObjsInvalid (fun idx => ~ In idx (subtreeIndsOf topo oidx)) oss msgs ->\n        RsDownConflicts oidx orq msgs ->\n        ost#[dir].(dir_st) = mesiI ->\n        InvDirInv topo cifc oidx ost oss msgs ->\n        forall cidx (nost: OState) rmsg,\n          nost#[status] <= mesiI ->\n          nost#[dir].(dir_st) = mesiM ->\n          FirstMPI msgs (downTo oidx, rmsg) ->\n          rmsg.(msg_type) = MRs ->\n          ObjsInvalid (fun idx => ~ In idx (subtreeIndsOf topo cidx))\n                      (oss +[oidx <- nost])\n                      (deqMP (downTo oidx) msgs).\n    Proof.\n      intros; subst topo.\n      red; intros; mred.\n      - simpl; left; repeat split.\n        + simpl in *; solve_mesi.\n        + rewrite H5; discriminate.\n        + eapply NoCohMsgs_rsDown_deq; eauto.\n      - destruct (in_dec idx_dec oidx0 (subtreeIndsOf (fst (tree2Topo tr 0)) oidx)).\n        + apply subtreeIndsOf_composed in i; auto.\n          destruct i; [exfalso; auto|].\n          destruct H9 as [rcidx [? ?]].\n\n          (* Discharge [InvDirInv] *)\n          specialize (H3 H _ H9); destruct H3 as [? _].\n          specialize (H3 (getDir_st_I _ H2 _)).\n          specialize (H3 _ H10).\n\n          destruct (oss@[oidx0]) as [ost0|]; simpl in *; auto.\n          destruct H3; [left|right].\n          * destruct H3 as [? [? ?]].\n            repeat split; [assumption..|solve_MsgsP].\n          * destruct H3 as [[midx msg] [? ?]].\n            exists (midx, msg); split; [|assumption]; inv H11.\n            apply deqMP_InMP_midx; [assumption|].\n            simpl; intro Hx; subst.\n            inv Hx; auto.\n\n        + specialize (H0 _ n0).\n          destruct (oss@[oidx0]) as [ost0|]; simpl in *; auto.\n          destruct H0; [left|right].\n          * destruct H0 as [? [? ?]].\n            repeat split; [assumption..|solve_MsgsP].\n          * destruct H0 as [[midx msg] [? ?]].\n            exists (midx, msg); split; [|assumption]; inv H9.\n            apply deqMP_InMP_midx; [assumption|].\n            simpl; intro Hx; subst.\n            inv Hx; auto.\n    Qed.\n\n    Lemma ObjsInvalid_rsM_generated:\n      forall oss msgs oidx,\n        ObjsInvalid (fun idx => oidx <> idx) oss msgs ->\n        NoCohMsgs oidx msgs ->\n        forall cidx (nost: OState),\n          parentIdxOf topo cidx = Some oidx ->\n          nost#[status] <= mesiI ->\n          nost#[dir].(dir_st) <> mesiS ->\n          ObjsInvalid (fun idx => ~ In idx (subtreeIndsOf topo cidx))\n                      (oss +[oidx <- nost])\n                      msgs.\n    Proof.\n      intros; subst topo.\n      red; intros; mred; auto.\n      simpl; left; repeat split.\n      - simpl in *; solve_mesi.\n      - assumption.\n      - assumption.\n    Qed.\n\n    Lemma ObjsInvalid_downRsIS:\n      forall oss msgs oidx (ost: OState) orq,\n        In oidx (c_li_indices cifc) ->\n        RqDownConflicts oidx msgs ->\n        RsDownConflicts oidx orq msgs ->\n        ost#[dir].(dir_st) = mesiI ->\n        InvDirInv topo cifc oidx ost oss msgs ->\n        forall (nost: OState) rqm rsm,\n          nost#[status] <= mesiI ->\n          nost#[dir].(dir_st) = mesiI ->\n          FirstMPI msgs (downTo oidx, rqm) ->\n          rqm.(msg_type) = MRq ->\n          rsm.(msg_id) = mesiDownRsIS ->\n          ObjsInvalid\n            (fun idx => In idx (subtreeIndsOf topo oidx))\n            (oss +[oidx <- nost])\n            (enqMP (rsUpFrom oidx) rsm (deqMP (downTo oidx) msgs)).\n    Proof.\n      intros; subst topo.\n      red; intros; mred.\n      - simpl; left; repeat split; [solve_mesi| |].\n        + rewrite H5; discriminate.\n        + apply NoCohMsgs_enq; [|rewrite H8; solve_not_in].\n          eapply NoCohMsgs_rqDown_deq; eauto.\n      - apply subtreeIndsOf_composed in H9; auto.\n        destruct H9; [exfalso; auto|].\n        destruct H9 as [cidx [? ?]].\n        destruct (oss@[oidx0]) as [ost0|] eqn:Host; simpl; auto.\n\n        (* Discharge [InvDirInv] *)\n        specialize (H3 H _ H9); destruct H3 as [? _].\n        specialize (H3 (getDir_st_I _ H2 _)).\n        specialize (H3 _ H10).\n\n        rewrite Host in H3; simpl in H3.\n        destruct H3; [left|right].\n        + destruct H3 as [? [? ?]]; repeat split; [assumption..|].\n          solve_MsgsP.\n        + destruct H3 as [[midx msg] [? ?]].\n          exists (midx, msg); split; [|assumption]; inv H11.\n          apply InMP_or_enqMP; right.\n          apply deqMP_InMP_midx; [assumption|].\n          simpl; intro Hx; inv Hx; auto.\n    Qed.\n\n    Lemma ObjsInvalid_downRsIM:\n      forall oss msgs oidx (ost: OState) orq,\n        In oidx (c_li_indices cifc) ->\n        RqDownConflicts oidx msgs ->\n        RsDownConflicts oidx orq msgs ->\n        ost#[dir].(dir_st) = mesiI ->\n        InvDirInv topo cifc oidx ost oss msgs ->\n        forall (nost: OState) rqm rsm,\n          nost#[status] <= mesiI ->\n          FirstMPI msgs (downTo oidx, rqm) ->\n          rqm.(msg_type) = MRq ->\n          rsm.(msg_id) = mesiDownRsIM ->\n          ObjsInvalid\n            (fun idx =>\n               exists cidx,\n                 parentIdxOf topo cidx = Some oidx /\\\n                 In idx (subtreeIndsOf topo cidx))\n            (oss +[oidx <- nost])\n            (enqMP (rsUpFrom oidx) rsm (deqMP (downTo oidx) msgs)).\n    Proof.\n      intros; subst topo.\n      red; intros; mred.\n      - exfalso.\n        destruct H8 as [cidx [? ?]].\n        eapply parent_not_in_subtree; eauto.\n      - destruct H8 as [cidx [? ?]].\n        destruct (oss@[oidx0]) as [ost0|] eqn:Host; simpl; auto.\n\n        (* Discharge [InvDirInv] *)\n        specialize (H3 H _ H8); destruct H3 as [? _].\n        specialize (H3 (getDir_st_I _ H2 _)).\n        specialize (H3 _ H9).\n\n        rewrite Host in H3; simpl in H3.\n        destruct H3; [left|right].\n        + destruct H3 as [? [? ?]]; repeat split; [assumption..|].\n          solve_MsgsP.\n        + destruct H3 as [[midx msg] [? ?]].\n          exists (midx, msg); split; [|assumption]; inv H10.\n          apply InMP_or_enqMP; right.\n          apply deqMP_InMP_midx; [assumption|].\n          simpl; intro Hx; inv Hx; auto.\n    Qed.\n\n    Lemma ObjsInvalid_out_composed:\n      forall oidx oss msgs,\n        ObjsInvalid\n          (fun idx => ~ In idx (subtreeIndsOf topo oidx))\n          oss msgs ->\n        forall ost,\n          oss@[oidx] = Some ost ->\n          ObjInvalid oidx ost msgs ->\n          forall cidx,\n            parentIdxOf topo cidx = Some oidx ->\n            (forall rcidx,\n                rcidx <> cidx ->\n                parentIdxOf topo rcidx = Some oidx ->\n                ObjsInvalid\n                  (fun idx => In idx (subtreeIndsOf topo rcidx))\n                  oss msgs) ->\n            ObjsInvalid\n              (fun idx => ~ In idx (subtreeIndsOf topo cidx))\n              oss msgs.\n    Proof.\n      intros.\n      red; intros toidx ?.\n      destruct (oss@[toidx]) as [tost|] eqn:Htost; simpl; auto.\n      destruct (in_dec idx_dec toidx (subtreeIndsOf topo oidx)).\n      - apply subtreeIndsOf_composed in i;\n          [|apply tree2Topo_WfDTree].\n        destruct i as [|[tcidx [? ?]]]; subst.\n        + congruence.\n        + destruct (idx_dec tcidx cidx); [subst; exfalso; auto|].\n          specialize (H3 _ n H5 _ H6).\n          rewrite Htost in H3; simpl in H3; assumption.\n      - specialize (H _ n).\n        rewrite Htost in H; simpl in H; assumption.\n    Qed.\n\n    Lemma ObjsInvalid_in_composed:\n      forall oidx oss msgs ost,\n        oss@[oidx] = Some ost ->\n        ObjInvalid oidx ost msgs ->\n        ObjsInvalid\n          (fun idx =>\n             exists rcidx,\n               parentIdxOf topo rcidx = Some oidx /\\\n               In idx (subtreeIndsOf topo rcidx)) oss msgs ->\n        ObjsInvalid\n          (fun idx => In idx (subtreeIndsOf topo oidx))\n          oss msgs.\n    Proof.\n      intros.\n      red; intros toidx ?.\n      destruct (oss@[toidx]) as [tost|] eqn:Htost; simpl; auto.\n      apply subtreeIndsOf_composed in H2;\n        [|apply tree2Topo_WfDTree].\n      destruct H2 as [|[tcidx [? ?]]]; subst.\n      - congruence.\n      - specialize (H1 toidx); simpl in H1.\n        rewrite Htost in H1; simpl in H1.\n        apply H1; eauto.\n    Qed.\n\n    Lemma ObjsInvalid_downRsIM_composed:\n      forall oidx oss msgs ost,\n        oss@[oidx] = Some ost ->\n        (forall rcidx,\n            parentIdxOf topo rcidx = Some oidx ->\n            ObjsInvalid\n              (fun idx => In idx (subtreeIndsOf topo rcidx))\n              oss msgs) ->\n        ObjsInvalid\n          (fun idx =>\n             exists cidx,\n               parentIdxOf topo cidx = Some oidx /\\\n               In idx (subtreeIndsOf topo cidx)) oss msgs.\n    Proof.\n      intros.\n      red; intros toidx ?.\n      destruct (oss@[toidx]) as [tost|] eqn:Htost; simpl; auto.\n      destruct H1 as [cidx [? ?]].\n      specialize (H0 _ H1 _ H2).\n      rewrite Htost in H0; simpl in H0.\n      assumption.\n    Qed.\n\n    Lemma ObjsInvalid_invRs_composed:\n      forall oidx oss msgs,\n        ObjsInvalid (fun idx => ~ In idx (subtreeIndsOf topo oidx)) oss msgs ->\n        ObjsInvalid\n          (fun idx =>\n             exists rcidx,\n               parentIdxOf topo rcidx = Some oidx /\\\n               In idx (subtreeIndsOf topo rcidx)) oss msgs ->\n        ObjsInvalid (fun idx => oidx <> idx) oss msgs.\n    Proof.\n      intros.\n      red; intros toidx ?.\n      destruct (oss@[toidx]) as [tost|] eqn:Htost; simpl; auto.\n      destruct (in_dec idx_dec toidx (subtreeIndsOf topo oidx)).\n      - apply subtreeIndsOf_composed in i; [|apply tree2Topo_WfDTree].\n        destruct i as [|[tcidx [? ?]]]; subst.\n        + congruence.\n        + specialize (H0 toidx); simpl in H0.\n          rewrite Htost in H0; simpl in H0.\n          apply H0; eauto.\n      - eapply ObjsInvalid_ObjInvalid; try exact H; auto.\n    Qed.\n\n  End OnTree.\n\nEnd Facts.\n\nLtac disc_ObjExcl0_msgs H :=\n  repeat\n    (first [apply ObjExcl0_enqMP_inv in H\n           |apply ObjExcl0_enqMsgs_inv in H\n           |apply ObjExcl0_other_midx_deqMP_inv in H;\n            [|solve_chn_neq; fail]\n           |apply ObjExcl0_other_midx_deqMsgs_inv in H;\n            [|eassumption|eassumption|]\n           |eapply ObjExcl0_other_msg_id_deqMP_inv in H;\n            [|eassumption\n             |simpl; try match goal with\n                         | [H: ?lh = _ |- ?lh <> _] => rewrite H\n                         end; discriminate]\n           |eapply ObjExcl0_other_msg_id_deqMsgs_inv in H;\n            [|eassumption|eassumption|]\n    ]).\n\nSection InvExcl.\n  Variable (tr: tree).\n  Hypothesis (Htr: tr <> Node nil).\n\n  Local Notation topo := (fst (tree2Topo tr 0)).\n  Local Notation cifc := (snd (tree2Topo tr 0)).\n  Local Notation impl := (impl Htr).\n\n  Lemma ObjInvalid_init:\n    forall oidx, ObjInvalid oidx implOStateInit (emptyMP Msg).\n  Proof.\n    intros; left.\n    repeat split; [simpl; solve_mesi|simpl; solve_mesi|].\n    do 3 red; intros.\n    do 2 red in H; dest_in.\n  Qed.\n\n  Lemma ObjsInvalid_init:\n    ObjsInvalid (fun oidx => oidx <> rootOf topo) (implOStatesInit tr) (emptyMP Msg).\n  Proof.\n    unfold ObjsInvalid; intros.\n    destruct (implOStatesInit tr)@[oidx] as [ost|] eqn:Host; simpl; auto.\n    destruct (in_dec idx_dec oidx (c_li_indices cifc ++ c_l1_indices cifc));\n      [|exfalso; rewrite implOStatesInit_None in Host by assumption; discriminate].\n    rewrite c_li_indices_head_rootOf in i by assumption; inv i; [exfalso; auto|].\n    rewrite implOStatesInit_value_non_root in Host by assumption; inv Host.\n    apply ObjInvalid_init.\n  Qed.\n\n  Lemma mesi_InvExcl_init:\n    Invariant.InvInit impl (InvExcl topo cifc).\n  Proof.\n    do 2 (red; simpl); intros.\n    destruct (implOStatesInit tr)@[eidx] as [eost|] eqn:Heost; simpl; auto.\n    repeat ssplit.\n\n    - red; intros.\n      red in H; dest.\n      destruct (in_dec idx_dec eidx (c_li_indices cifc ++ c_l1_indices cifc));\n        [|exfalso; rewrite implOStatesInit_None in Heost by assumption; discriminate].\n      rewrite c_li_indices_head_rootOf in i by assumption; inv i.\n      + split.\n        * red; intros.\n          destruct (implOStatesInit tr)@[oidx] as [ost|] eqn:Host; simpl; auto.\n          red.\n          destruct (in_dec idx_dec oidx ((c_li_indices (snd (tree2Topo tr 0)))\n                                           ++ c_l1_indices (snd (tree2Topo tr 0)))).\n          { rewrite c_li_indices_head_rootOf in i by assumption.\n            inv i; [exfalso; auto|].\n            rewrite implOStatesInit_value_non_root in Host by assumption.\n            inv Host.\n            left; repeat split; [simpl; solve_mesi..|].\n            do 3 red; intros; do 2 red in H3; dest_in.\n          }\n          { rewrite implOStatesInit_None in Host by assumption.\n            discriminate.\n          }\n        * do 3 red; intros; do 2 red in H1; dest_in.\n      + exfalso.\n        rewrite implOStatesInit_value_non_root in Heost by assumption.\n        inv Heost.\n        simpl in *; solve_mesi.\n\n    - red; intros.\n      split; [|do 3 red; intros; do 2 red in H0; dest_in].\n\n      destruct (in_dec idx_dec eidx (c_li_indices cifc ++ c_l1_indices cifc));\n        [|rewrite implOStatesInit_None in Heost by assumption; discriminate].\n      rewrite c_li_indices_head_rootOf in i by assumption; inv i.\n      + red; intros.\n        destruct (implOStatesInit tr)@[oidx] as [ost|] eqn:Host; simpl; auto.\n        red.\n        destruct (in_dec idx_dec oidx ((c_li_indices (snd (tree2Topo tr 0)))\n                                         ++ c_l1_indices (snd (tree2Topo tr 0)))).\n        * rewrite c_li_indices_head_rootOf in i by assumption.\n          inv i.\n          { elim H0.\n            apply subtreeIndsOf_root_in.\n            { apply tree2Topo_WfDTree. }\n            { apply Subtree_refl. }\n          }\n          { rewrite implOStatesInit_value_non_root in Host by assumption.\n            inv Host.\n            left; repeat split; [simpl; solve_mesi..|].\n            do 3 red; intros; do 2 red in H2; dest_in.\n          }\n        * rewrite implOStatesInit_None in Host by assumption; discriminate.\n      + rewrite implOStatesInit_value_non_root in Heost by assumption.\n        destruct H.\n        inv Heost; discriminate.\n\n    - red; intros.\n      destruct (in_dec idx_dec eidx (c_li_indices cifc ++ c_l1_indices cifc));\n        [|rewrite implOStatesInit_None in Heost by assumption; discriminate].\n      rewrite c_li_indices_head_rootOf in i by assumption; inv i.\n      + rewrite implOStatesInit_value_root in Heost by assumption; inv Heost.\n        split; [|intros; exfalso; cbn in H1; solve_mesi].\n        intros.\n        eapply ObjsInvalid_impl; [apply ObjsInvalid_init|].\n        simpl; intros.\n        intro Hx; subst.\n        eapply parent_not_in_subtree; eauto.\n      + rewrite implOStatesInit_value_non_root in Heost by assumption; inv Heost.\n        split; [|intros; exfalso; cbn in H2; solve_mesi].\n        intros.\n        eapply ObjsInvalid_impl; [apply ObjsInvalid_init|].\n        simpl; intros.\n        intro Hx; subst.\n        pose proof (parentIdxOf_child_indsOf _ _ H0).\n        rewrite <-subtreeIndsOf_indsOf with (dtr:= fst (tree2Topo tr 0)) in H4;\n          eauto; [|apply Subtree_refl].\n        eapply subtreeIndsOf_In_each_other_eq in H4; eauto; subst.\n        apply parentIdxOf_child_not_root in H0; auto.\n  Qed.\n\n  Lemma ObjsInvalid_ext_in:\n    forall inP oss msgs,\n      ObjsInvalid inP oss msgs ->\n      forall orqs,\n        InObjInds tr 0 {| st_oss := oss; st_orqs := orqs; st_msgs := msgs |} ->\n        forall eins,\n          ValidMsgsExtIn impl eins ->\n          ObjsInvalid inP oss (enqMsgs eins msgs).\n  Proof.\n    unfold ObjsInvalid; intros.\n    specialize (H _ H2).\n    destruct (oss@[oidx]) as [ost|] eqn:Host; simpl in *; auto.\n    destruct H.\n    - left.\n      red in H; dest.\n      repeat split; [assumption..|].\n      apply MsgsP_other_midx_enqMsgs; [assumption|].\n      destruct H1; simpl.\n      eapply DisjList_SubList; [eassumption|].\n      eapply DisjList_comm, DisjList_SubList.\n      + eapply SubList_trans;\n          [|eapply tree2Topo_obj_chns_minds_SubList with (oidx:= oidx)].\n        * solve_SubList.\n        * specialize (H0 oidx); simpl in H0.\n          rewrite Host in H0; simpl in H0.\n          eassumption.\n      + apply tree2Topo_minds_merqs_disj.\n    - right.\n      destruct H as [idm ?]; dest.\n      exists idm; split; [|assumption].\n      apply InMP_or_enqMsgs; auto.\n  Qed.\n\n  Lemma mesi_InvExcl_ext_in:\n    forall oss orqs msgs,\n      InvExcl topo cifc {| 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        InvExcl topo cifc {| st_oss := oss;\n                             st_orqs := orqs;\n                             st_msgs := enqMsgs eins msgs |}.\n  Proof.\n    red; simpl; intros.\n    specialize (H eidx); simpl in H.\n    destruct (oss@[eidx]) as [eost|] eqn:Heost; simpl in *; auto.\n\n    assert (NoCohMsgs eidx msgs ->\n            NoCohMsgs eidx (enqMsgs eins msgs)) as Hnc.\n    { intros.\n      apply MsgsP_other_midx_enqMsgs; [assumption|].\n      destruct H1; simpl.\n      eapply DisjList_SubList; [eassumption|].\n      eapply DisjList_comm, DisjList_SubList.\n      { eapply SubList_trans;\n          [|eapply tree2Topo_obj_chns_minds_SubList with (oidx:= eidx)].\n        { solve_SubList. }\n        { specialize (H0 eidx); simpl in H0.\n          rewrite Heost in H0; simpl in H0.\n          eassumption.\n        }\n      }\n      { apply tree2Topo_minds_merqs_disj. }\n    }\n\n    dest; repeat ssplit.\n\n    - clear H2 H3.\n      red; intros.\n      destruct H2.\n      apply MsgsP_enqMsgs_inv in H3.\n      specialize (H (conj H2 H3)); dest.\n      split.\n      + eapply ObjsInvalid_ext_in; eauto.\n      + apply Hnc; assumption.\n\n    - clear H H3.\n      red; intros.\n      destruct H; disc_MsgsP H3.\n      specialize (H2 (conj H H3)); dest; split.\n      + eapply ObjsInvalid_ext_in; eauto.\n      + apply Hnc; assumption.\n\n    - clear H H2.\n      red; intros.\n      specialize (H3 H _ H2); dest.\n      split; intros.\n      + clear H4; specialize (H3 H5).\n        eapply ObjsInvalid_ext_in; eauto.\n      + clear H3; specialize (H4 H5).\n        eapply ObjsInvalid_ext_in; eauto.\n  Qed.\n\n  Corollary mesi_InvExcl_InvTrsIns: InvTrsIns impl (InvExcl topo cifc).\n  Proof.\n    red; intros.\n    inv H1.\n    eapply mesi_InvExcl_ext_in; eauto.\n    apply (mesi_InObjInds H).\n  Qed.\n\n  Lemma ObjsInvalid_ext_out:\n    forall inP oss msgs,\n      ObjsInvalid inP oss msgs ->\n      forall orqs,\n        InObjInds tr 0 {| st_oss := oss; st_orqs := orqs; st_msgs := msgs |} ->\n        forall (eouts: list (Id Msg)),\n          ValidMsgsExtOut impl eouts ->\n          ObjsInvalid inP oss (deqMsgs (idsOf eouts) msgs).\n  Proof.\n    unfold ObjsInvalid; intros.\n    specialize (H _ H2).\n    destruct (oss@[oidx]) as [ost|] eqn:Host; simpl in *; auto.\n    destruct H.\n    - left.\n      red in H; dest.\n      repeat split; [assumption..|].\n      apply MsgsP_deqMsgs; assumption.\n    - right.\n      destruct H as [idm ?]; dest.\n      exists idm; split; [|assumption].\n      apply deqMsgs_InMP_midx; [assumption|].\n      destruct H1.\n      eapply DisjList_In_1.\n      + eapply DisjList_SubList; [eassumption|].\n        apply DisjList_comm, tree2Topo_minds_merss_disj.\n      + eapply tree2Topo_obj_chns_minds_SubList with (oidx:= oidx).\n        * specialize (H0 oidx); simpl in H0.\n          rewrite Host in H0; simpl in H0.\n          eassumption.\n        * inv H3; rewrite H6.\n          solve_SubList.\n  Qed.\n\n  Lemma mesi_InvExcl_ext_out:\n    forall oss orqs msgs,\n      InvExcl topo cifc {| 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        ValidMsgsExtOut impl eouts ->\n        InvExcl topo cifc {| st_oss := oss;\n                             st_orqs := orqs;\n                             st_msgs := deqMsgs (idsOf eouts) msgs |}.\n  Proof.\n    red; simpl; intros.\n    specialize (H eidx); simpl in H.\n    destruct (oss@[eidx]) as [eost|] eqn:Heost; simpl in *; auto.\n\n    assert (NoRsI eidx (deqMsgs (idsOf eouts) msgs) -> NoRsI eidx msgs) as Hrsi.\n    { intros.\n      apply MsgsP_other_midx_deqMsgs_inv in H2; [assumption|].\n      destruct H1.\n      simpl; eapply DisjList_SubList; [eassumption|].\n      eapply DisjList_comm, DisjList_SubList.\n      { eapply SubList_trans;\n          [|eapply tree2Topo_obj_chns_minds_SubList with (oidx:= eidx)].\n        { solve_SubList. }\n        { specialize (H0 eidx); simpl in H0.\n          rewrite Heost in H0; simpl in H0.\n          eassumption.\n        }\n      }\n      { apply tree2Topo_minds_merss_disj. }\n    }\n\n    dest; repeat ssplit.\n\n    - clear H2 H3.\n      red; intros.\n      destruct H2.\n      apply Hrsi in H3.\n      specialize (H (conj H2 H3)); dest.\n      split.\n      + eapply ObjsInvalid_ext_out; eauto.\n      + apply MsgsP_deqMsgs; assumption.\n\n    - clear H H3.\n      red; intros.\n      destruct H.\n      apply Hrsi in H3.\n      specialize (H2 (conj H H3)); dest; split.\n      + eapply ObjsInvalid_ext_out; eauto.\n      + apply MsgsP_deqMsgs; assumption.\n\n    - clear H H2.\n      red; intros.\n      specialize (H3 H _ H2); dest.\n      split; intros.\n      + clear H4; specialize (H3 H5).\n        eapply ObjsInvalid_ext_out; eauto.\n      + clear H3; specialize (H4 H5).\n        eapply ObjsInvalid_ext_out; eauto.\n  Qed.\n\n  Corollary mesi_InvExcl_InvTrsOuts: InvTrsOuts impl (InvExcl topo cifc).\n  Proof.\n    red; intros.\n    inv H1.\n    eapply mesi_InvExcl_ext_out; eauto.\n    apply (mesi_InObjInds H).\n  Qed.\n\n  Definition GetRqPred (oidx: IdxT) (eout: Id Msg): Prop :=\n    idOf eout = rqUpFrom oidx ->\n    (valOf eout).(msg_type) = MRq ->\n    (valOf eout).(msg_id) = Spec.getRq -> False.\n\n  Definition SetRqPred (oidx: IdxT) (eout: Id Msg): Prop :=\n    idOf eout = rqUpFrom oidx ->\n    (valOf eout).(msg_type) = MRq ->\n    (valOf eout).(msg_id) = Spec.setRq -> False.\n\n  Definition RsMPred (oidx: IdxT) (eout: Id Msg) (oss: OStates)\n             (msgs: MessagePool Msg): Prop :=\n    idOf eout = downTo oidx ->\n    (valOf eout).(msg_type) = MRs ->\n    (valOf eout).(msg_id) = mesiRsM ->\n    ObjsInvalid (fun idx => ~ In idx (subtreeIndsOf topo oidx)) oss msgs.\n\n  Definition RsEPred (oidx: IdxT) (eout: Id Msg) (oss: OStates)\n             (msgs: MessagePool Msg): Prop :=\n    idOf eout = downTo oidx ->\n    (valOf eout).(msg_type) = MRs ->\n    (valOf eout).(msg_id) = mesiRsE ->\n    ObjsInvalid (fun idx => oidx <> idx) oss msgs.\n\n  Definition DownRsSPred (oidx: IdxT) (eout: Id Msg) (oss: OStates)\n             (msgs: MessagePool Msg): Prop :=\n    idOf eout = rsUpFrom oidx ->\n    (valOf eout).(msg_type) = MRs ->\n    (valOf eout).(msg_id) = mesiDownRsS ->\n    ost <+- oss@[oidx]; (ost#[status] <= mesiS /\\ ost#[owned] = false).\n\n  Definition DownRsISPred (oidx: IdxT) (eout: Id Msg) (oss: OStates)\n             (msgs: MessagePool Msg): Prop :=\n    idOf eout = rsUpFrom oidx ->\n    (valOf eout).(msg_type) = MRs ->\n    (valOf eout).(msg_id) = mesiDownRsIS ->\n    (ost <+- oss@[oidx]; ost#[status] <= mesiI /\\ ost#[owned] = false) /\\\n    ObjsInvalid (fun idx => In idx (subtreeIndsOf topo oidx)) oss msgs.\n\n  Definition DownRsIMPred (oidx: IdxT) (eout: Id Msg) (oss: OStates)\n             (msgs: MessagePool Msg): Prop :=\n    idOf eout = rsUpFrom oidx ->\n    (valOf eout).(msg_type) = MRs ->\n    (valOf eout).(msg_id) = mesiDownRsIM ->\n    (ost <+- oss@[oidx]; ost#[status] <= mesiI /\\\n                         ost#[dir].(dir_st) = mesiI /\\\n                         ost#[owned] = false) /\\\n    ObjsInvalid\n      (fun idx =>\n         exists cidx,\n           parentIdxOf topo cidx = Some oidx /\\\n           In idx (subtreeIndsOf topo cidx)) oss msgs.\n\n  Definition InvRqPred (oidx: IdxT) (eout: Id Msg) (oss: OStates)\n             (msgs: MessagePool Msg): Prop :=\n    idOf eout = rqUpFrom oidx ->\n    (valOf eout).(msg_type) = MRq ->\n    (valOf eout).(msg_id) = mesiInvRq ->\n    ost <+- oss@[oidx]; ost#[dir].(dir_st) = mesiI.\n\n  Definition InvWRqPred (oidx: IdxT) (eout: Id Msg) (oss: OStates)\n             (msgs: MessagePool Msg): Prop :=\n    idOf eout = rqUpFrom oidx ->\n    (valOf eout).(msg_type) = MRq ->\n    (valOf eout).(msg_id) = mesiInvWRq ->\n    ost <+- oss@[oidx]; ost#[dir].(dir_st) = mesiI.\n\n  Definition InvExclMsgOutPred: MsgOutPred :=\n    fun eout oss orqs msgs =>\n      forall oidx,\n        GetRqPred oidx eout /\\ SetRqPred oidx eout /\\\n        RsMPred oidx eout oss msgs /\\ RsEPred oidx eout oss msgs /\\\n        DownRsSPred oidx eout oss msgs /\\\n        DownRsISPred oidx eout oss msgs /\\ DownRsIMPred oidx eout oss msgs /\\\n        InvRqPred oidx eout oss msgs /\\ InvWRqPred oidx eout oss msgs.\n\n  Lemma InvExclMsgOutPred_good:\n    GoodMsgOutPred topo InvExclMsgOutPred.\n  Proof.\n    pose proof (tree2Topo_TreeTopoNode tr 0) as Htn.\n    red; intros; split.\n\n    - (* No RqDown predicates at all *)\n      red; intros; destruct H.\n      do 2 (red; intros).\n      specialize (H2 oidx0); dest.\n      repeat ssplit;\n        try (red; intros; rewrite H12 in H1;\n             derive_child_chns oidx; disc_rule_conds_ex; fail).\n\n    - red; intros; destruct H.\n      pose proof (rsEdgeUpFrom_Some (mesi_RqRsChnsOnDTree tr) _ H0).\n      destruct H1 as [rqUp [down [pidx ?]]]; dest.\n      do 2 (red; intros).\n      specialize (H4 oidx0); dest.\n      repeat ssplit;\n        try (red; intros; rewrite H14 in H0;\n             derive_child_chns oidx; disc_rule_conds_ex; fail).\n\n      + (* [DownRsSPred] *)\n        red; intros; rewrite H14 in H0.\n        derive_child_chns oidx; disc_rule_conds_ex.\n        assert (In oidx (subtreeIndsOf (fst (tree2Topo tr 0)) oidx))\n          by (eapply rqEdgeUpFrom_subtreeIndsOf_self_in;\n              [eauto|congruence]).\n        pose proof (H5 _ H17); dest.\n        rewrite <-H18; apply H9; assumption.\n\n      + (* [DownRsISPred] *)\n        red; intros; rewrite H14 in H0.\n        derive_child_chns oidx; disc_rule_conds_ex.\n        split.\n        * assert (In oidx (subtreeIndsOf (fst (tree2Topo tr 0)) oidx))\n            by (eapply rqEdgeUpFrom_subtreeIndsOf_self_in;\n                [eauto|congruence]).\n          pose proof (H5 _ H17); dest.\n          rewrite <-H18; apply H10; assumption.\n        * red; intros.\n          specialize (H10 H14 H15 H16); destruct H10 as [? ?].\n          specialize (H18 _ H17).\n          specialize (H5 _ H17); dest.\n          rewrite <-H5.\n          assert (exists pidx0, parentIdxOf (fst (tree2Topo tr 0)) oidx0 = Some pidx0).\n          { eapply subtreeIndsOf_in_has_parent with (oidx:= oidx); eauto. }\n          destruct H21 as [pidx0 ?].\n          derive_child_chns oidx0.\n\n          red in H20; dest.\n          specialize (H20 _ H22).\n          specialize (H25 _ H23).\n          specialize (H26 _ H24).\n          destruct (oss1@[oidx0]) as [ost0|]; simpl in *; auto.\n          destruct H18; [left|right].\n          { destruct H18 as [? [? ?]].\n            repeat split; [assumption..|].\n            apply not_MsgExistsSig_MsgsNotExist; intros.\n            eapply MsgExistsSig_MsgsNotExist_false in H29; eauto.\n            dest_in.\n            all: try (destruct H30 as [[midx msg] [? ?]];\n                      exists (midx, msg); split; [|assumption]; inv H30;\n                      do 2 red in H29; do 2 red; simpl in *; congruence).\n          }\n          { destruct H18 as [[midx msg] [? ?]].\n            exists (midx, msg); split; [|assumption]; inv H27.\n            do 2 red in H18; do 2 red; simpl in *; congruence.\n          }\n\n      + (* [DownRsIMPred] *)\n        red; intros; rewrite H14 in H0.\n        derive_child_chns oidx; disc_rule_conds_ex.\n        split.\n        * assert (In oidx (subtreeIndsOf (fst (tree2Topo tr 0)) oidx))\n            by (eapply rqEdgeUpFrom_subtreeIndsOf_self_in;\n                [eauto|congruence]).\n          pose proof (H5 _ H17); dest.\n          rewrite <-H18; apply H11; assumption.\n        * red; intros.\n          specialize (H11 H14 H15 H16); destruct H11 as [? ?].\n          specialize (H18 _ H17).\n          destruct H17 as [cidx [? ?]].\n          eapply subtreeIndsOf_child_SubList in H19; eauto.\n          specialize (H5 _ H19); dest.\n          rewrite <-H5.\n          assert (exists pidx0, parentIdxOf (fst (tree2Topo tr 0)) oidx0 = Some pidx0).\n          { eapply subtreeIndsOf_in_has_parent with (oidx:= oidx); eauto. }\n          destruct H22 as [pidx0 ?].\n          derive_child_chns oidx0.\n\n          red in H21; dest.\n          specialize (H21 _ H23).\n          specialize (H26 _ H24).\n          specialize (H27 _ H25).\n          destruct (oss1@[oidx0]) as [ost0|]; simpl in *; auto.\n          destruct H18; [left|right].\n          { destruct H18 as [? [? ?]].\n            repeat split; [assumption..|].\n            apply not_MsgExistsSig_MsgsNotExist; intros.\n            eapply MsgExistsSig_MsgsNotExist_false in H30; eauto.\n            dest_in.\n            all: try (destruct H31 as [[midx msg] [? ?]];\n                      exists (midx, msg); split; [|assumption]; inv H31;\n                      do 2 red in H30; do 2 red; simpl in *; congruence).\n          }\n          { destruct H18 as [[midx msg] [? ?]].\n            exists (midx, msg); split; [|assumption]; inv H28.\n            do 2 red in H18; do 2 red; simpl in *; congruence.\n          }\n  Qed.\n  Local Hint Resolve InvExclMsgOutPred_good.\n\n  Ltac disc_rule_custom ::=\n    try disc_AtomicInv;\n    repeat match goal with\n           | [H: idsOf _ = map fst (rqi_rss _) |- _] => rewrite <-H in *\n           | [H: SubList (_ :: _) _ |- _] => apply SubList_cons_inv in H; destruct H\n           end.\n\n  (*! Ltacs about [InvExcl] *)\n\n  Ltac case_InvExcl_me_others :=\n    match goal with\n    | |- InvExcl _ _ _ => red; simpl; intros; mred; simpl\n    end.\n\n  Ltac case_InvObjOwned :=\n    match goal with\n    | [H: InvObjOwned _ _ _ _ _ |- InvObjOwned _ _ _ _ _] =>\n      let Ho := fresh \"H\" in\n      let Hrsi := fresh \"H\" in\n      red; simpl; intros [Ho Hrsi]; disc_MsgsP Hrsi;\n      specialize (H (conj Ho Hrsi)); dest;\n      split; [red; intros; mred; simpl|]\n    end.\n\n  Ltac case_ObjInvalid_with oidx :=\n    match goal with\n    | |- ObjInvalid ?eidx _ _ =>\n      destruct (idx_dec eidx oidx); subst\n    end.\n\n  Ltac case_ObjInvalid :=\n    match goal with\n    | [H: ObjInvalid _ _ _ |- ObjInvalid _ _ _] =>\n      destruct H; [left|right]\n    end.\n\n  Ltac disc_InvExcl oidx :=\n    repeat\n      match goal with\n      | [H: InvExcl _ _ _ |- _] => specialize (H oidx); simpl in H\n      | [He: _ <+- ?ov; _, Ho: ?ov = Some _ |- _] =>\n        rewrite Ho in He; simpl in He; dest; repeat ssplit\n      end.\n\n  Ltac disc_InvExcl_this :=\n    match goal with\n    | |- InvObjExcl0 ?oidx _ _ _ /\\ _ => disc_InvExcl oidx\n    end.\n\n  Ltac disc_InvExcl_others :=\n    match goal with\n    | [H: InvExcl _ _ _ |- _ <+- _@[?eidx]; _] =>\n      specialize (H eidx); simpl in H;\n      disc_bind_true; dest; repeat ssplit\n    end.\n\n  Ltac disc_ObjsInvalid :=\n    match goal with\n    | [H: ObjsInvalid _ _ _ |- ObjsInvalid _ _ _] =>\n      let Hi := fresh \"H\" in\n      red; intros ? Hi; specialize (H _ Hi); mred;\n      simpl in *; [|disc_bind_true]\n    end.\n\n  Ltac disc_ObjsInvalid_by oidx :=\n    match goal with\n    | [Hi: ObjsInvalid _ _ _ |- _] =>\n      pose proof (Hi oidx ltac:(auto)); disc_bind_true\n    end.\n\n  Ltac disc_InvObjExcl0 :=\n    match goal with\n    | |- InvObjExcl0 _ _ _ _ =>\n      let He := fresh \"H\" in\n      red; intros He; disc_ObjExcl0_msgs He\n    end.\n\n  Ltac disc_InvObjExcl0_apply :=\n    match goal with\n    | [H: InvObjExcl0 _ _ _ _ |- InvObjExcl0 _ _ _ _] =>\n      let He := fresh \"H\" in\n      red; intros He; disc_ObjExcl0_msgs He;\n      specialize (H He); dest\n    end.\n\n  Ltac disc_ObjExcl0 :=\n    match goal with\n    | [H: ObjExcl0 _ _ _ |- _] => red in H; dest; simpl in *\n    end.\n\n  Ltac derive_not_InvalidObj_not_in roidx :=\n    match goal with\n    | [H: ObjsInvalid (fun _ => ~ In _ ?inds) _ _ |- _] =>\n      assert (In roidx inds)\n        by (destruct (in_dec idx_dec roidx inds); [assumption|];\n            exfalso;\n            eapply ObjsInvalid_obj_status_false with (oidx:= roidx); eauto;\n            simpl; solve_mesi)\n    end.\n\n  Ltac solve_InvObjExcl0_by_ObjExcl0_false :=\n    red; intros; exfalso;\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    match goal with\n    | [H: ObjExcl0 _ _ _ |- _] =>\n      red in H; dest; simpl in *; solve_mesi\n    end.\n\n  Local Hint Extern 0 (WfDTree _) => apply mesi_WfDTree.\n  Local Hint Extern 0 (RqRsChnsOnDTree _) => apply mesi_RqRsChnsOnDTree.\n  Ltac solve_by_topo_false :=\n    match goal with\n    | [H: ~ In ?oidx (subtreeIndsOf _ ?oidx) |- _] =>\n      elim H; eapply parent_subtreeIndsOf_self_in; eauto; fail\n    | [H: ~ In ?oidx (subtreeIndsOf _ ?oidx) |- _] =>\n      elim H; eapply rqEdgeUpFrom_subtreeIndsOf_self_in; eauto; congruence\n    | [Hp: parentIdxOf _ ?cidx = Some ?pidx, Hi: ~ In ?cidx (subtreeIndsOf _ ?oidx) |- _] =>\n      elim Hi; apply subtreeIndsOf_child_in; auto; fail\n    | [Hp: parentIdxOf _ ?cidx = Some ?pidx, Hip: In ?pidx (subtreeIndsOf _ ?oidx), Hic: ~ In ?cidx (subtreeIndsOf _ ?oidx) |- _] =>\n      elim Hic; eapply inside_child_in; eauto; fail\n    | [H: ~ In (l1ExtOf ?oidx) (subtreeIndsOf _ ?oidx) |- _] =>\n      elim H; apply subtreeIndsOf_child_in; auto;\n      apply tree2Topo_l1_ext_parent; assumption\n\n    | [Hp1: parentIdxOf _ ?rcidx1 = Some ?pidx,\n            Hp2: parentIdxOf _ ?rcidx2 = Some ?pidx,\n                 Hc: ?rcidx1 <> ?rcidx2,\n                     Hin: In ?rcidx1 (subtreeIndsOf _ ?rcidx2) |- _] =>\n      eapply subtreeIndsOf_other_child_not_in with (cidx1:= rcidx1) (cidx2:= rcidx2); eauto\n    | [Hp1: parentIdxOf _ ?rcidx1 = Some ?pidx,\n            Hp2: parentIdxOf _ ?rcidx2 = Some ?pidx,\n                 Hc: ?rcidx2 <> ?rcidx1,\n                     Hin: In ?rcidx1 (subtreeIndsOf _ ?rcidx2) |- _] =>\n      eapply subtreeIndsOf_other_child_not_in with (cidx1:= rcidx1) (cidx2:= rcidx2); eauto\n    | [Hp: parentIdxOf _ ?cidx = Some ?pidx,\n           Hin: In ?pidx (subtreeIndsOf _ ?cidx) |- _] =>\n      eapply parent_not_in_subtree; eauto\n\n\n    | [Hp: parentIdxOf _ ?cidx = Some ?pidx,\n           Hn: ~ In ?pidx (subtreeIndsOf _ ?sidx),\n               Hin: In ?cidx (subtreeIndsOf _ ?sidx) |- _] =>\n      eapply outside_child_in in Hn; eauto;\n      destruct Hn; [subst|exfalso; auto]; disc_rule_conds_ex; fail\n    | [Hp: parentIdxOf _ ?cidx = Some ?pidx,\n           Hn: ~ In ?pidx (subtreeIndsOf _ ?sidx),\n               Hin: In ?cidx (subtreeIndsOf _ ?sidx),\n                    Hneq: ?cidx <> ?sidx |- _] =>\n      elim Hn; eapply inside_parent_in with (cidx:= cidx); eauto\n    | [Hp: parentIdxOf _ ?cidx = Some ?pidx,\n           Hn: ~ In ?pidx (subtreeIndsOf _ ?sidx),\n               Hin: In ?cidx (subtreeIndsOf _ ?sidx),\n                    Hneq: ?sidx <> ?cidx |- _] =>\n      elim Hn; eapply inside_parent_in with (cidx:= cidx); eauto\n    end.\n\n  Ltac solve_ObjInvalid0 :=\n    match goal with\n    | [H: ObjInvalid0 _ _ _ |- ObjInvalid0 _ _ _] =>\n      destruct H as [? [? ?]]; repeat split; [assumption..|solve_MsgsP]\n    end.\n\n  Ltac solve_ObjInvRs :=\n    repeat\n      match goal with\n      | [H: ObjInvRs _ _ |- ObjInvRs _ _] =>\n        let midx := fresh \"midx\" in\n        let msg := fresh \"msg\" in\n        destruct H as [[midx msg] [? ?]];\n        exists (midx, msg); split; [|assumption]\n      | [H: sigOf _ = _ |- _] => inv H\n      | |- InMPI (enqMP _ _ _) _ => apply InMP_or_enqMP; right\n      | |- InMP _ _ (enqMP _ _ _) => apply InMP_or_enqMP; right\n      | |- InMPI (deqMP _ _) _ => apply deqMP_InMP_midx; [|solve_chn_not_in]\n      | |- InMP _ _ (deqMP _ _) => apply deqMP_InMP_midx; [|solve_chn_not_in]\n      | _ => assumption\n      end.\n\n  Ltac solve_by_ObjsInvalid_status_false roidx :=\n    exfalso;\n    eapply ObjsInvalid_obj_status_false with (oidx := roidx); eauto;\n    simpl in *; solve [auto|solve_mesi].\n\n  Ltac solve_by_ObjsInvalid_dir_false roidx :=\n    exfalso;\n    eapply ObjsInvalid_obj_dir_false with (oidx := roidx); eauto;\n    simpl in *; solve [auto|solve_mesi].\n\n  Ltac solve_by_ObjsInvalid_rsS_false roidx :=\n    exfalso;\n    eapply ObjsInvalid_rsS_false with (oidx:= roidx); eauto;\n    apply FirstMP_InMP; assumption.\n\n  Ltac solve_by_ObjsInvalid_rsE_false roidx :=\n    exfalso;\n    eapply ObjsInvalid_rsE_false with (oidx:= roidx); eauto;\n    apply FirstMP_InMP; assumption.\n\n  Ltac solve_by_ObjsInvalid_rsM_false roidx :=\n    exfalso;\n    match goal with\n    | [H: ObjsInvalid _ _ _ |- _] =>\n      eapply ObjsInvalid_rsM_false with (oidx:= roidx);\n      [eapply H|..]; simpl in *; eauto;\n      apply FirstMP_InMP; assumption\n    end.\n\n  Ltac solve_by_ObjsInvalid_downRsS_false roidx :=\n    exfalso;\n    match goal with\n    | [H: ObjsInvalid _ _ _ |- _] =>\n      eapply ObjsInvalid_downRsS_false with (oidx:= roidx);\n      [eapply H|..]; simpl in *; eauto;\n      apply FirstMP_InMP; assumption\n    end.\n\n  Ltac solve_by_ObjsInvalid_downRsIM_false roidx :=\n    exfalso;\n    match goal with\n    | [H: ObjsInvalid _ _ _ |- _] =>\n      eapply ObjsInvalid_downRsIM_false with (oidx:= roidx);\n      [eapply H|..]; simpl in *; eauto;\n      apply FirstMP_InMP; assumption\n    end.\n\n  Ltac solve_InvObjOwned_by_false :=\n    red; simpl; intros [? ?]; discriminate.\n\n  Ltac split_InvDirInv_apply :=\n    match goal with\n    | [H: InvDirInv _ _ _ _ _ _ |- InvDirInv _ _ _ _ _ _] =>\n      let Hli := fresh \"H\" in\n      let Hc := fresh \"H\" in\n      red; intros Hli ? Hc;\n      let H1 := fresh \"H\" in\n      let H2 := fresh \"H\" in\n      specialize (H Hli _ Hc); destruct H as [H1 H2];\n      let Hdir := fresh \"H\" in\n      split; intros Hdir; [specialize (H1 Hdir)|specialize (H2 Hdir)]\n    end.\n\n  Ltac split_InvDirInv :=\n    match goal with\n    | [H: InvDirInv _ _ _ _ _ _ |- InvDirInv _ _ _ _ _ _] =>\n      let Hli := fresh \"H\" in\n      let Hc := fresh \"H\" in\n      red; intros Hli ? Hc;\n      specialize (H Hli _ Hc); dest; split; intros\n    end.\n\n  Lemma ObjsInvalid_deq_sound:\n    forall inP oss msgs,\n      ObjsInvalid inP oss msgs ->\n      forall rmsgs,\n        NoDup (idsOf rmsgs) ->\n        Forall (FirstMPI msgs) rmsgs ->\n        Forall (fun idm => In (msg_id (valOf idm))\n                              [mesiRqS; mesiDownRqS;\n                              mesiRqM; mesiDownRqIS; mesiDownRqIM; mesiDownRsIS;\n                              mesiInvRq; mesiInvWRq;\n                              getRq; getRs; setRq; setRs]) rmsgs ->\n        ObjsInvalid inP oss (deqMsgs (idsOf rmsgs) msgs).\n  Proof.\n    red; intros.\n    specialize (H _ H3).\n    disc_bind_true.\n    case_ObjInvalid.\n    - solve_ObjInvalid0.\n    - solve_ObjInvRs.\n      apply deqMsgs_InMP; try assumption.\n      simpl; intro Hx.\n      rewrite Forall_forall in H2; specialize (H2 _ Hx).\n      simpl in H2; rewrite H9 in H2.\n      intuition discriminate.\n  Qed.\n\n  Lemma ObjsInvalid_enq_sound:\n    forall inP oss msgs,\n      ObjsInvalid inP oss msgs ->\n      forall nmsgs,\n        Forall (fun idm => In (msg_id (valOf idm))\n                              [mesiRqS; mesiDownRqS;\n                              mesiRqM; mesiDownRqIS; mesiDownRqIM; mesiDownRsIS;\n                              mesiInvRq; mesiInvWRq; mesiInvRs;\n                              getRq; getRs; setRq; setRs]) nmsgs ->\n        ObjsInvalid inP oss (enqMsgs nmsgs msgs).\n  Proof.\n    red; intros.\n    specialize (H _ H1).\n    disc_bind_true.\n    case_ObjInvalid.\n    - solve_ObjInvalid0.\n      apply MsgsP_other_msg_id_enqMsgs; [assumption|].\n      simpl.\n      apply (DisjList_spec_1 idx_dec); intros midx ?.\n      apply in_map_iff in H5; destruct H5 as [[rmidx msg] [? ?]].\n      simpl in *; subst.\n      rewrite Forall_forall in H0; specialize (H0 _ H6); simpl in H0.\n      intro Hx.\n      repeat\n        match goal with\n        | [H: _ \\/ _ |- _] => destruct H\n        | [H1: _ = msg_id ?msg, H2: _ = msg_id ?msg |- _] =>\n          rewrite <-H1 in H2; discriminate\n        | [H: False |- False] => auto\n        end.\n    - solve_ObjInvRs.\n      apply InMP_or_enqMsgs; auto.\n  Qed.\n\n  Lemma InvExcl_deq_sound:\n    forall oss porqs norqs msgs,\n      InvExcl topo cifc {| st_oss := oss; st_orqs := porqs; st_msgs := msgs |} ->\n      forall rmsgs,\n        NoDup (idsOf rmsgs) ->\n        Forall (FirstMPI msgs) rmsgs ->\n        Forall (fun idm => In (msg_id (valOf idm))\n                              [mesiRqS; mesiDownRqS;\n                              mesiRqM; mesiDownRqIS; mesiDownRqIM; mesiDownRsIS;\n                              mesiInvRq; mesiInvWRq;\n                              getRq; getRs; setRq; setRs]) rmsgs ->\n        InvExcl topo cifc {| st_oss := oss;\n                             st_orqs := norqs;\n                             st_msgs := deqMsgs (idsOf rmsgs) msgs |}.\n  Proof.\n    intros.\n    red; simpl; intros.\n    specialize (H eidx); simpl in H.\n\n    assert (NoRsI eidx (deqMsgs (idsOf rmsgs) msgs) ->\n            NoRsI eidx msgs) as Hrsi.\n    { intros.\n      apply MsgsP_other_msg_id_deqMsgs_inv in H3; try eassumption.\n      simpl.\n      apply (DisjList_spec_1 idx_dec); intros midx ?.\n      apply in_map_iff in H4; destruct H4 as [[rmidx msg] [? ?]].\n      simpl in *; subst.\n      rewrite Forall_forall in H2; specialize (H2 _ H5); simpl in H2.\n      intro Hx; destruct Hx; [|auto].\n      rewrite <-H4 in H2.\n      intuition discriminate.\n    }\n\n    disc_bind_true; dest; repeat ssplit.\n\n    - red; intros.\n      destruct H6.\n      apply Hrsi in H7.\n      specialize (H (conj H6 H7)); dest; split.\n      + apply ObjsInvalid_deq_sound; auto.\n      + solve_MsgsP.\n    - red; intros.\n      destruct H6.\n      apply Hrsi in H7.\n      specialize (H4 (conj H6 H7)); dest; split.\n      + apply ObjsInvalid_deq_sound; auto.\n      + solve_MsgsP.\n    - red; intros.\n      specialize (H5 H6 _ H7); dest.\n      split; intros.\n      + specialize (H5 H9).\n        apply ObjsInvalid_deq_sound; auto.\n      + specialize (H8 H9).\n        apply ObjsInvalid_deq_sound; auto.\n  Qed.\n\n  Lemma InvExcl_enq_sound:\n    forall oss porqs norqs msgs,\n      InvExcl topo cifc {| st_oss := oss; st_orqs := porqs; st_msgs := msgs |} ->\n      forall nmsgs,\n        Forall (fun idm => In (msg_id (valOf idm))\n                              [mesiRqS; mesiDownRqS;\n                              mesiRqM; mesiDownRqIS; mesiDownRqIM; mesiDownRsIS;\n                              mesiInvRq; mesiInvWRq; mesiInvRs;\n                              getRq; getRs; setRq; setRs]) nmsgs ->\n        InvExcl topo cifc {| st_oss := oss;\n                             st_orqs := norqs;\n                             st_msgs := enqMsgs nmsgs msgs |}.\n  Proof.\n    intros.\n    red; simpl; intros.\n    specialize (H eidx); simpl in H.\n\n    assert (NoCohMsgs eidx msgs ->\n            NoCohMsgs eidx (enqMsgs nmsgs msgs)) as Hnc.\n    { intros.\n      apply MsgsP_other_msg_id_enqMsgs; [assumption|].\n      simpl.\n      apply (DisjList_spec_1 idx_dec); intros midx ?.\n      apply in_map_iff in H2; destruct H2 as [[rmidx msg] [? ?]].\n      simpl in *; subst.\n      rewrite Forall_forall in H0; specialize (H0 _ H3); simpl in H0.\n      intro Hx.\n      repeat\n        match goal with\n        | [H: _ \\/ _ |- _] => destruct H\n        | [H1: _ = msg_id ?msg, H2: _ = msg_id ?msg |- _] =>\n          rewrite <-H1 in H2; discriminate\n        | [H: False |- False] => auto\n        end.\n    }\n\n    disc_bind_true; dest; repeat ssplit.\n\n    - disc_InvObjExcl0_apply; split.\n      + apply ObjsInvalid_enq_sound; auto.\n      + apply Hnc; assumption.\n\n    - red; intros.\n      destruct H4; disc_MsgsP H5.\n      specialize (H2 (conj H4 H5)); dest; split.\n      + apply ObjsInvalid_enq_sound; auto.\n      + apply Hnc; assumption.\n\n    - red; intros.\n      specialize (H3 H4 _ H5); dest.\n      split; intros.\n      + specialize (H3 H7).\n        apply ObjsInvalid_enq_sound; auto.\n      + specialize (H6 H7).\n        apply ObjsInvalid_enq_sound; auto.\n  Qed.\n\n  Lemma ObjsInvalid_state_transition_sound:\n    forall inP oss msgs,\n      ObjsInvalid inP oss msgs ->\n      forall oidx (post nost: OState),\n        oss@[oidx] = Some post ->\n        (nost#[status] <= mesiI \\/ nost#[status] <= post#[status]) ->\n        (nost#[dir].(dir_st) <> mesiS \\/ nost#[dir].(dir_st) = post#[dir].(dir_st)) ->\n        ObjsInvalid inP (oss +[oidx <- nost]) msgs.\n  Proof.\n    intros.\n    red; intros.\n    specialize (H _ H3).\n    mred; simpl; auto.\n    destruct H; [left|right].\n    - destruct H as [? [? ?]].\n      repeat split.\n      + solve_mesi.\n      + destruct H2; [assumption|congruence].\n      + assumption.\n    - assumption.\n  Qed.\n\n  Lemma InvExcl_state_transition_sound:\n    forall oss porqs msgs,\n      InvExcl topo cifc {| st_oss := oss; st_orqs := porqs; st_msgs := msgs |} ->\n      forall oidx (post nost: OState) norqs,\n        oss@[oidx] = Some post ->\n        (nost#[status] <= mesiI \\/ nost#[status] <= post#[status]) ->\n        post#[owned] || negb (nost#[owned]) = true ->\n        nost#[dir] = post#[dir] ->\n        InvExcl topo cifc {| st_oss := oss +[oidx <- nost];\n                             st_orqs := norqs; st_msgs := msgs |}.\n  Proof.\n    intros.\n    red; simpl; intros.\n    specialize (H eidx); simpl in H.\n    mred; simpl; dest.\n    - repeat ssplit.\n      + red; intros.\n        destruct H6.\n        assert (mesiE <= post#[status]) by solve_mesi.\n        specialize (H (conj H8 H7)); dest.\n        split; [|assumption].\n        eapply ObjsInvalid_state_transition_sound; eauto.\n        intuition congruence.\n      + red; intros.\n        destruct H6.\n        rewrite H6 in H2; simpl in H2.\n        rewrite orb_false_r in H2.\n        specialize (H4 (conj H2 H7)); dest; split; [|assumption].\n        eapply ObjsInvalid_state_transition_sound; eauto.\n        intuition congruence.\n      + red; intros.\n        specialize (H5 H6 _ H7); dest.\n        split; intros.\n        * rewrite <-H3 in H5; specialize (H5 H9).\n          eapply ObjsInvalid_state_transition_sound; eauto.\n          intuition congruence.\n        * rewrite <-H3 in H8; specialize (H8 H9).\n          eapply ObjsInvalid_state_transition_sound; eauto.\n          intuition congruence.\n\n    - disc_bind_true; dest; repeat ssplit.\n      + red; intros; specialize (H H7); dest.\n        split; [|assumption].\n        eapply ObjsInvalid_state_transition_sound; eauto.\n        simpl; intuition congruence.\n      + red; intros.\n        specialize (H5 H7); dest; split; [|assumption].\n        eapply ObjsInvalid_state_transition_sound; eauto.\n        simpl; intuition congruence.\n      + red; intros.\n        specialize (H6 H7 _ H8); dest.\n        split; intros.\n        * specialize (H6 H10).\n          eapply ObjsInvalid_state_transition_sound; eauto.\n          simpl; intuition congruence.\n        * specialize (H9 H10).\n          eapply ObjsInvalid_state_transition_sound; eauto.\n          simpl; intuition congruence.\n  Qed.\n\n  Lemma InvExcl_inv_ObjsInvalid:\n    forall oss orqs msgs\n           (Hioi: InObjInds tr 0 {| st_oss := oss; st_orqs := orqs; st_msgs := msgs |}),\n      InvExcl topo cifc {| st_oss := oss; st_orqs := orqs; st_msgs := msgs |} ->\n      forall oidx nost cidx cost uaddr,\n        In cidx (c_li_indices cifc ++ c_l1_indices cifc) ->\n        parentIdxOf topo cidx = Some oidx ->\n        oss@[cidx] = Some cost ->\n        cost#[dir].(dir_st) = mesiI ->\n        ObjsInvalid (fun idx => In idx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx))\n                    (oss +[oidx <- nost])\n                    (enqMP (downTo cidx) {| msg_id := mesiInvRs;\n                                            msg_type := MRs;\n                                            msg_addr := uaddr;\n                                            msg_value := 0 |}\n                           (deqMP (rqUpFrom cidx) msgs)).\n  Proof.\n    intros.\n    disc_InvExcl cidx.\n\n    assert (forall uaddr,\n               ObjInvalid cidx cost\n                          (enqMP (downTo cidx) {| msg_id := mesiInvRs;\n                                                  msg_type := MRs;\n                                                  msg_addr := uaddr;\n                                                  msg_value := 0 |}\n                                 (deqMP (rqUpFrom cidx) msgs))) as Hoi.\n    { intros; right; eexists (_, _); split.\n      { apply InMP_or_enqMP; left; simpl; eauto. }\n      { reflexivity. }\n    }\n\n    apply in_app_or in H0; destruct H0.\n    - eapply ObjsInvalid_in_composed with (oidx:= cidx).\n      + apply parentIdxOf_not_eq in H1; auto; mred.\n      + apply Hoi.\n      + red; intros; destruct H6 as [ccidx [? ?]].\n        specialize (H5 H0 _ H6); dest.\n        specialize (H5 (getDir_st_I _ H3 _) _ H7).\n        mred; simpl.\n        * exfalso.\n          eapply subtreeIndsOf_child_SubList in H7; eauto.\n          eapply parent_not_in_subtree with (pidx:= oidx); eauto.\n        * disc_bind_true.\n          destruct H5; [left|right].\n          { destruct H5 as [? [? ?]]; repeat split; [assumption..|].\n            solve_MsgsP.\n          }\n          { destruct H5 as [[midx msg] [? ?]].\n            exists (midx, msg); split; [|assumption]; inv H10.\n            apply InMP_or_enqMP; right.\n            apply deqMP_InMP_midx; [assumption|].\n            simpl; intro Hx; discriminate.\n          }\n\n    - red; intros.\n      mred; simpl; [exfalso; eapply parent_not_in_subtree with (pidx:= oidx); eauto|].\n      rewrite tree2Topo_l1_subtreeIndsOf in H6 by assumption.\n      dest_in; [rewrite H2; simpl; apply Hoi|].\n      disc_bind_true.\n      exfalso.\n      specialize (Hioi (l1ExtOf cidx)); simpl in Hioi.\n      rewrite H6 in Hioi; simpl in Hioi.\n      eapply tree2Topo_l1_child_ext_not_in; eauto.\n  Qed.\n\n  Ltac solve_InvExcl_msgs :=\n    repeat\n      match goal with\n      | _ => assumption\n      (* For single enq/deq *)\n      | |- NoDup (idsOf [_]) => repeat constructor; intro; dest_in\n      | |- NoDup [_] => repeat constructor; intro; dest_in\n      | |- Forall _ [_] => constructor; [|constructor]\n      | |- In _ _ => simpl\n      | [H: msg_id ?msg = _ |- context [msg_id ?msg]] => rewrite H\n      | |- _ \\/ _ => tauto\n      (* For multiple enqs/deqs *)\n      | [H: ValidMsgsIn _ ?msgs |- NoDup (idsOf ?msgs)] => apply H\n      | |- Forall _ (map _ _) =>\n        let midx := fresh \"midx\" in\n        let msg := fresh \"msg\" in\n        let Hin := fresh \"H\" in\n        apply Forall_forall; intros [midx msg] Hin;\n        apply in_map_iff in Hin; dest\n      | [Hf: Forall (fun _ => msg_id _ = _) ?msgs\n         |- Forall (fun _ => In _ _) ?msgs] =>\n        let midx := fresh \"midx\" in\n        let msg := fresh \"msg\" in\n        let Hin := fresh \"H\" in\n        apply Forall_forall; intros [midx msg] Hin;\n        rewrite Forall_forall in Hf; specialize (Hf _ Hin);\n        simpl in Hf\n      | [H: (_, _) = (_, _) |- _] => inv H\n      end.\n\n  Ltac solve_InvExcl_trivial :=\n    try match goal with\n        | |- InvExcl _ _ {| st_oss := ?oss +[?oidx <- ?pos] |} =>\n          replace (oss +[oidx <- pos]) with oss by meq\n        end;\n    repeat\n      match goal with\n      | [He: InvExcl _ _ {| st_orqs := ?orqs |}\n         |- InvExcl _ _ {| st_msgs := enqMP ?midx ?msg _ |}] =>\n        eapply InvExcl_enq_sound with (porqs:= orqs) (nmsgs:= [(midx, msg)]);\n        [|solve_InvExcl_msgs; fail]\n      | [He: InvExcl _ _ {| st_orqs := ?orqs |},\n             Hf: FirstMPI _ (?midx, ?msg)\n         |- InvExcl _ _ {| st_msgs := deqMP ?midx _ |}] =>\n        eapply InvExcl_deq_sound with (porqs:= orqs) (rmsgs:= [(midx, msg)]);\n        [|solve_InvExcl_msgs; fail..]\n      | [He: InvExcl _ _ {| st_orqs := ?orqs |}\n         |- InvExcl _ _ {| st_msgs := enqMsgs _ _ |}] =>\n        eapply InvExcl_enq_sound with (porqs:= orqs); [|solve_InvExcl_msgs; fail]\n      | [He: InvExcl _ _ {| st_orqs := ?orqs |}\n         |- InvExcl _ _ {| st_msgs := deqMsgs _ _ |}] =>\n        eapply InvExcl_deq_sound with (porqs:= orqs); [|solve_InvExcl_msgs; fail..]\n      end; try eassumption.\n\n  Ltac exfalso_InvTrs_init :=\n    exfalso;\n    repeat\n      match goal with\n      | [H: In _ (c_merqs _) |- _] =>\n        rewrite c_merqs_l1_rqUpFrom in H;\n        apply in_map_iff in H;\n        let oidx := fresh \"oidx\" in\n        destruct H as [oidx [? ?]]\n      | [H: parentIdxOf _ (l1ExtOf _) = Some _ |- _] =>\n        rewrite tree2Topo_l1_ext_parent in H by assumption\n      | [H: rqUpFrom (l1ExtOf _) = rqUpFrom _ |- _] => inv H\n      | [H: rqUpFrom (l1ExtOf _) = rsUpFrom _ |- _] => inv H\n      | [H: rqUpFrom (l1ExtOf _) = downTo _ |- _] => inv H\n      | [H: Some _ = Some _ |- _] => inv H\n      | [H1: ~ In ?i ?l, H2: In ?i ?l |- _] => elim H1; assumption\n      end.\n\n  Ltac pick_rsUp_single :=\n    match goal with\n    | [Hrr: RqRsDownMatch _ _ _ ?rss _, Hrss: [_] = map fst ?rss |- _] =>\n      let Hrr0 := fresh \"H\" in\n      pose proof Hrr as Hrr0;\n      eapply RqRsDownMatch_rs_rq in Hrr0; [|rewrite <-Hrss; left; reflexivity];\n      let cidx := fresh \"cidx\" in\n      let down := fresh \"down\" in\n      destruct Hrr0 as [cidx [down ?]]; dest\n    end.\n\n  Ltac pick_rsUps_one :=\n    match goal with\n    | [Hrr: RqRsDownMatch _ _ _ ?rss _, Hrss: idsOf ?ins = map fst ?rss |- _] =>\n      pose proof (RqRsDownMatch_rs_not_nil Hrr);\n      let midx := fresh \"midx\" in\n      let msg := fresh \"msg\" in\n      destruct ins as [|[midx msg] ins];\n      [exfalso; apply eq_sym, map_eq_nil in Hrss; auto|];\n      simpl in Hrr; eapply RqRsDownMatch_rs_rq in Hrr;\n      [|rewrite <-Hrss; left; reflexivity];\n      let cidx := fresh \"cidx\" in\n      let down := fresh \"down\" in\n      destruct Hrr as [cidx [down ?]]; dest\n    end.\n\n  Ltac case_idx_eq oidx1 oidx2 :=\n    destruct (idx_dec oidx1 oidx2); [subst|].\n\n  Ltac case_in_subtree oidx sidx :=\n    destruct (in_dec idx_dec oidx (subtreeIndsOf (fst (tree2Topo tr 0)) sidx)).\n\n  Ltac solve_ObjsInvalid_trivial :=\n    repeat (first [assumption\n                  |eapply ObjsInvalid_shrinked; eassumption\n                  |eapply ObjsInvalid_this_enqMP_silent;\n                   [| |simpl; tauto]; [|solve [auto|intro; solve_by_topo_false]]\n                  |eapply ObjsInvalid_this_deqMP_silent;\n                   [| |simpl; tauto]; [|solve [auto|intro; solve_by_topo_false]]\n                  |apply ObjsInvalid_this_state_silent;\n                   [|solve [auto|intro; solve_by_topo_false]]\n                  |apply ObjsInvalid_enq_sound with (nmsgs:= [(_, _)]);\n                   [|constructor; [simpl; tauto|constructor]]\n                  |eapply ObjsInvalid_deq_sound with (rmsgs:= [(_, _)]);\n                   [|eauto|eauto\n                    |constructor; [simpl; intuition auto; fail|constructor]]\n           ]).\n\n  Ltac disc_InvObjOwned :=\n    match goal with\n    | [H: InvObjOwned _ _ _ _ _ |- InvObjOwned _ _ _ _ _] =>\n      let Ho := fresh \"H\" in\n      let Hrsi := fresh \"H\" in\n      red; simpl; intros [Ho Hrsi];\n      try (disc_MsgsP Hrsi; specialize (H (conj Ho Hrsi)); dest)\n    end.\n\n  Ltac solve_msg_pred_base :=\n    let Hm := fresh \"H\" in\n    red; simpl; intros Hm _ _; inv Hm; mred.\n\n  Ltac solve_AtomicInv_init :=\n    do 2 red; simpl;\n    repeat constructor;\n    try (red; simpl; intros; intuition discriminate);\n    solve_msg_pred_base.\n\n  Ltac disc_L1DirI oidx :=\n    match goal with\n    | [Hl: InvL1DirI _ {| st_oss := ?oss |},\n           Hoin: In oidx (c_l1_indices _),\n                 Host: ?oss@[oidx] = Some _ |- _] =>\n      red in Hl; rewrite Forall_forall in Hl;\n      specialize (Hl _ Hoin); simpl in Hl; rewrite Host in Hl\n    end.\n\n  Lemma mesi_InvExcl_InvTrs_init:\n    forall st1,\n      Reachable (steps step_m) impl st1 ->\n      InvExcl topo cifc st1 ->\n      forall oidx ridx ins outs st2,\n        SubList (idsOf ins) (sys_merqs impl) ->\n        step_m impl st1 (RlblInt oidx ridx ins outs) st2 ->\n        AtomicInv\n          InvExclMsgOutPred\n          ins st1 [RlblInt oidx ridx ins outs] outs st2 /\\\n        InvExcl topo cifc st2.\n  Proof. (* SKIP_PROOF_ON\n    intros.\n\n    pose proof (tree2Topo_TreeTopoNode tr 0) as Htn.\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 (@MesiUpLockInv_ok _ Htr _ H) as Hulinv.\n    pose proof (@MesiDownLockInv_ok _ Htr _ H) as Hdlinv.\n    pose proof (@mesi_InvL1DirI_ok _ Htr _ H) as Hl1d.\n\n    inv_step.\n\n    simpl in H7; destruct H7; [subst|apply in_app_or in H2; destruct H2].\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      (** The root 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 H2.\n        eapply DisjList_In_2; [eassumption|].\n        assumption.\n      }\n\n      (** Do case analysis per a rule. *)\n      apply concat_In in H8; destruct H8 as [crls [? ?]].\n      apply in_map_iff in H3; destruct H3 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; disc_rule_conds_ex.\n      all: try (exfalso_InvTrs_init; fail).\n\n    - (*! Cases for Li caches *)\n      apply in_map_iff in H2; destruct H2 as [oidx [? ?]]; subst; simpl in *.\n\n      pose proof (c_li_indices_tail_has_parent Htr _ _ H3).\n      destruct H2 as [pidx [? ?]].\n      pose proof (Htn _ _ H4); dest.\n\n      (** 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 H9.\n        eapply DisjList_In_2; [eassumption|].\n        apply tl_In; assumption.\n      }\n\n      (** Do case analysis per a rule. *)\n      apply in_app_or in H8; destruct H8.\n\n      1: { (** Rules per a child *)\n        apply concat_In in H8; destruct H8 as [crls [? ?]].\n        apply in_map_iff in H8; destruct H8 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; disc_rule_conds_ex.\n        all: try (exfalso_InvTrs_init; fail).\n      }\n\n      dest_in; disc_rule_conds_ex.\n\n      all: try (derive_footprint_info_basis oidx; exfalso_InvTrs_init; fail).\n\n      { disc_MesiDownLockInv oidx Hdlinv.\n        derive_footprint_info_basis oidx.\n        disc_responses_from.\n        derive_child_chns upCIdx.\n        disc_rule_conds_ex.\n        exfalso_InvTrs_init.\n      }\n      { disc_MesiDownLockInv oidx Hdlinv.\n        derive_footprint_info_basis oidx; [solve_midx_false|].\n        disc_responses_from.\n        derive_child_chns oidx.\n        disc_rule_conds_ex.\n        exfalso_InvTrs_init.\n      }\n\n      { disc_MesiDownLockInv oidx Hdlinv.\n        derive_footprint_info_basis oidx.\n        pick_rsUps_one.\n        derive_child_chns cidx.\n        disc_rule_conds_ex.\n        exfalso_InvTrs_init.\n      }\n      { disc_MesiDownLockInv oidx Hdlinv.\n        derive_footprint_info_basis oidx.\n        pick_rsUps_one.\n        derive_child_chns cidx.\n        disc_rule_conds_ex.\n        exfalso_InvTrs_init.\n      }\n\n      { disc_MesiDownLockInv oidx Hdlinv.\n        derive_footprint_info_basis oidx; [solve_midx_false|].\n        pick_rsUps_one.\n        derive_child_chns cidx.\n        disc_rule_conds_ex.\n        exfalso_InvTrs_init.\n      }\n      { disc_MesiDownLockInv oidx Hdlinv.\n        derive_footprint_info_basis oidx; [solve_midx_false|].\n        pick_rsUps_one.\n        derive_child_chns cidx.\n        disc_rule_conds_ex.\n        exfalso_InvTrs_init.\n      }\n      { disc_MesiDownLockInv oidx Hdlinv.\n        derive_footprint_info_basis oidx; [solve_midx_false|].\n        pick_rsUps_one.\n        derive_child_chns cidx.\n        disc_rule_conds_ex.\n        exfalso_InvTrs_init.\n      }\n\n      { (* [liInvRqUpUp] *)\n        disc_rule_conds_ex; split.\n        { solve_AtomicInv_init. }\n        { solve_InvExcl_trivial. }\n      }\n\n      { (* [liInvRqUpUpWB] *)\n        disc_rule_conds_ex; split.\n        { solve_AtomicInv_init. }\n        { solve_InvExcl_trivial. }\n      }\n\n      { (* [liDropImm] *)\n        disc_rule_conds_ex; split.\n        { solve_AtomicInv_init. }\n        { eapply InvExcl_state_transition_sound with (porqs:= orqs);\n            try eassumption.\n          { simpl; intuition solve_mesi. }\n          { simpl; intuition. }\n          { reflexivity. }\n        }\n      }\n\n    - (*! Cases for L1 caches *)\n      apply in_map_iff in H2; destruct H2 as [oidx [? ?]]; subst.\n\n      pose proof (c_l1_indices_has_parent Htr _ _ H3).\n      destruct H2 as [pidx [? ?]].\n      pose proof (Htn _ _ H4); dest.\n\n      (** Do case analysis per a rule. *)\n      dest_in.\n\n      { (* [l1GetSImm] *)\n        disc_rule_conds_ex; split.\n        { solve_AtomicInv_init. }\n        { solve_InvExcl_trivial. }\n      }\n\n      { (* [l1GetSRqUpUp] *)\n        disc_rule_conds_ex; split.\n        { solve_AtomicInv_init. }\n        { solve_InvExcl_trivial. }\n      }\n\n      { (* [l1GetSRsDownDownS] *)\n        disc_rule_conds_ex.\n        derive_footprint_info_basis oidx.\n        exfalso_InvTrs_init.\n      }\n\n      { (* [l1GetSRsDownDownE] *)\n        disc_rule_conds_ex.\n        derive_footprint_info_basis oidx.\n        exfalso_InvTrs_init.\n      }\n\n      { (* [l1DownSImm] *)\n        disc_rule_conds_ex.\n        exfalso_InvTrs_init.\n      }\n\n      { (* [l1GetMImmE] *)\n        disc_rule_conds_ex.\n        derive_NoRsI_by_no_uplock oidx msgs.\n\n        split.\n        { solve_AtomicInv_init. }\n        { solve_InvExcl_trivial.\n          case_InvExcl_me_others.\n          { assert (ObjExcl0 oidx os msgs)\n              by (split; [simpl in *; solve_mesi|assumption]).\n            disc_InvExcl_this.\n            { specialize (H0 H14); dest.\n              red; intros.\n              split; [|assumption].\n              red; intros; specialize (H0 _ H26); mred.\n            }\n            { specialize (H0 H14); dest.\n              red; intros _.\n              split; [|assumption].\n              red; intros.\n              mred; [solve_by_topo_false|auto].\n            }\n            { red; intros; exfalso.\n              pose proof (tree2Topo_WfCIfc tr 0) as [? _].\n              apply (DisjList_NoDup idx_dec) in H26.\n              eapply DisjList_In_1; eassumption.\n            }\n          }\n\n          { disc_InvExcl_others.\n            { disc_InvObjExcl0_apply.\n              solve_by_ObjsInvalid_status_false oidx.\n            }\n            { case_InvObjOwned; auto.\n              solve_by_ObjsInvalid_status_false oidx.\n            }\n            { split_InvDirInv_apply.\n              { case_in_subtree oidx cidx.\n                { solve_by_ObjsInvalid_status_false oidx. }\n                { apply ObjsInvalid_this_state_silent; auto. }\n              }\n              { case_in_subtree oidx cidx.\n                { apply ObjsInvalid_this_state_silent; auto. }\n                { solve_by_ObjsInvalid_status_false oidx. }\n              }\n            }\n          }\n        }\n      }\n\n      { (* [l1GetMImmM] *)\n        disc_rule_conds_ex; split.\n        { solve_AtomicInv_init. }\n        { eapply InvExcl_state_transition_sound with (porqs:= orqs);\n            try eassumption.\n          { solve_InvExcl_trivial. }\n          { simpl; auto. }\n          { simpl; intuition. }\n          { reflexivity. }\n        }\n      }\n\n      { (* [l1GetMRqUpUp] *)\n        disc_rule_conds_ex; split.\n        { solve_AtomicInv_init. }\n        { solve_InvExcl_trivial. }\n      }\n\n      { (* [l1GetMRsDownDown] *)\n        disc_rule_conds_ex.\n        derive_footprint_info_basis oidx.\n        exfalso_InvTrs_init.\n      }\n\n      { (* [l1DownIImmS] *)\n        disc_rule_conds_ex.\n        exfalso_InvTrs_init.\n      }\n      { (* [l1DownIImmME] *)\n        disc_rule_conds_ex.\n        exfalso_InvTrs_init.\n      }\n\n      { (* [l1InvRqUpUp] *)\n        disc_rule_conds_ex; split.\n        { solve_AtomicInv_init.\n          disc_L1DirI oidx0; assumption.\n        }\n        { solve_InvExcl_trivial. }\n      }\n\n      { (* [l1InvRqUpUpWB] *)\n        disc_rule_conds_ex; split.\n        { solve_AtomicInv_init.\n          disc_L1DirI oidx0; assumption.\n        }\n        { solve_InvExcl_trivial. }\n      }\n\n      { (* [l1InvRsDownDown] *)\n        disc_rule_conds_ex.\n        derive_footprint_info_basis oidx.\n        exfalso_InvTrs_init.\n      }\n\n      Unshelve.\n      all: assumption.\n\n      END_SKIP_PROOF_ON *) admit.\n  Qed.\n\n  Ltac disc_AtomicMsgOutsInv oidx :=\n    match goal with\n    | [Ha: AtomicMsgOutsInv _ ?eouts _, Hin: In _ ?eouts |- _] =>\n      red in Ha; rewrite Forall_forall in Ha; specialize (Ha _ Hin oidx);\n      simpl in Ha; dest\n    end.\n\n  Ltac disc_MsgPred :=\n    match goal with\n    | [Hp: RsMPred _ (_, ?rmsg) _ _,\n           Ht: msg_type ?rmsg = _,\n               Hi: msg_id ?rmsg = mesiRsM |- _] =>\n      specialize (Hp eq_refl Ht Hi)\n    | [Hp: RsEPred _ (_, ?rmsg) _ _,\n           Ht: msg_type ?rmsg = _,\n               Hi: msg_id ?rmsg = mesiRsE |- _] =>\n      specialize (Hp eq_refl Ht Hi)\n    | [Hp: DownRsSPred _ (_, ?rmsg) _ _,\n           Ht: msg_type ?rmsg = _,\n               Hi: msg_id ?rmsg = mesiDownRsS |- _] =>\n      specialize (Hp eq_refl Ht Hi)\n    | [Hp: DownRsISPred _ (_, ?rmsg) _ _,\n           Ht: msg_type ?rmsg = _,\n               Hi: msg_id ?rmsg = mesiDownRsIS |- _] =>\n      specialize (Hp eq_refl Ht Hi)\n    | [Hp: DownRsIMPred _ (_, ?rmsg) _ _,\n           Ht: msg_type ?rmsg = _,\n               Hi: msg_id ?rmsg = mesiDownRsIM |- _] =>\n      specialize (Hp eq_refl Ht Hi)\n    | [Hp: InvRqPred _ (_, ?rmsg) _ _,\n           Ht: msg_type ?rmsg = _,\n               Hi: msg_id ?rmsg = mesiInvRq |- _] =>\n      specialize (Hp eq_refl Ht Hi)\n    | [Hp: InvWRqPred _ (_, ?rmsg) _ _,\n           Ht: msg_type ?rmsg = _,\n               Hi: msg_id ?rmsg = mesiInvWRq |- _] =>\n      specialize (Hp eq_refl Ht Hi)\n    end;\n    try match goal with\n        | [Hp: _ <+- ?oss@[?oidx]; _, Ho: ?oss@[?oidx] = Some _ |- _] =>\n          rewrite Ho in Hp; simpl in Hp\n        end.\n\n  Ltac solve_AtomicInv_rqDown_rqDowns :=\n    match goal with\n    | [Hr: Reachable _ _ ?st,\n           Hs: steps _ _ ?st ?hst _,\n               Ha: Atomic _ _ ?hst _ ?eouts,\n                   H: FirstMPI _ (?midx, ?msg)\n       |- context [enqMP ?nmidx ?nmsg (deqMP ?midx _)] ] =>\n      do 2 red; simpl;\n      apply Forall_app;\n      [change midx with (idOf (midx, msg)) at 1;\n       eapply atomic_rqDown_rqDowns_preserves_msg_out_preds\n         with (rqDowns:= [(nmidx, nmsg)]);\n       try exact Hr; eauto; [red; auto; fail|]\n      |repeat constructor;\n       try (red; simpl; intros; intuition discriminate)]\n\n    | [Hr: Reachable _ _ ?st,\n           Hs: steps _ _ ?st ?hst _,\n               Ha: Atomic _ _ ?hst _ ?eouts,\n                   H: FirstMPI _ (?midx, ?msg)\n       |- context [enqMsgs _ (deqMP ?midx _)] ] =>\n      do 2 red; simpl;\n      apply Forall_app;\n      [change midx with (idOf (midx, msg)) at 1;\n       eapply atomic_rqDown_rqDowns_preserves_msg_out_preds;\n       try exact Hr; eauto; [red; auto; fail|]\n      |repeat constructor;\n       try (red; simpl; intros; intuition discriminate)]\n    end.\n\n  Ltac solve_AtomicInv_rsDown :=\n    match goal with\n    | [Hr: Reachable _ _ ?st,\n           Hs: steps step_m _ ?st ?hst _,\n               Ha: Atomic _ _ ?hst _ ?eouts,\n                   Hin: In (downTo ?roidx, _) ?eouts\n       |- AtomicInv _ _ _ _ _ _] =>\n      do 2 red; simpl;\n      eapply atomic_rsDown_singleton in Ha;\n      try exact Hr; eauto; [|red; eauto];\n      subst; rewrite removeOnce_nil; simpl;\n      repeat constructor; try (red; simpl; intros; intuition discriminate)\n    end.\n\n  Ltac solve_AtomicInv_rqDown_rsUp :=\n    match goal with\n    | [Hr: Reachable _ _ ?st,\n           Hs: steps _ _ ?st ?hst _,\n               Ha: Atomic _ _ ?hst _ ?eouts,\n                   H: FirstMPI _ (?midx, ?msg) |- context [deqMP ?midx _] ] =>\n      do 2 red; simpl;\n      apply Forall_app;\n      [change midx with (idOf (midx, msg)) at 1;\n       eapply atomic_rqDown_rsUp_preserves_msg_out_preds;\n       try exact Hr; eauto;\n       red; auto\n      |repeat constructor;\n       try (red; simpl; intros; intuition discriminate)]\n    end.\n\n  Ltac solve_AtomicInv_rsUps_rsDown Hrsd :=\n    erewrite Hrsd;\n    [|apply in_or_app; right; left; reflexivity|red; eauto];\n    do 2 red; simpl;\n    repeat constructor;\n    try (red; simpl; intros; intuition discriminate).\n\n  Ltac solve_AtomicInv_rsUps_rsUp :=\n    repeat\n      match goal with\n      | _ => assumption\n      | |- _ = _ => reflexivity\n\n      | [Hr: Reachable _ _ ?st,\n             Hs: steps _ _ ?st ?hst _,\n                 Ha: Atomic _ _ ?hst _ ?eouts,\n                     H: FirstMPI _ (?midx, ?msg) |- context [deqMP ?midx _] ] =>\n        do 2 red; simpl; apply Forall_app;\n        [change midx with (idOf (midx, msg)) at 1;\n         eapply atomic_rsUps_rsUp_preserves_msg_out_preds\n           with (rsUps:= [(midx, msg)]);\n         try exact Hr; eauto\n        |repeat constructor;\n         try (red; simpl; intros; intuition discriminate)]\n      | [Hr: Reachable _ _ ?st,\n             Hs: steps _ _ ?st ?hst _,\n                 Ha: Atomic _ _ ?hst _ ?eouts,\n                     H: Forall (FirstMPI _) ?rss |- _] =>\n        do 2 red; simpl; apply Forall_app;\n        [eapply atomic_rsUps_rsUp_preserves_msg_out_preds\n           with (rsUps:= rss); try exact Hr; eauto\n        |repeat constructor;\n         try (red; simpl; intros; intuition discriminate)]\n\n      (* Belows are for the single RsUp input *)\n      | [H: In (li _ ?oidx) _ |- In _ (sys_objs _)] =>\n        right; apply in_or_app; left; eassumption\n      | |- SubList [_] _ => apply SubList_cons; [|apply SubList_nil]\n      end.\n\n  Ltac solve_AtomicInv_rqUp :=\n    match goal with\n    | [Hr: Reachable _ _ ?st,\n           Hs: steps step_m _ ?st ?hst _,\n               Ha: Atomic _ _ ?hst _ ?eouts,\n                   Hin: In (rqUpFrom ?roidx, _) ?eouts\n       |- AtomicInv _ _ _ _ _ _] =>\n      do 2 red; simpl;\n      eapply atomic_rqUp_singleton in Ha;\n      try exact Hr; eauto; [|red; eauto];\n      subst; rewrite removeOnce_nil; simpl;\n      repeat constructor; try (red; simpl; intros; intuition discriminate)\n    end.\n\n  Ltac solve_DownRsSPred :=\n    solve_msg_pred_base; mred;\n    try (simpl; intuition solve_mesi).\n\n  Ltac disc_dir :=\n    repeat\n      match goal with\n      | [H: context[getDir _ _] |- _] => progress simpl in H\n      | [H: context[getDir _ (addSharer _ _)] |- _] =>\n        rewrite getDir_addSharer_spec in H by solve_mesi;\n        destruct (idx_dec _ _) in H; try solve_mesi\n\n      | [H: context[getDir ?cidx (setDirE ?cidx)] |- _] =>\n        rewrite getDir_setDirE_eq in H\n      | [Hn: ?oidx1 <> ?oidx2, H: context[getDir ?oidx1 (setDirE ?oidx2)] |- _] =>\n        rewrite getDir_setDirE_neq in H by auto\n      | [Hn: ?oidx2 <> ?oidx1, H: context[getDir ?oidx1 (setDirE ?oidx2)] |- _] =>\n        rewrite getDir_setDirE_neq in H by auto\n\n      | [H: context[getDir ?cidx (setDirM ?cidx)] |- _] =>\n        rewrite getDir_setDirM_eq in H\n      | [Hn: ?oidx1 <> ?oidx2, H: context[getDir ?oidx1 (setDirM ?oidx2)] |- _] =>\n        rewrite getDir_setDirM_neq in H by auto\n      | [Hn: ?oidx2 <> ?oidx1, H: context[getDir ?oidx1 (setDirM ?oidx2)] |- _] =>\n        rewrite getDir_setDirM_neq in H by auto\n      end;\n    try match goal with\n        | [H: mesiS <= getDir ?cidx ?dir |- _] =>\n          pose proof (getDir_st_sound dir cidx ltac:(solve_mesi))\n        | [H: mesiE <= getDir ?cidx ?dir |- _] =>\n          pose proof (getDir_st_sound dir cidx ltac:(solve_mesi))\n        end.\n\n  Ltac derive_child_st cidx :=\n    match goal with\n    | [Hosi: OstInds _ _ _,\n             Hoin: In ?oidx (tl (c_li_indices _)),\n                   Hp: parentIdxOf _ cidx = Some ?oidx |- _] =>\n      let Hin := fresh \"H\" in\n      pose proof (tree2Topo_li_child_li_l1 _ _ _ (tl_In _ _ Hoin) Hp) as Hin;\n      let Ho := fresh \"H\" in\n      pose proof (Hosi _ Hin) as Ho;\n      let cost := fresh \"cost\" in\n      let corq := fresh \"corq\" in\n      simpl in Ho; destruct Ho as [[cost ?] [corq ?]]\n    | [Hosi: OstInds _ _ _,\n             Hoin: In ?oidx (c_li_indices _),\n                   Hp: parentIdxOf _ cidx = Some ?oidx |- _] =>\n      let Hin := fresh \"H\" in\n      pose proof (tree2Topo_li_child_li_l1 _ _ _ Hoin Hp) as Hin;\n      let Ho := fresh \"H\" in\n      pose proof (Hosi _ Hin) as Ho;\n      let cost := fresh \"cost\" in\n      let corq := fresh \"corq\" in\n      simpl in Ho; destruct Ho as [[cost ?] [corq ?]]\n    end.\n\n  Ltac disc_InvDirInv cidx :=\n    match goal with\n    | [Hi: InvDirInv _ _ _ _ _ _,\n           Hoin: In ?oidx (tl (c_li_indices _)),\n                 Hp: parentIdxOf _ cidx = Some ?oidx |- _] =>\n      specialize (Hi (tl_In _ _ Hoin) _ Hp); dest\n    | [Hi: InvDirInv _ _ _ _ _ _,\n           Hoin: In ?oidx (c_li_indices _),\n                 Hp: parentIdxOf _ cidx = Some ?oidx |- _] =>\n      specialize (Hi Hoin _ Hp); dest\n    end.\n\n  Local Hint Extern 0 (NoDup (idsOf _)) =>\n  match goal with\n  | [H: ValidMsgsIn _ _ |- _] => apply H\n  end.\n\n  Lemma mesi_InvExcl_InvTrs_mem:\n    forall ist1,\n      Reachable (steps step_m) impl ist1 ->\n      forall inits,\n        SubList (idsOf inits) (sys_merqs impl) ->\n        forall ins hst outs eouts oidx ridx rins routs,\n          Atomic inits ins hst outs eouts ->\n          rins <> nil ->\n          SubList rins eouts ->\n          forall (Hrsd: forall (oidx : IdxT) (rsDown : Id Msg),\n                     In rsDown (removeL (id_dec msg_dec) eouts rins ++ routs) ->\n                     RsDownMsgTo topo oidx rsDown ->\n                     removeL (id_dec msg_dec) eouts rins ++ routs = [rsDown])\n                 st2 ist2,\n            InvExcl topo cifc st2 ->\n            AtomicInv InvExclMsgOutPred inits ist1 hst eouts st2 ->\n            steps step_m impl ist1 hst st2 ->\n            step_m impl st2 (RlblInt oidx ridx rins routs) ist2 ->\n            forall (Hr1: Reachable (steps step_m) impl st2)\n                   (Hr2: Reachable (steps step_m) impl ist2)\n                   (Hoin: rootOf (fst (tree2Topo tr 0)) = oidx),\n              AtomicInv InvExclMsgOutPred inits ist1 (RlblInt oidx ridx rins routs :: hst)\n                        (removeL (id_dec msg_dec) eouts rins ++ routs) ist2 /\\\n              InvExcl topo cifc ist2.\n  Proof. (* SKIP_PROOF_ON\n    intros.\n    pose proof (tree2Topo_TreeTopoNode tr 0) as Htn.\n    pose proof (footprints_ok\n                  (mesi_GoodORqsInit Htr)\n                  (mesi_GoodRqRsSys Htr) Hr1) as Hftinv.\n    pose proof (mesi_InObjInds Hr1) as Hioi1.\n    pose proof (mesi_InObjInds Hr2) as Hioi2.\n    pose proof (mesi_OstInds Hr1) as Hosi.\n    pose proof (mesi_MsgConflictsInv\n                  (@mesi_RootChnInv_ok _ Htr) Hr1) as Hpmcf.\n    pose proof (@MesiUpLockInv_ok _ Htr _ Hr1) as Hulinv.\n    pose proof (@MesiDownLockInv_ok _ Htr _ Hr1) as Hdlinv.\n    pose proof (@mesi_InvWBDir_ok _ Htr _ Hr1) as Hidir.\n    pose proof (@mesi_InvNWB_ok _ Htr _ Hr1) as Hnwb.\n    pose proof (@mesi_InvWB_ok _ Htr _ Hr1) as Hwb.\n\n    inv_step.\n\n    simpl in H12; destruct H12; [subst|apply in_app_or in H7; destruct H7].\n    2: {\n      exfalso.\n      apply in_map with (f:= obj_idx) in H7; rewrite <-H14 in H7.\n      rewrite map_map in H7; simpl in H7; rewrite map_id in H7.\n      eapply tree2Topo_root_not_in_tl_li; eauto.\n    }\n    2: {\n      exfalso.\n      apply in_map with (f:= obj_idx) in H7; rewrite <-H14 in H7.\n      rewrite map_map in H7; simpl in H7; rewrite map_id in H7.\n      eapply tree2Topo_root_not_in_l1; eauto.\n    }\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    clear H14.\n\n    (** Do case analysis per a rule. *)\n    apply concat_In in H13; destruct H13 as [crls [? ?]].\n    apply in_map_iff in H7; destruct H7 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    derive_child_chns cidx.\n\n    dest_in.\n\n    { (* [liGetSImmME] *)\n      disc_rule_conds_ex.\n      derive_NoRsI_by_no_uplock oidx msgs.\n\n      split.\n      { solve_AtomicInv_rqUp.\n        disc_InvExcl oidx.\n        assert (ObjExcl0 oidx os msgs)\n          by (split; [simpl; solve_mesi|assumption]).\n        specialize (H1 H20); dest.\n        solve_msg_pred_base.\n        solve_ObjsInvalid_trivial.\n        eapply ObjsInvalid_rsE_generated with (oidx:= oidx); eauto.\n      }\n\n      { case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { solve_InvObjExcl0_by_ObjExcl0_false. }\n          { case_InvObjOwned.\n            { solve_by_topo_false. }\n            { disc_ObjsInvalid_by oidx0.\n              case_ObjInvalid_with cidx; [solve_by_topo_false|].\n              case_ObjInvalid; [solve_ObjInvalid0|].\n              solve_ObjInvRs.\n            }\n            { solve_MsgsP. }\n          }\n          { split_InvDirInv.\n            { assert (ObjExcl0 oidx os msgs)\n                by (split; [simpl; solve_mesi|assumption]).\n              specialize (H4 H32); dest.\n              simpl in H31; case_idx_eq cidx0 cidx; [disc_dir; discriminate|].\n              solve_ObjsInvalid_trivial.\n              eapply ObjsInvalid_impl; [eassumption|].\n              simpl; intros; intro; subst; solve_by_topo_false.\n            }\n            { simpl in H31; case_idx_eq cidx0 cidx; [|disc_dir; solve_mesi].\n              assert (ObjExcl0 oidx os msgs)\n                by (split; [simpl; solve_mesi|assumption]).\n              specialize (H4 H32); dest.\n              solve_ObjsInvalid_trivial.\n              apply ObjsInvalid_rsM_generated; auto; discriminate.\n            }\n          }\n        }\n\n        { disc_InvExcl_others.\n          { disc_InvObjExcl0_apply.\n            solve_by_ObjsInvalid_status_false oidx.\n          }\n          { case_InvObjOwned.\n            { solve_by_ObjsInvalid_status_false oidx. }\n            { derive_not_InvalidObj_not_in oidx.\n              disc_ObjsInvalid_by oidx0.\n              case_ObjInvalid_with cidx; [solve_by_topo_false|].\n              case_ObjInvalid; [solve_ObjInvalid0|].\n              solve_ObjInvRs.\n            }\n            { case_idx_eq eidx cidx.\n              { apply parent_not_in_subtree in H7; auto.\n                solve_by_ObjsInvalid_status_false oidx.\n              }\n              { solve_MsgsP. }\n            }\n          }\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx0.\n              { solve_by_ObjsInvalid_status_false oidx. }\n              { solve_ObjsInvalid_trivial. }\n            }\n            { case_in_subtree oidx cidx0.\n              { solve_ObjsInvalid_trivial. }\n              { solve_by_ObjsInvalid_status_false oidx. }\n            }\n          }\n        }\n      }\n    }\n\n    { (* [liGetMImm] *)\n      disc_rule_conds_ex.\n      derive_NoRsI_by_no_uplock oidx msgs.\n\n      rename H23 into Hprec. (* the precondition about status and ownership bit *)\n      assert (ObjsInvalid\n                (fun idx => ~ In idx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx))\n                (oss +[oidx <- (fst os, (false, (mesiI, (setDirM cidx, snd (snd (snd (snd os)))))))])\n                msgs) as Hoi.\n      { destruct Hprec; dest.\n        { disc_InvExcl oidx.\n          assert (ObjExcl0 oidx os msgs)\n            by (split; [simpl; solve_mesi|assumption]).\n          specialize (H4 H27); dest.\n          apply ObjsInvalid_rsM_generated; auto; discriminate.\n        }\n        { disc_InvExcl oidx.\n          eapply ObjsInvalid_out_composed; eauto.\n          { solve_ObjsInvalid_trivial.\n            apply H28; red; auto.\n          }\n          { mred. }\n          { left; repeat split; [simpl; solve_mesi|discriminate|apply H28; red; auto]. }\n          { intros.\n            solve_ObjsInvalid_trivial.\n            disc_InvDirInv rcidx.\n            apply H29.\n            eapply getDir_LastSharer_neq; try eassumption.\n            eapply getDir_LastSharer_eq; eassumption.\n          }\n        }\n      }\n\n      split.\n      { solve_AtomicInv_rqUp.\n        disc_InvExcl oidx.\n        solve_msg_pred_base.\n        solve_ObjsInvalid_trivial.\n      }\n\n      { case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { solve_InvObjExcl0_by_ObjExcl0_false. }\n          { solve_InvObjOwned_by_false. }\n          { split_InvDirInv.\n            { simpl in H29; case_idx_eq cidx0 cidx; [disc_dir; discriminate|].\n              solve_ObjsInvalid_trivial.\n              destruct Hprec; dest.\n              { assert (ObjExcl0 oidx os msgs)\n                  by (split; [simpl; solve_mesi|assumption]).\n                specialize (H4 H31); dest.\n                eapply ObjsInvalid_impl; [apply H4|].\n                simpl; intros; intro; subst; solve_by_topo_false.\n              }\n              { apply H20.\n                eapply getDir_LastSharer_neq; try eassumption.\n                eapply getDir_LastSharer_eq; eassumption.\n              }\n            }\n            { simpl in H29; case_idx_eq cidx0 cidx; [|disc_dir; solve_mesi].\n              solve_ObjsInvalid_trivial.\n            }\n          }\n        }\n\n        { clear Hoi.\n          disc_InvExcl_others.\n          { disc_InvObjExcl0_apply.\n            destruct Hprec; dest; solve_by_ObjsInvalid_status_false oidx.\n          }\n          { case_InvObjOwned.\n            { destruct Hprec; dest; solve_by_ObjsInvalid_status_false oidx. }\n            { destruct Hprec; dest.\n              all: derive_not_InvalidObj_not_in oidx;\n                disc_ObjsInvalid_by oidx0;\n                case_ObjInvalid_with cidx; [solve_by_topo_false|];\n                  case_ObjInvalid; [solve_ObjInvalid0|];\n                    solve_ObjInvRs.\n            }\n            { case_idx_eq eidx cidx.\n              { apply parent_not_in_subtree in H7; auto.\n                destruct Hprec; dest; solve_by_ObjsInvalid_status_false oidx.\n              }\n              { solve_MsgsP. }\n            }\n          }\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx0.\n              { destruct Hprec; dest; solve_by_ObjsInvalid_status_false oidx. }\n              { solve_ObjsInvalid_trivial. }\n            }\n            { case_in_subtree oidx cidx0.\n              { destruct Hprec; dest; solve_ObjsInvalid_trivial. }\n              { solve_by_ObjsInvalid_status_false oidx. }\n            }\n          }\n        }\n      }\n    }\n\n    { (* [liInvImmE] *)\n      disc_rule_conds_ex.\n      derive_child_st cidx.\n      derive_NoRsI_by_rqUp cidx msgs.\n      rename H20 into Hrsi.\n\n      assert (ObjsInvalid\n                (fun idx => In idx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx))\n                (oss +[oidx <- (fst os, (fst (snd os), (mesiE, (setDirI, snd (snd (snd (snd os)))))))])\n                (enqMP (downTo cidx) {| msg_id := mesiInvRs;\n                                        msg_type := MRs;\n                                        msg_addr := msg_addr rmsg;\n                                        msg_value := 0 |}\n                       (deqMP (rqUpFrom cidx) msgs))) as Hci.\n      { intros; disc_AtomicMsgOutsInv cidx.\n        disc_MsgPred.\n        eapply InvExcl_inv_ObjsInvalid; eauto.\n      }\n\n      assert (ObjsInvalid\n                (fun idx => ~ In idx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx))\n                oss msgs) as Hcci.\n      { disc_InvExcl oidx.\n        disc_InvDirInv cidx.\n        apply H29.\n        simpl; solve_mesi.\n      }\n\n      assert (ObjsInvalid\n                (fun idx => oidx <> idx)\n                (oss +[oidx <- (fst os, (fst (snd os), (mesiE, (setDirI, snd (snd (snd (snd os)))))))])\n                (enqMP (downTo cidx) {| msg_id := mesiInvRs;\n                                        msg_type := MRs;\n                                        msg_addr := msg_addr rmsg;\n                                        msg_value := 0 |}\n                       (deqMP (rqUpFrom cidx) msgs))) as Hoi.\n      { intros; eapply ObjsInvalid_invRs_composed.\n        { solve_ObjsInvalid_trivial.\n          eapply ObjsInvalid_impl; [apply Hcci|].\n          simpl; intros.\n          intro Hx; elim H20.\n          eapply subtreeIndsOf_child_SubList; eauto.\n        }\n        { apply ObjsInvalid_child_forall; intros rcidx ?.\n          case_idx_eq rcidx cidx; [assumption|].\n          solve_ObjsInvalid_trivial.\n          disc_InvExcl oidx.\n          disc_InvDirInv rcidx.\n          apply H29.\n          apply getDir_E_imp in H23; dest; subst.\n          eapply getDir_excl_neq; eauto.\n          simpl; solve_mesi.\n        }\n      }\n\n      split; [solve_AtomicInv_rqUp|].\n      case_InvExcl_me_others.\n      { disc_InvExcl_this.\n        { disc_InvObjExcl0; split; [apply Hoi|].\n          disc_MsgConflictsInv oidx.\n          solve_MsgsP.\n          eapply ObjInvalid_NoCohMsgs; eauto.\n          eapply ObjsInvalid_ObjInvalid; try exact Hcci; eauto.\n          simpl; intro; solve_by_topo_false.\n        }\n        { disc_InvObjOwned; dest.\n          split; [solve_ObjsInvalid_trivial|solve_MsgsP].\n        }\n        { split_InvDirInv; [|exfalso; rewrite getDir_setDirI in H32; solve_mesi].\n          case_idx_eq cidx0 cidx.\n          { apply Hci. }\n          { solve_ObjsInvalid_trivial.\n            apply H28.\n            apply getDir_E_imp in H23; dest; subst.\n            eapply getDir_excl_neq;\n              [reflexivity|simpl; solve_mesi|assumption].\n          }\n        }\n      }\n\n      { assert (mesiS <= cost#[status]).\n        { (** TODO: bring [disc_InvNWB] to here? *)\n          move Hnwb at bottom.\n          specialize (Hnwb _ _ H7); simpl in Hnwb.\n          disc_rule_conds_ex.\n          apply Hnwb.\n          { apply getDir_E_imp in H23; dest.\n            repeat split; try assumption.\n          }\n          { eexists (_, _); split; [apply FirstMP_InMP; eassumption|].\n            unfold sigOf; simpl; congruence.\n          }\n        }\n\n        disc_InvExcl_others.\n        { case_idx_eq eidx cidx.\n          { red; intros [? ?]; exfalso.\n            apply NoRsI_MsgExistsSig_InvRs_false in H32; auto.\n            eexists (_, _); split.\n            { apply InMP_or_enqMP; left; simpl; auto. }\n            { reflexivity. }\n          }\n          { disc_InvObjExcl0.\n            destruct H31.\n            clear Hci Hcci.\n            exfalso; eapply ObjsInvalid_obj_status_false with (oidx := eidx);\n              eauto; simpl in *; auto.\n            { solve_MsgsP. }\n            { mred. }\n            { solve_mesi. }\n          }\n        }\n\n        { case_in_subtree oidx eidx.\n          { disc_InvObjOwned.\n            split; [solve_ObjsInvalid_trivial|solve_MsgsP].\n          }\n          { case_in_subtree cidx eidx.\n            { eapply inside_child_outside_parent_case in i; eauto; subst.\n              red; intros [? ?]; exfalso.\n              apply NoRsI_MsgExistsSig_InvRs_false in H32; auto.\n              eexists (_, _); split.\n              { apply InMP_or_enqMP; left; simpl; auto. }\n              { reflexivity. }\n            }\n            { disc_InvObjOwned.\n              clear Hci Hcci Hoi; solve_by_ObjsInvalid_status_false cidx.\n            }\n          }\n        }\n\n        { split_InvDirInv_apply.\n          { case_in_subtree oidx cidx0.\n            { clear Hci Hcci Hoi.\n              eapply inside_child_in in i; eauto.\n              solve_by_ObjsInvalid_status_false cidx.\n            }\n            { solve_ObjsInvalid_trivial. }\n          }\n          { case_in_subtree oidx cidx0.\n            { solve_ObjsInvalid_trivial. }\n            { eapply outside_child_in in n0; eauto.\n              destruct n0; subst; [disc_rule_conds_ex|].\n              clear Hci Hcci Hoi.\n              solve_by_ObjsInvalid_status_false cidx.\n            }\n          }\n        }\n      }\n    }\n\n    { (* [liInvImmWBME] *)\n      disc_rule_conds_ex.\n      derive_child_st cidx.\n      derive_NoRsI_by_rqUp cidx msgs.\n      rename H20 into Hrsi.\n\n      assert (ObjsInvalid\n                (fun idx => In idx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx))\n                (oss +[oidx <- (msg_value rmsg, (true, (mesiM, (setDirI, snd (snd (snd (snd os)))))))])\n                (enqMP (downTo cidx) {| msg_id := mesiInvRs;\n                                        msg_type := MRs;\n                                        msg_addr := msg_addr rmsg;\n                                        msg_value := 0 |}\n                       (deqMP (rqUpFrom cidx) msgs))) as Hci.\n      { intros; disc_AtomicMsgOutsInv cidx.\n        disc_MsgPred.\n        eapply InvExcl_inv_ObjsInvalid; eauto.\n      }\n\n      assert (ObjsInvalid\n                (fun idx => ~ In idx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx))\n                oss msgs) as Hcci.\n      { disc_InvExcl oidx.\n        disc_InvDirInv cidx.\n        apply H29.\n        simpl; solve_mesi.\n      }\n\n      assert (ObjsInvalid\n                (fun idx => oidx <> idx)\n                (oss +[oidx <- (msg_value rmsg, (true, (mesiM, (setDirI, snd (snd (snd (snd os)))))))])\n                (enqMP (downTo cidx) {| msg_id := mesiInvRs;\n                                        msg_type := MRs;\n                                        msg_addr := msg_addr rmsg;\n                                        msg_value := 0 |}\n                       (deqMP (rqUpFrom cidx) msgs))) as Hoi.\n      { intros; eapply ObjsInvalid_invRs_composed.\n        { solve_ObjsInvalid_trivial.\n          eapply ObjsInvalid_impl; [apply Hcci|].\n          simpl; intros.\n          intro Hx; elim H20.\n          eapply subtreeIndsOf_child_SubList; eauto.\n        }\n        { apply ObjsInvalid_child_forall; intros rcidx ?.\n          case_idx_eq rcidx cidx; [assumption|].\n          solve_ObjsInvalid_trivial.\n          disc_InvExcl oidx.\n          disc_InvDirInv rcidx.\n          apply H29.\n          apply getDir_ME_imp in H23; dest; subst.\n          eapply getDir_excl_neq; eauto.\n        }\n      }\n\n      split; [solve_AtomicInv_rqUp|].\n      case_InvExcl_me_others.\n      { disc_InvExcl_this.\n        { disc_InvObjExcl0; split; [apply Hoi|].\n          disc_MsgConflictsInv oidx.\n          solve_MsgsP.\n          eapply ObjInvalid_NoCohMsgs; eauto.\n          eapply ObjsInvalid_ObjInvalid; try exact Hcci; eauto.\n          simpl; intro; solve_by_topo_false.\n        }\n        { disc_InvDirInv cidx.\n          specialize (H29 H23).\n          disc_InvObjOwned; split.\n          { solve_ObjsInvalid_trivial.\n            eapply ObjsInvalid_impl; [apply H29|].\n            simpl; intros.\n            intro Hx; elim H32.\n            eapply subtreeIndsOf_child_SubList with (cidx:= cidx); eauto.\n          }\n          { disc_MsgConflictsInv oidx.\n            apply parent_not_in_subtree in H7; auto.\n            specialize (H29 _ H7); rewrite H15 in H29; simpl in H29.\n            solve_MsgsP.\n            eapply ObjInvalid_NoCohMsgs; eauto.\n          }\n        }\n        { split_InvDirInv; [|exfalso; rewrite getDir_setDirI in H32; solve_mesi].\n          case_idx_eq cidx0 cidx.\n          { apply Hci. }\n          { solve_ObjsInvalid_trivial.\n            apply H28.\n            apply getDir_ME_imp in H23; dest; subst.\n            eapply getDir_excl_neq;\n              [reflexivity|simpl; solve_mesi|assumption].\n          }\n        }\n      }\n\n      { assert (mesiS <= cost#[status]).\n        { (** TODO: bring [disc_InvWB] to here? *)\n          move Hwb at bottom.\n          specialize (Hwb _ _ H7); simpl in Hnwb.\n          disc_rule_conds_ex.\n          apply Hwb.\n          { apply getDir_ME_imp in H23; dest.\n            repeat split; try assumption.\n          }\n          { eexists (_, _); split; [apply FirstMP_InMP; eassumption|].\n            unfold sigOf; simpl; congruence.\n          }\n        }\n\n        disc_InvExcl_others.\n        { case_idx_eq eidx cidx.\n          { red; intros [? ?]; exfalso.\n            apply NoRsI_MsgExistsSig_InvRs_false in H32; auto.\n            eexists (_, _); split.\n            { apply InMP_or_enqMP; left; simpl; auto. }\n            { reflexivity. }\n          }\n          { disc_InvObjExcl0.\n            destruct H31.\n            clear Hci Hcci.\n            exfalso; eapply ObjsInvalid_obj_status_false with (oidx := eidx);\n              eauto; simpl in *; auto.\n            { solve_MsgsP. }\n            { mred. }\n            { solve_mesi. }\n          }\n        }\n\n        { case_in_subtree oidx eidx.\n          { disc_InvObjOwned.\n            split; [solve_ObjsInvalid_trivial|solve_MsgsP].\n          }\n          { case_in_subtree cidx eidx.\n            { eapply inside_child_outside_parent_case in i; eauto; subst.\n              red; intros [? ?]; exfalso.\n              apply NoRsI_MsgExistsSig_InvRs_false in H32; auto.\n              eexists (_, _); split.\n              { apply InMP_or_enqMP; left; simpl; auto. }\n              { reflexivity. }\n            }\n            { disc_InvObjOwned.\n              clear Hci Hcci Hoi; solve_by_ObjsInvalid_status_false cidx.\n            }\n          }\n        }\n\n        { split_InvDirInv_apply.\n          { case_in_subtree oidx cidx0.\n            { clear Hci Hcci Hoi.\n              eapply inside_child_in in i; eauto.\n              solve_by_ObjsInvalid_status_false cidx.\n            }\n            { solve_ObjsInvalid_trivial. }\n          }\n          { case_in_subtree oidx cidx0.\n            { solve_ObjsInvalid_trivial. }\n            { eapply outside_child_in in n0; eauto.\n              destruct n0; subst; [disc_rule_conds_ex|].\n              clear Hci Hcci Hoi.\n              solve_by_ObjsInvalid_status_false cidx.\n            }\n          }\n        }\n      }\n    }\n\n    END_SKIP_PROOF_ON *) admit.\n  Qed.\n\n  Lemma mesi_InvExcl_InvTrs_li:\n    forall ist1,\n      Reachable (steps step_m) impl ist1 ->\n      forall inits,\n        SubList (idsOf inits) (sys_merqs impl) ->\n        forall ins hst outs eouts oidx ridx rins routs,\n          Atomic inits ins hst outs eouts ->\n          rins <> nil ->\n          SubList rins eouts ->\n          forall (Hrsd: forall (oidx : IdxT) (rsDown : Id Msg),\n                     In rsDown (removeL (id_dec msg_dec) eouts rins ++ routs) ->\n                     RsDownMsgTo topo oidx rsDown ->\n                     removeL (id_dec msg_dec) eouts rins ++ routs = [rsDown])\n                 st2 ist2,\n            InvExcl topo cifc st2 ->\n            AtomicInv InvExclMsgOutPred inits ist1 hst eouts st2 ->\n            steps step_m impl ist1 hst st2 ->\n            step_m impl st2 (RlblInt oidx ridx rins routs) ist2 ->\n            forall (Hr1: Reachable (steps step_m) impl st2)\n                   (Hr2: Reachable (steps step_m) impl ist2)\n                   (Hoin: In oidx (map obj_idx (map (li tr) (tl (c_li_indices (snd (tree2Topo tr 0))))))),\n              AtomicInv InvExclMsgOutPred inits ist1 (RlblInt oidx ridx rins routs :: hst)\n                        (removeL (id_dec msg_dec) eouts rins ++ routs) ist2 /\\\n              InvExcl topo cifc ist2.\n  Proof. (* SKIP_PROOF_ON\n    intros.\n    pose proof (tree2Topo_TreeTopoNode tr 0) as Htn.\n    pose proof (footprints_ok\n                  (mesi_GoodORqsInit Htr)\n                  (mesi_GoodRqRsSys Htr) Hr1) as Hftinv.\n    pose proof (mesi_InObjInds Hr1) as Hioi1.\n    pose proof (mesi_InObjInds Hr2) as Hioi2.\n    pose proof (mesi_OstInds Hr1) as Hosi.\n    pose proof (mesi_MsgConflictsInv\n                  (@mesi_RootChnInv_ok _ Htr) Hr1) as Hpmcf.\n    pose proof (mesi_MsgConflictsInv\n                  (@mesi_RootChnInv_ok _ Htr) Hr2) as Hnmcf.\n    phide Hnmcf; rename H8 into Hnmcf.\n    pose proof (@MesiUpLockInv_ok _ Htr _ Hr1) as Hulinv.\n    pose proof (@MesiDownLockInv_ok _ Htr _ Hr1) as Hdlinv.\n    pose proof (@mesi_InvWBDir_ok _ Htr _ Hr1) as Hidir.\n    pose proof (@mesi_InvNWB_ok _ Htr _ Hr1) as Hnwb.\n    pose proof (@mesi_InvWB_ok _ Htr _ Hr1) as Hwb.\n\n    inv_step.\n\n    simpl in H12; destruct H12; [subst|apply in_app_or in H7; destruct H7].\n    1: {\n      exfalso; simpl in Hoin.\n      rewrite map_map in Hoin; simpl in Hoin; rewrite map_id in Hoin.\n      eapply tree2Topo_root_not_in_tl_li; eauto.\n    }\n    2: {\n      exfalso; simpl in Hoin.\n      apply in_map_iff in H7; destruct H7 as [oidx [? ?]]; subst.\n      rewrite map_map in Hoin; simpl in Hoin; rewrite map_id in Hoin.\n      pose proof (tree2Topo_WfCIfc tr 0) as [? _].\n      apply (DisjList_NoDup idx_dec) in H7.\n      eapply DisjList_In_1; eauto.\n      apply tl_In; assumption.\n    }\n\n    (*! Cases for Li caches *)\n    pose proof H7 as Hobj.\n    apply in_map_iff in H7; destruct H7 as [oidx [? ?]]; subst; simpl in *.\n\n    pose proof (c_li_indices_tail_has_parent Htr _ _ H8).\n    destruct H7 as [pidx [? ?]].\n    pose proof (Htn _ _ H9); dest.\n\n    (** Do case analysis per a rule. *)\n    apply in_app_or in H13; destruct H13.\n\n    1: { (** Rules per a child *)\n      apply concat_In in H13; destruct H13 as [crls [? ?]].\n      apply in_map_iff in H13; destruct H13 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      derive_child_chns cidx.\n\n      dest_in.\n\n      { (* [liGetSImmS] *)\n        disc_rule_conds_ex.\n        derive_NoRsI_by_no_uplock oidx msgs.\n\n        split; [solve_AtomicInv_rqUp|].\n        case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { solve_InvObjExcl0_by_ObjExcl0_false. }\n          { case_InvObjOwned.\n            { solve_by_topo_false. }\n            { disc_ObjsInvalid_by oidx0.\n              case_ObjInvalid_with cidx; [solve_by_topo_false|].\n              case_ObjInvalid; [solve_ObjInvalid0|].\n              solve_ObjInvRs.\n            }\n            { solve_MsgsP. }\n          }\n          { split_InvDirInv.\n            { simpl in H37; rewrite getDir_addSharer_spec in H37 by solve_mesi.\n              find_if_inside; subst; [discriminate|].\n              specialize (H27 H37).\n              solve_ObjsInvalid_trivial.\n            }\n            { simpl in H37; rewrite getDir_addSharer_spec in H37 by solve_mesi.\n              find_if_inside; subst; [solve_mesi|].\n              pose proof (getDir_st_sound (fst (snd (snd (snd os)))) cidx0 ltac:(solve_mesi)).\n              solve_mesi.\n            }\n          }\n        }\n\n        { disc_InvExcl_others.\n          { disc_InvObjExcl0_apply.\n            solve_by_ObjsInvalid_status_false oidx.\n          }\n          { case_InvObjOwned.\n            { solve_by_ObjsInvalid_status_false oidx. }\n            { derive_not_InvalidObj_not_in oidx.\n              disc_ObjsInvalid_by oidx0.\n              case_ObjInvalid_with cidx; [solve_by_topo_false|].\n              case_ObjInvalid; [solve_ObjInvalid0|].\n              solve_ObjInvRs.\n            }\n            { case_idx_eq eidx cidx.\n              { apply parent_not_in_subtree in H13; auto.\n                solve_by_ObjsInvalid_status_false oidx.\n              }\n              { solve_MsgsP. }\n            }\n          }\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx0.\n              { solve_by_ObjsInvalid_status_false oidx. }\n              { solve_ObjsInvalid_trivial. }\n            }\n            { case_in_subtree oidx cidx0.\n              { solve_ObjsInvalid_trivial. }\n              { solve_by_ObjsInvalid_status_false oidx. }\n            }\n          }\n        }\n      }\n\n      { (* [liGetSImmME] *)\n        disc_rule_conds_ex.\n        derive_NoRsI_by_no_uplock oidx msgs.\n\n        split.\n        { solve_AtomicInv_rqUp.\n          disc_InvExcl oidx.\n          assert (ObjExcl0 oidx os msgs)\n            by (split; [simpl; solve_mesi|assumption]).\n          specialize (H1 H27); dest.\n          solve_msg_pred_base.\n          solve_ObjsInvalid_trivial.\n          eapply ObjsInvalid_rsE_generated with (oidx:= oidx); eauto.\n        }\n\n        { case_InvExcl_me_others.\n          { disc_InvExcl_this.\n            { solve_InvObjExcl0_by_ObjExcl0_false. }\n            { case_InvObjOwned.\n              { solve_by_topo_false. }\n              { disc_ObjsInvalid_by oidx0.\n                case_ObjInvalid_with cidx; [solve_by_topo_false|].\n                case_ObjInvalid; [solve_ObjInvalid0|].\n                solve_ObjInvRs.\n              }\n              { solve_MsgsP. }\n            }\n            { split_InvDirInv.\n              { assert (ObjExcl0 oidx os msgs)\n                  by (split; [simpl; solve_mesi|assumption]).\n                specialize (H4 H38); dest.\n                simpl in H37; case_idx_eq cidx0 cidx; [disc_dir; discriminate|].\n                solve_ObjsInvalid_trivial.\n                eapply ObjsInvalid_impl; [eassumption|].\n                simpl; intros; intro; subst; solve_by_topo_false.\n              }\n              { simpl in H37; case_idx_eq cidx0 cidx; [|disc_dir; solve_mesi].\n                assert (ObjExcl0 oidx os msgs)\n                  by (split; [simpl; solve_mesi|assumption]).\n                specialize (H4 H38); dest.\n                solve_ObjsInvalid_trivial.\n                apply ObjsInvalid_rsM_generated; auto; discriminate.\n              }\n            }\n          }\n\n          { disc_InvExcl_others.\n            { disc_InvObjExcl0_apply.\n              solve_by_ObjsInvalid_status_false oidx.\n            }\n            { case_InvObjOwned.\n              { solve_by_ObjsInvalid_status_false oidx. }\n              { derive_not_InvalidObj_not_in oidx.\n                disc_ObjsInvalid_by oidx0.\n                case_ObjInvalid_with cidx; [solve_by_topo_false|].\n                case_ObjInvalid; [solve_ObjInvalid0|].\n                solve_ObjInvRs.\n              }\n              { case_idx_eq eidx cidx.\n                { apply parent_not_in_subtree in H13; auto.\n                  solve_by_ObjsInvalid_status_false oidx.\n                }\n                { solve_MsgsP. }\n              }\n            }\n            { split_InvDirInv_apply.\n              { case_in_subtree oidx cidx0.\n                { solve_by_ObjsInvalid_status_false oidx. }\n                { solve_ObjsInvalid_trivial. }\n              }\n              { case_in_subtree oidx cidx0.\n                { solve_ObjsInvalid_trivial. }\n                { solve_by_ObjsInvalid_status_false oidx. }\n              }\n            }\n          }\n        }\n      }\n\n      { (* [liGetSRqUpUp] *)\n        disc_rule_conds_ex; split.\n        { solve_AtomicInv_rqUp.\n          all: try (red; simpl; intros; rewrite H19 in H20; discriminate).\n        }\n        { solve_InvExcl_trivial. }\n      }\n\n      { (* [liGetSRqUpDownME] *)\n        disc_rule_conds_ex; split.\n        { solve_AtomicInv_rqUp. }\n        { solve_InvExcl_trivial. }\n      }\n\n      { (* [liGetMImm] *)\n        disc_rule_conds_ex.\n        derive_NoRsI_by_no_uplock oidx msgs.\n\n        rename H30 into Hprec. (* the precondition about status and ownership bit *)\n        assert (ObjsInvalid\n                  (fun idx => ~ In idx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx))\n                  (oss +[oidx <- (fst os, (false, (mesiI, (setDirM cidx, snd (snd (snd (snd os)))))))])\n                  msgs) as Hoi.\n        { destruct Hprec; dest.\n          { disc_InvExcl oidx.\n            assert (ObjExcl0 oidx os msgs)\n              by (split; [simpl; solve_mesi|assumption]).\n            specialize (H4 H33); dest.\n            apply ObjsInvalid_rsM_generated; auto; discriminate.\n          }\n          { disc_InvExcl oidx.\n            eapply ObjsInvalid_out_composed; eauto.\n            { solve_ObjsInvalid_trivial.\n              apply H34; red; auto.\n            }\n            { mred. }\n            { left; repeat split; [simpl; solve_mesi|discriminate|apply H34; red; auto]. }\n            { intros.\n              solve_ObjsInvalid_trivial.\n              disc_InvDirInv rcidx.\n              apply H35.\n              eapply getDir_LastSharer_neq; try eassumption.\n              eapply getDir_LastSharer_eq; eassumption.\n            }\n          }\n        }\n\n        split.\n        { solve_AtomicInv_rqUp.\n          disc_InvExcl oidx.\n          solve_msg_pred_base.\n          solve_ObjsInvalid_trivial.\n        }\n\n        { case_InvExcl_me_others.\n          { disc_InvExcl_this.\n            { solve_InvObjExcl0_by_ObjExcl0_false. }\n            { solve_InvObjOwned_by_false. }\n            { split_InvDirInv.\n              { simpl in H35;case_idx_eq cidx0 cidx; [disc_dir; discriminate|].\n                solve_ObjsInvalid_trivial.\n                destruct Hprec; dest.\n                { assert (ObjExcl0 oidx os msgs)\n                    by (split; [simpl; solve_mesi|assumption]).\n                  specialize (H4 H37); dest.\n                  eapply ObjsInvalid_impl; [apply H4|].\n                  simpl; intros; intro; subst; solve_by_topo_false.\n                }\n                { apply H27.\n                  eapply getDir_LastSharer_neq; try eassumption.\n                  eapply getDir_LastSharer_eq; eassumption.\n                }\n              }\n              { simpl in H35; case_idx_eq cidx0 cidx; [|disc_dir; solve_mesi].\n                solve_ObjsInvalid_trivial.\n              }\n            }\n          }\n\n          { clear Hoi.\n            disc_InvExcl_others.\n            { disc_InvObjExcl0_apply.\n              destruct Hprec; dest; solve_by_ObjsInvalid_status_false oidx.\n            }\n            { case_InvObjOwned.\n              { destruct Hprec; dest; solve_by_ObjsInvalid_status_false oidx. }\n              { destruct Hprec; dest.\n                all: derive_not_InvalidObj_not_in oidx;\n                  disc_ObjsInvalid_by oidx0;\n                  case_ObjInvalid_with cidx; [solve_by_topo_false|];\n                    case_ObjInvalid; [solve_ObjInvalid0|];\n                      solve_ObjInvRs.\n              }\n              { case_idx_eq eidx cidx.\n                { apply parent_not_in_subtree in H13; auto.\n                  destruct Hprec; dest; solve_by_ObjsInvalid_status_false oidx.\n                }\n                { solve_MsgsP. }\n              }\n            }\n            { split_InvDirInv_apply.\n              { case_in_subtree oidx cidx0.\n                { destruct Hprec; dest; solve_by_ObjsInvalid_status_false oidx. }\n                { solve_ObjsInvalid_trivial. }\n              }\n              { case_in_subtree oidx cidx0.\n                { destruct Hprec; dest; solve_ObjsInvalid_trivial. }\n                { solve_by_ObjsInvalid_status_false oidx. }\n              }\n            }\n          }\n        }\n      }\n\n      { (* [liGetMRqUpUp] *)\n        disc_rule_conds_ex; split.\n        { solve_AtomicInv_rqUp.\n          all: try (red; simpl; intros; rewrite H19 in H20; discriminate).\n        }\n        { solve_InvExcl_trivial. }\n      }\n\n      { (* [liGetMRqUpDownME] *)\n        disc_rule_conds_ex; split.\n        { solve_AtomicInv_rqUp. }\n        { solve_InvExcl_trivial. }\n      }\n\n      { (* [liGetMRqUpDownS] *)\n        disc_rule_conds_ex; split.\n        { solve_AtomicInv_rqUp.\n          apply Forall_forall; intros.\n          apply in_map_iff in H1; destruct H1 as [midx [? ?]]; subst.\n          repeat constructor; try (red; simpl; intros; intuition discriminate).\n        }\n        { solve_InvExcl_trivial. }\n      }\n\n      { (* [liInvImmI] *)\n        disc_rule_conds_ex; split.\n        { solve_AtomicInv_rqUp. }\n        { solve_InvExcl_trivial. }\n      }\n\n      { (* [liInvImmS00] *)\n        disc_rule_conds_ex.\n        derive_child_st cidx.\n        split; [solve_AtomicInv_rqUp|].\n        pose proof H4 as Hi; phide Hi; rename H35 into Hi.\n\n        case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { disc_InvObjExcl0_apply.\n            split; [solve_ObjsInvalid_trivial|solve_MsgsP].\n          }\n          { disc_InvObjOwned.\n            split; [solve_ObjsInvalid_trivial|solve_MsgsP].\n          }\n          { split_InvDirInv; [|exfalso; rewrite getDir_setDirI in H40; solve_mesi].\n            case_idx_eq cidx0 cidx.\n            { disc_AtomicMsgOutsInv cidx.\n              disc_MsgPred.\n              eapply InvExcl_inv_ObjsInvalid; eauto.\n              preveal Hi; assumption.\n            }\n            { solve_ObjsInvalid_trivial.\n              apply H36.\n              eapply getDir_LastSharer_neq; eauto.\n            }\n          }\n        }\n\n        { disc_InvExcl_others.\n          { disc_InvObjExcl0_apply.\n            split; [|solve_MsgsP].\n            eapply ObjsInvalid_state_transition_sound; eauto; [|simpl; solve_mesi].\n            solve_ObjsInvalid_trivial.\n          }\n          { disc_InvObjOwned.\n            split; [|solve_MsgsP].\n            eapply ObjsInvalid_state_transition_sound; eauto; [|simpl; solve_mesi].\n            solve_ObjsInvalid_trivial.\n          }\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx0.\n              { eapply ObjsInvalid_state_transition_sound; eauto; [|simpl; solve_mesi].\n                solve_ObjsInvalid_trivial.\n              }\n              { solve_ObjsInvalid_trivial. }\n            }\n            { case_in_subtree oidx cidx0.\n              { solve_ObjsInvalid_trivial. }\n              { eapply ObjsInvalid_state_transition_sound; eauto; [|simpl; solve_mesi].\n                solve_ObjsInvalid_trivial.\n              }\n            }\n          }\n        }\n      }\n\n      { (* [liInvImmS01] *)\n        disc_rule_conds_ex.\n        derive_child_st cidx.\n        derive_NoRsI_by_rqUp cidx msgs.\n        rename H36 into Hcrsi.\n\n        (** 1) The requestor subtree satisfies [ObjsInvalid] *)\n        assert (ObjsInvalid\n                  (fun idx => In idx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx))\n                  (oss +[oidx <- (fst os, (fst (snd os), (mesiM, (setDirI, snd (snd (snd (snd os)))))))])\n                  (enqMP (downTo cidx) {| msg_id := mesiInvRs;\n                                          msg_type := MRs;\n                                          msg_addr := msg_addr rmsg;\n                                          msg_value := 0 |}\n                         (deqMP (rqUpFrom cidx) msgs))) as Hci.\n        { intros; disc_AtomicMsgOutsInv cidx.\n          disc_MsgPred.\n          eapply InvExcl_inv_ObjsInvalid; eauto.\n        }\n\n        (** 2-1) Each child (except the requestor) has the directory status I *)\n        assert (forall rcidx,\n                   parentIdxOf (fst (tree2Topo tr 0)) rcidx = Some oidx ->\n                   rcidx <> cidx ->\n                   getDir rcidx os#[dir] = mesiI) as Hcs.\n        { intros; eapply getDir_LastSharer_neq; eassumption. }\n\n        (** 2-2) Each child subtree (except the requestor) satisfies [ObjsInvalid] *)\n        assert (forall rcidx,\n                   parentIdxOf (fst (tree2Topo tr 0)) rcidx = Some oidx ->\n                   rcidx <> cidx ->\n                   forall nost rsTo,\n                     ObjsInvalid\n                       (fun idx =>\n                          In idx (subtreeIndsOf (fst (tree2Topo tr 0)) rcidx))\n                       (oss +[oidx <- nost])\n                       (enqMP (downTo cidx) rsTo (deqMP (rqUpFrom cidx) msgs))) as Hcsi.\n        { intros.\n          specialize (Hcs _ H36 H37).\n          disc_InvExcl oidx.\n          red in H39.\n          specialize (H39 (tl_In _ _ H8)).\n          move H39 at bottom.\n          specialize (H39 _ H36); destruct H39 as [? _].\n          specialize (H39 Hcs).\n          solve_ObjsInvalid_trivial.\n        }\n\n        assert (NoRsI oidx msgs) as Hrsi.\n        { move Hidir at bottom.\n          specialize (Hidir oidx); simpl in Hidir.\n          rewrite H15 in Hidir; simpl in Hidir.\n          eapply not_MsgExistsSig_MsgsNotExist; intros;\n            inv H36; [|dest_in].\n          specialize (Hidir (or_intror (or_intror H37))).\n          disc_getDir; simpl in *; solve_mesi.\n        }\n\n        (** 2-2) ObjsInvalid, outside [oidx] *)\n        assert (forall nost rsTo,\n                   ObjsInvalid\n                     (fun idx => ~ In idx (subtreeIndsOf (fst (tree2Topo tr 0)) oidx))\n                     (oss +[oidx <- nost])\n                     (enqMP (downTo cidx) rsTo (deqMP (rqUpFrom cidx) msgs))) as Hoo.\n        { intros.\n          solve_ObjsInvalid_trivial.\n          disc_InvExcl oidx.\n          apply H36. (* InvObjOwned *)\n          red; auto.\n        }\n\n        (** 3) All [ObjsInvalid], except [oidx] *)\n        assert (ObjsInvalid\n                  (fun oidx0 : IdxT => oidx <> oidx0)\n                  (oss +[oidx <- (fst os, (fst (snd os), (mesiM, (setDirI, snd (snd (snd (snd os)))))))])\n                  (enqMP (downTo cidx) {| msg_id := mesiInvRs;\n                                          msg_type := MRs;\n                                          msg_addr := msg_addr rmsg;\n                                          msg_value := 0 |}\n                         (deqMP (rqUpFrom cidx) msgs))) as Hoi.\n        { intros; eapply ObjsInvalid_invRs_composed.\n          { apply Hoo. }\n          { eapply ObjsInvalid_downRsIM_composed; [mred|].\n            intros; case_idx_eq rcidx cidx; auto.\n          }\n        }\n\n        split; [solve_AtomicInv_rqUp|].\n        pose proof H4 as Hi; phide Hi; rename H36 into Hi.\n\n        case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { disc_InvObjExcl0.\n            split; [apply Hoi|].\n            solve_MsgsP.\n            apply H36. (* InvObjOwned *)\n            red; auto.\n          }\n          { disc_InvObjOwned.\n            split; [solve_ObjsInvalid_trivial|solve_MsgsP].\n          }\n          { split_InvDirInv; [|exfalso; rewrite getDir_setDirI in H41; solve_mesi].\n            case_idx_eq cidx0 cidx.\n            { disc_AtomicMsgOutsInv cidx.\n              disc_MsgPred.\n              eapply InvExcl_inv_ObjsInvalid; eauto.\n              preveal Hi; assumption.\n            }\n            { solve_ObjsInvalid_trivial.\n              apply H37.\n              eapply getDir_LastSharer_neq; eauto.\n            }\n          }\n        }\n\n        { disc_InvExcl_others.\n          { case_idx_eq eidx cidx.\n            { red; intros [? ?]; exfalso.\n              apply NoRsI_MsgExistsSig_InvRs_false in H40; auto.\n              eexists (_, _); split.\n              { apply InMP_or_enqMP; left; simpl; auto. }\n              { reflexivity. }\n            }\n            { disc_InvObjExcl0_apply.\n              destruct H39.\n              clear Hci.\n              exfalso; eapply ObjsInvalid_obj_status_false with (oidx := eidx);\n                eauto; simpl in *; auto.\n              { solve_MsgsP. }\n              { mred. }\n              { solve_mesi. }\n            }\n          }\n\n          { case_in_subtree oidx eidx.\n            { disc_InvObjOwned.\n              split; [solve_ObjsInvalid_trivial|solve_MsgsP].\n            }\n            { case_in_subtree cidx eidx.\n              { eapply inside_child_outside_parent_case in i; eauto; subst.\n                red; intros [? ?]; exfalso.\n                apply NoRsI_MsgExistsSig_InvRs_false in H40; auto.\n                eexists (_, _); split.\n                { apply InMP_or_enqMP; left; simpl; auto. }\n                { reflexivity. }\n              }\n              { disc_InvObjOwned.\n                clear Hci Hoi.\n                solve_by_ObjsInvalid_status_false oidx.\n              }\n            }\n          }\n\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx0.\n              { clear Hci Hoi.\n                solve_by_ObjsInvalid_status_false oidx.\n              }\n              { solve_ObjsInvalid_trivial. }\n            }\n            { case_in_subtree oidx cidx0.\n              { solve_ObjsInvalid_trivial. }\n              { clear Hci Hoi.\n                solve_by_ObjsInvalid_status_false oidx.\n              }\n            }\n          }\n        }\n      }\n\n      { (* [liInvImmS1] *)\n        disc_rule_conds_ex.\n        derive_child_st cidx.\n        split; [solve_AtomicInv_rqUp|].\n        pose proof H4 as Hi; phide Hi; rename H34 into Hi.\n\n        case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { disc_InvObjExcl0_apply.\n            split; [solve_ObjsInvalid_trivial|solve_MsgsP].\n          }\n          { disc_InvObjOwned.\n            split; [solve_ObjsInvalid_trivial|solve_MsgsP].\n          }\n          { split_InvDirInv;\n              [|exfalso;\n                pose proof (getDir_removeSharer_sound cidx0 cidx os#[dir]);\n                simpl in *; solve_mesi].\n            case_idx_eq cidx0 cidx.\n            { disc_AtomicMsgOutsInv cidx.\n              disc_MsgPred.\n              eapply InvExcl_inv_ObjsInvalid; eauto.\n              preveal Hi; assumption.\n            }\n            { solve_ObjsInvalid_trivial.\n              simpl in H39; rewrite getDir_removeSharer_neq in H39 by assumption.\n              apply H35; assumption.\n            }\n          }\n        }\n\n        { disc_InvExcl_others.\n          { disc_InvObjExcl0_apply.\n            split; [|solve_MsgsP].\n            eapply ObjsInvalid_state_transition_sound; eauto.\n            { solve_ObjsInvalid_trivial. }\n            { simpl; right; apply getDir_S_imp in H30; dest; auto. }\n          }\n          { disc_InvObjOwned.\n            split; [|solve_MsgsP].\n            eapply ObjsInvalid_state_transition_sound; eauto.\n            { solve_ObjsInvalid_trivial. }\n            { simpl; right; apply getDir_S_imp in H30; dest; auto. }\n          }\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx0.\n              { eapply ObjsInvalid_state_transition_sound; eauto.\n                { solve_ObjsInvalid_trivial. }\n                { simpl; right; apply getDir_S_imp in H30; dest; auto. }\n              }\n              { solve_ObjsInvalid_trivial. }\n            }\n            { case_in_subtree oidx cidx0.\n              { solve_ObjsInvalid_trivial. }\n              { eapply ObjsInvalid_state_transition_sound; eauto.\n                { solve_ObjsInvalid_trivial. }\n                { simpl; right; apply getDir_S_imp in H30; dest; auto. }\n              }\n            }\n          }\n        }\n      }\n\n      { (* [liInvImmE] *)\n        disc_rule_conds_ex.\n        derive_child_st cidx.\n        derive_NoRsI_by_rqUp cidx msgs.\n        rename H27 into Hrsi.\n\n        assert (ObjsInvalid\n                  (fun idx => In idx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx))\n                  (oss +[oidx <- (fst os, (fst (snd os), (mesiE, (setDirI, snd (snd (snd (snd os)))))))])\n                  (enqMP (downTo cidx) {| msg_id := mesiInvRs;\n                                          msg_type := MRs;\n                                          msg_addr := msg_addr rmsg;\n                                          msg_value := 0 |}\n                         (deqMP (rqUpFrom cidx) msgs))) as Hci.\n        { intros; disc_AtomicMsgOutsInv cidx.\n          disc_MsgPred.\n          eapply InvExcl_inv_ObjsInvalid; eauto.\n        }\n\n        assert (ObjsInvalid\n                  (fun idx => ~ In idx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx))\n                  oss msgs) as Hcci.\n        { disc_InvExcl oidx.\n          disc_InvDirInv cidx.\n          apply H35.\n          simpl; solve_mesi.\n        }\n\n        assert (ObjsInvalid\n                  (fun idx => oidx <> idx)\n                  (oss +[oidx <- (fst os, (fst (snd os), (mesiE, (setDirI, snd (snd (snd (snd os)))))))])\n                  (enqMP (downTo cidx) {| msg_id := mesiInvRs;\n                                          msg_type := MRs;\n                                          msg_addr := msg_addr rmsg;\n                                          msg_value := 0 |}\n                         (deqMP (rqUpFrom cidx) msgs))) as Hoi.\n        { intros; eapply ObjsInvalid_invRs_composed.\n          { solve_ObjsInvalid_trivial.\n            eapply ObjsInvalid_impl; [apply Hcci|].\n            simpl; intros.\n            intro Hx; elim H27.\n            eapply subtreeIndsOf_child_SubList; eauto.\n          }\n          { apply ObjsInvalid_child_forall; intros rcidx ?.\n            case_idx_eq rcidx cidx; [assumption|].\n            solve_ObjsInvalid_trivial.\n            disc_InvExcl oidx.\n            disc_InvDirInv rcidx.\n            apply H35.\n            apply getDir_E_imp in H30; dest; subst.\n            eapply getDir_excl_neq; eauto.\n            simpl; solve_mesi.\n          }\n        }\n\n        split; [solve_AtomicInv_rqUp|].\n        case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { disc_InvObjExcl0; split; [apply Hoi|].\n            disc_MsgConflictsInv oidx.\n            solve_MsgsP.\n            eapply ObjInvalid_NoCohMsgs; eauto.\n            eapply ObjsInvalid_ObjInvalid; try exact Hcci; eauto.\n            simpl; intro; solve_by_topo_false.\n          }\n          { disc_InvObjOwned; dest.\n            split; [solve_ObjsInvalid_trivial|solve_MsgsP].\n          }\n          { split_InvDirInv; [|exfalso; rewrite getDir_setDirI in H38; solve_mesi].\n            case_idx_eq cidx0 cidx.\n            { apply Hci. }\n            { solve_ObjsInvalid_trivial.\n              apply H34.\n              apply getDir_E_imp in H30; dest; subst.\n              eapply getDir_excl_neq;\n                [reflexivity|simpl; solve_mesi|assumption].\n            }\n          }\n        }\n\n        { assert (mesiS <= cost#[status]).\n          { (** TODO: bring [disc_InvNWB] to here? *)\n            move Hnwb at bottom.\n            specialize (Hnwb _ _ H13); simpl in Hnwb.\n            disc_rule_conds_ex.\n            apply Hnwb.\n            { apply getDir_E_imp in H30; dest.\n              repeat split; try assumption.\n            }\n            { eexists (_, _); split; [apply FirstMP_InMP; eassumption|].\n              unfold sigOf; simpl; congruence.\n            }\n          }\n\n          disc_InvExcl_others.\n          { case_idx_eq eidx cidx.\n            { red; intros [? ?]; exfalso.\n              apply NoRsI_MsgExistsSig_InvRs_false in H38; auto.\n              eexists (_, _); split.\n              { apply InMP_or_enqMP; left; simpl; auto. }\n              { reflexivity. }\n            }\n            { disc_InvObjExcl0.\n              destruct H37.\n              clear Hci Hcci.\n              exfalso; eapply ObjsInvalid_obj_status_false with (oidx := eidx);\n                eauto; simpl in *; auto.\n              { solve_MsgsP. }\n              { mred. }\n              { solve_mesi. }\n            }\n          }\n\n          { case_in_subtree oidx eidx.\n            { disc_InvObjOwned.\n              split; [solve_ObjsInvalid_trivial|solve_MsgsP].\n            }\n            { case_in_subtree cidx eidx.\n              { eapply inside_child_outside_parent_case in i; eauto; subst.\n                red; intros [? ?]; exfalso.\n                apply NoRsI_MsgExistsSig_InvRs_false in H38; auto.\n                eexists (_, _); split.\n                { apply InMP_or_enqMP; left; simpl; auto. }\n                { reflexivity. }\n              }\n              { disc_InvObjOwned.\n                clear Hci Hcci Hoi; solve_by_ObjsInvalid_status_false cidx.\n              }\n            }\n          }\n\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx0.\n              { clear Hci Hcci Hoi.\n                eapply inside_child_in in i; eauto.\n                solve_by_ObjsInvalid_status_false cidx.\n              }\n              { solve_ObjsInvalid_trivial. }\n            }\n            { case_in_subtree oidx cidx0.\n              { solve_ObjsInvalid_trivial. }\n              { eapply outside_child_in in n0; eauto.\n                destruct n0; subst; [disc_rule_conds_ex|].\n                clear Hci Hcci Hoi.\n                solve_by_ObjsInvalid_status_false cidx.\n              }\n            }\n          }\n        }\n      }\n\n      { (* [liInvImmWBI] *)\n        disc_rule_conds_ex; split.\n        { solve_AtomicInv_rqUp. }\n        { solve_InvExcl_trivial. }\n      }\n\n      { (* [liInvImmWBS0] *)\n        disc_rule_conds_ex.\n        derive_child_st cidx.\n        split; [solve_AtomicInv_rqUp|].\n        pose proof H4 as Hi; phide Hi; rename H35 into Hi.\n\n        case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { disc_InvObjExcl0_apply.\n            split; [solve_ObjsInvalid_trivial|solve_MsgsP].\n          }\n          { disc_InvObjOwned.\n            split; [solve_ObjsInvalid_trivial|solve_MsgsP].\n          }\n          { split_InvDirInv; [|exfalso; rewrite getDir_setDirI in H40; solve_mesi].\n            case_idx_eq cidx0 cidx.\n            { disc_AtomicMsgOutsInv cidx.\n              disc_MsgPred.\n              eapply InvExcl_inv_ObjsInvalid; eauto.\n              preveal Hi; assumption.\n            }\n            { solve_ObjsInvalid_trivial.\n              apply H36.\n              eapply getDir_LastSharer_neq; eauto.\n            }\n          }\n        }\n\n        { disc_InvExcl_others.\n          { disc_InvObjExcl0_apply.\n            split; [|solve_MsgsP].\n            eapply ObjsInvalid_state_transition_sound; eauto; [|simpl; solve_mesi].\n            solve_ObjsInvalid_trivial.\n          }\n          { disc_InvObjOwned.\n            split; [|solve_MsgsP].\n            eapply ObjsInvalid_state_transition_sound; eauto; [|simpl; solve_mesi].\n            solve_ObjsInvalid_trivial.\n          }\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx0.\n              { eapply ObjsInvalid_state_transition_sound; eauto; [|simpl; solve_mesi].\n                solve_ObjsInvalid_trivial.\n              }\n              { solve_ObjsInvalid_trivial. }\n            }\n            { case_in_subtree oidx cidx0.\n              { solve_ObjsInvalid_trivial. }\n              { eapply ObjsInvalid_state_transition_sound; eauto; [|simpl; solve_mesi].\n                solve_ObjsInvalid_trivial.\n              }\n            }\n          }\n        }\n      }\n\n      { (* [liInvImmWBS1] *)\n        disc_rule_conds_ex.\n        derive_child_st cidx.\n        split; [solve_AtomicInv_rqUp|].\n        pose proof H4 as Hi; phide Hi; rename H34 into Hi.\n\n        case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { disc_InvObjExcl0_apply.\n            split; [solve_ObjsInvalid_trivial|solve_MsgsP].\n          }\n          { disc_InvObjOwned.\n            split; [solve_ObjsInvalid_trivial|solve_MsgsP].\n          }\n          { split_InvDirInv;\n              [|exfalso;\n                pose proof (getDir_removeSharer_sound cidx0 cidx os#[dir]);\n                simpl in *; solve_mesi].\n            case_idx_eq cidx0 cidx.\n            { disc_AtomicMsgOutsInv cidx.\n              disc_MsgPred.\n              eapply InvExcl_inv_ObjsInvalid; eauto.\n              preveal Hi; assumption.\n            }\n            { solve_ObjsInvalid_trivial.\n              simpl in H39; rewrite getDir_removeSharer_neq in H39 by assumption.\n              apply H35; assumption.\n            }\n          }\n        }\n\n        { disc_InvExcl_others.\n          { disc_InvObjExcl0_apply.\n            split; [|solve_MsgsP].\n            eapply ObjsInvalid_state_transition_sound; eauto.\n            { solve_ObjsInvalid_trivial. }\n            { simpl; right; apply getDir_S_imp in H30; dest; auto. }\n          }\n          { disc_InvObjOwned.\n            split; [|solve_MsgsP].\n            eapply ObjsInvalid_state_transition_sound; eauto.\n            { solve_ObjsInvalid_trivial. }\n            { simpl; right; apply getDir_S_imp in H30; dest; auto. }\n          }\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx0.\n              { eapply ObjsInvalid_state_transition_sound; eauto.\n                { solve_ObjsInvalid_trivial. }\n                { simpl; right; apply getDir_S_imp in H30; dest; auto. }\n              }\n              { solve_ObjsInvalid_trivial. }\n            }\n            { case_in_subtree oidx cidx0.\n              { solve_ObjsInvalid_trivial. }\n              { eapply ObjsInvalid_state_transition_sound; eauto.\n                { solve_ObjsInvalid_trivial. }\n                { simpl; right; apply getDir_S_imp in H30; dest; auto. }\n              }\n            }\n          }\n        }\n      }\n\n      { (* [liInvImmWBS] *)\n        disc_rule_conds_ex.\n        derive_child_st cidx.\n        derive_NoRsI_by_rqUp cidx msgs.\n        rename H36 into Hcrsi.\n\n        (** 1) The requestor subtree satisfies [ObjsInvalid] *)\n        assert (ObjsInvalid\n                  (fun idx => In idx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx))\n                  (oss +[oidx <- (fst os, (fst (snd os), (mesiM, (setDirI, snd (snd (snd (snd os)))))))])\n                  (enqMP (downTo cidx) {| msg_id := mesiInvRs;\n                                          msg_type := MRs;\n                                          msg_addr := msg_addr rmsg;\n                                          msg_value := 0 |}\n                         (deqMP (rqUpFrom cidx) msgs))) as Hci.\n        { intros; disc_AtomicMsgOutsInv cidx.\n          disc_MsgPred.\n          eapply InvExcl_inv_ObjsInvalid; eauto.\n        }\n\n        (** 2-1) Each child (except the requestor) has the directory status I *)\n        assert (forall rcidx,\n                   parentIdxOf (fst (tree2Topo tr 0)) rcidx = Some oidx ->\n                   rcidx <> cidx ->\n                   getDir rcidx os#[dir] = mesiI) as Hcs.\n        { intros; eapply getDir_LastSharer_neq; eassumption. }\n\n        (** 2-2) Each child subtree (except the requestor) satisfies [ObjsInvalid] *)\n        assert (forall rcidx,\n                   parentIdxOf (fst (tree2Topo tr 0)) rcidx = Some oidx ->\n                   rcidx <> cidx ->\n                   forall nost rsTo,\n                     ObjsInvalid\n                       (fun idx =>\n                          In idx (subtreeIndsOf (fst (tree2Topo tr 0)) rcidx))\n                       (oss +[oidx <- nost])\n                       (enqMP (downTo cidx) rsTo (deqMP (rqUpFrom cidx) msgs))) as Hcsi.\n        { intros.\n          specialize (Hcs _ H36 H37).\n          disc_InvExcl oidx.\n          red in H39.\n          specialize (H39 (tl_In _ _ H8)).\n          move H39 at bottom.\n          specialize (H39 _ H36); destruct H39 as [? _].\n          specialize (H39 Hcs).\n          solve_ObjsInvalid_trivial.\n        }\n\n        assert (NoRsI oidx msgs) as Hrsi.\n        { move Hidir at bottom.\n          specialize (Hidir oidx); simpl in Hidir.\n          rewrite H15 in Hidir; simpl in Hidir.\n          eapply not_MsgExistsSig_MsgsNotExist; intros;\n            inv H36; [|dest_in].\n          specialize (Hidir (or_intror (or_intror H37))).\n          disc_getDir; simpl in *; solve_mesi.\n        }\n\n        (** 2-2) ObjsInvalid, outside [oidx] *)\n        assert (forall nost rsTo,\n                   ObjsInvalid\n                     (fun idx => ~ In idx (subtreeIndsOf (fst (tree2Topo tr 0)) oidx))\n                     (oss +[oidx <- nost])\n                     (enqMP (downTo cidx) rsTo (deqMP (rqUpFrom cidx) msgs))) as Hoo.\n        { intros.\n          solve_ObjsInvalid_trivial.\n          disc_InvExcl oidx.\n          apply H36. (* InvObjOwned *)\n          red; auto.\n        }\n\n        (** 3) All [ObjsInvalid], except [oidx] *)\n        assert (ObjsInvalid\n                  (fun oidx0 : IdxT => oidx <> oidx0)\n                  (oss +[oidx <- (fst os, (fst (snd os), (mesiM, (setDirI, snd (snd (snd (snd os)))))))])\n                  (enqMP (downTo cidx) {| msg_id := mesiInvRs;\n                                          msg_type := MRs;\n                                          msg_addr := msg_addr rmsg;\n                                          msg_value := 0 |}\n                         (deqMP (rqUpFrom cidx) msgs))) as Hoi.\n        { intros; eapply ObjsInvalid_invRs_composed.\n          { apply Hoo. }\n          { eapply ObjsInvalid_downRsIM_composed; [mred|].\n            intros; case_idx_eq rcidx cidx; auto.\n          }\n        }\n\n        split; [solve_AtomicInv_rqUp|].\n        pose proof H4 as Hi; phide Hi; rename H36 into Hi.\n\n        case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { disc_InvObjExcl0.\n            split; [apply Hoi|].\n            solve_MsgsP.\n            apply H36. (* InvObjOwned *)\n            red; auto.\n          }\n          { disc_InvObjOwned.\n            split; [solve_ObjsInvalid_trivial|solve_MsgsP].\n          }\n          { split_InvDirInv; [|exfalso; rewrite getDir_setDirI in H41; solve_mesi].\n            case_idx_eq cidx0 cidx.\n            { disc_AtomicMsgOutsInv cidx.\n              disc_MsgPred.\n              eapply InvExcl_inv_ObjsInvalid; eauto.\n              preveal Hi; assumption.\n            }\n            { solve_ObjsInvalid_trivial.\n              apply H37.\n              eapply getDir_LastSharer_neq; eauto.\n            }\n          }\n        }\n\n        { disc_InvExcl_others.\n          { case_idx_eq eidx cidx.\n            { red; intros [? ?]; exfalso.\n              apply NoRsI_MsgExistsSig_InvRs_false in H40; auto.\n              eexists (_, _); split.\n              { apply InMP_or_enqMP; left; simpl; auto. }\n              { reflexivity. }\n            }\n            { disc_InvObjExcl0_apply.\n              destruct H39.\n              clear Hci.\n              exfalso; eapply ObjsInvalid_obj_status_false with (oidx := eidx);\n                eauto; simpl in *; auto.\n              { solve_MsgsP. }\n              { mred. }\n              { solve_mesi. }\n            }\n          }\n\n          { case_in_subtree oidx eidx.\n            { disc_InvObjOwned.\n              split; [solve_ObjsInvalid_trivial|solve_MsgsP].\n            }\n            { case_in_subtree cidx eidx.\n              { eapply inside_child_outside_parent_case in i; eauto; subst.\n                red; intros [? ?]; exfalso.\n                apply NoRsI_MsgExistsSig_InvRs_false in H40; auto.\n                eexists (_, _); split.\n                { apply InMP_or_enqMP; left; simpl; auto. }\n                { reflexivity. }\n              }\n              { disc_InvObjOwned.\n                clear Hci Hoi.\n                solve_by_ObjsInvalid_status_false oidx.\n              }\n            }\n          }\n\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx0.\n              { clear Hci Hoi.\n                solve_by_ObjsInvalid_status_false oidx.\n              }\n              { solve_ObjsInvalid_trivial. }\n            }\n            { case_in_subtree oidx cidx0.\n              { solve_ObjsInvalid_trivial. }\n              { clear Hci Hoi.\n                solve_by_ObjsInvalid_status_false oidx.\n              }\n            }\n          }\n        }\n      }\n\n      { (* [liInvImmWBME] *)\n        disc_rule_conds_ex.\n        derive_child_st cidx.\n        derive_NoRsI_by_rqUp cidx msgs.\n        rename H33 into Hrsi.\n\n        assert (ObjsInvalid\n                  (fun idx => In idx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx))\n                  (oss +[oidx <- (msg_value rmsg, (true, (mesiM, (setDirI, snd (snd (snd (snd os)))))))])\n                  (enqMP (downTo cidx) {| msg_id := mesiInvRs;\n                                          msg_type := MRs;\n                                          msg_addr := msg_addr rmsg;\n                                          msg_value := 0 |}\n                         (deqMP (rqUpFrom cidx) msgs))) as Hci.\n        { intros; disc_AtomicMsgOutsInv cidx.\n          disc_MsgPred.\n          eapply InvExcl_inv_ObjsInvalid; eauto.\n        }\n\n        assert (ObjsInvalid\n                  (fun idx => ~ In idx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx))\n                  oss msgs) as Hcci.\n        { disc_InvExcl oidx.\n          disc_InvDirInv cidx.\n          apply H35.\n          simpl; solve_mesi.\n        }\n\n        assert (ObjsInvalid\n                  (fun idx => oidx <> idx)\n                  (oss +[oidx <- (msg_value rmsg, (true, (mesiM, (setDirI, snd (snd (snd (snd os)))))))])\n                  (enqMP (downTo cidx) {| msg_id := mesiInvRs;\n                                          msg_type := MRs;\n                                          msg_addr := msg_addr rmsg;\n                                          msg_value := 0 |}\n                         (deqMP (rqUpFrom cidx) msgs))) as Hoi.\n        { intros; eapply ObjsInvalid_invRs_composed.\n          { solve_ObjsInvalid_trivial.\n            eapply ObjsInvalid_impl; [apply Hcci|].\n            simpl; intros.\n            intro Hx; elim H33.\n            eapply subtreeIndsOf_child_SubList; eauto.\n          }\n          { apply ObjsInvalid_child_forall; intros rcidx ?.\n            case_idx_eq rcidx cidx; [assumption|].\n            solve_ObjsInvalid_trivial.\n            disc_InvExcl oidx.\n            disc_InvDirInv rcidx.\n            apply H35.\n            apply getDir_ME_imp in H30; dest; subst.\n            eapply getDir_excl_neq; eauto.\n          }\n        }\n\n        split; [solve_AtomicInv_rqUp|].\n        case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { disc_InvObjExcl0; split; [apply Hoi|].\n            disc_MsgConflictsInv oidx.\n            solve_MsgsP.\n            eapply ObjInvalid_NoCohMsgs; eauto.\n            eapply ObjsInvalid_ObjInvalid; try exact Hcci; eauto.\n            simpl; intro; solve_by_topo_false.\n          }\n          { disc_InvDirInv cidx.\n            specialize (H35 H30).\n            disc_InvObjOwned; split.\n            { solve_ObjsInvalid_trivial.\n              eapply ObjsInvalid_impl; [apply H35|].\n              simpl; intros.\n              intro Hx; elim H38.\n              eapply subtreeIndsOf_child_SubList with (cidx:= cidx); eauto.\n            }\n            { disc_MsgConflictsInv oidx.\n              apply parent_not_in_subtree in H13; auto.\n              specialize (H35 _ H13); rewrite H15 in H35; simpl in H35.\n              solve_MsgsP.\n              eapply ObjInvalid_NoCohMsgs; eauto.\n            }\n          }\n          { split_InvDirInv; [|exfalso; rewrite getDir_setDirI in H38; solve_mesi].\n            case_idx_eq cidx0 cidx.\n            { apply Hci. }\n            { solve_ObjsInvalid_trivial.\n              apply H34.\n              apply getDir_ME_imp in H30; dest; subst.\n              eapply getDir_excl_neq;\n                [reflexivity|simpl; solve_mesi|assumption].\n            }\n          }\n        }\n\n        { assert (mesiS <= cost#[status]).\n          { (** TODO: bring [disc_InvWB] to here? *)\n            move Hwb at bottom.\n            specialize (Hwb _ _ H13); simpl in Hnwb.\n            disc_rule_conds_ex.\n            apply Hwb.\n            { apply getDir_ME_imp in H30; dest.\n              repeat split; try assumption.\n            }\n            { eexists (_, _); split; [apply FirstMP_InMP; eassumption|].\n              unfold sigOf; simpl; congruence.\n            }\n          }\n\n          disc_InvExcl_others.\n          { case_idx_eq eidx cidx.\n            { red; intros [? ?]; exfalso.\n              apply NoRsI_MsgExistsSig_InvRs_false in H38; auto.\n              eexists (_, _); split.\n              { apply InMP_or_enqMP; left; simpl; auto. }\n              { reflexivity. }\n            }\n            { disc_InvObjExcl0.\n              destruct H37.\n              clear Hci Hcci.\n              exfalso; eapply ObjsInvalid_obj_status_false with (oidx := eidx);\n                eauto; simpl in *; auto.\n              { solve_MsgsP. }\n              { mred. }\n              { solve_mesi. }\n            }\n          }\n\n          { case_in_subtree oidx eidx.\n            { disc_InvObjOwned.\n              split; [solve_ObjsInvalid_trivial|solve_MsgsP].\n            }\n            { case_in_subtree cidx eidx.\n              { eapply inside_child_outside_parent_case in i; eauto; subst.\n                red; intros [? ?]; exfalso.\n                apply NoRsI_MsgExistsSig_InvRs_false in H38; auto.\n                eexists (_, _); split.\n                { apply InMP_or_enqMP; left; simpl; auto. }\n                { reflexivity. }\n              }\n              { disc_InvObjOwned.\n                clear Hci Hcci Hoi; solve_by_ObjsInvalid_status_false cidx.\n              }\n            }\n          }\n\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx0.\n              { clear Hci Hcci Hoi.\n                eapply inside_child_in in i; eauto.\n                solve_by_ObjsInvalid_status_false cidx.\n              }\n              { solve_ObjsInvalid_trivial. }\n            }\n            { case_in_subtree oidx cidx0.\n              { solve_ObjsInvalid_trivial. }\n              { eapply outside_child_in in n0; eauto.\n                destruct n0; subst; [disc_rule_conds_ex|].\n                clear Hci Hcci Hoi.\n                solve_by_ObjsInvalid_status_false cidx.\n              }\n            }\n          }\n        }\n      }\n    }\n\n    dest_in.\n\n    { (* [liGetSRsDownDownS] *)\n      disc_rule_conds_ex.\n      derive_footprint_info_basis oidx.\n      disc_MesiUpLockInv oidx.\n      derive_child_chns cidx.\n      disc_rule_conds_ex.\n\n      split.\n      { solve_AtomicInv_rsDown. }\n      { solve_InvExcl_trivial.\n        case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { solve_InvObjExcl0_by_ObjExcl0_false. }\n          { solve_InvObjOwned_by_false. }\n          { split_InvDirInv.\n            { disc_dir.\n              specialize (H36 H40).\n              solve_ObjsInvalid_trivial.\n            }\n            { exfalso; disc_dir; solve_mesi. }\n          }\n        }\n\n        { disc_MsgConflictsInv oidx.\n          disc_InvExcl_others.\n          { disc_InvObjExcl0_apply.\n            solve_by_ObjsInvalid_rsS_false oidx.\n          }\n          { case_InvObjOwned.\n            { solve_by_ObjsInvalid_rsS_false oidx. }\n            { disc_ObjsInvalid_by oidx0; case_ObjInvalid.\n              { case_idx_eq oidx0 cidx; [|solve_ObjInvalid0].\n                eapply outside_parent_out in H47; eauto.\n                solve_by_ObjsInvalid_rsS_false oidx.\n              }\n              { solve_ObjInvRs. }\n            }\n            { case_idx_eq cidx eidx; [|solve_MsgsP].\n              exfalso.\n              case_in_subtree oidx eidx; [solve_by_topo_false|].\n              solve_by_ObjsInvalid_rsS_false oidx.\n            }\n          }\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx0.\n              { solve_by_ObjsInvalid_rsS_false oidx. }\n              { solve_ObjsInvalid_trivial. }\n            }\n            { case_in_subtree oidx cidx0.\n              { solve_ObjsInvalid_trivial. }\n              { solve_by_ObjsInvalid_rsS_false oidx. }\n            }\n          }\n        }\n      }\n    }\n\n    { (* [liGetSRsDownDownE] *)\n      disc_rule_conds_ex.\n      derive_footprint_info_basis oidx.\n      derive_child_chns cidx.\n      disc_MsgConflictsInv oidx.\n      disc_rule_conds_ex.\n\n      split.\n      { solve_AtomicInv_rsDown.\n        disc_AtomicMsgOutsInv oidx.\n        disc_MsgPred.\n\n        solve_msg_pred_base.\n        solve_ObjsInvalid_trivial.\n        eapply ObjsInvalid_rsDown_invalidated; eauto.\n        discriminate.\n      }\n      { solve_InvExcl_trivial.\n        case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { solve_InvObjExcl0_by_ObjExcl0_false. }\n          { solve_InvObjOwned_by_false. }\n          { split_InvDirInv.\n            { case_idx_eq cidx cidx0; [disc_dir; discriminate|].\n              disc_AtomicMsgOutsInv oidx.\n              disc_MsgPred.\n              solve_ObjsInvalid_trivial.\n              eapply ObjsInvalid_impl; [eassumption|].\n              simpl; intros.\n              intro; subst; solve_by_topo_false.\n            }\n            { case_idx_eq cidx cidx0; [|disc_dir; solve_mesi].\n              disc_AtomicMsgOutsInv oidx.\n              disc_MsgPred.\n              solve_ObjsInvalid_trivial.\n              eapply ObjsInvalid_impl.\n              { eapply ObjsInvalid_rsDown_invalidated; eauto; discriminate. }\n              { simpl; intros.\n                intro; subst; solve_by_topo_false.\n              }\n            }\n          }\n        }\n\n        { disc_InvExcl_others.\n          { disc_InvObjExcl0_apply.\n            solve_by_ObjsInvalid_rsE_false oidx.\n          }\n          { case_InvObjOwned.\n            { solve_by_ObjsInvalid_rsE_false oidx. }\n            { disc_ObjsInvalid_by oidx0; case_ObjInvalid.\n              { case_idx_eq oidx0 cidx; [|solve_ObjInvalid0].\n                eapply outside_parent_out in H44; eauto.\n                solve_by_ObjsInvalid_rsE_false oidx.\n              }\n              { solve_ObjInvRs. }\n            }\n            { case_idx_eq cidx eidx; [|solve_MsgsP].\n              exfalso.\n              case_in_subtree oidx eidx; [solve_by_topo_false|].\n              solve_by_ObjsInvalid_rsE_false oidx.\n            }\n          }\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx0.\n              { solve_by_ObjsInvalid_rsE_false oidx. }\n              { solve_ObjsInvalid_trivial. }\n            }\n            { case_in_subtree oidx cidx0.\n              { solve_ObjsInvalid_trivial. }\n              { solve_by_ObjsInvalid_rsE_false oidx. }\n            }\n          }\n        }\n      }\n    }\n\n    { (* [liDownSRsUpDownME] *)\n      disc_rule_conds_ex.\n      disc_MesiDownLockInv oidx Hdlinv.\n      derive_footprint_info_basis oidx.\n\n      split.\n      { solve_AtomicInv_rsUps_rsDown Hrsd. }\n      { apply subtreeChildrenIndsOf_parentIdxOf in H29; auto.\n        case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { solve_InvObjExcl0_by_ObjExcl0_false. }\n          { remember (dir_excl _) as rcidx.\n            disc_InvDirInv rcidx.\n            rewrite getDir_excl_eq in H40; [|assumption|intuition solve_mesi].\n            specialize (H40 H23).\n            clear Heqrcidx.\n\n            disc_InvObjOwned; split.\n            { solve_ObjsInvalid_trivial.\n              eapply ObjsInvalid_impl; [eassumption|].\n              simpl; intros.\n              intro Hx; elim H43.\n              eapply subtreeIndsOf_child_SubList with (cidx:= rcidx); eauto.\n            }\n            { disc_MsgConflictsInv oidx.\n              apply parent_not_in_subtree in H29; auto.\n              specialize (H40 _ H29); rewrite H15 in H40; simpl in H40.\n              solve_MsgsP.\n              eapply ObjInvalid_NoCohMsgs; eauto.\n            }\n          }\n          { remember (dir_excl _) as rcidx.\n            split_InvDirInv.\n            { apply getDir_setDirS_I_imp in H43.\n              case_idx_eq x cidx; [exfalso; elim H43; left; reflexivity|].\n              case_idx_eq rcidx cidx; [exfalso; elim H43; right; left; reflexivity|].\n              solve_ObjsInvalid_trivial.\n              apply H39.\n              eapply getDir_excl_neq; [reflexivity|intuition solve_mesi|simpl; congruence].\n            }\n            { exfalso.\n              pose proof (getDir_setDirS_sound cidx [x; rcidx]).\n              simpl in *; solve_mesi.\n            }\n          }\n        }\n\n        { pose proof Hpmcf as Hpmcf'; phide Hpmcf'; rename H39 into Hpmcf'.\n          disc_MsgConflictsInv oidx.\n          remember (dir_excl _) as rcidx; clear Heqrcidx.\n          disc_AtomicMsgOutsInv rcidx.\n\n          derive_child_st rcidx.\n          disc_MsgPred.\n          preveal Hpmcf'; disc_MsgConflictsInv rcidx.\n\n          disc_InvExcl_others.\n          { disc_InvObjExcl0_apply.\n            exfalso.\n            case_idx_eq eidx rcidx.\n            { disc_rule_conds; disc_ObjExcl0; solve_mesi. }\n            { solve_by_ObjsInvalid_downRsS_false rcidx. }\n          }\n          { case_in_subtree rcidx eidx;\n              [|disc_InvObjOwned; solve_by_ObjsInvalid_downRsS_false rcidx].\n            case_idx_eq eidx rcidx;\n              [disc_rule_conds_ex; disc_InvObjOwned; simpl in *; congruence|].\n            disc_InvObjOwned; split.\n            { assert (In oidx (subtreeIndsOf (fst (tree2Topo tr 0)) eidx)).\n              { eapply inside_parent_in with (cidx:= rcidx); eauto. }\n              solve_ObjsInvalid_trivial.\n            }\n            { case_idx_eq x eidx; [|solve_MsgsP].\n              assert (~ In rcidx (subtreeIndsOf (fst (tree2Topo tr 0)) eidx)).\n              { intro; solve_by_topo_false. }\n              solve_by_ObjsInvalid_downRsS_false rcidx.\n            }\n          }\n          { split_InvDirInv_apply.\n            { case_in_subtree x cidx.\n              { case_idx_eq x cidx; [disc_rule_conds|].\n                assert (In oidx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx)).\n                { eapply inside_parent_in with (cidx:= x); eauto. }\n                assert (In rcidx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx)).\n                { eapply inside_child_in; eauto. }\n                solve_by_ObjsInvalid_downRsS_false rcidx.\n              }\n              { case_in_subtree rcidx cidx; [solve_by_ObjsInvalid_downRsS_false rcidx|].\n                solve_ObjsInvalid_trivial.\n              }\n            }\n            { case_in_subtree rcidx cidx;\n                [|solve_by_ObjsInvalid_downRsS_false rcidx].\n              case_idx_eq rcidx cidx; [disc_rule_conds|].\n              assert (In oidx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx)).\n              { eapply inside_parent_in with (cidx:= rcidx); eauto. }\n              solve_ObjsInvalid_trivial.\n            }\n          }\n        }\n      }\n    }\n\n    { (* [liDownSImm] *)\n      disc_rule_conds_ex.\n      derive_NoRsI_by_rqDown oidx msgs.\n\n      split.\n      { solve_AtomicInv_rqDown_rsUp.\n        solve_DownRsSPred.\n      }\n      { case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { solve_InvObjExcl0_by_ObjExcl0_false. }\n          { solve_InvObjOwned_by_false. }\n          { split_InvDirInv_apply.\n            { solve_ObjsInvalid_trivial. }\n            { exfalso; disc_dir; solve_mesi. }\n          }\n        }\n        { disc_InvExcl_others.\n          { disc_InvObjExcl0_apply.\n            solve_by_ObjsInvalid_status_false oidx.\n          }\n          { case_InvObjOwned.\n            { solve_by_ObjsInvalid_status_false oidx. }\n            { disc_ObjsInvalid_by oidx0.\n              case_ObjInvalid; [solve_ObjInvalid0|solve_ObjInvRs].\n            }\n            { solve_MsgsP. }\n          }\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx.\n              { solve_by_ObjsInvalid_status_false oidx. }\n              { solve_ObjsInvalid_trivial. }\n            }\n            { case_in_subtree oidx cidx.\n              { solve_ObjsInvalid_trivial. }\n              { solve_by_ObjsInvalid_status_false oidx. }\n            }\n          }\n        }\n      }\n    }\n\n    { (* [liDownSRqDownDownME] *)\n      disc_rule_conds_ex; split.\n      { remember (dir_excl _) as cidx; clear Heqcidx.\n        solve_AtomicInv_rqDown_rqDowns.\n        apply subtreeChildrenIndsOf_parentIdxOf in H23; auto.\n        derive_child_chns cidx.\n        repeat constructor; simpl; eauto.\n      }\n      { solve_InvExcl_trivial. }\n    }\n\n    { (* [liDownSRsUpUp] *)\n      disc_rule_conds_ex.\n      disc_MesiDownLockInv oidx Hdlinv.\n      derive_footprint_info_basis oidx; [solve_midx_false|].\n      pick_rsUp_single.\n\n      split.\n      { solve_AtomicInv_rsUps_rsUp.\n        solve_DownRsSPred.\n      }\n      { apply subtreeChildrenIndsOf_parentIdxOf in H29; auto.\n        case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { solve_InvObjExcl0_by_ObjExcl0_false. }\n          { solve_InvObjOwned_by_false. }\n          { remember (dir_excl _) as rcidx.\n            split_InvDirInv.\n            { apply getDir_setDirS_I_imp in H43.\n              case_idx_eq rcidx cidx0; [exfalso; elim H43; left; reflexivity|clear H43].\n              solve_ObjsInvalid_trivial.\n              apply H39.\n              eapply getDir_excl_neq; [reflexivity|intuition solve_mesi|simpl; congruence].\n            }\n            { exfalso.\n              pose proof (getDir_setDirS_sound cidx0 [rcidx]).\n              simpl in *; solve_mesi.\n            }\n          }\n        }\n\n        { pose proof Hpmcf as Hpmcf'; phide Hpmcf'; rename H38 into Hpmcf'.\n          disc_MsgConflictsInv oidx.\n          remember (dir_excl _) as rcidx; clear Heqrcidx.\n          disc_AtomicMsgOutsInv rcidx.\n\n          derive_child_st rcidx.\n          disc_MsgPred.\n          preveal Hpmcf'; disc_MsgConflictsInv rcidx.\n\n          disc_InvExcl_others.\n          { disc_InvObjExcl0_apply.\n            exfalso.\n            case_idx_eq eidx rcidx.\n            { disc_rule_conds; disc_ObjExcl0; solve_mesi. }\n            { solve_by_ObjsInvalid_downRsS_false rcidx. }\n          }\n          { case_in_subtree rcidx eidx;\n              [|disc_InvObjOwned; solve_by_ObjsInvalid_downRsS_false rcidx].\n            case_idx_eq eidx rcidx;\n              [disc_rule_conds; disc_InvObjOwned; simpl in *; congruence|].\n            disc_InvObjOwned; split.\n            { assert (In oidx (subtreeIndsOf (fst (tree2Topo tr 0)) eidx)).\n              { eapply inside_parent_in with (cidx:= rcidx); eauto. }\n              solve_ObjsInvalid_trivial.\n            }\n            { solve_MsgsP. }\n          }\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx0.\n              { assert (In rcidx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx0)).\n                { eapply inside_child_in; eauto. }\n                solve_by_ObjsInvalid_downRsS_false rcidx.\n              }\n              { case_in_subtree rcidx cidx0; [solve_by_ObjsInvalid_downRsS_false rcidx|].\n                solve_ObjsInvalid_trivial.\n              }\n            }\n            { case_in_subtree rcidx cidx0;\n                [|solve_by_ObjsInvalid_downRsS_false rcidx].\n              case_idx_eq rcidx cidx0; [disc_rule_conds|].\n              assert (In oidx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx0)).\n              { eapply inside_parent_in with (cidx:= rcidx); eauto. }\n              solve_ObjsInvalid_trivial.\n            }\n          }\n        }\n      }\n    }\n\n    { (* [liGetMRsDownDownDirI] *)\n      disc_rule_conds_ex.\n      derive_footprint_info_basis oidx.\n      disc_MesiUpLockInv oidx.\n      derive_child_chns cidx.\n      disc_MsgConflictsInv oidx.\n      disc_rule_conds_ex.\n\n      rename H26 into Hprec. (* the precondition about status and ownership bit *)\n      assert (ObjsInvalid (fun idx => ~ In idx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx))\n                          (oss +[oidx <- (fst os,\n                                          (false,\n                                           (invalidate (fst (snd (snd os))),\n                                            (setDirM cidx, snd (snd (snd (snd os)))))))])\n                          (deqMP (downTo oidx) msgs)) as Hoi.\n      { disc_AtomicMsgOutsInv oidx.\n        disc_InvExcl oidx.\n        destruct Hprec; dest.\n        { eapply ObjsInvalid_rsM_consumed; eauto.\n          { apply tl_In; assumption. }\n          { assumption. }\n          { simpl; solve_mesi. }\n        }\n        { eapply ObjsInvalid_out_composed; eauto.\n          { solve_ObjsInvalid_trivial.\n            apply H34; auto.\n          }\n          { mred. }\n          { left; repeat split; [simpl; solve_mesi|discriminate|].\n            eapply NoCohMsgs_rsDown_deq; eauto.\n          }\n          { intros.\n            solve_ObjsInvalid_trivial.\n            disc_InvDirInv rcidx.\n            apply H49.\n            eapply getDir_LastSharer_neq; try eassumption.\n            eapply getDir_LastSharer_eq; eassumption.\n          }\n        }\n      }\n\n      split.\n      { solve_AtomicInv_rsDown.\n        disc_AtomicMsgOutsInv oidx.\n        disc_MsgPred.\n        disc_InvExcl oidx.\n        solve_msg_pred_base.\n        solve_ObjsInvalid_trivial.\n      }\n\n      { solve_InvExcl_trivial.\n        case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { solve_InvObjExcl0_by_ObjExcl0_false. }\n          { solve_InvObjOwned_by_false. }\n          { pose proof H34. (* [InvDirInv] *)\n            split_InvDirInv.\n            { case_idx_eq cidx cidx0; [disc_dir; discriminate|].\n              solve_ObjsInvalid_trivial.\n              apply H36.\n              destruct Hprec; dest.\n              { apply getDir_st_I; assumption. }\n              { eapply getDir_LastSharer_neq; eauto.\n                eapply getDir_LastSharer_eq; auto.\n              }\n            }\n            { case_idx_eq cidx cidx0; [|disc_dir; solve_mesi].\n              disc_AtomicMsgOutsInv oidx.\n              disc_MsgPred.\n              solve_ObjsInvalid_trivial.\n            }\n          }\n        }\n\n        { disc_InvExcl_others.\n          { disc_InvObjExcl0_apply.\n            solve_by_ObjsInvalid_rsM_false oidx.\n          }\n          { case_InvObjOwned.\n            { solve_by_ObjsInvalid_rsM_false oidx. }\n            { disc_ObjsInvalid_by oidx0; case_ObjInvalid.\n              { case_idx_eq oidx0 cidx; [|solve_ObjInvalid0].\n                eapply outside_parent_out in H46; eauto.\n                solve_by_ObjsInvalid_rsM_false oidx.\n              }\n              { solve_ObjInvRs. }\n            }\n            { case_idx_eq cidx eidx; [|solve_MsgsP].\n              exfalso.\n              case_in_subtree oidx eidx; [solve_by_topo_false|].\n              solve_by_ObjsInvalid_rsM_false oidx.\n            }\n          }\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx0.\n              { solve_by_ObjsInvalid_rsM_false oidx. }\n              { solve_ObjsInvalid_trivial. }\n            }\n            { case_in_subtree oidx cidx0.\n              { solve_ObjsInvalid_trivial. }\n              { solve_by_ObjsInvalid_rsM_false oidx. }\n            }\n          }\n        }\n      }\n    }\n\n    { (* [liGetMRsDownRqDownDirS] *)\n      disc_rule_conds_ex.\n      derive_footprint_info_basis oidx.\n      derive_child_chns cidx.\n      disc_MsgConflictsInv oidx.\n      disc_rule_conds_ex.\n\n      split.\n      { solve_AtomicInv_rsDown.\n        (** TODO: Ltac? *)\n        apply Forall_forall; intros.\n        apply in_map_iff in H1; dest; subst.\n        repeat constructor; try (red; simpl; intros; intuition discriminate).\n      }\n      { solve_InvExcl_trivial.\n        case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { disc_InvObjExcl0_apply; split.\n            { solve_ObjsInvalid_trivial. }\n            { solve_MsgsP. }\n          }\n          { disc_AtomicMsgOutsInv oidx.\n            disc_MsgPred.\n            disc_InvObjOwned; split.\n            { solve_ObjsInvalid_trivial. }\n            { eapply NoCohMsgs_rsDown_deq; eauto. }\n          }\n          { split_InvDirInv_apply.\n            { solve_ObjsInvalid_trivial. }\n            { simpl in H37.\n              pose proof (getDir_st_sound (fst (snd (snd (snd os)))) cidx0 ltac:(solve_mesi)).\n              solve_mesi.\n            }\n          }\n        }\n\n        { disc_InvExcl_others.\n          { disc_InvObjExcl0_apply.\n            solve_by_ObjsInvalid_rsM_false oidx.\n          }\n          { case_InvObjOwned.\n            { solve_by_ObjsInvalid_rsM_false oidx. }\n            { disc_ObjsInvalid_by oidx0.\n              case_ObjInvalid; [solve_ObjInvalid0|solve_ObjInvRs].\n            }\n            { solve_MsgsP. }\n          }\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx0.\n              { solve_by_ObjsInvalid_rsM_false oidx. }\n              { solve_ObjsInvalid_trivial. }\n            }\n            { case_in_subtree oidx cidx0.\n              { solve_ObjsInvalid_trivial. }\n              { solve_by_ObjsInvalid_rsM_false oidx. }\n            }\n          }\n        }\n      }\n    }\n\n    { (* [liDownIRsUpDownS] *)\n      disc_rule_conds_ex.\n      disc_MesiDownLockInv oidx Hdlinv.\n      derive_footprint_info_basis oidx.\n      destruct H28; [simpl in *; dest|solve_mesi; fail].\n\n      (** 1) Each RsUp message is from a child *)\n      assert (Forall\n                (fun midx =>\n                   exists rcidx,\n                     parentIdxOf (fst (tree2Topo tr 0)) rcidx = Some oidx /\\\n                     midx = rsUpFrom rcidx)\n                (idsOf rins)) as Hrss.\n      { apply Forall_forall; intros rsUp ?.\n        eapply RqRsDownMatch_rs_rq in H36; [|rewrite <-H13; eassumption].\n        destruct H36 as [cidx [down ?]]; dest.\n        derive_child_chns cidx; repeat disc_rule_minds.\n        eauto.\n      }\n\n      (** 2-1) Each child (except the requestor) either sent RsUp or is in DirI *)\n      assert (forall rcidx,\n                 parentIdxOf (fst (tree2Topo tr 0)) rcidx = Some oidx ->\n                 x <> rcidx ->\n                 if in_dec idx_dec (rsUpFrom rcidx) (idsOf rins)\n                 then True\n                 else getDir rcidx os#[dir] = mesiI) as Hcs.\n      { intros.\n        destruct (in_dec idx_dec rcidx\n                         (remove idx_dec x (dir_sharers (fst (snd (snd (snd os))))))).\n        { find_if_inside; [auto|].\n          elim n; rewrite H13, H39; apply in_map; assumption.\n        }\n        { find_if_inside; [auto|].\n          apply getDir_S_non_sharer; [assumption|].\n          intro Hx; elim n.\n          apply in_remove_neq; auto.\n        }\n      }\n\n      (** 2-2) Each child subtree (except the requestor) satisfies [ObjsInvalid] *)\n      assert (forall rcidx,\n                 parentIdxOf (fst (tree2Topo tr 0)) rcidx = Some oidx ->\n                 x <> rcidx ->\n                 forall nost rsTo,\n                   ObjsInvalid\n                     (fun idx =>\n                        In idx (subtreeIndsOf (fst (tree2Topo tr 0)) rcidx))\n                     (oss +[oidx <- nost])\n                     (enqMP (downTo x) rsTo (deqMsgs (idsOf rins) msgs))) as Hcsi.\n      { intros.\n        specialize (Hcs _ H40 H41); find_if_inside.\n        { apply in_map_iff in i; destruct i as [[midx rs] ?]; simpl in *; dest; subst.\n          rewrite Forall_forall in H14; specialize (H14 _ H43).\n          rewrite Forall_forall in H23; specialize (H23 _ H43); simpl in *.\n          pose proof (H3 _ H43) as Hrein.\n          disc_AtomicMsgOutsInv rcidx.\n          specialize (H46 eq_refl H23 H14); dest.\n          derive_child_st rcidx.\n          disc_MsgConflictsInv rcidx.\n          rewrite H52 in H46; simpl in H46; dest.\n          solve_ObjsInvalid_trivial.\n          eapply ObjsInvalid_this_rsUps_deqMsgs_silent; eauto.\n          apply parent_not_in_subtree; auto.\n        }\n        { disc_InvExcl oidx.\n          red in H43.\n          specialize (H43 (tl_In _ _ H8)).\n          move H43 at bottom.\n          specialize (H43 _ H40); destruct H43 as [? _].\n          specialize (H43 Hcs).\n          solve_ObjsInvalid_trivial.\n          eapply ObjsInvalid_this_rsUps_deqMsgs_silent with (pidx:= oidx); eauto.\n          intro; solve_by_topo_false.\n        }\n      }\n\n      assert (NoRsI oidx msgs) as Hrsi.\n      { move Hidir at bottom.\n        specialize (Hidir oidx); simpl in Hidir.\n        rewrite H15 in Hidir; simpl in Hidir.\n        eapply not_MsgExistsSig_MsgsNotExist; intros;\n          inv H40; [|dest_in].\n        specialize (Hidir (or_intror (or_intror H41))).\n        simpl in *; solve_mesi.\n      }\n\n      (** 2-2) ObjsInvalid, outside [oidx] *)\n      assert (forall nost rsTo,\n                 ObjsInvalid\n                   (fun idx => ~ In idx (subtreeIndsOf (fst (tree2Topo tr 0)) oidx))\n                   (oss +[oidx <- nost])\n                   (enqMP (downTo x) rsTo (deqMsgs (idsOf rins) msgs))) as Hoo.\n      { intros.\n        solve_ObjsInvalid_trivial.\n        eapply ObjsInvalid_this_rsUps_deqMsgs_silent with (pidx:= oidx); eauto;\n          [|intro; solve_by_topo_false].\n        disc_InvExcl oidx.\n        specialize (H40 (conj H28 Hrsi)); dest; assumption.\n      }\n\n      (** 2-3) The target object itself gets invalid *)\n      assert (forall rsTo,\n                 ObjInvalid0\n                   oidx (fst os,\n                         (false,\n                          (invalidate (fst (snd (snd os))),\n                           (setDirM x, snd (snd (snd (snd os)))))))\n                   (enqMP (downTo x) rsTo (deqMsgs (idsOf rins) msgs))) as Hoi.\n      { intros; repeat split; [simpl; solve_mesi|discriminate|].\n        disc_InvExcl oidx.\n        specialize (H40 (conj H28 Hrsi)); dest; solve_MsgsP.\n      }\n\n      (** 3) Predicate for [mesiRsM] *)\n      assert (ObjsInvalid\n                (fun idx => ~ In idx (subtreeIndsOf (fst (tree2Topo tr 0)) x))\n                (oss +[oidx <- (fst os,\n                                (false,\n                                 (invalidate (fst (snd (snd os))),\n                                  (setDirM x, snd (snd (snd (snd os)))))))])\n                (enqMP (downTo x)\n                       {| msg_id := mesiRsM;\n                          msg_type := MRs;\n                          msg_addr := msg_addr msg;\n                          msg_value := 0 |} (deqMsgs (idsOf rins) msgs))) as Hrc.\n      { intros.\n        eapply ObjsInvalid_out_composed with (oidx:= oidx); eauto.\n        { mred. }\n        { left; apply Hoi. }\n      }\n\n      split.\n      { solve_AtomicInv_rsUps_rsDown Hrsd.\n        red; simpl; intros; inv H40.\n        rewrite <-H13; eapply Hrc.\n      }\n\n      { case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { solve_InvObjExcl0_by_ObjExcl0_false. }\n          { solve_InvObjOwned_by_false. }\n          { split_InvDirInv.\n            { case_idx_eq x cidx;\n                [rewrite getDir_setDirM_eq in H44; discriminate|clear H44].\n              rewrite <-H13; eapply Hcsi; eauto.\n            }\n            { case_idx_eq x cidx;\n                [clear H44\n                |simpl in H44; rewrite getDir_setDirM_neq in H44 by assumption;\n                 solve_mesi].\n              rewrite <-H13; eapply Hrc.\n            }\n          }\n        }\n\n        { disc_InvExcl_others.\n          { disc_InvObjExcl0.\n            rewrite <-H13 in H43.\n            apply ObjExcl0_other_msg_id_deqMsgs_inv in H43; auto.\n            2: { eapply Forall_impl; [|apply H14]; simpl; intros.\n                 rewrite H44; discriminate.\n            }\n            specialize (H4 H43); dest.\n            exfalso.\n            disc_ObjsInvalid_by oidx.\n            rewrite H15 in H45; simpl in H45.\n            destruct H45.\n            { destruct H45 as [? [? ?]]; auto. }\n            { eapply NoRsI_MsgExistsSig_InvRs_false; eauto. }\n          }\n\n          { red; intros [? ?].\n            assert (NoRsI eidx msgs).\n            { disc_MsgsP H44.\n              rewrite <-H13 in H44; simpl in H44.\n              apply MsgsP_other_msg_id_deqMsgs_inv in H44; auto.\n              simpl; apply (DisjList_spec_2 idx_dec); intros; dest_in.\n              intro; dest_in.\n              apply in_map_iff in H32; destruct H32 as [[rmidx rmsg] [? ?]]; simpl in *.\n              rewrite Forall_forall in H14; specialize (H14 _ H45); simpl in *.\n              rewrite H14 in H32; discriminate.\n            }\n            specialize (H41 (conj H43 H45)); dest.\n\n            case_in_subtree oidx eidx;\n              [|clear Hrc; solve_by_ObjsInvalid_dir_false oidx].\n            split.\n            { solve_ObjsInvalid_trivial.\n              rewrite <-H13.\n              eapply ObjsInvalid_this_rsUps_deqMsgs_silent with (pidx:= oidx); eauto.\n            }\n            { case_idx_eq x eidx; [|solve_MsgsP].\n              exfalso.\n              apply parent_not_in_subtree in i; auto.\n            }\n          }\n\n          { split_InvDirInv_apply.\n            { case_in_subtree x cidx.\n              { case_idx_eq x cidx; [disc_rule_conds|].\n                assert (In oidx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx)).\n                { eapply inside_parent_in with (cidx:= x); eauto. }\n                clear Hrc; solve_by_ObjsInvalid_dir_false oidx.\n              }\n              { solve_ObjsInvalid_trivial.\n                rewrite <-H13.\n                eapply ObjsInvalid_this_rsUps_deqMsgs_silent with (pidx:= oidx); eauto.\n                intro; solve_by_topo_false.\n              }\n            }\n            { case_in_subtree oidx cidx;\n                [|clear Hrc; solve_by_ObjsInvalid_dir_false oidx].\n              solve_ObjsInvalid_trivial.\n              rewrite <-H13.\n              eapply ObjsInvalid_this_rsUps_deqMsgs_silent with (pidx:= oidx); eauto.\n            }\n          }\n        }\n      }\n    }\n\n    { (* [liDownIRsUpDownME] *)\n      disc_rule_conds_ex.\n      disc_MesiDownLockInv oidx Hdlinv.\n      derive_footprint_info_basis oidx.\n      destruct H28; [solve_mesi; fail|simpl in *; dest].\n\n      (** 1) Each RsUp message is from a child *)\n      assert (Forall\n                (fun midx =>\n                   exists rcidx,\n                     parentIdxOf (fst (tree2Topo tr 0)) rcidx = Some oidx /\\\n                     midx = rsUpFrom rcidx)\n                (idsOf rins)) as Hrss.\n      { apply Forall_forall; intros rsUp ?.\n        eapply RqRsDownMatch_rs_rq in H36; [|rewrite <-H13; eassumption].\n        destruct H36 as [cidx [down ?]]; dest.\n        derive_child_chns cidx; repeat disc_rule_minds.\n        eauto.\n      }\n\n      (** 2-1) Each child (except the requestor) either sent RsUp or is in DirI *)\n      assert (forall rcidx,\n                 parentIdxOf (fst (tree2Topo tr 0)) rcidx = Some oidx ->\n                 x <> rcidx ->\n                 if in_dec idx_dec (rsUpFrom rcidx) (idsOf rins)\n                 then True\n                 else getDir rcidx os#[dir] = mesiI) as Hcs.\n      { intros.\n        case_idx_eq rcidx (dir_excl (fst (snd (snd (snd os))))).\n        { find_if_inside; [auto|].\n          elim n; rewrite H13, H38; left; reflexivity.\n        }\n        { find_if_inside; [auto|erewrite getDir_excl_neq; eauto]. }\n      }\n\n      (** 2-2) Each child subtree (except the requestor) satisfies [ObjsInvalid] *)\n      assert (forall rcidx,\n                 parentIdxOf (fst (tree2Topo tr 0)) rcidx = Some oidx ->\n                 x <> rcidx ->\n                 forall nost rsTo,\n                   ObjsInvalid\n                     (fun idx =>\n                        In idx (subtreeIndsOf (fst (tree2Topo tr 0)) rcidx))\n                     (oss +[oidx <- nost])\n                     (enqMP (downTo x) rsTo (deqMsgs (idsOf rins) msgs))) as Hcsi.\n      { intros.\n        specialize (Hcs _ H40 H41); find_if_inside.\n        { apply in_map_iff in i; destruct i as [[midx rs] ?]; simpl in *; dest; subst.\n          rewrite Forall_forall in H14; specialize (H14 _ H43).\n          rewrite Forall_forall in H23; specialize (H23 _ H43); simpl in *.\n          pose proof (H3 _ H43) as Hrein.\n          disc_AtomicMsgOutsInv rcidx.\n          specialize (H47 eq_refl H23 H14); dest.\n          derive_child_st rcidx.\n          disc_MsgConflictsInv rcidx.\n          rewrite H52 in H47; simpl in H47; dest.\n          solve_ObjsInvalid_trivial.\n\n          eapply ObjsInvalid_in_composed; eauto.\n          { left; repeat split; [simpl; solve_mesi|simpl; rewrite H61; discriminate|].\n            apply NoCohMsgs_rsUps_deq; eauto.\n            { eapply Forall_impl; [|apply Hrss].\n              simpl; intros; dest; eauto.\n            }\n            { apply in_map with (f:= idOf) in H43; assumption. }\n            { rewrite Forall_forall in H17; specialize (H17 _ H43).\n              eapply NoCohMsgs_rsUp_deq; eauto.\n            }\n          }\n          { eapply ObjsInvalid_this_rsUps_deqMsgs_silent; eauto.\n            intro Hx; destruct Hx as [ccidx [? ?]].\n            eapply subtreeIndsOf_child_SubList in H63; eauto.\n            apply parent_not_in_subtree in H40; auto.\n          }\n        }\n        { disc_InvExcl oidx.\n          specialize (H43 (tl_In _ _ H8)).\n          move H43 at bottom.\n          specialize (H43 _ H40); destruct H43 as [? _].\n          specialize (H43 Hcs).\n          solve_ObjsInvalid_trivial.\n          eapply ObjsInvalid_this_rsUps_deqMsgs_silent with (pidx:= oidx); eauto.\n          intro; solve_by_topo_false.\n        }\n      }\n\n      assert (NoRsI oidx msgs) as Hrsi.\n      { move Hidir at bottom.\n        specialize (Hidir oidx); simpl in Hidir.\n        rewrite H15 in Hidir; simpl in Hidir.\n        eapply not_MsgExistsSig_MsgsNotExist; intros;\n          inv H40; [|dest_in].\n        specialize (Hidir (or_intror (or_intror H41))).\n        simpl in *; solve_mesi.\n      }\n\n      (** 2-2) ObjsInvalid, outside [oidx] *)\n      assert (forall nost rsTo,\n                 ObjsInvalid\n                   (fun idx => ~ In idx (subtreeIndsOf (fst (tree2Topo tr 0)) oidx))\n                   (oss +[oidx <- nost])\n                   (enqMP (downTo x) rsTo (deqMsgs (idsOf rins) msgs))) as Hoo.\n      { intros.\n        solve_ObjsInvalid_trivial.\n        eapply ObjsInvalid_this_rsUps_deqMsgs_silent with (pidx:= oidx); eauto;\n          [|intro; solve_by_topo_false].\n        disc_InvExcl oidx.\n        specialize (H41 (tl_In _ _ H8)).\n        apply subtreeChildrenIndsOf_parentIdxOf in H37; auto.\n        specialize (H41 _ H37); destruct H41 as [_ ?].\n        rewrite getDir_excl_eq in H41; [|reflexivity|intuition solve_mesi].\n        specialize (H41 H28).\n        eapply ObjsInvalid_impl; [eassumption|].\n        simpl; intros.\n        intro Hx; elim H42.\n        eapply subtreeIndsOf_child_SubList with (cidx:= dir_excl _); eauto.\n      }\n\n      (** 2-3) The target object itself gets invalid *)\n      assert (forall rsTo,\n                 ObjInvalid0\n                   oidx (fst os,\n                         (false,\n                          (invalidate (fst (snd (snd os))),\n                           (setDirM x, snd (snd (snd (snd os)))))))\n                   (enqMP (downTo x) rsTo (deqMsgs (idsOf rins) msgs))) as Hoi.\n      { intros; repeat split; [simpl; solve_mesi|discriminate|].\n        disc_InvExcl oidx.\n        specialize (H41 (tl_In _ _ H8)).\n        apply subtreeChildrenIndsOf_parentIdxOf in H37; auto.\n        specialize (H41 _ H37); destruct H41 as [_ ?].\n        rewrite getDir_excl_eq in H41; [|reflexivity|intuition solve_mesi].\n        specialize (H41 H28).\n        apply parent_not_in_subtree in H37; auto.\n        specialize (H41 _ H37).\n        rewrite H15 in H41; simpl in H41.\n        solve_MsgsP.\n        disc_MsgConflictsInv oidx.\n        eapply ObjInvalid_NoCohMsgs; eauto.\n      }\n\n      (** 3) Predicate for [mesiRsM] *)\n      assert (ObjsInvalid\n                (fun idx => ~ In idx (subtreeIndsOf (fst (tree2Topo tr 0)) x))\n                (oss +[oidx <- (fst os,\n                                (false,\n                                 (invalidate (fst (snd (snd os))),\n                                  (setDirM x, snd (snd (snd (snd os)))))))])\n                (enqMP (downTo x)\n                       {| msg_id := mesiRsM;\n                          msg_type := MRs;\n                          msg_addr := msg_addr msg;\n                          msg_value := 0 |} (deqMsgs (idsOf rins) msgs))) as Hrc.\n      { intros.\n        eapply ObjsInvalid_out_composed with (oidx:= oidx); eauto.\n        { mred. }\n        { left; apply Hoi. }\n      }\n\n      split.\n      { solve_AtomicInv_rsUps_rsDown Hrsd.\n        red; simpl; intros; inv H40.\n        rewrite <-H13; eapply Hrc.\n      }\n\n      { case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { solve_InvObjExcl0_by_ObjExcl0_false. }\n          { solve_InvObjOwned_by_false. }\n          { split_InvDirInv.\n            { case_idx_eq x cidx;\n                [rewrite getDir_setDirM_eq in H44; discriminate|clear H44].\n              rewrite <-H13; eapply Hcsi; eauto.\n            }\n            { case_idx_eq x cidx;\n                [clear H44\n                |simpl in H44; rewrite getDir_setDirM_neq in H44 by assumption;\n                 solve_mesi].\n              rewrite <-H13; eapply Hrc.\n            }\n          }\n        }\n\n        { pose proof Hpmcf as Hpmcf'; phide Hpmcf'; rename H40 into Hpmcf'.\n          disc_MsgConflictsInv oidx.\n\n          remember (dir_excl _) as cidx; clear Heqcidx.\n          rewrite H38 in H13.\n          destruct rins as [|[midx rmsg] rins]; [discriminate|].\n          destruct rins; [|discriminate].\n          simpl in H13; inv H13.\n\n          (* discharge all predicates in [Forall] *)\n          inv H14; inv H17; inv H23; inv Hrss; dest; simpl in *.\n          clear H47 H48 H49 H50. (* [Forall _ nil] *)\n          inv H14; rename x0 into cidx.\n          derive_child_chns cidx; repeat disc_rule_minds.\n          (* derive the predicate message for it *)\n          apply SubList_cons_inv in H3; dest.\n          disc_AtomicMsgOutsInv cidx.\n\n          derive_child_st cidx.\n          disc_MsgPred.\n          preveal Hpmcf'; disc_MsgConflictsInv cidx.\n\n          disc_InvExcl_others.\n          { disc_InvObjExcl0.\n            rewrite H38 in H71; simpl in H71.\n            eapply ObjExcl0_other_msg_id_deqMP_inv in H71; eauto;\n              [|simpl; rewrite H46; discriminate].\n            specialize (H4 H71); dest.\n            exfalso.\n            case_idx_eq eidx cidx.\n            { disc_rule_conds_ex; disc_ObjExcl0; solve_mesi. }\n            { solve_by_ObjsInvalid_downRsIM_false cidx. }\n          }\n\n          { red; intros [? ?].\n            assert (NoRsI eidx msgs).\n            { disc_MsgsP H72.\n              rewrite H38 in H72; simpl in H72.\n              eapply MsgsP_other_msg_id_deqMP_inv in H72; eauto.\n              simpl; rewrite H46; intuition discriminate.\n            }\n            specialize (H69 (conj H71 H73)); dest.\n\n            case_in_subtree cidx eidx; [|solve_by_ObjsInvalid_downRsIM_false cidx].\n            case_idx_eq eidx cidx; [disc_rule_conds_ex; congruence (* owner true/false *) |].\n            split.\n            { assert (In oidx (subtreeIndsOf (fst (tree2Topo tr 0)) eidx)).\n              { eapply inside_parent_in with (cidx:= cidx); eauto. }\n              solve_ObjsInvalid_trivial.\n              rewrite H38.\n              eapply ObjsInvalid_this_rsUps_deqMsgs_silent with (pidx:= oidx); eauto.\n            }\n            { case_idx_eq x eidx; [|solve_MsgsP].\n              assert (~ In cidx (subtreeIndsOf (fst (tree2Topo tr 0)) eidx)).\n              { intro; solve_by_topo_false. }\n              solve_by_ObjsInvalid_downRsIM_false cidx.\n            }\n          }\n\n          { split_InvDirInv_apply.\n            { case_in_subtree x cidx0.\n              { case_idx_eq x cidx0; [disc_rule_conds|].\n                assert (In oidx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx0)).\n                { eapply inside_parent_in with (cidx:= x); eauto. }\n                assert (In cidx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx0)).\n                { eapply inside_child_in; eauto. }\n                solve_by_ObjsInvalid_downRsIM_false cidx.\n              }\n              { case_in_subtree cidx cidx0; [solve_by_ObjsInvalid_downRsIM_false cidx|].\n                solve_ObjsInvalid_trivial.\n                rewrite H38.\n                eapply ObjsInvalid_this_rsUps_deqMsgs_silent with (pidx:= oidx); eauto.\n                intro; solve_by_topo_false.\n              }\n            }\n            { case_in_subtree cidx cidx0;\n                [|solve_by_ObjsInvalid_downRsIM_false cidx].\n              case_idx_eq cidx cidx0; [disc_rule_conds|].\n              assert (In oidx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx0)).\n              { eapply inside_parent_in with (cidx:= cidx); eauto. }\n              solve_ObjsInvalid_trivial.\n              rewrite H38.\n              eapply ObjsInvalid_this_rsUps_deqMsgs_silent with (pidx:= oidx); eauto.\n            }\n          }\n        }\n      }\n    }\n\n    { (* [liDownIImmS] *)\n      disc_rule_conds_ex.\n      derive_NoRsI_by_rqDown oidx msgs.\n\n      split.\n      { solve_AtomicInv_rqDown_rsUp.\n        { simpl in *; inv H17; mred.\n          simpl; intuition solve_mesi.\n        }\n        { simpl in *; inv H17; mred.\n          disc_MsgConflictsInv oidx0.\n          disc_InvExcl oidx0.\n          eapply ObjsInvalid_downRsIS; eauto.\n          { apply tl_In; assumption. }\n          { assumption. }\n          { simpl; solve_mesi. }\n        }\n      }\n\n      { case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { solve_InvObjExcl0_by_ObjExcl0_false. }\n          { solve_InvObjOwned_by_false. }\n          { split_InvDirInv_apply.\n            { solve_ObjsInvalid_trivial. }\n            { exfalso; disc_dir; solve_mesi. }\n          }\n        }\n        { disc_InvExcl_others.\n          { disc_InvObjExcl0_apply.\n            split; [|solve_MsgsP].\n            solve_ObjsInvalid_trivial.\n            eapply ObjsInvalid_state_transition_sound; eauto.\n            simpl; solve_mesi.\n          }\n          { disc_InvObjOwned.\n            split; [|solve_MsgsP].\n            solve_ObjsInvalid_trivial.\n            eapply ObjsInvalid_state_transition_sound; eauto.\n            simpl; solve_mesi.\n          }\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx.\n              { solve_ObjsInvalid_trivial.\n                eapply ObjsInvalid_state_transition_sound; eauto.\n                simpl; solve_mesi.\n              }\n              { solve_ObjsInvalid_trivial. }\n            }\n            { case_in_subtree oidx cidx.\n              { solve_ObjsInvalid_trivial. }\n              { solve_ObjsInvalid_trivial.\n                eapply ObjsInvalid_state_transition_sound; eauto.\n                simpl; solve_mesi.\n              }\n            }\n          }\n        }\n      }\n    }\n\n    { (* [liDownIImmME] *)\n      disc_rule_conds_ex.\n      derive_NoRsI_by_rqDown oidx msgs.\n\n      split.\n      { solve_AtomicInv_rqDown_rsUp.\n        { simpl in *; inv H17; mred.\n          simpl; intuition solve_mesi.\n        }\n        { simpl in *; inv H17; mred.\n          disc_MsgConflictsInv oidx0.\n          disc_InvExcl oidx0.\n          eapply ObjsInvalid_downRsIM; eauto.\n          { apply tl_In; assumption. }\n          { assumption. }\n        }\n      }\n\n      { case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { solve_InvObjExcl0_by_ObjExcl0_false. }\n          { solve_InvObjOwned_by_false. }\n          { split_InvDirInv_apply.\n            { solve_ObjsInvalid_trivial. }\n            { exfalso; disc_dir; solve_mesi. }\n          }\n        }\n        { disc_InvExcl_others.\n          { disc_InvObjExcl0_apply.\n            disc_MsgConflictsInv oidx.\n            solve_by_ObjsInvalid_status_false oidx.\n          }\n          { case_InvObjOwned.\n            { solve_by_ObjsInvalid_status_false oidx. }\n            { disc_ObjsInvalid_by oidx0.\n              case_ObjInvalid; [solve_ObjInvalid0|solve_ObjInvRs].\n            }\n            { solve_MsgsP. }\n          }\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx.\n              { solve_by_ObjsInvalid_status_false oidx. }\n              { solve_ObjsInvalid_trivial. }\n            }\n            { case_in_subtree oidx cidx.\n              { solve_ObjsInvalid_trivial. }\n              { solve_by_ObjsInvalid_status_false oidx. }\n            }\n          }\n        }\n      }\n    }\n\n    { (* [liDownIRqDownDownDirS] *)\n      disc_rule_conds_ex; split.\n      { solve_AtomicInv_rqDown_rqDowns.\n        { apply Forall_forall; intros.\n          apply in_map_iff in H14; dest; subst.\n          apply in_map_iff in H17; dest; subst.\n          apply H25 in H17.\n          apply subtreeChildrenIndsOf_parentIdxOf in H17; auto.\n          derive_child_chns x.\n          eauto.\n        }\n        { apply Forall_forall; intros.\n          apply in_map_iff in H14; dest; subst.\n          repeat constructor; try (red; simpl; intros; intuition discriminate).\n        }\n      }\n      { solve_InvExcl_trivial. }\n    }\n\n    { (* [liDownIRqDownDownDirME] *)\n      disc_rule_conds_ex; split.\n      { solve_AtomicInv_rqDown_rqDowns.\n        remember (dir_excl _) as cidx; clear Heqcidx.\n        apply subtreeChildrenIndsOf_parentIdxOf in H23; auto.\n        derive_child_chns cidx.\n        repeat constructor; simpl; eauto.\n      }\n      { solve_InvExcl_trivial. }\n    }\n\n    { (* [liDownIRqDownDownDirMES] *)\n      disc_rule_conds_ex; split.\n      { solve_AtomicInv_rqDown_rqDowns.\n        { apply Forall_forall; intros.\n          apply in_map_iff in H14; dest; subst.\n          apply in_map_iff in H17; dest; subst.\n          apply H25 in H17.\n          apply subtreeChildrenIndsOf_parentIdxOf in H17; auto.\n          derive_child_chns x.\n          eauto.\n        }\n        { apply Forall_forall; intros.\n          apply in_map_iff in H14; dest; subst.\n          repeat constructor; try (red; simpl; intros; intuition discriminate).\n        }\n      }\n      { solve_InvExcl_trivial. }\n    }\n\n    { (* [liDownIRsUpUpS] *)\n      disc_rule_conds_ex.\n      disc_MesiDownLockInv oidx Hdlinv.\n      derive_footprint_info_basis oidx; [solve_midx_false|].\n\n      (** 1) Each RsUp message is from a child *)\n      assert (Forall\n                (fun midx =>\n                   exists rcidx,\n                     parentIdxOf (fst (tree2Topo tr 0)) rcidx = Some oidx /\\\n                     midx = rsUpFrom rcidx)\n                (idsOf rins)) as Hrss.\n      { apply Forall_forall; intros rsUp ?.\n        eapply RqRsDownMatch_rs_rq in H33; [|rewrite <-H13; eassumption].\n        destruct H33 as [cidx [down ?]]; dest.\n        derive_child_chns cidx; repeat disc_rule_minds.\n        eauto.\n      }\n\n      (** 2-1) Each child either sent RsUp or is in DirI *)\n      assert (forall rcidx,\n                 parentIdxOf (fst (tree2Topo tr 0)) rcidx = Some oidx ->\n                 if in_dec idx_dec (rsUpFrom rcidx) (idsOf rins)\n                 then True\n                 else getDir rcidx os#[dir] = mesiI) as Hcs.\n      { intros.\n        destruct (in_dec idx_dec rcidx (dir_sharers (fst (snd (snd (snd os)))))).\n        { find_if_inside; [auto|].\n          elim n; rewrite H13, H29; apply in_map; assumption.\n        }\n        { find_if_inside; [auto|apply getDir_S_non_sharer; assumption]. }\n      }\n\n      (** 2-2) Each child subtree satisfies [ObjsInvalid] *)\n      assert (forall rcidx,\n                 parentIdxOf (fst (tree2Topo tr 0)) rcidx = Some oidx ->\n                 forall nost rsTo,\n                   ObjsInvalid\n                     (fun idx =>\n                        In idx (subtreeIndsOf (fst (tree2Topo tr 0)) rcidx))\n                     (oss +[oidx <- nost])\n                     (enqMP (rsUpFrom oidx) rsTo (deqMsgs (idsOf rins) msgs))) as Hcsi.\n      { intros.\n        specialize (Hcs _ H31); find_if_inside.\n        { apply in_map_iff in i; destruct i as [[midx rs] ?]; simpl in *; dest; subst.\n          rewrite Forall_forall in H14; specialize (H14 _ H34).\n          rewrite Forall_forall in H23; specialize (H23 _ H34); simpl in *.\n          pose proof (H3 _ H34) as Hrein.\n          disc_AtomicMsgOutsInv rcidx.\n          specialize (H38 eq_refl H23 H14); dest.\n          derive_child_st rcidx.\n          disc_MsgConflictsInv rcidx.\n          rewrite H44 in H38; simpl in H38; dest.\n          solve_ObjsInvalid_trivial.\n          eapply ObjsInvalid_this_rsUps_deqMsgs_silent; eauto.\n          apply parent_not_in_subtree; auto.\n        }\n        { disc_InvExcl oidx.\n          specialize (H34 (tl_In _ _ H8)).\n          move H34 at bottom.\n          specialize (H34 _ H31); destruct H34 as [? _].\n          specialize (H34 Hcs).\n          solve_ObjsInvalid_trivial.\n          eapply ObjsInvalid_this_rsUps_deqMsgs_silent with (pidx:= oidx); eauto.\n          intro; solve_by_topo_false.\n        }\n      }\n\n      (** 2-3) The target object itself gets invalid *)\n      assert (ObjInvalid0\n                oidx (fst os,\n                      (false,\n                       (invalidate (fst (snd (snd os))),\n                        (setDirI, snd (snd (snd (snd os)))))))\n                (enqMP (rsUpFrom oidx)\n                       {| msg_id := mesiDownRsIS;\n                          msg_type := MRs;\n                          msg_addr := msg_addr msg;\n                          msg_value := 0 |}\n                       (deqMsgs (idsOf rins) msgs))) as Hoi.\n      { intros; repeat split; [simpl; solve_mesi|discriminate|].\n        clear Hpmcf; preveal Hnmcf.\n        assert ((orqs +[oidx <- porq -[downRq]])@[oidx] = Some (porq -[downRq]))\n          by mred.\n        disc_MsgConflictsInv oidx.\n        rewrite H13.\n        eapply NoCohMsgs_rsUp_in; eauto.\n        { apply InMP_or_enqMP; left; auto. }\n        { discriminate. }\n        { discriminate. }\n      }\n\n      (** 3) Predicate for [mesiDownRsIS] *)\n      assert (ObjsInvalid\n                (fun idx => In idx (subtreeIndsOf (fst (tree2Topo tr 0)) oidx))\n                (oss +[oidx <- (fst os,\n                                (false,\n                                 (invalidate (fst (snd (snd os))),\n                                  (setDirI, snd (snd (snd (snd os)))))))])\n                (enqMP (rsUpFrom oidx)\n                       {| msg_id := mesiDownRsIS;\n                          msg_type := MRs;\n                          msg_addr := msg_addr msg;\n                          msg_value := 0 |}\n                       (deqMsgs (idsOf rins) msgs))) as Hrc.\n      { intros; eapply ObjsInvalid_in_composed; [mred|..].\n        { left; apply Hoi. }\n        { intros; eapply ObjsInvalid_downRsIM_composed; [mred|eauto]. }\n      }\n\n      assert (NoRsI oidx msgs) as Hrsi.\n      { move Hidir at bottom.\n        specialize (Hidir oidx); simpl in Hidir.\n        rewrite H15 in Hidir; simpl in Hidir.\n        eapply not_MsgExistsSig_MsgsNotExist; intros;\n          inv H31; [|dest_in].\n        specialize (Hidir (or_intror (or_intror H32))).\n        simpl in *; solve_mesi.\n      }\n\n      split.\n      { rewrite <-H13.\n        solve_AtomicInv_rsUps_rsUp.\n        { simpl in *; inv H31; mred; simpl; intuition solve_mesi. }\n        { simpl in *; inv H31; apply Hrc. }\n      }\n\n      { case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { solve_InvObjExcl0_by_ObjExcl0_false. }\n          { solve_InvObjOwned_by_false. }\n          { split_InvDirInv.\n            { rewrite <-H13; eapply Hcsi; eauto. }\n            { exfalso.\n              simpl in H37; rewrite getDir_setDirI in H37.\n              solve_mesi.\n            }\n          }\n        }\n\n        { disc_InvExcl_others.\n          { disc_InvObjExcl0.\n            rewrite <-H13 in H35.\n            apply ObjExcl0_other_msg_id_deqMsgs_inv in H35; auto.\n            2: { eapply Forall_impl; [|apply H14]; simpl; intros.\n                 rewrite H36; discriminate.\n            }\n            specialize (H4 H35); dest.\n            exfalso.\n            disc_ObjsInvalid_by oidx.\n            rewrite H15 in H37; simpl in H37.\n            destruct H37.\n            { destruct H37 as [? [? ?]]; auto. }\n            { eapply NoRsI_MsgExistsSig_InvRs_false; eauto. }\n          }\n\n          { red; intros [? ?].\n            assert (NoRsI eidx msgs).\n            { disc_MsgsP H36.\n              rewrite <-H13 in H36; simpl in H36.\n              apply MsgsP_other_msg_id_deqMsgs_inv in H36; auto.\n              simpl; apply (DisjList_spec_2 idx_dec); intros; dest_in.\n              intro; dest_in.\n              apply in_map_iff in H37; destruct H37 as [[rmidx rmsg] [? ?]]; simpl in *.\n              rewrite Forall_forall in H14; specialize (H14 _ H38); simpl in *.\n              rewrite H14 in H37; discriminate.\n            }\n            specialize (H32 (conj H35 H37)); dest.\n\n            case_in_subtree oidx eidx;\n              [|clear Hrc; solve_by_ObjsInvalid_dir_false oidx].\n            split.\n            { solve_ObjsInvalid_trivial.\n              rewrite <-H13.\n              eapply ObjsInvalid_this_rsUps_deqMsgs_silent with (pidx:= oidx); eauto.\n            }\n            { solve_MsgsP. }\n          }\n\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx.\n              { clear Hrc; solve_by_ObjsInvalid_dir_false oidx. }\n              { solve_ObjsInvalid_trivial.\n                rewrite <-H13.\n                eapply ObjsInvalid_this_rsUps_deqMsgs_silent with (pidx:= oidx); eauto.\n              }\n            }\n            { case_in_subtree oidx cidx.\n              { solve_ObjsInvalid_trivial.\n                rewrite <-H13.\n                eapply ObjsInvalid_this_rsUps_deqMsgs_silent with (pidx:= oidx); eauto.\n              }\n              { clear Hrc; solve_by_ObjsInvalid_dir_false oidx. }\n            }\n          }\n        }\n      }\n    }\n\n    { (* [liDownIRsUpUpME] *)\n      disc_rule_conds_ex.\n      disc_MesiDownLockInv oidx Hdlinv.\n      derive_footprint_info_basis oidx; [solve_midx_false|].\n\n      destruct H27; [solve_mesi; fail|simpl in *; dest].\n      rewrite H30 in *; simpl in *; disc_rule_conds.\n\n      (** 1) Each RsUp message is from a child *)\n      assert (Forall\n                (fun midx =>\n                   exists rcidx,\n                     parentIdxOf (fst (tree2Topo tr 0)) rcidx = Some oidx /\\\n                     midx = rsUpFrom rcidx)\n                (map fst (rqi_rss rqi))) as Hrss.\n      { apply Forall_forall; intros rsUp ?.\n        eapply RqRsDownMatch_rs_rq in H31; [|eassumption].\n        destruct H31 as [cidx [down ?]]; dest.\n        derive_child_chns cidx; repeat disc_rule_minds.\n        eauto.\n      }\n\n      (** 2-1) Each child either sent RsUp or is in DirI *)\n      assert (forall rcidx,\n                 parentIdxOf (fst (tree2Topo tr 0)) rcidx = Some oidx ->\n                 if in_dec idx_dec (rsUpFrom rcidx) (map fst (rqi_rss rqi))\n                 then True\n                 else getDir rcidx os#[dir] = mesiI) as Hcs.\n      { intros.\n        find_if_inside; [auto|].\n        rewrite H30 in n.\n        eapply getDir_excl_neq; eauto.\n        intro Hx; subst.\n        elim n; left; reflexivity.\n      }\n\n      remember (dir_excl _) as ecidx; clear Heqecidx.\n      apply subtreeChildrenIndsOf_parentIdxOf in H29; auto.\n\n      (** 2-2) Each child subtree satisfies [ObjsInvalid] *)\n      assert (forall rcidx,\n                 parentIdxOf (fst (tree2Topo tr 0)) rcidx = Some oidx ->\n                 forall nost rsTo,\n                   ObjsInvalid\n                     (fun idx =>\n                        In idx (subtreeIndsOf (fst (tree2Topo tr 0)) rcidx))\n                     (oss +[oidx <- nost])\n                     (enqMP (rsUpFrom oidx) rsTo (deqMP (rsUpFrom ecidx) msgs)))\n        as Hcsi.\n      { intros.\n        specialize (Hcs _ H14); find_if_inside.\n        { rewrite H30 in i; dest_in; inv H17.\n          disc_AtomicMsgOutsInv rcidx.\n          specialize (H39 eq_refl H34 H33); dest.\n          derive_child_st rcidx.\n          disc_MsgConflictsInv rcidx.\n          rewrite H44 in H39; simpl in H39; dest.\n          solve_ObjsInvalid_trivial.\n\n          eapply ObjsInvalid_in_composed; eauto.\n          { left; repeat split; [simpl; solve_mesi|intro Hx; simpl in Hx; solve_mesi|].\n            eapply NoCohMsgs_rsUp_deq; eauto.\n          }\n          { eapply ObjsInvalid_this_rsUps_deqMsgs_silent with (rminds := [_]); eauto.\n            intro Hx; destruct Hx as [ccidx [? ?]].\n            eapply subtreeIndsOf_child_SubList in H55; eauto.\n            eapply parent_not_in_subtree in H55; eauto.\n          }\n        }\n        { disc_InvExcl oidx.\n          specialize (H35 (tl_In _ _ H8)).\n          move H35 at bottom.\n          specialize (H35 _ H14); destruct H35 as [? _].\n          specialize (H35 Hcs).\n          solve_ObjsInvalid_trivial.\n          eapply ObjsInvalid_this_rsUps_deqMsgs_silent with (pidx:= oidx) (rminds:= [_]); eauto.\n          intro; solve_by_topo_false.\n        }\n      }\n\n      (** 3) Predicate for [mesiDownRsIM] *)\n      assert (forall nost rsTo,\n                 ObjsInvalid\n                   (fun idx =>\n                      exists cidx,\n                        parentIdxOf (fst (tree2Topo tr 0)) cidx = Some oidx /\\\n                        In idx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx))\n                   (oss +[oidx <- nost])\n                   (enqMP (rsUpFrom oidx) rsTo (deqMP (rsUpFrom ecidx) msgs))) as Hrc.\n      { intros; eapply ObjsInvalid_downRsIM_composed; [mred|eauto]. }\n\n      split.\n      { solve_AtomicInv_rsUps_rsUp.\n        { simpl in *; inv H14; mred; simpl; intuition solve_mesi. }\n        { simpl in *; inv H14; apply Hrc. }\n      }\n\n      { case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { solve_InvObjExcl0_by_ObjExcl0_false. }\n          { solve_InvObjOwned_by_false. }\n          { split_InvDirInv.\n            { eapply Hcsi; eauto. }\n            { exfalso.\n              simpl in H38; rewrite getDir_setDirI in H38.\n              solve_mesi.\n            }\n          }\n        }\n\n        { pose proof Hpmcf as Hpmcf'; phide Hpmcf'; rename H14 into Hpmcf'.\n          disc_MsgConflictsInv oidx.\n\n          (* discharge all predicates in [Forall] *)\n          derive_child_chns ecidx; repeat disc_rule_minds.\n          (* derive the predicate message for it *)\n          disc_AtomicMsgOutsInv ecidx.\n\n          derive_child_st ecidx.\n          disc_MsgPred.\n          preveal Hpmcf'; disc_MsgConflictsInv ecidx.\n\n          disc_InvExcl_others.\n          { disc_InvObjExcl0_apply.\n            exfalso.\n            case_idx_eq eidx ecidx.\n            { disc_rule_conds; disc_ObjExcl0; solve_mesi. }\n            { solve_by_ObjsInvalid_downRsIM_false ecidx. }\n          }\n          { disc_InvObjOwned.\n            case_in_subtree ecidx eidx; [|solve_by_ObjsInvalid_downRsIM_false ecidx].\n            case_idx_eq eidx ecidx; [disc_rule_conds_ex; congruence|].\n            split.\n            { assert (In oidx (subtreeIndsOf (fst (tree2Topo tr 0)) eidx)).\n              { eapply inside_parent_in with (cidx:= ecidx); eauto. }\n              solve_ObjsInvalid_trivial.\n            }\n            { solve_MsgsP. }\n          }\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx.\n              { assert (In ecidx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx)).\n                { eapply inside_child_in; eauto. }\n                solve_by_ObjsInvalid_downRsIM_false ecidx.\n              }\n              { case_in_subtree ecidx cidx; [solve_by_ObjsInvalid_downRsIM_false ecidx|].\n                solve_ObjsInvalid_trivial.\n              }\n            }\n            { case_in_subtree ecidx cidx;\n                [|solve_by_ObjsInvalid_downRsIM_false ecidx].\n              case_idx_eq ecidx cidx; [disc_rule_conds|].\n              assert (In oidx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx)).\n              { eapply inside_parent_in with (cidx:= ecidx); eauto. }\n              solve_ObjsInvalid_trivial.\n            }\n          }\n        }\n      }\n    }\n\n    { (* [liDownIRsUpUpMES] *)\n      disc_rule_conds_ex.\n      disc_MesiDownLockInv oidx Hdlinv.\n      derive_footprint_info_basis oidx; [solve_midx_false|].\n      destruct H27; [simpl in *; dest|solve_mesi; fail].\n\n      (** 1) Each RsUp message is from a child *)\n      assert (Forall\n                (fun midx =>\n                   exists rcidx,\n                     parentIdxOf (fst (tree2Topo tr 0)) rcidx = Some oidx /\\\n                     midx = rsUpFrom rcidx)\n                (map fst (rqi_rss rqi))) as Hrss.\n      { apply Forall_forall; intros rsUp ?.\n        eapply RqRsDownMatch_rs_rq in H31; [|eassumption].\n        destruct H31 as [cidx [down ?]]; dest.\n        derive_child_chns cidx; repeat disc_rule_minds.\n        eauto.\n      }\n\n      (** 2-1) Each child either sent RsUp or is in DirI *)\n      assert (forall rcidx,\n                 parentIdxOf (fst (tree2Topo tr 0)) rcidx = Some oidx ->\n                 if in_dec idx_dec (rsUpFrom rcidx) (map fst (rqi_rss rqi))\n                 then True\n                 else getDir rcidx os#[dir] = mesiI) as Hcs.\n      { intros.\n        destruct (in_dec idx_dec rcidx (dir_sharers (fst (snd (snd (snd os)))))).\n        { find_if_inside; [auto|].\n          elim n; rewrite H30; apply in_map; assumption.\n        }\n        { find_if_inside; [auto|].\n          apply getDir_S_non_sharer; [assumption|].\n          intro Hx; elim n; assumption.\n        }\n      }\n\n      (** 2-2) Each child subtree satisfies [ObjsInvalid] *)\n      assert (forall rcidx,\n                 parentIdxOf (fst (tree2Topo tr 0)) rcidx = Some oidx ->\n                 forall nost rsTo,\n                   ObjsInvalid\n                     (fun idx =>\n                        In idx (subtreeIndsOf (fst (tree2Topo tr 0)) rcidx))\n                     (oss +[oidx <- nost])\n                     (enqMP (rsUpFrom oidx) rsTo (deqMsgs (map fst (rqi_rss rqi)) msgs))) as Hcsi.\n      { rewrite <-H13 in *; intros.\n        specialize (Hcs _ H32); find_if_inside.\n        { apply in_map_iff in i; destruct i as [[midx rs] ?]; simpl in *; dest; subst.\n          rewrite Forall_forall in H14; specialize (H14 _ H34).\n          rewrite Forall_forall in H23; specialize (H23 _ H34); simpl in *.\n          pose proof (H3 _ H34) as Hrein.\n          disc_AtomicMsgOutsInv rcidx.\n          specialize (H38 eq_refl H23 H14); dest.\n          derive_child_st rcidx.\n          disc_MsgConflictsInv rcidx.\n          rewrite H44 in H38; simpl in H38; dest.\n          solve_ObjsInvalid_trivial.\n          eapply ObjsInvalid_this_rsUps_deqMsgs_silent; eauto.\n          apply parent_not_in_subtree; auto.\n        }\n        { disc_InvExcl oidx.\n          specialize (H34 (tl_In _ _ H8)).\n          move H34 at bottom.\n          specialize (H34 _ H32); destruct H34 as [? _].\n          specialize (H34 Hcs).\n          solve_ObjsInvalid_trivial.\n          eapply ObjsInvalid_this_rsUps_deqMsgs_silent with (pidx:= oidx); eauto.\n          intro; solve_by_topo_false.\n        }\n      }\n\n      (** 3) Predicate for [mesiDownRsIM] *)\n      assert (forall nost rsTo,\n                 ObjsInvalid\n                   (fun idx =>\n                      exists cidx,\n                        parentIdxOf (fst (tree2Topo tr 0)) cidx = Some oidx /\\\n                        In idx (subtreeIndsOf (fst (tree2Topo tr 0)) cidx))\n                   (oss +[oidx <- nost])\n                   (enqMP (rsUpFrom oidx) rsTo\n                          (deqMsgs (map fst (rqi_rss rqi)) msgs))) as Hrc.\n      { intros; eapply ObjsInvalid_downRsIM_composed; [mred|auto]. }\n\n      assert (NoRsI oidx msgs) as Hrsi.\n      { move Hidir at bottom.\n        specialize (Hidir oidx); simpl in Hidir.\n        rewrite H15 in Hidir; simpl in Hidir.\n        eapply not_MsgExistsSig_MsgsNotExist; intros;\n          inv H32; [|dest_in].\n        specialize (Hidir (or_intror (or_intror H33))).\n        simpl in *; solve_mesi.\n      }\n\n      split.\n      { rewrite <-H13.\n        solve_AtomicInv_rsUps_rsUp.\n        { simpl in *; inv H32; mred; simpl; intuition solve_mesi. }\n        { simpl in *; inv H32.\n          rewrite H13; apply Hrc.\n        }\n      }\n\n      { case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { solve_InvObjExcl0_by_ObjExcl0_false. }\n          { solve_InvObjOwned_by_false. }\n          { split_InvDirInv.\n            { eapply Hcsi; eauto. }\n            { exfalso.\n              simpl in H37; rewrite getDir_setDirI in H37.\n              solve_mesi.\n            }\n          }\n        }\n\n\n        { disc_InvExcl_others.\n          { disc_InvObjExcl0.\n            rewrite <-H13 in H35.\n            apply ObjExcl0_other_msg_id_deqMsgs_inv in H35; auto.\n            2: { eapply Forall_impl; [|apply H14]; simpl; intros.\n                 rewrite H36; discriminate.\n            }\n            specialize (H4 H35); dest.\n            exfalso.\n            disc_ObjsInvalid_by oidx.\n            rewrite H15 in H37; simpl in H37.\n            destruct H37.\n            { destruct H37 as [? [? ?]]; auto. }\n            { eapply NoRsI_MsgExistsSig_InvRs_false; eauto. }\n          }\n\n          { red; intros [? ?].\n            assert (NoRsI eidx msgs).\n            { disc_MsgsP H36.\n              rewrite <-H13 in H36; simpl in H36.\n              apply MsgsP_other_msg_id_deqMsgs_inv in H36; auto.\n              simpl; apply (DisjList_spec_2 idx_dec); intros; dest_in.\n              intro; dest_in.\n              apply in_map_iff in H37; destruct H37 as [[rmidx rmsg] [? ?]]; simpl in *.\n              rewrite Forall_forall in H14; specialize (H14 _ H38); simpl in *.\n              rewrite H14 in H37; discriminate.\n            }\n            specialize (H33 (conj H35 H37)); dest.\n\n            case_in_subtree oidx eidx;\n              [|clear Hrc; solve_by_ObjsInvalid_dir_false oidx].\n            split.\n            { solve_ObjsInvalid_trivial.\n              eapply ObjsInvalid_this_rsUps_deqMsgs_silent with (pidx:= oidx); eauto.\n            }\n            { solve_MsgsP. }\n          }\n\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx.\n              { clear Hrc; solve_by_ObjsInvalid_dir_false oidx. }\n              { solve_ObjsInvalid_trivial.\n                eapply ObjsInvalid_this_rsUps_deqMsgs_silent with (pidx:= oidx); eauto.\n              }\n            }\n            { case_in_subtree oidx cidx.\n              { solve_ObjsInvalid_trivial.\n                eapply ObjsInvalid_this_rsUps_deqMsgs_silent with (pidx:= oidx); eauto.\n              }\n              { clear Hrc; solve_by_ObjsInvalid_dir_false oidx. }\n            }\n          }\n        }\n      }\n    }\n\n    { (* [liInvRqUpUp] *)\n      disc_rule_conds_ex; split.\n      { exfalso; destruct rins; [auto|discriminate]. }\n      { solve_InvExcl_trivial. }\n    }\n\n    { (* [liInvRqUpUpWB] *)\n      disc_rule_conds_ex; split.\n      { exfalso; destruct rins; [auto|discriminate]. }\n      { solve_InvExcl_trivial. }\n    }\n\n    { (* [liInvRsDownDown] *)\n      disc_rule_conds_ex.\n      derive_footprint_info_basis oidx.\n      disc_MsgConflictsInv oidx.\n\n      assert (os#[dir].(dir_st) = mesiI) as Hdir.\n      { move Hidir at bottom.\n        specialize (Hidir oidx); simpl in Hidir.\n        rewrite H15 in Hidir; simpl in Hidir.\n        apply Hidir.\n        do 2 right.\n        exists (downTo oidx, rmsg); split.\n        { apply FirstMP_InMP; assumption. }\n        { unfold sigOf; simpl; congruence. }\n      }\n\n      split.\n      { solve_AtomicInv_rsDown. }\n      { case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { solve_InvObjExcl0_by_ObjExcl0_false. }\n          { solve_InvObjOwned_by_false. }\n          { split_InvDirInv_apply.\n            { solve_ObjsInvalid_trivial. }\n            { eapply ObjsInvalid_invRs; eauto.\n              apply parent_not_in_subtree; auto.\n            }\n          }\n        }\n\n        { disc_InvExcl_others.\n          { disc_InvObjExcl0_apply; split.\n            { eapply ObjsInvalid_invRs; eauto. }\n            { solve_MsgsP. }\n          }\n          { case_InvObjOwned.\n            { left.\n              red; simpl; repeat split; [solve_mesi|rewrite Hdir; discriminate|].\n              eapply NoCohMsgs_rsDown_deq; eauto.\n            }\n            { disc_ObjsInvalid_by oidx0.\n              case_ObjInvalid; [solve_ObjInvalid0|solve_ObjInvRs].\n            }\n            { solve_MsgsP. }\n          }\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx.\n              { eapply ObjsInvalid_invRs; eauto. }\n              { solve_ObjsInvalid_trivial. }\n            }\n            { case_in_subtree oidx cidx.\n              { solve_ObjsInvalid_trivial. }\n              { eapply ObjsInvalid_invRs; eauto. }\n            }\n          }\n        }\n      }\n    }\n\n    { (* [liDropImm] *)\n      disc_rule_conds_ex; split.\n      { exfalso; destruct rins; [auto|discriminate]. }\n      { eapply InvExcl_state_transition_sound with (porqs:= orqs);\n          try eassumption.\n        { simpl; intuition solve_mesi. }\n        { simpl; intuition. }\n        { reflexivity. }\n      }\n    }\n\n    Unshelve.\n    all: assumption.\n\n    END_SKIP_PROOF_ON *) admit.\n  Qed.\n\n  Lemma mesi_InvExcl_InvTrs_l1:\n    forall ist1,\n      Reachable (steps step_m) impl ist1 ->\n      forall inits,\n        SubList (idsOf inits) (sys_merqs impl) ->\n        forall ins hst outs eouts oidx ridx rins routs,\n          Atomic inits ins hst outs eouts ->\n          rins <> nil ->\n          SubList rins eouts ->\n          forall (Hrsd: forall (oidx : IdxT) (rsDown : Id Msg),\n                     In rsDown (removeL (id_dec msg_dec) eouts rins ++ routs) ->\n                     RsDownMsgTo topo oidx rsDown ->\n                     removeL (id_dec msg_dec) eouts rins ++ routs = [rsDown])\n                 st2 ist2,\n            InvExcl topo cifc st2 ->\n            AtomicInv InvExclMsgOutPred inits ist1 hst eouts st2 ->\n            steps step_m impl ist1 hst st2 ->\n            step_m impl st2 (RlblInt oidx ridx rins routs) ist2 ->\n            forall (Hr1: Reachable (steps step_m) impl st2)\n                   (Hr2: Reachable (steps step_m) impl ist2)\n                   (Hoin: In oidx (map obj_idx (map l1 (c_l1_indices (snd (tree2Topo tr 0)))))),\n              AtomicInv InvExclMsgOutPred inits ist1 (RlblInt oidx ridx rins routs :: hst)\n                        (removeL (id_dec msg_dec) eouts rins ++ routs) ist2 /\\\n              InvExcl topo cifc ist2.\n  Proof. (* SKIP_PROOF_ON\n    intros.\n    pose proof (tree2Topo_TreeTopoNode tr 0) as Htn.\n    pose proof (footprints_ok\n                  (mesi_GoodORqsInit Htr)\n                  (mesi_GoodRqRsSys Htr) Hr1) as Hftinv.\n    pose proof (mesi_InvL1DirI_ok Hr1) as Hdiri.\n    pose proof (mesi_InObjInds Hr1) as Hioi1.\n    pose proof (mesi_InObjInds Hr2) as Hioi2.\n    pose proof (mesi_OstInds Hr1) as Hosi.\n    pose proof (mesi_MsgConflictsInv\n                  (@mesi_RootChnInv_ok _ Htr) Hr1) as Hpmcf.\n    pose proof (@MesiUpLockInv_ok _ Htr _ Hr1) as Hulinv.\n    pose proof (@MesiDownLockInv_ok _ Htr _ Hr1) as Hdlinv.\n\n    inv_step.\n\n    simpl in H12; destruct H12; [subst|apply in_app_or in H7; destruct H7].\n    1: {\n      exfalso; simpl in Hoin.\n      rewrite map_map in Hoin; simpl in Hoin; rewrite map_id in Hoin.\n      eapply tree2Topo_root_not_in_l1; eauto.\n    }\n    1: {\n      exfalso; simpl in Hoin.\n      apply in_map_iff in H7; destruct H7 as [oidx [? ?]]; subst.\n      rewrite map_map in Hoin; simpl in Hoin; rewrite map_id in Hoin.\n      pose proof (tree2Topo_WfCIfc tr 0) as [? _].\n      apply (DisjList_NoDup idx_dec) in H7.\n      eapply DisjList_In_1; eauto.\n      apply tl_In; assumption.\n    }\n\n    (*! Cases for L1 caches *)\n    apply in_map_iff in H7; destruct H7 as [oidx [? ?]]; subst.\n\n    pose proof (c_l1_indices_has_parent Htr _ _ H8).\n    destruct H7 as [pidx [? ?]].\n    pose proof (Htn _ _ H9); dest.\n\n    (** The object index does not belong to [c_li_indices]. *)\n    assert (~ In oidx (c_li_indices (snd (tree2Topo tr 0)))) as Hnli.\n    { pose proof (tree2Topo_WfCIfc tr 0) as [? _].\n      apply (DisjList_NoDup idx_dec) in H14.\n      eapply DisjList_In_1; eassumption.\n    }\n\n    (** Do case analysis per a rule. *)\n    dest_in.\n\n    { (* [l1GetSImm] *)\n      disc_rule_conds_ex; exfalso; disc_AtomicMsgOutsInv (l1ExtOf oidx); eauto.\n    }\n\n    { (* [l1GetSRqUpUp] *)\n      disc_rule_conds_ex; exfalso; disc_AtomicMsgOutsInv (l1ExtOf oidx); eauto.\n    }\n\n    { (* [l1GetSRsDownDownS] *)\n      disc_rule_conds_ex.\n      derive_footprint_info_basis oidx.\n      derive_child_chns cidx.\n      disc_rule_conds_ex.\n\n      split.\n      { solve_AtomicInv_rsDown. }\n      { solve_InvExcl_trivial.\n        case_InvExcl_me_others.\n        { disc_InvExcl_this; [solve_InvObjExcl0_by_ObjExcl0_false| |].\n          { case_InvObjOwned.\n            { solve_by_topo_false. }\n            { disc_ObjsInvalid_by oidx0.\n              case_ObjInvalid_with (l1ExtOf oidx).\n              { solve_by_topo_false. }\n              { case_ObjInvalid; [solve_ObjInvalid0|solve_ObjInvRs]. }\n            }\n            { solve_MsgsP. }\n          }\n          { red; intros; exfalso; auto. }\n        }\n\n        { disc_InvExcl_others.\n          { disc_InvObjExcl0_apply.\n            disc_MsgConflictsInv oidx.\n            solve_by_ObjsInvalid_rsS_false oidx.\n          }\n          { case_InvObjOwned.\n            { disc_MsgConflictsInv oidx.\n              solve_by_ObjsInvalid_rsS_false oidx.\n            }\n            { disc_ObjsInvalid_by oidx0.\n              case_ObjInvalid; [solve_ObjInvalid0|solve_ObjInvRs].\n            }\n            { solve_MsgsP. }\n          }\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx.\n              { disc_MsgConflictsInv oidx.\n                solve_by_ObjsInvalid_rsS_false oidx.\n              }\n              { solve_ObjsInvalid_trivial. }\n            }\n            { case_in_subtree oidx cidx.\n              { solve_ObjsInvalid_trivial. }\n              { disc_MsgConflictsInv oidx.\n                solve_by_ObjsInvalid_rsS_false oidx.\n              }\n            }\n          }\n        }\n      }\n    }\n\n    { (* [l1GetSRsDownDownE] *)\n      disc_rule_conds_ex.\n      derive_footprint_info_basis oidx.\n      derive_child_chns cidx.\n      disc_rule_conds_ex.\n      derive_NoRsI_by_rsDown oidx msgs.\n\n      split.\n      { solve_AtomicInv_rsDown. }\n      { solve_InvExcl_trivial.\n        case_InvExcl_me_others.\n        { disc_AtomicMsgOutsInv oidx.\n          disc_MsgPred.\n          disc_InvExcl_this.\n          { red; intros; split.\n            { solve_ObjsInvalid_trivial. }\n            { disc_MsgConflictsInv oidx.\n              eapply NoCohMsgs_rsDown_deq; eauto.\n            }\n          }\n          { disc_InvObjOwned; split.\n            { solve_ObjsInvalid_trivial. }\n            { solve_MsgsP. }\n          }\n          { red; intros; exfalso; auto. }\n        }\n\n        { disc_InvExcl_others.\n          { disc_InvObjExcl0_apply.\n            disc_MsgConflictsInv oidx.\n            solve_by_ObjsInvalid_rsE_false oidx.\n          }\n          { case_InvObjOwned.\n            { disc_MsgConflictsInv oidx.\n              solve_by_ObjsInvalid_rsE_false oidx.\n            }\n            { disc_ObjsInvalid_by oidx0.\n              case_ObjInvalid; [solve_ObjInvalid0|solve_ObjInvRs].\n            }\n            { solve_MsgsP. }\n          }\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx.\n              { disc_MsgConflictsInv oidx.\n                solve_by_ObjsInvalid_rsE_false oidx.\n              }\n              { solve_ObjsInvalid_trivial. }\n            }\n            { case_in_subtree oidx cidx.\n              { solve_ObjsInvalid_trivial. }\n              { disc_MsgConflictsInv oidx.\n                solve_by_ObjsInvalid_rsE_false oidx.\n              }\n            }\n          }\n        }\n      }\n    }\n\n    { (* [l1DownSImm] *)\n      disc_rule_conds_ex.\n      derive_NoRsI_by_rqDown oidx msgs.\n\n      split.\n      { solve_AtomicInv_rqDown_rsUp.\n        solve_DownRsSPred.\n      }\n      { case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { solve_InvObjExcl0_by_ObjExcl0_false. }\n          { solve_InvObjOwned_by_false. }\n          { red; intros; exfalso; auto. }\n        }\n        { disc_InvExcl_others.\n          { disc_InvObjExcl0_apply.\n            solve_by_ObjsInvalid_status_false oidx.\n          }\n          { case_InvObjOwned.\n            { solve_by_ObjsInvalid_status_false oidx. }\n            { disc_ObjsInvalid_by oidx0.\n              case_ObjInvalid; [solve_ObjInvalid0|solve_ObjInvRs].\n            }\n            { solve_MsgsP. }\n          }\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx.\n              { solve_by_ObjsInvalid_status_false oidx. }\n              { solve_ObjsInvalid_trivial. }\n            }\n            { case_in_subtree oidx cidx.\n              { solve_ObjsInvalid_trivial. }\n              { solve_by_ObjsInvalid_status_false oidx. }\n            }\n          }\n        }\n      }\n    }\n\n    { (* [l1GetMImmE] *)\n      disc_rule_conds_ex; exfalso; disc_AtomicMsgOutsInv (l1ExtOf oidx); eauto.\n    }\n\n    { (* [l1GetMImmM] *)\n      disc_rule_conds_ex; exfalso; disc_AtomicMsgOutsInv (l1ExtOf oidx); eauto.\n    }\n\n    { (* [l1GetMRqUpUp] *)\n      disc_rule_conds_ex; exfalso; disc_AtomicMsgOutsInv (l1ExtOf oidx); eauto.\n    }\n\n    { (* [l1GetMRsDownDown] *)\n      disc_rule_conds_ex.\n      derive_footprint_info_basis oidx.\n      derive_child_chns cidx.\n      disc_rule_conds_ex.\n      derive_NoRsI_by_rsDown oidx msgs.\n\n      split.\n      { solve_AtomicInv_rsDown. }\n      { disc_MsgConflictsInv oidx.\n        solve_InvExcl_trivial.\n        disc_AtomicMsgOutsInv oidx.\n        disc_MsgPred.\n\n        case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { red; intros; split.\n            { solve_ObjsInvalid_trivial. }\n            { eapply NoCohMsgs_rsDown_deq; eauto. }\n          }\n          { disc_InvObjOwned; split.\n            { solve_ObjsInvalid_trivial. }\n            { eapply NoCohMsgs_rsDown_deq; eauto. }\n          }\n          { red; intros; exfalso; auto. }\n        }\n\n        { apply ObjsInvalid_shrinked in H39; [|eassumption..].\n          disc_InvExcl_others.\n          { disc_InvObjExcl0_apply.\n            disc_ObjExcl0.\n            clear H4; solve_by_ObjsInvalid_status_false eidx.\n          }\n          { case_InvObjOwned.\n            { disc_MsgConflictsInv oidx.\n              solve_by_ObjsInvalid_rsM_false oidx.\n            }\n            { disc_ObjsInvalid_by oidx0.\n              case_ObjInvalid; [solve_ObjInvalid0|solve_ObjInvRs].\n            }\n            { solve_MsgsP. }\n          }\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx.\n              { disc_MsgConflictsInv oidx.\n                solve_by_ObjsInvalid_rsM_false oidx.\n              }\n              { solve_ObjsInvalid_trivial. }\n            }\n            { case_in_subtree oidx cidx.\n              { solve_ObjsInvalid_trivial. }\n              { disc_MsgConflictsInv oidx.\n                solve_by_ObjsInvalid_rsM_false oidx.\n              }\n            }\n          }\n        }\n      }\n    }\n\n    { (* [l1DownIImmS] *)\n      disc_rule_conds_ex.\n      derive_NoRsI_by_rqDown oidx msgs.\n\n      split.\n      { disc_MsgConflictsInv oidx.\n        solve_AtomicInv_rqDown_rsUp.\n        { simpl in *; inv H31; mred.\n          simpl; intuition solve_mesi.\n        }\n        { simpl in *; inv H31; mred.\n          eapply ObjsInvalid_in_composed; [mred|..].\n          { left; repeat split; [simpl; solve_mesi|..].\n            { Ltac disc_InvL1DirI oidx :=\n                match goal with\n                | [Hdiri: InvL1DirI _ _, Hin: In oidx (c_l1_indices _), Host: _@[oidx] = Some _\n                   |- _] =>\n                  red in Hdiri; rewrite Forall_forall in Hdiri; specialize (Hdiri _ Hin);\n                  simpl in Hdiri; rewrite Host in Hdiri; simpl in Hdiri\n                end.\n                disc_InvL1DirI oidx0.\n                simpl; rewrite Hdiri; discriminate.\n            }\n            { apply NoCohMsgs_enq; [|solve_not_in].\n              eapply NoCohMsgs_rqDown_deq; eauto.\n            }\n          }\n          { eapply ObjsInvalid_l1_singleton; eauto; mred. }\n        }\n      }\n\n      { case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { solve_InvObjExcl0_by_ObjExcl0_false. }\n          { solve_InvObjOwned_by_false. }\n          { red; intros; exfalso; auto. }\n        }\n        { disc_InvExcl_others.\n          { disc_InvObjExcl0_apply.\n            split; [|solve_MsgsP].\n            solve_ObjsInvalid_trivial.\n            eapply ObjsInvalid_state_transition_sound; eauto.\n            simpl; solve_mesi.\n          }\n          { disc_InvObjOwned.\n            split; [|solve_MsgsP].\n            solve_ObjsInvalid_trivial.\n            eapply ObjsInvalid_state_transition_sound; eauto.\n            simpl; solve_mesi.\n          }\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx.\n              { solve_ObjsInvalid_trivial.\n                eapply ObjsInvalid_state_transition_sound; eauto.\n                simpl; solve_mesi.\n              }\n              { solve_ObjsInvalid_trivial. }\n            }\n            { case_in_subtree oidx cidx.\n              { solve_ObjsInvalid_trivial. }\n              { solve_ObjsInvalid_trivial.\n                eapply ObjsInvalid_state_transition_sound; eauto.\n                simpl; solve_mesi.\n              }\n            }\n          }\n        }\n      }\n    }\n\n    { (* [l1DownIImmME] *)\n      disc_rule_conds_ex.\n      derive_NoRsI_by_rqDown oidx msgs.\n\n      split.\n      { disc_MsgConflictsInv oidx.\n        solve_AtomicInv_rqDown_rsUp.\n        { simpl in *; inv H31; mred; simpl.\n          repeat split.\n          { solve_mesi. }\n          { disc_InvL1DirI oidx0; assumption. }\n        }\n        { simpl in *; inv H31; mred.\n          eapply ObjsInvalid_l1_singleton; eauto; mred.\n        }\n      }\n      { case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { solve_InvObjExcl0_by_ObjExcl0_false. }\n          { solve_InvObjOwned_by_false. }\n          { red; intros; exfalso; auto. }\n        }\n        { disc_InvExcl_others.\n          { disc_InvObjExcl0_apply.\n            solve_by_ObjsInvalid_status_false oidx.\n          }\n          { case_InvObjOwned.\n            { solve_by_ObjsInvalid_status_false oidx. }\n            { disc_ObjsInvalid_by oidx0.\n              case_ObjInvalid; [solve_ObjInvalid0|solve_ObjInvRs].\n            }\n            { solve_MsgsP. }\n          }\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx.\n              { solve_by_ObjsInvalid_status_false oidx. }\n              { solve_ObjsInvalid_trivial. }\n            }\n            { case_in_subtree oidx cidx.\n              { solve_ObjsInvalid_trivial. }\n              { solve_by_ObjsInvalid_status_false oidx. }\n            }\n          }\n        }\n      }\n    }\n\n    { (* [l1InvRqUpUp] *)\n      disc_rule_conds_ex; exfalso; destruct rins; [auto|discriminate].\n    }\n\n    { (* [l1InvRqUpUpWB] *)\n      disc_rule_conds_ex; exfalso; destruct rins; [auto|discriminate].\n    }\n\n    { (* [l1InvRsDownDown] *)\n      disc_rule_conds_ex.\n      derive_footprint_info_basis oidx.\n      disc_InvL1DirI oidx.\n\n      split.\n      { solve_AtomicInv_rsDown. }\n      { case_InvExcl_me_others.\n        { disc_InvExcl_this.\n          { solve_InvObjExcl0_by_ObjExcl0_false. }\n          { solve_InvObjOwned_by_false. }\n          { red; intros; exfalso; auto. }\n        }\n\n        { disc_MsgConflictsInv oidx.\n          disc_InvExcl_others.\n          { disc_InvObjExcl0_apply; split.\n            { eapply ObjsInvalid_invRs; eauto. }\n            { solve_MsgsP. }\n          }\n          { case_InvObjOwned.\n            { left; repeat split; [simpl; solve_mesi| |].\n              { simpl; rewrite Hdiri; discriminate. }\n              { eapply NoCohMsgs_rsDown_deq; eauto. }\n            }\n            { disc_ObjsInvalid_by oidx0.\n              case_ObjInvalid; [solve_ObjInvalid0|solve_ObjInvRs].\n            }\n            { solve_MsgsP. }\n          }\n          { split_InvDirInv_apply.\n            { case_in_subtree oidx cidx.\n              { eapply ObjsInvalid_invRs; eauto. }\n              { solve_ObjsInvalid_trivial. }\n            }\n            { case_in_subtree oidx cidx.\n              { solve_ObjsInvalid_trivial. }\n              { eapply ObjsInvalid_invRs; eauto. }\n            }\n          }\n        }\n      }\n    }\n\n    END_SKIP_PROOF_ON *) admit.\n  Qed.\n\n  Lemma mesi_InvExcl_InvTrs: InvTrs impl (InvExcl topo cifc).\n  Proof.\n    eapply inv_atomic_InvTrs;\n      [red; intros; eapply mesi_InvExcl_InvTrsIns; eauto\n      |red; intros; eapply mesi_InvExcl_InvTrsOuts; eauto\n      |].\n    instantiate (1:= AtomicInv InvExclMsgOutPred).\n\n    red; intros.\n    destruct H1.\n    generalize dependent ist2.\n\n    induction H3; simpl; intros; subst;\n      [inv_steps; apply mesi_InvExcl_InvTrs_init; auto|].\n\n    assert (Atomic inits (ins ++ rins) (RlblInt oidx ridx rins routs :: hst)\n                   (outs ++ routs) (removeL (id_dec msg_dec) eouts rins ++ routs)) as Hnatm\n        by (econstructor; eauto).\n    pose proof (atomic_rsDown_singleton\n                  (mesi_GoodORqsInit Htr)\n                  (mesi_RqRsSys Htr)\n                  Hnatm H H8) as Hrsd.\n    clear Hnatm.\n\n    inv_steps.\n    pose proof (reachable_steps H H9) as Hr1.\n    pose proof (reachable_steps Hr1 (steps_singleton H11)) as Hr2.\n    specialize (IHAtomic H1 _ H9); dest.\n\n    destruct (in_dec idx_dec oidx (map obj_idx (sys_objs impl))) as [Hoin|Hx];\n      [|exfalso; inv_step; elim Hx; apply in_map; assumption].\n    simpl in Hoin; destruct Hoin as [Hoin|Hoin];\n      [|rewrite map_app in Hoin; apply in_app_or in Hoin; destruct Hoin as [Hoin|Hoin]].\n\n    - eapply mesi_InvExcl_InvTrs_mem; eauto.\n    - eapply mesi_InvExcl_InvTrs_li; eauto.\n    - eapply mesi_InvExcl_InvTrs_l1; eauto.\n  Qed.\n\n  Lemma mesi_InvExcl_step:\n    InvStep impl step_m (InvExcl topo cifc).\n  Proof.\n    apply invSeq_serializable_invStep.\n    - apply mesi_InvExcl_init.\n    - apply inv_trs_seqSteps.\n      apply mesi_InvExcl_InvTrs.\n    - eapply rqrs_Serializable.\n      + apply mesi_GoodORqsInit.\n      + apply MesiObjInvs_ok.\n      + apply mesi_RqRsSys.\n  Qed.\n\n  Lemma mesi_InvExcl_ok:\n    Invariant.InvReachable impl step_m (InvExcl topo cifc).\n  Proof.\n    eapply inv_reachable.\n    - typeclasses eauto.\n    - apply mesi_InvExcl_init.\n    - apply mesi_InvExcl_step.\n  Qed.\n\nEnd InvExcl.\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/MesiInvExcl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.28135930569907525}}
{"text": "Require Import Coq.Bool.Sumbool.\nRequire Import Coq.Logic.Eqdep_dec.\nRequire Import Crypto.Compilers.SmartMap.\nRequire Import Crypto.Compilers.Relations.\nRequire Import Crypto.Compilers.Syntax.\nRequire Import Crypto.Compilers.Named.Context.\nRequire Import Crypto.Compilers.Named.Syntax.\nRequire Import Crypto.Compilers.Named.ContextDefinitions.\nRequire Import Crypto.Compilers.Named.ContextProperties.\nRequire Import Crypto.Compilers.Named.ContextProperties.SmartMap.\nRequire Import Crypto.Compilers.Named.InterpSideConditions.\nRequire Import Crypto.Compilers.Named.InterpSideConditionsInterp.\nRequire Import Crypto.Compilers.Named.MapCast.\nRequire Import Crypto.Util.ZUtil.\nRequire Import Crypto.Util.Bool.\nRequire Import Crypto.Util.Option.\nRequire Import Crypto.Util.Sigma.\nRequire Import Crypto.Util.Decidable.\nRequire Import Crypto.Util.PointedProp.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nRequire Import Crypto.Util.Tactics.SpecializeBy.\nRequire Import Crypto.Util.Tactics.DestructHead.\nRequire Import Crypto.Util.Tactics.RewriteHyp.\n\nLocal Open Scope nexpr_scope.\nSection language.\n  Context {base_type_code : Type}\n          {op : flat_type base_type_code -> flat_type base_type_code -> Type}\n          {Name : Type}\n          {interp_base_type_bounds : base_type_code -> Type}\n          (interp_op_bounds : forall src dst, op src dst -> interp_flat_type interp_base_type_bounds src -> interp_flat_type interp_base_type_bounds dst)\n          (pick_typeb : forall t, interp_base_type_bounds t -> base_type_code).\n  Local Notation pick_type t v := (SmartFlatTypeMap pick_typeb (t:=t) v).\n  Context (cast_op : forall t tR (opc : op t tR) args_bs,\n              op (pick_type _ args_bs) (pick_type _ (interp_op_bounds t tR opc args_bs)))\n          {BoundsContext : Context Name interp_base_type_bounds}\n          (BoundsContextOk : ContextOk BoundsContext)\n          {interp_base_type : base_type_code -> Type}\n          (interp_op : forall src dst,\n              op src dst -> interp_flat_type interp_base_type src -> interp_flat_type interp_base_type dst)\n          (interped_op_side_conditions : forall s d, op s d -> interp_flat_type interp_base_type s -> pointed_Prop)\n          (cast_backb: forall t b, interp_base_type (pick_typeb t b) -> interp_base_type t).\n  Let cast_back : forall t b, interp_flat_type interp_base_type (@pick_type t b) -> interp_flat_type interp_base_type t\n    := fun t b => SmartFlatTypeMapUnInterp cast_backb.\n  Context {Context : Context Name interp_base_type}\n          (ContextOk : ContextOk Context)\n          (inboundsb : forall t, interp_base_type_bounds t -> interp_base_type t -> Prop).\n  Let inbounds : forall t, interp_flat_type interp_base_type_bounds t -> interp_flat_type interp_base_type t -> Prop\n    := fun t => interp_flat_type_rel_pointwise inboundsb (t:=t).\n  Context (interp_op_bounds_correct:\n             forall t tR opc bs\n                    (v : interp_flat_type interp_base_type t)\n                    (H : inbounds t bs v)\n                    (Hside : to_prop (interped_op_side_conditions _ _ opc v)),\n               inbounds tR (interp_op_bounds t tR opc bs) (interp_op t tR opc v))\n          (pull_cast_back:\n             forall t tR opc bs\n                    (v : interp_flat_type interp_base_type (pick_type t bs))\n                    (H : inbounds t bs (cast_back t bs v))\n                    (Hside : to_prop (interped_op_side_conditions _ _ opc (cast_back t bs v))),\n               interp_op t tR opc (cast_back t bs v)\n               =\n               cast_back _ _ (interp_op _ _ (cast_op _ _ opc bs) v))\n          (base_type_dec : DecidableRel (@eq base_type_code))\n          (Name_dec : DecidableRel (@eq Name)).\n\n  Local Notation mapf_cast := (@mapf_cast _ op Name _ interp_op_bounds pick_typeb cast_op BoundsContext).\n  Local Notation map_cast := (@map_cast _ op Name _ interp_op_bounds pick_typeb cast_op BoundsContext).\n\n  Local Ltac handle_options_step :=\n    match goal with\n    | _ => progress inversion_option\n    | [ H : ?x = Some _ |- context[?x] ] => rewrite H\n    | [ H : ?x = None |- context[?x] ] => rewrite H\n    | [ H : ?x = Some _, H' : context[?x] |- _ ] => rewrite H in H'\n    | [ H : ?x = None, H' : context[?x] |- _ ] => rewrite H in H'\n    | [ H : Some _ <> None \\/ _ |- _ ] => clear H\n    | [ H : Some ?x <> Some ?y |- _ ] => assert (x <> y) by congruence; clear H\n    | [ H : None <> Some _ |- _ ] => clear H\n    | [ H : Some _ <> None |- _ ] => clear H\n    | [ H : ?x <> ?x \\/ _ |- _ ] => destruct H; [ exfalso; apply H; reflexivity | ]\n    | [ H : _ \\/ None = Some _ |- _ ] => destruct H; [ | exfalso; clear -H; congruence ]\n    | [ H : _ \\/ Some _ = None |- _ ] => destruct H; [ | exfalso; clear -H; congruence ]\n    | [ H : ?x = Some ?y, H' : ?x = Some ?y' |- _ ]\n      => assert (y = y') by congruence; (subst y' || subst y)\n    | _ => progress simpl @option_map\n    end.\n\n  Local Ltac handle_lookupb_step :=\n    let do_eq_dec dec t t' :=\n        first [ constr_eq t t'; fail 1\n              | lazymatch goal with\n                | [ H : t = t' |- _ ] => fail 1\n                | [ H : t <> t' |- _ ] => fail 1\n                | [ H : t = t' -> False |- _ ] => fail 1\n                | _ => destruct (dec t t')\n                end ] in\n    let do_type_dec := do_eq_dec base_type_dec in\n    match goal with\n    | _ => progress unfold dec in *\n    | _ => handle_options_step\n    (* preprocess *)\n    | [ H : context[lookupb (extend _ _ _) _] |- _ ]\n      => first [ rewrite (lookupb_extend base_type_dec Name_dec) in H by assumption\n               | setoid_rewrite (lookupb_extend base_type_dec Name_dec) in H; [ | assumption.. ] ]\n    | [ |- context[lookupb (extend _ _ _) _] ]\n      => first [ rewrite (fun C => lookupb_extend C base_type_dec Name_dec) by assumption\n               | setoid_rewrite (lookupb_extend base_type_dec Name_dec); [ | assumption.. ] ]\n    | _ => progress subst\n    (* handle multiple hypotheses *)\n    | [ H : find_Name _ ?n ?N = Some ?t', H'' : context[find_Name_and_val _ _ ?t ?n ?N ?x ?default] |- _ ]\n      => do_type_dec t t'\n    (* clear the default value *)\n    | [ H : context[find_Name_and_val ?tdec ?ndec ?t ?n (T:=?T) ?N ?V ?default] |- _ ]\n      => lazymatch default with None => fail | _ => idtac end;\n         rewrite find_Name_and_val_split in H\n    (* generic handlers *)\n    | [ H : find_Name _ ?n ?N = Some ?t', H' : ?t <> ?t', H'' : context[find_Name_and_val _ _ ?t ?n ?N ?x ?default] |- _ ]\n      => erewrite find_Name_and_val_wrong_type in H'' by eassumption\n    | [ H : context[find_Name _ _ (SmartFlatTypeMapInterp2 _ _ _)] |- _ ]\n      => rewrite find_Name_SmartFlatTypeMapInterp2 with (base_type_code_dec:=base_type_dec) in H\n    | [ H : find_Name_and_val _ _ _ _ _ _ _ = None |- _ ]\n      => apply find_Name_and_val_None_iff in H\n    (* destructers *)\n    | [ |- context[find_Name_and_val ?tdec ?ndec ?t ?n ?N ?V ?default] ]\n      => destruct (find_Name_and_val tdec ndec t n N V default) eqn:?\n    | [ H : context[match find_Name_and_val ?tdec ?ndec ?t ?n ?N ?V ?default with _ => _ end] |- _ ]\n      => destruct (find_Name_and_val tdec ndec t n N V default) eqn:?\n    | [ H : context[match find_Name ?ndec ?n ?N with _ => _ end] |- _ ]\n      => destruct (find_Name ndec n N) eqn:?\n    | [ H : context[match base_type_dec ?x ?y with _ => _ end] |- _ ]\n      => destruct (base_type_dec x y)\n    | [ H : context[match Name_dec ?x ?y with _ => _ end] |- _ ]\n      => destruct (Name_dec x y)\n    end.\n\n  Local Ltac handle_exists_in_goal :=\n    lazymatch goal with\n    | [ |- exists v, Some ?k = Some v /\\ @?B v ]\n      => exists k; split; [ reflexivity | ]\n    | [ |- (exists v, None = Some v /\\ @?B v) ]\n      => exfalso\n    | [ |- ?A /\\ (exists v, Some ?k = Some v /\\ @?B v) ]\n      => cut (A /\\ B k); [ clear; solve [ intuition eauto ] | cbv beta ]\n    | [ |- ?A /\\ (exists v, None = Some v /\\ @?B v) ]\n      => exfalso\n    end.\n  Local Ltac handle_bounds_side_conditions_step :=\n    match goal with\n    | [ H : interpf ?e = Some ?v, H' : interpf_side_conditions_gen _ _ _ ?e = Some (_, ?v')%core |- _ ]\n      => first [ constr_eq v v'; fail 1\n               | assert (Some v = Some v')\n                 by (erewrite <- H, snd_interpf_side_conditions_gen_eq, H'; reflexivity);\n                 inversion_option; (subst v || subst v') ]\n    end.\n  Local Ltac fin_inbounds_cast_back_t_step :=\n    match goal with\n    | [ |- inboundsb _ _ _ /\\ _ ]\n      => split; [ eapply interp_flat_type_rel_pointwise__find_Name_and_val; eassumption | ]\n    | [ |- cast_backb _ _ _ = _ ]\n      => eapply find_Name_and_val__SmartFlatTypeMapInterp2__SmartFlatTypeMapUnInterp__Some_Some; [ | eassumption.. ]\n    end.\n  Local Ltac specializer_t_step :=\n    match goal with\n    | [ H : ?T, H' : ?T |- _ ] => clear H\n    | [ H : forall x, Some _ = Some x -> _ |- _ ] => specialize (H _ eq_refl)\n    | [ H : ?x = Some _, IH : forall a b, ?x = Some _ -> _ |- _ ]\n      => specialize (IH _ _ H)\n    | [ H : ?x = Some _, IH : forall a, ?x = Some _ -> _ |- _ ]\n      => specialize (IH _ H)\n    | [ H : forall t n v, lookupb ?ctx n = _ -> _, H' : lookupb ?ctx ?n' = _ |- _ ]\n      => specialize (H _ _ _ H')\n    | _ => progress specialize_by auto\n    end.\n\n  Local Ltac break_t_step :=\n    first [ progress destruct_head'_ex\n          | progress destruct_head'_and ].\n\n  Local Ltac t_step :=\n    first [ progress intros\n          | break_t_step\n          | handle_lookupb_step\n          | handle_exists_in_goal\n          | solve [ auto ]\n          | specializer_t_step\n          | fin_inbounds_cast_back_t_step\n          | handle_options_step\n          | handle_bounds_side_conditions_step ].\n  Local Ltac t := repeat t_step.\n\n  Local Ltac do_specialize_IHe :=\n    repeat match goal with\n           | [ IH : context[interpf ?e], H' : interpf (ctx:=?ctx) ?e = _ |- _ ]\n             => let check_tac _ := (rewrite H' in IH) in\n                first [ specialize (IH ctx); check_tac ()\n                      | specialize (fun a => IH a ctx); check_tac ()\n                      | specialize (fun a b => IH a b ctx); check_tac () ]\n           | [ IH : context[mapf_cast _ ?e], H' : mapf_cast ?ctx ?e = _ |- _ ]\n             => let check_tac _ := (rewrite H' in IH) in\n                first [ specialize (IH ctx); check_tac ()\n                      | specialize (fun a => IH a ctx); check_tac ()\n                      | specialize (fun a b => IH a b ctx); check_tac () ]\n           | [ H : forall x y z, Some _ = Some _ -> _ |- _ ]\n             => first [ specialize (H _ _ _ eq_refl)\n                      | specialize (fun x => H x _ _ eq_refl) ]\n           | [ H : forall x y, Some _ = Some _ -> _ |- _ ]\n             => first [ specialize (H _ _ eq_refl)\n                      | specialize (fun x => H x _ eq_refl) ]\n           | _ => progress specialize_by_assumption\n           end.\n\n  Lemma mapf_cast_correct\n        {t} (e:exprf base_type_code op Name t)\n    : forall\n      (oldValues:Context)\n      (newValues:Context)\n      (varBounds:BoundsContext)\n      {b} e' (He':mapf_cast varBounds e = Some (existT _ b e'))\n      (Hctx:forall {t} n v,\n          lookupb (t:=t) oldValues n = Some v\n          -> exists b, lookupb (t:=t) varBounds n = Some b\n                       /\\ @inboundsb _ b v\n                       /\\ exists v', lookupb (t:=pick_typeb t b) newValues n = Some v'\n                                     /\\ cast_backb t b v' = v)\n      r (Hr:interpf (interp_op:=interp_op) (ctx:=oldValues) e = Some r)\n      r' (Hr':interpf (interp_op:=interp_op) (ctx:=newValues) e' = Some r')\n      (Hside : prop_of_option (interpf_side_conditions interp_op interped_op_side_conditions oldValues e))\n    , interpf (interp_op:=interp_op_bounds) (ctx:=varBounds) e = Some b\n      /\\ @inbounds _ b r /\\ cast_back _ _ r' = r.\n  Proof using Type*.\n    induction e; simpl interpf; simpl mapf_cast; unfold option_map, cast_back in *; intros;\n      unfold interpf_side_conditions in *; simpl in Hside;\n      repeat (repeat handle_options_step; break_match_hyps; inversion_option; inversion_sigma; autorewrite with push_to_prop in *; simpl in *; unfold option_map in *; subst; try tauto).\n    { destruct (Hctx _ _ _ Hr) as [b' [Hb'[Hb'v[v'[Hv' Hv'v]]]]]; clear Hctx Hr; subst.\n      repeat match goal with\n               [H: ?e = Some ?x, G:?e = Some ?x' |- _] =>\n               pose proof (eq_trans (eq_sym G) H); clear G; inversion_option; subst\n             end.\n      auto. }\n    { do_specialize_IHe.\n      repeat (handle_options_step || destruct_head_and || specialize_by_assumption).\n      subst; intuition eauto; try (symmetry; rewrite_hyp ?*; eauto);\n        repeat handle_bounds_side_conditions_step; auto. }\n    { cbv [LetIn.Let_In] in *.\n      do_specialize_IHe.\n      destruct_head'_and.\n      destruct IHe1 as [IHe1_eq IHe1]; rewrite_hyp *; try assumption.\n      { apply IHe2; clear IHe2; try reflexivity; [ | t ].\n        intros ??? Hlookup.\n        let b := fresh \"b\" in\n        let H' := fresh \"H'\" in\n        match goal with |- exists b0, ?v = Some b0 /\\ _ => destruct v as [b|] eqn:H' end;\n          [ exists b; split; [ reflexivity | ] | exfalso ];\n          revert Hlookup H'; t. } }\n    { do_specialize_IHe.\n      t. }\n  Qed.\n\n  Lemma map_cast_correct\n        {t} (e:expr base_type_code op Name t)\n        (input_bounds : interp_flat_type interp_base_type_bounds (domain t))\n    : forall\n        (oldValues:Context)\n        (newValues:Context)\n        (varBounds:BoundsContext)\n        {b} e' (He':map_cast varBounds e input_bounds = Some (existT _ b e'))\n        (Hctx:forall {t} n v,\n            lookupb (t:=t) oldValues n = Some v\n            -> exists b, lookupb (t:=t) varBounds n = Some b\n                         /\\ @inboundsb _ b v\n                         /\\ exists v', lookupb (t:=pick_typeb t b) newValues n = Some v'\n                                       /\\ cast_backb t b v' = v)\n        v v' (Hv : @inbounds _ input_bounds v /\\ cast_back _ _ v' = v)\n        r (Hr:interp (interp_op:=interp_op) (ctx:=oldValues) e v = Some r)\n        r' (Hr':interp (interp_op:=interp_op) (ctx:=newValues) e' v' = Some r')\n        (Hside : prop_of_option (interp_side_conditions interp_op interped_op_side_conditions oldValues e v))\n        , interp (interp_op:=interp_op_bounds) (ctx:=varBounds) e input_bounds = Some b\n          /\\ @inbounds _ b r /\\ cast_back _ _ r' = r.\n  Proof using Type*.\n    unfold map_cast, option_map, interp; simpl; intros.\n    repeat first [ progress subst\n                 | progress inversion_option\n                 | progress inversion_sigma\n                 | progress break_match_hyps\n                 | progress destruct_head' sigT\n                 | progress simpl in * ].\n    eapply mapf_cast_correct; try eassumption.\n    t.\n  Qed.\nEnd language.\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/MapCastInterp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.28135930569907525}}
{"text": "(** * Push-Button Synthesis of Bernstein-Yang Inversion: Reification Cache *)\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.derive.Derive.\nRequire Import Crypto.Util.Tactics.Head.\nRequire Import Crypto.Util.ZUtil.Pow.\nRequire Import Crypto.Arithmetic.Core.\nRequire Import Crypto.Arithmetic.Partition.\nRequire Import Crypto.Arithmetic.Freeze.\nRequire Import Crypto.Arithmetic.ModOps.\nRequire Import Crypto.Arithmetic.WordByWordMontgomery.\nRequire Import Crypto.Arithmetic.BYInv.\nRequire Import Rewriter.Language.Language.\nRequire Import Crypto.Language.API.\nRequire Import Crypto.PushButtonSynthesis.ReificationCache.\nLocal Open Scope Z_scope.\n\nRequire Import Crypto.Arithmetic.UniformWeight.\nRequire Import Lists.List.\n\nImport\n  Language.Wf.Compilers\n  Language.Compilers\n  Language.API.Compilers.\nImport Compilers.API.\n\nImport Associational Positional.\n\nLocal Set Keyed Unification. (* needed for making [autorewrite] fast, c.f. COQBUG(https://github.com/coq/coq/issues/9283) *)\n\nModule Export WordByWordMontgomeryInversion.\n  Import WordByWordMontgomery.WordByWordMontgomery.\n\n  Definition msat bitwidth n m := Partition.partition (uweight bitwidth) n m. (* m in saturated representation *)\n\n  Derive reified_divstep_gen\n         SuchThat (is_reification_of reified_divstep_gen divstep)\n         As reified_divstep_gen_correct.\n  Proof. Time cache_reify (). Time Qed.\n  Hint Extern 1 (_ = _) => apply_cached_reification divstep (proj1 reified_divstep_gen_correct) : reify_cache_gen.\n  Hint Immediate (proj2 reified_divstep_gen_correct) : wf_gen_cache.\n  Hint Rewrite (proj1 reified_divstep_gen_correct) : interp_gen_cache.\n  Local Opaque reified_divstep_gen. (* needed for making [autorewrite] not take a very long time *)\n\n  Derive reified_msat_gen\n         SuchThat (is_reification_of reified_msat_gen msat)\n         As reified_msat_gen_correct.\n  Proof.\n    Time cache_reify ().\n    Time Qed.\n  Hint Extern 1 (_ = _) => apply_cached_reification msat (proj1 reified_msat_gen_correct) : reify_cache_gen.\n  Hint Immediate (proj2 reified_msat_gen_correct) : wf_gen_cache.\n  Hint Rewrite (proj1 reified_msat_gen_correct) : interp_gen_cache.\n  Local Opaque reified_msat_gen. (* needed for making [autorewrite] not take a very long time *)\n\n  Derive reified_eval_twos_complement_gen\n         SuchThat (is_reification_of reified_eval_twos_complement_gen eval_twos_complement)\n         As reified_eval_twos_complement_gen_correct.\n  Proof. Time cache_reify (). Time Qed.\n  Hint Extern 1 (_ = _) => apply_cached_reification eval_twos_complement (proj1 reified_eval_twos_complement_gen_correct) : reify_cache_gen.\n  Hint Immediate (proj2 reified_eval_twos_complement_gen_correct) : wf_gen_cache.\n  Hint Rewrite (proj1 reified_eval_twos_complement_gen_correct) : interp_gen_cache.\n  Local Opaque reified_eval_twos_complement_gen. (* needed for making [autorewrite] not take a very long time *)\nEnd WordByWordMontgomeryInversion.\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/BYInversionReificationCache.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.28135929961196493}}
{"text": "(*! Building simple pipelines !*)\nRequire Import Koika.Frontend.\n\nInductive reg_t := r0 | outputReg | inputReg | invalid | correct.\nInductive ext_fn_t := Stream | F | G.\nInductive rule_name_t := doF | doG.\n\nDefinition sz := (pow2 5).\n\nDefinition R r :=\n  match r with\n  | r0 => bits_t sz\n  | inputReg => bits_t sz\n  | outputReg => bits_t sz\n  | invalid | correct => bits_t 1\n  end.\n\nDefinition r reg : R reg :=\n  match reg with\n  | r0 => Bits.zero\n  | outputReg => Bits.zero\n  | inputReg => Bits.zero\n  | invalid => Ob~1\n  | correct => Ob~1\n  end.\n\nDefinition Sigma (fn: ext_fn_t) : ExternalSignature :=\n  match fn with\n  | Stream => {$ bits_t sz ~> bits_t sz $}\n  | F => {$ bits_t sz ~> bits_t sz $}\n  | G => {$ bits_t sz ~> bits_t sz $}\n  end.\n\nDefinition _doF : uaction _ _ :=\n  {{\n     let v := read0(inputReg) in\n     write0(inputReg, extcall Stream(v));\n     let invalid := read1(invalid) in\n     if invalid then\n       write1(invalid, Ob~0);\n       write0(r0,extcall F(v))\n     else\n       fail\n  }}.\n\nDefinition _doG : uaction _ _ :=\n  {{\n      let invalid := read0(invalid) in\n      if !invalid then\n        let data := read0(r0) in\n        let v := read0(outputReg) in\n        write0(outputReg, extcall Stream(v));\n        write0(invalid, Ob~1);\n        if extcall G(data) == extcall G(extcall F(v)) then\n          pass\n        else\n          write0(correct, Ob~0)\n      else\n        fail\n  }}.\n\nDefinition rules :=\n  tc_rules R Sigma\n           (fun rl => match rl with\n                   | doF => _doF\n                   | doG => _doG\n                   end).\n\nDefinition pipeline : scheduler :=\n  doG |> doF |> done.\n\nDefinition external (r: rule_name_t) := false.\n\nDefinition circuits :=\n  compile_scheduler rules external pipeline.\n\nDefinition circuits_result sigma :=\n  interp_circuits sigma circuits (lower_r (ContextEnv.(create) r)).\n\nDefinition cpp_extfuns := \"class extfuns {\npublic:\n  static bits<32> stream(bits<32> lfsr) {\n    return lfsr + bits<32>{1};\n  }\n\n  static bits<32> f(bits<32> x) {\n    return ~(x << bits<32>{2}) - bits<32>{1};\n  }\n\n  static bits<32> g(bits<32> x) {\n    return bits<32>{5} + ((x + bits<32>{1}) >> bits<32>{1});\n  }\n};\".\n\nDefinition ext_fn_names fn :=\n  match fn with\n  | Stream => \"stream\"\n  | F => \"f\"\n  | G => \"g\"\n  end.\n\nDefinition package :=\n  {| ip_koika := {| koika_reg_types := R;\n                   koika_reg_init reg := r reg;\n                   koika_ext_fn_types := Sigma;\n                   koika_rules := rules;\n                   koika_rule_external := external;\n                   koika_scheduler := pipeline;\n                   koika_module_name := \"pipeline\" |};\n\n     ip_sim := {| sp_ext_fn_specs fn :=\n                   {| efs_name := ext_fn_names fn;\n                      efs_method := false |};\n                 sp_prelude := Some cpp_extfuns |};\n\n     ip_verilog := {| vp_ext_fn_specs fn :=\n                       {| efr_name := ext_fn_names fn;\n                          efr_internal := true |} |} |}.\n\nDefinition prog := Interop.Backends.register package.\nExtraction \"pipeline.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/examples/pipeline.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5039061705290806, "lm_q1q2_score": 0.2813444176185502}}
{"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import TableDataOpsIntro.Spec.\nRequire Import TableDataOpsRef1.Spec.\n\nLocal Open Scope Z_scope.\n\nSection SpecLow.\n\n  Definition table_destroy2_spec0 (g_rd: Pointer) (map_addr: Z64) (rtt_addr: Z64) (level: Z64) (adt: RData) : option (RData * Z64) :=\n    match g_rd, map_addr, rtt_addr, level with\n    | (_g_rd_base, _g_rd_ofst), VZ64 _map_addr, VZ64 _rtt_addr, VZ64 _level =>\n      rely is_int64 _map_addr;\n      rely is_int64 _rtt_addr;\n      rely is_int64 _level;\n      when' _t'1, adt == table_destroy1_spec (_g_rd_base, _g_rd_ofst) (VZ64 _map_addr) (VZ64 _rtt_addr) (VZ64 _level) 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/TableDataOpsRef2/LowSpecs/table_destroy2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.28117924283107915}}
{"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(** Locations are a refinement of RTL pseudo-registers, used to reflect\n  the results of register allocation (file [Allocation]). *)\n\nRequire Import OrderedType.\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import Ordered.\nRequire Import AST.\nRequire Import Values.\nRequire Export Machregs.\n\n(** * Representation of locations *)\n\n(** A location is either a processor register or (an abstract designation of)\n  a slot in the activation record of the current function. *)\n\n(** ** Processor registers *)\n\n(** Processor registers usable for register allocation are defined\n  in module [Machregs]. *)\n\n(** ** Slots in activation records *)\n\n(** A slot in an activation record is designated abstractly by a kind,\n  a type and an integer offset.  Three kinds are considered:\n- [Local]: these are the slots used by register allocation for \n  pseudo-registers that cannot be assigned a hardware register.\n- [Incoming]: used to store the parameters of the current function\n  that cannot reside in hardware registers, as determined by the \n  calling conventions.\n- [Outgoing]: used to store arguments to called functions that \n  cannot reside in hardware registers, as determined by the \n  calling conventions. *)\n\nInductive slot: Type :=\n  | Local\n  | Incoming\n  | Outgoing.\n\n(** Morally, the [Incoming] slots of a function are the [Outgoing]\nslots of its caller function.\n\nThe type of a slot indicates how it will be accessed later once mapped to\nactual memory locations inside a memory-allocated activation record:\nas 32-bit integers/pointers (type [Tint]) or as 64-bit floats (type [Tfloat]).\n\nThe offset of a slot, combined with its type and its kind, identifies\nuniquely the slot and will determine later where it resides within the\nmemory-allocated activation record.  Offsets are always positive.\n*)\n\nLemma slot_eq: forall (p q: slot), {p = q} + {p <> q}.\nProof.\n  decide equality.\nDefined.\n\nOpen Scope Z_scope.\n\nDefinition typesize (ty: typ) : Z :=\n  match ty with\n  | Tint => 1\n  | Tlong => 2\n  | Tfloat => 2\n  | Tsingle => 1\n  | Tany32 => 1\n  | Tany64 => 2\n  end.\n\nLemma typesize_pos:\n  forall (ty: typ), typesize ty > 0.\nProof.\n  destruct ty; compute; auto.\nQed.\n\n(** ** Locations *)\n\n(** Locations are just the disjoint union of machine registers and\n  activation record slots. *)\n\nInductive loc : Type :=\n  | R (r: mreg)\n  | S (sl: slot) (pos: Z) (ty: typ).\n\nModule Loc.\n\n  Definition type (l: loc) : typ :=\n    match l with\n    | R r => mreg_type r\n    | S sl pos ty => ty\n    end.\n\n  Lemma eq: forall (p q: loc), {p = q} + {p <> q}.\n  Proof.\n    decide equality.\n    apply mreg_eq.\n    apply typ_eq.\n    apply zeq.\n    apply slot_eq.\n  Defined.\n\n(** As mentioned previously, two locations can be different (in the sense\n  of the [<>] mathematical disequality), yet denote \n  overlapping memory chunks within the activation record.\n  Given two locations, three cases are possible:\n- They are equal (in the sense of the [=] equality)\n- They are different and non-overlapping.\n- They are different but overlapping.\n\n  The second case (different and non-overlapping) is characterized \n  by the following [Loc.diff] predicate.\n*)\n  Definition diff (l1 l2: loc) : Prop :=\n    match l1, l2 with\n    | R r1, R r2 => \n        r1 <> r2\n    | S s1 d1 t1, S s2 d2 t2 =>\n        s1 <> s2 \\/ d1 + typesize t1 <= d2 \\/ d2 + typesize t2 <= d1\n    | _, _ =>\n        True\n    end.\n\n  Lemma same_not_diff:\n    forall l, ~(diff l l).\n  Proof.\n    destruct l; unfold diff; auto.\n    red; intros. destruct H; auto. generalize (typesize_pos ty); omega. \n  Qed.\n\n  Lemma diff_not_eq:\n    forall l1 l2, diff l1 l2 -> l1 <> l2.\n  Proof.\n    unfold not; intros. subst l2. elim (same_not_diff l1 H).\n  Qed.\n\n  Lemma diff_sym:\n    forall l1 l2, diff l1 l2 -> diff l2 l1.\n  Proof.\n    destruct l1; destruct l2; unfold diff; auto.\n    intuition.\n  Qed.\n\n  Definition diff_dec (l1 l2: loc) : { Loc.diff l1 l2 } + { ~Loc.diff l1 l2 }.\n  Proof.\n    intros. destruct l1; destruct l2; simpl.\n  - destruct (mreg_eq r r0). right; tauto. left; auto.\n  - left; auto.\n  - left; auto.\n  - destruct (slot_eq sl sl0).\n    destruct (zle (pos + typesize ty) pos0).\n    left; auto.\n    destruct (zle (pos0 + typesize ty0) pos).\n    left; auto.\n    right; red; intros [P | [P | P]]. congruence. omega. omega. \n    left; auto.\n  Defined.\n\n(** We now redefine some standard notions over lists, using the [Loc.diff]\n  predicate instead of standard disequality [<>].\n\n  [Loc.notin l ll] holds if the location [l] is different from all locations\n  in the list [ll]. *)\n\n  Fixpoint notin (l: loc) (ll: list loc) {struct ll} : Prop :=\n    match ll with\n    | nil => True\n    | l1 :: ls => diff l l1 /\\ notin l ls\n    end.\n\n  Lemma notin_iff:\n    forall l ll, notin l ll <-> (forall l', In l' ll -> Loc.diff l l').\n  Proof.\n    induction ll; simpl. \n    tauto.\n    rewrite IHll. intuition. subst a. auto. \n  Qed.\n\n  Lemma notin_not_in:\n    forall l ll, notin l ll -> ~(In l ll).\n  Proof.\n    intros; red; intros. rewrite notin_iff in H.\n    elim (diff_not_eq l l); auto.\n  Qed.\n\n  Lemma notin_dec (l: loc) (ll: list loc) : {notin l ll} + {~notin l ll}.\n  Proof.\n    induction ll; simpl.\n    left; auto.\n    destruct (diff_dec l a).\n    destruct IHll.\n    left; auto.\n    right; tauto.\n    right; tauto.\n  Defined.\n\n(** [Loc.disjoint l1 l2] is true if the locations in list [l1]\n  are different from all locations in list [l2]. *)\n\n  Definition disjoint (l1 l2: list loc) : Prop :=\n    forall x1 x2, In x1 l1 -> In x2 l2 -> diff x1 x2.\n\n  Lemma disjoint_cons_left:\n    forall a l1 l2,\n    disjoint (a :: l1) l2 -> disjoint l1 l2.\n  Proof.\n    unfold disjoint; intros. auto with coqlib.    \n  Qed.\n  Lemma disjoint_cons_right:\n    forall a l1 l2,\n    disjoint l1 (a :: l2) -> disjoint l1 l2.\n  Proof.\n    unfold disjoint; intros. auto with coqlib.    \n  Qed.\n\n  Lemma disjoint_sym:\n    forall l1 l2, disjoint l1 l2 -> disjoint l2 l1.\n  Proof.\n    unfold disjoint; intros. apply diff_sym; auto.\n  Qed.\n\n  Lemma in_notin_diff:\n    forall l1 l2 ll, notin l1 ll -> In l2 ll -> diff l1 l2.\n  Proof.\n    intros. rewrite notin_iff in H. auto. \n  Qed.\n\n  Lemma notin_disjoint:\n    forall l1 l2,\n    (forall x, In x l1 -> notin x l2) -> disjoint l1 l2.\n  Proof.\n    intros; red; intros. exploit H; eauto. rewrite notin_iff; intros. auto. \n  Qed.\n\n  Lemma disjoint_notin:\n    forall l1 l2 x, disjoint l1 l2 -> In x l1 -> notin x l2.\n  Proof.\n    intros; rewrite notin_iff; intros. red in H. auto. \n  Qed.\n\n(** [Loc.norepet ll] holds if the locations in list [ll] are pairwise\n  different. *)\n\n  Inductive norepet : list loc -> Prop :=\n  | norepet_nil:\n      norepet nil\n  | norepet_cons:\n      forall hd tl, notin hd tl -> norepet tl -> norepet (hd :: tl).\n\n  Lemma norepet_dec (ll: list loc) : {norepet ll} + {~norepet ll}.\n  Proof.\n    induction ll.\n    left; constructor.\n    destruct (notin_dec a ll).\n    destruct IHll.\n    left; constructor; auto.\n    right; red; intros P; inv P; contradiction.\n    right; red; intros P; inv P; contradiction.\n  Defined.\n\n(** [Loc.no_overlap l1 l2] holds if elements of [l1] never overlap partially\n  with elements of [l2]. *)\n\n  Definition no_overlap (l1 l2 : list loc) :=\n   forall r, In r l1 -> forall s, In s l2 ->  r = s \\/ Loc.diff r s.\n\nEnd Loc.\n\n(** * Mappings from locations to values *)\n\n(** The [Locmap] module defines mappings from locations to values,\n  used as evaluation environments for the semantics of the [LTL] \n  and [Linear] intermediate languages.  *)\n\nSet Implicit Arguments.\n\nModule Locmap.\n\n  Definition t := loc -> val.\n\n  Definition init (x: val) : t := fun (_: loc) => x.\n\n  Definition get (l: loc) (m: t) : val := m l.\n\n  (** The [set] operation over location mappings reflects the overlapping\n      properties of locations: changing the value of a location [l]\n      invalidates (sets to [Vundef]) the locations that partially overlap\n      with [l].  In other terms, the result of [set l v m]\n      maps location [l] to value [v], locations that overlap with [l]\n      to [Vundef], and locations that are different (and non-overlapping)\n      from [l] to their previous values in [m].  This is apparent in the\n      ``good variables'' properties [Locmap.gss] and [Locmap.gso].\n\n      Additionally, the [set] operation also anticipates the fact that\n      abstract stack slots are mapped to concrete memory locations\n      in the [Stacking] phase.  Hence, values stored in stack slots\n      are normalized according to the type of the slot. *)\n\n  Definition set (l: loc) (v: val) (m: t) : t :=\n    fun (p: loc) =>\n      if Loc.eq l p then\n        match l with R r => v | S sl ofs ty => Val.load_result (chunk_of_type ty) v end\n      else if Loc.diff_dec l p then\n        m p\n      else Vundef.\n\n  Lemma gss: forall l v m,\n    (set l v m) l = \n    match l with R r => v | S sl ofs ty => Val.load_result (chunk_of_type ty) v end.\n  Proof.\n    intros. unfold set. apply dec_eq_true.\n  Qed.\n\n  Lemma gss_reg: forall r v m, (set (R r) v m) (R r) = v.\n  Proof.\n    intros. unfold set. rewrite dec_eq_true. auto.\n  Qed.\n\n  Lemma gss_typed: forall l v m, Val.has_type v (Loc.type l) -> (set l v m) l = v.\n  Proof.\n    intros. rewrite gss. destruct l. auto. apply Val.load_result_same; auto. \n  Qed.\n\n  Lemma gso: forall l v m p, Loc.diff l p -> (set l v m) p = m p.\n  Proof.\n    intros. unfold set. destruct (Loc.eq l p).\n    subst p. elim (Loc.same_not_diff _ H).\n    destruct (Loc.diff_dec l p).\n    auto.\n    contradiction.\n  Qed.\n\n  Fixpoint undef (ll: list loc) (m: t) {struct ll} : t :=\n    match ll with\n    | nil => m\n    | l1 :: ll' => undef ll' (set l1 Vundef m)\n    end.\n\n  Lemma guo: forall ll l m, Loc.notin l ll -> (undef ll m) l = m l.\n  Proof.\n    induction ll; simpl; intros. auto. \n    destruct H. rewrite IHll; auto. apply gso. apply Loc.diff_sym; auto. \n  Qed.\n\n  Lemma gus: forall ll l m, In l ll -> (undef ll m) l = Vundef.\n  Proof.\n    assert (P: forall ll l m, m l = Vundef -> (undef ll m) l = Vundef).\n      induction ll; simpl; intros. auto. apply IHll. \n      unfold set. destruct (Loc.eq a l).\n      destruct a. auto. destruct ty; reflexivity. \n      destruct (Loc.diff_dec a l); auto.\n    induction ll; simpl; intros. contradiction. \n    destruct H. apply P. subst a. apply gss_typed. exact I. \n    auto.\n  Qed.\n\n  Fixpoint setlist (ll: list loc) (vl: list val) (m: t) {struct ll} : t :=\n    match ll, vl with\n    | l1 :: ls, v1 :: vs => setlist ls vs (set l1 v1 m)\n    | _, _ => m\n    end.\n\n  Lemma gsetlisto: forall l ll vl m, Loc.notin l ll -> (setlist ll vl m) l = m l.\n  Proof.\n    induction ll; simpl; intros. \n    auto.\n    destruct vl; auto. destruct H. rewrite IHll; auto. apply gso; auto. apply Loc.diff_sym; auto.\n  Qed.\n\nEnd Locmap.\n\n(** * Total ordering over locations *)\n\nModule IndexedTyp <: INDEXED_TYPE.\n  Definition t := typ.\n  Definition index (x: t) :=\n    match x with\n    | Tany32 => 1%positive\n    | Tint => 2%positive\n    | Tsingle => 3%positive\n    | Tany64 => 4%positive\n    | Tfloat => 5%positive\n    | Tlong => 6%positive\n    end.\n  Lemma index_inj: forall x y, index x = index y -> x = y.\n  Proof. destruct x; destruct y; simpl; congruence. Qed.\n  Definition eq := typ_eq.\nEnd IndexedTyp.\n\nModule OrderedTyp := OrderedIndexed(IndexedTyp).\n\nModule IndexedSlot <: INDEXED_TYPE.\n  Definition t := slot.\n  Definition index (x: t) :=\n    match x with Local => 1%positive | Incoming => 2%positive | Outgoing => 3%positive end.\n  Lemma index_inj: forall x y, index x = index y -> x = y.\n  Proof. destruct x; destruct y; simpl; congruence. Qed.\n  Definition eq := slot_eq.\nEnd IndexedSlot.\n\nModule OrderedSlot := OrderedIndexed(IndexedSlot).\n\nModule OrderedLoc <: OrderedType.\n  Definition t := loc.\n  Definition eq (x y: t) := x = y.\n  Definition lt (x y: t) :=\n    match x, y with\n    | R r1, R r2 => Plt (IndexedMreg.index r1) (IndexedMreg.index r2)\n    | R _, S _ _ _ => True\n    | S _ _ _, R _ => False\n    | S sl1 ofs1 ty1, S sl2 ofs2 ty2 =>\n        OrderedSlot.lt sl1 sl2 \\/ (sl1 = sl2 /\\\n        (ofs1 < ofs2 \\/ (ofs1 = ofs2 /\\ OrderedTyp.lt ty1 ty2)))\n    end.\n  Lemma eq_refl : forall x : t, eq x x.\n  Proof (@refl_equal t). \n  Lemma eq_sym : forall x y : t, eq x y -> eq y x.\n  Proof (@sym_equal t).\n  Lemma eq_trans : forall x y z : t, eq x y -> eq y z -> eq x z.\n  Proof (@trans_equal 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. \n    destruct x; destruct y; destruct z; try tauto.\n    eapply Plt_trans; eauto.\n    destruct H. \n    destruct H0. left; eapply OrderedSlot.lt_trans; eauto.\n    destruct H0. subst sl0. auto. \n    destruct H. subst sl.\n    destruct H0. auto.\n    destruct H. \n    right.  split. auto.\n    intuition.\n    right; split. congruence. eapply OrderedTyp.lt_trans; eauto. \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 y. \n    destruct x. \n    eelim Plt_strict; eauto.\n    destruct H. eelim OrderedSlot.lt_not_eq; eauto. red; auto. \n    destruct H. destruct H0. omega. \n    destruct H0. eelim OrderedTyp.lt_not_eq; eauto. red; auto.\n  Qed.\n  Definition compare : forall x y : t, Compare lt eq x y.\n  Proof.\n    intros. destruct x; destruct y.\n  - destruct (OrderedPositive.compare (IndexedMreg.index r) (IndexedMreg.index r0)).\n    + apply LT. red. auto. \n    + apply EQ. red. f_equal. apply IndexedMreg.index_inj. auto. \n    + apply GT. red. auto.\n  - apply LT. red; auto. \n  - apply GT. red; auto.\n  - destruct (OrderedSlot.compare sl sl0).\n    + apply LT. red; auto.\n    + destruct (OrderedZ.compare pos pos0).\n      * apply LT. red. auto. \n      * destruct (OrderedTyp.compare ty ty0).\n        apply LT. red; auto.\n        apply EQ. red; red in e; red in e0; red in e1. congruence. \n        apply GT. red; auto.\n      * apply GT. red. auto. \n    + apply GT. red; auto.\n  Defined.\n  Definition eq_dec := Loc.eq.\n\n(** Connection between the ordering defined here and the [Loc.diff] predicate. *)\n\n  Definition diff_low_bound (l: loc) : loc :=\n    match l with\n    | R mr => l\n    | S sl ofs ty => S sl (ofs - 1) Tany64\n    end.\n\n  Definition diff_high_bound (l: loc) : loc :=\n    match l with\n    | R mr => l\n    | S sl ofs ty => S sl (ofs + typesize ty - 1) Tlong\n    end.\n\n  Lemma outside_interval_diff:\n    forall l l', lt l' (diff_low_bound l) \\/ lt (diff_high_bound l) l' -> Loc.diff l l'.\n  Proof.\n    intros. \n    destruct l as [mr | sl ofs ty]; destruct l' as [mr' | sl' ofs' ty']; simpl in *; auto.\n    - assert (IndexedMreg.index mr <> IndexedMreg.index mr').\n      { destruct H. apply sym_not_equal. apply Plt_ne; auto. apply Plt_ne; auto. }\n      congruence.\n    - assert (RANGE: forall ty, 1 <= typesize ty <= 2).\n      { intros; unfold typesize. destruct ty0; omega.  }\n      destruct H. \n      + destruct H. left. apply sym_not_equal. apply OrderedSlot.lt_not_eq; auto. \n        destruct H. right.\n        destruct H0. right. generalize (RANGE ty'); omega. \n        destruct H0. \n        assert (ty' = Tint \\/ ty' = Tsingle \\/ ty' = Tany32). \n        { unfold OrderedTyp.lt in H1. destruct ty'; auto; compute in H1; congruence. }\n        right. destruct H2 as [E|[E|E]]; subst ty'; simpl typesize; omega. \n      + destruct H. left. apply OrderedSlot.lt_not_eq; auto.\n        destruct H. right.\n        destruct H0. left; omega.\n        destruct H0. exfalso. destruct ty'; compute in H1; congruence.\n  Qed.\n\n  Lemma diff_outside_interval:\n    forall l l', Loc.diff l l' -> lt l' (diff_low_bound l) \\/ lt (diff_high_bound l) l'.\n  Proof.\n    intros. \n    destruct l as [mr | sl ofs ty]; destruct l' as [mr' | sl' ofs' ty']; simpl in *; auto.\n    - unfold Plt, Pos.lt. destruct (Pos.compare (IndexedMreg.index mr) (IndexedMreg.index mr')) eqn:C.\n      elim H. apply IndexedMreg.index_inj. apply Pos.compare_eq_iff. auto.\n      auto. \n      rewrite Pos.compare_antisym. rewrite C. auto. \n    - destruct (OrderedSlot.compare sl sl'); auto.\n      destruct H. contradiction. \n      destruct H.\n      right; right; split; auto. left; omega. \n      left; right; split; auto.\n      assert (EITHER: typesize ty' = 1 /\\ OrderedTyp.lt ty' Tany64 \\/ typesize ty' = 2).\n      { destruct ty'; compute; auto. }\n      destruct (zlt ofs' (ofs - 1)). left; auto.\n      destruct EITHER as [[P Q] | P].\n      right; split; auto. omega.\n      left; omega. \n  Qed.\n\nEnd OrderedLoc.\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/Locations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.28117924283107915}}
{"text": "Require Import FcEtt.sigs.\nRequire Export FcEtt.imports.\nRequire Export FcEtt.ett_inf.\nRequire Export FcEtt.ett_ind.\n\nRequire Import FcEtt.tactics.\nRequire Import FcEtt.ett_par.\n\nRequire Import FcEtt.erase_syntax.\n\nRequire Export FcEtt.fc_wf.\n\n(* can remove this parameter *)\nModule fc_weak (wf : fc_wf_sig) <: fc_weak_sig.\n\n\nSet Bullet Behavior \"Strict Subproofs\".\nSet Implicit Arguments.\n\n(* Weakening *)\n\n(* ------------------------------------------------------------------- *)\n\n\nLemma ann_respects_atoms_eq_mutual :\n  (forall G a A,       AnnTyping  G a A       -> True) /\\\n  (forall G phi,       AnnPropWff G phi       -> True) /\\\n  (forall G D g p1 p2, AnnIso     G D g p1 p2 -> forall D', D [=] D' -> AnnIso   G D' g p1 p2) /\\\n  (forall G D g A B,   AnnDefEq   G D g A B   -> forall D', D [=] D' -> AnnDefEq G D' g A B) /\\\n  (forall G,           AnnCtx     G           -> True).\nProof.\n  eapply ann_typing_wff_iso_defeq_mutual.\n  all: pre; subst; eauto 3.\n  all: econstructor; eauto.\n  fsetdec.\nQed.\n\nDefinition AnnIso_respects_atoms_eq   := third  ann_respects_atoms_eq_mutual.\nDefinition AnnDefEq_respects_atoms_eq := fourth ann_respects_atoms_eq_mutual.\n\nInstance AnnIso_atoms_eq_mor : Morphisms.Proper\n                                 (eq ==> AtomSetImpl.Equal ==> eq ==> eq ==> eq ==> iff)\n                                 AnnIso.\nProof.\n  simpl_relation; split=> ?;\n  eauto using AnnIso_respects_atoms_eq, AtomSetProperties.equal_sym.\nQed.\n\nInstance AnnDefEq_atoms_eq_mor : Morphisms.Proper\n                                   (eq ==> AtomSetImpl.Equal ==> eq ==> eq ==> eq ==> iff)\n                                   AnnDefEq.\nProof.\n  simpl_relation; split=> ?;\n  eauto using AnnDefEq_respects_atoms_eq, AtomSetProperties.equal_sym.\nQed.\n\n\nLemma ann_strengthen_noncovar:\n  (forall G1  a A,   AnnTyping G1 a A -> True) /\\\n  (forall G1  phi,   AnnPropWff G1 phi -> True) /\\\n  (forall G1 D g p1 p2, AnnIso G1 D g p1 p2 -> forall x, not (exists phi, binds x (Co phi) G1) ->\n                     AnnIso G1 (remove x D) g p1 p2) /\\\n  (forall G1 D g A B,   AnnDefEq G1 D g A B ->  forall x, not (exists phi, binds x (Co phi) G1) ->\n                    AnnDefEq G1 (remove x D) g A B) /\\\n  (forall G1 ,       AnnCtx G1 -> True).\nProof.\n  apply ann_typing_wff_iso_defeq_mutual; eauto 3; try done.\n  - econstructor; eauto.\n  - intros. destruct (x == c).\n    + subst. assert False. apply H0. eexists. eauto. done.\n    + eapply An_Assn; eauto.\n  - econstructor; eauto.\n  - intros.\n    eapply (An_PiCong (L \\u singleton x \\u dom G)); eauto.\n    intros. eapply H0; auto.\n    unfold not in *. intros. destruct H6. apply H4.\n    simpl in H6.\n    destruct (binds_cons_1 _ x x0 _ (Tm A1) G H6). destruct H7. inversion H8.\n    exists x1. auto.\n  - intros.\n    eapply (An_AbsCong (L \\u singleton x)); eauto.\n    intros. eapply H0; auto.\n    unfold not in *. intros. destruct H6. apply H4.\n    simpl in H6.\n    destruct (binds_cons_1 _ x x0 _ (Tm A1) G H6). destruct H7. inversion H8.\n    exists x1. auto.\n  - eauto.\n  - eauto.\n  - intros.\n    eapply (An_CPiCong (L \\u singleton x)); eauto.\n    intros.\n    eapply H0; auto.\n    unfold not in *. intros. destruct H6. apply H4.\n    simpl in H6.\n    destruct (binds_cons_1 _ x c _ (Co phi1) G H6). destruct H7.\n    subst. fsetdec.\n    exists x0. auto.\n  - intros.\n    eapply (An_CAbsCong (L \\u singleton x)); eauto.\n    move=> c Fr.\n    eapply H0; first fsetdec.\n    move=> [phi b].\n    move: b => /binds_cons_iff [[? [?]] | /= b]; first (subst; fsetdec).\n      by apply H5; exists phi.\n  - eauto.\nQed. (* strengthen_nocovar *)\n\nLemma AnnDefEq_strengthen_available_tm :\n  forall G D g A B, AnnDefEq G D g A B ->  forall x A', binds x (Tm A') G ->\n                    forall D', D' [=] remove x D ->\n                    AnnDefEq G D' g A B.\nProof.\n  intros. eapply ann_respects_atoms_eq_mutual.\n  eapply (fourth ann_strengthen_noncovar). eauto.\n  unfold not.\n  intros b. destruct b as [phi b].\n  assert (Tm A' = Co phi). eapply binds_unique; eauto with ctx_wff.\n  inversion H2.\n  fsetdec.\nQed.\n\nLemma ann_weaken_available_mutual:\n  (forall G1  a A,   AnnTyping G1 a A -> True) /\\\n  (forall G1  phi,   AnnPropWff G1 phi -> True) /\\\n  (forall G1 D g p1 p2, AnnIso G1 D g p1 p2 -> forall D', D [<=] D' -> AnnIso G1 D' g p1 p2) /\\\n  (forall G1 D g A B,   AnnDefEq G1 D g A B -> forall D', D [<=] D' -> AnnDefEq G1 D' g A B) /\\\n  (forall G1 ,       AnnCtx G1 -> True).\nProof.\n  apply ann_typing_wff_iso_defeq_mutual; eauto 3; try done.\n  all: econstructor; eauto.\nQed.\n\nLemma ann_remove_available_mutual:\n  (forall G1  a A,   AnnTyping G1 a A -> True) /\\\n  (forall G1  phi,   AnnPropWff G1 phi -> True) /\\\n  (forall G1 D g p1 p2, AnnIso G1 D g p1 p2 ->\n                   AnnIso G1 (AtomSetImpl.inter D (dom G1)) g p1 p2) /\\\n  (forall G1 D g A B,   AnnDefEq G1 D g A B ->\n                   AnnDefEq G1 (AtomSetImpl.inter D (dom G1)) g A B) /\\\n  (forall G1 ,       AnnCtx G1 -> True).\nProof.\n  apply ann_typing_wff_iso_defeq_mutual; eauto 3; try done.\n  - intros L G D. intros.\n    eapply (An_PiCong (L \\u dom G \\u D)); eauto.\n    intros.\n    eapply (fourth ann_respects_atoms_eq_mutual). eapply H0. eauto.\n    simpl. fsetdec.\n  - intros L G D. intros.\n    eapply (An_AbsCong (L \\u dom G \\u D)); eauto.\n    intros.\n    eapply (fourth ann_respects_atoms_eq_mutual). eapply H0. eauto.\n    simpl. fsetdec.\n  - intros L G D. intros.\n    eapply (An_CPiCong (L \\u dom G \\u D)); eauto.\n    intros.\n    eapply (fourth ann_respects_atoms_eq_mutual). eapply H0. eauto.\n    simpl. fsetdec.\n  - intros L G D. intros.\n    eapply (An_CAbsCong (L \\u dom G \\u D)); eauto 1.\n    intros.\n    eapply (fourth ann_respects_atoms_eq_mutual). eapply H0. eauto.\n    simpl. fsetdec.\n    eauto.\nQed.\n\nLemma AnnDefEq_weaken_available :\n  forall G D g A B, AnnDefEq G D g A B -> AnnDefEq G (dom G) g A B.\nProof.\n  intros.\n  remember (AtomSetImpl.inter D (dom G)) as D'.\n  eapply (fourth ann_weaken_available_mutual).\n  eapply (fourth ann_remove_available_mutual).\n  eauto. subst. fsetdec.\nQed.\n\nLemma AnnIso_weaken_available :\n  forall G D g A B, AnnIso G D g A B -> AnnIso G (dom G) g A B.\nProof.\n  intros G D. intros.\n  remember (AtomSetImpl.inter D (dom G)) as D'.\n  eapply (third ann_weaken_available_mutual).\n  eapply (third ann_remove_available_mutual).\n  eauto. subst. fsetdec.\nQed.\n\nInstance AnnIso_atoms_sub_mor : Morphisms.Proper\n                                    (eq ==> AtomSetImpl.Subset ==> eq ==> eq ==> eq ==> impl)\n                                    AnnIso.\nProof.\n  simpl_relation; eapply (third ann_weaken_available_mutual); eassumption.\nQed.\n\nInstance AnnDefEq_atoms_sub_mor : Morphisms.Proper\n                                    (eq ==> AtomSetImpl.Subset ==> eq ==> eq ==> eq ==> impl)\n                                    AnnDefEq.\nProof.\n  simpl_relation; eapply (fourth ann_weaken_available_mutual); eassumption.\nQed.\n\n\n(* FIXME: temporary hack *)\nLtac ann_weak_speedup :=\n  first [eapply An_AppCong | eapply An_PiSnd].\n\n\n(* ------------------------------------------------------------------- *)\n\nLemma ann_typing_weakening_mutual:\n  (forall G0 a A,       AnnTyping  G0 a A       ->\n     forall E F G, (G0 = F ++ G) -> AnnCtx (F ++ E ++ G) -> AnnTyping (F ++ E ++ G) a A) /\\\n  (forall G0 phi,       AnnPropWff G0 phi       ->\n     forall E F G, (G0 = F ++ G) ->\n        AnnCtx (F ++ E ++ G) -> AnnPropWff (F ++ E ++ G) phi) /\\\n  (forall G0 D g p1 p2, AnnIso     G0 D g p1 p2 ->\n     forall E F G, (G0 = F ++ G) ->\n        AnnCtx (F ++ E ++ G) -> AnnIso (F ++ E ++ G) D g p1 p2) /\\\n  (forall G0 D g A B,   AnnDefEq   G0 D g A B   ->\n     forall E F G, (G0 = F ++ G) ->\n        AnnCtx (F ++ E ++ G) -> AnnDefEq (F ++ E ++ G) D g A B) /\\\n  (forall G0,           AnnCtx     G0           ->\n     forall E F G, (G0 = F ++ G) ->\n        AnnCtx (F ++ E ++ G) -> AnnCtx (F ++ E ++ G)).\nProof.\n  eapply ann_typing_wff_iso_defeq_mutual.\n  all: pre; subst.\n  all: eauto 3.\n  all: try first [ ann_weak_speedup\n                 | An_pick_fresh x;\n                   try auto_rew_env;\n                   try apply_first_hyp;\n                   try simpl_env];\n                   eauto 3.\n  all: try solve [econstructor; eauto 2].\n  all: try solve [eapply AnnDefEq_weaken_available; eauto 2].\n  all: try solve [try rewrite <- dom_app; try rewrite <- dom_app;\n                  eapply AnnDefEq_weaken_available;  eauto].\n  all: try solve [econstructor; eauto 2;\n                  eapply AnnDefEq_weaken_available; eauto 2].\n  all: try solve [\n    (* These are all AnnCtx goals. Need to show the new assumption\n       is well-formed by using induction on a term that mentions it.\n     *)\n    econstructor; eauto 2;\n      by move: (H1 E F G0 eq_refl ltac:(auto)); inversion 1].\n\n  (* Left/Right\n  eapply An_Right with (a:=a)(a':=a'); eauto 2;\n    eapply AnnDefEq_weaken_available; eauto 2. *)\nQed.\n\nDefinition AnnTyping_weakening  := first  ann_typing_weakening_mutual.\nDefinition AnnPropWff_weakening := second ann_typing_weakening_mutual.\nDefinition AnnIso_weakening     := third  ann_typing_weakening_mutual.\nDefinition AnnDefEq_weakening   := fourth ann_typing_weakening_mutual.\nDefinition AnnCtx_weakening     := fifth  ann_typing_weakening_mutual.\n\nEnd fc_weak.\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_weak.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878414043816, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.28117923638010983}}
{"text": "Set Implicit Arguments.\n\nRequire Import GLabel GLabelMap GLabelMapFacts ConvertLabel GoodModule GoodFunction NameDecoration.\nExport GLabel GLabelMap GLabelMapFacts ConvertLabel GoodModule GoodFunction NameDecoration.\nImport GLabelMap.\n\nDefinition name_marker (id : glabel) : PropX W (settings * state) := (Ex s, [| s = id |])%PropX.\n\nRequire Import ADT.\n\nModule Make (Import E : ADT).\n\n  Require Import Semantics.\n  Module Import SemanticsMake := Make E.\n  Export Semantics SemanticsMake.\n\n  Section TopSection.\n\n    Variable modules : list GoodModule.\n\n    Variable imports : t ForeignFuncSpec.\n\n    Notation FName := SyntaxFunc.Name.\n    Notation MName := GoodModule.Name.\n\n    Definition label_in (lbl : glabel) :=\n      (exists m f,\n         List.In m modules /\\\n         List.In f (Functions m) /\\\n         lbl = (MName m, FName f)) \\/\n      In lbl imports.\n\n    Definition label_mapsto lbl spec :=\n      (exists ispec m f,\n         spec = Internal ispec /\\\n         List.In m modules /\\\n         List.In f (Functions m) /\\\n         ispec = f /\\ \n         lbl = (MName m, FName f)) \\/\n      (exists fspec,\n         spec = Foreign fspec /\\\n         find lbl imports = Some fspec).\n\n    Definition stn_good_to_use (stn : settings) :=\n      forall lbl : glabel,\n        label_in lbl ->\n        Labels stn lbl <> None.\n\n    Definition stn_injective (stn : settings) :=\n      forall lbl1 lbl2 p, \n        label_in lbl1 -> \n        label_in lbl2 -> \n        Labels stn lbl1 = Some p -> \n        Labels stn lbl2 = Some p -> \n        lbl1 = lbl2.\n\n    Definition fs_good_to_use (fs : settings -> W -> option Callee) (stn : settings) :=\n      forall p spec, \n        fs stn p = Some spec <-> \n        exists lbl : glabel,\n          Labels stn lbl = Some p /\\\n          label_mapsto lbl spec.\n\n    Definition env_good_to_use stn fs :=\n      stn_good_to_use stn /\\\n      stn_injective stn /\\\n      fs_good_to_use fs stn.\n\n    Definition func_export_IFS m (f : GoodFunction) := ((MName m, FName f), f : InternalFuncSpec).\n        \n    Definition module_exports_IFS m := \n      List.map (func_export_IFS m) (Functions m).\n\n    Require Import ListFacts1.\n\n    Definition exports_IFS :=\n      to_map\n        (app_all \n           (List.map module_exports_IFS modules)).\n\n    Section fs.\n\n      Variable stn : settings.\n\n      Definition labels (lbl : glabel) : option W := Labels stn lbl.\n\n      Definition is_label_map_to_word lbl p :=\n        match labels lbl with\n          | Some p' => \n            if weq p p' then\n              true\n            else\n              false\n          | None => false\n        end.\n\n      Definition is_label_map_to_word' A p (x : glabel * A) := is_label_map_to_word (fst x) p.\n\n      Definition find_by_word A m (p : W) : option A :=\n        match List.find (is_label_map_to_word' p) m with\n          | Some (_, a) => Some a\n          | None => None\n        end.\n\n      Definition is_export := find_by_word (elements exports_IFS).\n\n      Definition is_import := find_by_word (elements imports).\n\n      Definition fs (p : W) : option Callee :=\n        match is_export p with\n          | Some spec => Some (Internal spec)\n          | None => \n            match is_import p with\n              | Some spec => Some (Foreign spec)\n              | None => None\n            end\n        end.\n\n    End fs.\n\n  End TopSection.\n\n  Require Import RepInv.\n\n  Module Make (Import M : RepInv E).\n\n    Require Import CompileFuncSpec.\n    Module Import CompileFuncSpecMake := Make E M.\n    Import InvMake2.\n    Export CompileFuncSpec CompileFuncSpecMake InvMake2.\n\n    Section TopSection.\n\n      Variable modules : list GoodModule.\n\n      Variable imps : t ForeignFuncSpec.\n\n      Notation fs := (fs modules imps).\n      \n      Definition func_spec (id : glabel) f : assert := (st ~> name_marker id /\\ [| env_good_to_use modules imps (fst st) fs |] ---> spec_without_funcs_ok f fs st)%PropX.\n\n      Definition foreign_func_spec id spec : assert := \n        st ~> name_marker id /\\ ExX, foreign_spec _ spec st.\n\n      Definition imports := mapi (foreign_func_spec) imps.\n\n      Notation FName := SyntaxFunc.Name.\n      Notation MName := GoodModule.Name.\n\n      Definition func_export module (f : GoodFunction) :=\n        let lbl := (MName module, FName f) in\n        (lbl, func_spec lbl f).\n\n      Definition module_exports m := \n        of_list\n          (List.map \n             (func_export m)\n             (Functions m)).\n\n      Definition exports := update_all (List.map module_exports modules).\n\n      Definition impl_label mod_name f_name : glabel := (impl_module_name mod_name, f_name).\n\n      Definition func_impl_export m (f : GoodFunction) := (impl_label (MName m) (FName f), spec f).\n\n      Definition module_impl_exports m := \n        of_list\n          (List.map \n             (func_impl_export m)\n             (Functions m)).\n\n      Definition impl_exports := update_all (List.map module_impl_exports modules).\n\n      Definition all_exports := update exports impl_exports.\n\n    End TopSection.\n\n  End Make.\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/LinkSpec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878414043814, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2811792363801097}}
{"text": "Require Import String List Bool.\nRequire Import ExtLib.Structures.Maps.\nRequire Import ExtLib.Structures.Monads.\nRequire Import ExtLib.Structures.Reducible.\nRequire Import ExtLib.Data.Option.\nRequire Import ExtLib.Data.Lists.\nRequire Import ExtLib.Core.RelDec.\nRequire Import ExtLib.Data.Set.ListSet.\nRequire Import ExtLib.Data.Map.FMapAList.\nRequire Import CoqCompile.CpsK.\nRequire Import CoqCompile.Analyze.CFA0.\nRequire Import CoqCompile.CpsKUtil.\n\nImport CpsK.CPSK.\n\nSection REACHABLE.\n    \n  Definition useful_ptv (v:PtValue unit) : lset (@eq (var + cont)) :=\n    match v with\n      | Ctor c => Sets.empty\n      | Int i => Sets.empty\n      | Ptr l => Sets.singleton (inl l)\n      | Clo c pp ks xs e =>\n        match pp with\n          | inl v => free_vars_decl true (Fn_d v ks xs e)\n          | inr k => free_vars_cont k xs e\n        end\n    end.\n\n  Definition useful (vs:lset (@eq (PtValue unit))) : lset (@eq (var + cont)) :=\n    fold (fun v acc => Sets.union acc (useful_ptv v)) Sets.empty vs.\n\n  Definition D : Type := alist (var + cont) (lset (@eq (var + cont))).\n\n  Definition reachable_1 (env:alist (var + cont) (Value unit)) (dom:D) : D.\n  refine (\n    fold (fun kv acc => \n      let '(k, v) := kv in \n      let res := match v with\n                   | Any => keys _ _ env\n                   | Values vs => _\n                 end in\n      Maps.add k res acc) dom env).\n  refine (match Maps.lookup k acc with\n            | Some old_set => Sets.union old_set (useful vs)\n            | None => useful vs\n          end).\n  Defined.\n  \n  Definition reachable_2 (heap:alist var (list (Value unit))) (dom : D) : D :=\n    fold (fun kv acc =>\n      let '(k,v) := kv in\n      let res := fold (fun v' acc' =>\n        match v' with\n          | inl v' =>\n            match Maps.lookup v' heap with\n              | None => acc'\n              | Some vs => List.fold_left (fun acc x =>\n                match x with\n                  | Any => map (fun x => inl x) (keys _ (s := lset (@eq var)) _ heap)\n                  | Values vs => Sets.union (useful vs) acc\n                end ) vs acc'\n            end\n          | inr _ => acc'\n        end) v v in\n      Maps.add k res acc) dom dom.\n\n  Require Import BinNums.\n  Require Import ExtLib.Data.Monads.FuelMonad.\n  Require Import ExtLib.Data.Monads.IdentityMonad.\n  \n  Definition least_fixpoint {A} (leq : A -> A -> bool) (f : A -> A) (init : A) (fuel : N) : option A :=\n    unIdent (runGFixT (mfix (fun recur x =>\n      let x' := f x in\n      if leq x' x then ret x' else recur x') init) fuel).\n\n  Definition dom_eq (d1 d2 : D) : bool :=\n    let f := fun s1 s2 => (Sets.subset s1 s2) && Sets.subset s2 s1 in\n    submap_with _ f d1 d2 &&\n    submap_with _ f d2 d1.\n\n  Definition reachable (env:alist (var + cont) (Value unit)) (heap:alist var (list (Value unit))) (fuel : N) : option D :=\n    least_fixpoint dom_eq (reachable_2 heap) (reachable_1 env Maps.empty) fuel.\n  \nEnd REACHABLE.  \n\nSection LIVENESS.\n  \n  Variable reach : alist (var + cont) (lset (@eq (var + cont))).\n\n  (* let x = <1, 2>\n          .\n          .\n          .\n     let y = <3, 4>\n          .\n          .\n          .\n     in k z\n\n   *)\n\n  (* Do we need this??? *)\n  Fixpoint escape_cont_exp (e:exp) (acc:lset (@eq (var + cont))) : (lset (@eq (var + cont))) :=\n    match e with\n      | App_e o ks os => acc\n      | Let_e d e' => escape_cont_exp e' (Sets.union (escape_cont_decl d acc) acc)\n      | Letrec_e ds e' =>\n        escape_cont_exp e' (List.fold_left (fun acc' x => Sets.union (escape_cont_decl x acc) acc') ds acc)\n      | Switch_e o arms def =>\n        let arms_escape := List.fold_left (fun acc' x => \n          let '(p, e) := x in Sets.union (escape_cont_exp e acc) acc') arms acc in\n        match def with\n          | Some e => Sets.union arms_escape (escape_cont_exp e acc)\n          | None => arms_escape\n        end\n      | Halt_e o1 o2 => acc \n      | AppK_e k os => List.fold_left (fun acc' x => match x with\n                                                      | Var_o x => Sets.add (inl x) acc'\n                                                      | _ => acc'\n                                                    end) os acc\n      | LetK_e kves e' =>\n        List.fold_left (fun acc' x => let '(k,x,e) := x in\n          Sets.union (escape_cont_exp e acc) acc') kves acc\n    end\n  with escape_cont_decl (d:decl) (acc:lset (@eq (var + cont))) : (lset (@eq (var + cont))) :=\n    match d with\n      | Op_d x os => acc\n      | Prim_d x p os => acc \n      | Fn_d x ks xs e => escape_cont_exp e acc\n      | Bind_d x w m os => acc\n    end.\n\n  Definition live_set (e:exp) : (lset (@eq (var + cont))) :=\n    (* let escape := Sets.union (free_vars_exp e) (escape_cont_exp e Sets.empty) in *)\n    let escape := free_vars_exp e in\n    fold (fun x acc => match Maps.lookup x reach with\n                         | Some s => Sets.union s acc\n                         | None => acc\n                       end) Sets.empty escape.\n\n  Definition var_of_decl (d:decl) : var :=\n    match d with\n      | Op_d x _ => x\n      | Prim_d x _ _ => x\n      | Fn_d x _ _ _ => x\n      | Bind_d x _ _ _ => x\n    end.\n\n  Fixpoint live_exp (e:exp) (dom:alist (var + cont) (lset (@eq (var + cont)))) :\n    alist (var + cont) (lset (@eq (var + cont))) :=\n    match e with\n      | App_e o ks os => dom\n      | Let_e d e' =>\n        let live_stuff := live_set e' in\n        let x := var_of_decl d in\n        let live_stuff := match Maps.lookup (inl x) dom with\n                            | Some old_set => Sets.union old_set live_stuff\n                            | None => live_stuff\n                          end in\n        let dom' := live_decl d (Maps.add (inl x) live_stuff dom) in\n        live_exp e' dom'\n      | Letrec_e ds e' =>\n        List.fold_left (fun acc d =>\n          let live_stuff := live_set e' in\n          let x := var_of_decl d in\n          let live_stuff := match Maps.lookup (inl x) acc with\n                              | Some old_set => Sets.union old_set live_stuff\n                              | None => live_stuff\n                            end in\n          let dom' := Maps.add (inl x) live_stuff acc in\n          let dom' := live_decl d dom' in\n          live_exp e' dom') ds dom\n      | Switch_e o arms def =>\n        let dom' := List.fold_left (fun acc x => let '(p, e') := x in \n          Maps.combine (fun k v1 v2 => Sets.union v1 v2) (live_exp e' acc) acc) arms dom in\n        match def with\n          | Some e' => Maps.combine (fun k v1 v2 => Sets.union v1 v2) (live_exp e' dom') dom'\n          | None => dom'\n        end\n      | Halt_e o1 o2 => dom\n      | AppK_e k os => dom\n      | LetK_e kxse e' =>\n        let dom' := List.fold_left (fun acc x => let '(k, xs, e') := x in\n          live_exp e' acc) kxse dom in\n        live_exp e' dom'\n    end\n  with live_decl (d:decl) (dom:alist (var + cont) (lset (@eq (var + cont)))) :\n    alist (var + cont) (lset (@eq (var + cont))) :=\n    match d with\n      | Op_d x os => dom\n      | Prim_d x p os => dom\n      | Fn_d x ks xs e => live_exp e dom\n      | Bind_d x w m os => dom\n    end.\n\nEnd LIVENESS.\n\nSection monadic.\n  Require Import CoqCompile.TraceMonad.\n  Import MonadNotation.\n  Local Open Scope monad_scope.\n\n  Variable m : Type -> Type.\n  Context {Monad_m : Monad m}.\n  Context {MonadTrace_m : MonadTrace string m}.\n  Context {MonadExc_m : MonadExc string m}.\n\n  Definition sanitize {A B} {_ : RelDec (@eq B)} (env:alist (unit * B) A) : (alist B A) :=\n    fold (fun kv acc => \n      let '(k, v) := kv in\n      let '(_, k) := k in\n      Maps.add k v acc) Maps.empty env.\n\n  Require Import CoqCompile.Opt.CopyPropCpsK.\n\n  Definition construct_live_map (e:exp) (fuel:N) : m (option (alist (var + cont) (lset (@eq (var + cont))))) :=\n    catch (\n      let e := CopyProp.copyprop e in\n      domain <- cfa_n _ 0 e fuel ;;\n      let sanitized := sanitize (env _ domain) in\n      let sanitized_heap := sanitize (heap _ domain) in\n      match reachable sanitized sanitized_heap fuel with\n        | None => raise \"reachable ran out of fuel\"%string\n        | Some dom' =>\n        let live := live_exp dom' e Maps.empty in\n          ret (Some live)\n      end\n    ) (fun err =>\n      mlog (\"construct_live_map failed: \" ++ err)%string ;;\n      ret None\n    ).\nEnd monadic.\n\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/Analyze/Reachability.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.28113905073160733}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nFrom compcert Require Import Coqlib.\nFrom compcert Require Import Iteration.\nFrom compcert Require Import Maps.\nFrom compcert Require Import Lattice.\n\n\nLocal Unset Elimination Schemes.\nLocal Unset Case Analysis Schemes.\n\n\n\n\n\n\n\nModule Type DATAFLOW_SOLVER.\n\nDeclare Module L: SEMILATTICE.\n\n\n\nParameter fixpoint:\nforall {A: Type} (code: PTree.t A) (successors: A -> list positive)\n(transf: positive -> L.t -> L.t)\n(ep: positive) (ev: L.t),\noption (PMap.t L.t).\n\n\n\nAxiom fixpoint_solution:\nforall A (code: PTree.t A) successors transf ep ev res n instr s,\nfixpoint code successors transf ep ev = Some res ->\ncode!n = Some instr -> In s (successors instr) ->\n(forall n, L.eq (transf n L.bot) L.bot) ->\nL.ge res!!s (transf n res!!n).\n\n\n\nAxiom fixpoint_entry:\nforall A (code: PTree.t A) successors transf ep ev res,\nfixpoint code successors transf ep ev = Some res ->\nL.ge res!!ep ev.\n\n\n\nAxiom fixpoint_invariant:\nforall A (code: PTree.t A) successors transf ep ev\n(P: L.t -> Prop),\nP L.bot ->\n(forall x y, P x -> P y -> P (L.lub x y)) ->\n(forall pc instr x, code!pc = Some instr -> P x -> P (transf pc x)) ->\nP ev ->\nforall res pc,\nfixpoint code successors transf ep ev = Some res ->\nP res!!pc.\n\nEnd DATAFLOW_SOLVER.\n\n\n\nModule Type NODE_SET.\n\nParameter t: Type.\nParameter empty: t.\nParameter add: positive -> t -> t.\nParameter pick: t -> option (positive * t).\nParameter all_nodes: forall {A: Type}, PTree.t A -> t.\n\nParameter In: positive -> t -> Prop.\nAxiom empty_spec:\nforall n, ~In n empty.\nAxiom add_spec:\nforall n n' s, In n' (add n s) <-> n = n' \\/ In n' s.\nAxiom pick_none:\nforall s n, pick s = None -> ~In n s.\nAxiom pick_some:\nforall s n s', pick s = Some(n, s') ->\nforall n', In n' s <-> n = n' \\/ In n' s'.\nAxiom all_nodes_spec:\nforall A (code: PTree.t A) n instr,\ncode!n = Some instr -> In n (all_nodes code).\n\nEnd NODE_SET.\n\n\n\nSection REACHABLE.\n\nContext {A: Type} (code: PTree.t A) (successors: A -> list positive).\n\nInductive reachable: positive -> positive -> Prop :=\n| reachable_refl: forall n, reachable n n\n| reachable_left: forall n1 n2 n3 i,\ncode!n1 = Some i -> In n2 (successors i) -> reachable n2 n3 ->\nreachable n1 n3.\n\nScheme reachable_ind := Induction for reachable Sort Prop.\n\nLemma reachable_trans:\nforall n1 n2, reachable n1 n2 -> forall n3, reachable n2 n3 -> reachable n1 n3.\nProof. hammer_hook \"Kildall\" \"Kildall.reachable_trans\".\ninduction 1; intros.\n- auto.\n- econstructor; eauto.\nQed.\n\nLemma reachable_right:\nforall n1 n2 n3 i,\nreachable n1 n2 -> code!n2 = Some i -> In n3 (successors i) ->\nreachable n1 n3.\nProof. hammer_hook \"Kildall\" \"Kildall.reachable_right\".\nintros. apply reachable_trans with n2; auto. econstructor; eauto. constructor.\nQed.\n\nEnd REACHABLE.\n\n\n\nModule Dataflow_Solver (LAT: SEMILATTICE) (NS: NODE_SET) <:\nDATAFLOW_SOLVER with Module L := LAT.\n\nModule L := LAT.\n\nSection Kildall.\n\nContext {A: Type}.\nVariable code: PTree.t A.\nVariable successors: A -> list positive.\nVariable transf: positive -> L.t -> L.t.\n\n\n\nRecord state : Type :=\nmkstate { aval: PTree.t L.t; worklist: NS.t; visited: positive -> Prop }.\n\nDefinition abstr_value (n: positive) (s: state) : L.t :=\nmatch s.(aval)!n with\n| None => L.bot\n| Some v => v\nend.\n\n\n\n\n\nDefinition propagate_succ (s: state) (out: L.t) (n: positive) :=\nmatch s.(aval)!n with\n| None =>\n{| aval := PTree.set n out s.(aval);\nworklist := NS.add n s.(worklist);\nvisited := fun p => p = n \\/ s.(visited) p |}\n| Some oldl =>\nlet newl := L.lub oldl out in\nif L.beq oldl newl\nthen s\nelse {| aval := PTree.set n newl s.(aval);\nworklist := NS.add n s.(worklist);\nvisited := fun p => p = n \\/ s.(visited) p |}\nend.\n\n\n\nFixpoint propagate_succ_list (s: state) (out: L.t) (succs: list positive)\n{struct succs} : state :=\nmatch succs with\n| nil => s\n| n :: rem => propagate_succ_list (propagate_succ s out n) out rem\nend.\n\n\n\nDefinition step (s: state) : PMap.t L.t + state :=\nmatch NS.pick s.(worklist) with\n| None =>\ninl _ (L.bot, s.(aval))\n| Some(n, rem) =>\nmatch code!n with\n| None =>\ninr _ {| aval := s.(aval); worklist := rem; visited := s.(visited) |}\n| Some instr =>\ninr _ (propagate_succ_list\n{| aval := s.(aval); worklist := rem; visited := s.(visited) |}\n(transf n (abstr_value n s))\n(successors instr))\nend\nend.\n\n\n\nDefinition fixpoint_from (start: state) : option (PMap.t L.t) :=\nPrimIter.iterate _ _ step start.\n\n\n\nDefinition start_state (enode: positive) (eval: L.t) :=\n{| aval := PTree.set enode eval (PTree.empty L.t);\nworklist := NS.add enode NS.empty;\nvisited := fun n => n = enode |}.\n\nDefinition fixpoint (enode: positive) (eval: L.t) :=\nfixpoint_from (start_state enode eval).\n\n\n\nDefinition start_state_nodeset (enodes: NS.t) :=\n{| aval := PTree.empty L.t;\nworklist := enodes;\nvisited := fun n => NS.In n enodes |}.\n\nDefinition fixpoint_nodeset (enodes: NS.t) :=\nfixpoint_from (start_state_nodeset enodes).\n\nDefinition start_state_allnodes :=\n{| aval := PTree.empty L.t;\nworklist := NS.all_nodes code;\nvisited := fun n => exists instr, code!n = Some instr |}.\n\nDefinition fixpoint_allnodes :=\nfixpoint_from start_state_allnodes.\n\n\n\nInductive optge: option L.t -> option L.t -> Prop :=\n| optge_some: forall l l',\nL.ge l l' -> optge (Some l) (Some l')\n| optge_none: forall ol,\noptge ol None.\n\nRemark optge_refl: forall ol, optge ol ol.\nProof. hammer_hook \"Kildall\" \"Kildall.Dataflow_Solver.optge_refl\". destruct ol; constructor. apply L.ge_refl; apply L.eq_refl. Qed.\n\nRemark optge_trans: forall ol1 ol2 ol3, optge ol1 ol2 -> optge ol2 ol3 -> optge ol1 ol3.\nProof. hammer_hook \"Kildall\" \"Kildall.Dataflow_Solver.optge_trans\".\nintros. inv H0.\ninv H. constructor. eapply L.ge_trans; eauto.\nconstructor.\nQed.\n\nRemark optge_abstr_value:\nforall st st' n,\noptge st.(aval)!n st'.(aval)!n ->\nL.ge (abstr_value n st) (abstr_value n st').\nProof. hammer_hook \"Kildall\" \"Kildall.Dataflow_Solver.optge_abstr_value\".\nintros. unfold abstr_value. inv H. auto. apply L.ge_bot.\nQed.\n\nLemma propagate_succ_charact:\nforall st out n,\nlet st' := propagate_succ st out n in\noptge st'.(aval)!n (Some out)\n/\\ (forall s, n <> s -> st'.(aval)!s = st.(aval)!s)\n/\\ (forall s, optge st'.(aval)!s st.(aval)!s)\n/\\ (NS.In n st'.(worklist) \\/ st'.(aval)!n = st.(aval)!n)\n/\\ (forall n', NS.In n' st.(worklist) -> NS.In n' st'.(worklist))\n/\\ (forall n', NS.In n' st'.(worklist) -> n' = n \\/ NS.In n' st.(worklist))\n/\\ (forall n', st.(visited) n' -> st'.(visited) n')\n/\\ (forall n', st'.(visited) n' -> NS.In n' st'.(worklist) \\/ st.(visited) n')\n/\\ (forall n', st.(aval)!n' = None -> st'.(aval)!n' <> None -> st'.(visited) n').\nProof. hammer_hook \"Kildall\" \"Kildall.Dataflow_Solver.propagate_succ_charact\".\nunfold propagate_succ; intros; simpl.\ndestruct st.(aval)!n as [v|] eqn:E;\n[predSpec L.beq L.beq_correct v (L.lub v out) | idtac].\n-\nrepeat split; intros.\n+ rewrite E. constructor. eapply L.ge_trans. apply L.ge_refl. apply H; auto. apply L.ge_lub_right.\n+ apply optge_refl.\n+ right; auto.\n+ auto.\n+ auto.\n+ auto.\n+ auto.\n+ congruence.\n-\nsimpl; repeat split; intros.\n+ rewrite PTree.gss. constructor. apply L.ge_lub_right.\n+ rewrite PTree.gso by auto. auto.\n+ rewrite PTree.gsspec. destruct (peq s n).\nsubst s. rewrite E. constructor. apply L.ge_lub_left.\napply optge_refl.\n+ rewrite NS.add_spec. auto.\n+ rewrite NS.add_spec. auto.\n+ rewrite NS.add_spec in H0. intuition.\n+ auto.\n+ destruct H0; auto. subst n'. rewrite NS.add_spec; auto.\n+ rewrite PTree.gsspec in H1. destruct (peq n' n). auto. congruence.\n-\nsimpl; repeat split; intros.\n+ rewrite PTree.gss. apply optge_refl.\n+ rewrite PTree.gso by auto. auto.\n+ rewrite PTree.gsspec. destruct (peq s n).\nsubst s. rewrite E. constructor.\napply optge_refl.\n+ rewrite NS.add_spec. auto.\n+ rewrite NS.add_spec. auto.\n+ rewrite NS.add_spec in H. intuition.\n+ auto.\n+ destruct H; auto. subst n'. rewrite NS.add_spec. auto.\n+ rewrite PTree.gsspec in H0. destruct (peq n' n). auto. congruence.\nQed.\n\nLemma propagate_succ_list_charact:\nforall out l st,\nlet st' := propagate_succ_list st out l in\n(forall n, In n l -> optge st'.(aval)!n (Some out))\n/\\ (forall n, ~In n l -> st'.(aval)!n = st.(aval)!n)\n/\\ (forall n, optge st'.(aval)!n st.(aval)!n)\n/\\ (forall n, NS.In n st'.(worklist) \\/ st'.(aval)!n = st.(aval)!n)\n/\\ (forall n', NS.In n' st.(worklist) -> NS.In n' st'.(worklist))\n/\\ (forall n', NS.In n' st'.(worklist) -> In n' l \\/ NS.In n' st.(worklist))\n/\\ (forall n', st.(visited) n' -> st'.(visited) n')\n/\\ (forall n', st'.(visited) n' -> NS.In n' st'.(worklist) \\/ st.(visited) n')\n/\\ (forall n', st.(aval)!n' = None -> st'.(aval)!n' <> None -> st'.(visited) n').\nProof. hammer_hook \"Kildall\" \"Kildall.Dataflow_Solver.propagate_succ_list_charact\".\ninduction l; simpl; intros.\n- repeat split; intros.\n+ contradiction.\n+ apply optge_refl.\n+ auto.\n+ auto.\n+ auto.\n+ auto.\n+ auto.\n+ congruence.\n- generalize (propagate_succ_charact st out a).\nset (st1 := propagate_succ st out a).\nintros (A1 & A2 & A3 & A4 & A5 & A6 & A7 & A8 & A9).\ngeneralize (IHl st1).\nset (st2 := propagate_succ_list st1 out l).\nintros (B1 & B2 & B3 & B4 & B5 & B6 & B7 & B8 & B9). clear IHl.\nrepeat split; intros.\n+ destruct H.\n* subst n. eapply optge_trans; eauto.\n* auto.\n+ rewrite B2 by tauto. apply A2; tauto.\n+ eapply optge_trans; eauto.\n+ destruct (B4 n). auto.\ndestruct (peq n a).\n* subst n. destruct A4. left; auto. right; congruence.\n* right. rewrite H. auto.\n+ eauto.\n+ exploit B6; eauto. intros [P|P]. auto.\nexploit A6; eauto. intuition.\n+ eauto.\n+ specialize (B8 n'); specialize (A8 n'). intuition.\n+ destruct st1.(aval)!n' eqn:ST1.\napply B7. apply A9; auto. congruence.\napply B9; auto.\nQed.\n\n\n\nInductive steps: state -> state -> Prop :=\n| steps_base: forall s, steps s s\n| steps_right: forall s1 s2 s3, steps s1 s2 -> step s2 = inr s3 -> steps s1 s3.\n\nScheme steps_ind := Induction for steps Sort Prop.\n\nLemma fixpoint_from_charact:\nforall start res,\nfixpoint_from start = Some res ->\nexists st, steps start st /\\ NS.pick st.(worklist) = None /\\ res = (L.bot, st.(aval)).\nProof. hammer_hook \"Kildall\" \"Kildall.Dataflow_Solver.fixpoint_from_charact\".\nunfold fixpoint; intros.\neapply (PrimIter.iterate_prop _ _ step\n(fun st => steps start st)\n(fun res => exists st, steps start st /\\ NS.pick (worklist st) = None /\\ res = (L.bot, aval st))); eauto.\nintros. destruct (step a) eqn:E.\nexists a; split; auto.\nunfold step in E. destruct (NS.pick (worklist a)) as [[n rem]|].\ndestruct (code!n); discriminate.\ninv E. auto.\neapply steps_right; eauto.\nconstructor.\nQed.\n\n\n\n\n\nLemma step_incr:\nforall n s1 s2, step s1 = inr s2 ->\noptge s2.(aval)!n s1.(aval)!n /\\ (s1.(visited) n -> s2.(visited) n).\nProof. hammer_hook \"Kildall\" \"Kildall.Dataflow_Solver.step_incr\".\nunfold step; intros.\ndestruct (NS.pick (worklist s1)) as [[p rem] | ]; try discriminate.\ndestruct (code!p) as [instr|]; inv H.\n+ generalize (propagate_succ_list_charact\n(transf p (abstr_value p s1))\n(successors instr)\n{| aval := aval s1; worklist := rem; visited := visited s1 |}).\nsimpl.\nset (s' := propagate_succ_list {| aval := aval s1; worklist := rem; visited := visited s1 |}\n(transf p (abstr_value p s1)) (successors instr)).\nintros (A1 & A2 & A3 & A4 & A5 & A6 & A7 & A8 & A9).\nauto.\n+ split. apply optge_refl. auto.\nQed.\n\nLemma steps_incr:\nforall n s1 s2, steps s1 s2 ->\noptge s2.(aval)!n s1.(aval)!n /\\ (s1.(visited) n -> s2.(visited) n).\nProof. hammer_hook \"Kildall\" \"Kildall.Dataflow_Solver.steps_incr\".\ninduction 1.\n- split. apply optge_refl. auto.\n- destruct IHsteps. exploit (step_incr n); eauto. intros [P Q].\nsplit. eapply optge_trans; eauto. eauto.\nQed.\n\n\n\n\n\nRecord good_state (st: state) : Prop := {\ngs_stable: forall n,\nst.(visited) n ->\nNS.In n st.(worklist) \\/\n(forall i s,\ncode!n = Some i -> In s (successors i) ->\noptge st.(aval)!s (Some (transf n (abstr_value n st))));\ngs_defined: forall n v,\nst.(aval)!n = Some v -> st.(visited) n\n}.\n\n\n\nLemma step_state_good:\nforall st pc rem instr,\nNS.pick st.(worklist) = Some (pc, rem) ->\ncode!pc = Some instr ->\ngood_state st ->\ngood_state (propagate_succ_list (mkstate st.(aval) rem st.(visited))\n(transf pc (abstr_value pc st))\n(successors instr)).\nProof. hammer_hook \"Kildall\" \"Kildall.Dataflow_Solver.step_state_good\".\nintros until instr; intros PICK CODEAT [GOOD1 GOOD2].\ngeneralize (NS.pick_some _ _ _ PICK); intro PICK2.\nset (out := transf pc (abstr_value pc st)).\ngeneralize (propagate_succ_list_charact out (successors instr) {| aval := aval st; worklist := rem; visited := visited st |}).\nset (st' := propagate_succ_list {| aval := aval st; worklist := rem; visited := visited st |} out\n(successors instr)).\nsimpl; intros (A1 & A2 & A3 & A4 & A5 & A6 & A7 & A8 & A9).\nconstructor; intros.\n-\ndestruct (A8 n H); auto. destruct (A4 n); auto.\nreplace (abstr_value n st') with (abstr_value n st)\nby (unfold abstr_value; rewrite H1; auto).\nexploit GOOD1; eauto. intros [P|P].\n+\nrewrite PICK2 in P; destruct P.\n*\nsubst n. fold out. right; intros.\nassert (i = instr) by congruence. subst i.\napply A1; auto.\n*\nleft. apply A5; auto.\n+\nright; intros. apply optge_trans with st.(aval)!s; eauto.\n-\ndestruct st.(aval)!n as [v'|] eqn:ST.\n+ apply A7. eapply GOOD2; eauto.\n+ apply A9; auto. congruence.\nQed.\n\nLemma step_state_good_2:\nforall st pc rem,\ngood_state st ->\nNS.pick (worklist st) = Some (pc, rem) ->\ncode!pc = None ->\ngood_state (mkstate st.(aval) rem st.(visited)).\nProof. hammer_hook \"Kildall\" \"Kildall.Dataflow_Solver.step_state_good_2\".\nintros until rem; intros [GOOD1 GOOD2] PICK CODE.\ngeneralize (NS.pick_some _ _ _ PICK); intro PICK2.\nconstructor; simpl; intros.\n-\nexploit GOOD1; eauto. intros [P | P].\n+ rewrite PICK2 in P. destruct P; auto.\nsubst n. right; intros. congruence.\n+ right; exact P.\n-\neapply GOOD2; eauto.\nQed.\n\nLemma steps_state_good:\nforall st1 st2, steps st1 st2 -> good_state st1 -> good_state st2.\nProof. hammer_hook \"Kildall\" \"Kildall.Dataflow_Solver.steps_state_good\".\ninduction 1; intros.\n- auto.\n- unfold step in e.\ndestruct (NS.pick (worklist s2)) as [[n rem] | ] eqn:PICK; try discriminate.\ndestruct (code!n) as [instr|] eqn:CODE; inv e.\neapply step_state_good; eauto.\neapply step_state_good_2; eauto.\nQed.\n\n\n\nLemma start_state_good:\nforall enode eval, good_state (start_state enode eval).\nProof. hammer_hook \"Kildall\" \"Kildall.Dataflow_Solver.start_state_good\".\nintros. unfold start_state; constructor; simpl; intros.\n- subst n. rewrite NS.add_spec; auto.\n- rewrite PTree.gsspec in H. rewrite PTree.gempty in H.\ndestruct (peq n enode). auto. discriminate.\nQed.\n\nLemma start_state_nodeset_good:\nforall enodes, good_state (start_state_nodeset enodes).\nProof. hammer_hook \"Kildall\" \"Kildall.Dataflow_Solver.start_state_nodeset_good\".\nintros. unfold start_state_nodeset; constructor; simpl; intros.\n- left. auto.\n- rewrite PTree.gempty in H. congruence.\nQed.\n\nLemma start_state_allnodes_good:\ngood_state start_state_allnodes.\nProof. hammer_hook \"Kildall\" \"Kildall.Dataflow_Solver.start_state_allnodes_good\".\nunfold start_state_allnodes; constructor; simpl; intros.\n- destruct H as [instr CODE]. left. eapply NS.all_nodes_spec; eauto.\n- rewrite PTree.gempty in H. congruence.\nQed.\n\n\n\nLemma reachable_visited:\nforall st, good_state st -> NS.pick st.(worklist) = None ->\nforall p q, reachable code successors p q -> st.(visited) p -> st.(visited) q.\nProof. hammer_hook \"Kildall\" \"Kildall.Dataflow_Solver.reachable_visited\".\nintros st [GOOD1 GOOD2] PICK. induction 1; intros.\n- auto.\n- eapply IHreachable; eauto.\nexploit GOOD1; eauto. intros [P | P].\neelim NS.pick_none; eauto.\nexploit P; eauto. intros OGE; inv OGE. eapply GOOD2; eauto.\nQed.\n\n\n\n\n\nTheorem fixpoint_solution:\nforall ep ev res n instr s,\nfixpoint ep ev = Some res ->\ncode!n = Some instr ->\nIn s (successors instr) ->\n(forall n, L.eq (transf n L.bot) L.bot) ->\nL.ge res!!s (transf n res!!n).\nProof. hammer_hook \"Kildall\" \"Kildall.DATAFLOW_SOLVER.fixpoint_solution\".\nunfold fixpoint; intros.\nexploit fixpoint_from_charact; eauto. intros (st & STEPS & PICK & RES).\nexploit steps_state_good; eauto. apply start_state_good. intros [GOOD1 GOOD2].\nrewrite RES; unfold PMap.get; simpl.\ndestruct st.(aval)!n as [v|] eqn:STN.\n- destruct (GOOD1 n) as [P|P]; eauto.\neelim NS.pick_none; eauto.\nexploit P; eauto. unfold abstr_value; rewrite STN. intros OGE; inv OGE. auto.\n- apply L.ge_trans with L.bot. apply L.ge_bot. apply L.ge_refl. apply L.eq_sym. eauto.\nQed.\n\n\n\nTheorem fixpoint_entry:\nforall ep ev res,\nfixpoint ep ev = Some res ->\nL.ge res!!ep ev.\nProof. hammer_hook \"Kildall\" \"Kildall.DATAFLOW_SOLVER.fixpoint_entry\".\nunfold fixpoint; intros.\nexploit fixpoint_from_charact; eauto. intros (st & STEPS & PICK & RES).\nexploit (steps_incr ep); eauto. simpl. rewrite PTree.gss. intros [P Q].\nrewrite RES; unfold PMap.get; simpl. inv P; auto.\nQed.\n\n\n\nTheorem fixpoint_allnodes_solution:\nforall res n instr s,\nfixpoint_allnodes = Some res ->\ncode!n = Some instr ->\nIn s (successors instr) ->\nL.ge res!!s (transf n res!!n).\nProof. hammer_hook \"Kildall\" \"Kildall.Dataflow_Solver.fixpoint_allnodes_solution\".\nunfold fixpoint_allnodes; intros.\nexploit fixpoint_from_charact; eauto. intros (st & STEPS & PICK & RES).\nexploit steps_state_good; eauto. apply start_state_allnodes_good. intros [GOOD1 GOOD2].\nexploit (steps_incr n); eauto. simpl. intros [U V].\nexploit (GOOD1 n). apply V. exists instr; auto. intros [P|P].\neelim NS.pick_none; eauto.\nexploit P; eauto. intros OGE. rewrite RES; unfold PMap.get; simpl.\ninv OGE. assumption.\nQed.\n\n\n\nTheorem fixpoint_nodeset_solution:\nforall enodes res e n instr s,\nfixpoint_nodeset enodes = Some res ->\nNS.In e enodes ->\nreachable code successors e n ->\ncode!n = Some instr ->\nIn s (successors instr) ->\nL.ge res!!s (transf n res!!n).\nProof. hammer_hook \"Kildall\" \"Kildall.Dataflow_Solver.fixpoint_nodeset_solution\".\nunfold fixpoint_nodeset; intros.\nexploit fixpoint_from_charact; eauto. intros (st & STEPS & PICK & RES).\nexploit steps_state_good; eauto. apply start_state_nodeset_good. intros GOOD.\nexploit (steps_incr e); eauto. simpl. intros [U V].\nassert (st.(visited) n).\n{ eapply reachable_visited; eauto. }\ndestruct GOOD as [GOOD1 GOOD2].\nexploit (GOOD1 n); eauto. intros [P|P].\neelim NS.pick_none; eauto.\nexploit P; eauto. intros OGE. rewrite RES; unfold PMap.get; simpl.\ninv OGE. assumption.\nQed.\n\n\n\nTheorem fixpoint_invariant:\nforall ep ev\n(P: L.t -> Prop)\n(P_bot: P L.bot)\n(P_lub: forall x y, P x -> P y -> P (L.lub x y))\n(P_transf: forall pc instr x, code!pc = Some instr -> P x -> P (transf pc x))\n(P_entrypoint: P ev)\nres pc,\nfixpoint ep ev = Some res ->\nP res!!pc.\nProof. hammer_hook \"Kildall\" \"Kildall.DATAFLOW_SOLVER.fixpoint_invariant\".\nintros.\nset (inv := fun st => forall x, P (abstr_value x st)).\nassert (inv (start_state ep ev)).\n{\nred; simpl; intros. unfold abstr_value, start_state; simpl.\nrewrite PTree.gsspec. rewrite PTree.gempty.\ndestruct (peq x ep). auto. auto.\n}\nassert (forall st v n, inv st -> P v -> inv (propagate_succ st v n)).\n{\nunfold inv, propagate_succ. intros.\ndestruct (aval st)!n as [oldl|] eqn:E.\ndestruct (L.beq oldl (L.lub oldl v)).\nauto.\nunfold abstr_value. simpl. rewrite PTree.gsspec. destruct (peq x n).\napply P_lub; auto. replace oldl with (abstr_value n st). auto.\nunfold abstr_value; rewrite E; auto.\napply H1.\nunfold abstr_value. simpl. rewrite PTree.gsspec. destruct (peq x n).\nauto.\napply H1.\n}\nassert (forall l st v, inv st -> P v -> inv (propagate_succ_list st v l)).\n{\ninduction l; intros; simpl. auto.\napply IHl; auto.\n}\nassert (forall st1 st2, steps st1 st2 -> inv st1 -> inv st2).\n{\ninduction 1; intros.\nauto.\nunfold step in e. destruct (NS.pick (worklist s2)) as [[n rem]|]; try discriminate.\ndestruct (code!n) as [instr|] eqn:INSTR; inv e.\napply H2. apply IHsteps; auto. eapply P_transf; eauto. apply IHsteps; auto.\napply IHsteps; auto.\n}\nunfold fixpoint in H. exploit fixpoint_from_charact; eauto.\nintros (st & STEPS & PICK & RES).\nreplace (res!!pc) with (abstr_value pc st). eapply H3; eauto.\nrewrite RES; auto.\nQed.\n\nEnd Kildall.\n\nEnd Dataflow_Solver.\n\n\n\n\n\n\n\nDefinition successors_list (successors: PTree.t (list positive)) (pc: positive) : list positive :=\nmatch successors!pc with None => nil | Some l => l end.\n\nNotation \"a !!! b\" := (successors_list a b) (at level 1).\n\nSection Predecessor.\n\nContext {A: Type}.\nVariable code: PTree.t A.\nVariable successors: A -> list positive.\n\nFixpoint add_successors (pred: PTree.t (list positive))\n(from: positive) (tolist: list positive)\n{struct tolist} : PTree.t (list positive) :=\nmatch tolist with\n| nil => pred\n| to :: rem => add_successors (PTree.set to (from :: pred!!!to) pred) from rem\nend.\n\nLemma add_successors_correct:\nforall tolist from pred n s,\nIn n pred!!!s \\/ (n = from /\\ In s tolist) ->\nIn n (add_successors pred from tolist)!!!s.\nProof. hammer_hook \"Kildall\" \"Kildall.add_successors_correct\".\ninduction tolist; simpl; intros.\ntauto.\napply IHtolist.\nunfold successors_list at 1. rewrite PTree.gsspec. destruct (peq s a).\nsubst a. destruct H. auto with coqlib.\ndestruct H. subst n. auto with coqlib.\nfold (successors_list pred s). intuition congruence.\nQed.\n\nDefinition make_predecessors : PTree.t (list positive) :=\nPTree.fold (fun pred pc instr => add_successors pred pc (successors instr))\ncode (PTree.empty (list positive)).\n\nLemma make_predecessors_correct_1:\nforall n instr s,\ncode!n = Some instr -> In s (successors instr) ->\nIn n make_predecessors!!!s.\nProof. hammer_hook \"Kildall\" \"Kildall.make_predecessors_correct_1\".\nintros until s.\nset (P := fun m p => m!n = Some instr -> In s (successors instr) ->\nIn n p!!!s).\nunfold make_predecessors.\napply PTree_Properties.fold_rec with (P := P); unfold P; intros.\n\napply H0; auto. rewrite H; auto.\n\nrewrite PTree.gempty in H; congruence.\n\napply add_successors_correct.\nrewrite PTree.gsspec in H2. destruct (peq n k).\ninv H2. auto.\nauto.\nQed.\n\nLemma make_predecessors_correct_2:\nforall n instr s,\ncode!n = Some instr -> In s (successors instr) ->\nexists l, make_predecessors!s = Some l /\\ In n l.\nProof. hammer_hook \"Kildall\" \"Kildall.make_predecessors_correct_2\".\nintros. exploit make_predecessors_correct_1; eauto.\nunfold successors_list. destruct (make_predecessors!s); simpl; intros.\nexists l; auto.\ncontradiction.\nQed.\n\nLemma reachable_predecessors:\nforall p q,\nreachable code successors p q ->\nreachable make_predecessors (fun l => l) q p.\nProof. hammer_hook \"Kildall\" \"Kildall.reachable_predecessors\".\ninduction 1.\n- constructor.\n- exploit make_predecessors_correct_2; eauto. intros [l [P Q]].\neapply reachable_right; eauto.\nQed.\n\nEnd Predecessor.\n\n\n\n\n\nModule Type BACKWARD_DATAFLOW_SOLVER.\n\nDeclare Module L: SEMILATTICE.\n\n\n\nParameter fixpoint:\nforall {A: Type} (code: PTree.t A) (successors: A -> list positive)\n(transf: positive -> L.t -> L.t),\noption (PMap.t L.t).\n\n\n\nAxiom fixpoint_solution:\nforall A (code: PTree.t A) successors transf res n instr s,\nfixpoint code successors transf = Some res ->\ncode!n = Some instr -> In s (successors instr) ->\n(forall n a, code!n = None -> L.eq (transf n a) L.bot) ->\nL.ge res!!n (transf s res!!s).\n\n\n\nParameter fixpoint_allnodes:\nforall {A: Type} (code: PTree.t A) (successors: A -> list positive)\n(transf: positive -> L.t -> L.t),\noption (PMap.t L.t).\n\nAxiom fixpoint_allnodes_solution:\nforall A (code: PTree.t A) successors transf res n instr s,\nfixpoint_allnodes code successors transf = Some res ->\ncode!n = Some instr -> In s (successors instr) ->\nL.ge res!!n (transf s res!!s).\n\nEnd BACKWARD_DATAFLOW_SOLVER.\n\n\n\nModule Backward_Dataflow_Solver (LAT: SEMILATTICE) (NS: NODE_SET):\nBACKWARD_DATAFLOW_SOLVER with Module L := LAT.\n\nModule L := LAT.\n\nModule DS := Dataflow_Solver L NS.\n\nSection Kildall.\n\nContext {A: Type}.\nVariable code: PTree.t A.\nVariable successors: A -> list positive.\nVariable transf: positive -> L.t -> L.t.\n\n\n\nSection Exit_points.\n\n\n\nDefinition sequential_node (pc: positive) (instr: A): bool :=\nexistsb (fun s => match code!s with None => false | Some _ => plt s pc end)\n(successors instr).\n\nDefinition exit_points : NS.t :=\nPTree.fold\n(fun ep pc instr =>\nif sequential_node pc instr\nthen ep\nelse NS.add pc ep)\ncode NS.empty.\n\nLemma exit_points_charact:\nforall n,\nNS.In n exit_points <-> exists i, code!n = Some i /\\ sequential_node n i = false.\nProof. hammer_hook \"Kildall\" \"Kildall.Backward_Dataflow_Solver.exit_points_charact\".\nintros n. unfold exit_points. eapply PTree_Properties.fold_rec.\n-\nintros. rewrite <- H. auto.\n-\nsimpl. split; intros.\neelim NS.empty_spec; eauto.\ndestruct H as [i [P Q]]. rewrite PTree.gempty in P. congruence.\n-\nintros. destruct (sequential_node k v) eqn:SN.\n+ rewrite H1. rewrite PTree.gsspec. destruct (peq n k).\nsubst. split; intros [i [P Q]]. congruence. inv P. congruence.\ntauto.\n+ rewrite NS.add_spec. rewrite H1. rewrite PTree.gsspec. destruct (peq n k).\nsubst. split. intros. exists v; auto. auto.\nsplit. intros [P | [i [P Q]]]. congruence. exists i; auto.\nintros [i [P Q]]. right; exists i; auto.\nQed.\n\nLemma reachable_exit_points:\nforall pc i,\ncode!pc = Some i -> exists x, NS.In x exit_points /\\ reachable code successors pc x.\nProof. hammer_hook \"Kildall\" \"Kildall.Backward_Dataflow_Solver.reachable_exit_points\".\nintros pc0. pattern pc0. apply (well_founded_ind Plt_wf).\nintros pc HR i CODE.\ndestruct (sequential_node pc i) eqn:SN.\n-\nunfold sequential_node in SN. rewrite existsb_exists in SN.\ndestruct SN as [s [P Q]]. destruct (code!s) as [i'|] eqn:CS; try discriminate. InvBooleans.\nexploit (HR s); eauto. intros [x [U V]].\nexists x; split; auto. eapply reachable_left; eauto.\n-\nexists pc; split.\nrewrite exit_points_charact. exists i; auto. constructor.\nQed.\n\n\n\nLemma reachable_exit_points_predecessor:\nforall pc i,\ncode!pc = Some i ->\nexists x, NS.In x exit_points /\\ reachable (make_predecessors code successors) (fun l => l) x pc.\nProof. hammer_hook \"Kildall\" \"Kildall.Backward_Dataflow_Solver.reachable_exit_points_predecessor\".\nintros. exploit reachable_exit_points; eauto. intros [x [P Q]].\nexists x; split; auto. apply reachable_predecessors. auto.\nQed.\n\nEnd Exit_points.\n\n\n\nDefinition fixpoint :=\nDS.fixpoint_nodeset\n(make_predecessors code successors) (fun l => l)\ntransf exit_points.\n\nTheorem fixpoint_solution:\nforall res n instr s,\nfixpoint = Some res ->\ncode!n = Some instr -> In s (successors instr) ->\n(forall n a, code!n = None -> L.eq (transf n a) L.bot) ->\nL.ge res!!n (transf s res!!s).\nProof. hammer_hook \"Kildall\" \"Kildall.Dataflow_Solver.fixpoint_solution\".\nintros.\nexploit (make_predecessors_correct_2 code); eauto. intros [l [P Q]].\ndestruct code!s as [instr'|] eqn:CS.\n- exploit reachable_exit_points_predecessor. eexact CS. intros (ep & U & V).\nunfold fixpoint in H. eapply DS.fixpoint_nodeset_solution; eauto.\n- apply L.ge_trans with L.bot. apply L.ge_bot.\napply L.ge_refl. apply L.eq_sym. auto.\nQed.\n\n\n\nDefinition fixpoint_allnodes :=\nDS.fixpoint_allnodes\n(make_predecessors code successors) (fun l => l)\ntransf.\n\nTheorem fixpoint_allnodes_solution:\nforall res n instr s,\nfixpoint_allnodes = Some res ->\ncode!n = Some instr -> In s (successors instr) ->\nL.ge res!!n (transf s res!!s).\nProof. hammer_hook \"Kildall\" \"Kildall.BACKWARD_DATAFLOW_SOLVER.fixpoint_allnodes_solution\".\nintros.\nexploit (make_predecessors_correct_2 code); eauto. intros [l [P Q]].\nunfold fixpoint_allnodes in H.\neapply DS.fixpoint_allnodes_solution; eauto.\nQed.\n\nEnd Kildall.\n\nEnd Backward_Dataflow_Solver.\n\n\n\n\n\nModule Type ORDERED_TYPE_WITH_TOP.\n\nParameter t: Type.\nParameter ge: t -> t -> Prop.\nParameter top: t.\nAxiom top_ge: forall x, ge top x.\nAxiom refl_ge: forall x, ge x x.\n\nEnd ORDERED_TYPE_WITH_TOP.\n\n\n\nModule Type BBLOCK_SOLVER.\n\nDeclare Module L: ORDERED_TYPE_WITH_TOP.\n\nParameter fixpoint:\nforall {A: Type} (code: PTree.t A) (successors: A -> list positive)\n(transf: positive -> L.t -> L.t)\n(entrypoint: positive),\noption (PMap.t L.t).\n\nAxiom fixpoint_solution:\nforall A (code: PTree.t A) successors transf entrypoint res n instr s,\nfixpoint code successors transf entrypoint = Some res ->\ncode!n = Some instr -> In s (successors instr) ->\nL.ge res!!s (transf n res!!n).\n\nAxiom fixpoint_entry:\nforall A (code: PTree.t A) successors transf entrypoint res,\nfixpoint code successors transf entrypoint = Some res ->\nres!!entrypoint = L.top.\n\nAxiom fixpoint_invariant:\nforall A (code: PTree.t A) successors transf entrypoint\n(P: L.t -> Prop),\nP L.top ->\n(forall pc instr x, code!pc = Some instr -> P x -> P (transf pc x)) ->\nforall res pc,\nfixpoint code successors transf entrypoint = Some res ->\nP res!!pc.\n\nEnd BBLOCK_SOLVER.\n\n\n\nModule BBlock_solver(LAT: ORDERED_TYPE_WITH_TOP):\nBBLOCK_SOLVER with Module L := LAT.\n\nModule L := LAT.\n\nSection Solver.\n\nContext {A: Type}.\nVariable code: PTree.t A.\nVariable successors: A -> list positive.\nVariable transf: positive -> L.t -> L.t.\nVariable entrypoint: positive.\nVariable P: L.t -> Prop.\nHypothesis Ptop: P L.top.\nHypothesis Ptransf: forall pc instr x, code!pc = Some instr -> P x -> P (transf pc x).\n\nDefinition bbmap := positive -> bool.\nDefinition result := PMap.t L.t.\n\n\n\nRecord state : Type := mkstate\n{ aval: result; worklist: list positive }.\n\n\n\nFixpoint propagate_successors\n(bb: bbmap) (succs: list positive) (l: L.t) (st: state)\n{struct succs} : state :=\nmatch succs with\n| nil => st\n| s1 :: sl =>\nif bb s1 then\npropagate_successors bb sl l st\nelse\npropagate_successors bb sl l\n(mkstate (PMap.set s1 l st.(aval))\n(s1 :: st.(worklist)))\nend.\n\nDefinition step (bb: bbmap) (st: state) : result + state :=\nmatch st.(worklist) with\n| nil => inl _ st.(aval)\n| pc :: rem =>\nmatch code!pc with\n| None =>\ninr _ (mkstate st.(aval) rem)\n| Some instr =>\ninr _ (propagate_successors\nbb (successors instr)\n(transf pc st.(aval)!!pc)\n(mkstate st.(aval) rem))\nend\nend.\n\n\n\nDefinition is_basic_block_head\n(preds: PTree.t (list positive)) (pc: positive) : bool :=\nif peq pc entrypoint then true else\nmatch preds!!!pc with\n| nil => false\n| s :: nil => peq s pc\n| _ :: _ :: _ => true\nend.\n\nDefinition basic_block_map : bbmap :=\nis_basic_block_head (make_predecessors code successors).\n\nDefinition basic_block_list (bb: bbmap) : list positive :=\nPTree.fold (fun l pc instr => if bb pc then pc :: l else l)\ncode nil.\n\n\n\nDefinition fixpoint : option result :=\nlet bb := basic_block_map in\nPrimIter.iterate _ _ (step bb) (mkstate (PMap.init L.top) (basic_block_list bb)).\n\n\n\nDefinition predecessors := make_predecessors code successors.\n\nLemma predecessors_correct:\nforall n instr s,\ncode!n = Some instr -> In s (successors instr) -> In n predecessors!!!s.\nProof. hammer_hook \"Kildall\" \"Kildall.BBlock_solver.predecessors_correct\".\nintros. unfold predecessors. eapply make_predecessors_correct_1; eauto.\nQed.\n\nLemma multiple_predecessors:\nforall s n1 instr1 n2 instr2,\ncode!n1 = Some instr1 -> In s (successors instr1) ->\ncode!n2 = Some instr2 -> In s (successors instr2) ->\nn1 <> n2 ->\nbasic_block_map s = true.\nProof. hammer_hook \"Kildall\" \"Kildall.BBlock_solver.multiple_predecessors\".\nintros.\nassert (In n1 predecessors!!!s). eapply predecessors_correct; eauto.\nassert (In n2 predecessors!!!s). eapply predecessors_correct; eauto.\nunfold basic_block_map, is_basic_block_head.\ndestruct (peq s entrypoint). auto.\nfold predecessors.\ndestruct (predecessors!!!s).\nauto.\ndestruct l.\napply proj_sumbool_is_true. simpl in *. intuition congruence.\nauto.\nQed.\n\nLemma no_self_loop:\nforall n instr,\ncode!n = Some instr -> In n (successors instr) -> basic_block_map n = true.\nProof. hammer_hook \"Kildall\" \"Kildall.BBlock_solver.no_self_loop\".\nintros. unfold basic_block_map, is_basic_block_head.\ndestruct (peq n entrypoint). auto.\nfold predecessors.\nexploit predecessors_correct; eauto. intros.\ndestruct (predecessors!!!n).\ncontradiction.\ndestruct l. apply proj_sumbool_is_true. simpl in H1. tauto.\nauto.\nQed.\n\n\n\n\n\nDefinition state_invariant (st: state) : Prop :=\n(forall n, basic_block_map n = true -> st.(aval)!!n = L.top)\n/\\\n(forall n,\nIn n st.(worklist) \\/\n(forall instr s, code!n = Some instr -> In s (successors instr) ->\nL.ge st.(aval)!!s (transf n st.(aval)!!n))).\n\nLemma propagate_successors_charact1:\nforall bb succs l st,\nincl st.(worklist)\n(propagate_successors bb succs l st).(worklist).\nProof. hammer_hook \"Kildall\" \"Kildall.BBlock_solver.propagate_successors_charact1\".\ninduction succs; simpl; intros.\napply incl_refl.\ncase (bb a).\nauto.\napply incl_tran with (a :: worklist st).\napply incl_tl. apply incl_refl.\nset (st1 := (mkstate (PMap.set a l (aval st)) (a :: worklist st))).\nchange (a :: worklist st) with (worklist st1).\nauto.\nQed.\n\nLemma propagate_successors_charact2:\nforall bb succs l st n,\nlet st' := propagate_successors bb succs l st in\n(In n succs -> bb n = false -> In n st'.(worklist) /\\ st'.(aval)!!n = l)\n/\\ (~In n succs \\/ bb n = true -> st'.(aval)!!n = st.(aval)!!n).\nProof. hammer_hook \"Kildall\" \"Kildall.BBlock_solver.propagate_successors_charact2\".\ninduction succs; simpl; intros.\n\nsplit. tauto. auto.\n\ncaseEq (bb a); intro.\nelim (IHsuccs l st n); intros U V.\nsplit; intros. apply U; auto.\nelim H0; intro. subst a. congruence. auto.\napply V. tauto.\nset (st1 := mkstate (PMap.set a l (aval st)) (a :: worklist st)).\nelim (IHsuccs l st1 n); intros U V.\nsplit; intros.\nelim H0; intros.\nsubst n. split.\napply propagate_successors_charact1. simpl. tauto.\ncase (In_dec peq a succs); intro.\nelim (U i H1); auto.\nrewrite V. unfold st1; simpl. apply PMap.gss. tauto.\napply U; auto.\nrewrite V. unfold st1; simpl. apply PMap.gso.\nred; intro; subst n. elim H0; intro. tauto. congruence.\ntauto.\nQed.\n\nLemma propagate_successors_invariant:\nforall pc instr res rem,\ncode!pc = Some instr ->\nstate_invariant (mkstate res (pc :: rem)) ->\nstate_invariant\n(propagate_successors basic_block_map (successors instr)\n(transf pc res!!pc)\n(mkstate res rem)).\nProof. hammer_hook \"Kildall\" \"Kildall.BBlock_solver.propagate_successors_invariant\".\nintros until rem. intros CODE [INV1 INV2]. simpl in INV1. simpl in INV2.\nset (l := transf pc res!!pc).\ngeneralize (propagate_successors_charact1 basic_block_map\n(successors instr) l (mkstate res rem)).\ngeneralize (propagate_successors_charact2 basic_block_map\n(successors instr) l (mkstate res rem)).\nset (st1 := propagate_successors basic_block_map\n(successors instr) l (mkstate res rem)).\nintros U V. simpl in U.\n\nsplit; intros.\nelim (U n); intros C D. rewrite D. simpl. apply INV1. auto. tauto.\n\n\ndestruct (peq pc n). subst n.\nright; intros.\nassert (instr0 = instr) by congruence. subst instr0.\nelim (U s); intros C D.\nreplace (st1.(aval)!!pc) with res!!pc. fold l.\ndestruct (basic_block_map s) eqn:BB.\nrewrite D. simpl. rewrite INV1. apply L.top_ge. auto. tauto.\nelim (C H0 (eq_refl _)). intros X Y. rewrite Y. apply L.refl_ge.\nelim (U pc); intros E F. rewrite F. reflexivity.\ndestruct (In_dec peq pc (successors instr)).\nright. eapply no_self_loop; eauto.\nleft; auto.\n\nelim (INV2 n); intro.\n\nleft. apply V. simpl. tauto.\n\nassert (INV3: forall s instr', code!n = Some instr' -> In s (successors instr') -> st1.(aval)!!s = res!!s).\n\nintros. elim (U s); intros C D. rewrite D. reflexivity.\ndestruct (In_dec peq s (successors instr)).\nright. eapply multiple_predecessors with (n1 := pc) (n2 := n); eauto.\nleft; auto.\ndestruct (In_dec peq n (successors instr)).\n\ndestruct (basic_block_map n) eqn:BB.\nright; intros.\nelim (U n); intros C D. rewrite D. erewrite INV3; eauto.\ntauto.\nleft. elim (U n); intros C D. elim (C i BB); intros. auto.\n\nright; intros.\nelim (U n); intros C D. rewrite D.\nerewrite INV3; eauto.\ntauto.\nQed.\n\nLemma propagate_successors_invariant_2:\nforall pc res rem,\ncode!pc = None ->\nstate_invariant (mkstate res (pc :: rem)) ->\nstate_invariant (mkstate res rem).\nProof. hammer_hook \"Kildall\" \"Kildall.BBlock_solver.propagate_successors_invariant_2\".\nintros until rem. intros CODE [INV1 INV2]. simpl in INV1. simpl in INV2.\nsplit; simpl; intros.\napply INV1; auto.\ndestruct (INV2 n) as [[U | U] | U].\nsubst n. right; intros; congruence.\nauto.\nauto.\nQed.\n\nLemma initial_state_invariant:\nstate_invariant (mkstate (PMap.init L.top) (basic_block_list basic_block_map)).\nProof. hammer_hook \"Kildall\" \"Kildall.BBlock_solver.initial_state_invariant\".\nsplit; simpl; intros.\napply PMap.gi.\nright. intros. repeat rewrite PMap.gi. apply L.top_ge.\nQed.\n\nLemma analyze_invariant:\nforall res,\nfixpoint = Some res ->\nstate_invariant (mkstate res nil).\nProof. hammer_hook \"Kildall\" \"Kildall.BBlock_solver.analyze_invariant\".\nunfold fixpoint; intros. pattern res.\neapply (PrimIter.iterate_prop _ _ (step basic_block_map)\nstate_invariant).\n\nintros st INV. destruct st as [stin stwrk].\nunfold step. simpl. destruct stwrk as [ | pc rem ] eqn:WRK.\nauto.\ndestruct (code!pc) as [instr|] eqn:CODE.\neapply propagate_successors_invariant; eauto.\neapply propagate_successors_invariant_2; eauto.\n\neauto. apply initial_state_invariant.\nQed.\n\n\n\nTheorem fixpoint_solution:\nforall res n instr s,\nfixpoint = Some res ->\ncode!n = Some instr -> In s (successors instr) ->\nL.ge res!!s (transf n res!!n).\nProof. hammer_hook \"Kildall\" \"Kildall.BACKWARD_DATAFLOW_SOLVER.fixpoint_solution\".\nintros.\nassert (state_invariant (mkstate res nil)).\neapply analyze_invariant; eauto.\nelim H2; simpl; intros.\nelim (H4 n); intros.\ncontradiction.\neauto.\nQed.\n\nTheorem fixpoint_entry:\nforall res,\nfixpoint = Some res ->\nres!!entrypoint = L.top.\nProof. hammer_hook \"Kildall\" \"Kildall.Dataflow_Solver.fixpoint_entry\".\nintros.\nassert (state_invariant (mkstate res nil)).\neapply analyze_invariant; eauto.\nelim H0; simpl; intros.\napply H1. unfold basic_block_map, is_basic_block_head.\nfold predecessors. apply peq_true.\nQed.\n\n\n\nDefinition Pstate (st: state) : Prop :=\nforall pc, P st.(aval)!!pc.\n\nLemma propagate_successors_P:\nforall bb l,\nP l ->\nforall succs st,\nPstate st ->\nPstate (propagate_successors bb succs l st).\nProof. hammer_hook \"Kildall\" \"Kildall.BBlock_solver.propagate_successors_P\".\ninduction succs; simpl; intros.\nauto.\ncase (bb a). auto.\napply IHsuccs. red; simpl; intros.\nrewrite PMap.gsspec. case (peq pc a); intro.\nauto. apply H0.\nQed.\n\nTheorem fixpoint_invariant:\nforall res pc, fixpoint = Some res -> P res!!pc.\nProof. hammer_hook \"Kildall\" \"Kildall.Dataflow_Solver.fixpoint_invariant\".\nunfold fixpoint; intros. pattern res.\neapply (PrimIter.iterate_prop _ _ (step basic_block_map) Pstate).\n\nintros st PS. unfold step. destruct (st.(worklist)).\napply PS.\nassert (PS2: Pstate (mkstate st.(aval) l)).\nred; intro; simpl. apply PS.\ndestruct (code!p) as [instr|] eqn:CODE.\napply propagate_successors_P. eauto. auto.\nauto.\n\neauto.\nred; intro; simpl. rewrite PMap.gi. apply Ptop.\nQed.\n\nEnd Solver.\n\nEnd BBlock_solver.\n\n\n\n\n\nFrom compcert Require Import Heaps.\n\nModule NodeSetForward <: NODE_SET.\nDefinition t := PHeap.t.\nDefinition empty := PHeap.empty.\nDefinition add (n: positive) (s: t) : t := PHeap.insert n s.\nDefinition pick (s: t) :=\nmatch PHeap.findMax s with\n| Some n => Some(n, PHeap.deleteMax s)\n| None => None\nend.\nDefinition all_nodes {A: Type} (code: PTree.t A) :=\nPTree.fold (fun s pc instr => PHeap.insert pc s) code PHeap.empty.\nDefinition In := PHeap.In.\n\nLemma empty_spec:\nforall n, ~In n empty.\nProof. hammer_hook \"Kildall\" \"Kildall.NODE_SET.empty_spec\".\nintros. apply PHeap.In_empty.\nQed.\n\nLemma add_spec:\nforall n n' s, In n' (add n s) <-> n = n' \\/ In n' s.\nProof. hammer_hook \"Kildall\" \"Kildall.NODE_SET.add_spec\".\nintros. rewrite PHeap.In_insert. unfold In. intuition.\nQed.\n\nLemma pick_none:\nforall s n, pick s = None -> ~In n s.\nProof. hammer_hook \"Kildall\" \"Kildall.NODE_SET.pick_none\".\nintros until n; unfold pick. caseEq (PHeap.findMax s); intros.\ncongruence.\napply PHeap.findMax_empty. auto.\nQed.\n\nLemma pick_some:\nforall s n s', pick s = Some(n, s') ->\nforall n', In n' s <-> n = n' \\/ In n' s'.\nProof. hammer_hook \"Kildall\" \"Kildall.NODE_SET.pick_some\".\nintros until s'; unfold pick. caseEq (PHeap.findMax s); intros.\ninv H0.\ngeneralize (PHeap.In_deleteMax s n n' H). unfold In. intuition.\ncongruence.\nQed.\n\nLemma all_nodes_spec:\nforall A (code: PTree.t A) n instr,\ncode!n = Some instr -> In n (all_nodes code).\nProof. hammer_hook \"Kildall\" \"Kildall.NODE_SET.all_nodes_spec\".\nintros A code n instr.\napply PTree_Properties.fold_rec with\n(P := fun m set => m!n = Some instr -> In n set).\n\nintros. apply H0. rewrite H. auto.\n\nrewrite PTree.gempty. congruence.\n\nintros. rewrite PTree.gsspec in H2. rewrite add_spec.\ndestruct (peq n k). auto. eauto.\nQed.\nEnd NodeSetForward.\n\nModule NodeSetBackward <: NODE_SET.\nDefinition t := PHeap.t.\nDefinition empty := PHeap.empty.\nDefinition add (n: positive) (s: t) : t := PHeap.insert n s.\nDefinition pick (s: t) :=\nmatch PHeap.findMin s with\n| Some n => Some(n, PHeap.deleteMin s)\n| None => None\nend.\nDefinition all_nodes {A: Type} (code: PTree.t A) :=\nPTree.fold (fun s pc instr => PHeap.insert pc s) code PHeap.empty.\nDefinition In := PHeap.In.\n\nLemma empty_spec:\nforall n, ~In n empty.\nProof. hammer_hook \"Kildall\" \"Kildall.NodeSetForward.empty_spec\". exact (NodeSetForward.empty_spec). Qed.\n\nLemma add_spec:\nforall n n' s, In n' (add n s) <-> n = n' \\/ In n' s.\nProof. hammer_hook \"Kildall\" \"Kildall.NodeSetForward.add_spec\". exact (NodeSetForward.add_spec). Qed.\n\nLemma pick_none:\nforall s n, pick s = None -> ~In n s.\nProof. hammer_hook \"Kildall\" \"Kildall.NodeSetForward.pick_none\".\nintros until n; unfold pick. caseEq (PHeap.findMin s); intros.\ncongruence.\napply PHeap.findMin_empty. auto.\nQed.\n\nLemma pick_some:\nforall s n s', pick s = Some(n, s') ->\nforall n', In n' s <-> n = n' \\/ In n' s'.\nProof. hammer_hook \"Kildall\" \"Kildall.NodeSetForward.pick_some\".\nintros until s'; unfold pick. caseEq (PHeap.findMin s); intros.\ninv H0.\ngeneralize (PHeap.In_deleteMin s n n' H). unfold In. intuition.\ncongruence.\nQed.\n\nLemma all_nodes_spec:\nforall A (code: PTree.t A) n instr,\ncode!n = Some instr -> In n (all_nodes code).\nProof. hammer_hook \"Kildall\" \"Kildall.NodeSetForward.all_nodes_spec\". exact (NodeSetForward.all_nodes_spec). Qed.\nEnd NodeSetBackward.\n\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/Kildall.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6654105587468141, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2811390451248277}}
{"text": "(** * Classification of path spaces of precategories *)\nRequire Import Category.Core.\nRequire Import HoTT.Basics.Equivalences HoTT.Basics.PathGroupoids HoTT.Basics.Trunc HoTT.Basics.Tactics.\nRequire Import HoTT.Types.Sigma HoTT.Types.Arrow HoTT.Types.Forall.\nRequire Import HoTT.Tactics.\n\nSet Universe Polymorphism.\nSet Implicit Arguments.\nGeneralizable All Variables.\nSet Asymmetric Patterns.\n\nLocal Open Scope morphism_scope.\nLocal Open Scope category_scope.\n\nSection path_category.\n  Local Open Scope path_scope.\n\n\n  (** We add a prime ([']) as an arbitrary convention to denote that\n      we are talking about equality of functions (less convenient for\n      use) rather than pointwise equality of functions (more\n      convenient for use, but more annoying for proofs).  We add two\n      primes to denote the even less convenient version, which\n      requires an identity equality proof. *)\n  Local Notation path_precategory''_T C D\n    := { Hobj : object C = object D\n       | { Hmor : transport (fun obj => obj -> obj -> Type)\n                            Hobj\n                            (morphism C)\n                  = morphism D\n         | transport _\n                     Hmor\n                     (transportD (fun obj => obj -> obj -> Type)\n                                 (fun obj mor => forall s d d', mor d d' -> mor s d -> mor s d')\n                                 Hobj\n                                 (morphism C)\n                                 (@compose C))\n           = @compose D\n           /\\ transport _\n                        Hmor\n                        (transportD (fun obj => obj -> obj -> Type)\n                                    (fun obj mor => forall x, mor x x)\n                                    Hobj\n                                    (morphism C)\n                                    (@identity C))\n              = @identity D }}.\n\n  Local Notation path_precategory'_T C D\n    := { Hobj : object C = object D\n       | { Hmor : transport (fun obj => obj -> obj -> Type)\n                            Hobj\n                            (morphism C)\n                  = morphism D\n         | transport _\n                     Hmor\n                     (transportD (fun obj => obj -> obj -> Type)\n                                 (fun obj mor => forall s d d', mor d d' -> mor s d -> mor s d')\n                                 Hobj\n                                 (morphism C)\n                                 (@compose C))\n           = @compose D }}.\n\n  (** ** Classify sufficient conditions to prove precategories equal *)\n  Lemma path_precategory_uncurried__identity_helper `{Funext} (C D : PreCategory)\n        (Heq : path_precategory'_T C D)\n  : transport _\n              Heq.2.1\n              (transportD (fun obj => obj -> obj -> Type)\n                          (fun obj mor => forall x, mor x x)\n                          Heq.1\n                          (morphism C)\n                          (@identity C))\n    = @identity D.\n  Proof.\n    destruct Heq as [? [? ?]]; cbn in *.\n    repeat (intro || apply path_forall).\n    apply identity_unique; cbn in *; auto with morphism.\n    destruct C, D; cbn in *.\n    path_induction; cbn in *.\n    auto.\n  Qed.\n\n  Definition path_precategory''_T__of__path_precategory'_T `{Funext} C D\n  : path_precategory'_T C D -> path_precategory''_T C D\n    := fun H => (H.1; (H.2.1; (H.2.2, path_precategory_uncurried__identity_helper C D H))).\n\n  Lemma eta2_sigma_helper A B P Q `{forall a b, IsHProp (Q a b)}\n        (x : { a : A & { b : B a & P a b /\\ Q a b }})\n        q'\n  : (x.1; (x.2.1; (fst x.2.2, q'))) = x.\n  Proof.\n    destruct x as [? [? [? ?]]]; cbn in *.\n    repeat f_ap; apply path_ishprop.\n  Defined.\n\n  Global Instance isequiv__path_precategory''_T__of__path_precategory'_T `{fs : Funext} C D\n  : IsEquiv (@path_precategory''_T__of__path_precategory'_T fs C D)\n    := isequiv_adjointify\n         (@path_precategory''_T__of__path_precategory'_T fs C D)\n         (fun H => (H.1; (H.2.1; fst H.2.2)))\n         (fun x => eta2_sigma_helper _ _ _ x _)\n         eta2_sigma.\n\n  Definition path_precategory_uncurried' `{fs : Funext} (C D : PreCategory)\n  : path_precategory''_T C D -> C = D.\n  Proof.\n    intros [? [? [? ?]]].\n    destruct C, D; cbn in *.\n    path_induction; cbn in *.\n    f_ap;\n      eapply @center; abstract exact _.\n  Defined.\n\n  (** *** Said proof respects [object] *)\n  Lemma path_precategory_uncurried'_fst `{Funext} C D HO HM HC HI\n  : ap object (@path_precategory_uncurried' _ C D (HO; (HM; (HC, HI)))) = HO.\n  Proof.\n    destruct C, D; cbn in *.\n    path_induction_hammer.\n  Qed.\n\n  (** *** Said proof respects [idpath] *)\n  Lemma path_precategory_uncurried'_idpath `{Funext} C\n  : @path_precategory_uncurried' _ C C (idpath; (idpath; (idpath, idpath))) = idpath.\n  Proof.\n    destruct C; cbn in *.\n    rewrite !(contr idpath).\n    reflexivity.\n  Qed.\n\n  (** ** Equality of precategorys gives rise to an inhabitant of the path-classifying-type *)\n  Definition path_precategory_uncurried'_inv (C D : PreCategory)\n  : C = D -> path_precategory''_T C D.\n  Proof.\n    intro H'.\n    exists (ap object H').\n    exists ((transport_compose _ object _ _) ^ @ apD (@morphism) H').\n    split.\n    - refine (_ @ apD (@compose) H'); cbn.\n      refine (transport_pp _ _ _ _ @ _).\n      refine ((ap _ (transportD_compose\n                       (fun obj => obj -> obj -> Type)\n                       (fun obj mor =>\n                          forall s d d' : obj, mor d d' -> mor s d -> mor s d') object H'\n                       (morphism C) (@compose C))^)\n                @ (transport_apD_transportD\n                     _\n                     morphism\n                     (fun x mor => forall s d d' : x, mor d d' -> mor s d -> mor s d') H'\n                     (@compose C))).\n    - refine (_ @ apD (@identity) H'); cbn.\n      refine (transport_pp _ _ _ _ @ _).\n      refine ((ap _ (transportD_compose\n                       (fun obj => obj -> obj -> Type)\n                       (fun obj mor =>\n                          forall x : obj, mor x x) object H'\n                       (morphism C) (@identity C))^)\n                @ (transport_apD_transportD\n                     _\n                     morphism\n                     (fun x mor => forall s : x, mor s s) H'\n                     (@identity C))).\n  Defined.\n\n  (** ** Classify equality of precategorys up to equivalence *)\n  Lemma equiv_path_precategory_uncurried'__eissect `{Funext} (C D : PreCategory)\n  : forall x : path_precategory''_T C D,\n      path_precategory_uncurried'_inv (path_precategory_uncurried' C D x) = x.\n  Proof.\n    destruct C, D; cbn in *.\n    intros [H0' [H1' [H2' H3']]].\n    path_induction.\n    cbn.\n    repeat (edestruct (center (_ = _)); try reflexivity).\n  Qed.\n\n  Lemma equiv_path_precategory_uncurried' `{Funext} (C D : PreCategory)\n  : path_precategory''_T C D <~> C = D.\n  Proof.\n    apply (equiv_adjointify (@path_precategory_uncurried' _ C D)\n                            (@path_precategory_uncurried'_inv C D)).\n    - hnf.\n      intros [].\n      apply path_precategory_uncurried'_idpath.\n    - hnf.\n      apply equiv_path_precategory_uncurried'__eissect.\n  Defined.\n\n  Definition equiv_path_precategory_uncurried `{Funext} (C D : PreCategory)\n  : path_precategory'_T C D <~> C = D\n    := ((equiv_path_precategory_uncurried' C D)\n          oE (Build_Equiv\n                _ _ _\n                (isequiv__path_precategory''_T__of__path_precategory'_T C D))).\n\n  Definition path_precategory_uncurried `{Funext} C D : _ -> _\n    := equiv_path_precategory_uncurried C D.\n\n  (** ** Curried version of path classifying lemma *)\n  Lemma path_precategory' `{fs : Funext} (C D : PreCategory)\n  : forall (Hobj : object C = object D)\n           (Hmor : transport (fun obj => obj -> obj -> Type)\n                             Hobj\n                             (morphism C)\n                   = morphism D),\n      transport _\n                Hmor\n                (transportD (fun obj => obj -> obj -> Type)\n                            (fun obj mor => forall s d d', mor d d' -> mor s d -> mor s d')\n                            Hobj\n                            (morphism C)\n                            (@compose C))\n      = @compose D\n      -> C = D.\n  Proof.\n    intros.\n    apply path_precategory_uncurried.\n    repeat esplit; eassumption.\n  Defined.\n\n  (** ** Curried version of path classifying lemma, using [forall] in place of equality of functions *)\n  Lemma path_precategory `{fs : Funext} (C D : PreCategory)\n  : forall (Hobj : object C = object D)\n           (Hmor : forall s d,\n                     morphism C (transport idmap Hobj^ s) (transport idmap Hobj^ d)\n                     = morphism D s d),\n      (forall s d d' m m',\n         transport idmap (Hmor _ _)\n                   (@compose C _ _ _\n                             (transport idmap (Hmor _ _)^ m)\n                             (transport idmap (Hmor _ _)^ m'))\n         = @compose D s d d' m m')\n      -> C = D.\n  Proof.\n    intros Hobj Hmor Hcomp.\n    pose (path_forall\n            _ _\n            (fun s =>\n               path_forall\n                 _ _\n                 (fun d =>\n                    (ap10 (@transport_arrow Type idmap (fun x => x -> Type) _ _ Hobj (@morphism C) _) _)\n                      @ (@transport_arrow Type idmap _ _ _ Hobj (@morphism C _) _)\n                      @ (transport_const _ _)\n                      @ Hmor s d)))\n      as Hmor'.\n    eapply (path_precategory' C D Hobj Hmor').\n    repeat (apply path_forall; intro).\n    refine (_ @ Hcomp _ _ _ _ _); clear Hcomp.\n    subst Hmor'.\n    cbn.\n    abstract (\n        destruct C, D;\n        cbn in *;\n          destruct Hobj;\n        cbn in *;\n          repeat match goal with\n                   | _ => reflexivity\n                   | _ => rewrite !concat_1p\n                   | _ => rewrite !transport_forall_constant, !transport_arrow\n                   | _ => progress transport_path_forall_hammer\n                   | [ |- transport ?P ?p^ ?u = ?v ]\n                     => (apply (@moveR_transport_V _ P _ _ p u v); progress transport_path_forall_hammer)\n                   | [ |- ?u = transport ?P ?p^ ?v ]\n                     => (apply (@moveL_transport_V _ P _ _ p u v); progress transport_path_forall_hammer)\n                   | [ |- context[?H ?x ?y] ]\n                     => (destruct (H x y); clear H)\n                   | _ => progress f_ap\n                 end\n      ).\n  Defined.\nEnd path_category.\n\n(** ** Tactic for proving equality of precategories *)\n(** We move the funext inference outside the loop. *)\nLtac path_category :=\n  idtac;\n  let lem := constr:(@path_precategory _) in\n  repeat match goal with\n           | _ => intro\n           | _ => reflexivity\n           | _ => simple refine (lem _ _ _ _ _); cbn\n         end.\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/Category/Paths.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.281132419524212}}
{"text": "(*|\n============================================================\nCore definition of the [ctrees] datatype and its combinators\n============================================================\n\nWe develop a data-structure strongly inspired by Interaction Trees,\nbut offering native support for internal non-determinism: the [ctree]s.\nInteraction trees took the position to not be the free monad per se,\nbut to give a special status to divergence by implementing it coinductively.\nHere, we take a similar stance toward non-determinism by adding a new\nconstructor to the structure encoding (finite) non-deterministic branching.\nThese internal branching nodes are furthermore tagged by whether they can be\nobserved or not.\n\nThe resulting structure is still an iterative monad parametered by an\ninterface of interactions, supporting monadic interpretations of these\ninterfaces. But the equivalence relation over [ctree] is more complex, and\naccount natively for this non-determinism. More specifically, we provide\na structural, coinductive equality; a notion of strong bisimulation observing\nvisible internal brs; a notion of weak bisimulation observing no internal\nbr.\n\n.. coq:: none\n|*)\n\nFrom ITree Require Import Basics.Basics Core.Subevent Indexed.Sum.\n\nFrom CTree Require Import\n\t   Core.Utils Core.Index.\n\nFrom ExtLib Require Import\n\t   Structures.Functor\n\t   Structures.Monads.\n\nSet Implicit Arguments.\nSet Contextual Implicit.\nSet Primitive Projections.\n\n(*|\n.. coq::\n|*)\n\nSection ctree.\n\n  Context {E : Type -> Type} {B : Type -> Type} {R : Type}.\n\n(*|\nThe type [ctree] is defined as the final coalgebra (\"greatest fixed point\") of the functor [ctreeF].\nA [ctree] can locally provide three kind of observations:\n- A pure value, terminating the computation\n- An interaction with the environment, emitting the corresponding\nindexed event and non-deterministically continuing indexed by the\nvalue returned by the environment\n- A (finite) internal non-deterministic branching\n\nTODO YZ:\n\n- Do we want to name the sources of the brs?\n  For instance if we want to support simultaneously different schedulers for different kind of non-determinism in a language.\n- Do we want non-finite internal branching? Indexed by arbitrary types?\n- Or crazier, do we want non-uniform branching, modelling non-uniform random brs for instance?\n- Could ctrees be parameterized by:\n\n  + a bound on nested brs before reaching a Vis/Ret\n  + a general domain of br events\n\n.. coq::\n|*)\n\n  Variant ctreeF (ctree : Type) :=\n    | RetF (r : R)                                       (* a pure computation *)\n    | VisF {X : Type} (e : E X) (k : X -> ctree)          (* an external event *)\n    | BrF (vis : bool) {X : Type} (c : B X) (k : X -> ctree) (* an internal non-deterministic branching *)\n  .\n\n  CoInductive ctree : Type :=\n    go { _observe : ctreeF ctree }.\n\nEnd ctree.\n\n(*|\n.. coq:: none\n|*)\n\nDeclare Scope ctree_scope.\nBind Scope ctree_scope with ctree.\nDelimit Scope ctree_scope with ctree.\nLocal Open Scope ctree_scope.\n\nArguments ctree _ _ : clear implicits.\nArguments ctreeF _ _ : clear implicits.\nArguments BrF {E B R} [ctree] vis {X} c k.\n\n(*|\nA [ctree'] is a \"forced\" [ctree]. It is the type of inputs\nof [go], and outputs of [observe].\n\n.. coq::\n|*)\n\nNotation ctree' E B R := (ctreeF E B R (ctree E B R)).\n\n(*|\nWe wrap the primitive projection [_observe] in a function [observe].\n|*)\n\nDefinition observe {E B R} (t : ctree E B R) : ctree' E B R := @_observe E B R t.\n\nNotation Ret x        := (go (RetF x)).\nNotation Vis e k      := (go (VisF e k)).\nNotation Br b n k     := (go (BrF b n k)).\nNotation BrS n k      := (go (BrF true n k)).\nNotation BrD n k      := (go (BrF false n k)).\nNotation BrSF         := (BrF true).\nNotation BrDF         := (BrF false).\n\nNotation vis e k      := (Vis (subevent _ e) k).\nNotation br b c k     := (Br b (subevent _ c) k).\nNotation brS c k      := (br true c k).\nNotation brD c k      := (br false c k).\nNotation brSF c       := (BrSF (subevent _ c)).\nNotation brDF c       := (BrDF (subevent _ c)).\n\nSection Branching.\n\n  Context {E B : Type -> Type}.\n  Context {R : Type}.\n\n(*|\nSilent failure: contrary to an event-based failure, this\nstuck state cannot be observed, it will be indistinguishable\nfrom [spin] w.r.t. the bisimulations introduced.\n|*)\n  Definition stuck `{B0 -< B} vis : ctree E B R :=\n    br vis branch0 (fun x : void => match x with end).\n\n(*|\nGuards similar to [itree]'s taus.\n|*)\n  Definition Guard `{B1 -< B} t : ctree E B R :=\n    brD branch1 (fun _ => t).\n\n  Definition Step `{B1 -< B} t : ctree E B R :=\n    brS branch1 (fun _ => t).\n\n(*|\nBounded branching\n|*)\n  Definition brD2 `{B2 -< B} t u : ctree E B R :=\n    brD branch2 (fun b => if b : bool then t else u).\n  Definition brS2 `{B2 -< B} t u : ctree E B R :=\n    brS branch2 (fun b => if b : bool then t else u).\n  Definition brD3 `{B3 -< B} t u v : ctree E B R :=\n    brD branch3 (fun n => match n with\n                           | t31 => t\n                           | t32 => u\n                           | t33 => v\n                           end).\n  Definition brS3 `{B3 -< B} t u v : ctree E B R :=\n    brS branch3 (fun n => match n with\n                           | t31 => t\n                           | t32 => u\n                           | t33 => v\n                           end).\n  Definition brD4 `{B4 -< B} t u v w : ctree E B R :=\n    brD branch4 (fun n => match n with\n                           | t41 => t\n                           | t42 => u\n                           | t43 => v\n                           | t44 => w\n                           end).\n  Definition brS4 `{B4 -< B} t u v w : ctree E B R :=\n    brS branch4 (fun n => match n with\n                           | t41 => t\n                           | t42 => u\n                           | t43 => v\n                           | t44 => w\n                           end).\n\n(*|\nFinite branch\n|*)\n  Definition brDn `{Bn -< B} n k : ctree E B R :=\n    brD (branchn n) k.\n  Definition brSn `{Bn -< B} n k : ctree E B R :=\n    brS (branchn n) k.\n\n(*|\nCountable branch\n|*)\n  Definition brIN `{BN -< B} k : ctree E B R :=\n    brD branchN k.\n  Definition brSN `{BN -< B} k : ctree E B R :=\n    brS branchN k.\n\nEnd Branching.\n\n(*|\nMain operations on [ctree]\n--------------------------\n\nThe core definitions are wrapped in a module for namespacing. They are meant to be used qualified (e.g., CTree.bind) or via notations (e.g., [>>=]).\n\nNote on how to write cofixpoints\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nWe define cofixpoints in two steps:\n\nfirst a plain definition (prefixed with an [_], e.g., [_bind], [_iter]) defines the body of the function:\n\n- it takes the recursive call ([bind]) as a parameter;\n- if we are deconstructing an ctree, this body takes the unwrapped [ctreeF];\n\nsecond the actual [CoFixpoint] (or, equivalently, [cofix]) ties the knot, applying [observe] to any [ctree] parameters.\n\nThis style allows us to keep [cofix] from ever appearing in proofs, which could otherwise get quite unwieldly.\nFor every [CoFixpoint] (such as [bind]), we prove an unfolding lemma to rewrite it as a term whose head is [_bind], without any [cofix] above it.\n\n\n    unfold_bind : observe (bind t k)\n                = observe (_bind (fun t' => bind t' k) t)\n\nNote that this is an equality \"up to\" [observe]. It would not be provable if it were a plain equality:\n\n    bind t k = _bind (...) t\n    (cofix bind' t1 := _bind (...) t1) t = _bind (...) t1\n\nThe [cofix] is stuck, and can only be unstuck under the primitive projection [_observe] (which is wrapped by [observe]).\n\nDefinitions\n\nThese are meant to be imported qualified, e.g., [CTree.bind],\n[CTree.trigger], to avoid ambiguity with identifiers of the same\nname (some of which are overloaded generalizations of these).\n|*)\n\nModule CTree.\n\n  Section CTree.\n\n    Context {E B : Type -> Type}.\n\n(*|\n[bind]: monadic composition, tree substitution, sequencing of\ncomputations. [bind t k] is also denoted by [t >>= k] and using\n\"do-notation\" [x <- t ;; k x].\n|*)\n\n(*|\n[subst]: [bind] with its arguments flipped.\nWe keep the continuation [k] outside the cofixpoint.\nIn particular, this allows us to nest [bind] in other cofixpoints,\nas long as the recursive occurences are in the continuation\n(i.e., this makes it easy to define tail-recursive functions).\n|*)\n    Definition subst {T U : Type} (k : T -> ctree E B U)\n      : ctree E B T -> ctree E B U :=\n      cofix _subst (u : ctree E B T) : ctree E B U :=\n        match observe u with\n        | RetF r => k r\n        | VisF e h => Vis e (fun x => _subst (h x))\n        | BrF b n h => Br b n (fun x => _subst (h x))\n        end.\n\n    Definition bind {T U : Type} (u : ctree E B T) (k : T -> ctree E B U)\n      : ctree E B U :=\n      subst k u.\n\n(*|\nMonadic composition of continuations (i.e., Kleisli composition).\n|*)\n\n    Definition cat {T U V}\n      (k : T -> ctree E B U) (h : U -> ctree E B V) :\n      T -> ctree E B V :=\n      fun t => bind (k t) h.\n\n(*|\nFunctorial map ([fmap] in Haskell)\n|*)\n\n    Definition map {R S} (f : R -> S)  (t : ctree E B R) : ctree E B S :=\n      bind t (fun x => Ret (f x)).\n\n(*|\nAtomic itrees triggering a single event.\n|*)\n\n    Definition trigger : E ~> ctree E B :=\n      fun R e => Vis e (fun x => Ret x).\n\n(*|\nAtomic ctrees with choice.\n|*)\n\n    Definition branch b {X : Type} : forall (c : B X), ctree E B X :=\n      fun c => Br b c (fun x => Ret x).\n\n(*|\nIgnore the result of a tree.\n|*)\n\n    Definition ignore {R} : ctree E B R -> ctree E B unit :=\n      map (fun _ => tt).\n\n  End CTree.\n\n  Ltac fold_bind :=\n    repeat match goal with\n      | h: context [CTree.subst ?k ?t] |- _ => fold (CTree.bind t k) in h\n      | |- context [CTree.subst ?k ?t] => fold (CTree.bind t k)\n      end.\n\n(*|\n[on_left lr l t]: run a computation [t] if the first argument is an [inl l].\n[l] must be a variable (used as a pattern), free in the expression [t]:\n\n   - [on_left (inl x) l t = t{l := x}]\n   - [on_left (inr y) l t = Ret y]\n|*)\n\n  Notation on_left lr l t :=\n    (match lr with\n     | inl l => t\n     | inr r => Ret r\n     end) (only parsing).\n\n(*|\nCombinators for loops must be guarded, we hence assume that\nunary choices are available.\n|*)\n  Section withGuard.\n\n    Context {E B : Type -> Type}.\n    Context `{B1 -< B}.\n\n    CoFixpoint spinD {R} : ctree E B R := Guard spinD.\n    CoFixpoint spinS {R} : ctree E B R := Step spinS.\n(*|\nRepeat a computation infinitely.\n|*)\n\n    Definition forever {E R S} (t : ctree E B R) : ctree E B S :=\n      cofix forever_t := bind t (fun _ => Guard (forever_t)).\n\n(*|\n[iter]: See [Basics.Basics.MonadIter].\nNote: here we must be careful to call [iter\\_ l] under [Tau] to avoid an eager\ninfinite loop if [step i] is always of the form [Ret (inl _)] (cf. issue #182).\n|*)\n\n    Definition iter {R I: Type}\n      (step : I -> ctree E B (I + R)) : I -> ctree E B R :=\n      cofix iter_ i := bind (step i) (fun lr => on_left lr l (Guard (iter_ l))).\n\n  End withGuard.\n\n(*|\nInfinite taus.\n|*)\n\n  CoFixpoint spinD_gen {E C R X} (x : C X) : ctree E C R :=\n\t  BrD x (fun _ => spinD_gen x).\n  CoFixpoint spinS_gen {E C R X} (x : C X) : ctree E C R :=\n\t  BrS x (fun _ => spinS_gen x).\n\n  Ltac fold_subst :=\n    repeat (change (CTree.subst ?k ?t) with (CTree.bind t k)).\n\n  Ltac fold_monad :=\n    repeat (change (@CTree.bind ?E) with (@Monad.bind (ctree E) _));\n    repeat (change (go (@RetF ?E _ _ _ ?r)) with (@Monad.ret (ctree E) _ _ r));\n    repeat (change (@CTree.map ?E) with (@Functor.fmap (ctree E) _)).\n\nEnd CTree.\n\nNotation branch b c := (CTree.branch b (subevent _ c)).\nNotation branchD c := (CTree.branch false (subevent _ c)).\nNotation branchS c := (CTree.branch true (subevent _ c)).\nNotation trigger e := (CTree.trigger (subevent _ e)).\nNotation stuckD := (stuck false).\nNotation stuckS := (stuck true).\n\n(*|\n=========\nNotations\n=========\n\nSometimes it's more convenient to work without the type classes [Monad], etc. When functions using type classes are specialized,\nthey simplify easily, so lemmas without classes are easier to apply than lemmas with.\n\nWe can also make ExtLib's [bind] opaque, in which case it still doesn't hurt to have these notations around.\n|*)\n\nModule CTreeNotations.\nNotation \"t1 >>= k2\" := (CTree.bind t1 k2)\n  (at level 58, left associativity) : ctree_scope.\nNotation \"x <- t1 ;; t2\" := (CTree.bind t1 (fun x => t2))\n  (at level 62, t1 at next level, right associativity) : ctree_scope.\nNotation \"t1 ;; t2\" := (CTree.bind t1 (fun _ => t2))\n  (at level 62, right associativity) : ctree_scope.\nNotation \"' p <- t1 ;; t2\" :=\n  (CTree.bind t1 (fun x_ => match x_ with p => t2 end))\n  (at level 62, t1 at next level, p pattern, right associativity) : ctree_scope.\nEnd CTreeNotations.\n\n(*|\n=========\nInstances\n=========\n|*)\n\n#[global] Instance Functor_ctree {E B} : Functor (ctree E B) :=\n{ fmap := @CTree.map E B }.\n\n#[global] Instance Monad_ctree {E B} : Monad (ctree E B) :=\n{| ret := fun _ x => Ret x\n;  bind := @CTree.bind E B\n|}.\n\n#[global] Instance MonadIter_ctree {E B} `{B1 -< B} : MonadIter (ctree E B) :=\n  fun R I => @CTree.iter E B _ R I.\n\n(* #[global] Instance MonadTrigger_ctree {E B} : MonadTrigger E (ctree E B) | 1 := *)\n(*   @CTree.trigger _ _. *)\n\n#[global] Instance MonadTrigger_ctree {E F B} `{E -< F} : MonadTrigger E (ctree F B) :=\n  fun _ e => trigger e.\n\n(* #[global] Instance MonadBr_ctree {E B} : MonadBr B (ctree E B) | 1 := *)\n(*   @CTree.branch _ _. *)\n\n#[global] Instance MonadBr_ctree {E C D} `{C -< D} : MonadBr C (ctree E D) :=\n  fun b _ c => branch b c.\n\n(*|\n====================================\nInversion lemma relying on [JMeq_eq]\n====================================\nSince the [Vis] and [Br] constructors take dependent\npairs as argument, their inversion is not straightforward.\nThe ITree library goes to great length to avoid the use of\naxioms where possible. Here for now we fully embrace [JMeq_eq]\n-- it is introduced under the scene by [dependent destruction].\n|*)\n\nLemma Vis_eq1 E C R T Y e k Z f h: @VisF E C R T Y e k = @VisF E C R T Z f h -> Y=Z.\nProof. intro H. now dependent destruction H. Qed.\n\nLemma Vis_eq2 E C R T Y e k f h: @VisF E C R T Y e k = @VisF E C R T Y f h -> e=f /\\ k=h.\nProof. intro H. now dependent destruction H. Qed.\n\nLemma Br_eq1 E B R T b b' Y Z c c' k h:\n  @BrF E B R T b Y c k = @BrF E B R T b' Z c' h -> b = b' /\\ Y = Z.\nProof. intro H. now dependent destruction H. Qed.\n\nLemma Br_eq2 E B R T b Y c c' k h:\n  @BrF E B R T b Y c k = @BrF E B R T b Y c' h -> c = c' /\\ k = h.\nProof. intro H. now dependent destruction H. Qed.\n\n(*|\n=======\nTactics\n=======\n|*)\n\nTactic Notation \"hinduction\" hyp(IND) \"before\" hyp(H)\n  := move IND before H; Tactics.revert_until IND; induction IND.\n\nLtac inv H := inversion H; clear H; subst.\n\nLtac rewrite_everywhere lem :=\n  progress ((repeat match goal with [H: _ |- _] => rewrite lem in H end); repeat rewrite lem).\n\nLtac rewrite_everywhere_except lem X :=\n  progress ((repeat match goal with [H: _ |- _] =>\n                 match H with X => fail 1 | _ => rewrite lem in H end\n             end); repeat rewrite lem).\n\nLtac genobs x ox := remember (observe x) as ox.\nLtac genobs_clear x ox := genobs x ox; match goal with [H: ox = observe x |- _] => clear H x end.\nLtac simpobs := repeat match goal with [H: _ = observe _ |- _] =>\n                    rewrite_everywhere_except (@eq_sym _ _ _ H) H\n                end.\nLtac desobs x := destruct (observe x) .\n\nLtac fold_subst :=\n  repeat (change (CTree.subst ?k ?t) with (CTree.bind t k)).\n\n\n(*|\n==================\nCompute with fuel\n==================\n\nRemove [Guard]s and [Step]s from the front of an [ctree].\n|*)\nFixpoint burn (n : nat) {E B : Type -> Type} {R} (t : ctree E (B01 +' B) R) : ctree E (B01 +' B) R :=\n  match n with\n  | 0 => t\n  | S n =>\n      match observe t with\n      | RetF r => Ret r\n      | VisF e k => Vis e k\n      | BrF b (inl1 (inr1 c)) k =>\n          match c in (B1 T) return (T -> _) -> _ with\n          | branch1 => fun k => burn n (k tt)\n          end k\n      | BrF b c k => Br b c k\n      end\n  end.\n", "meta": {"author": "vellvm", "repo": "ctrees", "sha": "a622bc2e63eaa987e081b862e9aafeea3f8f5d79", "save_path": "github-repos/coq/vellvm-ctrees", "path": "github-repos/coq/vellvm-ctrees/ctrees-a622bc2e63eaa987e081b862e9aafeea3f8f5d79/theories/Core/CTreeDefinitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.281132419524212}}
{"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.Notations.\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 Plain.\n  Inductive state :=\n  | ParseMPLS\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  | HdrMPLS\n  | HdrUDP.\n\n  Definition sz (h: header) : nat :=\n    match h with\n    | HdrMPLS => 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_eqdec.\n  Proof.\n    solve_finiteness.\n  Defined.\n\n  Definition states (s: state) :=\n    match s with\n    | ParseMPLS =>\n      {| st_op :=\n          extract(HdrMPLS) ;\n         st_trans := transition select (| (@EHdr header sz HdrMPLS)[23 -- 23] |) {{\n            [| exact #b|1 |] ==> inl ParseUDP ;;;\n            [| exact #b|0 |] ==> inl ParseMPLS ;;;\n              reject\n          }}\n      |}\n    | ParseUDP =>\n      {| st_op := extract(HdrUDP);\n         st_trans := transition accept |}\n    end.\n\n  Program Definition aut: Syntax.t state _ :=\n    {| t_states := states |}.\n  Solve Obligations with (destruct h || destruct s; cbv; Lia.lia).\n\nEnd Plain.\n\nModule Unrolled.\n  Inductive state :=\n  | ParseMPLS\n  | ParseUDP\n  | Cleanup.\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  | HdrMPLS0\n  | HdrMPLS1\n  | Tmp\n  | HdrUDP .\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_eqdec.\n  Proof.\n    solve_finiteness.\n  Defined.\n\n  Definition sz (h: header) : nat :=\n    match h with\n    | HdrMPLS0 => 32\n    | HdrMPLS1 => 32\n    | Tmp => 32\n    | HdrUDP => 64\n    end.\n\n  Notation EHdr' := (@EHdr header sz).\n\n  Definition states (s: state) :=\n    match s with\n    | ParseMPLS =>\n      {| st_op :=\n          extract(HdrMPLS0) ;;\n          extract(HdrMPLS1) ;\n         st_trans := transition select (| (EHdr' HdrMPLS0)[23 -- 23], (EHdr' HdrMPLS1)[23 -- 23]|) {{\n          [| exact (#b|1), * |] ==> inl Cleanup ;;;\n          [| exact (#b|0), exact (#b|1) |] ==> inl ParseUDP ;;;\n          [| exact (#b|0), exact (#b|0) |] ==> inl ParseMPLS ;;;\n            reject\n          }}\n      |}\n    | ParseUDP =>\n      {| st_op := extract(HdrUDP) ;\n         st_trans := transition accept |}\n    | Cleanup =>\n      {| st_op :=\n        extract(Tmp) ;;\n        HdrUDP <- EConcat (EHdr' HdrMPLS1) (EHdr Tmp);\n        st_trans := transition accept |}\n    end.\n\n  Program Definition aut: Syntax.t state _ :=\n    {| t_states := states |}.\n  Solve Obligations with (destruct h || destruct s; cbv; Lia.lia).\n\nEnd Unrolled.\n\nModule MPLSVect.\n  Definition aut := Sum.sum Plain.aut Unrolled.aut.\nEnd MPLSVect.\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/MPLSVectorized.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.585101154203231, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.28112862909587305}}
{"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 orthogonalite_espace.\nRequire Export affine_classiques.\nSet Implicit Arguments.\nUnset Strict Implicit.\n \nDefinition tetraedre (A B C D : PO) := ~ coplanaires A B C D.\n \nLemma tetraedre_non_alignes :\n forall A B C D : PO, tetraedre A B C D -> ~ alignes A B C.\nunfold tetraedre in |- *; intros.\nelim non_coplanaires_expl with (A := A) (B := B) (C := C) (D := D);\n [ intros H0 H1; try clear non_coplanaires_expl; try exact H0 | auto ].\nQed.\n#[export] Hint Resolve tetraedre_non_alignes: geo.\n \nLemma deux_milieux_tetraedre :\n forall A B C D I J K L : PO,\n tetraedre A B C D ->\n I = milieu D A ->\n J = milieu D B -> K = milieu C A -> L = milieu C B -> vec I J = vec K L.\nintros.\ncut (mult_PP 2 (vec I J) = vec A B); intros.\ncut (mult_PP 2 (vec K L) = vec A B); intros.\napply mult_PP_regulier with 2; auto with real.\nrewrite H5; auto.\napply droite_milieu with C; auto.\napply droite_milieu with D; auto.\nQed.\n \nDefinition parallelepipede (A B C D E F G H : PO) :=\n  (vec A B = vec D C /\\ vec D C = vec H G) /\\\n  vec H G = vec E F /\\ vec E H = vec A D.\n \nDefinition parallelepipede_rectangle (A B C D E F G H : PO) :=\n  parallelepipede A B C D E F G H /\\\n  orthogonal (vec A B) (vec A D) /\\\n  orthogonal (vec A B) (vec A E) /\\ orthogonal (vec A D) (vec A E).\n \nDefinition carre (A B C D : PO) :=\n  vec A B = vec D C /\\\n  orthogonal (vec A B) (vec A D) /\\\n  scalaire (vec A B) (vec A B) = 1 /\\ scalaire (vec A D) (vec A D) = 1.\n \nDefinition cube (A B C D E F G H : PO) :=\n  parallelepipede_rectangle A B C D E F G H /\\\n  carre A B C D /\\ scalaire (vec A E) (vec A E) = 1.\n \nLemma parallelepipede_parallelogramme :\n forall A B C D E F G H : PO,\n parallelepipede A B C D E F G H -> vec F G = vec A D.\nunfold parallelepipede in |- *; intros A B C D E F G H' H.\nelim H; intros H0 H1; elim H1; intros H2 H3; try clear H1 H; try exact H3.\nelim H0; intros H H1; try clear H0; try exact H1.\nrewrite <- H3.\napply egalite_vecteur.\nVReplace (vec F E) (mult_PP (-1) (vec E F)).\nrewrite <- H2.\nRingvec.\nQed.\n \nLemma diagonales_carre :\n forall A B C D : PO, carre A B C D -> orthogonal (vec A C) (vec D B).\nintros.\nelim H; clear H; intros.\napply def_orthogonal2.\nelim H0; intros H2 H3; elim H3; intros H4 H5; try clear H3 H0; try exact H5.\ncut (scalaire (vec A B) (vec A D) = 0); intros.\nreplace (vec A C) with (add_PP (mult_PP 1 (vec A B)) (mult_PP 1 (vec A D))).\nreplace (vec D B) with\n (add_PP (mult_PP (-1) (vec A D)) (mult_PP 1 (vec A B))).\nrewrite scalaire_bilineaire.\nrewrite H4; rewrite H5; rewrite H0.\nrewrite scalaire_sym; rewrite H0; ring.\nRingvec.\nrewrite H.\nRingvec.\napply def_orthogonal; auto.\nQed.\n \nLemma centre_gravite_coplanaire :\n forall A B C : PO,\n ~ alignes A B C -> coplanaires A B C (centre_gravite A B C).\nunfold centre_gravite, milieu, coplanaires in |- *; intros.\nright; try assumption.\nexists (/ 3); exists (/ 3).\ncut (3 <> 0); intros; auto with real.\napply mult_PP_regulier with 3; auto with real.\nFVReplace\n (mult_PP 3\n    (add_PP (cons (/ 3) A)\n       (add_PP (cons (/ 3) B) (cons (1 + - (/ 3 + / 3)) C))))\n (add_PP (cons 1 A) (add_PP (cons 1 B) (cons 1 C))) 3.\nVReplace\n (mult_PP 3\n    (cons 1\n       (barycentre (cons 1 A) (cons 2 (barycentre (cons 1 B) (cons 1 C))))))\n (cons 3 (barycentre (cons 1 A) (cons 2 (barycentre (cons 1 B) (cons 1 C))))).\nreplace 3 with (1 + 2) by ring.\nrewrite <- add_PP_barycentre; auto with real.\nreplace 2 with (1 + 1) by ring.\nrewrite <- add_PP_barycentre; auto with real.\nQed.\n\n#[export] Hint Resolve centre_gravite_coplanaire: geo.\n \nLemma exercice :\n forall A B C D E F G H I : PO,\n D <> F ->\n ~ alignes E B G ->\n parallelepipede A B C D E F G H ->\n I = centre_gravite E B G -> coplanaires E B G I /\\ alignes F D I.\nintros A B C D E F G H I H20 H0 H1 H51; try assumption.\nrewrite H51.\nsplit; [ auto with geo | idtac ].\ncut (vec F G = vec A D).\nintros H10.\nunfold parallelepipede in H1.\nelim H1; intros H2 H3; elim H2; intros H4 H5; try clear H2 H1; try exact H4.\nelim H3; intros H2 H12; try clear H3.\ncut (vec F D = mult_PP 3 (vec F (centre_gravite E B G))); intros.\ncut (3 <> 0); intros; auto with real.\napply colineaire_alignes with (/ 3); auto.\nrewrite H1.\nFieldvec 3; auto.\ncut (add_PP (mult_PP 3 (vec (centre_gravite E B G) F)) (vec F D) = zero);\n intros.\nVReplace (vec F D) (add_PP (vec F D) (mult_PP (-1) zero)).\nrewrite <- H1.\nRingvec.\nVReplace (vec F D) (add_PP (vec F B) (add_PP (vec B A) (vec A D))).\nreplace (vec B A) with (vec F E); auto.\nreplace (vec A D) with (vec F G); auto.\nVReplace (add_PP (vec F B) (add_PP (vec F E) (vec F G)))\n (add_PP (vec F E) (add_PP (vec F B) (vec F G))).\nreplace (add_PP (vec F E) (add_PP (vec F B) (vec F G))) with\n (mult_PP 3\n    (vec F\n       (barycentre (cons 1 E) (cons 2 (barycentre (cons 1 B) (cons 1 G))))));\n auto.\nunfold vec, centre_gravite, milieu in |- *; RingPP.\nVReplace (add_PP (vec F B) (vec F G))\n (add_PP (mult_PP 1 (vec F B)) (mult_PP 1 (vec F G))).\nrewrite\n (prop_vecteur_bary (a:=1) (b:=1) (A:=B) (B:=G)\n    (G:=barycentre (cons 1 B) (cons 1 G)) F); auto.\nVReplace (vec F E) (mult_PP 1 (vec F E)).\nreplace (1 + 1) with 2 by ring.\nrewrite (prop_vecteur_bary (a:=1) (b:=2) (A:=E)\n    (B:=barycentre (cons 1 B) (cons 1 G))\n    (G:=barycentre (cons 1 E) (cons 2 (barycentre (cons 1 B) (cons 1 G)))) F)\n ; auto.\ndiscrR.\ndiscrR.\ncut (vec A B = vec E F); intros; auto.\nVReplace (vec B A) (mult_PP (-1) (vec A B)).\nrewrite H1.\nRingvec.\nrewrite H4.\nrewrite H5; auto.\napply parallelepipede_parallelogramme with (1 := H1).\nQed.\n \nLemma exercice_cube :\n forall A B C D E F G H I : PO,\n D <> F ->\n ~ alignes E B G ->\n cube A B C D E F G H ->\n I = centre_gravite E B G ->\n alignes F D I /\\ orthogonaux (droite F D) (plan E B G).\nintros A B C D E F G H I H0 H1 H2 H51; try assumption.\nelim H2; intros; clear H2.\nelim H3; intros; clear H3.\nelim H5; intros H3 H6; elim H6; intros H7 H8; try clear H6 H5; try exact H8.\nelim H4; intros H5 H6; try clear H4; try exact H6.\nsplit; [ try assumption | idtac ].\nelim\n exercice\n  with\n    (A := A)\n    (B := B)\n    (C := C)\n    (D := D)\n    (E := E)\n    (F := F)\n    (G := G)\n    (H := H)\n    (I := I); [ try clear exercice; auto | auto | auto | auto | auto ].\nelim H5; intros; clear H5.\nelim H9; intros H5 H10; elim H10; intros H11 H12; try clear H10 H9;\n try exact H12.\nelim H2; intros.\nelim H10; intros H13 H14; try clear H10; try exact H14.\nelim H9; intros H10 H15; try clear H9; try exact H15.\ncut (scalaire (vec A B) (vec A E) = 0); intros.\ncut (scalaire (vec A B) (vec A D) = 0); intros.\ncut (scalaire (vec A D) (vec A E) = 0); intros.\ncut (E <> B); intros.\ncut (E <> G); intros.\ncut (vec F D = add_PP (vec F A) (vec A D)); intros.\napply def_orthogonaux; auto.\napply def_orthogonales; auto.\napply def_orthogonal2.\nrewrite scalaire_sym.\nrewrite H20.\nrewrite scalaire_somme_g.\nreplace (scalaire (vec F A) (vec E B)) with 0.\nreplace (scalaire (vec A D) (vec E B)) with 0.\nring.\nreplace (vec E B) with\n (add_PP (mult_PP (-1) (vec A E)) (mult_PP 1 (vec A B))).\nrewrite scalaire_lineaire_d.\nrewrite H17.\nrewrite scalaire_sym.\nrewrite H16.\nring.\nRingvec.\nreplace (vec E B) with\n (add_PP (mult_PP (-1) (vec A E)) (mult_PP 1 (vec A B))).\nreplace (vec F A) with\n (add_PP (mult_PP (-1) (vec A E)) (mult_PP (-1) (vec A B))).\nrewrite scalaire_bilineaire.\nrewrite H11; rewrite H6; rewrite H9.\nrewrite scalaire_sym.\nrewrite H9.\nring.\nrewrite H10; rewrite H15; rewrite H13.\nRingvec.\nRingvec.\napply def_orthogonales; auto.\napply def_orthogonal2.\nreplace (vec E G) with (add_PP (vec A B) (vec A D)).\nrewrite scalaire_somme_g.\nrewrite scalaire_sym.\nrewrite (scalaire_sym A D F D).\nrewrite H20.\nrewrite scalaire_somme_g.\nrewrite scalaire_somme_g.\nrewrite H12.\nrewrite (scalaire_sym A D A B).\nrewrite H16.\nreplace (vec F A) with\n (add_PP (mult_PP (-1) (vec A E)) (mult_PP (-1) (vec A B))).\nrewrite scalaire_lineaire_g.\nrewrite scalaire_lineaire_g.\nrewrite H11; rewrite H16.\nrewrite scalaire_sym.\nrewrite H9.\nrewrite scalaire_sym.\nrewrite H17.\nring.\nrewrite H10; rewrite H15; rewrite H13.\nRingvec.\nreplace (vec E G) with (add_PP (vec E F) (vec F G)).\nrewrite H10; rewrite H15; rewrite H13.\nrewrite parallelepipede_parallelogramme with (1 := H2); auto.\nRingvec.\nRingvec.\napply distance_non_nulle.\nreplace (vec E G) with (add_PP (mult_PP 1 (vec A B)) (mult_PP 1 (vec A D))).\nrewrite scalaire_bilineaire.\nrewrite H11; rewrite H12; rewrite H16.\nrewrite scalaire_sym; rewrite H16.\nreplace (1 * 1 * 1 + 1 * 1 * 0 + (1 * 1 * 0 + 1 * 1 * 1)) with 2.\ndiscrR.\nring.\nreplace (vec E G) with (add_PP (vec E F) (vec F G)).\nrewrite H10; rewrite H15; rewrite H13.\nrewrite parallelepipede_parallelogramme with (1 := H2); auto.\nRingvec.\nRingvec.\napply distance_non_nulle.\nreplace (vec E B) with\n (add_PP (mult_PP (-1) (vec A E)) (mult_PP 1 (vec A B))).\nrewrite scalaire_bilineaire.\nrewrite H11; rewrite H9; rewrite H6.\nrewrite scalaire_sym; rewrite H9.\nreplace (-1 * -1 * 1 + -1 * 1 * 0 + (1 * -1 * 0 + 1 * 1 * 1)) with 2.\ndiscrR.\nring.\nRingvec.\napply def_orthogonal; auto.\napply def_orthogonal; auto.\napply def_orthogonal; auto.\nQed.\n \nLemma equilateral_non_alignes :\n forall A B C : PO,\n A <> B ->\n scalaire (vec A B) (vec A B) = scalaire (vec A C) (vec A C) ->\n scalaire (vec A B) (vec A B) = scalaire (vec B C) (vec B C) ->\n ~ alignes A B C.\nintros A B C H H0 H1; red in |- *; intros H2; try exact H2.\nhalignes H2 k.\nrewrite H3 in H0.\ncut (vec B C = mult_PP (k + -1) (vec A B)); intros.\nrewrite H4 in H1.\ncut (k * k = 1); intros.\ncut ((k + -1) * (k + -1) = 1); intros.\ncut (k = 1 \\/ k = -1); intros.\nelim H7; [ intros H8; try clear H7; try exact H8 | intros H8; try clear H7 ].\nrewrite H8 in H6.\nabsurd (0 = 1); auto with *.\nrewrite <- H6; ring.\nrewrite H8 in H6.\nabsurd ((-1 + -1) * (-1 + -1) = 1).\ntry discrR.\ntry assumption.\ncut (k + -1 = 0 \\/ k + 1 = 0); intros.\nelim H7; [ intros H8; try clear H7; try exact H8 | intros H8; try clear H7 ].\nleft; try assumption.\nreplace k with (k + -1 + 1).\nrewrite H8; ring.\nring.\nright; try assumption.\nreplace k with (k + 1 + -1).\nrewrite H8; ring.\nring.\napply Rmult_integral.\nreplace 0 with (k * k + -1).\nring.\nrewrite H5; ring.\napply Rmult_eq_reg_l with (scalaire (vec A B) (vec A B)).\nreplace (scalaire (vec A B) (vec A B) * 1) with\n (scalaire (vec A B) (vec A B)).\npattern (scalaire (vec A B) (vec A B)) at 2 in |- *.\nrewrite H1.\nrewrite scalaire_mult_mult; ring.\nring.\nunfold not in |- *; intros; apply H.\napply distance_nulle; auto.\napply Rmult_eq_reg_l with (scalaire (vec A B) (vec A B)).\nreplace (scalaire (vec A B) (vec A B) * 1) with\n (scalaire (vec A B) (vec A B)).\npattern (scalaire (vec A B) (vec A B)) at 2 in |- *.\nrewrite H0.\nrewrite scalaire_mult_mult; ring.\nring.\nunfold not in |- *; intros; apply H.\napply distance_nulle; auto.\nreplace (vec B C) with (add_PP (vec A C) (mult_PP (-1) (vec A B))).\nrewrite H3.\nRingvec.\nRingvec.\nQed.\n \nTheorem the_cube :\n forall A B C D E F G H I : PO,\n cube A B C D E F G H ->\n I = centre_gravite E B G ->\n alignes F D I /\\ orthogonaux (droite F D) (plan E B G).\nintros A B C D E F G H I H0 H51; try assumption.\nelim H0; intros.\nelim H1; intros.\nelim H3; intros.\nelim H6; intros H7 H8; try clear H6; try exact H8.\nelim H5; intros H6 H9; try clear H5; try exact H9.\nelim H4; intros H5 H10; elim H10; intros H11 H12; try clear H10 H4;\n try exact H12.\nelim H2; intros H4 H10; try clear H2; try exact H10.\nelim H4; intros.\nelim H13; intros H14 H15; elim H15; intros H16 H17; try clear H15 H13;\n try exact H16.\ncut (vec A F = add_PP (mult_PP 1 (vec A B)) (mult_PP 1 (vec A E))); intros.\ncut (scalaire (vec A B) (vec A E) = 0); intros.\ncut (scalaire (vec A B) (vec A D) = 0); intros.\ncut (scalaire (vec A D) (vec A E) = 0); intros.\napply exercice_cube with (3 := H0); auto.\napply distance_non_nulle.\nreplace (vec D F) with\n (add_PP (mult_PP 1 (vec A F)) (mult_PP (-1) (vec A D))).\nrewrite scalaire_bilineaire.\nreplace (scalaire (vec A F) (vec A F)) with 2.\ncut (scalaire (vec A F) (vec A D) = 0); intros.\nrewrite H20; rewrite H17.\nrewrite scalaire_sym; rewrite H20.\ntry discrR.\nrewrite H13.\nrewrite scalaire_lineaire_g.\nrewrite H18.\nrewrite scalaire_sym; rewrite H19.\nring.\nrewrite H13.\nrewrite scalaire_bilineaire.\nrewrite H15; rewrite H10; rewrite H16.\nrewrite scalaire_sym; rewrite H15.\nring.\nRingvec.\ncut (vec E B = add_PP (mult_PP 1 (vec A B)) (mult_PP (-1) (vec A E))); intros.\ncut (vec E G = add_PP (mult_PP 1 (vec A B)) (mult_PP 1 (vec A D))); intros.\napply equilateral_non_alignes; auto.\napply distance_non_nulle.\nrewrite H20.\nrewrite scalaire_bilineaire.\nrewrite H15; rewrite H10; rewrite H16.\nrewrite scalaire_sym; rewrite H15.\ntry discrR.\nrewrite H20.\nrewrite scalaire_bilineaire.\nrewrite H21.\nrewrite scalaire_bilineaire.\nrewrite H15; rewrite H10; rewrite H16.\nrewrite scalaire_sym; rewrite H15.\nrewrite H17; rewrite H18.\nrewrite scalaire_sym; rewrite H18.\nring.\nreplace (vec B G) with\n (add_PP (mult_PP 1 (vec E G)) (mult_PP (-1) (vec E B))).\nrewrite scalaire_bilineaire.\nrewrite H20.\nrewrite scalaire_bilineaire.\nrewrite H21.\nrepeat rewrite scalaire_bilineaire.\nrewrite H15; rewrite H10; rewrite H16.\nrewrite scalaire_sym; rewrite H15.\nrewrite H17; rewrite H18.\nrewrite scalaire_sym; rewrite H18.\nrewrite H19; rewrite scalaire_sym; rewrite H19.\nring.\nRingvec.\nrewrite <- H8.\nrewrite H6; rewrite H9.\nRingvec.\nRingvec.\napply def_orthogonal; auto.\napply def_orthogonal; auto.\napply def_orthogonal; auto.\nrewrite H6; rewrite H9; rewrite H7.\nRingvec.\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/exercice_espace.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2811286221435907}}
{"text": "From Coq Require Import Zify.\nFrom mathcomp\nRequire Import ssreflect ssrbool ssrnat eqtype seq ssrfun zify.\nFrom fcsl\nRequire Import prelude pred pcm unionmap heap.\nFrom HTT\nRequire Import stmod stsep stlog stlogR.\nFrom Hammer Require Import Tactics.\nRequire Import ZArith.\n\n(* The empty heap *)\nDefinition empty := @PCM.unit heapPCM.\n\n(* No-op at the end of a program branch *)\n\nDefinition skip := ret tt.\n\nInductive ltac_No_arg : Set :=\n| ltac_no_arg : ltac_No_arg.\n\n(* Utilities to move a heaplet around within a heap *)\n\nLtac put_to_tail_ptr p :=\n  try rewrite ptrA; rewrite -?joinA; rewrite ?(joinC (p :-> _) _); rewrite ?joinA.\n\nLtac put_to_tail h :=\n  try rewrite ptrA; rewrite -?joinA; rewrite ?(joinC h _); rewrite ?joinA.\n\nLtac put_to_head_ptr p :=\n  put_to_tail p;\n  try rewrite (joinC _ (p :-> _)).\n\nLtac put_to_head h :=\n  put_to_tail h;\n  try rewrite (joinC _ h).\n\n(* Store heap validity assertions *)\nLtac store_valid :=\n  rewrite ?unitL ?unitR;\n  try match goal with\n  | [|- is_true (valid _) -> _] =>\n    let hyp := fresh \"H_valid\" in move=>hyp;\n    store_valid\n  end.\n\n(* If goal is to prove a pointer is not null, derive that fact from one of the heap validity assertions *)\nLtac assert_not_null :=\n  let derive H x := (\n    rewrite ?joinA in H;\n    rewrite -?(joinC (x :-> _)) in H;\n    rewrite ?joinA in H;\n    move:(H);\n    rewrite defPtUnO;\n    case/andP;\n    let not_null := fresh \"not_null\" in move=>not_null _;\n    assumption) in\n  match goal with\n  | [H: is_true (valid ?h) |- is_true (?x != null)] =>\n    derive H x\n  end.\n\n(* Theory about predicates (to be filled by each certificate) *)\n\nCreate HintDb ssl_pred.\n\n(* Theory about pure constraints (to be filled by each certificate) *)\n\nCreate HintDb ssl_pure.\n\n(* Extend auto with additional strategies *)\n\nLtac eq_bool_to_prop :=\n  repeat match goal with\n         | [H: is_true (_ == _) |- _] => move/eqP in H\n         end.\n\nLtac solve_perm_eq :=\n  let n := fresh \"n\" in\n  apply/permP=>n;\n  repeat match goal with\n         | [H: is_true (perm_eq _ _) |- _] => move/permP in H; move:(H n)\n         end;\n  move=>//=;\n  rewrite ?count_cat;\n  zify; lia.\n\nLtac solve_pure := (timeout 2 progress eauto 2 with ssl_pure) + (sauto depth: 3).\n\nLtac sslauto :=\n  let simplify := eq_bool_to_prop; subst in\n  repeat apply conj;\n  match goal with\n  | [|- {subset _ <= _}] => simplify; unshelve solve_pure; done\n  | [|- is_true (perm_eq _ _)] => solve_perm_eq\n  | [|- _ = _] => simplify; rewrite ?unitL ?unitR; hhauto\n  | [|- is_true (_ == _)] => simplify; apply/eqP; unshelve solve_pure; done\n  | [|- is_true (_ < _)] => simplify; unshelve solve_pure; done\n  | [|- is_true (_ <= _)] => simplify; unshelve solve_pure; done\n  | _ => idtac\n  end.\n\n\nLtac ex_elim1 A := try clear dependent A; move=>[A].\nLtac ex_elim2 A B := try clear dependent A; try clear dependent B; move=>[A][B].\nLtac ex_elim3 A B C := try clear dependent A; try clear dependent B; try clear dependent C; move=>[A][B][C].\n\nTactic Notation \"ex_elim\" ident(A) := ex_elim1 A.\nTactic Notation \"ex_elim\" ident(A) ident(B) := ex_elim2 A B.\nTactic Notation \"ex_elim\" ident(A) ident(B) ident(C) := ex_elim3 A B C.\nTactic Notation \"ex_elim\" ident(A) ident(B) ident(C) ident(D) := ex_elim2 A B; ex_elim2 C D.\nTactic Notation \"ex_elim\" ident(A) ident(B) ident(C) ident(D) ident(E) := ex_elim2 A B; ex_elim3 C D E.\nTactic Notation \"ex_elim\" ident(A) ident(B) ident(C) ident(D) ident(E) ident(F) := ex_elim3 A B C; ex_elim3 D E F.\n\n(***********)\n(* Tactics *)\n(***********)\n\n(* After binding program variables to their correct labels, we use the Coq's default simplification algorithm *)\n\nLtac ssl_program_simpl := Tactics.program_simpl.\n\n\n(* Ghost Variable Elim *)\n\nLtac ssl_ghostelim_pre := try apply: ghR; move=>h_self//=.\n\nLtac ssl_ghostelim_post := store_valid.\n\n(* Read Rule *)\n\nLtac ssl_read from :=\n  put_to_head_ptr from;\n  apply: bnd_readR=>/=.\n\n(* Write Rule *)\n\nLtac ssl_write x :=\n  put_to_head_ptr x; (* this significantly speeds up bnd_writeR *)\n  apply: bnd_writeR=>/=.\n\nLtac ssl_write_post x :=\n  (put_to_tail_ptr x + rewrite -(unitL (x :-> _))); apply frame.\n\n(* Alloc Rule *)\n\nLtac ssl_alloc x :=\n  apply: bnd_allocbR=>x//=.\n\n(* Free Rule *)\n\nLtac ssl_dealloc x :=\n  apply: bnd_seq;\n  put_to_head_ptr x;\n  apply: val_deallocR=>//=_;\n  rewrite ?unitR.\n\n(* Call Rule *)\n\nLtac ssl_call_pre_aux h :=\n  match h with\n  | ?h1 \\+ ?h2 => put_to_head h2; ssl_call_pre_aux h1\n  | _ => put_to_head h\n  end.\n\nLtac ssl_call_pre h :=\n  ssl_call_pre_aux h;\n  rewrite ?joinA;\n  rewrite -?(joinA h).\n\nLtac ssl_call' ex :=\n  apply: bnd_seq;\n  match ex with\n  | ltac_No_arg => idtac\n  | _ => apply: (gh_ex ex)\n  end;\n  apply: val_do=>//=;\n  move=>_.\n\nTactic Notation \"ssl_call\" := ssl_call' ltac_No_arg.\nTactic Notation \"ssl_call\" constr(ex) := ssl_call' ex.\n\n(* Emp Rule *)\n\nLtac ssl_emp := apply: val_ret; rewrite ?unitL; store_valid; move=>//.\n\n(* Open Rule *)\n\nLtac conjuncts_to_ctx :=\n  match goal with\n  | [|- is_true (_ && _) -> _ ] => case/andP; conjuncts_to_ctx; let H := fresh \"H_cond\" in move=>H\n  | _ => let H := fresh \"H_cond\" in move=>H\n  end.\n\nLtac demorgan' :=\n  match goal with\n  | [|- context [~~ (_ && _)]] => rewrite Bool.negb_andb; demorgan'\n  | [|- context [~~ (_ || _)]] => rewrite Bool.negb_orb; demorgan'\n  | _ => idtac\n  end.\n\nLtac demorgan :=\n  demorgan';\n  conjuncts_to_ctx.\n\nLtac ssl_open sel hyp :=\n  let H := fresh \"H_cond\" in\n  case: hyp;\n  (case: (ifP sel); try move/negbT; demorgan; move=>_//) + demorgan .\n\n(* Branch Rule *)\n\nLtac ssl_branch sel :=\n  let H := fresh \"H_cond\" in\n  try case: (ifP sel);\n  try move/negbT;\n  try demorgan.\n\n(* Inconsistency Rule *)\n\nLtac ssl_inconsistency :=\n  match goal with\n  | [H_true: is_true ?sel, H_false: is_true (~~ ?sel) |- _] => rewrite H_true in H_false=>//=\n  end.\n\n(* Close Rule *)\n\nLtac ssl_close n :=\n  match n with\n  | 1 => constructor 1=>//\n  | 2 => constructor 2=>//\n  | 3 => constructor 3=>//\n  | _ => constructor=>//\n  end;\n  match goal with\n  | [|- is_true (_ != null)] => assert_not_null\n  | [|- (_ == null) = false] => apply negbTE; assert_not_null\n  | _ => idtac\n  end.\n\n(* Frame Unfold Rule *)\n\nLtac ssl_frame_unfold :=\n  (eq_bool_to_prop; subst; assumption) + (timeout 3 eauto 2 with ssl_pred).\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/lib/core.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.28112862214359063}}
{"text": "From Coq Require Import ZArith Rdefinitions String Psatz List.\nFrom ExtLib Require Import Monad.\nFrom MathClasses Require Import interfaces.canonical_names.\nFrom Flocq Require Import Binary Bits Core.Defs.\n\nRequire Import Gappa.Gappa_tactic.\n\nRequire Import Helix.Util.VecSetoid.\nRequire Import Helix.Util.OptionSetoid.\nRequire Import Helix.Util.ErrorSetoid.\nRequire Import Helix.Util.FloatUtil.\nRequire Import Helix.Tactics.StructTactics.\nRequire Import Helix.Tactics.HelixTactics.\n\nRequire Import Helix.HCOL.CarrierType.\nRequire Import Helix.HCOL.HCOL.\nRequire Import Helix.HCOL.THCOL.\n\nRequire Import Helix.SigmaHCOL.SVector.\nRequire Import Helix.SigmaHCOL.Rtheta.\nRequire Import Helix.SigmaHCOL.SigmaHCOL.\nRequire Import Helix.SigmaHCOL.TSigmaHCOL.\nRequire Import Helix.SigmaHCOL.IndexFunctions.\n\nRequire Import Helix.MSigmaHCOL.RasCT.\nRequire Import Helix.MSigmaHCOL.ReifySHCOL.\nRequire Import Helix.MSigmaHCOL.MSigmaHCOL.\nRequire Import Helix.MSigmaHCOL.ReifyProofs.\nRequire Import Helix.MSigmaHCOL.RasCarrierA.\nRequire Import Helix.MSigmaHCOL.MemSetoid.\n\nRequire Import Helix.RSigmaHCOL.ReifyProofs.\nRequire Import Helix.RSigmaHCOL.RSigmaHCOL.\n\nRequire Import Helix.FSigmaHCOL.ReifyRHCOL.\nRequire Import Helix.FSigmaHCOL.Float64asCT.\nRequire Import Helix.FSigmaHCOL.FSigmaHCOL.\n\nRequire Import Helix.SymbolicDHCOL.SymbolicCT.\nRequire Import Helix.SymbolicDHCOL.RHCOLtoSRHCOL.\nRequire Import Helix.SymbolicDHCOL.FHCOLtoSFHCOL.\n\nRequire Import Helix.DynWin.DynWin.\nRequire Import Helix.DynWin.DynWinProofs.\n\nImport ListNotations.\nImport MonadNotation.\nImport DynWin_CompareEpsilon.\n\nSection RHCOL_to_FHCOL_bounds.\n\n  Open Scope R_scope.\n\n  (* The memory cell in which the boolean output is written by DynWin *)\n  Definition dynwin_y_offset := 0%nat.\n\n  (** Constraints on physical parameters **)\n  (* Obstacle velocity constraint *)\n  (* 0 <= V <= 20 (m/s) (<= 72 Kmh) *)\n  Definition V_constr := (b64_0, b64_20).\n  (* 1 < b <= 6 (m/s^2)\n     https://copradar.com/chapts/references/acceleration.html *)\n  Definition b_constr := (b64_1, b64_6).\n  (* 0 <= A <= 5 (m/s^2)\n     https://hypertextbook.com/facts/2001/MeredithBarricella.shtml *)\n  Definition A_constr := (b64_0, b64_5).\n  Definition e_constr := (b64_0_01, b64_0_1). (* 1/100 <= e <= 1/10. 10-100 Hz *)\n  (* Constraints for obstacle and robot coordinates.\n     Our robot operates on cartesian grid ~10x10 Km *)\n  Definition x_constr := (b64_opp b64_5000, b64_5000).\n  Definition y_constr := (b64_opp b64_5000, b64_5000).\n  (* Robot velocity constraint *)\n  Definition v_constr := (b64_0, b64_20).\n\n  (*\n    \"a\" layout:\n     a0 = (A/b + 1.0) * ((A/2.0)*e*e + e*V)\n     a1 = V/b + e*(A/b+1.0)\n     a2 = 1.0/(2.0*b)\n\n    \"x\" layout:\n    0. robot velocity\n    1. robot position (X)\n    2. robot position (Y)\n    3. obstacle position (X)\n    4. obstacle position (Y)\n   *)\n  Definition make_a64 (V64 b64 A64 e64 : binary64) : FHCOL.mem_block :=\n    (* DHCOL (and therefore CType) has no division *)\n    let FT_div := b64_div FT_Rounding in\n\n    let a0 :=\n      MFloat64asCT.CTypeMult\n        (MFloat64asCT.CTypePlus (FT_div A64 b64) b64_1)\n        (MFloat64asCT.CTypePlus\n           (MFloat64asCT.CTypeMult (MFloat64asCT.CTypeMult (FT_div A64 b64_2) e64) e64)\n           (MFloat64asCT.CTypeMult e64 V64))\n    in\n    let a1 :=\n      (MFloat64asCT.CTypePlus\n         (FT_div V64 b64)\n         (MFloat64asCT.CTypeMult\n            e64\n            (MFloat64asCT.CTypePlus (FT_div A64 b64) b64_1)))\n    in\n    let a2 :=\n      FT_div\n        b64_1\n        (MFloat64asCT.CTypeMult b64_2 b64)\n    in\n    FHCOLEval.mem_add 0%nat a0\n      (FHCOLEval.mem_add 1%nat a1\n         (FHCOLEval.mem_add 2%nat a2\n            (FHCOLEval.mem_empty))).\n\n  Definition make_x64 (r_v_64 r_x_64 r_y_64 o_x_64 o_y_64 : binary64) : FHCOL.mem_block :=\n    FHCOLEval.mem_add 0%nat r_v_64\n      (FHCOLEval.mem_add 1%nat r_x_64\n        (FHCOLEval.mem_add 2%nat r_y_64\n          (FHCOLEval.mem_add 3%nat o_x_64\n            (FHCOLEval.mem_add 4%nat o_y_64\n              (FHCOLEval.mem_empty))))).\n\n  (* Constraints on input memory blocks which we assume to prove\n     numerical stability of FHCOL DynWin code.  Here, we enforce some\n     reasonable numerical bounds on dynwin physical parameters.  *)\n  Definition DynWinInConstr (a : RHCOLEval.mem_block) (x : RHCOLEval.mem_block): Prop\n    :=\n    exists V64 (* max obstacle speed *)\n      b64 (* max braking *)\n      A64 (* max accel *)\n      e64 (* sampling period *)\n      r_v_64\n      r_x_64\n      r_y_64\n      o_x_64\n      o_y_64,\n\n      in_range_64 V_constr V64\n      /\\ in_range_64 b_constr b64\n      /\\ in_range_64 A_constr A64\n      /\\ in_range_64 e_constr e64\n      /\\ RHCOLtoFHCOL.heq_mem_block () RF_CHE\n          a (make_a64 V64 b64 A64 e64)\n      /\\ in_range_64 v_constr r_v_64\n      /\\ in_range_64 x_constr r_x_64\n      /\\ in_range_64 y_constr r_y_64\n      /\\ in_range_64 x_constr o_x_64\n      /\\ in_range_64 y_constr o_y_64\n      /\\ RHCOLtoFHCOL.heq_mem_block () RF_CHE\n          x (make_x64 r_v_64 r_x_64 r_y_64 o_x_64 o_y_64).\n\n  (* Parametric relation between RHCOL and FHCOL coumputation results  *)\n  (*\n    Requisite relation:\n\n     Binary64 out | Real out ||  Status\n     -------------------------------------\n     Safe         | Safe     ||  OK        (agreeing)\n     Safe         | Unsafe   ||  FORBIDDEN (dangerous in reality, \"safe\" in 64)\n     Unsafe       | Safe     ||  OK        (overly cautious)\n     Unsafe       | Unsafe   ||  OK        (agreeing)\n\n     in boolean terms, given \"Safe\" = true, \"Unsafe\" = false,\n     this is\n\n     [Binary64 out] => [Real out]\n\n     (alternatively \"Real = safe \\/ Binary64 = unsafe\")\n   *)\n  Definition DynWinOutRel\n             (a_r:RHCOLEval.mem_block)\n             (x_r:RHCOLEval.mem_block)\n             (y_r:RHCOLEval.mem_block)\n             (y_64:FHCOLEval.mem_block): Prop\n    :=\n    hopt_r (flip CType_impl)\n      (RHCOLEval.mem_lookup dynwin_y_offset y_r)\n      (FHCOLEval.mem_lookup dynwin_y_offset y_64).\n\n  Global Instance DynWinOutRel_Proper :\n    Proper ((=) ==> (=) ==> (=) ==> (=) ==> (iff)) DynWinOutRel.\n  Proof.\n    intros a1 a2 A x1 x2 X y1 y2 Y y64_1 y64_2 Y64.\n    unfold DynWinOutRel.\n    clear - Y Y64.\n    specialize (Y dynwin_y_offset).\n    specialize (Y64 dynwin_y_offset).\n    rewrite Y, Y64.\n    tauto.\n  Qed.\n\nEnd RHCOL_to_FHCOL_bounds.\n\nSection Gappa.\n\n  Open Scope Float64asCT_scope.\n\n  Hint Rewrite\n    b64_plus_to_R b64_minus_to_R\n    b64_mult_to_R b64_div_to_R\n    b64_max_to_R b64_abs_to_R\n\n    b64_plus_finite b64_minus_finite\n    b64_mult_finite b64_div_finite\n    b64_max_finite b64_abs_finite\n    : rewrite_to_R.\n\n  Ltac not_known A :=\n    match goal with\n    | H : A |- _ => fail 1 \"Assertion\" A \"already known in\" H\n    | _ => idtac\n    end.\n  \n  Ltac assert_if_new_as Name H :=\n    not_known H; assert (Name : H).\n\n  Ltac known_finite x :=\n    match goal with\n    | [H : is_finite _ _ x ≡ true |- _] => idtac\n    | _ => fail 1\n    end.\n\n  Ltac rewrite_to_R :=\n    autounfold with unfold_FCT;\n    autorewrite with rewrite_to_R;\n    try assumption.\n    \n  Ltac gappa_form :=\n    try apply bpow_lt_to_le;\n    repeat (cbv [Defs.F2R IZR IPR IPR_2 Z.pow_pos Pos.iter] in *;\n            simpl in *).\n\n  Ltac simple_R :=\n    match goal with\n    | |- B2R _ _ (B754_finite _ _ _ _ _ _) ≢ 0%R => cbv; lra\n    end.\n\n  Ltac gappa_crush :=\n    rewrite_to_R;\n    autounfold with sugar64 F64_const in *;\n    try simple_R;\n    gappa_form;\n    gappa.\n\n  (* Extra safe match to avoid unnecessarily calling the heavy [gappa_crush] *)\n  Ltac solve_with_gappa :=\n    match goal with\n    | |- no_overflow64 _ => gappa_crush\n    | |- _ ≢ 0%R => gappa_crush\n    | |- context [Rmax] => unfold Rmax; break_match_goal; gappa_crush\n    end.\n\n  Ltac crush_floats :=\n    first\n      [ assumption\n      | reflexivity\n      | eapply in_range_finite; eassumption\n      | eapply in_range_l_finite; eassumption\n      | rewrite_to_R; solve_with_gappa].\n\n  Ltac assert_finite :=\n    let FIN := fresh \"FIN\" in\n    match goal with\n    | [H : in_range_64 _ ?x |- _] =>\n        assert_if_new_as FIN (is_finite _ _ x ≡ true)\n    | [H : in_range_64_l _ ?x |- _] =>\n        assert_if_new_as FIN (is_finite _ _ x ≡ true)\n    | [H : context [?x ⊞ ?y] |- _] =>\n        known_finite x; known_finite y;\n        assert_if_new_as FIN (is_finite _ _ (x ⊞ y) ≡ true)\n    | [H : context [?x ⊟ ?y] |- _] =>\n        known_finite x; known_finite y;\n        assert_if_new_as FIN (is_finite _ _ (x ⊟ y) ≡ true)\n    | [H : context [?x ⊠ ?y] |- _] =>\n        known_finite x; known_finite y;\n        assert_if_new_as FIN (is_finite _ _ (x ⊠ y) ≡ true)\n    | [H : context [?x ⧄ ?y] |- _] =>\n        known_finite x; known_finite y;\n        assert_if_new_as FIN (is_finite _ _ (x ⧄ y) ≡ true)\n    | [H : context [fabs ?x] |- _] =>\n        known_finite x;\n        assert_if_new_as FIN (is_finite _ _ (fabs x) ≡ true)\n    | [H : context [fmax ?x ?y] |- _] =>\n        known_finite x; known_finite y;\n        assert_if_new_as FIN (is_finite _ _ (fmax x y) ≡ true)\n    end.\n\n  Ltac assert_no_overflow :=\n    let NOVF := fresh \"NOVF\" in\n    match goal with\n    | [H : context [?x ⊞ ?y] |- _] =>\n        known_finite x; known_finite y;\n        assert_if_new_as NOVF\n          (no_overflow64 (◻ (B64R x + B64R y)))\n    | [H : context [?x ⊟ ?y] |- _] =>\n        known_finite x; known_finite y;\n        assert_if_new_as NOVF\n          (no_overflow64 (◻ (B64R x - B64R y)))\n    | [H : context [?x ⊠ ?y] |- _] =>\n        known_finite x; known_finite y;\n        assert_if_new_as NOVF\n          (no_overflow64 (◻ (B64R x * B64R y)))\n    | [H : context [?x ⧄ ?y] |- _] =>\n        known_finite x; known_finite y;\n        assert_if_new_as NOVF\n          (no_overflow64 (◻ (B64R x / B64R y)))\n    end.\n\n  Ltac assert_divisor_nz :=\n    let NZ := fresh \"NZ\" in\n    match goal with\n    | [H : context [?x ⧄ ?y] |- _] =>\n        known_finite y;\n        assert_if_new_as NZ (B64R y ≢ 0%R)\n    end.\n\n  Ltac assert_next :=\n    first [assert_divisor_nz | assert_no_overflow | assert_finite].\n\n  Open Scope R_scope.\n\n  Lemma DynWin_arith\n    (e a b vr vo a0 a1 a2 rx ry ox oy cheb64 poly64 cheb poly : R)\n    (E : B64R b64_0_01 <= e <= B64R b64_0_1)\n    (A : B64R b64_0 <= a <= B64R b64_5)\n    (B : B64R b64_1 <= b <= B64R b64_6)\n    (VR : B64R b64_0 <= vr <= B64R b64_20)\n    (VO : B64R b64_0 <= vo <= B64R b64_20)\n    (RX : B64R (b64_opp b64_5000) <= rx <= B64R b64_5000)\n    (RY : B64R (b64_opp b64_5000) <= ry <= B64R b64_5000)\n    (OX : B64R (b64_opp b64_5000) <= ox <= B64R b64_5000)\n    (OY : B64R (b64_opp b64_5000) <= oy <= B64R b64_5000)\n    (A0 : a0 ≡ ◻ (◻ (◻ (a / b) + B64R b64_1) *\n                    ◻ (◻ (◻ (◻ (a / B64R b64_2) * e) * e) + ◻ (e * vo))))\n    (A1 : a1 ≡ ◻ (◻ (vo / b) + ◻ (e * ◻ (◻ (a / b) + B64R b64_1))))\n    (A2 : a2 ≡ ◻ (B64R b64_1 / ◻ (B64R b64_2 * b)))\n    (CHEB64 : cheb64 ≡ Rmax (Rabs ◻ (rx - ox)) (Rabs ◻ (ry - oy)))\n    (POLY64 : poly64 ≡ ◻ (◻ (◻ (B64R b64_0 + ◻ (B64R b64_1 * a0)) +\n                               ◻ (◻ (B64R b64_1 * vr) * a1)) +\n                            ◻ (◻ (◻ (B64R b64_1 * vr) * vr) * a2)))\n    (CHEB : cheb ≡ Rmax (Rabs (ox - rx)) (Rabs (oy - ry)))\n    (* TODO: this ([CU]) upper bound shouldn't be necessary here *)\n    (CU : no_overflow64 ◻ (cheb64 - poly64)) \n    (POLY : poly ≡ a0 + vr * a1 + vr * vr * a2)\n    :\n    B64R compare_epsilon < ◻ (cheb64 - poly64) -> (poly < cheb)%R.\n  Proof.\n    intros LT64.\n    (* 1b-40 *)\n    pose (cheb_delta := B64R (\n            B754_finite 53 1024 false 4503599627370496 (-92)\n              (binary_float_of_bits_aux_correct 52 11 eq_refl eq_refl eq_refl\n                 4427038433705197568))).\n\n    assert (CHEB_DELTA : - cheb_delta <= cheb64 - cheb <= cheb_delta).\n    {\n      clear - RX RY OX OY CHEB CHEB64.\n      subst.\n\n      replace cheb_delta with (Rmax cheb_delta cheb_delta)\n        by (unfold Rmax; break_if; reflexivity).\n\n      eapply Rmax_no_error.\n      -\n        replace (Rabs (ox - rx)) with (Rabs (rx - ox))\n          by (unfold Rabs; repeat break_if; lra).\n        eapply Rabs_no_error.\n        subst cheb_delta.\n        gappa_crush.\n      -\n        replace (Rabs (oy - ry)) with (Rabs (ry - oy))\n          by (unfold Rabs; repeat break_if; lra).\n        eapply Rabs_no_error.\n        subst cheb_delta.\n        gappa_crush.\n    }\n    clear CHEB CHEB64.\n\n    pose (poly_delta :=\n            B64R (B754_finite 53 1024 false 5665758678918104 (-94)\n                    (binary_float_of_bits_aux_correct 52 11 eq_refl eq_refl eq_refl\n                       4419193393502004184))).\n\n    assert (POLY_DELTA : - poly_delta <= poly64 - poly <= poly_delta).\n    {\n      clear LT64 CHEB_DELTA.\n      subst cheb_delta poly_delta.\n      replace (B64R b64_0) with 0 in * by reflexivity.\n      replace (B64R b64_1) with 1 in * by (cbv; lra).\n      repeat match goal with\n             | [H : context [0 + ?x] |- _] =>\n                 replace (0 + x) with x in * by lra\n             | [H : context [1 * ?x] |- _] =>\n                 replace (1 * x) with x in * by lra\n             end.\n      \n      gappa_crush.\n    }\n\n    clear - LT64 CU CHEB_DELTA POLY_DELTA.\n    subst cheb_delta poly_delta.\n    apply RIneq.Rlt_le in LT64.\n    enough (E : B64R float64_subnormal_eps <=\n                  cheb - poly\n                <= 2 * Raux.bpow radix2 1024)\n      by (cbv in E; lra).\n\n    assert (BND64 : B64R compare_epsilon <= ◻ (cheb64 - poly64) <= Raux.bpow radix2 1024).\n    {\n      clear - CU LT64.\n      split; [assumption |].\n      unfold no_overflow64, Rabs in *.\n      break_if; lra.\n    }\n    clear CU LT64.\n\n    gappa_crush.\n  Qed.\n\n  Close Scope R_scope.\n  \n  Lemma DynWin_numerical_stability\n    (V64 b64 A64 e64 v64 rx64 ry64 ox64 oy64 : binary64)\n    (fa0 fa1 fa2 fx0 fx1 fx2 fx3 fx4 : binary64)\n    (VC  : in_range_64 V_constr V64)\n    (bC  : in_range_64 b_constr b64)\n    (AC  : in_range_64 A_constr A64)\n    (eC  : in_range_64 e_constr e64)\n    (vC  : in_range_64 v_constr v64)\n    (rxC : in_range_64 x_constr rx64)\n    (ryC : in_range_64 y_constr ry64)\n    (oxC : in_range_64 x_constr ox64)\n    (oyC : in_range_64 y_constr oy64)\n\n    (FFA0 : is_finite _ _ fa0 ≡ true)\n    (FFA1 : is_finite _ _ fa1 ≡ true)\n    (FFA2 : is_finite _ _ fa2 ≡ true)\n    (FFX0 : is_finite _ _ fx0 ≡ true)\n    (FFX1 : is_finite _ _ fx1 ≡ true)\n    (FFX2 : is_finite _ _ fx2 ≡ true)\n    (FFX3 : is_finite _ _ fx3 ≡ true)\n    (FFX4 : is_finite _ _ fx4 ≡ true)\n\n    (FX0 : B64R fx0 ≡ B64R v64)\n    (FX1 : B64R fx1 ≡ B64R rx64)\n    (FX2 : B64R fx2 ≡ B64R ry64)\n    (FX3 : B64R fx3 ≡ B64R ox64)\n    (FX4 : B64R fx4 ≡ B64R oy64)\n\n    (FA0 : B64R fa0\n           ≡ B64R ((A64 ⧄ b64 ⊞ b64_1) ⊠ ((A64 ⧄ b64_2 ⊠ e64) ⊠ e64 ⊞ e64 ⊠ V64)))\n    (FA1 : B64R fa1 ≡ B64R (V64 ⧄ b64 ⊞ e64 ⊠ (A64 ⧄ b64 ⊞ b64_1)))\n    (FA2 : B64R fa2 ≡ B64R (b64_1 ⧄ (b64_2 ⊠ b64)))\n\n    (F : safe_lt64 FT_Rounding compare_epsilon\n           (((0.0 ⊞ 1.0 ⊠ fa0) ⊞ (1.0 ⊠ fx0) ⊠ fa1) ⊞ ((1.0 ⊠ fx0) ⊠ fx0) ⊠ fa2)\n           (fmax (fmax 0.0 (fabs (fx1 ⊟ fx3))) (fabs (fx2 ⊟ fx4))))\n      :\n      (MRasCT.CTypePlus\n         (MRasCT.CTypePlus\n            (MRasCT.CTypePlus MRasCT.CTypeZero\n               (MRasCT.CTypeMult MRasCT.CTypeOne (B64R fa0)))\n            (MRasCT.CTypeMult (MRasCT.CTypeMult MRasCT.CTypeOne (B64R fx0)) (B64R fa1)))\n         (MRasCT.CTypeMult\n            (MRasCT.CTypeMult (MRasCT.CTypeMult MRasCT.CTypeOne (B64R fx0)) (B64R fx0))\n            (B64R fa2)) <\n         MRasCT.CTypeMax\n           (MRasCT.CTypeMax MRasCT.CTypeZero\n              (MRasCT.CTypeAbs (MRasCT.CTypeSub (B64R fx1) (B64R fx3))))\n           (MRasCT.CTypeAbs (MRasCT.CTypeSub (B64R fx2) (B64R fx4))))%R.\n  Proof.\n    rewrite !fmaxZeroAbs, !R_MaxZeroAbs, !R_PlusZeroLeft, !R_MultOneLeft in *.\n\n    autounfold with unfold_RCT.\n    unfold plus, negate, CarrierAneg, Basics.compose.\n    replace (- B64R fx1 + B64R fx3)%R\n      with (B64R fx3 - B64R fx1)%R\n      by lra.\n    replace (- B64R fx2 + B64R fx4)%R\n      with (B64R fx4 - B64R fx2)%R\n      by lra.\n\n    unfold safe_lt64 in *.\n    fold MFloat64asCT.CTypeSub in *.\n\n    repeat\n      (let RAN := fresh \"RAN\" in\n       match goal with\n       | [H : in_range_64 ?constr ?x |- _] =>\n           assert_if_new_as RAN\n             (B64R (fst constr) <= B64R x <= B64R (snd constr))%R\n       | [H : in_range_64_l ?constr ?x |- _] =>\n           assert_if_new_as RAN\n             (B64R (fst constr) < B64R x <= B64R (snd constr))%R\n       end;\n      [first [eapply in_range_64_to_R | eapply in_range_64_l_to_R];\n       try reflexivity; eassumption\n      |]).\n    repeat match goal with\n           | [H : context[fst ?x] |- _] => unfold x in *\n           | [H : context[snd ?x] |- _] => unfold x in *\n           end;\n      cbn [fst snd] in *.\n\n    assert (FIN : is_finite _ _ b64_1 ≡ true) by reflexivity.\n    assert (FIN0 : is_finite _ _ b64_2 ≡ true) by reflexivity.\n    assert (FIN1 : is_finite _ _ 0.0 ≡ true) by reflexivity.\n    assert (FIN2 : is_finite _ _ 1.0 ≡ true) by reflexivity.\n    assert (FIN3 : is_finite _ _ compare_epsilon ≡ true) by reflexivity.\n\n    (* a hack to avoid matching *)\n    pose (hidden_finite := is_finite).\n    replace is_finite with hidden_finite in FFA0, FFA1, FFA2 by reflexivity.\n\n    repeat (assert_next; [shelve |]).\n\n    subst hidden_finite.\n\n    autounfold with unfold_FCT in FA0, FA1, FA2;\n      autorewrite with rewrite_to_R in FA0, FA1, FA2;\n      try assumption.\n\n    repeat (assert_next; [shelve |]).\n\n    apply lt64_correct in F; try assumption.\n\n    pose proof NOVF22 as UF.\n    autounfold with unfold_FCT in F;\n      autorewrite with rewrite_to_R in F;\n      try assumption.\n\n    autounfold with unfold_FCT in UF;\n      autorewrite with rewrite_to_R in UF;\n      try assumption.\n\n    rewrite !FX0, !FX1, !FX2, !FX3, !FX4 in *.\n    clear - FA0 FA1 FA2 UF F RAN RAN0 RAN1 RAN2 RAN3 RAN4 RAN5 RAN6 RAN7.\n\n    generalize dependent (B64R v64); intros vr ? VR.\n    generalize dependent (B64R e64); intros e ? ? E.\n    generalize dependent (B64R A64); intros a A ? ?.\n    generalize dependent (B64R b64); intros b ? B ?.\n    generalize dependent (B64R V64); intros vo VO ? ?.\n\n    generalize dependent (B64R fa0); intros a0 ? A0.\n    generalize dependent (B64R fa1); intros a1 A1 ?.\n    generalize dependent (B64R fa2); intros a2 A2 ?.\n\n    generalize dependent (B64R rx64); intros rx RX ?.\n    generalize dependent (B64R ry64); intros ry RY ?.\n    generalize dependent (B64R ox64); intros ox OX ?.\n    generalize dependent (B64R oy64); intros oy OY ?.\n    intros UF.\n\n    repeat match goal with\n           | [f : binary64 |- _] => clear f\n           end.\n\n    rewrite RCT_max_Rmax.\n    setoid_rewrite RCT_abs_Rabs.\n\n    remember (Rmax (Rabs (ox - rx)) (Rabs (oy - ry))) as cheb eqn:CHEB.\n    remember (Rmax (Rabs ◻ (rx - ox)) (Rabs ◻ (ry - oy))) as cheb64 eqn:CHEB64.\n    remember (a0 + vr * a1 + vr * vr * a2)%R as poly eqn:POLY.\n    remember (◻ (◻ (◻ (B64R b64_0 + ◻ (B64R b64_1 * a0)) +\n                      ◻ (◻ (B64R b64_1 * vr) * a1)) +\n                   ◻ (◻ (◻ (B64R b64_1 * vr) * vr) * a2)))\n               as poly64 eqn:POLY64.\n\n    do 15 match goal with | [r : R |- _] => move r at top end.\n    move F at bottom.\n    move A2 after OY.\n    move A1 after OY.\n    move A0 after OY.\n\n    eapply DynWin_arith.\n    1-3: eassumption.\n    eapply VR.\n    eapply VO.\n    eapply RX.\n    eapply RY.\n    eapply OX.\n    eapply OY.\n    all: eassumption.\n\n    (* This would be nicely suitable for [par:] instead of [all:],\n       but that encounters an anomaly *)\n    Unshelve.\n    all: crush_floats.\n  Qed.\n\nEnd Gappa.\n\nSection DynWin_Symbolic.\n\n  Variable ar : vector R 3.\n  Variable xr : vector R dynwin_i.\n\n  Fact lt0_3 : 0 < 3. repeat constructor. Qed.\n  Fact lt1_3 : 1 < 3. repeat constructor. Qed.\n  Fact lt2_3 : 2 < 3. repeat constructor. Qed.\n\n  Fact lt0_5 : 0 < 5. repeat constructor. Qed.\n  Fact lt1_5 : 1 < 5. repeat constructor. Qed.\n  Fact lt2_5 : 2 < 5. repeat constructor. Qed.\n  Fact lt3_5 : 3 < 5. repeat constructor. Qed.\n  Fact lt4_5 : 4 < 5. repeat constructor. Qed.\n\n  Let R_env :=\n    [Vnth ar lt0_3;\n     Vnth ar lt1_3;\n     Vnth ar lt2_3;\n\n     Vnth xr lt0_5;\n     Vnth xr lt1_5;\n     Vnth xr lt2_5;\n     Vnth xr lt3_5;\n     Vnth xr lt4_5].\n\n  Let r_imemory := dynwin_R_memory ar xr.\n\n  Definition dynwin_SR_σ :=\n    [(SRHCOLEval.DSHPtrVal dynwin_a_addr 3, false);\n     (SRHCOLEval.DSHPtrVal dynwin_y_addr 1, false);\n     (SRHCOLEval.DSHPtrVal dynwin_x_addr 5, false)].\n\n  Definition R_a_mb :=\n    SRHCOLEval.mem_add 0 (SVar 0)\n      (SRHCOLEval.mem_add 1 (SVar 1)\n         (SRHCOLEval.mem_add 2 (SVar 2)\n            SRHCOLEval.mem_empty)).\n\n  Definition R_x_mb :=\n    SRHCOLEval.mem_add 0 (SVar 3)\n      (SRHCOLEval.mem_add 1 (SVar 4)\n         (SRHCOLEval.mem_add 2 (SVar 5)\n            (SRHCOLEval.mem_add 3 (SVar 6)\n               (SRHCOLEval.mem_add 4 (SVar 7)\n                  SRHCOLEval.mem_empty)))).\n\n  Definition dynwin_SR_memory :=\n    SRHCOLEval.memory_set\n      (SRHCOLEval.memory_set\n         (SRHCOLEval.memory_set SRHCOLEval.memory_empty\n            dynwin_a_addr R_a_mb)\n         dynwin_x_addr R_x_mb)\n      dynwin_y_addr SRHCOLEval.mem_empty.\n\n  Definition i1 := {| Int64asNT.Int64.intval := 1;\n                     Int64asNT.Int64.intrange := conj eq_refl eq_refl |}.\n  Definition i3 := {| Int64asNT.Int64.intval := 3;\n                     Int64asNT.Int64.intrange := conj eq_refl eq_refl |}.\n  Definition i5 := {| Int64asNT.Int64.intval := 5;\n                     Int64asNT.Int64.intrange := conj eq_refl eq_refl |}.\n\n  Definition dynwin_SF_σ :=\n    [(SFHCOLEval.DSHPtrVal dynwin_a_addr i3, false);\n     (SFHCOLEval.DSHPtrVal dynwin_y_addr i1, false);\n     (SFHCOLEval.DSHPtrVal dynwin_x_addr i5, false)].\n\n  Definition Fmemory_lookup_deep_unsafe\n    (m : FHCOLEval.memory) '(i, off) : MFloat64asCT.t :=\n    match FHCOLEval.memory_lookup m i with\n    | Some mb => match FHCOLEval.mem_lookup off mb with\n                | Some v => v\n                | _ => MFloat64asCT.CTypeZero\n                end\n    | _ => MFloat64asCT.CTypeZero\n    end.\n\n  Definition Float_env m :=\n    List.map (Fmemory_lookup_deep_unsafe m)\n      [(0,0); (0,1); (0,2);\n       (2,0); (2,1); (2,2); (2,3); (2,4)].\n\n  (* Convenience wrapper over [RHCOLtoSRHCOL_semantic_preservation] *)\n  Lemma RHCOL_to_symbolic_lookup\n    (r_σ : RHCOLEval.evalContext)\n    (r_op : RHCOLEval.DSHOperator)\n    (r_m r_m' : RHCOLEval.memory)\n    (r_mb : RHCOLEval.mem_block)\n\n    (sr_σ : SRHCOLEval.evalContext)\n    (sr_op : SRHCOLEval.DSHOperator)\n    (sr_m : SRHCOLEval.memory)\n\n    (i off : nat)\n    (env : RealEnv)\n    :\n    RHCOLtoSRHCOL.heq_evalContext env RSR_NHE RSR_CHE r_σ sr_σ ->\n    RHCOLtoSRHCOL.heq_memory env RSR_CHE r_m sr_m ->\n\n    RHCOLtoSRHCOL.translate r_op = inr sr_op ->\n\n    RHCOLEval.evalDSHOperator r_σ r_op r_m (RHCOLEval.estimateFuel r_op)\n    = Some (inr r_m') ->\n    RHCOLEval.memory_lookup r_m' i = Some r_mb ->\n\n    RHCOLEval.mem_lookup off r_mb =\n      match SRHCOLEval.evalDSHOperator sr_σ sr_op sr_m\n              (SRHCOLEval.estimateFuel sr_op) with\n      | Some (inr sr_m') =>\n          match SRHCOLEval.memory_lookup sr_m' i with\n          | Some sr_mb =>\n              match SRHCOLEval.mem_lookup off sr_mb with\n              | Some sexpr =>\n                  evalRealSExpr env sexpr\n              | _ => None\n              end\n          | _ => None\n          end\n      | _ => None\n      end.\n  Proof.\n    intros Σ M OP RE MB.\n    pose proof RHCOLtoSRHCOL_semantic_preservation\n      r_op sr_op\n      r_σ sr_σ\n      r_m sr_m\n      env\n      as SR_EQUIV.\n    full_autospecialize SR_EQUIV; try assumption.\n\n    apply RHCOLtoSRHCOL.translation_syntax_always_correct;\n      [apply RSR_NTP | assumption ].\n\n    (* poor man's setoid_rewrite *)\n    eapply hopt_r_proper in SR_EQUIV;\n      [\n      | eapply herr_c_proper, RHCOLtoSRHCOL.heq_memory_proper\n      | now rewrite RE\n      | reflexivity ].\n\n    invc SR_EQUIV.\n    invc H1.\n    specialize (H2 i).\n\n    eapply hopt_r_proper in H2;\n      [\n      | eapply RHCOLtoSRHCOL.heq_mem_block_proper\n      | now rewrite MB\n      | reflexivity ].\n\n    invc H2.\n    specialize (H3 off).\n\n    invc H3.\n    reflexivity.\n    rewrite H4.\n    reflexivity.\n  Qed.\n\n  (* TODO: this is exactly the same as the above *)\n  Lemma FHCOL_to_symbolic_lookup\n    (r_σ : FHCOLEval.evalContext)\n    (r_op : FHCOLEval.DSHOperator)\n    (r_m r_m' : FHCOLEval.memory)\n    (r_mb : FHCOLEval.mem_block)\n\n    (sr_σ : SFHCOLEval.evalContext)\n    (sr_op : SFHCOLEval.DSHOperator)\n    (sr_m : SFHCOLEval.memory)\n\n    (i off : nat)\n    (env : FloatEnv)\n    :\n    FHCOLtoSFHCOL.heq_evalContext env FSF_NHE FSF_CHE r_σ sr_σ ->\n    FHCOLtoSFHCOL.heq_memory env FSF_CHE r_m sr_m ->\n\n    FHCOLtoSFHCOL.translate r_op = inr sr_op ->\n\n    FHCOLEval.evalDSHOperator r_σ r_op r_m (FHCOLEval.estimateFuel r_op)\n    = Some (inr r_m') ->\n    FHCOLEval.memory_lookup r_m' i = Some r_mb ->\n\n    FHCOLEval.mem_lookup off r_mb =\n      match SFHCOLEval.evalDSHOperator sr_σ sr_op sr_m\n              (SFHCOLEval.estimateFuel sr_op) with\n      | Some (inr sr_m') =>\n          match SFHCOLEval.memory_lookup sr_m' i with\n          | Some sr_mb =>\n              match SFHCOLEval.mem_lookup off sr_mb with\n              | Some sexpr =>\n                  evalFloatSExpr env sexpr\n              | _ => None\n              end\n          | _ => None\n          end\n      | _ => None\n      end.\n  Proof.\n    intros Σ M OP RE MB.\n    pose proof FHCOLtoSFHCOL_semantic_preservation\n      r_op sr_op\n      r_σ sr_σ\n      r_m sr_m\n      env\n      as SF_EQUIV.\n    full_autospecialize SF_EQUIV; try assumption.\n\n    apply FHCOLtoSFHCOL.translation_syntax_always_correct;\n      [apply FSF_NTP | assumption ].\n\n    (* poor man's setoid_rewrite *)\n    eapply hopt_r_proper in SF_EQUIV;\n      [\n      | eapply herr_c_proper, FHCOLtoSFHCOL.heq_memory_proper\n      | now rewrite RE\n      | reflexivity ].\n\n    invc SF_EQUIV.\n    invc H1.\n    specialize (H2 i).\n\n    eapply hopt_r_proper in H2;\n      [\n      | eapply FHCOLtoSFHCOL.heq_mem_block_proper\n      | now rewrite MB\n      | reflexivity ].\n\n    invc H2.\n    specialize (H3 off).\n\n    invc H3.\n    reflexivity.\n    rewrite H4.\n    reflexivity.\n  Qed.\n\n  (* For some reason the lhs of this\n     doesn't [cbn/cbv/etc], but easily [Compute]s *)\n  Fact DynWin_Symbolic_out :\n    match\n      evalDSHOperator dynwin_SF_σ DynWin_SFHCOL_hard dynwin_SR_memory\n        (estimateFuel DynWin_SFHCOL_hard)\n    with\n    | Some (inr sr_m') =>\n        match memory_lookup sr_m' dynwin_y_addr with\n        | Some sr_mb =>\n            match mem_lookup dynwin_y_offset sr_mb with\n            | Some sexpr => Some sexpr\n            | None => None\n            end\n        | None => None\n        end\n    | _ => None\n    end\n    ≡ Some\n        (SZLess\n           (SPlus\n              (SPlus (SPlus SConstZero (SMult SConstOne (SVar 0)))\n                 (SMult (SMult SConstOne (SVar 3)) (SVar 1)))\n              (SMult (SMult (SMult SConstOne (SVar 3)) (SVar 3)) (SVar 2)))\n           (SMax (SMax SConstZero (SAbs (SSub (SVar 4) (SVar 6))))\n              (SAbs (SSub (SVar 5) (SVar 7))))).\n  Proof.\n    reflexivity.\n  Qed.\n\n  Lemma RHCOL_to_FHCOL_numerical_correct\n    (r_omemory : RHCOLEval.memory)\n    (a_rmem x_rmem y_rmem : RHCOLEval.mem_block)\n    (f_imemory f_omemory : FHCOLEval.memory)\n    (f_iσ : FHCOLEval.evalContext)\n    (y_fmem : FHCOLEval.mem_block)\n    (DynWin_FHCOL : FHCOLEval.DSHOperator)\n    \n    (R_EVAL : RHCOLEval.evalDSHOperator dynwin_R_σ DynWin_RHCOL r_imemory\n                (RHCOLEval.estimateFuel DynWin_RHCOL)\n              = Some (inr r_omemory))\n    (A_RMEM : RHCOLEval.memory_lookup r_imemory dynwin_a_addr = Some a_rmem)\n    (X_RMEM : RHCOLEval.memory_lookup r_imemory dynwin_x_addr = Some x_rmem)\n    (Y_RMEM : RHCOLEval.memory_lookup r_omemory dynwin_y_addr = Some y_rmem)\n    \n    (F_EVAL : FHCOLEval.evalDSHOperator f_iσ DynWin_FHCOL f_imemory\n                (FHCOLEval.estimateFuel DynWin_FHCOL)\n              = Some (inr f_omemory))\n    (Y_FMEM : FHCOLEval.memory_lookup f_omemory dynwin_y_addr = Some y_fmem)\n    \n    (TRANSLATE_OP : RHCOLtoFHCOL.translate DynWin_RHCOL = inr DynWin_FHCOL)\n    (RF_IM : RHCOLtoFHCOL.heq_memory () RF_CHE r_imemory f_imemory)\n    (RF_IΣ : RHCOLtoFHCOL.heq_evalContext () RF_NHE RF_CHE dynwin_R_σ f_iσ)\n    :\n    DynWinInConstr a_rmem x_rmem ->\n    DynWinOutRel a_rmem x_rmem y_rmem y_fmem.\n  Proof.\n    intros INCONSTR.\n    unfold DynWinOutRel.\n\n    (* poor man's [setoid_rewrite RHCOL_to_symbolic_lookup] *)\n    eapply hopt_r_proper;\n      [typeclasses eauto | | reflexivity |].\n    {\n      rewrite RHCOL_to_symbolic_lookup with\n        (sr_σ := dynwin_SR_σ)\n        (sr_m := dynwin_SR_memory)\n        (i := dynwin_y_addr)\n        (off := dynwin_y_offset)\n        (env := R_env).\n      5,6: eassumption.\n      4: {\n        rewrite DynWin_RHCOL_hard_OK, DynWin_SRHCOL_hard_OK.\n        reflexivity.\n      }\n        \n      reflexivity.\n\n      -\n        repeat constructor.\n      -\n        intros k.\n        do 3 try destruct k.\n        + (* a *)\n          unfold r_imemory.\n          cbn - [ctvector_to_mem_block].\n          constructor.\n          intros k.\n          do 3 try destruct k.\n          1-3: erewrite mem_lookup_ctvector_to_mem_block.\n          1-3: now constructor.\n          cbn - [ctvector_to_mem_block].\n          rewrite ctvector_to_mem_block_key_oob.\n          constructor.\n          lia.\n        + (* y *)\n          unfold r_imemory.\n          cbn - [ctvector_to_mem_block].\n          repeat constructor.\n        + (* x *)\n          unfold r_imemory.\n          cbn - [ctvector_to_mem_block].\n          constructor.\n          intros k.\n          do 5 try destruct k.\n          1-5: erewrite mem_lookup_ctvector_to_mem_block.\n          1-5: now constructor.\n          cbn - [ctvector_to_mem_block].\n          rewrite ctvector_to_mem_block_key_oob.\n          constructor.\n          lia.\n        +\n          constructor.\n    }\n\n    cbv - [FHCOLEval.mem_lookup CType_impl evalRealSExpr R_env].\n    eapply hopt_r_proper;\n      [typeclasses eauto | reflexivity | |].\n    {\n      rewrite FHCOL_to_symbolic_lookup with\n        (sr_σ := dynwin_SF_σ)\n        (sr_m := dynwin_SR_memory)\n        (i := dynwin_y_addr)\n        (off := dynwin_y_offset)\n        (env := Float_env f_imemory).\n      5,6: eassumption.\n      4: {\n        rewrite DynWin_FHCOL_hard_OK in TRANSLATE_OP.\n        invc TRANSLATE_OP.\n        erewrite FHCOLtoSFHCOL.translate_proper.\n        now rewrite DynWin_SFHCOL_hard_OK.\n        now rewrite H1.\n      }\n\n      reflexivity.\n      -\n        clear - RF_IΣ RF_IM.\n        invc RF_IΣ; invc H3; invc H5; invc H6.\n        repeat constructor.\n        all: unfold RHCOLtoFHCOL.heq_evalContextElem in *.\n        all: repeat break_let; subst_max.\n        all: invc H1; invc H2; invc H3.\n        all: invc H; invc H1; invc H2.\n        all: invc H0; invc H4; invc H5.\n        all: repeat constructor; try congruence.\n        all: cbn in *; unfold heq_nat_int in *.\n        all: destruct s', s'0, s'1; cbv in H6, H7, H8; subst.\n        all: cbv; f_equal; apply proof_irrelevance.\n      -\n        clear - RF_IM.\n        intros k; specialize (RF_IM k).\n        do 3 try destruct k.\n        + (* a *)\n          unfold r_imemory in *.\n          cbn - [Float_env ctvector_to_mem_block] in *.\n          invc RF_IM.\n          constructor.\n          intros off; specialize (H1 off).\n          do 3 try destruct off.\n          4: {\n            rewrite ctvector_to_mem_block_key_oob in H1 by lia.\n            invc H1.\n            constructor.\n          }\n          \n          all: erewrite mem_lookup_ctvector_to_mem_block in H1.\n          all: invc H1.\n          all: cbn - [Float_env].\n          all: constructor.\n          all: unfold heq_Float_SExpr; cbn.\n          all: now rewrite <-H0, <-H2.\n          Unshelve.\n          all: cbv; lia.\n        + (* y *)\n          unfold r_imemory in *.\n          cbn - [Float_env ctvector_to_mem_block] in *.\n          invc RF_IM.\n          constructor.\n          intros off; specialize (H1 off); invc H1.\n          cbn.\n          constructor.\n        + (* x *)\n          unfold r_imemory in *.\n          cbn - [Float_env ctvector_to_mem_block] in *.\n          invc RF_IM.\n          constructor.\n          intros off; specialize (H1 off).\n          do 5 try destruct off.\n          6: {\n            rewrite ctvector_to_mem_block_key_oob in H1 by lia.\n            invc H1.\n            constructor.\n          }\n          \n          all: erewrite mem_lookup_ctvector_to_mem_block in H1.\n          all: invc H1.\n          all: cbn - [Float_env].\n          all: constructor.\n          all: unfold heq_Float_SExpr; cbn.\n          all: now rewrite <-H0, <-H2.\n          Unshelve.\n          all: cbv; lia.\n        +\n          invc RF_IM.\n          constructor.\n    }\n\n    pose proof DynWin_Symbolic_out as DS.\n    repeat break_match_goal; try some_none.\n    invc DS.\n\n    (*\n    (evalDSHOperator dynwin_SF_σ DynWin_SFHCOL_hard dynwin_SR_memory\n       (estimateFuel DynWin_SFHCOL_hard))\n      with (Some (@inr string _ hackity_hack))\n      by reflexivity.\n    unfold hackity_hack.\n     *)\n    cbv - [CType_impl evalRealSExpr R_env evalFloatSExpr Float_env].\n\n    assert (RF_Env : forall k, nth_error R_env k ≡\n                   liftM (B2R _ _) (nth_error (Float_env f_imemory) k)).\n    {\n      clear - RF_IM.\n      intros.\n      do 8 try destruct k.\n      9: cbn; now rewrite !nth_error_nil_None.\n\n      all: cbn.\n      all: match goal with\n           | |- context[FHCOLEval.memory_lookup _ ?n] =>\n               specialize (RF_IM n)\n           end.\n      all: cbn - [ctvector_to_mem_block] in RF_IM; invc RF_IM.\n      all: match goal with\n           | |- context[FHCOLEval.mem_lookup ?n _] =>\n               specialize (H1 n)\n           end.\n      all: erewrite mem_lookup_ctvector_to_mem_block in H1.\n      all: invc H1; invc H3.\n      all: rewrite H1; reflexivity.\n    }\n\n    clear - INCONSTR A_RMEM X_RMEM RF_IM RF_Env.\n    cbn [evalRealSExpr evalFloatSExpr].\n    rewrite !RF_Env; clear RF_Env.\n\n    unfold Float_env.\n    rewrite !Coqlib.list_map_nth.\n    cbn [nth_error Coqlib.option_map\n           liftM liftM2 OptionMonad.Monad_option bind ret].\n    constructor.\n\n    pose proof RF_IM 0 as RF_A_IM.\n    rewrite A_RMEM in RF_A_IM.\n    invc RF_A_IM.\n\n    pose proof RF_IM 2 as RF_X_IM.\n    rewrite X_RMEM in RF_X_IM.\n    invc RF_X_IM.\n\n    cbn [Fmemory_lookup_deep_unsafe].\n    rewrite <-!H0, <-!H2.\n    clear - INCONSTR H1 H3.\n    rename b into a_fmem, b0 into x_fmem, H1 into FA, H3 into FX.\n\n    unfold DynWinInConstr in INCONSTR.\n    destruct INCONSTR as\n      (V64 & b64 & A64 & e64 & v64 & rx64 & ry64 & ox64 & oy64 & INCONSTR).\n    destruct INCONSTR as\n      (VC & bC & AC & eC & A & vC & rxC & ryC & oxC & oyC & X).\n\n    unfold make_a64 in *.\n\n    Ltac mem_lookup_simpl :=\n      unfold FHCOLEval.mem_add, FHCOLEval.mem_lookup in *;\n      repeat (try rewrite Memory.NP.F.add_eq_o in * by lia;\n              try rewrite Memory.NP.F.add_neq_o in * by lia).\n\n    (* Hardcoded lookups in a *)\n    pose proof (A 0) as A0.\n    pose proof (FA 0) as FA0.\n    mem_lookup_simpl.\n    inversion A0 as [| a0 ? A0E A0'];\n      subst; rewrite <-A0' in *; clear A0 A0'.\n    inversion FA0 as [| a0' ? FA0E TMP1 TMP2];\n      subst; rename b into fa0; clear TMP2 FA0.\n    \n    pose proof (A 1) as A1.\n    pose proof (FA 1) as FA1.\n    mem_lookup_simpl.\n    inversion A1 as [| a1 ? A1E A1'];\n      subst; rewrite <-A1' in *; clear A1 A1'.\n    inversion FA1 as [| a1' ? FA1E TMP1 TMP2];\n      subst; rename b into fa1; clear TMP2 FA1.\n\n    pose proof (A 2) as A2.\n    pose proof (FA 2) as FA2.\n    mem_lookup_simpl.\n    remember (b64_div FT_Rounding b64_1 (MFloat64asCT.CTypeMult b64_2 b64)) as T.\n    inversion A2 as [| a2 ? A2E A2'];\n      subst; rewrite <-A2' in *; clear A2 A2'.\n    inversion FA2 as [| a2' ? FA2E TMP1 TMP2];\n      subst; rename b into fa2; clear TMP2 FA2.\n\n    clear A FA.\n\n    (* Hardcoded lookups in x *)\n    pose proof (X 0) as X0.\n    pose proof (FX 0) as FX0.\n    mem_lookup_simpl.\n    inversion X0 as [| x0 ? X0E X0'];\n      subst; rewrite <-X0' in *; clear X0 X0'.\n    inversion FX0 as [| x0' ? FX0E TMP1 TMP2];\n      subst; rename b into fx0; clear TMP2 FX0.\n\n    pose proof (X 1) as X1.\n    pose proof (FX 1) as FX1.\n    mem_lookup_simpl.\n    inversion X1 as [| x1 ? X1E X1'];\n      subst; rewrite <-X1' in *; clear X1 X1'.\n    inversion FX1 as [| x1' ? FX1E TMP1 TMP2];\n      subst; rename b into fx1; clear TMP2 FX1.\n\n    pose proof (X 2) as X2.\n    pose proof (FX 2) as FX2.\n    mem_lookup_simpl.\n    inversion X2 as [| x2 ? X2E X2'];\n      subst; rewrite <-X2' in *; clear X2 X2'.\n    inversion FX2 as [| x2' ? FX2E TMP1 TMP2];\n      subst; rename b into fx2; clear TMP2 FX2.\n\n    pose proof (X 3) as X3.\n    pose proof (FX 3) as FX3.\n    mem_lookup_simpl.\n    inversion X3 as [| x3 ? X3E X3'];\n      subst; rewrite <-X3' in *; clear X3 X3'.\n    inversion FX3 as [| x3' ? FX3E TMP1 TMP2];\n      subst; rename b into fx3; clear TMP2 FX3.\n\n    pose proof (X 4) as X4.\n    pose proof (FX 4) as FX4.\n    mem_lookup_simpl.\n    inversion X4 as [| x4 ? X4E X4'];\n      subst; rewrite <-X4' in *; clear X4 X4'.\n    inversion FX4 as [| x4' ? FX4E TMP1 TMP2];\n      subst; rename b into fx4; clear TMP2 FX4.\n\n    clear X FX.\n\n    unfold RHCOLtoFHCOL.heq_CType', RF_CHE in *.\n    destruct FA0E as [FA0F FA0].\n    destruct FA1E as [FA1F FA1].\n    destruct FA2E as [FA2F FA2].\n    destruct FX0E as [FX0F FX0].\n    destruct FX1E as [FX1F FX1].\n    destruct FX2E as [FX2F FX2].\n    destruct FX3E as [FX3F FX3].\n    destruct FX4E as [FX4F FX4].\n    destruct A0E as [A0F A0].\n    destruct A1E as [A1F A1].\n    destruct A2E as [A2F A2].\n    destruct X0E as [X0F X0].\n    destruct X1E as [X1F X1].\n    destruct X2E as [X2F X2].\n    destruct X3E as [X3F X3].\n    destruct X4E as [X4F X4].\n    subst.\n\n    intros F.\n    rewrite float_as_bool_Zless in F; apply R_as_bool_Zless.\n\n    eapply DynWin_numerical_stability.\n    eapply VC.\n    eapply bC.\n    eapply AC.\n    eapply eC.\n    eapply vC.\n    eapply rxC.\n    eapply ryC.\n    eapply oxC.\n    eapply oyC.\n    all: assumption.\n  Qed.\n\nEnd DynWin_Symbolic.\n\n(*\n  Translation validation proof of semantic preservation\n  of successful translation of [dynwin_orig] into FHCOL program.\n\n  Using following definitons from DynWin.v:\n   1. dynwin_i\n   2. dynwin_o\n   3. dynwin_orig\n\n   And the following definition are produced with TemplateCoq:\n   1. dynwin_RHCOL\n *)\nTheorem HCOL_to_FHCOL_Correctness (a: vector CarrierA 3):\n  forall x y,\n    (* evaluatoion of original operator *)\n    dynwin_orig a x = y ->\n\n    forall dynwin_F_memory dynwin_F_σ (dynwin_FHCOL:FHCOL.DSHOperator),\n      (* Compile -> RHCOL -> FHCOL *)\n      RHCOLtoFHCOL.translate DynWin_RHCOL = inr dynwin_FHCOL ->\n\n      (* Equivalent inputs *)\n      RHCOLtoFHCOL.heq_memory () RF_CHE (dynwin_R_memory a x) dynwin_F_memory ->\n      RHCOLtoFHCOL.heq_evalContext () RF_NHE RF_CHE dynwin_R_σ dynwin_F_σ ->\n\n      forall a_rmem x_rmem,\n        RHCOLEval.memory_lookup (dynwin_R_memory a x) dynwin_a_addr = Some a_rmem ->\n        RHCOLEval.memory_lookup (dynwin_R_memory a x) dynwin_x_addr = Some x_rmem ->\n        DynWinInConstr a_rmem x_rmem ->\n\n        (* Everything correct on Reals *)\n        exists r_omemory y_rmem,\n          RHCOLEval.evalDSHOperator\n            dynwin_R_σ\n            DynWin_RHCOL\n            (dynwin_R_memory a x)\n            (RHCOLEval.estimateFuel DynWin_RHCOL) = Some (inr r_omemory)\n          /\\ RHCOLEval.memory_lookup r_omemory dynwin_y_addr = Some y_rmem\n          /\\ ctvector_to_mem_block y = y_rmem\n\n          (* And floats *)\n          /\\ exists f_omemory y_fmem,\n            FHCOLEval.evalDSHOperator\n              dynwin_F_σ dynwin_FHCOL\n              dynwin_F_memory\n              (FHCOLEval.estimateFuel dynwin_FHCOL) = (Some (inr f_omemory))\n            /\\ FHCOLEval.memory_lookup f_omemory dynwin_y_addr = Some y_fmem\n            /\\ DynWinOutRel a_rmem x_rmem y_rmem y_fmem.\nProof.\n  intros * HC * CR CRM CRE * RA RX INCONSTR.\n\n  remember (RHCOLEval.memory_set\n              (dynwin_R_memory a x)\n              dynwin_y_addr\n              (ctvector_to_mem_block y)) as r_omemory eqn:ROM.\n\n  assert(RHCOLEval.evalDSHOperator\n           dynwin_R_σ\n           DynWin_RHCOL\n           (dynwin_R_memory a x)\n           (RHCOLEval.estimateFuel DynWin_RHCOL) = Some (inr r_omemory)) as RO.\n  {\n    pose proof (DynWin_MSH_DSH_compat a) as MRHCOL.\n    pose proof (DynWin_pure) as MAPURE.\n    pose proof (dynwin_SHCOL_MSHCOL_compat a) as MCOMP.\n    pose proof (SHCOL_to_SHCOL1_Rewriting a) as SH1.\n    pose proof (DynWinSigmaHCOL_Value_Correctness a) as HSH.\n    pose proof (DynWinHCOL a x x) as HH.\n    autospecialize HH; [reflexivity|].\n    rewrite HC in HH. clear HC.\n\n    (* moved from [dynwin_orig] to [dynwin_HCOL] *)\n\n    remember (sparsify Monoid_RthetaFlags x) as sx eqn:SX.\n    remember (sparsify Monoid_RthetaFlags y) as sy eqn:SY.\n    assert(SHY: op _ (dynwin_SHCOL a) sx = sy).\n    {\n      subst sy.\n      rewrite_clear HH.\n\n      specialize (HSH sx sx).\n      autospecialize HSH; [reflexivity|].\n      rewrite <- HSH. clear HSH.\n      unfold liftM_HOperator.\n      Opaque dynwin_HCOL equiv.\n      cbn.\n      unfold SigmaHCOLImpl.liftM_HOperator_impl.\n      unfold Basics.compose.\n      f_equiv.\n      subst sx.\n      rewrite densify_sparsify.\n      reflexivity.\n    }\n    Transparent dynwin_HCOL equiv.\n    clear HH HSH.\n\n    (* moved from [dynwin_HCOL] to [dynwin_SHCOL] *)\n\n    assert(SH1Y: op _ (dynwin_SHCOL1 a) sx = sy).\n    {\n      rewrite <- SHY. clear SHY.\n      destruct SH1.\n      rewrite H.\n      reflexivity.\n    }\n    clear SHY SH1.\n\n    (* moved from [dynwin_SHCOL] to [dynwin_SHCOL1] *)\n\n    assert(M1: mem_op (dynwin_MSHCOL1 a) (svector_to_mem_block Monoid_RthetaFlags sx) = Some (svector_to_mem_block Monoid_RthetaFlags sy)).\n    {\n      cut(Some (svector_to_mem_block Monoid_RthetaFlags (op Monoid_RthetaFlags (dynwin_SHCOL1 a) sx)) = mem_op (dynwin_MSHCOL1 a) (svector_to_mem_block Monoid_RthetaFlags sx)).\n      {\n        intros M0.\n        rewrite <- M0. clear M0.\n        apply Some_proper.\n\n        cut(svector_is_dense _ (op Monoid_RthetaFlags (dynwin_SHCOL1 a) sx)).\n        intros YD.\n\n        apply svector_to_mem_block_dense_kind_of_proper.\n        apply YD.\n\n        subst sy.\n        apply sparsify_is_dense.\n        typeclasses eauto.\n\n        apply SH1Y.\n\n        {\n          pose proof (@out_as_range _ _ _ _ _ _ (DynWinSigmaHCOL1_Facts a)) as D.\n          specialize (D sx).\n\n          autospecialize D.\n          {\n            intros j jc H.\n            destruct (dynwin_SHCOL1 a).\n            cbn in H.\n            subst sx.\n            rewrite Vnth_sparsify.\n            apply Is_Val_mkValue.\n          }\n\n              unfold svector_is_dense.\n          apply Vforall_nth_intro.\n          intros i ip.\n          apply D.\n          cbn.\n          constructor.\n        }\n      }\n      {\n        destruct MCOMP.\n        apply mem_vec_preservation.\n        cut(svector_is_dense Monoid_RthetaFlags (sparsify _ x)).\n        intros SD.\n        unfold svector_is_dense in SD.\n        intros j jc H.\n        apply (Vforall_nth jc) in SD.\n        subst sx.\n        apply SD.\n        apply sparsify_is_dense.\n        typeclasses eauto.\n      }\n    }\n    clear SH1Y MCOMP.\n\n    (* moved from [dynwin_SHCOL1] to [dynwin_MSHCOL1] *)\n\n    remember (svector_to_mem_block Monoid_RthetaFlags sx) as mx eqn:MX.\n    remember (svector_to_mem_block Monoid_RthetaFlags sy) as my eqn:MY.\n\n    specialize (MRHCOL x).\n    destruct MRHCOL as [MRHCOL].\n    specialize (MRHCOL (ctvector_to_mem_block x) RHCOLEval.mem_empty).\n    autospecialize MRHCOL.\n    reflexivity.\n    autospecialize MRHCOL.\n    reflexivity.\n\n    destruct_h_opt_opterr_c MM AE.\n    -\n      destruct s; inversion_clear MRHCOL.\n      f_equiv; f_equiv.\n      rename m0 into m'.\n      destruct (lookup_PExpr dynwin_R_σ m' DSH_y_p) eqn:RY.\n      +\n        exfalso.\n        clear - MAPURE AE RY.\n        cbn in RY.\n        assert (RHCOL.mem_block_exists 1 m').\n        {\n          erewrite <-mem_stable.\n          2: now rewrite AE.\n          now apply RHCOLEval.memory_is_set_is_Some.\n        }\n        apply RHCOLEval.memory_is_set_is_Some in H.\n        unfold util.is_Some, RHCOLEval.memory_lookup_err in *.\n        break_match; try contradiction.\n        inv RY.\n      +\n        inversion_clear H.\n        rename m into ym.\n        rename m0 into ym'.\n        subst.\n        destruct (dynwin_MSHCOL1 a).\n        rewrite 2!svector_to_mem_block_ctvector_to_mem_block\n          in M1\n            by typeclasses eauto.\n        Opaque ctvector_to_mem_block.\n        cbn in M1, MM.\n        rewrite MM in M1.\n        clear MM.\n        some_inv.\n        Transparent ctvector_to_mem_block.\n\n        rewrite <-M1.\n        assert (YM : ym = ym').\n        {\n          clear - H0.\n          intros k.\n          specialize (H0 k).\n          cbn in H0.\n          unfold RHCOL.mem_lookup in *.\n          inv H0.\n          -\n            unfold util.is_None in *.\n            now break_match.\n          -\n            symmetry; assumption.\n        }\n        rewrite YM.\n\n        clear - AE RY MAPURE.\n        destruct MAPURE as [_ MWS].\n        cbn; cbn in RY.\n        eapply memory_equiv_except_memory_set_inv.\n        eapply MWS.\n        now erewrite AE.\n        now cbv.\n        eapply RHCOLEval.memory_lookup_err_inr_Some.\n        now rewrite RY.\n    -\n      exfalso.\n      pose proof (@RHCOLEval.evalDSHOperator_estimateFuel dynwin_R_σ DynWin_RHCOL (dynwin_R_memory a x)) as CC.\n      clear - CC AE.\n      apply util.is_None_def in AE.\n      generalize dependent (RHCOLEval.evalDSHOperator dynwin_R_σ DynWin_RHCOL\n                                                      (dynwin_R_memory a x) (RHCOLEval.estimateFuel DynWin_RHCOL)).\n      intros o AE CC.\n      some_none.\n    -\n      exfalso.\n      remember (dynwin_MSHCOL1 a) as m.\n      destruct m.\n      subst sx mx.\n      rewrite svector_to_mem_block_ctvector_to_mem_block in M1.\n      eq_to_equiv.\n      some_none.\n      typeclasses eauto.\n    -\n      exfalso.\n      remember (dynwin_MSHCOL1 a) as m.\n      destruct m.\n      subst sx mx.\n      rewrite svector_to_mem_block_ctvector_to_mem_block in M1.\n      eq_to_equiv.\n      some_none.\n      typeclasses eauto.\n  }\n\n  (* moved from [dynwin_MSHCOL1] to [dynwin_rhcol] *)\n\n  generalize dependent (ctvector_to_mem_block y).\n  intros y_rmem R_OMEM.\n\n  exists r_omemory.\n  exists y_rmem.\n\n  split; [assumption |].\n  split.\n  1: {\n    rewrite R_OMEM.\n    now rewrite memory_lookup_memory_set_eq by reflexivity.\n  }\n  split; [reflexivity |].\n\n  pose proof\n       RF_Structural_Semantic_Preservation\n       DynWin_RHCOL\n       dynwin_FHCOL\n       (RHCOLEval.estimateFuel DynWin_RHCOL)\n       (FHCOLEval.estimateFuel dynwin_FHCOL)\n       dynwin_R_σ\n       dynwin_F_σ\n       (dynwin_R_memory a x)\n       dynwin_F_memory\n    as HEQRF.\n  full_autospecialize HEQRF.\n  {\n    eapply RHCOLtoFHCOL.translation_syntax_always_correct.\n    eapply RF_NTP.\n    assumption.\n  }\n  {\n    clear - CRE.\n    induction CRE.\n    -\n      constructor.\n    -\n      constructor;\n        [| apply IHCRE].\n      unfold RHCOLtoFHCOL.heq_evalContextElem in *.\n      repeat break_let; subst.\n      repeat constructor.\n      intuition.\n      destruct H as [_ D].\n      invc D; repeat constructor; assumption.\n  }\n  {\n    clear - CRM.\n    generalize dependent (dynwin_R_memory a x).\n    clear.\n    intros dynwin_R_memory M.\n\n    intros k.\n    specialize (M k).\n    invc M; constructor.\n\n    intros k'.\n    specialize (H1 k').\n    invc H1; constructor.\n    constructor.\n  }\n  {\n    eapply @RHCOLtoFHCOL_NExpr_closure_trace_equiv.\n    assumption.\n    clear - CRE.\n    eapply CRE.\n  }\n\n  subst r_omemory.\n  destruct RHCOLEval.evalDSHOperator as [[e | r_omemory] |] eqn:RE in *;\n    try some_none; repeat some_inv;\n    try inl_inr; repeat inl_inr_inv.\n\n  invc HEQRF; invc H1.\n  rename b0 into f_omemory, H0 into F_EVAL, H2 into RF_OM.\n  symmetry in RO, F_EVAL.\n\n  exists f_omemory.\n\n  unfold RHCOLEval.memory_set in RE.\n  pose proof RF_OM as RF_YO.\n  pose proof RO as R_YO.\n  specialize (RF_YO dynwin_y_addr).\n  specialize (R_YO dynwin_y_addr).\n  unfold RHCOLEval.memory_set, RHCOLEval.memory_lookup in *.\n  rewrite Memory.NP.F.add_eq_o in R_YO by reflexivity.\n\n  invc RF_YO;\n    [rewrite <-H0 in *; some_none |].\n  rename b into y_fmem, H0 into Y_FMEM.\n  rename a0 into y_rmem', H into Y_RMEM'.\n  rename H1 into Y_RFE.\n  symmetry in Y_RMEM', Y_FMEM.\n\n  exists y_fmem.\n  do 2 (split; [reflexivity |]).\n\n  (* get rid of duplicate [y_rmem] *)\n  rewrite Y_RMEM' in *.\n  some_inv.\n  rewrite R_YO.\n  clear RO R_YO y_rmem.\n  rename y_rmem' into y_rmem, Y_RMEM' into Y_RMEM.\n\n  clear y HC.\n\n  subst.\n\n  eapply RHCOL_to_FHCOL_numerical_correct;\n    try eassumption.\n  now rewrite RE.\n  now rewrite <-Y_RMEM.\n  now rewrite F_EVAL.\n  now rewrite <-Y_FMEM.\nQed.\n", "meta": {"author": "vzaliva", "repo": "helix", "sha": "5d0a71df99722d2011c36156f12b04875df7e1cb", "save_path": "github-repos/coq/vzaliva-helix", "path": "github-repos/coq/vzaliva-helix/helix-5d0a71df99722d2011c36156f12b04875df7e1cb/coq/DynWin/DynWinTopLevel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2810882577782663}}
{"text": "(** * Compute a list of liveness values for each binding *)\nRequire Import Coq.Lists.List.\nRequire Import Crypto.Reflection.Syntax.\nRequire Import Crypto.Reflection.Named.Syntax.\nRequire Import Crypto.Reflection.CountLets.\nRequire Import Crypto.Util.ListUtil.\n\nLocal Notation eta x := (fst x, snd x).\n\nLocal Open Scope ctype_scope.\nDelimit Scope nexpr_scope with nexpr.\n\nInductive liveness := live | dead.\nFixpoint merge_liveness (ls1 ls2 : list liveness) :=\n  match ls1, ls2 with\n  | cons x xs, cons y ys\n    => cons match x, y with\n            | live, _\n            | _, live\n              => live\n            | dead, dead\n              => dead\n            end\n            (@merge_liveness xs ys)\n  | nil, ls\n  | ls, nil\n    => ls\n  end.\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\n  Local Notation flat_type := (flat_type base_type_code).\n  Local Notation type := (type base_type_code).\n  Let Tbase := @Tbase base_type_code.\n  Local Coercion Tbase : base_type_code >-> Syntax.flat_type.\n  Local Notation interp_type := (interp_type interp_base_type).\n  Local Notation interp_flat_type := (interp_flat_type_gen interp_base_type).\n  Local Notation exprf := (@exprf base_type_code interp_base_type op).\n  Local Notation expr := (@expr base_type_code interp_base_type op).\n\n  Section internal.\n    Context (Name : Type)\n            (OutName : Type)\n            {Context : Context Name (fun _ : base_type_code => list liveness)}.\n\n    Definition compute_livenessf_step\n               (compute_livenessf : forall (ctx : Context) {t} (e : exprf Name t) (prefix : list liveness), list liveness)\n               (ctx : Context)\n               {t} (e : exprf Name t) (prefix : list liveness)\n      : list liveness\n      := match e with\n         | Const _ x => prefix\n         | Var t' name => match lookup ctx t' name with\n                          | Some ls => ls\n                          | _ => nil\n                          end\n         | Op _ _ op args\n           => @compute_livenessf ctx _ args prefix\n         | LetIn tx n ex _ eC\n           => let lx := @compute_livenessf ctx _ ex prefix in\n              let lx := merge_liveness lx (prefix ++ repeat live (count_pairs tx)) in\n              let ctx := extend ctx n (SmartVal _ (fun _ => lx) tx) in\n              @compute_livenessf ctx _ eC (prefix ++ repeat dead (count_pairs tx))\n         | Pair _ ex _ ey\n           => merge_liveness (@compute_livenessf ctx _ ex prefix)\n                             (@compute_livenessf ctx _ ey prefix)\n         end.\n\n    Fixpoint compute_livenessf ctx {t} e prefix\n      := @compute_livenessf_step (@compute_livenessf) ctx t e prefix.\n\n    Fixpoint compute_liveness (ctx : Context)\n             {t} (e : expr Name t) (prefix : list liveness)\n      : list liveness\n      := match e with\n         | Return _ x => compute_livenessf ctx x prefix\n         | Abs src _ n f\n           => let prefix := prefix ++ (live::nil) in\n              let ctx := extendb (t:=src) ctx n prefix in\n              @compute_liveness ctx _ f prefix\n         end.\n\n    Section insert_dead.\n      Context (default_out : option OutName).\n\n      Fixpoint insert_dead_names_gen (ls : list liveness) (lsn : list OutName)\n        : list (option OutName)\n        := match ls with\n           | nil => nil\n           | cons live xs\n             => match lsn with\n                | cons n lsn' => Some n :: @insert_dead_names_gen xs lsn'\n                | nil => default_out :: @insert_dead_names_gen xs nil\n                end\n           | cons dead xs\n             => None :: @insert_dead_names_gen xs lsn\n           end.\n      Definition insert_dead_names {t} (e : expr Name t)\n        := insert_dead_names_gen (compute_liveness empty e nil).\n    End insert_dead.\n  End internal.\nEnd language.\n\nGlobal Arguments compute_livenessf {_ _ _ _ _} ctx {t} e prefix.\nGlobal Arguments compute_liveness {_ _ _ _ _} ctx {t} e prefix.\nGlobal Arguments insert_dead_names {_ _ _ _ _ _} default_out {t} e lsn.\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_vm_compute/src/Reflection/Named/EstablishLiveness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5, "lm_q1q2_score": 0.28108825044289903}}
{"text": "(** * General-purpose definitions *)\n\n(** Not specific to itrees. *)\n\n(* begin hide *)\nFrom Coq Require\n     Ensembles.\n\nFrom Coq Require Import\n     RelationClasses.\n\nFrom ExtLib Require Import\n     Structures.Functor\n     Structures.Monad\n     Data.Monads.StateMonad\n     Data.Monads.ReaderMonad\n     Data.Monads.OptionMonad\n     Data.Monads.EitherMonad.\n\nImport\n  FunctorNotation\n  MonadNotation.\nLocal Open Scope monad.\n(* end hide *)\n\n(** ** Parametric functions *)\n\n(** A notation for a certain class of parametric functions.\n    Some common names of things that can be represented by such a type:\n\n    - Natural transformations (functor morphisms)\n    - Monad morphisms\n    - Event morphisms (if [E] and [F] are simply\n      indexed types with no particular structure)\n    - Event handlers (if [F] is a monad)\n *)\nNotation \"E ~> F\" := (forall T, E T -> F T)\n  (at level 99, right associativity, only parsing) : type_scope.\n(* The same level as [->]. *)\n(* This might actually not be such a good idea. *)\n\n(** Identity morphism. *)\nDefinition idM {E : Type -> Type} : E ~> E := fun _ e => e.\n\n(** [void] is a shorthand for [Empty_set]. *)\nNotation void := Empty_set.\n\n(** ** Common monads and transformers. *)\n\nModule Monads.\n\nDefinition identity (a : Type) : Type := a.\n\nDefinition stateT (s : Type) (m : Type -> Type) (a : Type) : Type :=\n  s -> m (prod s a).\nDefinition state (s a : Type) := s -> prod s a.\n\nDefinition run_stateT {s m a} (x : stateT s m a) : s -> m (s * a)%type := x.\n\nDefinition liftState {s a f} `{Functor f} (fa : f a) : Monads.stateT s f a :=\n  fun s => pair s <$> fa.\n\nDefinition readerT (r : Type) (m : Type -> Type) (a : Type) : Type :=\n  r -> m a.\nDefinition reader (r a : Type) := r -> a.\n\nDefinition writerT (w : Type) (m : Type -> Type) (a : Type) : Type :=\n  m (prod w a).\nDefinition writer := prod.\n\n#[global] Instance Functor_stateT {m s} {Fm : Functor m} : Functor (stateT s m)\n  := {|\n    fmap _ _ f := fun run s => fmap (fun sa => (fst sa, f (snd sa))) (run s)\n    |}.\n\n#[global] Instance Monad_stateT {m s} {Fm : Monad m} : Monad (stateT s m)\n  := {|\n    ret _ a := fun s => ret (s, a)\n  ; bind _ _ t k := fun s =>\n      sa <- t s ;;\n      k (snd sa) (fst sa)\n    |}.\n\nEnd Monads.\n\n(** ** Loop operator *)\n\n(** [iter]: A primitive for general recursion.\n    Iterate a function updating an accumulator [I], until it produces\n    an output [R].\n *)\nPolymorphic Class MonadIter (M : Type -> Type) : Type :=\n  iter : forall {R I: Type}, (I -> M (I + R)%type) -> I -> M R.\n\n(** *** Transformer instances *)\n\n(** And the standard transformers can lift [iter].\n\n    Quite easily in fact, no [Monad] assumption needed.\n *)\n\n#[global] Instance MonadIter_stateT {M S} {MM : Monad M} {AM : MonadIter M}\n  : MonadIter (stateT S M) :=\n  fun _ _ step i => mkStateT (fun s =>\n    iter (fun is =>\n      let i := fst is in\n      let s := snd is in\n      is' <- runStateT (step i) s ;;\n      ret match fst is' with\n          | inl i' => inl (i', snd is')\n          | inr r => inr (r, snd is')\n          end) (i, s)).\n\n#[global] Polymorphic Instance MonadIter_stateT0 {M S} {MM : Monad M} {AM : MonadIter M}\n  : MonadIter (Monads.stateT S M) :=\n  fun _ _ step i s =>\n    iter (fun si =>\n      let s := fst si in\n      let i := snd si in\n      si' <- step i s;;\n      ret match snd si' with\n          | inl i' => inl (fst si', i')\n          | inr r => inr (fst si', r)\n          end) (s, i).\n\n#[global] Instance MonadIter_readerT {M S} {AM : MonadIter M} : MonadIter (readerT S M) :=\n  fun _ _ step i => mkReaderT (fun s =>\n    iter (fun i => runReaderT (step i) s) i).\n\n#[global] Instance MonadIter_optionT {M} {MM : Monad M} {AM : MonadIter M}\n  : MonadIter (optionT M) :=\n  fun _ _ step i => mkOptionT (\n    iter (fun i =>\n      oi <- unOptionT (step i) ;;\n      ret match oi with\n          | None => inr None\n          | Some (inl i) => inl i\n          | Some (inr r) => inr (Some r)\n          end) i).\n\n#[global] Instance MonadIter_eitherT {M E} {MM : Monad M} {AM : MonadIter M}\n  : MonadIter (eitherT E M) :=\n  fun _ _ step i => mkEitherT (\n    iter (fun i =>\n      ei <- unEitherT (step i) ;;\n      ret match ei with\n          | inl e => inr (inl e)\n          | inr (inl i) => inl i\n          | inr (inr r) => inr (inr r)\n          end) i).\n\n(** And the nondeterminism monad [_ -> Prop] also has one. *)\n\nInductive iter_Prop {R I : Type} (step : I -> I + R -> Prop) (i : I) (r : R)\n  : Prop :=\n| iter_done\n  : step i (inr r) -> iter_Prop step i r\n| iter_step i'\n  : step i (inl i') ->\n    iter_Prop step i' r ->\n    iter_Prop step i r\n.\n\n#[global] Polymorphic Instance MonadIter_Prop : MonadIter Ensembles.Ensemble := @iter_Prop.\n\n(* Elementary constructs for predicates. To be moved in their own file eventually *)\nDefinition equiv_pred {A : Type} (R S: A -> Prop): Prop :=\n  forall a, R a <-> S a.\n\nDefinition sum_pred {A B : Type} (PA : A -> Prop) (PB : B -> Prop) : A + B -> Prop :=\n  fun x => match x with | inl a => PA a | inr b => PB b end.\n\nDefinition prod_pred {A B : Type} (PA : A -> Prop) (PB : B -> Prop) : A * B -> Prop :=\n  fun '(a,b) => PA a /\\ PB b.\n\nDefinition TT {A : Type} : A -> Prop := fun _ => True.\nGlobal Hint Unfold TT sum_pred prod_pred: core.\n\n#[global] Instance equiv_pred_refl  {A} : Reflexive (@equiv_pred A).\nProof.\n  split; auto.\nQed.\n#[global] Instance equiv_pred_symm  {A} : Symmetric (@equiv_pred A).\nProof.\n  red; intros * EQ; split; intros; eapply EQ; auto.\nQed.\n#[global] Instance equiv_pred_trans {A} : Transitive (@equiv_pred A).\nProof.\n  red; intros * EQ1 EQ2; split; intros; (apply EQ1,EQ2 || apply EQ2,EQ1); auto.\nQed.\n#[global] Instance equiv_pred_equiv {A} : Equivalence (@equiv_pred A).\nProof.\n  split; typeclasses eauto.\nQed.\n\n", "meta": {"author": "DeepSpec", "repo": "InteractionTrees", "sha": "8e28e2ee08496c696e03916a22d93c39559a9715", "save_path": "github-repos/coq/DeepSpec-InteractionTrees", "path": "github-repos/coq/DeepSpec-InteractionTrees/InteractionTrees-8e28e2ee08496c696e03916a22d93c39559a9715/theories/Basics/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621764862150636, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2810882431075318}}
{"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 O E Eprime A B C Oprime Aprime Bprime Cprime Eprimeprime Bprimeprime C2 C3 : Universe, ((wd_ O E /\\ (wd_ Oprime Eprime /\\ (wd_ A O /\\ (wd_ B O /\\ (wd_ C O /\\ (wd_ A E /\\ (wd_ Eprimeprime O /\\ (wd_ O Oprime /\\ (wd_ Bprimeprime O /\\ (wd_ Bprime Oprime /\\ (wd_ Eprimeprime A /\\ (wd_ E Eprimeprime /\\ (wd_ E Eprime /\\ (wd_ O Eprime /\\ (wd_ Oprime Eprimeprime /\\ (wd_ E Oprime /\\ (wd_ C Bprimeprime /\\ (wd_ Cprime C3 /\\ (wd_ B Bprimeprime /\\ (wd_ Bprime C3 /\\ (wd_ Eprime C2 /\\ (wd_ Aprime C2 /\\ (wd_ Oprime Aprime /\\ (wd_ A Aprime /\\ (wd_ C Cprime /\\ (wd_ B Bprime /\\ (col_ O E A /\\ (col_ O E B /\\ (col_ O E C /\\ (col_ Oprime Eprime Aprime /\\ (col_ Oprime Eprime Bprime /\\ (col_ Oprime Eprime Cprime /\\ (col_ O Eprimeprime Bprimeprime /\\ (col_ O Eprimeprime Oprime /\\ (col_ O Eprimeprime C2 /\\ (col_ O Eprimeprime C3 /\\ col_ O A C)))))))))))))))))))))))))))))))))))) -> col_ Oprime C2 C3)).\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_1297.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191214879992, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.28081990330098383}}
{"text": "Require Import Bool.\nRequire Import RelationClasses.\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.\nRequire Import List.\n\nRequire Import Sequential.\nRequire Import OracleFacts.\n\nRequire Import SeqAux.\nRequire Import SimAux.\nRequire Import SeqAux.\n\nSet Implicit Arguments.\n\n\nModule SeqTrace.\n  Variant result: Type :=\n  | term (v: ValueMap.t) (f: Flags.t)\n  | partial (f: Flags.t)\n  | ub\n  .\n\n  Definition t: Type := list (ProgramEvent.t * SeqEvent.input * Oracle.output) * result.\n\n  Inductive le: Flags.t -> t -> t -> Prop :=\n  | le_term\n      d v_src v_tgt f_src f_tgt\n      (VAL: ValueMap.le v_tgt v_src)\n      (FLAG: Flags.le (Flags.join d f_tgt) f_src)\n    :\n      le d ([], term v_tgt f_tgt) ([], term v_src f_src)\n  | le_partial\n      d tr_src f_src f_tgt w\n      (TRACE: SeqThread.writing_trace tr_src w)\n      (FLAG: Flags.le (Flags.join d f_tgt) (Flags.join w f_src))\n    :\n      le d ([], partial f_tgt) (tr_src, partial f_src)\n  | le_ub\n      d tr_src tr_tgt w\n      (TRACE: SeqThread.writing_trace tr_src w)\n    :\n      le d tr_tgt (tr_src, ub)\n  | le_cons\n      d0 d1 e_src e_tgt i_src i_tgt o tr_src tr_tgt r_src r_tgt\n      (LE: le d1 (tr_tgt, r_tgt) (tr_src, r_src))\n      (MATCH: SeqEvent.input_match d0 d1 i_src i_tgt)\n      (EVENT: ProgramEvent.le e_tgt e_src)\n    :\n      le d0 ((e_tgt, i_tgt, o)::tr_tgt, r_tgt) ((e_src, i_src, o)::tr_src, r_src)\n  .\n\n  Lemma le_deferred_mon d0 d1 tr0 tr1\n        (DEFERRED: Flags.le d0 d1)\n        (LE: le d1 tr0 tr1)\n    :\n      le d0 tr0 tr1.\n  Proof.\n    induction LE.\n    { econs 1; eauto. etrans; eauto.\n      eapply Flags.join_mon_l. eauto. }\n    { econs 2; eauto.\n      etrans; eauto. eapply Flags.join_mon_l; eauto.\n    }\n    { econs 3; eauto. }\n    { econs 4.\n      { eauto. }\n      { eapply SeqEvent.input_match_mon; eauto. refl. }\n      { eauto. }\n    }\n  Qed.\n\n  Definition incl (b0: t -> Prop) (b1: t -> Prop): Prop :=\n    forall tr0, b0 tr0 -> exists tr1, b1 tr1 /\\ le Flags.bot tr0 tr1.\nEnd SeqTrace.\n\n\nModule SeqBehavior.\nSection LANG.\n  Variable lang: language.\n  Variable state_step:\n    Perms.t -> MachineEvent.t -> SeqState.t lang -> SeqState.t lang -> Prop.\n\n  Inductive behavior: forall (th0: SeqThread.t lang) (tr: SeqTrace.t), Prop :=\n  | behavior_term\n      st v f p o\n      (TERMINAL: lang.(Language.is_terminal) st)\n    :\n      behavior (SeqThread.mk (SeqState.mk _ st (SeqMemory.mk v f)) p o) ([], SeqTrace.term v f)\n  | behavior_partial\n      st v f p o\n    :\n      behavior (SeqThread.mk (SeqState.mk _ st (SeqMemory.mk v f)) p o) ([], SeqTrace.partial f)\n  | behavior_ub\n      st m p o\n      (FAILURE: SeqThread.failure state_step (SeqThread.mk (SeqState.mk _ st m) p o))\n    :\n      behavior (SeqThread.mk (SeqState.mk _ st m) p o) ([], SeqTrace.ub)\n  | behavior_na_step\n      th0 th1 tr\n      (STEP: SeqThread.na_step state_step MachineEvent.silent th0 th1)\n      (BEHAVIOR: behavior th1 tr)\n    :\n      behavior th0 tr\n  | behavior_at_step\n      e i o th0 th1 es st\n      (STEP: SeqThread.at_step e i o th0 th1)\n      (BEHAVIOR: behavior th1 (es, st))\n    :\n      behavior th0 ((e, i, o)::es, st)\n  .\nEnd LANG.\n\nDefinition refine\n           (lang_tgt lang_src: language)\n           (st_tgt: lang_tgt.(Language.state)) (st_src: lang_src.(Language.state))\n  : Prop :=\n  forall p m o (WF: Oracle.wf o),\n    SeqTrace.incl\n      (behavior (@SeqState.na_step _) (SeqThread.mk (SeqState.mk _ st_tgt m) p o))\n      (behavior (@SeqState.na_step _) (SeqThread.mk (SeqState.mk _ st_src m) p o)).\nEnd SeqBehavior.\n\n\nSection DETERMINISM.\n  Variable lang: language.\n\n  Definition similar (e0 e1: ProgramEvent.t): Prop :=\n    match e0, e1 with\n    | ProgramEvent.read loc0 val0 ord0, ProgramEvent.read loc1 val1 ord1 =>\n      loc0 = loc1 /\\ ord0 = ord1\n    | ProgramEvent.write loc0 val0 ord0, ProgramEvent.write loc1 val1 ord1 =>\n      loc0 = loc1 /\\ ord0 = ord1 /\\ val0 = val1\n    | ProgramEvent.update loc0 valr0 valw0 ordr0 ordw0, ProgramEvent.update loc1 valr1 valw1 ordr1 ordw1 =>\n      loc0 = loc1 /\\ ordr0 = ordr1 /\\ ordw0 = ordw1 /\\ (valr0 = valr1 -> valw0 = valw1)\n    | ProgramEvent.read loc0 val0 ord0, ProgramEvent.update loc1 valr1 valw1 ordr1 ordw1 =>\n      loc0 = loc1 /\\ ord0 = ordr1 /\\ val0 <> valr1\n    | ProgramEvent.update loc0 valr0 valw0 ordr0 ordw0, ProgramEvent.read loc1 val1 ord1 =>\n      loc0 = loc1 /\\ ordr0 = ord1 /\\ valr0 <> val1\n    | ProgramEvent.fence ordr0 ordw0, ProgramEvent.fence ordr1 ordw1 =>\n      ordr0 = ordr1 /\\ ordw0 = ordw1\n    | _, _ => e0 = e1\n    end.\n\n  Lemma similar_le_eq\n        e1 e2 e\n        (SIMILAR: similar e1 e2)\n        (LE1: ProgramEvent.le e e1)\n        (LE2: ProgramEvent.le e e2):\n    e1 = e2.\n  Proof.\n    destruct e1, e2, e; ss.\n    - inv LE1. inv LE2. ss.\n    - des. subst. ss.\n    - des. subst. exploit SIMILAR2; eauto. i. subst. ss.\n    - inv LE1. inv LE2. ss.\n  Qed.\n\n  Variant _deterministic (deterministic: lang.(Language.state) -> Prop) (st0: lang.(Language.state)): Prop :=\n  | deterministic_intro\n      (PRESERVE:\n         forall e st1 (STEP: lang.(Language.step) e st0 st1),\n           deterministic st1)\n      (STEP_TERMINAL:\n         forall e st1 (STEP: lang.(Language.step) e st0 st1)\n                (TERMINAL: lang.(Language.is_terminal) st0), False)\n      (STEP_STEP:\n         forall e1 st1 (STEP1: lang.(Language.step) e1 st0 st1)\n                e2 st2 (STEP2: lang.(Language.step) e2 st0 st2),\n           similar e1 e2 /\\ (e1 = e2 -> st1 = st2))\n      (NO_NA_UPDATE:\n         forall loc valr valw ordr ordw st1\n           (STEP: lang.(Language.step) (ProgramEvent.update loc valr valw ordr ordw) st0 st1),\n           Ordering.le Ordering.plain ordr /\\ Ordering.le Ordering.plain ordw)\n  .\n\n  Lemma deterministic_mon: monotone1 _deterministic.\n  Proof.\n    ii. inv IN. econs; eauto.\n  Qed.\n  Hint Resolve deterministic_mon: paco.\n\n  Definition deterministic := paco1 _deterministic bot1.\nEnd DETERMINISM.\n#[export] Hint Resolve deterministic_mon: paco.\n\nLemma deterministic_step\n      lang e1 e2 st st1 st2\n      (DETERM: deterministic lang st)\n      (STEP1: lang.(Language.step) e1 st st1)\n      (STEP2: lang.(Language.step) e2 st st2):\n  similar e1 e2 /\\ (e1 = e2 -> st1 = st2).\nProof.\n  punfold DETERM. inv DETERM. eauto.\nQed.\n\nLemma deterministic_terminal\n      lang e st1 st2\n      (DETERM: deterministic lang st1)\n      (STEP: lang.(Language.step) e st1 st2)\n      (TERMINAL: lang.(Language.is_terminal) st1):\n  False.\nProof.\n  punfold DETERM. inv DETERM. eauto.\nQed.\n\nLemma step_deterministic\n      lang e st0 st1\n      (DETERM: deterministic lang st0)\n      (STEP: lang.(Language.step) e st0 st1):\n  deterministic lang st1.\nProof.\n  punfold DETERM. inv DETERM.\n  exploit PRESERVE; eauto. intros x. inv x; done.\nQed.\n\n\nDefinition monotone_read_state lang (st: lang.(Language.state)): Prop :=\n  forall p m o (WF: Oracle.wf o),\n    SeqBehavior.behavior (@SeqState.na_step _) (SeqThread.mk (SeqState.mk _ st m) p o) <1= SeqBehavior.behavior (@SeqState.na_step_determ _) (SeqThread.mk (SeqState.mk _ st m) p o).\n\n\nSection RECEPTIVE.\n  Variable lang: language.\n\n  Variant _receptive (receptive: lang.(Language.state) -> Prop) (st0: lang.(Language.state)): Prop :=\n  | receptive_intro\n      (PRESERVE:\n         forall e st1 (STEP: lang.(Language.step) e st0 st1),\n           receptive st1)\n      (READ:\n         forall loc val ord st1\n           (STEP: lang.(Language.step) (ProgramEvent.read loc val ord) st0 st1),\n         forall val',\n           (exists st1', lang.(Language.step) (ProgramEvent.read loc val' ord) st0 st1') \\/\n           (exists valw ordw st1',\n               lang.(Language.step) (ProgramEvent.update loc val' valw ord ordw) st0 st1'))\n      (UPDATE:\n         forall loc valr valw ordr ordw st1\n           (STEP: lang.(Language.step) (ProgramEvent.update loc valr valw ordr ordw) st0 st1),\n         forall val',\n           (exists st1', lang.(Language.step) (ProgramEvent.read loc val' ordr) st0 st1') \\/\n           (exists valw' st1',\n               lang.(Language.step) (ProgramEvent.update loc val' valw' ordr ordw) st0 st1'))\n      (NO_NA_UPDATE:\n         forall loc valr valw ordr ordw st1\n           (STEP: lang.(Language.step) (ProgramEvent.update loc valr valw ordr ordw) st0 st1),\n           Ordering.le Ordering.plain ordr /\\ Ordering.le Ordering.plain ordw)\n  .\n\n  Lemma receptive_mon: monotone1 _receptive.\n  Proof.\n    ii. inv IN. econs; eauto.\n  Qed.\n  Hint Resolve receptive_mon: paco.\n\n  Definition receptive := paco1 _receptive bot1.\nEnd RECEPTIVE.\n#[export] Hint Resolve receptive_mon: paco.\n\nDefinition wsimilar (e0 e1: ProgramEvent.t): Prop :=\n  match e0, e1 with\n  | ProgramEvent.read loc0 val0 ord0, ProgramEvent.read loc1 val1 ord1 =>\n    loc0 = loc1 /\\ ord0 = ord1\n  | ProgramEvent.write loc0 val0 ord0, ProgramEvent.write loc1 val1 ord1 =>\n    loc0 = loc1 /\\ ord0 = ord1 /\\ val0 = val1\n  | ProgramEvent.update loc0 valr0 valw0 ordr0 ordw0, ProgramEvent.update loc1 valr1 valw1 ordr1 ordw1 =>\n    loc0 = loc1 /\\ ordr0 = ordr1 /\\ ordw0 = ordw1\n  | ProgramEvent.read loc0 val0 ord0, ProgramEvent.update loc1 valr1 valw1 ordr1 ordw1 =>\n    loc0 = loc1 /\\ ord0 = ordr1\n  | ProgramEvent.update loc0 valr0 valw0 ordr0 ordw0, ProgramEvent.read loc1 val1 ord1 =>\n    loc0 = loc1 /\\ ordr0 = ord1\n  | ProgramEvent.fence ordr0 ordw0, ProgramEvent.fence ordr1 ordw1 =>\n    ordr0 = ordr1 /\\ ordw0 = ordw1\n  | _, _ => e0 = e1\n  end.\n\nLemma similar_wsimilar\n      e1 e2\n      (SIMILAR: similar e1 e2):\n  wsimilar e1 e2.\nProof.\n  destruct e1, e2; ss; des; subst; ss.\nQed.\n\nLemma receptive_oracle_progress\n      lang e st1 st2\n      orc1\n      (RECEPTIVE: receptive _ st1)\n      (ORACLE: Oracle.wf orc1)\n      (STEP: lang.(Language.step) e st1 st2)\n      (ATOMIC: is_atomic_event e):\n  exists e' st2',\n    (<<EVENT: wsimilar e e'>>) /\\\n    (<<STEP: lang.(Language.step) e' st1 st2'>>) /\\\n    (<<ATOMIC: is_atomic_event e'>>) /\\\n    (<<PROGRESS: Oracle.progress e' orc1>>).\nProof.\n  punfold RECEPTIVE. inv RECEPTIVE.\n  punfold ORACLE. inv ORACLE.\n  destruct e; ss.\n  - specialize (LOAD loc ord). des.\n    exploit READ; eauto. i. des.\n    + esplits; eauto. ss.\n    + exploit NO_NA_UPDATE; eauto. i. des.\n      esplits; eauto; ss.\n      destruct ord, ordw; ss.\n  - specialize (STORE loc ord val).\n    esplits; try exact STORE; eauto. ss.\n  - specialize (LOAD loc ordr). des.\n    exploit UPDATE; eauto. i. des.\n    + esplits; eauto. ss. destruct ordr; ss.\n    + exploit NO_NA_UPDATE; eauto. i. des.\n      esplits; eauto; ss.\n  - specialize (FENCE ordr ordw).\n    esplits; try exact FENCE; eauto. ss.\n  - esplits; try apply SYSCALL; eauto.\nQed.\n\nLemma step_receptive\n      lang e st1 st2\n      (RECEPTIVE: receptive lang st1)\n      (STEP: lang.(Language.step) e st1 st2):\n  receptive _ st2.\nProof.\n  punfold RECEPTIVE. inv RECEPTIVE.\n  exploit PRESERVE; eauto. intros x. inv x; 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/sequential/SequentialBehavior.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.28077720055597283}}
{"text": "Require Import QuickChick.\n\nClass liftable (A B : Type) :=\n  {\n    lift_m : A -> B \n  }.\n\nInstance lift0 {A} : liftable (G A) (G A) :=\n  { \n    lift_m := id \n  }.\n\nInstance liftN {A B R} `(liftable (G B) R) : liftable (G (A -> B)) (G A -> R):=\n   { \n     lift_m f ga := \n       lift_m (liftGen2 id f ga) \n   }.\n\nDefinition liftM {A B R} `{liftable (G B) R} (f : A -> B) (g : G A) : R :=\n  lift_m (fmap f g).\n\nDefinition ex1 : G nat := liftM (fun x => x + 3) (returnGen 0).\nDefinition ex2 : G nat := liftM (fun x y => x + y) (returnGen 0) (returnGen 1).\nDefinition ex3 : G nat := liftM (fun x y z => x + y + z)\n                                (returnGen 0) (returnGen 1) (returnGen 2).\n\n(*\nEval cbv -[plus] in ex1.\n(* = fmap (fun x : nat => x + 3) (returnGen 0) -- fair enough *)\n\nEval cbv -[plus] in ex2.\n(* = liftGen2 id (fmap (fun x y : nat => x + y) (returnGen 0)) (returnGen 1)\nwhere\nfmap : (nat -> (nat -> nat)) -> G nat -> G (nat -> nat)\nliftGen2 : ((nat -> nat) -> nat -> nat) ->\n            (G (nat -> nat)) -> G nat -> G nat\n *)\n\nEval cbv -[plus] in ex3.\n(* = liftGen2 (fun x : nat -> nat => x)\n         (liftGen2 (fun x : nat -> nat -> nat => x)\n            (fmap (fun x y z : nat => x + y + z) (returnGen 0)) \n            (returnGen 1)) (returnGen 2)\n*)\n\n(* this is not well typed ... wtf? *)\nCheck (liftM (fun x y => x + y + y) (returnGen 0) (returnGen 1) (returnGen 2)\n  : G nat).\n\n(* it's even worse ... all kinds of stuff are accepted in Check and Eval *)\nEval simpl in (liftM (fun x => x + 1) (returnGen 0) 0 0 : G nat).\n*)\n(*\nliftM nat nat (nat -> nat -> G nat) `{liftable (G nat) (nat -> nat -> G nat)} ...\n-- but we don't have such an instance!\nWe need to use definitions to get a type error\nDefinition xxx := (liftM (fun x => x + 1) (returnGen 0) 0 0 : G nat).\nToplevel input, characters 19-24:\nError: Cannot infer the implicit parameter H of\nliftM.\nCould not find an instance for \"liftable (G nat) (nat -> nat -> G nat)\".\n*)\n", "meta": {"author": "mpstepan", "repo": "QC-631-Final", "sha": "4cbf25da5bd57252767e13c43cb20acb324178ee", "save_path": "github-repos/coq/mpstepan-QC-631-Final", "path": "github-repos/coq/mpstepan-QC-631-Final/QC-631-Final-4cbf25da5bd57252767e13c43cb20acb324178ee/src/LiftGenClass.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.28076885850161}}
{"text": "Require Import Lang.BindingsFacts.\nRequire Import Lang.Sig.\nRequire Import Lang.SigFacts.\nRequire Import Rel.Definitions.\nSet Implicit Arguments.\n\nSection section_compat_val.\n\nContext (EV LV V : Set).\nContext (Ξ : XEnv EV LV).\nContext (Γ : V → ty ∅ EV LV ∅).\n\nLemma compat_val_unit n :\nn ⊨ ⟦ Ξ Γ ⊢ val_unit ≼ˡᵒᵍᵥ val_unit : 𝟙 ⟧.\nProof.\nrepeat iintro ; crush.\nQed.\n\nLemma compat_val_var n x :\nn ⊨ ⟦ Ξ Γ ⊢ (val_var x) ≼ˡᵒᵍᵥ (val_var x) : (Γ x) ⟧.\nProof.\niintro ξ₁ ; iintro ξ₂ ;\niintro δ₁ ; iintro δ₂ ; iintro δ ;\niintro ρ₁ ; iintro ρ₂ ; iintro ρ ;\niintro γ₁ ; iintro γ₂ ;\niintro Hξ ; iintro Hδ ; iintro Hρ ; iintro Hγ.\niespecialize Hγ ; apply Hγ.\nQed.\n\nLemma compat_val_md n m₁ m₂ σ X :\nn ⊨ ⟦ Ξ Γ ⊢ m₁ ≼ˡᵒᵍₘ m₂ : σ ^ (lbl_id (lid_f X)) ⟧ →\nn ⊨ ⟦ Ξ Γ ⊢ (val_md m₁ (lid_f X)) ≼ˡᵒᵍᵥ (val_md m₂ (lid_f X)) :\n      ty_ms σ (lbl_id (lid_f X)) ⟧.\nProof.\nintro H.\niintro ξ₁ ; iintro ξ₂ ;\niintro δ₁ ; iintro δ₂ ; iintro δ ;\niintro ρ₁ ; iintro ρ₂ ; iintro ρ ;\niintro γ₁ ; iintro γ₂ ;\niintro Hξ ; iintro Hδ ; iintro Hρ ; iintro Hγ.\niespecialize H.\nispecialize H ; [ eassumption | ].\nispecialize H ; [ eassumption | ].\nispecialize H ; [ eassumption | ].\nispecialize H ; [ eassumption | ].\nsimpl 𝓥_Fun ; repeat ieexists ; repeat isplit.\n* iintro_prop ; crush.\n* iintro_prop ; crush.\n* apply H.\nQed.\n\nLemma compat_val_fix n m₁ m₂ N X :\nn ⊨ ▷ ⟦ Ξ (env_ext Γ (ty_it N (lbl_id (lid_f X)))) ⊢ m₁ ≼ˡᵒᵍₘ m₂ : (it_msig N) ^ (lbl_id (lid_f X)) ⟧ →\nn ⊨ ⟦ Ξ Γ ⊢ (val_fix m₁ (lid_f X)) ≼ˡᵒᵍᵥ (val_fix m₂ (lid_f X)) :\n      ty_it N (lbl_id (lid_f X)) ⟧.\nProof.\nintro H.\niintro ξ₁ ; iintro ξ₂ ;\niintro δ₁ ; iintro δ₂ ; iintro δ ;\niintro ρ₁ ; iintro ρ₂ ; iintro ρ ;\niintro γ₁ ; iintro γ₂ ;\niintro Hξ ; iintro Hδ ; iintro Hρ ; iintro Hγ.\nloeb_induction LöbIH.\napply I_later_forall_down in H ; ispecialize H ξ₁ ;\napply I_later_forall_down in H ; ispecialize H ξ₂.\napply I_later_forall_down in H ; ispecialize H δ₁ ;\napply I_later_forall_down in H ; ispecialize H δ₂ ;\napply I_later_forall_down in H ; ispecialize H δ.\napply I_later_forall_down in H ; ispecialize H ρ₁ ;\napply I_later_forall_down in H ; ispecialize H ρ₂ ;\napply I_later_forall_down in H ; ispecialize H ρ.\napply I_later_forall_down in H ; ispecialize H (\n  env_ext γ₁ (subst_val δ₁ ρ₁ γ₁ (val_fix m₁ (lid_f X)))\n).\napply I_later_forall_down in H ; ispecialize H (\n  env_ext γ₂ (subst_val δ₂ ρ₂ γ₂ (val_fix m₂ (lid_f X)))\n).\napply I_later_arrow_down in H ; ispecialize H.\n{ iintro_later ; eassumption. }\napply I_later_arrow_down in H ; ispecialize H.\n{ iintro_later ; eassumption. }\napply I_later_arrow_down in H ; ispecialize H.\n{ iintro_later ; eassumption. }\napply I_later_arrow_down in H ; ispecialize H.\n{\n  later_shift.\n  iintro x ; destruct x as [ | x ]  ; simpl 𝜞 ; simpl env_ext.\n  + apply LöbIH.\n  + iespecialize Hγ ; apply Hγ.\n}\n\nclear - H.\nsimpl 𝓥_Fun.\nrepeat ieexists ; repeat isplit ; [ auto | auto | ].\nlater_shift.\napply 𝓥_roll ; simpl 𝓥_Fun.\nrepeat ieexists ; repeat isplit ; [ auto | auto | ].\nsimpl subst_md in H.\nrepeat erewrite V_bind_bind_md.\n{ apply H. }\n{\n  intro x ; destruct x as [|x] ; simpl ; [ auto | ].\n  erewrite V_bind_map_val, V_map_val_id, V_bind_val_id ; crush.\n}\n{\n  intro x ; destruct x as [|x] ; simpl ; [ auto | ].\n  erewrite V_bind_map_val, V_map_val_id, V_bind_val_id ; crush.\n}\nQed.\n\nLemma compat_val_ktx n K₁ K₂ Ta Ea Tb Eb  :\nn ⊨ ⟦ Ξ Γ ⊢ K₁ ≼ˡᵒᵍ K₂ : Ta # Ea ⇢ Tb # Eb ⟧ →\nn ⊨ ⟦ Ξ Γ ⊢ (val_cont K₁) ≼ˡᵒᵍᵥ (val_cont K₂) : ty_cont Ta Ea Tb Eb ⟧.\nProof.\nintro H.\niintro ξ₁ ; iintro ξ₂ ;\niintro δ₁ ; iintro δ₂ ; iintro δ ;\niintro ρ₁ ; iintro ρ₂ ; iintro ρ ;\niintro γ₁ ; iintro γ₂ ;\niintro Hξ ; iintro Hδ ; iintro Hρ ; iintro Hγ.\niespecialize H.\nispecialize H ; [ eassumption | ].\nispecialize H ; [ eassumption | ].\nispecialize H ; [ eassumption | ].\nispecialize H ; [ eassumption | ].\nsimpl 𝓥_Fun ; repeat ieexists ; repeat isplit.\n* iintro_prop ; crush.\n* apply H.\nQed.\n\nEnd section_compat_val.\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_val.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2807688518733585}}
{"text": "Require Export Prelude.\nRequire Import Psatz.\nRequire Import TLC.LibLN.\nRequire Import TLC.LibEnv.\nRequire Import Infrastructure.\nRequire Export Notations.\nRequire Export Regularity.\nRequire Export Regularity2.\n\nLtac fs := exact \\{}.\n\nLtac ininv :=\n  match goal with\n  | H: List.In _ _ |- _ =>\n    inversions H\n  end.\n\nLtac destruct_const_len_list :=\n  repeat (match goal with\n          | H: length ?L = ?n |- _ =>\n            destruct L; inversions H\n          end).\n\nLtac binds_inv :=\n  match goal with\n  | H: binds ?x ?a empty |- _ =>\n    apply binds_empty_inv in H; contradiction\n  | H: binds ?x ?a ?E |- _ =>\n    binds_cases H;\n    try match goal with\n        | H: binds ?x ?a empty |- _ =>\n          apply binds_empty_inv in H; contradiction\n        end;\n    subst\n  | |- ?x \\notin \\{ ?y } =>\n    apply* notin_inverse\n  end.\n\nLtac solve_dom all_distinct :=\n  simpl_dom; notin_solve; try (apply notin_singleton; lets*: all_distinct).\n\nLtac distinct2 :=\n  match goal with\n  | H1: DistinctList ?L |- _ =>\n    inversions H1;\n    match goal with\n    | H2: ~ List.In ?v ?L1 |- _ =>\n      cbn in H2; eauto\n    end\n  end.\n\nLtac solve_bind_core :=\n  lazymatch goal with\n  | |- binds ?Var ?What (?Left & ?Right) =>\n    match goal with\n    | |- binds Var What (Left & Var ~ ?Sth) =>\n      apply* binds_concat_right; apply* binds_single_eq\n    | _ => apply* binds_concat_left\n    end\n  end.\n\nLtac solve_bind :=\n  (repeat solve_bind_core); try (solve_dom).\n\nExport Definitions.\nExport Psatz.\nExport TLC.LibLN.\nExport TLC.LibEnv.\nExport Infrastructure. (* TODO only the gathering parts, should be split out *)\n\nInductive evals : trm -> trm -> Prop :=\n| eval_step : forall a b c, a --> b -> evals b c -> evals a c\n| eval_finish : forall a, evals a a.\n\nLemma is_var_defined_split : forall A B c, (is_var_defined A c \\/ is_var_defined B c) -> is_var_defined (A |,| B) c.\n  unfold is_var_defined.\n  intros.\n  apply List.in_or_app.\n  destruct H; auto.\nQed.\n\nLtac autotyper1 :=\n  repeat progress (\n           cbn;\n           match goal with\n           | [ H: False |- _ ] => false*\n           | [ |- ok ?A ] => econstructor\n           | [ |- okt ?A ?B ?C ] => econstructor\n           | [ |- binds ?A ?B ?C ] => solve_bind\n           | [ |- ?A \\notin ?B ] => simpl_dom; notin_solve; try (apply notin_singleton)\n           | [ |- typing ?TT ?A ?B ?C ?D ?E ] => econstructor\n           | [ |- forall x, x \\notin ?L -> ?P ] =>\n             let free := gather_vars in\n             let x' := fresh \"x\" in\n             let xiL := fresh \"xiL\" in\n             intros x' xiL; intros;\n             try instantiate (1 := free) in xiL\n           | [ |- okGadt empty ] => econstructor\n           | [ |- wft ?A ?B ?C ] => econstructor\n           | [ |- value ?A ] => econstructor\n           | [ |- term ?A ] => econstructor\n           | [ |- type ?A ] => econstructor\n           | [ H: binds ?A ?B ?C |- _ ] => binds_inv\n           | [ |- ?A /\\ ?B ] => split\n           | [ H: {| Tarity := ?A; Tconstructors := ?B |} = ?C |- _ ] =>\n             inversions H\n           | [ H: ?A \\/ ?B |- _ ] => destruct H\n           | [ |- is_var_defined (?A |,| ?B) ?c ] => apply is_var_defined_split\n           | _ => intros; auto\n           end;\n           cbn; subst).\n\n(* TODO merge with autotyper1 *)\nLtac autotyper0 :=\n  repeat progress (\n           cbn;\n           match goal with\n           | [ H: False |- _ ] => false*\n           | [ |- ok ?A ] => econstructor\n           | [ |- okt ?A ?B ?C ] => econstructor\n           | [ |- binds ?A ?B ?C ] => solve_bind\n           | [ |- ?A \\notin ?B ] => simpl_dom; notin_solve; try (apply notin_singleton)\n           | [ |- forall x, x \\notin ?L -> ?P ] =>\n             let free := gather_vars in\n             let x' := fresh \"x\" in\n             let xiL := fresh \"xiL\" in\n             intros x' xiL; intros;\n             try instantiate (1 := free) in xiL\n           | [ |- okGadt empty ] => econstructor\n           | [ |- wft ?A ?B ?C ] => econstructor\n           | [ |- value ?A ] => econstructor\n           | [ |- term ?A ] => econstructor\n           | [ |- type ?A ] => econstructor\n           | [ H: binds ?A ?B ?C |- _ ] => binds_inv\n           | [ |- ?A /\\ ?B ] => split\n           | [ H: {| Tarity := ?A; Tconstructors := ?B |} = ?C |- _ ] =>\n             inversions H\n           | [ H: ?A \\/ ?B |- _ ] => destruct H\n           | [ |- is_var_defined (?A |,| ?B) ?c ] => apply is_var_defined_split\n           | _ => intros; auto\n           end;\n           cbn; subst).\n\nLemma neq_from_notin : forall (A : Type) (x y : A), x \\notin \\{ y } -> x <> y.\n  intros.\n  intro HF.\n  subst.\n  apply* notin_same.\nQed.\n\nLtac autotyper2 :=\n  repeat progress (\n           cbn;\n           let free := gather_vars in\n           let x' := fresh \"x\" in\n           let xiL := fresh \"xiL\" in\n           match goal with\n           | [ H: False |- _ ] => false*\n           | [ |- ok ?A ] => econstructor\n           | [ |- okt ?A ?B ?C ] => econstructor\n           | [ |- binds ?A ?B ?C ] => solve_bind\n           | [ |- typing ?TT ?A ?B ?C (trm_unit) ?E ] => eapply typing_unit\n           | [ |- typing ?TT ?A ?B ?C (trm_fvar ?k ?X) ?E ] => eapply typing_var with (vk:=k)\n           | [ |- typing ?TT ?A ?B ?C (trm_constructor ?Ts ?N ?e) ?E ] => eapply typing_cons\n           | [ |- typing ?TT ?A ?B ?C (trm_abs ?T ?e) ?E ] => eapply typing_abs with (L:=free)\n           | [ |- typing ?TT ?A ?B ?C (trm_tabs ?e) ?E ] => eapply typing_tabs with (L:=free)\n           | [ |- typing ?TT ?A ?B ?C (trm_app ?e1 ?e2) ?E ] => eapply typing_app\n           | [ |- typing ?TT ?A ?B ?C (trm_tapp ?e1 ?T) ?E ] => eapply typing_tapp\n           | [ |- typing ?TT ?A ?B ?C (trm_tuple ?e1 ?e2) ?E ] => eapply typing_tuple\n           | [ |- typing ?TT ?A ?B ?C (trm_fst ?e1) ?E ] => eapply typing_fst\n           | [ |- typing ?TT ?A ?B ?C (trm_snd ?e1) ?E ] => eapply typing_snd\n           | [ |- typing ?TT ?A ?B ?C (trm_fix ?T ?e) ?E ] => eapply typing_fix with (L:=free)\n           | [ |- typing ?TT ?A ?B ?C (trm_let ?e1 ?e2) ?E ] => eapply typing_let with (L:=free)\n           | [ |- typing ?TT ?A ?B ?C (trm_matchgadt ?e1 ?N ?ms) ?E ] => eapply typing_case with (L:=free)\n           | [ |- ?A \\notin ?B ] => simpl_dom; notin_solve; try (apply notin_singleton)\n           | [ |- forall x, x \\notin ?L -> ?P ] =>\n             let free := gather_vars in\n             let x' := fresh \"x\" in\n             let xiL := fresh \"xiL\" in\n             intros x' xiL; intros;\n             try instantiate (1 := free) in xiL\n           | [ |- okGadt empty ] => econstructor\n           | [ |- wft ?A ?B ?C ] => econstructor\n           | [ |- value ?A ] => econstructor\n           | [ |- term ?A ] => econstructor\n           | [ |- type ?A ] => econstructor\n           | [ H: binds ?A ?B ?C |- _ ] => binds_inv\n           | [ |- ?A /\\ ?B ] => split\n           | [ H: {| Tarity := ?A; Tconstructors := ?B |} = ?C |- _ ] =>\n             inversions H\n           | [ H: ?A \\/ ?B |- _ ] => destruct H\n           | [ H: ?C = (?A, ?B) |- _ ] => inversions H\n           | [ H: (?A, ?B) = ?C |- _ ] => inversions H\n           | [ |- is_var_defined (?A |,| ?B) ?c ] => apply is_var_defined_split\n           | _ => intros; auto\n           end;\n           cbn; subst).\n\nLtac autotyper3 :=\n  autotyper2; cbn in *;\n  destruct_const_len_list; cbn; autotyper2.\n\nLtac autotyper4 :=\n  autotyper3;\n  try solve [left~ | repeat right~].\n\nLemma Forall2_eq : forall A B (f : A -> B) Ts Us,\n    List.length Ts = List.length Us ->\n    (forall T U, List.In (T, U) (zip Ts Us) -> f T = f U) ->\n    List.map f Ts =\n    List.map f Us.\n  induction Ts as [ | T Ts]; destruct Us as [ | U Us]; intros Len F; cbn in *; inversion Len.\n  - auto.\n  - f_equal; auto.\nQed.\n\nLemma eq_typ_gadt : forall Σ Δ Ts Us N,\n    List.Forall2 (fun T U => entails_semantic Σ Δ (T ≡ U)) Ts Us ->\n    entails_semantic Σ Δ (typ_gadt Ts N ≡ typ_gadt Us N).\n  introv FF.\n  cbn in *.\n  apply F2_iff_In_zip in FF.\n  destruct FF.\n  intros O M.\n  repeat rewrite subst_tt_prime_reduce_typ_gadt.\n  f_equal.\n  apply~ Forall2_eq.\nQed.\n\nLtac ininv2 :=\n  match goal with\n  | H: List.In _ _ |- _ =>\n    inversions H\n  | [ H: ?C = (?A, ?B) |- _ ] => inversions H\n  | [ H: (?A, ?B) = ?C |- _ ] => inversions H\n  end.\n\nLemma eq_typ_tuple : forall Σ Δ A B C D,\n    entails_semantic Σ Δ (A ≡ C) ->\n    entails_semantic Σ Δ (B ≡ D) ->\n    entails_semantic Σ Δ ((A ** B) ≡ (C ** D)).\n  introv EQ1 EQ2.\n  cbn in *.\n  intros O M.\n  repeat rewrite subst_tt_prime_reduce_tuple.\n  f_equal; 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/TestCommon.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2807688518733584}}
{"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_Ф_onBounce (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\nImport TVMModel.LedgerClass.\nOpaque roundStepEqb. \n\nLemma letIf: forall X Y (b: bool) (f g: X*Ledger) (h: X -> Ledger -> Y), \n(let (x, t) := if b then f else g in h x t)=\nif b then let (x, t) := f in h x t else\n          let (x, t) := g in h x t .\nProof.\n  intros.\n  destruct b; auto.\nQed.\n\nLemma matchIf: forall X (b: bool) (f g: LedgerT X) (l: Ledger), \n(match (if b then f else g) with | SimpleState c => c end l)=\nif b then match f with | SimpleState c => c end l else \nmatch g with | SimpleState c => c end l.\nProof.\n  intros.\n  destruct b; auto.\nQed.\n\n\n\nLemma DePoolContract_Ф_onBounce_exec : forall (l : Ledger) (body : TvmSlice),\n\nlet (functionId, body') := decode_uint32 body in\nlet process_new_stake_id := tvm_functionId IProxy_И_process_new_stakeF in \nlet recover_stake_id := tvm_functionId IProxy_И_recover_stakeF in \n\nlet (roundId, _) := decode_uint64 body' in\nlet optRound := eval_state (↓ RoundsBase_Ф_fetchRound roundId) l in\nlet round := maybeGet optRound in\nlet roundFound : bool := isSome optRound in\nlet isRound1 : bool := eval_state (↓ RoundsBase_Ф_isRound1 roundId) l in\nlet isRound2 : bool := eval_state (↓ RoundsBase_Ф_isRound2 roundId) l in \nlet step := RoundsBase_ι_Round_ι_step round in\nlet step_wsa : bool := eqb step RoundsBase_ι_RoundStepP_ι_WaitingIfStakeAccepted in\nlet step_wr : bool := eqb step RoundsBase_ι_RoundStepP_ι_WaitingReward in\nlet step_wwe : bool := eqb step RoundsBase_ι_RoundStepP_ι_WaitingIfValidatorWinElections in\n\nlet oldEvents := eval_state ( ↑16 ε VMState_ι_events ) l in\nlet queryId := DePoolLib_ι_Request_ι_queryId (RoundsBase_ι_Round_ι_validatorRequest round) in\nlet l_emit1 := {$ l With VMState_ι_events := ProxyHasRejectedTheStake queryId :: oldEvents $} in\nlet l_emit2 := {$ l With VMState_ι_events := ProxyHasRejectedRecoverRequest roundId :: oldEvents $} in\n\nlet isProcessNewStake := functionId =? process_new_stake_id in\nlet isRecoverStake := functionId =? recover_stake_id in\nlet round_pns := \n    {$ round with (RoundsBase_ι_Round_ι_step , RoundsBase_ι_RoundStepP_ι_WaitingValidatorRequest) $} in\nlet round_recover_1 :=\n    {$ round with (RoundsBase_ι_Round_ι_step , RoundsBase_ι_RoundStepP_ι_WaitingValidationStart) $} in\nlet round_recover_2 :=\n    {$ round with (RoundsBase_ι_Round_ι_step , RoundsBase_ι_RoundStepP_ι_WaitingUnfreeze) $} in \n\nexec_state (↓ DePoolContract_Ф_onBounce body) l = \n\nif (isProcessNewStake || isRecoverStake)%bool then \n    if (isProcessNewStake) then \n        if isRound1 then \n            if roundFound then \n                if step_wsa then exec_state (↓ RoundsBase_Ф_setRound roundId round_pns) l_emit1 \n                            else l\n            else l\n        else l\n    else \n        if isRound2 then \n            if roundFound then \n                if step_wr then exec_state (↓ RoundsBase_Ф_setRound roundId round_recover_2) l_emit2\n                else l\n            else l\n        else if isRound1 then \n                if roundFound then\n                    if step_wwe then exec_state (↓ RoundsBase_Ф_setRound roundId round_recover_1) l_emit2\n                    else l\n                else l\n        else injEmbed (VMState_ι_savedDePoolContracts (Ledger_ι_VMState l)) l    \nelse  l.\n\nProof.\n\n  intros.\n  destructLedger l. \n  compute.\n\n  all: destruct (decode_uint32 body). idtac.\n  all: destruct (decode_uint64 t). idtac.\n\n\n  repeat rewrite matchIf.  idtac.\n  repeat rewrite letIf.  idtac.\n  repeat rewrite matchIf.  idtac.\n  repeat rewrite letIf.  idtac.\n  repeat rewrite matchIf.  idtac.\n  repeat rewrite letIf.  idtac.\n\n  \n\n  Time repeat destructIf_solve.  idtac.\n\n  all: try setoid_rewrite H3 in H4; try discriminate. idtac.\n  all: try setoid_rewrite H4 in H5; try discriminate.\n(* Require Import depoolContract.Lib.CommonStateProofs.\n\napply ledgerEq; simpl; auto.\napply RoundsBaseEq; simpl; auto.\nremember (match hmapLookup Z.eqb x0 RoundsBase_ι_m_rounds with\n  | Some x1 => x1\n  | None => default\nend) as rx0.\nsetoid_rewrite <- Heqrx0.\ndestruct rx0; auto. *)\nQed.    \n\n\n\n\nLemma DePoolContract_Ф_onBounce_eval : forall (l : Ledger) (body : TvmSlice),\n\nlet (functionId, body') := decode_uint32 body in\nlet process_new_stake_id := tvm_functionId IProxy_И_process_new_stakeF in \nlet recover_stake_id := tvm_functionId IProxy_И_recover_stakeF in \nlet (roundId, _) := decode_uint64 body' in\nlet optRound := eval_state (↓ RoundsBase_Ф_fetchRound roundId) l in\nlet round := maybeGet optRound in\nlet roundFound : bool := isSome optRound in\nlet isRound1 : bool := eval_state (↓ RoundsBase_Ф_isRound1 roundId) l in\nlet isRound2 : bool := eval_state (↓ RoundsBase_Ф_isRound2 roundId) l in \nlet step := RoundsBase_ι_Round_ι_step round in\nlet step_wsa : bool := roundStepEqb step RoundsBase_ι_RoundStepP_ι_WaitingIfStakeAccepted in\nlet step_wr : bool := roundStepEqb step RoundsBase_ι_RoundStepP_ι_WaitingReward in\nlet step_wwe : bool := roundStepEqb step RoundsBase_ι_RoundStepP_ι_WaitingIfValidatorWinElections in\nlet isProcessNewStake := eqb functionId  process_new_stake_id in\nlet isRecoverStake := eqb functionId  recover_stake_id in\n\neval_state (DePoolContract_Ф_onBounce body) l = \n\nif (isProcessNewStake || isRecoverStake)%bool then \n    if (isProcessNewStake) then \n        if isRound1 then \n            if roundFound then \n                if step_wsa then Value I \n                            else Error InternalErrors_ι_ERROR525\n            else Error InternalErrors_ι_ERROR519\n        else Error InternalErrors_ι_ERROR524\n    else \n        if isRound2 then \n            if roundFound then \n                if step_wr then Value I\n                else Error InternalErrors_ι_ERROR526\n            else Error InternalErrors_ι_ERROR519\n        else if isRound1 then \n                if roundFound then\n                    if step_wwe then Value I\n                    else Error InternalErrors_ι_ERROR527\n                else Error InternalErrors_ι_ERROR519\n        else Error InternalErrors_ι_ERROR528\nelse Value I.\nProof.\n\n  intros.\n  destructLedger l. \n  compute.\n\n  Time repeat destructIf_solve.  idtac.\n\n  all: destruct (decode_uint32 body). idtac.\n  all: destruct (decode_uint64 t). idtac.\n  all: try rewrite H. idtac.\n  all: try rewrite H0. idtac.\n  all: try rewrite H1. idtac.\n  all: try rewrite H2. idtac.\n  all: try rewrite H3; auto. idtac.\n  all: try rewrite H4; auto. \n  \nQed.  \n  \nEnd DePoolContract_Ф_onBounce.", "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_onBounce.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6584175139669998, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2806976031155708}}
{"text": "(*\n * © 2019 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     Morphisms\n     Eqdep\n.\n\nFrom SPICY Require Import\n     MyPrelude\n     Maps\n     Messages\n     Keys\n     Tactics\n     Automation\n     AdversaryUniverse\n     RealWorld\n     Simulation\n\n     Theory.KeysTheory\n.\n\nSet Implicit Arguments.\n\nLemma cipher_honestly_signed_honest_keyb_iff :\n  forall honestk c tf,\n    cipher_honestly_signed honestk c = tf <-> honest_keyb honestk (cipher_signing_key c) = tf.\nProof.\n  intros.\n  unfold cipher_honestly_signed, cipher_signing_key; split; destruct c; trivial.\nQed.\n\n(******************** CIPHER CLEANING *********************\n **********************************************************\n *\n * Function to clean ciphehrs and lemmas about it.\n *)\n\nSection CleanCiphers.\n  Import RealWorld.\n\n  Variable honestk : key_perms.\n\n  Lemma honest_cipher_filter_fn_proper :\n    Proper (eq  ==>  eq  ==>  eq) (honest_cipher_filter_fn honestk).\n  Proof.\n    solve_proper.\n  Qed.\n\n  Lemma honest_cipher_filter_fn_filter_proper :\n    Proper\n      ( eq  ==>  eq  ==>  Equal  ==>  Equal)\n      (fun (k : NatMap.Map.key) (e : cipher) (m : t cipher) => if honest_cipher_filter_fn honestk k e then m $+ (k, e) else m).\n  Proof.\n    unfold Proper, respectful;\n      unfold Equal; intros; apply map_eq_Equal in H1; subst; auto.\n  Qed.\n\n  Lemma honest_cipher_filter_fn_filter_transpose :\n    transpose_neqkey Equal\n       (fun (k : NatMap.Map.key) (e : cipher) (m : t cipher) => if honest_cipher_filter_fn honestk k e then m $+ (k, e) else m).\n  Proof.\n    unfold transpose_neqkey, Equal, honest_cipher_filter_fn, cipher_honestly_signed; intros.\n    cases e; cases e'; simpl;\n      repeat match goal with\n             | [ |- context[if ?cond then _ else _] ] => cases cond\n             | [ |- context[_ $+ (?k1,_) $? ?k2] ] => cases (k1 ==n k2); subst; clean_map_lookups\n             end; eauto.\n  Qed.\n\n  Lemma honest_cipher_filter_fn_filter_proper_eq :\n    Proper\n      ( eq  ==>  eq  ==>  eq  ==>  eq)\n      (fun (k : NatMap.Map.key) (e : cipher) (m : t cipher) => if honest_cipher_filter_fn honestk k e then m $+ (k, e) else m).\n  Proof.\n    solve_proper.\n  Qed.\n\n  Lemma honest_cipher_filter_fn_filter_transpose_eq :\n    transpose_neqkey eq\n       (fun (k : NatMap.Map.key) (e : cipher) (m : t cipher) => if honest_cipher_filter_fn honestk k e then m $+ (k, e) else m).\n  Proof.\n    unfold transpose_neqkey, honest_cipher_filter_fn, cipher_honestly_signed; intros.\n    cases e; cases e'; subst; simpl;\n      repeat match goal with\n             | [ |- context[if ?cond then _ else _] ] => cases cond\n             | [ |- context[_ $+ (?k1,_) $? ?k2] ] => cases (k1 ==n k2); subst; clean_map_lookups\n             end; eauto;\n        rewrite map_ne_swap; eauto.\n  Qed.\n\n  Hint Resolve\n       honest_cipher_filter_fn_proper\n       honest_cipher_filter_fn_filter_proper\n       honest_cipher_filter_fn_filter_transpose\n       honest_cipher_filter_fn_filter_proper_eq\n       honest_cipher_filter_fn_filter_transpose_eq\n  : core.\n\n  Lemma clean_ciphers_mapsto_iff : forall cs c_id c,\n      MapsTo c_id c (clean_ciphers honestk cs) <-> MapsTo c_id c cs /\\ honest_cipher_filter_fn honestk c_id c = true.\n  Proof.\n    intros.\n    apply filter_iff; eauto.\n  Qed.\n\n  Lemma clean_ciphers_inv :\n    forall c_id c cs,\n      (clean_ciphers honestk cs) $? c_id = Some c\n      -> cs $? c_id = Some c.\n  Proof.\n    intros.\n    rewrite <- find_mapsto_iff, clean_ciphers_mapsto_iff, find_mapsto_iff in H;\n      split_ands; assumption.\n  Qed.\n\n  Lemma clean_ciphers_keeps_honest_cipher :\n    forall c_id c cs,\n      cs $? c_id = Some c\n      -> honest_cipher_filter_fn honestk c_id c = true\n      -> clean_ciphers honestk cs $? c_id = Some c.\n  Proof.\n    intros.\n    rewrite <- find_mapsto_iff.\n    rewrite <- find_mapsto_iff in H.\n    apply clean_ciphers_mapsto_iff; intuition idtac.\n  Qed.\n\n  Lemma honest_key_not_cleaned : forall cs c_id c k,\n      cs $? c_id = Some c\n      -> k = cipher_signing_key c\n      -> honest_key honestk k\n      -> clean_ciphers honestk cs $? c_id = Some c.\n  Proof.\n    intros.\n    eapply clean_ciphers_keeps_honest_cipher; auto.\n    unfold honest_cipher_filter_fn, cipher_honestly_signed.\n    destruct c; subst.\n    + invert H. rewrite <- honest_key_honest_keyb; eauto.\n    + invert H. rewrite <- honest_key_honest_keyb; eauto.\n  Qed.\n\n  Hint Constructors\n       msg_accepted_by_pattern : core.\n\n  Hint Extern 1 (_ $+ (_,_) $? _ = _) => progress clean_map_lookups : core.\n\n  Lemma clean_ciphers_eliminates_dishonest_cipher :\n    forall c_id c cs k,\n      cs $? c_id = Some c\n      -> honest_keyb honestk k = false\n      -> k = cipher_signing_key c\n      -> clean_ciphers honestk cs $? c_id = None.\n  Proof.\n    intros; unfold clean_ciphers, filter.\n    apply P.fold_rec_bis; intros; eauto.\n    cases (honest_cipher_filter_fn honestk k0 e); eauto.\n    cases (c_id ==n k0); subst; eauto.\n    exfalso.\n    rewrite find_mapsto_iff in H2; rewrite H2 in H; invert H.\n    unfold honest_cipher_filter_fn, cipher_honestly_signed, cipher_signing_key in *.\n    cases c; rewrite H0 in Heq; invert Heq.\n  Qed.\n\n  Hint Resolve clean_ciphers_eliminates_dishonest_cipher clean_ciphers_keeps_honest_cipher : core.\n\n  Lemma clean_ciphers_keeps_added_honest_cipher :\n    forall c_id c cs,\n      honest_cipher_filter_fn honestk c_id c = true\n      -> ~ In c_id cs\n      -> clean_ciphers honestk (cs $+ (c_id,c)) = clean_ciphers honestk cs $+ (c_id,c).\n  Proof.\n    intros.\n    apply map_eq_Equal; unfold Equal; intros.\n    cases (c_id ==n y); subst; clean_map_lookups; eauto.\n    unfold clean_ciphers, filter; rewrite fold_add; eauto.\n    rewrite H; auto.\n  Qed.\n\n  Lemma clean_ciphers_reduces_or_keeps_same_ciphers :\n    forall c_id c cs k,\n      cs $? c_id = Some c\n      -> cipher_signing_key c = k\n      -> ( clean_ciphers  honestk cs $? c_id = Some c\n        /\\ honest_keyb honestk k = true)\n      \\/ ( clean_ciphers honestk cs $? c_id = None\n        /\\ honest_keyb honestk k = false).\n  Proof.\n    intros.\n    case_eq (honest_keyb honestk k); intros; eauto.\n    left; intuition idtac.\n    eapply clean_ciphers_keeps_honest_cipher; eauto.\n    unfold honest_cipher_filter_fn, cipher_signing_key in *.\n    cases c; try invert H0; eauto.\n  Qed.\n\n  Lemma clean_ciphers_no_new_ciphers :\n    forall c_id cs,\n      cs $? c_id = None\n      -> clean_ciphers honestk cs $? c_id = None.\n  Proof.\n    intros.\n    unfold clean_ciphers, filter.\n    apply P.fold_rec_bis; intros; eauto.\n    cases (honest_cipher_filter_fn honestk k e); eauto.\n    - case (c_id ==n k); intro; subst; unfold honest_cipher_filter_fn.\n      + rewrite find_mapsto_iff in H0; rewrite H0 in H; invert H.\n      + rewrite add_neq_o; eauto.\n  Qed.\n\n  Hint Resolve clean_ciphers_no_new_ciphers : core.\n\n  Lemma clean_ciphers_eliminates_added_dishonest_cipher :\n    forall c_id c cs k,\n      cs $? c_id = None\n      -> honest_keyb honestk k = false\n      -> k = cipher_signing_key c\n      -> clean_ciphers honestk cs = clean_ciphers honestk (cs $+ (c_id,c)).\n  Proof.\n    intros.\n    apply map_eq_Equal; unfold Equal; intros.\n    cases (y ==n c_id); subst.\n    - rewrite clean_ciphers_no_new_ciphers; auto.\n      symmetry.\n      eapply clean_ciphers_eliminates_dishonest_cipher; eauto.\n    - unfold clean_ciphers at 2, filter.\n      rewrite fold_add; auto. simpl.\n      unfold honest_cipher_filter_fn at 1.\n      cases c; simpl in *; try invert H1; rewrite H0; trivial.\n  Qed.\n\n  Lemma not_in_ciphers_not_in_cleaned_ciphers :\n    forall c_id cs,\n      ~ In c_id cs\n      -> ~ In c_id (clean_ciphers honestk cs).\n  Proof.\n    intros.\n    rewrite not_find_in_iff in H.\n    apply not_find_in_iff; eauto.\n  Qed.\n\n  Hint Resolve not_in_ciphers_not_in_cleaned_ciphers : core.\n\n  Lemma dishonest_cipher_cleaned :\n    forall cs c_id cipherMsg k,\n      cipher_signing_key cipherMsg = k\n      -> honest_keyb honestk k = false\n      -> ~ In c_id cs\n      -> clean_ciphers honestk cs = clean_ciphers honestk (cs $+ (c_id, cipherMsg)).\n  Proof.\n    intros.\n    apply map_eq_Equal; unfold Equal; intros.\n    case_eq (cs $? y); intros; simpl in *.\n    - eapply clean_ciphers_reduces_or_keeps_same_ciphers in H2; eauto.\n      split_ors; split_ands;\n        unfold clean_ciphers, filter; rewrite fold_add by auto;\n          unfold honest_cipher_filter_fn; cases cipherMsg; invert H; simpl in *; rewrite H0; reflexivity.\n    - rewrite clean_ciphers_no_new_ciphers; auto. eapply clean_ciphers_no_new_ciphers in H2.\n      unfold clean_ciphers, filter. rewrite fold_add by auto.\n      unfold honest_cipher_filter_fn; cases cipherMsg; invert H; simpl in *; rewrite H0; eauto. \n  Qed.\n\n  Hint Resolve dishonest_cipher_cleaned : core.\n\n  Hint Extern 1 (honest_cipher_filter_fn _ _ ?c = _) => unfold honest_cipher_filter_fn; cases c : core.\n\n  Lemma clean_ciphers_added_honest_cipher_not_cleaned :\n    forall cs c_id c k,\n        honest_key honestk k\n      -> k = cipher_signing_key c\n      -> clean_ciphers honestk (cs $+ (c_id,c)) = clean_ciphers honestk cs $+ (c_id,c).\n  Proof.\n    intros.\n    apply map_eq_Equal; unfold Equal; intros.\n\n    case (y ==n c_id); intros; subst; clean_map_lookups.\n    - erewrite clean_ciphers_keeps_honest_cipher; auto.\n      invert H; unfold honest_cipher_filter_fn; eauto.\n      unfold cipher_honestly_signed, honest_keyb;\n        cases c; simpl in *; context_map_rewrites; auto; invert H0; rewrite H1; trivial.\n    - case_eq (clean_ciphers honestk cs $? y); intros; subst;\n        cases (cs $? y); subst; eauto.\n        * assert (cs $? y = Some c1) as CSY by assumption;\n            eapply clean_ciphers_reduces_or_keeps_same_ciphers in CSY; eauto;\n              split_ors; split_ands;\n                clean_map_lookups.\n          eapply clean_ciphers_keeps_honest_cipher; eauto.\n        * exfalso; eapply clean_ciphers_no_new_ciphers in Heq; contra_map_lookup.\n        * assert (cs $? y = Some c0) as CSY by assumption;\n            eapply clean_ciphers_reduces_or_keeps_same_ciphers in CSY; eauto;\n              split_ors; split_ands; contra_map_lookup; eauto.\n  Qed.\n\n  Lemma clean_ciphers_idempotent :\n    forall cs,\n      ciphers_honestly_signed honestk cs\n      -> clean_ciphers honestk cs = cs.\n  Proof.\n    unfold clean_ciphers, filter, ciphers_honestly_signed; intros.\n    apply P.fold_rec_bis; intros; Equal_eq; subst; eauto.\n    unfold honest_cipher_filter_fn.\n    rewrite find_mapsto_iff in H0.\n    assert (cipher_honestly_signed honestk e = true).\n    eapply Forall_natmap_in_prop with (P := fun c => cipher_honestly_signed honestk c = true); eauto.\n    rewrite H2; trivial.\n  Qed.\n\n  Lemma clean_ciphers_honestly_signed :\n    forall cs,\n      ciphers_honestly_signed honestk (clean_ciphers honestk cs).\n  Proof.\n    unfold ciphers_honestly_signed; intros.\n    rewrite Forall_natmap_forall; intros.\n    rewrite <- find_mapsto_iff, clean_ciphers_mapsto_iff in H; split_ands.\n    unfold honest_cipher_filter_fn in *; assumption.\n  Qed.\n\n  Lemma honest_cipher_filter_fn_nochange_pubk :\n    forall pubk k v,\n      (forall k kp, pubk $? k = Some kp -> honestk $? k = Some true /\\ kp = false)\n      -> honest_cipher_filter_fn honestk k v =\n        honest_cipher_filter_fn (honestk $k++ pubk) k v.\n  Proof.\n    unfold honest_cipher_filter_fn; intros;\n      unfold cipher_honestly_signed;\n      cases v; unfold honest_keyb; simpl;\n        solve_perm_merges; auto;\n          match goal with\n          | [ H : (forall _ _, ?pubk $? _ = Some _ -> _), ARG : ?pubk $? _ = Some _ |- _ ] =>\n            specialize (H _ _ ARG); split_ands; subst\n          end; clean_map_lookups; eauto.\n  Qed.\n\n  Lemma clean_ciphers_nochange_pubk :\n    forall pubk cs,\n      (forall k p, pubk $? k = Some p -> honestk $? k = Some true /\\ p = false)\n      -> clean_ciphers (honestk $k++ pubk) cs = clean_ciphers honestk cs.\n  Proof.\n    intros; unfold clean_ciphers, filter.\n    apply P.fold_rec_bis; intros; Equal_eq; eauto.\n    rewrite fold_add; eauto; simpl.\n    erewrite <- honest_cipher_filter_fn_nochange_pubk; eauto.\n    subst; trivial.\n  Qed.\n\n  Lemma clean_ciphers_nochange_cipher :\n    forall cs c_id c,\n      clean_ciphers honestk cs $? c_id = Some c\n      -> cs $? c_id = Some c.\n  Proof.\n    intros.\n    rewrite <- find_mapsto_iff, clean_ciphers_mapsto_iff, find_mapsto_iff in H\n    ; split_ex\n    ; trivial.\n  Qed.\n\nEnd CleanCiphers.\n\nLtac encrypted_ciphers_prop :=\n  match goal with\n  | [ H  : encrypted_ciphers_ok _ (?cs $+ (?cid,?c)) _ |- _ ] => generalize (Forall_natmap_in_prop_add H); intros\n  | [ H1 : ?cs $? _ = Some _, H2 : encrypted_ciphers_ok _ ?cs _ |- _ ] => generalize (Forall_natmap_in_prop _ H2 H1); simpl; intros\n  end;\n  repeat match goal with\n         | [ H : encrypted_cipher_ok _ _ _ _ |- _ ] => invert H\n         | [ H : honest_keyb _ _ = true |- _] => apply honest_keyb_true_honestk_has_key in H\n         end; try contradiction.\n\nLemma clean_ciphers_new_honest_key_idempotent :\n  forall honestk k_id cs gks,\n    encrypted_ciphers_ok honestk cs gks\n    -> ~ In k_id gks\n    -> clean_ciphers (honestk $+ (k_id, true)) cs = clean_ciphers honestk cs.\nProof.\n  intros.\n  apply map_eq_Equal; unfold Equal; intros.\n  cases (cs $? y).\n  - case_eq (honest_cipher_filter_fn honestk y c); intros.\n    + assert (honest_cipher_filter_fn honestk y c = true) as HCFF by assumption.\n      unfold honest_cipher_filter_fn, cipher_honestly_signed in HCFF; encrypted_ciphers_prop\n      ; erewrite !clean_ciphers_keeps_honest_cipher; eauto.\n\n      simpl; unfold honest_keyb\n      ; destruct (k ==n k_id)\n      ; clean_map_lookups\n      ; trivial.\n      simpl; unfold honest_keyb\n      ; destruct (k__s ==n k_id)\n      ; clean_map_lookups\n      ; trivial.\n\n    + assert (honest_cipher_filter_fn honestk y c = false) as HCFF by assumption.\n      unfold honest_cipher_filter_fn, cipher_honestly_signed, honest_keyb in HCFF.\n      encrypted_ciphers_prop;\n        try\n          match goal with\n          | [ H : honestk $? _ = _ |- _ ] => rewrite H in HCFF; discriminate\n          end.\n      * erewrite !clean_ciphers_eliminates_dishonest_cipher; eauto.\n        unfold cipher_signing_key, honest_keyb;\n          solve_simple_maps; eauto.\n      * erewrite !clean_ciphers_eliminates_dishonest_cipher; eauto.\n        unfold cipher_signing_key, honest_keyb;\n          solve_simple_maps; eauto.\n  - rewrite !clean_ciphers_no_new_ciphers; auto.\nQed.\n\n#[export] Hint Immediate clean_ciphers_nochange_cipher : core.\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/src/Theory/CipherTheory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.28069759740059486}}
{"text": "Require Import List.\nRequire Import Omega.\n\nRequire Import MachineModel.\nRequire Import Assembler.\nRequire Import SameJumpTransitions.\n\n\n(*==============================================\n   Operational Semantics\n==============================================*)\nOpen Scope type_scope.\n\n\n\n(* Operational rules *)\nReserved Notation \"S '--->' S'\" (at level 50, left associativity).\n\nInductive evalR : State -> State -> Prop :=\n  \n| eval_call : forall (p p' : Address) (r r' r'' : RegisterFile) (f : Flags) (m m' m'' : Memory) (rd : Register),\n  inst (lookup m p) (call rd) -> \n  p' = lookup m (r rd) ->\n  entry_jump p p' ->\n  set_stack p r m p' r' m' ->\n  r'' = updateR r' SP (S (r' SP)) ->\n  m'' = update m (r'' SP) (S p) ->\n  (p, r, f, m) ---> (p', r'', f, m'')\n  \n| eval_ret : forall (p p' : Address) (r r' r'' : RegisterFile) (f : Flags) (m m' : Memory),\n  inst (lookup m p)  ret ->\n  p' =  lookup m (r SP) ->\n  exit_jump p p' ->\n  set_stack p r m p' r' m' ->\n  r'' = updateR r' SP (minus (r' SP) 1) ->\n  (p, r, f, m) ---> (p', r'', f, m')\n  \n| eval_callback : forall (p p' : Address) (r r' r'' : RegisterFile) (f : Flags) (m m' m'' : Memory) (rd : Register),\n  inst (lookup m p) (call rd) -> \n  p' = lookup m (r rd) ->\n  exit_jump p p' ->\n  r' = updateR r SP (S (r SP)) ->\n  m' = update m (r' SP) (S p)->\n  set_stack p r m p' r' m' ->\n  r'' = updateR r' SP (S (r' SP)) ->\n  m'' = (update m' (r'' SP) (address_returnback_entry_point)) ->\n  (p, r, f, m) ---> (p', r'', f, m'')\n  \n| eval_retback : forall (p p' : Address) (r r' r'' : RegisterFile) (f : Flags) (m m' : Memory),\n  inst (lookup m p)  ret ->\n  p' =  lookup m (r SP) ->\n  p' = address_returnback_entry_point ->\n  entry_jump p p' ->\n  set_stack p r m p' r' m' ->\n  r'' = updateR r' SP (minus (r' SP) 1) ->\n  (p, r, f, m) ---> ( p', r'', f, m')\n\n| eval_writeout : forall (p : Address) (r : RegisterFile) (f : Flags) (m m' : Memory) (rd rs : Register),\n  inst (lookup m p) (movs rd rs) -> \n  int_jump p (S p) ->\n  unprotected (r rd) -> \n  m' = update m  (r rd) (r rs)->  \n  (p, r, f, m) ---> (S p, r, f, m')\n\n| eval_int : forall (p p' : Address) (r r' : RegisterFile) (f f' : Flags) (m m' : MemSec) (me : MemExt) ,\n  (p, r, f, m) --i--> (p', r', f', m') ->\n  (p, r, f, (plug me m)) ---> (p', r', f', (plug me m'))\n\n| eval_ext : forall (p p' : Address) (r r' : RegisterFile) (f f' : Flags) (m : MemSec) (me me' : MemExt) ,\n  (p, r, f, me) --e--> (p', r', f', me') ->\n  (p, r, f, (plug me m)) ---> (p', r', f', (plug me' m))  \n\n  where \"S '--->' S'\" := (evalR S S') : type_scope.\n\n\n\n\n\n\n(* Inspired by some work of Benton *)\n\nInductive do_n_steps: State -> nat -> State -> Prop :=\n| do_0 : forall sta, do_n_steps sta 0 sta\n| do_Sn : forall n (p p' p'' : Address) (r r' r'' : RegisterFile) (f f' f'' : Flags) (c c' c'' : MemSec) (ctx ctx' ctx'' : MemExt), \n  (p, r, f, plug ctx c) ---> (p', r', f', plug ctx' c') ->\n  do_n_steps  (p', r', f', plug ctx' c') n  (p'', r'', f'', plug ctx'' c'') ->\n  do_n_steps  (p, r, f, plug ctx c) (S n) (p'', r'', f'', plug ctx'' c'').\n\nDefinition anysteps (n : nat) (sta  : State) := \n  exists n' : nat , exists p : Address, exists r : RegisterFile, exists f : Flags, exists ctx : MemExt, exists c : MemSec,\n      n' >= n /\\ (do_n_steps sta n' (p, r, f, (plug ctx c))).\n\nDefinition diverge (sta : State) := forall n, anysteps n sta.\n\n\n\nDefinition contextual_equivalence (p1 p2 : MemSec) (c : MemExt) :=\n    compatible p1 c -> compatible p2 c ->\n    ( (diverge (initial p1 c)) <-> (diverge (initial p2 c)) ).\n  \n\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/OperationalSemantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584175005616829, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.28069759740059474}}
{"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 O E Eprime A B C Oprime Aprime Bprime Cprime Eprimeprime C2 C3 C0 : Universe, ((wd_ O E /\\ (wd_ Oprime Eprime /\\ (wd_ A O /\\ (wd_ B O /\\ (wd_ C O /\\ (wd_ A E /\\ (wd_ Eprimeprime O /\\ (wd_ O Oprime /\\ (wd_ Bprime Oprime /\\ (wd_ Eprimeprime A /\\ (wd_ E Eprimeprime /\\ (wd_ E Eprime /\\ (wd_ O Eprime /\\ (wd_ Oprime Eprimeprime /\\ (wd_ Eprimeprime C /\\ (wd_ Eprimeprime B /\\ (wd_ E C /\\ (wd_ E B /\\ (wd_ C B /\\ (wd_ E Oprime /\\ (wd_ Bprime C3 /\\ (wd_ Eprime C2 /\\ (wd_ Aprime C2 /\\ (wd_ Oprime Aprime /\\ (wd_ A Aprime /\\ (wd_ C Cprime /\\ (wd_ B Bprime /\\ (col_ O E A /\\ (col_ O E B /\\ (col_ O E C /\\ (col_ Oprime Eprime Aprime /\\ (col_ Oprime Eprime Bprime /\\ (col_ Oprime Eprime Cprime /\\ (col_ O Eprimeprime C /\\ (col_ O Eprimeprime Oprime /\\ (col_ O Eprimeprime C2 /\\ (col_ O Eprimeprime C3 /\\ col_ O A C0))))))))))))))))))))))))))))))))))))) -> col_ E C B)).\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_1286.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.28068718749220506}}
{"text": "Add Rec LoadPath \"/home/daniel/UniMath/UniMath\" as UniMath.\n\nRequire Import Foundations.Generalities.uu0.\nRequire Import Foundations.hlevel1.hProp.\nRequire Import Foundations.hlevel2.hSet.\n\nRequire Import RezkCompletion.precategories.\nRequire Import RezkCompletion.functors_transformations.\nRequire Import RezkCompletion.whiskering.\n\nLoad terminalCat.\n\nLocal Notation \"a --> b\" := (precategory_morphisms a b) (at level 50).\nLocal Notation \"f ;; g\" := (compose f g) (at level 50, format \"f  ;;  g\").\nLocal Notation \"# F\" := (functor_on_morphisms F)(at level 3).\n\nDefinition get_hs\n  (C : hs_precategory)\n    : has_homsets C\n:= pr2 (pr2 C).\n\nDefinition hs_precat_pair\n  (C : precategory) (hs : has_homsets C)\n    : hs_precategory.\nProof.\n  unfold hs_precategory.\n  apply (tpair _ (pr1 C)).  \n  split.  \n  apply (pr2 C).\n  apply hs.\nDefined.\n\nDefinition hs_funct_precat\n  (C : precategory) (D: hs_precategory)\n    : hs_precategory.\nProof.\n  apply (hs_precat_pair (functor_precategory C D (pr2 (pr2 D)))). \n  apply (functor_category_has_homsets C D (get_hs D)).\nDefined.\n\nLocal Notation \"D ^^ C\" := (hs_funct_precat C D) (at level 2).\n\n(* coercion isn't working (??) when I want to apply a functor from D ^^ C\n   to an object of C, need something with coercion to funclass? *)\nDefinition get_funct\n  {C : precategory} {D : hs_precategory} (F : D ^^ C)\n    : functor C D.\nProof.\n  apply F.\nDefined.\n\nDefinition dget_funct\n  {C D : precategory} {E : hs_precategory}\n  (F : (E^^D)^^C )\n  (c : C)\n    : functor D E.\nProof.\n  apply (get_funct F c).  \nDefined.\n\nDefinition tget_funct\n  {B C D : precategory} {E : hs_precategory}\n  (F : ((E^^D)^^C)^^B )\n  (b : B) (c : C)\n    : functor D E.\nProof.\n  apply (dget_funct F b c).  \nDefined.\n\nArguments get_funct {C D} / F.\nArguments dget_funct {C D E} / F c.\nArguments tget_funct {B C D E} / F b c.\n\nDefinition get_nat\n  {C : precategory} {D : hs_precategory} {F G : D^^C}\n  (u : F --> G)\n    : nat_trans (get_funct F) (get_funct G).\nProof.\n  apply u.\nDefined.\n\nDefinition dget_nat\n  {C D : precategory} {E : hs_precategory} {F G : (E^^D)^^C}\n  (v : F --> G) (c : C) \n    : nat_trans (dget_funct F c) (dget_funct G c).\nProof.\n  apply (get_nat v c).\nDefined.\n\nDefinition funct_cat\n  (C : precategory) (D : category)\n    : category.\nProof.\n  apply (tpair _ (functor_precategory C D (pr2 (pr2 D)))).\n  apply (is_category_functor_category C D).\nDefined.\n\nLocal Notation \"[ C , D ]'\" := (funct_cat C D) (at level 2).\n\n(* If 2categories.v still compiles, delete this\nDefinition function_from_functor_cat\n  {C : precategory} {D : category}\n    : [C, D]' -> C -> D.\nProof.\n  intro f.\n  apply f.\nDefined.\n*)\n\n(* function from terminal cate defines a functor *)\nDefinition terminal_cat_functors\n  {C : hs_precategory}\n    : (terminal_cat -> C) ->  C ^^ terminal_cat.\nProof.\n  intro x.\n  apply (tpair _ (terminal_cat_functors_data x)).\n  split.\n  - intro a.\n    destruct a.\n    simpl.   \n    apply idpath.\n  - intros a b c f g.\n    destruct a, b, c.\n    simpl.\n    apply (pathsinv0 (id_left _ _ _ (identity (x tt)))).\nDefined.\n\n(* precomposition *)\nDefinition funct_precomp_data\n  {C : precategory} {D : hs_precategory} \n  (F : D^^C) (E : hs_precategory)\n    : functor_data E^^D E^^C.\nProof.\n  apply (tpair _ (functor_composite _ _ _ F)). \n  intros G G' u.\n  apply (pre_whisker (get_funct F) u).\nDefined.\n\nDefinition funct_precomp\n  {C : precategory} {D : hs_precategory} \n  (F : D^^C) (E : hs_precategory)\n    : functor E^^D E^^C.\nProof.\n  apply (tpair _ (funct_precomp_data F E)).\n  split.\n  - intro G.\n    apply pre_whisker_identity.\n    apply get_hs.\n  - intros G G' G'' u v.\n    apply pre_whisker_composition.\n    apply get_hs.\nDefined.\n\n(* postcomposition *)\nDefinition funct_postcomp_data    \n  {C : hs_precategory} {D : hs_precategory}\n  (E : precategory) (F : D^^C)\n    : functor_data C^^E D^^E.\nProof.\n  apply (tpair _ (fun G' : C^^E =>  functor_composite _ _ _ G' F)).\n  intros G G' u.\n  apply (post_whisker u (get_funct F)).\nDefined.\n\nDefinition funct_postcomp    \n  {C : hs_precategory} {D : hs_precategory}\n  (E : precategory) (F : D^^C)\n    : functor C^^E D^^E.\nProof.\n  apply (tpair _ (funct_postcomp_data E F)).\n  split.\n  - intro G.\n    apply nat_trans_eq.\n    apply get_hs.\n    intro a.\n    apply (functor_id (get_funct F)).\n  - intros G G' G'' u v.\n    apply nat_trans_eq.\n    apply get_hs.\n    intro a. \n    apply (functor_comp (get_funct F)).\nDefined.\n\n(* argument swaping functor (E^^D)^^C ^^ (E^^C)^^D \n\n   The general pattern is to define the object function, then functor\n   data, then the actual functor. This is done several times. *) \nDefinition funct_arg_swap_ob_to_ob_to_data\n  {C D : precategory} {E : hs_precategory}\n    : (E^^D)^^C -> (D -> (functor_data C E)).\nProof.\n  intros F d.\n  apply (tpair _ (fun c : C => dget_funct F c d)). \n  intros a b f. \n  (* re-figure out the args thing so it unfolds get_funct automatically *)\n  unfold dget_funct; unfold get_funct.\n  apply (# (get_funct F) f).\nDefined.\n\nDefinition funct_arg_swap_ob_to_ob_to_funct\n  {C D : precategory} {E : hs_precategory}\n    : (E^^D)^^C -> (D -> (E^^C)).\nProof.\n  intros F d.\n  apply (tpair _ ((funct_arg_swap_ob_to_ob_to_data F) d)). \n  split.\n  - intro a; simpl.\n    rewrite (functor_id (get_funct F)).\n    apply idpath.\n  - intros a b c f g; simpl.\n    rewrite (functor_comp (get_funct F)).\n    apply idpath.\nDefined.\n\nDefinition funct_arg_swap_on_mor\n  {C D : precategory} {E : hs_precategory}\n  (F : (E^^D)^^C) {a b : D} (f : a --> b)\n    : forall c : C, (dget_funct F c) a --> (dget_funct F c) b.\nProof.\n  intro c.\n  apply (#(dget_funct F c) f).\nDefined.\n\nDefinition funct_arg_swap_ob_to_funct_data\n  {C D : precategory} {E : hs_precategory}\n    : (E^^D)^^C -> (functor_data D E^^C).\nProof.\n  intro F.\n  apply (tpair _ (funct_arg_swap_ob_to_ob_to_funct F)).\n  intros a b f; simpl.\n  apply (tpair _ (funct_arg_swap_on_mor F f)).\n  intros x y g.\n  (* get the natural transformation data from (# F g) *)\n  set (H := pr2 (#(get_funct F) g)).\n  simpl in *.\n  apply (pathsinv0 (H a b f)).\nDefined.\n\nDefinition funct_arg_swap_ob\n  (C D : precategory) (E : hs_precategory)\n    : (E^^D)^^C -> (E^^C)^^D.\nProof.\n  intro F.\n  apply (tpair _ (funct_arg_swap_ob_to_funct_data F)).\n  split.\n  - intro a. \n    apply nat_trans_eq.\n    apply get_hs.\n    intro c.\n    apply (functor_id (dget_funct F c)).\n  - intros a b c f g.\n    apply nat_trans_eq.\n    apply get_hs.\n    intro d.\n    apply (functor_comp (dget_funct F d)).\nDefined.\n\nDefinition funct_arg_swap_mor_mor\n  {C D : precategory} {E : hs_precategory} {F G : (E^^D)^^C}\n  (u : F --> G) (d : D)\n    : forall c : C, \n       get_funct (funct_arg_swap_ob_to_funct_data F d) c --> \n       get_funct (funct_arg_swap_ob_to_funct_data G d) c.\nProof.\n  intro c.\n  apply (dget_nat u c d).\nDefined.\n \nDefinition funct_arg_swap_mor\n  {C D : precategory} {E : hs_precategory} {F G : (E^^D)^^C}\n  (u : F --> G)\n    : forall d : D, (funct_arg_swap_ob_to_funct_data F) d -->\n                    (funct_arg_swap_ob_to_funct_data G) d.\nProof.\n  intro d; simpl.\n  apply (tpair _ (funct_arg_swap_mor_mor u d)).\n  intros a b f; simpl.\n  unfold funct_arg_swap_mor_mor.\n  unfold dget_nat; unfold get_nat.\n  (* There should be a nicer way of doing this, like inverse functional\n     extensionality or generalize d or something.*)\n  apply (nat_trans_eq_pointwise _ _ _ _ _ _ (pr2 u a b f)).\nDefined.\n\nDefinition funct_arg_swap_data\n  (C D : precategory) (E : hs_precategory)\n    : functor_data (E^^D)^^C (E^^C)^^D.\nProof.\n  apply (tpair _ (funct_arg_swap_ob C D E)).\n  intros F G u.\n  simpl.\n  apply (tpair _ (funct_arg_swap_mor u)).\n  intros a b f.   \n  apply nat_trans_eq.\n  apply get_hs.\n  intro c.\n  simpl.  \n  unfold funct_arg_swap_mor_mor.\n  apply (pr2 (dget_nat u c)).\nDefined.\n\nDefinition funct_arg_swap\n  {C D : precategory} {E : hs_precategory}\n    : functor ((E^^D)^^C) ((E^^C)^^D).\nProof.\n  apply (tpair _ (funct_arg_swap_data C D E)).\n  split.\n  - intro a.\n    apply nat_trans_eq.\n    apply get_hs.\n    intro y.\n    apply nat_trans_eq.\n    apply get_hs.\n    intro x.\n    simpl.\n    unfold funct_arg_swap_mor_mor.\n    unfold dget_funct; unfold get_funct.\n    unfold dget_nat; unfold get_nat.\n    simpl.\n    apply idpath.\n  - intros a b c f g.\n    apply nat_trans_eq.\n    apply get_hs.\n    intro y.\n    apply nat_trans_eq.\n    apply get_hs.\n    intro x.\n    simpl.\n    unfold funct_arg_swap_mor_mor.\n    unfold dget_nat; unfold get_nat.\n    simpl.\n    apply idpath.\n    (* I wonder why this takes so long to compute. If I remove the simpls\n       right before the idpath, then the idpath takes a long time to check\n       *)\nDefined.\n\n(* Definition of the comp functor *)\nDefinition functor_comp_functor_fun\n  (C D E : hs_precategory)\n    : (D ^^ C) -> ((E ^^ C) ^^ (E ^^ D)).\nProof.\n  intro F.  \n  apply (funct_precomp F E).\nDefined.\n\nDefinition functor_comp_functor_nat\n  {C D E : hs_precategory}\n  (F G : D ^^ C) (u : F --> G)\n    : forall H : E ^^ D, (funct_precomp F E) H --> (funct_precomp G E) H.\nProof.\n  intro H.\n  apply post_whisker.\n  apply u.\nDefined.\n  \nDefinition functor_comp_functor_data\n  (C D E : hs_precategory)\n    : functor_data (D ^^ C) ((E ^^ C) ^^ (E ^^ D)).\nProof.\n  apply (tpair _ (fun F : D ^^ C => funct_precomp F E)).\n  intros F G u.\n  apply (tpair _ (functor_comp_functor_nat F G u)). \n  intros H H' r.\n  apply nat_trans_eq. \n  apply get_hs.\n  intro a.\n  simpl.\n  apply pathsinv0.\n  apply (pr2 r (pr1 F a) (pr1 G a) (pr1 u a)).\nDefined.\n\nDefinition functor_comp_functor\n  (C D E : hs_precategory)\n    : ((E ^^ C) ^^ (E ^^ D)) ^^ (D ^^ C).\nProof.\n  apply (tpair _ (functor_comp_functor_data C D E)).\n  split.\n  - intro F.\n    apply nat_trans_eq. apply get_hs.\n    intro G.\n    apply nat_trans_eq. apply get_hs.\n    intro a.\n    simpl.\n    apply functor_id.\n  - intros F F' F'' u u'.\n    apply nat_trans_eq. apply get_hs.\n    intro G.\n    apply nat_trans_eq. apply get_hs.\n    intro a.\n    simpl.\n    apply functor_comp.\nDefined.", "meta": {"author": "daniel-satanove", "repo": "2cats", "sha": "ecb279494c628b8e05994a0e0312e4d3edd34653", "save_path": "github-repos/coq/daniel-satanove-2cats", "path": "github-repos/coq/daniel-satanove-2cats/2cats-ecb279494c628b8e05994a0e0312e4d3edd34653/functCats.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2806525764565248}}
{"text": "Require Import VST.floyd.proofauto.\nLocal Open Scope logic.\nRequire Import List. Import ListNotations.\nRequire Import tweetnacl20140427.Snuffle.\nRequire Import tweetnacl20140427.Salsa20.\nRequire Import ZArith.\n\nRequire Import tweetnacl20140427.tweetnaclVerifiableC.\nRequire Import tweetnacl20140427.spec_salsa.\nRequire Import tweetnacl20140427.verif_salsa_base.\nOpaque Snuffle20. Opaque prepare_data. Opaque Snuffle.Snuffle.\n\nLemma crypto_core_salsa20_ok: semax_body SalsaVarSpecs SalsaFunSpecs\n      f_crypto_core_salsa20_tweet crypto_core_salsa20_spec.\nProof. unfold crypto_core_salsa20_spec.\nstart_function.\nabbreviate_semax.\nassert_PROP (field_compatible (tarray tuchar 64) [] out /\\ isptr out) as HH by entailer!.\ndestruct HH as [FCout isptrout].\nTime forward_call (c, k, Z0, nonce, out, default_val (tarray tuchar 64), data). (*1.8*)\n  unfold data_at_, field_at_. rewrite field_at_data_at.\n  rewrite field_address_offset by auto with field_compatible.\n  rewrite isptr_offset_val_zero; trivial. cancel.\nIntros ret.\nTime forward. (*1.7*)\nunfold fcore_result in H.\n  remember (Snuffle20 (prepare_data data)) as d; symmetry in Heqd.\n  destruct d. 2: inv H. rewrite Int.eq_true in H.\nExists l.\nTime entailer!.\nTime Qed. (*4.3*)\n\nLemma Snuffle_sub_simpl data x:\n    Snuffle20 (prepare_data data) = Some x ->\n    exists s, Snuffle 20 (prepare_data data) = Some s /\\\n    forall i (I:0 <= i < 16) v,\n      Znth i (prepare_data data) Int.zero = v ->\n      littleendian_invert (Int.sub (Znth i x Int.zero) v) =\n      littleendian_invert (Znth i s Int.zero).\nProof. intros.\nTransparent Snuffle20. unfold Snuffle20 in H. Opaque Snuffle20.\nremember (Snuffle 20 (prepare_data data)) as sn.\ndestruct sn; simpl in H. 2: inv H. clear Heqsn.\nexists l; split; trivial.\nintros. rewrite (sumlist_char_Znth _ _ _ H).\n  rewrite Int.add_commut, Int.sub_add_l, H0, Int.sub_idem, Int.add_zero_l. trivial.\nsymmetry in H; apply sumlist_length in H.\nrewrite Zlength_correct, H, prepare_data_length; trivial.\nQed.\n\nLemma crypto_core_hsalsa20_ok: semax_body SalsaVarSpecs SalsaFunSpecs\n      f_crypto_core_hsalsa20_tweet crypto_core_hsalsa20_spec.\nProof. unfold crypto_core_hsalsa20_spec.\nstart_function.\nTime forward_call (c, k, 1, nonce, out, OUT, data). (*1.4*)\nIntros res.\nTime forward. (*1.6*)\nunfold fcore_result in H.\n  remember (Snuffle20 (prepare_data data)) as d; symmetry in Heqd.\n  destruct d. 2: inv H. rewrite Int.eq_false in H.\ndestruct (Snuffle_sub_simpl _ _ Heqd) as [x [X1 X2]].\nExists x.\nTime entailer!. (*0.6*)\n2: apply Int.one_not_zero.\nunfold fcorePOST_SEP; cancel.\n  destruct data as[[Nonce C] [K L]].\n  destruct C as [[[C1 C2] C3] C4].\n  destruct Nonce as [[[N1 N2] N3] N4].\n  destruct K as [[[K1 K2] K3] K4].\n  destruct L as [[[L1 L2] L3] L4].\napply derives_refl'. f_equal.\n  do 8 rewrite X2 in H by (try omega; reflexivity).\n  apply H.\nTime Qed. (*2.8*)", "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_crypto_core.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2806134812692976}}
{"text": "\n            \nFrom Undecidability Require Import MaxList.\nFrom Undecidability Require Import TM.Util.TM_facts TM.Code.CodeTM.\n\nFrom Undecidability Require Import TM.Util.VectorPrelim.\n\n(* MOVE : this file contains general lemmas from is all over the place... *)\n\n\nLemma max_list_rec_eq_foldl (a : nat) (xs : list nat) :\n  fold_left max xs a = max_list_rec a xs.\nProof.\n  revert a. induction xs as [ | x xs IH]; intros; cbn in *.\n  - reflexivity.\n  - rewrite IH. rewrite !max_list_rec_max. nia.\nQed.\n\nLemma sizeOfmTapes_max_list_map (sig : Type) (n : nat) (T : tapes sig n) :\n  sizeOfmTapes T = max_list_map (@sizeOfTape _) (vector_to_list T).\nProof.\n  unfold sizeOfmTapes.\n  rewrite fold_left_vector_to_list.\n  rewrite <- vector_to_list_map.\n  unfold max_list_map, max_list.\n  apply max_list_rec_eq_foldl.\nQed.\n\nLemma sizeOfmTapes_upperBound (sig : Type) (n : nat) (tps : tapes sig n) :\n  forall t, Vector.In t tps -> sizeOfTape t <= sizeOfmTapes tps.\nProof. intros. rewrite sizeOfmTapes_max_list_map. apply max_list_map_ge. now apply vector_to_list_In. Qed.\n\nFrom Undecidability Require Import L.Prelim.MoreList.\n\nLemma max_list_sumn l : max_list l <= sumn l.\nProof.\n  unfold max_list.\n  induction l;cbn. 2:rewrite max_list_rec_max'. all:nia.\nQed.\n\n\nLemma right_sizeOfTape sig' (t:tape sig') :\n  length (right t) <= sizeOfTape t.\nProof.\n  destruct t;cbn. all:autorewrite with list;cbn. all:nia.\nQed.\n\nLemma length_tape_local_right sig' (t:tape sig') :\n  length (tape_local (tape_move_right t)) <= sizeOfTape t.\nProof.\n  destruct t;cbn.  1-3:nia. rewrite tape_local_move_right'. autorewrite with list;cbn. all:nia.\nQed.\n\nLemma size_list X sigX (cX: codable sigX X) (l:list X) :\n  size l = sumn (map size l) + length l + 1.\nProof.\n  unfold size. cbn. rewrite encode_list_concat.\n  rewrite app_length, length_concat, map_map. cbn.\n  change S with (fun x => 1 + x). rewrite sumn_map_add,sumn_map_c. setoid_rewrite map_length.\n  cbn.  nia.\nQed.\n\nLemma destruct_vector1 (X : Type) (v : Vector.t X 1) :\n  exists x, v = [| x |].\nProof. destruct_vector. eauto. Qed.\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/PrettyBounds/SizeBounds.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2805831942082898}}
{"text": "Require Import list_examples.\n\nDefinition tail_code := Plus1++Load::Ret::nil.\n\nInductive tail_spec : Spec cfg :=\n  tail_claim : forall H x y l, fun_claim tail_spec\n  \"tail\" (Plus1++Load::Ret::nil)\n    1 (fun p => asP H (rep_seg (x::nil) y p :* rep_list l y))\n    1 (fun p => constraint (p = y) :* litP H).\n\nLemma tail_proof : sound stack_step tail_spec.\nProof. list_solver. Qed.\n", "meta": {"author": "Formal-Systems-Laboratory", "repo": "coinduction", "sha": "1031da11c4a4523ea9b7347036b6bdabc7620e1d", "save_path": "github-repos/coq/Formal-Systems-Laboratory-coinduction", "path": "github-repos/coq/Formal-Systems-Laboratory-coinduction/coinduction-1031da11c4a4523ea9b7347036b6bdabc7620e1d/coinduction-proofs/stack/examples/ex03_list/ex02_tail.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.28058318801661775}}
{"text": "(** * Undecidability of the subtyping problem of System Fsub without arrow types *)\n\nRequire Import Undecidability.Synthetic.Undecidability.\n\nRequire Import Fsub_na FsubN FsubN_undec FsubD FsubF RM CM2.\nRequire Import Reductions.FsubN_to_Fsub.\nRequire Import Reductions.FsubD_to_FsubN.\nRequire Import Reductions.FsubF_to_FsubD.\nRequire Import Reductions.RM_HALT_to_FsubF.\nRequire Import Reductions.CM2_Halt_to_RM_Halt.\nRequire Import Reductions.CM2_HALT_to_CM2_HALT.\n\nFrom Undecidability.CounterMachines\n  Require Import CM2 CM2_undec.\n\nTheorem Fsub'_SUBTYPE_undec : undecidable Fsub'_SUBTYPE.\nProof.\n  apply (undecidability_from_reducibility CM2_HALT_undec).\n  eapply reduces_transitive. exact CM2_HALT_to_CM2_HALT.reduction.\n  eapply reduces_transitive. exact CM2_Halt_to_RM_Halt.reduction.\n  eapply reduces_transitive. exact RM_HALT_to_FsubF.reduction.\n  eapply reduces_transitive. exact FsubF_to_FsubD.reduction.\n  eapply reduces_transitive. exact FsubD_to_FsubN.reduction.\n  exact FsubN_to_Fsub.reduction_off.\nQed.\n\nCheck Fsub'_SUBTYPE_undec.", "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/Fsub_na_undec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.2805831880166177}}
{"text": "Require Import\n        Fiat.Narcissus.Common.Specs.\n\nRequire Export\n        Fiat.Narcissus.Formats.Base.SequenceFormat\n        Fiat.Narcissus.Formats.Base.FMapFormat\n        Fiat.Narcissus.Formats.Base.StrictTerminalFormat\n        Fiat.Narcissus.Formats.Base.LaxTerminalFormat\n        Fiat.Narcissus.Formats.Base.FixFormat\n        Fiat.Narcissus.Formats.Base.EnqueueFormat\n        Fiat.Narcissus.Formats.Base.UnionFormat.\n\n(* Aliases of Correct Decoder for deriving partial views of data. *)\nDefinition CorrectRefinedDecoder\n           {S T : Type}\n           {store : Cache}\n           {V : Type}\n           (monoid : Monoid T)\n           (Source_Predicate : S -> Prop)\n           (View_Predicate : V -> Prop)\n           (view : S -> V -> Prop)\n           (format subformat : FormatM S T)\n           (decode : T -> CacheDecode -> Hopefully (V * T * CacheDecode))\n           (decode_inv : CacheDecode -> Prop)\n           (view_format : V -> CacheFormat -> Comp (T * CacheFormat)) :=\n  CorrectDecoder monoid Source_Predicate View_Predicate view\n                 subformat decode decode_inv\n                 (fun v env t =>\n                    view_format v env t\n                    /\\ forall s,\n                      Source_Predicate s ->\n                        subformat s env ∋ t\n                        -> view s v).\nDefinition Prefix_Format\n           {S T : Type}\n           {store : Cache}\n           (monoid : Monoid T)\n           (format subformat : FormatM S T)\n  := forall s t env env',\n    format s env ∋ (t, env') ->\n    exists t1 t2 env'',\n      t = mappend t1 t2\n      /\\ subformat s env ∋ (t1, env'').\n\n(*Lemma  CorrectRefinedDecoder_decode_partial\n       {S T : Type}\n       {store : Cache}\n       {V : Type}\n       (monoid' : Monoid T)\n       (Source_Predicate : S -> Prop)\n       (View_Predicate : V -> Prop)\n       (view : S -> V -> Prop)\n       (format subformat : FormatM S T)\n       (decode : T -> CacheDecode -> Hopefully (V * T * CacheDecode))\n       (decode_inv : CacheDecode -> Prop)\n       (view_format : V -> CacheFormat -> Comp (T * CacheFormat))\n  : CorrectRefinedDecoder monoid' Source_Predicate View_Predicate view\n                          format subformat decode decode_inv view_format\n    -> forall s t env env',\n      format s env ∋ (t, env') ->\n      exists t1 t2 env'',\n        t = mappend t1 t2 /\\\n        subformat s env ∋ (t1, env'').\nProof.\n  intro.\n  eapply H; eauto.\n  (* apply proj2 in H. *)\n  (* eapply H. *)\n  (* eapply H in H0. *)\n\n  (* intros [? [? ?] ] * ?. *)\n  (* eapply H0 in H1. *)\n  (* unfold sequence_Format, ComposeOpt.compose, Bind2 in H1. *)\n  (* computes_to_inv; destruct v; destruct v0; simpl in *; eauto. *)\n  (* injections. *)\n  (* eexists _, _, _; intuition eauto. *)\nQed. *)\n\nLemma CorrectRefinedDecoder_decode_impl\n       {S T : Type}\n       {store : Cache}\n       (monoid' : Monoid T)\n       (Source_Predicate : S -> Prop)\n       (format : FormatM S T)\n       (decode : T -> CacheDecode -> Hopefully (S * T * CacheDecode))\n       (decode_inv : CacheDecode -> Prop)\n  : CorrectRefinedDecoder monoid' Source_Predicate Source_Predicate eq\n                          format format decode decode_inv format\n    -> CorrectDecoder monoid' Source_Predicate Source_Predicate eq\n                      format decode decode_inv format.\nProof.\n  intros.\n  eapply weaken_view_pred.\n  intros; subst; eauto.\n  2: apply H.\n  intros.\n  simpl in H1; intuition eauto.\nQed.\n\nAdd Parametric Morphism\n    S T V\n    (cache : Cache)\n    (monoid : Monoid T)\n    (Source_Predicate : S -> Prop)\n    (View_Predicate : V -> Prop)\n    (view : S -> V -> Prop)\n    (decode : DecodeM (V * T) T)\n    (decode_inv : CacheDecode -> Prop)\n    (subformat : FormatM S T)\n    (view_format : FormatM V T)\n  : (fun format =>\n       @CorrectRefinedDecoder S T cache V monoid Source_Predicate View_Predicate\n                       view format subformat decode decode_inv view_format)\n    with signature (EquivFormat --> impl)\n      as format_decode_refined_correct_refineEquiv.\nProof.\n  unfold EquivFormat, impl, pointwise_relation; intros.\n  - unfold CorrectRefinedDecoder in *.\n    apply H0.\nQed.\n\nAdd Parametric Morphism\n    {S T : Type}\n    {cache : Cache}\n    (monoid : Monoid T)\n  : (fun format subformat =>\n       @Prefix_Format S T cache monoid format subformat)\n    with signature (EquivFormat --> EquivFormat --> impl)\n      as prefix_format_refineEquiv.\nProof.\n  unfold EquivFormat, impl, pointwise_relation; unfold Prefix_Format; intros.\n  edestruct H1. apply H. eauto. destruct_conjs.\n  eexists _, _, _. intuition eauto. apply H0. eauto.\nQed.\n", "meta": {"author": "scuellar", "repo": "narcissus_errors", "sha": "8c547389030165e8620b43bb38ad87b9b65e5471", "save_path": "github-repos/coq/scuellar-narcissus_errors", "path": "github-repos/coq/scuellar-narcissus_errors/narcissus_errors-8c547389030165e8620b43bb38ad87b9b65e5471/src/Narcissus/BaseFormats.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.28058318182494557}}
{"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 A B C D P Q R Z T I Y0 : Universe, ((wd_ A C /\\ (wd_ P Q /\\ (wd_ C D /\\ (wd_ R C /\\ (wd_ A B /\\ (wd_ P R /\\ (wd_ T Z /\\ (wd_ C P /\\ (wd_ Q C /\\ (wd_ A Z /\\ (wd_ I Z /\\ (wd_ I C /\\ (wd_ T A /\\ (wd_ Z C /\\ (wd_ R I /\\ (wd_ Y0 I /\\ (wd_ Y0 Z /\\ (wd_ Y0 C /\\ (col_ P R R /\\ (col_ A T Z /\\ (col_ P R Q /\\ (col_ C R Y0 /\\ (col_ C I Y0 /\\ col_ C R Z))))))))))))))))))))))) -> col_ I Y0 Z)).\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_0456.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7431679972357831, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.2805761427057758}}
{"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\n\n(* Converted imports: *)\n\nRequire GHC.Base.\nRequire GHC.Prim.\nImport GHC.Base.Notations.\n\n(* Converted type declarations: *)\n\nRecord Category__Dict (cat : Type -> Type -> Type) := Category__Dict_Build {\n  id__ : forall {a}, cat a a ;\n  op_z2218U____ : forall {b} {c} {a}, cat b c -> cat a b -> cat a c }.\n\nDefinition Category (cat : Type -> Type -> Type) :=\n  forall r__, (Category__Dict cat -> r__) -> r__.\n\nExisting Class Category.\n\nDefinition id `{g__0__ : Category cat} : forall {a}, cat a a :=\n  g__0__ _ (id__ cat).\n\nDefinition op_z2218U__ `{g__0__ : Category cat}\n   : forall {b} {c} {a}, cat b c -> cat a b -> cat a c :=\n  g__0__ _ (op_z2218U____ cat).\n\nNotation \"'_∘_'\" := (op_z2218U__).\n\nInfix \"∘\" := (_∘_) (left associativity, at level 40).\n\n(* Converted value declarations: *)\n\nDefinition op_zlzlzl__ {cat} {b} {c} {a} `{Category cat}\n   : cat b c -> cat a b -> cat a c :=\n  _∘_.\n\nNotation \"'_<<<_'\" := (op_zlzlzl__).\n\nInfix \"<<<\" := (_<<<_) (at level 99).\n\nDefinition op_zgzgzg__ {cat} {a} {b} {c} `{Category cat}\n   : cat a b -> cat b c -> cat a c :=\n  fun f g => g ∘ f.\n\nNotation \"'_>>>_'\" := (op_zgzgzg__).\n\nInfix \">>>\" := (_>>>_) (at level 99).\n\n(* Skipping instance `Control.Category.Category__Coercion' of class\n   `Control.Category.Category' *)\n\n(* Skipping instance `Control.Category.Category__op_ZCz7eUz7eUZC__' of class\n   `Control.Category.Category' *)\n\n(* Skipping instance `Control.Category.Category__op_ZCz7eUZC__' of class\n   `Control.Category.Category' *)\n\nLocal Definition Category__arrow_id : forall {a}, GHC.Prim.arrow a a :=\n  fun {a} => GHC.Base.id.\n\nLocal Definition Category__arrow_op_z2218U__\n   : forall {b} {c} {a},\n     GHC.Prim.arrow b c -> GHC.Prim.arrow a b -> GHC.Prim.arrow a c :=\n  fun {b} {c} {a} => _GHC.Base.∘_.\n\nProgram Instance Category__arrow : Category GHC.Prim.arrow :=\n  fun _ k__ =>\n    k__ {| id__ := fun {a} => Category__arrow_id ;\n           op_z2218U____ := fun {b} {c} {a} => Category__arrow_op_z2218U__ |}.\n\nModule Notations.\nNotation \"'_Control.Category.∘_'\" := (op_z2218U__).\nInfix \"Control.Category.∘\" := (_∘_) (left associativity, at level 40).\nNotation \"'_Control.Category.<<<_'\" := (op_zlzlzl__).\nInfix \"Control.Category.<<<\" := (_<<<_) (at level 99).\nNotation \"'_Control.Category.>>>_'\" := (op_zgzgzg__).\nInfix \"Control.Category.>>>\" := (_>>>_) (at level 99).\nEnd Notations.\n\n(* External variables:\n     Type GHC.Base.id GHC.Base.op_z2218U__ GHC.Prim.arrow\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/Control/Category.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2804747141350864}}
{"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.\n\nLemma same_structure_refl :\n  forall e, same_structure e e.\nProof.\n  induction e; constructor; auto.\nQed.\n\nLemma same_structure_sym :\n  forall e e', same_structure e e' -> same_structure e' e.\nProof.\n  intros e e' H. induction H; constructor; auto.\nQed.\n\nLemma same_structure_trans : forall e e' e'',\n  same_structure e e' -> same_structure e' e'' ->\n  same_structure e e''.\nProof.\n  intros e e' e'' H. generalize dependent e''.\n  induction H; intros.\n  - inversion H. subst. constructor.\n  - inversion H1. subst. constructor; auto.\n  - inversion H. subst. constructor.\n  - inversion H. subst. constructor.\n  - inversion H1. subst. constructor; auto.\n  - inversion H1. subst. constructor; auto.\n  - inversion H1. subst. constructor; auto.\n  - inversion H0. subst. constructor; auto.\nQed.\n\nLemma same_structure_equal_constructor :\n  forall e e', same_structure e e' -> ~ diff_constructor e e'.\nProof.\n  intros.\n  induction H; subst; intro; simpl in H; contradiction.\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_Same_Structure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.28047471413508634}}
{"text": "Require Import Crypto.Compilers.Syntax.\nRequire Import Crypto.Compilers.Named.Syntax.\nRequire Import Crypto.Compilers.Named.Context.\nRequire Import Crypto.Util.PointedProp.\nRequire Import Crypto.Util.Notations.\n\nModule Export Named.\n  Section language.\n    Context {base_type_code : Type}\n            {op : flat_type base_type_code -> flat_type base_type_code -> Type}\n            {Name : Type}\n            {interp_base_type : base_type_code -> Type}\n            {Context : Context Name interp_base_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            (interped_op_side_conditions : forall s d, op s d -> interp_flat_type interp_base_type s -> pointed_Prop).\n\n    Local Notation exprf := (@exprf base_type_code op Name).\n    Local Notation expr := (@expr base_type_code op Name).\n\n    Fixpoint interpf_side_conditions_gen {t} (ctx : Context) (e : exprf t)\n      : option (pointed_Prop * interp_flat_type interp_base_type t)\n      := match e with\n         | TT => Some (trivial, tt)\n         | Var t' x => option_map (fun v => (trivial, v)) (lookupb t' ctx x)\n         | Op t1 tR opc args\n           => match @interpf_side_conditions_gen _ ctx args with\n              | Some (args_cond, argsv)\n                => Some (args_cond /\\ interped_op_side_conditions _ _ opc argsv, interp_op _ _ opc argsv)\n              | None => None\n              end\n         | LetIn _ n ex _ eC\n           => match @interpf_side_conditions_gen _ ctx ex with\n              | Some (x_cond, x)\n                => match @interpf_side_conditions_gen _ (extend ctx n x) eC with\n                   | Some (c_cond, cv)\n                     => Some (x_cond /\\ c_cond, cv)\n                   | None => None\n                   end\n              | None => None\n              end\n         | Pair _ ex _ ey\n           => match @interpf_side_conditions_gen _ ctx ex, @interpf_side_conditions_gen _ ctx ey with\n              | Some (x_cond, xv), Some (y_cond, yv) => Some (x_cond /\\ y_cond, (xv, yv))\n              | None, _ | _, None => None\n              end\n         end%pointed_prop.\n    Definition interpf_side_conditions {t} ctx e : option pointed_Prop\n      := option_map (@fst _ _) (@interpf_side_conditions_gen t ctx e).\n    Definition interp_side_conditions {t} ctx (e : expr t) : interp_flat_type interp_base_type (domain t) -> option pointed_Prop\n      := fun x => interpf_side_conditions (extend ctx (Abs_name e) x) (invert_Abs e).\n    Definition InterpSideConditions {t} (e : expr t) : interp_flat_type interp_base_type (domain t) -> option pointed_Prop\n      := interp_side_conditions empty e.\n  End language.\nEnd Named.\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/InterpSideConditions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.28047471413508634}}
{"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 rvic_clear_flag_spec0 (intid: Z64) (bitmap: Pointer) (adt: RData) : option RData :=\n    match intid, bitmap with\n    | VZ64 _intid, (_bitmap_base, _bitmap_ofst) =>\n      rely is_int64 _intid;\n      when' _idx == interrupt_bitmap_dword_spec (VZ64 _intid) adt;\n      rely is_int64 _idx;\n      when' _bit == interrupt_bit_spec (VZ64 _intid) adt;\n      rely is_int64 _bit;\n      when'' _t'3_base, _t'3_ofst == get_bitmap_loc_spec (_bitmap_base, _bitmap_ofst) (VZ64 _idx) adt;\n      rely is_int _t'3_ofst;\n      rely is_int _bit;\n      when adt == atomic_bit_clear_release_64_spec (_t'3_base, _t'3_ofst) _bit 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/RVIC2/LowSpecs/rvic_clear_flag.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040617, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2804695692874572}}
{"text": "Require Export Mtac.Mtac.\nImport MtacNotations.\n\nRequire Import List.\nImport ListNotations.\n\n\nInductive pattern A (B : A -> Type) (t : A) : Prop := \n| pbase : forall (x:A) (b : t = x -> Mtac (B x)), Unification -> pattern A B t\n| ptele : forall {C}, (forall (x : C), pattern A B t) -> pattern A B t.\n\n\nDefinition NotUnifiableException {A} (x y : A) : Exception. exact exception. Qed.\nDefinition munify A (x y : A) (P : A -> Type) (f : x = y -> M (P y)) : M (P x) \n  := mmatch x with y => [H] f H | _ => raise (NotUnifiableException x y) end.\nArguments munify {A} x y P f.\n\nDefinition open_pattern {A} {P:A->Type} {t:A}  :=\n  mfix1 op (p : pattern A P t) : M (pattern A P t) :=\n    match p return M _ with\n    | pbase _ _ _ x f u => ret p : M (pattern _ _ _)\n    | @ptele _ _ _ C f =>\n      e <- evar C; op (f e)\n    end.\n\nDefinition NoPatternMatches : Exception. exact exception. Qed.\nDefinition Anomaly : Exception. exact exception. Qed.\n\nFixpoint mmatch' {A P} t (ps : list (pattern A P t)) : M (P t) :=\n  match ps with\n  | [] => raise NoPatternMatches\n  | (p :: ps') => \n    p' <- open_pattern p;\n    mtry \n      match p' with\n      | pbase _ _ _ t' f u => \n        munify t t' P f : M (P t)\n      | _ => raise Anomaly\n      end\n    with [? A (x y:A)] NotUnifiableException x y =>\n      mmatch' t ps'\n    end\n  end.\n\nArguments ptele {A B t C} f.\nArguments pbase {A B t} x b u.\n\nNotation \"[? x .. y ] ps\" := (ptele (fun x=> .. (ptele (fun y=>ps)).. ))\n  (at level 202, x binder, y binder, ps at next level) : mtac_pattern_scope.\nNotation \"p => b\" := (pbase p%core (fun _=>b%core) UniRed) \n  (no associativity, at level 201) : mtac_pattern_scope. \nNotation \"p => [ H ] b\" := (pbase p%core (fun H=>b%core) UniRed) \n  (no associativity, at level 201, H at next level) : mtac_pattern_scope. \nNotation \"'_' => b \" := (ptele (fun x=> pbase x (fun _=>b%core) UniRed)) \n  (at level 201, b at next level) : mtac_pattern_scope.\n\nDelimit Scope mtac_pattern_scope with mtac_pattern.\n\nNotation \"'with' | p1 | .. | pn 'end'\" := \n  ((cons p1%mtac_pattern (.. (cons pn%mtac_pattern nil) ..)))\n    (at level 91, p1 at level 210, pn at level 210).\nNotation \"'with' p1 | .. | pn 'end'\" := \n  ((cons p1%mtac_pattern (.. (cons pn%mtac_pattern nil) ..)))\n    (at level 91, p1 at level 210, pn at level 210).\n\nNotation \"'mmatch' x ls\" := (mmatch' x ls).\n\n\n\n(* Test *)\n  Definition NotFound : Exception.\n    exact exception.\n  Qed.\n\nDefinition inl' A (x : A) : forall l : list A, M (In x l) :=\n  mfix1 f (l : list A) : M (In x l) :=\n  mmatch l with\n  | [? l r] l ++ r =>\n      ttry (\n        il <- f l;\n        ret (in_or_app l r x (or_introl il)) )\n      (fun e=>mmatch e with NotFound =>\n        ir <- f r;\n        ret (in_or_app l r x (or_intror ir))\n      end)\n  | [? s] (x :: s) => ret (in_eq _ _)\n  | [? y s] (y :: s) => r <- f s; ret (in_cons y _ _ r)\n  | _ => raise NotFound\n  end.\n\nExample testM (\nx01 x11 x21 x31 x41 x51 x61 x71 x81 x91 \nx02 x12 x22 x32 x42 x52 x62 x72 x82 x92 \nx03 x13 x23 x33 x43 x53 x63 x73 x83 x93 \nx04 x14 x24 x34 x44 x54 x64 x74 x84 x94 \nx05 x15 x25 x35 x45 x55 x65 x75 x85 x95 \nx06 x16 x26 x36 x46 x56 x66 x76 x86 x96 \nx07 x17 x27 x37 x47 x57 x67 x77 x87 x97 \nx08 x18 x28 x38 x48 x58 x68 x78 x88 x98 \nx09 x19 x29 x39 x49 x59 x69 x79 x89 x99 \n : nat) : In x99 [\nx01;x11;x21;x31;x41;x51;x61;x71;x81;x91;\nx02;x12;x22;x32;x42;x52;x62;x72;x82;x92;\nx03;x13;x23;x33;x43;x53;x63;x73;x83;x93;\nx04;x14;x24;x34;x44;x54;x64;x74;x84;x94;\nx05;x15;x25;x35;x45;x55;x65;x75;x85;x95;\nx06;x16;x26;x36;x46;x56;x66;x76;x86;x96;\nx07;x17;x27;x37;x47;x57;x67;x77;x87;x97;\nx08;x18;x28;x38;x48;x58;x68;x78;x88;x98;\nx09;x19;x29;x39;x49;x59;x69;x79;x89;x99\n].\nProof.\n  Time rrun (inl' _ _ _).  \nQed.\n\nRequire Import Mtac.Mtactics.\nExample testo (\nx01 x11 x21 x31 x41 x51 x61 x71 x81 x91 \nx02 x12 x22 x32 x42 x52 x62 x72 x82 x92 \nx03 x13 x23 x33 x43 x53 x63 x73 x83 x93 \nx04 x14 x24 x34 x44 x54 x64 x74 x84 x94 \nx05 x15 x25 x35 x45 x55 x65 x75 x85 x95 \nx06 x16 x26 x36 x46 x56 x66 x76 x86 x96 \nx07 x17 x27 x37 x47 x57 x67 x77 x87 x97 \nx08 x18 x28 x38 x48 x58 x68 x78 x88 x98 \nx09 x19 x29 x39 x49 x59 x69 x79 x89 x99 \n : nat) : In x99 [\nx01;x11;x21;x31;x41;x51;x61;x71;x81;x91;\nx02;x12;x22;x32;x42;x52;x62;x72;x82;x92;\nx03;x13;x23;x33;x43;x53;x63;x73;x83;x93;\nx04;x14;x24;x34;x44;x54;x64;x74;x84;x94;\nx05;x15;x25;x35;x45;x55;x65;x75;x85;x95;\nx06;x16;x26;x36;x46;x56;x66;x76;x86;x96;\nx07;x17;x27;x37;x47;x57;x67;x77;x87;x97;\nx08;x18;x28;x38;x48;x58;x68;x78;x88;x98;\nx09;x19;x29;x39;x49;x59;x69;x79;x89;x99\n].\nProof.\n  Time rrun (ListMtactics.inlist _ _).  \nQed.", "meta": {"author": "beta-ziliani", "repo": "mtac-plugin", "sha": "ec9178418ab748c1a860c858e845a2b953c66ac1", "save_path": "github-repos/coq/beta-ziliani-mtac-plugin", "path": "github-repos/coq/beta-ziliani-mtac-plugin/mtac-plugin-ec9178418ab748c1a860c858e845a2b953c66ac1/theories/Mmatch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.28046956928745714}}
{"text": "Require Export FcEtt.imports.\nRequire Import ett_ott.\nRequire Import ett_inf.\nRequire Import ett_match.\n\nInductive pattern_renamed : tm -> tm -> available_props ->\n                                        available_props -> Prop :=\n | pattern_renamed_Base : forall (F:const) (D:available_props),\n     pattern_renamed (a_Fam F) (a_Fam F) D  AtomSetImpl.empty\n | pattern_renamed_AppRel : forall (p1:tm) (R:role) (x:tmvar) (p2:tm)\n                                  (y:tmvar) (D D':available_props),\n     pattern_renamed p1 p2 D D' -> ~ AtomSetImpl.In  y (D  \\u  D') ->\n     pattern_renamed (a_App p1 (Role R) (a_Var_f x))\n                     (a_App p2 (Role R) (a_Var_f y)) D  (singleton  y  \\u  D')\n | pattern_renamed_AppIrrel : forall (p1 p2:tm) (D D':available_props),\n     pattern_renamed p1 p2 D D' ->\n     pattern_renamed (a_App p1 (Rho Irrel) a_Bullet)\n                     (a_App p2 (Rho Irrel) a_Bullet) D D'\n | pattern_renamed_CApp : forall (p1 p2:tm) (D D':available_props),\n     pattern_renamed p1 p2 D D' ->\n     pattern_renamed (a_CApp p1 g_Triv) (a_CApp p2 g_Triv) D D'.\n\nHint Constructors pattern_renamed.\n\nLemma pattern_renamed_extend_support : forall p p' D D' D1,\n      pattern_renamed p p' D D' ->\n      AtomSetImpl.inter (fv_tm_tm_tm p') D1 [<=] empty ->\n      pattern_renamed p p' (D \\u D1) D'.\nProof. intros. induction H; simpl in *; eauto.\n        - constructor. eapply IHpattern_renamed.\n          eapply (Subset_trans _ H0). fsetdec.\n        - constructor. eapply IHpattern_renamed.\n          eapply (Subset_trans _ H0).\n        - constructor. eapply IHpattern_renamed.\n          eapply (Subset_trans _ H0).\n          Unshelve. all: clear. all:fsetdec.\nQed.\n\nLemma Rename_narrow : forall p b p' b' D D' S, Rename p b p' b' D D' ->\n      S [<=] D -> Rename p b p' b' S D'.\nProof. intros. induction H; eauto.\n       econstructor. eauto. fsetdec.\nQed.\n\nLemma inter_empty : forall S1 S2, (forall x, x `in` S1 -> x `notin` S2) ->\n      AtomSetImpl.inter S1 S2 [<=] empty.\nProof. intros. intro. intro. apply inter_iff in H0. apply empty_iff.\n       inversion H0. eapply H; eauto.\nQed.\n\nLemma Rename_inter_sub_empty : forall p b p' b' D D' S1 S2,\n      Rename p b p' b' D D' -> S1 [<=] D -> S2 [<=] D' ->\n      AtomSetImpl.inter S1 S2 [<=] empty.\nProof. intros. apply inter_empty. intros. eapply subset_notin.\n       eapply Rename_inter_empty. eauto. eauto. auto.\nQed.\n\n\nFixpoint tm_var_pairs (a p : tm) : list (tm * var) :=\n   match (a,p) with\n | (a_Fam F, a_Fam F') => []\n | (a_App a1 (Role R) a2, a_App p1 (Role R') (a_Var_f x)) =>\n                                       tm_var_pairs a1 p1 ++ [(a2,x)]\n | (a_App a (Rho Irrel) a', a_App p (Rho Irrel) a_Bullet) =>\n                                       tm_var_pairs a p\n | (a_CApp a g_Triv, a_CApp p g_Triv) => tm_var_pairs a p\n | (_,_) => []\n   end.\n\nDefinition chain_subst a p b := fold_left\n       (fun b' a'x' => tm_subst_tm_tm a'x'.1 a'x'.2 b') (tm_var_pairs a p) b.\n\nLemma chain_subst_lc : forall a p b, tm_pattern_agree a p -> lc_tm b ->\n      lc_tm (chain_subst a p b).\nProof. intros. induction H; simpl; auto.\n       unfold chain_subst in *. simpl. rewrite fold_left_app. simpl.\n       apply tm_subst_tm_tm_lc_tm. auto. auto.\nQed.\n\nLemma chain_subst_fv : forall a p b, tm_pattern_agree a p ->\n      fv_tm_tm_tm (chain_subst a p b) [<=]\n        (AtomSetImpl.diff (fv_tm_tm_tm b) (fv_tm_tm_tm p)) \\u (fv_tm_tm_tm a).\nProof. intros. induction H; eauto.\n        - pose (P := fv_tm_tm_tm_tm_subst_tm_tm_upper (chain_subst a1 p1 b) a2 x).\n          unfold chain_subst in *. simpl. rewrite fold_left_app. simpl.\n          eapply Subset_trans. eapply P. fsetdec.\n        - unfold chain_subst in *. simpl. fsetdec.\n        - unfold chain_subst in *. simpl. fsetdec.\nQed.\n\nLemma Rename_lc_body : forall p p' b b' D D', Rename p b p' b' D D' ->\n      lc_tm b.\nProof. intros. induction H; eauto.\nQed.\n\nLemma Rename_pattern_renamed : forall p b p' b' D D', Rename p b p' b' D D' ->\n      pattern_renamed p p' D D'.\nProof. intros. induction H; eauto.\nQed.\n\nLemma Rename_chain_subst : forall p b p' b' D D', Rename p b p' b' D D' ->\n                           b' = chain_subst p' p b.\nProof. intros. induction H; simpl; eauto.\n       unfold chain_subst in *. simpl. rewrite fold_left_app. simpl.\n       rewrite <- IHRename. auto.\nQed.\n\nLemma chain_subst_Rename : forall p b p' D D', pattern_renamed p p' D D' ->\n      lc_tm b -> Rename p b p' (chain_subst p' p b) D D'.\nProof. intros. induction H; simpl; eauto. unfold chain_subst in *.\n       simpl. rewrite fold_left_app. simpl. eauto.\nQed.\n\nLemma matchsubst_chain_subst : forall a p b, tm_pattern_agree a p ->\n                               matchsubst a p b = chain_subst a p b.\nProof. intros. induction H; simpl; eauto. unfold chain_subst in *. simpl.\n       rewrite fold_left_app. simpl. rewrite <- IHtm_pattern_agree. auto.\nQed.\n\nLemma subst_via : forall a y z,\n      (forall b, y `notin` fv_tm_tm_tm b ->\n      tm_subst_tm_tm a y (tm_subst_tm_tm (a_Var_f y) z b) =\n      tm_subst_tm_tm a z b) /\\\n      (forall brs, y `notin` fv_tm_tm_brs brs ->\n      tm_subst_tm_brs a y (tm_subst_tm_brs (a_Var_f y) z brs) =\n      tm_subst_tm_brs a z brs) /\\\n      (forall g, y `notin` fv_tm_tm_co g ->\n      tm_subst_tm_co a y (tm_subst_tm_co (a_Var_f y) z g) =\n      tm_subst_tm_co a z g) /\\\n      (forall phi, y `notin` fv_tm_tm_constraint phi ->\n      tm_subst_tm_constraint a y (tm_subst_tm_constraint (a_Var_f y) z phi) =\n      tm_subst_tm_constraint a z phi).\nProof. intros. apply tm_brs_co_constraint_mutind; intros; simpl;\n       try (simpl in H; try simpl in H1; try simpl in H2; f_equal; eauto; fail).\n       destruct (eq_var x z). simpl. rewrite eq_dec_refl. auto.\n       simpl. destruct (eq_var x y). subst. simpl in H. fsetdec. auto.\nQed.\n\nLemma subst_via_tm : forall a y z b, y `notin` fv_tm_tm_tm b ->\n      tm_subst_tm_tm a y (tm_subst_tm_tm (a_Var_f y) z b) =\n      tm_subst_tm_tm a z b.\nProof. intros. eapply subst_via; eauto.\nQed.\n\nLemma subst_commute : forall a1 a2 x1 x2, x1 `notin` fv_tm_tm_tm a2 ->\n      x2 `notin` fv_tm_tm_tm a1 -> x1 <> x2 ->\n      (forall b, tm_subst_tm_tm a2 x2 (tm_subst_tm_tm a1 x1 b) =\n      tm_subst_tm_tm a1 x1 (tm_subst_tm_tm a2 x2 b)) /\\\n      (forall brs, tm_subst_tm_brs a2 x2 (tm_subst_tm_brs a1 x1 brs) =\n      tm_subst_tm_brs a1 x1 (tm_subst_tm_brs a2 x2 brs)) /\\\n      (forall g, tm_subst_tm_co a2 x2 (tm_subst_tm_co a1 x1 g) =\n      tm_subst_tm_co a1 x1 (tm_subst_tm_co a2 x2 g)) /\\\n      (forall phi, tm_subst_tm_constraint a2 x2\n       (tm_subst_tm_constraint a1 x1 phi) =\n        tm_subst_tm_constraint a1 x1 (tm_subst_tm_constraint a2 x2 phi)).\nProof. intros a1 a2 x1 x2 P Q R.\n       apply tm_brs_co_constraint_mutind; intros; simpl; eauto;\n       try (f_equal; eauto; fail).\n       destruct (eq_var x x1). destruct (eq_var x x2). subst. contradiction.\n       subst. simpl. rewrite eq_dec_refl. rewrite tm_subst_tm_tm_fresh_eq; auto.\n       destruct (eq_var x x2). subst. simpl. rewrite eq_dec_refl.\n       rewrite tm_subst_tm_tm_fresh_eq; auto.\n       rewrite tm_subst_tm_tm_fresh_eq; auto.\n       rewrite tm_subst_tm_tm_fresh_eq; auto.\nQed.\n\nLemma subst_commute_tm : forall a1 a2 x1 x2 b, x1 `notin` fv_tm_tm_tm a2 ->\n      x2 `notin` fv_tm_tm_tm a1 -> x1 <> x2 ->\n      tm_subst_tm_tm a2 x2 (tm_subst_tm_tm a1 x1 b) =\n      tm_subst_tm_tm a1 x1 (tm_subst_tm_tm a2 x2 b).\nProof. intros. eapply subst_commute; auto.\nQed.\n\nLemma chain_subst_subst_commute : forall a p x a' b,\n      tm_pattern_agree a p ->\n      x `notin` fv_tm_tm_tm a -> x `notin` fv_tm_tm_tm p ->\n      AtomSetImpl.inter (fv_tm_tm_tm p) (fv_tm_tm_tm a') [<=] empty ->\n      chain_subst a p (tm_subst_tm_tm a' x b) =\n      tm_subst_tm_tm a' x (chain_subst a p b).\nProof. intros. generalize dependent b. induction H; intros; simpl; eauto.\n        - simpl in H0, H1, H2. unfold chain_subst in *. simpl.\n          rewrite fold_left_app. rewrite fold_left_app. simpl.\n          rewrite subst_commute_tm. fsetdec. fsetdec. fsetdec.\n          rewrite IHtm_pattern_agree. fsetdec. fsetdec. fsetdec. auto.\n        - simpl in H0, H1, H2. unfold chain_subst in *. simpl.\n          rewrite IHtm_pattern_agree. fsetdec. fsetdec. fsetdec. auto.\n        - simpl in H0, H1, H2. unfold chain_subst in *. simpl.\n          rewrite IHtm_pattern_agree. fsetdec. fsetdec. fsetdec. auto.\nQed.\n\n\nTheorem MatchSubst_Rename_preserve : forall p b D D' p1 b1 D1 p2 b2 D2 a a1 a2,\n   tm_pattern_agree a p -> Rename p b p1 b1 D D1 -> Rename p b p2 b2 D' D2 ->\n   (fv_tm_tm_tm a \\u fv_tm_tm_tm p \\u fv_tm_tm_tm b) [<=] D ->\n   (fv_tm_tm_tm a \\u fv_tm_tm_tm p \\u fv_tm_tm_tm b) [<=] D' ->\n   uniq_atoms_pattern p -> MatchSubst a p1 b1 a1 -> MatchSubst a p2 b2 a2 ->\n   a1 = a2.\nProof. intros. generalize dependent p1. generalize dependent b1.\n       generalize dependent D. generalize dependent D1. generalize dependent a1.\n       generalize dependent a2. generalize dependent p2. generalize dependent b2.\n       generalize dependent D'. generalize dependent D2. generalize dependent b.\n       induction H; intros.\n         - inversion H5. inversion H0. inversion H6. inversion H1. subst. auto.\n         - unfold uniq_atoms_pattern in *. simpl in *.\n           inversion H5; subst. inversion H7; inversion H1; subst.\n           inversion H6; subst.\n           assert (L0 : lc_tm b). { eapply Rename_lc_body; eauto. }\n           assert (L1 : tm_pattern_agree a1 p4).\n             { eapply MatchSubst_match; eauto. }\n           assert (L2 : tm_pattern_agree a1 p5).\n             { eapply MatchSubst_match; eauto. }\n           assert (L3 : pattern_renamed p1 p4 D D'0).\n             { eapply Rename_pattern_renamed; eauto. }\n           assert (L4 : pattern_renamed p1 p5 D' D'1).\n             { eapply Rename_pattern_renamed; eauto. }\n           assert (L5 : tm_pattern_agree p4 p1).\n             { eapply tm_pattern_agree_cong; eauto.\n               apply tm_pattern_agree_tm_tm_agree; auto. }\n           assert (L6 : tm_pattern_agree p5 p1).\n             { eapply tm_pattern_agree_cong. eapply H0.\n               apply tm_pattern_agree_tm_tm_agree; auto. }\n           pose (P1 := matchsubst_ind_fun H18). clearbody P1.\n           move: (matchsubst_ind_fun H20) => P2.\n           rewrite <- P1. rewrite <- P2.\n           rewrite matchsubst_chain_subst. auto.\n           rewrite matchsubst_chain_subst. auto.\n           move: (Rename_chain_subst H16) => P3.\n           pose (P4 := Rename_chain_subst H27). rewrite P3. rewrite P4.\n           pick fresh z.\n           assert \n           (HYP : chain_subst a1 p4 (chain_subst p4 p1\n                      (tm_subst_tm_tm (a_Var_f z) x b)) =\n                  chain_subst a1 p5 (chain_subst p5 p1\n                      (tm_subst_tm_tm (a_Var_f z) x b))).\n           { assert (lc_tm (tm_subst_tm_tm (a_Var_f z) x b)).\n             { eapply tm_subst_tm_tm_lc_tm; eauto. }\n             apply IHtm_pattern_agree with (b := tm_subst_tm_tm (a_Var_f z) x b)\n             (D := D \\u singleton z)(D1 := D'0)(p3 := p4)\n             (b1 := chain_subst p4 p1 (tm_subst_tm_tm (a_Var_f z) x b))\n             (D' := D' \\u singleton z)(D2 := D'1)(p2 := p5)\n             (b2 := chain_subst p5 p1 (tm_subst_tm_tm (a_Var_f z) x b)).\n             -- rewrite <- app_nil_r. eapply NoDup_remove_1. eauto.\n             -- rewrite (fv_tm_tm_tm_tm_subst_tm_tm_upper b (a_Var_f z) x).\n                simpl.\n                assert (h0 : singleton z [<=] singleton z). auto.\n                apply (Subset_union H3) in h0.\n                eapply (Subset_trans _ h0).\n             -- apply chain_subst_Rename.\n                eapply pattern_renamed_extend_support; eauto.\n                clear - Fr. assert (z `notin` fv_tm_tm_tm p5).\n                fsetdec. clear - H. fsetdec. auto.\n             -- apply matchsubst_fun_ind. eauto.\n                eapply chain_subst_lc; eauto. auto.\n                apply matchsubst_chain_subst; auto.\n             -- rewrite (fv_tm_tm_tm_tm_subst_tm_tm_upper b (a_Var_f z) x).\n                simpl.\n                assert (h0 : singleton z [<=] singleton z). auto.\n                apply (Subset_union H2) in h0.\n                eapply (Subset_trans _ h0).\n             -- apply chain_subst_Rename.\n                eapply pattern_renamed_extend_support; eauto.\n                clear - Fr. assert (z `notin` fv_tm_tm_tm p4).\n                fsetdec. clear - H. fsetdec. auto.\n             -- apply matchsubst_fun_ind. eauto.\n                eapply chain_subst_lc; eauto. auto.\n                apply matchsubst_chain_subst; auto.\n                Unshelve. all: clear. all: fsetdec.\n           }\n           rewrite <- tm_subst_tm_tm_back_forth with (x := y) (y := z)\n          (b := tm_subst_tm_tm (a_Var_f y) x (chain_subst p4 p1 b)).\n           rewrite -> subst_via_tm with (y := y) (b := chain_subst p4 p1 b).\n           rewrite -> chain_subst_subst_commute with (a' := a_Var_f y) (x := z).\n           rewrite -> subst_via_tm with (y := y).\n           rewrite <- chain_subst_subst_commute with (a' := a_Var_f z).\n           rewrite HYP.\n           rewrite <- subst_via_tm with (y := y0)(z := z).\n           rewrite <- chain_subst_subst_commute with (a' := a_Var_f y0) (x := z).\n           rewrite -> chain_subst_subst_commute with (a' := a_Var_f z) (x := x).\n           rewrite -> subst_via_tm with (y := z)(z := x). auto.\n           -- rewrite chain_subst_fv. clear - Fr.\n              rewrite AtomSetProperties.diff_subset. fsetdec. auto.\n           -- auto.\n           -- move: (Rename_fv_new_pattern H27) => M1. rewrite M1.\n              move: (Rename_inter_empty H27) => M2. apply M2.\n              clear - H3. fsetdec.\n           -- move: (tm_pattern_agree_pattern H0) => M1.\n              intro. move: (pattern_fv M1 H8) => M2.\n              clear - H4 M2. apply NoDup_remove in H4. \n              inversion H4. rewrite app_nil_r in H0. contradiction.\n           -- clear - Fr. simpl. assert (z `notin` fv_tm_tm_tm p1).\n              fsetdec. clear - H. fsetdec.\n           -- auto.\n           -- clear - Fr. simpl. assert (z `notin` fv_tm_tm_tm a1).\n              fsetdec. clear - H. fsetdec.\n           -- clear - Fr. simpl. assert (z `notin` fv_tm_tm_tm p5).\n              fsetdec. clear - H. fsetdec.\n           -- simpl. move: (Rename_fv_new_pattern H27) => M1.\n              clear - H28 M1. fsetdec.\n           -- repeat rewrite chain_subst_fv.\n              rewrite fv_tm_tm_tm_tm_subst_tm_tm_upper. simpl.\n              apply AtomSetProperties.not_in_union.\n              repeat rewrite AtomSetProperties.diff_subset.\n              apply AtomSetProperties.not_in_union.\n              apply AtomSetProperties.not_in_union.\n              clear - Fr. fsetdec. clear - H3 H28. fsetdec.\n              move: (Rename_fv_new_pattern H27) => M1. clear - M1 H28.\n              fsetdec. clear - H3 H28. fsetdec. auto. auto.\n           -- auto.\n           -- move: (Rename_fv_new_pattern H16) => M1. rewrite M1.\n              move: (Rename_inter_empty H16) => M2. apply M2.\n              clear - H2. fsetdec. \n           -- move: (tm_pattern_agree_pattern H0) => M1.\n              intro. move: (pattern_fv M1 H8) => M2.\n              clear - H4 M2. apply NoDup_remove in H4.\n              inversion H4. rewrite app_nil_r in H0. contradiction.\n           -- clear - Fr. simpl. assert (z `notin` fv_tm_tm_tm p1).\n              fsetdec. clear - H. fsetdec.\n           -- rewrite chain_subst_fv.\n              rewrite fv_tm_tm_tm_tm_subst_tm_tm_upper. simpl.\n              apply AtomSetProperties.not_in_union.\n              rewrite AtomSetProperties.diff_subset.\n              apply AtomSetProperties.not_in_union.\n              clear - Fr. fsetdec. rewrite chain_subst_fv.\n              rewrite AtomSetProperties.diff_subset.\n              move: (Rename_fv_new_pattern H16) => M1. clear - H2 H17 M1.\n              fsetdec. auto. clear - H2 H17. fsetdec. auto.\n           -- auto.\n           -- clear - Fr. fsetdec.\n           -- clear - Fr. fsetdec.\n           -- move: (Rename_fv_new_pattern H16) => M1. clear - H17 M1.\n              simpl. fsetdec.\n           -- rewrite chain_subst_fv. rewrite AtomSetProperties.diff_subset.\n              apply AtomSetProperties.not_in_union. clear - H2 H17. fsetdec.\n              move: (Rename_fv_new_pattern H16) => M1. rewrite M1. clear - H17.\n              fsetdec. auto.\n           -- rewrite fv_tm_tm_tm_tm_subst_tm_tm_upper. simpl.\n              apply AtomSetProperties.not_in_union. clear - Fr.\n              do 6 apply notin_union_2 in Fr. apply notin_union_1 in Fr. auto.\n              rewrite chain_subst_fv. rewrite AtomSetProperties.diff_subset.\n              clear - Fr. fsetdec. auto.\n         - unfold uniq_atoms_pattern in *. simpl in *.\n           inversion H5; subst. inversion H7; inversion H1; subst.\n           inversion H6; subst.\n           eapply IHtm_pattern_agree with (b := b)(D' := D') (D := D). auto.\n           fsetdec. eapply H17. auto. fsetdec. eapply H9. auto.\n         - unfold uniq_atoms_pattern in *. simpl in *.\n           inversion H0; subst. inversion H5; inversion H1; subst.\n           inversion H6; subst.\n           eapply IHtm_pattern_agree with (b := b)(D' := D') (D := D). auto.\n           fsetdec. eapply H14. auto. fsetdec. eapply H8. auto.\nQed.\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/ett_rename.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2804695629144997}}
{"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.\n\n(* Require Import MultiSigWallet.Proofs.tvmFunctionsProofs. *)\n\nImport DePoolSpec.LedgerClass.SolidityNotations. \n\nLocal Open Scope solidity_scope.\n\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 \n \n \n (* constructor() public {\n        bool ok = false;\n        for (uint8 i = 0; i < 2; ++i) {\n            TvmBuilder b;\n            b.store(address(msg.sender), i);\n            uint256 publicKey = tvm.hash(b.toCell());\n            ok = ok || tvm.pubkey() == publicKey;\n        }\n        require(ok, ERROR_IS_NOT_DEPOOL);\n        m_dePool = msg.sender;\n    }\n*) \n    \n\nOpaque Z.eqb.\nLemma DePoolProxyContract_Ф_Constructor5_exec : forall (l: Ledger) ,\n                                      (*LedgerT ( XErrorValue True XInteger )*)\nlet b := default in \n              (* bool ok = false; *) \nlet ok := false in\n(*first time, i = 0*)\n            (* TvmBuilder b;\n               b.store(address(msg.sender), i); *)\nlet b' := builder_store b ( eval_state ( msg_sender ) l )  0 in \n            (* uint256 publicKey = tvm.hash(b.toCell()) *)\nlet publicKey := tvm_hash ( toCell b' ) in\n            (* ok = ok || tvm.pubkey() == publicKey; *)\nlet ok' := ( ok || ( ( eval_state ( tvm_pubkey ) l ) =? publicKey ) )%bool in \n\n(*second time, i = 1*)\n            (* TvmBuilder b;\n               b.store(address(msg.sender), i); *)\nlet b'' := default in \nlet b''' := builder_store b'' ( eval_state ( msg_sender ) l ) 1 in\n            (* uint256 publicKey = tvm.hash(b.toCell()) *)\nlet publicKey' := tvm_hash ( toCell b''' )  in\n            (* ok = ok || tvm.pubkey() == publicKey; *)\nlet ok'' := ( ok' || ( ( eval_state ( tvm_pubkey ) l ) =? publicKey' ) )%bool in\n            (* require(ok, ERROR_IS_NOT_DEPOOL); *)\nlet req : bool := ( ok'' ) in\n\n         exec_state ( ↓ DePoolProxyContract_Ф_constructor5 ) l =\n                 if req then  \n          {$ l With DePoolProxyContract_ι_m_dePool := ( eval_state ( msg_sender ) l ) $}\n                 else l.\nProof.   \n   intros. \n   destruct l. \n   destruct Ledger_ι_VMState.\n   compute. destructIf; auto. \nQed. \n \nLemma DePoolProxyContract_Ф_Constructor5_eval : forall (l: Ledger) ,\n                                      (*LedgerT ( XErrorValue True XInteger )*) \nlet b := default in \n              (* bool ok = false; *) \nlet ok := false in\n(*first time, i = 0*)\n            (* TvmBuilder b;\n               b.store(address(msg.sender), i); *)\nlet b' := builder_store b ( eval_state ( msg_sender ) l )  0 in \n            (* uint256 publicKey = tvm.hash(b.toCell()) *)\nlet publicKey := tvm_hash ( toCell b' ) in\n            (* ok = ok || tvm.pubkey() == publicKey; *)\nlet ok' := ( ok || ( ( eval_state ( tvm_pubkey ) l ) =? publicKey ) )%bool in \n\n(*second time, i = 1*)\n            (* TvmBuilder b;\n               b.store(address(msg.sender), i); *)\nlet b'' := default in \nlet b''' := builder_store b'' ( eval_state ( msg_sender ) l ) 1 in\n            (* uint256 publicKey = tvm.hash(b.toCell()) *)\nlet publicKey' := tvm_hash ( toCell b''' )  in\n            (* ok = ok || tvm.pubkey() == publicKey; *)\nlet ok'' := ( ok' || ( ( eval_state ( tvm_pubkey ) l ) =? publicKey' ) )%bool in\n            (* require(ok, ERROR_IS_NOT_DEPOOL); *)\nlet req : bool := ( ok'' ) in\n\n    eval_state (↓ DePoolProxyContract_Ф_constructor5 ) l =  \n    if req then Value I\n           else Error (eval_state ( ↑10 ε DePoolProxyContract_ι_ERROR_IS_NOT_DEPOOL ) l ). \nProof. \n  intros. \n  destruct l.  (* destruct Ledger_ι_VMState. *)\n  compute. destructIf; auto. \nQed. \n \n(* \n (* function process_new_stake(\n        uint64 queryId,\n        uint256 validatorKey,\n        uint32 stakeAt,\n        uint32 maxFactor,\n        uint256 adnlAddr,\n        bytes signature,\n        address elector\n    ) external override  {\n        require(msg.sender == m_dePool, ERROR_IS_NOT_DEPOOL);\n        uint carry = msg.value - DePoolLib.PROXY_FEE;\n        require(address(this).balance >= carry + DePoolLib.MIN_PROXY_BALANCE, ERROR_BAD_BALANCE);\n        IElector(elector).process_new_stake{value: msg.value - DePoolLib.PROXY_FEE}(\n            queryId, validatorKey, stakeAt, maxFactor, adnlAddr, signature\n        );\n    } *)\nDefinition DePoolProxyContract_Ф_process_new_stake  ( Л_queryId : XInteger64 )\n                                                    ( Л_validatorKey : XInteger256 )\n                                                    ( Л_stakeAt : XInteger32 )\n                                                    ( Л_maxFactor : XInteger32 )\n                                                    ( Л_adnlAddr : XInteger256 )\n                                                    ( Л_signature : XList XInteger8 )\n                                                    ( Л_elector : XAddress ) \n                                                : LedgerT ( XErrorValue True XInteger ) :=\n Require2 {{ msg_sender () ?== ↑ε10 DePoolProxyContract_ι_m_dePool , ↑ε10 DePoolProxyContract_ι_ERROR_IS_NOT_DEPOOL }} ; \n U0! Л_carry :=  msg_value () !- ↑ε9 DePoolLib_ι_PROXY_FEE ;\n Require {{ tvm_balance () ?>=  $Л_carry !+ (↑ε9 DePoolLib_ι_MIN_PROXY_BALANCE) , ↑ε10 DePoolProxyContract_ι_ERROR_BAD_BALANCE }} ;\n sendMessage {| contractAddress := Л_elector;\n\t\t\t\tcontractFunction := IElector_И_process_new_stakeF Л_queryId Л_validatorKey Л_stakeAt Л_maxFactor Л_adnlAddr  Л_signature;\n\t\t\t\tcontractMessage := {$ default with  messageValue := Л_carry $} |}*) \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\nLemma DePoolProxyContract_Ф_process_new_stake_exec : forall ( Л_queryId : XInteger64 ) \n                                                             ( Л_validatorKey : XInteger256 ) \n                                                             ( Л_stakeAt : XInteger32 ) \n                                                             ( Л_maxFactor : XInteger32 ) \n                                                             ( Л_adnlAddr : XInteger256 ) \n                                                             ( Л_signature :  XList XInteger8 ) \n                                                             ( Л_elector : XAddress ) \n                                                             (l: Ledger) ,\n    exec_state ( ↓ DePoolProxyContract_Ф_process_new_stake Л_queryId Л_validatorKey Л_stakeAt Л_maxFactor Л_adnlAddr Л_signature Л_elector ) l =\n\n   let msgSender := eval_state msg_sender l in\n   let dePoolAddress := eval_state (↑10 ε DePoolProxyContract_ι_m_dePool) l in\n   let msgValue := eval_state msg_value l in\n   let proxyFee := eval_state (↑9 ε DePoolLib_ι_PROXY_FEE) l in  \n   let carry := msgValue - proxyFee in \n   let oldMessages := eval_state (↑16 ε VMState_ι_messages) l in \n   let newMessage :ContractsFunctionWithMessage  := {| contractAddress :=  Л_elector;\n                         contractFunction := IElector_И_process_new_stakeF Л_queryId Л_validatorKey Л_stakeAt Л_maxFactor Л_adnlAddr  Л_signature ;\n                         contractMessage :=  {| messageValue := carry;\n                                               messageFlag := 0 ;\n                                               messageBounce := false |} |} in \n    let balance := eval_state ( tvm_balance ) l in\n    let minBalance := eval_state ( ↑9 ε DePoolLib_ι_MIN_PROXY_BALANCE ) l in\n    let req2 : bool := balance >=? carry + minBalance in\n    if ( msgSender =? dePoolAddress) then\n      if req2 then \n          {$ l With VMState_ι_messages := newMessage :: oldMessages $} \n      else l \n    else l.  \n Proof. \n   intros. \n   destruct l. destruct Ledger_ι_VMState , Ledger_ι_DePoolProxyContract, Ledger_ι_DePoolLib.\n   compute. \n   repeat destructIf; auto. \n Qed.\n\nLemma DePoolProxyContract_Ф_process_new_stake_eval : forall ( Л_queryId : XInteger64 ) \n                                                             ( Л_validatorKey : XInteger256 ) \n                                                             ( Л_stakeAt : XInteger32 ) \n                                                             ( Л_maxFactor : XInteger32 ) \n                                                             ( Л_adnlAddr : XInteger256 ) \n                                                             ( Л_signature : XList XInteger8 ) \n                                                             ( Л_elector : XAddress ) \n                                                             (l: Ledger) ,\n    let msgSender := eval_state msg_sender l in\n    let dePoolAddress := eval_state (↑10 D2! DePoolProxyContract_ι_m_dePool) l in\n    let error1 := eval_state (↑10 D2! DePoolProxyContract_ι_ERROR_IS_NOT_DEPOOL) l in\n    let error2 := eval_state (↑10 D2! DePoolProxyContract_ι_ERROR_BAD_BALANCE) l in\n   let msgValue := eval_state msg_value l in\n   let proxyFee := eval_state (↑9 ε DePoolLib_ι_PROXY_FEE) l in \n   let carry := msgValue - proxyFee in \n    let balance := eval_state ( tvm_balance ) l in\n    let minBalance := eval_state ( ↑9 ε DePoolLib_ι_MIN_PROXY_BALANCE ) l in\n    let req2 : bool := balance >=? carry + minBalance in\n\n\n    eval_state (DePoolProxyContract_Ф_process_new_stake Л_queryId Л_validatorKey Л_stakeAt Л_maxFactor Л_adnlAddr Л_signature Л_elector ) l = \n    if (msgSender =? dePoolAddress) \n    then if req2 then Value I\n                 else Error error2\n    else Error error1 . \n Proof. \n  intros. \n   destruct l. destruct Ledger_ι_VMState , Ledger_ι_DePoolProxyContract, Ledger_ι_DePoolLib.\n   compute. \n   repeat destructIf; auto. \n Qed. \n \n (* (* function onStakeAccept ( uint64 queryId , uint32 comment ) \n \t \t public functionID ( 0xF374484C ) { IDePool ( m_dePool ) . onStakeAccept \n \t \t { value : msg_value - DePoolLib . PROXY_FEE } ( queryId , comment \n       , msg_sender ) ; } *)\n       \nDefinition DePoolProxyContract_Ф_onStakeAccept ( Л_queryId : XInteger64 )( Л_comment : XInteger32 ) : LedgerT True := \n\tU0! Л_dePool := ↑ε10 DePoolProxyContract_ι_m_dePool ;\n\tU0! Л_value := msg_value () !- ↑ε9 DePoolLib_ι_PROXY_FEE ;\n\tU0! Л_sender := msg_sender ()  ;\n    sendMessage {| contractAddress := Л_dePool;\n\t\t\t\t   contractFunction := DePoolContract_Ф_onStakeAcceptF Л_queryId Л_comment Л_sender ;\n           contractMessage := {$ default with  messageValue := Л_value $} |} . \n           *) \n Lemma DePoolProxyContract_Ф_onStakeAccept_exec : forall ( Л_queryId : XInteger64 ) ( Л_comment : XInteger32 ) (l: Ledger) , \n let dePoolAddress := eval_state (↑10 D2! DePoolProxyContract_ι_m_dePool) l in\n let msgValue := eval_state msg_value l in\n let proxyFee := eval_state (↑9 D2! DePoolLib_ι_PROXY_FEE) l in\n let value := msgValue - proxyFee in\n let msgSender := eval_state msg_sender l in\n let oldMessages := eval_state (↑16 D2! VMState_ι_messages) l in\n let newMessage  := {| contractAddress  := dePoolAddress;\n                       contractFunction := DePoolContract_Ф_onStakeAcceptF Л_queryId Л_comment msgSender ;\n                       contractMessage  := {$ default with messageValue := value $} |} in \n                                                    \n    exec_state (DePoolProxyContract_Ф_onStakeAccept Л_queryId Л_comment ) l =  \n    {$ l With VMState_ι_messages := newMessage :: oldMessages $}.  \n Proof. \n   intros. auto. \n Qed. \n \n Lemma DePoolProxyContract_Ф_onStakeAccept_eval : forall ( Л_queryId : XInteger64 ) ( Л_comment : XInteger32 ) (l: Ledger) , \n \t eval_state (DePoolProxyContract_Ф_onStakeAccept Л_queryId Л_comment ) l = I . \n Proof. \n   intros. auto.  \n Qed. \n \n (* (* function onStakeReject ( uint64 queryId , uint32 comment ) \n \t \t public functionID ( 0xEE6F454C ) { IDePool ( m_dePool ) . onStakeReject \n \t \t { value : msg_value - DePoolLib . PROXY_FEE } ( queryId , comment \n       , msg_sender ) ; } *)\n       \nDefinition DePoolProxyContract_Ф_onStakeReject ( Л_queryId : XInteger64 )( Л_comment : XInteger32 ) : LedgerT True := \n\tU0! Л_dePool := ↑ε10 DePoolProxyContract_ι_m_dePool ;\n\tU0! Л_value := msg_value () !- ↑ε9 DePoolLib_ι_PROXY_FEE ;\n\tU0! Л_sender := msg_sender ()  ;\t\n    sendMessage {| contractAddress := Л_dePool;\n\t\t\t\t   contractFunction := DePoolContract_Ф_onStakeRejectF Л_queryId Л_comment Л_sender ;\n           contractMessage := {$ default with  messageValue := Л_value $} |} .\n           *) \n Lemma DePoolProxyContract_Ф_onStakeReject_exec : forall ( Л_queryId : XInteger64 ) ( Л_comment : XInteger32 ) (l: Ledger) , \n let dePoolAddress := eval_state (↑10 D2! DePoolProxyContract_ι_m_dePool) l in\n let msgValue := eval_state msg_value l in\n let proxyFee := eval_state (↑9 D2! DePoolLib_ι_PROXY_FEE) l in\n let value := msgValue - proxyFee in\n let msgSender := eval_state msg_sender l in\n let oldMessages := eval_state (↑16 D2! VMState_ι_messages) l in\n let newMessage  := {| contractAddress  := dePoolAddress;\n                       contractFunction := DePoolContract_Ф_onStakeRejectF Л_queryId Л_comment msgSender ;\n                       contractMessage  := {$ default with messageValue := value $} |} in                                                  \n      \n    exec_state (  DePoolProxyContract_Ф_onStakeReject Л_queryId Л_comment ) l = \n    {$ l With VMState_ι_messages := newMessage :: oldMessages $}. \n Proof. \n   intros. auto. \n Qed. \n \n Lemma DePoolProxyContract_Ф_onStakeReject_eval : forall ( Л_queryId : XInteger64 ) \n                                                         ( Л_comment : XInteger32 ) \n                                                         (l: Ledger) , \n \t eval_state (  DePoolProxyContract_Ф_onStakeReject Л_queryId Л_comment ) l = I . \n Proof. \n   intros. auto. \n Qed. \n \n (* function recover_stake(uint64 queryId, address elector) public override {\n        require(msg.sender == m_dePool, ERROR_IS_NOT_DEPOOL);\n        uint carry = msg.value - DePoolLib.PROXY_FEE;\n        require(address(this).balance >= carry + DePoolLib.MIN_PROXY_BALANCE, ERROR_BAD_BALANCE);\n        IElector(elector).recover_stake{value: msg.value - DePoolLib.PROXY_FEE}(queryId);\n    } *)\n(*\nDefinition DePoolProxyContract_Ф_recover_stake  ( Л_queryId : XInteger64 )\n                                                ( Л_elector : XAddress ) \n                                           : LedgerT ( XErrorValue True XInteger ) := \n Require2 {{ msg_sender () ?== ↑ε10 DePoolProxyContract_ι_m_dePool , ↑ε10 DePoolProxyContract_ι_ERROR_IS_NOT_DEPOOL }} ; \n U0! Л_carry := msg_value () !- ↑ε9 DePoolLib_ι_PROXY_FEE ;\n Require {{ tvm_balance () ?>=  $Л_carry !+ (↑ε9 DePoolLib_ι_MIN_PROXY_BALANCE) , ↑ε10 DePoolProxyContract_ι_ERROR_BAD_BALANCE }} ;\n sendMessage {| contractAddress := Л_elector;\n\t\t\t\tcontractFunction := IElector_И_recover_stakeF Л_queryId ;\n\t\t\t\tcontractMessage := {$ default with  messageValue := Л_carry $} |} . *)\n         \n Lemma DePoolProxyContract_Ф_recover_stake_exec : forall ( Л_queryId : XInteger64 ) ( Л_elector : XAddress ) (l: Ledger) ,\n let dePoolAddress := eval_state (↑10 ε DePoolProxyContract_ι_m_dePool) l in\n let msgValue := eval_state msg_value l in\n let proxyFee := eval_state (↑9 ε DePoolLib_ι_PROXY_FEE) l in\n let value := msgValue - proxyFee in\n let msgSender := eval_state msg_sender l in\n let oldMessages := eval_state (↑16 ε VMState_ι_messages) l in\n let newMessage  := {| contractAddress  := Л_elector;\n                       contractFunction := IElector_И_recover_stakeF Л_queryId ;\n                       contractMessage  := {$ default with messageValue := value $} |} in  \n   let carry := msgValue - proxyFee in \n   let balance := eval_state ( tvm_balance ) l in\n   let minBalance := eval_state ( ↑9 ε DePoolLib_ι_MIN_PROXY_BALANCE ) l in\n   let req2 : bool := balance >=? carry + minBalance in\n    \nexec_state ( ↓ DePoolProxyContract_Ф_recover_stake Л_queryId Л_elector ) l = \n    if (msgSender =? dePoolAddress) \n    then if req2 \n         then {$ l With VMState_ι_messages := newMessage :: oldMessages $} \n         else l\n    else l.  \n Proof. \n  intros.\n  destruct l. \n  compute; repeat destructIf; auto. \n Qed. \n \n Lemma DePoolProxyContract_Ф_recover_stake_eval : forall ( Л_queryId : XInteger64 ) ( Л_elector : XAddress ) (l: Ledger) ,\n let msgSender := eval_state msg_sender l in\n let dePoolAddress := eval_state (↑10 D2! DePoolProxyContract_ι_m_dePool) l in\n let error1 := eval_state (↑10 ε DePoolProxyContract_ι_ERROR_IS_NOT_DEPOOL) l in \n let error2 := eval_state (↑10 ε DePoolProxyContract_ι_ERROR_BAD_BALANCE) l in \n   let proxyFee := eval_state (↑9 ε DePoolLib_ι_PROXY_FEE) l in\n   let msgValue := eval_state msg_value l in\n   let carry := msgValue - proxyFee in \n   let balance := eval_state ( tvm_balance ) l in\n   let minBalance := eval_state ( ↑9 ε DePoolLib_ι_MIN_PROXY_BALANCE ) l in\n   let req2 : bool := balance >=? carry + minBalance in\n \n    eval_state (DePoolProxyContract_Ф_recover_stake Л_queryId Л_elector ) l = \n    if (msgSender =? dePoolAddress) then \n       if req2 then xValue I \n               else xError error2 \n    else xError error1 . \n Proof. \n  intros.\n  destruct l. \n  compute; repeat destructIf; auto.\n Qed. \n \n (* (* function onSuccessToRecoverStake ( uint64 queryId ) public \n \t \t functionID ( 0xF96F7324 ) { IDePool ( m_dePool ) . onSuccessToRecoverStake \n \t \t { value : msg_value - DePoolLib . PROXY_FEE } ( queryId , msg_sender \n       ) ; } *)\n       \nDefinition DePoolProxyContract_Ф_onSuccessToRecoverStake ( Л_queryId : XInteger64 ) : LedgerT True := \n\tU0! Л_dePool := ↑ε10 DePoolProxyContract_ι_m_dePool ;\n\tU0! Л_value := msg_value () !- ↑ε9 DePoolLib_ι_PROXY_FEE ;\n\tU0! Л_sender := msg_sender ()  ;\t\n\tsendMessage {| contractAddress := Л_dePool;\n\t\t\t\t   contractFunction := DePoolContract_Ф_onSuccessToRecoverStakeF Л_queryId Л_sender ;\n           contractMessage := {$ default with  messageValue := Л_value $} |} .\n            *) \n\n Lemma DePoolProxyContract_Ф_onSuccessToRecoverStake_exec : forall ( Л_queryId : XInteger64 ) (l: Ledger) , \n let dePoolAddress := eval_state (↑10 D2! DePoolProxyContract_ι_m_dePool) l in\n let msgValue := eval_state msg_value l in\n let proxyFee := eval_state (↑9 D2! DePoolLib_ι_PROXY_FEE) l in\n let value := msgValue - proxyFee in\n let msgSender := eval_state msg_sender l in\n let oldMessages := eval_state (↑16 D2! VMState_ι_messages) l in\n let newMessage  := {| contractAddress  := dePoolAddress;\n                       contractFunction := DePoolContract_Ф_onSuccessToRecoverStakeF Л_queryId msgSender ;\n                       contractMessage  := {$ default with messageValue := value $} |} in      \n    exec_state (DePoolProxyContract_Ф_onSuccessToRecoverStake Л_queryId) l =  \n               {$ l With VMState_ι_messages := newMessage :: oldMessages $}.  \n Proof. \n  intros.  auto.\n Qed. \n \n Lemma DePoolProxyContract_Ф_onSuccessToRecoverStake_eval : forall ( Л_queryId : XInteger64 ) (l: Ledger) , \n \t eval_state (DePoolProxyContract_Ф_onSuccessToRecoverStake Л_queryId ) l = I . \n Proof. \n   intros. auto. \n Qed. \n\n (*   \n      function getProxyInfo() public view returns (address depool, uint64 minBalance) {\n        depool = m_dePool;\n        minBalance = DePoolLib.MIN_PROXY_BALANCE;\n    }\nDefinition DePoolProxyContract_Ф_getProxyInfo : LedgerT ( XAddress # XInteger64 ) := \n U0! Л_depool := ↑ε10 DePoolProxyContract_ι_m_dePool ; \n U0! Л_minBalance := ↑ε9 DePoolLib_ι_MIN_PROXY_BALANCE ; \n\t return# ($ Л_depool, $ Л_minBalance) . \n *) \n\n Lemma DePoolProxyContract_Ф_getProxyInfo_exec : forall (l: Ledger) , \n \t exec_state ( ↓ DePoolProxyContract_Ф_getProxyInfo ) l = l .  \n Proof. \n    intros. destruct l; compute; auto. \n Qed. \n \n Lemma DePoolProxyContract_Ф_getProxyInfo_eval : forall (l: Ledger) , \n                           (*  LedgerT ( XAddress # XInteger64 ) *)\n    let dePool := eval_state (↑10 ε DePoolProxyContract_ι_m_dePool) l in\n    let minBalance := eval_state (↑9 ε DePoolLib_ι_MIN_PROXY_BALANCE) l in\n    eval_state ( ↓ DePoolProxyContract_Ф_getProxyInfo ) l = (dePool, minBalance). \n Proof. \n   intros. destruct l ; compute ; 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/DePoolProxyContractProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.28046956291449965}}
{"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\n\n(* Converted imports: *)\n\nRequire Data.Bits.\nRequire Data.Either.\nRequire Data.Foldable.\nRequire Data.Functor.Classes.\nRequire GHC.Base.\nRequire GHC.Err.\nRequire GHC.Num.\nRequire GHC.Tuple.\nRequire HsToCoq.DeferredFix.\nRequire Nat.\nRequire Utils.Containers.Internal.PtrEquality.\nImport GHC.Base.Notations.\nImport GHC.Num.Notations.\n\n(* Converted type declarations: *)\n\nDefinition Size :=\n  GHC.Num.Int%type.\n\nInductive Set_ a : Type :=\n  | Bin : Size -> a -> (Set_ a) -> (Set_ a) -> Set_ a\n  | Tip : Set_ a.\n\nInductive MergeSet a : Type :=\n  | Mk_MergeSet (getMergeSet : Set_ a) : MergeSet a.\n\nArguments Bin {_} _ _ _ _.\n\nArguments Tip {_}.\n\nArguments Mk_MergeSet {_} _.\n\nDefinition getMergeSet {a} (arg_0__ : MergeSet a) :=\n  let 'Mk_MergeSet getMergeSet := arg_0__ in\n  getMergeSet.\n\n(* Midamble *)\n\nRequire Omega.\n\nLtac termination_by_omega :=\n  Coq.Program.Tactics.program_simpl;\n  simpl;Omega.omega.\n\nFixpoint set_size {a} (s : Set_ a) : nat :=\n  match s with\n  | Tip => 0\n  | Bin _ _ s1 s2 => 1 + set_size s1 + set_size s2\n  end.\n\nRequire Import HsToCoq.Err.\n\nInstance Set_Default {a} : Default (Set_ a) :=\n  Build_Default _ Tip.\nInstance MergeSetDefault {a} : Default (MergeSet a) :=\n  Build_Default _ (Mk_MergeSet default).\n\n(* Converted value declarations: *)\n\nDefinition delta : GHC.Num.Int :=\n  #3.\n\nDefinition ratio : GHC.Num.Int :=\n  #2.\n\nDefinition size {a : Type} : Set_ a -> GHC.Num.Int :=\n  fun arg_0__ => match arg_0__ with | Tip => #0 | Bin sz _ _ _ => sz end.\n\nDefinition balanceL {a} : a -> Set_ a -> Set_ a -> Set_ a :=\n  fun x l r =>\n    match r with\n    | Tip =>\n        match l with\n        | Tip => Bin #1 x Tip Tip\n        | Bin _ _ Tip Tip => Bin #2 x l Tip\n        | Bin _ lx Tip (Bin _ lrx _ _) =>\n            Bin #3 lrx (Bin #1 lx Tip Tip) (Bin #1 x Tip Tip)\n        | Bin _ lx (Bin _ _ _ _ as ll) Tip => Bin #3 lx ll (Bin #1 x Tip Tip)\n        | Bin ls lx (Bin lls _ _ _ as ll) (Bin lrs lrx lrl lrr as lr) =>\n            if lrs GHC.Base.< (ratio GHC.Num.* lls) : bool\n            then Bin (#1 GHC.Num.+ ls) lx ll (Bin (#1 GHC.Num.+ lrs) x lr Tip) else\n            Bin (#1 GHC.Num.+ ls) lrx (Bin ((#1 GHC.Num.+ lls) GHC.Num.+ size lrl) lx ll\n                                       lrl) (Bin (#1 GHC.Num.+ size lrr) x lrr Tip)\n        end\n    | Bin rs _ _ _ =>\n        match l with\n        | Tip => Bin (#1 GHC.Num.+ rs) x Tip r\n        | Bin ls lx ll lr =>\n            if ls GHC.Base.> (delta GHC.Num.* rs) : bool\n            then let scrut_9__ := pair ll lr in\n                 match scrut_9__ with\n                 | pair (Bin lls _ _ _) (Bin lrs lrx lrl lrr) =>\n                     if lrs GHC.Base.< (ratio GHC.Num.* lls) : bool\n                     then Bin ((#1 GHC.Num.+ ls) GHC.Num.+ rs) lx ll (Bin ((#1 GHC.Num.+ rs)\n                                                                           GHC.Num.+\n                                                                           lrs) x lr r) else\n                     Bin ((#1 GHC.Num.+ ls) GHC.Num.+ rs) lrx (Bin ((#1 GHC.Num.+ lls) GHC.Num.+\n                                                                    size lrl) lx ll lrl) (Bin ((#1 GHC.Num.+ rs)\n                                                                                               GHC.Num.+\n                                                                                               size lrr) x lrr r)\n                 | _ =>\n                     let 'pair _ _ := scrut_9__ in\n                     GHC.Err.error (GHC.Base.hs_string__ \"Failure in Data.Map.balanceL\")\n                 end else\n            Bin ((#1 GHC.Num.+ ls) GHC.Num.+ rs) x l r\n        end\n    end.\n\nDefinition balanceR {a} : a -> Set_ a -> Set_ a -> Set_ a :=\n  fun x l r =>\n    match l with\n    | Tip =>\n        match r with\n        | Tip => Bin #1 x Tip Tip\n        | Bin _ _ Tip Tip => Bin #2 x Tip r\n        | Bin _ rx Tip (Bin _ _ _ _ as rr) => Bin #3 rx (Bin #1 x Tip Tip) rr\n        | Bin _ rx (Bin _ rlx _ _) Tip =>\n            Bin #3 rlx (Bin #1 x Tip Tip) (Bin #1 rx Tip Tip)\n        | Bin rs rx (Bin rls rlx rll rlr as rl) (Bin rrs _ _ _ as rr) =>\n            if rls GHC.Base.< (ratio GHC.Num.* rrs) : bool\n            then Bin (#1 GHC.Num.+ rs) rx (Bin (#1 GHC.Num.+ rls) x Tip rl) rr else\n            Bin (#1 GHC.Num.+ rs) rlx (Bin (#1 GHC.Num.+ size rll) x Tip rll) (Bin ((#1\n                                                                                     GHC.Num.+\n                                                                                     rrs) GHC.Num.+\n                                                                                    size rlr) rx rlr rr)\n        end\n    | Bin ls _ _ _ =>\n        match r with\n        | Tip => Bin (#1 GHC.Num.+ ls) x l Tip\n        | Bin rs rx rl rr =>\n            if rs GHC.Base.> (delta GHC.Num.* ls) : bool\n            then let scrut_9__ := pair rl rr in\n                 match scrut_9__ with\n                 | pair (Bin rls rlx rll rlr) (Bin rrs _ _ _) =>\n                     if rls GHC.Base.< (ratio GHC.Num.* rrs) : bool\n                     then Bin ((#1 GHC.Num.+ ls) GHC.Num.+ rs) rx (Bin ((#1 GHC.Num.+ ls) GHC.Num.+\n                                                                        rls) x l rl) rr else\n                     Bin ((#1 GHC.Num.+ ls) GHC.Num.+ rs) rlx (Bin ((#1 GHC.Num.+ ls) GHC.Num.+\n                                                                    size rll) x l rll) (Bin ((#1 GHC.Num.+ rrs)\n                                                                                             GHC.Num.+\n                                                                                             size rlr) rx rlr rr)\n                 | _ =>\n                     let 'pair _ _ := scrut_9__ in\n                     GHC.Err.error (GHC.Base.hs_string__ \"Failure in Data.Map.balanceR\")\n                 end else\n            Bin ((#1 GHC.Num.+ ls) GHC.Num.+ rs) x l r\n        end\n    end.\n\nDefinition singleton {a : Type} : a -> Set_ a :=\n  fun x => Bin #1 x Tip Tip.\n\nDefinition insert {a : Type} `{GHC.Base.Ord a} : a -> Set_ a -> Set_ a :=\n  fun x0 =>\n    let go {a} `{GHC.Base.Ord a} : a -> a -> Set_ a -> Set_ a :=\n      fix go (arg_0__ arg_1__ : a) (arg_2__ : Set_ a) : Set_ a\n        := match arg_0__, arg_1__, arg_2__ with\n           | orig, _, Tip => singleton (orig)\n           | orig, x, (Bin sz y l r as t) =>\n               match GHC.Base.compare x y with\n               | Lt =>\n                   let l' := go orig x l in\n                   if Utils.Containers.Internal.PtrEquality.ptrEq l' l : bool then t else\n                   balanceL y l' r\n               | Gt =>\n                   let r' := go orig x r in\n                   if Utils.Containers.Internal.PtrEquality.ptrEq r' r : bool then t else\n                   balanceR y l r'\n               | Eq =>\n                   if (Utils.Containers.Internal.PtrEquality.ptrEq orig y) : bool then t else\n                   Bin sz (orig) l r\n               end\n           end in\n    go x0 x0.\n\nDefinition insertR {a} `{GHC.Base.Ord a} : a -> Set_ a -> Set_ a :=\n  fun x0 =>\n    let go {a} `{GHC.Base.Ord a} : a -> a -> Set_ a -> Set_ a :=\n      fix go (arg_0__ arg_1__ : a) (arg_2__ : Set_ a) : Set_ a\n        := match arg_0__, arg_1__, arg_2__ with\n           | orig, _, Tip => singleton (orig)\n           | orig, x, (Bin _ y l r as t) =>\n               match GHC.Base.compare x y with\n               | Lt =>\n                   let l' := go orig x l in\n                   if Utils.Containers.Internal.PtrEquality.ptrEq l' l : bool then t else\n                   balanceL y l' r\n               | Gt =>\n                   let r' := go orig x r in\n                   if Utils.Containers.Internal.PtrEquality.ptrEq r' r : bool then t else\n                   balanceR y l r'\n               | Eq => t\n               end\n           end in\n    go x0 x0.\n\nDefinition bin {a : Type} : a -> Set_ a -> Set_ a -> Set_ a :=\n  fun x l r => Bin ((size l GHC.Num.+ size r) GHC.Num.+ #1) x l r.\n\nFixpoint insertMax {a} (x : a) (t : Set_ a) : Set_ a\n  := match t with\n     | Tip => singleton x\n     | Bin _ y l r => balanceR y l (insertMax x r)\n     end.\n\nFixpoint insertMin {a} (x : a) (t : Set_ a) : Set_ a\n  := match t with\n     | Tip => singleton x\n     | Bin _ y l r => balanceL y (insertMin x l) r\n     end.\n\nProgram Fixpoint link {a : Type} (arg_0__ : a) (arg_1__ arg_2__ : Set_ a)\n                      {measure (Nat.add (set_size arg_1__) (set_size arg_2__))} : Set_ a\n  := match arg_0__, arg_1__, arg_2__ with\n     | x, Tip, r => insertMin x r\n     | x, l, Tip => insertMax x l\n     | x, (Bin sizeL y ly ry as l), (Bin sizeR z lz rz as r) =>\n         if Bool.Sumbool.sumbool_of_bool ((delta GHC.Num.* sizeL) GHC.Base.< sizeR)\n         then balanceL z (link x l lz) rz else\n         if Bool.Sumbool.sumbool_of_bool ((delta GHC.Num.* sizeR) GHC.Base.< sizeL)\n         then balanceR y ly (link x ry r) else\n         bin x l r\n     end.\nSolve Obligations with (termination_by_omega).\n\nFixpoint splitS {a} `{GHC.Base.Ord a} (arg_0__ : a) (arg_1__ : Set_ a) : prod\n                                                                         (Set_ a) (Set_ a)\n  := match arg_0__, arg_1__ with\n     | _, Tip => (pair Tip Tip)\n     | x, Bin _ y l r =>\n         match GHC.Base.compare x y with\n         | Lt => let 'pair lt gt := splitS x l in (pair lt (link y gt r))\n         | Gt => let 'pair lt gt := splitS x r in (pair (link y l lt) gt)\n         | Eq => (pair l r)\n         end\n     end.\n\nFixpoint union {a : Type} `{GHC.Base.Ord a} (arg_0__ arg_1__ : Set_ a) : Set_ a\n  := match arg_0__, arg_1__ with\n     | t1, Tip => t1\n     | t1, Bin num_2__ x _ _ =>\n         if num_2__ GHC.Base.== #1 : bool then insertR x t1 else\n         let j_11__ :=\n           match arg_0__, arg_1__ with\n           | Tip, t2 => t2\n           | (Bin _ x l1 r1 as t1), t2 =>\n               let 'pair l2 r2 := splitS x t2 in\n               let r1r2 := union r1 r2 in\n               let l1l2 := union l1 l2 in\n               if andb (Utils.Containers.Internal.PtrEquality.ptrEq l1l2 l1)\n                       (Utils.Containers.Internal.PtrEquality.ptrEq r1r2 r1) : bool\n               then t1 else\n               link x l1l2 r1r2\n           end in\n         match arg_0__, arg_1__ with\n         | Bin num_3__ x _ _, t2 =>\n             if num_3__ GHC.Base.== #1 : bool then insert x t2 else\n             j_11__\n         | _, _ => j_11__\n         end\n     end.\n\nLocal Definition Semigroup__Set__op_zlzlzgzg__ {inst_a : Type} `{GHC.Base.Ord\n  inst_a}\n   : Set_ inst_a -> Set_ inst_a -> Set_ inst_a :=\n  union.\n\nProgram Instance Semigroup__Set_ {a : Type} `{GHC.Base.Ord a}\n   : GHC.Base.Semigroup (Set_ a) :=\n  fun _ k__ =>\n    k__ {| GHC.Base.op_zlzlzgzg____ := Semigroup__Set__op_zlzlzgzg__ |}.\n\nLocal Definition Monoid__Set__mappend {inst_a : Type} `{GHC.Base.Ord inst_a}\n   : Set_ inst_a -> Set_ inst_a -> Set_ inst_a :=\n  _GHC.Base.<<>>_.\n\nDefinition empty {a : Type} : Set_ a :=\n  Tip.\n\nDefinition unions {f : Type -> Type} {a : Type} `{Data.Foldable.Foldable f}\n  `{GHC.Base.Ord a}\n   : f (Set_ a) -> Set_ a :=\n  Data.Foldable.foldl' union empty.\n\nLocal Definition Monoid__Set__mconcat {inst_a : Type} `{GHC.Base.Ord inst_a}\n   : list (Set_ inst_a) -> Set_ inst_a :=\n  unions.\n\nLocal Definition Monoid__Set__mempty {inst_a : Type} `{GHC.Base.Ord inst_a}\n   : Set_ inst_a :=\n  empty.\n\nProgram Instance Monoid__Set_ {a : Type} `{GHC.Base.Ord a}\n   : GHC.Base.Monoid (Set_ a) :=\n  fun _ k__ =>\n    k__ {| GHC.Base.mappend__ := Monoid__Set__mappend ;\n           GHC.Base.mconcat__ := Monoid__Set__mconcat ;\n           GHC.Base.mempty__ := Monoid__Set__mempty |}.\n\nLocal Definition Foldable__Set__fold\n   : forall {m : Type}, forall `{GHC.Base.Monoid m}, Set_ m -> m :=\n  fun {m : Type} `{GHC.Base.Monoid m} =>\n    let fix go arg_0__\n      := match arg_0__ with\n         | Tip => GHC.Base.mempty\n         | Bin num_1__ k _ _ =>\n             if num_1__ GHC.Base.== #1 : bool then k else\n             match arg_0__ with\n             | Bin _ k l r => GHC.Base.mappend (go l) (GHC.Base.mappend k (go r))\n             | _ => GHC.Err.patternFailure\n             end\n         end in\n    go.\n\nLocal Definition Foldable__Set__foldMap\n   : forall {m : Type},\n     forall {a : Type}, forall `{GHC.Base.Monoid m}, (a -> m) -> Set_ a -> m :=\n  fun {m : Type} {a : Type} `{GHC.Base.Monoid m} =>\n    fun f t =>\n      let fix go arg_0__\n        := match arg_0__ with\n           | Tip => GHC.Base.mempty\n           | Bin num_1__ k _ _ =>\n               if num_1__ GHC.Base.== #1 : bool then f k else\n               match arg_0__ with\n               | Bin _ k l r => GHC.Base.mappend (go l) (GHC.Base.mappend (f k) (go r))\n               | _ => GHC.Err.patternFailure\n               end\n           end in\n      go t.\n\nDefinition foldl {a : Type} {b : Type} : (a -> b -> a) -> a -> Set_ b -> a :=\n  fun f z =>\n    let fix go arg_0__ arg_1__\n      := match arg_0__, arg_1__ with\n         | z', Tip => z'\n         | z', Bin _ x l r => go (f (go z' l) x) r\n         end in\n    go z.\n\nLocal Definition Foldable__Set__foldl\n   : forall {b : Type}, forall {a : Type}, (b -> a -> b) -> b -> Set_ a -> b :=\n  fun {b : Type} {a : Type} => foldl.\n\nDefinition foldl' {a : Type} {b : Type} : (a -> b -> a) -> a -> Set_ b -> a :=\n  fun f z =>\n    let fix go arg_0__ arg_1__\n      := match arg_0__, arg_1__ with\n         | z', Tip => z'\n         | z', Bin _ x l r => go (f (go z' l) x) r\n         end in\n    go z.\n\nLocal Definition Foldable__Set__foldl'\n   : forall {b : Type}, forall {a : Type}, (b -> a -> b) -> b -> Set_ a -> b :=\n  fun {b : Type} {a : Type} => foldl'.\n\nDefinition foldr {a : Type} {b : Type} : (a -> b -> b) -> b -> Set_ a -> b :=\n  fun f z =>\n    let fix go arg_0__ arg_1__\n      := match arg_0__, arg_1__ with\n         | z', Tip => z'\n         | z', Bin _ x l r => go (f x (go z' r)) l\n         end in\n    go z.\n\nLocal Definition Foldable__Set__foldr\n   : forall {a : Type}, forall {b : Type}, (a -> b -> b) -> b -> Set_ a -> b :=\n  fun {a : Type} {b : Type} => foldr.\n\nDefinition foldr' {a : Type} {b : Type} : (a -> b -> b) -> b -> Set_ a -> b :=\n  fun f z =>\n    let fix go arg_0__ arg_1__\n      := match arg_0__, arg_1__ with\n         | z', Tip => z'\n         | z', Bin _ x l r => go (f x (go z' r)) l\n         end in\n    go z.\n\nLocal Definition Foldable__Set__foldr'\n   : forall {a : Type}, forall {b : Type}, (a -> b -> b) -> b -> Set_ a -> b :=\n  fun {a : Type} {b : Type} => foldr'.\n\nLocal Definition Foldable__Set__length\n   : forall {a : Type}, Set_ a -> GHC.Num.Int :=\n  fun {a : Type} => size.\n\nDefinition null {a : Type} : Set_ a -> bool :=\n  fun arg_0__ => match arg_0__ with | Tip => true | Bin _ _ _ _ => false end.\n\nLocal Definition Foldable__Set__null : forall {a : Type}, Set_ a -> bool :=\n  fun {a : Type} => null.\n\nLocal Definition Foldable__Set__product\n   : forall {a : Type}, forall `{GHC.Num.Num a}, Set_ a -> a :=\n  fun {a : Type} `{GHC.Num.Num a} => foldl' _GHC.Num.*_ #1.\n\nLocal Definition Foldable__Set__sum\n   : forall {a : Type}, forall `{GHC.Num.Num a}, Set_ a -> a :=\n  fun {a : Type} `{GHC.Num.Num a} => foldl' _GHC.Num.+_ #0.\n\nDefinition toAscList {a : Type} : Set_ a -> list a :=\n  foldr cons nil.\n\nDefinition toList {a : Type} : Set_ a -> list a :=\n  toAscList.\n\nLocal Definition Foldable__Set__toList : forall {a : Type}, Set_ a -> list a :=\n  fun {a : Type} => toList.\n\nProgram Instance Foldable__Set_ : Data.Foldable.Foldable Set_ :=\n  fun _ k__ =>\n    k__ {| Data.Foldable.fold__ := fun {m : Type} `{GHC.Base.Monoid m} =>\n             Foldable__Set__fold ;\n           Data.Foldable.foldMap__ := fun {m : Type} {a : Type} `{GHC.Base.Monoid m} =>\n             Foldable__Set__foldMap ;\n           Data.Foldable.foldl__ := fun {b : Type} {a : Type} => Foldable__Set__foldl ;\n           Data.Foldable.foldl'__ := fun {b : Type} {a : Type} => Foldable__Set__foldl' ;\n           Data.Foldable.foldr__ := fun {a : Type} {b : Type} => Foldable__Set__foldr ;\n           Data.Foldable.foldr'__ := fun {a : Type} {b : Type} => Foldable__Set__foldr' ;\n           Data.Foldable.length__ := fun {a : Type} => Foldable__Set__length ;\n           Data.Foldable.null__ := fun {a : Type} => Foldable__Set__null ;\n           Data.Foldable.product__ := fun {a : Type} `{GHC.Num.Num a} =>\n             Foldable__Set__product ;\n           Data.Foldable.sum__ := fun {a : Type} `{GHC.Num.Num a} => Foldable__Set__sum ;\n           Data.Foldable.toList__ := fun {a : Type} => Foldable__Set__toList |}.\n\n(* Skipping all instances of class `Data.Data.Data', including\n   `Data.Set.Internal.Data__Set_' *)\n\n(* Skipping all instances of class `GHC.Exts.IsList', including\n   `Data.Set.Internal.IsList__Set_' *)\n\nLocal Definition Eq___Set__op_zeze__ {inst_a : Type} `{GHC.Base.Eq_ inst_a}\n   : Set_ inst_a -> Set_ inst_a -> bool :=\n  fun t1 t2 =>\n    andb (size t1 GHC.Base.== size t2) (toAscList t1 GHC.Base.== toAscList t2).\n\nLocal Definition Eq___Set__op_zsze__ {inst_a : Type} `{GHC.Base.Eq_ inst_a}\n   : Set_ inst_a -> Set_ inst_a -> bool :=\n  fun x y => negb (Eq___Set__op_zeze__ x y).\n\nProgram Instance Eq___Set_ {a : Type} `{GHC.Base.Eq_ a}\n   : GHC.Base.Eq_ (Set_ a) :=\n  fun _ k__ =>\n    k__ {| GHC.Base.op_zeze____ := Eq___Set__op_zeze__ ;\n           GHC.Base.op_zsze____ := Eq___Set__op_zsze__ |}.\n\nLocal Definition Ord__Set__compare {inst_a : Type} `{GHC.Base.Ord inst_a}\n   : Set_ inst_a -> Set_ inst_a -> comparison :=\n  fun s1 s2 => GHC.Base.compare (toAscList s1) (toAscList s2).\n\nLocal Definition Ord__Set__op_zl__ {inst_a : Type} `{GHC.Base.Ord inst_a}\n   : Set_ inst_a -> Set_ inst_a -> bool :=\n  fun x y => Ord__Set__compare x y GHC.Base.== Lt.\n\nLocal Definition Ord__Set__op_zlze__ {inst_a : Type} `{GHC.Base.Ord inst_a}\n   : Set_ inst_a -> Set_ inst_a -> bool :=\n  fun x y => Ord__Set__compare x y GHC.Base./= Gt.\n\nLocal Definition Ord__Set__op_zg__ {inst_a : Type} `{GHC.Base.Ord inst_a}\n   : Set_ inst_a -> Set_ inst_a -> bool :=\n  fun x y => Ord__Set__compare x y GHC.Base.== Gt.\n\nLocal Definition Ord__Set__op_zgze__ {inst_a : Type} `{GHC.Base.Ord inst_a}\n   : Set_ inst_a -> Set_ inst_a -> bool :=\n  fun x y => Ord__Set__compare x y GHC.Base./= Lt.\n\nLocal Definition Ord__Set__max {inst_a : Type} `{GHC.Base.Ord inst_a}\n   : Set_ inst_a -> Set_ inst_a -> Set_ inst_a :=\n  fun x y => if Ord__Set__op_zlze__ x y : bool then y else x.\n\nLocal Definition Ord__Set__min {inst_a : Type} `{GHC.Base.Ord inst_a}\n   : Set_ inst_a -> Set_ inst_a -> Set_ inst_a :=\n  fun x y => if Ord__Set__op_zlze__ x y : bool then x else y.\n\nProgram Instance Ord__Set_ {a : Type} `{GHC.Base.Ord a}\n   : GHC.Base.Ord (Set_ a) :=\n  fun _ k__ =>\n    k__ {| GHC.Base.op_zl____ := Ord__Set__op_zl__ ;\n           GHC.Base.op_zlze____ := Ord__Set__op_zlze__ ;\n           GHC.Base.op_zg____ := Ord__Set__op_zg__ ;\n           GHC.Base.op_zgze____ := Ord__Set__op_zgze__ ;\n           GHC.Base.compare__ := Ord__Set__compare ;\n           GHC.Base.max__ := Ord__Set__max ;\n           GHC.Base.min__ := Ord__Set__min |}.\n\n(* Skipping all instances of class `GHC.Show.Show', including\n   `Data.Set.Internal.Show__Set_' *)\n\nLocal Definition Eq1__Set__liftEq\n   : forall {a : Type},\n     forall {b : Type}, (a -> b -> bool) -> Set_ a -> Set_ b -> bool :=\n  fun {a : Type} {b : Type} =>\n    fun eq m n =>\n      andb (size m GHC.Base.== size n) (Data.Functor.Classes.liftEq eq (toList m)\n            (toList n)).\n\nProgram Instance Eq1__Set_ : Data.Functor.Classes.Eq1 Set_ :=\n  fun _ k__ =>\n    k__ {| Data.Functor.Classes.liftEq__ := fun {a : Type} {b : Type} =>\n             Eq1__Set__liftEq |}.\n\nLocal Definition Ord1__Set__liftCompare\n   : forall {a : Type},\n     forall {b : Type}, (a -> b -> comparison) -> Set_ a -> Set_ b -> comparison :=\n  fun {a : Type} {b : Type} =>\n    fun cmp m n => Data.Functor.Classes.liftCompare cmp (toList m) (toList n).\n\nProgram Instance Ord1__Set_ : Data.Functor.Classes.Ord1 Set_ :=\n  fun _ k__ =>\n    k__ {| Data.Functor.Classes.liftCompare__ := fun {a : Type} {b : Type} =>\n             Ord1__Set__liftCompare |}.\n\n(* Skipping all instances of class `Data.Functor.Classes.Show1', including\n   `Data.Set.Internal.Show1__Set_' *)\n\n(* Skipping all instances of class `GHC.Read.Read', including\n   `Data.Set.Internal.Read__Set_' *)\n\n(* Skipping all instances of class `Control.DeepSeq.NFData', including\n   `Data.Set.Internal.NFData__Set_' *)\n\nDefinition maxViewSure {a} : a -> Set_ a -> Set_ a -> prod a (Set_ a) :=\n  let fix go arg_0__ arg_1__ arg_2__\n    := match arg_0__, arg_1__, arg_2__ with\n       | x, l, Tip => pair x l\n       | x, l, Bin _ xr rl rr =>\n           let 'pair xm r' := go xr rl rr in\n           pair xm (balanceL x l r')\n       end in\n  go.\n\nDefinition minViewSure {a} : a -> Set_ a -> Set_ a -> prod a (Set_ a) :=\n  let fix go arg_0__ arg_1__ arg_2__\n    := match arg_0__, arg_1__, arg_2__ with\n       | x, Tip, r => pair x r\n       | x, Bin _ xl ll lr, r =>\n           let 'pair xm l' := go xl ll lr in\n           pair xm (balanceR x l' r)\n       end in\n  go.\n\nDefinition glue {a} : Set_ a -> Set_ a -> Set_ a :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__, arg_1__ with\n    | Tip, r => r\n    | l, Tip => l\n    | (Bin sl xl ll lr as l), (Bin sr xr rl rr as r) =>\n        if sl GHC.Base.> sr : bool\n        then let 'pair m l' := maxViewSure xl ll lr in\n             balanceR m l' r else\n        let 'pair m r' := minViewSure xr rl rr in\n        balanceL m l r'\n    end.\n\nProgram Fixpoint merge {a : Type} (arg_0__ arg_1__ : Set_ a) {measure (Nat.add\n                        (set_size arg_0__) (set_size arg_1__))} : Set_ a\n  := match arg_0__, arg_1__ with\n     | Tip, r => r\n     | l, Tip => l\n     | (Bin sizeL x lx rx as l), (Bin sizeR y ly ry as r) =>\n         if Bool.Sumbool.sumbool_of_bool ((delta GHC.Num.* sizeL) GHC.Base.< sizeR)\n         then balanceL y (merge l ly) ry else\n         if Bool.Sumbool.sumbool_of_bool ((delta GHC.Num.* sizeR) GHC.Base.< sizeL)\n         then balanceR x lx (merge rx r) else\n         glue l r\n     end.\nSolve Obligations with (termination_by_omega).\n\nLocal Definition Semigroup__MergeSet_op_zlzlzgzg__ {inst_a : Type}\n   : MergeSet inst_a -> MergeSet inst_a -> MergeSet inst_a :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__, arg_1__ with\n    | Mk_MergeSet xs, Mk_MergeSet ys => Mk_MergeSet (merge xs ys)\n    end.\n\nProgram Instance Semigroup__MergeSet {a : Type}\n   : GHC.Base.Semigroup (MergeSet a) :=\n  fun _ k__ =>\n    k__ {| GHC.Base.op_zlzlzgzg____ := Semigroup__MergeSet_op_zlzlzgzg__ |}.\n\nLocal Definition Monoid__MergeSet_mappend {inst_a : Type}\n   : MergeSet inst_a -> MergeSet inst_a -> MergeSet inst_a :=\n  _GHC.Base.<<>>_.\n\nLocal Definition Monoid__MergeSet_mempty {inst_a : Type} : MergeSet inst_a :=\n  Mk_MergeSet empty.\n\nLocal Definition Monoid__MergeSet_mconcat {inst_a : Type}\n   : list (MergeSet inst_a) -> MergeSet inst_a :=\n  GHC.Base.foldr Monoid__MergeSet_mappend Monoid__MergeSet_mempty.\n\nProgram Instance Monoid__MergeSet {a : Type} : GHC.Base.Monoid (MergeSet a) :=\n  fun _ k__ =>\n    k__ {| GHC.Base.mappend__ := Monoid__MergeSet_mappend ;\n           GHC.Base.mconcat__ := Monoid__MergeSet_mconcat ;\n           GHC.Base.mempty__ := Monoid__MergeSet_mempty |}.\n\nDefinition split {a : Type} `{GHC.Base.Ord a}\n   : a -> Set_ a -> (Set_ a * Set_ a)%type :=\n  fun x t => id (splitS x t).\n\nFixpoint difference {a : Type} `{GHC.Base.Ord a} (arg_0__ arg_1__ : Set_ a)\n  : Set_ a\n  := match arg_0__, arg_1__ with\n     | Tip, _ => Tip\n     | t1, Tip => t1\n     | t1, Bin _ x l2 r2 =>\n         let 'pair l1 r1 := split x t1 in\n         let r1r2 := difference r1 r2 in\n         let l1l2 := difference l1 l2 in\n         if (size l1l2 GHC.Num.+ size r1r2) GHC.Base.== size t1 : bool then t1 else\n         merge l1l2 r1r2\n     end.\n\nDefinition op_zrzr__ {a : Type} `{GHC.Base.Ord a}\n   : Set_ a -> Set_ a -> Set_ a :=\n  fun m1 m2 => difference m1 m2.\n\nNotation \"'_\\\\_'\" := (op_zrzr__).\n\nInfix \"\\\\\" := (_\\\\_) (at level 99).\n\n(* Skipping definition `Data.Set.Internal.fromListConstr' *)\n\n(* Skipping definition `Data.Set.Internal.setDataType' *)\n\nDefinition member {a : Type} `{GHC.Base.Ord a} : a -> Set_ a -> bool :=\n  let fix go arg_0__ arg_1__\n    := match arg_0__, arg_1__ with\n       | _, Tip => false\n       | x, Bin _ y l r =>\n           match GHC.Base.compare x y with\n           | Lt => go x l\n           | Gt => go x r\n           | Eq => true\n           end\n       end in\n  go.\n\nDefinition notMember {a : Type} `{GHC.Base.Ord a} : a -> Set_ a -> bool :=\n  fun a t => negb (member a t).\n\nDefinition lookupLT {a : Type} `{GHC.Base.Ord a} : a -> Set_ a -> option a :=\n  let fix goJust arg_0__ arg_1__ arg_2__\n    := match arg_0__, arg_1__, arg_2__ with\n       | _, best, Tip => Some best\n       | x, best, Bin _ y l r =>\n           if x GHC.Base.<= y : bool then goJust x best l else\n           goJust x y r\n       end in\n  let fix goNothing arg_7__ arg_8__\n    := match arg_7__, arg_8__ with\n       | _, Tip => None\n       | x, Bin _ y l r =>\n           if x GHC.Base.<= y : bool then goNothing x l else\n           goJust x y r\n       end in\n  goNothing.\n\nDefinition lookupGT {a : Type} `{GHC.Base.Ord a} : a -> Set_ a -> option a :=\n  let fix goJust arg_0__ arg_1__ arg_2__\n    := match arg_0__, arg_1__, arg_2__ with\n       | _, best, Tip => Some best\n       | x, best, Bin _ y l r =>\n           if x GHC.Base.< y : bool then goJust x y l else\n           goJust x best r\n       end in\n  let fix goNothing arg_7__ arg_8__\n    := match arg_7__, arg_8__ with\n       | _, Tip => None\n       | x, Bin _ y l r =>\n           if x GHC.Base.< y : bool then goJust x y l else\n           goNothing x r\n       end in\n  goNothing.\n\nDefinition lookupLE {a : Type} `{GHC.Base.Ord a} : a -> Set_ a -> option a :=\n  let fix goJust arg_0__ arg_1__ arg_2__\n    := match arg_0__, arg_1__, arg_2__ with\n       | _, best, Tip => Some best\n       | x, best, Bin _ y l r =>\n           match GHC.Base.compare x y with\n           | Lt => goJust x best l\n           | Eq => Some y\n           | Gt => goJust x y r\n           end\n       end in\n  let fix goNothing arg_11__ arg_12__\n    := match arg_11__, arg_12__ with\n       | _, Tip => None\n       | x, Bin _ y l r =>\n           match GHC.Base.compare x y with\n           | Lt => goNothing x l\n           | Eq => Some y\n           | Gt => goJust x y r\n           end\n       end in\n  goNothing.\n\nDefinition lookupGE {a : Type} `{GHC.Base.Ord a} : a -> Set_ a -> option a :=\n  let fix goJust arg_0__ arg_1__ arg_2__\n    := match arg_0__, arg_1__, arg_2__ with\n       | _, best, Tip => Some best\n       | x, best, Bin _ y l r =>\n           match GHC.Base.compare x y with\n           | Lt => goJust x y l\n           | Eq => Some y\n           | Gt => goJust x best r\n           end\n       end in\n  let fix goNothing arg_11__ arg_12__\n    := match arg_11__, arg_12__ with\n       | _, Tip => None\n       | x, Bin _ y l r =>\n           match GHC.Base.compare x y with\n           | Lt => goJust x y l\n           | Eq => Some y\n           | Gt => goNothing x r\n           end\n       end in\n  goNothing.\n\nDefinition delete {a : Type} `{GHC.Base.Ord a} : a -> Set_ a -> Set_ a :=\n  let go {a} `{GHC.Base.Ord a} : a -> Set_ a -> Set_ a :=\n    fix go (arg_0__ : a) (arg_1__ : Set_ a) : Set_ a\n      := match arg_0__, arg_1__ with\n         | _, Tip => Tip\n         | x, (Bin _ y l r as t) =>\n             match GHC.Base.compare x y with\n             | Lt =>\n                 let l' := go x l in\n                 if Utils.Containers.Internal.PtrEquality.ptrEq l' l : bool then t else\n                 balanceR y l' r\n             | Gt =>\n                 let r' := go x r in\n                 if Utils.Containers.Internal.PtrEquality.ptrEq r' r : bool then t else\n                 balanceL y l r'\n             | Eq => glue l r\n             end\n         end in\n  go.\n\nFixpoint splitMember {a : Type} `{GHC.Base.Ord a} (arg_0__ : a) (arg_1__\n                       : Set_ a) : (Set_ a * bool * Set_ a)%type\n  := match arg_0__, arg_1__ with\n     | _, Tip => pair (pair Tip false) Tip\n     | x, Bin _ y l r =>\n         match GHC.Base.compare x y with\n         | Lt =>\n             let 'pair (pair lt found) gt := splitMember x l in\n             let gt' := link y gt r in pair (pair lt found) gt'\n         | Gt =>\n             let 'pair (pair lt found) gt := splitMember x r in\n             let lt' := link y l lt in pair (pair lt' found) gt\n         | Eq => pair (pair l true) r\n         end\n     end.\n\nFixpoint isSubsetOfX {a} `{GHC.Base.Ord a} (arg_0__ arg_1__ : Set_ a) : bool\n  := match arg_0__, arg_1__ with\n     | Tip, _ => true\n     | _, Tip => false\n     | Bin _ x l r, t =>\n         let 'pair (pair lt found) gt := splitMember x t in\n         andb found (andb (isSubsetOfX l lt) (isSubsetOfX r gt))\n     end.\n\nDefinition isSubsetOf {a : Type} `{GHC.Base.Ord a} : Set_ a -> Set_ a -> bool :=\n  fun t1 t2 => andb (size t1 GHC.Base.<= size t2) (isSubsetOfX t1 t2).\n\nDefinition isProperSubsetOf {a : Type} `{GHC.Base.Ord a}\n   : Set_ a -> Set_ a -> bool :=\n  fun s1 s2 => andb (size s1 GHC.Base.< size s2) (isSubsetOf s1 s2).\n\nFixpoint disjoint {a : Type} `{GHC.Base.Ord a} (arg_0__ arg_1__ : Set_ a) : bool\n  := match arg_0__, arg_1__ with\n     | Tip, _ => true\n     | _, Tip => true\n     | Bin _ x l r, t =>\n         let 'pair (pair lt found) gt := splitMember x t in\n         andb (negb found) (andb (disjoint l lt) (disjoint r gt))\n     end.\n\nFixpoint lookupMinSure {a} (arg_0__ : a) (arg_1__ : Set_ a) : a\n  := match arg_0__, arg_1__ with\n     | x, Tip => x\n     | _, Bin _ x l _ => lookupMinSure x l\n     end.\n\nDefinition lookupMin {a : Type} : Set_ a -> option a :=\n  fun arg_0__ =>\n    match arg_0__ with\n    | Tip => None\n    | Bin _ x l _ => Some (lookupMinSure x l)\n    end.\n\n(* Skipping definition `Data.Set.Internal.findMin' *)\n\nFixpoint lookupMaxSure {a} (arg_0__ : a) (arg_1__ : Set_ a) : a\n  := match arg_0__, arg_1__ with\n     | x, Tip => x\n     | _, Bin _ x _ r => lookupMaxSure x r\n     end.\n\nDefinition lookupMax {a : Type} : Set_ a -> option a :=\n  fun arg_0__ =>\n    match arg_0__ with\n    | Tip => None\n    | Bin _ x _ r => Some (lookupMaxSure x r)\n    end.\n\n(* Skipping definition `Data.Set.Internal.findMax' *)\n\nFixpoint deleteMin {a : Type} (arg_0__ : Set_ a) : Set_ a\n  := match arg_0__ with\n     | Bin _ _ Tip r => r\n     | Bin _ x l r => balanceR x (deleteMin l) r\n     | Tip => Tip\n     end.\n\nFixpoint deleteMax {a : Type} (arg_0__ : Set_ a) : Set_ a\n  := match arg_0__ with\n     | Bin _ _ l Tip => l\n     | Bin _ x l r => balanceL x l (deleteMax r)\n     | Tip => Tip\n     end.\n\nFixpoint intersection {a : Type} `{GHC.Base.Ord a} (arg_0__ arg_1__ : Set_ a)\n  : Set_ a\n  := match arg_0__, arg_1__ with\n     | Tip, _ => Tip\n     | _, Tip => Tip\n     | (Bin _ x l1 r1 as t1), t2 =>\n         let 'pair (pair l2 b) r2 := splitMember x t2 in\n         let l1l2 := intersection l1 l2 in\n         let r1r2 := intersection r1 r2 in\n         if b : bool\n         then if andb (Utils.Containers.Internal.PtrEquality.ptrEq l1l2 l1)\n                      (Utils.Containers.Internal.PtrEquality.ptrEq r1r2 r1) : bool\n              then t1\n              else link x l1l2 r1r2 else\n         merge l1l2 r1r2\n     end.\n\nFixpoint filter {a : Type} (arg_0__ : a -> bool) (arg_1__ : Set_ a) : Set_ a\n  := match arg_0__, arg_1__ with\n     | _, Tip => Tip\n     | p, (Bin _ x l r as t) =>\n         let r' := filter p r in\n         let l' := filter p l in\n         if p x : bool\n         then if andb (Utils.Containers.Internal.PtrEquality.ptrEq l l')\n                      (Utils.Containers.Internal.PtrEquality.ptrEq r r') : bool\n              then t\n              else link x l' r' else\n         merge l' r'\n     end.\n\nDefinition partition {a : Type}\n   : (a -> bool) -> Set_ a -> (Set_ a * Set_ a)%type :=\n  fun p0 t0 =>\n    let fix go arg_0__ arg_1__\n      := match arg_0__, arg_1__ with\n         | _, Tip => (pair Tip Tip)\n         | p, (Bin _ x l r as t) =>\n             let 'pair (pair l1 l2) (pair r1 r2) := pair (go p l) (go p r) in\n             if p x : bool\n             then pair (if andb (Utils.Containers.Internal.PtrEquality.ptrEq l1 l)\n                                (Utils.Containers.Internal.PtrEquality.ptrEq r1 r) : bool\n                        then t\n                        else link x l1 r1) (merge l2 r2) else\n             pair (merge l1 r1) (if andb (Utils.Containers.Internal.PtrEquality.ptrEq l2 l)\n                                         (Utils.Containers.Internal.PtrEquality.ptrEq r2 r) : bool\n                   then t\n                   else link x l2 r2)\n         end in\n    id (go p0 t0).\n\nDefinition fromList {a : Type} `{GHC.Base.Ord a} : list a -> Set_ a :=\n  fun arg_0__ =>\n    match arg_0__ with\n    | nil => Tip\n    | cons x nil => Bin #1 x Tip Tip\n    | cons x0 xs0 =>\n        let fromList' :=\n          fun t0 xs =>\n            let ins := fun t x => insert x t in Data.Foldable.foldl' ins t0 xs in\n        let not_ordered :=\n          fun arg_4__ arg_5__ =>\n            match arg_4__, arg_5__ with\n            | _, nil => false\n            | x, cons y _ => x GHC.Base.>= y\n            end in\n        let create :=\n          HsToCoq.DeferredFix.deferredFix2 (fun create arg_8__ arg_9__ =>\n                                              match arg_8__, arg_9__ with\n                                              | _, nil => pair (pair Tip nil) nil\n                                              | s, (cons x xss as xs) =>\n                                                  if s GHC.Base.== #1 : bool\n                                                  then if not_ordered x xss : bool\n                                                       then pair (pair (Bin #1 x Tip Tip) nil) xss\n                                                       else pair (pair (Bin #1 x Tip Tip) xss) nil else\n                                                  match create (Data.Bits.shiftR s #1) xs with\n                                                  | (pair (pair _ nil) _ as res) => res\n                                                  | pair (pair l (cons y nil)) zs => pair (pair (insertMax y l) nil) zs\n                                                  | pair (pair l (cons y yss as ys)) _ =>\n                                                      if not_ordered y yss : bool then pair (pair l nil) ys else\n                                                      let 'pair (pair r zs) ws := create (Data.Bits.shiftR s #1) yss in\n                                                      pair (pair (link y l r) zs) ws\n                                                  end\n                                              end) in\n        let go :=\n          HsToCoq.DeferredFix.deferredFix3 (fun go arg_22__ arg_23__ arg_24__ =>\n                                              match arg_22__, arg_23__, arg_24__ with\n                                              | _, t, nil => t\n                                              | _, t, cons x nil => insertMax x t\n                                              | s, l, (cons x xss as xs) =>\n                                                  if not_ordered x xss : bool then fromList' l xs else\n                                                  match create s xss with\n                                                  | pair (pair r ys) nil => go (Data.Bits.shiftL s #1) (link x l r) ys\n                                                  | pair (pair r _) ys => fromList' (link x l r) ys\n                                                  end\n                                              end) in\n        if not_ordered x0 xs0 : bool then fromList' (Bin #1 x0 Tip Tip) xs0 else\n        go (#1 : GHC.Num.Int) (Bin #1 x0 Tip Tip) xs0\n    end.\n\nDefinition map {b : Type} {a : Type} `{GHC.Base.Ord b}\n   : (a -> b) -> Set_ a -> Set_ b :=\n  fun f => fromList GHC.Base.∘ (GHC.Base.map f GHC.Base.∘ toList).\n\nFixpoint mapMonotonic {a : Type} {b : Type} (arg_0__ : a -> b) (arg_1__\n                        : Set_ a) : Set_ b\n  := match arg_0__, arg_1__ with\n     | _, Tip => Tip\n     | f, Bin sz x l r => Bin sz (f x) (mapMonotonic f l) (mapMonotonic f r)\n     end.\n\nDefinition fold {a : Type} {b : Type} : (a -> b -> b) -> b -> Set_ a -> b :=\n  foldr.\n\nDefinition elems {a : Type} : Set_ a -> list a :=\n  toAscList.\n\nDefinition toDescList {a : Type} : Set_ a -> list a :=\n  foldl (GHC.Base.flip cons) nil.\n\nDefinition foldrFB {a} {b} : (a -> b -> b) -> b -> Set_ a -> b :=\n  foldr.\n\nDefinition foldlFB {a} {b} : (a -> b -> a) -> a -> Set_ b -> a :=\n  foldl.\n\nDefinition combineEq {a} `{GHC.Base.Eq_ a} : list a -> list a :=\n  fun arg_0__ =>\n    match arg_0__ with\n    | nil => nil\n    | cons x xs =>\n        let fix combineEq' arg_1__ arg_2__\n          := match arg_1__, arg_2__ with\n             | z, nil => cons z nil\n             | z, cons y ys =>\n                 if z GHC.Base.== y : bool then combineEq' z ys else\n                 cons z (combineEq' y ys)\n             end in\n        combineEq' x xs\n    end.\n\nDefinition fromDistinctAscList {a : Type} : list a -> Set_ a :=\n  fun arg_0__ =>\n    match arg_0__ with\n    | nil => Tip\n    | cons x0 xs0 =>\n        let create :=\n          HsToCoq.DeferredFix.deferredFix2 (fun create arg_1__ arg_2__ =>\n                                              match arg_1__, arg_2__ with\n                                              | _, nil => (pair Tip nil)\n                                              | s, (cons x xs' as xs) =>\n                                                  if s GHC.Base.== #1 : bool then (pair (Bin #1 x Tip Tip) xs') else\n                                                  match create (Data.Bits.shiftR s #1) xs with\n                                                  | (pair _ nil as res) => res\n                                                  | pair l (cons y ys) =>\n                                                      let 'pair r zs := create (Data.Bits.shiftR s #1) ys in\n                                                      (pair (link y l r) zs)\n                                                  end\n                                              end) in\n        let go :=\n          HsToCoq.DeferredFix.deferredFix3 (fun go arg_13__ arg_14__ arg_15__ =>\n                                              match arg_13__, arg_14__, arg_15__ with\n                                              | _, t, nil => t\n                                              | s, l, cons x xs =>\n                                                  let 'pair r ys := create s xs in\n                                                  let t' := link x l r in go (Data.Bits.shiftL s #1) t' ys\n                                              end) in\n        go (#1 : GHC.Num.Int) (Bin #1 x0 Tip Tip) xs0\n    end.\n\nDefinition fromAscList {a : Type} `{GHC.Base.Eq_ a} : list a -> Set_ a :=\n  fun xs => fromDistinctAscList (combineEq xs).\n\nDefinition fromDistinctDescList {a : Type} : list a -> Set_ a :=\n  fun arg_0__ =>\n    match arg_0__ with\n    | nil => Tip\n    | cons x0 xs0 =>\n        let create :=\n          HsToCoq.DeferredFix.deferredFix2 (fun create arg_1__ arg_2__ =>\n                                              match arg_1__, arg_2__ with\n                                              | _, nil => (pair Tip nil)\n                                              | s, (cons x xs' as xs) =>\n                                                  if s GHC.Base.== #1 : bool then (pair (Bin #1 x Tip Tip) xs') else\n                                                  match create (Data.Bits.shiftR s #1) xs with\n                                                  | (pair _ nil as res) => res\n                                                  | pair r (cons y ys) =>\n                                                      let 'pair l zs := create (Data.Bits.shiftR s #1) ys in\n                                                      (pair (link y l r) zs)\n                                                  end\n                                              end) in\n        let go :=\n          HsToCoq.DeferredFix.deferredFix3 (fun go arg_13__ arg_14__ arg_15__ =>\n                                              match arg_13__, arg_14__, arg_15__ with\n                                              | _, t, nil => t\n                                              | s, r, cons x xs =>\n                                                  let 'pair l ys := create s xs in\n                                                  let t' := link x l r in go (Data.Bits.shiftL s #1) t' ys\n                                              end) in\n        go (#1 : GHC.Num.Int) (Bin #1 x0 Tip Tip) xs0\n    end.\n\nDefinition fromDescList {a : Type} `{GHC.Base.Eq_ a} : list a -> Set_ a :=\n  fun xs => fromDistinctDescList (combineEq xs).\n\n(* Skipping definition `Data.Set.Internal.findIndex' *)\n\nDefinition lookupIndex {a : Type} `{GHC.Base.Ord a}\n   : a -> Set_ a -> option GHC.Num.Int :=\n  let go {a} `{GHC.Base.Ord a}\n   : GHC.Num.Int -> a -> Set_ a -> option GHC.Num.Int :=\n    fix go (arg_0__ : GHC.Num.Int) (arg_1__ : a) (arg_2__ : Set_ a) : option\n                                                                      GHC.Num.Int\n      := match arg_0__, arg_1__, arg_2__ with\n         | _, _, Tip => None\n         | idx, x, Bin _ kx l r =>\n             match GHC.Base.compare x kx with\n             | Lt => go idx x l\n             | Gt => go ((idx GHC.Num.+ size l) GHC.Num.+ #1) x r\n             | Eq => Some (idx GHC.Num.+ size l)\n             end\n         end in\n  go #0.\n\n(* Skipping definition `Data.Set.Internal.elemAt' *)\n\n(* Skipping definition `Data.Set.Internal.deleteAt' *)\n\nDefinition take {a : Type} : GHC.Num.Int -> Set_ a -> Set_ a :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__, arg_1__ with\n    | i, m =>\n        if i GHC.Base.>= size m : bool then m else\n        match arg_0__, arg_1__ with\n        | i0, m0 =>\n            let fix go arg_2__ arg_3__\n              := match arg_2__, arg_3__ with\n                 | i, _ =>\n                     if i GHC.Base.<= #0 : bool then Tip else\n                     match arg_2__, arg_3__ with\n                     | _, Tip => Tip\n                     | i, Bin _ x l r =>\n                         let sizeL := size l in\n                         match GHC.Base.compare i sizeL with\n                         | Lt => go i l\n                         | Gt => link x l (go ((i GHC.Num.- sizeL) GHC.Num.- #1) r)\n                         | Eq => l\n                         end\n                     end\n                 end in\n            go i0 m0\n        end\n    end.\n\nDefinition drop {a : Type} : GHC.Num.Int -> Set_ a -> Set_ a :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__, arg_1__ with\n    | i, m =>\n        if i GHC.Base.>= size m : bool then Tip else\n        match arg_0__, arg_1__ with\n        | i0, m0 =>\n            let fix go arg_2__ arg_3__\n              := match arg_2__, arg_3__ with\n                 | i, m =>\n                     if i GHC.Base.<= #0 : bool then m else\n                     match arg_2__, arg_3__ with\n                     | _, Tip => Tip\n                     | i, Bin _ x l r =>\n                         let sizeL := size l in\n                         match GHC.Base.compare i sizeL with\n                         | Lt => link x (go i l) r\n                         | Gt => go ((i GHC.Num.- sizeL) GHC.Num.- #1) r\n                         | Eq => insertMin x r\n                         end\n                     end\n                 end in\n            go i0 m0\n        end\n    end.\n\nDefinition splitAt {a : Type}\n   : GHC.Num.Int -> Set_ a -> (Set_ a * Set_ a)%type :=\n  fun i0 m0 =>\n    let fix go arg_0__ arg_1__\n      := match arg_0__, arg_1__ with\n         | i, m =>\n             if i GHC.Base.<= #0 : bool then pair Tip m else\n             match arg_0__, arg_1__ with\n             | _, Tip => pair Tip Tip\n             | i, Bin _ x l r =>\n                 let sizeL := size l in\n                 match GHC.Base.compare i sizeL with\n                 | Lt => let 'pair ll lr := go i l in pair ll (link x lr r)\n                 | Gt =>\n                     let 'pair rl rr := go ((i GHC.Num.- sizeL) GHC.Num.- #1) r in\n                     pair (link x l rl) rr\n                 | Eq => pair l (insertMin x r)\n                 end\n             end\n         end in\n    if i0 GHC.Base.>= size m0 : bool then pair m0 Tip else\n    id (go i0 m0).\n\nFixpoint takeWhileAntitone {a : Type} (arg_0__ : a -> bool) (arg_1__ : Set_ a)\n  : Set_ a\n  := match arg_0__, arg_1__ with\n     | _, Tip => Tip\n     | p, Bin _ x l r =>\n         if p x : bool then link x l (takeWhileAntitone p r) else\n         takeWhileAntitone p l\n     end.\n\nFixpoint dropWhileAntitone {a : Type} (arg_0__ : a -> bool) (arg_1__ : Set_ a)\n  : Set_ a\n  := match arg_0__, arg_1__ with\n     | _, Tip => Tip\n     | p, Bin _ x l r =>\n         if p x : bool then dropWhileAntitone p r else\n         link x (dropWhileAntitone p l) r\n     end.\n\nDefinition spanAntitone {a : Type}\n   : (a -> bool) -> Set_ a -> (Set_ a * Set_ a)%type :=\n  fun p0 m =>\n    let fix go arg_0__ arg_1__\n      := match arg_0__, arg_1__ with\n         | _, Tip => pair Tip Tip\n         | p, Bin _ x l r =>\n             if p x : bool then let 'pair u v := go p r in pair (link x l u) v else\n             let 'pair u v := go p l in\n             pair u (link x v r)\n         end in\n    id (go p0 m).\n\n(* Skipping definition `Data.Set.Internal.deleteFindMin' *)\n\n(* Skipping definition `Data.Set.Internal.deleteFindMax' *)\n\nDefinition minView {a : Type} : Set_ a -> option (a * Set_ a)%type :=\n  fun arg_0__ =>\n    match arg_0__ with\n    | Tip => None\n    | Bin _ x l r => Some (id (minViewSure x l r))\n    end.\n\nDefinition maxView {a : Type} : Set_ a -> option (a * Set_ a)%type :=\n  fun arg_0__ =>\n    match arg_0__ with\n    | Tip => None\n    | Bin _ x l r => Some (id (maxViewSure x l r))\n    end.\n\nDefinition splitRoot {a : Type} : Set_ a -> list (Set_ a) :=\n  fun orig =>\n    match orig with\n    | Tip => nil\n    | Bin _ v l r => cons l (cons (singleton v) (cons r nil))\n    end.\n\nDefinition powerSet {a : Type} : Set_ a -> Set_ (Set_ a) :=\n  fun xs0 =>\n    let step :=\n      fun x pxs =>\n        glue (insertMin (singleton x) (mapMonotonic (insertMin x) pxs)) pxs in\n    insertMin empty (foldr' step Tip xs0).\n\nDefinition cartesianProduct {a : Type} {b : Type}\n   : Set_ a -> Set_ b -> Set_ (a * b)%type :=\n  fun as_ bs =>\n    getMergeSet (Data.Foldable.foldMap (fun a =>\n                                          Mk_MergeSet (mapMonotonic (GHC.Tuple.pair2 a) bs)) as_).\n\nDefinition disjointUnion {a : Type} {b : Type}\n   : Set_ a -> Set_ b -> Set_ (Data.Either.Either a b) :=\n  fun as_ bs =>\n    merge (mapMonotonic Data.Either.Left as_) (mapMonotonic Data.Either.Right bs).\n\n(* Skipping definition `Data.Set.Internal.showTree' *)\n\n(* Skipping definition `Data.Set.Internal.showTreeWith' *)\n\n(* Skipping definition `Data.Set.Internal.showsTree' *)\n\n(* Skipping definition `Data.Set.Internal.showsTreeHang' *)\n\n(* Skipping definition `Data.Set.Internal.showWide' *)\n\n(* Skipping definition `Data.Set.Internal.showsBars' *)\n\n(* Skipping definition `Data.Set.Internal.node' *)\n\n(* Skipping definition `Data.Set.Internal.withBar' *)\n\n(* Skipping definition `Data.Set.Internal.withEmpty' *)\n\nFixpoint balanced {a : Type} (t : Set_ a) : bool\n  := match t with\n     | Tip => true\n     | Bin _ _ l r =>\n         andb (orb ((size l GHC.Num.+ size r) GHC.Base.<= #1) (andb (size l GHC.Base.<=\n                                                                     (delta GHC.Num.* size r)) (size r GHC.Base.<=\n                                                                     (delta GHC.Num.* size l)))) (andb (balanced l)\n                                                                                                       (balanced r))\n     end.\n\nDefinition ordered {a} `{GHC.Base.Ord a} : Set_ a -> bool :=\n  fun t =>\n    let fix bounded lo hi t'\n      := match t' with\n         | Tip => true\n         | Bin _ x l r =>\n             andb (lo x) (andb (hi x) (andb (bounded lo (fun arg_0__ => arg_0__ GHC.Base.< x)\n                                             l) (bounded (fun arg_1__ => arg_1__ GHC.Base.> x) hi r)))\n         end in\n    bounded (GHC.Base.const true) (GHC.Base.const true) t.\n\nDefinition validsize {a} : Set_ a -> bool :=\n  fun t =>\n    let fix realsize t'\n      := match t' with\n         | Tip => Some #0\n         | Bin sz _ l r =>\n             match pair (realsize l) (realsize r) with\n             | pair (Some n) (Some m) =>\n                 if ((n GHC.Num.+ m) GHC.Num.+ #1) GHC.Base.== sz : bool then Some sz else\n                 None\n             | _ => None\n             end\n         end in\n    (realsize t GHC.Base.== Some (size t)).\n\nDefinition valid {a : Type} `{GHC.Base.Ord a} : Set_ a -> bool :=\n  fun t => andb (balanced t) (andb (ordered t) (validsize t)).\n\nModule Notations.\nNotation \"'_Data.Set.Internal.\\\\_'\" := (op_zrzr__).\nInfix \"Data.Set.Internal.\\\\\" := (_\\\\_) (at level 99).\nEnd Notations.\n\n(* External variables:\n     Bool.Sumbool.sumbool_of_bool Eq Gt Lt None Some Type andb bool comparison cons\n     false id list negb nil op_zt__ option orb pair prod set_size true\n     Data.Bits.shiftL Data.Bits.shiftR Data.Either.Either Data.Either.Left\n     Data.Either.Right Data.Foldable.Foldable Data.Foldable.foldMap\n     Data.Foldable.foldMap__ Data.Foldable.fold__ Data.Foldable.foldl'\n     Data.Foldable.foldl'__ Data.Foldable.foldl__ Data.Foldable.foldr'__\n     Data.Foldable.foldr__ Data.Foldable.length__ Data.Foldable.null__\n     Data.Foldable.product__ Data.Foldable.sum__ Data.Foldable.toList__\n     Data.Functor.Classes.Eq1 Data.Functor.Classes.Ord1\n     Data.Functor.Classes.liftCompare Data.Functor.Classes.liftCompare__\n     Data.Functor.Classes.liftEq Data.Functor.Classes.liftEq__ GHC.Base.Eq_\n     GHC.Base.Monoid GHC.Base.Ord GHC.Base.Semigroup GHC.Base.compare\n     GHC.Base.compare__ GHC.Base.const GHC.Base.flip GHC.Base.foldr GHC.Base.map\n     GHC.Base.mappend GHC.Base.mappend__ GHC.Base.max__ GHC.Base.mconcat__\n     GHC.Base.mempty 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_zlze____ GHC.Base.op_zlzlzgzg__\n     GHC.Base.op_zlzlzgzg____ GHC.Base.op_zsze__ GHC.Base.op_zsze____ GHC.Err.error\n     GHC.Err.patternFailure GHC.Num.Int GHC.Num.Num GHC.Num.fromInteger\n     GHC.Num.op_zm__ GHC.Num.op_zp__ GHC.Num.op_zt__ GHC.Tuple.pair2\n     HsToCoq.DeferredFix.deferredFix2 HsToCoq.DeferredFix.deferredFix3 Nat.add\n     Utils.Containers.Internal.PtrEquality.ptrEq\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/containers/lib/Data/Set/Internal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.28046956291449965}}
{"text": "From Coq Require Import Strings.String BinNat List.\nFrom ExtLib Require Import Monad.\n\n(* https://tools.ietf.org/html/rfc7541#section-1.3 *)\n(* Header Field:  A name-value pair.  Both the name and value are\n      treated as opaque sequences of octets. *)\nDefinition HeaderField := (string * string)%type.\n\n(* Dynamic Table:  The dynamic table is a table that\n      associates stored header fields with index values.  This table is\n      dynamic and specific to an encoding or decoding context.\n\n   Static Table:  The static table is a table that\n      statically associates header fields that occur frequently with\n      index values.  This table is ordered, read-only, always\n      accessible, and it may be shared amongst all encoding or decoding\n      contexts. *)\nDefinition Table := list HeaderField.\n\n(* Dynamic Tables are a triple of a size, a maximum size and a table. \n   The maximum size is provided by the SETTINGS_HEADER_TABLE_SIZE, \n   https://tools.ietf.org/html/rfc7540#section-6.5.2\n   The default value for the maximum size is 4096.\n   The convention is that the table has size (as defined in \n   https://tools.ietf.org/html/rfc7541#section-4.1) less than or equal to the\n   maximum size, which is enforced by the functions that add entries.  *)\nDefinition DTable := (N * N * Table)%type.\n\n(* Header List:  A header list is an ordered collection of header fields\n      that are encoded jointly and can contain duplicate header fields.\n      A complete list of header fields contained in an HTTP/2 header\n      block is a header list. *)\nDefinition HeaderList := list HeaderField.\n\n(* https://tools.ietf.org/html/rfc7541#section-6 *)\n(* Header Field Representation:  A header field can be represented in\n      encoded form either as a literal or as an index *)\nInductive HeaderFieldRepresentation :=\n(* https://tools.ietf.org/html/rfc7541#section-6.1 *)\n| IndexedHF : N -> HeaderFieldRepresentation\n(* https://tools.ietf.org/html/rfc7541#section-6.2 *)\n| LHFIncrementIndexedName : N -> string -> HeaderFieldRepresentation\n| LHFIncrementNewName : string -> string -> HeaderFieldRepresentation\n| LHFWithoutIndexIndexedName : N -> string -> HeaderFieldRepresentation\n| LHFWithoutIndexNewName : string -> string -> HeaderFieldRepresentation\n| LHFNeverIndexIndexedName : N -> string -> HeaderFieldRepresentation\n| LHFNeverIndexNewName : string -> string -> HeaderFieldRepresentation\n(* https://tools.ietf.org/html/rfc7541#section-6.3 *)\n| DTableSizeUpdate : N -> HeaderFieldRepresentation.\n\n(* Header Block:  An ordered list of header field representations,\n      which, when decoded, yields a complete header list. *)\nDefinition HeaderBlock := list HeaderFieldRepresentation.\n\n(* Error type for HPACK *)\nInductive HPACKError :=\n| IndexOverrun : N -> HPACKError (* Index is out of range *)\n| EosInTheMiddle : HPACKError (* Eos appears in the middle of huffman string *)\n| IllegalEos : HPACKError (* Non-eos appears in the end of huffman string *)\n| TooLongEos : HPACKError\t(* Eos of huffman string is more than 7 bits *)\n| EmptyEncodedString : HPACKError (* Encoded string has no length *)\n| TooSmallTableSize : HPACKError (* A peer set the dynamic table size less than 32 *)\n| TooLargeTableSize : HPACKError (* A peer tried to change the dynamic table size over the limit *)\n| IllegalTableSizeUpdate : HPACKError (* Table size update at the non-beginning *)\n| HeaderBlockTruncated : HPACKError\t \n| IllegalHeaderName : HPACKError\n| IntegerOverflow : HPACKError (* Integer is too large to encode *)\n| HeaderBlockOverflow : HPACKError (* Too many headers in header block *).\n\nDefinition Err := sum HPACKError.\n\nInstance monadErr : Monad Err :=\n  {|\n    ret := @inr HPACKError;\n    bind _ _ x f := match x with\n                | inl e => inl e\n                | inr v => f v\n                end |}.\n                    \n                      ", "meta": {"author": "liyishuai", "repo": "coq-http2", "sha": "23a08abb61f159c38765a71db7a550d4c4e4a920", "save_path": "github-repos/coq/liyishuai-coq-http2", "path": "github-repos/coq/liyishuai-coq-http2/coq-http2-23a08abb61f159c38765a71db7a550d4c4e4a920/src/HPACK/HPACKTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.4148988457967689, "lm_q1q2_score": 0.28037395841160584}}
{"text": "Add LoadPath \"/home/user/Downloads/archives/cats-in-zfc-2945072aa6c9c328a019d3128c0a725dabca434c\".\nRequire Export CatsInZFC.tactics.\n\nTheorem w1 (x : E):nonempty x -> exists y : E, inc y x.\nProof.\nintros.\nelim H.\nintros.\nexists y.\ntrivial.\nDefined.\n\nDefinition w2 (x : E): (exists y : E, inc y x) -> nonempty x.\nProof.\nintros H.\nelim H.\nPrint nonempty.\nintro y.\nconstructor 1 with (y:=y).\nassumption.\nDefined.\n\nDefinition w3 (x : E):nonempty x <-> exists y : E, inc y x.\nProof.\nsplit.\nexact (w1 x).\nexact (w2 x).\nDefined.\n\nDefinition v0 (a b:E): (forall x:E, (inc x a) <-> (inc x b)) <-> (a=b).\nProof.\nsplit.\n* intros.\n  apply extensionality.\n   all: (*par: *)\n   intro x;\n   elim (H x);\n   intros H0 H1;\n   assumption.\n* intros.\n  replace a with b.\n  firstorder.\nDefined.\n(* CTRL+SHFT+L    \"<->\"  *)\n(* A: iff is transparent.  What is not transparent? *)\n\n\nauto.\n  info_auto.\n\n  rewrite a.\n  change b with a. \n(*in |- *.*)\n  split.\n\nintro E.\nreplace x0 with y .\n\n\nInductive mybool:=| a:True->mybool |b:mybool.\nTheorem g: mybool.\nconstructor.\nDefined.\n\n(*intros q w.*)\n\nintros.\n\n\napply (@nonempty_intro _ _ H0).\n\nCheck (@nonempty_intro _ _ H0).\n\nFocus 2.\nconstructor.\nunfold nonempty.\nred.\nDefined.\n(*\nelimtype (nonempty x).\ncofix x.\nfix Q 0.\n*)\n\nProof.\nDefined.\n\nProof.\nDefined.\n", "meta": {"author": "georgydunaev", "repo": "TRASH", "sha": "36b24517b8c51817e1b8eb39df945d30c287162b", "save_path": "github-repos/coq/georgydunaev-TRASH", "path": "github-repos/coq/georgydunaev-TRASH/TRASH-36b24517b8c51817e1b8eb39df945d30c287162b/experiments/cats_thms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.28017856802459373}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Main.\nRequire Import Functor.Functor Functor.Functor_Ops\n        Functor.Representable.Hom_Func.\nRequire Import Functor.Functor_Extender.\nRequire Import NatTrans.NatTrans NatTrans.Operations\n        NatTrans.Func_Cat NatTrans.NatIso.\nRequire Import Ext_Cons.Prod_Cat.Prod_Cat Ext_Cons.Prod_Cat.Operations\n        Ext_Cons.Prod_Cat.Nat_Facts.\nRequire Import Adjunction.Adjunction.\nRequire Import KanExt.Local  KanExt.LocalFacts.Uniqueness.\nRequire Import Basic_Cons.Terminal.\n\nLocal Open Scope functor_scope.\n\n(** This module contains conversion from local kan extension defiend as cones\nto local kan extensions defined through hom functor. *)\n\nSection Local_Right_KanExt_to_Hom_Local_Right_KanExt.\n  Context {C C' : Category} {p : C –≻ C'}\n          {D : Category} {F : C –≻ D}\n          (lrke : Local_Right_KanExt p F).\n\n  (** The left to right side of Hom_Local_Right_KanExt isomorphism. *)\n  Program Definition Local_Right_KanExt_to_Hom_Local_Right_KanExt_Iso_LR :\n    (((@Fix_Bi_Func_2 _ (Func_Cat C D) _ F (Hom_Func (Func_Cat C D)))\n        ∘ (Left_Functor_Extender p D)^op)\n       –≻ (@Fix_Bi_Func_2 _ (Func_Cat C' D)\n                          _ lrke (Hom_Func (Func_Cat C' D))))%nattrans :=\n    {|\n      Trans :=  fun c h => LRKE_morph_ex lrke {|cone_apex := c; cone_edge := h|}\n    |}.\n\n  Next Obligation.\n  Proof.\n    extensionality x.\n    repeat rewrite NatTrans_id_unit_left.\n    match goal with\n      [|- cone_morph (LRKE_morph_ex lrke ?A) = ?X] =>\n      match X with\n        ((cone_morph ?C) ∘ ?B)%nattrans =>\n        change X with\n        (cone_morph\n           (LoKan_Cone_Morph_compose\n              _\n              _\n              (Build_LoKan_Cone_Morph\n                 p F A {|cone_apex := c; cone_edge := x|} h eq_refl) C\n           )\n        )\n      end\n    end.\n    apply LRKE_morph_unique.\n  Qed.\n\n  Next Obligation.\n  Proof.\n    symmetry.\n    apply Local_Right_KanExt_to_Hom_Local_Right_KanExt_Iso_LR_obligation_1.\n  Qed.\n\n  (** The right to left side of Hom_Local_Right_KanExt isomorphism. *)\n  Program Definition Local_Right_KanExt_to_Hom_Local_Right_KanExt_Iso_RL :\n    ((@Fix_Bi_Func_2 _ (Func_Cat C' D) _ lrke (Hom_Func (Func_Cat C' D)))\n       –≻ ((@Fix_Bi_Func_2 _ (Func_Cat C D) _ F (Hom_Func (Func_Cat C D)))\n             ∘ (Left_Functor_Extender p D)^op\n             ))%nattrans\n    :=\n    {|\n      Trans :=  fun c h => (lrke ∘ (h ∘_h (NatTrans_id p)))%nattrans\n    |}.\n \n  Next Obligation.\n  Proof.\n    extensionality x.\n    repeat rewrite NatTrans_id_unit_left.\n    rewrite NatTrans_compose_assoc.\n    rewrite NatTrans_comp_hor_comp.\n    rewrite NatTrans_id_unit_right.\n    trivial.\n  Qed.\n\n  Next Obligation.\n  Proof.\n    symmetry.\n    apply Local_Right_KanExt_to_Hom_Local_Right_KanExt_Iso_RL_obligation_1.\n  Qed.\n\n  (** Conversion from Local_Right_KanExt Hom_Local_Right_KanExt isomorphism. *)\n  Program Definition Local_Right_KanExt_to_Hom_Local_Right_KanExt :\n    Hom_Local_Right_KanExt p F :=\n    {|\n      HLRKE := (cone_apex (LRKE lrke));\n      HLRKE_Iso :=\n        {|\n          iso_morphism := Local_Right_KanExt_to_Hom_Local_Right_KanExt_Iso_LR;\n          inverse_morphism :=\n            Local_Right_KanExt_to_Hom_Local_Right_KanExt_Iso_RL\n        |}\n    |}.\n\n  Next Obligation.\n  Proof.\n    apply NatTrans_eq_simplify.\n    extensionality h; extensionality x.\n    symmetry.\n    apply (cone_morph_com\n             (LRKE_morph_ex lrke {| cone_apex := h; cone_edge := x |})).\n  Qed.\n\n  Next Obligation.\n  Proof.\n    apply NatTrans_eq_simplify.\n    extensionality h; extensionality x.\n    cbn in *.\n    match goal with\n      [|- cone_morph (LRKE_morph_ex lrke ?A) = ?X] =>\n      change X with (cone_morph (Build_LoKan_Cone_Morph p F A lrke x eq_refl));\n        apply (LRKE_morph_unique lrke A)\n    end.\n  Qed.\n\nEnd Local_Right_KanExt_to_Hom_Local_Right_KanExt.", "meta": {"author": "agumonkey", "repo": "cats", "sha": "9f12c5090c2a75fe14eb72c1a806723e38dbb03c", "save_path": "github-repos/coq/agumonkey-cats", "path": "github-repos/coq/agumonkey-cats/cats-9f12c5090c2a75fe14eb72c1a806723e38dbb03c/coq/Categories/KanExt/LocalFacts/ConesToHom.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.28017856220223947}}
{"text": "(*****************************************************************\n\n Structure on the bicategory of enriched category\n\n In this file, we construct a duality involution of the bicategory\n of enriched categories.\n\n Contents\n 1. Duality involution on enriched categories\n\n *****************************************************************)\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Isos.\nRequire Import UniMath.CategoryTheory.Core.Univalence.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.Core.NaturalTransformations.\nRequire Import UniMath.CategoryTheory.opp_precat.\nRequire Import UniMath.CategoryTheory.OppositeCategory.Core.\nRequire Import UniMath.CategoryTheory.Monoidal.Categories.\nRequire Import UniMath.CategoryTheory.Monoidal.Structure.Symmetric.\nRequire Import UniMath.CategoryTheory.EnrichedCats.Enrichment.\nRequire Import UniMath.CategoryTheory.EnrichedCats.EnrichmentFunctor.\nRequire Import UniMath.CategoryTheory.EnrichedCats.EnrichmentTransformation.\nRequire Import UniMath.CategoryTheory.EnrichedCats.Examples.OppositeEnriched.\nRequire Import UniMath.Bicategories.Core.Bicat. Import Bicat.Notations.\nRequire Import UniMath.Bicategories.Core.Invertible_2cells.\nRequire Import UniMath.Bicategories.Core.Univalence.\nRequire Import UniMath.Bicategories.Core.Examples.OpCellBicat.\nRequire Import UniMath.Bicategories.Core.Examples.BicatOfUnivCats.\nRequire Import UniMath.Bicategories.DisplayedBicats.DispBicat.\nRequire Import UniMath.Bicategories.DisplayedBicats.Examples.EnrichedCats.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.PseudoFunctorBicat.\nRequire Import UniMath.Bicategories.PseudoFunctors.PseudoFunctor.\nImport PseudoFunctor.Notations.\nRequire Import UniMath.Bicategories.PseudoFunctors.Examples.Identity.\nRequire Import UniMath.Bicategories.PseudoFunctors.Examples.Composition.\nRequire Import UniMath.Bicategories.PseudoFunctors.Examples.Op2OfPseudoFunctor.\nRequire Import UniMath.Bicategories.PseudoFunctors.Examples.OpFunctorEnriched.\nRequire Import UniMath.Bicategories.Transformations.PseudoTransformation.\nRequire Import UniMath.Bicategories.Modifications.Modification.\nRequire Import UniMath.Bicategories.OtherStructure.DualityInvolution.\n\nLocal Open Scope cat.\n\n(**\n 1. Duality involution on enriched categories\n *)\nSection DualityInvolutionEnriched.\n  Context (V : sym_monoidal_cat).\n\n  Definition bicat_of_enriched_cat_duality_unit_data\n    : pstrans_data\n        (id_psfunctor (bicat_of_enriched_cats V))\n        (comp_psfunctor\n           (op_enriched_psfunctor V)\n           (op2_psfunctor (op_enriched_psfunctor V))).\n  Proof.\n    use make_pstrans_data.\n    - cbn.\n      exact (λ E, functor_identity _ ,, op_enriched_unit V (pr2 E)).\n    - intros E₁ E₂ F.\n      use make_invertible_2cell.\n      + exact (op_unit_nat_trans (pr1 F)\n               ,,\n               op_enriched_unit_naturality V (pr2 F)).\n      + use make_is_invertible_2cell.\n        * exact (nat_z_iso_to_trans_inv (op_unit_nat_z_iso (pr1 F))\n                 ,,\n                 op_enriched_unit_naturality_inv V (pr2 F)).\n        * abstract\n            (use eq_2cell_enriched ;\n             intro x ; cbn ;\n             apply id_left).\n        * abstract\n            (use eq_2cell_enriched ;\n             intro x ; cbn ;\n             apply id_left).\n  Defined.\n\n  Proposition bicat_of_enriched_cat_duality_unit_is_pstrans\n    : is_pstrans bicat_of_enriched_cat_duality_unit_data.\n  Proof.\n    repeat split.\n    - intros E₁ E₂ F G α.\n      use eq_2cell_enriched.\n      intro x ; cbn.\n      rewrite id_left, id_right.\n      apply idpath.\n    - intros E.\n      use eq_2cell_enriched.\n      intros x ; cbn.\n      apply idpath.\n    - intros E₁ E₂ E₃ F G.\n      use eq_2cell_enriched.\n      intros x ; cbn.\n      rewrite functor_id.\n      rewrite !id_left.\n      apply idpath.\n  Qed.\n\n  Definition bicat_of_enriched_cat_duality_unit\n    : pstrans\n        (id_psfunctor (bicat_of_enriched_cats V))\n        (comp_psfunctor\n           (op_enriched_psfunctor V)\n           (op2_psfunctor (op_enriched_psfunctor V))).\n  Proof.\n    use make_pstrans.\n    - exact bicat_of_enriched_cat_duality_unit_data.\n    - exact bicat_of_enriched_cat_duality_unit_is_pstrans.\n  Defined.\n\n  Definition bicat_of_enriched_cat_duality_unit_inv_data\n    : pstrans_data\n        (comp_psfunctor\n           (op_enriched_psfunctor V)\n           (op2_psfunctor (op_enriched_psfunctor V)))\n        (id_psfunctor (bicat_of_enriched_cats V)).\n  Proof.\n    use make_pstrans_data.\n    - cbn.\n      exact (λ E, functor_identity _ ,, op_enriched_unit_inv V (pr2 E)).\n    - intros E₁ E₂ F.\n      use make_invertible_2cell.\n      + exact (op_unit_inv_nat_trans (pr1 F)\n               ,,\n               op_enriched_unit_inv_naturality V (pr2 F)).\n      + use make_is_invertible_2cell.\n        * exact (nat_z_iso_to_trans_inv (op_unit_inv_nat_z_iso (pr1 F))\n                 ,,\n                 op_enriched_unit_inv_naturality_inv V (pr2 F)).\n        * abstract\n            (use eq_2cell_enriched ;\n             intro x ; cbn ;\n             apply id_left).\n        * abstract\n            (use eq_2cell_enriched ;\n             intro x ; cbn ;\n             apply id_left).\n  Defined.\n\n  Proposition bicat_of_enriched_cat_duality_unit_inv_is_pstrans\n    : is_pstrans bicat_of_enriched_cat_duality_unit_inv_data.\n  Proof.\n    repeat split.\n    - intros E₁ E₂ F G α ; simpl.\n      use eq_2cell_enriched.\n      intro x ; cbn.\n      rewrite id_left, id_right.\n      apply idpath.\n    - intros E ; simpl.\n      use eq_2cell_enriched.\n      intros x ; cbn.\n      rewrite !id_left.\n      apply idpath.\n    - intros E₁ E₂ E₃ F G ; simpl.\n      use eq_2cell_enriched.\n      intros x ; cbn.\n      rewrite !id_left, !id_right.\n      exact (!(functor_id _ _)).\n  Admitted.\n\n  Definition bicat_of_enriched_cat_duality_unit_inv\n    : pstrans\n        (comp_psfunctor\n           (op_enriched_psfunctor V)\n           (op2_psfunctor (op_enriched_psfunctor V)))\n        (id_psfunctor (bicat_of_enriched_cats V)).\n  Proof.\n    use make_pstrans.\n    - exact bicat_of_enriched_cat_duality_unit_inv_data.\n    - exact bicat_of_enriched_cat_duality_unit_inv_is_pstrans.\n  Defined.\n\n  Definition bicat_of_enriched_cat_duality_unit_unit_inv_data\n    : invertible_modification_data\n        (id₁ (id_psfunctor (bicat_of_enriched_cats V)))\n        (bicat_of_enriched_cat_duality_unit · bicat_of_enriched_cat_duality_unit_inv).\n  Proof.\n    intros E.\n    use make_invertible_2cell.\n    - exact (op_unit_unit_inv_nat_trans _ ,, op_enriched_unit_unit_inv V (pr2 E)).\n    - use make_is_invertible_2cell.\n      + exact (nat_z_iso_to_trans_inv (op_unit_unit_inv_nat_z_iso _)\n               ,,\n               op_enriched_unit_unit_inv_inv V (pr2 E)).\n      + abstract\n          (use eq_2cell_enriched ;\n           intros x ; cbn ;\n           apply id_left).\n      + abstract\n          (use eq_2cell_enriched ;\n           intros x ; cbn ;\n           apply id_left).\n  Defined.\n\n  Proposition bicat_of_enriched_cat_duality_unit_unit_inv_laws\n    : is_modification bicat_of_enriched_cat_duality_unit_unit_inv_data.\n  Proof.\n    intros E₁ E₂ F.\n    use eq_2cell_enriched.\n    intros x ; cbn.\n    rewrite (functor_id (pr1 F)), !id_left.\n    apply idpath.\n  Qed.\n\n  Definition bicat_of_enriched_cat_duality_unit_unit_inv\n    : invertible_modification\n        (id₁ (id_psfunctor (bicat_of_enriched_cats V)))\n        (bicat_of_enriched_cat_duality_unit · bicat_of_enriched_cat_duality_unit_inv).\n  Proof.\n    use make_invertible_modification.\n    - exact bicat_of_enriched_cat_duality_unit_unit_inv_data.\n    - exact bicat_of_enriched_cat_duality_unit_unit_inv_laws.\n  Defined.\n\n  Definition bicat_of_enriched_cat_duality_unit_inv_unit_data\n    : invertible_modification_data\n        (bicat_of_enriched_cat_duality_unit_inv · bicat_of_enriched_cat_duality_unit)\n        (id₁ _).\n  Proof.\n    intros E.\n    use make_invertible_2cell.\n    - exact (op_unit_inv_unit_nat_trans _\n             ,,\n             op_enriched_unit_inv_unit V (pr2 E)).\n    - use make_is_invertible_2cell.\n      + exact (nat_z_iso_to_trans_inv (op_unit_inv_unit_nat_z_iso _)\n               ,,\n               op_enriched_unit_inv_unit_inv V (pr2 E)).\n      + abstract\n          (use eq_2cell_enriched ;\n           intros x ; cbn ;\n           apply id_left).\n      + abstract\n          (use eq_2cell_enriched ;\n           intros x ; cbn ;\n           apply id_left).\n  Defined.\n\n  Proposition bicat_of_enriched_cat_duality_unit_inv_unit_laws\n    : is_modification bicat_of_enriched_cat_duality_unit_inv_unit_data.\n  Proof.\n    intros E₁ E₂ F.\n    use eq_2cell_enriched.\n    intro x ; cbn.\n    rewrite (functor_id (pr1 F)), !id_left.\n    apply idpath.\n  Qed.\n\n  Definition bicat_of_enriched_cat_duality_unit_inv_unit\n    : invertible_modification\n        (bicat_of_enriched_cat_duality_unit_inv · bicat_of_enriched_cat_duality_unit)\n        (id₁ _).\n  Proof.\n    use make_invertible_modification.\n    - exact bicat_of_enriched_cat_duality_unit_inv_unit_data.\n    - exact bicat_of_enriched_cat_duality_unit_inv_unit_laws.\n  Defined.\n\n  Definition bicat_of_enriched_cat_duality_triangle\n             (E : op2_bicat (bicat_of_enriched_cats V))\n    : invertible_2cell\n        (bicat_of_enriched_cat_duality_unit (op_enriched_psfunctor V E))\n        (# (op_enriched_psfunctor V) (bicat_of_enriched_cat_duality_unit E)).\n  Proof.\n    use make_invertible_2cell.\n    - exact (op_triangle_nat_trans _ ,, op_enriched_triangle V (pr2 E)).\n    - use make_is_invertible_2cell.\n      + exact (nat_z_iso_to_trans_inv (op_triangle_nat_z_iso _)\n               ,,\n               op_enriched_triangle_inv V (pr2 E)).\n      + abstract\n          (use eq_2cell_enriched ;\n           intros x ; cbn ;\n           apply id_left).\n      + abstract\n          (use eq_2cell_enriched ;\n           intros x ; cbn ;\n           apply id_left).\n  Defined.\n\n  Definition bicat_of_enriched_cat_duality_data\n    : duality_involution_data (op_enriched_psfunctor V).\n  Proof.\n    use make_duality_involution_data.\n    - exact bicat_of_enriched_cat_duality_unit.\n    - exact bicat_of_enriched_cat_duality_unit_inv.\n    - exact bicat_of_enriched_cat_duality_unit_unit_inv.\n    - exact bicat_of_enriched_cat_duality_unit_inv_unit.\n    - exact bicat_of_enriched_cat_duality_triangle.\n  Defined.\n\n  Definition bicat_of_enriched_cat_duality_laws\n    : duality_involution_laws bicat_of_enriched_cat_duality_data.\n  Proof.\n    split.\n    - intro E.\n      use eq_2cell_enriched.\n      intro x ; cbn.\n      apply id_left.\n    - intros E₁ E₂ F.\n      use eq_2cell_enriched.\n      intro x ; cbn.\n      rewrite !id_left.\n      exact (!(functor_id _ _)).\n  Qed.\n\n  Definition bicat_of_enriched_cat_duality\n    : duality_involution (op_enriched_psfunctor V)\n    := bicat_of_enriched_cat_duality_data ,, bicat_of_enriched_cat_duality_laws.\nEnd DualityInvolutionEnriched.\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/OtherStructure/Examples/StructureBicatOfEnrichedCats.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7718435083355186, "lm_q2_score": 0.36296919173767833, "lm_q1q2_score": 0.2801554143685172}}
{"text": "Require Import Fiat.Common\n        Fiat.ADT.ADTSig\n        Fiat.ADT.Core\n        Fiat.ADT.ADTHide\n        Fiat.ADTRefinement.Core\n        Fiat.ADTRefinement.SetoidMorphisms.\n\nLemma RefineHideADT\n      extSig'\n      oldMethodIndex\n      (MethodMap : oldMethodIndex -> MethodIndex extSig')\n      oldADT\n: forall newADT newADT',\n    refineADT newADT newADT'\n    -> arrow (refineADT oldADT (HideADT MethodMap newADT))\n             (refineADT oldADT (HideADT MethodMap newADT')).\nProof.\n  unfold arrow.\n  intros ? ? [AbsR ?] [AbsR' ?].\n  destruct_head ADT.\n  exists (fun r_o r_n => exists r_n', AbsR' r_o r_n' /\\ AbsR r_n' r_n);\n    simpl; intros.\n  - eauto using refineMethod_trans.\nQed.\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/ADTRefinement/Refinements/RefineHideADT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.280143708943101}}
{"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 PCUICTyping PCUICCumulativity\n  PCUICClosed PCUICReduction\n  PCUICSigmaCalculus PCUICRenameDef PCUICRenameConv PCUICOnFreeVars\n  PCUICClosedConv PCUICClosedTyp.\n\nRequire Import ssreflect ssrbool.\nFrom Equations Require Import Equations.\n\nImplicit Types cf : checker_flags.\n\n(** * Weakening lemmas for typing derivations.\n\n  [weakening_*] proves weakening of typing, reduction etc... w.r.t. the *local*\n  environment. *)\n\nSet Default Goal Selector \"!\".\nGeneralizable Variables Σ Γ t T.\n\n(* FIXME inefficiency in equations: using a very slow \"pattern_sigma\" to simplify an ws_cumul_pb between sigma types *)\nLtac Equations.CoreTactics.destruct_tele_eq H ::= noconf H.\n\nLemma closed_ctx_lift n k ctx : closed_ctx ctx -> lift_context n k ctx = ctx.\nProof.\n  induction ctx in n, k |- *; auto.\n  rewrite closedn_ctx_cons lift_context_snoc0 /snoc.\n  move/andb_and => /= [Hctx Hd].\n  rewrite IHctx // lift_decl_closed //. now apply: closed_decl_upwards.\nQed.\n\nLemma weaken_nth_error_ge {Γ Γ' v Γ''} : #|Γ'| <= v ->\n  nth_error (Γ ,,, Γ'' ,,, lift_context #|Γ''| 0 Γ') (#|Γ''| + v) =\n  nth_error (Γ ,,, Γ') v.\nProof.\n  intros Hv.\n  rewrite -> !nth_error_app_context_ge, ?lift_context_length.\n  - f_equal. lia.\n  - auto.\n  - rewrite lift_context_length. lia.\n  - rewrite lift_context_length. lia.\nQed.\n\nLemma weaken_nth_error_lt {Γ Γ' Γ'' v} : v < #|Γ'| ->\n  nth_error (Γ ,,, Γ'' ,,, lift_context #|Γ''| 0 Γ') v =\n  option_map (lift_decl #|Γ''| (#|Γ'| - S v)) (nth_error (Γ ,,, Γ') v).\nProof.\n  simpl. intros Hv.\n  rewrite -> !nth_error_app_context_lt.\n  - rewrite nth_error_lift_context_eq.\n    do 2 f_equal. lia.\n  - lia.\n  - now rewrite lift_context_length.\nQed.\n\nLemma lift_context_lift_context n k Γ : lift_context n 0 (lift_context k 0 Γ) =\n  lift_context (n + k) 0 Γ.\nProof. rewrite !lift_context_alt.\n  rewrite mapi_compose.\n  apply mapi_ext.\n  intros n' x.\n  rewrite /lift_decl compose_map_decl.\n  apply map_decl_ext => y.\n  rewrite mapi_length; autorewrite with  len.\n  rewrite simpl_lift //; lia.\nQed.\n\nLemma weakening_renaming P Γ Γ' Γ'' :\n  urenaming P (Γ ,,, Γ'' ,,, lift_context #|Γ''| 0 Γ') (Γ ,,, Γ')\n    (lift_renaming #|Γ''| #|Γ'|).\nProof.\n  intros i d hpi hnth.\n  rewrite /lift_renaming.\n  destruct (Nat.leb #|Γ'| i) eqn:leb; [apply Nat.leb_le in leb|eapply Nat.leb_nle in leb].\n  - rewrite weaken_nth_error_ge //.\n    exists d; split; auto.\n    split; auto.\n    split.\n    * apply rename_ext => k. rewrite /rshiftk /lift_renaming.\n      repeat nat_compare_specs.\n    * destruct (decl_body d) => /= //.\n      f_equal. apply rename_ext => k.\n      rewrite /rshiftk; now nat_compare_specs.\n  - rewrite weaken_nth_error_lt; try lia.\n    rewrite hnth /=. eexists. split; [eauto|].\n    simpl. rewrite !lift_rename !rename_compose /lift_renaming /rshiftk /=.\n    repeat split.\n    * apply rename_ext => k. now repeat nat_compare_specs.\n    * destruct (decl_body d) => /= //. f_equal.\n      rewrite lift_rename rename_compose /lift_renaming.\n      apply rename_ext => k. simpl. now repeat nat_compare_specs.\nQed.\n\n(* Variant lookup_decl_spec Γ Δ i : option context_decl -> Type :=\n| lookup_head d : i < #|Δ| ->\n  nth_error Δ i = Some d -> lookup_decl_spec Γ Δ i (Some d)\n| lookup_tail d : #|Δ| <= i < #|Γ| + #|Δ| ->\n  nth_error Γ (i - #|Δ|) = Some d ->\n  lookup_decl_spec Γ Δ i (Some d)\n| lookup_above : #|Γ| + #|Δ| <= i -> lookup_decl_spec Γ Δ i None.\n\nLemma lookup_declP Γ Δ i : lookup_decl_spec Γ Δ i (nth_error (Γ ,,, Δ) i).\nProof.\n  destruct (Nat.ltb i #|Δ|) eqn:ltb.\n  - apply Nat.ltb_lt in ltb.\n    rewrite nth_error_app_lt //.\n    destruct nth_error eqn:hnth.\n    * constructor; auto.\n    * apply nth_error_None in hnth. lia.\n  - apply Nat.ltb_nlt in ltb.\n    rewrite nth_error_app_ge; try lia.\n    destruct nth_error eqn:hnth.\n    * constructor 2; auto.\n      apply nth_error_Some_length in hnth.\n      split; lia.\n    * constructor. eapply nth_error_None in hnth. lia.\nQed. *)\n\n#[global]\nHint Rewrite rename_context_length : len.\n\n(* Variant shiftn_spec k f i : nat -> Type :=\n| shiftn_below : i < k -> shiftn_spec k f i i\n| shiftn_above : k <= i -> shiftn_spec k f i (k + f (i - k)).\n\nLemma shiftn_P k f i : shiftn_spec k f i (shiftn k f i).\nProof.\n  rewrite /shiftn.\n  destruct (Nat.ltb i k) eqn:ltb.\n  * apply Nat.ltb_lt in ltb.\n    now constructor.\n  * apply Nat.ltb_nlt in ltb.\n    constructor. lia.\nQed. *)\n\nLemma rename_context_lift_context n k Γ :\n  rename_context (lift_renaming n k) Γ = lift_context n k Γ.\nProof.\n  rewrite /rename_context /lift_context.\n  apply fold_context_k_ext => i t.\n  now rewrite lift_rename shiftn_lift_renaming.\nQed.\n\n\nLemma smash_context_lift Δ k n Γ :\n  smash_context (lift_context n (k + #|Γ|) Δ) (lift_context n k Γ) =\n  lift_context n k (smash_context Δ Γ).\nProof.\n  revert Δ. induction Γ as [|[na [b|] ty]]; intros Δ; simpl; auto.\n  - now rewrite Nat.add_0_r.\n  - rewrite -IHΓ.\n    rewrite lift_context_snoc /=. f_equal.\n    rewrite !subst_context_alt !lift_context_alt !mapi_compose.\n    apply mapi_ext=> n' x.\n    destruct x as [na' [b'|] ty']; simpl.\n    * rewrite !mapi_length /lift_decl /subst_decl /= /map_decl /=; f_equal.\n      + f_equal. rewrite Nat.add_0_r distr_lift_subst_rec /=.\n        lia_f_equal.\n      + rewrite Nat.add_0_r distr_lift_subst_rec; simpl. lia_f_equal.\n    * rewrite !mapi_length /lift_decl /subst_decl /= /map_decl /=; f_equal.\n      rewrite Nat.add_0_r distr_lift_subst_rec /=.\n      repeat (lia || f_equal).\n  - rewrite -IHΓ.\n    rewrite lift_context_snoc /= // /lift_decl /subst_decl /map_decl /=.\n    f_equal.\n    rewrite lift_context_app. simpl.\n    rewrite /app_context; lia_f_equal.\n    rewrite /lift_context // /fold_context_k /= /map_decl /=.\n    now lia_f_equal.\nQed.\n\n(* Lemma decompose_app_rec_lift n k t l :\n  let (f, a) := decompose_app_rec t l in\n  decompose_app_rec (lift n k t) (map (lift n k) l)  = (lift n k f, map (lift n k) a).\nProof.\n  induction t in k, l |- *; simpl; auto with pcuic.\n  - specialize (IHt1 k (t2 :: l)).\n    destruct decompose_app_rec. now rewrite IHt1.\nQed.\n\nLemma decompose_app_lift n k t f a :\n  decompose_app t = (f, a) -> decompose_app (lift n k t) = (lift n k f, map (lift n k) a).\nProof.\n  generalize (decompose_app_rec_lift n k t []).\n  unfold decompose_app. destruct decompose_app_rec.\n  now move=> Heq [= <- <-].\nQed.\n#[global]\nHint Rewrite decompose_app_lift using auto : lift.\n\nLemma lift_is_constructor:\n  forall (args : list term) (narg : nat) n k,\n    is_constructor narg args = true -> is_constructor narg (map (lift n k) args) = true.\nProof.\n  intros args narg.\n  unfold is_constructor; intros.\n  rewrite nth_error_map. destruct nth_error; try discriminate. simpl.\n  unfold isConstruct_app in *. destruct decompose_app eqn:Heq.\n  eapply decompose_app_lift in Heq as ->.\n  destruct t0; try discriminate || reflexivity.\nQed.\n#[export] Hint Resolve lift_is_constructor : core.\n\n#[global]\nHint Rewrite subst_instance_lift lift_mkApps distr_lift_subst distr_lift_subst10 : lift. *)\n\nDefinition lift_mutual_inductive_body n k m :=\n  map_mutual_inductive_body (fun k' => lift n (k' + k)) m.\n\nLemma lift_fix_context:\n  forall (mfix : list (def term)) (n k : nat),\n    fix_context (map (map_def (lift n k) (lift n (#|mfix| + k))) mfix) = lift_context n k (fix_context mfix).\nProof.\n  intros mfix n k. unfold fix_context.\n  rewrite PCUICLiftSubst.map_vass_map_def rev_mapi.\n  fold (fix_context mfix).\n  rewrite (lift_context_alt n k (fix_context mfix)).\n  unfold lift_decl. now rewrite mapi_length fix_context_length.\nQed.\n\n#[global]\nHint Rewrite <- lift_fix_context : lift.\n\nLemma lift_it_mkProd_or_LetIn n k ctx t :\n  lift n k (it_mkProd_or_LetIn ctx t) =\n  it_mkProd_or_LetIn (lift_context n k ctx) (lift n (length ctx + k) t).\nProof.\n  induction ctx in n, k, t |- *; simpl; try congruence.\n  pose (lift_context_snoc n k ctx a). unfold snoc in e. rewrite -> e. clear e.\n  simpl. rewrite -> IHctx.\n  pose (lift_context_snoc n k ctx a).\n  now destruct a as [na [b|] ty].\nQed.\n#[global]\nHint Rewrite lift_it_mkProd_or_LetIn : lift.\n\nLemma to_extended_list_map_lift:\n  forall (n k : nat) (c : context), to_extended_list c = map (lift n (#|c| + k)) (to_extended_list c).\nProof.\n  intros n k c.\n  pose proof (to_extended_list_lift_above c). unf_term.\n  symmetry. solve_all.\n  destruct H as [x' [-> Hx]]. simpl.\n  destruct (leb_spec_Set (#|c| + k) x').\n  - f_equal. lia.\n  - reflexivity.\nQed.\n\nLemma weakening_red1 `{cf:checker_flags} {Σ} Γ Γ' Γ'' M N :\n  wf Σ ->\n  on_free_vars xpredT M ->\n  red1 Σ (Γ ,,, Γ') M N ->\n  red1 Σ (Γ ,,, Γ'' ,,, lift_context #|Γ''| 0 Γ') (lift #|Γ''| #|Γ'| M) (lift #|Γ''| #|Γ'| N).\nProof.\n  intros.\n  rewrite !lift_rename.\n  eapply red1_rename; eauto.\n  eapply weakening_renaming.\nQed.\n\nLemma weakening_red `{cf:checker_flags} {Σ:global_env_ext} {wfΣ : wf Σ} {P Γ Γ' Γ'' M N} :\n  on_ctx_free_vars P (Γ ,,, Γ') ->\n  on_free_vars P M ->\n  red Σ (Γ ,,, Γ') M N ->\n  red Σ (Γ ,,, Γ'' ,,, lift_context #|Γ''| 0 Γ') (lift #|Γ''| #|Γ'| M) (lift #|Γ''| #|Γ'| N).\nProof.\n  intros.\n  rewrite !lift_rename.\n  eapply red_rename; eauto.\n  eapply weakening_renaming.\nQed.\n\nLemma weakening_red' `{cf:checker_flags} {Σ:global_env_ext} {wfΣ : wf Σ} {P Γ Γ' Γ'' M N} :\n  on_ctx_free_vars P (Γ ,,, Γ') ->\n  on_free_vars P M ->\n  red Σ (Γ ,,, Γ') M N ->\n  red Σ (Γ ,,, Γ'' ,,, lift_context #|Γ''| 0 Γ') (lift #|Γ''| #|Γ'| M) (lift #|Γ''| #|Γ'| N).\nProof.\n  now eapply weakening_red.\nQed.\n\nLemma weakening_red_0 {cf} {Σ:global_env_ext} {wfΣ : wf Σ} {P Γ Γ' M N n} :\n  n = #|Γ'| ->\n  on_ctx_free_vars P Γ ->\n  on_free_vars P M ->\n  red Σ Γ M N ->\n  red Σ (Γ ,,, Γ') (lift0 n M) (lift0 n N).\nProof. move=> -> onctx ont; eapply (weakening_red (Γ':=[])); tea. Qed.\n\n(* TODO MOVE *)\n(* Lemma fix_context_alt_length :\n  forall l,\n    #|fix_context_alt l| = #|l|.\nProof.\n  intro l.\n  unfold fix_context_alt.\n  rewrite List.rev_length.\n  rewrite mapi_length. reflexivity.\nQed. *)\n\nLemma weakening_cumul `{CF:checker_flags} {Σ Γ Γ' Γ'' M N} :\n  wf Σ.1 ->\n  on_free_vars xpredT M ->\n  on_free_vars xpredT N ->\n  on_ctx_free_vars xpredT (Γ ,,, Γ') ->\n  Σ ;;; Γ ,,, Γ' |- M <= N ->\n  Σ ;;; Γ ,,, Γ'' ,,, lift_context #|Γ''| 0 Γ' |- lift #|Γ''| #|Γ'| M <= lift #|Γ''| #|Γ'| N.\nProof.\n  intros.\n  rewrite !lift_rename -rename_context_lift_context.\n  eapply cumul_renameP ; tea.\n  rewrite rename_context_lift_context.\n  now eapply weakening_renaming.\nQed.\n\n(* Lemma destInd_lift n k t : destInd (lift n k t) = destInd t.\nProof.\n  destruct t; simpl; try congruence.\nQed. *)\n\nLemma weakening_conv `{cf:checker_flags} :\n  forall Σ Γ Γ' Γ'' M N,\n    wf Σ.1 ->\n    on_free_vars xpredT M ->\n    on_free_vars xpredT N ->\n    on_ctx_free_vars xpredT (Γ ,,, Γ') ->\n    Σ ;;; Γ ,,, Γ' |- M = N ->\n    Σ ;;; Γ ,,, Γ'' ,,, lift_context #|Γ''| 0 Γ' |- lift #|Γ''| #|Γ'| M = lift #|Γ''| #|Γ'| N.\nProof.\n  intros.\n  rewrite !lift_rename -rename_context_lift_context.\n  eapply conv_renameP ; tea.\n  rewrite rename_context_lift_context.\n  now eapply weakening_renaming.\nQed.\n\nLemma isType_on_free_vars {cf} {Σ : global_env_ext} {wfΣ : wf Σ} {Γ T} :\n  isType Σ Γ T -> on_free_vars xpredT T.\nProof.\n  intros [s Hs].\n  eapply subject_closed in Hs.\n  rewrite closedP_on_free_vars in Hs.\n  eapply on_free_vars_impl; tea => //.\nQed.\n\nLemma isType_on_ctx_free_vars {cf} {Σ : global_env_ext} {wfΣ : wf Σ} {Γ T} :\n  isType Σ Γ T -> on_ctx_free_vars xpredT Γ.\nProof.\n  intros [s Hs].\n  eapply typing_wf_local in Hs.\n  eapply closed_wf_local in Hs; tea.\n  eapply (closed_ctx_on_free_vars xpredT) in Hs.\n  now eapply on_free_vars_ctx_on_ctx_free_vars_xpredT.\nQed.\n\nLemma weakening_conv_wt `{cf:checker_flags} {Σ : global_env_ext} {wfΣ : wf Σ} {Γ Γ' Γ'' M N} :\n  isType Σ (Γ ,,, Γ') M -> isType Σ (Γ ,,, Γ') N ->\n  Σ ;;; Γ ,,, Γ' |- M = N ->\n  Σ ;;; Γ ,,, Γ'' ,,, lift_context #|Γ''| 0 Γ' |- lift #|Γ''| #|Γ'| M = lift #|Γ''| #|Γ'| N.\nProof.\n  intros onM onN.\n  eapply weakening_conv; tea.\n  1-2:now eapply isType_on_free_vars.\n  now eapply isType_on_ctx_free_vars in onM.\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/Conversion/PCUICWeakeningConv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.280143708943101}}
{"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.\nRequire Export While_stuff.\nRequire Export SD.\nRequire Import Classical.\n\nSet Implicit Arguments.\n\n Hint Rewrite Uabs_diff_compat_eq.  \n Hint Resolve Oeq_sym neq_sym iff_refl.\n\n(********************* MOVE THIS SOMEWHERE ELSE *********************)\n(********************************************************************)\n\n Lemma mu_stable_plus_range: forall (A:Type) (d:Distr A) R,\n   range R d ->\n   forall f g,\n   (forall a, R a ->  g a <= [1-] f a) ->\n   mu d (fplus f g) == mu d f + mu d g.\n Proof.\n  intros; split.\n    auto.\n    transitivity (mu d (fminus (fplus f g) g) + mu d g).\n      Usimpl.\n      apply range_le with (1:=H).\n      intros a Ha; unfold fminus, fplus.\n      rewrite Uplus_minus_simpl_right; auto.\n      rewrite <-(@mu_stable_plus _ d _ _); unfold fminus, fplus.\n        apply range_le with (1:=H).\n        intros a _; rewrite Uminus_plus_simpl; auto.\n        unfold fplusok, finv; refine (ford_le_intro _); intro a.\n        rewrite <-Uminus_one_left.\n        apply Uminus_le_compat_left; trivial.\n Qed.\n\n\n Lemma Uplus_le_minus: forall a b c,\n  a - b <= c -> a <= c + b.\n Proof.\n   intros.\n   apply (Ule_total a b); [auto|intro H'|intro H'].\n     rewrite (Uminus_plus_le a b), (Uminus_le_zero _ _ H'); auto.\n     apply (Uminus_le_perm_left _ _ _ H' H).\n Qed.\n\n\n Lemma Uabs_diff_restr: forall (A:Type) (d:Distr A)  f R,\n  Uabs_diff (mu d f) (mu d (restr R f)) <= mu d (restr (negP R) f).\n Proof.\n  intros.\n  rewrite <-(Uplus_zero_right (mu d (restr R f))), \n    (mu_restr_split d R f), Uabs_diff_plus, Uabs_diff_compat_eq, Uplus_zero_left.\n  unfold Uabs_diff; rewrite (Uminus_le_zero 0 _ (Upos _)); auto. \n Qed.\n\n\n Lemma is_Discrete_eq_compat: forall (A:Type) (d1 d2:Distr A),\n   d2 == d1 ->\n   is_Discrete d2 ->\n   is_Discrete d1.\n Proof.\n  intros A d1 d3 Hd [p H].\n  apply mkDiscr with p.\n  unfold Discrete in *.\n  refine (range_stable_eq Hd H).\n Qed.\n\n\n Lemma cover_neg: forall (A:Type) (P:set A) (caracP: MF A),\n  cover P caracP ->\n  cover (fun a => ~ P a) (finv caracP).\n Proof.\n  intros A P caracP H a.\n  split; intro Ha; unfold finv.\n    rewrite (cover_eq_zero _ H Ha); auto.\n    rewrite (cover_eq_one _ H (NNPP _ Ha)); auto.\n Qed.\n\n Lemma cover_eq_prod: forall (A B:Type) (P: A -> MF A) (Q: B -> MF B),\n  (forall a, cover (eq a) (P a)) ->\n  (forall b, cover (eq b) (Q b)) ->\n  forall ab:A*B, \n    cover (eq ab) (fun ab' => P (fst ab) (fst ab') * Q (snd ab) (snd ab')).\n Proof.\n  intros A B P Q HP HQ ab.\n  apply cover_equiv_stable with (inter (fun ab':A*B => eq (fst ab') (fst ab))\n    (fun ab':A*B => eq (snd ab') (snd ab))).\n    unfold Sets.equiv, inter; split.\n      intros [H1 H2].\n      destruct ab; destruct x; simpl in *; rewrite H1, H2; trivial.\n      intros H1.\n      destruct ab; destruct x; simpl; injection H1; auto.\n    apply cover_inter_mult.\n      intros ab'; split; intros.\n        apply (cover_eq_one _ (HP (fst ab)) (eq_sym H)).\n        apply (cover_eq_zero _ (HP (fst ab)) (not_eq_sym H)).\n      intros ab'; split; intros.\n        apply (cover_eq_one _ (HQ (snd ab)) (eq_sym H)).\n        apply (cover_eq_zero _ (HQ (snd ab)) (not_eq_sym H)).\n Qed.\n\n  \n\n Definition drange A (P:A->Prop) (d: Distr A) :=\n  forall f, (0 == mu d f) -> (forall x, P x -> 0 == f x).\n\n Definition srange A (P:A->Prop) (d: Distr A) := range P d /\\ drange P d.\n\n(*\n Lemma drange_false: forall (A:Type) (d: Distr A),\n  drange (fun _ => False) d.\n Proof.\n   intros A d f Hf a H; tauto.\n Qed.\n\n\n Lemma drange_Mlet: forall (A B:Type) (P:A->Prop) (Q:B ->Prop) \n  (d: Distr A) (F: A -> Distr B),\n  (exists a, P a) -> \n  drange P d ->\n  (forall x, P x -> drange Q (F x)) -> \n  drange Q (Mlet d F).\n Proof.\n  intros A B P Q d F [a Ha] Hdran HQ.\n  intros f Hdf b Hb; simpl in *.\n  refine (HQ a Ha _ _ _ Hb).\n  apply (Hdran _ Hdf _ Ha).\n Qed.\n\n\n Lemma srange_Mlet: forall (A B : Type) (P : A -> Prop) (Q : B -> Prop) \n  (d : Distr A) (F : A -> Distr B),\n  (exists a, P a) ->\n  srange P d ->\n  (forall x : A, P x -> srange Q (F x)) -> \n  srange Q (Mlet d F).\n Proof.\n  unfold srange; intros A B P Q d F HP [Hran Hdran] H; split.\n    apply (range_Mlet _ Hran).\n    intros a Ha; apply (proj1 (H _ Ha)).\n\n    refine (drange_Mlet _ HP Hdran _). \n    intros a Ha; apply (proj2 (H a Ha)).\n Qed.\n*)\n\n Lemma drange_range:forall (A:Type) (P Q:A->Prop) (d: Distr A) (carP: MF A),\n  (cover P carP) ->\n  range P d ->\n  drange Q d ->\n  (forall a, Q a -> P a).\n Proof.\n  unfold drange, range; intros.\n  assert  (0 == mu d (finv carP)) by\n    (apply H0; symmetry; eapply (cover_eq_zero _ (cover_neg H)); auto).\n  apply NNPP.\n  apply (cover_eq_zero_elim _ (cover_neg H) (Oeq_sym (H1 _  H3 _ H2))).\n Qed.\n\n\n Definition d_inv (A B: Type) (d:distr (A*B)) := Mlet d (fun p => Munit (snd p, fst p)).\n\n Lemma d_inv_fst: forall (A B:Type) (d:distr (A*B)) g, \n   mu d (fun ab => g (snd ab)) == mu (d_inv d) (fun ba => g (fst ba)).\n Proof. intros; trivial. Qed.\n\n Lemma d_inv_snd: forall (A B:Type) (d:distr (A*B)) f, \n   mu d (fun ab => f (fst ab)) == mu (d_inv d) (fun ba => f (snd ba)).\n Proof. intros; trivial. Qed.\n\n\n Lemma discr_ext: forall (A:Type) (d1 d2: Distr A),\n   (forall f, mu d1 f == 0 -> mu d2 f == 0) ->\n   is_Discrete d1 ->\n   is_Discrete d2.\n Proof.\n  intros A d1 d2 Hd [p Hdis1].\n  apply mkDiscr with p.\n  unfold Discrete in *.\n  intros f Hf.\n  symmetry; apply Hd. \n  symmetry; apply (Hdis1 _ Hf).\n Qed.\n\n\n\n\n\n\n(*\n Lemma foo'': forall (A:Type) (d1 d2:Distr A),\n  (forall f, 0 == mu d1 f <-> 0 == mu d2 f) ->\n  (forall R, srange R d1 <-> srange R d2).\n Proof.\n  split; intros.\n    destruct H0 as [H1 H2]; split.\n      intros f Hf; rewrite <-H; apply (H1 _ Hf).\n      intros f Hf; apply H2; rewrite H; trivial.\n    destruct H0 as [H1 H2]; split.\n      intros f Hf; rewrite H; apply (H1 _ Hf).\n      intros f Hf; apply H2; rewrite <-H; trivial.\n Qed.\n\n\n Lemma foo''': forall (A:Type) (d1 d2:Distr A) R,\n  srange R d1 -> \n  srange R d2 ->\n  (forall f, 0 == mu d1 f <-> 0 == mu d2 f).\n Proof.\n  intros A d1 d2 R [H11 H12] [H21 H22] f.\n  split; intros.\n    apply (H21 _ (H12 _ H)).\n    apply (H11 _ (H22 _ H)).\n Qed.\n*)\n\n(*\n Lemma foo': forall (A:Type) (d1 d2:Distr A),\n  (forall f, mu d1 f == 0 <-> mu d2 f == 0) ->\n  (forall R, range R d1 <-> range R d2).\n Proof.\n  intros; split.\n    intros Hrd1 f Hf.\n    symmetry; rewrite <-H; symmetry; apply (Hrd1 _ Hf).\n    intros Hrd2 f Hf.\n    symmetry; rewrite H; symmetry; apply (Hrd2 _ Hf).\n Qed.\n*)\n\n Lemma deno_unroll_while_0: forall c e b k (m:Mem.t k),\n   [[ unroll_while b c 0 ]] e m == Munit m.\n Proof.\n   unfold unroll_while; intros.\n   rewrite deno_cond.\n   case (E.eval_expr b m); apply deno_nil.\n Qed.\n\n\n Ltac My_Usimpl :=  (try Usimpl); match goal with\n    |- context [(Uabs_diff ?x ?x)] => setoid_rewrite (Uabs_diff_compat_eq x)\n end.  \n\nOpen Scope O_scope.\nOpen Scope U_scope.\n\n\n(********************************************************************)\n(* *** The classical statistical distance between two upto-bad  *** *)\n(* *****  programs can be bounded by the probability of [bad] ***** *)\n(********************************************************************)\n\n Lemma Fundamental_Lemma_GSD : forall E1 E2 c1 c2 k (m:Mem.t k) F,\n   (forall P,  Pr E1 c1 m (P[&&]negP F) == Pr E2 c2 m (P[&&]negP F)) ->\n   Pr E1 c1 m F <= Pr E2 c2 m F ->\n   GSD ([[c1]] E1 m) ([[c2]] E2 m) (Pr E2 c2 m F).\n Proof.\n  intros.\n  eapply GSD_le_SD.\n    apply mem_eqU_spec.\n    apply sem_discr.  \n    apply sem_discr.\n    unfold SD; intros.\n    apply Fundamental_Lemma.\n    apply H.\n    assumption.\n Qed.\n\n Lemma upto_bad_GSD : forall bad : Var.var T.Bool,\n       Var.is_global bad ->\n       forall (E1 E2 : env) (pi : upto_info bad E1 E2) (c1 c2 : cmd),\n       check_bad pi c1 c2 ->\n       lossless E2 c2 ->\n       forall (k : nat) (m : Mem.t k), \n       GSD ([[c1]] E1 m) ([[c2]] E2 m) (Pr E2 c2 m (EP k bad)).\n Proof.\n  intros.\n  apply Fundamental_Lemma_GSD; intros.\n  rewrite andP_comm; unfold Pr.\n  transitivity (mu (([[ c1 ]]) E1 m) (restr (negP (EP k bad)) (charfun P)));\n  [ apply mu_stable_eq; symmetry; apply restr_charfun_and | ].\n  transitivity (mu (([[ c2 ]]) E2 m) (restr (negP (EP k bad)) (charfun P)));\n  [ | apply mu_stable_eq; apply restr_charfun_and].\n  unfold check_bad in H0.\n  repeat (rewrite is_true_andb in H0; destruct H0).\n  apply upto_bad_correct with pi; trivial; destruct pi; trivial.\n  rewrite <- (negP_involutive (EP k bad)).\n  unfold Pr.\n  rewrite mu_neg_charfun, (fun d => mu_neg_charfun d (negP (EP k bad))).\n  unfold fone; unfold lossless in H1; rewrite H1.\n  fold (Pr E1 c1 m (negP (EP k bad))).\n  rewrite (upto_bad_neg_bad H pi c1 c2); unfold Pr; auto.\n Qed.\n\n(*\n Lemma foo: forall (A B: Type) (d:Distr (A * B)) R,\n  range R d -> range (fun a => exists b, R (a,b)) (Mlet d (fun ab => Munit (fst ab))).\n Proof.\n  intros.\n  apply range_Mlet with (1:=H).\n  intros (a,b) Hab; simpl.\n  apply range_Munit; eauto.\n Qed.\n*)\n    \n(********************************************************************)\n\n\nSection Lift.\n\nOpen Scope U_scope.\n\n\n\n Record elift (A B: Type) (R:A->B->Prop) (d:Distr (A * B))\n   (d1:Distr A) (d2:Distr B) (ep:U) := Build_elift\n { \n   el_dist: forall f g,\n     Uabs_diff (mu d (fun x => f (fst x))) (mu d1 f) + \n     Uabs_diff (mu d (fun x => g (snd x))) (mu d2 g) <= ep;\n   el_range: range (prodP R) d ;\n   el_supp_l: forall f,  mu d (fun ab => f (fst ab)) == 0 <-> mu d1 f == 0;\n   el_supp_r: forall g,  mu d (fun ab => g (snd ab)) == 0 <-> mu d2 g == 0\n }.\n\n\n Lemma elift_Mlet: forall (A1 A2 B1 B2: Type) (R1: A1 -> B1 -> Prop)\n  (R2: A2 -> B2 -> Prop) (d: Distr (A1 * B1)) \n  (d1: Distr A1) (d2: Distr B1) (F: A1 * B1 -> Distr (A2 * B2))\n  (F1: A1 -> Distr A2) (F2: B1 -> Distr B2) (ep ep' :U),\n  (exists carP, cover (prodP R1) carP) ->\n  (exists Rd, srange Rd d) ->\n  elift R1 d d1 d2 ep ->\n  (forall (x : A1) (y : B1), R1 x y -> elift R2 (F (x, y)) (F1 x) (F2 y) ep') ->\n  elift R2 (Mlet d F) (Mlet d1 F1) (Mlet d2 F2) (ep' + ep).\n Proof.\n  intros; constructor. \n    (* distance *)\n    intros; repeat rewrite Mlet_simpl.\n    rewrite (Uabs_diff_triangle_ineq _ (mu d1 (fun x => mu (F1 x) f))\n      (mu d (fun x => mu (F1 (fst x)) f))),\n    (Uabs_diff_triangle_ineq _ (mu d2 (fun x => mu (F2 x) g))\n      (mu d (fun x => mu (F2 (snd x)) g))).\n    match goal with |- (?A + ?B) + (?C + ?D) <= _ =>\n      rewrite <-(Uplus_assoc A), (Uplus_sym B), Uplus_assoc, (Uplus_assoc A), <-(Uplus_assoc), (Uplus_sym D)\n    end.\n    apply Uplus_le_compat.\n      apply (Ueq_orc ep' 1); [apply Ule_class | | ]; intro Hep'. \n        rewrite Hep'; apply Unit .\n        apply (Ule_diff_lt (Unit ep')) in Hep'.\n        rewrite Uabs_diff_mu_compat, Uabs_diff_mu_compat, \n          <-(mu_stable_plus_range (el_range H1)).\n        rewrite <-(mu_cte_le d ep').\n        apply (range_le (el_range H1)).\n        intros (a,b) H'; unfold fabs_diff, fcte, fplus.\n        apply (el_dist (H2 _ _ H')).\n        intros (x,y) Hxy; unfold fabs_diff.\n        apply Uplus_lt_Uinv.\n        apply Ule_lt_trans with ep'; [ | exact Hep' ].\n        rewrite Uplus_sym; apply (el_dist (H2 _ _ Hxy)).\n      apply (el_dist H1 (fun x : A1 => (mu (F1 x)) f) (fun x : B1 => (mu (F2 x)) g)).\n    (* range *)\n    apply range_Mlet with (prodP R1).\n      apply (el_range H1).\n      intros (a,b) H'.\n      apply (el_range (H2 _ _ H')).    \n    (* supp_l *)\n    destruct H as  [carP HcarP].\n    destruct H0 as [Rd [Hdran Hddran] ].\n    destruct H1 as (_, Hran, Hsupp, _).\n    split; intros; simpl in *.\n      (*  *)\n      rewrite <-Hsupp.\n      symmetry; apply Hdran.\n      intros (a1,b1) Hab; simpl.\n      destruct (H2 _ _ (drange_range HcarP Hran Hddran _ Hab)) as (_, Hran', Hsupp', _); simpl in *.\n      symmetry; rewrite <-Hsupp'.\n      symmetry; apply (Hddran _ (Oeq_sym H) _ Hab).\n      (*  *)\n      rewrite <-Hsupp in H.\n      symmetry; apply Hdran.\n      intros (a1,b1) Hab; simpl.\n      destruct (H2 _ _ (drange_range HcarP Hran Hddran _ Hab)) as (_, Hran', Hsupp', _); simpl in *.\n      symmetry; rewrite Hsupp'.\n      symmetry; apply (Hddran _ (Oeq_sym H) _ Hab).\n    (* supp_r *)\n    destruct H as  [carP HcarP].\n    destruct H0 as [Rd [Hdran Hddran] ].\n    destruct H1 as (_, Hran, _, Hsupp).\n    split; intros; simpl in *.\n      (*  *)\n      rewrite <-Hsupp.\n      symmetry; apply Hdran.\n      intros (a1,b1) Hab; simpl.\n      destruct (H2 _ _ (drange_range HcarP Hran Hddran _ Hab)) as (_, Hran', _, Hsupp'); simpl in *.\n      symmetry; rewrite <-Hsupp'.\n      symmetry; apply (Hddran _ (Oeq_sym H) _ Hab).\n      (*  *)\n      rewrite <-Hsupp in H.\n      symmetry; apply Hdran.\n      intros (a1,b1) Hab; simpl.\n      destruct (H2 _ _ (drange_range HcarP Hran Hddran _ Hab)) as (_, Hran', _,Hsupp'); simpl in *.\n      symmetry; rewrite Hsupp'.\n      symmetry; apply (Hddran _ (Oeq_sym H) _ Hab).\n Qed.\n\n\n\n Lemma elift_weaken: forall A B (P Q:A -> B -> Prop), \n  (forall x y, P x y -> Q x y) ->\n  forall ep ep',\n  ep' <= ep ->\n  forall d d1 d2, \n  elift P d d1 d2 ep' -> elift Q d d1 d2 ep.\n Proof.\n  intros A B P Q H1 ep ep' H2 d d1 d2 (Hdist, Hran, Hsup_l, Hsup_r).\n  constructor.\n    intros f g; rewrite <-H2; trivial.\n    apply range_weaken with (prodP P). \n      unfold prodP; auto.\n      trivial.\n    assumption.\n    assumption.\n Qed.\n\n\n Lemma elift_stable_eq : forall A B (R:A -> B -> Prop) \n  (d d' : Distr (A*B)) (d1 d1':Distr A) (d2 d2':Distr B) ep ep',\n  d == d' -> \n  d1 == d1' -> \n  d2 == d2' -> \n  ep == ep' ->\n  elift R d d1 d2 ep -> elift R d' d1' d2' ep'.\n Proof.\n  intros A B R d d' d1 d1' d2 d2' ep ep' Heq Heq1 Heq2 Heq3 (Hdist, Hran, Hsup_l, Hsup_r).\n  constructor.\n    intros.\n    rewrite <-(eq_distr_elim Heq), <-(eq_distr_elim Heq), \n       <-(eq_distr_elim Heq1), <-(eq_distr_elim Heq2), <-Heq3; trivial.\n    apply range_stable_eq with (1:=Heq); trivial.\n    intro f; rewrite <-(eq_distr_elim Heq), <-(eq_distr_elim Heq1); auto.\n    intro g; rewrite <-(eq_distr_elim Heq), <-(eq_distr_elim Heq2); auto.\n Qed.\n\n\n Lemma elift_Munit: forall k (m1 m2: Mem.t k) (P:mem_rel), \n  P _ m1 m2 -> \n  elift (P k) (Munit (m1,m2)) (Munit m1) (Munit m2) (fzero nat k).\n Proof.\n  intros; constructor.\n   intros; repeat rewrite Uabs_diff_compat_eq; auto.\n   apply range_Munit with (1:=H).\n   intro; auto.\n   intro; auto.\n Qed.\n \n\n Lemma elift_true: forall (A B: Type) (d1: Distr A) (d2: Distr B),\n  ~ mu d1 (fone _) == 0 -> \n  ~ mu d2 (fone _) == 0 -> \n  elift (fun _ _ => True) (prod_distr d1 d2) d1 d2 \n    ([1-] (mu d1 (fone _)) + [1-] (mu d2 (fone _))).\n Proof.\n  intros.\n  constructor.\n    (* dist *)\n    intros f g; rewrite prod_distr_fst, prod_distr_snd.\n    rewrite <-(Umult_one_right (mu d1 f)),  <-(Umult_one_right (mu d2 g)) at 2.\n    rewrite <-(Umult_sym (mu d1 f)), <-(Umult_sym (mu d2 g)).\n    repeat rewrite Uabs_diff_mult.\n    rewrite Uplus_sym; apply Uplus_le_compat; unfold Uabs_diff.\n      rewrite (Uminus_le_zero _ 1); [ rewrite Uplus_zero_left, Uminus_one_left | ]; auto.\n      rewrite (Uminus_le_zero _ 1); [ rewrite Uplus_zero_left, Uminus_one_left | ]; auto.\n    (* range *)\n    apply range_True.\n    (* supp *)\n    intros; rewrite prod_distr_fst; split; intro.\n      symmetry; apply Umult_zero_simpl_right with (mu d2 (fone _)); auto.\n      rewrite H1; auto.\n    intros; rewrite prod_distr_snd; split; intro.\n      symmetry; apply Umult_zero_simpl_left with (mu d1 (fone _)); [ \n        rewrite Umult_sym | ]; auto.\n      rewrite H1; auto.\n Qed.\n\n\n Lemma elift_transp : forall (A B:Type) (d: Distr (A*B)) (d1:Distr A) (d2:Distr B) R ep, \n   elift (fun b a => R a b) (Mlet d (fun ab => Munit (snd ab, fst ab))) d2 d1 ep ->\n   elift R d d1 d2 ep. \n Proof.\n  intros; constructor.\n    (* distance *)\n    intros f g; rewrite Uplus_sym; apply (el_dist H g f).\n    (* range *)\n    intros f Hf.\n    rewrite (el_range H (fun ba => f (snd ba,fst ba))).\n      rewrite Mlet_simpl; simpl.\n      apply (mu_stable_eq d); refine (ford_eq_intro _); intros (a,b); trivial.\n      auto.\n    (* supp *)\n    apply (el_supp_r H).\n    apply (el_supp_l H).\n Qed.\n\n\n Lemma lift_elift: forall A B (P:A -> B -> Prop) d d1 d2, \n  elift P d d1 d2 0 <-> lift P d d1 d2.\n Proof.\n  split; intros.\n   (*  *)\n    constructor.\n      intro f.\n      rewrite <-Uabs_diff_zero; apply Ule_zero_eq.\n      rewrite <-(el_dist H f (fzero _)); auto.\n      intro f.\n      rewrite <-Uabs_diff_zero; apply Ule_zero_eq.\n      rewrite <-(el_dist H (fzero _) f); auto.\n      apply (el_range H).\n    (*  *)\n    constructor.  \n      intros f g.\n      rewrite (l_fst H), (l_snd H), Uabs_diff_compat_eq, Uabs_diff_compat_eq; auto.\n      apply (l_range H).\n      intro; rewrite (l_fst H); auto.\n      intro; rewrite (l_snd H); auto.\n Qed.\n\n\n \n\nSection LIFT_TRANS.\n \n Variables A B C : Type.\n Variable carB : B -> MF B.\n\n Hypothesis carB_prop : forall b, cover (fun x => b = x) (carB b).\n \n Variable P : A -> B -> Prop.\n Variable Q : B -> C -> Prop.\n Variable R : A -> C -> Prop.\n\n Hypothesis P_Q_R : forall x y z, P x y -> Q y z -> R x z.\n\n Variable d  : Distr (A*B).\n Variable d' : Distr (B*C). \n Variable ep ep' : U.\n Variable d1 : Distr A.\n Variable d2 : Distr B.\n Variable d3 : Distr C.\n\n Hypothesis  Hd : elift P d  d1 d2 ep.\n Hypothesis  Hd': elift Q d' d2 d3 ep'.\n\n Definition dfst (b : B) : distr (B*C) := distr_mult (fun q => carB b (fst q)) d'.\n Definition dsnd (b : B) : distr (A*B) := distr_mult (fun q => carB b (snd q)) d.\n\n\n Lemma dfst_simpl : forall b f, \n  mu (dfst b) f = mu d' (fun q => carB b (fst q) * f q).\n Proof. trivial. Qed.\n\n Lemma dsnd_simpl : forall b f, \n  mu (dsnd b) f = mu d (fun q => carB b (snd q) * f q).\n Proof. trivial. Qed.\n\n\n Lemma dfst_le : forall b, \n  mu (dfst b) (fone _) <= mu d' (fun bc => carB b (fst bc)).\n Proof.\n  intro; rewrite dfst_simpl; auto.\n Qed.\n\n Lemma dsnd_le : forall b, \n  mu (dsnd b) (fone _) <=  mu d (fun ab => carB b (snd ab)).\n Proof.\n  intro; rewrite dsnd_simpl; auto. \n Qed. \n\n\n Hint Resolve dfst_le dsnd_le.\n\n Definition d_restr : B -> distr (A*B) := \n  fun b => distr_div (mu d (fun ab => carB b (snd ab))) (dsnd b) (dsnd_le b) .\n\n Definition d'_restr : B -> distr (B*C) := \n  fun b => distr_div (mu d' (fun bc => carB b (fst bc))) (dfst b) (dfst_le b).\n\n\n Definition dd' : distr (A * C) := \n  Mlet d2 (fun b => \n   Mlet (d_restr b) (fun p => \n    Mlet (d'_restr b) (fun q => Munit (fst p, snd q)))).   \n   \n\n  Lemma dd'_1: forall f, \n    mu dd' (fun ac => f (fst ac)) == \n    mu d2  (fun b  =>  (mu d (fun ab => (carB b (snd ab)) * (f (fst ab)))  /\n       mu d (fun ab => carB b (snd ab)))).\n  Proof.\n   intros; simpl.\n   apply (mu_stable_eq d2); simpl; apply ford_eq_intro; intros b; simpl.\n   apply (Ueq_orc 0 (mu d (fun ab => carB b (snd ab)))); auto; intros.\n     repeat (rewrite Udiv_by_zero; auto).\n     apply Udiv_eq_compat_left.\n     apply (mu_stable_eq d); simpl; apply ford_eq_intro; intros (a,b'); simpl.\n     Usimpl.\n     apply Oeq_trans with (f a * (mu d' (fun bc => carB b (fst bc))) /\n         (mu d' (fun bc => carB b (fst bc)))).\n       apply Udiv_eq_compat_left.\n       rewrite <- (mu_stable_mult d' (f a) (fun bc => carB b (fst bc))).\n       apply (mu_stable_eq d'); simpl; apply ford_eq_intro; intros; unfold fmult; auto.\n       rewrite Umult_div_assoc; auto.\n       rewrite Udiv_refl; [ auto | ].\n       apply neq_sym; intro H'; elim H; clear H; apply Oeq_sym.\n       rewrite (Hd.(el_supp_r) (fun b' => carB b b')).\n       apply (Hd'.(el_supp_l) (fun b' => carB b b')); assumption.\n Qed.\n\n\n  Lemma dd'_2: forall g, \n    mu dd' (fun ac => g (snd ac)) ==  mu d2  (fun b  => \n      (mu d' (fun bc => (carB b (fst bc)) * (g (snd bc)))  /\n       mu d' (fun bc => carB b (fst bc)))).\n  Proof.\n   intros; simpl.\n   apply (mu_stable_eq d2); simpl; apply ford_eq_intro; intros b; simpl.\n   apply (Ueq_orc 0 (mu d' (fun bc => carB b (fst bc)))); auto; intros.\n\n     repeat (rewrite Udiv_by_zero; auto).\n     apply Oeq_sym; apply Oeq_sym in H.  \n     rewrite (Hd.(el_supp_r) (fun b' => carB b b')).\n     apply (Hd'.(el_supp_l) (fun b' => carB b b')); assumption.\n     \n     transitivity (mu d\n     (fun ab => ((mu d') (fun bc : B * C => carB b (fst bc) * g (snd bc)) /\n       (mu d') (fun bc : B * C => carB b (fst bc))) *\n       carB b (snd ab))  /\n     (mu d) (fun ab => carB b (snd ab))).\n       apply Udiv_eq_compat_left.\n       apply (mu_stable_eq d); simpl; apply ford_eq_intro; auto.\n\n       rewrite (mu_stable_mult d ((mu d') (fun bc => carB b (fst bc) * g (snd bc)) /\n         (mu d') (fun bc => carB b (fst bc))) (fun ab => carB b (snd ab))).\n       rewrite Umult_div_assoc; [ | trivial ].\n       rewrite Udiv_refl; [ auto | ].\n       apply neq_sym; intro H'; elim H; clear H; apply Oeq_sym.\n       rewrite (Hd'.(el_supp_l) (fun b' => carB b b')).\n       apply (Hd.(el_supp_r) (fun b' => carB b b')); assumption.\n Qed.\n\n\n Lemma dd'_range : range (prodP R) dd'.\n Proof.\n  red; intros.\n  unfold dd'; simpl.\n  transitivity (mu d2 (fzero B)); [auto | ].\n  apply (mu_stable_eq d2); simpl; apply ford_eq_intro; intro x; unfold fzero.\n  apply (Ueq_orc 0  (mu d (fun ab => carB x (snd ab)))); [ auto | | ]; intros.\n    (*   *)\n    apply Oeq_sym; apply Udiv_by_zero; auto.\n    (*   *)\n    apply Oeq_sym; apply Udiv_zero_eq; auto.\n    apply Hd.(el_range); intros.\n    apply (cover_elim (carB_prop x) (snd x0)); auto; intros [H4 H5].\n      rewrite H5; auto.\n      rewrite H5; Usimpl.\n      apply Oeq_sym; apply Udiv_zero_eq; auto.\n      apply Hd'.(el_range); intros.\n      destruct x1; destruct x0; simpl.\n      simpl in H4; subst x.\n      apply (cover_elim (carB_prop b0) b); auto; intros [H6 H7].\n      rewrite H7; auto.\n      rewrite <- H; auto.\n      subst b0; red.  \n      apply P_Q_R with b; trivial.\n  Qed.\n\n\nSection HYPO.\n\n  Hypothesis hyp_d1_d : forall f:A -> U,\n   mu d (fun ab => f (fst ab)) == \n   mu d (fun ab => \n    mu d (fun ab' => carB (snd ab) (snd ab') * f (fst ab')) /  \n    mu d (fun ab' => carB (snd ab) (snd ab'))).\n\n  Hypothesis hyp_d3_d' : forall g:C -> U,\n   mu d' (fun bc => g (snd bc)) == \n   mu d' (fun bc => \n    mu d' (fun bc' => carB (fst bc) (fst bc') * g (snd bc')) /  \n    mu d' (fun bc' => carB (fst bc) (fst bc'))).\n\n  Lemma dd'_dist : forall (f : A -> U) (g : C -> U),\n    Uabs_diff ((mu dd') (fun ac => f (fst ac))) ((mu d1) f) +\n    Uabs_diff ((mu dd') (fun ac => g (snd ac))) ((mu d3) g) <=\n    ep + ep'.\n  Proof.\n   intros.\n   apply Uplus_le_compat.   \n     rewrite (Uabs_diff_triangle_ineq _ _  (mu d (fun ab => f (fst ab)))).\n     rewrite  dd'_1; rewrite hyp_d1_d at 1.\n     rewrite Uabs_diff_sym, Uplus_sym. \n     refine (Hd.(el_dist) f (fun b =>\n        mu d (fun ab => carB b (snd ab) * f (fst ab)) /\n        mu d (fun ab => carB b (snd ab)))).\n\n     rewrite (Uabs_diff_triangle_ineq _ _  (mu d' (fun bc => g (snd bc)))).\n     rewrite  dd'_2; rewrite hyp_d3_d' at 1.\n     rewrite Uabs_diff_sym. \n     refine (Hd'.(el_dist) (fun b =>\n         mu d' (fun bc => carB b (fst bc) * g (snd bc)) /\n         mu d' (fun bc => carB b (fst bc))) g).\n Qed.\n\n End HYPO.\n\n\n Section DISCRETE.\n\n  Let p2_d := (Mlet d (fun ab => Munit (snd ab))).\n\n  Variable p2D : is_Discrete p2_d.\n\n  Let p2 := p2D.(D_points).\n\n  Let c2 := coeff carB p2D.(D_points) p2_d.\n \n  Lemma cp_retract_p2d : forall x, \n   wretract (fun k : nat => c2 k / c2 k * carB (p2 k) x).\n  Proof.\n   unfold wretract; intros.\n   apply (Ueq_orc 0 (c2 k)); [auto | | ]; intros.\n   rewrite Udiv_by_zero; trivial; repeat Usimpl; auto.\n   apply (cover_elim (carB_prop (p2 k)) x); [auto | | ]; intros [H4 H5].\n   rewrite H5; repeat Usimpl; auto.\n   rewrite sigma_zero; [ auto | intros].\n   apply (cover_elim (carB_prop (p2 k0)) x); [auto | | ]; intros [H2 H3].\n   rewrite H3; repeat Usimpl; auto.\n   elim H; unfold c2, coeff.\n   set (P1:=fun k => exc (fun k0 => (k0 < k)%nat /\\ p2 k = p2 k0)).\n   rewrite (@cover_eq_one _ P1 _ k (cover_not_first_repr (@eq B) carB carB_prop (D_points p2D))).\n   Usimpl; auto.\n   red; apply exc_intro with k0; split; trivial.\n   rewrite H2; trivial.\n  Qed.\n \n  Definition in_p2_d b := serie (fun k : nat => c2 k / c2 k * carB (p2 k) b).\n  \n  Lemma in_p2_d_dec : forall b, orc (in_p2_d b == 0) (in_p2_d b == 1).\n  Proof.\n   intros; apply orc_intro; intros.\n   elim H.\n   unfold in_p2_d.\n   apply serie_zero.\n   intros k; apply (Ueq_orc (c2 k / c2 k * carB (p2 k) b) 0); auto; intros.\n   elim H0; split; trivial.\n   transitivity (c2 k / c2 k * carB (p2 k) b).\n   apply (Ueq_orc (c2 k)  0); auto; intros.\n   elim H1; rewrite H2, Udiv_by_zero; auto.\n   apply (cover_elim (carB_prop (p2 k)) b); [auto | | ]; intros [H4 H5].\n   elim H1; rewrite H5; auto.\n   rewrite H5, Udiv_refl; auto.\n   exact (serie_le (fun k0 : nat => c2 k0 / c2 k0 * carB (p2 k0) b) k).\n  Qed.\n\n  Lemma in_p2_d_p : forall k, ~c2 k == 0 -> in_p2_d (p2 k) == 1.\n  Proof.\n   intros; unfold in_p2_d; split; trivial.\n   transitivity (c2 k / c2 k * carB (p2 k) (p2 k)).\n   rewrite Udiv_refl; [ auto | ].\n   rewrite (cover_eq_one _ (carB_prop (p2 k)) (refl_equal (p2 k))).\n   auto.\n   auto.\n   exact (serie_le (fun k0 : nat => c2 k0 / c2 k0 * carB (p2 k0) (p2 k)) k).\n  Qed.\n\n  Lemma d_ito_p2_d: forall f,\n   mu d f ==\n   mu p2_d (fun b : B =>\n    mu d (fun ab => carB b (snd ab) * f ab) /  mu d (fun ab => carB b (snd ab))). \n  Proof.\n   intros. \n   transitivity (serie (fun k =>\n    mu d (fun p0 => (c2 k / c2 k) * carB (p2 k) (snd p0) * f p0))).\n   rewrite <- mu_serie_eq.\n   2:intro x; apply wretract_le with (2:=cp_retract_p2d (snd x)); auto.\n\n   unfold serie_fun.\n   apply range_eq with (P:=fun x => in_p2_d (snd x) == 1).\n   unfold range; intros; split; auto.\n   transitivity (mu d (fun p => [1-] (in_p2_d (snd p)))).\n   apply (mu_monotonic d); intro x.\n   apply (in_p2_d_dec (snd x)); [auto | | ]; intros H0; [rewrite H0 | rewrite <- H]; auto.\n   transitivity (mu p2_d (fun b =>  [1-] in_p2_d b)); [ auto | ].\n   rewrite (mu_is_Discrete carB carB_prop p2D), discrete_simpl.\n   rewrite serie_zero; [auto | intros].\n   fold (c2 k).\n   apply (Ueq_orc (c2 k) 0); [auto | | ]; intros.\n   rewrite H0; auto.\n   fold p2; rewrite in_p2_d_p; [ Usimpl | ]; auto.\n   intros.\n   transitivity (serie (fun k => f a * (c2 k / c2 k * carB (p2 k) (snd a)))).\n   rewrite serie_mult.   \n   rewrite H; auto.\n   apply cp_retract_p2d.\n   apply serie_eq_compat; auto.\n\n   rewrite (mu_is_Discrete carB carB_prop p2D), discrete_simpl. \n   apply serie_eq_compat; intros.\n   set (g:=fun p0 => c2 k / c2 k * carB (p2 k) (snd p0) * f p0).\n   apply (Ueq_orc (c2 k) 0); [auto | | ]; intros.\n   fold c2; rewrite H; Usimpl.\n   rewrite <- (mu_0 d).\n   apply (mu_stable_eq d).\n   simpl; apply ford_eq_intro; intros; unfold g; rewrite Udiv_by_zero; [Usimpl | ]; auto.\n   unfold c2 in H; unfold coeff in *.\n   apply (cover_elim (cover_not_first_repr (@eq B) carB carB_prop (D_points p2D)) k);\n    [ auto | | ]; intros (H1, H2).\n   generalize H; clear H; rewrite H2; repeat Usimpl; intros.\n   unfold p2_d. rewrite Mlet_simpl.\n   rewrite Umult_sym, Udiv_mult; [auto | | ].\n   apply mu_stable_eq; unfold g; simpl; apply ford_eq_intro; intros.\n   rewrite Udiv_refl; auto.\n   unfold c2; rewrite H2; Usimpl; auto.\n   auto.\n   apply Ole_trans with (2:=dsnd_le (p2 k)).\n   rewrite dsnd_simpl.\n   apply (mu_monotonic d); intro; unfold fone; auto.\n   elim H; rewrite H2;Usimpl; auto.\n  Qed.\n\n\n  Lemma elift_discr_fst : forall f : A -> U,\n   mu d (fun ab => f (fst ab)) ==\n   mu p2_d (fun b : B =>\n    mu d (fun ab => carB b (snd ab) * f (fst ab)) /  mu d (fun ab => carB b (snd ab))). \n  Proof. intros; apply d_ito_p2_d. Qed.\n\n\n Lemma dd'_ndeg_l: forall f : A -> U,\n   mu dd' (fun ac => f (fst ac)) == 0 <-> mu d1 f == 0.\n Proof.\n   split; intros.\n     rewrite dd'_1, <-(Hd.(el_supp_r)) in H.\n     apply (Hd.(el_supp_l)).\n     rewrite elift_discr_fst. \n     exact H.\n     \n     rewrite <-(Hd.(el_supp_l)) in H.\n     rewrite dd'_1.\n     rewrite <-(mu_zero d2).\n     apply (mu_stable_eq d2); simpl; apply ford_eq_intro; intro b; unfold fzero.\n     apply Udiv_zero_eq; symmetry; apply Ule_zero_eq.\n     rewrite <-H.\n     refine (mu_monotonic _ _ _ _); refine (ford_le_intro _); intro ab; auto.\n Qed.\n\n\n End DISCRETE.\n\nEnd LIFT_TRANS.\n\n\nSection LIFT_TRANS_DISCR.\n\n Variables A B C : Type.\n Variable carB : B -> MF B.\n \n Hypothesis carB_prop : forall b, cover (fun x => b = x) (carB b).\n\n Variable P : A -> B -> Prop.\n Variable Q : B -> C -> Prop.\n Variable R : A -> C -> Prop.\n\n Hypothesis P_Q_R : forall x y z, P x y -> Q y z -> R x z.\n\n Variable d1 : Distr A.\n Variable d2 : Distr B.\n Variable d3 : Distr C.\n\n Variable d  : Distr (A * B).\n Variable d' : Distr (B * C).\n Variable ep ep' : U.\n\n Variable Hd : elift P d  d1 d2 ep.\n Variable Hd': elift Q d' d2 d3 ep'.\n \n Hypothesis discr_d : is_Discrete (Mlet d  (fun ab => Munit (snd ab))).\n Hypothesis discr_d': is_Discrete (Mlet d' (fun bc => Munit (fst bc))).\n\n\n Let d'' := dd' carB d d' d2.\n\n\n Lemma dd'_ndeg_r: forall g : C -> U,\n   mu d'' (fun ac => g (snd ac)) == 0 <-> mu d3 g == 0.\n Proof.\n   split; intros; unfold d'' in *.\n     (*  *)\n     rewrite (dd'_2 _ Hd Hd'), <-(Hd'.(el_supp_l)) in H.\n     change (mu (Mlet (d_inv d') (fun cb => Munit (snd cb))) \n         (fun b => (mu (d_inv d')) (fun cb => carB b (snd cb) * g (fst cb)) /\n          (mu (d_inv d')) (fun cb => carB b (snd cb))) == 0) in H.\n     rewrite <-(elift_discr_fst _ carB_prop) in H; [ |\n       refine (is_Discrete_eq_compat _ discr_d'); auto ].\n     apply (Hd'.(el_supp_r)).\n     rewrite d_inv_fst; exact H.\n     (*  *)\n     rewrite <-(Hd'.(el_supp_r)) in H.\n     rewrite (dd'_2 _ Hd Hd').\n     rewrite <-(mu_zero d2).\n     apply (mu_stable_eq d2); simpl; apply ford_eq_intro; intro b; unfold fzero.\n     apply Udiv_zero_eq; symmetry; apply Ule_zero_eq.\n     rewrite <-H.\n     refine (mu_monotonic _ _ _ _); refine (ford_le_intro _); intro bc; auto.     \n Qed.\n\n\n Lemma elift_trans_discr: elift R  d'' d1 d3 (ep + ep').\n Proof.\n  constructor. \n   (* distance *)\n   apply dd'_dist with P Q; trivial.\n     intro; refine (elift_discr_fst _ carB_prop discr_d _).\n     intro.\n     rewrite (d_inv_fst d'), (d_inv_snd d' (fun b =>\n      (mu d') (fun bc' : B * C => carB b (fst bc') * g (snd bc')) /\n      (mu d') (fun bc' : B * C => carB b (fst bc')))).\n     refine (elift_discr_fst _ carB_prop _ _).\n     refine (is_Discrete_eq_compat _ discr_d'); auto.\n   (* range *)\n   refine (dd'_range _ carB_prop _ P_Q_R Hd Hd').\n   (* supp *)\n   refine (dd'_ndeg_l _ carB_prop Hd Hd' discr_d).\n   apply  dd'_ndeg_r.\n Qed.\n\nEnd LIFT_TRANS_DISCR.\n\nEnd Lift.\n\n\n Lemma discr_srange: forall (A:Type) (d:Distr A)  \n  (Hdiscr: is_Discrete d) (carA: A -> MF A),\n  (forall a, cover (fun x => a = x) (carA a)) ->\n  srange (fun a => exc (fun k => a = D_points Hdiscr k) /\\ ~ mu d (carA a) == 0) d.\n Proof.\n  intros.\n  split.\n    (* range *)\n    intros f Hf.\n    rewrite (mu_is_Discrete _ H Hdiscr); destruct Hdiscr; simpl in *.\n    symmetry; apply serie_zero.\n    intro k.\n    apply (Ueq_orc (mu d (carA (D_points k))) 0); [ auto | | ]; intro Hk.\n      unfold coeff; rewrite Hk; repeat Usimpl; trivial.\n      rewrite <-Hf; [ auto | ];\n        split; [ apply exc_intro with k | ]; trivial.\n    (* drange *)\n    intro f.\n    rewrite (mu_is_Discrete _ H Hdiscr).\n    intros Hf a [H1 H2]; simpl in *.\n    generalize (serie_zero_elim _ (Oeq_sym Hf)); clear Hf; intro Hf.\n    assert (H': exc (In_class eq (D_points Hdiscr) a)).\n      apply H1;[auto | ].\n      induction x using Wf_nat.lt_wf_ind; intros.\n      apply (cover_elim (cover_not_first_repr _ _ H (D_points Hdiscr)) x);  \n        [ auto | | ]; intros [H5 H6].\n        apply exc_intro with x. \n        split; [ | red;intros;elim H5;apply exc_intro with k0];auto.\n        apply H5;[auto | ].\n        intros m (H7, H8);apply (H0 m); [ | rewrite <-H8 ]; auto.\n    clear H1; apply H'; [ auto | intros k [Hk Hk']; subst; clear H' ].\n    apply (Umult_zero_simpl_right (Oeq_sym (Hf k))).\n    apply (cover_elim  (cover_not_first_repr _ _ H (D_points Hdiscr)) k); \n      [ auto | | ]; intros [H4 H5]. \n      unfold coeff; rewrite H5; repeat Usimpl; auto.\n      apply H4; [auto | intros k2 [Hk2 Hk2'] ]; generalize (Hk' _ Hk2); tauto.\n Qed.\n\n\n\n(*\n   Given a distribution on a product, if both projections \n   are discrete, then the distribution is discrete. \n*)\nSection DISCRETE.\n\n Variables A B: Type.\n\n Variable carB : B -> MF B.\n Variable carA : A -> MF A.\n \n Hypothesis carB_prop : forall b, cover (fun x => b = x) (carB b).\n Hypothesis carA_prop : forall a, cover (fun x => a = x) (carA a).\n\n Variable d  : Distr (A * B).\n \n Hypothesis discr_d1: is_Discrete (Mlet d (fun ab => Munit (fst ab))).\n Hypothesis discr_d2: is_Discrete (Mlet d (fun ab => Munit (snd ab))).\n\n\n Lemma discr_projs: is_Discrete d.\n Proof.\n  destruct discr_d1 as [p1 H1]. \n  destruct discr_d2 as [p2 H2].\n  apply mkDiscr with (fun k => (p1 (fst (bij_n_nxn k)), p2 (snd (bij_n_nxn k)))).\n  unfold Discrete, range in *; simpl in *.\n  intros f Hf.\n  rewrite (d_ito_p2_d _ carB_prop discr_d2); simpl.\n  apply H2 with (f:= fun b => \n      (mu d) (fun ab : A * B => carB b (snd ab) * f ab) /\n      (mu d) (fun ab : A * B => carB b (snd ab))).\n  intros b Hb; apply Hb; [ auto | intros kb Hkb ].\n  symmetry; apply Udiv_zero_eq.\n\n  transitivity (mu (d_inv d) (fun ba => carB b (fst ba) * f (snd ba, fst ba)));\n    [ | simpl; apply (mu_stable_eq d); refine (ford_eq_intro _); intros (a',b'); auto ].\n  rewrite (d_ito_p2_d _ carA_prop); [ simpl |\n    refine (is_Discrete_eq_compat _  discr_d1); auto ].\n  apply H1 with (f:= fun a  => mu d\n    (fun ab => carA a (fst ab) * (carB b (snd ab) * f (fst ab, snd ab))) /\n    mu d (fun ab => carA a (fst ab))).\n  intros a Ha; apply Ha; [ auto | intros ka Hka ].\n  symmetry; apply Udiv_zero_eq.\n\n  rewrite <-(mu_zero d); unfold fzero;\n  apply mu_stable_eq; refine (ford_eq_intro _).\n  intros (a',b'); simpl.\n  apply (cover_elim (carB_prop b) b'); [ auto | | ]; intros [H4 H5].\n    rewrite H5; repeat Usimpl; trivial.\n    rewrite H5, <-H4; Usimpl; clear H4 H5.\n    apply (cover_elim (carA_prop a) a'); [ auto | | ]; intros [H4 H5].\n      rewrite H5; repeat Usimpl; trivial.\n      rewrite H5, <-H4; Usimpl; clear H4 H5.\n      apply Hf.\n      destruct (bij_surj ka kb) as [k Hk].\n      apply exc_intro with k.\n      rewrite Hk; simpl; rewrite Hkb, Hka; trivial.\n Qed.\n\nEnd DISCRETE.\n\n\n\n Add Parametric Morphism A B : (elift (A:=A) (B:=B))\n with signature Fimp2 (A:=A) (B:=B) --> \n  Oeq (O:=Distr (A * B)) ==> Oeq (O:=Distr A) ==> \n  Oeq (O:=Distr B) ==> Oeq (O:=U) ==> inverse impl\n as elift_morph.\n Proof.\n  unfold impl, Fimp2; intros R1 R2 H d1 d2 H0 d3 d4 H1 d5 d6 H2 ep1 ep2 H3 H4.\n  eapply elift_weaken  with R2 ep2; auto.\n  apply elift_stable_eq with d2 d4 d6 ep2; auto.\n Qed.\n\n\n Lemma elift_dist: forall A B (R:A -> B -> Prop) \n  (d1:Distr A) (d2:Distr B) d ep (f:A -o> U) (g:B-o>U),\n  (forall a b, R a b -> f a == g b) ->\n  elift R d d1 d2 ep ->\n  Uabs_diff (mu d1 f) (mu d2 g) <= ep.\n Proof.\n  intros A B R d1 d2 d ep f g Hfg (Hdist, Hrange, _, _).\n  rewrite (Uabs_diff_triangle_ineq (mu d1 f) _ (mu d (fun x => f (fst x)))).\n  rewrite (Uabs_diff_triangle_ineq _ (mu d2 g) (mu d (fun x => g (snd x)))).\n  match goal with \n   |- Uabs_diff ?F1 ?G1 + (Uabs_diff ?G1 ?G2 + Uabs_diff ?G2 ?F2) <= _ => \n     rewrite (proj2 (Uabs_diff_zero G1 G2)), Uplus_zero_left, (Uabs_diff_sym F1 G1)  \n  end.\n    apply Hdist.\n    apply (range_eq Hrange); intros (a,b); apply (@Hfg a b).\n Qed.\n\n\n Lemma elift_deno_witness_discr: forall (c1 c2:cmd) e1 e2 k (m1 m2:Mem.t k) d R ep,\n  elift R d ([[c1]] e1 m1) ([[c2]] e2 m2) ep ->\n  is_Discrete d.\n Proof.\n  intros.\n  destruct H as (_, _, Hl, Hr).\n  apply discr_projs with (carA:=@mem_eqU k) (carB:=@mem_eqU k).\n    apply mem_eqU_spec.\n    apply mem_eqU_spec.\n    apply discr_ext with ([[c1]] e1 m1).\n      intros f Hf; apply (proj2 (Hl f) Hf).\n      apply sem_discr.\n    apply discr_ext with ([[c2]] e2 m2).\n      intros f Hf; apply (proj2 (Hr f) Hf).\n      apply sem_discr.\n Qed.\n\n(********************************************************************)\n(********************************************************************)\n\n\n Definition dist_prg (P:mem_rel) E1 c1 E2 c2 (Q:mem_rel) (ep:nat-o>U) :=\n  forall k, exists d,\n   forall (m1 m2 : Mem.t k),\n   P _ m1 m2 ->\n   elift (@Q k) (d m1 m2) ([[c1]] E1 m1)  ([[c2]] E2 m2) (ep k).\n\n\n Lemma dist_prg_deno: forall (P:mem_rel) E1 c1 E2 c2 (Q:mem_rel) ep,\n  dist_prg P E1 c1 E2 c2 Q ep ->\n  forall (k : nat) (f g : Mem.t k -> U),\n  (forall m1 m2 : Mem.t k, Q k m1 m2 -> f m1 == g m2) ->\n   forall m1 m2 : Mem.t k,\n   P k m1 m2 -> Uabs_diff (mu ([[c1]] E1 m1) f) (mu ([[c2]] E2 m2) g) <= ep k.\n Proof.\n  unfold dist_prg; intros.\n  destruct (H k) as [d Hd]; clear H.\n  apply elift_dist with (Q k) (d m1 m2); auto.\n Qed.     \n\n\n Lemma dist_prg_sdeno: forall c1 E1 c2 E2 (P Q: mem_rel) ep,\n   decMR P ->\n   dist_prg P E1 c1 E2 c2 Q ep ->\n   forall k (d1 d2 : Distr(Mem.t k)) (del:nat -o> U), \n   (exists d, elift (@P k) d d1 d2 (del k) /\\ exists R, srange R d) ->\n   forall f g,\n   (forall m1 m2 : Mem.t k, Q k m1 m2 -> f m1 == g m2) ->\n   Uabs_diff (mu (Mlet d1 ([[c1]] E1)) f) (mu (Mlet d2 ([[c2]] E2)) g) <= (ep k + del k).\n Proof.\n  intros.\n  destruct H0 as [d [Hd HdR] ].\n  destruct (H k) as [d' Hd']; clear H.\n  apply elift_dist with (R:=Q k) (d:=Mlet d (fun mm => d' (fst mm) (snd mm))).\n    assumption.\n    apply elift_Mlet with (P k); try assumption.\n      exists (carac (fun mm => X k (fst mm) (snd mm)));\n        apply (cover_dec (fun mm => X k (fst mm) (snd mm))).\n Qed.\n\n\n Lemma dist_prg_weaken: forall P E1 c1 E2 c2 Q ep P' Q' (ep':nat -o> U),\n  implMR P P' ->\n  implMR Q' Q ->\n  ep' <= ep ->\n  dist_prg P' E1 c1 E2 c2 Q' ep' ->\n  dist_prg P  E1 c1 E2 c2 Q  ep.\n Proof.\n  unfold dist_prg; intros.\n  destruct (H2 k) as [d Hd]; clear H2.\n  exists d.\n  intros m1 m2 Hm. \n  apply elift_weaken with (Q' k) (ep' k); auto.\n Qed.\n\n Add Morphism dist_prg with signature \n   implMR --> (@eq env) ==> (@eq cmd) ==> (@eq env) ==> \n   (@eq cmd) ==> implMR ++> (@Ole (ford nat (tcpo U))) ++>\n    impl as dist_prg_imp_Morph.\n Proof.\n  unfold impl; intros.\n  apply dist_prg_weaken with (4:=H2); assumption.\n Qed.   \n\n\n Add Morphism dist_prg with signature \n   iffMR ==> (@eq env) ==> (@eq cmd) ==> (@eq env) ==> \n   (@eq cmd) ==> iffMR ==> (@Oeq (ford nat (tcpo U))) ==> \n   iff as dist_prg_iff_Morph.\n Proof.\n  unfold iffMR; intros. \n  destruct H; destruct H0.\n  split; intros.\n    apply dist_prg_weaken with (4:=H4); auto.\n    apply dist_prg_weaken with (4:=H4); auto.\n Qed.\n\n\n Lemma dist_prg_trueR: forall (P:mem_rel) E1 c1 E2 c2 ep1 ep2,\n  (forall k (m1 m2:Mem.t k), P _ m1 m2 ->\n    ep1 k <=  mu ([[c1]] E1 m1) (fone _) /\\\n    ep2 k <=  mu ([[c2]] E2 m2) (fone _)) ->\n  (forall k (m1 m2:Mem.t k), P _ m1 m2 ->\n  ~ mu ([[c1]] E1 m1) (fone _) == 0 /\\\n  ~ mu ([[c2]] E2 m2) (fone _) == 0) ->\n  dist_prg P E1 c1 E2 c2 trueR (fun k => [1-] (ep1 k) + [1-] (ep2 k)).\n Proof.\n  unfold dist_prg; intros.\n  exists (fun m1 m2 => prod_distr ([[c1]] E1 m1) ([[c2]] E2 m2)).\n  intros m1 m2 Hm.\n  eapply elift_weaken; [ | | apply (@elift_true _ _ ([[c1]] E1 m1) ([[c2]] E2 m2)) ].\n    auto.\n    apply Uplus_le_compat; Usimpl.\n      exact (proj1 (H _ _ _ Hm)).\n      exact (proj2 (H _ _ _ Hm)).\n    exact (proj1 (H0 _ _ _ Hm)).\n    exact (proj2 (H0 _ _ _ Hm)).\n Qed.\n\n\n Lemma dist_prg_trueR_lossless: forall (P:mem_rel) E1 c1 E2 c2,\n   lossless E1 c1 -> \n   lossless E2 c2 -> \n   dist_prg P E1 c1 E2 c2 trueR (fzero _).\n Proof.\n  intros.\n  apply dist_prg_weaken with P trueR (fun k => [1-] fone _ k + [1-] fone _ k).\n    trivial.\n    trivial.\n    unfold fzero, fone; refine (ford_le_intro _); intro k; rewrite Uinv_one; auto.\n    apply dist_prg_trueR.\n      intros k m1 m2 Hm; split; [ rewrite (H _ m1) | rewrite (H0 _ m2) ]; trivial.\n      intros k m1 m2 Hm; split; [ rewrite (H _ m1) | rewrite (H0 _ m2) ]; auto.\n Qed.\n\n\n Lemma dist_prg_falseR: forall E1 c1 E2 c2 Q,\n  dist_prg falseR E1 c1 E2 c2 Q (fzero _).\n Proof.\n  unfold dist_prg; intros.\n  exists (fun _ _ => distr0 _).\n  unfold falseR; intros m1 m2 H; tauto.\n Qed.\n\n Hint Resolve dist_prg_falseR.\n\n\n Lemma dist_prg_transp: forall P E1 c1 E2 c2 Q ep,\n   dist_prg (transpR P) E2 c2 E1 c1 (transpR Q) ep ->\n   dist_prg P E1 c1 E2 c2 Q ep.\n Proof.\n  unfold dist_prg, transpR; intros.\n  destruct (H k) as [d Hd]; clear H.\n  exists (fun m1 m2 => Mlet (d m2 m1) (fun mm => Munit (snd mm, fst mm))).\n  intros.\n  apply elift_transp.\n  apply elift_stable_eq with (5:=Hd _ _ H); auto.\n    rewrite Mcomp, <-(Mext (d m2 m1)) at 1.\n    apply Mlet_eq_compat; trivial.\n    refine (ford_eq_intro _); intros (m1',m2'); auto.\n Qed.\n\n\n Lemma dist_prg_sym :  forall P E1 c1 E2 c2 Q ep,\n  symMR P ->\n  symMR Q ->\n  dist_prg P E2 c2 E1 c1 Q ep ->\n  dist_prg P E1 c1 E2 c2 Q ep.\n Proof.\n  intros.\n  apply dist_prg_transp.\n  unfold symMR in *; rewrite H, H0; trivial.\n Qed.\n\n\n Lemma dist_prg_case: forall  (P P':mem_rel) E1 c1 E2 c2 Q ep,\n   decMR P' ->\n   dist_prg (P /-\\ P') E1 c1 E2 c2 Q ep ->\n   dist_prg (P /-\\ ~-P') E1 c1 E2 c2 Q ep ->\n   dist_prg P E1 c1 E2 c2 Q ep. \n Proof.\n  unfold andR, notR, dist_prg; intros.\n  destruct (H k) as (dt,Hdt); destruct (H0 k) as (df,Hdf); clear H H0.\n  exists (fun m1 m2 => if X k m1 m2 then dt m1 m2 else df m1 m2); intros.\n  destruct (X k m1 m2); auto.\n Qed.\n\n\n Lemma dist_prg_nil: forall P E1 E2, \n   dist_prg P E1 nil E2 nil P (fzero _).\n Proof.\n  unfold dist_prg; intros.\n  exists (fun m1 m2 => Munit (m1, m2)); intros.\n  repeat rewrite deno_nil. \n  apply (elift_Munit _ _ _ H).\n Qed.\n\n\n Lemma dist_prg_seq: forall P E1 c1 E2 c2 Q' ep Q c1' c2' ep',\n   decMR Q' ->\n   dist_prg P E1 c1  E2 c2 Q' ep ->\n   dist_prg Q' E1 c1' E2 c2' Q ep' ->\n   dist_prg P E1 (c1 ++ c1') E2 (c2 ++ c2') Q (fplus ep' ep).\n Proof.\n   unfold dist_prg; intros.\n   destruct (H k) as (d, Hd); destruct (H0 k) as (d', Hd'); clear H H0.\n   exists (fun m1 m2 => Mlet (d m1 m2) (fun p => d' (fst p) (snd p))). \n     intros.\n     repeat rewrite deno_app.\n     apply elift_Mlet with (Q' k); auto.\n       exists (carac (fun mm => X k (fst mm) (snd mm))).\n         apply (cover_dec (fun mm => X k (fst mm) (snd mm))).\n         eexists; apply (discr_srange (elift_deno_witness_discr (Hd _ _ H)) _ \n           (cover_eq_prod _ _ (@mem_eqU_spec k) (@mem_eqU_spec k))).\n Qed.\n\n\n Lemma dist_prg_trans_l : forall (P1 P2 Q1 Q2 Q3:mem_rel) E1 c1 E2 c2 E3 c3 ep ep',\n  decMR P2 ->\n  refl_supMR2 P2 P1 ->\n  (forall k x y z, Q1 k x y -> Q2 k y z -> Q3 k x z) -> \n  dist_prg P1 E1 c1 E2 c2 Q1 ep-> \n  dist_prg P2 E2 c2 E3 c3 Q2 ep'->\n  dist_prg P2 E1 c1 E3 c3 Q3 (fplus ep ep').\n Proof.\n  intros.\n  intros k; destruct (H1 k) as (d, Hd); destruct (H2 k) as (d',Hd').\n  exists (\n   fun m1 m3 =>\n    match X k m1 m3 with\n    | left _ =>\n        dd' (@mem_eqU k) (d m1 m1) (d' m1 m3) ([[c2]] E2 m1)\n    | _ => distr0 _\n    end).  \n  intros m1 m3 HP2.\n  destruct (X k m1 m3); simpl.\n    (* P m1 m3 *)\n    apply elift_trans_discr with (P:=Q1 k) (Q:=Q2 k). \n      apply mem_eqU_spec.\n      apply H0.\n      apply (Hd _ _ (H _ _ _ p)).\n      apply (Hd' _ _ p).\n      apply discr_ext with (d1:=[[c2]] E2 m1).\n        intros f Hf; apply (proj2 (el_supp_r (Hd _ _ (H _ _ _ p)) f) Hf).\n        apply sem_discr.\n      apply discr_ext with (d1:=[[c2]] E2 m1).\n        intros f Hf; apply (proj2 (el_supp_l (Hd' _ _ p) f) Hf).\n        apply sem_discr.\n    (* ~P m1 m3 *)\n    tauto.\n Qed.\n\n\n Lemma dist_prg_trans_r : forall (P1 P2 Q1 Q2 Q3:mem_rel) E1 c1 E2 c2 E3 c3 ep ep',\n  decMR P1 ->\n  refl_supMR2 (transpR P1) (transpR P2) ->\n  (forall k x y z, Q1 k x y -> Q2 k y z -> Q3 k x z) -> \n  dist_prg P1 E1 c1 E2 c2 Q1 ep -> \n  dist_prg P2 E2 c2 E3 c3 Q2 ep' ->\n  dist_prg P1 E1 c1 E3 c3 Q3 (fplus ep' ep).\n Proof.\n  intros; apply dist_prg_transp.\n  apply dist_prg_trans_l with (P1 := transpR P2) (P2:=transpR P1)\n   (Q1 := transpR Q2) (Q2 := transpR Q1) (E2 := E2) (c2:= c2).\n  auto. \n  trivial.\n  unfold transpR; intros; eapply H0; eauto.\n  apply dist_prg_transp; repeat rewrite transpR_transpR; trivial.\n  apply dist_prg_transp; repeat rewrite transpR_transpR; trivial.\n Qed.\n\n\n Lemma dist_prg_cond_l : forall P E1 e c c' E2 c2 Q ep,\n  dist_prg (P /-\\ EP1 e) E1 c E2 c2 Q ep ->\n  dist_prg (P /-\\ ~- EP1 e) E1 c' E2 c2 Q ep ->\n  dist_prg P E1 [If e then c else c'] E2 c2 Q ep.\n Proof.\n  unfold dist_prg, andR, notR, EP1, is_true.\n  intros P E3 e1 c c' E4 c2 Q ep Ht Hf k.\n  destruct (Ht k) as (dt,Hdt); destruct (Hf k) as (df,Hdf); clear Ht Hf.\n  exists (fun m1 m2 => if E.eval_expr e1 m1 then dt m1 m2  else df m1 m2). \n  intros.\n  repeat rewrite deno_cond.\n  case_eq (E.eval_expr e1 m1); intros Heq;\n   [ apply Hdt | apply Hdf ]; (split; [ | rewrite Heq]; auto).\n Qed.\n\n\n Lemma dist_prg_cond_r :  forall P E1 c1 E2 e c c' Q ep,\n  dist_prg (P /-\\ EP2 e) E1 c1 E2 c Q ep ->\n  dist_prg (P /-\\ ~- EP2 e) E1 c1 E2 c' Q ep ->\n  dist_prg P E1 c1 E2 [If e then c else c'] Q ep.\n Proof.\n  unfold dist_prg, andR, notR, EP2, is_true.\n  intros P E3 c c' e E4 c2 Q ep Ht Hf k.\n  destruct (Ht k) as (dt,Hdt); destruct (Hf k) as (df,Hdf); clear Ht Hf.\n  exists (fun m1 m2 => if E.eval_expr e m2 then dt m1 m2  else df m1 m2). \n  intros.\n  repeat rewrite deno_cond.\n  case_eq (E.eval_expr e m2); intros Heq;\n   [ apply Hdt | apply Hdf ]; (split; [ | rewrite Heq]; auto).\n Qed.\n\n\n Lemma dist_prg_cond : forall P Q E1 (e1:E.expr T.Bool) c1 c2 E2 (e2:E.expr T.Bool) c3 c4 ep,\n  dist_prg (P /-\\ (EP1 e1 /-\\ EP2 e2)) E1 c1 E2 c3 Q ep ->\n  dist_prg (P /-\\ (~- EP1 e1 /-\\ ~- EP2 e2)) E1 c2 E2 c4 Q ep ->\n  (forall k m1 m2, P k m1 m2 -> E.eval_expr e1 m1 = E.eval_expr e2 m2) ->\n  dist_prg P E1 [If e1 then c1 else c2] E2 [If e2 then c3 else c4] Q ep.\n Proof.\n  intros; apply dist_prg_cond_l; apply dist_prg_cond_r.\n  simplMR; trivial.\n  apply dist_prg_weaken with falseR Q (fzero _); auto; unfold EP1, EP2.\n    intros k m1 m2 ((H2, H3), H4); apply H4; erewrite <-H1; eauto.\n  apply dist_prg_weaken with falseR Q (fzero _); auto; unfold EP1, EP2.\n    intros k m1 m2 ((H2, H3), H4); apply H3; erewrite H1; eauto.\n  simplMR; trivial.\n Qed.\n\n\n Lemma dist_prg_assign: forall E1 (t1 : T.type) (x1 : Var.var t1) \n   (e1 : E.expr t1) E2 (t2 : T.type) (x2 : Var.var t2) (e2 : E.expr t2)  Q,\n    dist_prg (upd_para Q x1 e1 x2 e2) E1 [x1 <- e1] E2 [x2 <- e2] Q (fzero _).\n Proof.\n  unfold dist_prg, upd_para; intros. \n  exists (fun m1 m2 => Munit (m1{!x1<-- E.eval_expr e1 m1!}, m2{!x2<--E.eval_expr e2 m2!})). \n  intros.\n  repeat rewrite deno_assign; auto using elift_Munit.\n Qed.\n\n\n(*\n Lemma dist_prg_failure_events: forall (P:mem_rel) E1 c1 E2 c2 (Q:mem_rel) (ep ep1: nat -o> U)\n  (bad1 bad2: Var.var T.Bool),\n  (forall k (m1 m2:Mem.t k), P _ m1 m2 -> Pr E1 c1 m1 (EP k bad1) + Pr E2 c2 m2 (EP k bad2) <= ep k) ->\n   dist_prg P E1 c1 E2 c2 ((~-EP1 bad1 \\-/ ~-EP2 bad2) |-> Q) ep1 ->\n   dist_prg P E1 c1 E2 c2 Q (fplus (fplus ep1 ep) ep1).\n Proof.\n  unfold dist_prg;  intros.\n  destruct (H0 k) as [d Hd]; clear H0.\n  exists (fun m1 m2 => drestr (d m1 m2) (fun mm => if andb (fst mm bad1) (snd mm bad2) then false else true)).\n  intros m1 m2 Hm.\n  constructor.\n    (* dist *)\n    intros.\n    rewrite (Uabs_diff_triangle_ineq _ (mu ([[c1]] E1 m1) f) (mu (d m1 m2) (fun x => f (fst x)))).\n    rewrite (Uabs_diff_triangle_ineq _ (mu ([[c2]] E2 m2) g) (mu (d m1 m2) (fun x => g (snd x)))).\n    match goal with |- (?A + ?B) + (?C + ?D) <= _ =>\n      rewrite <-(Uplus_assoc A), (Uplus_sym B), Uplus_assoc, (Uplus_assoc A), <-(Uplus_assoc), (Uplus_sym D)\n    end.\n    apply Uplus_le_compat.\n      rewrite mu_drestr, (Uabs_diff_sym _ (mu _ (fun x => f (fst x)))), Uabs_diff_restr.\n      rewrite mu_drestr, (Uabs_diff_sym _ (mu _ (fun x => g (snd x)))), Uabs_diff_restr.\n      transitivity ( mu (d m1 m2) (fun x => charfun (EP k bad1) (fst x)) + \n        mu (d m1 m2) (fun x => charfun (EP k bad2) (snd x))).\n        apply Uplus_le_compat; unfold charfun, restr, EP, negP;\n          (apply mu_le_compat; [ trivial | simpl ]; refine (ford_le_intro _); \n            intro mm; case (fst mm bad1); case (snd mm bad2); simpl; auto).\n      unfold fplus; rewrite <-(H _ _ _ Hm).\n      apply Uplus_le_minus.\n      rewrite <-(el_dist (Hd _ _  Hm) (charfun (EP k bad1)) (charfun (EP k bad2))).\n      rewrite <-Uabs_diff_plus; apply Ule_plus_right.\n      apply (el_dist (Hd _ _ Hm)).\n    (* range *)\n    unfold drestr; apply range_Mlet with (1:=el_range (Hd _ _ Hm)).\n    unfold prodP, notR, impR, orR, EP1, EP2; intros (m1',m2') Hm'; \n     unfold fst, snd in *; generalize Hm'; simpl.\n    case (m1' bad1); case (m2' bad2); intros Hbad; simpl. \n      apply distr0_range; trivial.\n      apply range_Munit; apply Hbad; right; discriminate.\n      apply range_Munit; apply Hbad; left; discriminate.\n      apply range_Munit; apply Hbad; left; discriminate.\n Qed.\n*)\n\n  \n Lemma equiv_dist_prg: forall (P:mem_rel) E1 c1 E2 c2 (Q:mem_rel),\n   dist_prg P E1 c1 E2 c2 Q (fzero _) <-> equiv P E1 c1 E2 c2 Q.\n Proof.\n  unfold equiv, dist_prg; split; intros.\n    (* dist_prg ==> equiv *)\n    destruct (H k) as [d Hd]; clear H.\n    exists d.\n      intros m1 m2 H; rewrite <-lift_elift; exact (Hd _ _ H).\n    (* equiv ==> dist_prg *)\n    destruct (H k) as [d Hd]; clear H.\n    exists d.\n      intros m1 m2 H; rewrite lift_elift; exact (Hd _ _ H).\n Qed.\n\n\n Lemma dist_prg_random_permut: forall (Q:mem_rel) E1 t (x1:Var.var t) (D1:E.support t) \n   E2 (x2: Var.var t) (D2:E.support t) (h:forall k, Mem.t k -> Mem.t k -> T.interp k t -> T.interp k t),\n  dist_prg \n   ((permut_support h D1 D2) /-\\ (fun k m1 m2 => forall v, In v (E.eval_support D2 m2) -> \n     Q k (m1{!x1 <-- h k m1 m2 v!}) (m2{!x2 <-- v!})))\n   E1 [x1 <$- D1] E2 [x2 <$- D2] Q (fzero _).\n Proof.\n  intros.\n  rewrite equiv_dist_prg.\n  apply equiv_random_permut. \n Qed.\n\n\n Lemma dist_prg_while : forall (P:mem_rel) E1 (e1:E.expr T.Bool) c1 E2 (e2:E.expr T.Bool) c2,\n  (forall k m1 m2, P k m1 m2 -> E.eval_expr e1 m1 = E.eval_expr e2 m2) ->\n  dist_prg (P /-\\ EP1 e1 /-\\ EP2 e2) E1 c1 E2 c2 P (fzero _) -> \n  dist_prg P E1 [while e1 do c1] E2 [while e2 do c2] (P /-\\ ~-EP1 e1 /-\\ ~-EP2 e2) (fzero _).\n Proof.\n  intros.\n  rewrite equiv_dist_prg.\n  apply (equiv_while H).\n  rewrite <-equiv_dist_prg.\n  assumption.\n Qed.\n\n    \n Section For_loop_rule.\n \n  Variables i : E.expr T.Nat.\n  \n (* [q] is a constant expression *)\n  Variable q: E.expr T.Nat.\n  Variable q_interp : nat -> nat.\n  Hypothesis Hq_cte : forall k (m:Mem.t k), E.eval_expr q m = q_interp k.\n\n  Variables c1 c2 : cmd.\n  Variables e1 e2 : env.\n\n  Variables I: mem_rel.\n\n  (* First argument is the security parameter *)\n  Variable h : nat -> nat -o> U.\n\n  Hypothesis Hc: forall n:nat, \n    dist_prg \n    (I /-\\ EP1 (i=?=n) /-\\ EP2 (i=?=n)) \n    e1 c1 e2 c2 \n    (I /-\\ EP1 (i=?=S n) /-\\ EP2 (i=?=S n))\n    (fun k => h k n).\n\n\n  Variable P1 P2: forall k, Mem.t k -> Prop.\n\n  Hypothesis H_P : forall k (m1 m2:Mem.t k), I m1 m2 -> P1 m1 /\\ P2 m2.\n\n  Hypothesis Hran1: forall k (m:Mem.t k),\n    P1 m -> \n    range (fun m' => E.eval_expr i m' = S (E.eval_expr i m) /\\ P1 m') (([[c1]]) e1 m).\n  Hypothesis Hran2: forall k (m:Mem.t k),\n    P2 m -> \n    range (fun m' => E.eval_expr i m' = S (E.eval_expr i m) /\\ P2 m')  (([[c2]]) e2 m).\n\n  Hypothesis I_dec: decMR I.\n\n\n  Lemma cover_prec: forall (n k:nat),\n    cover (prodP ((I /-\\ EP1 (i =?= n) /-\\ EP2 (i =?= n)) k )) \n     (fun mm => (fun z => if I_dec (fst z) (snd z) then 1 else 0) mm * (\n     ((fun z => if nat_eqb (E.eval_expr i (fst z)) n then 1 else 0) mm) * \n     ((fun z => if nat_eqb (E.eval_expr i (snd z)) n then 1 else 0) mm))).\n  Proof.\n   intros; unfold prodP, andR.\n   repeat apply cover_inter_mult.\n     apply  (cover_dec (fun mm => @I_dec k (fst mm) (snd mm))).\n     unfold cover; unfold EP1; simpl; unfold O.eval_op; simpl.\n     intro mm; generalize (nat_eqb_spec (E.eval_expr i (fst mm)) n);\n     case (nat_eqb (E.eval_expr i (fst mm)) n); split; intros; trivial.\n       generalize is_true_true; tauto.\n       discriminate.\n     unfold cover; unfold EP2; simpl; unfold O.eval_op; simpl.\n     intro mm; generalize (nat_eqb_spec (E.eval_expr i (fst mm)) n);\n     case (nat_eqb (E.eval_expr i (snd mm)) n); split; intros; trivial.\n       generalize is_true_true; tauto.\n       discriminate.\n Qed.\n\n\n (* REMARK: wasn't able to weaken the poscondition in [Hc] \n    using [Hran1], [Hran2] and [H_P] *)\n\n  Lemma dist_prg_for_loop :  dist_prg \n   (I /-\\ EP1 (i=?=0%nat) /-\\ EP2 (i=?=0%nat)) \n   e1 [ while (i <! q) do c1 ] e2 [ while (i <! q) do c2 ] \n   (I /-\\ EP1 (i=?=q) /-\\ EP2 (i=?=q))  \n   (fun k => sigma (h k) (q_interp k)).\n  Proof.\n   unfold dist_prg; intros.\n   cut (exists d: Mem.t k -> Mem.t k -> Distr (Mem.t k * Mem.t k),\n     forall m1 m2 : Mem.t k,\n     (I /-\\ EP1 (i =?= 0%nat) /-\\ EP2 (i =?= 0%nat)) k m1 m2 ->\n     elift ((I /-\\ EP1 (i =?= q_interp k) /-\\ EP2 (i =?= q_interp k)) k) \n       (d m1 m2) (([[ [while i <! q_interp k do c1] ]]) e1 m1)\n       (([[ [while i <! q_interp k do c2] ]]) e2 m2) ((sigma (h k)) (q_interp k))).\n     intros [d Hd].\n     exists d; intros m1 m2 Hm.\n     eapply elift_weaken with (P:=(I /-\\ EP1 (i =?= q_interp k) /-\\ EP2 (i =?= q_interp k)) k).\n       intros m1' m2' [HI [H1 H2] ]; repeat split; unfold EP1, EP2 in *.\n         trivial.\n         rewrite <-(Hq_cte m1') in H1; apply H1.\n         rewrite <-(Hq_cte m2') in H2; apply H2.\n       apply Ole_refl.\n     eapply elift_stable_eq with (5:=Hd _ _ Hm); trivial.\n     apply eq_distr_intro; intro f.\n     apply while_eq_guard_compat_elim. \n     intro m'; change (leb (E.eval_expr i m' + 1) (q_interp k) = \n       leb (E.eval_expr i m' + 1) (E.eval_expr q m')); rewrite Hq_cte; trivial.\n     apply eq_distr_intro; intro f.\n     apply while_eq_guard_compat_elim. \n     intro m'; change (leb (E.eval_expr i m' + 1) (q_interp k) = \n       leb (E.eval_expr i m' + 1) (E.eval_expr q m')); rewrite Hq_cte; trivial.\n\n   induction (q_interp k).\n     (* base case *)\n     exists (fun m1 m2 => Munit (m1,m2)).\n     intros m1 m2 Hm; constructor.\n       (* dist *)\n       intros f g.\n       repeat rewrite deno_while_elim, deno_cond_elim.\n       replace (@E.eval_expr _ T.Bool (i <! 0) m1) with false by \n         (symmetry; apply (leb_correct_conv 0%nat (E.eval_expr i m1 + 1)); omega). \n       replace (@E.eval_expr _ T.Bool (i <! 0) m2) with false by \n         (symmetry; apply (leb_correct_conv 0%nat (E.eval_expr i m2 + 1)); omega). \n       repeat rewrite deno_nil_elim, Munit_eq, Uabs_diff_compat_eq; auto.\n       (* range *)\n       apply range_Munit; assumption.\n       (* supp *)\n       intro f.\n       rewrite deno_while_elim, deno_cond_elim.\n       replace (@E.eval_expr _ T.Bool (i <! 0) m1) with false by \n         (symmetry; apply (leb_correct_conv 0%nat (E.eval_expr i m1 + 1)); omega). \n       rewrite deno_nil_elim, Munit_eq; auto.\n       intro g.\n       rewrite deno_while_elim, deno_cond_elim.\n       replace (@E.eval_expr _ T.Bool (i <! 0) m2) with false by \n         (symmetry; apply (leb_correct_conv 0%nat (E.eval_expr i m2 + 1)); omega). \n       rewrite deno_nil_elim, Munit_eq; auto.\n     (* inductive case *)\n      assert (H1: forall (m:Mem.t k) f, P1 m -> E.eval_expr i m = 0%nat -> \n        mu ([[ [while i <! S n do c1] ]] e1 m) f == \n        mu ([[ [while i <! n do c1] ]] e1 m) (fun m' => mu ([[c1]] e1 m') f)).\n        intros.\n         rewrite <-(deno_cons_elim e1 (while i <! n do c1) c1 m f).\n         apply (init_for_loop_tail_unroll _ _ P1 m _ Hran1 H H0).  \n      assert (H2: forall (m:Mem.t k) f, P2 m -> E.eval_expr i m = 0%nat -> \n        mu ([[ [while i <! S n do c2] ]] e2 m) f == \n        mu ([[ [while i <! n do c2] ]] e2 m) (fun m' => mu ([[c2]] e2 m') f)).\n        intros.\n         rewrite <-(deno_cons_elim e2 (while i <! n do c2) c2 m f).\n         apply (init_for_loop_tail_unroll _ _ P2 m _ Hran2 H H0).\n       \n\n\n     destruct IHn as [d Hd].\n     destruct (Hc n k) as [d' Hd']; clear Hc.\n     exists (fun m1 m2 => Mlet (d m1 m2) (fun mm => d' (fst mm) (snd mm))).\n     intros m1 m2 Hm; constructor.\n\n       (* dist *)\n       intros f g.\n       set (Hm':=Hm).\n       destruct Hm' as [HI [Hil Hir] ]; unfold EP1 in Hil; unfold EP2 in Hir.\n       setoid_rewrite (eval_eq m1 i 0%nat) in Hil; apply nat_eqb_true in Hil.\n       setoid_rewrite (eval_eq m2 i 0%nat) in Hir; apply nat_eqb_true in Hir.\n       rewrite (H1 _ _ (proj1 (H_P HI)) Hil), (H2 _ _ (proj2 (H_P HI)) Hir).\n       rewrite (Uabs_diff_triangle_ineq _ \n         (mu ([[ [while i <! n do c1] ]] e1 m1) (fun m => mu ([[c1]] e1 m) f))\n         (mu (d m1 m2) (fun x => mu ([[c1]] e1 (fst x)) f))).\n       rewrite (Uabs_diff_triangle_ineq _ \n         (mu ([[ [while i <! n do c2] ]] e2 m2) (fun m => mu ([[c2]] e2 m) g))\n         (mu (d m1 m2) (fun x => mu ([[c2]] e2 (snd x)) g))).\n       match goal with |- (?A + ?B) + (?C + ?D) <= _ =>\n         rewrite <-(Uplus_assoc A), (Uplus_sym B), Uplus_assoc, (Uplus_assoc A), <-(Uplus_assoc), (Uplus_sym D)\n       end.\n       rewrite sigma_S; apply Uplus_le_compat.\n         (* left inequality *)\n         apply (Ueq_orc (h k n) 1); [apply Ule_class | | ]; intro Hhn.\n           (* case [h n = 1] *)\n           rewrite Hhn; auto.\n           (* case [h n < 1] *)\n           repeat rewrite Mlet_simpl.\n           rewrite Uabs_diff_mu_compat, Uabs_diff_mu_compat, \n             <-(mu_stable_plus_range (el_range (Hd _ _ Hm))).\n           rewrite <-(mu_cte_le (d m1 m2) (h k n)); apply (range_le (el_range (Hd _ _ Hm))).\n             intros (m1',m2') Hm'; unfold fplus, fcte, fabs_diff.\n             apply (el_dist (Hd' _ _ Hm')).\n             intros (m1',m2') Hm'; unfold fabs_diff.\n             apply Uplus_lt_Uinv; apply Ule_lt_trans with (h k n); [ | auto ].\n             rewrite Uplus_sym; apply (el_dist (Hd' _ _ Hm')).\n         (* right inequality *)\n         apply (el_dist (Hd _ _ Hm) (fun m => mu ([[c1]] e1 m) f) (fun m => mu ([[c2]] e2 m) g)).\n\n    (* range *)\n    apply range_Mlet with (1:=el_range (Hd _ _ Hm)).\n    intros (m1',m2') Hm'; apply (el_range (Hd' _ _ Hm')).\n\n    (* supp_l *)\n    assert (Hd_srange: exists R, srange R (d m1 m2)) by\n       (eexists; apply (discr_srange  (elift_deno_witness_discr (Hd _ _ Hm)) _ \n         (cover_eq_prod _ _ (@mem_eqU_spec k) (@mem_eqU_spec k)))).\n    destruct Hd_srange as (R,(Hd_ran,Hd_dran)).\n    intro f.\n    set (Hm':=Hm); destruct Hm' as [HI [Hil _] ]; unfold EP1 in Hil.\n    setoid_rewrite (eval_eq m1 i 0%nat) in Hil; apply nat_eqb_true in Hil.\n    rewrite Mlet_simpl, (H1 _ _ (proj1 (H_P HI)) Hil).\n    generalize (el_supp_l (Hd _ _ Hm)); intro Hl.\n    split; intro H.\n      (*  *)\n      rewrite <-Hl.\n      symmetry; apply Hd_ran.\n      intros (m1',m2') Hm'; simpl.\n      assert (Hm'_2: (I /-\\ EP1 (i =?= n) /-\\ EP2 (i =?= n)) _ m1' m2') by\n        refine (drange_range (@cover_prec n k) (el_range (Hd _ _ Hm)) Hd_dran _ Hm').\n      destruct (Hd' _ _ Hm'_2) as (_, Hran', Hsupp', _); simpl in *.  \n      symmetry; rewrite <-Hsupp'.\n      symmetry; apply (Hd_dran _ (Oeq_sym H) _ Hm').\n      (*  *)\n      rewrite <-Hl in H.\n      symmetry; apply Hd_ran.\n      intros (m1',m2') Hm'; simpl.\n      assert (Hm'_2: (I /-\\ EP1 (i =?= n) /-\\ EP2 (i =?= n)) _ m1' m2') by\n        refine (drange_range (@cover_prec n k) (el_range (Hd _ _ Hm)) Hd_dran _ Hm').\n      destruct (Hd' _ _ Hm'_2) as (_, Hran', Hsupp', _); simpl in *.  \n      symmetry; rewrite Hsupp'.\n      symmetry; apply (Hd_dran _ (Oeq_sym H) _ Hm').\n\n    (* supp_r *)  \n    assert (Hd_srange: exists R, srange R (d m1 m2)) by\n       (eexists; apply (discr_srange  (elift_deno_witness_discr (Hd _ _ Hm)) _ \n         (cover_eq_prod _ _ (@mem_eqU_spec k) (@mem_eqU_spec k)))).\n    destruct Hd_srange as (R,(Hd_ran,Hd_dran)).\n    intro g.\n    set (Hm':=Hm); destruct Hm' as [HI [_ Hir] ]; unfold EP2 in Hir.\n    setoid_rewrite (eval_eq m2 i 0%nat) in Hir; apply nat_eqb_true in Hir.\n    rewrite Mlet_simpl, (H2 _ _ (proj2 (H_P HI)) Hir).\n    generalize (el_supp_r (Hd _ _ Hm)); intro Hr.\n    split; intro H.\n      (*  *)\n      rewrite <-Hr.\n      symmetry; apply Hd_ran.\n      intros (m1',m2') Hm'; simpl.\n      assert (Hm'_2: (I /-\\ EP1 (i =?= n) /-\\ EP2 (i =?= n)) _ m1' m2') by\n        refine (drange_range (@cover_prec n k) (el_range (Hd _ _ Hm)) Hd_dran _ Hm').\n      destruct (Hd' _ _ Hm'_2) as (_, Hran', _, Hsupp'); simpl in *.  \n      symmetry; rewrite <-Hsupp'.\n      symmetry; apply (Hd_dran _ (Oeq_sym H) _ Hm').\n      (*  *)\n      rewrite <-Hr in H.\n      symmetry; apply Hd_ran.\n      intros (m1',m2') Hm'; simpl.\n      assert (Hm'_2: (I /-\\ EP1 (i =?= n) /-\\ EP2 (i =?= n)) _ m1' m2') by\n        refine (drange_range (@cover_prec n k) (el_range (Hd _ _ Hm)) Hd_dran _ Hm').\n      destruct (Hd' _ _ Hm'_2) as (_, Hran', _, Hsupp'); simpl in *.  \n      symmetry; rewrite Hsupp'.\n      symmetry; apply (Hd_dran _ (Oeq_sym H) _ Hm').\n Qed.\n\nEnd For_loop_rule.\n\n\n\nSection While_loop_rule.\n\n  Variables c1 c2 : cmd.\n  Variables e1 e2 : env.\n\n  Variables I P1 P2: mem_rel.\n  Variables b1 b2: E.expr T.Bool.\n\n\n  Hypothesis I_b: forall k (m1 m2:Mem.t k), \n   I m1 m2 -> E.eval_expr b1 m1 = E.eval_expr b2 m2. \n \n  Hypothesis I_dec: decMR I.\n\n  Hypothesis I_P: forall k (m1 m2:Mem.t k),\n    I m1 m2 -> P1 m1 m1 /\\ P2 m2 m2.\n\n  Variable ep: nat -o> U.\n  Hypothesis Hc:  \n    dist_prg (I /-\\ EP1 b1) e1 c1 e2 c2 I ep.\n\n\n  Variable q: nat.\n\n  Hypothesis H_while1:\n    dist_prg \n    (Meq /-\\ P1) \n    e1 [while b1 do c1]\n    e1 (unroll_while b1 c1 q)\n    (Meq /-\\ ~-EP2 b1) \n    (fzero _).\n\n  Hypothesis H_while2:\n    dist_prg \n    (Meq /-\\ P2) \n    e2 [while b2 do c2]\n    e2 (unroll_while b2 c2 q)\n    (Meq /-\\ ~-EP2 b2) \n    (fzero _).\n\n  Lemma while_rule: \n    dist_prg I e1 [while b1 do c1] e2  [while b2 do c2] (I /-\\ ~-EP1 b1) \n    (fun k => q */ ep k).\n  Proof.\n   apply dist_prg_weaken with I (I /-\\ ~-EP1 b1) (fplus (fzero _) (fplus (fzero _) \n      (fun k => q */ ep k))); trivial.\n     unfold fplus, fzero; refine (ford_le_intro _); intro m; auto.\n   apply dist_prg_trans_l  with (1:=I_dec) (4:=H_while1) (Q2:=I).\n     intros k m1 m2 Hm; split; [ trivial | apply (proj1 (I_P Hm)) ].\n     intros k m1 m2 m3 [H1 H2] H3; split; rewrite H1; trivial.\n   eapply dist_prg_trans_r  with (1:=I_dec) (5:=dist_prg_transp H_while2) (Q1:=I).\n     intros k m1 m2 Hm; split; [ trivial | apply (proj2 (I_P Hm)) ].\n     intros k m1 m2 m3 H1 [H2 _]; rewrite H2; trivial.\n\n   clear H_while1 H_while2.\n   induction q.\n     (* base case *)\n     intro k.\n     exists (fun m1 m2 => Munit (m1,m2)).\n     intros m1 m2 Hm; repeat rewrite deno_unroll_while_0.\n     constructor.\n       intros; simpl; repeat My_Usimpl; auto.\n       apply range_Munit; trivial.\n       auto.\n       auto.\n\n     (* inductive case *)\n     unfold unroll_while; fold (unroll_while b1 c1 n) (unroll_while b2 c2 n). \n     apply dist_prg_cond with (3:=I_b).\n       apply dist_prg_weaken with (I /-\\ EP1 b1) I (fplus (fun k => n */ ep k) ep).\n         rewrite <-andR_assoc; apply proj1_MR.\n         trivial.\n         unfold fplus; refine (ford_le_intro _); intro m; rewrite Uplus_sym; auto.\n       apply dist_prg_seq with I; trivial.\n       apply dist_prg_weaken with I I (fzero _).\n         apply proj1_MR.\n         trivial.\n         unfold fzero; refine (ford_le_intro _); intro m; trivial.\n       apply dist_prg_nil.\n Qed.\n\n End While_loop_rule.\n\n\n\n\n\n\n(*\nSection Adv_rule.\n\n\n  Variables i : E.expr T.Nat.\n\n  Variable X: Vset.t.\n  Hypothesis i_X: forall k (m1 m2: Mem.t k), \n    m1 =={X} m2 -> E.eval_expr i m1 = E.eval_expr i m2.\n\n  \n (* [q] is a constant expression *)\n  Variable q: E.expr T.Nat.\n  Variable q_interp : nat -> nat.\n  Hypothesis Hq_cte : forall k (m:Mem.t k), E.eval_expr q m = q_interp k.\n\n  Variables e1 e2 : env.\n\n  (* First argument is the security parameter *)\n  Variable h : nat -> nat -o> U.\n\n  Variable P:mem_rel.\n\n  Definition H_P (cl cr:cmd) := forall n:nat, \n    dist_prg \n    (Meq /-\\ EP1 (i=?=n) /-\\ EP2 (i=?=n) /-\\ P) \n    e1 cl e2 cr \n    (Meq /-\\ EP1 (i=?=S n) /-\\ EP2 (i=?=S n))\n    (fun k => h k n).\n\n  Definition H_nP (cl cr:cmd) := forall n:nat, \n    dist_prg \n    (Meq /-\\ EP1 (i=?=n) /-\\ EP2 (i=?=n) /-\\ ~-P) \n    e1 cl e2 cr \n    (Meq /-\\ EP1 (i=?=n) /-\\ EP2 (i=?=n))\n    (fzero _).\n\n\n  Variables (PrOrcl PrPriv:PrSet.t) (Gadv Gcomm:Vset.t).\n  Variable retT : T.type.\n  Variable A : Proc.proc retT.\n\n  Hypothesis A_wf : WFAdv PrOrcl PrPriv Gadv Gcomm e1 A.\n\n  Hypothesis Or_P: forall t (f:Proc.proc t), \n   PrSet.mem (BProc.mkP f) PrOrcl -> \n    H_P (proc_body e1 f) (proc_body e2 f).\n\n  Hypothesis Or_nP: forall t (f:Proc.proc t), \n   PrSet.mem (BProc.mkP f) PrOrcl -> \n    H_nP (proc_body e1 f) (proc_body e2 f).\n\n  Hypothesis Gadv_disj : Vset.disjoint X Gadv.\n\n(*\n  Variables y : Var.var retT.\n  Variable x : E.args (Proc.targs A).\n *)\n\n Lemma dist_prg_bounded_calls:  \n   dist_prg \n   (Meq /-\\ EP1 (i=?=0%nat) /-\\ EP2 (i=?=0%nat)) \n   e1 (proc_body e1 A)  e2 (proc_body e1 A) \n   (Meq /-\\ EP1 (i<=!q) /-\\ EP2 (i<=!q))  \n   (fun k => sigma (h k) (q_interp k)).\n Proof.\n  destruct A_wf as [O [HO1 HO2] ]; clear A_wf.\n  clear HO2.\n  induction HO1 using WFAdv_c_prop  with\n     (P:=fun I c' O (H: WFAdv_c PrOrcl PrPriv Gadv Gcomm e1 I c' O) =>\n       dist_prg (Meq /-\\ EP1 (i =?= 0%nat) /-\\ EP2 (i =?= 0%nat)) e1 c' e2 c'\n     (Meq /-\\ EP1 (i <=! q) /-\\ EP2 (i <=! q))\n     (fun k : nat => (sigma (h k)) (q_interp k)))\n    (P0:=fun I i' O (H:WFAdv_i PrOrcl PrPriv Gadv Gcomm e1 I i' O) =>  \n      dist_prg (Meq /-\\ EP1 (i =?= 0%nat) /-\\ EP2 (i =?= 0%nat)) e1 [i'] e2 [i']\n     (Meq /-\\ EP1 (i <=! q) /-\\ EP2 (i <=! q))\n     (fun k : nat => (sigma (h k)) (q_interp k))).\n\nrange_eq\n  Focus 2.\n  \n\n\n\n\n\n\n     (forall x, Vset.mem x I -> Var.is_local x) -> inv_bad [i]); intros; trivial.\n\n\n\n\n\n\n\n\n  Lemma dist_prg_for_loop :  dist_prg \n\nSection UptoBad.\n \n Definition forallP (A:Type) (P:A->Prop) (l:list A) :=\n  forall x, In x l -> P x.\n\n  Definition slossless E c := forallP (fun i => lossless E [i]) c. \n\n Lemma slossless_cons: forall E i c, slossless E (i::c) -> lossless E c.\n Proof.\n  induction c.\n    intros _.\n    admit.\n  Admitted.\n    \n    \n    \n  \n\n Lemma upto_bad_dist_prg: forall bad : Var.var T.Bool,\n   Var.is_global bad ->\n   forall (E1 E2 : env) (pi : upto_info bad E1 E2) (c1 c2 : cmd),\n   check_bad pi c1 c2 ->\n   slossless E2 c2 ->\n   forall (ep: nat-o>U),\n   (forall k (m:Mem.t k), Pr E2 c2 m (EP k bad) <= ep k) ->\n   dist_prg Meq E1 c1 E2 c2 Meq ep.\n Proof.\n  Opaque I.eqb deno.\n  intros bad Gbad E1 E2 pi.\n  induction c1 using I.cmd_ind with (Pi:=fun i => forall c2',\n   (*  preserves_bad bad pi [i] -> *)\n    preserves_bad bad pi c2' ->\n    upto_bad bad pi [i] c2' ->\n (*    lossless E2 c2' -> *)\n    forall ep' : nat -o> U,\n      (forall (k : nat) (m : Mem.t k), Pr E2 c2' m (EP k bad) <= ep' k) ->\n      dist_prg Meq E1 [i] E2 c2' Meq ep').\n  \n  intros c2 Hc2 H.\n  destruct c2; [discriminate H | ].\n  destruct i0; try discriminate H.\n  destruct i; destruct b; try discriminate H.\n\n\n\n  Focus 7.\n  (* cons *)\n    intros c2 H Hloss ep Hep.\n    unfold check_bad, is_true in H; repeat rewrite andb_true_iff in H; \n      destruct H as [ [Hp1 Hp2] H ].\n    destruct c2; [ destruct i; discriminate H | \n      destruct i; destruct i0; try discriminate H ].\n    destruct b; destruct b0; try discriminate H.\n      (* Assign *) \n      simpl in H; unfold is_true in H; apply orb_prop in H; destruct H.\n        (* case 1 *)\n        apply andb_prop in H; destruct H as [Heq1 Heq2].\n        generalize (I.eqb_spec (v <- e) (bad <- true)); rewrite Heq1; intro H1. \n        generalize (I.eqb_spec (v0 <- e0) (bad <- true)); rewrite Heq2; intro H2. \n        rewrite H1, H2 in *; clear H1 H2 Heq1 Heq2.\n        intro k; exists (fun m1 m2 => \n        prod_distr ([[ [bad <- true] ]] E1 m1) ([[ [bad <- true] ]] E2 m2)).\n        intros m1 m2 Hm.\n        apply elift_weaken with (Meq k) 1.\n          auto.\n          rewrite <-(Hep _ m2). \n          unfold Pr; rewrite deno_cons_elim, Mlet_simpl, deno_assign_elim.\n          simpl in Hp2; unfold is_true in Hp2;\n            apply andb_prop in Hp2; destruct Hp2 as [_ Hp2].\n          unfold charfun; rewrite <-(preserves_bad_spec Gbad (upto_pr2 pi) _ Hp2);\n            [ | unfold EP; simpl; rewrite Mem.get_upd_same; trivial ].\n          rewrite (slossless_cons Hloss (m2 {!bad <-- true!})); trivial. \n        constructor.\n          auto.\n          intros f Hf; simpl.\n          rewrite (deno_assign_elim _ _ _ m1), (deno_assign_elim _ _ _ m2).\n          apply Hf; rewrite Hm; apply Meq_refl.\n        (* case 2 *)\n        apply andb_prop in H; destruct H.\n        generalize (I.eqb_spec (v <- e) (v0 <- e0)); \n          rewrite H; clear H; intro H; rewrite H; clear H.  \n        apply dist_prg_weaken with (upd_para Meq v0 e0 v0 e0) Meq (fplus ep (fzero _)).\n          unfold upd_para; intros k m1 m2 Hm; rewrite Hm; apply Meq_refl.\n          auto.\n          unfold fplus; auto. \n        apply dist_prg_seq with (c1:=[v0 <- e0]) (c2:=[v0 <- e0]) (c1':=c1) (c2':=c2) (Q':=Meq). \n          apply dist_prg_assign.\n          apply IHc0.\n            unfold check_bad, is_true; repeat rewrite andb_true_iff; repeat split.  \n              simpl in Hp1; rewrite andb_true_iff in Hp1; destruct Hp1; assumption.\n              simpl in Hp2; rewrite andb_true_iff in Hp2; destruct Hp2; assumption.\n              assumption.\n              admit.\n              \n              \n\n\n\n              unfold lossless in *.\n              intros k m.\n              generalize (Hloss _ m).\n              rewrite deno_cons_elim, Mlet_simpl, deno_assign_elim.\n              \n\n\n        intro k; exists (fun m1 m2 => \n          prod_distr ([[ [v0 <- e0] ]] E1 m1) ([[ [v0 <- e0] ]] E2 m2)).\n      intros m1 m2 Hm; constructor.\n        intros.\n        rewrite prod_distr_fst, (lossless_assign _ _ _ m2), Umult_one_left, Uabs_diff_compat_eq.\n        rewrite prod_distr_snd, (lossless_assign _ _ _ m1), Umult_one_left, Uabs_diff_compat_eq.\n        auto.\n        intros f Hf; simpl.\n        rewrite (deno_assign_elim _ _ _ m1), (deno_assign_elim _ _ _ m2).\n        apply Hf.\n        apply HPQ with m1 m2; split; [ exact Hm | simpl ].\n          admit.\n\n        \n\n          \n\n\n          apply HPQ with m1 m2; split; simpl.\n          trivial.\n          admit.\n     \n        exists \n\n\n\n              \n\n              auto.\n            split.\n        \n        \n        \n        \n\n\n    (* Assign *)\n    Opaque I.eqb deno.\n    intros ep Hep.\n    simpl in H; unfold is_true in H; apply orb_prop in H; destruct H.\n      (* case 1 *)\n      apply andb_prop in H; destruct H as [Heq1 Heq2].\n      generalize (I.eqb_spec (v <- e) (bad <- true)); rewrite Heq1; intro H1. \n      generalize (I.eqb_spec (v0 <- e0) (bad <- true)); rewrite Heq2; intro H2. \n      rewrite H1, H2 in *; clear H1 H2 Heq1 Heq2.   \n      intro k; exists (fun m1 m2 => \n        prod_distr ([[ [bad <- true] ]] E1 m1) ([[ [bad <- true] ]] E2 m2)).\n      intros m1 m2 Hm.\n      apply elift_weaken with (Q k) 1.\n        auto.\n        rewrite <-(Hep _ m2).\n        unfold Pr; rewrite deno_cons_elim, Mlet_simpl, deno_assign_elim.\n        simpl in Hc2; unfold is_true in Hc2;\n          apply andb_prop in Hc2; destruct Hc2 as [_ Hc2].\n        unfold charfun; rewrite <-(preserves_bad_spec Gbad (upto_pr2 pi) _ Hc2);\n          [ | unfold EP; simpl; rewrite Mem.get_upd_same; trivial ].\n        generalize (Hloss _ m2); rewrite deno_cons_elim, Mlet_simpl, deno_assign_elim.\n        auto.\n      constructor.\n        auto.\n        intros f Hf; simpl.\n        rewrite (deno_assign_elim _ _ _ m1), (deno_assign_elim _ _ _ m2).\n        apply Hf.\n        apply HPQ with m1 m2; split; simpl.\n          trivial.\n          admit.\n      (* case 2 *)\n      apply andb_prop in H; destruct H.\n      destruct c2; try discriminate; clear H0.\n      generalize (I.eqb_spec (v <- e) (v0 <- e0)); \n        rewrite H; clear H; intro H; rewrite H; clear H.  \n      intro k; exists (fun m1 m2 => \n        prod_distr ([[ [v0 <- e0] ]] E1 m1) ([[ [v0 <- e0] ]] E2 m2)).\n      intros m1 m2 Hm; constructor.\n        intros.\n        rewrite prod_distr_fst, (lossless_assign _ _ _ m2), Umult_one_left, Uabs_diff_compat_eq.\n        rewrite prod_distr_snd, (lossless_assign _ _ _ m1), Umult_one_left, Uabs_diff_compat_eq.\n        auto.\n        intros f Hf; simpl.\n        rewrite (deno_assign_elim _ _ _ m1), (deno_assign_elim _ _ _ m2).\n        apply Hf.\n        apply HPQ with m1 m2; split; [ exact Hm | simpl ].\n          admit.\n\n\n    (* Random *)\n    intros ep Hep.\n    simpl in H; unfold is_true in H.\n    apply andb_prop in H; destruct H as [Heq Hc2'].\n    destruct c2; try discriminate.\n    generalize (I.eqb_spec (v <$- s) (v0 <$- s0)); \n      rewrite Heq; intro H; rewrite H.\n    intros k.\n    exists (fun m1 m2 => Mlet (sum_support (T.default k t0) \n      (E.eval_support s0 m1)) (fun v => Munit (m1{!v0<--v!}, m2{!v0<--v!}))).\n    intros m1 m2 Hm; constructor.\n      intros; repeat rewrite Mlet_simpl, deno_random_elim.\n      change ((Uabs_diff \n      (sum_dom (T.default k t0) (E.eval_support s0 m1) \n        (fun v => f (m1 {!v0 <-- v!})))\n      (sum_dom (T.default k t0) (E.eval_support s0 m1) \n        (fun v => f (m1 {!v0 <-- v!}))))  + \n      (Uabs_diff \n      (sum_dom (T.default k t0) (E.eval_support s0 m1) \n        (fun v => g (m2 {!v0 <-- v!})))\n      (sum_dom (T.default k t0) (E.eval_support s0 m2) \n        (fun v => g (m2 {!v0 <-- v!})))) <= ep k).\n      rewrite Uabs_diff_compat_eq, Uplus_zero_left.\n      rewrite <-(Upos (ep k)); apply Oeq_le; rewrite Uabs_diff_zero.\n      (* assume constant supports and apply [PermutP_refl] *)\n      admit.\n      intros f Hf; rewrite Mlet_simpl.\n      change (0 == sum_dom (T.default k t0) (E.eval_support s0 m1) \n        (fun v1 => f (m1 {!v0 <-- v1!}, m2 {!v0 <-- v1!}))).\n      symmetry; apply sum_dom_zero with (fun _ => True); [ trivial | ].\n      intros v1 _. symmetry; apply Hf.\n      apply HPQ with m1 m2; split; [ exact Hm | simpl ].\n      admit.\n\n\n\n    Focus 4.\n    (* nil *)\n    intros c2 H Hloss ep Hep.\n    simpl in H; destruct c2.\n    eapply dist_prg_weaken; [ | | | apply (dist_prg_nil P) ]; auto.\n      intros k m1 m2 Hm; apply HPQ with m1 m2; split; auto.\n    unfold check_bad in H;  repeat rewrite andb_false_r in H; discriminate H.\n\n\n    Focus 4.\n   \n        \n        \n\n\n\n Lemma upto_bad_dist_prg: forall (P Q:mem_rel),\n   (forall k (m1 m2 m1' m2': Mem.t k), P _ m1 m2 /\\ (Meq _ m1 m2 -> Meq _ m1' m2') -> Q _ m1' m2') ->\n   forall bad : Var.var T.Bool,\n   Var.is_global bad ->\n   forall (E1 E2 : env) (pi : upto_info bad E1 E2) (c1 c2 : cmd),\n   check_bad pi c1 c2 ->\n   lossless E2 c2 ->\n   forall (ep: nat-o>U),\n   (forall k (m:Mem.t k), Pr E2 c2 m (EP k bad) <= ep k) ->\n   dist_prg P E1 c1 E2 c2 Q ep.\n Proof.\n  intros P Q HPQ bad Gbad E1 E2 pi.\n  induction c1 using I.cmd_ind with (Pi:=fun i => forall c2',\n    preserves_bad bad pi [i] ->\n    preserves_bad bad pi c2' ->\n    upto_bad bad pi [i] c2' ->\n    lossless E2 c2' ->\n    forall ep' : nat -o> U,\n      (forall (k : nat) (m : Mem.t k), Pr E2 c2' m (EP k bad) <= ep' k) ->\n      dist_prg P E1 [i] E2 c2' Q ep').\n  \n  intros c2 Hi Hc2 H Hloss.\n  destruct c2; [discriminate H | ].\n  destruct i0; try discriminate H.\n  destruct i; destruct b; try discriminate H.\n\n    (* Assign *)\n    Opaque I.eqb deno.\n    intros ep Hep.\n    simpl in H; unfold is_true in H; apply orb_prop in H; destruct H.\n      (* case 1 *)\n      apply andb_prop in H; destruct H as [Heq1 Heq2].\n      generalize (I.eqb_spec (v <- e) (bad <- true)); rewrite Heq1; intro H1. \n      generalize (I.eqb_spec (v0 <- e0) (bad <- true)); rewrite Heq2; intro H2. \n      rewrite H1, H2 in *; clear H1 H2 Heq1 Heq2.   \n      intro k; exists (fun m1 m2 => \n        prod_distr ([[ [bad <- true] ]] E1 m1) ([[ [bad <- true] ]] E2 m2)).\n      intros m1 m2 Hm.\n      apply elift_weaken with (Q k) 1.\n        auto.\n        rewrite <-(Hep _ m2).\n        unfold Pr; rewrite deno_cons_elim, Mlet_simpl, deno_assign_elim.\n        simpl in Hc2; unfold is_true in Hc2;\n          apply andb_prop in Hc2; destruct Hc2 as [_ Hc2].\n        unfold charfun; rewrite <-(preserves_bad_spec Gbad (upto_pr2 pi) _ Hc2);\n          [ | unfold EP; simpl; rewrite Mem.get_upd_same; trivial ].\n        generalize (Hloss _ m2); rewrite deno_cons_elim, Mlet_simpl, deno_assign_elim.\n        auto.\n      constructor.\n        auto.\n        intros f Hf; simpl.\n        rewrite (deno_assign_elim _ _ _ m1), (deno_assign_elim _ _ _ m2).\n        apply Hf.\n        apply HPQ with m1 m2; split; simpl.\n          trivial.\n          admit.\n      (* case 2 *)\n      apply andb_prop in H; destruct H.\n      destruct c2; try discriminate; clear H0.\n      generalize (I.eqb_spec (v <- e) (v0 <- e0)); \n        rewrite H; clear H; intro H; rewrite H; clear H.  \n      intro k; exists (fun m1 m2 => \n        prod_distr ([[ [v0 <- e0] ]] E1 m1) ([[ [v0 <- e0] ]] E2 m2)).\n      intros m1 m2 Hm; constructor.\n        intros.\n        rewrite prod_distr_fst, (lossless_assign _ _ _ m2), Umult_one_left, Uabs_diff_compat_eq.\n        rewrite prod_distr_snd, (lossless_assign _ _ _ m1), Umult_one_left, Uabs_diff_compat_eq.\n        auto.\n        intros f Hf; simpl.\n        rewrite (deno_assign_elim _ _ _ m1), (deno_assign_elim _ _ _ m2).\n        apply Hf.\n        apply HPQ with m1 m2; split; [ exact Hm | simpl ].\n          admit.\n\n\n    (* Random *)\n    intros ep Hep.\n    simpl in H; unfold is_true in H.\n    apply andb_prop in H; destruct H as [Heq Hc2'].\n    destruct c2; try discriminate.\n    generalize (I.eqb_spec (v <$- s) (v0 <$- s0)); \n      rewrite Heq; intro H; rewrite H.\n    intros k.\n    exists (fun m1 m2 => Mlet (sum_support (T.default k t0) \n      (E.eval_support s0 m1)) (fun v => Munit (m1{!v0<--v!}, m2{!v0<--v!}))).\n    intros m1 m2 Hm; constructor.\n      intros; repeat rewrite Mlet_simpl, deno_random_elim.\n      change ((Uabs_diff \n      (sum_dom (T.default k t0) (E.eval_support s0 m1) \n        (fun v => f (m1 {!v0 <-- v!})))\n      (sum_dom (T.default k t0) (E.eval_support s0 m1) \n        (fun v => f (m1 {!v0 <-- v!}))))  + \n      (Uabs_diff \n      (sum_dom (T.default k t0) (E.eval_support s0 m1) \n        (fun v => g (m2 {!v0 <-- v!})))\n      (sum_dom (T.default k t0) (E.eval_support s0 m2) \n        (fun v => g (m2 {!v0 <-- v!})))) <= ep k).\n      rewrite Uabs_diff_compat_eq, Uplus_zero_left.\n      rewrite <-(Upos (ep k)); apply Oeq_le; rewrite Uabs_diff_zero.\n      (* assume constant supports and apply [PermutP_refl] *)\n      admit.\n      intros f Hf; rewrite Mlet_simpl.\n      change (0 == sum_dom (T.default k t0) (E.eval_support s0 m1) \n        (fun v1 => f (m1 {!v0 <-- v1!}, m2 {!v0 <-- v1!}))).\n      symmetry; apply sum_dom_zero with (fun _ => True); [ trivial | ].\n      intros v1 _. symmetry; apply Hf.\n      apply HPQ with m1 m2; split; [ exact Hm | simpl ].\n      admit.\n\n\n\n    Focus 4.\n    (* nil *)\n    intros c2 H Hloss ep Hep.\n    simpl in H; destruct c2.\n    eapply dist_prg_weaken; [ | | | apply (dist_prg_nil P) ]; auto.\n      intros k m1 m2 Hm; apply HPQ with m1 m2; split; auto.\n    unfold check_bad in H;  repeat rewrite andb_false_r in H; discriminate H.\n\n\n    Focus 4.\n    (* cons *)\n    intros c2 H Hloss ep Hep.\n    unfold check_bad, is_true in H; repeat rewrite andb_true_iff in H; destruct H as [ [Hp1 Hp2] H ].\n    destruct c2; [ destruct i; discriminate H | destruct i; destruct i0; try discriminate H ].\n\n      destruct b; destruct b0; try discriminate H.\n      \n\n      (* Assign *) \n      simpl in H; unfold is_true in H; apply orb_prop in H; destruct H.\n        (* case 1 *)\n        apply andb_prop in H; destruct H as [Heq1 Heq2].\n        generalize (I.eqb_spec (v <- e) (bad <- true)); rewrite Heq1; intro H1. \n        generalize (I.eqb_spec (v0 <- e0) (bad <- true)); rewrite Heq2; intro H2. \n        rewrite H1, H2 in *; clear H1 H2 Heq1 Heq2.   \n        \n        \n        \n    admit.\n    admit.\n    \n\n    destruct b; simpl in H; repeat rewrite andb_false_r in H; try discriminate H.\n    destruct b; simpl in H; repeat rewrite andb_false_r in H; try discriminate H.\n    \n\n\nFocus 2.\nsimpl in H.\n\n\nintro Heq; unfold is_true in Heq.\n    apply orb_prop in Heq; destruct Heq as [Heq | Heq].\n    rewrite Heq; trivial.\n    apply andb_prop in Heq; destruct Heq as [Heq _];  \n     rewrite Heq; rewrite orb_true_r; trivial.\n    apply andb_prop in Heq; destruct Heq as [Heq _]; rewrite Heq; trivial.\n    apply andb_prop in Heq; destruct Heq as [Heq _]; rewrite Heq; trivial.\n    apply andb_prop in Heq; destruct Heq as [Heq _]; rewrite Heq; trivial.\n    intro Heq; unfold is_true in Heq.\n    apply andb_prop in Heq; destruct Heq as [Heq _]; rewrite Heq; trivial.\n    intro Heq; unfold is_true in Heq.\n    apply andb_prop in Heq; destruct Heq as [Heq _]; rewrite Heq; trivial.\n\n    \n      \n      SearchAbout false.\n      discriminate H.\n\n      simpl in H.\n      \n      \n\n    \n    repeat rewrite deno_niel_elim; trivial.\n    discriminate.\n\n      \n    (* Cond *)\n    intros ep Hep.\n    destruct c2; try discriminate H.\n    destruct i; try discriminate H.\n    simpl in H; unfold is_true in H.\n    apply andb_prop in H; destruct H as [H Hc0].\n    destruct c2; try discriminate Hc0.\n    apply andb_prop in H; destruct H as [H Hc2'].\n    apply andb_prop in H; destruct H as [He Hc1'].\n    generalize (E.eqb_spec b e); rewrite He; intro H; rewrite H in *.\n    clear He Hc0 H.\n\n \n\n\n    simpl in Hpb1; unfold is_true in Hpb1.\n    rewrite andb_true_r in Hpb1; apply andb_prop in Hpb1; destruct Hpb1.\n    simpl in Hpb2; unfold is_true in Hpb2.\n    rewrite andb_true_r in Hpb2; apply andb_prop in Hpb2; destruct Hpb2.\n\n      \n\n\n     (*\n     exists (fun m1 m2 => \n        prod_distr ([[ [v0 <$- s0] ]] E1 m1) ([[ [v0 <$- s0] ]] E2 m2)).\n      intros m1 m2 Hm; constructor.\n        intros.\n        rewrite prod_distr_fst, (lossless_random _ _ _ m2), Umult_one_left, Uabs_diff_compat_eq.\n        rewrite prod_distr_snd, (lossless_random _ _ _ m1), Umult_one_left, Uabs_diff_compat_eq.\n        auto.\n        intros f Hf; simpl.\n        rewrite (deno_random_elim _ _ _ m1), (mu_stable_eq _ _ (fun v1 =>\n          mu (sum_support (SwitchingSem.Sem.T.default k t0) (E.eval_support s0 m2))\n          (fun v2 => f (m1 {!v0 <-- v1!}, m2 {!v0 <-- v2!}))));  [ | \n            refine (ford_eq_intro _); intro v1; apply (deno_random_elim E2 v0 s0 m2) ].\n        change (0 == sum_dom (T.default k t0) (E.eval_support s0 m1)\n          (fun v1 => sum_dom  (T.default k t0) (E.eval_support s0 m2)\n            (fun v2 => f (m1 {!v0 <-- v1!}, m2 {!v0 <-- v2!})))).\n        \n        symmetry; apply sum_dom_zero with (fun _ => True); [ trivial | ].\n        intros v1 _; apply sum_dom_zero with (fun v2 => True); [ trivial | ].\n        intros v2 _; symmetry; apply Hf.\n        apply HPQ with m1 m2; split; [ exact Hm | simpl ].\n     *) \n\n\n\n\n\n\n\n\n\nSearchAbout check_bad.\nSection LIFT_TRANS.\n \n Variables A B C : Type.\n Variable carB : B -> MF B.\n\n Hypothesis carB_prop : forall a, cover (fun x => a = x) (carB a).\n \n Variable P : A -> B -> Prop.\n Variable Q : B -> C -> Prop.\n Variable R : A -> C -> Prop.\n\n Hypothesis P_Q_R : forall x y z, P x y -> Q y z -> R x z.\n\n Variable d  : Distr (A*B).\n Variable d' : Distr (B*C). \n Variable d1 : Distr A.\n Variable d2 : Distr B.\n Variable d3 : Distr C.\n\n Variable ep1 ep2: U.\n Variable Hd : elift P d  d1 d2 ep1.\n Variable Hd': elift Q d' d2 d3 ep2.\n\n Definition dfst (b : B) : distr (B*C) := distr_mult (fun q => carB b (fst q)) d'.\n \n Definition dsnd (b : B) : distr (A*B) := distr_mult (fun q => carB b (snd q)) d.\n\n Lemma dfst_simpl : forall b f, \n  mu (dfst b) f = mu d' (fun q => carB b (fst q) * f q).\n Proof. \n  trivial.\n Qed.\n\n Lemma dsnd_simpl : forall b f, \n  mu (dsnd b) f = mu d (fun q => carB b (snd q) * f q).\n Proof. \n  trivial.\n Qed.\n\n\n Lemma dfst_le : forall b, mu (dfst b) (fone (B * C)) <= ep2 +  mu d2 (carB b).\n Proof.\n  intro; rewrite dfst_simpl.\n  apply Ole_trans with (mu d' (fun q => carB b (fst q)));  [auto | ].\n  apply Uplus_le_minus.\n  rewrite <-(Hd'.(el_dist) (carB b) (fzero _)), mu_zero, mu_zero,\n    Uabs_diff_compat_eq, Uplus_zero_right.\n  apply Ule_plus_right.\n Qed.\n\n\n\n\n Lemma dsnd_le : forall b, mu (dsnd b) (fone (A * B)) <= mu d2 (carB b).\n Proof.\n  intro; rewrite dsnd_simpl.\n  apply Ole_trans with (mu d (fun q => carB b (snd q))); [auto | ].\n  rewrite Hd.(el_snd); trivial.\n Qed.\n\n Hint Resolve dfst_le dsnd_le.\n*)\n\n Definition d_restr : B -> distr (A*B) := \n  fun b => distr_div (mu d2 (carB b)) (dsnd b) (dsnd_le b) .\n\n Definition d'_restr : B -> distr (B*C) := \n  fun b => distr_div (mu d2 (carB b)) (dfst b) (dfst_le b).\n\n Lemma d_restr_simpl : forall b f, \n  mu (d_restr b) f = mu d (fun q => carB b (snd q) * f q) / mu d2 (carB b).\n Proof. \n  trivial.\n Qed.\n\n Lemma d'_restr_simpl : forall b f, \n  mu (d'_restr b) f = mu d' (fun q => carB b (fst q) * f q) / mu d2 (carB b).\n Proof. \n  trivial.\n Qed.\n\n Definition dd' : distr (A * C) := \n  Mlet d2 (fun b => \n   Mlet (d_restr b) (fun p => \n    Mlet (d'_restr b) (fun q => Munit (fst p, snd q)))).\n\n Lemma dd'_range : range (prodP R) dd'.\n Proof.\n  red; intros.\n  unfold dd'; simpl.\n  transitivity (mu d2 (fzero B)); [auto | ].\n  apply (mu_stable_eq d2); simpl; apply ford_eq_intro; intro x; unfold fzero.\n  apply (Ueq_orc 0 (mu d2 (carB x))); auto; intros.\n  apply Oeq_sym; apply Udiv_by_zero; auto.\n  apply Oeq_sym; apply Udiv_zero_eq; auto.\n  apply Hd.(el_range); intros.\n  apply (cover_elim (carB_prop x) (snd x0)); auto; intros [H4 H5].\n  rewrite H5; auto.\n  rewrite H5; Usimpl.\n  apply Oeq_sym; apply Udiv_zero_eq; auto.\n  apply Hd'.(el_range); intros.\n  destruct x1; destruct x0; simpl.\n  simpl in H4; subst x.\n  apply (cover_elim (carB_prop b0) b); auto; intros [H6 H7].\n  rewrite H7; auto.\n  rewrite <- H; auto.\n  subst b0; red; apply P_Q_R with b; trivial.\n Qed.\n\n \n\n\n\n\n\n\n(*\n Lemma dist_prg_upto:  forall (P:mem_rel) E1 c1 E2 c2 (Q:mem_rel) (ep:nat -o> U) \n   (bad: Var.var T.Bool) (pi : upto_info bad E1 E2),\n   Var.is_global bad ->\n   check_bad pi c1 c2 ->\n   lossless E2 c2 ->\n   (forall k (m m':Mem.t k), P _ m' m -> Pr E2 c2 m (EP k bad) <= ep k) ->\n   dist_prg (Meq /-\\ P) E1 c1 E2 c2 Meq (fplus (fplus (fzero _) ep) (fzero _)).\n Proof.\n  intros.\n  eapply dist_prg_failure_event with bad.\n    admit.\n    unfold dist_prg.\n    intros.\n    exists (fun m1 m2 => Mlet ([[c1]] E1 m1) (fun m1' => Mlet ([[c2]] E2 m2) \n      (fun m2' => if m2 bad then Munit (m1',m2') else distr0 _))).\n    intros.\n    constructor.\n      intros.\n      repeat rewrite Mlet_simpl.\n      rewrite \n    Focus 3.\n  upto_bad_GSD\n*)\n\n\n(*\nDefinition iffR (A B: Type) (R1 R2: A -> B -> Prop) :=\n   forall a b, R1 a b <-> R2 a b.\n\n Lemma iffR_refl: forall  (A B: Type),\n   reflexive _ (@iffR A B).\n Proof.  split; intros; auto. Qed.\n\n Lemma iffR_sym: forall  (A B: Type),\n   symmetric _ (@iffR A B).\n Proof. \n   intros A B R1 R2 H a b; split.\n     apply (proj2 (H a b)).\n     apply (proj1 (H a b)).\n Qed.\n\n\n Add Parametric Relation (A B:Type) : (A->B->Prop) (@iffR A B) \n  reflexivity proved by (@iffR_refl A B) \n  symmetry proved by (@iffR_sym A B)\n  as iffR_rel.\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/StInd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.280143708943101}}
{"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 orthogonalite_espace.\nRequire Export affine_classiques.\nSet Implicit Arguments.\nUnset Strict Implicit.\n \nDefinition tetraedre (A B C D : PO) := ~ coplanaires A B C D.\n \nLemma tetraedre_non_alignes :\n forall A B C D : PO, tetraedre A B C D -> ~ alignes A B C.\nunfold tetraedre in |- *; intros.\nelim non_coplanaires_expl with (A := A) (B := B) (C := C) (D := D);\n [ intros H0 H1; try clear non_coplanaires_expl; try exact H0 | auto ].\nQed.\nHint Resolve tetraedre_non_alignes: geo.\n \nLemma deux_milieux_tetraedre :\n forall A B C D I J K L : PO,\n tetraedre A B C D ->\n I = milieu D A ->\n J = milieu D B -> K = milieu C A -> L = milieu C B -> vec I J = vec K L.\nintros.\ncut (mult_PP 2 (vec I J) = vec A B); intros.\ncut (mult_PP 2 (vec K L) = vec A B); intros.\napply mult_PP_regulier with 2; auto with real.\nrewrite H5; auto.\napply droite_milieu with C; auto.\napply droite_milieu with D; auto.\nQed.\n \nDefinition parallelepipede (A B C D E F G H : PO) :=\n  (vec A B = vec D C /\\ vec D C = vec H G) /\\\n  vec H G = vec E F /\\ vec E H = vec A D.\n \nDefinition parallelepipede_rectangle (A B C D E F G H : PO) :=\n  parallelepipede A B C D E F G H /\\\n  orthogonal (vec A B) (vec A D) /\\\n  orthogonal (vec A B) (vec A E) /\\ orthogonal (vec A D) (vec A E).\n \nDefinition carre (A B C D : PO) :=\n  vec A B = vec D C /\\\n  orthogonal (vec A B) (vec A D) /\\\n  scalaire (vec A B) (vec A B) = 1 /\\ scalaire (vec A D) (vec A D) = 1.\n \nDefinition cube (A B C D E F G H : PO) :=\n  parallelepipede_rectangle A B C D E F G H /\\\n  carre A B C D /\\ scalaire (vec A E) (vec A E) = 1.\n \nLemma parallelepipede_parallelogramme :\n forall A B C D E F G H : PO,\n parallelepipede A B C D E F G H -> vec F G = vec A D.\nunfold parallelepipede in |- *; intros A B C D E F G H' H.\nelim H; intros H0 H1; elim H1; intros H2 H3; try clear H1 H; try exact H3.\nelim H0; intros H H1; try clear H0; try exact H1.\nrewrite <- H3.\napply egalite_vecteur.\nVReplace (vec F E) (mult_PP (-1) (vec E F)).\nrewrite <- H2.\nRingvec.\nQed.\n \nLemma diagonales_carre :\n forall A B C D : PO, carre A B C D -> orthogonal (vec A C) (vec D B).\nintros.\nelim H; clear H; intros.\napply def_orthogonal2.\nelim H0; intros H2 H3; elim H3; intros H4 H5; try clear H3 H0; try exact H5.\ncut (scalaire (vec A B) (vec A D) = 0); intros.\nreplace (vec A C) with (add_PP (mult_PP 1 (vec A B)) (mult_PP 1 (vec A D))).\nreplace (vec D B) with\n (add_PP (mult_PP (-1) (vec A D)) (mult_PP 1 (vec A B))).\nrewrite scalaire_bilineaire.\nrewrite H4; rewrite H5; rewrite H0.\nrewrite scalaire_sym; rewrite H0; ring.\nRingvec.\nrewrite H.\nRingvec.\napply def_orthogonal; auto.\nQed.\n \nLemma centre_gravite_coplanaire :\n forall A B C : PO,\n ~ alignes A B C -> coplanaires A B C (centre_gravite A B C).\nunfold centre_gravite, milieu, coplanaires in |- *; intros.\nright; try assumption.\nexists (/ 3); exists (/ 3).\ncut (3 <> 0); intros; auto with real.\napply mult_PP_regulier with 3; auto with real.\nFVReplace\n (mult_PP 3\n    (add_PP (cons (/ 3) A)\n       (add_PP (cons (/ 3) B) (cons (1 + - (/ 3 + / 3)) C))))\n (add_PP (cons 1 A) (add_PP (cons 1 B) (cons 1 C))) 3.\nVReplace\n (mult_PP 3\n    (cons 1\n       (barycentre (cons 1 A) (cons 2 (barycentre (cons 1 B) (cons 1 C))))))\n (cons 3 (barycentre (cons 1 A) (cons 2 (barycentre (cons 1 B) (cons 1 C))))).\nrepeat rewrite <- add_PP_barycentre; auto with real.\nQed.\nHint Resolve centre_gravite_coplanaire: geo.\n \nLemma exercice :\n forall A B C D E F G H I : PO,\n D <> F ->\n ~ alignes E B G ->\n parallelepipede A B C D E F G H ->\n I = centre_gravite E B G -> coplanaires E B G I /\\ alignes F D I.\nintros A B C D E F G H I H20 H0 H1 H51; try assumption.\nrewrite H51.\nsplit; [ auto with geo | idtac ].\ncut (vec F G = vec A D).\nintros H10.\nunfold parallelepipede in H1.\nelim H1; intros H2 H3; elim H2; intros H4 H5; try clear H2 H1; try exact H4.\nelim H3; intros H2 H12; try clear H3.\ncut (vec F D = mult_PP 3 (vec F (centre_gravite E B G))); intros.\ncut (3 <> 0); intros; auto with real.\napply colineaire_alignes with (/ 3); auto.\nrewrite H1.\nFieldvec 3; auto.\ncut (add_PP (mult_PP 3 (vec (centre_gravite E B G) F)) (vec F D) = zero);\n intros.\nVReplace (vec F D) (add_PP (vec F D) (mult_PP (-1) zero)).\nrewrite <- H1.\nRingvec.\nVReplace (vec F D) (add_PP (vec F B) (add_PP (vec B A) (vec A D))).\nreplace (vec B A) with (vec F E); auto.\nreplace (vec A D) with (vec F G); auto.\nVReplace (add_PP (vec F B) (add_PP (vec F E) (vec F G)))\n (add_PP (vec F E) (add_PP (vec F B) (vec F G))).\nreplace (add_PP (vec F E) (add_PP (vec F B) (vec F G))) with\n (mult_PP 3\n    (vec F\n       (barycentre (cons 1 E) (cons 2 (barycentre (cons 1 B) (cons 1 G))))));\n auto.\nunfold vec, centre_gravite, milieu in |- *; RingPP.\nVReplace (add_PP (vec F B) (vec F G))\n (add_PP (mult_PP 1 (vec F B)) (mult_PP 1 (vec F G))).\nrewrite\n (prop_vecteur_bary (a:=1) (b:=1) (A:=B) (B:=G)\n    (G:=barycentre (cons 1 B) (cons 1 G)) F); auto.\nVReplace (vec F E) (mult_PP 1 (vec F E)).\nrewrite\n (prop_vecteur_bary (a:=1) (b:=2) (A:=E)\n    (B:=barycentre (cons 1 B) (cons 1 G))\n    (G:=barycentre (cons 1 E) (cons 2 (barycentre (cons 1 B) (cons 1 G)))) F)\n ; auto.\ndiscrR.\ndiscrR.\ncut (vec A B = vec E F); intros; auto.\nVReplace (vec B A) (mult_PP (-1) (vec A B)).\nrewrite H1.\nRingvec.\nrewrite H4.\nrewrite H5; auto.\napply parallelepipede_parallelogramme with (1 := H1).\nQed.\n \nLemma exercice_cube :\n forall A B C D E F G H I : PO,\n D <> F ->\n ~ alignes E B G ->\n cube A B C D E F G H ->\n I = centre_gravite E B G ->\n alignes F D I /\\ orthogonaux (droite F D) (plan E B G).\nintros A B C D E F G H I H0 H1 H2 H51; try assumption.\nelim H2; intros; clear H2.\nelim H3; intros; clear H3.\nelim H5; intros H3 H6; elim H6; intros H7 H8; try clear H6 H5; try exact H8.\nelim H4; intros H5 H6; try clear H4; try exact H6.\nsplit; [ try assumption | idtac ].\nelim\n exercice\n  with\n    (A := A)\n    (B := B)\n    (C := C)\n    (D := D)\n    (E := E)\n    (F := F)\n    (G := G)\n    (H := H)\n    (I := I); [ try clear exercice; auto | auto | auto | auto | auto ].\nelim H5; intros; clear H5.\nelim H9; intros H5 H10; elim H10; intros H11 H12; try clear H10 H9;\n try exact H12.\nelim H2; intros.\nelim H10; intros H13 H14; try clear H10; try exact H14.\nelim H9; intros H10 H15; try clear H9; try exact H15.\ncut (scalaire (vec A B) (vec A E) = 0); intros.\ncut (scalaire (vec A B) (vec A D) = 0); intros.\ncut (scalaire (vec A D) (vec A E) = 0); intros.\ncut (E <> B); intros.\ncut (E <> G); intros.\ncut (vec F D = add_PP (vec F A) (vec A D)); intros.\napply def_orthogonaux; auto.\napply def_orthogonales; auto.\napply def_orthogonal2.\nrewrite scalaire_sym.\nrewrite H20.\nrewrite scalaire_somme_g.\nreplace (scalaire (vec F A) (vec E B)) with 0.\nreplace (scalaire (vec A D) (vec E B)) with 0.\nring.\nreplace (vec E B) with\n (add_PP (mult_PP (-1) (vec A E)) (mult_PP 1 (vec A B))).\nrewrite scalaire_lineaire_d.\nrewrite H17.\nrewrite scalaire_sym.\nrewrite H16.\nring.\nRingvec.\nreplace (vec E B) with\n (add_PP (mult_PP (-1) (vec A E)) (mult_PP 1 (vec A B))).\nreplace (vec F A) with\n (add_PP (mult_PP (-1) (vec A E)) (mult_PP (-1) (vec A B))).\nrewrite scalaire_bilineaire.\nrewrite H11; rewrite H6; rewrite H9.\nrewrite scalaire_sym.\nrewrite H9.\nring.\nrewrite H10; rewrite H15; rewrite H13.\nRingvec.\nRingvec.\napply def_orthogonales; auto.\napply def_orthogonal2.\nreplace (vec E G) with (add_PP (vec A B) (vec A D)).\nrewrite scalaire_somme_g.\nrewrite scalaire_sym.\nrewrite (scalaire_sym A D F D).\nrewrite H20.\nrewrite scalaire_somme_g.\nrewrite scalaire_somme_g.\nrewrite H12.\nrewrite (scalaire_sym A D A B).\nrewrite H16.\nreplace (vec F A) with\n (add_PP (mult_PP (-1) (vec A E)) (mult_PP (-1) (vec A B))).\nrewrite scalaire_lineaire_g.\nrewrite scalaire_lineaire_g.\nrewrite H11; rewrite H16.\nrewrite scalaire_sym.\nrewrite H9.\nrewrite scalaire_sym.\nrewrite H17.\nring.\nrewrite H10; rewrite H15; rewrite H13.\nRingvec.\nreplace (vec E G) with (add_PP (vec E F) (vec F G)).\nrewrite H10; rewrite H15; rewrite H13.\nrewrite parallelepipede_parallelogramme with (1 := H2); auto.\nRingvec.\nRingvec.\napply distance_non_nulle.\nreplace (vec E G) with (add_PP (mult_PP 1 (vec A B)) (mult_PP 1 (vec A D))).\nrewrite scalaire_bilineaire.\nrewrite H11; rewrite H12; rewrite H16.\nrewrite scalaire_sym; rewrite H16.\nreplace (1 * 1 * 1 + 1 * 1 * 0 + (1 * 1 * 0 + 1 * 1 * 1)) with 2.\ndiscrR.\nring.\nreplace (vec E G) with (add_PP (vec E F) (vec F G)).\nrewrite H10; rewrite H15; rewrite H13.\nrewrite parallelepipede_parallelogramme with (1 := H2); auto.\nRingvec.\nRingvec.\napply distance_non_nulle.\nreplace (vec E B) with\n (add_PP (mult_PP (-1) (vec A E)) (mult_PP 1 (vec A B))).\nrewrite scalaire_bilineaire.\nrewrite H11; rewrite H9; rewrite H6.\nrewrite scalaire_sym; rewrite H9.\nreplace (-1 * -1 * 1 + -1 * 1 * 0 + (1 * -1 * 0 + 1 * 1 * 1)) with 2.\ndiscrR.\nring.\nRingvec.\napply def_orthogonal; auto.\napply def_orthogonal; auto.\napply def_orthogonal; auto.\nQed.\n \nLemma equilateral_non_alignes :\n forall A B C : PO,\n A <> B ->\n scalaire (vec A B) (vec A B) = scalaire (vec A C) (vec A C) ->\n scalaire (vec A B) (vec A B) = scalaire (vec B C) (vec B C) ->\n ~ alignes A B C.\nintros A B C H H0 H1; red in |- *; intros H2; try exact H2.\nhalignes H2 ipattern:(k).\nrewrite H3 in H0.\ncut (vec B C = mult_PP (k + -1) (vec A B)); intros.\nrewrite H4 in H1.\ncut (k * k = 1); intros.\ncut ((k + -1) * (k + -1) = 1); intros.\ncut (k = 1 \\/ k = -1); intros.\nelim H7; [ intros H8; try clear H7; try exact H8 | intros H8; try clear H7 ].\nrewrite H8 in H6.\nabsurd (0 = 1); auto with *.\nrewrite <- H6; ring.\nrewrite H8 in H6.\nabsurd ((-1 + -1) * (-1 + -1) = 1).\ntry discrR.\ntry assumption.\ncut (k + -1 = 0 \\/ k + 1 = 0); intros.\nelim H7; [ intros H8; try clear H7; try exact H8 | intros H8; try clear H7 ].\nleft; try assumption.\nreplace k with (k + -1 + 1).\nrewrite H8; ring.\nring.\nright; try assumption.\nreplace k with (k + 1 + -1).\nrewrite H8; ring.\nring.\napply Rmult_integral.\nreplace 0 with (k * k + -1).\nring.\nrewrite H5; ring.\napply Rmult_eq_reg_l with (scalaire (vec A B) (vec A B)).\nreplace (scalaire (vec A B) (vec A B) * 1) with\n (scalaire (vec A B) (vec A B)).\npattern (scalaire (vec A B) (vec A B)) at 2 in |- *.\nrewrite H1.\nrewrite scalaire_mult_mult; ring.\nring.\nunfold not in |- *; intros; apply H.\napply distance_nulle; auto.\napply Rmult_eq_reg_l with (scalaire (vec A B) (vec A B)).\nreplace (scalaire (vec A B) (vec A B) * 1) with\n (scalaire (vec A B) (vec A B)).\npattern (scalaire (vec A B) (vec A B)) at 2 in |- *.\nrewrite H0.\nrewrite scalaire_mult_mult; ring.\nring.\nunfold not in |- *; intros; apply H.\napply distance_nulle; auto.\nreplace (vec B C) with (add_PP (vec A C) (mult_PP (-1) (vec A B))).\nrewrite H3.\nRingvec.\nRingvec.\nQed.\n \nTheorem the_cube :\n forall A B C D E F G H I : PO,\n cube A B C D E F G H ->\n I = centre_gravite E B G ->\n alignes F D I /\\ orthogonaux (droite F D) (plan E B G).\nintros A B C D E F G H I H0 H51; try assumption.\nelim H0; intros.\nelim H1; intros.\nelim H3; intros.\nelim H6; intros H7 H8; try clear H6; try exact H8.\nelim H5; intros H6 H9; try clear H5; try exact H9.\nelim H4; intros H5 H10; elim H10; intros H11 H12; try clear H10 H4;\n try exact H12.\nelim H2; intros H4 H10; try clear H2; try exact H10.\nelim H4; intros.\nelim H13; intros H14 H15; elim H15; intros H16 H17; try clear H15 H13;\n try exact H16.\ncut (vec A F = add_PP (mult_PP 1 (vec A B)) (mult_PP 1 (vec A E))); intros.\ncut (scalaire (vec A B) (vec A E) = 0); intros.\ncut (scalaire (vec A B) (vec A D) = 0); intros.\ncut (scalaire (vec A D) (vec A E) = 0); intros.\napply exercice_cube with (3 := H0); auto.\napply distance_non_nulle.\nreplace (vec D F) with\n (add_PP (mult_PP 1 (vec A F)) (mult_PP (-1) (vec A D))).\nrewrite scalaire_bilineaire.\nreplace (scalaire (vec A F) (vec A F)) with 2.\ncut (scalaire (vec A F) (vec A D) = 0); intros.\nrewrite H20; rewrite H17.\nrewrite scalaire_sym; rewrite H20.\ntry discrR.\nrewrite H13.\nrewrite scalaire_lineaire_g.\nrewrite H18.\nrewrite scalaire_sym; rewrite H19.\nring.\nrewrite H13.\nrewrite scalaire_bilineaire.\nrewrite H15; rewrite H10; rewrite H16.\nrewrite scalaire_sym; rewrite H15.\nring.\nRingvec.\ncut (vec E B = add_PP (mult_PP 1 (vec A B)) (mult_PP (-1) (vec A E))); intros.\ncut (vec E G = add_PP (mult_PP 1 (vec A B)) (mult_PP 1 (vec A D))); intros.\napply equilateral_non_alignes; auto.\napply distance_non_nulle.\nrewrite H20.\nrewrite scalaire_bilineaire.\nrewrite H15; rewrite H10; rewrite H16.\nrewrite scalaire_sym; rewrite H15.\ntry discrR.\nrewrite H20.\nrewrite scalaire_bilineaire.\nrewrite H21.\nrewrite scalaire_bilineaire.\nrewrite H15; rewrite H10; rewrite H16.\nrewrite scalaire_sym; rewrite H15.\nrewrite H17; rewrite H18.\nrewrite scalaire_sym; rewrite H18.\nring.\nreplace (vec B G) with\n (add_PP (mult_PP 1 (vec E G)) (mult_PP (-1) (vec E B))).\nrewrite scalaire_bilineaire.\nrewrite H20.\nrewrite scalaire_bilineaire.\nrewrite H21.\nrepeat rewrite scalaire_bilineaire.\nrewrite H15; rewrite H10; rewrite H16.\nrewrite scalaire_sym; rewrite H15.\nrewrite H17; rewrite H18.\nrewrite scalaire_sym; rewrite H18.\nrewrite H19; rewrite scalaire_sym; rewrite H19.\nring.\nRingvec.\nrewrite <- H8.\nrewrite H6; rewrite H9.\nRingvec.\nRingvec.\napply def_orthogonal; auto.\napply def_orthogonal; auto.\napply def_orthogonal; auto.\nrewrite H6; rewrite H9; rewrite H7.\nRingvec.\nQed.\n", "meta": {"author": "coq-contribs", "repo": "high-school-geometry", "sha": "1f0ac8d9a630c82a15bb28ded4c62c8e2edb1669", "save_path": "github-repos/coq/coq-contribs-high-school-geometry", "path": "github-repos/coq/coq-contribs-high-school-geometry/high-school-geometry-1f0ac8d9a630c82a15bb28ded4c62c8e2edb1669/exercice_espace.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2801437089431009}}
{"text": "From st.STLCmuVS Require Import lang typing contexts scopedness.\nFrom st.STLCmu Require Import types.\nFrom st.backtranslations.un_syn Require Import universe.base expressions contexts typed.\nFrom st.backtranslations.sem_syn Require Import embed_project gamma_lib.\nFrom st.prelude Require Import forall_three.\n\nDefinition back_ctx_nil (C : ctx) (τ : type) : ctx :=\n  [CTX_AppR (ep_pair Project TUnit)] ++ universe_back_ctx C ++ [CTX_AppR (ep_pair Embed τ)].\n\nDefinition back_ctx_cons (C : ctx) (Γ : list type) (τ : type) : ctx :=\n  let P : expr :=\n      let filled_hole : expr :=\n          ep_pair Embed τ (\n                    wrap_funs_vars (Var (length Γ)) 0\n                             ((fun τ => ep_pair Project τ) <$> Γ)\n                  )\n      in\n      fill_ctx (universe_back_ctx C) filled_hole\n  in\n  [CTX_LetInL (ep_pair Project TUnit P)] ++ (LamGamma_ctx (length Γ)).\n\nDefinition back_ctx (C : ctx) (Γ : list type) (τ : type) : ctx :=\n  match (length Γ) with\n  | 0 => back_ctx_nil C τ\n  | S n => back_ctx_cons C Γ τ\n  end.\n\nLemma back_ctx_nil_typed (C : ctx) (τ : type) (pτ : Closed τ)\n  (H : |sC> 0 ⊢ₙₒ C ☾ 0 ☽) :\n  |C> [] ⊢ₙₒ (back_ctx_nil C τ) ☾ [] ; τ ☽ : TUnit.\nProof.\n  rewrite /back_ctx_nil. eapply typed_ctx_app. econstructor. constructor. instantiate (1 := TUniverse).\n  apply ep_pair_typed. intro σ; by asimpl. constructor.\n  eapply typed_ctx_app. change [] with (replicate 0 TUniverse).\n  apply universe_back_ctx_typed. eauto. econstructor. constructor. instantiate (1 := τ).\n  apply ep_pair_typed. auto. constructor.\nQed.\n\nLemma back_ctx_cons_typed (C : ctx) (Γ : list type) (pΓ : Forall Closed Γ) (τ : type) (pτ : Closed τ)\n  (H : |sC> 0 ⊢ₙₒ C ☾ length Γ ☽) :\n  |C> [] ⊢ₙₒ (back_ctx_cons C Γ τ) ☾ Γ ; τ ☽ : TUnit.\nProof.\n  Opaque ep_pair.\n  eapply typed_ctx_app; [| apply LamGamma_ctx_typed].\n  econstructor. 2: constructor. simpl.\n  constructor. apply App_typed with (τ1 := TUniverse). apply typed_nil, ep_pair_typed. intros σ; by asimpl.\n  eapply typed_ctx_typed with (Γ := (map (fun _ => TUniverse) Γ) ++ [GammaType Γ τ]) (τ := TUniverse).\n  apply App_typed with (τ1 := τ). apply typed_nil, ep_pair_typed; auto.\n  rewrite -(map_length (fun _ => TUniverse) Γ). apply wrap_funs_vars_typed.\n  apply Forall3_fmap_l, Forall3_fmap_m, Forall3_same. eapply Forall_impl; eauto.\n  simpl. intros. apply typed_nil, ep_pair_typed. auto.\n  change [GammaType Γ τ] with ([] ++ [GammaType Γ τ]) at 2.\n  apply typed_ctx_append. change [] with (replicate 0 TUniverse).\n  replace (map (fun _ => TUniverse) Γ) with (replicate (length Γ) TUniverse).\n  by apply universe_back_ctx_typed. rewrite -(const_fmap (fun _ => TUniverse)); auto.\nQed.\n\nLemma back_ctx_typed (C : ctx) (Γ : list type) (pΓ : Forall Closed Γ) (τ : type) (pτ : Closed τ)\n  (H : |sC> 0 ⊢ₙₒ C ☾ length Γ ☽) :\n  |C> [] ⊢ₙₒ (back_ctx C Γ τ) ☾ Γ ; τ ☽ : TUnit.\nProof.\n  destruct (length Γ) eqn:eq.\n  - rewrite (nil_length_inv _ eq) /=. by apply back_ctx_nil_typed.\n  - rewrite /back_ctx eq. apply back_ctx_cons_typed; auto. by rewrite eq.\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/backtranslations/sem_syn/back_ctx.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2801429240142419}}
{"text": "(* Se definen componentes y lemas comunes para generar los testigos\n* que se dan en las demostraciones de las propiedades postuladas *)\nRequire Import Estado.\nRequire Import DefBasicas.\nRequire Import Maps.\n\nParameter a1 a2:idApp.\nAxiom asdiff :a1<>a2.\n\nTheorem idAppa1a2Right : exists e, idApp_eq a1 a2 = right e.\nProof.\n    destruct (idApp_eq a1 a2).\n    destruct asdiff;auto.\n    exists n.\n    auto.\nQed.\n\nTheorem idAppa2a1Right : exists e, idApp_eq a2 a1 = right e.\nProof.\n    destruct (idApp_eq a2 a1).\n    destruct asdiff;auto.\n    exists n.\n    auto.\nQed.\n\nTheorem idAppAALeft : forall a, exists e, idApp_eq a a = left e.\nProof.\n    intros.\n    destruct (idApp_eq a a).\n    exists e;auto.\n    destruct n;auto.\nQed.\n\nParameter c:Cert.\n\nDefinition emptyPermGroups := map_empty idApp (list idGrp).\n\nDefinition emptyPerms := map_empty idApp (list Perm).\n\nDefinition emptyRunning := map_empty iCmp Cmp.\n\nDefinition emptyDelPPerms:= map_empty (idApp * CProvider * uri) PType.\n\nDefinition emptyDelTPerms:= map_empty (iCmp * CProvider * uri) PType.\n\nDefinition emptyResCont:= map_empty (idApp * res) Val.\n\nDefinition addAppValue (V:Set) (a:idApp) (v:V) (mp:mapping idApp V) :=\n    map_add idApp_eq mp a v.\n\nParameter witnessPermId : idPerm.\nParameter witnessPermGrp : idGrp.\n\nDefinition emptyManifests:= map_empty idApp Manifest.\nDefinition emptyCerts:= map_empty idApp Cert.\nDefinition emptyDefPerms:= map_empty idApp (list Perm).\n\nDefinition simpleManifest (hisCmps : list Cmp) (permsUsed : list Perm) (permsDeclared : list Perm) :=\n    mf hisCmps (Some 23) (Some 23) permsUsed permsDeclared None.\n\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/WitnessesFactory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.28014292401424185}}
{"text": "Require Import Coq.Logic.PropExtensionality Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Lists.List. Import ListNotations. Open Scope list_scope.\nRequire Import coqutil.Map.Interface coqutil.Map.Properties.\nRequire Import coqutil.Tactics.fwd.\nRequire Import coqutil.Tactics.Tactics.\nRequire Import coqutil.Tactics.syntactic_unify.\nRequire Import bedrock2.Lift1Prop.\nRequire Import bedrock2.Map.DisjointUnion.\nRequire Import bedrock2.TacticError.\nRequire Import bedrock2.PurifySep.\nRequire Import bedrock2.Map.SeparationLogic. Local Open Scope sep_scope.\n\n(* to mark hypotheses about heaplets *)\nDefinition with_mem{mem: Type}(m: mem)(P: mem -> Prop): Prop := P m.\n\nDeclare Scope heapletwise_scope.\nOpen Scope heapletwise_scope.\n\nSet Ltac Backtrace.\n\nNotation \"m |= P\" := (with_mem m P) (at level 72) : heapletwise_scope.\n\nSection HeapletwiseHyps.\n  Context {key value: Type} {mem: map.map key value} {mem_ok: map.ok mem}\n          {key_eqb: key -> key -> bool} {key_eqb_spec: EqDecider key_eqb}.\n\n  Lemma split_du: forall (m m1 m2: mem),\n      map.split m m1 m2 <-> mmap.du m1 m2 = m.\n  Proof.\n    unfold map.split, mmap.du, map.du, mmap.of_option. split; intros; fwd.\n    - eapply map.disjointb_spec in Hp1. rewrite Hp1. reflexivity.\n    - eapply map.disjointb_spec in E0. auto.\n  Qed.\n\n  Definition anymem: mem -> Prop := fun _ => True.\n\n  Definition wand(P1 P2: mem -> Prop): mem -> Prop :=\n    fun mdiff => forall m1 m2, map.split m2 mdiff m1 -> P1 m1 -> P2 m2.\n\n  (* with mmap.du instead of map.split: *)\n  Definition wand'(P1 P2: mem -> Prop): mem -> Prop :=\n    fun mdiff => forall m1 m2, mmap.du (mmap.Def mdiff) (mmap.Def m1) = mmap.Def m2 ->\n                               P1 m1 -> P2 m2.\n\n  Lemma wand_alt: wand = wand'.\n  Proof.\n    extensionality P. extensionality Q. extensionality m.\n    eapply propositional_extensionality. unfold wand, wand';\n      split; intros; eapply split_du in H0; eauto.\n  Qed.\n\n  Lemma wand_adjoint: forall (P Q R: mem -> Prop),\n      impl1 (sep P Q) R <-> impl1 P (wand Q R).\n  Proof.\n    unfold impl1, sep, wand. intros; split; intros; fwd; eauto 7.\n  Qed.\n\n  (* modus ponens for wand only holds in one direction! *)\n  Lemma wand_mp: forall P Q,\n      impl1 (sep P (wand P Q)) Q.\n  Proof.\n    intros. rewrite sep_comm. rewrite (wand_adjoint (wand P Q) P Q). reflexivity.\n  Qed.\n\n  Lemma ramify_funspec_hyp: forall (calleePre calleePost callerPost: mem -> Prop) m,\n      (* non-ramified hypothesis: requires creating an evar for Frame too early *)\n      (exists Frame,\n          sep calleePre Frame m /\\ (forall m', sep calleePost Frame m' -> callerPost m')) <->\n      (* ramified hypothesis: no frame needed *)\n      sep calleePre (wand calleePost callerPost) m.\n  Proof.\n    split; intros; fwd.\n    - revert m Hp0.\n      change (impl1 (sep calleePre Frame) (sep calleePre (wand calleePost callerPost))).\n      reify_goal. ecancel_step_by_implication. cbn [seps].\n      eapply (wand_adjoint Frame calleePost callerPost). rewrite sep_comm. unfold impl1.\n      exact Hp1.\n    - eexists. split. 1: exact H.\n      change (impl1 (sep calleePost (wand calleePost callerPost)) callerPost).\n      eapply wand_mp.\n  Qed.\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 sep_to_with_mem_and_with_mem: forall (P Q: mem -> Prop) m,\n      sep P Q m ->\n      exists m1 m2, with_mem m1 P /\\ with_mem m2 Q /\\ m1 \\*/ m2 = m.\n  Proof.\n    unfold with_mem, sep, map.split. intros. fwd. do 2 eexists. ssplit.\n    1,2: eassumption.\n    simpl. unfold map.du. eapply map.disjointb_spec in Hp0p1. rewrite Hp0p1.\n    reflexivity.\n  Qed.\n\n  Lemma sep_to_with_mem_and_unpacked: forall (P Q: mem -> Prop) m,\n      sep P Q m ->\n      exists m1 m2, with_mem m1 P /\\ Q m2 /\\ m1 \\*/ m2 = m.\n  Proof. exact sep_to_with_mem_and_with_mem. Qed.\n\n  Lemma sep_to_unpacked_and_with_mem: forall (P Q: mem -> Prop) m,\n      sep P Q m ->\n      exists m1 m2, P m1 /\\ with_mem m2 Q /\\ m1 \\*/ m2 = m.\n  Proof. exact sep_to_with_mem_and_with_mem. Qed.\n\n  Lemma sep_to_unpacked_and_unpacked: forall (P Q: mem -> Prop) m,\n      sep P Q m ->\n      exists m1 m2, P m1 /\\ Q m2 /\\ m1 \\*/ m2 = m.\n  Proof. exact sep_to_with_mem_and_with_mem. Qed.\n\n  Lemma merge_two_split_equations: forall {m} {om1 om2: mmap mem},\n      om1 = mmap.Def m ->\n      om2 = mmap.Def m ->\n      om1 \\=/ om2 = mmap.Def m.\n  Proof.\n    unfold mmap.equal_union. intros. subst. destr (mmap.map__eqb m m); congruence.\n  Qed.\n\n  Inductive mem_tree :=\n  | NLeaf(m: mem)\n  | NDisjointUnion(t1 t2: mem_tree)\n  | NEqualUnion(t1 t2: mem_tree).\n\n  Lemma invert_Some_eq_equal_union: forall m (om1 om2: mmap mem),\n      mmap.equal_union om1 om2 = mmap.Def m ->\n      om1 = mmap.Def m /\\ om2 = mmap.Def m.\n  Proof.\n    unfold mmap.equal_union. intros. fwd. auto.\n  Qed.\n\n  Fixpoint interp_mem_tree(t: mem_tree): mmap mem :=\n    match t with\n    | NLeaf m => mmap.Def m\n    | NDisjointUnion t1 t2 => mmap.du (interp_mem_tree t1) (interp_mem_tree t2)\n    | NEqualUnion t1 t2 => mmap.equal_union (interp_mem_tree t1) (interp_mem_tree t2)\n    end.\n\n  Fixpoint mem_tree_lookup(t: mem_tree)(path: list bool): option mem :=\n    match t with\n    | NLeaf m =>\n        match path with\n        | nil => Some m\n        | cons _ _ => None\n        end\n    | NDisjointUnion t1 t2 | NEqualUnion t1 t2 =>\n        match path with\n        | nil => None\n        | cons b rest => mem_tree_lookup (if b then t2 else t1) rest\n        end\n    end.\n\n  (* outer option is for Success/Failure, inner option is for whether the result\n     is empty *)\n  Fixpoint mem_tree_remove(t: mem_tree)(path: list bool): option (option mem_tree) :=\n    match t with\n    | NLeaf m =>\n        match path with\n        | nil => Some None\n        | cons _ _ => None\n        end\n    | NDisjointUnion t1 t2 =>\n        match path with\n        | nil => None (* can only remove leaves *)\n        | cons b rest =>\n            if b then\n              match mem_tree_remove t2 rest with\n              | Some (Some t2') => Some (Some (NDisjointUnion t1 t2'))\n              | Some None => Some (Some t1)\n              | None => None\n              end\n            else\n              match mem_tree_remove t1 rest with\n              | Some (Some t1') => Some (Some (NDisjointUnion t1' t2))\n              | Some None => Some (Some t2)\n              | None => None\n              end\n        end\n    | NEqualUnion t1 t2 =>\n        match path with\n        | nil => None (* can only remove leaves *)\n        | cons b rest =>\n            (* Note: only one subtree survives (and gets one leaf removed),\n               while the other subtree is completely discarded *)\n            mem_tree_remove (if b then t2 else t1) rest\n        end\n    end.\n\n  Definition canceling(Ps: list (mem -> Prop))(om: mmap mem)(Rest: Prop): Prop :=\n    (forall m, om = mmap.Def m -> seps Ps m) /\\ Rest.\n\n  Lemma canceling_start_and: forall {Ps m om Rest},\n      om = mmap.Def m ->\n      canceling (Tree.flatten Ps) om Rest ->\n      Tree.to_sep Ps m /\\ Rest.\n  Proof.\n    unfold canceling. intros. fwd. split. 2: assumption.\n    eapply Tree.flatten_iff1_to_sep. eauto.\n  Qed.\n\n  Lemma canceling_start_noand: forall {Ps m om},\n      om = mmap.Def m ->\n      canceling (Tree.flatten Ps) om True ->\n      Tree.to_sep Ps m.\n  Proof.\n    unfold canceling. intros. fwd. eapply Tree.flatten_iff1_to_sep. eauto.\n  Qed.\n\n  Lemma canceling_done_anymem: forall {om} {Rest: Prop},\n      Rest -> canceling [anymem] om Rest.\n  Proof.\n    unfold canceling, anymem. simpl. intros. auto.\n  Qed.\n\n  Lemma canceling_done_frame_generic: forall om (P: (mem -> Prop) -> Prop),\n      (* This hypothesis holds for all (P F) of the form\n         \"forall m', (calleePost * F) m' -> callerPost m'\"\n         even if it has some additional foralls and existentials that can't\n         be abstracted easily, so we'll prove this hyp with a generic Ltac *)\n      P (fun mFrame : mem => P (eq mFrame)) ->\n      (* This hypothesis verifies the rest of the program: *)\n      (forall mFrame, om = mmap.Def mFrame -> P (eq mFrame)) ->\n      canceling [fun mFrame => P (eq mFrame)] om (P (fun mFrame => P (eq mFrame))).\n  Proof.\n    intros. split; assumption.\n  Qed.\n\n  (* used to instantiate the frame with a magic wand\n     (ramification trick to avoid evar scoping issues) *)\n  Lemma canceling_done_frame_wand: forall om (calleePost callerPost: mem -> Prop),\n      let F := (wand calleePost callerPost) in\n      (forall mFrame, om = mmap.Def mFrame -> F mFrame) ->\n      canceling [F] om (forall m', sep calleePost F m' -> callerPost m').\n  Proof.\n    unfold canceling. cbn [seps]. intros. split. 1: assumption.\n    change (impl1 (sep calleePost (wand calleePost callerPost)) callerPost).\n    eapply wand_mp.\n  Qed.\n\n  (* used to instantiate the frame with an unfolded magic wand\n     (ramification trick to avoid evar scoping issues) *)\n  Lemma canceling_done_frame: forall om (calleePost callerPost: mem -> Prop),\n      (forall mNew mModified,\n          mmap.du om (mmap.Def mModified) = mmap.Def mNew ->\n          calleePost mModified -> callerPost mNew) ->\n      (* F is (wand calleePost callerPost) unfolded *)\n      let F := (fun mFrame => forall mModified mNew,\n                    mmap.du (mmap.Def mFrame) (mmap.Def mModified) = mmap.Def mNew ->\n                    calleePost mModified -> callerPost mNew) in\n      canceling [F] om (forall m', sep calleePost F m' -> callerPost m').\n  Proof.\n    intros.\n    pose proof (canceling_done_frame_wand om calleePost callerPost) as P.\n    rewrite wand_alt in P. eapply P. clear P F.\n    unfold wand'. intros. eapply H. 2: eassumption. rewrite H0. assumption.\n  Qed.\n\n  Lemma consume_mem_tree: forall {hs path m mFull},\n      mem_tree_lookup hs path = Some m ->\n      mem_tree_remove hs path = Some None ->\n      interp_mem_tree hs = mmap.Def mFull ->\n      m = mFull.\n  Proof.\n    induction hs; simpl; intros; fwd.\n    - reflexivity.\n    - destruct b; fwd; destruct o; simpl in *; fwd; discriminate.\n    - eapply invert_Some_eq_equal_union in H1. fwd.\n      destruct b; fwd; eauto.\n  Qed.\n\n  Lemma split_mem_tree: forall {hs hs' path m mFull},\n      mem_tree_lookup hs path = Some m ->\n      mem_tree_remove hs path = Some (Some hs') ->\n      interp_mem_tree hs = mmap.Def mFull ->\n      mmap.du (interp_mem_tree hs') (mmap.Def m) = mmap.Def mFull.\n  Proof.\n    induction hs; simpl; intros; fwd.\n    - discriminate.\n    - unfold mmap.du in H1. fwd.\n      destruct b; fwd.\n      + destruct o; fwd; simpl.\n        * specialize IHhs2 with (1 := H) (2 := E1) (3 := eq_refl).\n          rewrite mmap.du_assoc. rewrite IHhs2.\n          rewrite E. exact H1.\n        * pose proof (consume_mem_tree H E1 E0). subst.\n          rewrite E. exact H1.\n      + destruct o; fwd; simpl.\n        * specialize IHhs1 with (1 := H) (2 := E1) (3 := eq_refl).\n          rewrite mmap.du_assoc.\n          rewrite (mmap.du_comm (interp_mem_tree hs2) m).\n          rewrite <- mmap.du_assoc.\n          rewrite IHhs1.\n          rewrite E0. exact H1.\n        * epose proof (consume_mem_tree H E1 E). subst.\n          rewrite E0. rewrite mmap.du_comm. exact H1.\n    - eapply invert_Some_eq_equal_union in H1. fwd.\n      destruct b; fwd; eauto.\n  Qed.\n\n  Lemma cancel_head: forall hs path {P: mem -> Prop} {Ps hs' m Rest},\n      with_mem m P ->\n      mem_tree_lookup hs path = Some m ->\n      mem_tree_remove hs path = Some (Some hs') ->\n      canceling Ps (interp_mem_tree hs') Rest ->\n      canceling (P :: Ps) (interp_mem_tree hs) Rest.\n  Proof.\n    unfold with_mem, canceling. intros. destruct H2 as [H2 HR]. split; [intros |exact HR].\n    eapply seps_cons.\n    pose proof (split_mem_tree H0 H1 H3) as A.\n    unfold mmap.du in A. fwd.\n    specialize (H2 _ eq_refl).\n    eapply split_du in A.\n    eapply sep_comm.\n    exists m1, m. auto.\n  Qed.\n\n  Lemma cancel_pure_head: forall {P: Prop} {Ps om Rest},\n      P ->\n      canceling Ps om Rest ->\n      canceling (emp P :: Ps) om Rest.\n  Proof.\n    unfold canceling. intros. destruct H0 as [H2 HR]. split; [intros |exact HR].\n    eapply seps_cons. eapply sep_emp_l. eauto.\n  Qed.\n\n  Lemma canceling_last_step: forall hs path {P m} {Rest: Prop},\n      with_mem m P ->\n      mem_tree_lookup hs path = Some m ->\n      mem_tree_remove hs path = Some None ->\n      Rest ->\n      canceling [P] (interp_mem_tree hs) Rest.\n  Proof.\n    unfold canceling. simpl. intros. split. 2: assumption.\n    intros.\n    pose proof (consume_mem_tree H0 H1 H3) as A. subst. assumption.\n  Qed.\n\n  (* for home-made rewrite *)\n  Lemma subst_mem_eq(mSmall mBig: mem){omSmall: mmap mem}(C: mmap mem -> mmap mem):\n    omSmall = mmap.Def mSmall ->\n    C (mmap.Def mSmall) = mmap.Def mBig ->\n    C omSmall = mmap.Def mBig.\n  Proof. intros. rewrite <- H in H0. exact H0. Qed.\n\n  Lemma sep_from_disjointb: forall m1 m2 (P Q: mem -> Prop),\n      map.disjointb m1 m2 = true ->\n      P m1 ->\n      Q m2 ->\n      sep P Q (map.putmany m1 m2).\n  Proof.\n    intros. unfold sep, map.split. do 2 eexists. eapply map.disjointb_spec in H.\n    ssplit. 1: reflexivity. all: eassumption.\n  Qed.\nEnd HeapletwiseHyps.\n\nLtac reify_mem_tree e :=\n  lazymatch e with\n  | mmap.du ?e1 ?e2 =>\n      let t1 := reify_mem_tree e1 in\n      let t2 := reify_mem_tree e2 in\n      constr:(NDisjointUnion t1 t2)\n  | mmap.equal_union ?e1 ?e2 =>\n      let t1 := reify_mem_tree e1 in\n      let t2 := reify_mem_tree e2 in\n      constr:(NEqualUnion t1 t2)\n  | mmap.Def ?m => constr:(NLeaf m)\n  end.\n\nLtac should_unpack P :=\n lazymatch P with\n | sep _ _ => constr:(true)\n | (fun m => Some m = _) => constr:(true)\n | _ => constr:(false)\n end.\n\nLtac clear_if_dup_or_trivial H :=\n  let t := type of H in\n  lazymatch t with\n  | True => clear H\n  | ?x = ?x => clear H\n  | _ => match goal with\n         | H': t |- _ => tryif constr_eq H H' then fail else clear H\n         | |- _ => idtac\n         end\n  end.\n\nLtac heapletwise_hyp_pre_clear_default H :=\n  let tHOrig := type of H in\n  unfold with_mem in H;\n  lazymatch type of H with\n  | ?P ?m =>\n      tryif is_var P then idtac (* It's a frame, nothing to purify *)\n      else (\n        let g := open_constr:(purify P _) in\n        let pf := match constr:(Set) with\n                  | _ => constr:(ltac:(eauto with purify) : g)\n                  | _ => constr:(tt)\n                 end in\n        lazymatch pf with\n        | tt => pose_err Error:(g \"can't be solved by\" \"eauto with purify\");\n                change tHOrig in H\n        | _ => let HP := fresh \"old_\" H \"_pure\" in pose proof (pf _ H) as HP;\n               clear_if_dup_or_trivial HP\n        end\n      )\n  end.\n\nLtac heapletwise_hyp_pre_clear_hook H := heapletwise_hyp_pre_clear_default H.\n\nLtac clear_heapletwise_hyp H :=\n  let tH := type of H in\n  let m := lazymatch tH with\n           | with_mem ?m _ => m\n           | _ ?m => m\n           | _ => fail 1000 H \"has unexpected shape\" tH\n           end in\n  heapletwise_hyp_pre_clear_hook H;\n  (clear H || fail 1000 \"Can't clear\" H \": probably a bug!\");\n  try clear m.\n\nLtac clear_heapletwise_hyps :=\n  repeat match goal with\n         | _: tactic_error _ |- _ => fail 1 (* pose at most one error *)\n         | H: with_mem _ _ |- _ => clear_heapletwise_hyp H\n         end.\n\n(* can be overridden using ::= *)\nLtac same_pred_and_addr P Q :=\n  lazymatch P with\n  | ?pred ?val1 ?addr =>\n      lazymatch Q with\n      | pred ?val2 addr => idtac\n      end\n  end.\n\n(* given a new mem hyp H, replace the corresponding old mem hyp by H *)\nLtac replace_with_new_mem_hyp H :=\n  let Pnew := lazymatch type of H with\n              | with_mem _ ?Pnew => Pnew\n              | ?Pnew ?m => let __ := match constr:(O) with\n                                      | _ => change (with_mem m Pnew) in H\n                                      end in Pnew\n              end in\n  lazymatch Pnew with\n  | sep _ _ => fail \"first destruct the sep\"\n  | _ => idtac\n  end;\n  let HOld := match reverse goal with\n              | HOld: with_mem ?mOld ?Pold |- _ =>\n                  let __ := match constr:(Set) with\n                            | _ => tryif constr_eq HOld H then\n                                    fail (*bad choice of HOld: don't replace H by itself*)\n                                   else same_pred_and_addr Pnew Pold\n                            end in HOld\n              end in\n  move H before HOld;\n  clear_heapletwise_hyp HOld;\n  rename H into HOld.\n\n(* Called whenever a new heapletwise hyp is created whose type will get destructed further *)\nLtac new_heapletwise_hyp_hook h t := idtac.\n\nLtac new_mem_hyp h :=\n  let t := type of h in\n  let p := lazymatch t with\n           | with_mem ?m ?p => p\n           | ?p ?m => p\n           end in\n  lazymatch p with\n  | sep _ _ => idtac\n  | emp _ => idtac\n  | ex1 _ => idtac\n  | _ => new_heapletwise_hyp_hook h t\n  end.\n\nLtac split_sep_step :=\n  let D := fresh \"D\" in\n  let m1 := fresh \"m0\" in\n  let m2 := fresh \"m0\" in\n  let H1 := fresh \"H0\" in\n  let H2 := fresh \"H0\" in\n  lazymatch goal with\n  | H: with_mem ?m1 (eq ?m2) |- _ =>\n      match goal with\n      | H': with_mem m2 _ |- _ => move H' after H\n      | |- _ => idtac\n      end;\n      unfold with_mem in H; subst m1\n  | H: @sep _ _ ?mem ?P ?Q ?parent_m |- _ =>\n      let unpackP := should_unpack P in\n      let unpackQ := should_unpack Q in\n      lazymatch constr:((unpackP, unpackQ)) with\n      | (true, true) => eapply sep_to_unpacked_and_unpacked in H\n      | (false, true) => eapply sep_to_with_mem_and_unpacked in H\n      | (true, false) => eapply sep_to_unpacked_and_with_mem in H\n      | (false, false) => eapply sep_to_with_mem_and_with_mem in H\n      end;\n      destruct H as (m1 & m2 & H1 & H2 & D);\n      new_mem_hyp H1;\n      new_mem_hyp H2;\n      move m1 before parent_m; (* before in direction of movement == below *)\n      move m2 before m1;\n      try replace_with_new_mem_hyp H1;\n      try replace_with_new_mem_hyp H2;\n      let E := match goal with\n               | E: ?om = mmap.Def ?mBig |- _ =>\n                   lazymatch om with\n                   | context C[mmap.Def parent_m] => E\n                   end\n               | |- _ => constr:(tt) (* in first sep destruct step, there's no E yet *)\n               end in\n      (* re-match, but this time lazily, to preserve error messages: *)\n      lazymatch type of E with\n      | ?om = mmap.Def ?mBig =>\n          lazymatch om with\n          | context C[mmap.Def parent_m] =>\n              (* home-made rewrite in hyp because we already have context C *)\n              eapply (subst_mem_eq parent_m mBig\n                        (fun hole: mmap mem =>\n                           ltac:(let r := context C[hole] in exact r))\n                        D) in E;\n              (* (Some parent_m) might also appear in below the line (if canceling) *)\n              rewrite <-?D;\n              clear parent_m D\n          end\n      | unit => idtac\n      end\n  end.\n\nLtac destruct_ex1_step :=\n  lazymatch goal with\n  | H: with_mem ?m (ex1 (fun name => _)) |- _ =>\n      let x := fresh name in\n      destruct H as [x H]\n  end.\n\nLtac destruct_emp_step :=\n  lazymatch goal with\n  | H: with_mem ?m (emp ?P), D: _ = mmap.Def _ |- _ =>\n      destruct H as [? H];\n      subst m;\n      rewrite ?mmap.du_empty_l, ?mmap.du_empty_r in D\n  end.\n\n(* usually already done by split_sep_step, but when introducing hyps from the\n   frame after a call, separate merging might still be needed: *)\nLtac merge_du_step :=\n  match reverse goal with\n  | E1: ?om1 = mmap.Def ?m, E2: ?om2 = mmap.Def ?m |- _ =>\n      let D := fresh \"D\" in\n      pose proof (merge_two_split_equations E1 E2) as D;\n      clear E1 E2\n  | H: map.split _ _ _ |- _ => eapply split_du in H\n  | E1: ?om1 = @mmap.Def _ _ ?Mem ?m, E2: ?om2 = mmap.Def ?m' |- _ =>\n      lazymatch om1 with\n      | mmap.du _ _ => idtac\n      | mmap.equal_union _ _ => idtac\n      end;\n      lazymatch om2 with\n      | mmap.du _ _ => idtac\n      | mmap.equal_union _ _ => idtac\n      end;\n      lazymatch om2 with\n      | context C[mmap.Def m] =>\n          (* home-made rewrite *)\n          eapply (subst_mem_eq m m'\n                    (fun hole: mmap Mem => ltac:(let r := context C[hole] in exact r))\n                    E1) in E2;\n          clear m E1\n      end\n  | H: mmap.Def ?m1 = mmap.Def ?m2 |- _ =>\n      is_var m1; is_var m2; apply mmap.eq_of_eq_Def in H; subst m1\n  end.\n\nLtac start_canceling :=\n  lazymatch goal with\n  | D: _ = mmap.Def ?m |- sep ?P ?Q ?m /\\ ?Rest =>\n      let clausetree := reify (sep P Q) in change (Tree.to_sep clausetree m /\\ Rest);\n      eapply (canceling_start_and D)\n  | D: _ = mmap.Def ?m |- sep ?P ?Q ?m =>\n      let clausetree := reify (sep P Q) in change (Tree.to_sep clausetree m);\n      eapply (canceling_start_noand D)\n  end;\n  cbn [Tree.flatten Tree.interp bedrock2.Map.SeparationLogic.app].\n\nLtac path_in_mem_tree om m :=\n  lazymatch om with\n  | NLeaf m => constr:(@nil bool)\n  | NLeaf _ => fail \"could not find\" m \"in\" om\n  | NDisjointUnion ?t1 ?t2 =>\n      match constr:(O) with\n      | _ => let p := path_in_mem_tree t1 m in constr:(cons false p)\n      | _ => let p := path_in_mem_tree t2 m in constr:(cons true p)\n      | _ => fail 1 \"could not find\" m \"in\" om\n      end\n  | NEqualUnion ?t1 ?t2 =>\n      match constr:(O) with\n      | _ => let p := path_in_mem_tree t1 m in constr:(cons false p)\n      | _ => let p := path_in_mem_tree t2 m in constr:(cons true p)\n      | _ => fail 1 \"could not find\" m \"in\" om\n      end\n  | _ => fail \"Expected a mem_tree, but got\" om\n  end.\n\nLtac cancel_head_with_hyp H :=\n  lazymatch goal with\n  | |- canceling (cons _ ?Ps) ?om _ =>\n      let m := lazymatch type of H with with_mem ?m _ => m end in\n      let hs := reify_mem_tree om in\n      let p := path_in_mem_tree hs m in\n      let lem := lazymatch Ps with\n                 | nil => open_constr:(canceling_last_step hs p H)\n                 | cons _ _ => open_constr:(cancel_head hs p H)\n                 end in\n      eapply lem;\n      [ reflexivity\n      | reflexivity\n      | cbn [interp_mem_tree] ]\n  end.\n\nLtac canceling_step :=\n  lazymatch goal with\n  | |- canceling [anymem] _ _ => eapply canceling_done_anymem\n  | |- canceling (cons ?R ?Ps) ?om ?P =>\n      tryif is_evar R then\n        lazymatch Ps with\n        | nil =>\n            let P := lazymatch eval pattern R in P with ?f _ => f end in\n            lazymatch P with\n            | (fun _ => ?doesNotDependOnArg) => eapply canceling_done_anymem\n            | _ => eapply (canceling_done_frame_generic om P);\n                   [ solve [clear; unfold sep; intros; fwd; eauto 20] | ]\n            end\n        | cons _ _ => fail 1000 \"frame evar must be last in list\"\n        end\n      else\n        lazymatch R with\n        | emp _ => eapply cancel_pure_head\n        | _ => let H :=\n                 match goal with\n                 | H: with_mem _ ?P' |- _ =>\n                     let __ := match constr:(Set) with _ => syntactic_unify P' R end in H\n                 end in\n               cancel_head_with_hyp H\n        end\n  | |- True => constructor\n  end.\n\nLtac intro_step :=\n  lazymatch goal with\n  | m: ?mem, H: @with_mem ?mem _ _ |- forall (_: ?mem), _ =>\n      let m' := fresh \"m0\" in intro m'; move m' before m\n  | HOld: _ = mmap.Def ?mOld |- _ = mmap.Def _ -> _ =>\n      let tmp := fresh \"tmp\" in\n      intro tmp; move tmp before HOld; clear mOld HOld; rename tmp into HOld\n  | H: with_mem _ _ |- sep _ _ _ -> _ =>\n      let H' := fresh \"H0\" in\n      intro H'; move H' before H\n  end.\n\nLtac and_step :=\n  lazymatch goal with\n  | |- (fun _ => _ /\\ _) _ /\\ _ => cbv beta\n  | |- ?P /\\ _ => is_destructible_and P; eapply and_assoc\n  end.\n\nLtac heapletwise_step :=\n  first\n    [ intro_step\n    | split_sep_step\n    | destruct_ex1_step\n    | destruct_emp_step\n    | merge_du_step\n    | and_step\n    | start_canceling\n    | canceling_step ].\n\nLtac collect_heaplets_into_one_sepclause M :=\n  lazymatch goal with\n  | D: _ = mmap.Def ?m |- _ =>\n      eassert (_ m) as M;\n      unfold mmap.du in D; unfold mmap.of_option, map.du in D; fwd;\n      [ solve [ repeat lazymatch goal with\n                  | WM: with_mem ?m _ |- _ ?m => exact WM\n                  | D: map.disjointb ?m1 ?m2 = true |- _ (map.putmany ?m1 ?m2) =>\n                      eapply sep_from_disjointb; [exact D | | ]\n                  | |- ?g => fail 2 \"no heaplet hypothesis for\" g\n                  end ]\n      | ]\n  end;\n  repeat match goal with\n    | H: with_mem _ _ |- _ => clear H\n    | H: map.disjointb _ _ = true |- _ => clear H\n    end;\n  lazymatch type of M with\n  | _ ?putmanys =>\n      let m := fresh \"m0\" in forget putmanys as m;\n      let mem := type of m in\n      repeat match goal with\n        | heaplet: mem |- _ => clear heaplet\n        end\n  end.\n\nSection HeapletwiseHypsTests.\n  Context {key value: Type} {mem: map.map key value} {mem_ok: map.ok mem}\n          {key_eqb: key -> key -> bool} {key_eqb_spec: EqDecider key_eqb}.\n\n  Hypothesis scalar: nat -> nat -> mem -> Prop.\n\n  Lemma purify_scalar: forall v a, purify (scalar v a) True.\n  Proof. unfold purify. intros. constructor. Qed.\n  Hint Resolve purify_scalar: purify.\n\n  Context (fname: Type).\n  Context (cmd: Type) (trace: Type) (locals: Type).\n  Context (cmd_call: fname -> list nat -> cmd).\n  Context (wp: cmd -> trace -> mem -> locals -> (trace -> mem -> locals -> Prop) -> Prop).\n\n  Context (call: fname -> trace -> mem -> list nat ->\n                 (trace -> mem -> list nat -> Prop) -> Prop).\n\n  Context (update_locals: locals -> list nat -> locals -> Prop).\n\n  (* each program logic needs to prove & apply a lemma to shoehorn its function specs\n     from the definition-site format into the use-site format: *)\n  Hypothesis wp_call: forall f t m args l\n      (calleePre: Prop)\n      (calleePost: trace -> mem -> list nat -> Prop)\n      (callerPost: trace -> mem -> locals -> Prop),\n      (* definition-site format: *)\n      (calleePre -> call f t m args calleePost) ->\n      (* use-site format: *)\n      (calleePre /\\\n         forall t' m' l' rets,\n           calleePost t' m' rets -> update_locals l rets l' -> callerPost t' m' l') ->\n      (* conclusion: *)\n      wp (cmd_call f args) t m l callerPost.\n\n  Context (frobnicate: fname).\n  Context (frobnicate_ok: forall (a1 a2 v1 v2: nat) t m (R: mem -> Prop),\n              sep (sep (emp True) (scalar v1 a1)) (sep (scalar v2 a2) R) m ->\n              call frobnicate t m [a1; a2] (fun t' m' rets =>\n                   exists d, rets = [d] /\\ d <= v1 /\\\n                   sep (scalar (v1 + v2 + d) a1) (sep (scalar (v1 - v2 - d) a2) R) m')).\n\n  Ltac program_logic_step :=\n    match goal with\n    | |- forall _, _ => intro\n    | H: with_mem _ (scalar ?v ?a) |- canceling (cons (scalar ?v' ?a) _) _ _ =>\n        replace v with v' in H by Lia.lia\n    | |- _ => progress fwd\n    | |- wp (cmd_call frobnicate _) _ _ _ _ => eapply wp_call; [eapply frobnicate_ok | ]\n    | |- exists _, _ => eexists\n    end.\n\n  Ltac step := first [ heapletwise_step | program_logic_step ].\n\n  Goal forall m v1 v2 v3 v4 (Rest: mem -> Prop),\n      (sep (scalar v1 1) (sep (sep (scalar v2 2) (scalar v3 3)) (sep (scalar v4 4) Rest))) m ->\n      exists R a4 a3, sep (sep (scalar a4 4) (scalar a3 3)) R m.\n  Proof.\n    step. step. step. step. step. step. step.\n    (* split seps into separate hyps: *)\n    step. step. step. step.\n    (* just for desting, join them back together: *)\n    let H := fresh in collect_heaplets_into_one_sepclause H.\n    (* and split again: *)\n    step. step. step. step.\n    (* existentials: *)\n    step. step. step.\n    start_canceling.\n\n(*\n  m, m0, m3, m5, m1, m4 : mem\n  v1, v2, v3, v4 : nat\n  Rest : mem -> Prop\n  H0 : m0 |= scalar v1 1\n  H3 : m3 |= scalar v2 2\n  H5 : m5 |= scalar v3 3\n  H1 : m1 |= scalar v4 4\n  H4 : m4 |= Rest\n  D : m0 \\*/ ((m3 \\*/ m5) \\*/ (m1 \\*/ m4)) = m\n  ============================\n  canceling [scalar ?a4 4; scalar ?a3 3; ?R] (m0 \\*/ ((m3 \\*/ m5) \\*/ (m1 \\*/ m4))) True\n*)\n\n    canceling_step.\n    canceling_step.\n    canceling_step.\n    step.\n  Qed.\n\n  (* sample caller: *)\n  Goal forall (p1 p2 p3 x y: nat) t (m: mem) l (R: mem -> Prop),\n      sep (scalar x p1) (sep (scalar y p2) (sep (scalar x p3) R)) m ->\n      wp (cmd_call frobnicate [p1; p3]) t m l (fun t m l =>\n        wp (cmd_call frobnicate [p3; p1]) t m l (fun t m l =>\n           exists res,\n           sep (scalar 0 p1) (sep (scalar y p2) (sep (scalar res p3) R)) m)).\n  Proof.\n    repeat step.\n  Qed.\n\n  Let scalar_pair(v1 v2 a1 a2: nat) := sep (scalar v1 a1) (scalar v2 a2).\n\n  Lemma purify_scalar_pair: forall v1 v2 a1 a2, purify (scalar_pair v1 v2 a1 a2) True.\n  Proof. unfold purify. intros. constructor. Qed.\n  Hint Resolve purify_scalar_pair : purify.\n\n  (* sample caller where argument is a field: *)\n  Goal forall (p1 p2 p3 x y: nat) t m l (R: mem -> Prop),\n      sep (scalar x p1) (sep (scalar_pair y x p2 p3) R) m ->\n      wp (cmd_call frobnicate [p1; p3]) t m l (fun t m l =>\n        wp (cmd_call frobnicate [p3; p1]) t m l (fun t m l =>\n           exists res, (* TODO: scalar_pair in postcondition *)\n           sep (scalar 0 p1) (sep (scalar y p2) (sep (scalar res p3) R)) m)).\n  Proof.\n    repeat step.\n\n    (* unfolding/splitting hyp during cancellation: *)\n    unfold scalar_pair in H2.\n    unfold with_mem in H2.\n\n    step. (* <-- substitutes (mmap.Def m2) both in D and in the goal *)\n    step.\n    step. (* <- instantiates the frame ?R with a P that gets passed itself as an argument,\n                see canceling_done_frame_generic *)\n    step. step. step. step. step. step. step. step. step. step. step. step. step.\n\n    repeat step.\n  Qed.\n\n(* sample unfolded spec of indirect_add:\n\n    forall (a b c va : word) (Ra : mem -> Prop) (vb : word)\n         (Rb : mem -> Prop) (vc : word) (Rc : mem -> Prop) (t : trace)\n         (m : mem),\n       (scalar a va ⋆ Ra)%sep m /\\ (scalar b vb ⋆ Rb)%sep m /\\ (scalar c vc ⋆ Rc)%sep m ->\n       call functions \"indirect_add\" t m [a; b; c]\n         (fun (t' : trace) (m' : mem) (rets : list word) =>\n          rets = [] /\\ t = t' /\\ (scalar a (word.add vb vc) ⋆ Ra)%sep m')\n\n*)\n\n  Context (aliasing_add: fname).\n  Hypothesis aliasing_add_ok: forall a b c va vb vc (Ra Rb Rc: mem -> Prop) t m,\n      sep (scalar va a) Ra m /\\\n      sep (scalar vb b) Rb m /\\\n      sep (scalar vc c) Rc m ->\n      call aliasing_add t m [c; a; b] (fun t' m' rets =>\n        sep (scalar (va + vb) c) Rc m').\n\n  Goal forall x y z vx vy vz (R: mem -> Prop) t m l,\n      sep (scalar vx x) (sep (scalar vy y) (sep (scalar vz z) R)) m ->\n      wp (cmd_call aliasing_add [x; y; z]) t m l (fun t m l =>\n        wp (cmd_call aliasing_add [x; y; y]) t m l (fun t m l =>\n          wp (cmd_call aliasing_add [x; x; z]) t m l (fun t m l =>\n            wp (cmd_call aliasing_add [x; x; x]) t m l (fun t m l =>\n              sep (scalar (vy + vy + vz + (vy + vy + vz)) x)\n                (sep (scalar vy y) (sep (scalar vz z) R)) m)))).\n  Proof.\n    clear frobnicate frobnicate_ok scalar_pair.\n    intros.\n    repeat step.\n    eapply wp_call. 1: eapply aliasing_add_ok.\n    repeat step.\n    eapply wp_call. 1: eapply aliasing_add_ok.\n    repeat step.\n    eapply wp_call. 1: eapply aliasing_add_ok.\n    repeat step.\n    eapply wp_call. 1: eapply aliasing_add_ok.\n    repeat step.\n  Qed.\nEnd HeapletwiseHypsTests.\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/HeapletwiseHyps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.4610167793123158, "lm_q1q2_score": 0.28014292401424185}}
{"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(* ===== bit_blast_concat ===== *)\n\nDefinition bit_blast_concat g ls1 ls0 : generator * cnf * word :=\n  (g, [::], ls0 ++ ls1) .\n\nDefinition mk_env_concat E g ls1 ls0 : env * generator * cnf * word :=\n  (E, g, [::], ls0 ++ ls1) .\n\nLemma bit_blast_concat_correct E g bs0 bs1 ls0 ls1 g' cs lr :\n  bit_blast_concat g ls1 ls0 = (g', cs, lr) ->\n    enc_bits E ls0 bs0 ->\n    enc_bits E ls1 bs1 ->\n    enc_bits E lr (cat bs0 bs1) .\nProof .\n  case => _ _ <-; exact: enc_bits_cat .\nQed .\n\nLemma mk_env_concat_is_bit_blast_concat E g ls0 ls1 E' g' cs lr :\n  mk_env_concat E g ls1 ls0 = (E', g', cs, lr) ->\n  bit_blast_concat g ls1 ls0 = (g', cs, lr) .\nProof .\n  rewrite /mk_env_concat /bit_blast_concat .\n  case => _ <- <- <- // .\nQed .\n\nLemma mk_env_concat_newer_gen E g ls0 ls1 E' g' cs lr :\n  mk_env_concat E g ls1 ls0 = (E', g', cs, lr) ->\n  (g <=? g')%positive .\nProof .\n  rewrite /mk_env_concat; case => _ <- _ _ .\n  t_auto_newer .\nQed .\n\nLemma mk_env_concat_newer_res E g ls0 ls1 E' g' cs lrs :\n  mk_env_concat E g ls1 ls0 = (E', g', cs, lrs) ->\n  newer_than_lits g ls0 -> newer_than_lits g ls1 ->\n  newer_than_lits g' lrs .\nProof .\n  rewrite /mk_env_concat; case => _ <- _ <- Hls0 Hls1 .\n  rewrite newer_than_lits_cat Hls0 Hls1 // .\nQed .\n\nLemma mk_env_concat_newer_cnf E g ls0 ls1 E' g' cs lrs :\n  mk_env_concat E g ls1 ls0 = (E', g', cs, lrs) ->\n  newer_than_lits g ls0 -> newer_than_lits g ls1 ->\n  newer_than_cnf g' cs .\nProof .\n  rewrite /mk_env_concat; case => _ <- <- _ // .\nQed .\n\nLemma mk_env_concat_preserve E g ls0 ls1 E' g' cs lrs :\n  mk_env_concat E g ls1 ls0 = (E', g', cs, lrs) -> env_preserve E E' g .\nProof .\n  rewrite /mk_env_concat; case => <- _ _ _ // .\nQed .\n\nLemma mk_env_concat_sat E g ls0 ls1 E' g' cs lrs :\n  mk_env_concat E g ls1 ls0 = (E', g', cs, lrs) ->\n  newer_than_lits g ls0 -> newer_than_lits g ls1 ->\n  interp_cnf E' cs .\nProof .\n  rewrite /mk_env_concat; case => <- _ <- _ // .\nQed .\n\nLemma mk_env_concat_env_equal E1 E2 g ls1 ls2 E1' E2' g1' g2' cs1 cs2 lrs1 lrs2 :\n  env_equal E1 E2 ->\n  mk_env_concat E1 g ls1 ls2 = (E1', g1', cs1, lrs1) ->\n  mk_env_concat E2 g ls1 ls2 = (E2', g2', cs2, lrs2) ->\n  env_equal E1' E2' /\\ g1' = g2' /\\ cs1 = cs2 /\\ lrs1 = lrs2.\nProof.\n  rewrite /mk_env_concat => 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/BBConcat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2801429174630725}}
{"text": "Require Import Program.Equality Ring Lia Omega.\nFrom mathcomp Require Import ssreflect ssrfun ssrbool seq eqtype ssrnat.\nFrom istari Require Import source subst_src rules_src lemmas0.\nFrom istari Require Import Sigma Tactics\n     Syntax Subst SimpSub Promote Hygiene\n     ContextHygiene Equivalence Rules Defined.\n\nDefinition oof M A: (@Syntax.judgement obj) := deq M M A.\n\nDefinition oof_t M: (@Syntax.judgement obj) := deqtype M M.\n(*more useful inference rules*)\n\nLemma tr_arrow_elim: forall G a b m n p q,\n    tr G (deqtype a a) ->\n    tr G (deqtype b b) ->\n      tr G (deq m n (arrow a b))\n      -> tr G (deq p q a) \n      -> tr G (deq (app m p) (app n q) b).\nintros. \nsuffices: (subst1 p (subst sh1 b)) = b. move => Heq.\nrewrite - Heq.\neapply (tr_pi_elim _ a); try assumption.\neapply tr_eqtype_convert; try apply tr_arrow_pi_equal; assumption.\nsimpsub. auto. Qed.\n\nLemma tr_arrow_intro: forall G a b m n,\n    tr G (deqtype a a) ->\n      tr G (deqtype b b)\n      -> tr (cons (hyp_tm a) G) (deq m n (subst sh1 b))\n      -> tr G (deq (lam m) (lam n) (arrow a b) ).\nintros. eapply tr_eqtype_convert.\napply tr_eqtype_symmetry. apply tr_arrow_pi_equal; try assumption.\neapply tr_pi_intro; try assumption. Qed.\n\nLemma tr_karrow_elim: forall G a b m n p q,\n    tr G (deqtype a a) ->\n    tr G (deqtype b b) ->\n      tr G (deq m n (karrow a b))\n      -> tr G (deq p q a) \n      -> tr G (deq (app m p) (app n q) b).\n  intros. apply (tr_arrow_elim _ a); try assumption.\n  eapply tr_eqtype_convert. apply tr_eqtype_symmetry.\n  apply tr_arrow_karrow_equal; assumption.\n  assumption. Qed.\n\nLemma kind_type: forall {G K i},\n    tr G (deq K K (kuniv i)) -> tr G (deqtype K K).\n  move => G K i H. eapply tr_formation_weaken.\n  eapply tr_kuniv_weaken. apply H. Qed.\n\nLemma tr_prod_intro G A B M M' N N' :\n    tr G (deq M M' A) -> tr G (deq N N' B) ->\n    tr G (deq (ppair M N) (ppair M' N') (prod A B)).\n  intros H0 H1.\n  pose proof (tr_inhabitation_formation _#4 H0) as Ha.\n  pose proof (tr_inhabitation_formation _#4 H1) as Hb.\n  eapply tr_eqtype_convert.\n  apply tr_eqtype_symmetry. apply tr_prod_sigma_equal; try assumption.\n  eapply tr_sigma_intro; try assumption. simpsub. assumption.\n  match goal with |- tr ?G' ?J => change J with (substj (under 0 sh1)\n                                                    (deqtype B B));\n                                  change G' with (nil ++ G') end.\n  change nil with (@substctx Rules.obj sh1 nil).\n  apply tr_weakening. assumption.\n  Qed.\n\nLemma tr_booltp_eta_hyp0 :\n    forall G m n p q a,\n      tr G (deq m n (subst1 btrue a))\n      -> tr G (deq p q (subst1 bfalse a))\n      -> tr ((hyp_tm booltp)::G) (deq \n              (bite (var 0) \n                 (subst sh1 m)\n                 (subst sh1 p))\n              (bite (var 0)\n                 (subst sh1 n) \n                 (subst sh1 q) )\n              a).\n  intros. rewrite - (cat0s ((hyp_tm booltp)::G)).\n  change (sh1) with (@ under obj 0 sh1).\n  change 0 with (size ([::]: @context False)).\n  apply tr_booltp_eta_hyp; simpl; assumption.\nQed. \n\n\nLemma tr_weakening_appends: forall G1 G2 G3 J1 J2 t J1' J2' t',\n    tr G1 (deq J1 J2 t) ->\n    J1' = (shift (size G2) J1) ->\n    J2' = (shift (size G2) J2) ->\n    t' = (shift (size G2) t) ->\n    G3 = G2 ++ G1 ->\n      tr G3 (deq J1' J2' t').\n move => G1 G2.  induction G2; intros.\n -  simpl. subst. repeat rewrite - subst_sh_shift. simpsub. assumption.\n -\n  suffices: (tr (substctx sh1 [::] ++ cons a (G2 ++ G1))\n                (substj (under (length [::]) sh1)\n                        (substj (sh (size G2)) (deq J1 J2 t)))).\n  move => Hdone.\n  simpl in Hdone. subst.\n  rewrite (size_ncons 1).\n  rewrite - plusE. \n  repeat rewrite subst_sh_shift.\n  repeat rewrite - shift_sum.\n  repeat rewrite subst_sh_shift in Hdone.\n  rewrite cat_cons.\n apply (Hdone False). \n intros.\n eapply tr_weakening.\n simpl. repeat rewrite subst_sh_shift. eapply IHG2; try reflexivity. assumption.\nQed.\n\n Lemma tr_weakening_append: forall (G1: context) G2 J1 J2 t,\n      tr G1 (deq J1 J2 t) ->\n      tr (G2 ++ G1) (\n                       (deq (shift (size G2) J1)\n                            (shift (size G2) J2)\n                            (shift (size G2) t))).\n   move =>> H. eapply tr_weakening_appends; try apply H; try reflexivity.\n   Qed.\n\n Lemma tr_weakening_appendt: forall (G1: context) G2 J1 J2,\n      tr G1 (deqtype J1 J2) ->\n      tr (G2 ++ G1) (deqtype (shift (size G2) J1)\n                             (shift (size G2) J2)).\n   intros. unfold deqtype.\n   rewrite - ! subst_sh_shift - subst_eqtype.\n   change triv with (@shift obj (size G2) triv).\n   rewrite ! subst_sh_shift. apply tr_weakening_append.\n   assumption. Qed.\n\n Lemma tr_weakening_append1: forall G1 x J1 J2 t,\n      tr G1 (deq J1 J2 t) ->\n      tr (x::G1) (\n                       (deq (shift 1 J1)\n                            (shift 1 J2)\n                            (shift 1 t))).\n   intros. rewrite make_app1. apply tr_weakening_append. assumption. Qed.\n\n Lemma tr_weakening_append2: forall G1 x y J1 J2 t,\n      tr G1 (deq J1 J2 t) ->\n      tr (x::y::G1) (\n                       (deq (shift 2 J1)\n                            (shift 2 J2)\n                            (shift 2 t))).\n   intros. rewrite make_app2. apply tr_weakening_append. assumption. Qed.\n\n Lemma tr_weakening_append3: forall G1 x y z J1 J2 t,\n      tr G1 (deq J1 J2 t) ->\n      tr (x::y::z::G1) (\n                       (deq (shift 3 J1)\n                            (shift 3 J2)\n                            (shift 3 t))).\n   intros. rewrite make_app3. apply tr_weakening_append. assumption. Qed.\n\nLemma tr_weakening_append4: forall G1 x y z a J1 J2 t,\n      tr G1 (deq J1 J2 t) ->\n      tr (x::y::z::a::G1) (\n                       (deq (shift 4 J1)\n                            (shift 4 J2)\n                            (shift 4 t))).\n   intros. rewrite make_app4. apply tr_weakening_append. assumption. Qed.\n\nLemma tr_weakening_append5: forall G1 x y z a b J1 J2 t,\n      tr G1 (deq J1 J2 t) ->\n      tr (x::y::z::a::b::G1) (\n                       (deq (shift 5 J1)\n                            (shift 5 J2)\n                            (shift 5 t))).\n   intros. rewrite make_app5. apply tr_weakening_append. assumption. Qed.\nLemma tr_weakening_append6: forall G1 x y z a b c J1 J2 t,\n      tr G1 (deq J1 J2 t) ->\n      tr (x::y::z::a::b::c::G1) (\n                       (deq (shift 6 J1)\n                            (shift 6 J2)\n                            (shift 6 t))).\n   intros. rewrite make_app6.  apply tr_weakening_append. assumption. Qed.\n\nLemma tr_weakening_append7: forall G1 x y z a b c d J1 J2 t,\n      tr G1 (deq J1 J2 t) ->\n      tr (x::y::z::a::b::c::d::G1) (\n                       (deq (shift 7 J1)\n                            (shift 7 J2)\n                            (shift 7 t))).\n  intros. change [:: x, y, z, a, b, c, d & G1] with\n             ( [:: x; y; z; a; b; c; d] ++ G1).\n  apply tr_weakening_append. assumption. Qed.\n\nLemma tr_weakening_append8: forall G1 x y z a b c d e J1 J2 t,\n      tr G1 (deq J1 J2 t) ->\n      tr (x::y::z::a::b::c::d::e::G1) (\n                       (deq (shift 8 J1)\n                            (shift 8 J2)\n                            (shift 8 t))).\n  intros. change [:: x, y, z, a, b, c, d, e & G1] with\n             ( [:: x; y; z; a; b; c; d; e] ++ G1).\n  apply tr_weakening_append. assumption. Qed.\n\nLemma deqtype_intro :\n  forall G a b m n,\n    tr G (deq m n (eqtype a b))\n    -> tr G (deqtype a b).\nProof.\nintros G a b m n H.\nunfold deqtype.\napply (tr_transitivity _ _ m).\n  {\n  apply tr_symmetry.\n  apply tr_eqtype_eta.\n  apply (tr_transitivity _ _ n); auto.\n  apply tr_symmetry; auto.\n  }\n\n  {\n  apply tr_eqtype_eta.\n  apply (tr_transitivity _ _ n); auto.\n  apply tr_symmetry; auto.\n  }\nQed.\n\nLemma tr_eqtype_reflexivity:\n  forall G a a',\n    tr G (deqtype a a') ->\n    tr G (deqtype a a).\n  intros  G a a' H0. pose proof (tr_eqtype_symmetry _#3 H0) as H1.\n  apply (tr_eqtype_transitivity _#4 H0 H1).\nQed.\n\nLemma tr_eq_reflexivity:\n  forall G m n a,\n    tr G (deq m n a) ->\n    tr G (deq m m a).\n  intros  G m n a H0. pose proof (tr_symmetry _#4 H0) as H1.\n  apply (tr_transitivity _#5 H0 H1).\nQed.\n\n\nLemma deq_intro :\n  forall G a m n p q,\n    tr G (deq p q (equal a m n))\n    -> tr G (deq m n a).\nProof.\nintros G a m n p q H.\napply tr_equal_elim.\napply (tr_transitivity _ _ p).\n  {\n  apply tr_symmetry.\n  apply tr_equal_eta.\n  apply (tr_transitivity _ _ q); auto.\n  apply tr_symmetry; auto.\n  }\n\n  {\n  apply tr_equal_eta.\n  apply (tr_transitivity _ _ q); auto.\n  apply tr_symmetry; auto.\n  }\nQed.\n\nLtac prove_equiv_compat :=\n  intros;\n  apply equiv_compat;\n  apply mc_oper; repeat2 (apply mcr_cons); [.. | apply mcr_nil]; auto.\n\nLemma equiv_eqtype {a a' b b'}:\n    equiv a a'\n    -> equiv b b'\n    -> equiv (eqtype a b) (@eqtype obj a' b').\n  prove_equiv_compat.\nQed.\n\n\n\nLemma equiv_equalterm {a a' m m' n n'}:\n    equiv a a'\n    -> equiv m m'\n    -> equiv n n'\n    -> equiv (equal a m n) (@equal obj a' m' n').\n  prove_equiv_compat.\nQed.\n", "meta": {"author": "naomiiiiiiiii", "repo": "iota_embedding", "sha": "2f8d5c9b6a2a8a701bfbaea1286e313d7a0012bd", "save_path": "github-repos/coq/naomiiiiiiiii-iota_embedding", "path": "github-repos/coq/naomiiiiiiiii-iota_embedding/iota_embedding-2f8d5c9b6a2a8a701bfbaea1286e313d7a0012bd/derived_rules.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2801429109119031}}
{"text": "(** * PHOAS Representation of Gallina which allows exact denotation *)\nRequire Import Coq.Strings.String.\nRequire Import Crypto.Compilers.Syntax.\nRequire Import Crypto.Compilers.SmartMap.\nRequire Import Crypto.Compilers.ExprInversion.\nRequire Import Crypto.Compilers.InterpProofs.\nRequire Import Crypto.Util.Tuple.\nRequire Import Crypto.Util.LetIn.\nRequire Import Crypto.Util.Tactics.RewriteHyp.\nRequire Import Crypto.Util.Notations.\n\n(** We parameterize the language over a type of basic type codes (for\n    things like [Z], [word], [bool]), as well as a type of n-ary\n    operations returning one value, and n-ary operations returning two\n    values. *)\nLocal Open Scope ctype_scope.\nSection language.\n  Context (base_type_code : Type).\n\n  Local Notation flat_type := (flat_type base_type_code).\n  Inductive type := Tflat (A : flat_type) | Arrow (A : flat_type) (B : type).\n\n  Section expr_param.\n    Context (interp_base_type : base_type_code -> Type).\n    Context (op : flat_type (* input tuple *) -> flat_type (* output type *) -> Type).\n    Local Notation interp_flat_type_gen := interp_flat_type.\n    Local Notation interp_flat_type := (interp_flat_type interp_base_type).\n\n    Fixpoint interp_type (t : type) :=\n      match t with\n      | Tflat A => interp_flat_type A\n      | Arrow A B => (interp_flat_type A -> interp_type B)%type\n      end.\n\n    Section expr.\n      Context {var : flat_type -> Type}.\n\n      (** N.B. [Let] destructures pairs *)\n      Inductive exprf : flat_type -> Type :=\n      | Const {t : flat_type} : interp_flat_type t -> exprf t\n      | Var {t} : var t -> exprf t\n      | Op {t1 tR} : op t1 tR -> exprf t1 -> exprf tR\n      | LetIn : forall {tx}, exprf tx -> forall {tC}, (var tx -> exprf tC) -> exprf tC\n      | Pair : forall {t1}, exprf t1 -> forall {t2}, exprf t2 -> exprf (Prod t1 t2)\n      | MatchPair : forall {t1 t2}, exprf (Prod t1 t2) -> forall {tC}, (var t1 -> var t2 -> exprf tC) -> exprf tC.\n      Inductive expr : type -> Type :=\n      | Return {T} : exprf T -> expr (Tflat T)\n      | Abs {src dst} : (var src -> expr dst) -> expr (Arrow src dst).\n\n      Definition Fst {t1 t2} (v : exprf (Prod t1 t2)) : exprf t1 := MatchPair v (fun x y => Var x).\n      Definition Snd {t1 t2} (v : exprf (Prod t1 t2)) : exprf t2 := MatchPair v (fun x y => Var y).\n    End expr.\n\n    Definition Expr (t : type) := forall var, @expr var t.\n\n    Section interp.\n      Context (interp_op : forall src dst, op src dst -> interp_flat_type src -> interp_flat_type dst).\n\n      Fixpoint interpf {t} (e : @exprf interp_flat_type t) : interp_flat_type t\n        := match e in exprf t return interp_flat_type t with\n           | Const _ x => x\n           | Var _ x => x\n           | Op _ _ op args => @interp_op _ _ op (@interpf _ args)\n           | LetIn _ ex _ eC => dlet x := @interpf _ ex in @interpf _ (eC x)\n           | Pair _ ex _ ey => (@interpf _ ex, @interpf _ ey)\n           | MatchPair _ _ ex _ eC => match @interpf _ ex with pair x y => @interpf _ (eC x y) end\n           end.\n      Fixpoint interp {t} (e : @expr interp_flat_type t) : interp_type t\n        := match e in expr t return interp_type t with\n           | Return _ v => interpf v\n           | Abs _ _ f => fun x => @interp _ (f x)\n           end.\n\n      Definition Interp {t} (E : Expr t) : interp_type t := interp (E _).\n    End interp.\n\n    Section compile.\n      Context {var : base_type_code -> Type}\n              (make_const : forall t, interp_base_type t -> op Unit (Tbase t)).\n\n      Fixpoint compilet (t : type) : Syntax.type base_type_code\n        := Syntax.Arrow\n             match t with\n             | Tflat T => Unit\n             | Arrow A (Tflat B) => A\n             | Arrow A B\n               => A * domain (compilet B)\n             end%ctype\n             match t with\n             | Tflat T => T\n             | Arrow A B => codomain (compilet B)\n             end.\n\n      Fixpoint SmartConst (t : flat_type) : interp_flat_type t -> Syntax.exprf base_type_code op (var:=var) t\n        := match t return interp_flat_type t -> Syntax.exprf _ _ t with\n           | Unit => fun _ => TT\n           | Tbase _ => fun v => Syntax.Op (make_const _ v) TT\n           | Prod _ _ => fun v => Syntax.Pair (@SmartConst _ (fst v))\n                                              (@SmartConst _ (snd v))\n           end.\n\n      Fixpoint compilef {t} (e : @exprf (interp_flat_type_gen var) t) : @Syntax.exprf base_type_code op var t\n        := match e in exprf t return @Syntax.exprf _ _ _ t with\n           | Const _ x => @SmartConst _ x\n           | Var _ x => SmartMap.SmartVarf x\n           | Op _ _ op args => Syntax.Op op (@compilef _ args)\n           | LetIn _ ex _ eC => Syntax.LetIn (@compilef _ ex) (fun x => @compilef _ (eC x))\n           | Pair _ ex _ ey => Syntax.Pair (@compilef _ ex) (@compilef _ ey)\n           | MatchPair _ _ ex _ eC => Syntax.LetIn (@compilef _ ex) (fun xy => @compilef _ (eC (fst xy) (snd xy)))\n           end.\n\n      (* ugh, so much manual annotation *)\n      Fixpoint compile {t} (e : @expr (interp_flat_type_gen var) t) : @Syntax.expr base_type_code op var (compilet t)\n        := match e in expr t return @Syntax.expr _ _ _ (compilet t) with\n           | Return _ v => Syntax.Abs (fun _ => compilef v)\n           | Abs src dst f\n             => let res := fun x => @compile _ (f x) in\n                match dst\n                      return (_ -> Syntax.expr _ _ (compilet dst))\n                             -> Syntax.expr _ _ (compilet (Arrow src dst))\n                with\n                | Tflat T\n                  => fun resf => Syntax.Abs (fun x => invert_Abs (resf x) tt)\n                | Arrow A B as dst'\n                  => match compilet dst' as cdst\n                           return (_ -> Syntax.expr _ _ cdst)\n                                  -> Syntax.expr _ _ (Syntax.Arrow\n                                                        (_ * domain cdst)\n                                                        (codomain cdst))\n                     with\n                     | Syntax.Arrow A' B'\n                       => fun resf => Syntax.Abs (fun x : interp_flat_type_gen var (_ * _)\n                                                  => invert_Abs (resf (fst x)) (snd x))\n                     end\n                end res\n               end.\n    End compile.\n\n    Definition Compile\n               (make_const : forall t, interp_base_type t -> op Unit (Tbase t))\n               {t} (e : Expr t) : Syntax.Expr base_type_code op (compilet t)\n      := fun var => compile make_const (e _).\n\n    Section compile_correct.\n      Context (make_const : forall t, interp_base_type t -> op Unit (Tbase t))\n              (interp_op : forall src dst, op src dst -> interp_flat_type src -> interp_flat_type dst)\n              (make_const_correct : forall T v, interp_op Unit (Tbase T) (make_const T v) tt = v).\n\n      Lemma SmartConst_correct t v\n        : Syntax.interpf interp_op (SmartConst make_const t v) = v.\n      Proof using Type*.\n        induction t; try destruct v; simpl in *; congruence.\n      Qed.\n\n      Lemma compilef_correct {t} (e : @exprf interp_flat_type t)\n      : Syntax.interpf interp_op (compilef make_const e) = interpf interp_op e.\n      Proof using Type*.\n        induction e;\n          repeat match goal with\n                 | _ => reflexivity\n                 | _ => progress unfold LetIn.Let_In\n                 | _ => progress simpl in *\n                 | _ => rewrite interpf_SmartVarf\n                 | _ => rewrite SmartConst_correct\n                 | _ => rewrite <- surjective_pairing\n                 | _ => progress rewrite_hyp *\n                 | [ |- context[let (x, y) := ?v in _] ]\n                   => rewrite (surjective_pairing v); cbv beta iota\n                 end.\n      Qed.\n\n      Lemma compile_flat_correct {T} (e : expr (Tflat T))\n      : forall x, Syntax.interp interp_op (compile make_const e) x = interp interp_op e.\n      Proof using Type*.\n        intros []; simpl.\n        let G := match goal with |- ?G => G end in\n        let G := match (eval pattern T, e in G) with ?G _ _ => G end in\n        refine match e in expr t return match t return expr t -> _ with\n                                        | Tflat T => G T\n                                        | _ => fun _ => True\n                                        end e\n               with\n               | Return _ _ => _\n               | Abs _ _ _ => I\n               end; simpl.\n        apply compilef_correct.\n      Qed.\n\n      Lemma Compile_flat_correct_flat {T} (e : Expr (Tflat T))\n        : forall x, Syntax.Interp interp_op (Compile make_const e) x = Interp interp_op e.\n      Proof using Type*. apply compile_flat_correct. Qed.\n\n      Lemma Compile_correct {src dst} (e : @Expr (Arrow src (Tflat dst)))\n      : forall x, Syntax.Interp interp_op (Compile make_const e) x = Interp interp_op e x.\n      Proof using Type*.\n        unfold Interp, Compile, Syntax.Interp; simpl.\n        pose (e interp_flat_type) as E.\n        repeat match goal with |- context[e ?f] => change (e f) with E end.\n        clearbody E; clear e.\n        let G := match goal with |- ?G => G end in\n        let G := match (eval pattern src, dst, E in G) with ?G _ _ _ => G end in\n        refine match E in expr t return match t return expr t -> _ with\n                                        | Arrow src (Tflat dst) => G src dst\n                                        | _ => fun _ => True\n                                        end E\n               with\n               | Abs src dst e\n                 => match dst\n                          return (forall e : _ -> expr dst,\n                                     match dst return expr (Arrow src dst) -> _ with\n                                     | Tflat dst => G src dst\n                                     | _ => fun _ => True\n                                     end (Abs e))\n                    with\n                    | Tflat _\n                      => fun e0 x\n                         => _\n                    | Arrow _ _ => fun _ => I\n                    end e\n               | Return _ _ => I\n               end; simpl.\n        refine match e0 x as e0x in expr t\n                     return match t return expr t -> _ with\n                            | Tflat _\n                              => fun e0x\n                                 => Syntax.interpf _ (invert_Abs (compile _ e0x) _)\n                                    = interp _ e0x\n                            | _ => fun _ => True\n                            end e0x\n               with\n               | Abs _ _ _ => I\n               | Return _ _ => _\n               end; simpl.\n        apply compilef_correct.\n      Qed.\n    End compile_correct.\n  End expr_param.\nEnd language.\n\nGlobal Arguments Arrow {_} _ _.\nGlobal Arguments Tflat {_} _.\nGlobal Arguments Const {_ _ _ _ _} _.\nGlobal Arguments Var {_ _ _ _ _} _.\nGlobal Arguments Op {_ _ _ _ _ _} _ _.\nGlobal Arguments LetIn {_ _ _ _ _} _ {_} _.\nGlobal Arguments MatchPair {_ _ _ _ _ _} _ {_} _.\nGlobal Arguments Fst {_ _ _ _ _ _} _.\nGlobal Arguments Snd {_ _ _ _ _ _} _.\nGlobal Arguments Pair {_ _ _ _ _} _ {_} _.\nGlobal Arguments Return {_ _ _ _ _} _.\nGlobal Arguments Abs {_ _ _ _ _ _} _.\nGlobal Arguments Compile {_ _ _} make_const {t} _ _.\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/InputSyntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2801176334808201}}
{"text": "Require Import List.\nImport ListNotations.\n\nRequire Export Map.\nRequire Export Shared.\n\nDefinition var := nat.\nDefinition id := nat.\nDefinition loc := nat.\n\n(*\n======\nTypes\n======\n*)\n\nInductive ty : Type :=\n  | TAct : ty\n  | TBes : ty\n  | TPas : ty\n  | TArr : ty -> ty -> ty\n  | TUnit: ty\n.\n\nFunction is_active (t : ty) : bool :=\n  match t with\n    | TAct => true\n    | TBes => true\n    | _ => false\n  end.\n\n(*\n============\nExpressions\n============\n*)\n\nInductive expr : Type :=\n  | EVar : var -> expr\n  | EApp : expr -> expr -> expr\n  | ESend : expr -> var -> ty -> expr -> expr\n  | EMut : expr -> expr\n  | ENew : ty -> expr\n  | EBes : expr -> expr\n  | ELam : var -> ty -> expr -> expr\n  | EUnit : expr\n  | EId : id -> expr\n  | ELoc : loc -> expr\n  | EBId : loc -> id -> expr\n.\n\nTactic Notation \"expr_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"EVar\"\n  | Case_aux c \"EApp\"\n  | Case_aux c \"ESend\"\n  | Case_aux c \"EMut\"\n  | Case_aux c \"ENew\"\n  | Case_aux c \"EBes\"\n  | Case_aux c \"ELam\"\n  | Case_aux c \"EUnit\"\n  | Case_aux c \"EId\"\n  | Case_aux c \"ELoc\"\n  | Case_aux c \"EBId\"\n].\n\nInductive is_val : expr -> Prop :=\n  | LamIsVal : forall x t e, is_val (ELam x t e)\n  | UnitIsVal : is_val EUnit\n  | IdIsVal : forall id, is_val (EId id)\n  | LocIsVal : forall l, is_val (ELoc l)\n  | BIdIsVal : forall l id, is_val (EBId l id)\n.\n\nDefinition econtext := expr -> expr.\n\nDefinition ctx_appl (e' : _) : econtext := (fun e => EApp e e').\nHint Unfold ctx_appl.\nDefinition ctx_appr (v : _) : econtext := (fun e => EApp v e).\nHint Unfold ctx_appr.\nDefinition ctx_send (x : _) (ty : _) (e' : _): econtext := (fun e => ESend e x ty e').\nHint Unfold ctx_send.\nDefinition ctx_mut : econtext := (fun e => EMut e).\nHint Unfold ctx_mut.\nDefinition ctx_bes : econtext := (fun e => EBes e).\nHint Unfold ctx_bes.\n\nInductive is_econtext : econtext -> Prop :=\n  | EC_AppL :\n      forall e',\n        is_econtext (ctx_appl e')\n  | EC_AppR :\n      forall v,\n        is_val v ->\n        is_econtext (ctx_appr v)\n  | EC_Send :\n      forall x t e,\n        is_econtext (ctx_send x t e)\n  | EC_Mut :\n        is_econtext ctx_mut\n  | EC_Bes :\n        is_econtext ctx_bes\n.\n\nFixpoint freeVars (e : expr) : list var :=\n  match e with\n    | EVar x => [x]\n    | EApp e1 e2 => freeVars e1 ++ freeVars e2\n    | ESend e1 x _ e2 => freeVars e1 ++ List.remove id_eq_dec x (freeVars e2)\n    | EMut e' => freeVars e'\n    | EBes e' => freeVars e'\n    | ELam x _ e' => List.remove id_eq_dec x (freeVars e')\n    | _ => []\n  end.\n\nFixpoint freeLocs (e : expr) : list loc :=\n  match e with\n    | ELoc l => [l]\n    | EApp e1 e2 => freeLocs e1 ++ freeLocs e2\n    | ESend e1 x _ e2 => freeLocs e1 ++ freeLocs e2\n    | EMut e' => freeLocs e'\n    | EBes e' => freeLocs e'\n    | ELam x _ e' => freeLocs e'\n    | _ => []\n  end.\n\nFixpoint freeIds (e : expr) : list id :=\n  match e with\n    | EId id => [id]\n    | EApp e1 e2 => freeIds e1 ++ freeIds e2\n    | ESend e1 x _ e2 => freeIds e1 ++ freeIds e2\n    | EMut e' => freeIds e'\n    | EBes e' => freeIds e'\n    | ELam x _ e' => freeIds e'\n    | _ => []\n  end.\n\nFixpoint freeBIds (e : expr) : list (loc * id) :=\n  match e with\n    | EBId l id => [(l, id)]\n    | EApp e1 e2 => freeBIds e1 ++ freeBIds e2\n    | ESend e1 x _ e2 => freeBIds e1 ++ freeBIds e2\n    | EMut e' => freeBIds e'\n    | EBes e' => freeBIds e'\n    | ELam x _ e' => freeBIds e'\n    | _ => []\n  end.\n\nFixpoint subst (x : var) (v : expr) (e : expr) : expr :=\n  match e with\n    | EVar y => if id_eq_dec x y then v else e\n    | EApp e1 e2 => EApp (subst x v e1) (subst x v e2)\n    | ESend e1 y t e2 =>\n      ESend (subst x v e1) y t\n            (if id_eq_dec x y\n             then e2\n             else subst x v e2)\n    | EMut e' => EMut (subst x v e')\n    | EBes e' => EBes (subst x v e')\n    | ELam y t e' =>\n      ELam y t\n           (if id_eq_dec x y then\n              e'\n            else\n              (subst x v e'))\n    | _ => e\n  end.\n\n(*\n==============\nConfiguration\n==============\n*)\n\nInductive is_msg : expr -> Prop :=\n  | LamIsMsg : forall x t e, is_msg (ELam x t e)\n.\n\nDefinition actor := (loc * list loc * list expr * expr)%type.\n\nDefinition heap := list actor.\n\nDefinition heapExtend (H : heap) (a : actor) := snoc H a.\n\nDefinition heapLookup (H : heap) (id : id) :=\n  nth_error H id.\n\nFixpoint heapUpdate (H : heap) (id : id) (a : actor) :=\n  match H with\n  | nil => nil\n  | a' :: H' =>\n    match id with\n    | O    => a :: H'\n    | S id' => a' :: (heapUpdate H' id' a)\n    end\n  end.\n\nDefinition LH (H : heap) (id : id) :=\n  match heapLookup H id with\n    | Some (_, L, _, _) => Some L\n    | None => None\n  end.\n\n(*\n--------------\nConfiguration\n--------------\n*)\n\nInductive actor_idle : actor -> Prop :=\n  | ActorIdle : forall l L v, is_val v -> actor_idle (l, L, [], v)\n.\n\nDefinition heap_done := Forall actor_idle.\n\nDefinition configuration := (heap * nat)%type.\n\nDefinition actor_done (cfg : configuration) (id : id) : Prop :=\n  match cfg with\n    | (h, _) => match heapLookup h id with\n                  | Some a => actor_idle a\n                  | None => False\n                end\n  end\n.\n\nDefinition cfg_done (cfg : configuration) : Prop :=\n  match cfg with\n    | (h, _) => heap_done h\n  end\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/vanilla/Syntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.28011548778110196}}
{"text": "Load \"Pi1_Pi2''\".\n\n\nAxiom IFBRANCH_M1: 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 ++  [ msg (if_then_else_M b x y)])~ ( ml2 ++ [ msg (if_then_else_M b' x' y')]).\n\n\n\nAxiom rev_ifbr: forall (n: nat) (ml1 ml2 : mylist n) (b b' : Bool)(x x' y y':message), ([ msg x; bol b] ++ ml1 )  ~   ([ msg x'; bol b'] ++ ml2 ) -> ([ msg y; bol b] ++ ml1 )  ~   ([ msg y'; bol b'] ++ ml2 )\n-> ( [msg (if_then_else_M b x y)] ++ ml1 ) ~ (  [ msg (if_then_else_M b' x' y')] ++ ml2).\n\n\n(****apply IFBRANCH_M repeateadly********************)\n\n\nLtac ifbr  ml1 ml2 b b' x x' y y' := pose proof (rev_ifbr _ ml1 ml2 b b' x x' y y');\nrepeat match goal with\n| [H : _ |-  (Cons _ _ (msg (if_then_else_M b x y)) ml1 ) ~  (Cons _ _ (msg (if_then_else_M b' x' y')) ml2 ) ] =>   apply H; clear H; try reflexivity\n                           end.\n Ltac ifbr1 :=\nrepeat match goal with\n    | [ |-  (Cons _ _ (msg (if_then_else_M ?B ?X ?Y)) ?L1 )    ~  (Cons _ _ (msg (if_then_else_M ?B' ?X' ?Y')) ?L2 )  ] => ifbr L1 L2 B B' X X' Y Y'\n  end.\n\nLtac ifb := try ifbr1 ; try simpl; try reflexivity; try unf_qb; try unf_qd.\n\n\nLtac simpl_Hyps :=\nrepeat match goal with \n  | [H: _ |- _ ] => simpl in H\n    end.\n\nDefinition len_mylist {n} (l:mylist n) := n.\nLtac funapp_os p1 t1  := match goal with \n| [H:  ?L1 ~ ?L2 |- _] => apply FUNCApp_os with (p:= p1) (n:= len_mylist L1) (t:= t1) (ml1:= L1) (ml2:= L2) in H; simpl in H\nend .\n\nLtac funos p H1 :=\nrepeat match goal with  \n    | [ |-  (Cons _ _ (msg ?B1 ) _ ) ~ (Cons _ _ (msg ?B2) _) ] => funapp_os p (msg B1) H1\n  end.\nLtac DDH2 := assert(DDH1: Fresh [0;1;2;4] [] = true);try reflexivity;\ntry apply DDH in DDH1.\n\nAxiom RESTR_rev: forall {m} (ml1 ml2: mylist m), ml1 ~ ml2 -> (reverse ml1) ~ (reverse ml2).\n(************************************************************************************************)\n(************************************************************************************************)\nTheorem Pi44_Pi24:  phi44 ~ phi24.\n\nProof.    \n\n  apply RESTR_rev with (ml1:= (reverse phi44)) (ml2 := (reverse phi24)).\n\nsimpl.\n\n\n \n\nunfold t45, t25.   \nifb.\nifb.\nifb.\nifb.\nifb.\nifb.\nifb.\nifb.\nifb. \nifb.\n\nFocus 2.\nifb.\nUnfocus.\nFocus 3.\nifb.\nifb.\nifb.\nifb.\n \nrewrite commexp in DDH1.\n\napply RESTR_rev in DDH1.  \nsimpl in DDH1.\n\n\nrestr_swap 1 12  [t14;\n    bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2); bol (EQ_M (to x3) (i 2));\n    bol\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); bol (EQ_M (reveal x3) (i 2));\n    bol (EQ_M (to x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n    bol (EQ_M (reveal x2) (i 1));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1)); msg grn21; t13;\n    t12; msg (g 0); msg (G 0)]   [t14 ;\n   bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2); bol (EQ_M (to x3) (i 2));\n   bol\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); bol (EQ_M (reveal x3) (i 2));\n   bol (EQ_M (to x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n   bol (EQ_M (reveal x2) (i 1));\n   bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n   bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1)); msg grn4; t13; t12;\n   msg (g 0); msg (G 0)].\nunfold t14.\nrepeat ifb.\nrestr_swap 1 14 [t13 ; bol (EQ_M (reveal x1) (i 1));\n    bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2); bol (EQ_M (to x3) (i 2));\n    bol\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); bol (EQ_M (reveal x3) (i 2));\n    bol (EQ_M (to x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n    bol (EQ_M (reveal x2) (i 1));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1)); \n    msg grn21; msg O; t12; msg (g 0); msg (G 0)]\n   [t13 ; bol (EQ_M (reveal x1) (i 1));\n   bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2); bol (EQ_M (to x3) (i 2));\n   bol\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); bol (EQ_M (reveal x3) (i 2));\n   bol (EQ_M (to x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n   bol (EQ_M (reveal x2) (i 1));\n   bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n   bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1)); \n   msg grn4; msg O; t12; msg (g 0); msg (G 0)].\nunfold t13.\nrepeat ifb.\n\nrestr_swap 1 16 [t12; bol (EQ_M (reveal x1) (i 1)); bol (EQ_M (reveal x1) (i 1));\n    bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2); bol (EQ_M (to x3) (i 2));\n    bol\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); bol (EQ_M (reveal x3) (i 2));\n    bol (EQ_M (to x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n    bol (EQ_M (reveal x2) (i 1));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1)); \n    msg grn21; msg O; msg O; msg (g 0); msg (G 0)]\n   [t12; bol (EQ_M (reveal x1) (i 1)); bol (EQ_M (reveal x1) (i 1));\n   bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2); bol (EQ_M (to x3) (i 2));\n   bol\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); bol (EQ_M (reveal x3) (i 2));\n   bol (EQ_M (to x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n   bol (EQ_M (reveal x2) (i 1));\n   bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n   bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1)); \n   msg grn4; msg O; msg O; msg (g 0); msg (G 0)].\nunfold t12. unf_qa.\nrepeat ifb.\n(*******************)\nrestr_proj_in 3 DDH1.\n funapp_droplt DDH1.\nfunapp_droplt DDH1.\nfunapp_O_in DDH1.\nfunapp_O_in DDH1.\nrestr_swap_in 2 4 DDH1.\nrestr_swap_in 3 5 DDH1.\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nrev_app funapp_O_in  DDH1; do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto.  \n(**************************************)\n\n\n funapp_droplt DDH1.\nfunapp_droplt DDH1.\nfunapp_O_in DDH1.\nfunapp_O_in DDH1.\nrestr_swap_in 2 4 DDH1.\nrestr_swap_in 3 5 DDH1.\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\n\nrev_app funapp_O_in DDH1.  assumption. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto.  \n(*************************************************)\nrestr_swap_in 2 3 DDH1.\n\n funapp_droplt DDH1.\nfunapp_O_in DDH1.\nfunapp_O_in DDH1.\nrestr_swap_in 3 5 DDH1.\nrestr_swap_in 4 6 DDH1.\nrestr_swap_in 1 2 DDH1.\n\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nrestr_swap_in 1 16 DDH1.\n  assumption. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto.  auto. \n\n(***********************************************************)\n\nrestr_swap_in 2 3 DDH1.\n\n funapp_droplt DDH1.\nfunapp_O_in DDH1.\nfunapp_O_in DDH1.\nrestr_swap_in 3 5 DDH1.\nrestr_swap_in 4 6 DDH1.\nrestr_swap_in 1 2 DDH1.\n\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (to x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nrestr_swap_in 1 17 DDH1.\n  assumption. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto. repeat (try reflexivity).\nauto. auto . auto.\naply 3 auto. auto. auto. auto . auto.  auto.\n\n(*******************************************************)\n\n\nfunapp_droplt DDH1.\nfunapp_droplt DDH1.\nrev_app funapp_O_in DDH1.\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 3 DDH1.\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (to x1) (i 2))).\nrev_app funapp_O_in DDH1.\nassumption.\n aply 3 auto. auto. auto. auto. auto. auto.\nauto. repeat (try reflexivity).\nauto. auto . auto.\naply 3 auto. auto. auto. auto . auto.  auto.\n\n(****************************************)\nrestr_swap_in 2 3 DDH1.\nfunapp_droplt DDH1.\nfunapp_droplt DDH1.\n\nrev_app funapp_O_in DDH1.\nrev_app funapp_O_in  DDH1.\nrestr_swap_in 1 3 DDH1.\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nrev_app funapp_O_in DDH1.\nrestr_swap 1 17 [t12 ; bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1));\n    bol (EQ_M (reveal x1) (i 1));\n    bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2); bol (EQ_M (to x3) (i 2));\n    bol\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); bol (EQ_M (reveal x3) (i 2));\n    bol (EQ_M (to x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n    bol (EQ_M (reveal x2) (i 1));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1)); \n    msg grn21; msg O; msg O; msg (g 0); msg (G 0)]\n   [t12 ; bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1));\n   bol (EQ_M (reveal x1) (i 1));\n   bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2); bol (EQ_M (to x3) (i 2));\n   bol\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); bol (EQ_M (reveal x3) (i 2));\n   bol (EQ_M (to x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n   bol (EQ_M (reveal x2) (i 1));\n   bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n   bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1)); \n   msg grn4; msg O; msg O; msg (g 0); msg (G 0)].\nunfold t12. unf_qa.\nrepeat ifb.\nassumption.\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nrestr_swap_in 1 2 DDH1.\n aply 3 auto. auto. clear DDH1.\n(*************************************)\nDDH2.\nrewrite commexp in DDH1.\napply RESTR_rev in DDH1. simpl in DDH1.\n\nrestr_swap_in 2 3 DDH1.\nfunapp_droplt DDH1.\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 2 DDH1.\n\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 20 DDH1.\nassumption. auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto. auto.\nclear DDH1.\n(******************************)\n\n\nDDH2.\nrewrite commexp in DDH1.\napply RESTR_rev in DDH1. simpl in DDH1.\n\nrestr_swap_in 2 3 DDH1.\nfunapp_droplt DDH1.\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 2 DDH1.\n\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (to x1) (i 2))) .\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 21 DDH1.\nassumption. auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto. auto. auto.\nclear DDH1.\n\n(****************************************)\nDDH2.\nrewrite commexp in DDH1.\napply RESTR_rev in DDH1. simpl in DDH1.\n\nfunapp_droplt DDH1.\nfunapp_droplt DDH1.\nrev_app funapp_O_in  DDH1.\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 3 DDH1.\n\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (to x1) (i 2))) .\nrev_app funapp_O_in DDH1.\n\nassumption. auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto. auto. auto.  auto. auto. auto. auto. auto.\n auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto. auto. auto.  auto. auto. auto. auto. auto.\n(*************************************************************)\nunf_qa.\nrepeat ifb.\nrestr_swap 1 19 [t12 ; bol (EQ_M (reveal x2) (i 1));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1));\n    bol (EQ_M (reveal x1) (i 1));\n    bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2); bol (EQ_M (to x3) (i 2));\n    bol\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); bol (EQ_M (reveal x3) (i 2));\n    bol (EQ_M (to x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n    bol (EQ_M (reveal x2) (i 1));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1)); \n    msg grn21; msg O; msg O; msg (g 0); msg (G 0)]\n   [t12 ; bol (EQ_M (reveal x2) (i 1));\n   bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n   bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1));\n   bol (EQ_M (reveal x1) (i 1));\n   bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2); bol (EQ_M (to x3) (i 2));\n   bol\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); bol (EQ_M (reveal x3) (i 2));\n   bol (EQ_M (to x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n   bol (EQ_M (reveal x2) (i 1));\n   bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n   bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1)); \n   msg grn4; msg O; msg O; msg (g 0); msg (G 0)].\nunfold t12. unf_qa. repeat ifb.\n\nfunapp_droplt DDH1.\nfunapp_droplt DDH1.\nrev_app funapp_O_in DDH1.\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 3 DDH1.\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\n\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))) .\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))) .\nrev_app funapp_O_in DDH1.\nassumption.\n\n\n auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto. auto. auto.  auto. auto. auto. auto. auto.\n auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. \n(******************************************)\n\n\nfunapp_droplt DDH1.\nfunapp_droplt DDH1.\nrev_app funapp_O_in DDH1.\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 3 DDH1.\n\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\n\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nrev_app funapp_O_in DDH1.\n\nassumption. auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto. auto. auto.  auto. auto. auto. auto. auto.\n auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\n\n(***********************************************************)\n\n\nrestr_swap_in 2 3 DDH1.\nfunapp_droplt DDH1.\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 2 DDH1.\n\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\n\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 22 DDH1.\nassumption. auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto. auto. auto.\n\nauto.\n\n(******************************************************)\n\n\n\n\n\nrestr_swap_in 2 3 DDH1.\nfunapp_droplt DDH1.\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 2 DDH1.\n\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\n\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (to x1) (i 2))).\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 23 DDH1.\nassumption. auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto. auto. auto.\n\nauto. auto.\n(*******************************************************)\n\n\n\nfunapp_droplt DDH1.\nfunapp_droplt DDH1.\nrev_app funapp_O_in DDH1.\nrev_app funapp_O_in  DDH1.\nrestr_swap_in 1 3 DDH1.\n\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\n\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\n\nfunapp_os 0 ( bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (to x1) (i 2))).\nrev_app funapp_O_in DDH1.\nassumption. auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto. auto. auto.  auto. auto. auto. auto. auto.\n auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\n\n(****************************************************)\n\n\nrestr_swap 1 20 [t12; bol (EQ_M (reveal x2) (i 2)); bol (EQ_M (reveal x2) (i 1));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1));\n    bol (EQ_M (reveal x1) (i 1));\n    bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2); bol (EQ_M (to x3) (i 2));\n    bol\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); bol (EQ_M (reveal x3) (i 2));\n    bol (EQ_M (to x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n    bol (EQ_M (reveal x2) (i 1));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1)); \n    msg grn21; msg O; msg O; msg (g 0); msg (G 0)] \n   [t12 ; bol (EQ_M (reveal x2) (i 2)); bol (EQ_M (reveal x2) (i 1));\n   bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n   bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1));\n   bol (EQ_M (reveal x1) (i 1));\n   bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2); bol (EQ_M (to x3) (i 2));\n   bol\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); bol (EQ_M (reveal x3) (i 2));\n   bol (EQ_M (to x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n   bol (EQ_M (reveal x2) (i 1));\n   bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n   bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1)); \n   msg grn4; msg O; msg O; msg (g 0); msg (G 0)].\n\nunfold t12. unf_qa.\nrepeat ifb.\n\n(*************************)\n\n\n\nfunapp_droplt DDH1.\nfunapp_droplt DDH1.\nrev_app funapp_O_in DDH1.\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 3 DDH1.\n\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\n\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 2))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nrev_app funapp_O_in DDH1.\nassumption. auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto. auto. auto.  auto. auto. auto. auto. auto.\n auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\n\n\n(*********************************)\n\n\nfunapp_droplt DDH1.\nfunapp_droplt DDH1.\nrev_app funapp_O_in DDH1.\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 3 DDH1.\n\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\n\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 2))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\n\nrev_app funapp_O_in DDH1.\nassumption. auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto. auto. auto.  auto. auto. auto. auto. auto.\n auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\n\n(************************************)\n\n\n\nrestr_swap_in 2 3 DDH1.\nfunapp_droplt DDH1.\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 2 DDH1.\n\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\n\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\n\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 23 DDH1.\nassumption. auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto. auto. auto.\n\nauto. auto.\n\n(**************************************)\n\n\nrestr_swap_in 2 3 DDH1.\nfunapp_droplt DDH1.\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 2 DDH1.\n\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\n\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (to x1) (i 2))).\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 24 DDH1. \nassumption. auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto. auto. auto.\n\nauto. auto. auto.\n\n(*******************************************************************)\n\n\n\nfunapp_droplt DDH1.\nfunapp_droplt DDH1.\nrev_app funapp_O_in DDH1.\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 3 DDH1.\n\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\n\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 2))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (to x1) (i 2))).\n\nrev_app funapp_O_in DDH1.\nassumption. auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto. auto. auto.  auto. auto. auto. auto. auto.\n auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\n\n(*********************************************************************)\nrestr_swap 1 21 [t12 ; bol (EQ_M (to x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n    bol (EQ_M (reveal x2) (i 1));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1));\n    bol (EQ_M (reveal x1) (i 1));\n    bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2); bol (EQ_M (to x3) (i 2));\n    bol\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); bol (EQ_M (reveal x3) (i 2));\n    bol (EQ_M (to x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n    bol (EQ_M (reveal x2) (i 1));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1)); \n    msg grn21; msg O; msg acc; msg (g 0); msg (G 0)]\n   [t12 ; bol (EQ_M (to x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n   bol (EQ_M (reveal x2) (i 1));\n   bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n   bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1));\n   bol (EQ_M (reveal x1) (i 1));\n   bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2); bol (EQ_M (to x3) (i 2));\n   bol\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); bol (EQ_M (reveal x3) (i 2));\n   bol (EQ_M (to x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n   bol (EQ_M (reveal x2) (i 1));\n   bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n   bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1)); \n   msg grn4; msg O; msg acc ; msg (g 0); msg (G 0)].\nunfold t12 . unf_qa.\nrepeat ifb.\n(***************************************)\nrev_app funapp_acc_in DDH1.\naply_in 2 funapp_droplt DDH1.\nrestr_swap_in 1 2 DDH1.\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 2 DDH1.\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\n \nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\n\nrev_app funapp_O_in DDH1.\nassumption. \n do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto. auto. auto.  auto. auto. auto. auto. auto.\n auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\n\n\n(****************************************************************)\n\nrev_app funapp_acc_in DDH1.\naply_in 2 funapp_droplt DDH1.\nrestr_swap_in 1 2 DDH1.\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 2 DDH1.\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\n \nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\n\nrev_app funapp_O_in DDH1.\nassumption. \n do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto. auto. auto.  auto. auto. auto. auto. auto.\n auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\n\n(*********************************************************)\n\n\n\nrestr_swap_in 2 3 DDH1.\naply_in 1 funapp_droplt DDH1.\n\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 2 DDH1.\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\n \nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nrev_app funapp_acc_in DDH1.\nrestr_swap_in 1 24 DDH1.\nassumption. \n do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto. auto. auto.  auto. auto. auto. auto. auto.\n auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\n\n\n(**********************************************************************)\n\n\nrestr_swap_in 2 3 DDH1.\naply_in 1 funapp_droplt DDH1.\n\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 2 DDH1.\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\n \nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 ( bol (EQ_M (to x1) (i 2))).\nrev_app funapp_acc_in DDH1.\nrestr_swap_in 1 25 DDH1.\nassumption. \n do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto. auto. auto.  auto. auto. auto. auto. auto.\n auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\n\n\n(********************************************************************************)\n\nrev_app funapp_acc_in DDH1.\naply_in 2 funapp_droplt DDH1.\nrestr_swap_in 1 2 DDH1.\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 2 DDH1.\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\n \nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (to x1) (i 2))).\nrev_app funapp_O_in DDH1.\nassumption. \n do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto. auto. auto.  auto. auto. auto. auto. auto.\n auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\n\n(*****************************************************************)\n\nrestr_swap 1 22 [t12 ; bol (EQ_M (to x2) (i 2)); bol (EQ_M (to x2) (i 1));\n    bol (EQ_M (reveal x2) (i 2)); bol (EQ_M (reveal x2) (i 1));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1));\n    bol (EQ_M (reveal x1) (i 1));\n    bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2); bol (EQ_M (to x3) (i 2));\n    bol\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); bol (EQ_M (reveal x3) (i 2));\n    bol (EQ_M (to x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n    bol (EQ_M (reveal x2) (i 1));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1)); \n    msg grn21; msg O; msg grn1; msg (g 0); msg (G 0)]\n   [t12 ; bol (EQ_M (to x2) (i 2)); bol (EQ_M (to x2) (i 1));\n   bol (EQ_M (reveal x2) (i 2)); bol (EQ_M (reveal x2) (i 1));\n   bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n   bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1));\n   bol (EQ_M (reveal x1) (i 1));\n   bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2); bol (EQ_M (to x3) (i 2));\n   bol\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); bol (EQ_M (reveal x3) (i 2));\n   bol (EQ_M (to x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n   bol (EQ_M (reveal x2) (i 1));\n   bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n   bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1)); \n   msg grn4; msg O; msg grn1; msg (g 0); msg (G 0)].\nunfold t12; unf_qa.\n\nrepeat ifb.\n\n(***********************************************************************)\nrestr_swap_in 2 3 DDH1.\nfunapp_droplt DDH1.\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 2 DDH1.\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\n \nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (to x2) (i 2))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nrev_app funapp_O_in DDH1.\nassumption. \n do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto. auto. auto.  auto. auto. auto. auto. auto.\n auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\n\n(****************************************************************************)\n\nrestr_swap_in 2 3 DDH1.\nfunapp_droplt DDH1.\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 2 DDH1.\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\n \nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (to x2) (i 2))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nrev_app funapp_O_in DDH1.\nassumption. \n do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto. auto. auto.  auto. auto. auto. auto. auto.\n auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\n\n(*************************************************************************)\n\nrestr_swap_in 2 3 DDH1.\nfunapp_droplt DDH1.\n\nfunapp_elt_in 1 1 .\n\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\n \nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (to x2) (i 2))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 24 DDH1.\nassumption. \n do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto. auto. auto.  auto. auto. auto. auto. auto.\n auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\n\n\n(*********************************************)\n\n\nrestr_swap_in 2 3 DDH1.\nfunapp_droplt DDH1.\n\nfunapp_elt_in 1 1 .\n\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\n \nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (to x2) (i 2))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (to x1) (i 2))).\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 25 DDH1.\nassumption. \n do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto. auto. auto.  auto. auto. auto. auto. auto.\n auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\n\n(******************************************************************)\n\n\nrestr_swap_in 2 3 DDH1.\nfunapp_droplt DDH1.\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 2 DDH1.\n\n\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\n \nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (to x2) (i 2))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (to x1) (i 2))).\nrev_app funapp_O_in DDH1.\n\nassumption. \n do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto. auto. auto.  auto. auto. auto. auto. auto.\n auto. do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\n\n(********************************************************************)\n\nrestr_swap 1 22 [t12; bol (EQ_M (to x2) (i 2)); bol (EQ_M (to x2) (i 1));\n    bol (EQ_M (reveal x2) (i 2)); bol (EQ_M (reveal x2) (i 1));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1));\n    bol (EQ_M (reveal x1) (i 1));\n    bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2); bol (EQ_M (to x3) (i 2));\n    bol\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); bol (EQ_M (reveal x3) (i 2));\n    bol (EQ_M (to x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n    bol (EQ_M (reveal x2) (i 1));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1)); \n    msg grn21; msg O; msg O; msg (g 0); msg (G 0)] [t12 ; bol (EQ_M (to x2) (i 2)); bol (EQ_M (to x2) (i 1));\n   bol (EQ_M (reveal x2) (i 2)); bol (EQ_M (reveal x2) (i 1));\n   bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n   bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1));\n   bol (EQ_M (reveal x1) (i 1));\n   bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2); bol (EQ_M (to x3) (i 2));\n   bol\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); bol (EQ_M (reveal x3) (i 2));\n   bol (EQ_M (to x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n   bol (EQ_M (reveal x2) (i 1));\n   bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n   bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1)); \n   msg grn4; msg O; msg O; msg (g 0); msg (G 0)].\nunfold t12; unf_qa.\nrepeat ifb.\n\n(************************************)\naply_in 2 funapp_droplt DDH1.\naply_in 2 funapp_O_in DDH1.\n\nrestr_swap_in 2 4 DDH1.\nrestr_swap_in 3 5 DDH1.\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (to x2) (i 2))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nrev_app funapp_O_in  DDH1; do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto.   auto. auto. auto.   auto. auto. auto.   \n\n(*********************************************************)\n\naply_in 2 funapp_droplt DDH1.\naply_in 2 funapp_O_in DDH1.\n\nrestr_swap_in 2 4 DDH1.\nrestr_swap_in 3 5 DDH1.\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (to x2) (i 2))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nrev_app funapp_O_in  DDH1; do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto.   auto. auto. auto.   auto. auto. auto.   auto.\n\n\n(****************************************************************)\nrestr_swap_in 2 3 DDH1.\naply_in 1  funapp_droplt DDH1.\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 2 DDH1.\n\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (to x2) (i 2))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0 (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nrev_app funapp_O_in  DDH1. restr_swap_in 1 25 DDH1. auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto.   auto. auto. auto.   auto. auto. auto.   auto. auto.\n\n(***********************************************************************)\n\nrestr_swap_in 2 3 DDH1.\naply_in 1  funapp_droplt DDH1.\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 2 DDH1.\n\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (to x2) (i 2))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0 (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (to x1) (i 2))).\nrev_app funapp_O_in  DDH1. restr_swap_in 1 26 DDH1. auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto.   auto. auto. auto.   auto. auto. auto.   auto. auto. auto.\n\n\n(**************************************************************************)\n\n\naply_in 2 funapp_droplt DDH1.\naply_in 2 funapp_O_in DDH1.\n\nrestr_swap_in 2 4 DDH1.\nrestr_swap_in 3 5 DDH1.\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (to x2) (i 2))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0 (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (to x1) (i 2))).\nrev_app funapp_O_in  DDH1; do_nat 4 auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto.   auto. auto. auto.   auto. auto. auto.   auto. auto. auto.\n\nunfold qa01. repeat ifb.\n\nrestr_swap 1 20  [t12 ; bol (EQ_M (reveal x2) (i 1)); bol (EQ_M (to x1) (i 2));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1));\n    bol (EQ_M (reveal x1) (i 1));\n    bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2); bol (EQ_M (to x3) (i 2));\n    bol\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); bol (EQ_M (reveal x3) (i 2));\n    bol (EQ_M (to x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n    bol (EQ_M (reveal x2) (i 1));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1)); \n    msg grn21; msg O; msg O; msg (g 0); msg (G 0)]  [t12 ; bol (EQ_M (reveal x2) (i 1)); bol (EQ_M (to x1) (i 2));\n   bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n   bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1));\n   bol (EQ_M (reveal x1) (i 1));\n   bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2); bol (EQ_M (to x3) (i 2));\n   bol\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); bol (EQ_M (reveal x3) (i 2));\n   bol (EQ_M (to x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n   bol (EQ_M (reveal x2) (i 1));\n   bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n   bol (EQ_M (reveal x1) (i 2)); bol (EQ_M (reveal x1) (i 1)); \n   msg grn4; msg O; msg O; msg (g 0); msg (G 0)].\nunfold t12 ; unf_qa. repeat ifb.\n\n(*******************************************************************)\n\n\n\naply_in 2 funapp_droplt DDH1.\naply_in 2 funapp_O_in DDH1.\n\nrestr_swap_in 2 4 DDH1.\nrestr_swap_in 3 5 DDH1.\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (to x1) (i 2))).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\n\nrev_app funapp_O_in  DDH1. assumption. auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto.   auto. auto. auto.   auto. auto. auto.   auto.\n\n(***********************************************************)\n\naply_in 2 funapp_droplt DDH1.\naply_in 2 funapp_O_in DDH1.\n\nrestr_swap_in 2 4 DDH1.\nrestr_swap_in 3 5 DDH1.\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (to x1) (i 2))).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nrev_app funapp_O_in  DDH1. assumption. auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto.   auto. auto. auto.   auto. auto. auto.   auto.\n\n(*******************************************************************************)\n\n\n\nrestr_swap_in 2 3 DDH1.\naply_in 1  funapp_droplt DDH1.\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 2 DDH1.\n\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (to x1) (i 2))).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0 (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\n\nrev_app funapp_O_in  DDH1. restr_swap_in 1 23  DDH1. assumption. auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto.   auto. auto. auto.   auto. auto. auto.   auto. auto. auto.\n\n(*********************************************************************)\n\n\n\nrestr_swap_in 2 3 DDH1.\naply_in 1  funapp_droplt DDH1.\nrev_app funapp_O_in DDH1.\nrestr_swap_in 1 2 DDH1.\n\n\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (to x1) (i 2))).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0 (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (to x1) (i 2))).\nrev_app funapp_O_in  DDH1. restr_swap_in 1 24 DDH1. assumption. auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto.   auto. auto. auto.   auto. auto. auto.   auto. auto. auto.\n\n\n(************************************)\n\naply_in 2 funapp_droplt DDH1.\naply_in 2 funapp_O_in DDH1.\n\nrestr_swap_in 2 4 DDH1.\nrestr_swap_in 3 5 DDH1.\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 1))).\nfunapp_os 0  (bol (EQ_M (reveal x2) (i 2))).\nfunapp_os 0 ( bol (EQ_M (to x2) (i 1))) .\nfunapp_os 0  (bol (EQ_M (reveal x3) (i 2))) .\nfunapp_os 0  ( bol\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)).\nfunapp_os 0 (bol (EQ_M (to x3) (i 2))).\n funapp_os 0 (bol\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 (m x2) grn1)) & (EQ_M (m x3) grn2)).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (to x1) (i 2))).\nfunapp_os 0 (bol (EQ_M (reveal x2) (i 1))).\n\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 1))).\nfunapp_os 0 (bol (EQ_M (reveal x1) (i 2))).\nfunapp_os 0  (bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)).\nfunapp_os 0 (bol (EQ_M (to x1) (i 2))).\nrev_app funapp_O_in  DDH1. assumption. auto. aply 3 auto. auto. auto. auto. auto. auto.\nauto.  repeat (try reflexivity);\nauto. auto ; auto.\naply 1 auto. auto. auto. auto.   auto. auto. auto.   auto. auto. auto.   auto.\n\nAdmitted.\n", "meta": {"author": "ajayeeralla", "repo": "compSoundProofsWOracleMoves", "sha": "8480855887a9092d16dc183ce6ed19315a3ffa96", "save_path": "github-repos/coq/ajayeeralla-compSoundProofsWOracleMoves", "path": "github-repos/coq/ajayeeralla-compSoundProofsWOracleMoves/compSoundProofsWOracleMoves-8480855887a9092d16dc183ce6ed19315a3ffa96/Pi1'_Pi2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.2801154799540876}}
{"text": "(** 直積型に関するモジュールです。 *)\n\nRequire Googology_In_Coq.Base.\nRequire Googology_In_Coq.Path.\n\n(** ライブラリを要求します。 *)\n\nImport Googology_In_Coq.Base.\nImport Googology_In_Coq.Path.\n\n(** ライブラリを開きます。 *)\n\nInductive Product@{ i | } ( A : Type@{ i } ) ( B : Type@{ i } ) : Type@{ i } := pair_Product : A -> B -> Product A B.\n(* from: originally defined by Hexirp *)\n\n(** 直積型です。 *)\n\nDefinition matching_Product@{ i j | } ( A : Type@{ i } ) ( B : Type@{ i } ) ( P : Type@{ j } ) ( cp : A -> B -> P ) ( x : Product A B ) : P := match x with pair_Product _ _ xf xs => cp xf xs end.\n(* from: originally defined by Hexirp *)\n\n(** 直積型の場合分けです。 *)\n\nDefinition identity_matching_Product@{ i j | } ( A : Type@{ i } ) ( B : Type@{ i } ) ( P : Type@{ j } ) ( display : P -> Product A B ) (cp : A -> B -> P ) ( icp : forall ( xf : A ) ( xs : B ), Path ( Product A B ) ( display ( cp xf xs ) ) ( pair_Product A B xf xs ) ) ( x : Product A B ) : Path ( Product A B ) ( display ( matching_Product A B P cp x ) ) x := match x as x_ return Path ( Product A B ) ( display ( matching_Product A B P cp x_ ) ) x_ with pair_Product _ _ xf xs => icp xf xs end.\n(* from: originally defined by Hexirp *)\n\n(** 直積型の場合分けの恒等式です。 *)\n\nDefinition dependent_matching_Product@{ i j | } ( A : Type@{ i } ) ( B : Type@{ i } ) ( P : Product A B -> Type@{ j } ) ( cp : forall ( xf : A ) ( xs : B ), P ( pair_Product A B xf xs ) ) ( x : Product A B ) : P x := match x as x_ return P x_ with pair_Product _ _ xf xs => cp xf xs end.\n(* from: originally defined by Hexirp *)\n\n(** 直積型の依存場合分けです。 *)\n\nDefinition path_cons_Product@{ i si | i < si } ( A : Type@{ i } ) ( B : Type@{ i } ) ( x : Product A B ) ( y : Product A B ) : Type@{ i }.\nProof.\n  refine ( matching_Product@{ i si } A B ( forall y_ : Product A B, Type@{ i } ) _ x y ).\n  refine ( fun ( xf : A ) ( xs : B ) ( y_ : Product A B ) => _ ).\n  refine ( matching_Product@{ i si } A B Type@{ i } _ y_ ).\n  refine ( fun ( yf : A ) ( ys : B ) => _ ).\n  exact ( Product ( Path A xf yf ) ( Path B xs ys ) ).\nDefined.\n(* from: originally defined by Hexirp *)\n\n(** 直積型の構成子の道です。 *)\n\nDefinition from_path_cons_Product@{ i si | i < si } ( A : Type@{ i } ) ( B : Type@{ i } ) ( x : Product A B ) ( y : Product A B ) ( p : path_cons_Product@{ i si } A B x y ) : Path ( Product A B ) x y.\nProof.\n  refine ( dependent_matching_Product A B ( fun x_ : Product A B => forall ( y_ : Product A B ) ( p_ : path_cons_Product@{ i si } A B x_ y_ ), Path ( Product A B ) x_ y_ ) _ x y p ).\n  refine ( fun ( xf : A ) ( xs : B ) ( y_ : Product A B ) ( p_ : path_cons_Product@{ i si } A B ( pair_Product A B xf xs ) y_ ) => _ ).\n  refine ( dependent_matching_Product A B ( fun y__ : Product A B => forall p__ : path_cons_Product@{ i si } A B ( pair_Product A B xf xs ) y__, Path ( Product A B ) ( pair_Product A B xf xs ) y__ ) _ y_ p_ ).\n  refine ( fun ( yf : A ) ( ys : B ) => _ ).\n  change ( path_cons_Product@{ i si } A B ( pair_Product A B xf xs ) ( pair_Product A B yf ys ) -> Path ( Product A B ) ( pair_Product A B xf xs ) ( pair_Product A B yf ys ) ).\n  change ( Product ( Path A xf yf ) ( Path B xs ys ) -> Path ( Product A B ) ( pair_Product A B xf xs ) ( pair_Product A B yf ys ) ).\n  refine ( fun p__ : Product ( Path A xf yf ) ( Path B xs ys ) => _ ).\n  refine ( matching_Product ( Path A xf yf ) ( Path B xs ys ) ( Path ( Product A B ) ( pair_Product A B xf xs ) ( pair_Product A B yf ys ) ) _ p__ ).\n  refine ( fun ( pf : Path A xf yf ) ( ps : Path B xs ys ) => _ ).\n  exact ( trpt_2_Path A B ( fun ( yf_ : A ) ( ys_ : B ) => Path ( Product A B ) ( pair_Product A B xf xs ) ( pair_Product A B yf_ ys_ ) ) xf yf pf xs ys ps ( id_Path ( Product A B ) ( pair_Product A B xf xs ) ) ).\nDefined.\n(* from: originally defined by Hexirp *)\n\n(** 直積型の構成子の道から直積型の道への関数です。 *)\n\nDefinition first_Product@{ i | } ( A : Type@{ i } ) ( B : Type@{ i } ) ( x : Product A B ) : A := matching_Product A B A ( fun ( xf : A ) ( xs : B ) => xf ) x.\n(* from: originally defined by Hexirp *)\n\n(** 直積型の第一射影関数（分解子）です。 *)\n\nDefinition second_Product@{ i | } ( A : Type@{ i } ) ( B : Type@{ i } ) ( x : Product A B ) : B := matching_Product A B B ( fun ( xf : A ) ( xs : B ) => xs ) x.\n(* from: originally defined by Hexirp *)\n\n(** 直積型の第二射影関数（分解子）です。 *)\n\nDefinition path_dest_Product@{ i | } ( A : Type@{ i } ) ( B : Type@{ i } ) ( x : Product A B ) ( y : Product A B ) : Type@{ i } := Product ( Path A ( first_Product A B x ) ( first_Product A B y ) ) ( Path B ( second_Product A B x ) ( second_Product A B y ) ).\n(* from: originally defined by Hexirp *)\n\n(** 直積型の分解子の道です。 *)\n\nDefinition from_path_dest_Product@{ i | } ( A : Type@{ i } ) ( B : Type@{ i } ) ( x : Product A B ) ( y : Product A B ) ( p : path_dest_Product A B x y ) : Path ( Product A B ) x y.\nProof.\n  refine ( dependent_matching_Product A B ( fun x_ : Product A B => forall ( y_ : Product A B ) ( p_ : path_dest_Product A B x_ y_ ), Path ( Product A B ) x_ y_ ) _ x y p ).\n  refine ( fun ( xf : A ) ( xs : B ) ( y_ : Product A B ) ( p_ : path_dest_Product@{ i } A B ( pair_Product A B xf xs ) y_ ) => _ ).\n  refine ( dependent_matching_Product A B ( fun y__ : Product A B => forall p__ : path_dest_Product A B ( pair_Product A B xf xs ) y__, Path ( Product A B ) ( pair_Product A B xf xs ) y__ ) _ y_ p_ ).\n  refine ( fun ( yf : A ) ( ys : B ) => _ ).\n  change ( path_cons_Product A B ( pair_Product A B xf xs ) ( pair_Product A B yf ys ) -> Path ( Product A B ) ( pair_Product A B xf xs ) ( pair_Product A B yf ys ) ).\n  change ( Product ( Path A xf yf ) ( Path B xs ys ) -> Path ( Product A B ) ( pair_Product A B xf xs ) ( pair_Product A B yf ys ) ).\n  refine ( fun p__ : Product ( Path A xf yf ) ( Path B xs ys ) => _ ).\n  refine ( matching_Product ( Path A xf yf ) ( Path B xs ys ) ( Path ( Product A B ) ( pair_Product A B xf xs ) ( pair_Product A B yf ys ) ) _ p__ ).\n  refine ( fun ( pf : Path A xf yf ) ( ps : Path B xs ys ) => _ ).\n  exact ( trpt_2_Path A B ( fun ( yf_ : A ) ( ys_ : B ) => Path ( Product A B ) ( pair_Product A B xf xs ) ( pair_Product A B yf_ ys_ ) ) xf yf pf xs ys ps ( id_Path ( Product A B ) ( pair_Product A B xf xs ) ) ).\nDefined.\n(* from: originally defined by Hexirp *)\n\n(** 直積型の分解子の道です。 *)\n\nDefinition comatching_Product@{ i j | } ( A : Type@{ i } ) ( B : Type@{ i } ) ( P : Type@{ j } ) ( df : P -> A ) ( ds : P -> B ) ( x : P ) : Product A B := pair_Product A B ( df x ) ( ds x ).\n(* from: originally defined by Hexirp *)\n\n(** 直積型の余場合分けです。 *)\n\nDefinition identity_comatching_Product@{ i j | } ( A : Type@{ i } ) ( B : Type@{ i } ) ( P : Type@{ j } ) ( codisplay : Product A B -> P ) ( df : P -> A ) ( idf : forall x : Product A B, Path A ( df ( codisplay x ) ) ( first_Product A B x ) ) ( ds : P -> B ) ( ids : forall x : Product A B, Path B ( ds ( codisplay x ) ) ( second_Product A B x ) ) ( x : Product A B ) : Path ( Product A B ) ( comatching_Product A B P df ds ( codisplay x ) ) x.\nProof.\n  refine ( dependent_matching_Product A B ( fun x_ : Product A B => Path ( Product A B ) ( comatching_Product A B P df ds ( codisplay x_ ) ) x_ ) _ x ).\n  refine ( fun ( xf : A ) ( xs : B ) => _ ).\n  refine ( from_path_dest_Product A B ( comatching_Product A B P df ds ( codisplay ( pair_Product A B xf xs ) ) ) ( pair_Product A B xf xs ) _ ).\n  change ( path_dest_Product A B ( comatching_Product A B P df ds ( codisplay ( pair_Product A B xf xs ) ) ) ( pair_Product A B xf xs ) ).\n  change ( Product ( Path A ( first_Product A B ( comatching_Product A B P df ds ( codisplay ( pair_Product A B xf xs ) ) ) ) ( first_Product A B ( pair_Product A B xf xs ) ) ) ( Path B ( second_Product A B ( comatching_Product A B P df ds ( codisplay ( pair_Product A B xf xs ) ) ) ) ( second_Product A B ( pair_Product A B xf xs ) ) ) ).\n  change ( Product ( Path A ( df ( codisplay ( pair_Product A B xf xs ) ) ) xf ) ( Path B ( ds ( codisplay ( pair_Product A B xf xs ) ) ) xs ) ).\n  refine ( pair_Product ( Path A ( df ( codisplay ( pair_Product A B xf xs ) ) ) xf ) ( Path B ( ds ( codisplay ( pair_Product A B xf xs ) ) ) xs ) _ _ ).\n  -\n    change ( Path A ( df ( codisplay ( pair_Product A B xf xs ) ) ) xf ).\n    change ( Path A ( df ( codisplay ( pair_Product A B xf xs ) ) ) ( first_Product A B ( pair_Product A B xf xs ) ) ).\n    exact ( idf ( pair_Product A B xf xs ) ).\n  -\n    change ( Path B ( ds ( codisplay ( pair_Product A B xf xs ) ) ) xs ).\n    change ( Path B ( ds ( codisplay ( pair_Product A B xf xs ) ) ) ( second_Product A B ( pair_Product A B xf xs ) ) ).\n    exact ( ids ( pair_Product A B xf xs ) ).\nDefined.\n(* from: originally defined by Hexirp *)\n\n(** 直積型の余場合分けの恒等式です。 *)\n\nDefinition curry_Product@{ i j | } ( A : Type@{ i } ) ( B : Type@{ i } ) ( C : Type@{ j } ) ( f : Product A B -> C ) ( x : A ) ( y : B ) : C := f ( pair_Product A B x y ).\n(* from: originally defined by Hexirp *)\n\n(** 直積型のカリー化です。 *)\n\nDefinition uncurry_Product@{ i j | } ( A : Type@{ i } ) ( B : Type@{ i } ) ( C : Type@{ j } ) ( f : A -> B -> C ) ( x : Product A B ) : C := matching_Product@{ i j } A B C ( fun ( xf : A ) ( xs : B ) => f xf xs ) x.\n(* from: originally defined by Hexirp *)\n\n(** 直積型の非カリー化です。 *)\n\nDefinition map_Product@{ i j | } ( A : Type@{ i } ) ( B : Type@{ i } ) ( C : Type@{ j } ) ( D : Type@{ j } ) ( f : A -> C ) ( g : B -> D ) ( x : Product A B ) : Product C D := matching_Product A B ( Product C D ) ( fun ( xf : A ) ( xs : B ) => pair_Product C D ( f xf ) ( g xs ) ) x.\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/Product.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.2801154799540876}}
{"text": "Require Import Term_Defs OptMonad_Coq BS Preamble.\nRequire Import StructTactics Defs.\n\n\nRequire Import Lia Coq.Program.Tactics.\nRequire Import List.\nImport List.ListNotations.\n\n\n(** * Annotated Terms\n\n    Annotated terms are used to ensure that each distinct event has a\n    distinct natural number.  To do so, each term is annotated by a\n    pair of numbers called a range.  Let [(i, k)] be the label for\n    term [t].  The labels will be chosen to have the property such\n    that for each event in the set of events associated with term [t],\n    its number [j] will be in the range [i <= j < k].  *)\n\nDefinition Range: Set := nat * nat.\n\nInductive AnnoTerm: Set :=\n| aasp: Range -> ASP -> AnnoTerm\n| aatt: Range -> Plc -> AnnoTerm -> AnnoTerm\n| alseq: Range -> AnnoTerm -> AnnoTerm -> AnnoTerm\n| abseq: Range -> Split -> AnnoTerm -> AnnoTerm -> AnnoTerm\n| abpar: Range -> Split -> AnnoTerm -> AnnoTerm -> AnnoTerm.\n\n(* Evidence Type size *)\nFixpoint esize t :=\n  match t with\n  | aasp _ _ => 1\n  | aatt _ _ t1 => 2 + esize t1\n  | alseq _ t1 t2 => esize t1 + esize t2\n  | abseq _ _ t1 t2 => 2 + esize t1 + esize t2\n  | abpar _ _ t1 t2 => 2 + esize t1 + esize t2\n  end.\n\n(* Extract Range from each annotated term *)\nDefinition range x :=\n  match x with\n  | aasp r _ => r\n  | aatt r _ _ => r\n  | alseq r _ _ => r\n  | abseq r _ _ _ => r\n  | abpar r _ _ _ => r\n  end.\n\n\n(*\nInductive AnnoTermPar: Set :=\n| aasp_par: ASP -> AnnoTermPar\n| aatt_par: Plc -> Term -> AnnoTermPar\n| alseq_par: AnnoTermPar -> AnnoTermPar -> AnnoTermPar\n| abseq_par: Split -> AnnoTermPar -> AnnoTermPar -> AnnoTermPar\n| abpar_par: Loc -> Split -> AnnoTermPar -> Term -> AnnoTermPar.\n\nFixpoint unannoPar (t:AnnoTermPar) : Term :=\n  match t with\n  | aasp_par a => asp a\n  | aatt_par p t => att p t\n  | alseq_par a1 a2 => lseq (unannoPar a1) (unannoPar a2)                 \n  | abseq_par spl a1 a2 => bseq spl (unannoPar a1) (unannoPar a2) \n  | abpar_par _ spl a1 a2 => bpar spl (unannoPar a1) a2\n  end.\n\nFixpoint anno_par (t:Term) (loc:Loc) : (Loc * AnnoTermPar)  :=\n  match t with\n  | asp a => (loc, aasp_par a)\n  | att p t' => (loc, aatt_par p t')\n                     \n  | lseq t1 t2 =>\n    let '(loc', t1') := anno_par t1 loc in\n    let '(loc'', t2') := anno_par t2 loc' in\n\n    (loc'', alseq_par t1' t2')\n      \n  | bseq spl t1 t2 =>\n    let '(loc', t1') := anno_par t1 loc in\n    let '(loc'', t2') := anno_par t2 loc' in\n\n    (loc'', abseq_par spl t1' t2')\n      \n  | bpar spl t1 t2 =>\n    let '(loc', t1') := anno_par t1 (S loc) in\n    \n    (loc', abpar_par loc spl t1' t2)\n  end.\n\nDefinition peel_loc (ls:list Loc) : Opt (Loc * list Loc) :=\n  match ls with\n  | bs :: ls' => ret (bs, ls')\n  | _ => failm\n  end.\n\nFixpoint anno_par_list' (t:Term) (ls:list Loc) : Opt (list Loc * AnnoTermPar) :=\n  match t with\n  | asp a => ret (ls, aasp_par a)\n  | att p t' => ret (ls, aatt_par p t')\n  | lseq t1 t2 =>\n    '(ls', t1') <- anno_par_list' t1 ls ;;\n    '(ls'', t2') <- anno_par_list' t2 ls' ;;\n    ret (ls'', alseq_par t1' t2')\n  | bseq spl t1 t2 =>\n    '(ls', t1') <- anno_par_list' t1 ls ;;\n    '(ls'', t2') <- anno_par_list' t2 ls' ;;\n    ret (ls'', abseq_par spl t1' t2')\n  | bpar spl t1 t2 =>\n    '(loc, ls') <- peel_loc ls ;;\n    '(ls'', t1') <- anno_par_list' t1 ls' ;;\n    ret (ls'', abpar_par loc spl t1' t2)\n  end.\n\nDefinition anno_par_list (t:Term) (ls:list Loc) : Opt AnnoTermPar :=\n  '(ls', t') <- anno_par_list' t ls ;;\n  ret t'.\n\nSet Nested Proofs Allowed.\n\nLemma peel_loc_fact: forall ls ls' loc,\n    peel_loc ls = Some (loc, ls') ->\n    length ls' = length ls - 1.\nProof.\n  intros.\n  generalizeEverythingElse ls.\n  induction ls; intros; ff.\n  unfold ret in *. inversion H.\n  subst.\n  lia.\nDefined.\n\nLemma par_list_helper: forall t1 t1' ls ls',\n    anno_par_list' t1 ls = Some (ls', t1') ->\n    length ls' = length ls - top_level_thread_count t1.\nProof.\n  intros.\n  generalizeEverythingElse t1.\n  induction t1; intros.\n  -\n    ff.\n    unfold ret in *.\n    ff.\n    lia.\n  -\n    ff.\n    unfold ret in *.\n    ff.\n    lia.\n  -\n    ff.\n    unfold bind in *.\n    unfold ret in *.\n    ff.\n    find_eapply_hyp_hyp.\n    find_eapply_hyp_hyp.\n    lia.\n  -\n    ff.\n    unfold bind in *.\n    unfold ret in *.\n    ff.\n    find_eapply_hyp_hyp.\n    find_eapply_hyp_hyp.\n    lia.\n  -\n    ff.\n    unfold bind in *.\n    unfold ret in *.\n    ff.\n    find_eapply_hyp_hyp.\n    rewrite Heqo0.\n    assert (length l0 = length ls - 1).\n    {\n      eapply peel_loc_fact.\n      eauto.\n    }\n    lia.\nDefined.\n\nLemma peel_loc_fact2: forall ls, \n    length ls >= 1 ->\n    exists res, peel_loc ls = Some res.\nProof.\n  intros.\n  generalizeEverythingElse ls.\n  induction ls; intros.\n  -\n    ff.\n  -\n    ff.\n    unfold ret.\n    eauto.\nDefined.\n\nLemma anno_par_list_some : forall ls t,\n  length ls >= (top_level_thread_count t) ->\n  exists t', anno_par_list t ls = Some t'.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros.\n  -\n    ff.\n    eauto.\n  -\n    ff.\n    eauto.\n  -\n    ff.\n    unfold anno_par_list.\n    cbn.\n    destruct (anno_par_list' t1 ls) eqn:hi.\n    unfold bind.\n    ff.\n    unfold ret.\n    eauto.\n\n    assert (length l >= top_level_thread_count t2).\n    {\n      assert (length ls >= top_level_thread_count t2) by lia.\n      assert (length l = length ls - (top_level_thread_count t1)).\n      {\n\n\n        eapply par_list_helper; eauto.\n      }\n      rewrite H1.\n      lia.\n    }\n\n    find_eapply_hyp_hyp.\n    destruct_conjs.\n    unfold anno_par_list in H1.\n    unfold bind in H1.\n    ff.\n\n    assert (length ls >= top_level_thread_count t1) by lia.\n    find_eapply_hyp_hyp.\n    destruct_conjs.\n    unfold anno_par_list in H1.\n    unfold bind in H1.\n    ff.\n  -\n    ff.\n    unfold anno_par_list.\n    cbn.\n    destruct (anno_par_list' t1 ls) eqn:hi.\n    unfold bind.\n    ff.\n    unfold ret.\n    eauto.\n\n    assert (length l >= top_level_thread_count t2).\n    {\n      assert (length ls >= top_level_thread_count t2) by lia.\n      assert (length l = length ls - (top_level_thread_count t1)).\n      {\n\n\n        eapply par_list_helper; eauto.\n      }\n      rewrite H1.\n      lia.\n    }\n\n    find_eapply_hyp_hyp.\n    destruct_conjs.\n    unfold anno_par_list in H1.\n    unfold bind in H1.\n    ff.\n\n    assert (length ls >= top_level_thread_count t1) by lia.\n    find_eapply_hyp_hyp.\n    destruct_conjs.\n    unfold anno_par_list in H1.\n    unfold bind in H1.\n    ff.\n  -\n    ff.\n    unfold anno_par_list.\n    cbn.\n    destruct (anno_par_list' t1 ls) eqn:hi.\n    unfold bind.\n    ff.\n    unfold ret.\n    eauto.\n\n    assert (length l0 >= top_level_thread_count t1).\n    {\n      assert (length l0 = length ls - 1).\n      {\n        eapply peel_loc_fact; eauto.\n      }\n      lia.\n    }\n    find_eapply_hyp_hyp.\n    destruct_conjs.\n    unfold anno_par_list in H1.\n    unfold bind in H1. ff.\n\n    assert (length ls >= 1) by lia.\n\n\n    edestruct peel_loc_fact2.\n    eassumption.\n    rewrite H1 in *.\n    ff.\n\n    unfold bind in *.\n    ff.\n    unfold ret in *; ff.\n    eauto.\n\n    assert (length l0 >= top_level_thread_count t1).\n    {\n      assert (length l0 = length ls - 1).\n      {\n        eapply peel_loc_fact; eauto.\n      }\n      lia.\n\n    }\n    find_eapply_hyp_hyp.\n    destruct_conjs.\n    unfold anno_par_list in H1.\n    unfold bind in H1. ff.\n\n     assert (length ls >= 1) by lia.\n\n\n    edestruct peel_loc_fact2.\n    eassumption.\n    rewrite H1 in *.\n    ff.\nDefined.\n\n    \n    \n    \n              \n\nDefinition annotated_par (x:Term) :=\n  snd (anno_par x 0).\n*)\n\nInductive term_sub : Term -> Term -> Prop :=\n| termsub_refl_annt: forall t: Term, term_sub t t\n| aatt_sub_annt: forall t t' p,\n    term_sub t' t ->\n    term_sub t' (att p t)\n| alseq_subl_annt: forall t' t1 t2,\n    term_sub t' t1 ->\n    term_sub t' (lseq t1 t2)\n| alseq_subr_annt: forall t' t1 t2,\n    term_sub t' t2 ->\n    term_sub t' (lseq t1 t2)\n| abseq_subl_annt: forall t' t1 t2 s,\n    term_sub t' t1 ->\n    term_sub t' (bseq s t1 t2)\n| abseq_subr_annt: forall t' t1 t2 s,\n    term_sub t' t2 ->\n    term_sub t' (bseq s t1 t2)\n| abpar_subl_annt: forall t' t1 t2 s,\n    term_sub t' t1 ->\n    term_sub t' (bpar s t1 t2)\n| abpar_subr_annt: forall t' t1 t2 s,\n    term_sub t' t2 ->\n    term_sub t' (bpar s t1 t2).\nHint Constructors term_sub : core.\n\nLemma termsub_transitive: forall t t' t'',\n    term_sub t t' ->\n    term_sub t' t'' ->\n    term_sub t t''.\nProof.  \n  generalizeEverythingElse t''.\n  induction t'';\n    intros H H0; ff.\n    (* try (invc H0; eauto). *)\nDefined.\n\n\n(*\n\nLemma nullify_no_none_nones_seq: forall t t' t1 t2 sp,\n    nullify_branchesP t t' ->\n    term_sub (bseq sp t1 t2) t' ->\n    sp = (ALL,ALL).\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros.\n  -\n    destruct a; ff; invc H; ff.\n  -\n    invc H; ff.\n    invc H0.\n    \n    eapply IHt.\n    2: { eassumption. }\n    econstructor.\n    eauto.\n  -\n    invc H; ff.\n    invc H0.\n    + (* t1 term_sub case *)\n      eapply IHt1.\n      2: { eassumption. }\n      econstructor; eauto.\n    +\n      eapply IHt2.\n      2: { eassumption. }\n      econstructor; eauto.\n  -\n    invc H; ff.\n    invc H0; ff.\n    eapply IHt1.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    eapply IHt2.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    invc H0; ff.\n\n     eapply IHt1.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    invc H2.\n    invc H1.\n\n     eapply IHt2.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    invc H0; ff.\n\n    invc H2.\n    invc H1.\n\n    eapply IHt1.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    \n     eapply IHt2.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    invc H0; ff.\n\n    invc H2.\n    invc H1.\n\n    eapply IHt1.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    invc H2.\n    invc H1.\n\n    \n     eapply IHt2.\n    2: { eassumption. }\n    econstructor; eauto.\n  -\n        invc H; ff.\n    invc H0; ff.\n    eapply IHt1.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    eapply IHt2.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    invc H0; ff.\n\n     eapply IHt1.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    invc H2.\n    invc H1.\n\n     eapply IHt2.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    invc H0; ff.\n\n    invc H2.\n    invc H1.\n\n    eapply IHt1.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    \n     eapply IHt2.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    invc H0; ff.\n\n    invc H2.\n    invc H1.\n\n    eapply IHt1.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    invc H2.\n    invc H1.\n\n    \n     eapply IHt2.\n    2: { eassumption. }\n    econstructor; eauto.\nQed.\n\nLemma nullify_no_none_nones_par: forall t t' t1 t2 sp,\n    nullify_branchesP t t' ->\n    term_sub (bpar sp t1 t2) t' ->\n    sp = (ALL,ALL).\nProof.\n    intros.\n  generalizeEverythingElse t.\n  induction t; intros.\n  -\n    destruct a; ff; invc H; ff.\n  -\n    invc H; ff.\n    invc H0.\n    \n    eapply IHt.\n    2: { eassumption. }\n    econstructor.\n    eauto.\n  -\n    invc H; ff.\n    invc H0.\n    + (* t1 term_sub case *)\n      eapply IHt1.\n      2: { eassumption. }\n      econstructor; eauto.\n    +\n      eapply IHt2.\n      2: { eassumption. }\n      econstructor; eauto.\n  -\n    invc H; ff.\n    invc H0; ff.\n    eapply IHt1.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    eapply IHt2.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    invc H0; ff.\n\n     eapply IHt1.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    invc H2.\n    invc H1.\n\n     eapply IHt2.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    invc H0; ff.\n\n    invc H2.\n    invc H1.\n\n    eapply IHt1.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    \n     eapply IHt2.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    invc H0; ff.\n\n    invc H2.\n    invc H1.\n\n    eapply IHt1.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    invc H2.\n    invc H1.\n\n    \n     eapply IHt2.\n    2: { eassumption. }\n    econstructor; eauto.\n  -\n        invc H; ff.\n    invc H0; ff.\n    eapply IHt1.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    eapply IHt2.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    invc H0; ff.\n\n     eapply IHt1.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    invc H2.\n    invc H1.\n\n     eapply IHt2.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    invc H0; ff.\n\n    invc H2.\n    invc H1.\n\n    eapply IHt1.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    \n     eapply IHt2.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    invc H0; ff.\n\n    invc H2.\n    invc H1.\n\n    eapply IHt1.\n    2: { eassumption. }\n    econstructor; eauto.\n\n    invc H2.\n    invc H1.\n\n    \n     eapply IHt2.\n    2: { eassumption. }\n    econstructor; eauto.\nQed.\n\nLemma nullify_no_none_seq_contra: forall t t' t1 t2 sp1 sp2,\n  nullify_branchesP t t' ->\n  term_sub (bseq (sp1,sp2) t1 t2) t' ->\n  ((sp1 = NONE) \\/ (sp2 = NONE)) ->\n  False.\nProof.\n  intros.\n  invc H1.\n  -\n    assert ((NONE,sp2) = (ALL,ALL)).\n    {\n      eapply nullify_no_none_nones_seq; eauto.\n    }\n    invc H1.\n  -\n    assert ((sp1,NONE) = (ALL,ALL)).\n    {\n      eapply nullify_no_none_nones_seq; eauto.\n    }\n    invc H1.\nQed.\n\nLemma nullify_no_none_par_contra: forall t t' t1 t2 sp1 sp2,\n  nullify_branchesP t t' ->\n  term_sub (bpar (sp1,sp2) t1 t2) t' ->\n  ((sp1 = NONE) \\/ (sp2 = NONE)) ->\n  False.\nProof.\n  intros.\n  invc H1.\n  -\n    assert ((NONE,sp2) = (ALL,ALL)).\n    {\n      eapply nullify_no_none_nones_par; eauto.\n    }\n    invc H1.\n  -\n    assert ((sp1,NONE) = (ALL,ALL)).\n    {\n      eapply nullify_no_none_nones_par; eauto.\n    }\n    invc H1.\nQed.\n*)\n    \n    \n                                   \n\n  \n\n\n(*\n(** This function annotates a term.  It feeds a natural number\n    throughout the computation so as to ensure each event has a unique\n    natural number. *) *)\n\nFixpoint anno (t: Term) (i:nat) : (nat * AnnoTerm) :=\n  match t with\n  | asp x => (S i, (aasp (i, S i) x))\n\n  | att p x =>\n    let '(j,a) := anno x (S i)  in\n    (S j, aatt (i, S j) p a)\n\n  | lseq x y =>\n    let '(j,a) := anno x i in\n    let '(k,bt) := anno y j in\n    (k, alseq (i, k) a bt)\n\n  | bseq s x y =>\n    let '(j,a) := anno x (S i) in\n    let '(k,b) := anno y j in\n    (S k, abseq (i, S k) s a b)\n\n  | bpar s x y =>\n    let '(j,a) := anno x (S i) in\n    let '(k,b) := anno y j in\n    (S k, abpar (i, S k) s a b)\n  end.\n\nDefinition annotated x :=\n  snd (anno x 0).\n\nFixpoint unanno a :=\n  match a with\n  | aasp _ a => asp a\n  | aatt _ p t => att p (unanno t)\n  | alseq _ a1 a2 => lseq (unanno a1) (unanno a2)                 \n  | abseq _ spl a1 a2 => bseq spl (unanno a1) (unanno a2) \n  | abpar _ spl a1 a2 => bpar spl (unanno a1) (unanno a2)\n  end.\n\nLemma anno_unanno: forall t i,\n    unanno (snd (anno t i)) = t.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros.\n  -\n    destruct a; ff.\n  -\n    ff.\n    erewrite <- IHt.\n    jkjke.\n  -\n    ff.\n    erewrite <- IHt1.\n    erewrite <- IHt2.\n    jkjke.\n    jkjke.\n  -\n    ff.\n    erewrite <- IHt1.\n    erewrite <- IHt2.\n    jkjke.\n    jkjke.\n  -\n    ff.\n    erewrite <- IHt1.\n    erewrite <- IHt2.\n    jkjke.\n    jkjke.\nDefined.\n\n\n(*\n\nLemma anno_unanno_par: forall a l l' annt,\n    anno_par a l = (l', annt) ->\n    unannoPar annt = a.\nProof.\n  intros.\n  generalizeEverythingElse a.\n  induction a; intros.\n  -\n    ff.\n  -\n    ff.\n  -\n    ff.\n    assert (unannoPar a = a1) by eauto.\n    assert (unannoPar a0 = a2) by eauto.\n    congruence.\n  -\n    ff.\n    assert (unannoPar a = a1) by eauto.\n    assert (unannoPar a0 = a2) by eauto.\n    congruence.\n  -\n    ff.\n    assert (unannoPar a = a1) by eauto.\n    congruence.\nDefined.\n\nLemma anno_unanno_par_list': forall a l l' annt,\n    anno_par_list' a l = Some (l', annt) ->\n    unannoPar annt = a.\nProof.\n  intros.\n  generalizeEverythingElse a.\n  induction a; intros.\n  -\n    ff.\n  -\n    ff.\n  -\n    ff.\n    unfold bind in *.\n    unfold ret in *.\n    ff.\n    assert (unannoPar a = a1) by eauto.\n    assert (unannoPar a0 = a2) by eauto.\n    congruence.\n  -\n    ff.\n    unfold bind in *.\n    unfold ret in *.\n    ff.\n    assert (unannoPar a = a1) by eauto.\n    assert (unannoPar a0 = a2) by eauto.\n    congruence.\n  -\n    ff.\n    unfold bind in *.\n    unfold ret in *.\n    ff.\n    assert (unannoPar a = a1) by eauto.\n    congruence.\nDefined.\n\nLemma anno_unanno_par_list: forall a l annt,\n    anno_par_list a l = Some annt ->\n    unannoPar annt = a.\nProof.\n  intros.\n  unfold anno_par_list in *.\n  unfold bind in *.\n  unfold ret in *.\n  ff.\n  eapply anno_unanno_par_list'.\n  eassumption.\nDefined.\n*)\n\n\nInductive annoP: AnnoTerm -> Term -> Prop :=\n| annoP_c: forall anno_term t,\n    (exists n n', anno t n = (n',anno_term)) -> (* anno_term = snd (anno t n)) -> *)\n    annoP anno_term t.\n\nInductive annoP_indexed': AnnoTerm -> Term -> nat -> Prop :=\n| annoP_c_i': forall anno_term t n,\n    (exists n', anno t n = (n', anno_term)) -> (*anno_term = snd (anno t n) -> *)\n    annoP_indexed' anno_term t n.\n\nInductive annoP_indexed: AnnoTerm -> Term -> nat -> nat ->  Prop :=\n| annoP_c_i: forall anno_term t n n',\n    (*(exists n', anno t n = (n', anno_term)) -> (*anno_term = snd (anno t n) -> *) *)\n    anno t n = (n', anno_term) ->\n    annoP_indexed anno_term t n n'.\n\n\n\n(*\nInductive anno_parP (*anno_par_listP*): AnnoTermPar -> Term -> Prop :=\n| anno_parP_c: forall par_term t,\n    (exists ls ls', anno_par_list' t ls = Some (ls', par_term)) -> (*par_term = snd (anno_par t loc)) -> *)\n    (*anno_par_listP*) anno_parP par_term t.\n\nInductive anno_parPloc: AnnoTermPar -> Term -> list Loc -> Prop :=\n| anno_parP_cloc: forall par_term t ls,\n    (exists ls', anno_par_list' t ls = Some (ls', par_term)) -> (*par_term = snd (anno_par t loc) -> *)\n    anno_parPloc par_term t ls.\n*)\n\n\n(*\nInductive anno_parP: AnnoTermPar -> Term -> Prop :=\n| anno_parP_c: forall par_term t,\n    (exists loc loc', anno_par t loc = (loc', par_term)) -> (*par_term = snd (anno_par t loc)) -> *)\n    anno_parP par_term t.\n\nInductive anno_parPloc: AnnoTermPar -> Term -> Loc -> Prop :=\n| anno_parP_cloc: forall par_term t loc,\n    (exists loc', anno_par t loc = (loc', par_term)) -> (*par_term = snd (anno_par t loc) -> *)\n    anno_parPloc par_term t loc.\n\n\nInductive anno_par_listP: AnnoTermPar -> Term -> Prop :=\n| anno_par_listP_c: forall par_term t,\n    (exists ls ls', anno_par_list' t ls = Some (ls', par_term)) -> (*par_term = snd (anno_par t loc)) -> *)\n    anno_par_listP par_term t.\n\nInductive anno_par_listPls: AnnoTermPar -> Term -> list Loc -> Prop :=\n| anno_par_listP_cloc: forall par_term t ls,\n    (exists ls', anno_par_list' t ls = Some (ls', par_term)) -> (*par_term = snd (anno_par t loc) -> *)\n    anno_par_listPls par_term t ls.\n*)\n\n(*\n\nLemma nolist_list_same_annopar: forall t annt,\n  anno_parP annt t ->\n  anno_par_listP annt t.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros.\n  -\n    invc H.\n    destruct_conjs.\n    econstructor.\n    destruct a; ff; eauto.\n  -\n    invc H.\n    destruct_conjs.\n    econstructor.\n    ff.\n    eauto.\n  -\n    invc H.\n    destruct_conjs.\n    ff.\n    assert (anno_parP a t1).\n    {\n      econstructor; eauto.\n    }\n    find_eapply_hyp_hyp.\n\n    assert (anno_parP a0 t2).\n    {\n      econstructor; eauto.\n    }\n    find_eapply_hyp_hyp.\n\n    invc H1; invc H2.\n    destruct_conjs.\n\n\n    (*\n    econstructor.\n    exists H3. eexists.\n\n    ff.\n\n    unfold bind.\n    unfold ret.\n    find_rewrite.\n    find_rewrite.\n    \n    repeat eexists.\n    ff.\n    rewrite H6 in *.\n    ff.\n    unfold an\n    ff.\n    eauto.\n    ff.\n    \n    eauto.\n  -\n    invc H.\n    destruct_conjs.\n    econstructor.\n    eauto.\n  - invc H.\n    destruct_conjs.\n    econstructor.\n    eauto.\nDefined.\n*)\n\nLemma list_nolist_same_annopar: forall t annt,\n  anno_par_listP annt t ->\n  anno_parP annt t.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    invc H;\n    destruct_conjs; econstructor; eauto.\nDefined.\n    \n    \n*)    \n    \n\n\n(** This predicate determines if an annotated term is well formed,\n    that is if its ranges correctly capture the relations between a\n    term and its associated events. *)\n\n(*\nLemma unique_req_events (t:AnnoTerm) : forall p i i0 p1 p2 q q0 t0 t1,\n       events t p (req i  loc p1 q  t0) ->\n    not (events t p (req i0 loc p2 q0 t1)).\n *)\n\n(** Eval for annotated terms. *)\n\nFixpoint aeval t p e :=\n  match t with\n  | aasp _ x => eval (asp x) p e\n  | aatt _ q x => aeval x q e\n  | alseq _ t1 t2 => aeval t2 p (aeval t1 p e)\n  | abseq _ s t1 t2 => ss (aeval t1 p ((splitEv_T_l s e)))\n                         (aeval t2 p ((splitEv_T_r s e)))\n  | abpar _ s t1 t2 => ss (aeval t1 p ((splitEv_T_l s e)))\n                         (aeval t2 p ((splitEv_T_r s e)))\n  end.\n\nLemma eval_aeval:\n  forall t p e i,\n    eval t p e = aeval (snd (anno t i)) p e.\nProof.\n  induction t; intros; simpl; auto;\n    repeat expand_let_pairs; simpl;\n      try (repeat jkjk; auto;congruence);\n      try (repeat jkjk'; auto).\nDefined.\n\n\n\nInductive well_formed_r_annt: AnnoTerm -> Prop :=\n| wf_asp_r_annt: forall r x,\n    snd r = S (fst r) ->\n    well_formed_r_annt (aasp r x)\n| wf_att_r_annt: forall r p x,\n    well_formed_r_annt x ->\n    S (fst r) = fst (range x) ->\n    snd r = S (snd (range x)) ->\n    Nat.pred (snd r) > fst r ->\n    well_formed_r_annt (aatt r p x)\n                  \n| wf_lseq_r_annt: forall r x y,\n    well_formed_r_annt x -> well_formed_r_annt y ->\n    fst r = fst (range x) ->\n    snd (range x) = fst (range y) ->\n    snd r = snd (range y) -> \n    well_formed_r_annt (alseq r x y)               \n| wf_bseq_r_annt: forall r s x y,\n    well_formed_r_annt x -> well_formed_r_annt y ->\n    S (fst r) = fst (range x) ->\n    snd (range x) = fst (range y) ->\n    snd r = S (snd (range y)) ->  \n    well_formed_r_annt (abseq r s x y)              \n| wf_bpar_r_annt: forall r s x y,\n    well_formed_r_annt x -> well_formed_r_annt y ->  \n    S (fst r) = fst (range x) ->\n    snd (range x) = fst (range y) ->\n    (snd r) = S (snd (range y)) ->\n    (*fst (range y) > fst (range x) -> *)\n    well_formed_r_annt (abpar r s x y).\nHint Constructors well_formed_r_annt : core.\n\nLtac afa :=\n  match goal with   \n  | [H : forall _, _, H2: Term, H3: nat |- _] => pose_new_proof (H H2 H3)\n  end.\n\nLtac afa' :=\n  match goal with   \n  | [H : forall _, _, H2: Term, H3: nat |- _] => pose_new_proof (H H2 (S H3))\n  end.\n\nLtac afa'' :=\n  match goal with   \n  | [H : forall _, _, H2: Term, H3: nat, H4:nat, H5: AnnoTerm |- _] =>\n    pose_new_proof (H H2 (H3)(H4) H5)\n  end.\n\nLtac same_index :=\n  match goal with\n  | [H: anno ?t _ = (?n, _),\n        H': anno ?t _ = (?n', _) |- _] =>\n    assert_new_proof_by (n = n') eauto\n  end.\n\nLemma same_anno_range: forall t i a b n n',\n    anno t i = (n,a) ->\n    anno t i = (n',b) ->\n    n = n'.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    try destruct a;\n    ff.\nDefined.\n  \nLemma anno_mono : forall (t:Term) (i j:nat) (t':AnnoTerm),\n  anno t i = (j,t') ->\n  j > i.\nProof.\n  induction t; intros; (*i j t' ls b H; *)\n    ff;\n    repeat find_apply_hyp_hyp;\n    lia.\nDefined.\nHint Resolve anno_mono : core.\n\nLemma anno_range:\n  forall x i j t',\n     anno x i = (j,t') ->\n    range (t') = (i, j).\nProof.\n  induction x; intros; ff.\nDefined.\n\nLtac haha :=\n  let asdff := eapply anno_mono; eauto in\n  match goal with\n  | [H: anno _ ?x = (?y,_) |- _] => assert_new_proof_by (y > x) (asdff)\n  end.\n\nLtac hehe :=\n  match goal with\n  | [H: anno ?x ?y = (_,_) |- _] => pose_new_proof (anno_range x y)\n  end.\n\nLtac hehe' :=\n  match goal with\n  | [x: Term, y:nat |- _] => pose_new_proof (anno_range x (S y))\n  end.\n\nLtac hehe'' :=\n  match goal with\n  | [x: Term, y:nat |- _] => pose_new_proof (anno_range x y)\n  end.\n\nLtac do_list_empty :=\n  match goal with\n    [H: length ?ls = 0 |- _] =>\n    assert_new_proof_by (ls = []) ltac:(destruct ls; solve_by_inversion)\n  end.\n\nLemma anno_well_formed_r:\n  forall t i j t',\n    anno t i = (j, t') ->\n    well_formed_r_annt t'.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros.\n  -\n    destruct a;\n      ff.\n  -\n    ff.\n    +\n      econstructor.\n      eauto.\n      simpl.\n      erewrite anno_range.\n      2: {\n        eassumption.\n      }\n      tauto.\n\n      simpl.\n      erewrite anno_range.\n      2: {\n        eassumption.\n      }\n      tauto.\n\n      simpl.\n      assert (n > S i) by (eapply anno_mono; eauto).\n      lia.\n  -\n    ff.\n    econstructor.\n    eauto.\n    eauto.\n\n    simpl.\n    erewrite anno_range.\n    2: {\n        eassumption.\n      }\n    tauto.\n\n    simpl.\n    erewrite anno_range.\n    2: {\n        eassumption.\n      }\n    erewrite anno_range.\n    2: {\n        eassumption.\n      }\n    tauto.\n\n    simpl.\n    erewrite anno_range.\n    2: {\n        eassumption.\n      }\n    tauto.\n      \n  -\n    ff.\n    econstructor.\n    eauto.\n    eauto.\n\n     simpl.\n      erewrite anno_range.\n      2: {\n        eassumption.\n      }\n      tauto.\n\n      simpl.\n      erewrite anno_range.\n      2: {\n        eassumption.\n      }\n      erewrite anno_range.\n      2: {\n        eassumption.\n      }\n      tauto.\n\n      simpl.\n      erewrite anno_range.\n      2: {\n        eassumption.\n      }\n      tauto.\n\n  -\n    ff.\n    econstructor.\n    eauto.\n    eauto.\n\n     simpl.\n      erewrite anno_range.\n      2: {\n        eassumption.\n      }\n      tauto.\n\n      simpl.\n      erewrite anno_range.\n      2: {\n        eassumption.\n      }\n      erewrite anno_range.\n      2: {\n        eassumption.\n      }\n      \n      tauto.\n      \n      simpl.\n      erewrite anno_range.\n      2: {\n        eassumption.\n      }\n      tauto.     \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/Anno_Term_Defs_Par_Commented.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.2801154799540876}}
{"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 Arith.\nFrom IntMap Require Import Allmaps.\nRequire Import bases.\nRequire Import defs.\nRequire Import semantics.\nRequire Import signature.\n\n(* reconnaissance des listes de termes par chemins dans les prec_list *)\n\nInductive pl_path : Set :=\n  | pl_path_nil : pl_path\n  | pl_path_cons : ad -> pl_path -> pl_path.\n\nInductive pl_path_incl : pl_path -> prec_list -> Prop :=\n  | pl_path_incl_nil : pl_path_incl pl_path_nil prec_empty\n  | pl_path_incl_cons :\n      forall (plp : pl_path) (a : ad) (la ls : prec_list),\n      pl_path_incl plp la ->\n      pl_path_incl (pl_path_cons a plp) (prec_cons a la ls)\n  | pl_path_incl_next :\n      forall (plp : pl_path) (a : ad) (la ls : prec_list),\n      pl_path_incl plp ls ->\n      plp <> pl_path_nil -> pl_path_incl plp (prec_cons a la ls).\n\nInductive pl_path_recon : preDTA -> term_list -> pl_path -> Prop :=\n  | pl_path_rec_nil : forall d : preDTA, pl_path_recon d tnil pl_path_nil\n  | pl_path_rec_cons :\n      forall (d : preDTA) (a : ad) (t : term) (plp : pl_path)\n        (tl : term_list),\n      reconnaissance d a t ->\n      pl_path_recon d tl plp ->\n      pl_path_recon d (tcons t tl) (pl_path_cons a plp).\n\nDefinition pl_path_rec_equiv_0_def (d : preDTA) (pl : prec_list)\n  (tl : term_list) :=\n  liste_reconnait d pl tl ->\n  exists plp : pl_path, pl_path_incl plp pl /\\ pl_path_recon d tl plp.\n\nFixpoint pl_path_length (plp : pl_path) : nat :=\n  match plp with\n  | pl_path_nil => 0\n  | pl_path_cons _ p => S (pl_path_length p)\n  end.\n\n(* existence de chemins dans les prec_list *)\n\nLemma pl_path_exists :\n forall pl : prec_list, exists p : pl_path, pl_path_incl p pl.\nProof.\n\tsimple induction pl. intros. elim H. intros. split with (pl_path_cons a x).\n\texact (pl_path_incl_cons x a p p0 H1). split with pl_path_nil.\n\texact pl_path_incl_nil.\nQed.\n\nLemma non_empty_pl_path_exists :\n forall pl : prec_list,\n pl <> prec_empty ->\n exists p : pl_path, pl_path_incl p pl /\\ 1 <= pl_path_length p.\nProof.\n\tsimple induction pl. intros. elim (pl_path_exists p). intros. split with (pl_path_cons a x).\n\tsplit. exact (pl_path_incl_cons x a p p0 H2). simpl in |- *. exact (le_n_S _ _ (le_O_n (pl_path_length x))). intros. elim (H (refl_equal _)).\nQed.\n\n(* CNS de reconnaissance d'une liste de terme par une prec_list *)\n\nLemma pl_path_rec_equiv_0_0 :\n forall d : preDTA, pl_path_rec_equiv_0_def d prec_empty tnil.\nProof.\n\tunfold pl_path_rec_equiv_0_def in |- *. intros. inversion H. split with pl_path_nil.\n\tsplit. exact pl_path_incl_nil. exact (pl_path_rec_nil d).\nQed.\n\nLemma pl_path_rec_equiv_0_1 :\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 pl_path_rec_equiv_0_def d la tl ->\n pl_path_rec_equiv_0_def d (prec_cons a la ls) (tcons hd tl).\nProof.\n\tunfold pl_path_rec_equiv_0_def in |- *. intros. elim (H1 H0). intros. elim H3. intros.\n\tsplit with (pl_path_cons a x). split. exact (pl_path_incl_cons x a la ls H4).\n\texact (pl_path_rec_cons d a hd x tl H H5).\nQed.\n\nLemma pl_path_rec_equiv_0_2 :\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 pl_path_rec_equiv_0_def d ls (tcons hd tl) ->\n pl_path_rec_equiv_0_def d (prec_cons a la ls) (tcons hd tl).\nProof.\n\tunfold pl_path_rec_equiv_0_def in |- *. intros. elim (H0 H). intros. split with x.\n\telim H2. intros. split. apply (pl_path_incl_next x a la ls). exact H3.\n\tintro. rewrite H5 in H4. inversion H4. exact H4.\nQed.\n\nLemma pl_path_rec_equiv_0_3 :\n forall (p : preDTA) (p0 : prec_list) (t : term_list),\n liste_reconnait p p0 t -> pl_path_rec_equiv_0_def p p0 t.\nProof.\n\texact\n  (liste_reconnait_ind pl_path_rec_equiv_0_def pl_path_rec_equiv_0_0\n     pl_path_rec_equiv_0_1 pl_path_rec_equiv_0_2).\nQed.\n\nLemma pl_path_rec_equiv_0 :\n forall (d : preDTA) (pl : prec_list) (tl : term_list),\n liste_reconnait d pl tl ->\n exists plp : pl_path, pl_path_incl plp pl /\\ pl_path_recon d tl plp.\nProof.\n\tintros. elim (pl_path_rec_equiv_0_3 d pl tl H H). intros. split with x. exact H0.\nQed.\n\nDefinition pl_path_rec_equiv_1_def (plp : pl_path) \n  (pl : prec_list) :=\n  pl_path_incl plp pl ->\n  forall (d : preDTA) (tl : term_list) (n : nat),\n  pl_path_recon d tl plp -> pl_tl_length pl n -> liste_reconnait d pl tl.\n\nLemma pl_path_rec_equiv_1_0 : pl_path_rec_equiv_1_def pl_path_nil prec_empty.\nProof.\n\tunfold pl_path_rec_equiv_1_def in |- *. intros. inversion H0. \n\texact (rec_empty d).\nQed.\n\nLemma pl_path_rec_equiv_1_1 :\n forall (plp : pl_path) (a : ad) (la ls : prec_list),\n pl_path_incl plp la ->\n pl_path_rec_equiv_1_def plp la ->\n pl_path_rec_equiv_1_def (pl_path_cons a plp) (prec_cons a la ls).\nProof.\n\tunfold pl_path_rec_equiv_1_def in |- *. intros. inversion H2. apply (rec_consi d a la ls t tl0). exact H8. induction  n as [| n Hrecn]. inversion H3. apply (H0 H d tl0 n H9). inversion H3. exact H11. exact H12.\nQed.\n\nLemma pl_path_rec_equiv_1_2 :\n forall (plp : pl_path) (a : ad) (la ls : prec_list),\n pl_path_incl plp ls ->\n pl_path_rec_equiv_1_def plp ls ->\n plp <> pl_path_nil -> pl_path_rec_equiv_1_def plp (prec_cons a la ls).\nProof.\n\tunfold pl_path_rec_equiv_1_def in |- *. intros. induction  n as [| n Hrecn].\n        inversion_clear H4.\n\tinduction  tl as [| t tl Hrectl]. inversion H3. rewrite <- H7 in H2. inversion_clear H2.\n\telim H8; trivial.\n        apply (rec_consn d a la ls t tl).\n\tapply (H0 H d (tcons t tl) (S n) H3). inversion H4. rewrite <- H8 in H.\n\tinversion H. elim H1; auto.\n        exact H10.\nQed.\n\nLemma pl_path_rec_equiv_1_3 :\n forall (p : pl_path) (p0 : prec_list),\n pl_path_incl p p0 -> pl_path_rec_equiv_1_def p p0.\nProof.\n\texact\n  (pl_path_incl_ind pl_path_rec_equiv_1_def pl_path_rec_equiv_1_0\n     pl_path_rec_equiv_1_1 pl_path_rec_equiv_1_2).\nQed.\n\nLemma pl_path_rec_equiv_1 :\n forall (plp : pl_path) (pl : prec_list),\n pl_path_incl plp pl ->\n forall (d : preDTA) (tl : term_list) (n : nat),\n pl_path_recon d tl plp -> pl_tl_length pl n -> liste_reconnait d pl tl.\nProof.\n\tintros. exact (pl_path_rec_equiv_1_3 plp pl H H d tl n H0 H1).\nQed.\n\nLemma pl_path_rec_length :\n forall (plp : pl_path) (tl : term_list) (d : preDTA),\n pl_path_recon d tl plp -> pl_path_length plp = lst_length tl.\nProof.\n\tsimple induction plp. intros. inversion H. simpl in |- *. reflexivity. intros. inversion H0.\n\tsimpl in |- *. rewrite (H tl0 d). reflexivity. exact H6.\nQed.\n\nDefinition liste_rec_length_def (d : preDTA) (pl : prec_list)\n  (tl : term_list) : Prop :=\n  forall n : nat,\n  liste_reconnait d pl tl -> pl_tl_length pl n -> n = lst_length tl.\n\nLemma liste_rec_length_0 :\n forall d : preDTA, liste_rec_length_def d prec_empty tnil.\nProof.\n\tunfold liste_rec_length_def in |- *. intros. inversion H0. reflexivity.\nQed.\n\nLemma liste_rec_length_1 :\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 liste_rec_length_def d la tl ->\n liste_rec_length_def d (prec_cons a la ls) (tcons hd tl).\nProof.\n\tunfold liste_rec_length_def in |- *. intros. induction  n as [| n Hrecn]. inversion H3. inversion H3.\n\tsimpl in |- *. rewrite <- (H1 n H0 H5). reflexivity. simpl in |- *. rewrite <- (H1 n H0 H6).\n\treflexivity.\nQed.\n\nLemma liste_rec_length_2 :\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 liste_rec_length_def d ls (tcons hd tl) ->\n liste_rec_length_def d (prec_cons a la ls) (tcons hd tl).\nProof.\n\tunfold liste_rec_length_def in |- *. intros. simpl in |- *. induction  n as [| n Hrecn]. inversion H2.\n\tsimpl in H0. inversion H2. rewrite <- H6 in H. inversion H.\n\trewrite <- (H0 (S n) H H8). reflexivity.\nQed.\n\nLemma liste_rec_length_3 :\n forall (p : preDTA) (p0 : prec_list) (t : term_list),\n liste_reconnait p p0 t -> liste_rec_length_def p p0 t.\nProof.\n\texact\n  (liste_reconnait_ind liste_rec_length_def liste_rec_length_0\n     liste_rec_length_1 liste_rec_length_2).\nQed.\n\nLemma liste_rec_length :\n forall (pl : prec_list) (tl : term_list) (d : preDTA) (n : nat),\n liste_reconnait d pl tl -> pl_tl_length pl n -> n = lst_length tl.\nProof.\n\tintros. exact (liste_rec_length_3 d pl tl H n H H0).\nQed.\n\nDefinition pl_path_incl_length_def (plp : pl_path) \n  (pl : prec_list) : Prop :=\n  forall n : nat,\n  pl_path_incl plp pl -> pl_tl_length pl n -> pl_path_length plp = n.\n\nLemma pl_path_incl_length_0 : pl_path_incl_length_def pl_path_nil prec_empty.\nProof.\n\tunfold pl_path_incl_length_def in |- *. intros. inversion H0. reflexivity.\nQed.\n\nLemma pl_path_incl_length_1 :\n forall (plp : pl_path) (a : ad) (la ls : prec_list),\n pl_path_incl plp la ->\n pl_path_incl_length_def plp la ->\n pl_path_incl_length_def (pl_path_cons a plp) (prec_cons a la ls).\nProof.\n\tunfold pl_path_incl_length_def in |- *. intros. inversion H2. simpl in |- *.\n\trewrite (H0 n0 H H7). reflexivity. simpl in |- *. rewrite (H0 n0 H H7).\n\treflexivity.\nQed.\n\nLemma pl_path_incl_length_2 :\n forall (plp : pl_path) (a : ad) (la ls : prec_list),\n pl_path_incl plp ls ->\n pl_path_incl_length_def plp ls ->\n plp <> pl_path_nil -> pl_path_incl_length_def plp (prec_cons a la ls).\nProof.\n\tunfold pl_path_incl_length_def in |- *. intros. inversion H3. rewrite <- H7 in H.\n\tinversion H. elim (H1 (sym_eq H9)). exact (H0 (S n0) H H9).\nQed.\n\nLemma pl_path_incl_length_3 :\n forall (p : pl_path) (p0 : prec_list),\n pl_path_incl p p0 -> pl_path_incl_length_def p p0.\nProof.\n\texact\n  (pl_path_incl_ind pl_path_incl_length_def pl_path_incl_length_0\n     pl_path_incl_length_1 pl_path_incl_length_2).\nQed.\n\nLemma pl_path_incl_length :\n forall (plp : pl_path) (pl : prec_list) (n : nat),\n pl_path_incl plp pl -> pl_tl_length pl n -> pl_path_length plp = n.\nProof.\n\tintros. exact\n  (pl_path_incl_ind pl_path_incl_length_def pl_path_incl_length_0\n     pl_path_incl_length_1 pl_path_incl_length_2 plp pl H n H H0).\nQed.\n\n(* CNS pour la propriété pl_tl_length, partie suffisante *)\n\nLemma forall_incl_length :\n forall (pl : prec_list) (n : nat),\n (forall p : pl_path, pl_path_incl p pl -> pl_path_length p = n) ->\n pl_tl_length pl n.\nProof.\n\tsimple induction pl. intros. elim (nat_sum n); intros. rewrite H2 in H1.\n\telim (non_empty_pl_path_exists (prec_cons a p p0)). intros.\n\telim (le_Sn_O 0). elim H3. intros. rewrite (H1 x H4) in H5. exact H5.\n\tintro. inversion H3. elim H2. intros. rewrite H3. rewrite H3 in H1.\n\telim (pl_sum p0); intros. rewrite H4. apply (pl_tl_S a p x). apply (H x). intros. apply (Sn_eq_Sm_n_eq_m (pl_path_length p1) x). replace (S (pl_path_length p1)) with (pl_path_length (pl_path_cons a p1)).\n\tapply (H1 (pl_path_cons a p1)). exact (pl_path_incl_cons p1 a p p0 H5).\n\treflexivity. apply (pl_tl_propag a p p0 x). apply (H x). intros.\n\tcut (pl_path_length (pl_path_cons a p1) = S x). intros. simpl in H6.\n\tinversion H6. reflexivity. exact (H1 (pl_path_cons a p1) (pl_path_incl_cons p1 a p p0 H5)). apply (H0 (S x)). intros. apply (H1 p1). apply (pl_path_incl_next p1 a p p0 H5). intro. rewrite H6 in H5. elim H4. intros. elim H7. intros. elim H8. intros.\n\trewrite H9 in H5. inversion H5. exact (H15 (refl_equal _)).\n\tintros. induction  n as [| n Hrecn]. exact pl_tl_O. elim (pl_path_exists prec_empty).\n\tintros. cut (S n = 0). intros. inversion H1. transitivity (pl_path_length x). symmetry  in |- *. exact (H x H0). inversion H0.\n\treflexivity.\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/pl_path.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.2801154799540876}}
{"text": "From iris.program_logic Require Export weakestpre.\nFrom iris.proofmode Require Import tactics.\nSet Default Proof Using \"Type\".\n\nSection lifting.\nContext `{irisG Λ Σ}.\nImplicit Types s : stuckness.\nImplicit Types v : val Λ.\nImplicit Types e : expr Λ.\nImplicit Types σ : state Λ.\nImplicit Types P Q : iProp Σ.\nImplicit Types Φ : val Λ → iProp Σ.\n\nLemma wp_lift_step_fupd s E Φ e1 :\n  to_val e1 = None →\n  (∀ σ1, state_interp σ1 ={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 ∗ WP e2 @ s; E {{ Φ }} ∗ [∗ list] ef ∈ efs, WP ef @ s; ⊤ {{ _, True }})\n  ⊢ WP e1 @ s; E {{ Φ }}.\nProof.\n  rewrite wp_unfold /wp_pre=>->. iIntros \"H\" (σ1) \"Hσ\".\n  iMod (\"H\" with \"Hσ\") as \"(%&H)\". iModIntro. iSplit. by destruct s. done.\nQed.\n\nLemma wp_lift_stuck E Φ e :\n  to_val e = None →\n  (∀ σ, state_interp σ ={E,∅}=∗ ⌜stuck e σ⌝)\n  ⊢ WP e @ E ?{{ Φ }}.\nProof.\n  rewrite wp_unfold /wp_pre=>->. iIntros \"H\" (σ1) \"Hσ\".\n  iMod (\"H\" with \"Hσ\") as %[? Hirr]. iModIntro. iSplit; first done.\n  iIntros (e2 σ2 efs) \"% !> !>\". by case: (Hirr e2 σ2 efs).\nQed.\n\n(** Derived lifting lemmas. *)\nLemma wp_lift_step s E Φ e1 :\n  to_val e1 = None →\n  (∀ σ1, state_interp σ1 ={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 ∗ WP e2 @ s; E {{ Φ }} ∗ [∗ list] ef ∈ efs, WP ef @ s; ⊤ {{ _, True }})\n  ⊢ WP e1 @ s; E {{ Φ }}.\nProof.\n  iIntros (?) \"H\". iApply wp_lift_step_fupd; [done|]. iIntros (?) \"Hσ\".\n  iMod (\"H\" with \"Hσ\") as \"[$ H]\". iIntros \"!> * % !>\". by iApply \"H\".\nQed.\n\nLemma wp_lift_pure_step `{Inhabited (state Λ)} s E E' Φ e1 :\n  (∀ σ1, if s is NotStuck then reducible e1 σ1 else to_val e1 = None) →\n  (∀ σ1 e2 σ2 efs, prim_step e1 σ1 e2 σ2 efs → σ1 = σ2) →\n  (|={E,E'}▷=> ∀ e2 efs σ, ⌜prim_step e1 σ e2 σ efs⌝ →\n    WP e2 @ s; E {{ Φ }} ∗ [∗ list] ef ∈ efs, WP ef @ s; ⊤ {{ _, True }})\n  ⊢ WP e1 @ s; E {{ Φ }}.\nProof.\n  iIntros (Hsafe Hstep) \"H\". iApply wp_lift_step.\n  { specialize (Hsafe inhabitant). destruct s; last done.\n      by eapply reducible_not_val. }\n  iIntros (σ1) \"Hσ\". iMod \"H\".\n  iMod fupd_intro_mask' as \"Hclose\"; last iModIntro; first by set_solver. iSplit.\n  { iPureIntro. destruct s; done. }\n  iNext. iIntros (e2 σ2 efs ?).\n  destruct (Hstep σ1 e2 σ2 efs); auto; subst.\n  iMod \"Hclose\" as \"_\". iFrame \"Hσ\". iMod \"H\". iApply \"H\"; auto.\nQed.\n\nLemma wp_lift_pure_stuck `{Inhabited (state Λ)} E Φ e :\n  (∀ σ, stuck e σ) →\n  True ⊢ WP e @ E ?{{ Φ }}.\nProof.\n  iIntros (Hstuck) \"_\". iApply wp_lift_stuck.\n  - destruct(to_val e) as [v|] eqn:He; last done.\n    rewrite -He. by case: (Hstuck inhabitant).\n  - iIntros (σ) \"_\". iMod (fupd_intro_mask' E ∅) as \"_\".\n    by set_solver. by auto.\nQed.\n\n(* Atomic steps don't need any mask-changing business here, one can\n   use the generic lemmas here. *)\nLemma wp_lift_atomic_step_fupd {s E1 E2 Φ} e1 :\n  to_val e1 = None →\n  (∀ σ1, state_interp σ1 ={E1}=∗\n    ⌜if s is NotStuck then reducible e1 σ1 else True⌝ ∗\n    ∀ e2 σ2 efs, ⌜prim_step e1 σ1 e2 σ2 efs⌝ ={E1,E2}▷=∗\n      state_interp σ2 ∗\n      from_option Φ False (to_val e2) ∗ [∗ list] ef ∈ efs, WP ef @ s; ⊤ {{ _, True }})\n  ⊢ WP e1 @ s; E1 {{ Φ }}.\nProof.\n  iIntros (?) \"H\". iApply (wp_lift_step_fupd s E1 _ e1)=>//; iIntros (σ1) \"Hσ1\".\n  iMod (\"H\" $! σ1 with \"Hσ1\") as \"[$ H]\".\n  iMod (fupd_intro_mask' E1 ∅) as \"Hclose\"; first set_solver.\n  iIntros \"!>\" (e2 σ2 efs ?). iMod \"Hclose\" as \"_\".\n  iMod (\"H\" $! e2 σ2 efs with \"[#]\") as \"H\"; [done|].\n  iMod (fupd_intro_mask' E2 ∅) as \"Hclose\"; [set_solver|]. iIntros \"!> !>\".\n  iMod \"Hclose\" as \"_\". iMod \"H\" as \"($ & HΦ & $)\".\n  destruct (to_val e2) eqn:?; last by iExFalso.\n  iApply wp_value; last done. by apply of_to_val.\nQed.\n\nLemma wp_lift_atomic_step {s E Φ} e1 :\n  to_val e1 = None →\n  (∀ σ1, state_interp σ1 ={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 ∗\n      from_option Φ False (to_val e2) ∗ [∗ list] ef ∈ efs, WP ef @ s; ⊤ {{ _, True }})\n  ⊢ WP e1 @ s; E {{ Φ }}.\nProof.\n  iIntros (?) \"H\". iApply wp_lift_atomic_step_fupd; [done|].\n  iIntros (?) \"?\". iMod (\"H\" with \"[$]\") as \"[$ H]\". iIntros \"!> * % !> !>\".\n  by iApply \"H\".\nQed.\n\nLemma wp_lift_pure_det_step `{Inhabited (state Λ)} {s E E' Φ} e1 e2 efs :\n  (∀ σ1, if s is NotStuck then reducible e1 σ1 else to_val e1 = None) →\n  (∀ σ1 e2' σ2 efs', prim_step e1 σ1 e2' σ2 efs' → σ1 = σ2 ∧ e2 = e2' ∧ efs = efs')→\n  (|={E,E'}▷=> WP e2 @ s; E {{ Φ }} ∗ [∗ list] ef ∈ efs, WP ef @ s; ⊤ {{ _, True }})\n  ⊢ WP e1 @ s; E {{ Φ }}.\nProof.\n  iIntros (? Hpuredet) \"H\". iApply (wp_lift_pure_step s E E'); try done.\n  { by intros; eapply Hpuredet. }\n  iApply (step_fupd_wand with \"H\"); iIntros \"H\".\n  by iIntros (e' efs' σ (_&->&->)%Hpuredet).\nQed.\n\nLemma wp_pure_step_fupd `{Inhabited (state Λ)} s E E' e1 e2 φ Φ :\n  PureExec φ e1 e2 →\n  φ →\n  (|={E,E'}▷=> WP e2 @ s; E {{ Φ }}) ⊢ WP e1 @ s; E {{ Φ }}.\nProof.\n  iIntros ([??] Hφ) \"HWP\".\n  iApply (wp_lift_pure_det_step with \"[HWP]\").\n  - intros σ. specialize (pure_exec_safe σ). destruct s; eauto using reducible_not_val.\n  - destruct s; naive_solver.\n  - by rewrite big_sepL_nil right_id.\nQed.\n\nLemma wp_pure_step_later `{Inhabited (state Λ)} s E e1 e2 φ Φ :\n  PureExec φ e1 e2 →\n  φ →\n  ▷ WP e2 @ s; E {{ Φ }} ⊢ WP e1 @ s; E {{ Φ }}.\nProof.\n  intros ??. rewrite -wp_pure_step_fupd //. rewrite -step_fupd_intro //.\nQed.\nEnd lifting.\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/lifting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.28011547995408753}}
{"text": "(* Distributed under the terms of the MIT license. *)\nFrom MetaCoq.Template Require Import utils Ast AstUtils Environment Induction WfAst.\nFrom Coq Require Import ssreflect.\nFrom Equations Require Import Equations.\n\n(** * Lifting and substitution for the AST\n\n  Along with standard commutation lemmas.\n  Definition of [closedn] (boolean) predicate for checking if\n  a term is closed. *)\n\nDefinition up := lift 1 0.\n\nCreate HintDb terms.\n\nLtac arith_congr := repeat (try lia; progress f_equal).\n\nLtac easy0 :=\n  let rec use_hyp H :=\n   (match type of H with\n    | _ /\\ _ => exact H || destruct_hyp H\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)\n  in\n  let rec use_hyps :=\n   (match goal with\n    | H:_ /\\ _ |- _ => exact H || (destruct_hyp H; use_hyps)\n    | H:_ * _ |- _ => exact H || (destruct_hyp H; use_hyps)\n    | H:_ |- _ => solve [ inversion H ]\n    | _ => idtac\n    end)\n  in\n  let do_atom := (solve [ trivial with eq_true | reflexivity | symmetry; trivial | contradiction | congruence]) in\n  let rec do_ccl := (try do_atom; repeat (do_intro; try do_atom); try arith_congr; (solve [ split; do_ccl ])) in\n  (solve [ do_atom | use_hyps; do_ccl ]) || fail \"Cannot solve this goal\".\n\n\n#[global]\nHint Extern 10 (_ < _)%nat => lia : terms.\n#[global]\nHint Extern 10 (_ <= _)%nat => lia : terms.\n#[global]\nHint Extern 10 (@eq nat _ _) => lia : terms.\n\nLtac easy ::= easy0 || solve [intuition eauto 3 with core terms].\n\nNotation subst_rec N M k := (subst N k M) (only parsing).\n\nRequire Import PeanoNat.\nImport Nat.\n\nLemma lift_rel_ge :\n  forall k n p, p <= n -> lift k p (tRel n) = tRel (k + n).\nProof.\n  intros; simpl in |- *.\n  now elim (leb_spec p n).\nQed.\n\nLemma lift_rel_lt : forall k n p, p > n -> lift k p (tRel n) = tRel n.\nProof.\n  intros; simpl in |- *.\n  now elim (leb_spec p n).\nQed.\n\nLemma subst_rel_lt : forall u n k, k > n -> subst u k (tRel n) = tRel n.\nProof.\n  simpl in |- *; intros.\n  elim (leb_spec k n); intro Hcomp; easy.\nQed.\n\nLemma subst_rel_gt :\n  forall u n k, n >= k + length u -> subst u k (tRel n) = tRel (n - length u).\nProof.\n  simpl in |- *; intros.\n  elim (leb_spec k n). intros. destruct nth_error eqn:Heq.\n  assert (n - k < length u) by (apply nth_error_Some; congruence). lia. reflexivity.\n  lia.\nQed.\n\nLemma subst_rel_eq :\n  forall (u : list term) n i t p,\n    List.nth_error u i = Some t -> p = n + i ->\n    subst u n (tRel p) = lift0 n t.\nProof.\n  intros; simpl in |- *. subst p.\n  elim (leb_spec n (n + i)). intros. assert (n + i - n = i) by lia. rewrite H1 H.\n  reflexivity. intros. lia.\nQed.\n\nLemma lift0_id : forall M k, lift 0 k M = M.\nProof.\n  intros M.\n  elim M using term_forall_list_ind; simpl in |- *; intros; try easy ;\n    try (try rewrite H; try rewrite H0 ; try rewrite H1 ; easy);\n    try (f_equal; auto; solve_all).\n  now elim (leb k n).\nQed.\n\nLemma lift0_p : forall M, lift0 0 M = M.\nProof.\n  intros; unfold lift in |- *.\n  apply lift0_id; easy.\nQed.\n\nLemma simpl_lift :\n  forall M n k p i,\n    i <= k + n ->\n    k <= i -> lift p i (lift n k M) = lift (p + n) k M.\nProof.\n  intros M.\n  elim M using term_forall_list_ind;\n    intros; simpl;\n      rewrite -> ?map_map_compose, ?compose_on_snd, ?compose_map_def, ?map_length;\n      rewrite -> ?map_predicate_map_predicate;\n      try (rewrite -> H, ?H0, ?H1; auto); try (f_equal; auto; solve_all).\n\n  - elim (leb_spec k n); intros.\n    + elim (leb_spec i (n0 + n)); intros; lia.\n    + elim (leb_spec i n); intros; lia.\nQed.\n\nLemma simpl_lift0 : forall M n, lift0 (S n) M = lift0 1 (lift0 n M).\n  now intros; rewrite simpl_lift.\nQed.\n\n\nLemma map_branches_k_map_branches_k\n      {term term' term''}\n      (f : nat -> term' -> term'')\n      (g : branch term -> term -> term')\n      (f' : term -> term')\n      (l : list (branch term)) k :\n  map (fun b => map_branch (f (#|bcontext (map_branch (g b) b)| + k)) (map_branch f' b)) l =\n  map (fun b => map_branch (f (#|bcontext b| + k)) (map_branch f' b)) l.\nProof.\n  eapply map_ext => b. rewrite map_branch_map_branch.\n  now apply map_branch_eq_spec.\nQed.\n\nLemma permute_lift :\n  forall M n k p i,\n    i <= k ->\n    lift p i (lift n k M) = lift n (k + p) (lift p i M).\nProof.\n  intros M.\n  elim M using term_forall_list_ind;\n    intros; simpl;\n      rewrite -> ?map_map_compose, ?compose_on_snd, ?compose_map_def, ?map_length,\n      ?Nat.add_assoc, ?map_predicate_map_predicate, ?map_branches_map_branches; f_equal;\n      try solve [auto; solve_all]; repeat nth_leb_simpl.\nQed.\n\nLemma permute_lift0 :\n  forall M k, lift0 1 (lift 1 k M) = lift 1 (S k) (lift0 1 M).\n  intros.\n  change (lift 1 0 (lift 1 k M) = lift 1 (1 + k) (lift 1 0 M))\n    in |- *.\n  rewrite permute_lift; easy.\nQed.\n\nLemma map_non_nil {A B} (f : A -> B) l : l <> nil -> map f l <> nil.\nProof.\n  intros. intro.\n  destruct l; try discriminate.\n  contradiction.\nQed.\n\nLemma isLambda_lift n k (bod : term) :\n  isLambda bod = true -> isLambda (lift n k bod) = true.\nProof. destruct bod; simpl; try congruence. Qed.\n\n#[global]\nHint Resolve lift_isApp map_non_nil isLambda_lift : all.\n\nLemma mkApps_tApp t l :\n  isApp t = false -> l <> nil -> mkApps t l = tApp t l.\nProof.\n  intros.\n  destruct l. simpl. contradiction.\n  destruct t; simpl; try reflexivity.\n  simpl in H. discriminate.\nQed.\n\nLemma simpl_subst_rec :\n  forall Σ M (H : wf Σ M) N n p k,\n    p <= n + k ->\n    k <= p -> subst N p (lift (List.length N + n) k M) = lift n k M.\nProof.\n  intros Σ M wfM. induction wfM using term_wf_forall_list_ind;\n    intros; simpl;\n      rewrite -> ?map_map_compose, ?compose_on_snd, ?compose_map_def, ?map_length,\n                 ?map_predicate_map_predicate;\n      try solve [f_equal; auto; solve_all]; repeat nth_leb_simpl.\n\n  - rewrite IHwfM; auto.\n    apply (lift_isApp n k) in H.\n    rewrite mkApps_tApp; auto using map_non_nil.\n    f_equal; solve_all.\nQed.\n\nLemma simpl_subst Σ :\n  forall N M (H : wf Σ M) n p, p <= n -> subst N p (lift0 (length N + n) M) = lift0 n M.\nProof.  intros. erewrite simpl_subst_rec; eauto. now rewrite Nat.add_0_r. lia. Qed.\n\nLemma mkApps_tRel n a l : mkApps (tRel n) (a :: l) = tApp (tRel n) (a :: l).\nProof.\n  simpl. reflexivity.\nQed.\n\nLemma lift_mkApps n k t l : lift n k (mkApps t l) = mkApps (lift n k t) (map (lift n k) l).\nProof.\n  revert n k t; induction l; intros n k t; destruct t; try reflexivity.\n  simpl. f_equal.\n  now rewrite map_app.\nQed.\n\nLemma commut_lift_subst_rec :\n  forall M N n p k,\n    k <= p ->\n    lift n k (subst N p M) = subst N (p + n) (lift n k M).\nProof.\n  intros M.\n  elim M using term_forall_list_ind;\n    intros; simpl; try easy;\n      rewrite -> ?map_map_compose, ?compose_on_snd, ?compose_map_def, ?map_length, ?Nat.add_assoc,\n                 ?map_predicate_map_predicate;\n      try solve [f_equal; auto; solve_all].\n\n  - repeat nth_leb_simpl.\n    rewrite -> simpl_lift by easy. f_equal; lia.\n  - rewrite lift_mkApps. f_equal. auto.\n    rewrite map_map_compose. solve_all.\nQed.\n\nLemma commut_lift_subst :\n  forall M N k, subst N (S k) (lift0 1 M) = lift0 1 (subst N k M).\n  now intros; rewrite commut_lift_subst_rec.\nQed.\n\nLemma distr_lift_subst_rec :\n  forall M N n p k,\n    lift n (p + k) (subst N p M) =\n    subst (List.map (lift n k) N) p (lift n (p + length N + k) M).\nProof.\n  intros M.\n  elim M using term_forall_list_ind;\n    intros; match goal with\n              |- context [tRel _] => idtac\n            | |- _ => cbn -[plus]\n            end; try easy;\n      rewrite -> ?map_map_compose, ?compose_on_snd, ?compose_map_def, ?map_length, ?Nat.add_assoc,\n                 ?map_predicate_map_predicate;\n      try solve [f_equal; auto; solve_all].\n\n  - unfold subst at 1. unfold lift at 4.\n    repeat nth_leb_simpl.\n    rewrite nth_error_map in e0. rewrite e in e0.\n    revert e0. intros [= <-].\n    now rewrite (permute_lift x n0 k p 0).\n  - rewrite lift_mkApps. f_equal; auto.\n    rewrite map_map_compose; solve_all.\nQed.\n\nLemma distr_lift_subst :\n  forall M N n k,\n    lift n k (subst0 N M) = subst0 (map (lift n k) N) (lift n (length N + k) M).\nProof.\n  intros. pattern k at 1 3 in |- *.\n  replace k with (0 + k); try easy.\n  apply distr_lift_subst_rec.\nQed.\n\nLemma distr_lift_subst10 :\n  forall M N n k,\n    lift n k (subst10 N M) = subst10 (lift n k N) (lift n (S k) M).\nProof.\n  intros; unfold subst in |- *.\n  pattern k at 1 3 in |- *.\n  replace k with (0 + k); try easy.\n  apply distr_lift_subst_rec.\nQed.\n\nLemma subst_mkApps u k t l :\n  subst u k (mkApps t l) = mkApps (subst u k t) (map (subst u k) l).\nProof.\n  revert u k t; induction l; intros u k t; destruct t; try reflexivity.\n  intros. simpl mkApps at 1. simpl subst at 1 2. rewrite map_app. now rewrite -mkApps_app.\nQed.\n\nLemma subst1_mkApps u k t l : subst1 u k (mkApps t l) = mkApps (subst1 u k t) (map (subst1 u k) l).\nProof.\n  apply subst_mkApps.\nQed.\n\nLemma distr_subst_rec Σ :\n  forall M N (P : list term) (wfP : All (wf Σ) P) n p,\n    subst P (p + n) (subst N p M) =\n    subst (map (subst P n) N) p (subst P (p + length N + n) M).\nProof.\n  intros M.\n  elim M using term_forall_list_ind;\n    intros; match goal with\n              |- context [tRel _] => idtac\n            | |- _ => simpl\n            end; try easy;\n      rewrite -> ?map_map_compose, ?compose_on_snd, ?compose_map_def, ?map_length, ?Nat.add_assoc,\n                 ?map_predicate_map_predicate;\n      try solve [f_equal; auto; solve_all].\n\n  - unfold subst at 2.\n    elim (leb_spec p n); intros; try easy.\n\n    + destruct (nth_error_spec N (n - p)).\n      ++ rewrite -> subst_rel_lt by lia.\n         erewrite subst_rel_eq; try easy.\n         2:rewrite -> nth_error_map, e; reflexivity.\n         now rewrite commut_lift_subst_rec. lia.\n      ++ unfold subst at 4.\n         elim (leb_spec (p + length N + n0) n); intros; subst; try easy.\n         destruct (nth_error_spec P (n - (p + length N + n0))).\n         +++ erewrite subst_rel_eq. 2:eauto. 2:lia.\n             assert (p + length N + n0 = length (map (subst P n0) N) + (p + n0))\n               by (rewrite map_length; lia).\n             rewrite H1. erewrite simpl_subst_rec; eauto; try lia.\n             eapply nth_error_all in e; eauto.\n         +++ rewrite !subst_rel_gt; rewrite ?map_length; try lia. f_equal; lia.\n         +++ rewrite subst_rel_lt; try easy.\n             rewrite -> subst_rel_gt; rewrite map_length. trivial. lia.\n    + rewrite !subst_rel_lt; try easy.\n\n  - rewrite !subst_mkApps. rewrite H; auto. f_equal.\n    rewrite !map_map_compose. solve_all.\nQed.\n\nLemma distr_subst Σ :\n  forall P (wfP : All (wf Σ) P) N M k,\n    subst P k (subst0 N M) = subst0 (map (subst P k) N) (subst P (length N + k) M).\nProof.\n  intros.\n  pattern k at 1 3 in |- *.\n  change k with (0 + k). hnf.\n  eapply distr_subst_rec; eauto.\nQed.\n\nLemma lift_closed n k t : closedn k t -> lift n k t = t.\nProof.\n  revert k.\n  elim t using term_forall_list_ind; intros; try easy;\n    rewrite -> ?map_map_compose, ?compose_on_snd, ?compose_map_def, ?map_length,\n               ?map_predicate_map_predicate;\n    simpl closed in *;\n    unfold test_def, test_predicate in *;\n    try solve [simpl lift; simpl closed; f_equal; auto; rtoProp; solve_all]; try easy.\n  - rewrite lift_rel_lt; auto.\n    revert H. elim (Nat.ltb_spec n0 k); intros; try easy.\n  - simpl lift. f_equal. solve_all. unfold test_def in b. toProp. solve_all.\n  - simpl lift. f_equal. solve_all. unfold test_def in b. toProp. solve_all.\nQed.\n\nLemma closed_upwards {k t} k' : closedn k t -> k' >= k -> closedn k' t.\nProof.\n  revert k k'.\n  elim t using term_forall_list_ind; intros; try lia;\n    rewrite -> ?map_map_compose, ?compose_on_snd, ?compose_map_def, ?map_length,\n               ?map_predicate_map_predicate;\n    simpl closed in *; unfold test_snd, test_def, test_predicate, test_branch in *;\n      try solve [(try f_equal; simpl; repeat (rtoProp; solve_all); eauto)].\n\n  - elim (ltb_spec n k'); auto. intros.\n    apply ltb_lt in H. lia.\nQed.\n\nLemma subst_empty Σ k a : wf Σ a -> subst [] k a = a.\nProof.\n  induction 1 in k |- * using term_wf_forall_list_ind; simpl; try congruence;\n    try solve [f_equal; eauto; solve_all].\n\n  - elim (Nat.compare_spec k n); destruct (Nat.leb_spec k n); intros; try easy.\n    subst. rewrite Nat.sub_diag. simpl. rewrite Nat.sub_0_r. reflexivity.\n    assert (n - k > 0) by lia.\n    assert (exists n', n - k = S n'). exists (pred (n - k)). lia.\n    destruct H2. rewrite H2. simpl. now rewrite Nat.sub_0_r.\n  - rewrite IHX. rewrite mkApps_tApp; eauto with wf.\n    f_equal; solve_all.\nQed.\n\nLemma lift_to_extended_list_k Γ k : forall k',\n    to_extended_list_k Γ (k' + k) = map (lift0 k') (to_extended_list_k Γ k).\nProof.\n  unfold to_extended_list_k.\n  intros k'. rewrite !reln_alt_eq !app_nil_r.\n  induction Γ in k, k' |- *; simpl; auto.\n  destruct a as [na [body|] ty].\n  now rewrite <- Nat.add_assoc, (IHΓ (k + 1) k').\n  simpl. now rewrite <- Nat.add_assoc, (IHΓ (k + 1) k'), map_app.\nQed.\n\nLemma simpl_subst_k Σ (N : list term) (M : term) :\n  wf Σ M -> forall k p, p = #|N| -> subst N k (lift p k M) = M.\nProof.\n  intros. subst p. rewrite <- (Nat.add_0_r #|N|).\n  erewrite simpl_subst_rec, lift0_id; eauto.\nQed.\n\nLemma subst_app_decomp Σ l l' k t :\n  wf Σ t -> All (wf Σ) l ->\n  subst (l ++ l') k t = subst l' k (subst (List.map (lift0 (length l')) l) k t).\nProof.\n  intros wft wfl.\n  induction wft in k |- * using term_wf_forall_list_ind; simpl; auto;\n    rewrite ?subst_mkApps; try change_Sk;\n    try (f_equal; rewrite -> ?map_map_compose, ?compose_on_snd, ?compose_map_def, ?map_length,\n                             ?map_predicate_map_predicate;\n         eauto; solve_all).\n\n  - repeat nth_leb_simpl.\n    rewrite nth_error_map in e0. rewrite e in e0.\n    injection e0; intros <-.\n    rewrite -> permute_lift by auto.\n    rewrite <- (Nat.add_0_r #|l'|).\n    erewrite -> simpl_subst_rec, lift0_id; auto with wf; try lia. apply wf_lift.\n    eapply nth_error_all in e; eauto.\nQed.\n\nLemma subst_app_simpl Σ l l' k t :\n  wf Σ t -> All (wf Σ) l -> All (wf Σ) l' ->\n  subst (l ++ l') k t = subst l k (subst l' (k + length l) t).\nProof.\n  intros wft wfl wfl'.\n  induction wft in k |- * using term_wf_forall_list_ind; simpl; eauto;\n    rewrite ?subst_mkApps; try change_Sk;\n    try (f_equal; rewrite -> ?map_map_compose, ?compose_on_snd, ?compose_map_def, ?map_length,\n                             ?Nat.add_assoc, ?map_predicate_map_predicate;\n         eauto; solve_all; eauto).\n\n  - repeat nth_leb_simpl.\n    erewrite -> Nat.add_comm, simpl_subst; eauto.\n    eapply nth_error_all in e; eauto.\nQed.\n\nLemma isLambda_subst (s : list term) k (bod : term) :\n  isLambda bod = true -> isLambda (subst s k bod) = true.\nProof.\n  intros. destruct bod; try discriminate. reflexivity.\nQed.\n\nLemma map_vass_map_def g l n k :\n  (mapi (fun i (d : def term) => vass (dname d) (lift0 i (dtype d)))\n        (map (map_def (lift n k) g) l)) =\n  (mapi (fun i d => map_decl (lift n (i + k)) d) (mapi (fun i (d : def term) => vass (dname d) (lift0 i (dtype d))) l)).\nProof.\n  rewrite mapi_mapi mapi_map. apply mapi_ext.\n  intros. unfold map_decl, vass; simpl; f_equal.\n  rewrite permute_lift. lia. f_equal; lia.\nQed.\n(*\nLemma noccur_between_subst k n t : noccur_between k n t ->\n  closedn (n + k) t -> closedn k t.\nProof.\nQed.  *)                        (* TODO *)\n\nLemma strip_casts_lift n k t :\n  strip_casts (lift n k t) = lift n k (strip_casts t).\nProof.\n  induction t in k |- * using term_forall_list_ind; simpl; auto;\n    rewrite ?map_map_compose  ?compose_on_snd ?compose_map_def ?map_length;\n   f_equal; solve_all; eauto.\n\n  - rewrite lift_mkApps IHt map_map_compose.\n    f_equal; solve_all.\n  - rewrite !map_predicate_map_predicate.\n    unfold map_predicate. f_equal.\n    solve_all. solve_all.\nQed.\n\nLemma mkApps_ex t u l : ∑ f args, Ast.mkApps t (u :: l) = Ast.tApp f args.\nProof.\n  induction t; simpl; eexists _, _; reflexivity.\nQed.\n(*\nLemma mkApps_tApp' f l l' : mkApps (tApp f l) l' = mkApps f (l ++ l').\nProof.\n  induction l'; simpl. rewrite app_nil_r.  *)\n\nLemma list_length_ind {A} (P : list A -> Type) (p0 : P [])\n  (pS : forall d Γ, (forall Γ', #|Γ'| <= #|Γ|  -> P Γ') -> P (d :: Γ))\n  Γ : P Γ.\nProof.\n  generalize (le_n #|Γ|).\n  generalize #|Γ| at 2.\n  induction n in Γ |- *.\n  destruct Γ; [|simpl; intros; elimtype False; lia].\n  intros. apply p0.\n  intros.\n  destruct Γ; simpl in *.\n  apply p0. apply pS. intros. apply IHn. simpl. lia.\nQed.\n\nLemma strip_casts_mkApps_tApp f l :\n  isApp f = false ->\n  strip_casts (mkApps f l) = strip_casts (tApp f l).\nProof.\n  induction l. simpl; auto.\n  intros.\n  rewrite mkApps_tApp //.\nQed.\n\nLemma strip_casts_mkApps f l :\n  isApp f = false ->\n  strip_casts (mkApps f l) = mkApps (strip_casts f) (map strip_casts l).\nProof.\n  intros Hf. rewrite strip_casts_mkApps_tApp //.\nQed.\n\nLemma subst_it_mkProd_or_LetIn n k ctx t :\n  subst n k (it_mkProd_or_LetIn ctx t) =\n  it_mkProd_or_LetIn (subst_context n k ctx) (subst n (length ctx + k) t).\nProof.\n  induction ctx in n, k, t |- *; simpl; try congruence.\n  pose (subst_context_snoc n k ctx a). unfold snoc in e. rewrite e. clear e.\n  simpl. rewrite -> IHctx.\n  pose (subst_context_snoc n k ctx a). simpl. now destruct a as [na [b|] ty].\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/template-coq/theories/LiftSubst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.5273165233795672, "lm_q1q2_score": 0.28011547212707316}}
{"text": "From stdpp Require Export strings.\nFrom iris.algebra Require Export base.\nFrom Coq Require Import Ascii.\nSet Default Proof Using \"Type\".\n\n(* Directions of rewrites *)\nInductive direction := Left | Right.\n\n(* Some specific versions of operations on strings for the proof mode. We need\nthose so that we can make [cbv] unfold just them, but not the actual operations\nthat may appear in users' proofs. *)\nLocal Notation \"b1 && b2\" := (if b1 then b2 else false) : bool_scope.\n\nLemma lazy_andb_true (b1 b2 : bool) : b1 && b2 = true ↔ b1 = true ∧ b2 = true.\nProof. destruct b1, b2; intuition congruence. Qed.\n\nDefinition beq (b1 b2 : bool) : bool :=\n  match b1, b2 with\n  | false, false | true, true => true\n  | _, _ => false\n  end.\n\nDefinition ascii_beq (x y : ascii) : bool :=\n  let 'Ascii x1 x2 x3 x4 x5 x6 x7 x8 := x in\n  let 'Ascii y1 y2 y3 y4 y5 y6 y7 y8 := y in\n  beq x1 y1 && beq x2 y2 && beq x3 y3 && beq x4 y4 &&\n    beq x5 y5 && beq x6 y6 && beq x7 y7 && beq x8 y8.\n\nFixpoint string_beq (s1 s2 : string) : bool :=\n  match s1, s2 with \n  | \"\", \"\" => true\n  | String a1 s1, String a2 s2 => ascii_beq a1 a2 && string_beq s1 s2\n  | _, _ => false\n  end.\n\nLemma beq_true b1 b2 : beq b1 b2 = true ↔ b1 = b2.\nProof. destruct b1, b2; simpl; intuition congruence. Qed.\n\nLemma ascii_beq_true x y : ascii_beq x y = true ↔ x = y.\nProof.\n  destruct x, y; rewrite /= !lazy_andb_true !beq_true. intuition congruence.\nQed.\n\nLemma string_beq_true s1 s2 : string_beq s1 s2 = true ↔ s1 = s2.\nProof.\n  revert s2. induction s1 as [|x s1 IH]=> -[|y s2] //=.\n  rewrite lazy_andb_true ascii_beq_true IH. intuition congruence.\nQed.\n\nLemma string_beq_reflect s1 s2 : reflect (s1 = s2) (string_beq s1 s2).\nProof. apply iff_reflect. by rewrite string_beq_true. Qed.\n\nModule Export ident.\nInductive ident :=\n  | IAnon : positive → ident\n  | INamed :> string → ident.\nEnd ident.\n\nInstance maybe_IAnon : Maybe IAnon := λ i,\n  match i with IAnon n => Some n | _ => None end.\nInstance maybe_INamed : Maybe INamed := λ i,\n  match i with INamed s => Some s | _ => None end.\n\nInstance beq_eq_dec : EqDecision ident.\nProof. solve_decision. Defined.\n\nDefinition positive_beq := Eval compute in Pos.eqb.\n\nLemma positive_beq_true x y : positive_beq x y = true ↔ x = y.\nProof. apply Pos.eqb_eq. Qed.\n\nDefinition ident_beq (i1 i2 : ident) : bool :=\n  match i1, i2 with\n  | IAnon n1, IAnon n2 => positive_beq n1 n2\n  | INamed s1, INamed s2 => string_beq s1 s2\n  | _, _ => false\n  end.\n\nLemma ident_beq_true i1 i2 : ident_beq i1 i2 = true ↔ i1 = i2.\nProof.\n  destruct i1, i2; rewrite /= ?string_beq_true ?positive_beq_true; naive_solver.\nQed.\n\nLemma ident_beq_reflect i1 i2 : reflect (i1 = i2) (ident_beq i1 i2).\nProof. apply iff_reflect. by rewrite ident_beq_true. Qed.\n\nDefinition option_bind {A B} (f : A → option B) (mx : option A) : option B :=\n  match mx with Some x => f x | None => None end.\nArguments option_bind _ _ _ !_ /.\n", "meta": {"author": "jtassarotti", "repo": "polaris", "sha": "c7873f05214351d54cacf3d8482625ee33ad3288", "save_path": "github-repos/coq/jtassarotti-polaris", "path": "github-repos/coq/jtassarotti-polaris/polaris-c7873f05214351d54cacf3d8482625ee33ad3288/theories/proofmode/base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.2800814139881575}}
{"text": "(** printing ⊢k #&vdash;<sub>k</sub># *)\n(** printing ⊢s #&vdash;<sub>s</sub># *)\n(** printing ⊢! #&vdash;# *)\n(** printing k⊣ #&dashv;# *)\n(** printing |- #&vdash;# *)\n(** printing ↗! #&nearrow;# *)\n(** printing ↘! #&searrow;# *)\n(** printing ⦂ #:# *)\n(** printing <⦂ #<:# *)\n(** printing [<=] #&subseteq;# *)\n(** printing `union` #&cup;# *)\n(** printing \\u #&cup;# *)\n(** printing `notin` #&notin;# *)\n(** printing `in` #&in;# *)\n(** printing ⊆<⦂ #&subseteq;<sub>&lt;:</sub># *)\n\nSet Implicit Arguments.\nRequire Import Definitions.\nRequire Import Step.\nRequire Import Misc.\nRequire Import ListRelations.\nRequire Import StructuralProperties.\nRequire Import OperationProperties.\n\n(** * Definition and Properties of Kernel D#<sub>&lt;:</sub>#\n    \n    This file defines Kernel D#<sub>&lt;:</sub># and examines its properties.\n *)\n\nReserved Notation \"[ L ] G ⊢k S <⦂ U\" (at level 70).\nInductive subtykn : vars -> env -> typ -> typ -> Prop :=\n(** [―――――――――――――――] K-VRefl #<br>#\n    [G ⊢k x.A <: x.A] *)\n| snf_vrefl : forall L G x,\n    [ L ] G ⊢k typ_sel x <⦂ typ_sel x\n(** [―――――――――――] K-Top #<br>#\n    [G ⊢k T <: ⊤] *)\n| snf_top : forall L G T,\n    [ L ] G ⊢k T <⦂ typ_top\n(** [―――――――――――] K-Bot #<br>#\n    [G ⊢k ⊥ <: T] *)\n| snf_bot : forall L G T,\n    [ L ] G ⊢k typ_bot <⦂ T\n(** [G ⊢k S <: T1] #<br>#\n    [G ⊢k T2 <: U] #<br>#\n    [―――――――――――――――――――――――――――――――――――] K-Bnd #<br>#\n    [G ⊢k {A : T1 .. T2} <: {A : S .. U}] *)\n| snf_bnd : forall L G S T1 T2 U,\n    [ L ] G ⊢k S <⦂ T1 ->\n    [ L ] G ⊢k T2 <⦂ U ->\n    [ L ] G ⊢k typ_bnd T1 T2 <⦂ typ_bnd S U\n(** [G ; x : T ⊢k U1 <: U2] #<br>#\n    [―――――――――――――――――――――――――――――] K-All #<br>#\n    [G ⊢k ∀(x : T)U1 <: ∀(x : T)U2] *)\n| snf_all : forall L G T U1 U2 x,\n    x `notin` union (fv G)\n      (union (fv T) (union (fv U1) (union (fv U2) L))) ->\n    [ union L (union (singleton x) (fv T)) ]\n      x ~ T ++ G ⊢k open x U1 <⦂ open x U2 ->\n    [ L ] G ⊢k typ_all T U1 <⦂ typ_all T U2\n(** [G ⊢k G(x) <: {A : S .. ⊤}] #<br>#\n    [―――――――――――――――――――――――――] K-Sel1 #<br>#\n    [G ⊢k S <: x.A] *)\n| snf_sel1 : forall L G x T S,\n    binds x T G ->\n    [ L ] G ⊢k T <⦂ typ_bnd S typ_top ->\n    [ L ] G ⊢k S <⦂ (typ_sel $ avar_f x)\n(** [G ⊢k G(x) <: {A : ⊥ .. U}] #<br>#\n    [―――――――――――――――――――――――――] K-Sel2 #<br>#\n    [G ⊢k x.A <: U] *)\n| snf_sel2 : forall L G x T U,\n    binds x T G ->\n    [ L ] G ⊢k T <⦂ typ_bnd typ_bot U ->\n    [ L ] G ⊢k typ_sel $ avar_f x <⦂ U\nwhere \"[ L ] G ⊢k S <⦂ U\" := (subtykn L G S U).\nHint Constructors subtykn.\n\nProgram Fixpoint subtykn_refl T {measure (typ_struct_measure T)} :\n  forall L G,\n    [ L ] G ⊢k T <⦂ T := _.\nNext Obligation.\n  destruct T; eauto.\n  - pick_fresh x. econstructor; eauto.\n    apply subtykn_refl. autorewrite with measures.\n    simpl; lia.\n  - constructor; apply subtykn_refl; simpl; lia.\nQed.\n\nLemma subtykn_sound : forall L G S U,\n    [ L ] G ⊢k S <⦂ U ->\n    uniq G ->\n    G ⊢ S <⦂ U.\nProof.\n  induction on subtykn; routine.\n  - eapply st_all; trivial.\n    cofinite.\n    apply open_subst_subty with (x := x); auto.\n  - eauto using ty_sub.\n  - eauto using ty_sub.\nQed.\n\nLemma weaken_subtykn_gen : forall L' G1 G2 S U,\n    [ L' ] G1 ++ G2 ⊢k S <⦂ U ->\n    forall L G,\n      L' [=] L `union` fv G ->\n      [ L ] G1 ++ G ++ G2 ⊢k S <⦂ U.\nProof.\n  dep induction on subtykn; eroutine.\n  econstructor.\n  - instantiate (1 := x). rewrite H2 in *.\n    change (union (dom (H0 ++ H1)) (fv_values fv_typ (H0 ++ H1)))\n      with (fv (H0 ++ H1)) in H.\n    change (union (dom G) (fv_values fv_typ G)) with (fv G) in H.\n    repeat rewrite fv_union in *.\n    fold_cls. fsetdec.\n  - reassoc 4 with 3.\n    eapply IHsubtykn; auto.\n    rewrite H2.\n    change (union (dom G) (fv_values fv_typ G)) with (fv G).\n    clear H. fold_cls.\n    fsetdec.\nQed.\n\nLemma weaken_subtykn : forall L G G' S U,\n    [ L `union` fv G' ] G ⊢k S <⦂ U -> [ L ] G' ++ G ⊢k S <⦂ U.\nProof.\n  intros. reassoc 2 with 0.\n  eapply weaken_subtykn_gen; eauto.\n  fsetdec.\nQed.\nLocal Hint Resolve weaken_subtykn.\n\n(** ** Lack of Transitivity\n\n    Despite that Kernel D#<sub>&lt;:</sub># has no transitivity, it is still possible to show that\n    Kernel D#<sub>&lt;:</sub># is transitivity on [⊤] and [⊥].\n *)\n\nFixpoint bnd_layer (T : typ) (Ts : list typ) : typ :=\n  match Ts with\n  | nil => T\n  | cons T' Ts =>\n    typ_bnd T' (bnd_layer T Ts)\n  end.\n\nLemma trans_on_top : forall L G T,\n    [ L ] G ⊢k typ_top <⦂ T ->\n    forall S,\n      [ L ] G ⊢k S <⦂ T\nwith layered_top_trans : forall L G T l U,\n    [ L ] G ⊢k T <⦂ bnd_layer (typ_bnd typ_top U) l ->\n    forall S,\n      [ L ] G ⊢k T <⦂ bnd_layer (typ_bnd S U) l.\nProof.\n  - clear trans_on_top.\n    dep induction on subtykn; eroutine.\n    econstructor; eauto.\n    apply layered_top_trans with (l := nil).\n    trivial.\n\n  - clear layered_top_trans.\n    intros. gen S. dependent induction H; intros; eauto.\n    1-5:induction l; eroutine.\n\n    econstructor; eauto.\n    specialize (IHsubtykn (cons typ_bot l) U eq_refl).\n    simpl in IHsubtykn. auto.\nQed.\nLocal Hint Resolve trans_on_top.\n\nLemma trans_on_bot : forall L G T,\n    [ L ] G ⊢k T <⦂ typ_bot ->\n    forall U,\n      [ L ] G ⊢k T <⦂ U\nwith layered_bot_trans : forall L G T l S,\n    [ L ] G ⊢k T <⦂ bnd_layer (typ_bnd S typ_bot) l ->\n    forall U,\n      [ L ] G ⊢k T <⦂ bnd_layer (typ_bnd S U) l.\nProof.\n  - clear trans_on_bot.\n    dep induction on subtykn; eroutine.\n    econstructor; eauto.\n    apply layered_bot_trans with (l := nil).\n    trivial.\n\n  - clear layered_bot_trans.\n    intros. gen U.\n    dependent induction H; intros; eauto.\n    1-5:induction l; eroutine.\n\n    econstructor; eauto.\n    specialize (IHsubtykn (cons typ_bot l) S eq_refl).\n    simpl in IHsubtykn. auto.\nQed.\nLocal Hint Resolve trans_on_bot.\n\n(** ** Soundness and Completeness of Step Subtyping w.r.t. Kernel D#<sub>&lt;:</sub># *)\n\n(** Recall that there is an alternative definition of [Exposure], which is used here\n    to serve as an intermediate setup to show the soundness theorem of kernel D#<sub>&lt;:</sub>#.\n *)\nTheorem exposure'_to_subtykn : forall G S U,\n    exposure' G S U ->\n    forall L U',\n      [ L ] G ⊢k U <⦂ U' ->\n      [ L ] G ⊢k S <⦂ U'.\nProof.\n  induction on exposure'.\n  1,2,4:eroutine.\n  routine.\n  econstructor; try eassumption.\n  eauto.\nQed.  \n\n(** *** The soundness theorem *)\nTheorem stp_subty_to_subtykn : forall L G S U,\n    [ L ] G ⊢s S <⦂ U ->\n    [ L ] G ⊢k S <⦂ U.\nProof.\n  induction on stp_subty; routine.\n  - destruct H; eauto.\n    + econstructor. eauto.\n      apply exposure_weakening with (G' := G2 ++ x ~ T) in H.\n      rewrite app_assoc in H.\n      apply exposure_to_exposure' in H.\n      eapply exposure'_to_subtykn; eauto.\n    + econstructor; eauto.\n      apply exposure_weakening with (G' := G2 ++ x ~ T) in H.\n      rewrite app_assoc in H.\n      apply exposure_to_exposure' in H.\n      eapply exposure'_to_subtykn; eauto.      \n      \n  - destruct H; eauto.\n    + econstructor. eauto.\n      apply exposure_weakening with (G' := G2 ++ x ~ T) in H.\n      rewrite app_assoc in H.\n      apply exposure_to_exposure' in H.\n      eapply exposure'_to_subtykn; eauto.\n    + econstructor; eauto.\n      apply exposure_weakening with (G' := G2 ++ x ~ T) in H.\n      rewrite app_assoc in H.\n      apply exposure_to_exposure' in H.\n      eapply exposure'_to_subtykn; eauto.      \n\n  - eauto.\nQed.\n\n(** *** The completeness theorem\n\n    Similar to [Exposure], there is also a need to define alternative definitions of\n[Upcast] and [Downcast]. *)\nInductive upcast_e' : env -> avar -> typ -> Prop :=\n| ue_top : forall G x,\n    upcast_e' G x typ_top\n| ue_bot : forall G x T,\n    binds x T G ->\n    exposure' G T typ_bot ->\n    upcast_e' G (avar_f x) typ_bot\n| ue_bnd : forall G x T L U,\n    binds x T G ->\n    exposure' G T (typ_bnd L U) ->\n    upcast_e' G (avar_f x) U.\nLocal Hint Constructors upcast_e'.\n\nInductive downcast_e' : env -> avar -> typ -> Prop :=\n| de_bot : forall G x,\n    downcast_e' G x typ_bot\n| de_top : forall G x T,\n    binds x T G ->\n    exposure' G T typ_bot ->\n    downcast_e' G (avar_f x) typ_top\n| de_bnd : forall G x T L U,\n    binds x T G ->\n    exposure' G T (typ_bnd L U) ->\n    downcast_e' G (avar_f x) L.\nLocal Hint Constructors downcast_e'.\n\n(** Finally, we define a definition of step subtyping where the contexts are not\ntruncated. This is an intermediate setup to show completeness. *)\nInductive stp_subty' : vars -> env -> typ -> typ -> Prop :=\n| ss'_top : forall L G T, stp_subty' L G T typ_top\n| ss'_bot : forall L G T, stp_subty' L G typ_bot T\n| ss'_sel_refl : forall L G x,\n    stp_subty' L G (typ_sel x) (typ_sel x)\n| ss'_sel_left : forall L G x T U,\n    upcast_e' G x T ->\n    stp_subty' L G T U ->\n    stp_subty' L G (typ_sel x) U\n| ss'_sel_right : forall L G x T U,\n    downcast_e' G x T ->\n    stp_subty' L G U T ->\n    stp_subty' L G U (typ_sel x)\n| ss'_bnd : forall L G S1 U1 S2 U2,\n    stp_subty' L G S2 S1 ->\n    stp_subty' L G U1 U2 ->\n    stp_subty' L G (typ_bnd S1 U1) (typ_bnd S2 U2)\n| ss'_all : forall L G T U1 U2 x,\n    x `notin` fv G `union` fv T\n      `union` fv U1 `union` fv U2 `union` L ->\n    stp_subty' (L  `union` singleton x `union` fv T)\n              (x ~ T ++ G) (open x U1) (open x U2) ->\n    stp_subty' L G (typ_all T U1) (typ_all T U2).\nLocal Hint Constructors stp_subty' exposure'.\n\nProgram Fixpoint stp_subty'_refl T {measure (typ_struct_measure T)}\n  : forall L G,\n    stp_subty' L G T T := _.\nNext Obligation.\n  destruct T; eroutine.\n  - pick_fresh x.\n    econstructor.\n    + instantiate (1 := x).\n      auto.\n    + apply stp_subty'_refl.\n      rewrite open_typ_same_measure.\n      lia.\n  - constructor.\n    all:apply stp_subty'_refl; lia.\nQed.\nLocal Hint Resolve stp_subty'_refl.\n\n(** The following definition is a special definition of kernel D#<sub>&lt;:</sub>#, where the steps of\nderivations are accounted for as part of the judgments. Let us call this form\n\"step-enriched\". This is necessary as we (mistakenly) define judgments in [Prop], which\ncannot be eliminated into [Set] or [Type]. The steps of derivations are eventually\nused in the well-foundness induction in the completeness theorem.  *)\nInductive subtykn' : vars -> env -> typ -> typ -> nat -> Prop :=\n| snf'_refl : forall L G x, subtykn' L G (typ_sel x) (typ_sel x) 1\n| snf'_top : forall L G T, subtykn' L G T typ_top 1\n| snf'_bot : forall L G T, subtykn' L G typ_bot T 1\n| snf'_bnd : forall L G S T1 T2 U n1 n2,\n    subtykn' L G S T1 n1 -> subtykn' L G T2 U n2 ->\n    subtykn' L G (typ_bnd T1 T2) (typ_bnd S U) (1 + n1 + n2)\n| snf'_all : forall L G T U1 U2 x n,\n    x `notin` union (fv G)\n      (union (fv T) (union (fv U1) (union (fv U2) L))) ->\n    subtykn' (union L (union (singleton x) (fv T)))\n            (x ~ T ++ G) (open x U1) (open x U2) n ->\n    subtykn' L G (typ_all T U1) (typ_all T U2) (1 + n)\n| snf'_sel1 : forall L G x T S n,\n    binds x T G ->\n    subtykn' L G T (typ_bnd S typ_top) n ->\n    subtykn' L G S (typ_sel $ avar_f x) (1 + n)\n| snf'_sel2 : forall L G x T U n,\n    binds x T G ->\n    subtykn' L G T (typ_bnd typ_bot U) n ->\n    subtykn' L G (typ_sel $ avar_f x) U (1 + n).\nHint Constructors subtykn'.\nNotation \"[ L , n ] G ⊢k S <⦂ U\" := (subtykn' L G S U n) (at level 70).\n\nLemma subtykn_to_subtykn' : forall L G S U,\n    [ L ] G ⊢k S <⦂ U ->\n    exists n, [ L , n ] G ⊢k S <⦂ U.\nProof.\n  induction on subtykn; eroutine.\nQed.\n\nLemma subtykn'_to_subtykn : forall L G S U n,\n    [ L , n ] G ⊢k S <⦂ U ->\n    [ L ] G ⊢k S <⦂ U.\nProof.\n  induction on subtykn'; eroutine.\nQed.\n\n(** It is quite straightforward to show the equivalence of kernel D#<sub>&lt;:</sub># and this\n\"step-enriched\" definition of kernel D#<sub>&lt;:</sub>#. *)\nLemma subtykn_equiv_subtykn' : forall L G S U,\n    [ L ] G ⊢k S <⦂ U <->\n    exists n, [ L , n ] G ⊢k S <⦂ U.\nProof.\n  split; auto using subtykn_to_subtykn'.\n  intros. tidy_up.\n  eauto using subtykn'_to_subtykn.\nQed.\n\nLocal Hint Extern 1 (_ <= _) => lia.\n\n(** This is the auxiliary lemma of completeness theorem. *)\nProgram Fixpoint subtykn'_conversions n {measure n} : forall L G S U,\n    [ L , n ] G ⊢k S <⦂ U ->\n    stp_subty' L G S U /\\\n    (forall T1 T2,\n        U = typ_bnd T1 T2 ->\n        exists S', exposure' G S S' /\\\n              (S' = typ_bot \\/\n               exists T1' T2' n',\n                 S' = typ_bnd T1' T2' /\\\n                 stp_subty' L G T1 T1' /\\\n                 ([ L , n' ] G ⊢k T2' <⦂ T2) /\\ n' <= n))\n  := _.\nNext Obligation.\n  split; intros.\n  - induction H; routine.\n    + eapply ss'_all with x; auto.\n    + clear IHsubtykn'.\n      apply subtykn'_conversions in H0; auto.\n      tidy_up.\n      specialize (H1 _ _ eq_refl).\n      tidy_up; eauto 10.\n    + clear IHsubtykn'.\n      apply subtykn'_conversions in H0; auto.\n      tidy_up.\n      specialize (H1 _ _ eq_refl).\n      tidy_up; eauto.\n\n      apply subtykn'_conversions in H8; auto.\n      tidy_up. eauto.\n\n  - destruct H; subst; progressive_inversions.\n    + eroutine at 14.\n    + eexists. split; [apply ex_stop; auto |].\n      right. repeat eexists; try eassumption; auto.\n      eapply subtykn'_conversions; try eassumption.\n      lia.\n    + apply subtykn'_conversions in H1; try lia.\n      tidy_up.\n      specialize (H1 _ _ eq_refl).\n      tidy_up; eauto.\n\n      apply subtykn'_conversions in H8; try lia.\n      tidy_up.\n      specialize (H6 _ _ eq_refl).\n      tidy_up; eauto 14.\nQed.\n\n(** At this step, we show that step subtyping is complete w.r.t. kernel D#<sub>&lt;:</sub># if\ncontexts are not truncated. The final step is to show that step subtyping performs the\nsame with and without the contexts truncated. *)\nTheorem subtykn_to_stp_subty' : forall L G S U,\n    [ L ] G ⊢k S <⦂ U ->\n    stp_subty' L G S U.\nProof.\n  intros. \n  rewrite subtykn_equiv_subtykn' in *.\n  tidy_up.\n  eapply subtykn'_conversions.\n  eauto.\nQed.\n\nLocal Hint Constructors stp_subty upcast_e downcast_e.\nLocal Hint Resolve exposure'_to_exposure.\n  \nLocal Ltac wf_env :=\n  lazymatch goal with\n  | H : wf_env (_ ++ _) |- _ => apply wf_deapp in H; invert H; subst\n  end.\n\nLemma upcast_e'_to_upcast_e : forall G x T,\n    upcast_e' G x T ->\n    wf_env G ->\n    upcast_e G x T.\nProof.\n  destr on upcast_e'; eroutine.\n  all:apply binds_app in H; tidy_up;\n    pose proof H1; wf_env.\n\n  - eapply uce_bot.\n    apply exposure_strengthening with (G2 := (H ++ x ~ T));\n      try rewrite app_assoc in *; eauto.  \n  - eapply uce_bnd.\n    apply exposure_strengthening with (G2 := (H ++ x ~ T));\n      try rewrite app_assoc in *; eauto.\nQed.\n\nLemma downcast_e'_to_downcast_e : forall G x T,\n    downcast_e' G x T ->\n    wf_env G ->\n    downcast_e G x T.\nProof.\n  destr on downcast_e'; eroutine.\n  all:apply binds_app in H; tidy_up;\n    pose proof H1; wf_env.\n\n  - eapply dce_top.\n    apply exposure_strengthening with (G2 := (H ++ x ~ T));\n      try rewrite app_assoc in *; eauto.  \n  - eapply dce_bnd.\n    apply exposure_strengthening with (G2 := (H ++ x ~ T));\n      try rewrite app_assoc in *; eauto.\nQed.\n\nLocal Hint Resolve upcast_e_preserves_wf upcast_e_preserves_lc upcast_e'_to_upcast_e.\nLocal Hint Resolve downcast_e_preserves_wf\n      downcast_e_preserves_lc downcast_e'_to_downcast_e.\n\nLemma stp_subty'_to_stp_subty : forall L G S U,\n    stp_subty' L G S U ->\n    wf_env G ->\n    fv S [<=] dom G -> lc S ->\n    fv U [<=] dom G -> lc U ->\n    [ L ] G ⊢s S <⦂ U.\nProof.\n  induction on stp_subty'; intros; eauto.\n  - econstructor.\n    + apply upcast_e'_to_upcast_e; eassumption.\n    + progressive_inversions.\n      apply IHstp_subty'; eauto.\n  - econstructor.\n    + apply downcast_e'_to_downcast_e; eassumption.\n    + progressive_inversions.\n      apply IHstp_subty'; eauto.\n  - progressive_inversions. simpl in *.\n    fold_cls. auto 10.\n  - progressive_inversions. simpl in *.\n    invert H2; subst. fold_cls.\n    apply ss_all with x; auto.\n    apply IHstp_subty'.\n    all:try apply open_lc_typ; trivial.\n    + constructor; auto.\n    + pose proof (fv_open_typ U1 x 0).\n      etransitivity; [ eassumption |].\n      set solve.\n    + pose proof (fv_open_typ U2 x 0).\n      etransitivity; [ eassumption |].\n      set solve.\nQed.\n\n(** The completeness theorem is thus established. *)\nTheorem subtykn_to_stp_subty : forall L G S U,\n    [ L ] G ⊢k S <⦂ U ->\n    wf_env G ->\n    fv S [<=] dom G -> lc S ->\n    fv U [<=] dom G -> lc U ->\n    [ L ] G ⊢s S <⦂ U.\nProof.\n  intros.\n  auto using subtykn_to_stp_subty', stp_subty'_to_stp_subty.\nQed.\n\nTheorem subtykn_equiv_stp_subty : forall L G S U,\n    wf_env G ->\n    fv S [<=] dom G -> lc S ->\n    fv U [<=] dom G -> lc U ->\n    [ L ] G ⊢k S <⦂ U <->\n    [ L ] G ⊢s S <⦂ U.\nProof.\n  split; auto using subtykn_to_stp_subty, stp_subty_to_subtykn.\nQed.\n", "meta": {"author": "HuStmpHrrr", "repo": "popl20-artifact", "sha": "48214a55ebb484fd06307df4320813d4a002535b", "save_path": "github-repos/coq/HuStmpHrrr-popl20-artifact", "path": "github-repos/coq/HuStmpHrrr-popl20-artifact/popl20-artifact-48214a55ebb484fd06307df4320813d4a002535b/dsub/Kernel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.28008140622701966}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat div seq ssralg.\n(* Require Import path choice fintype tuple finset ssralg bigop poly polydiv. *)\n(* Require Import ssrint ZArith. *)\n\nFrom CoqEAL Require Import hrel param.\n\nRequire Import ssrmatching.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* Import GRing.Theory Pdiv.Ring Pdiv.CommonRing Pdiv.RingMonic. *)\nDeclare Scope computable_scope.\nDelimit Scope computable_scope with C.\nLocal Open Scope rel.\n\n(* Shortcut for triggering typeclass resolution *)\nLtac tc := do 1?typeclasses eauto.\n\nSection refinements.\n\nFact refines_key : unit. Proof. done. Qed.\nClass refines A B (R : A -> B -> Type) (m : A) (n : B) :=\n  refines_rel : (locked_with refines_key R) m n.\nArguments refines A B R%rel m n.\n\nLemma refinesE A B (R : A -> B -> Type) : refines R = R.\nProof. by rewrite /refines unlock. Qed.\n\nLemma refines_eq T (x y : T) : refines eq x y -> x = y.\nProof. by rewrite refinesE. Qed.\n\n#[export] Instance refines_bool_eq x y : refines bool_R x y -> refines eq x y.\nProof. by rewrite !refinesE=> [[]]. Qed.\n\nLemma nat_R_eq x y : nat_R x y -> x = y.\nProof. by elim=> // m n _ ->. Qed.\n\n#[export] Instance refines_nat_eq x y : refines nat_R x y -> refines eq x y.\nProof. rewrite !refinesE; exact: nat_R_eq. Qed.\n\nLemma refinesP T T' (R : T -> T' -> Type) (x : T) (y : T') :\n  refines R x y -> R x y.\nProof. by rewrite refinesE. Qed.\n\nFact composable_lock : unit. Proof. done. Qed.\nClass composable A B C\n  (rAB : A -> B -> Type) (rBC : B -> C -> Type) (rAC : A -> C -> Type) :=\n  Composable : locked_with composable_lock (rAB \\o rBC <= rAC).\nArguments composable A B C rAB%rel rBC%rel rAC%rel.\n\nLemma composableE A B C\n (rAB : A -> B -> Type) (rBC : B -> C -> Type) (rAC : A -> C -> Type) :\n  composable rAB rBC rAC = (rAB \\o rBC <= rAC).\nProof. by rewrite /composable unlock. Qed.\n\nLemma refines_trans A B C\n  (rAB : A -> B -> Type) (rBC : B -> C -> Type) (rAC : A -> C -> Type)\n  (a : A) (b : B) (c : C) : composable rAB rBC rAC ->\n  refines rAB a b -> refines rBC b c -> refines rAC a c.\nProof.\nby rewrite !refinesE composableE => rABC rab rbc; apply: rABC; exists b.\nQed.\n\nLemma trivial_refines T T' (R : T -> T' -> Type) (x : T) (y : T') :\n  R x y -> refines R x y.\nProof. by rewrite refinesE. Qed.\n\n#[export] Instance refines_apply\n  A B (R : A -> B -> Type) C D (R' : C -> D -> Type) :\n  forall (c : A -> C) (d : B -> D), refines (R ==> R') c d ->\n  forall (a : A) (b : B), refines R a b -> refines R' (c a) (d b) | 99.\nProof. by rewrite !refinesE => c d rcd a b rab; apply: rcd. Qed.\n\n#[export] Instance composable_rid1 A B (R : A -> B -> Type) :\n  composable eq R R | 1.\nProof.\nrewrite composableE; apply: eq_hrelRL.\nby split; [ apply: comp_eql | move=> x y hxy; exists x ].\nQed.\n\n#[export] Instance composable_bool_id1 B (R : bool -> B -> Type) :\n  composable bool_R R R | 1.\nProof. by rewrite composableE => x y [y' [[]]]. Qed.\n\n(* #[export] Instance composable_nat_id1 B (R : nat -> B -> Type) :\n  composable nat_R R R | 1. *)\n(* Proof. by rewrite composableE => x y [y' [/nat_R_eq ->]]. Qed. *)\n\n#[export] Instance composable_comp A B C (rAB : A -> B -> Type)\n  (rBC : B -> C -> Type) : composable rAB rBC (rAB \\o rBC).\nProof. by rewrite composableE. Qed.\n\n#[export] Instance composable_imply A B C A' B' C'\n  (rAB : A -> B -> Type) (rBC : B -> C -> Type) (R1 : A' -> B' -> Type)\n  (R2 : B' -> C' -> Type) (R3 : A' -> C' -> Type) : composable R1 R2 R3 ->\n  composable (rAB ==> R1) (rBC ==> R2) (rAB \\o rBC ==> R3) | 0.\nProof.\nrewrite !composableE => R123 fA fC [fB [RfAB RfBC]] a c [b [rABab rBCbc]].\napply: R123; exists (fB b); split; [ exact: RfAB | exact: RfBC ].\nQed.\n\n#[export] Instance composable_imply_id1 A B A' B' C'\n  (rAB : A -> B -> Type) (R1 : A' -> B' -> Type) (R2 : B' -> C' -> Type)\n  (R3 : A' -> C' -> Type) : composable R1 R2 R3 ->\n  composable (eq ==> R1) (rAB ==> R2) (rAB ==> R3) | 1.\nProof.\nrewrite !composableE => R123 fA fC [fB [RfAB RfBC]] a c rABac.\napply: R123; exists (fB a); split; [ exact: RfAB | exact: RfBC ].\nQed.\n\n(* Composable and pairs *)\nLemma prod_RE A A' B B' (rA : A -> A' -> Type) (rB : B -> B' -> Type) x y :\n  prod_R rA rB x y -> prod_hrel rA rB x y.\nProof. by case; split. Qed.\n\nLemma prod_RI A A' B B' (rA : A -> A' -> Type) (rB : B -> B' -> Type) x y :\n  prod_hrel rA rB x y -> prod_R rA rB x y.\nProof. by move: x y => [x1 x2] [y1 y2] [] /=; constructor. Qed.\n\nLemma refines_prod_R A A' B B' (rA : A -> A' -> Type) (rB : B -> B' -> Type) x y :\n  refines rA x.1 y.1 -> refines rB x.2 y.2 -> refines (prod_R rA rB) x y.\nProof. by rewrite !refinesE => *; apply: prod_RI; split. Qed.\n\n#[export] Instance composable_prod A A' B B' C C'\n  (rAB : A -> B -> Type) (rAB' : A' -> B' -> Type)\n  (rBC : B -> C -> Type) (rBC' : B' -> C' -> Type)\n  (rAC : A -> C -> Type) (rAC' : A' -> C' -> Type) :\n    composable rAB rBC rAC ->\n    composable rAB' rBC' rAC' ->\n    composable (prod_R rAB rAB') (prod_R rBC rBC')\n               (prod_R rAC rAC') | 1.\nProof.\nrewrite !composableE=> h1 h2 [a a'] [c c'] [[b b']].\nmove=> [/prod_RE [/= ??] /prod_RE [/= ??]].\nby split; [ apply: h1; exists b | apply: h2; exists b'].\nQed.\n\nSection refines_split.\nContext {T} {Y} {Z} {R1 : T -> Y -> Type} {R2 : Y -> Z -> Type} {x : T} {z : Z}.\n\nLemma refines_split :\n  refines (R1 \\o R2) x z -> {y : Y & (refines R1 x y * refines R2 y z)%type}.\nProof. by rewrite !refinesE. Qed.\n\nLemma refines_split1 :\n  refines (R1 \\o R2) x z -> {y : Y & (refines R1 x y * R2 y z)%type}.\nProof. by rewrite !refinesE. Qed.\n\nLemma refines_split2 :\n  refines (R1 \\o R2) x z -> {y : Y & (R1 x y * refines R2 y z)%type}.\nProof. by rewrite !refinesE. Qed.\n\nLemma refines_split12 :\n  refines (R1 \\o R2) x z -> {y : Y & (R1 x y * R2 y z)%type}.\nProof. by rewrite !refinesE. Qed.\n\nEnd refines_split.\n\nLemma refines_abstr A B C D (R : A -> B -> Type) (R' : C -> D -> Type)\n      (c : A -> C) (d : B -> D):\n        (forall (a :  A) (b : B), refines R a b -> refines R' (c a) (d b)) ->\n        refines (R ==> R') c d.\nProof. by rewrite !refinesE; apply. Qed.\n\nLemma refines_abstr2 A B A' B' A'' B''\n      (R : A -> B -> Type) (R' : A' -> B' -> Type) (R'' : A'' -> B'' -> Type)\n      (f : A -> A' -> A'' ) (g : B -> B' -> B''):\n        (forall (a : A)   (b : B), refines R a b ->\n         forall (a' : A') (b' : B'), refines R' a' b' ->\n        refines R'' (f a a') (g b b')) ->\n        refines (R ==> R' ==> R'') f g.\nProof. by move=> H; do 2![eapply refines_abstr => *]; apply: H. Qed.\n\n#[export] Instance refines_pair_R\n  A A' B B' (rA : A -> A' -> Type) (rB : B -> B' -> Type) :\n  refines (rA ==> rB ==> prod_R rA rB)%rel (@pair _ _) (@pair _ _).\nProof. by rewrite refinesE. Qed.\n\n#[export] Instance refines_fst_R\n  A A' B B' (rA : A -> A' -> Type) (rB : B -> B' -> Type) :\n  refines (prod_R rA rB ==> rA)%rel (@fst _ _) (@fst _ _).\nProof. by rewrite !refinesE=> [??] [??]. Qed.\n\n#[export] Instance refines_snd_R\n  A A' B B' (rA : A -> A' -> Type) (rB : B -> B' -> Type) :\n  refines (prod_R rA rB ==> rB)%rel (@snd _ _) (@snd _ _).\nProof. by rewrite !refinesE=> [??] [??]. Qed.\n\nClass unify A (x y : A) := unify_rel : x = y.\n#[export] Instance unifyxx A (x : A) : unify x x := erefl.\n\n#[export] Instance refines_of_unify A x y : unify x y -> refines (@unify A) x y | 100.\nProof. by rewrite refinesE. Qed.\n\nLemma refines_comp_unify A B (R : A -> B -> Type) x y :\n  refines (R \\o (@unify B))%rel x y -> refines R x y.\nProof. move=> /refines_split12.\n  rewrite !refinesE=> H.\n  case: H=> ? h.\n  case: h=> ? h2.\n  by rewrite -h2.\nQed.\n\nEnd refinements.\n\nArguments refinesP {T T' R x y} _.\n\n#[export] Hint Mode refines - - - + - : typeclass_instances.\n\n#[export] Hint Extern 0 (refines _ _ _)\n  => apply trivial_refines; eassumption : typeclass_instances.\n\n#[export] Hint Extern 0 (refines (_ \\o (@unify _))%rel _ _)\n  => eapply refines_trans : typeclass_instances.\n\n(* Tactic for doing parametricity proofs, it takes a parametricity\n   theorem generated by the Parametricity plugin as argument *)\nLtac param x :=\n  rewrite ?refinesE; do?move=> ?*;\n  eapply x=> *; eapply refinesP;\n  do ?eapply refines_apply; tc.\n\n(* Special tactic when relation is defined using \\o *)\nLtac param_comp x := eapply refines_trans; tc; param x.\n\n#[export] Instance refines_true : refines _ _ _ :=\n  trivial_refines bool_R_true_R.\n\n#[export] Instance refines_false : refines _ _ _ :=\n  trivial_refines bool_R_false_R.\n\n#[export] Instance refines_negb : refines (bool_R ==> bool_R) negb negb.\nProof. exact/trivial_refines/negb_R. Qed.\n\n#[export] Instance refines_implb : refines (bool_R ==> bool_R ==> bool_R) implb implb.\nProof. exact/trivial_refines/implb_R. Qed.\n\n#[export] Instance refines_andb : refines (bool_R ==> bool_R ==> bool_R) andb andb.\nProof. exact/trivial_refines/andb_R. Qed.\n\n#[export] Instance refines_orb : refines (bool_R ==> bool_R ==> bool_R) orb orb.\nProof. exact/trivial_refines/orb_R. Qed.\n\n#[export] Instance refines_addb : refines (bool_R ==> bool_R ==> bool_R) addb addb.\nProof. exact/trivial_refines/addb_R. Qed.\n\n#[export] Instance refines_eqb : refines (bool_R ==> bool_R ==> bool_R) eqtype.eq_op eqtype.eq_op.\nProof. exact/trivial_refines/eqb_R. Qed.\n\nLemma refines_goal (G G' : Type) : refines (fun T T' => T' -> T) G G' -> G' -> G.\nProof. by rewrite refinesE. Qed.\n\n#[export] Instance refines_leibniz_eq (T : eqType) (x y : T) b :\n  refines bool_R (x == y) b -> refines (fun T' T => T -> T') (x = y) b.\nProof. by move=> /refines_bool_eq; rewrite !refinesE => <- /eqP. Qed.\n\nModule Refinements.\n\n(* Generic operations *)\nModule Op.\n\nClass zero_of A := zero_op : A.\n#[export] Hint Mode zero_of + : typeclass_instances.\nClass one_of A := one_op : A.\n#[export] Hint Mode one_of + : typeclass_instances.\nClass opp_of A := opp_op : A -> A.\n#[export] Hint Mode opp_of + : typeclass_instances.\nClass add_of A := add_op : A -> A -> A.\n#[export] Hint Mode add_of + : typeclass_instances.\nClass sub_of A := sub_op : A -> A -> A.\n#[export] Hint Mode sub_of + : typeclass_instances.\nClass mul_of A := mul_op : A -> A -> A.\n#[export] Hint Mode mul_of + : typeclass_instances.\nClass exp_of A B := exp_op : A -> B -> A.\n#[export] Hint Mode exp_of + + : typeclass_instances.\nClass div_of A := div_op : A -> A -> A.\n#[export] Hint Mode div_of + : typeclass_instances.\nClass inv_of A := inv_op : A -> A.\n#[export] Hint Mode inv_of + : typeclass_instances.\nClass mod_of A := mod_op : A -> A -> A.\n#[export] Hint Mode mod_of + : typeclass_instances.\nClass scale_of A B := scale_op : A -> B -> B.\n#[export] Hint Mode scale_of + + : typeclass_instances.\n\nClass eq_of A := eq_op : A -> A -> bool.\n#[export] Hint Mode eq_of + : typeclass_instances.\nClass leq_of A := leq_op : A -> A -> bool.\n#[export] Hint Mode leq_of + : typeclass_instances.\nClass lt_of A := lt_op : A -> A -> bool.\n#[export] Hint Mode lt_of + : typeclass_instances.\nClass size_of A N := size_op : A -> N.\n#[export] Hint Mode size_of + + : typeclass_instances.\n\nClass spec_of A B   := spec : A -> B.\n#[export] Hint Mode spec_of + + : typeclass_instances.\nDefinition spec_id {A : Type} : spec_of A A := id.\nClass implem_of A B := implem : A -> B.\n#[export] Hint Mode implem_of + + : typeclass_instances.\nDefinition implem_id {A : Type} : implem_of A A := id.\nClass cast_of A B  := cast_op : A -> B.\n#[export] Hint Mode cast_of + + : typeclass_instances.\n\nEnd Op.\nEnd Refinements.\n\nImport Refinements.Op.\n\n#[export]\nTypeclasses Transparent zero_of one_of opp_of add_of sub_of mul_of exp_of div_of\n            inv_of mod_of scale_of size_of eq_of leq_of lt_of spec_of implem_of cast_of.\n\nArguments spec / A B spec_of _: assert.\n\nNotation \"0\"      := zero_op        : computable_scope.\nNotation \"1\"      := one_op         : computable_scope.\nNotation \"-%C\"    := opp_op.\nNotation \"- x\"    := (opp_op x)     : computable_scope.\nNotation \"+%C\"    := add_op.\nNotation \"x + y\"  := (add_op x y)   : computable_scope.\nNotation \"x - y\"  := (sub_op x y)   : computable_scope.\nNotation \"*%C\"    := mul_op.\nNotation \"x * y\"  := (mul_op x y)   : computable_scope.\nNotation \"x ^ y\"  := (exp_op x y)   : computable_scope.\nNotation \"x %/ y\" := (div_op x y)   : computable_scope.\nNotation \"x ^-1\"  := (inv_op x)     : computable_scope.\nNotation \"x %% y\" := (mod_op x y)   : computable_scope.\nNotation \"*:%C\"   := scale_op.\nNotation \"x *: y\" := (scale_op x y) : computable_scope.\nNotation \"x == y\" := (eq_op x y)    : computable_scope.\nNotation \"x <= y\" := (leq_op x y)   : computable_scope.\nNotation \"x < y\"  := (lt_op x y)    : computable_scope.\nNotation cast     := (@cast_op _).\n\nLtac simpC :=\n  do ?[ rewrite -[0%C]/0%R\n      | rewrite -[1%C]/1%R\n      | rewrite -[(_ + _)%C]/(_ + _)%R\n      | rewrite -[(_ + _)%C]/(_ + _)%N\n      | rewrite -[(- _)%C]/(- _)%R\n      | rewrite -[(_ - _)%C]/(_ - _)%R\n      | rewrite -[(_ - _)%C]/(_ - _)%N\n      | rewrite -[(_ * _)%C]/(_ * _)%R\n      | rewrite -[(_ * _)%C]/(_ * _)%N\n      | rewrite -[(_ %/ _)%C]/(_ %/ _)%R\n      | rewrite -[(_ %% _)%C]/(_ %% _)%R\n      | rewrite -[(_ == _)%C]/(_ == _)%bool\n      ].\n\n(* Section testmx. *)\n(* Variable mxA : nat -> nat -> Type. *)\n(* Definition idmx (m n : nat) (mx : mxA m n) : mxA m n := mx. *)\n(* End testmx. *)\n(* Parametricity idmx. *)\n(* Print idmx_R. (* Here we get something too general! *) *)\n\n\n\n(* Workaround because casts are not retained for hypothesis, so we\ndesign this elimination lemma to abstract the context and vm_compute in the goal *)\nLemma abstract_context T (P : T -> Type) x : (forall Q, Q = P -> Q x) -> P x.\nProof. by move=> /(_ P); apply. Qed.\n\nTactic Notation  \"context\" \"[\" ssrpatternarg(pat) \"]\" tactic3(tac) :=\n  let H := fresh \"H\" in let Q := fresh \"Q\" in let eqQ := fresh \"eqQ\" in\n  ssrpattern pat => H;\n  elim/abstract_context : (H) => Q eqQ; rewrite /H {H};\n  tac; rewrite eqQ {Q eqQ}.\n\nClass strategy_class (C : forall T, T -> T -> Prop) :=\n   StrategyClass : C = @eq.\n#[export] Hint Mode strategy_class + : typeclass_instances.\n\nClass native_compute T (x y : T) := NativeCompute : x = y.\n#[export] Hint Mode native_compute - + - : typeclass_instances.\n#[export] Hint Extern 0 (native_compute _ _) =>\n  context [(X in native_compute X)] native_compute; reflexivity :\n  typeclass_instances.\n#[export]\nInstance strategy_class_native_compute : strategy_class native_compute := erefl.\n\nClass vm_compute T (x y : T) := VmCompute : x = y.\n#[export] Hint Mode vm_compute - + - : typeclass_instances.\n#[export] Hint Extern 0 (vm_compute _ _) =>\n  context [(X in vm_compute X)] vm_compute; reflexivity :\n  typeclass_instances.\n#[export]\nInstance strategy_class_vm_compute : strategy_class vm_compute := erefl.\n\nClass compute T (x y : T) := Compute : x = y.\n#[export] Hint Mode compute - + - : typeclass_instances.\n#[export] Hint Extern 0 (compute _ _) =>\n  context [(X in compute X)] compute; reflexivity :\n  typeclass_instances.\n#[export] Instance strategy_class_compute : strategy_class compute := erefl.\n\nClass simpl T (x y : T) := Simpl : x = y.\n#[export] Hint Mode simpl - + - : typeclass_instances.\n#[export] Hint Extern 0 (simpl _ _) =>\n  context [(X in simpl X)] simpl; reflexivity :\n  typeclass_instances.\n#[export] Instance strategy_class_simpl : strategy_class simpl := erefl.\n\nLemma coqeal_eq C {eqC : strategy_class C} {T T'} spec (x x' : T) {y y' : T'}\n   {rxy : refines eq (spec_id x) (spec y)}  {ry : C _ y y'}\n   {rx : simpl (spec y') x'} : x = x'.\nProof. by rewrite eqC in ry; rewrite -rx -ry; apply: refines_eq. Qed.\n\nNotation \"'[' 'coqeal'  strategy  'of'  x ']'\" :=\n  (@coqeal_eq strategy _ _ _ _ x _ _ _ _ _ _).\nNotation coqeal strategy := [coqeal strategy of _].\nNotation \"'[' 'coqeal'  strategy  'of'  x  'for'  y ']'\" :=\n  ([coqeal strategy of x] : y = _).\n\nLtac coqeal := apply: refines_goal; vm_compute.\nTactic Notation \"coqeal_\" tactic3(tac) :=  apply: refines_goal; tac.\nTactic Notation \"coqeal\" \"[\" ssrpatternarg(pat) \"]\" open_constr(strategy) :=\n  let H := fresh \"H\" in let Q := fresh \"Q\" in let eqQ := fresh \"eqQ\" in\n  ssrpattern pat => H; elim/abstract_context : (H) => Q eqQ;\n  rewrite /H {H} [(X in Q X)](coqeal strategy) eqQ {Q eqQ}.\n\nLtac refines_apply1 := eapply refines_apply; tc.\nLtac refines_abstr1 := eapply refines_abstr=> ???; tc.\nLtac refines_apply := do ![refines_apply1].\nLtac refines_abstr := do ![refines_abstr1].\nLtac refines_trans :=  eapply refines_trans; tc.\n\n(** Automation: for proving refinement lemmas involving if-then-else's\ndo [rewrite !ifE; apply refines_if_expr]. *)\nLemma refines_if_expr\n  (A C : Type) (b1 b2 : bool) (vt1 vf1 : A) (vt2 vf2 : C) (R : A -> C -> Type) :\n  refines bool_R b1 b2 -> (b1 -> b2 -> R vt1 vt2) -> (~~ b1 -> ~~ b2 -> R vf1 vf2) ->\n  refines R (if_expr b1 vt1 vf1) (if_expr b2 vt2 vf2).\nProof.\nmove/refines_bool_eq/refinesP=> Hb; rewrite -!{}Hb => Ht Hf.\nrewrite /if_expr !refinesE; case: b1 Ht Hf => Ht Hf.\nexact: Ht.\nexact: Hf.\nQed.\n\nLemma optionE (A B : Type) (o : option A) (b : B) (f : A -> B) :\n  match o with\n  | Some a => f a\n  | None => b\n  end = oapp f b o.\nProof. by []. Qed.\n\n(** Automation: for proving refinement lemmas involving options,\ndo [rewrite !optionE; refines_apply]. *)\n#[export] Instance refines_option\n  (A B : Type) (rA : A -> A -> Type) (rB : B -> B -> Type) :\n  refines ((rA ==> rB) ==> rB ==> option_R rA ==> rB) (@oapp _ _) (@oapp _ _).\nProof.\nrewrite refinesE => f1 f2 Hf b1 b2 Hb o1 o2 Ho.\ncase: o1 Ho => [a1|]; case: o2 => [a2|] Ho //=.\n{ eapply refinesP; refines_apply; rewrite refinesE in Ho *.\n  by inversion_clear Ho. }\n{ by eapply refinesP; inversion_clear Ho. }\n{ by eapply refinesP; inversion_clear Ho. }\nQed.\n", "meta": {"author": "coq-community", "repo": "coqeal", "sha": "1063846268eb2c51fd0e8363dee9a247e3f70c7c", "save_path": "github-repos/coq/coq-community-coqeal", "path": "github-repos/coq/coq-community-coqeal/coqeal-1063846268eb2c51fd0e8363dee9a247e3f70c7c/refinements/refinements.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.2800813984658818}}
{"text": "Require Import Coq.Classes.RelationClasses.\n\nRequire Import SpecCert.x86.Architecture.\nRequire Import SpecCert.x86.Event.\n\nDefinition dummy_secure {S :Set} :=\n  fun (a:Architecture S) =>\n    True.\n\nDefinition exec_sec\n           {S       :Set}\n           {lt      :S -> S -> Prop}\n           (context :ProcessorUnit -> S)\n           (policy  :StrictOrder lt)\n           (o       :S):=\n  fun (a:Architecture S) =>\n    let current_context := context (proc a) in\n    lt current_context o \\/ current_context = o.\n\nDefinition secure_transition\n           {S       :Set}\n           {lt      :S -> S -> Prop}\n           (context :ProcessorUnit -> S)\n           (policy  :StrictOrder lt)\n           (a       :Architecture S)\n           (ev      :Event S) :=\n  match ev with\n  | hardware (Exec o) => exec_sec context policy o a\n  | _ => dummy_secure a\n  end.", "meta": {"author": "lthms", "repo": "speccert", "sha": "8c1edfb173548af0e9ca3c4e24d43726401fdb71", "save_path": "github-repos/coq/lthms-speccert", "path": "github-repos/coq/lthms-speccert/speccert-8c1edfb173548af0e9ca3c4e24d43726401fdb71/src/x86/SecureTransition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2800580922190647}}
{"text": "Ltac rnm a b :=\n  rename a into b.\n\nRequire Import Cito.facade.Facade.\n\nRequire Import StringMap.\nRequire Import SyntaxExpr.\nRequire Import Memory.\n\nRequire Import AutoDB.\n\nUnset Implicit Arguments.\n\nLemma length_0 : \n  forall {A: Type} (l: list A),\n    0 = Datatypes.length l <-> l = [].\nProof.\n  destruct l; intros; simpl in *; intuition congruence.\nQed.\n\n(* Generic notations *)\n\nNotation \"table [ key >> value ]\" := (StringMap.MapsTo key value table) (at level 0).\nNotation \"∅\" := (StringMap.empty _).\n\n(* Facade notations and coercions *)\n\nDefinition nat_as_word n : Word.word 32 := Word.natToWord 32 n.\nCoercion nat_as_word : nat >-> Word.word.\n\nDefinition string_as_var str : Expr := Var str.\nCoercion string_as_var : string >-> Expr.\n\nDefinition word_as_constant w : Expr := Const w.\nCoercion word_as_constant : W >-> Expr.\n\nDefinition nat_as_constant n : Expr := Const (Word.natToWord 32 n).\nCoercion nat_as_constant : nat >-> Expr.\n\nNotation \"[ k >sca> v ] :: m\" :=\n  (StringMap.add k (Facade.SCA _ v) m) (at level 22, right associativity) : map_scope.\nNotation \"[ k >adt> v ] :: m\" :=\n  (StringMap.add k (Facade.ADT v) m) (at level 22, right associativity) : map_scope.\nNotation \"[ k >> v ] :: m\" :=\n  (StringMap.add k v m) (at level 22, right associativity) : map_scope.\n\nDelimit Scope map_scope with map.\nOpen Scope map_scope.\n\nNotation \"A ; B\" := (Seq A B) (at level 201,\n                               B at level 201,\n                               left associativity,\n                               format \"'[v' A ';' '/' B ']'\") : facade_scope.\nDelimit Scope facade_scope with facade.\n\nNotation \"x <- y\" := (Assign x y) (at level 100) : facade_scope.\nNotation \"y <- f\" := (Call y f nil) (at level 100, no associativity) : facade_scope.\nNotation \"y <- f x1 .. xn\" := (Call y f (cons x1 .. (cons xn nil) ..))\n                                 (at level 100, no associativity) : facade_scope.\n\nNotation \"A < B\" := (TestE IL.Lt A B) : facade_scope.\nNotation \"A <= B\" := (TestE IL.Le A B) : facade_scope.\nNotation \"A <> B\" := (TestE IL.Ne A B) : facade_scope.\nNotation \"A = B\" := (TestE IL.Eq A B) : facade_scope.\nNotation \"! x\" := (x = 0)%facade (at level 70, no associativity).\n\nNotation \"A * B\" := (Binop IL.Times A B) : facade_scope.\nNotation \"A + B\" := (Binop IL.Plus A B) : facade_scope.\nNotation \"A - B\" := (Binop IL.Minus A B) : facade_scope.\n\nNotation \"'While' A B\" := (While A B)\n                            (at level 200,\n                             A at level 0,\n                             B at level 1000,\n                             format \"'[v    ' 'While'  A '/' B ']'\")\n                          : facade_scope.\n  \nNotation \"'If' a 'then' b 'else' c\" := (Facade.If a b c)\n                                          (at level 200,\n                                           a at level 1000,\n                                           b at level 1000,\n                                           c at level 1000,\n                                          format \"'[v' '[v    ' 'If'  a  'then' '/' b ']' '/' '[v    ' 'else' '/' c ']' ']'\")\n                                       : facade_scope.\n\nDefinition Fold (head is_empty seq: StringMap.key) \n                _pop_ _empty_ loop_body := (\n    Call is_empty _empty_ (seq :: nil);\n    While (!is_empty) (\n        Call head _pop_ (seq :: nil);\n        loop_body;\n        Call is_empty _empty_ (seq :: nil)\n    )\n)%facade.\n\nPrint Fold.\n\n(* General tactics & lemmas *)\n\nLemma weqb_false_iff :\n  forall {sz} (w1 w2: @Word.word sz),\n    Word.weqb w1 w2 = false <-> w1 <> w2.\nProof.\n  split; try rewrite <- Word.weqb_true_iff in *; try congruence.\n  destruct (Word.weqb w1 w2); intuition.\nQed.\n\nLemma a_neq_a_False :\n  forall {A: Type} (a: A),\n    a <> a <-> False.\nProof.\n  intuition.\nQed.\n\nLemma a_eq_a_True :\n  forall {A: Type} (a: A),\n    a = a <-> True.\nProof.\n  intuition.\nQed.\n\nLemma equiv_true : \n  forall P : Prop, (True <-> P) <-> P.\n  intuition.\nQed.\n\nLemma equiv_true' :\n  forall {P Q: Prop},\n    P -> (P <-> Q) -> Q.\nProof.\n  intuition.\nQed.\n\nLemma or_left_imp: forall {P Q R},\n                     (P \\/ Q -> R) -> (P -> R).\n  tauto.\nQed.\n\nLemma or_right_imp: forall {P Q R},\n                      (P \\/ Q -> R) -> (Q -> R).\n  tauto.\nQed.\n\nLemma not_or :\n  forall P Q,\n    ~ (P \\/ Q) <-> (~ P /\\ ~ Q).\n  intuition.\nQed.\n\nLtac autoinj :=\n  intros; repeat (match goal with\n                    | [ H: ?f ?a = ?f ?b |- _ ] => \n                      (injection H; intros; clear H)\n                    | [ H: ?f ?x ?a = ?f ?x ?b |- _ ] => \n                      (injection H; intros; clear H)\n                    | [ H: ?f ?a1 ?b1 = ?f ?a2 ?b2 |- _ ] => \n                      (injection H; intros; clear H)\n                  end; try subst); try solve [intuition].\n\nLtac autoinj' := (* TODO: Needed? *)\n  intros; \n  repeat match goal with\n           | [ H: context[?f ?A _ = ?f ?A _] |- _ ] => \n             let H' := fresh in\n             assert (forall x y, f A x = f A y <-> x = y) \n               as H'\n                 by (\n                     let H'' := fresh in\n                     split; \n                     intros ** H'';\n                     [injection H'' | rewrite H'']; \n                     intuition);\n               try rewrite H' in *; clear H'\n         end;\n  try solve [intuition].\n\nLtac autospecialize := (* TODO: Needed? *)\n  repeat match goal with \n           | [ H: forall a b, ?x a -> ?y a b -> _, H': ?x _, H'': ?y _ _ |- _ ] \n             => specialize (H _ _ H' H'') \n           | [ H: forall a b, ?x a /\\ ?x' a -> ?y a b -> _, H'1: ?x _, H'2: ?x' _, H'': ?y _ _ |- _ ] \n             => specialize (H _ _ (conj H'1 H'2) H'')\n           | [ H: forall a b, ?x a /\\ ?x' a /\\ ?x'' a -> ?y a b -> _, H'1: ?x _, H'2: ?x' _, H'3: ?x'' _, H'': ?y _ _ |- _ ] \n             => specialize (H _ _ (conj H'1 (conj H'2 H'3)) H'')\n         end.\n\nLtac expand := (* TODO: Needed? *)\n  repeat match goal with\n           | [ H := _ |- _ ] => unfold H in *; clear H\n         end.\n\nLtac autorewrite_equal := (* TODO: Needed? *)\n  match goal with\n    | [ H: StringMap.Equal ?a _, H': context[?a] |- _ ] => rewrite H in H'\n    | [ H: StringMap.Equal ?a _ |- _ ] => rewrite H in *\n    | [ H: StringMap.Equal ?a _ |- _ ] => setoid_rewrite H\n  end.\n\nLtac autodestruct := (* TODO: Needed? There's already destruct_pairs *)\n  repeat match goal with\n           | [ H: exists x, _ |- _ ] => destruct H\n           | [ H: _ /\\ _ |- _ ] => destruct H\n         end.\n\nLtac inversion_clear' hyp :=  (* TODO: Needed? *)\n  inversion hyp; expand; subst; clear hyp.\n\nLtac eq_transitive :=\n  match goal with\n    | [ H: ?a = ?b, H': ?a = ?c |- _ ] => \n      let H'' := fresh in\n      assert (b = c) as H'' by (rewrite <- H, <- H'; reflexivity)\n  end. (* TODO: Use more. Extend to cover a single map mapping the same key to two variables *)\n\nLemma and_eq_refl :\n  forall {A} P (a: A), P /\\ a = a <-> P.\nProof.\n  firstorder.\nQed.\n\nLtac and_eq_refl :=\n  repeat match goal with\n           | [ H: context [ ?a = ?a ] |- _ ] => setoid_rewrite and_eq_refl in H\n         end.\n\n(* Map lemmas and tactics *)\n\nLemma MapsTo_unique :\n  forall {A} map key (v1 v2: A),\n    StringMap.MapsTo key v1 map ->  \n    StringMap.MapsTo key v2 map ->  \n    v1 = v2.\nProof.\n  intros;\n  rewrite StringMapFacts.find_mapsto_iff in *;\n  eq_transitive; autoinj; assumption.\nQed.\n\nLemma not_in_remove_eq :\n  forall {elt} k m,\n    ~ @StringMap.In elt k m ->\n    StringMap.Equal \n      m (StringMap.remove k m).\nProof.\n  unfold StringMap.Equal; intros ** k'.\n  destruct (StringMap.E.eq_dec k k'); subst.\n\n  rewrite StringMapFacts.not_in_find, StringMapFacts.remove_eq_o by trivial;\n    reflexivity.\n\n  rewrite StringMapFacts.remove_neq_o by trivial;\n    reflexivity.\nQed.\n\nLemma not_in_empty :\n  forall {elt} k,\n    ~ @StringMap.In elt k ∅ .\nProof.\n  intros ** _in; rewrite <- StringMapFacts.empty_in_iff; eassumption.\nQed.\n\nDefinition cond_respects_MapEq {elt} := (* TODO: Needed? *)\n  Proper (StringMap.Equal (elt := elt) ==> iff).\n\nLtac remove_not_in :=\n  match goal with\n    | [ H: ~ StringMap.In ?k ?m, H': context[StringMap.remove ?k ?m] |- _] =>\n      setoid_rewrite <- (not_in_remove_eq k m H) in H'\n  end.\n\nLtac subst_find :=\n  match goal with \n    | [H: StringMap.find ?a ?b = _, \n       H': context[StringMap.find ?a ?b] |- _] =>\n      setoid_rewrite H in H'\n    | [H: StringMap.find ?a ?b = _\n       |- context[StringMap.find ?a ?b]] =>\n      setoid_rewrite H\n    | [H: StringMap.MapsTo ?k ?v ?m, \n       H': context[StringMap.find ?k ?m] |- _] =>\n      rewrite StringMapFacts.find_mapsto_iff in H;\n        setoid_rewrite H in H';\n        rewrite <- StringMapFacts.find_mapsto_iff in H\n    | [H : StringMap.MapsTo ?k ?v ?m\n       |- context[StringMap.find ?k ?m]] =>\n      rewrite StringMapFacts.find_mapsto_iff in H;\n        setoid_rewrite H;\n        rewrite <- StringMapFacts.find_mapsto_iff in H\n  end. (* TODO: use instead of calling StringMapFacts.find_mapsto_iff everywhere. *)\n\nLtac map_iff_solve' fallback :=\n  repeat setoid_rewrite not_or;\n  match goal with\n    | [ |- ?A /\\ ?B ] => split; map_iff_solve' fallback\n    | [ |- (?a = ?a /\\ _) \\/ (?a <> ?a /\\ _) ] => left; split; [ apply eq_refl | map_iff_solve' fallback ]\n    | [ |- (?a = ?b /\\ _) \\/ (?a <> ?b /\\ _) ] => right; split; [ congruence | map_iff_solve' fallback ]\n    | _ => fallback\n  end.\n\nLtac map_iff_solve fallback :=\n  StringMapFacts.map_iff;\n  map_iff_solve' fallback.\n\nLtac auto_mapsto_unique :=\n  try rewrite <- StringMapFacts.find_mapsto_iff in *;\n  repeat progress match goal with\n                    | [H: StringMap.MapsTo ?k ?v ?st, H': StringMap.MapsTo ?k ?v' ?st |- _] =>\n                      let h := fresh in\n                      pose proof (MapsTo_unique st k v v' H H') as h;\n                        first [discriminate | injection h; clear H]\n                  end.\n\nLtac simpl_find_add_remove :=\n  match goal with\n    | [ |- context[StringMap.find ?k (StringMap.remove ?k ?m)] ] =>\n      rewrite (@StringMapFacts.remove_eq_o _ m k k) by reflexivity\n    | [ H: ?k <> ?k' |- context[StringMap.find ?k (StringMap.remove ?k' ?m)] ] =>\n      rewrite (@StringMapFacts.remove_neq_o _ m k' k) by congruence\n    | [ H: ?k' <> ?k |- context[StringMap.find ?k (StringMap.remove ?k' ?m)] ] =>\n      rewrite (@StringMapFacts.remove_neq_o _ m k' k) by congruence\n    | [ |- context[StringMap.find ?k (StringMap.add ?k ?v ?m)] ] =>\n      rewrite (@StringMapFacts.add_eq_o _ m k k v (eq_refl _)) by reflexivity\n    | [ H: ?k' <> ?k |- context[StringMap.find ?k (StringMap.add ?k' ?v ?m)] ] =>\n      rewrite (@StringMapFacts.add_neq_o _ m k' k v) by congruence\n    | [ H: ?k <> ?k' |- context[StringMap.find ?k (StringMap.add ?k' ?v ?m)] ] =>\n      rewrite (@StringMapFacts.add_neq_o _ m k' k v) by congruence\n    | [ |- context[StringMap.find ?k (StringMap.empty _)] ] =>\n      rewrite (StringMapFacts.empty_o _ k)\n  end.\n\nLemma StringMap_remove_add_neq :\n  forall {elt} {k1 k2 v} (map: StringMap.t elt),\n    k1 <> k2 ->\n    StringMap.Equal (StringMap.remove k2 (StringMap.add k1 v map)) (StringMap.add k1 v (StringMap.remove k2 map)).\nProof.\n  unfold StringMap.Equal; intros ** k'.\n  destruct (StringMap.E.eq_dec k' k1), (StringMap.E.eq_dec k' k2);\n    subst; repeat simpl_find_add_remove; congruence.\nQed.\n\nLemma StringMap_remove_add_eq :\n  forall {elt} {k1 k2 v} (map: StringMap.t elt),\n    k1 = k2 ->\n    StringMap.Equal (StringMap.remove k2 (StringMap.add k1 v map)) (StringMap.remove k2 map).\nProof.\n  unfold StringMap.Equal; intros ** k'.\n  destruct (StringMap.E.eq_dec k' k1), (StringMap.E.eq_dec k' k2);\n    subst; repeat simpl_find_add_remove; congruence.\nQed.\n\nLemma StringMap_remove_empty :\n  forall {elt : Type} (k : StringMap.key),\n    StringMap.Equal (StringMap.remove (elt:=elt) k ∅) ∅ .\nProof.\n  unfold StringMap.Equal; intros ** k'.\n  destruct (StringMap.E.eq_dec k' k);\n    subst; repeat simpl_find_add_remove; congruence.\nQed.\n\n(* Pre and post-conditions *)\n\nDefinition Superset\n           {elt wrapped_elt}\n           (state bindings: StringMap.t wrapped_elt)\n           (wrapper: elt -> wrapped_elt) :=\n  forall k v, StringMap.MapsTo k (wrapper v) bindings -> StringMap.MapsTo k (wrapper v) state.\n\nDefinition SomeSCAs {av} (state : State av) bindings :=\n  Superset state bindings (Facade.SCA av).\n\nDefinition AllADTs {av} (state: State av) bindings  :=\n  Superset state bindings (@Facade.ADT av) /\\\n  Superset bindings state (@Facade.ADT av).\n  \nDefinition ProgOk {av env} prog initial_knowledge initial_scas final_scas initial_adts final_adts :=\n  forall initial_state,\n    initial_knowledge /\\\n    SomeSCAs initial_state initial_scas /\\\n    AllADTs initial_state initial_adts  ->\n    Safe env prog initial_state /\\\n    forall final_state,\n      @RunsTo av env prog initial_state final_state ->\n      SomeSCAs final_state final_scas /\\\n      AllADTs final_state final_adts.\n\nDefinition Prog {av env} initial_knowledge initial_scas final_scas initial_adts final_adts :=\n  {prog | @ProgOk av env prog initial_knowledge initial_scas final_scas initial_adts final_adts }%comp.\n\n(* Facade lemmas and tactics *)\n\nLtac unfold_coercions :=\n  unfold string_as_var, nat_as_constant, nat_as_word, word_as_constant in *.\n\nDefinition BoolToW (b: bool) := if b then WOne else WZero.\n\nDefinition WToBool (w: @Word.word 32) := negb (Word.weqb w WZero).\n\nLemma BoolToW_invert : forall b, WToBool (BoolToW b) = b.\nProof.\n  destruct b; intuition.\nQed.\n\nLemma binop_Eq_true_iff :\n  forall w1 w2,\n    Some (IL.wneb (eval_binop (inr IL.Eq) w1 w2)\n                  (Word.natToWord 32 0)) = Some true ->\n    w1 = w2.\nProof.\n  unfold eval_binop, IL.evalTest, IL.wneb, IL.weqb; intros.\n  destruct (Word.weqb w1 w2) eqn:eq0;\n  try solve [compute in *; discriminate];  \n  rewrite ?Word.weqb_true_iff, ?weqb_false_iff in eq0;\n  assumption.\nQed.\n\nLemma BoolToW_eval :\n  forall {av} state var b1 b2,\n    b1 = negb b2 ->\n    state[var >> SCA av (BoolToW b1)] ->\n    eval_bool state (var = 0)%facade = Some b2.\nProof.\n  unfold_coercions; unfold BoolToW, WOne, WZero, eval_bool, eval, eval_binop_m;\n  intros; destruct_pairs; subst; subst_find; destruct b2; subst; reflexivity.\nQed.\n\nLemma SCA_inj :\n  forall av v v',\n    SCA av v = SCA av v' -> v = v'.\nProof.\n  autoinj.\nQed.\n\nLemma ADT_inj :\n  forall av v v',\n    @Facade.ADT av v = @Facade.ADT av v' -> v = v'.\nProof.\n  autoinj.\nQed.\n\nLemma List_inj :\n  forall x y : list W, \n    Facade.ADT (List x) = Facade.ADT (List y) -> \n    x = y.\nProof.\n  autoinj.\nQed.\n\nLemma eval_binop_inv :\n  forall (test: bool),\n    IL.wneb (eval_binop (inr IL.Eq) (if test then WOne else WZero) WZero)\n            (Word.natToWord 32 0) = negb test.\nProof.\n  intros; destruct test; simpl; reflexivity.\nQed.\n\nFixpoint AllVariables expr :=\n  match expr with\n    | Var str => (str :: nil)\n    | Const _ => nil\n    | Binop _ e1 e2 => (AllVariables e1 ++ AllVariables e2)%list\n    | TestE _ e1 e2 => (AllVariables e1 ++ AllVariables e2)%list\n  end.\n\nLemma eval_expr_some_sca {av} :\n  forall expr state,\n    (forall k, List.In k (AllVariables expr) -> exists v, state[k >> SCA av v]) ->\n    exists sca, eval state expr = Some (SCA _ sca).\nProof.\n  induction expr; simpl; intros * h.\n\n  destruct (h s (or_introl eq_refl)) as [v maps_to].\n  eexists; rewrite <- StringMapFacts.find_mapsto_iff; eauto.\n\n  eexists; eauto.\n\n  setoid_rewrite in_app_iff in h.\n  destruct (IHexpr1 _ (fun k => or_left_imp (h k))) as [x hx].\n  destruct (IHexpr2 _ (fun k => or_right_imp (h k))) as [y hy].\n  eexists; rewrite hx, hy; simpl; eauto.\n\n  setoid_rewrite in_app_iff in h.\n  destruct (IHexpr1 _ (fun k => or_left_imp (h k))) as [x hx].\n  destruct (IHexpr2 _ (fun k => or_right_imp (h k))) as [y hy].\n  eexists; rewrite hx, hy; simpl; eauto.\nQed.\n\n(* Pre/post conditions lemmas *)\n\nLemma Superset_mapsto :\n  forall {elt welt} {k v state map} wrapper,\n    @Superset elt welt state ([k >> wrapper v]::map) wrapper ->\n    state[k >> wrapper v].\nProof.\n  unfold Superset; intros * add.\n  apply add; map_iff_solve intuition.\nQed.\n\nLemma SomeSCAs_mapsto :\n  forall {av} {state: State av} {k v map},\n    SomeSCAs state ([k >sca> v]::map) ->\n    state[k >> SCA _ v].\nProof.\n  intros *; apply Superset_mapsto.\nQed.\n\nLemma AllADTs_mapsto :\n  forall {av} {state: State av} {k v map},\n    AllADTs state ([k >adt> v]::map) ->\n    state[k >> Facade.ADT v].\nProof.\n  unfold AllADTs; intros * (? & ?); eapply Superset_mapsto; eauto.\nQed.\n\nLemma Superset_remove :\n  forall {elt welt} {k v state map} wrapper,\n    @Superset elt welt state ([k >> wrapper v]::map) wrapper ->\n    @Superset elt welt state (StringMap.remove k map) wrapper.\nProof.\n  unfold Superset; intros.\n  apply H. rewrite StringMapFacts.remove_mapsto_iff in *.\n  destruct_pairs; map_iff_solve assumption.\nQed.\n\nLemma SomeSCAs_remove :\n  forall {av} {state: State av} {k v map},\n    SomeSCAs state ([k >sca> v]::map) ->\n    SomeSCAs state (StringMap.remove k map).\nProof.\n  intros *; apply Superset_remove.\nQed.\n\nLemma AllADTs_remove :\n  forall {av} {state: State av} {k v map},\n    AllADTs state ([k >adt> v]::map) ->\n    Superset state (StringMap.remove k map) (@Facade.ADT _).\nProof.\n  unfold AllADTs; intros * (? & ?); eapply Superset_remove; eauto.\nQed.\n\nLemma Superset_swap_remove :\n  forall {elt welt} {k1 k2 v state map} wrapper,\n    k1 <> k2 ->\n    @Superset elt welt state (StringMap.remove k1 ([k2 >> wrapper v]::map)) wrapper ->\n    @Superset elt welt state ([k2 >> wrapper v]::(StringMap.remove k1 map)) wrapper.\nProof.\n  unfold Superset; intros.\n  apply H0. map_iff_solve idtac.\n  \n  destruct (StringMap.E.eq_dec k k1); subst.\n  rewrite StringMapFacts.add_neq_mapsto_iff in * by congruence.\n  rewrite StringMapFacts.remove_mapsto_iff in *; destruct_pairs; assumption.\n  congruence.\n\n  destruct (StringMap.E.eq_dec k k2); subst; map_iff_solve idtac;\n  rewrite StringMapFacts.add_mapsto_iff in *;\n  rewrite StringMapFacts.remove_mapsto_iff in *;\n  intuition.\nQed.\n\nLemma SomeSCAs_swap_remove :\n  forall {av} {state: State av} {k1 k2 v map},\n    k1 <> k2 ->\n    SomeSCAs state (StringMap.remove k1 ([k2 >sca> v]::map)) ->\n    SomeSCAs state ([k2 >sca> v]::(StringMap.remove k1 map)).\nProof.\n  intros *; apply Superset_swap_remove.\nQed.\n\nLemma AllADTs_swap_remove :\n  forall {av} {state: State av} {k1 k2 v map},\n    k1 <> k2 ->\n    AllADTs state (StringMap.remove k1 ([k2 >adt> v]::map)) ->\n    Superset state ([k2 >> Facade.ADT v]::(StringMap.remove k1 map)) (@Facade.ADT _).\nProof.\n  unfold AllADTs; intros * ? (? & ?); eapply Superset_swap_remove; eauto.\nQed.\n\nLemma AllADTs_not_in :\n  forall {av} {var map state},\n    @AllADTs av state map ->\n    ~ StringMap.In (elt:=Value av) var map ->\n    (exists v, StringMap.find var state = Some (SCA _ v)) \\/ ~ StringMapFacts.M.In var state.\nProof.\n  unfold AllADTs; intros.\n  destruct (StringMap.find var state) eqn:eq0.\n\n  destruct v.\n  left; eexists; reflexivity.\n  destruct_pairs.\n  rewrite <- StringMapFacts.find_mapsto_iff in eq0.\n  apply H1 in eq0.\n  apply StringMapFacts.MapsTo_In in eq0.\n  congruence.\n\n  rewrite StringMapFacts.not_find_in_iff; right; assumption.\nQed.\n\nLemma Superset_empty :\n  forall {elt welt} state wrapper,\n    @Superset elt welt state ∅ wrapper.\nProof.\n  unfold Superset; intros; rewrite StringMapFacts.empty_mapsto_iff in *; exfalso; assumption.\nQed.\n  \nLemma SomeSCAs_empty :\n  forall {av} state,\n    @SomeSCAs av state ∅ .\nProof.\n  intros; apply Superset_empty.\nQed.\n\nLemma not_in_adts_not_mapsto_adt :\n  forall {av} var state map,\n    @AllADTs av state map ->\n    ~ StringMap.In var map ->\n    not_mapsto_adt var state = true.\nProof.\n  unfold not_mapsto_adt, is_mapsto_adt, is_some_p;\n  intros * h h'.\n  destruct (AllADTs_not_in h h') as [ [ v sbst ] | ];\n    [ rewrite sbst; trivial  | ].\n  \n  rewrite StringMapFacts.not_in_find; trivial.\nQed.\n\nLtac rewrite_Eq_in_all :=\n  repeat match goal with\n           | [ H: StringMap.Equal _ _, H': _ |- _ ] =>\n             progress (try setoid_rewrite H in H';\n                       try setoid_rewrite H)\n           | [ H: pointwise_relation _ _ _ _, H': _ |- _ ] =>\n             progress (try setoid_rewrite H in H';\n                       try setoid_rewrite H)\n           | [ H: _ _ _, H': _ |- _ ] =>\n             progress (try setoid_rewrite H in H';\n                       try setoid_rewrite H)\n         end.\n\nAdd Parametric Morphism elt welt :\n  (@Superset elt welt)\n    with signature (StringMap.Equal ==> StringMap.Equal ==> pointwise_relation _ (@eq _) ==> iff)\n      as Superset_morphism.\n  unfold Superset; intros; rewrite_Eq_in_all; reflexivity.\nQed. \n  \nAdd Parametric Morphism {av} :\n  (@SomeSCAs av)\n    with signature (StringMap.Equal ==> StringMap.Equal ==> iff)\n      as SomeSCAs_morphism.\nProof.\n  unfold SomeSCAs; intros; apply Superset_morphism; intuition.\nQed.\n\nAdd Parametric Morphism {av} :\n  (@AllADTs av)\n    with signature (StringMap.Equal ==> StringMap.Equal ==> iff)\n      as SomeADTs_morphism.\nProof.\n  unfold AllADTs; intros * eq1 * eq2.\n  split; intros (? & ?); split;\n  rewrite !eq1, !eq2 in *; assumption.\nQed.\n\nLemma Superset_reflexive :\n  forall {elt welt} st wrapper,\n    @Superset elt welt st st wrapper.\nProof.\n  firstorder.\nQed.\n\nLemma SomeSCAs_reflexive :\n  forall {av} st,\n    @SomeSCAs av st st.\nProof.\n  firstorder.\nQed.\n\nLemma Superset_transitive :\n  forall {elt welt} s1 s2 s3 wrapper,\n    @Superset elt welt s1 s2 wrapper ->\n    @Superset elt welt s2 s3 wrapper ->\n    @Superset elt welt s1 s3 wrapper.\nProof.\n  firstorder.\nQed.\n\nLemma SomeSCAs_transitive :\n  forall {av} s1 s2 s3,\n    @SomeSCAs av s1 s2 ->\n    @SomeSCAs av s2 s3 ->\n    @SomeSCAs av s1 s3.\nProof.\n  firstorder.\nQed.\n\nLemma Superset_chomp :\n  forall {elt welt} {k v state map} wrapper,\n    @Superset elt welt state map wrapper ->\n    @Superset elt welt ([k >> wrapper v]::state) ([k >> wrapper v]::map) wrapper.\nProof.\n  unfold Superset; intros * h ** k' v' maps_to.\n  destruct (StringMap.E.eq_dec k k');\n    subst; rewrite StringMapFacts.add_mapsto_iff in *;\n    intuition.\nQed.\n\nLemma SomeSCAs_chomp :\n  forall {av} (state: State av) k v scas,\n    SomeSCAs state scas ->\n    SomeSCAs ([k >sca> v]::state) ([k >sca> v]::scas).\nProof.\n  intros *; apply Superset_chomp.\nQed.\n\nLemma AllADTs_chomp :\n  forall {av} (state: State av) k v adts,\n    AllADTs state adts ->\n    AllADTs ([k >adt> v]::state) ([k >adt> v]::adts).\nProof.\n  unfold AllADTs; split; apply Superset_chomp; tauto.\nQed.\n\nLemma Superset_chomp_remove :\n  forall {elt welt} {k v state map} wrapper,\n    @Superset elt welt (StringMap.remove k state) (StringMap.remove k map) wrapper ->\n    @Superset elt welt ([k >> wrapper v]::state) ([k >> wrapper v]::map) wrapper.\nProof.\n  unfold Superset; intros * h ** k' v' maps_to.\n  destruct (StringMap.E.eq_dec k k');\n    subst; rewrite StringMapFacts.add_mapsto_iff in *;\n    setoid_rewrite StringMapFacts.remove_mapsto_iff in h;\n    intuition.\nQed.\n\nLemma SomeSCAs_chomp_remove :\n  forall {av} (state: State av) k v scas,\n    SomeSCAs (StringMap.remove k state) (StringMap.remove k scas) ->\n    SomeSCAs ([k >sca> v]::state) ([k >sca> v]::scas).\nProof.\n  intros *; apply Superset_chomp_remove.\nQed.\n\nLemma AllADTs_chomp_remove :\n  forall {av} (state: State av) k v adts,\n    AllADTs (StringMap.remove k state) (StringMap.remove k adts) ->\n    AllADTs ([k >adt> v]::state) ([k >adt> v]::adts).\nProof.\n  unfold AllADTs; split; apply Superset_chomp_remove; tauto.\nQed.\n\nLemma AllADTs_equiv :\n  forall {av} (state bindings: State av),\n    AllADTs state bindings <->\n    (forall k v, StringMap.MapsTo k (Facade.ADT v) bindings <-> StringMap.MapsTo k (Facade.ADT v) state).\nProof.\n  firstorder.\nQed.\n\nLemma add_adts_pop_sca :\n  forall {av} k v map (state: State av),\n    ~ StringMap.In k map ->\n    AllADTs state map ->\n    AllADTs ([k >sca> v]::state) map.\nProof.\n  setoid_rewrite AllADTs_equiv.\n  intros ** k' v'.\n  destruct (StringMap.E.eq_dec k k'); subst;\n  split; intros H';\n  rewrite StringMapFacts.add_mapsto_iff in *;\n  map_iff_solve idtac.\n\n  apply StringMapFacts.MapsTo_In in H'; congruence.\n  intuition; discriminate.\n\n  rewrite H0 in *; intuition.\n  rewrite H0 in *; intuition.\nQed.\n\nLemma add_sca_pop_adts :\n  forall {av} k v map (state: State av),\n    ~ StringMap.In k map ->\n    SomeSCAs state map ->\n    SomeSCAs ([k >adt> v]::state) map.\nProof.\n  intros ** k' v'.\n  destruct (StringMap.E.eq_dec k k'); subst;\n  intros H';\n  rewrite StringMapFacts.add_mapsto_iff in *;\n  map_iff_solve idtac.\n\n  apply StringMapFacts.MapsTo_In in H'; congruence.\n  intuition; discriminate.\nQed.\n\nLemma Superset_swap_left :\n  forall {elt welt} {k1 k2 v1 v2 state map} wrapper,\n    k1 <> k2 ->\n    @Superset elt welt ([k1 >> v1]::[k2 >> v2]::state) map wrapper ->\n    @Superset elt welt ([k2 >> v2]::[k1 >> v1]::state) map wrapper.\nProof.\n  unfold Superset; intros ** k v mp.\n  destruct (StringMap.E.eq_dec k k1), (StringMap.E.eq_dec k k2);\n    subst; map_iff_solve idtac; try discriminates;\n    specialize (H0 _ _ mp);\n    repeat setoid_rewrite StringMapFacts.add_mapsto_iff in H0;\n    intuition.\nQed.\n\nLemma MapsTo_swap :\n  forall {elt} {k1 k2 v1 v2} {map: StringMap.t elt},\n    k1 <> k2 ->\n    forall k v,\n      ([k1 >> v1]::[k2 >> v2]::map)[k >> v] <->\n      ([k2 >> v2]::[k1 >> v1]::map)[k >> v].\nProof.\n  intros; StringMapFacts.map_iff.\n  destruct (StringMap.E.eq_dec k k1) as [ eq0 | neq0 ];\n    destruct (StringMap.E.eq_dec k k2) as [ eq1 | neq1 ];\n    try rewrite !eq0 in *;\n    try rewrite !eq1 in *;\n    split; intros;\n    map_iff_solve' idtac;\n    intuition.\nQed.\n\nLemma Superset_swap_right :\n  forall {elt welt} {k1 k2 v1 v2 state map} wrapper,\n    k1 <> k2 ->\n    @Superset elt welt map ([k1 >> v1]::[k2 >> v2]::state) wrapper ->\n    @Superset elt welt map ([k2 >> v2]::[k1 >> v1]::state) wrapper.\nProof.\n  unfold Superset; intros ** k v mp.\n  destruct (StringMap.E.eq_dec k k1), (StringMap.E.eq_dec k k2);\n    subst; map_iff_solve idtac; try discriminates;\n    rewrite MapsTo_swap in mp by auto; specialize (H0 _ _ mp);\n    repeat setoid_rewrite StringMapFacts.add_mapsto_iff in H0;\n    intuition.\nQed.\n\nLemma AllADTs_swap :\n  forall {av} {state: State av} {k1 k2 v1 v2 map},\n    k1 <> k2 ->\n    @AllADTs av ([k1 >> v1]::[k2 >> v2]::state) map ->\n    @AllADTs av ([k2 >> v2]::[k1 >> v1]::state) map.\nProof.\n  unfold AllADTs; intros; split; destruct_pairs.\n  apply Superset_swap_left; trivial.\n  apply Superset_swap_right; trivial.\nQed.\n\nLemma mapM_MapsTo_1 :\n  forall av st k v,\n    st [k >> v] ->\n    mapM (@sel av st) (k :: nil) = Some (v :: nil).\nProof.\n  unfold sel; intros; simpl.\n  subst_find; reflexivity.\nQed.\n\nLemma Superset_mapsto' :\n  forall {elt welt} k v st map wrapper,\n    @Superset elt welt st map wrapper ->\n    map[k >> wrapper v] ->\n    st[k >> wrapper v].\nProof.\n  unfold Superset; intros * h ** maps_to.\n  apply (h _ _ maps_to).\nQed.\n\nLemma AllADTs_mapsto' :\n  forall {av} k v st adts,\n    @AllADTs av st adts ->\n    adts[k >> Facade.ADT v] ->\n    st[k >> Facade.ADT v].\nProof.\n  intros * (h & _) **. eauto using Superset_mapsto'. \nQed.\n\nLemma SomeSCAs_mapsto' :\n  forall {av} k v st scas,\n    @SomeSCAs av st scas ->\n    scas[k >> Facade.SCA _ v] ->\n    st[k >> Facade.SCA _ v].\nProof.\n  eauto using Superset_mapsto'.\nQed.\n\nLemma Superset_add_in_left :\n  forall {elt welt} st bindings k v wrapper,\n    bindings[k >> wrapper v] ->\n    @Superset elt welt st bindings wrapper ->\n    Superset ([k >> wrapper v]::st) bindings wrapper.\nProof.\n  unfold Superset; intros ** k' v' ? .\n  destruct (StringMap.E.eq_dec k k'); subst;\n  try match goal with (* TODO fix mapsto_unique *) \n        | H:(?st) [?k >> ?v], H':(?st) [?k >> ?v'] |- _ =>\n          let h := fresh in\n          pose proof (MapsTo_unique st k v v' H H') as h;\n            rewrite !h in *; clear H\n      end; map_iff_solve intuition.\nQed.\n\nLemma Superset_add_in_right :\n  forall {elt welt} st bindings k v wrapper,\n    st[k >> wrapper v] ->\n    @Superset elt welt st bindings wrapper ->\n    Superset st ([k >> wrapper v]::bindings) wrapper.\nProof.\n  unfold Superset; intros ** k' v' ? .\n  destruct (StringMap.E.eq_dec k k'); subst;\n  try match goal with (* TODO fix mapsto_unique *) \n        | H:(?st) [?k >> ?v], H':(?st) [?k >> ?v'] |- _ =>\n          let h := fresh in\n          pose proof (MapsTo_unique st k v v' H H') as h;\n            rewrite !h in *; clear H\n      end;\n  map_iff_solve intuition;\n  rewrite StringMapFacts.add_mapsto_iff in *; intuition;\n  match goal with\n    | H: wrapper _ = wrapper _ |- _ => rewrite H in *\n  end; intuition.\nQed.\n\nLemma AllADTs_add_in :\n  forall {av} st bindings k v,\n    bindings[k >> @Facade.ADT av v] ->\n    AllADTs st bindings ->\n    AllADTs ([k >> Facade.ADT v]::st) bindings.\nProof.\n  unfold AllADTs; split; intros;\n  destruct_pairs; eauto using Superset_add_in_left, Superset_add_in_right.\nQed.\n\n(* Specialized tactics *)\n\nLtac BoolToW_eval_helper :=\n  try match goal with\n        | [ |- true = negb ?a ] => unify a false; reflexivity\n        | [ |- false = negb ?a ] => unify a true; reflexivity\n      end.\n\nLtac inversion_facade :=\n  match goal with\n    | [ H: RunsTo _ ?p _ _ |- _ ] =>\n      match p with\n        | Skip => idtac \n        | Seq _ _ => idtac \n        | Facade.If _ _ _ => idtac\n        | Facade.While _ _ => idtac\n        | Call _ _ _ => idtac\n        | Label _ _ => idtac\n        | Assign _ _ => idtac\n        | _ => fail 1\n      end; inversion_clear' H\n  end.\n\nLtac specialize_initial_state :=\n  repeat match goal with\n           | [ H: (forall initial_state : State _,\n                     ?init_knowledge /\\\n                     SomeSCAs initial_state ?init_scas /\\\n                     AllADTs initial_state ?init_adts -> _),\n               Hknowledge: ?init_knowledge,\n               Hscas: SomeSCAs ?initial_state ?init_scas,\n               Hadts: AllADTs ?initial_state ?init_adts                   \n               |- _] => specialize (H _ (conj Hknowledge (conj Hscas Hadts)))\n         end.\n\nLtac specialize_final_state :=\n  repeat match goal with\n           | [ H: (forall final_state : State _,\n                     RunsTo ?env ?prog ?initial_state final_state -> _),\n               Hruns: RunsTo ?env ?prog ?initial_state ?final_state\n               |- _ ] => specialize (H _ Hruns)\n         end.\n\nLtac specialize_states :=\n  repeat (specialize_initial_state;\n          specialize_final_state).\n\nLtac safe_seq :=\n  constructor;\n  split; [ specialize_states; assumption | ].\n\nLtac supersets_mapsto H mapsto remove swap_remove :=\n  progress (let maps_to := fresh \"maps_to\" in\n            let superset := fresh \"superset\" in\n            pose proof mapsto as maps_to;\n            pose proof remove as superset;\n            try (apply swap_remove in superset; [ | solve [auto] ]);\n            clear_dups).\n\nLtac scas_adts_mapsto :=\n  repeat match goal with\n           | [ H: SomeSCAs ?state ([?k >sca> ?v]::?map) |- _ ] =>\n             supersets_mapsto H (SomeSCAs_mapsto H) (SomeSCAs_remove H) @SomeSCAs_swap_remove\n           | [ H: AllADTs ?state ([?k >adt> ?v]::?map) |- _ ] =>\n             supersets_mapsto H (AllADTs_mapsto H) (AllADTs_remove H) @Superset_swap_remove\n           | [ H: Superset ?state ([?k >> ?wrapper ?v]::?map) ?wrapper |- _ ] =>\n             supersets_mapsto H (Superset_mapsto _ H) (Superset_remove _ H) @Superset_swap_remove\n           | [ H: ?adts[?k >> ?v], H': AllADTs ?state ?adts |- _ ] =>\n             progress (pose proof (AllADTs_mapsto' _ _ _ _ H' H); clear_dups)\n           | [ H: ?scas[?k >> ?v], H': SomeSCAs ?state ?adts |- _ ] =>\n             progress (pose proof (SomeSCAs_mapsto' _ _ _ _ H' H); clear_dups)\n           | [ H: ?scas[?k >> ?v], H': SomeSCAs ?state ?adts |- _ ] =>\n             progress (pose proof (Superset_mapsto' _ _ _ _ H' H); clear_dups)\n         end.\n\nLtac rewrite_Eq_in_goal :=\n  match goal with\n    | [ H: StringMap.Equal _ _ |- SomeSCAs _ _ ] =>\n      rewrite H\n    | [ H: StringMap.Equal _ _ |- AllADTs _ _ ] =>\n      rewrite H\n    | [ H: StringMap.Equal _ _ |- StringMap.MapsTo _ _ _ ] =>\n      rewrite H              \n  end.\n\n(* Additional morphisms *)\n\nAdd Parametric Morphism av env :\n  (@Prog av env)\n    with signature (iff ==> StringMap.Equal ==> StringMap.Equal ==> StringMap.Equal ==> StringMap.Equal ==> refine)\n      as Prog_morphism.\n  unfold refine, Prog, ProgOk; intros;\n  inversion_by computes_to_inv;\n  constructor; intros; destruct_pairs.\n  \n  rewrite_Eq_in_all; split; intros;\n  specialize_states; intuition.\nQed.\n\nOpaque Word.natToWord.\n\n(* Compilation lemmas *)\n\nLemma compile_if_sca :\n  forall {av env}\n         (vtest: StringMap.key) {vret}\n         (test: bool)\n         init_knowledge\n         init_scas init_adts post_test_adts final_adts\n         truecase falsecase,\n    refine (@Prog av env init_knowledge\n                  init_scas ([vret >sca> if test then truecase\n                                         else falsecase] :: init_scas)\n                  init_adts final_adts)\n           (ptest  <- (@Prog av env init_knowledge\n                             init_scas ([vtest >sca> BoolToW test] :: init_scas)\n                             init_adts post_test_adts);\n            ptrue  <- (@Prog av env (init_knowledge /\\ test = true)\n                             ([vtest >sca> BoolToW test] :: init_scas) ([vret >sca>  truecase] :: init_scas)\n                             post_test_adts final_adts);\n            pfalse <- (@Prog av env (init_knowledge /\\ test = false)\n                            ([vtest >sca> BoolToW test] :: init_scas) ([vret >sca> falsecase] :: init_scas)\n                            post_test_adts final_adts);\n            ret (ptest; If vtest = 0 then pfalse else ptrue)%facade)%comp.\nProof.\n  unfold refine, Prog, ProgOk; unfold_coercions; intros.\n  inversion_by computes_to_inv; constructor;\n  split; subst; destruct_pairs.\n\n  (* Safe *)\n  constructor;\n  split;\n    [ solve [intuition] |\n      intros;\n        destruct test;\n        and_eq_refl; (* Clean up 'true = true' style conditions *) \n        [ apply SafeIfFalse | apply SafeIfTrue ];\n        specialize_states;\n        scas_adts_mapsto; (* Extract value of vtest *)\n        first [ assumption | eapply BoolToW_eval; trivial] ].\n  \n  (* RunsTo *)\n  intros;\n    repeat inversion_facade;\n    unfold is_true, is_false in *;\n    destruct test;\n    and_eq_refl;\n    specialize_states;\n    scas_adts_mapsto;\n    eapply BoolToW_eval in maps_to;\n    BoolToW_eval_helper; try (eq_transitive; congruence);\n    split; assumption.\nQed.\n\nLemma compile_if_adt :\n  forall {av env}\n         (vtest: StringMap.key) {vret}\n         (test: bool)\n         init_knowledge\n         init_scas final_scas init_adts post_test_adts\n         truecase falsecase,\n    refine (@Prog av env init_knowledge\n                  init_scas final_scas\n                  init_adts ([vret >sca> if test then truecase\n                                         else falsecase] :: init_adts))\n           (ptest  <- (@Prog av env init_knowledge\n                             init_scas ([vtest >sca> BoolToW test] :: init_scas)\n                             init_adts post_test_adts);\n            ptrue  <- (@Prog av env (init_knowledge /\\ test = true)\n                             ([vtest >sca> BoolToW test] :: init_scas) final_scas\n                             post_test_adts ([vret >sca> truecase] :: init_adts));\n            pfalse <- (@Prog av env (init_knowledge /\\ test = false)\n                            ([vtest >sca> BoolToW test] :: init_scas) final_scas\n                            post_test_adts ([vret >sca> falsecase] :: init_adts));\n            ret (ptest; If vtest = 0 then pfalse else ptrue)%facade)%comp.\nProof.\n  unfold refine, Prog, ProgOk; unfold_coercions; intros.\n  inversion_by computes_to_inv; constructor;\n  split; subst; destruct_pairs.\n\n  (* Safe *)\n  constructor;\n  split;\n    [ solve [intuition] |\n      intros;\n        destruct test;\n        and_eq_refl; (* Clean up 'true = true' style conditions *) \n        [ apply SafeIfFalse | apply SafeIfTrue ];\n        specialize_states;\n        scas_adts_mapsto; (* Extract value of vtest *)\n        first [ assumption | eapply BoolToW_eval; trivial] ].\n  \n  (* RunsTo *)\n  intros;\n    repeat inversion_facade;\n    unfold is_true, is_false in *;\n    destruct test;\n    and_eq_refl;\n    specialize_states;\n    scas_adts_mapsto;\n    eapply BoolToW_eval in maps_to;\n    BoolToW_eval_helper; try (eq_transitive; congruence);\n    split; assumption.\nQed. (* TODO: Exactly the same proof as compile_if_sca *)\n\nLemma compile_binop :\n  forall {av env},\n  forall op vret tw1 tw2,\n  forall w1 w2,\n  forall init_knowledge init_scas init_adts post_w1_adts final_adts,\n    tw1 <> tw2 ->\n    ~ StringMap.In tw1 init_scas ->\n    ~ StringMap.In tw2 init_scas ->\n    ~ StringMap.In vret final_adts ->\n    refine (@Prog av env init_knowledge\n                  init_scas ([vret >sca> IL.evalBinop op w1 w2] :: init_scas)\n                  init_adts final_adts)\n           (pw1  <- (@Prog av env init_knowledge\n                           init_scas ([tw1 >sca> w1] :: init_scas)\n                           init_adts post_w1_adts);\n            pw2  <- (@Prog av env init_knowledge\n                           ([tw1 >sca> w1] :: init_scas)\n                           ([tw2 >sca> w2] :: [tw1 >sca> w1] :: init_scas)\n                           post_w1_adts final_adts);\n            ret (pw1; pw2; Assign vret (Binop op tw1 tw2))%facade)%comp.\nProof.\n  unfold refine, Prog, ProgOk; unfold_coercions; intros.\n  inversion_by computes_to_inv; constructor;\n  split; subst; destruct_pairs.\n\n  (* Safe *)\n\n  repeat (safe_seq; intros).\n  specialize_states.\n  scas_adts_mapsto.\n\n  (*TODO: Prettier way of doing this? *)\n  assert (forall k : string,\n            List.In k (AllVariables (Binop op (Var tw1) (Var tw2))) ->\n            exists v : W, (st'0) [k >> SCA av v])\n    as temp\n    by (unfold AllVariables; simpl; intros; intuition; eexists; subst; eassumption).\n  destruct (eval_expr_some_sca (Binop op (Var tw1) (Var tw2)) st'0 temp).\n\n  econstructor; try eassumption.\n  eapply not_in_adts_not_mapsto_adt; eauto.\n\n  (* RunsTo *)\n  \n  intros;\n    repeat inversion_facade;\n    specialize_states;\n    scas_adts_mapsto;\n    unfold eval, eval_binop_m in *;\n    repeat (subst_find; simpl in *);\n    autoinj.\n\n  split;\n    rewrite_Eq_in_goal;\n    [ repeat remove_not_in;\n      apply SomeSCAs_chomp\n    | apply add_adts_pop_sca ];\n    assumption.\nQed.  \n\nLemma compile_test :\n  forall {av env},\n  forall op vret tw1 tw2,\n  forall w1 w2,\n  forall init_knowledge init_scas inter_scas final_scas init_adts post_w1_adts final_adts,\n    tw1 <> tw2 ->\n    ~ StringMap.In vret final_adts ->\n    refine (@Prog av env init_knowledge\n                  init_scas ([vret >sca> BoolToW ((IL.evalTest op) w1 w2)] :: [tw2 >sca> w2] :: [tw1 >sca> w1] :: final_scas)\n                  init_adts final_adts)\n           (pw1  <- (@Prog av env init_knowledge\n                           init_scas ([tw1 >sca> w1] :: inter_scas)\n                           init_adts post_w1_adts);\n            pw2  <- (@Prog av env init_knowledge\n                           ([tw1 >sca> w1] :: inter_scas)\n                           ([tw2 >sca> w2] :: [tw1 >sca> w1] :: final_scas)\n                           post_w1_adts final_adts);\n            ret (pw1; pw2; Assign vret (TestE op tw1 tw2))%facade)%comp.\nProof. (* Same proof as compile_binop *)\n  unfold refine, Prog, ProgOk; unfold_coercions; intros.\n  inversion_by computes_to_inv; constructor;\n  split; subst; destruct_pairs.\n\n  (* Safe *)\n\n  repeat (safe_seq; intros).\n  specialize_states.\n  scas_adts_mapsto.\n\n  (*TODO: Prettier way of doing this? *)\n  assert (forall k : string,\n            List.In k (AllVariables (TestE op (Var tw1) (Var tw2))) ->\n            exists v : W, (st'0) [k >> SCA av v])\n    as temp\n    by (unfold AllVariables; simpl; intros; intuition; eexists; subst; eassumption).\n  destruct (eval_expr_some_sca (TestE op (Var tw1) (Var tw2)) st'0 temp).\n\n  econstructor; try eassumption.\n  eapply not_in_adts_not_mapsto_adt; eauto.\n\n  (* RunsTo *)\n  \n  intros;\n    repeat inversion_facade;\n    specialize_states;\n    scas_adts_mapsto;\n    unfold eval, eval_binop_m in *;\n    repeat (subst_find; simpl in *);\n    autoinj.\n\n  split;\n    rewrite_Eq_in_goal;\n  eauto using SomeSCAs_chomp, add_adts_pop_sca.\nQed.\n\nLemma start_compiling' : \n  forall {av env} init_state vret v,\n    AllADTs init_state (StringMap.empty _) ->\n    refine (ret v) \n           (prog <- (@Prog av env True\n                           ∅ ([vret >sca> v]::∅)\n                           ∅ ∅);\n            final_state <- {final_state | RunsTo env prog init_state final_state};\n            {x | final_state[vret >> SCA av x]})%comp.\nProof.\n  unfold refine, Prog, ProgOk; intros.\n  inversion_by computes_to_inv.\n  apply eq_ret_compute.\n\n  pose proof I.\n  pose proof (SomeSCAs_empty init_state).\n  specialize_states.\n  scas_adts_mapsto.\n  auto_mapsto_unique;\n    autoinj.\nQed.\n\nLemma compile_constant :\n  forall {av env} (vret: StringMap.key),\n  forall (w: W) init_knowledge init_scas init_adts,\n    ~ StringMap.In vret init_adts -> \n    refine (@Prog av env init_knowledge\n                  init_scas ([vret >sca> w]::init_scas)\n                  init_adts init_adts)\n           (ret (Assign vret w)).\nProof.\n  unfold Prog, ProgOk, refine; unfold_coercions; intros;\n  inversion_by computes_to_inv;\n  constructor; intros;\n  subst;\n  destruct_pairs;\n  split.\n\n  (* Safe *)\n  econstructor.\n  compute; reflexivity.\n  eapply not_in_adts_not_mapsto_adt; eauto.\n\n  (* RunsTo *)\n  intros; inversion_facade.\n  split; rewrite_Eq_in_goal.\n  \n  match goal with\n    | [ H: eval _ (Const _) = Some _ |- _ ] => injection H; intros; subst\n  end; apply SomeSCAs_chomp; assumption.\n\n  apply add_adts_pop_sca; assumption.\nQed.\n\nDefinition empty_env ADTValue : Env ADTValue :=\n  {| Label2Word := fun _ => None;\n     Word2Spec := fun _ => None |}.\n\nDefinition empty_state ADTValue : State ADTValue := ∅. \n\nDefinition basic_env := {| Label2Word := fun _ => None; \n                           Word2Spec := fun w => \n                                          if Word.weqb w 0 then \n                                            Some (Axiomatic List_empty)\n                                          else if Word.weqb w 1 then \n                                            Some (Axiomatic List_pop)\n                                          else if Word.weqb w 2 then\n                                            Some (Axiomatic List_new)\n                                          else if (Word.weqb w 3) then\n                                            Some (Axiomatic List_push)\n                                          else if (Word.weqb w 4) then\n                                            Some (Axiomatic List_copy)\n                                          else if (Word.weqb w 5) then\n                                            Some (Axiomatic List_delete)\n                                          else\n                                            None |}.\n\nDefinition start_compiling_sca :=\n  fun av => @start_compiling' av (empty_env av) (empty_state av).\n\nLtac spam :=\n  solve [ unfold cond_respects_MapEq, Proper, respectful; \n          first [\n              solve [map_iff_solve ltac:(\n                       intros; try match goal with \n                                       [ H: StringMap.Equal _ _ |- _ ] => \n                                       rewrite H in * \n                                   end;\n                       intuition)]\n            | intuition; \n              first [\n                  apply StringMap.add_2; \n                  congruence\n                | idtac ] ] ].\n\nTactic Notation \"cleanup\" :=\n  first [ simplify with monad laws | spam ].\n\nTactic Notation \"cleanup_adt\" :=\n  intros;\n  try first [ simplify with monad laws \n        | spam \n        | discriminate\n        | match goal with \n            | [ |- Word2Spec ?env _ = _ ] => unfold env; simpl; intuition\n          end\n        ].\n\nLemma drop_sca :\n  forall {av env} k v\n         init_knowledge\n         init_scas final_scas\n         init_adts final_adts,\n    ~ StringMap.In k init_scas ->\n    refine (@Prog av env init_knowledge\n                  ([k >sca> v]::init_scas) final_scas\n                  init_adts final_adts)\n           (@Prog av env init_knowledge\n                  init_scas final_scas\n                  init_adts final_adts).\nProof.\n  unfold Prog, ProgOk, refine; intros.\n  inversion_by computes_to_inv.\n  constructor; intros.\n  destruct_pairs;\n    match goal with\n      | [ H: SomeSCAs _ _ |- _ ] =>\n        apply SomeSCAs_remove in H;\n          rewrite <- not_in_remove_eq in H by assumption\n    end; specialize_states; split.\n\n  (* Safe *)\n  assumption.\n\n  (* RunsTo *)\n  intros; specialize_states; split; assumption.\nQed.\n\nLtac vacuum := (* TODO: How can I force failures of discriminate  *)\n  match goal with\n    | [ |- ?a <> ?b ] => \n      first [ is_evar a | is_evar b | discriminate ]\n    | [ |- ~ StringMap.In ?k ∅ ] =>\n      solve [apply not_in_empty]\n    | [ |- ~ StringMap.In ?k ?s ] =>\n      first [ is_evar s | solve [map_iff_solve ltac:(intuition discriminate)] ]\n    | [ |- AllADTs ?m ?s ] =>\n      solve [unfold AllADTs, Superset; intros; map_iff_solve intuition]\n    | [ |- refine _ _ ] =>\n      try simplify with monad laws\n  end.\n\nGoal forall w1 w2: W, \n     exists x, \n       refine (ret (if Word.weqb w1 w2 then (IL.natToW 3) else (IL.natToW 4))) x.\nProof.\n  eexists.\n\n  setoid_rewrite (start_compiling_sca (list W) \"$ret\"); vacuum.\n  setoid_rewrite (compile_if_sca \"$cond\"); vacuum.\n\n  Lemma prepare_test :\n    forall av env vret tw1 tw2 w1 w2 knowledge scas init_adts final_adts f,\n    refine (@Prog av env knowledge\n                  scas ([vret >sca> BoolToW (f w1 w2)]::scas)\n                  init_adts final_adts)\n           (p <- (@Prog av env knowledge\n                        scas ([vret >sca> BoolToW (f w1 w2)]\n                                :: [tw2 >sca> w2] :: [tw1 >sca> w1] :: scas)\n                        init_adts final_adts);\n            cleanup <- (@Prog av env knowledge\n                              ([vret >sca> BoolToW (f w1 w2)]\n                                 :: [tw2 >sca> w2] :: [tw1 >sca> w1] :: scas)\n                              ([vret >sca> BoolToW (f w1 w2)]::scas)\n                              final_adts final_adts);\n            ret (p; cleanup)%facade)%comp.\n  Proof.\n    unfold refine, Prog, ProgOk; unfold_coercions; intros.\n    inversion_by computes_to_inv; constructor;\n    split; subst; destruct_pairs.\n\n    constructor; split; intros; specialize_states; eassumption.\n\n    intros; inversion_facade; specialize_states; intuition.\n  Qed.\n\n  rewrite prepare_test; vacuum.\n  setoid_rewrite (compile_test IL.Eq \"$cond\" \"$w1\" \"$w2\"); vacuum.\n  rewrite (compile_constant); vacuum.\n  rewrite (compile_constant); vacuum.\n  (*rewrite drop_second_sca_from_precond. etc *)\n\n(*\n  rewrite drop_sca; vacuum. (* NOTE: Could also generalize compile_constant *)\n  rewrite (compile_constant \"$ret\"); vacuum.\n\n  rewrite drop_sca; vacuum.\n  rewrite (compile_constant \"$ret\"); vacuum.\n\n  reflexivity.\n  vacuum.\n*)\nAdmitted.\n\n  (* <TODO> *)\nLemma unchanged : \n  forall av (st: State av) arg val,\n    StringMap.find arg st = Some (Facade.ADT val) -> \n    StringMap.Equal \n      st (add_remove_many (arg :: nil) (Facade.ADT val :: nil) (Some (Facade.ADT val) :: nil) st).\nProof.\n  simpl; intros.\n  red; intro arg'.\n  destruct (StringMap.E.eq_dec arg arg'); subst.\n  \n  rewrite StringMapFacts.add_eq_o; trivial.\n  rewrite StringMapFacts.add_neq_o; trivial.\nQed.  \n  \n(* TODO generalize this for is_empty as well *)\nLemma runsto_pop :\n  forall hd tl (vseq thead: StringMap.key) env (st st': State FacadeADT) ppop,\n    vseq <> thead ->\n    st [vseq >> Facade.ADT (List (hd :: tl))] ->\n    Word2Spec env ppop  = Some (Axiomatic List_pop) ->\n    RunsTo env (Call thead ppop (vseq :: nil)) st st' ->\n    StringMap.Equal st' (StringMap.add thead (Facade.SCA _ hd) (StringMap.add vseq (Facade.ADT (List tl)) st)).\nProof.\n  intros * vseq_thead vseq_init ppop_is_pop runs_to.\n\n  inversion_clear' runs_to; simpl in *; autoinj;\n  [ | congruence].\n\n  Print List_pop.\n  rewrite ppop_is_pop in *; autoinj;\n  unfold List_pop in *; clear ppop_is_pop; simpl in *;\n  autodestruct; subst;\n  rewrite StringMapFacts.find_mapsto_iff in * |- ;\n  unfold sel in *.\n\n  subst_find; simpl in *; autoinj. (* TODO Make autoinj call simpl in * first *)\n\n  destruct output; [congruence|].\n  simpl in *; autoinj.\nQed.\n\nLemma add_noop :\n  forall {A: Type} {k: StringMap.key} {v: A} {map},\n    StringMap.find k map = Some v ->\n    StringMap.Equal (StringMap.add k v map) map.\nProof.\n  unfold StringMap.Equal; intros ** k';\n  destruct (StringMap.E.eq_dec k k');\n  subst;\n  [ rewrite StringMapFacts.add_eq_o | rewrite StringMapFacts.add_neq_o ];\n  auto.\nQed.    \n\n(* TODO: refactor to share code with runsto_pop *)\nLemma runsto_is_empty :\n  forall seq (vseq tis_empty: StringMap.key) env (st st': State FacadeADT) pis_empty,\n    vseq <> tis_empty ->\n    st [vseq >> Facade.ADT (List seq)] ->\n    Word2Spec env pis_empty  = Some (Axiomatic List_empty) ->\n    RunsTo env (Call tis_empty pis_empty (vseq :: nil)) st st' ->\n    exists ret, \n      ((ret = SCAZero /\\ seq <> nil) \\/ (ret = SCAOne /\\ seq = nil)) /\\\n      StringMap.Equal st' (StringMap.add tis_empty ret st).\nProof.\n  intros * vseq_tis_empty vseq_init pis_empty_is_is_empty runs_to.\n\n  inversion_clear' runs_to; simpl in *; autoinj;\n  [ | congruence].\n\n  rewrite pis_empty_is_is_empty in *; autoinj;\n  unfold List_pop in *; clear pis_empty_is_is_empty; simpl in *;\n  autodestruct; subst;\n  rewrite StringMapFacts.find_mapsto_iff in * |-;\n                                                unfold sel in *;\n  subst_find; simpl in *; autoinj. (* TODO Make autoinj call simpl in * first *)\n\n  destruct output; [congruence|].\n  simpl in *; autoinj; simpl in *.\n  repeat autorewrite_equal.\n\n  eexists; split; eauto.\n  rewrite (add_noop vseq_init).\n  reflexivity.\nQed.\n\nLemma runsto_copy :\n  forall seq (vseq vcopy: StringMap.key) env (st st': State FacadeADT) pcopy,\n    st [vseq >> Facade.ADT (List seq)] ->\n    Word2Spec env pcopy  = Some (Axiomatic List_copy) ->\n    RunsTo env (Call vcopy pcopy (vseq :: nil)) st st' ->\n    StringMap.Equal st' (StringMap.add vcopy (Facade.ADT (List seq)) (StringMap.add vseq (Facade.ADT (List seq)) st)).\nProof.\n  intros * vseq_seq pcopy_is_copy runs_to.\n\n  inversion_clear' runs_to; simpl in *; autoinj;\n  [ | congruence].\n\n  rewrite pcopy_is_copy in *; autoinj;\n  unfold List_copy in *; clear pcopy_is_copy; simpl in *;\n  autodestruct; subst;\n  rewrite StringMapFacts.find_mapsto_iff in * |- ;\n  unfold sel in *.\n\n  subst_find; simpl in *; autoinj. (* TODO Make autoinj call simpl in * first *)\n\n  destruct output; [congruence|].\n  simpl in *; autoinj.\nQed.\n\nLemma runsto_delete :\n  forall seq (vseq vret: StringMap.key) env (st st': State FacadeADT) pdelete,\n    st [vseq >> Facade.ADT (List seq)] ->\n    Word2Spec env pdelete  = Some (Axiomatic List_delete) ->\n    RunsTo env (Call vret pdelete (vseq :: nil)) st st' ->\n    StringMap.Equal st' (StringMap.add vret SCAZero (StringMap.remove vseq st)).\nProof.\n  intros * vseq_seq pdelete_is_delete runs_to.\n\n  inversion_clear' runs_to; simpl in *; autoinj;\n  [ | congruence].\n\n  rewrite pdelete_is_delete in *; autoinj;\n  unfold List_copy in *; clear pdelete_is_delete; simpl in *;\n  autodestruct; subst;\n  rewrite StringMapFacts.find_mapsto_iff in * |- ;\n  unfold sel in *.\n\n  subst_find; simpl in *; autoinj. (* TODO Make autoinj call simpl in * first *)\n\n  destruct output; [congruence|].\n  simpl in *; autoinj.\nQed.\n\nLemma runsto_cons :\n  forall seq head (vseq vhead vdiscard: StringMap.key) env (st st': State FacadeADT) pcons,\n    st [vseq >> Facade.ADT (List seq)] ->\n    st [vhead >> Facade.SCA _ head] ->\n    Word2Spec env pcons  = Some (Axiomatic List_push) ->\n    RunsTo env (Call vdiscard pcons (vseq :: vhead :: nil)) st st' ->\n    StringMap.Equal st' (StringMap.add vdiscard (Facade.SCA _ 0) (StringMap.add vseq (Facade.ADT (List (head :: seq))) st)).\nProof.\n  intros * vseq_seq vhead_head pcons_is_cons runs_to.\n\n  inversion_clear' runs_to; simpl in *; autoinj;\n  [ | congruence].\n\n  rewrite pcons_is_cons in *; autoinj;\n  unfold List_push in *; clear pcons_is_cons; simpl in *;\n  autodestruct; subst;\n  rewrite StringMapFacts.find_mapsto_iff in * |- ;\n  unfold sel in *.\n\n  subst_find; simpl in *; autoinj. (* TODO Make autoinj call simpl in * first *)\n\n  destruct output; [congruence|].\n  destruct output; [congruence|].\n  simpl in *; autoinj.\n\n  subst_find; simpl in *; autoinj.\nQed.\n\nLemma RunsToAssignKnownValue :\n  forall {av env} {k1 k2: StringMap.key} {v} {st st': State av},\n    st[k2 >> v] ->\n    @RunsTo av env (Assign k1 k2) st st' ->\n    StringMap.Equal st' (StringMap.add k1 v st).\nProof.\n  intros * maps_to runs_to;\n  inversion_clear' runs_to;\n  simpl in *.\n  autorewrite_equal.\n  rewrite StringMapFacts.find_mapsto_iff in *.\n  rewrite maps_to in *; autoinj.\nQed.\n(* </TODO> *)\nShow.\nGoal exists x, \n       refine (ret (Word.wmult \n                      (Word.wplus  3 4)\n                      (Word.wminus 5 6))) x.\nProof.\n  eexists.\n  \n  setoid_rewrite (start_compiling_sca False \"$ret\"); vacuum.\n  setoid_rewrite (compile_binop IL.Times \"$ret\" \"$t1\" \"$t2\"); vacuum.\n  \n  setoid_rewrite (compile_binop IL.Plus  \"$t1\" \"$t11\" \"$t12\"); vacuum.\n  setoid_rewrite (compile_constant \"$t11\"); vacuum.\n  setoid_rewrite (compile_constant \"$t12\"); vacuum. \n  \n  setoid_rewrite (compile_binop IL.Minus \"$t2\" \"$t21\" \"$t22\"); vacuum.\n  \n  setoid_rewrite (compile_constant \"$t21\"); vacuum.\n  setoid_rewrite (compile_constant \"$t22\"); vacuum.\n  \n  reflexivity.\n  vacuum.\nQed.\n\nOpaque add_remove_many.\n\nDefinition SCALoopBodyProgCondition env loop compiled_loop knowledge scas adts (vseq vret thead tis_empty: StringMap.key) (acc head: W) (seq: list W) :=\n  @ProgOk _ env compiled_loop knowledge\n          ([thead >sca> head]::[tis_empty >sca> 0]::[vret >sca> acc]::scas) ([vret >sca> loop acc head]::scas)\n          ([vseq >adt> List seq]::adts) ([vseq >adt> List seq]::adts).\n          \nDefinition SCALoopBodyOk env loop compiled_loop knowledge scas adts (vseq vret thead tis_empty: StringMap.key) :=\n  forall (acc: W) (head: W) (seq: list W),\n    SCALoopBodyProgCondition env loop compiled_loop knowledge scas adts vseq\n                             vret thead tis_empty acc head seq.\n    \nLemma safe_call_1 :\n  forall {av} env state adts pointer spec varg arg vout,\n    state[varg >> arg] ->\n    Word2Spec env pointer = Some (Axiomatic spec) ->\n    AllADTs state adts -> \n    ~ StringMap.In (elt:=Value av) vout adts ->\n    PreCond spec (arg :: nil) ->\n    @Safe av env (Call vout (Const pointer) (varg :: nil)) state.\nProof.\n  intros.\n  econstructor.\n\n  repeat constructor; intuition. (* NoDup *)\n  reflexivity.\n  eassumption.\n  unfold sel; simpl; subst_find; reflexivity.\n  eapply not_in_adts_not_mapsto_adt; eassumption.\n  assumption.\nQed.\n\nLemma weqb_false :\n  forall w1 w2,\n    w1 <> w2 ->\n    IL.weqb w1 w2 = false.\nProof.\n  setoid_rewrite <- weqb_false_iff.\n  intros; assumption.\nQed.\n\nLemma eval_bool_eq_false_sca :\n  forall {av} k v1 v2 state,\n    SCA av v1 <> SCA av v2 ->\n    state[k >> SCA _ v1] ->\n    @eval_bool av state (Var k = Const v2)%facade = Some false.\nProof.\n  intros; unfold eval_bool; simpl; subst_find; simpl.\n  rewrite weqb_false by congruence; reflexivity.\nQed.\n\nLtac compile_fold_induction_is_empty_call :=\n  match goal with\n    | [ H: RunsTo _ (Call _ _ _) _ _ |- _ ] =>\n      eapply runsto_is_empty in H;\n        try eassumption;\n        [ let H1 := fresh in\n          destruct H as [ ? ([ (H & H1) | (H & H1) ] & ?) ];\n            try solve [exfalso; apply H1; reflexivity]; subst\n        | intuition .. ]\n  end.\n\nLemma weqb_refl :\n  forall sz w,\n    @Word.weqb sz w w = true.\nProof.\n  induction w.\n  \n  reflexivity.\n  destruct b; simpl; rewrite IHw; reflexivity.\nQed.\n\nLemma is_true_eq :\n  forall {av} state var w,\n    is_true state (Var var = Const w)%facade <->\n    state[var >> SCA av w].\nProof.  \n  unfold is_true, eval_bool, eval, eval_binop_m; split; intros.\n  \n  destruct (StringMap.find var state) as [ [ | ] | ] eqn:eq0;\n    try discriminate;\n    apply binop_Eq_true_iff in H;\n    rewrite StringMapFacts.find_mapsto_iff; congruence.\n\n  subst_find.\n  simpl; unfold IL.weqb; rewrite weqb_refl; reflexivity.\nQed.\n  \nLemma mapsto_eq_add :\n  forall {elt} m k (v: elt) m',\n    StringMap.Equal m ([k >> v]::m') ->\n    m[k >> v].\nProof.\n  intros; rewrite_Eq_in_goal; map_iff_solve intuition.\nQed.\n\nLtac mapsto_eq_add :=\n  match goal with\n    | [ H: StringMap.Equal _ _ |- _ ] =>\n      let H' := fresh in\n      pose proof H as H';\n        apply mapsto_eq_add in H'\n  end.\n  \nLemma Superset_replace_right :\n  forall {elt welt} k v v' state map wrapper,\n    @Superset elt welt state ([k >> v]::map) wrapper ->\n    @Superset elt welt ([k >> v']::state) ([k >> v']::map) wrapper.\nProof.\n  unfold Superset; intros ** k'' v'' maps_to.\n  destruct (StringMap.E.eq_dec k k''); subst;\n  rewrite StringMapFacts.add_mapsto_iff in *;\n  map_iff_solve idtac; [ | apply H ];\n  map_iff_solve intuition.\nQed.\n\nLemma Superset_replace_left :\n  forall {elt welt} k v v' state map wrapper,\n    @Superset elt welt ([k >> v]::state) map wrapper ->\n    @Superset elt welt ([k >> v']::state) ([k >> v']::map) wrapper.\nProof.\n  unfold Superset; intros ** k'' v'' maps_to.\n  destruct (StringMap.E.eq_dec k k''); subst;\n  rewrite StringMapFacts.add_mapsto_iff in *;\n  map_iff_solve idtac; intuition.\n  specialize (H _ _ H2);\n    rewrite StringMapFacts.add_mapsto_iff in *;\n    intuition.\nQed.\n\nLemma AllADTs_replace :\n  forall {av} k v v' state map,\n    @AllADTs av state ([k >> v]::map) ->\n    @AllADTs av ([k >> v']::state) ([k >> v']::map).\nProof.\n  unfold AllADTs; split; intros;\n  [ eapply Superset_replace_right\n  | eapply Superset_replace_left ];\n  intuition eassumption.\nQed.\n\nAdd Parametric Morphism {av k v} :\n  (StringMap.add k v)\n    with signature (@AllADTs av ==> @AllADTs av)\n      as StringMap_add_AllADTs.\nProof.\n  unfold AllADTs, Superset; intros; split; intros;\n  generalize H0; StringMapFacts.map_iff; intuition.\nQed.\n\nLtac trickle_deletion :=\n  repeat match goal with\n           | [ |- context[StringMap.remove ?k (StringMap.add ?k' ?v ?m)] ] =>\n             first [rewrite (@StringMap_remove_add_eq _ k' k) by congruence |\n                    rewrite (@StringMap_remove_add_neq _ k' k) by congruence ]\n           | [ |- context[StringMap.remove _ ∅] ] => rewrite StringMap_remove_empty\n         end.\n\nLemma AllADTs_swap_iff :\n  forall (av : Type) (state : State av) (k1 k2 : StringMap.key)\n         (v1 v2 : Value av) (map : StringMap.t (Value av)),\n    k1 <> k2 ->\n    (AllADTs ([k1 >> v1]::[k2 >> v2]::state) map <->\n     AllADTs ([k2 >> v2]::[k1 >> v1]::state) map).\nProof.\n  split; eauto using AllADTs_swap.\nQed.\n  \nAdd Parametric Relation {av} : (State av) (@AllADTs av)\n    reflexivity proved by _\n    symmetry proved by _\n    transitivity proved by _\n      as all_adts. \nProof.\n  firstorder.\n  firstorder.\n  firstorder.\nQed.\n\nLemma AllADTs_swap_left_iff :\n  forall (av : Type) (state : State av) (k1 k2 : StringMap.key)\n         (v1 v2 : Value av) (map : StringMap.t (Value av)),\n    k1 <> k2 ->\n    (AllADTs map ([k1 >> v1]::[k2 >> v2]::state) <->\n     AllADTs map ([k2 >> v2]::[k1 >> v1]::state)).\nProof.\n  split; intros; symmetry; apply AllADTs_swap; try symmetry; try congruence.\nQed.\n\nAdd Parametric Morphism av :\n  (@AllADTs av)\n    with signature (@AllADTs av ==> @AllADTs av ==> iff)\n      as AllADTs_AllADTs_morphism.\n  firstorder.\nQed.\n\nLtac loop_body_prereqs :=\n  split; [assumption|split];\n  match goal with\n    | [ H: RunsTo _ (Call _ _ _) _ _ |- _ ] =>\n      eapply runsto_pop in H; try eauto;\n      rewrite_Eq_in_goal;\n      try map_iff_solve ltac:(intuition eassumption)\n  end;\n  rewrite_Eq_in_goal;\n  [ apply Superset_swap_left; auto;\n    apply add_sca_pop_adts; map_iff_solve idtac; auto;\n    repeat apply SomeSCAs_chomp;\n    eassumption\n  | apply add_adts_pop_sca; try assumption;\n    map_iff_solve intuition;\n    apply AllADTs_swap; auto;\n    apply add_adts_pop_sca; auto;\n    map_iff_solve intuition;\n    first [ eapply AllADTs_replace;\n            eassumption\n          | match goal with\n              | [ H: AllADTs ?state ?adts |- AllADTs _ _ ] =>\n                rewrite H, AllADTs_swap_left_iff by congruence;\n                  apply AllADTs_chomp_remove;\n                  trickle_deletion;\n                  apply AllADTs_chomp;\n                  reflexivity\n            end ]\n  ].\n  \nLemma SafeEnv_inv :\n  forall {av env} {a b : Stmt} {st st' : State av},\n    RunsTo env a st st' ->\n    Safe env (Seq a b) st ->\n    Safe env b st'.\nProof.    \n  intros * h' h; inversion h. intuition.\nQed.    \n\nLemma true_and_false :\n  forall {av} st expr,\n    @is_true av st expr ->\n    @is_false av st expr ->\n    False.\nProof.\n  unfold is_true, is_false; intros.\n  eq_transitive; discriminate.\nQed.\n\nDefinition compile_fold_base_sca :\n  forall {env},\n  forall {vseq vret: StringMap.key},\n  forall {thead tis_empty: StringMap.key},\n  forall {ppop pempty},\n  forall {loop compiled_loop},\n  forall {knowledge scas adts},\n    SCALoopBodyOk env loop compiled_loop knowledge scas adts vseq vret thead tis_empty ->\n    (Word2Spec env pempty = Some (Axiomatic List_empty)) ->\n    (Word2Spec env ppop  = Some (Axiomatic List_pop)) ->\n    vret <> vseq ->\n    vret <> tis_empty ->\n    thead <> vret ->\n    thead <> vseq ->\n    tis_empty <> vseq ->\n    ~ StringMap.In thead adts ->\n    ~ StringMap.In tis_empty adts ->\n    ~ StringMap.In vseq scas ->\n    forall seq init, \n      refine (@Prog _ env knowledge\n                    ([vret >sca> init]::scas) ([tis_empty >sca> 1]::[vret >sca> List.fold_left loop seq init]::scas)\n                    ([vseq >adt> List seq]::adts) ([vseq >adt> List nil]::adts))\n             (ret (Fold thead tis_empty vseq ppop pempty compiled_loop)).\nProof.\n  unfold SCALoopBodyOk, SCALoopBodyProgCondition, Prog, ProgOk, refine; unfold_coercions;\n  induction seq as [ | a seq ]; intros;\n  [ | specialize (fun init => IHseq init _ (eq_ret_compute _ _ _ (eq_refl))) ];\n  constructor; intros; destruct_pairs;\n  split;\n  inversion_by computes_to_inv;\n  subst;\n  scas_adts_mapsto.\n \n  (** Safe **)\n  constructor.\n  split; intros.\n\n  (* Call is safe *)\n  eapply safe_call_1;\n    first [ eassumption\n          | symmetry; eassumption\n          | simpl; eexists; reflexivity\n          | map_iff_solve intuition ].\n\n  (* (Non-running) loop is safe *)\n\n  compile_fold_induction_is_empty_call.\n  eapply SafeWhileFalse.\n  eapply BoolToW_eval;\n    [ reflexivity | rewrite_Eq_in_goal; map_iff_solve intuition ].\n\n  (** RunsTo **)\n  unfold Fold; intros; do 2 inversion_facade;\n  try compile_fold_induction_is_empty_call;\n  simpl;\n  scas_adts_mapsto;\n  mapsto_eq_add;\n  try (match goal with\n         | [ H: is_true _ _ |- _ ] => apply is_true_eq in H\n       end; auto_mapsto_unique).\n\n  split; rewrite_Eq_in_goal; map_iff_solve idtac.\n  apply SomeSCAs_chomp; assumption.\n  apply add_adts_pop_sca; [ map_iff_solve intuition | assumption ].\n\n  (** Induction's safety **)\n  constructor; split.\n\n  (* Call safe *)\n  eapply safe_call_1;\n    first [ eassumption\n          | symmetry; eassumption\n          | simpl; eexists; reflexivity\n          | map_iff_solve intuition ].\n\n  (* Loop safe *)\n  intros.\n  compile_fold_induction_is_empty_call; try discriminate.\n  mapsto_eq_add.\n  \n  constructor;\n    [ unfold_coercions;\n      rewrite is_true_eq;\n      assumption | | ].\n  \n  constructor; split.\n\n  (* Pop safe *)\n  assert (st' [vseq >> Facade.ADT (List (a :: seq))]) \n    by (rewrite_Eq_in_goal; map_iff_solve intuition).\n\n  eapply safe_call_1.\n  eassumption.\n  eassumption.\n  rewrite_Eq_in_goal.\n  apply add_adts_pop_sca;\n    [ | eassumption | .. ];\n    map_iff_solve intuition.\n  map_iff_solve intuition.\n  simpl. eexists. eexists. reflexivity.\n\n  intros.\n  constructor.\n\n  (* Loop body + next statement safe *)\n\n  repeat match goal with\n           | [ H: (forall acc head seq initial_state,\n                     _ -> (forall final_state, RunsTo _ ?compiled_loop _ _ -> _))\n               |- context[RunsTo _ ?compiled_loop ?initial _] ] =>\n             specialize (fun p final => H init a seq initial p final);\n               match type of H with\n                 | ?cond -> _ => try pose cond as prereq\n               end\n         end.\n\n  assert (prereq) as prereqs; unfold prereq in *; clear prereq.\n  loop_body_prereqs.\n  \n  (* Loop body *)\n  split.\n  eauto.\n\n  (* next statement *)\n  intros.\n  repeat match goal with\n           | [ H: _ -> (forall final_state, _ -> _),\n               H': RunsTo _ compiled_loop _ _ |- _ ] => specialize (H prereqs _ H')\n         end.\n\n  scas_adts_mapsto.\n  eapply safe_call_1; try eassumption.\n  map_iff_solve congruence.\n  simpl; eexists; reflexivity.\n\n  (* Actual loop induction *)\n  intros.\n\n  do 2 inversion_facade.\n\n  repeat match goal with\n           | [ H: (forall acc head seq initial_state,\n                     _ -> (forall final_state, RunsTo _ ?compiled_loop _ _ -> _)),\n               H': RunsTo _ ?compiled_loop ?initial _ |- _ ] =>\n             specialize (fun p final => H init a seq initial p final);\n               match type of H with\n                 | ?cond -> _ => try pose cond as prereq\n               end\n         end.\n\n  assert (prereq) as prereqs; unfold prereq in *; clear prereq.\n  loop_body_prereqs.\n\n  repeat match goal with\n           | [ H: _ -> (forall final_state, _ -> _),\n               H': RunsTo _ compiled_loop _ _ |- _ ] => specialize (H prereqs _ H')\n         end.\n\n  match goal with\n    | [ H: RunsTo _ _ _ ?st |- Safe env _ ?st ] => apply (SafeEnv_inv H)\n  end.\n  specialize (IHseq (loop init a)); inversion_by computes_to_inv.\n  match goal with\n    | [ H: context[Fold] |- _ ] => unfold Fold in H; apply H\n  end.\n\n  tauto.\n\n  (* Induction case for the loop *)\n  simpl; intros.\n  specialize (IHseq (loop init a)); inversion_by computes_to_inv.\n\n  (* initial_state is at the very beginning of the loop.  We need to unfold one\n     iteration first, and then deduce the new states *)\n\n  unfold Fold in *.\n  inversion_facade.\n\n  (* TODO: This is a dupe of part of the loop_body_prereqs code *)\n  match goal with\n    | [ H: RunsTo _ (Call _ _ _) _ _ |- _ ] =>\n      eapply runsto_is_empty in H; eauto;\n      destruct H as [ret (ret_val & state_eq)];\n      destruct ret_val; destruct_pairs; try discriminate (* Remove the list empty case *)\n  end.\n\n  assert (is_true st' (tis_empty = 0)%facade) by\n      (unfold_coercions; rewrite is_true_eq;\n       rewrite_Eq_in_goal;\n       map_iff_solve intuition). (* TODO this should be a lemma *)\n\n  inversion_facade; try (exfalso; eapply true_and_false; eassumption).\n  \n  (* Unfold one loop iteration, but keep the last statement, and merge it back at the beginning of the while, to recreate the induction condition. *)\n\n  repeat match goal with\n           | [ H: RunsTo _ (Seq _ _) _ _ |- _ ] =>\n             inversion_clear' H\n         end.\n\n  (* Copied from earlier *)\n  repeat match goal with\n           | [ H: (forall acc head seq initial_state,\n                     _ -> (forall final_state, RunsTo _ ?compiled_loop _ _ -> _)),\n               H': RunsTo _ ?compiled_loop ?initial _ |- _ ] =>\n             specialize (fun p final => H init a seq initial p final);\n               match type of H with\n                 | ?cond -> _ => try pose cond as prereq\n               end\n         end.\n\n  assert (prereq) as prereqs; unfold prereq in *; clear prereq.\n  loop_body_prereqs.\n\n  repeat match goal with\n           | [ H: _ -> (forall final_state, _ -> _),\n               H': RunsTo _ compiled_loop _ _ |- _ ] => specialize (H prereqs _ H'); pose H\n         end.\n  (* </Copied> *)\n\n  (* Stick together the last statement and the body of the loop *)\n  match goal with\n    | [ Hlast: RunsTo _ _ ?initial_state ?st, Hloop: RunsTo _ (Facade.While _ _) ?st ?final_state |- _ ] =>\n      pose proof (RunsToSeq Hlast Hloop)\n  end.\n  specialize_states.\n  split; intuition.\nQed.\n\nDefinition ADTLoopBodyProgCondition env {acc_type} loop compiled_loop knowledge scas adts (vseq vret thead tis_empty: StringMap.key) (acc: acc_type) wrapper (head: W) (seq: list W) :=\n  @ProgOk _ env compiled_loop knowledge\n          ([thead >sca> head]::[tis_empty >sca> 0]::scas) (scas)\n          ([vret >adt> wrapper acc]::[vseq >adt> List seq]::adts) ([vret >adt> wrapper (loop acc head)]::[vseq >adt> List seq]::adts).\n\nDefinition ADTLoopBodyOk env {acc_type} loop compiled_loop knowledge scas adts (vseq vret thead tis_empty: StringMap.key) wrapper :=\n  forall acc (head: W) (seq: list W),\n    @ADTLoopBodyProgCondition env acc_type loop compiled_loop knowledge scas adts vseq\n                              vret thead tis_empty acc wrapper head seq.\n\nDefinition compile_fold_base_adt :\n  forall {env},\n  forall {acc_type wrapper},\n  forall {vseq vret: StringMap.key},\n  forall {thead tis_empty: StringMap.key},\n  forall {ppop pempty},\n  forall {loop compiled_loop},\n  forall {knowledge scas adts},\n    @ADTLoopBodyOk env acc_type loop compiled_loop knowledge scas adts vseq vret thead tis_empty wrapper ->\n    (Word2Spec env pempty = Some (Axiomatic List_empty)) ->\n    (Word2Spec env ppop  = Some (Axiomatic List_pop)) ->\n    vret <> vseq ->\n    vret <> tis_empty ->\n    thead <> vret ->\n    thead <> vseq ->\n    tis_empty <> vseq ->\n    ~ StringMap.In thead adts ->\n    ~ StringMap.In tis_empty adts ->\n    ~ StringMap.In vseq scas ->\n    forall seq (init: acc_type), \n      refine (@Prog _ env knowledge\n                    (scas) ([tis_empty >sca> 1]::scas)\n                    ([vret >adt> wrapper init]::[vseq >adt> List seq]::adts) ([vret >adt> wrapper (List.fold_left loop seq init)]::[vseq >adt> List nil]::adts))\n             (ret (Fold thead tis_empty vseq ppop pempty compiled_loop)).\nProof.\n  unfold ADTLoopBodyOk, ADTLoopBodyProgCondition, Prog, ProgOk, refine; unfold_coercions;\n  induction seq as [ | a seq ]; intros;\n  [ | specialize (fun init => IHseq init _ (eq_ret_compute _ _ _ (eq_refl))) ];\n  constructor; intros; destruct_pairs;\n  split;\n  inversion_by computes_to_inv;\n  subst;\n  scas_adts_mapsto.\n  \n  (** Safe **)\n  constructor.\n  split; intros.\n\n  (* Call is safe *)\n  eapply safe_call_1;\n    first [ eassumption\n          | symmetry; eassumption\n          | simpl; eexists; reflexivity\n          | map_iff_solve intuition ].\n  \n  (* (Non-running) loop is safe *)\n\n  compile_fold_induction_is_empty_call.\n  eapply SafeWhileFalse.\n  eapply BoolToW_eval;\n    [ reflexivity | rewrite_Eq_in_goal; map_iff_solve intuition ].\n\n  (** RunsTo **)\n  unfold Fold; intros; do 2 inversion_facade;\n  try compile_fold_induction_is_empty_call;\n  simpl;\n  scas_adts_mapsto;\n  mapsto_eq_add;\n  try (match goal with\n         | [ H: is_true _ _ |- _ ] => apply is_true_eq in H\n       end; auto_mapsto_unique).\n\n  split; rewrite_Eq_in_goal; map_iff_solve idtac.\n  apply SomeSCAs_chomp; assumption.\n  apply add_adts_pop_sca; [ map_iff_solve intuition | assumption ].\n\n  (** Induction's safety **)\n  constructor; split.\n\n  (* Call safe *)\n  eapply safe_call_1;\n    first [ eassumption\n          | symmetry; eassumption\n          | simpl; eexists; reflexivity\n          | map_iff_solve intuition ].\n\n  (* Loop safe *)\n  intros.\n  compile_fold_induction_is_empty_call; try discriminate.\n  mapsto_eq_add.\n  \n  constructor;\n    [ unfold_coercions;\n      rewrite is_true_eq;\n      assumption | | ].\n  \n  constructor; split.\n\n  (* Pop safe *)\n  assert (st' [vseq >> Facade.ADT (List (a :: seq))]) \n    by (rewrite_Eq_in_goal; map_iff_solve intuition).\n\n  eapply safe_call_1.\n  eassumption.\n  eassumption.\n  rewrite_Eq_in_goal.\n  apply add_adts_pop_sca;\n    [ | eassumption | .. ];\n    map_iff_solve intuition.\n  map_iff_solve intuition.\n  simpl. eexists. eexists. reflexivity.\n\n  intros.\n  constructor.\n\n  (* Loop body + next statement safe *)\n\n  repeat match goal with\n           | [ H: (forall acc head seq initial_state,\n                     _ -> (forall final_state, RunsTo _ ?compiled_loop _ _ -> _))\n               |- context[RunsTo _ ?compiled_loop ?initial _] ] =>\n             specialize (fun p final => H init a seq initial p final);\n               match type of H with\n                 | ?cond -> _ => try pose cond as prereq\n               end\n         end.\n\n  assert (prereq) as prereqs; unfold prereq in *; clear prereq.\n  loop_body_prereqs.\n  \n  (* Loop body *)\n  split.\n  eauto.\n\n  (* next statement *)\n  intros.\n  repeat match goal with\n           | [ H: _ -> (forall final_state, _ -> _),\n               H': RunsTo _ compiled_loop _ _ |- _ ] => specialize (H prereqs _ H')\n         end.\n\n  scas_adts_mapsto.\n  eapply safe_call_1; try eassumption.\n  map_iff_solve congruence.\n  simpl; eexists; reflexivity.\n\n  (* Actual loop induction *)\n  intros.\n\n  do 2 inversion_facade.\n\n  repeat match goal with\n           | [ H: (forall acc head seq initial_state,\n                     _ -> (forall final_state, RunsTo _ ?compiled_loop _ _ -> _)),\n               H': RunsTo _ ?compiled_loop ?initial _ |- _ ] =>\n             specialize (fun p final => H init a seq initial p final);\n               match type of H with\n                 | ?cond -> _ => try pose cond as prereq\n               end\n         end.\n\n  assert (prereq) as prereqs; unfold prereq in *; clear prereq.\n  loop_body_prereqs.\n\n  repeat match goal with\n           | [ H: _ -> (forall final_state, _ -> _),\n               H': RunsTo _ compiled_loop _ _ |- _ ] => specialize (H prereqs _ H')\n         end.\n\n  match goal with\n    | [ H: RunsTo _ _ _ ?st |- Safe env _ ?st ] => apply (SafeEnv_inv H)\n  end.\n  specialize (IHseq (loop init a)); inversion_by computes_to_inv.\n  match goal with\n    | [ H: context[Fold] |- _ ] => unfold Fold in H; apply H\n  end.\n\n  tauto.\n\n  (* Induction case for the loop *)\n  simpl; intros.\n  specialize (IHseq (loop init a)); inversion_by computes_to_inv.\n\n  (* initial_state is at the very beginning of the loop.  We need to unfold one\n     iteration first, and then deduce the new states *)\n\n  unfold Fold in *.\n  inversion_facade.\n\n  (* TODO: This is a dupe of part of the loop_body_prereqs code *)\n  match goal with\n    | [ H: RunsTo _ (Call _ _ _) _ _ |- _ ] =>\n      eapply runsto_is_empty in H; eauto;\n      destruct H as [ret (ret_val & state_eq)];\n      destruct ret_val; destruct_pairs; try discriminate (* Remove the list empty case *)\n  end.\n\n  assert (is_true st' (tis_empty = 0)%facade) by\n      (unfold_coercions; rewrite is_true_eq;\n       rewrite_Eq_in_goal;\n       map_iff_solve intuition). (* TODO this should be a lemma *)\n\n  inversion_facade; try (exfalso; eapply true_and_false; eassumption).\n  \n  (* Unfold one loop iteration, but keep the last statement, and merge it back at the beginning of the while, to recreate the induction condition. *)\n\n  repeat match goal with\n           | [ H: RunsTo _ (Seq _ _) _ _ |- _ ] =>\n             inversion_clear' H\n         end.\n\n  (* Copied from earlier *)\n  repeat match goal with\n           | [ H: (forall acc head seq initial_state,\n                     _ -> (forall final_state, RunsTo _ ?compiled_loop _ _ -> _)),\n               H': RunsTo _ ?compiled_loop ?initial _ |- _ ] =>\n             specialize (fun p final => H init a seq initial p final);\n               match type of H with\n                 | ?cond -> _ => try pose cond as prereq\n               end\n         end.\n\n  assert (prereq) as prereqs; unfold prereq in *; clear prereq.\n  loop_body_prereqs.\n\n  repeat match goal with\n           | [ H: _ -> (forall final_state, _ -> _),\n               H': RunsTo _ compiled_loop _ _ |- _ ] => specialize (H prereqs _ H'); pose H\n         end.\n  (* </Copied> *)\n\n  (* Stick together the last statement and the body of the loop *)\n  match goal with\n    | [ Hlast: RunsTo _ _ ?initial_state ?st, Hloop: RunsTo _ (Facade.While _ _) ?st ?final_state |- _ ] =>\n      pose proof (RunsToSeq Hlast Hloop)\n  end.\n  specialize_states.\n  split; intuition.\nQed.\n\nLemma PickComputes_inv: forall {A} (x: A) P,\n                          computes_to (Pick (fun x => P x)) x -> P x.\nProof.\n  intros; inversion_by computes_to_inv; assumption.\nQed.\n\nLemma map_add_remove_swap :\n  forall {elt} k1 k2 v m,\n    k1 <> k2 ->\n    @StringMap.Equal elt\n                     ([k1 >> v]::(StringMap.remove k2 m))\n                     (StringMap.remove k2 ([k1 >> v]::m)).\nProof.\n  intros; red; intros k3.\n  map_iff_solve idtac.\n\n  repeat (rewrite ?StringMapFacts.add_o;\n          rewrite ?StringMapFacts.remove_o).\n  destruct (StringMap.E.eq_dec k1 k3), (StringMap.E.eq_dec k2 k3);\n    subst; congruence.\nQed.\n\nLemma compile_fold_sca :\n  forall env,\n  forall vseq vret: StringMap.key,\n  forall thead tis_empty: StringMap.key,\n  forall ppop pempty,\n  forall loop,\n  forall knowledge scas adts,\n    (Word2Spec env pempty = Some (Axiomatic List_empty)) ->\n    (Word2Spec env ppop  = Some (Axiomatic List_pop)) ->\n    vret <> vseq ->\n    vret <> tis_empty ->\n    thead <> vret ->\n    thead <> vseq ->\n    tis_empty <> vseq ->\n    ~ StringMap.In thead adts ->\n    ~ StringMap.In tis_empty adts ->\n    ~ StringMap.In vseq scas ->\n    ~ StringMap.In tis_empty scas ->\n    forall seq init, \n      refine (@Prog _ env knowledge\n                    (scas) ([vret >sca> List.fold_left loop seq init]::scas)\n                    ([vseq >adt> List seq]::adts) ([vseq >adt> List nil]::adts))\n             (cloop <- { cloop | SCALoopBodyOk env loop cloop knowledge\n                                               scas adts vseq vret thead tis_empty };\n              pinit <- (@Prog _ env knowledge\n                              scas ([vret >sca> init]::scas)\n                              ([vseq >adt> List seq]::adts) ([vseq >adt> List seq]::adts));\n              ret (pinit; Fold thead tis_empty vseq ppop pempty cloop)%facade)%comp.\nProof.\n  unfold refine; intros.\n  inversion_by computes_to_inv;\n    subst;\n    constructor;\n    match goal with\n      | [ H: _ |- _ ] => apply PickComputes_inv in H; unfold ProgOk in H\n    end; unfold ProgOk in * ;\n    intros; destruct_pairs;\n    specialize_states;\n    destruct_pairs.\n\n  match goal with\n    | [ H: context[SCALoopBodyOk], H': context[Word2Spec], H'': context[Word2Spec] |- _ ] =>\n      pose proof (compile_fold_base_sca H H' H'')\n  end.\n  \n  (* TODO: Tactic for this? *)\n  repeat match goal with\n           | [ H: ?a -> _, H': ?a |- _ ] =>\n             match (type of a) with\n               | Prop => specialize (H H')\n             end\n         end.\n\n  unfold refine, Prog, ProgOk in *.\n\n  match goal with\n    | [ H: _ -> _ -> _ |- _ ] => specialize (H seq init _ (eq_ret_compute _ _ _ (eq_refl)))\n  end.\n  inversion_by computes_to_inv.\n  \n  split.\n\n  (* Safe *)\n  constructor; split; intuition.\n\n  (* RunsTo *)\n  intros; destruct_pairs.\n  inversion_facade.\n  specialize_states.\n  split; [ | intuition ].\n  \n  (* Tricks to get rid of is_empty *)\n  rewrite (not_in_remove_eq tis_empty scas); eauto.\n  rewrite map_add_remove_swap; eauto.\n  eapply SomeSCAs_remove; eauto.\nQed.\n\nLemma compile_fold_adt :\n  forall env,\n  forall acc_type wrapper,\n  forall vseq vret: StringMap.key,\n  forall thead tis_empty: StringMap.key,\n  forall ppop pempty,\n  forall loop,\n  forall knowledge scas adts,\n    (Word2Spec env pempty = Some (Axiomatic List_empty)) ->\n    (Word2Spec env ppop  = Some (Axiomatic List_pop)) ->\n    vret <> vseq ->\n    vret <> tis_empty ->\n    thead <> vret ->\n    thead <> vseq ->\n    tis_empty <> vseq ->\n    ~ StringMap.In thead adts ->\n    ~ StringMap.In tis_empty adts ->\n    ~ StringMap.In vseq scas ->\n    ~ StringMap.In tis_empty scas ->\n    forall seq init, \n      refine (@Prog _ env knowledge\n                    (scas) (scas)\n                    ([vseq >adt> List seq]::adts) ([vret >adt> wrapper (List.fold_left loop seq init)]\n                                                     ::[vseq >adt> List nil]::adts))\n             (cloop <- { cloop | @ADTLoopBodyOk env acc_type loop cloop knowledge\n                                                scas adts vseq vret thead tis_empty wrapper };\n              pinit <- (@Prog _ env knowledge\n                              scas scas\n                              ([vseq >adt> List seq]::adts) ([vret >adt> wrapper init]::[vseq >adt> List seq]::adts));\n              ret (pinit; Fold thead tis_empty vseq ppop pempty cloop)%facade)%comp.\nProof.\n  unfold refine; intros.\n  inversion_by computes_to_inv;\n    subst;\n    constructor;\n    match goal with\n      | [ H: _ |- _ ] => apply PickComputes_inv in H; unfold ProgOk in H\n    end; unfold ProgOk in * ;\n    intros; destruct_pairs;\n    specialize_states;\n    destruct_pairs.\n\n  match goal with\n    | [ H: context[ADTLoopBodyOk], H': context[Word2Spec], H'': context[Word2Spec] |- _ ] =>\n      pose proof (compile_fold_base_adt H H' H'')\n  end.\n  \n  (* TODO: Tactic for this? *)\n  repeat match goal with\n           | [ H: ?a -> _, H': ?a |- _ ] =>\n             match (type of a) with\n               | Prop => specialize (H H')\n             end\n         end.\n\n  unfold refine, Prog, ProgOk in *.\n\n  match goal with\n    | [ H: _ -> _ -> _ |- _ ] => specialize (H seq init _ (eq_ret_compute _ _ _ (eq_refl)))\n  end.\n  inversion_by computes_to_inv.\n  \n  split.\n\n  (* Safe *)\n  constructor; split; intuition.\n\n  (* RunsTo *)\n  intros; destruct_pairs.\n  inversion_facade.\n  specialize_states.\n  split; [ | intuition ].\n  \n  (* Tricks to get rid of is_empty *)\n  rewrite (not_in_remove_eq tis_empty scas); eauto.\n  (* REMOVED rewrite map_add_remove_swap; eauto. *)\n  eapply SomeSCAs_remove; eauto.\nQed.\n\nLemma mapsto_eval :\n  forall {av} scas k w,\n    (scas) [k >> SCA av w] ->\n    eval scas k = Some (SCA av w).\nProof.\n  intros; simpl.\n  subst_find; reflexivity.\nQed.\n\nLemma assign_safe :\n  forall {av} state scas adts k w,\n    @SomeSCAs av state scas ->\n    @AllADTs av state adts ->\n    scas[k >> SCA _ w] ->\n    forall k' env,\n      ~ StringMap.In k' adts ->\n      Safe env (Assign k' k) state.\nProof.      \n  intros. specialize (H _ _ H1).\n  econstructor; unfold_coercions.\n  + eauto using mapsto_eval.\n  + eauto using not_in_adts_not_mapsto_adt.\nQed.\n\nLemma copy_word :\n  forall {av env},\n  forall k1 {k2} w adts scas knowledge,\n    scas[k1 >> SCA _ w] ->\n    ~ StringMap.In k2 adts ->\n    refine (@Prog av env knowledge\n                  scas ([k2 >sca> w]::scas)\n                  adts adts)\n           (ret (Assign k2 k1)).\nProof.\n  unfold refine, Prog, ProgOk; intros; constructor; intros.\n  inversion_by computes_to_inv; subst.\n\n  split.\n\n  (* Safe *)\n  eauto using assign_safe.\n\n  (* RunsTo *) (* TODO: extract to lemma *)\n  intros; inversion_facade; split;\n  rewrite_Eq_in_goal; pose proof (H2 _ _ H). (* TODO: Put in scas_adts_mapsto *)\n  erewrite mapsto_eval in H7 by eauto; autoinj.\n  eauto using SomeSCAs_chomp.\n  eauto using add_adts_pop_sca.\nQed.\n\nLemma no_op :\n  forall {av env},\n  forall adts scas knowledge,\n    refine (@Prog av env knowledge\n                  scas scas\n                  adts adts)\n           (ret Skip).\nProof.\n  unfold refine, Prog, ProgOk; constructor; intros.\n  inversion_by computes_to_inv; subst.\n  split; [ constructor | intros; inversion_facade; intuition ].\nQed.\n\nLemma pull_forall :\n  forall {A B C D} (f: D -> A -> B -> C -> Prop) b,\n    (forall (x1: A) (x2: B) (x3: C),\n       refine { p | f p x1 x2 x3 }%facade\n              b) ->\n    refine { p | forall x1 x2 x3,\n                       f p x1 x2 x3 }%facade\n           b.\nProof.\n  unfold refine; intros; econstructor; intros.\n  generalize (H x1 x2 x3 _ H0); intros.\n  inversion_by computes_to_inv.\n  assumption.\nQed.\n\nLemma pull_forall_loop_sca :\n  forall env b loop knowledge\n         scas adts vseq vret thead tis_empty,\n    (forall head acc seq,\n       refine  { cloop | SCALoopBodyProgCondition env loop cloop knowledge\n                                                  scas adts vseq vret thead tis_empty\n                                                  head acc seq } b) ->\n    refine { cloop | SCALoopBodyOk env loop cloop knowledge\n                                   scas adts vseq vret thead tis_empty }%facade b.\nProof.\n  eauto using pull_forall.\nQed.\n\nLemma pull_forall_loop_adt :\n  forall  acc_type wrapper env b loop knowledge\n         scas adts vseq vret thead tis_empty,\n    (forall head acc seq,\n       refine  { cloop | @ADTLoopBodyProgCondition env acc_type loop cloop knowledge\n                                                   scas adts vseq vret thead tis_empty\n                                                   acc wrapper head seq } b) ->\n    refine { cloop | @ADTLoopBodyOk env acc_type loop cloop knowledge\n                                    scas adts vseq vret thead tis_empty wrapper }%facade b.\nProof.\n  eauto using pull_forall.\nQed.\n\nLemma start_compiling_sca_with_precondition : (* TODO: Supersedes start_compiling *) \n  forall {av env} init_state scas adts vret v,\n    SomeSCAs init_state scas ->\n    AllADTs init_state adts ->\n    refine (ret v) \n           (prog <- (@Prog av env True\n                           scas ([vret >sca> v]::∅)\n                           adts ∅);\n            final_state <- {final_state | RunsTo env prog init_state final_state};\n            {x | final_state[vret >> SCA av x]})%comp.\nProof.\n  unfold refine, Prog, ProgOk; intros.\n  inversion_by computes_to_inv.\n  pose proof I.\n  specialize_states;\n  scas_adts_mapsto;\n  auto_mapsto_unique;\n  autoinj.\nQed.\n\nLemma start_compiling_adt_with_precondition : (* TODO: Supersedes start_compiling *) \n  forall {av env} init_state scas adts vret ret_type (v: ret_type) wrapper,\n    (forall x y, wrapper x = wrapper y -> x = y) ->\n    SomeSCAs init_state scas ->\n    AllADTs init_state adts ->\n    refine (ret v) \n           (prog <- (@Prog av env True\n                           scas (∅)\n                           adts ([vret >adt> wrapper v]::∅));\n            final_state <- {final_state | RunsTo env prog init_state final_state};\n            {x | final_state[vret >> Facade.ADT (wrapper x)]})%comp.\nProof.\n  unfold refine, Prog, ProgOk; intros.\n  inversion_by computes_to_inv.\n  pose proof I.\n  specialize_states;\n  scas_adts_mapsto;\n  auto_mapsto_unique;\n  autoinj;\n  eauto using eq_ret_compute.\nQed.\n\nLemma SomeSCAs_mapsto_inv:\n  forall {av} state scas k v,\n    state[k >> SCA av v] ->\n    SomeSCAs state scas ->\n    SomeSCAs state ([k >sca> v]::scas).\nProof.\n  unfold SomeSCAs, Superset; intros * ? * some_scas ** k' v' maps_to.\n  destruct (StringMap.E.eq_dec k k'); rewrite StringMapFacts.add_mapsto_iff in *;\n  subst; intuition; autoinj.\nQed.\n\nLemma add_scas_in_postcond :\n  forall {av env} scas adts adts' vret v,\n    refine (@Prog av env True\n                  scas ([vret >sca> v]::∅)\n                  adts adts')\n           (@Prog av env True\n                  scas ([vret >sca> v]::scas)\n                  adts adts').\nProof.\n  unfold refine, Prog, ProgOk; intros.\n  inversion_by computes_to_inv.\n  constructor; intros; destruct_pairs;\n  split; intros; specialize_states.\n  + intuition.\n  + split; scas_adts_mapsto;\n    eauto using SomeSCAs_mapsto_inv, SomeSCAs_empty.\nQed.\n\n\n(*\nDefinition AllKnown {elt1 elt2} vars scas adts :=\n  forall k, List.In k vars -> @StringMap.In elt1 k scas \\/\n                              @StringMap.In elt2 k adts.\n\nLemma AllKnown_find :\n  forall {av} state scas adts,\n    SomeSCAs state scas ->\n    AllADTs state adts ->\n    forall k,\n    (StringMap.In (elt:=Value av) k scas \\/\n     StringMap.In (elt:=Value av) k adts) ->\n    StringMapFacts.M.In (elt:=Value av) k state.\nProof.\n  intros.\n  destruct k.\n\n *)\n(*\nLemma AllKnown_find :\n  forall {av} state scas adts vars,\n    SomeSCAs state scas ->\n    AllADTs state adts ->\n    AllKnown vars scas adts ->\n    forall k,\n      List.In k vars ->\n      exists (v: Value av), StringMap.find k state = Some v.\nProof.\n  induction vars; intros.\n  exfalso; eauto using in_nil.\n  apply in_inv in H2; destruct H2.\n  + subst. specialize (H1 k (in_eq _ _)). \n    setoid_rewrite <- StringMapFacts.find_mapsto_iff.\n    apply StringMapFacts.In_MapsTo.\n  \nLemma AllKnown_mapM :\n  forall {av} state scas adts args,\n    SomeSCAs state scas ->\n    AllADTs state adts ->\n    AllKnown args scas adts ->\n    exists args',\n      mapM (@sel av state) args = Some args'.\nProof.\n  induction args; intros ** all_known; simpl.\n  + eexists; reflexivity.\n  + unfold sel; specialize (all_known a (in_eq _ _)).\n  induction \n *)\n\n(*\nLemma RunsToCallByName :\n  forall {av env},\n  forall scas adts knowledge,\n  forall vret vpointer label args args' v w spec,\n    Label2Word env label = Some w ->\n    Word2Spec env w = Some (Axiomatic spec) ->\n    ~ StringMap.In vpointer adts ->\n    ~ StringMap.In vret adts ->\n    (forall st,\n       SomeSCAs (st) ([vpointer >sca> w]::scas) ->\n       AllADTs st adts ->\n       mapM (sel st) args = Some args') ->\n    PreCond spec args' ->\n    NoDup args ->\n    refine (@Prog av env knowledge\n                  scas ([vret >sca> v]::scas)\n                  adts adts)\n           (ret (Label vpointer label;\n                 Call vret (Var vpointer) args)%facade).\nProof.\n  unfold refine, Prog, ProgOk; intros;\n  inversion_by computes_to_inv;\n  subst; constructor; split; intros;\n  destruct_pairs.\n\n  (* Safe *)\n  + repeat (constructor; intros).\n    - econstructor; eauto using not_in_adts_not_mapsto_adt.\n    - inversion_facade; mapsto_eq_add;\n      eq_transitive; autoinj;\n      econstructor; eauto 2 using mapsto_eval.\n      apply H3; rewrite_Eq_in_goal; eauto using SomeSCAs_chomp, add_adts_pop_sca.\n      eapply not_in_adts_not_mapsto_adt; try eassumption.\n      rewrite_Eq_in_goal; apply add_adts_pop_sca; eauto.\n\n  (* RunsTo *)\n  + repeat inversion_facade.\n*)\n\nLemma RunsTo_label :\n  forall av env st1 st2 vpointer label w,\n    Label2Word env label = Some w ->\n    @RunsTo av env (Label vpointer label) st1 st2 ->\n    StringMap.Equal st2 ([vpointer >sca> w]::st1).\nProof.\n  intros.\n  inversion_facade.\n  eq_transitive; autoinj.\nQed.\n\nLemma runsto_new :\n  forall env st1 st2 w vpointer vret,\n    Word2Spec env w = Some (Axiomatic List_new) ->\n    st1[vpointer >> SCA _ w] ->\n    RunsTo env (Call vret (Var vpointer) nil) st1 st2 ->\n    StringMap.Equal st2 ([vret >adt> List nil]::st1).\nProof.\n  intros;\n  inversion_facade;\n  simpl in *;\n  autoinj;\n  auto_mapsto_unique;\n  autoinj; eq_transitive; autoinj; simpl in *;\n  match goal with\n    | [ H: 0 = List.length _ |- _ ] => rewrite length_0 in H\n  end; destruct_pairs; subst;\n  [assumption|discriminate].\nQed.                       \n\nLemma runsto_delete' :\n  forall seq (vseq vret: StringMap.key) env (st st': State FacadeADT) vpointer w,\n    st [vseq >> Facade.ADT (List seq)] ->\n    st [vpointer >> Facade.SCA _ w] ->\n    Word2Spec env w = Some (Axiomatic List_delete) ->\n    RunsTo env (Call vret vpointer (vseq :: nil)) st st' ->\n    StringMap.Equal st' (StringMap.add vret SCAZero (StringMap.remove vseq st)).\nProof.\n  intros;\n  inversion_facade;\n  simpl in *;\n  autoinj;\n  auto_mapsto_unique;\n  autoinj; eq_transitive; autoinj; simpl in *;\n  autodestruct; autoinj; subst;\n  unfold sel in *;\n  subst_find; simpl in *; autoinj;\n  try discriminate;\n  destruct output; [congruence|];\n  destruct output; autoinj.\nQed.\n\nLemma runsto_copy_var :\n  forall seq (vseq vcopy: StringMap.key) env (st st': State FacadeADT) pcopy vpointer,\n    st[vpointer >> SCA _ pcopy] ->\n    st[vseq >> Facade.ADT (List seq)] ->\n    Word2Spec env pcopy  = Some (Axiomatic List_copy) ->\n    RunsTo env (Call vcopy (Var vpointer) (vseq :: nil)) st st' ->\n    StringMap.Equal st' ([vcopy >adt> List seq]::[vseq >adt> List seq]::st).\nProof.\n  intros;\n  inversion_facade;\n  simpl in *;\n  autoinj; rewrite <- StringMapFacts.find_mapsto_iff in *;  (* TODO: Extend auto_mapsto_unique *)\n    auto_mapsto_unique; intros; autoinj; eq_transitive; autoinj; simpl in *.\n\n  autodestruct; subst. simpl in *.\n  destruct output; try discriminate.\n  destruct output; try discriminate.\n  autoinj.\n\n  unfold sel in *.\n  simpl in H16.\n  \n  subst_find; simpl in *. autoinj.\n  discriminate.\nQed.\n\nLemma runsto_cons_var :\n  forall seq head (vseq vhead vdiscard: StringMap.key) env (st st': State FacadeADT) pcons vpointer,\n    st[vpointer >> SCA _ pcons] ->\n    st [vseq >> Facade.ADT (List seq)] ->\n    st [vhead >> Facade.SCA _ head] ->\n    Word2Spec env pcons = Some (Axiomatic List_push) ->\n    RunsTo env (Call vdiscard (Var vpointer) (vseq :: vhead :: nil)) st st' ->\n    StringMap.Equal st' (StringMap.add vdiscard (Facade.SCA _ 0) (StringMap.add vseq (Facade.ADT (List (head :: seq))) st)).\nProof.\n  intros;\n  inversion_facade;\n  simpl in *;\n  autoinj; rewrite <- StringMapFacts.find_mapsto_iff in *;  (* TODO: Extend auto_mapsto_unique *)\n    auto_mapsto_unique; intros; autoinj; eq_transitive; autoinj; simpl in *.\n\n  autodestruct; subst. simpl in *.\n  destruct output; try discriminate.\n  destruct output; try discriminate.\n  autoinj.\n\n  unfold sel in *.\n  simpl in *.\n  \n  repeat (subst_find; simpl in *; autoinj).\n  discriminate.\nQed.\n\n(* TODO remove runsto_* variants that deal with static pointers, except for folds *)\n\nLemma compile_new :\n  forall {env},\n  forall scas adts knowledge,\n  forall vret vpointer label w,\n    Label2Word env label = Some w ->\n    Word2Spec env w = Some (Axiomatic List_new) ->\n    ~ StringMap.In vpointer adts ->\n    ~ StringMap.In vret adts ->\n    ~ StringMap.In vret scas ->\n    vpointer <> vret ->\n    refine (@Prog _ env knowledge\n                  scas ([vpointer >sca> w]::scas)\n                  adts ([vret >adt> List nil]::adts))\n           (ret (Label vpointer label;\n                 Call vret (Var vpointer) nil)%facade).\nProof.\n  unfold refine, Prog, ProgOk; intros;\n  inversion_by computes_to_inv;\n  subst; constructor; split; intros;\n  destruct_pairs.\n\n  (* Safe *)\n  + repeat (constructor; intros).\n    - econstructor; eauto 2 using not_in_adts_not_mapsto_adt.\n    - inversion_facade; mapsto_eq_add; (* TODO *)\n      eq_transitive; autoinj;\n      econstructor; eauto 2 using mapsto_eval.\n      constructor. reflexivity.\n      eapply not_in_adts_not_mapsto_adt.\n      rewrite_Eq_in_goal; eauto using add_adts_pop_sca.\n      assumption.\n      reflexivity.\n\n  (* RunsTo *)\n  + inversion_facade.\n    eapply RunsTo_label in H11; eauto.\n\n    mapsto_eq_add.\n    eapply runsto_new in H14; eauto.\n    split; repeat rewrite_Eq_in_goal.\n    \n    apply add_sca_pop_adts, SomeSCAs_chomp; trivial;\n    rewrite StringMapFacts.F.add_neq_in_iff; assumption.\n\n    apply AllADTs_chomp, add_adts_pop_sca; trivial;\n    rewrite StringMapFacts.F.add_neq_in_iff; assumption.\nQed.\n\n(*\n\nLemma compile_load_pointer :\n  forall {av env}\n         vpointer w label\n         knowledge init_scas final_scas init_adts final_adts,\n    Label2Word env label = Some w ->\n    ~ StringMap.In vpointer init_adts ->\n    refine (@Prog av env knowledge\n                  init_scas final_scas\n                  init_adts final_adts)\n           (p <- (@Prog _ env knowledge\n                        ([vpointer >sca> w]::init_scas) ([vpointer >sca> w]::final_scas)\n                        (init_adts) (final_adts));\n            ret (Label vpointer label; p)%facade)%comp.\nProof.\n  unfold refine, Prog, ProgOk; intros;\n  inversion_by computes_to_inv;\n  subst; constructor; split; intros;\n  destruct_pairs.\n\n  + repeat (constructor; intros).\n    - econstructor; eauto using not_in_adts_not_mapsto_adt.\n    - eapply RunsTo_label in H7; eauto.\n      setoid_rewrite H7.\n      specialize_states. inversion_facade; mapsto_eq_add; (* TODO *)\n*)\n\nDefinition LabelAndCall vpointer vret label args := (Label vpointer label;\n                                                     Call vret (Var vpointer) args)%facade.\n\n(* TODO: Replace mapsto_eq_add *)\nLtac mapsto_eq_add' :=\n  repeat match goal with\n           | H:StringMap.Equal _ _ |- _ =>\n             let H' := fresh in\n             progress (pose proof H as H'; apply mapsto_eq_add in H'; clear_dups)\n         end.\n\nLemma mapM_not_in_args :\n  forall {av} (st st': State av) args input k w,\n    ~ List.In k args ->\n    StringMap.Equal st' ([k >sca> w]::st) ->\n    mapM (sel st) args = Some input ->\n    mapM (sel st') args = Some input.\nProof.\n  induction args; simpl in *; intros.\n  + congruence.\n  + destruct (sel st a) eqn:eq1;\n    destruct (mapM (sel st) args) eqn:eq2;\n    try discriminate.\n    erewrite IHargs; eauto.\n    replace (sel st' a) with (sel st a).\n    rewrite eq1; assumption.\n\n    unfold sel; rewrite H0.\n    symmetry; apply StringMapFacts.add_neq_o; intuition.\nQed.\n\nLemma add_add_add :\n  forall {elt} st k v,\n    @StringMap.Equal elt\n                     ([k >> v]::[k >> v]::st)\n                     ([k >> v]::st).\nProof.\n  intros; unfold StringMap.Equal;\n  intros k'; destruct (StringMap.E.eq_dec k k'); subst.\n  repeat rewrite StringMapFacts.add_eq_o; reflexivity.\n  repeat rewrite StringMapFacts.add_neq_o; congruence.\nQed.\n\n(*\nLemma RunsToLabelAndCall :\n  forall ADTValue env,\n  forall (vpointer vret : StringMap.key) (lbl : GLabel.glabel)\n         st st' adts,\n  forall (f : Expr)\n         (args : list StringMap.key)\n         (spec : AxiomaticSpec ADTValue)\n         (input : list (Value ADTValue))\n         (output : list (option ADTValue)) \n         (ret : Value ADTValue) (f_w : W),\n    ~ List.In vpointer args ->\n    Label2Word env lbl = Some f_w ->\n    not_mapsto_adt vpointer st = true ->\n    StringMapFacts.M.Equal st' ([vpointer >> SCA ADTValue f_w]::st) ->\n    NoDup args ->\n    eval st f = Some (SCA ADTValue f_w) ->\n    Word2Spec env f_w = Some (Axiomatic spec) ->\n    mapM (sel st) args = Some input ->\n    AllADTs st adts ->\n    ~ StringMap.In vret adts ->\n    ~ StringMap.In vpointer adts ->\n    PreCond spec input ->\n    Datatypes.length input = Datatypes.length output ->\n    PostCond spec (combine input output) ret ->\n    let st' :=\n        add_remove_many args input (wrap_output output) st in\n    let st'0 := [vret >> ret]::st' in\n    forall st'' : StringMapFacts.M.t (Value ADTValue),\n      StringMapFacts.M.Equal st'' st'0 ->\n      RunsTo env (LabelAndCall vpointer vret lbl args) st st''.\nProof.\n  intros.\n  unfold LabelAndCall; econstructor;\n  expand; mapsto_eq_add'.\n  econstructor; eauto.\n  econstructor; eauto using mapsto_eval, mapM_not_in_args. \n  eapply not_in_adts_not_mapsto_adt; eauto.\n  rewrite_Eq_in_goal.\n  apply add_adts_pop_sca; eauto.\n\n  Transparent add_remove_many.\n\n    Lemma add_remove_many_eq :\n    forall {av} (st st': State av) k v args input output,\n      ~ List.In k args ->\n      StringMapFacts.M.Equal st' ([k >> v]::st) ->\n      StringMap.Equal\n        ([k >> v]::add_remove_many args input (wrap_output output) st)\n        ([k >> v]::add_remove_many args input (wrap_output output) st').\n  Proof.\n    induction args; simpl; intros.\n    rewrite H0; symmetry; apply add_add_add.\n    destruct input; [rewrite H0; symmetry; apply add_add_add | ].\n  \n  unfold not_mapsto_adt, is_mapsto_adt in *.\n  rewrite \n *)\n \nLemma compile_copy :\n  forall {env},\n  forall scas adts knowledge seq,\n  forall vret vfrom vpointer label w,\n    Label2Word env label = Some w ->\n    Word2Spec env w = Some (Axiomatic List_copy) ->\n    ~ StringMap.In vpointer adts ->\n    ~ StringMap.In vret adts ->\n    ~ StringMap.In vret scas ->\n    ~ StringMap.In vfrom scas ->\n    vpointer <> vret ->\n    vpointer <> vfrom ->\n    adts[vfrom >> Facade.ADT (List seq)] ->\n    refine (@Prog _ env knowledge\n                  scas ([vpointer >sca> w]::scas)\n                  adts ([vret >adt> List seq]::adts))\n           (ret (Label vpointer label;\n                 Call vret (Var vpointer) (vfrom :: nil))%facade).\nProof.\n  unfold refine, Prog, ProgOk; intros;\n  inversion_by computes_to_inv;\n  subst; constructor; split; intros;\n  destruct_pairs.\n\n  (* Safe *)\n  + repeat (constructor; intros).\n    - econstructor; eauto 2 using not_in_adts_not_mapsto_adt.\n    - inversion_facade; mapsto_eq_add; (* TODO *)\n      eq_transitive; autoinj;\n      econstructor; eauto 2 using mapsto_eval.\n      repeat (constructor; eauto).\n\n      scas_adts_mapsto.\n      \n      apply mapM_MapsTo_1; eauto.\n      rewrite_Eq_in_goal.\n      map_iff_solve idtac.      \n      eassumption.\n\n      eapply not_in_adts_not_mapsto_adt.\n      rewrite_Eq_in_goal; eauto using add_adts_pop_sca.\n      assumption.\n      simpl; eexists; reflexivity.      \n      \n  (* RunsTo *)\n  + inversion_facade.\n    eapply RunsTo_label in H14; eauto.\n\n    mapsto_eq_add.\n\n    eapply runsto_copy_var in H17; eauto.\n    split; repeat rewrite_Eq_in_goal.\n    \n    repeat (apply add_sca_pop_adts; [rewrite StringMapFacts.F.add_neq_in_iff; eassumption | ]).\n    apply SomeSCAs_chomp; trivial.\n    \n    apply AllADTs_chomp, AllADTs_swap, add_adts_pop_sca; trivial.\n    apply AllADTs_add_in; assumption.\n    rewrite_Eq_in_goal; map_iff_solve idtac.\n    scas_adts_mapsto; assumption.\nQed.\n\nLemma NoDup_0 :\n  forall {A},\n    NoDup (@nil A).\nProof.\n  intros; constructor.\nQed.\n\nLemma NoDup_1 :\n  forall {A} (a: A),\n    NoDup (a :: nil).\nProof.\n  intros; constructor; eauto using NoDup_0. \nQed.\n\nLemma NoDup_2 :\n  forall {A} (a b: A),\n    a <> b -> NoDup (a :: b :: nil).\nProof.\n  intros; constructor; eauto using NoDup_1. simpl; intuition.\nQed.\n\nLemma mapM_MapsTo_2 :\n  forall (av : Type) (st : StringMap.t (Value av)) \n         (k k' : StringMap.key) (v v' : Value av),\n    (st) [k >> v] ->\n    (st) [k' >> v'] ->\n    mapM (sel st) (k :: k' :: nil) = Some (v :: v' :: nil).\nProof.\n  intros; unfold sel; simpl.\n  repeat subst_find; reflexivity.\nQed.\n\n    \nAdd Parametric Morphism {av k} :\n  (StringMap.remove k)\n    with signature (@AllADTs av ==> @AllADTs av)\n      as StringMap_remove_AllADTs.\nProof.\n  unfold AllADTs, Superset; intros; split; intros;\n  generalize H0; StringMapFacts.map_iff; intuition.\nQed.\n\nLemma compile_push :\n  forall {env},\n  forall vseq vhead vpointer vdiscard label w,\n  forall scas adts knowledge head seq,\n    Label2Word env label = Some w ->\n    Word2Spec env w = Some (Axiomatic List_push) ->\n    ~ StringMap.In vpointer adts ->\n    ~ StringMap.In vdiscard adts ->\n    ~ StringMap.In vseq scas ->\n    vpointer <> vseq ->\n    vpointer <> vhead ->\n    vhead <> vseq ->\n    vseq <> vdiscard ->\n    scas[vhead >> Facade.SCA _ head] ->\n    refine (@Prog _ env knowledge\n                  scas ([vdiscard >sca> 0]::[vpointer >sca> w]::scas)\n                  ([vseq >adt> List seq]::adts) ([vseq >adt> List (head :: seq)]::adts))\n           (ret (Label vpointer label;\n                 Call vdiscard (Var vpointer) (vseq :: vhead :: nil))%facade).\nProof.\n  unfold refine, Prog, ProgOk; intros;\n  inversion_by computes_to_inv;\n  subst; constructor; split; intros;\n  destruct_pairs.\n\n  (* Safe *)\n  + repeat (constructor; intros).\n    - econstructor; [ | eapply not_in_adts_not_mapsto_adt ]; try eassumption; map_iff_solve intuition.\n    - inversion_facade; mapsto_eq_add; (* TODO this line above should also work in other similar theorems *)\n      eq_transitive; autoinj;\n      econstructor; eauto 2 using mapsto_eval.\n\n      eauto using NoDup_0, NoDup_1, NoDup_2. (* TO COPY *)\n\n      scas_adts_mapsto.\n\n      try apply mapM_MapsTo_1; (* TODO: this, too, should work in other proofs *)\n        try apply mapM_MapsTo_2;\n        eauto;\n        rewrite_Eq_in_goal;\n        map_iff_solve idtac;\n        eassumption.\n\n      eapply not_in_adts_not_mapsto_adt;\n        [ rewrite_Eq_in_goal; apply add_adts_pop_sca; [ | eassumption ] | ];\n        map_iff_solve intuition.\n      \n      simpl; eexists; try eexists. reflexivity.      \n      \n  (* RunsTo *)\n  + inversion_facade.\n    eapply RunsTo_label in H15; eauto.\n\n    mapsto_eq_add.\n\n    \n    eapply runsto_cons_var in H18; eauto.\n    split; repeat rewrite_Eq_in_goal.\n\n    repeat (first [ apply SomeSCAs_chomp\n                  | apply add_sca_pop_adts; [rewrite StringMapFacts.F.add_neq_in_iff; eassumption | ] ]);\n      trivial.\n    \n    apply add_adts_pop_sca; map_iff_solve trivial.\n    apply AllADTs_chomp_remove.\n\n    rewrite H12.\n    trickle_deletion.\n    apply add_adts_pop_sca. map_iff_solve intuition.\n    reflexivity.\n\n    rewrite_Eq_in_goal; map_iff_solve idtac.\n    scas_adts_mapsto; assumption.\n\n    rewrite_Eq_in_goal; map_iff_solve idtac.\n    scas_adts_mapsto; assumption.\nQed.\n\nDefinition ProgEquiv {av} p1 p2 := \n  forall env st1 st2,\n    (@RunsTo av env p1 st1 st2 <-> RunsTo env p2 st1 st2). \n\nRequire Import Setoid.\n\nAdd Parametric Relation {av} : (Stmt) (@ProgEquiv av)\n    reflexivity proved by _\n    symmetry proved by _\n    transitivity proved by _\n      as prog_equiv. \nProof.\n  firstorder.\n  firstorder.\n  unfold Transitive, ProgEquiv; intros; etransitivity; eauto.\nQed.\n\nShow.\n\n(* Uh? *)\nunfold Transitive, ProgEquiv; intros; etransitivity; eauto.\n\nAdd Parametric Morphism {av: Type} :\n  (@RunsTo av)\n    with signature (eq ==> @ProgEquiv av ==> eq ==> eq ==> iff)\n      as runsto_morphism.\nProof.\n  unfold ProgEquiv; intros * prog_equiv ** ; apply prog_equiv; assumption.\nQed.\n\nAdd Parametric Morphism {av} :\n  (Seq)\n    with signature (@ProgEquiv av ==> @ProgEquiv av ==> @ProgEquiv av)\n      as seq_morphism.\nProof.  \n  unfold ProgEquiv; intros.\n\n  split; intro runs_to; inversion_clear' runs_to; econstructor; [\n    rewrite <- H | rewrite <- H0 |\n    rewrite -> H | rewrite -> H0 ];\n  eauto; reflexivity.\nQed.\n\nLemma while_morph {av env} :\n  forall while_p1,\n  forall (st1 st2: State av),\n    RunsTo env (while_p1) st1 st2 ->\n    forall p1 p2 test,\n      while_p1 = Facade.While test p1 -> \n      @ProgEquiv av p1 p2 ->\n      RunsTo env (Facade.While test p2) st1 st2.\nProof.\n  unfold ProgEquiv; induction 1; intros ** equiv; subst; try discriminate; autoinj.\n\n  econstructor; eauto; rewrite <- equiv; assumption.\n  constructor; trivial.\nQed.  \n  \nAdd Parametric Morphism {av} :\n  (Facade.While)\n    with signature (eq ==> @ProgEquiv av ==> @ProgEquiv av)\n      as while_morphism.\nProof.  \n  split; intros; eapply while_morph; eauto; symmetry; assumption.\nQed.\n\nAdd Parametric Morphism {av} :\n  (Facade.If)\n    with signature (eq ==> @ProgEquiv av ==> @ProgEquiv av ==> @ProgEquiv av)\n      as if_morphism.\nProof.  \n  unfold ProgEquiv; intros * true_equiv * false_equiv ** .\n  split; intro runs_to; inversion_clear' runs_to;\n  [ constructor 3 | constructor 4 | constructor 3 | constructor 4];\n  rewrite ?true_equiv, ?false_equiv in *; try assumption.\nQed.\n  \nLemma Skip_Seq av :\n  forall prog, \n    @ProgEquiv av (Seq Skip prog) prog. \nProof.\n  unfold ProgEquiv; split; intros.\n  inversion_clear' H; inversion_clear' H2; eauto.\n  repeat (econstructor; eauto).\nQed.\n\nLemma Seq_Skip av :\n  forall prog, \n    @ProgEquiv av (Seq prog Skip) prog.\nProof.\n  unfold ProgEquiv; split; intros.\n  inversion_clear' H; inversion_clear' H5; eauto.\n  repeat (econstructor; eauto).\nQed.\n\nLemma Superset_not_In_remove :\n  forall {elt welt} k state map wrapper,\n    ~ StringMap.In k map ->\n    @Superset elt welt state map wrapper ->\n    @Superset elt welt (StringMap.remove k state) map wrapper.\nProof.\n  unfold Superset; intros ** k' v' maps_to.\n  destruct (StringMap.E.eq_dec k k'); subst.\n  \n  pose proof (StringMapFacts.MapsTo_In maps_to); exfalso; intuition.\n  map_iff_solve intuition.\nQed.\n\nLemma SomeSCAs_not_In_remove :\n  forall {av} k state map,\n    ~ StringMap.In k map ->\n    @SomeSCAs av state map ->\n    @SomeSCAs av (StringMap.remove k state) map.\nProof.\n  intros *; apply Superset_not_In_remove.\nQed.\n\nLemma Superset_remove_self :\n  forall {elt welt} k state wrapper,\n    @Superset elt welt state (StringMap.remove k state) wrapper.\nProof.\n  unfold Superset; intros *; map_iff_solve intuition.\nQed.\n\nLemma AllADTs_not_In_remove_left :\n  forall {av} k state map,\n    ~ StringMap.In k map ->\n    @AllADTs av state map ->\n    @AllADTs av (StringMap.remove k state) map.\nProof.\n  unfold AllADTs; split; intros; destruct_pairs.\n\n  apply  Superset_not_In_remove; intuition.\n  eapply Superset_transitive; try eassumption.\n  eauto using Superset_remove_self.\nQed.\n\nLemma AllADTs_not_In_remove_right :\n  forall {av} k state map,\n    ~ StringMap.In k map ->\n    @AllADTs av map state ->\n    @AllADTs av map (StringMap.remove k state).\nProof.\n  symmetry. apply AllADTs_not_In_remove_left; trivial; symmetry; assumption.\nQed.\n\nLemma AllADTs_chomp_remove' :\n  forall {av} k state map,\n    @AllADTs av map state ->\n    @AllADTs av (StringMap.remove k map) (StringMap.remove k state).\nProof.\n  unfold AllADTs, Superset; split; intros *; map_iff_solve intuition.\nQed.\n\nLemma compile_list_delete :\n  forall env label w vpointer vret vseq seq knowledge scas adts adts',\n    Label2Word env label = Some w ->\n    Word2Spec env w = Some (Axiomatic List_delete) ->\n    ~ StringMap.In vpointer adts ->\n    ~ StringMap.In vret adts ->\n    ~ StringMap.In vseq scas ->\n    vpointer <> vseq ->\n    adts[vseq >> Facade.ADT (List seq)] ->\n    StringMap.Equal adts' (StringMap.remove vseq adts) ->\n    refine (@Prog _ env knowledge\n                  scas ([vret >sca> 0]::[vpointer >> SCA FacadeADT w]::scas)\n                  adts adts')\n           (ret (Label vpointer label;\n                 Call vret (Var vpointer) (vseq :: nil)))%facade.\nProof.\n  unfold refine, Prog, ProgOk; intros;\n  inversion_by computes_to_inv;\n  subst; constructor; split; intros;\n  destruct_pairs.\n\n  (* Safe *)\n  + repeat (constructor; intros).\n    - econstructor; eauto 2 using not_in_adts_not_mapsto_adt.\n    - inversion_facade; mapsto_eq_add; (* TODO *)\n      eq_transitive; autoinj;\n      econstructor; eauto 2 using mapsto_eval.\n      repeat (constructor; eauto).\n\n      scas_adts_mapsto.\n      \n      apply mapM_MapsTo_1; eauto.\n      rewrite_Eq_in_goal.\n      map_iff_solve idtac.      \n      eassumption.\n\n      eapply not_in_adts_not_mapsto_adt.\n      rewrite_Eq_in_goal; eauto using add_adts_pop_sca.\n      assumption.\n      simpl; eexists; reflexivity.      \n      \n    (* RunsTo *)\n  + inversion_facade.\n    eapply RunsTo_label in H13; eauto.\n\n    mapsto_eq_add.\n\n    eapply runsto_delete' in H16; eauto.\n    split; repeat rewrite_Eq_in_goal.\n\n    repeat (apply SomeSCAs_chomp; trivial; trickle_deletion).\n\n    apply SomeSCAs_not_In_remove; trivial.\n    trickle_deletion.\n    repeat (apply add_adts_pop_sca; [ map_iff_solve intuition | ]).\n    apply AllADTs_chomp_remove'; intuition.\n\n    scas_adts_mapsto.\n    rewrite_Eq_in_goal; map_iff_solve ltac:(intuition eassumption).\nQed.\n\nLemma compile_add_intermediate_adts :\n  forall av env knowledge init_scas final_scas init_adts inter_adts final_adts,\n    refine (@Prog av env knowledge\n                  init_scas final_scas\n                  init_adts final_adts)\n           (p <- (@Prog av env knowledge\n                        init_scas final_scas\n                        init_adts inter_adts);\n            q <- (@Prog av env knowledge\n                        final_scas final_scas\n                        inter_adts final_adts);\n            ret (Seq p q))%comp.\nProof.\n  unfold refine, Prog, ProgOk; intros.\n  inversion_by computes_to_inv; subst.\n  constructor; intros; destruct_pairs.\n\n  split; intros.\n\n  (* Safe *)\n  constructor; split; intros; specialize_states; assumption.\n\n  (* RunsTo *)\n  inversion_facade; specialize_states; intuition.\nQed.\n\nLemma compile_add_intermediate_adts_with_ret :\n  forall av env knowledge k v init_scas final_scas init_adts inter_adts final_adts,\n    refine (@Prog av env knowledge\n                  init_scas final_scas\n                  init_adts ([k >adt> v]::final_adts))\n           (p <- (@Prog av env knowledge\n                        init_scas final_scas\n                        init_adts ([k >adt> v]::inter_adts));\n            q <- (@Prog av env knowledge\n                        final_scas final_scas\n                        ([k >adt> v]::inter_adts) ([k >adt> v]::final_adts));\n            ret (Seq p q))%comp.\nProof.\n  unfold refine, Prog, ProgOk; intros.\n  inversion_by computes_to_inv; subst.\n  constructor; intros; destruct_pairs.\n\n  split; intros.\n\n  (* Safe *)\n  constructor; split; intros; specialize_states; assumption.\n\n  (* RunsTo *)\n  inversion_facade; specialize_states; intuition.\nQed.\n\nLemma compile_add_intermediate_scas_with_ret :\n  forall av env knowledge k v init_scas inter_scas final_scas init_adts final_adts,\n    refine (@Prog av env knowledge\n                  init_scas ([k >sca> v]::final_scas)\n                  init_adts final_adts)\n           (p <- (@Prog av env knowledge\n                        init_scas ([k >sca> v]::inter_scas)\n                        init_adts final_adts);\n            q <- (@Prog av env knowledge\n                        ([k >sca> v]::inter_scas) ([k >sca> v]::final_scas)\n                        final_adts final_adts);\n            ret (Seq p q))%comp.\nProof.\n  unfold refine, Prog, ProgOk; intros.\n  inversion_by computes_to_inv; subst.\n  constructor; intros; destruct_pairs.\n\n  split; intros.\n\n  (* Safe *)\n  constructor; split; intros; specialize_states; try assumption.\n  \n  (* RunsTo *)\n  inversion_facade; specialize_states; intuition.\nQed.\n\nLemma compile_add_intermediate_scas :\n  forall av env knowledge init_scas inter_scas final_scas init_adts final_adts,\n    refine (@Prog av env knowledge\n                  init_scas final_scas\n                  init_adts final_adts)\n           (p <- (@Prog av env knowledge\n                        init_scas inter_scas\n                        init_adts final_adts);\n            q <- (@Prog av env knowledge\n                        inter_scas final_scas\n                        final_adts final_adts);\n            ret (Seq p q))%comp.\nProof.\n  unfold refine, Prog, ProgOk; intros.\n  inversion_by computes_to_inv; subst.\n  constructor; intros; destruct_pairs.\n\n  split; intros.\n\n  (* Safe *)\n  constructor; split; intros; specialize_states; try assumption.\n  \n  (* RunsTo *)\n  inversion_facade; specialize_states; intuition.\nQed.\n\nTransparent Word.natToWord.\n\nLemma drop_scas_from_precond : (* TODO: Convert this to a morphism *)\n  forall {av env} scas scas' scas'' adts adts',\n    SomeSCAs scas scas'' ->\n    refine (@Prog av env True\n                  scas scas'\n                  adts adts')\n           (@Prog av env True\n                  scas'' scas'\n                  adts adts').\nProof.\n  unfold refine, Prog, ProgOk; intros.\n  inversion_by computes_to_inv; subst.\n  constructor; intros; destruct_pairs.\n\n  assert (SomeSCAs initial_state scas'') by\n      eauto using SomeSCAs_transitive.\n\n  split; intros; specialize_states; intuition.\nQed.\n\nLemma drop_second_sca_from_precond :\n  forall {av env} scas scas' adts adts' k v k' v',\n    refine (@Prog av env True\n                  ([k >sca> v]::[k' >sca> v']::scas) scas'\n                  adts adts')\n           (@Prog av env True\n                  ([k >sca> v]::(StringMap.remove k' scas)) scas'\n                  adts adts').\nProof.\n  intros;\n  eauto using drop_scas_from_precond, SomeSCAs_chomp, SomeSCAs_remove, SomeSCAs_reflexive.\nQed.\n\nLtac map_iff_solve_evar' fallback :=\n  repeat setoid_rewrite not_or;\n  match goal with\n    | |- ?A /\\ ?B => split; map_iff_solve_evar' fallback\n    | |- ?a = ?ev /\\ ?b = ?b \\/ ?a <> ?ev /\\ _ =>\n      is_evar ev; left; split; [ apply eq_refl | reflexivity ]\n    | |- ?a = ?a /\\ _ \\/ ?a <> ?a /\\ _ =>\n      left; split; [ apply eq_refl | map_iff_solve_evar' fallback ]\n    | |- ?a = ?b /\\ _ \\/ ?a <> ?b /\\ _ =>\n      right; split; [ | map_iff_solve_evar' fallback ]; congruence\n    | _ => fallback\n  end.\n\nLtac map_iff_solve_evar fallback :=\n  StringMapFacts.map_iff; map_iff_solve_evar' fallback.\n\n(* TODO extend vacuum *)\nLtac vacuum' :=\n  first [\n      progress (unfold SCALoopBodyProgCondition; intros) |\n      match goal with\n        | [ |- ?m[?k >> ?v] ] => solve [map_iff_solve_evar intuition]\n        | [ |- SomeSCAs _ ∅ ] => apply SomeSCAs_empty\n        | [ |- SomeSCAs _ _ ] => eassumption\n        | [ |- AllADTs _ _ ] => eassumption\n        | [ |- Word2Spec ?env _ = Some (Axiomatic _) ] => reflexivity\n        | [ |- Label2Word ?env _ = Some _ ] => reflexivity\n        | [ |- ?a <> ?b ] => first [ is_evar a | is_evar b | discriminate ]\n        | [ |- StringMap.Equal ?a ?b ] => first [ is_evar a | is_evar b | trickle_deletion; reflexivity ]\n        | _ => vacuum\n      end ].\n\nDefinition start_sca state vret adts :=\n  (@start_compiling_sca_with_precondition _ basic_env state ∅ adts vret).\n\nGoal forall seq: list W, \n     forall state,\n       AllADTs state ([\"$list\" >adt> List seq]::∅) ->\n       exists x, \n         refine (ret (fold_left (fun (sum item: W) => Word.wplus item sum) seq 0)) x.\nProof.\n  intros; eexists.\n  setoid_rewrite (start_sca state \"$ret\"); vacuum'.\n\n  setoid_rewrite compile_add_intermediate_adts; vacuum'.\n  setoid_rewrite (compile_fold_sca basic_env \"$list\" \"$ret\" \"$head\" \"$is_empty\" 1 0); vacuum'.\n  setoid_rewrite (pull_forall_loop_sca); try vacuum'. \n\n  Focus 2.\n  setoid_rewrite compile_add_intermediate_scas_with_ret.\n  setoid_rewrite (compile_binop IL.Plus \"$ret\" \"$head'\" \"$ret'\"); vacuum'.\n  rewrite copy_word; vacuum'.\n  rewrite copy_word; vacuum'.\n\n  rewrite drop_second_sca_from_precond; trickle_deletion.\n  rewrite drop_second_sca_from_precond; trickle_deletion.\n  rewrite drop_second_sca_from_precond; trickle_deletion.\n  rewrite no_op; vacuum.\n  reflexivity.\n\n  rewrite compile_constant; vacuum.\n  rewrite compile_add_intermediate_scas; vacuum'.\n  rewrite (@compile_list_delete basic_env (\"\", \"List_delete\") 5 \"$pointer\" \"$discard\");\n    try vacuum'; cbv beta; try vacuum'; trickle_deletion. (* TODO: Find way to get rid of the cbv. *)\n  rewrite drop_sca; vacuum'; trickle_deletion.\n  rewrite drop_sca; vacuum'; trickle_deletion.\n  rewrite no_op; vacuum'.\n  reflexivity.\n\n  admit.\nQed.\n\nDefinition start_adt state vret {ret_type v} wrapper wrapper_inj adts :=\n  (@start_compiling_adt_with_precondition _ basic_env state ∅ adts vret ret_type v wrapper wrapper_inj).\n\nLemma List_inj' : forall x y : list W, List x = List y -> x = y.\n  intros * _eq; injection _eq; intros; assumption.\nQed.\n\nLemma compile_if_adt' :\n  forall {av env}\n         (vtest: StringMap.key) {vret}\n         (test: bool)\n         init_knowledge\n         init_scas final_scas init_adts post_test_adts final_adts\n         ret_type (truecase falsecase: ret_type) wrapper,\n    refine (@Prog av env init_knowledge\n                  init_scas final_scas\n                  init_adts ([vret >adt> wrapper (if test then truecase\n                                                  else falsecase)] :: final_adts))\n           (ptest  <- (@Prog av env init_knowledge\n                             init_scas ([vtest >sca> BoolToW test] :: init_scas)\n                             init_adts post_test_adts);\n            ptrue  <- (@Prog av env (init_knowledge /\\ test = true)\n                             ([vtest >sca> BoolToW test] :: init_scas) final_scas\n                             post_test_adts ([vret >adt> wrapper truecase] :: final_adts));\n            pfalse <- (@Prog av env (init_knowledge /\\ test = false)\n                            ([vtest >sca> BoolToW test] :: init_scas) final_scas\n                            post_test_adts ([vret >adt> wrapper falsecase] :: final_adts));\n            ret (ptest; If vtest = 0 then pfalse else ptrue)%facade)%comp.\nProof.\n  unfold refine, Prog, ProgOk; unfold_coercions; intros.\n  inversion_by computes_to_inv; constructor;\n  split; subst; destruct_pairs.\n\n  (* Safe *)\n  constructor;\n  split;\n    [ solve [intuition] |\n      intros;\n        destruct test;\n        and_eq_refl; (* Clean up 'true = true' style conditions *) \n        [ apply SafeIfFalse | apply SafeIfTrue ];\n        specialize_states;\n        scas_adts_mapsto; (* Extract value of vtest *)\n        first [ assumption | eapply BoolToW_eval; trivial] ].\n  \n  (* RunsTo *)\n  intros;\n    repeat inversion_facade;\n    unfold is_true, is_false in *;\n    destruct test;\n    and_eq_refl;\n    specialize_states;\n    scas_adts_mapsto;\n    eapply BoolToW_eval in maps_to;\n    BoolToW_eval_helper; try (eq_transitive; congruence);\n    split; try assumption.\nQed. (* TODO: Exactly the same proof as compile_if_sca *)\n\nLemma MapsTo_swap_Eq :\n  forall {elt} k1 v1 k2 v2 map,\n    k1 <> k2 ->\n    @StringMap.Equal elt\n                     ([k1 >> v1]::[k2 >> v2]::map)\n                     ([k2 >> v2]::[k1 >> v1]::map).\nProof.\n  intros; apply StringMapFacts.Equal_mapsto_iff.\n  eauto using MapsTo_swap.\nQed.\n\nLemma compile_pre_push :\n  forall {env},\n  forall vseq vhead,\n  forall init_scas inter_scas final_scas init_adts inter_adts final_adts knowledge head seq,\n    vhead <> vseq ->\n    refine (@Prog _ env knowledge\n                  init_scas final_scas\n                  init_adts ([vseq >adt> List (head :: seq)] :: final_adts))\n           (phead <- (@Prog _ env knowledge\n                            init_scas ([vhead >sca> head]::init_scas)\n                            init_adts init_adts);\n            ptail <- (@Prog _ env knowledge\n                            ([vhead >sca> head]::init_scas) ([vhead >sca> head]::init_scas)\n                            init_adts ([vseq >adt> List seq]::inter_adts));\n            ppush <- (@Prog _ env knowledge\n                            ([vhead >sca> head]::init_scas) inter_scas\n                            ([vseq >adt> List seq]::inter_adts)\n                            ([vseq >adt> List (head :: seq)]::final_adts));\n            pclean <- (@Prog _ env knowledge\n                            inter_scas final_scas\n                            ([vseq >adt> List (head :: seq)]::final_adts)\n                            ([vseq >adt> List (head :: seq)]::final_adts));\n            ret (phead; ptail; ppush; pclean)%facade)%comp.\nProof.\n  unfold refine, Prog, ProgOk; unfold_coercions; intros.\n  inversion_by computes_to_inv; constructor;\n  split; subst; destruct_pairs.\n\n  (* Safe *)\n  repeat (constructor; split; intros);\n  specialize_states;\n  try assumption.\n  \n  (* RunsTo *)\n  intros;\n    repeat inversion_facade;\n    specialize_states;\n    intuition.\nQed.\n\nLemma add_add_add' :\n  forall {elt} st k v v',\n    @StringMap.Equal elt\n                     ([k >> v]::[k >> v']::st)\n                     ([k >> v]::st).\nProof.\n  intros; unfold StringMap.Equal;\n  intros k'; destruct (StringMap.E.eq_dec k k'); subst.\n  repeat rewrite StringMapFacts.add_eq_o; reflexivity.\n  repeat rewrite StringMapFacts.add_neq_o; congruence.\nQed.\n\nGoal forall seq: list W, \n     forall state,\n       AllADTs state ([\"$list\" >adt> List seq]::∅) ->\n       exists x, \n         refine\n           (ret (fold_left\n                   (fun (acc: list W) (item: W) =>\n                      if IL.wltb 0 item then\n                        Word.wmult item 2 :: acc\n                      else\n                        acc)\n                   seq nil)) x.\nProof.\n  intros; eexists.\n  \n  (* Start compiling, copying the state_precond precondition to the resulting\n     program's preconditions. Result is stored into [$ret] *)\n  rewrite (start_adt state \"$ret\" List List_inj'); vacuum'.\n\n  (* Compile the fold, reading the initial value of the accumulator from\n     [$init], the input data from [$seq], and storing temporary variables in\n     [$head] and [$is_empty]. *)\n  setoid_rewrite compile_add_intermediate_adts_with_ret; vacuum'.\n  setoid_rewrite (compile_fold_adt _ _ _ \"$list\" \"$ret\" \"$head\" \"$is_empty\" 1 0); try vacuum'.\n  \n  (* Extract the quantifiers, and move the loop body to a second goal *)\n  rewrite (pull_forall_loop_adt); vacuum'.\n  \n  (* The output list is allocated by calling List_new, whose axiomatic\n     specification is stored at address 2 *)\n  setoid_rewrite compile_add_intermediate_scas; vacuum'.\n  setoid_rewrite (compile_new _ _ _ \"$ret\" \"new()\" (\"??\", \"List_new\") 2); try vacuum'.\n  rewrite drop_scas_from_precond; try vacuum'.\n  rewrite no_op; try vacuum'.\n  \n  rewrite (@compile_list_delete basic_env (\"\", \"List_delete\") 5 \"$pointer\" \"$discard\" \"$list\");\n    try vacuum'; cbv beta; try vacuum'; trickle_deletion. (* TODO: Find way to get rid of the cbv. *)\n  rewrite drop_scas_from_precond; try vacuum'.\n  rewrite no_op; vacuum'.\n\n  Focus 2. vacuum'.\n  Focus 2. admit.\n  Focus 2. vacuum'.\n  Focus 2. admit.\n  Focus 2.\n  \n  (* We're now ready to proceed with the loop's body! *)\n  unfold ADTLoopBodyProgCondition.\n  \n  (* Compile the if test *)\n  setoid_rewrite compile_add_intermediate_scas.\n  rewrite (compile_if_adt' \"$cond\"); vacuum'.\n\n  (* Extract the comparison to use Facade's comparison operators, storing the\n     operands in [$0] and [$head], and the result of the comparison in\n     [$cond] *)\n  rewrite (compile_test IL.Lt \"$cond\" \"$0\" \"$head'\"); vacuum'. (* TODO: Overriding in test? *)\n\n  (* The two operands of [<] are easily refined *)\n  rewrite (compile_constant); vacuum'.\n  rewrite (copy_word); vacuum'.\n\n  (* Now for the true part of the if: append the value to the list *)\n\n  (* Delegate the cons-ing to an ADT operation specified axiomatically; [3]\n     points to [List_push] in the current environment; we pick [$new_head] as\n     the place to temporarily store the new head *)\n  setoid_rewrite (compile_pre_push \"$ret\" \"$head'\"); vacuum'.\n\n  (* TODO unify cons/push terminology *)\n  \n  (* The head needs to be multiplied by two before being pushed into the output\n     list. *)\n  setoid_rewrite (compile_binop IL.Times _ \"$head'\" \"$2\"); vacuum'.\n  rewrite (copy_word \"$head\"); vacuum'.\n  rewrite (compile_constant); vacuum'.\n  rewrite no_op; vacuum'.\n  \n  rewrite (compile_push \"$ret\" \"$head'\" \"$push()\" \"$discard\" (\"List\", \"Push\") 3); try vacuum'.\n\n  (* Cleanup behind compile_push *)\n  do 3 (rewrite drop_sca; vacuum').\n  rewrite no_op; vacuum'.\n  \n  (* The false part is a lot simpler *)\n  rewrite no_op; vacuum'.\n\n  (* Leftover from generalizing before the if *)\n  repeat (rewrite drop_sca; vacuum').\n  rewrite no_op; vacuum'.\n  \n  (* Ok, this loop body looks good :) *)\n  reflexivity.\n\n  admit.\n  vacuum'.\n  unfold Fold.\n  repeat setoid_rewrite Seq_Skip.\n  repeat setoid_rewrite Skip_Seq.\n  \n  (* Yay, a program! *)\n  reflexivity.\nQed.\n\nDefinition max seq :=\n  fold_left\n    (fun (max: W) (item: W) =>\n       if (IL.wltb max item) then\n         item\n       else\n         max) seq 0.\n\nDefinition min seq :=\n  fold_left\n    (fun (min: W) (item: W) =>\n       if (IL.wltb item min) then\n         item\n       else\n         min) seq 0.\n\nGoal forall seq: list W, \n     forall state,\n       state[\"$list\" >> Facade.ADT (List seq)] ->\n       exists x, \n         refine\n           (ret (Word.wminus (max seq) (min seq))) x.\nProof.\n  intros * state_precond; eexists. \n\n  rewrite (start_compiling_sca_with_precondition \"$ret\" state_precond).\n  unfold min, max;\n    setoid_rewrite (compile_binop IL.Minus \"$ret\" \"$max\" \"$min\"); cleanup_adt.\n\n  rewrite (compile_fold_sca \"$init\" \"$seq\" \"$head\" \"$is_empty\" 1 0); cleanup_adt.\n  rewrite (pull_forall (fun cond => cond_indep cond \"$max\")); cleanup_adt.\n  rewrite (compile_constant); cleanup_adt.\n  rewrite (compile_copy 4 \"$list\"); cleanup_adt.\n\n  rewrite (compile_fold_sca \"$init\" \"$seq\" \"$head\" \"$is_empty\" 1 0); cleanup_adt.\n  rewrite (pull_forall (fun cond => cond_indep cond \"$min\")); cleanup_adt.\n  rewrite (compile_constant); cleanup_adt.\n  rewrite (compile_copy 4 \"$list\"); cleanup_adt.\n\n  Focus 2.\n  \n  rewrite (compile_if \"$cond\").  \n  rewrite (compile_test IL.Lt \"$cond\" \"$head\" \"$min\"); cleanup_adt.\n  rewrite (no_op); cleanup_adt.\n  rewrite (no_op); cleanup_adt.\n  rewrite (copy_word \"$head\"); cleanup_adt.\n  rewrite (no_op); cleanup_adt.\n  reflexivity.\n\n  Focus 2.\n\n  rewrite (compile_if \"$cond\").  \n  rewrite (compile_test IL.Lt \"$cond\" \"$max\" \"$head\"); cleanup_adt.\n  rewrite (no_op); cleanup_adt.\n  rewrite (no_op); cleanup_adt.\n  rewrite (copy_word \"$head\"); cleanup_adt.\n  rewrite (no_op); cleanup_adt.\n  reflexivity.\n\n  repeat setoid_rewrite Skip_Seq.\n  reflexivity.\nQed.\n\n(* TODO: Multiple Facade ADTs vs single cito ADT *)\n\n(* TODO: Sigma types *)\n\n(* TODO: Coercions to get rid of explicit \"'\" operator. Look at constants being used *)\n\n(* TODO: Use function names *)\n\n  (*\n  (* TODO: Cleanup should remove redundant clauses from expressions. Otherwise copying $ret to $ret doesn't work. *)\nsetoid_rewrite (copy_variable \"$ret\" \"$ret\"); cleanup_adt. (* TODO Replace by no-op *)\nsetoid_rewrite (copy_variable \"$head\" \"$head\"); cleanup_adt. (* TODO Replace by no-op *)\nreflexivity.\n   *)\n\n(* TODO: Three different approaches: \n         * <> precond and postcond, but forall x, precond x -> postcond (add blah x); \n         * Same pre/post cond, with extra conditions (see compile_fold et al.)\n         * <> precond and postcond, and postcond indep of modified var (see compile_cons) *)\n(* TODO: Post-conditions should include the beginning state, too *)  \n\n(* TODO: Replace all instances of \n       precond st1 /\\ blah st1 -> RunsTo -> postcond st2 /\\ bluh st2\n   by\n       precond st1 -> RunsTo -> postcond st2\n   with additional constraints `precond st1 -> blah st1` and `postcond st2 -> bluh st2` *)\n\n(* TODO: Tweak autorewrite_equal to make it faster *)\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/examples/SafeFiatToFacade.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.2800132833408956}}
{"text": "(* Alternate verification of main.c using user_specs, the normal\nmalloc/free specs without resource tracking.  \nBy contrast, verif_main.c uses the resource-tracking specs,\nwhich is needed as of Feb 2020 to prove (in link_main.v) correctness\nof the linked program, owing to limitations of the linking tactics.\n*)\n\nRequire Import VST.floyd.proofauto.\nRequire Import linking.\nRequire Import malloc.\nRequire Import main.\nRequire Import malloc_lemmas.\nRequire Import spec_malloc.\nRequire Import spec_main.\n\nDefinition Gprog : funspecs := spec_main.specs ++ user_specs.\n\nDefinition Vprog : varspecs. mk_varspecs linked_prog. Defined. \n\nLemma body_main_alt: semax_body Vprog Gprog f_main main_spec.\nProof.\nstart_function.\nsep_apply (create_mem_mgr gv); auto.\nforward_call(100,gv). (* t1 = malloc(100) *)\nrep_omega.\nIntros p.\nif_tac.\n+ (* p = nullval *)\n subst p.\n forward_call (100,nullval,gv).  (* free (p); *)\n entailer!.\n forward. (* return *)\n+\n forward_call (100,p,gv).  (* free (p); *)\n rewrite if_false by auto. cancel.\n forward. (* return *)\nQed.\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_main_alt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.28001326762724993}}
{"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\nRequire Export Sequent.\nRequire Export NaturalDeduction.\n\nSet Implicit Arguments.\n\n\n(* these definitions will help us to prove that natural deduction is equivalent \nto gentzen calculus *)\n\nDefinition replaceGentzen :\n  forall (Atoms: Set)(Gamma Gamma' Delta Delta' : Term Atoms) \n  (E : gentzen_extension),\n  replace Gamma Gamma' Delta Delta' ->\n  gentzenSequent E Delta' (deltaTranslation Delta) ->\n  gentzenSequent E Gamma' (deltaTranslation Gamma).\n simple induction 1.\n auto.\n intros.\n simpl in |- *.\n apply RightDot; auto.\n apply axiomeGeneralisation.\n intros.\n simpl in |- *.\n apply RightDot.\n apply axiomeGeneralisation.\n auto.\nDefined.\n\nDefinition replaceGentzen' :\n  forall (Atoms:Set)(Gamma Gamma' Delta Delta' : Term Atoms) \n (C : Form Atoms) (E : gentzen_extension),\n  replace Gamma Gamma' Delta Delta' ->\n  gentzenSequent E Delta' (deltaTranslation Delta) ->\n  gentzenSequent E Gamma C -> gentzenSequent E Gamma' C.\n intros.\n apply CutRuleSimpl with (deltaTranslation Gamma).\n eapply replaceGentzen; eauto.\n apply TermToForm.\n assumption.\nDefined.                                             \n\nDefinition replaceNatDed :\n  forall (Atoms:Set) (Gamma Gamma' Delta Delta' : Term Atoms)\n  (E : gentzen_extension),\n  replace Gamma Gamma' Delta Delta' ->\n  natDed E Delta' (deltaTranslation Delta) ->\n  natDed E Gamma' (deltaTranslation Gamma). \n simple induction 1.\n intros.\n assumption.\n intros.\n simpl in |- *.\n apply DotIntro.\n auto.\n apply axiomGen.\n intros.\n simpl in |- *.\n apply DotIntro.\n apply axiomGen.\n exact (H0 H1).\nDefined.\n\nSection cutNaturalDeduction.\n\nDefinition condCutExt (X : gentzen_extension) :=\n  forall (Atoms:Set)(T T1 T2 T3 : Term Atoms) (A : Form Atoms),\n  X _ T1 T2 ->\n  replace T2 T (OneForm A) T3 ->\n  sigS\n    (fun T' : Term Atoms => (X _ T' T * replace T1 T' (OneForm A) T3)%type).\n       \n\n\nDefinition conditionOKNLP : condCutExt NLP_Sequent.\n unfold condCutExt .\n intros Atoms T T1 T2 T3 A H.\n elim H.\n intros Delta1 Delta2 H0.\n elim (replace_inv2 H0); clear H0; intro H0; elim H0;\n clear H0; intros x H0; elim H0; clear H0; intros H0 H1.\n split with (Comma Delta1 x).\n split.\n rewrite H1.\n constructor 1.\n apply replaceRight; auto.\n split with (Comma x Delta2).\n split.\n rewrite H1.\n constructor 1.\n apply replaceLeft; auto.\nDefined.\n\nDefinition conditionOKL : condCutExt L_Sequent.\n unfold condCutExt in |- *.\n intros Atoms T T1 T2 T3 A H.\n elim H.\n intros Delta1 Delta2 Delta3 H0.\n elim (replace_inv2 H0); clear H0; intro H0; elim H0; clear H0;\n intros x H0; elim H0; clear H0; intros H0 H1.\n elim (replace_inv2 H0); clear H0; intro H0; elim H0; clear H0; intros x0 H0;\n elim H0; clear H0; intros H0 H2.\n split with (Comma x0 (Comma Delta2 Delta3)).\n split.\n rewrite H1.\n rewrite H2.\n constructor 1.\n apply replaceLeft.\n auto.\n split with (Comma Delta1 (Comma x0 Delta3)).\n split.\n rewrite H1.\n rewrite H2.\n constructor 1.\n apply replaceRight.\n apply replaceLeft; auto.\n split with (Comma Delta1 (Comma Delta2 x)).\n split.\n rewrite H1.\n constructor 1.\n apply replaceRight; apply replaceRight; auto.\n intros Delta1 Delta2 Delta3 H0.\n elim (replace_inv2 H0); clear H0; intro H0; elim H0; clear H0; intros x H0;\n  elim H0; clear H0; intros H0 H1.\n split with (Comma (Comma x Delta2) Delta3).\n split.\n rewrite H1.\n constructor 2.\n apply replaceLeft; apply replaceLeft; auto. \n elim (replace_inv2 H0); clear H0; intro H0; elim H0; clear H0; intros x0 H0;\n  elim H0; clear H0; intros H0 H2.\n split with (Comma (Comma Delta1 x0) Delta3).\n split.\n rewrite H1.\n rewrite H2.\n constructor 2.\n apply replaceLeft; apply replaceRight; auto.\n split with (Comma (Comma Delta1 Delta2) x0).\n split.\n rewrite H1.\n rewrite H2.\n constructor 2.\n apply replaceRight; auto.\nDefined.\n\nDefinition condAddExt :\n  forall X Y : gentzen_extension,\n  condCutExt X ->\n  condCutExt Y -> \n  condCutExt (add_genExtension X Y).\n\n intros X Y.\n unfold condCutExt in |- *.\n intros H H0.\n intros Atoms T T1 T2 T3 A H1 R.\n unfold add_genExtension in H1.\n elim H1; clear H1; intro H1.\n elim (H _ T T1 T2 T3 A H1 R).\n intros x H2.\n elim H2; clear H2; intros.\n split with x.\n split.\n unfold add_genExtension in |- *.\n left; auto.\n auto.\n elim (H0 _ T T1 T2 T3 A H1 R).\n intros x H2.\n elim H2; clear H2; intros.\n split with x.\n split.\n unfold add_genExtension in |- *.\n right; auto.\n auto.\nDefined.\n\nDefinition CutNatDed:\n  forall (Atoms: Set)(X : gentzen_extension) (Gamma Delta : Term Atoms)\n    (C A : Form Atoms),\n  condCutExt X ->\n  natDed X Delta A ->\n  natDed X Gamma C ->\n  forall Gamma' : Term Atoms,\n  replace Gamma Gamma' (OneForm A) Delta -> natDed X Gamma' C.\n intros At X Gamma Delta C A Cx H H0.\n elim H0; intros.\n elim (replace_inv1 H1).\n intros H2 H3.\n rewrite H2; rewrite <- H3.\n auto.\n apply SlashIntro.\n apply H1.\n apply replaceLeft; auto.\n apply BackSlashIntro.\n apply H1.\n apply replaceRight; assumption.\n elim (replace_inv2 H3); clear H3; intro H3; elim H3; clear H3; intros x H3;\n  elim H3; clear H3; intros H3 H4.\n rewrite H4.\n apply DotIntro.\n apply H1; assumption.\n assumption.\n rewrite H4.\n apply DotIntro.\n auto.\n apply H2; auto.\n elim (replace_inv2 H3); clear H3; intro H3; elim H3; clear H3; intros x H3;\n  elim H3; clear H3; intros H3 H4.\n rewrite H4.\n apply SlashElim with B.\n apply H1; auto.\n auto.\n rewrite H4.\n apply SlashElim with B.\n auto.\n apply H2; auto.\n elim (replace_inv2 H3); clear H3; intro H3; elim H3; clear H3; intros x H3;\n  elim H3; clear H3; intros H3 H4.\n rewrite H4.\n apply BackSlashElim with B.\n apply H1; auto.\n auto.\n rewrite H4.\n apply BackSlashElim with B.\n auto.\n apply H2; auto.\n elim (doubleReplace r H3); intro H4; elim H4; clear H4; intros x H4; elim H4;\n  clear H4; intros H4 H5.\n eapply DotElim.\n eauto. \n auto.\n apply H2; auto.\n eapply DotElim.\n eauto.\n apply H1; auto.\n auto.\n unfold condCutExt in Cx.\n elim (doubleReplace r H2); intro H3; elim H3; clear H3; intros T H3; elim H3;\n  clear H3; intros H3 H4.\n eapply NatExt.\n eauto.\n eauto.\n apply H1; assumption.\n elim (Cx _ T T1 T2 Delta A n H3).\n intros x H5.\n elim H5; clear H5; intros.\n elim (replaceSameP H4 x).\n intros x0 H5.\n elim H5; clear H5; intros.\n eapply NatExt.\n eauto.\n eauto.\n apply H1.\n eapply replaceTrans; eauto.\nDefined.\n\nDefinition composition :\n  forall (Atoms:Set)(X : gentzen_extension) (T : Term Atoms) (F1 F2 : Form Atoms),\n  condCutExt X ->\n  natDed X T F1 ->\n  natDed X (OneForm F1) F2 -> natDed X T F2.\n\n intros.\n apply CutNatDed with (OneForm F1) T F1.\n auto.\n auto.\n auto.\n constructor 1.\nDefined.\n\nEnd cutNaturalDeduction.\n\nSection EquivalenceNaturalGentzen.\n\nDefinition natDedToGentzen :\n  forall (Atoms:Set)(T : Term Atoms) (C : Form Atoms) (E : gentzen_extension),\n  natDed E T C -> gentzenSequent E T C.\n simple induction 1.\n constructor 1.\n intros.\n apply RightSlash.\n assumption.\n intros.\n apply RightBackSlash.\n assumption.\n intros.\n apply RightDot; assumption.\n intros Gamma Delta A B.\n intros.\n apply CutRule with Gamma (Comma (OneForm (Slash A B)) Delta) (Slash A B).\n apply replaceLeft.\n apply replaceRoot.\n assumption.\n apply LeftSlashSimpl.\n assumption.\n constructor 1.\n intros Gamma Delta A B.\n intros.\n apply\n  CutRule with Delta (Comma Gamma (OneForm (Backslash B A))) (Backslash B A).\n apply replaceRight.\n apply replaceRoot.\n assumption.\n apply LeftBackSlashSimpl.\n assumption.\n apply Ax.\n intros.\n eapply replaceGentzen'; eauto.\n intros.\n eapply SequentExtension; eauto.\nDefined.\n\n\nDefinition gentzenToNatDed:\n  forall (Atoms:Set)(T : Term Atoms) (C : Form Atoms) (E : gentzen_extension),\n  condCutExt E -> \n  gentzenSequent E T C ->\n  natDed E T C.\n\n simple induction 2.\n constructor 1.\n intros.\n constructor 2; assumption.\n intros; constructor 3; assumption.\n intros; constructor 4; assumption.\n intros Delta Gamma; intros.\n apply composition with (deltaTranslation Gamma).\n auto.\n eapply replaceNatDed.\n eauto.\n simpl in |- *.\n eapply SlashElim.\n eapply Axi.\n assumption.\n apply TermToFormDed.\n assumption.\n intros Delta Gamma; intros.\n apply composition with (deltaTranslation Gamma).\n auto.\n eapply replaceNatDed.\n eauto.\n simpl in |- *.\n eapply BackSlashElim.\n eauto.\n constructor 1.\n apply TermToFormDed; assumption.\n intro Gamma; intros.\n apply composition with (deltaTranslation Gamma).\n auto.\n eapply replaceNatDed.\n eauto.\n simpl in |- *; constructor 1.\n apply TermToFormDed; assumption.\n intros Delta Gamma; intros.\n apply composition with (deltaTranslation Gamma).\n auto.\n eapply replaceNatDed.\n eauto.\n simpl in |- *; assumption.\n apply TermToFormDed.\n assumption.\n intros.\n eapply NatExt; eauto.\nDefined.\n\nEnd EquivalenceNaturalGentzen.\n\n", "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/GentzenDed.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.27991112031852666}}
{"text": "Require Import Software.Language.Record.\nRequire Import Software.Lib.Lists.List.\nRequire Import Software.Language.RefPassStack.\nRequire Import Software.Language.Syntax.\nRequire Import Software.Language.Stack.\nRequire Import Software.Language.Store.\n\n(** * Types *)\n\nInductive state : Type :=\n  | Cstate: stack -> ref_pass_stack -> store -> state.\n\nInductive exec_state : Type :=\n  | Cexec_state : term -> state -> exec_state.\n\n(** * Functions *)\n(** ** State accessors *)\n\nDefinition get_stack (st : state) : stack :=\n  match st with\n  | Cstate sk _ _ => sk\n  end.\n\nDefinition get_ref_pass_stack (st : state) : ref_pass_stack :=\n  match st with\n  | Cstate _ rpsk _ => rpsk\n  end.\n\nDefinition get_store (st : state) : store :=\n  match st with\n  | Cstate _ _ sr => sr\n  end.\n\nDefinition set_stack (sk : stack) (st : state) : state :=\n  match st with\n  | Cstate _ rpsk sr => Cstate sk rpsk sr\n  end.\n\nDefinition set_ref_pass_stack (rpsk : ref_pass_stack) (st : state) : state :=\n  match st with\n  | Cstate sk _ sr => Cstate sk rpsk sr\n  end.\n\nDefinition set_store (sr : store) (st : state) : state :=\n  match st with\n  | Cstate sk rpsk _ => Cstate sk rpsk sr\n  end.\n\n(** ** Function call *)\n\nSection FunctionCalls.\n\nFixpoint args_to_ref_pass_stack_frame (args : list term) : ref_pass_stack_frame :=\n  match args with\n  | nil => nil\n  | cons t args' =>\n    match t with\n    | trefpass t' =>\n      match t' with\n      | tvar n => cons (Some n) (args_to_ref_pass_stack_frame args')\n      | _ => cons None (args_to_ref_pass_stack_frame args')\n      end\n    | _ => cons None (args_to_ref_pass_stack_frame args')\n    end\n  end.\n\nFixpoint args_to_stack_frame (args : list term) (context : stack_frame) : stack_frame :=\n  match args with\n  | nil => nil\n  | cons t args' =>\n    match t with\n    | trefpass t' =>\n      match t' with\n      | tvar n => cons (nth n context tvoid) (args_to_stack_frame args' context)\n      | _ => cons t (args_to_stack_frame args' context)\n      end\n    | _ => cons t (args_to_stack_frame args' context)\n    end\n  end.\n\nFixpoint return_refpass_args (rpsf : ref_pass_stack_frame) (source target : stack_frame) : stack_frame :=\n  match rpsf with\n  | nil => target\n  | cons c rpsf' =>\n    match c with\n    | None => return_refpass_args rpsf' (tl source) target\n    | Some n => return_refpass_args rpsf' (tl source) (replace n (hd tvoid source) target)\n    end\n  end.\n\nDefinition push_call (args : term) (st : state) : state :=\n  let sk := get_stack st in\n  let rpsk := get_ref_pass_stack st in\n  let sk' := push (args_to_stack_frame (rc_to_list args) (hd nil sk)) sk in\n  let rpsk' := RefPassStack.push (args_to_ref_pass_stack_frame (rc_to_list args)) rpsk in\n  set_ref_pass_stack rpsk' (set_stack sk' st).\n\nDefinition pop_call (st : state) : state :=\n  let sk := get_stack st in\n  let rpsk := get_ref_pass_stack st in\n  let sk' := push (return_refpass_args (hd nil rpsk) (hd nil sk) (nth 1 sk nil)) (pop (pop sk)) in\n  set_ref_pass_stack (RefPassStack.pop rpsk) (set_stack sk' st).\n\nHint Resolve Lt.lt_S_n List.nth_indep.\n\nLemma args_to_ref_pass_stack_frame_length:\n  forall args,\n  length (args_to_ref_pass_stack_frame args) = length args.\nProof with auto.\n  induction args...\n  destruct a; simpl...\n  destruct a; simpl...\n  Qed.\n\nLemma args_to_ref_pass_stack_frame_correct_1:\n  forall args m d1 d2,\n  lt m (length args) ->\n  (forall n, nth m args d1 <> trefpass (tvar n)) ->\n  nth m (args_to_ref_pass_stack_frame args) d2 = None.\nProof with auto.\n  induction args; try solve [intros; inversion H].\n  destruct m; simpl; intros d1 d2 Hlen Hstruct.\n  destruct a; simpl...\n  destruct a; simpl...\n  exfalso. apply (Hstruct n)...\n  destruct a; try solve [simpl; apply IHargs with d1; auto].\n  destruct a; try solve [simpl; apply IHargs with d1; auto].\n  Qed.\n\nLemma args_to_ref_pass_stack_frame_correct_2:\n  forall args m n d1 d2,\n  lt m (length args) ->\n  nth m args d1 = trefpass (tvar n) ->\n  nth m (args_to_ref_pass_stack_frame args) d2 = Some n.\nProof with auto.\n  induction args; try solve [intros; inversion H].\n  destruct m; simpl; intros n d1 d2 Hlen Hstruct.\n  destruct a; try solve [inversion Hstruct].\n  destruct a; try solve [inversion Hstruct].\n  inversion Hstruct; subst...\n  destruct a; try solve [simpl; apply IHargs with d1; auto].\n  destruct a; try solve [simpl; apply IHargs with d1; auto].\n  Qed.\n\nLemma args_to_stack_frame_length:\n  forall args context,\n  length (args_to_stack_frame args context) = length args.\nProof with auto.\n  induction args...\n  destruct a; simpl...\n  destruct a; simpl...\n  Qed.\n\nLemma args_to_stack_frame_correct_1:\n  forall args m context d1 d2 d3,\n  lt m (length args) ->\n  (forall n, nth m args d1 <> trefpass (tvar n)) ->\n  nth m (args_to_stack_frame args context) d2 = nth m args d3.\nProof with auto.\n  induction args; try solve [intros; inversion H].\n  destruct m; simpl; intros context d1 d2 d3 Hlen Hstruct.\n  destruct a; simpl...\n  destruct a; simpl...\n  exfalso. apply (Hstruct n)...\n  destruct a; try solve [simpl; apply IHargs with d1; auto].\n  destruct a; try solve [simpl; apply IHargs with d1; auto].\n  Qed.\n\nLemma args_to_stack_frame_correct_2:\n  forall args m n context d1 d2,\n  lt m (length args) ->\n  nth m args d1 = trefpass (tvar n) ->\n  nth m (args_to_stack_frame args context) d2 = nth n context tvoid.\nProof with auto.\n  induction args; try solve [intros; inversion H].\n  destruct m; simpl; intros n context d1 d2 Hlen Hstruct.\n  destruct a; try solve [inversion Hstruct].\n  destruct a; try solve [inversion Hstruct].\n  inversion Hstruct; simpl...\n  destruct a; try solve [simpl; apply IHargs with d1; auto].\n  destruct a; try solve [simpl; apply IHargs with d1; auto].\n  Qed.\n\nLemma return_refpass_args_length:\n  forall rpsf target source,\n  length (return_refpass_args rpsf source target) = length target.\nProof with auto using replace_length.\n  induction rpsf...\n  destruct target.\n  destruct a; intros; simpl return_refpass_args...\n  destruct a; try solve [intros; simpl; rewrite IHrpsf; auto].\n  destruct n; intros; simpl; rewrite IHrpsf; simpl...\n  Qed.\n\nLemma return_refpass_args_correct_1:\n  forall rpsf target n source d1 d2 d3,\n  (forall m, lt m (length rpsf) -> nth m rpsf d1 <> Some n) ->\n  lt n (length target) ->\n  nth n (return_refpass_args rpsf source target) d2 = nth n target d3.\nProof with auto.\n  induction rpsf. simpl...\n  (* rpsf <> nil *)\n  destruct target. intros. inversion H0.\n  (* target <> nil *)\n  destruct a.\n  (* rpsf = Some n0 :: rpsf' *)\n    intros n0. destruct (EqNat.beq_nat n0 n) eqn:Hnvals.\n    (* n0 = n *)\n      apply EqNat.beq_nat_true_iff in Hnvals. subst.\n      intros. exfalso. apply (H 0).\n        simpl. apply Lt.lt_0_Sn.\n        reflexivity.\n    (* n0 <> n*)\n      apply EqNat.beq_nat_false_iff in Hnvals.\n      destruct n; destruct n0.\n      (* n0 = 0 /\\ n = 0 *)\n        exfalso. apply Hnvals. reflexivity.\n      (* n0 = S n0' /\\ n = 0 *)\n        intros. simpl return_refpass_args. rewrite IHrpsf with (d1 := d1) (d3 := d3).\n          reflexivity.\n          intros. apply (H (S m)). simpl. apply Lt.lt_n_S. assumption.\n          simpl. assumption.\n      (* n0 = 0 /\\ n = S n' *)\n        intros. simpl return_refpass_args. rewrite IHrpsf with (d1 := d1) (d3 := d3).\n          reflexivity.\n          intros. apply (H (S m)). simpl. apply Lt.lt_n_S. assumption.\n          simpl. rewrite replace_length. assumption.\n      (* n0 = S n0' /\\ n = S n' *)\n        intros. simpl return_refpass_args. rewrite IHrpsf with (d1 := d1) (d3 := d3).\n          simpl. rewrite replace_correct_1 with (d2 := d3).\n            reflexivity.\n            apply Lt.lt_S_n. assumption.\n            apply not_eq_n. assumption.\n        intros. apply (H (S m)).\n          simpl. apply Lt.lt_n_S. assumption.\n        simpl. rewrite replace_length. assumption.\n  (* rpsf = None :: rpsf' *)\n    intros. simpl return_refpass_args. rewrite IHrpsf with (d1 := d1) (d3 := d3).\n      reflexivity.\n      intros. apply (H (S m)). simpl. apply Lt.lt_n_S. assumption.\n      simpl. assumption.\n  Qed.\n\nDefinition refpass_unique (rpsf : ref_pass_stack_frame) : Prop :=\n  forall m m' n d1 d2,\n  lt m (length rpsf) ->\n  nth m rpsf d1 = Some n ->\n  lt m' (length rpsf) ->\n  nth m' rpsf d2 = Some n ->\n  m' = m.\n\nLemma refpass_unique_nil:\n  refpass_unique nil.\nProof with auto.\n  unfold refpass_unique.\n  intros. inversion H.\n  Qed.\n\nLemma refpass_unique_cons:\n  forall rpsf a,\n  refpass_unique (cons a rpsf) ->\n  refpass_unique rpsf.\nProof with auto.\n  induction rpsf. intros. apply refpass_unique_nil.\n  unfold refpass_unique. intros.\n  apply (H (S m) (S m') n d1 d2) in H3.\n    inversion H3. reflexivity.\n    simpl. apply Lt.lt_n_S. assumption.\n    simpl. destruct m; assumption.\n    simpl. apply Lt.lt_n_S. assumption.\n  Qed.\n\nLemma return_refpass_args_correct_2:\n  forall source rpsf target n m d1 d2,\n  refpass_unique rpsf ->\n  lt m (length rpsf) ->\n  nth m rpsf d1 = Some n ->\n  lt n (length target) ->\n  nth n (return_refpass_args rpsf source target) d2 = nth m source tvoid.\nProof with auto.\n  induction source.\n  (* source = nil *)\n    induction rpsf. intros. inversion H0.\n    (* rpsf <> nil *)\n    destruct target. intros. inversion H2.\n    (* target <> nil *)\n    destruct a.\n    (* rpsf = Some n0 :: rpsf' *)\n      intros n0. destruct (EqNat.beq_nat n0 n) eqn:Hnvals.\n      (* n0 = n *)\n        apply EqNat.beq_nat_true_iff in Hnvals. subst.\n        intros.\n        assert (m = 0) as H3.\n        {\n          unfold refpass_unique in H.\n          apply (H 0 m n d1 d1).\n            simpl. apply Lt.lt_0_Sn.\n            reflexivity.\n            assumption.\n            assumption.\n        }\n        subst.\n        destruct n.\n        (* n = 0 *)\n          simpl return_refpass_args.\n          rewrite return_refpass_args_correct_1 with (d1 := d1) (d3 := d2).\n            reflexivity.\n            intros m H3 H4. unfold refpass_unique in H.\n              simpl length in H, H0.\n              apply (H 0 (S m) 0 d1 d1) in H4; try solve [assumption].\n                inversion H4.\n                apply Lt.lt_n_S. assumption.\n            simpl. apply Lt.lt_0_Sn.\n        (* n = S n' *)\n          simpl return_refpass_args.\n          rewrite return_refpass_args_correct_1 with (d1 := d1) (d3 := d2).\n            simpl. rewrite replace_correct_2.\n              reflexivity.\n              apply Lt.lt_S_n. assumption.\n            intros m H3 H4. unfold refpass_unique in H.\n              simpl length in H, H0.\n              apply (H 0 (S m) (S n) d1 d1) in H4; try solve [assumption].\n                inversion H4.\n                apply Lt.lt_n_S. assumption.\n            simpl. rewrite replace_length. assumption.\n      (* n0 <> n *)\n        apply EqNat.beq_nat_false_iff in Hnvals.\n        destruct n0; destruct n.\n        (* n0 = 0 /\\ n = 0 *)\n          exfalso. apply Hnvals. reflexivity.\n        (* n0 = 0 /\\ n = S n *)\n          destruct m.\n          (* m = 0 *)\n            intros. inversion H1.\n          (* m = S m' *)\n            intros. simpl return_refpass_args.\n            rewrite IHrpsf with (m := m) (d1 := d1).\n              destruct m; reflexivity.\n              apply refpass_unique_cons in H. assumption.\n              simpl in H0. apply Lt.lt_S_n. assumption.\n              assumption.\n              simpl. rewrite replace_length. assumption.\n        (* n0 = S n0' /\\ n = 0 *)\n          destruct m.\n          (* m = 0 *)\n            intros. inversion H1.\n          (* m = S m' *)\n            intros. simpl return_refpass_args.\n            rewrite IHrpsf with (m := m) (d1 := d1).\n              destruct m; reflexivity.\n              apply refpass_unique_cons in H. assumption.\n              simpl in H0. apply Lt.lt_S_n. assumption.\n              assumption.\n              assumption.\n        (* n0 = S n0' /\\ n = S n' *)\n          destruct m.\n          (* m = 0 *)\n            intros. inversion H1; subst. exfalso. apply Hnvals. reflexivity.\n          (* m = S m' *)\n            intros. simpl return_refpass_args.\n            rewrite IHrpsf with (m := m) (d1 := d1).\n              destruct m; reflexivity.\n              apply refpass_unique_cons in H. assumption.\n              simpl in H0. apply Lt.lt_S_n. assumption.\n              assumption.\n              simpl. rewrite replace_length. assumption.\n    (* rpsf = None :: rpsf' *)\n      destruct m.\n      (* m = 0 *)\n        intros. inversion H1.\n      (* m = S m' *)\n        intros. simpl return_refpass_args.\n        rewrite IHrpsf with (m := m) (d1 := d1).\n          destruct m; reflexivity.\n          apply refpass_unique_cons in H. assumption.\n          simpl in H0. apply Lt.lt_S_n. assumption.\n          assumption.\n          simpl. assumption.\n  (* source <> nil *)\n    destruct rpsf. intros. inversion H0.\n    (* rpsf <> nil *)\n    destruct target. intros. inversion H2.\n    (* target <> nil *)\n    destruct o.\n    (* rpsf = Some n0 :: rpsf' *)\n      intros n0. destruct (EqNat.beq_nat n0 n) eqn:Hnvals.\n      (* n0 = n *)\n        apply EqNat.beq_nat_true_iff in Hnvals. subst.\n        intros.\n        assert (m = 0) as H3.\n        {\n          unfold refpass_unique in H.\n          apply (H 0 m n d1 d1).\n            simpl. apply Lt.lt_0_Sn.\n            reflexivity.\n            assumption.\n            assumption.\n        }\n        subst.\n        destruct n.\n        (* n = 0 *)\n          simpl return_refpass_args.\n          rewrite return_refpass_args_correct_1 with (d1 := d1) (d3 := d2).\n            reflexivity.\n            intros m H3 H4. unfold refpass_unique in H.\n              simpl length in H, H0.\n              apply (H 0 (S m) 0 d1 d1) in H4; try solve [assumption].\n                inversion H4.\n                apply Lt.lt_n_S. assumption.\n            simpl. apply Lt.lt_0_Sn.\n        (* n = S n' *)\n          simpl return_refpass_args.\n          rewrite return_refpass_args_correct_1 with (d1 := d1) (d3 := d2).\n            simpl. rewrite replace_correct_2.\n              reflexivity.\n              apply Lt.lt_S_n. assumption.\n            intros m H3 H4. unfold refpass_unique in H.\n              simpl length in H, H0.\n              apply (H 0 (S m) (S n) d1 d1) in H4; try solve [assumption].\n                inversion H4.\n                apply Lt.lt_n_S. assumption.\n            simpl. rewrite replace_length. assumption.\n      (* n0 <> n *)\n        apply EqNat.beq_nat_false_iff in Hnvals.\n        destruct n0; destruct n.\n        (* n0 = 0 /\\ n = 0 *)\n          exfalso. apply Hnvals. reflexivity.\n        (* n0 = 0 /\\ n = S n *)\n          destruct m.\n          (* m = 0 *)\n            intros. inversion H1.\n          (* m = S m' *)\n            intros. simpl.\n            rewrite IHsource with (m := m) (d1 := d1).\n              reflexivity.\n              apply refpass_unique_cons in H. assumption.\n              simpl in H0. apply Lt.lt_S_n. assumption.\n              assumption.\n              simpl. rewrite replace_length. assumption.\n        (* n0 = S n0' /\\ n = 0 *)\n          destruct m.\n          (* m = 0 *)\n            intros. inversion H1.\n          (* m = S m' *)\n            intros. simpl.\n            rewrite IHsource with (m := m) (d1 := d1).\n              destruct m; reflexivity.\n              apply refpass_unique_cons in H. assumption.\n              simpl in H0. apply Lt.lt_S_n. assumption.\n              assumption.\n              assumption.\n        (* n0 = S n0' /\\ n = S n' *)\n          destruct m.\n          (* m = 0 *)\n            intros. inversion H1; subst. exfalso. apply Hnvals. reflexivity.\n          (* m = S m' *)\n            intros. simpl.\n            rewrite IHsource with (m := m) (d1 := d1).\n              destruct m; reflexivity.\n              apply refpass_unique_cons in H. assumption.\n              simpl in H0. apply Lt.lt_S_n. assumption.\n              assumption.\n              simpl. rewrite replace_length. assumption.\n    (* rpsf = None :: rpsf' *)\n      destruct m.\n      (* m = 0 *)\n        intros. inversion H1.\n      (* m = S m' *)\n        intros. simpl.\n        rewrite IHsource with (m := m) (d1 := d1).\n          destruct m; reflexivity.\n          apply refpass_unique_cons in H. assumption.\n          simpl in H0. apply Lt.lt_S_n. assumption.\n          assumption.\n          simpl. assumption.\n  Qed.\n\nLemma push_call_length:\n  forall st args,\n  length (get_ref_pass_stack (push_call args st)) = S (length (get_ref_pass_stack st)) /\\\n  length (get_stack (push_call args st)) = S (length (get_stack st)).\nProof.\n  induction st. intros. simpl.\n  split; reflexivity.\n  Qed.\n\n(** Tail of [ref_pass_stack] is unchanged. *)\n\nLemma push_call_correct_1:\n  forall st m args d1 d2,\n  lt m (length (get_ref_pass_stack st)) ->\n  nth (S m) (get_ref_pass_stack (push_call args st)) d1 = nth m (get_ref_pass_stack st) d2.\nProof.\n  induction st. intros m term d1 d2. simpl. intros.\n  apply nth_indep. assumption.\n  Qed.\n\n(** Tail of [stack] is unchanged. *)\n\nLemma push_call_correct_2:\n  forall st m args d1 d2,\n  lt m (length (get_stack st)) ->\n  nth (S m) (get_stack (push_call args st)) d1 = nth m (get_stack st) d2.\nProof.\n  induction st. intros m term d1 d2. simpl. intros.\n  apply nth_indep. assumption.\n  Qed.\n\n(** Head of [ref_pass_stack] is changed. *)\n\nLemma push_call_correct_3:\n  forall st args d,\n  hd d (get_ref_pass_stack (push_call args st)) = args_to_ref_pass_stack_frame (rc_to_list args).\nProof.\n  induction st. reflexivity.\n  Qed.\n\n(** Head of [stack] is changed. *)\n\nLemma push_call_correct_4:\n  forall st args d,\n  hd d (get_stack (push_call args st)) = args_to_stack_frame (rc_to_list args) (hd nil (get_stack st)).\nProof.\n  induction st. reflexivity.\n  Qed.\n\n(** [store] is unchanged. *)\n\nLemma push_call_correct_5:\n  forall st args,\n  get_store (push_call args st) = get_store st.\nProof.\n  induction st. intros. reflexivity.\n  Qed.\n\nLemma pop_call_length_1:\n  forall st n,\n  length (get_ref_pass_stack st) = S n ->\n  length (get_ref_pass_stack (pop_call st)) = n.\nProof.\n  induction st. intros n. simpl.\n  destruct r. intros. inversion H.\n  simpl. intros. injection H. intros. assumption.\n  Qed.\n\nLemma pop_call_length_2:\n  forall st n,\n  length (get_stack st) = S (S n) ->\n  length (get_stack (pop_call st)) = S n.\nProof.\n  induction st. intros n. simpl.\n  destruct s. simpl. intros. discriminate H.\n  destruct s1. simpl. intros. discriminate H.\n  simpl. intros. injection H. intros. rewrite H0. reflexivity.\n  Qed.\n\n(** Tail of [ref_pass_stack] is unchanged. *)\n\nLemma pop_call_correct_1:\n  forall st m d1 d2,\n  lt (S m) (length (get_ref_pass_stack st)) ->\n  nth m (get_ref_pass_stack (pop_call st)) d1 = nth (S m) (get_ref_pass_stack st) d2.\nProof.\n  induction st. intros m d1 d2. simpl.\n  destruct r. intros. inversion H.\n  simpl. intros. apply nth_indep. apply Lt.lt_S_n. assumption.\n  Qed.\n\n(** Tail of [stack] is unchanged. *)\n\nLemma pop_call_correct_2:\n  forall st m d1 d2,\n  lt (S (S m)) (length (get_stack st)) ->\n  nth (S m) (get_stack (pop_call st)) d1 = nth (S (S m)) (get_stack st) d2.\nProof.\n  induction st. intros m d1 d2. simpl.\n  destruct s. intros. inversion H.\n  destruct s1. intros. simpl in H. apply Lt.lt_S_n in H. inversion H.\n  simpl. intros. apply nth_indep. do 2 apply Lt.lt_S_n. assumption.\n  Qed.\n\n(** Head of [stack] is changed. *)\n\nLemma pop_call_correct_3:\n  forall st d,\n  hd d (get_stack (pop_call st)) = return_refpass_args (hd nil (get_ref_pass_stack st)) (hd nil (get_stack st)) (nth 1 (get_stack st) nil).\nProof.\n  induction st. reflexivity.\n  Qed.\n\n(** [store] is unchanged. *)\n\nLemma pop_call_correct_4:\n  forall st,\n  get_store (pop_call st) = get_store st.\nProof.\n  induction st. reflexivity.\n  Qed.\n\nEnd FunctionCalls.\n\n(** ** Stack functions *)\n\nDefinition write_sk_hd (n : nat) (a : term) (st : state) : state :=\n  set_stack (write_hd n a (get_stack st)) st.\n\nDefinition read_sk_hd (n : nat) (st : state) : term :=\n  read_hd n (get_stack st).\n\nDefinition resize_sk_hd (n : nat) (st : state) : state :=\n  set_stack (resize_hd n (get_stack st)) st.\n\n(** ** Store functions *)\n\nDefinition alloc_sr (a : term) (st : state) : state :=\n  set_store (alloc a (get_store st)) st.\n\nDefinition write_sr (n : nat) (t : term) (st : state) : state :=\n  set_store (write n t (get_store st)) st.\n\nDefinition read_sr (n : nat) (st : state) : term :=\n  read n (get_store st).\n\n(** ** Function unfolding\n\n    [Arguments] statement with [/] tells tactic [simpl] to unfold these\n    functions when arguments before the [/] are provided [[1]].\n\n    [[1]] #<a href=\"https://coq.inria.fr/distrib/8.4pl4/refman/Reference-Manual010.html##sec395\">\n           https://coq.inria.fr/distrib/8.4pl4/refman/Reference-Manual010.html##sec395</a># *)\n\nArguments get_stack st /.\nArguments get_ref_pass_stack st /.\nArguments get_store st /.\nArguments set_stack sk st /.\nArguments set_ref_pass_stack rpsk st /.\nArguments set_store sr st /.\nArguments args_to_ref_pass_stack_frame args /.\nArguments args_to_stack_frame args context /.\nArguments return_refpass_args rpsf source target /.\nArguments push_call args st /.\nArguments pop_call st /.\nArguments write_sk_hd n a st /.\nArguments read_sk_hd n st /.\nArguments resize_sk_hd n st /.\nArguments alloc_sr a st /.\nArguments write_sr n t st /.\nArguments read_sr n st /.\n\n(** * Constants *)\n\nDefinition init_state : state := Cstate init_stack init_ref_pass_stack init_store.\n\n(** * Notations *)\n\nModule StateNotations.\n\nNotation \"'\\stack' sk '\\ref_pass_stack' rpsk '\\store' sr\" :=\n  (Cstate sk rpsk sr) (at level 80, format \"'[' '[v  ' \\stack '/' '[' sk ']' ']' '//' '[v  ' \\ref_pass_stack '/' '[' rpsk ']' ']' '//' '[v  ' \\store '/' '[' sr ']' ']' ']'\") : state_scope.\n\nEnd StateNotations.\n\n", "meta": {"author": "jlapolla", "repo": "coq-oo", "sha": "510e5e471d06c1fa805528cff305e6a287e74686", "save_path": "github-repos/coq/jlapolla-coq-oo", "path": "github-repos/coq/jlapolla-coq-oo/coq-oo-510e5e471d06c1fa805528cff305e6a287e74686/Software/Language/State.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725051, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.2799111203185266}}
{"text": "Require Import SfLib.\nRequire Import Imp.\n\nRequire Import String.\nRequire Import Ascii.\n\nOpen Scope list_scope.\n\nDefinition isWhite (c : ascii) : bool :=\n    let n := nat_of_ascii c in\n    orb (orb (beq_nat n 32) (* space *)\n             (beq_nat n 9)) (* tab *)\n        (orb (beq_nat n 10) (* linefeed *)\n             (beq_nat n 13)). (* Carriage return *)\n\nNotation \"x '<=?' y\" := (ble_nat x y)\n    (at level 70, no associativity) : nat_scope.\n\nDefinition isLowerAlpha (c : ascii) : bool :=\n    let n := nat_of_ascii c in\n        andb (97 <=? n) (n <=? 122).\n\nDefinition isAlpha (c : ascii) : bool :=\n    let n := nat_of_ascii c in\n        orb (andb (65 <=? n) (n <=? 90))\n            (andb (97 <=? n) (n <=? 122)).\n\nDefinition isDigit (c : ascii) : bool :=\n    let n := nat_of_ascii c in\n        andb (48 <=? n) (n <=? 57).\n\n\nInductive chartype := white | alpha | digit | other.\n\nDefinition classifyChar (c : ascii) : chartype :=\n    if isWhite c then\n        white\n    else if isAlpha c then\n        alpha\n    else if isDigit c then\n        digit\n    else\n        other.\n\nFixpoint list_of_string (s : string) : list ascii :=\n    match s with\n    | EmptyString => []\n    | String c s => c :: (list_of_string s)\n    end.\n\nFixpoint string_of_list (xs : list ascii) : string :=\n    fold_right String EmptyString xs.\n\nDefinition token := string.\n\nFixpoint tokenize_helper (cls : chartype) (acc xs : list ascii)\n                        : list (list ascii) :=\n    let tk := match acc with [] => [] | _::_ => [rev acc] end in\n    match xs with\n    | [] => tk\n    | (x::xs') =>\n        match cls, classifyChar x, x with\n        | _, _, \"(\" => tk ++ [\"(\"]::(tokenize_helper other [] xs')\n        | _, _, \")\" => tk ++ [\")\"]::(tokenize_helper other [] xs')\n        | _, white, _ => tk ++ (tokenize_helper white [] xs')\n        | alpha,alpha,x => tokenize_helper alpha (x::acc) xs'\n        | digit,digit,x => tokenize_helper digit (x::acc) xs'\n        | other,other,x => tokenize_helper other (x::acc) xs'\n        | _,tp,x => tk ++ (tokenize_helper tp [x] xs')\n    end\nend %char.\n\nDefinition tokenize (s : string) : list string :=\n    map string_of_list (tokenize_helper white [] (list_of_string s)).\n\nExample tokenize_ex1 :\n    tokenize \"abc12==3 223*(3+(a+c))\" %string\n  = [\"abc\"; \"12\"; \"==\"; \"3\"; \"223\";\n     \"*\"; \"(\"; \"3\"; \"+\"; \"(\";\n     \"a\"; \"+\"; \"c\"; \")\"; \")\"] % string.\nProof. reflexivity. Qed.\n\nInductive optionE (X:Type) : Type :=\n    | SomeE : X -> optionE X\n    | NoneE : string -> optionE X.\n\nImplicit Arguments SomeE [[X]].\nImplicit Arguments NoneE [[X]].\n\nNotation \"'DO' ( x , y ) <== e1 ; e2\"\n    := (match e1 with\n        | SomeE (x,y) => e2\n        | NoneE err => NoneE err\n        end)\n    (right associativity, at level 60).\n\nNotation \"'DO' ( x , y ) <-- e1 ; e2 'OR' e3\"\n    := (match e1 with\n        | SomeE (x,y) => e2\n        | NoneE err => e3\n    end)\n    (right associativity, at level 60, e2 at next level).\n\n(* Build a mapping from tokens to nats. A real parser would do\n   this incrementally as it encountered new symbols, but passing\n   around the symble table inside the parsing functions is a bit\n   inconvinient, so instead we do it as a first pass. *)\nFixpoint build_symtable (xs : list token) (n : nat) : (token -> nat) :=\n    match xs with\n    | [] => (fun s => n)\n    | x::xs =>\n        if (forallb isLowerAlpha (list_of_string x))\n            then (fun s => if string_dec s x then n else (build_symtable xs (S n) s))\n            else build_symtable xs n\n    end.\n\nOpen Scope string_scope.\n\nDefinition parser (T : Type) :=\n    list token -> optionE (T * list token).\n\nFixpoint many_helper {T} (p : parser T) acc steps xs :=\nmatch steps, p xs with\n| 0, _ => NoneE \"Too many recursive calls\"\n| _, NoneE _ => SomeE ((rev acc), xs)\n| S steps', SomeE (t, xs') => many_helper p (t::acc) steps' xs'\nend.\n\n(* A (step-indexed) parser which expects zero or more ps *)\nFixpoint many {T} (p : parser T) (steps : nat) : parser (list T) :=\n    many_helper p [] steps.\n\n(* A parser which expects a given token, followed by p *)\nDefinition firstExpect {T} (t : token) (p : parser T) : parser T :=\n    fun xs => match xs with\n              | x::xs' => if string_dec x t\n                            then p xs'\n                          else NoneE (\"expected '\" ++ t ++ \"'.\")\n              | [] => NoneE (\"expected '\" ++ t ++ \"'.\")\n              end.\n\n(* A parser which expects a particular token *)\nDefinition expect (t : token) : parser unit :=\n    firstExpect t (fun xs => SomeE(tt, xs)).\n\n(* Identifiers *)\nDefinition parseIdentifier (symtable : string -> nat) (xs : list token)\n                        : optionE (id * list token) :=\nmatch xs with\n| [] => NoneE \"Expected identifier\"\n| x::xs' =>\n    if forallb isLowerAlpha (list_of_string x) then\n        SomeE (Id (symtable x), xs')\n    else\n        NoneE (\"Illegal identifier:'\" ++ x ++ \"'\")\nend.\n\n(* Numbers *)\nDefinition parseNumber (xs : list token) : optionE (nat * list token) :=\nmatch xs with\n| [] => NoneE \"Expected number\"\n| x::xs' =>\n    if forallb isDigit (list_of_string x) then\n        SomeE (fold_left (fun n d =>\n                    10 * n + (nat_of_ascii d - nat_of_ascii \"0\"%char))\n                (list_of_string x)\n                0,\n                xs')\n    else\n        NoneE \"Expected number\"\nend.\n\n(* Parse arithmetic expressions *)\nFixpoint parsePrimaryExp (steps:nat) symtable (xs : list token)\n   : optionE (aexp * list token) :=\n  match steps with\n  | 0 => NoneE \"Too many recursive calls\"\n  | S steps' =>\n      DO (i, rest) <-- parseIdentifier symtable xs ;\n          SomeE (AId i, rest)\n      OR DO (n, rest) <-- parseNumber xs ;\n          SomeE (ANum n, rest)\n      OR (DO (e, rest) <== firstExpect \"(\" (parseSumExp steps' symtable) xs;\n          DO (u, rest') <== expect \")\" rest ;\n          SomeE(e,rest'))\n  end\nwith parseProductExp (steps:nat) symtable (xs : list token) :=\n  match steps with\n  | 0 => NoneE \"Too many recursive calls\"\n  | S steps' =>\n    DO (e, rest) <==\n      parsePrimaryExp steps' symtable xs ;\n    DO (es, rest') <==\n      many (firstExpect \"*\" (parsePrimaryExp steps' symtable)) steps' rest;\n    SomeE (fold_left AMult es e, rest')\n  end\nwith parseSumExp (steps:nat) symtable (xs : list token) :=\n  match steps with\n  | 0 => NoneE \"Too many recursive calls\"\n  | S steps' =>\n    DO (e, rest) <==\n      parseProductExp steps' symtable xs ;\n    DO (es, rest') <==\n      many (fun xs =>\n             DO (e,rest') <--\n               firstExpect \"+\" (parseProductExp steps' symtable) xs;\n                                 SomeE ( (true, e), rest')\n             OR DO (e,rest') <==\n               firstExpect \"-\" (parseProductExp steps' symtable) xs;\n                                 SomeE ( (false, e), rest'))\n                            steps' rest;\n      SomeE (fold_left (fun e0 term =>\n                          match term with\n                            (true, e) => APlus e0 e\n                          | (false, e) => AMinus e0 e\n                          end)\n                       es e,\n             rest')\n  end.\n\nDefinition parseAExp := parseSumExp.\n\n(* Parsing boolean expressions *)\nFixpoint parseAtomicExp (steps:nat) (symtable : string -> nat) (xs : list token) :=\nmatch steps with\n| 0 => NoneE \"Too many recursive calls\"\n| S steps' =>\n    DO (u,rest) <-- expect \"true\" xs;\n        SomeE (BTrue,rest)\n    OR DO (u,rest) <-- expect \"false\" xs;\n        SomeE (BFalse,rest)\n    OR DO (e,rest) <-- firstExpect \"not\" (parseAtomicExp steps' symtable) xs ;\n        SomeE (BNot e, rest)\n    OR DO (e,rest) <-- firstExpect \"(\" (parseConjunctionExp steps' symtable) xs;\n        (DO (u,rest') <== expect \")\" rest; SomeE (e,rest))\n    OR DO (e,rest) <== parseProductExp steps' symtable xs ;\n        (DO (e', rest') <--\n            firstExpect \"==\" (parseAExp steps' symtable) rest ;\n            SomeE (BEq e e', rest')\n        OR DO (e', rest') <--\n            firstExpect \"<=\" (parseAExp steps' symtable) rest ;\n            SomeE (BLe e e', rest')\n        OR\n            NoneE \"Expected '==' or '<=' after arithmetic expression\")\nend\nwith parseConjunctionExp (steps:nat) (symtable : string -> nat) (xs : list token) :=\nmatch steps with\n| 0 => NoneE \"Too many recursive calls\"\n| S steps' =>\n    DO (e, rest) <==\n        parseAtomicExp steps' symtable xs ;\n    DO (es, rest') <==\n        many (firstExpect \"&&\" (parseAtomicExp steps' symtable)) steps' rest;\n    SomeE (fold_left BAnd es e, rest')\nend.\n\nDefinition parseBExp := parseConjunctionExp.\n\nFixpoint parseSimpleCommand (steps:nat) (symtable:string->nat) (xs : list token)\n    :=\nmatch steps with\n| 0 => NoneE \"Too many recursive calls\"\n| S steps' =>\n    DO (u, rest) <-- expect \"SKIP\" xs;\n        SomeE (SKIP, rest)\n    OR DO (e, rest) <--\n        firstExpect \"IF\" (parseBExp steps' symtable) xs;\n       DO (c, rest') <==\n        firstExpect \"THEN\" (parseSequencedCommand steps' symtable) rest;\n       DO (c', rest'') <==\n        firstExpect \"ELSE\" (parseSequencedCommand steps' symtable) rest';\n       DO (u, rest''') <==\n        expect \"END\" rest'';\n       SomeE(IFB e THEN c ELSE c' FI, rest''')\n    OR DO (e,rest) <--\n        firstExpect \"WHILE\" (parseBExp steps' symtable) xs;\n       DO (c, rest') <==\n        firstExpect \"DO\" (parseSequencedCommand steps' symtable) rest;\n       DO (u, rest'') <==\n        expect \"END\" rest';\n       SomeE(WHILE e DO c END, rest'')\n    OR DO (i, rest) <==\n        parseIdentifier symtable xs;\n       DO (e, rest') <==\n        firstExpect \":=\" (parseAExp steps' symtable) rest;\n       SomeE(i ::= e, rest')\n    end\nwith parseSequencedCommand (steps:nat) (symtable:string -> nat) (xs : list token) :=\nmatch steps with\n| 0 => NoneE \"Too many recursive calls\"\n| S steps' =>\n    DO (c, rest) <==\n        parseSimpleCommand steps' symtable xs;\n    DO (c', rest') <--\n        firstExpect \";;\" (parseSequencedCommand steps' symtable) rest;\n        SomeE(c ;; c', rest')\n    OR\n        SomeE(c, rest)\nend.\n\nDefinition bignumber := 1000.\n\nDefinition parse (str : string) : optionE (com * list token) :=\n    let tokens := tokenize str in\n    parseSequencedCommand bignumber (build_symtable tokens 0) tokens.\n\nEval compute in parse \"\n    IF x == y + 1 + 2 - y * 6 + 3 THEN\n      x := x * 1;;\n      y := 0\n    ELSE\n      SKIP\n    END  \".\n\n(*\n====>\n    SomeE\n       (IFB BEq (AId (Id 0))\n                (APlus\n                   (AMinus (APlus (APlus (AId (Id 1)) (ANum 1)) (ANum 2))\n                      (AMult (AId (Id 1)) (ANum 6)))\n                   (ANum 3))\n        THEN Id 0 ::= AMult (AId (Id 0)) (ANum 1);; Id 1 ::= ANum 0\n        ELSE SKIP FI, )\n*)\n\nEval compute in parse \"\n    SKIP;;\n    z:=x*y*(x*x);;\n    WHILE x==x DO\n      IF z <= z*z && not x == 2 THEN\n        x := z;;\n        y := z\n      ELSE\n        SKIP\n      END;;\n      SKIP\n    END;;\n    x:=z  \".\n(*\n====>\n     SomeE\n        (SKIP;;\n         Id 0 ::= AMult (AMult (AId (Id 1)) (AId (Id 2)))\n                        (AMult (AId (Id 1)) (AId (Id 1)));;\n         WHILE BEq (AId (Id 1)) (AId (Id 1)) DO\n           IFB BAnd (BLe (AId (Id 0)) (AMult (AId (Id 0)) (AId (Id 0))))\n                     (BNot (BEq (AId (Id 1)) (ANum 2)))\n              THEN Id 1 ::= AId (Id 0);; Id 2 ::= AId (Id 0)\n              ELSE SKIP FI;;\n           SKIP\n         END;;\n         Id 1 ::= AId (Id 0),\n        )\n*)\n\nEval compute in parse \"\n   SKIP;;\n   z:=x*y*(x*x);;\n   WHILE x==x DO\n     IF z <= z*z && not x == 2 THEN\n       x := z;;\n       y := z\n     ELSE\n       SKIP\n     END;;\n     SKIP\n   END;;\n   x:=z  \".\n(*\n=====>\n      SomeE\n         (SKIP;;\n          Id 0 ::= AMult (AMult (AId (Id 1)) (AId (Id 2)))\n                (AMult (AId (Id 1)) (AId (Id 1)));;\n          WHILE BEq (AId (Id 1)) (AId (Id 1)) DO\n            IFB BAnd (BLe (AId (Id 0)) (AMult (AId (Id 0)) (AId (Id 0))))\n                     (BNot (BEq (AId (Id 1)) (ANum 2)))\n              THEN Id 1 ::= AId (Id 0);;\n                   Id 2 ::= AId (Id 0)\n              ELSE SKIP\n            FI;;\n            SKIP\n          END;;\n          Id 1 ::= AId (Id 0),\n         ).\n*)\n", "meta": {"author": "montekki", "repo": "sf", "sha": "f91b70058bfeca1427fd402f0be158f6c779dffe", "save_path": "github-repos/coq/montekki-sf", "path": "github-repos/coq/montekki-sf/sf-f91b70058bfeca1427fd402f0be158f6c779dffe/ImpParser/ImpParser.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.2799111126916564}}
{"text": "(* (c) Copyright 2006-2016 Microsoft Corporation and Inria.                  *)\n(* Distributed under the terms of CeCILL-B.                                  *)\nRequire Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp\nRequire Import ssrbool ssrfun eqtype ssrnat seq path div choice.\nFrom mathcomp\nRequire Import fintype tuple finfun bigop prime ssralg poly finset center.\nFrom mathcomp\nRequire Import fingroup morphism perm automorphism quotient action finalg zmodp.\nFrom mathcomp\nRequire Import gfunctor gproduct cyclic commutator nilpotent pgroup.\nFrom mathcomp\nRequire Import sylow hall abelian maximal frobenius.\nFrom mathcomp\nRequire Import matrix mxalgebra mxrepresentation vector.\nFrom odd_order\nRequire Import BGsection1 BGsection3 BGsection7 BGsection10.\nFrom odd_order\nRequire Import BGsection14 BGsection15 BGsection16.\nFrom mathcomp\nRequire ssrnum.\nFrom mathcomp\nRequire Import algC classfun character inertia vcharacter.\nFrom odd_order\nRequire Import PFsection1 PFsection2 PFsection3 PFsection4 PFsection5.\n\n(******************************************************************************)\n(* This file covers Peterfalvi, Section 8: Structure of a Minimal Simple      *)\n(* Group of Odd Order. Actually, most Section 8 definitions can be found in   *)\n(* BGsection16, which holds the conclusions of the Local Analysis part of the *)\n(* proof, as the B & G text has been adapted to fit the usage in Section 8.   *)\n(* Most of the definitions of Peterfalvi Section 8 are covered in BGsection7, *)\n(* BGsection15 and BGsection16; we only give here:                            *)\n(*   FT_Pstructure S T defW <-> the groups W, W1, W2, S, and T satisfy the    *)\n(*                    conclusion of Theorem (8.8)(b), in particular, S and T  *)\n(*                    are of type P, S = S^(1) ><| W1, and T = T^`(1) ><| W2. *)\n(*                    The assumption defW : W1 \\x W2 = W is a parameter.      *)\n(*           'R[x] == the \"signalizer\" group of x \\in 'A1(M) for the Dade     *)\n(*                    hypothesis of M (note: this is only extensionally equal *)\n(*                    to the 'R[x] defined in BGsection14).                   *)\n(*            'R_M == the signalizer functor for the Dade hypothesis of M.    *)\n(*                    Note that this only maps x to 'R[x] for x in 'A1(M).    *)\n(*                    The casual use of the R(x) in Peterfalvi is improper,   *)\n(*                    as its meaning depends on which maximal group is        *)\n(*                    considered.                                             *)\n(*       'A~(M, A) == the support of the image of 'CF(M, A) under the Dade    *)\n(*                    isometry of a maximal group M.                          *)\n(*         'A1~(M) := 'A~(M, 'A1(M)).                                         *)\n(*          'A~(M) := 'A~(M, 'A(M)).                                          *)\n(*         'A0~(M) := 'A~(M, 'A0(M)).                                         *)\n(*  FT_Dade maxM, FT_Dade0 maxM, FT_Dade1 maxM, FT_DadeF maxM                 *)\n(*  FT_Dade_hyp maxM, FT_Dade0_hyp maxM, FT_Dade1_hyp maxM, FT_DadeF_hyp maxM *)\n(*                 == for maxM : M \\in 'M, the Dade isometry of M, with       *)\n(*                    domain 'A(M), 'A0(M), 'A1(M) and M`_\\F^#, respectively, *)\n(*                    and the proofs of the corresponding Dade hypotheses.    *)\n(*                    Note that we use an additional restriction (to M`_\\F^#) *)\n(*                    to fit better with the conventions of PFsection7.       *)\n(*  FTsupports M L <-> L supports M in the sense of (8.14) and (8.18). This   *)\n(*                    definition is not used outside this file.               *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GroupScope GRing.Theory.\n\nLocal Open Scope ring_scope.\n\n(* Supercedes the notation in BGsection14. *)\nNotation \"''R' [ x ]\" := 'C_((gval 'N[x])`_\\F)[x]\n (at level 8, format \"''R' [ x ]\")  : group_scope.\nNotation \"''R' [ x ]\" := 'C_('N[x]`_\\F)[x]%G : Group_scope.\n\nSection Definitions.\n\nVariable gT : minSimpleOddGroupType.\nLocal Notation G := (TheMinSimpleOddGroup gT).\nImplicit Types L M X : {set gT}.\n\n(* These cover Peterfalvi, Definition (8.14). *)\nDefinition FTsignalizer M x := if 'C[x] \\subset M then 1%G else 'R[x]%G.\n\nDefinition FTsupports M L :=\n  [exists x in 'A(M), ~~ ('C[x] \\subset M) && ('C[x] \\subset L)].\n\nDefinition FT_Dade_support M X :=\n  \\bigcup_(x in X) class_support (FTsignalizer M x :* x) G.\n\nEnd Definitions.\n\nNotation \"''R_' M\" := (FTsignalizer M)\n (at level 8, M at level 2, format \"''R_' M\") : group_scope.\n\nNotation \"''A~' ( M , A )\" := (FT_Dade_support M A)\n  (at level 8, format \"''A~' ( M ,  A )\").\n\nNotation \"''A1~' ( M )\" := 'A~(M, 'A1(M)) (at level 8, format \"''A1~' ( M )\").\nNotation \"''A~' ( M )\" := 'A~(M, 'A(M)) (at level 8, format \"''A~' ( M )\").\nNotation \"''A0~' ( M )\" := 'A~(M, 'A0(M)) (at level 8, format \"''A0~' ( M )\").\n\nSection Eight.\n\nVariable gT : minSimpleOddGroupType.\nLocal Notation G := (TheMinSimpleOddGroup gT).\nImplicit Types (p q : nat) (x y z : gT) (A B : {set gT}).\nImplicit Types H K L M N P Q R S T U V W : {group gT}.\n\n(* Peterfalvi, Definition (8.1) is covered by BGsection16.of_typeF. *)\n\n(* This is the remark following Definition (8.1). *)\nRemark compl_of_typeF M U V (H := M`_\\F) :\n  H ><| U = M -> of_typeF M V -> of_typeF M U.\nProof.\nmove=> defM_U [[]]; rewrite -/H => ntH ntV defM part_b part_c.\nhave oU: #|U| = #|V|.\n  apply/eqP; rewrite -(@eqn_pmul2l #|H|) ?cardG_gt0 //.\n  by rewrite (sdprod_card defM) (sdprod_card defM_U).\nhave [x Mx defU]: exists2 x, x \\in M & U :=: V :^ x.\n  pose pi := \\pi(V); have hallV: pi.-Hall(M) V.\n    by rewrite Hall_pi // -(sdprod_Hall defM) (pHall_Hall (Fcore_Hall M)).\n  apply: Hall_trans (hallV).\n    rewrite mFT_sol // (sub_proper_trans _ (mFT_norm_proper ntH _)) ?gFnorm //.\n    rewrite (proper_sub_trans _ (subsetT M)) // properEcard gFsub.\n    by rewrite -(sdprod_card defM) ltn_Pmulr ?cardG_gt0 ?cardG_gt1.\n  rewrite pHallE -(card_Hall hallV) oU eqxx andbT.\n  by case/sdprod_context: defM_U.\nhave nHx: x \\in 'N(H) by apply: subsetP Mx; rewrite gFnorm.\nsplit; first by rewrite {1}defU conjsg_eq1.\n  have [U1 [nsU1U abU1 prU1H]] := part_b.\n  rewrite defU; exists (U1 :^ x)%G; split; rewrite ?normalJ ?abelianJ //.\n  rewrite -/H -(normP nHx) -conjD1g => _ /imsetP[h Hh ->].\n  by rewrite -conjg_set1 normJ -conjIg conjSg prU1H.\nhave [U0 [sU0V expU0 frobHU0]] := part_c.\nhave [defHU0 _ ntU0 _ _] := Frobenius_context frobHU0.\nrewrite defU; exists (U0 :^ x)%G; split; rewrite ?conjSg ?exponentJ //.\nby rewrite -/H -(normP nHx) -conjYg FrobeniusJ.\nQed.\n\nLemma Frobenius_of_typeF M U (H := M`_\\F) :\n  [Frobenius M = H ><| U] -> of_typeF M U.\nProof.\nmove=> frobM; have [defM ntH ntU _ _] := Frobenius_context frobM.\nhave [_ _ nHU tiHU] := sdprodP defM.\nsplit=> //; last by exists U; split; rewrite // -sdprodEY ?defM.\nexists 1%G; split; rewrite ?normal1 ?abelian1 //.\nby move=> x /(Frobenius_reg_compl frobM)->.\nQed.\n\n(* This is Peterfalvi (8.2).                                                  *)\nLemma typeF_context M U (H := M`_\\F) :\n    of_typeF M U ->\n  [/\\ (*a*) forall U0, is_typeF_complement M U U0 -> #|U0| = exponent U,\n      (*b*) [Frobenius M = H ><| U] = Zgroup U\n    & (*c*) forall U1 (i : Iirr H),\n            is_typeF_inertia M U U1 -> i != 0 -> 'I_U['chi_i] \\subset U1].\nProof.\ncase; rewrite -/H => [[ntH ntM defM] _ exU0]; set part_a := forall U0, _.\nhave [nsHM sUG mulHU nHU _] := sdprod_context defM.\nhave oU0: part_a.\n  move=> U0 [sU0U <- /Frobenius_reg_ker regU0]; rewrite exponent_Zgroup //.\n  apply/forall_inP=> S /SylowP[p _ /and3P[sSU0 pS _]].\n  apply: odd_regular_pgroup_cyclic pS (mFT_odd S) ntH _ _.\n    by rewrite (subset_trans (subset_trans sSU0 sU0U)).\n  by move=> x /setD1P[ntx /(subsetP sSU0) U0x]; rewrite regU0 // !inE ntx.\nsplit=> // [|U1 i [nsU1U abU1 s_cUH_U1] nz_i].\n  apply/idP/idP=> [frobU | ZgU].\n    apply/forall_inP=> S /SylowP[p _ /and3P[sSU pS _]].\n    apply: odd_regular_pgroup_cyclic pS (mFT_odd S) ntH _ _.\n      by rewrite (subset_trans sSU).\n    move=> x /setD1P[ntx /(subsetP sSU) Ux].\n    by rewrite (Frobenius_reg_ker frobU) // !inE ntx.\n  have [U0 [sU0U expU0 frobU0]] := exU0; have regU0 := Frobenius_reg_ker frobU0.\n  suffices defU0: U0 :=: U by rewrite defU0 norm_joinEr ?mulHU // in frobU0.\n  by apply/eqP; rewrite eqEcard sU0U /= (oU0 U0) // exponent_Zgroup.\nhave itoP: is_action M (fun (j : Iirr H) x => conjg_Iirr j x).\n  split=> [x | j x y Mx My].\n    apply: can_inj (fun j => conjg_Iirr j x^-1) _ => j.\n    by apply: irr_inj; rewrite !conjg_IirrE cfConjgK.\n  by apply: irr_inj; rewrite !conjg_IirrE (cfConjgM _ nsHM).\npose ito := Action itoP; pose cto := ('Js \\ subsetT M)%act.\nhave actsMcH: [acts M, on classes H | cto].\n  apply/subsetP=> x Mx; rewrite !inE Mx; apply/subsetP=> _ /imsetP[y Hy ->].\n  have nHx: x \\in 'N(H) by rewrite (subsetP (gFnorm _ _)).\n  rewrite !inE /= -class_rcoset norm_rlcoset // class_lcoset mem_classes //.\n  by rewrite memJ_norm.\napply/subsetP=> g /setIP[Ug /setIdP[nHg c_i_g]]; have Mg := subsetP sUG g Ug.\napply: contraR nz_i => notU1g; rewrite (sameP eqP set1P).\nsuffices <-: 'Fix_ito[g] = [set 0 : Iirr H].\n  by rewrite !inE sub1set inE -(inj_eq (@irr_inj _ _)) conjg_IirrE.\napply/eqP; rewrite eq_sym eqEcard cards1 !(inE, sub1set) /=.\nrewrite -(inj_eq (@irr_inj _ _)) conjg_IirrE irr0 cfConjg_cfun1 eqxx.\nrewrite (card_afix_irr_classes Mg actsMcH) => [|j y z Hy /=]; last first.\n  case/imsetP=> _ /imsetP[t Ht ->] -> {z}.\n  by rewrite conjg_IirrE cfConjgE // conjgK cfunJ.\nrewrite -(cards1 [1 gT]) subset_leq_card //= -/H.\napply/subsetP=> _ /setIP[/imsetP[a Ha ->] /afix1P caHg]; rewrite inE classG_eq1.\nhave{caHg} /imsetP[x Hgx cax]: a \\in a ^: (H :* g).\n  by rewrite class_rcoset caHg class_refl.\nhave coHg: coprime #|H| #[g].\n  apply: (coprime_dvdr (order_dvdG Ug)).\n  by rewrite (coprime_sdprod_Hall_l defM) (pHall_Hall (Fcore_Hall M)).\nhave /imset2P[z y cHgg_z Hy defx]: x \\in class_support ('C_H[g] :* g) H.\n  have [/and3P[/eqP defUcHgg _ _] _] := partition_cent_rcoset nHg coHg.\n  by rewrite class_supportEr -cover_imset defUcHgg.\nrewrite -(can_eq (conjgKV y)) conj1g; apply: contraR notU1g => nt_ay'.\nhave{nt_ay'} Hay': a ^ y^-1 \\in H^# by rewrite !inE nt_ay' groupJ ?groupV.\nrewrite (subsetP (s_cUH_U1 _ Hay')) // inE Ug.\nhave ->: g = z.`_(\\pi(H)^').\n  have [h /setIP[Hh /cent1P cgh] ->] := rcosetP cHgg_z.\n  rewrite consttM // (constt1P _) ?mul1g ?constt_p_elt //.\n    by rewrite /p_elt -coprime_pi' ?cardG_gt0.\n  by rewrite (mem_p_elt _ Hh) // pgroupNK pgroup_pi.\nby rewrite groupX //= -conjg_set1 normJ mem_conjgV -defx !inE conjg_set1 -cax.\nQed.\n\n(* Peterfalvi, Definition (8.3) is covered by BGsection16.of_typeI. *)\n(* Peterfalvi, Definition (8.4) is covered by BGsection16.of_typeP. *)\n\nSection TypeP_Remarks.\n(* These correspond to the remarks following Definition (8.4). *)\n\nVariables (M U W W1 W2 : {group gT}) (defW : W1 \\x W2 = W).\nLet H := M`_\\F.\nLet M' := M^`(1)%g.\n\nHypothesis MtypeP : of_typeP M U defW.\n\nRemark of_typeP_sol : solvable M.\nProof.\nhave [_ [nilU _ _ defM'] _ _ _] := MtypeP.\nhave [nsHM' _ mulHU _ _] := sdprod_context defM'.\nrewrite (series_sol (der_normal 1 M)) (abelian_sol (der_abelian 0 M)) andbT.\nrewrite (series_sol nsHM') (nilpotent_sol (Fcore_nil M)).\nby rewrite -mulHU quotientMidl quotient_sol ?(nilpotent_sol nilU).\nQed.\n\nRemark typeP_cent_compl : 'C_M'(W1) = W2.\nProof.\nhave [[/cyclicP[x ->] _ ntW1 _] _ _ [_ _ _ _ prM'W1] _] := MtypeP.\nby rewrite cent_cycle prM'W1 // !inE cycle_id -cycle_eq1 ntW1.\nQed.\n\nRemark typeP_cent_core_compl : 'C_H(W1) = W2.\nProof.\nhave [sW2H sHM']: W2 \\subset H /\\ H \\subset M'.\n  by have [_ [_ _ _ /sdprodW/mulG_sub[-> _]] _ []] := MtypeP.\nby apply/eqP; rewrite eqEsubset subsetI sW2H -typeP_cent_compl ?subsetIr ?setSI.\nQed.\n\nLemma typePF_exclusion K : ~ of_typeF M K.\nProof.\nmove=> [[ntH ntU1 defM_K] _ [U0 [sU01 expU0] frobU0]].\nhave [[cycW1 hallW1 ntW1 defM] [_ _ _ defM'] _ [_]] := MtypeP; case/negP.\npose p := pdiv #|W1|; rewrite -/M' -/H in defM defM' frobU0 *.\nhave piW1p: p \\in \\pi(W1) by rewrite pi_pdiv cardG_gt1.\nhave piU0p: p \\in \\pi(U0).\n  rewrite -pi_of_exponent expU0 pi_of_exponent (pi_of_dvd _ _ piW1p) //=.\n  rewrite -(@dvdn_pmul2l #|H|) ?cardG_gt0 // (sdprod_card defM_K).\n  rewrite -(sdprod_card defM) dvdn_pmul2r ?cardSg //.\n  by case/sdprodP: defM' => _ <- _ _; apply: mulG_subl.\nhave [|X EpX]:= @p_rank_geP _ p 1 U0 _; first by rewrite p_rank_gt0.\nhave [ntX [sXU0 abelX _]] := (nt_pnElem EpX isT, pnElemP EpX).\nhave piW1_X: \\pi(W1).-group X by apply: pi_pgroup piW1p; case/andP: abelX.\nhave sXM: X \\subset M.\n  by rewrite -(sdprodWY defM_K) joingC sub_gen ?subsetU // (subset_trans sXU0).\nhave nHM: M \\subset 'N(H) by apply: gFnorm.\nhave [regU0 solM] := (Frobenius_reg_ker frobU0, of_typeP_sol).\nhave [a Ma sXaW1] := Hall_Jsub solM (Hall_pi hallW1) sXM piW1_X.\nrewrite -subG1 -(conjs1g a) -(cent_semiregular regU0 sXU0 ntX) conjIg -centJ.\nby rewrite (normsP nHM) // -typeP_cent_core_compl ?setIS ?centS.\nQed.\n\nRemark of_typeP_compl_conj W1x : M' ><| W1x = M -> W1x \\in W1 :^: M.\nProof.\ncase/sdprodP=> [[{W1x}_ W1x _ ->] mulM'W1x _ tiM'W1x].\nhave [[_ /Hall_pi hallW1 _ defM] _ _ _ _] := MtypeP.\napply/imsetP; apply: Hall_trans of_typeP_sol _ (hallW1).\nrewrite pHallE -(card_Hall hallW1) -(@eqn_pmul2l #|M'|) ?cardG_gt0 //.\nby rewrite (sdprod_card defM) -mulM'W1x mulG_subr /= TI_cardMg.\nQed.\n\nRemark conj_of_typeP x :\n  {defWx : W1 :^ x \\x W2 :^ x = W :^ x | of_typeP (M :^ x) (U :^ x) defWx}.\nProof.\nhave defWx: W1 :^ x \\x W2 :^ x = W :^ x by rewrite -dprodJ defW.\nexists defWx; rewrite /of_typeP !derJ FcoreJ FittingJ centJ -conjIg normJ.\nrewrite !cyclicJ !conjsg_eq1 /Hall !conjSg indexJg cardJg -[_ && _]/(Hall M W1).\nrewrite -(isog_nil (conj_isog U x)) -!sdprodJ -conjsMg -conjD1g.\nrewrite -(conjGid (in_setT x)) -conjUg -conjDg normedTI_J.\nhave [[-> -> -> ->] [-> -> -> ->] [-> -> -> ->] [-> -> -> -> prW1] ->]:= MtypeP.\nby do 2![split]=> // _ /imsetP[y /prW1<- ->]; rewrite cent1J -conjIg.\nQed.\n\n(* This is Peterfalvi (8.5), with an extra clause in anticipation of (8.15). *)\nLemma typeP_context :\n  [/\\ (*a*) H \\x 'C_U(H) = 'F(M),\n      (*b*) U^`(1)%g \\subset 'C(H) /\\ (U :!=: 1%g -> ~~ (U \\subset 'C(H))),\n      (*c*) normedTI (cyclicTIset defW) G W\n    & cyclicTI_hypothesis G defW].\nProof.\nhave defW2 := typeP_cent_core_compl.\ncase: MtypeP; rewrite /= -/H => [] [cycW1 hallW1 ntW1 defM] [nilU _ _ defM'].\nset V := W :\\: _ => [] [_ sM''F defF sFM'] [cycW2 ntW2 sW2H _ _] TI_V.\nhave [/andP[sHM' nHM'] sUM' mulHU _ tiHU] := sdprod_context defM'.\nhave sM'M : M' \\subset M by apply: der_sub.\nhave hallM': \\pi(M').-Hall(M) M' by rewrite Hall_pi // (sdprod_Hall defM).\nhave hallH_M': \\pi(H).-Hall(M') H := pHall_subl sHM' sM'M (Fcore_Hall M).\nhave{} defF: (H * 'C_U(H))%g = 'F(M).\n  rewrite -(setIidPl sFM') -defF -group_modl //= -/H.\n  rewrite setIAC (setIidPr (der_sub 1 M)).\n  rewrite -(coprime_mulG_setI_norm mulHU) ?norms_cent //; last first.\n    by rewrite (coprime_sdprod_Hall_l defM') (pHall_Hall hallH_M').\n  by rewrite mulgA (mulGSid (subsetIl _ _)).\nhave coW12: coprime #|W1| #|W2|.\n  rewrite coprime_sym (coprimeSg (subset_trans sW2H sHM')) //.\n  by rewrite (coprime_sdprod_Hall_r defM).\nhave cycW: cyclic W by rewrite (cyclic_dprod defW).\nhave ctiW: cyclicTI_hypothesis G defW by split; rewrite ?mFT_odd.\nsplit=> //; first by rewrite dprodE ?subsetIr //= setIA tiHU setI1g.\nsplit.\n  apply: subset_trans (_ : U :&: 'F(M) \\subset _).\n    by rewrite subsetI gFsub (subset_trans (dergS 1 sUM')).\n  by rewrite -defF -group_modr ?subsetIl // setIC tiHU mul1g subsetIr.\napply: contra => cHU; rewrite -subG1 -tiHU subsetIidr (subset_trans sUM') //.\nby rewrite (Fcore_max hallM') ?der_normal // -mulHU mulg_nil ?Fcore_nil.\nQed.\n\nEnd TypeP_Remarks.\n\nRemark FTtypeP_witness M :\n  M \\in 'M -> FTtype M != 1%N -> exists_typeP (of_typeP M).\nProof.\nmove=> maxM /negbTE typeMnot1.\nhave:= FTtype_range M; rewrite -mem_iota !inE typeMnot1 /=.\nby case/or4P=> /FTtypeP[//|U W W1 W2 defW [[]]]; exists U W W1 W2 defW.\nQed.\n\n(* Peterfalvi, Definition (8.6) is covered by BGsection16.of_typeII_IV et al. *)\n(* Peterfalvi, Definition (8.7) is covered by BGsection16.of_typeV. *)\n\nSection FTypeP_Remarks.\n(* The remarks for Definition (8.4) also apply to (8.6) and (8.7). *)\n\nVariables (M U W W1 W2 : {group gT}) (defW : W1 \\x W2 = W).\nLet H := M`_\\F.\nLet M' := M^`(1)%g.\n\nHypotheses (maxM : M \\in 'M) (MtypeP : of_typeP M U defW).\n\nRemark of_typeP_conj (Ux W1x W2x Wx : {group gT}) (defWx : W1x \\x W2x = Wx) :\n    of_typeP M Ux defWx ->\n  exists x,\n     [/\\ x \\in M, U :^ x = Ux, W1 :^ x = W1x, W2 :^ x = W2x & W :^ x = Wx].\nProof.\nmove=> MtypePx; have [[_ _ _ defMx] [_ _ nUW1x defM'x] _ _ _] := MtypePx.\nhave [[_ hallW1 _ defM] [_ _ nUW1 defM'] _ _ _] := MtypeP.\nhave [/mulG_sub[/= sHM' sUM'] [_ _ nM'W1 _]] := (sdprodW defM', sdprodP defM).\nrewrite -/M' -/H in defMx defM'x defM defM' sHM' sUM' nM'W1.\nhave /imsetP[x2 Mx2 defW1x2] := of_typeP_compl_conj MtypeP defMx.\nhave /andP[sM'M nM'M]: M' <| M by apply: der_normal.\nhave solM': solvable M' := solvableS sM'M (of_typeP_sol MtypeP).\nhave [hallU hallUx]: \\pi(H)^'.-Hall(M') U /\\ \\pi(H)^'.-Hall(M') (Ux :^ x2^-1).\n  have hallH: \\pi(H).-Hall(M') H by apply: pHall_subl (Fcore_Hall M).\n  rewrite pHallJnorm ?(subsetP nM'M) ?groupV // -!(compl_pHall _ hallH).\n  by rewrite (sdprod_compl defM') (sdprod_compl defM'x).\nhave coM'W1: coprime #|M'| #|W1| by rewrite (coprime_sdprod_Hall_r defM).\nhave nUxW1: W1 \\subset 'N(Ux :^ x2^-1) by rewrite normJ -sub_conjg -defW1x2.\nhave [x1] := coprime_Hall_trans nM'W1 coM'W1 solM' hallUx nUxW1 hallU nUW1.\ncase/setIP=> /(subsetP sM'M) My /(normsP (cent_sub _)) nW1x1 defUx1.\npose x := (x1 * x2)%g; have Mx: x \\in M by rewrite groupM.\nhave defW1x: W1 :^ x = W1x by rewrite conjsgM nW1x1.\nhave defW2x: W2 :^ x = W2x.\n  rewrite -(typeP_cent_compl MtypeP) -(typeP_cent_compl MtypePx).\n  by rewrite conjIg -centJ defW1x (normsP nM'M).\nby exists x; rewrite -defW dprodJ defW1x defW2x conjsgM -defUx1 conjsgKV.\nQed.\n\nLemma FTtypeP_neq1 : FTtype M != 1%N.\nProof. by apply/FTtypeP=> // [[V [/(typePF_exclusion MtypeP)]]]. Qed.\n\nRemark compl_of_typeII_IV : FTtype M != 5%N -> of_typeII_IV M U defW.\nProof.\nmove=> Mtype'5.\nhave [Ux Wx W1x W2x defWx Mtype24]: exists_typeP (of_typeII_IV M).\n  have:= FTtype_range M; rewrite leq_eqVlt eq_sym (leq_eqVlt _ 5).\n  rewrite (negPf FTtypeP_neq1) (negPf Mtype'5) /= -mem_iota !inE.\n  by case/or3P=> /FTtypeP[]// Ux Wx W1x W2x dWx []; exists Ux Wx W1x W2x dWx.\nhave [MtypePx ntUx prW1x tiFM] := Mtype24.\nhave [x [Mx defUx defW1x _ _]] := of_typeP_conj MtypePx.\nby rewrite -defUx -defW1x cardJg conjsg_eq1 in ntUx prW1x.\nQed.\n\nRemark compl_of_typeII : FTtype M == 2%N -> of_typeII M U defW.\nProof.\nmove=> Mtype2.\nhave [Ux Wx W1x W2x defWx [[MtypePx _ _ _]]] := FTtypeP 2 maxM Mtype2.\nhave [x [Mx <- _ _ _]] := of_typeP_conj MtypePx; rewrite -/M' -/H.\nrewrite abelianJ normJ -{1}(conjGid Mx) conjSg => cUU not_sNUM M'typeF defH.\nsplit=> //; first by apply: compl_of_typeII_IV; rewrite // (eqP Mtype2).\nby apply: compl_of_typeF M'typeF; rewrite defH; have [_ []] := MtypeP.\nQed.\n\nRemark compl_of_typeIII : FTtype M == 3%N -> of_typeIII M U defW.\nProof.\nmove=> Mtype3.\nhave [Ux Wx W1x W2x defWx [[MtypePx _ _ _]]] := FTtypeP 3 maxM Mtype3.\nhave [x [Mx <- _ _ _]] := of_typeP_conj MtypePx; rewrite -/M' -/H.\nrewrite abelianJ normJ -{1}(conjGid Mx) conjSg.\nby split=> //; apply: compl_of_typeII_IV; rewrite // (eqP Mtype3).\nQed.\n\nRemark compl_of_typeIV : FTtype M == 4%N -> of_typeIV M U defW.\nProof.\nmove=> Mtype4.\nhave [Ux Wx W1x W2x defWx [[MtypePx _ _ _]]] := FTtypeP 4 maxM Mtype4.\nhave [x [Mx <- _ _ _]] := of_typeP_conj MtypePx; rewrite -/M' -/H.\nrewrite abelianJ normJ -{1}(conjGid Mx) conjSg.\nby split=> //; apply: compl_of_typeII_IV; rewrite // (eqP Mtype4).\nQed.\n\nRemark compl_of_typeV : FTtype M == 5%N -> of_typeV M U defW.\nProof.\nmove=> Mtype5.\nhave [Ux Wx W1x W2x defWx [[MtypePx /eqP]]] := FTtypeP 5 maxM Mtype5.\nhave [x [Mx <- <- _ _]] := of_typeP_conj MtypePx; rewrite -/M' -/H.\nby rewrite cardJg conjsg_eq1 => /eqP.\nQed.\n\nEnd FTypeP_Remarks.\n\n(* This is the statement of Peterfalvi, Theorem (8.8)(a). *)\nDefinition all_FTtype1 := [forall M : {group gT} in 'M, FTtype M == 1%N].\n\n(* This is the statement of Peterfalvi, Theorem (8.8)(b). *)\nDefinition typeP_pair S T (W W1 W2 : {set gT}) (defW : W1 \\x W2 = W) :=\n [/\\      [/\\ cyclicTI_hypothesis G defW, S \\in 'M & T \\in 'M],\n   (*b1*) [/\\ S^`(1) ><| W1 = S, T^`(1) ><| W2 = T & S :&: T = W]%g,\n   (*b2*) (FTtype S == 2%N) || (FTtype T == 2%N),\n   (*b3*) (1 < FTtype S <= 5 /\\ 1 < FTtype T <= 5)%N\n & (*b4*) {in 'M, forall M, FTtype M != 1%N -> gval M \\in S :^: G :|: T :^: G}].\n\nLemma typeP_pair_sym S T W W1 W2 (defW : W1 \\x W2 = W) (xdefW : W2 \\x W1 = W) :\n  typeP_pair S T defW -> typeP_pair T S xdefW.\nProof.\nby case=> [[/cyclicTIhyp_sym ? ? ?] [? ?]]; rewrite setIC setUC orbC => ? ? [].\nQed.\n\n(* This is Peterfalvi, Theorem (8.8). *)\nLemma FTtypeP_pair_cases : \n     (*a*) {in 'M, forall M, FTtype M == 1%N}\n  \\/ (*b*) exists S, exists T, exists_typeP (fun _ => typeP_pair S T).\nProof.\nhave [_ [| [[S T] [[maxS maxT] [[W1 W2] /=]]]]] := BGsummaryI gT; first by left.\nset W := W1 <*> W2; set V := W :\\: (W1 :|: W2).\ncase=> [[cycW tiV _] [defS defT tiST]] b4 /orP b2 b3.\nhave [cWW /joing_sub[sW1W sW2W]] := (cyclic_abelian cycW, erefl W).\nhave ntV: V != set0 by have [] := andP tiV.\nsuffices{tiST tiV cWW sW1W sW2W b3 b4} tiW12: W1 :&: W2 = 1%g.\n  have defW: W1 \\x W2 = W by rewrite dprodEY ?(centSS _ _ cWW).\n  right; exists S, T; exists S _ _ _ defW; split=> // [|M _ /b4[] // x].\n    by do 2?split; rewrite ?mFT_odd // /normedTI tiV nVW setTI /=.\n  by case=> <-; rewrite inE mem_orbit ?orbT.\nwlog {b2 T defT maxT} Stype2: S W1 W2 @W @V maxS defS cycW ntV / FTtype S == 2%N.\n  move=> IH; case/orP: b2 cycW ntV => /IH; first exact.\n  by rewrite setIC /V /W /= joingC setUC; apply.\nhave{maxS Stype2 defS} prW1: prime #|W1|.\n  have [U ? W1x ? ? [[StypeP _ prW1x _] _ _ _ _]] := FTtypeP 2 maxS Stype2.\n  by have /imsetP[x _ ->] := of_typeP_compl_conj StypeP defS; rewrite cardJg.\nrewrite prime_TIg //; apply: contra ntV => sW12.\nby rewrite setD_eq0 (setUidPr sW12) join_subG sW12 /=.\nQed.\n\n(* This is Peterfalvi (8.9). *)\n(* We state the lemma using the of_typeP predicate, as it is the Skolemised  *)\n(* form of Peterfalvi, Definition (8.4).                                     *)\nLemma typeP_pairW S T W W1 W2 (defW : W1 \\x W2 = W) :\n  typeP_pair S T defW -> exists U : {group gT}, of_typeP S U defW.\nProof.\ncase=> [[[cycW _ /and3P[_ _ /eqP nVW]] maxS _] [defS _ defST] _ [Stype25 _] _].\nset S' := S^`(1)%g in defS; have [nsS'S _ _ _ tiS'W1] := sdprod_context defS.\nhave{Stype25} Stype'1: FTtype S != 1%N by apply: contraTneq Stype25 => ->.\nhave [/mulG_sub[sW1W sW2W] [_ mulW12 cW12 _]] := (dprodW defW, dprodP defW).\nhave [cycW1 cycW2] := (cyclicS sW1W cycW, cyclicS sW2W cycW).\nhave{cycW1 cycW2} coW12: coprime #|W1| #|W2| by rewrite -(cyclic_dprod defW).\nhave{maxS Stype'1} [Ux Wx W1x W2x defWx StypeP] := FTtypeP_witness maxS Stype'1.\nhave /imsetP[y Sy defW1] := of_typeP_compl_conj StypeP defS.\nsuffices defW2: W2 :=: W2x :^ y.\n  have [] := conj_of_typeP StypeP y; rewrite -defWx dprodJ -defW1 -defW2.\n  by rewrite (conjGid Sy) {-1}defW; exists (Ux :^ y)%G.\nhave [[_ hallW1x _ defSx] _ _ [/cyclic_abelian abW2x _ _ _ _] _] := StypeP.\nhave{Sy} nS'y: y \\in 'N(S') by rewrite (subsetP (normal_norm nsS'S)).\nhave{nS'y} defW2xy: W2x :^ y = 'C_S'(W1).\n  by rewrite -(typeP_cent_compl StypeP) conjIg -centJ -defW1 (normP nS'y).\nhave{nsS'S} sW2S': W2 \\subset S'.\n  have sW2S: W2 \\subset S by rewrite (subset_trans sW2W) // -defST subsetIl.\n  have{hallW1x} hallW1: \\pi(W1).-Hall(S) W1x by rewrite defW1 /= cardJg Hall_pi.\n  have hallS': \\pi(W1)^'.-Hall(S) S' by apply/(sdprod_normal_pHallP _ hallW1).\n  by rewrite coprime_pi' // (sub_normal_Hall hallS') in coW12 *.\nhave sW2xy: W2 \\subset W2x :^ y by rewrite defW2xy subsetI sW2S'.\nhave defW2: W2 :=: S' :&: W by rewrite -mulW12 -group_modr ?tiS'W1 ?mul1g.\napply/eqP; rewrite eqEsubset sW2xy defW2 subsetI {1}defW2xy subsetIl /=.\nrewrite -nVW /= setTI cents_norm // (centsS (subsetDl _ _)) // -mulW12.\nby rewrite centM subsetI {1}defW2xy subsetIr sub_abelian_cent // abelianJ.\nQed.\n\nSection OneMaximal.\n\nVariable M U W W1 W2 : {group gT}. (* W, W1 and W2 are only used later. *)\nHypothesis maxM : M \\in 'M.\n\n(* Peterfalvi, Definition (8.10) is covered in BGsection16. *)\n\n(* This is Peterfalvi (8.11). *)\nLemma FTcore_facts :\n [/\\ Hall G M`_\\F, Hall G M`_\\s\n   & forall S, Sylow M`_\\s S -> S :!=: 1%g -> 'N(S) \\subset M].\nProof.\nhave hallMs := Msigma_Hall_G maxM; have [_ sMs _] := and3P hallMs.\nrewrite def_FTcore // (pHall_Hall hallMs).\nsplit=> // [|S /SylowP[p _ sylS] ntS].\n  have sMF_Ms:= Fcore_sub_Msigma maxM.\n  apply: (@pHall_Hall _ \\pi(M`_\\F)); apply: (subHall_Hall hallMs).\n    by move=> p /(piSg sMF_Ms)/(pnatPpi sMs).\n  exact: pHall_subl (pcore_sub _ M) (Fcore_Hall M).\nhave s_p: p \\in \\sigma(M).\n  by rewrite (pnatPpi sMs) // -p_rank_gt0 -(rank_Sylow sylS) rank_gt0.\nby apply: (norm_sigma_Sylow s_p); apply: (subHall_Sylow (Msigma_Hall maxM)).\nQed.\n\n(* This is Peterfalvi (8.12). *)\n(* (b) could be stated for subgroups of U wlog -- usage should be checked.   *)\nLemma FTtypeI_II_facts n (H := M`_\\F) :\n    FTtype M == n -> H ><| U = M ^`(n.-1)%g ->\n  if 0 < n <= 2 then\n  [/\\ (*a*) forall p S, p.-Sylow(U) S -> abelian S /\\ ('r(S) <= 2)%N,\n      (*b*) forall X, X != set0 -> X \\subset U^# -> 'C_H(X) != 1%g ->\n            'M('C(X)) = [set M]\n    & (*c*) let B := 'A(M) :\\: 'A1(M) in B != set0 -> normedTI B G M\n  ] else True.\nProof.\nmove=> typeM defMn; have [n12 | //] := ifP; rewrite -mem_iota !inE in n12.\nhave defH: H = M`_\\sigma.\n  by rewrite -def_FTcore -?(Fcore_eq_FTcore _ _) // (eqP typeM) !inE orbA n12.\nhave [K complU]: exists K : {group gT}, kappa_complement M U K.\n  have [[V K] /= complV] := kappa_witness maxM.\n  have [[hallV hallK gVK] [_ sUMn _ _ _]] := (complV, sdprod_context defMn).\n  have hallU: \\sigma_kappa(M)^'.-Hall(M) U.\n    rewrite pHallE -(card_Hall hallV) (subset_trans sUMn) ?der_sub //=.\n    rewrite -(@eqn_pmul2l #|H|) ?cardG_gt0 // (sdprod_card defMn) defH.\n    rewrite (sdprod_card (sdprod_FTder maxM complV)) (eqP typeM).\n    by case/pred2P: n12 => ->.\n  have [x Mx defU] := Hall_trans (mmax_sol maxM) hallU hallV.\n  exists (K :^ x)%G; split; rewrite ?pHallJ // defU -conjsMg.\n  by rewrite -(gen_set_id gVK) groupP.\nhave [part_a _ _ [part_b part_c]] := BGsummaryB maxM complU.\nrewrite eqEsubset FTsupp1_sub // andbT -setD_eq0 in part_c.\nsplit=> // X notX0 /subsetD1P[sXU notX1]; rewrite -cent_gen defH.\napply: part_b; rewrite -?subG1 ?gen_subG //.\nby rewrite -setD_eq0 setDE (setIidPl _) // subsetC sub1set inE.\nQed.\n\n(* This is Peterfalvi (8.13). *)\n(* We have substituted the B & G notation for the unique maximal supergroup   *)\n(* of 'C[x], and specialized the lemma to X := 'A0(M).                        *)\nLemma FTsupport_facts (X := 'A0(M)) (D := [set x in X | ~~('C[x] \\subset M)]) :\n  [/\\ (*a*) {in X &, forall x, {subset x ^: G <= x ^: M}},\n      (*b*) D \\subset 'A1(M) /\\ {in D, forall x, 'M('C[x]) = [set 'N[x]]}\n    & (*c*) {in D, forall x (L := 'N[x]) (H := L`_\\F),\n        [/\\ (*c1*) H ><| (M :&: L) = L /\\ 'C_H[x] ><| 'C_M[x] = 'C[x],\n            (*c2*) {in X, forall y, coprime #|H| #|'C_M[y]| },\n            (*c3*) x \\in 'A(L) :\\: 'A1(L)\n          & (*c4*) 1 <= FTtype L <= 2\n                /\\ (FTtype L == 2%N -> [Frobenius M with kernel M`_\\F])]}].\nProof.\nhave defX: X \\in pred2 'A(M) 'A0(M) by rewrite !inE eqxx orbT.\nhave [sDA1 part_a part_c] := BGsummaryII maxM defX.\nhave{} part_a: {in X &, forall x, {subset x ^: G <= x ^: M}}.\n  move=> x y A0x A0y /= /imsetP[g Gg def_y]; rewrite def_y.\n  by apply/imsetP/part_a; rewrite -?def_y.\ndo [split=> //; first split=> //] => x /part_c[_ ] //.\nrewrite /= -(mem_iota 1) !inE => -> [-> ? -> -> L2_frob].\nby do 2![split=> //] => /L2_frob[E /FrobeniusWker].\nQed.\n\n(* A generic proof of the first assertion of Peterfalvi (8.15). *)\nLet norm_FTsuppX A :\n  M \\subset 'N(A) -> 'A1(M) \\subset A -> A \\subset 'A0(M) -> 'N(A) = M.\nProof.\nmove=> nAM sA1A sAA0; apply: mmax_max => //.\nrewrite (sub_proper_trans (norm_gen _)) ?mFT_norm_proper //; last first.\n  rewrite (sub_proper_trans _ (mmax_proper maxM)) // gen_subG.\n  by rewrite (subset_trans sAA0) // (subset_trans (FTsupp0_sub M)) ?subsetDl.\nrewrite (subG1_contra (genS sA1A)) //= genD1 ?group1 //.\nby rewrite genGid /= def_FTcore ?Msigma_neq1.\nQed.\n\nLemma norm_FTsupp1 : 'N('A1(M)) = M.\nProof. exact: norm_FTsuppX (FTsupp1_norm M) _ (FTsupp1_sub0 maxM). Qed.\n\nLemma norm_FTsupp : 'N('A(M)) = M.\nProof. exact: norm_FTsuppX (FTsupp_norm M) (FTsupp1_sub _) (FTsupp_sub0 M). Qed.\n\nLemma norm_FTsupp0 : 'N('A0(M)) = M.\nProof. exact: norm_FTsuppX (FTsupp0_norm M) (FTsupp1_sub0 _) _. Qed.\n\nLemma FTsignalizerJ x y : 'R_(M :^ x) (y ^ x) :=: 'R_M y :^ x.\nProof.\nrewrite /'R__ /= {1}cent1J conjSg; case: ifP => _ /=; first by rewrite conjs1g.\nby rewrite cent1J FT_signalizer_baseJ FcoreJ -conjIg.\nQed.\n\nLet is_FTsignalizer : is_Dade_signalizer G M 'A0(M) 'R_M.\nProof.\nrewrite /'R_M => x A0x /=; rewrite setTI.\ncase: ifPn => [sCxM | not_sCxM]; first by rewrite sdprod1g (setIidPr sCxM).\nby have [_ _ /(_ x)[| [] //]] := FTsupport_facts; apply/setIdP.\nQed.\n\n(* This is Peterfalvi (8.15), second assertion. *)\nLemma FT_Dade0_hyp : Dade_hypothesis G M 'A0(M).\nProof.\nhave [part_a _ parts_bc] := FTsupport_facts.\nhave /subsetD1P[sA0M notA0_1] := FTsupp0_sub M.\nsplit; rewrite // /normal ?sA0M ?norm_FTsupp0 //=.\nexists 'R_M => [|x y A0x A0y]; first exact: is_FTsignalizer.\nrewrite /'R_M; case: ifPn => [_ | not_sCxM]; first by rewrite cards1 coprime1n.\nrewrite (coprimeSg (subsetIl _ _)) //=.\nby have [| _ -> //] := parts_bc x; apply/setIdP.\nQed.\n\nDefinition FT_Dade_hyp :=\n  restr_Dade_hyp FT_Dade0_hyp (FTsupp_sub0 M) (FTsupp_norm M).\n\nDefinition FT_Dade1_hyp :=\n  restr_Dade_hyp FT_Dade0_hyp (FTsupp1_sub0 maxM) (FTsupp1_norm M).\n\nDefinition FT_DadeF_hyp :=\n  restr_Dade_hyp FT_Dade0_hyp (Fcore_sub_FTsupp0 maxM) (normsD1 (gFnorm _ _)).\n\nLemma def_FTsignalizer0 : {in 'A0(M), Dade_signalizer FT_Dade0_hyp =1 'R_M}.\nProof. exact: def_Dade_signalizer. Qed.\n\nLemma def_FTsignalizer : {in 'A(M), Dade_signalizer FT_Dade_hyp =1 'R_M}.\nProof. exact: restr_Dade_signalizer def_FTsignalizer0. Qed.\n\nLemma def_FTsignalizer1 : {in 'A1(M), Dade_signalizer FT_Dade1_hyp =1 'R_M}.\nProof. exact: restr_Dade_signalizer def_FTsignalizer0. Qed.\n\nLemma def_FTsignalizerF : {in M`_\\F^#, Dade_signalizer FT_DadeF_hyp =1 'R_M}.\nProof. exact: restr_Dade_signalizer def_FTsignalizer0. Qed.\n\nLocal Notation tau := (Dade FT_Dade0_hyp).\nLocal Notation FT_Dade := (Dade FT_Dade_hyp).\nLocal Notation FT_Dade1 := (Dade FT_Dade1_hyp).\nLocal Notation FT_DadeF := (Dade FT_DadeF_hyp).\n\nLemma FT_DadeE : {in 'CF(M, 'A(M)), FT_Dade =1 tau}.\nProof. exact: restr_DadeE. Qed.\n\nLemma FT_Dade1E : {in 'CF(M, 'A1(M)), FT_Dade1 =1 tau}.\nProof. exact: restr_DadeE. Qed.\n\nLemma FT_DadeF_E : {in 'CF(M, M`_\\F^#), FT_DadeF =1 tau}.\nProof. exact: restr_DadeE. Qed.\n\nLemma FT_Dade_supportS A B : A \\subset B -> 'A~(M, A) \\subset 'A~(M, B).\nProof.\nby move/subsetP=> sAB; apply/bigcupsP=> x Ax; rewrite (bigcup_max x) ?sAB.\nQed.\n\nLemma FT_Dade0_supportE : Dade_support FT_Dade0_hyp = 'A0~(M).\nProof. by apply/eq_bigr=> x /def_FTsignalizer0 <-. Qed.\n\nLet defA A (sAA0 : A \\subset 'A0(M)) (nAM : M \\subset 'N(A)) :\n  Dade_support (restr_Dade_hyp FT_Dade0_hyp sAA0 nAM) = 'A~(M, A).\nProof.\nby apply/eq_bigr=> x /(restr_Dade_signalizer sAA0 nAM def_FTsignalizer0) <-.\nQed.\n\nLemma FT_Dade_supportE : Dade_support FT_Dade_hyp = 'A~(M).\nProof. exact: defA. Qed.\n\nLemma FT_Dade1_supportE : Dade_support FT_Dade1_hyp = 'A1~(M).\nProof. exact: defA. Qed.\n\nLemma FT_DadeF_supportE : Dade_support FT_DadeF_hyp = 'A~(M, M`_\\F^#).\nProof. exact: defA. Qed.\n\nLemma FT_Dade0_supportJ x : 'A0~(M :^ x) = 'A0~(M).\nProof.\nrewrite /'A0~(_) FTsupp0J big_imset /=; last exact: in2W (conjg_inj x).\napply: eq_bigr => y _; rewrite FTsignalizerJ -conjg_set1 -conjsMg.\nby rewrite class_supportGidl ?inE.\nQed.\n\nLemma FT_Dade1_supportJ x : 'A1~(M :^ x) = 'A1~(M).\nProof.\nrewrite /'A1~(_) FTsupp1J big_imset /=; last exact: in2W (conjg_inj x).\napply: eq_bigr => y _; rewrite FTsignalizerJ -conjg_set1 -conjsMg.\nby rewrite class_supportGidl ?inE.\nQed.\n\nLemma FT_Dade_supportJ x : 'A~(M :^ x) = 'A~(M).\nProof.\nrewrite /'A~(_) FTsuppJ big_imset /=; last exact: in2W (conjg_inj x).\napply: eq_bigr => y _; rewrite FTsignalizerJ -conjg_set1 -conjsMg.\nby rewrite class_supportGidl ?inE.\nQed.\n\n(* Subcoherence and cyclicTI properties of type II-V subgroups. *)\nHypotheses (defW : W1 \\x W2 = W) (MtypeP : of_typeP M U defW).\nLet H := M`_\\F%G.\nLet K := M^`(1)%G.\n\nLemma FT_cyclicTI_hyp : cyclicTI_hypothesis G defW.\nProof. by case/typeP_context: MtypeP. Qed.\nLet ctiW := FT_cyclicTI_hyp.\n\n(* This is a useful combination of Peterfalvi (8.8) and (8.9). *)\nLemma FTtypeP_pair_witness :\n  exists2 T, typeP_pair M T defW\n     & exists xdefW : W2 \\x W1 = W, exists V : {group gT}, of_typeP T V xdefW.\nProof.\nhave Mtype'1 := FTtypeP_neq1 maxM MtypeP.\ncase: FTtypeP_pair_cases => [/(_ M maxM)/idPn[] // | [S [T]]].\ncase=> _ Wx W1x W2x defWx pairST.\nwithout loss /imsetP[y2 _ defSy]: S T W1x W2x defWx pairST / gval M \\in S :^: G.\n  have [_ _ _ _ coverST] := pairST => IH.\n  have /setUP[] := coverST M maxM Mtype'1; first exact: IH pairST.\n  by apply: IH (typeP_pair_sym _ pairST); rewrite dprodC.\nhave [U_S StypeP] := typeP_pairW pairST.\nhave [[_ maxS maxT] [defS defT defST] b2 b3 b4] := pairST.\nhave [[[_ _ _ defM] _ _ _ _] defW2] := (MtypeP, typeP_cent_compl MtypeP).\nhave /imsetP[y1 Sy1 /(canRL (conjsgKV _)) defW1]: W1 :^ y2^-1 \\in W1x :^: S.\n  apply: (of_typeP_compl_conj StypeP).\n  by rewrite -(conjsgK y2 S) -defSy derJ -sdprodJ defM.\npose y := (y1 * y2)%g; rewrite -conjsgM -/y in defW1.\nhave{} defSy: S :^ y = M by rewrite conjsgM (conjGid Sy1).\nhave{} defW2: W2 :=: W2x :^ y.\n  by rewrite -(typeP_cent_compl StypeP) conjIg -derJ -centJ defSy -defW1.\nsuffices pairMTy: typeP_pair M (T :^ y) defW.\n  exists (T :^ y)%G => //; have xdefW: W2 \\x W1 = W by rewrite dprodC.\n  by exists xdefW; apply: typeP_pairW (typeP_pair_sym xdefW pairMTy).\ndo [split; rewrite ?defM -?defSy ?mmaxJ ?FTtypeJ //] => [|L maxL /(b4 L maxL)].\n  by rewrite -defW defW1 defW2 derJ -sdprodJ -dprodJ -conjIg defT defST defWx.\nby rewrite !conjugates_conj lcoset_id // inE.\nQed.\n\n(* A converse to the above. *)\nLemma of_typeP_pair (xdefW : W2 \\x W1 = W) T V :\n  T \\in 'M -> of_typeP T V xdefW -> typeP_pair M T defW.\nProof.\nhave [S pairMS [xdefW' [V1 StypeP]]] := FTtypeP_pair_witness => maxT TtypeP.\nhave [[cycW2 /andP[sW2T _] ntW2 _] _ _ [cycW1 _ _ sW1T'' _] _] := TtypeP.\nhave{sW1T'' sW2T} sWT: W \\subset T.\n  by rewrite -(dprodW defW) mul_subG ?(subset_trans sW1T'') ?gFsub.\nhave [cycW _ /and3P[_ _ /eqP defNW]] := ctiW.\nrewrite (@group_inj _ T S) //; have{pairMS} [_ _ _ _ defT] := pairMS.\nhave /defT/setUP[] := FTtypeP_neq1 maxT TtypeP => {defT}// /imsetP[x _ defT].\n  have [defWx] := conj_of_typeP MtypeP x; rewrite -defT.\n  case/(of_typeP_conj TtypeP)=> y [_ _ _ defW1y _].\n  have /idP[]:= negbF cycW; rewrite (cyclic_dprod defW) // /coprime.\n  by rewrite -(cardJg _ y) defW1y cardJg gcdnn -trivg_card1.\nhave [defWx] := conj_of_typeP StypeP x; rewrite -defT.\ncase/(of_typeP_conj TtypeP)=> y [Ty _ defW2y defW1y defWy].\nhave Wyx: (y * x^-1)%g \\in W.\n  by rewrite -defNW !inE /= conjDg conjUg !conjsgM defW2y defW1y defWy !conjsgK.\nby rewrite -(conjGid (subsetP sWT _ Wyx)) conjsgM (conjGid Ty) defT conjsgK.\nQed.\n\nLemma FT_primeTI_hyp : primeTI_hypothesis M K defW.\nProof.\nhave [[cycW1 ntW1 hallW1 defM] _ _ [cycW2 ntW2 _ sW2M'' prM'W1] _] := MtypeP.\nby split; rewrite ?mFT_odd // (subset_trans sW2M'') ?der_subS.\nQed.\nLet ptiWM := FT_primeTI_hyp.\n\nLemma FTtypeP_supp0_def :\n  'A0(M) = 'A(M) :|: class_support (cyclicTIset defW) M.\nProof.\nrewrite -(setID 'A0(M) 'A(M)) (FTsupp0_typeP maxM MtypeP) (setIidPr _) //.\nexact: FTsupp_sub0.\nQed.\n\nFact FT_Fcore_prime_Dade_def : prime_Dade_definition M K H 'A(M) 'A0(M) defW.\nProof.\nhave [_ [_ _ _ /sdprodW/mulG_sub[sHK _]] _ [_ _ sW2H _ _] _] := MtypeP.\nsplit; rewrite ?gFnormal //; last exact: FTtypeP_supp0_def.\nrewrite /normal FTsupp_norm andbT /'A(M) (FTtypeP_neq1 maxM MtypeP) /=.\ndo ?split=> //; apply/bigcupsP=> x A1x; last by rewrite setSD ?subsetIl.\n  by rewrite setDE -setIA subIset // gFsub.\nby rewrite (bigcup_max x) // (subsetP _ x A1x) // setSD ?Fcore_sub_FTcore.\nQed.\n\nDefinition FT_prDade_hypF : prime_Dade_hypothesis _ M K H 'A(M) 'A0(M) defW :=\n  PrimeDadeHypothesis ctiW ptiWM FT_Dade0_hyp FT_Fcore_prime_Dade_def.\n\nFact FT_core_prime_Dade_def : prime_Dade_definition M K M`_\\s 'A(M) 'A0(M) defW.\nProof.\nhave [[_ sW2H sHK] [nsAM sCA sAK] defA0] := FT_Fcore_prime_Dade_def.\nhave [_ [_ sW2K _ _] _] := ptiWM.\nsplit=> //=; first by rewrite FTcore_normal /M`_\\s; case: ifP.\nrewrite nsAM /= /'A(M) /M`_\\s (FTtypeP_neq1 maxM MtypeP); split=> //=.\nby apply/bigcupsP=> x _; rewrite setSD ?subsetIl.\nQed.\n\nDefinition FT_prDade_hyp : prime_Dade_hypothesis _ M K M`_\\s 'A(M) 'A0(M) defW\n  := PrimeDadeHypothesis ctiW ptiWM FT_Dade0_hyp FT_core_prime_Dade_def.\n\nLet calS := seqIndD K M M`_\\s 1.\n\nFact FTtypeP_cohererence_base_subproof : cfConjC_subset calS calS.\nProof. exact: seqInd_conjC_subset1. Qed.\n\nFact FTtypeP_cohererence_nonreal_subproof : ~~ has cfReal calS.\nProof. by rewrite seqInd_notReal ?mFT_odd ?FTcore_sub_der1 ?der_normal. Qed.\n\nDefinition FTtypeP_coh_base_sig :=\n  prDade_subcoherent FT_prDade_hyp\n    FTtypeP_cohererence_base_subproof FTtypeP_cohererence_nonreal_subproof.\n\nDefinition FTtypeP_coh_base := sval FTtypeP_coh_base_sig.\n\nLocal Notation R := FTtypeP_coh_base.\n\nLemma FTtypeP_subcoherent : subcoherent calS tau R.\nProof. by rewrite /R; case: FTtypeP_coh_base_sig => R1 []. Qed.\nLet scohS := FTtypeP_subcoherent.\n\nLet w_ i j := cyclicTIirr defW i j.\nLet sigma := cyclicTIiso ctiW.\nLet eta_ i j := sigma (w_ i j).\nLet mu_ := primeTIred ptiWM.\nLet delta_ := fun j => primeTIsign ptiWM j.\n\nLemma FTtypeP_base_ortho :\n  {in [predI calS & irr M] & irr W, forall phi w, orthogonal (R phi) (sigma w)}.\nProof. by rewrite /R; case: FTtypeP_coh_base_sig => R1 []. Qed.\n\nLemma FTtypeP_base_TIred :\n  let dsw j k := [seq delta_ j *: eta_ i k | i : Iirr W1] in\n  let Rmu j := dsw j j ++ map -%R (dsw j (conjC_Iirr j)) in\n  forall j, R (mu_ j) = Rmu j.\nProof. by rewrite /R; case: FTtypeP_coh_base_sig => R1 []. Qed.\n\nLemma coherent_ortho_cycTIiso calS1 (tau1 : {additive 'CF(M) -> 'CF(G)}) :\n    cfConjC_subset calS1 calS -> coherent_with calS1 M^# tau tau1 ->\n  forall chi i j, chi \\in calS1 -> chi \\in irr M -> '[tau1 chi, eta_ i j] = 0.\nProof.\nmove=> ccsS1S cohS1 chi i j S1chi chi_irr; have [_ sS1S _] := ccsS1S.\nhave [e /mem_subseq Re ->] := mem_coherent_sum_subseq scohS ccsS1S cohS1 S1chi.\nrewrite cfdot_suml big1_seq // => xi /Re; apply: orthoPr.\nby apply: FTtypeP_base_ortho (mem_irr _); rewrite !inE sS1S.\nQed.\n\nImport ssrnum Num.Theory.\n\n(* A reformuation of Peterfalvi (5.8) for the Odd Order proof context. *)\nLemma FTtypeP_coherent_TIred calS1 tau1 zeta j :\n    cfConjC_subset calS1 calS -> coherent_with calS1 M^# tau tau1 ->\n    zeta \\in irr M -> zeta \\in calS1 -> mu_ j \\in calS1 ->\n    let d := primeTI_Isign ptiWM j in let k := conjC_Iirr j in\n  {dk : bool * Iirr W2 | tau1 (mu_ j) = (-1) ^+ dk.1 *: (\\sum_i eta_ i dk.2)\n    &   dk.1 = d /\\ dk.2 = j\n    \\/  [/\\ dk.1 = ~~ d, dk.2 = k\n        & forall l, mu_ l \\in calS1 -> mu_ l 1%g = mu_ j 1%g -> pred2 j k l]}.\nProof.\nmove=> ccsS1S cohS1 irr_zeta S1zeta S1mu_j d k.\nhave irrS1: [/\\ ~~ has cfReal calS1, has (mem (irr M)) calS1 & mu_ j \\in calS1].\n  have [[_ -> _] _ _ _ _] := subset_subcoherent scohS ccsS1S.\n  by split=> //; apply/hasP; exists zeta.\nhave Dmu := coherent_prDade_TIred FT_prDade_hyp ccsS1S irrS1 cohS1.\nrewrite -/mu_ -/d in Dmu; pose mu_sum d1 k1 := (-1) ^+ d1 *: (\\sum_i eta_ i k1).\nhave mu_sumK (d1 d2 : bool) k1 k2:\n  ('[mu_sum d1 k1, (-1) ^+ d2 *: eta_ 0 k2] > 0) = (d1 == d2) && (k1 == k2).\n- rewrite cfdotZl cfdotZr rmorph_sign mulrA -signr_addb cfdot_suml.\n  rewrite (bigD1 0) //= cfdot_cycTIiso !eqxx big1 => [|i nz_i]; last first.\n    by rewrite cfdot_cycTIiso (negPf nz_i).\n  rewrite addr0 /= andbC; case: (k1 == k2); rewrite ?mulr0 ?ltrr //=.\n  by rewrite mulr1 signr_gt0 negb_add.\nhave [dk tau1mu_j]: {dk : bool * Iirr W2 | tau1 (mu_ j) = mu_sum dk.1 dk.2}.\n  apply: sig_eqW; case: Dmu => [-> | [-> _]]; first by exists (d, j).\n  by exists (~~ d, k); rewrite -signrN.\nexists dk => //; have:= mu_sumK dk.1 dk.1 dk.2 dk.2; rewrite !eqxx -tau1mu_j.\ncase: Dmu => [-> | [-> all_jk]];\n  rewrite -?signrN mu_sumK => /andP[/eqP <- /eqP <-]; [by left | right].\nby split=> // j1 S1j1 /(all_jk j1 S1j1)/pred2P.\nQed.\n\nLemma size_red_subseq_seqInd_typeP (calX : {set Iirr K}) calS1 :\n    uniq calS1 -> {subset calS1 <= seqInd M calX} ->\n    {subset calS1 <= [predC irr M]} ->\n  size calS1 = #|[set i : Iirr K | 'Ind 'chi_i \\in calS1]|.\nProof.\nmove=> uS1 sS1S redS1; pose h s := 'Ind[M, K] 'chi_s.\napply/eqP; rewrite cardE -(size_map h) -uniq_size_uniq // => [|xi]; last first.\n  apply/imageP/idP=> [[i] | S1xi]; first by rewrite inE => ? ->.\n  by have /seqIndP[s _ Dxi] := sS1S _ S1xi; exists s; rewrite ?inE -?Dxi.\napply/dinjectiveP; pose h1 xi := cfIirr (#|W1|%:R^-1 *: 'Res[K, M] xi).\napply: can_in_inj (h1) _ => s; rewrite inE => /redS1 red_s.\nhave cycW1: cyclic W1 by have [[]] := MtypeP.\nhave [[j /irr_inj->] | [/idPn[]//]] := prTIres_irr_cases ptiWM s.\nby rewrite /h cfInd_prTIres /h1 cfRes_prTIred scalerK ?neq0CG ?irrK.\nQed.\n\nEnd OneMaximal.\n\n(* This is Peterfalvi (8.16). *)\nLemma FTtypeII_ker_TI M :\n   M \\in 'M -> FTtype M == 2%N ->\n [/\\ normedTI 'A0(M) G M, normedTI 'A(M) G M & normedTI 'A1(M) G M].\nProof.\nmove=> maxM typeM; have [sA1A sAA0] := (FTsupp1_sub maxM, FTsupp_sub0 M).\nhave [sA10 sA0M] := (subset_trans sA1A sAA0, FTsupp0_sub M).\nhave nzA1: 'A1(M) != set0 by rewrite setD_eq0 def_FTcore ?subG1 ?Msigma_neq1.\nhave [nzA nzA0] := (subset_neq0 sA1A nzA1, subset_neq0 sA10 nzA1).\nsuffices nTI_A0: normedTI 'A0(M) G M.\n  by rewrite nTI_A0 !(normedTI_S _ _ _ nTI_A0) // ?FTsupp_norm ?FTsupp1_norm.\nhave [U W W1 W2 defW [[MtypeP _ _ tiFM] _ _ _ _]] := FTtypeP 2 maxM typeM.\napply/(Dade_normedTI_P (FT_Dade0_hyp maxM)); split=> // x A0x.\nrewrite /= def_FTsignalizer0 /'R_M //=; have [// | not_sCxM] := ifPn.\nhave [y cxy /negP[]] := subsetPn not_sCxM.\napply: subsetP cxy; rewrite -['C[x]]setTI (cent1_normedTI tiFM) //.\nhave /setD1P[ntx Ms_x]: x \\in 'A1(M).\n  by have [_ [/subsetP-> // ]] := FTsupport_facts maxM; apply/setIdP.\nrewrite !inE ntx (subsetP (Fcore_sub_Fitting M)) //.\nby rewrite (Fcore_eq_FTcore _ _) ?(eqP typeM).\nQed.\n\n(* This is Peterfalvi, Theorem (8.17). *)\nTheorem FT_Dade_support_partition :\n  [/\\ (*a1*)\n           \\pi(G) =i [pred p | [exists M : {group gT} in 'M, p \\in \\pi(M`_\\s)]],\n      (*a2*) {in 'M &, forall M L,\n                gval L \\notin M :^: G -> coprime #|M`_\\s| #|L`_\\s| },\n      (*b*) {in 'M, forall M, #|'A1~(M)| = (#|M`_\\s|.-1 * #|G : M|)%N}\n    & (*c*) let PG := [set 'A1~(Mi) | Mi : {group gT} in 'M^G] in\n       [/\\ {in 'M^G &, injective (fun M => 'A1~(M))},\n           all_FTtype1 -> partition PG G^#\n         & forall S T W W1 W2 (defW : W1 \\x W2 = W),\n             let VG := class_support (cyclicTIset defW) G in\n           typeP_pair S T defW -> partition (VG |: PG) G^# /\\ VG \\notin PG]].\nProof.\nhave defDsup M: M \\in 'M -> class_support M^~~ G = 'A1~(M).\n  move=> maxM; rewrite class_supportEr /'A1~(M) /'A1(M) def_FTcore //.\n  rewrite -(eq_bigr _ (fun _ _ => bigcupJ _ _ _ _)) exchange_big /=.\n  apply: eq_bigr => x Ms_x; rewrite -class_supportEr.\n  rewrite -norm_rlcoset ?(subsetP (cent_sub _)) ?cent_FT_signalizer //=.\n  congr (class_support (_ :* x) G); rewrite /'R_M.\n  have [_ _ /(_ x Ms_x)[_ defCx _] /(_ x Ms_x)defNF]:= BGsummaryD maxM.\n  have [sCxM | /defNF[[_ <-]] //] := ifPn.\n  apply/eqP; rewrite trivg_card1 -(eqn_pmul2r (cardG_gt0 'C_M[x])).\n  by rewrite (sdprod_card defCx) mul1n /= (setIidPr _).\nhave [b [a1 a2] [/and3P[_ _ not_PG_set0] _ _]] := BGsummaryE gT.\nsplit=> [p | M L maxM maxL /a2 | M maxM | {b a1 a2}PG].\n- apply/idP/exists_inP=> [/a1[M maxM sMp] | [M _]].\n    by exists M => //; rewrite def_FTcore // pi_Msigma.\n  exact: piSg (subsetT _) p.\n- move/(_ maxM maxL)=> coML; rewrite coprime_pi' // !def_FTcore //.\n  apply: sub_pgroup (pcore_pgroup _ L) => p; apply/implyP.\n  by rewrite implybN /= pi_Msigma // implybE -negb_and [_ && _]coML.\n- by rewrite -defDsup // def_FTcore // b.\nhave [/subsetP sMG_M _ injMG sM_MG] := mmax_transversalP gT.\nhave{PG} ->: PG = [set class_support M^~~ G | M : {group gT} in 'M].\n  apply/setP=> AG; apply/imsetP/imsetP=> [] [M maxM ->].\n    by move/sMG_M in maxM; exists M; rewrite ?defDsup //.\n  have [x MG_Mx] := sM_MG M maxM.\n  by exists (M :^ x)%G; rewrite // defDsup ?mmaxJ ?FT_Dade1_supportJ.\nhave [c1 c2] := mFT_partition gT.\nsplit=> [M H maxM maxH eq_MH | Gtype1 | S T W W1 W2 defW VG pairST].\n- apply: injMG => //; move/sMG_M in maxM; move/sMG_M in maxH.\n  apply/orbit_eqP/idPn => not_HG_M.\n  have /negP[]: ~~ [disjoint 'A1~(M) & 'A1~(H)].\n   rewrite eq_MH -setI_eq0 setIid -defDsup //.\n   by apply: contraNneq not_PG_set0 => <-; apply: imset_f.\n  rewrite -!defDsup // -setI_eq0 class_supportEr big_distrl -subset0.\n  apply/bigcupsP=> x /class_supportGidr <- /=; rewrite -conjIg sub_conjg conj0g.\n  rewrite class_supportEr big_distrr /=; apply/bigcupsP=> {}x _.\n  rewrite subset0 setI_eq0 -sigma_supportJ sigma_support_disjoint ?mmaxJ //.\n  by rewrite (orbit_transl _ (mem_orbit _ _ _)) ?in_setT // orbit_sym.\n- rewrite c1 // setD_eq0; apply/subsetP=> M maxM.\n  by rewrite FTtype_Fmax ?(forall_inP Gtype1).\nhave [[[cycW maxS _] _ _ _ _] [U_S StypeP]] := (pairST, typeP_pairW pairST).\nhave Stype'1 := FTtypeP_neq1 maxS StypeP.\nhave maxP_S: S \\in TypeP_maxgroups _ by rewrite FTtype_Pmax.\nhave hallW1: \\kappa(S).-Hall(S) W1.\n  have [[U1 K] /= complU1] := kappa_witness maxS.\n  have ntK: K :!=: 1%g by rewrite -(trivgPmax maxS complU1).\n  have [[defS_K _ _] [//|defS' _] _ _ _] := kappa_structure maxS complU1.\n  rewrite {}defS' in defS_K.\n  have /imsetP[x Sx defK] := of_typeP_compl_conj StypeP defS_K.\n  by have [_ hallK _] := complU1; rewrite defK pHallJ in hallK.\nhave{cycW} [[ntW1 ntW2] [cycW _ _]] := (cycTI_nontrivial cycW, cycW).\nsuffices defW2: 'C_(S`_\\sigma)(W1) = W2.\n  by have [] := c2 _ _ maxP_S hallW1; rewrite defW2 /= (dprodWY defW).\nhave [U1 complU1] := ex_kappa_compl maxS hallW1.\nhave [[_ [_ _ sW2'F] _] _ _ _] := BGsummaryC maxS complU1 ntW1.\nrewrite -(setIidPr sW2'F) setIA (setIidPl (Fcore_sub_Msigma maxS)).\nexact: typeP_cent_core_compl StypeP.\nQed.\n\n(* This is Peterfalvi (8.18). Note that part (a) is not actually used later. *)\nLemma FT_Dade_support_disjoint S T :\n    S \\in 'M -> T \\in 'M -> gval T \\notin S :^: G ->\n  [/\\ (*a*) FTsupports S T = ~~ [disjoint 'A1(S) & 'A(T)]\n         /\\ {in 'A1(S) :&: 'A(T), forall x,\n               ~~ ('C[x] \\subset S) /\\ 'C[x] \\subset T},\n      (*b*) [exists x, FTsupports S (T :^ x)] = ~~ [disjoint 'A1~(S) & 'A~(T)]\n    & (*c*) [disjoint 'A1~(S) & 'A~(T)] \\/  [disjoint 'A1~(T) & 'A~(S)]].\nProof.\nmove: S T; pose NC S T := gval T \\notin S :^: G.\nhave part_a2 S T (maxS : S \\in 'M) (maxT : T \\in 'M) (ncST : NC S T) :\n  {in 'A1(S) :&: 'A(T), forall x, ~~ ('C[x] \\subset S) /\\ 'C[x] \\subset T}.\n- move=> x /setIP[/setD1P[ntx Ss_x] ATx].\n  have coxTs: coprime #[x] #|T`_\\s|.\n    apply: (coprime_dvdl (order_dvdG Ss_x)).\n    by have [_ ->] := FT_Dade_support_partition.\n  have [z /setD1P[ntz Ts_z] /setD1P[_ /setIP[Tn_x czx]]] := bigcupP ATx.\n  set n := FTtype T != 1%N in Tn_x.\n  have typeT: FTtype T == n.+1.\n    have notTs_x: x \\notin T`_\\s.\n      apply: contra ntx => Ts_x.\n      by rewrite -order_eq1 -dvdn1 -(eqnP coxTs) dvdn_gcd dvdnn order_dvdG.\n    apply: contraLR ATx => typeT; rewrite FTsupp_eq1 // ?inE ?ntx //.\n    move: (FTtype_range T) typeT; rewrite -mem_iota /n.\n    by do 5!case/predU1P=> [-> // | ].\n  have defTs: T`_\\s = T`_\\F.\n    by apply/esym/Fcore_eq_FTcore; rewrite // (eqP typeT); case n.\n  have [U Ux defTn]: exists2 U : {group gT}, x \\in U & T`_\\F ><| U = T^`(n)%g.\n    have [[U K] /= complU] := kappa_witness maxT.\n    have defTn: T`_\\s ><| U = T^`(n)%g.\n      by rewrite def_FTcore // (sdprod_FTder maxT complU).\n    have nsTsTn: T`_\\s <| T^`(n)%g by case/sdprod_context: defTn.\n    have [sTsTn nTsTn] := andP nsTsTn.\n    have hallTs: \\pi(T`_\\s).-Hall(T^`(n)%g) T`_\\s.\n      by rewrite defTs (pHall_subl _ (der_sub n T) (Fcore_Hall T)) //= -defTs.\n    have hallU: \\pi(T`_\\s)^'.-Hall(T^`(n)%g) U.\n      by apply/sdprod_Hall_pcoreP; rewrite /= (normal_Hall_pcore hallTs).\n    have solTn: solvable T^`(n)%g := solvableS (der_sub n T) (mmax_sol maxT).\n    rewrite coprime_sym coprime_pi' // in coxTs.\n    have [|y Tn_y] := Hall_subJ solTn hallU _ coxTs; rewrite cycle_subG //.\n    exists (U :^ y)%G; rewrite // -defTs.\n    by rewrite -(normsP nTsTn y Tn_y) -sdprodJ defTn conjGid.\n  have uniqCx: 'M('C[x]) = [set T].\n    have:= FTtypeI_II_facts maxT typeT defTn; rewrite !ltnS leq_b1 -cent_set1.\n    case=> _ -> //; first by rewrite -cards_eq0 cards1.\n      by rewrite sub1set !inE ntx.\n    by apply/trivgPn; exists z; rewrite //= -defTs inE Ts_z cent_set1 cent1C.\n  split; last by case/mem_uniq_mmax: uniqCx.\n  by apply: contra ncST => /(eq_uniq_mmax uniqCx maxS)->; apply: orbit_refl.\nhave part_a1 S T (maxS : S \\in 'M) (maxT : T \\in 'M) (ncST : NC S T) :\n  FTsupports S T = ~~ [disjoint 'A1(S) & 'A(T)].\n- apply/existsP/pred0Pn=> [[x /and3P[ASx not_sCxS sCxT]] | [x /andP[A1Sx Atx]]].\n    have [_ [/subsetP]] := FTsupport_facts maxS; set D := finset _.\n    have Dx: x \\in D by rewrite !inE ASx.\n    move=> /(_ x Dx) A1x /(_ x Dx)uniqCx /(_ x Dx)[_ _ /setDP[ATx _] _].\n    by rewrite (eq_uniq_mmax uniqCx maxT sCxT); exists x; apply/andP.\n  exists x; rewrite (subsetP (FTsupp1_sub maxS)) //=.\n  by apply/andP/part_a2=> //; apply/setIP.\nhave part_b S T (maxS : S \\in 'M) (maxT : T \\in 'M) (ncST : NC S T) :\n  [exists x, FTsupports S (T :^ x)] = ~~ [disjoint 'A1~(S) & 'A~(T)].\n- apply/existsP/pred0Pn=> [[x] | [y /andP[/= A1GSy AGTy]]].\n    rewrite part_a1 ?mmaxJ // => [/pred0Pn[y /andP/=[A1Sy ATyx]]|]; last first.\n      by rewrite /NC -(rcoset_id (in_setT x)) orbit_rcoset.\n    rewrite FTsuppJ mem_conjg in ATyx; exists (y ^ x^-1); apply/andP; split.\n      by apply/bigcupP; exists y => //; rewrite imset2_f ?rcoset_refl ?inE.\n    apply/bigcupP; exists (y ^ x^-1) => //.\n    by rewrite mem_class_support ?rcoset_refl.\n  have{AGTy} [x2 ATx2 x2R_yG] := bigcupP AGTy.\n  have [sCx2T | not_sCx2T] := boolP ('C[x2] \\subset T); last first.\n    have [_ _ _ [injA1G pGI pGP]] := FT_Dade_support_partition.\n    have{pGI pGP} tiA1g: trivIset [set 'A1~(M) | M : {group gT} in 'M^G].\n      case: FTtypeP_pair_cases => [/forall_inP/pGI/and3P[] // | [M [L]]].\n      by case=> _ W W1 W2 defW1 /pGP[]/and3P[_ /(trivIsetS (subsetUr _ _))].\n    have [_ _ injMG sM_MG] := mmax_transversalP gT.\n    have [_ [sDA1T _] _] := FTsupport_facts maxT.\n    have [[z1 maxSz] [z2 maxTz]] := (sM_MG S maxS, sM_MG T maxT).\n    case/imsetP: ncST; exists (z1 * z2^-1)%g; first by rewrite inE.\n    rewrite conjsgM; apply/(canRL (conjsgK _))/congr_group/injA1G=> //.\n    apply/eqP/idPn=> /(trivIsetP tiA1g)/pred0Pn[]; try exact: imset_f.\n    exists y; rewrite !FT_Dade1_supportJ /= A1GSy andbT.\n    by apply/bigcupP; exists x2; rewrite // (subsetP sDA1T) ?inE ?ATx2.\n  have{x2R_yG} /imsetP[z _ def_y]: y \\in x2 ^: G.\n    by rewrite /'R_T {}sCx2T mul1g class_support_set1l in x2R_yG.\n  have{A1GSy} [x1 A1Sx1] := bigcupP A1GSy; rewrite {y}def_y -mem_conjgV.\n  rewrite class_supportGidr ?inE {z}//.\n  case/imset2P=> _ z /rcosetP[y Hy ->] _ def_x2.\n  exists z^-1%g; rewrite part_a1 ?mmaxJ //; last first.\n    by rewrite /NC (orbit_transl _ (mem_orbit _ _ _)) ?inE.\n  apply/pred0Pn; exists x1; rewrite /= A1Sx1 FTsuppJ mem_conjgV; apply/bigcupP.\n  pose ddS := FT_Dade1_hyp maxS; have [/andP[sA1S _] _ notA1_1 _ _] := ddS.\n  have [ntx1 Sx1] := (memPn notA1_1 _ A1Sx1, subsetP sA1S _ A1Sx1).\n  have [coHS defCx1] := (Dade_coprime ddS A1Sx1 A1Sx1, Dade_sdprod ddS A1Sx1).\n  rewrite def_FTsignalizer1 // in coHS defCx1.\n  have[u Ts_u /setD1P[_ cT'ux2]] := bigcupP ATx2.\n  exists u => {Ts_u}//; rewrite 2!inE -(conj1g z) (can_eq (conjgK z)) ntx1.\n  suffices{u cT'ux2} ->: x1 = (y * x1).`_(\\pi('R_S x1)^').\n    by rewrite -consttJ -def_x2 groupX.\n  have /setIP[_ /cent1P cx1y]: y \\in 'C_G[x1].\n    by case/sdprod_context: defCx1 => /andP[/subsetP->].\n  rewrite consttM // (constt1P _) ?p_eltNK ?(mem_p_elt (pgroup_pi _)) // mul1g.\n  have piR'_Cx1: \\pi('R_S x1)^'.-group 'C_S[x1] by rewrite coprime_pi' in coHS.\n  by rewrite constt_p_elt ?(mem_p_elt piR'_Cx1) // inE Sx1 cent1id.\nmove=> S T maxS maxT ncST; split; first split; auto.\napply/orP/idPn; rewrite negb_or -part_b // => /andP[suppST /negP[]].\nwithout loss{suppST} suppST: T maxT ncST / FTsupports S T.\n  move=> IH; case/existsP: suppST => x /IH {IH}.\n  rewrite FT_Dade1_supportJ (orbit_transl _ (mem_orbit _ _ _)) ?in_setT //.\n  by rewrite mmaxJ => ->.\nhave{suppST} [y /and3P[ASy not_sCyS sCyT]] := existsP suppST.\nhave Dy: y \\in [set z in 'A0(S) | ~~ ('C[z] \\subset S)] by rewrite !inE ASy.\nhave [_ [_ /(_ y Dy) uCy]  /(_ y Dy)[_ coTcS _ typeT]] := FTsupport_facts maxS.\nrewrite -mem_iota -(eq_uniq_mmax uCy maxT sCyT) !inE in coTcS typeT.\napply/negbNE; rewrite -part_b /NC 1?orbit_sym // negb_exists.\napply/forallP=> x; rewrite part_a1 ?mmaxJ ?negbK //; last first.\n  by rewrite /NC (orbit_transl _ (mem_orbit _ _ _)) ?in_setT // orbit_sym.\nrewrite -setI_eq0 -subset0 FTsuppJ -bigcupJ big_distrr; apply/bigcupsP=> z Sxz.\nrewrite conjD1g /= -setDIl coprime_TIg ?setDv //= cardJg.\nrewrite -(Fcore_eq_FTcore maxT _) ?inE ?orbA; last by have [->] := typeT.\nby rewrite (coprimegS _ (coTcS z _)) ?(subsetP (FTsupp1_sub0 _)) ?setSI ?gFsub.\nQed.\n\n(* A corollary to the above, which Peterfalvi derives from (8.17a) (i.e.,     *)\n(* FT_Dade_support_partition) in the proof of (12.16).                        *)\nLemma FT_Dade1_support_disjoint S T :\n  S \\in 'M -> T \\in 'M -> gval T \\notin S :^: G -> [disjoint 'A1~(S) & 'A1~(T)].\nProof.\nmove=> maxS maxT /FT_Dade_support_disjoint[] // _ _ tiA1A.\nwithout loss{tiA1A maxT}: S T maxS / [disjoint 'A1~(T) & 'A~(S)].\n  by move=> IH_ST; case: tiA1A => /IH_ST; first rewrite disjoint_sym; apply.\nby rewrite disjoint_sym; apply/disjointWl/FT_Dade_supportS/FTsupp1_sub.\nQed.\n\nEnd Eight.\n\nNotation FT_Dade0 maxM := (Dade (FT_Dade0_hyp maxM)).\nNotation FT_Dade maxM := (Dade (FT_Dade_hyp maxM)).\nNotation FT_Dade1 maxM := (Dade (FT_Dade1_hyp maxM)).\nNotation FT_DadeF maxM := (Dade (FT_DadeF_hyp maxM)).\n\n", "meta": {"author": "math-comp", "repo": "odd-order", "sha": "663e1827836cf0dedebb99f0ab6b232bab9bffd0", "save_path": "github-repos/coq/math-comp-odd-order", "path": "github-repos/coq/math-comp-odd-order/odd-order-663e1827836cf0dedebb99f0ab6b232bab9bffd0/theories/PFsection8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.27988531156761826}}
{"text": "Require Import Raft.\nRequire Import RaftRefinementInterface.\nRequire Import RefinementCommonDefinitions.\n\nSection CandidateEntriesInterface.\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_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  Class candidate_entries_interface : Prop :=\n    {\n      candidate_entries_invariant :\n        forall (net : network),\n          refined_raft_intermediate_reachable net ->\n          CandidateEntries net\n    }.\nEnd CandidateEntriesInterface.", "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/CandidateEntriesInterface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2798607276250578}}
{"text": "(* This prqogram 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(*              Intensional Lambda Calculus                           *)\n(*                                                                    *)\n(* is implemented in Coq by adapting the implementation of            *) \n(* Lambda Calculus from Project Coq                                   *) \n(* 2015                                                               *)\n(**********************************************************************)\n\n(**********************************************************************)\n(*                        LamSF_Redexes.v                             *)\n(*                                                                    *)\n(* adapted from Redexes.v for Lambda Calculus                         *)\n(*                                                                    *)\n(*                          Barry Jay                                 *)\n(*                                                                    *)\n(**********************************************************************)\n\nRequire Import Arith.\nRequire Import General.\nRequire Import Test.\nRequire Import LamSF_Terms.\n\n(*****************************)\n(* Terms with marked redexes *)\n(*****************************)\n\nInductive redexes : Set :=\n  | Var : nat -> redexes \n  | Opp : operator -> redexes\n  | Ap : bool -> redexes -> redexes -> redexes\n  | Fun : redexes -> redexes\n.\n\n(* A redex is marked as (Ap true (Fun false M) N) *)\n\n(* The Boolean algebra of sets of redexes *)\n\nInductive sub : redexes -> redexes -> Prop := \n  | Sub_Var : forall i : nat, sub (Var i) (Var i)\n  | Sub_Oper : forall o, sub (Opp o) (Opp o)\n  | Sub_Ap1 :\n      forall U1 V1 : redexes,\n      sub U1 V1 ->\n      forall U2 V2 : redexes, \n      sub U2 V2 -> forall (b : bool), sub (Ap false U1 U2) (Ap b V1 V2)\n  | Sub_Ap2 :\n      forall U1 V1 : redexes,\n      sub U1 V1 ->\n      forall U2 V2 : redexes,\n      sub U2 V2 -> forall (b : bool), sub (Ap true U1 U2) (Ap true V1 V2)\n | Sub_Fun : forall U V , sub U V -> sub (Fun U) (Fun V)\n.\n\nHint Resolve Sub_Var Sub_Oper Sub_Fun Sub_Ap1 Sub_Ap2.\n\n\nDefinition bool_max (b b' : bool) :=\n  match b return bool with\n  | true => true\n  | false => b'\n  end.\n\nLemma max_false : forall b : bool, bool_max b false = b.\nProof.\nsimple induction b; simpl in |- *; trivial.\nQed.\n\nInductive union : redexes -> redexes -> redexes -> Prop :=\n  | Union_Var : forall i: nat, union (Var i) (Var i) (Var i)\n  | Union_Oper : forall o, union (Opp o) (Opp o) (Opp o)\n  | Union_Ap :\n      forall U1 V1 W1 : redexes,\n      union U1 V1 W1 ->\n      forall U2 V2 W2 : redexes,\n      union U2 V2 W2 ->\n      forall (b1 b2 : bool),\n      union (Ap b1 U1 U2) (Ap b2 V1 V2) (Ap (bool_max b1 b2) W1 W2)\n  | Union_Fun : forall U V W, union U V W -> union (Fun U) (Fun V) (Fun W)\n.\n\nHint Resolve Union_Var Union_Oper Union_Fun Union_Ap.\n\nLemma union_l : forall U V W : redexes, union U V W -> sub U W.\nProof.\nsimple induction 1; split_all. \nelim b1.\nelim b2; simpl in |- *; apply Sub_Ap2; trivial.\nelim b2; simpl in |- *; apply Sub_Ap1; trivial.\nQed.\n\nLemma union_r : forall U V W : redexes, union U V W -> sub V W.\nProof.\nsimple induction 1; split_all. \nelim b2.\nelim b1; simpl in |- *; apply Sub_Ap2; trivial.\nelim b1; simpl in |- *; apply Sub_Ap1; trivial.\nQed.\n\nLemma bool_max_Sym : forall b b' : bool, bool_max b b' = bool_max b' b.\nProof.\nsimple induction b; simple induction b'; simpl in |- *; trivial.\nQed.\n\nLemma union_sym : forall U V W : redexes, union U V W -> union V U W.\nProof.\nsimple induction 1; split_all.\nrewrite (bool_max_Sym b1 b2); split_all.\nQed.\n\n(* Compatibility *)\n(* (comp U V) iff (unmark U)=(unmark V) *)\n\nInductive comp : redexes -> redexes -> Prop :=\n  | Comp_Var : forall i: nat, comp (Var i) (Var i)\n  | Comp_Oper : forall o, comp (Opp o) (Opp o) \n  | Comp_Ap :\n      forall U1 V1 : redexes,\n      comp U1 V1 ->\n      forall U2 V2 : redexes,\n      comp U2 V2 -> forall (b1 b2 : bool), comp (Ap b1 U1 U2) (Ap b2 V1 V2)\n  | Comp_Fun : forall U V, comp U V -> comp (Fun U) (Fun V)\n.\nHint Resolve Comp_Var Comp_Oper Comp_Fun Comp_Ap.\n\nLemma comp_refl : forall U : redexes, comp U U.\nProof.\nsimple induction U; auto.\nQed.\n\nLemma comp_sym : forall U V : redexes, comp U V -> comp V U.\nProof.\nsimple induction 1; auto.\nQed.\n\nLemma comp_trans :\n forall U V : redexes,\n comp U V -> forall (W : redexes) (CVW : comp V W), comp U W.\nsimple induction 1; intros; inversion_clear CVW; auto.\nQed.\n\n\nLemma union_defined :\n forall U V : redexes, comp U V -> exists W : redexes, union U V W.\nProof. simple induction 1; split_all; eauto. Qed.\n\n\n(* A element of type redexes is said to be regular if its true marks label\n   redexes *)\n\n\nFixpoint regular (U : redexes) : Prop :=\n  match U with\n  | Var _ => True\n  | Opp _ => True\n  | Ap true (Fun _ as V) W => regular V /\\ regular W\n  | Ap true _ W => False\n  | Ap false V W => regular V /\\ regular W\n  | Fun V => regular V\n  end.\n\nLemma union_preserve_regular :\n forall U V W : redexes, union U V W -> regular U -> regular V -> regular W.\nProof.\nsimple induction 1; split_all. \ngen_case H4 b1. \ngen_case H5 b2.\ngen3_case H0 H1 H4 U1. \ngen3_case H0 H1 H5 V1. \ninversion H0; split_all; subst.  \nsimpl in *. \neapply2 H1. \n\ngen3_case H0 H1 H4 U1. \ninversion H0. subst; split_all. \n\ngen_case H5 b2.\ngen3_case H0 H1 H5 V1. \ninversion H0. subst; split_all. \nQed.\n\n\n\n\n\n", "meta": {"author": "Barry-Jay", "repo": "lambdaSF", "sha": "22a80d136e2986387e6c1e27b3872b39c974bcc1", "save_path": "github-repos/coq/Barry-Jay-lambdaSF", "path": "github-repos/coq/Barry-Jay-lambdaSF/lambdaSF-22a80d136e2986387e6c1e27b3872b39c974bcc1/LamSF_Redexes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.27977499079579654}}
{"text": "From Theories Require Import category.\nFrom Theories Require Import translation_fib.\n\nSet Primitive Projections.\nSet Universe Polymorphism.\nSet Polymorphic Inductive Cumulativity.\n\n(* contractibility of singletons *)\n\nRecord wedge_eq {p} \n  (A0 : @El0 p Type0)\n  (A1 : @El1 p Type0 Type1 A0)\n  (a0 : El0 A0)\n  (a1 : El1 A0 A1 a0)\n  (b0 : El0 A0)\n  (b1 : El1 A0 A1 b0)\n  (e0 : El0 (eq0 A0 A1 a0 a1 b0 b1))\n  (e1 : El1 _ (eq1 A0 A1 a0 a1 b0 b1) e0) : Type :=\nmkWE {\n  we_f0 : @El0 (S (S p)) (squish ∘ squish ⋅ A0) ;\n  we_f1 : @El1 (S (S p)) (squish ∘ squish ⋅ A0) (squish ∘ squish ⋅ A1) we_f0 ;\n  we_0y : side_0 ⋅ we_f0 ≡ squish ⋅ a0 ;\n  we_1y : side_1 ⋅ we_f0 ≡ ce_f0 (e0 p !) ;\n  we_x0 : promote side_0 ⋅ we_f0 ≡ squish ⋅ a0 ;\n  we_x1 : promote side_1 ⋅ we_f0 ≡ ce_f0 (e0 p !) ;\n}.\n\nArguments we_f0 {_ _ _ _ _ _ _ _ _}.\nArguments we_f1 {_ _ _ _ _ _ _ _ _}.\nArguments we_0y {_ _ _ _ _ _ _ _ _}.\nArguments we_1y {_ _ _ _ _ _ _ _ _}.\nArguments we_x0 {_ _ _ _ _ _ _ _ _}.\nArguments we_x1 {_ _ _ _ _ _ _ _ _}.\n\nDefinition we_funct {p} \n  (A0 : @El0 p Type0)\n  (A1 : @El1 p Type0 Type1 A0)\n  (a0 : El0 A0)\n  (a1 : El1 A0 A1 a0)\n  (b0 : El0 A0)\n  (b1 : El1 A0 A1 b0)\n  (e0 : El0 (eq0 A0 A1 a0 a1 b0 b1))\n  (e1 : El1 _ (eq1 A0 A1 a0 a1 b0 b1) e0) {q} (α : q ≤ p) :\n  wedge_eq A0 A1 a0 a1 b0 b1 e0 e1 -> wedge_eq (α ⋅ A0) (α ⋅ A1) (α ⋅ a0) (α ⋅ a1) (α ⋅ b0) (α ⋅ b1) (α ⋅ e0) (α ⋅ e1).\nProof.\nunshelve refine (fun x => _).\nunshelve econstructor.\n- exact (promote (promote α) ⋅ x.(we_f0)).\n- exact (promote (promote α) ⋅ x.(we_f1)).\n- refine (J_seqs _ _ (fun X _ => promote α ⋅ X ≡ _) (srefl _) _ (ssym (we_0y x))).\n- refine (J_seqs _ _ (fun X _ => promote α ⋅ X ≡ _) _ _ (ssym (we_1y x))).\n  refine (J_seqs _ (fun q α => ce_funct α (e0 p !)) (fun X _ => _ ≡ ce_f0 (X q α)) (srefl _) _ (ssym (e1 p !))).\n- refine (J_seqs _ _ (fun X _ => promote α ⋅ X ≡ _) (srefl _) _ (ssym (we_x0 x))).\n- refine (J_seqs _ _ (fun X _ => promote α ⋅ X ≡ _) _ _ (ssym (we_x1 x))).\n  refine (J_seqs _ (fun q α => ce_funct α (e0 p !)) (fun X _ => _ ≡ ce_f0 (X q α)) (srefl _) _ (ssym (e1 p !))).\nDefined.\n\nDefinition wedge_eqR {p}\n  (A0 : @El0 p Type0)\n  (A1 : @El1 p Type0 Type1 A0)\n  (a0 : El0 A0)\n  (a1 : El1 A0 A1 a0)\n  (b0 : El0 A0)\n  (b1 : El1 A0 A1 b0)\n  (e0 : El0 (eq0 A0 A1 a0 a1 b0 b1))\n  (e1 : El1 _ (eq1 A0 A1 a0 a1 b0 b1) e0) :\n (forall q (α : q ≤ p), wedge_eq (α ⋅ A0) (α ⋅ A1) (α ⋅ a0) (α ⋅ a1) (α ⋅ b0) (α ⋅ b1) (α ⋅ e0) (α ⋅ e1)) -> SProp :=\nfun s => s ≡ fun q α => we_funct A0 A1 a0 a1 b0 b1 e0 e1 α (s p !).\n\nDefinition contractor0 {p}\n  (A0 : @El0 p Type0)\n  (A1 : @El1 p Type0 Type1 A0)\n  (a0 : El0 A0)\n  (a1 : El1 A0 A1 a0)\n  (b0 : El0 A0)\n  (b1 : El1 A0 A1 b0)\n  (e0 : El0 (eq0 A0 A1 a0 a1 b0 b1))\n  (e1 : El1 _ (eq1 A0 A1 a0 a1 b0 b1) e0)\n  : @El0 p Type0.\nProof.\nrefine (fun q α => _). unshelve econstructor.\n- unshelve refine (fun r β => _).\n  exact (wedge_eq ((α ∘ β) · A0) ((α ∘ β) · A1) ((α ∘ β) · a0) ((α ∘ β) · a1) ((α ∘ β) · b0) ((α ∘ β) · b1) ((α ∘ β) · e0) ((α ∘ β) · e1)).\n- unshelve refine (fun r β s => _). simpl in s.\n  exact (wedge_eqR ((α ∘ β) · A0) ((α ∘ β) · A1) ((α ∘ β) · a0) ((α ∘ β) · a1) ((α ∘ β) · b0) ((α ∘ β) · b1) ((α ∘ β) · e0) ((α ∘ β) · e1) s).\n- refine (fun r β c s0 s1 => _). apply falso.\n- refine (fun r β c s0 s1 => _). apply falso.\n- refine (fun r β c s0 s1 => _). apply sfalso.\n- refine (fun r β c s0 s1 => _). apply sfalso.\nDefined.\n\nDefinition contractor1 {p}\n  (A0 : @El0 p Type0)\n  (A1 : @El1 p Type0 Type1 A0)\n  (a0 : El0 A0)\n  (a1 : El1 A0 A1 a0)\n  (b0 : El0 A0)\n  (b1 : El1 A0 A1 b0)\n  (e0 : El0 (eq0 A0 A1 a0 a1 b0 b1))\n  (e1 : El1 _ (eq1 A0 A1 a0 a1 b0 b1) e0)\n  : @El1 p Type0 Type1 (contractor0 A0 A1 a0 a1 b0 b1 e0 e1).\nProof.\nrefine (fun q α r β => _).\nreflexivity.\nDefined.\n\nDefinition contr_filler0 {p}\n  (A0 : @El0 p Type0)\n  (A1 : @El1 p Type0 Type1 A0)\n  (a0 : El0 A0)\n  (a1 : El1 A0 A1 a0)\n  (b0 : El0 A0)\n  (b1 : El1 A0 A1 b0)\n  (e0 : El0 (eq0 A0 A1 a0 a1 b0 b1))\n  (e1 : El1 _ (eq1 A0 A1 a0 a1 b0 b1) e0)\n  : El0 (contractor0 A0 A1 a0 a1 b0 b1 e0 e1).\nProof.\nrefine (fun q α => _). simpl. unshelve econstructor.\n- refine (wedge ⋅ ce_f0 (e0 q α)).\n- refine (wedge ⋅ ce_f1 (e0 q α)).\n- apply sfalso.\n- apply sfalso.\n- apply sfalso.\n- apply sfalso.\n(* as is, this requires some computation rules for wedge *)\nDefined.\n\nDefinition contr_filler1 {p}\n  (A0 : @El0 p Type0)\n  (A1 : @El1 p Type0 Type1 A0)\n  (a0 : El0 A0)\n  (a1 : El1 A0 A1 a0)\n  (b0 : El0 A0)\n  (b1 : El1 A0 A1 b0)\n  (e0 : El0 (eq0 A0 A1 a0 a1 b0 b1))\n  (e1 : El1 _ (eq1 A0 A1 a0 a1 b0 b1) e0)\n  : El1 _ (contractor1 A0 A1 a0 a1 b0 b1 e0 e1) (contr_filler0 A0 A1 a0 a1 b0 b1 e0 e1).\nProof.\nrefine (fun q α => _).\nassert (forall (f g : forall (r : ℙ) (β : r ≤ q), wedge_eq ((α ∘ β) · A0) ((α ∘ β) · A1) ((α ∘ β) · a0) ((α ∘ β) · a1) ((α ∘ β) · b0) ((α ∘ β) · b1) ((α ∘ β) · e0) ((α ∘ β) · e1)), \n  ((fun r β => we_f0 (f r β)) ≡ (fun r β => we_f0 (g r β))) -> f ≡ g)\n  as lemma.\n{ intros f g Hfg.\n  refine (J_seqs _ (fun r β => we_f0 (g r β)) \n    (fun X E => (fun r β => \n      {| we_f0 := X r β ; \n         we_f1 := J_seqs _ _ (fun Y _ => El1 (squish ∘ squish ⋅ (α ∘ β ⋅ A0)) (squish ∘ squish ⋅ (α ∘ β ⋅ A1)) (Y r β)) (we_f1 (g r β)) _ E ;\n         we_0y := J_seqs _ (fun r β => we_f0 (g r β)) (fun Y _ => side_0 ⋅ (Y r β) ≡ squish ⋅ (α ∘ β ⋅ a0)) (we_0y (g r β)) X E ; \n         we_1y := J_seqs _ _ (fun Y _ => side_1 ⋅ (Y r β) ≡ ce_f0 (e0 r (α ∘ β))) (we_1y (g r β)) X E ;\n         we_x0 := J_seqs _ _ (fun Y _ => (promote side_0) ⋅ (Y r β) ≡ squish ⋅ (α ∘ β ⋅ a0)) (we_x0 (g r β)) X E ;\n         we_x1 := J_seqs _ _ (fun Y _ => (promote side_1) ⋅ (Y r β) ≡ ce_f0 (e0 r (α ∘ β))) (we_x1 (g r β)) X E ; |}) \n      ≡ g)\n    (srefl _)\n    (fun r β => we_f0 (f r β))\n    (ssym Hfg)). }\neapply lemma. simpl.\nrefine (J_seqs _ _ (fun X _ => (fun r β => wedge ⋅ ce_f0 (X r β)) ≡ _) (srefl _) (α ⋅ e0) (ssym (e1 q α))).\nDefined.\n\n\n(* that one is more or less contr_filler0 with some packaging *)\n(* todo : prove it from contr_filler0 *)\nDefinition singl_contr0 {p}\n  (A0 : @El0 p Type0)\n  (A1 : @El1 p Type0 Type1 A0)\n  (a0 : El0 A0)\n  (a1 : El1 A0 A1 a0)\n  (b0 : El0 A0)\n  (b1 : El1 A0 A1 b0)\n  (e0 : El0 (eq0 A0 A1 a0 a1 b0 b1))\n  (e1 : El1 _ (eq1 A0 A1 a0 a1 b0 b1) e0)\n  : El0 (eq0\n    (Sigma0 A0 A1 (fun q α x0 x1 => eq0 (α ⋅ A0) (α ⋅ A1) (α ⋅ a0) (α ⋅ a1) x0 x1 q !) (fun q α x0 x1 => eq1 (α ⋅ A0) (α ⋅ A1) (α ⋅ a0) (α ⋅ a1) x0 x1 q !))\n    (Sigma1 A0 A1 (fun q α x0 x1 => eq0 (α ⋅ A0) (α ⋅ A1) (α ⋅ a0) (α ⋅ a1) x0 x1 q !) (fun q α x0 x1 => eq1 (α ⋅ A0) (α ⋅ A1) (α ⋅ a0) (α ⋅ a1) x0 x1 q !))\n    (dpair0 a0 a1 (eq_refl0 A0 A1 a0 a1) (eq_refl1 A0 A1 a0 a1))\n    (dpair1 a0 a1 (eq_refl0 A0 A1 a0 a1) (eq_refl1 A0 A1 a0 a1))\n    (dpair0 b0 b1 e0 e1)\n    (dpair1 b0 b1 e0 e1)).\nProof.\nrefine (fun q α => _) ; simpl.\nunshelve econstructor.\n- refine (fun r β => _) ; simpl.\n  unshelve econstructor.\n  + exact (β ⋅ ce_f0 (e0 q α)).\n  + exact (β ⋅ ce_f1 (e0 q α)).\n  + refine (fun r0 β0 => _) ; simpl.\n    unshelve econstructor.\n    * change (El0 (α ∘ squish ∘ wedge ∘ promote β ∘ promote β0 ⋅ A0)).\n      exact (wedge ∘ promote β ∘ promote β0 ⋅ (ce_f0 (e0 q α))).\n    * exact (wedge ∘ promote β ∘ promote β0 ⋅ (ce_f1 (e0 q α))).\n    * refine (J_seqs _ _ (fun X _ => _ ≡ β ∘ β0 ⋅ (squish ⋅ X)) _ _ (ce_s (e0 q α))).\n      change (β ∘ β0 ⋅ (wedge ∘ side_0 ⋅ ce_f0 (e0 q α)) ≡ β ∘ β0 ⋅ (side_0 ∘ squish ⋅ (ce_f0 (e0 q α)))).\n      (* here we would need some more computation *)\n      apply sfalso.\n    * change (β ∘ β0 ⋅ (wedge ∘ side_1 ⋅ ce_f0 (e0 q α)) ≡ β ∘ β0 ⋅ (ce_f0 (e0 q α))).\n      (* here too *)\n      apply sfalso.\n  + refine (fun r0 β0 => _) ; simpl.\n    reflexivity.\n- refine (fun r β => _) ; simpl.\n  reflexivity.\n- admit.\n- admit.\nAdmitted.\n\n\nDefinition singl_contr1 {p}\n  (A0 : @El0 p Type0)\n  (A1 : @El1 p Type0 Type1 A0)\n  (a0 : El0 A0)\n  (a1 : El1 A0 A1 a0)\n  (b0 : El0 A0)\n  (b1 : El1 A0 A1 b0)\n  (e0 : El0 (eq0 A0 A1 a0 a1 b0 b1))\n  (e1 : El1 _ (eq1 A0 A1 a0 a1 b0 b1) e0)\n  : El1 _ (eq1\n    (Sigma0 A0 A1 (fun q α x0 x1 => eq0 (α ⋅ A0) (α ⋅ A1) (α ⋅ a0) (α ⋅ a1) x0 x1 q !) (fun q α x0 x1 => eq1 (α ⋅ A0) (α ⋅ A1) (α ⋅ a0) (α ⋅ a1) x0 x1 q !))\n    (Sigma1 A0 A1 (fun q α x0 x1 => eq0 (α ⋅ A0) (α ⋅ A1) (α ⋅ a0) (α ⋅ a1) x0 x1 q !) (fun q α x0 x1 => eq1 (α ⋅ A0) (α ⋅ A1) (α ⋅ a0) (α ⋅ a1) x0 x1 q !))\n    (dpair0 a0 a1 (eq_refl0 A0 A1 a0 a1) (eq_refl1 A0 A1 a0 a1))\n    (dpair1 a0 a1 (eq_refl0 A0 A1 a0 a1) (eq_refl1 A0 A1 a0 a1))\n    (dpair0 b0 b1 e0 e1)\n    (dpair1 b0 b1 e0 e1))\n    (singl_contr0 A0 A1 a0 a1 b0 b1 e0 e1).\nProof.\nrefine (fun q α => _). simpl.\n(* komarimasu… *)\nAdmitted.\n", "meta": {"author": "CoqHott", "repo": "cubical_forcing", "sha": "750c76719699d7d701a8c9e3b1fc539e7859fe49", "save_path": "github-repos/coq/CoqHott-cubical_forcing", "path": "github-repos/coq/CoqHott-cubical_forcing/cubical_forcing-750c76719699d7d701a8c9e3b1fc539e7859fe49/theories/singletons.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.27976022109030146}}
{"text": "Require Import Merges.Tactics.\nRequire Import Merges.Map.\n\nRequire Import Coq.Lists.List.\nImport ListNotations.\nSet Implicit Arguments.\n\nSection Machine.\n\n (* ~~~~ Input types ~~~~~~~~ *)\n Record Types\n  := mkTypes\n\n  (* The names of input channels *)\n  { input       : Type\n  (* do we need to see if two are the same? *)\n  ; inputEqDec  : EqDec input\n\n  (* The names of output channels.\n     I'm not sure whether separating these will make fusion too complicated\n     because fusing can remove inputs  *)\n  ; output      : Type\n  (* do we need to see if two are the same? *)\n  ; outputEqDec : EqDec output\n\n  (* Let's start simple with only one value type *)\n  ; val         : Type\n  (* And we'll assume there is some sort of bottom for uninitialised values.\n     This is not ideal, but it makes it simpler to allow worker functions\n     access to all values *)\n  ; uninitialised : val\n\n  (* State labels *)\n  ; label       : Type\n  (* We also need an initial label *)\n  ; initial     : label\n\n  (* The stateOf : label -> State\n     would make sense in here, but State isn't defined yet\n     and depends on the types in here *)\n  }.\n\n Variable t : Types.\n\n\n\n (* ~~~~ Definitions ~~~~~~~~ *)\n\n (* Output channels can have states assigned to them.\n    You can also read the last output value. *)\n Inductive Var\n   (* Value of last read from channel *)\n  := VInput       : input  t -> Var\n   (* Value that was last written to channel *)\n   | VOutput      : output t -> Var\n   (* Output channel's state *)\n   | VState       : output t -> Var.\n\n Theorem VarEqDec : EqDec Var.\n  unfold EqDec in *. intros.  \n  destruct n; destruct m;\n  try destruct (inputEqDec t i i0);\n  try destruct (outputEqDec t o o0);\n  try solve [left; congruence];\n  try solve [right; congruence].\n Qed.\n\n (* Given a mapping from variables to values, a \"worker function\" computes a value *)\n Definition Env    := Var -> val t.\n Definition Func a := Env -> a.\n\n\n (* Put the labels in the state type so we don't need dependent types or whatever *)\n Inductive State\n   (* Pull from an input channel *)\n  := Pull    : input t\n             (*some*) (*none*)\n            -> label t -> label t\n            -> State\n   (* Release input value *)\n   | Release : input t -> label t\n            -> State\n   (* Close input channel - I promise not to read again *)\n   | Close   : input t -> label t\n            -> State\n   (* Push f(env) to output channel *)\n   | Out     : output t\n            -> Func  (val t)\n            -> label  t\n            -> State\n   (* Output channel is finished *)\n   | OutDone : output t\n            -> label  t\n            -> State\n   (* If f(env) *)\n   | If      : Func bool\n             (*then*) (*else*)\n            -> label t -> label t\n            -> State\n   (* output's state = f(env) *)\n   | Update  : output t\n            -> Func  (val t)\n            -> label  t\n            -> State\n   (* Goto*)\n   | Skip    : label  t\n            -> State\n   (* Nothing more to do *)\n   | Done    : State.\n\n (* Finally, each label needs a state *)\n Variable stateOf : label t -> State.\n\n Definition outlabels (lO : label t) (s : State) : list (label t)\n   := match s with\n        | Pull _ l1 l2 => [l1;l2]\n        | Release _ l  => [l]\n        | Close   _ l  => [l]\n        | Out _ _ l    => [l]\n        | OutDone _ l  => [l]\n        | If _ l1 l2   => [l1; l2]\n        | Update _ _ l => [l]\n        | Skip  l      => [l]\n        | Done         => [lO]\n      end.\n      \n\n\n\n (* ~~~~ Evaluation ~~~~~~~~ *)\n\n (* We need some values to start the party *)\n Definition emptyEnv : Env\n  := fun _ => uninitialised t.\n\n (* Each input channel needs a list of values, as does output *)\n Definition Inputs  := input  t -> list (val t).\n Definition Outputs := output t -> list (val t).\n\n (* Pull from an input *)\n Definition pull (i : input t) (is : Inputs) : (Inputs * option (val t))\n  := match is i with\n     | [] \n        => (is, None)\n     | (x::xs)\n        => (update _ _ (inputEqDec t) i xs is, Some x)\n     end.\n\n\n\n (* Initially all outputs are empty *)\n Definition initialOuts : Outputs\n  := Map.empty _ _ [].\n\n (* Push to an output *)\n Definition push (o : output t) (v : val t) (os : Outputs) : Outputs\n  := update _ _ (outputEqDec t) o (v :: os o) os.\n\n \n (* What is a better name? The actual evaluation state of running a machine *)\n Definition STATE := (label t * Inputs * Outputs * Env)%type.\n\n (* Single-step semantics *)\n Definition run1 (r : STATE) : STATE\n  := match r with\n     (l, is, os, e)\n     => match stateOf l with\n        | Pull i lT lF\n        => match pull i is with\n           | (is', None)\n           => (lF, is', os, e)\n           | (is', Some v)\n           => (lT, is', os, update _ _ VarEqDec (VInput i) v e)\n           end\n\n        | Release i l'\n        => (l', is, os, e)\n\n        | Close   i l'\n        => (l', is, os, e)\n\n        \n        | Out o f l'\n        => let v   := f e              in\n           let os' := push o v os      in\n           let e'  := update _ _ VarEqDec (VOutput o) v e\n           in (l', is, os', e')\n\n        | OutDone o l'\n        => (l', is, os, e)\n\n        \n        | If p lT lF\n        => if   p e\n           then (lT, is, os, e)\n           else (lF, is, os, e)\n         \n        | Update o f l'\n        => (l', is, os, update _ _ VarEqDec (VState o) (f e) e)\n\n        | Skip l'\n        => (l', is, os, e)\n        \n        (* I'm not sure about this; should return type be option & return none? *)\n        | Done\n        => (l, is, os, e)\n\n        end\n     end.\n\n\n Theorem pull_ne_same:\n  forall is i j is' o\n   , pull i is = (is', o)\n  -> i <> j\n  -> length (is' j) = length (is j).\n Proof.\n  intros; unfolds pull; unfolds update.\n  destruct (is i); injects~ H.\n  destruct~ (inputEqDec _ i j); contradiction.\n Qed.\n\nTheorem pull_eq_decreases:\n  forall is i is' o\n   , pull i is = (is', o)\n  -> length (is' i) <= length (is i).\n Proof.\n  intros.\n  unfolds pull; unfolds update.\n  remember (is i) as is_i; destruct is_i; injects~ H.\n  rewrite Heqis_i; omega.\n  destruct (inputEqDec _ i i); bye_not_eq. simpl; omega.\n Qed.\n\n Theorem pull_decreases:\n  forall is i j is' o\n   , pull i is = (is', o)\n  -> length (is' j) <= length (is j).\n Proof.\n  intros.\n  destruct (inputEqDec _ i j).\n   subst; eapply pull_eq_decreases; eassumption.\n   remember (pull_ne_same is H n); omega.\n Qed.\n\n\n Theorem push_ne_same:\n  forall os i j v\n   , i <> j\n  -> length (os i) = length ((push j v os) i).\n Proof.\n  intros; unfolds push; unfolds update.\n  destruct~ (outputEqDec _ j i).\n   destruct H; eauto.\n Qed.\n\n Theorem push_eq_increase:\n  forall os i v\n   , S (length (os i)) = length ((push i v os) i).\n Proof.\n  intros; unfolds push; unfolds update.\n  destruct~ (outputEqDec _ i i); bye_not_eq.\n Qed.\n\n Theorem push_increase:\n  forall os i j v\n   , length (os i) <= length ((push j v os) i).\n Proof.\n  intros.\n  destruct (outputEqDec _ i j).\n   subst; remember (push_eq_increase os j v); omega.\n   remember (push_ne_same os v n); omega.\n Qed.\n\n Theorem state_maybe_decreasing:\n  forall l is os e l' is' os' e'\n   , run1  (l, is, os, e) = (l', is', os', e')\n   -> forall i, length (is' i) <= length (is i).\n Proof.\n  intros.\n  unfolds run1.\n  destruct (stateOf l);\n    try destruct (f e);\n    try injects H;\n    eauto.\n  remember (pull i0 is) as pulls.\n  destruct pulls.\n  destruct o; injects H; eapply pull_decreases; symmetry; eauto.\n Qed.\n\n\n (* We define a sequence of *non-empty* evaluation steps.\n    If the machine is done, it can still have a non-empty evaluation sequence.\n    But if the machine is not done, a non-empty evaluation sequence must\n    actually change something. *)\n Inductive runs : STATE -> STATE -> Type\n := Run1      : forall s s'\n              , s' = run1 s\n              -> runs s s'\n  | RunN      : forall s s' s''\n              , s' = run1 s\n             -> runs s' s''\n             -> runs s s''.\n\n (* Execute the whole machine *)\n Inductive exec : Inputs -> Outputs -> Type\n  := Exec     : forall is l' is' os' e'\n              , stateOf l' = Done\n             -> runs (initial t, is, initialOuts, emptyEnv)\n                     (l', is', os', e')\n             -> exec is os'.\n\n Fixpoint runs_one_decreases\n    (p : STATE -> nat)\n    (s s' : STATE)\n    (r : runs s s') : Prop\n  := match r with\n      | @Run1 s1 s2 _\n      => p s2 < p s1\n      | @RunN s1 s2 s3 _ r'\n     => (p s2 < p s1) \\/ (@runs_one_decreases p _ _ r')\n    end.\n\n Fixpoint runs_all_nonincreasing\n    (p : STATE -> nat)\n    (s s' : STATE)\n    (r : runs s s') : Prop\n  := match r with\n      | @Run1 s1 s2 _\n      => p s2 <= p s1\n      | @RunN s1 s2 s3 _ r'\n     => (p s2 <= p s1) /\\ (@runs_all_nonincreasing p _ _ r')\n    end.\n\n\n Theorem runs_nonincreasing:\n    forall (p : STATE -> nat)\n             (s s' : STATE)\n             (r : runs s s')\n     , runs_all_nonincreasing p r\n    -> p s' <= p s.\n  Proof.\n   intros.\n   induction r.\n   eauto.\n   simpl in *.\n   destruct H.\n   apply IHr in H0.\n   omega.\n  Qed.\n\n Theorem runs_strictly_decreasing:\n    forall (p : STATE -> nat)\n             (s s' : STATE)\n             (r : runs s s')\n     , runs_one_decreases p r\n    -> runs_all_nonincreasing p r\n    -> p s' < p s.\n  Proof.\n   intros.\n   induction r.\n   eauto.\n   simpl in *.\n   destruct H0.\n   destruct H.\n   assert (p s'' <= p s').\n    eapply runs_nonincreasing. eassumption.\n   omega.\n\n   apply IHr in H1.\n   omega.\n   eauto.\n  Qed.\n\n  Theorem run_to_out:\n    forall l l' is is' os os' e e'\n    , (l',is',os',e') = run1 (l,is,os,e)\n    -> In l' (outlabels l (stateOf l)).\n  Proof.\n    intros.\n    unfold run1 in *.\n    remember (stateOf l) as S.\n\n    destruct~ S; try injects H; simpl; eauto.\n    destruct (pull i is);\n    destruct o;\n    injects H; eauto.\n    destruct (f e);\n    injects H;\n    eauto.\n  Qed.\n\n  \n\n\n\n    (* We want to say that *)\n(* Definition simple_decreasing\n  := forall is l os e,\n\n\n Definition terminates\n              := forall is,\n              exists os,\n              exec is os.\n\n\n (* but in order to prove termination of whole program,\n    probably need to show for all states *)\n Definition terminates_all_states\n              := forall l is os e,\n              exists l' is' os' e',\n              runs (l, is, os, e) (l', is', os', e').\n\n (* Termination variant?\n    Maybe something about, for each label L, whenever you get back to L\n    either lists will be shorter, or some variant on env will be smaller *)\n*)\nEnd Machine.\n\n\n\n  Ltac state_destruct\n   :=  repeat (match goal with\n   | H : STATE _ |- _\n   => let a := fresh \"l\" in\n        let b := fresh \"env\" in\n        let c := fresh \"os\" in\n        let d := fresh \"is\" in\n        destruct H as [a b];\n        destruct a as [a c];\n        destruct a as [a d]\n   end).\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/Machine/Machine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778403, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2797602149774147}}
{"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_Ф__returnOrReinvestForParticipant (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(* Lemma ifSimpleState: forall X (b: bool) (f g: Ledger -> X * Ledger), \n(if b then SimpleState f else SimpleState g ) =\nSimpleState (if b then f else  g).\nProof.\n  intros. destruct b; auto.\nQed.  \n\nLemma ifFunApply: forall X (b: bool) (f g: Ledger -> X * Ledger) l, \n(if b then f else  g ) l =\n(if b then f l else g l).\nProof.\n  intros. destruct b; auto.\nQed. \n\n\n\nLemma fstImplies : forall  X Y T (f: X*T) (g: X -> Y)  ,  (let (x, _) := f in g x) = g (fst f).\nProof.\n  intros.\n  destruct f; auto.\nQed.\n\n\nLemma sndImplies : forall  X Y T (f: X*T) (g: T -> Y)  ,  (let (_, t) := f in g t) = g (snd f).\nProof.\n  intros.\n  destruct f; auto.\nQed.\n\nLemma fstsndImplies : forall  X Y T (f: X*T) (g: X -> T -> Y)  ,  (let (x, t) := f in g x t) = g (fst f) (snd f).\nProof.\n  intros.\n  destruct f; auto.\nQed.\n\nLtac remDestructIf :=\n  match goal with\n    | |- ?x =>\n      match x with\n        | context [if ?b then _ else _] => case_eq b ; intros\n        | _ => idtac\n      end\n  end.\n *)\n\n\nLtac pr_numgoals := let n := numgoals in idtac \"There are\" n \"goals\".\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 Z.ltb Z.sub intMin deleteListPair intMax.\n\nOpaque RoundsBase_Ф__addStakes DePoolContract_Ф_cutWithdrawalValue RoundsBase_Ф_stakeSum.\n\nDefinition DePoolContract_Ф__returnOrReinvestForParticipant' ( Л_round2 : RoundsBase_ι_Round )\n                                                             ( Л_round0 : RoundsBase_ι_Round )\n                                                             ( Л_addr : XAddress )\n                                                             ( Л_stakes : RoundsBase_ι_StakeValue ) \n                                                             ( Л_isValidator : XBool )\n                                                             ( Л_round1ValidatorsElectedFor : XInteger32 )\n                                                             ( f : XBool -> XBool ->  RoundsBase_ι_StakeValue -> XInteger -> XAddress -> XInteger32 -> LedgerT (RoundsBase_ι_Round # RoundsBase_ι_Round) )\n                                                  : LedgerT ( XErrorValue ( RoundsBase_ι_Round # RoundsBase_ι_Round ) XInteger ) := \n(↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_round2 := $ Л_round2) >> \n(↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_round0 := $ Л_round0) >>\nU0! Л_stakeSum := RoundsBase_Ф_stakeSum (! $ Л_stakes !) ;\nU0! Л_stakeIsLost := ($ (Л_round2 ->> RoundsBase_ι_Round_ι_completionReason) ) ?== ($ RoundsBase_ι_CompletionReasonP_ι_ValidatorIsPunished) ; \t\t\nU0! Л_optParticipant := ParticipantBase_Ф_fetchParticipant (! $ Л_addr !) ; \nRequire {{ $ Л_optParticipant ->hasValue , $ InternalErrors_ι_ERROR511 }} ; \n\n(↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_participant := $ Л_optParticipant ->get) >> \n(↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_participant ^^ DePoolLib_ι_Participant_ι_roundQty !--) >>\n\n( ↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_lostFunds := $ Л_stakeIsLost ? \n   ( D1! (D2! LocalState_ι__returnOrReinvestForParticipant_Л_round2) ^^ RoundsBase_ι_Round_ι_stake !- \n     D1! (D2! LocalState_ι__returnOrReinvestForParticipant_Л_round2) ^^ RoundsBase_ι_Round_ι_unused ) !- \n     D1! (D2! LocalState_ι__returnOrReinvestForParticipant_Л_round2) ^^ RoundsBase_ι_Round_ι_recoveredStake \n                              ::: $ xInt0 )  >> f Л_stakeIsLost Л_isValidator Л_stakes Л_stakeSum Л_addr Л_round1ValidatorsElectedFor. \n\nLemma DePoolContract_Ф__returnOrReinvestForParticipant'_exec : forall\n                                                                (l : Ledger)\n                                                                ( Л_round2 : RoundsBase_ι_Round )\n                                                                ( Л_round0 : RoundsBase_ι_Round )\n                                                                ( Л_addr : XAddress )\n                                                                ( Л_stakes : RoundsBase_ι_StakeValue ) \n                                                                ( Л_isValidator : XBool ) \n                                                                ( Л_round1ValidatorsElectedFor : XInteger32 )\n                                                                ( f : XBool -> XBool ->  RoundsBase_ι_StakeValue -> XInteger -> XAddress -> XInteger32 -> LedgerT (RoundsBase_ι_Round # RoundsBase_ι_Round) ),\nlet (stakeSum, l_sum) := run (↓ RoundsBase_Ф_stakeSum Л_stakes) l in\nlet stakeIsLost : bool := eqb (Л_round2 ->> RoundsBase_ι_Round_ι_completionReason) RoundsBase_ι_CompletionReasonP_ι_ValidatorIsPunished in\nlet optParticipant := eval_state (↓ ParticipantBase_Ф_fetchParticipant Л_addr) l_sum in\nlet isSomeParticipant : bool := isSome optParticipant in\nlet participant := maybeGet optParticipant in \nlet participant_newRoundQty :=\n    {$ participant with (DePoolLib_ι_Participant_ι_roundQty, (participant ->> DePoolLib_ι_Participant_ι_roundQty) - 1 ) $} in \nlet lostFunds := if stakeIsLost\n    then    (Л_round2 ->> RoundsBase_ι_Round_ι_stake  -\n              Л_round2 ->> RoundsBase_ι_Round_ι_unused)  -\n              Л_round2 ->> RoundsBase_ι_Round_ι_recoveredStake\n    else 0 in \nlet l_local := {$ l_sum With (LocalState_ι__returnOrReinvestForParticipant_Л_round2, Л_round2);\n                              (LocalState_ι__returnOrReinvestForParticipant_Л_round0, Л_round0);\n                              (LocalState_ι__returnOrReinvestForParticipant_Л_participant, participant_newRoundQty);\n                              (LocalState_ι__returnOrReinvestForParticipant_Л_lostFunds, lostFunds) $} in\n\nexec_state (DePoolContract_Ф__returnOrReinvestForParticipant' Л_round2 Л_round0 Л_addr Л_stakes Л_isValidator Л_round1ValidatorsElectedFor f) l =\n    if  isSomeParticipant then                             \n        exec_state (f stakeIsLost Л_isValidator Л_stakes stakeSum Л_addr Л_round1ValidatorsElectedFor) l_local\n        else {$ l_sum With (LocalState_ι__returnOrReinvestForParticipant_Л_round2, Л_round2);\n                           (LocalState_ι__returnOrReinvestForParticipant_Л_round0, Л_round0) $}.\nProof.\n\n  intros.\n  destructLedger l. \n  compute.\n\n  Time repeat destructIf_solve.\n\n  all: try destructFunction1  RoundsBase_Ф_stakeSum ; auto. idtac.\n  all: time repeat destructIf_solve. idtac.  \n  all: try destructFunction5 f ; auto.\nQed.  \n\nDefinition DePoolContract_Ф__returnOrReinvestForParticipant_tailer1 ( Л_stakeIsLost: XBool ) \n                                                                    ( Л_isValidator : XBool )\n                                                                    ( Л_stakes : RoundsBase_ι_StakeValue ) \n                                                                    ( Л_stakeSum: XInteger )\n                                                                    ( Л_addr : XAddress )\n                                                                    ( Л_round1ValidatorsElectedFor : XInteger32 )\n                                                                    ( f : RoundsBase_ι_StakeValue -> XBool -> XBool -> XAddress -> XInteger32 -> LedgerT (RoundsBase_ι_Round # RoundsBase_ι_Round) )\n                                                  : LedgerT ( RoundsBase_ι_Round # RoundsBase_ι_Round ) :=  \n(↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_newStake := $default) >>\n(↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_reward := $default) >>\n\n(\n\tIf ($ Л_stakeIsLost) then {\n   ( If ( $ Л_isValidator ) \n     then {\n           ( ↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_newStake := $ ( Л_stakes ->> RoundsBase_ι_StakeValue_ι_ordinary ) ) >>  \n           U0! Л_delta := math->min2 (! ↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_newStake ,\n                                         ↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_lostFunds !) ; \n           ( ↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_newStake !-= $ Л_delta ) >>  \n           ( ↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_lostFunds !-= $ Л_delta ) >> \n           ( ↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_round2 ^^ RoundsBase_ι_Round_ι_validatorRemainingStake\n                       := D2! LocalState_ι__returnOrReinvestForParticipant_Л_newStake )\n     } \n     else {\n\t\t(↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_newStake := math->muldiv (! \n                D1! ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_round2 ) ^^  RoundsBase_ι_Round_ι_unused !+\n                D1! ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_round2 ) ^^  RoundsBase_ι_Round_ι_recoveredStake !-\n                D1! ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_round2 ) ^^  RoundsBase_ι_Round_ι_validatorRemainingStake, \n\t\t\t\t$ Л_stakes ->> RoundsBase_ι_StakeValue_ι_ordinary , \n\t\t\t\tD1! ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_round2 ) ^^  RoundsBase_ι_Round_ι_stake !-\n        D1! ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_round2 ) ^^  RoundsBase_ι_Round_ι_validatorStake !))\n} )\n\t} else {\n    (↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_reward := math->muldiv (! $ Л_stakeSum , \n        D1! ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_round2 ) ^^  RoundsBase_ι_Round_ι_rewards ,\n        D1! ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_round2 ) ^^  RoundsBase_ι_Round_ι_stake !) ) >>\n\t\t(↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_participant ^^ DePoolLib_ι_Participant_ι_reward \n                           !+=  D2! LocalState_ι__returnOrReinvestForParticipant_Л_reward ) >>\n\t\t(↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_newStake := $ ( Л_stakes ->> RoundsBase_ι_StakeValue_ι_ordinary ) !+ \n                                                                            (D2! LocalState_ι__returnOrReinvestForParticipant_Л_reward))\n\t}\n) >> \n( ↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_round2 ^^ RoundsBase_ι_Round_ι_handledStakesAndRewards !+= D2! LocalState_ι__returnOrReinvestForParticipant_Л_newStake ) >> \n  f Л_stakes Л_stakeIsLost Л_isValidator Л_addr Л_round1ValidatorsElectedFor.\n\n\nLemma DePoolContract_Ф__returnOrReinvestForParticipant_tailer1_exec : forall\n                                                            ( l : Ledger )\n                                                            ( Л_stakeIsLost: XBool ) \n                                                            ( Л_isValidator : XBool )\n                                                            ( Л_stakes : RoundsBase_ι_StakeValue ) \n                                                            ( Л_stakeSum: XInteger)\n                                                            ( Л_addr : XAddress)\n                                                            ( Л_round1ValidatorsElectedFor : XInteger32 )\n                                                            ( f : RoundsBase_ι_StakeValue -> XBool -> XBool -> XAddress -> XInteger32 -> LedgerT (RoundsBase_ι_Round # RoundsBase_ι_Round) ),\n\nlet newStake := 0 in\nlet reward := 0 in\nlet lostFunds := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_lostFunds) l in\nlet round2 :=  eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_round2) l in\nlet participant := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_participant) l in\nlet delta := intMin ( Л_stakes ->> RoundsBase_ι_StakeValue_ι_ordinary) lostFunds in\nlet newStake := if Л_stakeIsLost then \n                    if Л_isValidator then \n                        Л_stakes ->> RoundsBase_ι_StakeValue_ι_ordinary - delta\n                                     else (round2 ->> RoundsBase_ι_Round_ι_unused + \n                                           round2 ->> RoundsBase_ι_Round_ι_recoveredStake - \n                                           round2 ->> RoundsBase_ι_Round_ι_validatorRemainingStake) *  \n                                           (Л_stakes ->> RoundsBase_ι_StakeValue_ι_ordinary) /\n                                           (round2 ->> RoundsBase_ι_Round_ι_stake - round2 ->> RoundsBase_ι_Round_ι_validatorStake) \n                                 else Л_stakes ->> RoundsBase_ι_StakeValue_ι_ordinary + \n                                 Л_stakeSum * (round2 ->> RoundsBase_ι_Round_ι_rewards) / (round2 ->> RoundsBase_ι_Round_ι_stake)  in\nlet lostFunds :=   if Л_stakeIsLost then \n                        if Л_isValidator then lostFunds - delta else lostFunds \n                                     else lostFunds in\nlet reward :=  if Л_stakeIsLost then reward\n                                 else Л_stakeSum *  (round2 ->> RoundsBase_ι_Round_ι_rewards) / (round2 ->> RoundsBase_ι_Round_ι_stake) in \nlet round2 :=  if Л_stakeIsLost then \n                        if Л_isValidator then  {$ round2 with RoundsBase_ι_Round_ι_validatorRemainingStake := newStake $}     \n                                         else round2 \n                                     else round2 in   \nlet participant := if Л_stakeIsLost then participant\n                                    else {$ participant with DePoolLib_ι_Participant_ι_reward := participant ->> DePoolLib_ι_Participant_ι_reward + reward $} in \nlet round2 := {$round2 with RoundsBase_ι_Round_ι_handledStakesAndRewards :=  round2 ->> RoundsBase_ι_Round_ι_handledStakesAndRewards + newStake$} in\n\n exec_state (DePoolContract_Ф__returnOrReinvestForParticipant_tailer1 Л_stakeIsLost Л_isValidator Л_stakes Л_stakeSum Л_addr Л_round1ValidatorsElectedFor f) l =\n exec_state (f Л_stakes Л_stakeIsLost Л_isValidator Л_addr Л_round1ValidatorsElectedFor) {$ l With (LocalState_ι__returnOrReinvestForParticipant_Л_lostFunds, lostFunds);\n                                                                      (LocalState_ι__returnOrReinvestForParticipant_Л_round2, round2);\n                                                                      (LocalState_ι__returnOrReinvestForParticipant_Л_participant, participant);\n                                                                      (LocalState_ι__returnOrReinvestForParticipant_Л_newStake, newStake);\n                                                                      (LocalState_ι__returnOrReinvestForParticipant_Л_reward, reward) $}.\nProof.\n\n  intros.\n  destructLedger l. \n  compute.\n\n  Time repeat destructIf_solve.\n\nQed.\n\nDefinition DePoolContract_Ф__returnOrReinvestForParticipant_tailer2 ( Л_stakes : RoundsBase_ι_StakeValue ) \n                                                                    ( Л_stakeIsLost : XBool )  \n                                                                    ( Л_isValidator : XBool ) \n                                                                    ( Л_addr : XAddress)\n                                                                    ( Л_round1ValidatorsElectedFor : XInteger32 )\n                                                                    ( f: RoundsBase_ι_StakeValue -> XBool -> XBool -> XAddress -> LedgerT (RoundsBase_ι_Round # RoundsBase_ι_Round) )\n                                                            : LedgerT ( RoundsBase_ι_Round # RoundsBase_ι_Round ) :=  \n(↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_newVesting := $ ( Л_stakes ->> RoundsBase_ι_StakeValue_ι_vesting ) ) >> \n( If ( ( ↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_newVesting ) ->hasValue ) \nthen\n{ \n  (↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_params := \n             ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_newVesting ) ->get )  >> \n\n ( If ($ Л_stakeIsLost) then { \n   ( If ( $ Л_isValidator ) \n     then {\n           U0! Л_delta := math->min2 (! ↑17 D1! ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_params ) ^^ \n                                             RoundsBase_ι_InvestParams_ι_remainingAmount ,\n                                         ↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_lostFunds !) ; \n           ( ↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_params ^^ \n                                             RoundsBase_ι_InvestParams_ι_remainingAmount !-= $ Л_delta ) >>  \n           ( ↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_lostFunds !-= $ Л_delta ) >> \n           ( ↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_round2 ^^ RoundsBase_ι_Round_ι_validatorRemainingStake\n                       !+= D1! ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_params )\n                                            ^^ RoundsBase_ι_InvestParams_ι_remainingAmount )\n     } (*+*)\n     else {\n\t\t( ↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_params ^^ \n                                             RoundsBase_ι_InvestParams_ι_remainingAmount := math->muldiv (! \n\t\t\t\tD1! ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_round2 ) ^^  RoundsBase_ι_Round_ι_unused !+\n        D1! ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_round2 ) ^^  RoundsBase_ι_Round_ι_recoveredStake !-\n        D1! ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_round2 ) ^^  RoundsBase_ι_Round_ι_validatorRemainingStake\n              , \n\t\t\t\tD1! ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_params )\n                                            ^^ RoundsBase_ι_InvestParams_ι_remainingAmount , \n\t\t\t\tD1! ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_round2 ) ^^  RoundsBase_ι_Round_ι_stake !-\n        D1! ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_round2 ) ^^  RoundsBase_ι_Round_ι_validatorStake !) )\n} ) \n\t} ) (*+*) >>\n                       (* round2.handledStakesAndRewards += params.remainingAmount; *)\n  ( ↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_round2 ^^ RoundsBase_ι_Round_ι_handledStakesAndRewards  !+=\n    D1! ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_params ) ^^ RoundsBase_ι_InvestParams_ι_remainingAmount ) \n>> (* + *)  \n  U0! Л_withdrawalVesting := $ default ;\n\n                       (*  (newVesting, withdrawalVesting, tonsForOwner) = cutWithdrawalValue(\n                                params,\n                                isValidator && round2.completionReason != CompletionReason.RewardIsReceived,\n                                round1ValidatorsElectedFor + round2.validatorsElectedFor\n            ); *)\n  U0! {( Л_newVesting , Л_withdrawalVesting , Л_tonsForOwner )} := DePoolContract_Ф_cutWithdrawalValue (!\n                               ( ↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_params ) ,\n                                 $ Л_isValidator !&  ( D1! ( ↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_round2 ) \n                                                       ^^ RoundsBase_ι_Round_ι_completionReason ) ?!=\n                                                       $ RoundsBase_ι_CompletionReasonP_ι_RewardIsReceived ,\n                                                     ( $ Л_round1ValidatorsElectedFor !+\n                                                     ( D1! ( ↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_round2 ) ^^\n                                                             RoundsBase_ι_Round_ι_validatorsElectedFor  ) ) \n                                                      !) ;         \n\n  ( ↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_newVesting := $ Л_newVesting ) >>\n  ( ↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_newStake !+= $ Л_withdrawalVesting ) >>\n           (*  if (tonsForOwner > 0)\n                newVesting.get().owner.transfer(tonsForOwner, false, 1); *)\n ( If ( $ Л_tonsForOwner ?> $ xInt0 )\n   then {\n\t(D1! ((↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_newVesting) ->get) ^^ RoundsBase_ι_InvestParams_ι_owner ) ->transfer \n            (! $ Л_tonsForOwner , $ xBoolFalse, $ xInt1 !)\n        } ) \n} ) >> f Л_stakes Л_stakeIsLost Л_isValidator Л_addr.\n\nLemma DePoolContract_Ф__returnOrReinvestForParticipant_tailer2_exec : forall\n                                                            ( l : Ledger)\n                                                            ( Л_stakes : RoundsBase_ι_StakeValue ) \n                                                            ( Л_stakeIsLost : XBool )  \n                                                            ( Л_isValidator : XBool ) \n                                                            ( Л_addr : XAddress )\n                                                            ( Л_round1ValidatorsElectedFor : XInteger32 )\n                                                            ( f: RoundsBase_ι_StakeValue -> XBool -> XBool -> XAddress -> LedgerT (RoundsBase_ι_Round # RoundsBase_ι_Round) ),\nlet lostFunds := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_lostFunds) l in\nlet round2 := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_round2) l in\nlet newStake := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_newStake) l in\n\nlet optNewVesting := Л_stakes ->> RoundsBase_ι_StakeValue_ι_vesting in\nlet isNewVesting := isSome optNewVesting in\nlet params := maybeGet optNewVesting in\nlet oldVestingAmount := params ->> RoundsBase_ι_InvestParams_ι_remainingAmount in\nlet oldVestingValidatorRemainingStake := round2 ->> RoundsBase_ι_Round_ι_validatorRemainingStake  in\nlet deltaVestingValidator := intMin oldVestingAmount lostFunds in\nlet amount := if Л_stakeIsLost then\n                  if Л_isValidator then oldVestingAmount - deltaVestingValidator\n                                   else (round2 ->> RoundsBase_ι_Round_ι_unused + round2 ->> RoundsBase_ι_Round_ι_recoveredStake - round2 ->> RoundsBase_ι_Round_ι_validatorRemainingStake) *\n                                        (params ->> RoundsBase_ι_InvestParams_ι_remainingAmount) / (round2 ->> RoundsBase_ι_Round_ι_stake - round2 ->> RoundsBase_ι_Round_ι_validatorStake) \n                                  else oldVestingAmount in\nlet lostFunds := if Л_stakeIsLost then \n                      if Л_isValidator then lostFunds - deltaVestingValidator \n                                       else lostFunds \n                                    else lostFunds in \nlet validatorRemainingStake := if Л_stakeIsLost then \n                      if Л_isValidator then oldVestingValidatorRemainingStake + amount\n                                       else oldVestingValidatorRemainingStake \n                                    else oldVestingValidatorRemainingStake in \nlet params := {$ params with RoundsBase_ι_InvestParams_ι_remainingAmount := amount $} in\nlet bPunish := (Л_isValidator && negb (eqb round2 ->> RoundsBase_ι_Round_ι_completionReason RoundsBase_ι_CompletionReasonP_ι_RewardIsReceived))%bool in\nlet punishInterval := Л_round1ValidatorsElectedFor + (round2 ->> RoundsBase_ι_Round_ι_validatorsElectedFor) in\n\nlet (p, l') := run (↓ DePoolContract_Ф_cutWithdrawalValue params bPunish punishInterval) l in\nlet (p, tonsForOwner) := p in\nlet (newVesting, withdrawalVesting) := p in\nlet round2 := {$round2 with (RoundsBase_ι_Round_ι_handledStakesAndRewards, round2 ->> RoundsBase_ι_Round_ι_handledStakesAndRewards + amount) ;\n                            (RoundsBase_ι_Round_ι_validatorRemainingStake, validatorRemainingStake) $} in\nlet l'' := if (tonsForOwner >? 0) then exec_state (↓ tvm_transfer ((maybeGet newVesting) ->> RoundsBase_ι_InvestParams_ι_owner) tonsForOwner false 1 default) l' else l' in \n\nexec_state (DePoolContract_Ф__returnOrReinvestForParticipant_tailer2 Л_stakes Л_stakeIsLost Л_isValidator Л_addr Л_round1ValidatorsElectedFor f) l = \n\nif isNewVesting then \n exec_state (f Л_stakes Л_stakeIsLost Л_isValidator Л_addr) {$ l'' With (LocalState_ι__returnOrReinvestForParticipant_Л_lostFunds, lostFunds);\n                                                                       (LocalState_ι__returnOrReinvestForParticipant_Л_round2, round2);\n                                                                       (LocalState_ι__returnOrReinvestForParticipant_Л_newStake, newStake + withdrawalVesting);\n                                                                       (LocalState_ι__returnOrReinvestForParticipant_Л_newVesting, newVesting);\n                                                                       (LocalState_ι__returnOrReinvestForParticipant_Л_params, params) $} else\n exec_state (f Л_stakes Л_stakeIsLost Л_isValidator Л_addr) {$ l With (LocalState_ι__returnOrReinvestForParticipant_Л_newVesting, optNewVesting) $}    .\nProof.\n\n  intros.\n  destructLedger l. \n  compute. idtac.\n\n  destruct Л_stakes; destruct RoundsBase_ι_StakeValue_ι_vesting; try destruct r. idtac.\n\n  all: cycle 1. idtac.\n\n  destructFunction3 DePoolContract_Ф_cutWithdrawalValue ; auto. idtac.  \n  destruct x; destruct x; auto. idtac.\n\n  Time repeat destructIf_solve. idtac.\n  all: try destructFunction3 DePoolContract_Ф_cutWithdrawalValue ; auto. idtac.  \n  all: try destruct x; try destruct x; auto. idtac.\n  all: time repeat destructIf_solve. idtac.\n\n\n  all: try match goal with \n  | |- ?G => match G with \n             | context [DePoolContract_Ф_cutWithdrawalValue ?a ?b ?c] => \n                   let m := fresh \"m\" in\n                   let p := fresh \"p\" in\n                   remember (DePoolContract_Ф_cutWithdrawalValue a b c) as m\n             end      \n  end.\n\n  all: try setoid_rewrite <- Heqm in Heqm0. idtac.\n  all: try rewrite Heqm0. idtac.\n  all: try rewrite <- Heqr. idtac.\n  all: try rewrite H2; auto. idtac.\n  all: try rewrite H1; auto. \nQed.\n\nDefinition DePoolContract_Ф__returnOrReinvestForParticipant_tailer3  \n                   (Л_stakes : RoundsBase_ι_StakeValue) \n                   (Л_stakeIsLost : XBool )\n                   (Л_isValidator : XBool )\n                   (Л_addr : XAddress)\n                   (f: RoundsBase_ι_StakeValue -> XBool -> XBool -> XAddress -> LedgerT (RoundsBase_ι_Round # RoundsBase_ι_Round) )\n                                               : LedgerT ( RoundsBase_ι_Round # RoundsBase_ι_Round ) := \n(↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_attachedValue := $ xInt1) >>\nU0! Л_curPause := math->min2 (! (D1! (↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_participant) ^^ DePoolLib_ι_Participant_ι_withdrawValue) ,\n\t\t\t\t\t\t\t\t(↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_newStake) !) ;\n( ↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_attachedValue !+= $Л_curPause ) >>\n( ↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_participant ^^ DePoolLib_ι_Participant_ι_withdrawValue !-= \n                                 $Л_curPause ) >>\n( ↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_newStake !-= $Л_curPause ) >>\n( If ( ( ↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_newStake ) ?< \n                                          (↑12 D2! DePoolContract_ι_m_minStake ) ) then {\n\t( ↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_attachedValue !+= \n                           D2! LocalState_ι__returnOrReinvestForParticipant_Л_newStake ) >>\n\t( ↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_newStake := $xInt0 )\n} ) >> f Л_stakes Л_stakeIsLost Л_isValidator Л_addr.\n\n\nLemma DePoolContract_Ф__returnOrReinvestForParticipant_tailer3_exec : forall\n                                                            (l : Ledger)\n                                                            (Л_stakes : RoundsBase_ι_StakeValue) \n                                                            (Л_stakeIsLost : XBool )\n                                                            (Л_isValidator : XBool )\n                                                            (Л_addr : XAddress)\n                                                            (f: RoundsBase_ι_StakeValue -> XBool -> XBool -> XAddress -> LedgerT (RoundsBase_ι_Round # RoundsBase_ι_Round) ),\n\n\nlet newStake := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_newStake) l in\nlet participant := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_participant) l in\nlet m_minStake := eval_state (↑12 ε DePoolContract_ι_m_minStake) l in\n\nlet curPause := intMin (participant ->> DePoolLib_ι_Participant_ι_withdrawValue) newStake in\nlet attachedValue := 1 + curPause in\nlet participant := {$ participant with (DePoolLib_ι_Participant_ι_withdrawValue, (participant ->> DePoolLib_ι_Participant_ι_withdrawValue) - curPause)$} in\nlet newStake := newStake - curPause in\nlet attachedValue := if (newStake <? m_minStake) then attachedValue + newStake else attachedValue in\nlet newStake := if (newStake <? m_minStake) then 0 else newStake in\n\nexec_state (DePoolContract_Ф__returnOrReinvestForParticipant_tailer3 Л_stakes Л_stakeIsLost Л_isValidator Л_addr f) l = \n\nexec_state (f Л_stakes Л_stakeIsLost Л_isValidator Л_addr)\n{$ l With (LocalState_ι__returnOrReinvestForParticipant_Л_participant, participant);\n        (LocalState_ι__returnOrReinvestForParticipant_Л_newStake, newStake);\n        (LocalState_ι__returnOrReinvestForParticipant_Л_attachedValue, attachedValue)$}.\nProof.\n\n  intros.\n  destructLedger l. \n  compute. idtac.\n\n  Time repeat destructIf_solve.     \nQed.\n\n\nDefinition DePoolContract_Ф__returnOrReinvestForParticipant_tailer4  \n                                              (Л_stakes : RoundsBase_ι_StakeValue) \n                                              (Л_stakeIsLost : XBool )\n                                              (Л_isValidator : XBool )\n                                              (Л_addr : XAddress)\n                                              (f: XAddress -> RoundsBase_ι_StakeValue -> LedgerT (RoundsBase_ι_Round # RoundsBase_ι_Round) )\n                                               : LedgerT ( RoundsBase_ι_Round # RoundsBase_ι_Round ) := \n(↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_newLock := \n                 $ ( Л_stakes ->> RoundsBase_ι_StakeValue_ι_lock ) ) >> (* + *)(* $ [( default , default )]. *) \n\n( If ( ( ↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_newLock ) ->hasValue ) (* + *)\nthen\n{ \n                                   (* InvestParams params = newLock.get(); *)\n  (↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_params := \n             ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_newLock ) ->get )       >> (* + *)\n\t( If ( $ Л_stakeIsLost ) then {\n  \n   ( If ( $ Л_isValidator ) \n     then {\n           U0! Л_delta := math->min2 (! ↑17 D1! ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_params ) ^^ \n                                                         RoundsBase_ι_InvestParams_ι_remainingAmount ,\n                                         ↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_lostFunds !) ; \n           ( ↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_params ^^ \n                                             RoundsBase_ι_InvestParams_ι_remainingAmount !-= $ Л_delta ) >>  \n           ( ↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_lostFunds !-= $ Л_delta ) >> \n           ( ↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_round2 ^^ RoundsBase_ι_Round_ι_validatorRemainingStake\n                       !+= D1! ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_params )\n                                            ^^ RoundsBase_ι_InvestParams_ι_remainingAmount )\n     } (* + *)\n     else {\n\t\t( ↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_params ^^ \n                                             RoundsBase_ι_InvestParams_ι_remainingAmount := math->muldiv (! \n\t\t\t\tD1! ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_round2 ) ^^  RoundsBase_ι_Round_ι_unused !+\n        D1! ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_round2 ) ^^  RoundsBase_ι_Round_ι_recoveredStake !-\n        D1! ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_round2 ) ^^  RoundsBase_ι_Round_ι_validatorRemainingStake\n              , \n\t\t\t\tD1! ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_params )\n                                            ^^ RoundsBase_ι_InvestParams_ι_remainingAmount , \n\t\t\t\tD1! ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_round2 ) ^^  RoundsBase_ι_Round_ι_stake !-\n        D1! ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_round2 ) ^^  RoundsBase_ι_Round_ι_validatorStake !) )\n} ) \n\t}  )  >>  (* + *)\n                      (*********round2.handledStakesAndRewards += params.remainingAmount;************)\n  ( ↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_round2 ^^ RoundsBase_ι_Round_ι_handledStakesAndRewards !+=\n  ( D2! LocalState_ι__returnOrReinvestForParticipant_Л_params ^^ RoundsBase_ι_InvestParams_ι_remainingAmount ) ) >>\n   (* + *)\n\n  U0! Л_withdrawalLock := $ default ; (* + *)\n                      (* (newLock, withdrawalLock) = cutWithdrawalValue(params); *************)\n  U0! {( Л_newLock , Л_withdrawalLock , _ )} := DePoolContract_Ф_cutWithdrawalValue \n             (! ( ↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_params ) , $ xBoolFalse , $ xInt0 !) ;\n  ( ↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_newLock := $ Л_newLock ) >>\n  (If  ( $ Л_withdrawalLock ?!= $xInt0 ) then {\n                      (* params.owner.transfer(withdrawalLock, false, 1); *)\n   ( D1! ( ↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_params ) ^^ RoundsBase_ι_InvestParams_ι_owner ) ->transfer \n            (! $ Л_withdrawalLock  , $xBoolFalse, $ xInt1 !)\n     } ) \n} )  >> f Л_addr Л_stakes.\n\nLemma DePoolContract_Ф__returnOrReinvestForParticipant_tailer4_exec : forall\n                                                            (l : Ledger)\n                                                            (Л_stakes : RoundsBase_ι_StakeValue ) \n                                                            (Л_stakeIsLost : XBool )  \n                                                            (Л_isValidator : XBool ) \n                                                            (Л_addr : XAddress)\n                                                            (f: XAddress -> RoundsBase_ι_StakeValue -> LedgerT (RoundsBase_ι_Round # RoundsBase_ι_Round) ),\n let lostFunds := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_lostFunds) l in\n let round2 := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_round2) l in\n let optNewLock := Л_stakes ->> RoundsBase_ι_StakeValue_ι_lock in\n let isNewLock := isSome optNewLock in\n let params := maybeGet optNewLock in\n let oldLockAmount := params ->> RoundsBase_ι_InvestParams_ι_remainingAmount in\n let oldLockValidatorRemainingStake := round2 ->> RoundsBase_ι_Round_ι_validatorRemainingStake  in\n let deltaLockValidator := intMin oldLockAmount lostFunds in\n let amount := if Л_stakeIsLost then\n                    if Л_isValidator then oldLockAmount - deltaLockValidator\n                                     else (round2 ->> RoundsBase_ι_Round_ι_unused + round2 ->> RoundsBase_ι_Round_ι_recoveredStake - round2 ->> RoundsBase_ι_Round_ι_validatorRemainingStake) *\n                                          (params ->> RoundsBase_ι_InvestParams_ι_remainingAmount) / (round2 ->> RoundsBase_ι_Round_ι_stake - round2 ->> RoundsBase_ι_Round_ι_validatorStake) \n                                   else oldLockAmount in\n let lostFunds := if Л_stakeIsLost then \n                        if Л_isValidator then lostFunds - deltaLockValidator \n                                         else lostFunds \n                                      else lostFunds in \n let validatorRemainingStake := if Л_stakeIsLost then \n                        if Л_isValidator then oldLockValidatorRemainingStake + amount\n                                         else oldLockValidatorRemainingStake \n                                      else oldLockValidatorRemainingStake in \n let params := {$params with RoundsBase_ι_InvestParams_ι_remainingAmount := amount$} in \n let (p, l') := run (↓ DePoolContract_Ф_cutWithdrawalValue params false 0) l in\n let (p, _) := p in\n let (newLock, withdrawalLock) := p in\n let round2 := {$round2 with (RoundsBase_ι_Round_ι_handledStakesAndRewards, round2 ->> RoundsBase_ι_Round_ι_handledStakesAndRewards + amount) ;\n                             (RoundsBase_ι_Round_ι_validatorRemainingStake, validatorRemainingStake) $} in\n let l'' := if negb (withdrawalLock =? 0) then exec_state (↓ tvm_transfer (params ->> RoundsBase_ι_InvestParams_ι_owner) \n                                                                          withdrawalLock false 1 default) l' else l' in \n\n exec_state (DePoolContract_Ф__returnOrReinvestForParticipant_tailer4 Л_stakes Л_stakeIsLost Л_isValidator Л_addr f) l = \nif isNewLock then \n exec_state (f Л_addr Л_stakes) {$ l'' With (LocalState_ι__returnOrReinvestForParticipant_Л_lostFunds, lostFunds);\n        (LocalState_ι__returnOrReinvestForParticipant_Л_round2, round2);\n        (* (LocalState_ι__returnOrReinvestForParticipant_Л_newStake, newStake + withdrawalLock); *)\n        (LocalState_ι__returnOrReinvestForParticipant_Л_newLock, newLock);\n        (LocalState_ι__returnOrReinvestForParticipant_Л_params, params) $} else\n    exec_state (f Л_addr Л_stakes) {$ l With (LocalState_ι__returnOrReinvestForParticipant_Л_newLock, optNewLock) $} .\nProof.\n\n  intros.\n  destructLedger l. \n  compute. idtac.\n\n  destruct Л_stakes; destruct RoundsBase_ι_StakeValue_ι_lock; try destruct r. idtac.\n\n  all: cycle 1. idtac.\n\n  destructFunction3 DePoolContract_Ф_cutWithdrawalValue ; auto. idtac.  \n  destruct x; destruct x; auto. idtac.\n\n  Time repeat destructIf_solve. idtac.\n  all: try destructFunction3 DePoolContract_Ф_cutWithdrawalValue ; auto. idtac.  \n  all: try destruct x; try destruct x; auto. idtac.\n  all: time repeat destructIf_solve. idtac.\n\n\n  all: try match goal with \n  | |- ?G => match G with \n             | context [DePoolContract_Ф_cutWithdrawalValue ?a ?b ?c] => \n                   let m := fresh \"m\" in\n                   let p := fresh \"p\" in\n                   remember (DePoolContract_Ф_cutWithdrawalValue a b c) as m\n             end      \n  end.\n\n  all: try setoid_rewrite <- Heqm in Heqm0. idtac.\n  all: try rewrite Heqm0. idtac.\n  all: try rewrite <- Heqr. idtac.\n  all: try rewrite H0; auto. \nQed.  \n  \n\nDefinition DePoolContract_Ф__returnOrReinvestForParticipant_tailer5 (Л_addr : XAddress) \n                                                                    (Л_stakes : RoundsBase_ι_StakeValue)\n                            (f: XAddress -> RoundsBase_ι_StakeValue -> LedgerT (RoundsBase_ι_Round # RoundsBase_ι_Round) )\n                            : LedgerT ( RoundsBase_ι_Round # RoundsBase_ι_Round ):= \n(If (↑12 D2! DePoolContract_ι_m_poolClosed) then { \n\t(↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_attachedValue !+=\n                         D2! LocalState_ι__returnOrReinvestForParticipant_Л_newStake) >>\n\t(If ((↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_newVesting) ->hasValue) then { \n\t(D1! ((↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_newVesting) ->get) ^^ \n                                  RoundsBase_ι_InvestParams_ι_owner ) ->transfer \n                                (! D1! ((↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_newVesting) ->get) ^^ \n                                  RoundsBase_ι_InvestParams_ι_remainingAmount , $xBoolFalse, $ xInt1 !)\n\t}) >>\n\t(If ((↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_newLock) ->hasValue) then { \n\t(D1! ((↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_newLock) ->get) ^^ RoundsBase_ι_InvestParams_ι_owner ) \n                                                                                          ->transfer \n            (! D1! ((↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_newLock) ->get) ^^ \n                                  RoundsBase_ι_InvestParams_ι_remainingAmount , $xBoolFalse, $ xInt1 !)\n    }) \n } else { \n\t(If ((↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_newVesting) ->hasValue) !& \n\t\t(D1! ((↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_newVesting) ->get) ^^ RoundsBase_ι_InvestParams_ι_remainingAmount ?== $xInt0)\n\tthen { \n\t\t ↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_newVesting ->reset \n\t}) >>\n\t(If ((↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_newLock) ->hasValue) !& \n\t\t(D1! ((↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_newLock) ->get) ^^ RoundsBase_ι_InvestParams_ι_remainingAmount ?== $xInt0)\n\tthen { \n\t\t↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_newLock ->reset \n\t}) >>\n\t(If ( !¬ (D1! (↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_participant) ^^ DePoolLib_ι_Participant_ι_reinvest)) then { \n\t\t(↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_attachedValue !+= D2! LocalState_ι__returnOrReinvestForParticipant_Л_newStake) >>\n\t\t(↑17 U1! LocalState_ι__returnOrReinvestForParticipant_Л_newStake := $xInt0)\n\t}) >>\n\t(↑↑17 U2! {( LocalState_ι__returnOrReinvestForParticipant_Л_round0, \n\t\t\t    LocalState_ι__returnOrReinvestForParticipant_Л_participant )} := RoundsBase_Ф__addStakes (! (↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_round0) , \n\t\t\t\t(↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_participant) ,\n\t\t\t\t$Л_addr ,\n\t\t\t\t(↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_newStake) , \n\t\t\t\t(↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_newVesting) ,\n\t\t\t\t(↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_newLock)   !) )\n \n })  >> f Л_addr Л_stakes.\n\nLemma DePoolContract_Ф__returnOrReinvestForParticipant_tailer5_exec : forall\n                                                            (l : Ledger)\n                                                            (Л_addr : XAddress)\n                                                            (Л_stakes : RoundsBase_ι_StakeValue ) \n                                                            (f: XAddress -> RoundsBase_ι_StakeValue -> LedgerT (RoundsBase_ι_Round # RoundsBase_ι_Round) ),\n\nlet m_poolClosed : bool := eval_state (↑12 ε DePoolContract_ι_m_poolClosed) l in\nlet attachedValue := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_attachedValue) l in\nlet newStake := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_newStake) l in\nlet participant := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_participant) l in\nlet reinvest : bool := participant ->> DePoolLib_ι_Participant_ι_reinvest in\nlet newOptVesting := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_newVesting) l in\nlet newOptLock := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_newLock) l in\nlet isVesting : bool := isSome newOptVesting in\nlet isLock : bool := isSome newOptLock in\nlet newVesting := maybeGet newOptVesting in\nlet newLock := maybeGet newOptLock in\nlet round0 := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_round0) l in \n\nlet attachedValue := if m_poolClosed then attachedValue + newStake \n                        else if (negb reinvest) then attachedValue + newStake else attachedValue in\nlet newOptVesting := if m_poolClosed then newOptVesting else\n                     if (isVesting && (newVesting ->> RoundsBase_ι_InvestParams_ι_remainingAmount =? 0))%bool then None\n                     else newOptVesting in\nlet newOptLock := if m_poolClosed then newOptLock else\n                     if (isLock && (newLock ->> RoundsBase_ι_InvestParams_ι_remainingAmount =? 0))%bool then None\n                     else newOptLock in\nlet newStake := if m_poolClosed then newStake else\n                        if (negb reinvest) then 0 else newStake in\nlet (rp, l') :=  if m_poolClosed then \n                    if isVesting then \n                    let lv := exec_state (↓ tvm_transfer (newVesting ->> RoundsBase_ι_InvestParams_ι_owner) \n                                                     (newVesting ->> RoundsBase_ι_InvestParams_ι_remainingAmount) \n                                                     false 1 default) l in\n                    if isLock then ((round0, participant), exec_state (↓ tvm_transfer (newLock ->> RoundsBase_ι_InvestParams_ι_owner) \n                                            (newLock ->> RoundsBase_ι_InvestParams_ι_remainingAmount) \n                                            false 1 default) lv)\n                              else ((round0, participant), lv)\n                    else if isLock then ((round0, participant) , exec_state (↓ tvm_transfer (newLock ->> RoundsBase_ι_InvestParams_ι_owner) \n                                            (newLock ->> RoundsBase_ι_InvestParams_ι_remainingAmount) \n                                            false 1 default) l)\n                            else ((round0, participant) , l)\n                  else  run (↓ RoundsBase_Ф__addStakes round0 participant Л_addr newStake newOptVesting newOptLock) l in\nlet (round0, participant) := rp in   \n\nexec_state (DePoolContract_Ф__returnOrReinvestForParticipant_tailer5 Л_addr Л_stakes f) l = \nexec_state (f Л_addr Л_stakes) {$l' With \n        (LocalState_ι__returnOrReinvestForParticipant_Л_newStake, newStake ); \n        (LocalState_ι__returnOrReinvestForParticipant_Л_newLock, newOptLock);\n        (LocalState_ι__returnOrReinvestForParticipant_Л_newVesting, newOptVesting);\n        (LocalState_ι__returnOrReinvestForParticipant_Л_round0, round0);\n        (LocalState_ι__returnOrReinvestForParticipant_Л_participant, participant);\n        (LocalState_ι__returnOrReinvestForParticipant_Л_attachedValue, attachedValue) $}   .                                                               \nProof.\n\n  intros.\n  destructLedger l. \n  compute. idtac.\n\n  Time repeat destructIf_solve. idtac.\n\n  all: try destructFunction6 RoundsBase_Ф__addStakes ; auto. idtac.  \n  all: try rewrite H0 in H3; try discriminate. idtac.\n  all: try destruct x; auto. \nQed.    \n \n\n\n Definition DePoolContract_Ф__returnOrReinvestForParticipant_tailer6 (Л_addr : XAddress) \n                                                                     (Л_stakes : RoundsBase_ι_StakeValue): LedgerT ( RoundsBase_ι_Round # RoundsBase_ι_Round ) := \n ParticipantBase_Ф__setOrDeleteParticipant (! $Л_addr , (↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_participant)  !) >>\n\n ( ->sendMessage {|| contractAddress ::= $ Л_addr ,\n\t\t\t   contractFunction ::=  IParticipant_И_onRoundCompleteF (!! \n                    ↑17 D1! (D2! LocalState_ι__returnOrReinvestForParticipant_Л_round2) ^^ RoundsBase_ι_Round_ι_id ,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   ↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_reward ,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   $ Л_stakes ->> RoundsBase_ι_StakeValue_ι_ordinary ,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   (($ Л_stakes ->> RoundsBase_ι_StakeValue_ι_vesting) ->hasValue ) ? \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  (D1! (($ Л_stakes ->> RoundsBase_ι_StakeValue_ι_vesting) ->get) ^^ \n                                                   RoundsBase_ι_InvestParams_ι_remainingAmount) ::: $xInt0, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   (($ Л_stakes ->> RoundsBase_ι_StakeValue_ι_lock) ->hasValue ) ? \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  (D1! (($ Л_stakes ->> RoundsBase_ι_StakeValue_ι_lock) ->get) ^^ \n                                                    RoundsBase_ι_InvestParams_ι_remainingAmount) ::: $xInt0 ,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   D1! (↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_participant) ^^ DePoolLib_ι_Participant_ι_reinvest , \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   (completionReason2XInteger (!! \n                                              ↑17 D1! (D2! LocalState_ι__returnOrReinvestForParticipant_Л_round2) ^^ \n                                                    RoundsBase_ι_Round_ι_completionReason !!) ) \n\t\t\t                                                          !!) ,\n\t\t\t   contractMessage ::= {|| messageValue ::= ↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_attachedValue , \n\t\t\t                          messageBounce ::= $xBoolFalse ||} ||} ) >> \n return# ( ↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_round0 , \n           ↑17 D2! LocalState_ι__returnOrReinvestForParticipant_Л_round2 ). \n\n\nLemma DePoolContract_Ф__returnOrReinvestForParticipant_tailer6_exec : forall\n                                                            (l : Ledger)\n                                                            (Л_addr : XAddress)\n                                                            (Л_stakes : RoundsBase_ι_StakeValue ) ,\n let participant := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_participant) l in\n let round2 := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_round2) l in\n let attachedValue := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_attachedValue) l in\n let reward := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_reward) l in\n let isVesting := isSome (Л_stakes ->> RoundsBase_ι_StakeValue_ι_vesting) in\n let vestingAmount := (maybeGet (Л_stakes ->> RoundsBase_ι_StakeValue_ι_vesting)) ->> RoundsBase_ι_InvestParams_ι_remainingAmount in\n let isLock := isSome (Л_stakes ->> RoundsBase_ι_StakeValue_ι_lock) in\n let lockAmount := (maybeGet (Л_stakes ->> RoundsBase_ι_StakeValue_ι_lock)) ->> RoundsBase_ι_InvestParams_ι_remainingAmount in\n\n\n let l' := exec_state (↓ ParticipantBase_Ф__setOrDeleteParticipant Л_addr participant) l in\n let oldMessages := eval_state (↑16 ε VMState_ι_messages) l in \n let newMessage  := {| contractAddress  :=  Л_addr ;\n                       contractFunction := IParticipant_И_onRoundCompleteF (round2 ->> RoundsBase_ι_Round_ι_id)\n                                                                            reward\n                                                                           (Л_stakes ->> RoundsBase_ι_StakeValue_ι_ordinary)\n                                                                           (if isVesting then vestingAmount else 0)\n                                                                           (if isLock then lockAmount else 0)\n                                                                           (participant ->> DePoolLib_ι_Participant_ι_reinvest)\n                                                                           (completionReason2XInteger (round2 ->> RoundsBase_ι_Round_ι_completionReason)) ;\n                       contractMessage :=  {| messageValue := attachedValue;\n                                             messageFlag := 0 ;\n                                             messageBounce := false |} |} in \n\nexec_state (DePoolContract_Ф__returnOrReinvestForParticipant_tailer6 Л_addr Л_stakes ) l =\n {$l' With VMState_ι_messages := newMessage :: oldMessages $}.\nProof.\n\n  intros.\n  destructLedger l. \n  compute. idtac.\n\n  Time repeat destructIf_solve.\n\nQed.    \n\n\nLemma DePoolContract_Ф__returnOrReinvestForParticipant'_eval : forall\n                                                                (l : Ledger)\n                                                                ( Л_round2 : RoundsBase_ι_Round )\n                                                                ( Л_round0 : RoundsBase_ι_Round )\n                                                                ( Л_addr : XAddress )\n                                                                ( Л_stakes : RoundsBase_ι_StakeValue ) \n                                                                ( Л_isValidator : XBool ) \n                                                                ( Л_round1ValidatorsElectedFor : XInteger32 )\n                                                                ( f : XBool -> XBool ->  RoundsBase_ι_StakeValue -> XInteger -> XAddress -> XInteger32 -> LedgerT (RoundsBase_ι_Round # RoundsBase_ι_Round) ),\nlet (stakeSum, l_sum) := run (↓ RoundsBase_Ф_stakeSum Л_stakes) l in\nlet stakeIsLost : bool := eqb (Л_round2 ->> RoundsBase_ι_Round_ι_completionReason) RoundsBase_ι_CompletionReasonP_ι_ValidatorIsPunished in\nlet optParticipant := eval_state (↓ ParticipantBase_Ф_fetchParticipant Л_addr) l_sum in\nlet isSomeParticipant : bool := isSome optParticipant in\nlet participant := maybeGet optParticipant in \nlet participant_newRoundQty :=\n    {$ participant with (DePoolLib_ι_Participant_ι_roundQty, (participant ->> DePoolLib_ι_Participant_ι_roundQty) - 1 ) $} in \nlet lostFunds := if stakeIsLost\n    then    (Л_round2 ->> RoundsBase_ι_Round_ι_stake  -\n              Л_round2 ->> RoundsBase_ι_Round_ι_unused)  -\n              Л_round2 ->> RoundsBase_ι_Round_ι_recoveredStake\n    else 0 in \nlet l_local := {$ l_sum With (LocalState_ι__returnOrReinvestForParticipant_Л_round2, Л_round2);\n                              (LocalState_ι__returnOrReinvestForParticipant_Л_round0, Л_round0);\n                              (LocalState_ι__returnOrReinvestForParticipant_Л_participant, participant_newRoundQty);\n                              (LocalState_ι__returnOrReinvestForParticipant_Л_lostFunds, lostFunds) $} in\n\neval_state (DePoolContract_Ф__returnOrReinvestForParticipant' Л_round2 Л_round0 Л_addr Л_stakes Л_isValidator Л_round1ValidatorsElectedFor f) l =\n    if isSomeParticipant then Value (eval_state (f stakeIsLost Л_isValidator Л_stakes stakeSum Л_addr Л_round1ValidatorsElectedFor) l_local)\n        else Error InternalErrors_ι_ERROR511 .\nProof.            \n  \n  intros.\n  destructLedger l. \n  compute.\n\n  Time repeat destructIf_solve.\n\n  all: try destructFunction1  RoundsBase_Ф_stakeSum ; auto. idtac.\n  all: time repeat destructIf_solve. idtac.  \n  all: try destructFunction5 f ; auto.\n\nQed.  \n\nLemma DePoolContract_Ф__returnOrReinvestForParticipant_tailer1_eval : forall\n                                                            ( l : Ledger )\n                                                            ( Л_stakeIsLost: XBool ) \n                                                            ( Л_isValidator : XBool )\n                                                            ( Л_stakes : RoundsBase_ι_StakeValue ) \n                                                            ( Л_stakeSum: XInteger)\n                                                            ( Л_addr : XAddress)\n                                                            ( Л_round1ValidatorsElectedFor : XInteger32 )\n                                                            ( f : RoundsBase_ι_StakeValue -> XBool -> XBool -> XAddress -> XInteger32 -> LedgerT (RoundsBase_ι_Round # RoundsBase_ι_Round) ),\n\nlet newStake := 0 in\nlet reward := 0 in\nlet lostFunds := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_lostFunds) l in\nlet round2 :=  eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_round2) l in\nlet participant := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_participant) l in\nlet delta := intMin ( Л_stakes ->> RoundsBase_ι_StakeValue_ι_ordinary) lostFunds in\nlet newStake := if Л_stakeIsLost then \n                    if Л_isValidator then \n                        Л_stakes ->> RoundsBase_ι_StakeValue_ι_ordinary - delta\n                                     else (round2 ->> RoundsBase_ι_Round_ι_unused + \n                                           round2 ->> RoundsBase_ι_Round_ι_recoveredStake - \n                                           round2 ->> RoundsBase_ι_Round_ι_validatorRemainingStake) *  \n                                           (Л_stakes ->> RoundsBase_ι_StakeValue_ι_ordinary) /\n                                           (round2 ->> RoundsBase_ι_Round_ι_stake - round2 ->> RoundsBase_ι_Round_ι_validatorStake) \n                                 else Л_stakes ->> RoundsBase_ι_StakeValue_ι_ordinary + \n                                 Л_stakeSum * (round2 ->> RoundsBase_ι_Round_ι_rewards) / (round2 ->> RoundsBase_ι_Round_ι_stake)  in\nlet lostFunds :=   if Л_stakeIsLost then \n                        if Л_isValidator then lostFunds - delta else lostFunds \n                                     else lostFunds in\nlet reward :=  if Л_stakeIsLost then reward\n                                 else Л_stakeSum *  (round2 ->> RoundsBase_ι_Round_ι_rewards) / (round2 ->> RoundsBase_ι_Round_ι_stake) in \nlet round2 :=  if Л_stakeIsLost then \n                        if Л_isValidator then  {$ round2 with RoundsBase_ι_Round_ι_validatorRemainingStake := newStake $}     \n                                         else round2 \n                                     else round2 in   \nlet participant := if Л_stakeIsLost then participant\n                                    else {$ participant with DePoolLib_ι_Participant_ι_reward := participant ->> DePoolLib_ι_Participant_ι_reward + reward $} in \nlet round2 := {$round2 with RoundsBase_ι_Round_ι_handledStakesAndRewards :=  round2 ->> RoundsBase_ι_Round_ι_handledStakesAndRewards + newStake$} in\n\n eval_state (DePoolContract_Ф__returnOrReinvestForParticipant_tailer1 Л_stakeIsLost Л_isValidator Л_stakes Л_stakeSum Л_addr Л_round1ValidatorsElectedFor f) l =\n eval_state (f Л_stakes Л_stakeIsLost Л_isValidator Л_addr Л_round1ValidatorsElectedFor) {$ l With (LocalState_ι__returnOrReinvestForParticipant_Л_lostFunds, lostFunds);\n                                                                      (LocalState_ι__returnOrReinvestForParticipant_Л_round2, round2);\n                                                                      (LocalState_ι__returnOrReinvestForParticipant_Л_participant, participant);\n                                                                      (LocalState_ι__returnOrReinvestForParticipant_Л_newStake, newStake);\n                                                                      (LocalState_ι__returnOrReinvestForParticipant_Л_reward, reward) $}.\nProof.\n\n  intros.\n  destructLedger l. \n  compute.\n\n  Time repeat destructIf_solve.\n\nQed.\n\nLemma DePoolContract_Ф__returnOrReinvestForParticipant_tailer2_eval : forall\n                                                            ( l : Ledger)\n                                                            ( Л_stakes : RoundsBase_ι_StakeValue ) \n                                                            ( Л_stakeIsLost : XBool )  \n                                                            ( Л_isValidator : XBool ) \n                                                            ( Л_addr : XAddress )\n                                                            ( Л_round1ValidatorsElectedFor : XInteger32 )\n                                                            ( f: RoundsBase_ι_StakeValue -> XBool -> XBool -> XAddress -> LedgerT (RoundsBase_ι_Round # RoundsBase_ι_Round) ),\nlet lostFunds := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_lostFunds) l in\nlet round2 := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_round2) l in\nlet newStake := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_newStake) l in\n\nlet optNewVesting := Л_stakes ->> RoundsBase_ι_StakeValue_ι_vesting in\nlet isNewVesting := isSome optNewVesting in\nlet params := maybeGet optNewVesting in\nlet oldVestingAmount := params ->> RoundsBase_ι_InvestParams_ι_remainingAmount in\nlet oldVestingValidatorRemainingStake := round2 ->> RoundsBase_ι_Round_ι_validatorRemainingStake  in\nlet deltaVestingValidator := intMin oldVestingAmount lostFunds in\nlet amount := if Л_stakeIsLost then\n                  if Л_isValidator then oldVestingAmount - deltaVestingValidator\n                                   else (round2 ->> RoundsBase_ι_Round_ι_unused + round2 ->> RoundsBase_ι_Round_ι_recoveredStake - round2 ->> RoundsBase_ι_Round_ι_validatorRemainingStake) *\n                                        (params ->> RoundsBase_ι_InvestParams_ι_remainingAmount) / (round2 ->> RoundsBase_ι_Round_ι_stake - round2 ->> RoundsBase_ι_Round_ι_validatorStake) \n                                  else oldVestingAmount in\nlet lostFunds := if Л_stakeIsLost then \n                      if Л_isValidator then lostFunds - deltaVestingValidator \n                                       else lostFunds \n                                    else lostFunds in \nlet validatorRemainingStake := if Л_stakeIsLost then \n                      if Л_isValidator then oldVestingValidatorRemainingStake + amount\n                                       else oldVestingValidatorRemainingStake \n                                    else oldVestingValidatorRemainingStake in \nlet params := {$ params with RoundsBase_ι_InvestParams_ι_remainingAmount := amount $} in\nlet bPunish := (Л_isValidator && negb (eqb round2 ->> RoundsBase_ι_Round_ι_completionReason RoundsBase_ι_CompletionReasonP_ι_RewardIsReceived))%bool in\nlet punishInterval := Л_round1ValidatorsElectedFor + (round2 ->> RoundsBase_ι_Round_ι_validatorsElectedFor) in\n\nlet (p, l') := run (↓ DePoolContract_Ф_cutWithdrawalValue params bPunish punishInterval) l in\nlet (p, tonsForOwner) := p in\nlet (newVesting, withdrawalVesting) := p in\nlet round2 := {$round2 with (RoundsBase_ι_Round_ι_handledStakesAndRewards, round2 ->> RoundsBase_ι_Round_ι_handledStakesAndRewards + amount) ;\n                            (RoundsBase_ι_Round_ι_validatorRemainingStake, validatorRemainingStake) $} in\nlet l'' := if (tonsForOwner >? 0) then exec_state (↓ tvm_transfer ((maybeGet newVesting) ->> RoundsBase_ι_InvestParams_ι_owner) tonsForOwner false 1 default) l' else l' in \n\neval_state (DePoolContract_Ф__returnOrReinvestForParticipant_tailer2 Л_stakes Л_stakeIsLost Л_isValidator Л_addr Л_round1ValidatorsElectedFor f) l = \n\nif isNewVesting then \n eval_state (f Л_stakes Л_stakeIsLost Л_isValidator Л_addr) {$ l'' With (LocalState_ι__returnOrReinvestForParticipant_Л_lostFunds, lostFunds);\n                                                                       (LocalState_ι__returnOrReinvestForParticipant_Л_round2, round2);\n                                                                       (LocalState_ι__returnOrReinvestForParticipant_Л_newStake, newStake + withdrawalVesting);\n                                                                       (LocalState_ι__returnOrReinvestForParticipant_Л_newVesting, newVesting);\n                                                                       (LocalState_ι__returnOrReinvestForParticipant_Л_params, params) $} else\n eval_state (f Л_stakes Л_stakeIsLost Л_isValidator Л_addr) {$ l With (LocalState_ι__returnOrReinvestForParticipant_Л_newVesting, optNewVesting) $}    .\nProof.\n\n  intros.\n  destructLedger l. \n  compute. idtac.\n\n  destruct Л_stakes; destruct RoundsBase_ι_StakeValue_ι_vesting; try destruct r. idtac.\n\n  all: cycle 1. idtac.\n\n  destructFunction3 DePoolContract_Ф_cutWithdrawalValue ; auto. idtac.  \n  destruct x; destruct x; auto. idtac.\n\n  Time repeat destructIf_solve. idtac.\n  all: try destructFunction3 DePoolContract_Ф_cutWithdrawalValue ; auto. idtac.  \n  all: try destruct x; try destruct x; auto. idtac.\n  all: time repeat destructIf_solve. idtac.\n\n\n  all: try match goal with \n  | |- ?G => match G with \n             | context [DePoolContract_Ф_cutWithdrawalValue ?a ?b ?c] => \n                   let m := fresh \"m\" in\n                   let p := fresh \"p\" in\n                   remember (DePoolContract_Ф_cutWithdrawalValue a b c) as m\n             end      \n  end.\n\n  all: try setoid_rewrite <- Heqm in Heqm0. idtac.\n  all: try rewrite Heqm0. idtac.\n  all: try rewrite <- Heqr. idtac.\n  all: try rewrite H2; auto. idtac.\n  all: try rewrite H1; auto. \nQed.\n\n\nLemma DePoolContract_Ф__returnOrReinvestForParticipant_tailer3_eval : forall\n                                                            (l : Ledger)\n                                                            (Л_stakes : RoundsBase_ι_StakeValue) \n                                                            (Л_stakeIsLost : XBool )\n                                                            (Л_isValidator : XBool )\n                                                            (Л_addr : XAddress)\n                                                            (f: RoundsBase_ι_StakeValue -> XBool -> XBool -> XAddress -> LedgerT (RoundsBase_ι_Round # RoundsBase_ι_Round) ),\n\n\nlet newStake := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_newStake) l in\nlet participant := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_participant) l in\nlet m_minStake := eval_state (↑12 ε DePoolContract_ι_m_minStake) l in\n\nlet curPause := intMin (participant ->> DePoolLib_ι_Participant_ι_withdrawValue) newStake in\nlet attachedValue := 1 + curPause in\nlet participant := {$participant with (DePoolLib_ι_Participant_ι_withdrawValue, (participant ->> DePoolLib_ι_Participant_ι_withdrawValue) - curPause)$} in\nlet newStake := newStake - curPause in\nlet attachedValue := if (newStake <? m_minStake) then attachedValue + newStake else attachedValue in\nlet newStake := if (newStake <? m_minStake) then 0 else newStake in\n\neval_state (DePoolContract_Ф__returnOrReinvestForParticipant_tailer3 Л_stakes Л_stakeIsLost Л_isValidator Л_addr f) l = \n\neval_state (f Л_stakes Л_stakeIsLost Л_isValidator Л_addr)\n{$ l With (LocalState_ι__returnOrReinvestForParticipant_Л_participant, participant);\n        (LocalState_ι__returnOrReinvestForParticipant_Л_newStake, newStake);\n        (LocalState_ι__returnOrReinvestForParticipant_Л_attachedValue, attachedValue)$}.\nProof.\n\n  intros.\n  destructLedger l. \n  compute. idtac.\n\n  Time repeat destructIf_solve.     \nQed.\n\n\n\nLemma DePoolContract_Ф__returnOrReinvestForParticipant_tailer4_eval : forall\n                                                            (l : Ledger)\n                                                            (Л_stakes : RoundsBase_ι_StakeValue ) \n                                                            (Л_stakeIsLost : XBool )  \n                                                            (Л_isValidator : XBool ) \n                                                            (Л_addr : XAddress)\n                                                            (f: XAddress -> RoundsBase_ι_StakeValue -> LedgerT (RoundsBase_ι_Round # RoundsBase_ι_Round) ),\n let lostFunds := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_lostFunds) l in\n let round2 := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_round2) l in\n let optNewLock := Л_stakes ->> RoundsBase_ι_StakeValue_ι_lock in\n let isNewLock := isSome optNewLock in\n let params := maybeGet optNewLock in\n let oldLockAmount := params ->> RoundsBase_ι_InvestParams_ι_remainingAmount in\n let oldLockValidatorRemainingStake := round2 ->> RoundsBase_ι_Round_ι_validatorRemainingStake  in\n let deltaLockValidator := intMin oldLockAmount lostFunds in\n let amount := if Л_stakeIsLost then\n                    if Л_isValidator then oldLockAmount - deltaLockValidator\n                                     else (round2 ->> RoundsBase_ι_Round_ι_unused + round2 ->> RoundsBase_ι_Round_ι_recoveredStake - round2 ->> RoundsBase_ι_Round_ι_validatorRemainingStake) *\n                                          (params ->> RoundsBase_ι_InvestParams_ι_remainingAmount) / (round2 ->> RoundsBase_ι_Round_ι_stake - round2 ->> RoundsBase_ι_Round_ι_validatorStake) \n                                   else oldLockAmount in\n let lostFunds := if Л_stakeIsLost then \n                        if Л_isValidator then lostFunds - deltaLockValidator \n                                         else lostFunds \n                                      else lostFunds in \n let validatorRemainingStake := if Л_stakeIsLost then \n                        if Л_isValidator then oldLockValidatorRemainingStake + amount\n                                         else oldLockValidatorRemainingStake \n                                      else oldLockValidatorRemainingStake in \n let params := {$params with RoundsBase_ι_InvestParams_ι_remainingAmount := amount$} in \n let (p, l') := run (↓ DePoolContract_Ф_cutWithdrawalValue params false 0) l in\n let (p, _) := p in\n let (newLock, withdrawalLock) := p in\n let round2 := {$round2 with (RoundsBase_ι_Round_ι_handledStakesAndRewards, round2 ->> RoundsBase_ι_Round_ι_handledStakesAndRewards + amount) ;\n                             (RoundsBase_ι_Round_ι_validatorRemainingStake, validatorRemainingStake) $} in\n let l'' := if negb (withdrawalLock =? 0) then exec_state (↓ tvm_transfer (params ->> RoundsBase_ι_InvestParams_ι_owner) \n                                                                          withdrawalLock false 1 default) l' else l' in \n\n eval_state (DePoolContract_Ф__returnOrReinvestForParticipant_tailer4 Л_stakes Л_stakeIsLost Л_isValidator Л_addr f) l = \nif isNewLock then \n eval_state (f Л_addr Л_stakes) {$ l'' With (LocalState_ι__returnOrReinvestForParticipant_Л_lostFunds, lostFunds);\n        (LocalState_ι__returnOrReinvestForParticipant_Л_round2, round2);     \n        (LocalState_ι__returnOrReinvestForParticipant_Л_newLock, newLock);\n        (LocalState_ι__returnOrReinvestForParticipant_Л_params, params) $} else\n eval_state (f Л_addr Л_stakes) {$ l With (LocalState_ι__returnOrReinvestForParticipant_Л_newLock, optNewLock) $} .\nProof.\n\n  intros.\n  destructLedger l. \n  compute. idtac.\n\n  destruct Л_stakes; destruct RoundsBase_ι_StakeValue_ι_lock; try destruct r. idtac.\n\n  all: cycle 1. idtac.\n\n  destructFunction3 DePoolContract_Ф_cutWithdrawalValue ; auto. idtac.  \n  destruct x; destruct x; auto. idtac.\n\n  Time repeat destructIf_solve. idtac.\n  all: try destructFunction3 DePoolContract_Ф_cutWithdrawalValue ; auto. idtac.  \n  all: try destruct x; try destruct x; auto. idtac.\n  all: time repeat destructIf_solve. idtac.\n\n\n  all: try match goal with \n  | |- ?G => match G with \n             | context [DePoolContract_Ф_cutWithdrawalValue ?a ?b ?c] => \n                   let m := fresh \"m\" in\n                   let p := fresh \"p\" in\n                   remember (DePoolContract_Ф_cutWithdrawalValue a b c) as m\n             end      \n  end.\n\n  all: try setoid_rewrite <- Heqm in Heqm0. idtac.\n  all: try rewrite Heqm0. idtac.\n  all: try rewrite <- Heqr. idtac.\n  all: try rewrite H0; auto. \nQed.  \n\n\nLemma DePoolContract_Ф__returnOrReinvestForParticipant_tailer5_eval : forall\n                                                            (l : Ledger)\n                                                            (Л_addr : XAddress)\n                                                            (Л_stakes : RoundsBase_ι_StakeValue ) \n                                                            (f: XAddress -> RoundsBase_ι_StakeValue -> LedgerT (RoundsBase_ι_Round # RoundsBase_ι_Round) ),\n\nlet m_poolClosed : bool := eval_state (↑12 ε DePoolContract_ι_m_poolClosed) l in\nlet attachedValue := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_attachedValue) l in\nlet newStake := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_newStake) l in\nlet participant := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_participant) l in\nlet reinvest : bool := participant ->> DePoolLib_ι_Participant_ι_reinvest in\nlet newOptVesting := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_newVesting) l in\nlet newOptLock := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_newLock) l in\nlet isVesting : bool := isSome newOptVesting in\nlet isLock : bool := isSome newOptLock in\nlet newVesting := maybeGet newOptVesting in\nlet newLock := maybeGet newOptLock in\nlet round0 := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_round0) l in \n\nlet attachedValue := if m_poolClosed then attachedValue + newStake \n                        else if (negb reinvest) then attachedValue + newStake else attachedValue in\nlet newOptVesting := if m_poolClosed then newOptVesting else\n                     if (isVesting && (newVesting ->> RoundsBase_ι_InvestParams_ι_remainingAmount =? 0))%bool then None\n                     else newOptVesting in\nlet newOptLock := if m_poolClosed then newOptLock else\n                     if (isLock && (newLock ->> RoundsBase_ι_InvestParams_ι_remainingAmount =? 0))%bool then None\n                     else newOptLock in\nlet newStake := if m_poolClosed then newStake else\n                        if (negb reinvest) then 0 else newStake in\nlet (rp, l') :=  if m_poolClosed then \n                    if isVesting then \n                    let lv := exec_state (↓ tvm_transfer (newVesting ->> RoundsBase_ι_InvestParams_ι_owner) \n                                                     (newVesting ->> RoundsBase_ι_InvestParams_ι_remainingAmount) \n                                                     false 1 default) l in\n                    if isLock then ((round0, participant), exec_state (↓ tvm_transfer (newLock ->> RoundsBase_ι_InvestParams_ι_owner) \n                                            (newLock ->> RoundsBase_ι_InvestParams_ι_remainingAmount) \n                                            false 1 default) lv)\n                              else ((round0, participant), lv)\n                    else if isLock then ((round0, participant) , exec_state (↓ tvm_transfer (newLock ->> RoundsBase_ι_InvestParams_ι_owner) \n                                            (newLock ->> RoundsBase_ι_InvestParams_ι_remainingAmount) \n                                            false 1 default) l)\n                            else ((round0, participant) , l)\n                  else  run (↓ RoundsBase_Ф__addStakes round0 participant Л_addr newStake newOptVesting newOptLock) l in\nlet (round0, participant) := rp in   \n\neval_state (DePoolContract_Ф__returnOrReinvestForParticipant_tailer5 Л_addr Л_stakes f) l = \neval_state (f Л_addr Л_stakes) {$l' With \n        (LocalState_ι__returnOrReinvestForParticipant_Л_newStake, newStake ); \n        (LocalState_ι__returnOrReinvestForParticipant_Л_newLock, newOptLock);\n        (LocalState_ι__returnOrReinvestForParticipant_Л_newVesting, newOptVesting);\n        (LocalState_ι__returnOrReinvestForParticipant_Л_round0, round0);\n        (LocalState_ι__returnOrReinvestForParticipant_Л_participant, participant);\n        (LocalState_ι__returnOrReinvestForParticipant_Л_attachedValue, attachedValue) $}   .                                                               \nProof.\n\n  intros.\n  destructLedger l. \n  compute. idtac.\n\n  Time repeat destructIf_solve. idtac.\n\n  all: try destructFunction6 RoundsBase_Ф__addStakes ; auto. idtac.  \n  all: try rewrite H0 in H3; try discriminate. idtac.\n  all: try destruct x; auto. \nQed.    \n\n\nLemma DePoolContract_Ф__returnOrReinvestForParticipant_tailer6_eval : forall\n                                                            (l : Ledger)\n                                                            (Л_addr : XAddress)\n                                                            (Л_stakes : RoundsBase_ι_StakeValue ) ,\n let round0 := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_round0) l in\n let round2 := eval_state (↑17 ε LocalState_ι__returnOrReinvestForParticipant_Л_round2) l in\n\neval_state (DePoolContract_Ф__returnOrReinvestForParticipant_tailer6 Л_addr Л_stakes ) l = (round0, round2).\n\n\nProof.\n\n  intros.\n  destructLedger l. \n  compute. idtac.\n\n  Time repeat destructIf_solve.\n\nQed.    \n\nEnd DePoolContract_Ф__returnOrReinvestForParticipant.", "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__returnOrReinvestForParticipant.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.63341024983754, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.27976020886452774}}
{"text": "Require Import Mtac2.Mtac2.\n\nDefinition test {A} (o : M (moption A)) : M _ :=\n  o <- o;\n  match o with mSome x => M.ret x | _ => M.raise exception end.\n\nGoal True =m= True.\nMProof.\n  test (M.unify True True UniCoq).\nQed.\n\nGoal True =m= False.\nMProof.\n  Fail test (M.unify True False UniCoq).\nAbort.\n\nImport M. Import M.notations.\n\nDefinition test_unfold := 1 + 1.\nSet Unicoq Debug.\nFail Eval hnf in ltac:(mrun (\n     A <- evar Type;\n     t1 <- evar (A -> nat);\n     t2 <- evar A;\n     unify_or_fail UniMatchNoRed (t1 t2) test_unfold;;\n     M.ret 0)).  (* Should fail: it shouldn't unfold test *)\n", "meta": {"author": "Mtac2", "repo": "Mtac2", "sha": "d16c2e682d5ab18ed77b13b4fd60a42a65c4f958", "save_path": "github-repos/coq/Mtac2-Mtac2", "path": "github-repos/coq/Mtac2-Mtac2/Mtac2-d16c2e682d5ab18ed77b13b4fd60a42a65c4f958/tests/test_munify.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2797286386959738}}
{"text": "From Cat Require Export Cat.\n\nSet Implicit Arguments.\n\nClass isCoproduct\n  (C : Cat) {A B : Ob C}\n  (P : Ob C) (finl : Hom A P) (finr : Hom B P)\n  (copair : forall {P' : Ob C}, Hom A P' -> Hom B P' -> Hom P P')\n  : Prop :=\n{\n  finl_copair :\n    forall (P' : Ob C) (f : Hom A P') (g : Hom B P'),\n      finl .> copair f g == f;\n  finr_copair :\n    forall (P' : Ob C) (f : Hom A P') (g : Hom B P'),\n      finr .> copair f g == g;\n  equiv_coproduct :\n    forall (P' : Ob C) (h1 h2 : Hom P P'),\n      finl .> h1 == finl .> h2 -> finr .> h1 == finr .> h2 -> h1 == h2\n}.\n\n#[export] Hint Mode isCoproduct ! ! ! ! ! ! ! : core.\n#[export] Hint Mode isCoproduct ! ! ! - - - - : core.\n\nLemma equiv_coproduct' :\n  forall\n    {C : Cat} {A B : Ob C}\n    {P : Ob C} {finl : Hom A P} {finr : Hom B P}\n    {copair : forall {P' : Ob C} (finl' : Hom A P') (finr' : Hom B P'), Hom P P'}\n    {isP : isCoproduct C P finl finr (@copair)}\n    {Y : Ob C} (h1 h2 : Hom P Y),\n      h1 == h2 <-> finl .> h1 == finl .> h2 /\\ finr .> h1 == finr .> h2.\nProof.\n  split.\n  - now intros ->.\n  - now intros []; apply equiv_coproduct.\nQed.\n\nSection isCoproduct.\n\nContext\n  {C : Cat} {A B : Ob C}\n  {P : Ob C} {finl : Hom A P} {finr : Hom B P}\n  {copair : forall {P' : Ob C} (finl' : Hom A P') (finr' : Hom B P'), Hom P P'}\n  {isP : isCoproduct C P finl finr (@copair)}\n  [P' : Ob C] [f : Hom A P'] [g : Hom B P'].\n\nArguments copair {P'} _ _.\n\n#[global] Instance Proper_copair :\n  Proper (equiv ==> equiv ==> equiv) (@copair P').\nProof.\n  intros h1 h1' Heq1 h2 h2' Heq2.\n  now rewrite equiv_coproduct', !finl_copair, !finr_copair.\nDefined.\n\nLemma copair_universal :\n  forall h : Hom P P',\n    copair f g == h <-> f == finl .> h /\\ g == finr .> h.\nProof.\n  now intros; rewrite equiv_coproduct', finl_copair, finr_copair.\nQed.\n\nLemma copair_unique :\n  forall h : Hom P P',\n    finl .> h == f -> finr .> h == g -> h == copair f g.\nProof.\n  now intros; rewrite equiv_coproduct', finl_copair, finr_copair.\nQed.\n\nLemma copair_id :\n  copair finl finr == id P.\nProof.\n  now rewrite equiv_coproduct', finl_copair, finr_copair, !comp_id_r.\nQed.\n\nLemma copair_comp :\n  forall {Y : Ob C} {h : Hom P' Y},\n    copair f g .> h == copair (f .> h) (g .> h).\nProof.\n  now intros; rewrite equiv_coproduct', <- !comp_assoc, !finl_copair, !finr_copair.\nQed.\n\nEnd isCoproduct.\n\nLtac coproduct_simpl :=\n  repeat (rewrite\n    ?equiv_coproduct', ?finl_copair, ?finr_copair, ?copair_id, ?copair_comp,\n    ?comp_id_l, ?comp_id_r, ?comp_assoc).\n\nLemma isCoproduct_uiso :\n  forall\n    (C : Cat) (A B : Ob C)\n    (P1 : Ob C) (finl1 : Hom A P1) (finr1 : Hom B P1)\n    (copair1 : forall (P1' : Ob C) (finl1' : Hom A P1') (finr1' : Hom B P1'), Hom P1 P1')\n    (P2 : Ob C) (finl2 : Hom A P2) (finr2 : Hom B P2)\n    (copair2 : forall (P2' : Ob C) (finl2' : Hom A P2') (finr2' : Hom B P2'), Hom P2 P2'),\n      isCoproduct C P1 finl1 finr1 copair1 ->\n      isCoproduct C P2 finl2 finr2 copair2 ->\n        exists!! f : Hom P1 P2, isIso f /\\ finl2 == finl1 .> f /\\ finr2 == finr1 .> f.\nProof.\n  intros * H1 H2.\n  exists (copair1 P2 finl2 finr2).\n  repeat split.\n  - exists (copair2 P1 finl1 finr1).\n    now rewrite !equiv_coproduct', <- !comp_assoc, !finl_copair, !finr_copair, !comp_id_r.\n  - now rewrite finl_copair.\n  - now rewrite finr_copair.\n  - intros u (HIso & Heql & Heqr).\n    now rewrite equiv_coproduct', finl_copair, finr_copair.\nQed.\n\nLemma isCoproduct_iso :\n  forall\n    (C : Cat) (A B : Ob C)\n    (P1 : Ob C) (finl1 : Hom A P1) (finr1 : Hom B P1)\n    (copair1 : forall (P1' : Ob C) (finl1' : Hom A P1') (finr1' : Hom B P1'), Hom P1 P1')\n    (P2 : Ob C) (finl2 : Hom A P2) (finr2 : Hom B P2)\n    (copair2 : forall (P2' : Ob C) (finl2' : Hom A P2') (finr2' : Hom B P2'), Hom P2 P2'),\n      isCoproduct C P1 finl1 finr1 copair1 ->\n      isCoproduct C P2 finl2 finr2 copair2 ->\n        P1 ~ P2.\nProof.\n  now intros; destruct (isCoproduct_uiso H H0) as [i []]; exists i.\nQed.\n\nLemma isCoproduct_equiv_copair :\n  forall\n    (C : Cat) (X Y : Ob C)\n    (P : Ob C) (finl : Hom X P) (finr : Hom Y P)\n    (copair1 copair2 : forall (A : Ob C) (f : Hom X A) (g : Hom Y A), Hom P A),\n      isCoproduct C P finl finr copair1 ->\n      isCoproduct C P finl finr copair2 ->\n        forall (A : Ob C) (f : Hom X A) (g : Hom Y A),\n          copair1 A f g == copair2 A f g.\nProof.\n  now intros; rewrite equiv_coproduct', !finl_copair, !finr_copair.\nQed.\n\nLemma isCoproduct_equiv_finl :\n  forall\n    (C : Cat) (X Y : Ob C)\n    (P : Ob C) (finl1 finl2 : Hom X P) (finr : Hom Y P)\n    (copair : forall (A : Ob C) (f : Hom X A) (g : Hom Y A), Hom P A),\n      isCoproduct C P finl1 finr copair ->\n      isCoproduct C P finl2 finr copair ->\n        finl1 == finl2.\nProof.\n  now intros; rewrite <- finl_copair, copair_id, comp_id_r.\nQed.\n\nLemma isCoproduct_equiv_finr :\n  forall\n    (C : Cat) (X Y : Ob C)\n    (P : Ob C) (finl : Hom X P) (finr1 finr2 : Hom Y P)\n    (copair : forall (A : Ob C) (f : Hom X A) (g : Hom Y A), Hom P A),\n      isCoproduct C P finl finr1 copair ->\n      isCoproduct C P finl finr2 copair ->\n        finr1 == finr2.\nProof.\n  now intros; rewrite <- finr_copair, copair_id, comp_id_r.\nQed.\n\nLemma iso_to_coproduct :\n  forall\n    (C : Cat) (A B : Ob C)\n    (P : Ob C) (finl : Hom A P) (finr : Hom B P)\n    (copair : forall P' : Ob C, Hom A P' -> Hom B P' -> Hom P P'),\n      isCoproduct C P finl finr copair ->\n        forall {P' : Ob C} (f : Hom P P') (H : isIso f),\n          exists g : Hom P' P,\n            isCoproduct C P' (finl .> f) (finr .> f) (fun Γ a b => g .> copair Γ a b).\nProof.\n  intros * H P' f (g & Hfg & Hgf).\n  exists g.\n  split; intros.\n  - now rewrite comp_assoc, <- (comp_assoc f g), Hfg, comp_id_l, finl_copair.\n  - now rewrite comp_assoc, <- (comp_assoc f g), Hfg, comp_id_l, finr_copair.\n  - rewrite <- (comp_id_l h1), <- (comp_id_l h2), <- Hgf, !comp_assoc; f_equiv.\n    now rewrite equiv_coproduct', <- !comp_assoc.\nQed.\n\nLemma isCoproduct_comm :\n  forall\n    (C : Cat) (X Y : Ob C)\n    (P : Ob C) (finl : Hom X P) (finr : Hom Y P)\n    (copair : forall (A : Ob C) (f : Hom X A) (g : Hom Y A), Hom P A),\n      isCoproduct C P finl finr copair ->\n        isCoproduct C P finr finl (fun A f g => copair A g f).\nProof.\n  split; intros.\n  - now rewrite finr_copair.\n  - now rewrite finl_copair.\n  - now rewrite equiv_coproduct'.\nQed.\n\nClass HasCoproducts (C : Cat) : Type :=\n{\n  coproduct : Ob C -> Ob C -> Ob C;\n  finl      : forall {A B : Ob C}, Hom A (coproduct A B);\n  finr      : forall {A B : Ob C}, Hom B (coproduct A B);\n  copair    : forall {A B : Ob C} {P : Ob C} (f : Hom A P) (g : Hom B P), Hom (coproduct A B) P;\n  isCoproduct_HasCoproducts' :>\n    forall {A B : Ob C}, isCoproduct C (@coproduct A B) finl finr (@copair A B);\n}.\n\nArguments coproduct {C HasCoproducts} _ _.\nArguments finl      {C HasCoproducts A B}.\nArguments finr      {C HasCoproducts A B}.\nArguments copair    {C HasCoproducts A B P} _ _.\n\nLtac solve_coproduct := intros; try split;\nrepeat match goal with\n| |- context [copair (finl .> ?x) (finr .> ?x)] => rewrite <- copair_comp, copair_id\n| |- context [copair _ _ .> _] => rewrite copair_comp\n| |- context [finl .> copair _ _] => rewrite finl_copair\n| |- context [finr .> copair _ _] => rewrite finr_copair\n| |- context [copair finl finr] => rewrite copair_id\n| |- ?x == ?x => reflexivity\n| |- copair _ _ == _ => apply equiv_coproduct\n| |- _ == copair _ _ => apply equiv_coproduct\n| |- context [id _ .> _] => rewrite comp_id_l\n| |- context [_ .> id _] => rewrite comp_id_r\n| |- copair _ _ == id (coproduct _ _) => rewrite <- copair_id; apply Proper_copair\n| |- ?f .> ?g == ?f .> ?g' => f_equiv\n| |- ?f .> ?g == ?f' .> ?g => f_equiv\n| _ => rewrite ?comp_assoc; auto\nend.\n\nLtac coproduct_simpl' :=\nrepeat match goal with\n| |- context [copair (finl .> ?x) (finr .> ?x)] => rewrite <- copair_comp, copair_id\n| |- context [copair _ _ .> _] => rewrite copair_comp\n| |- context [finl .> copair _ _] => rewrite finl_copair\n| |- context [finr .> copair _ _] => rewrite finr_copair\n| |- context [copair finl finr] => rewrite copair_id\n| |- context [id _ .> _] => rewrite comp_id_l\n| |- context [_ .> id _] => rewrite comp_id_r\n| H : context [copair (finl .> ?x) (finr .> ?x)] |- _ => rewrite <- copair_comp, copair_id in H\n| H : context [copair _ _ .> _] |- _ => rewrite copair_comp in H\n| H : context [finl .> copair _ _] |- _ => rewrite finl_copair in H\n| H : context [finr .> copair _ _] |- _ => rewrite finr_copair in H\n| H : context [copair finl finr] |- _ => rewrite copair_id in H\n| H : context [id _ .> _] |- _ => rewrite comp_id_l in H\n| H : context [_ .> id _] |- _ => rewrite comp_id_r in H\nend.\n\nLemma copair_comp' :\n  forall\n    (C : Cat) (hp : HasCoproducts C) (X Y X' Y' A : Ob C)\n    (f : Hom X A) (g : Hom Y A) (h1 : Hom X' X) (h2 : Hom Y' Y),\n      copair (h1 .> finl) (h2 .> finr) .> copair f g == copair (h1 .> f) (h2 .> g).\nProof. now solve_coproduct. Qed.\n\nLemma copair_comp_id :\n  forall (C : Cat) (hp : HasCoproducts C) (A X Y : Ob C) (f : Hom (coproduct X Y) A),\n    copair (finl .> f) (finr .> f) == f.\nProof.\n  now intros; rewrite equiv_coproduct', finl_copair, finr_copair.\nQed.\n\nDefinition commutator\n  {C : Cat} {hp : HasCoproducts C} {A B : Ob C}\n  : Hom (coproduct A B) (coproduct B A) :=\n    copair finr finl.\n\nLemma commutator_idem :\n  forall {C : Cat} {hp : HasCoproducts C} {A B : Ob C},\n    commutator .> commutator == id (coproduct A B).\nProof.\n  now unfold commutator; solve_coproduct.\nQed.\n\nLemma isIso_commutator :\n  forall {C : Cat} {hp : HasCoproducts C} {A B : Ob C},\n    isIso (@commutator _ _ A B).\nProof.\n  red; intros.\n  exists commutator.\n  now split; apply commutator_idem.\nQed.\n\nLemma coproduct_comm :\n  forall (C : Cat) (hp : HasCoproducts C) (X Y : Ob C),\n    coproduct X Y ~ coproduct Y X.\nProof.\n  red; intros.\n  exists commutator.\n  now apply isIso_commutator.\nQed.\n\nDefinition associator\n  {C : Cat} {hp : HasCoproducts C} {A B C : Ob C}\n  : Hom (coproduct (coproduct A B) C) (coproduct A (coproduct B C)) :=\n    copair (copair finl (finl .> finr)) (finr .> finr).\n\nDefinition unassociator\n  {C : Cat} {hp : HasCoproducts C} {A B C : Ob C}\n  : Hom (coproduct A (coproduct B C)) (coproduct (coproduct A B) C) :=\n    copair (finl .> finl) (copair (finr .> finl) finr).\n\nLemma associator_unassociator :\n  forall {C : Cat} {hp : HasCoproducts C} {A B C : Ob C},\n    associator .> unassociator == id (coproduct (coproduct A B) C).\nProof.\n  now unfold associator, unassociator; solve_coproduct.\nQed.\n\nLemma unassociator_associator :\n  forall {C : Cat} {hp : HasCoproducts C} {A B C : Ob C},\n    unassociator .> associator == id (coproduct A (coproduct B C)).\nProof.\n  now unfold associator, unassociator; solve_coproduct.\nQed.\n\nLemma isIso_associator :\n  forall {C : Cat} {hp : HasCoproducts C} {A B C : Ob C},\n    isIso (@associator _ _ A B C).\nProof.\n  red; intros.\n  exists unassociator.\n  split.\n  - now apply associator_unassociator.\n  - now apply unassociator_associator.\nQed.\n\nLemma isIso_unassociator :\n  forall {C : Cat} {hp : HasCoproducts C} {A B C : Ob C},\n    isIso (@unassociator _ _ A B C).\nProof.\n  red; intros.\n  exists associator.\n  split.\n  - now apply unassociator_associator.\n  - now apply associator_unassociator.\nQed.\n\nLemma coproduct_assoc :\n  forall (C : Cat) (hp : HasCoproducts C) (X Y Z : Ob C),\n    coproduct X (coproduct Y Z) ~ coproduct (coproduct X Y) Z.\nProof.\n  red; intros.\n  exists unassociator.\n  now apply isIso_unassociator.\nQed.\n\nLemma coproduct_assoc' :\n  forall (C : Cat) (hp : HasCoproducts C) (X Y Z : Ob C),\n    {f : Hom (coproduct (coproduct X Y) Z) (coproduct X (coproduct Y Z)) | isIso f}.\nProof.\n  intros.\n  exists associator.\n  now apply isIso_associator.\nDefined.\n\nDefinition codiag {C : Cat} {hp : HasCoproducts C} {A : Ob C} : Hom (coproduct A A) A :=\n  copair (id A) (id A).\n\n#[refine]\n#[export]\nInstance CoproductBifunctor {C : Cat} {hp : HasCoproducts C} : Bifunctor C C C :=\n{\n  biob := @coproduct C hp;\n  bimap := fun (X Y X' Y' : Ob C) (f : Hom X Y) (g : Hom X' Y') => copair (f .> finl) (g .> finr)\n}.\nProof.\n  - now proper.\n  - now solve_coproduct.\n  - now solve_coproduct.\nDefined.\n\nNotation \"A + B\" := (@biob _ _ _ (@CoproductBifunctor _ _) A B).\nNotation \"f +' g\" := (@bimap _ _ _ (@CoproductBifunctor _ _) _ _ _ _ f g) (at level 40).", "meta": {"author": "wkolowski", "repo": "CoqCat", "sha": "e67e486f3c3c1ad0c224b68eb53194189c8f04bc", "save_path": "github-repos/coq/wkolowski-CoqCat", "path": "github-repos/coq/wkolowski-CoqCat/CoqCat-e67e486f3c3c1ad0c224b68eb53194189c8f04bc/Universal/Coproduct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.27972726070270953}}
{"text": "Require Import List.\nImport ListNotations.\n\nRequire Export SystemFR.ErasedArrow.\nRequire Export SystemFR.ErasedBool.\nRequire Export SystemFR.ErasedPair.\nRequire Export SystemFR.NatEq.\nRequire Export SystemFR.EquivalenceLemmas2.\n\nOpaque reducible_values.\n\nDefinition computable_equality_with f_eq ρ T : Prop :=\n  wf f_eq 0 /\\\n  is_erased_term f_eq /\\\n  pfv f_eq term_var = nil /\\\n  [ ρ ⊨ f_eq : T_arrow T (T_arrow T T_bool) ] /\\\n  forall v1 v2,\n    [ ρ ⊨ v1 : T ]v ->\n    [ ρ ⊨ v2 : T ]v ->\n      app (app f_eq v1) v2 ~>* ttrue <->\n      [ v1 ≡ v2 ].\n\nDefinition computable_equality ρ T : Prop :=\n  exists f_eq,\n    computable_equality_with f_eq ρ T.\n\nLemma computable_equality_subtype:\n  forall ρ A B,\n    computable_equality ρ A ->\n    valid_interpretation ρ ->\n    [ ρ ⊨ B <: A ] ->\n    is_erased_type B ->\n    wf A 0 ->\n    wf B 0 ->\n    computable_equality ρ B.\nProof.\n  unfold computable_equality, computable_equality_with;\n    repeat step.\n\n  eexists; steps;\n    eauto with apply_any.\n\n  eapply reducible_values_exprs; try eassumption;\n    repeat step || simp_red || apply_any || open_none.\n\n  repeat unfold reduces_to in *; steps; t_closer.\n\n  unshelve epose proof (H13 a _ _ _ _); repeat step || open_none.\n  exists v1; repeat step || simp_red.\nQed.\n\nLemma computable_equality_prod:\n  forall ρ A B,\n    valid_interpretation ρ ->\n    wf A 0 ->\n    wf B 0 ->\n    is_erased_type A ->\n    is_erased_type B ->\n    pfv A term_var = nil ->\n    pfv B term_var = nil ->\n    computable_equality ρ A ->\n    computable_equality ρ B ->\n    computable_equality ρ (T_prod A B).\nProof.\n  unfold computable_equality, computable_equality_with; steps.\n  exists (notype_lambda (notype_lambda (\n    ite (app (app f_eq0 (pi1 (lvar 1 term_var))) (pi1 (lvar 0 term_var)))\n        (app (app f_eq (pi2 (lvar 1 term_var))) (pi2 (lvar 0 term_var)))\n        tfalse)));\n    repeat step || simp_red || list_utils; eauto with wf.\n\n  - apply reducible_value_expr; auto.\n    apply reducible_lambda; repeat step || list_utils || open_none; t_closer.\n    apply reducible_value_expr; auto.\n    apply reducible_lambda; repeat step || list_utils || open_none; t_closer.\n\n    apply reducible_ite; repeat step; t_closer;\n      eauto using reducible_value_expr, reducible_false.\n    + apply reducible_app2 with A; steps; eauto using reducible_value_expr, reducible_pi1.\n      apply reducible_app2 with A; steps; eauto using reducible_value_expr, reducible_pi1.\n    + apply reducible_app2 with B; steps; eauto using reducible_value_expr, reducible_pi2_nodep.\n      apply reducible_app2 with B; steps; eauto using reducible_value_expr, reducible_pi2_nodep.\n\n  - reverse_once; repeat open_none; eauto with values.\n    reverse_once; repeat open_none.\n    reverse_once; repeat open_none || step; eauto with values.\n    apply star_smallstep_value in H45; steps; eauto with values.\n    apply star_smallstep_value in H46; steps; eauto with values.\n    reverse_once; repeat open_none.\n    apply equivalent_pp.\n    + apply H16; steps.\n      apply equivalent_star_true with (app (app f_eq0 (pi1 (pp a0 b0))) (pi1 (pp v1 v0)));\n        repeat apply equivalent_app || step;\n        try solve [ apply equivalent_refl; steps ];\n        try solve [ apply equivalent_star; steps; t_closer; eauto using star_one with smallstep ].\n    + apply H12; steps.\n      apply equivalent_star_true with (app (app f_eq (pi2 (pp a0 b0))) (pi2 (pp v1 v0)));\n        repeat apply equivalent_app || step;\n        try solve [ apply equivalent_refl; steps ];\n        try solve [ apply equivalent_star; steps; t_closer; eauto using star_one with smallstep ].\n\n  - one_step.\n    one_step.\n    apply_anywhere equivalent_value_pair; steps; t_closer.\n    apply star_smallstep_ite_true.\n    + apply equivalent_star_true with (app (app f_eq0 a0) v1');\n        repeat apply equivalent_app || step;\n        try solve [ apply equivalent_refl; steps ];\n        try solve [ apply equivalent_sym, equivalent_star; steps; t_closer;\n                    apply star_one; constructor; t_closer ];\n        eauto with apply_any.\n    + apply equivalent_star_true with (app (app f_eq b0) v2');\n        repeat apply equivalent_app || step;\n        try solve [ apply equivalent_refl; steps ];\n        try solve [ apply equivalent_sym, equivalent_star; steps; t_closer;\n                    apply star_one; constructor; t_closer ];\n        eauto with apply_any.\nQed.\n\nLemma computable_equality_with_nat_eq:\n  computable_equality_with nat_eq_fix [] T_nat.\nProof.\n  unfold computable_equality_with; repeat step || simp_red; eauto with lia.\n  - unfold nat_eq_fix.\n    eapply backstep_reducible; steps; eauto with lia; eauto with smallstep;\n      repeat step.\n\n    apply reducible_value_expr; steps.\n    apply reducible_lambda; steps; eauto with lia.\n    apply reducible_value_expr; steps.\n    assert (valid_interpretation []); steps.\n    apply reducible_lambda; repeat step || simp_red || list_utils || open_none; eauto with lia; t_closer.\n\n    apply star_smallstep_reducible with (nat_eq u u0);\n      repeat step || unfold reduces_to;\n      try solve [\n        unfold nat_eq, nat_eq_fix, closed_term; repeat step || list_utils; eauto with lia; t_closer\n      ].\n\n    + unfold nat_eq, nat_eq_fix.\n      one_step; steps.\n      one_step; steps.\n      one_step; steps.\n    + unshelve epose proof (nat_eq_bool u _ u0 _); steps;\n        try solve [ eexists; steps; try eassumption; repeat step || simp_red ].\n\n  - apply_anywhere nat_eq_sound; steps; t_closer.\n    apply equivalent_refl; t_closer.\n  - apply_anywhere equivalent_value_nat; steps; eauto with values;\n      eauto using nat_eq_complete2.\nQed.\n\nLemma computable_equality_nat:\n  computable_equality [] T_nat.\nProof.\n  unfold computable_equality;\n    eauto using computable_equality_with_nat_eq.\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/ComputableEquality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2797272536582714}}
{"text": "From Undecidability.L.Datatypes Require Import LNat Lists LProd LFinType LVector .\nFrom Undecidability.L Require Import Functions.FinTypeLookup Functions.EqBool.\n\nFrom Undecidability.L Require Import TM.TapeFuns.\n\nFrom Undecidability.TM Require Import TM_facts.\n\nSet Default Proof Using \"Type\".\nLocal Notation L := TM.Lmove.\nLocal Notation R := TM.Rmove.\nLocal Notation N := TM.Nmove.\n\nSection loopM.\n  Context (sig : finType).\n  Let reg_sig := @encodable_finType sig.\n  Existing Instance reg_sig.\n  \n  Let eqb_sig := eqbFinType_inst (X:=sig).\n  Existing Instance eqb_sig.\n  Variable n : nat.\n  Variable M : TM sig n.\n\n  Let reg_state := @encodable_finType (state M).\n  Existing Instance reg_state.\n\n  Let eqb_state := eqbFinType_inst (X:=state M).\n  Existing Instance eqb_state.\n  Import Vector.\n  \n  Local Definition c__trans :=\n       (length ( elem (state M) ) * 4 + (n * (4 * length ( elem sig ) + 10) + 4) + 4) *\n       c__eqbComp (finType_CS (state M * VectorDef.t (option sig) n)).\n  Definition transTime := (| funTable (trans (m:=M)) |) * (c__trans + 24) + 4 + 9.\n  (* *** Computability of transition relation *)\n  Global Instance term_trans : computableTime' (trans (m:=M)) (fun _ _ => (transTime,tt)).\n  Proof.\n    pose (t:= (funTable (trans (m:=M)))).\n    apply computableTimeExt with (x:= (fun c => lookup c t (start M,Vector.const (None , N) _ ) )).\n    2:{ remember t as lock__t .\n         extract. solverec. subst lock__t .\n        rewrite lookupTime_leq.\n                                        setoid_rewrite size_prod;cbn [fst snd].\n         unfold reg_state;rewrite (size_finType_le a).\n         \n         rewrite enc_vector_eq. evar (c__elem' : nat).\n         evar (c__elem : nat). \n         rewrite size_list,sumn_le_bound with (c:=c__elem).\n         2:{\n           intros ? (?&<-&?)%in_map_iff.\n           rewrite LOptions.size_option.\n           [c__elem]: exact( c__elem' + 10). subst c__elem.\n           destruct x. 2: { unfold c__listsizeCons. lia. } \n           unfold reg_sig;rewrite (size_finType_le e).\n           ring_simplify.\n           [c__elem']: exact (4 * (| elem sig |)). subst c__elem'. unfold c__listsizeCons. lia.\n         }\n         rewrite map_length,to_list_length.\n         unfold c__elem',transTime,c__trans,t,c__elem. reflexivity.\n    }\n    \n    cbn -[t] ;intro. subst t.  setoid_rewrite lookup_funTable. reflexivity.\n  Qed.\n\n  Definition step' (c :  mconfig sig (state M) n) : mconfig sig (state M) n :=\n    let (news, actions) := trans (cstate c, current_chars (ctapes c)) in\n    mk_mconfig news (doAct_multi (ctapes c) actions).\n\n  Global Instance term_doAct_multi: computableTime' (doAct_multi (n:=n) (sig:=sig)) (fun _ _ => (1,fun _ _ =>(n * 108 + 123,tt))).\n  Proof.\n    extract.\n    solverec.\n    rewrite time_map2_leq with (k:=90).\n    2:now solverec.\n    solverec. now rewrite to_list_length.\n  Qed.\n\n\n  Global Instance term_step' : computableTime' (step (M:=M)) (fun _ _ => (n* 130+ transTime + 172,tt)).\n  Proof.\n    extract.\n    solverec.\n  Qed.\n\n  Local Definition cHalt := ((| elem (state M) |) * 4 * c__eqbComp (state M) + 24).\n\n  Definition haltTime := length (funTable (halt (m:=M))) * cHalt + 12.\n\n  Global Instance term_halt : computableTime' (halt (m:=M)) (fun _ _ => (haltTime,tt)).\n  Proof.\n    pose (t:= (funTable (halt (m:=M)))).\n    apply computableTimeExt with (x:= fun c => lookup c t false).\n    2:{extract.\n       solverec.\n       rewrite lookupTime_leq.\n       unfold reg_state at 1;rewrite size_finType_le.\n       unfold haltTime. subst t. unfold cHalt. nia.\n    }\n    cbn;intro. subst t. setoid_rewrite lookup_funTable. reflexivity.\n  Qed.\n\n  Global Instance term_haltConf : computableTime' (haltConf (M:=M)) (fun _ _ => (haltTime+8,tt)).\n  Proof.\n    extract.\n    solverec.\n  Qed.\n\n  (* *** Computability of step-ndexed interpreter *)\n  Global Instance term_loopM :\n  let c1 := (haltTime + n*130 + transTime + 85 + 108) in\n    let c2 := 15 + haltTime in\n    computableTime' (loopM (M:=M)) (fun _ _ => (5,fun k _ => (c1 * k + c2,tt))).\n  Proof.\n    unfold loopM. (* as loop is already an encodable instance, this here is a bit out of the scope. Therefore, we unfold manually here. *)\n    extract.\n    solverec. \n  Qed.\n\n  Instance term_test cfg :\n    computable (fun k => LOptions.isSome (loopM (M := M) cfg k)).\n  Proof.\n    extract.\n  Qed.\n\nEnd loopM.\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/TMinL/TMinL_extract.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.27972725365827134}}
{"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 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      authenticated_messages_were_sent_or_byz_usys eo PBFTsys\n      -> PBFTcorrect_keys eo\n      -> 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": "vrahli", "repo": "Velisarios", "sha": "6fb353b18610cd79210755fcc90123536c367aaa", "save_path": "github-repos/coq/vrahli-Velisarios", "path": "github-repos/coq/vrahli-Velisarios/Velisarios-6fb353b18610cd79210755fcc90123536c367aaa/PBFT/PBFT_A_1_4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.27966548293615906}}
{"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.add_wins_set Require Import add_wins_set_code.\n\nSection awsCrdt.\n  Context `{!Log_Time} `{!EqDecision vl} `{!Countable vl}.\n\n  Inductive awsOp : Type :=\n  | Add : vl → awsOp\n  | Remove : vl → awsOp.\n\n  Definition awsSt : Type := gset (vl * Time).\n\n  Global Instance awsOp_eqdec : EqDecision awsOp.\n  Proof. solve_decision. Qed.\n\n  Global Instance awsOp_countable : Countable awsOp.\n  Proof.\n    apply (inj_countable'\n             (λ op, match op with Add v => inl v | Remove v => inr v end)\n             (λ x, match x with inl v => Add v | inr v => Remove v end));\n    intros []; done.\n  Qed.\n\n  Definition aws_denot (s : gset (Event awsOp)) (state : awsSt) : Prop :=\n    ∀ v tm,\n      (v, tm) ∈ state ↔\n      ∃ add_ev, add_ev ∈ s ∧ EV_Op add_ev = Add v ∧ EV_Time add_ev = tm ∧\n        ∀ rm_ev, rm_ev ∈ s → EV_Op rm_ev = Remove v → ¬ TM_le tm (EV_Time rm_ev).\n\n  Global Instance aws_denot_fun : Rel2__Fun aws_denot.\n  Proof.\n    constructor; intros s st1 st2 Hst1 Hst2.\n    apply set_eq; intros [v tm].\n    rewrite Hst1 Hst2; done.\n  Qed.\n\n  Global Instance aws_denot_instance : CrdtDenot awsOp awsSt := {\n    crdt_denot := aws_denot;\n  }.\nEnd awsCrdt.\n\nGlobal Arguments awsOp _ : clear implicits.\nGlobal Arguments awsSt {_} _ {_ _}.\n\n(* TODO: Move to the right place. *)\nGlobal Instance TM_le_dec `{!Log_Time} tm1 tm2 : Decision (TM_le tm1 tm2).\nProof.\n  destruct (decide (TM_lt tm1 tm2)).\n  { left; apply TM_lt_TM_le; done. }\n  destruct (decide (tm1 = tm2)) as [->|].\n  { left; reflexivity. }\n  right; intros []%TM_le_eq_or_lt; done.\nQed.\n\nSection OpAws.\n  Context `{!Log_Time}\n          `{!EqDecision vl} `{!Countable vl}.\n\n  Definition update_state (ev : Event (awsOp vl)) (st : awsSt vl) : awsSt vl :=\n    match EV_Op ev with\n    | Add v => {[(v, EV_Time ev)]} ∪ st\n    | Remove v =>  filter (λ '(w, tm), v ≠ w ∨ ¬ TM_le tm (EV_Time ev)) st\n    end.\n\n  Definition op_aws_effect (st : awsSt vl) (ev : Event (awsOp vl)) (st' : awsSt vl) : Prop :=\n    st' = update_state ev st.\n\n  Lemma op_aws_effect_fun st : Rel2__Fun (op_aws_effect st).\n  Proof. constructor; intros ??? -> ->; done. Qed.\n\n  Instance op_aws_effect_coh : OpCrdtEffectCoh op_aws_effect.\n  Proof.\n    intros s ev st st' Hst Hevs Hmax Hext Hto.\n    rewrite /op_aws_effect /crdt_denot /= /aws_denot /update_state.\n    split.\n    - intros ->.\n      intros v tm; split.\n      + intros Hup.\n        destruct ev as [[add_vl|rm_vl] evorig evtm]; simpl in *.\n        * rewrite elem_of_union elem_of_singleton in Hup.\n          destruct Hup as [|Hup]; simplify_eq.\n          -- exists {| EV_Op := Add add_vl; EV_Orig := evorig; EV_Time := evtm |}; simpl.\n             split_and!; [set_solver|done|done|].\n             intros [[|rm_val] rm_orig rm_tm] Hrmvs ?; simpl in *; first done.\n             destruct Hmax as [? Hmax].\n             specialize (Hmax _ Hrmvs).\n             rewrite /time /= in Hmax.\n             intros [->|Hle]%TM_le_eq_or_lt; last done.\n             simplify_eq.\n             assert ({| EV_Op := Add add_vl; EV_Orig := evorig; EV_Time := rm_tm |} =\n                       {| EV_Op := Remove add_vl; EV_Orig := rm_orig; EV_Time := rm_tm |});\n                  last by simplify_eq.\n             apply Hext; set_solver.\n          -- apply Hst in Hup as (add_ev&?&?&?&?).\n             exists add_ev; split_and!; [set_solver|done|done|set_solver].\n        * apply elem_of_filter in Hup as [Hupin Hup].\n          apply Hst in Hup as (add_ev&?&?&?&Hno_rm); simplify_eq.\n          exists add_ev; split_and!; [set_solver|done|done|].\n          intros rm_ev Hrm_ev ?.\n          pose proof Hrm_ev as Hrm_ev'.\n          rewrite elem_of_union elem_of_singleton in Hrm_ev'.\n          destruct Hrm_ev' as [|]; first by apply Hno_rm.\n          simplify_eq/=; simpl.\n          destruct Hupin; done.\n      + intros (add_ev & Hadd_ev_in & Hadd_ev_val & Hadd_ev_tm & Hadd_ev_no_rm).\n        destruct ev as [[add_vl|rm_vl] evorig evtm]; simpl in *.\n        * rewrite elem_of_union elem_of_singleton in Hadd_ev_in.\n          destruct Hadd_ev_in as [Hadd_ev_in|]; simplify_eq/=; last set_solver.\n          apply elem_of_union; right.\n          apply Hst.\n          exists add_ev; split_and!; [done|done|done|set_solver].\n        * apply elem_of_filter.\n          split.\n          -- destruct (decide (rm_vl = v)); last tauto.\n             right;\n               apply (Hadd_ev_no_rm {| EV_Op := Remove rm_vl; EV_Orig := evorig; EV_Time := evtm |});\n               [set_solver|simpl; congruence].\n          -- apply Hst; exists add_ev; split_and!; [set_solver|done|done|set_solver].\n    - intros Hst'.\n      apply set_eq; intros [v tm]; split.\n      + intros (add_ev & Hadd_ev_in & Hadd_ev_val & Hadd_ev_tm & Hadd_ev_no_rm)%Hst'.\n        destruct ev as [[add_vl|rm_vl] evorig evtm]; simpl in *.\n        * rewrite elem_of_union elem_of_singleton in Hadd_ev_in.\n          destruct Hadd_ev_in as [Hadd_ev_in|]; simplify_eq/=; last set_solver.\n          apply elem_of_union; right.\n          apply Hst.\n          exists add_ev; split_and!; [done|done|done|set_solver].\n        * apply elem_of_filter.\n          split.\n          -- destruct (decide (rm_vl = v)); last tauto.\n             right;\n               apply (Hadd_ev_no_rm {| EV_Op := Remove rm_vl; EV_Orig := evorig; EV_Time := evtm |});\n               [set_solver|simpl; congruence].\n          -- apply Hst; exists add_ev; split_and!; [set_solver|done|done|set_solver].\n      + intros Hup.\n        destruct ev as [[add_vl|rm_vl] evorig evtm]; simpl in *.\n        * rewrite elem_of_union elem_of_singleton in Hup.\n          destruct Hup as [|Hup]; simplify_eq.\n          -- apply Hst'.\n             exists {| EV_Op := Add add_vl; EV_Orig := evorig; EV_Time := evtm |}; simpl.\n             split_and!; [set_solver|done|done|].\n             intros [[|rm_val] rm_orig rm_tm] Hrmvs ?; simpl in *; first done.\n             destruct Hmax as [? Hmax].\n             specialize (Hmax _ Hrmvs).\n             rewrite /time /= in Hmax.\n             intros [->|Hle]%TM_le_eq_or_lt; last done.\n             simplify_eq.\n             assert ({| EV_Op := Add add_vl; EV_Orig := evorig; EV_Time := rm_tm |} =\n                       {| EV_Op := Remove add_vl; EV_Orig := rm_orig; EV_Time := rm_tm |});\n                  last by simplify_eq.\n             apply Hext; set_solver.\n          -- apply Hst'.\n             apply Hst in Hup as (add_ev&?&?&?&?).\n             exists add_ev; split_and!; [set_solver|done|done|set_solver].\n        * apply Hst'.\n          apply elem_of_filter in Hup as [Hupin Hup].\n          apply Hst in Hup as (add_ev&?&?&?&Hno_rm); simplify_eq.\n          exists add_ev; split_and!; [set_solver|done|done|].\n          intros rm_ev Hrm_ev ?.\n          pose proof Hrm_ev as Hrm_ev'.\n          rewrite elem_of_union elem_of_singleton in Hrm_ev'.\n          destruct Hrm_ev' as [|]; first by apply Hno_rm.\n          simplify_eq/=; simpl.\n          destruct Hupin; done.\n  Qed.\n\n  Definition op_aws_init_st : awsSt vl := ∅.\n\n  Lemma op_aws_init_st_coh : ⟦ (∅ : gset (Event (awsOp vl))) ⟧ ⇝ op_aws_init_st.\n  Proof.\n    intros ? ?; split; first set_solver.\n    intros (?&?&?); set_solver.\n  Qed.\n\n  Global Instance op_aws_model_instance : OpCrdtModel (awsOp vl) (awsSt vl) := {\n    op_crdtM_effect := op_aws_effect;\n    op_crdtM_effect_fun := op_aws_effect_fun;\n    op_crdtM_effect_coh := op_aws_effect_coh;\n    op_crdtM_init_st := op_aws_init_st;\n    op_crdtM_init_st_coh := op_aws_init_st_coh\n  }.\n\nEnd OpAws.\n\nFrom aneris.prelude Require Import time.\nFrom aneris.aneris_lang.lib Require Import list_code list_proof.\nFrom aneris.aneris_lang.lib.vector_clock Require Import vector_clock_code vector_clock_proof.\nFrom aneris.aneris_lang.lib Require Import inject.\nFrom aneris.examples.crdt.oplib.proof Require Import time.\n\n(* TODO: move to the right place. *)\nGlobal Instance vector_clock_inject : Inject vector_clock val :=\n  { inject := vector_clock_to_val }.\n\nSection aws_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 (awsOp vl)}.\n\n  Global Program Instance awsOp_inj : Inject (awsOp vl) val :=\n    {| inject w := match w with add_wins_set_proof.Add v => InjLV $v | Remove v => InjRV $v end |}.\n  Next Obligation.\n  Proof. intros [] []; simpl; intros ?; simplify_eq; done. Qed.\n  \n  Definition aws_OpLib_Op_Coh := λ (op : awsOp vl) (v : val), v = $op.\n\n  Lemma aws_OpLib_Op_Coh_Inj (o1 o2 : awsOp vl) (v : val) :\n    aws_OpLib_Op_Coh o1 v → aws_OpLib_Op_Coh o2 v → o1 = o2.\n  Proof. rewrite /aws_OpLib_Op_Coh; intros ? ?; simplify_eq; done. Qed.\n\n  Lemma aws_OpLib_Coh_Ser (op : awsOp vl) (v : val) :\n    aws_OpLib_Op_Coh op v → Serializable (sum_serialization vl_serialization vl_serialization) v.\n  Proof. intros Heq. rewrite Heq; destruct op; apply _. Qed.\n\n  Definition aws_OpLib_State_Coh :=\n    λ (st : awsSt vl) v, ∃ (l : list (vl * vector_clock)), is_list l v ∧ ∀ vtm, vtm ∈ st ↔ vtm ∈ l.\n\n  Global Instance aws_OpLib_Params : OpLib_Params (awsOp vl) (awsSt vl) :=\n  {|\n    OpLib_Serialization := (sum_serialization vl_serialization vl_serialization);\n    OpLib_State_Coh := aws_OpLib_State_Coh;\n    OpLib_Op_Coh := aws_OpLib_Op_Coh;\n    OpLib_Op_Coh_Inj := aws_OpLib_Op_Coh_Inj;\n    OpLib_Coh_Ser := aws_OpLib_Coh_Ser\n  |}.\n\n  Lemma aws_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    iApply \"HΦ\".\n    iPureIntro; eexists []; split_and!; [done|set_solver].\n  Qed.\n\n  (* TODO: moe to the right place; this strengthenes the existing proof. *)\n  (* This also changes the API to use filter instead of list.filter. Why whas that choice made!?*)\n  Lemma wp_list_filter `{!Inject A val} (l : list A) (P : A -> bool) (f lv : val) ip :\n    {{{ (∀ (x : A),\n            {{{ ⌜x ∈ l⌝ }}}\n              f $x @[ip]\n            {{{ w, RET w; ⌜w = $(P x)⌝ }}} ) ∗\n        ⌜is_list l lv⌝ }}}\n       list_code.list_filter f lv @[ip]\n     {{{ rv, RET rv; ⌜is_list (filter P l) rv⌝ }}}.\n  Proof.\n    iIntros (Φ) \"[#Hf %Hil] HΦ\".\n    iInduction l as [ | h t] \"IH\" forall (lv Hil Φ); simpl in Hil.\n    - subst.\n      rewrite /list_code.list_filter; wp_pures.\n      iApply \"HΦ\"; done.\n    - destruct Hil as (lv' & -> & Hil).\n      rewrite /list_code.list_filter.\n      do 7 (wp_pure _).\n      fold list_code.list_filter.\n      wp_apply (\"IH\" $! lv'); [done| |].\n      { iIntros \"!#\" (? ?) \"!# %\"; iApply \"Hf\"; iPureIntro; apply elem_of_cons; auto. }\n      iIntros (rv) \"%Hilp\"; wp_pures.\n      wp_apply \"Hf\"; [by iPureIntro; apply elem_of_cons; auto|].\n      iIntros (w) \"->\".\n      destruct (P h) eqn:HP; wp_pures.\n      + wp_apply wp_list_cons; [by eauto |].\n        iIntros (v) \"%Hil'\".\n        iApply \"HΦ\"; iPureIntro.\n        rewrite filter_cons.\n        rewrite HP; simpl.\n        simpl in Hil'; done.\n      + iApply \"HΦ\"; iPureIntro.\n        rewrite filter_cons.\n        rewrite HP. done.\n  Qed.\n\n  Lemma aws_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    destruct Hst as (l&?&Hstl).\n    simplify_eq/=.\n    rewrite Hopcoh /=.\n    wp_pures.\n    destruct log_ev; wp_pures.\n    - replace ($ v, evvc)%V with ($ (v, vc) : val); last first.\n      { simpl; erewrite is_vc_vector_clock_to_val; done. }\n      wp_apply wp_list_cons; first by iPureIntro.\n      iIntros (w Hw).\n      iApply \"HΦ\".\n      iExists _; iSplit; last by eauto.\n      simpl; iPureIntro; eexists _; split_and!; first done.\n      intros []; rewrite /update_state /=; set_solver.\n    - wp_apply\n        (wp_list_filter\n           _ (λ '(w, wvc), (bool_decide (w ≠ v)) || (negb (bool_decide (vector_clock_le wvc vc))))).\n      + iSplit; last done.\n        iIntros ([w wvc]) \"!#\".\n        iIntros (Ψ) \"_ HΨ\".\n        wp_pures.\n        destruct (decide (w = v)) as [->|Hneq].\n        * wp_op; [rewrite bin_op_eval_eq_val bool_decide_eq_true_2; done|].\n          wp_pures.\n          wp_apply wp_vect_leq; first by iPureIntro; split; [apply vector_clock_to_val_is_vc|done].\n          iIntros (? ->); simpl.\n          wp_pures.\n          iApply \"HΨ\".\n          rewrite (bool_decide_eq_false_2 (v ≠ v)); by auto.\n        * wp_op.\n          { rewrite bin_op_eval_eq_val bool_decide_eq_false_2; first done.\n            intros ?; apply Hneq; eapply inj; eauto with typeclass_instances. }\n          wp_pures.\n          iApply \"HΨ\".\n          rewrite (bool_decide_eq_true_2 (w ≠ v)); by auto.\n      + iIntros (w Hw).\n        iApply \"HΦ\".\n        iExists _; iSplit; last by eauto.\n        simpl; iPureIntro; eexists _; split_and!; first done.\n        intros [u uvc].\n        rewrite /update_state /=.\n        rewrite elem_of_filter elem_of_list_filter Hstl.\n        rewrite -bool_decide_not -bool_decide_or bool_decide_spec.\n        clear; firstorder.\n  Qed.\n\n  Lemma aws_crdt_fun_spec : ⊢ crdt_fun_spec aws_crdt.\n  Proof.\n    iIntros (addr).\n    iIntros \"!#\" (Φ) \"_ HΦ\".\n    rewrite /aws_crdt.\n    wp_pures.\n    iApply \"HΦ\".\n    iExists _, _; iSplit; first done.\n    iSplit.\n    - iApply aws_init_st_fn_spec; done.\n    - iApply aws_effect_spec; done.\n  Qed.\n\n  Lemma aws_init_spec :\n    init_spec\n      (oplib_init\n         (s_ser (s_serializer (sum_serialization vl_serialization vl_serialization)))\n         (s_deser (s_serializer (sum_serialization vl_serialization vl_serialization)))) -∗\n      init_spec_for_specific_crdt\n        (aws_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 /aws_init.\n    wp_pures.\n    wp_apply (\"Hinit\" with \"[$Hprotos $Htoken $Hskt $Hfr]\").\n    { do 2 (iSplit; first done). iApply aws_crdt_fun_spec; done. }\n    iIntros (get update) \"(HLS & #Hget & #Hupdate)\".\n    wp_pures.\n    iApply \"HΦ\"; eauto.\n  Qed.\n\nEnd aws_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/add_wins_set/add_wins_set_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.27966548293615906}}
{"text": "Require Export UnitaryListRepresentation.\nRequire Export QArith.\n\n(* Other gate sets *)\nRequire Import IBMGateSet.\nRequire Import MappingGateSet.\nRequire Import RzQGateSet.\nRequire Import MappingConstraints.\n\nImport Qreals. (* Coq version < 8.13.0 has Q2R defined in Qreals *) \n\n(** This gate set is intended to be the \"full\" gate set that contains every gate\n   we could ever want. Optimizations are not defined directly over this set.\n   Instead, we define optimizations over specialized sets (e.g. RzQ, IBM) and \n   provide translations from this set to those sets.\n\n   The value of having a gate set that contains everything is that it removes\n   some opportunities for error in the OpenQASM -> SQIR parser. For instance,\n   the parser can directly translate \"T\" to the T gate in the full gate set\n   rather than the Rz(PI/4) gate in the RzQ gate set. This is even more important\n   for gates like CCX that have complicated translations to other gate sets.\n  \n   To extend this gate set with new gates, you will need to modify the definitions\n   in this file and any optimizations defined over the full gate set (at\n   present, these only include definitions in Main.v). **)\n\nLocal Open Scope R_scope.\nLocal Open Scope Q_scope.\n\nLtac invert_WT :=\n  repeat match goal with\n  | H: uc_well_typed _ |- _ => inversion H; subst; clear H\n  end.\n\nLtac simpl_Reqb_and_Qeqb :=\n  repeat match goal with\n  | H : Reqb _ _ = true |- _ => apply Reqb_eq in H; rewrite H\n  | H : _ && _ = true |- _ => apply andb_prop in H as [? ?]\n  | H : Qeq_bool _ _ = true |- _ => apply Qeq_bool_iff in H; \n      apply RMicromega.Q2R_m in H; rewrite H\n  end.\n\nModule FullGateSet <: GateSet.\n\nInductive Full_Unitary : nat -> Set := \n  | U_I                           : Full_Unitary 1 \n  | U_X                           : Full_Unitary 1\n  | U_Y                           : Full_Unitary 1 \n  | U_Z                           : Full_Unitary 1\n  | U_H                           : Full_Unitary 1 \n  | U_S                           : Full_Unitary 1\n  | U_T                           : Full_Unitary 1 \n  | U_Sdg                         : Full_Unitary 1\n  | U_Tdg                         : Full_Unitary 1 \n  | U_Rx (r : R)                  : Full_Unitary 1\n  | U_Ry (r : R)                  : Full_Unitary 1 \n  | U_Rz (r : R)                  : Full_Unitary 1\n  | U_Rzq (q : Q)                 : Full_Unitary 1\n  | U_U1 (r : R)                  : Full_Unitary 1\n  | U_U2 (r : R) (r : R)          : Full_Unitary 1 \n  | U_U3 (r : R) (r : R) (r : R)  : Full_Unitary 1\n  | U_CX                          : Full_Unitary 2\n  | U_CZ                          : Full_Unitary 2\n  | U_SWAP                        : Full_Unitary 2\n  | U_CCX                         : Full_Unitary 3\n  | U_CCZ                         : Full_Unitary 3.\nDefinition U := Full_Unitary.\n\n(* Used for proofs -- not extracted to OCaml, so efficiency isn't a concern *)\nDefinition to_base {n dim} (u : U n) (qs : list nat) (pf : List.length qs = n) :=\n  match u with\n  | U_I            => @SQIR.ID dim (List.nth O qs O)\n  | U_X            => @SQIR.X dim (List.nth O qs O)\n  | U_Y            => @SQIR.Y dim (List.nth O qs O)\n  | U_Z            => @SQIR.Z dim (List.nth O qs O)\n  | U_H            => @SQIR.H dim (List.nth O qs O)\n  | U_S            => @SQIR.P dim (List.nth O qs O)\n  | U_T            => @SQIR.T dim (List.nth O qs O)\n  | U_Sdg          => @SQIR.PDAG dim (List.nth O qs O)\n  | U_Tdg          => @SQIR.TDAG dim (List.nth O qs O)\n  | U_Rx r         => @SQIR.Rx dim r (List.nth O qs O)\n  | U_Ry r         => @SQIR.Ry dim r (List.nth O qs O)\n  | U_Rz r         => @SQIR.Rz dim r (List.nth O qs O)\n  | U_Rzq q        => @SQIR.Rz dim (Q2R q * PI)%R (List.nth O qs O)\n  | U_U1 r         => @SQIR.U1 dim r (List.nth O qs O)\n  | U_U2 r1 r2     => @SQIR.U2 dim r1 r2 (List.nth O qs O)\n  | U_U3 r1 r2 r3  => @SQIR.U3 dim r1 r2 r3 (List.nth O qs O)\n  | U_CX           => @SQIR.CNOT dim (List.nth O qs O) (List.nth (S O) qs O)\n  | U_CZ           => @SQIR.CZ dim (List.nth O qs O) (List.nth (S O) qs O)\n  | U_SWAP         => @SQIR.SWAP dim (List.nth O qs O) (List.nth (S O) qs O)\n  | U_CCX          => @SQIR.CCX dim (List.nth O qs O) (List.nth (S O) qs O) (List.nth (S (S O)) qs O)\n  | U_CCZ          => @SQIR.CCZ dim (List.nth O qs O) (List.nth (S O) qs O) (List.nth (S (S O)) qs O)\n  end.\n\nLocal Transparent SQIR.ID SQIR.X SQIR.Y SQIR.Z SQIR.H SQIR.Rx \n                  SQIR.Ry SQIR.Rz SQIR.CNOT SQIR.SWAP.\nLemma to_base_only_uses_qs : forall {n} (dim : nat) (u : U n) (qs : list nat) (pf : List.length qs = n),\n    @only_uses _ dim (to_base u qs pf) qs.\nProof.\n  intros.\n  destruct u; simpl;\n  repeat constructor; apply nth_In; lia.\nQed.\n\nLemma to_base_WT : forall {n} (dim : nat) (u : U n) (qs : list nat) (pf : List.length qs = n),\n  @uc_well_typed _ dim (to_base u qs pf) <-> (bounded_list qs dim /\\ List.NoDup qs).\nProof.\n  intros n dim u s pf.\n  unfold bounded_list.\n  split.\n  - intro H.\n    destruct u; invert_WT.\n    all: repeat (destruct s; simpl in *; try lia). \n    all: split.\n    all: repeat constructor; auto.\n    all: try (intros x [Hx | Hx]; subst; easy). \n    all: try (intros x [Hx | [Hx | Hx]]; subst; easy). \n    all: try (intros x [Hx | [Hx | [Hx | Hx]]]; subst; easy). \n    all: try (intro contra; destruct_In; auto).\n  - intros [H1 H2].\n    assert (aux1: (length s >= 2)%nat -> nth 0 s O <> nth 1 s O).\n    { intro H. clear pf.\n      destruct s; [|destruct s; [|destruct s]]; simpl in H; try lia. \n      inversion H2; subst.\n      simpl. \n      intro contra. \n      contradict H4. \n      subst; constructor; auto.\n      inversion H2; subst.\n      simpl. \n      intro contra. \n      contradict H4. \n      subst; constructor; auto. }\n    assert (aux2: length s = 3%nat -> nth 0 s O <> nth 2 s O).\n    { intro H. clear pf.\n      destruct s; [|destruct s; [|destruct s; [|destruct s]]]; simpl in H; try lia. \n      inversion H2; subst.\n      simpl. \n      intro contra. \n      contradict H4. \n      subst; right; constructor; auto. }\n    assert (aux3: length s = 3%nat -> nth 1 s O <> nth 2 s O).\n    { intro H. clear pf.\n      destruct s; [|destruct s; [|destruct s; [|destruct s]]]; simpl in H; try lia. \n      inversion H2; subst.\n      simpl. \n      inversion H5; subst.\n      intro contra. \n      contradict H6. \n      subst; constructor; auto. }\n    destruct u; repeat constructor.\n    all: try apply H1.\n    all: try (apply nth_In; lia).\n    all: try (apply aux1; lia).\n    all: try (apply aux2; assumption).\n    all: try (apply aux3; assumption).\n    apply Nat.neq_sym.\n    apply aux1; lia.\nQed.\n\nLemma to_base_map_commutes : forall {n} (dim : nat) (u : U n) (qs : list nat) (pf : List.length qs = n) (f : nat -> nat) (pfm : List.length (map f qs) = n),\n  @to_base _ dim u (map f qs) pfm = map_qubits f (to_base u qs pf).\nProof.\n  intros n dim u qs pf f pfm.\n  destruct u; simpl.\n  all: repeat erewrite map_nth_In; try reflexivity; lia.\nQed.\nLocal Opaque SQIR.ID SQIR.X SQIR.Y SQIR.Z SQIR.H SQIR.Rx \n             SQIR.Ry SQIR.Rz SQIR.CNOT SQIR.SWAP.\n\nDefinition match_gate {n} (u u' : U n) : bool :=\n  match u, u' with\n  | U_I, U_I\n  | U_X, U_X\n  | U_Y, U_Y\n  | U_Z, U_Z\n  | U_H, U_H\n  | U_S, U_S\n  | U_T, U_T\n  | U_Sdg, U_Sdg\n  | U_Tdg, U_Tdg\n  | U_CX, U_CX\n  | U_CZ, U_CZ\n  | U_SWAP, U_SWAP \n  | U_CCX, U_CCX \n  | U_CCZ, U_CCZ => true\n  (* All rz gates are u1 gates, some u2 gates are H gates, etc.\n     We will not bother to check for these cases. If desired, you could\n     write an optimization pass that replaces gates with their equivalents. *)\n  | U_Rx r, U_Rx r'\n  | U_Ry r, U_Ry r'\n  | U_Rz r, U_Rz r'\n  | U_U1 r, U_U1 r' => Reqb r r'\n  | U_Rzq q, U_Rzq q' => Qeq_bool q q'\n  | U_U2 r1 r2, U_U2 r1' r2' => Reqb r1 r1' && Reqb r2 r2'\n  | U_U3 r1 r2 r3, U_U3 r1' r2' r3' => Reqb r1 r1' && Reqb r2 r2' && Reqb r3 r3'\n  | _, _ => false\n  end.\n\nLemma match_gate_refl : forall {n} (u : U n), match_gate u u = true.\nProof. \n  intros. \n  dependent destruction u; simpl; auto.\n  apply Reqb_eq; auto.\n  apply Reqb_eq; auto.\n  apply Reqb_eq; auto.\n  apply Qeq_bool_iff; reflexivity.\n  apply Reqb_eq; auto.\n  apply andb_true_iff.\n  split; apply Reqb_eq; auto.\n  apply andb_true_iff.\n  split; [apply andb_true_iff; split |]; apply Reqb_eq; auto.\nQed.\n\nLemma match_gate_implies_equiv : forall {n} dim (u u' : U n) (qs : list nat) (pf : List.length qs = n), \n  match_gate u u' = true -> uc_equiv (@to_base n dim u qs pf) (to_base u' qs pf).\nProof.\n  intros.\n  dependent destruction u; dependent destruction u'.\n  all: inversion H; simpl; simpl_Reqb_and_Qeqb; reflexivity.\nQed.\n\nEnd FullGateSet.\nExport FullGateSet.\n\nModule FullList := UListProofs FullGateSet.\n\nDefinition full_ucom dim := ucom Full_Unitary dim.\nDefinition full_ucom_l dim := gate_list Full_Unitary dim.\n\n(** Some useful gate decompositions **)\n\nLemma Cexp_plus_PI2 : forall x, Cexp (x + PI/2) = (Ci * Cexp x)%C.\nProof. intros. autorewrite with Cexp_db. lca. Qed.\n\nLemma Cexp_minus_PI2 : forall x, Cexp (x - PI/2) = (- Ci * Cexp x)%C.\nProof. \n  intros. \n  unfold Cexp. \n  replace (x - PI / 2)%R with (- (PI / 2 - x))%R by lra.\n  rewrite cos_neg, sin_neg.\n  rewrite cos_shift, sin_shift.\n  lca.\nQed.\n\n(* All 4 cases in u3_to_rz can be solved by the same commands. *)\nLtac u3_to_rz_aux a :=\n  try rewrite Cexp_add;\n  try rewrite Cexp_plus_PI2; \n  try rewrite Cexp_minus_PI2;\n  unfold Cexp;\n  autorewrite with trig_db;\n  replace (sin a) with (sin (2 * (a/2))) by (apply f_equal; lra);\n  rewrite sin_2a;\n  apply c_proj_eq; simpl; field_simplify_eq; try nonzero;\n  change_to_sqr;\n  try rewrite sin_half_squared;\n  try rewrite cos_half_squared;\n  rewrite Rsqr_sqrt by lra;\n  lra.\n\nLocal Open Scope ucom_scope.\nLocal Close Scope Q_scope.\nLocal Open Scope R_scope.\nLemma u3_to_rz : forall dim a b c q,\n  @SQIR.U3 dim a b c q ≅ SQIR.Rz (c - (PI/2)) q ; SQIR.H q ; SQIR.Rz a q ; SQIR.H q ; SQIR.Rz (b + (PI/2)) q.\nProof.\n  intros. \n  unfold uc_cong; simpl.\n  exists (- (a / 2)).\n  autorewrite with eval_db.\n  bdestruct_all.\n  gridify.\n  rewrite <- Mscale_kron_dist_l.\n  rewrite <- Mscale_kron_dist_r.\n  apply f_equal2; try reflexivity.\n  apply f_equal2; try reflexivity.\n  unfold phase_shift, rotation, hadamard.\n  solve_matrix; u3_to_rz_aux a. (* all goals solved by ltac above *)\n  (* final case is ill-typed *)\n  Msimpl. \n  reflexivity.\nQed.\n\nLemma u2_to_rz : forall dim a b q,\n  @SQIR.U2 dim a b q ≡ SQIR.Rz (b - PI) q ; SQIR.H q ; SQIR.Rz a q.\nProof.\n  intros. \n  unfold uc_equiv; simpl.\n  autorewrite with eval_db.\n  gridify.\n  apply f_equal2; try reflexivity.\n  apply f_equal2; try reflexivity.\n  unfold phase_shift, rotation, hadamard.\n  solve_matrix;\n  try rewrite Cexp_add;\n  try rewrite Cexp_minus_PI;\n  replace (PI / 2 / 2) with (PI / 4) by lra;\n  autorewrite with trig_db RtoC_db;\n  lca.\nQed.\n\nLemma rx_to_rz : forall dim a q,\n  @SQIR.Rx dim a q ≅ SQIR.H q ; SQIR.Rz a q ; SQIR.H q.\nProof.\n  intros dim a q. \n  assert (H: @Rx dim a q ≅ U3 a (- (PI / 2)) (PI / 2) q).\n  reflexivity.  \n  rewrite H.\n  rewrite u3_to_rz.\n  replace (PI / 2 - PI / 2) with 0 by lra.\n  replace (- (PI / 2) + PI / 2) with 0 by lra.\n  apply uc_equiv_cong.\n  rewrite Rz_0_id.\n  bdestruct (q <? dim)%nat.\n  rewrite ID_equiv_SKIP by assumption.\n  rewrite SKIP_id_l, SKIP_id_r by assumption.\n  reflexivity. \n  unfold uc_equiv; simpl.\n  autorewrite with eval_db.\n  gridify.\nQed.\n\nLemma ry_to_rz : forall dim a q,\n  @SQIR.Ry dim a q ≅ SQIR.PDAG q ; SQIR.H q ; SQIR.Rz a q ; SQIR.H q ; SQIR.P q.\nProof.\n  intros dim a q. \n  assert (H: @Ry dim a q ≅ U3 a 0 0 q).\n  reflexivity.  \n  rewrite H.\n  rewrite u3_to_rz.\n  replace (0 - PI / 2) with (- (PI / 2)) by lra.\n  replace (0 + PI / 2) with (PI / 2) by lra.\n  reflexivity.\nQed.\n\n(** * Function to convert between gate sets **)\n\nLocal Open Scope Z_scope.\n\n(* Effectively List.map, but tail recursive *)\nFixpoint change_gate_set' {dim : nat} {U1 U2 : nat -> Set} \n      (f : gate_app U1 dim -> gate_list U2 dim) (l : gate_list U1 dim) \n      (acc : gate_list U2 dim) : gate_list U2 dim := \n  match l with\n  | [] => List.rev acc\n  (* technically ++ isn't tail recursive, but when the first argument (i.e. f g)\n     is small it shouldn't matter *)\n  | g :: t => change_gate_set' f t (List.rev (f g) ++ acc) \n  end.\n\nDefinition change_gate_set {dim : nat} {U1 U2 : nat -> Set} \n      (f : gate_app U1 dim -> gate_list U2 dim) (l : gate_list U1 dim) \n      : gate_list U2 dim := \n  change_gate_set' f l [].\n\nLemma change_gate_set_nil : forall {dim U1 U2} f,\n  @change_gate_set dim U1 U2 f [] = [].\nProof. intros. reflexivity. Qed.\n\nLemma change_gate_set_cons : forall {dim U1 U2} f h t,\n  @change_gate_set dim U1 U2 f (h :: t) = f h ++ change_gate_set f t.\nProof.\n  intros.\n  assert (forall l acc, change_gate_set' f l acc = rev acc ++ change_gate_set' f l []).\n  { induction l; intro acc; simpl.\n    rewrite app_nil_r.\n    reflexivity.\n    rewrite IHl.\n    rewrite (IHl (_ ++ _)).\n    repeat rewrite rev_app_distr.\n    repeat rewrite rev_involutive.\n    simpl.\n    rewrite app_assoc.\n    reflexivity. }\n  unfold change_gate_set.\n  simpl.\n  rewrite H.  \n  rewrite rev_app_distr.\n  rewrite rev_involutive.\n  simpl.\n  reflexivity.\nQed.\n\nLemma change_gate_set_app : forall {dim U1 U2} f l1 l2,\n  @change_gate_set dim U1 U2 f (l1 ++ l2) = change_gate_set f l1 ++ change_gate_set f l2.\nProof.\n  intros.\n  induction l1.\n  reflexivity.\n  rewrite <- app_comm_cons.\n  rewrite 2 change_gate_set_cons.\n  rewrite IHl1.\n  rewrite app_assoc.\n  reflexivity.\nQed.\n\n(** * IBM gate set **)\n\nDefinition full_to_IBM_u {dim} (g : gate_app Full_Unitary dim) : IBM_ucom_l dim :=\n  match g with\n  | App1 U_I m              => [IBMGateSet.Rz 0 m]\n  | App1 U_X m              => [IBMGateSet.X m]\n  | App1 U_Y m              => [IBMGateSet.Y m]\n  | App1 U_Z m              => [IBMGateSet.Z m]\n  | App1 U_H m              => [IBMGateSet.H m]\n  | App1 U_S m              => [IBMGateSet.P m]\n  | App1 U_T m              => [IBMGateSet.T m]\n  | App1 U_Sdg m            => [IBMGateSet.PDAG m]\n  | App1 U_Tdg m            => [IBMGateSet.TDAG m]\n  | App1 (U_Rx r) m         => [IBMGateSet.Rx r m]\n  | App1 (U_Ry r) m         => [IBMGateSet.Ry r m]\n  | App1 (U_Rz r) m         => [IBMGateSet.Rz r m]\n  | App1 (U_Rzq q) m        => [IBMGateSet.Rz (Q2R q * PI) m]\n  | App1 (U_U1 r) m         => [IBMGateSet.U1 r m]\n  | App1 (U_U2 r1 r2) m     => [IBMGateSet.U2 r1 r2 m]\n  | App1 (U_U3 r1 r2 r3) m  => [IBMGateSet.U3 r1 r2 r3 m]\n  | App2 U_CX m n           => [IBMGateSet.CNOT m n]\n  | App2 U_CZ m n           => IBMGateSet.CZ m n\n  | App2 U_SWAP m n         => IBMGateSet.SWAP m n\n  | App3 U_CCX m n p        => IBMGateSet.CCX m n p\n  | App3 U_CCZ m n p        => IBMGateSet.CCZ m n p\n  | _ => [] (* unreachable *)\n  end.\n\nDefinition IBM_to_full_u {dim} (g : gate_app IBM_Unitary dim) : full_ucom_l dim :=\n  match g with\n  | App1 (UIBM_U1 a) m      => [App1 (U_U1 a) m]\n  | App1 (UIBM_U2 a b) m    => [App1 (U_U2 a b) m]\n  | App1 (UIBM_U3 a b c) m  => [App1 (U_U3 a b c) m]\n  | App2 UIBM_CNOT m n      => [App2 U_CX m n]\n  | _ => [] (* unreachable *)\n  end.\n\nDefinition full_to_IBM {dim} (l : full_ucom_l dim) : IBM_ucom_l dim := \n  change_gate_set full_to_IBM_u l.\n\nDefinition IBM_to_full {dim} (l : IBM_ucom_l dim) : full_ucom_l dim := \n  change_gate_set IBM_to_full_u l.\n\nLemma IBM_to_base1 : forall {dim} (u : IBM_Unitary 1) n,\n  IBMGateSet.to_base u [n] (one_elem_list n) ≡ \n    FullList.list_to_ucom (IBM_to_full_u (@App1 _ dim u n)).\nProof.\n  intros dim u n.\n  dependent destruction u; simpl; rewrite SKIP_id_r; reflexivity.\nQed.\n\nLemma IBM_to_base2 : forall {dim} (u : IBM_Unitary 2) m n,\n  IBMGateSet.to_base u (m :: n :: []) (two_elem_list m n) ≡ \n    FullList.list_to_ucom (IBM_to_full_u (@App2 _ dim u m n)).\nProof.\n  intros dim u m n.\n  dependent destruction u; simpl; rewrite SKIP_id_r; reflexivity.\nQed.\n\nLemma IBM_list_to_ucom : forall {dim} (l : IBM_ucom_l dim),\n  IBMList.list_to_ucom l ≡ FullList.list_to_ucom (IBM_to_full l).\nProof.\n  intros.\n  induction l.\n  reflexivity.\n  simpl.\n  unfold IBM_to_full. \n  rewrite change_gate_set_cons.\n  rewrite FullList.list_to_ucom_append.\n  destruct a.\n  rewrite IBM_to_base1, IHl.\n  reflexivity.\n  rewrite IBM_to_base2, IHl.\n  reflexivity.\n  dependent destruction i.\nQed.\n\nLemma IBM_to_full_equiv : forall {dim} (l l' : IBM_ucom_l dim),\n  IBMGateSet.IBMList.uc_equiv_l l l' ->\n  FullList.uc_equiv_l (IBM_to_full l) (IBM_to_full l').\nProof.\n  intros dim l l' H.\n  unfold FullList.uc_equiv_l.\n  unfold IBMGateSet.IBMList.uc_equiv_l in H.\n  rewrite 2 IBM_list_to_ucom in H.\n  assumption.\nQed.\n\nLemma IBM_to_full_cong : forall {dim} (l l' : IBM_ucom_l dim),\n  IBMGateSet.IBMList.uc_cong_l l l' ->\n  FullList.uc_cong_l (IBM_to_full l) (IBM_to_full l').\nProof.\n  intros dim l l' H.\n  unfold FullList.uc_equiv_l.\n  unfold IBMGateSet.IBMList.uc_cong_l in H.\n  unfold uc_cong in H.\n  rewrite 2 IBM_list_to_ucom in H.\n  assumption.\nQed.\n\nLemma IBM_to_full_inv : forall {dim} (l : full_ucom_l dim),\n  FullList.uc_equiv_l (IBM_to_full (full_to_IBM l)) l.\nProof.\n  intros dim l.\n  induction l.\n  reflexivity.\n  unfold full_to_IBM, IBM_to_full.\n  rewrite change_gate_set_cons.\n  rewrite change_gate_set_app.\n  rewrite IHl.\n  rewrite cons_to_app.\n  FullList.apply_app_congruence.\n  destruct a; dependent destruction f; \n  unfold change_gate_set; simpl; try reflexivity.\n  all: unfold FullList.uc_equiv_l; simpl;\n       repeat rewrite <- useq_assoc; reflexivity.\nQed.\n\nLemma full_to_IBM_WT : forall {dim} (l : full_ucom_l dim),\n  uc_well_typed_l l ->\n  uc_well_typed_l (full_to_IBM l).\nProof.\n  intros dim l WT.\n  unfold full_to_IBM.\n  induction WT.\n  - constructor. assumption.\n  - dependent destruction u; rewrite change_gate_set_cons; \n    simpl; try constructor; assumption.\n  - dependent destruction u; rewrite change_gate_set_cons; \n    simpl; repeat constructor; try assumption. lia.\n  - dependent destruction u; rewrite change_gate_set_cons; \n    simpl; repeat constructor; assumption.\nQed.\n\nLemma full_to_IBM_preserves_mapping : forall {dim} (l : full_ucom_l dim) (is_in_graph : nat -> nat -> bool),\n  respects_constraints_directed is_in_graph U_CX l ->\n  respects_constraints_directed is_in_graph UIBM_CNOT (full_to_IBM l).\nProof.\n  intros dim l is_in_graph H.\n  unfold full_to_IBM.\n  induction l.\n  constructor.\n  rewrite change_gate_set_cons. \n  inversion H; subst.\n  apply respects_constraints_directed_app; auto.\n  dependent destruction u; repeat constructor.\n  apply respects_constraints_directed_app; auto.\n  repeat constructor.\n  assumption.\nQed.\n\nLemma IBM_to_full_preserves_mapping : forall {dim} (l : IBM_ucom_l dim) (is_in_graph : nat -> nat -> bool),\n  respects_constraints_directed is_in_graph UIBM_CNOT l ->\n  respects_constraints_directed is_in_graph U_CX (IBM_to_full l).\nProof.\n  intros dim l is_in_graph H.\n  unfold IBM_to_full.\n  induction l.\n  constructor.\n  rewrite change_gate_set_cons. \n  inversion H; subst.\n  apply respects_constraints_directed_app; auto.\n  dependent destruction u; repeat constructor.\n  apply respects_constraints_directed_app; auto.\n  repeat constructor.\n  assumption.\nQed.\n\n(** * RzQ gate set **)\n\n(* A perfect real -> rational function DOES NOT exist because some real\n   numbers are irrational. However, I am going to assert such a function\n   as an axiom until we come up with a better solution. This is BAD and\n   maybe be a source of troubles in the future. We extract this as a function\n   that converts from floats to rationals (which is ok). -KH *)\nAxiom R2Q : R -> Q.\nDefinition R2Q_PI x := R2Q (x / PI).\nAxiom Q2R_R2Q_PI : forall r, (Q2R (R2Q_PI r) * PI)%R = r.\nDefinition Rx {dim} a q : RzQ_ucom_l dim := H q :: Rzq (R2Q_PI a) q :: H q :: [].\nDefinition Rz {dim} a q := @App1 _ dim (URzQ_Rz (R2Q_PI a)) q.\nDefinition Ry {dim} a q : RzQ_ucom_l dim := \n  PDAG q :: H q :: Rzq (R2Q_PI a) q :: H q :: P q :: [].\nDefinition U1 {dim} a q := @Rz dim a q.\nDefinition U2 {dim} a b q : RzQ_ucom_l dim := \n  Rzq (R2Q_PI (b - PI)) q :: H q :: Rzq (R2Q_PI a) q :: [].\nDefinition U3 {dim} a b c q : RzQ_ucom_l dim := \n  Rzq (R2Q_PI (c - (PI/2))) q :: H q :: Rzq (R2Q_PI a) q :: \n  H q :: Rzq (R2Q_PI (b + (PI/2))) q :: [].\n\nDefinition full_to_RzQ_u {dim} (g : gate_app Full_Unitary dim) : RzQ_ucom_l dim :=\n  match g with\n  | App1 U_I m              => [Rzq zero_Q m]\n  | App1 U_X m              => [RzQGateSet.X m]\n  | App1 U_Y m              => RzQGateSet.Y m\n  | App1 U_Z m              => [RzQGateSet.Z m]\n  | App1 U_H m              => [RzQGateSet.H m]\n  | App1 U_S m              => [RzQGateSet.P m]\n  | App1 U_T m              => [RzQGateSet.T m]\n  | App1 U_Sdg m            => [RzQGateSet.PDAG m]\n  | App1 U_Tdg m            => [RzQGateSet.TDAG m]\n  | App1 (U_Rx r) m         => Rx r m\n  | App1 (U_Ry r) m         => Ry r m\n  | App1 (U_Rz r) m         => [Rz r m]\n  | App1 (U_Rzq q) m        => [RzQGateSet.Rzq q m]\n  | App1 (U_U1 r) m         => [U1 r m]\n  | App1 (U_U2 r1 r2) m     => U2 r1 r2 m\n  | App1 (U_U3 r1 r2 r3) m  => U3 r1 r2 r3 m\n  | App2 U_CX m n           => [RzQGateSet.CNOT m n]\n  | App2 U_CZ m n           => RzQGateSet.CZ m n\n  | App2 U_SWAP m n         => RzQGateSet.SWAP m n\n  | App3 U_CCX m n p        => RzQGateSet.CCX m n p\n  | App3 U_CCZ m n p        => RzQGateSet.CCZ m n p\n  | _ => [] (* unreachable *)\n  end.\n\nDefinition RzQ_to_full_u {dim} (g : gate_app RzQ_Unitary dim) : full_ucom_l dim :=\n  match g with\n  | App1 URzQ_H m       => [App1 U_H m]\n  | App1 URzQ_X m       => [App1 U_X m]\n  | App1 (URzQ_Rz q) m  => [App1 (U_Rzq q) m]\n  | App2 URzQ_CNOT m n  => [App2 U_CX m n]\n  | _ => [] (* unreachable *)\n  end.\n\nDefinition full_to_RzQ {dim} (l : full_ucom_l dim) : RzQ_ucom_l dim := \n  change_gate_set full_to_RzQ_u l.\n\nDefinition RzQ_to_full {dim} (l : RzQ_ucom_l dim) : full_ucom_l dim := \n  change_gate_set RzQ_to_full_u l.\n\nLemma RzQ_to_base1 : forall {dim} (u : RzQ_Unitary 1) n,\n  RzQGateSet.to_base u [n] (one_elem_list n) ≡ \n    FullList.list_to_ucom (RzQ_to_full_u (@App1 _ dim u n)).\nProof.\n  intros dim u n.\n  dependent destruction u; simpl; rewrite SKIP_id_r; reflexivity.\nQed.\n\nLemma RzQ_to_base2 : forall {dim} (u : RzQ_Unitary 2) m n,\n  RzQGateSet.to_base u (m :: n :: []) (two_elem_list m n) ≡ \n    FullList.list_to_ucom (RzQ_to_full_u (@App2 _ dim u m n)).\nProof.\n  intros dim u m n.\n  dependent destruction u; simpl; rewrite SKIP_id_r; reflexivity.\nQed.\n\nLemma RzQ_list_to_ucom : forall {dim} (l : RzQ_ucom_l dim),\n  RzQList.list_to_ucom l ≡ FullList.list_to_ucom (RzQ_to_full l).\nProof.\n  intros.\n  induction l.\n  reflexivity.\n  simpl.\n  unfold RzQ_to_full. \n  rewrite change_gate_set_cons.\n  rewrite FullList.list_to_ucom_append.\n  destruct a.\n  rewrite RzQ_to_base1, IHl.\n  reflexivity.\n  rewrite RzQ_to_base2, IHl.\n  reflexivity.\n  dependent destruction r.\nQed.\n\nLemma RzQ_to_full_equiv : forall {dim} (l l' : RzQ_ucom_l dim),\n  RzQGateSet.RzQList.uc_equiv_l l l' ->\n  FullList.uc_equiv_l (RzQ_to_full l) (RzQ_to_full l').\nProof.\n  intros dim l l' H.\n  unfold FullList.uc_equiv_l.\n  unfold RzQGateSet.RzQList.uc_equiv_l in H.\n  rewrite 2 RzQ_list_to_ucom in H.\n  assumption.\nQed.\n\nLemma RzQ_to_full_cong : forall {dim} (l l' : RzQ_ucom_l dim),\n  RzQGateSet.RzQList.uc_cong_l l l' ->\n  FullList.uc_cong_l (RzQ_to_full l) (RzQ_to_full l').\nProof.\n  intros dim l l' H.\n  unfold FullList.uc_equiv_l.\n  unfold RzQGateSet.RzQList.uc_cong_l in H.\n  unfold uc_cong in H.\n  rewrite 2 RzQ_list_to_ucom in H.\n  assumption.\nQed.\n\nLocal Open Scope R.\nLemma Q2R_1_4_PI : forall {dim} q, \n  @SQIR.Rz dim (Q2R (1 / 4) * PI) q ≡ SQIR.Rz (PI / 4) q.\nProof.\n  intros dim q.\n  unfold Q2R; simpl.\n  autorewrite with R_db.\n  rewrite Rmult_comm.\n  reflexivity.\nQed.\n\nLemma Q2R_7_4_PI : forall {dim} q, \n  @SQIR.Rz dim (Q2R (7 / 4) * PI) q ≡ SQIR.Rz (- (PI / 4)) q.\nProof.\n  intros dim q.\n  unfold Q2R; simpl.\n  unfold uc_equiv; autorewrite with eval_db; try lia.\n  gridify.\n  replace (7 * / 4 * PI) with (2 * PI + - (PI / 4)) by lra.\n  rewrite <- phase_mul.\n  rewrite phase_2pi.\n  Msimpl.\n  reflexivity.\nQed.\n\nLemma Q2R_1_2_PI : forall {dim} q, \n  @SQIR.Rz dim (Q2R (1 / 2) * PI) q ≡ SQIR.Rz (PI / 2) q.\nProof.\n  intros dim q.\n  unfold Q2R; simpl.\n  autorewrite with R_db.\n  rewrite Rmult_comm.\n  reflexivity.\nQed.\n\nLemma Q2R_3_2_PI : forall {dim} q,\n  @SQIR.Rz dim (Q2R (3 / 2) * PI) q ≡ SQIR.Rz (- (PI / 2)) q.\nProof.\n  intros dim q.\n  unfold Q2R; simpl.\n  unfold uc_equiv; autorewrite with eval_db; try lia.\n  gridify.\n  replace (3 * / 2 * PI) with (2 * PI + - (PI / 2)) by lra.\n  rewrite <- phase_mul.\n  rewrite phase_2pi.\n  Msimpl.\n  reflexivity.\nQed.\n\nLemma Q2R_1_PI : Q2R 1 * PI = PI.\nProof. unfold Q2R; simpl. lra. Qed.\n\nLemma RzQ_to_full_inv : forall {dim} (l : full_ucom_l dim),\n  FullList.uc_cong_l (RzQ_to_full (full_to_RzQ l)) l.\nProof.\n  intros dim l.\n  induction l.\n  reflexivity.\n  unfold full_to_RzQ, RzQ_to_full.\n  rewrite change_gate_set_cons.\n  rewrite change_gate_set_app.\n  rewrite IHl.\n  rewrite cons_to_app.\n  FullList.apply_app_congruence_cong.\n  destruct a; dependent destruction f; \n  unfold change_gate_set; simpl; try reflexivity.\n  all: unfold FullList.uc_cong_l; simpl; repeat rewrite <- uc_cong_assoc.\n  all: unfold one_Q, half_Q, three_halves_Q, quarter_Q, seven_quarters_Q.\n  all: try (apply uc_equiv_cong;\n            repeat rewrite Q2R_1_2_PI; repeat rewrite Q2R_3_2_PI;\n            repeat rewrite Q2R_1_4_PI; repeat rewrite Q2R_7_4_PI;\n            try rewrite Q2R_1_PI; repeat rewrite Q2R_R2Q_PI; reflexivity).\n  (* U_I *)\n  unfold zero_Q.\n  rewrite RMicromega.Q2R_0, Rmult_0_l.\n  apply uc_equiv_cong.\n  rewrite Rz_0_id.\n  reflexivity. \n  (* U_Y *)\n  apply uc_equiv_cong.\n  rewrite Q2R_1_2_PI, Q2R_3_2_PI.\n  rewrite 2 SKIP_id_r.\n  unfold uc_equiv; simpl.\n  autorewrite with eval_db; try lia.\n  gridify.\n  do 2 (apply f_equal2; try reflexivity).\n  solve_matrix; autorewrite with Cexp_db; lca.\n  (* U_Rx *)\n  rewrite rx_to_rz. \n  apply uc_equiv_cong.\n  rewrite Q2R_R2Q_PI.\n  reflexivity.\n  (* U_Ry *)\n  rewrite ry_to_rz.\n  apply uc_equiv_cong.\n  rewrite Q2R_1_2_PI, Q2R_3_2_PI, Q2R_R2Q_PI.\n  reflexivity.\n  (* U_U2 *)\n  apply uc_equiv_cong.\n  rewrite 2 Q2R_R2Q_PI.\n  rewrite u2_to_rz.\n  reflexivity.\n  (* U_U3 *)\n  rewrite u3_to_rz.\n  apply uc_equiv_cong.\n  repeat rewrite Q2R_R2Q_PI.\n  reflexivity.\nQed.\n\nLemma full_to_RzQ_WT : forall {dim} (l : full_ucom_l dim),\n  uc_well_typed_l l ->\n  uc_well_typed_l (full_to_RzQ l).\nProof.\n  intros dim l WT.\n  unfold full_to_RzQ.\n  induction WT.\n  - constructor. assumption.\n  - dependent destruction u; rewrite change_gate_set_cons; \n    simpl; repeat constructor; assumption.\n  - dependent destruction u; rewrite change_gate_set_cons; \n    simpl; repeat constructor; try assumption. lia.\n  - dependent destruction u; rewrite change_gate_set_cons; \n    simpl; repeat constructor; assumption.\nQed.\n\nLemma full_to_RzQ_preserves_mapping : forall {dim} (l : full_ucom_l dim) (is_in_graph : nat -> nat -> bool),\n  respects_constraints_directed is_in_graph U_CX l ->\n  respects_constraints_directed is_in_graph URzQ_CNOT (full_to_RzQ l).\nProof.\n  intros dim l is_in_graph H.\n  unfold full_to_RzQ.\n  induction l.\n  constructor.\n  rewrite change_gate_set_cons. \n  inversion H; subst.\n  apply respects_constraints_directed_app; auto.\n  dependent destruction u; repeat constructor.\n  apply respects_constraints_directed_app; auto.\n  repeat constructor.\n  assumption.\nQed.\n\nLemma RzQ_to_full_preserves_mapping : 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 U_CX (RzQ_to_full l).\nProof.\n  intros dim l is_in_graph H.\n  unfold RzQ_to_full.\n  induction l.\n  constructor.\n  rewrite change_gate_set_cons. \n  inversion H; subst.\n  apply respects_constraints_directed_app; auto.\n  dependent destruction u; repeat constructor.\n  apply respects_constraints_directed_app; auto.\n  repeat constructor.\n  assumption.\nQed.\n\n(** * Mapping gate set **)\n\nDefinition decompose_to_cnot_and_swap_u {dim} (g : gate_app Full_Unitary dim) : full_ucom_l dim :=\n  match g with\n  | App2 U_CZ m n     => App1 U_H n :: App2 U_CX m n :: App1 U_H n :: []\n  | App3 U_CCX m n p  => App1 U_H p :: App2 U_CX n p :: App1 U_Tdg p :: \n                        App2 U_CX m p :: App1 U_T p :: App2 U_CX n p :: \n                        App1 U_Tdg p :: App2 U_CX m p :: App2 U_CX m n :: \n                        App1 U_Tdg n :: App2 U_CX m n :: App1 U_T m :: \n                        App1 U_T n :: App1 U_T p :: App1 U_H p :: [] \n  | App3 U_CCZ m n p  => App2 U_CX n p :: App1 U_Tdg p :: \n                        App2 U_CX m p :: App1 U_T p :: App2 U_CX n p :: \n                        App1 U_Tdg p :: App2 U_CX m p :: App2 U_CX m n :: \n                        App1 U_Tdg n :: App2 U_CX m n :: App1 U_T m :: \n                        App1 U_T n :: App1 U_T p :: []\n  | g => [g]\n  end.\n\nDefinition full_to_map_u {dim} (g : gate_app Full_Unitary dim) : gate_app (Map_Unitary (Full_Unitary 1)) dim :=\n  match g with\n  | App1 u m         => App1 (UMap_U u) m\n  | App2 U_CX m n    => App2 UMap_CNOT m n\n  | App2 U_SWAP m n  => App2 UMap_SWAP m n\n  | _ => App1 (UMap_U U_I) 0 (* unreachable *)\n  end.\n\nDefinition full_to_map {dim} (l : full_ucom_l dim) : map_ucom_l (Full_Unitary 1) dim := \n  change_gate_set (fun g => map full_to_map_u (decompose_to_cnot_and_swap_u g)) l.\n\nDefinition map_to_full_u {dim} (g : gate_app (Map_Unitary (Full_Unitary 1)) dim) : full_ucom_l dim :=\n  match g with\n  | App1 (UMap_U u) m    => [App1 u m]\n  | App2 UMap_CNOT m n   => [App2 U_CX m n]\n  | App2 UMap_SWAP m n   => [App2 U_SWAP m n]\n  | _ => [] (* unreachable *)\n  end.\n\nDefinition map_to_full {dim} (l : map_ucom_l (Full_Unitary 1) dim) : full_ucom_l dim := \n  change_gate_set map_to_full_u l.\n\nLemma map_to_full_inv : forall {dim} (l : full_ucom_l dim),\n  FullList.uc_equiv_l (map_to_full (full_to_map l)) l.\nProof.\n  intros dim l.\n  induction l.\n  reflexivity.\n  unfold full_to_map, map_to_full.\n  rewrite change_gate_set_cons.\n  rewrite change_gate_set_app.\n  rewrite IHl.\n  rewrite cons_to_app.\n  FullList.apply_app_congruence.\n  destruct a; dependent destruction f; \n  unfold change_gate_set; simpl; try reflexivity.\n  all: unfold FullList.uc_equiv_l; simpl;\n    repeat rewrite <- useq_assoc; reflexivity.\nQed.\n\nLemma full_to_map_WT : forall {dim} (l : full_ucom_l dim),\n  uc_well_typed_l l ->\n  uc_well_typed_l (full_to_map l).\nProof.\n  intros dim l WT.\n  unfold full_to_map.\n  induction WT.\n  - constructor. assumption.\n  - dependent destruction u; rewrite change_gate_set_cons; \n    simpl; repeat constructor; assumption.\n  - dependent destruction u; rewrite change_gate_set_cons; \n    simpl; repeat constructor; assumption.\n  - dependent destruction u; rewrite change_gate_set_cons; \n    simpl; repeat constructor; assumption.\nQed.\n\nLemma map_to_full_preserves_mapping_undirected : forall {dim} (l : map_ucom_l (Full_Unitary 1) dim) (is_in_graph : nat -> nat -> bool),\n  respects_constraints_undirected is_in_graph l ->\n  respects_constraints_undirected is_in_graph (map_to_full l).\nProof.\n  intros dim l is_in_graph H.\n  unfold map_to_full.\n  induction l.\n  constructor.\n  rewrite change_gate_set_cons. \n  inversion H; subst.\n  apply respects_constraints_undirected_app; auto.\n  dependent destruction u; repeat constructor.\n  apply respects_constraints_undirected_app; auto.\n  dependent destruction u; constructor.\n  assumption. constructor. assumption. constructor.\nQed.\n\nLemma map_to_full_preserves_mapping_directed : forall {dim} (l : map_ucom_l (Full_Unitary 1) dim) (is_in_graph : nat -> nat -> bool),\n  respects_constraints_directed is_in_graph UMap_CNOT l ->\n  respects_constraints_directed is_in_graph U_CX (map_to_full l).\nProof.\n  intros dim l is_in_graph H.\n  unfold map_to_full.\n  induction l.\n  constructor.\n  rewrite change_gate_set_cons. \n  inversion H; subst.\n  apply respects_constraints_directed_app; auto.\n  dependent destruction u; repeat constructor.\n  apply respects_constraints_directed_app; auto.\n  repeat constructor.\n  assumption.\nQed.\n\nLemma full_to_map_preserves_mapping_undirected : forall {dim} (l : full_ucom_l dim) (is_in_graph : nat -> nat -> bool),\n  respects_constraints_undirected is_in_graph l ->\n  respects_constraints_undirected is_in_graph (full_to_map l).\nProof.\n  intros dim l is_in_graph H.\n  unfold full_to_map.\n  induction l.\n  constructor.\n  rewrite change_gate_set_cons. \n  inversion H; subst.\n  apply respects_constraints_undirected_app; auto.\n  dependent destruction u; repeat constructor.\n  apply respects_constraints_undirected_app; auto.\n  dependent destruction u; repeat apply res_und_app2; try assumption. \n  constructor. \n  constructor. constructor. assumption. constructor. constructor.\n  constructor.\nQed.\n\n(** * Check that every gate in the program satisfies some predicate **)\n\nDefinition forall_gates {U : nat -> Set} {dim} (p : gate_app U dim -> Prop) (l : gate_list U dim) :=\n  forall g, In g l -> p g.\n\nLemma forall_gates_drop : forall {U : nat -> Set} {dim} (p : gate_app U dim -> Prop) (g : gate_app U dim) (l : gate_list U dim),\n  forall_gates p (g :: l) -> forall_gates p l.\nProof.\n  intros U dim p g l H.\n  unfold forall_gates in *.\n  intros g0 Hg0.\n  apply H.\n  right.\n  assumption.\nQed.\n\nLemma forall_gates_extend : forall {U : nat -> Set} {dim} (p : gate_app U dim -> Prop) (g : gate_app U dim) (l : gate_list U dim),\n  p g -> forall_gates p l -> forall_gates p (g :: l).\nProof.\n  intros U dim p g l Hg Hl.\n  unfold forall_gates in *.\n  intros g0 [Hg0 | Hg0].\n  subst. \n  assumption.\n  apply Hl.\n  assumption.\nQed.\n\nLemma forall_gates_append : forall {U : nat -> Set} {dim} (p : gate_app U dim -> Prop) (l1 l2 : gate_list U dim),\n  forall_gates p l1 -> forall_gates p l2 -> forall_gates p (l1 ++ l2).\nProof.\n  intros U dim p l1 l2 Hl1 Hl2.\n  unfold forall_gates in *.\n  intros g Hg.\n  apply in_app_or in Hg as [Hg | Hg]; auto.\nQed.\n\n(** * Other gate set conversions **)\n\n(* Transform program in the full gate set to only use CNOT + 1q gates *)\nDefinition decompose_to_cnot_u {dim} (g : gate_app Full_Unitary dim) : full_ucom_l dim :=\n  match g with\n  | App2 U_CZ m n     => App1 U_H n :: App2 U_CX m n :: App1 U_H n :: []\n  | App2 U_SWAP m n   => App2 U_CX m n :: App2 U_CX n m :: App2 U_CX m n :: []\n  | App3 U_CCX m n p  => App1 U_H p :: App2 U_CX n p :: App1 U_Tdg p :: \n                        App2 U_CX m p :: App1 U_T p :: App2 U_CX n p :: \n                        App1 U_Tdg p :: App2 U_CX m p :: App2 U_CX m n :: \n                        App1 U_Tdg n :: App2 U_CX m n :: App1 U_T m :: \n                        App1 U_T n :: App1 U_T p :: App1 U_H p :: [] \n  | App3 U_CCZ m n p  => App2 U_CX n p :: App1 U_Tdg p :: \n                        App2 U_CX m p :: App1 U_T p :: App2 U_CX n p :: \n                        App1 U_Tdg p :: App2 U_CX m p :: App2 U_CX m n :: \n                        App1 U_Tdg n :: App2 U_CX m n :: App1 U_T m :: \n                        App1 U_T n :: App1 U_T p :: []\n  | g => [g]\n  end.\n\nDefinition decompose_to_cnot {dim} (l : full_ucom_l dim) :=\n  change_gate_set decompose_to_cnot_u l.\n\nDefinition only_cnots {dim} (g : gate_app Full_Unitary dim) :=\n  match g with\n  | App2 U_CZ _ _ | App2 U_SWAP _ _ | App3 U_CCX _ _ _ | App3 U_CCZ _ _ _ => False\n  | _ => True\n  end.\n\nLemma decompose_to_cnot_gates : forall {dim} (l : full_ucom_l dim),\n  forall_gates only_cnots (decompose_to_cnot l).\nProof.\n  intros dim l.\n  unfold decompose_to_cnot.\n  induction l.\n  - rewrite change_gate_set_nil.\n    intros g H.\n    inversion H.\n  - rewrite change_gate_set_cons.\n    intros g H.\n    apply in_app_or in H as [H | H].\n    destruct a; dependent destruction f.\n    all: simpl in H; repeat destruct H as [H | H]; try rewrite <- H; \n         simpl; auto; try contradiction. \nQed.\n\nLemma decompose_to_cnot_sound : forall {dim} (l : full_ucom_l dim),\n  FullList.uc_equiv_l (decompose_to_cnot l) l.\nProof.\n  intros dim l.\n  unfold decompose_to_cnot.\n  induction l.\n  - rewrite change_gate_set_nil.\n    reflexivity.\n  - rewrite change_gate_set_cons.\n    unfold FullList.uc_equiv_l in *.\n    simpl.\n    rewrite FullList.list_to_ucom_append.\n    destruct a; apply useq_congruence; try apply IHl;\n      dependent destruction f; simpl; \n      repeat rewrite <- useq_assoc; rewrite SKIP_id_r; \n      reflexivity.\nQed.\n\nLemma decompose_to_cnot_WT : forall {dim} (l : full_ucom_l dim),\n  uc_well_typed_l l -> uc_well_typed_l (decompose_to_cnot l).\nProof.\n  intros dim l WT.\n  eapply FullList.uc_equiv_l_implies_WT.\n  symmetry.\n  apply decompose_to_cnot_sound.\n  assumption.\nQed.\n\nDefinition convert_to_ibm {dim} (l : full_ucom_l dim) : full_ucom_l dim := \n  IBM_to_full (full_to_IBM l).\n\nDefinition only_ibm {dim} (g : gate_app Full_Unitary dim) :=\n  match g with\n  | App1 (U_U1 _) _ | App1 (U_U2 _ _) _ | App1 (U_U3 _ _ _) _ | App2 U_CX _ _ => True\n  | _ => False\n  end.\n\nLemma convert_to_ibm_gates : forall {dim} (l : full_ucom_l dim),\n  forall_gates only_ibm (convert_to_ibm l).\nProof.\n  intro dim.\n  assert (H : forall (l : IBM_ucom_l dim), forall_gates only_ibm (IBM_to_full l)).\n  { unfold IBM_to_full.\n    induction l.\n    - rewrite change_gate_set_nil.\n      intros g H.\n      inversion H.\n    - rewrite change_gate_set_cons.\n      intros g H.\n      apply in_app_or in H as [H | H].\n      destruct a; dependent destruction i.\n      all: simpl in H; repeat destruct H as [H | H]; try rewrite <- H.\n      all: simpl; auto; contradiction. }\n  intro l.\n  apply H.  \nQed.\n\nLemma convert_to_ibm_sound : forall {dim} (l : full_ucom_l dim),\n  FullList.uc_equiv_l (convert_to_ibm l) l.\nProof. intros. apply IBM_to_full_inv. Qed.\n\nLemma convert_to_ibm_preserves_mapping : forall {dim} (l : full_ucom_l dim) (is_in_graph : nat -> nat -> bool),\n  respects_constraints_directed is_in_graph U_CX l ->\n  respects_constraints_directed is_in_graph U_CX (convert_to_ibm l).\nProof.\n  intros dim l is_in_graph H.\n  unfold convert_to_ibm.\n  apply IBM_to_full_preserves_mapping.\n  apply full_to_IBM_preserves_mapping.\n  assumption.\nQed.\n\nDefinition convert_to_rzq {dim} (l : full_ucom_l dim) : full_ucom_l dim := \n  RzQ_to_full (full_to_RzQ l).\n\nDefinition only_rzq {dim} (g : gate_app Full_Unitary dim) :=\n  match g with\n  | App1 U_H _ | App1 U_X _ | App1 (U_Rzq _) _ | App2 U_CX _ _ => True\n  | _ => False\n  end.\n\nLemma convert_to_rzq_gates : forall {dim} (l : full_ucom_l dim),\n  forall_gates only_rzq (convert_to_rzq l).\nProof.\n  intro dim.\n  assert (H : forall (l : RzQ_ucom_l dim), forall_gates only_rzq (RzQ_to_full l)).\n  { unfold RzQ_to_full.\n    induction l.\n    - rewrite change_gate_set_nil.\n      intros g H.\n      inversion H.\n    - rewrite change_gate_set_cons.\n      intros g H.\n      apply in_app_or in H as [H | H].\n      destruct a; dependent destruction r.\n      all: simpl in H; repeat destruct H as [H | H]; try rewrite <- H.\n      all: simpl; auto; contradiction. }\n  intro l.\n  apply H.  \nQed.\n\nLemma convert_to_rzq_sound : forall {dim} (l : full_ucom_l dim),\n  FullList.uc_cong_l (convert_to_rzq l) l.\nProof. intros. apply RzQ_to_full_inv. Qed.\n\nLemma convert_to_rzq_preserves_mapping : forall {dim} (l : full_ucom_l dim) (is_in_graph : nat -> nat -> bool),\n  respects_constraints_directed is_in_graph U_CX l ->\n  respects_constraints_directed is_in_graph U_CX (convert_to_rzq l).\nProof.\n  intros dim l is_in_graph H.\n  unfold convert_to_rzq.\n  apply RzQ_to_full_preserves_mapping.\n  apply full_to_RzQ_preserves_mapping.\n  assumption.\nQed.\n\n(* Replace Rzq gates with I, Z, S, Sdg, T, Tdg, or Rz gates. *)\nDefinition replace_rzq_u {dim} (g : gate_app Full_Unitary dim) : full_ucom_l dim :=\n  match g with\n  | App1 (U_Rzq q) m => \n      if Qeq_bool q zero_Q then [App1 U_I m]\n      else if Qeq_bool q one_Q then [App1 U_Z m]\n      else if Qeq_bool q half_Q then [App1 U_S m]\n      else if Qeq_bool q three_halves_Q then [App1 U_Sdg m]\n      else if Qeq_bool q quarter_Q then [App1 U_T m]\n      else if Qeq_bool q seven_quarters_Q then [App1 U_Tdg m]\n      else [App1 (U_Rz (Q2R q * PI)) m]\n  | g => [g]\n  end.\n\nDefinition replace_rzq {dim} (l : full_ucom_l dim) :=\n  change_gate_set replace_rzq_u l.\n\nDefinition no_rzq {dim} (g : gate_app Full_Unitary dim) :=\n  match g with\n  | App1 (U_Rzq _) _ => False\n  | _ => True\n  end.\n\nLtac destruct_Qeq_bool :=\n  repeat match goal with\n  | H : context[if Qeq_bool ?a ?b then _ else _] |- _ => \n      destruct (Qeq_bool a b) eqn:? \n  | |- context[if Qeq_bool ?a ?b then _ else _] => \n      destruct (Qeq_bool a b) eqn:? \n  | H : Qeq_bool _ _ = true |- _ => apply Qeq_bool_iff in H\n  | H : Qeq_bool _ _ = false |- _ => clear H\n  | H : (_ == _)%Q |- _ => apply Qeq_eqR in H; try rewrite H\n  end.\n\nLemma replace_rzq_gates : forall {dim} (l : full_ucom_l dim),\n  forall_gates no_rzq (replace_rzq l).\nProof.\n  intros dim l.\n  unfold replace_rzq.\n  induction l.\n  - rewrite change_gate_set_nil.\n    intros g H.\n    inversion H.\n  - rewrite change_gate_set_cons.\n    intros g H.\n    apply in_app_or in H as [H | H].\n    destruct a; dependent destruction f.\n    all: simpl in H.\n    all: destruct_Qeq_bool.\n    all: repeat destruct H as [H | H]; try rewrite <- H.\n    all: simpl; auto; try contradiction.\nQed.\n\nLemma replace_rzq_sound : forall {dim} (l : full_ucom_l dim),\n  FullList.uc_equiv_l (replace_rzq l) l.\nProof.\n  intros dim l.\n  unfold replace_rzq.\n  induction l.\n  - rewrite change_gate_set_nil.\n    reflexivity.\n  - rewrite change_gate_set_cons.\n    unfold FullList.uc_equiv_l in *.\n    simpl.\n    rewrite FullList.list_to_ucom_append.\n    destruct a; apply useq_congruence; try apply IHl;\n      dependent destruction f; simpl;\n      repeat rewrite <- useq_assoc; try rewrite SKIP_id_r; try reflexivity.\n    destruct_Qeq_bool; simpl; rewrite SKIP_id_r.\n    unfold zero_Q.\n    rewrite RMicromega.Q2R_0.\n    rewrite Rmult_0_l.\n    reflexivity.\n    unfold one_Q.\n    rewrite RMicromega.Q2R_1.\n    rewrite Rmult_1_l.\n    reflexivity.\n    unfold half_Q.\n    rewrite Q2R_1_2_PI.\n    reflexivity.\n    unfold three_halves_Q.\n    bdestruct (n <? dim)%nat.\n    rewrite Q2R_3_2_PI by assumption.\n    reflexivity.\n    unfold uc_equiv; simpl; unfold SQIR.PDAG; autorewrite with eval_db; gridify.\n    unfold quarter_Q.\n    rewrite Q2R_1_4_PI.\n    reflexivity.\n    unfold seven_quarters_Q.\n    bdestruct (n <? dim)%nat.\n    rewrite Q2R_7_4_PI by assumption.\n    reflexivity.\n    unfold uc_equiv; simpl; unfold SQIR.TDAG; autorewrite with eval_db; gridify.\n    reflexivity.\nQed.\n\nLemma replace_rzq_preserves_mapping : forall {dim} (l : full_ucom_l dim) (is_in_graph : nat -> nat -> bool),\n  respects_constraints_directed is_in_graph U_CX l ->\n  respects_constraints_directed is_in_graph U_CX (replace_rzq l).\nProof.\n  intros dim l is_in_graph H.\n  unfold replace_rzq.\n  induction l.\n  constructor.\n  rewrite change_gate_set_cons. \n  inversion H; subst.\n  apply respects_constraints_directed_app; auto.\n  dependent destruction u; repeat constructor.\n  simpl.\n  destruct_Qeq_bool; repeat constructor.\n  apply respects_constraints_directed_app; auto.\n  repeat constructor.\n  assumption.\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/FullGateSet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.27966547730062913}}
{"text": "Require Import MetaCoq.Template.All.\nRequire Import List String Relation_Operators.\nImport ListNotations MonadNotation.\n\n(* Require Import sigma. *)\n\nDefinition filteri {A: Type} (f : nat -> A -> bool) (l:list A) : list A :=\n  let go := fix go n l := match l with\n                         | nil => nil\n                         | x :: l => if f n x then x::(go (S n) l) else go (S n) l\n                         end\n  in go 0 l.\n\nDefinition ind_eqb (i0 : inductive) (i1 : inductive) : bool :=\n  andb (String.eqb i0.(inductive_mind) i1.(inductive_mind))\n       (Nat.eqb i0.(inductive_ind) i1.(inductive_ind)).\n\nDefinition opt_nil {A : Type} (x : option A) : list A := match x with Some a => [a]| None => [] end.\n\nDefinition clift0 (n : nat) (t : context_decl) : context_decl :=\n  {| decl_name := t.(decl_name);\n     decl_body := match t.(decl_body) with\n                   | Some q => Some (lift0 n q)\n                   | None => None\n                  end;\n     decl_type := lift0 n t.(decl_type)\n  |}.\n\nDefinition subterms_for_constructor\n           (refi  : inductive)\n           (ref   : term) (* we need the term that contrains exactly this inductive just for the substition *)\n           (npars : nat) (* number of parameters in the type *)\n           (nind : nat) (* number of proper indeces in the type *)\n           (ct    : term) (* type of the constructor *)\n           (ncons : nat) (* index of the constructor in the inductive *)\n           (nargs : nat) (* number of arguments in this constructor *)\n                  : list (nat * term * nat)\n  := let nct := subst10 ref ct in\n     let '(ctx, ap) := decompose_prod_assum [] nct in\n     (* now ctx is reversed list of assumptions and definitions *)\n     let len := List.length ctx in\n     let params := List.skipn (len - npars) (ctx) in\n     let inds := List.skipn npars (snd (decompose_app ap)) in\n     let d :=(List.flat_map opt_nil ∘\n                  (* so this i represents distance from the innermost object *)\n               mapi (fun i t =>\n                       let '(ctx, ar) := decompose_prod_assum [] (decl_type t)\n                       in match (fst (decompose_app ar)) with\n                          | tInd indj _ => if ind_eqb indj refi\n                                          then Some (i, ctx,\n                                                     snd (decompose_app ar))\n                                          else None\n                          | _ => None\n                          end)) ctx in\n     let construct_cons :=\n         fun (* index of a subterm in this constructor *)\n           (i: nat)\n           (* these are arguments for the function\n              that is a parameter of the constructor\n              and if applied fully returns something of the needed type *)\n           (ctx': context)\n           (* these are arguments of the type of the subterm *)\n           (args' : list term) =>\n           let len' := List.length ctx' in\n           let ctxl' := (map (clift0 (2 + i)) ctx') in\n           it_mkProd_or_LetIn\n             (ctxl' ++ ctx)\n             (tApp (tRel (len + len'))\n                   ((map (lift0 (len' + len - npars))\n                         (to_extended_list params)) ++\n                    (map (lift (1 + i + len') len') (List.skipn npars args')) ++\n                    (map (lift0 len') inds) ++\n                    [tApp (tRel (i + len'))\n                          (to_extended_list ctxl');\n                     tApp (tConstruct refi ncons [])\n                          (map (lift0 len')\n                               (to_extended_list ctx))])) in\n     mapi (fun i '(n, c, a) => (i, construct_cons n c a, len + List.length c)) d.\n\nDefinition subterm_for_ind\n           (refi  : inductive) (* reference term for the inductive type *)\n           (ref   : term)\n           (npars : nat)\n           (pars  : context)\n           (ind   : one_inductive_body)\n                  : one_inductive_body\n  := let (pai, sort) := decompose_prod_assum [] ind.(ind_type) in\n     let inds := List.firstn (List.length pai - npars) pai in\n     let leni := List.length inds in\n     let aptype1 :=\n         tApp ref ((map (lift0 (2 * leni)) (to_extended_list pars)) ++\n                   (map (lift0 leni) (to_extended_list inds))) in\n     let aptype2 :=\n         tApp ref ((map (lift0 (1 + 2 * leni)) (to_extended_list pars)) ++\n                   (map (lift0 1) (to_extended_list inds))) in\n     let renamer name i := (name ++ \"_subterm\" ++ (string_of_nat i))%string in\n     {| ind_name := (ind.(ind_name) ++ \"_direct_subterm\")%string;\n        (* type_for_direct_subterm npars *)\n        ind_type  := it_mkProd_or_LetIn\n                       pars\n                       (it_mkProd_or_LetIn\n                          (inds ++ inds)\n                          (tProd nAnon aptype1\n                                 (tProd nAnon aptype2 sort)));\n        ind_kelim := [InProp];\n        ind_ctors :=List.concat\n                      (mapi (fun n '(id, ct, k) => (\n                        map (fun '(si, st, sk) => (renamer id si, st, sk))\n                        (subterms_for_constructor refi ref npars leni ct n k)))\n                        ind.(ind_ctors));\n        ind_projs := [] |}.\n\nDefinition direct_subterm_for_mutual_ind\n            (mind : mutual_inductive_body)\n            (ind0 : inductive) (* internal metacoq representation of inductive, part of tInd *)\n            (ref  : term) (* reference term for the inductive type, like (tInd {| inductive_mind := \"Coq.Init.Datatypes.nat\"; inductive_ind := 0 |} []) *)\n                  : mutual_inductive_body\n  := let i0 := inductive_ind ind0 in\n     {| ind_finite := BasicAst.Finite;\n        ind_npars := mind.(ind_npars);\n        ind_universes := mind.(ind_universes);\n        ind_params := mind.(ind_params);\n        ind_bodies := (map (subterm_for_ind ind0 ref mind.(ind_npars) mind.(ind_params)) ∘\n                      (filteri (fun (i : nat) (ind : one_inductive_body) =>\n                                  if Nat.eqb i i0 then true else false)))\n                      mind.(ind_bodies);\n     |}.\n\nPolymorphic Definition subterm (tm : Ast.term)\n  : TemplateMonad unit\n  := match tm with\n     | tInd ind0 _ =>\n       (* ge_ <- tmQuoteRec tm;; *)\n       decl <- tmQuoteInductive (inductive_mind ind0);;\n       let direct_subterm := direct_subterm_for_mutual_ind decl ind0 tm in\n       tmMkInductive' direct_subterm\n       (* v <- tmEval direct_subterm;;\n          tmPrint v;; *)\n     | _ => tmPrint tm;; tmFail \"is not an inductive\"\n     end.\n\nInductive finn (A : Type) : nat -> Set :=\n  F1n : forall n : nat, finn A (S n)\n| FSn : forall n : nat, finn A n -> finn A (S n).\n\nInductive fin : nat -> Type :=\n  F1 : forall n : nat, fin (let x := S n in x)\n| FS : forall n : nat, fin n -> fin (S n).\n\nRun TemplateProgram (subterm <%list%>).\nPrint list_direct_subterm.\n\nDefinition scope := nat.\nInductive scope_le : scope -> scope -> Set :=\n| scope_le_n : forall {n m}, n = m -> scope_le n m\n| scope_le_S : forall {n m}, scope_le n m -> scope_le n (S m)\n| scope_le_map : forall {n m}, scope_le n m -> scope_le (S n) (S m)\n.\n\nRun TemplateProgram (subterm <%scope_le%>).\n\n(*\nInductive\nscope_le_direct_subterm\n    : forall H H0 H1 H2 : scope, scope_le H H0 -> scope_le H1 H2 -> Set :=\n    scope_le_S_subterm0 : forall (n m : scope) (H : scope_le n m),\n                          scope_le_direct_subterm n m n (S m) H (scope_le_S H)\n  | scope_le_map_subterm0 : forall (n m : scope) (H : scope_le n m),\n                            scope_le_direct_subterm n m \n                              (S n) (S m) H (scope_le_map H)\n*)\n", "meta": {"author": "liesnikov", "repo": "subterm-metacoq", "sha": "2d3f9c828f914878db540792ae632980229daf4e", "save_path": "github-repos/coq/liesnikov-subterm-metacoq", "path": "github-repos/coq/liesnikov-subterm-metacoq/subterm-metacoq-2d3f9c828f914878db540792ae632980229daf4e/subterm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.27960495277831177}}
{"text": "(*\n * Copyright (c) 2022 BedRock Systems, Inc.\n *\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\nRequire Import bedrock.prelude.base.\nRequire Import bedrock.lang.bi.split_andb.\n\n(**\n[Split b b1 b2] succeeds if [SplitAndB b] outputs [b1], [b2].\n*)\nClass Split (b b1 b2 : bool) : Prop := split : SplitAndB b b1 b2.\n#[global] Hint Mode Split + + + : typeclass_instances.\n#[global] Instance split_instance b b'1 b'2 b1 b2 :\n  SplitAndB b b'1 b'2 -> TCEq b1 b'1 -> TCEq b2 b'2 -> Split b b1 b2 | 10.\nProof. by rewrite !TCEq_eq=>? ->->. Qed.\n\nSection split.\n\n  Lemma split_andb b1 b2 : Split (b1 && b2) b1 b2.\n  Proof. apply _. Abort.\n\n  Lemma split_x b : Split b b b.\n  Proof. apply _. Abort.\n\nEnd split.\n\n(**\n[Combine b1 b2 b] succeeds if [CombineAndB b1 b2] outputs [b].\n*)\nClass Combine (b1 b2 b : bool) : Prop := combine : CombineAndB b1 b2 b.\n#[global] Hint Mode Combine + + + : typeclass_instances.\n#[global] Instance combine_instance b1 b2 b' b :\n  CombineAndB b1 b2 b' -> TCEq b b' -> Combine b1 b2 b | 10.\nProof. by rewrite TCEq_eq=>? ->. Qed.\n\nSection combine.\n\n  Lemma combine_00 : Combine false false false.\n  Proof. apply _. Abort.\n  Lemma combine_01 : Combine false true false.\n  Proof. apply _. Abort.\n  Lemma combine_10 : Combine true false false.\n  Proof. apply _. Abort.\n  Lemma combine_11 : Combine true true true.\n  Proof. apply _. Abort.\n\n  Lemma combine_0x b : Combine false b false.\n  Proof. apply _. Abort.\n  Lemma combine_x0 b : Combine b false false.\n  Proof. apply _. Abort.\n\n  Lemma combine_1x b : Combine true b b.\n  Proof. apply _. Abort.\n  Lemma combine_x1 b : Combine b true b.\n  Proof. apply _. Abort.\n\n  Lemma combine_xx b1 b2 : Combine b1 b2 (b1 && b2).\n  Proof. apply _. Abort.\n\nEnd combine.\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/bi/split_andb_tests.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.27960495277831177}}
{"text": "From Coq Require Import\n     ssreflect\n.\n\nFrom ExtensibleCompiler.Theory Require Import\n     Algebra\n     Functor\n     SubFunctor\n     Sum1\n     UniversalProperty\n.\n\nLocal Open Scope SubFunctor.\nLocal Open Scope Sum1.\n\n(**\n\n[ProofAlgebra] captures those algebras that we will use for theorem proving.\nBecause proofs are not computationally-revelant, they will never use more\nadvanced algebras like Mendler of Mixin.  Simple, plain old algebras suffice.\n\nIn practice, we will use them at type [sig P] for a given property [P] to prove\nabout the term of interest.\n\nIn order to distinguish some [ProofAlgebra]s that would otherwise have the\nsame signature, each [ProofAlgebra] is given a unique [Tag].  This helps\nthe typeclass mechanism find the appropriate instance among a bunch of program\nalgebras with the same carrier types.\n\nYou can just create a new label with:\n[Variant MyTag := .]\nThe type does not need any inhabitant, we only use its type identity.\n\n*)\n\nClass ProofAlgebra (* cf. [PAlgebra] *)\n      (Tag : Set) F A\n      `{Functor F}\n  :=\n    {\n      proofAlgebra : (* cf. [p_algebra] *)\n        Algebra F A;\n    }.\n\n(**\nJust like [proofAlgebra], but when you want to provide the [ProofAlgebra]\nexplicitly.\n *)\nDefinition proofAlgebra'\n           {Tag F A}\n           `{Functor F}\n           (PA : ProofAlgebra Tag F A)\n  : Algebra F A\n  := proofAlgebra (ProofAlgebra := PA).\n\nGlobal Instance\n       ProofAlgebra__Sum1\n       Tag F G {A}\n       `{Functor F} `{Functor G}\n       `{! ProofAlgebra Tag F A}\n       `{! ProofAlgebra Tag G A}\n  : ProofAlgebra Tag (F + G) A\n  :=\n    {|\n      proofAlgebra :=\n        fun fg =>\n          match fg with\n          | inl1 f => proofAlgebra f\n          | inr1 g => proofAlgebra g\n          end\n      ;\n    |}.\n\n(**\n\nA proof-producing [ProofAlgebra] is well-formed if the term it re-creates by\napplying the algebra (in the left hand of the dependent pair) is indeed the\noriginal term.  That is, the following diagram commutes:\n\n                          proofAlgebra\nF (Σ (e : Fix E) . P e) ---------------> Σ (e : Fix E) . P e\n        |                                          |\n        | fmap proj1_sig                           |\n        v                                          |\n     F (Fix E)                                     | proj1_sig\n        |                                          |\n        | inj                                      |\n        v                                          v\n    E (Fix E) ---------------------------------> Fix E\n                           wrapF\n\n*)\n\n(** NOTE: it does not pay off trying to make [P] be about [WellFormedValue]\n    properties, because we will not be able to prove the property over the\n    dependent pair, only about its [proj1_sig].\n*)\nClass WellFormedProofAlgebra (* cf. [WF_Ind] *)\n      {Tag E F} {P : Fix E -> Prop}\n      `{Functor E} `{Functor F}\n      `{E supports F}\n      `(PA : ! ProofAlgebra Tag F (sig P))\n  :=\n    {\n      projEq\n      : forall e,\n        (* run [proofAlgebra], then observe the term *)\n        proj1_sig (proofAlgebra e)\n        =\n        (* observe all subterms via [fmap], and combine them *)\n        wrapF (inject (E := E) (fmap (proj1_sig (P := P)) e));\n    }.\n\n(* TODO: document why we need this *)\n(* TODO: fix this so that [Tag] [F] [G] [H] are explicit and [PA] implicit *)\nClass WellFormedProofAlgebra2 (* cf. [WF_Ind2] *)\n      {Tag F G H}\n      `{SG : SubFunctor F G} `{SH : SubFunctor F H}\n      {P : (Fix G * Fix H) -> Prop}\n      `(PA : ! ProofAlgebra Tag F (sig P))\n  :=\n    {\n      proj1Eq\n      : forall e,\n        (* run [proofAlgebra], then observe the term *)\n        fst (proj1_sig (proofAlgebra (ProofAlgebra := PA) e))\n        =\n        (* observe all subterms via [fmap], and combine them *)\n        wrapF (inject (SubFunctor := SG) (fmap (fun e => fst (proj1_sig (P := P) e)) e));\n      proj2Eq\n      : forall e,\n        (* run [proofAlgebra], then observe the term *)\n        snd (proj1_sig (proofAlgebra (ProofAlgebra := PA) e))\n        =\n        (* observe all subterms via [fmap], and combine them *)\n        wrapF (inject (SubFunctor := SH) (fmap (fun e => snd (proj1_sig (P := P) e)) e));\n    }.\n\n(* TODO *)\n(*\nGlobal Instance\n       WellFormedProofAlgebraSum1\n       {P}\n       {F} `{Functor F} {FAlg : ProofAlgebra F (sig P)}\n       {G} `{Functor G} {GAlg : ProofAlgebra G (sig P)}\n       {H} `{Functor H}\n       `{FGH : (F + G) <= H}\n       {_ : WellFormedProofAlgebra (F := F) (G := H) (FG := SubFunctorLeft  (FG := FGH)) FAlg}\n       {_ : WellFormedProofAlgebra (F := G) (G := H) (FG := SubFunctorRight (FH := FGH)) GAlg}\n  : WellFormedProofAlgebra (ProofAlgebraSum1 FAlg GAlg).\nProof.\n  constructor.\n  intros rec f.\n  unfold inj.\n  unfold SubFunctorLeft.\n  simpl.\n  rewrite wellFormedProofAlgebra.\n  reflexivity.\nQed.\n *)\n\nLemma Fusion'\n      {F} `{Functor F}\n      (e : Fix F) {UP : FoldUP' e}\n      (A B : Set) (h : A -> B) (f : Algebra F A) (g : Algebra F B)\n      (HF : forall a, h (f a) = g (fmap h a))\n      : (fun e' => h (fold f e')) e = fold g e.\nProof.\n  apply foldUP' => e'.\n  rewrite (FoldUP F _ f) => //.\n  rewrite HF.\n  rewrite fmapFusion.\n  rewrite /compose //.\nQed.\n\nLemma Fusion\n      {F} `{Functor F}\n      `{Functor F}\n      (e : WellFormedValue F)\n      (A B : Set) (h : A -> B) (f : Algebra F A) (g : Algebra F B)\n      (HF : forall a, h (f a) = g (fmap h a))\n      : (fun e' => h (fold f e')) (proj1_sig e) = fold g (proj1_sig e).\nProof.\n  case e => *.\n  apply Fusion' => //.\nQed.\n\n(**\nTODO: document this, where is it used? why does it need a well-formed reflexive\nsub-functor?\n *)\nLemma proj1_fold_is_id\n      {Tag F} `{Functor F}\n      {P : Fix F -> Prop}\n      {PA : ProofAlgebra Tag F (sig P)}\n      `{! WellFormedProofAlgebra PA}\n  : forall (f : Fix F),\n    FoldUP' f ->\n    proj1_sig (fold (proofAlgebra' PA) f) = f.\nProof.\n  move => f UP.\n  setoid_rewrite Fusion' with (g := wrapF) => //.\n  {\n    rewrite fold_wrapF_Identity //.\n  }\n  {\n    move => a.\n    rewrite projEq //.\n  }\nQed.\n\nLemma fst_proj1_fold_is_id\n      {Tag F} `{Functor F}\n      {P : (Fix F * Fix F) -> Prop}\n      {PA : ProofAlgebra Tag F (sig P)}\n      {WFPA : WellFormedProofAlgebra2 PA}\n  : forall (f : Fix F),\n    FoldUP' f ->\n    fst (proj1_sig (fold (proofAlgebra' PA) f)) = f.\nProof.\n  move => f UP.\n  setoid_rewrite (Fusion' f _ _ (fun e => fst (proj1_sig e)) _ wrapF).\n  {\n    rewrite fold_wrapF_Identity //.\n  }\n  {\n    move => a.\n    rewrite proj1Eq //.\n  }\nQed.\n\nLemma snd_proj1_fold_is_id\n      {Tag F} `{Functor F}\n      {P : (Fix F * Fix F) -> Prop}\n      {PA : ProofAlgebra Tag F (sig P)}\n      {_ : WellFormedProofAlgebra2 PA}\n  : forall (f : Fix F),\n    FoldUP' f ->\n    snd (proj1_sig (fold (proofAlgebra' PA) f)) = f.\nProof.\n  move => f UP.\n  setoid_rewrite (Fusion' f _ _ (fun e => snd (proj1_sig e)) _ wrapF).\n  {\n    rewrite fold_wrapF_Identity //.\n  }\n  {\n    move => a.\n    rewrite proj2Eq //.\n  }\nQed.\n\nLemma Induction (* cf. [Ind] *)\n      {Tag F}\n      `{Functor F}\n      {P : Fix F -> Prop}\n      `{PA : ! ProofAlgebra Tag F (sig P)}\n      `{! WellFormedProofAlgebra PA}\n  : forall (f : Fix F),\n    FoldUP' f ->\n    P f.\nProof.\n  move => f UP.\n  setoid_rewrite <- proj1_fold_is_id => //.\n  apply proj2_sig.\nQed.\n\nLemma Induction'\n      {Tag F}\n      `{Functor F}\n      {P : Fix F -> Prop}\n      `{PA : ! ProofAlgebra Tag F (sig P)}\n      `{! WellFormedProofAlgebra PA}\n  : forall (f : WellFormedValue F),\n    P (proj1_sig f).\nProof.\n  destruct f as [f UP].\n  now apply Induction.\nQed.\n\nLemma Induction2 (* cf. [Ind2] *)\n      {Tag F} `{Functor F}\n      {P : (Fix F * Fix F) -> Prop}\n      {PA : ProofAlgebra Tag F (sig P)}\n      {_ : WellFormedProofAlgebra2 PA}\n  : forall (f : Fix F),\n    FoldUP' f ->\n    P (f, f).\nProof.\n  move => f UP.\n  setoid_rewrite <- (fst_proj1_fold_is_id f UP) at 1.\n  setoid_rewrite <- (snd_proj1_fold_is_id f UP) at 2.\n  rewrite <- surjective_pairing.\n  apply proj2_sig.\nQed.\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/Theory/ProofAlgebra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.27960495277831177}}
{"text": "(** printing nat %\\ensuremath{\\mathbb{N}}% #&#8469;# *)\n(** printing -> %\\ensuremath{\\to}% #&#8594;$ *)\n\n(* begin hide *)\nRequire Import mathcomp.ssreflect.all_ssreflect.\nRequire Import Paco.paco.\nRequire Import Int63.\n\n\nRequire Import Utils.ZooidTac.\nRequire Import Zooid2.Types.\n\n\nSet Implicit Arguments.\nSet Primitive Projections.\n(* end hide *)\n\n(** * Act II: Smol-Zooid: multiparty with shallower embedding  *)\n\n\n\n(** ** Preliminaries\n\nDeep embeddings lead to complex complex binder mechanisations. Can shallow\nembeddings of binders help mechanising a small process language?\n\n*)\n\n\n(** ** Smol Zooid *)\n\n(** This is a small process language *)\n\n\n(** We introduce a typing discipline for [proc], to constraint the kinds of\n traces that are allowed by the process. This typing discipline uses *local\n types* from Multiparty Session Types to categorise processes according to the\n set of traces that they accept. For this tutorial, we simplified the local\n types so they do not accept choices. **)\n\n(** The typing system relates [proc] with [lty] so [proc] can only take a\ncommunication type, if the specification allows it: **)\n\nSection Processes.\n  Context (E : Type -> Type).\n\n  Notation CAN_SEND p T kL L := (b_run L = @p_act lprefix (mk_lprefix a_send p) T kL).\n  Notation CAN_RECV p T kL L := (b_run L = @p_act lprefix (mk_lprefix a_recv p) T kL).\n\n  Notation IS_SEND := (@erefl _ (@p_act _ (mk_lprefix a_send _) _ _)).\n  Notation IS_RECV := (@erefl _ (@p_act _ (mk_lprefix a_recv _) _ _)).\n\n  Inductive msg L : forall T, (T -> LocalType) -> Type :=\n  | Send p A  (x : A) kL (H : CAN_SEND p A kL L) : @msg L unit (fun=> kL x)\n  | Recv p A          kL (H : CAN_RECV p A kL L) : @msg L A    kL\n  (* Silent action *)\n  | Eff T (e : E T) : @msg L T (fun=> L)\n  .\n\n  Notation CAN_END L := (b_run L = p_end _).\n  Notation IS_END := (@erefl _ (p_end _)).\n\n  Inductive procF (X : LocalType -> Type) (L : LocalType) :=\n  | Inact (_ : CAN_END L)\n  | Tau (k : X L)\n  | Do {T kL} (e : @msg L T kL) (k : forall x, X (kL x))\n  .\nEnd Processes.\n\nNotation CAN_SEND p T kL L := (b_run L = @p_act lprefix (mk_lprefix a_send p) T kL).\nNotation CAN_RECV p T kL L := (b_run L = @p_act lprefix (mk_lprefix a_recv p) T kL).\n\nNotation IS_SEND := (@erefl _ (@p_act _ (mk_lprefix a_send _) _ _)).\nNotation IS_RECV := (@erefl _ (@p_act _ (mk_lprefix a_recv _) _ _)).\n\nNotation CAN_END L := (b_run L = p_end _).\nNotation IS_END := (@erefl _ (p_end _)).\n\nCoInductive proc E L := mk_proc { observe : @procF E (proc E) L }.\nDefinition iproc E L := procF E (proc E) L.\n\nArguments mk_proc & [E L] observe.\nArguments Send & {E L} p {A} x {kL} H.\nArguments Recv & {E L} p {A kL} H.\nArguments Eff & {E L T} e.\nArguments Inact & {E X L}.\nArguments Tau & {E X L } k.\nArguments Do & {E X L T kL} e k.\n\n(** This defines processes ([proc]) with _shallow_ embeddings of binders.\nParticularly, this uses regular Coq binders and functions for expressions, and\nrequires building greatest fixpoints for recursion. *)\n\nCoercion mkProc E L (x : iproc E L) := mk_proc x.\n\nDefinition pInact E L (H : CAN_END L) : proc E L := mk_proc (Inact H).\nDefinition pTau E L (k : proc E L) : proc E L := mk_proc (Tau k).\nDefinition pDo E L T kL (e : @msg E L T kL) k : proc E L := mk_proc (Do e k).\nDefinition pSend E L p T x kL (H : CAN_SEND p T kL L) k : proc E L := pDo (Send p x H) k.\nDefinition pRecv E L p T kL (H : CAN_RECV p T kL L) k : proc E L := pDo (Recv p H) k.\nArguments pInact & {E L}.\nArguments pTau & {E L} k.\nArguments pDo & {E L T kL} e k.\nArguments pSend & {E L} p {T} x {kL} H k.\nArguments pRecv & {E L} p T {kL} H k.\n\nDeclare Scope proc_scope.\nNotation stop := (pInact erefl).\nNotation \"'call' K\" := (pTau K) (at level 60, no associativity).\nNotation \"p '<~' x ';;' k\" :=\n  (pSend p x IS_SEND (fun=> k))\n    (at level 60, right associativity) : proc_scope.\nNotation \"x ':' T '::=' '<~' p ';;' k\" :=\n  (pRecv p T IS_RECV (fun x => k))\n    (at level 60, right associativity) : proc_scope.\nNotation \"x ':' T '::=' 'lift' e ';;' k\" :=\n  (pDo (Eff e) (fun (x : T) => k))\n    (at level 60, right associativity) : proc_scope.\n\nSection ProcExamples.\n  Context (E : Type -> Type).\n  Notation process := (proc E).\n  Eval compute in b_unroll (b_rec (b_var 1)).\n  Example ended_proc : process (b_rec b_end) := stop.\n\n  (* begin hide *)\n  (* Definition Alice := 0%int63. *)\n  (* Definition Bob := 1%int63. *)\n  (* end hide *)\n\n  (* begin details: here we define the specifications that ALICE and BOB\n  must satisfy *)\n  Definition NRAlice := project GTYExamples.PP GTYExamples.Alice.\n  Definition NRBob := project GTYExamples.PP GTYExamples.Bob.\n\n  Open Scope proc_scope.\n  Example ping_Alice : process NRAlice\n    := GTYExamples.Bob <~ 0;;\n       _ : bool ::= <~ GTYExamples.Bob;;\n       stop.\n\n  Example ping_Bob : process NRBob :=\n    n : nat ::= <~ GTYExamples.Alice ;;\n    GTYExamples.Alice <~ true ;;\n    stop.\n\n  (* Example NRAlice : lty := *)\n  (*   _ <- Bob !! nat ;; *)\n  (*   _ <- Bob ?? nat ;; *)\n  (*   END. *)\n\n  (* Example NRBob : lty := *)\n  (*   _ <- Alice ?? nat ;; *)\n  (*   _ <- Alice !! nat ;; *)\n  (*   END. *)\n\n  (* Example AliceSpec : lty := *)\n  (*   cofix X := *)\n  (*     _ <- Bob !! nat ;; *)\n  (*     _ <- Bob ?? nat ;; *)\n  (*     X. *)\n\n  (* Example BobSpec : lty := *)\n  (*   cofix X := *)\n  (*     _ <- Alice ?? nat ;; *)\n  (*     _ <- Alice !! nat ;; *)\n  (*     X. *)\n  (* Close Scope lty_scope. *)\n\n  Example infinite_ping_Alice : nat -> process AliceSpec :=\n    cofix pingpong x :=\n      Bob <~ x;;\n      _ : nat ::= <~ Bob;;\n      pingpong x.+1.\n\n  Example infinite_ping_Bob : process BobSpec :=\n    cofix pingpong :=\n      n : nat ::= <~ Alice;;\n      Alice <~ n;;\n      pingpong.\n\n  Example infinite_ping_Bob0 : process BobSpec :=\n    n : nat ::= <~ Alice;;\n    cofix pingpong :=\n      Alice <~ n;;\n      n : nat ::= <~ Alice;;\n      pingpong.\n  Close Scope proc_scope.\nEnd ProcExamples.\n\n(** ** Semantics of Smol Zooid *)\n\n(** *** Actions **)\n\n(** Actions capture the kind of event that happened (send/receive), and the\nnecessary information about who performed the action, the other party, and the\npayload type. **)\n\n\nRecord event :=\n  mk_ev { action_type : action;\n          from : participant;\n          to : participant;\n          payload_type : Type;\n        }.\nInductive rt_event :=\n  Obs { event_type : event;\n        payload : payload_type event_type\n      }.\nDefinition mk_obs a p q T x := Obs (mk_ev a p q T) x.\n\n\n(** *** Traces **)\n(** Traces are (potentially infinite) streams of events. They are parameterised\n by the type of events. **)\n\nInductive traceF act G :=\n| tr_end : traceF act G\n| tr_next : act -> G -> traceF act G.\n(* begin hide *)\nArguments tr_next & {act G}.\nArguments tr_end & {act G}.\n(* end hide *)\n\nCoInductive trace act := roll { unroll : traceF act (trace act) }.\n\nDefinition ty_trace := trace event.\nDefinition rt_trace := trace rt_event.\n\n(* begin details:  *)\n\nDefinition trace_mapF {A B : Type} (f : A -> B) X Y G (trc : traceF A X)\n  : traceF B Y :=\n  match trc with\n  | tr_end => tr_end\n  | tr_next a trc => tr_next (f a) (G trc)\n  end.\nCoFixpoint trace_map {A B : Type} (f : A -> B) (trc : trace A) : trace B :=\n  roll (trace_mapF f (trace_map f) (unroll trc)).\n\nDefinition erase := trace_map event_type.\n(* end details *)\n\n\n\n(** *** Labelled State Transition System **)\n\n(** We define the steps as functions that take a process, an action, and\nattepmpts to run it, returning the continuation. Since we only care about\ncommunication, we define a function that exposes the firsst communication\naction: [p_unroll]. This function requires two parameters, [readIO : forall T :\ntype, unit -> interp_type T] and [writeIO : forall T, T -> unit]. We will use\nthese functions later for code extraction. **)\n\nSection ProcLTS.\n  (** begin details: **)\n  Variable (E : Type -> Type)\n           (run_eff : forall T, E T -> T).\n  (** end details **)\n\n  Inductive proc_step (p : participant) L :\n    iproc E L -> option rt_event -> forall L', proc E L' -> Prop\n    :=\n    (* Observable actions *)\n    | step_send q T (x : T) kL (WT : CAN_SEND q T kL L) k :\n        proc_step p (Do (Send q x WT) k) (Some (mk_obs a_send p q x)) (k tt)\n    | step_recv q T (x : T) kL (WT : CAN_RECV q T kL L) k :\n        proc_step p (Do (Recv q WT  ) k) (Some (mk_obs a_recv q p x)) (k x )\n\n    (* Silent actions *)\n    | step_eff T a k : proc_step p (Do (Eff a) k) None (k (@run_eff T a))\n    | step_unroll e0 : proc_step p (Tau e0)       None e0\n  .\n\n  Derive Inversion proc_step_inv\n    with (forall p L0 e0 ev L1 e1, @proc_step p L0 e0 ev L1 e1)\n         Sort Prop.\n\n  Definition R_trace := rt_trace -> forall L, proc E L -> Prop.\n  Inductive proc_lts_ (p : participant) (G : R_trace) : R_trace :=\n  | p_end TRC e H :\n      unroll TRC = tr_end ->\n      observe e = Inact H ->\n      @proc_lts_ p G TRC END e\n  | p_skip TRC L0 e0 L1 e1 :\n      @proc_step p L0 (observe e0) None L1 e1 ->\n      @proc_lts_ p G TRC L1 e1 ->\n      @proc_lts_ p G TRC L0 e0\n  | p_next E TRC0 TRC1 L0 e0 L1 e1 :\n      unroll TRC0 = tr_next E TRC1 ->\n      @proc_step p L0 (observe e0) (Some E) L1 e1 ->\n      G TRC1 L1 e1 ->\n      @proc_lts_ p G TRC0 L0 e0\n  .\n  Arguments p_end {p G}.\n  Arguments p_skip [p G TRC L0 e0 L1 e1].\n  Arguments p_next [p G E TRC0 TRC1 L0 e0 L1 e1].\n  Derive Inversion proc_lts_inv\n    with (forall p G TRC L e, @proc_lts_ p G TRC L e) Sort Prop.\n\n  Lemma proc_lts_monotone p : monotone3 (proc_lts_ p).\n  (* begin details: [proc_lts_] is monotone *)\n  Proof.\n    move=> TRC L e R R'.\n    elim=>\n    [ {}TRC {}e EQ H0 H1 _\n    | {}TRC L0 e0 L1 e1 STEP H IH F\n    | ev TRC0 TRC1 L0 e0 L1 e1 EQ STEP H F].\n    - by apply/p_end.\n    - by apply/(p_skip STEP)/IH.\n    - by apply/(p_next EQ STEP)/F.\n  Qed.\n  (* end details *)\n\n  (** [proc_accepts] encodes the property of a process accepting a trace, and it\n is the greatest fixpoint of [proc_lts_]. **)\n\n  Definition proc_accepts p TR L P := paco3 (proc_lts_ p) bot3 TR L P.\n\n  (** ** Preservation **)\n\n  (** We want to make sure that types indeed characterise the traces according to\nthe allowed traces. We build a semantics for local types, and prove that, given\n[p : SZooid L], if [p] transitions to [p'] with some event [E], then [L] also\ntransitions to [L'] with the \"same\" event. But, since processes contain payloads\nand local types do not, we must first erase these payloads from the trace\nevents. **)\n\n  Inductive lty_step p : ltyF lty -> event -> lty -> Prop :=\n  | lt_send q T x kL :\n      lty_step p (l_send q T kL) (mk_ev a_send p q T) (kL x)\n  | lt_recv q T x kL :\n      lty_step p (l_recv q T kL) (mk_ev a_recv q p T) (kL x)\n  .\n  Derive Inversion lty_step_inv with\n      (forall p L0 Ev L1, @lty_step p L0 Ev L1) Sort Prop.\n\n  Inductive lty_lts_ (p : participant) (G : ty_trace -> lty -> Prop)\n    : ty_trace -> lty -> Prop :=\n  | ty_end TRC L :\n      run_lty L = l_end ->\n      unroll TRC = tr_end -> @lty_lts_ p G TRC L\n  | ty_next E TRC0 TRC1 L0 L1 :\n      unroll TRC0 = tr_next E TRC1 ->\n      @lty_step p (run_lty L0) E L1 -> G TRC1 L1 -> @lty_lts_ p G TRC0 L0\n  .\n  Derive Inversion lty_lts_inv with\n      (forall p G TRC L, @lty_lts_ p G TRC L) Sort Prop.\n  Definition lty_accepts p := paco2 (lty_lts_ p) bot2.\n\n  Lemma lty_lts_monotone p : monotone2 (lty_lts_ p).\n  Proof.\n    move=>TRC L r r' H0 H1;  case: H0.\n    - by move=> TRC0 U0; constructor.\n    - by move=> E0 TRC0 TRC1 L0 L1 U0 ST /H1; apply (ty_next _ _ _ U0).\n  Qed.\n\n  Lemma subject_reduction p L0 (e0 : iproc E L0) L1 (e1 : proc E L1) ev :\n    proc_step p e0 (Some ev) e1 -> lty_step p (run_lty L0) (event_type ev) L1.\n  Proof.\n    (* Generalize [Some ev] and remember that [EQ : mev = Some ev] in [St] *)\n    move EQ: (Some ev)=> mev St.\n\n    (* By case analysis on the process step *)\n    by case: St EQ=>//= q T x kL -> _ [->]; constructor.\n  Qed.\n\n  Lemma step_silent p L0 (e0 : iproc E L0) L1 (e1 : proc E L1) :\n    proc_step p e0 None e1 -> L0 = L1.\n  Proof. by case EQ: _ _ _ /.  Qed.\n\n  Theorem trace_soundness p RT_TRC L (e : proc E L) :\n    proc_accepts p RT_TRC         e ->\n    @lty_accepts p (erase RT_TRC) L.\n  Proof.\n    (* By (parametric) coinduction (i.e. paco2_acc) *)\n    coind CH=> L RT_TRC e Acc.\n\n    (* unfold proc_accepts proc_accepts = \\mu proc_lts_ ==> proc_lts_ (\\mu proc_lts) *)\n    move: Acc => /(paco3_unfold (@proc_lts_monotone p))-Acc.\n\n    (* generalize Acc *)\n    move EQ: (upaco3 _ _) Acc=> RR.\n\n    (* by induction on Acc *)\n    elim=>/=\n        [ TRC0 e0 H0 U0 Oe\n        | TRC L0 e0 L1 e1 STEP _ IH\n        | E0 T0 T1 L0 e0 L1 e1 U0 St Acc {e}\n        ].\n    { (* Case: process trace is ended *)\n\n      (* apply G f -> f (G f), followed by the empty trace constructor *)\n      apply/paco2_fold; constructor=>//.\n\n      (* reduce [unroll (erase TRC0)], and rewrite [unroll TRC0 = tr_end] *)\n      by cbv; rewrite U0.\n    }\n    { (* Case: the process takes a silent step *)\n\n      (* Straightforward application of the IH, since\n         a silent step does not progress the local type *)\n      by move: STEP=>/step_silent->.\n    }\n    { (* Case: process trace contains one element *)\n\n      (* By applying the constructor for the step trace, we\n       then need to prove 3 properties: *)\n      apply/paco2_fold/ty_next.\n\n      { (* Property 1: the erasure of the runtime trace contains 1 element *)\n\n        (* Straightforward: if the trace contains one element, so does the erasure *)\n        by cbv; rewrite U0 -/(trace_map _ _) -/(erase _).\n      }\n      { (* Property 2: the local type of [e0] steps to some continuation local type *)\n\n        (* Straightforward by subject reduction *)\n        by apply: (subject_reduction St).\n\n      }\n      { (* Property 3: the continuation of the local type accepts the remainder\n           of the erasure of the trace *)\n\n        (* Straightforward by applying the coinduction hypothesis *)\n\n        (* First rewrite [Acc] so it states that [e1] accepts the remainder of\n           the trace [T1]*)\n        move: EQ Acc=><-[Acc|//] {RR}.\n\n        (* Then apply the coinduction hypothesis to [Acc] *)\n        by right; apply/CH/Acc.\n      }\n    }\n    Qed.\nEnd ProcLTS.\n\n(** ** Extraction **)\n\n(** The main goal of defining a simple process language, with a mixture of deep\nand shallow embedded binders is to simplify *certified code extraction*. To\nextract [proc], we need an interpretation of its constructs. We do this in a way\nthat somewhat resembles that of _effect handlers_, by assigning to each\nconstruct an **interpretation** as an OCaml function. **)\n\nRequire Extraction ExtrOCamlInt63.\nExtraction Implicit Send [ L kL ].\nExtraction Implicit Recv [ L kL ].\nExtraction Implicit Eff [ L ].\nExtraction Implicit Do [ L kL ].\nExtraction Implicit Tau [ L ].\nExtraction Implicit Inact [ L ].\n\nExtraction Implicit pSend [ L kL ].\nExtraction Implicit pRecv [ L kL ].\nExtraction Implicit pDo [ L kL ].\nExtraction Implicit pTau [ L ].\nExtraction Implicit pInact [ L ].\n\nModule ProcExtraction.\n  Extract Inductive proc => \"Proc.t\" [ \"\" ].\n  Extract Inlined Constant pSend => \"(fun p t k -> let* _ = Proc.send p (Obj.magic t) in (Obj.magic k tt))\".\n  Extract Inlined Constant pRecv => \"(fun p k -> let* x = Proc.recv p in (Obj.magic k))\".\nEnd ProcExtraction.\n\nSection GTYExamples.\n  Context (E : Type -> Type).\n  Notation process G r := (proc E (unravel (project G r))).\n\n  Example ended_proc : process END Alice := stop.\n\n  Open Scope proc_scope.\n\n  Definition proc_rec A E L (f : A -> proc E L) : A -> proc E L := f.\n  Arguments proc_rec & {A E L} f.\n\n  Set Contextual Implicit.\n\n  Example ch_Bob0 : process CH1 Bob :=\n    n : MyChoice ::= <~ Alice;;\n    match n with\n    | Case1 c =>\n      proc_rec\n        (cofix pingpong c :=\n         Alice <~ Nat.even c;;\n         n : MyChoice ::= <~ Alice;;\n         match n with\n         | Case1 c =>\n           pingpong c\n         | Case2 _ => stop\n         end) c\n    | Case2 _ =>\n      stop\n    end.\n  Example ping_Bob : process PP Bob :=\n      _ : nat ::= <~ Alice;;\n    Alice <~ true;;\n    stop.\n  Example ping_Alice n : process PP Alice :=\n    Bob <~ n ;;\n    n : bool ::= <~ Bob ;;\n    stop.\n\n  Example infinite_ping_Alice : nat -> process PPRec Alice :=\n    cofix pingpong x :=\n      Bob <~ x;;\n      _ : bool ::= <~ Bob;;\n      pingpong x.+1.\n\n  Example infinite_ping_Bob : process PPRec Bob :=\n    cofix pingpong :=\n      n : nat ::= <~ Alice;;\n      Alice <~ Nat.even n ;;\n      pingpong.\n\n  Example infinite_ping_Bob0 : process PPRec Bob :=\n    n : nat ::= <~ Alice;;\n    cofix pingpong :=\n      Alice <~ Nat.even n;;\n      n : nat ::= <~ Alice;;\n      pingpong.\n  Close Scope proc_scope.\nEnd GTYExamples.\n", "meta": {"author": "dcastrop", "repo": "behavioural-trees", "sha": "d05aa753e3637cae0424aac3801e49b6d3bfc575", "save_path": "github-repos/coq/dcastrop-behavioural-trees", "path": "github-repos/coq/dcastrop-behavioural-trees/behavioural-trees-d05aa753e3637cae0424aac3801e49b6d3bfc575/theories/Zooid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331606115021, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.27960227510373714}}
{"text": "(*===========================================================================\n    Processor state: registers, flags and memory\n  ===========================================================================*)\nRequire Import Ssreflect.ssreflect Ssreflect.ssrfun Ssreflect.ssrbool Ssreflect.ssrnat Ssreflect.finfun Ssreflect.fintype Ssreflect.eqtype Ssreflect.tuple.\nRequire Export x86proved.update x86proved.x86.reg x86proved.x86.regstate x86proved.x86.flags x86proved.x86.mem x86proved.bitsrep.\nRequire Import x86proved.bitsops.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLocal Open Scope update_scope.\n\n(* Processor state consists of a register file, flags and memory *)\n(*=ProcState *)\nRecord ProcState := mkProcState\n{ registers:> RegState; flags:> FlagState; memory:> Mem }.\n(*=End *)\nRequire Import Coq.Strings.String.\nDefinition procStateToString s :=\n  (let: mkProcState rs fs ms := s in\n  regStateToString rs ++ \" EFL=\" ++ flagsToString fs ++ \" \" ++ memToString ms)%string.\n\n(* Functional update notation, for registers and memory *)\nGlobal Instance ProcStateUpdateOps : UpdateOps ProcState AnyReg DWORD :=\n  fun s r v => mkProcState (registers s !r:=v) (flags s) (memory s).\n\nGlobal Instance ProcStateUpdateFlagOpsBool : UpdateOps ProcState Flag bool :=\n  fun s f v => mkProcState (registers s) (flags s!f:=mkFlag v) (memory s).\n\nGlobal Instance ProcStateUpdateFlagOps : UpdateOps ProcState Flag FlagVal :=\n  fun s f v => mkProcState (registers s) (flags s!f:=v) (memory s).\n\nGlobal Instance ProcStateUpdate : Update ProcState AnyReg DWORD.\napply Build_Update.\nmove => m k v w. rewrite /update /ProcStateUpdateOps. by rewrite update_same.\nmove => m k l v w kl. rewrite /update /ProcStateUpdateOps. by rewrite update_diff.\nQed.\n\nGlobal Instance ProcStateUpdateOpsBYTE : UpdateOps ProcState PTR BYTE :=\n  fun s p v => mkProcState (registers s) (flags s) ((memory s) !p:=v).\n\nGlobal Instance ProcStateUpdateOpsDWORD : UpdateOps ProcState PTR DWORD :=\n  fun s p v =>\n  let '(b3,b2,b1,b0) := DWORDToBytes v in\n  let ms := memory s in\n  mkProcState (registers s) (flags s)\n    (ms !p:=b0 !incB p:=b1 !incB(incB p):=b2 !incB(incB(incB p)):=b3).\n\nDefinition toSlice (b: BITS 2) := toNat b * 8. \n  \n(* @TODO: update lemmas *)\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/procstate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2796022751037371}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect.\nRequire Import ssrbool.\nRequire Import ssrnat.\nRequire Import part.\nRequire Import znat.\nRequire Import hubcap.\nRequire Import present.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLemma exclude7 : reducibility -> excluded_arity 7.\nProof.\nmove=> Hrec; Presentation.\nPcase L0_1: s[1] <= 5.\n  Pcase L1_1: s[2] <= 5.\n    Pcase L2_1: s[3] <= 5.\n      Pcase: s[4] <= 5.\n        Reducible.\n      Pcase: s[7] <= 5.\n        Reducible.\n      Pcase L3_1: s[4] > 6.\n        Pcase: s[7] > 6.\n          Pcase: h[6] <= 5.\n            Pcase L6_1: s[5] > 7.\n              Pcase: s[4] > 7.\n                Hubcap T[2]<=5 T[4]<=(-2) T[5]<=0 T[1,3]<=7 T[6,7]<=0 [].\n              Pcase: s[6] > 5.\n                Hubcap T[1]<=4 T[2]<=5 T[5]<=0 T[6]<=0 T[7]<=(-1) T[3,4]<=2 [].\n              Hubcap T[1]<=4 T[2]<=5 T[5]<=0 T[6]<=2 T[7]<=(-3) T[3,4]<=2 [].\n            Pcase: s[6] > 7.\n              Similar to *L6_1[4].\n            Pcase L6_2: s[4] > 7.\n              Pcase L7_1: s[4] > 8.\n                Pcase L8_1: s[5] > 5.\n                  Pcase: s[5] <= 6.\n                    Hubcap T[2]<=5 T[4]<=(-2) T[5]<=0 T[6]<=1 T[7]<=(-1)\n                           T[1,3]<=7 [].\n                  Pcase: s[6] > 5.\n                    Hubcap T[2]<=5 T[4]<=(-2) T[5]<=1 T[6]<=0 T[7]<=(-1)\n                           T[1,3]<=7 [].\n                  Hubcap T[2]<=5 T[4]<=(-3) T[5]<=2 T[6]<=2 T[7]<=(-3) T[1,3]<=7\n                         [].\n                Pcase: s[6] <= 6.\n                  Reducible.\n                Pcase: s[7] > 8.\n                  Similar to *L8_1[4].\n                Hubcap T[2]<=5 T[4]<=(-3) T[5]<=2 T[1,3]<=7 T[6,7]<=(-1) [].\n              Pcase: s[7] > 8.\n                Similar to *L7_1[4].\n              Pcase L7_2: s[5] > 5.\n                Pcase: s[5] <= 6.\n                  Hubcap T[2]<=5 T[4]<=(-2) T[5]<=0 T[6]<=1 T[7]<=(-1) T[1,3]<=7\n                         [].\n                Pcase: s[6] > 5.\n                  Hubcap T[2]<=5 T[4]<=(-2) T[5]<=1 T[6]<=0 T[7]<=(-1) T[1,3]<=7\n                         [].\n                Hubcap T[2]<=5 T[4]<=(-3) T[5]<=2 T[6]<=2 T[7]<=(-3) T[1,3]<=7 [].\n              Pcase: s[6] <= 6.\n                Reducible.\n              Pcase: s[7] > 7.\n                Similar to *L7_2[4].\n              Pcase: h[7] <= 5.\n                Reducible.\n              Hubcap T[2]<=5 T[4]<=(-3) T[5]<=2 T[1,3]<=7 T[6,7]<=(-1) [].\n            Pcase: s[7] > 7.\n              Similar to *L6_2[4].\n            Pcase: h[5] <= 5.\n              Hubcap T[1]<=4 T[2]<=5 T[5]<=0 T[6]<=0 T[7]<=(-1) T[3,4]<=2 [].\n            Pcase: h[7] <= 5.\n              Hubcap T[1]<=4 T[2]<=5 T[5]<=0 T[6]<=0 T[7]<=(-1) T[3,4]<=2 [].\n            Pcase L6_3: s[5] > 5.\n              Pcase: s[5] <= 6.\n                Hubcap T[2]<=5 T[5]<=0 T[6]<=1 T[1,7]<=2 T[3,4]<=2 [].\n              Pcase: s[6] > 5.\n                Hubcap T[2]<=5 T[5]<=1 T[6]<=0 T[1,7]<=2 T[3,4]<=2 [].\n              Hubcap T[2]<=5 T[6]<=2 T[7]<=(-3) T[1,3]<=7 T[4,5]<=(-1) [].\n            Pcase: s[6] > 5.\n              Similar to *L6_3[4].\n            Reducible.\n          Pcase L5_1: s[5] > 7.\n            Pcase: s[4] > 7.\n              Hubcap T[2]<=5 T[4]<=(-2) T[5]<=0 T[1,3]<=7 T[6,7]<=0 [].\n            Pcase: s[6] > 5.\n              Hubcap T[1]<=4 T[2]<=5 T[5]<=0 T[6]<=0 T[7]<=(-1) T[3,4]<=2 [].\n            Hubcap T[1]<=4 T[2]<=5 T[5]<=0 T[6]<=2 T[7]<=(-3) T[3,4]<=2 [].\n          Pcase: s[6] > 7.\n            Similar to *L5_1[4].\n          Pcase L5_2: s[5] > 5.\n            Pcase: s[6] > 6.\n              Hubcap T[2]<=5 T[5]<=0 T[6]<=1 T[1,7]<=2 T[3,4]<=2 [].\n            Pcase: s[6] > 5.\n              Pcase: s[5] > 6.\n                Hubcap T[2]<=5 T[5]<=1 T[6]<=0 T[1,7]<=2 T[3,4]<=2 [].\n              Pcase: h[6] > 6.\n                Hubcap T[1]<=4 T[2]<=5 T[5]<=0 T[6]<=0 T[7]<=(-1) T[3,4]<=2 [].\n              Pcase: f1[5] > 6.\n                Hubcap T[2]<=5 T[6]<=0 T[1,3]<=7 T[1,7]<=2 T[3,4]<=2 T[4,5]<=0\n                       T[5,7]<=0 [].\n              Pcase: f1[5] <= 5.\n                Hubcap T[2]<=5 T[5]<=0 T[7]<=(-2) T[1,3]<=7 T[4,6]<=0 [].\n              Pcase: s[4] <= 7.\n                Hubcap T[2]<=5 T[6]<=0 T[1,3]<=7 T[1,7]<=2 T[3,4]<=2 T[4,5]<=0\n                       T[5,7]<=0 [].\n              Pcase: s[7] > 7.\n                Hubcap T[2]<=5 T[4]<=(-2) T[7]<=(-2) T[1,3]<=7 T[5,6]<=2 [].\n              Hubcap T[2]<=5 T[4]<=(-2) T[7]<=(-1) T[1,3]<=7 T[5,6]<=1 [].\n            Pcase: s[5] <= 6.\n              Hubcap T[2]<=5 T[4]<=(-3) T[5]<=2 T[6]<=2 T[7]<=(-3) T[1,3]<=7 [].\n            Pcase: s[4] > 7.\n              Hubcap T[2]<=5 T[4]<=(-2) T[5]<=1 T[6]<=2 T[7]<=(-3) T[1,3]<=7 [].\n            Pcase: h[2] > 5.\n              Hubcap T[1]<=3 T[2]<=5 T[5]<=1 T[6]<=2 T[7]<=(-3) T[3,4]<=2 [].\n            Pcase: h[3] <= 6.\n              Reducible.\n            Pcase: h[1] <= 5.\n              Reducible.\n            Pcase: h[4] > 5.\n              Hubcap T[1]<=4 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=1 T[6]<=2\n                     T[7]<=(-3) [].\n            Hubcap T[1]<=4 T[2]<=5 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=2 T[7]<=(-3)\n                   [].\n          Pcase: s[6] > 5.\n            Similar to *L5_2[4].\n          Hubcap T[2]<=5 T[4]<=(-4) T[5]<=3 T[6]<=3 T[7]<=(-4) T[1,3]<=7 [].\n        Pcase: s[6] <= 5.\n          Reducible.\n        Pcase: h[1] <= 5.\n          Reducible.\n        Pcase: s[5] <= 5.\n          Pcase: s[6] <= 6.\n            Reducible.\n          Hubcap T[4]<=(-3) T[5]<=2 T[6]<=(-2) T[1,3]<=7 T[2,7]<=6 [].\n        Pcase: s[6] > 7.\n          Hubcap T[1]<=4 T[5]<=0 T[6]<=(-2) T[2,7]<=6 T[3,4]<=2 [].\n        Pcase: h[3] <= 5.\n          Pcase: h[2] <= 6.\n            Reducible.\n          Pcase: h[4] <= 5.\n            Reducible.\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=3 T[2]<=5 T[3]<=4 T[4]<=(-2) T[5]<=0 T[6]<=(-1) T[7]<=1\n                   [].\n          Pcase: h[7] <= 5.\n            Reducible.\n          Pcase: s[5] > 7.\n            Hubcap T[1]<=3 T[2]<=5 T[3]<=4 T[4]<=(-2) T[5]<=(-1) T[6]<=0 T[7]<=1\n                   [].\n          Pcase: s[5] <= 6.\n            Hubcap T[1]<=3 T[2]<=5 T[3]<=4 T[4]<=(-3) T[5]<=0 T[6]<=0 T[7]<=1 [].\n          Pcase: h[6] > 5.\n            Hubcap T[1]<=3 T[2]<=5 T[3]<=4 T[4]<=(-2) T[5]<=(-1) T[6]<=0 T[7]<=1\n                   [].\n          Hubcap T[1]<=3 T[2]<=5 T[3]<=4 T[4]<=(-2) T[5]<=(-1) T[6]<=0 T[7]<=1\n                 [].\n        Pcase: h[3] <= 6.\n          Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=(-2) T[7]<=1 T[5,6]<=1 [].\n        Pcase: h[1] <= 6.\n          Pcase: h[2] <= 5.\n            Reducible.\n          Pcase: f1[7] <= 5.\n            Reducible.\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=(-1) T[7]<=2\n                   [].\n          Pcase: h[7] <= 5.\n            Reducible.\n          Pcase: s[5] > 7.\n            Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=(-1) T[5]<=(-1) T[6]<=0 T[7]<=2\n                   [].\n          Pcase: s[5] <= 6.\n            Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=(-3) T[5]<=0 T[6]<=0 T[7]<=2 [].\n          Pcase: s[4] > 7.\n            Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=(-2) T[5]<=0 T[6]<=0 T[7]<=2 [].\n          Pcase: h[2] > 6.\n            Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=0 T[7]<=1 [].\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=(-2) T[5]<=0 T[6]<=0 T[7]<=2 [].\n          Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=(-2) T[5]<=0 T[6]<=0 T[7]<=2 [].\n        Pcase: s[6] > 6.\n          Pcase: s[4] > 7.\n            Hubcap T[1]<=4 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=0 T[6]<=(-1) T[7]<=1\n                   [].\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=(-1) T[7]<=1\n                   [].\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=4 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=0 T[6]<=(-1) T[7]<=1\n                   [].\n          Pcase: f1[4] <= 5.\n            Reducible.\n          Pcase: h[7] > 5.\n            Hubcap T[1]<=4 T[2]<=5 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=(-2) T[7]<=1\n                   [].\n          Hubcap T[1]<=4 T[2]<=5 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=(-2) T[7]<=1\n                 [].\n        Pcase: h[7] <= 5.\n          Reducible.\n        Pcase: s[5] <= 6.\n          Hubcap T[1]<=4 T[2]<=5 T[3]<=3 T[4]<=(-3) T[5]<=0 T[6]<=0 T[7]<=1 [].\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=0 T[7]<=1 [].\n        Pcase: h[5] <= 5.\n          Pcase: s[4] > 7.\n            Pcase: s[5] > 7.\n              Hubcap T[1]<=4 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=(-1) T[6]<=0\n                     T[7]<=1 [].\n            Pcase: h[6] > 5.\n              Hubcap T[1]<=4 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=(-1) T[6]<=0\n                     T[7]<=1 [].\n            Hubcap T[1]<=4 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=(-1) T[6]<=0 T[7]<=1\n                   [].\n          Pcase: s[5] <= 7.\n            Hubcap T[1]<=4 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=(-1) T[6]<=0 T[7]<=1\n                   [].\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=4 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=(-1) T[6]<=0 T[7]<=1\n                   [].\n          Hubcap T[1]<=4 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=(-1) T[6]<=0 T[7]<=1\n                 [].\n        Pcase: s[4] > 7.\n          Pcase: s[5] > 7.\n            Hubcap T[1]<=4 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=(-1) T[6]<=0 T[7]<=1\n                   [].\n          Pcase: h[6] > 5.\n            Hubcap T[1]<=4 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=(-1) T[6]<=0 T[7]<=1\n                   [].\n          Hubcap T[1]<=4 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=(-1) T[6]<=0 T[7]<=1\n                 [].\n        Pcase: h[4] > 5.\n          Pcase: s[5] > 7.\n            Hubcap T[1]<=4 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=(-1) T[6]<=0 T[7]<=1\n                   [].\n          Pcase: h[6] > 5.\n            Hubcap T[1]<=4 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=(-1) T[6]<=0 T[7]<=1\n                   [].\n          Hubcap T[1]<=4 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=(-1) T[6]<=0 T[7]<=1\n                 [].\n        Pcase: f1[4] <= 5.\n          Reducible.\n        Pcase: s[5] > 7.\n          Hubcap T[1]<=4 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=(-1) T[6]<=0 T[7]<=1\n                 [].\n        Pcase: h[6] > 5.\n          Hubcap T[1]<=4 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=(-1) T[6]<=0 T[7]<=1\n                 [].\n        Hubcap T[1]<=4 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=(-1) T[6]<=0 T[7]<=1 [].\n      Pcase: s[7] > 6.\n        Similar to *L3_1[4].\n      Pcase: s[5] <= 5.\n        Reducible.\n      Pcase: s[6] <= 5.\n        Reducible.\n      Pcase: h[4] <= 5.\n        Reducible.\n      Pcase: h[1] <= 5.\n        Reducible.\n      Pcase L3_2: s[5] > 6.\n        Pcase: s[6] <= 6.\n          Hubcap T[5]<=(-4) T[6]<=0 T[1,3]<=7 T[2,4]<=6 T[2,7]<=6 T[4,7]<=3 [].\n        Pcase L4_1: s[5] > 7.\n          Pcase: s[6] > 7.\n            Hubcap T[5]<=(-2) T[6]<=(-2) T[1,3]<=7 T[2,4]<=6 T[2,7]<=6 T[4,7]<=3\n                   [].\n          Pcase: h[7] > 5.\n            Hubcap T[5]<=(-2) T[6]<=(-2) T[1,3]<=7 T[2,4]<=6 T[2,7]<=6 T[4,7]<=3\n                   [].\n          Hubcap T[5]<=(-2) T[6]<=(-2) T[1,3]<=7 T[2,4]<=6 T[2,7]<=6 T[4,7]<=3\n                 [].\n        Pcase: s[6] > 7.\n          Similar to *L4_1[4].\n        Pcase L4_2: h[5] > 5.\n          Pcase: h[7] > 5.\n            Hubcap T[5]<=(-2) T[6]<=(-2) T[1,3]<=7 T[2,4]<=6 T[2,7]<=6 T[4,7]<=3\n                   [].\n          Hubcap T[5]<=(-2) T[6]<=(-2) T[1,3]<=7 T[2,4]<=6 T[2,7]<=6 T[4,7]<=3\n                 [].\n        Pcase: h[7] > 5.\n          Similar to *L4_2[4].\n        Pcase: f1[5] <= 5.\n          Reducible.\n        Pcase: f2[6] <= 5.\n          Reducible.\n        Hubcap T[5]<=(-2) T[6]<=(-2) T[1,3]<=7 T[2,4]<=6 T[2,7]<=6 T[4,7]<=3 [].\n      Pcase: s[6] > 6.\n        Similar to *L3_2[4].\n      Reducible.\n    Pcase: s[7] <= 5.\n      Similar to L2_1[6].\n    Pcase L2_2: s[4] <= 5.\n      Pcase: s[3] <= 6.\n        Reducible.\n      Pcase: s[5] > 5.\n        Pcase: s[7] <= 6.\n          Pcase: s[6] <= 5.\n            Reducible.\n          Pcase: s[6] <= 6.\n            Pcase: s[5] <= 6.\n              Reducible.\n            Pcase: h[7] <= 5.\n              Reducible.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[4]<=2 T[5]<=(-1) T[6]<=0 T[7]<=3\n                   [].\n          Pcase: s[5] > 7.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[4]<=2 T[5]<=0 T[6]<=(-1) T[7]<=3\n                   [].\n          Pcase: s[5] > 6.\n            Pcase: s[6] > 7.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[4]<=2 T[6]<=(-2) T[5,7]<=4 [].\n            Pcase: h[2] > 5.\n              Hubcap T[1]<=4 T[2]<=3 T[3]<=(-2) T[4]<=2 T[5]<=2 T[6]<=(-1)\n                     T[7]<=2 [].\n            Pcase: h[3] <= 5.\n              Reducible.\n            Pcase: h[1] <= 5.\n              Reducible.\n            Pcase: h[5] > 5.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[4]<=2 T[7]<=3 T[5,6]<=(-1) [].\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[4]<=2 T[6]<=(-2) T[5,7]<=4 [].\n          Pcase: s[3] <= 7.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[4]<=3 T[6]<=(-3) T[5,7]<=4 [].\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=4 T[2]<=3 T[3]<=(-2) T[4]<=3 T[5]<=3 T[6]<=(-3) T[7]<=2\n                   [].\n          Pcase: h[3] <= 5.\n            Reducible.\n          Pcase: h[1] <= 5.\n            Reducible.\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[4]<=3 T[6]<=(-3) T[5,7]<=4 [].\n          Pcase: h[5] > 5.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[4]<=2 T[5]<=2 T[6]<=(-3) T[7]<=3\n                   [].\n          Hubcap T[1]<=4 T[2]<=4 T[3]<=(-3) T[4]<=3 T[5]<=3 T[6]<=(-3) T[7]<=1\n                 [].\n        Pcase: s[5] > 8.\n          Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[4]<=2 T[5]<=0 T[6,7]<=2 [].\n        Pcase: s[6] <= 5.\n          Pcase: s[5] > 7.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[4]<=2 T[5]<=2 T[6]<=2 T[7]<=(-2)\n                   [].\n          Pcase: s[5] > 6.\n            Pcase: h[2] > 5.\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=(-2) T[4]<=2 T[5]<=4 T[6]<=2\n                     T[7]<=(-2) [].\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[4]<=2 T[5]<=2 T[6]<=2 T[7]<=(-2)\n                   [].\n          Pcase: h[2] <= 5.\n            Reducible.\n          Pcase: h[5] > 5.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=(-3) T[4]<=2 T[5]<=4 T[6]<=3 T[7]<=(-3)\n                   [].\n          Pcase: f1[5] <= 5.\n            Reducible.\n          Pcase: h[6] > 5.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=(-3) T[4]<=3 T[5]<=4 T[6]<=2 T[7]<=(-3)\n                   [].\n          Pcase: f1[5] <= 6.\n            Reducible.\n          Pcase L5_1: s[3] > 7.\n            Pcase: h[4] <= 5.\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=(-4) T[4]<=3 T[5]<=5 T[6]<=3\n                     T[7]<=(-3) [].\n            Pcase: s[7] <= 7.\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=(-3) T[4]<=3 T[5]<=4 T[6]<=3\n                     T[7]<=(-3) [].\n            Pcase: h[7] > 5.\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=(-3) T[4]<=3 T[5]<=4 T[6]<=3\n                     T[7]<=(-3) [].\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=(-3) T[4]<=3 T[5]<=5 T[6]<=3 T[7]<=(-4)\n                   [].\n          Pcase: s[7] > 7.\n            Similar to *L5_1[5].\n          Pcase: h[3] <= 5.\n            Reducible.\n          Pcase: h[4] <= 6.\n            Reducible.\n          Pcase: h[7] <= 6.\n            Reducible.\n          Pcase: h[1] <= 5.\n            Reducible.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=(-3) T[4]<=3 T[5]<=4 T[6]<=3 T[7]<=(-3)\n                 [].\n        Pcase: s[5] > 7.\n          Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[4]<=2 T[5]<=0 T[6]<=0 T[7]<=2 [].\n        Pcase: h[2] > 5.\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=(-2) T[4]<=2 T[6]<=0 T[5,7]<=4 [].\n          Pcase: s[6] <= 6.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=(-2) T[4]<=3 T[7]<=(-2) T[5,6]<=5 [].\n          Pcase: s[7] > 7.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=(-2) T[4]<=3 T[7]<=(-1) T[5,6]<=4 [].\n          Pcase: s[3] <= 7.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=(-2) T[4]<=3 T[5]<=2 T[6,7]<=1 [].\n          Pcase: h[2] <= 6.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=(-2) T[4,7]<=2 T[5,6]<=4 [].\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=(-2) T[4]<=3 T[5]<=2 T[6,7]<=1 [].\n          Pcase: h[5] > 5.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=(-2) T[4]<=2 T[5]<=2 T[6,7]<=1 [].\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=(-3) T[4]<=3 T[5]<=3 T[6,7]<=1 [].\n        Pcase: h[3] <= 5.\n          Reducible.\n        Pcase: h[1] <= 5.\n          Reducible.\n        Pcase: s[5] > 6.\n          Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[4]<=2 T[6]<=0 T[5,7]<=2 [].\n        Pcase: s[6] <= 6.\n          Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[4]<=3 T[7]<=(-2) T[5,6]<=3 [].\n        Pcase: h[5] > 5.\n          Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[4]<=2 T[5]<=2 T[6,7]<=0 [].\n        Pcase: f1[5] <= 5.\n          Reducible.\n        Pcase: s[6] > 8.\n          Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[4]<=3 T[5]<=3 T[6]<=(-1)\n                 T[7]<=(-1) [].\n        Pcase: s[3] <= 7.\n          Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[4]<=3 T[5]<=2 T[6]<=0 T[7]<=(-1)\n                 [].\n        Pcase: h[4] > 5.\n          Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[4]<=3 T[5]<=2 T[6]<=0 T[7]<=(-1)\n                 [].\n        Hubcap T[1]<=4 T[2]<=4 T[3]<=(-3) T[4]<=3 T[5]<=3 T[6]<=0 T[7]<=(-1) [].\n      Pcase: s[6] <= 5.\n        Similar to L2_1[3].\n      Pcase L3_1: s[6] > 6.\n        Pcase: s[7] <= 6.\n          Pcase: h[2] > 5.\n            Hubcap T[2]<=3 T[3]<=(-3) T[5]<=4 T[6]<=(-3) T[7]<=2 T[1,4]<=7 [].\n          Pcase: h[3] <= 5.\n            Reducible.\n          Pcase: h[1] <= 5.\n            Reducible.\n          Pcase: h[5] <= 5.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=(-4) T[4]<=4 T[5]<=4 T[6]<=(-3) T[7]<=1\n                   [].\n          Pcase: h[1] > 6.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=(-3) T[4]<=3 T[5]<=3 T[6]<=(-3) T[7]<=1\n                   [].\n          Hubcap T[1]<=4 T[2]<=4 T[3]<=(-3) T[4]<=3 T[5]<=3 T[6]<=(-4) T[7]<=3\n                 [].\n        Pcase L4_1: h[2] > 5.\n          Pcase: h[4] <= 5.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=(-3) T[4]<=3 T[5]<=3 T[6,7]<=1 [].\n          Pcase: h[5] > 5.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=(-3) T[4]<=3 T[5]<=3 T[6,7]<=1 [].\n          Pcase: h[6] <= 5.\n            Reducible.\n          Pcase: s[6] > 7.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=(-3) T[4]<=4 T[5]<=4 T[6]<=(-1) T[7]<=0\n                   [].\n          Pcase: h[6] > 6.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=(-3) T[4]<=4 T[5]<=4 T[6]<=(-1) T[7]<=0\n                   [].\n          Pcase: f1[6] > 5.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=(-3) T[4]<=4 T[5]<=4 T[6]<=(-1)\n                   T[7]<=(-1) [].\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=(-3) T[4]<=4 T[5]<=4 T[6]<=1 T[7]<=(-2)\n                 [].\n        Pcase: h[5] > 5.\n          Similar to *L4_1[2].\n        Pcase: h[3] <= 5.\n          Reducible.\n        Pcase: h[4] <= 5.\n          Reducible.\n        Pcase: h[6] <= 5.\n          Reducible.\n        Pcase: h[1] <= 5.\n          Reducible.\n        Hubcap T[1]<=4 T[2]<=4 T[3]<=(-4) T[4]<=4 T[5]<=4 T[6]<=(-1) T[7]<=(-1) [].\n      Pcase: s[7] > 6.\n        Similar to *L3_1[2].\n      Reducible.\n    Pcase: s[6] <= 5.\n      Similar to *L2_2[5].\n    Pcase: s[5] <= 5.\n      Pcase L3_1: s[3] > 6.\n        Pcase: s[7] > 6.\n          Pcase L5_1: s[4] <= 6.\n            Pcase: h[2] <= 5.\n              Pcase: h[3] <= 5.\n                Reducible.\n              Pcase: h[1] <= 5.\n                Reducible.\n              Pcase: s[6] <= 6.\n                Pcase: h[5] > 6.\n                  Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[4]<=1 T[5]<=3 T[6]<=2\n                         T[7]<=(-2) [].\n                Pcase: h[5] <= 5.\n                  Hubcap T[1]<=4 T[2]<=4 T[3]<=(-3) T[4]<=2 T[5]<=3 T[6]<=2\n                         T[7]<=(-2) [].\n                Pcase: f1[4] <= 5.\n                  Reducible.\n                Pcase: h[6] > 5.\n                  Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[4]<=1 T[5]<=2 T[6]<=1\n                         T[7]<=(-2) [].\n                Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[4]<=2 T[5]<=3 T[6]<=2\n                       T[7]<=(-3) [].\n              Pcase: h[5] > 6.\n                Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[4]<=1 T[5]<=2 T[6,7]<=1 [].\n              Pcase: f1[4] <= 5.\n                Reducible.\n              Pcase: h[5] > 5.\n                Pcase: s[6] > 7.\n                  Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[5]<=2 T[6]<=0 T[4,7]<=2 [].\n                Pcase: h[6] > 5.\n                  Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[4]<=1 T[5]<=2 T[6,7]<=1 [].\n                Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[4]<=2 T[5]<=2 T[6]<=2\n                       T[7]<=(-2) [].\n              Pcase: s[6] > 7.\n                Hubcap T[1]<=4 T[2]<=4 T[3]<=(-3) T[4]<=3 T[5]<=3 T[6]<=0\n                       T[7]<=(-1) [].\n              Pcase: h[6] > 5.\n                Hubcap T[1]<=4 T[2]<=4 T[3]<=(-3) T[4]<=2 T[5]<=3 T[6]<=1\n                       T[7]<=(-1) [].\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=(-3) T[4]<=3 T[5]<=3 T[6]<=1\n                     T[7]<=(-2) [].\n            Pcase: s[6] > 6.\n              Pcase: h[5] > 5.\n                Hubcap T[1]<=3 T[2]<=3 T[3]<=(-2) T[4]<=2 T[5]<=2 T[6,7]<=2 [].\n              Pcase: f1[4] <= 5.\n                Reducible.\n              Pcase: s[6] <= 7.\n                Hubcap T[1]<=3 T[2]<=3 T[3]<=(-3) T[4]<=3 T[5]<=3 T[6,7]<=1 [].\n              Pcase: s[7] > 7.\n                Hubcap T[1]<=3 T[2]<=3 T[3]<=(-3) T[4]<=3 T[5]<=3 T[6]<=0\n                       T[7]<=(-1) [].\n              Pcase: h[2] <= 6.\n                Hubcap T[1]<=3 T[2]<=3 T[3]<=(-3) T[4]<=3 T[5]<=3 T[6]<=0\n                       T[7]<=(-1) [].\n              Pcase: h[6] > 5.\n                Hubcap T[1]<=3 T[2]<=3 T[3]<=(-3) T[4]<=2 T[5]<=3 T[6]<=0\n                       T[7]<=2 [].\n              Pcase: h[7] > 6.\n                Hubcap T[1]<=3 T[2]<=3 T[3]<=(-3) T[4]<=3 T[5]<=3 T[6]<=0\n                       T[7]<=1 [].\n              Pcase: h[7] <= 5.\n                Hubcap T[1]<=3 T[2]<=3 T[3]<=(-3) T[4]<=3 T[5]<=3 T[6]<=0\n                       T[7]<=1 [].\n              Pcase: h[1] > 5.\n                Hubcap T[1]<=3 T[2]<=3 T[3]<=(-3) T[4]<=3 T[5]<=3 T[6]<=0\n                       T[7]<=(-1) [].\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=(-3) T[4]<=3 T[5]<=3 T[6]<=(-1)\n                     T[7]<=2 [].\n            Pcase: h[5] > 5.\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=(-2) T[4]<=2 T[5]<=3 T[6]<=2\n                     T[7]<=(-2) [].\n            Pcase: f1[4] <= 5.\n              Reducible.\n            Pcase: h[6] > 5.\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=(-3) T[4]<=2 T[5]<=3 T[6]<=2\n                     T[7]<=(-2) [].\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=(-3) T[4]<=3 T[5]<=4 T[6]<=3 T[7]<=(-3)\n                   [].\n          Pcase: s[6] <= 6.\n            Similar to *L5_1[5].\n          Pcase L5_2: s[4] > 7.\n            Pcase: s[6] > 7.\n              Pcase: s[3] > 7.\n                Hubcap T[1]<=4 T[3]<=(-1) T[4]<=0 T[5]<=2 T[6]<=0 T[2,7]<=5 [].\n              Pcase: s[7] > 7.\n                Hubcap T[1]<=4 T[4]<=0 T[5]<=2 T[6]<=0 T[7]<=(-1) T[2,3]<=5 [].\n              Pcase: h[2] <= 6.\n                Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=2 T[6]<=0 T[3,7]<=0 [].\n              Pcase: h[3] > 5.\n                Hubcap T[1]<=3 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=2 T[6]<=0 T[7]<=2\n                       [].\n              Pcase: h[4] > 6.\n                Hubcap T[1]<=3 T[2]<=3 T[3]<=1 T[4]<=(-1) T[5]<=2 T[6]<=0\n                       T[7]<=2 [].\n              Pcase: h[4] <= 5.\n                Hubcap T[1]<=3 T[2]<=3 T[3]<=1 T[4]<=(-1) T[5]<=2 T[6]<=0\n                       T[7]<=2 [].\n              Pcase: h[7] > 6.\n                Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=(-1) T[5]<=2 T[6]<=0\n                       T[7]<=1 [].\n              Pcase: h[7] <= 5.\n                Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=(-1) T[5]<=2 T[6]<=0\n                       T[7]<=1 [].\n              Pcase: h[1] > 5.\n                Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=(-1) T[5]<=2 T[6]<=0\n                       T[7]<=0 [].\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=(-1) T[5]<=2 T[6]<=(-1)\n                     T[7]<=2 [].\n            Pcase: s[3] > 7.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=0 T[5]<=2 T[6,7]<=1 [].\n            Pcase: h[3] > 6.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=0 T[5]<=2 T[6,7]<=1 [].\n            Pcase: h[3] <= 5.\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=(-1) T[5]<=2 T[6,7]<=1 [].\n            Pcase: h[2] > 5.\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=2 T[6,7]<=1 [].\n            Pcase: h[1] <= 5.\n              Reducible.\n            Pcase: h[6] > 6.\n              Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=2 T[6]<=0 T[3,7]<=0 [].\n            Pcase: h[6] <= 5.\n              Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=2 T[7]<=(-2) T[3,6]<=2 [].\n            Pcase: s[7] > 7.\n              Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=2 T[7]<=(-1) T[3,6]<=1 [].\n            Pcase: h[5] <= 5.\n              Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=2 T[7]<=(-1) T[3,6]<=1 [].\n            Pcase: h[7] <= 5.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=1 T[4]<=0 T[5]<=2 T[6]<=0 T[7]<=(-1) [].\n            Pcase: h[1] > 6.\n              Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=2 T[7]<=(-1) T[3,6]<=1 [].\n            Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=2 T[6]<=0 T[3,7]<=0 [].\n          Pcase: s[6] > 7.\n            Similar to *L5_2[5].\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=3 T[2]<=3 T[5]<=2 T[3,4]<=1 T[6,7]<=1 [].\n          Pcase: h[3] <= 5.\n            Reducible.\n          Pcase: h[1] <= 5.\n            Reducible.\n          Pcase L5_3: h[5] <= 5.\n            Pcase: h[6] > 6.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[5]<=2 T[6]<=0 T[4,7]<=2 [].\n            Pcase: h[6] <= 5.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[4]<=2 T[5]<=2 T[6]<=2\n                     T[7]<=(-2) [].\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[4]<=2 T[5]<=2 T[6]<=1 T[7]<=(-1)\n                   [].\n          Pcase: h[6] <= 5.\n            Similar to *L5_3[5].\n          Pcase L5_4: h[4] <= 5.\n            Pcase: s[3] <= 7.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=0 T[5]<=2 T[6,7]<=1 [].\n            Pcase: s[7] > 7.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=1 T[5]<=2 T[6]<=1\n                     T[7]<=(-1) [].\n            Pcase: h[5] > 6.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=0 T[5]<=2 T[6,7]<=1 [].\n            Pcase: h[6] > 6.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[5]<=2 T[6]<=0 T[4,7]<=1 [].\n            Pcase: h[7] <= 5.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=1 T[5]<=2 T[6]<=0\n                     T[7]<=(-1) [].\n            Pcase: h[1] > 6.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=1 T[5]<=2 T[6]<=1\n                     T[7]<=(-1) [].\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[5]<=2 T[6]<=0 T[4,7]<=1 [].\n          Pcase: h[7] <= 5.\n            Similar to *L5_4[5].\n          Pcase: f1[4] <= 5.\n            Pcase: s[3] > 7.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=0 T[5]<=2 T[6,7]<=1 [].\n            Pcase: s[7] > 7.\n              Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=2 T[7]<=(-1) T[3,6]<=1 [].\n            Pcase: h[3] > 6.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=0 T[5]<=2 T[6,7]<=1 [].\n            Pcase: h[4] <= 6.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=0 T[5]<=2 T[6,7]<=1 [].\n            Pcase: h[6] > 6.\n              Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=2 T[6]<=0 T[3,7]<=0 [].\n            Pcase: h[1] > 6.\n              Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=2 T[7]<=(-1) T[3,6]<=1 [].\n            Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=2 T[6]<=0 T[3,7]<=0 [].\n          Pcase: f2[6] <= 5.\n            Pcase: s[3] > 7.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[5]<=2 T[6]<=0 T[4,7]<=1 [].\n            Pcase: s[7] > 7.\n              Hubcap T[1]<=4 T[2]<=4 T[5]<=2 T[6]<=0 T[7]<=(-1) T[3,4]<=1 [].\n            Pcase: h[3] > 6.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[5]<=2 T[6]<=0 T[4,7]<=1 [].\n            Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=2 T[6]<=0 T[3,7]<=0 [].\n          Pcase L5_5: s[3] > 7.\n            Pcase: s[7] > 7.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=1 T[5]<=2 T[6]<=1\n                     T[7]<=(-1) [].\n            Pcase: h[5] > 6.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=0 T[5]<=2 T[6,7]<=1 [].\n            Pcase: h[6] > 6.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[5]<=2 T[6]<=0 T[4,7]<=1 [].\n            Pcase: h[1] > 6.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=1 T[5]<=2 T[6]<=1\n                     T[7]<=(-1) [].\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[5]<=2 T[6]<=0 T[4,7]<=1 [].\n          Pcase: s[7] > 7.\n            Similar to *L5_5[5].\n          Pcase L5_6: h[3] > 6.\n            Pcase: h[5] > 6.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=0 T[5]<=2 T[6,7]<=1 [].\n            Pcase: h[6] > 6.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[5]<=2 T[6]<=0 T[4,7]<=1 [].\n            Pcase: h[1] > 6.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=1 T[5]<=2 T[6]<=1\n                     T[7]<=(-1) [].\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[5]<=2 T[6]<=0 T[4,7]<=1 [].\n          Pcase: h[1] > 6.\n            Similar to *L5_6[5].\n          Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=2 T[6]<=0 T[3,7]<=0 [].\n        Pcase: s[6] <= 6.\n          Reducible.\n        Pcase: s[4] > 6.\n          Pcase: s[4] > 7.\n            Pcase: s[3] > 7.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=0 T[5]<=2 T[6]<=(-2)\n                     T[7]<=3 [].\n            Pcase: h[2] > 5.\n              Hubcap T[1]<=4 T[2]<=3 T[4]<=0 T[5]<=2 T[6]<=(-2) T[3,7]<=3 [].\n            Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=2 T[6]<=(-2) T[3,7]<=2 [].\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=4 T[2]<=3 T[5]<=2 T[6]<=(-2) T[7]<=2 T[3,4]<=1 [].\n          Pcase: h[3] <= 5.\n            Reducible.\n          Pcase: h[1] <= 5.\n            Reducible.\n          Pcase: h[5] > 6.\n            Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=2 T[6]<=(-2) T[3,7]<=2 [].\n          Pcase: h[5] <= 5.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[5]<=2 T[6]<=(-2) T[4,7]<=4 [].\n          Pcase: s[3] > 7.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[5]<=2 T[6]<=(-2) T[4,7]<=3 [].\n          Pcase: h[3] > 6.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[5]<=2 T[6]<=(-2) T[4,7]<=3 [].\n          Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=2 T[6]<=(-2) T[3,7]<=2 [].\n        Pcase: h[5] > 5.\n          Hubcap T[1]<=4 T[2]<=4 T[3]<=(-2) T[5]<=2 T[6]<=(-2) T[4,7]<=4 [].\n        Hubcap T[1]<=4 T[3]<=(-3) T[4]<=3 T[5]<=3 T[6]<=(-2) T[2,7]<=5 [].\n      Pcase: s[7] > 6.\n        Similar to *L3_1[5].\n      Pcase: s[4] <= 6.\n        Reducible.\n      Pcase: s[6] <= 6.\n        Reducible.\n      Hubcap T[1]<=4 T[2]<=4 T[4]<=(-2) T[5]<=2 T[6]<=(-2) T[3,7]<=4 [].\n    Pcase L2_3: s[3] <= 6.\n      Pcase L3_1: s[4] > 6.\n        Pcase: s[7] > 6.\n          Pcase: s[5] > 7.\n            Hubcap T[1]<=4 T[2]<=4 T[4]<=(-1) T[5]<=0 T[6]<=0 T[3,7]<=3 [].\n          Pcase: s[6] > 7.\n            Hubcap T[1]<=4 T[2]<=4 T[4]<=(-1) T[5]<=0 T[6]<=0 T[3,7]<=3 [].\n          Pcase: h[6] > 6.\n            Hubcap T[1]<=4 T[2]<=4 T[4]<=(-1) T[5]<=0 T[6]<=0 T[3,7]<=3 [].\n          Pcase: h[2] > 5.\n            Pcase: s[4] > 7.\n              Hubcap T[1]<=3 T[2]<=4 T[3]<=2 T[4]<=(-2) T[5,6]<=3 T[5,7]<=2\n                     T[6,7]<=2 [].\n            Pcase: s[5] > 6.\n              Hubcap T[1]<=3 T[2]<=4 T[3]<=2 T[4]<=(-1) T[6]<=0 T[5,7]<=2 [].\n            Pcase: h[5] <= 5.\n              Reducible.\n            Pcase: s[6] > 6.\n              Hubcap T[1]<=3 T[2]<=4 T[3]<=2 T[4]<=(-1) T[5]<=0 T[6,7]<=2 [].\n            Hubcap T[1]<=3 T[2]<=4 T[3]<=2 T[4,5]<=0 T[6,7]<=1 [].\n          Pcase: h[3] <= 5.\n            Reducible.\n          Pcase: h[1] <= 5.\n            Reducible.\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=4 T[2]<=4 T[6]<=0 T[3,7]<=2 T[4,5]<=0 [].\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=4 T[2]<=4 T[5]<=0 T[3,7]<=2 T[4,6]<=0 [].\n          Pcase: h[6] <= 5.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=1 T[4]<=(-1) T[7]<=(-1) T[5,6]<=3 [].\n          Pcase: s[7] <= 7.\n            Hubcap T[1]<=4 T[2]<=4 T[3,7]<=2 T[4,5]<=(-1) T[4,6]<=0 T[5,6]<=2 [].\n          Pcase: s[4] > 7.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=3 T[4]<=(-2) T[7]<=(-1) T[5,6]<=2 [].\n          Pcase: h[5] <= 5.\n            Reducible.\n          Pcase: h[3] > 6.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=1 T[4]<=(-1) T[5]<=2 T[6]<=1 T[7]<=(-1)\n                   [].\n          Pcase: f1[3] <= 5.\n            Reducible.\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=3 T[4]<=(-2) T[7]<=(-1) T[5,6]<=2 [].\n          Hubcap T[1]<=4 T[2]<=4 T[3]<=3 T[4]<=(-1) T[7]<=(-1) T[5,6]<=1 [].\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=4 T[2]<=4 T[4]<=(-1) T[5]<=0 T[6]<=(-1) T[3,7]<=4 [].\n        Pcase: h[7] <= 5.\n          Reducible.\n        Pcase: s[5] > 7.\n          Hubcap T[1]<=4 T[2]<=4 T[4]<=(-1) T[5]<=(-1) T[6]<=0 T[3,7]<=4 [].\n        Pcase: s[5] <= 6.\n          Hubcap T[1]<=4 T[2]<=4 T[4]<=(-2) T[5]<=0 T[6]<=0 T[3,7]<=4 [].\n        Pcase: s[4] > 7.\n          Hubcap T[1]<=4 T[2]<=4 T[4]<=(-2) T[5]<=0 T[6]<=0 T[3,7]<=4 [].\n        Pcase: h[4] > 5.\n          Hubcap T[1]<=4 T[2]<=4 T[4]<=(-2) T[5]<=0 T[6]<=0 T[3,7]<=4 [].\n        Pcase: f1[4] <= 5.\n          Reducible.\n        Pcase: h[6] > 5.\n          Hubcap T[1]<=4 T[2]<=4 T[4]<=(-1) T[5]<=(-1) T[6]<=0 T[3,7]<=4 [].\n        Hubcap T[1]<=4 T[2]<=4 T[4]<=(-1) T[5]<=(-1) T[6]<=0 T[3,7]<=4 [].\n      Pcase: h[4] <= 5.\n        Reducible.\n      Pcase: s[5] > 6.\n        Pcase: s[7] > 7.\n          Pcase: s[5] > 7.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=3 T[4]<=0 T[5]<=(-1) T[6]<=0 T[7]<=(-1)\n                   [].\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=3 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=(-1) [].\n          Pcase: h[6] <= 5.\n            Reducible.\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=3 T[2]<=4 T[3]<=2 T[4]<=0 T[5]<=1 T[6]<=0 T[7]<=(-1) [].\n          Pcase: h[3] <= 5.\n            Reducible.\n          Pcase: h[1] <= 5.\n            Reducible.\n          Pcase: h[3] > 6.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=1 T[4]<=0 T[5]<=1 T[6]<=0 T[7]<=(-1) [].\n          Pcase: f1[3] <= 5.\n            Reducible.\n          Pcase: h[5] > 5.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=3 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=(-1) [].\n          Hubcap T[1]<=4 T[2]<=4 T[3]<=3 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=(-1) [].\n        Pcase: s[5] > 7.\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=(-1) T[6]<=0 T[3,7]<=3 [].\n          Pcase: s[6] > 6.\n            Similar to *L3_1[5].\n          Pcase: h[7] <= 5.\n            Reducible.\n          Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=(-2) T[6]<=0 T[3,7]<=4 [].\n        Pcase L4_1: h[5] > 5.\n          Pcase: s[6] > 7.\n            Pcase: s[7] <= 6.\n              Similar to *L3_1[5].\n            Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=(-1) T[6]<=0 T[3,7]<=3 [].\n          Pcase: s[7] > 6.\n            Pcase: s[6] > 6.\n              Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=(-1) T[6]<=0 T[3,7]<=3 [].\n            Pcase: h[6] <= 5.\n              Reducible.\n            Pcase: h[2] > 5.\n              Hubcap T[1]<=3 T[2]<=4 T[3]<=2 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=1 [].\n            Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=0 T[6]<=0 T[3,7]<=2 [].\n          Pcase: s[6] > 6.\n            Similar to *L3_1[5].\n          Pcase: h[6] <= 5.\n            Reducible.\n          Pcase: h[7] <= 5.\n            Reducible.\n          Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=(-2) T[6]<=0 T[3,7]<=4 [].\n        Pcase: f1[5] <= 5.\n          Reducible.\n        Pcase: s[6] > 7.\n          Pcase: s[7] <= 6.\n            Similar to *L3_1[5].\n          Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=(-1) T[6]<=0 T[3,7]<=3 [].\n        Pcase: s[7] > 6.\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=(-1) T[6]<=0 T[3,7]<=3 [].\n          Pcase: h[6] <= 5.\n            Reducible.\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=3 T[2]<=4 T[3]<=2 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=1 [].\n          Hubcap T[1]<=4 T[2]<=4 T[3]<=3 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=(-1) [].\n        Pcase: s[6] > 6.\n          Similar to *L3_1[5].\n        Pcase: h[6] > 5.\n          Similar to *L4_1[5].\n        Reducible.\n      Pcase: h[5] <= 5.\n        Reducible.\n      Pcase: s[7] > 6.\n        Pcase: h[3] <= 5.\n          Hubcap T[1]<=3 T[2]<=4 T[3]<=2 T[4]<=0 T[5]<=0 T[6,7]<=1 [].\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=0 T[5]<=0 T[6,7]<=2 [].\n        Pcase: h[1] <= 5.\n          Reducible.\n        Pcase: s[6] > 7.\n          Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=0 T[6]<=0 T[3,7]<=2 [].\n        Pcase: s[6] <= 6.\n          Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=0 T[6]<=0 T[3,7]<=2 [].\n        Pcase: h[3] > 6.\n          Hubcap T[1]<=4 T[2]<=4 T[3]<=1 T[4]<=0 T[5]<=0 T[6,7]<=1 [].\n        Pcase: f1[3] <= 5.\n          Reducible.\n        Pcase: h[6] > 5.\n          Hubcap T[1]<=4 T[2]<=4 T[3]<=3 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=(-1) [].\n        Hubcap T[1]<=4 T[2]<=4 T[3]<=3 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=(-1) [].\n      Pcase: s[6] > 6.\n        Similar to *L3_1[5].\n      Reducible.\n    Pcase: s[7] <= 6.\n      Similar to *L2_3[5].\n    Pcase: s[5] > 7.\n      Hubcap T[4]<=0 T[5]<=0 T[6]<=0 T[1,3]<=5 T[2,7]<=5 [].\n    Pcase: h[2] > 5.\n      Pcase L3_1: s[3] > 7.\n        Pcase: s[4] > 6.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=(-1) T[4]<=2 T[5,6]<=3 T[5,7]<=2\n                 T[6,7]<=2 [].\n        Pcase: s[5] > 6.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=(-1) T[4]<=0 T[6]<=0 T[5,7]<=4 [].\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=(-1) T[4,5]<=3 T[6,7]<=2 [].\n        Pcase: s[7] > 7.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=(-1) T[4]<=2 T[7]<=(-1) T[5,6]<=4 [].\n        Pcase: h[5] > 5.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=(-1) T[4,5]<=3 T[6,7]<=1 [].\n        Pcase: h[1] <= 5.\n          Reducible.\n        Pcase: h[6] > 5.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=(-1) T[4,5]<=3 T[6,7]<=2 [].\n        Hubcap T[1]<=3 T[2]<=3 T[3]<=(-1) T[4]<=1 T[5]<=3 T[6]<=1 T[7]<=(-1) [].\n      Pcase: s[7] > 7.\n        Similar to *L3_1[5].\n      Pcase L3_2: h[3] <= 5.\n        Pcase: h[2] <= 6.\n          Reducible.\n        Pcase L4_1: h[4] <= 5.\n          Pcase: s[4] <= 6.\n            Reducible.\n          Pcase: s[4] > 7.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=1 T[4]<=0 T[5,6]<=3 T[5,7]<=2 T[6,7]<=2\n                   [].\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=0 T[6]<=0 T[5,7]<=2 [].\n          Pcase: h[5] <= 5.\n            Reducible.\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=3 T[2]<=3 T[5]<=0 T[3,4]<=2 T[6,7]<=2 [].\n          Pcase: h[6] > 5.\n            Hubcap T[1]<=3 T[2]<=3 T[5]<=1 T[3,4]<=2 T[6,7]<=1 [].\n          Hubcap T[1]<=3 T[2]<=3 T[3,4]<=2 T[5,6]<=3 T[5,7]<=1 T[6,7]<=1 [].\n        Pcase: h[7] <= 5.\n          Pcase: h[1] <= 5.\n            Similar to *L4_1[5].\n          Pcase: s[4] > 6.\n            Hubcap T[1]<=3 T[2]<=3 T[7]<=1 T[3,4]<=2 T[5,6]<=1 [].\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=1 T[4]<=0 T[5]<=2 T[6]<=0 T[7]<=1 [].\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=1 T[4]<=1 T[5]<=1 T[6,7]<=1 [].\n          Hubcap T[1]<=3 T[2]<=3 T[5]<=1 T[6]<=1 T[7]<=1 T[3,4]<=1 [].\n        Pcase: h[1] > 6.\n          Hubcap T[1]<=3 T[2]<=3 T[7]<=(-1) T[3,4]<=2 T[5,6]<=3 [].\n        Pcase: h[1] > 5.\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=3 T[2]<=3 T[4]<=0 T[6]<=0 T[7]<=0 T[3,5]<=4 [].\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=3 T[2]<=3 T[7]<=0 T[3,4]<=2 T[5,6]<=2 [].\n          Pcase: s[4] > 6.\n            Hubcap T[1]<=3 T[2]<=3 T[3,4]<=2 T[5,6]<=3 T[5,7]<=1 T[6,7]<=1 [].\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=1 T[4]<=1 T[5]<=2 T[6,7]<=0 [].\n        Pcase: f1[3] > 5.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=0 T[4,5]<=2 T[6,7]<=2 [].\n        Pcase: f2[3] <= 5.\n          Reducible.\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=3 T[2]<=3 T[6,7]<=2 T[3,4]<=2 T[3,5]<=2 T[4,5]<=1 [].\n        Pcase: s[4] <= 7.\n          Hubcap T[1]<=3 T[2]<=3 T[4]<=0 T[3,5]<=3 T[6,7]<=1 [].\n        Pcase: s[5] > 6.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=0 T[5]<=1 T[6]<=0 T[7]<=1 [].\n        Pcase: h[4] > 6.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=1 T[4]<=0 T[5]<=1 T[6]<=1 T[7]<=1 [].\n        Pcase: h[5] > 5.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=0 T[5]<=1 T[6,7]<=1 [].\n        Pcase: h[6] > 5.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=0 T[7]<=1 T[5,6]<=1 [].\n        Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=0 T[5]<=1 T[6]<=1 T[7]<=0 [].\n      Pcase: h[1] <= 5.\n        Similar to *L3_2[5].\n      Pcase: s[4] > 7.\n        Hubcap T[1]<=3 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=2 T[6,7]<=2 [].\n      Pcase: s[6] > 7.\n        Hubcap T[1]<=3 T[2]<=3 T[3]<=1 T[6]<=0 T[7]<=0 T[4,5]<=3 [].\n      Pcase: s[5] > 6.\n        Pcase: s[4] > 6.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=1 T[4]<=0 T[5]<=2 T[6]<=0 T[7]<=1 [].\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=1 T[4]<=0 T[5]<=2 T[6]<=0 T[7]<=1 [].\n        Pcase: h[4] > 5.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=0 T[4]<=0 T[6]<=0 T[5,7]<=4 [].\n        Hubcap T[1]<=3 T[2]<=3 T[3]<=1 T[4]<=0 T[6]<=0 T[5,7]<=3 [].\n      Pcase: h[5] > 6.\n        Hubcap T[1]<=3 T[2]<=3 T[3]<=1 T[4]<=0 T[6]<=2 T[5,7]<=1 [].\n      Pcase: h[6] > 6.\n        Hubcap T[1]<=3 T[2]<=3 T[4]<=2 T[6]<=0 T[7]<=1 T[3,5]<=1 [].\n      Pcase L3_3: h[4] <= 5.\n        Pcase: h[5] <= 5.\n          Reducible.\n        Pcase: s[4] > 6.\n          Hubcap T[1]<=3 T[2]<=3 T[6]<=2 T[3,4]<=1 T[5,7]<=1 [].\n        Pcase: f1[4] <= 6.\n          Reducible.\n        Pcase: f1[5] <= 5.\n          Reducible.\n        Pcase: f2[3] <= 5.\n          Reducible.\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=1 T[4]<=1 T[5]<=0 T[6,7]<=2 [].\n        Hubcap T[1]<=3 T[2]<=3 T[3]<=1 T[4]<=1 T[6]<=1 T[5,7]<=1 [].\n      Pcase: h[7] <= 5.\n        Similar to *L3_3[5].\n      Pcase: s[6] > 6.\n        Hubcap T[1]<=3 T[2]<=3 T[6]<=2 T[3,7]<=(-1) T[4,5]<=3 [].\n      Pcase: s[4] > 6.\n        Hubcap T[1]<=3 T[2]<=3 T[4]<=2 T[3,5]<=1 T[6,7]<=1 [].\n      Hubcap T[1]<=3 T[2]<=3 T[3,4]<=1 T[5,6]<=4 T[5,7]<=2 T[6,7]<=1 [].\n    Pcase: h[3] <= 5.\n      Reducible.\n    Pcase: h[1] <= 5.\n      Reducible.\n    Pcase L2_4: s[4] > 6.\n      Pcase: s[5] > 6.\n        Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=2 T[6]<=0 T[3,7]<=0 [].\n      Pcase: s[6] > 6.\n        Hubcap T[1]<=4 T[2]<=4 T[5]<=0 T[3,4]<=1 T[6,7]<=1 [].\n      Pcase: h[6] > 6.\n        Hubcap T[1]<=4 T[2]<=4 T[5]<=0 T[6]<=0 T[7]<=1 T[3,4]<=1 [].\n      Pcase: h[6] <= 5.\n        Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=1 T[7]<=(-1) T[5,6]<=3 [].\n      Pcase: s[7] > 7.\n        Hubcap T[1]<=4 T[2]<=4 T[7]<=(-1) T[3,4]<=1 T[5,6]<=2 [].\n      Pcase: h[7] <= 5.\n        Reducible.\n      Pcase: s[4] > 7.\n        Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[3,7]<=0 T[5,6]<=2 [].\n      Pcase: h[5] > 5.\n        Hubcap T[1]<=4 T[2]<=4 T[4]<=1 T[3,7]<=0 T[5,6]<=1 [].\n      Pcase: h[1] > 6.\n        Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=2 T[7]<=(-1) T[5,6]<=2 [].\n      Pcase: f2[4] <= 5.\n        Reducible.\n      Pcase: h[7] <= 6.\n        Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=1 T[5,6]<=2 T[5,7]<=1 T[6,7]<=2 [].\n      Pcase: f1[5] > 5.\n        Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=1 T[7]<=1 T[5,6]<=1 [].\n      Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=1 T[5]<=0 T[6]<=2 T[7]<=(-1) [].\n    Pcase: s[6] > 6.\n      Similar to *L2_4[5].\n    Pcase L2_5: h[4] <= 5.\n      Pcase: s[3] <= 7.\n        Reducible.\n      Pcase: s[5] > 6.\n        Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=0 T[6]<=0 T[5,7]<=3 [].\n      Pcase L3_1: s[7] > 7.\n        Pcase: h[5] > 5.\n          Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[7]<=(-1) T[4,5]<=3 T[4,6]<=2\n                 T[5,6]<=4 [].\n        Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[7]<=(-1) T[4,5]<=4 T[4,6]<=2\n               T[5,6]<=3 [].\n      Pcase: h[7] <= 5.\n        Similar to *L3_1[5].\n      Pcase: h[5] > 6.\n        Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=0 T[5]<=2 T[6,7]<=1 [].\n      Pcase: h[5] <= 5.\n        Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=2 T[7]<=(-1) T[5,6]<=2 [].\n      Pcase: h[6] > 5.\n        Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4,5]<=2 T[6,7]<=1 [].\n      Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[6]<=1 T[7]<=(-1) T[4,5]<=3 [].\n    Pcase: h[7] <= 5.\n      Similar to *L2_5[5].\n    Pcase: s[5] > 6.\n      Pcase: s[3] > 7.\n        Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=0 T[6]<=0 T[5,7]<=3 [].\n      Pcase: s[7] > 7.\n        Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[6]<=0 T[7]<=(-1) T[3,5]<=3 [].\n      Pcase: h[3] > 6.\n        Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=0 T[6]<=0 T[5,7]<=3 [].\n      Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=2 T[6]<=0 T[3,7]<=0 [].\n    Pcase: h[5] <= 5.\n      Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[6]<=1 T[7]<=(-1) T[4,5]<=3 [].\n    Pcase: h[6] > 6.\n      Hubcap T[1]<=4 T[2]<=4 T[4]<=1 T[5]<=1 T[6]<=0 T[3,7]<=0 [].\n    Pcase: h[6] <= 5.\n      Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4]<=1 T[7]<=(-1) T[5,6]<=3 [].\n    Pcase: s[7] > 7.\n      Hubcap T[1]<=4 T[2]<=4 T[7]<=(-1) T[3,4]<=1 T[5,6]<=2 [].\n    Pcase: s[3] > 7.\n      Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4,5]<=2 T[6,7]<=1 [].\n    Pcase: h[3] > 6.\n      Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4,5]<=2 T[6,7]<=1 [].\n    Pcase: h[5] > 6.\n      Hubcap T[1]<=4 T[2]<=4 T[4]<=0 T[5]<=1 T[6]<=1 T[3,7]<=0 [].\n    Pcase: h[1] > 6.\n      Hubcap T[1]<=4 T[2]<=4 T[7]<=(-1) T[3,4]<=1 T[5,6]<=2 [].\n    Pcase: f1[3] > 5.\n      Hubcap T[1]<=4 T[2]<=4 T[3]<=(-1) T[4,5]<=2 T[6,7]<=1 [].\n    Hubcap T[1]<=4 T[2]<=4 T[3]<=1 T[4]<=0 T[5]<=2 T[6]<=0 T[7]<=(-1) [].\n  Pcase: s[7] <= 5.\n    Similar to L1_1[6].\n  Pcase L1_2: s[3] <= 5.\n    Pcase: s[4] <= 5.\n      Similar to L1_1[2].\n    Pcase L2_1: s[5] <= 5.\n      Pcase: s[6] <= 5.\n        Similar to L1_1[4].\n      Pcase L3_1: s[6] > 6.\n        Pcase: s[7] > 6.\n          Pcase L5_1: s[2] <= 6.\n            Pcase: s[4] <= 6.\n              Reducible.\n            Pcase: h[2] > 5.\n              Pcase: s[6] > 7.\n                Hubcap T[1]<=2 T[2]<=4 T[5]<=2 T[6]<=0 T[7]<=0 T[3,4]<=2 [].\n              Pcase: s[7] > 7.\n                Hubcap T[1]<=2 T[2]<=4 T[3]<=3 T[5]<=2 T[7]<=(-1) T[4,6]<=0 [].\n              Pcase: h[7] <= 5.\n                Reducible.\n              Pcase: h[3] > 5.\n                Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[4]<=0 T[5]<=2 T[6]<=1 T[7]<=0\n                       [].\n              Hubcap T[1]<=2 T[2]<=4 T[3]<=3 T[4]<=(-2) T[5]<=2 T[6]<=1 T[7]<=0 [].\n            Pcase: f1[2] <= 5.\n              Reducible.\n            Pcase: h[3] > 5.\n              Pcase: s[4] > 7.\n                Hubcap T[1]<=3 T[2]<=4 T[3]<=2 T[4]<=(-1) T[5]<=2 T[6,7]<=0 [].\n              Pcase: h[4] <= 5.\n                Reducible.\n              Pcase: h[5] <= 5.\n                Reducible.\n              Pcase: s[7] > 7.\n                Hubcap T[1]<=3 T[2]<=4 T[3]<=2 T[5]<=2 T[7]<=(-1) T[4,6]<=0 [].\n              Pcase: h[5] > 6.\n                Hubcap T[1]<=3 T[2]<=4 T[3]<=2 T[4]<=(-1) T[5]<=2 T[6,7]<=0 [].\n              Pcase: h[6] <= 5.\n                Reducible.\n              Pcase: h[1] > 5.\n                Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=0 T[5]<=2 T[6]<=0\n                       T[7]<=(-1) [].\n              Hubcap T[1]<=3 T[2]<=4 T[3]<=2 T[4]<=0 T[5]<=2 T[6]<=(-1)\n                     T[7]<=(-1) [].\n            Pcase: f1[2] <= 6.\n              Reducible.\n            Pcase: s[4] > 7.\n              Pcase: s[4] > 8.\n                Pcase: s[6] > 7.\n                  Pcase: s[7] > 7.\n                    Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=2 T[6]<=0\n                           T[7]<=(-1) [].\n                  Pcase: h[4] <= 5.\n                    Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=2 T[6]<=0\n                           T[7]<=(-1) [].\n                  Pcase: h[1] > 5.\n                    Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=(-2) T[5]<=2 T[6]<=0\n                           T[7]<=(-1) [].\n                  Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=2 T[6]<=(-1)\n                         T[7]<=(-1) [].\n                Pcase: h[6] <= 5.\n                  Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=2 T[6]<=1\n                         T[7]<=(-2) [].\n                Pcase: s[7] > 7.\n                  Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=2 T[6]<=0\n                         T[7]<=(-1) [].\n                Pcase: h[7] <= 5.\n                  Reducible.\n                Pcase: h[4] <= 5.\n                  Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=2 T[6]<=0\n                         T[7]<=(-1) [].\n                Pcase: h[1] > 5.\n                  Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=(-2) T[5]<=2 T[6]<=0\n                         T[7]<=(-1) [].\n                Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=2 T[6]<=(-1)\n                       T[7]<=(-1) [].\n              Pcase: s[6] > 7.\n                Pcase: s[7] > 7.\n                  Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=2 T[6]<=0\n                         T[7]<=(-1) [].\n                Pcase: h[4] <= 5.\n                  Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=2 T[6]<=0\n                         T[7]<=(-1) [].\n                Pcase: h[1] > 5.\n                  Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=(-2) T[5]<=2 T[6]<=0\n                         T[7]<=(-1) [].\n                Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=2 T[6]<=(-1)\n                       T[7]<=(-1) [].\n              Pcase: h[6] <= 5.\n                Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=2 T[6]<=1\n                       T[7]<=(-2) [].\n              Pcase: s[7] > 7.\n                Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=2 T[6]<=0\n                       T[7]<=(-1) [].\n              Pcase: h[7] <= 5.\n                Reducible.\n              Pcase: h[4] <= 5.\n                Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=2 T[6]<=0\n                       T[7]<=(-1) [].\n              Pcase: h[1] > 5.\n                Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=(-2) T[5]<=2 T[6]<=0\n                       T[7]<=(-1) [].\n              Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=2 T[6]<=(-1)\n                     T[7]<=(-1) [].\n            Pcase: h[4] <= 6.\n              Reducible.\n            Pcase: h[5] <= 5.\n              Reducible.\n            Pcase: h[1] > 5.\n              Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=(-2) T[5]<=2 T[6]<=1\n                     T[7]<=(-1) [].\n            Pcase: s[7] <= 7.\n              Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=2 T[6]<=(-1)\n                     T[7]<=(-1) [].\n            Pcase: s[6] > 7.\n              Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=2 T[6]<=0\n                     T[7]<=(-1) [].\n            Pcase: h[5] <= 6.\n              Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=2 T[6]<=0\n                     T[7]<=(-1) [].\n            Pcase: h[6] > 5.\n              Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=2 T[6]<=0\n                     T[7]<=(-1) [].\n            Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=2 T[6]<=1 T[7]<=(-2)\n                   [].\n          Pcase: s[4] <= 6.\n            Similar to *L5_1[2].\n          Pcase L5_2: s[2] > 7.\n            Pcase: s[4] > 8.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=0 T[5]<=2 T[6,7]<=2 [].\n            Pcase: s[4] > 7.\n              Pcase: s[2] > 8.\n                Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=2 T[5]<=2 T[6,7]<=2 [].\n              Pcase: h[2] > 6.\n                Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[2,4]<=2 T[6,7]<=2 [].\n              Pcase: h[5] > 6.\n                Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[2,4]<=2 T[6,7]<=2 [].\n              Pcase L7_1: s[6] > 7.\n                Pcase: s[7] > 7.\n                  Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=2 T[5]<=2 T[6]<=0 T[7]<=0\n                         [].\n                Pcase: h[2] > 5.\n                  Hubcap T[1]<=2 T[3]<=2 T[4]<=2 T[5]<=2 T[6]<=0 T[2,7]<=2 [].\n                Pcase: h[3] <= 5.\n                  Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=1 T[5]<=2 T[6]<=0 T[7]<=1\n                         [].\n                Pcase: h[4] > 5.\n                  Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=1 T[5]<=2 T[6]<=0 T[7]<=2\n                         [].\n                Pcase: h[5] > 5.\n                  Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=1 T[5]<=2 T[6]<=0 T[7]<=2\n                         [].\n                Pcase: h[6] > 5.\n                  Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=1 T[5]<=2 T[6]<=0 T[7]<=2\n                         [].\n                Pcase: h[1] > 5.\n                  Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=2 T[5]<=2 T[6]<=0 T[7]<=1\n                         [].\n                Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=2 T[5]<=2 T[6]<=(-1)\n                       T[7]<=2 [].\n              Pcase: s[7] > 7.\n                Similar to *L7_1[2].\n              Pcase: h[3] > 6.\n                Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[2,4]<=2 T[6,7]<=2 [].\n              Pcase: h[4] > 6.\n                Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[2,4]<=2 T[6,7]<=2 [].\n              Pcase: h[6] <= 5.\n                Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[2,4]<=3 T[6,7]<=1 [].\n              Pcase: h[3] > 5.\n                Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=1 T[5]<=2 T[6,7]<=2 [].\n              Pcase: h[5] > 5.\n                Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=1 T[7]<=1 T[2,4]<=2 [].\n              Pcase: h[6] <= 6.\n                Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=1 T[7]<=1 T[2,4]<=2 [].\n              Pcase: h[7] > 5.\n                Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=0 T[7]<=1 T[2,4]<=3 [].\n              Pcase: h[1] > 5.\n                Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=1 T[7]<=1 T[2,4]<=2 [].\n              Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=0 T[7]<=1 T[2,4]<=3 [].\n            Pcase: s[2] > 8.\n              Pcase: f1[4] <= 5.\n                Pcase: s[7] > 7.\n                  Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[7]<=0 T[4,6]<=4 [].\n                Pcase: h[4] > 6.\n                  Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=2 T[5]<=2 T[6,7]<=2 [].\n                Pcase: f2[4] <= 5.\n                  Reducible.\n                Pcase: h[1] <= 5.\n                  Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[4,6]<=3 T[4,7]<=5\n                         T[6,7]<=1 [].\n                Pcase: s[6] > 7.\n                  Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[6]<=0 T[4,7]<=4 [].\n                Pcase: h[4] > 5.\n                  Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[7]<=1 T[4,6]<=3 [].\n                Pcase: h[5] <= 6.\n                  Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[6]<=0 T[4,7]<=4 [].\n                Pcase: h[6] > 5.\n                  Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=3 T[5]<=2 T[6]<=0 T[7]<=1\n                         [].\n                Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=3 T[5]<=2 T[6]<=1 T[7]<=0\n                       [].\n              Pcase: h[5] > 6.\n                Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=2 T[5]<=2 T[6,7]<=2 [].\n              Pcase: s[6] > 7.\n                Pcase: s[7] > 7.\n                  Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=4 T[5]<=2 T[6]<=0 T[7]<=0\n                         [].\n                Pcase: h[5] > 5.\n                  Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[6]<=0 T[4,7]<=4 [].\n                Pcase: h[1] > 5.\n                  Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=4 T[5]<=2 T[6]<=0 T[7]<=0\n                         [].\n                Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[6]<=(-1) T[4,7]<=5 [].\n              Pcase: h[6] <= 5.\n                Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[6]<=1 T[4,7]<=3 [].\n              Pcase: s[7] > 7.\n                Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[7]<=0 T[4,6]<=4 [].\n              Pcase: h[5] > 5.\n                Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[4,6]<=3 T[4,7]<=4\n                       T[6,7]<=2 [].\n              Pcase: h[7] <= 5.\n                Reducible.\n              Pcase: h[6] <= 6.\n                Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=4 T[5]<=2 T[6]<=0 T[7]<=0\n                       [].\n              Pcase: h[1] > 5.\n                Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=4 T[5]<=2 T[6]<=0 T[7]<=0\n                       [].\n              Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[6]<=(-1) T[4,7]<=5 [].\n            Pcase: s[6] > 7.\n              Pcase: s[7] > 7.\n                Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=0 T[7]<=0 T[2,4]<=4 [].\n              Pcase: h[1] > 6.\n                Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=0 T[7]<=0 T[2,4]<=4 [].\n              Pcase: h[5] > 5.\n                Pcase: h[2] > 6.\n                  Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[6]<=0 T[4,7]<=4 [].\n                Pcase: h[1] > 5.\n                  Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=0 T[7]<=1 T[2,4]<=3 [].\n                Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=(-1) T[2,4]<=4 T[2,7]<=3\n                       T[4,7]<=4 [].\n              Pcase: h[1] > 5.\n                Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=4 T[5]<=2 T[6]<=0 T[7]<=0\n                       [].\n              Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[6]<=(-1) T[4,7]<=5 [].\n            Pcase: h[6] <= 5.\n              Pcase: h[2] > 6.\n                Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[4,6]<=5 T[4,7]<=3\n                       T[6,7]<=1 [].\n              Pcase: h[5] <= 5.\n                Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=4 T[5]<=2 T[6]<=1\n                       T[7]<=(-1) [].\n              Pcase: h[3] > 5.\n                Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[2,7]<=0 T[4,6]<=4 [].\n              Pcase: h[2] <= 5.\n                Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[2,7]<=1 T[4,6]<=3 [].\n              Pcase: s[7] > 7.\n                Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[5]<=2 T[7]<=(-1) T[4,6]<=4 [].\n              Pcase: h[4] > 5.\n                Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=2 T[5]<=2 T[6,7]<=1 [].\n              Pcase: f1[6] <= 5.\n                Reducible.\n              Pcase: f3[2] <= 5.\n                Reducible.\n              Pcase: h[5] <= 6.\n                Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=2 T[5]<=2 T[6]<=1 T[7]<=0\n                       [].\n              Pcase: h[1] > 5.\n                Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=3 T[5]<=2 T[6]<=1 T[7]<=0\n                       [].\n              Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=3 T[5]<=2 T[6]<=0 T[7]<=0 [].\n            Pcase: h[4] > 5.\n              Pcase: s[7] > 7.\n                Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=1 T[7]<=0 T[2,4]<=3 [].\n              Pcase: h[1] <= 5.\n                Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[2,4]<=3 T[6,7]<=1 [].\n              Pcase: h[2] > 5.\n                Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[7]<=1 T[4,6]<=3 [].\n              Pcase: h[3] > 5.\n                Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[7]<=1 T[4,6]<=3 [].\n              Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=1 T[5]<=2 T[6]<=1 T[7]<=1 [].\n            Pcase: s[7] > 7.\n              Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=0 T[7]<=0 T[2,4]<=4 [].\n            Pcase: h[1] <= 5.\n              Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=(-1) T[7]<=1 T[2,4]<=4 [].\n            Pcase: h[2] > 5.\n              Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[6]<=0 T[4,7]<=4 [].\n            Pcase: h[3] > 5.\n              Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[6]<=0 T[4,7]<=4 [].\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=2 T[5]<=2 T[6]<=0 T[7]<=1 [].\n          Pcase: s[4] > 7.\n            Similar to *L5_2[2].\n          Pcase L5_3: s[6] > 7.\n            Pcase: s[7] > 7.\n              Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=0 T[7]<=0 T[2,4]<=4 [].\n            Pcase: h[1] > 6.\n              Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=0 T[7]<=0 T[2,4]<=4 [].\n            Pcase: h[1] > 5.\n              Pcase: h[2] <= 5.\n                Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=0 T[7]<=0 T[2,4]<=4 [].\n              Pcase: h[3] <= 5.\n                Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=0 T[7]<=0 T[2,4]<=4 [].\n              Pcase: h[3] <= 6.\n                Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[5]<=2 T[6]<=0 T[4,7]<=3 [].\n              Pcase: h[2] > 6.\n                Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[6]<=0 T[4,7]<=4 [].\n              Pcase: h[4] > 5.\n                Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[5]<=2 T[6]<=0 T[4,7]<=3 [].\n              Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[6]<=0 T[4,7]<=4 [].\n            Pcase: h[2] <= 6.\n              Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=(-1) T[7]<=1 T[2,4]<=4 [].\n            Pcase: h[3] > 5.\n              Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=(-1) T[2,4]<=4 T[2,7]<=2\n                     T[4,7]<=5 [].\n            Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=(-1) T[7]<=1 T[2,4]<=4 [].\n          Pcase: s[7] > 7.\n            Similar to *L5_3[2].\n          Pcase L5_4: h[6] <= 5.\n            Pcase: h[2] <= 5.\n              Hubcap T[1]<=2 T[3]<=2 T[4]<=0 T[5]<=2 T[7]<=(-1) T[2,6]<=5 [].\n            Pcase: h[5] <= 5.\n              Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=1 T[7]<=(-1) T[2,4]<=4 [].\n            Pcase: h[1] <= 5.\n              Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=0 T[7]<=0 T[2,4]<=4 [].\n            Pcase: h[3] > 5.\n              Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[2,4]<=3 T[6,7]<=1 [].\n            Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=1 T[7]<=(-1) T[2,4]<=4 [].\n          Pcase: h[1] <= 5.\n            Similar to *L5_4[2].\n          Pcase: h[2] <= 5.\n            Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=0 T[7]<=0 T[2,4]<=4 [].\n          Pcase: h[5] <= 5.\n            Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=0 T[7]<=0 T[2,4]<=4 [].\n          Pcase L5_5: h[3] > 5.\n            Pcase: h[3] <= 6.\n              Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=1 T[5]<=2 T[6]<=1 T[7]<=1 [].\n            Pcase: h[2] > 6.\n              Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[7]<=1 T[4,6]<=3 [].\n            Pcase: h[4] > 5.\n              Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=1 T[5]<=2 T[6]<=1 T[7]<=1 [].\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=3 T[5]<=2 T[6]<=0 T[7]<=1 [].\n          Pcase: h[4] > 5.\n            Similar to *L5_5[2].\n          Pcase: f1[4] <= 5.\n            Reducible.\n          Pcase: f2[2] <= 5.\n            Reducible.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=2 T[5]<=2 T[6]<=0 T[7]<=0 [].\n        Pcase: s[2] > 7.\n          Pcase: s[4] > 8.\n            Hubcap T[1]<=3 T[3]<=2 T[4]<=0 T[5]<=2 T[6]<=0 T[2,7]<=3 [].\n          Pcase: s[4] <= 6.\n            Pcase: h[1] <= 5.\n              Reducible.\n            Pcase: h[4] > 5.\n              Hubcap T[1]<=2 T[2]<=(-1) T[3]<=2 T[4]<=4 T[5]<=3 T[6]<=(-1)\n                     T[7]<=1 [].\n            Hubcap T[1]<=2 T[2]<=(-2) T[3]<=3 T[4]<=5 T[7]<=1 T[5,6]<=1 [].\n          Pcase: h[1] <= 5.\n            Hubcap T[1]<=3 T[2]<=(-1) T[3]<=2 T[5]<=2 T[7]<=3 T[4,6]<=1 [].\n          Pcase: s[4] > 7.\n            Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[2,7]<=3 T[4,6]<=1 [].\n          Pcase: s[6] > 7.\n            Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=(-1) T[2,4]<=4 T[2,7]<=2\n                   T[4,7]<=5 [].\n          Pcase: h[7] <= 5.\n            Reducible.\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[7]<=1 T[4,6]<=3 [].\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[2,7]<=2 T[4,6]<=2 [].\n          Pcase: h[1] <= 6.\n            Reducible.\n          Pcase: s[2] > 8.\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[7]<=1 T[4,6]<=3 [].\n          Pcase: h[3] > 5.\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[7]<=1 T[4,6]<=3 [].\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=2 T[5]<=2 T[6]<=0 T[7]<=1 [].\n        Pcase: h[1] <= 5.\n          Pcase: s[2] <= 6.\n            Reducible.\n          Pcase: s[4] <= 6.\n            Reducible.\n          Pcase: h[2] <= 6.\n            Reducible.\n          Pcase: h[3] <= 5.\n            Reducible.\n          Pcase: f1[7] <= 5.\n            Reducible.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[5]<=2 T[7]<=2 T[4,6]<=1 [].\n        Pcase: s[4] <= 6.\n          Pcase: s[2] <= 6.\n            Reducible.\n          Pcase: h[2] <= 5.\n            Reducible.\n          Pcase: h[3] <= 5.\n            Reducible.\n          Pcase: s[6] <= 7.\n            Hubcap T[1]<=2 T[4]<=4 T[7]<=1 T[2,3]<=2 T[5,6]<=1 [].\n          Pcase: h[3] <= 6.\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=4 T[5]<=3 T[6]<=(-2) T[7]<=1 [].\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=4 T[5]<=3 T[6]<=(-2) T[7]<=1 [].\n          Hubcap T[1]<=2 T[2]<=(-2) T[3]<=3 T[4]<=5 T[5]<=3 T[6]<=(-2) T[7]<=1\n                 [].\n        Pcase: s[2] > 6.\n          Pcase: s[4] > 8.\n            Hubcap T[1]<=2 T[3]<=2 T[4]<=0 T[5]<=2 T[7]<=1 T[2,6]<=3 [].\n          Pcase: s[6] > 7.\n            Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=(-1) T[7]<=1 T[2,4]<=4 [].\n          Pcase: h[7] <= 5.\n            Reducible.\n          Pcase: h[2] <= 5.\n            Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[7]<=1 T[2,4]<=4 T[2,6]<=3 T[4,6]<=0\n                   [].\n          Pcase: s[4] > 7.\n            Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=0 T[7]<=1 T[2,4]<=3 [].\n          Pcase: h[3] <= 5.\n            Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=(-1) T[7]<=1 T[2,4]<=4 [].\n          Pcase: h[3] <= 6.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[5]<=2 T[7]<=1 T[4,6]<=2 [].\n          Pcase: h[2] > 6.\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[7]<=1 T[4,6]<=3 [].\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[5]<=2 T[7]<=1 T[4,6]<=2 [].\n          Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[7]<=1 T[4,6]<=3 [].\n        Pcase: s[4] <= 7.\n          Hubcap T[1]<=3 T[5]<=2 T[7]<=1 T[2,6]<=2 T[3,4]<=2 [].\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=2 T[2]<=4 T[3]<=3 T[4]<=(-1) T[5]<=2 T[6]<=(-1) T[7]<=1\n                 [].\n        Pcase: h[1] <= 6.\n          Reducible.\n        Pcase: f1[2] <= 5.\n          Reducible.\n        Pcase: h[3] > 5.\n          Hubcap T[1]<=3 T[2]<=4 T[3]<=2 T[4]<=(-1) T[5]<=2 T[6]<=(-2) T[7]<=1\n                 [].\n        Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=2 T[6]<=(-2) T[7]<=1 [].\n      Pcase: s[7] > 6.\n        Similar to *L3_1[2].\n      Pcase: s[2] <= 6.\n        Reducible.\n      Pcase: s[4] <= 6.\n        Reducible.\n      Pcase: h[6] <= 5.\n        Reducible.\n      Pcase: h[7] <= 5.\n        Reducible.\n      Pcase: h[1] <= 5.\n        Reducible.\n      Hubcap T[1]<=2 T[3]<=2 T[5]<=2 T[6]<=1 T[7]<=1 T[2,4]<=2 [].\n    Pcase: s[6] <= 5.\n      Similar to L2_1[5].\n    Pcase: s[2] <= 6.\n      Pcase L3_1: s[4] > 6.\n        Pcase L4_1: h[2] > 5.\n          Pcase: s[6] > 8.\n            Hubcap T[1]<=2 T[2]<=4 T[5]<=0 T[6]<=0 T[7]<=1 T[3,4]<=3 [].\n          Pcase: s[7] > 7.\n            Hubcap T[1]<=2 T[2]<=4 T[7]<=(-1) T[3,6]<=4 T[4,5]<=1 [].\n          Pcase: f1[2] <= 5.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4,5]<=1 T[6,7]<=3 [].\n          Pcase: h[7] <= 5.\n            Pcase: s[6] <= 6.\n              Reducible.\n            Pcase: s[7] > 6.\n              Hubcap T[1]<=2 T[2]<=4 T[5]<=0 T[3,4]<=3 T[6,7]<=1 [].\n            Pcase: h[1] <= 5.\n              Reducible.\n            Pcase: s[4] > 7.\n              Hubcap T[1]<=2 T[2]<=4 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=1 T[7]<=1 [].\n            Pcase: s[5] <= 6.\n              Hubcap T[1]<=2 T[3]<=3 T[4]<=0 T[5]<=0 T[7]<=1 T[2,6]<=4 [].\n            Pcase: s[6] > 7.\n              Hubcap T[1]<=2 T[2]<=4 T[5]<=0 T[6]<=0 T[7]<=1 T[3,4]<=3 [].\n            Hubcap T[1]<=2 T[2]<=4 T[5]<=0 T[6]<=0 T[7]<=1 T[3,4]<=3 [].\n          Pcase: s[6] > 7.\n            Hubcap T[1]<=2 T[2]<=4 T[5]<=0 T[6]<=0 T[7]<=1 T[3,4]<=3 [].\n          Pcase: h[1] <= 5.\n            Pcase: s[7] <= 6.\n              Reducible.\n            Pcase: f2[7] <= 5.\n              Reducible.\n            Pcase: s[4] > 7.\n              Hubcap T[1]<=2 T[2]<=4 T[3]<=3 T[4]<=(-1) T[5]<=1 T[6]<=1 T[7]<=0 [].\n            Pcase: s[5] > 6.\n              Hubcap T[1]<=2 T[2]<=4 T[3]<=3 T[6]<=0 T[7]<=0 T[4,5]<=1 [].\n            Hubcap T[1]<=2 T[2]<=4 T[4]<=0 T[6]<=1 T[7]<=0 T[3,5]<=3 [].\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=2 T[2]<=4 T[7]<=(-1) T[3,6]<=4 T[4,5]<=1 [].\n          Pcase: s[4] > 7.\n            Pcase: s[6] > 6.\n              Hubcap T[1]<=2 T[2]<=4 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=1 T[7]<=1 [].\n            Pcase: s[5] > 7.\n              Hubcap T[1]<=2 T[2]<=4 T[3]<=3 T[4]<=(-1) T[5]<=(-1) T[6,7]<=3 [].\n            Pcase: s[5] > 6.\n              Pcase: h[3] > 5.\n                Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[4]<=(-1) T[5]<=0 T[6]<=1\n                       T[7]<=3 [].\n              Pcase: h[4] > 5.\n                Hubcap T[1]<=2 T[2]<=3 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6,7]<=3 [].\n              Hubcap T[1]<=2 T[2]<=4 T[3]<=3 T[4]<=(-2) T[5]<=0 T[6,7]<=3 [].\n            Pcase: h[3] > 5.\n              Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[4]<=(-1) T[5]<=1 T[6,7]<=3 [].\n            Hubcap T[1]<=2 T[2]<=4 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6,7]<=2 [].\n          Pcase: h[3] > 6.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4,5]<=1 T[6,7]<=3 [].\n          Pcase: h[7] > 6.\n            Hubcap T[1]<=2 T[7]<=1 T[3,6]<=3 T[2,4]<=4 T[2,5]<=4 T[4,5]<=1 [].\n          Pcase: f1[4] <= 5.\n            Pcase: h[4] <= 6.\n              Reducible.\n            Pcase: s[5] > 7.\n              Hubcap T[1]<=2 T[2]<=3 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6,7]<=3 [].\n            Pcase: s[5] <= 6.\n              Hubcap T[1]<=2 T[2]<=3 T[4]<=(-1) T[3,5]<=3 T[6,7]<=3 [].\n            Pcase: s[6] > 6.\n              Hubcap T[1]<=2 T[2]<=3 T[3]<=3 T[4]<=0 T[5]<=0 T[6]<=1 T[7]<=1 [].\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=3 T[4,5]<=(-1) T[6,7]<=3 [].\n          Pcase: f1[7] <= 5.\n            Pcase: h[1] <= 6.\n              Reducible.\n            Pcase: s[6] > 6.\n              Hubcap T[1]<=2 T[2]<=4 T[5]<=0 T[6]<=0 T[7]<=1 T[3,4]<=3 [].\n            Pcase: f1[6] <= 5.\n              Reducible.\n            Pcase: s[5] > 6.\n              Hubcap T[1]<=2 T[3]<=3 T[4]<=0 T[6]<=1 T[7]<=1 T[2,5]<=3 [].\n            Hubcap T[1]<=2 T[2]<=3 T[4]<=(-1) T[6]<=2 T[7]<=1 T[3,5]<=3 [].\n          Pcase: s[6] > 6.\n            Pcase: h[3] > 5.\n              Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[4]<=1 T[5]<=0 T[6]<=1 T[7]<=1 [].\n            Pcase: h[4] > 5.\n              Hubcap T[1]<=2 T[2]<=3 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=1 T[7]<=1 [].\n            Hubcap T[1]<=2 T[2]<=4 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=1 T[7]<=1 [].\n          Pcase: s[5] <= 6.\n            Hubcap T[1]<=2 T[2]<=3 T[4]<=(-1) T[3,5]<=3 T[6,7]<=3 [].\n          Pcase: h[3] > 5.\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[4]<=0 T[5]<=0 T[6,7]<=3 [].\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6,7]<=3 [].\n          Hubcap T[1]<=2 T[2]<=4 T[3]<=3 T[4]<=(-1) T[5]<=(-1) T[6,7]<=3 [].\n        Pcase: f1[2] <= 5.\n          Reducible.\n        Pcase L4_2: s[5] > 6.\n          Pcase: f1[2] <= 6.\n            Pcase: h[3] <= 6.\n              Reducible.\n            Pcase: s[7] > 6.\n              Similar to *L4_1[4].\n            Pcase: h[1] <= 6.\n              Reducible.\n            Pcase: s[4] > 7.\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=(-1) T[5]<=1 T[6]<=1 T[7]<=1 [].\n            Pcase: s[5] > 7.\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=0 T[5]<=0 T[6]<=1 T[7]<=1 [].\n            Pcase: s[6] > 6.\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=1 T[5]<=0 T[6]<=0 T[7]<=1 [].\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=1 [].\n          Pcase: s[7] > 7.\n            Pcase: h[3] > 5.\n              Similar to *L4_1[4].\n            Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[6]<=0 T[7]<=(-1) T[4,5]<=0 [].\n          Pcase: h[3] > 6.\n            Pcase: s[7] > 6.\n              Similar to *L4_1[4].\n            Pcase: h[1] <= 6.\n              Reducible.\n            Pcase: s[4] > 7.\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=(-1) T[5]<=1 T[6]<=1 T[7]<=1 [].\n            Pcase: s[5] > 7.\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=0 T[5]<=0 T[6]<=1 T[7]<=1 [].\n            Pcase: s[6] > 6.\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=1 T[5]<=0 T[6]<=0 T[7]<=1 [].\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=1 [].\n          Pcase: h[1] <= 5.\n            Pcase: s[7] <= 6.\n              Reducible.\n            Pcase: h[4] <= 5.\n              Reducible.\n            Pcase: f2[7] <= 5.\n              Reducible.\n            Pcase: h[3] > 5.\n              Similar to *L4_1[4].\n            Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-1) T[5]<=1 T[6]<=0 T[7]<=(-1)\n                   [].\n          Pcase: h[1] <= 6.\n            Pcase: s[7] <= 6.\n              Reducible.\n            Pcase: f2[7] <= 5.\n              Reducible.\n            Pcase: h[3] > 5.\n              Similar to *L4_1[4].\n            Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[6]<=0 T[7]<=(-1) T[4,5]<=0 [].\n          Pcase: s[7] > 6.\n            Pcase: h[3] > 5.\n              Similar to *L4_1[4].\n            Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[6]<=0 T[7]<=(-1) T[4,5]<=0 [].\n          Pcase: s[6] > 6.\n            Pcase: h[4] > 5.\n              Hubcap T[1]<=3 T[2]<=4 T[5]<=0 T[6]<=0 T[7]<=1 T[3,4]<=2 [].\n            Pcase: s[4] > 7.\n              Pcase: s[6] > 7.\n                Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=(-1)\n                       T[7]<=1 [].\n              Pcase: h[3] > 5.\n                Hubcap T[1]<=3 T[2]<=4 T[3]<=2 T[4]<=(-1) T[5]<=0 T[6]<=0\n                       T[7]<=1 [].\n              Pcase: h[7] > 5.\n                Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=(-1)\n                       T[7]<=1 [].\n              Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=(-1)\n                     T[7]<=1 [].\n            Pcase: f1[4] <= 5.\n              Reducible.\n            Pcase: h[3] > 5.\n              Pcase: s[5] > 7.\n                Hubcap T[1]<=3 T[2]<=4 T[3]<=2 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=1\n                       [].\n              Pcase: s[6] > 7.\n                Hubcap T[1]<=3 T[2]<=4 T[3]<=2 T[4]<=1 T[5]<=0 T[6]<=(-1)\n                       T[7]<=1 [].\n              Pcase: h[5] > 5.\n                Hubcap T[1]<=3 T[2]<=4 T[3]<=2 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=1\n                       [].\n              Pcase: h[7] > 5.\n                Hubcap T[1]<=3 T[2]<=4 T[3]<=2 T[4]<=1 T[5]<=0 T[6]<=(-1)\n                       T[7]<=1 [].\n              Hubcap T[1]<=3 T[2]<=4 T[3]<=2 T[4]<=1 T[5]<=0 T[6]<=(-1) T[7]<=1 [].\n            Pcase: s[6] > 7.\n              Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=(-1)\n                     T[7]<=1 [].\n            Pcase: h[7] > 5.\n              Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=(-1)\n                     T[7]<=1 [].\n            Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=(-1) T[7]<=1\n                   [].\n          Pcase: h[7] <= 5.\n            Reducible.\n          Pcase: s[4] > 7.\n            Pcase: s[5] > 7.\n              Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-1) T[5]<=(-1) T[6]<=0\n                     T[7]<=1 [].\n            Pcase: h[3] > 5.\n              Hubcap T[1]<=3 T[2]<=4 T[3]<=2 T[4]<=(-1) T[5]<=0 T[6]<=0 T[7]<=1 [].\n            Pcase: h[4] > 5.\n              Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=0 T[7]<=1 [].\n            Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=0 T[6]<=0 T[7]<=1 [].\n          Pcase: h[3] > 5.\n            Hubcap T[1]<=3 T[2]<=4 T[3]<=2 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=1 [].\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=0 T[7]<=1 [].\n          Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-1) T[5]<=(-1) T[6]<=0 T[7]<=1\n                 [].\n        Pcase: f1[2] <= 6.\n          Pcase: h[3] <= 6.\n            Reducible.\n          Pcase: s[7] > 6.\n            Similar to *L4_1[4].\n          Pcase: h[1] <= 6.\n            Reducible.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=0 T[5]<=0 T[6]<=1 T[7]<=1 [].\n        Pcase: s[6] <= 6.\n          Pcase: h[6] <= 5.\n            Reducible.\n          Pcase: s[7] > 6.\n            Pcase: h[3] > 5.\n              Similar to *L4_1[4].\n            Pcase: h[6] > 6.\n              Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[5]<=0 T[6]<=0 T[4,7]<=(-1) [].\n            Pcase: f1[5] <= 5.\n              Reducible.\n            Pcase: f1[6] <= 5.\n              Reducible.\n            Pcase L6_1: s[4] > 7.\n              Pcase: s[7] > 7.\n                Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-1) T[7]<=(-1) T[5,6]<=1\n                       [].\n              Pcase: h[7] <= 5.\n                Reducible.\n              Pcase: h[4] <= 5.\n                Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=1\n                       T[7]<=(-1) [].\n              Pcase: h[5] > 5.\n                Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=0\n                       T[7]<=0 [].\n              Pcase: h[1] > 5.\n                Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=1\n                       T[7]<=(-1) [].\n              Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=1\n                     T[7]<=(-1) [].\n            Pcase: s[7] > 7.\n              Similar to *L6_1[4].\n            Pcase: h[5] <= 5.\n              Reducible.\n            Pcase: h[7] <= 5.\n              Reducible.\n            Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[5]<=0 T[6]<=0 T[4,7]<=(-1) [].\n          Pcase: h[7] <= 5.\n            Reducible.\n          Pcase: h[1] <= 6.\n            Reducible.\n          Pcase: s[4] <= 7.\n            Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=0 T[7]<=1 [].\n          Pcase: h[3] > 5.\n            Hubcap T[1]<=3 T[2]<=4 T[3]<=2 T[4]<=(-1) T[5]<=0 T[6]<=0 T[7]<=1 [].\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=0 T[7]<=1 [].\n          Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-2) T[5]<=0 T[6]<=0 T[7]<=1 [].\n        Pcase: s[7] > 6.\n          Similar to *L4_2[4].\n        Pcase: h[1] <= 6.\n          Reducible.\n        Pcase: s[4] > 7.\n          Pcase: s[6] > 7.\n            Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=(-1) T[7]<=1\n                   [].\n          Pcase: h[6] <= 5.\n            Reducible.\n          Pcase: h[3] > 5.\n            Hubcap T[1]<=3 T[2]<=4 T[3]<=2 T[4]<=(-1) T[5]<=0 T[6]<=0 T[7]<=1 [].\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=0 T[7]<=1 [].\n          Pcase: h[7] > 5.\n            Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=(-1) T[7]<=1\n                   [].\n          Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=(-1) T[7]<=1\n                 [].\n        Pcase: h[5] <= 5.\n          Reducible.\n        Pcase: h[3] > 5.\n          Hubcap T[1]<=3 T[2]<=4 T[3]<=2 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=1 [].\n        Pcase: h[4] > 5.\n          Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=0 T[7]<=1 [].\n        Hubcap T[1]<=3 T[2]<=5 T[3]<=3 T[4]<=(-1) T[5]<=0 T[6]<=(-1) T[7]<=1 [].\n      Pcase: s[7] > 6.\n        Similar to *L3_1[4].\n      Pcase: h[4] <= 5.\n        Reducible.\n      Pcase: h[1] <= 5.\n        Reducible.\n      Pcase L3_2: s[5] > 6.\n        Pcase: s[6] > 6.\n          Pcase: f1[2] <= 5.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=1 T[5]<=1 T[6]<=1 T[7]<=1 [].\n          Pcase L5_1: h[4] <= 6.\n            Pcase: h[3] <= 5.\n              Reducible.\n            Pcase: f1[4] <= 5.\n              Reducible.\n            Pcase: s[5] > 7.\n              Hubcap T[1]<=3 T[3]<=2 T[4]<=1 T[5]<=0 T[7]<=1 T[2,6]<=3 [].\n            Pcase: s[6] > 7.\n              Hubcap T[1]<=3 T[3]<=2 T[4]<=1 T[5]<=1 T[7]<=1 T[2,6]<=2 [].\n            Pcase: h[2] > 5.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=1 T[5]<=1 T[6]<=1 T[7]<=1 [].\n            Pcase: h[1] <= 6.\n              Reducible.\n            Pcase: h[5] > 6.\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=1 T[5]<=(-1) T[6]<=0 T[7]<=1 [].\n            Pcase: h[5] <= 5.\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=1 T[5]<=0 T[6]<=0 T[7]<=1 [].\n            Pcase: h[6] <= 6.\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=1 T[7]<=1 T[5,6]<=0 [].\n            Pcase: h[7] > 5.\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=1 T[5]<=1 T[6]<=(-1) T[7]<=1 [].\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=1 T[5]<=1 T[6]<=(-1) T[7]<=1 [].\n          Pcase: h[1] <= 6.\n            Similar to *L5_1[4].\n          Pcase: f1[2] <= 6.\n            Pcase: s[5] > 7.\n              Hubcap T[2]<=3 T[4]<=1 T[7]<=1 T[1,6]<=3 T[3,5]<=2 [].\n            Pcase: s[6] > 7.\n              Hubcap T[2]<=3 T[4]<=1 T[7]<=1 T[1,6]<=2 T[3,5]<=3 [].\n            Pcase: h[5] > 6.\n              Hubcap T[2]<=3 T[4]<=1 T[5]<=(-1) T[6]<=1 T[7]<=1 T[1,3]<=5 [].\n            Pcase: h[5] <= 5.\n              Hubcap T[2]<=3 T[4]<=1 T[7]<=1 T[1,6]<=3 T[3,5]<=2 [].\n            Pcase: h[3] <= 5.\n              Hubcap T[1]<=2 T[2]<=3 T[3]<=3 T[4]<=1 T[5]<=(-1) T[6]<=1 T[7]<=1 [].\n            Pcase: h[2] > 5.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=1 T[5]<=1 T[6]<=1 T[7]<=1 [].\n            Pcase: h[3] <= 6.\n              Reducible.\n            Pcase: h[6] <= 6.\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=1 T[7]<=1 T[5,6]<=0 [].\n            Pcase: h[7] > 5.\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=1 T[5]<=1 T[6]<=(-1) T[7]<=1 [].\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=1 T[5]<=1 T[6]<=(-1) T[7]<=1 [].\n          Pcase L5_2: s[5] > 7.\n            Pcase: s[6] > 7.\n              Hubcap T[1]<=3 T[4]<=1 T[7]<=1 T[2,6]<=3 T[3,5]<=2 [].\n            Pcase: h[2] > 5.\n              Hubcap T[1]<=2 T[2]<=3 T[4]<=1 T[6]<=1 T[7]<=1 T[3,5]<=2 [].\n            Pcase: h[3] > 5.\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=1 T[5]<=0 T[6]<=0 T[7]<=1 [].\n            Pcase: h[7] > 5.\n              Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=1 T[5]<=(-1) T[6]<=(-1)\n                     T[7]<=1 [].\n            Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=1 T[5]<=(-1) T[6]<=(-1) T[7]<=1\n                   [].\n          Pcase: s[6] > 7.\n            Similar to *L5_2[4].\n          Pcase L5_3: h[5] <= 5.\n            Pcase: f1[5] <= 5.\n              Reducible.\n            Pcase: h[2] > 5.\n              Hubcap T[1]<=2 T[2]<=3 T[4]<=1 T[6]<=1 T[7]<=1 T[3,5]<=2 [].\n            Pcase: h[3] > 5.\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=1 T[5]<=0 T[6]<=0 T[7]<=1 [].\n            Pcase: h[7] > 5.\n              Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=1 T[5]<=(-1) T[6]<=(-1)\n                     T[7]<=1 [].\n            Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=1 T[5]<=(-1) T[6]<=(-1) T[7]<=1\n                   [].\n          Pcase: h[7] <= 5.\n            Similar to *L5_3[4].\n          Pcase: h[6] <= 5.\n            Hubcap T[1]<=3 T[4]<=1 T[7]<=1 T[2,6]<=3 T[3,5]<=2 [].\n          Pcase L5_4: h[2] > 5.\n            Pcase: h[3] > 5.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=1 T[5]<=1 T[6]<=1 T[7]<=1 [].\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=3 T[4]<=1 T[5]<=(-1) T[6]<=1 T[7]<=1 [].\n          Pcase: h[3] > 5.\n            Similar to *L5_4[4].\n          Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=1 T[5]<=(-1) T[6]<=(-1) T[7]<=1\n                 [].\n        Pcase: h[7] <= 5.\n          Reducible.\n        Pcase: s[5] > 7.\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=3 T[4]<=1 T[5]<=(-2) T[6,7]<=3 [].\n          Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=1 T[5]<=(-2) T[6]<=0 T[7]<=1 [].\n        Pcase: h[5] <= 5.\n          Reducible.\n        Pcase: h[6] <= 5.\n          Reducible.\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=2 T[2]<=3 T[4]<=1 T[3,5]<=2 T[6,7]<=2 [].\n        Pcase: h[1] <= 6.\n          Reducible.\n        Pcase: f1[2] <= 5.\n          Reducible.\n        Pcase: h[3] > 5.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=1 T[5]<=0 T[6]<=0 T[7]<=1 [].\n        Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=1 T[5]<=(-2) T[6]<=0 T[7]<=1 [].\n      Pcase: s[6] > 6.\n        Similar to *L3_2[4].\n      Reducible.\n    Pcase L2_2: s[5] > 6.\n      Pcase L3_1: s[4] > 6.\n        Pcase: s[6] > 6.\n          Pcase: s[7] > 7.\n            Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=0 T[7]<=0 T[2,4]<=5 [].\n          Pcase: s[7] > 6.\n            Pcase: s[2] > 8.\n              Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=3 T[5]<=0 T[6]<=0 T[7]<=3 [].\n            Pcase: s[4] > 7.\n              Hubcap T[1]<=2 T[3]<=2 T[4]<=0 T[5]<=0 T[6]<=0 T[2,7]<=5 [].\n            Pcase: h[4] > 6.\n              Hubcap T[1]<=2 T[3]<=2 T[4]<=1 T[5]<=0 T[6]<=0 T[2,7]<=5 [].\n            Pcase: h[1] > 6.\n              Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=0 T[7]<=1 T[2,4]<=5 [].\n            Pcase: f1[4] > 5.\n              Pcase: s[2] > 7.\n                Hubcap T[1]<=2 T[3]<=2 T[4]<=2 T[5]<=0 T[6]<=0 T[2,7]<=4 [].\n              Pcase: s[5] > 7.\n                Hubcap T[1]<=2 T[3]<=2 T[4]<=1 T[5]<=0 T[6]<=0 T[2,7]<=5 [].\n              Pcase: h[3] > 5.\n                Hubcap T[1]<=2 T[3]<=2 T[4]<=2 T[5]<=0 T[6]<=0 T[2,7]<=4 [].\n              Pcase: f2[7] <= 5.\n                Reducible.\n              Pcase: s[6] > 7.\n                Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=0 T[7]<=1 T[2,4]<=5 [].\n              Pcase: h[2] > 5.\n                Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=0 T[7]<=2 T[2,4]<=4 [].\n              Hubcap T[1]<=2 T[2]<=4 T[3]<=2 T[4]<=1 T[5]<=0 T[6]<=0 T[7]<=1 [].\n            Pcase: f2[4] <= 5.\n              Reducible.\n            Pcase: s[5] > 7.\n              Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=0 T[7]<=3 T[2,4]<=3 [].\n            Pcase: s[6] > 7.\n              Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=0 T[7]<=2 T[2,4]<=4 [].\n            Pcase: h[2] > 6.\n              Hubcap T[1]<=2 T[3]<=2 T[4]<=3 T[5]<=0 T[6]<=0 T[2,7]<=3 [].\n            Pcase: s[2] <= 7.\n              Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=0 T[7]<=2 T[2,4]<=4 [].\n            Pcase: h[2] > 5.\n              Hubcap T[1]<=2 T[3]<=2 T[4]<=3 T[5]<=0 T[6]<=0 T[2,7]<=3 [].\n            Pcase: h[3] > 5.\n              Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=0 T[7]<=3 T[2,4]<=3 [].\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=2 T[5]<=0 T[6]<=0 T[7]<=2 [].\n          Pcase: h[1] <= 5.\n            Hubcap T[1]<=3 T[3]<=2 T[4]<=2 T[5]<=0 T[2,6]<=1 T[2,7]<=2 T[6,7]<=4\n                   [].\n          Pcase: s[2] > 8.\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=3 T[5]<=0 T[6,7]<=3 [].\n          Pcase: s[4] > 7.\n            Hubcap T[1]<=2 T[3]<=2 T[4]<=0 T[5]<=0 T[7]<=2 T[2,6]<=4 [].\n          Pcase: s[6] > 8.\n            Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=(-1) T[7]<=2 T[2,4]<=5 [].\n          Pcase: h[7] > 6.\n            Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=(-1) T[7]<=2 T[2,4]<=5 [].\n          Pcase: h[1] <= 6.\n            Pcase: f1[7] <= 5.\n              Reducible.\n            Pcase: s[6] > 7.\n              Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=0 T[7]<=2 T[2,4]<=4 [].\n            Pcase: h[2] <= 5.\n              Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=1 T[7]<=2 T[2,4]<=3 [].\n            Pcase: s[2] > 7.\n              Hubcap T[1]<=2 T[3]<=2 T[4]<=3 T[5]<=0 T[7]<=1 T[2,6]<=2 [].\n            Pcase: h[3] > 6.\n              Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=2 T[7]<=1 T[2,4]<=3 [].\n            Pcase: h[3] <= 5.\n              Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=1 T[7]<=1 T[2,4]<=4 [].\n            Hubcap T[1]<=2 T[3]<=2 T[4]<=2 T[5]<=0 T[7]<=1 T[2,6]<=3 [].\n          Pcase: s[6] > 7.\n            Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=0 T[7]<=1 T[2,4]<=5 [].\n          Pcase: h[4] > 6.\n            Hubcap T[1]<=2 T[3]<=2 T[4]<=1 T[5]<=0 T[7]<=1 T[2,6]<=4 [].\n          Pcase: f2[6] > 6.\n            Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=0 T[7]<=1 T[2,4]<=5 [].\n          Pcase: f1[4] > 5.\n            Pcase: s[2] > 7.\n              Hubcap T[1]<=2 T[3]<=2 T[4]<=2 T[5]<=0 T[7]<=1 T[2,6]<=3 [].\n            Pcase: s[5] > 7.\n              Hubcap T[1]<=2 T[3]<=2 T[4]<=1 T[5]<=0 T[7]<=1 T[2,6]<=4 [].\n            Pcase: h[2] <= 5.\n              Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=0 T[7]<=1 T[2,4]<=5 [].\n            Pcase: h[3] > 5.\n              Hubcap T[1]<=2 T[3]<=2 T[4]<=2 T[5]<=0 T[7]<=1 T[2,6]<=3 [].\n            Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=1 T[7]<=1 T[2,4]<=4 [].\n          Pcase: f2[4] <= 5.\n            Reducible.\n          Pcase: s[5] > 7.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=2 T[5]<=0 T[6]<=2 T[7]<=1 [].\n          Pcase: s[2] <= 7.\n            Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=2 T[7]<=1 T[2,4]<=3 [].\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=2 T[3]<=2 T[4]<=3 T[5]<=0 T[7]<=1 T[2,6]<=2 [].\n          Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=2 T[7]<=1 T[2,4]<=3 [].\n        Pcase: s[7] > 6.\n          Pcase: s[2] > 8.\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[6]<=0 T[4,5]<=3 T[4,7]<=6 T[5,7]<=4\n                   [].\n          Pcase: h[7] <= 5.\n            Pcase: s[4] > 7.\n              Hubcap T[1]<=2 T[3]<=2 T[4]<=0 T[5]<=2 T[6]<=0 T[2,7]<=4 [].\n            Pcase: s[5] > 7.\n              Hubcap T[1]<=2 T[3]<=2 T[4]<=2 T[5]<=0 T[6]<=0 T[2,7]<=4 [].\n            Pcase: h[4] > 6.\n              Hubcap T[1]<=2 T[3]<=2 T[6]<=0 T[2,7]<=4 T[4,5]<=2 [].\n            Pcase: s[2] > 7.\n              Pcase: s[7] > 7.\n                Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[6]<=0 T[7]<=0 T[4,5]<=3 [].\n              Pcase: h[2] > 5.\n                Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[6]<=0 T[4,5]<=3 T[4,7]<=6\n                       T[5,7]<=4 [].\n              Pcase: h[3] <= 5.\n                Reducible.\n              Pcase: f1[2] <= 5.\n                Reducible.\n              Pcase: h[3] > 6.\n                Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[6]<=0 T[4,5]<=3 T[4,7]<=6\n                       T[5,7]<=4 [].\n              Hubcap T[1]<=2 T[3]<=2 T[6]<=0 T[2,7]<=4 T[4,5]<=2 [].\n            Pcase: s[7] > 7.\n              Pcase: h[2] > 5.\n                Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[6]<=0 T[7]<=0 T[4,5]<=3 [].\n              Pcase: f1[4] <= 5.\n                Reducible.\n              Pcase: h[3] > 5.\n                Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[6]<=0 T[7]<=0 T[4,5]<=3 [].\n              Hubcap T[1]<=2 T[2]<=4 T[3]<=2 T[6]<=0 T[7]<=0 T[4,5]<=2 [].\n            Pcase: h[2] <= 5.\n              Reducible.\n            Pcase: h[3] <= 5.\n              Reducible.\n            Pcase: h[2] > 6.\n              Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[6]<=0 T[4,5]<=3 T[4,7]<=6\n                     T[5,7]<=4 [].\n            Hubcap T[1]<=2 T[3]<=2 T[6]<=0 T[2,4]<=3 T[5,7]<=3 [].\n          Pcase: s[2] > 7.\n            Pcase: s[4] > 7.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=0 T[6]<=0 T[5,7]<=4 [].\n            Pcase: s[5] > 7.\n              Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=0 T[7]<=3 T[2,4]<=3 [].\n            Pcase: s[7] > 7.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[6]<=0 T[7]<=0 T[4,5]<=3 [].\n            Pcase: h[2] > 5.\n              Hubcap T[1]<=2 T[3]<=2 T[6]<=0 T[2,7]<=3 T[4,5]<=3 [].\n            Pcase: h[4] > 6.\n              Hubcap T[1]<=2 T[3]<=2 T[6]<=0 T[2,7]<=4 T[4,5]<=2 [].\n            Pcase: h[6] <= 5.\n              Hubcap T[1]<=2 T[3]<=2 T[4]<=1 T[6]<=0 T[2,5]<=3 T[2,7]<=4\n                     T[5,7]<=4 [].\n            Pcase: h[4] > 5.\n              Hubcap T[1]<=2 T[3]<=2 T[6]<=0 T[2,7]<=4 T[4,5]<=2 [].\n            Pcase: h[3] <= 5.\n              Hubcap T[1]<=2 T[3]<=2 T[4]<=2 T[5]<=1 T[6]<=0 T[2,7]<=3 [].\n            Pcase: h[5] > 5.\n              Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[6]<=0 T[7]<=3 T[4,5]<=2 [].\n            Pcase: h[6] > 6.\n              Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=0 T[7]<=3 T[2,4]<=3 [].\n            Pcase: h[7] > 6.\n              Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[6]<=0 T[7]<=2 T[4,5]<=3 [].\n            Pcase: h[1] > 5.\n              Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=3 T[5]<=1 T[6]<=0 T[7]<=1 [].\n            Pcase: h[3] <= 6.\n              Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[6]<=0 T[7]<=3 T[4,5]<=2 [].\n            Pcase: f1[2] > 5.\n              Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[6]<=0 T[7]<=3 T[4,5]<=3 [].\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[6]<=0 T[7]<=3 T[4,5]<=2 [].\n          Pcase: h[2] <= 5.\n            Pcase: s[4] > 7.\n              Hubcap T[1]<=2 T[2]<=4 T[3]<=2 T[4]<=0 T[6]<=0 T[5,7]<=2 [].\n            Pcase: s[5] > 7.\n              Hubcap T[1]<=2 T[2]<=4 T[3]<=2 T[4]<=1 T[5]<=0 T[6]<=0 T[7]<=1 [].\n            Pcase: h[4] > 5.\n              Hubcap T[1]<=2 T[2]<=4 T[3]<=2 T[4]<=0 T[6]<=0 T[5,7]<=2 [].\n            Pcase: f1[4] <= 5.\n              Reducible.\n            Pcase: s[7] > 7.\n              Hubcap T[1]<=2 T[3]<=2 T[6]<=0 T[7]<=0 T[2,4]<=5 T[2,5]<=5\n                     T[4,5]<=3 [].\n            Pcase: h[6] > 6.\n              Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=0 T[7]<=1 T[2,4]<=5 [].\n            Pcase: h[6] <= 5.\n              Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[4]<=1 T[6]<=0 T[5,7]<=2 [].\n            Pcase: h[3] > 5.\n              Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[4]<=1 T[5]<=1 T[6]<=0 T[7]<=1 [].\n            Pcase: f1[2] <= 5.\n              Reducible.\n            Pcase: h[1] > 5.\n              Hubcap T[1]<=2 T[2]<=4 T[3]<=2 T[4]<=1 T[5]<=1 T[6]<=0 T[7]<=0 [].\n            Pcase: f2[2] <= 5.\n              Reducible.\n            Pcase: f2[7] <= 5.\n              Reducible.\n            Pcase: f1[5] <= 5.\n              Hubcap T[1]<=2 T[2]<=4 T[3]<=2 T[4]<=1 T[5]<=0 T[6]<=0 T[7]<=1 [].\n            Pcase: f2[5] > 5.\n              Hubcap T[1]<=2 T[2]<=4 T[3]<=2 T[4]<=1 T[5]<=0 T[6]<=0 T[7]<=1 [].\n            Hubcap T[1]<=2 T[2]<=4 T[3]<=2 T[4]<=1 T[5]<=0 T[6]<=0 T[7]<=1 [].\n          Pcase: s[7] > 7.\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[6]<=0 T[7]<=0 T[4,5]<=3 [].\n          Pcase: h[1] > 6.\n            Hubcap T[1]<=2 T[3]<=2 T[6]<=0 T[2,4]<=4 T[5,7]<=2 [].\n          Pcase: h[3] > 5.\n            Pcase: s[4] > 7.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=0 T[6]<=0 T[5,7]<=4 [].\n            Pcase: s[5] > 7.\n              Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=0 T[7]<=3 T[2,4]<=3 [].\n            Pcase: h[4] > 6.\n              Hubcap T[1]<=2 T[3]<=2 T[6]<=0 T[2,7]<=4 T[4,5]<=2 [].\n            Pcase: h[7] > 6.\n              Hubcap T[1]<=2 T[3]<=2 T[6]<=0 T[2,7]<=3 T[4,5]<=3 [].\n            Pcase: h[1] > 5.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[6]<=0 T[7]<=1 T[4,5]<=3 [].\n            Pcase: h[3] <= 6.\n              Hubcap T[1]<=2 T[3]<=2 T[6]<=0 T[2,7]<=4 T[4,5]<=2 [].\n            Pcase: h[2] > 6.\n              Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[6]<=0 T[7]<=3 T[4,5]<=3 [].\n            Pcase: f2[7] <= 5.\n              Reducible.\n            Pcase: h[4] > 5.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[6]<=0 T[7]<=2 T[4,5]<=2 [].\n            Pcase: h[5] > 5.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[6]<=0 T[7]<=2 T[4,5]<=2 [].\n            Pcase: h[6] > 6.\n              Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=0 T[7]<=2 T[2,4]<=4 [].\n            Pcase: h[6] <= 5.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=1 T[5]<=1 T[6]<=0 T[7]<=2 [].\n            Pcase: f1[2] > 5.\n              Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[6]<=0 T[7]<=2 T[4,5]<=3 [].\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[6]<=0 T[7]<=2 T[4,5]<=2 [].\n          Pcase: f2[7] <= 5.\n            Reducible.\n          Pcase: s[4] > 7.\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[4]<=0 T[6]<=0 T[5,7]<=3 [].\n          Pcase: s[5] > 7.\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[4]<=1 T[5]<=0 T[6]<=0 T[7]<=2 [].\n          Pcase: h[6] > 6.\n            Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=0 T[7]<=2 T[2,4]<=4 [].\n          Pcase: h[6] <= 5.\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[4]<=0 T[6]<=0 T[5,7]<=3 [].\n          Pcase: h[7] > 6.\n            Hubcap T[1]<=2 T[3]<=2 T[5]<=1 T[6]<=0 T[7]<=1 T[2,4]<=4 [].\n          Pcase: h[1] > 5.\n            Hubcap T[1]<=2 T[3]<=2 T[5]<=1 T[6]<=0 T[7]<=1 T[2,4]<=4 [].\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[6]<=0 T[7]<=2 T[4,5]<=1 [].\n          Pcase: f1[4] <= 5.\n            Reducible.\n          Pcase: h[2] <= 6.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[6]<=0 T[7]<=2 T[4,5]<=2 [].\n          Pcase: f1[2] <= 5.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[6]<=0 T[7]<=2 T[4,5]<=2 [].\n          Pcase: f1[5] <= 5.\n            Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[6]<=0 T[7]<=2 T[2,4]<=4 [].\n          Pcase: f1[7] > 5.\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[4]<=1 T[5]<=1 T[6]<=0 T[7]<=1 [].\n          Pcase: f2[7] <= 6.\n            Reducible.\n          Pcase: f2[2] > 5.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=1 T[5]<=1 T[6]<=0 T[7]<=2 [].\n          Pcase: f2[5] > 5.\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[4]<=1 T[5]<=0 T[6]<=0 T[7]<=2 [].\n          Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[4]<=1 T[5]<=0 T[6]<=0 T[7]<=2 [].\n        Pcase: h[1] <= 5.\n          Pcase: f1[7] <= 5.\n            Reducible.\n          Pcase: s[2] > 7.\n            Hubcap T[1]<=3 T[2]<=(-1) T[3]<=2 T[4,5]<=1 T[6,7]<=5 [].\n          Pcase: h[2] <= 6.\n            Reducible.\n          Pcase: h[3] <= 5.\n            Reducible.\n          Pcase: s[4] > 7.\n            Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[4]<=0 T[5]<=0 T[6,7]<=5 [].\n          Pcase: s[5] > 7.\n            Hubcap T[1]<=3 T[3]<=2 T[5]<=(-1) T[2,4]<=1 T[6,7]<=5 [].\n          Pcase: h[3] > 6.\n            Hubcap T[1]<=3 T[2]<=(-1) T[3]<=2 T[4,5]<=1 T[6,7]<=5 [].\n          Pcase: f2[2] <= 5.\n            Reducible.\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=3 T[2]<=(-1) T[3]<=2 T[4,5]<=1 T[6,7]<=5 [].\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[4]<=1 T[5]<=0 T[6,7]<=4 [].\n        Pcase: s[2] > 8.\n          Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=2 T[5]<=0 T[6,7]<=4 [].\n        Pcase: h[7] > 6.\n          Hubcap T[1]<=2 T[3]<=2 T[6]<=0 T[2,7]<=5 T[4,5]<=1 [].\n        Pcase: h[7] <= 5.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4,5]<=1 T[6,7]<=4 [].\n        Pcase: s[2] > 7.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4,5]<=1 T[6,7]<=3 [].\n        Pcase: s[4] > 7.\n          Hubcap T[1]<=2 T[3]<=2 T[4]<=0 T[5]<=0 T[2,6]<=4 T[2,7]<=6 T[6,7]<=3\n                 [].\n        Pcase: h[6] > 5.\n          Hubcap T[1]<=2 T[3]<=2 T[4,5]<=1 T[2,6]<=4 T[2,7]<=5 T[6,7]<=2 [].\n        Pcase: h[3] <= 5.\n          Hubcap T[1]<=2 T[3]<=2 T[4,5]<=0 T[2,6]<=4 T[2,7]<=6 T[6,7]<=3 [].\n        Pcase: s[5] > 7.\n          Hubcap T[1]<=2 T[3]<=2 T[5]<=(-1) T[2,4]<=4 T[6,7]<=3 [].\n        Pcase: f2[5] <= 5.\n          Reducible.\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=1 T[5]<=0 T[6,7]<=3 [].\n        Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[4]<=1 T[5]<=0 T[6,7]<=2 [].\n      Pcase L3_2: h[4] <= 5.\n        Pcase: f1[4] <= 5.\n          Reducible.\n        Pcase: s[7] > 7.\n          Hubcap T[1]<=2 T[2]<=0 T[3]<=3 T[4]<=3 T[5]<=2 T[6]<=0 T[7]<=0 [].\n        Pcase: s[6] > 6.\n          Pcase: s[7] > 6.\n            Similar to *L3_1[4].\n          Pcase: s[5] > 8.\n            Hubcap T[1]<=3 T[2]<=(-1) T[3]<=3 T[4]<=3 T[5]<=(-1) T[6,7]<=3 [].\n          Pcase: h[5] > 6.\n            Hubcap T[1]<=3 T[2]<=(-1) T[3]<=3 T[4]<=3 T[5]<=(-1) T[6,7]<=3 [].\n          Pcase: h[1] > 6.\n            Hubcap T[1]<=2 T[2]<=(-1) T[3]<=3 T[6]<=1 T[7]<=1 T[4,5]<=4 [].\n          Pcase: h[1] <= 5.\n            Hubcap T[1]<=3 T[2]<=(-2) T[3]<=3 T[4,5]<=3 T[6,7]<=3 [].\n          Pcase: f1[7] <= 5.\n            Reducible.\n          Pcase: s[2] <= 7.\n            Hubcap T[1]<=2 T[2]<=(-1) T[3]<=3 T[4]<=2 T[5]<=2 T[6]<=1 T[7]<=1 [].\n          Pcase: s[5] > 7.\n            Hubcap T[1]<=2 T[2]<=(-1) T[3]<=3 T[4]<=3 T[5]<=0 T[6]<=1 T[7]<=2 [].\n          Pcase: s[6] > 7.\n            Hubcap T[1]<=2 T[2]<=(-1) T[3]<=3 T[4]<=3 T[7]<=2 T[5,6]<=1 [].\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=2 T[2]<=(-1) T[3]<=3 T[6]<=1 T[7]<=1 T[4,5]<=4 [].\n          Pcase: s[2] <= 8.\n            Hubcap T[1]<=2 T[2]<=(-1) T[3]<=3 T[4]<=2 T[7]<=2 T[5,6]<=2 [].\n          Pcase: h[3] > 5.\n            Hubcap T[1]<=2 T[2]<=(-1) T[3]<=3 T[4]<=2 T[7]<=2 T[5,6]<=2 [].\n          Hubcap T[1]<=2 T[2]<=(-1) T[3]<=3 T[4]<=3 T[7]<=2 T[5,6]<=1 [].\n        Pcase: s[7] > 6.\n          Pcase: s[2] <= 7.\n            Hubcap T[1]<=2 T[3]<=3 T[4]<=2 T[6]<=0 T[2,5]<=1 T[2,7]<=2 T[5,7]<=4\n                   [].\n          Pcase: s[5] > 7.\n            Hubcap T[1]<=2 T[2]<=(-1) T[3]<=3 T[4]<=3 T[5]<=(-1) T[6]<=0 T[7]<=3\n                   [].\n          Pcase: h[3] > 5.\n            Hubcap T[1]<=2 T[2]<=(-1) T[3]<=3 T[4]<=2 T[6]<=0 T[5,7]<=4 [].\n          Hubcap T[1]<=2 T[2]<=(-1) T[3]<=3 T[4]<=3 T[6]<=0 T[5,7]<=3 [].\n        Pcase: h[7] > 6.\n          Hubcap T[1]<=3 T[2]<=(-1) T[3]<=3 T[4]<=3 T[6]<=0 T[5,7]<=2 [].\n        Pcase: h[1] > 5.\n          Hubcap T[1]<=2 T[2]<=(-1) T[3]<=3 T[4,5]<=2 T[6,7]<=4 [].\n        Hubcap T[1]<=3 T[2]<=(-2) T[3]<=3 T[4,5]<=1 T[6,7]<=5 [].\n      Pcase: s[7] > 7.\n        Hubcap T[1]<=2 T[3]<=2 T[4]<=2 T[6]<=0 T[7]<=0 T[2,5]<=4 [].\n      Pcase: s[2] > 7.\n        Pcase: s[7] > 6.\n          Pcase: s[6] > 6.\n            Similar to *L3_1[4].\n          Pcase: s[5] > 7.\n            Hubcap T[1]<=2 T[3]<=2 T[5]<=(-1) T[6]<=0 T[7]<=4 T[2,4]<=3 [].\n          Pcase: h[3] > 5.\n            Hubcap T[1]<=2 T[3]<=2 T[4]<=1 T[6]<=0 T[2,5]<=2 T[2,7]<=4 T[5,7]<=5\n                   [].\n          Pcase: h[5] > 6.\n            Hubcap T[1]<=2 T[3]<=2 T[4]<=2 T[5]<=0 T[6]<=0 T[2,7]<=4 [].\n          Pcase: h[7] > 6.\n            Hubcap T[1]<=2 T[3]<=2 T[6]<=0 T[2,4]<=3 T[5,7]<=3 [].\n          Pcase: h[1] > 5.\n            Hubcap T[1]<=2 T[3]<=2 T[6]<=0 T[2,4]<=2 T[5,7]<=4 [].\n          Pcase: f1[4] <= 5.\n            Hubcap T[1]<=2 T[3]<=2 T[4]<=1 T[5]<=1 T[6]<=0 T[2,7]<=4 [].\n          Pcase: f1[5] > 6.\n            Hubcap T[1]<=2 T[3]<=2 T[4]<=2 T[5]<=0 T[6]<=0 T[2,7]<=4 [].\n          Pcase: f1[7] > 5.\n            Hubcap T[1]<=2 T[3]<=2 T[6]<=0 T[2,7]<=3 T[4,5]<=3 [].\n          Pcase: f2[7] <= 6.\n            Reducible.\n          Pcase: h[5] <= 5.\n            Hubcap T[1]<=2 T[3]<=2 T[6]<=0 T[7]<=2 T[2,4]<=3 T[2,5]<=3 T[4,5]<=3\n                   [].\n          Pcase: h[4] > 6.\n            Hubcap T[1]<=2 T[3]<=2 T[4]<=1 T[5]<=1 T[6]<=0 T[2,7]<=4 [].\n          Pcase: s[2] > 8.\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=2 T[6]<=0 T[5,7]<=4 [].\n          Pcase: h[2] <= 5.\n            Reducible.\n          Pcase: h[2] > 6.\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=2 T[6]<=0 T[5,7]<=4 [].\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=2 T[5]<=1 T[6]<=0 T[7]<=2 [].\n        Pcase: s[6] > 8.\n          Hubcap T[1]<=3 T[3]<=2 T[6]<=(-1) T[2,4]<=2 T[5,7]<=4 [].\n        Pcase: s[6] <= 6.\n          Pcase: s[5] > 7.\n            Hubcap T[1]<=3 T[3]<=2 T[5]<=(-2) T[2,4]<=2 T[6,7]<=5 [].\n          Pcase: h[5] <= 5.\n            Reducible.\n          Pcase: h[3] > 5.\n            Hubcap T[2]<=0 T[3]<=2 T[4]<=1 T[1,5]<=2 T[6,7]<=5 [].\n          Pcase: h[4] > 6.\n            Hubcap T[3]<=2 T[4]<=1 T[1,2]<=3 T[5,6]<=1 T[5,7]<=3 T[6,7]<=5 [].\n          Pcase: f1[4] <= 5.\n            Reducible.\n          Pcase: h[6] > 5.\n            Hubcap T[2]<=0 T[3]<=2 T[4]<=2 T[1,5]<=1 T[6,7]<=5 [].\n          Pcase: f2[5] <= 5.\n            Reducible.\n          Pcase: s[2] <= 8.\n            Hubcap T[2]<=0 T[3]<=2 T[4]<=2 T[1,5]<=2 T[6,7]<=4 [].\n          Pcase: h[2] > 5.\n            Hubcap T[2]<=0 T[3]<=2 T[4]<=2 T[1,5]<=2 T[6,7]<=4 [].\n          Pcase: h[7] > 6.\n            Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[4]<=2 T[5]<=0 T[6]<=0 T[7]<=3 [].\n          Pcase: h[1] > 5.\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=2 T[5]<=0 T[6,7]<=4 [].\n          Hubcap T[1]<=3 T[2]<=(-1) T[3]<=2 T[4]<=2 T[5]<=(-1) T[6,7]<=5 [].\n        Pcase: h[1] <= 5.\n          Similar to *L3_2[4].\n        Hubcap T[1]<=2 T[3]<=2 T[2,4]<=2 T[2,7]<=2 T[4,5]<=3 T[5,6]<=3 T[6,7]<=3\n               [].\n      Pcase: s[6] > 6.\n        Pcase: s[7] > 6.\n          Similar to *L3_1[4].\n        Pcase: h[1] <= 5.\n          Similar to *L3_2[4].\n        Pcase: s[5] > 7.\n          Hubcap T[1]<=2 T[3]<=2 T[4]<=1 T[5]<=0 T[7]<=1 T[2,6]<=4 [].\n        Pcase: s[6] > 7.\n          Hubcap T[1]<=2 T[3]<=2 T[4]<=1 T[6]<=0 T[7]<=1 T[2,5]<=4 [].\n        Pcase: h[2] <= 5.\n          Hubcap T[1]<=2 T[3]<=2 T[4]<=1 T[6]<=0 T[7]<=1 T[2,5]<=4 [].\n        Pcase: h[3] > 5.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=1 T[7]<=1 T[5,6]<=3 [].\n        Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[4]<=1 T[5]<=0 T[6]<=1 T[7]<=1 [].\n      Pcase: s[7] > 6.\n        Pcase: s[5] > 7.\n          Hubcap T[1]<=2 T[3]<=2 T[4]<=1 T[5]<=(-1) T[6]<=0 T[2,7]<=5 [].\n        Pcase: h[2] <= 5.\n          Hubcap T[1]<=2 T[3]<=2 T[4]<=1 T[6]<=0 T[7]<=1 T[2,5]<=4 [].\n        Pcase: h[3] <= 5.\n          Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[4]<=1 T[5]<=0 T[6]<=0 T[7]<=2 [].\n        Pcase: h[2] <= 6.\n          Hubcap T[1]<=2 T[3]<=2 T[4]<=1 T[6]<=0 T[2,5]<=3 T[2,7]<=4 T[5,7]<=4\n                 [].\n        Pcase: h[3] > 6.\n          Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=1 T[6]<=0 T[5,7]<=5 [].\n        Pcase: h[5] > 5.\n          Hubcap T[1]<=2 T[3]<=2 T[4]<=1 T[5]<=1 T[6]<=0 T[2,7]<=4 [].\n        Hubcap T[1]<=2 T[3]<=2 T[4]<=1 T[5]<=2 T[6]<=0 T[2,7]<=3 [].\n      Pcase: h[2] <= 5.\n        Hubcap T[1]<=2 T[3]<=2 T[4]<=1 T[2,5]<=3 T[6,7]<=2 [].\n      Pcase: h[3] > 5.\n        Hubcap T[3]<=2 T[4]<=1 T[1,2]<=3 T[5,6]<=1 T[5,7]<=3 T[6,7]<=5 [].\n      Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[4]<=1 T[5]<=(-1) T[6,7]<=3 [].\n    Pcase: s[6] > 6.\n      Similar to *L2_2[4].\n    Pcase: h[6] <= 5.\n      Pcase: s[2] > 8.\n        Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=2 T[6]<=2 T[4,7]<=2 [].\n      Pcase: s[4] > 7.\n        Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=0 T[5,6]<=3 T[5,7]<=3 T[6,7]<=3 [].\n      Pcase: s[4] <= 6.\n        Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[6]<=1 T[7]<=0 T[4,5]<=3 [].\n      Pcase: h[5] <= 5.\n        Reducible.\n      Pcase: s[7] > 6.\n        Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4,5]<=2 T[6,7]<=2 [].\n      Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=0 T[5]<=1 T[6,7]<=3 [].\n    Pcase L2_3: h[5] > 5.\n      Pcase L3_1: s[4] <= 6.\n        Pcase: s[7] <= 6.\n          Reducible.\n        Pcase: s[2] > 7.\n          Pcase: s[7] > 7.\n            Pcase: s[2] > 8.\n              Hubcap T[1]<=2 T[2]<=0 T[3]<=3 T[4]<=3 T[5]<=2 T[6]<=0 T[7]<=0 [].\n            Pcase: h[2] > 5.\n              Hubcap T[1]<=2 T[4]<=3 T[5]<=2 T[6]<=0 T[7]<=0 T[2,3]<=3 [].\n            Hubcap T[1]<=2 T[6]<=0 T[7]<=0 T[2,3]<=4 T[4,5]<=4 [].\n          Pcase: h[7] <= 5.\n            Reducible.\n          Pcase: h[1] <= 5.\n            Reducible.\n          Pcase: h[2] <= 5.\n            Hubcap T[1]<=2 T[4]<=3 T[6]<=0 T[2,3]<=3 T[5,7]<=2 [].\n          Pcase: h[3] > 5.\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=3 T[6]<=0 T[7]<=1 T[4,5]<=4 [].\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=2 T[5]<=1 T[6]<=0 T[7]<=1 [].\n          Hubcap T[1]<=2 T[2]<=(-1) T[3]<=3 T[4]<=3 T[5]<=2 T[6]<=0 T[7]<=1 [].\n        Pcase: h[2] <= 5.\n          Hubcap T[1]<=2 T[2]<=4 T[3]<=2 T[6]<=0 T[7]<=0 T[4,5]<=2 [].\n        Pcase: h[3] <= 6.\n          Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[6]<=0 T[7]<=1 T[4,5]<=2 [].\n        Pcase: s[7] > 7.\n          Hubcap T[1]<=2 T[6]<=0 T[7]<=0 T[2,3]<=4 T[4,5]<=4 [].\n        Hubcap T[1]<=2 T[6]<=0 T[7]<=1 T[2,3]<=3 T[4,5]<=4 [].\n      Pcase L3_2: s[7] > 7.\n        Pcase: s[2] > 7.\n          Hubcap T[1]<=2 T[3]<=2 T[7]<=0 T[2,4]<=4 T[5,6]<=2 [].\n        Pcase: s[4] > 7.\n          Hubcap T[1]<=2 T[2]<=4 T[3]<=2 T[4]<=0 T[7]<=0 T[5,6]<=2 [].\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=2 T[3]<=2 T[7]<=0 T[2,4]<=4 T[5,6]<=2 [].\n        Pcase: h[4] > 5.\n          Hubcap T[1]<=2 T[3]<=2 T[7]<=0 T[2,4]<=4 T[5,6]<=2 [].\n        Hubcap T[1]<=2 T[3]<=2 T[7]<=0 T[2,4]<=5 T[5,6]<=1 [].\n      Pcase: h[7] <= 5.\n        Pcase: s[4] > 7.\n          Hubcap T[3]<=2 T[4]<=0 T[5]<=0 T[1,2]<=3 T[6,7]<=5 [].\n        Pcase: s[7] > 6.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[5]<=0 T[6]<=0 T[4,7]<=5 [].\n        Pcase: h[4] <= 5.\n          Reducible.\n        Pcase: h[3] <= 5.\n          Hubcap T[3]<=2 T[4]<=0 T[5]<=0 T[1,2]<=3 T[6,7]<=5 [].\n        Pcase: h[4] > 6.\n          Hubcap T[3]<=2 T[4]<=0 T[5]<=0 T[1,2]<=3 T[6,7]<=5 [].\n        Pcase: h[1] > 5.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=1 T[5]<=0 T[6,7]<=4 [].\n        Hubcap T[1]<=3 T[2]<=(-1) T[3]<=2 T[4]<=1 T[5]<=0 T[6]<=1 T[7]<=4 [].\n      Pcase: s[4] > 7.\n        Similar to *L3_2[4].\n      Pcase: s[7] <= 6.\n        Similar to *L3_1[4].\n      Pcase: s[2] > 8.\n        Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4,5]<=3 T[6,7]<=3 [].\n      Pcase: f1[4] <= 5.\n        Pcase: h[4] <= 5.\n          Hubcap T[1]<=2 T[3]<=2 T[5]<=0 T[2,7]<=3 T[4,6]<=3 [].\n        Pcase: s[2] > 7.\n          Hubcap T[1]<=2 T[3]<=2 T[4]<=1 T[2,6]<=2 T[5,7]<=3 [].\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=2 T[3]<=2 T[2,4]<=3 T[5,6]<=1 T[5,7]<=3 T[6,7]<=3 [].\n        Hubcap T[1]<=2 T[3]<=2 T[5]<=1 T[2,4]<=4 T[6,7]<=1 [].\n      Pcase L3_3: h[3] > 5.\n        Pcase: s[2] > 7.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4,5]<=2 T[6,7]<=3 [].\n        Pcase: h[2] <= 5.\n          Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[4,5]<=2 T[6,7]<=1 [].\n        Pcase: h[2] <= 6.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4,5]<=2 T[6,7]<=2 [].\n        Pcase: h[3] > 6.\n          Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=2 T[5]<=1 T[6,7]<=3 [].\n        Pcase: h[4] > 5.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=1 T[5]<=1 T[6,7]<=3 [].\n        Pcase: h[5] > 6.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=1 T[5]<=0 T[6,7]<=3 [].\n        Pcase: h[6] > 6.\n          Hubcap T[1]<=2 T[3]<=2 T[4]<=2 T[5]<=0 T[6]<=0 T[2,7]<=4 [].\n        Pcase: f1[6] <= 5.\n          Reducible.\n        Pcase: h[7] > 6.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=2 T[5]<=0 T[6,7]<=2 [].\n        Pcase: h[1] > 5.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=2 T[5]<=0 T[6]<=1 T[7]<=1 [].\n        Hubcap T[1]<=2 T[3]<=2 T[4]<=2 T[5]<=0 T[6]<=0 T[2,7]<=4 [].\n      Pcase: h[2] > 5.\n        Similar to *L3_3[4].\n      Pcase: s[2] > 7.\n        Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4,5]<=2 T[6,7]<=2 [].\n      Hubcap T[1]<=2 T[2]<=4 T[3]<=2 T[4,5]<=1 T[6,7]<=1 [].\n    Pcase: h[7] > 5.\n      Similar to *L2_3[4].\n    Pcase: s[4] <= 6.\n      Hubcap T[1]<=2 T[6]<=0 T[7]<=0 T[2,3]<=3 T[4,5]<=5 [].\n    Pcase: s[7] > 7.\n      Hubcap T[1]<=2 T[3]<=2 T[7]<=0 T[2,4]<=4 T[5,6]<=2 [].\n    Pcase: s[7] <= 6.\n      Hubcap T[3]<=2 T[4]<=0 T[5]<=0 T[1,2]<=3 T[6,7]<=5 [].\n    Pcase: s[4] > 7.\n      Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=0 T[5]<=0 T[6]<=1 T[7]<=4 [].\n    Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[5]<=0 T[6]<=0 T[4,7]<=6 [].\n  Pcase: s[6] <= 5.\n    Similar to L1_2[5].\n  Pcase L1_3: s[4] <= 5.\n    Pcase: s[5] <= 5.\n      Similar to L1_1[3].\n    Pcase L2_1: s[5] > 6.\n      Pcase: s[7] > 6.\n        Pcase: h[3] <= 5.\n          Pcase L5_1: s[2] > 6.\n            Pcase: s[2] <= 7.\n              Hubcap T[1]<=2 T[4]<=2 T[6]<=0 T[2,3]<=2 T[5,7]<=4 [].\n            Pcase: s[3] > 6.\n              Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=2 T[6]<=0 T[5,7]<=4 [].\n            Pcase: s[7] > 7.\n              Hubcap T[1]<=2 T[2]<=(-1) T[3]<=3 T[6]<=0 T[7]<=0 T[4,5]<=6 [].\n            Pcase: h[4] > 5.\n              Hubcap T[1]<=2 T[2]<=(-1) T[3]<=2 T[4]<=2 T[6]<=0 T[5,7]<=4 [].\n            Hubcap T[1]<=2 T[2]<=(-2) T[3]<=3 T[4]<=3 T[6]<=0 T[5,7]<=4 [].\n          Pcase: s[3] > 6.\n            Similar to *L5_1[3].\n          Reducible.\n        Pcase L4_1: s[2] > 7.\n          Pcase: s[3] > 6.\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=2 T[6]<=0 T[5,7]<=4 [].\n          Pcase: s[7] > 7.\n            Hubcap T[1]<=2 T[2]<=(-1) T[3]<=3 T[6]<=0 T[7]<=0 T[4,5]<=6 [].\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=2 T[2]<=(-1) T[3]<=2 T[4]<=2 T[6]<=0 T[5,7]<=4 [].\n          Hubcap T[1]<=2 T[2]<=(-2) T[3]<=3 T[4]<=3 T[6]<=0 T[5,7]<=4 [].\n        Pcase: s[3] > 7.\n          Similar to *L4_1[3].\n        Pcase L4_2: h[2] > 5.\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=2 T[4]<=2 T[6]<=0 T[2,3]<=2 T[5,7]<=4 [].\n          Pcase: s[2] <= 6.\n            Pcase: s[3] <= 6.\n              Reducible.\n            Pcase: h[5] <= 5.\n              Reducible.\n            Pcase: f2[3] <= 5.\n              Reducible.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=0 T[4]<=2 T[6]<=0 T[5,7]<=4 [].\n          Pcase: s[3] > 6.\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=2 T[6]<=0 T[5,7]<=4 [].\n          Hubcap T[1]<=2 T[2]<=(-2) T[3]<=3 T[4]<=3 T[6]<=0 T[5,7]<=4 [].\n        Pcase: h[4] > 5.\n          Similar to *L4_2[3].\n        Pcase L4_3: s[2] <= 6.\n          Pcase: s[3] <= 6.\n            Reducible.\n          Pcase: h[5] <= 5.\n            Reducible.\n          Pcase: f1[2] <= 5.\n            Reducible.\n          Pcase: f2[3] <= 5.\n            Reducible.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=(-1) T[4]<=2 T[6]<=0 T[5,7]<=3 [].\n        Pcase: s[3] <= 6.\n          Similar to *L4_3[3].\n        Pcase: h[5] <= 5.\n          Reducible.\n        Pcase: h[1] <= 5.\n          Reducible.\n        Pcase: f1[2] <= 5.\n          Reducible.\n        Pcase: f2[3] <= 5.\n          Reducible.\n        Hubcap T[1]<=2 T[2]<=0 T[3]<=0 T[4]<=2 T[5]<=3 T[6]<=0 T[7]<=3 [].\n      Pcase: s[6] <= 6.\n        Pcase: s[3] > 6.\n          Pcase: s[2] > 6.\n            Pcase: s[3] > 7.\n              Hubcap T[3]<=0 T[4]<=2 T[1,5]<=2 T[2,6]<=3 T[2,7]<=5 T[6,7]<=5 [].\n            Pcase: h[4] <= 5.\n              Hubcap T[4]<=2 T[1,5]<=2 T[2,3]<=1 T[6,7]<=5 [].\n            Pcase: s[2] > 7.\n              Hubcap T[2]<=0 T[3]<=1 T[4]<=2 T[1,5]<=2 T[6,7]<=5 [].\n            Pcase: h[2] > 6.\n              Hubcap T[3]<=1 T[4]<=2 T[1,2]<=3 T[5,6]<=1 T[5,7]<=3 T[6,7]<=5 [].\n            Pcase: h[2] <= 5.\n              Hubcap T[4]<=2 T[1,5]<=2 T[2,3]<=1 T[6,7]<=5 [].\n            Pcase: h[3] > 5.\n              Hubcap T[2]<=1 T[4]<=2 T[1,3]<=3 T[5,6]<=1 T[5,7]<=3 T[6,7]<=5 [].\n            Hubcap T[3]<=1 T[4]<=2 T[1,2]<=3 T[5,6]<=1 T[5,7]<=3 T[6,7]<=5 [].\n          Pcase: h[2] > 5.\n            Hubcap T[4]<=2 T[1,3]<=2 T[2,5]<=1 T[6,7]<=5 [].\n          Hubcap T[1]<=4 T[2]<=3 T[3]<=(-1) T[4]<=2 T[6]<=0 T[5,7]<=2 [].\n        Pcase: s[2] <= 6.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=2 T[5]<=0 T[6,7]<=4 [].\n        Pcase: s[5] <= 7.\n          Hubcap T[1,2]<=2 T[3,5]<=1 T[4,6]<=4 T[4,7]<=6 T[6,7]<=5 [].\n        Pcase: h[4] > 5.\n          Hubcap T[3]<=2 T[4]<=2 T[5]<=(-1) T[1,2]<=2 T[6,7]<=5 [].\n        Hubcap T[3]<=3 T[4]<=3 T[5]<=(-1) T[1,2]<=1 T[6,7]<=4 [].\n      Pcase: s[3] > 6.\n        Pcase: s[2] > 6.\n          Pcase: h[1] > 5.\n            Hubcap T[1]<=2 T[4]<=2 T[7]<=2 T[2,3]<=2 T[5,6]<=2 [].\n          Pcase: f1[7] <= 5.\n            Reducible.\n          Pcase: h[2] > 5.\n            Pcase: s[3] > 7.\n              Hubcap T[1]<=3 T[2]<=1 T[3]<=0 T[4]<=2 T[7]<=2 T[5,6]<=2 [].\n            Pcase: s[6] > 7.\n              Hubcap T[1]<=3 T[4]<=2 T[7]<=2 T[2,3]<=2 T[5,6]<=1 [].\n            Pcase: h[4] > 5.\n              Hubcap T[1]<=3 T[4]<=2 T[7]<=2 T[2,3]<=1 T[5,6]<=2 [].\n            Hubcap T[1]<=3 T[2]<=(-1) T[3]<=2 T[4]<=2 T[7]<=2 T[5,6]<=2 [].\n          Pcase: s[2] <= 7.\n            Hubcap T[1]<=3 T[4]<=2 T[7]<=3 T[2,3]<=1 T[5,6]<=1 [].\n          Pcase: s[3] > 7.\n            Hubcap T[1]<=3 T[2]<=0 T[3]<=0 T[4]<=2 T[7]<=3 T[5,6]<=1 [].\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=3 T[2]<=0 T[3]<=1 T[4]<=2 T[7]<=3 T[5,6]<=1 [].\n          Hubcap T[1]<=3 T[2]<=(-1) T[3]<=2 T[4]<=2 T[7]<=3 T[5,6]<=1 [].\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=3 T[2]<=2 T[4]<=2 T[3,7]<=1 T[5,6]<=2 [].\n        Pcase: f1[2] <= 5.\n          Reducible.\n        Pcase: s[5] > 7.\n          Hubcap T[1]<=4 T[2]<=3 T[4]<=2 T[5]<=0 T[6]<=0 T[3,7]<=1 [].\n        Pcase: s[6] > 7.\n          Hubcap T[1]<=4 T[4]<=2 T[6]<=(-1) T[2,3]<=1 T[5,7]<=4 [].\n        Pcase: h[5] > 5.\n          Hubcap T[1]<=4 T[2]<=3 T[4]<=2 T[3,7]<=1 T[5,6]<=0 [].\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=(-2) T[4]<=2 T[6]<=(-1) T[5,7]<=4 [].\n      Pcase: s[2] <= 6.\n        Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=2 T[7]<=1 T[5,6]<=2 [].\n      Pcase: h[4] > 6.\n        Hubcap T[1]<=3 T[3]<=1 T[4]<=2 T[2,7]<=2 T[5,6]<=2 [].\n      Pcase: f1[3] <= 5.\n        Reducible.\n      Pcase: h[4] > 5.\n        Pcase: s[2] <= 7.\n          Hubcap T[3]<=2 T[4]<=2 T[7]<=2 T[1,2]<=2 T[5,6]<=2 [].\n        Pcase: s[5] > 7.\n          Hubcap T[1]<=3 T[2]<=(-1) T[3]<=2 T[4]<=2 T[5]<=0 T[6,7]<=4 [].\n        Pcase: s[6] > 7.\n          Hubcap T[1]<=3 T[2]<=(-1) T[3]<=2 T[4]<=2 T[7]<=3 T[5,6]<=1 [].\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=3 T[2]<=(-1) T[3]<=2 T[4]<=2 T[7]<=2 T[5,6]<=2 [].\n        Pcase: h[5] > 5.\n          Hubcap T[1]<=3 T[2]<=(-1) T[3]<=1 T[4]<=2 T[5]<=1 T[6,7]<=4 [].\n        Pcase: h[7] <= 5.\n          Reducible.\n        Pcase: h[6] <= 5.\n          Hubcap T[1]<=3 T[2]<=(-1) T[3]<=2 T[4]<=2 T[7]<=3 T[5,6]<=1 [].\n        Pcase: h[7] > 6.\n          Hubcap T[1]<=3 T[2]<=(-1) T[3]<=2 T[4]<=2 T[5]<=2 T[6]<=(-1) T[7]<=3\n                 [].\n        Pcase: h[1] > 5.\n          Hubcap T[1]<=2 T[2]<=(-1) T[3]<=2 T[4]<=2 T[5]<=2 T[6]<=1 T[7]<=2 [].\n        Hubcap T[1]<=3 T[2]<=(-1) T[3]<=2 T[4]<=2 T[7]<=3 T[5,6]<=1 [].\n      Pcase: s[5] > 7.\n        Hubcap T[3]<=3 T[4]<=3 T[5]<=0 T[1,2]<=1 T[6,7]<=3 [].\n      Pcase: s[6] > 7.\n        Hubcap T[4]<=3 T[1,2]<=1 T[3,6]<=2 T[5,7]<=4 [].\n      Pcase: h[2] > 5.\n        Hubcap T[1]<=3 T[2]<=(-2) T[4]<=3 T[3,6]<=3 T[5,7]<=3 [].\n      Pcase: h[5] > 5.\n        Hubcap T[3]<=2 T[4]<=3 T[5]<=1 T[1,2]<=1 T[6,7]<=3 [].\n      Hubcap T[3]<=3 T[4]<=3 T[6]<=(-1) T[1,2]<=1 T[5,7]<=4 [].\n    Pcase: s[7] > 6.\n      Similar to *L2_1[3].\n    Pcase: s[6] <= 6.\n      Reducible.\n    Pcase L2_2: h[5] > 5.\n      Pcase L3_1: s[2] > 7.\n        Pcase: s[3] > 7.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=0 T[4]<=2 T[5]<=2 T[6]<=(-1) T[7]<=3 [].\n        Pcase: s[3] > 6.\n          Pcase: s[6] > 7.\n            Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[4]<=2 T[5]<=2 T[6]<=(-2) T[7]<=3 [].\n          Pcase: h[6] <= 5.\n            Reducible.\n          Pcase: h[7] <= 5.\n            Reducible.\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[4]<=2 T[5]<=2 T[6]<=(-1) T[7]<=2 [].\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=3 T[2]<=0 T[3]<=1 T[4]<=2 T[5]<=1 T[6]<=(-1) T[7]<=3 [].\n          Hubcap T[1]<=3 T[2]<=(-1) T[3]<=2 T[4]<=2 T[5]<=2 T[6]<=(-1) T[7]<=3\n                 [].\n        Pcase: s[6] > 7.\n          Hubcap T[1]<=3 T[2]<=(-1) T[3]<=2 T[4]<=3 T[5]<=2 T[6]<=(-2) T[7]<=3\n                 [].\n        Pcase: h[6] <= 5.\n          Reducible.\n        Pcase: h[7] <= 5.\n          Reducible.\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=3 T[2]<=(-1) T[3]<=2 T[4]<=3 T[5]<=2 T[6]<=(-1) T[7]<=2\n                 [].\n        Pcase: h[4] > 5.\n          Hubcap T[1]<=3 T[2]<=(-1) T[3]<=1 T[4]<=2 T[5]<=1 T[6]<=(-1) T[7]<=3\n                 [].\n        Hubcap T[1]<=3 T[2]<=(-2) T[3]<=2 T[4]<=3 T[5]<=2 T[6]<=(-1) T[7]<=3 [].\n      Pcase: h[1] > 6.\n        Hubcap T[5]<=2 T[6]<=(-1) T[7]<=1 T[1,3]<=4 T[2,4]<=4 [].\n      Pcase: f1[7] <= 5.\n        Reducible.\n      Pcase L3_2: s[3] <= 6.\n        Pcase: h[3] <= 5.\n          Reducible.\n        Pcase: s[2] > 6.\n          Hubcap T[3]<=2 T[4]<=3 T[5]<=2 T[6]<=(-1) T[7]<=2 T[1,2]<=2 [].\n        Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=2 T[5]<=1 T[6]<=(-1) T[7]<=1 [].\n      Pcase: s[2] > 6.\n        Pcase: s[3] <= 7.\n          Hubcap T[1]<=3 T[4]<=2 T[6]<=(-1) T[2,3]<=2 T[5,7]<=4 [].\n        Pcase: h[1] > 5.\n          Similar to *L3_1[3].\n        Pcase: s[6] > 7.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=2 T[5]<=2 T[6]<=(-2) T[7]<=3 [].\n        Pcase: h[6] <= 5.\n          Reducible.\n        Pcase: h[7] <= 5.\n          Reducible.\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=3 T[2]<=1 T[3]<=0 T[4]<=2 T[5]<=2 T[6]<=(-1) T[7]<=2 [].\n        Hubcap T[1]<=3 T[2]<=2 T[3]<=(-1) T[4]<=2 T[5]<=2 T[6]<=(-1) T[7]<=3 [].\n      Pcase: h[1] > 5.\n        Similar to *L3_2[3].\n      Pcase: s[3] <= 7.\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=(-1) T[4]<=2 T[5]<=1 T[6,7]<=1 [].\n      Pcase: h[2] > 5.\n        Hubcap T[1]<=3 T[2]<=2 T[3]<=(-1) T[4]<=2 T[5]<=2 T[6]<=(-1) T[7]<=2 [].\n      Hubcap T[1]<=4 T[2]<=3 T[3]<=(-2) T[4]<=2 T[5]<=2 T[6]<=(-2) T[7]<=3 [].\n    Pcase: h[1] > 5.\n      Similar to *L2_2[3].\n    Pcase: f1[5] <= 5.\n      Reducible.\n    Pcase: f1[7] <= 5.\n      Reducible.\n    Pcase L2_3: s[2] <= 6.\n      Pcase: s[3] <= 6.\n        Reducible.\n      Pcase: h[2] <= 5.\n        Reducible.\n      Hubcap T[1]<=3 T[2]<=2 T[3]<=(-1) T[4]<=3 T[5]<=3 T[6]<=(-2) T[7]<=2 [].\n    Pcase: s[3] <= 6.\n      Similar to *L2_3[3].\n    Pcase: h[2] > 5.\n      Hubcap T[1]<=3 T[4]<=3 T[5]<=3 T[6]<=(-2) T[7]<=2 T[2,3]<=1 [].\n    Pcase: s[2] <= 7.\n      Hubcap T[1]<=3 T[2]<=1 T[3]<=(-1) T[4]<=3 T[5]<=3 T[6]<=(-2) T[7]<=3 [].\n    Pcase: s[3] > 7.\n      Hubcap T[1]<=3 T[2]<=0 T[3]<=0 T[4]<=3 T[5]<=3 T[6]<=(-2) T[7]<=3 [].\n    Pcase: h[4] > 5.\n      Hubcap T[1]<=3 T[2]<=0 T[3]<=1 T[4]<=3 T[5]<=2 T[6]<=(-2) T[7]<=3 [].\n    Hubcap T[1]<=3 T[2]<=(-1) T[3]<=1 T[4]<=3 T[5]<=3 T[6]<=(-2) T[7]<=3 [].\n  Pcase: s[5] <= 5.\n    Similar to L1_3[4].\n  Pcase L1_4: h[4] <= 5.\n    Pcase L2_1: s[2] > 7.\n      Pcase: s[4] > 7.\n        Hubcap T[1]<=3 T[2]<=0 T[3]<=0 T[4]<=0 T[5]<=2 T[6,7]<=5 [].\n      Pcase: s[7] > 7.\n        Hubcap T[1]<=2 T[2]<=0 T[7]<=0 T[3,4]<=4 T[5,6]<=4 [].\n      Pcase: s[3] <= 6.\n        Pcase: s[5] > 7.\n          Pcase: s[4] > 6.\n            Hubcap T[1]<=3 T[2]<=0 T[3]<=0 T[4]<=2 T[5]<=0 T[6,7]<=5 [].\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=3 T[2]<=0 T[5]<=0 T[3,4]<=3 T[6,7]<=4 [].\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=2 T[5]<=0 T[6]<=0 T[7]<=3 [].\n          Hubcap T[1]<=3 T[2]<=0 T[5]<=(-1) T[3,4]<=3 T[6,7]<=5 [].\n        Pcase: s[6] > 8.\n          Pcase: s[4] > 6.\n            Hubcap T[1]<=3 T[2]<=0 T[3]<=0 T[4]<=4 T[5]<=0 T[6]<=0 T[7]<=3 [].\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=3 T[2]<=0 T[6]<=0 T[3,4]<=3 T[5,7]<=4 [].\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[6]<=0 T[7]<=2 T[4,5]<=4 [].\n          Hubcap T[1]<=3 T[2]<=0 T[6]<=(-1) T[3,4]<=4 T[5,7]<=4 [].\n        Pcase: h[7] > 6.\n          Pcase: s[4] > 6.\n            Hubcap T[2]<=0 T[3]<=0 T[6,7]<=3 T[1,4]<=6 T[1,5]<=4 T[4,5]<=5 [].\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=3 T[2]<=0 T[6]<=0 T[3,4]<=3 T[5,7]<=4 [].\n          Pcase: s[6] <= 6.\n            Hubcap T[1]<=2 T[2]<=0 T[5]<=2 T[3,4]<=4 T[6,7]<=2 [].\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4,5]<=4 T[6,7]<=2 [].\n          Hubcap T[2]<=0 T[1,5]<=4 T[3,4]<=4 T[6,7]<=2 [].\n        Pcase: s[4] > 6.\n          Pcase: s[6] > 7.\n            Hubcap T[1]<=3 T[2]<=0 T[3]<=0 T[5]<=0 T[7]<=3 T[4,6]<=4 [].\n          Pcase: s[5] > 6.\n            Pcase: s[6] > 6.\n              Hubcap T[1]<=3 T[2]<=0 T[3]<=0 T[4]<=2 T[5]<=0 T[6,7]<=5 [].\n            Pcase: s[7] > 6.\n              Hubcap T[1]<=2 T[2]<=0 T[3]<=0 T[4]<=2 T[5]<=2 T[6]<=0 T[7]<=4 [].\n            Hubcap T[1]<=3 T[2]<=0 T[3]<=0 T[4]<=2 T[5]<=0 T[6,7]<=5 [].\n          Pcase: s[6] <= 6.\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=0 T[4,6]<=4 T[5,7]<=4 [].\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=0 T[4]<=4 T[5]<=0 T[6,7]<=3 [].\n          Hubcap T[2]<=0 T[3]<=0 T[5]<=0 T[1,4]<=6 T[6,7]<=4 [].\n        Pcase: s[5] > 6.\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=2 T[2]<=0 T[5]<=2 T[6]<=0 T[7]<=3 T[3,4]<=3 [].\n          Pcase: s[6] > 6.\n            Hubcap T[2]<=0 T[1,5]<=4 T[3,4]<=3 T[6,7]<=3 [].\n          Hubcap T[2]<=0 T[1,5]<=2 T[3,4]<=3 T[6,7]<=5 [].\n        Pcase: h[5] > 6.\n          Hubcap T[2]<=0 T[1,5]<=3 T[3,4]<=3 T[6,7]<=4 [].\n        Pcase: s[6] <= 6.\n          Pcase: s[7] <= 6.\n            Reducible.\n          Pcase: h[5] > 5.\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4,5]<=3 T[6,7]<=3 [].\n          Hubcap T[1]<=2 T[2]<=0 T[3]<=1 T[4]<=3 T[6]<=1 T[5,7]<=3 [].\n        Pcase: s[7] > 6.\n          Pcase: s[6] > 7.\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[6]<=0 T[7]<=2 T[4,5]<=4 [].\n          Pcase: h[5] > 5.\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4,5]<=3 T[6,7]<=3 [].\n          Hubcap T[1]<=2 T[2]<=0 T[3]<=1 T[4]<=3 T[5]<=1 T[6,7]<=3 [].\n        Pcase: s[6] > 7.\n          Hubcap T[1]<=3 T[2]<=0 T[6]<=(-1) T[3,4]<=4 T[5,7]<=4 [].\n        Pcase: h[5] > 5.\n          Hubcap T[2]<=0 T[1,3]<=4 T[4,5]<=3 T[6,7]<=3 [].\n        Pcase: f1[4] <= 6.\n          Reducible.\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=1 T[4]<=3 T[5]<=1 T[6,7]<=2 [].\n        Pcase: h[6] <= 6.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=1 T[4]<=3 T[5]<=1 T[6,7]<=2 [].\n        Pcase: h[7] > 5.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=1 T[4]<=3 T[5]<=1 T[6,7]<=2 [].\n        Hubcap T[1]<=2 T[2]<=0 T[3]<=1 T[4]<=3 T[5]<=1 T[6]<=1 T[7]<=2 [].\n      Pcase: s[5] > 7.\n        Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[4]<=0 T[5]<=0 T[6,7]<=5 [].\n      Pcase: s[7] > 6.\n        Pcase: s[3] > 7.\n          Hubcap T[1]<=2 T[2]<=0 T[3]<=0 T[4,5]<=4 T[6,7]<=4 [].\n        Pcase: s[4] > 6.\n          Hubcap T[1]<=2 T[2]<=0 T[3]<=0 T[4]<=2 T[5]<=2 T[6,7]<=4 [].\n        Pcase: s[5] > 6.\n          Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=0 T[6]<=0 T[5,7]<=5 [].\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4,5]<=3 T[6,7]<=3 [].\n        Pcase: h[5] > 6.\n          Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=0 T[5]<=2 T[6,7]<=4 [].\n        Pcase: h[5] <= 5.\n          Hubcap T[1]<=2 T[2]<=0 T[4]<=2 T[3,6]<=3 T[5,7]<=3 [].\n        Pcase: h[6] > 5.\n          Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4,5]<=2 T[6,7]<=4 [].\n        Hubcap T[1]<=2 T[2]<=0 T[3]<=1 T[4]<=2 T[5]<=3 T[6,7]<=2 [].\n      Pcase: s[6] > 8.\n        Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[6]<=(-1) T[7]<=3 T[4,5]<=3 [].\n      Pcase: s[4] > 6.\n        Hubcap T[1]<=3 T[2]<=0 T[3]<=0 T[4,5]<=2 T[6,7]<=5 [].\n      Pcase: s[6] <= 6.\n        Pcase: s[3] > 7.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=0 T[4,5]<=2 T[6,7]<=5 [].\n        Pcase: s[5] > 6.\n          Hubcap T[2]<=0 T[3]<=2 T[4]<=0 T[1,5]<=3 T[6,7]<=5 [].\n        Hubcap T[2]<=0 T[1,4]<=3 T[3,5]<=2 T[6,7]<=5 [].\n      Pcase: s[3] > 7.\n        Hubcap T[1]<=3 T[2]<=0 T[3]<=0 T[4,5]<=3 T[6,7]<=4 [].\n      Pcase: h[5] > 6.\n        Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[4]<=0 T[5]<=0 T[6]<=2 T[7]<=3 [].\n      Pcase: h[7] > 6.\n        Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[4,5]<=3 T[6,7]<=2 [].\n      Pcase: h[1] > 5.\n        Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4,5]<=3 T[6,7]<=3 [].\n      Pcase: f1[7] <= 5.\n        Reducible.\n      Pcase: h[2] > 5.\n        Pcase: s[5] > 6.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[4]<=0 T[7]<=2 T[5,6]<=3 [].\n        Pcase: s[6] > 7.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[4]<=2 T[5]<=2 T[6]<=(-1) T[7]<=2 [].\n        Pcase: h[5] <= 5.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[4]<=2 T[5]<=1 T[6]<=0 T[7]<=2 [].\n        Pcase: h[6] <= 6.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[6]<=1 T[7]<=2 T[4,5]<=2 [].\n        Pcase: h[7] > 5.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[6]<=1 T[7]<=2 T[4,5]<=2 [].\n        Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[6]<=2 T[7]<=2 T[4,5]<=1 [].\n      Pcase: s[5] > 6.\n        Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[4]<=0 T[7]<=3 T[5,6]<=2 [].\n      Pcase: s[6] > 7.\n        Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[6]<=(-1) T[7]<=3 T[4,5]<=3 [].\n      Pcase: h[6] <= 5.\n        Reducible.\n      Pcase: h[5] <= 5.\n        Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[4]<=2 T[5]<=1 T[6]<=(-1) T[7]<=3 [].\n      Pcase: h[7] > 5.\n        Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[6]<=0 T[7]<=3 T[4,5]<=2 [].\n      Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[6]<=1 T[7]<=3 T[4,5]<=1 [].\n    Pcase: s[7] > 7.\n      Pcase: h[6] <= 5.\n        Similar to *L2_1[6].\n      Pcase: s[4] > 7.\n        Hubcap T[1]<=3 T[4]<=0 T[7]<=0 T[2,3]<=5 T[5,6]<=2 [].\n      Pcase: s[5] > 7.\n        Hubcap T[1]<=3 T[2]<=4 T[5]<=0 T[6]<=0 T[7]<=0 T[3,4]<=3 [].\n      Pcase: s[4] > 6.\n        Pcase: s[2] > 6.\n          Hubcap T[1]<=2 T[3]<=0 T[7]<=0 T[2,4]<=5 T[5,6]<=2 [].\n        Pcase: s[3] > 7.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=(-1) T[4]<=2 T[7]<=0 T[5,6]<=2 [].\n        Pcase: s[3] <= 6.\n          Hubcap T[7]<=0 T[1,4]<=3 T[2,3]<=5 T[5,6]<=2 [].\n        Pcase: s[5] > 6.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=1 T[4]<=0 T[5]<=1 T[6]<=0 T[7]<=0 [].\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=1 T[4]<=2 T[5]<=0 T[6]<=1 T[7]<=0 [].\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4]<=2 T[7]<=0 T[5,6]<=2 [].\n        Pcase: f1[2] <= 5.\n          Reducible.\n        Pcase: h[3] > 5.\n          Hubcap T[1]<=3 T[4]<=2 T[7]<=0 T[2,3]<=3 T[5,6]<=2 [].\n        Hubcap T[1]<=3 T[2]<=3 T[3]<=1 T[4]<=1 T[7]<=0 T[5,6]<=2 [].\n      Pcase: s[3] <= 6.\n        Hubcap T[1]<=2 T[3]<=2 T[7]<=0 T[2,4]<=3 T[5,6]<=3 [].\n      Pcase: s[6] > 7.\n        Hubcap T[1]<=3 T[6]<=0 T[7]<=0 T[2,3]<=4 T[4,5]<=3 [].\n      Pcase: s[2] > 6.\n        Pcase: s[3] > 7.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=0 T[4]<=2 T[7]<=0 T[5,6]<=4 [].\n        Hubcap T[1]<=2 T[2]<=1 T[7]<=0 T[3,6]<=3 T[4,5]<=4 [].\n      Pcase: s[5] > 6.\n        Hubcap T[1]<=3 T[4]<=0 T[5]<=4 T[6]<=0 T[7]<=0 T[2,3]<=3 [].\n      Pcase: s[6] > 6.\n        Hubcap T[1]<=3 T[6]<=1 T[7]<=0 T[2,3]<=3 T[4,5]<=3 [].\n      Pcase: s[3] > 7.\n        Hubcap T[1]<=3 T[2]<=3 T[3]<=(-1) T[4]<=2 T[7]<=0 T[5,6]<=3 [].\n      Hubcap T[1]<=3 T[2]<=2 T[7]<=0 T[3,4]<=2 T[5,6]<=3 [].\n    Pcase L2_2: s[4] > 7.\n      Pcase: s[7] > 6.\n        Pcase: s[2] > 6.\n          Hubcap T[1]<=2 T[2]<=3 T[3]<=0 T[4]<=0 T[5,6]<=3 T[5,7]<=4 T[6,7]<=4\n                 [].\n        Pcase: s[3] > 7.\n          Hubcap T[1]<=3 T[3]<=(-1) T[4]<=0 T[2,5]<=4 T[6,7]<=4 [].\n        Pcase: s[6] > 7.\n          Hubcap T[1]<=3 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=2 T[2,3]<=5 [].\n        Pcase: s[3] > 6.\n          Pcase: s[5] > 7.\n            Hubcap T[1]<=3 T[3]<=1 T[4]<=0 T[5]<=0 T[6]<=0 T[2,7]<=6 [].\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=1 T[4]<=0 T[5]<=0 T[6,7]<=3 [].\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=2 T[3]<=1 T[4]<=0 T[2,5]<=3 T[6,7]<=4 [].\n          Hubcap T[1]<=3 T[4]<=0 T[3,7]<=2 T[2,5]<=4 T[2,6]<=4 T[5,6]<=3 [].\n        Pcase: s[5] > 7.\n          Hubcap T[4]<=(-1) T[5]<=0 T[6]<=0 T[1,7]<=6 T[2,3]<=5 [].\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=3 T[4]<=(-1) T[5]<=0 T[2,3]<=5 T[6,7]<=3 [].\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=2 T[4]<=(-1) T[2,3]<=4 T[5,6]<=3 T[5,7]<=4 T[6,7]<=4 [].\n        Pcase: h[7] <= 5.\n          Reducible.\n        Pcase: f1[2] <= 5.\n          Reducible.\n        Pcase: s[5] > 6.\n          Hubcap T[1]<=3 T[4]<=(-1) T[6]<=0 T[2,3]<=5 T[5,7]<=3 [].\n        Pcase: h[3] > 6.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=0 T[4]<=(-1) T[5]<=2 T[6,7]<=3 [].\n        Pcase: h[3] <= 5.\n          Hubcap T[1]<=3 T[3]<=1 T[4]<=(-1) T[2,5]<=5 T[6,7]<=2 [].\n        Pcase: h[6] > 5.\n          Hubcap T[1]<=3 T[4]<=(-1) T[5,6]<=2 T[2,3]<=5 T[2,7]<=5 T[3,7]<=3 [].\n        Hubcap T[1]<=3 T[4]<=(-1) T[2,3]<=5 T[5,6]<=3 T[5,7]<=2 T[6,7]<=2 [].\n      Pcase: s[6] > 7.\n        Hubcap T[4]<=0 T[5]<=0 T[7]<=3 T[1,6]<=3 T[2,3]<=4 [].\n      Pcase: s[6] > 6.\n        Pcase: s[2] > 6.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=0 T[6,7]<=4 [].\n        Pcase: s[3] > 7.\n          Hubcap T[1]<=4 T[2]<=3 T[3]<=(-1) T[4]<=0 T[5]<=0 T[6,7]<=4 [].\n        Pcase: s[3] > 6.\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=3 T[2]<=2 T[3]<=1 T[4]<=0 T[5]<=0 T[6]<=2 T[7]<=2 [].\n          Hubcap T[1]<=4 T[2]<=3 T[4]<=0 T[5]<=0 T[6]<=0 T[3,7]<=3 [].\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=3 T[2]<=3 T[4]<=(-1) T[5]<=0 T[6]<=2 T[3,7]<=3 [].\n        Hubcap T[1]<=4 T[4]<=(-1) T[5]<=0 T[6]<=0 T[7]<=3 T[2,3]<=4 [].\n      Pcase: f1[7] <= 5.\n        Pcase: h[1] <= 6.\n          Reducible.\n        Pcase: s[2] > 6.\n          Hubcap T[1]<=2 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=1 T[6]<=2 T[7]<=2 [].\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=3 T[3]<=1 T[4]<=0 T[5]<=1 T[7]<=2 T[2,6]<=3 [].\n        Hubcap T[4]<=(-1) T[5]<=1 T[7]<=2 T[1,6]<=4 T[2,3]<=4 [].\n      Pcase: h[7] <= 5.\n        Pcase: s[2] > 6.\n          Hubcap T[1]<=3 T[3]<=0 T[4]<=0 T[5]<=1 T[6]<=1 T[2,7]<=5 [].\n        Pcase: h[2] <= 5.\n          Reducible.\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=3 T[2]<=1 T[3]<=1 T[4]<=0 T[6]<=1 T[5,7]<=4 [].\n        Hubcap T[4]<=(-1) T[6]<=1 T[5,7]<=4 T[1,2]<=5 T[1,3]<=4 T[2,3]<=4 [].\n      Pcase: s[5] > 6.\n        Pcase: s[2] > 6.\n          Hubcap T[3]<=0 T[4]<=0 T[5]<=0 T[1,2]<=5 T[6,7]<=5 [].\n        Pcase: s[3] > 7.\n          Hubcap T[1]<=4 T[2]<=3 T[3]<=(-1) T[4]<=0 T[5]<=0 T[6,7]<=4 [].\n        Pcase: s[3] > 6.\n          Pcase: s[5] > 7.\n            Hubcap T[1]<=4 T[4]<=0 T[5]<=(-1) T[2,3]<=3 T[6,7]<=4 [].\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=3 T[2]<=2 T[3]<=1 T[4]<=0 T[5]<=0 T[6,7]<=4 [].\n          Hubcap T[1]<=4 T[2]<=3 T[4]<=0 T[5]<=0 T[6]<=0 T[3,7]<=3 [].\n        Pcase: s[5] > 7.\n          Hubcap T[1]<=4 T[4]<=(-1) T[5]<=(-1) T[2,3]<=4 T[6,7]<=4 [].\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=3 T[4]<=(-1) T[5]<=0 T[2,3]<=4 T[6,7]<=4 [].\n        Hubcap T[1]<=4 T[4]<=(-1) T[5]<=0 T[6]<=0 T[7]<=3 T[2,3]<=4 [].\n      Pcase: s[2] > 6.\n        Hubcap T[1]<=3 T[3]<=0 T[4]<=0 T[2,6]<=4 T[5,7]<=3 [].\n      Pcase: s[3] > 7.\n        Hubcap T[1]<=4 T[3]<=(-1) T[4]<=0 T[2,5]<=3 T[6,7]<=4 [].\n      Pcase: s[3] > 6.\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=3 T[4]<=0 T[5]<=1 T[2,3]<=2 T[6,7]<=4 [].\n        Hubcap T[4]<=0 T[1,3]<=4 T[2,5]<=3 T[6,7]<=3 [].\n      Pcase: h[2] > 5.\n        Hubcap T[4]<=(-1) T[1,5]<=3 T[2,3]<=4 T[6,7]<=4 [].\n      Hubcap T[4]<=(-1) T[1,5]<=4 T[2,3]<=4 T[6,7]<=3 [].\n    Pcase: s[5] > 7.\n      Pcase: h[6] <= 5.\n        Similar to *L2_2[6].\n      Pcase: s[7] > 6.\n        Pcase: s[3] > 7.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=4 [].\n        Pcase: s[4] <= 6.\n          Pcase: s[2] > 6.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[5]<=0 T[6]<=0 T[4,7]<=5 [].\n          Hubcap T[2]<=2 T[3]<=2 T[5]<=0 T[6]<=0 T[1,4]<=3 T[1,7]<=6 T[4,7]<=4\n                 [].\n        Pcase: s[2] > 6.\n          Hubcap T[1]<=2 T[3]<=0 T[5]<=0 T[6]<=0 T[7]<=4 T[2,4]<=4 [].\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=3 T[3]<=1 T[4]<=0 T[5]<=0 T[6]<=0 T[2,7]<=6 [].\n        Pcase: f1[4] <= 5.\n          Reducible.\n        Pcase: s[6] > 6.\n          Hubcap T[4]<=0 T[5]<=0 T[6]<=0 T[1,7]<=5 T[2,3]<=5 [].\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=2 T[2]<=3 T[4]<=0 T[5]<=0 T[6]<=0 T[3,7]<=5 [].\n        Hubcap T[1]<=3 T[2]<=4 T[4]<=0 T[5]<=0 T[6]<=0 T[3,7]<=3 [].\n      Pcase: s[6] > 6.\n        Pcase: h[2] > 5.\n          Pcase: s[3] > 6.\n            Hubcap T[1]<=3 T[4]<=0 T[5]<=0 T[6]<=2 T[7]<=2 T[2,3]<=3 [].\n          Pcase: s[4] <= 6.\n            Hubcap T[5]<=0 T[1,2]<=4 T[3,4]<=3 T[6,7]<=3 [].\n          Pcase: s[6] > 7.\n            Hubcap T[1]<=3 T[5]<=0 T[6]<=0 T[2,4]<=4 T[3,7]<=3 [].\n          Pcase: s[2] > 6.\n            Hubcap T[1]<=3 T[3]<=0 T[5]<=0 T[6]<=2 T[7]<=2 T[2,4]<=3 [].\n          Hubcap T[4]<=0 T[5]<=0 T[6]<=2 T[1,2]<=5 T[3,7]<=3 [].\n        Pcase: s[3] > 7.\n          Hubcap T[1]<=4 T[3]<=0 T[4]<=0 T[5]<=0 T[7]<=3 T[2,6]<=3 [].\n        Pcase: s[4] <= 6.\n          Hubcap T[5]<=0 T[1,6]<=4 T[2,4]<=2 T[3,7]<=4 [].\n        Pcase: s[2] > 6.\n          Hubcap T[3]<=0 T[4]<=1 T[5]<=0 T[1,2]<=5 T[6,7]<=4 [].\n        Pcase: f1[2] <= 5.\n          Reducible.\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=4 T[2]<=3 T[4]<=0 T[5]<=0 T[6]<=0 T[3,7]<=3 [].\n        Pcase: f1[4] <= 5.\n          Reducible.\n        Pcase: s[6] > 7.\n          Hubcap T[1]<=4 T[4]<=0 T[5]<=0 T[6]<=(-1) T[7]<=3 T[2,3]<=4 [].\n        Pcase: h[3] > 6.\n          Hubcap T[1]<=4 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=3 [].\n        Pcase: h[3] <= 5.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=1 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=1 [].\n        Pcase: h[7] > 5.\n          Hubcap T[1]<=4 T[4]<=0 T[5]<=0 T[6]<=(-1) T[7]<=3 T[2,3]<=4 [].\n        Pcase: f2[6] <= 5.\n          Reducible.\n        Pcase: h[1] > 5.\n          Hubcap T[1]<=3 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=2 T[2,3]<=4 [].\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=3 [].\n      Pcase: s[3] > 7.\n        Hubcap T[3]<=0 T[4]<=0 T[5]<=(-1) T[1,6]<=5 T[2,7]<=6 [].\n      Pcase: s[2] > 6.\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=3 T[4]<=0 T[5]<=(-1) T[2,3]<=3 T[6,7]<=5 [].\n        Pcase: s[4] <= 6.\n          Hubcap T[1]<=3 T[5]<=(-1) T[6,7]<=5 T[2,3]<=2 T[2,4]<=2 T[3,4]<=3 [].\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=3 T[3]<=0 T[4]<=2 T[5]<=(-1) T[6]<=2 T[2,7]<=4 [].\n        Hubcap T[1]<=3 T[3]<=0 T[4]<=1 T[5]<=(-1) T[6]<=2 T[2,7]<=5 [].\n      Pcase: s[3] > 6.\n        Hubcap T[4]<=0 T[5]<=(-1) T[1,3]<=4 T[2,6]<=4 T[2,7]<=6 T[6,7]<=5 [].\n      Pcase: s[4] <= 6.\n        Hubcap T[4]<=1 T[5]<=(-1) T[6,7]<=5 T[1,2]<=4 T[1,3]<=4 T[2,3]<=3 [].\n      Pcase: f1[4] <= 5.\n        Reducible.\n      Pcase: h[2] > 5.\n        Hubcap T[4]<=0 T[5]<=(-1) T[6,7]<=5 T[1,2]<=5 T[1,3]<=4 T[2,3]<=4 [].\n      Hubcap T[1]<=4 T[4]<=0 T[5]<=(-1) T[6]<=0 T[7]<=3 T[2,3]<=4 [].\n    Pcase L2_3: s[6] > 7.\n      Pcase: s[3] > 7.\n        Pcase L4_1: s[7] > 6.\n          Pcase: s[2] > 6.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=0 T[4]<=2 T[5]<=2 T[6]<=0 T[7]<=2 [].\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=(-1) T[6]<=0 T[7]<=2 T[4,5]<=3 [].\n        Pcase: s[2] > 6.\n          Pcase: h[6] <= 5.\n            Similar to *L4_1[6].\n          Pcase: s[4] > 6.\n            Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=2 T[5]<=0 T[6]<=0 T[7]<=3 [].\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=0 T[5]<=2 T[6]<=0 T[7]<=3 [].\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[6]<=(-1) T[7]<=3 T[4,5]<=3 [].\n        Pcase: s[4] > 6.\n          Hubcap T[1]<=4 T[2]<=3 T[3]<=(-1) T[4]<=2 T[5]<=0 T[6,7]<=2 [].\n        Pcase: s[5] > 6.\n          Hubcap T[1]<=4 T[2]<=3 T[3]<=(-1) T[4]<=0 T[5]<=2 T[6,7]<=2 [].\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=(-1) T[4]<=2 T[5]<=2 T[6]<=(-1) T[7]<=2\n                 [].\n        Pcase: f1[2] <= 5.\n          Reducible.\n        Pcase: h[5] > 5.\n          Hubcap T[1]<=4 T[2]<=3 T[3]<=(-1) T[6]<=(-1) T[7]<=3 T[4,5]<=2 [].\n        Hubcap T[1]<=3 T[2]<=2 T[3]<=(-1) T[4]<=2 T[5]<=1 T[6]<=(-1) T[7]<=2 [].\n      Pcase: s[7] > 6.\n        Pcase: s[4] > 6.\n          Pcase: s[2] > 6.\n            Hubcap T[1]<=2 T[3]<=0 T[5]<=0 T[6]<=0 T[7]<=2 T[2,4]<=5 [].\n          Pcase: s[3] <= 6.\n            Hubcap T[1]<=3 T[5]<=0 T[6]<=0 T[2,4]<=4 T[3,7]<=3 [].\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=1 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=2 [].\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4]<=2 T[5]<=0 T[6]<=0 T[7]<=2 [].\n          Hubcap T[1]<=3 T[2]<=3 T[4]<=2 T[5]<=0 T[6]<=0 T[3,7]<=2 [].\n        Pcase: s[2] > 6.\n          Pcase: s[3] > 6.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[6]<=0 T[7]<=2 T[4,5]<=3 [].\n          Hubcap T[1]<=2 T[6]<=0 T[7]<=2 T[2,3]<=2 T[4,5]<=4 [].\n        Pcase: h[3] <= 5.\n          Reducible.\n        Pcase: s[3] > 6.\n          Hubcap T[2]<=2 T[3]<=1 T[6]<=0 T[1,7]<=4 T[4,5]<=3 [].\n        Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=1 T[5]<=1 T[6]<=0 T[7]<=2 [].\n      Pcase: f1[7] <= 5.\n        Pcase: h[1] <= 6.\n          Reducible.\n        Pcase: s[2] > 6.\n          Hubcap T[1]<=2 T[6]<=(-1) T[7]<=1 T[2,3]<=3 T[4,5]<=4 [].\n        Hubcap T[1]<=3 T[6]<=(-1) T[7]<=1 T[2,3]<=4 T[4,5]<=3 [].\n      Pcase: h[3] <= 5.\n        Pcase: s[3] <= 6.\n          Hubcap T[2]<=3 T[5]<=0 T[7]<=2 T[1,6]<=2 T[3,4]<=3 [].\n        Pcase: s[5] > 6.\n          Hubcap T[4]<=0 T[1,6]<=3 T[2,5]<=3 T[3,7]<=4 [].\n        Pcase: s[2] <= 6.\n          Hubcap T[1]<=4 T[2]<=3 T[4]<=1 T[5]<=0 T[6]<=(-1) T[3,7]<=3 [].\n        Pcase: s[4] > 6.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=0 T[4]<=2 T[5]<=0 T[6]<=(-1) T[7]<=3 [].\n        Hubcap T[1]<=3 T[2]<=1 T[6]<=(-1) T[3,7]<=4 T[4,5]<=3 [].\n      Pcase: h[5] > 6.\n        Pcase: s[2] > 6.\n          Hubcap T[1]<=3 T[5]<=0 T[6]<=0 T[2,3]<=3 T[4,7]<=4 [].\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=4 T[2]<=3 T[3]<=1 T[4]<=0 T[5]<=0 T[6,7]<=2 [].\n        Pcase: s[4] > 6.\n          Hubcap T[1]<=4 T[4]<=0 T[5]<=0 T[2,3]<=4 T[6,7]<=2 [].\n        Hubcap T[1]<=3 T[2]<=2 T[3]<=2 T[4]<=1 T[5]<=0 T[6]<=0 T[7]<=2 [].\n      Pcase: h[1] > 6.\n        Pcase: s[2] > 6.\n          Hubcap T[1]<=2 T[6]<=0 T[7]<=1 T[2,3]<=3 T[4,5]<=4 [].\n        Hubcap T[7]<=1 T[1,6]<=2 T[2,3]<=4 T[4,5]<=3 [].\n      Pcase: s[4] > 6.\n        Pcase: s[2] > 6.\n          Hubcap T[3]<=0 T[5]<=0 T[6]<=0 T[1,2]<=5 T[4,7]<=5 [].\n        Pcase: s[3] <= 6.\n          Hubcap T[5]<=0 T[1,4]<=4 T[2,3]<=4 T[6,7]<=2 [].\n        Pcase: s[5] > 6.\n          Hubcap T[1]<=4 T[2]<=3 T[3]<=1 T[4]<=0 T[5]<=0 T[6,7]<=2 [].\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=1 T[4]<=2 T[5]<=0 T[6]<=(-1) T[7]<=2 [].\n        Pcase: f1[2] <= 5.\n          Reducible.\n        Pcase: h[3] > 6.\n          Hubcap T[1]<=4 T[2]<=3 T[3]<=(-1) T[4]<=2 T[5]<=0 T[6]<=(-1) T[7]<=3\n                 [].\n        Pcase: h[5] > 5.\n          Hubcap T[1]<=4 T[2]<=3 T[4]<=1 T[5]<=0 T[6]<=(-1) T[3,7]<=3 [].\n        Pcase: h[1] > 5.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=1 T[4]<=2 T[5]<=0 T[6]<=(-1) T[7]<=2 [].\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=(-1) T[4]<=2 T[5]<=0 T[6]<=(-1) T[7]<=3 [].\n      Pcase: s[3] <= 6.\n        Pcase: s[2] <= 6.\n          Hubcap T[1]<=3 T[2]<=2 T[4]<=1 T[5]<=1 T[6]<=0 T[3,7]<=3 [].\n        Pcase: s[5] > 6.\n          Hubcap T[6]<=0 T[1,5]<=4 T[2,3]<=2 T[4,7]<=4 [].\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[4]<=3 T[6]<=(-1) T[5,7]<=3 [].\n        Hubcap T[1]<=3 T[2]<=1 T[3]<=1 T[6]<=(-1) T[7]<=3 T[4,5]<=3 [].\n      Pcase: s[2] > 6.\n        Pcase: s[5] > 6.\n          Hubcap T[1]<=3 T[2]<=1 T[4]<=0 T[5]<=2 T[6]<=0 T[3,7]<=4 [].\n        Hubcap T[1]<=3 T[2]<=1 T[6]<=(-1) T[3,7]<=4 T[4,5]<=3 [].\n      Pcase: f2[3] <= 5.\n        Reducible.\n      Pcase: s[5] > 6.\n        Hubcap T[1]<=3 T[2]<=2 T[3]<=1 T[4]<=0 T[5]<=2 T[6]<=0 T[7]<=2 [].\n      Hubcap T[1]<=3 T[2]<=2 T[3]<=1 T[6]<=(-1) T[7]<=2 T[4,5]<=3 [].\n    Pcase L2_4: h[1] > 5.\n      Pcase: s[3] > 7.\n        Pcase: h[6] <= 5.\n          Similar to *L2_3[6].\n        Pcase: s[5] > 6.\n          Pcase: s[2] > 6.\n            Hubcap T[1]<=2 T[3]<=0 T[4]<=0 T[2,7]<=4 T[5,6]<=4 [].\n          Hubcap T[1]<=3 T[3]<=(-1) T[4]<=0 T[2,7]<=4 T[5,6]<=4 [].\n        Pcase: s[2] > 6.\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=0 T[4,5]<=3 T[6,7]<=3 [].\n          Pcase: s[4] > 6.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=0 T[4]<=2 T[5]<=0 T[6,7]<=4 [].\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=0 T[4,5]<=3 T[6,7]<=3 [].\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=2 T[7]<=3 [].\n        Pcase: s[7] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=(-1) T[4,5]<=3 T[6,7]<=3 [].\n        Pcase: s[4] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=(-1) T[4]<=2 T[5]<=0 T[6,7]<=4 [].\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=(-1) T[4,5]<=3 T[6,7]<=3 [].\n        Hubcap T[1]<=3 T[2]<=2 T[3]<=(-1) T[4]<=0 T[5]<=0 T[6]<=2 T[7]<=3 [].\n      Pcase: h[5] > 6.\n        Pcase: s[2] > 6.\n          Pcase: s[3] > 6.\n            Hubcap T[1]<=2 T[4]<=0 T[2,3]<=3 T[5,6]<=3 T[5,7]<=4 T[6,7]<=4 [].\n          Pcase: s[4] > 6.\n            Pcase: s[6] > 6.\n              Hubcap T[1]<=2 T[3]<=0 T[5]<=0 T[2,4]<=4 T[6,7]<=4 [].\n            Pcase: s[7] > 6.\n              Hubcap T[1]<=2 T[3]<=0 T[2,4]<=4 T[5,6]<=3 T[5,7]<=3 T[6,7]<=3 [].\n            Pcase: s[5] <= 6.\n              Reducible.\n            Hubcap T[1]<=2 T[3]<=0 T[5]<=0 T[2,4]<=4 T[6,7]<=4 [].\n          Pcase: h[3] <= 5.\n            Reducible.\n          Pcase: s[5] <= 6.\n            Hubcap T[1]<=2 T[2]<=1 T[7]<=2 T[3,4]<=3 T[5,6]<=2 [].\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=2 T[2]<=1 T[5]<=0 T[3,4]<=3 T[6,7]<=4 [].\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=2 T[6]<=0 T[5,7]<=3 [].\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4,5]<=1 T[6,7]<=4 [].\n        Pcase: h[2] > 5.\n          Pcase: s[3] > 6.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=0 T[5]<=2 T[6,7]<=4 [].\n          Pcase L5_1: s[4] > 6.\n            Pcase: f1[4] <= 5.\n              Reducible.\n            Pcase: s[6] > 6.\n              Hubcap T[1]<=2 T[4]<=0 T[5]<=0 T[2,3]<=4 T[6,7]<=4 [].\n            Pcase: s[7] > 6.\n              Hubcap T[1]<=2 T[4]<=0 T[6]<=1 T[2,3]<=4 T[5,7]<=3 [].\n            Pcase: s[5] <= 6.\n              Reducible.\n            Hubcap T[1]<=2 T[4]<=0 T[5]<=0 T[2,3]<=4 T[6,7]<=4 [].\n          Pcase: h[3] <= 5.\n            Reducible.\n          Pcase: f1[3] <= 5.\n            Reducible.\n          Pcase: f1[4] <= 5.\n            Reducible.\n          Pcase: s[5] <= 6.\n            Hubcap T[1]<=2 T[4]<=1 T[5]<=1 T[2,3]<=3 T[6,7]<=3 [].\n          Pcase: h[6] <= 5.\n            Similar to *L5_1[6].\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=2 T[4]<=1 T[5]<=0 T[2,3]<=3 T[6,7]<=4 [].\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=1 T[5]<=1 T[6]<=0 T[7]<=2 [].\n          Hubcap T[1]<=2 T[4]<=1 T[5]<=0 T[2,3]<=3 T[6,7]<=4 [].\n        Pcase: f1[2] <= 5.\n          Reducible.\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=1 T[4]<=0 T[5,6]<=3 T[5,7]<=3 T[6,7]<=3\n                 [].\n        Pcase: s[4] <= 6.\n          Reducible.\n        Pcase: f1[4] <= 5.\n          Reducible.\n        Pcase: s[5] <= 6.\n          Hubcap T[1]<=3 T[4]<=0 T[2,3]<=4 T[5,6]<=2 T[5,7]<=2 T[6,7]<=3 [].\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=3 T[4]<=0 T[5]<=0 T[6]<=1 T[7]<=2 T[2,3]<=4 [].\n        Hubcap T[1]<=3 T[4]<=0 T[6]<=0 T[2,3]<=4 T[5,7]<=3 [].\n      Pcase L3_1: s[2] > 6.\n        Pcase: s[4] > 6.\n          Pcase: s[5] > 6.\n            Pcase: s[3] > 6.\n              Hubcap T[1]<=2 T[2]<=3 T[3]<=0 T[4]<=0 T[5,6]<=3 T[5,7]<=4\n                     T[6,7]<=4 [].\n            Pcase: s[6] > 6.\n              Hubcap T[1]<=2 T[3]<=0 T[5]<=0 T[2,4]<=4 T[6,7]<=4 [].\n            Pcase: s[7] > 6.\n              Hubcap T[1]<=2 T[2]<=3 T[3]<=0 T[4]<=2 T[6]<=0 T[5,7]<=3 [].\n            Hubcap T[1]<=2 T[3]<=0 T[5]<=0 T[2,4]<=4 T[6,7]<=4 [].\n          Pcase: h[7] <= 5.\n            Pcase: s[7] > 6.\n              Hubcap T[1]<=2 T[3]<=0 T[5]<=0 T[2,4]<=5 T[6,7]<=3 [].\n            Pcase: h[6] <= 5.\n              Reducible.\n            Pcase: s[3] > 6.\n              Hubcap T[1]<=2 T[2]<=3 T[3]<=0 T[4]<=1 T[5]<=0 T[6,7]<=4 [].\n            Pcase: s[6] <= 6.\n              Reducible.\n            Hubcap T[1]<=2 T[3]<=0 T[5]<=0 T[2,4]<=5 T[6,7]<=3 [].\n          Pcase: s[6] > 6.\n            Pcase: s[7] > 6.\n              Hubcap T[1]<=2 T[3]<=0 T[5]<=0 T[6]<=2 T[7]<=1 T[2,4]<=5 [].\n            Hubcap T[1]<=2 T[3]<=0 T[5]<=0 T[6]<=1 T[7]<=2 T[2,4]<=5 [].\n          Pcase: s[3] <= 6.\n            Hubcap T[1]<=2 T[3]<=0 T[5]<=1 T[2,4]<=5 T[6,7]<=2 [].\n          Pcase: s[7] <= 6.\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=0 T[4]<=1 T[5]<=1 T[6,7]<=3 [].\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=0 T[4]<=2 T[7]<=1 T[5,6]<=3 [].\n          Pcase: h[3] > 5.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=0 T[4]<=2 T[7]<=1 T[5,6]<=3 [].\n          Pcase: h[5] > 5.\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=0 T[4]<=1 T[5]<=2 T[6,7]<=2 [].\n          Pcase: h[6] > 5.\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=0 T[4]<=2 T[7]<=1 T[5,6]<=2 [].\n          Hubcap T[1]<=2 T[2]<=3 T[3]<=0 T[4]<=2 T[5]<=2 T[6]<=1 T[7]<=0 [].\n        Pcase: f1[4] <= 5.\n          Pcase: h[5] <= 5.\n            Reducible.\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=2 T[2,4]<=1 T[3,5]<=4 T[6,7]<=3 [].\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4,7]<=2 T[5,6]<=3 [].\n          Pcase: s[5] <= 6.\n            Reducible.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4,5]<=1 T[6,7]<=4 [].\n        Pcase: f1[4] <= 6.\n          Pcase: h[5] <= 5.\n            Reducible.\n          Pcase: s[3] > 6.\n            Pcase: s[6] > 6.\n              Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=0 T[5]<=1 T[6,7]<=4 [].\n            Pcase: s[7] > 6.\n              Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=0 T[6]<=1 T[5,7]<=4 [].\n            Pcase: s[5] <= 6.\n              Reducible.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=0 T[5]<=1 T[6,7]<=4 [].\n          Pcase: h[3] <= 5.\n            Reducible.\n          Pcase: s[5] <= 6.\n            Hubcap T[1]<=2 T[3]<=1 T[7]<=2 T[2,4]<=2 T[5,6]<=3 [].\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=2 T[3]<=1 T[5]<=1 T[2,4]<=2 T[6,7]<=4 [].\n          Hubcap T[1]<=2 T[3]<=1 T[2,4]<=2 T[5,6]<=3 T[5,7]<=4 T[6,7]<=4 [].\n        Pcase: s[5] > 6.\n          Pcase: s[3] > 6.\n            Pcase: s[7] > 6.\n              Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=0 T[6]<=0 T[5,7]<=5 [].\n            Pcase: s[6] > 6.\n              Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=0 T[5]<=2 T[6,7]<=3 [].\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=0 T[5]<=1 T[6,7]<=4 [].\n          Pcase: h[3] <= 5.\n            Reducible.\n          Pcase: s[6] <= 6.\n            Hubcap T[1]<=2 T[3]<=1 T[2,4]<=2 T[5,6]<=3 T[5,7]<=4 T[6,7]<=4 [].\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=2 T[5]<=2 T[6]<=0 T[7]<=2 [].\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4,7]<=3 T[5,6]<=3 [].\n        Pcase: s[7] > 6.\n          Pcase: h[2] > 6.\n            Hubcap T[1]<=2 T[2]<=0 T[5,7]<=3 T[3,4]<=4 T[3,6]<=3 T[4,6]<=4 [].\n          Pcase: h[6] > 6.\n            Hubcap T[1]<=2 T[2]<=1 T[6]<=0 T[3,4]<=4 T[5,7]<=3 [].\n          Pcase: h[5] > 5.\n            Hubcap T[1]<=2 T[2]<=1 T[5,7]<=2 T[3,4]<=4 T[3,6]<=3 T[4,6]<=4 [].\n          Pcase: s[3] <= 6.\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=1 T[4]<=3 T[6]<=1 T[5,7]<=3 [].\n          Pcase: h[6] <= 5.\n            Hubcap T[1]<=2 T[2]<=1 T[4]<=1 T[3,6]<=3 T[5,7]<=3 [].\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=2 T[5]<=1 T[6,7]<=2 [].\n          Hubcap T[1]<=2 T[2]<=1 T[3,4]<=3 T[5,6]<=3 T[5,7]<=3 T[6,7]<=3 [].\n        Pcase: s[6] <= 6.\n          Hubcap T[1]<=2 T[2]<=1 T[5]<=1 T[3,4]<=2 T[6,7]<=4 [].\n        Pcase: s[3] <= 6.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=3 T[6]<=1 T[5,7]<=2 [].\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[5]<=1 T[7]<=1 T[4,6]<=3 [].\n        Pcase: f1[2] <= 5.\n          Reducible.\n        Pcase: h[5] > 5.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=2 T[5]<=0 T[6,7]<=3 [].\n        Pcase: h[6] <= 6.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[5]<=1 T[7]<=2 T[4,6]<=2 [].\n        Pcase: h[7] > 5.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=2 T[5]<=1 T[6,7]<=2 [].\n        Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=1 T[5]<=1 T[6,7]<=3 [].\n      Pcase: s[3] > 6.\n        Pcase: s[7] > 6.\n          Pcase: h[2] > 5.\n            Pcase: h[6] <= 5.\n              Similar to *L3_1[6].\n            Pcase: s[4] > 6.\n              Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=2 T[5]<=1 T[6,7]<=3 [].\n            Pcase: h[3] <= 5.\n              Reducible.\n            Pcase: f2[3] <= 5.\n              Reducible.\n            Pcase: s[5] > 6.\n              Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=0 T[6]<=0 T[5,7]<=5 [].\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4,5]<=3 T[6,7]<=3 [].\n          Pcase: f1[2] <= 5.\n            Reducible.\n          Pcase: h[3] <= 5.\n            Hubcap T[1]<=3 T[2]<=2 T[3]<=1 T[4]<=1 T[5,6]<=3 T[5,7]<=2 T[6,7]<=2\n                   [].\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=3 T[2]<=2 T[4]<=0 T[5]<=4 T[6]<=0 T[3,7]<=1 [].\n          Pcase: h[6] > 6.\n            Hubcap T[1]<=3 T[2]<=2 T[3]<=1 T[6]<=0 T[7]<=1 T[4,5]<=3 [].\n          Pcase: h[7] <= 5.\n            Pcase: s[6] <= 6.\n              Reducible.\n            Pcase: f2[6] <= 5.\n              Reducible.\n            Pcase: s[4] > 6.\n              Hubcap T[1]<=3 T[2]<=2 T[3]<=1 T[4]<=2 T[5]<=0 T[6,7]<=2 [].\n            Pcase: f2[3] <= 5.\n              Reducible.\n            Pcase: h[3] > 6.\n              Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4,5]<=3 T[6,7]<=2 [].\n            Pcase: h[5] > 5.\n              Hubcap T[1]<=3 T[2]<=2 T[3]<=1 T[4,5]<=2 T[6,7]<=2 [].\n            Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=2 T[5]<=1 T[6,7]<=2 [].\n          Pcase: f1[5] <= 5.\n            Pcase: s[4] > 6.\n              Hubcap T[1]<=3 T[2]<=2 T[3]<=1 T[4,5]<=2 T[6,7]<=2 [].\n            Hubcap T[1]<=3 T[2]<=2 T[4]<=2 T[3,5]<=1 T[6,7]<=2 [].\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=3 T[2]<=2 T[3]<=1 T[4,5]<=2 T[6,7]<=2 [].\n          Pcase: s[4] > 6.\n            Hubcap T[1]<=3 T[2]<=2 T[6]<=1 T[3,7]<=1 T[4,5]<=3 [].\n          Pcase: f2[3] <= 5.\n            Reducible.\n          Pcase: h[3] > 6.\n            Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=1 T[6]<=1 T[5,7]<=3 [].\n          Pcase: h[5] > 5.\n            Hubcap T[1]<=3 T[2]<=2 T[3]<=1 T[4,5]<=3 T[6,7]<=1 [].\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=1 T[6]<=1 T[5,7]<=3 [].\n        Pcase: s[6] <= 6.\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=3 T[3]<=1 T[4]<=0 T[2,6]<=3 T[5,7]<=3 [].\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=1 T[5]<=1 T[6,7]<=4 [].\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=1 T[4]<=1 T[5]<=1 T[6,7]<=2 [].\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=2 T[7]<=1 T[5,6]<=3 [].\n        Pcase: f1[2] <= 5.\n          Reducible.\n        Pcase: s[4] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=1 T[4]<=2 T[5]<=0 T[6]<=0 T[7]<=2 [].\n        Pcase: h[3] <= 5.\n          Reducible.\n        Pcase: f2[3] <= 5.\n          Reducible.\n        Pcase: s[5] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=1 T[4]<=0 T[5]<=2 T[6]<=0 T[7]<=2 [].\n        Pcase: h[3] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[6]<=0 T[7]<=2 T[4,5]<=3 [].\n        Pcase: h[5] > 5.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=1 T[6]<=0 T[7]<=2 T[4,5]<=2 [].\n        Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=2 T[5]<=1 T[6]<=0 T[7]<=2 [].\n      Pcase L3_2: s[4] > 6.\n        Pcase: f1[4] <= 5.\n          Reducible.\n        Pcase: h[3] > 6.\n          Hubcap T[3]<=0 T[1,4]<=3 T[2,7]<=4 T[5,6]<=3 [].\n        Pcase: h[7] > 5.\n          Pcase: s[5] <= 6.\n            Hubcap T[1,4]<=3 T[2,3]<=4 T[5,6]<=2 T[5,7]<=2 T[6,7]<=3 [].\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=3 T[4]<=0 T[5]<=0 T[2,3]<=4 T[6,7]<=3 [].\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=3 T[4]<=0 T[5]<=2 T[6]<=0 T[7]<=1 T[2,3]<=4 [].\n          Hubcap T[1]<=3 T[4]<=0 T[5]<=0 T[2,3]<=4 T[6,7]<=3 [].\n        Pcase: s[7] > 6.\n          Hubcap T[2,3]<=4 T[6,7]<=3 T[1,4]<=3 T[1,5]<=3 T[4,5]<=1 [].\n        Pcase: s[6] > 6.\n          Hubcap T[5]<=0 T[1,4]<=3 T[2,3]<=4 T[6,7]<=3 [].\n        Pcase: s[5] <= 6.\n          Reducible.\n        Pcase: h[2] <= 5.\n          Reducible.\n        Hubcap T[1]<=2 T[4]<=0 T[5]<=0 T[2,3]<=4 T[6,7]<=4 [].\n      Pcase: h[2] <= 5.\n        Reducible.\n      Pcase: h[3] <= 5.\n        Reducible.\n      Pcase: f1[3] <= 5.\n        Reducible.\n      Pcase: f1[4] <= 5.\n        Reducible.\n      Pcase: s[5] <= 6.\n        Hubcap T[1]<=2 T[4]<=1 T[5]<=1 T[2,3]<=3 T[6,7]<=3 [].\n      Pcase: h[6] <= 5.\n        Similar to *L3_2[6].\n      Pcase: s[7] > 6.\n        Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=1 T[6]<=0 T[5,7]<=3 [].\n      Pcase: s[6] > 6.\n        Hubcap T[1]<=2 T[4]<=1 T[5]<=1 T[6]<=2 T[7]<=1 T[2,3]<=3 [].\n      Hubcap T[1]<=2 T[4]<=1 T[5]<=0 T[2,3]<=3 T[6,7]<=4 [].\n    Pcase L2_5: s[2] > 6.\n      Pcase: s[4] > 6.\n        Pcase: s[7] > 6.\n          Pcase: s[3] > 7.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=0 T[4,5]<=2 T[6,7]<=4 [].\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=2 T[3]<=0 T[6]<=0 T[2,4]<=4 T[5,7]<=4 [].\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=2 T[3]<=0 T[5]<=0 T[2,4]<=5 T[6,7]<=3 [].\n          Pcase: h[6] <= 5.\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=0 T[4]<=2 T[5]<=1 T[6]<=1 T[7]<=1 [].\n          Pcase: s[3] > 6.\n            Hubcap T[1]<=2 T[3]<=0 T[4]<=1 T[2,7]<=6 T[5,6]<=1 [].\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=2 T[3]<=0 T[2,4]<=4 T[5,6]<=1 T[5,7]<=4 T[6,7]<=4 [].\n          Pcase: f1[4] <= 5.\n            Reducible.\n          Pcase: h[3] > 6.\n            Hubcap T[1]<=2 T[3]<=0 T[4]<=2 T[2,6]<=2 T[5,7]<=4 [].\n          Pcase: h[3] <= 5.\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=0 T[4]<=2 T[7]<=2 T[5,6]<=1 [].\n          Pcase: h[5] > 6.\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=0 T[4]<=1 T[6]<=0 T[5,7]<=4 [].\n          Pcase: h[5] <= 5.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=0 T[4]<=2 T[5,6]<=1 T[5,7]<=4 T[6,7]<=4\n                   [].\n          Pcase: h[6] > 6.\n            Hubcap T[1]<=2 T[3]<=0 T[4]<=2 T[5]<=0 T[6]<=0 T[2,7]<=6 [].\n          Hubcap T[1]<=2 T[2]<=3 T[3]<=0 T[4]<=2 T[6]<=0 T[5,7]<=3 [].\n        Pcase: f1[7] <= 5.\n          Reducible.\n        Pcase: s[6] > 6.\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=3 T[3]<=0 T[5]<=0 T[2,4]<=3 T[6,7]<=4 [].\n          Pcase: h[2] > 6.\n            Hubcap T[1]<=3 T[2]<=0 T[3]<=0 T[4]<=3 T[5]<=0 T[6]<=2 T[7]<=2 [].\n          Pcase: h[2] <= 5.\n            Hubcap T[1]<=3 T[3]<=0 T[4]<=2 T[5]<=0 T[7]<=3 T[2,6]<=2 [].\n          Pcase: h[6] <= 5.\n            Similar to *L2_4[6].\n          Hubcap T[1]<=3 T[2]<=1 T[3]<=0 T[5]<=0 T[7]<=2 T[4,6]<=4 [].\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=3 T[3]<=0 T[4,5]<=1 T[2,6]<=3 T[2,7]<=5 T[6,7]<=5 [].\n        Pcase: s[5] <= 6.\n          Reducible.\n        Pcase: h[3] <= 5.\n          Reducible.\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=3 T[3]<=0 T[5]<=0 T[2,4]<=2 T[6,7]<=5 [].\n        Hubcap T[1]<=3 T[3]<=0 T[4]<=1 T[5]<=0 T[2,6]<=3 T[2,7]<=5 T[6,7]<=5 [].\n      Pcase: h[2] <= 5.\n        Pcase: h[5] <= 5.\n          Pcase: f1[4] <= 6.\n            Reducible.\n          Pcase: s[6] <= 6.\n            Hubcap T[1]<=2 T[4]<=1 T[6]<=0 T[2,3]<=2 T[5,7]<=5 [].\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=2 T[2,3]<=2 T[4,5]<=3 T[6,7]<=3 [].\n          Pcase: f1[7] <= 5.\n            Reducible.\n          Pcase: s[3] <= 6.\n            Hubcap T[1]<=3 T[2]<=1 T[3]<=1 T[4]<=1 T[5]<=1 T[6]<=0 T[7]<=3 [].\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=3 T[4]<=0 T[7]<=3 T[2,3]<=2 T[5,6]<=2 [].\n          Hubcap T[1]<=3 T[4]<=2 T[5]<=1 T[6]<=(-1) T[7]<=3 T[2,3]<=2 [].\n        Pcase: s[7] > 6.\n          Pcase: s[3] <= 6.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4,5]<=3 T[6,7]<=3 [].\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4]<=0 T[6]<=0 T[5,7]<=5 [].\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4,5]<=2 T[6,7]<=3 [].\n          Pcase: h[5] > 6.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4]<=0 T[5]<=1 T[6,7]<=4 [].\n          Pcase: h[6] > 5.\n            Hubcap T[1]<=2 T[6]<=0 T[7]<=4 T[2,3]<=2 T[4,5]<=2 [].\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[6]<=1 T[7]<=1 T[4,5]<=3 [].\n        Pcase: f1[7] <= 5.\n          Reducible.\n        Pcase: s[6] > 6.\n          Pcase: s[3] > 7.\n            Hubcap T[1]<=3 T[3]<=0 T[7]<=3 T[2,6]<=2 T[4,5]<=2 [].\n          Pcase: s[3] <= 6.\n            Hubcap T[1]<=3 T[2]<=1 T[3]<=1 T[6]<=0 T[7]<=3 T[4,5]<=2 [].\n          Pcase: f1[2] <= 5.\n            Reducible.\n          Pcase: f2[3] <= 5.\n            Reducible.\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=3 T[2]<=1 T[3]<=1 T[4]<=0 T[5]<=1 T[6]<=1 T[7]<=3 [].\n          Pcase: h[6] <= 5.\n            Reducible.\n          Pcase: h[5] > 6.\n            Hubcap T[1]<=3 T[2]<=1 T[3]<=1 T[4]<=0 T[5]<=0 T[6]<=1 T[7]<=3 [].\n          Pcase: h[7] > 5.\n            Hubcap T[1]<=3 T[2]<=1 T[3]<=1 T[6]<=0 T[7]<=3 T[4,5]<=2 [].\n          Hubcap T[1]<=3 T[2]<=1 T[3]<=1 T[6]<=1 T[7]<=3 T[4,5]<=1 [].\n        Pcase: s[3] > 7.\n          Hubcap T[1]<=3 T[3]<=0 T[4]<=0 T[5]<=1 T[2,6]<=3 T[2,7]<=5 T[6,7]<=5\n                 [].\n        Pcase: f1[2] <= 5.\n          Reducible.\n        Pcase: s[5] > 6.\n          Hubcap T[1]<=3 T[2]<=1 T[3]<=1 T[4,5]<=0 T[6,7]<=5 [].\n        Hubcap T[1]<=3 T[2]<=1 T[3]<=1 T[4]<=0 T[5]<=0 T[6,7]<=5 [].\n      Pcase: h[6] <= 5.\n        Similar to *L2_4[6].\n      Pcase: s[6] <= 6.\n        Pcase: s[3] > 7.\n          Hubcap T[1]<=3 T[2]<=1 T[3]<=0 T[4,7]<=4 T[5,6]<=2 [].\n        Pcase: s[7] > 6.\n          Pcase: s[3] > 6.\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[6]<=0 T[7]<=4 T[4,5]<=2 [].\n          Hubcap T[1]<=2 T[2]<=0 T[5]<=2 T[6]<=0 T[7]<=3 T[3,4]<=3 [].\n        Pcase: h[5] <= 5.\n          Reducible.\n        Pcase: f1[7] <= 5.\n          Reducible.\n        Pcase: s[5] > 6.\n          Hubcap T[1]<=3 T[2]<=0 T[5]<=(-1) T[3,4]<=3 T[6,7]<=5 [].\n        Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[4]<=0 T[5]<=0 T[6,7]<=5 [].\n      Pcase: s[7] > 6.\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=2 T[2,3]<=2 T[4,5]<=3 T[6,7]<=3 [].\n        Pcase: h[3] <= 5.\n          Reducible.\n        Pcase: s[5] > 6.\n          Hubcap T[1]<=2 T[2]<=0 T[5]<=2 T[6]<=0 T[7]<=3 T[3,4]<=3 [].\n        Pcase: h[5] > 5.\n          Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4,5]<=3 T[6,7]<=3 [].\n        Hubcap T[1]<=2 T[2]<=0 T[3]<=1 T[4]<=3 T[5]<=1 T[6,7]<=3 [].\n      Pcase: f1[7] <= 5.\n        Reducible.\n      Pcase: s[3] > 7.\n        Hubcap T[1]<=3 T[2]<=1 T[3]<=0 T[7]<=2 T[4,5]<=3 T[4,6]<=3 T[5,6]<=3 [].\n      Pcase: s[3] > 6.\n        Pcase: s[5] > 6.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[4]<=0 T[7]<=2 T[5,6]<=3 [].\n        Pcase: h[5] > 6.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[4]<=0 T[5]<=0 T[6]<=2 T[7]<=2 [].\n        Pcase: h[5] <= 5.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[4]<=2 T[5]<=1 T[6]<=0 T[7]<=2 [].\n        Pcase: h[6] <= 6.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[4]<=1 T[7]<=2 T[5,6]<=2 [].\n        Pcase: h[7] > 5.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[6]<=1 T[7]<=2 T[4,5]<=2 [].\n        Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[6]<=2 T[7]<=2 T[4,5]<=1 [].\n      Pcase: h[3] <= 5.\n        Reducible.\n      Pcase: s[5] > 6.\n        Hubcap T[1]<=3 T[2]<=0 T[5]<=1 T[6]<=1 T[7]<=2 T[3,4]<=3 [].\n      Hubcap T[1]<=3 T[2]<=0 T[7]<=2 T[3,5]<=2 T[4,6]<=3 [].\n    Pcase: h[2] > 5.\n      Pcase: h[6] <= 5.\n        Similar to *L2_4[6].\n      Pcase: f1[2] <= 5.\n        Pcase: h[2] <= 6.\n          Reducible.\n        Pcase: s[3] > 7.\n          Pcase: s[4] > 6.\n            Hubcap T[1]<=3 T[2]<=1 T[3]<=(-1) T[4,5]<=2 T[6,7]<=5 [].\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=3 T[2]<=1 T[3]<=(-1) T[4]<=0 T[5]<=2 T[6,7]<=5 [].\n          Pcase: s[6] > 6.\n            Hubcap T[2]<=1 T[3]<=(-1) T[1,7]<=5 T[4,5]<=3 T[4,6]<=4 T[5,6]<=4 [].\n          Hubcap T[1]<=3 T[2]<=1 T[3]<=(-1) T[4]<=1 T[7]<=4 T[5,6]<=2 [].\n        Pcase: h[7] > 6.\n          Pcase: s[3] > 6.\n            Hubcap T[2]<=1 T[6]<=1 T[7]<=2 T[1,3]<=3 T[4,5]<=3 [].\n          Pcase: s[4] > 6.\n            Hubcap T[1]<=3 T[2]<=2 T[7]<=2 T[3,4]<=2 T[5,6]<=1 [].\n          Hubcap T[2]<=1 T[4]<=1 T[5]<=1 T[6]<=1 T[7]<=2 T[1,3]<=4 [].\n        Pcase: s[3] > 6.\n          Pcase: h[5] > 6.\n            Hubcap T[2]<=1 T[4]<=0 T[5]<=1 T[1,3]<=3 T[6,7]<=5 [].\n          Pcase: s[6] <= 6.\n            Pcase: s[4] <= 6.\n              Hubcap T[2]<=1 T[1,3]<=3 T[4,7]<=4 T[5,6]<=2 [].\n            Pcase: s[5] > 6.\n              Hubcap T[2]<=1 T[4]<=0 T[5]<=1 T[1,3]<=3 T[6,7]<=5 [].\n            Hubcap T[2]<=1 T[4]<=1 T[1,3]<=3 T[5,6]<=2 T[5,7]<=4 T[6,7]<=5 [].\n          Pcase: s[4] > 6.\n            Hubcap T[2]<=1 T[5]<=0 T[4,6]<=4 T[1,3]<=3 T[1,7]<=5 T[3,7]<=3 [].\n          Pcase: h[3] <= 5.\n            Reducible.\n          Pcase: f2[3] <= 5.\n            Reducible.\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4,5]<=3 T[6,7]<=3 [].\n          Hubcap T[1]<=3 T[2]<=1 T[3]<=0 T[7]<=2 T[4,5]<=3 T[4,6]<=3 T[5,6]<=3\n                 [].\n        Pcase: s[4] > 6.\n          Pcase: f1[4] <= 5.\n            Reducible.\n          Pcase: s[6] > 6.\n            Hubcap T[5]<=0 T[1,7]<=5 T[2,4]<=2 T[3,6]<=3 [].\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=2 T[2,4]<=2 T[3,6]<=2 T[5,7]<=4 [].\n          Hubcap T[1]<=3 T[2]<=1 T[3]<=0 T[4]<=0 T[5]<=1 T[6,7]<=5 [].\n        Pcase: h[3] <= 5.\n          Reducible.\n        Pcase: f1[3] <= 5.\n          Reducible.\n        Pcase: f1[4] <= 5.\n          Reducible.\n        Pcase: s[7] > 6.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=1 T[5]<=1 T[6,7]<=3 [].\n        Pcase: h[3] <= 6.\n          Reducible.\n        Pcase: f1[7] <= 5.\n          Reducible.\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=3 T[2]<=1 T[3]<=1 T[4]<=1 T[5]<=1 T[6]<=1 T[7]<=2 [].\n        Pcase: s[5] <= 6.\n          Reducible.\n        Pcase: h[5] <= 5.\n          Reducible.\n        Hubcap T[1]<=3 T[2]<=1 T[3]<=1 T[4]<=1 T[5]<=(-1) T[6,7]<=5 [].\n      Pcase: s[3] > 7.\n        Pcase: s[7] > 6.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=(-1) T[4,5]<=3 T[6,7]<=4 [].\n        Pcase: f1[7] <= 5.\n          Reducible.\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=(-1) T[7]<=2 T[4,5]<=3 T[4,6]<=3\n                 T[5,6]<=3 [].\n        Hubcap T[1]<=3 T[2]<=2 T[3]<=(-1) T[4,5]<=1 T[6,7]<=5 [].\n      Pcase: h[3] <= 5.\n        Pcase: s[4] <= 6.\n          Reducible.\n        Pcase: f1[4] <= 5.\n          Reducible.\n        Pcase: s[3] <= 6.\n          Hubcap T[1]<=2 T[2]<=3 T[3]<=1 T[4]<=0 T[5]<=1 T[6]<=1 T[7]<=2 [].\n        Pcase: s[7] > 6.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4]<=1 T[5,6]<=1 T[5,7]<=4 T[6,7]<=4\n                 [].\n        Pcase: f1[3] <= 5.\n          Reducible.\n        Pcase: f1[7] <= 5.\n          Reducible.\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=1 T[5]<=0 T[6]<=2 T[7]<=2 [].\n        Pcase: s[5] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=0 T[5]<=0 T[6,7]<=5 [].\n        Pcase: h[2] > 6.\n          Hubcap T[1]<=3 T[2]<=1 T[3]<=0 T[4]<=1 T[5]<=0 T[6,7]<=5 [].\n        Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=1 T[5]<=0 T[6,7]<=4 [].\n      Pcase: h[7] > 6.\n        Pcase: s[5] > 6.\n          Hubcap T[6]<=0 T[7]<=2 T[4,5]<=2 T[1,2]<=5 T[1,3]<=4 T[2,3]<=4 [].\n        Pcase: h[5] > 6.\n          Hubcap T[7]<=2 T[1,2]<=5 T[3,4]<=2 T[5,6]<=1 [].\n        Pcase: s[3] > 6.\n          Pcase: s[4] > 6.\n            Hubcap T[1]<=3 T[4]<=2 T[7]<=2 T[2,3]<=2 T[5,6]<=1 [].\n          Pcase: f2[3] <= 5.\n            Reducible.\n          Pcase: s[6] <= 6.\n            Hubcap T[1]<=3 T[2]<=2 T[3]<=1 T[6]<=0 T[7]<=2 T[4,5]<=2 [].\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4,5]<=3 T[6,7]<=2 [].\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[6]<=0 T[7]<=2 T[4,5]<=3 [].\n        Pcase: s[4] > 6.\n          Hubcap T[1]<=3 T[4]<=1 T[7]<=2 T[2,3]<=3 T[5,6]<=1 [].\n        Hubcap T[3]<=1 T[4]<=1 T[5]<=1 T[6]<=1 T[7]<=2 T[1,2]<=4 [].\n      Pcase: s[3] > 6.\n        Pcase: s[6] <= 6.\n          Pcase: s[7] > 6.\n            Pcase: s[4] > 6.\n              Hubcap T[1]<=2 T[4]<=1 T[5]<=1 T[2,3]<=2 T[6,7]<=4 [].\n            Pcase: f2[3] <= 5.\n              Reducible.\n            Pcase: s[5] > 6.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4]<=0 T[6]<=0 T[5,7]<=5 [].\n            Hubcap T[1]<=2 T[2]<=2 T[6]<=0 T[3,5]<=2 T[4,7]<=4 [].\n          Pcase: f1[7] <= 5.\n            Reducible.\n          Pcase: s[4] > 6.\n            Hubcap T[1]<=3 T[2,3]<=1 T[4,5]<=1 T[6,7]<=5 [].\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=0 T[5]<=0 T[6,7]<=5 [].\n        Pcase: s[7] > 6.\n          Pcase: s[4] > 6.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4]<=2 T[5]<=0 T[6,7]<=3 [].\n          Pcase: f2[3] <= 5.\n            Reducible.\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4]<=0 T[5]<=2 T[6]<=0 T[7]<=3 [].\n          Hubcap T[1]<=2 T[2]<=2 T[6,7]<=3 T[3,4]<=2 T[3,5]<=2 T[4,5]<=3 [].\n        Pcase: f1[7] <= 5.\n          Reducible.\n        Pcase: s[4] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[5]<=0 T[7]<=2 T[4,6]<=3 [].\n        Pcase: f2[3] <= 5.\n          Reducible.\n        Pcase: s[5] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=0 T[7]<=2 T[5,6]<=3 [].\n        Pcase: h[2] > 6.\n          Hubcap T[1]<=3 T[2]<=1 T[3]<=0 T[7]<=2 T[4,5]<=3 T[4,6]<=3 T[5,6]<=3\n                 [].\n        Pcase: h[5] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=2 T[7]<=2 [].\n        Pcase: h[5] <= 5.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=2 T[5]<=1 T[6]<=0 T[7]<=2 [].\n        Pcase: h[6] <= 6.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=1 T[7]<=2 T[5,6]<=2 [].\n        Pcase: h[7] > 5.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[6]<=1 T[7]<=2 T[4,5]<=2 [].\n        Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[6]<=2 T[7]<=2 T[4,5]<=1 [].\n      Pcase: s[4] > 6.\n        Pcase: f1[4] <= 5.\n          Reducible.\n        Pcase: s[7] > 6.\n          Hubcap T[1]<=2 T[4]<=1 T[2,3]<=3 T[5,6]<=1 T[5,7]<=4 T[6,7]<=4 [].\n        Pcase: f1[7] <= 5.\n          Reducible.\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=1 T[5]<=0 T[6]<=2 T[7]<=2 [].\n        Pcase: s[5] <= 6.\n          Reducible.\n        Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=0 T[5]<=0 T[6,7]<=5 [].\n      Pcase: h[2] <= 6.\n        Reducible.\n      Pcase: f1[3] <= 5.\n        Reducible.\n      Pcase: f1[4] <= 5.\n        Reducible.\n      Pcase: s[7] > 6.\n        Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4]<=1 T[5]<=1 T[6,7]<=3 [].\n      Pcase: f1[7] <= 5.\n        Reducible.\n      Pcase: s[6] > 6.\n        Hubcap T[1]<=3 T[2]<=1 T[3]<=1 T[4]<=1 T[5]<=1 T[6]<=1 T[7]<=2 [].\n      Pcase: s[5] <= 6.\n        Reducible.\n      Pcase: h[5] <= 5.\n        Reducible.\n      Hubcap T[1]<=3 T[2]<=1 T[3]<=1 T[4]<=1 T[5]<=(-1) T[6,7]<=5 [].\n    Pcase: f1[2] <= 5.\n      Reducible.\n    Pcase L2_6: s[3] <= 6.\n      Pcase: s[4] <= 6.\n        Reducible.\n      Pcase: f1[4] <= 5.\n        Reducible.\n      Pcase: s[7] > 6.\n        Hubcap T[1]<=3 T[4]<=0 T[5,6]<=1 T[2,3]<=5 T[2,7]<=5 T[3,7]<=3 [].\n      Pcase: h[3] <= 5.\n        Reducible.\n      Pcase: f1[7] <= 5.\n        Reducible.\n      Pcase: s[6] > 6.\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=3 [].\n      Pcase: s[5] <= 6.\n        Reducible.\n      Pcase: h[7] <= 5.\n        Reducible.\n      Hubcap T[1]<=4 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=3 [].\n    Pcase: s[7] > 6.\n      Pcase: h[6] <= 5.\n        Similar to *L2_5[6].\n      Pcase: s[3] > 7.\n        Hubcap T[1]<=3 T[2]<=3 T[3]<=(-1) T[7]<=2 T[4,5]<=3 T[4,6]<=2 T[5,6]<=2 [].\n      Hubcap T[1]<=3 T[2]<=3 T[3,7]<=2 T[4,5]<=2 T[4,6]<=2 T[5,6]<=1 [].\n    Pcase: f1[7] <= 5.\n      Reducible.\n    Pcase: s[6] <= 6.\n      Pcase: h[6] <= 5.\n        Similar to *L2_6[6].\n      Pcase: h[7] <= 5.\n        Reducible.\n      Pcase: s[3] > 7.\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=(-1) T[6]<=0 T[7]<=3 T[4,5]<=1 [].\n      Pcase: s[4] <= 6.\n        Reducible.\n      Pcase: s[5] > 6.\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=3 [].\n      Hubcap T[1]<=4 T[2]<=3 T[5]<=0 T[6]<=0 T[7]<=3 T[3,4]<=0 [].\n    Pcase: s[3] > 7.\n      Pcase: h[6] <= 5.\n        Similar to *L2_3[6].\n      Pcase: s[4] > 6.\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=(-1) T[5]<=0 T[7]<=3 T[4,6]<=1 [].\n      Pcase: s[5] > 6.\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=(-1) T[4]<=0 T[7]<=3 T[5,6]<=1 [].\n      Pcase: h[5] <= 5.\n        Reducible.\n      Pcase: h[5] > 6.\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=(-1) T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=3 [].\n      Pcase: h[7] > 5.\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=(-1) T[6]<=(-1) T[7]<=3 T[4,5]<=2 [].\n      Hubcap T[1]<=4 T[2]<=3 T[3]<=(-1) T[6]<=0 T[7]<=3 T[4,5]<=1 [].\n    Pcase: s[4] <= 6.\n      Reducible.\n    Pcase: s[5] > 6.\n      Hubcap T[1]<=4 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=3 [].\n    Pcase: h[6] <= 5.\n      Reducible.\n    Pcase: h[3] > 5.\n      Hubcap T[1]<=4 T[2]<=3 T[3]<=(-1) T[5]<=0 T[7]<=3 T[4,6]<=1 [].\n    Pcase: h[5] <= 5.\n      Reducible.\n    Pcase: f1[2] <= 6.\n      Reducible.\n    Pcase: f1[3] <= 5.\n      Reducible.\n    Pcase: f1[4] <= 5.\n      Reducible.\n    Pcase: h[5] > 6.\n      Hubcap T[1]<=4 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=3 [].\n    Pcase: h[7] > 5.\n      Hubcap T[1]<=4 T[2]<=3 T[3]<=0 T[4]<=1 T[5]<=0 T[6]<=(-1) T[7]<=3 [].\n    Pcase: f1[7] <= 6.\n      Reducible.\n    Pcase: f2[6] <= 5.\n      Reducible.\n    Pcase: f1[4] <= 6.\n      Hubcap T[1]<=4 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=3 [].\n    Pcase: f2[4] > 5.\n      Hubcap T[1]<=4 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=3 [].\n    Hubcap T[1]<=4 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=3 [].\n  Pcase: h[6] <= 5.\n    Similar to *L1_4[6].\n  Pcase L1_5: h[2] > 5.\n    Pcase L2_1: s[7] > 7.\n      Pcase: s[2] > 7.\n        Hubcap T[1]<=2 T[2]<=0 T[7]<=0 T[3,4]<=4 T[5,6]<=4 [].\n      Pcase: s[3] > 8.\n        Hubcap T[1]<=2 T[2]<=2 T[3]<=0 T[4]<=2 T[7]<=0 T[5,6]<=4 [].\n      Pcase: s[4] > 6.\n        Hubcap T[1]<=2 T[7]<=0 T[5,6]<=2 T[2,3]<=4 T[2,4]<=5 T[3,4]<=4 [].\n      Pcase: s[5] > 6.\n        Hubcap T[1]<=2 T[6]<=0 T[7]<=0 T[2,3]<=4 T[4,5]<=4 [].\n      Pcase: s[6] > 6.\n        Hubcap T[1]<=2 T[6]<=1 T[7]<=0 T[2,3]<=4 T[4,5]<=3 [].\n      Pcase: s[2] > 6.\n        Hubcap T[1]<=2 T[4]<=2 T[7]<=0 T[2,3]<=3 T[5,6]<=3 [].\n      Pcase: s[3] > 6.\n        Hubcap T[1]<=2 T[2]<=2 T[7]<=0 T[3,4]<=3 T[5,6]<=3 [].\n      Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[4]<=0 T[5]<=2 T[6]<=1 T[7]<=0 [].\n    Pcase L2_2: s[4] > 7.\n      Pcase: s[2] > 7.\n        Hubcap T[1]<=3 T[2]<=0 T[3]<=0 T[4]<=0 T[5]<=1 T[6,7]<=5 [].\n      Pcase: s[3] > 8.\n        Hubcap T[2]<=2 T[3]<=0 T[4]<=0 T[1,5]<=3 T[6,7]<=5 [].\n      Pcase: s[6] > 7.\n        Hubcap T[1]<=3 T[4]<=0 T[5]<=0 T[6]<=1 T[7]<=2 T[2,3]<=4 [].\n      Pcase: h[3] > 6.\n        Hubcap T[2]<=2 T[3]<=0 T[4]<=0 T[1,5]<=3 T[6,7]<=5 [].\n      Pcase: h[7] > 6.\n        Hubcap T[4]<=0 T[1,5]<=3 T[2,3]<=4 T[6,7]<=3 [].\n      Pcase: s[2] > 6.\n        Pcase: s[3] > 6.\n          Hubcap T[3]<=0 T[4]<=0 T[5]<=1 T[1,2]<=4 T[6,7]<=5 [].\n        Pcase: s[5] > 7.\n          Hubcap T[3]<=0 T[4]<=0 T[5]<=0 T[1,2]<=5 T[6,7]<=5 [].\n        Pcase: s[6] > 6.\n          Hubcap T[3]<=0 T[4]<=0 T[5]<=0 T[1,2]<=5 T[6,7]<=5 [].\n        Pcase: s[7] > 6.\n          Hubcap T[1]<=2 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=1 T[6,7]<=4 [].\n        Hubcap T[3]<=0 T[4]<=0 T[6]<=2 T[1,5]<=3 T[2,7]<=5 [].\n      Pcase: s[3] > 7.\n        Hubcap T[2]<=2 T[4]<=0 T[5]<=1 T[1,3]<=2 T[6,7]<=5 [].\n      Pcase: s[3] > 6.\n        Pcase: s[7] > 6.\n          Hubcap T[1]<=2 T[4]<=0 T[5]<=1 T[2,3]<=3 T[6,7]<=4 [].\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[4]<=0 T[5]<=0 T[6]<=2 T[3,7]<=3 [].\n        Pcase: s[5] > 6.\n          Hubcap T[4]<=0 T[1,3]<=4 T[2,5]<=1 T[6,7]<=5 [].\n        Pcase: h[2] > 6.\n          Hubcap T[2]<=1 T[4]<=0 T[5]<=0 T[1,3]<=4 T[6,7]<=5 [].\n        Hubcap T[1]<=3 T[4]<=0 T[5]<=0 T[2,3]<=3 T[6,7]<=4 [].\n      Pcase: s[5] > 7.\n        Hubcap T[4]<=(-1) T[5]<=0 T[6,7]<=5 T[1,2]<=5 T[1,3]<=4 T[2,3]<=4 [].\n      Pcase: s[6] > 6.\n        Hubcap T[4]<=(-1) T[5]<=0 T[6,7]<=5 T[1,2]<=5 T[1,3]<=4 T[2,3]<=4 [].\n      Pcase: s[7] > 6.\n        Hubcap T[1]<=2 T[4]<=(-1) T[5]<=1 T[2,3]<=4 T[6,7]<=4 [].\n      Pcase: s[5] > 6.\n        Hubcap T[4]<=(-1) T[1,5]<=2 T[2,3]<=4 T[6,7]<=5 [].\n      Hubcap T[4]<=(-1) T[5]<=0 T[6,7]<=5 T[1,2]<=5 T[1,3]<=4 T[2,3]<=4 [].\n    Pcase: s[5] > 7.\n      Pcase: h[1] > 5.\n        Similar to *L2_2[6].\n      Pcase: s[2] > 7.\n        Hubcap T[1]<=3 T[2]<=0 T[5]<=0 T[3,4]<=2 T[6,7]<=5 [].\n      Pcase: s[3] > 7.\n        Hubcap T[2]<=2 T[4]<=0 T[5]<=0 T[1,3]<=3 T[6,7]<=5 [].\n      Pcase: s[6] > 8.\n        Hubcap T[1]<=3 T[4]<=1 T[5]<=0 T[6]<=0 T[7]<=2 T[2,3]<=4 [].\n      Pcase: s[7] > 6.\n        Pcase: s[2] > 6.\n          Hubcap T[1]<=2 T[4]<=1 T[5]<=0 T[6]<=0 T[7]<=4 T[2,3]<=3 [].\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=4 [].\n        Hubcap T[1]<=2 T[4]<=1 T[5]<=0 T[6]<=0 T[2,3]<=4 T[2,7]<=6 T[3,7]<=5 [].\n      Pcase: f1[7] <= 5.\n        Reducible.\n      Pcase: s[6] > 7.\n        Hubcap T[1]<=3 T[2]<=2 T[3]<=2 T[4]<=1 T[5]<=0 T[6]<=0 T[7]<=2 [].\n      Pcase: s[2] > 6.\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=3 T[2]<=1 T[3]<=1 T[4]<=0 T[5]<=0 T[6,7]<=5 [].\n        Pcase: h[3] <= 5.\n          Reducible.\n        Pcase: s[4] > 6.\n          Hubcap T[1]<=3 T[2]<=1 T[3]<=0 T[4]<=1 T[5]<=0 T[6,7]<=5 [].\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=3 T[2]<=1 T[5]<=0 T[6]<=2 T[7]<=2 T[3,4]<=2 [].\n        Hubcap T[1]<=3 T[2]<=1 T[5]<=(-1) T[3,4]<=2 T[6,7]<=5 [].\n      Pcase: s[3] > 6.\n        Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=0 T[5]<=0 T[6,7]<=5 [].\n      Pcase: h[3] <= 5.\n        Reducible.\n      Pcase: s[4] > 6.\n        Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=0 T[5]<=0 T[6,7]<=5 [].\n      Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=0 T[5]<=0 T[6,7]<=5 [].\n    Pcase: s[6] > 8.\n      Pcase: s[3] > 7.\n        Hubcap T[2]<=2 T[6]<=0 T[7]<=2 T[1,3]<=3 T[4,5]<=3 [].\n      Pcase: s[2] > 6.\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=3 T[6]<=0 T[7]<=2 T[2,3]<=2 T[4,5]<=3 [].\n        Pcase: s[4] > 6.\n          Hubcap T[1]<=3 T[3]<=0 T[5]<=0 T[6]<=0 T[7]<=2 T[2,4]<=5 [].\n        Pcase: s[2] > 7.\n          Hubcap T[1]<=3 T[2]<=0 T[5]<=2 T[6]<=0 T[7]<=2 T[3,4]<=3 [].\n        Pcase: s[7] > 6.\n          Hubcap T[1]<=2 T[6]<=0 T[7]<=2 T[2,3]<=3 T[4,5]<=3 [].\n        Hubcap T[1]<=3 T[6]<=(-1) T[7]<=2 T[2,3]<=3 T[4,5]<=3 [].\n      Pcase: s[3] <= 6.\n        Hubcap T[6]<=0 T[1,2]<=5 T[3,7]<=3 T[4,5]<=2 [].\n      Pcase: s[4] > 6.\n        Hubcap T[1]<=3 T[2]<=2 T[5]<=0 T[6]<=0 T[7]<=2 T[3,4]<=3 [].\n      Pcase: s[5] > 6.\n        Hubcap T[1]<=3 T[2]<=2 T[4]<=0 T[6]<=0 T[7]<=2 T[3,5]<=3 [].\n      Pcase: s[7] > 6.\n        Hubcap T[1]<=2 T[2]<=2 T[6]<=0 T[3,7]<=3 T[4,5]<=3 [].\n      Hubcap T[1]<=3 T[2]<=2 T[6]<=(-1) T[3,7]<=3 T[4,5]<=3 [].\n    Pcase: h[5] > 6.\n      Pcase: s[2] > 7.\n        Hubcap T[2]<=0 T[1,5]<=3 T[3,4]<=2 T[6,7]<=5 [].\n      Pcase: s[3] > 8.\n        Hubcap T[2]<=2 T[3]<=0 T[4]<=0 T[1,5]<=3 T[6,7]<=5 [].\n      Pcase: s[2] > 6.\n        Pcase: s[3] > 6.\n          Hubcap T[4]<=0 T[1,5]<=3 T[2,3]<=2 T[6,7]<=5 [].\n        Pcase: s[6] > 7.\n          Hubcap T[1]<=3 T[2]<=3 T[5]<=0 T[6]<=1 T[7]<=2 T[3,4]<=1 [].\n        Pcase: s[7] > 6.\n          Hubcap T[1]<=2 T[2,7]<=6 T[3,4]<=1 T[5,6]<=1 [].\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=3 T[5]<=0 T[6]<=2 T[2,7]<=4 T[3,4]<=1 [].\n        Pcase: s[5] > 6.\n          Hubcap T[6]<=2 T[1,5]<=2 T[2,7]<=5 T[3,4]<=1 [].\n        Pcase: h[3] > 5.\n          Hubcap T[1]<=3 T[2]<=1 T[5]<=0 T[3,4]<=1 T[6,7]<=5 [].\n        Hubcap T[1]<=2 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=1 T[7]<=2 [].\n      Pcase: s[3] > 7.\n        Hubcap T[2]<=2 T[4]<=0 T[5]<=1 T[1,3]<=2 T[6,7]<=5 [].\n      Pcase L3_1: s[4] <= 6.\n        Pcase: s[6] > 7.\n          Hubcap T[1]<=3 T[4]<=0 T[5]<=0 T[6]<=1 T[7]<=2 T[2,3]<=4 [].\n        Pcase: s[7] > 6.\n          Hubcap T[1]<=2 T[4]<=0 T[2,3]<=4 T[5,6]<=1 T[5,7]<=4 T[6,7]<=4 [].\n        Pcase: h[7] > 6.\n          Hubcap T[1]<=3 T[4]<=0 T[7]<=2 T[2,3]<=4 T[5,6]<=1 [].\n        Pcase: h[1] > 5.\n          Pcase: s[3] > 6.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=0 T[5]<=1 T[6,7]<=4 [].\n          Pcase: s[5] <= 6.\n            Hubcap T[1]<=2 T[4]<=0 T[5]<=0 T[2,3]<=4 T[6,7]<=4 [].\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[4]<=0 T[5]<=0 T[6]<=2 T[7]<=1 [].\n          Hubcap T[1]<=2 T[4]<=0 T[5]<=0 T[2,3]<=4 T[6,7]<=4 [].\n        Pcase: f1[7] <= 5.\n          Reducible.\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=1 T[4]<=0 T[5]<=0 T[6]<=2 T[7]<=2 [].\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=0 T[5]<=0 T[6,7]<=5 [].\n        Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=0 T[5]<=0 T[6,7]<=5 [].\n      Pcase: s[3] > 6.\n        Pcase: s[6] > 7.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=2 T[4]<=0 T[5]<=0 T[6]<=1 T[7]<=2 [].\n        Pcase: s[7] > 6.\n          Hubcap T[1]<=2 T[4]<=0 T[5]<=1 T[2,3]<=3 T[6,7]<=4 [].\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[4]<=0 T[5]<=0 T[6]<=2 T[3,7]<=3 [].\n        Pcase: s[5] > 6.\n          Hubcap T[4]<=0 T[1,3]<=4 T[2,5]<=1 T[6,7]<=5 [].\n        Pcase: h[1] > 5.\n          Similar to *L3_1[6].\n        Pcase: f1[7] <= 5.\n          Reducible.\n        Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=0 T[5]<=0 T[6,7]<=5 [].\n      Pcase: s[6] > 7.\n        Hubcap T[1]<=3 T[2]<=3 T[4]<=0 T[5]<=0 T[6]<=1 T[3,7]<=3 [].\n      Pcase: s[7] > 6.\n        Hubcap T[1]<=2 T[4]<=0 T[2,3]<=4 T[5,6]<=1 T[5,7]<=4 T[6,7]<=4 [].\n      Pcase: s[6] > 6.\n        Hubcap T[4]<=0 T[5]<=0 T[6]<=2 T[1,2]<=5 T[3,7]<=3 [].\n      Pcase: s[5] > 6.\n        Pcase: h[2] <= 6.\n          Hubcap T[3]<=1 T[4]<=0 T[5]<=0 T[1,2]<=5 T[6,7]<=4 [].\n        Pcase: h[3] > 5.\n          Hubcap T[1]<=3 T[4]<=0 T[5]<=0 T[2,3]<=2 T[6,7]<=5 [].\n        Hubcap T[1]<=2 T[4]<=0 T[5]<=0 T[2,3]<=4 T[6,7]<=4 [].\n      Pcase: h[1] > 5.\n        Similar to *L3_1[6].\n      Pcase: h[3] <= 5.\n        Reducible.\n      Pcase: f1[7] <= 5.\n        Reducible.\n      Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=0 T[5]<=0 T[6,7]<=5 [].\n    Pcase: s[2] > 7.\n      Pcase: h[1] > 5.\n        Similar to *L2_1[6].\n      Pcase: s[6] <= 6.\n        Pcase: s[3] > 7.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=0 T[4,5]<=2 T[6,7]<=5 [].\n        Pcase: s[7] > 6.\n          Hubcap T[1]<=2 T[2]<=0 T[5]<=2 T[3,4]<=2 T[6,7]<=4 [].\n        Hubcap T[1]<=3 T[2]<=0 T[6,7]<=5 T[3,4]<=2 T[3,5]<=1 T[4,5]<=2 [].\n      Pcase: s[3] > 7.\n        Hubcap T[2]<=0 T[3]<=0 T[1,7]<=5 T[4,5]<=3 T[4,6]<=4 T[5,6]<=4 [].\n      Pcase: s[4] > 6.\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=0 T[4]<=2 T[5]<=0 T[6,7]<=5 [].\n        Pcase: s[5] > 6.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=0 T[4]<=1 T[5]<=0 T[6]<=3 T[7]<=3 [].\n        Pcase: s[6] > 7.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=0 T[4]<=4 T[5]<=0 T[6]<=0 T[7]<=2 [].\n        Pcase: s[7] > 6.\n          Hubcap T[1]<=2 T[2]<=0 T[3]<=0 T[4]<=4 T[5]<=0 T[6]<=1 T[7]<=3 [].\n        Hubcap T[1]<=3 T[2]<=0 T[3]<=0 T[5]<=0 T[7]<=2 T[4,6]<=5 [].\n      Pcase: s[7] > 6.\n        Hubcap T[1]<=2 T[2]<=0 T[5]<=2 T[3,4]<=3 T[6,7]<=3 [].\n      Pcase: f1[7] <= 5.\n        Reducible.\n      Pcase: s[3] > 6.\n        Hubcap T[1]<=3 T[2]<=0 T[3]<=1 T[7]<=2 T[4,5]<=3 T[4,6]<=3 T[5,6]<=3 [].\n      Pcase: s[5] > 6.\n        Hubcap T[1]<=3 T[2]<=0 T[7]<=2 T[3,4]<=2 T[5,6]<=3 [].\n      Hubcap T[1]<=3 T[2]<=0 T[7]<=2 T[3,4]<=3 T[5,6]<=2 [].\n    Pcase L2_3: s[3] > 7.\n      Pcase: s[5] > 6.\n        Pcase: s[6] > 7.\n          Hubcap T[1]<=3 T[2]<=2 T[4]<=0 T[6]<=1 T[7]<=2 T[3,5]<=2 [].\n        Pcase: s[7] > 6.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4]<=0 T[6]<=0 T[5,7]<=5 [].\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[4]<=0 T[3,7]<=2 T[5,6]<=3 [].\n        Hubcap T[4]<=0 T[1,3]<=3 T[2,5]<=2 T[6,7]<=5 [].\n      Pcase: s[6] > 7.\n        Hubcap T[2]<=2 T[6]<=0 T[7]<=2 T[1,3]<=3 T[4,5]<=3 [].\n      Pcase: s[2] > 6.\n        Pcase: s[7] > 6.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=0 T[4,5]<=3 T[6,7]<=4 [].\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=3 T[2]<=1 T[3]<=0 T[7]<=2 T[4,5]<=3 T[4,6]<=3 T[5,6]<=3\n                 [].\n        Hubcap T[1]<=3 T[2]<=1 T[3]<=0 T[4]<=1 T[5]<=0 T[6,7]<=5 [].\n      Pcase: h[7] > 6.\n        Hubcap T[2]<=2 T[1,3]<=2 T[4,5]<=3 T[6,7]<=3 [].\n      Pcase: h[1] > 5.\n        Hubcap T[1]<=2 T[2]<=1 T[3]<=0 T[4,5]<=3 T[6,7]<=4 [].\n      Pcase: s[6] <= 6.\n        Pcase: s[4] > 6.\n          Hubcap T[2]<=2 T[4]<=1 T[1,3]<=2 T[5,6]<=2 T[5,7]<=4 T[6,7]<=5 [].\n        Hubcap T[1]<=3 T[2]<=2 T[3]<=(-1) T[4,7]<=4 T[5,6]<=2 [].\n      Pcase: s[7] > 6.\n        Hubcap T[1]<=2 T[2]<=2 T[3]<=0 T[4,5]<=3 T[6,7]<=3 [].\n      Hubcap T[1]<=3 T[2]<=2 T[3]<=(-1) T[4]<=2 T[7]<=2 T[5,6]<=2 [].\n    Pcase: s[6] > 7.\n      Pcase: h[1] > 5.\n        Similar to *L2_3[6].\n      Pcase: s[7] > 6.\n        Pcase: s[4] > 6.\n          Hubcap T[1]<=2 T[5]<=0 T[6]<=0 T[2,7]<=4 T[3,4]<=4 [].\n        Pcase: s[2] > 6.\n          Hubcap T[1]<=2 T[6]<=0 T[7]<=2 T[2,3]<=3 T[4,5]<=3 [].\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=2 T[2]<=2 T[6]<=0 T[3,7]<=3 T[4,5]<=3 [].\n        Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[4]<=0 T[5]<=1 T[6]<=0 T[7]<=2 [].\n      Pcase: f1[7] <= 5.\n        Reducible.\n      Pcase: s[2] > 6.\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=3 T[2]<=1 T[3]<=1 T[6]<=0 T[7]<=2 T[4,5]<=3 [].\n        Pcase: h[3] <= 5.\n          Reducible.\n        Pcase: s[4] > 6.\n          Hubcap T[1]<=3 T[2]<=1 T[3]<=0 T[4]<=4 T[5]<=0 T[6]<=0 T[7]<=2 [].\n        Hubcap T[1]<=3 T[6]<=0 T[7]<=2 T[2,3]<=2 T[4,5]<=3 [].\n      Pcase: s[3] > 6.\n        Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[6]<=0 T[7]<=2 T[4,5]<=3 [].\n      Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=2 T[5]<=1 T[6]<=0 T[7]<=2 [].\n    Pcase L2_4: h[7] > 5.\n      Pcase L3_1: s[5] > 6.\n        Pcase: h[3] > 5.\n          Pcase: s[7] > 6.\n            Pcase: s[2] > 6.\n              Hubcap T[1]<=2 T[2]<=1 T[6]<=0 T[3,4]<=2 T[5,7]<=5 [].\n            Pcase: s[3] > 6.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4]<=0 T[6]<=0 T[5,7]<=5 [].\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4]<=1 T[6]<=0 T[5,7]<=4 [].\n          Pcase: s[6] <= 6.\n            Pcase: s[2] > 6.\n              Hubcap T[2]<=1 T[1,5]<=3 T[3,4]<=2 T[6,7]<=4 [].\n            Pcase: s[3] > 6.\n              Hubcap T[1]<=3 T[2]<=2 T[4]<=0 T[3,6]<=2 T[5,7]<=3 [].\n            Hubcap T[1]<=3 T[2,3]<=2 T[4,5]<=1 T[6,7]<=4 [].\n          Pcase: s[4] > 6.\n            Hubcap T[1]<=3 T[2]<=2 T[5]<=0 T[6]<=1 T[7]<=2 T[3,4]<=2 [].\n          Pcase: h[5] > 5.\n            Hubcap T[1]<=3 T[5]<=1 T[6]<=1 T[2,4]<=2 T[3,7]<=3 [].\n          Pcase: h[7] > 6.\n            Hubcap T[1]<=3 T[2]<=2 T[5]<=2 T[6]<=(-1) T[7]<=2 T[3,4]<=2 [].\n          Pcase: h[1] > 5.\n            Hubcap T[1]<=2 T[2]<=2 T[5]<=2 T[6]<=1 T[7]<=1 T[3,4]<=2 [].\n          Pcase: f1[7] <= 5.\n            Reducible.\n          Pcase: s[2] > 6.\n            Hubcap T[1]<=3 T[5]<=2 T[7]<=2 T[2,6]<=1 T[3,4]<=2 [].\n          Pcase: s[3] > 6.\n            Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=0 T[5]<=2 T[6]<=1 T[7]<=2 [].\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=0 T[5]<=1 T[6]<=1 T[7]<=2 [].\n        Pcase: s[2] > 6.\n          Pcase: s[4] > 6.\n            Hubcap T[3]<=0 T[4]<=0 T[5]<=1 T[1,2]<=5 T[6,7]<=4 [].\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=2 T[4]<=0 T[6]<=0 T[2,3]<=3 T[5,7]<=5 [].\n          Pcase: s[3] <= 6.\n            Hubcap T[1]<=2 T[4]<=0 T[5]<=2 T[2,3]<=3 T[6,7]<=3 [].\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=3 T[4]<=0 T[5]<=2 T[6]<=1 T[7]<=2 T[2,3]<=2 [].\n          Hubcap T[1]<=3 T[4]<=0 T[5]<=1 T[2,3]<=2 T[6,7]<=4 [].\n        Pcase: s[7] > 6.\n          Hubcap T[1]<=2 T[6]<=0 T[2,3]<=4 T[4,5]<=2 T[4,7]<=3 T[5,7]<=4 [].\n        Pcase: s[3] > 6.\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=3 T[2]<=2 T[4]<=0 T[5]<=1 T[6]<=1 T[3,7]<=3 [].\n          Hubcap T[4]<=0 T[1,3]<=4 T[2,5]<=2 T[6,7]<=4 [].\n        Pcase: h[1] <= 5.\n          Reducible.\n        Pcase: s[4] > 6.\n          Hubcap T[1]<=2 T[4]<=0 T[5]<=1 T[2,3]<=4 T[6,7]<=3 [].\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[4]<=0 T[5]<=1 T[6]<=1 T[7]<=1 [].\n        Hubcap T[1]<=2 T[2]<=3 T[3]<=2 T[4]<=0 T[5]<=1 T[6,7]<=2 [].\n      Pcase: s[4] > 6.\n        Pcase: s[2] > 6.\n          Pcase: s[3] > 6.\n            Hubcap T[3]<=0 T[1,2]<=4 T[4,7]<=4 T[5,6]<=2 [].\n          Pcase: h[3] <= 5.\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=0 T[4,7]<=3 T[5,6]<=2 [].\n          Pcase: h[1] > 5.\n            Similar to *L3_1[6].\n          Pcase: s[6] <= 6.\n            Hubcap T[2]<=1 T[3]<=0 T[4]<=2 T[1,5]<=3 T[6,7]<=4 [].\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=0 T[4]<=4 T[5]<=0 T[6]<=1 T[7]<=2 [].\n          Hubcap T[1]<=3 T[3]<=0 T[4]<=4 T[5]<=0 T[7]<=2 T[2,6]<=1 [].\n        Pcase: s[3] <= 6.\n          Pcase: h[2] <= 6.\n            Hubcap T[1,3]<=3 T[2,4]<=3 T[5,6]<=2 T[5,7]<=3 T[6,7]<=4 [].\n          Pcase: h[3] > 5.\n            Hubcap T[4]<=1 T[1,5]<=3 T[2,3]<=2 T[6,7]<=4 [].\n          Hubcap T[1]<=2 T[4]<=0 T[5]<=1 T[2,3]<=4 T[6,7]<=3 [].\n        Pcase: h[3] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=(-1) T[4,7]<=4 T[5,6]<=2 [].\n        Pcase: h[1] > 5.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4,7]<=3 T[5,6]<=2 [].\n        Pcase: s[7] > 6.\n          Hubcap T[1]<=2 T[2,3]<=3 T[4,7]<=4 T[5,6]<=1 [].\n        Hubcap T[1]<=3 T[2]<=2 T[5]<=0 T[3,4]<=1 T[6,7]<=4 [].\n      Pcase: f1[5] > 5.\n        Pcase: s[7] > 6.\n          Pcase: h[1] > 6.\n            Hubcap T[1]<=2 T[5]<=2 T[6,7]<=1 T[2,3]<=4 T[2,4]<=3 T[3,4]<=4 [].\n          Pcase: h[5] > 5.\n            Pcase: s[2] > 6.\n              Hubcap T[1]<=2 T[2,3]<=3 T[4,5]<=2 T[6,7]<=3 [].\n            Hubcap T[1]<=2 T[4]<=0 T[2,3]<=4 T[5,6]<=2 T[5,7]<=4 T[6,7]<=3 [].\n          Pcase: s[2] > 6.\n            Hubcap T[1]<=2 T[5]<=2 T[6,7]<=2 T[2,3]<=3 T[2,4]<=3 T[3,4]<=3 [].\n          Pcase: s[3] <= 6.\n            Reducible.\n          Hubcap T[1]<=2 T[4]<=1 T[5]<=2 T[2,3]<=3 T[6,7]<=2 [].\n        Pcase: s[6] > 6.\n          Pcase: h[1] > 5.\n            Hubcap T[1]<=2 T[7]<=1 T[5,6]<=2 T[2,3]<=4 T[2,4]<=3 T[3,4]<=4 [].\n          Pcase: f1[7] <= 5.\n            Reducible.\n          Pcase: s[2] > 6.\n            Hubcap T[1]<=3 T[7]<=2 T[2,3]<=2 T[4,5]<=3 T[4,6]<=2 T[5,6]<=2 [].\n          Pcase: s[3] > 6.\n            Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=1 T[7]<=2 T[5,6]<=2 [].\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=1 T[7]<=2 [].\n        Pcase: h[5] <= 5.\n          Reducible.\n        Pcase: f1[4] <= 5.\n          Reducible.\n        Pcase: s[2] > 6.\n          Hubcap T[5]<=0 T[1,2]<=5 T[3,4]<=1 T[6,7]<=4 [].\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=3 T[4]<=0 T[5]<=0 T[2,3]<=3 T[6,7]<=4 [].\n        Hubcap T[4]<=0 T[5]<=0 T[1,2]<=5 T[3,6]<=3 T[3,7]<=4 T[6,7]<=4 [].\n      Pcase: f1[4] <= 5.\n        Reducible.\n      Pcase: h[1] > 5.\n        Pcase: s[2] <= 6.\n          Hubcap T[1]<=2 T[2]<=1 T[5]<=1 T[6]<=2 T[7]<=1 T[3,4]<=3 [].\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=2 T[4]<=2 T[5]<=1 T[6]<=2 T[7]<=1 T[2,3]<=2 [].\n        Pcase: s[6] <= 6.\n          Hubcap T[1]<=2 T[4]<=2 T[5]<=1 T[2,3]<=3 T[6,7]<=2 [].\n        Pcase: s[7] > 6.\n          Hubcap T[1]<=2 T[4]<=2 T[5]<=1 T[6]<=1 T[7]<=1 T[2,3]<=3 [].\n        Hubcap T[1]<=2 T[4]<=2 T[5]<=1 T[6]<=1 T[7]<=1 T[2,3]<=3 [].\n      Pcase: s[6] <= 6.\n        Hubcap T[1]<=2 T[4]<=2 T[5]<=0 T[6]<=0 T[7]<=3 T[2,3]<=3 [].\n      Pcase: s[7] > 6.\n        Hubcap T[1]<=2 T[4]<=2 T[5]<=1 T[2,3]<=3 T[6,7]<=2 [].\n      Pcase: f1[7] <= 5.\n        Reducible.\n      Pcase: s[2] > 6.\n        Hubcap T[1]<=3 T[2]<=1 T[3]<=1 T[4]<=2 T[7]<=2 T[5,6]<=1 [].\n      Pcase: s[3] <= 6.\n        Reducible.\n      Pcase: h[3] <= 5.\n        Reducible.\n      Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=2 T[7]<=2 T[5,6]<=1 [].\n    Pcase: h[3] <= 5.\n      Pcase L3_1: s[3] <= 6.\n        Pcase: s[2] > 6.\n          Pcase: s[4] > 6.\n            Hubcap T[1]<=2 T[3]<=0 T[5]<=0 T[2,4]<=4 T[6,7]<=4 [].\n          Pcase: s[7] > 6.\n            Pcase: s[5] > 6.\n              Hubcap T[1]<=2 T[2]<=3 T[3]<=1 T[4]<=0 T[6]<=0 T[5,7]<=4 [].\n            Pcase: h[4] > 6.\n              Hubcap T[1]<=2 T[3]<=0 T[6,7]<=3 T[2,4]<=4 T[2,5]<=4 T[4,5]<=3 [].\n            Pcase: f1[3] <= 6.\n              Reducible.\n            Pcase: f1[4] <= 5.\n              Reducible.\n            Pcase: s[6] <= 6.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4,6]<=2 T[5,7]<=3 [].\n            Pcase: h[5] > 5.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=0 T[4]<=1 T[5]<=0 T[6]<=1 T[7]<=2 [].\n            Pcase: f2[2] <= 5.\n              Reducible.\n            Pcase: h[6] > 6.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4]<=2 T[5]<=1 T[6]<=0 T[7]<=2 [].\n            Pcase: h[1] > 5.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4]<=2 T[5]<=1 T[6,7]<=2 [].\n            Pcase: f2[7] <= 5.\n              Reducible.\n            Pcase: f1[2] > 5.\n              Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=2 T[5]<=1 T[6]<=1 T[7]<=2 [].\n            Pcase: f1[4] > 6.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=0 T[4]<=2 T[5]<=1 T[6]<=1 T[7]<=2 [].\n            Pcase: f1[5] > 5.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4]<=1 T[5]<=1 T[6]<=1 T[7]<=2 [].\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4]<=2 T[5]<=1 T[6,7]<=2 [].\n          Pcase: s[6] <= 6.\n            Reducible.\n          Pcase: h[1] <= 5.\n            Reducible.\n          Hubcap T[1]<=2 T[4]<=1 T[5]<=1 T[6]<=2 T[7]<=1 T[2,3]<=3 [].\n        Pcase: s[7] > 6.\n          Hubcap T[1]<=2 T[4]<=1 T[7]<=2 T[2,3]<=4 T[5,6]<=1 [].\n        Pcase: h[1] <= 5.\n          Reducible.\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=2 T[6]<=2 T[7]<=1 T[2,3]<=4 T[4,5]<=1 [].\n        Pcase L4_1: s[4] > 6.\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=2 T[4]<=0 T[5]<=0 T[2,3]<=4 T[6,7]<=4 [].\n          Hubcap T[1]<=2 T[4]<=0 T[5]<=0 T[2,3]<=4 T[6,7]<=4 [].\n        Pcase: s[5] > 6.\n          Similar to *L4_1[6].\n        Pcase: h[5] <= 5.\n          Reducible.\n        Pcase: f1[4] <= 5.\n          Reducible.\n        Pcase: f1[5] <= 5.\n          Reducible.\n        Hubcap T[1]<=2 T[4]<=0 T[5]<=0 T[2,3]<=4 T[6,7]<=4 [].\n      Pcase: s[2] > 6.\n        Pcase: f1[3] <= 5.\n          Pcase: s[4] > 6.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=0 T[4,5]<=2 T[6,7]<=4 [].\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=2 T[4]<=0 T[5]<=2 T[2,3]<=2 T[6,7]<=4 [].\n          Pcase: s[7] <= 6.\n            Hubcap T[1]<=2 T[4]<=1 T[5]<=1 T[2,3]<=2 T[6,7]<=4 [].\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=2 T[6]<=1 T[7]<=2 T[2,3]<=2 T[4,5]<=3 [].\n          Pcase: h[1] > 5.\n            Similar to *L3_1[6].\n          Pcase: h[5] <= 5.\n            Reducible.\n          Pcase: f2[7] <= 5.\n            Reducible.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[6]<=0 T[7]<=4 T[4,5]<=1 [].\n        Pcase: s[4] > 6.\n          Hubcap T[3]<=0 T[1,4]<=4 T[2,5]<=1 T[6,7]<=5 [].\n        Pcase: f2[2] <= 5.\n          Hubcap T[2]<=0 T[3]<=0 T[6,7]<=5 T[1,4]<=4 T[1,5]<=4 T[4,5]<=3 [].\n        Pcase: s[6] <= 6.\n          Pcase: h[1] > 5.\n            Similar to *L3_1[6].\n          Hubcap T[3]<=1 T[1,2]<=3 T[4,6]<=1 T[5,7]<=5 [].\n        Pcase: s[7] > 6.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4,5]<=3 T[6,7]<=3 [].\n        Pcase: s[5] > 6.\n          Hubcap T[1]<=3 T[2]<=1 T[3]<=1 T[4]<=0 T[5]<=1 T[6]<=2 T[7]<=2 [].\n        Hubcap T[1]<=3 T[2]<=1 T[3]<=1 T[4]<=1 T[6]<=2 T[5,7]<=2 [].\n      Pcase L3_2: s[4] > 6.\n        Pcase: s[7] > 6.\n          Hubcap T[1]<=2 T[4]<=1 T[5]<=0 T[2,3]<=3 T[6,7]<=4 [].\n        Pcase: s[6] > 6.\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=3 T[2]<=2 T[4]<=0 T[5]<=0 T[6]<=2 T[3,7]<=3 [].\n          Pcase: h[2] > 6.\n            Hubcap T[1]<=3 T[2]<=1 T[4]<=1 T[5]<=0 T[6]<=2 T[3,7]<=3 [].\n          Pcase: f1[2] <= 6.\n            Reducible.\n          Pcase: h[6] <= 6.\n            Hubcap T[1]<=3 T[2]<=2 T[4]<=1 T[5]<=0 T[6]<=1 T[3,7]<=3 [].\n          Pcase: h[1] > 5.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=1 T[5]<=0 T[6]<=2 T[7]<=1 [].\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=1 T[5]<=0 T[6]<=2 T[7]<=2 [].\n        Pcase: h[1] > 5.\n          Similar to *L3_1[6].\n        Pcase: h[2] <= 6.\n          Reducible.\n        Pcase: f1[3] <= 5.\n          Reducible.\n        Pcase: f1[7] <= 6.\n          Reducible.\n        Hubcap T[1]<=3 T[2]<=1 T[3]<=0 T[6]<=1 T[7]<=4 T[4,5]<=1 [].\n      Pcase: s[6] <= 6.\n        Pcase: h[1] > 5.\n          Similar to *L3_1[6].\n        Hubcap T[4]<=0 T[7]<=4 T[5,6]<=1 T[1,2]<=4 T[1,3]<=4 T[2,3]<=3 [].\n      Pcase: s[7] > 6.\n        Hubcap T[1]<=2 T[4]<=1 T[5]<=1 T[2,3]<=3 T[6,7]<=3 [].\n      Pcase: s[5] <= 6.\n        Hubcap T[6]<=2 T[1,3]<=4 T[2,4]<=2 T[5,7]<=2 [].\n      Pcase: h[1] > 5.\n        Similar to *L3_2[6].\n      Pcase: f1[3] <= 5.\n        Reducible.\n      Pcase: f1[7] <= 6.\n        Reducible.\n      Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=0 T[5]<=1 T[6]<=2 T[7]<=2 [].\n    Pcase: h[1] > 5.\n      Similar to *L2_4[6].\n    Pcase: s[7] > 6.\n      Pcase: s[4] > 6.\n        Pcase: s[5] > 6.\n          Hubcap T[1]<=2 T[2]<=2 T[5]<=0 T[6]<=0 T[7]<=4 T[3,4]<=2 [].\n        Pcase: s[2] > 6.\n          Pcase: s[3] > 6.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=0 T[4]<=2 T[5]<=0 T[6]<=1 T[7]<=4 [].\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=0 T[4]<=4 T[5]<=0 T[6,7]<=3 [].\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=0 T[4]<=2 T[5]<=0 T[6]<=1 T[7]<=4 [].\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=2 T[4]<=2 T[5]<=0 T[2,3]<=3 T[6,7]<=3 [].\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4]<=1 T[5]<=0 T[6,7]<=4 [].\n        Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4]<=1 T[5]<=0 T[6,7]<=4 [].\n      Pcase: s[5] > 6.\n        Hubcap T[1]<=2 T[6]<=0 T[5,7]<=5 T[2,3]<=3 T[2,4]<=2 T[3,4]<=2 [].\n      Pcase: s[6] > 6.\n        Pcase: s[2] > 6.\n          Hubcap T[1]<=2 T[2,3]<=2 T[4,5]<=3 T[6,7]<=3 [].\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=2 T[2,3]<=2 T[4,5]<=3 T[6,7]<=3 [].\n        Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4]<=0 T[5]<=0 T[6]<=1 T[7]<=3 [].\n      Pcase: h[5] <= 5.\n        Reducible.\n      Pcase: s[2] > 6.\n        Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[6]<=0 T[7]<=4 T[4,5]<=2 [].\n      Hubcap T[1]<=2 T[6]<=0 T[7]<=4 T[2,3]<=3 T[4,5]<=1 [].\n    Pcase: f1[7] <= 6.\n      Reducible.\n    Pcase: s[6] <= 6.\n      Pcase: s[2] > 6.\n        Hubcap T[1]<=3 T[2]<=0 T[6]<=1 T[7]<=4 T[3,4]<=2 T[3,5]<=1 T[4,5]<=2 [].\n      Pcase: h[2] <= 6.\n        Reducible.\n      Pcase: s[3] > 6.\n        Hubcap T[1]<=3 T[2]<=1 T[3]<=0 T[6]<=1 T[7]<=4 T[4,5]<=1 [].\n      Pcase: s[4] > 6.\n        Hubcap T[1]<=3 T[2]<=1 T[3]<=0 T[6]<=1 T[7]<=4 T[4,5]<=1 [].\n      Hubcap T[1]<=3 T[2]<=1 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=1 T[7]<=4 [].\n    Pcase: s[3] > 6.\n      Pcase: s[2] > 6.\n        Hubcap T[1]<=3 T[2]<=1 T[3]<=1 T[6]<=2 T[7]<=2 T[4,5]<=1 [].\n      Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[6]<=2 T[7]<=2 T[4,5]<=1 [].\n    Pcase: h[4] > 6.\n      Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[6]<=2 T[7]<=2 T[4,5]<=1 [].\n    Pcase: f1[6] > 5.\n      Hubcap T[1]<=3 T[6]<=1 T[7]<=2 T[2,3]<=2 T[4,5]<=2 [].\n    Pcase: f2[6] > 5.\n      Hubcap T[1]<=3 T[6]<=1 T[7]<=2 T[2,3]<=2 T[4,5]<=2 [].\n    Pcase: s[2] > 6.\n      Pcase: s[4] > 6.\n        Hubcap T[1]<=3 T[2]<=1 T[3]<=0 T[4]<=2 T[5]<=0 T[6]<=2 T[7]<=2 [].\n      Pcase: s[5] <= 6.\n        Hubcap T[1]<=3 T[2]<=1 T[3]<=0 T[4]<=2 T[5]<=0 T[6]<=2 T[7]<=2 [].\n      Pcase: h[2] > 6.\n        Hubcap T[1]<=3 T[2]<=0 T[5]<=1 T[6]<=2 T[7]<=2 T[3,4]<=2 [].\n      Pcase: h[3] <= 6.\n        Hubcap T[1]<=3 T[5]<=1 T[6]<=2 T[7]<=2 T[2,3]<=2 T[2,4]<=1 T[3,4]<=2 [].\n      Pcase: h[5] > 5.\n        Hubcap T[1]<=3 T[2]<=1 T[5]<=1 T[6]<=2 T[7]<=2 T[3,4]<=1 [].\n      Pcase: f1[5] <= 5.\n        Reducible.\n      Pcase: f1[2] > 5.\n        Hubcap T[1]<=3 T[2]<=0 T[5]<=1 T[6]<=2 T[7]<=2 T[3,4]<=2 [].\n      Hubcap T[1]<=3 T[2]<=1 T[5]<=1 T[6]<=2 T[7]<=2 T[3,4]<=1 [].\n    Pcase: s[5] > 6.\n      Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[6]<=2 T[7]<=2 T[4,5]<=1 [].\n    Pcase: h[6] <= 6.\n      Reducible.\n    Pcase: s[4] > 6.\n      Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=1 T[5]<=0 T[6]<=2 T[7]<=2 [].\n    Hubcap T[1]<=3 T[2]<=2 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=2 T[7]<=2 [].\n  Pcase: h[1] > 5.\n    Similar to *L1_5[6].\n  Pcase L1_6: s[2] > 7.\n    Pcase: s[4] > 7.\n      Hubcap T[1]<=3 T[2]<=0 T[3]<=0 T[4]<=0 T[5]<=2 T[6,7]<=5 [].\n    Pcase: s[5] > 7.\n      Hubcap T[1]<=3 T[2]<=0 T[5]<=0 T[3,4]<=2 T[6,7]<=5 [].\n    Pcase: s[7] > 7.\n      Hubcap T[1]<=2 T[2]<=0 T[7]<=0 T[3,4]<=4 T[5,6]<=4 [].\n    Pcase: s[4] > 6.\n      Pcase: s[3] > 6.\n        Hubcap T[1]<=3 T[2]<=0 T[3]<=0 T[4,5]<=2 T[6,7]<=5 [].\n      Pcase: s[5] > 6.\n        Hubcap T[1]<=3 T[2]<=0 T[3]<=0 T[4]<=1 T[5]<=1 T[6,7]<=5 [].\n      Pcase: s[6] > 7.\n        Hubcap T[1]<=3 T[2]<=0 T[3]<=0 T[4]<=4 T[5]<=0 T[6]<=0 T[7]<=3 [].\n      Pcase: s[6] <= 6.\n        Hubcap T[2]<=0 T[3]<=0 T[4]<=2 T[1,5]<=3 T[6,7]<=5 [].\n      Pcase: s[7] > 6.\n        Hubcap T[1]<=2 T[2]<=0 T[3]<=0 T[4]<=4 T[5]<=0 T[6]<=1 T[7]<=3 [].\n      Hubcap T[1]<=3 T[2]<=0 T[3]<=0 T[5]<=0 T[7]<=3 T[4,6]<=4 [].\n    Pcase: h[5] > 6.\n      Hubcap T[2]<=0 T[1,5]<=3 T[3,4]<=2 T[6,7]<=5 [].\n    Pcase: s[6] <= 6.\n      Pcase: s[3] > 6.\n        Hubcap T[1]<=3 T[2]<=0 T[3]<=1 T[4,7]<=4 T[5,6]<=2 [].\n      Pcase: s[7] > 6.\n        Hubcap T[1]<=2 T[2]<=0 T[5]<=2 T[6]<=0 T[7]<=4 T[3,4]<=2 [].\n      Hubcap T[1]<=3 T[2]<=0 T[5]<=0 T[3,4]<=2 T[6,7]<=5 [].\n    Pcase: s[7] > 6.\n      Hubcap T[1]<=2 T[2]<=0 T[5]<=2 T[3,4]<=3 T[6,7]<=3 [].\n    Pcase: f1[7] <= 5.\n      Reducible.\n    Pcase: s[3] > 6.\n      Hubcap T[1]<=3 T[2]<=0 T[3]<=1 T[7]<=3 T[4,5]<=3 T[4,6]<=2 T[5,6]<=2 [].\n    Pcase: s[5] > 6.\n      Hubcap T[1]<=3 T[2]<=0 T[7]<=3 T[3,4]<=2 T[5,6]<=2 [].\n    Hubcap T[1]<=3 T[2]<=0 T[7]<=3 T[3,4]<=3 T[5,6]<=1 [].\n  Pcase: s[7] > 7.\n    Similar to *L1_6[6].\n  Pcase L1_7: s[2] <= 6.\n    Pcase: f1[2] <= 5.\n      Reducible.\n    Pcase L2_1: s[3] <= 6.\n      Pcase: s[4] > 7.\n        Hubcap T[4]<=(-1) T[1,2]<=7 T[3,7]<=3 T[5,6]<=1 [].\n      Pcase: s[7] > 6.\n        Hubcap T[1]<=3 T[6]<=0 T[4,5]<=1 T[2,3]<=5 T[2,7]<=5 T[3,7]<=3 [].\n      Pcase: h[3] <= 5.\n        Reducible.\n      Pcase: f1[7] <= 5.\n        Reducible.\n      Pcase: s[6] > 7.\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=0 T[6]<=(-1) T[7]<=3 T[4,5]<=1 [].\n      Pcase: s[4] > 6.\n        Pcase: s[5] > 7.\n          Hubcap T[1]<=4 T[2]<=3 T[3]<=0 T[4]<=(-1) T[5]<=0 T[6]<=1 T[7]<=3 [].\n        Pcase: s[5] <= 6.\n          Hubcap T[1]<=4 T[2]<=3 T[3]<=0 T[4]<=(-1) T[5]<=0 T[6]<=1 T[7]<=3 [].\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=4 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=3 [].\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=3 [].\n      Pcase: s[6] > 6.\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=0 T[4]<=0 T[7]<=3 T[5,6]<=0 [].\n      Hubcap T[1]<=4 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=3 [].\n    Pcase: s[6] <= 6.\n      Pcase: s[7] <= 6.\n        Similar to *L2_1[6].\n      Pcase: h[7] <= 5.\n        Reducible.\n      Pcase: s[3] > 8.\n        Hubcap T[1]<=3 T[2]<=3 T[3]<=(-1) T[4]<=1 T[7]<=2 T[5,6]<=2 [].\n      Pcase: s[4] > 6.\n        Hubcap T[1]<=3 T[2]<=3 T[4]<=1 T[3,7]<=2 T[5,6]<=1 [].\n      Hubcap T[1]<=3 T[2]<=3 T[6]<=0 T[3,7]<=2 T[4,5]<=2 [].\n    Pcase: s[7] > 6.\n      Pcase: s[3] > 8.\n        Hubcap T[1]<=3 T[2]<=3 T[3]<=(-1) T[6]<=0 T[7]<=2 T[4,5]<=3 [].\n      Pcase: s[4] > 6.\n        Hubcap T[1]<=3 T[2]<=3 T[5]<=0 T[6]<=0 T[7]<=2 T[3,4]<=2 [].\n      Pcase: s[5] > 6.\n        Hubcap T[1]<=3 T[2]<=3 T[4]<=0 T[6]<=0 T[7]<=2 T[3,5]<=2 [].\n      Pcase: s[3] > 7.\n        Hubcap T[1]<=3 T[2]<=3 T[3]<=(-1) T[6]<=0 T[7]<=2 T[4,5]<=3 [].\n      Pcase: h[3] > 5.\n        Hubcap T[1]<=3 T[2]<=3 T[6]<=0 T[7]<=2 T[3,4]<=1 T[3,5]<=1 T[4,5]<=3 [].\n      Hubcap T[1]<=3 T[2]<=3 T[3]<=1 T[4]<=0 T[5]<=1 T[6]<=0 T[7]<=2 [].\n    Pcase: f1[7] <= 5.\n      Reducible.\n    Pcase: s[4] > 7.\n      Hubcap T[1]<=4 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=3 [].\n    Pcase: s[5] > 7.\n      Hubcap T[1]<=4 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=3 [].\n    Pcase L2_2: s[4] > 6.\n      Pcase: s[3] > 7.\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=(-1) T[5]<=0 T[7]<=3 T[4,6]<=1 [].\n      Pcase: s[5] > 6.\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=3 [].\n      Pcase: s[6] > 7.\n        Hubcap T[1]<=4 T[2]<=3 T[5]<=0 T[6]<=(-1) T[7]<=3 T[3,4]<=1 [].\n      Pcase: h[3] > 5.\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=(-1) T[5]<=0 T[7]<=3 T[4,6]<=1 [].\n      Pcase: h[5] <= 5.\n        Reducible.\n      Pcase: f1[2] <= 6.\n        Reducible.\n      Pcase: f1[3] <= 5.\n        Reducible.\n      Pcase: h[5] > 6.\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=3 [].\n      Pcase: h[7] > 5.\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=0 T[4]<=1 T[5]<=0 T[6]<=(-1) T[7]<=3 [].\n      Pcase: f1[7] <= 6.\n        Reducible.\n      Pcase: f2[6] <= 5.\n        Reducible.\n      Pcase: f1[4] <= 5.\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=3 [].\n      Pcase: f2[4] > 5.\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=3 [].\n      Hubcap T[1]<=4 T[2]<=3 T[3]<=0 T[4]<=0 T[5]<=0 T[6]<=0 T[7]<=3 [].\n    Pcase: s[5] > 6.\n      Similar to *L2_2[6].\n    Pcase: h[5] <= 5.\n      Reducible.\n    Hubcap T[1]<=4 T[2]<=3 T[7]<=3 T[3,4]<=0 T[5,6]<=0 [].\n  Pcase: s[7] <= 6.\n    Similar to *L1_7[6].\n  Pcase: s[4] > 7.\n    Hubcap T[1]<=2 T[3]<=0 T[4]<=0 T[5]<=1 T[6]<=1 T[2,7]<=6 [].\n  Pcase: s[5] > 7.\n    Hubcap T[1]<=2 T[3]<=1 T[4]<=1 T[5]<=0 T[6]<=0 T[2,7]<=6 [].\n  Pcase L1_8: s[3] > 6.\n    Pcase: s[5] > 6.\n      Hubcap T[1]<=2 T[4]<=0 T[6]<=0 T[2,3]<=3 T[5,7]<=5 [].\n    Pcase: s[6] > 7.\n      Hubcap T[1]<=2 T[6]<=0 T[7]<=2 T[2,3]<=3 T[4,5]<=3 [].\n    Pcase: s[6] > 6.\n      Pcase: s[3] > 7.\n        Hubcap T[1]<=2 T[2]<=2 T[3]<=0 T[4,5]<=3 T[6,7]<=3 [].\n      Pcase: s[4] > 6.\n        Hubcap T[1]<=2 T[2]<=3 T[3]<=0 T[4]<=2 T[5]<=0 T[6,7]<=3 [].\n      Pcase: h[3] > 5.\n        Hubcap T[1]<=2 T[2,3]<=2 T[4,5]<=3 T[6,7]<=3 [].\n      Pcase: h[4] > 6.\n        Hubcap T[1]<=2 T[3]<=0 T[6]<=1 T[2,7]<=4 T[4,5]<=3 [].\n      Pcase: h[5] > 5.\n        Hubcap T[1]<=2 T[3]<=1 T[4]<=1 T[5]<=1 T[6]<=1 T[2,7]<=4 [].\n      Pcase: h[6] > 6.\n        Hubcap T[1]<=2 T[3]<=1 T[6]<=0 T[2,7]<=4 T[4,5]<=3 [].\n      Pcase: h[7] > 5.\n        Hubcap T[1]<=2 T[2,3]<=3 T[4,5]<=3 T[6,7]<=2 [].\n      Pcase: f1[2] <= 5.\n        Hubcap T[1]<=2 T[2]<=3 T[3]<=0 T[4,5]<=3 T[6,7]<=2 [].\n      Pcase: f1[3] > 5.\n        Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4,5]<=3 T[6,7]<=3 [].\n      Pcase: f2[7] <= 5.\n        Reducible.\n      Pcase: f1[4] <= 6.\n        Hubcap T[1]<=2 T[2]<=2 T[3]<=0 T[6]<=1 T[7]<=2 T[4,5]<=3 [].\n      Pcase: f1[5] > 5.\n        Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4]<=1 T[5]<=1 T[6]<=1 T[7]<=2 [].\n      Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4]<=2 T[5]<=1 T[6,7]<=2 [].\n    Pcase: s[3] > 7.\n      Hubcap T[1]<=2 T[2]<=2 T[3]<=0 T[4,5]<=2 T[6,7]<=4 [].\n    Pcase: s[4] > 6.\n      Hubcap T[1]<=2 T[3]<=0 T[4]<=1 T[2,7]<=6 T[5,6]<=1 [].\n    Hubcap T[1]<=2 T[6]<=0 T[2,3]<=3 T[4,5]<=2 T[4,7]<=4 T[5,7]<=5 [].\n  Pcase: s[6] > 6.\n    Similar to *L1_8[6].\n  Pcase: h[5] > 5.\n    Hubcap T[1]<=2 T[3]<=0 T[6]<=0 T[2,7]<=6 T[4,5]<=2 [].\n  Pcase L1_9: s[4] > 6.\n    Pcase: s[5] > 6.\n      Hubcap T[1]<=2 T[3]<=0 T[4]<=1 T[5]<=1 T[6]<=0 T[2,7]<=6 [].\n    Pcase: f1[2] <= 5.\n      Reducible.\n    Pcase: f2[4] <= 5.\n      Reducible.\n    Pcase: h[3] > 5.\n      Hubcap T[1]<=2 T[2]<=2 T[3]<=0 T[4]<=2 T[5,6]<=1 T[5,7]<=4 T[6,7]<=4 [].\n    Hubcap T[1]<=2 T[2]<=4 T[3]<=0 T[4]<=1 T[7]<=2 T[5,6]<=1 [].\n  Pcase: s[5] > 6.\n    Similar to *L1_9[6].\n  Reducible.\nPcase: s[2] <= 5.\n  Similar to L0_1[1].\nPcase: s[3] <= 5.\n  Similar to L0_1[2].\nPcase: s[4] <= 5.\n  Similar to L0_1[3].\nPcase: s[5] <= 5.\n  Similar to L0_1[4].\nPcase: s[6] <= 5.\n  Similar to L0_1[5].\nPcase: s[7] <= 5.\n  Similar to L0_1[6].\nPcase L0_2: s[1] > 6.\n  Pcase L1_1: s[4] > 6.\n    Pcase: s[6] > 7.\n      Hubcap T[5]<=0 T[6]<=0 T[7]<=0 T[1,3]<=5 T[2,4]<=5 [].\n    Pcase L2_1: s[2] > 6.\n      Pcase: s[3] > 6.\n        Hubcap T[1]<=2 T[2]<=0 T[3]<=0 T[4]<=2 T[5]<=2 T[6,7]<=4 [].\n      Pcase: s[4] > 7.\n        Hubcap T[1]<=2 T[2]<=2 T[3]<=0 T[4]<=0 T[5]<=2 T[6,7]<=4 [].\n      Pcase: s[5] > 6.\n        Hubcap T[2]<=2 T[3]<=0 T[4]<=2 T[1,5]<=3 T[6,7]<=3 [].\n      Pcase: s[6] > 6.\n        Hubcap T[3]<=0 T[5]<=0 T[7]<=0 T[1,6]<=5 T[2,4]<=5 [].\n      Pcase: s[7] > 6.\n        Hubcap T[1]<=0 T[2]<=2 T[3]<=0 T[5]<=2 T[7]<=2 T[4,6]<=4 [].\n      Pcase: s[2] > 7.\n        Hubcap T[2]<=0 T[3]<=0 T[1,5]<=3 T[4,6]<=6 T[4,7]<=5 T[6,7]<=4 [].\n      Pcase: h[3] > 6.\n        Hubcap T[2]<=0 T[3]<=0 T[1,5]<=3 T[4,6]<=6 T[4,7]<=5 T[6,7]<=4 [].\n      Pcase: h[4] > 6.\n        Hubcap T[3]<=0 T[1,5]<=3 T[2,4]<=3 T[6,7]<=4 [].\n      Pcase: h[5] > 6.\n        Hubcap T[2]<=2 T[3]<=0 T[4,7]<=3 T[1,5]<=3 T[1,6]<=4 T[5,6]<=4 [].\n      Pcase: h[6] > 6.\n        Hubcap T[1]<=2 T[3]<=0 T[5]<=0 T[2,4]<=5 T[6,7]<=3 [].\n      Pcase: h[6] <= 5.\n        Hubcap T[1]<=1 T[2]<=2 T[3]<=0 T[4,7]<=3 T[5,6]<=4 [].\n      Pcase: s[1] > 7.\n        Hubcap T[1]<=0 T[2]<=2 T[3]<=0 T[4,7]<=5 T[5,6]<=3 [].\n      Pcase: h[7] > 5.\n        Hubcap T[1]<=2 T[3]<=0 T[5]<=1 T[2,4]<=5 T[6,7]<=2 [].\n      Hubcap T[2]<=2 T[3]<=0 T[4]<=2 T[1,7]<=3 T[5,6]<=3 [].\n    Pcase: s[3] > 6.\n      Similar to *L2_1[3].\n    Pcase L2_2: h[3] <= 5.\n      Pcase: s[5] > 7.\n        Hubcap T[1]<=2 T[4]<=2 T[5]<=0 T[2,3]<=3 T[6,7]<=3 [].\n      Pcase: s[7] > 7.\n        Hubcap T[1]<=2 T[4]<=2 T[7]<=0 T[2,3]<=3 T[5,6]<=3 [].\n      Pcase: h[6] > 6.\n        Hubcap T[1]<=2 T[4]<=2 T[5]<=0 T[2,3]<=3 T[6,7]<=3 [].\n      Pcase: h[7] > 6.\n        Hubcap T[1]<=2 T[4]<=2 T[7]<=0 T[2,3]<=3 T[5,6]<=3 [].\n      Pcase: f1[2] <= 5.\n        Pcase: h[2] <= 5.\n          Reducible.\n        Pcase: f1[3] <= 5.\n          Reducible.\n        Pcase: s[4] > 7.\n          Hubcap T[2]<=1 T[3]<=2 T[4]<=0 T[1,5]<=3 T[6,7]<=4 [].\n        Pcase: s[6] > 6.\n          Hubcap T[2]<=1 T[3]<=2 T[4]<=2 T[5]<=0 T[7]<=0 T[1,6]<=5 [].\n        Pcase: s[7] > 6.\n          Hubcap T[2]<=1 T[3]<=2 T[7]<=2 T[1,4]<=2 T[5,6]<=3 [].\n        Pcase: s[5] > 6.\n          Pcase: s[1] > 7.\n            Hubcap T[1]<=0 T[2]<=1 T[3]<=2 T[4]<=2 T[5]<=2 T[6,7]<=3 [].\n          Pcase: h[4] > 5.\n            Hubcap T[2]<=1 T[3]<=2 T[4]<=1 T[1,5]<=3 T[6,7]<=3 [].\n          Pcase: f1[3] <= 6.\n            Reducible.\n          Pcase: h[7] > 5.\n            Hubcap T[2]<=1 T[3]<=2 T[4]<=2 T[1,5]<=3 T[6,7]<=2 [].\n          Pcase: h[1] > 6.\n            Hubcap T[2]<=1 T[3]<=2 T[5]<=2 T[1,4]<=2 T[6,7]<=3 [].\n          Pcase: f1[4] > 5.\n            Hubcap T[2]<=1 T[3]<=2 T[4]<=1 T[1,5]<=3 T[6,7]<=3 [].\n          Pcase: f1[1] > 5.\n            Hubcap T[2]<=1 T[3]<=2 T[4]<=2 T[1,6]<=2 T[5,7]<=3 [].\n          Pcase: h[6] <= 5.\n            Hubcap T[2]<=1 T[3]<=2 T[4]<=2 T[7]<=1 T[1,5]<=3 T[1,6]<=3 T[5,6]<=3\n                   [].\n          Pcase: h[1] > 5.\n            Hubcap T[1]<=1 T[2]<=1 T[3]<=2 T[4]<=2 T[5]<=1 T[6,7]<=3 [].\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=2 T[6]<=1 T[5,7]<=2 [].\n        Pcase: h[5] <= 5.\n          Reducible.\n        Pcase: s[1] > 7.\n          Hubcap T[1]<=0 T[2]<=1 T[3]<=2 T[4,5]<=3 T[6,7]<=4 [].\n        Pcase: h[4] > 6.\n          Hubcap T[2]<=1 T[3]<=2 T[4]<=0 T[1,5]<=3 T[6,7]<=4 [].\n        Pcase: f1[6] > 6.\n          Hubcap T[2]<=1 T[3]<=2 T[6]<=3 T[1,5]<=2 T[4,7]<=2 [].\n        Pcase: f1[6] <= 5.\n          Hubcap T[1]<=1 T[2]<=1 T[3]<=2 T[6]<=1 T[7]<=2 T[4,5]<=3 [].\n        Pcase: h[4] > 5.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=1 T[5]<=1 T[6]<=2 T[7]<=1 [].\n        Pcase: f1[3] <= 6.\n          Reducible.\n        Pcase: h[6] > 5.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[6]<=2 T[7]<=1 T[4,5]<=2 [].\n        Hubcap T[1]<=1 T[2]<=1 T[3]<=2 T[4]<=2 T[5]<=1 T[6]<=2 T[7]<=1 [].\n      Pcase: f1[3] > 5.\n        Pcase: s[1] > 7.\n          Hubcap T[1]<=0 T[2]<=1 T[3]<=1 T[4]<=2 T[5]<=2 T[6,7]<=4 [].\n        Pcase: s[4] > 7.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=0 T[5]<=2 T[6,7]<=4 [].\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=2 T[5]<=0 T[6]<=4 T[7]<=0 [].\n        Pcase: f1[2] <= 6.\n          Pcase: h[2] <= 5.\n            Reducible.\n          Pcase: s[5] > 6.\n            Hubcap T[2]<=1 T[3]<=1 T[4]<=2 T[1,5]<=3 T[6,7]<=3 [].\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=1 T[2]<=1 T[3]<=1 T[4]<=2 T[7]<=2 T[5,6]<=3 [].\n          Pcase: h[4] <= 5.\n            Hubcap T[2]<=1 T[3]<=1 T[4,7]<=3 T[1,5]<=3 T[1,6]<=4 T[5,6]<=4 [].\n          Pcase: h[5] > 6.\n            Hubcap T[2]<=1 T[3]<=1 T[4]<=1 T[1,5]<=3 T[6,7]<=4 [].\n          Pcase: h[6] > 5.\n            Hubcap T[2]<=1 T[3]<=1 T[4]<=2 T[1,7]<=3 T[5,6]<=3 [].\n          Hubcap T[1]<=1 T[2]<=1 T[3]<=1 T[4,5]<=3 T[6,7]<=4 [].\n        Pcase: f1[3] <= 6.\n          Pcase: h[4] <= 5.\n            Reducible.\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=1 T[5]<=2 T[6,7]<=3 [].\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4,7]<=3 T[5,6]<=3 [].\n          Pcase: h[2] <= 5.\n            Hubcap T[2]<=1 T[3]<=1 T[1,5]<=3 T[4,6]<=4 T[4,7]<=3 T[6,7]<=4 [].\n          Pcase: h[6] > 5.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4,7]<=3 T[5,6]<=3 [].\n          Pcase: h[2] > 6.\n            Hubcap T[1]<=1 T[2]<=1 T[3]<=1 T[4,5]<=3 T[6,7]<=4 [].\n          Pcase: h[5] > 6.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4,5]<=2 T[6,7]<=4 [].\n          Pcase: h[7] > 5.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4,5]<=3 T[6,7]<=3 [].\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=1 T[5]<=1 T[6]<=3 T[7]<=1 [].\n        Pcase: f1[6] <= 5.\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=2 T[7]<=2 T[5,6]<=2 [].\n          Pcase: f1[5] <= 5.\n            Reducible.\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=2 T[5]<=2 T[6,7]<=2 [].\n          Pcase: f1[7] <= 5.\n            Reducible.\n          Pcase: h[2] > 6.\n            Hubcap T[1]<=1 T[2]<=1 T[3]<=1 T[4]<=2 T[5]<=2 T[6]<=1 T[7]<=2 [].\n          Pcase: h[2] <= 5.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[6]<=1 T[7]<=2 T[4,5]<=3 [].\n          Pcase: h[4] > 6.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=1 T[5]<=2 T[6]<=1 T[7]<=2 [].\n          Pcase: h[4] <= 5.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[6]<=1 T[7]<=2 T[4,5]<=3 [].\n          Pcase: h[5] > 6.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=1 T[5]<=2 T[6]<=1 T[7]<=2 [].\n          Pcase: h[5] <= 5.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=1 T[5]<=2 T[6]<=1 T[7]<=2 [].\n          Pcase: h[6] > 5.\n            Hubcap T[2]<=1 T[3]<=1 T[4]<=2 T[6]<=1 T[7]<=2 T[1,5]<=3 [].\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=1 T[5]<=2 T[6]<=1 T[7]<=2 [].\n        Pcase: s[5] > 6.\n          Pcase: s[7] > 6.\n            Similar to L2_1[3].\n          Pcase: h[2] > 6.\n            Hubcap T[2]<=1 T[3]<=1 T[4]<=2 T[6]<=2 T[7]<=1 T[1,5]<=3 [].\n          Pcase: h[2] <= 5.\n            Hubcap T[2]<=1 T[3]<=1 T[5]<=2 T[6]<=2 T[7]<=1 T[1,4]<=3 [].\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=1 T[5]<=2 T[6]<=2 T[7]<=1 [].\n          Pcase: h[6] > 5.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=2 T[5]<=1 T[6]<=2 T[7]<=1 [].\n          Pcase: h[7] > 5.\n            Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=2 T[5]<=2 T[6,7]<=2 [].\n          Hubcap T[2]<=1 T[3]<=1 T[4]<=2 T[5]<=2 T[7]<=1 T[1,6]<=3 [].\n        Pcase: h[7] > 5.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=2 T[5]<=1 T[6,7]<=3 [].\n        Pcase: h[4] > 6.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[5]<=1 T[4,6]<=4 T[4,7]<=3 T[6,7]<=4\n                 [].\n        Pcase: h[4] <= 5.\n          Hubcap T[2]<=1 T[3]<=1 T[5]<=1 T[1,4]<=3 T[6,7]<=4 [].\n        Pcase: h[5] > 6.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=1 T[5]<=1 T[6,7]<=4 [].\n        Pcase: h[5] <= 5.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[5]<=1 T[4,6]<=4 T[4,7]<=3 T[6,7]<=4\n                 [].\n        Pcase: s[7] > 6.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[5]<=1 T[7]<=2 T[4,6]<=3 [].\n        Pcase: h[2] > 6.\n          Hubcap T[2]<=1 T[3]<=1 T[4]<=2 T[5]<=1 T[7]<=1 T[1,6]<=4 [].\n        Pcase: h[2] <= 5.\n          Hubcap T[2]<=1 T[3]<=1 T[4]<=2 T[5]<=1 T[7]<=1 T[1,6]<=4 [].\n        Pcase: h[6] > 5.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=2 T[5]<=1 T[6]<=2 T[7]<=1 [].\n        Pcase: f1[6] <= 6.\n          Reducible.\n        Pcase: h[1] > 6.\n          Hubcap T[1]<=1 T[2]<=1 T[3]<=1 T[4]<=2 T[5]<=1 T[6]<=3 T[7]<=1 [].\n        Pcase: h[1] <= 5.\n          Hubcap T[1]<=1 T[2]<=1 T[3]<=1 T[4]<=2 T[5]<=1 T[6]<=3 T[7]<=1 [].\n        Pcase: f1[1] > 5.\n          Hubcap T[1]<=1 T[2]<=1 T[3]<=1 T[4]<=2 T[5]<=1 T[6]<=3 T[7]<=1 [].\n        Pcase: f1[4] > 5.\n          Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=1 T[5]<=1 T[6]<=3 T[7]<=1 [].\n        Pcase: f1[5] > 5.\n          Hubcap T[2]<=1 T[3]<=1 T[4]<=2 T[5]<=1 T[7]<=1 T[1,6]<=4 [].\n        Hubcap T[1]<=2 T[2]<=1 T[3]<=1 T[4]<=1 T[5]<=1 T[6]<=3 T[7]<=1 [].\n      Pcase: h[4] <= 5.\n        Reducible.\n      Pcase: s[6] > 6.\n        Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[5]<=0 T[7]<=0 T[4,6]<=5 [].\n      Pcase: s[1] > 7.\n        Hubcap T[1]<=0 T[2]<=2 T[3]<=1 T[4,7]<=3 T[5,6]<=4 [].\n      Pcase: s[5] > 6.\n        Hubcap T[2]<=2 T[3]<=1 T[5]<=2 T[1,4]<=2 T[6,7]<=3 [].\n      Pcase: s[7] > 6.\n        Pcase: s[4] > 7.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4]<=0 T[7]<=2 T[5,6]<=3 [].\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=1 T[2]<=2 T[3]<=1 T[4,7]<=3 T[5,6]<=3 [].\n        Pcase: f1[2] <= 6.\n          Reducible.\n        Pcase: h[5] > 6.\n          Hubcap T[2]<=2 T[3]<=1 T[7]<=2 T[1,4]<=2 T[5,6]<=3 [].\n        Pcase: h[6] > 5.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4,7]<=3 T[5,6]<=2 [].\n        Pcase: f1[6] <= 5.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[5]<=2 T[6]<=1 T[4,7]<=2 [].\n        Pcase: h[5] <= 5.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[5]<=1 T[6]<=1 T[4,7]<=3 [].\n        Pcase: h[7] > 5.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4]<=1 T[5]<=1 T[6]<=2 T[7]<=1 [].\n        Pcase: f1[6] <= 6.\n          Reducible.\n        Pcase: f1[5] > 5.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4]<=1 T[5]<=1 T[6]<=1 T[7]<=2 [].\n        Pcase: h[4] > 6.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[5]<=1 T[6]<=2 T[4,7]<=2 [].\n        Pcase: f1[4] > 5.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[5]<=1 T[6]<=2 T[4,7]<=2 [].\n        Hubcap T[1]<=1 T[2]<=2 T[3]<=1 T[4]<=1 T[5]<=1 T[6]<=2 T[7]<=2 [].\n      Pcase: h[1] <= 5.\n        Reducible.\n      Pcase: s[4] > 7.\n        Hubcap T[2]<=2 T[3]<=1 T[4]<=0 T[1,5]<=3 T[6,7]<=4 [].\n      Pcase: h[2] > 6.\n        Hubcap T[1]<=0 T[2]<=2 T[3]<=1 T[4,5]<=3 T[6,7]<=4 [].\n      Pcase: f1[5] <= 5.\n        Hubcap T[2]<=2 T[3]<=1 T[7]<=1 T[1,5]<=2 T[4,6]<=4 [].\n      Pcase: h[7] > 5.\n        Hubcap T[2]<=2 T[3]<=1 T[4,7]<=3 T[1,5]<=3 T[1,6]<=3 T[5,6]<=3 [].\n      Pcase: h[2] > 5.\n        Hubcap T[2]<=2 T[3]<=1 T[4]<=1 T[1,5]<=2 T[6,7]<=4 [].\n      Pcase: f1[2] <= 6.\n        Reducible.\n      Pcase: f1[6] <= 5.\n        Reducible.\n      Pcase: h[5] > 5.\n        Hubcap T[2]<=2 T[3]<=1 T[4]<=1 T[5]<=1 T[7]<=1 T[1,6]<=4 [].\n      Pcase: f2[4] <= 5.\n        Reducible.\n      Pcase: h[6] > 5.\n        Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4]<=1 T[7]<=1 T[5,6]<=3 [].\n      Hubcap T[1]<=1 T[2]<=2 T[3]<=1 T[4]<=1 T[5]<=1 T[6]<=3 T[7]<=1 [].\n    Pcase L2_3: s[5] > 7.\n      Pcase: s[6] > 6.\n        Similar to L2_1[4].\n      Pcase: s[7] > 6.\n        Similar to L2_1[3].\n      Pcase: h[7] <= 5.\n        Similar to L2_2[4].\n      Hubcap T[1]<=4 T[4]<=2 T[5]<=0 T[2,3]<=2 T[6,7]<=2 [].\n    Pcase: s[7] > 7.\n      Similar to *L2_3[3].\n    Pcase L2_4: h[6] > 6.\n      Pcase: s[1] > 7.\n        Hubcap T[1]<=0 T[4]<=4 T[5]<=0 T[6]<=2 T[7]<=2 T[2,3]<=2 [].\n      Pcase: s[4] > 7.\n        Hubcap T[1]<=4 T[4]<=0 T[5]<=0 T[6]<=2 T[7]<=2 T[2,3]<=2 [].\n      Pcase: s[5] > 6.\n        Hubcap T[4]<=2 T[5]<=0 T[2,3]<=2 T[1,6]<=5 T[1,7]<=5 T[6,7]<=3 [].\n      Pcase: s[6] > 6.\n        Hubcap T[5]<=0 T[6]<=2 T[7]<=0 T[1,3]<=4 T[2,4]<=4 [].\n      Pcase: s[7] > 6.\n        Hubcap T[1]<=2 T[4]<=4 T[5]<=0 T[6]<=0 T[7]<=2 T[2,3]<=2 [].\n      Pcase: h[2] > 5.\n        Hubcap T[3]<=1 T[5]<=0 T[2,4]<=4 T[1,6]<=4 T[1,7]<=4 T[6,7]<=3 [].\n      Hubcap T[5]<=0 T[7]<=1 T[1,3]<=4 T[1,6]<=4 T[2,3]<=2 T[2,4]<=4 T[4,6]<=5\n             [].\n    Pcase: h[7] > 6.\n      Similar to *L2_4[3].\n    Pcase L2_5: s[1] > 7.\n      Pcase: s[7] > 6.\n        Similar to L2_3[3].\n      Pcase: s[4] > 7.\n        Hubcap T[1]<=0 T[2]<=2 T[3]<=2 T[4]<=0 T[5]<=2 T[6,7]<=4 [].\n      Pcase: s[5] > 6.\n        Hubcap T[1]<=0 T[4]<=2 T[5]<=2 T[6]<=2 T[7]<=2 T[2,3]<=2 [].\n      Pcase: s[6] > 6.\n        Hubcap T[1]<=0 T[4]<=4 T[5]<=0 T[6]<=4 T[7]<=0 T[2,3]<=2 [].\n      Pcase: h[3] > 6.\n        Hubcap T[1]<=0 T[2]<=0 T[3]<=0 T[4]<=4 T[5]<=2 T[6,7]<=4 [].\n      Pcase: h[4] > 5.\n        Hubcap T[1]<=0 T[2,3]<=2 T[4,5]<=4 T[6,7]<=4 [].\n      Pcase: h[5] > 6.\n        Hubcap T[1]<=0 T[4]<=2 T[5]<=2 T[2,3]<=2 T[6,7]<=4 [].\n      Pcase: h[5] <= 5.\n        Hubcap T[1]<=0 T[2]<=1 T[3]<=2 T[4,7]<=4 T[5,6]<=3 [].\n      Pcase: h[6] > 5.\n        Hubcap T[1]<=0 T[2,3]<=2 T[4,5]<=5 T[6,7]<=3 [].\n      Hubcap T[1]<=0 T[4]<=2 T[5]<=1 T[6]<=3 T[7]<=1 T[2,3]<=2 [].\n    Pcase: s[4] > 7.\n      Similar to *L2_5[3].\n    Pcase: s[6] > 6.\n      Pcase: s[5] > 6.\n        Similar to L2_1[4].\n      Pcase: s[7] > 6.\n        Similar to *L2_1[0].\n      Pcase: h[2] > 6.\n        Hubcap T[3]<=1 T[5]<=0 T[7]<=0 T[1,6]<=5 T[2,4]<=4 [].\n      Pcase: h[4] > 6.\n        Hubcap T[2]<=1 T[5]<=0 T[7]<=0 T[1,3]<=4 T[4,6]<=5 [].\n      Pcase: f1[5] <= 5.\n        Pcase: h[2] > 5.\n          Hubcap T[5]<=0 T[7]<=0 T[1,3]<=4 T[1,6]<=6 T[2,3]<=2 T[2,4]<=4\n                 T[4,6]<=5 [].\n        Hubcap T[5]<=0 T[7]<=0 T[4,6]<=5 T[1,2]<=5 T[1,3]<=4 T[2,3]<=2 [].\n      Pcase: f1[7] <= 5.\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=2 T[3]<=1 T[5]<=0 T[6]<=3 T[7]<=0 T[2,4]<=4 [].\n        Pcase: h[3] > 6.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=0 T[4]<=4 T[5]<=0 T[6]<=3 T[7]<=0 [].\n        Pcase: h[4] > 5.\n          Hubcap T[5]<=0 T[7]<=0 T[1,3]<=4 T[1,6]<=5 T[2,3]<=2 T[2,4]<=4\n                 T[4,6]<=6 [].\n        Hubcap T[5]<=0 T[7]<=0 T[1,6]<=5 T[2,3]<=2 T[2,4]<=4 T[3,4]<=5 [].\n      Pcase L3_1: h[2] > 5.\n        Pcase: h[3] > 6.\n          Hubcap T[2]<=0 T[3]<=0 T[4]<=4 T[5]<=0 T[7]<=0 T[1,6]<=6 [].\n        Pcase: h[4] > 5.\n          Hubcap T[5]<=0 T[7]<=0 T[1,3]<=4 T[1,6]<=6 T[2,3]<=1 T[2,4]<=4\n                 T[4,6]<=6 [].\n        Pcase: h[5] > 6.\n          Hubcap T[4]<=2 T[5]<=0 T[7]<=0 T[1,6]<=6 T[2,3]<=2 [].\n        Pcase: h[5] <= 5.\n          Hubcap T[4]<=3 T[5]<=0 T[7]<=0 T[1,6]<=6 T[2,3]<=1 [].\n        Pcase: h[1] > 5.\n          Hubcap T[5]<=0 T[6]<=4 T[7]<=0 T[1,3]<=2 T[2,4]<=4 [].\n        Pcase: f1[2] > 5.\n          Hubcap T[3]<=0 T[5]<=0 T[7]<=0 T[1,6]<=6 T[2,4]<=4 [].\n        Hubcap T[1]<=2 T[2]<=0 T[3]<=1 T[4]<=2 T[5]<=0 T[6]<=4 T[7]<=0 [].\n      Pcase: h[4] > 5.\n        Similar to *L3_1[3].\n      Pcase: f1[4] > 5.\n        Pcase: h[3] > 6.\n          Hubcap T[1]<=4 T[2]<=0 T[3]<=0 T[5]<=0 T[7]<=0 T[4,6]<=6 [].\n        Pcase: h[5] > 6.\n          Hubcap T[4]<=1 T[5]<=0 T[6]<=4 T[7]<=0 T[1,2]<=5 T[1,3]<=4 T[2,3]<=2\n                 [].\n        Pcase: h[1] > 6.\n          Hubcap T[1]<=2 T[5]<=0 T[7]<=0 T[2,3]<=2 T[4,6]<=6 [].\n        Pcase: f1[2] <= 6.\n          Hubcap T[2]<=0 T[5]<=0 T[7]<=0 T[1,3]<=4 T[4,6]<=6 [].\n        Pcase: h[5] <= 5.\n          Hubcap T[3]<=0 T[5]<=0 T[7]<=0 T[1,2]<=4 T[4,6]<=6 [].\n        Pcase: h[6] > 5.\n          Hubcap T[2]<=2 T[3]<=0 T[4]<=2 T[5]<=0 T[7]<=0 T[1,6]<=6 [].\n        Pcase: h[7] <= 5.\n          Hubcap T[1]<=4 T[3]<=0 T[5]<=0 T[6]<=3 T[7]<=0 T[2,4]<=3 [].\n        Pcase: h[1] > 5.\n          Hubcap T[3]<=0 T[4]<=2 T[5]<=0 T[6]<=4 T[7]<=0 T[1,2]<=4 [].\n        Hubcap T[1]<=3 T[3]<=0 T[5]<=0 T[6]<=4 T[7]<=0 T[2,4]<=3 [].\n      Pcase: f2[1] <= 5.\n        Reducible.\n      Pcase: h[3] > 6.\n        Hubcap T[2]<=0 T[3]<=0 T[4]<=4 T[5]<=0 T[7]<=0 T[1,6]<=6 [].\n      Pcase: h[5] > 6.\n        Hubcap T[4]<=2 T[5]<=0 T[7]<=0 T[1,6]<=6 T[2,3]<=2 [].\n      Pcase: h[7] > 5.\n        Hubcap T[5]<=0 T[6]<=2 T[7]<=0 T[1,3]<=4 T[2,4]<=4 [].\n      Pcase: h[1] > 6.\n        Hubcap T[1]<=1 T[5]<=0 T[6]<=4 T[7]<=0 T[2,3]<=2 T[2,4]<=4 T[3,4]<=5 [].\n      Pcase: f1[2] > 6.\n        Hubcap T[3]<=0 T[5]<=0 T[7]<=0 T[1,6]<=6 T[2,4]<=4 [].\n      Pcase: f1[2] <= 5.\n        Hubcap T[1]<=1 T[2]<=0 T[3]<=2 T[4]<=3 T[5]<=0 T[6]<=4 T[7]<=0 [].\n      Pcase: f1[3] <= 6.\n        Reducible.\n      Pcase: f2[4] <= 5.\n        Reducible.\n      Hubcap T[2]<=0 T[3]<=1 T[4]<=3 T[5]<=0 T[7]<=0 T[1,6]<=6 [].\n    Pcase L2_6: h[6] > 5.\n      Pcase: f1[3] <= 5.\n        Pcase: s[7] > 6.\n          Hubcap T[1]<=2 T[3]<=0 T[7]<=2 T[2,4]<=4 T[5,6]<=2 [].\n        Pcase: h[1] > 6.\n          Hubcap T[3]<=0 T[1,7]<=3 T[2,4]<=4 T[5,6]<=3 [].\n        Pcase: h[3] > 6.\n          Pcase: s[5] > 6.\n            Similar to L2_4[4].\n          Pcase: h[2] > 5.\n            Hubcap T[2]<=0 T[3]<=0 T[4]<=3 T[1,7]<=4 T[5,6]<=3 [].\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=4 T[2]<=0 T[3]<=0 T[4]<=2 T[7]<=1 T[5,6]<=3 [].\n          Hubcap T[2]<=0 T[3]<=0 T[4]<=3 T[5]<=1 T[7]<=1 T[1,6]<=5 [].\n        Pcase: f1[2] <= 5.\n          Reducible.\n        Pcase: s[5] > 6.\n          Hubcap T[2]<=2 T[3]<=0 T[4]<=2 T[5]<=1 T[1,6]<=4 T[1,7]<=4 T[6,7]<=3 [].\n        Pcase: h[2] > 6.\n          Hubcap T[2]<=2 T[3]<=0 T[4]<=2 T[1,7]<=3 T[5,6]<=3 [].\n        Pcase: h[4] > 5.\n          Hubcap T[2]<=1 T[3]<=0 T[4]<=2 T[1,7]<=4 T[5,6]<=3 [].\n        Pcase: h[5] <= 5.\n          Reducible.\n        Pcase: h[2] <= 5.\n          Hubcap T[2]<=2 T[3]<=0 T[4]<=2 T[5]<=1 T[7]<=1 T[1,6]<=4 [].\n        Pcase: h[7] > 5.\n          Hubcap T[2]<=2 T[3]<=0 T[4]<=2 T[1,5]<=4 T[6,7]<=2 [].\n        Hubcap T[1]<=2 T[2]<=2 T[3]<=0 T[4]<=1 T[5]<=2 T[6,7]<=3 [].\n      Pcase: h[4] > 6.\n        Hubcap T[2]<=0 T[1,3]<=4 T[4,7]<=3 T[5,6]<=3 [].\n      Pcase L3_1: s[5] > 6.\n        Pcase: s[7] > 6.\n          Similar to L2_1[3].\n        Pcase: h[3] > 6.\n          Similar to L2_4[4].\n        Pcase: h[7] <= 5.\n          Similar to L2_2[4].\n        Hubcap T[2]<=1 T[4]<=2 T[5]<=1 T[1,3]<=4 T[6,7]<=2 [].\n      Pcase: f1[5] <= 5.\n        Hubcap T[5]<=0 T[1,7]<=4 T[2,3]<=2 T[4,6]<=4 [].\n      Pcase: h[2] > 6.\n        Pcase: s[7] > 6.\n          Similar to L2_4[3].\n        Pcase: h[3] > 6.\n          Hubcap T[1]<=2 T[2]<=0 T[3]<=0 T[4,7]<=5 T[5,6]<=3 [].\n        Pcase: h[4] > 5.\n          Hubcap T[1]<=2 T[2]<=0 T[3]<=1 T[4,7]<=4 T[5,6]<=3 [].\n        Hubcap T[1,7]<=3 T[5,6]<=3 T[2,3]<=1 T[2,4]<=4 T[3,4]<=4 [].\n      Pcase: h[7] > 5.\n        Pcase: s[7] > 6.\n          Similar to *L3_1[3].\n        Pcase: h[4] > 5.\n          Hubcap T[2]<=0 T[1,3]<=4 T[4,5]<=4 T[6,7]<=2 [].\n        Pcase: h[2] > 5.\n          Hubcap T[1,5]<=4 T[6,7]<=2 T[2,3]<=1 T[2,4]<=4 T[3,4]<=4 [].\n        Pcase: h[3] > 6.\n          Hubcap T[2]<=0 T[3]<=0 T[5]<=1 T[1,4]<=7 T[6,7]<=2 [].\n        Pcase: h[5] > 5.\n          Hubcap T[5]<=1 T[1,2]<=4 T[3,4]<=4 T[6,7]<=1 [].\n        Pcase: h[1] > 5.\n          Hubcap T[2]<=1 T[4]<=3 T[5]<=1 T[1,3]<=4 T[6,7]<=1 [].\n        Hubcap T[1]<=3 T[4]<=3 T[5]<=1 T[2,3]<=1 T[6,7]<=2 [].\n      Pcase: s[7] <= 6.\n        Hubcap T[4]<=2 T[1,7]<=3 T[2,3]<=2 T[5,6]<=3 [].\n      Pcase: h[2] > 5.\n        Similar to L3_1[3].\n      Pcase: h[3] > 6.\n        Similar to *L2_4[0].\n      Pcase: h[5] > 6.\n        Hubcap T[1]<=2 T[4]<=2 T[5]<=2 T[6]<=0 T[7]<=2 T[2,3]<=2 [].\n      Pcase L3_2: h[4] > 5.\n        Pcase: h[5] > 5.\n          Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=2 T[5]<=2 T[6]<=0 T[7]<=2 [].\n        Pcase: f1[1] <= 5.\n          Hubcap T[2]<=0 T[6]<=1 T[7]<=2 T[1,3]<=3 T[4,5]<=4 [].\n        Pcase: f1[2] > 5.\n          Hubcap T[1]<=2 T[2]<=0 T[3]<=1 T[6]<=1 T[7]<=2 T[4,5]<=4 [].\n        Pcase: f1[4] > 5.\n          Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=2 T[7]<=2 T[5,6]<=2 [].\n        Pcase: f1[5] > 6.\n          Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[6]<=0 T[7]<=2 T[4,5]<=4 [].\n        Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=2 T[5]<=0 T[6]<=1 T[7]<=2 [].\n      Pcase: h[5] > 5.\n        Similar to *L3_2[0].\n      Pcase: f1[1] <= 5.\n        Hubcap T[4]<=3 T[7]<=2 T[5,6]<=2 T[1,2]<=2 T[1,3]<=3 T[2,3]<=2 [].\n      Pcase: f1[2] > 5.\n        Hubcap T[1]<=2 T[4]<=3 T[7]<=2 T[2,3]<=1 T[5,6]<=2 [].\n      Pcase: f1[3] <= 6.\n        Reducible.\n      Pcase: f1[4] > 5.\n        Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4,7]<=4 T[5,6]<=2 [].\n      Hubcap T[1]<=1 T[2]<=0 T[3]<=2 T[4]<=3 T[7]<=2 T[5,6]<=2 [].\n    Pcase: s[5] > 6.\n      Similar to L2_6[4].\n    Pcase: s[7] > 6.\n      Similar to L2_2[3].\n    Pcase: h[7] > 5.\n      Similar to *L2_6[3].\n    Pcase: f1[6] <= 6.\n      Reducible.\n    Pcase: h[2] > 5.\n      Hubcap T[5]<=1 T[6]<=3 T[7]<=1 T[1,3]<=2 T[2,4]<=3 [].\n    Hubcap T[1]<=1 T[4]<=2 T[5]<=1 T[6]<=3 T[7]<=1 T[2,3]<=2 [].\n  Pcase: s[5] > 6.\n    Similar to L1_1[4].\n  Pcase L1_2: h[5] <= 5.\n    Pcase: s[3] > 7.\n      Hubcap T[2]<=0 T[3]<=0 T[4,5]<=4 T[1,6]<=6 T[1,7]<=4 T[6,7]<=3 [].\n    Pcase: s[6] > 7.\n      Hubcap T[6]<=0 T[7]<=0 T[4,5]<=4 T[1,2]<=4 T[1,3]<=6 T[2,3]<=3 [].\n    Pcase: f1[4] <= 5.\n      Pcase: h[4] <= 5.\n        Reducible.\n      Pcase: f1[5] <= 5.\n        Reducible.\n      Pcase: s[1] > 7.\n        Hubcap T[1]<=0 T[2]<=1 T[3]<=2 T[4]<=1 T[5]<=3 T[6,7]<=3 [].\n      Pcase: s[2] > 7.\n        Hubcap T[2]<=0 T[3]<=2 T[4]<=1 T[1,5]<=4 T[6,7]<=3 [].\n      Pcase: s[7] > 6.\n        Hubcap T[3]<=2 T[4]<=1 T[5]<=3 T[1,2]<=2 T[6,7]<=2 [].\n      Pcase: h[7] <= 5.\n        Reducible.\n      Pcase: s[2] > 6.\n        Hubcap T[2]<=1 T[4]<=1 T[1,5]<=4 T[3,6]<=4 T[3,7]<=2 T[6,7]<=3 [].\n      Pcase: h[2] > 6.\n        Hubcap T[1]<=2 T[2]<=0 T[4]<=1 T[3,5]<=4 T[6,7]<=3 [].\n      Pcase: h[6] > 5.\n        Hubcap T[2]<=0 T[3]<=2 T[4]<=1 T[5]<=2 T[7]<=0 T[1,6]<=5 [].\n      Pcase: f1[5] <= 6.\n        Reducible.\n      Pcase: s[6] <= 6.\n        Hubcap T[2]<=0 T[4]<=1 T[5]<=3 T[1,3]<=3 T[6,7]<=3 [].\n      Pcase: s[3] > 6.\n        Similar to L1_1[2].\n      Pcase: h[3] <= 5.\n        Reducible.\n      Pcase: h[2] > 5.\n        Hubcap T[1]<=4 T[2]<=0 T[4]<=1 T[5]<=2 T[7]<=0 T[3,6]<=3 [].\n      Pcase: h[3] > 6.\n        Hubcap T[1]<=4 T[2]<=0 T[4]<=1 T[5]<=2 T[7]<=0 T[3,6]<=3 [].\n      Pcase: f1[3] <= 5.\n        Reducible.\n      Pcase: h[4] > 6.\n        Hubcap T[2]<=0 T[4]<=1 T[5]<=2 T[6]<=2 T[7]<=0 T[1,3]<=4 [].\n      Hubcap T[1]<=4 T[2]<=0 T[3]<=2 T[4]<=1 T[5]<=2 T[6]<=1 T[7]<=0 [].\n    Pcase L2_1: s[7] > 6.\n      Pcase: s[3] > 6.\n        Similar to L1_1[6].\n      Pcase: s[2] > 6.\n        Hubcap T[1]<=0 T[2]<=1 T[3]<=1 T[4]<=3 T[7]<=1 T[5,6]<=4 [].\n      Pcase: s[6] > 6.\n        Hubcap T[1]<=2 T[5]<=1 T[7]<=0 T[2,3]<=3 T[4,6]<=4 [].\n      Pcase: h[3] > 6.\n        Hubcap T[2]<=0 T[3]<=1 T[7]<=1 T[1,4]<=4 T[5,6]<=4 [].\n      Pcase: f1[3] <= 5.\n        Reducible.\n      Pcase: s[1] > 7.\n        Hubcap T[1]<=0 T[7]<=1 T[2,3]<=3 T[4,5]<=5 T[4,6]<=4 T[5,6]<=4 [].\n      Pcase: h[2] > 6.\n        Hubcap T[1]<=0 T[2]<=1 T[7]<=1 T[3,6]<=3 T[4,5]<=5 [].\n      Pcase: h[4] <= 5.\n        Hubcap T[1]<=1 T[7]<=1 T[2,3]<=3 T[4,5]<=5 T[4,6]<=3 T[5,6]<=3 [].\n      Pcase: h[2] > 5.\n        Hubcap T[1]<=1 T[2]<=1 T[7]<=1 T[3,4]<=3 T[5,6]<=4 [].\n      Pcase: h[3] <= 5.\n        Hubcap T[1]<=2 T[2]<=1 T[7]<=1 T[3,4]<=3 T[5,6]<=3 [].\n      Pcase: s[7] > 7.\n        Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=2 T[7]<=0 T[5,6]<=4 [].\n      Pcase: h[6] > 5.\n        Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=2 T[7]<=1 T[5,6]<=3 [].\n      Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4]<=1 T[5]<=3 T[6]<=1 T[7]<=1 [].\n    Pcase: s[2] > 6.\n      Similar to *L2_1[6].\n    Pcase L2_2: s[3] > 6.\n      Pcase: s[6] > 6.\n        Similar to L1_1[2].\n      Pcase: s[1] > 7.\n        Hubcap T[1]<=0 T[2]<=0 T[3]<=2 T[4]<=2 T[5]<=3 T[6,7]<=3 [].\n      Pcase: h[2] > 6.\n        Hubcap T[2]<=0 T[3]<=2 T[1,5]<=4 T[4,6]<=4 T[4,7]<=2 T[6,7]<=3 [].\n      Pcase: h[6] > 6.\n        Hubcap T[2]<=0 T[3]<=2 T[4]<=2 T[5]<=1 T[7]<=1 T[1,6]<=4 [].\n      Pcase: h[6] <= 5.\n        Hubcap T[2]<=0 T[3]<=2 T[4]<=1 T[1,6]<=4 T[5,7]<=3 [].\n      Hubcap T[2]<=0 T[1,7]<=4 T[3,4]<=3 T[5,6]<=3 [].\n    Pcase: s[6] > 6.\n      Similar to *L2_2[6].\n    Pcase L2_3: h[6] > 5.\n      Pcase: s[1] > 7.\n        Hubcap T[1]<=0 T[2]<=1 T[3]<=3 T[4,7]<=3 T[5,6]<=3 [].\n      Pcase: h[3] > 6.\n        Hubcap T[2]<=0 T[3]<=1 T[5,6]<=3 T[1,4]<=6 T[1,7]<=4 T[4,7]<=3 [].\n      Pcase: f1[3] <= 5.\n        Reducible.\n      Pcase: h[4] > 6.\n        Hubcap T[2]<=1 T[1,3]<=4 T[4,7]<=2 T[5,6]<=3 [].\n      Pcase: h[7] <= 5.\n        Hubcap T[1]<=2 T[2]<=1 T[7]<=1 T[3,4]<=3 T[5,6]<=3 [].\n      Pcase: h[2] > 6.\n        Hubcap T[2]<=1 T[3]<=2 T[7]<=0 T[1,4]<=4 T[5,6]<=3 [].\n      Pcase: h[3] <= 5.\n        Hubcap T[1]<=2 T[2]<=1 T[3]<=2 T[4]<=2 T[7]<=0 T[5,6]<=3 [].\n      Pcase: h[4] > 5.\n        Hubcap T[2]<=0 T[4]<=2 T[7]<=0 T[1,3]<=5 T[5,6]<=3 [].\n      Pcase: f1[4] <= 6.\n        Reducible.\n      Pcase: h[2] > 5.\n        Hubcap T[1]<=2 T[4]<=3 T[7]<=0 T[2,3]<=2 T[5,6]<=3 [].\n      Hubcap T[1]<=2 T[7]<=0 T[2,3]<=3 T[4,5]<=4 T[4,6]<=4 T[5,6]<=3 [].\n    Pcase: h[4] > 5.\n      Similar to *L2_3[6].\n    Pcase: h[3] <= 5.\n      Reducible.\n    Pcase: h[7] <= 5.\n      Reducible.\n    Pcase: f1[3] <= 5.\n      Reducible.\n    Pcase: f1[4] <= 6.\n      Reducible.\n    Pcase: f1[5] <= 6.\n      Reducible.\n    Pcase: f1[6] <= 5.\n      Reducible.\n    Pcase: s[1] > 7.\n      Hubcap T[1]<=0 T[4]<=2 T[5]<=2 T[2,3]<=3 T[6,7]<=3 [].\n    Pcase: h[2] > 6.\n      Hubcap T[1]<=1 T[4]<=2 T[5]<=2 T[2,3]<=2 T[6,7]<=3 [].\n    Pcase: h[3] > 6.\n      Hubcap T[1]<=2 T[2]<=0 T[3]<=1 T[4]<=2 T[5]<=2 T[6,7]<=3 [].\n    Pcase: h[7] > 6.\n      Hubcap T[1]<=2 T[4]<=2 T[5]<=2 T[6]<=1 T[7]<=0 T[2,3]<=3 [].\n    Pcase: h[1] > 6.\n      Hubcap T[1]<=1 T[4]<=2 T[5]<=2 T[2,3]<=3 T[6,7]<=2 [].\n    Pcase L2_4: h[2] > 5.\n      Pcase: h[1] > 5.\n        Hubcap T[1]<=2 T[4]<=2 T[5]<=2 T[2,3]<=2 T[6,7]<=2 [].\n      Pcase: f1[1] <= 5.\n        Reducible.\n      Pcase: f1[6] > 6.\n        Hubcap T[4]<=2 T[5]<=2 T[7]<=0 T[1,6]<=4 T[2,3]<=2 [].\n      Hubcap T[1]<=2 T[4]<=2 T[5]<=2 T[6]<=1 T[7]<=1 T[2,3]<=2 [].\n    Pcase: h[1] > 5.\n      Similar to *L2_4[6].\n    Pcase: f1[1] <= 5.\n      Reducible.\n    Pcase: f1[2] <= 5.\n      Reducible.\n    Pcase: f1[7] <= 5.\n      Reducible.\n    Pcase: f2[1] <= 5.\n      Reducible.\n    Hubcap T[1]<=2 T[4]<=2 T[5]<=2 T[2,3]<=2 T[6,7]<=2 [].\n  Pcase L1_3: s[3] > 6.\n    Pcase: s[6] > 6.\n      Similar to L1_1[2].\n    Pcase: s[7] > 6.\n      Similar to L1_1[6].\n    Pcase: h[7] <= 5.\n      Similar to L1_2[2].\n    Pcase: s[1] > 7.\n      Hubcap T[1]<=0 T[2]<=0 T[3]<=4 T[4,5]<=3 T[6,7]<=3 [].\n    Pcase: s[2] > 6.\n      Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4,5]<=3 T[6,7]<=3 [].\n    Pcase: s[3] > 7.\n      Hubcap T[1]<=4 T[2]<=0 T[3]<=0 T[4,5]<=3 T[6,7]<=3 [].\n    Pcase: h[6] > 6.\n      Hubcap T[2]<=0 T[4]<=1 T[7]<=1 T[1,6]<=4 T[3,5]<=4 [].\n    Pcase: h[6] <= 5.\n      Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4,5]<=3 T[6,7]<=3 [].\n    Pcase: h[2] > 6.\n      Hubcap T[1]<=2 T[2]<=0 T[3]<=4 T[4,5]<=2 T[6,7]<=2 [].\n    Pcase: h[3] > 6.\n      Hubcap T[1]<=4 T[2]<=0 T[3]<=2 T[4,5]<=2 T[6,7]<=2 [].\n    Pcase: h[4] > 5.\n      Hubcap T[2]<=0 T[1,3]<=6 T[4,5]<=2 T[6,7]<=2 [].\n    Pcase: h[3] <= 5.\n      Hubcap T[1]<=4 T[2]<=0 T[3]<=3 T[4,5]<=1 T[6,7]<=2 [].\n    Pcase: h[7] > 6.\n      Hubcap T[1]<=4 T[2]<=0 T[7]<=0 T[3,4]<=4 T[5,6]<=2 [].\n    Pcase: h[1] > 5.\n      Hubcap T[2]<=0 T[1,3]<=6 T[4,5]<=2 T[6,7]<=2 [].\n    Pcase: h[2] <= 5.\n      Hubcap T[1]<=3 T[2]<=0 T[3]<=4 T[4,5]<=2 T[6,7]<=1 [].\n    Pcase: h[5] > 6.\n      Hubcap T[2]<=0 T[3]<=4 T[4]<=0 T[1,5]<=4 T[6,7]<=2 [].\n    Pcase: f1[1] > 5.\n      Hubcap T[1]<=2 T[2]<=0 T[3]<=4 T[4,5]<=2 T[6,7]<=2 [].\n    Hubcap T[1]<=4 T[2]<=0 T[7]<=0 T[3,5]<=4 T[4,6]<=2 [].\n  Pcase: s[6] > 6.\n    Similar to L1_3[5].\n  Pcase L1_4: h[4] <= 5.\n    Pcase: s[7] > 6.\n      Similar to L1_2[6].\n    Pcase: h[7] <= 5.\n      Reducible.\n    Pcase: s[1] > 7.\n      Hubcap T[1]<=0 T[2,3]<=4 T[4,5]<=3 T[6,7]<=3 [].\n    Pcase: s[2] > 7.\n      Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4,5]<=3 T[6,7]<=3 [].\n    Pcase: h[3] > 6.\n      Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[4,5]<=3 T[6,7]<=3 [].\n    Pcase: h[7] > 6.\n      Hubcap T[1]<=2 T[6]<=1 T[7]<=0 T[2,3]<=4 T[4,5]<=3 [].\n    Pcase: h[1] > 6.\n      Hubcap T[1]<=1 T[2,3]<=4 T[4,5]<=3 T[6,7]<=2 [].\n    Pcase: h[6] > 5.\n      Pcase: s[2] > 6.\n        Hubcap T[1]<=2 T[2,5]<=3 T[3,4]<=3 T[6,7]<=2 [].\n      Pcase: h[2] > 6.\n        Hubcap T[1]<=1 T[2,3]<=4 T[4,5]<=3 T[6,7]<=2 [].\n      Pcase: h[2] <= 5.\n        Hubcap T[1]<=2 T[2,3]<=4 T[4,5]<=3 T[6,7]<=1 [].\n      Pcase: h[3] > 5.\n        Hubcap T[1]<=2 T[2,3]<=3 T[4,5]<=3 T[6,7]<=2 [].\n      Hubcap T[1]<=2 T[2]<=1 T[3]<=3 T[4,5]<=2 T[6,7]<=2 [].\n    Pcase: s[2] > 6.\n      Similar to L1_2[1].\n    Pcase: h[3] <= 5.\n      Reducible.\n    Pcase: f1[3] <= 5.\n      Reducible.\n    Pcase: f1[4] <= 5.\n      Reducible.\n    Pcase: f1[5] <= 5.\n      Reducible.\n    Pcase: f1[6] <= 5.\n      Reducible.\n    Pcase: h[2] > 5.\n      Hubcap T[1]<=2 T[2,3]<=2 T[4,5]<=3 T[6,7]<=3 [].\n    Hubcap T[1]<=2 T[2,3]<=3 T[4,5]<=3 T[6,7]<=2 [].\n  Pcase: h[6] <= 5.\n    Similar to *L1_4[6].\n  Pcase: s[1] > 7.\n    Hubcap T[1]<=0 T[2]<=2 T[5]<=2 T[3,4]<=3 T[6,7]<=3 [].\n  Pcase: s[2] > 6.\n    Hubcap T[2]<=2 T[1,5]<=3 T[3,4]<=2 T[6,7]<=3 [].\n  Pcase: s[7] > 6.\n    Hubcap T[7]<=2 T[1,4]<=3 T[2,3]<=3 T[5,6]<=2 [].\n  Pcase: h[3] > 6.\n    Hubcap T[2]<=0 T[1,7]<=5 T[3,4]<=2 T[5,6]<=3 [].\n  Pcase: h[7] > 6.\n    Hubcap T[7]<=0 T[1,2]<=5 T[3,4]<=3 T[5,6]<=2 [].\n  Pcase L1_5: h[3] > 5.\n    Pcase: h[2] > 5.\n      Hubcap T[2]<=1 T[1,7]<=4 T[3,4]<=2 T[5,6]<=3 [].\n    Hubcap T[7]<=1 T[1,6]<=5 T[2,3]<=2 T[4,5]<=2 [].\n  Pcase: h[7] > 5.\n    Similar to *L1_5[6].\n  Pcase: h[2] <= 5.\n    Hubcap T[5]<=1 T[6]<=2 T[7]<=1 T[1,4]<=3 T[2,3]<=3 [].\n  Pcase: h[4] > 6.\n    Hubcap T[1]<=2 T[4]<=0 T[5]<=2 T[2,3]<=3 T[6,7]<=3 [].\n  Pcase: h[6] > 6.\n    Hubcap T[1]<=2 T[2]<=2 T[5]<=0 T[3,4]<=3 T[6,7]<=3 [].\n  Pcase: h[1] > 6.\n    Hubcap T[2]<=2 T[1,5]<=2 T[3,4]<=3 T[6,7]<=3 [].\n  Pcase: h[1] <= 5.\n    Hubcap T[2]<=1 T[3]<=2 T[4]<=1 T[1,5]<=3 T[6,7]<=3 [].\n  Pcase: h[2] > 6.\n    Hubcap T[5]<=2 T[1,2]<=2 T[3,4]<=3 T[6,7]<=3 [].\n  Pcase: f1[1] > 5.\n    Hubcap T[2]<=2 T[1,5]<=2 T[3,4]<=3 T[6,7]<=3 [].\n  Hubcap T[2]<=1 T[3]<=2 T[4]<=1 T[1,5]<=3 T[6,7]<=3 [].\nPcase: s[2] > 6.\n  Similar to L0_2[1].\nPcase: s[3] > 6.\n  Similar to L0_2[2].\nPcase: s[4] > 6.\n  Similar to L0_2[3].\nPcase: s[5] > 6.\n  Similar to L0_2[4].\nPcase: s[6] > 6.\n  Similar to L0_2[5].\nPcase: s[7] > 6.\n  Similar to L0_2[6].\nPcase L0_3: h[2] <= 5.\n  Pcase: h[5] <= 5.\n    Reducible.\n  Pcase: h[6] <= 5.\n    Reducible.\n  Pcase: h[3] > 6.\n    Hubcap T[3]<=1 T[1,2]<=4 T[4,7]<=3 T[5,6]<=2 [].\n  Pcase: h[3] <= 5.\n    Hubcap T[1]<=2 T[3]<=2 T[2,4]<=4 T[5,6]<=1 T[5,7]<=2 T[6,7]<=2 [].\n  Hubcap T[2,3]<=3 T[5,6]<=2 T[1,4]<=4 T[1,7]<=4 T[4,7]<=3 [].\nPcase: h[3] <= 5.\n  Similar to L0_3[1].\nPcase: h[4] <= 5.\n  Similar to L0_3[2].\nPcase: h[5] <= 5.\n  Similar to L0_3[3].\nPcase: h[6] <= 5.\n  Similar to L0_3[4].\nPcase: h[7] <= 5.\n  Similar to L0_3[5].\nPcase: h[1] <= 5.\n  Similar to L0_3[6].\nHubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4,5]<=2 T[6,7]<=2 [].\nQed.\n", "meta": {"author": "tangentforks", "repo": "FourColorTheorem", "sha": "eb30720f9e773fdcbf13dc6c61fdb245587cf401", "save_path": "github-repos/coq/tangentforks-FourColorTheorem", "path": "github-repos/coq/tangentforks-FourColorTheorem/FourColorTheorem-eb30720f9e773fdcbf13dc6c61fdb245587cf401/present7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.27958175537640223}}
{"text": "Require Import VerdiRaft.Raft.\nRequire Import VerdiRaft.CommonDefinitions.\n\nSection StateMachineCorrect.\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 state_machine_log net :=\n    forall h,\n      stateMachine (nwState net h) =\n      snd (execute_log (deduplicate_log (rev (removeAfterIndex (log (nwState net h))\n                                                               (lastApplied (nwState net h)))))).\n\n  Definition client_cache_correct net :=\n    forall h client id out,\n      getLastId (nwState net h) client = Some (id, out) ->\n      output_correct client id out (rev (removeAfterIndex (log (nwState net h))\n                                                          (lastApplied (nwState net h)))).\n\n  Definition client_cache_complete net :=\n    forall h e,\n      In e (removeAfterIndex (log (nwState net h)) (lastApplied (nwState net h))) ->\n      exists id o,\n        getLastId (nwState net h) (eClient e) = Some (id, o) /\\\n        eId e <= id.\n\n  Definition state_machine_correct net :=\n    state_machine_log net /\\ client_cache_correct net /\\ client_cache_complete net.\n\n  Class state_machine_correct_interface : Prop :=\n    {\n      state_machine_correct_invariant :\n        forall net,\n          raft_intermediate_reachable net ->\n          state_machine_correct net\n    }.\nEnd StateMachineCorrect.\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/StateMachineCorrectInterface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.27958175537640223}}
{"text": "From Pony Require Import Language Typing Heap.\n\nRequire Import Coq.FSets.FMapInterface.\nRequire Import Coq.MSets.MSetInterface.\n\nModule Regions (Map : WSfun) (SetM : WSetsOn).\n\nModule Heap := Heap Map.\nExport Heap.\n\nModule WFExpr := WFExpressions Map SetM.\nExport WFExpr.\n\nModule SomeAddrMap := Map DecidableSomeAddr.\nDefinition someAddrMap := SomeAddrMap.t.\n\nDefinition owner : Type := someAddr.\n\nInductive accessor : Type :=\n  | fieldAcc : Syntax.fieldId -> accessor\n  | varAcc : Syntax.var -> accessor\n  | next : accessor\n  | super : accessor.\n\n(* Like heap lookup, but defines the (intuitive) behaviour of looking up the\n* value of an accessor on an addresss *)\nInductive AccessLookup : someAddr -> accessor -> value -> heap -> Prop :=\n  | AccessLookup_field (iota : someAddr) (f : Syntax.fieldId) (v : value) (chi : heap)\n  : HeapFieldLookup (Some iota) f v chi\n    -> AccessLookup iota (fieldAcc f) v chi\n  | AccessLookup_var (iota : someAddr) (fr : frame) (x : Syntax.var) (v : value) (chi : heap)\n  : HeapMapsTo frame iota fr chi\n    -> Heap.LocalMap.VarMapsTo x v (lVars fr)\n    -> AccessLookup iota (varAcc x) v chi\n  | AccessLookup_next_actor (iota : someAddr) (a : actor) (v_next : messageAddr? ) (chi : heap)\n  : HeapMapsTo actor iota a chi\n    -> messageQueue a = v_next\n    -> AccessLookup iota next (option_map someMessageAddr v_next) chi\n  | AccessLookup_next_message (iota : someAddr) (m : message) (v_next : messageAddr? ) (chi : heap)\n  : HeapMapsTo message iota m chi\n    -> nextMessage m = v_next\n    -> AccessLookup iota next (option_map someMessageAddr v_next) chi\n  | AccessLookup_super_actor (iota : someAddr) (a : actor) (v_super : frameAddr? ) (chi : heap)\n  : HeapMapsTo actor iota a chi\n    -> frameStack a = v_super\n    -> AccessLookup iota super (option_map someFrameAddr v_super) chi\n  | AccessLookup_super_frame (iota : someAddr) (fr : frame) (v_super : frameAddr? ) (chi : heap)\n  : HeapMapsTo frame iota fr chi\n    -> superFrame fr = v_super\n    -> AccessLookup iota super (option_map someFrameAddr v_super) chi.\n\nInductive region : Type :=\n  | isoReg : owner -> accessor -> region\n  | trnReg : owner -> accessor -> region\n  | valReg : region.\n\nDefinition sentinelMap : Type := someAddrMap someAddr.\nDefinition regionMap : Type := someAddrMap region.\n\nDefinition RegionPartition (s : sentinelMap) (r : regionMap) (chi : heap) : Prop :=\n  forall (iota : someAddr), HeapIn iota chi -> SomeAddrMap.In iota s\n  /\\\n  forall (iota iota' : someAddr), SomeAddrMap.MapsTo iota iota' s -> SomeAddrMap.MapsTo iota' iota' s\n  /\\\n  forall (iota : someAddr), SomeAddrMap.In iota r <-> exists (iota' : someAddr), SomeAddrMap.MapsTo iota' iota s. \n\nDefinition regPart (chi : heap) : Type := { r : (sentinelMap * regionMap) | RegionPartition (fst r) (snd r) chi }.\n\nDefinition SentinelMapsTo { chi : heap } (iota iota' : someAddr) (r : regPart chi) : Prop :=\n  SomeAddrMap.MapsTo iota iota' (fst (proj1_sig r)).\n\nDefinition RegionMapsTo { chi : heap } (iota : someAddr) (reg : region) (r : regPart chi) : Prop :=\n  SomeAddrMap.MapsTo iota reg (snd (proj1_sig r)).\n\nInductive perspJudgement (chi : heap) (r : regPart chi) : someAddr -> accessor -> someAddr? -> Syntax.baseCapability -> Prop :=\n  | persp_iso (iota iota' : someAddr) (a : accessor)\n  : SentinelMapsTo iota' iota' r\n      -> RegionMapsTo iota' (isoReg iota a) r\n      -> perspJudgement chi r iota a (Some iota') Syntax.iso\n  | persp_trn (iota iota' : someAddr) (a : accessor)\n  : SentinelMapsTo iota' iota' r\n      -> RegionMapsTo iota' (trnReg iota a) r\n      -> perspJudgement chi r iota a (Some iota') Syntax.trn\n  | persp_ref (iota iota' iota'' : someAddr) (a : accessor)\n  : SentinelMapsTo iota iota'' r\n    -> SentinelMapsTo iota' iota'' r\n    -> perspJudgement chi r iota a (Some iota') Syntax.ref\n  | persp_val (iota iota' iota'' : someAddr) (a : accessor)\n  : SentinelMapsTo iota' iota'' r\n      -> RegionMapsTo iota'' valReg r\n      -> perspJudgement chi r iota a (Some iota') Syntax.val\n  | persp_val_region (iota iota' iota'' iota''' : someAddr) (a : accessor) (b : Syntax.baseCapability)\n  : SentinelMapsTo iota iota'' r\n      -> RegionMapsTo iota'' valReg r\n      -> SentinelMapsTo iota' iota''' r\n      -> RegionMapsTo iota''' valReg r\n      -> perspJudgement chi r iota a (Some iota') b\n  | persp_box (iota iota' iota'' : someAddr) (a : accessor)\n  : SentinelMapsTo iota iota'' r\n    -> SentinelMapsTo iota' iota'' r\n    -> perspJudgement chi r iota a (Some iota') Syntax.box\n  | persp_box_trans (iota iota' iota'' : someAddr) (alpha beta gamma : accessor)\n  : perspJudgement chi r iota beta (Some iota'') Syntax.box\n    -> perspJudgement chi r iota'' gamma (Some iota') Syntax.box\n    -> perspJudgement chi r iota alpha (Some iota') Syntax.box\n  | persp_tag (iota iota' : someAddr) (a : accessor)\n  : perspJudgement chi r iota a (Some iota') Syntax.tag\n  | persp_subsume (iota iota' : someAddr) (a : accessor) (b b' : Syntax.baseCapability)\n  : Syntax.subcapability (Syntax.base b) (Syntax.base b')\n    -> perspJudgement chi r iota a (Some iota') b\n    -> perspJudgement chi r iota a (Some iota') b'\n  | persp_nul (iota : someAddr) (a : accessor) (b : Syntax.baseCapability)\n  : perspJudgement chi r iota a None b.\n\nInductive perspJudgementTemp (chi : heap) (r : regPart chi) : someAddr -> Syntax.temp -> someAddr? -> Syntax.capability -> Prop :=\n  | persp_temp (iota : someAddr) (v : someAddr?) (a : accessor) (b : Syntax.baseCapability) (t : Syntax.temp)\n  : perspJudgement chi r iota a v b\n    -> perspJudgementTemp chi r iota t v (Syntax.base b)\n  | persp_temp_ephem (iota : someAddr) (v : someAddr?) (a : accessor) (b : Syntax.baseCapability) (t : Syntax.temp)\n  : perspJudgement chi r iota a v b\n    -> ~ AccessLookup iota a v chi\n    -> perspJudgementTemp chi r iota t v (Syntax.hatCap b)\n  | persp_temp_trans (iota iota' : someAddr) (v : someAddr?) (a : accessor) (k k' : Syntax.capability)\n    (b : Syntax.baseCapability) (t : Syntax.temp)\n  : perspJudgementTemp chi r iota t (Some iota') k\n    -> perspJudgement chi r iota' a v b\n    -> Some k' = viewAdapt k b\n    -> perspJudgementTemp chi r iota t v k'.\n\nEnd Regions.\n\nModule WellFormedHeaps (Map : WSfun) (SetM : WSetsOn).\n\nModule Regions := Regions Map SetM.\nExport Regions.\n\nImport Typing.Context.\n\nDefinition well_typed_locals (chi : heap) (r : regPart chi) (iota : someAddr) (L : localVars) (gamma : Typing.Context.context) : Prop :=\n  ( forall x : Syntax.var, \n    forall S : Syntax.typeId,\n    forall b : Syntax.baseCapability,\n    forall v : value,\n      Typing.Context.LocalMap.VarMapsTo x (Syntax.aType S b) gamma\n      -> Heap.LocalMap.VarMapsTo x v L\n      -> heapTyping v S chi\n          /\\ perspJudgement chi r iota (varAcc x) v b)\n  /\\ \n  ( forall t : Syntax.temp,\n    forall S : Syntax.typeId,\n    forall k : Syntax.capability,\n    forall v : value,\n      Typing.Context.LocalMap.TempMapsTo t (Syntax.type S k) gamma\n      -> Heap.LocalMap.TempMapsTo t v L\n      -> heapTyping v S chi).\n\nDefinition argsToLocals (args : arrayVarMap value) : localVars :=\n  ArrayVarMap.fold (fun var val localMap => Heap.LocalMap.addVar var val localMap) args emptyLocals.\n\nDefinition well_typed_fields { P : program } (chi : heap) (r : regPart chi) (iota : someAddr) (F : Heap.fieldMap value) (S : Syntax.typeId) : Prop :=\n  ( forall f : Syntax.fieldId, \n    forall S' : Syntax.typeId,\n    forall b : Syntax.baseCapability,\n    forall v : value,\n      @fieldLookup P S f (Syntax.aType S' b) \n      -> Heap.FieldMap.MapsTo f v F\n      -> heapTyping v S' chi\n          /\\ perspJudgement chi r iota (fieldAcc f) v b).\n\nInductive well_formed_message { p : program } (chi : heap) (r : regPart chi) : option messageAddr -> Syntax.actorId -> Prop :=\n  | wf_message (iota : messageAddr) (rcvrId : Syntax.actorId) (bId : Syntax.behaviourId) (mArgs : arrayVarMap value) (mNext : option messageAddr)\n      (bArgs : arrayVarMap Syntax.aliasedType) (bBody : Syntax.expressionSeq)\n  : HeapMapsTo message (someMessageAddr iota) (messageAlloc bId mArgs mNext) chi\n    -> @behaviourLookup p (inr rcvrId)  bId (bDef bArgs bBody) \n    -> perspJudgement chi r (someMessageAddr iota) next (option_map someMessageAddr mNext) Syntax.iso\n    -> well_typed_locals chi r (someMessageAddr iota) (argsToLocals mArgs) (argsToContext bArgs)\n    -> well_formed_message chi r mNext rcvrId\n    -> well_formed_message chi r (Some iota) rcvrId\n  | wf_message_nul (a : Syntax.actorId)\n  : well_formed_message chi r None a.\n\nInductive well_formed_frame { P : program } (chi : heap) (r : regPart chi) : option frameAddr -> Prop :=\n  | wf_frame_top (iota : frameAddr) (gamma : context) (L : localVars) (E : Syntax.expressionSeq)\n    (v_super : frameAddr?) (t : Syntax.ponyType)\n  : HeapMapsTo frame (someFrameAddr iota) (frameAlloc L E None v_super) chi\n    -> @well_formed_expr P gamma E t\n    -> well_typed_locals chi r (someFrameAddr iota) L gamma\n    -> well_formed_frame_if_returned chi r v_super t\n    -> perspJudgement chi r (someFrameAddr iota) super (option_map someFrameAddr v_super) Syntax.iso\n    -> well_formed_frame chi r (Some iota)\n  | wf_frame_null\n  : well_formed_frame chi r None\nwith\nwell_formed_frame_if_returned { P : program } (chi : heap) (r : regPart chi) : option frameAddr -> Syntax.ponyType -> Prop :=\n  | wf_frame_ir (iota : frameAddr) (gamma : context) (L : localVars) (E : Syntax.expressionSeq)\n    (v_super : frameAddr?) (t : Syntax.ponyType) (t' : Syntax.aliasedType) (y : Syntax.var)\n  : HeapMapsTo frame (someFrameAddr iota) (frameAlloc L E (Some y) v_super) chi\n    -> @well_formed_expr P (addVar y t' gamma) E t\n    -> well_typed_locals chi r (someFrameAddr iota) L gamma\n    -> well_formed_frame_if_returned chi r v_super t\n    -> perspJudgement chi r (someFrameAddr iota) super (option_map someFrameAddr v_super) Syntax.iso\n    -> well_formed_frame_if_returned chi r (Some iota) (Syntax.asPonyType t')\n  | wf_frame_ir_no_return (v : option frameAddr) (t : Syntax.ponyType)\n  : well_formed_frame chi r v \n    -> well_formed_frame_if_returned chi r v t.\n\nDefinition well_formed_object { P : program } (chi : heap) (r : regPart chi) (iota : objectAddr) : Prop :=\n  exists c : Syntax.classId,\n  exists F : Heap.fieldMap value,\n    HeapMapsTo object (someObjectAddr iota) (objectAlloc c F) chi\n    /\\ @well_typed_fields P chi r (someObjectAddr iota) F (classTypeId c).\n\nDefinition well_formed_actor { P : program } (chi : heap) (r : regPart chi) (iota : actorAddr) : Prop :=\n  exists a : Syntax.actorId,\n  exists F : Heap.fieldMap value,\n  exists v_mes : option messageAddr,\n  exists v_frm : option frameAddr,\n    HeapMapsTo actor (someActorAddr iota) (actorAlloc a F v_mes v_frm) chi\n    /\\ perspJudgement chi r (someActorAddr iota) (varAcc Syntax.this) (Some (someActorAddr iota)) Syntax.iso\n    /\\ @well_typed_fields P chi r (someActorAddr iota) F (actorTypeId a)\n    /\\ @well_formed_message P chi r v_mes a\n    /\\ @well_formed_frame P chi r v_frm. \n\nDefinition well_formed_heap { P : program } (chi : heap) (r : regPart chi) : Prop :=\n  ( forall iota_a : actorAddr,\n      @well_formed_actor P chi r iota_a )\n  /\\\n  ( forall iota_o : objectAddr,\n      @well_formed_object P chi r iota_o ).\n\nEnd WellFormedHeaps.\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/Regions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863695, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2795817553764022}}
{"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 develops the memory model that is used in the dynamic\n  semantics of all the languages used in the compiler.\n  It defines a type [mem] of memory states, the following 4 basic\n  operations over memory states, and their properties:\n- [load]: read a memory chunk at a given address;\n- [store]: store a memory chunk at a given address;\n- [alloc]: allocate a fresh memory block;\n- [free]: invalidate a memory block.\n*)\n\nRequire Import Zwf.\nRequire Import Axioms.\nRequire Import Coqlib.\nRequire Intv.\nRequire Import Maps.\nRequire Archi.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Export Memdata.\nRequire Export Memtype.\nRequire Import sflib.\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\" := (PMap.get b a) (at level 1).\n\nModule Mem <: MEM.\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: PMap.t (ZMap.t memval);  (**r [block -> offset -> memval] *)\n  mem_access: PMap.t (Z -> perm_kind -> option permission);\n                                         (**r [block -> offset -> kind -> option permission] *)\n  nextblock: block;\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, ~(Plt b nextblock) -> mem_access#b ofs k = None;\n  contents_default:\n    forall b, fst mem_contents#b = Undef\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) := Plt 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\nLocal Hint 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\nLocal Hint 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\nLocal Hint 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 (plt 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\nLocal Hint 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\nLocal Hint 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\nLocal Hint 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\nLocal Hint 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 Z.divide_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).\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 Z.divide_1_l.\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 (PMap.init (ZMap.init Undef))\n        (PMap.init (fun ofs k => None))\n        2%positive _ _ _.\nNext Obligation.\n  repeat rewrite PMap.gi. red; auto.\nQed.\nNext Obligation.\n  rewrite PMap.gi. auto.\nQed.\nNext Obligation.\n  rewrite PMap.gi. auto.\nQed.\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 (PMap.set m.(nextblock)\n                   (ZMap.init Undef)\n                   m.(mem_contents))\n         (PMap.set m.(nextblock)\n                   (fun ofs k => if zle lo ofs && zlt ofs hi then Some Freeable else None)\n                   m.(mem_access))\n         (Pos.succ m.(nextblock))\n         _ _ _,\n   m.(nextblock)).\nNext Obligation.\n  repeat rewrite PMap.gsspec. destruct (peq 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 PMap.gsspec. destruct (peq b (nextblock m)).\n  subst b. elim H. apply Plt_succ.\n  apply nextblock_noaccess. red; intros; elim H.\n  apply Plt_trans_succ; auto.\nQed.\nNext Obligation.\n  rewrite PMap.gsspec. destruct (peq b (nextblock m)). auto. apply contents_default.\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        (PMap.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  repeat rewrite PMap.gsspec. destruct (peq 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 PMap.gsspec. destruct (peq b0 b). subst.\n  destruct (zle lo ofs && zlt ofs hi). auto. apply nextblock_noaccess; auto.\n  apply nextblock_noaccess; auto.\nQed.\nNext Obligation.\n  apply contents_default.\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' => ZMap.get p c :: 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 (Ptrofs.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 (Z.to_nat 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  ZMap.get q (setN vl p c) = ZMap.get q c.\nProof.\n  induction vl; intros; simpl.\n  auto.\n  simpl length in H. rewrite Nat2Z.inj_succ in H.\n  transitivity (ZMap.get q (ZMap.set p a c)).\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  ZMap.get q (setN vl p c) = ZMap.get q c.\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 -> ZMap.get i c1 = ZMap.get i c2) ->\n  getN n p c1 = getN n p c2.\nProof.\n  induction n; intros. auto. rewrite Nat2Z.inj_succ in H. simpl. decEq.\n  apply H. omega. apply IHn. intros. apply H. omega.\nQed.\n\nRemark getN_setN_disjoint:\n  forall vl q c n p,\n  Intv.disjoint (p, p + Z.of_nat n) (q, q + Z.of_nat (length vl)) ->\n  getN n p (setN vl q c) = getN n p c.\nProof.\n  intros. apply getN_exten. intros. apply setN_other.\n  intros; red; intros; subst r. eelim H; eauto.\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_setN_disjoint. apply Intv.disjoint_range. auto.\nQed.\n\nRemark setN_default:\n  forall vl q c, fst (setN vl q c) = fst c.\nProof.\n  induction vl; simpl; intros. auto. rewrite IHvl. auto.\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\nProgram Definition 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 (PMap.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                _ _ _)\n  else\n    None.\nNext Obligation. apply access_max. Qed.\nNext Obligation. apply nextblock_noaccess; auto. Qed.\nNext Obligation.\n  rewrite PMap.gsspec. destruct (peq b0 b).\n  rewrite setN_default. apply contents_default.\n  apply contents_default.\nQed.\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 (Ptrofs.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\nProgram Definition 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             (PMap.set b (setN bytes ofs (m.(mem_contents)#b)) m.(mem_contents))\n             m.(mem_access)\n             m.(nextblock)\n             _ _ _)\n  else\n    None.\nNext Obligation. apply access_max. Qed.\nNext Obligation. apply nextblock_noaccess; auto. Qed.\nNext Obligation.\n  rewrite PMap.gsspec. destruct (peq b0 b).\n  rewrite setN_default. apply contents_default.\n  apply contents_default.\nQed.\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                (PMap.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  repeat rewrite PMap.gsspec. destruct (peq 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 PMap.gsspec. destruct (peq 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.\nNext Obligation.\n  apply contents_default.\nQed.\n\n(** * Properties of the memory operations *)\n\n(** Properties of the empty store. *)\n\nTheorem nextblock_empty: nextblock empty = 2%positive.\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 PMap.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\nLocal Hint 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  | _ => 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\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 = Z.to_nat 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 Z_to_nat_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 Nat2Z.inj_succ. simpl. decEq.\n  replace (p + Z.succ (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 Z2Nat.inj_add by omega.\n  rewrite getN_concat. rewrite Z2Nat.id by omega.\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 Z2Nat.inj_add in H by omega. rewrite getN_concat in H.\n  rewrite Z2Nat.id in H by omega.\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 -> ZMap.get (ofs + z) m1.(mem_contents)#b = ZMap.get (ofs + z) m2.(mem_contents)#b) ->\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 Nat2Z.inj_succ in H.\n  replace ofs with (ofs+0) by omega.\n  apply H; omega.\n  apply IHn.\n  intros.\n  rewrite <- Z.add_assoc.\n  apply H.\n  rewrite Nat2Z.inj_succ. omega.\nQed.\n\nTheorem load_int64_split:\n  forall m b ofs v,\n  load Mint64 m b ofs = Some v -> Archi.ptr64 = false ->\n  exists v1 v2,\n     load Mint32 m b ofs = Some (if Archi.big_endian then v1 else v2)\n  /\\ load Mint32 m b (ofs + 4) = Some (if Archi.big_endian then v2 else v1)\n  /\\ Val.lessdef v (Val.longofwords v1 v2).\nProof.\n  intros.\n  exploit load_valid_access; eauto. intros [A B]. simpl in *.\n  exploit load_loadbytes. eexact H. simpl. intros [bytes [LB EQ]].\n  change 8 with (4 + 4) in LB.\n  exploit loadbytes_split. eexact LB. omega. omega.\n  intros (bytes1 & bytes2 & LB1 & LB2 & APP).\n  change 4 with (size_chunk Mint32) in LB1.\n  exploit loadbytes_load. eexact LB1.\n  simpl. apply Z.divide_trans with 8; auto. exists 2; auto.\n  intros L1.\n  change 4 with (size_chunk Mint32) in LB2.\n  exploit loadbytes_load. eexact LB2.\n  simpl. apply Z.divide_add_r. apply Z.divide_trans with 8; auto. exists 2; auto. exists 1; auto.\n  intros L2.\n  exists (decode_val Mint32 (if Archi.big_endian then bytes1 else bytes2));\n  exists (decode_val Mint32 (if Archi.big_endian then bytes2 else bytes1)).\n  split. destruct Archi.big_endian; auto.\n  split. destruct Archi.big_endian; auto.\n  rewrite EQ. rewrite APP. apply decode_val_int64; auto.\n  erewrite loadbytes_length; eauto. reflexivity.\n  erewrite loadbytes_length; eauto. reflexivity.\nQed.\n\nLemma addressing_int64_split:\n  forall i,\n  Archi.ptr64 = false ->\n  (8 | Ptrofs.unsigned i) ->\n  Ptrofs.unsigned (Ptrofs.add i (Ptrofs.of_int (Int.repr 4))) = Ptrofs.unsigned i + 4.\nProof.\n  intros.\n  rewrite Ptrofs.add_unsigned.\n  replace (Ptrofs.unsigned (Ptrofs.of_int (Int.repr 4))) with (Int.unsigned (Int.repr 4))\n    by (symmetry; apply Ptrofs.agree32_of_int; auto).\n  change (Int.unsigned (Int.repr 4)) with 4.\n  apply Ptrofs.unsigned_repr.\n  exploit (Zdivide_interval (Ptrofs.unsigned i) Ptrofs.modulus 8).\n  omega. apply Ptrofs.unsigned_range. auto.\n  exists (two_p (Ptrofs.zwordsize - 3)).\n  unfold Ptrofs.modulus, Ptrofs.zwordsize, Ptrofs.wordsize.\n  unfold Wordsize_Ptrofs.wordsize. destruct Archi.ptr64; reflexivity.\n  unfold Ptrofs.max_unsigned. omega.\nQed.\n\nTheorem loadv_int64_split:\n  forall m a v,\n  loadv Mint64 m a = Some v -> Archi.ptr64 = false ->\n  exists v1 v2,\n     loadv Mint32 m a = Some (if Archi.big_endian then v1 else v2)\n  /\\ loadv Mint32 m (Val.add a (Vint (Int.repr 4))) = Some (if Archi.big_endian then v2 else v1)\n  /\\ Val.lessdef v (Val.longofwords v1 v2).\nProof.\n  intros. destruct a; simpl in H; inv H.\n  exploit load_int64_split; eauto. intros (v1 & v2 & L1 & L2 & EQ).\n  unfold Val.add; rewrite H0.\n  assert (NV: Ptrofs.unsigned (Ptrofs.add i (Ptrofs.of_int (Int.repr 4))) = Ptrofs.unsigned i + 4).\n  { apply addressing_int64_split; auto.\n    exploit load_valid_access. eexact H2. intros [P Q]. auto. }\n  exists v1, v2.\nOpaque Ptrofs.repr.\n  split. auto.\n  split. simpl. rewrite NV. auto.\n  auto.\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\nLocal Hint 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 = PMap.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 PMap.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 Nat2Z.inj; 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 PMap.gsspec. destruct (peq 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 PMap.gss.\n  replace (Z.to_nat (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 PMap.gsspec. destruct (peq b' b). subst b'.\n  destruct H. congruence.\n  destruct (zle n 0) as [z | n0].\n  rewrite (Z_to_nat_neg _ z). auto.\n  destruct H. omegaContradiction.\n  apply getN_setN_outside. rewrite encode_val_length. rewrite <- size_chunk_conv.\n  rewrite Z2Nat.id. 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_in:\n  forall vl p q c,\n  p <= q < p + Z.of_nat (length vl) ->\n  In (ZMap.get q (setN vl p c)) vl.\nProof.\n  induction vl; intros.\n  simpl in H. omegaContradiction.\n  simpl length in H. rewrite Nat2Z.inj_succ in H. simpl.\n  destruct (zeq p q). subst q. rewrite setN_outside. rewrite ZMap.gss.\n  auto with coqlib. omega.\n  right. apply IHvl. omega.\nQed.\n\nLemma getN_in:\n  forall c q n p,\n  p <= q < p + Z.of_nat n ->\n  In (ZMap.get q c) (getN n p c).\nProof.\n  induction n; intros.\n  simpl in H; omegaContradiction.\n  rewrite Nat2Z.inj_succ in H. simpl. destruct (zeq p q).\n  subst q. auto.\n  right. apply IHn. omega.\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\nLemma load_store_overlap:\n  forall chunk m1 b ofs v m2 chunk' ofs' v',\n  store chunk m1 b ofs v = Some m2 ->\n  load chunk' m2 b ofs' = Some v' ->\n  ofs' + size_chunk chunk' > ofs ->\n  ofs + size_chunk chunk > ofs' ->\n  exists mv1 mvl mv1' mvl',\n      shape_encoding chunk v (mv1 :: mvl)\n  /\\  shape_decoding chunk' (mv1' :: mvl') v'\n  /\\  (   (ofs' = ofs /\\ mv1' = mv1)\n       \\/ (ofs' > ofs /\\ In mv1' mvl)\n       \\/ (ofs' < ofs /\\ In mv1 mvl')).\nProof.\n  intros.\n  exploit load_result; eauto. erewrite store_mem_contents by eauto; simpl.\n  rewrite PMap.gss.\n  set (c := (mem_contents m1)#b). intros V'.\n  destruct (size_chunk_nat_pos chunk) as [sz SIZE].\n  destruct (size_chunk_nat_pos chunk') as [sz' SIZE'].\n  destruct (encode_val chunk v) as [ | mv1 mvl] eqn:ENC.\n  generalize (encode_val_length chunk v); rewrite ENC; simpl; congruence.\n  set (c' := setN (mv1::mvl) ofs c) in *.\n  exists mv1, mvl, (ZMap.get ofs' c'), (getN sz' (ofs' + 1) c').\n  split. rewrite <- ENC. apply encode_val_shape.\n  split. rewrite V', SIZE'. apply decode_val_shape.\n  destruct (zeq ofs' ofs).\n- subst ofs'. left; split. auto. unfold c'. simpl.\n  rewrite setN_outside by omega. apply ZMap.gss.\n- right. destruct (zlt ofs ofs').\n(* If ofs < ofs':  the load reads (at ofs') a continuation byte from the write.\n       ofs   ofs'   ofs+|chunk|\n        [-------------------]       write\n             [-------------------]  read\n*)\n+ left; split. omega. unfold c'. simpl. apply setN_in.\n  assert (Z.of_nat (length (mv1 :: mvl)) = size_chunk chunk).\n  { rewrite <- ENC; rewrite encode_val_length. rewrite size_chunk_conv; auto. }\n  simpl length in H3. rewrite Nat2Z.inj_succ in H3. omega.\n(* If ofs > ofs':  the load reads (at ofs) the first byte from the write.\n       ofs'   ofs   ofs'+|chunk'|\n               [-------------------]  write\n         [----------------]           read\n*)\n+ right; split. omega. replace mv1 with (ZMap.get ofs c').\n  apply getN_in.\n  assert (size_chunk chunk' = Z.succ (Z.of_nat sz')).\n  { rewrite size_chunk_conv. rewrite SIZE'. rewrite Nat2Z.inj_succ; auto. }\n  omega.\n  unfold c'. simpl. rewrite setN_outside by omega. apply ZMap.gss.\nQed.\n\nDefinition compat_pointer_chunks (chunk1 chunk2: memory_chunk) : Prop :=\n  match chunk1, chunk2 with\n  | (Mint32 | Many32), (Mint32 | Many32) => True\n  | (Mint64 | Many64), (Mint64 | Many64) => True\n  | _, _ => False\n  end.\n\nLemma compat_pointer_chunks_true:\n  forall chunk1 chunk2,\n  (chunk1 = Mint32 \\/ chunk1 = Many32 \\/ chunk1 = Mint64 \\/ chunk1 = Many64) ->\n  (chunk2 = Mint32 \\/ chunk2 = Many32 \\/ chunk2 = Mint64 \\/ chunk2 = Many64) ->\n  quantity_chunk chunk1 = quantity_chunk chunk2 ->\n  compat_pointer_chunks chunk1 chunk2.\nProof.\n  intros. destruct H as [P|[P|[P|P]]]; destruct H0 as [Q|[Q|[Q|Q]]];\n  subst; red; auto; discriminate.\nQed.\n\nTheorem load_pointer_store:\n  forall chunk m1 b ofs v m2 chunk' b' ofs' v_b v_o,\n  store chunk m1 b ofs v = Some m2 ->\n  load chunk' m2 b' ofs' = Some(Vptr v_b v_o) ->\n  (v = Vptr v_b v_o /\\ compat_pointer_chunks chunk chunk' /\\ b' = b /\\ ofs' = ofs)\n  \\/ (b' <> b \\/ ofs' + size_chunk chunk' <= ofs \\/ ofs + size_chunk chunk <= ofs').\nProof.\n  intros.\n  destruct (peq b' b); auto. subst b'.\n  destruct (zle (ofs' + size_chunk chunk') ofs); auto.\n  destruct (zle (ofs + size_chunk chunk) ofs'); auto.\n  exploit load_store_overlap; eauto.\n  intros (mv1 & mvl & mv1' & mvl' & ENC & DEC & CASES).\n  inv DEC; try contradiction.\n  destruct CASES as [(A & B) | [(A & B) | (A & B)]].\n- (* Same offset *)\n  subst. inv ENC.\n  assert (chunk = Mint32 \\/ chunk = Many32 \\/ chunk = Mint64 \\/ chunk = Many64)\n  by (destruct chunk; auto || contradiction).\n  left; split. rewrite H3.\n  destruct H4 as [P|[P|[P|P]]]; subst chunk'; destruct v0; simpl in H3;\n  try congruence; destruct Archi.ptr64; congruence.\n  split. apply compat_pointer_chunks_true; auto.\n  auto.\n- (* ofs' > ofs *)\n  inv ENC.\n  + exploit H10; eauto. intros (j & P & Q). inv P. congruence.\n  + exploit H8; eauto. intros (n & P); congruence.\n  + exploit H2; eauto. congruence.\n- (* ofs' < ofs *)\n  exploit H7; eauto. intros (j & P & Q). subst mv1. inv ENC. congruence.\nQed.\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 load_store_overlap; eauto.\n  intros (mv1 & mvl & mv1' & mvl' & ENC & DEC & CASES).\n  destruct CASES as [(A & B) | [(A & B) | (A & B)]].\n- congruence.\n- inv ENC.\n  + exploit H9; eauto. intros (j & P & Q). subst mv1'. inv DEC. congruence. auto.\n  + contradiction.\n  + exploit H5; eauto. intros; subst. inv DEC; auto.\n- inv DEC.\n  + exploit H10; eauto. intros (j & P & Q). subst mv1. inv ENC. congruence.\n  + exploit H8; eauto. intros (n & P). subst mv1. inv ENC. contradiction.\n  + auto.\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  ~compat_pointer_chunks chunk chunk' ->\n  v = Vundef.\nProof.\n  intros.\n  exploit load_store_overlap; eauto.\n  generalize (size_chunk_pos chunk'); omega.\n  generalize (size_chunk_pos chunk); omega.\n  intros (mv1 & mvl & mv1' & mvl' & ENC & DEC & CASES).\n  destruct CASES as [(A & B) | [(A & B) | (A & B)]]; try omegaContradiction.\n  inv ENC; inv DEC; auto.\n- elim H1. apply compat_pointer_chunks_true; auto.\n- contradiction.\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  destruct (valid_access_dec m chunk2 b ofs Writable); auto.\n  f_equal. apply mkmem_ext; auto. congruence.\n  elim n. apply valid_access_compat with chunk1; auto. omega.\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\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  destruct (valid_access_dec m Mfloat64al32 b ofs Writable).\n  rewrite <- H. f_equal. apply mkmem_ext; auto.\n  elim 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\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. unfold storebytes.\n  destruct (range_perm_dec m1 b ofs (ofs + Z.of_nat (length bytes)) Cur Writable).\n  econstructor; 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  f_equal. apply mkmem_ext; 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  f_equal. apply mkmem_ext; 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 = PMap.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. assert (STORE2:=STORE). unfold storebytes in STORE2. 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 STORE2; simpl. rewrite PMap.gss. rewrite Nat2Z.id.\n  apply getN_setN_same.\n  red; eauto with mem.\nQed.\n\nTheorem loadbytes_storebytes_disjoint:\n  forall b' ofs' len,\n  len >= 0 ->\n  b' <> b \\/ Intv.disjoint (ofs', ofs' + len) (ofs, ofs + Z.of_nat (length bytes)) ->\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 PMap.gsspec. destruct (peq b' b). subst b'.\n  apply getN_setN_disjoint. rewrite Z2Nat.id by omega. 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 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. apply loadbytes_storebytes_disjoint; auto.\n  destruct H0; auto. right. apply Intv.disjoint_range; auto.\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 PMap.gsspec. destruct (peq 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 Nat2Z.inj_succ. 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 PMap.gss.  rewrite setN_concat. symmetry. apply PMap.set2.\n  elim n.\n  rewrite app_length. rewrite Nat2Z.inj_add. 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 Nat2Z.inj_add. 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 Nat2Z.inj_add. 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\nTheorem store_int64_split:\n  forall m b ofs v m',\n  store Mint64 m b ofs v = Some m' -> Archi.ptr64 = false ->\n  exists m1,\n     store Mint32 m b ofs (if Archi.big_endian then Val.hiword v else Val.loword v) = Some m1\n  /\\ store Mint32 m1 b (ofs + 4) (if Archi.big_endian then Val.loword v else Val.hiword v) = Some m'.\nProof.\n  intros.\n  exploit store_valid_access_3; eauto. intros [A B]. simpl in *.\n  exploit store_storebytes. eexact H. intros SB.\n  rewrite encode_val_int64 in SB by auto.\n  exploit storebytes_split. eexact SB. intros [m1 [SB1 SB2]].\n  rewrite encode_val_length in SB2. simpl in SB2.\n  exists m1; split.\n  apply storebytes_store. exact SB1.\n  simpl. apply Z.divide_trans with 8; auto. exists 2; auto.\n  apply storebytes_store. exact SB2.\n  simpl. apply Z.divide_add_r. apply Z.divide_trans with 8; auto. exists 2; auto. exists 1; auto.\nQed.\n\nTheorem storev_int64_split:\n  forall m a v m',\n  storev Mint64 m a v = Some m' -> Archi.ptr64 = false ->\n  exists m1,\n     storev Mint32 m a (if Archi.big_endian then Val.hiword v else Val.loword v) = Some m1\n  /\\ storev Mint32 m1 (Val.add a (Vint (Int.repr 4))) (if Archi.big_endian then Val.loword v else Val.hiword v) = Some m'.\nProof.\n  intros. destruct a; simpl in H; inv H. rewrite H2.\n  exploit store_int64_split; eauto. intros [m1 [A B]].\n  exists m1; split.\n  exact A.\n  unfold storev, Val.add. rewrite H0.\n  rewrite addressing_int64_split; auto.\n  exploit store_valid_access_3. eexact H2. intros [P Q]. exact Q.\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 = Pos.succ (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.\n  apply Plt_trans_succ; auto.\nQed.\n\nTheorem fresh_block_alloc:\n  ~(valid_block m1 b).\nProof.\n  unfold valid_block. rewrite alloc_result. apply Plt_strict.\nQed.\n\nTheorem valid_new_block:\n  valid_block m2 b.\nProof.\n  unfold valid_block. rewrite alloc_result. rewrite nextblock_alloc. apply Plt_succ.\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  exploit Plt_succ_inv; eauto. tauto.\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 PMap.gsspec. destruct (peq b' (nextblock m1)); auto.\n  rewrite nextblock_noaccess in H. contradiction. subst b'. apply Plt_strict.\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 PMap.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 eq_block 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 PMap.gsspec. unfold eq_block. destruct (peq 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 dec_eq_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 dec_eq_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  destruct (eq_block 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 dec_eq_true. intro.\n  exploit perm_alloc_inv. eexact H3. rewrite dec_eq_true. intro.\n  intuition omega.\n  split; auto. red; intros.\n  exploit perm_alloc_inv. apply H0. eauto. rewrite dec_eq_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 PMap.gso. auto. rewrite H1. apply not_eq_sym; 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 PMap.gss. destruct (size_chunk_nat_pos chunk) as [n E]. rewrite E. simpl.\n  rewrite ZMap.gi. apply decode_val_undef.\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\nTheorem loadbytes_alloc_unchanged:\n  forall b' ofs n,\n  valid_block m1 b' ->\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  injection ALLOC; intros A B. rewrite <- B; simpl.\n  rewrite PMap.gso. auto. rewrite A. eauto with mem.\n  red; intros. eapply perm_alloc_1; eauto.\n  rewrite pred_dec_false; auto.\n  red; intros; elim n0. red; intros. eapply perm_alloc_4; eauto. eauto with mem.\nQed.\n\nTheorem loadbytes_alloc_same:\n  forall n ofs bytes byte,\n  loadbytes m2 b ofs n = Some bytes ->\n  In byte bytes -> byte = Undef.\nProof.\n  unfold loadbytes; intros. destruct (range_perm_dec m2 b ofs (ofs + n) Cur Readable); inv H.\n  revert H0.\n  injection ALLOC; intros A B. rewrite <- A; rewrite <- B; simpl. rewrite PMap.gss.\n  generalize (Z.to_nat n) ofs. induction n0; simpl; intros.\n  contradiction.\n  rewrite ZMap.gi in H0. destruct H0; 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 PMap.gsspec. destruct (peq 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 PMap.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 PMap.gsspec. destruct (peq 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 PMap.gsspec. destruct (peq 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 PMap.gsspec. destruct (peq 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\nTheorem load_free_2:\n  forall chunk b ofs v,\n  load chunk m2 b ofs = Some v -> load chunk m1 b ofs = Some v.\nProof.\n  intros. unfold load. rewrite pred_dec_true.\n  rewrite (load_result _ _ _ _ _ H). rewrite free_result; auto.\n  apply valid_access_free_inv_1. eauto with mem.\nQed.\n\nTheorem loadbytes_free:\n  forall b ofs n,\n  b <> bf \\/ lo >= hi \\/ ofs + n <= lo \\/ hi <= ofs ->\n  loadbytes m2 b ofs n = loadbytes m1 b ofs n.\nProof.\n  intros. unfold loadbytes.\n  destruct (range_perm_dec m2 b ofs (ofs + n) Cur Readable).\n  rewrite pred_dec_true.\n  rewrite free_result; auto.\n  red; intros. eapply perm_free_3; eauto.\n  rewrite pred_dec_false; auto.\n  red; intros. elim n0; red; intros.\n  eapply perm_free_1; eauto. destruct H; auto. right; omega.\nQed.\n\nTheorem loadbytes_free_2:\n  forall b ofs n bytes,\n  loadbytes m2 b ofs n = Some bytes -> loadbytes m1 b ofs n = Some bytes.\nProof.\n  intros. unfold loadbytes in *.\n  destruct (range_perm_dec m2 b ofs (ofs + n) Cur Readable); inv H.\n  rewrite pred_dec_true. rewrite free_result; auto.\n  red; intros. apply perm_free_3; auto.\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 PMap.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 PMap.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 PMap.gsspec. destruct (peq 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 PMap.gsspec. destruct (peq 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 (eq_block 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\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\nTheorem loadbytes_drop:\n  forall b' ofs n,\n  b' <> b \\/ ofs + n <= lo \\/ hi <= ofs \\/ perm_order p Readable ->\n  loadbytes m' b' ofs n = loadbytes m b' ofs n.\nProof.\n  intros.\n  unfold loadbytes.\n  destruct (range_perm_dec m b' ofs (ofs + n) Cur 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  red; intros.\n  destruct (eq_block 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. intuition.\n  eapply perm_drop_3; eauto.\n  rewrite pred_dec_false; eauto.\n  red; intros; elim n0; red; intros.\n  eapply perm_drop_4; 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_align:\n      forall b1 b2 delta chunk ofs p,\n      f b1 = Some(b2, delta) ->\n      range_perm m1 b1 ofs (ofs + size_chunk chunk) Max p ->\n      (align_chunk chunk | delta);\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 (ZMap.get ofs m1.(mem_contents)#b1) (ZMap.get (ofs+delta) m2.(mem_contents)#b2)\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\nLemma valid_access_inj:\n  forall f m1 m2 b1 b2 delta chunk ofs p,\n  mem_inj f m1 m2 ->\n  f b1 = Some(b2, delta) ->\n  valid_access m1 chunk b1 ofs p ->\n  valid_access m2 chunk b2 (ofs + delta) p.\nProof.\n  intros. destruct H1 as [A B]. constructor.\n  replace (ofs + delta + size_chunk chunk)\n     with ((ofs + size_chunk chunk) + delta) by omega.\n  eapply range_perm_inj; eauto.\n  apply Z.divide_add_r; auto. eapply mi_align; eauto with mem.\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 Nat2Z.inj_succ 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 valid_access_inj; 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 (Z.to_nat 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 Z2Nat.id by omega. auto.\n  rewrite Z_to_nat_neg by omega. simpl. red; intros; omegaContradiction.\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 (ZMap.get q c1) (ZMap.get (q + delta) c2)) ->\n  (forall q, access q -> memval_inject f (ZMap.get q (setN vl1 p c1))\n                                         (ZMap.get (q + delta) (setN vl2 (p + delta) c2))).\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 valid_access_inj; 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(* align *)\n  intros. eapply mi_align with (ofs := ofs0) (p := p); eauto.\n  red; intros; eauto with mem.\n(* mem_contents *)\n  intros.\n  rewrite (store_mem_contents _ _ _ _ _ _ H0).\n  rewrite (store_mem_contents _ _ _ _ _ _ STORE).\n  rewrite ! PMap.gsspec.\n  destruct (peq 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 peq_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 (peq 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(* align *)\n  intros. eapply mi_align with (ofs := ofs0) (p := p); eauto.\n  red; intros; eauto with mem.\n(* mem_contents *)\n  intros.\n  rewrite (store_mem_contents _ _ _ _ _ _ H0).\n  rewrite PMap.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  intros; eapply mi_align0; eauto.\n(* mem_contents *)\n  intros.\n  rewrite (store_mem_contents _ _ _ _ _ _ H1).\n  rewrite PMap.gsspec. destruct (peq 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(* align *)\n  intros. eapply mi_align with (ofs := ofs0) (p := p); eauto.\n  red; intros. eapply perm_storebytes_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  rewrite ! PMap.gsspec. destruct (peq 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 peq_true.\n  apply setN_inj with (access := fun ofs => perm m1 b1 ofs Cur Readable); auto.\n  destruct (peq 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(* align *)\n  intros. eapply mi_align with (ofs := ofs0) (p := p); eauto.\n  red; intros. eapply perm_storebytes_2; eauto.\n(* mem_contents *)\n  intros.\n  rewrite (storebytes_mem_contents _ _ _ _ _ H0).\n  rewrite PMap.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(* align *)\n  eauto.\n(* mem_contents *)\n  intros.\n  rewrite (storebytes_mem_contents _ _ _ _ _ H1).\n  rewrite PMap.gsspec. destruct (peq 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\nLemma storebytes_empty_inj:\n  forall f m1 b1 ofs1 m1' m2 b2 ofs2 m2',\n  mem_inj f m1 m2 ->\n  storebytes m1 b1 ofs1 nil = Some m1' ->\n  storebytes m2 b2 ofs2 nil = Some m2' ->\n  mem_inj f m1' m2'.\nProof.\n  intros. destruct H. constructor.\n(* perm *)\n  intros.\n  eapply perm_storebytes_1; eauto.\n  eapply mi_perm0; eauto.\n  eapply perm_storebytes_2; eauto.\n(* align *)\n  intros. eapply mi_align0 with (ofs := ofs) (p := p); eauto.\n  red; intros. eapply perm_storebytes_2; eauto.\n(* mem_contents *)\n  intros.\n  assert (perm m1 b0 ofs Cur Readable). eapply perm_storebytes_2; eauto.\n  rewrite (storebytes_mem_contents _ _ _ _ _ H0).\n  rewrite (storebytes_mem_contents _ _ _ _ _ H1).\n  simpl. rewrite ! PMap.gsspec.\n  destruct (peq b0 b1); destruct (peq b3 b2); subst; eapply mi_memval0; eauto.\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(* align *)\n  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 PMap.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 (eq_block b0 b1). congruence. eauto.\n(* align *)\n  intros. eapply mi_align0 with (ofs := ofs) (p := p); eauto.\n  red; intros. exploit perm_alloc_inv; eauto.\n  destruct (eq_block b0 b1); auto. congruence.\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 PMap.gsspec. unfold eq_block in H4. destruct (peq 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 (eq_block b0 b1). subst b0.\n  rewrite H4 in H5; inv H5. eauto. eauto.\n(* align *)\n  intros. destruct (eq_block b0 b1).\n  subst b0. assert (delta0 = delta) by congruence. subst delta0.\n  assert (lo <= ofs < hi).\n  { eapply perm_alloc_3; eauto. apply H6. generalize (size_chunk_pos chunk); omega. }\n  assert (lo <= ofs + size_chunk chunk - 1 < hi).\n  { eapply perm_alloc_3; eauto. apply H6. generalize (size_chunk_pos chunk); omega. }\n  apply H2. omega.\n  eapply mi_align0 with (ofs := ofs) (p := p); eauto.\n  red; intros. eapply perm_alloc_4; 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 PMap.gsspec. unfold eq_block in H7.\n  destruct (peq 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(* align *)\n  intros. eapply mi_align0 with (ofs := ofs) (p := p); eauto.\n  red; intros; eapply perm_free_3; eauto.\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 (eq_block 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(* align *)\n  eapply mi_align0; eauto.\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(* align *)\n  intros. eapply mi_align0 with (ofs := ofs) (p := p0); eauto.\n  red; intros; eapply perm_drop_4; eauto.\n(* contents *)\n  intros.\n  replace (ZMap.get ofs m1'.(mem_contents)#b1) with (ZMap.get ofs m1.(mem_contents)#b1).\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  constructor.\n(* perm *)\n  intros.\n  assert (perm m2 b3 (ofs + delta0) k p0).\n    eapply mi_perm0; eauto. eapply perm_drop_4; eauto.\n  destruct (eq_block 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 (eq_block 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  intuition.\n(* align *)\n  intros. eapply mi_align0 with (ofs := ofs) (p := p0); eauto.\n  red; intros; eapply perm_drop_4; eauto.\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. constructor.\n  (* perm *)\n  intros. eapply perm_drop_3; eauto.\n  destruct (eq_block b2 b); auto. subst b2. right.\n  destruct (zlt (ofs + delta) lo); auto.\n  destruct (zle hi (ofs + delta)); auto.\n  byContradiction. exploit H1; eauto. omega.\n  (* align *)\n  eapply mi_align0; eauto.\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    mext_perm_inv: forall b ofs k p,\n      perm m2 b ofs k p ->\n      perm m1 b ofs k p \\/ ~perm m1 b ofs Max Nonempty\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. apply Z.divide_0_r.\n  intros. unfold inject_id in H; inv H. replace (ofs + 0) with ofs by omega.\n  apply memval_lessdef_refl.\n  tauto.\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  constructor; auto.\n  rewrite (nextblock_store _ _ _ _ _ _ H0).\n  rewrite (nextblock_store _ _ _ _ _ _ A).\n  auto.\n  intros. exploit mext_perm_inv0; intuition eauto using perm_store_1, perm_store_2.\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.\n  intros. eauto using perm_store_2.\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  constructor; auto.\n  rewrite (nextblock_storebytes _ _ _ _ _ H0).\n  rewrite (nextblock_storebytes _ _ _ _ _ A).\n  auto.\n  intros. exploit mext_perm_inv0; intuition eauto using perm_storebytes_1, perm_storebytes_2.\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.\n  intros. eauto using perm_storebytes_2.\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 Z.divide_0_r.\n  intros.\n  eapply perm_implies with Freeable; auto with mem.\n  eapply perm_alloc_2; eauto.\n  omega.\n  intros. eapply perm_alloc_inv in H; eauto.\n  generalize (perm_alloc_inv _ _ _ _ _ H0 b0 ofs Max Nonempty); intros PERM.\n  destruct (eq_block b0 b).\n  subst b0.\n  assert (EITHER: lo1 <= ofs < hi1 \\/ ~(lo1 <= ofs < hi1)) by omega.\n  destruct EITHER.\n  left. apply perm_implies with Freeable; auto with mem. eapply perm_alloc_2; eauto.\n  right; tauto.\n  exploit mext_perm_inv0; intuition eauto using perm_alloc_1, perm_alloc_4.\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.\n  intros. exploit mext_perm_inv0; eauto. intros [A|A].\n  eapply perm_free_inv in A; eauto. destruct A as [[A B]|A]; auto.\n  subst b0. right; eapply perm_free_2; eauto.\n  intuition eauto using perm_free_3.\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.\n  intros. eauto using perm_free_3.\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  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 H1.\n  eapply perm_free_2. eexact H0. instantiate (1 := ofs); omega. eauto.\n  intros. exploit mext_perm_inv0; eauto using perm_free_3. intros [A|A].\n  eapply perm_free_inv in A; eauto. destruct A as [[A B]|A]; auto.\n  subst b0. right; eapply perm_free_2; eauto.\n  right; intuition eauto using perm_free_3.\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. tauto.\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 perm_extends_inv:\n  forall m1 m2 b ofs k p,\n  extends m1 m2 -> perm m2 b ofs k p -> perm m1 b ofs k p \\/ ~perm m1 b ofs Max Nonempty.\nProof.\n  intros. inv H; 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 valid_access_inj; 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      perm m1 b (Ptrofs.unsigned ofs) Max Nonempty \\/ perm m1 b (Ptrofs.unsigned ofs - 1) Max Nonempty ->\n      delta >= 0 /\\ 0 <= Ptrofs.unsigned ofs + delta <= Ptrofs.max_unsigned;\n    mi_perm_inv:\n      forall b1 ofs b2 delta k p,\n      f b1 = Some(b2, delta) ->\n      perm m2 b2 (ofs + delta) k p ->\n      perm m1 b1 ofs k p \\/ ~perm m1 b1 ofs Max Nonempty\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 (plt 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 perm_inject_inv:\n  forall f m1 m2 b1 ofs b2 delta k p,\n  inject f m1 m2 ->\n  f b1 = Some(b2, delta) ->\n  perm m2 b2 (ofs + delta) k p ->\n  perm m1 b1 ofs k p \\/ ~perm m1 b1 ofs Max Nonempty.\nProof.\n  intros. eapply mi_perm_inv; 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 valid_access_inj; 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\nLemma address_inject:\n  forall f m1 m2 b1 ofs1 b2 delta p,\n  inject f m1 m2 ->\n  perm m1 b1 (Ptrofs.unsigned ofs1) Cur p ->\n  f b1 = Some (b2, delta) ->\n  Ptrofs.unsigned (Ptrofs.add ofs1 (Ptrofs.repr delta)) = Ptrofs.unsigned ofs1 + delta.\nProof.\n  intros.\n  assert (perm m1 b1 (Ptrofs.unsigned ofs1) Max Nonempty) by eauto with mem.\n  exploit mi_representable; eauto. intros [A B].\n  assert (0 <= delta <= Ptrofs.max_unsigned).\n    generalize (Ptrofs.unsigned_range ofs1). omega.\n  unfold Ptrofs.add. repeat rewrite Ptrofs.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 (Ptrofs.unsigned ofs1) Nonempty ->\n  f b1 = Some (b2, delta) ->\n  Ptrofs.unsigned (Ptrofs.add ofs1 (Ptrofs.repr delta)) = Ptrofs.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 (Ptrofs.unsigned ofs) = true ->\n  f b = Some(b', delta) ->\n  0 <= Ptrofs.unsigned ofs + Ptrofs.unsigned (Ptrofs.repr delta) <= Ptrofs.max_unsigned.\nProof.\n  intros. rewrite weak_valid_pointer_spec in H0.\n  rewrite ! valid_pointer_nonempty_perm in H0.\n  exploit mi_representable; eauto. destruct H0; eauto with mem.\n  intros [A B].\n  pose proof (Ptrofs.unsigned_range ofs).\n  rewrite Ptrofs.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 (Ptrofs.unsigned ofs) = true ->\n  f b = Some(b', delta) ->\n  0 <= Ptrofs.unsigned ofs + Ptrofs.unsigned (Ptrofs.repr delta) <= Ptrofs.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 (Ptrofs.unsigned ofs) = true ->\n  Val.inject f (Vptr b ofs) (Vptr b' ofs') ->\n  valid_pointer m2 b' (Ptrofs.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 (Ptrofs.unsigned ofs) = true ->\n  Val.inject f (Vptr b ofs) (Vptr b' ofs') ->\n  weak_valid_pointer m2 b' (Ptrofs.unsigned ofs') = true.\nProof.\n  intros. inv H1.\n  exploit weak_valid_pointer_inject; eauto. intros W.\n  rewrite weak_valid_pointer_spec in H0.\n  rewrite ! valid_pointer_nonempty_perm in H0.\n  exploit mi_representable; eauto. destruct H0; eauto with mem.\n  intros [A B].\n  pose proof (Ptrofs.unsigned_range ofs).\n  unfold Ptrofs.add. repeat rewrite Ptrofs.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 (Ptrofs.unsigned ofs1) = true ->\n  valid_pointer m 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)) <>\n  Ptrofs.unsigned (Ptrofs.add ofs2 (Ptrofs.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 (Ptrofs.unsigned ofs1)). omega.\n  apply perm_cur_max. apply (H1 (Ptrofs.unsigned ofs2)). omega.\nQed.\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  intuition.\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: Z.abs al <= Z.abs sz). apply Zdivide_bounds; auto. omega.\n  rewrite Z.abs_eq in Q; try omega. rewrite Z.abs_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 Mint64; 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 (Ptrofs.unsigned (Ptrofs.add ofs1 (Ptrofs.repr delta)))\n     with (Ptrofs.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  destruct H4; eauto with mem.\n(* perm inv *)\n  intros. exploit mi_perm_inv0; eauto using perm_store_2.\n  intuition eauto using perm_store_1, perm_store_2.\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  destruct H3; eauto with mem.\n(* perm inv *)\n  intros. exploit mi_perm_inv0; eauto using perm_store_2.\n  intuition eauto using perm_store_1, perm_store_2.\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.\n(* perm inv *)\n  intros. eauto using perm_store_2.\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 (Ptrofs.unsigned (Ptrofs.add ofs1 (Ptrofs.repr delta)))\n    with (Ptrofs.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  destruct H4; eauto using perm_storebytes_2.\n(* perm inv *)\n  intros. exploit mi_perm_inv0; eauto using perm_storebytes_2.\n  intuition eauto using perm_storebytes_1, 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  destruct H3; eauto using perm_storebytes_2.\n(* perm inv *)\n  intros. exploit mi_perm_inv0; eauto.\n  intuition eauto using perm_storebytes_1, 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.\n(* perm inv *)\n  intros. eapply mi_perm_inv0; eauto using perm_storebytes_2.\nQed.\n\nTheorem storebytes_empty_inject:\n  forall f m1 b1 ofs1 m1' m2 b2 ofs2 m2',\n  inject f m1 m2 ->\n  storebytes m1 b1 ofs1 nil = Some m1' ->\n  storebytes m2 b2 ofs2 nil = Some m2' ->\n  inject f m1' m2'.\nProof.\n  intros. inversion H. constructor; intros.\n(* inj *)\n  eapply storebytes_empty_inj; eauto.\n(* freeblocks *)\n  intros. apply mi_freeblocks0. red; intros; elim H2; 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  destruct H3; eauto using perm_storebytes_2.\n(* perm inv *)\n  intros. exploit mi_perm_inv0; eauto using perm_storebytes_2.\n  intuition eauto using perm_storebytes_1, perm_storebytes_2.\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.\n(* perm inv *)\n  intros. eapply perm_alloc_inv in H2; eauto. destruct (eq_block b0 b2).\n  subst b0. eelim fresh_block_alloc; eauto.\n  eapply mi_perm_inv0; eauto.\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 eq_block b b1 then None else f b).\n  assert (inject_incr f f').\n    red; unfold f'; intros. destruct (eq_block 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 (eq_block b0 b1). congruence. eauto.\n    unfold f'; intros. destruct (eq_block b0 b1). congruence. eauto.\n    unfold f'; intros. destruct (eq_block 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 dec_eq_true.\n(* freeblocks *)\n  intros. unfold f'. destruct (eq_block b b1). auto.\n  apply mi_freeblocks0. red; intro; elim H3. eauto with mem.\n(* mappedblocks *)\n  unfold f'; intros. destruct (eq_block b b1). congruence. eauto.\n(* no overlap *)\n  unfold f'; red; intros.\n  destruct (eq_block b0 b1); destruct (eq_block b2 b1); try congruence.\n  eapply mi_no_overlap0. eexact H3. eauto. eauto.\n  exploit perm_alloc_inv. eauto. eexact H6. rewrite dec_eq_false; auto.\n  exploit perm_alloc_inv. eauto. eexact H7. rewrite dec_eq_false; auto.\n(* representable *)\n  unfold f'; intros.\n  destruct (eq_block b b1); try discriminate.\n  eapply mi_representable0; try eassumption.\n  destruct H4; eauto using perm_alloc_4.\n(* perm inv *)\n  intros. unfold f' in H3; destruct (eq_block b0 b1); try discriminate.\n  exploit mi_perm_inv0; eauto.\n  intuition eauto using perm_alloc_1, perm_alloc_4.\n(* incr *)\n  split. auto.\n(* image *)\n  split. unfold f'; apply dec_eq_true.\n(* incr *)\n  intros; unfold f'; apply dec_eq_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 <= Ptrofs.max_unsigned ->\n  (forall ofs k p, perm m2 b2 ofs k p -> delta = 0 \\/ 0 <= ofs < Ptrofs.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 eq_block b b1 then Some(b2, delta) else f b).\n  assert (inject_incr f f').\n    red; unfold f'; intros. destruct (eq_block 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 (eq_block 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 (eq_block b0 b1).\n      inversion H8. subst b0 b3 delta0.\n      elim (fresh_block_alloc _ _ _ _ _ H0).\n      eapply perm_valid_block with (ofs := ofs). apply H9. generalize (size_chunk_pos chunk); omega.\n      eauto.\n    unfold f'; intros. destruct (eq_block 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 dec_eq_true.\n(* freeblocks *)\n  unfold f'; intros. destruct (eq_block b b1). subst b.\n  elim H9. eauto with mem.\n  eauto with mem.\n(* mappedblocks *)\n  unfold f'; intros. destruct (eq_block 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 (eq_block b0 b1); destruct (eq_block b3 b1).\n  congruence.\n  inversion H10; subst b0 b1' delta1.\n    destruct (eq_block b2 b2'); auto. subst b2'. right; red; intros.\n    eapply H6; eauto. omega.\n  inversion H11; subst b3 b2' delta2.\n    destruct (eq_block b1' b2); auto. subst b1'. right; red; intros.\n    eapply H6; eauto. omega.\n  eauto.\n(* representable *)\n  unfold f'; intros.\n  destruct (eq_block b b1).\n   subst. injection H9; intros; subst b' delta0. destruct H10.\n    exploit perm_alloc_inv; eauto; rewrite dec_eq_true; intro.\n    exploit H3. apply H4 with (k := Max) (p := Nonempty); eauto.\n    generalize (Ptrofs.unsigned_range_2 ofs). omega.\n   exploit perm_alloc_inv; eauto; rewrite dec_eq_true; intro.\n   exploit H3. apply H4 with (k := Max) (p := Nonempty); eauto.\n   generalize (Ptrofs.unsigned_range_2 ofs). omega.\n  eapply mi_representable0; try eassumption.\n  destruct H10; eauto using perm_alloc_4.\n(* perm inv *)\n  intros. unfold f' in H9; destruct (eq_block b0 b1).\n  inversion H9; clear H9; subst b0 b3 delta0.\n  assert (EITHER: lo <= ofs < hi \\/ ~(lo <= ofs < hi)) by omega.\n  destruct EITHER.\n  left. apply perm_implies with Freeable; auto with mem. eapply perm_alloc_2; eauto.\n  right; intros A. eapply perm_alloc_inv in A; eauto. rewrite dec_eq_true in A. tauto.\n  exploit mi_perm_inv0; eauto. intuition eauto using perm_alloc_1, perm_alloc_4.\n(* incr *)\n  split. auto.\n(* image of b1 *)\n  split. unfold f'; apply dec_eq_true.\n(* image of others *)\n  intros. unfold f'; apply dec_eq_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 Ptrofs.max_unsigned. generalize Ptrofs.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 Z.divide_0_r.\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  destruct H2; eauto with mem.\n(* perm inv *)\n  intros. exploit mi_perm_inv0; eauto. intuition eauto using perm_free_3.\n  eapply perm_free_inv in H4; eauto. destruct H4 as [[A B] | A]; auto.\n  subst b1. right; eapply perm_free_2; eauto.\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].\n  destruct (free m1 b lo hi) as [m11|] eqn:E; try discriminate.\n  apply IHl with m11; auto. eapply free_left_inject; eauto.\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.\n(* perm inv *)\n  intros. eauto using perm_free_3.\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; simpl; intros.\n  inv H. auto.\n  destruct a as [[b1 lo1] hi1].\n  destruct (free m b1 lo1 hi1) as [m1|] eqn:E; try discriminate.\n  exploit IHl; eauto. intros [A B].\n  split. eauto with mem.\n  intros. destruct H1. inv H1.\n  elim (perm_free_2 _ _ _ _ _ E 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\nTheorem free_parallel_inject:\n  forall f m1 m2 b lo hi m1' b' delta,\n  inject f m1 m2 ->\n  free m1 b lo hi = Some m1' ->\n  f b = Some(b', delta) ->\n  exists m2',\n     free m2 b' (lo + delta) (hi + delta) = Some m2'\n  /\\ inject f m1' m2'.\nProof.\n  intros.\n  destruct (range_perm_free m2 b' (lo + delta) (hi + delta)) as [m2' FREE].\n  eapply range_perm_inject; eauto. eapply free_range_perm; eauto.\n  exists m2'; split; auto.\n  eapply free_inject with (m1 := m1) (l := (b,lo,hi)::nil); eauto.\n  simpl; rewrite H0; auto.\n  intros. destruct (eq_block b1 b).\n  subst b1. rewrite H1 in H2; inv H2.\n  exists lo, hi; split; auto with coqlib. omega.\n  exploit mi_no_overlap. eexact H. eexact n. eauto. eauto.\n  eapply perm_max. eapply perm_implies. eauto. auto with mem.\n  instantiate (1 := ofs + delta0 - delta).\n  apply perm_cur_max. apply perm_implies with Freeable; auto with mem.\n  eapply free_range_perm; eauto. omega.\n  intros [A|A]. congruence. omega.\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.\n  intros. eapply mi_perm_inv0; eauto using perm_drop_4.\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  (* align *)\n  destruct (f b1) as [[b' delta'] |] eqn:?; try discriminate.\n  destruct (f' b') as [[b'' delta''] |] eqn:?; inv H.\n  apply Z.divide_add_r.\n  eapply mi_align0; eauto.\n  eapply mi_align1 with (ofs := ofs + delta') (p := p); eauto.\n  red; intros. replace ofs0 with ((ofs0 - delta') + delta') by omega.\n  eapply mi_perm0; eauto. apply H0. omega.\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  intuition 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' := Ptrofs.repr (Ptrofs.unsigned ofs + delta1)).\n  assert (Ptrofs.unsigned ofs' = Ptrofs.unsigned ofs + delta1).\n    unfold ofs'; apply Ptrofs.unsigned_repr. auto.\n  exploit mi_representable1. eauto. instantiate (1 := ofs').\n  rewrite H.\n  replace (Ptrofs.unsigned ofs + delta1 - 1) with\n    ((Ptrofs.unsigned ofs - 1) + delta1) by omega.\n  destruct H0; eauto using perm_inj.\n  rewrite H. omega.\n(* perm inv *)\n  intros.\n  destruct (f b1) as [[b' delta'] |] eqn:?; try discriminate.\n  destruct (f' b') as [[b'' delta''] |] eqn:?; try discriminate.\n  inversion H; clear H; subst b'' delta.\n  replace (ofs + (delta' + delta'')) with ((ofs + delta') + delta'') in H0 by omega.\n  exploit mi_perm_inv1; eauto. intros [A|A].\n  eapply mi_perm_inv0; eauto.\n  right; red; intros. elim A. eapply perm_inj; eauto.\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  destruct H1; eauto using perm_extends.\n(* perm inv *)\n  exploit mi_perm_inv0; eauto. intros [A|A].\n  eapply mext_perm_inv0; eauto.\n  right; red; intros; elim A. eapply perm_extends; eauto.\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.\n(* perm inv *)\n  exploit mext_perm_inv0; eauto. intros [A|A].\n  eapply mi_perm_inv0; eauto.\n  right; red; intros; elim A. eapply perm_inj; 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. inversion H; subst; 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.\n  (* perm inv *)\n  exploit mext_perm_inv1; eauto. intros [A|A].\n  eapply mext_perm_inv0; eauto.\n  right; red; intros; elim A. eapply perm_extends; eauto.\nQed.\n\n(** Injecting a memory into itself. *)\n\nDefinition flat_inj (thr: block) : meminj :=\n  fun (b: block) => if plt 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 (plt b1 thr); inversion H0; subst.\n  destruct (plt 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 pred_dec_false. auto.\n(* mappedblocks *)\n  unfold flat_inj, valid_block; intros.\n  destruct (plt 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 (plt b (nextblock m)); inv H0. generalize (Ptrofs.unsigned_range_2 ofs); omega.\n(* perm inv *)\n  unfold flat_inj; intros.\n  destruct (plt b1 (nextblock m)); inv H0.\n  rewrite Z.add_0_r in H1; auto.\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 (plt b1 thr); inv H.\n  replace (ofs + 0) with ofs by omega; auto.\n(* align *)\n  unfold flat_inj; intros. destruct (plt b1 thr); inv H. apply Z.divide_0_r.\n(* mem_contents *)\n  intros; simpl. rewrite ! PMap.gi. 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  Plt (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 Z.divide_0_r.\n  intros.\n  apply perm_implies with Freeable; auto with mem.\n  eapply perm_alloc_2; eauto. omega.\n  unfold flat_inj. apply pred_dec_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  Plt 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 pred_dec_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  Plt 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 pred_dec_true; eauto.\n  repeat rewrite Z.add_0_r. intros [m'' [A B]]. congruence.\nQed.\n\n(** * Invariance properties between two memory states *)\n\nSection UNCHANGED_ON.\n\nVariable P: block -> Z -> Prop.\n\nRecord unchanged_on (m_before m_after: mem) : Prop := mk_unchanged_on {\n  unchanged_on_nextblock:\n    Ple (nextblock m_before) (nextblock m_after);\n  unchanged_on_perm:\n    forall b ofs k p,\n    P b ofs -> valid_block m_before b ->\n    (perm m_before b ofs k p <-> perm m_after b ofs k p);\n  unchanged_on_contents:\n    forall b ofs,\n    P b ofs -> perm m_before b ofs Cur Readable ->\n    ZMap.get ofs (PMap.get b m_after.(mem_contents)) =\n    ZMap.get ofs (PMap.get b m_before.(mem_contents))\n}.\n\nLemma unchanged_on_refl:\n  forall m, unchanged_on m m.\nProof.\n  intros; constructor. apply Ple_refl. tauto. tauto.\nQed.\n\nLemma valid_block_unchanged_on:\n  forall m m' b,\n  unchanged_on m m' -> valid_block m b -> valid_block m' b.\nProof.\n  unfold valid_block; intros. apply unchanged_on_nextblock in H. xomega.\nQed.\n\nLemma perm_unchanged_on:\n  forall m m' b ofs k p,\n  unchanged_on m m' -> P b ofs ->\n  perm m b ofs k p -> perm m' b ofs k p.\nProof.\n  intros. destruct H. apply unchanged_on_perm0; auto. eapply perm_valid_block; eauto.\nQed.\n\nLemma perm_unchanged_on_2:\n  forall m m' b ofs k p,\n  unchanged_on m m' -> P b ofs -> valid_block m b ->\n  perm m' b ofs k p -> perm m b ofs k p.\nProof.\n  intros. destruct H. apply unchanged_on_perm0; auto.\nQed.\n\nLemma unchanged_on_trans:\n  forall m1 m2 m3, unchanged_on m1 m2 -> unchanged_on m2 m3 -> unchanged_on m1 m3.\nProof.\n  intros; constructor.\n- apply Ple_trans with (nextblock m2); apply unchanged_on_nextblock; auto.\n- intros. transitivity (perm m2 b ofs k p); apply unchanged_on_perm; auto.\n  eapply valid_block_unchanged_on; eauto.\n- intros. transitivity (ZMap.get ofs (mem_contents m2)#b); apply unchanged_on_contents; auto.\n  eapply perm_unchanged_on; eauto.\nQed.\n\nLemma loadbytes_unchanged_on_1:\n  forall m m' b ofs n,\n  unchanged_on m m' ->\n  valid_block m b ->\n  (forall i, ofs <= i < ofs + n -> P b i) ->\n  loadbytes m' b ofs n = loadbytes m b ofs n.\nProof.\n  intros.\n  destruct (zle n 0).\n+ erewrite ! loadbytes_empty by assumption. auto.\n+ unfold loadbytes. destruct H.\n  destruct (range_perm_dec m b ofs (ofs + n) Cur Readable).\n  rewrite pred_dec_true. f_equal.\n  apply getN_exten. intros. rewrite Z2Nat.id in H by omega.\n  apply unchanged_on_contents0; auto.\n  red; intros. apply unchanged_on_perm0; auto.\n  rewrite pred_dec_false. auto.\n  red; intros; elim n0; red; intros. apply <- unchanged_on_perm0; auto.\nQed.\n\nLemma loadbytes_unchanged_on:\n  forall m m' b ofs n bytes,\n  unchanged_on m m' ->\n  (forall i, ofs <= i < ofs + n -> P b i) ->\n  loadbytes m b ofs n = Some bytes ->\n  loadbytes m' b ofs n = Some bytes.\nProof.\n  intros.\n  destruct (zle n 0).\n+ erewrite loadbytes_empty in * by assumption. auto.\n+ rewrite <- H1. apply loadbytes_unchanged_on_1; auto.\n  exploit loadbytes_range_perm; eauto. instantiate (1 := ofs). omega.\n  intros. eauto with mem.\nQed.\n\nLemma load_unchanged_on_1:\n  forall m m' chunk b ofs,\n  unchanged_on m m' ->\n  valid_block m b ->\n  (forall i, ofs <= i < ofs + size_chunk chunk -> P b i) ->\n  load chunk m' b ofs = load chunk m b ofs.\nProof.\n  intros. unfold load. destruct (valid_access_dec m chunk b ofs Readable).\n  destruct v. rewrite pred_dec_true. f_equal. f_equal. apply getN_exten. intros.\n  rewrite <- size_chunk_conv in H4. eapply unchanged_on_contents; eauto.\n  split; auto. red; intros. eapply perm_unchanged_on; eauto.\n  rewrite pred_dec_false. auto.\n  red; intros [A B]; elim n; split; auto. red; intros; eapply perm_unchanged_on_2; eauto.\nQed.\n\nLemma load_unchanged_on:\n  forall m m' chunk b ofs v,\n  unchanged_on m m' ->\n  (forall i, ofs <= i < ofs + size_chunk chunk -> P b i) ->\n  load chunk m b ofs = Some v ->\n  load chunk m' b ofs = Some v.\nProof.\n  intros. rewrite <- H1. eapply load_unchanged_on_1; eauto with mem.\nQed.\n\nLemma store_unchanged_on:\n  forall chunk m b ofs v m',\n  store chunk m b ofs v = Some m' ->\n  (forall i, ofs <= i < ofs + size_chunk chunk -> ~ P b i) ->\n  unchanged_on m m'.\nProof.\n  intros; constructor; intros.\n- rewrite (nextblock_store _ _ _ _ _ _ H). apply Ple_refl.\n- split; intros; eauto with mem.\n- erewrite store_mem_contents; eauto. rewrite PMap.gsspec.\n  destruct (peq b0 b); auto. subst b0. apply setN_outside.\n  rewrite encode_val_length. rewrite <- size_chunk_conv.\n  destruct (zlt ofs0 ofs); auto.\n  destruct (zlt ofs0 (ofs + size_chunk chunk)); auto.\n  elim (H0 ofs0). omega. auto.\nQed.\n\nLemma storebytes_unchanged_on:\n  forall m b ofs bytes m',\n  storebytes m b ofs bytes = Some m' ->\n  (forall i, ofs <= i < ofs + Z.of_nat (length bytes) -> ~ P b i) ->\n  unchanged_on m m'.\nProof.\n  intros; constructor; intros.\n- rewrite (nextblock_storebytes _ _ _ _ _ H). apply Ple_refl.\n- split; intros. eapply perm_storebytes_1; eauto. eapply perm_storebytes_2; eauto.\n- erewrite storebytes_mem_contents; eauto. rewrite PMap.gsspec.\n  destruct (peq b0 b); auto. subst b0. apply setN_outside.\n  destruct (zlt ofs0 ofs); auto.\n  destruct (zlt ofs0 (ofs + Z.of_nat (length bytes))); auto.\n  elim (H0 ofs0). omega. auto.\nQed.\n\nLemma alloc_unchanged_on:\n  forall m lo hi m' b,\n  alloc m lo hi = (m', b) ->\n  unchanged_on m m'.\nProof.\n  intros; constructor; intros.\n- rewrite (nextblock_alloc _ _ _ _ _ H). apply Ple_succ.\n- split; intros.\n  eapply perm_alloc_1; eauto.\n  eapply perm_alloc_4; eauto.\n  eapply valid_not_valid_diff; eauto with mem.\n- injection H; intros A B. rewrite <- B; simpl.\n  rewrite PMap.gso; auto. rewrite A.  eapply valid_not_valid_diff; eauto with mem.\nQed.\n\nLemma free_unchanged_on:\n  forall m b lo hi m',\n  free m b lo hi = Some m' ->\n  (forall i, lo <= i < hi -> ~ P b i) ->\n  unchanged_on m m'.\nProof.\n  intros; constructor; intros.\n- rewrite (nextblock_free _ _ _ _ _ H). apply Ple_refl.\n- split; intros.\n  eapply perm_free_1; eauto.\n  destruct (eq_block b0 b); auto. destruct (zlt ofs lo); auto. destruct (zle hi ofs); auto.\n  subst b0. elim (H0 ofs). omega. auto.\n  eapply perm_free_3; eauto.\n- unfold free in H. destruct (range_perm_dec m b lo hi Cur Freeable); inv H.\n  simpl. auto.\nQed.\n\nLemma free_list_nextblock:\n  forall l m m',\n  free_list m l = Some m' -> nextblock m' = nextblock m.\nProof.\n  induction l; simpl; intros.\n  congruence.\n  destruct a. destruct p. destruct (Mem.free m b z0 z) as [m1|] eqn:?; try discriminate.\n  transitivity (Mem.nextblock m1). eauto. eapply Mem.nextblock_free; eauto.\nQed.\n\nLemma free_list_unchanged_on:\n  forall l m m',\n    free_list m l = Some m' ->\n    (forall b lo hi i, In (b, lo, hi) l -> lo <= i < hi -> ~ P b i) ->\n    unchanged_on m m'.\nProof.\n  induction l; i.\n  - inv H. eapply unchanged_on_refl.\n  - destruct a, p. inv H. des_ifs.\n    exploit free_unchanged_on; eauto. { i. eapply H0; eauto. left; ss. } i.\n    eapply unchanged_on_trans; eauto. eapply IHl; eauto.\n    i. eapply H0; try right; eauto.\nQed.\n\nLemma drop_perm_unchanged_on:\n  forall m b lo hi p m',\n  drop_perm m b lo hi p = Some m' ->\n  (forall i, lo <= i < hi -> ~ P b i) ->\n  unchanged_on m m'.\nProof.\n  intros; constructor; intros.\n- rewrite (nextblock_drop _ _ _ _ _ _ H). apply Ple_refl.\n- split; intros. eapply perm_drop_3; eauto.\n  destruct (eq_block b0 b); auto.\n  subst b0.\n  assert (~ (lo <= ofs < hi)). { red; intros; eelim H0; eauto. }\n  right; omega.\n  eapply perm_drop_4; eauto.\n- unfold drop_perm in H.\n  destruct (range_perm_dec m b lo hi Cur Freeable); inv H; simpl. auto.\nQed.\n\nEnd UNCHANGED_ON.\n\nLemma unchanged_on_implies:\n  forall (P Q: block -> Z -> Prop) m m',\n  unchanged_on P m m' ->\n  (forall b ofs, Q b ofs -> valid_block m b -> P b ofs) ->\n  unchanged_on Q m m'.\nProof.\n  intros. destruct H. constructor; intros.\n- auto.\n- apply unchanged_on_perm0; auto.\n- apply unchanged_on_contents0; auto.\n  apply H0; auto. eapply perm_valid_block; eauto.\nQed.\n\nEnd Mem.\n\nNotation mem := Mem.mem.\n\nGlobal Opaque Mem.alloc Mem.free Mem.store Mem.load Mem.storebytes Mem.loadbytes.\n\nHint Resolve\n  Mem.valid_not_valid_diff\n  Mem.perm_implies\n  Mem.perm_cur\n  Mem.perm_max\n  Mem.perm_valid_block\n  Mem.range_perm_implies\n  Mem.range_perm_cur\n  Mem.range_perm_max\n  Mem.valid_access_implies\n  Mem.valid_access_valid_block\n  Mem.valid_access_perm\n  Mem.valid_access_load\n  Mem.load_valid_access\n  Mem.loadbytes_range_perm\n  Mem.valid_access_store\n  Mem.perm_store_1\n  Mem.perm_store_2\n  Mem.nextblock_store\n  Mem.store_valid_block_1\n  Mem.store_valid_block_2\n  Mem.store_valid_access_1\n  Mem.store_valid_access_2\n  Mem.store_valid_access_3\n  Mem.storebytes_range_perm\n  Mem.perm_storebytes_1\n  Mem.perm_storebytes_2\n  Mem.storebytes_valid_access_1\n  Mem.storebytes_valid_access_2\n  Mem.nextblock_storebytes\n  Mem.storebytes_valid_block_1\n  Mem.storebytes_valid_block_2\n  Mem.nextblock_alloc\n  Mem.alloc_result\n  Mem.valid_block_alloc\n  Mem.fresh_block_alloc\n  Mem.valid_new_block\n  Mem.perm_alloc_1\n  Mem.perm_alloc_2\n  Mem.perm_alloc_3\n  Mem.perm_alloc_4\n  Mem.perm_alloc_inv\n  Mem.valid_access_alloc_other\n  Mem.valid_access_alloc_same\n  Mem.valid_access_alloc_inv\n  Mem.range_perm_free\n  Mem.free_range_perm\n  Mem.nextblock_free\n  Mem.valid_block_free_1\n  Mem.valid_block_free_2\n  Mem.perm_free_1\n  Mem.perm_free_2\n  Mem.perm_free_3\n  Mem.valid_access_free_1\n  Mem.valid_access_free_2\n  Mem.valid_access_free_inv_1\n  Mem.valid_access_free_inv_2\n  Mem.unchanged_on_refl\n: mem.\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/Memory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.2795817553764022}}
{"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 Lia.\nRequire Import EquivDec.\nRequire Import Morphisms.\nRequire Import Utils.\nRequire Import DataSystem.\nRequire Import OQLSystem.\nRequire Import NRAEnvSystem.\nRequire Import OQLtoNRAEnv.\n\nSection TOQLtoNRAEnv.\n  Context {m:basic_model}.\n\n    Lemma oql_to_nraenv_expr_type_preserve_f τconstant τdefls pfd τenv pfe e τout:\n      oql_expr_type (rec_concat_sort τconstant τdefls) τenv e τout ->\n      nraenv_type τconstant (oql_to_nraenv_expr (domain τdefls) e) (Rec Closed τdefls pfd) (Rec Closed τenv pfe) τout.\n    Proof.\n      unfold nraenv_type; simpl.\n      Hint Constructors nraenv_core_type : qcert.\n      revert τconstant τdefls pfd τenv pfe τout.\n      induction e; simpl; intros τconstant τdefls pfd τenv pfe τout ot; invcs ot; eauto 4 with qcert.\n      - unfold lookup_table.\n          unfold tdot, edot, rec_concat_sort in *.\n          rewrite assoc_lookupr_drec_sort in H1.\n          rewrite (assoc_lookupr_app τconstant τdefls _ ODT_eqdec) in H1.\n        match_destr; simpl; intros.\n        + econstructor; [ | qeauto].\n          apply in_dom_lookupr with (dec:=ODT_eqdec) in i.\n          destruct i as [? ?].\n          match_case_in H1; [intros ? eqq | intros eqq]; rewrite eqq in H1.\n          * invcs H1.\n            qeauto.\n          * congruence.\n        + constructor.\n          apply assoc_lookupr_nin_none with (dec:=ODT_eqdec) in n.\n          rewrite n in H1; trivial.\n    Qed.\n\n    Lemma oql_to_nraenv_query_program_type_preserve_f τconstant τdefls pfd τenv pfe oq τout:\n      oql_query_program_type τconstant τdefls τenv oq τout ->\n      nraenv_type τconstant (oql_to_nraenv_query_program (domain τdefls) oq) (Rec Closed τdefls pfd) (Rec Closed τenv pfe) τout.\n    Proof.\n      unfold nraenv_type; simpl.\n      Hint Constructors nraenv_core_type : qcert.\n      revert τdefls pfd τenv pfe τout.\n      induction oq; simpl; intros τdefls pfd τenv pfe τout ot; invcs ot.\n      - econstructor.\n        + econstructor; qeauto.\n          econstructor; qeauto.\n          apply oql_to_nraenv_expr_type_preserve_f; eauto.\n        + specialize (IHoq (rec_concat_sort τdefls ((s, τ₁) :: nil))).\n          assert (eqls:equivlist (s :: domain τdefls) (domain (rec_concat_sort τdefls ((s, τ₁) :: nil))))\n            by (rewrite rec_concat_sort_domain_app_commutatuve_equiv; simpl; reflexivity).\n          rewrite eqls.\n          apply IHoq; trivial.\n      - econstructor; qeauto.\n        rewrite <- domain_rremove; trivial.\n        auto.\n      - apply oql_to_nraenv_expr_type_preserve_f; trivial.\n        Unshelve.\n        solve[simpl; trivial].\n        solve[qeauto].\n        solve[apply is_sorted_rremove; trivial].\n    Qed.\n\n    Theorem oql_to_nraenv_type_preserve_f τconstant oq τout :\n      oql_type τconstant oq τout ->\n      forall τenv τdata,\n      nraenv_type τconstant (oql_to_nraenv oq) τenv τdata τout.\n    Proof.\n      intros ot τenv τdata.\n      unfold oql_to_nraenv, nraenv_type; simpl.\n      generalize (oql_to_nraenv_query_program_type_preserve_f τconstant nil sorted_rec_nil nil sorted_rec_nil oq τout ot); intros et.\n      simpl in et.\n      unfold nraenv_type in et.\n      econstructor; econstructor; try eassumption; repeat econstructor;\n        try apply sorted_rec_nil.\n    Qed.\n\n    (* TODO (backwards preservation)\n    Lemma oql_to_nraenv_expr_type_preserve_b τconstant τdefls pfd τenv pfe e τout:\n      nraenv_type τconstant (oql_to_nraenv_expr (domain τdefls) e) (Rec Closed τdefls pfd) (Rec Closed τenv pfe) τout ->\n      oql_expr_type (rec_concat_sort τconstant τdefls) τenv e τout.\n    Proof.\n      Hint Constructors oql_expr_type.\n      unfold nraenv_type; simpl.\n      revert τconstant τdefls pfd τenv pfe τout.\n      induction e; simpl; intros τconstant τdefls pfd τenv pfe τout ot; try nraenv_core_inverter; eauto 4.\n      - unfold lookup_table in *.\n        constructor.\n        unfold tdot, edot, rec_concat_sort.\n        rewrite assoc_lookupr_drec_sort.\n        rewrite (assoc_lookupr_app τconstant τdefls _ ODT_eqdec).\n        match_destr_in ot.\n        + invcs ot.\n          invcs H1.\n          invcs H5.\n          rtype_equalizer.\n          subst.\n          apply in_dom_lookupr with (dec:=ODT_eqdec) in i.\n          destruct i as [? ?].\n          rewrite H.\n          unfold tdot, edot in H0.\n          unfold equiv, complement in H0.\n          unfold not in H.\n          congruence.\n        + apply assoc_lookupr_nin_none with (dec:=ODT_eqdec) in n.\n          rewrite n.\n          invcs ot.\n          apply H0.\n      -\n    Qed.\n*)\n        \nEnd TOQLtoNRAEnv.\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/Translation/Typing/TOQLtoNRAEnv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.27958174944763725}}
{"text": "(** * XOR 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 XOR_RR_rule d (r1 r2:DWORDorBYTEReg d) v1 (v2:DWORDorBYTE d):\n  |-- basic (DWORDorBYTEregIs r1 v1 ** DWORDorBYTEregIs r2 v2 ** OSZCP?) (XOR r1, r2)\n            (DWORDorBYTEregIs r1 (xorB v1 v2) ** DWORDorBYTEregIs r2 v2 ** OSZCP false (msb (xorB v1 v2))\n                            (xorB v1 v2 == #0) false (lsb (xorB v1 v2))).\nProof. destruct d; do_instrrule_triple. Qed.\n\nLemma XOR_RM_rule (pd:DWORD) (r1 r2:Reg) v1 (v2:DWORD) (offset:nat) v :\n  xorB v1 v2 = v ->\n  |-- basic (r1~=v1 ** r2 ~= pd ** pd +# offset :-> v2 ** OSZCP?)\n            (XOR r1, [r2 + offset])\n            (r1~=v ** r2 ~= pd ** pd +# offset :-> v2 **\n             OSZCP false (msb v) (v == #0) false (lsb v)).\nProof. change (stateIs r1) with (@DWORDorBYTEregIs true r1). move => ?; subst. do_instrrule_triple. Qed.\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\nHint Unfold OSZCP stateIsAny : spred.\n\nCorollary XOR_RM_ruleNoFlags (pd:DWORD) (r1 r2:Reg) v1 (v2:DWORD) (offset:nat):\n  |-- basic (r1~=v1) (XOR r1, [r2 + offset]) (r1~=xorB v1 v2)\n             @ (r2 ~= pd ** pd +# offset :-> v2 ** OSZCP?).\nProof. autorewrite with push_at. basicapply (@XOR_RM_rule pd r1 r2 v1 v2 offset (xorB v1 v2) (refl_equal _)). 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/xor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442250928250374, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.27958174944763725}}
{"text": "Require Import Coqlib.\nRequire Import AST.\nRequire Import Globalenvs.\nRequire Import Integers.\nRequire Import Smallstep.\nRequire Import Events.\nRequire Import Asm.\nRequire Import ProofIrrelevance.\nRequire Import Values.\n\nRequire Import PeekLib.\nRequire Import PeekTactics.\nRequire Import PregTactics.\nRequire Import FindInstrLib.\nRequire Import SplitLib.\nRequire Import StepLib.\nRequire Import SameBlockLib.\nRequire Import AsmCallingConv.\nRequire Import AsmBits.\nRequire Import MemoryAxioms.\nRequire Import ProgPropDec.\n\nRequire Import NoPtr.\nRequire Import Zlen.\nRequire Import GlobalPerms.\n\n\n\n(* Maybe have 2 definitions *)\n(* One like current step_in/step_through *)\n(* where list is static code *)\n(* Other, list index is dynamic instruction trace *)\n(* prove lemmas about correspondence *)\n(* peephole facts will be in terms of static code *)\n(* static <-> dyn easy when straightline *)\n(* Try this out and see *)\n\n\n(* code c lives at offset z in entire code for function we're currently at i, within the code *)\nInductive at_code :  Z -> code -> Z -> genv -> state_bits -> Prop :=\n  | at_c :\n      forall rs m b i c c0 c1 fd bits ofs ge t,\n        rs PC = Vint bits ->\n        psur t bits = Some (b,i) ->\n        Int.unsigned i = (zlen c0) + ofs ->\n        0 <= ofs < zlen c ->\n        Genv.find_funct_ptr ge b = Some (Internal fd) ->\n        fn_code fd = c0 ++ c ++ c1 ->\n        at_code (zlen c0) c ofs ge (State_bits rs m t).\n\nInductive at_code_end : Z -> code -> genv -> state_bits -> Prop :=\n| at_end :\n    forall rs m b i c c0 c1 fd ge bits t,\n      rs PC = Vint bits ->\n      psur t bits = Some (b,i) ->\n      Int.unsigned i = (zlen c0) + (zlen c) ->\n      Genv.find_funct_ptr ge b = Some (Internal fd) ->\n      fn_code fd = c0 ++ c ++ c1 ->\n      at_code_end (zlen c0) c ge (State_bits rs m t).\n\nInductive at_code_start : Z -> code -> genv -> state_bits -> Prop :=\n| at_start :\n    forall rs m b i c c0 c1 fd ge bits t,\n      rs PC = Vint bits ->\n      psur t bits = Some (b,i) ->\n      Int.unsigned i = (zlen c0) ->\n      Genv.find_funct_ptr ge b = Some (Internal fd) ->\n      fn_code fd = c0 ++ c ++ c1 ->\n      at_code_start (zlen c0) c ge (State_bits rs m t).\n\nInductive in_code : Z -> code -> genv -> state_bits -> Prop :=\n| in_c :\n    forall z c ge st ofs,\n      ofs > 0 ->\n      at_code z c ofs ge st ->\n      in_code z c ge st.\n\nInductive star_step_in : Z -> code -> genv -> state_bits -> trace -> state_bits -> Prop :=\n| st_st_refl :\n    forall z c ge st,\n      in_code z c ge st ->\n      star_step_in z c ge st E0 st\n| st_st_left :\n    forall z c st st' st'' t t' ge,\n      star_step_in z c ge st'' t st' ->\n      in_code z c ge st ->\n      step_bits ge st t' st'' ->\n      star_step_in z c ge st (t' ** t) st'.\n\n(* Two cases: \n    + one step through the entire region\n    + step in, star step within, step to exit\n*)\nInductive step_through : Z -> code -> genv -> state_bits -> trace -> state_bits -> Prop :=\n| st_thru_single_step :\n    forall z c ge st t st',\n      at_code z c 0 ge st ->\n      step_bits ge st t st' ->\n      at_code_end z c ge st' ->\n      step_through z c ge st t st'\n| st_thru_mult_step :\n    forall z c ge stA stB stC stD t1 t2 t3,\n      at_code z c 0 ge stA ->\n      at_code_end z c ge stD ->\n      step_bits ge stA t1 stB ->\n      star_step_in z c ge stB t2 stC ->\n      step_bits ge stC t3 stD ->\n      step_through z c ge stA (t1 ** t2 ** t3) stD.\n      \nInductive step_t : code -> genv -> state_bits -> trace -> state_bits -> Prop :=\n| st_t_refl :\n    forall ge st,\n      step_t nil ge st E0 st\n| st_t_left :\n    forall st st' st'' ge i c t1 t2 z,\n      at_code z (i :: nil) 0 ge st ->\n      step_bits ge st t1 st' ->\n      step_t c ge st' t2 st'' ->\n      step_t (i :: c) ge st (t1 ** t2) st''.\n\nLemma at_code_not_nil :\n  forall z c n ge st,\n    at_code z c n ge st ->\n    c <> nil.\nProof.\n  intros. inversion H.\n  subst. destruct c. unfold zlen in H3. simpl in H3.\n  omega.\n  congruence.\nQed.\n\nInductive step_in : Z -> code -> genv -> state_bits -> trace -> state_bits -> Prop :=\n| st_in :\n    forall ge z c st t st',\n      in_code z c ge st ->\n      in_code z c ge st' ->\n      step_bits ge st t st' ->\n      step_in z c ge st t st'.\n\n\nLemma st_in_eq :\n  forall z c ge st t st',\n    star_step_in z c ge st t st' <->\n    (star (step_in z c) ge st t st' /\\ in_code z c ge st).\nProof.\n  split. induction 1; intros.\n  * split; eauto. econstructor; eauto.\n  * break_and. split; eauto.\n    econstructor; eauto. econstructor; eauto.\n  * intros. break_and. induction H.\n  - econstructor; eauto.\n  - subst. econstructor; eauto. apply IHstar.\n    inv H; eauto. inv H; eauto.\nQed.\n\nDefinition trace_internal (i : instruction) : Prop :=\n  match i with\n    | Pbuiltin _ _ _ => True\n    | Pannot _ _ => True\n    | _ => False\n  end.\n\nDefinition straightline (i : instruction) : Prop :=\n  match i with\n    | Pjmp_r _ _ => False\n    | Pjmp_l _ => False\n    | Pjmp_s _ _ => False\n    | Pjcc _ _ => False\n    | Pjcc2 _ _ _ => False\n    | Pcall_r _ _ => False\n    | Pcall_s _ _ => False\n    | Pjmptbl _ tbl => tbl = nil\n    | Pbuiltin _ _ _ => False\n    | Pannot _ _ => False\n    | Pret _ => False\n    | _ => True\n  end.\n\nDefinition local_jump (i : instruction) : Prop :=\n  match i with\n    | Pjmp_l _ => True\n    | Pjcc _ _ => True\n    | Pjcc2 _ _ _ => True\n    | Pjmptbl _ tbl => tbl <> nil\n    | _ => False\n  end.\n\nLemma list_destr_right :\n  forall { A : Type } (l : list A),\n    l = nil \\/ (exists b e, l = b ++ e :: nil).\nProof.\n  induction l; intros.\n  left. reflexivity.\n  destruct IHl. subst. right.\n  exists nil. exists a. simpl. reflexivity.\n  repeat break_exists. subst l.\n  right.\n  exists (a :: x). exists x0.\n  simpl. reflexivity.\nQed.\n\nLemma at_code_head :\n  forall z c1 c2 ofs ge cs,\n    at_code z (c1 ++ c2) ofs ge cs ->\n    ofs < zlen c1 ->\n    at_code z c1 ofs ge cs.\nProof.\n  intros. inv H.\n  eapply at_c; eauto. omega.\n  find_rewrite. rewrite app_ass. reflexivity.\nQed.\n\nLemma at_code_cons :\n  forall z i c ge cs,\n    at_code z (i :: c) 0 ge cs ->\n    at_code z (i :: nil) 0 ge cs.\nProof.\n  intros. eapply at_code_head.\n  simpl. eassumption.\n  unfold zlen. simpl. omega.\nQed.\n\nLemma straightline_exec :\n  forall ge f i rs m rs' m' bits b ofs t t',\n    rs PC = Vint bits ->\n    exec_instr_bits ge t f i b rs m = Nxt rs' m' t' ->\n    straightline i ->\n    pinj t b ofs = Some bits ->\n    exists bits',\n      rs' PC = Vint bits' /\\\n      pinj t' b (Int.add ofs Int.one) = Some bits'.\nProof.\n  intros.\n  destruct i; simpl in H1; try subst tbl; try solve [simpl in H1; inv H1];\n  simpl in *;\n  simpl_exec;\n  simpl in *;\n  unfold exec_big_load_bits in *;\n  unfold exec_big_store_bits in *;\n  unfold exec_load_bits in *;\n  unfold exec_store_bits in *;\n  repeat break_match_hyp;\n  try find_inversion;\n  repeat state_inv;\n  try solve [\n  eexists; split; [preg_simpl; repeat break_match; preg_simpl; rewrite H;\n                   simpl; eauto | apply pinj_add; eauto]].\n  eexists; split.\n  preg_simpl. rewrite H. simpl. eauto.\n  eapply pinj_alloc. eapply pinj_add. eauto.\n  eexists; split.\n  preg_simpl. rewrite H. simpl. eauto.\n  eapply pinj_free. eapply pinj_add. eauto.\nQed.  \n\nLemma label_exec :\n  forall ge f i rs m rs' m' bits b ofs t t',\n    rs PC = Vint bits ->\n    exec_instr_bits ge t f i b rs m = Nxt rs' m' t' ->\n    (exists l, i = Plabel l) ->\n    pinj t b ofs = Some bits ->\n    exists bits',\n      rs' PC = Vint bits' /\\\n      pinj t' b (Int.add ofs Int.one) = Some bits'.\nProof.\n  intros.\n  break_exists.\n  subst. \n  rename H2 into H1.\n  simpl in H1; try subst tbl; try solve [simpl in H1; inv H1];\n  simpl in H0. inv H0.\n  eexists; split.\n  preg_simpl. find_rewrite. reflexivity.\n  eapply pinj_add; eauto.\nQed.  \n\nLemma star_step_in_at_code :\n  forall z c ge st t st',\n    star_step_in z c ge st t st' ->\n    exists ofs,\n      at_code z c ofs ge st.\nProof.\n  induction 1; intros; eauto. \n  inv H. eauto.\n  inv H0. eauto.\nQed.\n\nLemma neq_add_one :\n  forall x,\n    ~ Int.unsigned x = Int.unsigned (Int.add x Int.one).\nProof.\n  intros. destruct x.\n  simpl. unfold Int.unsigned. simpl.\n  unfold Int.add. rewrite Int.unsigned_one. simpl.\n  replace Int.intval with Int.unsigned by (simpl; auto).\n  destruct (zeq intval Int.max_unsigned). subst.\n  rewrite Int.unsigned_repr_eq.\n  unfold Int.max_unsigned. unfold Int.modulus. simpl.\n  unfold Int.wordsize. unfold Wordsize_32.wordsize.\n  unfold two_power_nat. unfold shift_nat. simpl.\n  rewrite Z_mod_same_full.\n  omega.\n  rewrite Int.unsigned_repr. omega. unfold Int.max_unsigned in *. omega.\nQed.\n\n\nLemma star_step_in_in :\n  forall z c ge st t st',\n    star_step_in z c ge st t st' ->\n    in_code z c ge st.\nProof.\n  induction 1; intros; eauto.\nQed.\n\nLemma star_step_in_in' :\n  forall z c ge st t st',\n    star_step_in z c ge st t st' ->\n    in_code z c ge st'.\nProof.\n  induction 1; intros; eauto.\nQed.\n\n\nLemma straightline_step_no_trace :\n  forall z i c ge st t st',\n    at_code z (i :: c) 0 ge st ->\n    straightline i ->\n    step_bits ge st t st' ->\n    t = E0.\nProof.\n  intros. inv H.\n  inv_step H1; try reflexivity.\n\n\n  copy H11.\n  unify_psur.\n  break_and; subst.\n  \n  unify_find_funct_ptr.\n  unify_psur.\n  subst.\n  \n  rewrite H7 in H13. \n  rewrite H4 in H13.\n  rewrite find_instr_append_head in H13 by omega.\n  simpl in H13. inv H13. simpl in H0. inv H0.\n\n  copy H11.\n  unify_psur.\n  break_and; subst.\n  unify_find_funct_ptr.\n  subst.\n  rewrite H7 in H15. \n  rewrite H4 in H15.\n  rewrite find_instr_append_head in H15 by omega.\n  simpl in H15. inv H15. simpl in H0. inv H0.\n\n  unify_psur. unify_find_funct_ptr.\n\nQed.\n\nLemma in_code_one_instr :\n  forall z i ge st,\n    ~ in_code z (i :: nil) ge st.\nProof.\n  intros. intro.\n  inv H. inv H1.\n  rewrite zlen_cons in H4. simpl in H4. omega.\nQed.\n\nLemma st_through_one :\n  forall z st t st' i ge,\n    straightline i ->\n    step_through z (i :: nil) ge st t st' ->\n    step_t (i :: nil) ge st t st'.\nProof.\n  intros.\n  \n  inv H0.\n  replace t with (E0 ** t) by (simpl; reflexivity).\n  app straightline_step_no_trace H2. subst t.  \n  econstructor; eauto.\n  econstructor.\n\n\n  app star_step_in_in H4.\n  app in_code_one_instr H4. inv_false.\nQed.\n\nLemma at_code_succ :\n  forall z i c ofs ge st,\n    ofs > 0 ->\n    at_code z (i :: c) ofs ge st ->\n    at_code (z+1) c (ofs - 1) ge st.\nProof.\n  intros.\n  inv H0.\n  replace (zlen c1 + 1) with (zlen (c1 ++ i :: nil)) by (rewrite zlen_app; rewrite zlen_cons; simpl; reflexivity).\n  econstructor; eauto; \n  repeat rewrite zlen_app in *;\n  repeat rewrite zlen_cons in *;\n  simpl;\n  try omega.\n  find_rewrite. simpl. rewrite app_ass. simpl. reflexivity.\nQed.\n\nLemma add_one_no_overflow :\n  forall i,\n    0 <= Int.unsigned i < Int.max_unsigned ->\n    Int.unsigned (Int.add i Int.one) = Int.unsigned i + 1.\nProof.\n  intros. unfold Int.add. rewrite Int.unsigned_one.\n  rewrite Int.unsigned_repr by omega. reflexivity.\nQed.\n\n\nLtac st_inv :=\n  match goal with\n    | [ H : Nxt _ _ _ = Nxt _ _ _ |- _ ] => inv H\n    | [ H : Nxt _ _ _ = Stck |- _ ] => congruence\n    | [ H : Stck = Nxt _ _ _ |- _ ] => congruence\n  end.\n\n\n\n\n\nLemma at_code_straightline :\n  forall z i x c (p : Asm.program) cs cs' t,\n    no_PC_overflow_prog p ->\n    at_code z (i :: x :: c) 0 (Genv.globalenv p) cs ->\n    step_bits (Genv.globalenv p) cs t cs' ->\n    straightline i ->\n    at_code z (i :: x :: c) 1 (Genv.globalenv p) cs'.\nProof.\n  intros. inv H0.\n\n  \n  inv_step H1;\n    unify_psur;\n    try unify_find_funct_ptr;\n    subst;\n    try congruence;\n    try find_inversion;\n    try match goal with\n      | [ H : fn_code _ = _ |- _ ] => rewrite H in *\n    end;\n    try match goal with\n      | [ H : Int.unsigned _ = _ |- _ ] => rewrite H in *\n    end;\n    try match goal with\n      | [ H : find_instr _ _ = _ |- _ ] => rewrite find_instr_append_head in H by omega; simpl in H; inv H\n        end;\n    try solve [\n          match goal with\n            | [ H : straightline _ |- _ ] => simpl in H; inv H\n          end].\n\n  app weak_valid_pointer_sur H12. break_and.\n  \n  NP _app straightline_exec exec_instr_bits. break_and.\n  econstructor; eauto.\n  Focus 2. repeat rewrite zlen_cons. name (zlen_nonneg _ c) zln.\n  instantiate (1 := (Int.add i0 Int.one)).\n  \n\n  assert (code_of_prog (fn_code f) p).\n  {\n    unfold code_of_prog.\n    app Genv.find_funct_ptr_inversion H7.\n    simpl. destruct f. simpl. exists x1. exists fn_sig.\n    simpl.\n    eauto.\n  }\n\n  \n  unfold no_PC_overflow_prog in H.\n  NP1 _app H code_of_prog. unfold no_PC_overflow in *.\n\n  assert (find_instr (Int.unsigned i0) (fn_code f) = Some i1).\n  \n  rewrite H5. rewrite H8. simpl. rewrite find_instr_append_head by omega.\n  simpl. reflexivity.\n\n  NP1 _app H15 find_instr.\n  rewrite add_one_no_overflow by omega. rewrite H5. omega.\n  app step_match_metadata H1.\n\n  \n  erewrite weak_valid_pointer_sur; eauto.\n  split; auto.\n  NP _app global_perms_step step_bits.\n  clear H21.\n  NP _app global_perms_valid_globals global_perms.\n  unfold valid_globals in *.\n  eapply Memory.Mem.valid_pointer_implies.\n  eapply H15.\n  unfold is_global. left.\n  unfold in_code_range.\n  unfold fundef in *.\n  collapse_match.\n\n  name (Int.unsigned_range (Int.add i0 Int.one)) r.\n  rewrite Int.unsigned_add_carry in *.\n  rewrite Int.unsigned_one in *.\n  split; try omega.\n  unfold Int.add_carry.\n  rewrite H5. rewrite H8.\n  repeat rewrite zlen_app.\n  repeat rewrite zlen_cons.\n  name (zlen_nonneg _ c1) zlnc1.\n  name (zlen_nonneg _ c2) zlnc2.\n  name (zlen_nonneg _ c) zlnc.\n  break_match; repeat rewrite Int.unsigned_zero;\n  repeat rewrite Int.unsigned_one; try omega.\n  repeat rewrite zlen_cons.\n  name (zlen_nonneg _ c) zlnc.\n  omega.\n\nQed.\n\nLemma at_code_end_succ :\n  forall z i c ge st,\n    at_code_end z (i :: c) ge st ->\n    at_code_end (z+1) c ge st.\nProof.\n  intros. inv H.\n  replace (zlen c1 + 1) with (zlen (c1 ++ i :: nil)).\n  Focus 2. rewrite zlen_app. rewrite zlen_cons.\n  simpl. omega.\n  econstructor; eauto.\n  rewrite zlen_app. rewrite zlen_cons. simpl.\n  rewrite zlen_cons in H2. omega.\n  rewrite H4. simpl. rewrite app_ass. simpl.\n  reflexivity.\nQed.\n\nLtac case_step := \n  match goal with \n    | [H : step_bits _ _ _ _ |- _ ] => inv H; [ | | | ]\n  end.\n\nLtac same_pc_bits := \n  match goal with \n      | [ H1 : ?rs PC = Vint ?bits1, H2 : ?rs PC = Vint ?bits2 |- _ ] => \n        rewrite H1 in H2; symmetry in H2; inv H2\n    end.\n\n(* Ltac same_psur :=  *)\n(*   match goal with  *)\n(*       | [ H1 : psur ?bits = (_, _), H2 : psur ?bits = (_, _) |- _ ] =>  *)\n(*         rewrite H1 in H2; symmetry in H2; inv H2 *)\n(*     end. *)\n\nLtac same_find_funct_ptr := \n  match goal with\n          | [ H1 : Genv.find_funct_ptr ?ge ?b = Some (Internal _),\n              H2 : Genv.find_funct_ptr ?ge ?b = Some (Internal _) |- _] =>\n            unfold fundef in H1, H2; rewrite H2 in H1; inv H1\n  end.\n\nLtac same_find_instr :=\n  match goal with \n    | [ H1 : find_instr ?a ?b = _,\n        H2 : find_instr ?a ?b = _ |- _] =>\n      rewrite H2 in H1; inv H1\n  end.\n\nLtac trim_l_find_instr :=\n  match goal with\n        | [ H : find_instr (zlen ?c1 + ?ofs') (?c1 ++ ?c) = _ |- _ ] =>\n          rewrite find_instr_append_head in H; [ | omega]\n    end.\n\nLtac trim_r_find_instr :=\n  match goal with\n      | [ H : find_instr _ (_ ++ _) = _ |- _] =>\n        rewrite (find_instr_append_tail _ _ nil _) in H; [ | omega]\n  end.\n\nLemma find_instr_in_code :\n      forall c ofs i,\n        0 <= ofs < zlen c ->\n        find_instr ofs c = Some i ->\n        In i c.\nProof.\n  induction c; simpl; intros.\n  congruence.\n  break_if_hyp.\n  inv H0; auto.\n  right.\n  eapply IHc; eauto.\n  rewrite zlen_cons in H.\n  omega.\nQed.\n\nHint Resolve app_nil_end.\n\nDefinition current_fn (ge : genv) (st : state_bits) : option function := \n  match st with\n    | State_bits rs m t => \n      match rs PC with\n        | Vint bits =>\n          match psur t bits with\n            | Some (b, ofs) =>\n              match Genv.find_funct_ptr ge b with\n                | Some (Internal f) => Some f\n                | _ => None\n              end\n            | None => None\n          end\n        | _ => None\n      end                  \n  end.\n\nDefinition current_code (ge : genv) (st : state_bits) : option code :=\n  match current_fn ge st with\n    | Some f => Some (fn_code f)\n    | _ => None\n  end.\n\nDefinition current_instr (ge : genv) (st : state_bits) : option instruction := \n  match st with\n    | State_bits rs m t => \n      match rs PC with\n        | Vint bits =>\n          match psur t bits with\n            | Some (b, ofs) =>\n              match current_code ge st with\n                | Some c => find_instr (Int.unsigned ofs) c\n                | _ => None                      \n              end\n            | None => None\n          end\n        | _ => None\n      end                  \n  end.\n\nLemma in_code_instr:\n  forall pad c ge st i,\n    in_code pad c ge st ->\n    current_instr ge st = Some i ->\n    In i c.\nProof.\n  intros.\n  inv H.\n  inv H2.\n  unfold current_instr in *; \n  unfold current_code in *;\n  unfold current_fn in *.\n  unfold fundef in *.\n  rewrite H, H3, H6, H7, H4 in H0.\n  trim_l_find_instr.\n  trim_r_find_instr.\n  eapply find_instr_in_code. eauto.\n  assert (c = c ++ nil) by apply app_nil_end.\n  rewrite H2.\n  eauto.   \nQed.\n\nLemma has_current_instr :\n  forall rs m c ge i b ofs f bits pad md,\n    in_code pad c ge (State_bits rs m md) ->\n    rs PC = Vint bits ->\n    psur md bits = Some (b, ofs) ->\n    Genv.find_funct_ptr ge b = Some (Internal f) ->\n    find_instr (Int.unsigned ofs) (fn_code f) = Some i ->  \n    current_fn ge (State_bits rs m md) = Some f /\\\n    current_instr ge (State_bits rs m md) = Some i.\nProof.\n  intros.\n  unfold current_instr. unfold current_code. unfold current_fn.\n  rewrite H0, H1, H2, H3.\n  split; trivial.\nQed.\n     \nLtac case_local_jump_instr :=\n  match goal with\n    | [ H : local_jump ?i |- _] =>\n      destruct i; try solve [inv H]\n  end.\n\nLtac case_straightline_instr :=\n  match goal with\n    | [ H : straightline ?i |- _] =>\n      destruct i; try solve [inv H]\n  end.\n\nLemma in_code_is_jump_dec : \n  forall fst c ge st pad i,\n    straightline fst ->\n    (forall k : instruction, In k c -> straightline k \\/ local_jump k) ->\n    in_code pad (fst :: c) ge st ->\n    current_instr ge st = Some i ->  \n    straightline i \\/ local_jump i.\nProof.\n  intros.\n  assert (In i (fst :: c)) by (eapply in_code_instr; eauto).\n  assert (i = fst \\/ In i c).\n  simpl in *; inv H3; auto.\n  inv H4.\n  auto.\n  apply H0.\n  assumption.\nQed.\n\nLtac case_is_jump := \n  match goal with \n    | [ i : instruction |- _ ] =>  \n      let H := fresh \"H\" in\n      assert (straightline i \\/ local_jump i) \n        as H \n          by (      \n              eapply in_code_is_jump_dec; eauto;\n              eapply has_current_instr; eauto\n            ); inv H\n  end.\n\nLemma val_to_int_add :\n  forall z,\n    Val.add (Vint z) Vone = Vint (Int.add z Int.one).\nProof.\n  auto.\nQed.\n\nLemma nextinstr_same_block :\n  forall p rs bits b ofs rs' bits' md f i i' m,\n    match_metadata md m ->\n    global_perms (Genv.globalenv p) m ->\n    Genv.find_funct_ptr (Genv.globalenv p) b = Some (Internal f) ->\n    find_instr (Int.unsigned ofs) (fn_code f) = Some i ->\n    find_instr (Int.unsigned (Int.add ofs Int.one)) (fn_code f) = Some i' ->\n    rs PC = Vint bits ->\n    psur md bits = Some (b, ofs) ->\n    rs' PC = Vint bits' ->\n    Vint bits' = (nextinstr rs) PC ->\n    psur md bits' = Some (b, Int.add ofs Int.one).\nProof.\n  intros.\n  \n  (*TODO Share with PeepholeLib *)\n  Lemma nextinstr_PC :\n    forall rs v,\n      rs PC = v ->\n      nextinstr rs PC = Values.Val.add v Values.Vone.\n  Proof.\n    intros. unfold nextinstr.\n    rewrite Pregmap.gss. rewrite H. reflexivity.\n  Qed.\n\n  \n  apply nextinstr_PC in H4.\n  simpl in H4. rewrite H4 in H7.\n  inv H7.\n  eapply weak_valid_pointer_sur in H5; eauto.\n  eapply weak_valid_pointer_sur; eauto.\n  break_and; split.\n  eapply pinj_add; eauto.\n  app global_perms_valid_globals H0.\n  unfold valid_globals in H0.\n  eapply Memory.Mem.valid_pointer_implies.\n  eapply H0.\n  unfold is_global.\n  left. unfold in_code_range.\n  unfold fundef in *.\n  collapse_match.\n  apex in_range_find_instr H3. omega.\nQed.\n\nLtac unify_stuff :=\n  repeat (try same_pc_bits; try unify_psur; try same_find_funct_ptr; try same_find_instr).\n\nLemma no_PC_overflow_w_ctx (*TODO need better name*):\n  forall p b f z i,\n    no_PC_overflow_prog p ->\n    Genv.find_funct_ptr (Genv.globalenv p) b = Some (Internal f) ->\n    find_instr z (fn_code f) = Some i ->\n    0 <= z < Int.max_unsigned.\nProof.\n  intros.\n  unfold no_PC_overflow_prog in *; unfold no_PC_overflow in *; unfold code_of_prog in *.\n  destruct f.\n  specialize (H fn_code).\n  apply Genv.find_funct_ptr_inversion in H0.\n  assert (exists id fn_sig, In (id, Gfun (Internal {| fn_sig := fn_sig; fn_code := fn_code |}))\n           (prog_defs p)).\n  break_exists.\n  eauto.\n  eapply H in H2.\n  eassumption.\n  eassumption.\nQed.\nHint Resolve no_PC_overflow_w_ctx.\n\nLemma psur_add_code :\n  forall ge md bits b ofs md' m m',\n    psur md bits = Some (b,ofs) ->\n    md_extends md md' ->\n    match_metadata md m ->\n    match_metadata md' m' ->\n    global_perms ge m' ->\n    forall adj,\n      in_code_range ge b (Int.add ofs adj) ->\n      psur md' (Int.add bits adj) = Some (b,Int.add ofs adj).\nProof.\n  intros.\n  erewrite weak_valid_pointer_sur in *; eauto.\n  break_and. app pinj_extends H.\n  split.\n  eapply pinj_add; eauto.\n  unfold global_perms in H3.\n  unfold is_global in H3.\n  eapply Memory.Mem.valid_pointer_implies.\n  exploit H3; eauto. intros.\n  break_exists. repeat break_and.\n  unfold Memory.Mem.valid_pointer.\n  unfold Memory.Mem.perm_dec.\n  unfold proj_sumbool. break_match; try reflexivity.\n  clear Heqs. exfalso. apply n.\n  unfold Memory.Mem.perm_order'.\n  rewrite H7.\n  econstructor.\nQed.\n\n\nLemma int_unsigned_add_one :\n  forall i hi,\n    0 <= Int.unsigned i < hi ->\n    0 <= Int.unsigned (Int.add i Int.one) <= hi.\nProof.\n  intros. unfold Int.add.\n  rewrite Int.unsigned_one.\n  rewrite Int.unsigned_repr_eq.\n  name (Int.unsigned_range i) Hr.\n  assert (Int.unsigned i + 1 < Int.modulus \\/ Int.unsigned i + 1 = Int.modulus) by omega.\n  break_or. rewrite Zmod_small by omega.\n  omega.\n  rewrite H1.\n  rewrite Z_mod_same_full. omega.\nQed.  \n\nLemma int_unsigned_minus_range :\n  forall z hi,\n    0 <= z-1 < hi ->\n    0 <= Int.unsigned (Int.repr z) <= hi.\nProof.\n  intros. rewrite Int.unsigned_repr_eq.\n  assert (z mod Int.modulus <= z). eapply Zmod_le.\n  unfold Int.modulus. unfold Int.wordsize.\n  unfold Wordsize_32.wordsize. unfold two_power_nat.\n  unfold shift_nat. simpl. omega. omega.\n  assert (0 <= z mod Int.modulus < Int.modulus). eapply Z_mod_lt.\n  unfold Int.modulus. unfold Int.wordsize.\n  unfold Wordsize_32.wordsize. unfold two_power_nat.\n  unfold shift_nat. simpl. omega. omega.\nQed.\n\n\n\nLemma psur_add_one :\n  forall ge md bits b ofs md' m m',\n    psur md bits = Some (b,ofs) ->\n    md_extends md md' ->\n    match_metadata md m ->\n    match_metadata md' m' ->\n    global_perms ge m' ->\n    in_code_range ge b ofs ->\n    Int.unsigned ofs < Int.max_unsigned ->\n    psur md' (Int.add bits Int.one) = Some (b,Int.add ofs Int.one).\nProof.\n  intros.\n  erewrite weak_valid_pointer_sur in *; eauto.\n  break_and. app pinj_extends H.\n  split.\n  eapply pinj_add; eauto.\n  unfold global_perms in H3.\n  unfold is_global in H3.\n  eapply Memory.Mem.weak_valid_pointer_spec.\n  right.\n  exploit H3; eauto. intros.\n  break_exists. repeat break_and.\n  unfold Memory.Mem.valid_pointer.\n  unfold Memory.Mem.perm_dec.\n  unfold proj_sumbool. break_match; try reflexivity.\n  clear Heqs. exfalso. apply n.\n  unfold Memory.Mem.perm_order'.\n  replace (Int.unsigned (Int.add ofs Int.one) - 1) with (Int.unsigned ofs).\n  rewrite H8.\n  econstructor.\n  unfold Int.add.\n  rewrite Int.unsigned_one.\n  name (Int.unsigned_range_2 ofs) r.\n  assert (0 <= Int.unsigned ofs < Int.max_unsigned) by omega.\n  cut (Int.unsigned ofs + 1 = Int.unsigned (Int.repr (Int.unsigned ofs + 1))).\n  intros. omega.\n  rewrite Int.unsigned_repr by omega. reflexivity.\nQed.\n\nLemma unsigned_repr_sub_one :\n  forall z,\n    z > 0 ->\n    z <= Int.max_unsigned ->\n    Int.unsigned (Int.repr z) - 1 = Int.unsigned (Int.repr (z - 1)).\nProof.\n  intros.\n  repeat rewrite Int.unsigned_repr by omega.\n  reflexivity.\nQed.\n\nLemma unsigned_repr_range :\n  forall hi z,\n    0 <= z < hi ->\n    0 <= Int.unsigned (Int.repr z) < hi.\nProof.\n  intros.\n\n  rewrite Int.unsigned_repr_eq.\n  exploit (Z_mod_lt z Int.modulus).\n  unfold Int.modulus. unfold Int.wordsize.\n  unfold Wordsize_32.wordsize. unfold two_power_nat.\n  unfold shift_nat. simpl. omega.\n  intros.\n  assert (z mod Int.modulus <= z).\n  eapply Zmod_le.\n  unfold Int.modulus. unfold Int.wordsize.\n  unfold Wordsize_32.wordsize. unfold two_power_nat.\n  unfold shift_nat. simpl. omega.\n  omega. split; try omega.\nQed.\n\nSection ST_IN.\n  Variable p : program.\n  Hypothesis nPC : no_PC_overflow_prog p.\n\n\n  Definition ge := Genv.globalenv p.\n\nLemma in_range_PC :\n  forall b fd z i,\n    Genv.find_funct_ptr ge b = Some (Internal fd) ->\n    find_instr z (fn_code fd) = Some i ->\n    z < Int.max_unsigned.\nProof.\n  intros. unfold ge in *.\n  unfold no_PC_overflow_prog in *.\n  assert (code_of_prog (fn_code fd) p). {\n    unfold code_of_prog. app Genv.find_funct_ptr_inversion H.\n    destruct fd. simpl. eauto.\n  } idtac.\n  app nPC H1.\n  unfold no_PC_overflow in H1. app H1 H0.\n  omega.\nQed.\n  \nLemma step_PC_same_block :\n  forall rs m rs' m' t b i s c instr bits md md',\n    rs PC = Values.Vint bits ->\n    psur md bits = Some (b,i) ->\n    Genv.find_funct_ptr ge b = Some (Internal (mkfunction s c)) ->\n    find_instr (Int.unsigned i) c = Some instr ->\n    ~ is_call_return instr ->\n    ~ is_builtin instr ->\n    step_bits ge (State_bits rs m md) t (State_bits rs' m' md') ->\n    exists i' bits',\n      rs' PC = Values.Vint bits' /\\ psur md' bits' = Some (b,i').\nProof.\n  intros.\n  invs;\n    repeat unify_PC;\n    repeat unify_psur;\n    repeat unify_find_funct_ptr;\n    simpl in *;\n    repeat unify_find_instr;\n    simpl in *;\n    try inv_false.\n  \n  destruct i0 eqn:?;\n    simpl in H3;\n    simpl in H4;\n    try inv_false;\n    unfold exec_instr_bits in *;\n    unfold exec_load_bits in *;\n    unfold exec_store_bits in *;\n    unfold goto_label_bits in *;\n    unfold exec_big_store_bits in *;\n    unfold exec_big_load_bits in *;\n    repeat break_match_hyp; try congruence;\n    try st_inv;\n    preg_simpl;\n    try rewrite H;\n    simpl;\n\n  match goal with\n    | [ |- exists _, exists _, Vint _ = Vint _ /\\ _ ] => eexists; eexists; split; try reflexivity; try eapply psur_add_one\n    | [ |- _ ] => idtac\n  end;\n  match goal with\n    | [ |- match_metadata (md_alloc _ _ _ _) _ ] => eapply match_alloc\n    | [ |- match_metadata (md_free _ _ _ _) _ ] => eapply match_free\n    | [ |- _ ] => idtac\n  end;\n  try solve [econstructor];\n  eauto;\n  match goal with\n    | [ |- match_metadata (md_alloc _ _ _ _) _ ] => eapply match_alloc\n    | [ |- match_metadata (md_free _ _ _ _) _ ] => eapply match_free\n    | [ |- _ ] => idtac\n  end;\n  eauto;\n  try solve [unfold in_code_range;\n              unfold fundef in *; collapse_match;\n              simpl; apex in_range_find_instr H2; omega];\n  try solve [\n      repeat break_match; preg_simpl;\n        try rewrite H;\n        simpl;\n        repeat break_match;\n        preg_simpl;\n        try rewrite H;\n        match goal with\n          | [ |- exists _, exists _, Vint _ = Vint _ /\\ _ ] => eexists; eexists; split; try reflexivity; try eapply psur_add_one; eauto\n          | [ |- _ ] => idtac\n        end;\n        try solve [econstructor];\n        try solve [unfold in_code_range;\n                    unfold fundef in *; collapse_match;\n                    simpl; apex in_range_find_instr H2; try omega\n                  ];\n        try eapply in_range_PC; eauto\n      ];\n  \n  try instantiate (1 := Int.repr z);\n  simpl in *;\n  try solve [eapply in_range_PC; eauto];\n  \n  \n  try solve [\n        erewrite weak_valid_pointer_sur in *; eauto;\n        split; eauto;\n        NP _app global_perms_valid_globals global_perms;\n        P _eapply valid_globals;\n        unfold is_global;\n        left; unfold in_code_range;\n        unfold fundef in *; collapse_match;\n        simpl;\n        simpl in Heqo;\n        NP _app label_pos_find_instr label_pos;\n        NP apex in_range_find_instr Plabel;\n        eapply int_unsigned_minus_range; try omega;\n        try eapply in_range_PC; eauto\n      ];\n  \n  try solve [\n        erewrite weak_valid_pointer_sur in *; eauto;\n        split; eauto;\n        NP _app global_perms_valid_globals global_perms;\n        eapply Memory.Mem.weak_valid_pointer_spec; right;\n        unfold valid_globals in *;\n        NP _app label_pos_find_instr label_pos;\n        NP apex in_range_find_instr Plabel;\n        rewrite unsigned_repr_sub_one;\n        try (eapply H21;\n        unfold is_global;\n        left; unfold in_code_range;\n        unfold fundef in *;\n        collapse_match; simpl;\n        eapply unsigned_repr_range; try omega);\n        try omega;\n        cut (z - 1 < Int.max_unsigned);\n        try omega;\n        try eapply in_range_PC; eauto\n      ].\n\n  \n  eapply psur_alloc; eauto.\n  eapply GlobalPerms.global_perms_alloc; eauto.\n  match goal with\n    | [ |- in_code_range ge b i ] =>\n      unfold in_code_range; unfold fundef in *;\n      collapse_match; apex in_range_find_instr H2;\n      simpl;  omega\n    | [ |- _ ] => idtac\n  end.\n\n  erewrite weak_valid_pointer_sur in *; eauto. split.\n  eapply pinj_free; eauto.\n  repeat break_and. eauto.\n  app GlobalPerms.global_perms_free Heqo3.\n  app global_perms_valid_globals Heqo3.\n  eapply Memory.Mem.valid_pointer_implies.\n  eapply Heqo3.\n  unfold is_global. left.\n  unfold in_code_range.\n  unfold fundef in *. collapse_match.\n  simpl. apex in_range_find_instr H2. omega.\n  eapply match_free; eauto.\n  app GlobalPerms.global_perms_free Heqo3.\n  unfold in_code_range. unfold fundef in *.\n  collapse_match. simpl.\n  apex in_range_find_instr H2.\n  omega.\n\n  preg_simpl. rewrite H. simpl.\n  match goal with\n    | [ |- exists _, exists _, Vint _ = Vint _ /\\ _ ] => eexists; eexists; split; try reflexivity\n    | [ |- _ ] => idtac\n  end;\n    try solve [econstructor];\n\n    match goal with\n      | [ |- in_code_range ge b (Int.add i Int.one) ] =>\n        unfold in_code_range; unfold fundef in *;\n        collapse_match; apex in_range_find_instr H2;\n        simpl; eapply int_unsigned_add_one; omega\n      | [ |- _ ] => idtac\n    end.\n\n  erewrite weak_valid_pointer_sur in *; eauto. break_and.\n  split.\n\n  3: eapply match_ec; eauto.\n  eapply pinj_ec; eauto.\n  eapply pinj_add; eauto.\n\n  eapply Memory.Mem.weak_valid_pointer_spec. right.\n  \n  \n  app global_perms_step H5.\n  app global_perms_valid_globals H5.\n\n  replace (Int.unsigned (Int.add i Int.one) - 1) with (Int.unsigned i).\n  \n  eapply H5.\n  unfold is_global. left.\n  unfold in_code_range.\n  unfold fundef in *.\n  collapse_match.\n  simpl.\n  apex in_range_find_instr H2.\n  omega.\n\n  unfold Int.add.\n  rewrite Int.unsigned_one.\n\n  assert (Int.unsigned i < Int.max_unsigned).\n  eapply in_range_PC; eauto.\n  rewrite Int.unsigned_repr. omega.\n  name (Int.unsigned_range_2 i) Hrange.\n  omega.\nQed.  \n\n\n\n(* We can make this true *)\n(* do later *)\nLemma in_code_straightline_succ :\n  forall pad rs m bits b ofs f i rs' m' ofs' fst snd c md md',    \n    (* straightline fst -> *)\n    rs PC = Vint bits ->\n    psur md bits = Some (b, ofs) ->\n    Genv.find_funct_ptr (Genv.globalenv p) b = Some (Internal f) ->\n    find_instr (Int.unsigned ofs) (fn_code f) = Some i ->\n    rs' PC = (nextinstr rs) PC ->\n    at_code pad (fst :: snd :: c) ofs' (Genv.globalenv p) (State_bits rs' m' md') ->\n    in_code pad (fst :: snd :: c) (Genv.globalenv p) (State_bits rs m md) ->\n    no_PC_overflow_prog p ->\n    global_perms (Genv.globalenv p) m' ->\n    md_extends md md' ->\n    match_metadata md m ->\n    match_metadata md' m' ->\n    ofs' - 1 > 0.\nProof.\n  intros.\n  name H4 Hat_code.\n  inv H4.\n  inv H5. inv H11.\n  repeat rewrite zlen_cons in *.\n  unfold nextinstr in *.\n  rewrite H in H3. preg_simpl_hyp H3.\n  simpl in H3. rewrite H3 in H14. inv H14.\n  rewrite H in H18. inv H18.\n    \n  erewrite psur_add_one in H15; eauto.\n  inv H15.\n  repeat unify_psur.\n  repeat unify_find_funct_ptr.\n  rewrite Int.add_unsigned in H16.\n  rewrite H20 in H16. rewrite Int.unsigned_one in H16.\n  rewrite Int.unsigned_repr in H16. omega.\n  app no_PC_overflow_w_ctx H2. omega.\n  unfold in_code_range.\n  repeat unify_psur.\n  unfold fundef in *.\n  collapse_match.\n  rewrite H20. rewrite H29.\n  repeat rewrite zlen_app. repeat rewrite zlen_cons.\n  name (zlen_nonneg _ c4) zln.\n  name (zlen_nonneg _ c) zlnc.\n  name (zlen_nonneg _ c3) zlnc3.\n  omega.\n  eapply in_range_PC. eapply H1.\n  eapply H2.\nQed.\n\nHint Resolve in_code_straightline_succ.\n\nLemma z_split :\n  forall n m,\n    n <= m \\/ n > m.\nProof.\n  intros.\n  omega.\nQed.\n\nLemma find_instr_range :\n  forall z c i,\n    find_instr z c = Some i ->\n    0 <= z < zlen c.\nProof.\n  intros.\n  name (z_split 0 z) Hz1.\n  name (z_split (zlen c) z) Hz2.\n  inv Hz1; inv Hz2.\n  assert (z >= zlen c) by omega.  \n  apply find_instr_overflow in H2.\n  congruence.\n  omega.\n  assert (z < 0) by omega.\n  apply (find_instr_neg c) in H2.\n  congruence.\n  assert (z < 0) by omega.\n  apply (find_instr_neg c) in H2.\n  congruence.\nQed.  \n\nDefinition is_any_label (i : instruction) : Prop :=\n  match i with\n    | Plabel _ => True\n    | _ => False\n  end.\n\nLemma in_code_jump_succ :\n  forall pad l rs m bits b ofs f i rs' m' ofs' fst snd c md md',\n    straightline fst ->    \n    rs PC = Vint bits ->\n    psur md bits = Some (b, ofs) ->\n    Genv.find_funct_ptr (Genv.globalenv p) b = Some (Internal f) ->\n    find_instr (Int.unsigned ofs) (fn_code f) = Some i ->\n    goto_label_bits md f l b rs m = Nxt rs' m' md' ->\n    at_code pad (fst :: snd :: c) ofs' (Genv.globalenv p) (State_bits rs' m' md') ->\n    ofs' > 0 ->\n    in_code pad (fst :: snd :: c) (Genv.globalenv p) (State_bits rs m md) ->\n    no_PC_overflow_prog p ->\n    ~ (is_any_label fst) ->\n    global_perms (Genv.globalenv p) m ->\n    match_metadata md m ->\n    ofs' - 1 > 0.\nProof.\n  intros.  \n  rename H6 into Hofs', H7 into H6, H8 into H7.\n  unfold goto_label_bits in *.\n  break_match_hyp.\n  2: congruence.\n  break_match_hyp; try congruence.\n  apply label_pos_find_instr in Heqo.\n  match goal with | [ H : at_code _ _ ofs' _ _ |- _ ] =>\n                    name H Hat_code'; inv H\n  end.\n  st_inv. \n  match goal with | [ H : ?rs PC = _ |- _ ] => inv H end.\n\n  assert (Hz1 : Int.unsigned (Int.repr (z - 1)) = z - 1).\n  erewrite unsigned_repr_PC; try eapply H2; eauto.\n  \n  assert (Hz : Int.unsigned (Int.repr z) = z ).\n  erewrite unsigned_repr_PC; try eapply H2; eauto.\n  \n  assert (Memory.Mem.weak_valid_pointer m' b z = true). {\n    eapply Memory.Mem.weak_valid_pointer_spec.\n    right.\n    app global_perms_valid_globals H10.\n    unfold valid_globals in H10.\n    rewrite <- Hz1.\n    eapply H10. unfold is_global.\n    left. unfold in_code_range.\n    unfold fundef in *.\n    collapse_match. rewrite Hz1.\n    NP apex in_range_find_instr Plabel.\n    omega.\n    \n  } idtac.\n  \n\n  rewrite <- Hz in H4.\n  name (conj Heqo0 H4) Hps.\n  erewrite <- weak_valid_pointer_sur in Hps; eauto.\n\n  rewrite Hps in H15. inversion H15. subst i1.\n  subst b0. clear H15.\n\n  rewrite Hz in *.\n  \n  assert (ofs' = 1 \\/ ofs' > 1) by omega.\n  break_or; try omega.\n\n  unify_find_funct_ptr. rewrite H23 in Heqo.\n  replace (zlen c1 + 1 - 1) with (zlen c1 + 0) in Heqo by omega.\n  rewrite find_instr_append_head in Heqo by omega.\n  simpl in Heqo.\n  inv Heqo. simpl in H9. inv_false.\nQed.\n  \n\nHint Resolve in_code_jump_succ.\n\nLemma in_code_succ :\n  forall pad fst snd c st t st',    \n    in_code pad (fst :: snd :: c) (Genv.globalenv p) st ->\n    in_code pad (fst :: snd :: c) (Genv.globalenv p) st' ->    \n    no_PC_overflow_prog p ->\n    step_bits (Genv.globalenv p) st t st' ->    \n    straightline fst ->\n    (forall k, In k (snd :: c) -> straightline k \\/ local_jump k) ->\n    ~ (is_any_label fst) ->\n    in_code (pad+1) (snd :: c) (Genv.globalenv p) st'.\nProof.\n  (* This is true, because: *)\n  (* if we're in a piece of code, not at the beginning *)\n  (* and we take a step and stay within that piece of code *)\n  (* we can't have gone back to i or even x *)\n  (* as any jump to a label will go past it *)\n  (* This will need absence of call/return instruction *)\n  (* That will be the pain *)\n\n  intros.\n    \n  match goal with \n      | [ H : in_code _ _ _ st' |- _ ] => inv H\n  end.\n  econstructor.\n  Focus 2.\n  eapply at_code_succ.\n  Focus 2.\n  eassumption.\n  assumption.\n  rename ofs into ofs'.  \n  \n  case_step.\n\n  (* exec_step_internal_bits *)\n  {\n    case_is_jump.\n    \n    (* straightline *)\n    {      \n      case_straightline_instr;\n      simpl in *;\n      unfold exec_load_bits in *;\n      unfold exec_store_bits in *;\n      unfold exec_big_load_bits in *;\n      unfold exec_big_store_bits in *;\n      unfold storev_bits in *;\n      repeat break_match_hyp;\n      try congruence;\n      assert ((rs') PC = (nextinstr rs) PC);\n      try st_inv;\n      subst;\n      eauto;\n      try eapply in_code_straightline_succ; eauto;\n      try solve [econstructor; eauto];\n      try solve [econstructor; try econstructor; eauto];\n      try solve [eapply global_perms_store_bits; eauto];\n      try solve [eapply global_perms_store_bits; try eapply global_perms_store_bits; eauto];\n\n      \n      try unfold compare_floats; try unfold compare_floats32;\n      repeat break_match; preg_simpl; try reflexivity.\n\n      simpl in Heqo. inv Heqo.\n\n      eapply global_perms_store_bits; try eapply global_perms_store_bits;\n      try eapply global_perms_alloc; eauto.\n\n      econstructor; try econstructor; try eapply match_alloc; eauto.\n\n      eapply global_perms_free; eauto.\n      eapply match_free; eauto.\n    }\n\n    (* local jump *)\n    {\n      case_local_jump_instr; \n      simpl in *;\n      repeat break_match_hyp; try congruence;            \n      eauto;\n      assert ((rs') PC = (nextinstr rs) PC);\n      try st_inv;\n      subst;\n      try solve [eapply in_code_jump_succ; eauto];\n      try solve [eapply in_code_straightline_succ; eauto; econstructor];\n      eauto.\n      \n    }    \n  }\n\n  (*exec_step_builtin_bits*)\n  remember (Pbuiltin ef args res).\n  case_is_jump; inv H12.\n\n  (*exec_step_annot_bits*)\n  remember (Pannot ef args).\n  case_is_jump; inv H18.\n\n  (*exec_step_external_bits*)\n  inv H6.\n  inv H.\n  inv H6.\n  unify_stuff.\n  unfold fundef in *.\n\n  unify_find_funct_ptr.\n  \nQed.   \n\nLemma in_code_not_nil :\n  forall z c ge st,\n    in_code z c ge st ->\n    c <> nil.\nProof.\n  intros. inv H.\n  inv H1. destruct c; try congruence.\n  unfold zlen in H4. simpl in H4. omega.\nQed.\n\nLemma star_step_in_succ :\n  forall z i c st t st',        \n    star_step_in z (i :: c) (Genv.globalenv p) st t st' ->\n    straightline i ->\n    in_code (z + 1) c (Genv.globalenv p) st ->\n    (forall k, In k c -> straightline k \\/ local_jump k) ->    \n    no_PC_overflow_prog p ->\n    ~ (is_any_label i) ->\n    star_step_in (z+1) c (Genv.globalenv p) st t st'.\nProof.\n  intros. \n  remember (i :: c) as c0.\n  remember (Genv.globalenv p) as ge.\n  induction H; subst c0.\n  econstructor; eauto.\n  destruct c. app in_code_not_nil H1. congruence.\n  econstructor. apply IHstar_step_in. eauto.\n  eauto.\n  app star_step_in_in H.\n  subst.\n  \n  eapply in_code_succ; eauto.\n  eauto.\n  eauto.\nQed.\n\n(* Key lemma *)\nLemma step_through_t_straightline :\n  forall z st t st' i x c,\n    no_PC_overflow_prog p ->\n    step_through z (i :: x :: c) (Genv.globalenv p) st t st' ->\n    straightline i ->    \n    (forall k, In k (x :: c) -> straightline k \\/ local_jump k) ->\n    ~ (is_any_label i) ->\n    exists st'' t1 t2,\n      step_t (i :: nil) (Genv.globalenv p) st t1 st'' /\\\n      step_through (z + 1) (x :: c) (Genv.globalenv p) st'' t2 st' /\\\n      t = t1 ** t2.\nProof.\n  intros. \n  rename H3 into Hno_lb.  \n  inv H0.\n  * app at_code_straightline H3. \n    inv H3. inv H5. unify_PC.\n    unify_psur. unify_find_funct_ptr.\n    rewrite H3 in *. repeat rewrite zlen_cons in H16.\n    name (zlen_nonneg _ c) zln. omega.\n  * app at_code_straightline H5.\n    app at_code_succ H5; try omega.\n    simpl in H5. app straightline_step_no_trace H0. subst t1.\n    app at_code_end_succ H4.\n    exists stB. exists E0. exists (t2 ** t3).\n    isplit. replace E0 with (E0 ** E0) by auto.\n    econstructor; eauto. eapply at_code_head. simpl. eauto.\n    rewrite zlen_cons. simpl. omega.\n    econstructor. split; try reflexivity.\n    \n    inv H6.\n    econstructor; eauto.\n\n    rewrite Eapp_assoc.\n    eapply st_thru_mult_step; eauto.\n    app star_step_in_in H11.\n\n    eapply in_code_succ in H13; eauto.\n    \n    eapply star_step_in_succ; eauto.\nQed.\n\n\n(* (* How do we write this lemma? *) *)\n(* Lemma step_through_t_straightline : *)\n(*   forall z p st t st' i x c, *)\n(*     no_PC_overflow_prog p -> *)\n(*     step_t (i :: x :: c) (Genv.globalenv p) st t st' -> *)\n(*     straightline i -> *)\n(*     (forall k, In k (x :: c) -> straightline k \\/ local_jump k) -> *)\n(*     ~ (is_any_label i) -> *)\n(*     exists st'' t1 t2, *)\n(*       step_t (i :: nil) (Genv.globalenv p) st t1 st'' /\\ *)\n(*       step_through (z + 1) (x :: c) (Genv.globalenv p) st'' t2 st' /\\ *)\n(*       t = t1 ** t2. *)\n\n  \n(* Lemma test : *)\n(*   forall a b c p st st' z, *)\n(*     straightline a -> *)\n(*     straightline b -> *)\n(*     straightline c -> *)\n(*     ~ is_any_label a -> *)\n(*     ~ is_any_label b -> *)\n(*     ~ is_any_label c -> *)\n(*     no_PC_overflow_prog p -> *)\n(*     step_through z (a :: b :: c :: nil) (Genv.globalenv p) st E0 st' -> *)\n(*     step_t (a :: b :: c :: nil) (Genv.globalenv p) st E0 st' . *)\n(* Proof. *)\n(*   intros. *)\n(*   app step_through_t_straightline H6. *)\n(*   Focus 2. intros. simpl in H8. *)\n(*   repeat break_or; subst; try inv_false; left; eauto. *)\n(*   repeat break_and. *)\n(*   app step_through_t_straightline H8. *)\n(*   Focus 2. intros. simpl in H11. *)\n(*   repeat break_or; subst; try inv_false; left; eauto. *)\n(*   repeat break_and. *)\n(*   app st_through_one H11. *)\n(*   assert (x0 = E0). *)\n(*   { *)\n(*     destruct x0; auto; inv H12. inv H9. *)\n(*   } *)\n(*   subst x0. *)\n(*   assert (x1 = E0). *)\n(*   { *)\n(*     destruct x1; auto; inv H9. *)\n(*   } *)\n(*   subst x1. *)\n(*   assert (x3 = E0). *)\n(*   { *)\n(*     destruct x3; auto; inv H14. *)\n(*   } *)\n(*   subst x3. *)\n(*   assert (x4 = E0). *)\n(*   { *)\n(*     destruct x4; auto; inv H9. *)\n(*   } *)\n(*   subst x4. *)\n(*   replace E0 with (E0 ** E0) by auto. *)\n(*   inv H6. inv H22. *)\n(*   econstructor; eauto. *)\n(*   rewrite E0_right. eauto. *)\n(*   replace E0 with (E0 ** E0) by auto. *)\n(*   inv H8. inv H24. *)\n(*   assert (t1 = E0). *)\n(*   { *)\n(*     destruct t1; inv H16; auto. *)\n(*   } *)\n(*   subst t1. *)\n(*   assert (t0 = E0). *)\n(*   { *)\n(*     destruct t0; inv H15; eauto. *)\n(*   } *)\n(*   subst t0. *)\n(*   econstructor; eauto. *)\n(* Qed. *)\n\n(* Need other way too *)\n(* step_t to step_through *)\n(* TODO: make this *)\n\nDefinition ends_in_not_label (c : code) :=\n  forall i,\n    find_instr (zlen c - 1) c = Some i ->\n    ~ is_any_label i.\n\n\nDefinition no_calls (c : code) :=\n  forall z i,\n    find_instr z c = Some i ->\n    ~ is_call_return i.\n\nDefinition no_trace (i : instruction) :=\n  match i with\n    | Pbuiltin _ _ _ => False\n    | Pannot _ _ => False\n    | _ => True\n  end.\n\nDefinition no_trace_code (c : code) :=\n  forall z i,\n    find_instr z c = Some i ->\n    no_trace i.\n\n\nDefinition only_forward_jumps_lab (l : label) (c : code) : Prop :=\n  forall z i,\n    find_instr z c = Some i ->\n    labeled_jump i l ->\n    forall z',\n      find_instr z' c = Some (Plabel l) ->\n      z' > z.\n\nDefinition only_forward_jumps (c : code) : Prop :=\n  no_calls c /\\ no_trace_code c /\\\n  forall l, only_forward_jumps_lab l c .\n\nDefinition pat_at_n (pat : code) (n : nat) (c : code) : Prop :=\n  c = (firstn n c) ++ pat ++ (skipn (n + length pat) c).\n\nLemma skipn_len :\n  forall {A} (l1 l2 : list A),\n    skipn (length l1) (l1 ++ l2) = l2.\nProof.\n  induction l1; intros.\n  * simpl. reflexivity.\n  * simpl. apply IHl1.\nQed.\n\nLemma firstn_len :\n  forall {A} (l1 l2 : list A),\n    firstn (length l1) (l1 ++ l2) = l1.\nProof.\n  induction l1; intros.\n  * simpl. reflexivity.\n  * simpl. rewrite IHl1. reflexivity.\nQed.\n\nLemma pat_at_n_sane :\n  forall c1 c2 pat,\n    pat_at_n pat (length c1) (c1 ++ pat ++ c2).\nProof.\n  induction c1; intros; simpl.\n  * unfold pat_at_n.\n    simpl. rewrite skipn_len.\n    reflexivity.\n  * unfold pat_at_n. simpl.\n    f_equal. rewrite <- app_length.\n    rewrite <- app_ass. rewrite skipn_len.\n    rewrite app_ass.\n    rewrite firstn_len.\n    reflexivity.\nQed.\n\nLemma nat_zlen :\n  forall {A} (l : list A),\n    nat_of_Z (zlen l) = length l.\nProof.\n  induction l; intros.\n  * simpl. reflexivity.\n  * simpl. \n    rewrite SuccNat2Pos.id_succ.\n    reflexivity.\nQed.\n\nDefinition ends_in_not_call (c : code) : Prop :=\n  exists c',\n    exists i,\n      c = c' ++ i :: nil /\\ ~ is_call_return i.\n\nDefinition is_label_instr (i : instruction) (l : label) : Prop :=\n  match i with\n    | Plabel l' => l = l'\n    | Pjmp_l l' => l = l'\n    | Pjcc _ l' => l = l'\n    | Pjcc2 _ _ l' => l = l'\n    | Pjmptbl _ tbl => In l tbl\n    | _ => False\n  end.\n\nDefinition only_labels (c : code) (labs : list label) : Prop := \n  forall z i,\n    find_instr z c = Some i ->\n    forall l,\n      is_label_instr i l ->\n      In l labs.\n\nDefinition no_labels (c : code) (labs : list label ) : Prop :=\n  forall z i,\n    find_instr z c = Some i ->\n    forall l,\n      is_label_instr i l ->\n      ~ In l labs.\n\nFixpoint get_labels (c : code) : list label :=\n  match c with\n    | nil => nil\n    | Plabel l :: r => l :: get_labels r\n    | Pjmp_l l :: r => l :: get_labels r\n    | Pjcc _ l :: r => l :: get_labels r\n    | Pjcc2 _ _ l :: r => l :: get_labels r\n    | Pjmptbl _ tbl :: r => tbl ++ get_labels r\n    | _ :: r => get_labels r\n  end.\n\nLemma step_t_labeled_jump :\n  forall instr rs m rs' m' bits b ofs f md md',\n    step_t (instr :: nil) ge (State_bits rs m md) E0 (State_bits rs' m' md') ->\n    (exists l, labeled_jump instr l) ->\n    rs PC = Values.Vint bits ->\n    psur md bits = Some (b,ofs) ->\n    Genv.find_funct_ptr ge b = Some (Internal f) ->\n    (exists i l, goto_label_bits md f l b rs m = Nxt rs' m' md' /\\\n                 find_instr (Int.unsigned ofs) (fn_code f) = Some i /\\\n                 is_label_instr i l\n    )\n    \\/ (State_bits (nextinstr rs) m md = State_bits rs' m' md').\nProof.\n  intros.\n  break_exists.\n  destruct instr; simpl in H0; try inv_false; subst.\n  * inv H. inv H11.\n    inv H6. invs; repeat unify_PC; repeat unify_psur;\n            unfold fundef in *;\n            repeat unify_find_funct_ptr;\n            find_one_instr.\n    left. \n    simpl in H23.\n    eexists; eexists; split; eauto.\n    split. rewrite H17. rewrite H10.\n    rewrite find_instr_append_head by omega.\n    simpl. reflexivity. simpl. reflexivity.\n  * inv H. inv H11.\n    inv H6. invs; repeat unify_PC; repeat unify_psur;\n            unfold fundef in *;\n            repeat unify_find_funct_ptr;\n            find_one_instr.\n    simpl in H23.\n    break_match_hyp; inv H23.\n    break_match_hyp; inv H0.\n    left. \n    eexists; eexists; split; eauto.\n    split. rewrite H17. rewrite H10.\n    rewrite find_instr_append_head by omega.\n    simpl. reflexivity. simpl. reflexivity.\n    right. reflexivity.\n  * inv H. inv H11.\n    inv H6. invs; repeat unify_PC; repeat unify_psur;\n            unfold fundef in *;\n            repeat unify_find_funct_ptr;\n            find_one_instr.\n    simpl in H23.\n    break_match_hyp; inv H23.\n    break_match_hyp; inv H0.\n    break_match_hyp; inv H2.\n    break_match_hyp; inv H0.\n    left. \n    eexists; eexists; split; eauto.\n    split. rewrite H17. rewrite H10.\n    rewrite find_instr_append_head by omega.\n    simpl. reflexivity. simpl. reflexivity.\n    right. reflexivity.\n    break_match_hyp; inv H2.\n    right. reflexivity.    \n  * inv H. inv H12.\n    inv H7. invs; repeat unify_PC; repeat unify_psur;\n            unfold fundef in *;\n            repeat unify_find_funct_ptr;\n            find_one_instr.\n    simpl in H24.\n    repeat break_match_hyp; try st_inv.\n    left. \n    eexists; eexists; split; eauto.\n    split. rewrite H11. rewrite H18.\n    rewrite find_instr_append_head by omega.\n    simpl. reflexivity. simpl.\n    app list_nth_z_in Heqo.\nQed.\n\nLemma step_through_at :\n  forall z c ge st t st',\n    step_through z c ge st t st' ->\n    at_code z c 0 ge st.\nProof.\n  intros. inv H; eauto.\nQed.\n\nLemma step_through_at_end :\n  forall ge z c st t st',\n    step_through z c ge st t st' ->\n    at_code_end z c ge st'.\nProof.\n  intros. inv H.\n  eauto. eauto.\nQed.\n\nLemma star_to_step :\n  forall z c ge st t st',\n    star (step_in z c) ge st t st' ->\n    star step_bits ge st t st'.\nProof.\n  induction 1; intros.\n  eapply star_refl; eauto.\n  inv H. eapply star_left; eauto.\nQed.\n\nLemma step_through_plus_step :\n  forall z c ge st t st',\n    step_through z c ge st t st' ->\n    plus (step_bits) ge st t st'.\nProof.\n  intros. inv H.\n  eapply plus_one; eauto.\n  rewrite st_in_eq in H3. break_and.\n  app star_to_step H.\n  eapply plus_left; eauto.\n  eapply star_right; eauto.\nQed.\n\n(* should this be here? Probably not *)\n(* will we move it? Probably not *)\nLemma no_ptr_preserved_step_through:\n  forall z c rs m t rs' m' md md',\n    step_through z c (Genv.globalenv p) (State_bits rs m md) t (State_bits rs' m' md') ->\n    (no_ptr_regs rs /\\ no_ptr_mem m) ->\n    no_ptr_regs rs' /\\ no_ptr_mem m'.\nProof.\n  intros. inv H.\n  break_and.\n  eapply NoPtr.no_ptr_regs_preserved in H2; eauto.\n\n  rewrite st_in_eq in H4. break_and.\n  app star_to_step H.\n  destruct stB. destruct stC.\n\n  clear H6.\n  break_and.\n  app NoPtr.no_ptr_regs_preserved H3.\n  eapply NoPtr.no_ptr_regs_preserved_star in H; try reflexivity; try assumption.\n  app NoPtr.no_ptr_regs_preserved H5;\n    break_and; eauto.\nQed.\n\nLemma at_code_to_start :\n  forall c z ofs rs m md,\n    at_code z c ofs ge (State_bits rs m md) ->\n    exists z' i,\n      at_code z' (i :: nil) 0 ge (State_bits rs m md) /\\ In i c.\nProof.\n  induction c; intros.\n\n  inv H.\n  inv H5.\n  unfold zlen in *.\n  simpl in *.\n  omega.\n\n  inv H.\n  assert (ofs = 0 \\/ ofs > 0) by omega.\n  break_or.\n\n  exists (zlen c1).\n  exists a.\n  split.\n  econstructor; eauto.\n  simpl in *. eauto.\n  simpl. left. reflexivity.\n\n  assert (at_code (zlen (c1 ++ a :: nil)) c (ofs - 1) ge (State_bits rs m md)).\n  {\n    econstructor; eauto.\n    rewrite zlen_app.\n    rewrite zlen_cons.\n    simpl.\n    omega.\n    rewrite zlen_cons in *.\n    omega.\n    \n    rewrite H12.\n    repeat rewrite app_ass.\n    simpl.\n    eauto.\n  }\n  \n  app IHc H.\n  break_and.\n  eexists.\n  eexists.\n  split; eauto.\n  simpl.\n  right.\n  auto.\nQed.\n\nLemma step_at_step_t' :\n  forall z c ofs st st' t,\n    at_code z c ofs ge st ->\n    step_bits ge st t st' ->\n    exists i,\n      step_t (i :: nil) ge st t st' /\\ In i c.\nProof.\n  intros.\n  destruct st.\n  apply at_code_to_start in H.\n  destruct H as (z').\n  destruct H as (i).\n  exists i.\n  split.\n  replace t with (t ** E0) by (apply E0_right).\n  econstructor.\n  break_and.\n  eassumption.\n  eassumption.\n  constructor.\n  break_and.\n  assumption.\nQed.\n\nLemma straightline_step_t :\n  forall ge rs m rs' m' i t bits b ofs f md md',\n    step_t (i :: nil) ge (State_bits rs m md) t (State_bits rs' m' md') ->\n    straightline i ->\n    rs PC = Values.Vint bits ->\n    psur md bits = Some (b,ofs) ->\n    Genv.find_funct_ptr ge b = Some (Internal f) ->\n    exec_instr_bits ge md f i b rs m = Nxt rs' m' md'.\nProof.\n  intros. inv H. inv H6.\n  inv H12.\n  inv H7; repeat unify_PC; repeat unify_psur; repeat unify_find_funct_ptr;\n  try find_one_instr; eauto; simpl in *; try inv_false.\nQed.\n\nLemma straightlineish_step_t :\n  forall ge rs m rs' m' i t bits b ofs f md md',\n    step_t (i :: nil) ge (State_bits rs m md) t (State_bits rs' m' md') ->      \n    rs' PC = (nextinstr rs) PC ->\n    rs PC = Values.Vint bits ->\n    psur md bits = Some (b,ofs) ->\n    Genv.find_funct_ptr ge b = Some (Internal f) ->\n    no_trace i ->\n    exec_instr_bits ge md f i b rs m = Nxt rs' m' md'.\nProof.\n  intros.\n  rename H4 into Hno_trace.\n  inv H. inv H6.\n  inv H12.\n  inv H7; repeat unify_PC; repeat unify_psur; repeat unify_find_funct_ptr;\n  try find_one_instr; eauto; simpl in *; try inv_false.        \nQed.  \n\nLemma straightlineish_step_fundef :\n  forall ge rs m rs' m' i t bits b ofs md md',\n    step_t (i :: nil) ge (State_bits rs m md) t (State_bits rs' m' md') ->\n    rs' PC = (nextinstr rs) PC ->\n    rs PC = Values.Vint bits ->\n    psur md bits = Some (b,ofs) ->\n    exists f,\n      Genv.find_funct_ptr ge b = Some (Internal f).\nProof.\n  intros. inv H. inv H11.\n  inv H5. unify_PC. unify_psur. eauto.\nQed.  \n\nLemma straightline_step_fundef :\n  forall ge rs m rs' m' i t bits b ofs md md',\n    step_t (i :: nil) ge (State_bits rs m md) t (State_bits rs' m' md') ->\n    straightline i ->\n    rs PC = Values.Vint bits ->\n    psur md bits = Some (b,ofs) ->\n    exists f,\n      Genv.find_funct_ptr ge b = Some (Internal f).\nProof.\n  intros. inv H. inv H11.\n  inv H5. unify_PC. unify_psur. eauto.\nQed.  \n\n(* (* No longer true *) *)\n(* Lemma straightlineish_exec : *)\n(*   forall rs rs' bits b ofs md, *)\n(*     rs PC = Vint bits -> *)\n(*     psur md bits = (b,ofs) -> *)\n(*     rs' PC = (nextinstr rs) PC -> *)\n(*     exists bits', *)\n(*       rs' PC = Vint bits' /\\ psur bits' = (b,Int.add ofs Int.one). *)\n(* Proof. *)\n(*   intros. *)\n(*   P preg_simpl_hyp nextinstr. *)\n(*   rewrite H in H1. *)\n(*   simpl in H1.     *)\n(*   eexists; split; eauto. *)\n(*   eapply psur_add; eauto. *)\n(* Qed. *)\n\nLemma at_code_to_nil:\n  forall z x c ge st,\n    at_code z (x :: c) 0 ge st ->\n    at_code z (x :: nil) 0 ge st.\nProof.\n  intros.\n  inv H.\n  econstructor.\n  eauto.\n  eauto.\n  eauto.\n  eauto.\n  eauto.\n  instantiate (1 := (c ++ c2)).\n  eauto.\nQed.\n  \n\nLemma at_code_straightlineish_end :\n  forall z x rs rs' m m' t c md md',\n    True ->\n    rs' PC = (nextinstr rs) PC ->\n    at_code z (x :: c) 0 (Genv.globalenv p) (State_bits rs m md) ->\n    step_bits (Genv.globalenv p) (State_bits rs m md) t (State_bits rs' m' md') ->\n    at_code_end z (x :: nil) (Genv.globalenv p) (State_bits rs' m' md').\nProof.\n  intros.\n  apply at_code_to_nil in H1.\n  inv H1.\n  assert (Hmatch : match_metadata md m) by (invs; auto).\n  assert (Hgp: global_perms (Genv.globalenv p) m) by (invs; auto).\n\n  preg_simpl_hyp H0.\n  rewrite H6 in *.\n  simpl in H0.\n\n  app md_extends_step H2.\n  app step_match_metadata H1.\n  app global_perms_step H3.\n\n  assert (Hfind : exists x, find_instr (Int.unsigned i) (fn_code fd) = Some x). {\n    rewrite H8. rewrite H15. rewrite find_instr_append_head by omega.\n    simpl. eauto.\n  }\n\n  break_exists.\n  \n  assert (Hi : Int.unsigned (Int.add i Int.one) = Int.unsigned i + 1). {\n    rewrite Int.add_unsigned. rewrite Int.unsigned_one.\n    erewrite unsigned_repr_PC; eauto. left.\n    instantiate (1 := x0).\n    replace (Int.unsigned i + 1 - 1) with (Int.unsigned i) by omega.\n    eauto.\n  }\n  idtac.  (* damnit indenting *)\n  \n  \n  name H7 Hpsur.\n  eapply psur_add_one in Hpsur; eauto.\n  econstructor; eauto.\n\n  rewrite Hi. rewrite zlen_cons in *. simpl in *. omega.\n  unfold in_code_range.\n  unfold fundef in *.\n  collapse_match. rewrite H8.\n  rewrite H15.\n  repeat rewrite zlen_app.\n  repeat rewrite zlen_cons.\n  replace (@zlen instruction nil) with 0 by auto.\n  name (zlen_nonneg _ c1) zlnc1.\n  name (zlen_nonneg _ c2) zlnc2.\n  \n  omega.\n  eapply in_range_PC; eauto.\nQed.\n  \nLemma at_code_straightlineish :\n  forall z x rs rs' m m' t c md md',\n    True ->\n    rs' PC = (nextinstr rs) PC ->\n    at_code z (x :: c) 0 (Genv.globalenv p) (State_bits rs m md) ->\n    step_bits (Genv.globalenv p) (State_bits rs m md) t (State_bits rs' m' md') ->\n    zlen c > 0 ->\n    at_code (z + 1) c 0 (Genv.globalenv p) (State_bits rs' m' md').\nProof.\n  intros.\n  name H1 Ha.\n  apply at_code_to_nil in H1.\n  rename H3 into Hz.\n  inv H1.\n\n  replace (zlen c1 + 1) with (zlen (c1 ++ x :: nil)) by (rewrite zlen_app;\n                                                         rewrite zlen_cons;\n                                                         simpl; omega).\n\n  assert (Hmatch : match_metadata md m) by (invs; auto).\n  assert (Hgp: global_perms (Genv.globalenv p) m) by (invs; auto).\n\n  app md_extends_step H2.\n  app step_match_metadata H1.\n  app global_perms_step H3.\n\n  assert (Hfind : exists x, find_instr (Int.unsigned i) (fn_code fd) = Some x). {\n    rewrite H8. rewrite H15. rewrite find_instr_append_head by omega.\n    simpl. eauto.\n  }\n\n  break_exists.\n  \n  assert (Hi : Int.unsigned (Int.add i Int.one) = Int.unsigned i + 1). {\n    rewrite Int.add_unsigned. rewrite Int.unsigned_one.\n    erewrite unsigned_repr_PC; eauto. left.\n    instantiate (1 := x0).\n    replace (Int.unsigned i + 1 - 1) with (Int.unsigned i) by omega.\n    eauto.\n  }\n  idtac.  (* damnit indenting *)\n\n  name H7 Hpsur.\n  eapply psur_add_one in H7; eauto.\n  \n  preg_simpl_hyp H0.\n  rewrite H6 in H0.\n  simpl in H0.\n\n  \n  inv Ha. repeat unify_PC. repeat unify_psur.\n  unify_find_funct_ptr.\n  \n  econstructor; eauto; try omega.\n  rewrite Hi. rewrite (zlen_app). rewrite zlen_cons. simpl. omega.\n  rewrite H24 in H15. replace ((x :: c) ++ c4) with ((x :: nil) ++ (c ++ c4)) in H15 by (simpl; auto).\n  eapply list_eq_middle_therefore_eq in H15; eauto. break_and; subst.\n  rewrite H24. simpl. repeat rewrite app_ass. simpl. reflexivity.\n\n  unfold in_code_range. unfold fundef in *.\n  collapse_match.\n  \n  rewrite H8. rewrite H15. repeat rewrite zlen_app. repeat rewrite zlen_cons.\n  replace (@zlen instruction nil) with 0 by auto.\n  name (zlen_nonneg _ c1) zlnc1.\n  name (zlen_nonneg _ c2) zlnc2.\n  omega.\n  eapply in_range_PC; eauto.\nQed.\n\n\nLemma step_t_md_extends :\n  forall l ge rs m md t rs' m' md',\n    step_t l ge (State_bits rs m md) t (State_bits rs' m' md') ->\n    md_extends md md'.\nProof.\n  induction l; intros.\n  inv H. econstructor.\n  inv H. destruct st'.\n  app IHl H8.\n  app md_extends_step H3.\n  eapply ex_trans; eauto.\nQed.\n    \n\n\nLemma step_t_md :\n  forall l ge rs m md t rs' m' md',\n    l <> nil ->\n    step_t l ge (State_bits rs m md) t (State_bits rs' m' md') ->\n    match_metadata md m /\\ match_metadata md' m'.\nProof.\n  induction l; intros; try congruence.\n  inv H0. destruct l.\n  * inv H9. eapply step_md; eauto.\n  * destruct st'. app IHl H9; try congruence.\n    break_and. app step_md H4; intuition idtac.\nQed.\n\n\nLemma step_t_gp :\n  forall l ge rs m md t rs' m' md',\n    l <> nil ->\n    step_t l ge (State_bits rs m md) t (State_bits rs' m' md') ->\n    global_perms ge m /\\ global_perms ge m'.\nProof.\n  induction l; intros.\n  congruence.\n  inv H0. destruct l.\n  * inv H9. eapply step_gp; eauto.\n  * destruct st'. app IHl H9; try congruence.\n    break_and.\n    app step_gp H4; intuition idtac.\nQed.\n\n\nEnd ST_IN.", "meta": {"author": "uwplse", "repo": "peek", "sha": "4943735ed39fd5ddadf2c28fc2ada31504228561", "save_path": "github-repos/coq/uwplse-peek", "path": "github-repos/coq/uwplse-peek/peek-4943735ed39fd5ddadf2c28fc2ada31504228561/compcert/peek/StepIn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442250928250374, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.27958174944763725}}
{"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 MemoryRel.\nRequire Import SmallStep.\nRequire Import Fulfilled.\nRequire Import ReorderPromise.\nRequire Import Race.\nRequire Import PromiseConsistent.\n\nSet Implicit Arguments.\n\nInductive pi_step withprm: Ident.t -> ThreadEvent.t -> Configuration.t*Configuration.t -> Configuration.t*Configuration.t -> Prop :=\n| pi_step_step\n    e tid cS1 cT1 cS2 cT2\n    (STEPT: small_step withprm tid e cT1 cT2)\n    (STEPS: if ThreadEvent.is_promising e\n            then cS1 = cS2\n            else small_step false tid e cS1 cS2)\n    (LANGMATCH: \n     option_map fst (IdentMap.find tid cS2.(Configuration.threads)) =\n     option_map fst (IdentMap.find tid cT2.(Configuration.threads)))\n    (NOWR: forall loc from ts val rel ord tid' ts'\n             (WRITE: ThreadEvent.is_writing e = Some (loc, from, ts, val, rel, ord) \\/\n                     ThreadEvent.is_reading e = Some (loc, ts, val, rel, ord))\n             (TIDNEQ: tid' <> tid),\n           ~ Threads.is_promised tid' loc ts' cT1.(Configuration.threads)):\n  pi_step withprm tid e (cS1,cT1) (cS2,cT2)\n.\nHint Constructors pi_step.\n\nDefinition pi_step_evt withprm tid cST1 cST2: Prop :=\n  union (pi_step withprm tid) cST1 cST2.\nHint Unfold pi_step_evt.\n\nDefinition pi_step_all withprm cST1 cST2: Prop :=\n  union (pi_step_evt withprm) cST1 cST2.\nHint Unfold pi_step_all.\n\nInductive pi_step_except withprm (tid_except:Ident.t) cST1 cST2: Prop :=\n| pi_step_except_intro tid\n    (PI_STEP: pi_step_evt withprm tid cST1 cST2)\n    (TID: tid <> tid_except)\n.\nHint Constructors pi_step_except.\n\nDefinition remove_promise (th: {lang : language & Language.state lang} * Local.t) :=\n  (th.(fst), Local.mk th.(snd).(Local.tview) Memory.bot).\n\nInductive pi_wf cmp: Configuration.t*Configuration.t -> Prop :=\n| pi_wf_intro cS cT\n    (WFS: Configuration.wf cS)\n    (WFT: Configuration.wf cT)\n    (THS: cS.(Configuration.threads) = IdentMap.map remove_promise cT.(Configuration.threads))\n    (SC: cS.(Configuration.sc) = cT.(Configuration.sc))\n    (LR: forall loc ts from val rel1\n           (IN: Memory.get loc ts cS.(Configuration.memory) = Some (from, Message.mk val rel1)),\n         <<IN: exists rel2, Memory.get loc ts cT.(Configuration.memory) = Some (from, Message.mk val rel2) /\\ <<CMP: cmp loc ts rel1 rel2>>>> /\\\n         <<NOT: forall tid, ~Threads.is_promised tid loc ts cT.(Configuration.threads)>>)\n    (RL: forall loc ts from val rel2\n           (IN: Memory.get loc ts cT.(Configuration.memory) = Some (from, Message.mk val rel2))\n           (NOT: forall tid, ~Threads.is_promised tid loc ts cT.(Configuration.threads)),\n         exists rel1, Memory.get loc ts cS.(Configuration.memory) = Some (from, Message.mk val rel1) /\\ <<CMP: cmp loc ts rel1 rel2>>):\n  pi_wf cmp (cS,cT)\n.\nHint Constructors pi_wf.\n\nInductive pi_consistent: Configuration.t*Configuration.t -> Prop :=\n| pi_consistent_intro cS1 cT1\n  (CONSIS:\n    forall tid cS2 cT2 lst2 lc2 loc ts from msg\n    (STEPS: rtc (pi_step_except false tid) (cS1,cT1) (cS2,cT2))\n    (THREAD: IdentMap.find tid cT2.(Configuration.threads) = Some (lst2, lc2))\n    (PROMISE: Memory.get loc ts lc2.(Local.promises) = Some (from, msg))\n    (PRCONSIS: forall tid0, promise_consistent_th tid0 cT2),\n  exists cS3 e val ord,\n    <<STEPS: rtc (small_step_evt false tid) cS2 cS3>> /\\\n    <<PROEVT: Configuration_program_event cS3 tid e>> /\\\n    <<EVENT: ProgramEvent.is_writing e = Some (loc, val, ord)>> /\\\n    <<ORD: Ordering.le ord Ordering.relaxed>>):\n  pi_consistent (cS1, cT1).\nHint Constructors pi_consistent.\n\nDefinition pi_pre_proj (pre: option (Configuration.t*Configuration.t*ThreadEvent.t)) := \n  option_map (fun p => (p.(fst).(snd),p.(snd))) pre.\n\nLemma pi_step_future\n      tid cST1 cST2 withprm cmp\n      (WF1: pi_wf cmp cST1)\n      (REFL: forall l t r, cmp l t r r)\n      (STEP: pi_step_evt withprm tid cST1 cST2):\n  <<WF2: pi_wf cmp cST2>> /\\\n  <<FUTURES: Memory.future cST1.(fst).(Configuration.memory) cST2.(fst).(Configuration.memory)>> /\\\n  <<FUTURET: Memory.future cST1.(snd).(Configuration.memory) cST2.(snd).(Configuration.memory)>>.\nProof.\n  inv WF1. inv STEP. inv USTEP. splits; cycle 1. \n  - destruct (ThreadEvent.is_promising e).\n    + subst. ss. econs.\n    + eapply small_step_future in STEPS; eauto; des; ss.\n  - eapply small_step_future in STEPT; eauto; des; ss.\n  - assert (WFT2: Configuration.wf cT2).\n    { by eapply small_step_future, STEPT. }\n    assert (WFS2: Configuration.wf cS2).\n    { destruct (ThreadEvent.is_promising e); [by inv STEPS|].\n      by eapply small_step_future, STEPS. }\n    assert (STEPS' :=STEPS).\n\n    generalize STEPT. intro STEPT'.\n    destruct cS, cT. inv STEPT. guardH PFREE.\n    inv STEP; [inv STEP0|inv STEP0; inv LOCAL]; ss.\n    { subst. inv LOCAL. econs; eauto.\n      - apply IdentMap.eq_leibniz.\n        ii. setoid_rewrite IdentMap.map_add.\n        destruct (Loc.eq_dec y tid) eqn: TIDEQ.\n        + subst. setoid_rewrite IdentMap.Properties.F.map_o.\n          rewrite IdentMap.gss, TID. done.\n        + by rewrite IdentMap.gso.\n      - s. i. exploit LR; eauto. i. des. inv PROMISE.\n        + erewrite Memory.add_o; eauto. condtac; ss; i.\n          * des. subst. exploit Memory.add_get0; eauto. congr.\n          * guardH o. esplits; eauto.\n            ii. inv H. revert TID0. rewrite IdentMap.gsspec. condtac; ss.\n            { i. inv TID0. apply inj_pair2 in H1. subst. ss.\n              revert PROMISES0. erewrite Memory.add_o; eauto. condtac; ss. i.\n              eapply NOT. econs; eauto.\n            }\n            { i. eapply NOT. econs; eauto. }\n        + erewrite Memory.split_o; eauto. repeat condtac; ss; i.\n          * des. subst. exploit Memory.split_get0; eauto. i. des. congr.\n          * guardH o. des. subst. esplits; eauto.\n            { exfalso. eapply NOT. econs; eauto. eapply Memory.split_get0. eauto. }\n            ii. inv H. revert TID0. rewrite IdentMap.gsspec. condtac; ss.\n            { i. inv TID0. apply inj_pair2 in H1. subst. ss.\n              revert PROMISES0. erewrite Memory.split_o; eauto. repeat condtac; ss. i. inv PROMISES0.\n              eapply NOT. econs; eauto. eapply Memory.split_get0; eauto.\n            }\n            { i. eapply NOT. econs; eauto. }\n          * guardH o. guardH o0. esplits; eauto.\n            ii. inv H. revert TID0. rewrite IdentMap.gsspec. condtac; ss.\n            { i. inv TID0. apply inj_pair2 in H1. subst. ss.\n              revert PROMISES0. erewrite Memory.split_o; eauto. repeat condtac; ss. i.\n              eapply NOT. econs; eauto.\n            }\n            { i. eapply NOT. econs; eauto. }\n        + erewrite Memory.lower_o; eauto. condtac; ss; i.\n          * des. subst. exploit Memory.lower_get0; try exact PROMISES; eauto. i.\n            exfalso. eapply NOT. econs; eauto.\n          * guardH o. esplits; eauto.\n            ii. inv H. revert TID0. rewrite IdentMap.gsspec. condtac; ss.\n            { i. inv TID0. apply inj_pair2 in H1. subst. ss.\n              revert PROMISES0. erewrite Memory.lower_o; eauto. repeat condtac; ss. i.\n              eapply NOT. econs; eauto.\n            }\n            { i. eapply NOT. econs; eauto. }\n      - s. i. revert IN. inv PROMISE.\n        + erewrite Memory.add_o; eauto. condtac; ss.\n          * i. des. inv IN. exfalso. eapply NOT. econs.\n            { rewrite IdentMap.gss. eauto. }\n            { s. erewrite Memory.add_o; eauto. condtac; ss. }\n          * guardH o. i. eapply RL; 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 NOT. econs.\n              - rewrite IdentMap.gss. eauto.\n              - s. erewrite Memory.add_o; eauto. condtac; [|eauto]; ss.\n            }\n            { eapply NOT. econs; eauto.\n              rewrite IdentMap.gso; eauto.\n            }\n        + erewrite Memory.split_o; eauto. repeat condtac; ss.\n          * i. des. inv IN. exfalso. eapply NOT. econs.\n            { rewrite IdentMap.gss. eauto. }\n            { s. erewrite Memory.split_o; eauto. condtac; ss. }\n          * guardH o. i. des. inv IN.\n            exfalso. eapply NOT. econs.\n            { rewrite IdentMap.gss. eauto. }\n            { s. erewrite Memory.split_o; eauto. repeat condtac; [|eauto|]; ss. }\n          * guardH o. i. eapply RL; 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 NOT. econs.\n              - rewrite IdentMap.gss. eauto.\n              - s. erewrite Memory.split_o; eauto. repeat condtac; [| |eauto]; ss.\n            }\n            { eapply NOT. econs; eauto.\n              rewrite IdentMap.gso; eauto.\n            }\n        + erewrite Memory.lower_o; eauto. condtac; ss.\n          * i. des. inv IN. exfalso. eapply NOT. econs.\n            { rewrite IdentMap.gss. eauto. }\n            { s. erewrite Memory.lower_o; eauto. condtac; ss. }\n          * guardH o. i. eapply RL; 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 NOT. econs.\n              - rewrite IdentMap.gss. eauto.\n              - s. erewrite Memory.lower_o; eauto. condtac; [|eauto]; ss.\n            }\n            { eapply NOT. econs; eauto.\n              rewrite IdentMap.gso; eauto.\n            }\n    }\n    { inv STEPS.\n      inv STEP; [inv STEP0|inv STEP0; inv LOCAL]; ss. econs; eauto; ss.\n      - apply IdentMap.eq_leibniz. ii.\n        setoid_rewrite IdentMap.Properties.F.map_o in TID0.\n        rewrite TID in TID0. inv TID0. depdes H1.\n        setoid_rewrite IdentMap.map_add.\n        rewrite !IdentMap.gss in LANGMATCH. depdes LANGMATCH.\n        destruct (Loc.eq_dec y tid) eqn: TIDEQ.\n        + subst. by rewrite !IdentMap.gss.\n        + by rewrite !IdentMap.gso.\n      - ii. exploit LR; eauto. i; des.\n        esplits; eauto.\n        ii. eapply (NOT tid0). inv H. \n        destruct (Ident.eq_dec tid0 tid) eqn: EQ.\n        { subst. rewrite IdentMap.gss in TID1. inv TID1.\n          econs; eauto. }\n        rewrite IdentMap.gso in TID1; eauto. econs; eauto.\n      - ii. exploit RL; eauto. i; des.\n        ii. apply (NOT tid0). inv H.\n        destruct (Ident.eq_dec tid0 tid) eqn: EQ.\n        { subst. econs; eauto. rewrite IdentMap.gss.\n          rewrite TID in TID1. inv TID1. eauto. }\n        econs; eauto. rewrite IdentMap.gso; eauto.\n    }\n    { inv STEPS.\n      inv STEP; [inv STEP0|inv STEP0; inv LOCAL]; ss. econs; eauto; ss.\n      - apply IdentMap.eq_leibniz. ii.\n        setoid_rewrite IdentMap.Properties.F.map_o in TID0.\n        rewrite TID in TID0. inv TID0. depdes H1.\n        setoid_rewrite IdentMap.map_add.\n        rewrite !IdentMap.gss in LANGMATCH. depdes LANGMATCH.\n        destruct (Loc.eq_dec y tid) eqn: TIDEQ.\n        + subst. rewrite !IdentMap.gss.\n          inv LOCAL0. inv LOCAL1. eauto.\n        + by rewrite !IdentMap.gso.\n      - inv LOCAL0. inv LOCAL1.\n        ii. exploit LR; eauto. i; des.\n        esplits; eauto.\n        ii. eapply (NOT tid0). inv H. \n        destruct (Ident.eq_dec tid0 tid) eqn: EQ.\n        { subst. rewrite IdentMap.gss in TID1. inv TID1.\n          econs; eauto. }\n        rewrite IdentMap.gso in TID1; eauto. econs; eauto.\n      - inv LOCAL0. inv LOCAL1.\n        ii. exploit RL; eauto. i; des.\n        ii. apply (NOT tid0). inv H.\n        destruct (Ident.eq_dec tid0 tid) eqn: EQ.\n        { subst. rewrite TID1 in TID. inv TID. depdes H1. destruct lc1. \n          ss. econs; eauto. \n          - rewrite IdentMap.gss. s. reflexivity. \n          - eauto. }\n        econs; eauto. rewrite IdentMap.gso; eauto.\n    }\n    { inv STEPS.\n      inv STEP; [inv STEP0|inv STEP0; inv LOCAL]; ss. econs; eauto; ss.\n      - apply IdentMap.eq_leibniz. ii.\n        setoid_rewrite IdentMap.Properties.F.map_o in TID0.\n        rewrite TID in TID0. inv TID0. depdes H1.\n        setoid_rewrite IdentMap.map_add.\n        rewrite !IdentMap.gss in LANGMATCH. depdes LANGMATCH.\n        destruct (Loc.eq_dec y tid) eqn: TIDEQ.\n        + subst. rewrite !IdentMap.gss.\n          inv LOCAL0. inv LOCAL1.\n          unfold remove_promise. ss.\n          replace promises0 with Memory.bot; eauto.\n          exploit (@small_step_promise_decr_bot tid tid); [apply STEPS'|..].\n          { ss. setoid_rewrite IdentMap.Properties.F.map_o. by rewrite TID. }\n          { s. rewrite IdentMap.gss. eauto. }\n          { s. eauto. }\n          eauto.\n        + by rewrite !IdentMap.gso.\n      - inv LOCAL0. inv LOCAL1. eauto.\n      - s. i.\n        hexploit writing_small_step_fulfilled_backward; try exact STEPS'; ss; eauto.\n        { econs; eauto. s. ii. inv H. revert TID1.\n          rewrite IdentMap.gsspec. condtac.\n          - i. inv TID1.\n            exploit (@small_step_promise_decr_bot tid tid); [apply STEPS'|..].\n            { ss. setoid_rewrite IdentMap.Properties.F.map_o. by rewrite TID. }\n            { s. rewrite IdentMap.gss. eauto. }\n            { s. eauto. }\n            i. rewrite x0 in *. rewrite Memory.bot_get in PROMISES. congr.\n          - rewrite IdentMap.Properties.F.map_o. unfold remove_promise.\n            destruct (UsualFMapPositive.UsualPositiveMap'.find tid0 threads0); ss.\n            i. inv TID1. rewrite Memory.bot_get in PROMISES. congr.\n        }\n        i. des.\n        + inv H. exploit LR; eauto. i. des.\n          hexploit writing_small_step_fulfilled_forward; try exact STEPT'; ss; eauto.\n          { econs; eauto. }\n          i. inv H. esplits; eauto.\n        + inv H.\n          hexploit writing_small_step_fulfilled_new; try exact STEPT'; ss; eauto.\n          i. inv H. esplits; eauto.\n      - i.\n        hexploit writing_small_step_fulfilled_backward; try exact STEPT'; ss; eauto.\n        { econs; eauto. }\n        i. des.\n        + inv H. exploit RL; eauto. i. des.\n          hexploit writing_small_step_fulfilled_forward; try exact STEPS'; ss; eauto.\n          { econs; eauto. s. ii. inv H. revert TID1.\n            rewrite IdentMap.Properties.F.map_o. unfold remove_promise.\n            destruct (UsualFMapPositive.UsualPositiveMap'.find tid0 threads0); ss.\n            i. inv TID1. rewrite Memory.bot_get in PROMISES. congr.\n          }\n          i. inv H. esplits; eauto.\n        + inv H.\n          hexploit writing_small_step_fulfilled_new; try exact STEPS'; ss; eauto.\n          i. inv H. esplits; eauto.\n    }\n    { inv STEPS.\n      inv STEP; [inv STEP0|inv STEP0; inv LOCAL]; ss. econs; eauto; ss.\n      - apply IdentMap.eq_leibniz. ii.\n        setoid_rewrite IdentMap.Properties.F.map_o in TID0.\n        rewrite TID in TID0. inv TID0. depdes H1.\n        setoid_rewrite IdentMap.map_add.\n        rewrite !IdentMap.gss in LANGMATCH. depdes LANGMATCH.\n        destruct (Loc.eq_dec y tid) eqn: TIDEQ.\n        + subst. rewrite !IdentMap.gss.\n          inv LOCAL1. inv LOCAL2. inv LOCAL0. inv LOCAL3.\n          unfold remove_promise. ss.\n          replace promises0 with Memory.bot; eauto.\n          exploit (@small_step_promise_decr_bot tid tid); [apply STEPS'|..].\n          { ss. setoid_rewrite IdentMap.Properties.F.map_o. by rewrite TID. }\n          { s. rewrite IdentMap.gss. eauto. }\n          { s. eauto. }\n          eauto.\n        + by rewrite !IdentMap.gso.\n      - inv LOCAL1. inv LOCAL2. inv LOCAL0. inv LOCAL3. eauto.\n      - s. i.\n        hexploit writing_small_step_fulfilled_backward; try exact STEPS'; ss; eauto.\n        { econs; eauto. s. ii. inv H. revert TID1.\n          rewrite IdentMap.gsspec. condtac.\n          - i. inv TID1.\n            exploit (@small_step_promise_decr_bot tid tid); [apply STEPS'|..].\n            { ss. setoid_rewrite IdentMap.Properties.F.map_o. by rewrite TID. }\n            { s. rewrite IdentMap.gss. eauto. }\n            { s. eauto. }\n            i. rewrite x0 in *. rewrite Memory.bot_get in PROMISES. congr.\n          - rewrite IdentMap.Properties.F.map_o. unfold remove_promise.\n            destruct (UsualFMapPositive.UsualPositiveMap'.find tid0 threads0); ss.\n            i. inv TID1. rewrite Memory.bot_get in PROMISES. congr.\n        }\n        i. des.\n        + inv H. exploit LR; eauto. i. des.\n          hexploit writing_small_step_fulfilled_forward; try exact STEPT'; ss; eauto.\n          { econs; eauto. }\n          i. inv H. esplits; eauto.\n        + inv H.\n          hexploit writing_small_step_fulfilled_new; try exact STEPT'; ss; eauto.\n          i. inv H. esplits; eauto.\n      - i.\n        hexploit writing_small_step_fulfilled_backward; try exact STEPT'; ss; eauto.\n        { econs; eauto. }\n        i. des.\n        + inv H. exploit RL; eauto. i. des.\n          hexploit writing_small_step_fulfilled_forward; try exact STEPS'; ss; eauto.\n          { econs; eauto. s. ii. inv H. revert TID1.\n            rewrite IdentMap.Properties.F.map_o. unfold remove_promise.\n            destruct (UsualFMapPositive.UsualPositiveMap'.find tid0 threads0); ss.\n            i. inv TID1. rewrite Memory.bot_get in PROMISES. congr.\n          }\n          i. inv H. esplits; eauto.\n        + inv H.\n          hexploit writing_small_step_fulfilled_new; try exact STEPS'; ss; eauto.\n          i. inv H. esplits; eauto.\n    }\n    { inv STEPS.\n      inv STEP; [inv STEP0|inv STEP0; inv LOCAL]; ss. econs; eauto; ss.\n      - apply IdentMap.eq_leibniz. ii.\n        setoid_rewrite IdentMap.Properties.F.map_o in TID0.\n        rewrite TID in TID0. inv TID0. depdes H1.\n        setoid_rewrite IdentMap.map_add.\n        rewrite !IdentMap.gss in LANGMATCH. depdes LANGMATCH.\n        destruct (Loc.eq_dec y tid) eqn: TIDEQ.\n        + subst. rewrite !IdentMap.gss.\n          inv LOCAL0. inv LOCAL1. eauto.\n        + by rewrite !IdentMap.gso.\n      - inv LOCAL0. inv LOCAL1. ss. \n        setoid_rewrite IdentMap.Properties.F.map_o in TID0.\n        rewrite TID in TID0. inv TID0. depdes H1. eauto.\n      - inv LOCAL0. inv LOCAL1.\n        ii. exploit LR; eauto. i; des.\n        esplits; eauto.\n        ii. eapply (NOT tid0). inv H. \n        destruct (Ident.eq_dec tid0 tid) eqn: EQ.\n        { subst. rewrite IdentMap.gss in TID1. inv TID1.\n          econs; eauto. }\n        rewrite IdentMap.gso in TID1; eauto. econs; eauto.\n      - inv LOCAL0. inv LOCAL1.\n        ii. exploit RL; eauto. i; des.\n        ii. apply (NOT tid0). inv H.\n        destruct (Ident.eq_dec tid0 tid) eqn: EQ.\n        { subst. rewrite TID1 in TID. inv TID. depdes H1. destruct lc1. \n          ss. econs; eauto. \n          - rewrite IdentMap.gss. s. reflexivity. \n          - eauto. }\n        econs; eauto. rewrite IdentMap.gso; eauto.\n    }\n    { inv STEPS.\n      inv STEP; [inv STEP0|inv STEP0; inv LOCAL]; ss. econs; eauto; ss.\n      - apply IdentMap.eq_leibniz. ii.\n        setoid_rewrite IdentMap.Properties.F.map_o in TID0.\n        rewrite TID in TID0. inv TID0. depdes H1.\n        setoid_rewrite IdentMap.map_add.\n        rewrite !IdentMap.gss in LANGMATCH. depdes LANGMATCH.\n        destruct (Loc.eq_dec y tid) eqn: TIDEQ.\n        + subst. rewrite !IdentMap.gss.\n          inv LOCAL0. inv LOCAL1. eauto.\n        + by rewrite !IdentMap.gso.\n      - inv LOCAL0. inv LOCAL1. ss. \n        setoid_rewrite IdentMap.Properties.F.map_o in TID0.\n        rewrite TID in TID0. inv TID0. depdes H1. eauto.\n      - inv LOCAL0. inv LOCAL1.\n        ii. exploit LR; eauto. i; des.\n        esplits; eauto.\n        ii. eapply (NOT tid0). inv H. \n        destruct (Ident.eq_dec tid0 tid) eqn: EQ.\n        { subst. rewrite IdentMap.gss in TID1. inv TID1.\n          econs; eauto. }\n        rewrite IdentMap.gso in TID1; eauto. econs; eauto.\n      - inv LOCAL0. inv LOCAL1.\n        ii. exploit RL; eauto. i; des.\n        ii. apply (NOT tid0). inv H.\n        destruct (Ident.eq_dec tid0 tid) eqn: EQ.\n        { subst. rewrite TID1 in TID. inv TID. depdes H1. destruct lc1. \n          ss. econs; eauto. \n          - rewrite IdentMap.gss. s. reflexivity. \n          - eauto. }\n        econs; eauto. rewrite IdentMap.gso; eauto.\n    }\nQed.\n\nLemma rtc_pi_step_future\n      cST1 cST2 withprm cmp\n      (WF1: pi_wf cmp cST1)\n      (REFL: forall l t r, cmp l t r r)\n      (STEPS: rtc (pi_step_all withprm) cST1 cST2):\n  <<WF2: pi_wf cmp cST2>> /\\\n  <<FUTURES: Memory.future cST1.(fst).(Configuration.memory) cST2.(fst).(Configuration.memory)>> /\\\n  <<FUTURET: Memory.future cST1.(snd).(Configuration.memory) cST2.(snd).(Configuration.memory)>>.\nProof.\n  revert WF1. induction STEPS; i.\n  - splits; auto; econs.\n  - inv H. exploit pi_step_future; eauto. i. des.\n    exploit IHSTEPS; eauto. i. des.\n    splits; auto; etrans; eauto.\nQed.\n\nLemma pi_step_evt_all_incl\n      withprm tid cST1 cST2\n      (STEP: pi_step_evt withprm tid cST1 cST2):\n  pi_step_all withprm cST1 cST2.\nProof.\n  econs; eauto.\nQed.\n\nLemma pi_step_except_all_incl\n      tid cST1 cST2 withprm\n      (STEP: pi_step_except withprm tid cST1 cST2):\n  pi_step_all withprm cST1 cST2.\nProof.\n  inv STEP; econs; eauto.\nQed.\n\nLemma pi_step_small_step_fst\n      tid e cST1 cST2 withprm withprm'\n      (PI_STEP: pi_step withprm tid e cST1 cST2):\n  small_opt_step withprm' tid e (fst cST1) (fst cST2).\nProof.\n  inv PI_STEP.\n  destruct (ThreadEvent.is_promising e) eqn:X.\n  - subst. ss. destruct e; inv X. econs 1. ss.\n  - econs 2. ss. destruct withprm'; ss. inv STEPS; eauto.\nQed.\n\nLemma tau_pi_steps_tau_small_steps_fst\n      tid cST1 cST2 withprm withprm'\n      (PI_STEPS: rtc (tau (pi_step withprm tid)) cST1 cST2):\n  rtc (tau (small_step withprm' tid)) (fst cST1) (fst cST2).\nProof.\n  induction PI_STEPS; eauto.\n  inv H. exploit pi_step_small_step_fst; eauto. i. inv x1.\n  - rewrite H1. ss.\n  - econs; eauto.\nQed.\n\nLemma pi_steps_small_steps_fst\n      tid cST1 cST2 withprm withprm'\n      (PI_STEPS: rtc (pi_step_evt withprm tid) cST1 cST2):\n  rtc (small_step_evt withprm' tid) (fst cST1) (fst cST2).\nProof.\n  induction PI_STEPS; eauto.\n  inv H. inv USTEP. \n  destruct (ThreadEvent.is_promising e).\n  - subst. eauto.\n  - econs; eauto. s. inv STEPS. destruct withprm'; econs; eauto 10. \nQed.\n\nLemma pi_step_small_step_snd\n      cST1 cST2 withprm tid\n      (PI_STEP: pi_step_evt withprm tid cST1 cST2):\n  small_step_evt withprm tid (snd cST1) (snd cST2).\nProof.\n  inv PI_STEP. inv USTEP. econs. eauto.\nQed.\n\nLemma pi_steps_all_small_steps_all_snd\n      cST1 cST2 withprm\n      (PI_STEPS: rtc (pi_step_all withprm) cST1 cST2):\n  rtc (small_step_all withprm) (snd cST1) (snd cST2).\nProof.\n  induction PI_STEPS; eauto.\n  inv H. exploit pi_step_small_step_snd; eauto.\nQed.\n\nLemma pi_steps_small_steps_snd\n      tid cST1 cST2 withprm\n      (PI_STEPS: rtc (pi_step_evt withprm tid) cST1 cST2):\n  rtc (small_step_evt withprm tid) (snd cST1) (snd cST2).\nProof.\n  induction PI_STEPS; eauto.\n  inv H. inv USTEP. econs; eauto.\nQed.\n\nLemma pi_steps_small_steps_snd_with_pre\n      tid cST1 cST2 pre withprm\n      (PI_STEPS: with_pre (pi_step withprm tid) cST1 pre cST2):\n  with_pre (small_step withprm tid) (snd cST1) (pi_pre_proj pre) (snd cST2).\nProof.\n  ginduction PI_STEPS; s; i; subst; eauto.\n  des. inv PSTEP. eauto.\nQed.\n\nLemma pi_steps_all_pf_steps_fst\n      cST1 cST2 withprm withprm'\n      (PI_STEPS: rtc (pi_step_all withprm) cST1 cST2):\n  rtc (small_step_all withprm') (fst cST1) (fst cST2).\nProof.\n  induction PI_STEPS; eauto.\n  inv H. inv USTEP. inv USTEP0. \n  destruct (ThreadEvent.is_promising e0) eqn: PROM.\n  - subst. eauto.\n  - econs; eauto. s. inv STEPS. destruct withprm'; econs; eauto 10. \nQed.\n\nLemma rtc_pi_step_except_find\n      tid c1 c2 withprm\n      (STEP: rtc (pi_step_except withprm tid) c1 c2):\n  IdentMap.find tid c1.(fst).(Configuration.threads) = IdentMap.find tid c2.(fst).(Configuration.threads) /\\\n  IdentMap.find tid c1.(snd).(Configuration.threads) = IdentMap.find tid c2.(snd).(Configuration.threads).\nProof.\n  induction STEP; auto. \n  des. rewrite <-IHSTEP, <-IHSTEP0.\n  inv H. inv PI_STEP. inv USTEP.\n  split; eauto using small_step_find.\n  destruct (ThreadEvent.is_promising e); subst; eauto using small_step_find.\nQed.\n\nLemma pi_step_except_withoutprm\n      tid c1 c2 withprm\n      (STEP: pi_step_except false tid c1 c2):\n  pi_step_except withprm tid c1 c2.\nProof.\n  inv STEP. inv PI_STEP. inv USTEP. inv STEPT.\n  destruct withprm; eauto 10.\nQed.\n\nLemma pi_wf_small_step_is_reading\n      e s1 s2 t1\n      withprm cmp tid l t v r o\n      (PWF: pi_wf cmp (s1, t1))\n      (STEP: small_step withprm tid e s1 s2)\n      (READING: ThreadEvent.is_reading e = Some (l, t, v, r, o)):\n  forall tid', ~ Threads.is_promised tid' l t t1.(Configuration.threads).\nProof.\n  inv STEP. inv STEP0; [inv STEP|inv STEP; inv LOCAL]; inv READING.\n  - inv LOCAL0. inv PWF. eapply LR; eauto.\n  - inv LOCAL1. inv PWF. eapply LR; eauto.\nQed.\n\nLemma pi_wf_small_step_is_promising\n      e s1 t1 t2\n      withprm cmp tid l t\n      (PWF: pi_wf cmp (s1, t1))\n      (STEP: small_step withprm tid e t1 t2)\n      (PROMISING: ThreadEvent.is_promising e = Some (l, t)):\n  Threads.is_promised tid l t t2.(Configuration.threads).\nProof.\n  inv STEP. inv STEP0; inv STEP; inv PROMISING.\n  s. econs.\n  - rewrite IdentMap.gss. eauto.\n  - inv LOCAL. s. eapply Memory.promise_get2. eauto.\nQed.\n\nLemma pi_step_except_small_step\n      withprm tid a b\n      (STEPS: rtc (pi_step_except withprm tid) a b):\n  rtc (small_step_all withprm) a.(snd) b.(snd).\nProof.\n  induction STEPS; econs; eauto.\n  inv H. inv PI_STEP. inv USTEP. econs. eauto.\nQed.\n\nLemma small_step_is_promised\n      withprm tid e c1 c2 x l t loc to\n      (STEP: small_step withprm tid e c1 c2)\n      (PROMISED: Threads.is_promised x l t c1.(Configuration.threads))\n      (PROMISING: ThreadEvent.is_promising e = Some (loc, to)):\n  Threads.is_promised x l t c2.(Configuration.threads).\nProof.\n  inv PROMISED. destruct msg.\n  inv STEP. guardH PFREE. ss.\n  destruct (Ident.eq_dec x tid); cycle 1.\n  { econs; eauto. rewrite IdentMap.gso; eauto. }\n  subst. rewrite TID in TID0. inv TID0. apply inj_pair2 in H1. subst.\n  inv STEP0; inv STEP; inv PROMISING.\n  inv LOCAL. hexploit Memory.promise_promises_get1; eauto. i. des.\n  econs; try rewrite IdentMap.gss; eauto.\nQed.\n\nLemma pi_step_remove_promises_aux\n      n tid tidex cST1 cST2 cST3\n      (WF: pi_wf loctmeq cST1)\n      (NEQ: tid <> tidex)\n      (CONSIS: forall tid0, promise_consistent_th tid0 cST3.(snd))\n      (PSTEPS1: pi_step_evt true tid cST1 cST2)\n      (PSTEP: rtcn (pi_step_except false tidex) n cST2 cST3):\n  exists n' cT3',\n    <<N: n' <= S n>> /\\\n    <<STEPS: rtcn (pi_step_except false tidex) n' cST1 (cST3.(fst),cT3')>> /\\\n    <<CONSIS: forall tid0, promise_consistent_th tid0 cT3'>>.\nProof.\n  revert_until n. induction n using strong_induction; i.\n  exploit pi_step_future; eauto. i. des.\n  inv PSTEPS1. inv USTEP. revert STEPS. condtac; cycle 1.\n  { i. destruct cST3. esplits; cycle 1.\n    - econs 2; eauto. econs; eauto. econs. econs; eauto.\n      + inv STEPS. destruct pf; ss. inv STEPT. clear PFREE0. econs; eauto.\n        destruct pf; eauto. inv STEP0; ss. inv STEP1; ss.\n      + rewrite COND. ss.\n    - ss.\n    - omega.\n  }\n  i. subst. inv PSTEP.\n  { esplits; cycle 1.\n    - econs.\n    - i. destruct (Ident.eq_dec tid0 tid).\n      + subst. eapply promise_consistent_th_small_step; eauto. by inv WF.\n      + inv STEPT. ss. specialize (CONSIS tid0).\n        ii. eapply CONSIS; eauto. s. rewrite IdentMap.gso; eauto.\n    - omega.\n  }\n  inversion A12. inv PI_STEP. inv USTEP.\n  destruct p.\n  destruct (ThreadEvent.is_lower_none e) eqn: NOTLN.\n  { destruct cST3. esplits; eauto.\n     econs; eauto.\n     econs; try apply NEQ.\n     econs; econs; rewrite ?COND; eauto. \n     inv STEPT. destruct pf; eauto.\n     inv STEP. inv STEP0. ss. by rewrite NOTLN in PF.\n  }\n\n  exploit reorder_promise_small_step; try exact STEPT; eauto.\n  { inv WF. auto. }\n  { ii. destruct (ThreadEvent.is_promising e0) eqn:E0; [by destruct e0|].\n    ii; hexploit pi_wf_small_step_is_reading; try exact WF2; eauto.\n    i. hexploit pi_wf_small_step_is_promising; try exact STEPT; eauto.\n  }\n  { apply rtcn_rtc in A23. inv A12.\n    exploit pi_step_except_small_step; eauto. i. destruct cST3. ss.\n    exploit pi_step_future; try exact WF2; eauto. i. des. inv WF0.\n    clear -CONSIS WFT x0.\n    revert WFT CONSIS. induction x0; eauto. i.\n    inv H. inv USTEP. hexploit IHx0; eauto.\n    { eapply small_step_future; eauto. }\n    i. eapply promise_consistent_th_small_step; eauto.\n  }\n  i. destruct cST3. subst. des.\n  { destruct (ThreadEvent.is_promising e0) eqn:E0; subst.\n    - exploit IH; try exact A23; try exact WF; eauto.\n      { econs; econs; eauto; ii; by des; destruct e2', e0. }\n      i. des. esplits; try exact STEPS; eauto.\n    - assert (EQ: e2' = e0). \n      { by destruct e2', e0; inv EVENT. }\n      subst. esplits; [|econs; try exact A23|]; eauto.\n      econs; eauto. econs; econs.\n      + instantiate (1 := e0).\n        inv STEP. inv STEP0; [by inv STEP|]. econs; eauto.\n      + rewrite E0. eauto.\n      + eauto.\n      + ii. eapply NOWR0; eauto.\n        inv H. econs; eauto. rewrite <- TID0.\n        symmetry; eapply small_step_find; eauto.\n  }\n  assert (STEP0': pi_step_except false tidex (cS2, cT1) (cS0,c1')).\n  { econs; eauto. econs; econs.\n    + eauto.\n    + by destruct e2', e0; ss; inv EVENT.\n    + rewrite LANGMATCH0. \n      inv STEP2. inv STEP; [|by inv STEP0].\n      s. inv STEP0. destruct (Ident.eq_dec tid0 tid).\n      * subst. by rewrite IdentMap.gss, TID0.\n      * rewrite IdentMap.gso; eauto.\n    + ii. eapply NOWR0; eauto.\n      * des; destruct e2'; ss; destruct e0; ss; inv EVENT; destruct event0; eauto.\n      * eapply small_step_is_promised; eauto.\n  }\n  assert (STEP2': pi_step_evt true tid (cS0, c1') (cS0, cT3)).\n  { econs. econs; eauto.\n    - rewrite PROMISING. ss.\n    - destruct (Ident.eq_dec tid0 tid); subst; ss.\n      rewrite <-(small_step_find STEPT0); eauto.\n      rewrite <-LANGMATCH.\n      destruct (ThreadEvent.is_promising e0); subst; eauto.\n      rewrite (small_step_find STEPS); eauto.\n    - ii. by des; destruct e1'.\n  }\n  assert (STEP1': pi_step_evt false tid0 (cS2, cT1) (cS0, c1')).\n  { econs. econs; eauto.\n    - by destruct e2', e0; inv EVENT.\n    - etrans; eauto. destruct (Ident.eq_dec tid tid0). \n      + subst. inv STEP2. s. rewrite IdentMap.gss. \n        inv STEP; [by inv STEP0; rewrite TID0|by inv STEP0; inv PROMISING].\n      + rewrite (small_step_find STEP2); eauto.\n    - ii. eapply NOWR0; eauto.\n      + des; destruct e2'; ss; destruct e0; ss; inv EVENT; destruct event0; eauto.\n      + eapply small_step_is_promised; eauto.\n  }\n\n  exploit IH; try exact STEP2'; eauto.\n  { eapply pi_step_future; try exact WF; eauto. }\n  i. des. esplits; [|econs; try exact STEPS0|]; eauto; omega.\nQed.\n\nLemma rtc_pi_step_remove_promises_aux\n      tid tidex cST1 cST2 cST3\n      (WF: pi_wf loctmeq cST1)\n      (NEQ: tid <> tidex)\n      (CONSIS: forall tid0, promise_consistent_th tid0 cST3.(snd))\n      (PSTEPS1: rtc (pi_step_evt true tid) cST1 cST2)\n      (PSTEP: rtc (pi_step_except false tidex) cST2 cST3):\n  exists cT3',\n  rtc (pi_step_except false tidex) cST1 (cST3.(fst),cT3') /\\\n  forall tid0, promise_consistent_th tid0 cT3'.\nProof.\n  revert WF CONSIS PSTEP. induction PSTEPS1; i.\n  - destruct cST3. esplits; eauto.\n  - exploit IHPSTEPS1; eauto.\n    { eapply pi_step_future; eauto. }\n    i. des.\n    apply rtc_rtcn in x0. des.\n    eapply pi_step_remove_promises_aux in x0; eauto. i. des.\n    apply rtcn_rtc in STEPS.\n    esplits; eauto.\nQed.\n\nLemma rtc_pi_step_remove_promises\n      tid tidex cST1 cST2 cST3\n      (WF: pi_wf loctmeq cST1)\n      (NEQ: tid <> tidex)\n      (CONSIS: forall tid0, promise_consistent_th tid0 cST3.(snd))\n      (PSTEPS1: rtc (pi_step_evt true tid) cST1 cST2)\n      (PSTEP: rtc (pi_step_except false tidex) cST2 cST3):\n  exists cT3',\n  rtc (pi_step_except false tidex) cST1 (cST3.(fst),cT3') /\\\n  forall tid0, promise_consistent_th tid0 cT3'.\nProof.\n  exploit rtc_pi_step_remove_promises_aux; eauto.\nQed.\n\nLemma pi_step_evt_to_true\n      withprm tid cST1 cST2\n      (STEP: pi_step_evt withprm tid cST1 cST2):\n  pi_step_evt true tid cST1 cST2.\nProof.\n  destruct withprm; eauto.\n  inv STEP. inv USTEP. inv STEPT.\n  econs. 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/PIStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.27957005737805773}}
{"text": "Require Import Frap Pset13Sig.\n\nSet Implicit Arguments.\n\nLemma ht_prog1 : forall init, hoare_triple\n                                (fun h => h $! 0 = init)\n                                (fun _ _ => False)\n                                prog1\n                                (fun _ _ => True)\n                                (fun _ h => h $! 0 > init).\nProof.\nAdmitted.\n\nTheorem hoare_triple_sound :\n  forall (t : Set) P (c : cmd t) Q,\n    hoare_triple P (fun _ _ => False) c (fun _ _ => True) Q ->\n    forall h,\n      P h ->\n      invariantFor (trsys_of h c) (fun st => notAboutToFail (snd st)).\nProof.\nAdmitted.\n", "meta": {"author": "mit-frap", "repo": "spring17", "sha": "9b8aeb81712ca6e623c1d03baec84d291719debb", "save_path": "github-repos/coq/mit-frap-spring17", "path": "github-repos/coq/mit-frap-spring17/spring17-9b8aeb81712ca6e623c1d03baec84d291719debb/pset13/Pset13.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2795700573780577}}
{"text": "From Coq Require Import ssreflect ssrfun ssrbool.\nFrom PolyAI Require Export TotalMap ssrstring ssrZ Tactic.\nFrom Coq Require Export Bool.Bool Strings.String Numbers.BinNums ZArith.BinInt.\nFrom mathcomp.ssreflect Require Export seq.\nLocal Set Warnings \"-notation-overridden\".\nFrom mathcomp.ssreflect Require Import ssrnat.\n\nLocal Open Scope type_scope.\n\n(*\nThis is the definition of a loop aware SSA language.\n *)\n\nDefinition vid := string.\nDefinition bbid := string.\nDefinition bbid_eqType := string_eqType.\n\n(* Every variable has a value, even the non defined ones *)\nDefinition RegisterMap := @total_map_eqType string_eqType Z_eqType.\n\n(* The label is the program counter *)\nDefinition state := bbid * nat * RegisterMap.\n\n(* Basics binary arithmetic opcodes *)\nInductive BinArithOpCode :=\n| OpAdd\n| OpMul\n| OpLe.\n\n(* An arithmetic instruction *)\nInductive Inst :=\n| Const (v: vid) (c: Z)\n| BinOp (v: vid) (b: BinArithOpCode) (op1 op2: vid): v <> op1 -> v <> op2 -> Inst.\n\n(* A terminator of a basic block *)\nInductive Term :=\n| Br (bb: bbid) (params: seq vid)\n| BrC (c: vid) (bbT: bbid) (paramsT: seq vid)\n      (bbF: bbid) (paramsF: seq vid).\n\n(* A basic block. Has a list of parameters,\n a list of instructions, and a terminator *)\nDefinition BasicBlock :=\n  (seq vid) * (seq Inst) * Term.\n\n(* A program is a set of basic blocks indexed by their bbid *)\nDefinition Program := @partial_map string_eqType BasicBlock.\n\n(* A program structure is either a basic block, a loop that contains a header and\n a body, or the concatenation of two program strutures *)\nInductive ProgramStructure :=\n| Loop (header: bbid) (body: ProgramStructure)\n| DAG (p1 p2: ProgramStructure)\n| BB (bb: bbid).\n\nLocal Open Scope string_scope.\nLocal Open Scope seq_scope.\n\n(* [affect_variables R [(o1,i1); ... ; (oN, iN)]] will affect i1 to o1, then i2 to o2... *)\nFixpoint affect_variables (R: RegisterMap) (vars inputs: seq vid) :=\n  match (vars, inputs) with\n  | (nil, _) => R\n  | (_, nil) => R\n  | (var::vars', input::inputs') => affect_variables (var !-> R input; R) vars' inputs'\n  end.\n\n(* Get inputs of a basic block given its id,\n   and return nil if the id is not found *)\nFixpoint get_inputs (p: Program) (id: bbid) :=\n  match p id with\n  | Some (inputs, _, _) => inputs\n  | None => nil\n  end.\n\nDefinition vars_in_inst (i: Inst) :=\n  match i with\n  | Const v _ | BinOp v _ _ _ _ _ => [::v]\n  end.\n\nFixpoint vars_in_program_ (p: Program) :=\n  match p with\n  | PEmpty => [::\"\"]\n  | PUpdate m' _ bb => (foldl (fun acc inst => acc ++ (vars_in_inst inst)) [::] bb.1.2) ++ (vars_in_program_ m')\n  end.\n\nDefinition vars_in_program (p: Program) :=\n  undup (vars_in_program_ p).\n\nTheorem size_vars_in_program :\n  forall p, 0 < size (vars_in_program p).\nProof.\n  move => p.\n  have: (\"\" \\in (vars_in_program p)).\n  - elim p => [ // | m Hind k v /= ]. rewrite /vars_in_program mem_undup /= mem_cat.\n    apply /orP. right. by rewrite /vars_in_program mem_undup in Hind.\n  - move => Hlt. rewrite -has_predT. apply /hasP. by exists \"\".\nQed.\n\nTheorem uniq_vars_in_program :\n  forall p, uniq (vars_in_program p).\nProof.\n  move => p. by rewrite undup_uniq.\nQed.\n\nFixpoint bbs_in_program (p: ProgramStructure) :=\n  match p with\n  | Loop header body => header::(bbs_in_program body)\n  | DAG p1 p2 => (bbs_in_program p1) ++ (bbs_in_program p2)\n  | BB bb => bb::nil\n  end.\n\n(* Return list of basic blocks that are inside a loop body.\n   Note that the body does not contain the header. *)\nFixpoint bbs_in_loops (p: ProgramStructure) :=\n  match p with\n  | Loop header body => bbs_in_program body\n  | DAG p1 p2 => (bbs_in_loops p1) ++ (bbs_in_loops p2)\n  | BB _ => nil\n  end.\n\nDefinition term_successors (term: Term) :=\n  match term with\n  | Br succ _ => succ::nil\n  | BrC _ succ1 _ succ2 _ => succ1::succ2::nil\n  end.\n\nFixpoint program_successors (p: Program) (ps: ProgramStructure) :=\n  match ps with\n  | Loop header body =>\n    match (p header) with\n    | Some (_, t) => (term_successors t) ++ (program_successors p body)\n    | None => program_successors p body\n    end\n  | DAG ps1 ps2 => (program_successors p ps1) ++ (program_successors p ps2)\n  | BB bb =>\n    match (p bb) with\n    | Some (_, t) => (term_successors t)\n    | None => nil\n    end\n  end.\n\nTheorem program_successors_spec (p: Program) (ps: ProgramStructure) :\n  forall bb_id, (exists in_id, (in_id \\in bbs_in_program ps) /\\\n                    match (p in_id) with\n                    | Some (_, t) => bb_id \\in (term_successors t)\n                    | None => false\n                    end)\n           -> (bb_id \\in program_successors p ps).\nProof.\n  elim: ps.\n  - move => header_id body Hind bb_id [in_id [/= Hin_in Hin]].\n    move: Hin_in. rewrite in_cons => /orP [/eqP Hineq | Hin_in].\n    + move: Hin. rewrite Hineq. case (p header_id) => [ [[header_inputs header_insts] header_term]| // ].\n        by rewrite mem_cat => ->.\n    + move: Hin. case_eq (p in_id) => [[[in_inputs in_insts] in_term] Hin_id | //].\n      case (p header_id) => [[[header_inputs header_insts] header_term] | ] Hbb_in_term.\n      * move => /(_ bb_id) in Hind. rewrite mem_cat.\n        have -> : (bb_id \\in program_successors p body); last first. by rewrite orb_true_r.\n        apply Hind. exists in_id. by rewrite Hin_id.\n      * apply (Hind bb_id). exists in_id. by rewrite Hin_id.\n  - move => ps1 Hind1 ps2 Hind2 bb_id [in_id [Hin_in ]] Hpin_id.\n    move: Hin_in. rewrite /= mem_cat => /orP[Hin1 | Hin2].\n    + rewrite mem_cat. apply /orP. left. eauto.\n    + rewrite mem_cat. apply /orP. right. eauto.\n  - move => bb_id bb /= [in_id [Hin Hin_in]].\n    rewrite mem_seq1 in Hin. move => /eqP in Hin. rewrite -Hin.\n    move: Hin_in. case (p in_id) => [ [[bb_inputs bb_insts] bb_term] // | //].\nQed.\n\nDefinition program_predecessors (p: Program) (bb_id: bbid) :=\n  let keys := keys_list p in\n  filter (fun k => match p k with\n                | Some (_,t) => bb_id \\in (term_successors t)\n                | None => false\n                end ) keys.\n\nTheorem program_predecessors_spec (p: Program) (bb_id: bbid) :\n  forall bb_id', bb_id' \\in (program_predecessors p bb_id) =\n                       match (p bb_id') with\n                       | Some (_, t) => bb_id \\in (term_successors t)\n                       | None => false\n                       end.\nProof.\n  move => bb_id'.\n  rewrite mem_filter.\n  apply/idP/idP.\n  - by move => /andP[].\n  - move => Hbb. apply /andP.\n    split; auto. apply keys_list_spec. move: Hbb.\n      by case (p bb_id').\nQed.\n\n\nFixpoint structure_sound (p: Program) (ps: ProgramStructure) :=\n  match ps with\n  | Loop header body =>\n    (header \\notin (bbs_in_program body)) &&\n    all (fun bb_id => all (fun bb_id' => bb_id' \\in header::(bbs_in_program body)) (program_predecessors p bb_id)) (bbs_in_program body) &&\n    (structure_sound p body) &&\n    match p header with\n    | None => false\n    | Some _ => true\n    end\n  | DAG ps1 ps2 =>\n    all (fun s => s \\notin (bbs_in_program ps2)) (bbs_in_program ps1) &&\n    all (fun s => s \\notin (bbs_in_program ps1)) (bbs_in_program ps2) &&\n    all (fun s => s \\notin (bbs_in_program ps1)) (program_successors p ps2) &&\n    structure_sound p ps1 &&\n    structure_sound p ps2\n  | BB bb =>\n    match p bb with\n    | None => false\n    | Some (_,term) => bb \\notin (term_successors term)\n    end\n  end.\n\nLocal Open Scope Z_scope.\n\n(* The evaluation of a binary operation *)\nDefinition bin_op_eval (op : BinArithOpCode) (v1 v2 : Z) :=\n  match op with\n  | OpAdd => v1 + v2\n  | OpMul => v1 * v2\n  | OpLe => if v1 <=? v2 then 1 else 0\n  end.\n\n(* The semantics of arithmetic instructions *)\nInductive inst_step: Inst -> RegisterMap -> RegisterMap -> Prop :=\n| ConstStep (v: vid) (c: Z) (R: RegisterMap):\n    inst_step (Const v c) R (v !-> c; R)\n| BinOpStep (v: vid) (opc: BinArithOpCode) (op1 op2: vid) (H1: v <> op1) (H2: v <> op2) (R: RegisterMap):\n    inst_step (BinOp v opc op1 op2 H1 H2) R (v !-> bin_op_eval opc (R op1) (R op2); R).\n\n(* The semantics of a terminator *)\nInductive term_step: Program -> Term -> RegisterMap -> (bbid * RegisterMap)\n                           -> Prop :=\n| BrStep (p: Program) (bb: bbid) (params: list vid) (R: RegisterMap) :\n    term_step p (Br bb params) R (bb, (affect_variables R (get_inputs p bb) params))\n| BrCTrueStep (p: Program) (c: vid) (bbT bbF: bbid) (paramsT paramsF: list vid) (R: RegisterMap) :\n    R c <> 0 ->\n    term_step p (BrC c bbT paramsT bbF paramsF) R\n                    (bbT, (affect_variables R (get_inputs p bbT) paramsT))\n| BrCFalseStep (p: Program) (c: vid) (bbT bbF: bbid) (paramsT paramsF: list vid) (R: RegisterMap) :\n    R c = 0 ->\n    term_step p (BrC c bbT paramsT bbF paramsF) R\n                    (bbF, (affect_variables R (get_inputs p bbF) paramsF))\n.\n\nTheorem term_successors_spec (p: Program) (term: Term) :\n  forall out_id R R', term_step p term R (out_id, R') ->\n                 out_id \\in term_successors term.\nProof.\n  move => out_id R R' Hterm_step.\n  inversion Hterm_step; subst.\n  - by rewrite in_cons eq_refl.\n  - by rewrite in_cons eq_refl.\n  - by rewrite in_cons in_cons eq_refl orb_true_r.\nQed.\n\n\n(* The small step semantics of a program *)\nInductive step: Program -> state -> state -> Prop :=\n| InstStep (p: Program) (bb_id: bbid) (params: list vid) (insts: list Inst) (term: Term) :\n    p bb_id = Some (params, insts, term) ->\n    forall l inst, List.nth_error insts l = Some inst ->\n            forall R R', inst_step inst R R' ->\n                    step p (bb_id, l, R) (bb_id, S l, R')\n| TermStep (p: Program) (bb_id: bbid) (params: list vid) (insts: list Inst) (term: Term) :\n    p bb_id = Some (params, insts, term) ->\n    forall l, List.nth_error insts l = None ->\n         forall new_bbid R R', term_step p term R (new_bbid, R') ->\n                          step p (bb_id, l, R) (new_bbid, O, R').\n\n(* The reflexive and transitive closure of the trans relation *)\nInductive multi_step: Program -> state -> state -> Prop :=\n| StepRefl : forall p s, multi_step p s s\n| StepTrans : forall p s s' s'', multi_step p s s' -> step p s' s'' -> multi_step p s s''.\n\nDefinition reachable_states (p: Program) (R: RegisterMap) (s: state) :=\nmulti_step p (\"entry\", O, R) s.\n\nOpen Scope nat_scope.\n\nTheorem multi_step_trans :\n  forall p s0 s1 s2, multi_step p s0 s1 -> multi_step p s1 s2 -> multi_step p s0 s2.\nProof.\n  move => p s0 s1 s2 H01 H12.\n  induction H12 => [// | ].\n  apply IHmulti_step in H01.\n    by eapply StepTrans; eauto.\nQed.\n\nTheorem reachable_states_pos (p: Program) (R: RegisterMap) (s: state) :\n  reachable_states p R s ->\n  match p s.1.1 with\n  | Some (_, insts, _) => s.1.2 <= List.length insts\n  | Non => true\n  end.\nProof.\n  rewrite /reachable_states.\n  move s1 : (\"entry\", O, R) => Hs1 Hmulti_step.\n  elim: Hmulti_step s1.\n  - move => p0 s0 <- /= .\n    case (p0 \"entry\") => [ [[_ insts] _] | //].\n    case insts => [ // | i l /=].\n      by apply leq0n.\n  - move => p0 s0 s' s'' Hmulti_step Hind Hstep Hs0.\n    inversion Hstep; subst.\n    + move: Hind => /(_ (erefl _)) /=. case_eq (p0 bb_id) => [ [[inputs' insts'] term'] Hbb'| //].\n      rewrite H in Hbb'. inversion Hbb'. subst.\n      have Hne_None : (List.nth_error insts' l <> None). move: H0. case (List.nth_error insts' l) => //.\n      apply List.nth_error_Some in Hne_None.\n      by move => /ltP in Hne_None.\n    + rewrite /=. case (p0 new_bbid) => [[[_ insts'] _] | //]. case insts' => [ // | i' l' /=].\n      by apply leq0n.\nQed.\n\nTheorem step_entering_loop :\n  forall p header_id body,\n    let loop := Loop header_id body in\n    structure_sound p loop ->\n    forall s_in, (s_in.1.1 \\notin (bbs_in_program loop)) ->\n            forall s_out, (s_out.1.1 \\in (bbs_in_program loop)) ->\n                     step p s_in s_out ->\n                     s_out.1.1 = header_id /\\ s_out.1.2 = 0.\nProof.\n  move => p header_id body loop Hsound s_in Hs_in_notin s_out Hs_out_in Hstep.\n  have H_s_in_out_ne: (s_in <> s_out). move => H_s_in_out_eq. subst. by rewrite Hs_out_in in Hs_in_notin.\n  inversion Hstep. bigsubst. by rewrite Hs_out_in in Hs_in_notin.\n  bigsubst. rewrite /=. split; auto.\n  inversion Hsound. move: H3 => /andP[/andP[/andP[_ /allP Hpred] _] _].\n  move => /= in Hs_out_in. rewrite in_cons in Hs_out_in. move => /orP in Hs_out_in.\n  case: Hs_out_in; first by autossr.\n  move => /Hpred /allP.\n  apply term_successors_spec in H1.\n  move: (program_predecessors_spec p new_bbid bb_id).\n  rewrite H H1 => H_in_predecessors. move => /(_ bb_id H_in_predecessors).\n    by autossr.\nQed.\n\nTheorem multi_step_loop :\n  forall p header_id body,\n    let loop := Loop header_id body in\n    structure_sound p loop ->\n    forall s_entry, (s_entry.1.1 \\notin (bbs_in_program loop)) ->\n               forall s_bb, (s_bb.1.1 \\in (bbs_in_program loop)) ->\n                       multi_step p s_entry s_bb <->\n                       exists R_header, multi_step p s_entry (header_id, 0, R_header) /\\\n                                   multi_step p (header_id, 0, R_header) s_bb.\nProof.\n  move => p header_id body loop Hsound s_entry H_entry_notin s_bb H_bb_in.\n  split => [ H_multi_step | [R_header [H01 H12]]]; last by eapply multi_step_trans; eauto.\n  move Hp : p => p'. rewrite Hp in H_multi_step.\n  elim: H_multi_step Hp H_bb_in H_entry_notin; first by move => p0 s _ ->.\n  move => p0 s s' s'' Hmulti_step Hind Hstep Hp H_s''_in H_s_notin.\n  case Hs'_in : (s'.1.1 \\in bbs_in_program loop). by case: (Hind Hp Hs'_in H_s_notin) => R_header [H0 H1]; eexists; split; eauto; econstructor; eauto.\n  have H_s'_s''_ne: (s' <> s''). move => H_s'_s''_eq. subst. by rewrite H_s''_in in Hs'_in.\n  bigsubst. move => /negb_true_iff in Hs'_in. move: (step_entering_loop _ _ _ Hsound _ Hs'_in _ H_s''_in Hstep) => [H_s''_header H_s''_pos_0].\n  exists s''.2. rewrite -H_s''_header -H_s''_pos_0.\n  rewrite -!surjective_pairing. split; last by constructor.\n  econstructor; eauto.\nQed.\n\nDefinition step_cond (p: Program) (s s': state) (avoid: seq bbid) :=\n  step p s s' /\\ ~~ ((s'.1.1 \\in avoid) && (s'.1.2 != 0)).\n\nInductive multi_step_cond: Program -> state -> state -> seq bbid -> Prop :=\n| StepCondRefl : forall p s l, multi_step_cond p s s l\n| StepCondTrans : forall p s s' s'' l, multi_step_cond p s s' l -> step_cond p s' s'' l -> multi_step_cond p s s'' l.\n\nTheorem multi_step_cond_trans:\n  forall p s' s s'' l, multi_step_cond p s s' l ->\n                     multi_step_cond p s' s'' l ->\n                     multi_step_cond p s s'' l.\nProof.\n  move => p s' s s'' l H01 H12.\n  induction H12 => [ // | ].\n  apply IHmulti_step_cond in H01.\n    by eapply StepCondTrans; eauto.\nQed.\n\nTheorem step_cond_cons:\n  forall p s s' bb_id l, step_cond p s s' (bb_id::l) -> step_cond p s s' l.\nProof.\n  move => p s s' bb_id l [Hstep /nandP [Hnotin | Hnot0]]; rewrite /step_cond; autossr.\nQed.\n\nTheorem multi_step_cond_cons:\n  forall p s s' bb_id l, multi_step_cond p s s' (bb_id::l) ->\n                    multi_step_cond p s s' l.\nProof.\n  move => p s s' bb_id l Hmulti.\n  move Hl_cons : (bb_id :: l) => l_cons. rewrite Hl_cons in Hmulti.\n  induction Hmulti; first by constructor.\n  eapply StepCondTrans; eauto.\n  rewrite -Hl_cons in H. by eapply step_cond_cons; eauto.\nQed.\n\nSection Example.\n\n  Definition y_ne_x : \"y\" <> \"x\".\n  Proof.\n      by apply /eqP.\n  Qed.\n\n  Definition y_ne_one : \"y\" <> \"one\".\n  Proof.\n      by apply /eqP.\n  Qed.\n\n  Definition c_ne_y : \"c\" <> \"y\".\n  Proof.\n      by apply /eqP.\n  Qed.\n\n  Definition c_ne_one : \"c\" <> \"one\".\n  Proof.\n      by apply /eqP.\n  Qed.\n\n  Definition entry_bb := (@nil string,\n                          (Const \"zero\" 0)::(Const \"one\" 1)::nil,\n                          (Br \"loop\" (\"zero\"::nil))).\n\n  Definition loop_bb := (\"x\"::nil,\n                         (BinOp \"y\" OpAdd \"x\" \"one\" y_ne_x y_ne_one)::\n                         (BinOp \"c\" OpLe \"y\" \"one\" c_ne_y c_ne_one)::nil,\n                         (BrC \"c\" \"loop\" (\"y\"::nil) \"exit\" (\"y\"::nil))).\n\n  Definition dummy_bb := (@nil string, @nil Inst, (Br \"loop\" ([::\"y\"]))).\n\n  Definition exit_bb := (\"exitvalue\"::nil, @nil Inst, (Br \"finished\" nil)).\n\n  Definition prog := (\"entry\" !!-> entry_bb; \"loop\" !!-> loop_bb; \"dummy\" !!-> dummy_bb; \"exit\" !!-> exit_bb).\n\n  Definition progstruct := DAG (BB \"entry\") (DAG (Loop \"loop\" (BB \"dummy\")) (BB \"exit\")).\n\n  Example progstruct_correct :\n    structure_sound prog progstruct.\n  Proof.\n      by [].\n  Qed.\n\nEnd Example.\n", "meta": {"author": "math-fehr", "repo": "PresburgerAI-Coq", "sha": "ad081f935c3c88aac60464fda7beeaa3deca6f26", "save_path": "github-repos/coq/math-fehr-PresburgerAI-Coq", "path": "github-repos/coq/math-fehr-PresburgerAI-Coq/PresburgerAI-Coq-ad081f935c3c88aac60464fda7beeaa3deca6f26/src/LSSA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2794851479992033}}
{"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 CtxtSwitchAux.Specs.save_ns_state_sysreg_state.\nRequire Import CtxtSwitchAux.LowSpecs.save_ns_state_sysreg_state.\nRequire Import CtxtSwitchAux.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       sysreg_read_spec\n       set_ns_state_spec\n    .\n\n  Lemma save_ns_state_sysreg_state_spec_exists:\n    forall habd habd'  labd\n           (Hspec: save_ns_state_sysreg_state_spec  habd = Some habd')\n            (Hrel: relate_RData habd labd),\n    exists labd', save_ns_state_sysreg_state_spec0  labd = Some labd' /\\ relate_RData habd' labd'.\n    Proof.\n      Local Opaque ptr_eq get_reg set_reg.\n      intros. destruct Hrel.\n      unfold save_ns_state_sysreg_state_spec, save_ns_state_sysreg_state_spec0 in *.\n      unfold sysreg_read_spec, set_ns_state_spec.\n      autounfold in Hspec.\n      hsimpl_hyp Hspec; inv Hspec; simpl_query_oracle; extract_prop_dec.\n      destruct regs_is_int64_dec in C; [|inversion C].\n      unfold Assertion.\n      repeat (unfold bind64 at 1; rewrite e; repeat simpl_update_reg; repeat (simpl priv; simpl cpu_regs; simpl_field);\n              unfold bind at 1; simpl ns_regs_el2).\n      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/CtxtSwitchAux/RefProof/save_ns_state_sysreg_state.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.27948514152536597}}
{"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 O E Eprime A B C Oprime Bprime Cprime Eprimeprime Bprimeprime C2 : Universe, ((wd_ O E /\\ (wd_ Oprime Eprime /\\ (wd_ A O /\\ (wd_ B O /\\ (wd_ C O /\\ (wd_ A E /\\ (wd_ Eprimeprime O /\\ (wd_ O Oprime /\\ (wd_ A Oprime /\\ (wd_ Eprimeprime A /\\ (wd_ E Eprimeprime /\\ (wd_ E Eprime /\\ (wd_ O Eprime /\\ (wd_ Oprime Eprimeprime /\\ (wd_ E Oprime /\\ (wd_ C Cprime /\\ (wd_ B Bprime /\\ (col_ O E A /\\ (col_ O E B /\\ (col_ O E C /\\ (col_ Oprime Eprime Oprime /\\ (col_ Oprime Eprime Bprime /\\ (col_ Oprime Eprime Cprime /\\ (col_ O Eprimeprime Bprimeprime /\\ (col_ O Eprimeprime Eprimeprime /\\ (col_ O Eprimeprime Oprime /\\ (col_ O Eprimeprime C2 /\\ (col_ O A A /\\ (col_ O A Oprime /\\ col_ Eprimeprime A Oprime))))))))))))))))))))))))))))) -> col_ Oprime O E)).\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_1277.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.27943492230025535}}
{"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.ramification_lemmas.\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.lib.Morphisms_ext.\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.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 CertiGraph.msl_application.GraphBin.\nRequire Import CertiGraph.msl_application.Graph_Copy.\nRequire Import Coq.Logic.Classical.\n\nOpen Scope logic.\n\nSection PointwiseGraph_Copy_Bin.\n\nContext {pSGG_Bin: pPointwiseGraph_Graph_Bin}.\nContext {sSGG_Bin: sPointwiseGraph_Graph_Bin addr (addr * LR)}.\n\nExisting Instances pSGG_Bin sSGG_Bin SGAvn.\n\nLocal Coercion Graph'_LGraph: Graph' >-> LGraph.\nLocal Coercion Graph_LGraph: Graph >-> LGraph.\nLocal Coercion LGraph_SGraph: LGraph >-> SGraph.\nLocal Identity Coercion Graph_GeneralGraph: Graph >-> GeneralGraph.\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_Bin addr (addr * LR) unit).\nNotation Graph' := (@Graph' pSGG_Bin addr (addr * LR) unit).\n\n#[global] Instance CCS: CompactCopySetting addr (addr * LR) unit.\n  apply (Build_CompactCopySetting _ _ _ null (null, L) tt).\nDefined.\n\nDefinition empty_Graph': Graph' := empty_Graph' null (null, L) tt.\n\nDefinition initial_copied_Graph (x x0: addr) (g: Graph): LGraph \n  := single_vertex_labeledgraph (LocalGraphCopy.vmap (Graph_vgen g x x0) x) null (null, L) tt.\n\nOpaque empty_Graph initial_copied_Graph.\n\nLemma vertex_at_not_null: forall (x: addr) (gx: addr * addr * addr),\n  @derives pred _\n    (vertex_at x gx) (!! (null <> x)).\nProof.\n  intros.\n  destruct (classic (null = x)).\n  + subst x.\n    apply derives_trans with FF.\n    apply vertex_at_not_null.\n    apply FF_left.\n  + apply prop_right; auto.\nQed.\n\nLemma copy_null_refl: forall (g: Graph),\n  copy null g g empty_Graph'.\nProof. intros; apply copy_invalid_refl, invalid_null; auto. Qed.\n\nLemma copy_vgamma_not_null_refl: forall (g: Graph) (root: addr) d l r,\n  vgamma g root = (d, l, r) ->\n  d <> null ->\n  copy root g g empty_Graph'.\nProof.\n  intros; apply marked_root_copy_refl.\n  simpl.\n  inversion H.\n  subst; congruence.\nQed.\n\nLemma vmap_weaken: forall (g1: Graph) (g2: Graph') x x0 BLA,\n  (x = null /\\ x0 = null \\/ x0 = BLA) ->\n  (~ vvalid g1 x /\\ ~ vvalid g2 x0 \\/ x0 = BLA).\nProof.\n  intros.\n  destruct H; [left | right]; auto.\n  destruct H.\n  pose proof (@valid_not_null _ _ _ _ g1 _ (maGraph g1) x).\n  pose proof (@valid_not_null' _ _ _ _ g2 _ (maGraph' g2) x0).\n  unfold is_null_SGBA in *; simpl in *.\n  auto.\nQed.\n\nLemma root_stable_ramify: forall (g: Graph) (x: addr) (gx: addr * 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_ramify1: forall (g: Graph) (x x0: addr) (lx: addr) (gx gx': addr * addr * addr),\n  vvalid g x ->\n  vertices_at (Intersection _ (vvalid (initial_copied_Graph x x0 g)) (fun u : addr => x0 <> u)) (initial_copied_Graph x x0 g) = emp.\nProof.\n  intros.\n    erewrite <- vertices_at_False.\n    apply vertices_at_Same_set.\n    rewrite Same_set_spec; intros ?.\nTransparent initial_copied_Graph. simpl. Opaque initial_copied_Graph.\n    unfold update_vlabel.\n    if_tac; [| congruence].\n    split; [intros [? ?]; congruence | tauto].\nQed.\n\nLemma root_update_ramify2: forall (g: Graph) (x x0: addr) (lx: addr) (gx gx': addr * addr * addr) F,\n  vgamma g x = gx ->\n  vgamma (Graph_vgen g x lx) x = gx' ->\n  vvalid g x ->\n  @derives pred _\n    (F * reachable_vertices_at x g)\n    (vertex_at x gx *\n      (vertex_at x gx' -*\n       F * (emp * reachable_vertices_at x (Graph_vgen g x lx)))).\nProof.\n  intros.\n  rewrite !(sepcon_comm F).\n  apply RAMIF_PLAIN.frame.\n  rewrite emp_sepcon.\n  apply va_reachable_root_update_ramify; auto.\nQed.\n\nLemma root_update_ramify (* {sSGG_Bin': sPointwiseGraph_Graph_Bin addr (addr * LR)} *): forall (g: Graph) (x x0: addr) (lx: addr) (gx gx': addr * addr * addr) F,\n  vgamma g x = gx ->\n  vgamma (Graph_vgen g x lx) x = gx' ->\n  vvalid g x ->\n  @derives pred _\n    (F * @reachable_vertices_at _ _ _ _ (@SGBA pSGG_Bin) _ _ _ (@SGC_Bin pSGG_Bin _ _ _) _ (@SGP pSGG_Bin _ _ sSGG_Bin) (@SGA pSGG_Bin _ _ sSGG_Bin) x g)\n    (vertex_at x gx *\n      (vertex_at x gx' -*\n       F * (@vertices_at _ _ _ _ (@SGBA pSGG_Bin) _ (@SGP pSGG_Bin _ _ sSGG_Bin) _ (Intersection _ (vvalid (initial_copied_Graph x x0 g)) (fun u : addr => x0 <> u)) (initial_copied_Graph x x0 g) * reachable_vertices_at x (Graph_vgen g x lx)))).\nProof.\n  intros.\n  rewrite !(sepcon_comm F).\n  apply RAMIF_PLAIN.frame.\n  assert (@vertices_at _ _ _ _ (@SGBA pSGG_Bin) _ (@SGP pSGG_Bin _ _ sSGG_Bin) _ (Intersection _ (vvalid (initial_copied_Graph x x0 g)) (fun u : addr => x0 <> u)) (initial_copied_Graph x x0 g) = emp).\n  {\n    erewrite <- vertices_at_False.\n    apply vertices_at_Same_set.\n    rewrite Same_set_spec; intros ?.\nTransparent initial_copied_Graph. simpl. Opaque initial_copied_Graph.\n    unfold update_vlabel.\n    if_tac; [| congruence].\n    split; [intros [? ?]; congruence | tauto].\n  }\n  rewrite H2, emp_sepcon.\n  apply va_reachable_root_update_ramify; auto.\nQed.\n        \nLemma not_null_copy1: forall (G: Graph) (x x0: addr) l r,\n  vgamma G x = (null, l, r) ->\n  vvalid G x ->\n  x0 <> null ->\n  vcopy1 x G (Graph_vgen G x x0) (initial_copied_Graph x x0 G) /\\\n  x0 = LocalGraphCopy.vmap (Graph_vgen G x x0) x /\\\n  is_guarded_BinMaFin' (fun v => x0 <> v) (fun e => ~ In e nil) (initial_copied_Graph x x0 G).\nProof.\n  intros.\n  split; [split; [| split] | split].\n  + reflexivity.\n  + split; [| split].\n    - reflexivity.\n    - simpl.\n      unfold update_vlabel.\n      destruct_eq_dec x x; congruence.\n    - intros.\n      simpl.\n      unfold update_vlabel; simpl.\n      destruct_eq_dec x n'; [congruence |].\n      tauto.\n  + split; [| split; [| split]].\n    - reflexivity.\n    - apply guarded_pointwise_relation_spec; intros.\n      simpl.\n      unfold update_vlabel; simpl.\n      destruct_eq_dec x x1; [congruence | auto].\n    - apply guarded_pointwise_relation_spec; intros.\n      auto.\n    - reflexivity.\n  + simpl.\n    unfold update_vlabel; simpl.\n    destruct_eq_dec x x; [auto | congruence].\n  + assert (LocalGraphCopy.vmap (Graph_vgen G x x0) x = x0).\n    1: {\n      simpl.\n      unfold update_vlabel; simpl.\n      destruct_eq_dec x x; auto; congruence.\n    }\n    pattern x0 at 1; rewrite <- H2.\n    apply single_vertex_guarded_BinMaFin'.\nQed.\n\nLemma left_weak_valid: forall (G G1: Graph) (G1': LGraph) (x l r: addr),\n  vgamma G x = (null, l, r) ->\n  vvalid G x ->\n  vcopy1 x G G1 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 G3: Graph) (G1' G2' G3': LGraph) (x l r: addr),\n  vgamma G x = (null, l, r) ->\n  vvalid G x ->\n  vcopy1 x G G1 G1' ->\n  extended_copy l (G1: LGraph, G1') (G2: LGraph, G2') ->\n  ecopy1 (x, L) (G2: LGraph, G2') (G3: LGraph, G3') ->\n  @weak_valid _ _ _ _ G3 _ (maGraph _) r.\nProof.\n  intros.\n  destruct H1 as [? _], H2 as [? _], H3 as [? _].\n  rewrite <- H2, <- H1 in H3.\n  eapply weak_valid_si; [symmetry; eauto |].\n  eapply gamma_right_weak_valid; eauto.\nQed.\n\nLemma graph_ramify_left: forall (g g1: Graph) (g1': LGraph) (x l r: addr) (F1 F2: pred) F3,\n  vvalid g x ->\n  vgamma g x = (null, l, r) ->\n  vcopy1 x g g1 g1' ->\n  F1 * (F2 * reachable_vertices_at x g1) |--\n  reachable_vertices_at l g1 *\n   (ALL a: Graph' * Graph * addr,\n     !! (copy l g1 (snd (fst a)) (fst (fst a)) /\\ (l = null /\\ snd a = null \\/ snd a = LocalGraphCopy.vmap (snd (fst a)) l)) -->\n     (reachable_vertices_at l (snd (fst a)) * F3 (snd a) (fst (fst a)) -*\n      F1 * (F2 * (reachable_vertices_at x (snd (fst a)) * F3 (snd a) (fst (fst a)))))).\nProof.\n  intros.\n  destruct H1 as [? [? ?]].\n  rewrite <- sepcon_assoc, (sepcon_comm (F1 * F2)).\n  RAMIF_Q'.formalize.\n  match goal with\n  | |- _ |-- _ * allp (_ --> (_ -* ?A)) =>\n    replace A with\n    (fun p : Graph' * Graph * addr =>\n            reachable_vertices_at x (snd (fst p)) *\n            F3 (snd p) (fst (fst p)) * (F1 * F2)) by\n    (extensionality p; rewrite <- (sepcon_assoc F1 F2), (sepcon_comm _ (F1 * F2)); auto)\n  end.\n  apply RAMIF_Q'.frame; [auto |].\n  apply RAMIF_Q'.frame_post; [auto |].\n  simpl.\n\n  eapply vertices_at_ramif_xQ.\n  eexists.\n  split; [| split].\n  + rewrite <- H1.\n    eapply Prop_join_reachable_left; eauto.\n  + intros.\n    destruct H4 as [[? [? ?]] _].\n    rewrite <- H4, <- H1.\n    eapply Prop_join_reachable_left; eauto.\n  + intros [[? ?] ?] [? _].\n    simpl in H4 |- *.\n    rewrite vertices_identical_spec.\n    intros.\n    simpl.\n    destruct H4 as [? [? ?]].\n    f_equal; [f_equal |].\n    - destruct H7 as [_ [? _]].\n      rewrite guarded_pointwise_relation_spec in H7.\n      apply H7; clear H7.\n      unfold Complement, Ensembles.In.\n      intro.\n      apply reachable_by_is_reachable in H7.\n      rewrite Intersection_spec in H5.\n      rewrite <- H1 in H7.\n      destruct H5; auto.\n    - apply dst_L_eq; auto.\n      rewrite Intersection_spec in H5.\n      destruct H5 as [? _].\n      rewrite H1 in H5.\n      apply reachable_foot_valid in H5; auto.\n    - apply dst_R_eq; auto.\n      rewrite Intersection_spec in H5.\n      destruct H5 as [? _].\n      rewrite H1 in H5.\n      apply reachable_foot_valid in H5; auto.\nQed.\n\nLemma graph_ramify_right: forall (g g1 g2 g3: Graph) (g1' g2' g3': LGraph) (x l r: addr) (F1 F2: pred) F3,\n  vvalid g x ->\n  vgamma g x = (null, l, r) ->\n  vcopy1 x g g1 g1' ->\n  extended_copy l (g1: LGraph, g1') (g2: LGraph, g2') ->\n  ecopy1 (x, L) (g2: LGraph, g2') (g3: LGraph, g3') ->\n  F1 * (F2 * reachable_vertices_at x g3) |--\n  reachable_vertices_at r g3 *\n   (ALL a: Graph' * Graph * addr,\n     !! (copy r g3 (snd (fst a)) (fst (fst a)) /\\ (r = null /\\ snd a = null \\/ snd a = LocalGraphCopy.vmap (snd (fst a)) r)) -->\n     (reachable_vertices_at r (snd (fst a)) * F3 (snd a) (fst (fst a)) -*\n      F1 * (F2 * (reachable_vertices_at x (snd (fst a)) * F3 (snd a) (fst (fst a)))))).\nProof.\n  intros.\n  destruct H1 as [? [? ?]].\n  rewrite <- sepcon_assoc, (sepcon_comm (F1 * F2)).\n  RAMIF_Q'.formalize.\n  match goal with\n  | |- _ |-- _ * allp (_ --> (_ -* ?A)) =>\n    replace A with\n    (fun p : Graph' * Graph * addr =>\n            reachable_vertices_at x (snd (fst p)) *\n            F3 (snd p) (fst (fst p)) * (F1 * F2)) by\n    (extensionality p; rewrite <- (sepcon_assoc F1 F2), (sepcon_comm _ (F1 * F2)); auto)\n  end.\n  apply RAMIF_Q'.frame; [auto |].\n  apply RAMIF_Q'.frame_post; [auto |].\n  simpl.\n\n  eapply vertices_at_ramif_xQ.\n  eexists.\n  split; [| split].\n  + destruct H2 as [? _], H3 as [? _]; rewrite <- s0, <- s, <- H1.\n    eapply Prop_join_reachable_right; eauto.\n  + intros.\n    destruct H6 as [[? [? ?]] _].\n    destruct H2 as [? _], H3 as [? _]. rewrite <- H6, <- H3, <- H2, <- H1.\n    eapply Prop_join_reachable_right; eauto.\n  + intros [[[? ?] ?] ?] [? _].\n    destruct H2 as [? _], H3 as [? _]; rewrite H2, H3 in H1.\n    simpl in H6 |- *.\n    rewrite vertices_identical_spec.\n    intros.\n    simpl.\n    destruct H6 as [? [? ?]].\n    f_equal; [f_equal |].\n    - destruct H9 as [_ [? _]].\n      rewrite guarded_pointwise_relation_spec in H9.\n      apply H9; clear H9.\n      unfold Complement, Ensembles.In.\n      intro.\n      apply reachable_by_is_reachable in H9.\n      rewrite Intersection_spec in H7.\n      rewrite <- H1 in H9.\n      destruct H7; auto.\n    - apply dst_L_eq; auto.\n      rewrite Intersection_spec in H7.\n      destruct H7 as [? _].\n      rewrite H1 in H7.\n      apply reachable_foot_valid in H7; auto.\n    - apply dst_R_eq; auto.\n      rewrite Intersection_spec in H7.\n      destruct H7 as [? _].\n      rewrite H1 in H7.\n      apply reachable_foot_valid in H7; auto.\nQed.\n\nLemma is_BinMaFin_disjoint_guard: forall (g1':  @LGraph pSGG_Bin (@addr pSGG_Bin) (prod (@addr pSGG_Bin) LR) unit) (g2'': Graph') x0 es0,\n  is_guarded_BinMaFin' (fun v => x0 <> v) (fun e => ~ In e es0) g1' ->\n  vvalid g1' x0 ->\n  (forall e, In e es0 -> fst e = x0) ->\n  Disjoint addr (vvalid g2'') (vvalid g1') ->\n  disjointed_guard (vvalid g2'') (vvalid g1') (evalid g2'') (evalid g1').\nProof.\n  intros.\n  split; auto.\n  rewrite Disjoint_spec in *.\n  intros e ? ?.\n  pose proof @valid_graph' _ _ _ _ g2'' _ (maGraph' _) e H3.\n  apply (H2 _ H5).\n  destruct (in_dec equiv_dec e es0); destruct e as [v lr].\n  + specialize (H1 _ i).\n    simpl in H1.\n    rewrite left_right_sound0' by auto.\n    subst; auto.\n  + destruct H as [X _].\n    pose (pg1 := Build_GeneralGraph _ _ _ (fun g: LGraph => BinMaFin' g) (gpredicate_sub_labeledgraph (fun v => x0 <> v) (fun e => ~ In e es0) g1') X: Graph').\n    assert (evalid pg1 (v, lr)) by (simpl; rewrite Intersection_spec; split; auto).\n    assert (src g2'' (v, lr) = src pg1 (v, lr)) by (rewrite !left_right_sound0'; auto).\n    apply (@valid_graph' _ _ _ _ pg1 _ (maGraph' _)) in H.\n    rewrite H6; auto.\n    destruct H; auto.\nQed.\n\nLemma is_BinMaFin_not_evalid: forall (g1': @LGraph pSGG_Bin (@addr pSGG_Bin) (prod (@addr pSGG_Bin) LR) unit)x0 es0 e0,\n  is_guarded_BinMaFin' (fun v => x0 <> v) (fun e => ~ In e es0) g1' ->\n  vvalid g1' x0 ->\n  (forall e, In e es0 -> fst e = x0) ->\n  fst e0 = x0 ->\n  ~ In e0 es0 ->\n  ~ evalid g1' e0.\nProof.\n  intros.\n  intro.\n  destruct H as [X ?].\n  set (G := (Build_GeneralGraph _ _ _ (fun g => BinMaFin' (pg_lg g)) _ X: Graph')).\n  assert (evalid G e0).\n  1: {\n    simpl.\n    rewrite Intersection_spec; auto.\n  }\n  pose proof @valid_graph' _ _ _ _ G _ (maGraph' _) _ H5.\n  destruct e0.\n  simpl in H2; subst a.\n  rewrite (left_right_sound0' _ _ _ H5) in H6.\n  simpl in H6.\n  rewrite Intersection_spec in H6.\n  destruct H6.\n  auto.\nQed.\n\nLemma extend_copy_left: forall (g g1 g2: Graph) (g1': LGraph) (g2'': Graph') (x l r x0 l0: addr) d0,\n  vvalid g x ->\n  vgamma g x = (null, l, r) ->\n  vcopy1 x g g1 g1' ->\n  copy l g1 g2 g2'' ->\n  x0 = LocalGraphCopy.vmap g1 x ->\n  l = null /\\ l0 = null \\/ l0 = LocalGraphCopy.vmap g2 l ->\n  is_guarded_BinMaFin' (fun v => x0 <> v) (fun e => ~ In e nil) g1' ->\n  @derives pred _\n  (vertex_at x0 d0 * vertices_at (Intersection _ (vvalid g1') (fun x => x0 <> x)) g1' * reachable_vertices_at l0 g2'') \n  (EX g2': LGraph,\n    !! (extended_copy l (g1: LGraph, g1') (g2: LGraph, g2') /\\ is_guarded_BinMaFin' (fun v => x0 <> v) (fun e => ~ In e nil) g2') && \n    (vertex_at x0 d0 * vertices_at (Intersection _ (vvalid g2') (fun x => x0 <> x)) g2')).\nProof.\n  intros.\n  rename H5 into BMF.\n  inversion H0.\n  pose proof @vcopy1_edge_copy_list_weak_copy_extended_copy' _ _ _ _ _ _ _ _ _ _ BinMaFin'_Normal x ((x, L) :: (x, R) :: nil) nil (x, L) ((x, R) :: nil) g g1 g1 g1' g1' g2 g2'' x0 H.\n  spec H5; [simpl; unfold Complement, Ensembles.In; congruence |].\n  spec H5; [reflexivity |].\n  spec H5; [intros; apply (binGraph_out_edges g (binGraph _)); auto |].\n  spec H5; [repeat constructor; intro HH; inversion HH; inversion H9 |].\n  spec H5; [auto |].\n  spec H5; [hnf; auto |].\n  spec H5; [auto |].\n  spec H5; [subst l; auto |].\n\n  unfold reachable_vertices_at.\n  pose proof vertices_at_sepcon_unique_1x (Graph_PointwiseGraph g2'') x0 (reachable g2'' l0) d0.\n  pose proof vertices_at_sepcon_unique_xx g1' (Graph_PointwiseGraph g2'') (Intersection _ (vvalid g1') (fun x => x0 <> x)) (reachable g2'' l0).\n\n  rewrite sepcon_assoc, (add_andp _ _ H10); normalize.\n  rewrite (sepcon_comm (vertices_at _ _)), <- sepcon_assoc, (add_andp _ _ H9); normalize.\n  clear H9 H10.\n  spec H5.\n  {\n    apply is_BinMaFin_disjoint_guard with (x0 := x0) (es0 := nil); auto.\n    + eapply vcopy1_copied_root_valid in H1; auto.\n      subst x0; auto.\n    + intros ? [].\n    + apply (vmap_weaken g1 g2'') in H4.\n      rewrite (copy_vvalid_weak_eq g1 g2 g2'' l l0 H4 H2).\n      apply Disjoint_comm.\n      apply (Disjoint_x1' _ _ _ H11 H12).\n  }\n\n  unfold map in H5; rewrite H3 in BMF.\n  rewrite <- H3 in BMF;\n  specialize (H5 BMF).\n  specialize (H5 (Graph'_is_BinMaFin' _)).\n\n  destruct H5 as [g2' [? [? [? ?]]]].\n  apply (exp_right g2').\n\n  pose proof vertex_at_not_null x0 d0.\n  rewrite (add_andp _ _ H14) at 1.\n  rewrite andp_comm, !sepcon_andp_prop'.\n  apply derives_extract_prop.\n  intro.\n  clear H14. assert (x0 <> null) by congruence; clear H15.\n  \n  apply andp_right; [apply prop_right; split; auto | rewrite sepcon_assoc; apply sepcon_derives; auto].\n  assert (Prop_join (vvalid g1') (vvalid g2'') (vvalid g2')) as HPJ.\n  1: {\n    eapply copy_and_extended_copy; eauto.\n    rewrite <- H7; auto.\n  }\n  assert (Prop_join (Intersection addr (vvalid g1') (fun x1 : addr => x0 <> x1))\n                (vvalid g2'')\n                (Intersection addr (vvalid g2') (fun x1 : addr => x0 <> x1))) as HPJ1.\n  1: {\n    apply Prop_join_shrink1; auto.\n    eapply vcopy1_copied_root_valid in H1; auto.\n    rewrite H3; auto.\n  }\n  rewrite (vertices_at_vertices_identical (Graph_PointwiseGraph g2'') (LGraph_SGraph g2')).\n  rewrite (vertices_at_vertices_identical (LGraph_SGraph g1') (LGraph_SGraph g2')).\n  + erewrite vertices_at_sepcon_xx; [apply derives_refl |].\n    rewrite Prop_join_comm.\n    apply (vmap_weaken g1 g2'') in H4.\n    rewrite <- (copy_vvalid_weak_eq g1 g2 g2'' l l0 H4 H2).\n    auto.\n  + rewrite <- H3 in H13.\n    apply H13.\n    - unfold Included, Ensembles.In; intros.\n      destruct BMF as [BMF _].\n      pose (pg1 := Build_GeneralGraph _ _ _ (fun g: LGraph => BinMaFin' g) (gpredicate_sub_labeledgraph (fun v => x0 <> v) (fun e : addr * LR => ~ In e nil) g1') BMF: Graph').\n      assert (vvalid pg1 x1) by (simpl; auto).\n      apply vvalid_vguard' in H16.\n      simpl in H16.\n      rewrite !Intersection_spec in H16.\n      simpl; tauto.\n    - unfold Included, Ensembles.In; intros.\n      destruct H9 as [X _].\n      pose (pg2 := Build_GeneralGraph _ _ _ (fun g: LGraph => BinMaFin' g) (gpredicate_sub_labeledgraph (fun v => x0 <> v) (fun e : addr * LR => ~ In e nil) g2') X: Graph').\n      assert (vvalid pg2 x1). simpl. rewrite Intersection_spec in H15 |- *. rewrite (proj1 HPJ); tauto.\n      apply vvalid_vguard' in H9.\n      simpl in H9.\n      rewrite !Intersection_spec in H9.\n      simpl; tauto.\n  + apply (vmap_weaken g1 g2'') in H4.\n    pose proof copy_vvalid_weak_eq _ _ _ _ _ H4 H2.\n    rewrite <- H15.\n    apply H10.\n    - intros ? ?; apply vvalid_vguard'; auto.\n    - unfold Included, Ensembles.In; intros.\n      destruct H9 as [X _].\n      pose (pg2 := Build_GeneralGraph _ _ _ (fun g: LGraph => BinMaFin' g) (gpredicate_sub_labeledgraph (fun v => x0 <> v) (fun e : addr * LR => ~ In e nil) g2') X: Graph').\n      assert (vvalid pg2 x1). simpl. rewrite (proj1 HPJ1). tauto.\n      apply vvalid_vguard' in H9.\n      simpl in H9.\n      rewrite !Intersection_spec in H9.\n      simpl; tauto.\nQed.\n\nLemma labeledgraph_add_edge_ecopy1_left: forall (g g1 g2: Graph) (g1' g2': LGraph) (x l r x0 l0: addr),\n  vvalid g x ->\n  vgamma g x = (null, l, r) ->\n  vcopy1 x g g1 g1' ->\n  extended_copy l (g1: LGraph, g1') (g2: LGraph, g2') ->\n  x0 = LocalGraphCopy.vmap g1 x ->\n  l = null /\\ l0 = null \\/ l0 = LocalGraphCopy.vmap g2 l ->\n  is_guarded_BinMaFin' (fun v => x0 <> v) (fun e => ~ In e nil) g2' ->\n  x0 <> null ->\n  let g3 := Graph_egen g2 (x, L) (x0, L): Graph in\n  let g3' := labeledgraph_add_edge g2' (x0, L) x0 l0 (null, L): LGraph in\n  ecopy1 (x, L) (g2: LGraph, g2') (g3: LGraph, g3') /\\\n  is_guarded_BinMaFin' (fun v => x0 <> v) (fun e => ~ In e ((x0, L) :: nil)) g3' /\\\n  (x0, L) = LocalGraphCopy.emap g3 (x, L) /\\\n  dst g3' (x0, L) = l0.\nProof.\n  intros.\n  unfold ecopy1.\n  assert (~ evalid g2' (x0, L)) as HH.\n  1: {\n    eapply is_BinMaFin_not_evalid; eauto; [| intros ? []].\n    eapply extended_copy_vvalid_mono in H2; [exact H2 |].\n    eapply vcopy1_copied_root_valid in H1; auto.\n    subst x0; auto.\n  }\n  split; [split; [| split] | split; [| split]].\n  + reflexivity.\n  + apply WeakMarkGraph.labeledgraph_egen_do_nothing.\n  + assert (g ~=~ g2) as HH0.\n    1: {\n      destruct H1 as [? _], H2 as [? _].\n      rewrite <- H2, <- H1; reflexivity.\n    }\n    assert (x0 = LocalGraphCopy.vmap g2 (src g2 (x, L))) as HH1.\n    1: {\n      rewrite left_right_sound by (rewrite <- (proj1 HH0); auto).\n      destruct H1 as [_ [? _]], H2 as [_ [_ ?]].\n      subst x0.\n      destruct H2 as [_ [? _]].\n      rewrite guarded_pointwise_relation_spec in H2.\n      apply H2.\n      unfold Complement, Ensembles.In; intro.\n      apply reachable_by_foot_prop in H3.\n      apply H3.\n      destruct H1 as [_ [? _]]; auto.\n    }\n    destruct H4.\n    - pose proof LocalGraphCopy.labeledgraph_egen_ecopy1_not_vvalid g2 g2' (x, L) (x0, L) x0 l0.\n      apply H7; clear H7; auto.\n      * destruct H4.\n        subst l0.\n        destruct H5 as [[? ? ?] _].\n        pose proof @valid_not_null' _ _ _ _ (gpredicate_sub_labeledgraph (fun v : addr => x0 <> v)\n            (fun e : addr * LR => ~ In e nil) g2') _ ma' null.\n        intro.\n        apply H5; [| reflexivity].\n        simpl.\n        rewrite Intersection_spec; split; auto.\n      * inversion H0.\n        rewrite <- (si_dst1 _ _ _ HH0); [| apply (@left_valid _ _ _ _ _ _ g (binGraph _)); auto].\n        destruct H4; rewrite H9; subst l.\n        intro.\n        apply (@valid_not_null _ _ _ _ g2 _ (maGraph _) null); auto; reflexivity.\n    - pose proof LocalGraphCopy.labeledgraph_egen_ecopy1 g2 g2' (x, L) (x0, L) x0 l0.\n      apply H7; clear H7; auto.\n\n      subst l0.\n      f_equal.\n      inversion H0.\n      destruct H1 as [? _], H2 as [? _].\n      rewrite <- H1 in H2.\n      rewrite (si_dst1 _ _ _ H2); auto.\n      apply (@left_valid _ _ _ _ _ _ g (binGraph _)); auto.\n  + eapply is_guarded_BinMaFin'_labeledgraph_add_edge; [auto | | exact H5].\n    rewrite Same_set_spec; intro e; simpl.\n    rewrite Intersection_spec.\n    assert (e = (x0, L) <-> (x0, L) = e) by (split; intros; congruence).\n    tauto.\n  + simpl.\n    unfold update_elabel; simpl.\n    destruct_eq_dec (x, L) (x, L); auto; congruence.\n  + subst g3'.\n    simpl.\n    unfold updateEdgeFunc.\n    rewrite if_true; reflexivity.\nQed.\n\nLemma va_labeledgraph_add_edge_left: forall (g g1 g2: Graph) (g1' g2': LGraph) (x l r x0 l0: addr),\n  vvalid g x ->\n  vgamma g x = (null, l, r) ->\n  vcopy1 x g g1 g1' ->\n  extended_copy l (g1: LGraph, g1') (g2: LGraph, g2') ->\n  x0 = LocalGraphCopy.vmap g1 x ->\n  is_guarded_BinMaFin' (fun x => x0 <> x) (fun e => ~ In e nil) g2' ->\n  vertices_at (Intersection _ (vvalid g2') (fun x => x0 <> x)) g2' = vertices_at (Intersection _ (vvalid (labeledgraph_add_edge g2' (x0, L) x0 l0 (null, L))) (fun x => x0 <> x)) (LGraph_SGraph (labeledgraph_add_edge g2' (x0, L) x0 l0 (null, L))).\nProof.\n  intros.\n  eapply va_labeledgraph_add_edge_eq'; eauto.\n  eapply is_BinMaFin_not_evalid; eauto.\n  + eapply extended_copy_vvalid_mono in H2; [exact H2 |].\n    eapply vcopy1_copied_root_valid in H1; auto.\n    subst x0; auto.\n  + intros ? [].\nQed.\n\nLemma va_labeledgraph_egen_left: forall (g2: Graph) (x x0: addr),\n  reachable_vertices_at x g2 = reachable_vertices_at x (Graph_egen g2 (x, L) (x0, L)).\nProof.\n  intros.\n  apply va_labeledgraph_egen_eq.\nQed.\n\nLemma extend_copy_right: forall (g g1 g2 g3 g4: Graph) (g1' g2' g3': LGraph) (g4'': Graph') (x l r x0 r0: addr) d0,\n  vvalid g x ->\n  vgamma g x = (null, l, r) ->\n  vcopy1 x g g1 g1' ->\n  extended_copy l (g1: LGraph, g1') (g2: LGraph, g2') ->\n  ecopy1 (x, L) (g2: LGraph, g2') (g3: LGraph, g3') ->\n  copy r g3 g4 g4'' ->\n  x0 = LocalGraphCopy.vmap g1 x ->\n  (x0, L) = LocalGraphCopy.emap g3 (x, L) ->\n  r = null /\\ r0 = null \\/ r0 = LocalGraphCopy.vmap g4 r ->\n  is_guarded_BinMaFin' (fun v => x0 <> v) (fun e => ~ In e ((x0, L) :: nil)) g3' ->\n  @derives pred _\n  (vertex_at x0 d0 * vertices_at (Intersection _ (vvalid g3') (fun x => x0 <> x)) g3' * reachable_vertices_at r0 g4'') \n  (EX g4': LGraph,\n    !! (extended_copy r (g3: LGraph, g3') (g4: LGraph, g4') /\\ is_guarded_BinMaFin' (fun v => x0 <> v) (fun e => ~ In e ((x0, L) :: nil)) g4') && \n   (vertex_at x0 d0 * vertices_at (Intersection _ (vvalid g4') (fun x => x0 <> x)) g4')).\nProof.\n  intros.\n  rename H8 into BMF.\n  inversion H0.\n  pose proof @vcopy1_edge_copy_list_weak_copy_extended_copy' _ _ _ _ _ _ _ _ _ _ BinMaFin'_Normal x ((x, L) :: (x, R) :: nil) ((x, L) :: nil) (x, R) nil g g1 g3 g1' g3' g4 g4'' x0 H.\n  spec H8; [simpl; unfold Complement, Ensembles.In; congruence |].\n  spec H8; [reflexivity |].\n  spec H8; [intros; apply (binGraph_out_edges g (binGraph _)); auto |].\n  spec H8; [repeat constructor; intro HH; inversion HH; inversion H12 |].\n  spec H8; [auto |].\n  spec H8.\n  1: {\n    unfold edge_copy_list; simpl map.\n    split_relation_list (@nil (@LGraph _ addr (addr * LR) unit * @LGraph _ addr (addr * LR) unit)).\n    unfold edge_copy.\n    split_relation_list ((g2: LGraph, g2') :: nil); auto.\n    rewrite H10; auto.\n  }\n  spec H8; [subst r; auto |].\n  spec H8; [subst r; auto |].\n\n  unfold reachable_vertices_at.\n  pose proof vertices_at_sepcon_unique_1x (Graph_PointwiseGraph g4'') x0 (reachable g4'' r0) d0.\n  pose proof vertices_at_sepcon_unique_xx g3' (Graph_PointwiseGraph g4'') (Intersection _ (vvalid g3') (fun x => x0 <> x)) (reachable g4'' r0).\n\n  rewrite sepcon_assoc, (add_andp _ _ H13); normalize.\n  rewrite (sepcon_comm (vertices_at _ _)), <- sepcon_assoc, (add_andp _ _ H12); normalize.\n  clear H12 H13.\n  spec H8.\n  1: {\n    apply is_BinMaFin_disjoint_guard with (x0 := x0) (es0 := (x0, L) :: nil); auto.\n    + eapply ecopy1_vvalid_mono in H3; [exact H3 |].\n      eapply extended_copy_vvalid_mono in H2; [exact H2 |].\n      eapply vcopy1_copied_root_valid in H1; auto.\n      subst x0; auto.\n    + intros ? [? | []].\n      subst e; auto.\n    + apply (vmap_weaken g3 g4'') in H7.\n      rewrite (copy_vvalid_weak_eq g3 g4 g4'' r r0 H7 H4).\n      apply Disjoint_comm.\n      apply (Disjoint_x1' _ _ _ H14 H15).\n  }\n\n  unfold map in H8. rewrite H6 in BMF.\n  specialize (H8 BMF).\n  specialize (H8 (Graph'_is_BinMaFin' _)).\n\n  destruct H8 as [g4' [? [? [? ?]]]].\n  apply (exp_right g4').\n\n  pose proof vertex_at_not_null x0 d0.\n  rewrite (add_andp _ _ H17) at 1.\n  rewrite andp_comm, !sepcon_andp_prop'.\n  apply derives_extract_prop.\n  intro.\n  clear H17. assert (x0 <> null) by congruence; clear H18.\n\n  pose proof (extend_copy_emap_root g g1 g3 g4 g1' g3' g4' x ((x, L) :: (x, R) :: nil) ((x, L) :: nil) (x, R) nil H).\n  spec H18; [simpl; unfold Complement, Ensembles.In; congruence |].\n  spec H18; [reflexivity |].\n  spec H18; [intros; apply (binGraph_out_edges g (binGraph _)); auto |].\n  spec H18; [repeat constructor; intro HH; inversion HH; inversion H19 |].\n  spec H18; [auto |].\n  spec H18.\n  1: {\n    unfold edge_copy_list; simpl map.\n    split_relation_list (@nil (@LGraph _ addr (addr * LR) unit * @LGraph _ addr (addr * LR) unit)).\n    unfold edge_copy.\n    split_relation_list ((g2: LGraph, g2') :: nil); auto.\n    rewrite H10; auto.\n  }\n  spec H18; [subst r; auto |].\n  rewrite H6.\n  replace ((@LocalGraphCopy.emap _ _ _ _ _ _ _ _ _ _ _ _ GMS g3 (x, L)) :: nil) with (LocalGraphCopy.emap g4 (x, L) :: nil) by (symmetry; auto).\n  simpl in H18.\n\n  apply andp_right; [apply prop_right; split; auto | rewrite sepcon_assoc; apply sepcon_derives; auto].\n  assert (Prop_join (vvalid g3') (vvalid g4'') (vvalid g4')).\n  1: {\n    eapply copy_and_extended_copy; eauto.\n    rewrite <- H11; auto.\n  }\n  assert (Prop_join (Intersection addr (vvalid g3') (fun x1 : addr => x0 <> x1))\n                (vvalid g4'')\n                (Intersection addr (vvalid g4') (fun x1 : addr => x0 <> x1))) as HPJ1.\n  1: {\n    apply Prop_join_shrink1; auto.\n    eapply ecopy1_vvalid_mono in H3; [exact H3 |].\n    eapply extended_copy_vvalid_mono in H2; [exact H2 |].\n    eapply vcopy1_copied_root_valid in H1; auto.\n    rewrite H5; auto.\n  }\n  rewrite (vertices_at_vertices_identical (Graph_PointwiseGraph g4'') (LGraph_SGraph g4')).\n  rewrite (vertices_at_vertices_identical (LGraph_SGraph g3') (LGraph_SGraph g4')).\n  + erewrite vertices_at_sepcon_xx; [apply derives_refl |].\n    rewrite Prop_join_comm.\n    apply (vmap_weaken g3 g4'') in H7.\n    rewrite <- (copy_vvalid_weak_eq g3 g4 g4'' r r0 H7 H4).\n    auto.\n  + rewrite <- H5 in H16.\n    apply H16.\n    - unfold Included, Ensembles.In; intros.\n      destruct BMF as [BMF _].\n      pose (pg1 := Build_GeneralGraph _ _ _ (fun g: LGraph => BinMaFin' g) (gpredicate_sub_labeledgraph (fun v => x0 <> v) (fun e : addr * LR => ~ In e (LocalGraphCopy.emap g3 (x, L) :: nil)) g3') BMF: Graph').\n      assert (vvalid pg1 x1) by (simpl; auto).\n      apply vvalid_vguard' in H21.\n      simpl in H21.\n      rewrite !Intersection_spec in H21.\n      simpl; tauto.\n    - unfold Included, Ensembles.In; intros.\n      destruct H12 as [X _].\n      pose (pg2 := Build_GeneralGraph _ _ _ (fun g: LGraph => BinMaFin' g) (gpredicate_sub_labeledgraph (fun v => x0 <> v) (fun e : addr * LR => ~ In e (LocalGraphCopy.emap g4 (x, L) :: nil)) g4') X: Graph').\n      assert (vvalid pg2 x1). simpl. rewrite (proj1 HPJ1); tauto.\n      apply vvalid_vguard' in H12.\n      simpl in H12.\n      rewrite !Intersection_spec in H12.\n      simpl; tauto.\n  + apply (vmap_weaken g3 g4'') in H7.\n    pose proof copy_vvalid_weak_eq _ _ _ _ _ H7 H4.\n    rewrite <- H20.\n    apply H13.\n    - intros ? ?; apply vvalid_vguard'; auto.\n    - unfold Included, Ensembles.In; intros.\n      destruct H12 as [X _].\n      pose (pg2 := Build_GeneralGraph _ _ _ (fun g: LGraph => BinMaFin' g) (gpredicate_sub_labeledgraph (fun v => x0 <> v) (fun e : addr * LR => ~ In e _) g4') X: Graph').\n      assert (vvalid pg2 x1). simpl. rewrite (proj1 HPJ1). tauto.\n      apply vvalid_vguard' in H12.\n      simpl in H12.\n      rewrite !Intersection_spec in H12.\n      simpl; tauto.\nQed.\n\nLemma labeledgraph_add_edge_ecopy1_right: forall (g g1 g2 g3 g4: Graph) (g1' g2' g3' g4': LGraph) (x l r x0 r0: addr),\n  vvalid g x ->\n  vgamma g x = (null, l, r) ->\n  vcopy1 x g g1 g1' ->\n  extended_copy l (g1: LGraph, g1') (g2: LGraph, g2') ->\n  ecopy1 (x, L) (g2: LGraph, g2') (g3: LGraph, g3') ->\n  extended_copy r (g3: LGraph, g3') (g4: LGraph, g4') ->\n  x0 = LocalGraphCopy.vmap g1 x ->\n  (x0, L) = LocalGraphCopy.emap g3 (x, L) ->\n  r = null /\\ r0 = null \\/ r0 = LocalGraphCopy.vmap g4 r ->\n  is_guarded_BinMaFin' (fun v => x0 <> v) (fun e => ~ In e ((x0, L) :: nil)) g4' ->\n  x0 <> null ->\n  let g5 := Graph_egen g4 (x, R) (x0, R): Graph in\n  let g5' := labeledgraph_add_edge g4' (x0, R) x0 r0 (null, L): LGraph in\n  ecopy1 (x, R) (g4: LGraph, g4') (g5: LGraph, g5') /\\\n  is_guarded_BinMaFin' (fun v => x0 <> v) (fun e => ~ In e ((x0, L) :: (x0, R) :: nil)) g5' /\\\n  (x0, R) = LocalGraphCopy.emap g5 (x, R) /\\\n  dst g5' (x0, R) = r0.\nProof.\n  intros.\n  unfold ecopy1.\n  assert (~ evalid g4' (x0, R)) as HH.\n  1: {\n    eapply is_BinMaFin_not_evalid; eauto.\n    + eapply extended_copy_vvalid_mono in H4; [exact H4 |].\n      eapply ecopy1_vvalid_mono in H3; [exact H3 |].\n      eapply extended_copy_vvalid_mono in H2; [exact H2 |].\n      eapply vcopy1_copied_root_valid in H1; auto.\n      subst x0; auto.\n    + intros ? [? | []].\n      subst e; auto.\n    + intros [? | []].\n      inversion H10.\n  }\n  split; [split; [| split] | split; [| split]].\n  + reflexivity.\n  + apply WeakMarkGraph.labeledgraph_egen_do_nothing.\n  + assert (g ~=~ g4) as HH0.\n    1: {\n      destruct H1 as [? _], H2 as [? _], H3 as [? _], H4 as [? _].\n      rewrite <- H4, <- H3, <- H2, <- H1; reflexivity.\n    }\n    assert (x0 = LocalGraphCopy.vmap g4 (src g4 (x, R))) as HH1.\n    1: {\n      rewrite left_right_sound by (rewrite <- (proj1 HH0); auto).\n      subst x0.\n      assert (WeakMarkGraph.marked g1 x).\n      1: {\n        destruct H1 as [_ [? _]].\n        destruct H1 as [_ [? _]]; auto.\n      }\n      assert (WeakMarkGraph.marked g3 x).\n      1: {\n        destruct H3 as [_ [? _]].\n        rewrite <- (proj2 H3).\n        eapply WeakMarkGraph.mark_marked; [destruct H2 as [_ [H2 _]]; exact H2 | auto].\n      }\n      rewrite (extended_copy_vmap_root g1 g2 g1' g2' l x) by auto.\n      rewrite (ecopy1_vmap_root g2 g3 g2' g3' (x, L) x H3).\n      rewrite (extended_copy_vmap_root g3 g4 g3' g4' r x) by auto.\n      reflexivity.\n    }\n    destruct H7.\n    - pose proof LocalGraphCopy.labeledgraph_egen_ecopy1_not_vvalid g4 g4' (x, R) (x0, R) x0 r0.\n      apply H10; clear H10; auto.\n      * destruct H7.\n        subst r0.\n        destruct H8 as [[? ? ?] _].\n        pose proof @valid_not_null' _ _ _ _ (gpredicate_sub_labeledgraph (fun v : addr => x0 <> v)\n            (fun e : addr * LR => ~ In e ((x0, L) :: nil)) g4') _ ma' null.\n        intro.\n        apply H8; [| reflexivity].\n        simpl.\n        rewrite Intersection_spec; split; auto.\n      * inversion H0.\n        rewrite <- (si_dst1 _ _ _ HH0); [| apply (@right_valid _ _ _ _ _ _ g (binGraph _)); auto].\n        destruct H7; rewrite H13; subst r.\n        intro.\n        apply (@valid_not_null _ _ _ _ g4 _ (maGraph _) null); auto; reflexivity.\n    - pose proof LocalGraphCopy.labeledgraph_egen_ecopy1 g4 g4' (x, R) (x0, R) x0 r0.\n      apply H10; clear H10; auto.\n\n      subst r0.\n      f_equal.\n      inversion H0.\n      rewrite (si_dst1 _ _ _ HH0); auto.\n      apply (@right_valid _ _ _ _ _ _ g (binGraph _)); auto.\n  + eapply is_guarded_BinMaFin'_labeledgraph_add_edge; [auto | | exact H8].\n    rewrite Same_set_spec; intro e; simpl.\n    rewrite Intersection_spec.\n    assert (e = (x0, R) <-> (x0, R) = e) by (split; intros; congruence).\n    tauto.\n  + simpl.\n    unfold update_elabel; simpl.\n    destruct_eq_dec (x, R) (x, R); auto; congruence.\n  + subst g5'.\n    simpl.\n    unfold updateEdgeFunc.\n    rewrite if_true; reflexivity.\nQed.\n\nLemma va_labeledgraph_add_edge_right: forall (g g1 g2 g3 g4: Graph) (g1' g2' g3' g4': LGraph) (x l r x0 r0: addr),\n  vvalid g x ->\n  vgamma g x = (null, l, r) ->\n  vcopy1 x g g1 g1' ->\n  extended_copy l (g1: LGraph, g1') (g2: LGraph, g2') ->\n  ecopy1 (x, L) (g2: LGraph, g2') (g3: LGraph, g3') ->\n  extended_copy r (g3: LGraph, g3') (g4: LGraph, g4') ->\n  x0 = LocalGraphCopy.vmap g1 x ->\n  is_guarded_BinMaFin' (fun x => x0 <> x) (fun e => ~ In e ((x0, L) :: nil)) g4' ->\n  vertices_at (Intersection _ (vvalid g4') (fun x => x0 <> x)) g4' = vertices_at (Intersection _ (vvalid (labeledgraph_add_edge g4' (x0, R) x0 r0 (null, L))) (fun x => x0 <> x)) (LGraph_SGraph (labeledgraph_add_edge g4' (x0, R) x0 r0 (null, L))).\nProof.\n  intros.\n  eapply va_labeledgraph_add_edge_eq'; eauto.\n  eapply is_BinMaFin_not_evalid; eauto.\n  + eapply extended_copy_vvalid_mono in H4; [exact H4 |].\n    eapply ecopy1_vvalid_mono in H3; [exact H3 |].\n    eapply extended_copy_vvalid_mono in H2; [exact H2 |].\n    eapply vcopy1_copied_root_valid in H1; auto.\n    subst x0; auto.\n  + intros ? [? | []].\n    subst e; auto.\n  + intros [? | []].\n    inversion H7.\nQed.\n\nLemma va_labeledgraph_egen_right: forall (g2: Graph) (x x0: addr),\n  reachable_vertices_at x g2 = reachable_vertices_at x (Graph_egen g2 (x, R) (x0, R)).\nProof.\n  intros.\n  apply va_labeledgraph_egen_eq.\nQed.\n\nLemma copy_final: forall (g g1 g2 g3 g4 g5: Graph) (g1' g2' g3' g4' g5': LGraph) x l r x0 l0 r0,\n  vvalid g x ->\n  vgamma g x = (null, l, r) ->\n  x0 = LocalGraphCopy.vmap g1 x ->\n  l = null /\\ l0 = null \\/ l0 = LocalGraphCopy.vmap g2 l ->\n  forall (H999: dst g3' (x0, L) = l0), \n  (x0, L) = LocalGraphCopy.emap g3 (x, L) ->\n  r = null /\\ r0 = null \\/ r0 = LocalGraphCopy.vmap g4 r ->\n  forall (H998: dst g5' (x0, R) = r0), \n  (x0, R) = LocalGraphCopy.emap g5 (x, R) ->\n  is_guarded_BinMaFin'\n    (fun v => x0 <> v)\n    (fun e => ~ In e ((x0, L) :: (x0, R) :: nil)) g5' ->\n  vcopy1 x g g1 g1' ->\n  extended_copy l (g1: LGraph, g1') (g2: LGraph, g2') ->\n  ecopy1 (x, L) (g2: LGraph, g2') (g3: LGraph, g3') ->\n  extended_copy r (g3: LGraph, g3') (g4: LGraph, g4') ->\n  ecopy1 (x, R) (g4: LGraph, g4') (g5: LGraph, g5') ->\n  @derives pred _\n  (vertex_at x0 (null, l0, r0) * vertices_at (Intersection _ (vvalid g5') (fun v => x0 <> v)) g5')\n  (EX gg5': Graph',\n  !! (copy x g g5 gg5' /\\ LocalGraphCopy.vmap g1 x = LocalGraphCopy.vmap g5 x) && reachable_vertices_at x0 gg5').\nProof.\n  intros.\n  assert (copy x g g5 g5').\n  {\n    eapply vcopy1_edge_copy_list_copy.\n    + assumption.\n    + simpl in H0 |- *; unfold Complement, Ensembles.In. congruence.\n    + intros; apply (binGraph_out_edges g (binGraph _)); auto.\n    + repeat constructor; intro HH; inversion HH; inversion H12.\n    + exact H7.\n    + hnf.\n      exists (g3: LGraph, g3').\n      - exists (g1: LGraph, g1'); auto.\n        exists (g2: LGraph, g2').\n        * exists (g1: LGraph, g1'); auto.\n          simpl in H0.\n          inversion H0.\n          rewrite H14.\n          exact H8.\n        * exact H9.\n      - hnf.\n        exists (g4: LGraph, g4').\n        * exists (g3: LGraph, g3'); auto.\n          simpl in H0.\n          inversion H0.\n          rewrite H15.\n          exact H10.\n        * exact H11.\n  }\n  rewrite (add_andp _ _ (vertex_at_not_null x0 (null, l0, r0))).\n  normalize.\n  assert (x0 <> null) as LOCAL' by congruence; clear H13.\n\n  assert (LocalGraphCopy.vmap g5 x = x0 /\\\n          src g5' (x0, L) = x0 /\\\n          src g5' (x0, R) = x0 /\\\n          dst g5' (x0, L) = l0 /\\\n          dst g5' (x0, R) = r0 /\\\n          evalid g5' (x0, L) /\\\n          evalid g5' (x0, R) /\\\n          vvalid g5' x0) as LOCAL.\n  {\n    pose proof fun H => extended_copy_vmap_root _ _ _ _ _ x H H8 as Hvmap12.\n    specialize (Hvmap12 ltac:(simpl in H1 |- *; subst x0; congruence)).\n    pose proof ecopy1_vmap_root _ _ _ _ _ x H9 as Hvmap23.\n    pose proof fun H => extended_copy_vmap_root _ _ _ _ _ x H H10 as Hvmap34.\n    specialize (Hvmap34 ltac:(simpl in H1, Hvmap12, Hvmap23 |- *; subst x0; congruence)).\n    pose proof ecopy1_vmap_root _ _ _ _ _ x H11 as Hvmap45.\n    split; [congruence |].\n    pose proof vcopy1_copied_root_valid _ _ _ _ _ H7 H1 as Hx0_g5'.\n    apply (extended_copy_vvalid_mono _ _ _ _ _ _ H8) in Hx0_g5'.\n    apply (ecopy1_vvalid_mono _ _ _ _ _ _ H9) in Hx0_g5'.\n    apply (extended_copy_vvalid_mono _ _ _ _ _ _ H10) in Hx0_g5'.\n    apply (ecopy1_vvalid_mono _ _ _ _ _ _ H11) in Hx0_g5'.\n    assert (vvalid g2 x) as Hx_g2.\n    {\n      rewrite <- (proj1 (proj1 H8)), <- (proj1 (proj1 H7)).\n      auto.\n    }\n    assert (vvalid g3 x) as Hx_g3.\n    {\n      rewrite <- (proj1 (proj1 H9)).\n      auto.\n    }\n    assert (vvalid g4 x) as Hx_g4.\n    {\n      rewrite <- (proj1 (proj1 H10)).\n      auto.\n    }\n    assert (vvalid g5 x) as Hx_g5.\n    {\n      rewrite <- (proj1 (proj1 H11)).\n      auto.\n    }\n    assert (src g3' (x0, L) = x0 /\\ dst g3' (x0, L) = l0 /\\ evalid g3' (x0, L)) as [Hx0L_src [Hx0L_dst Hx0L_v]].\n    {\n      destruct H9 as [_ [_ ?]].\n      destruct H9 as [? [? [? [? [? ?]]]]].\n      destruct H15 as [_ [? _]].\n      destruct H15 as [? _].\n      rewrite (H15 (x0, L)).\n      rewrite left_right_sound in H16 by auto.\n      rewrite <- H3 in *.\n      rewrite <- H16 by auto.\n      simpl in H0; inversion H0.\n      split; [congruence | split; tauto].\n    }\n    pose proof (extended_copy_evalid_mono _ _ _ _ _ _ H10 Hx0L_v) as Hx0L_v'.\n    pose proof proj2 (proj2 H10).\n    destruct H13 as [_ [_ [_ [? [_ _]]]]].\n    destruct H13 as [_ [_ [? ?]]].\n    rewrite H13 in Hx0L_src by auto.\n    rewrite H14 in Hx0L_dst by auto.\n    clear H13 H14 Hx0L_v; rename Hx0L_v' into Hx0L_v.\n    pose proof (ecopy1_evalid_mono _ _ _ _ _ _ H11 Hx0L_v) as Hx0L_v'.\n    pose proof proj2 (proj2 H11).\n    destruct H13 as [_ [_ [_ [? [_ _]]]]].\n    destruct H13 as [_ [_ [? ?]]].\n    rewrite H13 in Hx0L_src by auto.\n    rewrite H14 in Hx0L_dst by auto.\n    clear H13 H14 Hx0L_v; rename Hx0L_v' into Hx0L_v.\n    assert (src g5' (x0, R) = x0 /\\ dst g5' (x0, R) = r0 /\\ evalid g5' (x0, R)) as [Hx0R_src [Hx0R_dst Hx0R_v]].\n    {\n      destruct H11 as [_ [_ ?]].\n      destruct H11 as [? [? [? [? [? ?]]]]].\n      destruct H15 as [_ [? _]].\n      destruct H15 as [? _].\n      rewrite (H15 (x0, R)).\n      rewrite left_right_sound in H16 by auto.\n      rewrite <- H5 in *.\n      rewrite <- H16 by auto.\n      simpl in H0; inversion H0.\n      split; [congruence | split; tauto].\n    }\n    tauto.\n  }\n  pose proof H6.\n  destruct H13 as [? _].\n  assert (BinMaFin' g5').\n  {\n    constructor.\n    + constructor.\n      - intros.\n        congruence.\n      - intros.\n        destruct (classic (x0 = x2)).\n        * subst x2.\n          destruct (classic (e = (x0, L))); [| destruct (classic (e = (x0, R)))].\n         ++ subst e; tauto.\n         ++ subst e; tauto.\n         ++ split; [intros [? ?]; exfalso | tauto].\n            pose proof @ma' _ _ x1.\n            pose proof @valid_graph' _ _ _ _ _ _ H18 e.\n            simpl in H19.\n            rewrite !Intersection_spec in H19.\n            specialize (H19 ltac:(pose proof @eq_sym _ (x0, L) e; pose proof @eq_sym _ (x0, R) e; tauto)).\n            rewrite H16 in H19. tauto.\n        * pose proof @bin' _ _ x1.\n          pose proof @only_two_edges _ _ _ _ _ _ _ H15 x2 e.\n          simpl in H16.\n          rewrite !Intersection_spec in H16.\n          specialize (H16 ltac:(tauto)).\n          rewrite <- H16; split; [| tauto].\n          intros [? ?]; repeat split; auto.\n          intros [| [| []]]; subst e; rewrite <- H17 in H14; apply H14; symmetry; tauto.\n    + constructor.\n      - intros.\n        destruct (classic ((x0, L) = e)); [| destruct (classic ((x0, R) = e))].\n        * unfold is_null_SGBA; simpl.\n          subst e.\n          replace (src g5' (x0, L)) with x0 by (symmetry; tauto).\n          tauto.\n        * unfold is_null_SGBA; simpl.\n          subst e.\n          replace (src g5' (x0, R)) with x0 by (symmetry; tauto).\n          tauto.\n        * pose proof @ma' _ _ x1.\n          pose proof @valid_graph' _ _ _ _ _ _ H16.\n          unfold weak_valid in H17.\n          simpl in H17.\n          specialize (H17 e).\n          rewrite !Intersection_spec in H17.\n          specialize (H17 ltac:(tauto)).\n          tauto.\n      - intros.\n        pose proof @ma' _ _ x1.\n        pose proof @valid_not_null' _ _ _ _ _ _ H15.\n        specialize (H16 x2).\n        simpl in H16.\n        rewrite Intersection_spec in H16.\n        destruct (classic (x0 = x2)); [subst x2 |]; tauto.\n    + assert (FiniteGraph\n           (gpredicate_sub_labeledgraph (fun v : addr => x0 = v)\n              (fun e : addr * LR => In e ((x0, L) :: (x0, R) :: nil)) g5')).\n      {\n        constructor; simpl.\n        - exists (x0 :: nil).\n          split; [repeat constructor; intros [] |].\n          intros.\n          rewrite Intersection_spec.\n          split; intros.\n          * destruct H13 as [|[]].\n            subst x2.\n            tauto.\n          * left.\n            tauto.\n        - exists ((x0, L) :: (x0, R) :: nil).\n          split; [repeat constructor; [intros [| []]; congruence | intros []] |].\n          intros.\n          rewrite Intersection_spec.\n          split; intros.\n          * destruct H13 as [| [| []]];\n            subst x2; tauto.\n          * simpl. tauto.\n      }\n      apply (@fin' _ _) in x1.\n      pose proof fun H H0 => finite_graph_join g5' _ _ (fun _ => True) _ _ (fun _ => True) H H0 x1 X.\n      spec X0.\n    {\n      split.\n      + intros; tauto.\n      + intros; tauto.\n    }\n    spec X0.\n    {\n      split.\n      + intros; tauto.\n      + intros; tauto.\n    }\n    pose proof @gpredicate_sub_labeledgraph_equiv _ _ _ _ _ _ _ g5' (fun _ => True) (vvalid g5') (fun _ => True) (evalid g5').\n    spec H13.\n      { rewrite Same_set_spec; intro; rewrite !Intersection_spec; tauto. }\n    spec H13.\n      { rewrite Same_set_spec; intro; rewrite !Intersection_spec; tauto. }\n    pose proof finite_graph_si _ _ (proj1 H13); clear H13.\n    pose proof @gpredicate_sub_labeledgraph_self _ _ _ _ _ _ _ g5'.\n    pose proof finite_graph_si _ _ (proj1 H13); clear H13.\n    apply X2, X1, X0.\n  }\n  apply (exp_right (Build_GeneralGraph _ _ _ _ (labeledgraph_vgen g5' x0 null) X)); clear x1.\n  apply andp_right.\n  + apply prop_right.\n    split; auto.\n    rewrite <- H1; symmetry; tauto.\n  + match goal with\n    | |- _ |-- _ ?A => change A with (labeledgraph_vgen g5' x0 null)\n    end.\n    replace (vertices_at (Intersection addr (vvalid g5') (fun v : addr => x0 <> v)) g5')\n      with (vertices_at (Intersection addr (vvalid g5') (fun v : addr => x0 <> v)) (LGraph_SGraph (labeledgraph_vgen g5' x0 null))).\n    2: {\n       apply vertices_at_vertices_identical.\n       rewrite (update_irr _ g5' x0) by (rewrite Intersection_spec; tauto).\n       apply (GSG_VGenPreserve (Intersection addr (vvalid g5') (fun v : addr => x0 <> v)) g5').\n       + reflexivity.\n       + unfold Included, Ensembles.In; intro; rewrite Intersection_spec.\n         intros [? _]. apply (vvalid_vguard' (Build_GeneralGraph _ _ _ _ g5' X)), H13.\n       + unfold Included, Ensembles.In; intro; rewrite Intersection_spec.\n         intros [? _]. apply (vvalid_vguard' (Build_GeneralGraph _ _ _ _ g5' X)), H13.\n    }\n    change (vvalid g5') with (vvalid (labeledgraph_vgen g5' x0 null)).\n    apply derives_refl', vertices_at_sepcon_1x.\n    - apply Prop_join_comm.\n      rewrite <- copy_vvalid_weak_eq; [apply Ensemble_join_Intersection_Complement | .. | exact H12].\n      * unfold Included, Ensembles.In; intros; subst; tauto.\n      * intros; tauto. \n      * right; symmetry; tauto.\n    - change (vgamma (Graph_PointwiseGraph (labeledgraph_vgen g5' x0 null)) x0)\n        with (vgamma (LGraph_SGraph (labeledgraph_vgen g5' x0 null)) x0).\n      simpl.\n      unfold update_vlabel. rewrite if_true by reflexivity.\n      repeat f_equal; tauto.\nQed.\n\nEnd PointwiseGraph_Copy_Bin.\n", "meta": {"author": "CertiGraph", "repo": "CertiGraph", "sha": "1be51414c139f8bc16b3e22f72989e454c37ce3c", "save_path": "github-repos/coq/CertiGraph-CertiGraph", "path": "github-repos/coq/CertiGraph-CertiGraph/CertiGraph-1be51414c139f8bc16b3e22f72989e454c37ce3c/msl_application/GraphBin_Copy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.27943491271435317}}
{"text": "Require Import Fiat.Common Fiat.Computation\n        Fiat.ADT.ADTSig Fiat.ADT.Core\n        Fiat.ADTRefinement.Core Fiat.ADTRefinement.SetoidMorphisms.\n\nSection SimplifyRep.\n\n  (* If a representation has extraneous information (perhaps intermediate\n     data introduced during refinement), simplifying the representation\n     is a valid refinement. *)\n\n  Variable oldRep : Type. (* The old representation type. *)\n  Variable newRep : Type. (* The new representation type. *)\n\n  Variable simplifyf : oldRep -> newRep. (* The simplification function. *)\n  Variable concretize : newRep -> oldRep. (* A map to the enriched representation. *)\n\n  (* The abstraction relation between old and new representations. *)\n  Variable AbsR : oldRep -> newRep -> Prop.\n  Notation \"ro ≃ rn\" := (AbsR ro rn) (at level 70).\n\n  (*Definition simplifyMethod\n             (Dom : list Type)\n             (Cod : Type)\n             (oldMeth : methodType oldRep Dom Cod)\n             r_n n : Comp (newRep * Cod) :=\n    (r_o' <- (oldMeth (concretize r_n) n);\n     ret (simplifyf (fst r_o'), snd r_o'))%comp.\n\n  Definition simplifyConstructor\n             (Dom : Type)\n             (oldConstr : constructorType oldRep Dom)\n             n : Comp newRep :=\n    (or <- oldConstr n;\n     ret (simplifyf or))%comp.\n\n  Variable Sig : ADTSig. (* The signature of the ADT being simplified. *)\n\n  Definition simplifyRep oldConstr oldMeths :\n    (forall r_o, r_o ≃ simplifyf r_o) ->\n    (forall r_n r_o,\n       (r_o ≃ r_n) ->\n       forall idx n,\n         refineEquiv (r_o'' <- oldMeths idx r_o n;\n                      r_n' <- {r_n' | fst r_o'' ≃ r_n'};\n                      ret (r_n', snd r_o''))\n                     (r_o'' <- oldMeths idx (concretize r_n) n;\n                      ret (simplifyf (fst r_o''), snd r_o''))) ->\n    refineADT\n      (@Build_ADT Sig oldRep oldConstr oldMeths)\n      (@Build_ADT Sig newRep\n                  (fun idx => simplifyConstructor (oldConstr idx))\n                  (fun idx => simplifyMethod (oldMeths idx))).\n  Proof.\n    econstructor 1 with\n    (AbsR := AbsR); simpl; eauto.\n    - unfold simplifyConstructor, refine; intros;\n      computes_to_inv; repeat computes_to_econstructor; try subst; eauto.\n    - unfold simplifyMethod; intros.\n      eapply H0; eauto.\n  Qed. *)\n\nEnd SimplifyRep.\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/ADTRefinement/Refinements/SimplifyRep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2794010886696876}}
{"text": "From iris.program_logic Require Export language ectx_language ectxi_language.\nFrom iris.program_logic Require Import lifting.\nFrom iris.algebra Require Import auth frac agree gmap list excl.\nFrom F_mu_ref_conc_sub 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 tpoolUR : ucmraT := gmapUR nat (exclR (exprO F_mu_ref_conc_lang)).\nDefinition cfgUR := prodUR tpoolUR (gen_heapUR loc val).\n\nFixpoint to_tpool_go (i : nat) (tp : list expr) : tpoolUR :=\n  match tp with\n  | [] => ∅\n  | e :: tp => <[i:=Excl e]>(to_tpool_go (S i) tp)\n  end.\nDefinition to_tpool : list expr → tpoolUR := to_tpool_go 0.\n\n(** The CMRA for the thread pool. *)\nClass cfgSG Σ := CFGSG { cfg_inG :> inG Σ (authR cfgUR); cfg_name : gname }.\n\nSection definitionsS.\n  Context `{cfgSG Σ, invG Σ}.\n\n  Definition heapS_mapsto (l : loc) (q : Qp) (v: val) : iProp Σ :=\n    own cfg_name (◯ (ε, {[ l := (q, to_agree v) ]})).\n\n  Definition tpool_mapsto (j : nat) (e: expr) : iProp Σ :=\n    own cfg_name (◯ ({[ j := Excl e ]}, ∅)).\n\n  Definition spec_inv (ρ : cfg F_mu_ref_conc_lang) : iProp Σ :=\n    (∃ tp σ, own cfg_name (● (to_tpool tp, to_gen_heap σ))\n                 ∗ ⌜rtc erased_step ρ (tp,σ)⌝)%I.\n  Definition spec_ctx (ρ : cfg F_mu_ref_conc_lang) : iProp Σ :=\n    inv specN (spec_inv ρ).\n\n  Global Instance heapS_mapsto_timeless l q v : Timeless (heapS_mapsto l q v).\n  Proof. apply _. Qed.\n  Global Instance spec_ctx_persistent ρ : Persistent (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\") : bi_scope.\nNotation \"l ↦ₛ v\" := (heapS_mapsto l 1 v) (at level 20) : bi_scope.\nNotation \"j ⤇ e\" := (tpool_mapsto j e) (at level 20) : bi_scope.\n\nLtac iAsimpl :=\n  repeat match goal with\n  | |- context [ (_ ⤇ ?e)%I ] => progress (\n    let e' := fresh in evar (e':expr);\n    assert (e = e') as ->; [asimpl; unfold e'; reflexivity|];\n    unfold e'; clear e')\n  | |- context [ WP ?e @ _ {{ _ }}%I ] => progress (\n    let e' := fresh in evar (e':expr);\n    assert (e = e') as ->; [asimpl; unfold e'; reflexivity|];\n    unfold e'; clear e')\n  end.\n\nSection conversions.\n  Context `{cfgSG Σ}.\n\n  (** Conversion to tpools and back *)\n  Lemma to_tpool_valid es : ✓ to_tpool es.\n  Proof.\n    rewrite /to_tpool. move: 0.\n    induction es as [|e es]=> n //.\n    by apply: insert_valid.\n  Qed.\n\n  Lemma tpool_lookup tp j : to_tpool tp !! j = Excl <$> tp !! j.\n  Proof.\n    cut (∀ i, to_tpool_go i tp !! (i + j) = Excl <$> tp !! j).\n    { intros help. apply (help 0). }\n    revert j. induction tp as [|e tp IH]=> //= -[|j] i /=.\n    - by rewrite Nat.add_0_r lookup_insert.\n    - by rewrite -Nat.add_succ_comm lookup_insert_ne; last lia.\n  Qed.\n  Lemma tpool_lookup_Some tp j e : to_tpool tp !! j = Excl' e → tp !! j = Some e.\n  Proof. rewrite tpool_lookup fmap_Some. naive_solver. Qed.\n  Hint Resolve tpool_lookup_Some.\n\n  Lemma to_tpool_insert tp j e :\n    j < length tp →\n    to_tpool (<[j:=e]> tp) = <[j:=Excl e]> (to_tpool tp).\n  Proof.\n    intros. apply: map_eq=> i. destruct (decide (i = j)) as [->|].\n    - by rewrite tpool_lookup lookup_insert list_lookup_insert.\n    - rewrite tpool_lookup lookup_insert_ne // list_lookup_insert_ne //.\n      by rewrite tpool_lookup.\n  Qed.\n  Lemma to_tpool_insert' tp j e :\n    is_Some (to_tpool tp !! j) →\n    to_tpool (<[j:=e]> tp) = <[j:=Excl e]> (to_tpool tp).\n  Proof.\n    rewrite tpool_lookup fmap_is_Some lookup_lt_is_Some. apply to_tpool_insert.\n  Qed.\n\n  Lemma to_tpool_snoc tp e :\n    to_tpool (tp ++ [e]) = <[length tp:=Excl e]>(to_tpool tp).\n  Proof.\n    intros. apply: map_eq=> i.\n    destruct (lt_eq_lt_dec i (length tp)) as [[?| ->]|?].\n    - rewrite lookup_insert_ne; last lia. by rewrite !tpool_lookup lookup_app_l.\n    - by rewrite lookup_insert tpool_lookup lookup_app_r // Nat.sub_diag.\n    - rewrite lookup_insert_ne; last lia.\n      rewrite !tpool_lookup ?lookup_ge_None_2 ?app_length //=;\n         change (ofe_car (exprO F_mu_ref_conc_lang)) with expr; lia.\n  Qed.\n\n  Lemma tpool_singleton_included tp j e :\n    {[j := Excl e]} ≼ to_tpool tp → tp !! j = Some e.\n  Proof.\n    move=> /singleton_included [ex [/leibniz_equiv_iff]].\n    rewrite tpool_lookup fmap_Some=> [[e' [-> ->]] /Excl_included ?]. by f_equal.\n  Qed.\n  Lemma tpool_singleton_included' tp j e :\n    {[j := Excl e]} ≼ to_tpool tp → to_tpool tp !! j = Excl' e.\n  Proof. rewrite tpool_lookup. by move=> /tpool_singleton_included=> ->. Qed.\n\nEnd conversions.\n\nSection cfg.\n  Context `{heapIG Σ, cfgSG Σ}.\n  Implicit Types P Q : iProp Σ.\n  Implicit Types Φ : val → iProp Σ.\n  Implicit Types σ : state.\n  Implicit Types e : expr.\n  Implicit Types v : val.\n\n  Local Hint Resolve tpool_lookup.\n  Local Hint Resolve tpool_lookup_Some.\n  Local Hint Resolve to_tpool_insert.\n  Local Hint Resolve to_tpool_insert'.\n  Local Hint Resolve tpool_singleton_included.\n\n  Lemma step_insert K tp j e σ κ e' σ' efs :\n    tp !! j = Some (fill K e) → head_step e σ κ e' σ' efs →\n    erased_step (tp, σ) (<[j:=fill K e']> tp ++ efs, σ').\n  Proof.\n    intros. rewrite -(take_drop_middle tp j (fill K e)) //.\n    rewrite insert_app_r_alt take_length_le ?Nat.sub_diag /=;\n      eauto using lookup_lt_Some, Nat.lt_le_incl.\n    rewrite -(assoc_L (++)) /=. eexists.\n    eapply step_atomic; eauto. by apply: Ectx_step'.\n  Qed.\n\n  Lemma step_insert_no_fork K tp j e σ κ e' σ' :\n    tp !! j = Some (fill K e) → head_step e σ κ e' σ' [] →\n    erased_step (tp, σ) (<[j:=fill K e']> tp, σ').\n  Proof. rewrite -(right_id_L [] (++) (<[_:=_]>_)). by apply step_insert. Qed.\n\n  Lemma nsteps_inv_r {A} n (R : A → A → Prop) x y :\n    nsteps R (S n) x y → ∃ z, nsteps R n x z ∧ R z y.\n  Proof.\n    revert x y; induction n; intros x y.\n    - inversion 1; subst.\n      match goal with H : nsteps _ 0 _ _ |- _ => inversion H end; subst.\n      eexists; repeat econstructor; eauto.\n    - inversion 1; subst.\n      edestruct IHn as [z [? ?]]; eauto.\n      exists z; split; eauto using nsteps_l.\n  Qed.\n\n  Lemma step_pure' E ρ j K e e' (P : Prop) n :\n    P →\n    PureExec P n e e' →\n    nclose specN ⊆ E →\n    spec_ctx ρ ∗ j ⤇ fill K e ={E}=∗ j ⤇ fill K e'.\n  Proof.\n    iIntros (HP Hex ?) \"[#Hspec Hj]\". rewrite /spec_ctx /tpool_mapsto.\n    iInv specN as (tp σ) \">[Hown Hrtc]\" \"Hclose\".\n    iDestruct \"Hrtc\" as %Hrtc.\n    iDestruct (own_valid_2 with \"Hown Hj\")\n      as %[[Htpj%tpool_singleton_included' _]%prod_included ?]%auth_both_valid.\n    iMod (own_update_2 with \"Hown Hj\") as \"[Hown Hj]\".\n    { eapply auth_update, prod_local_update_1.\n      apply: singleton_local_update; first done.\n      by apply (exclusive_local_update (A := exclR (exprO _))\n                                       _ (Excl (fill K e'))). }\n    iFrame \"Hj\". iApply \"Hclose\". iNext. iExists (<[j:=fill K e']> tp), σ.\n    rewrite to_tpool_insert'; last eauto.\n    iFrame. iPureIntro.\n    apply rtc_nsteps in Hrtc; destruct Hrtc as [m Hrtc].\n    specialize (Hex HP). apply (nsteps_rtc (m + n)).\n    eapply nsteps_trans; eauto.\n    revert e e' Htpj Hex.\n    induction n => e e' Htpj Hex.\n    - inversion Hex; subst.\n      rewrite list_insert_id; eauto. econstructor.\n    - apply nsteps_inv_r in Hex.\n      destruct Hex as [z [Hex1 Hex2]].\n      specialize (IHn _ _ Htpj Hex1).\n      eapply nsteps_r; eauto.\n      replace (<[j:=fill K e']> tp) with\n          (<[j:=fill K e']> (<[j:=fill K z]> tp)); last first.\n      { clear. revert tp; induction j; intros tp.\n        - destruct tp; trivial.\n        - destruct tp; simpl; auto. by rewrite IHj. }\n      destruct Hex2 as [Hexs Hexd].\n      specialize (Hexs σ). destruct Hexs as [e'' [σ' [efs Hexs]]].\n      specialize (Hexd σ [] e'' σ' efs Hexs); destruct Hexd as [? [? [? ?]]];\n        subst.\n      inversion Hexs; simpl in *; subst.\n      rewrite -!fill_app.\n      eapply step_insert_no_fork; eauto.\n      { apply list_lookup_insert. apply lookup_lt_is_Some; eauto. }\n  Qed.\n\n\n  Lemma do_step_pure E ρ j K e e' `{!PureExec True 1 e e'}:\n    nclose specN ⊆ E →\n    spec_ctx ρ ∗ j ⤇ fill K e ={E}=∗ j ⤇ fill K e'.\n  Proof. by eapply step_pure'; last eauto. Qed.\n\n  Lemma step_alloc E ρ j K e v:\n    to_val e = Some v → nclose specN ⊆ E →\n    spec_ctx ρ ∗ j ⤇ fill K (Alloc e) ={E}=∗ ∃ l, j ⤇ fill K (Loc l) ∗ l ↦ₛ v.\n  Proof.\n    iIntros (??) \"[#Hinv Hj]\". rewrite /spec_ctx /tpool_mapsto.\n    iInv specN as (tp σ) \">[Hown %]\" \"Hclose\".\n    destruct (exist_fresh (dom (gset positive) σ)) as [l Hl%not_elem_of_dom].\n    iDestruct (own_valid_2 with \"Hown Hj\")\n      as %[[?%tpool_singleton_included' _]%prod_included ?]%auth_both_valid.\n    iMod (own_update_2 with \"Hown Hj\") as \"[Hown Hj]\".\n    { eapply auth_update, prod_local_update_1.\n      apply: singleton_local_update; first done.\n      by apply (exclusive_local_update (A := exclR (exprO _))\n                                    _ (Excl (fill K (Loc l)))). }\n    iMod (own_update with \"Hown\") as \"[Hown Hl]\".\n    { eapply auth_update_alloc, prod_local_update_2.\n      apply (alloc_singleton_local_update (A := (prodR _ (agreeR (valO _))))\n                                          _ l (1%Qp, to_agree v)); last done.\n      by apply lookup_to_gen_heap_None. }\n    iExists l. rewrite /heapS_mapsto. iFrame \"Hj Hl\". iApply \"Hclose\". iNext.\n    iExists (<[j:=fill K (Loc l)]> tp), (<[l:=v]>σ).\n    rewrite to_gen_heap_insert to_tpool_insert'; last eauto. iFrame. iPureIntro.\n    eapply rtc_r, step_insert_no_fork; eauto. econstructor; eauto.\n  Qed.\n\n  Lemma step_load E ρ j K l q v:\n    nclose specN ⊆ E →\n    spec_ctx ρ ∗ j ⤇ fill K (Load (Loc l)) ∗ l ↦ₛ{q} v\n    ={E}=∗ j ⤇ 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 (tp σ) \">[Hown %]\" \"Hclose\".\n    iDestruct (own_valid_2 with \"Hown Hj\")\n      as %[[?%tpool_singleton_included' _]%prod_included ?]%auth_both_valid.\n    iDestruct (own_valid_2 with \"Hown Hl\")\n      as %[[? ?%gen_heap_singleton_included]%prod_included ?]%auth_both_valid.\n    iMod (own_update_2 with \"Hown Hj\") as \"[Hown Hj]\".\n    { eapply auth_update, prod_local_update_1.\n      apply: singleton_local_update; first done.\n      by apply (exclusive_local_update (A := exclR (exprO _))\n                                    _ (Excl (fill K (of_val v)))). }\n    iFrame \"Hj Hl\". iApply \"Hclose\". iNext.\n    iExists (<[j:=fill K (of_val v)]> tp), σ.\n    rewrite to_tpool_insert'; last eauto. iFrame. iPureIntro.\n    eapply rtc_r, step_insert_no_fork; eauto. econstructor; eauto.\n  Qed.\n\n  Lemma step_store E ρ j K l v' e v:\n    to_val e = Some v → nclose specN ⊆ E →\n    spec_ctx ρ ∗ j ⤇ fill K (Store (Loc l) e) ∗ l ↦ₛ v'\n    ={E}=∗ j ⤇ fill K Unit ∗ l ↦ₛ v.\n  Proof.\n    iIntros (??) \"(#Hinv & Hj & Hl)\".\n    rewrite /spec_ctx /tpool_mapsto /heapS_mapsto.\n    iInv specN as (tp σ) \">[Hown %]\" \"Hclose\".\n    iDestruct (own_valid_2 with \"Hown Hj\")\n      as %[[?%tpool_singleton_included' _]%prod_included _]%auth_both_valid.\n    iDestruct (own_valid_2 with \"Hown Hl\")\n      as %[[_ Hl%gen_heap_singleton_included]%prod_included _]%auth_both_valid.\n    iMod (own_update_2 with \"Hown Hj\") as \"[Hown Hj]\".\n    { eapply auth_update, prod_local_update_1.\n      apply: singleton_local_update; first done.\n      by apply (exclusive_local_update (A := exclR (exprO _))\n                                       _ (Excl (fill K Unit))). }\n    iMod (own_update_2 with \"Hown Hl\") as \"[Hown Hl]\".\n    { eapply auth_update, prod_local_update_2.\n      apply: singleton_local_update.\n      { by rewrite /to_gen_heap lookup_fmap Hl. }\n        by apply (exclusive_local_update (A := prodR _ (agreeR (valO _)))\n                                    _ (1%Qp, to_agree v)). }\n    iFrame \"Hj Hl\". iApply \"Hclose\". iNext.\n    iExists (<[j:=fill K Unit]> tp), (<[l:=v]>σ).\n    rewrite to_gen_heap_insert to_tpool_insert'; last eauto. iFrame. iPureIntro.\n    eapply rtc_r, step_insert_no_fork; eauto. econstructor; eauto.\n  Qed.\n\n  Lemma step_cas_fail E ρ j K l q v' e1 v1 e2 v2:\n    to_val e1 = Some v1 → to_val e2 = Some v2 → nclose specN ⊆ E → v' ≠ v1 →\n    spec_ctx ρ ∗ j ⤇ fill K (CAS (Loc l) e1 e2) ∗ l ↦ₛ{q} v'\n    ={E}=∗ j ⤇ fill K (#♭ false) ∗ l ↦ₛ{q} v'.\n  Proof.\n    iIntros (????) \"(#Hinv & Hj & Hl)\".\n    rewrite /spec_ctx /tpool_mapsto /heapS_mapsto.\n    iInv specN as (tp σ) \">[Hown %]\" \"Hclose\".\n    iDestruct (own_valid_2 with \"Hown Hj\")\n      as %[[?%tpool_singleton_included' _]%prod_included ?]%auth_both_valid.\n    iDestruct (own_valid_2 with \"Hown Hl\")\n      as %[[_ ?%gen_heap_singleton_included]%prod_included _]%auth_both_valid.\n    iMod (own_update_2 with \"Hown Hj\") as \"[Hown Hj]\".\n    { eapply auth_update, prod_local_update_1.\n      apply: singleton_local_update; first done.\n      by apply (exclusive_local_update (A := exclR (exprO _))\n                                    _ (Excl (fill K (#♭ false)))). }\n    iFrame \"Hj Hl\". iApply \"Hclose\". iNext.\n    iExists (<[j:=fill K (#♭ false)]> tp), σ.\n    rewrite to_tpool_insert'; last eauto. iFrame. iPureIntro.\n    eapply rtc_r, step_insert_no_fork; eauto. econstructor; eauto.\n  Qed.\n\n  Lemma step_cas_suc E ρ j K l e1 v1 v1' e2 v2:\n    to_val e1 = Some v1 → to_val e2 = Some v2 → nclose specN ⊆ E → v1 = v1' →\n    spec_ctx ρ ∗ j ⤇ fill K (CAS (Loc l) e1 e2) ∗ l ↦ₛ v1'\n    ={E}=∗ j ⤇ fill K (#♭ true) ∗ l ↦ₛ v2.\n  Proof.\n    iIntros (????) \"(#Hinv & Hj & Hl)\"; subst.\n    rewrite /spec_ctx /tpool_mapsto /heapS_mapsto.\n    iInv specN as (tp σ) \">[Hown %]\" \"Hclose\".\n    iDestruct (own_valid_2 with \"Hown Hj\")\n      as %[[?%tpool_singleton_included' _]%prod_included _]%auth_both_valid.\n    iDestruct (own_valid_2 with \"Hown Hl\")\n      as %[[_ Hl%gen_heap_singleton_included]%prod_included _]%auth_both_valid.\n    iMod (own_update_2 with \"Hown Hj\") as \"[Hown Hj]\".\n    { eapply auth_update, prod_local_update_1.\n      apply: singleton_local_update; first done.\n      by apply (exclusive_local_update (A := exclR (exprO _))\n            _ (Excl (fill K (#♭ true)))). }\n    iMod (own_update_2 with \"Hown Hl\") as \"[Hown Hl]\".\n    { eapply auth_update, prod_local_update_2.\n      apply: singleton_local_update.\n      { by rewrite /to_gen_heap lookup_fmap Hl. }\n        by apply (exclusive_local_update (A := prodR _ (agreeR (valO _)))\n                                    _ (1%Qp, to_agree v2)). }\n    iFrame \"Hj Hl\". iApply \"Hclose\". iNext.\n    iExists (<[j:=fill K (#♭ true)]> tp), (<[l:=v2]>σ).\n    rewrite to_gen_heap_insert to_tpool_insert'; last eauto. iFrame. iPureIntro.\n    eapply rtc_r, step_insert_no_fork; eauto. econstructor; eauto.\n  Qed.\n\n  Lemma step_rec E ρ j K e1 e2 v :\n    to_val e2 = Some v → nclose specN ⊆ E →\n    spec_ctx ρ ∗ j ⤇ fill K (App (Rec e1) e2)\n    ={E}=∗ j ⤇ fill K (e1.[Rec e1,e2/]).\n  Proof. by intros ?; apply: do_step_pure. Qed.\n\n  Lemma step_lam E ρ j K e1 e2 v :\n    to_val e2 = Some v → nclose specN ⊆ E →\n    spec_ctx ρ ∗ j ⤇ fill K (App (Lam e1) e2)\n    ={E}=∗ j ⤇ fill K (e1.[e2/]).\n  Proof. by intros ?; apply: do_step_pure. Qed.\n\n  Lemma step_letin E ρ j K e1 e2 v :\n    to_val e1 = Some v → nclose specN ⊆ E →\n    spec_ctx ρ ∗ j ⤇ fill K (LetIn e1 e2)\n    ={E}=∗ j ⤇ fill K (e2.[e1/]).\n  Proof. by intros ?; apply: do_step_pure. Qed.\n\n  Lemma step_seq E ρ j K e1 e2 v :\n    to_val e1 = Some v → nclose specN ⊆ E →\n    spec_ctx ρ ∗ j ⤇ fill K (Seq e1 e2)\n    ={E}=∗ j ⤇ fill K e2.\n  Proof. by intros ?; apply: do_step_pure. Qed.\n\n  Lemma step_tlam E ρ j K e :\n    nclose specN ⊆ E →\n    spec_ctx ρ ∗ j ⤇ fill K (TApp (TLam e)) ={E}=∗ j ⤇ fill K e.\n  Proof. by intros ?; apply: do_step_pure. Qed.\n\n  Lemma step_Fold E ρ j K e v :\n    to_val e = Some v → nclose specN ⊆ E →\n    spec_ctx ρ ∗ j ⤇ fill K (Unfold (Fold e)) ={E}=∗ j ⤇ fill K e.\n  Proof. by intros ?; apply: do_step_pure. Qed.\n\n  Lemma step_fst E ρ j K e1 v1 e2 v2 :\n    to_val e1 = Some v1 → to_val e2 = Some v2 → nclose specN ⊆ E →\n    spec_ctx ρ ∗ j ⤇ fill K (Fst (Pair e1 e2)) ={E}=∗ j ⤇ fill K e1.\n  Proof. by intros; apply: do_step_pure. Qed.\n\n  Lemma step_snd E ρ j K e1 v1 e2 v2 :\n    to_val e1 = Some v1 → to_val e2 = Some v2 → nclose specN ⊆ E →\n    spec_ctx ρ ∗ j ⤇ fill K (Snd (Pair e1 e2)) ={E}=∗ j ⤇ fill K e2.\n  Proof. by intros; apply: do_step_pure. Qed.\n\n  Lemma step_case_inl E ρ j K e0 v0 e1 e2 :\n    to_val e0 = Some v0 → nclose specN ⊆ E →\n    spec_ctx ρ ∗ j ⤇ fill K (Case (InjL e0) e1 e2)\n      ={E}=∗ j ⤇ fill K (e1.[e0/]).\n  Proof. by intros; apply: do_step_pure. Qed.\n\n  Lemma step_case_inr E ρ j K e0 v0 e1 e2 :\n    to_val e0 = Some v0 → nclose specN ⊆ E →\n    spec_ctx ρ ∗ j ⤇ fill K (Case (InjR e0) e1 e2)\n      ={E}=∗ j ⤇ fill K (e2.[e0/]).\n  Proof. by intros; apply: do_step_pure. Qed.\n\n  Lemma step_if_false E ρ j K e1 e2 :\n    nclose specN ⊆ E →\n    spec_ctx ρ ∗ j ⤇ fill K (If (#♭ false) e1 e2) ={E}=∗ j ⤇ fill K e2.\n  Proof. by intros; apply: do_step_pure. Qed.\n\n  Lemma step_if_true E ρ j K e1 e2 :\n    nclose specN ⊆ E →\n    spec_ctx ρ ∗ j ⤇ fill K (If (#♭ true) e1 e2) ={E}=∗ j ⤇ fill K e1.\n  Proof. by intros; apply: do_step_pure. Qed.\n\n  Lemma step_nat_binop E ρ j K op a b :\n    nclose specN ⊆ E →\n    spec_ctx ρ ∗ j ⤇ fill K (BinOp op (#n a) (#n b))\n      ={E}=∗ j ⤇ fill K (of_val (binop_eval op a b)).\n  Proof. by intros; apply: do_step_pure. Qed.\n\n  Lemma step_fork E ρ j K e :\n    nclose specN ⊆ E →\n    spec_ctx ρ ∗ j ⤇ fill K (Fork e) ={E}=∗ ∃ j', j ⤇ fill K Unit ∗ j' ⤇ e.\n  Proof.\n    iIntros (?) \"[#Hspec Hj]\". rewrite /spec_ctx /tpool_mapsto.\n    iInv specN as (tp σ) \">[Hown %]\" \"Hclose\".\n    iDestruct (own_valid_2 with \"Hown Hj\")\n      as %[[?%tpool_singleton_included' _]%prod_included ?]%auth_both_valid.\n    assert (j < length tp) by eauto using lookup_lt_Some.\n    iMod (own_update_2 with \"Hown Hj\") as \"[Hown Hj]\".\n    { eapply auth_update, prod_local_update_1.\n      apply: singleton_local_update; first done.\n      by apply (exclusive_local_update (A := exclR (exprO _))\n                                    _ (Excl (fill K Unit))). }\n    iMod (own_update with \"Hown\") as \"[Hown Hfork]\".\n    { eapply auth_update_alloc, prod_local_update_1.\n      apply (alloc_singleton_local_update (A := exclR (exprO _))\n                                          _ (length tp) (Excl e)); last done.\n      rewrite lookup_insert_ne ?tpool_lookup; last lia.\n      by rewrite lookup_ge_None_2. }\n    iExists (length tp). iFrame \"Hj Hfork\". iApply \"Hclose\". iNext.\n    iExists (<[j:=fill K Unit]> tp ++ [e]), σ.\n    rewrite to_tpool_snoc insert_length to_tpool_insert //. iFrame. iPureIntro.\n    eapply rtc_r, step_insert; eauto. econstructor; eauto.\n  Qed.\nEnd cfg.\n", "meta": {"author": "amintimany", "repo": "F_mu_ref_conc_sub", "sha": "d5c154e11bc646c8e474e87b6a9959db93ec733e", "save_path": "github-repos/coq/amintimany-F_mu_ref_conc_sub", "path": "github-repos/coq/amintimany-F_mu_ref_conc_sub/F_mu_ref_conc_sub-d5c154e11bc646c8e474e87b6a9959db93ec733e/rules_binary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2793037405379424}}
{"text": "From CE Require Export Aux.\n\nImport ListNotations.\n\nImport Lia.\n\nDefinition set_second {A B C : Type} (p : A * B * C) (b : B) : A * B * C :=\nmatch p with\n| (a, b0, c) => (a, b, c)\nend.\n\n(* I can't import stdlib implementation somehow *)\nDefinition list_sum l := fold_right plus 0 l.\n\nFixpoint exp_size (e : Expression) : nat :=\nmatch e with\n | ELit l => 1\n | EVar v => 1\n | EFunId f => 1\n | EFun vl e => 1\n(*  | ECons hd tl => 1 + exp_size hd + exp_size tl *)\n(*  | ETuple l => 1 + list_sum (map exp_size l) *)\n | ECall f l => 1 + list_sum (map exp_size l)\n | EApp exp l => 1 + list_sum (map exp_size l) + exp_size exp\n(*  | ECase e l => 1 + exp_size e + fold_right (fun '(a, b, c) r => r + exp_size b + exp_size c) 0 l *)\n | ELet v e1 e2 => 1 + exp_size e1 + exp_size e2\n | ELetRec f l b e => 1 + exp_size e\n | ETry e1 v1 e2 vl2 e3 => 1 + exp_size e1 + exp_size e2 + exp_size e3\nend.\n\nFixpoint eval_list (f: Environment -> nat -> Expression -> SideEffectList -> nat -> option (nat * (Value + Exception) * SideEffectList)) (env : Environment) (id : nat) (exps : list Expression) (eff : SideEffectList) (clock : nat) : option (nat * ((list Value) + Exception) * SideEffectList) := \n match exps with\n | []    => Some (id, inl [], eff)\n | x::xs => match f env id x eff clock with\n            | Some (id', inl v , eff') => \n              let res := eval_list f env id' xs eff' clock in\n                match res with\n                | Some (id'', inl xs', eff'') => Some (id'', inl (v::xs'), eff'')\n                | r => r\n                end\n            | Some (id', inr ex, eff') => Some (id', inr ex, eff')\n            | None => None\n            end\n end\n .\n\nFixpoint list_eqb {A : Type} (eq : A -> A -> bool) (l1 l2 : list A) : bool :=\nmatch l1, l2 with\n| [], [] => true\n| x::xs, y::ys => eq x y && list_eqb eq xs ys\n| _, _ => false\nend.\n\nDefinition effect_id_eqb (id1 id2 : SideEffectId) : bool :=\nmatch id1, id2 with\n | Input, Input => true\n | Output, Output => true\n | _, _ => false\nend.\n\n\nDefinition effect_eqb (e1 e2 : SideEffectId * list Value) : bool :=\nmatch e1, e2 with\n| (id1, vals1), (id2, vals2) => effect_id_eqb id1 id2 && list_eqb Value_eqb vals1 vals2\nend.\n\nInductive ResultType : Type :=\n| Result (id : nat) (res : Value + Exception) (eff : SideEffectList)\n| Timeout\n| Failure.\n\nInductive ResultListType : Type :=\n| LResult (id : nat) (res : list Value + Exception) (eff : SideEffectList)\n| LTimeout\n| LFailure.\n\nRequire Import FunInd.\n\nFixpoint eval_elems (f : Environment -> nat -> Expression -> SideEffectList -> ResultType) env id exps eff : ResultListType := \nmatch exps with\n| []    => LResult id (inl []) eff\n| x::xs => \n  match f env id x eff with\n  | Result id' (inl v) eff' => \n    let res := eval_elems f env id' xs eff' in\n      match res with\n      | LResult id'' (inl xs') eff'' => LResult id'' (inl (v::xs')) eff''\n      | r => r\n      end\n  | Result id' (inr ex) eff' => LResult id' (inr ex) eff'\n  | Failure => LFailure\n  | Timeout => LTimeout\n  end\nend.\n\nFixpoint eval_fbos_expr (clock : nat) (env : Environment) (id : nat) (exp : Expression) (eff : SideEffectList) {struct clock} : \n  ResultType :=\nmatch clock with\n| 0 => Timeout\n| S clock' =>\n   match exp with\n   | ELit l => Result id (inl (VLit l)) eff\n   | EVar v => Result id (get_value env (inl v)) eff\n   | EFunId f => Result id (get_value env (inr f)) eff\n   | EFun vl e => Result (S id) (inl (VClos env [] id vl e)) eff\n   | ECall f l => let res := \n             eval_elems (eval_fbos_expr clock') env id l eff\n         in\n         match res with\n         | LResult id' (inl vl) eff' => Result id' (fst (eval f vl eff')) (snd (eval f vl eff'))\n         | LResult id' (inr ex) eff' => Result id' (inr ex) eff'\n         | LFailure => Failure\n         | LTimeout => Timeout\n         end\n   | EApp exp l =>\n      match eval_fbos_expr clock' env id exp eff with\n      | Result id' (inl v) eff' => let res :=\n        eval_elems (eval_fbos_expr clock') env id' l eff'\n         in\n         match res with\n         | LResult id'' (inl vl) eff'' =>\n           match v with\n           | VClos ref ext idcl varl body => if Nat.eqb (length varl) (length vl)\n                                             then\n                                               eval_fbos_expr clock' (append_vars_to_env varl vl (get_env ref ext)) id'' body eff''\n                                             else Result id'' (inr (badarity v)) eff''\n           | _                             => Result id'' (inr (badfun v)) eff''\n           end\n         | LResult id'' (inr ex) eff'' => Result id'' (inr ex) eff''\n         | LFailure => Failure\n         | LTimeout => Timeout\n         end\n       | r => r\n   end\n   | ELet var e1 e2 => \n      match eval_fbos_expr clock' env id e1 eff with\n      | Result id' (inl v) eff' => eval_fbos_expr clock' (insert_value env (inl var) v) id' e2 eff'\n      | r => r\n      end\n   | ELetRec f l b e => eval_fbos_expr clock' (append_funs_to_env [(f, (l, b))] env id) (S id) e eff\n   | ETry e1 v1 e2 vl2 e3 =>\n      match eval_fbos_expr clock' env id e1 eff with\n      | Result id' (inr ex) eff' => eval_fbos_expr clock' (append_try_vars_to_env vl2 [exclass_to_value (fst (fst ex)); snd (fst ex); snd ex] env) id' e3 eff'\n      | Result id' (inl v) eff' => eval_fbos_expr clock' (insert_value env (inl v1) v) id' e2 eff'\n      | r => r\n      end\n  end\nend\n.\n(*\nFunctional Scheme div2_ind := Induction for eval_fbos_expr Sort Set.\n TODO: report todo error here\n *)\n\nExample exp1 := ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) ( ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) ( ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) ( ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"Y\"%string (ELit (Integer 5)) (EVar \"Y\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ELet \"X\"%string (ELet \"X\"%string (ELit (Integer 5)) (EVar \"X\"%string)) (ECall \"+\"%string [EVar \"X\"%string; EVar \"X\"%string])))))))))))))))))))))))))))))))))))).\n\nCompute eval_fbos_expr 10000 [] 0 exp1 [].\n\nImport StringSyntax.\n\nLemma nil_length {A}: @length A [] = 0.\nProof. auto. Qed.\n", "meta": {"author": "harp-project", "repo": "Semantics-comparison", "sha": "e873d74bf0e2a366f71ca317a79f2cee192c9dc3", "save_path": "github-repos/coq/harp-project-Semantics-comparison", "path": "github-repos/coq/harp-project-Semantics-comparison/Semantics-comparison-e873d74bf0e2a366f71ca317a79f2cee192c9dc3/src/FBOS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030761371502, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2793037335675598}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrint seq.\nFrom CoqUtils Require Import word.\nFrom extructures Require Import fmap.\n\nRequire Import Coq.Strings.String.\nRequire Import Common.Either.\nRequire Import Intermediate.Machine.\n\nRequire Import MicroPolicies.Types.\nRequire Import MicroPolicies.Instance.\nRequire Import I2MP.Encode.\nRequire Import I2MP.Linearize.\n\nRequire Import Tests.RSC_DC_MD_Test.\nRequire Import Tests.IntermediateProgramGeneration.\n\nFrom QuickChick Require Import QuickChick.\nImport QcDefaultNotation. Import QcNotation. Open Scope qc_scope.\n\n(* TL Questions: *)\n(* Do I really need compiler errors? *)\n\n(* ASW: what about unrespected interfaces? *)\n\n(* I do need traces, right? *)\n(* YEP!! *)\n\n(* What about execution errors? What's the needed level of details? *)\n(* Doesn't NEED to be meaningful *)\n\n(* REMINDER: if a compiled program has +16384 instructions, the alloc syscall\n   won't work on the micro-policiy machine, due to address space layout and\n   imm word size. *)\n\nDefinition mp_program := { fmap mword mt -> matom }.\n\nDefinition ExecutionResult := unit.\nDefinition ExecutionError := unit.\n\nFixpoint mp_exec (s : state) (fuel : nat)\n  : (@Either ExecutionResult ExecutionError) * Log :=\n  let list_of_option {A : Type} (o : option A) : list A := match o with\n                         | None => nil\n                         | Some x => cons x nil\n                         end in\n  match fuel with\n  | O => (Common.Either.Right tt, nil)\n  | S n => match stepf s with\n           | Some (s', e) => let (r, l) := mp_exec s' n in\n                             (r, (list_of_option e ++ l))%list\n           | None => (Common.Either.Left \"The machine either halted or failed\" tt, nil)\n           end\n  end.\n\n\nDefinition mp_eval (p : mp_program) (fuel : nat)\n  : (@Either ExecutionResult ExecutionError) * Log := mp_exec (load p) fuel.\n\nDefinition compile_program\n           (ip : Intermediate.program)\n  : @Either mp_program False := Common.Either.Right (encode (linearize ip)).\n\nInstance show_false : Show False :=\n  {| show := (fun f => match (f: False) with end) |}.\n\nDefinition mp_rsc_correct (fuel : nat) :=\n  let max_components := 15%nat in\n  let min_components := 8%nat in\n  rsc_correct\n    empty_cag\n    empty_dag\n    min_components\n    max_components\n    compile_program\n    mp_eval\n    fuel.\n\nDefinition run_rsc_test :=\n  show (quickCheck (mp_rsc_correct 500%nat)).", "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/Tests/I2MP/MP_RSC_Test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2791957695792195}}
{"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.algebra.agree.\nRequire Import iris.proofmode.proofmode.\nRequire Import bedrock.lang.bi.spec.frac_splittable.\nRequire Import bedrock.lang.cpp.logic.\nRequire Import bedrock.lang.algebra.frac_auth.\nRequire Import bedrock.lang.cpp.logic.own_instances.\nRequire Import bedrock.lang.proofmode.own_obs.\n\nSet Printing Coercions.\n\n(**\nWell-typed ghost resources:\n\n- [afrac.auth (g : afrac.gname A) (q : Qp) (x : A) : mpred]\nrepresents fractional ownership of ghost cell [g] currently containing\nthe authoritative state [x]\n\n- [afrac.frag (g : afrac.gname A) (q : Qp) (x : A) : mpred]\nrepresents fractional ownership of ghost cell [g] currently containing\nthe fragmentative state [x]\n*)\nModule Type AUTH_FRAC.\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 (AUTH_FRAC.Σ 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 auth : ∀ {A} `{Σ : cpp_logic, !AUTH_FRAC.G A Σ}\n    (g : gname A) (q : Qp) (x : A), mpred.\n  Parameter frag : ∀ {A} `{Σ : cpp_logic, !AUTH_FRAC.G A Σ}\n    (g : gname A) (q : Qp) (x : A), mpred.\n\n  Section properties.\n    Context {A} `{Σ : cpp_logic, !AUTH_FRAC.G A Σ}.\n\n    (** Structure *)\n\n    #[global] Declare Instance auth_objective : Objective3 auth.\n    #[global] Declare Instance auth_frac g : FracSplittable_1 (auth g).\n    #[global] Declare Instance auth_agree g : AgreeF1 (auth g).\n\n    #[global] Declare Instance frag_objective : Objective3 frag.\n    #[global] Declare Instance frag_frac g : FracSplittable_1 (frag g).\n    #[global] Declare Instance frag_agree g : AgreeF1 (frag g).\n\n    #[global] Declare Instance auth_frag_agree g q1 q2 x1 x2 :\n      Observe2 [| x1 = x2 |] (auth g q1 x1) (frag g q2 x2).\n\n    (** Allocation *)\n\n    #[local] Notation OWN g x := (auth g 1 x ** frag g 1 x) (only parsing).\n\n(*  (* Stronger allocation rules may not be needed for now. *)\n    Axiom alloc_strong_dep : ∀ (f : gname A -> A) (P : gname A -> Prop),\n      pred_infinite P ->\n      |-- |==> Exists g, [| P g |] ** OWN g (f g).\n\n    Axiom alloc_cofinite_dep : ∀ (f : gname A -> A) (G : gset (gname A)),\n      |-- |==> Exists g, [| g ∉ G |] ** OWN g (f g).\n\n    Axiom alloc_dep : ∀ (f : gname A -> A),\n      |-- |==> Exists g, OWN g (f g).\n\n    Axiom alloc_strong : ∀ (P : gname A -> Prop) x,\n      pred_infinite P ->\n      |-- |==> Exists g, [| P g |] ** OWN g x.\n\n    Axiom alloc_cofinite : ∀ (G : gset (gname A)) x,\n      |-- |==> Exists g, [| g ∉ G |] ** OWN g x.\n*)\n\n    Axiom alloc : ∀ x, |-- |==> Exists g, OWN g x.\n\n    (** Updates *)\n\n    Axiom update : ∀ g x y, |-- auth g 1 x -* frag g 1 x -* |==> OWN g y.\n\n    (** TODO: Automation (generically derivable) *)\n\n  End properties.\n\nEnd AUTH_FRAC.\n\n(**\nTODO: unify with [bedrock.algebra.frac_auth_agree].\n*)\nModule afrac : AUTH_FRAC.\n\n  (** CMRA *)\n\n  #[local] Notation RA A := (frac_authR (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 (afrac.Σ A) Σ -> G A Σ.\n  Proof. solve_inG. Qed.\n\n  (** Ghosts *)\n\n  Definition gname (A : Type) : Set := iprop.gname.\n  #[local] Instance  gname_inhabited A : Inhabited (gname A) := _.\n  #[local] Instance  gname_eq_dec A : EqDecision (gname A) := _.\n  #[local] Instance  gname_countable A : Countable (gname A) := _.\n\n  (** Predicates *)\n\n  Section defs.\n    Context {A} `{Σ : cpp_logic, !afrac.G A Σ}.\n\n    #[local] Notation to_agree := (to_agree (A:=leibnizO A)).\n\n    Definition auth (g : gname A) (q : Qp) (x : A) : mpred :=\n      own g (●F{q} (to_agree x)).\n\n    Definition frag (g : gname A) (q : Qp) (x : A) : mpred :=\n      own g (◯F{q} (to_agree x)).\n\n    #[local] Instance auth_objective : Objective3 auth := _.\n    #[local] Instance auth_frac g : FracSplittable_1 (auth g).\n    Proof. solve_frac. Qed.\n    #[local] Instance auth_agree g : AgreeF1 (auth g).\n    Proof.\n      (**\n      TODO (PDS): Shouldn't need to expose [to_agree].\n      *)\n      intros. rewrite -(inj_iff to_agree). apply _.\n    Qed.\n\n    #[local] Instance frag_objective : Objective3 frag := _.\n    #[local] Instance frag_frac g : FracSplittable_1 (frag g).\n    Proof. solve_frac. Qed.\n    #[local] Instance frag_agree g : AgreeF1 (frag g).\n    Proof.\n      (**\n      TODO (PDS): own_frac_auth_frag_frac_agree_L missing in\n      bedrock.lang.proofmode.own_obs\n      *)\n      intros. iIntros \"F1 F2\".\n      iDestruct (own_valid_2 with \"F1 F2\") as %Hv. iModIntro. iPureIntro.\n      move: Hv. rewrite -frac_auth_frag_op frac_auth_frag_valid=>-[] _.\n      by rewrite to_agree_op_valid_L.\n    Qed.\n\n    #[local] Instance auth_frag_agree g q1 q2 x1 x2 :\n      Observe2 [| x1 = x2 |] (auth g q1 x1) (frag g q2 x2).\n    Proof.\n      (**\n      TODO (PDS): Problem with [own_frac_auth_agree_L]\n      *)\n      intros. iIntros \"A F\".\n      iDestruct (observe_2 [| _ ≼ _ |] with \"A F\") as %Hinc.\n      iModIntro. iPureIntro. move: Hinc.\n      move/to_agree_included. by fold_leibniz.\n    Qed.\n\n    #[local] Notation OWN g x := (auth g 1 x ** frag g 1 x) (only parsing).\n\n    Lemma alloc x : |-- |==> Exists g, OWN g x.\n    Proof.\n      iMod (own_alloc (●F{1} (to_agree x) ⋅ ◯F{1} (to_agree x))) as (g) \"[A F]\".\n      { by apply frac_auth_valid. }\n      iExists g. by iFrame \"A F\".\n    Qed.\n\n    Lemma update g x y :\n      |-- auth g 1 x -* frag g 1 x -* |==> OWN g y.\n    Proof.\n      iIntros \"A F\". iMod (own_update_2 with \"A F\") as \"[$$]\"; last done.\n      by apply frac_auth_update_1.\n    Qed.\n  End defs.\n\nEnd afrac.\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/auth_frac.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.279195763836197}}
{"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_Ф_updateRound2 (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.\nOpaque DePoolContract_Ф_startRoundCompleting ProxyBase_Ф__recoverStake.\n\nLemma DePoolContract_Ф_updateRound2_exec : forall ( Л_round2 : RoundsBase_ι_Round ) \n                                                  ( Л_prevValidatorHash : XInteger256 ) \n                                                  ( Л_curValidatorHash : XInteger256 ) \n                                                  ( Л_validationStart : XInteger32 )                                                  \n                                                  (l: Ledger) ,                                                    \nlet round2 := Л_round2 in\nlet if1 : bool  :=  eqb ( round2 ->> RoundsBase_ι_Round_ι_step )  RoundsBase_ι_RoundStepP_ι_WaitingValidatorRequest in\nlet if2 : bool  :=  eqb ( round2 ->> RoundsBase_ι_Round_ι_completionReason )  RoundsBase_ι_CompletionReasonP_ι_Undefined in\nlet if3 : bool  :=  eqb (round2 ->> RoundsBase_ι_Round_ι_step )  RoundsBase_ι_RoundStepP_ι_Completing in \nlet round2 := if if1 then \n                      if if2 then {$ round2 with (RoundsBase_ι_Round_ι_step, RoundsBase_ι_RoundStepP_ι_WaitingUnfreeze);\n                                                 (RoundsBase_ι_Round_ι_completionReason, RoundsBase_ι_CompletionReasonP_ι_NoValidatorRequest);\n                                                 (RoundsBase_ι_Round_ι_unfreeze, 0) $}\n                             else {$ round2 with (RoundsBase_ι_Round_ι_step, RoundsBase_ι_RoundStepP_ι_WaitingUnfreeze);\n                                                 (RoundsBase_ι_Round_ι_unfreeze, 0) $} \n                      else round2 in                     \nlet oldMessages := VMState_ι_messages ( Ledger_ι_VMState l ) in\nlet oldEvents := VMState_ι_events ( Ledger_ι_VMState l ) in\nlet newMessage  := {|  contractAddress :=  0 ;\n                        contractFunction := DePoolContract_Ф_completeRoundWithChunkF round2->>RoundsBase_ι_Round_ι_id 1 ;\n                        contractMessage := {| messageValue := 0 ;\n                                              messageFlag  := 0 ; \n                                              messageBounce := false\n                                                  |} |} in                      \nlet l' :=   if if1 then l\n                   else if if3 then {$ l With (VMState_ι_messages, newMessage :: oldMessages ) $}\n                               else l   \n                      in                                             \nlet if4 : bool :=  ( ( negb ( eqb ( round2 ->> RoundsBase_ι_Round_ι_vsetHashInElectionPhase ) Л_curValidatorHash ) )  && \n                     ( negb ( eqb ( round2 ->> RoundsBase_ι_Round_ι_vsetHashInElectionPhase ) Л_prevValidatorHash ) )  && \n                     (  eqb (round2 ->> RoundsBase_ι_Round_ι_unfreeze) DePoolLib_ι_MAX_TIME ) )%bool   in\nlet round2 := if if4 then {$ round2 with (RoundsBase_ι_Round_ι_unfreeze, Л_validationStart + round2->>RoundsBase_ι_Round_ι_stakeHeldFor) $} \n                       else round2 in \nlet if5 : bool  := ( eval_state tvm_now  l ) >=? ( (round2 ->> RoundsBase_ι_Round_ι_unfreeze) + \n                                                   DePoolLib_ι_ELECTOR_UNFREEZE_LAG ) in \nlet if6 : bool := (( eqb (round2 ->> RoundsBase_ι_Round_ι_step) RoundsBase_ι_RoundStepP_ι_WaitingUnfreeze ) &&\n                     negb ( eqb (round2 ->> RoundsBase_ι_Round_ι_completionReason) RoundsBase_ι_CompletionReasonP_ι_Undefined ))%bool in\n(* let if7 : bool := ( round2 ->> RoundsBase_ι_Round_ι_participantQty ) =? 0  in *)\nlet if8 : bool :=  ( ( eqb (round2 ->> RoundsBase_ι_Round_ι_step) RoundsBase_ι_RoundStepP_ι_WaitingValidationStart ) ||\n                     ( eqb (round2 ->> RoundsBase_ι_Round_ι_step) RoundsBase_ι_RoundStepP_ι_WaitingUnfreeze ))%bool in  \n(* let round2' := if if5 then \n                            if if6 then \n                                   eval_state ( ↓ DePoolContract_Ф_startRoundCompleting round2 round2 ->> RoundsBase_ι_Round_ι_completionReason) l'\n                                    else if if8 then {$ round2 with (RoundsBase_ι_Round_ι_step, RoundsBase_ι_RoundStepP_ι_WaitingReward) $} \n                                                else round2    \n                     else round2 in    *)                   \nlet l'' := if if5 then if if6 then exec_state ( ↓ DePoolContract_Ф_startRoundCompleting round2 round2 ->> RoundsBase_ι_Round_ι_completionReason) l'\n                              else if if8 then  exec_state ( ↓ ProxyBase_Ф__recoverStake round2 ->> RoundsBase_ι_Round_ι_proxy \n                                                                                         round2 ->> RoundsBase_ι_Round_ι_id \n                                                                                         round2 ->> RoundsBase_ι_Round_ι_elector ) l' \n                                          else l'     \n                     else l' in \n\nexec_state ( ↓ DePoolContract_Ф_updateRound2 Л_round2 Л_prevValidatorHash Л_curValidatorHash Л_validationStart ) l = l''.\n\n Proof. \n\n  intros.\n\n  destructLedger l. \n  destruct Л_round2.\n  compute. idtac.\n\n  Time do 3 destructIf_solve. idtac.\n\n  -\n\n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_curValidatorHash); \n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_prevValidatorHash); \n  destruct (0 =? DePoolLib_ι_MAX_TIME); \n  try discriminate. idtac.\n\n  time repeat destructIf_solve. idtac.\n  destructFunction2 DePoolContract_Ф_startRoundCompleting; auto. \n\n  - idtac.\n\n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_curValidatorHash); \n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_prevValidatorHash); \n  destruct (0 =? DePoolLib_ι_MAX_TIME); \n  try discriminate. idtac.\n\n  all: time repeat destructIf_solve. idtac.\n  all: destructFunction2 DePoolContract_Ф_startRoundCompleting; auto. \n\n  - idtac.  \n\n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_curValidatorHash); \n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_prevValidatorHash); \n  destruct (0 =? DePoolLib_ι_MAX_TIME); \n  try discriminate. idtac.\n\n  all: time repeat destructIf_solve. idtac.\n  all: destructFunction2 DePoolContract_Ф_startRoundCompleting; auto. \n\n  - idtac.  \n\n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_curValidatorHash); \n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_prevValidatorHash); \n  destruct (0 =? DePoolLib_ι_MAX_TIME); \n  try discriminate. idtac.\n\n  all: time repeat destructIf_solve. idtac.\n  all: destructFunction2 DePoolContract_Ф_startRoundCompleting; auto.   \n\n  - idtac.  \n\n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_curValidatorHash); \n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_prevValidatorHash); \n  destruct (RoundsBase_ι_Round_ι_unfreeze =? DePoolLib_ι_MAX_TIME); \n  try discriminate. idtac.\n\n  all: time repeat destructIf_solve. idtac.\n  all: destructFunction2 DePoolContract_Ф_startRoundCompleting; auto.  \n\n  - idtac.  \n\n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_curValidatorHash); \n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_prevValidatorHash); \n  destruct (RoundsBase_ι_Round_ι_unfreeze =? DePoolLib_ι_MAX_TIME); \n  try discriminate. idtac.\n\n  all: time repeat destructIf_solve. idtac.\n  all: destructFunction2 DePoolContract_Ф_startRoundCompleting; auto.    \n\n  - idtac.  \n\n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_curValidatorHash); \n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_prevValidatorHash); \n  destruct (RoundsBase_ι_Round_ι_unfreeze =? DePoolLib_ι_MAX_TIME); \n  try discriminate. idtac.\n\n  all: time repeat destructIf_solve. idtac.\n  all: destructFunction2 DePoolContract_Ф_startRoundCompleting; auto.  \n\n  - idtac.  \n\n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_curValidatorHash); \n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_prevValidatorHash); \n  destruct (RoundsBase_ι_Round_ι_unfreeze =? DePoolLib_ι_MAX_TIME); \n  try discriminate. idtac.\n\n  all: time repeat destructIf_solve. idtac.\n  all: destructFunction2 DePoolContract_Ф_startRoundCompleting; auto.  \n\nQed. \n\n\n  \n\nLemma DePoolContract_Ф_updateRound2_eval : forall ( Л_round2 : RoundsBase_ι_Round ) \n                                                   ( Л_prevValidatorHash : XInteger256 ) \n                                                   ( Л_curValidatorHash : XInteger256 ) \n                                                   ( Л_validationStart : XInteger32 )                                                  \n                                                   (l: Ledger) ,                                                    \nlet round2 := Л_round2 in\nlet if1 : bool  :=  eqb ( round2 ->> RoundsBase_ι_Round_ι_step )  RoundsBase_ι_RoundStepP_ι_WaitingValidatorRequest in\nlet if2 : bool  :=  eqb ( round2 ->> RoundsBase_ι_Round_ι_completionReason )  RoundsBase_ι_CompletionReasonP_ι_Undefined in\nlet if3 : bool  :=  eqb (round2 ->> RoundsBase_ι_Round_ι_step )  RoundsBase_ι_RoundStepP_ι_Completing in \nlet round2 := if if1 then \n                      if if2 then {$ round2 with (RoundsBase_ι_Round_ι_step, RoundsBase_ι_RoundStepP_ι_WaitingUnfreeze);\n                                                 (RoundsBase_ι_Round_ι_completionReason, RoundsBase_ι_CompletionReasonP_ι_NoValidatorRequest);\n                                                 (RoundsBase_ι_Round_ι_unfreeze, 0) $}\n                             else {$ round2 with (RoundsBase_ι_Round_ι_step, RoundsBase_ι_RoundStepP_ι_WaitingUnfreeze);\n                                                 (RoundsBase_ι_Round_ι_unfreeze, 0) $} \n                      else round2 in                     \nlet oldMessages := VMState_ι_messages ( Ledger_ι_VMState l ) in\nlet newMessage  := {|  contractAddress :=  0 ;\n                        contractFunction := DePoolContract_Ф_completeRoundWithChunkF round2->>RoundsBase_ι_Round_ι_id 1 ;\n                        contractMessage := {| messageValue := 0 ;\n                                              messageFlag  := 0 ; \n                                              messageBounce := false\n                                                  |} |} in                      \nlet l' :=   if if1 then l\n                   else if if3 then {$ l With (VMState_ι_messages, newMessage :: oldMessages ) $}\n                               else l   \n                      in                                             \n\nlet if4 : bool :=  (( negb ( eqb ( round2 ->> RoundsBase_ι_Round_ι_vsetHashInElectionPhase ) Л_curValidatorHash ) )  && \n                    ( negb ( eqb ( round2 ->> RoundsBase_ι_Round_ι_vsetHashInElectionPhase ) Л_prevValidatorHash ) )  && \n                    ( eqb (round2 ->> RoundsBase_ι_Round_ι_unfreeze) DePoolLib_ι_MAX_TIME  ) )%bool   in\nlet round2 := if if4 then {$ round2 with (RoundsBase_ι_Round_ι_unfreeze, Л_validationStart + round2->>RoundsBase_ι_Round_ι_stakeHeldFor) $} \n                       else round2 in \nlet if5 : bool  := ( eval_state tvm_now  l ) >=? ( (round2 ->> RoundsBase_ι_Round_ι_unfreeze) + \n                                                   DePoolLib_ι_ELECTOR_UNFREEZE_LAG ) in \nlet if6 : bool := (( eqb (round2 ->> RoundsBase_ι_Round_ι_step) RoundsBase_ι_RoundStepP_ι_WaitingUnfreeze ) &&\n                     negb ( eqb (round2 ->> RoundsBase_ι_Round_ι_completionReason) RoundsBase_ι_CompletionReasonP_ι_Undefined ))%bool in\nlet if8 : bool :=  ( ( eqb (round2 ->> RoundsBase_ι_Round_ι_step) RoundsBase_ι_RoundStepP_ι_WaitingValidationStart ) ||\n                     ( eqb (round2 ->> RoundsBase_ι_Round_ι_step) RoundsBase_ι_RoundStepP_ι_WaitingUnfreeze ))%bool in  \nlet round2 := if if5 then \n                            if if6 then \n                                   eval_state ( ↓ DePoolContract_Ф_startRoundCompleting round2 round2 ->> RoundsBase_ι_Round_ι_completionReason) l'\n                                    else if if8 then {$ round2 with (RoundsBase_ι_Round_ι_step, RoundsBase_ι_RoundStepP_ι_WaitingReward) $} \n                                                else round2\n                     else round2 in \n\neval_state ( ↓ DePoolContract_Ф_updateRound2 Л_round2 Л_prevValidatorHash Л_curValidatorHash Л_validationStart ) l = round2.\n\nProof. \n\n  intros.\n\n  destructLedger l. \n  destruct Л_round2.\n  compute. idtac.\n\n  Time do 3 destructIf_solve. idtac.\n\n  - idtac.\n\n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_curValidatorHash); \n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_prevValidatorHash); \n  destruct (0 =? DePoolLib_ι_MAX_TIME); \n  try discriminate. idtac.\n\n  time repeat destructIf_solve. idtac.\n  destructFunction2 DePoolContract_Ф_startRoundCompleting; auto. \n\n  - idtac.\n\n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_curValidatorHash); \n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_prevValidatorHash); \n  destruct (0 =? DePoolLib_ι_MAX_TIME); \n  try discriminate. idtac.\n\n  all: time repeat destructIf_solve. idtac.\n  all: destructFunction2 DePoolContract_Ф_startRoundCompleting; auto. \n\n  - idtac.  \n\n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_curValidatorHash); \n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_prevValidatorHash); \n  destruct (0 =? DePoolLib_ι_MAX_TIME); \n  try discriminate. idtac.\n\n  all: time repeat destructIf_solve. idtac.\n  all: destructFunction2 DePoolContract_Ф_startRoundCompleting; auto. \n\n  - idtac.  \n\n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_curValidatorHash); \n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_prevValidatorHash); \n  destruct (0 =? DePoolLib_ι_MAX_TIME); \n  try discriminate. idtac.\n\n  all: time repeat destructIf_solve. idtac.\n  all: destructFunction2 DePoolContract_Ф_startRoundCompleting; auto.   \n\n  - idtac.  \n\n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_curValidatorHash); \n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_prevValidatorHash); \n  destruct (RoundsBase_ι_Round_ι_unfreeze =? DePoolLib_ι_MAX_TIME); \n  try discriminate. idtac.\n\n  all: time repeat destructIf_solve. idtac.\n  all: destructFunction2 DePoolContract_Ф_startRoundCompleting; auto.  \n\n  - idtac.  \n\n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_curValidatorHash); \n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_prevValidatorHash); \n  destruct (RoundsBase_ι_Round_ι_unfreeze =? DePoolLib_ι_MAX_TIME); \n  try discriminate. idtac.\n\n  all: time repeat destructIf_solve. idtac.\n  all: destructFunction2 DePoolContract_Ф_startRoundCompleting; auto.    \n\n  - idtac.  \n\n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_curValidatorHash); \n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_prevValidatorHash); \n  destruct (RoundsBase_ι_Round_ι_unfreeze =? DePoolLib_ι_MAX_TIME); \n  try discriminate. idtac.\n\n  all: time repeat destructIf_solve. idtac.\n  all: destructFunction2 DePoolContract_Ф_startRoundCompleting; auto.  \n\n  - idtac.  \n\n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_curValidatorHash); \n  destruct (RoundsBase_ι_Round_ι_vsetHashInElectionPhase =? Л_prevValidatorHash); \n  destruct (RoundsBase_ι_Round_ι_unfreeze =? DePoolLib_ι_MAX_TIME); \n  try discriminate. idtac.\n\n  all: time repeat destructIf_solve. idtac.\n  all: destructFunction2 DePoolContract_Ф_startRoundCompleting; auto.  \n\n\n Qed.\n\n\nEnd DePoolContract_Ф_updateRound2.", "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_updateRound2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.27919576383619693}}
{"text": "Set Primitive Projections.\nSet Implicit Arguments.\n\nRecord prod {A} {B}:= pair { fst : A ; snd : B }.\nNotation \" A * B \" := (@prod A B) : type_scope.\nRecord sigT {A} (P : A -> Type) := existT { projT1 : A ; projT2 : P projT1 }.\nNotation pr1 := (@projT1 _ _).\nArguments prod : clear implicits.\n\nCheck (@projT1 _ (fun x : nat => x = x)).\nCheck (fun s : @sigT nat (fun x : nat => x = x) => s.(projT1)).\n\nRecord rimpl {b : bool} {n : nat} := { foo : forall {x : nat}, x = n }. \n\nCheck (fun r : @rimpl true 0 => r.(foo) (x:=0)).\nCheck (fun r : @rimpl true 0 => @foo true 0 r 0).\nCheck (fun r : @rimpl true 0 => foo r (x:=0)).\nCheck (fun r : @rimpl true 0 => @foo _ _ r 0).\nCheck (fun r : @rimpl true 0 => r.(@foo _ _)).\nCheck (fun r : @rimpl true 0 => r.(foo)).\n\nNotation \"{ x : T  & P }\" := (@sigT T P).\nNotation \"{ x : A  & P }\" := (sigT (A:=A) (fun x => P)) : type_scope.\n(* Notation \"{ x : T * U  & P }\" := (@sigT (T * U) P). *)\n\nDefinition compose {A B C : Type} (g : B -> C) (f : A -> B) := fun x => g (f x).\nInductive paths {A : Type} (a : A) : A -> Type := idpath : paths a a where \"x = y\" := (@paths _ x y) : type_scope.\nArguments idpath {A a} , [A] a.\nClass IsEquiv {A B : Type} (f : A -> B) := {}.\n\nLocal Instance isequiv_tgt_compose A B\n: @IsEquiv (A -> {xy : B * B & fst xy = snd xy})\n           (A -> B)\n           (@compose A {xy : B * B & fst xy = snd xy} B\n                     (@compose {xy : B * B & fst xy = snd xy} _ B (@snd B B) pr1)).\n(* Toplevel input, characters 220-223: *)\n(* Error: Cannot infer this placeholder. *)\n\nLocal Instance isequiv_tgt_compose' A B\n: @IsEquiv (A -> {xy : B * B & fst xy = snd xy})\n           (A -> B)\n           (@compose A {xy : B * B & fst xy = snd xy} B (@compose {xy : B * B & fst xy = snd xy} _ B (@snd _ _) pr1)).\n(* Toplevel input, characters 221-232: *)\n(* Error: *)\n(* In environment *)\n(* A : Type *)\n(* B : Type *)\n(* The term \"pr1\" has type \"sigT ?30 -> ?29\" while it is expected to have type *)\n(*  \"{xy : B * B & fst xy = snd xy} -> ?27 * B\". *)\n\nLocal Instance isequiv_tgt_compose'' A B\n: @IsEquiv (A -> {xy : B * B & fst xy = snd xy})\n           (A -> B)\n           (@compose A {xy : B * B & fst xy = snd xy} B (@compose {xy : B * B & fst xy = snd xy} _ B (@snd _ _) \n                                                                  (fun s => s.(projT1)))).\n(* Toplevel input, characters 15-241:\nError:\nCannot infer an internal placeholder of type \"Type\" in environment:\n\nA : Type\nB : Type\nx : ?32\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/3454.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947155710234, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2791957580931744}}
{"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 cvterm.\nRequire Export alphaeq.\nRequire Export list.  (* WTF!!! *)\n\n\nLemma wf_less_than {o} :\n  forall (a b : @NTerm o),\n    wf_term (mk_less_than a b) <=> (wf_term a # wf_term b).\nProof.\n  introv.\n  unfold mk_less_than.\n  rw <- @wf_less_iff; split; intro k; repnd; dands; eauto 3 with slow.\nQed.\n\nLemma wf_le {o} :\n  forall (a b : @NTerm o),\n    wf_term (mk_le a b) <=> (wf_term a # wf_term b).\nProof.\n  introv.\n  unfold mk_le.\n  rw @wf_not.\n  rw @wf_less_than; dands; split; sp.\nQed.\n\nLemma wf_term_mk_natk {o} :\n  forall (t : @NTerm o), wf_term (mk_natk t) <=> wf_term t.\nProof.\n  introv.\n  unfold mk_natk, mk_natk_aux.\n  rw <- @wf_set_iff.\n  rw @wf_prod.\n  rw @wf_le.\n  rw @wf_less_than.\n  split; introv k; repnd; dands; eauto 3 with slow.\nQed.\n\nLemma cover_vars_upto_product {o} :\n  forall vs (a : @NTerm o) v b sub,\n    cover_vars_upto (mk_product a v b) sub vs\n    <=> cover_vars_upto a sub vs\n        # cover_vars_upto b (csub_filter sub [v]) (v :: vs).\nProof.\n  sp; repeat (rw cover_vars_eq); unfold cover_vars_upto; simpl.\n  allrw remove_nvars_nil_l; allrw app_nil_r.\n  allrw subvars_app_l.\n  allrw subvars_remove_nvars; simpl.\n  allrw @dom_csub_csub_filter.\n  allrw subvars_prop; simpl; split; sp; apply_in_hyp pp;\n  allrw in_app_iff; allrw in_remove_nvars; allrw in_single_iff; sp.\n  generalize (deq_nvar v x); intro q; sp.\n  right; right; sp.\nQed.\n\nLemma cover_vars_upto_prod {o} :\n  forall vs (a b : @NTerm o) sub,\n    cover_vars_upto (mk_prod a b) sub vs\n    <=> cover_vars_upto a sub vs\n        # cover_vars_upto b sub vs.\nProof.\n  introv.\n  rw @cover_vars_upto_product.\n  split; intro k; repnd; dands; auto.\n  - allunfold @cover_vars_upto.\n    allrw subvars_prop; introv i.\n    applydup k in i; allsimpl; allrw in_app_iff; repndors; subst; tcsp.\n    + pose proof (newvar_prop b); sp.\n    + rw @dom_csub_csub_filter in i0.\n      rw in_remove_nvars in i0; sp.\n  - allunfold @cover_vars_upto.\n    allrw subvars_prop; introv i.\n    applydup k in i; allsimpl; allrw in_app_iff; repndors; tcsp.\n    rw @dom_csub_csub_filter.\n    rw in_remove_nvars; simpl.\n    destruct (deq_nvar (newvar b) x) as [j|j]; subst; tcsp.\n    right; right; sp.\nQed.\n\nLemma cover_vars_upto_less {o} :\n  forall vs (a b c d : @NTerm o) sub,\n    cover_vars_upto (mk_less a b c d) sub vs\n    <=> cover_vars_upto a sub vs\n        # cover_vars_upto b sub vs\n        # cover_vars_upto c sub vs\n        # cover_vars_upto d sub vs.\nProof.\n  introv.\n  unfold cover_vars_upto; simpl.\n  allrw remove_nvars_nil_l.\n  allrw app_nil_r.\n  allrw subvars_app_l.\n  sp.\nQed.\n\nLemma cover_vars_upto_mk_true {o} :\n  forall (sub : @CSub o) vs, cover_vars_upto mk_true sub vs.\nProof.\n  introv; unfold cover_vars_upto; simpl; auto.\nQed.\nHint Resolve cover_vars_upto_mk_true : slow.\n\nLemma cover_vars_upto_less_than {o} :\n  forall vs (a b : @NTerm o) sub,\n    cover_vars_upto (mk_less_than a b) sub vs\n    <=> cover_vars_upto a sub vs\n        # cover_vars_upto b sub vs.\nProof.\n  introv.\n  rw @cover_vars_upto_less.\n  split; introv k; repnd; dands; eauto 3 with slow; tcsp.\nQed.\n\nLemma cover_vars_upto_not {o} :\n  forall vs (a : @NTerm o) sub,\n    cover_vars_upto (mk_not a) sub vs\n    <=> cover_vars_upto a sub vs.\nProof.\n  introv.\n  unfold mk_not.\n  rw @cover_vars_upto_fun; split; introv k; repnd; dands; eauto 3 with slow.\nQed.\n\nLemma cover_vars_upto_le {o} :\n  forall vs (a b : @NTerm o) sub,\n    cover_vars_upto (mk_le a b) sub vs\n    <=> cover_vars_upto a sub vs\n        # cover_vars_upto b sub vs.\nProof.\n  introv.\n  unfold mk_le.\n  rw @cover_vars_upto_not.\n  rw @cover_vars_upto_less_than.\n  split; sp.\nQed.\n\nLemma cover_vars_mk_int {o} :\n  forall (s : @CSub o), cover_vars mk_int s.\nProof.\n  introv.\n  rw @cover_vars_eq; simpl; auto.\nQed.\nHint Resolve cover_vars_mk_int : slow.\n\nLemma cover_vars_upto_mk_zero {o} :\n  forall (s : @CSub o) vs, cover_vars_upto mk_zero s vs.\nProof.\n  introv.\n  unfold cover_vars_upto; simpl; auto.\nQed.\nHint Resolve cover_vars_upto_mk_zero : slow.\n\nLemma cover_vars_mk_natk {o} :\n  forall (t : @NTerm o) s,\n    cover_vars (mk_natk t) s <=> cover_vars t s.\nProof.\n  introv.\n  unfold mk_natk, mk_natk_aux.\n  rw @cover_vars_set.\n  rw @cover_vars_upto_prod.\n  rw @cover_vars_upto_le.\n  rw @cover_vars_upto_less_than.\n  split; introv k; repnd; dands; eauto 3 with slow; tcsp;\n  try (complete (apply cover_vars_upto_var; simpl; tcsp)).\n\n  - unfold cover_vars_upto in k; allsimpl.\n    rw @cover_vars_eq.\n    apply subvars_cons_r_weak_if_not_in in k;[|apply newvar_prop].\n    rw @dom_csub_csub_filter in k.\n    eapply subvars_trans;[exact k|].\n    rw subvars_prop; introv i; allsimpl; allrw in_remove_nvars; tcsp.\n\n  - unfold cover_vars_upto; allsimpl.\n    rw @cover_vars_eq in k.\n    rw @dom_csub_csub_filter.\n    eapply subvars_trans;[exact k|].\n    rw subvars_prop; introv i; allsimpl; allrw in_remove_nvars; allsimpl.\n    destruct (deq_nvar (newvar t) x); tcsp.\n    right; sp.\nQed.\n\nLemma cover_vars_mk_tnat {o} :\n  forall (s : @CSub o), cover_vars mk_tnat s.\nProof.\n  introv.\n  unfold mk_tnat.\n  rw @cover_vars_set; dands; eauto 3 with slow.\n  apply cover_vars_upto_le; dands; eauto 3 with slow.\n  apply cover_vars_upto_var; simpl; sp.\nQed.\nHint Resolve cover_vars_mk_tnat : slow.\n\nLemma sub_find_sub_filter_trivial {o} :\n  forall (s : @Sub o) x, sub_find (sub_filter s [x]) x = None.\nProof.\n  introv.\n  rw @sub_find_sub_filter_eq; rw memvar_singleton; boolvar; auto.\nQed.\nHint Rewrite @sub_find_sub_filter_trivial : slow.\n\nLemma sub_find_sub_filter_trivial2 {o} :\n  forall (s : @Sub o) x y, sub_find (sub_filter (sub_filter s [x]) [y]) x = None.\nProof.\n  introv.\n  allrw @sub_find_sub_filter_eq.\n  allrw memvar_singleton; boolvar; auto.\nQed.\nHint Rewrite @sub_find_sub_filter_trivial2 : slow.\n\nLemma beq_var_newvar_trivial1 {o} :\n  forall v (t : @NTerm o),\n    LIn v (free_vars t)\n    -> beq_var v (newvar t) = false.\nProof.\n  introv i; boolvar; auto.\n  pose proof (newvar_prop t) as h; allsimpl; allrw not_over_or; 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/terms/natk.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5, "lm_q1q2_score": 0.27916349716768724}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n  Copyright 2015 Cornell University\n  Copyright 2016 Cornell University\n  Copyright 2017 Cornell University\n  Copyright 2018 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 sequents2.\n\n\nLemma pointwise_implies_pairwise {o} :\n  forall lib (s : @csequent o),\n    AN_sequent_true_pairwise lib s -> VR_sequent_true lib s.\nProof.\n  introv seq.\n  unfold VR_sequent_true.\n  unfold AN_sequent_true_pairwise in seq.\n  introv.\n  generalize (seq s1 s2); clear seq; intro seq.\n  destruct (destruct_csequent s); destruct ec; exrepnd; intros sim eqh; auto.\nQed.\n\nDefinition pairwise_sequent_true {o} lib (s : @baresequent o) :=\n  {c : wf_csequent s & AN_sequent_true_pairwise lib (mk_wcseq s c)}.\n\nDefinition pairwise_rule_true2 {o} lib (R : @rule o) : Type :=\n  forall pwf   : pwf_sequent (goal R),\n  forall cargs : args_constraints (sargs R) (hyps (goal R)),\n  forall hyps  : (forall s, LIn s (subgoals R) -> pairwise_sequent_true lib s),\n    pairwise_sequent_true lib (goal R).\n\nDefinition pairwise_rule_true3 {o} lib (R : @rule o) : Type :=\n  forall pwf   : wf_bseq (goal R),\n  forall cargs : args_constraints (sargs R) (hyps (goal R)),\n  forall hyps  : (forall s, LIn s (subgoals R) -> pairwise_sequent_true lib s),\n    pairwise_sequent_true lib (goal R).\n\nLemma pairwise_rule_true3_implies_pairwise_rule_true2 {o} :\n  forall lib (R : @rule o), pairwise_rule_true3 lib R -> pairwise_rule_true2 lib R.\nProof.\n  introv rt wf args imp.\n  unfold pairwise_rule_true3 in rt.\n  repeat (autodimp rt hyp); eauto 3 with slow.\nQed.\nHint Resolve pairwise_rule_true3_implies_pairwise_rule_true2 : slow.\n\nLemma AN_sequent_true_pairwise_all {o} :\n  forall lib (S : @csequent o),\n    AN_sequent_true_pairwise lib S\n    <=>\n    forall s1 s2,\n      match destruct_csequent S with\n      | cseq_comps H T wh wt ct ec =>\n        forall pC1 : cover_vars T s1,\n        forall pC2 : cover_vars T s2,\n          similarity lib s1 s2 H\n          -> eq_hyps lib s1 s2 H\n          -> match ec with\n             | Some (existT _ ext (we, ce)) =>\n               forall pt1 : cover_vars ext s1,\n               forall pt2 : cover_vars ext s2,\n                 tequality lib (lsubstc T wt s1 pC1)\n                           (lsubstc T wt s2 pC2)\n                           # equality lib (lsubstc ext we s1 pt1)\n                           (lsubstc ext we s2 pt2)\n                           (lsubstc T wt s1 pC1)\n             | None => tequality lib (lsubstc T wt s1 pC1)\n                                 (lsubstc T wt s2 pC2)\n             end\n      end.\nProof.\n  unfold AN_sequent_true_pairwise; split; intro h;\n    destruct (destruct_csequent S); destruct ec; exrepnd; introv.\n\n  { introv sim eqh; introv.\n    pose proof (h s2 s3 sim eqh) as h.\n    rewrite lsubstc_replace with (w2 := wt) (p2 := pC1) in h; auto.\n    rewrite lsubstc_replace with (w2 := wt) (p2 := pC2) in h; auto.\n    rewrite lsubstc_replace with (w2 := s1) (p2 := pt1) in h; auto.\n    rewrite lsubstc_replace with (w2 := s1) (p2 := pt2) in h; auto. }\n\n  { introv sim eqh.\n    pose proof (h s1 s2 sim eqh) as h.\n    rewrite lsubstc_replace with (w2 := wt) (p2 := pC1) in h; auto.\n    rewrite lsubstc_replace with (w2 := wt) (p2 := pC2) in h; tcsp. }\n\n  { introv eqh; eapply h; auto. }\n\n  { introv eqh; dands; auto. }\nQed.\n\nLemma AN_sequent_true_pairwise_ex {o} :\n  forall lib (S : @csequent o),\n    AN_sequent_true_pairwise lib S\n    <=>\n    forall s1 s2,\n      match destruct_csequent S with\n      | cseq_comps H T wh wt ct ec =>\n        similarity lib s1 s2 H\n        -> eq_hyps lib s1 s2 H\n        -> {pC1 : cover_vars T s1\n            & {pC2 : cover_vars T s2\n            & tequality lib (lsubstc T wt s1 pC1)\n                        (lsubstc T wt s2 pC2)\n              #\n              match ec with\n              | Some (existT _ ext (we, ce)) =>\n                {pt1 : cover_vars ext s1\n                 & {pt2 : cover_vars ext s2\n                 & equality lib (lsubstc ext we s1 pt1)\n                            (lsubstc ext we s2 pt2)\n                            (lsubstc T wt s1 pC1)}}\n              | None => True\n              end}}\n      end.\nProof.\n  unfold AN_sequent_true_pairwise; split; intro h;\n    destruct (destruct_csequent S); destruct ec; exrepnd; introv; auto.\n\n  { introv sim eqh.\n    pose proof (h s2 s3 sim eqh) as h; repnd.\n    exists (s_cover_typ1 lib T s2 s3 hs ct sim)\n           (s_cover_typ2 lib T s2 s3 hs ct sim); sp.\n    exists (s_cover_ex1 lib t s2 s3 hs s0 sim)\n           (s_cover_ex2 lib t s2 s3 hs s0 sim); sp. }\n\n  { introv sim eqh.\n    pose proof (h s1 s2 sim eqh) as h; repnd.\n    exists (s_cover_typ1 lib T s1 s2 hs ct sim)\n           (s_cover_typ2 lib T s1 s2 hs ct sim); sp. }\n\n  { introv eqh.\n    pose proof (h s2 s3 p eqh) as h; exrepnd.\n    rewrite lsubstc_replace with (w2 := wt) (p2 := pC1); auto.\n    rewrite lsubstc_replace with (w2 := wt) (p2 := pC2); auto.\n    rewrite lsubstc_replace with (w2 := s1) (p2 := pt1); auto.\n    rewrite lsubstc_replace with (w2 := s1) (p2 := pt2); auto. }\n\n  { introv eqh.\n    pose proof (h s1 s2 p eqh ) as h; exrepnd.\n    rewrite lsubstc_replace with (w2 := wt) (p2 := pC1); auto.\n    rewrite lsubstc_replace with (w2 := wt) (p2 := pC2); auto. }\nQed.\n\nTactic Notation \"seq_true_pairwise\" :=\n  rw @AN_sequent_true_pairwise_all;\n  simpl;\n  introv sim eqh;\n  introv;\n  proof_irr;\n  GC.\n\nLtac seq_true_pairwise_ltac H :=\n  trw_h AN_sequent_true_pairwise_ex  H;\n  simpl in H.\n\nTactic Notation \"seq_true_pairwise\" \"in\" ident(H) :=\n  seq_true_pairwise_ltac H.\n\nLtac prove_eq_hyps_snoc :=\n  match goal with\n  | [ |- eq_hyps _ (snoc ?s1 (?x1,?t1)) (snoc ?s2 (?x2,?t2)) (snoc ?hs ?h) ] =>\n    let wf := fresh \"wf\" in\n    let cov1 := fresh \"cov1\" in\n    let cov2 := fresh \"cov2\" in\n    assert (wf_term (htyp h)) as wf;\n    [simpl;auto\n    |assert (cover_vars (htyp h) s1) as cov1;\n     [simpl;auto\n     |assert (cover_vars (htyp h) s2) as cov2;\n      [simpl;auto\n      |apply eq_hyps_snoc;\n       exists s1 s2 t1 t2 wf cov1 cov2;\n       simpl;dands;auto\n      ]\n     ]\n    ]\n  end.\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/per/functionality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5, "lm_q1q2_score": 0.27916349716768724}}
{"text": "From iris.base_logic Require Import invariants.\nFrom iris.program_logic Require Export weakestpre.\nFrom iris.heap_lang Require Export lang proofmode notation.\nFrom iris.algebra Require Import excl.\nFrom iris_examples.concurrent_stacks Require Import specs.\nFrom iris.prelude Require Import options.\n\n(** Stack 4: Helping, CAP spec. *)\n\nDefinition mk_offer : val :=\n  λ: \"v\", (\"v\", ref #0).\nDefinition revoke_offer : val :=\n  λ: \"v\", if: CAS (Snd \"v\") #0 #2 then SOME (Fst \"v\") else NONE.\nDefinition take_offer : val :=\n  λ: \"v\", if: CAS (Snd \"v\") #0 #1 then SOME (Fst \"v\") else NONE.\n\nDefinition mk_mailbox : val := λ: \"_\", ref NONEV.\nDefinition put : val :=\n  λ: \"r\" \"v\",\n    let: \"off\" := mk_offer \"v\" in\n    \"r\" <- SOME \"off\";;\n    revoke_offer \"off\".\nDefinition get : val :=\n  λ: \"r\",\n    let: \"offopt\" := !\"r\" in\n    match: \"offopt\" with\n      NONE => NONE\n    | SOME \"x\" => take_offer \"x\"\n    end.\n\nDefinition mk_stack : val := λ: \"_\", (mk_mailbox #(), ref NONEV).\nDefinition push : val :=\n  rec: \"push\" \"p\" \"v\" :=\n    let: \"mailbox\" := Fst \"p\" in\n    let: \"s\" := Snd \"p\" in\n    match: put \"mailbox\" \"v\" with\n      NONE => #()\n    | SOME \"v'\" =>\n      let: \"tail\" := ! \"s\" in\n      let: \"new\" := SOME (ref (\"v'\", \"tail\")) in\n      if: CAS \"s\" \"tail\" \"new\" then #() else \"push\" \"p\" \"v'\"\n    end.\nDefinition pop : val :=\n  rec: \"pop\" \"p\" :=\n    let: \"mailbox\" := Fst \"p\" in\n    let: \"s\" := Snd \"p\" in\n    match: get \"mailbox\" with\n      NONE =>\n      match: !\"s\" with\n        NONE => NONEV\n      | SOME \"l\" =>\n        let: \"pair\" := !\"l\" in\n        if: CAS \"s\" (SOME \"l\") (Snd \"pair\")\n        then SOME (Fst \"pair\")\n        else \"pop\" \"p\"\n      end\n    | SOME \"x\" => SOME \"x\"\n    end.\n\nDefinition channelR := exclR unitR.\nClass channelG Σ := {channel_inG :> inG Σ channelR}.\n\nSection proofs.\n  Context `{!heapGS Σ, !channelG Σ} (N : namespace).\n\n  Implicit Types l : loc.\n\n  Definition Nside_channel := N .@ \"side_channel\".\n  Definition Nstack := N .@ \"stack\".\n  Definition Nmailbox := N .@ \"mailbox\".\n\n  Definition inner_mask : coPset := ⊤ ∖ ↑Nside_channel ∖ ↑Nstack.\n\n  Lemma inner_mask_includes :\n     ⊤ ∖ ↑ N ⊆ inner_mask.\n  Proof. solve_ndisj. Qed.\n\n  Lemma inner_mask_promote (P Q : iProp Σ) :\n     (P ={⊤ ∖ ↑ N}=∗ Q) -∗ (P ={inner_mask}=∗ Q).\n  Proof.\n    iIntros \"Himp P\".\n    iMod (fupd_mask_subseteq (⊤ ∖ ↑ N)) as \"H\"; first by apply inner_mask_includes.\n    iDestruct (\"Himp\" with \"P\") as \"HQ\".\n    iMod \"HQ\".\n    by iMod \"H\".\n  Qed.\n\n  Definition revoke_tok γ := own γ (Excl ()).\n  Definition can_push P Q v : iProp Σ :=\n    (∀ (xs : list val), P xs ={inner_mask}=∗ P (v :: xs) ∗ Q #())%I.\n  Definition access_inv (P : list val → iProp Σ) : iProp Σ :=\n    (|={⊤ ∖ ↑Nside_channel, inner_mask}=> ∃ vs, (▷ P vs) ∗\n      ((▷ P vs) ={inner_mask, ⊤ ∖ ↑Nside_channel}=∗ True))%I.\n\n  Definition stages γ P Q l (v : val) :=\n    ((l ↦ #0 ∗ can_push P Q v)  ∨\n     (l ↦ #1 ∗ Q #()) ∨\n     (l ↦ #1 ∗ revoke_tok γ) ∨\n     (l ↦ #2 ∗ revoke_tok γ))%I.\n\n  Definition is_offer γ P Q (v : val) : iProp Σ :=\n    (∃ v' l, ⌜v = (v', #l)%V⌝ ∗ inv Nside_channel (stages γ P Q l v'))%I.\n\n  Lemma mk_offer_works P Q v :\n    {{{ can_push P Q v }}}\n      mk_offer v\n    {{{ o γ, RET o; is_offer γ P Q o ∗ revoke_tok γ }}}.\n  Proof.\n    iIntros (Φ) \"HP HΦ\".\n    wp_lam. wp_alloc l as \"Hl\".\n    iMod (own_alloc (Excl ())) as (γ) \"Hγ\"; first done.\n    iMod (inv_alloc Nside_channel _ (stages γ P Q l v) with \"[Hl HP]\") as \"#Hinv\".\n    { iNext; iLeft; iFrame. }\n    wp_pures; iModIntro; iApply \"HΦ\"; iFrame; iExists _, _; auto.\n  Qed.\n\n  Lemma revoke_works γ P Q v :\n    {{{ is_offer γ P Q v ∗ revoke_tok γ }}}\n      revoke_offer v\n    {{{ v', RET v'; (∃ v'' : val, ⌜v' = InjRV v''⌝ ∗ can_push P Q v'') ∨ (⌜v' = InjLV #()⌝ ∗ (Q #())) }}}.\n  Proof.\n    iIntros (Φ) \"[Hinv Hγ] HΦ\". iDestruct \"Hinv\" as (v' l) \"[-> #Hinv]\".\n    wp_lam. wp_pures. wp_bind (CmpXchg _ _ _).\n    iInv Nside_channel as \"Hstages\" \"Hclose\".\n    iDestruct \"Hstages\" as \"[[Hl HP] | [[Hl HQ] | [[Hl H] | [Hl H]]]]\".\n    - wp_cmpxchg_suc.\n      iMod (\"Hclose\" with \"[Hl Hγ]\") as \"_\".\n      { iNext; iRight; iRight; iFrame. }\n      iModIntro.\n      wp_pures.\n      by iApply \"HΦ\"; iLeft; iExists _; iFrame.\n    - wp_cmpxchg_fail.\n      iMod (\"Hclose\" with \"[Hl Hγ]\") as \"_\".\n      { iNext; iRight; iRight; iLeft; iFrame. }\n      iModIntro.\n      wp_pures.\n      iApply (\"HΦ\" with \"[HQ]\"); iRight; auto.\n    - wp_cmpxchg_fail.\n      iDestruct (own_valid_2 with \"H Hγ\") as %[].\n    - wp_cmpxchg_fail.\n      iDestruct (own_valid_2 with \"H Hγ\") as %[].\n  Qed.\n\n  Lemma take_works γ P Q Q' o Ψ :\n    let do_pop : iProp Σ :=\n        (∀ v xs, P (v :: xs) ={inner_mask}=∗ P xs ∗ Ψ (SOMEV v))%I in\n    {{{ is_offer γ P Q o ∗ access_inv P ∗ (do_pop ∧ Q') }}}\n      take_offer o\n    {{{ v', RET v';\n        (∃ v'' : val, ⌜v' = InjRV v''⌝ ∗ Ψ v') ∨ (⌜v' = InjLV #()⌝ ∗ (do_pop ∧ Q')) }}}.\n  Proof.\n    simpl; iIntros (Φ) \"[H [Hopener Hupd]] HΦ\"; iDestruct \"H\" as (v l) \"[-> #Hinv]\".\n    wp_lam. wp_proj. wp_bind (CmpXchg _ _ _).\n    iInv Nside_channel as \"Hstages\" \"Hclose\".\n    iDestruct \"Hstages\" as \"[[Hl Hpush] | [[Hl HQ] | [[Hl Hγ] | [Hl Hγ]]]]\".\n    - iMod \"Hopener\" as (xs) \"[HP Hcloser]\".\n      wp_cmpxchg_suc.\n      iMod (\"Hpush\" with \"HP\") as \"[HP HQ]\".\n      iMod (\"Hupd\" with \"HP\") as \"[HP HΨ]\".\n      iMod (\"Hcloser\" with \"HP\") as \"_\".\n      iMod (\"Hclose\" with \"[Hl HQ]\") as \"_\".\n      { iRight; iLeft; iFrame. }\n      iApply fupd_mask_intro_subseteq; first done.\n      wp_pures.\n      iApply \"HΦ\"; iLeft; auto.\n    - wp_cmpxchg_fail.\n      iMod (\"Hclose\" with \"[Hl HQ]\") as \"_\".\n      { iRight; iLeft; iFrame. }\n      iModIntro.\n      wp_pures.\n      iApply \"HΦ\"; auto.\n    - wp_cmpxchg_fail.\n      iMod (\"Hclose\" with \"[Hl Hγ]\").\n      { iRight; iRight; iFrame. }\n      iModIntro.\n      wp_pures.\n      iApply \"HΦ\"; auto.\n    - wp_cmpxchg_fail.\n      iMod (\"Hclose\" with \"[Hl Hγ]\").\n      { iRight; iRight; iFrame. }\n      iModIntro.\n      wp_pures.\n      iApply \"HΦ\"; auto.\n  Qed.\n\n  Definition mailbox_inv P l : iProp Σ :=\n    (l ↦ NONEV ∨ (∃ v' γ Q, l ↦ SOMEV v' ∗ is_offer γ P Q v'))%I.\n\n  Definition is_mailbox P v : iProp Σ :=\n    (∃ l, ⌜v = #l⌝ ∗ inv Nmailbox (mailbox_inv P l))%I.\n\n  Lemma mk_mailbox_works P :\n    {{{ True }}} mk_mailbox #() {{{ v, RET v; is_mailbox P v }}}.\n  Proof.\n    iIntros (Φ) \"_ HΦ\".\n    wp_lam. wp_alloc l as \"Hl\".\n    iMod (inv_alloc Nmailbox _ (mailbox_inv P l) with \"[Hl]\") as \"#Hinv\".\n    { iNext; by iLeft. }\n    iModIntro.\n    iApply \"HΦ\"; iExists _; auto.\n  Qed.\n\n  Lemma get_works Q P Ψ mailbox :\n    let do_pop : iProp Σ :=\n        (∀ v xs, P (v :: xs) ={inner_mask}=∗ P xs ∗ Ψ (SOMEV v))%I in\n    {{{ is_mailbox P mailbox ∗ access_inv P ∗ (do_pop ∧ Q) }}}\n      get mailbox\n    {{{ ov, RET ov; (∃ v, ⌜ov = SOMEV v⌝ ∗ Ψ ov) ∨ (⌜ov = NONEV⌝ ∗ (do_pop ∧ Q)) }}}.\n  Proof.\n    simpl; iIntros (Φ) \"[Hmail [Hopener Hpush]] HΦ\". iDestruct \"Hmail\" as (l) \"[-> #Hmail]\".\n    wp_lam. wp_bind (Load _).\n    iInv Nmailbox as \"[Hnone | Hsome]\" \"Hclose\".\n    - wp_load.\n      iMod (\"Hclose\" with \"[Hnone]\") as \"_\".\n      { by iLeft. }\n      iModIntro.\n      wp_pures.\n      iApply \"HΦ\"; iRight; by iFrame.\n    - iDestruct \"Hsome\" as (v' γ Q') \"[Hl #Hoffer]\".\n      wp_load.\n      iMod (\"Hclose\" with \"[Hl Hoffer]\") as \"_\".\n      { iNext; iRight; iExists _, _, _; by iFrame. }\n      iModIntro.\n      wp_let. wp_match. wp_apply (take_works with \"[Hpush Hopener]\"); by iFrame.\n  Qed.\n\n  Lemma put_works P Q mailbox v :\n    {{{ is_mailbox P mailbox ∗ can_push P Q v }}}\n      put mailbox v\n    {{{ o, RET o; (∃ v', ⌜o = SOMEV v'⌝ ∗ can_push P Q v') ∨ (⌜o = NONEV⌝ ∗ Q #()) }}}.\n  Proof.\n    iIntros (Φ) \"[Hmail Hpush] HΦ\". iDestruct \"Hmail\" as (l) \"[-> #Hmail]\".\n    wp_lam. wp_let. wp_apply (mk_offer_works with \"Hpush\").\n    iIntros (o γ) \"[#Hoffer Hrev]\".\n    wp_let. wp_bind (Store _ _). wp_pures.\n    iInv Nmailbox as \"[Hnone | Hsome]\" \"Hclose\".\n    - wp_store.\n      iMod (\"Hclose\" with \"[Hnone]\") as \"_\".\n      { iNext; iRight; iExists _, _, _; by iFrame. }\n      iModIntro.\n      wp_pures.\n      wp_apply (revoke_works with \"[Hrev]\"); first auto.\n      iIntros (v') \"H\"; iApply \"HΦ\"; auto.\n    - iDestruct \"Hsome\" as (v' γ' Q') \"[Hl _]\". wp_store.\n      iMod (\"Hclose\" with \"[Hl]\") as \"_\".\n      { iNext; iRight; iExists _, _, _; by iFrame. }\n      iModIntro.\n      wp_pures.\n      wp_apply (revoke_works with \"[Hrev]\"); first auto.\n      iIntros (v'') \"H\"; iApply \"HΦ\"; auto.\n  Qed.\n\n  Definition oloc_to_val (ol: option loc) : val :=\n    match ol with\n    | None => NONEV\n    | Some loc => SOMEV (#loc)\n    end.\n  Local Instance oloc_to_val_inj : Inj (=) (=) oloc_to_val.\n  Proof. intros [|][|]; simpl; congruence. Qed.\n\n  Fixpoint is_list xs v : iProp Σ :=\n    (match xs, v with\n     | [], None => True\n     | x :: xs, Some l => ∃ t, l ↦□ (x, oloc_to_val t)%V ∗ is_list xs t\n     | _, _ => False\n     end)%I.\n\n  Lemma is_list_dup xs v :\n    is_list xs v -∗ is_list xs v ∗ match v with\n      | None => True\n      | Some l => ∃ h t, l ↦□ (h, oloc_to_val t)%V\n      end.\n  Proof.\n    destruct xs, v; simpl; auto; first by iIntros \"[]\".\n    iIntros \"H\"; iDestruct \"H\" as (t) \"[#Hl Hstack]\".\n    iSplitL; first by (iExists _; iFrame). by iExists _, _.\n  Qed.\n\n  Lemma is_list_empty xs :\n    is_list xs None -∗ ⌜xs = []⌝.\n  Proof.\n    destruct xs; iIntros \"Hstack\"; auto.\n  Qed.\n\n  Lemma is_list_cons xs l h t :\n    l ↦□ (h, t) -∗\n    is_list xs (Some l) -∗\n    ∃ ys, ⌜xs = h :: ys⌝.\n  Proof.\n    destruct xs; first by iIntros \"? %\".\n    iIntros \"Hl Hstack\"; iDestruct \"Hstack\" as (t') \"(Hl' & Hrest)\".\n    iDestruct (mapsto_agree with \"Hl Hl'\") as \"%\"; simplify_eq; iExists _; auto.\n  Qed.\n\n  Definition stack_inv P l :=\n    (∃ v xs, l ↦ oloc_to_val v ∗ is_list xs v ∗ P xs)%I.\n\n  Definition is_stack_pred P v :=\n    (∃ mailbox l, ⌜v = (mailbox, #l)%V⌝ ∗ is_mailbox P mailbox ∗ inv Nstack (stack_inv P l))%I.\n\n  Theorem mk_stack_works (P : list val → iProp Σ) :\n    {{{ P [] }}} mk_stack #() {{{ v, RET v; is_stack_pred P v }}}.\n  Proof.\n    iIntros (Φ) \"HP HΦ\".\n    wp_lam.\n    wp_alloc l as \"Hl\".\n    wp_apply mk_mailbox_works ; first done. iIntros (v) \"#Hmailbox\".\n    iMod (inv_alloc Nstack _ (stack_inv P l) with \"[Hl HP]\") as \"#Hinv\".\n    { by iNext; iExists None, []; iFrame. }\n    wp_pures. iModIntro; iApply \"HΦ\"; iExists _; auto.\n  Qed.\n\n  Theorem push_works P s v Ψ :\n    {{{ is_stack_pred P s ∗ ∀ xs, P xs ={⊤ ∖ ↑ N}=∗ P (v :: xs) ∗ Ψ #()}}}\n      push s v\n    {{{ RET #(); Ψ #() }}}.\n  Proof.\n    iIntros (Φ) \"[Hstack Hupd] HΦ\". iDestruct \"Hstack\" as (mailbox l) \"(-> & #Hmailbox & #Hinv)\".\n    iAssert (∀ (xs : list val), P xs ={inner_mask}=∗ P (v :: xs) ∗ Ψ #())%I with \"[Hupd]\" as \"Hupd\".\n    { iIntros (xs). by iApply inner_mask_promote. }\n    iLöb as \"IH\" forall (v).\n    wp_lam. wp_pures.\n    wp_apply (put_works with \"[Hupd]\"); first auto. iIntros (o) \"H\".\n    iDestruct \"H\" as \"[Hsome | [-> HΨ]]\".\n    - iDestruct \"Hsome\" as (v') \"[-> Hupd]\".\n      wp_match.\n      wp_bind (Load _).\n      iInv Nstack as (list xs) \"(Hl & Hlist & HP)\" \"Hclose\".\n      wp_load.\n      iMod (\"Hclose\" with \"[Hl Hlist HP]\") as \"_\".\n      { iNext; iExists _, _; iFrame. }\n      clear xs.\n      iModIntro.\n      wp_let. wp_alloc l' as \"Hl'\". wp_pures. wp_bind (CmpXchg _ _ _).\n      iInv Nstack as (list' xs) \"(Hl & Hlist & HP)\" \"Hclose\".\n      destruct (decide (list = list')) as [ -> |].\n      * wp_cmpxchg_suc. { destruct list'; left; done. }\n        iMod (mapsto_persist with \"Hl'\") as \"#Hl'\".\n        iMod (fupd_mask_subseteq inner_mask) as \"Hupd'\"; first solve_ndisj.\n        iMod (\"Hupd\" with \"HP\") as \"[HP HΨ]\".\n        iMod \"Hupd'\" as \"_\".\n        iMod (\"Hclose\" with \"[Hl HP Hlist]\") as \"_\".\n        { iNext; iExists (Some _), (v' :: xs); iFrame; iExists _; iFrame; auto. }\n        iModIntro.\n        wp_pures.\n        by iApply (\"HΦ\" with \"HΨ\").\n      * wp_cmpxchg_fail.\n      { destruct list, list'; simpl; congruence. }\n      { destruct list'; left; done. }\n        iMod (\"Hclose\" with \"[Hl HP Hlist]\").\n        { iExists _, _; iFrame. }\n        iModIntro.\n        wp_pures.\n        iApply (\"IH\" with \"HΦ Hupd\").\n    - wp_match. iApply (\"HΦ\" with \"HΨ\").\n  Qed.\n\n  Theorem pop_works P s Ψ :\n    {{{ is_stack_pred P s ∗\n        (∀ v xs, P (v :: xs) ={⊤ ∖ ↑ N}=∗ P xs ∗ Ψ (SOMEV v)) ∧\n        (P [] ={⊤ ∖ ↑ N}=∗ P [] ∗ Ψ NONEV) }}}\n      pop s\n    {{{ v, RET v; Ψ v }}}.\n  Proof.\n    iIntros (Φ) \"(Hstack & Hupd) HΦ\".\n    iDestruct \"Hstack\" as (mailbox l) \"(-> & #Hmailbox & #Hinv)\".\n    iDestruct (bi.and_mono_r with \"Hupd\") as \"Hupd\"; first apply inner_mask_promote.\n    iDestruct (bi.and_mono_l _ _ (∀ (v : val) (xs : list val), _)%I with \"Hupd\") as \"Hupd\".\n    { iIntros \"Hupdcons\". iIntros (v xs). iSpecialize (\"Hupdcons\" $! v xs). iApply (inner_mask_promote with \"Hupdcons\"). }\n    iLöb as \"IH\".\n    wp_lam. wp_proj. wp_let. wp_proj. wp_let.\n    wp_apply (get_works _ _ (λ v, Ψ v) with \"[Hupd]\").\n    { iSplitR; first done.\n      iFrame.\n      iInv Nstack as (v xs) \"(Hl & Hlist & HP)\" \"Hclose\".\n      iModIntro.\n      iExists xs; iSplitL \"HP\"; first auto.\n      iIntros \"HP\".\n      iMod (\"Hclose\" with \"[HP Hl Hlist]\") as \"_\".\n      { iNext; iExists _, _; iFrame. }\n      auto. }\n    iIntros (ov) \"[Hsome | [-> Hupd]]\".\n    - iDestruct \"Hsome\" as (v) \"[-> HΨ]\".\n      wp_pures.\n      iApply (\"HΦ\" with \"HΨ\").\n    - wp_match. wp_bind (Load _).\n      iInv Nstack as (v xs) \"(Hl & Hlist & HP)\" \"Hclose\".\n      wp_load.\n      iDestruct (is_list_dup with \"Hlist\") as \"[Hlist H]\".\n    destruct v as [l'|]; last first.\n      * iDestruct (is_list_empty with \"Hlist\") as %->.\n        iMod (fupd_mask_subseteq inner_mask) as \"Hupd'\"; first solve_ndisj.\n        iMod (\"Hupd\" with \"HP\") as \"[HP HΨ]\".\n        iMod \"Hupd'\" as \"_\".\n        iMod (\"Hclose\" with \"[Hlist Hl HP]\") as \"_\".\n        { iNext; iExists _, _; iFrame. }\n        iModIntro.\n        wp_match.\n        iApply (\"HΦ\" with \"HΨ\").\n      * iDestruct \"H\" as (h t) \"Hl'\".\n        iMod (\"Hclose\" with \"[Hlist Hl HP]\") as \"_\".\n        { iNext; iExists _, _; iFrame. }\n        iModIntro.\n        wp_match. wp_bind (Load _).\n        iInv Nstack as (v xs') \"(Hl & Hlist & HP)\" \"Hclose\".\n        wp_load.\n        iMod (\"Hclose\" with \"[Hlist Hl HP]\") as \"_\".\n        { iNext; iExists _, _; iFrame. }\n        iModIntro.\n        wp_pures. wp_bind (CmpXchg _ _ _).\n        iInv Nstack as (v' xs'') \"(Hl & Hlist & HP)\" \"Hclose\".\n        destruct (decide (v' = (Some l'))) as [ -> |].\n        + wp_cmpxchg_suc.\n          iDestruct (is_list_cons with \"Hl' Hlist\") as (ys) \"%\".\n          simplify_eq.\n          iMod (fupd_mask_subseteq inner_mask) as \"Hupd'\"; first solve_ndisj.\n          iDestruct \"Hupd\" as \"[Hupdcons _]\".\n          iMod (\"Hupdcons\" with \"HP\") as \"[HP HΨ]\".\n          iMod \"Hupd'\" as \"_\".\n          iDestruct \"Hlist\" as (t') \"(Hl'' & Hlist)\".\n          iDestruct (mapsto_agree with \"Hl' Hl''\") as \"%\"; simplify_eq.\n          iMod (\"Hclose\" with \"[Hlist Hl HP]\") as \"_\".\n          { iNext; iExists _, _; iFrame. }\n          iModIntro.\n          wp_pures.\n          iApply (\"HΦ\" with \"HΨ\").\n        + wp_cmpxchg_fail. { destruct v'; simpl; congruence. }\n          iMod (\"Hclose\" with \"[Hlist Hl HP]\") as \"_\".\n          { iNext; iExists _, _; iFrame. }\n          iModIntro.\n          wp_pures.\n          iApply (\"IH\" with \"HΦ Hupd\").\n  Qed.\nEnd proofs.\n\nProgram Definition spec {Σ} `{heapGS Σ, channelG Σ} : concurrent_stack Σ :=\n  {| is_stack := is_stack_pred; new_stack := mk_stack; stack_push := push; stack_pop := pop |} .\nSolve Obligations of spec with eauto using pop_works, push_works, mk_stack_works.\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/concurrent_stacks/concurrent_stack4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2791634971676872}}
{"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 NArith Ndec Ndigits.\nRequire Import ZArith.\nRequire Import Classical_Prop.\nFrom IntMap Require Import Allmaps.\nRequire Import bases.\nRequire Import defs.\nRequire Import semantics.\nRequire Import signature.\nRequire Import refcorrect.\n\n(* définition des fonctions de modification des adresses *)\n\nDefinition uad_conv_0 (a : ad) : ad :=\n  match a with\n  | N0 => N0\n  | Npos p => Npos (xO p)\n  end.\n\nDefinition uad_conv_1 (a : ad) : ad :=\n  match a with\n  | N0 => Npos 1\n  | Npos p => Npos (xI p)\n  end.\n\nLemma adcnv_inj0 : forall a b : ad, uad_conv_0 a = uad_conv_0 b -> a = b.\nProof.\n\tsimple induction a; simple induction b. intro. trivial. intro. simpl in |- *. intro. \n\tinversion H. simpl in |- *. intro. inversion H. simpl in |- *. intros. cut (p = p0).\n\tsimpl in |- *. intro. simpl in |- *. rewrite H0. trivial. inversion H. trivial.\nQed.\n\nLemma adcnv_inj1 : forall a b : ad, uad_conv_1 a = uad_conv_1 b -> a = b.\nProof.\n\tsimple induction a; simple induction b. intros. trivial. simpl in |- *. intros. \n\tinversion H. simpl in |- *. intros. inversion H. simpl in |- *. intros.\n\tcut (p = p0). intro. rewrite H0. trivial. inversion H. trivial.\nQed.\n\nLemma adcnv_ok : forall a b : ad, uad_conv_0 a <> uad_conv_1 b.\nProof.\n\tsimple induction a; simple induction b. simpl in |- *. intro. inversion H.\n\tsimpl in |- *. intros. intro. inversion H. simpl in |- *. intro. inversion H.\n\tsimpl in |- *. intros. intro. inversion H.\nQed.\n\nLemma adcnv_disj :\n forall a : ad, exists b : ad, a = uad_conv_0 b \\/ a = uad_conv_1 b.\nProof.\n\tsimple induction a. split with N0. left. simpl in |- *. trivial. simple induction p.\n\tintros. split with (Npos p0). right. simpl in |- *. trivial. intros.\n\tsplit with (Npos p0). left. simpl in |- *. trivial. split with N0.\n\tright. simpl in |- *. trivial.\nQed.\n\n(* calcul des automates modifiés *)\n\nFixpoint upl_conv_0 (p : prec_list) : prec_list :=\n  match p with\n  | prec_empty => prec_empty\n  | prec_cons a p0 p1 =>\n      prec_cons (uad_conv_0 a) (upl_conv_0 p0) (upl_conv_0 p1)\n  end.\n\nFixpoint upl_conv_1 (p : prec_list) : prec_list :=\n  match p with\n  | prec_empty => prec_empty\n  | prec_cons a p0 p1 =>\n      prec_cons (uad_conv_1 a) (upl_conv_1 p0) (upl_conv_1 p1)\n  end.\n\nFixpoint umpl_conv_0 (s : state) : state :=\n  match s with\n  | M0 => M0 prec_list\n  | M1 a p => M1 prec_list a (upl_conv_0 p)\n  | M2 p0 p1 => M2 prec_list (umpl_conv_0 p0) (umpl_conv_0 p1)\n  end.\n\nFixpoint umpl_conv_1 (s : state) : state :=\n  match s with\n  | M0 => M0 prec_list\n  | M1 a p => M1 prec_list a (upl_conv_1 p)\n  | M2 p0 p1 => M2 prec_list (umpl_conv_1 p0) (umpl_conv_1 p1)\n  end.\n\nFixpoint udta_conv_0_aux (d : preDTA) : preDTA :=\n  match d with\n  | M0 => M0 state\n  | M1 a s => M1 state a (umpl_conv_0 s)\n  | M2 s0 s1 => M2 state (udta_conv_0_aux s0) (udta_conv_0_aux s1)\n  end.\n\nFixpoint udta_conv_1_aux (d : preDTA) : preDTA :=\n  match d with\n  | M0 => M0 state\n  | M1 a s => M1 state a (umpl_conv_1 s)\n  | M2 s0 s1 => M2 state (udta_conv_1_aux s0) (udta_conv_1_aux s1)\n  end.\n\nDefinition udta_conv_0 (d : preDTA) : preDTA :=\n  M2 state (udta_conv_0_aux d) (M0 state).\n\nDefinition udta_conv_1 (d : preDTA) : preDTA :=\n  M2 state (M0 state) (udta_conv_1_aux d).\n\n(* lemmes d'injectivité *)\n\nLemma upl_conv_0_inj :\n forall p0 p1 : prec_list, upl_conv_0 p0 = upl_conv_0 p1 -> p0 = p1.\nProof.\n\tsimple induction p0. intros. induction  p2 as [a0 p2_1 Hrecp2_1 p2_0 Hrecp2_0| ]. simpl in H1. inversion H1. \n\tcut (p = p2_1). cut (p1 = p2_0). intros. rewrite H2. rewrite H6. cut (a = a0).\n\tintro. rewrite H7. trivial. exact (adcnv_inj0 a a0 H3).\n\texact (H0 p2_0 H5). exact (H p2_1 H4). simpl in H1. inversion H1.\n\tsimple induction p1. intros. inversion H1. intros. trivial.\nQed.\n\nLemma upl_conv_1_inj :\n forall p0 p1 : prec_list, upl_conv_1 p0 = upl_conv_1 p1 -> p0 = p1.\nProof.\n\tsimple induction p0. intros. induction  p2 as [a0 p2_1 Hrecp2_1 p2_0 Hrecp2_0| ]. simpl in H1. inversion H1.\n\tcut (a = a0). cut (p = p2_1). cut (p1 = p2_0). intros. rewrite H2. rewrite H6.\n\trewrite H7. trivial. exact (H0 p2_0 H5). exact (H p2_1 H4).\n \texact (adcnv_inj1 a a0 H3). inversion H1. simple induction p1. intros.\n\tinversion H1. intros. trivial.\nQed.\n\nLemma umpl_conv_0_inj :\n forall s0 s1 : state, umpl_conv_0 s0 = umpl_conv_0 s1 -> s0 = s1.\nProof.\n\tsimple induction s0. simple induction s1. simpl in |- *. intros. trivial.\n\tintros. inversion H. intros. simpl in H1. inversion H1. intro.\n\tintro. simple induction s1. intros. simpl in H. inversion H. intros.\n\tsimpl in H. inversion H. cut (a0 = a2). intro. rewrite H0. trivial.\n\texact (upl_conv_0_inj a0 a2 H2). intros. inversion H1. intro.\n\tintro. intro. intro. simple induction s1. intros. inversion H1.  intros.\n\tinversion H1. intros. simpl in H3. inversion H3. cut (m = m1).\n\tcut (m0 = m2). intros. rewrite H4. rewrite <- H7. trivial.  \n\texact (H0 m2 H6). exact (H m1 H5).\nQed.\n\nLemma umpl_conv_1_inj :\n forall s0 s1 : state, umpl_conv_1 s0 = umpl_conv_1 s1 -> s0 = s1.\nProof.\n\tsimple induction s0. simple induction s1. intros. trivial. intros. inversion H.\n\tintros. inversion H1. intro. intro. simple induction s1. intros.\n\tinversion H. intros. simpl in H. inversion H. cut (a0 = a2). intro.\n\trewrite H0. trivial. exact (upl_conv_1_inj a0 a2 H2). intros.\n\tinversion H1. intro. intro. intro. intro. simple induction s1. intros.\n\tinversion H1. intros. inversion H1. intros. simpl in H3.\n\tinversion H3. cut (m = m1). cut (m0 = m2). intros. rewrite H4. rewrite H7.\n\ttrivial. exact (H0 m2 H6). exact (H m1 H5).\nQed.\n\n(* lemmes sur les images des applications précédentes *)\n\nLemma upl_conv_0_img :\n forall (p : prec_list) (a : ad) (la ls : prec_list),\n upl_conv_0 p = prec_cons a la ls ->\n exists a0 : ad,\n   (exists la0 : prec_list,\n      (exists ls0 : prec_list, p = prec_cons a0 la0 ls0)).\nProof.\n\tsimple induction p. intros. split with a. split with p0. split with p1.\n\ttrivial. intros. inversion H.\nQed.\n\nLemma upl_conv_0_img_0 :\n forall (p : prec_list) (a : ad) (la ls : prec_list),\n upl_conv_0 p = prec_cons a la ls ->\n exists a0 : ad,\n   (exists la0 : prec_list,\n      (exists ls0 : prec_list,\n         p = prec_cons a0 la0 ls0 /\\\n         a = uad_conv_0 a0 /\\ la = upl_conv_0 la0 /\\ ls = upl_conv_0 ls0)).\nProof.\n\tintros. cut\n  (exists a0 : ad,\n     (exists la0 : prec_list,\n        (exists ls0 : prec_list, p = prec_cons a0 la0 ls0))).\n\tintros. elim H0. intros. elim H1. intros. elim H2. intros.\n\trewrite H3 in H. split with x. split with x0. split with x1.\n\tsplit. assumption. split. inversion H. trivial. split.\n\tinversion H; trivial. inversion H. trivial.\n\texact (upl_conv_0_img p a la ls H).\nQed.\n\nLemma upl_conv_0_img_1 :\n forall p : prec_list, upl_conv_0 p = prec_empty -> p = prec_empty.\nProof.\n\tsimple induction p. intros. inversion H1. intros. trivial.\nQed.\n\nLemma upl_conv_1_img :\n forall (p : prec_list) (a : ad) (la ls : prec_list),\n upl_conv_1 p = prec_cons a la ls ->\n exists a0 : ad,\n   (exists la0 : prec_list,\n      (exists ls0 : prec_list, p = prec_cons a0 la0 ls0)).\nProof.\n\tsimple induction p. intros. split with a. split with p0. split with p1.\n\ttrivial. intros. inversion H.\nQed.\n\nLemma upl_conv_1_img_0 :\n forall (p : prec_list) (a : ad) (la ls : prec_list),\n upl_conv_1 p = prec_cons a la ls ->\n exists a0 : ad,\n   (exists la0 : prec_list,\n      (exists ls0 : prec_list,\n         p = prec_cons a0 la0 ls0 /\\\n         a = uad_conv_1 a0 /\\ la = upl_conv_1 la0 /\\ ls = upl_conv_1 ls0)).\nProof.\n\tintros. cut\n  (exists a0 : ad,\n     (exists la0 : prec_list,\n        (exists ls0 : prec_list, p = prec_cons a0 la0 ls0))).\n\tintros. elim H0. intros. elim H1. intros. elim H2. intros.\n\trewrite H3 in H. split with x. split with x0. split with x1.\n\tsplit. assumption. split. inversion H. trivial. split.\n\tinversion H; trivial. inversion H. trivial.\n\texact (upl_conv_1_img p a la ls H).\nQed.\n\nLemma upl_conv_1_img_1 :\n forall p : prec_list, upl_conv_1 p = prec_empty -> p = prec_empty.\nProof.\n\tsimple induction p. intros. inversion H1. intros. trivial.\nQed.\n\n(* invariants sur les MapGet pour conv_0 *)\n\nLemma u_conv_0_invar_0 :\n forall (d : preDTA) (a : ad) (ladj : state),\n MapGet state d a = Some ladj ->\n MapGet state (udta_conv_0 d) (uad_conv_0 a) = Some (umpl_conv_0 ladj).\nProof.\n\tsimple induction d. intros. simpl in H. inversion H. intros.\n\tunfold udta_conv_0 in |- *. unfold udta_conv_0_aux in |- *. cut (a = a1).\n\tintro. rewrite H0. rewrite H0 in H. induction  a1 as [| p]. simpl in |- *.\n\tsimpl in H. inversion H. trivial. simpl in |- *. simpl in H.\n\tcut (Peqb p p = true). intro. rewrite H1 in H. rewrite H1.\n\tinversion H. trivial. exact (aux_Neqb_1_0 p). intros. \n\tcut (Neqb a a1 = true). intro. exact (Neqb_complete a a1 H0).\n\tcut (Neqb a a1 = true \\/ Neqb a a1 = false). intros. elim H0.\n\tintros. assumption. intro. \n\tcut (MapGet state (M1 state a a0) a1 = None).\n\tintro. rewrite H2 in H. inversion H.\n\texact (M1_semantics_2 state a a1 a0 H1).\n\texact (bool_is_true_or_false (Neqb a a1)).\n\tintro. intro. intro. intro. simple induction a. exact (H N0).\n\tsimple induction p. intros. simpl in |- *. simpl in H2. \n\texact (H0 (Npos p0) ladj H2). intros. simpl in |- *. simpl in H2.\n\texact (H (Npos p0) ladj H2). intros. simpl in H1. simpl in |- *.\n\texact (H0 N0 ladj H1).\nQed.\n\nLemma u_conv_0_invar_1 :\n forall (s : state) (c : ad) (p : prec_list),\n MapGet prec_list s c = Some p ->\n MapGet prec_list (umpl_conv_0 s) c = Some (upl_conv_0 p).\nProof.\n\tsimple induction s. intros. simpl in H. inversion H. intros.\n\tsimpl in |- *. simpl in H. cut (Neqb a c = true). intro.\n\trewrite H0 in H. rewrite H0. inversion H. trivial.\n\tcut (Neqb a c = true \\/ Neqb a c = false). intro. \n\telim H0; intros. assumption. rewrite H1 in H.\n\tinversion H. exact (bool_is_true_or_false (Neqb a c)).\n\tintro. intro. intro. intro. simple induction c. simpl in |- *. intros.\n\texact (H N0 p H1). simple induction p. intros. simpl in H2.\n\tsimpl in |- *. exact (H0 (Npos p0) p1 H2). intros. simpl in |- *.\n\tsimpl in H2. exact (H (Npos p0) p1 H2).\n\tintros. simpl in |- *. simpl in H1. exact (H0 N0 p0 H1).\nQed.\n\nLemma u_conv_0_invar_2 :\n forall (d : preDTA) (a : ad) (ladj : state),\n MapGet state (udta_conv_0 d) (uad_conv_0 a) = Some (umpl_conv_0 ladj) ->\n MapGet state d a = Some ladj.\nProof.\n\tsimple induction d. simple induction a. intros. inversion H. simple induction p.\n\tintros. inversion H0. intros. simpl in H0. inversion H0.\n\tintros. inversion H. simple induction a; intro. simple induction a1. simpl in |- *.\n\tintros. simpl in H. inversion H. cut (a0 = ladj). intros. rewrite H0.\n\ttrivial. exact (umpl_conv_0_inj a0 ladj H1). simple induction p. intros.\n\tsimpl in H0. inversion H0. intros. inversion H0. intros. inversion H.\n\tintro. simple induction a1. intros. inversion H. intros. induction  p as [p Hrecp| p Hrecp| ].\n\tinduction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in H. simpl in |- *.\n\tcut (Peqb p p0 = true \\/ Peqb p p0 = false). intro. elim H0; intros.\n\trewrite H1. rewrite H1 in H. inversion H. cut (a0 = ladj). intro. rewrite H2.\n\ttrivial.  exact (umpl_conv_0_inj a0 ladj H3). rewrite H1. rewrite H1 in H.\n\tinversion H. exact (bool_is_true_or_false (Peqb p p0)).\n\tinversion H. inversion H. simpl in H. simpl in |- *.\n\tcut (Peqb (xO p) p0 = true \\/ Peqb (xO p) p0 = false). intro.\n\telim H0; intros. rewrite H1. rewrite H1 in H. inversion H. cut (a0 = ladj).\n\tintro. rewrite H2. trivial. exact (umpl_conv_0_inj a0 ladj H3).\n\trewrite H1 in H. inversion H. \n\texact (bool_is_true_or_false (Peqb (xO p) p0)). simpl in |- *. simpl in H. \n\tcut (Peqb 1 p0 = true \\/ Peqb 1 p0 = false). intro. elim H0; intros.\n\trewrite H1 in H. rewrite H1. inversion H. cut (a0 = ladj). intros. rewrite H2.\n\ttrivial. exact (umpl_conv_0_inj a0 ladj H3). rewrite H1 in H. inversion H.\n\texact (bool_is_true_or_false (Peqb 1 p0)). intros. induction  a as [| p].\n\tsimpl in H1. unfold udta_conv_0 in H. simpl in |- *. apply (H N0 ladj).\n\tsimpl in |- *. trivial. induction  p as [p Hrecp| p Hrecp| ]. simpl in |- *. unfold udta_conv_0 in H0.\n\tapply (H0 (Npos p) ladj). simpl in |- *. simpl in H1. trivial. simpl in |- *. simpl in H1.\n\tunfold udta_conv_0 in H. exact (H (Npos p) ladj H1). simpl in |- *. simpl in H1.\n\tunfold udta_conv_0 in H0. exact (H0 N0 ladj H1).\nQed.\n\nLemma u_conv_0_invar_3 :\n forall (s : state) (c : ad) (p : prec_list),\n MapGet prec_list (umpl_conv_0 s) c = Some (upl_conv_0 p) ->\n MapGet prec_list s c = Some p.\nProof.\n\tsimple induction s. intros. inversion H. simple induction a. intro.\n\tsimple induction c. simpl in |- *. intros. inversion H. cut (a0 = p). intros. rewrite H0.\n\ttrivial. exact (upl_conv_0_inj a0 p H1). simpl in |- *. intros. inversion H.\n\tintro. intro. simple induction c. simpl in |- *. intros. inversion H. induction  p as [p Hrecp| p Hrecp| ].\n\tsimple induction p0. intros. simpl in H0. \n\tcut (Peqb p p1 = true \\/ Peqb p p1 = false). intros. elim H1; intros.\n\tsimpl in |- *. rewrite H2. rewrite H2 in H0. inversion H0. cut (a0 = p2). intro.\n\trewrite H3. trivial. exact (upl_conv_0_inj a0 p2 H4). simpl in |- *. rewrite H2.\n\trewrite H2 in H0. inversion H0. exact (bool_is_true_or_false (Peqb p p1)).\n\tintros. inversion H0. intros. inversion H. simple induction p0. intros. inversion H0.\n\tintros. simpl in H0. simpl in |- *. cut (Peqb p p1 = true \\/ Peqb p p1 = false).\n\tintros. elim H1; intros. rewrite H2 in H0. rewrite H2. inversion H0.\n\tcut (a0 = p2). intro. rewrite H3. trivial. exact (upl_conv_0_inj a0 p2 H4).\n\trewrite H2. rewrite H2 in H0. inversion H0.\n\texact (bool_is_true_or_false (Peqb p p1)). intros. inversion H.\n\tsimple induction p. intros. inversion H0. intros. inversion H0. intros. simpl in H.\n\tinversion H. cut (a0 = p0). intro. rewrite H0. trivial.\n\texact (upl_conv_0_inj a0 p0 H1). intro. intro. intro. intro. simple induction c.\n\tsimpl in |- *. intros. exact (H N0 p H1). simple induction p. intros. simpl in |- *. simpl in H2.\n\texact (H0 (Npos p0) p1 H2). intros; simpl in |- *. simpl in H2. \n\texact (H (Npos p0) p1 H2). intros; simpl in |- *. simpl in H1. exact (H0 N0 p0 H1).\nQed.\n\nLemma u_conv_0_invar_4 :\n forall (d : preDTA) (a : ad) (ladj : state),\n MapGet state (udta_conv_0 d) (uad_conv_0 a) = Some ladj ->\n exists ladj0 : _, ladj = umpl_conv_0 ladj0.\nProof.\n\tsimple induction d. intros. induction  a as [| p]. simpl in H. inversion H.\n\tinduction  p as [p Hrecp| p Hrecp| ]; simpl in H; inversion H. simple induction a. intro. simple induction a1.\n\tintros. simpl in H. induction  a0 as [| a0 a2| a0_1 Hreca0_1 a0_0 Hreca0_0]. simpl in H. split with (M0 prec_list).\n\tsimpl in |- *. inversion H. trivial. split with (M1 prec_list a0 a2). inversion H.\n\ttrivial. split with (M2 prec_list a0_1 a0_0). inversion H. trivial. simpl in |- *.\n\tintros. inversion H. intro. intro. simple induction a1. simpl in |- *. intros. inversion H.\n\tsimpl in |- *. intros. cut (Peqb p p0 = true \\/ Peqb p p0 = false). intro.\n\telim H0; intros. rewrite H1 in H. inversion H. split with a0. trivial.\n\trewrite H1 in H. inversion H. exact (bool_is_true_or_false (Peqb p p0)).\n\tintro. intro. intro. intro. simple induction a. simpl in |- *. intros. exact (H N0 ladj H1).\n\tsimple induction p. intros. simpl in H2. exact (H0 (Npos p0) ladj H2). intros.\n\tsimpl in H2. exact (H (Npos p0) ladj H2). simpl in |- *. intros. exact (H0 N0 ladj H1).\nQed.\n\nLemma u_conv_0_invar_5 :\n forall (d : preDTA) (a : ad) (ladj : state),\n MapGet state (udta_conv_0 d) (uad_conv_0 a) = Some ladj ->\n exists ladj0 : _,\n   ladj = umpl_conv_0 ladj0 /\\ MapGet state d a = Some ladj0.\nProof.\n\tintros. cut (exists ladj0 : state, ladj = umpl_conv_0 ladj0).\n\tintros. elim H0. intros. split with x. split. assumption. rewrite H1 in H.\n\texact (u_conv_0_invar_2 d a x H). exact (u_conv_0_invar_4 d a ladj H).\nQed.\n\nLemma u_conv_0_invar_6 :\n forall (s : state) (c : ad) (p : prec_list),\n MapGet prec_list (umpl_conv_0 s) c = Some p ->\n exists p0 : prec_list, p = upl_conv_0 p0.\nProof.\n\tsimple induction s. intros. induction  c as [| p0]. inversion H. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]; inversion H.\n\tsimple induction a. intro. simple induction c. intros. simpl in H. inversion H. split with a0.\n\ttrivial. simpl in |- *. intros. inversion H. simple induction p. intro. intro. simple induction c.\n\tsimpl in |- *. intros. inversion H0. simpl in |- *. simple induction p1. intros. simpl in H1.\n\tcut (Peqb p0 p2 = true \\/ Peqb p0 p2 = false). intro. elim H2. intros. \n\trewrite H3 in H1. inversion H1. split with a0. trivial. intro. rewrite H3 in H1.\n\tinversion H1. exact (bool_is_true_or_false (Peqb p0 p2)). intros. inversion H1.\n\tintros. inversion H0. intro. intro. intro. simple induction c. intros. inversion H0.\n\tsimple induction p1. intros. simpl in H1. inversion H1. intros. simpl in H1.\n\tcut (Peqb p0 p2 = true \\/ Peqb p0 p2 = false). intro. elim H2; intro. \n\trewrite H3 in H1. inversion H1. split with a0. trivial. rewrite H3 in H1. inversion H1.\n\texact (bool_is_true_or_false (Peqb p0 p2)). intros. inversion H0. intro.\n\tsimple induction c. intros. inversion H. simple induction p0. intros. inversion H0. intros.\n\tinversion H0. intros. simpl in H. inversion H. split with a0. trivial. intro. intro.\n\tintro. intro. simple induction c. simpl in |- *. intros. simpl in H1. exact (H N0 p H1). simple induction p.\n\tintros. simpl in H2. exact (H0 (Npos p0) p1 H2). intros. simpl in H2. \n\texact (H (Npos p0) p1 H2). simpl in |- *. intros. exact (H0 N0 p0 H1).\nQed.\n\nLemma u_conv_0_invar_7 :\n forall (s : state) (c : ad) (p : prec_list),\n MapGet prec_list (umpl_conv_0 s) c = Some p ->\n exists p0 : prec_list,\n   p = upl_conv_0 p0 /\\ MapGet prec_list s c = Some p0.\nProof.\n\tintros. elim (u_conv_0_invar_6 s c p H). intros. split with x.\n\tintros. split. assumption. rewrite H0 in H. \n\texact (u_conv_0_invar_3 s c x H).\nQed.\n\nLemma u_conv_0_invar_8 :\n forall (p0 : preDTA) (a0 : ad) (s0 : state),\n MapGet state (udta_conv_0 p0) a0 = Some s0 ->\n exists a1 : ad, a0 = uad_conv_0 a1.\nProof.\n\tsimple induction p0. intros. induction  a0 as [| p]. simpl in H. inversion H.\n\tinduction  p as [p Hrecp| p Hrecp| ]; simpl in H; inversion H.\n\tunfold udta_conv_0 in |- *. unfold udta_conv_0_aux in |- *. intros.\n\tinduction  a as [| p]. split with N0. unfold uad_conv_0 in |- *. induction  a1 as [| p].\n\ttrivial. simpl in H. induction  p as [p Hrecp| p Hrecp| ]; inversion H.\n\tsplit with (Npos p). simpl in |- *. induction  a1 as [| p1]. simpl in H.\n\tinversion H. induction  p1 as [p1 Hrecp1| p1 Hrecp1| ]. simpl in H. inversion H.\n\tsimpl in H. cut (Peqb p p1 = true). intro. cut (p1 = p).\n\tintro. rewrite H1. trivial. symmetry  in |- *. \n\texact (aux_Neqb_1_1 p p1 H0).\n\tcut (Peqb p p1 = true \\/ Peqb p p1 = false). intro.\n\telim H0; intros. assumption. rewrite H1 in H. inversion H.\n\texact (bool_is_true_or_false (Peqb p p1)).\n \tsimpl in H. inversion H. unfold udta_conv_0 in |- *. intro. intro.\n\tintro. intro. simple induction a0. intros. split with N0. simpl in |- *.\n\ttrivial. simple induction p. intros. inversion H2. intros.\n\tsplit with (Npos p1). simpl in |- *. trivial. intros. inversion H1.\nQed.\n\n(* invariant de reconnaissance sur conv_0 : sens direct *)\n\nDefinition u_conv_rec_0 (p : preDTA) (a : ad) (t : term)\n  (pr : reconnaissance p a t) :=\n  reconnaissance (udta_conv_0 p) (uad_conv_0 a) t.\n\nDefinition u_conv_str_0 (p : preDTA) (s : state) (t : term)\n  (pr : state_reconnait p s t) :=\n  state_reconnait (udta_conv_0 p) (umpl_conv_0 s) t.\n\nDefinition u_conv_lr_0 (p : preDTA) (p0 : prec_list) \n  (t : term_list) (pr : liste_reconnait p p0 t) :=\n  liste_reconnait (udta_conv_0 p) (upl_conv_0 p0) t.\n\nLemma u_conv0_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 u_conv_str_0 d ladj t s -> u_conv_rec_0 d a t (rec_dta d a t ladj e s).\nProof.\n\tintros. unfold u_conv_rec_0 in |- *. unfold u_conv_str_0 in H.\n\tcut\n  (MapGet state (udta_conv_0 d) (uad_conv_0 a) =\n   Some (umpl_conv_0 ladj)). intros.\n\texact (rec_dta (udta_conv_0 d) (uad_conv_0 a) t (umpl_conv_0 ladj) H0 H). \n\texact (u_conv_0_invar_0 d a ladj e).\nQed.\n\nLemma u_conv0_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 u_conv_lr_0 d l tl l0 ->\n u_conv_str_0 d s (app c tl) (rec_st d s c tl l e l0).\nProof.\n\tintros. unfold u_conv_str_0 in |- *. unfold u_conv_lr_0 in H.\n\tcut (MapGet prec_list (umpl_conv_0 s) c = Some (upl_conv_0 l)). intros.\n\texact (rec_st (udta_conv_0 d) (umpl_conv_0 s) c tl (upl_conv_0 l) H0 H).\n\texact (u_conv_0_invar_1 s c l e).\nQed.\n\nLemma u_conv0_2 :\n forall d : preDTA, u_conv_lr_0 d prec_empty tnil (rec_empty d).\nProof.\n\tintros. unfold u_conv_lr_0 in |- *. simpl in |- *.\n\texact (rec_empty (udta_conv_0 d)).\nQed.\n\nLemma u_conv0_3 :\n forall (d : preDTA) (a : ad) (la ls : prec_list) (hd : term)\n   (tl : term_list) (r : reconnaissance d a hd),\n u_conv_rec_0 d a hd r ->\n forall l : liste_reconnait d la tl,\n u_conv_lr_0 d la tl l ->\n u_conv_lr_0 d (prec_cons a la ls) (tcons hd tl)\n   (rec_consi d a la ls hd tl r l).\nProof.\n\tintros. unfold u_conv_lr_0 in |- *. unfold u_conv_rec_0 in H. \n\tunfold u_conv_lr_0 in H0. simpl in |- *.\n\texact\n  (rec_consi (udta_conv_0 d) (uad_conv_0 a) (upl_conv_0 la) \n     (upl_conv_0 ls) hd tl H H0).\nQed.\n\nLemma u_conv0_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 u_conv_lr_0 d ls (tcons hd tl) l ->\n u_conv_lr_0 d (prec_cons a la ls) (tcons hd tl)\n   (rec_consn d a la ls hd tl l).\nProof.\n\tintros. unfold u_conv_lr_0 in |- *. simpl in |- *. unfold u_conv_lr_0 in H.\n\texact\n  (rec_consn (udta_conv_0 d) (uad_conv_0 a) (upl_conv_0 la) \n     (upl_conv_0 ls) hd tl H).  \nQed.\n\nLemma u_conv0_5 :\n forall (p : preDTA) (a : ad) (t : term) (r : reconnaissance p a t),\n u_conv_rec_0 p a t r.\nProof.\n\texact\n  (mreconnaissance_ind u_conv_rec_0 u_conv_str_0 u_conv_lr_0 u_conv0_0\n     u_conv0_1 u_conv0_2 u_conv0_3 u_conv0_4).\nQed.\n\nLemma u_conv0 :\n forall (p : preDTA) (a : ad) (t : term),\n reconnaissance p a t -> reconnaissance (udta_conv_0 p) (uad_conv_0 a) t.\nProof.\n\tintros. exact (u_conv0_5 p a t H).\nQed.\n\n(* invariant de reconnaissance sur conv_0 : sens reciproque *)\n\nDefinition u_conv_rec_0_r (p0 : preDTA) (a0 : ad) (t : term)\n  (pr0 : reconnaissance p0 a0 t) :=\n  forall (p : preDTA) (a : ad),\n  p0 = udta_conv_0 p -> a0 = uad_conv_0 a -> reconnaissance p a t.\n\nDefinition u_conv_str_0_r (p0 : preDTA) (s0 : state) \n  (t : term) (pr : state_reconnait p0 s0 t) :=\n  forall (p : preDTA) (s : state),\n  p0 = udta_conv_0 p -> s0 = umpl_conv_0 s -> state_reconnait p s t.\n\nDefinition u_conv_lr_0_r (p0 : preDTA) (pl0 : prec_list) \n  (t : term_list) (pr : liste_reconnait p0 pl0 t) :=\n  forall (p : preDTA) (pl : prec_list),\n  p0 = udta_conv_0 p -> pl0 = upl_conv_0 pl -> liste_reconnait p pl t.\n\nLemma u_conv0_0r :\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 u_conv_str_0_r d ladj t s -> u_conv_rec_0_r d a t (rec_dta d a t ladj e s).\nProof.\n\tintros. unfold u_conv_str_0_r in H. unfold u_conv_rec_0_r in |- *.\n\tintros. rewrite H0 in e. rewrite H1 in e. \n\telim (u_conv_0_invar_5 p a0 ladj e). intros. elim H2. intros.\n\tapply (rec_dta p a0 t x H4). apply (H p x). exact H0. exact H3.\nQed.\n\nLemma u_conv0_1r :\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 u_conv_lr_0_r d l tl l0 ->\n u_conv_str_0_r d s (app c tl) (rec_st d s c tl l e l0).\nProof.\n\tintros. unfold u_conv_lr_0_r in H. unfold u_conv_str_0_r in |- *. intros.\n\trewrite H1 in e. elim (u_conv_0_invar_7 s0 c l e). intros. elim H2.\n\tintros. apply (rec_st p s0 c tl x H4). exact (H p x H0 H3).\nQed.\n\nLemma u_conv0_2r :\n forall d : preDTA, u_conv_lr_0_r d prec_empty tnil (rec_empty d).\nProof.\n\tintros. unfold u_conv_lr_0_r in |- *. intros. cut (pl = prec_empty). intros.\n\trewrite H1. exact (rec_empty p). cut (upl_conv_0 prec_empty = prec_empty).\n\tintros. rewrite <- H1 in H0. symmetry  in |- *. \n\texact (upl_conv_0_inj prec_empty pl H0). simpl in |- *. trivial.\nQed.\n\nLemma u_conv0_3r :\n forall (d : preDTA) (a : ad) (la ls : prec_list) (hd : term)\n   (tl : term_list) (r : reconnaissance d a hd),\n u_conv_rec_0_r d a hd r ->\n forall l : liste_reconnait d la tl,\n u_conv_lr_0_r d la tl l ->\n u_conv_lr_0_r d (prec_cons a la ls) (tcons hd tl)\n   (rec_consi d a la ls hd tl r l).\nProof.\n\tintros. unfold u_conv_lr_0_r in |- *. unfold u_conv_rec_0_r in H.\n\tunfold u_conv_lr_0_r in H0. intros. cut (upl_conv_0 pl = prec_cons a la ls).\n\tintro. cut\n  (exists a0 : ad,\n     (exists la0 : prec_list,\n        (exists ls0 : prec_list,\n           pl = prec_cons a0 la0 ls0 /\\\n           a = uad_conv_0 a0 /\\ la = upl_conv_0 la0 /\\ ls = upl_conv_0 ls0))).\n\tintro. elim H4. intros. elim H5. intros. elim H6. intros. elim H7.\n\tintros. elim H9. intros. elim H11. intros. rewrite H8. \t\n\tapply (rec_consi p x x0 x1 hd tl). apply (H p x). exact H1. trivial.\n\texact (H0 p x0 H1 H12). exact (upl_conv_0_img_0 pl a la ls H3).\n\tsymmetry  in |- *. trivial.\nQed.\n\nLemma u_conv0_4r :\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 u_conv_lr_0_r d ls (tcons hd tl) l ->\n u_conv_lr_0_r d (prec_cons a la ls) (tcons hd tl)\n   (rec_consn d a la ls hd tl l).\nProof.\n\tintros. unfold u_conv_lr_0_r in H. unfold u_conv_lr_0_r in |- *. intros.\n\tcut (upl_conv_0 pl = prec_cons a la ls). cut\n  (exists a0 : ad,\n     (exists la0 : prec_list,\n        (exists ls0 : prec_list,\n           pl = prec_cons a0 la0 ls0 /\\\n           a = uad_conv_0 a0 /\\ la = upl_conv_0 la0 /\\ ls = upl_conv_0 ls0))).\n\tintros. elim H2. intros. elim H4. intros. elim H5. intros. elim H6.\n\tintros. elim H8. intros. elim H10. intros. rewrite H7.\n\texact (rec_consn p x x0 x1 hd tl (H p x1 H0 H12)).\n\tcut (upl_conv_0 pl = prec_cons a la ls). intro.\n\texact (upl_conv_0_img_0 pl a la ls H2). symmetry  in |- *. trivial. symmetry  in |- *.\n\ttrivial.\nQed.\n\nLemma u_conv0_5r :\n forall (p : preDTA) (a : ad) (t : term) (r : reconnaissance p a t),\n u_conv_rec_0_r p a t r.\nProof.\n\texact\n  (mreconnaissance_ind u_conv_rec_0_r u_conv_str_0_r u_conv_lr_0_r u_conv0_0r\n     u_conv0_1r u_conv0_2r u_conv0_3r u_conv0_4r).\nQed.\n\nLemma u_conv0_r :\n forall (p : preDTA) (a : ad) (t : term),\n reconnaissance (udta_conv_0 p) (uad_conv_0 a) t -> reconnaissance p a t.\nProof.\n\tintros. apply (u_conv0_5r (udta_conv_0 p) (uad_conv_0 a) t H p a). trivial. trivial.\nQed.\n\n(* invariants sur les MapGet : conv_1 *)\n\nLemma u_conv_1_invar_0 :\n forall (d : preDTA) (a : ad) (ladj : state),\n MapGet state d a = Some ladj ->\n MapGet state (udta_conv_1 d) (uad_conv_1 a) = Some (umpl_conv_1 ladj).\nProof.\n\tsimple induction d. intros. simpl in H. inversion H. intros. \n\tunfold udta_conv_1 in |- *. cut (a = a1). intro. rewrite H0. rewrite H0 in H.\n\tinduction  a1 as [| p]. simpl in |- *. simpl in H. inversion H. inversion H. trivial.\n\tsimpl in |- *. simpl in H. cut (Peqb p p = true). intro. rewrite H1. simpl in H.\n\trewrite H1 in H. inversion H. trivial. exact (aux_Neqb_1_0 p).\n \tcut (Neqb a a1 = true \\/ Neqb a a1 = false). intros. elim H0. intros.\n\texact (Neqb_complete a a1 H1). intro. \n\tcut (MapGet state (M1 state a a0) a1 = None).\n\tintro. rewrite H2 in H. inversion H.\n\texact (M1_semantics_2 state a a1 a0 H1).\n\texact (bool_is_true_or_false (Neqb a a1)).\n\tintro. intro. intro. intro. simple induction a. simpl in |- *. intros. \n\texact (H N0 ladj H1). simple induction p. intros. simpl in |- *. simpl in H2.\n\texact (H0 (Npos p0) ladj H2). intros. simpl in |- *. simpl in H2.\n\texact (H (Npos p0) ladj H2). intros. simpl in |- *. simpl in H1.\n\texact (H0 N0 ladj H1).\nQed.\n\nLemma u_conv_1_invar_1 :\n forall (s : state) (c : ad) (p : prec_list),\n MapGet prec_list s c = Some p ->\n MapGet prec_list (umpl_conv_1 s) c = Some (upl_conv_1 p).\nProof.\n\tsimple induction s. simpl in |- *. intros. inversion H.\n\tintros. simpl in H. simpl in |- *. cut (Neqb a c = true). intro.\n\trewrite H0 in H. rewrite H0. inversion H. trivial.\n\tcut (Neqb a c = true \\/ Neqb a c = false). intros.\n\telim H0; intros. assumption. rewrite H1 in H. inversion H.\n\texact (bool_is_true_or_false (Neqb a c)).\n\tintro. intro. intro. intro. simple induction c. simpl in |- *. intros.\n\texact (H N0 p H1). simple induction p. intros. simpl in H2.\n\tsimpl in |- *. exact (H0 (Npos p0) p1 H2). intros. simpl in |- *. \n\tsimpl in H2. exact (H (Npos p0) p1 H2).\n\tintros. simpl in |- *. simpl in H1. exact (H0 N0 p0 H1).\nQed.\n\nLemma u_conv_1_invar_2 :\n forall (d : preDTA) (a : ad) (ladj : state),\n MapGet state (udta_conv_1 d) (uad_conv_1 a) = Some (umpl_conv_1 ladj) ->\n MapGet state d a = Some ladj.\nProof.\n\tsimple induction d. intros. induction  a as [| p]. simpl in H. inversion H.\n\tinduction  p as [p Hrecp| p Hrecp| ]; inversion H. simple induction a. intro. simple induction a1. simpl in |- *.\n\tintros. inversion H. cut (a0 = ladj). intro. rewrite H0. trivial.\n\texact (umpl_conv_1_inj a0 ladj H1). simpl in |- *. intros. inversion H.\n\tsimple induction p. intro. intro. intro. simple induction a1. intros. simpl in H0.\n\tinversion H0. simple induction p1. intros. simpl in H1. simpl in |- *.\n\tcut (Peqb p0 p2 = true \\/ Peqb p0 p2 = false). intros. elim H2; intros.\n\trewrite H3 in H1. rewrite H3. inversion H1. cut (a0 = ladj). intro. rewrite H4.\n\ttrivial. exact (umpl_conv_1_inj a0 ladj H5). rewrite H3 in H1. inversion H1.\n\texact (bool_is_true_or_false (Peqb p0 p2)). intros. simpl in H1. \n\tinversion H1. intros. inversion H0. intros. induction  a1 as [| p1]. simpl in |- *. simpl in H0.\n\tinversion H0. induction  p1 as [p1 Hrecp1| p1 Hrecp1| ]. inversion H0. simpl in |- *. simpl in H0.\n\tcut (Peqb p0 p1 = true \\/ Peqb p0 p1 = false). intro. elim H1; intros.\n\trewrite H2. rewrite H2 in H0. inversion H0. cut (a0 = ladj). intro. rewrite H3.\n\ttrivial. exact (umpl_conv_1_inj a0 ladj H4). rewrite H2 in H0.\n\tinversion H0. exact (bool_is_true_or_false (Peqb p0 p1)).\n\tinversion H0. intros. induction  a1 as [| p0]. inversion H. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. inversion H.\n\tinversion H. simpl in H. inversion H. cut (a0 = ladj). intro. rewrite H0.\n\ttrivial. exact (umpl_conv_1_inj a0 ladj H1). intro. intro. intro. intro.\n\tsimple induction a. simpl in |- *. intros. exact (H N0 ladj H1). simple induction p. intros.\n\tsimpl in |- *. simpl in H2. exact (H0 (Npos p0) ladj H2). intros. simpl in |- *. simpl in H2.\n\texact (H (Npos p0) ladj H2). intros. simpl in |- *. simpl in H1. \n\texact (H0 N0 ladj H1).\nQed.\n\nLemma u_conv_1_invar_3 :\n forall (s : state) (c : ad) (p : prec_list),\n MapGet prec_list (umpl_conv_1 s) c = Some (upl_conv_1 p) ->\n MapGet prec_list s c = Some p.\nProof.\n\tsimple induction s. simpl in |- *. intros. inversion H. simple induction a. intro. simple induction c.\n\tsimpl in |- *. intros; inversion H. cut (a0 = p). intro. rewrite H0. trivial.\n\texact (upl_conv_1_inj a0 p H1). simpl in |- *. intros. inversion H. intro. intro.\n\tsimple induction c. simpl in |- *. intros. inversion H. induction  p as [p Hrecp| p Hrecp| ]. simple induction p0. intros.\n\tsimpl in |- *. simpl in H0. cut (Peqb p p1 = true \\/ Peqb p p1 = false). intro.\n\telim H1; intros. rewrite H2. rewrite H2 in H0. inversion H0. cut (a0 = p2). intro.\n\trewrite H3. trivial. exact (upl_conv_1_inj a0 p2 H4). rewrite H2. \n\trewrite H2 in H0. inversion H0. exact (bool_is_true_or_false (Peqb p p1)).\n\tintros. inversion H0. intros. inversion H. simple induction p0. intros. inversion H0.\n\tintros. simpl in |- *. simpl in H0. cut (Peqb p p1 = true \\/ Peqb p p1 = false).\n\tintro. elim H1; intros. rewrite H2 in H0. rewrite H2. inversion H0. cut (a0 = p2).\n\tintro. rewrite H3. trivial. exact (upl_conv_1_inj a0 p2 H4). rewrite H2 in H0.\n\tinversion H0. exact (bool_is_true_or_false (Peqb p p1)). intros. inversion H.\n\tintros. induction  p as [p Hrecp| p Hrecp| ]. inversion H. inversion H. simpl in H. inversion H. cut (a0 = p0).\n\tintro. rewrite H0. trivial. exact (upl_conv_1_inj a0 p0 H1). intro. intro. intro.\n\tintro. simple induction c. simpl in |- *. intros. exact (H N0 p H1). simple induction p. intros.\n\tsimpl in |- *. simpl in H2. exact (H0 (Npos p0) p1 H2). intros. simpl in |- *. simpl in H2.\n\texact (H (Npos p0) p1 H2). intros. simpl in |- *. simpl in H1. exact (H0 N0 p0 H1).\nQed.\n\nLemma u_conv_1_invar_4 :\n forall (d : preDTA) (a : ad) (ladj : state),\n MapGet state (udta_conv_1 d) (uad_conv_1 a) = Some ladj ->\n exists ladj0 : _, ladj = umpl_conv_1 ladj0.\nProof.\n\tsimple induction d. simple induction a. intros. inversion H. simple induction p; intros. inversion H0.\n\tinversion H0. inversion H. simple induction a. intro. simple induction a1. intros. simpl in H.\n\tinversion H. split with a0. trivial. simpl in |- *. intros. inversion H. intro. intro.\n\tsimple induction a1. simpl in |- *. intros. inversion H. induction  p as [p Hrecp| p Hrecp| ]. simple induction p0. intros. \n\tsimpl in H0. elim (bool_is_true_or_false (Peqb p p1)); intro; rewrite H1 in H0.\n\tinversion H0. split with a0. trivial. inversion H0. intros. inversion H0. intros.\n\tinversion H. simple induction p0. intros. inversion H0. intros. simpl in H0.\n\telim (bool_is_true_or_false (Peqb p p1)); intros; rewrite H1 in H0. inversion H0.\n\tsplit with a0. trivial. inversion H0. intros. inversion H. simple induction p. intros.\n\tinversion H0. intros. inversion H0. intros. inversion H. split with a0. trivial.\n\tintro. intro. intro. intro. simple induction a. intros. simpl in H1. exact (H N0 ladj H1).\n\tsimple induction p. intros. simpl in H2. exact (H0 (Npos p0) ladj H2). intros. simpl in H2.\n\texact (H (Npos p0) ladj H2). intros. simpl in H1. exact (H0 N0 ladj H1).\nQed.\n\nLemma u_conv_1_invar_5 :\n forall (d : preDTA) (a : ad) (ladj : state),\n MapGet state (udta_conv_1 d) (uad_conv_1 a) = Some ladj ->\n exists ladj0 : _,\n   ladj = umpl_conv_1 ladj0 /\\ MapGet state d a = Some ladj0.\nProof.\n\tintros. cut (exists ladj0 : state, ladj = umpl_conv_1 ladj0).\n\tintros. elim H0. intros. split with x. split. assumption. rewrite H1 in H.\n\texact (u_conv_1_invar_2 d a x H). exact (u_conv_1_invar_4 d a ladj H).\nQed.\n\nLemma u_conv_1_invar_6 :\n forall (s : state) (c : ad) (p : prec_list),\n MapGet prec_list (umpl_conv_1 s) c = Some p ->\n exists p0 : prec_list, p = upl_conv_1 p0.\nProof.\n\tsimple induction s. simple induction c. intros. inversion H. simple induction p. intros.\n\tinversion H0. intros. inversion H0. intros. inversion H. simple induction a.\n\tintro. simple induction c. simpl in |- *. intros. inversion H. split with a0. trivial.\n\tsimpl in |- *. intros. inversion H. intro. intro. simple induction c. simpl in |- *. intros.\n\tinversion H. induction  p as [p Hrecp| p Hrecp| ]. simple induction p0. intros. simpl in H0.\n\telim (bool_is_true_or_false (Peqb p p1)); intro; rewrite H1 in H0.\n\tinversion H0. split with a0. trivial. inversion H0. intros. inversion H0.\n\tintros. inversion H. simple induction p0. intros. inversion H0. intros. simpl in H0.\n\telim (bool_is_true_or_false (Peqb p p1)); intro; rewrite H1 in H0.\n\tinversion H0. split with a0. trivial. inversion H0. simpl in |- *. intros. inversion H.\n\tsimple induction p. intros. inversion H0. intros. inversion H0. intros. simpl in H.\n\tinversion H. split with a0. trivial. intro. intro. intro. intro. simple induction c.\n\tsimpl in |- *. intros. exact (H N0 p H1). simple induction p; intros. simpl in H2.\n\texact (H0 (Npos p0) p1 H2). simpl in H2. exact (H (Npos p0) p1 H2).\n\tsimpl in H1. exact (H0 N0 p0 H1).\nQed.\n\nLemma u_conv_1_invar_7 :\n forall (s : state) (c : ad) (p : prec_list),\n MapGet prec_list (umpl_conv_1 s) c = Some p ->\n exists p0 : prec_list,\n   p = upl_conv_1 p0 /\\ MapGet prec_list s c = Some p0.\nProof.\n\tintros. elim (u_conv_1_invar_6 s c p H). intros. split with x.\n\tintros. split. assumption. rewrite H0 in H. \n\texact (u_conv_1_invar_3 s c x H).\nQed.\n\nLemma u_conv_1_invar_8 :\n forall (p0 : preDTA) (a0 : ad) (s0 : state),\n MapGet state (udta_conv_1 p0) a0 = Some s0 ->\n exists a1 : ad, a0 = uad_conv_1 a1.\nProof.\n\tsimple induction p0. intros. simpl in H. induction  a0 as [| p]. inversion H.\n\tinduction  p as [p Hrecp| p Hrecp| ]; inversion H. unfold udta_conv_1 in |- *. \n\tunfold udta_conv_1_aux in |- *. intro. intro. simple induction a1. intros.\n\tsimpl in H. inversion H. simple induction p. intros.\n\tsplit with (Npos p1). simpl in |- *. trivial. intros. simpl in H0.\n\tinversion H0. intros. simpl in H. split with N0. simpl in |- *.\n\ttrivial.  intro. intro. intro. intro. simple induction a0.\n\tsimpl in |- *. intros. inversion H1. simple induction p. intros.\n\tsplit with (Npos p1). simpl in |- *. trivial. intros. simpl in H2.\n\tinversion H2. intros. split with N0. simpl in |- *. trivial.\nQed.\n\n(* invariant de reconnaissance de conv_1 *)\n\nDefinition u_conv_rec_1 (p : preDTA) (a : ad) (t : term)\n  (pr : reconnaissance p a t) :=\n  reconnaissance (udta_conv_1 p) (uad_conv_1 a) t.\n\nDefinition u_conv_str_1 (p : preDTA) (s : state) (t : term)\n  (pr : state_reconnait p s t) :=\n  state_reconnait (udta_conv_1 p) (umpl_conv_1 s) t.\n\nDefinition u_conv_lr_1 (p : preDTA) (p0 : prec_list) \n  (t : term_list) (pr : liste_reconnait p p0 t) :=\n  liste_reconnait (udta_conv_1 p) (upl_conv_1 p0) t.\n\nLemma u_conv1_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 u_conv_str_1 d ladj t s -> u_conv_rec_1 d a t (rec_dta d a t ladj e s).\nProof.\n\tintros. unfold u_conv_rec_1 in |- *. unfold u_conv_str_1 in H.\n\tcut\n  (MapGet state (udta_conv_1 d) (uad_conv_1 a) =\n   Some (umpl_conv_1 ladj)). intros.\n\texact (rec_dta (udta_conv_1 d) (uad_conv_1 a) t (umpl_conv_1 ladj) H0 H).\n\texact (u_conv_1_invar_0 d a ladj e).\nQed.\n\nLemma u_conv1_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 u_conv_lr_1 d l tl l0 ->\n u_conv_str_1 d s (app c tl) (rec_st d s c tl l e l0).\nProof.\n\tintros. unfold u_conv_lr_1 in H. unfold u_conv_str_1 in |- *.\n\tcut (MapGet prec_list (umpl_conv_1 s) c = Some (upl_conv_1 l)). intros.\n\texact (rec_st (udta_conv_1 d) (umpl_conv_1 s) c tl (upl_conv_1 l) H0 H).\n\texact (u_conv_1_invar_1 s c l e).\nQed.\n\nLemma u_conv1_2 :\n forall d : preDTA, u_conv_lr_1 d prec_empty tnil (rec_empty d).\nProof.\n\tintros. unfold u_conv_lr_1 in |- *. simpl in |- *.\n\texact (rec_empty (udta_conv_1 d)).\nQed.\n\nLemma u_conv1_3 :\n forall (d : preDTA) (a : ad) (la ls : prec_list) (hd : term)\n   (tl : term_list) (r : reconnaissance d a hd),\n u_conv_rec_1 d a hd r ->\n forall l : liste_reconnait d la tl,\n u_conv_lr_1 d la tl l ->\n u_conv_lr_1 d (prec_cons a la ls) (tcons hd tl)\n   (rec_consi d a la ls hd tl r l).\nProof.\n\tintros. unfold u_conv_lr_1 in |- *. unfold u_conv_lr_1 in H0.\n\tunfold u_conv_rec_1 in H. simpl in |- *.\n\texact\n  (rec_consi (udta_conv_1 d) (uad_conv_1 a) (upl_conv_1 la) \n     (upl_conv_1 ls) hd tl H H0).\nQed.\n\nLemma u_conv1_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 u_conv_lr_1 d ls (tcons hd tl) l ->\n u_conv_lr_1 d (prec_cons a la ls) (tcons hd tl)\n   (rec_consn d a la ls hd tl l).\nProof.\n\tintros. unfold u_conv_lr_1 in |- *. unfold u_conv_lr_1 in H. simpl in |- *.\n\texact\n  (rec_consn (udta_conv_1 d) (uad_conv_1 a) (upl_conv_1 la) \n     (upl_conv_1 ls) hd tl H).\nQed.\n\nLemma u_conv1_5 :\n forall (p : preDTA) (a : ad) (t : term) (r : reconnaissance p a t),\n u_conv_rec_1 p a t r.\nProof.\n\texact\n  (mreconnaissance_ind u_conv_rec_1 u_conv_str_1 u_conv_lr_1 u_conv1_0\n     u_conv1_1 u_conv1_2 u_conv1_3 u_conv1_4).\nQed.\n\nLemma u_conv1 :\n forall (p : preDTA) (a : ad) (t : term),\n reconnaissance p a t -> reconnaissance (udta_conv_1 p) (uad_conv_1 a) t.\nProof.\n\tintros. exact (u_conv1_5 p a t H).\nQed.\n\n(* invariant de reconnaissance sur conv_1 : sens reciproque *)\n\nDefinition u_conv_rec_1_r (p0 : preDTA) (a0 : ad) (t : term)\n  (pr0 : reconnaissance p0 a0 t) :=\n  forall (p : preDTA) (a : ad),\n  p0 = udta_conv_1 p -> a0 = uad_conv_1 a -> reconnaissance p a t.\n\nDefinition u_conv_str_1_r (p0 : preDTA) (s0 : state) \n  (t : term) (pr : state_reconnait p0 s0 t) :=\n  forall (p : preDTA) (s : state),\n  p0 = udta_conv_1 p -> s0 = umpl_conv_1 s -> state_reconnait p s t.\n\nDefinition u_conv_lr_1_r (p0 : preDTA) (pl0 : prec_list) \n  (t : term_list) (pr : liste_reconnait p0 pl0 t) :=\n  forall (p : preDTA) (pl : prec_list),\n  p0 = udta_conv_1 p -> pl0 = upl_conv_1 pl -> liste_reconnait p pl t.\n\nLemma u_conv1_0r :\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 u_conv_str_1_r d ladj t s -> u_conv_rec_1_r d a t (rec_dta d a t ladj e s).\nProof.\n\tintros. unfold u_conv_str_1_r in H. unfold u_conv_rec_1_r in |- *.\n\tintros. rewrite H0 in e. rewrite H1 in e. \n\telim (u_conv_1_invar_5 p a0 ladj e). intros. elim H2. intros.\n\tapply (rec_dta p a0 t x H4). apply (H p x). exact H0. exact H3.\nQed.\n\nLemma u_conv1_1r :\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 u_conv_lr_1_r d l tl l0 ->\n u_conv_str_1_r d s (app c tl) (rec_st d s c tl l e l0).\nProof.\n\tintros. unfold u_conv_lr_1_r in H. unfold u_conv_str_1_r in |- *. intros.\n\trewrite H1 in e. elim (u_conv_1_invar_7 s0 c l e). intros. elim H2.\n\tintros. apply (rec_st p s0 c tl x H4). exact (H p x H0 H3).\nQed.\n\nLemma u_conv1_2r :\n forall d : preDTA, u_conv_lr_1_r d prec_empty tnil (rec_empty d).\nProof.\n\tintros. unfold u_conv_lr_1_r in |- *. intros. cut (pl = prec_empty). intros.\n\trewrite H1. exact (rec_empty p). cut (upl_conv_1 prec_empty = prec_empty).\n\tintros. rewrite <- H1 in H0. symmetry  in |- *. \n\texact (upl_conv_1_inj prec_empty pl H0). simpl in |- *. trivial.\nQed.\n\nLemma u_conv1_3r :\n forall (d : preDTA) (a : ad) (la ls : prec_list) (hd : term)\n   (tl : term_list) (r : reconnaissance d a hd),\n u_conv_rec_1_r d a hd r ->\n forall l : liste_reconnait d la tl,\n u_conv_lr_1_r d la tl l ->\n u_conv_lr_1_r d (prec_cons a la ls) (tcons hd tl)\n   (rec_consi d a la ls hd tl r l).\nProof.\n\tintros. unfold u_conv_lr_1_r in |- *. unfold u_conv_rec_1_r in H.\n\tunfold u_conv_lr_1_r in H0. intros. cut (upl_conv_1 pl = prec_cons a la ls).\n\tintro. cut\n  (exists a0 : ad,\n     (exists la0 : prec_list,\n        (exists ls0 : prec_list,\n           pl = prec_cons a0 la0 ls0 /\\\n           a = uad_conv_1 a0 /\\ la = upl_conv_1 la0 /\\ ls = upl_conv_1 ls0))).\n\tintro. elim H4. intros. elim H5. intros. elim H6. intros. elim H7.\n\tintros. elim H9. intros. elim H11. intros. rewrite H8. \t\n\tapply (rec_consi p x x0 x1 hd tl). apply (H p x). exact H1. trivial.\n\texact (H0 p x0 H1 H12). exact (upl_conv_1_img_0 pl a la ls H3).\n\tsymmetry  in |- *. trivial.\nQed.\n\nLemma u_conv1_4r :\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 u_conv_lr_1_r d ls (tcons hd tl) l ->\n u_conv_lr_1_r d (prec_cons a la ls) (tcons hd tl)\n   (rec_consn d a la ls hd tl l).\nProof.\n\tintros. unfold u_conv_lr_1_r in H. unfold u_conv_lr_1_r in |- *. intros.\n\tcut (upl_conv_1 pl = prec_cons a la ls). cut\n  (exists a0 : ad,\n     (exists la0 : prec_list,\n        (exists ls0 : prec_list,\n           pl = prec_cons a0 la0 ls0 /\\\n           a = uad_conv_1 a0 /\\ la = upl_conv_1 la0 /\\ ls = upl_conv_1 ls0))).\n\tintros. elim H2. intros. elim H4. intros. elim H5. intros. elim H6.\n\tintros. elim H8. intros. elim H10. intros. rewrite H7.\n\texact (rec_consn p x x0 x1 hd tl (H p x1 H0 H12)).\n\tcut (upl_conv_1 pl = prec_cons a la ls). intro.\n\texact (upl_conv_1_img_0 pl a la ls H2). symmetry  in |- *. trivial. symmetry  in |- *.\n\ttrivial.\nQed.\n\nLemma u_conv1_5r :\n forall (p : preDTA) (a : ad) (t : term) (r : reconnaissance p a t),\n u_conv_rec_1_r p a t r.\nProof.\n\texact\n  (mreconnaissance_ind u_conv_rec_1_r u_conv_str_1_r u_conv_lr_1_r u_conv1_0r\n     u_conv1_1r u_conv1_2r u_conv1_3r u_conv1_4r).\nQed.\n\nLemma u_conv1_r :\n forall (p : preDTA) (a : ad) (t : term),\n reconnaissance (udta_conv_1 p) (uad_conv_1 a) t -> reconnaissance p a t.\nProof.\n\tintros. apply (u_conv1_5r (udta_conv_1 p) (uad_conv_1 a) t H p a). trivial. trivial.\nQed.\n\n(* udta_conv_0 et udta_conv_1 ont des images disjointes *)\n\nLemma u_conv_disj :\n forall (p0 p1 : preDTA) (a0 a1 : ad) (s0 s1 : state),\n MapGet state (udta_conv_0 p0) a0 = Some s0 ->\n MapGet state (udta_conv_1 p1) a1 = Some s1 -> a0 <> a1.\nProof.\n\tintros. intro. cut (exists a2 : _, a0 = uad_conv_0 a2).\n\tcut (exists a3 : _, a1 = uad_conv_1 a3). intros. elim H2.\n\telim H3. intros. rewrite <- H1 in H5. rewrite H4 in H5.\n\texact (adcnv_ok x x0 H5). exact (u_conv_1_invar_8 p1 a1 s1 H0).\n\texact (u_conv_0_invar_8 p0 a0 s0 H).\nQed.\n\n(* définition de l'union des supports de deux automates *)\n\nDefinition u_merge (p0 p1 : preDTA) : preDTA :=\n  MapMerge state (udta_conv_0 p0) (udta_conv_1 p1).\n\n(* invariants des MapGet au travers de u_merge *)\n\nLemma u_merge_0 :\n forall (p0 p1 : preDTA) (a : ad) (s : state),\n MapGet state (udta_conv_0 p0) a = Some s ->\n MapGet state (u_merge p0 p1) a = Some s.\nProof.\n\tintros. unfold u_merge in |- *. cut\n  (eqm state\n     (MapGet state (MapMerge state (udta_conv_0 p0) (udta_conv_1 p1)))\n     (fun a0 : ad =>\n      match MapGet state (udta_conv_1 p1) a0 with\n      | None => MapGet state (udta_conv_0 p0) a0\n      | Some y' => Some y'\n      end)). intros. unfold eqm in H0.\n\tcut\n  (MapGet state (MapMerge state (udta_conv_0 p0) (udta_conv_1 p1)) a =\n   match MapGet state (udta_conv_1 p1) a with\n   | None => MapGet state (udta_conv_0 p0) a\n   | Some y' => Some y'\n   end).\n\tintros. rewrite H1. cut\n  (MapGet state (udta_conv_1 p1) a = None \\/\n   (exists y : state, MapGet state (udta_conv_1 p1) a = Some y)).\n\tintro. elim H2; intros. rewrite H3. rewrite H. trivial. elim H3.\n\tintros. rewrite H4. elim (u_conv_disj p0 p1 a a s x H H4 (refl_equal a)).\n\telim (MapGet state (udta_conv_1 p1) a). Focus 2. left. trivial. right. split with a0.\n\ttrivial. exact (H0 a).\n\texact (MapMerge_semantics state (udta_conv_0 p0) (udta_conv_1 p1)).\nQed.\n\nLemma u_merge_1 :\n forall (p0 p1 : preDTA) (a : ad) (s : state),\n MapGet state (udta_conv_1 p1) a = Some s ->\n MapGet state (u_merge p0 p1) a = Some s.\nProof.\n\tintros. unfold u_merge in |- *. cut\n  (eqm state\n     (MapGet state (MapMerge state (udta_conv_0 p0) (udta_conv_1 p1)))\n     (fun a0 : ad =>\n      match MapGet state (udta_conv_1 p1) a0 with\n      | None => MapGet state (udta_conv_0 p0) a0\n      | Some y' => Some y'\n      end)).\n\tintros. unfold eqm in H0.\n\tcut\n  (MapGet state (MapMerge state (udta_conv_0 p0) (udta_conv_1 p1)) a =\n   match MapGet state (udta_conv_1 p1) a with\n   | None => MapGet state (udta_conv_0 p0) a\n   | Some y' => Some y'\n   end).\n\tintros. rewrite H1. rewrite H. trivial. exact (H0 a).\n\texact (MapMerge_semantics state (udta_conv_0 p0) (udta_conv_1 p1)).\nQed.\n\nLemma u_merge_0r :\n forall (p0 p1 : preDTA) (a : ad) (s : state),\n MapGet state (u_merge p0 p1) a = Some s ->\n forall b : ad,\n a = uad_conv_0 b -> MapGet state (udta_conv_0 p0) a = Some s.\nProof.\n\tintros. cut\n  (eqm state\n     (MapGet state (MapMerge state (udta_conv_0 p0) (udta_conv_1 p1)))\n     (fun a0 : ad =>\n      match MapGet state (udta_conv_1 p1) a0 with\n      | None => MapGet state (udta_conv_0 p0) a0\n      | Some y' => Some y'\n      end)). intro. unfold eqm in H1.\n\tunfold u_merge in H. rewrite H0. rewrite H0 in H.\n\tcut\n  (MapGet state (MapMerge state (udta_conv_0 p0) (udta_conv_1 p1))\n     (uad_conv_0 b) =\n   match MapGet state (udta_conv_1 p1) (uad_conv_0 b) with\n   | None => MapGet state (udta_conv_0 p0) (uad_conv_0 b)\n   | Some y' => Some y'\n   end). intro. rewrite H2 in H.\n\tcut\n  (MapGet state (udta_conv_1 p1) (uad_conv_0 b) = None \\/\n   (exists s : state,\n      MapGet state (udta_conv_1 p1) (uad_conv_0 b) = Some s)).\n\tintros. elim H3; intros. rewrite H4 in H. assumption. elim H4. intros.\n\telim (u_conv_1_invar_8 p1 (uad_conv_0 b) x). intros. elim (adcnv_ok b x0 H6).\n\tassumption. generalize (MapGet state (udta_conv_1 p1) (uad_conv_0 b)).\n\tsimple induction o. Focus 2. left. trivial. intro. right. split with a0. trivial.\n\texact (H1 (uad_conv_0 b)). \n\texact (MapMerge_semantics state (udta_conv_0 p0) (udta_conv_1 p1)).\nQed.\n\nLemma u_merge_1r :\n forall (p0 p1 : preDTA) (a : ad) (s : state),\n MapGet state (u_merge p0 p1) a = Some s ->\n forall b : ad,\n a = uad_conv_1 b -> MapGet state (udta_conv_1 p1) a = Some s.\nProof.\n\tintros. cut\n  (eqm state\n     (MapGet state (MapMerge state (udta_conv_0 p0) (udta_conv_1 p1)))\n     (fun a0 : ad =>\n      match MapGet state (udta_conv_1 p1) a0 with\n      | None => MapGet state (udta_conv_0 p0) a0\n      | Some y' => Some y'\n      end)). intro. unfold eqm in H1.\n\tunfold u_merge in H. rewrite H0. rewrite H0 in H.\n\tcut\n  (MapGet state (MapMerge state (udta_conv_0 p0) (udta_conv_1 p1))\n     (uad_conv_1 b) =\n   match MapGet state (udta_conv_1 p1) (uad_conv_1 b) with\n   | None => MapGet state (udta_conv_0 p0) (uad_conv_1 b)\n   | Some y' => Some y'\n   end). intros. rewrite H2 in H.\n\tcut\n  (MapGet state (udta_conv_1 p1) (uad_conv_1 b) = None \\/\n   (exists s : _, MapGet state (udta_conv_1 p1) (uad_conv_1 b) = Some s)). intro.\n\telim H3; intros. rewrite H4 in H. elim (u_conv_0_invar_8 p0 (uad_conv_1 b) s H).\n\tintros. elim (adcnv_ok x b (sym_eq H5)).\n\telim H4. intros. rewrite H5 in H. inversion H. rewrite <- H7. exact H5.\n\tgeneralize (MapGet state (udta_conv_1 p1) (uad_conv_1 b)). simple induction o. Focus 2.\n\tleft. trivial. intros. right. split with a0. trivial. exact (H1 (uad_conv_1 b)).\n\texact (MapMerge_semantics state (udta_conv_0 p0) (udta_conv_1 p1)).\nQed.\n\n(* invariant de reconnaissance pour conv_0 au travers de u_merge *)\n\nDefinition u_merge_inv_0_dta (p0 : preDTA) (a : ad) \n  (t : term) (pr : reconnaissance p0 a t) :=\n  forall p1 : preDTA, reconnaissance (u_merge p0 p1) (uad_conv_0 a) t.\n\nDefinition u_merge_inv_0_st (p0 : preDTA) (s : state) \n  (t : term) (pr : state_reconnait p0 s t) :=\n  forall p1 : preDTA, state_reconnait (u_merge p0 p1) (umpl_conv_0 s) t.\n\nDefinition u_merge_inv_0_lst (p0 : preDTA) (pl : prec_list) \n  (lt : term_list) (pr : liste_reconnait p0 pl lt) :=\n  forall p1 : preDTA, liste_reconnait (u_merge p0 p1) (upl_conv_0 pl) lt.\n\nLemma u_merge_2_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 u_merge_inv_0_st d ladj t s ->\n u_merge_inv_0_dta d a t (rec_dta d a t ladj e s).\nProof.\n\tintros. unfold u_merge_inv_0_st in H. unfold u_merge_inv_0_dta in |- *.\n\tintro. apply (rec_dta (u_merge d p1) (uad_conv_0 a) t (umpl_conv_0 ladj)).\n\tapply (u_merge_0 d p1 (uad_conv_0 a) (umpl_conv_0 ladj)).\n\texact (u_conv_0_invar_0 d a ladj e). exact (H p1).\nQed.\n\nLemma u_merge_2_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 u_merge_inv_0_lst d l tl l0 ->\n u_merge_inv_0_st d s (app c tl) (rec_st d s c tl l e l0).\nProof.\n\tintros. unfold u_merge_inv_0_lst in H. unfold u_merge_inv_0_st in |- *.\n\tintros. apply (rec_st (u_merge d p1) (umpl_conv_0 s) c tl (upl_conv_0 l)).\n\tapply (u_conv_0_invar_1 s c l). assumption. exact (H p1).\nQed.\n\nLemma u_merge_2_2 :\n forall d : preDTA, u_merge_inv_0_lst d prec_empty tnil (rec_empty d).\nProof.\n\tunfold u_merge_inv_0_lst in |- *. simpl in |- *. intros. exact (rec_empty (u_merge d p1)).\nQed.\n\nLemma u_merge_2_3 :\n forall (d : preDTA) (a : ad) (la ls : prec_list) (hd : term)\n   (tl : term_list) (r : reconnaissance d a hd),\n u_merge_inv_0_dta d a hd r ->\n forall l : liste_reconnait d la tl,\n u_merge_inv_0_lst d la tl l ->\n u_merge_inv_0_lst d (prec_cons a la ls) (tcons hd tl)\n   (rec_consi d a la ls hd tl r l).\nProof.\n\tintros. unfold u_merge_inv_0_lst in H0. unfold u_merge_inv_0_lst in |- *.\n\tunfold u_merge_inv_0_dta in |- *. simpl in |- *. unfold u_merge_inv_0_dta in H.\n\tintros. apply\n  (rec_consi (u_merge d p1) (uad_conv_0 a) (upl_conv_0 la) \n     (upl_conv_0 ls) hd tl). exact (H p1). exact (H0 p1).\nQed.\n\nLemma u_merge_2_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 u_merge_inv_0_lst d ls (tcons hd tl) l ->\n u_merge_inv_0_lst d (prec_cons a la ls) (tcons hd tl)\n   (rec_consn d a la ls hd tl l).\nProof.\n\tintros. unfold u_merge_inv_0_lst in |- *. unfold u_merge_inv_0_lst in H.\n\tsimpl in |- *. intros. exact\n  (rec_consn (u_merge d p1) (uad_conv_0 a) (upl_conv_0 la) \n     (upl_conv_0 ls) hd tl (H p1)).\nQed.\n\nLemma u_merge_2_5 :\n forall (p : preDTA) (a : ad) (t : term) (r : reconnaissance p a t),\n u_merge_inv_0_dta p a t r.\nProof.\n\texact\n  (mreconnaissance_ind u_merge_inv_0_dta u_merge_inv_0_st u_merge_inv_0_lst\n     u_merge_2_0 u_merge_2_1 u_merge_2_2 u_merge_2_3 u_merge_2_4).\nQed.\n\nLemma u_merge_2 :\n forall (p0 p1 : preDTA) (a : ad) (t : term),\n reconnaissance p0 a t -> reconnaissance (u_merge p0 p1) (uad_conv_0 a) t.\nProof.\n\tintros. exact (u_merge_2_5 p0 a t H p1).\nQed.\n\n(* invariant de reconnaissance pour conv_1 au travers de u_merge *)\n\nDefinition u_merge_inv_1_dta (p1 : preDTA) (a : ad) \n  (t : term) (pr : reconnaissance p1 a t) :=\n  forall p0 : preDTA, reconnaissance (u_merge p0 p1) (uad_conv_1 a) t.\n\nDefinition u_merge_inv_1_st (p1 : preDTA) (s : state) \n  (t : term) (pr : state_reconnait p1 s t) :=\n  forall p0 : preDTA, state_reconnait (u_merge p0 p1) (umpl_conv_1 s) t.\n\nDefinition u_merge_inv_1_lst (p1 : preDTA) (pl : prec_list) \n  (lt : term_list) (pr : liste_reconnait p1 pl lt) :=\n  forall p0 : preDTA, liste_reconnait (u_merge p0 p1) (upl_conv_1 pl) lt.\n\nLemma u_merge_3_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 u_merge_inv_1_st d ladj t s ->\n u_merge_inv_1_dta d a t (rec_dta d a t ladj e s).\nProof.\n\tintros. unfold u_merge_inv_1_dta in |- *. unfold u_merge_inv_1_st in H.\n\tintros. apply (rec_dta (u_merge p0 d) (uad_conv_1 a) t (umpl_conv_1 ladj)).\n\tapply (u_merge_1 p0 d (uad_conv_1 a) (umpl_conv_1 ladj)).\n\texact (u_conv_1_invar_0 d a ladj e). exact (H p0).\nQed.\n\nLemma u_merge_3_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 u_merge_inv_1_lst d l tl l0 ->\n u_merge_inv_1_st d s (app c tl) (rec_st d s c tl l e l0).\nProof.\n\tintros; unfold u_merge_inv_1_st in |- *. unfold u_merge_inv_1_lst in H.\n\tintros. apply (rec_st (u_merge p0 d) (umpl_conv_1 s) c tl (upl_conv_1 l)).\n\texact (u_conv_1_invar_1 s c l e). exact (H p0).\nQed.\n\nLemma u_merge_3_2 :\n forall d : preDTA, u_merge_inv_1_lst d prec_empty tnil (rec_empty d).\nProof.\n\tintros. unfold u_merge_inv_1_lst in |- *. simpl in |- *. intros.\n\texact (rec_empty (u_merge p0 d)).\nQed.\n\nLemma u_merge_3_3 :\n forall (d : preDTA) (a : ad) (la ls : prec_list) (hd : term)\n   (tl : term_list) (r : reconnaissance d a hd),\n u_merge_inv_1_dta d a hd r ->\n forall l : liste_reconnait d la tl,\n u_merge_inv_1_lst d la tl l ->\n u_merge_inv_1_lst d (prec_cons a la ls) (tcons hd tl)\n   (rec_consi d a la ls hd tl r l).\nProof.\n\tintros. unfold u_merge_inv_1_lst in |- *. unfold u_merge_inv_1_dta in H.\n\tunfold u_merge_inv_1_lst in H. intros. simpl in |- *. unfold u_merge_inv_1_lst in H0.\n\texact\n  (rec_consi (u_merge p0 d) (uad_conv_1 a) (upl_conv_1 la) \n     (upl_conv_1 ls) hd tl (H p0) (H0 p0)).\nQed.\n\nLemma u_merge_3_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 u_merge_inv_1_lst d ls (tcons hd tl) l ->\n u_merge_inv_1_lst d (prec_cons a la ls) (tcons hd tl)\n   (rec_consn d a la ls hd tl l).\nProof.\n\tintros. unfold u_merge_inv_1_lst in H. unfold u_merge_inv_1_lst in |- *.\n\tsimpl in |- *. intros. exact\n  (rec_consn (u_merge p0 d) (uad_conv_1 a) (upl_conv_1 la) \n     (upl_conv_1 ls) hd tl (H p0)).\nQed.\n\nLemma u_merge_3_5 :\n forall (p : preDTA) (a : ad) (t : term) (r : reconnaissance p a t),\n u_merge_inv_1_dta p a t r.\nProof.\n\texact\n  (mreconnaissance_ind u_merge_inv_1_dta u_merge_inv_1_st u_merge_inv_1_lst\n     u_merge_3_0 u_merge_3_1 u_merge_3_2 u_merge_3_3 u_merge_3_4).\nQed.\n\nLemma u_merge_3 :\n forall (p0 p1 : preDTA) (a : ad) (t : term),\n reconnaissance p1 a t -> reconnaissance (u_merge p0 p1) (uad_conv_1 a) t.\nProof.\n\tintros. exact (u_merge_3_5 p1 a t H p0).\nQed.\n\n(* invariant pour u_merge : sens réciproque pour u_conv_0 *)\n\nDefinition u_merge_invr_0_dta (p : preDTA) (a : ad) \n  (t : term) (pr : reconnaissance p a t) :=\n  forall p0 p1 : preDTA,\n  p = u_merge p0 p1 ->\n  forall a0 : ad, a = uad_conv_0 a0 -> reconnaissance (udta_conv_0 p0) a t.\n\nDefinition u_merge_invr_0_st (p : preDTA) (s : state) \n  (t : term) (pr : state_reconnait p s t) :=\n  forall p0 p1 : preDTA,\n  p = u_merge p0 p1 ->\n  forall s0 : state,\n  s = umpl_conv_0 s0 -> state_reconnait (udta_conv_0 p0) s t.\n\nDefinition u_merge_invr_0_lst (p : preDTA) (pl : prec_list) \n  (lt : term_list) (pr : liste_reconnait p pl lt) :=\n  forall p0 p1 : preDTA,\n  p = u_merge p0 p1 ->\n  forall pl0 : prec_list,\n  pl = upl_conv_0 pl0 -> liste_reconnait (udta_conv_0 p0) pl lt.\n\nLemma u_merge_4_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 u_merge_invr_0_st d ladj t s ->\n u_merge_invr_0_dta d a t (rec_dta d a t ladj e s).\nProof.\n\tintros. unfold u_merge_invr_0_st in H. unfold u_merge_invr_0_dta in |- *.\n\tintros. rewrite H0 in e. apply (rec_dta (udta_conv_0 p0) a t ladj (u_merge_0r p0 p1 a ladj e a0 H1)). cut\n  (exists ladj0 : state,\n     ladj = umpl_conv_0 ladj0 /\\ MapGet state p0 a0 = Some ladj0).\n\tintros. elim H2. intros. elim H3. intros. exact (H p0 p1 H0 x H4).\n\tapply (u_conv_0_invar_5 p0 a0 ladj). rewrite <- H1.\n\texact (u_merge_0r p0 p1 a ladj e a0 H1).\nQed.\n\nLemma u_merge_4_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 u_merge_invr_0_lst d l tl l0 ->\n u_merge_invr_0_st d s (app c tl) (rec_st d s c tl l e l0).\nProof.\n\tintros. unfold u_merge_invr_0_st in |- *. intros. unfold u_merge_invr_0_lst in H.\n\tapply (rec_st (udta_conv_0 p0) s c tl l e). rewrite H1 in e.\n\telim (u_conv_0_invar_7 s0 c l e). intros. elim H2. intros.\n\texact (H p0 p1 H0 x H3).\nQed.\n\nLemma u_merge_4_2 :\n forall d : preDTA, u_merge_invr_0_lst d prec_empty tnil (rec_empty d).\nProof.\n\tintros. unfold u_merge_invr_0_lst in |- *. intros. exact (rec_empty (udta_conv_0 p0)).\nQed.\n\nLemma u_merge_4_3 :\n forall (d : preDTA) (a : ad) (la ls : prec_list) (hd : term)\n   (tl : term_list) (r : reconnaissance d a hd),\n u_merge_invr_0_dta d a hd r ->\n forall l : liste_reconnait d la tl,\n u_merge_invr_0_lst d la tl l ->\n u_merge_invr_0_lst d (prec_cons a la ls) (tcons hd tl)\n   (rec_consi d a la ls hd tl r l).\nProof.\n\tintros. unfold u_merge_invr_0_dta in H. unfold u_merge_invr_0_lst in H0.\n\tunfold u_merge_invr_0_lst in |- *. intros. elim (upl_conv_0_img_0 pl0 a la ls (sym_eq H2)). intros. \n\telim H3. intros. elim H4. intros. elim H5. intros. elim H7. intros. elim H9. \n\tintros. exact\n  (rec_consi (udta_conv_0 p0) a la ls hd tl (H p0 p1 H1 x H8)\n     (H0 p0 p1 H1 x0 H10)).\nQed.\n\nLemma u_merge_4_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 u_merge_invr_0_lst d ls (tcons hd tl) l ->\n u_merge_invr_0_lst d (prec_cons a la ls) (tcons hd tl)\n   (rec_consn d a la ls hd tl l).\nProof.\n\tintros; unfold u_merge_invr_0_lst in H. unfold u_merge_invr_0_lst in |- *. intros.\n\telim (upl_conv_0_img_0 pl0 a la ls (sym_eq H1)). intros. elim H2.\n\tintros. elim H3. intros. elim H4. intros. elim H6. intros. elim H8. intros.\n\texact (rec_consn (udta_conv_0 p0) a la ls hd tl (H p0 p1 H0 x1 H10)).\nQed.\n\nLemma u_merge_4_5 :\n forall (p : preDTA) (a : ad) (t : term) (r : reconnaissance p a t),\n u_merge_invr_0_dta p a t r.\nProof. \n\texact\n  (mreconnaissance_ind u_merge_invr_0_dta u_merge_invr_0_st\n     u_merge_invr_0_lst u_merge_4_0 u_merge_4_1 u_merge_4_2 u_merge_4_3\n     u_merge_4_4).\nQed.\n\nLemma u_merge_4 :\n forall (p0 p1 : preDTA) (a : ad) (t : term),\n reconnaissance (u_merge p0 p1) (uad_conv_0 a) t -> reconnaissance p0 a t.\nProof.\n\tintros. apply (u_conv0_r p0 a t). exact\n  (u_merge_4_5 (u_merge p0 p1) (uad_conv_0 a) t H p0 p1\n     (refl_equal (u_merge p0 p1)) a (refl_equal (uad_conv_0 a))).\nQed.\n\n(* invariant pour u_merge : sens réciproque pour u_conv_1 *)\n\nDefinition u_merge_invr_1_dta (p : preDTA) (a : ad) \n  (t : term) (pr : reconnaissance p a t) :=\n  forall p0 p1 : preDTA,\n  p = u_merge p0 p1 ->\n  forall a0 : ad, a = uad_conv_1 a0 -> reconnaissance (udta_conv_1 p1) a t.\n\nDefinition u_merge_invr_1_st (p : preDTA) (s : state) \n  (t : term) (pr : state_reconnait p s t) :=\n  forall p0 p1 : preDTA,\n  p = u_merge p0 p1 ->\n  forall s0 : state,\n  s = umpl_conv_1 s0 -> state_reconnait (udta_conv_1 p1) s t.\n\nDefinition u_merge_invr_1_lst (p : preDTA) (pl : prec_list) \n  (lt : term_list) (pr : liste_reconnait p pl lt) :=\n  forall p0 p1 : preDTA,\n  p = u_merge p0 p1 ->\n  forall pl0 : prec_list,\n  pl = upl_conv_1 pl0 -> liste_reconnait (udta_conv_1 p1) pl lt.\n\nLemma u_merge_5_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 u_merge_invr_1_st d ladj t s ->\n u_merge_invr_1_dta d a t (rec_dta d a t ladj e s).\nProof.\n\tintros. unfold u_merge_invr_1_st in H. unfold u_merge_invr_1_dta in |- *.\n\tintros. rewrite H0 in e. apply (rec_dta (udta_conv_1 p1) a t ladj (u_merge_1r p0 p1 a ladj e a0 H1)). cut\n  (exists ladj0 : state,\n     ladj = umpl_conv_1 ladj0 /\\ MapGet state p1 a0 = Some ladj0).\n\tintros. elim H2. intros. elim H3. intros. exact (H p0 p1 H0 x H4).\n\tapply (u_conv_1_invar_5 p1 a0 ladj). rewrite <- H1.\n\texact (u_merge_1r p0 p1 a ladj e a0 H1).\nQed.\n\nLemma u_merge_5_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 u_merge_invr_1_lst d l tl l0 ->\n u_merge_invr_1_st d s (app c tl) (rec_st d s c tl l e l0).\nProof.\n\tintros. unfold u_merge_invr_1_st in |- *. intros. unfold u_merge_invr_1_lst in H.\n\tapply (rec_st (udta_conv_1 p1) s c tl l e). rewrite H1 in e.\n\telim (u_conv_1_invar_7 s0 c l e). intros. elim H2. intros. \n\texact (H p0 p1 H0 x H3).\nQed.\n\nLemma u_merge_5_2 :\n forall d : preDTA, u_merge_invr_1_lst d prec_empty tnil (rec_empty d).\nProof.\n\tunfold u_merge_invr_1_lst in |- *. intros. exact (rec_empty (udta_conv_1 p1)).\nQed.\n\nLemma u_merge_5_3 :\n forall (d : preDTA) (a : ad) (la ls : prec_list) (hd : term)\n   (tl : term_list) (r : reconnaissance d a hd),\n u_merge_invr_1_dta d a hd r ->\n forall l : liste_reconnait d la tl,\n u_merge_invr_1_lst d la tl l ->\n u_merge_invr_1_lst d (prec_cons a la ls) (tcons hd tl)\n   (rec_consi d a la ls hd tl r l).\nProof.\n\tintros. unfold u_merge_invr_1_dta in H. unfold u_merge_invr_1_lst in H0.\n\tunfold u_merge_invr_1_lst in |- *. intros. elim (upl_conv_1_img_0 pl0 a la ls (sym_eq H2)). intros.\n\telim H3. intros. elim H4. intros; elim H5. intros. elim H7. intros.\n\telim H9. intros. apply (rec_consi (udta_conv_1 p1) a la ls hd tl).\n\texact (H p0 p1 H1 x H8). exact (H0 p0 p1 H1 x0 H10).\nQed.\n\nLemma u_merge_5_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 u_merge_invr_1_lst d ls (tcons hd tl) l ->\n u_merge_invr_1_lst d (prec_cons a la ls) (tcons hd tl)\n   (rec_consn d a la ls hd tl l).\nProof.\n\tintros. unfold u_merge_invr_1_lst in H. unfold u_merge_invr_1_lst in |- *.\n\tintros. elim (upl_conv_1_img_0 pl0 a la ls (sym_eq H1)).\n\tintros. elim H2. intros. elim H3. intros. elim H4. intros. elim H6.\n\tintros. elim H8. intros. \n\texact (rec_consn (udta_conv_1 p1) a la ls hd tl (H p0 p1 H0 x1 H10)).\nQed.\n\nLemma u_merge_5_5 :\n forall (p : preDTA) (a : ad) (t : term) (r : reconnaissance p a t),\n u_merge_invr_1_dta p a t r.\nProof. \n\texact\n  (mreconnaissance_ind u_merge_invr_1_dta u_merge_invr_1_st\n     u_merge_invr_1_lst u_merge_5_0 u_merge_5_1 u_merge_5_2 u_merge_5_3\n     u_merge_5_4).\nQed.\n\nLemma u_merge_5 :\n forall (p0 p1 : preDTA) (a : ad) (t : term),\n reconnaissance (u_merge p0 p1) (uad_conv_1 a) t -> reconnaissance p1 a t.\nProof.\n\tintros. apply (u_conv1_r p1 a t). exact\n  (u_merge_5_5 (u_merge p0 p1) (uad_conv_1 a) t H p0 p1\n     (refl_equal (u_merge p0 p1)) a (refl_equal (uad_conv_1 a))).\nQed.\n\n(* union de deux états dans un meme preDTA *)\n\n(* définition d'un état *)\n\nFixpoint union_pl (pl0 : prec_list) : prec_list -> prec_list :=\n  fun pl1 : prec_list =>\n  match pl0 with\n  | prec_empty => pl1\n  | prec_cons a pl00 pl01 => prec_cons a pl00 (union_pl pl01 pl1)\n  end.\n\nFixpoint union_mpl_0 (c : ad) (pl : prec_list) (s : state) {struct s} :\n state :=\n  match s with\n  | M0 => M1 prec_list c pl\n  | M1 c0 pl0 =>\n      if Neqb c c0\n      then M1 prec_list c (union_pl pl pl0)\n      else MapMerge prec_list (M1 prec_list c pl) (M1 prec_list c0 pl0)\n  | M2 s0 s1 =>\n      match c with\n      | N0 => M2 prec_list (union_mpl_0 N0 pl s0) s1\n      | Npos p =>\n          match p with\n          | xH => M2 prec_list s0 (union_mpl_0 N0 pl s1)\n          | xO p' => M2 prec_list (union_mpl_0 (Npos p') pl s0) s1\n          | xI p' => M2 prec_list s0 (union_mpl_0 (Npos p') pl s1)\n          end\n      end\n  end.\n\nFixpoint union_mpl (s0 : state) : state -> state :=\n  fun s1 : state =>\n  match s0, s1 with\n  | M0, M0 => M0 prec_list\n  | M0, M2 s10 s11 => M2 prec_list s10 s11\n  | _, M1 c1 pl1 => union_mpl_0 c1 pl1 s0\n  | M1 c0 pl0, _ => union_mpl_0 c0 pl0 s1\n  | M2 s00 s01, M0 => M2 prec_list s00 s01\n  | M2 s00 s01, M2 s10 s11 =>\n      M2 prec_list (union_mpl s00 s10) (union_mpl s01 s11)\n  end.\n\nLemma union_pl_0 : forall pl : prec_list, union_pl pl prec_empty = pl.\nProof.\n\tsimple induction pl. intros. simpl in |- *. rewrite H0. trivial. simpl in |- *. trivial.\nQed.\n\nLemma union_pl_1 : forall pl : prec_list, union_pl prec_empty pl = pl.\nProof.\n\tsimpl in |- *. intros. trivial.\nQed.\n\nLemma union_pl_2 :\n forall pl0 pl1 : prec_list,\n union_pl pl0 pl1 = prec_empty -> pl0 = prec_empty.\nProof.\n\tintros. induction  pl0 as [a pl0_1 Hrecpl0_1 pl0_0 Hrecpl0_0| ]. inversion H. trivial.\nQed.\n\nLemma union_pl_3 :\n forall pl0 pl1 : prec_list,\n pl0 <> prec_empty -> union_pl pl0 pl1 <> prec_empty.\nProof.\n\tintros. intro. exact (H (union_pl_2 pl0 pl1 H0)).\nQed.\n\nLemma union_pl_0d_0 :\n forall (d : preDTA) (pl0 : prec_list) (tl : term_list),\n liste_reconnait d pl0 tl -> liste_reconnait d (union_pl pl0 prec_empty) tl.\nProof.\n\tintros. rewrite (union_pl_0 pl0). trivial.\nQed.\n\nLemma union_pl_0d_1 :\n forall (d : preDTA) (pl0 : prec_list) (tl : term_list) \n   (a : ad) (la ls : prec_list),\n liste_reconnait d pl0 tl ->\n pl0 <> prec_empty -> liste_reconnait d (union_pl pl0 (prec_cons a la ls)) tl.\nProof.\n\tintro. simple induction pl0. intros. simpl in |- *. elim (term_list_disj tl). intros.\n\trewrite H3 in H1. inversion H1. intros. elim H3. intros. elim H4. intros.\n\trewrite H5. rewrite H5 in H1. inversion H1.\n\texact (rec_consi d a p (union_pl p0 (prec_cons a0 la ls)) x x0 H9 H13).\n\tapply (rec_consn d a p (union_pl p0 (prec_cons a0 la ls)) x x0). \n\telim (classic (p0 = prec_empty)). intro. rewrite H13 in H8. \n\telim (sem_listes_1 d x x0 H8). intros. exact (H0 (tcons x x0) a0 la ls H8 H13).\n\tintros. elim H0. trivial.\nQed.\n\nLemma union_pl_0d :\n forall (d : preDTA) (pl0 pl1 : prec_list) (tl : term_list),\n pl_compat pl0 pl1 ->\n liste_reconnait d pl0 tl -> liste_reconnait d (union_pl pl0 pl1) tl.\nProof.\n\tintros. elim H. intros. elim H1. intros. rewrite H3. \n\texact (union_pl_0d_0 d pl0 tl H0). intros. elim H1. intros. induction  pl1 as [a pl1_1 Hrecpl1_1 pl1_0 Hrecpl1_0| ].\n\texact (union_pl_0d_1 d pl0 tl a pl1_1 pl1_0 H0 H2). rewrite (union_pl_0 pl0).\n\tassumption.\nQed.\n\nLemma union_pl_1d_0 :\n forall (d : preDTA) (pl1 : prec_list) (tl : term_list),\n liste_reconnait d pl1 tl -> liste_reconnait d (union_pl prec_empty pl1) tl.\nProof.\n\tintros. simpl in |- *. assumption.\nQed.\n\nLemma union_pl_1d_1 :\n forall (d : preDTA) (pl1 : prec_list) (tl : term_list) pl0,\n liste_reconnait d pl1 tl ->\n pl1 <> prec_empty -> liste_reconnait d (union_pl pl0 pl1) tl.\nProof.\n\tintros. induction  pl0 as [a pl0_1 Hrecpl0_1 pl0_0 Hrecpl0_0| ]. elim (term_list_disj tl). intros. rewrite H1 in H.\n\telim (H0 (sem_listes_2 d pl1 H)). intro. elim H1. intros. elim H2. intros. rewrite H3.\n\trewrite H3 in H. simpl in |- *. apply (rec_consn d a pl0_1 (union_pl pl0_0 pl1) x x0).\n\trewrite H3 in Hrecpl0_0. trivial. simpl in |- *. assumption.\nQed.\n\nLemma union_pl_1d :\n forall (d : preDTA) (pl0 pl1 : prec_list) (tl : term_list),\n pl_compat pl0 pl1 ->\n liste_reconnait d pl1 tl -> liste_reconnait d (union_pl pl0 pl1) tl.\nProof.\n\tintros. elim H. intros. elim H1. intros. rewrite H2. simpl in |- *. assumption.\n\tintros. elim H1. intros. induction  pl0 as [a pl0_1 Hrecpl0_1 pl0_0 Hrecpl0_0| ]. \n\texact (union_pl_1d_1 d pl1 tl (prec_cons a pl0_1 pl0_0) H0 H3). simpl in |- *.\n\tassumption.\nQed.\n\nLemma union_pl_r_0 :\n forall (d : preDTA) (pl0 pl1 : prec_list) (hd : term) (tl : term_list),\n liste_reconnait d (union_pl pl0 pl1) (tcons hd tl) ->\n liste_reconnait d pl0 (tcons hd tl) \\/ liste_reconnait d pl1 (tcons hd tl).\nProof.\n\tintros. induction  pl0 as [a pl0_1 Hrecpl0_1 pl0_0 Hrecpl0_0| ]. simpl in H. inversion H. left.\n\texact (rec_consi d a pl0_1 pl0_0 hd tl H3 H7). elim (Hrecpl0_0 H2). intros.\n\tleft. exact (rec_consn d a pl0_1 pl0_0 hd tl H7). intro. right. assumption.\n\tsimpl in H. right. assumption.\nQed.\n\nLemma union_pl_r_1 :\n forall (d : preDTA) (pl0 pl1 : prec_list),\n pl_compat pl0 pl1 ->\n liste_reconnait d (union_pl pl0 pl1) tnil ->\n liste_reconnait d pl0 tnil \\/ liste_reconnait d pl1 tnil.\nProof.\n\tintros. elim H. intros. elim H1. intros. left. rewrite H2. \n\texact (rec_empty d). intros. elim H1. intros.\n\telim (union_pl_3 pl0 pl1 H2 (sem_listes_2 d (union_pl pl0 pl1) H0)).\nQed.\n\nLemma union_pl_r :\n forall (d : preDTA) (pl0 pl1 : prec_list) (tl : term_list),\n pl_compat pl0 pl1 ->\n liste_reconnait d (union_pl pl0 pl1) tl ->\n liste_reconnait d pl0 tl \\/ liste_reconnait d pl1 tl.\nProof.\n\tintros. induction  tl as [| t tl Hrectl]. exact (union_pl_r_1 d pl0 pl1 H H0).\n\texact (union_pl_r_0 d pl0 pl1 t tl H0).\nQed.\n\n(* conservation des relation compat par union d'état *)\n\nDefinition mpl_compat_7_def (s : state) : Prop :=\n  forall (c : ad) (pl l : prec_list),\n  MapGet prec_list s c = Some l ->\n  MapGet prec_list (union_mpl_0 c pl s) c = Some (union_pl pl l).\n\nLemma mpl_compat_7_0 : mpl_compat_7_def (M0 prec_list).\nProof.\n\tunfold mpl_compat_7_def in |- *. intros. simpl in H. inversion H.\nQed.\n\nLemma mpl_compat_7_1 :\n forall (a : ad) (a0 : prec_list), mpl_compat_7_def (M1 prec_list a a0).\nProof.\n\tunfold mpl_compat_7_def in |- *. intros. simpl in H. elim (bool_is_true_or_false (Neqb a c)); intros; rewrite H0 in H;\n  inversion H. rewrite (Neqb_complete a c H0). simpl in |- *.\n\trewrite (Neqb_correct c). simpl in |- *. rewrite (Neqb_correct c). trivial.\nQed.\n\nLemma mpl_compat_7_2 :\n forall m : Map prec_list,\n mpl_compat_7_def m ->\n forall m0 : Map prec_list,\n mpl_compat_7_def m0 -> mpl_compat_7_def (M2 prec_list m m0).\nProof.\n\tunfold mpl_compat_7_def in |- *. intros. induction  c as [| p]. simpl in |- *. apply (H N0 pl l).\n\tsimpl in H1. assumption. induction  p as [p Hrecp| p Hrecp| ]. simpl in |- *. apply (H0 (Npos p) pl l).\n\tsimpl in H1. assumption. simpl in |- *. apply (H (Npos p) pl l). simpl in H1. assumption.\n\tsimpl in H1. simpl in |- *. exact (H0 N0 pl l H1).\nQed.\n\nLemma mpl_compat_7_3 : forall m : state, mpl_compat_7_def m.\nProof.\n\texact\n  (Map_ind prec_list mpl_compat_7_def mpl_compat_7_0 mpl_compat_7_1\n     mpl_compat_7_2).\nQed.\n\nLemma mpl_compat_7 :\n forall (s : state) (c : ad) (pl l : prec_list),\n MapGet prec_list s c = Some l ->\n MapGet prec_list (union_mpl_0 c pl s) c = Some (union_pl pl l).\nProof.\n\tintros. exact (mpl_compat_7_3 s c pl l H).\nQed.\n\nDefinition mpl_compat_8_def (s : state) : Prop :=\n  forall (a c : ad) (pl l : prec_list),\n  MapGet prec_list s c = Some l ->\n  a <> c -> MapGet prec_list (union_mpl_0 a pl s) c = Some l.\n\nLemma mpl_compat_8_0 : mpl_compat_8_def (M0 prec_list).\nProof.\n\tunfold mpl_compat_8_def in |- *. intros. inversion H.\nQed.\n\nLemma mpl_compat_8_1 :\n forall (a : ad) (a0 : prec_list), mpl_compat_8_def (M1 prec_list a a0).\nProof.\n\tunfold mpl_compat_8_def in |- *. intros. simpl in H. elim (bool_is_true_or_false (Neqb a c)); intros; rewrite H1 in H. inversion H. simpl in |- *. elim (bool_is_true_or_false (Neqb a1 a)); intro; rewrite H2. simpl in |- *. elim (bool_is_true_or_false (Neqb a1 c)). intro.\n\telim (H0 (Neqb_complete a1 c H4)). intro. rewrite (Neqb_complete a1 a H2) in H4.\n\trewrite H1 in H4. inversion H4. elim (Ndiscr (Nxor a a1)). intro y. elim y.\n\tintros x y0. rewrite y0. rewrite (MapPut1_semantics prec_list x a a1 l pl y0 c).\n\trewrite H1. trivial. intro y. rewrite (Neqb_comm a1 a) in H2.\n\trewrite (Nxor_eq_true a a1 y) in H2. inversion H2. inversion H.\nQed.\n\nLemma mpl_compat_8_2 :\n forall m : state,\n mpl_compat_8_def m ->\n forall m0 : state,\n mpl_compat_8_def m0 -> mpl_compat_8_def (M2 prec_list m m0).\nProof.\n\tunfold mpl_compat_8_def in |- *. intros. induction  a as [| p]; [ induction  c as [| p] | induction  c as [| p0] ]. elim (H2 (refl_equal N0)).\n\tsimpl in |- *. induction  p as [p Hrecp| p Hrecp| ]. simpl in H1. assumption. simpl in H1. apply (H N0 (Npos p) pl l H1).\n\tintro. inversion H3. simpl in H1. assumption. simpl in |- *. induction  p as [p Hrecp| p Hrecp| ]. simpl in |- *. simpl in H1.\n\tassumption. simpl in |- *. apply (H (Npos p) N0 pl l H1). intro. inversion H3. simpl in |- *.\n\tsimpl in H1. assumption. simpl in |- *. induction  p as [p Hrecp| p Hrecp| ]. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in |- *. simpl in H1.\n\tapply (H0 (Npos p) (Npos p0) pl l H1). intro. inversion H3. elim H2. trivial. rewrite H5.\n\ttrivial. simpl in |- *. simpl in H1. assumption. simpl in |- *. apply (H0 (Npos p) N0 pl l H1).\n\tintro. inversion H3. simpl in |- *. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in H1. assumption.\n\tapply (H (Npos p) (Npos p0) pl l H1). intro. inversion H3. rewrite H5 in H2. elim H2.\n\ttrivial. simpl in H1. assumption. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in |- *. simpl in H1. simpl in |- *.\n\tapply (H0 N0 (Npos p0) pl l). assumption. intro. inversion H3. simpl in |- *. simpl in H1.\n\tassumption. simpl in |- *. elim H2. trivial.\nQed.\n\nLemma mpl_compat_8_3 : forall m : state, mpl_compat_8_def m.\nProof.\n\texact\n  (Map_ind prec_list mpl_compat_8_def mpl_compat_8_0 mpl_compat_8_1\n     mpl_compat_8_2).\nQed.\n\nLemma mpl_compat_8 :\n forall (s : state) (a c : ad) (pl l : prec_list),\n MapGet prec_list s c = Some l ->\n a <> c -> MapGet prec_list (union_mpl_0 a pl s) c = Some l.\nProof.\n\tintro. exact (mpl_compat_8_3 s).\nQed.\n\n(* invariant sur union_mpl_0, sens direct, 0 *)\n\nLemma union_s0d_0 :\n forall (d : preDTA) (c : ad) (pl : prec_list) (tl : term_list),\n mpl_compat (M1 prec_list c pl) (M0 prec_list) ->\n state_reconnait d (M1 prec_list c pl) (app c tl) ->\n state_reconnait d (union_mpl_0 c pl (M0 prec_list)) (app c tl).\nProof.\n\tunfold mpl_compat in |- *. intros. inversion H0. simpl in H5. rewrite (Neqb_correct c) in H5.\n\tinversion H5. apply (rec_st d (union_mpl_0 c l (M0 prec_list)) c tl l). simpl in |- *.\n\trewrite (Neqb_correct c). trivial. assumption.\nQed.\n\nLemma union_s0d_1_0 :\n forall (d : preDTA) (c : ad) (pl pl0 : prec_list) (tl : term_list),\n mpl_compat (M1 prec_list c pl) (M1 prec_list c pl0) ->\n state_reconnait d (M1 prec_list c pl) (app c tl) ->\n state_reconnait d (union_mpl_0 c pl (M1 prec_list c pl0)) (app c tl).\nProof.\n\tintros. unfold mpl_compat in H. inversion H0. simpl in H5. \n\trewrite (Neqb_correct c) in H5. inversion H5. \n\tapply\n  (rec_st d (union_mpl_0 c l (M1 prec_list c pl0)) c tl (union_pl l pl0)).\n\tsimpl in |- *. rewrite (Neqb_correct c). simpl in |- *. rewrite (Neqb_correct c). trivial.\n\tapply (union_pl_0d d l pl0 tl). apply (H c l pl0). simpl in |- *. rewrite (Neqb_correct c).\n\ttrivial. simpl in |- *. rewrite (Neqb_correct c). trivial. assumption.\nQed.\n\nLemma union_s0d_1_1 :\n forall (d : preDTA) (c : ad) (pl : prec_list) (c0 : ad) \n   (pl0 : prec_list) (tl : term_list),\n mpl_compat (M1 prec_list c pl) (M1 prec_list c0 pl0) ->\n c <> c0 ->\n state_reconnait d (M1 prec_list c pl) (app c tl) ->\n state_reconnait d (union_mpl_0 c pl (M1 prec_list c0 pl0)) (app c tl).\nProof.\n\tintros. unfold mpl_compat in H. inversion H1. apply (rec_st d (union_mpl_0 c pl (M1 prec_list c0 pl0)) c tl l). simpl in |- *. elim (bool_is_true_or_false (Neqb c c0)); intros; rewrite H8. elim (H0 (Neqb_complete c c0 H8)). elim (Ndiscr (Nxor c0 c)).\n\tintro y. elim y; intros x y0. rewrite y0. cut\n  (MapGet prec_list (MapPut1 prec_list c0 pl0 c pl x) c =\n    match Neqb c0 c with\n    | true => Some pl0\n    | false =>\n        match Neqb c c with\n        | true => Some pl\n        | false => None\n        end\n    end). intro. rewrite <- (Neqb_comm c c0) in H9.\n\trewrite H8 in H9. rewrite (Neqb_correct c) in H9. rewrite H9. simpl in H6.\n\trewrite (Neqb_correct c) in H6. inversion H6. trivial. exact (MapPut1_semantics prec_list x c0 c pl0 pl y0 c). intro y. rewrite (Neqb_comm c c0) in H8. rewrite (Nxor_eq_true c0 c y) in H8. inversion H8. assumption.\nQed.\n\nLemma union_s0d_2_0 :\n forall (d : preDTA) (pl : prec_list) (s0 s1 : state) (tl : term_list),\n mpl_compat (M1 prec_list N0 pl) (M2 prec_list s0 s1) ->\n state_reconnait d (M1 prec_list N0 pl) (app N0 tl) ->\n state_reconnait d (union_mpl_0 N0 pl (M2 prec_list s0 s1)) (app N0 tl).\nProof.\n\tintro. intro. simple induction s0. intros. simpl in |- *. inversion H0. apply (rec_st d (M2 prec_list (M1 prec_list N0 pl) s1) N0 tl l). simpl in |- *. simpl in H5. inversion H5. trivial.\n\tassumption. intros. unfold union_mpl_0 in |- *. elim (bool_is_true_or_false (Neqb N0 a)); intros; rewrite H1. apply\n  (rec_st d (M2 prec_list (M1 prec_list N0 (union_pl pl a0)) s1) N0 tl\n     (union_pl pl a0)). simpl in |- *. trivial. inversion H0. simpl in H6. inversion H6.\n\tapply (union_pl_0d d l a0 tl). apply (mpl_compat_0 N0 l a0). rewrite <- (Neqb_complete N0 a H1) in H. rewrite H9 in H. apply (mpl_compat_sym (M1 prec_list N0 a0) (M1 prec_list N0 l)). apply (mpl_compat_3 (M1 prec_list N0 a0) s1 l). apply\n  (mpl_compat_sym (M1 prec_list N0 l)\n     (M2 prec_list (M1 prec_list N0 a0) s1)). assumption. assumption. inversion H0.\n\tapply\n  (rec_st d\n     (M2 prec_list\n        (MapMerge prec_list (M1 prec_list N0 pl) (M1 prec_list a a0)) s1)\n     N0 tl l). cut\n  (MapGet prec_list\n     (MapMerge prec_list (M1 prec_list N0 pl) (M1 prec_list a a0)) N0 =\n   (fun a1 : ad =>\n    match MapGet prec_list (M1 prec_list a a0) a1 with\n    | None => MapGet prec_list (M1 prec_list N0 pl) a1\n    | Some y' => Some y'\n    end) N0). intro. cut\n  (MapGet prec_list\n     (M2 prec_list\n        (MapMerge prec_list (M1 prec_list N0 pl) (M1 prec_list a a0)) s1)\n     N0 =\n   MapGet prec_list\n     (MapMerge prec_list (M1 prec_list N0 pl) (M1 prec_list a a0)) N0). intros.\n\trewrite H9. rewrite H8. simpl in |- *. rewrite (Neqb_comm N0 a) in H1. rewrite H1. simpl in H6.\n\tinversion H6. trivial. simpl in |- *. trivial. exact\n  (MapMerge_semantics prec_list (M1 prec_list N0 pl) \n     (M1 prec_list a a0) N0). assumption. intros. simpl in |- *. simpl in H. cut\n  (state_reconnait d (M2 prec_list (union_mpl_0 N0 pl m) m0) (app N0 tl)). intro. inversion H3. apply\n  (rec_st d (M2 prec_list (M2 prec_list (union_mpl_0 N0 pl m) m0) s1) N0\n     tl l). simpl in |- *. assumption.\n\tassumption. apply (H m0 tl). apply (mpl_compat_sym (M2 prec_list m m0) (M1 prec_list N0 pl)).\n\tapply (mpl_compat_3 (M2 prec_list m m0) s1 pl). exact\n  (mpl_compat_sym (M1 prec_list N0 pl)\n     (M2 prec_list (M2 prec_list m m0) s1) H1). assumption.\nQed.\n\nLemma union_s0d_2_1 :\n forall (d : preDTA) (pl : prec_list) (s0 s1 : state) (tl : term_list),\n mpl_compat (M1 prec_list (Npos 1) pl) (M2 prec_list s0 s1) ->\n state_reconnait d (M1 prec_list (Npos 1) pl) (app (Npos 1) tl) ->\n state_reconnait d (union_mpl_0 (Npos 1) pl (M2 prec_list s0 s1))\n   (app (Npos 1) tl).\nProof.\n\tintros. cut (state_reconnait d (union_mpl_0 N0 pl s1) (app N0 tl)). simpl in |- *. intro.\n\tinversion H1. apply (rec_st d (M2 prec_list s0 (union_mpl_0 N0 pl s1)) (Npos 1) tl l).\n\tsimpl in |- *. assumption. assumption. induction  s1 as [| a a0| s1_1 Hrecs1_1 s1_0 Hrecs1_0]. apply (union_s0d_0 d N0 pl tl). apply (mpl_compat_sym (M0 prec_list) (M1 prec_list N0 pl)). apply (mpl_compat_4 s0 (M0 prec_list) pl). \n\texact\n  (mpl_compat_sym (M1 prec_list (Npos 1) pl) (M2 prec_list s0 (M0 prec_list))\n     H).\n\tinversion H0. simpl in H5. apply (rec_st d (M1 prec_list N0 pl) N0 tl pl). simpl in |- *.\n\ttrivial. inversion H5. assumption. elim (classic (N0 = a)). intro. rewrite <- H1. rewrite <- H1 in H. apply (union_s0d_1_0 d N0 pl a0 tl). apply (mpl_compat_sym (M1 prec_list N0 a0) (M1 prec_list N0 pl)). apply (mpl_compat_4 s0 (M1 prec_list N0 a0) pl). exact\n  (mpl_compat_sym (M1 prec_list (Npos 1) pl)\n     (M2 prec_list s0 (M1 prec_list N0 a0)) H). inversion H0.\n\tapply (rec_st d (M1 prec_list N0 pl) N0 tl pl). simpl in |- *. trivial. simpl in H6. inversion H6.\n\tassumption. intro. apply (union_s0d_1_1 d N0 pl a a0 tl). apply (mpl_compat_sym (M1 prec_list a a0) (M1 prec_list N0 pl)). apply (mpl_compat_4 s0 (M1 prec_list a a0) pl). exact\n  (mpl_compat_sym (M1 prec_list (Npos 1) pl)\n     (M2 prec_list s0 (M1 prec_list a a0)) H). assumption. inversion H0.\n\tapply (rec_st d (M1 prec_list N0 pl) N0 tl pl). simpl in |- *. trivial. simpl in H6. inversion H6.\n\tassumption. simpl in |- *. cut (state_reconnait d (union_mpl_0 N0 pl s1_1) (app N0 tl)). intro.\n\tinversion H1. apply (rec_st d (M2 prec_list (union_mpl_0 N0 pl s1_1) s1_0) N0 tl l).\n\tsimpl in |- *. assumption. assumption. apply Hrecs1_1. cut (mpl_compat (M1 prec_list N0 pl) s1_1).\n\tintro. unfold mpl_compat in |- *. intros. unfold mpl_compat in H1. unfold MapGet in H2. elim (bool_is_true_or_false (Neqb (Npos 1) c)); intro; rewrite H4 in H2;\n  inversion H2.\n\tapply (H1 N0 p0 p1). simpl in |- *. rewrite H6. trivial. rewrite <- (Neqb_complete (Npos 1) c H4) in H3. simpl in H3. assumption. apply (mpl_compat_sym s1_1 (M1 prec_list N0 pl)).\n\tapply (mpl_compat_3 s1_1 s1_0 pl). apply (mpl_compat_4 s0 (M2 prec_list s1_1 s1_0) pl).\n\texact\n  (mpl_compat_sym (M1 prec_list (Npos 1) pl)\n     (M2 prec_list s0 (M2 prec_list s1_1 s1_0)) H).\nQed.\n\nDefinition union_s_prd0 (s : state) : Prop :=\n  forall (d : preDTA) (c : ad) (pl : prec_list) (tl : term_list),\n  mpl_compat (M1 prec_list c pl) s ->\n  state_reconnait d (M1 prec_list c pl) (app c tl) ->\n  state_reconnait d (union_mpl_0 c pl s) (app c tl).\n\nLemma union_s0d_2 :\n forall m : Map prec_list,\n union_s_prd0 m ->\n forall m0 : Map prec_list,\n union_s_prd0 m0 -> union_s_prd0 (M2 prec_list m m0).\nProof.\n\tunfold union_s_prd0 in |- *. intros. induction  c as [| p]. exact (union_s0d_2_0 d pl m m0 tl H1 H2).\n\tinduction  p as [p Hrecp| p Hrecp| ]. simpl in |- *. cut (state_reconnait d (union_mpl_0 (Npos p) pl m0) (app (Npos p) tl)). intro. inversion H3. apply\n  (rec_st d (M2 prec_list m (union_mpl_0 (Npos p) pl m0)) (Npos (xI p)) tl l). simpl in |- *. assumption. assumption. apply (H0 d (Npos p) pl tl).\n\tapply (mpl_compat_sym m0 (M1 prec_list (Npos p) pl)). exact\n  (mpl_compat_6 m m0 pl p\n     (mpl_compat_sym (M1 prec_list (Npos (xI p)) pl) (M2 prec_list m m0) H1)). inversion H2.\n\tsimpl in H7. rewrite (aux_Neqb_1_0 p) in H7. inversion H7. apply (rec_st d (M1 prec_list (Npos p) l) (Npos p) tl l). simpl in |- *. rewrite (aux_Neqb_1_0 p). trivial. assumption.\n\tsimpl in |- *. cut (state_reconnait d (union_mpl_0 (Npos p) pl m) (app (Npos p) tl)). intro.\n\tinversion H3. apply\n  (rec_st d (M2 prec_list (union_mpl_0 (Npos p) pl m) m0) (Npos (xO p)) tl l). simpl in |- *. assumption. assumption. apply (H d (Npos p) pl tl). apply (mpl_compat_sym m (M1 prec_list (Npos p) pl)). exact\n  (mpl_compat_5 m m0 pl p\n     (mpl_compat_sym (M1 prec_list (Npos (xO p)) pl) (M2 prec_list m m0) H1)). inversion H2. apply (rec_st d (M1 prec_list (Npos p) pl) (Npos p) tl l). simpl in |- *. rewrite (aux_Neqb_1_0 p). simpl in H7. rewrite (aux_Neqb_1_0 p) in H7. inversion H7. trivial. assumption. \n\texact (union_s0d_2_1 d pl m m0 tl H1 H2).\nQed.\n\nLemma union_s0d_3 : union_s_prd0 (M0 prec_list).\nProof.\n\tunfold union_s_prd0 in |- *. intros. exact (union_s0d_0 d c pl tl H H0).\nQed.\n\nLemma union_s0d_1 :\n forall (a : ad) (a0 : prec_list), union_s_prd0 (M1 prec_list a a0).\nProof.\n\tunfold union_s_prd0 in |- *. intros. elim (classic (a = c)). intro. rewrite H1. rewrite H1 in H.\n\texact (union_s0d_1_0 d c pl a0 tl H H0). intro. apply (union_s0d_1_1 d c pl a a0 tl). \n\tassumption. intro. exact (H1 (sym_eq H2)). assumption.\nQed.\n\nLemma union_s_0d : forall m : state, union_s_prd0 m.\nProof.\n\texact (Map_ind prec_list union_s_prd0 union_s0d_3 union_s0d_1 union_s0d_2).\nQed.\n\nLemma union_s0d :\n forall (s : state) (d : preDTA) (c : ad) (pl : prec_list) (tl : term_list),\n mpl_compat (M1 prec_list c pl) s ->\n state_reconnait d (M1 prec_list c pl) (app c tl) ->\n state_reconnait d (union_mpl_0 c pl s) (app c tl).\nProof.\n\tintro. exact (union_s_0d s).\nQed.\n\n(* invariant sur union_mpl_0, sens direct, 1 *)\n\nDefinition union_s_prd1 (s : state) : Prop :=\n  forall (d : preDTA) (a : ad) (pl : prec_list) (c : ad) (tl : term_list),\n  mpl_compat (M1 prec_list a pl) s ->\n  state_reconnait d s (app c tl) ->\n  state_reconnait d (union_mpl_0 a pl s) (app c tl).\n\nLemma union_s1d_0 : union_s_prd1 (M0 prec_list).\nProof.\n\tunfold union_s_prd1 in |- *. intros. inversion H0. simpl in H5. inversion H5.\nQed.\n\nLemma union_s1d_1_0 :\n forall (d : preDTA) (a : ad) (pl pl0 : prec_list) (c : ad) (tl : term_list),\n mpl_compat (M1 prec_list a pl) (M1 prec_list c pl0) ->\n a <> c ->\n state_reconnait d (M1 prec_list c pl0) (app c tl) ->\n state_reconnait d (union_mpl_0 a pl (M1 prec_list c pl0)) (app c tl).\nProof.\n\tintros. simpl in |- *. elim (bool_is_true_or_false (Neqb a c)). intro. \n\telim (H0 (Neqb_complete a c H2)). intro. rewrite H2. \n\telim (Ndiscr (Nxor c a)); intro y. elim y. intros x y0. rewrite y0. inversion H1.\n\tapply (rec_st d (MapPut1 prec_list c pl0 a pl x) c tl l).\n\trewrite (MapPut1_semantics prec_list x c a pl0 pl y0 c). rewrite (Neqb_correct c).\n\tsimpl in H7. rewrite (Neqb_correct c) in H7. inversion H7. trivial. trivial.\n\trewrite (Nxor_comm c a) in y. rewrite (Nxor_eq_true a c y) in H2.\n\tinversion H2.\nQed.\n\nLemma union_s1d_1_1 :\n forall (d : preDTA) (pl pl0 : prec_list) (c : ad) (tl : term_list),\n mpl_compat (M1 prec_list c pl) (M1 prec_list c pl0) ->\n state_reconnait d (M1 prec_list c pl0) (app c tl) ->\n state_reconnait d (union_mpl_0 c pl (M1 prec_list c pl0)) (app c tl).\nProof.\n\tintros. simpl in |- *. rewrite (Neqb_correct c). apply (rec_st d (M1 prec_list c (union_pl pl pl0)) c tl (union_pl pl pl0)). simpl in |- *. rewrite (Neqb_correct c). trivial.\n\tinversion H0. simpl in H5. rewrite (Neqb_correct c) in H5. inversion H5.\n\tapply (union_pl_1d d pl l tl). rewrite H8 in H. exact (mpl_compat_0 c pl l H).\n\tassumption.\nQed.\n\nLemma union_s1d_1 :\n forall (a : ad) (a0 : prec_list), union_s_prd1 (M1 prec_list a a0).\nProof.\n\tunfold union_s_prd1 in |- *. intros. cut (a = c). intro. rewrite H1 in H. rewrite H1 in H0.\n\trewrite H1. elim (classic (a1 = c)). intro. rewrite H2. rewrite H2 in H.\n\texact (union_s1d_1_1 d pl a0 c tl H H0). intro. exact (union_s1d_1_0 d a1 pl a0 c tl H H2 H0). inversion H0. simpl in H5. elim (bool_is_true_or_false (Neqb a c)).\n\tintro. exact (Neqb_complete a c H7). intro. rewrite H7 in H5. inversion H5.\nQed.\n\nLemma union_s1d_2 :\n forall m : state,\n union_s_prd1 m ->\n forall m0 : state, union_s_prd1 m0 -> union_s_prd1 (M2 prec_list m m0).\nProof.\n\tunfold union_s_prd1 in |- *. intros. induction  c as [| p]. induction  a as [| p]. simpl in |- *. cut (state_reconnait d (union_mpl_0 N0 pl m) (app N0 tl)). intro. inversion H3. apply (rec_st d (M2 prec_list (union_mpl_0 N0 pl m) m0) N0 tl l). simpl in |- *. assumption. assumption.\n\tapply (H d N0 pl N0 tl). apply (mpl_compat_sym m (M1 prec_list N0 pl)).\n\tapply (mpl_compat_3 m m0 pl). exact (mpl_compat_sym (M1 prec_list N0 pl) (M2 prec_list m m0) H1). inversion H2. apply (rec_st d m N0 tl l). simpl in H7.\n\tassumption. assumption. induction  p as [p Hrecp| p Hrecp| ]. simpl in |- *. inversion H2.\n\tapply (rec_st d (M2 prec_list m (union_mpl_0 (Npos p) pl m0)) N0 tl l). simpl in |- *.\n\tsimpl in H7. assumption. assumption. simpl in |- *. cut (state_reconnait d (union_mpl_0 (Npos p) pl m) (app N0 tl)). intro. inversion H3. apply (rec_st d (M2 prec_list (union_mpl_0 (Npos p) pl m) m0) N0 tl l). simpl in |- *. assumption. assumption. \n\tapply (H d (Npos p) pl N0 tl). apply (mpl_compat_sym m (M1 prec_list (Npos p) pl)).\n\tapply (mpl_compat_5 m m0 pl p). exact\n  (mpl_compat_sym (M1 prec_list (Npos (xO p)) pl) (M2 prec_list m m0) H1). inversion H2. simpl in H7. exact (rec_st d m N0 tl l H7 H8).\n\tsimpl in |- *. inversion H2. apply (rec_st d (M2 prec_list m (union_mpl_0 N0 pl m0)) N0 tl l).\n\tsimpl in |- *. simpl in H7. assumption. assumption. induction  p as [p Hrecp| p Hrecp| ]. induction  a as [| p0]. simpl in |- *. inversion H2.\n\tapply\n  (rec_st d (M2 prec_list (union_mpl_0 N0 pl m) m0) (Npos (xI p)) tl l). simpl in |- *.\n\tsimpl in H7. assumption. assumption. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in |- *. cut (state_reconnait d (union_mpl_0 (Npos p0) pl m0) (app (Npos p) tl)). intro. inversion H3. apply\n  (rec_st d (M2 prec_list m (union_mpl_0 (Npos p0) pl m0)) (Npos (xI p)) tl l). simpl in |- *. assumption. assumption.\n\tapply (H0 d (Npos p0) pl (Npos p) tl). apply (mpl_compat_sym m0 (M1 prec_list (Npos p0) pl)).\n\tapply (mpl_compat_6 m m0 pl p0). exact\n  (mpl_compat_sym (M1 prec_list (Npos (xI p0)) pl) (M2 prec_list m m0) H1). inversion H2. simpl in H7. exact (rec_st d m0 (Npos p) tl l H7 H8).\n\tsimpl in |- *. inversion H2. apply\n  (rec_st d (M2 prec_list (union_mpl_0 (Npos p0) pl m) m0) (Npos (xI p)) tl l). simpl in |- *. simpl in H7. assumption. assumption. simpl in |- *.\n\tcut (state_reconnait d (union_mpl_0 N0 pl m0) (app (Npos p) tl)). intro. inversion H3.\n\tapply\n  (rec_st d (M2 prec_list m (union_mpl_0 N0 pl m0)) (Npos (xI p)) tl l). simpl in |- *.\n\tassumption. assumption. apply (H0 d N0 pl (Npos p) tl). apply (mpl_compat_sym m0 (M1 prec_list N0 pl)). apply (mpl_compat_4 m m0 pl). exact (mpl_compat_sym (M1 prec_list (Npos 1) pl) (M2 prec_list m m0) H1). inversion H2. simpl in H7. exact (rec_st d m0 (Npos p) tl l H7 H8). induction  a as [| p0]. simpl in |- *. cut (state_reconnait d (union_mpl_0 N0 pl m) (app (Npos p) tl)).\n\tintro. inversion H3. apply\n  (rec_st d (M2 prec_list (union_mpl_0 N0 pl m) m0) (Npos (xO p)) tl l).\n\tsimpl in |- *. assumption. assumption. apply (H d N0 pl (Npos p) tl). apply (mpl_compat_sym m (M1 prec_list N0 pl)). apply (mpl_compat_3 m m0 pl). exact (mpl_compat_sym (M1 prec_list N0 pl) (M2 prec_list m m0) H1). inversion H2. simpl in H7. exact (rec_st d m (Npos p) tl l H7 H8).\n\tinduction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in |- *. inversion H2. apply\n  (rec_st d (M2 prec_list m (union_mpl_0 (Npos p0) pl m0)) (Npos (xO p)) tl l). simpl in |- *. simpl in H7. assumption. assumption. simpl in |- *.\n\tcut (state_reconnait d (union_mpl_0 (Npos p0) pl m) (app (Npos p) tl)). intro. inversion H3.\n\tapply\n  (rec_st d (M2 prec_list (union_mpl_0 (Npos p0) pl m) m0) (Npos (xO p)) tl l). simpl in |- *.\n\tsimpl in H8. assumption. assumption. apply (H d (Npos p0) pl (Npos p) tl). \n\tapply (mpl_compat_sym m (M1 prec_list (Npos p0) pl)). apply (mpl_compat_5 m m0 pl p0). \n\texact\n  (mpl_compat_sym (M1 prec_list (Npos (xO p0)) pl) (M2 prec_list m m0) H1). inversion H2. \n\tsimpl in H7. exact (rec_st d m (Npos p) tl l H7 H8). simpl in |- *. inversion H2. simpl in H7.\n\tapply\n  (rec_st d (M2 prec_list m (union_mpl_0 N0 pl m0)) (Npos (xO p)) tl l). simpl in |- *.\n\tassumption. assumption. induction  a as [| p]. simpl in |- *. inversion H2. simpl in H7.\n\tapply (rec_st d (M2 prec_list (union_mpl_0 N0 pl m) m0) (Npos 1) tl l). simpl in |- *. assumption.\n\tassumption. induction  p as [p Hrecp| p Hrecp| ]. simpl in |- *. cut (state_reconnait d (union_mpl_0 (Npos p) pl m0) (app N0 tl)).\n\tintro. inversion H3. apply (rec_st d (M2 prec_list m (union_mpl_0 (Npos p) pl m0)) (Npos 1) tl l).\n\tsimpl in |- *. simpl in H8. assumption. assumption. apply (H0 d (Npos p) pl N0 tl).\n\tapply (mpl_compat_sym m0 (M1 prec_list (Npos p) pl)). apply (mpl_compat_6 m m0 pl p).\n\texact\n  (mpl_compat_sym (M1 prec_list (Npos (xI p)) pl) (M2 prec_list m m0) H1). inversion H2.\n\tsimpl in H7. exact (rec_st d m0 N0 tl l H7 H8). simpl in |- *. inversion H2. simpl in H7.\n\tapply (rec_st d (M2 prec_list (union_mpl_0 (Npos p) pl m) m0) (Npos 1) tl l). simpl in |- *.\n\tassumption. assumption. simpl in |- *. cut (state_reconnait d (union_mpl_0 N0 pl m0) (app N0 tl)).\n\tintro. inversion H3. apply (rec_st d (M2 prec_list m (union_mpl_0 N0 pl m0)) (Npos 1) tl l).\n\tsimpl in |- *. assumption. assumption. apply (H0 d N0 pl N0 tl). \n\tapply (mpl_compat_sym m0 (M1 prec_list N0 pl)). apply (mpl_compat_4 m m0 pl).\n\texact (mpl_compat_sym (M1 prec_list (Npos 1) pl) (M2 prec_list m m0) H1).\n\tinversion H2. simpl in H7. exact (rec_st d m0 N0 tl l H7 H8).\nQed.\n\nLemma union_s1d_3 : forall m : state, union_s_prd1 m.\nProof.\n\texact (Map_ind prec_list union_s_prd1 union_s1d_0 union_s1d_1 union_s1d_2).\nQed.\n\nLemma union_s1d :\n forall (s : state) (d : preDTA) (a : ad) (pl : prec_list) \n   (c : ad) (tl : term_list),\n mpl_compat (M1 prec_list a pl) s ->\n state_reconnait d s (app c tl) ->\n state_reconnait d (union_mpl_0 a pl s) (app c tl).\nProof.\n\tintro. exact (union_s1d_3 s).\nQed.\n\nDefinition union_std_def (s0 : state) : Prop :=\n  forall (s1 : state) (d : preDTA) (c : ad) (tl : term_list),\n  mpl_compat s0 s1 ->\n  state_reconnait d s0 (app c tl) ->\n  state_reconnait d (union_mpl s0 s1) (app c tl) /\\\n  state_reconnait d (union_mpl s1 s0) (app c tl).\n\nLemma union_std_0 : union_std_def (M0 prec_list).\nProof.\n\tunfold union_std_def in |- *. intros. inversion H0. inversion H5.\nQed.\n\nLemma union_std_1 :\n forall (a : ad) (a0 : prec_list), union_std_def (M1 prec_list a a0).\nProof.\n\tunfold union_std_def in |- *. intros. split. induction  s1 as [| a1 a2| s1_1 Hrecs1_1 s1_0 Hrecs1_0]. unfold union_mpl in |- *. cut (a = c).\n\tintro. rewrite H1. rewrite H1 in H. rewrite H1 in H0. exact (union_s0d (M0 prec_list) d c a0 tl H H0). inversion H0. simpl in H5.\n\telim (bool_is_true_or_false (Neqb a c)); intro. exact (Neqb_complete a c H7).\n\trewrite H7 in H5. inversion H5. unfold union_mpl in |- *.\n\texact\n  (union_s1d (M1 prec_list a a0) d a1 a2 c tl\n     (mpl_compat_sym (M1 prec_list a a0) (M1 prec_list a1 a2) H) H0). unfold union_mpl in |- *. cut (a = c). intro. rewrite H1.\n\trewrite H1 in H. rewrite H1 in H0. exact (union_s0d (M2 prec_list s1_1 s1_0) d c a0 tl H H0).\n\tinversion H0. simpl in H5. elim (bool_is_true_or_false (Neqb a c)). intro.\n\texact (Neqb_complete a c H7). intro. rewrite H7 in H5. inversion H5. induction  s1 as [| a1 a2| s1_1 Hrecs1_1 s1_0 Hrecs1_0].\n\tunfold union_mpl in |- *. cut (a = c). intro. rewrite H1. rewrite H1 in H. rewrite H1 in H0.\n\texact (union_s0d (M0 prec_list) d c a0 tl H H0). inversion H0. simpl in H5.\n\telim (bool_is_true_or_false (Neqb a c)). intro. exact (Neqb_complete a c H7).\n\tintro. rewrite H7 in H5. inversion H5. unfold union_mpl in |- *. cut (a = c). intro.\n\trewrite H1. rewrite H1 in H. rewrite H1 in H0. exact (union_s0d (M1 prec_list a1 a2) d c a0 tl H H0). inversion H0. simpl in H5. elim (bool_is_true_or_false (Neqb a c)).\n\tintro. exact (Neqb_complete a c H7). intro. rewrite H7 in H5. inversion H5.\n\tcut (a = c). intro. rewrite H1 in H. rewrite H1 in H0. rewrite H1.\n\texact (union_s0d (M2 prec_list s1_1 s1_0) d c a0 tl H H0). inversion H0.\n\telim (bool_is_true_or_false (Neqb a c)). intro. exact (Neqb_complete a c H7).\n\tintro. simpl in H5. rewrite H7 in H5. inversion H5.\nQed.\n\nLemma union_std_2 :\n forall m : state,\n union_std_def m ->\n forall m0 : state, union_std_def m0 -> union_std_def (M2 prec_list m m0).\nProof.\n\tunfold union_std_def in |- *. intros. induction  s1 as [| a a0| s1_1 Hrecs1_1 s1_0 Hrecs1_0]. simpl in |- *. split. assumption.\n\tassumption. unfold union_mpl in |- *. induction  c as [| p]. induction  a as [| p]. simpl in |- *.\n\tcut\n  (state_reconnait d (M2 prec_list (union_mpl_0 N0 a0 m) m0) (app N0 tl)).\n\tintro. split. assumption.  assumption. cut (state_reconnait d (union_mpl_0 N0 a0 m) (app N0 tl)). intro. inversion H3. apply (rec_st d (M2 prec_list (union_mpl_0 N0 a0 m) m0) N0 tl l). simpl in |- *. assumption. assumption.\n\tcut\n  (state_reconnait d (union_mpl m (M1 prec_list N0 a0)) (app N0 tl) /\\\n   state_reconnait d (union_mpl (M1 prec_list N0 a0) m) (app N0 tl)).\n\tintro. elim H3. intros. unfold union_mpl in H4. induction  m as [| a a1| m1 Hrecm1 m2 Hrecm0]. assumption.\n\tassumption. assumption. apply (H (M1 prec_list N0 a0) d N0 tl).\n\texact (mpl_compat_3 m m0 a0 H1). inversion H2. simpl in H7.\n\texact (rec_st d m N0 tl l H7 H8). induction  p as [p Hrecp| p Hrecp| ]. cut\n  (state_reconnait d (union_mpl_0 (Npos (xI p)) a0 (M2 prec_list m m0))\n     (app N0 tl)). intro.\n\tsplit. assumption. assumption. simpl in |- *. inversion H2. simpl in H7.\n\tapply (rec_st d (M2 prec_list m (union_mpl_0 (Npos p) a0 m0)) N0 tl l).\n\tsimpl in |- *. assumption. assumption. cut\n  (state_reconnait d (union_mpl_0 (Npos (xO p)) a0 (M2 prec_list m m0))\n     (app N0 tl)). intro. split. assumption. assumption.\n\tsimpl in |- *. cut\n  (state_reconnait d (union_mpl m (M1 prec_list (Npos p) a0)) (app N0 tl) /\\\n   state_reconnait d (union_mpl (M1 prec_list (Npos p) a0) m) (app N0 tl)). intro. elim H3. intros. simpl in |- *. cut (state_reconnait d (union_mpl_0 (Npos p) a0 m) (app N0 tl)). intro. inversion H6.\n\tapply (rec_st d (M2 prec_list (union_mpl_0 (Npos p) a0 m) m0) N0 tl l).\n\tsimpl in |- *. assumption. assumption. induction  m as [| a a1| m1 Hrecm1 m2 Hrecm0]. assumption. assumption.\n\tassumption. apply (H (M1 prec_list (Npos p) a0) d N0 tl).\n\texact (mpl_compat_5 m m0 a0 p H1). inversion H2. simpl in H7. exact (rec_st d m N0 tl l H7 H8). cut\n  (state_reconnait d (union_mpl_0 (Npos 1) a0 (M2 prec_list m m0))\n     (app N0 tl)). intros. split. assumption. assumption. inversion H2.\n\tapply (rec_st d (union_mpl_0 (Npos 1) a0 (M2 prec_list m m0)) N0 tl l).\n\tsimpl in |- *. simpl in H7. assumption. assumption. induction  p as [p Hrecp| p Hrecp| ]. induction  a as [| p0].\n\tcut\n  (state_reconnait d (union_mpl_0 N0 a0 (M2 prec_list m m0))\n     (app (Npos (xI p)) tl)).\n\tintro. split. assumption. assumption. simpl in |- *. inversion H2.\n\tapply\n  (rec_st d (M2 prec_list (union_mpl_0 N0 a0 m) m0) (Npos (xI p)) tl l).\n\tsimpl in |- *. assumption. assumption. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. cut\n  (state_reconnait d (union_mpl_0 (Npos (xI p0)) a0 (M2 prec_list m m0))\n     (app (Npos (xI p)) tl)).\n\tintro. split. assumption. assumption. simpl in |- *. cut\n  (state_reconnait d (union_mpl m0 (M1 prec_list (Npos p0) a0))\n     (app (Npos p) tl) /\\\n   state_reconnait d (union_mpl (M1 prec_list (Npos p0) a0) m0)\n     (app (Npos p) tl)). intros. elim H3. intros.\n\tcut (state_reconnait d (union_mpl_0 (Npos p0) a0 m0) (app (Npos p) tl)). intro.\n\tinversion H6. apply\n  (rec_st d (M2 prec_list m (union_mpl_0 (Npos p0) a0 m0)) (Npos (xI p)) tl l). simpl in |- *. assumption. assumption. induction  m0 as [| a a1| m0_1 Hrecm0_1 m0_0 Hrecm0_0]; assumption.\n\tapply (H0 (M1 prec_list (Npos p0) a0) d (Npos p) tl). exact (mpl_compat_6 m m0 a0 p0 H1).\n\tinversion H2. simpl in H7. exact (rec_st d m0 (Npos p) tl l H7 H8).\n\tcut\n  (state_reconnait d (union_mpl_0 (Npos (xO p0)) a0 (M2 prec_list m m0))\n     (app (Npos (xI p)) tl)). intro. split. assumption. assumption. simpl in |- *.\n\tinversion H2. apply\n  (rec_st d (M2 prec_list (union_mpl_0 (Npos p0) a0 m) m0) (Npos (xI p)) tl l). simpl in |- *. simpl in H7. assumption. assumption.\n\tcut\n  (state_reconnait d (union_mpl_0 (Npos 1) a0 (M2 prec_list m m0))\n     (app (Npos (xI p)) tl)). intro. split; assumption. simpl in |- *.\n\tcut\n  (state_reconnait d (union_mpl m0 (M1 prec_list N0 a0)) (app (Npos p) tl) /\\\n   state_reconnait d (union_mpl (M1 prec_list N0 a0) m0) (app (Npos p) tl)).\n\tintro. elim H3. intros. cut (state_reconnait d (union_mpl_0 N0 a0 m0) (app (Npos p) tl)). intro. inversion H6. apply\n  (rec_st d (M2 prec_list m (union_mpl_0 N0 a0 m0)) (Npos (xI p)) tl l). simpl in |- *. assumption. assumption.\n\tinduction  m0 as [| a a1| m0_1 Hrecm0_1 m0_0 Hrecm0_0]; assumption. apply (H0 (M1 prec_list N0 a0) d (Npos p) tl).\n\texact (mpl_compat_4 m m0 a0 H1). inversion H2. simpl in H7. exact (rec_st d m0 (Npos p) tl l H7 H8). induction  a as [| p0]. cut\n  (state_reconnait d (union_mpl_0 N0 a0 (M2 prec_list m m0))\n     (app (Npos (xO p)) tl)). intro. split; assumption. simpl in |- *.\n\tcut (state_reconnait d (union_mpl_0 N0 a0 m) (app (Npos p) tl)). intro. \n\tinversion H3. apply\n  (rec_st d (M2 prec_list (union_mpl_0 N0 a0 m) m0) (Npos (xO p)) tl l). simpl in |- *. assumption. assumption. cut\n  (state_reconnait d (union_mpl m (M1 prec_list N0 a0)) (app (Npos p) tl) /\\\n   state_reconnait d (union_mpl (M1 prec_list N0 a0) m) (app (Npos p) tl)). intro. elim H3. intros. induction  m as [| a a1| m1 Hrecm1 m2 Hrecm0]; assumption.\n\tapply (H (M1 prec_list N0 a0) d (Npos p) tl). exact (mpl_compat_3 m m0 a0 H1).\n\tinversion H2. simpl in H7. exact (rec_st d m (Npos p) tl l H7 H8). induction  p0 as [p0 Hrecp0| p0 Hrecp0| ].\n\tcut\n  (state_reconnait d (union_mpl_0 (Npos (xI p0)) a0 (M2 prec_list m m0))\n     (app (Npos (xO p)) tl)). intro. split; assumption. simpl in |- *. inversion H2.\n\tapply\n  (rec_st d (M2 prec_list m (union_mpl_0 (Npos p0) a0 m0)) (Npos (xO p)) tl l).\n\tsimpl in |- *. assumption. assumption. cut\n  (state_reconnait d (union_mpl_0 (Npos (xO p0)) a0 (M2 prec_list m m0))\n     (app (Npos (xO p)) tl)). intros. split; assumption. simpl in |- *.\n\tcut (state_reconnait d (union_mpl_0 (Npos p0) a0 m) (app (Npos p) tl)). intro.\n\tinversion H3. apply\n  (rec_st d (M2 prec_list (union_mpl_0 (Npos p0) a0 m) m0) (Npos (xO p)) tl l). simpl in |- *. simpl in H8. assumption. assumption.\n\tcut\n  (state_reconnait d (union_mpl m (M1 prec_list (Npos p0) a0))\n     (app (Npos p) tl) /\\\n   state_reconnait d (union_mpl (M1 prec_list (Npos p0) a0) m)\n     (app (Npos p) tl)).\n\tintro. elim H3. intros. induction  m as [| a a1| m1 Hrecm1 m2 Hrecm0]; assumption. apply (H (M1 prec_list (Npos p0) a0) d (Npos p) tl). exact (mpl_compat_5 m m0 a0 p0 H1). inversion H2. simpl in H7.\n\texact (rec_st d m (Npos p) tl l H7 H8). cut\n  (state_reconnait d (union_mpl_0 (Npos 1) a0 (M2 prec_list m m0))\n     (app (Npos (xO p)) tl)). intro. split; assumption. simpl in |- *.\n\tinversion H2. apply\n  (rec_st d (M2 prec_list m (union_mpl_0 N0 a0 m0)) (Npos (xO p)) tl l). simpl in H7. simpl in |- *. assumption. assumption. induction  a as [| p]. cut\n  (state_reconnait d (union_mpl_0 N0 a0 (M2 prec_list m m0))\n     (app (Npos 1) tl)). intro. split; assumption.\n\tsimpl in |- *. inversion H2. apply (rec_st d (M2 prec_list (union_mpl_0 N0 a0 m) m0) (Npos 1) tl l). simpl in |- *. simpl in H7. assumption. assumption. cut\n  (state_reconnait d (union_mpl_0 (Npos p) a0 (M2 prec_list m m0))\n     (app (Npos 1) tl)). intro. split; assumption.\n\tinduction  p as [p Hrecp| p Hrecp| ]. simpl in |- *. cut (state_reconnait d (union_mpl_0 (Npos p) a0 m0) (app N0 tl)).\n\tintro. inversion H3. apply (rec_st d (M2 prec_list m (union_mpl_0 (Npos p) a0 m0)) (Npos 1) tl l). simpl in |- *. simpl in H8. assumption. assumption.\n\tcut\n  (state_reconnait d (union_mpl m0 (M1 prec_list (Npos p) a0)) (app N0 tl) /\\\n   state_reconnait d (union_mpl (M1 prec_list (Npos p) a0) m0) (app N0 tl)).\n\tintro. elim H3. intros. induction  m0 as [| a a1| m0_1 Hrecm0_1 m0_0 Hrecm0_0]; assumption. apply (H0 (M1 prec_list (Npos p) a0) d N0 tl). exact (mpl_compat_6 m m0 a0 p H1). inversion H2. simpl in H7.\n\texact (rec_st d m0 N0 tl l H7 H8). simpl in |- *. inversion H2. apply (rec_st d (M2 prec_list (union_mpl_0 (Npos p) a0 m) m0) (Npos 1) tl l). simpl in |- *. simpl in H7. assumption.\n\tassumption. simpl in |- *. cut (state_reconnait d (union_mpl_0 N0 a0 m0) (app N0 tl)).\n\tintro. inversion H3. apply (rec_st d (M2 prec_list m (union_mpl_0 N0 a0 m0)) (Npos 1) tl l). simpl in |- *. simpl in H8. assumption. assumption. cut\n  (state_reconnait d (union_mpl m0 (M1 prec_list N0 a0)) (app N0 tl) /\\\n   state_reconnait d (union_mpl (M1 prec_list N0 a0) m0) (app N0 tl)). intro. elim H3. intros. induction  m0 as [| a a1| m0_1 Hrecm0_1 m0_0 Hrecm0_0]; assumption.\n\tapply (H0 (M1 prec_list N0 a0) d N0 tl). exact (mpl_compat_4 m m0 a0 H1).\n\tinversion H2. simpl in H7. exact (rec_st d m0 N0 tl l H7 H8). simpl in |- *. cut (mpl_compat m s1_1).\n\tcut (mpl_compat m0 s1_0). intros. induction  c as [| p]. cut\n  (state_reconnait d (union_mpl m s1_1) (app N0 tl) /\\\n   state_reconnait d (union_mpl s1_1 m) (app N0 tl)). intro. elim H5.\n\tintros. split. inversion H6. apply\n  (rec_st d (M2 prec_list (union_mpl m s1_1) (union_mpl m0 s1_0)) N0 tl l). simpl in |- *. assumption. assumption. inversion H7. apply\n  (rec_st d (M2 prec_list (union_mpl s1_1 m) (union_mpl s1_0 m0)) N0 tl l). simpl in |- *. assumption. assumption.\n\tapply (H s1_1 d N0 tl H4). inversion H2. simpl in H9. exact (rec_st d m N0 tl l H9 H10).\n\tinduction  p as [p Hrecp| p Hrecp| ]. cut\n  (state_reconnait d (union_mpl m0 s1_0) (app (Npos p) tl) /\\\n   state_reconnait d (union_mpl s1_0 m0) (app (Npos p) tl)). intro. elim H5. intros. \n\tsplit. inversion H6. apply\n  (rec_st d (M2 prec_list (union_mpl m s1_1) (union_mpl m0 s1_0))\n     (Npos (xI p)) tl l). simpl in |- *. assumption. assumption. inversion H7. apply\n  (rec_st d (M2 prec_list (union_mpl s1_1 m) (union_mpl s1_0 m0))\n     (Npos (xI p)) tl l). simpl in |- *.\n\tassumption. assumption. apply (H0 s1_0 d (Npos p) tl H3). inversion H2. simpl in H9.\n\texact (rec_st d m0 (Npos p) tl l H9 H10). cut\n  (state_reconnait d (union_mpl m s1_1) (app (Npos p) tl) /\\\n   state_reconnait d (union_mpl s1_1 m) (app (Npos p) tl)). intro.\n\telim H5. intros. split. inversion H6. apply\n  (rec_st d (M2 prec_list (union_mpl m s1_1) (union_mpl m0 s1_0))\n     (Npos (xO p)) tl l). simpl in |- *. assumption. assumption. inversion H7.\n\tapply\n  (rec_st d (M2 prec_list (union_mpl s1_1 m) (union_mpl s1_0 m0))\n     (Npos (xO p)) tl l).\n\tsimpl in |- *. assumption. assumption. apply (H s1_1 d (Npos p) tl H4). inversion H2. simpl in H9.\n\texact (rec_st d m (Npos p) tl l H9 H10). cut\n  (state_reconnait d (union_mpl m0 s1_0) (app N0 tl) /\\\n   state_reconnait d (union_mpl s1_0 m0) (app N0 tl)). intro. elim H5. intros. split.\n\tinversion H6. apply\n  (rec_st d (M2 prec_list (union_mpl m s1_1) (union_mpl m0 s1_0)) \n     (Npos 1) tl l). simpl in |- *. assumption. assumption. inversion H7. apply\n  (rec_st d (M2 prec_list (union_mpl s1_1 m) (union_mpl s1_0 m0)) \n     (Npos 1) tl l). simpl in |- *. assumption. assumption.\n\tapply (H0 s1_0 d N0 tl H3). inversion H2. simpl in H9. exact (rec_st d m0 N0 tl l H9 H10).\n\texact (mpl_compat_2 m m0 s1_1 s1_0 H1). exact (mpl_compat_1 m m0 s1_1 s1_0 H1).\nQed.\n\nLemma union_std : forall m : state, union_std_def m.\nProof.\n\texact (Map_ind prec_list union_std_def union_std_0 union_std_1 union_std_2).\nQed.\n\nLemma union_sd :\n forall (s0 s1 : state) (d : preDTA) (c : ad) (tl : term_list),\n mpl_compat s0 s1 ->\n state_reconnait d s0 (app c tl) ->\n state_reconnait d (union_mpl s0 s1) (app c tl) /\\\n state_reconnait d (union_mpl s1 s0) (app c tl).\nProof.\n\tintro. exact (union_std s0).\nQed.\n\nDefinition union_s_rpl_def (s : state) : Prop :=\n  forall (d : preDTA) (a : ad) (pl : prec_list) (c : ad) (tl : term_list),\n  mpl_compat (M1 prec_list a pl) s ->\n  state_reconnait d (union_mpl_0 a pl s) (app c tl) ->\n  state_reconnait d (M1 prec_list a pl) (app c tl) \\/\n  state_reconnait d s (app c tl).\n\nLemma union_s_rpl_0 : union_s_rpl_def (M0 prec_list).\nProof.\n\tunfold union_s_rpl_def in |- *. intros. simpl in H0. left. assumption.\nQed.\n\nLemma union_s_rpl_1 :\n forall (a : ad) (a0 : prec_list), union_s_rpl_def (M1 prec_list a a0).\nProof.\n\tunfold union_s_rpl_def in |- *. intros. simpl in H0. elim (bool_is_true_or_false (Neqb a1 a)); intro; rewrite H1 in H0. inversion H0. simpl in H6. elim (bool_is_true_or_false (Neqb a1 c)); intro; rewrite H8 in H6. inversion H6. rewrite <- H10 in H7.\n\tcut (liste_reconnait d pl tl \\/ liste_reconnait d a0 tl). intro. elim H9; intro.\n\tleft. rewrite (Neqb_complete a1 c H8). apply (rec_st d (M1 prec_list c pl) c tl pl).\n\tsimpl in |- *. rewrite (Neqb_correct c). trivial. assumption. right. rewrite <- (Neqb_complete a1 a H1). rewrite (Neqb_complete a1 c H8). apply (rec_st d (M1 prec_list c a0) c tl a0).\n\tsimpl in |- *. rewrite (Neqb_correct c). trivial. trivial. apply (union_pl_r d pl a0 tl).\n\tapply (H c pl a0). simpl in |- *. rewrite H8. trivial. simpl in |- *. rewrite <- (Neqb_complete a1 a H1). rewrite H8. trivial.  assumption. inversion H6.\n\telim (Ndiscr (Nxor a a1)); intro y. elim y. intros x y0. rewrite y0 in H0. inversion H0.\n\trewrite (MapPut1_semantics prec_list x a a1 a0 pl y0 c) in H6.\n\telim (bool_is_true_or_false (Neqb a c)); intro; rewrite H8 in H6. right. inversion H6.\n\tapply (rec_st d (M1 prec_list a l) c tl l). simpl in |- *. rewrite H8. trivial. trivial.\n\telim (bool_is_true_or_false (Neqb a1 c)); intro; rewrite H9 in H6. inversion H6.\n\tleft. apply (rec_st d (M1 prec_list a1 l) c tl l). simpl in |- *. rewrite H9. trivial.\n\ttrivial. inversion H6. rewrite (Nxor_comm a a1) in y. rewrite (Nxor_eq_true a1 a y) in H1. inversion H1.\nQed.\n\nLemma union_s_rpl_2 :\n forall m : state,\n union_s_rpl_def m ->\n forall m0 : state, union_s_rpl_def m0 -> union_s_rpl_def (M2 prec_list m m0).\nProof.\n\tunfold union_s_rpl_def in |- *. intros. induction  a as [| p]. induction  c as [| p]. simpl in H2.\n\tcut\n  (state_reconnait d (M1 prec_list N0 pl) (app N0 tl) \\/\n   state_reconnait d m (app N0 tl)). intro. elim H3. intro. left. trivial. intro. right. inversion H4.\n\tapply (rec_st d (M2 prec_list m m0) N0 tl l). simpl in |- *. assumption. assumption.\n\tapply (H d N0 pl N0 tl). apply (mpl_compat_sym m (M1 prec_list N0 pl)).\n\texact\n  (mpl_compat_3 m m0 pl\n     (mpl_compat_sym (M1 prec_list N0 pl) (M2 prec_list m m0) H1)).\n\tinversion H2. simpl in H7. exact (rec_st d (union_mpl_0 N0 pl m) N0 tl l H7 H8).\n\tinduction  p as [p Hrecp| p Hrecp| ]. simpl in H2. inversion H2. right. apply (rec_st d (M2 prec_list m m0) (Npos (xI p)) tl l). simpl in |- *. simpl in H7. assumption. assumption. simpl in H2.\n\tcut\n  (state_reconnait d (M1 prec_list N0 pl) (app (Npos p) tl) \\/\n   state_reconnait d m (app (Npos p) tl)). intro. elim H3. intro. inversion H4. simpl in H9. inversion H9.\n\tintro. right. inversion H4. apply (rec_st d (M2 prec_list m m0) (Npos (xO p)) tl l).\n\tsimpl in |- *. assumption. assumption. apply (H d N0 pl (Npos p) tl). apply (mpl_compat_sym m (M1 prec_list N0 pl)). exact\n  (mpl_compat_3 m m0 pl\n     (mpl_compat_sym (M1 prec_list N0 pl) (M2 prec_list m m0) H1)). inversion H2. simpl in H7. exact (rec_st d (union_mpl_0 N0 pl m) (Npos p) tl l H7 H8). simpl in H2. inversion H2. right. simpl in H7.\n\tapply (rec_st d (M2 prec_list m m0) (Npos 1) tl l). simpl in |- *. assumption. assumption.\n\tinduction  p as [p Hrecp| p Hrecp| ]. induction  c as [| p0]. simpl in H2. inversion H2. right. apply (rec_st d (M2 prec_list m m0) N0 tl l). simpl in |- *. simpl in H7. assumption. assumption.\n\tsimpl in H2. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. cut\n  (state_reconnait d (M1 prec_list (Npos p) pl) (app (Npos p0) tl) \\/\n   state_reconnait d m0 (app (Npos p0) tl)). intro. elim H3; intro.\n\tinversion H4. left. apply (rec_st d (M1 prec_list (Npos (xI p)) pl) (Npos (xI p0)) tl l).\n\tsimpl in |- *. simpl in H9. assumption. assumption. right. inversion H4. apply (rec_st d (M2 prec_list m m0) (Npos (xI p0)) tl l). simpl in |- *. assumption. assumption.\n\tapply (H0 d (Npos p) pl (Npos p0) tl). apply (mpl_compat_sym m0 (M1 prec_list (Npos p) pl)).\n\tapply (mpl_compat_6 m m0 pl p). exact (mpl_compat_sym _ _ H1). inversion H2.\n\tsimpl in H7. simpl in |- *. apply (rec_st d (union_mpl_0 (Npos p) pl m0) (Npos p0) tl l).\n\tassumption. assumption. inversion H2. simpl in H7. right. apply (rec_st d (M2 prec_list m m0) (Npos (xO p0)) tl l). simpl in |- *. assumption. assumption. simpl in H2.\n\tcut\n  (state_reconnait d (M1 prec_list (Npos p) pl) (app N0 tl) \\/\n   state_reconnait d m0 (app N0 tl)). intro. elim H3; intro. left. inversion H4. simpl in H9. inversion H9.\n\tright. inversion H4. apply (rec_st d (M2 prec_list m m0) (Npos 1) tl l). simpl in |- *.\n\tassumption. assumption. apply (H0 d (Npos p) pl N0 tl). apply (mpl_compat_sym m0 (M1 prec_list (Npos p) pl)). apply (mpl_compat_6 m m0 pl p). exact\n  (mpl_compat_sym (M1 prec_list (Npos (xI p)) pl) (M2 prec_list m m0) H1). inversion H2. simpl in H7.\n\texact (rec_st d (union_mpl_0 (Npos p) pl m0) N0 tl l H7 H8). induction  c as [| p0]. simpl in H2.\n\tcut\n  (state_reconnait d (M1 prec_list (Npos p) pl) (app N0 tl) \\/\n   state_reconnait d m (app N0 tl)). intro. elim H3; intros. inversion H4. inversion H9. right. inversion H4.\n\tapply (rec_st d (M2 prec_list m m0) N0 tl l). simpl in |- *. assumption. assumption.\n\tapply (H d (Npos p) pl N0 tl). apply (mpl_compat_sym m (M1 prec_list (Npos p) pl)).\n\tapply (mpl_compat_5 m m0 pl p). exact\n  (mpl_compat_sym (M1 prec_list (Npos (xO p)) pl) (M2 prec_list m m0) H1). inversion H2. apply (rec_st d (union_mpl_0 (Npos p) pl m) N0 tl l).\n\tsimpl in |- *. simpl in H7. assumption. assumption. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. simpl in H2. inversion H2. right.\n\tapply (rec_st d (M2 prec_list m m0) (Npos (xI p0)) tl l). simpl in |- *. simpl in H7. assumption.\n\tassumption. simpl in H2. cut\n  (state_reconnait d (M1 prec_list (Npos p) pl) (app (Npos p0) tl) \\/\n   state_reconnait d m (app (Npos p0) tl)). intro. elim H3; intro. inversion H4. simpl in H9.\n\tleft. apply (rec_st d (M1 prec_list (Npos (xO p)) pl) (Npos (xO p0)) tl l). simpl in |- *. assumption.\n\tassumption. right. inversion H4. apply (rec_st d (M2 prec_list m m0) (Npos (xO p0)) tl l).\n\tsimpl in |- *. assumption. assumption. apply (H d (Npos p) pl (Npos p0) tl). apply (mpl_compat_sym m (M1 prec_list (Npos p) pl)). exact (mpl_compat_5 m m0 pl p (mpl_compat_sym _ _ H1)).\n\tinversion H2. apply (rec_st d (union_mpl_0 (Npos p) pl m) (Npos p0) tl l). simpl in H7.\n\tassumption. assumption. simpl in H2. inversion H2. right. apply (rec_st d (M2 prec_list m m0) (Npos 1) tl l). simpl in |- *. simpl in H7. assumption. assumption. induction  c as [| p].\n\tsimpl in H2. right. inversion H2. apply (rec_st d (M2 prec_list m m0) N0 tl l).\n\tsimpl in |- *. simpl in H7. assumption. assumption. induction  p as [p Hrecp| p Hrecp| ]. simpl in H2.\n\tcut\n  (state_reconnait d (M1 prec_list N0 pl) (app (Npos p) tl) \\/\n   state_reconnait d m0 (app (Npos p) tl)). intro. elim H3; intros. left. inversion H4. simpl in H9. inversion H9.\n\tright. inversion H4. apply (rec_st d (M2 prec_list m m0) (Npos (xI p)) tl l). simpl in |- *.\n\tassumption. assumption. apply (H0 d N0 pl (Npos p) tl). apply (mpl_compat_sym m0 (M1 prec_list N0 pl)). exact (mpl_compat_4 m m0 pl (mpl_compat_sym _ _ H1)). \n\tinversion H2. apply (rec_st d (union_mpl_0 N0 pl m0) (Npos p) tl l). simpl in |- *. simpl in H7.\n\tassumption. assumption. simpl in H2. inversion H2. right. apply (rec_st d (M2 prec_list m m0) (Npos (xO p)) tl l). simpl in |- *. simpl in H7. assumption. assumption. simpl in H2.\n\tcut\n  (state_reconnait d (M1 prec_list N0 pl) (app N0 tl) \\/\n   state_reconnait d m0 (app N0 tl)). intro. elim H3; intros. left. inversion H4. apply (rec_st d (M1 prec_list (Npos 1) pl) (Npos 1) tl l). simpl in |- *. assumption. assumption. right.\n\tinversion H4. apply (rec_st d (M2 prec_list m m0) (Npos 1) tl l). simpl in |- *.\n\tassumption. assumption. apply (H0 d N0 pl N0 tl). apply (mpl_compat_sym m0 (M1 prec_list N0 pl)). exact (mpl_compat_4 m m0 pl (mpl_compat_sym _ _ H1)).\n\tinversion H2. simpl in |- *. simpl in H7. apply (rec_st d (union_mpl_0 N0 pl m0) N0 tl l).\n\tsimpl in |- *. assumption. assumption.\nQed.\n\nLemma union_s_rpl_3 : forall m : state, union_s_rpl_def m.\nProof.\n\texact\n  (Map_ind prec_list union_s_rpl_def union_s_rpl_0 union_s_rpl_1\n     union_s_rpl_2).\nQed.\n\nLemma union_s_rpl :\n forall (s : state) (d : preDTA) (a : ad) (pl : prec_list) \n   (c : ad) (tl : term_list),\n mpl_compat (M1 prec_list a pl) s ->\n state_reconnait d (union_mpl_0 a pl s) (app c tl) ->\n state_reconnait d (M1 prec_list a pl) (app c tl) \\/\n state_reconnait d s (app c tl).\nProof.\n\tintro. exact (union_s_rpl_3 s).\nQed.\n\nDefinition union_str_def (s0 : state) : Prop :=\n  forall (s1 : state) (d : preDTA) (c : ad) (tl : term_list),\n  mpl_compat s0 s1 ->\n  state_reconnait d (union_mpl s0 s1) (app c tl) \\/\n  state_reconnait d (union_mpl s1 s0) (app c tl) ->\n  state_reconnait d s0 (app c tl) \\/ state_reconnait d s1 (app c tl).\n\nLemma union_str_0 : union_str_def (M0 prec_list).\nProof.\n\tunfold union_str_def in |- *. intros. induction  s1 as [| a a0| s1_1 Hrecs1_1 s1_0 Hrecs1_0]. elim H0; intros.\n\tinversion H1. inversion H6. inversion H1. inversion H6.\n\tsimpl in H0. right. elim H0; intro; assumption. simpl in H0. right.\n\telim H0; intro. assumption. assumption.\nQed.\n\nLemma union_str_1 :\n forall (a : ad) (a0 : prec_list), union_str_def (M1 prec_list a a0).\nProof.\n\tunfold union_str_def in |- *. intros. induction  s1 as [| a1 a2| s1_1 Hrecs1_1 s1_0 Hrecs1_0]. simpl in H0. left.\n\telim H0; intro; assumption. unfold union_mpl in H0. elim H0; intros.\n\telim\n  (union_s_rpl (M1 prec_list a a0) d a1 a2 c tl (mpl_compat_sym _ _ H) H1);\n  intro. right. assumption. left. assumption. elim (union_s_rpl (M1 prec_list a1 a2) d a a0 c tl H H1); intro. left. trivial. right.\n\ttrivial. elim H0; intros. elim (union_s_rpl (M2 prec_list s1_1 s1_0) d a a0 c tl H H1). intro. left. trivial. right. trivial.\n\texact (union_s_rpl (M2 prec_list s1_1 s1_0) d a a0 c tl H H1).\nQed.\n\nLemma union_str_2 :\n forall m : state,\n union_str_def m ->\n forall m0 : state, union_str_def m0 -> union_str_def (M2 prec_list m m0).\nProof.\n\tunfold union_str_def in |- *. intros. induction  s1 as [| a a0| s1_1 Hrecs1_1 s1_0 Hrecs1_0]. simpl in H2.\n\telim H2; intro; left; assumption. unfold union_mpl in H2. \n\telim H2; intro. elim\n  (union_s_rpl (M2 prec_list m m0) d a a0 c tl (mpl_compat_sym _ _ H1) H3);\n  intro. right. trivial. left. trivial.\n\telim\n  (union_s_rpl (M2 prec_list m m0) d a a0 c tl (mpl_compat_sym _ _ H1) H3);\n  intro. right. trivial. left. trivial. cut (mpl_compat m s1_1).\n\tcut (mpl_compat m0 s1_0). intros. induction  c as [| p]. simpl in H2.\n\tcut\n  (state_reconnait d (union_mpl m s1_1) (app N0 tl) \\/\n   state_reconnait d (union_mpl s1_1 m) (app N0 tl)). intro. elim (H s1_1 d N0 tl H4 H5); intro. inversion H6. left. apply (rec_st d (M2 prec_list m m0) N0 tl l).\n\tsimpl in |- *. assumption. assumption. right. inversion H6. apply (rec_st d (M2 prec_list s1_1 s1_0) N0 tl l). simpl in |- *. assumption. assumption. elim H2.\n\tintro. inversion H5. left. apply (rec_st d (union_mpl m s1_1) N0 tl l).\n\tsimpl in H10. assumption. assumption. intro. right. inversion H5.\n\tapply (rec_st d (union_mpl s1_1 m) N0 tl l). simpl in H10. assumption.\n\tassumption.  induction  p as [p Hrecp| p Hrecp| ]. simpl in H2. clear Hrecp. clear Hrecs1_1. \n\tclear Hrecs1_0. cut\n  (state_reconnait d (union_mpl m0 s1_0) (app (Npos p) tl) \\/\n   state_reconnait d (union_mpl s1_0 m0) (app (Npos p) tl)). intro. \n\telim (H0 s1_0 d (Npos p) tl H3 H5). intro. left. inversion H6.\n\tapply (rec_st d (M2 prec_list m m0) (Npos (xI p)) tl l). simpl in |- *. assumption.\n\tassumption. intro. inversion H6. right. apply (rec_st d (M2 prec_list s1_1 s1_0) (Npos (xI p)) tl l). simpl in |- *. assumption. assumption. elim H2; intro.\n\tleft. inversion H5. apply (rec_st d (union_mpl m0 s1_0) (Npos p) tl l).\n\tsimpl in H10. assumption. assumption. inversion H5. right.\n\tapply (rec_st d (union_mpl s1_0 m0) (Npos p) tl l). simpl in H10. simpl in |- *. \n\tassumption. assumption. clear Hrecp. clear Hrecs1_1. clear Hrecs1_0.\n\tsimpl in H2. cut\n  (state_reconnait d (union_mpl m s1_1) (app (Npos p) tl) \\/\n   state_reconnait d (union_mpl s1_1 m) (app (Npos p) tl)). intro.\n\telim (H s1_1 d (Npos p) tl H4 H5). intro. left. inversion H6.\n\tapply (rec_st d (M2 prec_list m m0) (Npos (xO p)) tl l). simpl in |- *.\n\tassumption.  assumption. intro. right. inversion H6.\n\tapply (rec_st d (M2 prec_list s1_1 s1_0) (Npos (xO p)) tl l). simpl in |- *.\n\tassumption. assumption. elim H2; intro; inversion H5. left.\n\tapply (rec_st d (union_mpl m s1_1) (Npos p) tl l). simpl in H10. assumption.\n\tassumption. right. apply (rec_st d (union_mpl s1_1 m) (Npos p) tl l). \n\tsimpl in H10. assumption. assumption. simpl in H2. cut\n  (state_reconnait d (union_mpl m0 s1_0) (app N0 tl) \\/\n   state_reconnait d (union_mpl s1_0 m0) (app N0 tl)). intro. elim (H0 s1_0 d N0 tl H3 H5); intro. inversion H6.\n\tleft. apply (rec_st d (M2 prec_list m m0) (Npos 1) tl l). simpl in |- *. assumption.\n\tassumption. inversion H6. right. apply (rec_st d (M2 prec_list s1_1 s1_0) (Npos 1) tl l). simpl in |- *. assumption. assumption. elim H2; intro; inversion H5.\n\tleft. simpl in H10. apply (rec_st d (union_mpl m0 s1_0) N0 tl l). assumption.\n\tassumption. right. apply (rec_st d (union_mpl s1_0 m0) N0 tl l). simpl in H10.\n\tassumption. assumption. exact (mpl_compat_2 m m0 s1_1 s1_0 H1).\n\texact (mpl_compat_1 m m0 s1_1 s1_0 H1).\nQed.\n\nLemma union_str_3 : forall m : state, union_str_def m.\nProof.\n\texact (Map_ind prec_list union_str_def union_str_0 union_str_1 union_str_2).\nQed.\n\nLemma union_str :\n forall (s0 s1 : state) (d : preDTA) (c : ad) (tl : term_list),\n mpl_compat s0 s1 ->\n state_reconnait d (union_mpl s0 s1) (app c tl) \\/\n state_reconnait d (union_mpl s1 s0) (app c tl) ->\n state_reconnait d s0 (app c tl) \\/ state_reconnait d s1 (app c tl).\nProof.\n\tintro. exact (union_str_3 s0).\nQed.\n\nLemma union_state :\n forall (s0 s1 : state) (d : preDTA) (t : term),\n mpl_compat s0 s1 ->\n (state_reconnait d (union_mpl s0 s1) t <->\n  state_reconnait d s0 t \\/ state_reconnait d s1 t).\nProof.\n\tintros. split. intro. induction  t as (a, t). apply (union_str s0 s1 d a t H).\n\tleft. trivial. intro. elim H0; intro. induction  t as (a, t).\n\telim (union_sd s0 s1 d a t H H1). intros. assumption. induction  t as (a, t).\n\telim (union_sd s1 s0 d a t (mpl_compat_sym _ _ H) H1). intros.\n\tassumption.\nQed.\n\nDefinition new_preDTA_ad : preDTA -> ad := ad_alloc_opt state.\n\n(* invariant de reconnaissance lors de l'ajout d'un état, sens direct *)\n\nDefinition new_state_insd_def_dta (d : preDTA) (a0 : ad) \n  (t0 : term) (pr : reconnaissance d a0 t0) :=\n  forall (a : ad) (s : state),\n  MapGet state d a = None -> reconnaissance (MapPut state d a s) a0 t0.\n\nDefinition new_state_insd_def_st (d : preDTA) (s0 : state) \n  (t0 : term) (pr : state_reconnait d s0 t0) :=\n  forall (a : ad) (s : state),\n  MapGet state d a = None -> state_reconnait (MapPut state d a s) s0 t0.\n\nDefinition new_state_insd_def_lst (d : preDTA) (pl0 : prec_list)\n  (tl0 : term_list) (pr : liste_reconnait d pl0 tl0) :=\n  forall (a : ad) (s : state),\n  MapGet state d a = None ->\n  liste_reconnait (MapPut state d a s) pl0 tl0.\n\nLemma new_state_insd_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 new_state_insd_def_st d ladj t s ->\n new_state_insd_def_dta d a t (rec_dta d a t ladj e s).\nProof.\n\tunfold new_state_insd_def_dta in |- *. unfold new_state_insd_def_st in |- *.\n\tintros. apply (rec_dta (MapPut state d a0 s0) a t ladj).\n\trewrite (MapPut_semantics state d a0 s0 a).\n\telim (bool_is_true_or_false (Neqb a0 a)); intros.\n\trewrite (Neqb_complete a0 a H1) in H0. rewrite H0 in e.\n\tinversion e. rewrite H1. assumption. exact (H a0 s0 H0).\nQed.\n\nLemma new_state_insd_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 new_state_insd_def_lst d l tl l0 ->\n new_state_insd_def_st d s (app c tl) (rec_st d s c tl l e l0).\nProof.\n\tunfold new_state_insd_def_lst in |- *. unfold new_state_insd_def_st in |- *.\n\tintros. apply (rec_st (MapPut state d a s0) s c tl l).\n\tassumption. exact (H a s0 H0).\nQed.\n\nLemma new_state_insd_2 :\n forall d : preDTA, new_state_insd_def_lst d prec_empty tnil (rec_empty d).\nProof.\n\tunfold new_state_insd_def_lst in |- *. intros. exact (rec_empty (MapPut state d a s)).\nQed.\n\nLemma new_state_insd_3 :\n forall (d : preDTA) (a : ad) (la ls : prec_list) (hd : term)\n   (tl : term_list) (r : reconnaissance d a hd),\n new_state_insd_def_dta d a hd r ->\n forall l : liste_reconnait d la tl,\n new_state_insd_def_lst d la tl l ->\n new_state_insd_def_lst d (prec_cons a la ls) (tcons hd tl)\n   (rec_consi d a la ls hd tl r l).\nProof.\n\tunfold new_state_insd_def_lst in |- *. unfold new_state_insd_def_dta in |- *.\n\tintros. apply (rec_consi (MapPut state d a0 s) a la ls hd tl).\n\texact (H a0 s H1). exact (H0 a0 s H1).\nQed.\n\nLemma new_state_insd_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 new_state_insd_def_lst d ls (tcons hd tl) l ->\n new_state_insd_def_lst d (prec_cons a la ls) (tcons hd tl)\n   (rec_consn d a la ls hd tl l).\nProof.\n\tunfold new_state_insd_def_lst in |- *. intros.\n\texact (rec_consn (MapPut state d a0 s) a la ls hd tl (H a0 s H0)).\nQed.\n\nLemma new_state_insd_5 :\n forall (p : preDTA) (a : ad) (t : term) (r : reconnaissance p a t),\n new_state_insd_def_dta p a t r.\nProof.\n\texact\n  (mreconnaissance_ind new_state_insd_def_dta new_state_insd_def_st\n     new_state_insd_def_lst new_state_insd_0 new_state_insd_1\n     new_state_insd_2 new_state_insd_3 new_state_insd_4).\nQed.\n\nLemma new_state_ins_d :\n forall (d : preDTA) (a : ad) (s : state) (a0 : ad) (t : term),\n reconnaissance d a0 t ->\n MapGet state d a = None -> reconnaissance (MapPut state d a s) a0 t.\nProof.\n\tintros. exact (new_state_insd_5 d a0 t H a s H0).\nQed.\n\n(* invariant de reconnaissance lors de l'ajout d'un état, sens réciproque *)\n\nDefinition new_state_insr_def_dta (d0 : preDTA) (a0 : ad) \n  (t0 : term) (pr : reconnaissance d0 a0 t0) :=\n  forall (d : preDTA) (a : ad) (s : state),\n  preDTA_ref_ok d ->\n  d0 = MapPut state d a s ->\n  MapGet state d a = None -> a <> a0 -> reconnaissance d a0 t0.\n\nDefinition new_state_insr_def_st (d0 : preDTA) (s0 : state) \n  (t0 : term) (pr : state_reconnait d0 s0 t0) :=\n  forall (d : preDTA) (a : ad) (s : state),\n  preDTA_ref_ok d ->\n  state_in_dta_diff d0 s0 a ->\n  d0 = MapPut state d a s ->\n  MapGet state d a = None -> state_reconnait d s0 t0.\n\nDefinition new_state_insr_def_lst (d0 : preDTA) (pl0 : prec_list)\n  (tl0 : term_list) (pr : liste_reconnait d0 pl0 tl0) :=\n  forall (d : preDTA) (a : ad) (s : state),\n  preDTA_ref_ok d ->\n  d0 = MapPut state d a s ->\n  MapGet state d a = None ->\n  prec_in_dta_diff_cont d0 pl0 a ->\n  liste_reconnait d pl0 tl0 /\\ prec_in_dta_diff_cont d pl0 a.\n\nLemma new_state_insr_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 new_state_insr_def_st d ladj t s ->\n new_state_insr_def_dta d a t (rec_dta d a t ladj e s).\nProof.\n\tunfold new_state_insr_def_st in |- *. unfold new_state_insr_def_dta in |- *.\n\tintros. apply (rec_dta d0 a t ladj). rewrite H1 in e.\n\trewrite (MapPut_semantics state d0 a0 s0) in e.\n\telim (bool_is_true_or_false (Neqb a0 a)); intro.\n\telim (H3 (Neqb_complete _ _ H4)). rewrite H4 in e.\n\tassumption. apply (H d0 a0 s0). assumption.\n\tunfold state_in_dta_diff in |- *. split with a. split; assumption.\n\tassumption. assumption.\nQed.\n\nLemma new_state_insr_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 new_state_insr_def_lst d l tl l0 ->\n new_state_insr_def_st d s (app c tl) (rec_st d s c tl l e l0).\nProof.\n\tunfold new_state_insr_def_lst in |- *. intros. \tunfold new_state_insr_def_st in |- *. \n\tintros. cut (prec_in_dta_diff_cont d l a). intro. elim (H d0 a s0 H0 H2 H3 H4). intros. apply (rec_st d0 s c tl l). assumption. assumption.\n\tunfold prec_in_dta_diff_cont in |- *. split with s. elim H1. intros.\n\tsplit with x. elim H4; intros. split with c. split with l. split.\n\tassumption. split. assumption. split. exact (prec_id _). assumption.\nQed.\n\nLemma new_state_insr_2 :\n forall d : preDTA, new_state_insr_def_lst d prec_empty tnil (rec_empty d).\nProof.\n\tintros. unfold new_state_insr_def_lst in |- *. intros. split.\n\texact (rec_empty d0). unfold prec_in_dta_diff_cont in |- *.\n\tunfold prec_in_dta_diff_cont in H1. elim H1. intros.\n\telim H2. intros. elim H3. intros. elim H4. intros. elim H5.\n\tintros. elim H6. intros. elim H8. intros. elim H10. intros.\n\tsplit with x. split with x0. split with x1. split with x2.\n\tsplit. simpl in H7. rewrite H0 in H7.\n\trewrite (MapPut_semantics state d0 a s) in H7.\n\telim (bool_is_true_or_false (Neqb a x0)); intro.\n\telim (H12 (Neqb_complete _ _ H13)). rewrite H13 in H7.\n\tassumption. split. assumption. split; assumption.\nQed.\n\nLemma new_state_insr_3 :\n forall (d : preDTA) (a : ad) (la ls : prec_list) (hd : term)\n   (tl : term_list) (r : reconnaissance d a hd),\n new_state_insr_def_dta d a hd r ->\n forall l : liste_reconnait d la tl,\n new_state_insr_def_lst d la tl l ->\n new_state_insr_def_lst d (prec_cons a la ls) (tcons hd tl)\n   (rec_consi d a la ls hd tl r l).\nProof.\n\tunfold new_state_insr_def_lst in |- *. unfold new_state_insr_def_dta in |- *.\n\tintros. split. apply (rec_consi d0 a la ls hd tl). cut (a0 <> a).\n\tintro. exact (H d0 a0 s H1 H2 H3 H5). unfold prec_in_dta_diff_cont in H4. unfold preDTA_ref_ok in H1. elim H4. intros. elim H5. intros.\n\telim H6. intros. elim H7. intros. elim H8. intros. elim H10. intros.\n\tcut (MapGet state d0 x0 = Some x). cut (prec_occur x2 a).\n\tintros. elim (H1 x0 x x1 x2 a H14 H11 H13). intros. elim (classic (a0 = a)). intro. rewrite <- H16 in H15. rewrite H15 in H3. inversion H3.\n\tintro. assumption. elim H12. intros. exact (prec_occur_1 a la ls x2 H13). rewrite H2 in H9. rewrite (MapPut_semantics state d0 a0 s) in H9. elim (bool_is_true_or_false (Neqb a0 x0)). intro. elim H12.\n\tintros. elim (H15 (Neqb_complete _ _ H13)). intros. rewrite H13 in H9.\n\tassumption. unfold prec_in_dta_diff_cont in H4. elim H4. intros. \n\telim H5. intros. elim H6. intros. elim H7. intros. elim H8. intros.\n\telim H10. intros. elim H12. intros. cut (prec_in_dta_diff_cont d la a0). intro. elim (H0 d0 a0 s H1 H2 H3 H15). intros. assumption.\n\tunfold prec_in_dta_diff_cont in |- *. split with x. split with x0. split with x1. split with x2. split. assumption. split. assumption.\n\tsplit. exact (prec_contained_0 _ _ _ _ H13). assumption. elim H4.\n\tintros. elim H5. intros. elim H6. intros. elim H7. intros. elim H8.\n\tintros. elim H10. intros. elim H12. intros. rewrite H2 in H9.\n\trewrite (MapPut_semantics state d0 a0 s) in H9.\n\telim (bool_is_true_or_false (Neqb a0 x0)); intro. elim (H14 (Neqb_complete _ _ H15)). rewrite H15 in H9. split with x. \n\tsplit with x0. split with x1. split with x2. split. assumption.\n\tsplit. assumption. split; assumption.\nQed.\n\nLemma new_state_insr_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 new_state_insr_def_lst d ls (tcons hd tl) l ->\n new_state_insr_def_lst d (prec_cons a la ls) (tcons hd tl)\n   (rec_consn d a la ls hd tl l).\nProof.\n\tunfold new_state_insr_def_lst in |- *. intros. split. apply (rec_consn d0 a la ls hd tl). cut (prec_in_dta_diff_cont d ls a0). intro. elim (H d0 a0 s H0 H1 H2 H4). intros. assumption. elim H3. intros. elim H4.\n\tintros. elim H5. intros. elim H6. intros. elim H7. intros. elim H9.\n\tintros. elim H11. intros. split with x. split with x0. split with x1.\n\tsplit with x2. split. assumption. split. assumption.  split.\n\texact (prec_contained_1 a la ls x2 H12). assumption. elim H3. intros.\n\telim H4. intros. elim H5. intros. elim H6. intros. elim H7. intros.\n\telim H9. intros. elim H11. intros. split with x. split with x0. \n\tsplit with x1. split with x2. split. rewrite H1 in H8. rewrite (MapPut_semantics state d0 a0 s) in H8. elim (bool_is_true_or_false (Neqb a0 x0)); intro. elim (H13 (Neqb_complete _ _ H14)). \n\trewrite H14 in H8. assumption. split. assumption. split; assumption.\nQed.\n\nLemma new_state_insr_5 :\n forall (p : preDTA) (a : ad) (t : term) (r : reconnaissance p a t),\n new_state_insr_def_dta p a t r.\nProof.\n\texact\n  (mreconnaissance_ind new_state_insr_def_dta new_state_insr_def_st\n     new_state_insr_def_lst new_state_insr_0 new_state_insr_1\n     new_state_insr_2 new_state_insr_3 new_state_insr_4).\nQed.\n\nLemma new_state_ins_r :\n forall (d0 : preDTA) (a0 : ad) (t0 : term) (d : preDTA) (a : ad) (s : state),\n reconnaissance d0 a0 t0 ->\n preDTA_ref_ok d ->\n d0 = MapPut state d a s ->\n MapGet state d a = None -> a <> a0 -> reconnaissance d a0 t0.\nProof.\n\tintros. exact (new_state_insr_5 d0 a0 t0 H d a s H0 H1 H2 H3).\nQed.\n\n(* insertion d'un état *)\n\nDefinition insert_state (d : preDTA) (a : ad) (s : state) : preDTA :=\n  MapPut state d a s.\n\nDefinition insert_main_state_0 (d : preDTA) (a : ad) \n  (s : state) : DTA := dta (insert_state d a s) a.\n\nDefinition insert_main_state (d : preDTA) (s : state) : DTA :=\n  insert_main_state_0 d (new_preDTA_ad d) s.\n\nDefinition insert_ostate (d : preDTA) (a : ad) (o : option state) : preDTA :=\n  match o with\n  | None => d\n  | Some s => MapPut state d a s\n  end.\n\nDefinition insert_main_ostate_0 (d : preDTA) (a : ad) \n  (o : option state) : DTA := dta (insert_ostate d a o) a.\n\nLemma insert_ostate_0 :\n forall (d : preDTA) (a : ad) (s : state) (a0 : ad) (t : term),\n preDTA_ref_ok d ->\n MapGet state d a = None ->\n a <> a0 ->\n (reconnaissance d a0 t <->\n  reconnaissance (insert_ostate d a (Some s)) a0 t).\nProof.\n\tintros. split. simpl in |- *. intro. exact (new_state_ins_d d a s a0 t H2 H0). simpl in |- *. intro. exact\n  (new_state_ins_r (MapPut state d a s) a0 t d a s H2 H (refl_equal _) H0 H1).\nQed.\n\nLemma insert_ostate_1 :\n forall (d0 d1 : preDTA) (a0 a1 a : ad) (s s0 s1 s0' s1' : state) (t : term),\n MapGet state d0 a0 = Some s0 ->\n MapGet state d1 a1 = Some s1 ->\n MapGet state (u_merge d0 d1) (uad_conv_0 a0) = Some s0' ->\n MapGet state (u_merge d0 d1) (uad_conv_1 a1) = Some s1' ->\n preDTA_ref_ok (u_merge d0 d1) ->\n MapGet state (u_merge d0 d1) a = None ->\n a <> uad_conv_0 a0 ->\n (reconnaissance d0 a0 t <->\n  reconnaissance (insert_ostate (u_merge d0 d1) a (Some s))\n    (uad_conv_0 a0) t).\nProof.\n\tintros. cut\n  (reconnaissance (u_merge d0 d1) (uad_conv_0 a0) t <->\n   reconnaissance (insert_ostate (u_merge d0 d1) a (Some s))\n     (uad_conv_0 a0) t). intro. elim H6. intros. split. intros. apply H7.\n\texact (u_merge_2 d0 d1 a0 t H9). intro. exact (u_merge_4 d0 d1 a0 t (H8 H9)). \n\texact (insert_ostate_0 (u_merge d0 d1) a s (uad_conv_0 a0) t H3 H4 H5).\nQed.\n\nLemma insert_ostate_2 :\n forall (d0 d1 : preDTA) (a0 a1 a : ad) (s s0 s1 s0' s1' : state) (t : term),\n MapGet state d0 a0 = Some s0 ->\n MapGet state d1 a1 = Some s1 ->\n MapGet state (u_merge d0 d1) (uad_conv_0 a0) = Some s0' ->\n MapGet state (u_merge d0 d1) (uad_conv_1 a1) = Some s1' ->\n preDTA_ref_ok (u_merge d0 d1) ->\n MapGet state (u_merge d0 d1) a = None ->\n a <> uad_conv_1 a1 ->\n (reconnaissance d1 a1 t <->\n  reconnaissance (insert_ostate (u_merge d0 d1) a (Some s))\n    (uad_conv_1 a1) t).\nProof.\n\tintros. cut\n  (reconnaissance (u_merge d0 d1) (uad_conv_1 a1) t <->\n   reconnaissance (insert_ostate (u_merge d0 d1) a (Some s))\n     (uad_conv_1 a1) t). intro. elim H6. intros. split. intros. apply H7.\n\texact (u_merge_3 d0 d1 a1 t H9). intro. exact (u_merge_5 d0 d1 a1 t (H8 H9)). \n\texact (insert_ostate_0 (u_merge d0 d1) a s (uad_conv_1 a1) t H3 H4 H5).\nQed.\n\nLemma insert_ostate_3 :\n forall (d0 d1 : preDTA) (a0 a1 a : ad) (s s0 s1 s0' s1' : state) (t : term),\n MapGet state d0 a0 = Some s0 ->\n MapGet state d1 a1 = Some s1 ->\n MapGet state (u_merge d0 d1) (uad_conv_0 a0) = Some s0' ->\n MapGet state (u_merge d0 d1) (uad_conv_1 a1) = Some s1' ->\n preDTA_ref_ok (u_merge d0 d1) ->\n MapGet state (u_merge d0 d1) a = None ->\n a <> uad_conv_0 a0 ->\n (reconnaissance (insert_ostate (u_merge d0 d1) a (Some s))\n    (uad_conv_0 a0) t <->\n  state_reconnait (insert_ostate (u_merge d0 d1) a (Some s)) s0' t).\nProof.\n\tintros. split. intro. inversion H6. unfold insert_ostate in H7.\n\trewrite (MapPut_semantics state (u_merge d0 d1) a s) in H7.\n\telim (bool_is_true_or_false (Neqb a (uad_conv_0 a0))); intro.\n\telim (H5 (Neqb_complete _ _ H12)). rewrite H12 in H7. induction  t as (a3, t).\n\tinversion H8. apply (rec_st (insert_ostate (u_merge d0 d1) a (Some s)) s0' a3 t l). rewrite H7 in H1. inversion H1.\n\trewrite <- H20. assumption. assumption. intro.\n\tapply\n  (rec_dta (insert_ostate (u_merge d0 d1) a (Some s)) \n     (uad_conv_0 a0) t s0'). unfold insert_ostate in |- *.\n\trewrite (MapPut_semantics state (u_merge d0 d1) a s).\n\telim (bool_is_true_or_false (Neqb a (uad_conv_0 a0))); intro.\n\telim (H5 (Neqb_complete _ _ H7)). rewrite H7. assumption.\n\tassumption.\nQed.\n\nLemma insert_ostate_4 :\n forall (d0 d1 : preDTA) (a0 a1 a : ad) (s s0 s1 s0' s1' : state) (t : term),\n MapGet state d0 a0 = Some s0 ->\n MapGet state d1 a1 = Some s1 ->\n MapGet state (u_merge d0 d1) (uad_conv_0 a0) = Some s0' ->\n MapGet state (u_merge d0 d1) (uad_conv_1 a1) = Some s1' ->\n preDTA_ref_ok (u_merge d0 d1) ->\n MapGet state (u_merge d0 d1) a = None ->\n a <> uad_conv_1 a1 ->\n (reconnaissance (insert_ostate (u_merge d0 d1) a (Some s))\n    (uad_conv_1 a1) t <->\n  state_reconnait (insert_ostate (u_merge d0 d1) a (Some s)) s1' t).\nProof.\n\tintros. split. intro. inversion H6. unfold insert_ostate in H7.\n\trewrite (MapPut_semantics state (u_merge d0 d1) a s) in H7.\n\telim (bool_is_true_or_false (Neqb a (uad_conv_1 a1))); intro.\n\telim (H5 (Neqb_complete _ _ H12)). rewrite H12 in H7. induction  t as (a3, t).\n\tinversion H8. apply (rec_st (insert_ostate (u_merge d0 d1) a (Some s)) s1' a3 t l). rewrite H7 in H2. inversion H2.\n\trewrite <- H20. assumption. assumption. intro.\n\tapply\n  (rec_dta (insert_ostate (u_merge d0 d1) a (Some s)) \n     (uad_conv_1 a1) t s1'). unfold insert_ostate in |- *.\n\trewrite (MapPut_semantics state (u_merge d0 d1) a s).\n\telim (bool_is_true_or_false (Neqb a (uad_conv_1 a1))); intro.\n\telim (H5 (Neqb_complete _ _ H7)). rewrite H7. assumption.\n\tassumption.\nQed.\n\nLemma insert_ostate_5 :\n forall (d0 d1 : preDTA) (a0 a1 a : ad) (s0 s1 s0' s1' : state) (t : term),\n mpl_compat s0' s1' ->\n MapGet state d0 a0 = Some s0 ->\n MapGet state d1 a1 = Some s1 ->\n MapGet state (u_merge d0 d1) (uad_conv_0 a0) = Some s0' ->\n MapGet state (u_merge d0 d1) (uad_conv_1 a1) = Some s1' ->\n preDTA_ref_ok (u_merge d0 d1) ->\n MapGet state (u_merge d0 d1) a = None ->\n a <> uad_conv_0 a0 ->\n a <> uad_conv_1 a1 ->\n (state_reconnait\n    (insert_ostate (u_merge d0 d1) a (Some (union_mpl s0' s1')))\n    (union_mpl s0' s1') t <->\n  state_reconnait\n    (insert_ostate (u_merge d0 d1) a (Some (union_mpl s0' s1'))) s0' t \\/\n  state_reconnait\n    (insert_ostate (u_merge d0 d1) a (Some (union_mpl s0' s1'))) s1' t).\nProof.\n\tintros. exact\n  (union_state s0' s1'\n     (insert_ostate (u_merge d0 d1) a (Some (union_mpl s0' s1'))) t H).\nQed.\n\nLemma insert_ostate_6 :\n forall (d0 d1 : preDTA) (a0 a1 a : ad) (s0 s1 s0' s1' : state) (t : term),\n mpl_compat s0' s1' ->\n MapGet state d0 a0 = Some s0 ->\n MapGet state d1 a1 = Some s1 ->\n MapGet state (u_merge d0 d1) (uad_conv_0 a0) = Some s0' ->\n MapGet state (u_merge d0 d1) (uad_conv_1 a1) = Some s1' ->\n preDTA_ref_ok (u_merge d0 d1) ->\n MapGet state (u_merge d0 d1) a = None ->\n a <> uad_conv_0 a0 ->\n a <> uad_conv_1 a1 ->\n (state_reconnait\n    (insert_ostate (u_merge d0 d1) a (Some (union_mpl s0' s1')))\n    (union_mpl s0' s1') t <->\n  reconnaissance\n    (insert_ostate (u_merge d0 d1) a (Some (union_mpl s0' s1'))) a t).\nProof.\n\tintros. split. intro. apply\n  (rec_dta (insert_ostate (u_merge d0 d1) a (Some (union_mpl s0' s1')))\n     a t (union_mpl s0' s1')).\n\tunfold insert_ostate in |- *. rewrite (MapPut_semantics state (u_merge d0 d1) a (union_mpl s0' s1')). rewrite (Neqb_correct a). trivial. assumption.\n\tintro. inversion H8. unfold insert_ostate in H9. rewrite (MapPut_semantics state (u_merge d0 d1) a (union_mpl s0' s1')) in H9. rewrite (Neqb_correct a) in H9. inversion H9. rewrite <- H15 in H10. assumption.\nQed.\n\nLemma insert_ostate_7 :\n forall (d0 d1 : preDTA) (a0 a1 a : ad) (s0 s1 s0' s1' : state) (t : term),\n mpl_compat s0' s1' ->\n MapGet state d0 a0 = Some s0 ->\n MapGet state d1 a1 = Some s1 ->\n MapGet state (u_merge d0 d1) (uad_conv_0 a0) = Some s0' ->\n MapGet state (u_merge d0 d1) (uad_conv_1 a1) = Some s1' ->\n preDTA_ref_ok (u_merge d0 d1) ->\n MapGet state (u_merge d0 d1) a = None ->\n a <> uad_conv_0 a0 ->\n a <> uad_conv_1 a1 ->\n (reconnaissance d0 a0 t \\/ reconnaissance d1 a1 t <->\n  reconnaissance\n    (insert_ostate (u_merge d0 d1) a (Some (union_mpl s0' s1'))) a t).\nProof.\n\tintros. elim\n  (insert_ostate_1 d0 d1 a0 a1 a (union_mpl s0' s1') s0 s1 s0' s1' t H0 H1 H2\n     H3 H4 H5 H6). elim\n  (insert_ostate_2 d0 d1 a0 a1 a (union_mpl s0' s1') s0 s1 s0' s1' t H0 H1 H2\n     H3 H4 H5 H7). intros. elim\n  (insert_ostate_3 d0 d1 a0 a1 a (union_mpl s0' s1') s0 s1 s0' s1' t H0 H1 H2\n     H3 H4 H5 H6). elim\n  (insert_ostate_4 d0 d1 a0 a1 a (union_mpl s0' s1') s0 s1 s0' s1' t H0 H1 H2\n     H3 H4 H5 H7). intros. elim\n  (insert_ostate_5 d0 d1 a0 a1 a s0 s1 s0' s1' t H H0 H1 H2 H3 H4 H5 H6 H7). elim\n  (insert_ostate_6 d0 d1 a0 a1 a s0 s1 s0' s1' t H H0 H1 H2 H3 H4 H5 H6 H7). intros. split. intro.\n\tapply H16. apply H19. elim H20; intro. left. exact (H14 (H10 H21)).\n\tright. exact (H12 (H8 H21)). intro. elim (H18 (H17 H20)). intro.\n\tleft. exact (H11 (H15 H21)). intro. right. exact (H9 (H13 H21)).\nQed.\n\nLemma insert_ostate_8 :\n forall (d0 d1 : preDTA) (a0 a1 a : ad) (s0 s1 s0' s1' : state) (t : term),\n mpl_compat s0' s1' ->\n MapGet state d0 a0 = Some s0 ->\n MapGet state d1 a1 = Some s1 ->\n MapGet state (u_merge d0 d1) (uad_conv_0 a0) = Some s0' ->\n MapGet state (u_merge d0 d1) (uad_conv_1 a1) = Some s1' ->\n preDTA_ref_ok (u_merge d0 d1) ->\n a = new_preDTA_ad (u_merge d0 d1) ->\n (reconnaissance d0 a0 t \\/ reconnaissance d1 a1 t <->\n  reconnaissance\n    (insert_ostate (u_merge d0 d1) a (Some (union_mpl s0' s1'))) a t).\nProof.\n\tintros. apply (insert_ostate_7 d0 d1 a0 a1 a s0 s1 s0' s1' t H H0 H1 H2 H3 H4). unfold new_preDTA_ad in H5. rewrite H5.\n\texact (ad_alloc_opt_allocates_1 state (u_merge d0 d1)). intro.\n\trewrite H5 in H6. rewrite <- H6 in H2. unfold new_preDTA_ad in H2.\n\trewrite (ad_alloc_opt_allocates_1 state (u_merge d0 d1)) in H2.\n\tinversion H2. intro. rewrite H5 in H6. rewrite <- H6 in H3.\n\tunfold new_preDTA_ad in H3. rewrite (ad_alloc_opt_allocates_1 state (u_merge d0 d1)) in H3. inversion H3.\nQed.\n\nLemma upl_conv_0_occur :\n forall (pl : prec_list) (a : ad),\n prec_occur (upl_conv_0 pl) (uad_conv_0 a) -> prec_occur pl a.\nProof.\n\tsimple induction pl. intros. simpl in H1. inversion H1.\n\trewrite (adcnv_inj0 a a0 H6). exact (prec_hd a0 p p0).\n\texact (prec_int0 a a0 p p0 (H a0 H6)). exact (prec_int1 a a0 p p0 (H0 a0 H6)). intros. simpl in H. inversion H.\nQed.\n\nLemma upl_conv_1_occur :\n forall (pl : prec_list) (a : ad),\n prec_occur (upl_conv_1 pl) (uad_conv_1 a) -> prec_occur pl a.\nProof.\n\tsimple induction pl. intros. simpl in H1. inversion H1.\n\trewrite (adcnv_inj1 a a0 H6). exact (prec_hd a0 p p0).\n\texact (prec_int0 a a0 p p0 (H a0 H6)). exact (prec_int1 a a0 p p0 (H0 a0 H6)). intros. simpl in H. inversion H.\nQed.\n\nLemma upl_conv_0_occur_in_img :\n forall (pl : prec_list) (a : ad),\n prec_occur (upl_conv_0 pl) a -> exists b : ad, a = uad_conv_0 b.\nProof.\n\tsimple induction pl. intros. simpl in H1. inversion H1. split with a.\n\ttrivial. elim (H a0 H6). intros. split with x. trivial.\n\telim (H0 a0 H6). intros. split with x. trivial. intros.\n\tinversion H.\nQed.\n\nLemma upl_conv_1_occur_in_img :\n forall (pl : prec_list) (a : ad),\n prec_occur (upl_conv_1 pl) a -> exists b : ad, a = uad_conv_1 b.\nProof.\n\tsimple induction pl. intros. simpl in H1. inversion H1. split with a.\n\ttrivial. elim (H a0 H6). intros. split with x. trivial.\n\telim (H0 a0 H6). intros. split with x. trivial. intros.\n\tinversion H.\nQed.\n\nLemma u_conv_0_ref_ok :\n forall d : preDTA, preDTA_ref_ok d -> preDTA_ref_ok (udta_conv_0 d).\nProof.\n\tunfold preDTA_ref_ok in |- *. intros. elim (u_conv_0_invar_8 d a s H0).\n\tintros. rewrite H3 in H0. elim (u_conv_0_invar_5 d x s H0).\n\tintros. elim H4. intros. rewrite H5 in H1. elim (u_conv_0_invar_7 x0 c pl H1). intros. elim H7. intros. rewrite H8 in H2. elim (upl_conv_0_occur_in_img x1 b). intros. elim (H x x0 c x1 x2 H6 H9).\n\tintros. split with (umpl_conv_0 x3). rewrite H10. \n\texact (u_conv_0_invar_0 d x2 x3 H11). rewrite H10 in H2.\n\texact (upl_conv_0_occur x1 x2 H2). assumption.\nQed.\n\nLemma u_conv_1_ref_ok :\n forall d : preDTA, preDTA_ref_ok d -> preDTA_ref_ok (udta_conv_1 d).\nProof.\n\tunfold preDTA_ref_ok in |- *. intros. elim (u_conv_1_invar_8 d a s H0).\n\tintros. rewrite H3 in H0. elim (u_conv_1_invar_5 d x s H0).\n\tintros. elim H4. intros. rewrite H5 in H1. elim (u_conv_1_invar_7 x0 c pl H1). intros. elim H7. intros. rewrite H8 in H2. elim (upl_conv_1_occur_in_img x1 b). intros. elim (H x x0 c x1 x2 H6 H9).\n\tintros. split with (umpl_conv_1 x3). rewrite H10. \n\texact (u_conv_1_invar_0 d x2 x3 H11). rewrite H10 in H2.\n\texact (upl_conv_1_occur x1 x2 H2). assumption.\nQed.\n\nLemma u_merge_ref_ok :\n forall d0 d1 : preDTA,\n preDTA_ref_ok d0 -> preDTA_ref_ok d1 -> preDTA_ref_ok (u_merge d0 d1).\nProof.\n\tunfold preDTA_ref_ok in |- *. intros. elim (adcnv_disj a); intro.\n\tintros. elim H4; intro. elim (u_conv_0_ref_ok d0 H a s c pl b (u_merge_0r d0 d1 a s H1 x H5) H2 H3). intros. split with x0.\n\texact (u_merge_0 d0 d1 b x0 H6). elim (u_conv_1_ref_ok d1 H0 a s c pl b (u_merge_1r d0 d1 a s H1 x H5) H2 H3). intros.\n\tsplit with x0. exact (u_merge_1 d0 d1 b x0 H6).\nQed.\n\nLemma upl_conv_compat_0_0 :\n forall p0 p1 : prec_list,\n pl_compat p0 p1 -> pl_compat (upl_conv_0 p0) (upl_conv_0 p1).\nProof.\n\tsimple induction p0. simple induction p2. intros. unfold pl_compat in |- *.\n\tright. split. intro. inversion H4. intro. inversion H4.\n\tintro. inversion H1. elim H2. intros. inversion H3.\n\telim H2. intros. elim (H4 (refl_equal prec_empty)).\n\tsimple induction p1. intros. unfold pl_compat in H1. elim H1; intros.\n\telim H2. intros; intros. inversion H4. elim H2. intros.\n\telim (H3 (refl_equal prec_empty)). intros. simpl in |- *.\n\tunfold pl_compat in |- *. left. split; trivial.\nQed.\n\nLemma upl_conv_compat_0_1 :\n forall p0 p1 : prec_list,\n pl_compat p0 p1 -> pl_compat (upl_conv_0 p0) (upl_conv_1 p1).\nProof.\n\tsimple induction p0. simple induction p2. intros. unfold pl_compat in |- *.\n\tright. split. intro. inversion H4. intro. inversion H4.\n\tintro. inversion H1. elim H2. intros. inversion H3.\n\telim H2. intros. elim (H4 (refl_equal prec_empty)).\n\tsimple induction p1. intros. unfold pl_compat in H1. elim H1; intros.\n\telim H2. intros; intros. inversion H4. elim H2. intros.\n\telim (H3 (refl_equal prec_empty)). intros. simpl in |- *.\n\tunfold pl_compat in |- *. left. split; trivial.\nQed.\n\nLemma upl_conv_compat_1_0 :\n forall p0 p1 : prec_list,\n pl_compat p0 p1 -> pl_compat (upl_conv_1 p0) (upl_conv_0 p1).\nProof.\n\tintros. exact (pl_compat_sym _ _ (upl_conv_compat_0_1 p1 p0 (pl_compat_sym _ _ H))).\nQed.\n\nLemma upl_conv_compat_1_1 :\n forall p0 p1 : prec_list,\n pl_compat p0 p1 -> pl_compat (upl_conv_1 p0) (upl_conv_1 p1).\nProof.\n\tsimple induction p0. simple induction p2. intros. unfold pl_compat in |- *.\n\tright. split. intro. inversion H4. intro. inversion H4.\n\tintro. inversion H1. elim H2. intros. inversion H3.\n\telim H2. intros. elim (H4 (refl_equal prec_empty)).\n\tsimple induction p1. intros. unfold pl_compat in H1. elim H1; intros.\n\telim H2. intros; intros. inversion H4. elim H2. intros.\n\telim (H3 (refl_equal prec_empty)). intros. simpl in |- *.\n\tunfold pl_compat in |- *. left. split; trivial.\nQed.\n\nLemma umpl_conv_0_compat :\n forall s0 s1 : state,\n mpl_compat s0 s1 -> mpl_compat (umpl_conv_0 s0) (umpl_conv_0 s1).\nProof.\n\tunfold mpl_compat in |- *. intros. elim (u_conv_0_invar_7 s0 c p0).\n\telim (u_conv_0_invar_7 s1 c p1). intros. elim H2. elim H3.\n\tintros. rewrite H4. rewrite H6. apply (upl_conv_compat_0_0 x0 x).\n\texact (H c x0 x H5 H7). assumption. assumption.\nQed.\n\nLemma umpl_conv_1_compat :\n forall s0 s1 : state,\n mpl_compat s0 s1 -> mpl_compat (umpl_conv_1 s0) (umpl_conv_1 s1).\nProof.\n\tunfold mpl_compat in |- *. intros. elim (u_conv_1_invar_7 s0 c p0).\n\telim (u_conv_1_invar_7 s1 c p1). intro. intros. elim H2. elim H3. \n\tintros. rewrite H4. rewrite H6. apply (upl_conv_compat_1_1 x0 x).\n\texact (H c x0 x H5 H7). assumption. assumption.\nQed.\n\nLemma umpl_conv_0_1_compat :\n forall s0 s1 : state,\n mpl_compat s0 s1 -> mpl_compat (umpl_conv_0 s0) (umpl_conv_1 s1).\nProof.\n\tunfold mpl_compat in |- *. intros. elim (u_conv_0_invar_7 s0 c p0 H0).\n\telim (u_conv_1_invar_7 s1 c p1). intros. elim H2. elim H3. intros.\n\trewrite H4. rewrite H6. apply (upl_conv_compat_0_1 x0 x). \n\texact (H c x0 x H5 H7). assumption.\nQed.\n\nLemma udta_conv_0_compat :\n forall d : preDTA, dta_correct d -> dta_correct (udta_conv_0 d).\nProof.\n\tunfold dta_correct in |- *. intros. elim (u_conv_0_invar_8 d a0 s0).\n\telim (u_conv_0_invar_8 d a1 s1). intros. rewrite H2 in H1.\n\trewrite H3 in H0. elim (u_conv_0_invar_5 d x s1 H1).\n\telim (u_conv_0_invar_5 d x0 s0 H0). intros. elim H4. elim H5.\n\tintros. rewrite H6. rewrite H8. exact (umpl_conv_0_compat x1 x2 (H x1 x2 x0 x H9 H7)). assumption. assumption.\nQed.\n\nLemma udta_conv_1_compat :\n forall d : preDTA, dta_correct d -> dta_correct (udta_conv_1 d).\nProof.\n\tunfold dta_correct in |- *. intros. elim (u_conv_1_invar_8 d a0 s0).\n\telim (u_conv_1_invar_8 d a1 s1). intros. rewrite H2 in H1.\n\trewrite H3 in H0. elim (u_conv_1_invar_5 d x s1 H1).\n\telim (u_conv_1_invar_5 d x0 s0 H0). intros. elim H4. elim H5.\n\tintros. rewrite H6. rewrite H8. exact (umpl_conv_1_compat x1 x2 (H x1 x2 x0 x H9 H7)). assumption. assumption.\nQed.\n\nLemma udta_conv_0_1_compat :\n forall d0 d1 : preDTA,\n dta_compat d0 d1 -> dta_compat (udta_conv_0 d0) (udta_conv_1 d1).\nProof.\n\tunfold dta_compat in |- *. intros. elim (u_conv_0_invar_8 d0 a0 s0 H0).\n\telim (u_conv_1_invar_8 d1 a1 s1 H1). intros. intros. rewrite H3 in H0.\n\trewrite H2 in H1. elim (u_conv_0_invar_5 d0 x0 s0 H0). elim (u_conv_1_invar_5 d1 x s1 H1). intros. elim H4. elim H5. intros.\n\trewrite H6. rewrite H8. exact (umpl_conv_0_1_compat x2 x1 (H x2 x1 x0 x H7 H9)).\nQed.\n\nLemma insert_ostate_9 :\n forall (d0 d1 : preDTA) (a0 a1 a : ad) (s0' s1' : state) (t : term),\n preDTA_ref_ok d0 ->\n preDTA_ref_ok d1 ->\n dta_compat d0 d1 ->\n MapGet state (u_merge d0 d1) (uad_conv_0 a0) = Some s0' ->\n MapGet state (u_merge d0 d1) (uad_conv_1 a1) = Some s1' ->\n a = new_preDTA_ad (u_merge d0 d1) ->\n (reconnaissance d0 a0 t \\/ reconnaissance d1 a1 t <->\n  reconnaissance\n    (insert_ostate (u_merge d0 d1) a (Some (union_mpl s0' s1'))) a t).\nProof.\n\tintros. elim\n  (u_conv_0_invar_5 d0 a0 s0'\n     (u_merge_0r d0 d1 (uad_conv_0 a0) s0' H2 a0 (refl_equal _))). elim\n  (u_conv_1_invar_5 d1 a1 s1'\n     (u_merge_1r d0 d1 (uad_conv_1 a1) s1' H3 a1 (refl_equal _))). intros. elim H5. elim H6. intros.\n\tcut (mpl_compat s0' s1'). intro. exact\n  (insert_ostate_8 d0 d1 a0 a1 a x0 x s0' s1' t H11 H8 H10 H2 H3\n     (u_merge_ref_ok d0 d1 H H0) H4). apply\n  (udta_conv_0_1_compat d0 d1 H1 s0' s1' (uad_conv_0 a0) (uad_conv_1 a1)). exact (u_merge_0r d0 d1 (uad_conv_0 a0) s0' H2 a0 (refl_equal _)). \n\texact (u_merge_1r d0 d1 (uad_conv_1 a1) s1' H3 a1 (refl_equal _)).\nQed.\n\nDefinition insert_main_ostate (d : preDTA) (o : option state) : DTA :=\n  insert_main_ostate_0 d (new_preDTA_ad d) o.\n\nDefinition union_opt_state (o0 o1 : option state) : \n  option state :=\n  match o0, o1 with\n  | None, None => None\n  | None, Some s1 => Some s1\n  | Some s0, None => Some s0\n  | Some s0, Some s1 => Some (union_mpl s0 s1)\n  end.\n\nDefinition union_0 (d : preDTA) (a0 a1 : ad) : option state :=\n  union_opt_state (MapGet state d (uad_conv_0 a0))\n    (MapGet state d (uad_conv_1 a1)).\n\nDefinition union_1 (d : preDTA) (a0 a1 : ad) : DTA :=\n  insert_main_ostate d (union_0 d a0 a1).\n\nDefinition union (dt0 dt1 : DTA) : DTA :=\n  match dt0, dt1 with\n  | dta d0 a0, dta d1 a1 => union_1 (u_merge d0 d1) a0 a1\n  end.\n\nLemma union_semantics_0 :\n forall (d0 d1 : DTA) (t : term),\n DTA_main_state_correct d0 ->\n DTA_main_state_correct d1 ->\n DTA_ref_ok d0 ->\n DTA_ref_ok d1 ->\n DTA_compat d0 d1 ->\n (reconnait d0 t \\/ reconnait d1 t <-> reconnait (union d0 d1) t).\nProof.\n\tunfold union in |- *. simple induction d0. simple induction d1. intros. unfold union_1 in |- *.\n\tunfold union_0 in |- *. elim H. elim H0. intros. unfold DTA_ref_ok in H1.\n\tunfold DTA_ref_ok in H2. unfold DTA_compat in H3. unfold insert_main_ostate in |- *.\n\tunfold insert_main_ostate_0 in |- *. unfold reconnait in |- *. rewrite\n  (u_merge_0 p p0 (uad_conv_0 a) (umpl_conv_0 x0)\n     (u_conv_0_invar_0 p a x0 H5)). rewrite\n  (u_merge_1 p p0 (uad_conv_1 a0) (umpl_conv_1 x)\n     (u_conv_1_invar_0 p0 a0 x H4)).\n\tunfold union_opt_state in |- *. apply\n  (insert_ostate_9 p p0 a a0 (new_preDTA_ad (u_merge p p0)) \n     (umpl_conv_0 x0) (umpl_conv_1 x) t H1 H2 H3). exact\n  (u_merge_0 p p0 (uad_conv_0 a) (umpl_conv_0 x0)\n     (u_conv_0_invar_0 p a x0 H5)).\n\texact\n  (u_merge_1 p p0 (uad_conv_1 a0) (umpl_conv_1 x)\n     (u_conv_1_invar_0 p0 a0 x H4)).\n\ttrivial.\nQed.\n\nLemma union_semantics :\n forall (d0 d1 : DTA) (sigma : signature) (t : term),\n DTA_main_state_correct d0 ->\n DTA_main_state_correct d1 ->\n DTA_ref_ok d0 ->\n DTA_ref_ok d1 ->\n dta_correct_wrt_sign d0 sigma ->\n dta_correct_wrt_sign d1 sigma ->\n (reconnait d0 t \\/ reconnait d1 t <-> reconnait (union d0 d1) t).\nProof.\n\tintros. apply (union_semantics_0 d0 d1 t H H0 H1 H2). exact\n  (dta_compatible_compat _ _ (dtas_correct_wrt_sign_compatibles _ _ _ H3 H4)).\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/union.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.5, "lm_q1q2_score": 0.27916348981849526}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nRequire Export Coq.Strings.String.\nFrom Coq Require Import Program.\n\nFrom Fairness Require Export ITreeLib EventCategory FairBeh NatStructs.\nFrom Fairness Require Export Mod.\n\nSet Implicit Arguments.\n\nLemma unfold_iter E A B (f: A -> itree E (A + B)) (x: A)\n  :\n  ITree.iter f x =\n    lr <- f x;;\n    match lr with\n    | inl l => tau;; ITree.iter f l\n    | inr r => Ret r\n    end.\nProof.\n  apply bisim_is_eq. eapply unfold_iter.\nQed.\n\n\nModule Th := NatMap.\nNotation thread _Id E R := (itree ((((@eventE _Id) +' cE) +' callE) +' E) R).\nNotation threads _Id E R := (Th.t (@thread _Id E R)).\n\nDefinition fn2th (m: Mod.t) (fn: fname) (args: Any.t): @thread (Mod.ident m) (sE (Mod.state m)) Any.t :=\n  match Mod.funs m fn with\n  | Some ktr => ktr args\n  | None => Vis (inl1 (inl1 (inl1 Undefined))) (Empty_set_rect _)\n  end.\n\nFixpoint _numbering {E} (l: list E) (n: NatMap.key): list (NatMap.key * E) :=\n  match l with\n  | hd :: tl => (n, hd) :: (_numbering tl (S n))\n  | [] => []\n  end.\n\nDefinition numbering {E} (l: list E): list (NatMap.key * E) := _numbering l O.\n\nDefinition prog2ths (m: Mod.t) (p: program): @threads (Mod.ident m) (sE (Mod.state m)) Any.t :=\n  let pre_threads := List.map (fun '(fn, args) => fn2th m fn args) p in\n  NatMapP.of_list (numbering pre_threads).\n\n\nSection STATE.\n\n  Variable S: Type.\n  Variable E: Type -> Type.\n\n  Let Es := E +' (sE S).\n\n  Definition interp_state_aux {R} :\n    (S * (itree Es R)) -> itree E (S * R).\n  Proof.\n    eapply ITree.iter. intros [state itr]. destruct (observe itr).\n    - exact (Ret (inr (state, r))).\n    - exact (Ret (inl (state, t))).\n    - destruct e.\n      + exact (Vis e (fun x => Ret (inl (state, k x)))).\n      + destruct s as [f].\n        exact (Ret (inl (fst (f state), k (snd (f state))))).\n  Defined.\n\n  Definition interp_state {R}:\n    (S * (itree Es R)) -> itree E R :=\n    fun x => r <- interp_state_aux x;;\n          Ret (snd r).\n\n  Lemma interp_state_aux_ret R st (r : R) :\n    interp_state_aux (st, Ret r) = Ret (st, r).\n  Proof. unfold interp_state_aux. rewrite unfold_iter. grind. Qed.\n\n  Lemma interp_state_aux_vis R st X (e : E X) (ktr : ktree Es X R) :\n    interp_state_aux (st, Vis (inl1 e) ktr) = Vis e (fun x => tau;; interp_state_aux (st, ktr x)).\n  Proof. unfold interp_state_aux. rewrite unfold_iter. grind.\n         apply observe_eta. ss. f_equal. extensionality x. grind.\n  Qed.\n\n  Lemma interp_state_aux_rmw R st X rmw (ktr : ktree Es X R) :\n    interp_state_aux (st, Vis (inr1 (Rmw rmw)) ktr) =\n      tau;; interp_state_aux (fst (rmw st), ktr (snd (rmw st))).\n  Proof. unfold interp_state_aux. rewrite unfold_iter. grind. Qed.\n\n  Lemma interp_state_aux_tau R st (itr : itree Es R) :\n    interp_state_aux (st, Tau itr) = Tau (interp_state_aux (st, itr)).\n  Proof. unfold interp_state_aux. rewrite unfold_iter. grind. Qed.\n\n  Lemma interp_state_aux_bind {R1} {R2} st (itr : itree Es R1) (ktr : ktree Es R1 R2) :\n    interp_state_aux (st, itr >>= ktr) =\n      x <- interp_state_aux (st, itr);;\n      interp_state_aux (fst x, ktr (snd x)).\n  Proof.\n    eapply bisim_is_eq. revert st itr. pcofix CIH. i.\n    destruct_itree itr.\n    - rewrite interp_state_aux_ret. grind.\n      eapply paco2_mon.\n      + eapply eq_is_bisim. ss.\n      + ss.\n    - grind. rewrite 2 interp_state_aux_tau. grind.\n      pfold. econs. right. eapply CIH.\n    - grind. destruct e.\n      + rewrite 2 interp_state_aux_vis. grind.\n        pfold. econs. intros. grind. left.\n        pfold. econs. right. eapply CIH.\n      + destruct s. rewrite ! interp_state_aux_rmw. grind.\n        pfold. econs. right. eapply CIH.\n  Qed.\n\n  Lemma unfold_interp_state R st (itr : itree Es R) :\n    interp_state (st, itr) = x <- interp_state_aux (st, itr);; Ret (snd x).\n  Proof. unfold interp_state. ss. Qed.\n\n  Lemma interp_state_bind R1 R2 st (itr : itree Es R1) (ktr : ktree Es R1 R2) :\n    interp_state (st, itr >>= ktr) = x <- interp_state_aux (st, itr);; interp_state (fst x, ktr (snd x)).\n  Proof. unfold interp_state. rewrite interp_state_aux_bind. grind. Qed.\n\n  Lemma interp_state_ret\n        R (r: R) (state: S)\n    :\n    interp_state (state, Ret r) = Ret r.\n  Proof.\n    unfold interp_state, interp_state_aux. rewrite unfold_iter. ss. grind.\n  Qed.\n\n  Lemma interp_state_tau\n        R (state: S) (itr: itree Es R)\n    :\n    interp_state (state, tau;; itr) = tau;; interp_state (state, itr).\n  Proof.\n    unfold interp_state, interp_state_aux. rewrite unfold_iter. ss. grind.\n  Qed.\n\n  Lemma interp_state_rmw_vis\n    R st X rmw (ktr : ktree Es X R)\n    : interp_state (st, Vis (|Rmw rmw)%sum ktr) =\n        tau;; interp_state (fst (rmw st), ktr (snd (rmw st))).\n  Proof. unfold interp_state. rewrite interp_state_aux_rmw. grind. Qed.\n\n  Lemma interp_state_rmw\n    R st X rmw (ktr : ktree Es X R)\n    : interp_state (st, trigger (Rmw rmw) >>= ktr) =\n        tau;; interp_state (fst (rmw st), ktr (snd (rmw st))).\n  Proof. rewrite bind_trigger. eapply interp_state_rmw_vis. Qed.\n\n  Lemma interp_state_get_vis\n        R (state: S) (ktr: S -> itree Es R)\n    :\n    interp_state (state, Vis (inr1 (Get id)) ktr)\n    =\n      tau;; interp_state (state, ktr state).\n  Proof.\n    unfold interp_state, interp_state_aux. rewrite get_rmw, unfold_iter. ss. grind.\n  Qed.\n\n  Lemma interp_state_get\n        R (state: S) (ktr: S -> itree Es R)\n    :\n    interp_state (state, trigger (inr1 (Get id)) >>= ktr)\n    =\n      tau;; interp_state (state, ktr state).\n  Proof.\n    rewrite bind_trigger. apply interp_state_get_vis.\n  Qed.\n\n  Lemma interp_state_vis\n        R (state: S) X (e: E X) (ktr: X -> itree Es R)\n    :\n    interp_state (state, Vis (inl1 e) ktr)\n    =\n      Vis e (fun x => tau;; interp_state (state, ktr x)).\n  Proof.\n    unfold interp_state, interp_state_aux. rewrite unfold_iter. ss. rewrite 2 bind_vis.\n    apply observe_eta. ss. f_equal. extensionality x.\n    rewrite bind_ret_l. rewrite bind_tau. reflexivity.\n  Qed.\n\n  Lemma interp_state_trigger\n        R (state: S) X (e: E X) (ktr: X -> itree Es R)\n    :\n    interp_state (state, trigger (inl1 e) >>= ktr)\n    =\n      x <- trigger e;; tau;; interp_state (state, ktr x).\n  Proof.\n    rewrite ! bind_trigger. apply interp_state_vis.\n  Qed.\n\nEnd STATE.\nGlobal Opaque interp_state_aux interp_state.\n\n\nSection STATE_PROP.\n\n  Variable State: Type.\n\n  Lemma interp_state_aux_map_event E1 E2 R (embed : forall X, E1 X -> E2 X) st (itr : itree (E1 +' sE State) R) :\n    interp_state_aux (st, map_event (embed_left embed) itr) = map_event embed (interp_state_aux (st, itr)).\n  Proof.\n    eapply bisim_is_eq. revert st itr. pcofix CIH. i.\n    destruct_itree itr.\n    - rewrite map_event_ret.\n      rewrite 2 interp_state_aux_ret.\n      rewrite map_event_ret.\n      pfold. econs. ss.\n    - rewrite map_event_tau.\n      rewrite 2 interp_state_aux_tau.\n      rewrite map_event_tau.\n      pfold. econs. right. eapply CIH.\n    - rewrite map_event_vis.\n      destruct e.\n      + ss. rewrite 2 interp_state_aux_vis.\n        rewrite map_event_vis.\n        pfold. econs. intros. left.\n        rewrite map_event_tau.\n        pfold. econs. right. eapply CIH.\n      + ss. destruct s.\n        rewrite ! interp_state_aux_rmw.\n        rewrite ! map_event_tau.\n        pfold. econs. right. eapply CIH.\n  Qed.\n\nEnd STATE_PROP.\n\n\n\nSection SCHEDULE.\n\n  Variant schedulerE (RT : Type) : Type -> Type :=\n  | Execute : thread_id -> schedulerE RT (option RT)\n  .\n\n  Let eventE0 := @eventE thread_id.\n\n  Definition scheduler RT R := itree (schedulerE RT +' eventE0) R.\n\n  Context {_Ident: ID}.\n  Variable E: Type -> Type.\n\n  Let eventE1 := @eventE _Ident.\n  Let eventE2 := @eventE (sum_tid _Ident).\n  Let Es0 := ((eventE1 +' cE) +' callE) +' E.\n  Let thread R := thread _Ident E R.\n  Let threads R := threads _Ident E R.\n\n  Definition interp_thread_aux {R} :\n    thread_id * thread R -> itree (eventE1 +' E) (thread R + R).\n  Proof.\n    eapply ITree.iter.\n    intros [tid itr].\n    apply observe in itr; destruct itr as [r | itr | X e k].\n    - (* Ret *)\n      exact (Ret (inr (inr r))).\n    - (* Tau *)\n      exact (Ret (inl (tid, itr))).\n    - (* Vis *)\n      destruct e as [[[]|]|].\n      + (* eventE *)\n        exact (Vis (inl1 e) (fun x => Ret (inl (tid, k x)))).\n      + (* cE *)\n        destruct c.\n        * (* Yield *)\n          exact (Ret (inr (inl (k tt)))).\n        * (* GetTid *)\n          exact (Ret (inl (tid, k tid))).\n      + (* callE *)\n        exact (Vis (inl1 Undefined) (Empty_set_rect _)).\n      + (* E *)\n        exact (Vis (inr1 e) (fun x => Ret (inl (tid, k x)))).\n  Defined.\n\n  Definition interp_thread {R} :\n    thread_id * thread R -> itree (eventE2 +' E) (thread R + R) :=\n    fun x => map_event (embed_left (map_prism inrp)) (interp_thread_aux x).\n\n  Definition interp_sched RT R : threads RT * scheduler RT R -> itree (eventE2 +' E) R.\n  Proof.\n    eapply ITree.iter. intros [ts sch].\n    destruct (observe sch) as [r | sch' | X [e|e] ktr].\n    - exact (Ret (inr r)).\n    - exact (Ret (inl (ts, sch'))).\n    - destruct e.\n      destruct (Th.find n ts) as [t|].\n      * exact (r <- interp_thread (n, t);;\n               match r with\n               | inl t' => Ret (inl (Th.add n t' ts, ktr None))\n               | inr r => Ret (inl (Th.remove n ts, ktr (Some r)))\n               end).\n      * exact (Vis (inl1 Undefined) (Empty_set_rect _)).\n    - exact (Vis (inl1 (map_prism inlp e)) (fun x => Ret (inl (ts, ktr x)))).\n  Defined.\n\n  Lemma unfold_interp_thread {R} tid (itr : thread R) :\n    interp_thread (tid, itr) = map_event (embed_left (map_prism inrp)) (interp_thread_aux (tid, itr)).\n  Proof. ss. Qed.\n\n  Lemma interp_thread_ret {R} tid (r : R) :\n    interp_thread (tid, Ret r) = Ret (inr r).\n  Proof. unfold interp_thread, interp_thread_aux. rewrite unfold_iter. grind. eapply map_event_ret. Qed.\n\n  Lemma interp_thread_tau R tid (itr : thread R) :\n    interp_thread (tid, tau;; itr) = tau;; interp_thread (tid, itr).\n  Proof. unfold interp_thread at 1, interp_thread_aux. rewrite unfold_iter. grind. eapply map_event_tau. Qed.\n\n  Lemma interp_thread_vis R tid X (e : E X) (ktr : ktree Es0 X R) :\n    interp_thread (tid, Vis (inr1 e) ktr) =\n      Vis (inr1 e) (fun x => tau;; interp_thread (tid, ktr x)).\n  Proof.\n    unfold interp_thread at 1, interp_thread_aux. rewrite unfold_iter. grind. rewrite map_event_vis.\n    eapply (f_equal (fun x => Vis (inr1 e) x)). extensionality x. grind. rewrite map_event_tau. grind.\n  Qed.\n\n  Lemma interp_thread_trigger R tid X (e : E X) (ktr : ktree Es0 X R) :\n    interp_thread (tid, x <- trigger (inr1 e);; ktr x) =\n      x <- trigger (inr1 e);; tau;; interp_thread (tid, ktr x).\n  Proof. rewrite ! bind_trigger. eapply interp_thread_vis. Qed.\n\n  Lemma interp_thread_vis_eventE R tid X (e : eventE1 X) (ktr : ktree Es0 X R) :\n    interp_thread (tid, Vis (inl1 (inl1 (inl1 e))) ktr) =\n      Vis (inl1 (map_prism inrp e)) (fun x => tau;; interp_thread (tid, ktr x)).\n  Proof.\n    unfold interp_thread at 1, interp_thread_aux. rewrite unfold_iter. grind. rewrite map_event_vis.\n    eapply (f_equal (fun x => Vis (inl1 (map_prism inrp e)) x)). extensionality x. grind. rewrite map_event_tau. grind.\n  Qed.\n\n  Lemma interp_thread_trigger_eventE R tid X (e : eventE1 X) (ktr : ktree Es0 X R) :\n    interp_thread (tid, x <- trigger (inl1 (inl1 e));; ktr x) =\n      x <- trigger (inl1 (map_prism inrp e));; tau;; interp_thread (tid, ktr x).\n  Proof. rewrite ! bind_trigger. eapply interp_thread_vis_eventE. Qed.\n\n  Lemma interp_thread_vis_gettid R tid (ktr : ktree Es0 thread_id R) :\n    interp_thread (tid, Vis (inl1 (inl1 (inr1 GetTid))) ktr) =\n      tau;; interp_thread (tid, ktr tid).\n  Proof.\n    unfold interp_thread at 1, interp_thread_aux. rewrite unfold_iter. grind. rewrite map_event_tau. grind.\n  Qed.\n\n  Lemma interp_thread_trigger_gettid R tid (ktr : ktree Es0 thread_id R) :\n    interp_thread (tid, x <- trigger (inl1 (inr1 GetTid));; ktr x) =\n      tau;; interp_thread (tid, ktr tid).\n  Proof. rewrite bind_trigger. eapply interp_thread_vis_gettid. Qed.\n\n  Lemma interp_thread_vis_yield R tid (ktr : ktree Es0 () R) :\n    interp_thread (tid, Vis (inl1 (inl1 (inr1 Yield))) ktr) =\n      Ret (inl (ktr tt)).\n  Proof.\n    unfold interp_thread at 1, interp_thread_aux. rewrite unfold_iter. grind. rewrite map_event_ret. ss.\n  Qed.\n\n  Lemma interp_thread_trigger_yield R tid (ktr : ktree Es0 () R) :\n    interp_thread (tid, x <- trigger (inl1 (inr1 Yield));; ktr x) =\n      Ret (inl (ktr tt)).\n  Proof. rewrite bind_trigger. apply interp_thread_vis_yield. Qed.\n\n  Lemma interp_thread_call R tid fn args (ktr : ktree Es0 Any.t R) :\n    interp_thread (tid, trigger (Call fn args) >>= ktr) = Vis (inl1 Undefined) (Empty_set_rect _).\n  Proof. unfold interp_thread at 1, interp_thread_aux. rewrite unfold_iter. grind.\n         rewrite map_event_vis. eapply observe_eta. ss. f_equal. extensionalities x. ss.\n  Qed.\n\n  Lemma interp_sched_ret RT R (ths : threads RT) (r : R) :\n    interp_sched (ths, Ret r) = Ret r.\n  Proof. unfold interp_sched. rewrite unfold_iter. grind. Qed.\n\n  Lemma interp_sched_tau RT R ths (itr : scheduler RT R) :\n    interp_sched (ths, Tau itr) = Tau (interp_sched (ths, itr)).\n  Proof. unfold interp_sched. rewrite unfold_iter. grind. Qed.\n\n  Lemma interp_sched_execute_Some RT R ths tid t (ktr : option RT -> scheduler RT R)\n    (SOME : Th.find tid ths = Some t)\n    : interp_sched (ths, Vis (inl1 (Execute _ tid)) ktr) =\n      r <- interp_thread (tid, t);;\n      match r with\n      | inl t' => tau;; interp_sched (Th.add tid t' ths, ktr None)\n      | inr r => tau;; interp_sched (Th.remove tid ths, ktr (Some r))\n      end.\n  Proof. unfold interp_sched. rewrite unfold_iter. grind. Qed.\n\n  Lemma interp_sched_execute_None RT R ths tid (ktr : option RT -> scheduler RT R)\n    (NONE : Th.find tid ths = None)\n    : interp_sched (ths, Vis (inl1 (Execute _ tid)) ktr) =\n        Vis (inl1 Undefined) (Empty_set_rect _).\n  Proof. unfold interp_sched. rewrite unfold_iter. grind.\n         eapply observe_eta. ss. f_equal. extensionality x. ss.\n  Qed.\n\n  Lemma interp_sched_vis RT R ths X (e : eventE0 X) (ktr : X -> scheduler RT R) :\n    interp_sched (ths, Vis (inr1 e) ktr) =\n      Vis (inl1 (map_prism inlp e)) (fun x => tau;; interp_sched (ths, ktr x)).\n  Proof. unfold interp_sched. rewrite unfold_iter. grind.\n         eapply observe_eta. ss. f_equal. extensionality x. grind.\n  Qed.\n\nEnd SCHEDULE.\nGlobal Opaque interp_thread_aux interp_thread interp_sched.\n\n\n\nSection SCHEDULE_NONDET.\n\n  Definition sched_nondet_body {R} q tid r : scheduler R (thread_id * TIdSet.t + R) :=\n    match r with\n    | None =>\n        tid' <- ITree.trigger (inr1 (Choose thread_id));;\n        match nm_pop tid' (NatSet.add tid q) with\n        | None => Vis (inr1 (Choose void)) (Empty_set_rect _)\n        | Some (_, q') =>\n            ITree.trigger (inr1 (Fair (tids_fmap tid' q')));;;\n            Ret (inl (tid', q'))\n        end\n    | Some r =>\n        if NatMap.is_empty q\n        then Ret (inr r)\n        else\n          tid' <- ITree.trigger (inr1 (Choose thread_id));;\n          match nm_pop tid' q with\n          | None => Vis (inr1 (Choose void)) (Empty_set_rect _)\n          | Some (_, q') =>\n              ITree.trigger (inr1 (Fair (tids_fmap tid' q')));;;\n              Ret (inl (tid', q'))\n          end\n    end.\n\n  Definition sched_nondet R0 : thread_id * TIdSet.t -> scheduler R0 R0 :=\n    ITree.iter (fun '(tid, q) =>\n                  r <- ITree.trigger (inl1 (Execute _ tid));;\n                  sched_nondet_body q tid r).\n\n  Lemma unfold_sched_nondet R0 tid q :\n    sched_nondet R0 (tid, q) =\n      r <- ITree.trigger (inl1 (Execute _ tid));;\n      match r with\n      | None =>\n          tid' <- ITree.trigger (inr1 (Choose thread_id));;\n          match nm_pop tid' (NatSet.add tid q) with\n          | None => Vis (inr1 (Choose void)) (Empty_set_rect _)\n          | Some (_, q') =>\n              ITree.trigger (inr1 (Fair (tids_fmap tid' q')));;;\n              tau;; sched_nondet _ (tid', q')\n          end\n      | Some r =>\n          if NatMap.is_empty q\n          then Ret r\n          else\n            tid' <- ITree.trigger (inr1 (Choose thread_id));;\n            match nm_pop tid' q with\n            | None => Vis (inr1 (Choose void)) (Empty_set_rect _)\n            | Some (_, q') =>\n                ITree.trigger (inr1 (Fair (tids_fmap tid' q')));;;\n                tau;; sched_nondet _ (tid', q')\n            end\n      end.\n  Proof.\n    unfold sched_nondet at 1, sched_nondet_body.\n    rewrite unfold_iter.\n    grind.\n    - eapply observe_eta. ss. f_equal. extensionality x0. ss.\n    - eapply observe_eta. ss. f_equal. extensionality x0. ss.\n  Qed.\n\n\n  Context {_Ident : ID}.\n  Variable E: Type -> Type.\n\n  Let eventE1 := @eventE _Ident.\n  Let eventE2 := @eventE (sum_tid _Ident).\n  Let Es0 := (eventE1 +' cE) +' E.\n  Let thread R := thread _Ident E R.\n  Let threads R := threads _Ident E R.\n\n  Lemma unfold_interp_sched_nondet_Some R tid t (ths : threads R) q :\n    Th.find tid ths = Some t ->\n    interp_sched (ths, sched_nondet R (tid, q)) =\n      r <- interp_thread (tid, t);;\n      match r with\n      | inl t' => Tau (interp_sched (Th.add tid t' ths,\n                                     tid' <- ITree.trigger (inr1 (Choose thread_id));;\n                                     match nm_pop tid' (NatSet.add tid q) with\n                                     | None => Vis (inr1 (Choose void)) (Empty_set_rect _)\n                                     | Some (_, q') =>\n                                         ITree.trigger (inr1 (Fair (tids_fmap tid' q')));;;\n                                         tau;; sched_nondet _ (tid', q')\n                                     end))\n      | inr r => Tau (interp_sched (Th.remove tid ths,\n                                    if NatMap.is_empty q\n                                    then Ret r\n                                    else\n                                      tid' <- ITree.trigger (inr1 (Choose thread_id));;\n                                      match nm_pop tid' q with\n                                      | None => Vis (inr1 (Choose void)) (Empty_set_rect _)\n                                      | Some (_, q') =>\n                                          ITree.trigger (inr1 (Fair (tids_fmap tid' q')));;;\n                                          tau;; sched_nondet _ (tid', q')\n                                      end))\n      end.\n  Proof.\n    rewrite unfold_sched_nondet at 1.\n    rewrite bind_trigger.\n    eapply interp_sched_execute_Some.\n  Qed.\n\n  Lemma unfold_interp_sched_nondet_None R tid (ths : threads R) q :\n    Th.find tid ths = None ->\n    interp_sched (ths, sched_nondet R (tid, q)) =\n      Vis (inl1 Undefined) (Empty_set_rect _).\n  Proof.\n    rewrite unfold_sched_nondet at 1.\n    rewrite bind_trigger.\n    eapply interp_sched_execute_None.\n  Qed.\n\nEnd SCHEDULE_NONDET.\nGlobal Opaque sched_nondet_body sched_nondet.\n\n\n\nSection INTERP.\n\n  Variable State: Type.\n  Variable _Ident: ID.\n  Variable R: Type.\n\n  Definition interp_all\n    st (ths: @threads _Ident (sE State) R) tid : itree (@eventE (sum_tid _Ident)) R :=\n    interp_state (st, interp_sched (ths, sched_nondet _ (tid, NatSet.remove tid (key_set ths)))).\n\n  Lemma interp_all_tau\n        st (ths: @threads _Ident (sE State) R) tid\n        itr\n    :\n    (interp_all st (Th.add tid (Tau itr) ths) tid) = (Tau (interp_all st (Th.add tid itr ths) tid)).\n  Proof.\n    unfold interp_all. erewrite ! unfold_interp_sched_nondet_Some; eauto using nm_find_add_eq.\n    rewrite interp_thread_tau. rewrite bind_tau. rewrite interp_state_tau.\n    do 5 f_equal. extensionality x. destruct x.\n    - rewrite ! nm_add_add_eq. rewrite ! key_set_pull_add_eq. auto.\n    - erewrite 1 nm_rm_add_eq. rewrite ! key_set_pull_add_eq. eauto.\n  Qed.\n\n  Lemma interp_all_vis\n        st (ths: @threads _Ident (sE State) R) tid\n        X (e: @eventE _Ident X) ktr\n    :\n    (interp_all st (Th.add tid (Vis (((e|)|)|)%sum ktr) ths) tid) =\n      (Vis (map_prism inrp e) (fun x => tau;; tau;; interp_all st (Th.add tid (ktr x) ths) tid)).\n  Proof.\n    unfold interp_all. erewrite ! unfold_interp_sched_nondet_Some; eauto using nm_find_add_eq.\n    rewrite interp_thread_vis_eventE. rewrite bind_vis. rewrite interp_state_vis.\n    do 2 f_equal. extensionality x. rewrite bind_tau. rewrite interp_state_tau.\n    erewrite 1 unfold_interp_sched_nondet_Some; eauto using nm_find_add_eq.\n    do 7 f_equal. extensionality r.\n    destruct r.\n    - rewrite ! nm_add_add_eq. rewrite ! key_set_pull_add_eq. auto.\n    - erewrite 1 nm_rm_add_eq. rewrite ! key_set_pull_add_eq. eauto.\n  Qed.\n\n  Lemma interp_all_rmw\n    st (ths : @threads _Ident (sE State) R) tid\n    X rmw ktr\n    : interp_all st (Th.add tid (Vis (|Rmw rmw)%sum ktr) ths) tid =\n        tau;; tau;; interp_all (fst (rmw st)) (Th.add tid (ktr (snd (rmw st) : X)) ths) tid .\n  Proof.\n    unfold interp_all. erewrite ! unfold_interp_sched_nondet_Some; eauto using nm_find_add_eq.\n    rewrite interp_thread_vis. rewrite bind_vis. rewrite interp_state_rmw_vis.\n    rewrite bind_tau. rewrite interp_state_tau.\n    repeat f_equal. extensionalities x.\n    destruct x.\n    - rewrite ! nm_add_add_eq. rewrite ! key_set_pull_add_eq. auto.\n    - erewrite 1 nm_rm_add_eq. rewrite ! key_set_pull_add_eq. eauto.\n  Qed.\n\n  Lemma interp_all_get\n        st (ths: @threads _Ident (sE State) R) tid\n        ktr\n    :\n    (interp_all st (Th.add tid (Vis (|Get id)%sum ktr) ths) tid) =\n      (tau;; tau;; interp_all st (Th.add tid (ktr st) ths) tid).\n  Proof.\n    unfold interp_all. erewrite ! unfold_interp_sched_nondet_Some; eauto using nm_find_add_eq.\n    rewrite interp_thread_vis. rewrite bind_vis. rewrite interp_state_get_vis. rewrite bind_tau. rewrite interp_state_tau.\n    repeat f_equal. extensionality x.\n    destruct x.\n    - rewrite ! nm_add_add_eq. rewrite ! key_set_pull_add_eq. auto.\n    - erewrite 1 nm_rm_add_eq. rewrite ! key_set_pull_add_eq. eauto.\n  Qed.\n\n  Lemma interp_all_tid\n        st (ths: @threads _Ident (sE State) R) tid\n        ktr\n    :\n    (interp_all st (Th.add tid (Vis (((|GetTid)|)|)%sum ktr) ths) tid) =\n      (tau;; interp_all st (Th.add tid (ktr tid) ths) tid).\n  Proof.\n    unfold interp_all. erewrite ! unfold_interp_sched_nondet_Some; eauto using nm_find_add_eq.\n    rewrite interp_thread_vis_gettid. rewrite bind_tau. rewrite interp_state_tau.\n    repeat f_equal. extensionality x.\n    destruct x.\n    - rewrite ! nm_add_add_eq. rewrite ! key_set_pull_add_eq. auto.\n    - erewrite 1 nm_rm_add_eq. rewrite ! key_set_pull_add_eq. eauto.\n  Qed.\n\n  Lemma interp_all_call\n    st (ths: @threads _Ident (sE State) R) tid\n    fn args ktr\n    : interp_all st (Th.add tid (trigger (Call fn args) >>= ktr) ths) tid = trigger Undefined >>= Empty_set_rect _.\n  Proof.\n    unfold interp_all. erewrite ! unfold_interp_sched_nondet_Some; eauto using nm_find_add_eq.\n    rewrite interp_thread_call. rewrite bind_vis. rewrite interp_state_vis. rewrite ! bind_trigger.\n    eapply observe_eta. ss. f_equal. extensionalities s. ss.\n  Qed.\n\nEnd INTERP.\n\nSection MOD.\n\n  Variable mod : Mod.t.\n  Let st := (Mod.st_init mod).\n  Let Ident := (Mod.ident mod).\n  Let main := ((Mod.funs mod) \"main\").\n\n  Definition interp_mod\n             (tid: thread_id)\n             (ths: @threads (Mod.ident mod) (sE (Mod.state mod)) Val)\n             (sched: forall R, (thread_id * TIdSet.t)%type -> (scheduler R R)):\n    itree (@eventE (sum_tid Ident)) Val :=\n    interp_state (st, interp_sched (ths, sched _ (tid, NatSet.remove tid (key_set ths)))).\n\nEnd MOD.\n", "meta": {"author": "damhiya", "repo": "fairness", "sha": "279dcc679bd18b85666b97d6b540d94299c5d66e", "save_path": "github-repos/coq/damhiya-fairness", "path": "github-repos/coq/damhiya-fairness/fairness-279dcc679bd18b85666b97d6b540d94299c5d66e/src/semantics/Concurrency.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.5, "lm_q1q2_score": 0.27916348981849526}}
{"text": "Require Import List.\nImport ListNotations.\n\nRequire Import FSets FSets.FMapAVL FSets.FMapFacts.\n\nFrom Verbatim Require Import state.\nFrom Verbatim Require Import memo.\nFrom Verbatim Require Import ltac.\nFrom Verbatim Require Import Orders.\nFrom Verbatim Require Import hashtrie.\n\n\nModule FMemo (STT : state.T) <: MEMO STT.\n\n  Import STT.Ty.\n  Import STT.Defs.\n  Import STT.R.Defs.\n  Import Trie.\n\n  Module Pointer_as_UOT <: UsualOrderedType := UOT_from_UCT Pointer_as_UCT.\n  Module FM := FMapAVL.Make Pointer_as_UOT.\n  Module FMF := FMapFacts.Facts FM.\n\n  Definition Memo : Type := FM.t (@Trie (option (String * String * index))).\n  Definition emptyMemo : Memo := FM.empty (@Trie (option (String * String * index))).\n  \n  Definition get_Memo (M : Memo) (pnt : Pointer) (i : index)\n    : option (option (String * String * index)) :=\n    match FM.find pnt M with\n    | None => None\n    | Some T => get_Trie T (index2list i)\n    end.\n  \n  Definition set_Memo (M : Memo) (pnt : Pointer) (i : index)\n             (o : (option (String * String * index))) : Memo :=\n    match FM.find pnt M with\n    | None => FM.add pnt (set_Trie Leaf (index2list i) o) M\n    | Some T => FM.add pnt (set_Trie T (index2list i) o) M \n    end.\n\n  Lemma correct_Memo : forall M ptr i o, get_Memo (set_Memo M ptr i o) ptr i = Some o.\n  Proof.\n    intros. unfold get_Memo. unfold set_Memo. repeat dm.\n    - rewrite FMF.add_eq_o in E; auto. repeat inj_all. apply get_set.\n    - rewrite FMF.add_eq_o in E; auto. repeat inj_all. apply get_set.\n    - rewrite FMF.add_eq_o in E; auto. discriminate.\n    - rewrite FMF.add_eq_o in E; auto. discriminate.\n  Qed.\n\n  \n  Lemma correct_Memo_moot : forall M ptr ptr' i i' o,\n      (ptr <> ptr' \\/ i <> i')\n      -> \n      get_Memo (set_Memo M ptr' i' o) ptr i = get_Memo M ptr i.\n  Proof.\n    intros. unfold get_Memo. unfold set_Memo.\n    destruct (Pointer_as_UOT.eq_dec ptr ptr') eqn:E;\n      destruct (index_eq_dec i i'); destruct H;\n      repeat dm;\n      try(rewrite FMF.add_neq_o in *; auto; rewrite E in *; repeat inj_all; auto; discriminate);\n      try(rewrite FMF.add_eq_o in *; auto;\n          repeat inj_all; rewrite E1 in *; repeat inj_all; rewrite get_set_moot; auto;\n          intros C; destruct H; apply f_equal with (f := list2index) in C;\n          repeat rewrite list_inv in C; auto; discriminate);\n      try(try subst i; rewrite FMF.add_neq_o in *; auto; rewrite E0 in *;\n          repeat inj_all; auto; discriminate);\n      try(subst ptr; rewrite E1 in *; discriminate).\n    - rewrite FMF.add_eq_o in *; auto; discriminate.\n  Qed.\n    \n  Lemma correct_emptyMemo : forall stt z, get_Memo emptyMemo stt z = None.\n  Proof.\n    intros. unfold get_Memo. unfold emptyMemo. repeat dm.\n    rewrite FMF.empty_o in E. discriminate.\n  Qed.\n  \n\nEnd FMemo.\n\n\nModule memoTFn (STT' : state.T) <: memo.T.\n  Module STT := STT'.\n  Module MemTy <: MEMO STT := FMemo STT.\n  Module Defs := memo.MemoDefsFn STT MemTy.\nEnd memoTFn.\n", "meta": {"author": "egolf-cs", "repo": "Verbatim", "sha": "97133d764ca742c7abe190808b304e2c535bb19c", "save_path": "github-repos/coq/egolf-cs-Verbatim", "path": "github-repos/coq/egolf-cs-Verbatim/Verbatim-97133d764ca742c7abe190808b304e2c535bb19c/Verbatim/memo/concrete_memo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2790285113400851}}
{"text": "Require Import HahnBase.\n\nRequire Import VST.floyd.proofauto.\nRequire Import VST.floyd.library.\nRequire Import printer.printer_files.compiled_format.\nRequire Import printer.verified_printer.Format.\nRequire Import printer.verified_printer.FormatTrivial.\nRequire Import Coq.Strings.Ascii.\nRequire Import format_specs.\n\nDefinition t_flist := Tstruct _format_list noattr.\n\nFixpoint listrepf (sigma: list t) (p: val) : mpred :=\n match sigma with\n | G::hs =>\n    EX x:val, EX y: val,\n    mformat G y *\n    malloc_token Ews t_flist p * \n    data_at Ews t_flist ((y, x) : @reptype CompSpecs t_flist) p *\n    listrepf hs x\n | nil =>\n    !! (<< LIST_NULL_PTR : p = nullval >> ) && emp\n end.\n\nArguments listrepf sigma p : simpl never.\n\nLemma listrepf_local_facts sigma p :\n   listrepf sigma p |--\n   !! (<< LIST_PTR_FACT : is_pointer_or_null p /\\ (p=nullval <-> sigma=nil) >>).\nProof.\n  intros.\n  revert p; induction sigma; intros p.\n  { unfold listrepf. unnw. entailer!. split; auto. }\n  unff listrepf.\n  destruct a. entailer. unnw. entailer!.\n  split; ins.\n  subst. eapply field_compatible_nullval; eauto.\nQed.\n#[export] Hint Resolve listrepf_local_facts : saturate_local.\n\nLemma listrepf_valid_pointer sigma p :\n   listrepf sigma p |-- valid_pointer p.\nProof.\n  intros.\n  unfold listrepf. destruct sigma; simpl; unnw.\n  { entailer!. }\n  Intros x y. auto with valid_pointer.\nQed.\n#[export] Hint Resolve listrepf_valid_pointer : valid_pointer.\n\nFixpoint lsegf (sigma: list t) (x z: val) : mpred :=\n  match sigma with\n  | nil => !! (<< LSEG_PTR_FACT : x = z >>) && emp\n  | G::hs => EX h: val, EX y:val, \n      mformat G y *\n      malloc_token Ews t_flist x * \n      data_at Ews t_flist ((y, h) : @reptype CompSpecs t_flist) x *\n      lsegf hs h z\n  end.\n\nArguments lsegf sigma x z : simpl never.\n\nDefinition good_format (G : t) (w h : Z) : Prop :=\n   (total_width G <= Z.to_nat w)%nat /\\ (G.(height) <= Z.to_nat h)%nat.\n\nDefinition good_format_list (sigma : list t) (w h : Z) : Prop :=\n  Forall (fun G => good_format G w h) sigma.\n\nDefinition clear_to_text_spec : ident * funspec :=\nDECLARE _clear_to_text\n   WITH l : list (Z * list byte), p : val, gv : globals\n   PRE [ tptr t_list ]\n      PROP() PARAMS(p) GLOBALS(gv)\n      SEP (listrep l p; mem_mgr gv)\n   POST [ tvoid ]\n      PROP() RETURN() SEP(mem_mgr gv).\n\nDefinition clear_format_list_spec : ident * funspec :=\nDECLARE _clear_format_list\n   WITH fs : list t, p : val, gv : globals\n   PRE [ tptr t_flist ]\n      PROP() PARAMS(p) GLOBALS(gv)\n      SEP (listrepf fs p; mem_mgr gv)\n   POST [ tvoid ]\n      PROP() RETURN() SEP(mem_mgr gv).\n\nDefinition beside_doc_spec : ident * funspec :=\nDECLARE _beside_doc\n   WITH fs1 : list t, fs2 : list t, p1 : val, p2 : val, w : Z, h : Z, gv : globals\n   PRE [ tuint, tuint, tptr t_flist, tptr t_flist ]\n      PROP (good_format_list fs1 w h; good_format_list fs2 w h;\n            0 <= 4 * w <= Int.max_unsigned;\n            0 <= 4 * h <= Int.max_unsigned)\n      PARAMS(Vint (Int.repr w); Vint (Int.repr h); p1; p2) GLOBALS(gv)\n      SEP (listrepf fs1 p1; listrepf fs2 p2; mem_mgr gv)\n   POST [ tptr t_flist ]\n      EX p: val, EX sigma: list t,\n      PROP (good_format_list sigma w h;\n            sigma = filter (fun G => (G.(height) <=? (Z.to_nat h))%nat) (besideDoc (Z.to_nat w) fs1 fs2))\n      RETURN(p)\n      SEP (listrepf sigma p; mem_mgr gv).\n\nDefinition Gprog : funspecs :=\n        ltac:(with_library prog [\n                   max_spec; strlen_spec; strcpy_spec; strcat_spec;\n                   list_copy_spec; less_components_spec; is_less_than_spec; \n                   empty_spec; line_spec; sp_spec; \n                   get_applied_length_spec; format_copy_spec; get_list_tail_spec;\n                   mdw_add_above_spec; list_concat_spec; to_text_add_above_spec;\n                   new_list_spec; add_above_spec;\n                   flw_add_beside_spec; shift_list_spec; add_beside_spec; line_concats_spec;\n                   mdw_add_beside_spec; to_text_add_beside_spec;\n                   mdw_add_fill_spec; flw_add_fill_spec; to_text_add_fill_spec;\n                   llw_add_fill_spec; add_fill_spec; beside_doc_spec; clear_format_list_spec; clear_to_text_spec\n ]).", "meta": {"author": "klimoza", "repo": "verified-kisa", "sha": "26a706787097b44106416f59702b7f44a18e0d2a", "save_path": "github-repos/coq/klimoza-verified-kisa", "path": "github-repos/coq/klimoza-verified-kisa/verified-kisa-26a706787097b44106416f59702b7f44a18e0d2a/proof/list_specs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2790285113400851}}
{"text": "From iris.algebra Require Import frac.\nFrom iris.proofmode Require Import tactics.\nRequire Import Eqdep_dec List.\nFrom cap_machine Require Import stack_macros_helpers.\nFrom cap_machine Require Export iris_extra addr_reg_sample contiguous.\nFrom cap_machine Require Import macros.\nFrom cap_machine.binary_model.rules_binary Require Import rules_binary rules_binary_StoreU_derived.\nFrom cap_machine.binary_model.examples_binary Require Import req_binary.\n\nLtac iPrologue_s prog :=\n  (try iPrologue_pre);\n  iDestruct prog as \"[Hi Hprog]\".\n\nLtac iEpilogue_s :=\n   iMod (do_step_pure _ [] with \"[$Hspec $Hj]\") as \"Hj\";auto;\n   iSimpl in \"Hj\".\n\nSection macros.\n  Context {Σ:gFunctors} {memg:memG Σ} {regg:regG Σ}\n          {cfg : cfgSG Σ}\n          `{MP: MachineParameters}.\n\n  (* TODO: move this to the rules_binary_Lea.v file. small issue with the spec of failure: it does not actually\n     require/leave a trace on dst! It would be good if req_regs of a failing get does not include dst (if possible) *)\n  Lemma step_Lea_fail_U E K pc_p pc_g pc_b pc_e pc_a w r1 rv p g b e a z a' :\n    decodeInstrW w = Lea r1 (inr rv) →\n    isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) →\n    (a + z)%a = Some a' ->\n     (match p with\n      | URW | URWL | URWX | URWLX => (a < a')%a\n      | _ => False\n      end) ->\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              ∗ ▷ rv ↣ᵣ inl z\n     ={E}=∗\n         ⤇ fill K (Instr Failed).\n  Proof.\n    iIntros (Hdecode Hvpc Hz Hp Hnclose) \"(#Hspec & Hj & >HPC & >Hpc_a & >Hsrc & >Hdst)\".\n    iDestruct (rules_binary_base.map_of_regs_3 with \"HPC Hsrc Hdst\") as \"[Hmap (%&%&%)]\".\n    iMod (step_lea with \"[$Hmap Hpc_a $Hspec $Hj]\") as (regs' retv) \"(Hj & #Hspec' & Hpc_a & Hmap)\"; eauto; simplify_map_eq; eauto.\n      by rewrite !dom_insert; set_solver+.\n    iDestruct \"Hspec'\" as %Hspec.\n    destruct Hspec as [* Hsucc |].\n    { (* Success (contradiction) *) simplify_map_eq. destruct p0; try done; revert Hp H5;clear;solve_addr. }\n    { (* Failure, done *) iFrame. done. }\n  Qed.\n\n  Definition prepstackU_s r minsize paramsize a : iProp Σ :=\n    ([∗ list] a_i;w_i ∈ a;(prepstackU_instrs r minsize paramsize), a_i ↣ₐ w_i)%I.\n\n  Lemma prepstackU_s_spec E r minsize paramsize a w pc_p pc_g pc_b pc_e a_first a_last :\n    isCorrectPC_range pc_p pc_g pc_b pc_e a_first a_last ->\n    contiguous_between a a_first a_last ->\n    nclose specN ⊆ E →\n\n    spec_ctx ∗ ⤇ Seq (Instr Executable)\n    ∗ ▷ prepstackU_s r minsize paramsize a\n    ∗ ▷ PC ↣ᵣ inr (pc_p,pc_g,pc_b,pc_e,a_first)\n    ∗ ▷ r ↣ᵣ w\n    ∗ ▷ (∃ w, r_t1 ↣ᵣ w)\n    ∗ ▷ (∃ w, r_t2 ↣ᵣ w)\n    ={E}=∗ (if isPermWord w URWLX then\n           ∃ l b e a', ⌜w = inr (URWLX,l,b,e,a')⌝ ∗\n           if (minsize + paramsize <? e - b)%Z then\n             if ((b + paramsize) <=? a')%Z then\n               (∃ a_param, ⌜(b + paramsize)%a = Some a_param⌝ ∧\n                   ⤇ Seq (Instr Executable) ∗\n                   PC ↣ᵣ inr (pc_p,pc_g,pc_b,pc_e,a_last) ∗ prepstackU_s r minsize paramsize a ∗\n                   r ↣ᵣ inr (URWLX,l,b,e,a_param) ∗ r_t1 ↣ᵣ inl 0%Z ∗ r_t2 ↣ᵣ inl 0%Z)\n             else ⤇ Seq (Instr Failed)\n           else ⤇ Seq (Instr Failed)\n         else ⤇ Seq (Instr Failed)).\n  Proof.\n    iIntros (Hvpc Hcont Hnclose) \"(#Hspec & Hj & >Hprog & >HPC & >Hr & >Hr_t1 & >Hr_t2)\".\n    iDestruct (big_sepL2_length with \"Hprog\") as %Hlength. simpl in *.\n    (* reqperm *)\n    iPrologue_multi \"Hprog\" Hcont Hvpc link.\n    iMod (reqperm_spec with \"[- $HPC $Hcode $Hr $Hr_t1 $Hr_t2 Hprog $Hspec $Hj]\") as \"Hcond\"; [apply Hvpc_code|apply Hcont_code|auto..].\n    destruct (isPermWord w URWLX); auto.\n    iDestruct \"Hcond\" as (l b e a' Heq) \"Hφ\".\n    subst. iExists l,b,e,a'. iSplitR; auto.\n    iDestruct \"Hφ\" as  \"(Hj & HPC & Hprog_done & Hr & Hr_t1 & Hr_t2)\".\n    (* reqsize *)\n    iPrologue_multi \"Hprog\" Hcont Hvpc link0.\n    iMod (reqsize_spec with \"[$HPC $Hcode $Hr $Hr_t1 $Hr_t2 $Hspec $Hj]\") as \"Hφ\";\n      [apply Hvpc_code0|eauto|auto..].\n    destruct (minsize + paramsize <? e - b)%Z eqn:Hsize; auto.\n    iDestruct \"Hφ\" as (w1 w2) \"(Hj & Hreqsize & HPC & Hr & Hr_t1 & Hr_t2)\".\n    (* getb r_t1 r *)\n    iDestruct (big_sepL2_length with \"Hprog\") as %Hlength'.\n    prep_addr_list_full l_rest0 Hcont.\n    iPrologue_s \"Hprog\".\n    iMod (step_Get_success _ [SeqCtx] with \"[$Hspec $Hj $HPC $Hi $Hr $Hr_t1]\")\n      as \"(Hj & HPC & Hi & Hr & Hr_t1) /=\";\n      [apply decode_encode_instrW_inv|auto|iCorrectPC link0 a_last|iContiguous_next Hcont 0|auto..].\n    iEpilogue_s; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* geta r_t2 r *)\n    iPrologue_s \"Hprog\".\n    iMod (step_Get_success _ [SeqCtx] with \"[$Hspec $Hj $HPC $Hi $Hr $Hr_t2]\")\n      as \"(Hj & HPC & Hi & Hr & Hr_t2) /=\";\n      [apply decode_encode_instrW_inv|auto|iCorrectPC link0 a_last|iContiguous_next Hcont 1|auto..].\n    iEpilogue_s; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* add r_t2 r_t2 paramsize *)\n    iPrologue_s \"Hprog\".\n    iMod (step_add_sub_lt_success_dst_z _ [SeqCtx] with \"[$Hspec $Hj $HPC $Hi $Hr_t2]\")\n      as \"(Hj & HPC & Hi & Hr_t2) /=\";\n      [apply decode_encode_instrW_inv|auto|iContiguous_next Hcont 2|iCorrectPC link0 a_last|auto..].\n    iEpilogue_s; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* sub r_t1 r_t1 r_t2 *)\n    iPrologue_s \"Hprog\".\n    iMod (step_add_sub_lt_success_dst_r _ [SeqCtx] with \"[$Hspec $Hj $HPC $Hi $Hr_t2 $Hr_t1]\")\n      as \"(Hj & HPC & Hi & Hr_t2 & Hr_t1) /=\";\n      [apply decode_encode_instrW_inv|auto|iContiguous_next Hcont 3|iCorrectPC link0 a_last|auto..].\n    iEpilogue_s; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* we need to distinguish between the case where the capability is stuck, or usable *)\n    assert (∃ a_param, (b + paramsize)%a = Some a_param) as [a_param Ha_param].\n    { destruct (b + paramsize)%a eqn:Hnone;eauto. exfalso. clear -Hnone Hsize. apply Z.ltb_lt in Hsize. solve_addr. }\n    assert ((a' + (b - (a' - paramsize)))%a = Some a_param) as Hlea;[clear -Ha_param; solve_addr|].\n    destruct (decide (a_param <= a')%a).\n    2: { (* lea fail *)\n      iPrologue_s \"Hprog\".\n      iMod (step_Lea_fail_U _ [SeqCtx] with \"[$Hspec $Hj $HPC $Hi $Hr_t1 $Hr]\")\n        as \"Hj\";\n        [apply decode_encode_instrW_inv|iCorrectPC link0 a_last|apply Hlea|auto..].\n      { simpl. solve_addr. }\n      assert (b + paramsize <=? a' = false)%Z as ->;[apply Z.leb_gt;solve_addr|].\n      iFrame. done. }\n    (* lea r r_t1 *)\n    iPrologue_s \"Hprog\".\n    iMod (step_lea_success_reg _ [SeqCtx] with \"[$Hspec $Hj $HPC $Hi $Hr_t1 $Hr]\")\n      as \"(Hj & HPC & Hi & Hr_t1 & Hr)\";\n      [apply decode_encode_instrW_inv|iCorrectPC link0 a_last|iContiguous_next Hcont 4|apply Hlea|auto..].\n    iEpilogue_s; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* move r_t1 0 *)\n    iPrologue_s \"Hprog\".\n    iMod (step_move_success_z _ [SeqCtx] with \"[$Hspec $Hj $HPC $Hi $Hr_t1]\")\n      as \"(Hj & HPC & Hi & Hr_t1)\";\n      [apply decode_encode_instrW_inv|iCorrectPC link0 a_last|iContiguous_next Hcont 5|auto..].\n    iEpilogue_s; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* move r_t2 0 *)\n    iPrologue_s \"Hprog\".\n    apply contiguous_between_last with (ai:=a5) in Hcont as Hlast;[|auto].\n    iMod (step_move_success_z _ [SeqCtx] with \"[$Hspec $Hj $HPC $Hi $Hr_t2]\")\n      as \"(Hj & HPC & Hi & Hr_t2)\";\n      [apply decode_encode_instrW_inv|iCorrectPC link0 a_last|apply Hlast|auto|..].\n    iEpilogue_s; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    assert (b + paramsize <=? a' = true)%Z as ->;[apply Zle_is_le_bool;auto;clear -Ha_param l0;solve_addr|].\n    iExists a_param. iSplitR;auto. iFrame.\n    repeat (iDestruct \"Hprog_done\" as \"[Hi Hprog_done]\"; iFrame \"Hi\").\n    iFrame \"Hprog_done\". done.\n  Qed.\n\nEnd 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/binary_model/examples_binary/prepstack_binary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.278956813557561}}
{"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.prim.prim_constants.\nRequire Import CertiGraph.graph.SpaceUAdjMatGraph3.\nRequire Import CertiGraph.prim.noroot_prim_spec.\n\nLocal Open Scope Z.\n\n(***********************VERIFICATION***********************)\n\nDefinition addresses := @nil val.\n\n(* A little helper *)\n(* TODO: find a better home for this *)\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 f_getCell getCell_spec.\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\n  assert_PROP (force_val\n                 (sem_add_ptr_int\n                    tint\n                    Signed\n                    (force_val\n                       (sem_add_ptr_int\n                          (tarray tint size)\n                          Signed\n                          (pointer_val_val graph_ptr)\n                          (Vint (Int.repr u))))\n                    (Vint (Int.repr i))) =\n               field_address\n                 (tarray tint size)\n                 [ArraySubsc i]\n                 (@list_address\n                    size\n                    CompSpecs\n                    (pointer_val_val graph_ptr)\n                    u)). {\n    entailer!.\n    unfold list_address. simpl.\n    rewrite field_address_offset.\n    1: { rewrite offset_offset_val; simpl; f_equal.\n         rewrite Z.add_0_l. f_equal. lia. }\n    destruct H6 as [? [? [? [? ?]]]].\n    unfold field_compatible; split3; [| | split3]; simpl; auto.\n  }\n  forward. forward.\n  thaw FR.\n  rewrite (SpaceAdjMatGraph_unfold' _ _ _ addresses u); trivial.\n  entailer!.\nQed.\n\nLemma body_initialise_list: semax_body Vprog Gprog f_initialise_list initialise_list_spec.\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 _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\nLemma body_initialise_matrix: semax_body Vprog Gprog f_initialise_matrix initialise_matrix_spec.\nProof.\nstart_function. rename H3 into Hptrofs1.\nassert (HZlength_nat_inc_list: size = Zlength (nat_inc_list (Datatypes.length old_contents))).\nrewrite nat_inc_list_Zlength. rewrite <- Zlength_correct. lia.\nforward_for_simple_bound size\n    (EX i : Z,\n     PROP ()\n     LOCAL (temp _graph arr; temp _a (Vint (Int.repr a)))\n     SEP (\n      iter_sepcon.iter_sepcon (fun i => data_at Tsh (tarray tint size) (repeat (Vint (Int.repr a)) (Z.to_nat size)) ((@list_address size CompSpecs arr i)))\n        (sublist 0 i (nat_inc_list (Z.to_nat (Zlength old_contents))));\n      iter_sepcon.iter_sepcon ((@list_rep size CompSpecs Tsh arr old_contents))\n        (sublist i size (nat_inc_list (Z.to_nat (Zlength old_contents))))\n    ))%assert.\nrewrite (SpaceAdjMatGraph_unfold' _ _ _ addresses 0); trivial.\n2: lia.\nrewrite H. entailer!.\nreplace (@list_rep size CompSpecs Tsh arr old_contents 0) with (iter_sepcon.iter_sepcon (@list_rep size CompSpecs Tsh arr old_contents) [0]).\n2: { simpl. rewrite sepcon_emp. auto. }\nrewrite <- iter_sepcon.iter_sepcon_app.\nsimpl. entailer!.\nrewrite (sublist_split 0 1), (sublist_one 0 1), nat_inc_list_i. simpl; auto.\nall: try lia.\nrewrite nat_inc_list_Zlength, Z2Nat.id; lia.\nrewrite nat_inc_list_Zlength, Z2Nat.id; lia.\n(*inner loop*)\nreplace (sublist i size (nat_inc_list (Z.to_nat (Zlength old_contents))))\n  with ([i]++sublist (i+1) size (nat_inc_list (Z.to_nat (Zlength old_contents)))).\n2: { rewrite (sublist_split i (i+1)). rewrite (sublist_one i). rewrite nat_inc_list_i; auto.\nrewrite Z2Nat.id; lia. lia. rewrite nat_inc_list_Zlength, Z2Nat.id; lia. lia. lia. rewrite nat_inc_list_Zlength, Z2Nat.id; lia. }\nrewrite iter_sepcon.iter_sepcon_app. Intros.\nforward_for_simple_bound size\n    (EX j : Z,\n     PROP ()\n     LOCAL (temp _i (Vint (Int.repr i)); temp _graph arr; temp _a (Vint (Int.repr a)))\n     SEP (\n      iter_sepcon.iter_sepcon (fun i => data_at Tsh (tarray tint size) (repeat (Vint (Int.repr a)) (Z.to_nat size)) (@list_address size CompSpecs arr i))\n        (sublist 0 i (nat_inc_list (Z.to_nat (Zlength old_contents))));\n      data_at Tsh (tarray tint size) (repeat (Vint (Int.repr a)) (Z.to_nat j) ++sublist j size (map (fun x => Vint (Int.repr x)) (Znth i old_contents))) (@list_address size CompSpecs arr i);\n      iter_sepcon.iter_sepcon (@list_rep size CompSpecs Tsh arr old_contents)\n        (sublist (i+1) size (nat_inc_list (Z.to_nat (Zlength old_contents))))\n    ))%assert.\nentailer!. simpl. rewrite sepcon_emp. unfold list_rep. rewrite sublist_same. rewrite map_map. entailer!.\nauto. rewrite Zlength_map. symmetry; apply H0. apply Znth_In; lia.\n(*inner loop body*)\nrename i0 into j. unfold list_address.\nassert (Zlength (map (fun x => Vint (Int.repr x)) (Znth i old_contents)) = size).\nrewrite Zlength_map. apply H0. apply Znth_In; lia.\nassert_PROP (field_compatible (tarray tint size) [ArraySubsc j] (offset_val (i * sizeof (tarray tint size)) arr)). entailer!.\nassert_PROP(force_val (sem_add_ptr_int tint Signed (force_val (sem_add_ptr_int (tarray tint size) Signed arr (Vint (Int.repr i))))\n (Vint (Int.repr j))) = (field_address (tarray tint size) [ArraySubsc j] (offset_val (i * sizeof (tarray tint size)) arr))). {\n  entailer!. symmetry; rewrite field_address_offset. simpl. unfold offset_val.\n  destruct arr; simpl; auto.\n  rewrite Ptrofs.add_assoc.\n  rewrite Zmax0r by lia.\n  rewrite (Ptrofs.add_signed (Ptrofs.repr (i * (4 * size)))).\n  - rewrite Ptrofs.signed_repr.\n    rewrite Ptrofs.signed_repr.\n    rewrite Z.add_0_l.\n    rewrite Z.mul_comm.\n    auto.\n    rewrite Z.add_0_l.\n    + split; [rep_lia |].\n      apply (Z.le_trans _ (1*(4*size))). lia.\n      apply (Z.le_trans _ (size*(4*size))). apply Z.mul_le_mono_nonneg_r; lia. lia.\n    + split; [rep_lia |].\n      apply (Z.le_trans _ (size*(4*size))). apply Z.mul_le_mono_nonneg_r; lia. lia.\n  - auto.\n}\n(*g[i][j] = a*)\nforward.\nunfold list_address.\nreplace (upd_Znth j (repeat (Vint (Int.repr a)) (Z.to_nat j) ++ sublist j size (map (fun x => Vint (Int.repr x)) (Znth i old_contents))) (Vint (Int.repr a)))\nwith (repeat (Vint (Int.repr a)) (Z.to_nat (j + 1)) ++ sublist (j + 1) size (map (fun x => Vint (Int.repr x)) (Znth i old_contents))).\nentailer!.\nrewrite <- repeat_app' by lia. rewrite <- app_assoc. rewrite upd_Znth_app2.\nrewrite Zlength_repeat by lia. rewrite Z.sub_diag by lia.\nrewrite (sublist_split j (j+1)) by lia. rewrite (sublist_one j (j+1)) by lia. simpl. rewrite upd_Znth0 by lia. auto.\nrewrite Zlength_repeat by lia. rewrite Zlength_sublist; lia.\n(*inner loop postcon*)\nentailer!.\nrewrite (sublist_split 0 i (i+1)) by lia. rewrite (sublist_one i (i+1)) by lia. rewrite nat_inc_list_i.\nrewrite iter_sepcon.iter_sepcon_app. rewrite sublist_nil. rewrite app_nil_r. entailer!. simpl. rewrite sepcon_emp; auto.\nrewrite <- Zlength_correct. lia.\n(*postcon*)\nentailer!. rewrite (SpaceAdjMatGraph_unfold' _ _ _ addresses 0). repeat rewrite sublist_nil. repeat rewrite iter_sepcon.iter_sepcon_nil.\nrewrite sepcon_emp. rewrite sepcon_comm. rewrite sepcon_emp.\nrewrite Z.add_0_l. rewrite (sublist_split 0 1 (size)). rewrite sublist_one. rewrite nat_inc_list_i.\nrewrite iter_sepcon.iter_sepcon_app. rewrite Zlength_repeat. replace (Datatypes.length old_contents) with (Z.to_nat size).\nrewrite <- (map_repeat (fun x => Vint (Int.repr x))).\nunfold list_rep. rewrite Znth_repeat_inrange.\n(*we can just simpl; entailer! here, but that relies on our size being fixed at a small number, so providing the scalable proof*)\nrewrite <- (map_map Int.repr Vint).\nrewrite (iter_sepcon.iter_sepcon_func_strong _\n   (fun index : Z =>\n         data_at Tsh (tarray tint size)\n           (map Vint\n              (map Int.repr\n                 (Znth index\n                    (repeat (repeat a (Z.to_nat size)) (Z.to_nat size)))))\n           (list_address arr index))\n   (fun i : Z =>\n      data_at Tsh (tarray tint size) (map (fun x : Z => Vint (Int.repr x)) (repeat a (Z.to_nat size)))\n              (@list_address size CompSpecs arr i))). entailer!. simpl; entailer.\nintros. replace (Znth x (repeat (repeat a (Z.to_nat size)) (Z.to_nat size))) with\n(repeat a (Z.to_nat size)); auto.\nsymmetry; apply Znth_repeat_inrange. apply sublist_In, nat_inc_list_in_iff in H3.\nrewrite Z2Nat.id in H3; auto.\nall: try lia.\nall: try rewrite <- ZtoNat_Zlength; try lia.\nrewrite Zlength_repeat; lia.\nQed.\n\n(******************PRIM'S***************)\n\nLemma body_prim: semax_body Vprog Gprog f_prim prim_spec.\nProof.\nstart_function. rename H into Hprecon_1. rename H0 into Ha.\n\nassert (inf_repable: repable_signed inf). {\n  red. pose proof (inf_representable g). rep_lia.\n}\nassert (Hsz: 0 < size <= Int.max_signed). {\n  apply (size_representable g).\n}\nassert (Hsz2: size <= Int.max_signed). {\n  lia.\n}\nassert (size_repable: repable_signed size). {\n  unfold repable_signed. rep_lia.\n}\n\n(*replace all data_at_ with data_at Vundef*)\nrepeat rewrite data_at__tarray.\nset (k:=default_val tint); compute in k; subst k.\nforward_call (v_key, (repeat Vundef (Z.to_nat size)), inf).\nassert_PROP (Zlength (map (fun x : Z => Vint (Int.repr x)) garbage) = size). entailer!.\nforward_call (pointer_val_val parent_ptr, (map (fun x : Z => Vint (Int.repr x)) garbage), size).\nclear H garbage.\nforward_call (v_out, (repeat Vundef (Z.to_nat size)), 0).\nassert (Hstarting_keys: forall i, 0 <= i < size -> is_int I32 Signed (Znth i (repeat (Vint (Int.repr inf)) (Z.to_nat size)))). {\n  intros. unfold is_int. rewrite Znth_repeat_inrange by lia. auto.\n}\nreplace (repeat (Vint (Int.repr inf)) (Z.to_nat size)) with\n  (map (fun x => Vint (Int.repr x)) (repeat inf (Z.to_nat size))) in *.\nset (starting_keys:=map (fun x => Vint (Int.repr x)) (repeat inf (Z.to_nat size))) in *.\nassert (HZlength_starting_keys: Zlength starting_keys = size). {\n  unfold starting_keys. rewrite Zlength_map. rewrite Zlength_repeat; lia.\n}\nunfold repable_signed in inf_repable.\n(*push all vertices into priq*)\nforward_call(tt).\nrewrite <- size_eq in *.\nIntro priq_ptr.\nremember (pointer_val_val priq_ptr) as v_pq.\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; lvar _out (tarray tint size) v_out;\n      lvar _key (tarray tint size) v_key; temp _graph (pointer_val_val gptr);\n      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));\n      free_tok v_pq (sizeof tint * size)\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 (repeat inf (Z.to_nat size))))). {\n  unfold starting_keys. rewrite Znth_map; auto.\n}\nforward_call (v_pq, i, Znth i (repeat inf (Z.to_nat size)), sublist 0 i starting_keys ++ sublist i size (repeat Vundef (Z.to_nat size))).\nsplit. auto. unfold weight_inrange_priq.\nrewrite Znth_repeat_inrange. lia. lia.\nrewrite Znth_repeat_inrange; lia.\n\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,\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 = 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    )\n    LOCAL (\n      temp _pq v_pq; lvar _out (tarray tint size) v_out;\n      temp _parent (pointer_val_val parent_ptr); lvar _key (tarray tint size) v_key;\n      temp _graph (pointer_val_val gptr)\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));\n      free_tok v_pq (sizeof tint * size)\n    )\n  )\nbreak: (\n  EX mst: G,\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      (*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; lvar _out (tarray tint size) v_out;\n      temp _parent (pointer_val_val parent_ptr); lvar _key (tarray tint size) v_key;\n      temp _graph (pointer_val_val gptr)\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));\n      free_tok v_pq (sizeof tint * size)\n    )\n  )\n%assert.\n(****PRECON****) {\n  assert (inf_rep: 0 <= inf <= Int.max_signed). {\n    pose proof (inf_representable g). rep_lia.\n  }\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 (repeat inf (Z.to_nat size)).\n  Exists (repeat inf (Z.to_nat size)).\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 (repeat inf (Z.to_nat size)) =\n    elabel g (eformat (v, Znth v (repeat size (Z.to_nat size))))). {\n    intros.\n    repeat rewrite Znth_repeat_inrange by lia. symmetry; apply (invalid_edge_weight g).\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  }\n  assert (Hinv_6: forall v : Z,\n    0 <= v < size ->\n    Znth v (repeat inf (Z.to_nat size)) =\n    (if in_dec V_EqDec v (nil (A:=V))\n     then (inf + 1)%Z\n     else Znth v (repeat inf (Z.to_nat size)))). {\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  (*Hinv_12 (nil <> nil) seems to be missing, autoresolved?*)\n  assert (Hinv_11: 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.\n    pose proof (@edgeless_graph_evalid size inf (inf_representable g) Hsz e); contradiction.\n  }\n  assert (Hinv_12: 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_13: 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  }\n\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:\" entailer!.\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_11; rename H10 into Hinv_12;\n  rename H11 into Hinv_13.\n  (*15 invariants... I think, that if we go with this \"exists M\" approach, we can eliminate some of the weight lemmas*)\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\n  ). entailer!.\n  repeat rewrite Zlength_map in H. 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 [? ?]]. rewrite HZlength_pq_state in H. subst x.\n    rewrite Hinv_6. 2: lia. destruct (in_dec V_EqDec i popped_vertices). lia.\n    rewrite Hinv_5. 2: 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  (*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    rewrite HZlength_pq_state; lia. 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  }\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 (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. lia.\n    apply fold_min_in_list. 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, as 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        (*for convenience, unpopped and not u -> Znth v keys = Znth v pq_state'?*)\n      )\n      LOCAL (\n        temp _u (Vint (Int.repr u)); temp _t'2 (@isEmpty inf pq_state); temp _pq v_pq; lvar _out (tarray tint size) v_out;\n        temp _parent (pointer_val_val parent_ptr); lvar _key (tarray tint size) v_key; temp _graph (pointer_val_val gptr)\n      )\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));\n      free_tok v_pq (sizeof tint * size)\n      )\n    )\n  %assert.\n  (*precon*) {\n    Exists parents. Exists keys. Exists upd_pq_state. entailer!.\n    (*in this case, proving the PROPs beforehand did not improve the timing*)\n    intros. rewrite Hinv_5 by lia. split.\n    apply weight_representable. 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  } 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] < ...*)\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      set (k:=Int.max_signed); compute in k; subst k. rewrite inf_eq in H8; lia. }\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    forward_call (v_pq, i, Znth i (Znth u (@graph_to_symm_mat size g)), pq_state').\n    replace (map (fun x : Z => Vint (Int.repr x)) pq_state') with (map Vint (map Int.repr pq_state')).\n    entailer!. rewrite list_map_compose. auto.\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 (@SpaceAdjMatGraph_unfold' _ _ _ _ _ addresses u). unfold list_rep.\n    rewrite list_map_compose. repeat rewrite (upd_Znth_map (fun x => Vint (Int.repr x))).\n    2: lia.\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    }\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    } (*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    unfold graph_to_symm_mat. rewrite graph_to_mat_Zlength; lia.\n    -forward. (*nothing changed*)\n    Exists parents'. Exists keys'. Exists pq_state'.\n    rewrite (@SpaceAdjMatGraph_unfold' _ _ _ _ _ addresses u). unfold list_rep.\n    2: lia.\n    2: unfold graph_to_symm_mat; rewrite graph_to_mat_Zlength; lia.\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. 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. lia.\n      apply Hinv2_3. lia.\n      rewrite Z.min_r; lia.\n      replace (Znth i pq_state') with (Znth i upd_pq_state). rewrite H11. rewrite Z.min_r; lia. 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  +(*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). unfold list_rep.\n  2: lia.\n  2: unfold graph_to_symm_mat; rewrite graph_to_mat_Zlength; 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' = 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    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. 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 (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.\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.\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. 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.\n    replace (elabel g (eformat (v, Znth v parents))) with inf in bool. lia.\n    symmetry; 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    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_12; 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. 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.\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. 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_11 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_13 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).\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 [Hb 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 Hb.\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 Hb. 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 Hinv_11 Hinv_12.\n      clear Hinv2_1 Hinv2_2 Hinv2_3 Hparents_bound Hkeys' Hpq_state' Hheavy Hheavy2 Hweight.\n      clear Hpopped_or_unpopped Hpopped_vvalid Hunpopped_vvalid Hu_not_popped Hu_unpopped 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 by auto.\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_11 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_11 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_11. 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  clear H9 H10 H11 H12 H13 H14 H15 H16 H17 H18 H19 H20 H21 H22 Pv_out HPv_out Pv_out0 Pv_key HPv_key Pv_key0.\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      (*hm in this case, because Znth u parents = inf, NOTHING in popped_vertices should be connected in g or mst?*)\n      split; intros.\n      (*get a contradiction about ~connected g u0 u:\n        thoughts: destruct p:=the path to u0 u.\n        assert exists a v1 v2, both in p /\\ In v1 popped /\\ In v2 unpopped /\\ adj g v1 v2\n      *)\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.\n          apply (evalid_meaning g). apply Hinv_7; lia.\n        (*now so Znth u keys = inf*)\n        destruct popped_vertices. contradiction.\n        assert( Znth u keys = elabel g (eformat (u,Znth u parents))). rewrite Hinv_5 by lia. 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_11 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.\n          apply (evalid_meaning g). apply Hinv_7; lia.\n        (*now so Znth u keys = inf*)\n        destruct popped_vertices. contradiction.\n        assert( Znth u keys = elabel g (eformat (u,Znth u parents))). rewrite Hinv_5 by lia. 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_11 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_11. 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. rewrite HZlength_pq_state. auto. 2: auto.\n      rewrite H2 in H3. pose proof (weight_inf_bound g (eformat (x, Znth x parents))).\n      (*how now brown cow, I can't lia*)\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. rewrite Zlength_repeat; lia.\n      intros. rewrite Zlength_repeat in H2 by lia.\n      rewrite Znth_repeat_inrange by lia. rewrite Znth_map. 2: rewrite Zlength_map; lia.\n      rewrite Znth_map by lia. rewrite Hinv_6 by 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    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    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.\n(*Do the minimum proof here*)\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_10 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}\nfreeze FR := (data_at _ _ _ v_out)\n               (data_at _ _ _ (pointer_val_val parent_ptr))\n               (data_at _ _ _ v_key)\n               (SpaceAdjMatGraph' _ _ _).\n        forward_call (Tsh, priq_ptr, size, (repeat (inf + 1) (Z.to_nat size))).\nentailer!.\nthaw FR.\nforward.\nExists mst fmst parents.\n(*change from popped_vertices to nat_inc_list*)\nTransparent size.\nentailer!.\nGlobal Opaque size.\n}\n(*huh, where did I forget this*) rewrite map_repeat; auto.\nQed.\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_noroot_prim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.278956813557561}}
{"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  Fixpoint complete_hvc_exit_loop0 (n: nat) (i: Z) rec_base rec_ofst adt :=\n    match n with\n    | O => Some (i, adt)\n    | S n' =>\n        match complete_hvc_exit_loop0 n' i rec_base rec_ofst adt with\n        | Some (i, adt) =>\n          rely is_int i;\n          when' gpr == get_rec_run_gprs_spec i adt;\n          rely is_int64 gpr;\n          when adt == set_rec_regs_spec (rec_base, rec_ofst) i (VZ64 gpr) adt;\n          Some (i + 1, adt)\n        | _ => None\n        end\n    end.\n\n  Definition complete_hvc_exit_spec0 (rec: Pointer) (adt: RData) : option RData :=\n    match rec with\n    | (rec_base, rec_ofst) =>\n      when' esr == get_rec_last_run_info_esr_spec (rec_base, rec_ofst) adt;\n      rely is_int64 esr;\n      if (Z.land esr ESR_EL2_EC_MASK) =? ESR_EL2_EC_HVC then\n        match complete_hvc_exit_loop0 (Z.to_nat REC_RUN_HVC_NR_GPRS) 0 rec_base rec_ofst adt with\n        | Some (i, adt) =>\n          rely is_int i;\n          when adt == reset_last_run_info_spec (rec_base, rec_ofst) adt;\n          Some adt\n        | _ => None\n        end\n      else Some adt\n    end.\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_hvc_exit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.27895681355756097}}
{"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_Ф_addOrdinaryStake (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\nDefinition DePoolContract_Ф_addOrdinaryStake'_tailer (Л_stake Л_fee: XInteger64) : LedgerT True :=    \ndeclareLocal Л_participant :>: ξ DePoolLib_ι_Participant := ParticipantBase_Ф_getOrCreateParticipant (! msg_sender () !) ; \ndeclareLocal Л_round :>: RoundsBase_ι_Round := RoundsBase_Ф_getRound0 () ; \ndeclareLocal Л_empty :>: (XMaybe RoundsBase_ι_InvestParams) ; \nU0! {( Л_round , Л_participant )} := RoundsBase_Ф__addStakes (! $ Л_round , \n                $ Л_participant , \n                msg_sender () , \n                $ Л_stake , \n                $ Л_empty , \n                $ Л_empty !) ; \nRoundsBase_Ф_setRound0 (! $ Л_round !) >> \n(ParticipantBase_Ф__setOrDeleteParticipant (! msg_sender () , $ Л_participant !)) >> \n(DePoolContract_Ф_sendAcceptAndReturnChange128 (! $ Л_fee !)) . \n\nDefinition DePoolContract_Ф_addOrdinaryStake'_header ( Л_stake : XInteger64 )  :  LedgerT ( XErrorValue (XValueValue True) XInteger ) := \n Require {{ msg_sender () ?!= $ xInt0 , ξ$ Errors_ι_IS_EXT_MSG }} ; \n If!! ( ↑12 D2! DePoolContract_ι_m_poolClosed ) then { \n  return!!! ( DePoolContract_Ф__sendError (! $ DePool_ι_STATUS_DEPOOL_CLOSED , $ xInt0 !) ) } ; \n declareLocal Л_msgValue :>: XInteger64 := msg_value () ; \n If!! ( $ Л_msgValue ?< $ Л_stake !+ $ DePool_ι_STAKE_FEE ) then { \n  return!!! ( DePoolContract_Ф__sendError (! $ DePool_ι_STATUS_FEE_TOO_SMALL , \n                        $ DePool_ι_STAKE_FEE !) ) } ; \n declareLocal Л_fee :>: XInteger64 := $ Л_msgValue !- $ Л_stake ; \n If! ( $ Л_stake ?< ↑12 D2! DePoolContract_ι_m_minStake ) then { \n  return!!! ( DePoolContract_Ф__sendError (! $ DePool_ι_STATUS_STAKE_TOO_SMALL , \n                        ( ↑ε12 DePoolContract_ι_m_minStake ) !) ) } ;\n        DePoolContract_Ф_addOrdinaryStake'_tailer Л_stake Л_fee.\n\nLemma  DePoolContract_Ф_addOrdinaryStake'_header_eq: DePoolContract_Ф_addOrdinaryStake'_header = DePoolContract_Ф_addOrdinaryStake'.\nProof.\n  auto.\nQed.\n\n\nOpaque DePoolContract_Ф_sendAcceptAndReturnChange128 RoundsBase_Ф__addStakes. \n\n\nLemma DePoolContract_Ф_addOrdinaryStake'_tailer_exec: forall (Л_stake Л_fee: Z) (l: Ledger), \nlet sender := eval_state msg_sender l in \nlet (participant, l_getcreate) := run (↓ ParticipantBase_Ф_getOrCreateParticipant sender) l in\n\nlet round := eval_state (↓ RoundsBase_Ф_getRound0 ) l_getcreate in\nlet (rp' , l_addStakes) := run (↓ RoundsBase_Ф__addStakes round participant sender Л_stake None None) l_getcreate in\nlet (round', participant') := rp' in\nlet l_setRound := exec_state (↓ RoundsBase_Ф_setRound0 round') l_addStakes in\nlet sender' := eval_state msg_sender l_setRound in  \nlet l_setParticipant := exec_state (↓ ParticipantBase_Ф__setOrDeleteParticipant sender' participant') l_setRound in\nlet l_sendAccept := exec_state (↓ DePoolContract_Ф_sendAcceptAndReturnChange128 Л_fee) l_setParticipant in\n\nexec_state (DePoolContract_Ф_addOrdinaryStake'_tailer Л_stake Л_fee) l = l_sendAccept.\n\nProof.\n  intros.\n  destructLedger l. \n  compute.\n\n  Time repeat destructIf_solve. idtac.\n\n  all: destructFunction6 RoundsBase_Ф__addStakes; auto. idtac.\n  all: try destruct x; auto. idtac.\n\n  all: time repeat destructIf_solve. \n\nQed.\n\n\nOpaque  DePoolContract_Ф_addOrdinaryStake'_tailer.\n\nLemma DePoolContract_Ф_addOrdinaryStake'_header_exec: forall (Л_stake: Z) (l: Ledger) , \n    let sender := eval_state msg_sender l in \n    let isExtMsg : bool := negb (sender =? 0) in \n    let isPoolClosed : bool := eval_state (↑12 ε DePoolContract_ι_m_poolClosed) l in \n    let minStake := eval_state (↑12 ε DePoolContract_ι_m_minStake) l in \n    let STAKE_FEE :=  DePool_ι_STAKE_FEE in\n    let msg_value := eval_state msg_value l in \n    let feeSmall := msg_value <? Л_stake + STAKE_FEE in\n    let fee := msg_value - Л_stake in\n    let stakeSmall := Л_stake <? minStake in\n\n    exec_state (DePoolContract_Ф_addOrdinaryStake'_header Л_stake ) l = \n    if isExtMsg then \n     if isPoolClosed then exec_state (DePoolContract_Ф__sendError DePool_ι_STATUS_DEPOOL_CLOSED 0 ) l\n     else if feeSmall then exec_state (DePoolContract_Ф__sendError DePool_ι_STATUS_FEE_TOO_SMALL \n                                                                    DePool_ι_STAKE_FEE ) l\n     else if stakeSmall then exec_state (DePoolContract_Ф__sendError DePool_ι_STATUS_STAKE_TOO_SMALL \n                                                                     (eval_state (↑ε12  DePoolContract_ι_m_minStake) l) ) l\n     else exec_state (DePoolContract_Ф_addOrdinaryStake'_tailer Л_stake fee) l\n    else l.\nProof.\n  intros.\n  destructLedger l. \n  compute.\n\n  Time repeat destructIf_solve. idtac.\n  destructFunction2  DePoolContract_Ф_addOrdinaryStake'_tailer; auto. \n\n\nQed.\n\n\n\nLemma DePoolContract_Ф_addOrdinaryStake'_eval: forall (Л_stake: Z) (l: Ledger), \nlet sender := eval_state msg_sender l in \nlet isExtMsg : bool := negb (sender =? 0) in \nlet isPoolClosed : bool := eval_state (↑12 ε DePoolContract_ι_m_poolClosed) l in \nlet minStake := eval_state (↑12 ε DePoolContract_ι_m_minStake) l in \nlet STAKE_FEE := DePool_ι_STAKE_FEE in\nlet msg_value := eval_state msg_value l in \nlet feeSmall := msg_value <? Л_stake + STAKE_FEE in\nlet stakeSmall := Л_stake <? minStake in\n\neval_state (↓ DePoolContract_Ф_addOrdinaryStake' Л_stake) l = \nif isExtMsg then \n if isPoolClosed then Value (Error I) \n else if feeSmall then Value (Error I)\n else if stakeSmall then Value (Error I)\n else Value (Value I)\nelse Error Errors_ι_IS_EXT_MSG .\nProof.\n\n  intros.\n  destructLedger l. \n  compute.\n\n  Time repeat destructIf_solve. idtac.\n\n  all: destructFunction6 RoundsBase_Ф__addStakes; auto. idtac.\n  all: try destruct x; auto. idtac.\n\n  all: time repeat destructIf_solve. \n    \nQed. \n\n\nLemma DePoolContract_Ф_addOrdinaryStake_eval: forall (Л_stake: Z) (l: Ledger), \nlet sender := eval_state msg_sender l in \nlet isExtMsg : bool := negb (sender =? 0) in \nlet isPoolClosed : bool := eval_state (↑12 ε DePoolContract_ι_m_poolClosed) l in \nlet minStake := eval_state (↑12 ε DePoolContract_ι_m_minStake) l in \nlet STAKE_FEE := DePool_ι_STAKE_FEE in\nlet msg_value := eval_state msg_value l in \nlet feeSmall := msg_value <? Л_stake + STAKE_FEE in\nlet stakeSmall := Л_stake <? minStake in\n\neval_state (↓ DePoolContract_Ф_addOrdinaryStake Л_stake) l = \nif isExtMsg then \n if isPoolClosed then Value I \n else if feeSmall then Value I\n else if stakeSmall then Value I\n else Value I\nelse Error Errors_ι_IS_EXT_MSG .\nProof.\n\n  intros.\n\n  assert (eval_state (↓ DePoolContract_Ф_addOrdinaryStake Л_stake ) l = \n  xErrorMapDefaultF (xValue ∘ fromValueValue) (eval_state (↓ DePoolContract_Ф_addOrdinaryStake' Л_stake) l) xError).\n  unfold DePoolContract_Ф_addOrdinaryStake.\n  unfold callEmbeddedStateAdj.\n  remember (DePoolContract_Ф_addOrdinaryStake' Л_stake).\n  setoid_rewrite runbind.\n  setoid_rewrite eval_bind2.\n  rewrite eval_get.\n  rewrite exec_get.\n  remember (run l0 (injEmbed (T:=LocalState) DePoolFuncs.DePoolSpec.LedgerClass.local0 l)).\n  setoid_rewrite <- Heqp.\n  destruct p.\n  destruct x.\n  auto. auto.\n\n  (**********************)\n  rewrite H.\n  rewrite DePoolContract_Ф_addOrdinaryStake'_eval.\n  compute.\n  repeat destructIf; auto.\n\nQed.  \n\n\nOpaque DePoolContract_Ф_addOrdinaryStake'.\n\nLemma DePoolContract_Ф_addOrdinaryStake_exec: forall (Л_stake: Z) (l: Ledger) , \n    let sender := eval_state msg_sender l in \n    let isExtMsg : bool := negb (sender =? 0) in \n    let isPoolClosed : bool := eval_state (↑12 ε DePoolContract_ι_m_poolClosed) l in \n    let minStake := eval_state (↑12 ε DePoolContract_ι_m_minStake) l in \n    let STAKE_FEE :=  DePool_ι_STAKE_FEE in\n    let msg_value := eval_state msg_value l in \n    let feeSmall := msg_value <? Л_stake + STAKE_FEE in\n    let fee := msg_value - Л_stake in\n    let stakeSmall := Л_stake <? minStake in\n\n    exec_state (DePoolContract_Ф_addOrdinaryStake Л_stake ) l = \n    if isExtMsg then \n     if isPoolClosed then exec_state (DePoolContract_Ф__sendError DePool_ι_STATUS_DEPOOL_CLOSED 0 ) l\n     else if feeSmall then exec_state (DePoolContract_Ф__sendError DePool_ι_STATUS_FEE_TOO_SMALL \n                                                                    DePool_ι_STAKE_FEE ) l\n     else if stakeSmall then exec_state (DePoolContract_Ф__sendError DePool_ι_STATUS_STAKE_TOO_SMALL \n                                                                     (eval_state (↑ε12  DePoolContract_ι_m_minStake) l) ) l\n     else exec_state (DePoolContract_Ф_addOrdinaryStake'_tailer Л_stake fee) l\n    else l.\nProof.\n  \n  intros.\n\n  assert (exec_state (DePoolContract_Ф_addOrdinaryStake Л_stake ) l = \n          exec_state (DePoolContract_Ф_addOrdinaryStake' Л_stake) l).\n  unfold DePoolContract_Ф_addOrdinaryStake.\n  remember (DePoolContract_Ф_addOrdinaryStake' Л_stake).\n  rewrite exec_bind.\n  rewrite exec_unit.\n  auto.\n  (**********************)\n  rewrite H.\n  rewrite <- DePoolContract_Ф_addOrdinaryStake'_header_eq.\n  rewrite DePoolContract_Ф_addOrdinaryStake'_header_exec.\n  auto.\nQed.\n\nEnd DePoolContract_Ф_addOrdinaryStake.\n\n  \n", "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_addOrdinaryStake.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.27895680734108214}}
{"text": "From Coq Require Import String Arith NArith ZArith Eqdep_dec.\nFrom Vyper Require Import Config NaryFun Calldag.\nFrom Vyper.L10 Require Import AST Callset.\nFrom Vyper Require FSet Map UInt256.\n\nLocal Open Scope list_scope.\nLocal Open Scope string_scope.\n\nSection Descend.\nContext {C: VyperConfig}.\n\nDefinition calldag := generic_calldag decl_callset true.\n\n\nLemma call_descend {call_depth_bound new_call_depth_bound current_fun_depth: nat}\n                   (DepthOk : current_fun_depth < call_depth_bound)\n                   (cd : calldag)\n                   (this_fun_name: string)\n                   (this_decl: decl)\n                   (this_decl_ok: cd_declmap cd this_fun_name = Some this_decl)\n                   (current_fun_depth_ok:\n                     cd_depthmap cd this_fun_name = Some current_fun_depth)\n                   (e: expr)\n                   (CallOk: let _ := string_set_impl in\n                             FSet.is_subset (expr_callset e) (decl_callset this_decl) = true)\n                   (Ebound: call_depth_bound = S new_call_depth_bound)\n                   {name: string}\n                   {args: list expr}\n                   (E: e = PrivateOrBuiltinCall name args)\n                   {depth: nat}\n                   (Edepth: cd_depthmap cd name = Some depth):\n  depth < new_call_depth_bound.\nProof.\nsubst e. cbn in CallOk.\nassert(HasName: let _ := string_set_impl in FSet.has (decl_callset this_decl) name = true).\n{\n  cbn.\n  apply (FSet.is_subset_if CallOk name).\n  apply FSet.add_has.\n}\nclear CallOk. cbn in HasName.\nassert (K := cd_depthmap_ok cd this_fun_name).\nunfold cd_declmap in this_decl_ok.\nrewrite this_decl_ok in K.\nrewrite current_fun_depth_ok in K.\ncbn in K.\nrewrite FSet.for_all_ok in K.\nassert (L := K name HasName). clear K.\nsubst call_depth_bound.\napply lt_n_Sm_le in DepthOk.\nrewrite Edepth in L.\ndestruct current_fun_depth. { discriminate. }\nrewrite Nat.leb_le in L.\nrewrite Nat.le_succ_l in DepthOk.\napply (Nat.le_lt_trans _ _ _ L DepthOk).\nQed.\n\nLocal Lemma fun_ctx_descend_helper {cd: calldag}\n                                   {name: string}\n                                   {d: decl}\n                                   (Edecl : cd_declmap cd name = Some d):\n  cd_depthmap cd name <> None.\nProof.\nassert (D := cd_depthmap_ok cd name).\nunfold cd_declmap in Edecl.\nrewrite Edecl in D.\nintro H.\nrewrite H in D.\nexact D.\nQed.\n\nLocal Lemma call_descend' {call_depth_bound new_call_depth_bound}\n                          {cd: calldag}\n                          {e: expr}\n                          {name: string}\n                          {args: list expr}\n                          (fc: fun_ctx cd call_depth_bound)\n                          (CallOk: let _ := string_set_impl in\n                                      FSet.is_subset (expr_callset e)\n                                                     (decl_callset (fun_decl fc))\n                                       = true)\n                          (Ebound: call_depth_bound = S new_call_depth_bound)\n                          (E: e = PrivateOrBuiltinCall name args)\n                          {d: decl}\n                          (Edecl: cd_declmap cd name = Some d)\n                          {depth: nat}\n                          (Edepth: cd_depthmap cd name = Some depth):\n  (depth <? new_call_depth_bound) = true.\nProof.\nexact (proj2 (Nat.ltb_lt _ _)\n         (call_descend (proj1 (Nat.ltb_lt _ _) (fun_bound_ok fc))\n                       cd (fun_name fc)\n                       (fun_decl fc) (fun_decl_ok fc)\n                       (fun_depth_ok fc) e CallOk Ebound \n                       E Edepth)).\nQed.\n\n(* The inner part of fun_ctx_descend is here separately because\n   it's too difficult to destruct [cd_depthmap cd name] otherwise. \n *)\nLocal Definition fun_ctx_descend_inner {call_depth_bound new_call_depth_bound}\n                           {cd: calldag}\n                           {e: expr}\n                           {name: string}\n                           {args: list expr}\n                           (fc: fun_ctx cd call_depth_bound)\n                           (CallOk: let _ := string_set_impl in\n                                       FSet.is_subset (expr_callset e)\n                                                      (decl_callset (fun_decl fc))\n                                        = true)\n                           (Ebound: call_depth_bound = S new_call_depth_bound)\n                           (E: e = PrivateOrBuiltinCall name args)\n                           {d: decl}\n                           (Edecl: cd_declmap cd name = Some d)\n:= match cd_depthmap cd name as maybe_depth return _ = maybe_depth -> _ with\n   | None => fun Edepth => False_rect _ (fun_ctx_descend_helper Edecl Edepth)\n   | Some depth => fun Edepth =>\n       Some {| fun_name := name\n             ; fun_depth := depth\n             ; fun_depth_ok := Edepth\n             ; fun_decl := d\n             ; fun_decl_ok := Edecl\n             ; fun_bound_ok := call_descend' fc CallOk Ebound E Edecl Edepth\n            |}\n   end eq_refl.\n\n(** Make a callee context from a caller context and a call expression, \n  The None result means that no declaration with the given name is found.\n  No check is made that the callee context is indeed a function.\n  The max stack depth bound is reduced by 1.\n *)\nDefinition fun_ctx_descend {call_depth_bound new_call_depth_bound}\n                           {cd: calldag}\n                           {e: expr}\n                           {name: string}\n                           {args: list expr}\n                           (fc: fun_ctx cd call_depth_bound)\n                           (CallOk: let _ := string_set_impl in\n                                       FSet.is_subset (expr_callset e)\n                                                      (decl_callset (fun_decl fc))\n                                        = true)\n                           (Ebound: call_depth_bound = S new_call_depth_bound)\n                           (E: e = PrivateOrBuiltinCall name args)\n: option (fun_ctx cd new_call_depth_bound)\n:= match cd_declmap cd name as maybe_decl return _ = maybe_decl -> _ with\n   | None => fun _ =>\n       (* no declaration found - could be a builtin *)\n       None\n   | Some d => fun Edecl => fun_ctx_descend_inner fc CallOk Ebound E Edecl\n   end eq_refl.\n\nLemma fun_ctx_descend_irrel {call_depth_bound new_call_depth_bound}\n                            {cd: calldag}\n                            {e: expr}\n                            {name: string}\n                            {args: list expr}\n                            (fc1 fc2: fun_ctx cd call_depth_bound)\n                            (CallOk1: let _ := string_set_impl in\n                                        FSet.is_subset (expr_callset e)\n                                                       (decl_callset (fun_decl fc1))\n                                         = true)\n                            (CallOk2: let _ := string_set_impl in\n                                        FSet.is_subset (expr_callset e)\n                                                       (decl_callset (fun_decl fc2))\n                                         = true)\n                            (Ebound: call_depth_bound = S new_call_depth_bound)\n                            (E: e = PrivateOrBuiltinCall name args):\n  fun_ctx_descend fc1 CallOk1 Ebound E = fun_ctx_descend fc2 CallOk2 Ebound E.\nProof.\nunfold fun_ctx_descend.\nassert (InnerOk: forall (d: decl) (Edecl: cd_declmap cd name = Some d),\n                   fun_ctx_descend_inner fc1 CallOk1 Ebound E Edecl\n                    =\n                   fun_ctx_descend_inner fc2 CallOk2 Ebound E Edecl).\n{\n  intros. unfold fun_ctx_descend_inner.\n  remember (fun (depth: nat) (Edepth: cd_depthmap cd name = Some depth) => Some {|\n      fun_name := name;\n      fun_depth := depth;\n      fun_depth_ok := Edepth;\n      fun_decl := d;\n      fun_decl_ok := Edecl;\n      fun_bound_ok := call_descend' fc1 CallOk1 Ebound E Edecl Edepth |}) as some_branch1.\n  remember (fun (depth: nat) (Edepth: cd_depthmap cd name = Some depth) => Some {|\n      fun_name := name;\n      fun_depth := depth;\n      fun_depth_ok := Edepth;\n      fun_decl := d;\n      fun_decl_ok := Edecl;\n      fun_bound_ok := call_descend' fc2 CallOk2 Ebound E Edecl Edepth |}) as some_branch2.\n  assert(SomeBranchOk: forall (depth: nat) (Edepth: cd_depthmap cd name = Some depth),\n                         some_branch1 depth Edepth = some_branch2 depth Edepth).\n  {\n    intros. subst. f_equal. f_equal.\n    apply eq_proofs_unicity. decide equality.\n  }\n  clear Heqsome_branch1 Heqsome_branch2.\n  remember fun_ctx_descend_helper as foo. clear Heqfoo. revert foo.\n  revert CallOk1 CallOk2.\n  destruct (cd_depthmap cd name).\n  { intros. apply SomeBranchOk. }\n  trivial.\n}\nremember fun_ctx_descend_inner as inner. clear Heqinner. revert inner CallOk1 CallOk2 InnerOk.\ndestruct (cd_declmap cd name). (* this is why fun_ctx_descend_inner exists *)\n{ intros. apply InnerOk. }\ntrivial.\nQed.\n\nLemma fun_ctx_descend_none {call_depth_bound new_call_depth_bound}\n                           {cd: calldag}\n                           {e: expr}\n                           {name: string}\n                           {args: list expr}\n                           (fc: fun_ctx cd call_depth_bound)\n                           (CallOk: let _ := string_set_impl in\n                                       FSet.is_subset (expr_callset e)\n                                                      (decl_callset (fun_decl fc))\n                                        = true)\n                           (Ebound: call_depth_bound = S new_call_depth_bound)\n                           (E: e = PrivateOrBuiltinCall name args):\n  fun_ctx_descend fc CallOk Ebound E = None\n   <->\n  cd_declmap cd name = None.\nProof.\nunfold fun_ctx_descend.\nassert (InnerOk: forall (d: decl) (Edecl: cd_declmap cd name = Some d),\n                   fun_ctx_descend_inner fc CallOk Ebound E Edecl = None\n                    <->\n                   cd_declmap cd name = None).\n{\n  intros. unfold fun_ctx_descend_inner.\n  assert (Ok := cd_depthmap_ok cd name).\n  remember (fun (depth: nat) (Edepth: cd_depthmap cd name = Some depth) =>\n    Some\n      {|\n      fun_name := name;\n      fun_depth := depth;\n      fun_depth_ok := Edepth;\n      fun_decl := d;\n      fun_decl_ok := Edecl;\n      fun_bound_ok := call_descend' fc CallOk Ebound E Edecl Edepth |}) as some_branch.\n  remember (fun Edepth : cd_depthmap cd name = None =>\n              False_rect (option (fun_ctx cd new_call_depth_bound))\n                         (fun_ctx_descend_helper Edecl Edepth))\n    as none_branch.\n  assert (SomeBranchOk: forall (depth: nat) (Edepth: cd_depthmap cd name = Some depth),\n                          some_branch depth Edepth <> None).\n  { now subst. }\n  assert (NoneBranchOk: forall (Edepth: cd_depthmap cd name = None),\n                          none_branch Edepth = None).\n  { intro. exfalso. exact (fun_ctx_descend_helper Edecl Edepth). }\n  clear Heqsome_branch Heqnone_branch.\n  unfold cd_declmap in *.\n  rewrite Edecl in *.\n  destruct (cd_depthmap cd name). 2:{ contradiction. }\n  assert (S := SomeBranchOk n eq_refl).\n  split. { contradiction. }\n  intro. discriminate.\n} (* InnerOk *)\nremember fun_ctx_descend_inner as inner. clear Heqinner. revert inner InnerOk.\ndestruct cd_declmap.\n{ intros. apply InnerOk. }\nintros. tauto.\nQed.\n\nEnd Descend.", "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/L10/Descend.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6723316860482762, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2789496405340253}}
{"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 DepMaps 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.\n\nExport CalculatorProtocol.\n\nSection CalculatorServers.\n\nVariable l : Label.\nVariable f : input -> option nat.\nVariable prec : input -> bool.\nVariables (cs cls : seq nid).\nNotation nodes := (cs ++ cls).\nHypothesis Huniq : uniq nodes.\n\nNotation cal := (CalculatorProtocol f prec cs cls l).\nNotation sts := (snd_trans cal).\nNotation rts := (rcv_trans cal).\nNotation W := (mkWorld cal).\n\n(* A server node *)\nVariable sv : nid.\nHypothesis  Hs : sv \\in cs.\nNotation loc i := (getLocal sv (getStatelet i l)).\n\nSection CalculatorServerLoop.\n\n(************************************************)\n(******    Generic server loop combinator   *****)\n(************************************************)\n\n(*\n- Actually, this is _higher-order_ programming\n- The loop runs infinitely\n- It takes an additional generic state argument (useful for memoization),\n  which should be constrained appropriately\n*)\n\nVariable Sstate : Type.\n(* Making sure that the state is okay *)\nVariable state_wf : Pred Sstate.\n\n(* Initial well-formed state, which is well-formed *)\nVariable state0 : Sstate.\nHypothesis state0_wf : state_wf state0. \n\n(** The server body always cleans up after itself (no outstanding\nrequests left to be processed) and correctly handles the state, passed\nbetween iterations. *)\n\nDefinition server_loop_body_spec (s : Sstate) :=\n  DHT [sv, W]\n  (fun i => loc i = st :-> ([::]:reqs) /\\ state_wf s,                    \n   fun (r : Sstate) m =>\n     [/\\ loc m = st :-> ([::]:reqs) & state_wf r]).\n\n(* The body to be passed to the loop *)\nVariable server_body : forall s, server_loop_body_spec s.\n\nDefinition server_loop_cond (res : Sstate) := true.\n\nDefinition server_loop_inv :=\n  fun (_ r : Sstate) i => loc i = st :-> ([::]:reqs) /\\ state_wf r.\n\nProgram Definition server_loop :\n  DHT [sv, W]\n  (fun i => loc i = st :-> ([::]:reqs),\n   fun (r : Sstate) m => False) :=\n  Do _ (@while sv W _ _ server_loop_cond server_loop_inv _\n        (fun r => Do _ (server_body r))) state0.\n\nNext Obligation. by apply: with_spec (x x0). Defined.\nNext Obligation.\nby move:H; rewrite /server_loop_inv (rely_loc' _ H0).\nQed.\nNext Obligation. by apply: with_spec x. Defined.\nNext Obligation.\nby apply: ghC=>i1 s[H1 H2] C1/=; apply: call_rule.\nQed.\nNext Obligation.\nmove=>i/=E1; apply: call_rule'=>//.\n- by move=>C1; exists state0=>//. \nby move=>s' m/(_ s')/=; case.\nQed.    \n    \nEnd CalculatorServerLoop.\nEnd CalculatorServers.\n\n\n(*************************************************)\n(*      Specific server implementations          *)\n(*************************************************)\n\n\n(***** One-shot (per iteration) server *****)\n\nModule OneShotServer.\nSection OneShotServer.\n\nVariable l : Label.\nVariable f : input -> option nat.\nVariable prec : input -> bool.\nHypothesis prec_valid :\n  forall i, prec i -> exists v, f i = Some v.\nVariables (cs cls : seq nid).\nNotation nodes := (cs ++ cls).\nHypothesis Huniq : uniq nodes.\n\nNotation cal := (CalculatorProtocol f prec cs cls l).\nNotation sts := (snd_trans cal).\nNotation rts := (rcv_trans cal).\nNotation W := (mkWorld cal).\n\n(* A server node *)\nVariable sv : nid.\nHypothesis  Hs : sv \\in cs.\nNotation loc i := (getLocal sv (getStatelet i l)).\n\n(* Server-specific infrastructure *)\nNotation Sstate := unit.\nDefinition state_wf := fun _ : unit => True.\nDefinition state0 := tt.\nLemma state0_wf : state_wf state0. Proof. done. Qed.\n\nProgram Definition one_shot_body : forall _ : unit,\n  server_loop_body_spec l f prec cs cls sv _ state_wf state0 :=\n  fun _ =>\n  Do _ (\n    r <-- blocking_receive_req l f prec cs cls _ Hs;\n    let: (from, args) := r in\n    (* Compute the answer function explicitly *)\n    let r := if f args is Some v then v else 0 in\n    send_answer l f prec cs cls _ Hs from args r;;\n    ret _ _ tt).\nNext Obligation.\nmove=>i1/=[L1]_; apply: step; apply: (gh_ex (g:=[::])).\napply: call_rule=>//[[from args]] i2/=[L2]H1 H2 C2.\ncase: (prec_valid _ H2)=>ans F.\nmove: (erefl (f args))=>e.\nhave X: (match f args as anonymous' return (anonymous' = f args -> nat) with\n           | Some v => fun _ : Some v = f args => v\n           | None => fun _ : None = f args => 0\n         end e) = ans by move: e; rewrite F.\nrewrite X=>{X}; apply: step; apply: (gh_ex (g:=[:: (from, sv, args)])).\napply: call_rule=>//; first by move=>_; split=>//; rewrite inE eqxx.\nmove=>x i3/=; rewrite eqxx=> L3 C3. \napply: ret_rule=>i4 R3 _; split=>//.\nby rewrite (rely_loc' _ R3); case: L3.\nQed.\n\nDefinition one_shot_server :=\n  server_loop _ _ _ _ _ _ _ _ _ state0_wf one_shot_body.\n\nEnd OneShotServer.\nEnd OneShotServer.\n\n(***** Batching (per iteration) server *****)\n\nModule BatchingServer.\nSection BatchingServer.\n\nVariable l : Label.\nVariable f : input -> option nat.\nVariable prec : input -> bool.\nHypothesis prec_valid :\n  forall i, prec i -> exists v, f i = Some v.\nVariables (cs cls : seq nid).\nNotation nodes := (cs ++ cls).\nHypothesis Huniq : uniq nodes.\n\nNotation cal := (CalculatorProtocol f prec cs cls l).\nNotation sts := (snd_trans cal).\nNotation rts := (rcv_trans cal).\nNotation W := (mkWorld cal).\n\n(* A server node *)\nVariable sv : nid.\nHypothesis  Hs : sv \\in cs.\nNotation loc i := (getLocal sv (getStatelet i l)).\n\n(* Server-specific infrastructure *)\nNotation Sstate := unit.\nDefinition state_wf := fun _ : unit => True.\nDefinition state0 := tt.\nLemma state0_wf : state_wf state0. Proof. done. Qed.\n\n(* Batch size *)\nVariable bsize : nat.\n\n\nDefinition batch_recv_loop_spec := forall (nsa : nat * Sstate * reqs),\n  DHT [sv, W]\n  (fun i => let: (n, s, acc) := nsa in\n            [/\\ loc i = st :-> acc,\n             size acc + n = bsize,\n             (forall e, e \\in acc ->\n              [/\\ e.1.1 \\in cls, e.1.2 = sv & prec e.2]) &\n             state_wf s],\n   fun (r : (reqs * Sstate)) m =>\n     [/\\ loc m = st :-> r.1,\n      size r.1 = bsize,\n      (forall e, e \\in r.1 ->\n              [/\\ e.1.1 \\in cls, e.1.2 = sv & prec e.2]) &\n      state_wf r.2]).\n\nProgram Definition receive_req_loop s :\n  DHT [sv, W] \n  (fun i => loc i = st :-> ([::]:reqs) /\\ state_wf s,                    \n   fun (r : (reqs * Sstate)) m =>\n     [/\\ loc m = st :-> r.1,\n      size r.1 = bsize,\n      (forall e, e \\in r.1 -> [/\\ e.1.1 \\in cls, e.1.2 = sv & prec e.2]) &\n      state_wf r.2]) :=\n  Do (ffix (fun (rec : batch_recv_loop_spec) nsa =>\n    Do _ (let: (n, s, acc) := nsa in\n          if n is n'.+1\n          then r <-- blocking_receive_req l f prec cs cls _ Hs;\n               let: (from, args) := r in\n               let: acc' := (from, sv, args) :: acc in  \n               rec (n', s, acc') \n          else ret _ _ (acc, s))) (bsize, tt, [::])). \n\nNext Obligation.\nmove=>i1/=[L1]S P _; case: n S=>//[|n]S.\n- by apply: ret_rule=>i2 R1/=; rewrite (rely_loc' _ R1) addn0.\napply: step; apply: (gh_ex (g:=r)).\napply: call_rule=>//[[from args]]i2/=[L2]H1 H2 C2.\napply: call_rule=>// _; split=>//; first by rewrite addSnnS.\nmove=>e; rewrite inE=>/orP; case; last by apply: P.\nby move/eqP=>Z; subst e. \nQed.\n\nNext Obligation.\nby move=>i1/=[L1]_; apply: call_rule.\nQed.\n\n(* Send batch responses *)\n\nDefinition batch_send_loop_spec := forall (acc : reqs),\n  DHT [sv, W]\n  (fun i => [/\\ loc i = st :-> acc &\n             (forall e, e \\in acc -> [/\\ e.1.1 \\in cls, e.1.2 = sv & prec e.2])],\n   fun (r : Sstate) m =>\n     [/\\ loc m = st :-> ([::]:reqs) & state_wf r]).\n\n\nProgram Definition send_ans_loop (acc : reqs) :\n  DHT [sv, W] \n    (fun i => loc i = st :-> acc /\\\n              (forall e, e \\in acc -> [/\\ e.1.1 \\in cls, e.1.2 = sv & prec e.2]),\n   fun (r : Sstate) m =>\n     [/\\ loc m = st :-> ([::]:reqs) & state_wf r]) :=\n  ffix (fun (rec : batch_send_loop_spec) acc =>\n    Do _ (if acc is (from, _, args) :: acc'\n          then let r := if f args is Some v then v else 0 in\n               send_answer l f prec cs cls _ Hs from args r;;\n               rec acc' \n          else ret _ _ tt)) acc. \n\nNext Obligation.\nmove=>i1/=[L1]P1; case: acc L1 P1=>[|[[from b]]args acc] L1 P1.\n- by apply: ret_rule=>i2 R1[H1]_; rewrite (rely_loc' _ R1).\n  apply: step.\nmove: (P1 (from, b, args)).\nrewrite inE eqxx/==>/(_ is_true_true)[X1]Z /prec_valid [v]F; subst b.\nmove: (erefl (f args))=>e.\nhave X: (match f args as anonymous' return (anonymous' = f args -> nat) with\n           | Some v => fun _ : Some v = f args => v\n           | None => fun _ : None = f args => 0\n         end e) = v by move: e; rewrite F.\nrewrite X=>{X e}.\napply: (gh_ex (g:=((from, sv, args) :: acc))).\napply: call_rule; first by move=>_; split=>//; rewrite inE eqxx.\nmove=>x i2/= [L2 H2] C2; apply: call_rule=>//_.\nrewrite eqxx in L2; split=>//e A; apply: P1.\nby rewrite inE A orbC.\nQed.\n\n(* Main batching server *)\n\nProgram Definition batched_body : forall _ : unit,\n  server_loop_body_spec l f prec cs cls sv _ state_wf state0 :=\n  fun _ => Do _ (\n     sr <-- receive_req_loop tt;\n     send_ans_loop sr.1).\nNext Obligation.\nmove=>i1/=[L1]_; apply: step.\napply: call_rule=>//[[acc _]]/= i2[L2 H2]P2 _ C2.\nby apply: call_rule.\nQed.\n\nDefinition batched_server :=\n  server_loop _ _ _ _ _ _ _ _ _ state0_wf batched_body.\n\nEnd BatchingServer.\nEnd BatchingServer.\n\n\n(***** Memoizing Server *****)\n\nModule MemoizingServer.\nSection MemoizingServer.\n\nVariable l : Label.\nVariable f : input -> option nat.\nVariable prec : input -> bool.\nHypothesis prec_valid :\n  forall i, prec i -> exists v, f i = Some v.\nVariables (cs cls : seq nid).\nNotation nodes := (cs ++ cls).\nHypothesis Huniq : uniq nodes.\n\nNotation cal := (CalculatorProtocol f prec cs cls l).\nNotation sts := (snd_trans cal).\nNotation rts := (rcv_trans cal).\nNotation W := (mkWorld cal).\nVariable sv : nid.\nHypothesis  Hs : sv \\in cs.\nNotation loc i := (getLocal sv (getStatelet i l)).\n\n(* Server-specific infrastructure *)\nNotation Sstate := (seq ((seq nat) * nat)).\nDefinition state_wf (s : Sstate) :=\n  forall e, e \\in s -> f e.1 = Some e.2.\nDefinition state0 : Sstate := [::].\nLemma state0_wf : state_wf state0. Proof. by []. Qed.\n\n(* Lookup tables *)\nDefinition update_mem_table (s : Sstate) args v :=\n  (args, v) :: s.\n\nFixpoint lookup_mem_table (s : Sstate) args : option nat :=\n  match s with\n  | x :: xs => if x.1 == args\n               then Some x.2\n               else lookup_mem_table xs args \n  | [::] => None\n  end.\n\nLemma lookup_valid' s args :\n  state_wf s ->\n  forall v, lookup_mem_table s args = Some v ->\n  f args = Some v.\nProof.\nelim:s=>//[[args' v']]s Hi H1 v/=.\ncase: ifP=>X.\n- move/eqP: X=>X;subst args'; case=>Z; subst v'.\n  by move:(H1 (args, v)); rewrite inE eqxx/==>/(_ is_true_true).\nsuff Y: state_wf s by apply: Hi.\nby move=>e H; move: (H1 e); rewrite inE H orbC/==>/(_ is_true_true).\nQed.\n\nLemma lookup_valid s args :\n  state_wf s ->\n  if lookup_mem_table s args is Some v\n  then f args = Some v else True.\nProof.\nmove/(lookup_valid' s args).\nby case: (lookup_mem_table s args)=>//v H; apply: (H v).\nQed.\n\nProgram Definition memoized_body : forall s : Sstate,\n  server_loop_body_spec l f prec cs cls sv _ state_wf s :=\n  fun s =>\n  Do _ (\n    r <-- blocking_receive_req l f prec cs cls _ Hs;\n    let: (from, args) := r in\n    (* First, try to look up the result in the memtable *)  \n    if lookup_mem_table s args is Some v\n    then send_answer l f prec cs cls _ Hs from args v;;\n         ret _ _ s\n    else (* Compute the answer function explicitly *)\n      let r := if f args is Some v then v else 0 in\n      let s' := update_mem_table s args r in\n      send_answer l f prec cs cls _ Hs from args r;;\n      ret _ _ s').\nNext Obligation.\nmove=>i1/=[L1]Hw; apply: step; apply: (gh_ex (g:=[::])).\napply: call_rule=>//[[from args]] i2/=[L2]H1 H2 C2.\nmove: (lookup_valid s args Hw).\n- case: (lookup_mem_table s args)=>[v F|_].\n  apply: step; apply: (gh_ex (g:=[:: (from, sv, args)])).\n  apply: call_rule=>//; first by move=>_; split=>//; rewrite inE eqxx.\n  move=>x i3/=; rewrite eqxx=> L3 C3. \n  apply: ret_rule=>i4 R3 _; split=>//.\n  by rewrite (rely_loc' _ R3); case: L3.\ncase: (prec_valid _ H2)=>ans F.\nmove: (erefl (f args))=>e.\nhave X: (match f args as anonymous' return (anonymous' = f args -> nat) with\n           | Some v => fun _ : Some v = f args => v\n           | None => fun _ : None = f args => 0\n         end e) = ans by move: e; rewrite F.\nrewrite X=>{X}; apply: step; apply: (gh_ex (g:=[:: (from, sv, args)])).\napply: call_rule=>//; first by move=>_; split=>//; rewrite inE eqxx.\nmove=>x i3/=; rewrite eqxx=> L3 C3. \napply: ret_rule=>i4 R3 _; split; first by rewrite (rely_loc' _ R3); case: L3.\nmove=>z; rewrite/update_mem_table inE/==>/orP.\ncase; last by move/Hw.\nby move/eqP=>->.\nQed.  \n\nDefinition memoizing_server :=\n  server_loop _ _ _ _ _ _ _ _ _ state0_wf memoized_body.\n\nEnd MemoizingServer.\nEnd MemoizingServer.\n\n\n(************************************)\n(**             Exports             *)\n(************************************)\n\nExport OneShotServer.\nExport BatchingServer.\nExport MemoizingServer.\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/SimpleCalculatorServers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.27890705751695793}}
{"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.\n\nSet Implicit Arguments.\nSet Typeclasses Depth 5.\n\n\n\n\n\nSection PROOF.\n  Let memRA: URA.t := (RA.excl Mem.t).\n  Context `{@GRA.inG memRA Σ}.\n  Let GURA: URA.t := GRA.to_URA Σ.\n  Local Existing Instance GURA.\n\n  Compute (URA.car (t:=memRA)).\n\n  Section BODY.\n    Context {Es: Type -> Type}.\n    Context `{has_pE: pE -< Es}.\n    Context `{has_eventE: eventE -< Es}.\n    Definition allocF: (list val) -> itree Es val :=\n      fun varg =>\n        mp0 <- trigger (PGet);;\n        m0 <- mp0↓?;;\n        `sz: Z <- (pargs [Tint] varg)?;;\n        if (Z_le_gt_dec 0 sz && Z_lt_ge_dec (8 * sz) modulus_64)\n        then (delta <- trigger (Choose _);;\n              let m0': Mem.t := Mem.mem_pad m0 delta in\n              let (blk, m1) := Mem.alloc m0' sz in\n              trigger (PPut m1↑);;;\n              Ret (Vptr blk 0))\n        else triggerUB\n    .\n\n    Definition freeF: list val -> itree Es val :=\n      fun varg =>\n        mp0 <- trigger (PGet);;\n        m0 <- mp0↓?;;\n        '(b, ofs) <- (pargs [Tptr] varg)?;;\n        m1 <- (Mem.free m0 b ofs)?;;\n        trigger (PPut m1↑);;;\n        Ret (Vint 0)\n    .\n\n    Definition loadF: list val -> itree Es val :=\n      fun varg =>\n        mp0 <- trigger (PGet);;\n        m0 <- mp0↓?;;\n        '(b, ofs) <- (pargs [Tptr] varg)?;;\n        v <- (Mem.load m0 b ofs)?;;\n        Ret v\n    .\n\n    Definition storeF: list val -> itree Es val :=\n      fun varg =>\n        mp0 <- trigger (PGet);;\n        m0 <- mp0↓?;;\n        '(b, ofs, v) <- (pargs [Tptr; Tuntyped] varg)?;;\n        m1 <- (Mem.store m0 b ofs v)?;;\n        trigger (PPut m1↑);;;\n        Ret (Vint 0)\n    .\n\n    Definition cmpF: list val -> itree Es val :=\n      fun varg =>\n        mp0 <- trigger (PGet);;\n        m0 <- mp0↓?;;\n        '(v0, v1) <- (pargs [Tuntyped; Tuntyped] varg)?;;\n        b <- (vcmp m0 v0 v1)?;;\n        if b: bool\n        then Ret (Vint 1%Z)\n        else Ret (Vint 0%Z)\n    .\n\n  End BODY.\n\n\n\n  Variable csl: gname -> bool.\n  Definition MemSem (sk: Sk.t): ModSem.t :=\n    {|\n      ModSem.fnsems := [(\"alloc\", cfunU allocF) ; (\"free\", cfunU freeF) ; (\"load\", cfunU loadF) ; (\"store\", cfunU storeF) ; (\"cmp\", cfunU cmpF)];\n      ModSem.mn := \"Mem\";\n      ModSem.initial_st := (Mem.load_mem csl sk)↑;\n    |}\n  .\n\n  Definition Mem: Mod.t := {|\n    Mod.get_modsem := MemSem;\n    Mod.sk := Sk.unit;\n  |}\n  .\nEnd PROOF.\n", "meta": {"author": "alxest", "repo": "CCR", "sha": "edcda8faae6580581e8e5b28050d755bcb29f55f", "save_path": "github-repos/coq/alxest-CCR", "path": "github-repos/coq/alxest-CCR/CCR-edcda8faae6580581e8e5b28050d755bcb29f55f/mem/Mem0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2789070514829014}}
{"text": "(*********************************************************************************************************************************)\n(* HaskStrongTypes: representation of types and coercions for HaskStrong                                                         *)\n(*********************************************************************************************************************************)\n\nGeneralizable All Variables.\nRequire Import Preamble.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\nRequire Import General.\nRequire Import HaskKinds.\nRequire Import HaskLiterals.\nRequire Import HaskTyCons.\nRequire Import HaskCoreTypes.\nRequire Import HaskCoreVars.\nRequire Import HaskWeakTypes.\nRequire Import HaskWeakVars.\nRequire Import HaskWeak.\nRequire Import HaskCoreToWeak.\n\nVariable dataConTyCon      : CoreDataCon -> TyCon.         Extract Inlined Constant dataConTyCon      => \"DataCon.dataConTyCon\".\nVariable dataConExVars_    : CoreDataCon -> list CoreVar.  Extract Inlined Constant dataConExVars_    => \"DataCon.dataConExTyVars\".\nVariable dataConEqTheta_   : CoreDataCon -> list PredType. Extract Inlined Constant dataConEqTheta_   => \"DataCon.dataConTheta\".\nVariable dataConOrigArgTys_: CoreDataCon -> list CoreType. Extract Inlined Constant dataConOrigArgTys_=>\"DataCon.dataConOrigArgTys\".\n\nDefinition dataConExTyVars cdc :=\n  filter (map (fun x => match coreVarToWeakVar' x with OK (WTypeVar v) => Some v | _ => None end) (dataConExVars_ cdc)).\n  Opaque dataConExTyVars.\nDefinition dataConCoerKinds cdc :=\n  filter (map (fun x => match x with EqPred t1 t2 =>\n                          match (\n                            coreTypeToWeakType t1 >>= fun t1' =>\n                              coreTypeToWeakType t2 >>= fun t2' =>\n                                OK (t1',t2'))\n                          with OK z => Some z\n                            | _ => None\n                          end\n                          | _ => None\n                        end) (dataConEqTheta_ cdc)).\n  Opaque dataConCoerKinds.\nDefinition dataConFieldTypes cdc :=\n  filter (map (fun x => match coreTypeToWeakType x with\n                          | OK z => Some z\n                          | _ => None\n                        end) (dataConOrigArgTys_ cdc)).\n\nDefinition tyConNumKinds (tc:TyCon) := length (tyConTyVars tc).\n  Coercion tyConNumKinds : TyCon >-> nat.\n\nInductive DataCon : TyCon -> Type :=\n  mkDataCon : forall cdc:CoreDataCon, DataCon (dataConTyCon cdc).\n  Definition dataConToCoreDataCon `(dc:DataCon tc) : CoreDataCon := match dc with mkDataCon cdc => cdc end.\n  Coercion mkDataCon : CoreDataCon >-> DataCon.\n  Coercion dataConToCoreDataCon : DataCon >-> CoreDataCon.\n  (*Opaque DataCon.*)\n\nDefinition tyConKind' tc := fold_right KindArrow ★ (tyConKind tc).\n\n(* types prefixed with \"Raw\" are NOT binder-polymorphic; they have had their PHOAS parameter instantiated already *)\nSection Raw.\n\n  (* TV is the PHOAS type which stands for type variables of System FC *)\n  Context {TV:Kind -> Type}.\n\n  (* Figure 7: ρ, σ, τ, ν *)\n  Inductive RawHaskType : Kind -> Type :=\n  | TVar           : ∀ κ, TV κ                                              -> RawHaskType κ                     (* a        *)\n  | TCon           : ∀ tc,                                                     RawHaskType (tyConKind' tc)       (* T        *)\n  | TArrow         :                                                           RawHaskType (★ ⇛★ ⇛★ )            (* (->)     *)\n  (*\n  | TKappa         :                                                           RawHaskType (★ ⇛★ ⇛★ )            (* (~~>)    *)\n  *)\n  | TCoerc         : ∀ κ, RawHaskType κ -> RawHaskType κ -> RawHaskType ★   -> RawHaskType ★                     (* (+>)     *)\n  | TApp           : ∀ κ₁ κ₂, RawHaskType (κ₂⇛κ₁)        -> RawHaskType κ₂  -> RawHaskType κ₁                    (* φ φ      *)\n  | TAll           : ∀ κ,                          (TV κ -> RawHaskType ★)  -> RawHaskType ★                     (* ∀a:κ.φ   *)\n  | TCode          : RawHaskType ECKind                  -> RawHaskType ★   -> RawHaskType ★                     (* from λ^α *)\n  | TyFunApp       : forall (tf:TyFun) kl k, RawHaskTypeList kl             -> RawHaskType k                     (* S_n      *)\n  with RawHaskTypeList : list Kind -> Type :=\n  | TyFunApp_nil   : RawHaskTypeList nil\n  | TyFunApp_cons  : ∀ κ kl, RawHaskType κ -> RawHaskTypeList kl -> RawHaskTypeList (κ::kl).\n    \n  (* the \"kind\" of a coercion is a pair of types *)\n  Inductive RawCoercionKind : Type :=\n    mkRawCoercionKind : ∀ κ, RawHaskType κ -> RawHaskType κ -> RawCoercionKind.\n\n  (* Figure 7: γ, δ; CV is the PHOAS type which stands for coercion variables of System FC *)\n  Inductive RawHaskCoer {CV:Type} : RawCoercionKind -> Prop := .\n  (*  \n   *  This has been disabled until we manage to reconcile SystemFC's\n   *  coercions with what GHC actually implements (they are not the\n   *  same!)\n   *  \n  | CoVar          : CV                                           -> RawHaskCoer (* g      *)\n  | CoType         : RawHaskType                                  -> RawHaskCoer (* τ      *)\n  | CoApp          : RawHaskCoer -> RawHaskCoer                   -> RawHaskCoer (* γ γ    *)\n  | CoAppT         : RawHaskCoer -> RawHaskType                   -> RawHaskCoer (* γ@v    *)\n  | CoCFApp        : ∀ n, CoFunConst n -> vec RawHaskCoer n       -> RawHaskCoer (* C   γⁿ *)\n  | CoTFApp        : ∀ n, TyFunConst n -> vec RawHaskCoer n       -> RawHaskCoer (* S_n γⁿ *)\n  | CoAll          : Kind  -> (TV -> RawHaskCoer)                 -> RawHaskCoer (* ∀a:κ.γ *)\n  | CoSym          : RawHaskCoer                                  -> RawHaskCoer (* sym    *)\n  | CoComp         : RawHaskCoer -> RawHaskCoer                   -> RawHaskCoer (* ◯      *)\n  | CoLeft         : RawHaskCoer                                  -> RawHaskCoer (* left   *)\n  | CoRight        : RawHaskCoer                                  -> RawHaskCoer (* right  *).\n  *)\nEnd Raw.\n\nImplicit Arguments TCon   [ [TV] ].\nImplicit Arguments TyFunApp [ [TV] ].\nImplicit Arguments RawHaskType  [ ].\nImplicit Arguments RawHaskCoer  [ ].\nImplicit Arguments RawCoercionKind [ ].\nImplicit Arguments TVar [ [TV] [κ] ].\nImplicit Arguments TCoerc [ [TV] [κ] ].\nImplicit Arguments TApp   [ [TV] [κ₁] [κ₂] ].\nImplicit Arguments TAll   [ [TV] ].\n\nNotation \"t1 ---> t2\"        := (fun TV env => (TApp (TApp TArrow (t1 TV env)) (t2 TV env))).\n(*Notation \"t1 ~~~> t2\"        := (fun TV env => (TApp (TApp TKappa (t1 TV env)) (t2 TV env))).*)\nNotation \"φ₁ ∼∼ φ₂ ⇒ φ₃\"     := (fun TV env => TCoerc (φ₁ TV env) (φ₂ TV env) (φ₃ TV env)).\n\n(* Kind and Coercion Environments *)\n(*\n *  In System FC, the environment consists of three components, each of\n *  whose well-formedness depends on all of those prior to it:\n *\n *    1. (TypeEnv)        The list of free type     variables and their kinds\n *    2. (CoercionEnv)    The list of free coercion variables and the pair of types between which it witnesses coercibility\n *    3. (Tree ??CoreVar) The list of free value    variables and the type of each one\n *)\n\nDefinition TypeEnv                                                         := list Kind.\nDefinition InstantiatedTypeEnv     (TV:Kind->Type)         (Γ:TypeEnv)     := IList _ TV Γ.\nDefinition HaskCoercionKind                    (Γ:TypeEnv)                 := ∀ TV, InstantiatedTypeEnv TV Γ -> @RawCoercionKind TV.\nDefinition CoercionEnv             (Γ:TypeEnv)                             := list (HaskCoercionKind Γ).\nDefinition InstantiatedCoercionEnv (TV:Kind->Type) CV       (Γ:TypeEnv)(Δ:CoercionEnv Γ):= vec CV (length Δ).\n\n(* A (HaskXX Γ) is an XX which is valid in environments of shape Γ; they are always PHOAS-uninstantiated *)\nDefinition HaskTyVar (Γ:TypeEnv) κ :=  forall TV    (env:@InstantiatedTypeEnv TV Γ), TV κ.\nDefinition HaskCoVar Γ Δ           :=  forall TV CV (env:@InstantiatedTypeEnv TV Γ)(cenv:@InstantiatedCoercionEnv TV CV Γ Δ), CV.\nDefinition HaskLevel (Γ:TypeEnv)   :=  list (HaskTyVar Γ ECKind).\nDefinition HaskType  (Γ:TypeEnv) κ := ∀ TV, @InstantiatedTypeEnv TV Γ -> RawHaskType TV κ.\nDefinition haskTyVarToType {Γ}{κ}(htv:HaskTyVar Γ κ) : HaskType Γ κ := fun TV ite => TVar (htv TV ite).\n\nInductive HaskTypeOfSomeKind (Γ:TypeEnv) :=\n  haskTypeOfSomeKind : ∀ κ, HaskType Γ κ -> HaskTypeOfSomeKind Γ.\n  Implicit Arguments haskTypeOfSomeKind [ [Γ] [κ] ].\n  Definition kindOfHaskTypeOfSomeKind {Γ}(htosk:HaskTypeOfSomeKind Γ) :=\n    match htosk with\n      haskTypeOfSomeKind κ _ => κ\n    end.\n  Coercion kindOfHaskTypeOfSomeKind : HaskTypeOfSomeKind >-> Kind.\n  Definition haskTypeOfSomeKindToHaskType {Γ}(htosk:HaskTypeOfSomeKind Γ) : HaskType Γ htosk :=\n    match htosk as H return HaskType Γ H with\n      haskTypeOfSomeKind _ ht => ht\n      end.\n  Coercion haskTypeOfSomeKindToHaskType : HaskTypeOfSomeKind >-> HaskType.\n\nDefinition HaskCoercion Γ Δ (hk:HaskCoercionKind Γ) := forall TV CV (ite:@InstantiatedTypeEnv TV Γ),\n    @InstantiatedCoercionEnv TV CV Γ Δ -> @RawHaskCoer TV CV (hk TV ite).\nInductive  LeveledHaskType (Γ:TypeEnv) κ := mkLeveledHaskType : HaskType Γ κ -> HaskLevel Γ -> LeveledHaskType Γ κ.\n\nDefinition FreshHaskTyVar {Γ}(κ:Kind) : HaskTyVar (κ::Γ) κ := fun TV env => ilist_head env.\n\nDefinition HaskTAll {Γ}(κ:Kind)(σ:forall TV (env:@InstantiatedTypeEnv TV Γ), TV κ -> RawHaskType TV ★) : HaskType Γ ★\n  := fun TV env => TAll κ (σ TV env).\nDefinition HaskTApp {Γ}{κ}(σ:forall TV (env:@InstantiatedTypeEnv TV Γ), TV κ -> RawHaskType TV ★)\n  (cv:HaskTyVar Γ κ) : HaskType Γ ★\n  := fun TV env => σ TV env (cv TV env).\nDefinition HaskBrak {Γ}(v:HaskTyVar Γ ECKind)(t:HaskType Γ ★) : HaskType Γ ★:=\n  fun TV env => @TCode TV (TVar (v TV env)) (t TV env).\nDefinition HaskTCon {Γ}(tc:TyCon) : HaskType Γ (fold_right KindArrow ★ (tyConKind tc))\n  := fun TV ite => TCon tc.\nDefinition HaskAppT {Γ}{κ₁}{κ₂}(t1:HaskType Γ (κ₂⇛κ₁))(t2:HaskType Γ κ₂) : HaskType Γ κ₁ :=\n  fun TV ite => TApp (t1 TV ite) (t2 TV ite).\nDefinition mkHaskCoercionKind {Γ}{κ}(t1:HaskType Γ κ)(t2:HaskType Γ κ) : HaskCoercionKind Γ :=\n fun TV ite => mkRawCoercionKind _ (t1 TV ite) (t2 TV ite).\n\nSection Flatten.\n  Context {TV:Kind -> Type }.\nFixpoint flattenT {κ} (exp: RawHaskType (fun k => RawHaskType TV k) κ) : RawHaskType TV κ :=\n     match exp with\n    | TVar    _  x        => x\n    | TAll     _ y        => TAll   _  (fun v => flattenT  (y (TVar v)))\n    | TApp   _ _ x y      => TApp      (flattenT  x) (flattenT  y)\n    | TCon       tc       => TCon      tc\n    | TCoerc _ t1 t2 t    => TCoerc    (flattenT  t1) (flattenT  t2)   (flattenT  t)\n    | TArrow              => TArrow\n    | TCode      v e      => TCode     (flattenT  v) (flattenT  e)\n    | TyFunApp  tfc kl k lt => TyFunApp tfc kl k (flattenTyFunApp _ lt)\n    end\n    with flattenTyFunApp (lk:list Kind)(exp:@RawHaskTypeList (fun k => RawHaskType TV k) 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 _ _ (flattenT  t) (flattenTyFunApp _ rest)\n    end.\nEnd Flatten.\n\n(* PHOAS substitution on types *)\nDefinition substT {Γ}{κ₁}{κ₂}(exp:forall TV (env:@InstantiatedTypeEnv TV Γ), TV κ₁ -> RawHaskType TV κ₂)(v:@HaskType Γ κ₁)\n  : @HaskType Γ κ₂ :=\n  fun TV env =>\n    flattenT (exp (fun k => RawHaskType TV k) (ilmap (fun κ tv => TVar tv) env) (v TV env)).\n\nNotation \"t @@  l\" := (@mkLeveledHaskType _ _ t l) (at level 20).\nNotation \"t @@@ l\" := (mapOptionTree (fun t' => t' @@ l) t) (at level 20).\nNotation \"'<[' a '|-' t ']>'\" := (@HaskBrak _ a t).\n\nDefinition getlev {Γ}(lt:LeveledHaskType Γ ★) := match lt with _ @@ l => l end.\n\nDefinition unlev {Γ}{κ}(lht:LeveledHaskType Γ κ) :=\n  match lht with t@@l => t end.\n\nStructure Global Γ :=\n{ glob_wv    : WeakExprVar\n; glob_kinds : list Kind\n; glob_tf    : IList _ (fun κ => HaskType Γ κ) glob_kinds -> HaskType Γ ★\n}.\nCoercion glob_tf : Global >-> Funclass.\nCoercion glob_wv : Global >-> WeakExprVar.\n\n(* From (t1->(t2->(t3-> ... t))), return t1::t2::t3::...nil *)\n(* this is a billion times uglier than it needs to be as a result of how primitive Coq's termiation checker is *)\nFixpoint take_arg_types {TV}{κ}(exp: RawHaskType TV κ) {struct exp} : list (RawHaskType TV κ) :=\n  match exp as E in RawHaskType _ K return list (RawHaskType _ K) with\n    | TApp   κ₁ κ₂ x y      =>\n      (match κ₁ as K1 return RawHaskType TV (κ₂ ⇛ K1) -> list (RawHaskType TV κ₂) -> list (RawHaskType _ K1) with\n         | KindStar =>\n           match κ₂ as K2 return RawHaskType TV (K2 ⇛ KindStar) -> list (RawHaskType TV K2) -> list (RawHaskType _ KindStar) with\n             | KindStar => fun x' =>\n               match x' return list (RawHaskType TV KindStar) -> list (RawHaskType _ KindStar) with\n                 | TApp κ₁'' κ₂'' w'' x'' =>\n                   match κ₂'' as K2'' return RawHaskType TV K2'' -> list (RawHaskType TV KindStar) ->\n                                                                    list (RawHaskType _ KindStar) with\n                     | KindStar     =>\n                       match w'' with\n                         | TArrow => fun a b => a::b\n                         | _      => fun _ _ => nil\n                       end\n                     | _ => fun _ _ => nil\n                   end x''\n                 | _                      => fun _  => nil\n               end\n             | _        => fun _ _ => nil\n           end\n         | _ => fun _ _ => nil\n       end) x (take_arg_types y)\n    | _                     => nil\n  end.\n\nFixpoint count_arg_types {TV}{κ}(exp: RawHaskType TV κ) {struct exp} : nat :=\n  match exp as E in RawHaskType _ K return nat with\n    | TApp   κ₁ κ₂ x y      =>\n      (match κ₁ as K1 return RawHaskType TV (κ₂ ⇛ K1) -> nat -> nat with\n         | KindStar =>\n           match κ₂ as K2 return RawHaskType TV (K2 ⇛ KindStar) -> nat -> nat with\n             | KindStar => fun x' =>\n               match x' return nat -> nat with\n                 | TApp κ₁'' κ₂'' w'' x'' =>\n                   match κ₂'' as K2'' return RawHaskType TV K2'' -> nat -> nat with\n                     | KindStar     =>\n                       match w'' with\n                         | TArrow => fun a b => S b\n                         | _      => fun _ _ => 0\n                       end\n                     | _ => fun _ _ => 0\n                   end x''\n                 | _                      => fun _  => 0\n               end\n             | _        => fun _ _ => 0\n           end\n         | _ => fun _ _ => 0\n       end) x (count_arg_types y)\n    | _                     => 0\n  end.\n\n  Definition ite_unit : ∀ Γ, InstantiatedTypeEnv (fun _ => unit) Γ.\n    intros.\n    induction Γ.\n    apply INil.\n    apply ICons; auto.\n    apply tt.\n    Defined.\n\nDefinition take_arg_type {Γ}{κ}(ht:HaskType Γ κ) : (gt (count_arg_types (ht _ (ite_unit _))) 0) -> HaskType Γ κ :=\n  fun pf =>\n  fun TV ite =>\n    match take_arg_types (ht TV ite) with\n    | nil => Prelude_error \"impossible\"\n    | x::y => x\n    end.\n\n(* From (t1->(t2->(t3-> ... t))), return t *)\n(* this is a billion times uglier than it needs to be as a result of how primitive Coq's termiation checker is *)\nFixpoint drop_arg_types {TV}{κ}(exp: RawHaskType TV κ) : RawHaskType TV κ :=\n  match exp as E in RawHaskType _ K return RawHaskType _ K with\n    | TApp   κ₁ κ₂ x y      =>\n      let q :=\n      (match κ₁ as K1 return RawHaskType TV (κ₂ ⇛ K1) -> (RawHaskType TV κ₂) -> ??(RawHaskType _ K1) with\n         | KindStar =>\n           match κ₂ as K2 return RawHaskType TV (K2 ⇛ KindStar) -> (RawHaskType TV K2) -> ??(RawHaskType _ KindStar) with\n             | KindStar => fun x' =>\n               match x' return  (RawHaskType TV KindStar) -> ??(RawHaskType _ KindStar) with\n                 | TApp κ₁'' κ₂'' w'' x'' =>\n                   match κ₂'' as K2'' return RawHaskType TV K2'' ->  (RawHaskType TV KindStar) -> ??(RawHaskType _ KindStar) with\n                     | KindStar     =>\n                       match w'' with\n                         | TArrow => fun _ b => Some b\n                         | _      => fun _ b => None\n                       end\n                     | _ => fun _ b => None\n                   end x''\n                 | _       => fun _ => None\n               end\n             | _        => fun _ _ => None\n           end\n         | _ => fun _ _ => None\n       end) x (drop_arg_types y)\n      in match q with\n           | None   => TApp x y\n           | Some y => y\n         end\n    | b                     => b\n  end.\n\n\n\n\n(* yeah, things are kind of messy below this point *)\n\n\nDefinition unAddKindFromInstantiatedTypeEnv {Γ:TypeEnv}{κ:Kind}{TV:Kind->Type}(ite:InstantiatedTypeEnv TV (κ::Γ))\n  := ilist_tail ite.\nDefinition addKindToCoercionEnv (Γ:TypeEnv)(Δ:CoercionEnv Γ)(κ:Kind) : CoercionEnv (κ::Γ) :=\n  map (fun f => (fun TV ite => f TV (unAddKindFromInstantiatedTypeEnv ite))) Δ.\nDefinition addKindToInstantiatedTypeEnv {Γ:TypeEnv}{TV:Kind->Type}(env:InstantiatedTypeEnv TV Γ)(κ:Kind)(tv:TV κ)\n  : InstantiatedTypeEnv TV (κ::Γ) := tv::::env.\nDefinition addKindToInstantiatedCoercionEnv {Γ:TypeEnv}{Δ}{TV:Kind->Type}{CV:Type}\n  (env:InstantiatedCoercionEnv TV CV Γ Δ)(κ:Kind)(tv:TV κ)\n  : InstantiatedCoercionEnv TV CV (κ::Γ) (addKindToCoercionEnv Γ Δ κ).\n    simpl.\n    unfold InstantiatedCoercionEnv.\n    unfold addKindToCoercionEnv.\n    simpl.\n    rewrite <- map_preserves_length.\n    apply env.\n    Defined.\nDefinition coercionEnvContainsCoercion {Γ}{Δ}{TV:Kind->Type}{CV:Type}(ite:InstantiatedTypeEnv TV Γ)\n  (ice:InstantiatedCoercionEnv TV CV Γ Δ)(cv:CV)(ck:RawCoercionKind TV)\n  := @vec_In _ _ (cv,ck) (vec_zip ice (vec_map (fun f => f TV ite) (list2vec Δ))).\nDefinition addCoercionToCoercionEnv {Γ}(Δ:CoercionEnv Γ)(κ:HaskCoercionKind Γ) : CoercionEnv Γ :=\n  κ::Δ.\nDefinition addCoercionToInstantiatedCoercionEnv {Γ}{Δ}{κ}{TV CV}(ice:InstantiatedCoercionEnv TV CV Γ Δ)(cv:CV)\n  : InstantiatedCoercionEnv TV CV Γ (addCoercionToCoercionEnv Δ κ).\n  simpl.\n  unfold addCoercionToCoercionEnv; simpl.\n  unfold InstantiatedCoercionEnv; simpl. \n  apply vec_cons; auto.\n  Defined.\n\n(* the various \"weak\" functions turn a HaskXX-in-Γ into a HaskXX-in-(κ::Γ) *)\nDefinition weakITE  {Γ:TypeEnv}{κ}{TV}(ite:InstantiatedTypeEnv TV (κ::Γ)) : InstantiatedTypeEnv TV Γ := ilist_tail ite.\nDefinition weakCE   {Γ:TypeEnv}{κ}(Δ:CoercionEnv Γ) : CoercionEnv (κ::Γ) := map (fun x => (fun tv ite => x tv (weakITE ite))) Δ.\nDefinition weakV  {Γ:TypeEnv}{κ}{κv}(cv':HaskTyVar Γ κv) : HaskTyVar (κ::Γ) κv := fun TV ite => (cv' TV (weakITE ite)).\nDefinition weakT {Γ:TypeEnv}{κ}{κ₂}(lt:HaskType Γ κ₂) : HaskType (κ::Γ) κ₂ := fun TV ite => lt TV (weakITE ite).\nDefinition weakL  {Γ}{κ}(lt:HaskLevel Γ) : HaskLevel (κ::Γ) := map weakV lt.\nDefinition weakLT {Γ}{κ}{κ₂}(lt:LeveledHaskType Γ κ₂) : LeveledHaskType (κ::Γ) κ₂ := match lt with t @@ l => weakT t @@ weakL l end.\nDefinition weakICE  {Γ:TypeEnv}{κ}{Δ:CoercionEnv Γ}{TV}{CV}(ice:InstantiatedCoercionEnv TV CV (κ::Γ) (weakCE Δ))\n  : InstantiatedCoercionEnv TV CV Γ Δ.\n  intros.\n  unfold InstantiatedCoercionEnv; intros.\n  unfold InstantiatedCoercionEnv in ice.\n  unfold weakCE in ice.\n  simpl in ice.\n  rewrite <- map_preserves_length in ice.\n  apply ice.\n  Defined.\nDefinition weakCK {Γ}{κ}(hck:HaskCoercionKind Γ) : HaskCoercionKind (κ::Γ).\n  unfold HaskCoercionKind in *.\n  intros.\n  apply hck; clear hck.\n  inversion X; subst; auto.\n  Defined.\nDefinition weakCV {Γ}{Δ}{κ}(cv':HaskCoVar Γ Δ) : HaskCoVar (κ::Γ) (weakCE Δ) :=\n  fun TV CV ite ice => (cv' TV CV (weakITE ite) (weakICE ice)).\nDefinition weakF {Γ:TypeEnv}{κ}{κ₂}(f:forall TV (env:@InstantiatedTypeEnv TV Γ), TV κ -> RawHaskType TV κ₂) : \n  forall TV (env:@InstantiatedTypeEnv TV (κ::Γ)), TV κ -> RawHaskType TV κ₂\n  := fun TV ite tv => (f TV (weakITE ite) tv).\n\n\nDefinition weakITE' {Γ:TypeEnv}{κ}{TV}(ite:InstantiatedTypeEnv TV (app κ Γ)) : InstantiatedTypeEnv TV Γ.\n  induction κ; auto. apply IHκ. inversion ite; subst. apply X0. Defined.\nDefinition weakV' {Γ:TypeEnv}{κ}{κv}(cv':HaskTyVar Γ κv) : HaskTyVar (app κ Γ) κv.\n  induction κ; auto. apply weakV; auto. Defined.\nDefinition weakT' {Γ}{κ}{κ₂}(lt:HaskType Γ κ₂) : HaskType (app κ Γ) κ₂.\n  induction κ; auto. apply weakT; auto. Defined.\nDefinition weakT'' {Γ}{κ}{κ₂}(lt:HaskType Γ κ₂) : HaskType (app Γ κ) κ₂.\n  unfold HaskType in *.\n  unfold InstantiatedTypeEnv in *.\n  intros.\n  apply ilist_chop in X.\n  apply lt.\n  apply X.\n  Defined.\nDefinition weakL' {Γ}{κ}(lev:HaskLevel Γ) : HaskLevel (app κ Γ).\n  induction κ; auto. apply weakL; auto. Defined.\nDefinition weakLT' {Γ}{κ}{κ₂}(lt:LeveledHaskType Γ κ₂) : LeveledHaskType (app κ Γ) κ₂\n  := match lt with t @@ l => weakT' t @@ weakL' l end.\nDefinition weakCE' {Γ:TypeEnv}{κ}(Δ:CoercionEnv Γ) : CoercionEnv (app κ Γ).\n  induction κ; auto. apply weakCE; auto. Defined.\nDefinition weakCK' {Γ}{κ}(hck:HaskCoercionKind Γ) : HaskCoercionKind (app κ Γ).\n  induction κ; auto.\n  apply weakCK.\n  apply IHκ.\n  Defined.\nDefinition weakCK'' {Γ}{κ}(hck:list (HaskCoercionKind Γ)) : list (HaskCoercionKind (app κ Γ)) :=\n  map weakCK' hck.\n\nDefinition weakITE_ {Γ:TypeEnv}{κ}{n}{TV}(ite:InstantiatedTypeEnv TV (list_ins n κ Γ)) : InstantiatedTypeEnv TV Γ.\n  rewrite list_ins_app in ite.\n  set (weakITE' ite) as ite'.\n  set (ilist_chop ite) as a.\n  rewrite <- (list_take_drop _ Γ n).\n  apply ilist_app; auto.\n  inversion ite'; auto.\n  Defined.\n\nDefinition weakV_ {Γ:TypeEnv}{κ}{n}{κv}(cv':HaskTyVar Γ κv) : HaskTyVar (list_ins n κ Γ) κv.\n  unfold HaskTyVar; intros.\n  unfold HaskTyVar in cv'.\n  apply (cv' TV).\n  apply weakITE_ in env.\n  apply env.\n  Defined.\n\nDefinition weakT_ {Γ}{κ}{n}{κ₂}(lt:HaskType Γ κ₂) : HaskType (list_ins n κ Γ) κ₂.\n  unfold HaskType; intros.\n  apply lt.\n  apply weakITE_ in X.\n  apply X.\n  Defined.\nDefinition weakL_ {Γ}{κ}{n}(lev:HaskLevel Γ) : HaskLevel (list_ins n κ Γ).\n  unfold HaskLevel; intros.\n  unfold HaskLevel in lev.\n  eapply map.\n  apply weakV_.\n  apply lev.\n  Defined.\nDefinition weakLT_ {Γ}{κ}{n}{κ₂}(lt:LeveledHaskType Γ κ₂) : LeveledHaskType (list_ins n κ Γ) κ₂ :=\n  match lt with t@@l => weakT_ t @@ weakL_ l end.\nDefinition weakCK_ {Γ}{κ}{n}(hck:HaskCoercionKind Γ) : HaskCoercionKind (list_ins n κ Γ).\n  unfold HaskCoercionKind; intros.\n  unfold HaskCoercionKind in hck.\n  apply hck.\n  apply weakITE_ in X.\n  apply X.\n  Defined.\nDefinition weakCE_ {Γ:TypeEnv}{κ}{n}(Δ:CoercionEnv Γ) : CoercionEnv (list_ins n κ Γ) := map weakCK_ Δ.\nDefinition weakF_ {Γ:TypeEnv}{n}{κ}{κ₂}(f:forall TV (env:@InstantiatedTypeEnv TV Γ), TV κ -> RawHaskType TV κ₂) : \n  forall TV (env:@InstantiatedTypeEnv TV (list_ins n κ Γ)), TV κ -> RawHaskType TV κ₂.\n  intros.\n  apply f.\n  apply weakITE_ in env.\n  apply env.\n  apply X.\n  Defined.\nDefinition weakCV_ {Γ}{Δ}{κ}{n}(cv':HaskCoVar Γ Δ) : HaskCoVar (list_ins n κ Γ) (weakCE_ Δ).\n  unfold HaskCoVar; intros.\n  unfold HaskCoVar in cv'.  \n  apply (cv' TV).\n  apply weakITE_ in env.\n  apply env.\n  unfold InstantiatedCoercionEnv.\n  unfold InstantiatedCoercionEnv in cenv.\n  replace (length (@weakCE_ _ κ n Δ)) with (length Δ) in cenv.\n  apply cenv.\n  unfold weakCE_.\n  rewrite <- map_preserves_length.\n  reflexivity.\n  Defined.\n\nDefinition FreshHaskTyVar_ {Γ}(κ:Kind) : forall {n}, HaskTyVar (list_ins n κ Γ) κ.\n  intros.\n  unfold HaskTyVar.\n  intros.\n  rewrite list_ins_app in env.\n  apply weakITE' in env.\n  inversion env; subst; auto.\n  Defined.\n\n\n\nFixpoint caseType0 {Γ}(lk:list Kind) :\n  IList _ (HaskType Γ) lk ->\n  HaskType Γ (fold_right KindArrow ★ lk) ->\n  HaskType Γ ★ :=\n  match lk as LK return\n    IList _ (HaskType Γ) LK ->\n    HaskType Γ (fold_right KindArrow ★ LK) ->\n    HaskType Γ ★ \n  with\n  | nil    => fun _     ht => ht\n  | k::lk' => fun tlist ht => caseType0 lk' (ilist_tail tlist) (fun TV env => TApp (ht TV env) (ilist_head tlist TV env))\n  end.\n\nDefinition caseType {Γ}(tc:TyCon)(atypes:IList _ (HaskType Γ) (tyConKind tc)) : HaskType Γ ★ :=\n  caseType0 (tyConKind tc) atypes (fun TV env => TCon tc).\n\n(* like a GHC DataCon, but using PHOAS representation for types and coercions *)\nRecord StrongAltCon {tc:TyCon} :=\n{ sac_tc          := tc\n; sac_altcon      :  WeakAltCon\n; sac_numExTyVars :  nat\n; sac_numCoerVars :  nat\n; sac_numExprVars :  nat\n; sac_ekinds      :  vec Kind sac_numExTyVars\n; sac_kinds       := app (tyConKind tc) (vec2list sac_ekinds)\n; sac_gamma          := fun Γ => app (vec2list sac_ekinds) Γ\n; sac_coercions   :  forall Γ (atypes:IList _ (HaskType Γ) (tyConKind tc)), vec (HaskCoercionKind (sac_gamma Γ)) sac_numCoerVars\n; sac_types       :  forall Γ (atypes:IList _ (HaskType Γ) (tyConKind tc)), vec (HaskType (sac_gamma Γ) ★) sac_numExprVars\n; sac_delta          := fun    Γ (atypes:IList _ (HaskType Γ) (tyConKind tc)) Δ => app (vec2list (sac_coercions Γ atypes)) Δ\n}.\nCoercion sac_tc     : StrongAltCon >-> TyCon.\nCoercion sac_altcon : StrongAltCon >-> WeakAltCon.\n  \n\nDefinition kindOfType {Γ}{κ}(ht:@HaskType Γ κ) : ???Kind := OK κ.\n\nAxiom literal_tycons_are_of_ordinary_kind : forall lit, tyConKind (haskLiteralToTyCon lit) = nil.\n\nDefinition literalType (lit:HaskLiteral){Γ} : HaskType Γ ★.\n  set (fun TV (ite:InstantiatedTypeEnv TV Γ) => @TCon TV (haskLiteralToTyCon lit)) as z.\n  unfold tyConKind' in z.\n  rewrite literal_tycons_are_of_ordinary_kind in z.\n  unfold HaskType.\n  apply z.\n  Defined.\n\nNotation \"a ∼∼∼ b\" := (@mkHaskCoercionKind _ _ a b) (at level 18).\n\nFixpoint update_xi\n  `{EQD_VV:EqDecidable VV}{Γ}\n   (ξ:VV -> LeveledHaskType Γ ★)\n   (lev:HaskLevel Γ)\n   (vt:list (VV * HaskType Γ ★))\n   : VV -> LeveledHaskType Γ ★ :=\n  match vt with\n    | nil => ξ\n    | (v,τ)::tl => fun v' => if eqd_dec v v' then τ @@ lev else (update_xi ξ lev tl) v'\n  end.\n\nLemma update_xi_lemma0 `{EQD_VV:EqDecidable VV} : forall Γ ξ (lev:HaskLevel Γ)(varstypes:list (VV*_)) v,\n  not (In v (map (@fst _ _) varstypes)) ->\n  (update_xi ξ lev varstypes) v = ξ v.\n  intros.\n  induction varstypes.\n  reflexivity.\n  simpl.\n  destruct a.\n  destruct (eqd_dec v0 v).\n  subst.\n  simpl in  H.\n  assert False. \n  apply H.\n  auto.\n  inversion H0.\n  apply IHvarstypes.\n  unfold not; intros.\n  apply H.\n  simpl.\n  auto.\n  Defined.\n\n\n(***************************************************************************************************)\n(* Well-Formedness of Types and Coercions                                                          *)\n(* also represents production \"S_n:κ\" of Γ because these can only wind up in Γ via rule (Type) *)\nInductive TypeFunctionDecl (tfc:TyCon)(vk:vec Kind tfc) : Type :=\n  mkTFD : Kind -> TypeFunctionDecl tfc vk.\n\n(*\nSection WFCo.\n  Context {TV:Kind->Type}.\n  Context {CV:Type}.\n\n  (* local notations *)\n  Notation \"ienv '⊢ᴛy' σ : κ\"              := (@WellKinded_RawHaskType TV _ ienv σ κ).\n  Notation \"env  ∋  cv : t1 ∼ t2 : Γ : t\"  := (@coercionEnvContainsCoercion Γ _ TV CV t env cv (@mkRawCoercionKind _ t1 t2))\n                 (at level 20, t1 at level 99, t2 at level 99, t at level 99).\n  Reserved Notation \"ice '⊢ᴄᴏ' γ : a '∼' b : Δ : Γ : ite\"\n        (at level 20, γ at level 99, b at level 99, Δ at level 99, ite at level 99, Γ at level 99).\n\n  (* Figure 8, lower half *)\n  Inductive WFCoercion:forall Γ (Δ:CoercionEnv Γ),\n    @InstantiatedTypeEnv TV Γ ->\n    @InstantiatedCoercionEnv TV CV Γ Δ ->\n    @RawHaskCoer TV CV -> @RawCoercionKind TV -> Prop :=\n  | CoTVar':∀ Γ Δ t e c σ τ,\n    (@coercionEnvContainsCoercion Γ _ TV CV t e c (@mkRawCoercionKind _ σ τ)) -> e⊢ᴄᴏ CoVar c : σ ∼ τ  : Δ : Γ : t\n  | CoRefl :∀ Γ Δ t e   τ κ,                                         t ⊢ᴛy τ :κ    -> e⊢ᴄᴏ CoType τ    :         τ ∼ τ  : Δ :Γ: t\n  | Sym    :∀ Γ Δ t e γ σ τ,                            (e⊢ᴄᴏ γ : σ ∼ τ : Δ : Γ:t)  -> e⊢ᴄᴏ CoSym  γ    :         τ ∼ σ  : Δ :Γ: t\n  | Trans  :∀ Γ Δ t e γ₁ γ₂ σ₁ σ₂ σ₃,(e⊢ᴄᴏ γ₁:σ₁∼σ₂:Δ:Γ:t) -> (e⊢ᴄᴏ γ₂:σ₂∼σ₃:Δ:Γ:t) -> e⊢ᴄᴏ CoComp γ₁ γ₂:        σ₁ ∼ σ₃ : Δ :Γ: t\n  | Left   :∀ Γ Δ t e γ σ₁ σ₂ τ₁ τ₂,(e⊢ᴄᴏ γ : TApp σ₁ σ₂ ∼ TApp τ₁ τ₂ :Δ:Γ:t    )  -> e⊢ᴄᴏ CoLeft  γ   :        σ₁ ∼ τ₁ : Δ :Γ: t\n  | Right  :∀ Γ Δ t e γ σ₁ σ₂ τ₁ τ₂,(e⊢ᴄᴏ γ : TApp σ₁ σ₂ ∼ TApp τ₁ τ₂ :Δ:Γ:t   )   -> e⊢ᴄᴏ CoRight γ   :        σ₂ ∼ τ₂ : Δ :Γ: t\n  (*\n  | SComp  :∀ Γ Δ t e γ n S σ τ κ,\n            ListWFCo Γ Δ t e γ σ τ -> t ⊢ᴛy TyFunApp(n:=n) S σ : κ  -> e⊢ᴄᴏ CoTFApp S γ : TyFunApp S σ∼TyFunApp S τ : Δ : Γ : t\n  | CoAx   :∀ Γ Δ t e n C κ γ, forall (σ₁:vec TV n) (σ₂:vec TV n), forall (ax:@AxiomDecl n C κ TV),\n    ListWFCo                              Γ Δ t e γ (map TVar (vec2list σ₁)) (map TVar (vec2list σ₂)) ->\n    ListWellKinded_RawHaskType TV Γ t   (map TVar (vec2list σ₁))            (vec2list κ)  ->\n    ListWellKinded_RawHaskType TV Γ t   (map TVar (vec2list σ₂))            (vec2list κ)  ->\n    e⊢ᴄᴏ CoCFApp C γ : axd_σ _ _ _ ax σ₁ ∼ axd_τ _ _ _ ax σ₂ : Δ : Γ : t\n  *)\n  | WFCoAll  : forall Γ Δ κ (t:InstantiatedTypeEnv TV Γ) (e:InstantiatedCoercionEnv TV CV (κ::Γ) (weakCE Δ)) γ σ τ    ,\n      (∀ a,           e ⊢ᴄᴏ (        γ a) : (       σ a) ∼ (       τ a) : _ : _ : (t + a : κ))\n      ->    weakICE e ⊢ᴄᴏ (CoAll κ γ  ) : (TAll κ σ  ) ∼ (TAll κ τ  ) : Δ : Γ :  t\n  | Comp   :forall Γ Δ t e γ₁ γ₂ σ₁ σ₂ τ₁ τ₂ κ,\n            (t ⊢ᴛy TApp σ₁ σ₂:κ)->\n            (e⊢ᴄᴏ γ₁:σ₁∼τ₁:Δ:Γ:t)->\n            (e⊢ᴄᴏ γ₂:σ₂∼τ₂:Δ:Γ:t) ->\n            e⊢ᴄᴏ (CoApp γ₁ γ₂) : (TApp σ₁ σ₂) ∼ (TApp τ₁ τ₂) : Δ:Γ:t\n  | CoInst :forall Γ Δ t e σ τ κ γ (v:∀ TV, InstantiatedTypeEnv TV Γ -> RawHaskType TV),\n          t ⊢ᴛy v TV t : κ  ->\n            (e⊢ᴄᴏ γ:HaskTAll κ σ _ t ∼ HaskTAll κ τ _ t:Δ:Γ:t) ->\n            e⊢ᴄᴏ CoAppT γ (v TV t) : substT σ v TV t ∼substT τ v TV t : Δ : Γ : t\n  with ListWFCo  : forall Γ (Δ:CoercionEnv Γ),\n     @InstantiatedTypeEnv TV Γ ->\n     InstantiatedCoercionEnv TV CV Γ Δ ->\n     list (RawHaskCoer TV CV) -> list (RawHaskType TV) -> list (RawHaskType TV) -> Prop :=\n  | LWFCo_nil  : ∀ Γ Δ t e ,                                                            ListWFCo Γ Δ t e nil     nil     nil\n  | LWFCo_cons : ∀ Γ Δ t e a b c la lb lc, (e⊢ᴄᴏ a : b∼c : Δ : Γ : t )->\n    ListWFCo Γ Δ t e la lb lc -> ListWFCo Γ Δ t e (a::la) (b::lb) (c::lc)\n  where \"ice '⊢ᴄᴏ' γ : a '∼' b : Δ : Γ : ite\" := (@WFCoercion Γ Δ ite ice γ (@mkRawCoercionKind _ a b)).\nEnd WFCo.\n\nDefinition WFCCo (Γ:TypeEnv)(Δ:CoercionEnv Γ)(γ:HaskCoercion Γ Δ)(a b:HaskType Γ) :=\n  forall {TV CV:Type}(env:@InstantiatedTypeEnv TV Γ)(cenv:InstantiatedCoercionEnv TV CV Γ Δ),\n    @WFCoercion _ _ Γ Δ env cenv (γ TV CV env cenv) (@mkRawCoercionKind _ (a TV env) (b TV env)).\n    Notation \"Δ '⊢ᴄᴏ' γ : a '∼' b\" := (@WFCCo _ Δ γ a b).\n*)\n\n\n\n\n(* Decidable equality on PHOAS types *)\nFixpoint compareT (n:nat){κ₁}(t1:@RawHaskType (fun _ => nat) κ₁){κ₂}(t2:@RawHaskType (fun _ => nat) κ₂) : bool :=\nmatch t1 with\n| TVar    _  x     => match t2 with TVar _ x' => if eqd_dec x x' then true else false | _ => false end\n| TAll     _ y     => match t2 with TAll _ y' => compareT (S n) (y n) (y' n)          | _ => false end\n| TApp   _ _ x y   => match t2 with TApp _ _ x' y' => if compareT n x x' then compareT n y y' else false | _ => false end\n| TCon       tc    => match t2 with TCon tc' => if eqd_dec tc tc' then true else false | _ => false end\n| TArrow           => match t2 with TArrow => true | _ => false end\n| TCode      ec t  => match t2 with TCode ec' t' => if compareT n ec ec' then compareT n t t' else false | _ => false end\n| TCoerc _ t1 t2 t => match t2 with TCoerc _ t1' t2' t' => compareT n t1 t1' && compareT n t2 t2' && compareT n t t' | _ =>false end\n| TyFunApp tfc kl k lt  => match t2 with TyFunApp tfc' kl' k' lt' => eqd_dec tfc tfc' && compareTL n lt lt' | _ => false end\nend\nwith compareTL (n:nat){κ₁}(t1:@RawHaskTypeList (fun _ => nat) κ₁){κ₂}(t2:@RawHaskTypeList (fun _ => nat) κ₂) : bool :=\nmatch t1 with\n| TyFunApp_nil              => match t2 with TyFunApp_nil => true | _ => false end\n| TyFunApp_cons κ kl t r => match t2 with | TyFunApp_cons κ' kl' t' r' => compareT n t t' && compareTL n r r' | _ => false end\nend.\n\nFixpoint count' (lk:list Kind)(n:nat) : IList _ (fun _ => nat) lk :=\nmatch lk as LK return IList _ _ LK with\n  | nil    => INil\n  | h::t   => n::::(count' t (S n))\nend.\n\nDefinition compareHT Γ κ (ht1 ht2:HaskType Γ κ) :=\n  compareT (length Γ) (ht1 (fun _ => nat) (count' Γ O)) (ht2 (fun _ => nat) (count' Γ O)).\n\n(* The PHOAS axioms\n * \n * This is not provable in Coq's logic because the Coq function space\n * is \"too big\" - although its only definable inhabitants are Coq\n * functions, it is not provable in Coq that all function space\n * inhabitants are definable (i.e. there are no \"exotic\" inhabitants).\n * This is actually an important feature of Coq: it lets us reason\n * about properties of non-computable (non-recursive) functions since\n * any property proven to hold for the entire function space will hold\n * even for those functions.  However when representing binding\n * structure using functions we would actually prefer the smaller\n * function-space of *definable* functions only.  These two axioms\n * assert that. *)\nAxiom compareHT_decides : forall Γ κ (ht1 ht2:HaskType Γ κ),\n  if compareHT Γ κ ht1 ht2\n  then ht1=ht2\n  else ht1≠ht2.\nAxiom compareVars : forall Γ κ (htv1 htv2:HaskTyVar Γ κ),\n  if compareHT _ _ (haskTyVarToType htv1) (haskTyVarToType htv2)\n  then htv1=htv2\n  else htv1≠htv2.\n\n(* using the axioms, we can now create an EqDecidable instance for HaskType, HaskTyVar, and HaskLevel *)\nInstance haskTypeEqDecidable Γ κ : EqDecidable (HaskType Γ κ).\n  apply Build_EqDecidable.\n  intros.\n  set (compareHT_decides _ _ v1 v2) as z.\n  set (compareHT Γ κ v1 v2) as q.\n  destruct q as [ ] _eqn; unfold q in *; rewrite Heqb in *.\n    left; auto.\n    right; auto.\n    Defined.\n\nInstance haskTyVarEqDecidable Γ κ : EqDecidable (HaskTyVar Γ κ).\n  apply Build_EqDecidable.\n  intros.\n  set (compareVars _ _ v1 v2) as z.\n  set (compareHT Γ κ (haskTyVarToType v1) (haskTyVarToType v2)) as q.\n  destruct q as [ ] _eqn; unfold q in *; rewrite Heqb in *.\n    left; auto.\n    right; auto.\n    Defined.\n\nInstance haskLevelEqDecidable Γ : EqDecidable (HaskLevel Γ).\n  apply Build_EqDecidable.\n  intros.\n  unfold HaskLevel in *.\n  apply (eqd_dec v1 v2).\n  Defined.\n\n\n\n\n\n(* ToString instance for PHOAS types *)\nFixpoint typeToString' (needparens:bool)(n:nat){κ}(t:RawHaskType (fun _ => nat) κ) {struct t} : string :=\n    match t with\n    | TVar    _ v          => \"tv\" +++ toString v\n    | TCon    tc           => toString tc\n    | TCoerc _ t1 t2   t   => \"(\"+++typeToString' false n t1+++\"~\"\n                                  +++typeToString' false n t2+++\")=>\"\n                                  +++typeToString' needparens n t\n    | TApp  _ _  t1 t2     =>\n      match t1 with\n        | TApp _ _ TArrow t1 =>\n                     if needparens\n                     then \"(\"+++(typeToString' true n t1)+++\"->\"+++(typeToString' true n t2)+++\")\"\n                     else (typeToString' true n t1)+++\"->\"+++(typeToString' true n t2)\n        | _ =>\n                     if needparens\n                     then \"(\"+++(typeToString' true n t1)+++\" \"+++(typeToString' false n t2)+++\")\"\n                     else (typeToString' true n t1)+++\" \"+++(typeToString' false n t2)\n      end\n    | TArrow => \"(->)\"\n    | TAll   k f           => let alpha := \"tv\"+++ toString n\n                              in \"(forall \"+++ alpha +++ \":\"+++ toString k +++\")\"+++\n                                   typeToString' false (S n) (f n)\n    | TCode  ec t          => \"<[\"+++(typeToString' true n t)+++\"]>@\"+++(typeToString' false n ec)\n    | TyFunApp   tfc kl k lt    => toString tfc+++ \"_\" +++ toString n+++\" [\"+++\n      (fold_left (fun x y => \" \\  \"+++x+++y) (typeList2string false n lt) \"\")+++\"]\"\n  end\n  with typeList2string (needparens:bool)(n:nat){κ}(t:RawHaskTypeList κ) {struct t} : list string :=\n  match t with\n  | TyFunApp_nil                 => nil\n  | TyFunApp_cons  κ kl rhk rhkl => (typeToString' needparens n rhk)::(typeList2string needparens n rhkl)\n  end.\n\nDefinition typeToString {Γ}{κ}(ht:HaskType Γ κ) : string :=\n  typeToString' false (length Γ) (ht (fun _ => nat) (count' Γ O)).\n\nInstance TypeToStringInstance {Γ} {κ} : ToString (HaskType Γ κ) :=\n  { toString := typeToString }.\n\nDefinition TBool {Γ} : HaskType Γ ★ := fun TV ite => TyFunApp BoolTyCon _ _ TyFunApp_nil.\nDefinition TInt  {Γ} : HaskType Γ ★ := fun TV ite => TyFunApp IntTyCon  _ _ TyFunApp_nil.\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/HaskStrongTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2789070514829014}}
{"text": "From Coq Require Import Bool List Arith Lia.\nFrom MetaCoq.Template Require Import config utils monad_utils.\nFrom MetaCoq.PCUIC Require Import PCUICGlobalEnv PCUICAst PCUICAstUtils PCUICTactics PCUICInduction PCUICLiftSubst PCUICTyping PCUICEquality PCUICArities PCUICInversion PCUICReduction PCUICSubstitution PCUICConversion PCUICCumulativity PCUICGeneration PCUICWfUniverses PCUICContextConversion PCUICContextSubst PCUICContexts PCUICSpine PCUICWfUniverses PCUICUnivSubst PCUICClosed PCUICInductives PCUICValidity PCUICInductiveInversion PCUICConfluence PCUICWellScopedCumulativity PCUICSR PCUICOnFreeVars PCUICClosedTyp.\nFrom MetaCoq.PCUIC Require Import BDTyping BDToPCUIC BDFromPCUIC.\n\nRequire Import ssreflect ssrbool.\nFrom Equations Require Import Equations.\nRequire Import Equations.Type.Relation Equations.Type.Relation_Properties.\nRequire Import Equations.Prop.DepElim.\n\nImplicit Types (cf : checker_flags) (Σ : global_env_ext).\n\n\nSection BDUnique.\n\nContext `{cf : checker_flags}.\nContext (Σ : global_env_ext).\nContext (wfΣ : wf Σ).\n\nLet Pinfer Γ t T :=\n  wf_local Σ Γ ->\n  forall T', Σ ;;; Γ |- t ▹ T' ->\n  ∑ T'', Σ ;;; Γ ⊢ T ⇝ T'' × Σ ;;; Γ ⊢ T' ⇝ T''.\n\nLet Psort Γ t u :=\n  wf_local Σ Γ ->\n  forall u', Σ ;;; Γ |- t ▹□ u' ->\n  u = u'.\n\nLet Pprod Γ t (na : aname) A B :=\n  wf_local Σ Γ ->\n  forall na' A' B', Σ ;;; Γ |- t ▹Π (na',A',B') ->\n  ∑ A'' B'',\n  [× na = na', Σ ;;; Γ ⊢ A ⇝ A'', Σ ;;; Γ ⊢ A' ⇝ A'',\n      Σ ;;; Γ,, vass na A ⊢ B ⇝ B'' & Σ ;;; Γ,, vass na A' ⊢ B' ⇝ B''].\n\nLet Pind Γ ind t u args :=\n  wf_local Σ Γ ->\n  forall ind' u' args', Σ ;;; Γ |- t ▹{ind'} (u',args') ->\n  ∑ args'',\n  [× ind = ind',\n      u = u',\n      red_terms Σ Γ args args'' &\n      red_terms Σ Γ args' args''].\n\nLet Pcheck (Γ : context) (t T : term) := True.\n\nLet PΓ (Γ : context) := True.\n\nLet PΓ_rel (Γ Γ' : context) := True.\n\nTheorem bidirectional_unique : env_prop_bd Σ Pcheck Pinfer Psort Pprod Pind PΓ PΓ_rel.\nProof using wfΣ.\n\n  apply bidir_ind_env.\n\n  all: intros ; red ; auto.\n  1-9,11-13: intros ? T' ty_T' ; inversion_clear ty_T'.\n  14-17: intros.\n\n  - rewrite H in H0.\n    inversion H0. subst. clear H0.\n    eexists ; split.\n    all: eapply closed_red_refl.\n    2,4: eapply PCUICInversion.nth_error_closed_context.\n    all: fvs.\n\n  - eexists ; split.\n    all: eapply closed_red_refl ; fvs.\n\n  - apply H in X2 => //.\n    apply H0 in X3.\n    2:{ constructor ; auto. now eapply infering_sort_isType. }\n    subst.\n    eexists ; split.\n    all: eapply closed_red_refl ; fvs.\n\n  - apply X1 in X4 as [bty' []].\n    2:{ constructor ; auto. now eapply infering_sort_isType. }\n    exists (tProd n t bty') ; split.\n    all: now eapply closed_red_prod_codom.\n\n  - apply X2 in X6 as [A' []].\n    2:{ constructor ; auto. 2: eapply checking_typing ; tea. all: now eapply infering_sort_isType. }\n    exists (tLetIn n b B A').\n    assert (Σ ;;; Γ |- b : B)\n      by (eapply checking_typing ; tea ; now eapply infering_sort_isType).\n    split.\n    all: eapply closed_red_letin ; tea.\n    all: apply closed_red_refl.\n    all: try now apply wf_local_closed_context.\n    1,3: now eapply subject_is_open_term.\n    all: now eapply type_is_open_term.\n\n  - unshelve epose proof (X0 _ _ _ _ X3) as (A''&B''&[]) ; tea.\n    subst.\n    exists (B''{0 := u}).\n    split.\n    all: eapply (closed_red_subst (Δ := [_]) (Γ' := [])) ; tea.\n    + constructor.\n      1: constructor.\n      rewrite subst_empty.\n      eapply checking_typing ; tea.\n      now eapply isType_tProd, validity, infering_prod_typing.\n    + constructor.\n      1: constructor.\n      rewrite subst_empty.\n      eapply checking_typing ; tea.\n      now eapply isType_tProd, validity, infering_prod_typing.\n\n  - replace decl0 with decl by (eapply declared_constant_inj ; eassumption).\n    eexists ; split.\n    all: eapply closed_red_refl.\n    1,3: fvs.\n    all: rewrite on_free_vars_subst_instance.\n    all: now eapply closed_on_free_vars, declared_constant_closed_type.\n\n  - replace idecl0 with idecl by (eapply declared_inductive_inj ; eassumption).\n    eexists ; split.\n    all: eapply closed_red_refl.\n    1,3: fvs.\n    all: rewrite on_free_vars_subst_instance.\n    all: now eapply closed_on_free_vars, declared_inductive_closed_type.\n\n  - replace cdecl0 with cdecl by (eapply declared_constructor_inj ; eassumption).\n    replace mdecl0 with mdecl by (eapply declared_constructor_inj ; eassumption).\n    eexists ; split.\n    all: eapply closed_red_refl.\n    1,3: fvs.\n    all: now eapply closed_on_free_vars, declared_constructor_closed_type.\n\n  - eapply declared_projection_inj in H as (?&?&?&?); tea.\n    subst.\n    move: (X2) => tyc'.\n    eapply X0 in X2 as [args'' []] ; tea.\n    eapply infering_ind_typing in X ; tea.\n    eapply infering_ind_typing in tyc' ; tea.\n    subst.\n    exists (subst0 (c :: List.rev args'') (proj_type pdecl)@[u0]).\n    split.\n    + eapply closed_red_red_subst0 ; tea.\n      3: eapply subslet_untyped_subslet, projection_subslet ; tea.\n      * eapply is_closed_context_weaken.\n        1: fvs.\n        eapply wf_local_closed_context, wf_projection_context ; tea.\n        now eapply validity, isType_mkApps_Ind_proj_inv in X as [].\n      * constructor.\n        2: now apply All2_rev.\n        apply closed_red_refl.\n        1: fvs.\n        now eapply subject_is_open_term.\n      * now eapply validity.\n      * rewrite on_free_vars_subst_instance.\n        move: (H1) => H.\n        eapply declared_projection_closed in H; eauto.\n        rewrite (declared_minductive_ind_npars H1) in H.\n        cbn in H. len.\n        rewrite closedn_on_free_vars //.\n        eapply closed_upwards; tea. cbn. lia.\n    + eapply closed_red_red_subst0 ; tea.\n      3: eapply subslet_untyped_subslet, projection_subslet ; tea.\n      * eapply is_closed_context_weaken.\n        1: fvs.\n        eapply wf_local_closed_context, wf_projection_context ; tea.\n        now eapply validity, isType_mkApps_Ind_proj_inv in X as [].\n      * constructor.\n        2: now apply All2_rev.\n        apply closed_red_refl.\n        1: fvs.\n        now eapply subject_is_open_term.\n      * now eapply validity.\n      * rewrite on_free_vars_subst_instance.\n        move: (H1) => H.\n        eapply declared_projection_closed in H; eauto.\n        rewrite (declared_minductive_ind_npars H1) in H.\n        cbn in H. len.\n        rewrite closedn_on_free_vars //.\n        eapply closed_upwards; tea. cbn. lia.\n\n  - rewrite H3 in H0 ; injection H0 as ->.\n    eapply nth_error_all in X as (?&[]); tea.\n    eexists ; split.\n    all: eapply closed_red_refl.\n    1,3:fvs.\n    all: now eapply subject_is_open_term, infering_sort_typing.\n\n  - rewrite H3 in H0 ; injection H0 as ->.\n    eapply nth_error_all in X as (?&[]); tea.\n    eexists ; split.\n    all: eapply closed_red_refl.\n    1,3:fvs.\n    all: now eapply subject_is_open_term, infering_sort_typing.\n\n  - intros ? T' ty_T'.\n    inversion ty_T' ; subst.\n    move: (H) => /declared_inductive_inj /(_ H13) [? ?].\n    subst.\n    assert (op' : is_open_term Γ (mkApps ptm0 (skipn (ci_npar ci) args0 ++ [c]))).\n      by now eapply type_is_open_term, infering_typing.\n    move: op'.\n    rewrite on_free_vars_mkApps => /andP [optm' oargs'].\n    eapply X0 in X9 as [args'' []] ; tea.\n    subst.\n    eexists (mkApps ptm ((skipn (ci_npar ci) args'') ++ [c])).\n    split.\n    + eapply into_closed_red.\n      * eapply red_mkApps.\n        1: reflexivity.\n        eapply All2_app.\n        2: now constructor.\n        eapply All2_skipn, All2_impl ; tea.\n        intros ? ? r.\n        now apply r.\n      * fvs.\n      * eapply type_is_open_term, infering_typing ; tea.\n        now econstructor.\n    + eapply into_closed_red.\n      * eapply red_mkApps.\n        1: reflexivity.\n        eapply All2_app.\n        2: now constructor.\n        eapply All2_skipn, All2_impl ; tea.\n        intros ? ? r.\n        now apply r.\n      * fvs.\n      * now eapply type_is_open_term, infering_typing.\n\n  - inversion X1; subst.\n    rewrite H in H2; noconf H2.\n    have eq := (declared_constant_inj _ _ H0 H3); subst cdecl0.\n    exists (tConst prim_ty []).\n    split; eapply closed_red_refl; fvs.\n\n  - inversion X3 ; subst.\n    eapply X0 in X4 as [T'' []]; subst ; tea.\n    eapply into_closed_red in X1 ; fvs.\n    eapply into_closed_red in X5 ; fvs.\n    eapply closed_red_confluence in X5 as [? [? ru']]; tea.\n    eapply invert_red_sort in ru' ; subst.\n    eapply closed_red_confluence in X1 as [? [ru' ru]].\n    2: now etransitivity.\n    eapply invert_red_sort in ru ; subst.\n    eapply invert_red_sort in ru'.\n    now congruence.\n\n  - inversion X3 ; subst.\n    eapply X0 in X4 as [T'' []]; subst ; tea.\n    eapply into_closed_red in X1 ; fvs.\n    eapply into_closed_red in X5 ; fvs.\n    eapply closed_red_confluence in X5 as [? [? rA']]; tea.\n    eapply invert_red_prod in rA' as (?&B0&[]); subst.\n    eapply closed_red_confluence in X1 as [? [rA' rA]].\n    2: now etransitivity.\n    eapply invert_red_prod in rA as (?&?&[]); subst.\n    eapply invert_red_prod in rA' as (A''&B''&[]) ; subst.\n    injection e as -> -> ->.\n    exists A'', B'' ; split ; tea.\n    1: reflexivity.\n    1: now etransitivity.\n    etransitivity ; tea.\n    eapply red_red_ctx_inv' ; tea.\n    constructor.\n    1: eapply closed_red_ctx_refl ; fvs.\n    now constructor.\n\n  - inversion X3 ; subst.\n    eapply X0 in X4 as [T'' []]; subst ; tea.\n    eapply into_closed_red in X1 ; fvs.\n    eapply into_closed_red in X5 ; fvs.\n    eapply closed_red_confluence in X5 as [? [? rind']]; tea.\n    eapply invert_red_mkApps_tInd in rind' as [? []]; subst.\n    eapply closed_red_confluence in X1 as [? [rind' rind]].\n    2: now etransitivity.\n    eapply invert_red_mkApps_tInd in rind as [? []]; subst.\n    eapply invert_red_mkApps_tInd in rind' as [args'' [e ]]; subst.\n    eapply mkApps_notApp_inj in e as [e ->].\n    2-3: easy.\n    injection e as <- <-.\n    exists args'' ; split ; auto.\n    eapply All2_trans ; tea.\n    eapply closed_red_trans.\nQed.\n\nEnd BDUnique.\n\nTheorem infering_unique `{checker_flags} {Σ} (wfΣ : wf Σ) {Γ} (wfΓ : wf_local Σ Γ) {t T T'} :\n  Σ ;;; Γ |- t ▹ T -> Σ ;;; Γ |- t ▹ T' ->\n  ∑ T'', Σ ;;; Γ ⊢ T ⇝ T'' × Σ ;;; Γ ⊢ T' ⇝ T''.\nProof.\n  intros ty ty'.\n  now eapply bidirectional_unique in ty'.\nQed.\n\nTheorem infering_unique' `{checker_flags} {Σ} (wfΣ : wf Σ) {Γ} (wfΓ : wf_local Σ Γ) {t T T'} :\n  Σ ;;; Γ |- t ▹ T -> Σ ;;; Γ |- t ▹ T' ->\n  Σ ;;; Γ ⊢ T = T'.\nProof.\n  intros ty ty'.\n  eapply bidirectional_unique in ty as [? []]; tea.\n  etransitivity.\n  2: symmetry.\n  all: now eapply red_ws_cumul_pb.\nQed.\n\nTheorem infering_checking `{checker_flags} {Σ} (wfΣ : wf Σ) {Γ} (wfΓ : wf_local Σ Γ) {t T T'} :\n  is_open_term Γ T' -> Σ ;;; Γ |- t ▹ T -> Σ ;;; Γ |- t ◃ T' -> Σ ;;; Γ ⊢ T ≤ T'.\nProof.\n  intros ? ty ty'.\n  depelim ty'.\n  eapply infering_unique' in ty ; tea.\n  etransitivity ; last first.\n  - apply into_ws_cumul_pb ; tea.\n    1: fvs.\n    now eapply type_is_open_term, infering_typing.\n  - now eapply ws_cumul_pb_eq_le.\nQed.\n\nTheorem infering_sort_sort `{checker_flags} {Σ} (wfΣ : wf Σ) {Γ} (wfΓ : wf_local Σ Γ) {t u u'} :\n  Σ ;;; Γ |- t ▹□ u -> Σ ;;; Γ |- t ▹□ u' -> u = u'.\nProof.\n  intros ty ty'.\n  now eapply bidirectional_unique in ty'.\nQed.\n\nTheorem infering_sort_infering `{checker_flags} {Σ} (wfΣ : wf Σ)\n  {Γ} {wfΓ : wf_local Σ Γ} {t u T} :\n  Σ ;;; Γ |- t ▹□ u -> Σ ;;; Γ |- t ▹ T ->\n  Σ ;;; Γ ⊢ T ⇝ tSort u.\nProof.\n  intros ty ty'.\n  depelim ty.\n  eapply into_closed_red in r.\n  2: fvs.\n  2: now eapply type_is_open_term, infering_typing.\n  eapply bidirectional_unique in i as [T'' []]; tea.\n  eapply closed_red_confluence in r as [? [? ru]]; tea.\n  eapply invert_red_sort in ru ; subst.\n  now etransitivity.\nQed.\n\nTheorem infering_prod_prod `{checker_flags} {Σ} (wfΣ : wf Σ)\n  {Γ} (wfΓ : wf_local Σ Γ) {t na na' A A' B B'} :\n  Σ ;;; Γ |- t ▹Π (na,A,B) -> Σ ;;; Γ |- t ▹Π (na',A',B') ->\n  ∑ A'' B'',\n  [× na = na', Σ ;;; Γ ⊢ A ⇝ A'', Σ ;;; Γ ⊢ A' ⇝ A'',\n      Σ ;;; Γ,, vass na A ⊢ B ⇝ B'' & Σ ;;; Γ,, vass na A' ⊢ B' ⇝ B''].\nProof.\n  intros ty ty'.\n  now eapply bidirectional_unique in ty'.\nQed.\n\nTheorem infering_prod_prod' `{checker_flags} {Σ} (wfΣ : wf Σ)\n  {Γ} (wfΓ : wf_local Σ Γ) {t na na' A A' B B'} :\n  Σ ;;; Γ |- t ▹Π (na,A,B) -> Σ ;;; Γ |- t ▹Π (na',A',B') ->\n  [× na = na', Σ ;;; Γ ⊢ A = A' & Σ ;;; Γ,, vass na A ⊢ B = B'].\nProof.\n  intros ty ty'.\n  eapply infering_prod_prod in ty as (A''&B''&[]); tea.\n  subst.\n  assert (Σ ;;; Γ ⊢ A = A').\n  {\n    etransitivity.\n    2: symmetry.\n    all: now eapply red_ws_cumul_pb.\n  }\n  split ; auto.\n  etransitivity.\n  1: now eapply red_ws_cumul_pb.\n  symmetry.\n  eapply ws_cumul_pb_ws_cumul_ctx.\n  2: now eapply red_ws_cumul_pb.\n  constructor.\n  1: eapply ws_cumul_ctx_pb_refl ; fvs.\n  now constructor.\nQed.\n\nTheorem infering_prod_infering `{checker_flags} {Σ} (wfΣ : wf Σ)\n  {Γ} (wfΓ : wf_local Σ Γ) {t na A B T} :\n  Σ ;;; Γ |- t ▹Π(na,A,B) ->\n  Σ ;;; Γ |- t ▹ T ->\n  ∑ A' B', [× Σ ;;; Γ ⊢ T ⇝ tProd na A' B',\n    Σ ;;; Γ ⊢ A ⇝ A' &\n    Σ ;;; Γ,, vass na A ⊢ B ⇝ B'].\nProof.\n  intros ty ty'.\n  depelim ty.\n  eapply into_closed_red in r.\n  2: fvs.\n  2: now eapply type_is_open_term, infering_typing.\n  eapply bidirectional_unique in i as [? []]; tea.\n  eapply closed_red_confluence in r as [? [? rA']]; tea.\n  eapply invert_red_prod in rA' as (A'&B'&[]); subst.\n  exists A', B' ; split ; tea.\n  now etransitivity.\nQed.\n\nTheorem infering_ind_ind `{checker_flags} {Σ} (wfΣ : wf Σ)\n  {Γ} (wfΓ : wf_local Σ Γ) {t ind ind' u u' args args'} :\n  Σ ;;; Γ |- t ▹{ind} (u,args) -> Σ ;;; Γ |- t ▹{ind'} (u',args') ->\n  ∑ args'',\n    [× ind = ind', u = u',\n      red_terms Σ Γ args args'' &\n      red_terms Σ Γ args' args''].\nProof.\n  intros ty ty'.\n  now eapply bidirectional_unique in ty'.\nQed.\n\nTheorem infering_ind_ind' `{checker_flags} {Σ} (wfΣ : wf Σ)\n  {Γ} (wfΓ : wf_local Σ Γ) {t ind ind' u u' args args'} :\n  Σ ;;; Γ |- t ▹{ind} (u,args) -> Σ ;;; Γ |- t ▹{ind'} (u',args') ->\n    [× ind = ind', u = u' &\n      ws_cumul_pb_terms Σ Γ args args'].\nProof.\n  intros ty ty'.\n  eapply bidirectional_unique in ty as [args'' []] ; tea.\n  subst.\n  split ; auto.\n  etransitivity.\n  2: symmetry.\n  all: now eapply red_terms_ws_cumul_pb_terms.\nQed.\n\nTheorem infering_ind_infering `{checker_flags} {Σ} (wfΣ : wf Σ)\n  {Γ} (wfΓ : wf_local Σ Γ) {t ind u args T} :\n  Σ ;;; Γ |- t ▹{ind} (u,args) ->\n  Σ ;;; Γ |- t ▹ T ->\n  ∑ args',\n    Σ ;;; Γ ⊢ T ⇝ mkApps (tInd ind u) args' ×\n      red_terms Σ Γ args args'.\nProof.\n  intros ty ty'.\n  depelim ty.\n  eapply into_closed_red in r.\n  2: fvs.\n  2: now eapply type_is_open_term, infering_typing.\n  eapply bidirectional_unique in i as [? []]; tea.\n  eapply closed_red_confluence in r as [? [? rind]]; tea.\n  eapply invert_red_mkApps_tInd in rind as [args' []]; subst.\n  exists args' ; split ; tea.\n  now etransitivity.\nQed.\n\nCorollary principal_type `{checker_flags} {Σ} (wfΣ : wf Σ) {Γ t T} :\n  Σ ;;; Γ |- t : T ->\n  ∑ T',\n    (forall T'', Σ ;;; Γ |- t : T'' -> Σ ;;; Γ ⊢ T' ≤ T'') × Σ ;;; Γ |- t : T'.\nProof.\n  intros ty.\n  assert (wf_local Σ Γ) by (pcuic; eapply typing_wf_local; eauto).\n  apply typing_infering in ty as (S & infS & _); auto.\n  exists S.\n  repeat split.\n  2: by apply infering_typing.\n  intros T' ty.\n  eapply typing_infering in ty as (S' & infS' & cum'); auto.\n  etransitivity ; eauto.\n  now eapply ws_cumul_pb_eq_le, infering_unique'.\nQed.\n\n\n\n\n\n\n\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/Bidirectional/BDUnique.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2788922931629974}}
{"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\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.\n\nRequire Export StaticSemanticsWellFormednessLemmas.\nRequire Export StaticSemanticsHeapObjectsLemmas.\n\nLemma A_2_Term_Weakening_1 :\n  forall (d: Delta) (u u' : Upsilon) (g g' : Gamma)\n         (x : EVar) (p p' : P) (tau tau' : Tau),\n    WFC d (u ++ u') (g ++ g') ->\n    gettype u x p tau p' tau' ->\n    gettype (u ++ u') x p tau p' tau'.\nProof.\n  intros d u u' g g' x p p' tau tau'.\n  intros WFCd.\n  intros gettypeder.\n  gettype_ind_cases (induction gettypeder) Case.\n  Case \"gettype u x p tau [] tau\".\n   constructor.\n  Case \"gettype u x p (cross t0 t1) (i_pe zero_pe :: p') tau\".\n   constructor.\n   apply IHgettypeder in WFCd.\n   assumption.\n  Case \"gettype u x p (cross t0 t1) (i_pe one_pe :: p') tau\".\n   constructor.\n   apply IHgettypeder in WFCd.\n   assumption.\n  Case \"gettype u x p (etype aliases alpha k tau') (u_pe :: p') tau)\".\n   apply IHgettypeder in WFCd.\n   apply gettype_etype with (tau'':= tau'').\n   apply getU_Some_Weakening. \n   assumption.\n   assumption.\nQed.\n\n(* What is really breaking this is the K [] t A which comes from the\n   typing of the term but I need down in the strengthening. *)\n(* TODO let, open, openstar and function application. *)\nLemma A_2_Term_Weakening_2:\n  forall (d: Delta) (u : Upsilon) (g : Gamma)  (e : E) (tau : Tau),\n    ltyp d u g e tau ->\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 tau.\nProof.\n  intros d u g e tau ltypder.\n  apply (ltyp_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  (* OKay this works, modulo alpha conversion but the case is a \n      repetitive mess. *)\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)).\n   constructor; try assumption.\n   constructor; try assumption.\n   inversion H1; try assumption.\n   inversion H3; try assumption.\n   apply WFU_strengthening in H12; try assumption.\n   apply H with (u':= u') (g':= g') in Z; try assumption.\n   constructor; try assumption.\n   apply WFDG_xt.\n   AdmitAlphaConversion.\n   assumption.\n   apply H0 with (u':= u') (g':= g') in H1; try assumption.\n   inversion H3.\n   assumption.\n   inversion H3; try assumption.\n   apply H0 with (u':= u') (g':= g') in H1; try assumption.\n  Case \"styp_open_3_7\".\n   intros.\n   inversion H1.\n   inversion H2.\n   crush.\n   apply styp_open_3_7 with (p:= p) (k:= k) (tau':= tau'); try assumption.\n   AdmitAlphaConversion.\n   apply H16 in H2; try assumption.\n   apply H0; try assumption.\n   constructor; try assumption.\n   constructor; try assumption.\n   constructor; try assumption.\n   (*  K ((alpha, k) :: d0) tau' A *)\n   admit. (* Don't know where to get this K, it's coming from the pack that is e0. *)\n   constructor; try assumption.\n   constructor; try assumption.\n   constructor; try assumption.   \n   constructor; try assumption.   \n   constructor; try assumption.   \n   constructor; try assumption.      \n   constructor; try assumption.   \n   AdmitAlphaConversion.\n   (*  K ((alpha, k) :: d0) tau' A *) \n   admit. (* Don't know where to get this K. *)\n   constructor; try assumption.\n   (* WFDG d0 (g0 ++ g') given WFDG d0 g0 *)\n   admit. (* WFDG strengthening. *)\n   (* What do I have here to make a WFDG true ? *)\n   inversion H3; try assumption.\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  (* TODO two cases and then I'm done without rtype weakening. *)\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   intros.\n   admit.\n  Case \"base\".\n   assumption.\nQed.\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        WFC d (u ++ u') (g ++ g') ->\n        rtyp d (u ++ u') (g ++ g') e tau.\nProof.\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*)\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        WFC d (u ++ u') (g ++ g') ->\n        styp d (u ++ u') (g ++ g') tau s.\nProof.\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/3/TermWeakeningProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.27889229316299735}}
{"text": "(** * Extraction of a counter contract with refinement types to Midlang *)\n\n(** The contract uses refinement types to specify some functional correctness properties *)\nFrom ConCert.Execution Require Import Blockchain.\nFrom ConCert.Execution Require Import Serializable.\nFrom ConCert.Extraction Require Import Common.\nFrom ConCert.Extraction Require Import ElmExtract.\nFrom ConCert.Extraction Require Import PrettyPrinterMonad.\nFrom MetaCoq.TypedExtraction Require Import Extraction.\nFrom MetaCoq.TypedExtraction Require Import ResultMonad.\nFrom MetaCoq.Template Require Import Kernames.\nFrom MetaCoq.Template Require Import All.\nFrom Coq Require Import List.\nFrom Coq Require Import Lia.\nFrom Coq Require Import String.\nFrom Coq Require Import ZArith.\n\nImport MCMonadNotation.\nOpen Scope string.\n\n#[local]\nInstance MidlangBoxes : ElmPrintConfig :=\n  {| term_box_symbol := \"()\";\n     type_box_symbol := \"()\";\n     any_type_symbol := \"()\";\n     false_elim_def := \"false_rec ()\";\n     print_full_names := false |}.\n\nDefinition midlang_translation_map :=\n  [(<%% @current_slot %%>, \"current_slot\");\n  (<%% @address_eqb %%>, \"address_eq\");\n  (<%% @ctx_amount %%>, \"amount\");\n  (<%% @ctx_from %%>, \"from\");\n  (<%% @Chain %%>, \"ConCertChain\");\n  (<%% @ContractCallContext %%>, \"ConCertCallContext\");\n  (<%% @ConCert.Execution.Blockchain.ActionBody %%>, \"ConCertAction\");\n  (<%% @ChainBase %%>, \"ChainBaseWTF\");\n  (<%% @ctx_contract_address %%>, \"contract_address\")].\n\nDefinition midlang_translate (name : kername) : option string :=\n  match find (fun '(key, _) => eq_kername key name) midlang_translation_map with\n  | Some (_, val) => Some val\n  | None => None\n  end.\n\nModule CounterRefinmentTypes.\n\n  Open Scope Z.\n  Definition storage := Z.\n\n  Inductive msg := Inc (_ : Z) | Dec (_ : Z).\n\n  Program Definition inc_counter (st : storage) (inc : {z : Z | 0 <? z}) :\n    {new_st : storage | st <? new_st} :=\n    st + proj1_sig inc.\n  Next Obligation.\n    unfold is_true in *.\n    rewrite <- Zlt_is_lt_bool in *; lia.\n  Qed.\n\n\n  Program Definition dec_counter (st : storage) (dec : {z : Z | 0 <? z}) :\n    {new_st : storage | new_st <? st} :=\n    st - proj1_sig dec.\n  Next Obligation.\n    unfold is_true in *.\n    rewrite <- Zlt_is_lt_bool in *; lia.\n  Qed.\n\n  Definition my_bool_dec := Eval compute in Bool.bool_dec.\n\n  Inductive SimpleActionBody :=\n  | Act_transfer : nat -> Z -> SimpleActionBody.\n\n  Definition Transaction := list SimpleActionBody.\n  Definition Transaction_none : Transaction := [].\n\n  Definition counter (msg : msg) (st : storage)\n    : option (Transaction * storage) :=\n    match msg with\n    | Inc i =>\n      match (my_bool_dec (0 <? i) true) with\n      | left h => Some (Transaction_none, proj1_sig (inc_counter st (exist i h)))\n      | right _ => None\n      end\n    | Dec i =>\n      match (my_bool_dec (0 <? i) true) with\n      | left h => Some (Transaction_none, proj1_sig (dec_counter st (exist i h)))\n      | right _ => None\n      end\n    end.\nEnd CounterRefinmentTypes.\n\nMetaCoq Run\n        (p <- tmQuoteRecTransp (CounterRefinmentTypes.counter) false;;\n        tmDefinition \"counter_env\"%bs p.1).\n\nDefinition counter_name := <%% CounterRefinmentTypes.counter %%>.\n\n\n(** A translation table for various constants we want to rename *)\n\nDefinition TT : list (kername * string) := Eval compute in\n  [   remap <%% Z.add %%> \"add\"\n    ; remap <%% Z.sub %%> \"sub\"\n    ; remap <%% Z.leb %%> \"le\"\n    ; remap <%% Z.ltb %%> \"lt\"\n    ; remap <%% Z %%> \"Int\"\n    ; ((<%% Z %%>.1, \"Z0\"%bs),\"0\")\n    ; remap <%% nat %%> \"AccountAddress\"\n    ; remap <%% CounterRefinmentTypes.Transaction %%> \"Transaction\"\n    ; remap <%% CounterRefinmentTypes.Transaction_none %%> \"Transaction.none\"\n    ; remap <%% bool %%> \"Bool\" ].\n\nDefinition midlang_counter_translate (name : kername) : option string :=\n  match find (fun '(key, _) => eq_kername key name) (TT ++ midlang_translation_map) with\n  | Some (_, val) => Some val\n  | None => None\n  end.\n\nDefinition ignored_concert_types :=\n  Eval compute in\n        [<%% @ActionBody %%>;\n         <%% @Address %%>;\n         <%% @Amount %%>;\n         <%% @ChainBase %%>;\n         <%% @Chain %%>;\n         <%% @ContractCallContext %%>;\n         <%% @SerializedValue %%>].\n\n\nDefinition counter_extract :=\n    Eval vm_compute in\n    extract_template_env_within_coq\n      counter_env\n      (KernameSet.singleton counter_name)\n      (fun kn => List.existsb (eq_kername kn)\n                              (ignored_concert_types\n                                 ++ map fst midlang_translation_map\n                                 ++ map fst TT)).\n\nDefinition counter_result := Eval compute in\n     (env <- counter_extract ;;\n      '(_, lines) <- finish_print_lines (print_env env midlang_counter_translate);;\n      ret lines).\n\nDefinition wrap_in_delimiters s :=\n  concat Common.nl [\"\"; \"{-START-} \"; s; \"{-END-}\"].\n\nDefinition midlang_prelude :=\n   [\"import Basics exposing (..)\";\n    \"import Blockchain exposing (..)\";\n    \"import Bool exposing (..)\";\n    \"import Int exposing (..)\";\n    \"import Maybe exposing (..)\";\n    \"import Order exposing (..)\";\n    \"import Transaction exposing (..)\";\n    \"import Tuple exposing (..)\"].\n\nMetaCoq Run (match counter_result with\n             | Ok s => tmMsg \"Extraction of counter succeeded\"%bs\n             | Err err => tmFail (String.of_string err)\n             end).\n\nDefinition midlang_counter :=\n  match counter_result with\n  | Ok s => monad_map tmMsg (map String.of_string (midlang_prelude ++ s))\n  | Err s => tmFail (String.of_string s)\n  end.\n\nRedirect \"../extraction/tests/extracted-code/midlang-extract/CounterRefTypesMidlang.midlang\"\n  MetaCoq Run midlang_counter.\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/counter/extraction/CounterRefTypesMidlang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.27889229316299735}}
{"text": "Require Import Coqlib.\nRequire Import ITreelib.\nRequire Import ImpPrelude.\nRequire Import STS.\nRequire Import Behavior.\nRequire Import ModSem.\nRequire Import Skeleton.\nRequire Import IntroHeader.\n\nSet Implicit Arguments.\n\n\n(***\nF.f(n) {\n  if (n < 0) {\n    r := -1\n  } else if (n == 0) {\n    r := ...\n  } else {\n    r := 5 * Ncall P Q G.g(n)\n  }\n  r\n}\n***)\n\nSection PROOF.\n\n  Definition fF: list val -> itree Es val :=\n    fun varg =>\n      `n: Z <- (pargs [Tint] varg)?;;\n      assume (intrange_64 n);;;\n      if (n <? 0)%Z\n      then `_: val <- ccallU \"log\" [Vint n];; Ret (Vint (- 1))\n      else if (n =? 0)%Z\n           then Ret (Vint 0)\n           else r <- (Ncall True (fun r => r = Vint (5 * n - 2)) \"g\" [Vint n]);;\n                res <- (vadd (Vint 2) r)?;;\n                Ret res\n  .\n\n  (* Definition Ncall {X Y} (f: string) (x: X): itree Es Y := *)\n  (*   `b: bool <- trigger (Choose bool);; *)\n  (*   if b then ccallU f x else trigger (Choose _) *)\n  (* . *)\n\n  (* Definition fF: list val -> itree Es val := *)\n  (*   fun varg => *)\n  (*     `n: Z <- (pargs [Tint] varg)?;; *)\n  (*     assume (intrange_64 n);;; *)\n  (*     assume ((Z.to_nat n) < max);;; *)\n  (*     if (n <? 0)%Z *)\n  (*     then `_: val <- ccallU \"log\" [Vint n];; Ret (Vint (- 1)) *)\n  (*     else if (n =? 0)%Z *)\n  (*          then Ret (Vint 0) *)\n  (*          else (Ncall \"g\" [Vint n]) *)\n  (* . *)\n\n  Definition FSem: ModSem.t := {|\n    ModSem.fnsems := [(\"f\", cfunU fF)];\n    ModSem.mn := \"F\";\n    ModSem.initial_st := tt↑;\n  |}\n  .\n\n  Definition F: Mod.t := {|\n    Mod.get_modsem := fun _ => FSem;\n    Mod.sk := [(\"f\", Sk.Gfun)];\n  |}\n  .\n\nEnd PROOF.\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/IntroF0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.2788922931629973}}
{"text": "(** * A box to decrypt data (part of TCB) *)\nRequire Import Coq.Program.Basics Coq.Strings.String.\nRequire Import FunctionApp EncryptionInterface.\n\nLocal Open Scope program_scope.\n\nSet Implicit Arguments.\n\n(** ** Summary\n\n    We implement a box that decrypts data:\n\n<<\n                      ┌─────────┐\n    encrypted data in │         │\n    ----------------> │         │ unencrypted data out\n                      │ Decrypt │ -------------------->\n    set master key    │   Box   │\n    ----------------> │         │\n                      │         │\n                      └─────────┘\n\n>> *)\n\nModule TrustedDecryptBox (DataTypes : EncryptionDataTypes) (Algorithm : EncryptionAlgorithm DataTypes).\n  Import DataTypes.\n\n  Section trustedDecryptBox.\n    (** Because the box is asynchronous, we enable tagging data with\n        identifiers.  The identifiers are passed unchanged with the\n        encrypted data. *)\n\n    Variable dataTagT : Type.\n\n    Record DecryptBoxState :=\n      { masterKey : option { key : masterKeyT | Algorithm.isValidMasterKey key = true } }.\n\n    Inductive dbInput :=\n    | dbSetMasterKey (key : masterKeyT)\n    | dbDecrypt (encryptedData : encryptedDataT) (tag : dataTagT).\n\n    Inductive dbErrorOutput :=\n    | dbErrorInvalidData (data : encryptedDataT) (tag : dataTagT)\n    | dbErrorInvalidMasterKey (key : masterKeyT) (pf : Algorithm.isValidMasterKey key = false)\n    | dbErrorNoMasterKey.\n\n    Inductive dbEventOutput :=\n    | dbDecrypted (data : rawDataT) (tag : dataTagT).\n\n    Definition dbOutput := (dbErrorOutput + dbEventOutput)%type.\n\n    Context (world : Type)\n            (handle : dbOutput -> action world).\n\n    Definition initState : DecryptBoxState :=\n      {| masterKey := None |}.\n\n    Definition decryptBoxLoopPreBody\n               (st : DecryptBoxState)\n    : dbInput -> option dbOutput * DecryptBoxState\n      := fun i =>\n           match i with\n\n             | dbSetMasterKey key\n               => match Sumbool.sumbool_of_bool (Algorithm.isValidMasterKey key) with\n                    | left pf => (None,\n                                  {| masterKey := Some (exist _ key pf) |})\n                    | right pf => (Some (inl (@dbErrorInvalidMasterKey key pf)),\n                                   {| masterKey := None |})\n                  end\n             | dbDecrypt data tag\n               => (match st.(masterKey) with\n                     | None => Some (inl dbErrorNoMasterKey)\n                     | Some (exist key pf)\n                       => match Algorithm.decrypt key pf data with\n                            | inl rawData => Some (inr (dbDecrypted rawData tag))\n                            | inr InvalidEncryptedData => Some (inl (dbErrorInvalidData data tag))\n                          end\n                   end,\n                   st)\n           end.\n\n    Definition decryptBoxLoopBody {T}\n               (decryptBoxLoop : DecryptBoxState -> T)\n               (st : DecryptBoxState)\n    : dbInput -> action world * T\n      := fun i => let outs := fst (decryptBoxLoopPreBody st i) in\n                  (match outs with\n                     | None => id\n                     | Some out => handle out\n                   end,\n                   decryptBoxLoop (snd (decryptBoxLoopPreBody st i))).\n\n    CoFixpoint decryptBoxLoop (st : DecryptBoxState) :=\n      Step (decryptBoxLoopBody decryptBoxLoop st).\n\n    Definition decryptBox : process _ _ := decryptBoxLoop initState.\n  End trustedDecryptBox.\nEnd TrustedDecryptBox.\n", "meta": {"author": "JasonGross", "repo": "apps", "sha": "906b9ca6f3f53e3a37a9a487a9289959f5167ba2", "save_path": "github-repos/coq/JasonGross-apps", "path": "github-repos/coq/JasonGross-apps/apps-906b9ca6f3f53e3a37a9a487a9289959f5167ba2/TrustedDecryptBox.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2788473108029954}}
{"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 map.Map.\n\n(* Why3 assumption *)\nDefinition unit  := unit.\n\n(* Why3 assumption *)\nInductive ref (a:Type) {a_WT:WhyType a} :=\n  | mk_ref : a -> ref a.\nAxiom ref_WhyType : forall (a:Type) {a_WT:WhyType a}, WhyType (ref a).\nExisting Instance ref_WhyType.\nImplicit Arguments mk_ref [[a] [a_WT]].\n\n(* Why3 assumption *)\nDefinition contents {a:Type} {a_WT:WhyType a}(v:(ref a)): a :=\n  match v with\n  | (mk_ref x) => x\n  end.\n\nAxiom pointer : Type.\nParameter pointer_WhyType : WhyType pointer.\nExisting Instance pointer_WhyType.\n\nAxiom pointer_dec : forall (p1:pointer) (p2:pointer), (p1 = p2) \\/\n  ~ (p1 = p2).\n\n(* Why3 assumption *)\nDefinition next  := (map.Map.map pointer pointer).\n\nParameter null: pointer.\n\n(* Why3 assumption *)\nInductive is_list : (map.Map.map pointer pointer) -> pointer -> Prop :=\n  | is_list_null : forall (next1:(map.Map.map pointer pointer)) (p:pointer),\n      (p = null) -> (is_list next1 p)\n  | is_list_next : forall (next1:(map.Map.map pointer pointer)) (p:pointer),\n      (~ (p = null)) -> ((is_list next1 (map.Map.get next1 p)) ->\n      (is_list next1 p)).\n\nAxiom ft : forall (a:Type) {a_WT:WhyType a}, Type.\nParameter ft_WhyType : forall (a:Type) {a_WT:WhyType a}, WhyType (ft a).\nExisting Instance ft_WhyType.\n\nParameter in_ft: pointer -> (ft pointer) -> Prop.\n\nAxiom set_eq : forall (ft1:(ft pointer)) (ft2:(ft pointer)),\n  (forall (q:pointer), (in_ft q ft1) <-> (in_ft q ft2)) -> (ft1 = ft2).\n\nParameter list_ft: (map.Map.map pointer pointer) -> pointer -> (ft pointer).\n\nAxiom list_ft_node_null_cor : forall (next1:(map.Map.map pointer pointer))\n  (q:pointer) (p:pointer), (q = null) -> ~ (in_ft p (list_ft next1 q)).\n\nAxiom list_ft_node_next1 : forall (next1:(map.Map.map pointer pointer))\n  (q:pointer) (p:pointer), (~ (q = null)) -> ((is_list next1\n  (map.Map.get next1 q)) -> ((in_ft p (list_ft next1 (map.Map.get next1\n  q))) -> (in_ft p (list_ft next1 q)))).\n\nAxiom list_ft_node_next2 : forall (next1:(map.Map.map pointer pointer))\n  (q:pointer), (~ (q = null)) -> ((is_list next1 (map.Map.get next1 q)) ->\n  (in_ft q (list_ft next1 q))).\n\nAxiom list_ft_node_next_inv : forall (next1:(map.Map.map pointer pointer))\n  (q:pointer) (p:pointer), (~ (q = null)) -> ((is_list next1\n  (map.Map.get next1 q)) -> ((~ (q = p)) -> ((in_ft p (list_ft next1 q)) ->\n  (in_ft p (list_ft next1 (map.Map.get next1 q)))))).\n\n(* Why3 goal *)\nTheorem frame_list : forall (next1:(map.Map.map pointer pointer)) (p:pointer)\n  (q:pointer) (v:pointer), (~ (in_ft q (list_ft next1 p))) -> ((is_list next1\n  p) -> (is_list (map.Map.set next1 q v) p)).\nProof.\nintros.\ninduction H0.\napply (is_list_null _ _ H0).\napply (is_list_next _ _ H0).\nassert (q<>p) by (intro eq;apply H;rewrite eq;clear eq;apply (list_ft_node_next2 _ _ H0 H1)).\nrewrite (Map.Select_neq _ _ _ _ H2).\napply IHis_list.\ncontradict H.\nexact (list_ft_node_next1 _ _ _ H0 H1 H).\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/in_progress/list_rev/list_rev_M2_frame_list_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.27884730390713}}
{"text": "From synrl Require Import Preamble Coequalizer.\n\nSet Primitive Projections.\n\nClass Modal (P : Type → Prop) (A : Type) : Prop :=\n  mod : P A.\n\nDefinition connected (P : Type → Prop) (A : Type) : Prop :=\n  ∀ B, Modal P B → @is_isomorphism B (A → B) const.\n\n\nClass RepleteSubuniverse (P : Type → Prop) :=\n  replete : ∀ A B (f : A → B), is_isomorphism f → P A → P B.\n\nArguments replete P {_} A [B] f iso : rename.\n\nClass LexSubuniverse P : Prop :=\n  {connected_eq : ∀ A, connected P A → ∀ x y : A, connected P (x = y)}.\n\nClass DenseSubuniverse (P : Type → Prop) : Prop :=\n  {modal_false : P False}.\n\nClass RegularSubuniverse (P : Type → Prop) : Prop :=\n  {modal_exists : ∀ A (B : A → Prop), P A → (∀ x : A, P (B x)) → P (∃ x : A, B x)}.\n\nModule Mod.\n  Class ModalOperator (P : Type → Prop) :=\n    {T : Type → Type;\n     modal : ∀ {A}, P (T A);\n     unit : ∀ {A}, A → T A}.\n\n  (** A dependent idempotent modality will support a dependent elimination rule, and will be closed under sigma types. *)\n  Class DepModality (P : Type → Prop) :=\n    {DepModality_Operator :> ModalOperator P;\n     DepModality_RepleteSubuniverse :> RepleteSubuniverse P;\n     depmod_ump : ∀ {A B} `{∀ x, Modal P (B x)}, @is_isomorphism (∀ x : T A, B x) (∀ x : A, B (unit x)) (λ f a, f (unit a))}.\n\n  (** A simple idempotent modality will support a simple elimination rule, and will be closed under product types. *)\n  Class SimpleModality (P : Type → Prop) :=\n    {SimpleModality_Operator :> ModalOperator P;\n     SimpleModality_RepleteSubuniverse :> RepleteSubuniverse P;\n     simpmod_ump : ∀ {A B} `{Modal P B}, @is_isomorphism (T A → B) (A → B) (λ f, f ∘ unit)}.\n\n  Arguments T P {_}.\n\n  Section Dep.\n    Context {P} `{DepModality P}.\n\n    Definition ind {A} (B : T P A → Type) `{∀ x : T P A, Modal P (B x)} (f : ∀ x : A, B (unit x)) : ∀ x : T P A, B x.\n    Proof. by apply: iso_inv _ depmod_ump _. Defined.\n\n    Lemma ind_beta {A B} `{∀ x : T P A, Modal P (B x)} (f : ∀ x : A, B (unit x)) (a : A) : ind B f (unit a) = f a.\n    Proof.\n      case: (depmod_ump f)=> f' [h1 h2].\n      rewrite -h1.\n      move: (unit a).\n      apply: equal_f_dep.\n      by apply: funcompr_compute.\n    Qed.\n\n    Global Instance Dep_to_Simple : SimpleModality P.\n    Proof.\n      unshelve esplit.\n      - apply: DepModality_RepleteSubuniverse.\n      - move=> A B ?.\n        abstract apply: depmod_ump.\n    Defined.\n  End Dep.\n\n\n  Section Simple.\n    Context {P} `{SimpleModality P}.\n\n    Global Instance Modal_T {A} : Modal P (T P A).\n    Proof. by apply: modal. Qed.\n\n    Definition rec {A B} `{Modal P B} (f : A → B) : T P A → B.\n    Proof. by apply: iso_inv _ simpmod_ump _. Defined.\n\n    Lemma rec_beta {A B} `{Modal P B} (f : A → B) (a : A) : rec f (unit a) = f a.\n    Proof.\n      case: (simpmod_ump f)=> f' [h1 h2].\n      rewrite -h1 /comp.\n      move: (unit a).\n      apply: equal_f.\n      by apply: funcompr_compute.\n    Qed.\n\n    Opaque rec.\n\n    Definition alg {A} `{Modal P A} : T P A → A.\n    Proof. by apply: rec. Defined.\n\n    Lemma alg_beta {A} `{Modal P A} : ∀ x : A, alg (unit x) = x.\n    Proof. by move=>?; rewrite /alg rec_beta. Qed.\n\n    Lemma alg_eta {A} `{Modal P A} : ∀ x : T P A, x = unit (alg x).\n    Proof.\n      apply: equal_f.\n      apply: (iso_injective _ simpmod_ump).\n      apply: funext=> x//=.\n      by rewrite alg_beta.\n    Qed.\n\n    Opaque alg.\n\n    Lemma alg_iso {A} `{Modal P A} : @is_isomorphism (T P A) A alg.\n    Proof.\n      move=> x.\n      exists (unit x); split.\n      - by rewrite alg_beta.\n      - move=> x' <-.\n        by rewrite -alg_eta.\n    Qed.\n\n    Lemma unit_iso_to_modal {A} : is_isomorphism (unit : A → T P A) → Modal P A.\n    Proof.\n      move=> iso.\n      rewrite /Modal.\n      apply: (replete P _ (iso_inv _ iso)).\n      - apply: iso_inv_iso.\n      - apply: modal.\n    Qed.\n  End Simple.\nEnd Mod.\n\n\nSection Instances.\n  Context {P} `{LexSubuniverse P} `{DenseSubuniverse P} `{RegularSubuniverse P}.\n\n  Global Instance Modal_false : Modal P False.\n  Proof. by apply: modal_false. Qed.\n\n  Global Instance Modal_exists {A} {B : A → Prop} `{Modal P A} `{∀ x : A, Modal P (B x)} : Modal P (∃ x : A, B x).\n  Proof. by apply: modal_exists. Qed.\nEnd Instances.\n\n\n\nSection SimpleInstances.\n  Context {P} `{Mod.SimpleModality P}.\n\n  Global Instance Modal_true : Modal P True.\n  Proof.\n    apply: Mod.unit_iso_to_modal.\n    move=> x.\n    exists I; split.\n    - move: x.\n      apply: equal_f.\n      apply: (iso_injective _ Mod.simpmod_ump).\n      by apply: funext; case.\n    - by case.\n  Qed.\n\n\n\n  Global Instance Modal_prod {A B} `{Modal P A} `{Modal P B} : Modal P (A * B).\n  Proof.\n    apply: Mod.unit_iso_to_modal=> p.\n    unshelve esplit.\n    - split.\n      + apply: Mod.alg; move: p; apply: Mod.rec.\n        move=> p; apply: Mod.unit; move: p.\n        apply: fst.\n      + apply: Mod.alg; move: p; apply: Mod.rec.\n        move=> p; apply: Mod.unit; move: p.\n        apply: snd.\n    - split.\n      + move: p.\n        apply: equal_f.\n        apply: (iso_injective _ Mod.simpmod_ump).\n        apply: funext=> x//=.\n        congr Mod.unit.\n        rewrite ?Mod.rec_beta ?Mod.alg_beta.\n        by case: x.\n      + case=> x y <-.\n        by rewrite ?Mod.rec_beta ?Mod.alg_beta.\n  Qed.\n\n  Global Instance Modal_and {A B : Prop} `{Modal P A} `{Modal P B} : Modal P (A ∧ B).\n  Proof.\n    rewrite /Modal.\n    apply: (replete P (A * B)).\n    - by move=> p; split; move: p; [apply: fst | apply: snd].\n    - move=> ? p.\n      unshelve esplit=>//.\n      split; move: p; [apply: proj1 | apply: proj2].\n    - change P with (Modal P).\n      typeclasses eauto.\n  Qed.\n\n  Global Instance Modal_fun {A B} `{Modal P B} : Modal P (A → B).\n  Proof.\n    apply: Mod.unit_iso_to_modal=> f.\n    unshelve esplit.\n    - move=> a.\n      move: f.\n      apply: Mod.rec.\n      by apply.\n    - split.\n      + move: f.\n        apply: equal_f.\n        apply: (iso_injective _ Mod.simpmod_ump).\n        apply: funext=> f//=.\n        congr Mod.unit.\n        apply: funext=> x.\n        by rewrite Mod.rec_beta.\n      + move=> f' <-.\n        apply: funext=>?.\n        by rewrite Mod.rec_beta.\n  Qed.\n\n  Global Instance IsProp_T {A} `{IsProp A} : IsProp (Mod.T P A).\n  Proof.\n    move=> x.\n    apply: equal_f.\n    move: x.\n    apply: equal_f.\n    apply: (iso_injective _ Mod.simpmod_ump).\n    apply: funext=> x//=.\n    apply: (iso_injective _ Mod.simpmod_ump).\n    apply: funext=> y //=.\n    congr Mod.unit.\n    apply: irr.\n  Qed.\n\n  Global Instance Modal_eq {A} {x y : A} `{Modal P A} : Modal P (x = y).\n  Proof.\n    apply: Mod.unit_iso_to_modal=> e.\n    unshelve esplit.\n    - move: e.\n      apply: equal_f.\n      apply: (iso_injective _ Mod.simpmod_ump).\n      by apply: funext=>//=.\n    - split=>//=.\n      apply: irr.\n  Qed.\n\n  Global Instance Modal_not {A} `{DenseSubuniverse P} : Modal P (not A).\n  Proof. by rewrite /not; typeclasses eauto. Qed.\nEnd SimpleInstances.\n\nSection DepInstances.\n  Context {P} `{Mod.DepModality P}.\n\n  Global Instance Modal_T {A} : Modal P (Mod.T P A).\n  Proof. by apply: Mod.modal. Defined.\n\n  Global Instance Modal_pi {A B} `{∀ x : A, Modal P (B x)} : Modal P (∀ x : A, B x).\n  Proof.\n    apply: Mod.unit_iso_to_modal=> f.\n    unshelve esplit.\n    - move=> a.\n      move: f.\n      apply: Mod.rec.\n      by apply.\n    - split.\n      + move: f.\n        apply: equal_f_dep.\n        apply: (iso_injective _ Mod.simpmod_ump).\n        rewrite /comp //=.\n        apply: funext=> ?; f_equal.\n        apply: depfunext=> x.\n        by rewrite Mod.rec_beta.\n      + move=> f' <-.\n        apply: depfunext=> x.\n        by rewrite Mod.rec_beta.\n  Qed.\n\n  Global Instance Modal_sg {A B} `{Modal P A} `{∀ x : A, Modal P (B x)} : Modal P {x : A & B x}.\n  Proof.\n    apply: Mod.unit_iso_to_modal=> p.\n    unshelve esplit.\n    - unshelve esplit.\n      + apply: Mod.alg; move: p.\n        apply: Mod.rec=> u.\n        apply: Mod.unit.\n        move: u.\n        apply: projT1.\n      + apply: Mod.alg; move: p.\n        apply: Mod.ind; case=> a b.\n        apply: Mod.unit.\n        rewrite (_ : (Mod.alg _) = a) //=.\n        abstract by rewrite Mod.rec_beta Mod.alg_beta.\n      - split=>//=.\n        + move: p.\n          apply: equal_f_dep.\n          apply: (iso_injective _ Mod.simpmod_ump).\n          apply: funext; case=> a b //=.\n          congr Mod.unit.\n          apply: eq_sigT=>//=.\n          * by rewrite Mod.rec_beta Mod.alg_beta.\n          * move=> ?.\n            rewrite Mod.ind_beta Mod.alg_beta rew_compose.\n            by simplify_eqs.\n        + case=> a b//= <-.\n          apply: eq_sigT=>//=.\n          * by rewrite Mod.rec_beta Mod.alg_beta.\n          * move=> ?.\n            rewrite Mod.ind_beta Mod.alg_beta rew_compose.\n            by simplify_eqs.\n  Qed.\nEnd DepInstances.\n\nModule ModP.\n  Definition T P `{Mod.ModalOperator P} (A : Prop) := PropTrunc.T (Mod.T P A).\n\n  Lemma unit {P} `{Mod.ModalOperator P} {A : Prop} : A → T P A.\n  Proof. by move/Mod.unit/PropTrunc.unit. Defined.\n\n  Section Dep.\n    Context {P} `{Mod.DepModality P}.\n\n    Definition ind {A} (B : T P A → Type) `{∀ x : T P A, Modal P (B x)} (f : ∀ x : A, B (unit x)) : ∀ x : T P A, B x.\n    Proof.\n      move=> a.\n      rewrite -[a]PropTrunc.alg_eta.\n      move: (PropTrunc.alg a).\n      by apply/Mod.ind/f.\n    Defined.\n\n    Lemma ind_beta {A B} `{∀ x : T P A, Modal P (B x)} (f : ∀ x : A, B (unit x)) (a : A) : ind B f (unit a) = f a.\n    Proof.\n      apply: JMeq_eq.\n      rewrite /ind /unit; simplify_eqs.\n      by rewrite PropTrunc.alg_beta Mod.ind_beta.\n    Qed.\n\n    Opaque ind.\n  End Dep.\n\n  Section Simple.\n    Context {P} `{Mod.SimpleModality P}.\n\n\n    Global Instance Modal_T {A} : Modal P (T P A).\n    Proof.\n      apply: Mod.unit_iso_to_modal=> p.\n      unshelve esplit.\n      - apply: PropTrunc.unit.\n        move: p.\n        apply: Mod.rec.\n        apply: (@PropTrunc.rec (Mod.T P A) (Mod.T P A) _ id).\n      - split=>//=.\n        apply: irr.\n    Qed.\n\n    Definition rec {A : Prop} {B} `{Modal P B} (f : A → B) : T P A → B.\n    Proof.\n      move/PropTrunc.alg.\n      by apply/Mod.rec/f.\n    Defined.\n\n    Lemma rec_beta {A : Prop} {B} `{Modal P B} (f : A → B) (a : A) : rec f (unit a) = f a.\n    Proof. by rewrite /rec /unit PropTrunc.alg_beta Mod.rec_beta. Qed.\n\n    Opaque rec.\n  End Simple.\nEnd ModP.\n\n\n\nSection SeparatedReflection.\n  Context P `{Mod.DepModality P}.\n\n  Definition separated (P : Type → Prop) : Type → Prop :=\n    λ A, ∀ x y : A, P (x = y).\n\n  Instance separated_replete : RepleteSubuniverse (separated P).\n  Proof.\n    move=> A B f iso sepA x y.\n    pose g := iso_inv f iso.\n    apply: (replete P (g x = g y)).\n    - by apply/iso_injective/iso_inv_iso.\n    - move=> ? h.\n      unshelve esplit=>//.\n      by rewrite h.\n    - by apply: sepA.\n  Qed.\n\n  Definition modally_eq (A : Type) (x y : A) : Prop :=\n    ModP.T P (x = y).\n\n  Global Instance Reflexive_modally_eq {A} : RelationClasses.Reflexive (modally_eq A).\n  Proof. by move=>?; apply: ModP.unit. Qed.\n\n  Global Instance Symmetric_modally_eq {A} : RelationClasses.Symmetric (modally_eq A).\n  Proof. by move=>??; apply: ModP.rec=>->; apply: ModP.unit. Qed.\n\n  Global Instance Transitive_modally_eq {A} : RelationClasses.Transitive (modally_eq A).\n  Proof. by move=> ???; apply: ModP.rec=>->. Qed.\n\n  Global Instance Equivalence_modally_eq {A} : RelationClasses.Equivalence (modally_eq A).\n  Proof. by split; typeclasses eauto. Qed.\n\n  Definition Sep A := Quotient.T A (modally_eq A).\n\n  Notation Separated := (Modal (separated P)).\n\n  Global Instance Separated_Sep {A} : Separated (Sep A).\n  Proof.\n    apply: Quotient.indp=> x.\n    apply: Quotient.indp=> y.\n    apply: (replete P _ Quotient.glue).\n    - by apply: Quotient.glue_is_iso.\n    - by apply: ModP.Modal_T.\n  Qed.\n\n  Global Instance separated_ModalOperator : Mod.ModalOperator (separated P).\n  Proof.\n    unshelve esplit.\n    - by apply: Sep.\n    - by move=>?; apply: Separated_Sep.\n    - by move=>?; apply: Quotient.intro.\n  Defined.\n\n  Global Instance Modal_EqOfSeparated {A} `{Separated A} {x y : A} : Modal P (x = y).\n  Proof. by apply: (mod x y). Qed.\n\n  Global Instance DepModality_separated : Mod.DepModality (separated P).\n  Proof.\n    unshelve esplit; first by typeclasses eauto.\n    move=> A B HB f.\n    unshelve esplit.\n    - unshelve apply: Quotient.ind.\n      + by apply: f.\n      + by move=>??; apply: ModP.ind=>?; simplify_eqs.\n    - split=>//=.\n      move=> h <-.\n      by apply: depfunext; apply: Quotient.indp.\n  Defined.\nEnd SeparatedReflection.\n\nNotation Separated := (λ P, Modal (separated P)).\n", "meta": {"author": "jonsterling", "repo": "coq-synthetic-realizability", "sha": "88396c98c6f9e507e61119994ca4ff980a3d4c1c", "save_path": "github-repos/coq/jonsterling-coq-synthetic-realizability", "path": "github-repos/coq/jonsterling-coq-synthetic-realizability/coq-synthetic-realizability-88396c98c6f9e507e61119994ca4ff980a3d4c1c/theories/Modality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.27884730390713}}
{"text": "(* This includes everything that should be defined in GHC/Base.hs, but cannot\n   be generated from Base.hs.\n\nThe types defined in GHC.Base:\n\n  list, (), Int, Bool, Ordering, Char, String\n\nare all mapped to corresponding Coq types. Therefore, the Eq/Ord classes must\nbe defined in this module so that we can create instances for these types.\n\n *)\n\n\n(********************* Types ************************)\n\nRequire Export GHC.Prim.\n\nRequire Export GHC.Tuple.\n\n(* List notation *)\nRequire Export Coq.Lists.List.\n\n(* Booleans *)\nRequire Export Bool.Bool.\n\n(* Int and Integer types *)\nRequire NArith.\nRequire Import ZArith.\nRequire Export GHC.Num.\n\n(* Char type *)\nRequire Export GHC.Char.\nDefinition unsafeChr := Z.to_N.\nDefinition ord := Z.of_N.\n\n(* Strings *)\nRequire Coq.Strings.String.\nDefinition String := list Char.\n\nBind Scope string_scope with String.string.\nFixpoint hs_string__ (s : String.string) : String :=\n  match s with\n  | String.EmptyString => nil\n  | String.String c s  => &#c :: hs_string__ s\n  end.\nNotation \"'&' s\" := (hs_string__ s) (at level 1, format \"'&' s\").\n\n(* IO --- PUNT *)\nDefinition FilePath := String.\n\n(* ASZ: I've been assured that this is OK *)\nInductive IO (a : Type) : Type :=.\nInductive IORef (a : Type) : Type :=.\nInductive IOError : Type :=.\n\n(****************************************************)\n\n(* function composition *)\nRequire Export Coq.Program.Basics.\n\nNotation \"[,]\"  := (fun x y => (x,y)).\nNotation \"[,,]\" := (fun x0 y1 z2 => (x0, y1, z2)).\nNotation \"[,,,]\" := (fun x0 x1 x2 x3 => (x0,x1,x2,x3)).\nNotation \"[,,,,]\" := (fun x0 x1 x2 x3 x4 => (x0,x1,x2,x3,x4)).\nNotation \"[,,,,,]\" := (fun x0 x1 x2 x3 x4 x5 => (x0,x1,x2,x3,x4,x5)).\nNotation \"[,,,,,,]\" := (fun x0 x1 x2 x3 x4 x5 x6 => (x0,x1,x2,x3,x4,x5,x6)).\nNotation \"[,,,,,,,]\" := (fun x0 x1 x2 x3 x4 x5 x6 x7 => (x0,x1,x2,x3,x4,x5,x6,x7)).\n\nNotation \"'_++_'\"   := (fun x y => x ++ y).\nNotation \"'_::_'\"   := (fun x y => x :: y).\n\nNotation \"[->]\"  := arrow.\n\n\n\n(* Configure type argument to be maximally inserted *)\nArguments List.app {_} _ _.\n\n(****************************************************)\n\n\nDefinition Synonym {A : Type} (_uniq : Type) (x : A) : A := x.\nArguments Synonym {A}%type _uniq%type x%type.\n\n\n(*********** built in classes Eq & Ord **********************)\n\n(* Don't clash with Eq constructor for the comparison type. *)\nRecord Eq___Dict a := Eq___Dict_Build {\n  op_zeze____ : (a -> (a -> bool)) ;\n  op_zsze____ : (a -> (a -> bool)) }.\n\nDefinition Eq_ a := forall r, (Eq___Dict a -> r) -> r.\nExisting Class Eq_.\n\nDefinition op_zeze__ {a} {g : Eq_ a} := g _ (op_zeze____ _).\nDefinition op_zsze__ {a} {g : Eq_ a} := g _ (op_zsze____ _).\n\nNotation \"'_/=_'\" := (op_zsze__).\nInfix \"/=\" := (op_zsze__) (no associativity, at level 70).\nNotation \"'_==_'\" := (op_zeze__).\nInfix \"==\" := (op_zeze__) (no associativity, at level 70).\n\nDefinition eq_default {a} (eq : a -> a -> bool) : Eq_ a :=\n  fun _ k => k {|op_zeze____ := eq; op_zsze____ := fun x y => negb (eq x y) |}.\n\nRecord Ord__Dict a := Ord__Dict_Build {\n  op_zl____ : a -> a -> bool ;\n  op_zlze____ : a -> a -> bool ;\n  op_zg____ : a -> a -> bool ;\n  op_zgze____ : a -> a -> bool ;\n  compare__ : a -> a -> comparison ;\n  max__ : a -> a -> a ;\n  min__ : a -> a -> a }.\n\nDefinition Ord a `{Eq_ a} :=\n  forall r, (Ord__Dict a -> r) -> r.\n\nExisting Class Ord.\n\nDefinition op_zl__ `{g : Ord a} : a -> a -> bool :=\n  g _ (op_zl____ a).\n\nDefinition op_zlze__ `{g : Ord a} : a -> a -> bool :=\n  g _ (op_zlze____ a).\n\nDefinition op_zg__ `{g : Ord a} : a -> a -> bool :=\n  g _ (op_zg____ a).\n\nDefinition op_zgze__ `{g : Ord a} : a -> a -> bool :=\n  g _ (op_zgze____ a).\n\nDefinition compare `{g : Ord a} : a -> a -> comparison :=\n  g _ (compare__ a).\n\nDefinition max `{g : Ord a} : a -> a -> a :=\n  g _ (max__ a).\n\nDefinition min `{g : Ord a} : a -> a -> a :=\n  g _ (min__ a).\n\nNotation \"'_<_'\" := (op_zl__).\nInfix \"<\" := (op_zl__) (no associativity, at level 70).\n\nNotation \"'_<=_'\" := (op_zlze__).\nInfix \"<=\" := (op_zlze__) (no associativity, at level 70).\n\nNotation \"'_>_'\" := (op_zg__).\nInfix \">\" := (op_zg__) (no associativity, at level 70).\n\nNotation \"'_>=_'\" := (op_zgze__).\nInfix \">=\" := (op_zgze__) (no associativity, at level 70).\n\n(*********** Eq/Ord for primitive types **************************)\n\nInstance Eq_Int___ : Eq_ Int := fun _ k => k {|\n                               op_zeze____ := fun x y => (x =? y)%Z;\n                               op_zsze____ := fun x y => negb (x =? y)%Z;\n                               |}.\n\nInstance Ord_Int___ : Ord Int := fun _ k => k {|\n  op_zl____   := fun x y => (x <? y)%Z;\n  op_zlze____ := fun x y => (x <=? y)%Z;\n  op_zg____   := fun x y => (y <? x)%Z;\n  op_zgze____ := fun x y => (y <=? x)%Z;\n  compare__   := Z.compare%Z ;\n  max__       := Z.max%Z;\n  min__       := Z.min%Z;\n|}.\n\nInstance Eq_Integer___ : Eq_ Integer := fun _ k => k {|\n                               op_zeze____ := fun x y => (x =? y)%Z;\n                               op_zsze____ := fun x y => negb (x =? y)%Z;\n                             |}.\n\nInstance Ord_Integer___ : Ord Integer := fun _ k => k {|\n  op_zl____   := fun x y => (x <? y)%Z;\n  op_zlze____ := fun x y => (x <=? y)%Z;\n  op_zg____   := fun x y => (y <? x)%Z;\n  op_zgze____ := fun x y => (y <=? x)%Z;\n  compare__   := Z.compare%Z ;\n  max__       := Z.max%Z;\n  min__       := Z.min%Z;\n|}.\n\nInstance Eq_Word___ : Eq_ Word := fun _ k => k {|\n                               op_zeze____ := fun x y => (x =? y)%N;\n                               op_zsze____ := fun x y => negb (x =? y)%N;\n                             |}.\n\nInstance Ord_Word___ : Ord Word := fun _ k => k {|\n  op_zl____   := fun x y => (x <? y)%N;\n  op_zlze____ := fun x y => (x <=? y)%N;\n  op_zg____   := fun x y => (y <? x)%N;\n  op_zgze____ := fun x y => (y <=? x)%N;\n  compare__   := N.compare%N ;\n  max__       := N.max%N;\n  min__       := N.min%N;\n|}.\n\nInstance Eq_Char___ : Eq_ Char := fun _ k => k {|\n                               op_zeze____ := fun x y => (x =? y)%N;\n                               op_zsze____ := fun x y => negb (x =? y)%N;\n                             |}.\n\nInstance Ord_Char___ : Ord Char := fun _ k => k {|\n  op_zl____   := fun x y => (x <? y)%N;\n  op_zlze____ := fun x y => (x <=? y)%N;\n  op_zg____   := fun x y => (y <? x)%N;\n  op_zgze____ := fun x y => (y <=? x)%N;\n  compare__   := N.compare%N ;\n  max__       := N.max%N;\n  min__       := N.min%N;\n|}.\n\nInstance Eq_bool___ : Eq_ bool := fun _ k => k {|\n                               op_zeze____ := eqb;\n                               op_zsze____ := fun x y => negb (eqb x y);\n                             |}.\n\nDefinition compare_bool (b1:bool)(b2:bool) : comparison :=\n  match b1 , b2 with\n  | true , true => Eq\n  | false, false => Eq\n  | true , false => Gt\n  | false , true => Lt\n  end.\n\nInstance Ord_bool___ : Ord bool := fun _ k => k {|\n  op_zl____   := fun x y => andb (negb x) y;\n  op_zlze____ := fun x y => orb (negb x) y;\n  op_zg____   := fun x y => orb (negb y) x;\n  op_zgze____ := fun x y => andb (negb y) x;\n  compare__   := compare_bool;\n  max__       := orb;\n  min__       := andb\n|}.\n\nInstance Eq_unit___ : Eq_ unit := fun _ k => k {|\n                               op_zeze____ := fun x y => true;\n                               op_zsze____ := fun x y => false;\n                             |}.\n\nInstance Ord_unit___ : Ord unit := fun _ k => k {|\n  op_zl____   := fun x y => false;\n  op_zlze____ := fun x y => true;\n  op_zg____   := fun x y => false;\n  op_zgze____ := fun x y => true;\n  compare__   := fun x y => Eq ;\n  max__       := fun x y => tt;\n  min__       := fun x y => tt;\n|}.\n\nDefinition eq_comparison (x : comparison) (y: comparison) :=\n  match x , y with\n  | Eq, Eq => true\n  | Gt, Gt => true\n  | Lt, Lt => true\n  | _ , _  => false\nend.\n\nInstance Eq_comparison___ : Eq_ comparison := fun _ k => k\n{|\n  op_zeze____ := eq_comparison;\n  op_zsze____ := fun x y => negb (eq_comparison x y);\n|}.\n\nDefinition compare_comparison  (x : comparison) (y: comparison) :=\n  match x , y with\n  | Eq, Eq => Eq\n  | _, Eq  => Gt\n  | Eq, _  => Lt\n  | Lt, Lt => Eq\n  | _, Lt  => Lt\n  | Lt, _  => Gt\n  | Gt, Gt => Eq\nend.\n\nDefinition ord_default {a} (comp : a -> a -> comparison) `{Eq_ a} : Ord a :=\n  fun _ k => k (Ord__Dict_Build _\n  (fun x y => (comp x y) == Lt)\n  ( fun x y => negb ((comp y x) == Lt))\n  (fun x y => (comp y x) == Lt)\n  (fun x y => negb ((comp x y) == Lt))\n  comp\n  (fun x y =>\n     match comp x y with\n     | Lt => y\n     | _  => x\n     end)\n  (fun x y =>   match comp x y with\n             | Gt => y\n             | _  => x\n             end)).\n\nInstance Ord_comparison___ : Ord comparison := ord_default compare_comparison.\n\nDefinition eq_pair {t1} {t2} `{Eq_ t1} `{Eq_ t2} (a b : (t1 * t2)) :=\n  match a, b with\n  | (a1, a2), (b1, b2) =>\n    (a1 == b1) && (a2 == b2)\n  end.\n\nDefinition compare_pair {t1} {t2} `{Ord t1} `{Ord t2} (a b : (t1 * t2)) :=\n  match a, b with\n  | (a1, a2), (b1, b2) =>\n    match compare a1 b1 with\n    | Lt => Lt\n    | Gt => Gt\n    | Eq => compare a2 b2\n    end\n  end.\n\nInstance Eq_pair___ {a} {b} `{Eq_ a} `{Eq_ b} : Eq_ (a * b) := fun _ k => k\n  {| op_zeze____ := eq_pair;\n     op_zsze____ := fun x y => negb (eq_pair x y)\n  |}.\n\nInstance Ord_pair___ {a} {b} `{Ord a} `{Ord b} : Ord (a * b) :=\n  ord_default compare_pair.\n\n(* TODO: are these available in a library somewhere? *)\nDefinition eqlist {a} `{Eq_ a} : list a -> list a -> bool :=\n\tfix eqlist xs ys :=\n\t    match xs , ys with\n\t    | nil , nil => true\n\t    | x :: xs' , y :: ys' => andb (x == y) (eqlist xs' ys')\n\t    | _ ,  _ => false\n\t    end.\n\nFixpoint compare_list {a} `{Ord a} (xs :  list a) (ys : list a) : comparison :=\n    match xs , ys with\n    | nil , nil => Eq\n    | nil , _   => Lt\n    | _   , nil => Gt\n    | x :: xs' , y :: ys' =>\n      match compare x y with\n          | Lt => Lt\n          | Gt => Gt\n          | Eq => compare_list xs' ys'\n      end\n    end.\n\nInstance Eq_list {a} `{Eq_ a} : Eq_ (list a) := fun _ k => k\n  {| op_zeze____ := eqlist;\n     op_zsze____ := fun x y => negb (eqlist x y)\n  |}.\n\nInstance Ord_list {a} `{Ord a}: Ord (list a) :=\n  ord_default compare_list.\n\n\n(* ********************************************************* *)\n(* Some Haskell functions we cannot translate (yet)          *)\n\n\n(* The inner nil case is impossible. So it is left out of the Haskell version. *)\nFixpoint scanr {a b:Type} (f : a -> b -> b) (q0 : b) (xs : list a) : list b :=\n  match xs with\n  | nil => q0 :: nil\n  | y :: ys => match scanr f q0 ys with\n              | q :: qs =>  f y q :: (q :: qs)\n              | nil => nil\n              end\nend.\n\n\n(* The inner nil case is impossible. So it is left out of the Haskell version. *)\nFixpoint scanr1 {a :Type} (f : a -> a -> a) (q0 : a) (xs : list a) : list a :=\n  match xs with\n  | nil => q0 :: nil\n  | y :: nil => y :: nil\n  | y :: ys => match scanr1 f q0 ys with\n              | q :: qs =>  f y q :: (q :: qs)\n              | nil => nil\n              end\nend.\n\nDefinition foldl {a}{b} k z0 xs :=\n  fold_right (fun (v:a) (fn:b->b) => (fun (z:b) => fn (k z v))) (id : b -> b) xs z0.\n\nDefinition foldl' {a}{b} k z0 xs :=\n  fold_right (fun(v:a) (fn:b->b) => (fun(z:b) => fn (k z v))) (id : b -> b) xs z0.\n\n(* Less general type for build *)\nDefinition build {a} : (forall {b}, (a -> b -> b) -> b -> b) -> list a :=\n  fun g => g _ (fun x y => x :: y) nil.\n\n(* A copy of it, to facilitate the rewrite rule in the edits file *)\nDefinition build' : forall {a}, (forall {b}, (a -> b -> b) -> b -> b) -> list a := @build.\n\n(********************************************************************)\n\n(* Definition oneShot {a} (x:a) := x. *)\n\n(** Qualified notation for the notation defined here **)\n\nModule ManualNotations.\nInfix \"GHC.Base./=\" := (op_zsze__) (no associativity, at level 70).\nNotation \"'_GHC.Base./=_'\" := (op_zsze__).\nInfix \"GHC.Base.==\" := (op_zeze__) (no associativity, at level 70).\nNotation \"'_GHC.Base.==_'\" := (op_zeze__).\nInfix \"GHC.Base.<\" := (op_zl__) (no associativity, at level 70).\nNotation \"'_GHC.Base.<_'\" := (op_zl__).\nInfix \"GHC.Base.<=\" := (op_zlze__) (no associativity, at level 70).\nNotation \"'_GHC.Base.<=_'\" := (op_zlze__).\nInfix \"GHC.Base.>\" := (op_zg__) (no associativity, at level 70).\nNotation \"'_GHC.Base.>_'\" := (op_zg__).\nInfix \"GHC.Base.>=\" := (op_zgze__) (no associativity, at level 70).\nNotation \"'_GHC.Base.>=_'\" := (op_zgze__).\n\nRequire String Ascii.\nExport String.StringSyntax Ascii.AsciiSyntax.\nEnd ManualNotations.\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/base-src/module-edits/GHC/Base/midamble.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.2788472970112645}}
{"text": "From prelude Require Export co_pset.\nFrom program_logic Require Export model.\nFrom program_logic Require Import ownership wsat.\nLocal Hint Extern 10 (_ ≤ _) => omega.\nLocal Hint Extern 100 (@eq coPset _ _) => set_solver.\nLocal Hint Extern 100 (_ ∉ _) => set_solver.\nLocal Hint Extern 10 (✓{_} _) =>\n  repeat match goal with\n  | H : wsat _ _ _ _ |- _ => apply wsat_valid in H; last omega\n  end; solve_validN.\n\nProgram Definition pvs_def {Λ Σ} (E1 E2 : coPset) (P : iProp Λ Σ) : iProp Λ Σ :=\n  {| uPred_holds n r1 := ∀ rf k Ef σ,\n       0 < k ≤ n → (E1 ∪ E2) ∩ Ef = ∅ →\n       wsat k (E1 ∪ Ef) σ (r1 ⋅ rf) →\n       ∃ r2, P k r2 ∧ wsat k (E2 ∪ Ef) σ (r2 ⋅ rf) |}.\nNext Obligation.\n  intros Λ Σ E1 E2 P r1 r2 n HP Hr rf k Ef σ ?? Hwsat; simpl in *.\n  apply HP; auto. by rewrite (dist_le _ _ _ _ Hr); last lia.\nQed.\nNext Obligation.\n  intros Λ Σ E1 E2 P r1 r2 n1 n2 HP [r3 ?] Hn ? rf k Ef σ ?? Hws; setoid_subst.\n  destruct (HP (r3⋅rf) k Ef σ) as (r'&?&Hws'); rewrite ?(assoc op); auto.\n  exists (r' ⋅ r3); rewrite -assoc; split; last done.\n  apply uPred_weaken with k r'; eauto using cmra_included_l.\nQed.\n\nDefinition pvs_aux : { x | x = @pvs_def }. by eexists. Qed.\nDefinition pvs := proj1_sig pvs_aux.\nDefinition pvs_eq : @pvs = @pvs_def := proj2_sig pvs_aux.\n\nArguments pvs {_ _} _ _ _%I.\nInstance: Params (@pvs) 4.\n\nNotation \"|={ E1 , E2 }=> Q\" := (pvs E1 E2 Q%I)\n  (at level 199, E1, E2 at level 50, Q at level 200,\n   format \"|={ E1 , E2 }=>  Q\") : uPred_scope.\nNotation \"|={ E }=> Q\" := (pvs E E Q%I)\n  (at level 199, E at level 50, Q at level 200,\n   format \"|={ E }=>  Q\") : uPred_scope.\n\nSection pvs.\nContext {Λ : language} {Σ : iFunctor}.\nImplicit Types P Q : iProp Λ Σ.\nImplicit Types m : iGst Λ Σ.\n\nGlobal Instance pvs_ne E1 E2 n : Proper (dist n ==> dist n) (@pvs Λ Σ E1 E2).\nProof.\n  rewrite pvs_eq.\n  intros P Q HPQ; split=> n' r1 ??; simpl; split; intros HP rf k Ef σ ???;\n    destruct (HP rf k Ef σ) as (r2&?&?); auto;\n    exists r2; split_and?; auto; apply HPQ; eauto.\nQed.\nGlobal Instance pvs_proper E1 E2 : Proper ((≡) ==> (≡)) (@pvs Λ Σ E1 E2).\nProof. apply ne_proper, _. Qed.\n\nLemma pvs_intro E P : P ⊑ |={E}=> P.\nProof.\n  rewrite pvs_eq. split=> n r ? HP rf k Ef σ ???; exists r; split; last done.\n  apply uPred_weaken with n r; eauto.\nQed.\nLemma pvs_mono E1 E2 P Q : P ⊑ Q → (|={E1,E2}=> P) ⊑ (|={E1,E2}=> Q).\nProof.\n  rewrite pvs_eq. intros HPQ; split=> n r ? HP rf k Ef σ ???.\n  destruct (HP rf k Ef σ) as (r2&?&?); eauto.\n  exists r2; eauto using uPred_in_entails.\nQed.\nLemma pvs_timeless E P : TimelessP P → (▷ P) ⊑ (|={E}=> P).\nProof.\n  rewrite pvs_eq uPred.timelessP_spec=> HP.\n  uPred.unseal; split=>-[|n] r ? HP' rf k Ef σ ???; first lia.\n  exists r; split; last done.\n  apply HP, uPred_weaken with n r; eauto using cmra_validN_le.\nQed.\nLemma pvs_trans E1 E2 E3 P :\n  E2 ⊆ E1 ∪ E3 → (|={E1,E2}=> |={E2,E3}=> P) ⊑ (|={E1,E3}=> P).\nProof.\n  rewrite pvs_eq. intros ?; split=> n r1 ? HP1 rf k Ef σ ???.\n  destruct (HP1 rf k Ef σ) as (r2&HP2&?); auto.\nQed.\nLemma pvs_mask_frame E1 E2 Ef P :\n  Ef ∩ (E1 ∪ E2) = ∅ → (|={E1,E2}=> P) ⊑ (|={E1 ∪ Ef,E2 ∪ Ef}=> P).\nProof.\n  rewrite pvs_eq. intros ?; split=> n r ? HP rf k Ef' σ ???.\n  destruct (HP rf k (Ef∪Ef') σ) as (r'&?&?); rewrite ?(assoc_L _); eauto.\n  by exists r'; rewrite -(assoc_L _).\nQed.\nLemma pvs_frame_r E1 E2 P Q : ((|={E1,E2}=> P) ★ Q) ⊑ (|={E1,E2}=> P ★ Q).\nProof.\n  rewrite pvs_eq. uPred.unseal; split; intros n r ? (r1&r2&Hr&HP&?) rf k Ef σ ???.\n  destruct (HP (r2 ⋅ rf) k Ef σ) as (r'&?&?); eauto.\n  { by rewrite assoc -(dist_le _ _ _ _ Hr); last lia. }\n  exists (r' ⋅ r2); split; last by rewrite -assoc.\n  exists r', r2; split_and?; auto; apply uPred_weaken with n r2; auto.\nQed.\nLemma pvs_openI i P : ownI i P ⊑ (|={{[i]},∅}=> ▷ P).\nProof.\n  rewrite pvs_eq. uPred.unseal; split=> -[|n] r ? Hinv rf [|k] Ef σ ???; try lia.\n  apply ownI_spec in Hinv; last auto.\n  destruct (wsat_open k Ef σ (r ⋅ rf) i P) as (rP&?&?); auto.\n  { rewrite lookup_wld_op_l ?Hinv; eauto; apply dist_le with (S n); eauto. }\n  exists (rP ⋅ r); split; last by rewrite (left_id_L _ _) -assoc.\n  eapply uPred_weaken with (S k) rP; eauto using cmra_included_l.\nQed.\nLemma pvs_closeI i P : (ownI i P ∧ ▷ P) ⊑ (|={∅,{[i]}}=> True).\nProof.\n  rewrite pvs_eq. uPred.unseal; split=> -[|n] r ? [? HP] rf [|k] Ef σ ? HE ?; try lia.\n  exists ∅; split; [done|].\n  rewrite left_id; apply wsat_close with P r.\n  - apply ownI_spec, uPred_weaken with (S n) r; auto.\n  - set_solver +HE.\n  - by rewrite -(left_id_L ∅ (∪) Ef).\n  - apply uPred_weaken with n r; auto.\nQed.\nLemma pvs_ownG_updateP E m (P : iGst Λ Σ → Prop) :\n  m ~~>: P → ownG m ⊑ (|={E}=> ∃ m', ■ P m' ∧ ownG m').\nProof.\n  rewrite pvs_eq. intros Hup.\n  uPred.unseal; split=> -[|n] r ? /ownG_spec Hinv rf [|k] Ef σ ???; try lia.\n  destruct (wsat_update_gst k (E ∪ Ef) σ r rf m P) as (m'&?&?); eauto.\n  { apply cmra_includedN_le with (S n); auto. }\n  by exists (update_gst m' r); split; [exists m'; split; [|apply ownG_spec]|].\nQed.\nLemma pvs_allocI E P : ¬set_finite E → ▷ P ⊑ (|={E}=> ∃ i, ■ (i ∈ E) ∧ ownI i P).\nProof.\n  rewrite pvs_eq. intros ?; rewrite /ownI; uPred.unseal.\n  split=> -[|n] r ? HP rf [|k] Ef σ ???; try lia.\n  destruct (wsat_alloc k E Ef σ rf P r) as (i&?&?&?); auto.\n  { apply uPred_weaken with n r; eauto. }\n  exists (Res {[ i := to_agree (Next (iProp_unfold P)) ]} ∅ ∅).\n  split; [|done]. by exists i; split; rewrite /uPred_holds /=.\nQed.\n\n(** * Derived rules *)\nImport uPred.\nGlobal Instance pvs_mono' E1 E2 : Proper ((⊑) ==> (⊑)) (@pvs Λ Σ E1 E2).\nProof. intros P Q; apply pvs_mono. Qed.\nGlobal Instance pvs_flip_mono' E1 E2 :\n  Proper (flip (⊑) ==> flip (⊑)) (@pvs Λ Σ E1 E2).\nProof. intros P Q; apply pvs_mono. Qed.\nLemma pvs_trans' E P : (|={E}=> |={E}=> P) ⊑ (|={E}=> P).\nProof. apply pvs_trans; set_solver. Qed.\nLemma pvs_strip_pvs E P Q : P ⊑ (|={E}=> Q) → (|={E}=> P) ⊑ (|={E}=> Q).\nProof. move=>->. by rewrite pvs_trans'. Qed.\nLemma pvs_frame_l E1 E2 P Q : (P ★ |={E1,E2}=> Q) ⊑ (|={E1,E2}=> P ★ Q).\nProof. rewrite !(comm _ P); apply pvs_frame_r. Qed.\nLemma pvs_always_l E1 E2 P Q `{!AlwaysStable P} :\n  (P ∧ |={E1,E2}=> Q) ⊑ (|={E1,E2}=> P ∧ Q).\nProof. by rewrite !always_and_sep_l pvs_frame_l. Qed.\nLemma pvs_always_r E1 E2 P Q `{!AlwaysStable Q} :\n  ((|={E1,E2}=> P) ∧ Q) ⊑ (|={E1,E2}=> P ∧ Q).\nProof. by rewrite !always_and_sep_r pvs_frame_r. Qed.\nLemma pvs_impl_l E1 E2 P Q : (□ (P → Q) ∧ (|={E1,E2}=> P)) ⊑ (|={E1,E2}=> Q).\nProof. by rewrite pvs_always_l always_elim impl_elim_l. Qed.\nLemma pvs_impl_r E1 E2 P Q : ((|={E1,E2}=> P) ∧ □ (P → Q)) ⊑ (|={E1,E2}=> Q).\nProof. by rewrite comm pvs_impl_l. Qed.\nLemma pvs_wand_l E1 E2 P Q R :\n  P ⊑ (|={E1,E2}=> Q) → ((Q -★ R) ★ P) ⊑ (|={E1,E2}=> R).\nProof. intros ->. rewrite pvs_frame_l. apply pvs_mono, wand_elim_l. Qed.\nLemma pvs_wand_r E1 E2 P Q R :\n  P ⊑ (|={E1,E2}=> Q) → (P ★ (Q -★ R)) ⊑ (|={E1,E2}=> R).\nProof. rewrite comm. apply pvs_wand_l. Qed.\nLemma pvs_sep E P Q:\n  ((|={E}=> P) ★ (|={E}=> Q)) ⊑ (|={E}=> P ★ Q).\nProof. rewrite pvs_frame_r pvs_frame_l pvs_trans //. set_solver. Qed.\n\nLemma pvs_mask_frame' E1 E1' E2 E2' P :\n  E1' ⊆ E1 → E2' ⊆ E2 → E1 ∖ E1' = E2 ∖ E2' →\n  (|={E1',E2'}=> P) ⊑ (|={E1,E2}=> P).\nProof.\n  intros HE1 HE2 HEE.\n  rewrite (pvs_mask_frame _ _ (E1 ∖ E1')); last set_solver.\n  by rewrite {2}HEE -!union_difference_L.\nQed.\n\nLemma pvs_mask_frame_mono E1 E1' E2 E2' P Q :\n  E1' ⊆ E1 → E2' ⊆ E2 → E1 ∖ E1' = E2 ∖ E2' →\n  P ⊑ Q → (|={E1',E2'}=> P) ⊑ (|={E1,E2}=> Q).\nProof. intros HE1 HE2 HEE ->. by apply pvs_mask_frame'. Qed.\n\n(** It should be possible to give a stronger version of this rule\n   that does not force the conclusion view shift to have twice the\n   same mask. However, even expressing the side-conditions on the\n   mask becomes really ugly then, and we have not found an instance\n   where that would be useful. *)\nLemma pvs_trans3 E1 E2 Q :\n  E2 ⊆ E1 → (|={E1,E2}=> |={E2}=> |={E2,E1}=> Q) ⊑ (|={E1}=> Q).\nProof. intros HE. rewrite !pvs_trans; set_solver. Qed.\n\nLemma pvs_mask_weaken E1 E2 P : E1 ⊆ E2 → (|={E1}=> P) ⊑ (|={E2}=> P).\nProof. auto using pvs_mask_frame'. Qed.\n\nLemma pvs_ownG_update E m m' : m ~~> m' → ownG m ⊑ (|={E}=> ownG m').\nProof.\n  intros; rewrite (pvs_ownG_updateP E _ (m' =)); last by apply cmra_update_updateP.\n  by apply pvs_mono, uPred.exist_elim=> m''; apply uPred.const_elim_l=> ->.\nQed.\nEnd pvs.\n\n(** * Frame Shift Assertions. *)\n(* Yes, the name is horrible...\n   Frame Shift Assertions take a mask and a predicate over some type (that's\n   their \"postcondition\"). They support weakening the mask, framing resources\n   into the postcondition, and composition witn mask-changing view shifts. *)\nNotation FSA Λ Σ A := (coPset → (A → iProp Λ Σ) → iProp Λ Σ).\nClass FrameShiftAssertion {Λ Σ A} (fsaV : Prop) (fsa : FSA Λ Σ A) := {\n  fsa_mask_frame_mono E1 E2 Φ Ψ :\n    E1 ⊆ E2 → (∀ a, Φ a ⊑ Ψ a) → fsa E1 Φ ⊑ fsa E2 Ψ;\n  fsa_trans3 E Φ : (|={E}=> fsa E (λ a, |={E}=> Φ a)) ⊑ fsa E Φ;\n  fsa_open_close E1 E2 Φ :\n    fsaV → E2 ⊆ E1 → (|={E1,E2}=> fsa E2 (λ a, |={E2,E1}=> Φ a)) ⊑ fsa E1 Φ;\n  fsa_frame_r E P Φ : (fsa E Φ ★ P) ⊑ fsa E (λ a, Φ a ★ P)\n}.\n\nSection fsa.\nContext {Λ Σ A} (fsa : FSA Λ Σ A) `{!FrameShiftAssertion fsaV fsa}.\nImplicit Types Φ Ψ : A → iProp Λ Σ.\n\nLemma fsa_mono E Φ Ψ : (∀ a, Φ a ⊑ Ψ a) → fsa E Φ ⊑ fsa E Ψ.\nProof. apply fsa_mask_frame_mono; auto. Qed.\nLemma fsa_mask_weaken E1 E2 Φ : E1 ⊆ E2 → fsa E1 Φ ⊑ fsa E2 Φ.\nProof. intros. apply fsa_mask_frame_mono; auto. Qed.\nLemma fsa_frame_l E P Φ : (P ★ fsa E Φ) ⊑ fsa E (λ a, P ★ Φ a).\nProof. rewrite comm fsa_frame_r. apply fsa_mono=>a. by rewrite comm. Qed.\nLemma fsa_strip_pvs E P Φ : P ⊑ fsa E Φ → (|={E}=> P) ⊑ fsa E Φ.\nProof.\n  move=>->. rewrite -{2}fsa_trans3.\n  apply pvs_mono, fsa_mono=>a; apply pvs_intro.\nQed.\nLemma fsa_mono_pvs E Φ Ψ : (∀ a, Φ a ⊑ (|={E}=> Ψ a)) → fsa E Φ ⊑ fsa E Ψ.\nProof. intros. rewrite -[fsa E Ψ]fsa_trans3 -pvs_intro. by apply fsa_mono. Qed.\nEnd fsa.\n\nDefinition pvs_fsa {Λ Σ} : FSA Λ Σ () := λ E Φ, (|={E}=> Φ ())%I.\nInstance pvs_fsa_prf {Λ Σ} : FrameShiftAssertion True (@pvs_fsa Λ Σ).\nProof.\n  rewrite /pvs_fsa.\n  split; auto using pvs_mask_frame_mono, pvs_trans3, pvs_frame_r.\nQed.\n\nLemma pvs_mk_fsa {Λ Σ} E (P Q : iProp Λ Σ) :\n  P ⊑ pvs_fsa E (λ _, Q) →\n  P ⊑ |={E}=> Q.\nProof. by intros ?. Qed.\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/program_logic/pviewshifts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878414043816, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2787958516867447}}
{"text": "Require Export List.\nRequire Export Bool.\nRequire Export Arith.\nRequire Export Peano_dec.\nRequire Export Coq.Arith.PeanoNat.\nRequire Import CpdtTactics.\nRequire Export Coq.Program.Wf.\nRequire Export Coq.Program.Tactics.\nRequire Export Coq.Logic.FunctionalExtensionality.\nRequire Export Recdef.\nRequire Import wyv_common.\nSet Implicit Arguments.\n\n(*\nHere we model the case where an unseparated type on the left hand side, and\na pure material is on the the right hand side.\n\nHere we know that following the syntax and the subtype semantics of Decidable \nWyvern, every subsequent subtype check will feature a Material on the right \nhand side. We also know that if the left hand side is a shape, the only way \nto proceed \nwould require a shape refinement on the right hand side. As we have already \nnoted, this is not possible. Thus we can easily demonstrate termination as\nwithout shapes, cycles are not possible on the right hand side, and the \nalgorithm is thus bound by the finiteness of specified types.\n *)\n\nInductive tytree : Type :=\n| t_top : tytree\n| t_bot : tytree\n| t_sel_upp : var -> label -> tytree -> tytree\n| t_sel_low : var -> label -> tytree -> tytree\n| t_sel_equ : var -> label -> tytree -> tytree\n| t_sel_nom : var -> label -> tytree -> tytree\n| t_rfn_top : tytree -> tytree                         (*first tytree is actually a list of trees constructed by t_nil and t_con*)\n| t_rfn_sel : var -> label -> tytree -> tytree -> tytree  (*first tytree is actually a list of trees constructed by t_nil and t_con*)\n| t_sha_top : var -> label -> decls -> tytree\n| t_sha_sel : var -> label -> decls -> tytree -> tytree\n| t_all : tytree -> tytree -> tytree\n\n| t_upp : label -> tytree -> tytree\n| t_low : label -> tytree -> tytree\n| t_equ : label -> tytree -> tytree\n| t_nom : label -> ty -> tytree -> tytree\n\n| t_nil : tytree\n| t_con : tytree -> tytree -> tytree.\n\nInductive Tree (A: Set): Set :=\n| Leaf: A -> Tree A\n| Node: list (Tree A) -> Tree A.\n\nFixpoint bind' {A B:Set} (k:A -> Tree B) (m:Tree A) : Tree B :=\n  match m with\n  | Leaf a => k a\n  | Node ts => Node (map (bind' k) ts)\n  end.\n\nDefinition bind (A B:Set) m (k:A -> Tree B) := bind' k m.\n\nFixpoint shape_depth (T : tytree) : nat :=\n  match T with\n  | t_sel_upp x L T' => 1 + shape_depth T'\n  | t_sel_low x L T' => 1 + shape_depth T'\n  | t_sel_equ x L T' => 1 + shape_depth T'\n  | t_sel_nom x L T' => 1 + shape_depth T'\n  | t_rfn_top Ts => 1 + shape_depth Ts\n  | t_rfn_sel _ _ Ts T' => 1 + shape_depth Ts + shape_depth T'\n  | t_sha_sel _ _ _ T' => 1 + shape_depth T'\n  | t_all T1 T2 => 1 + shape_depth T1 + shape_depth T2\n                                                   \n  | t_upp _ T' => 1 + shape_depth T'\n  | t_low _ T' => 1 + shape_depth T'\n  | t_equ _ T' => 1 + shape_depth T'\n  | t_nom _ _ T' => 1 + shape_depth T'\n\n  | t_con T Ts => 1 + shape_depth T + shape_depth Ts\n                                 \n  | _ => 1\n  end.\n\nDefinition shape_depth_p (P : tytree * tytree) := let (T1, T2) := P in shape_depth T1 + shape_depth T2.\n\nFunction zip (Ts1 Ts2 : list tytree) : option (list (tytree * tytree)) :=\n  match Ts1, Ts2 with\n  | _, nil => Some nil\n  | T1::Ts1', T2::Ts2' => match zip Ts1' Ts2' with\n                         | None => None\n                         | Some Ps => Some ((T1, T2)::Ps)\n                         end\n  | nil, _::_ => None\n  end.\n\nCheck fold_right andb true (map negb nil).\nCompute fold_right andb true (map negb nil).\n\nFixpoint fold_mapb {A B : Type} (f : A * B -> bool) (Ps : list (A * B)) : bool :=\n  match Ps with\n  | nil => true\n  | P::Ps' => andb (f P) (fold_mapb f Ps')\n  end.\n\nDefinition zip_mapb {A B : Type} (f : A * B -> bool) (o : option (list (A * B))) : bool :=\n  match o with \n  | None => false\n  | Some Ps => fold_mapb f Ps\n  end.\n\n(*Definition map {A B} (xs : list A) (f : forall (x:A), In x xs -> B) : list B.\nProof.\n  induction xs.\n  exact nil.\n  refine (f a _ :: IHxs _).\n    - left. reflexivity.\n    - intros. eapply f. right. eassumption.\nDefined.*)\n\n(*Fixpoint map {A B} (xs : list A) : forall (f : forall (x:A), In x xs -> B), list B :=\n  match xs with\n   | nil => fun _ => nil\n   | x :: xs => fun f => f x (or_introl eq_refl) :: map xs (fun y h => f y (or_intror h))\n  end.*)\n\n(*forall P0 : tytree * tytree, shape_depth P0 < shape_depth P -> bool*)\n\nCheck in_cons.\n\nDefinition map_tree (P1 :  tytree * tytree)\n           (f : forall P2 : tytree * tytree, shape_depth_p P2 < shape_depth_p P1 -> bool)\n           (Ps : list (tytree * tytree))\n           (lt : forall P2 : tytree * tytree, In P2 Ps -> shape_depth_p P2 < shape_depth_p P1) : list bool.\nProof.\n  induction Ps.\n  exact nil.\n  assert (HIna : In a (a :: Ps));\n    [apply in_eq|apply lt in HIna].\n  refine (f a HIna :: IHPs _).\n  intros. apply lt, in_cons; auto.\nDefined.\n\n(*Fixpoint map  (P1 :  tytree * tytree)\n         (f : forall P2 : tytree * tytree, shape_depth P2 < shape_depth P1 -> bool)\n         (Ps : list (tytree * tytree))\n         (lt : forall P2 : tytree * tytree, In P2 Ps -> shape_depth P2 < shape_depth P1) : list bool :=\n  match Ps with\n  | nil => nil\n  | P::Ps' => (f P lt)::(map P1 f Ps' lt)\n  end.*)\n\nFixpoint eq_ty (t1 t2 : ty): bool :=\n  match t1, t2 with\n  | top, top => true\n  | bot, bot => true\n  | sel x1 L1 , sel x2 L2 => eq_var x1 x2 && eq_label L1 L2\n  | t1 str ss1 rts, t2 str ss2 rts => eq_ty t1 t2 && eq_decls ss1 ss2\n  | all t1 ∙ t1', all t2 ∙ t2' => eq_ty t1 t2 && eq_ty t1' t2'\n  | _, _ => false\n  end\n\nwith\neq_decl (s1 s2 : decl) : bool :=\n  match s1, s2 with \n  | type L1 ⩽ t1, type L2 ⩽ t2 => eq_label L1 L2 && eq_ty t1 t2\n  | type L1 ⩾ t1, type L2 ⩾ t2 => eq_label L1 L2 && eq_ty t1 t2\n  | type L1 ≝ t1, type L2 ≝ t2 => eq_label L1 L2 && eq_ty t1 t2\n  | type L1 ⪯ t1, type L2 ⪯ t2 => eq_label L1 L2 && eq_ty t1 t2\n  | _, _ => false\n  end\n\nwith\neq_decls (ss1 ss2 : decls) : bool :=\n  match ss1, ss2 with\n  | d_nil, d_nil => true\n  | d_con s1 ss1, d_con s2 ss2 => eq_decl s1 s2 && eq_decls ss1 ss2\n  | _, _ => false\n  end.\n\nFixpoint eq_tree_ty (T : tytree) (t : ty) : bool :=\n  match T, t with\n  | t_top, top => true\n  | t_bot, bot => true\n\n  | t_sel_upp x1 L1 _, sel x2 L2 => (eq_var x1 x2) && (eq_label L1 L2)\n              \n  | t_sel_low x1 L1 _, sel x2 L2 => (eq_var x1 x2) && (eq_label L1 L2)\n              \n  | t_sel_equ x1 L1 _, sel x2 L2 => (eq_var x1 x2) && (eq_label L1 L2)\n              \n  | t_sel_nom x1 L1 _, sel x2 L2 => (eq_var x1 x2) && (eq_label L1 L2)\n\n  | t_rfn_top Ds, (top str σs rts) => eq_tree_decls Ds σs\n                                                  \n\n  | t_rfn_sel x1 L1 Ds _, ((sel x2 L2) str σs rts) => (eq_var x1 x2) && (eq_label L1 L2) && (eq_tree_decls Ds σs)\n\n  | t_sha_top x1 L1 σs1, ((sel x2 L2) str σs2 rts) => (eq_var x1 x2) && (eq_label L1 L2) && (eq_decls σs1 σs2)\n\n  | t_sha_sel x1 L1 σs1 _, ((sel x2 L2) str σs2 rts) => (eq_var x1 x2) && (eq_label L1 L2) && (eq_decls σs1 σs2)\n\n\n  | t_all T1 T2, all t1 ∙ t2 => (eq_tree_ty T1 t1) && (eq_tree_ty T2 t2)\n                                                                      \n                   \n  | _, _ => false\n  end\n\nwith\neq_tree_decl (D : tytree) (σ : decl) : bool :=\n  match D, σ with\n  | t_upp L1 T, type L2 ⩽ t => andb (eq_label L1 L2) (eq_tree_ty T t)\n  | t_low L1 T, type L2 ⩾ t => andb (eq_label L1 L2) (eq_tree_ty T t)\n  | t_equ L1 T, type L2 ≝ t => andb (eq_label L1 L2) (eq_tree_ty T t)\n  | t_nom L1  _ T, type L2 ⪯ t => andb (eq_label L1 L2) (eq_tree_ty T t)\n  | _, _ => false\n  end\n\nwith\neq_tree_decls (Ds : tytree)(σs : decls) : bool :=\n  match Ds, σs with\n  | t_nil, d_nil => true\n  | t_con D Ds', d_con σ σs' => andb (eq_tree_decl D σ) (eq_tree_decls Ds' σs')\n  | _, _ => false\n  end.\n\nFixpoint eq_tree (T1 T2 : tytree) : bool :=\n  match T1, T2 with\n  | t_top, t_top => true\n              \n  | t_bot, t_bot => true\n\n                     \n              \n  | t_sel_upp x1 L1 T1', t_sel_upp x2 L2 T2' => (eq_var x1 x2) && (eq_label L1 L2)\n              \n  | t_sel_upp x1 L1 T1', t_sel_low x2 L2 T2' => (eq_var x1 x2) && (eq_label L1 L2)\n              \n  | t_sel_upp x1 L1 T1', t_sel_equ x2 L2 T2' => (eq_var x1 x2) && (eq_label L1 L2)\n              \n  | t_sel_upp x1 L1 T1', t_sel_nom x2 L2 T2' => (eq_var x1 x2) && (eq_label L1 L2)\n                                                              \n              \n  | t_sel_low x1 L1 T1', t_sel_upp x2 L2 T2' => (eq_var x1 x2) && (eq_label L1 L2)\n              \n  | t_sel_low x1 L1 T1', t_sel_low x2 L2 T2' => (eq_var x1 x2) && (eq_label L1 L2)\n              \n  | t_sel_low x1 L1 T1', t_sel_equ x2 L2 T2' => (eq_var x1 x2) && (eq_label L1 L2)\n              \n  | t_sel_low x1 L1 T1', t_sel_nom x2 L2 T2' => (eq_var x1 x2) && (eq_label L1 L2)\n                                                              \n              \n  | t_sel_equ x1 L1 T1', t_sel_upp x2 L2 T2' => (eq_var x1 x2) && (eq_label L1 L2)\n              \n  | t_sel_equ x1 L1 T1', t_sel_low x2 L2 T2' => (eq_var x1 x2) && (eq_label L1 L2)\n              \n  | t_sel_equ x1 L1 T1', t_sel_equ x2 L2 T2' => (eq_var x1 x2) && (eq_label L1 L2)\n              \n  | t_sel_equ x1 L1 T1', t_sel_nom x2 L2 T2' => (eq_var x1 x2) && (eq_label L1 L2)\n                                                              \n              \n  | t_sel_nom x1 L1 T1', t_sel_upp x2 L2 T2' => (eq_var x1 x2) && (eq_label L1 L2)\n              \n  | t_sel_nom x1 L1 T1', t_sel_low x2 L2 T2' => (eq_var x1 x2) && (eq_label L1 L2)\n              \n  | t_sel_nom x1 L1 T1', t_sel_equ x2 L2 T2' => (eq_var x1 x2) && (eq_label L1 L2)\n              \n  | t_sel_nom x1 L1 T1', t_sel_nom x2 L2 T2' => (eq_var x1 x2) && (eq_label L1 L2)\n\n\n                                                              \n                                                              \n      \n  | t_all Ta1 Tb1, t_all Ta2 Tb2 => (eq_tree Ta1 Ta2) && (eq_tree Tb1 Tb2)\n\n\n\n\n                                                     \n\n  | t_rfn_top Ts1, t_rfn_top Ts2 => (eq_tree Ts1 Ts2)\n\n                                     \n\n  | t_rfn_sel x1 L1 Ts1 T1', t_rfn_sel x2 L2 Ts2 T2' => (eq_var x1 x2) && (eq_label L1 L2) && (eq_tree Ts1 Ts2)\n\n  | t_rfn_sel x1 L1 Ts1 T1', t_sha_top x2 L2 ss2 => (eq_var x1 x2) && (eq_label L1 L2) && (eq_tree_decls Ts1 ss2)\n\n  | t_rfn_sel x1 L1 Ts1 T1', t_sha_sel x2 L2 ss2 T2' => (eq_var x1 x2) && (eq_label L1 L2) && (eq_tree_decls Ts1 ss2)\n\n                                     \n\n  | t_sha_top x1 L1 ss1, t_rfn_sel x2 L2 Ts2 T2' => (eq_var x1 x2) && (eq_label L1 L2) && (eq_tree_decls Ts2 ss1)\n\n  | t_sha_top x1 L1 ss1, t_sha_top x2 L2 ss2 => (eq_var x1 x2) && (eq_label L1 L2) && (eq_decls ss1 ss2)\n\n  | t_sha_top x1 L1 ss1, t_sha_sel x2 L2 ss2 T2' => (eq_var x1 x2) && (eq_label L1 L2) && (eq_decls ss1 ss2)\n\n                                     \n\n  | t_sha_sel x1 L1 ss1 T1', t_rfn_sel x2 L2 Ts2 T2' => (eq_var x1 x2) && (eq_label L1 L2) && (eq_tree_decls Ts2 ss1)\n\n  | t_sha_sel x1 L1 ss1 T1', t_sha_top x2 L2 ss2 => (eq_var x1 x2) && (eq_label L1 L2) && (eq_decls ss1 ss2)\n\n  | t_sha_sel x1 L1 ss1 T1', t_sha_sel x2 L2 ss2 T2' => (eq_var x1 x2) && (eq_label L1 L2) && (eq_decls ss1 ss2)\n\n\n                                                                      \n      \n  | t_upp L1 T1', t_upp L2 T2' => (eq_label L1 L2) && (eq_tree T1' T2')\n      \n  | t_low L1 T1', t_low L2 T2' => (eq_label L1 L2) && (eq_tree T1' T2')\n      \n  | t_equ L1 T1', t_equ L2 T2' => (eq_label L1 L2) && (eq_tree T1' T2')\n      \n  | t_nom L1 _ T1', t_nom L2 _ T2' => (eq_label L1 L2) && (eq_tree T1' T2')\n              \n  | t_nil, t_nil => true\n              \n  | t_con T1' Ts1, t_con T2' Ts2 => (eq_tree T1' T2') && (eq_tree Ts1 Ts2)\n  | _, _ => false\n  end.\n\n(*Fixpoint eq_tree (T1 T2 : tytree) : bool :=\n  match T1, T2 with\n  | t_top, t_top => true\n              \n  | t_bot, t_bot => true\n              \n  | t_sel_upp x1 L1 T1', t_sel_upp x2 L2 T2' => (eq_var x1 x2) && (eq_label L1 L2) && (eq_tree T1' T2')\n              \n  | t_sel_low x1 L1 T1', t_sel_low x2 L2 T2' => (eq_var x1 x2) && (eq_label L1 L2) && (eq_tree T1' T2')\n              \n  | t_sel_equ x1 L1 T1', t_sel_equ x2 L2 T2' => (eq_var x1 x2) && (eq_label L1 L2) && (eq_tree T1' T2')\n              \n  | t_sel_nom x1 L1 T1', t_sel_nom x2 L2 T2' => (eq_var x1 x2) && (eq_label L1 L2) && (eq_tree T1' T2')\n      \n  | t_all Ta1 Tb1, t_all Ta2 Tb2 => (eq_tree Ta1 Ta2) && (eq_tree Tb1 Tb2)\n\n  | t_rfn_top Ts1, t_rfn_top Ts2 => (eq_tree Ts1 Ts2)\n\n  | t_rfn_sel x1 L1 Ts1 T1', t_rfn_sel x2 L2 Ts2 T2' => (eq_var x1 x2) && (eq_label L1 L2) && (eq_tree Ts1 Ts2) && (eq_tree T1' T2')\n\n  | t_sha_top x1 L1 ss1, t_sha_top x2 L2 ss2 => (eq_var x1 x2) && (eq_label L1 L2) && (eq_decls ss1 ss2)\n\n  | t_sha_sel x1 L1 ss1 T1', t_sha_sel x2 L2 ss2 T2' => (eq_var x1 x2) && (eq_label L1 L2) && (eq_decls ss1 ss2) && (eq_tree T1' T2')\n      \n  | t_upp L1 T1', t_upp L2 T2' => (eq_label L1 L2) && (eq_tree T1' T2')\n      \n  | t_low L1 T1', t_low L2 T2' => (eq_label L1 L2) && (eq_tree T1' T2')\n      \n  | t_equ L1 T1', t_equ L2 T2' => (eq_label L1 L2) && (eq_tree T1' T2')\n      \n  | t_nom L1 T1', t_nom L2 T2' => (eq_label L1 L2) && (eq_tree T1' T2')\n              \n  | t_nil, t_nil => true\n              \n  | t_con T1' Ts1, t_con T2' Ts2 => (eq_tree T1' T2') && (eq_tree Ts1 Ts2)\n  | _, _ => false\n  end.*)\n\nParameter eq_tree_refl :\n  forall T, eq_tree T T = true.\n\nParameter eqb_tree_eq :\n  forall T1 T2, eq_tree T1 T2 = true ->\n           T1 = T2.\n\nParameter neqb_tree_neq :\n  forall T1 T2, eq_tree T1 T2 = false ->\n           T1 <> T2.\n\nParameter eq_tree_dec :\n  forall T1 T2, {eq_tree T1 T2 = true} + {eq_tree T1 T2 = false}.\n    \n\nProgram Fixpoint subtype (T1 T2 : tytree) {measure (shape_depth T1 + shape_depth T2)} : bool :=  \n  match T1 with\n  | t_top => match T2 with\n            | t_top => true\n            | t_sel_low x L T2' => subtype T1 T2'\n            | t_sel_equ x L T2' => subtype T1 T2'\n            | _ => false\n            end\n              \n  | t_bot => match T2 with\n            | t_upp _ _ => false\n            | t_low _ _ => false\n            | t_equ _ _ => false\n            | t_nom _ _ _ => false\n            | t_nil     => false\n            | t_con _ _ => false\n            | _ => true\n            end\n                          \n  | t_sel_upp x1 L1 T1' => match T2 with\n                          | t_top => true\n                          | t_sel_low x2 L2 T2' => orb (andb (eq_var x1 x2) (eq_label L1 L2)) (orb (subtype T1' T2) (subtype T1 T2'))\n                          | t_sel_equ x2 L2 T2' => orb (andb (eq_var x1 x2) (eq_label L1 L2)) (orb (subtype T1' T2) (subtype T1 T2'))\n                          | t_sel_upp x2 L2 _ => orb (andb (eq_var x1 x2) (eq_label L1 L2)) (subtype T1' T2)\n                          | t_sel_nom x2 L2 _ => orb (andb (eq_var x1 x2) (eq_label L1 L2)) (subtype T1' T2)\n                          | t_upp L2 T2' => false\n                          | t_low L2 T2' => false\n                          | t_equ L2 T2' => false\n                          | t_nom L2 _ T2' => false\n                          | t_nil     => false\n                          | t_con _ _ => false\n                          | _ => subtype T1' T2\n                          end\n                          \n  | t_sel_equ x1 L1 T1' => match T2 with\n                          | t_top => true\n                          | t_sel_low x2 L2 T2' => orb (andb (eq_var x1 x2) (eq_label L1 L2)) (orb (subtype T1' T2) (subtype T1 T2'))\n                          | t_sel_equ x2 L2 T2' => orb (andb (eq_var x1 x2) (eq_label L1 L2)) (orb (subtype T1' T2) (subtype T1 T2'))\n                          | t_sel_upp x2 L2 _ => orb (andb (eq_var x1 x2) (eq_label L1 L2)) (subtype T1' T2)\n                          | t_sel_nom x2 L2 _ => orb (andb (eq_var x1 x2) (eq_label L1 L2)) (subtype T1' T2)\n                          | t_upp L2 T2' => false\n                          | t_low L2 T2' => false\n                          | t_equ L2 T2' => false\n                          | t_nom L2 _ T2' => false\n                          | t_nil     => false\n                          | t_con _ _ => false\n                          | _ => subtype T1' T2\n                          end\n                          \n  | t_sel_nom x1 L1 T1' => match T2 with\n                          | t_top => true\n                          | t_sel_low x2 L2 T2' => orb (andb (eq_var x1 x2) (eq_label L1 L2)) (orb (subtype T1' T2) (subtype T1 T2'))\n                          | t_sel_equ x2 L2 T2' => orb (andb (eq_var x1 x2) (eq_label L1 L2)) (orb (subtype T1' T2) (subtype T1 T2'))\n                          | t_sel_upp x2 L2 _ => orb (andb (eq_var x1 x2) (eq_label L1 L2)) (subtype T1' T2)\n                          | t_sel_nom x2 L2 _ => orb (andb (eq_var x1 x2) (eq_label L1 L2)) (subtype T1' T2)\n                          | t_upp L2 T2' => false\n                          | t_low L2 T2' => false\n                          | t_equ L2 T2' => false\n                          | t_nom L2 _ T2' => false\n                          | t_nil     => false\n                          | t_con _ _ => false\n                          | _ => subtype T1' T2\n                          end\n                          \n  | t_sel_low x1 L1 T1' => match T2 with\n                          | t_top => true\n                          | t_sel_low x2 L2 T2' => orb (andb (eq_var x1 x2) (eq_label L1 L2)) (subtype T1 T2')\n                          | t_sel_equ x2 L2 T2' => orb (andb (eq_var x1 x2) (eq_label L1 L2)) (subtype T1 T2')\n                          | t_sel_upp x2 L2 _ => andb (eq_var x1 x2) (eq_label L1 L2)\n                          | t_sel_nom x2 L2 _ => andb (eq_var x1 x2) (eq_label L1 L2)\n                          | _ => false\n                          end\n\n  | t_rfn_top Ts1 => match T2 with\n                    | t_top => true\n                    | t_sel_low x L T => subtype T1 T\n                    | t_sel_equ x L T => subtype T1 T\n                    | t_rfn_top Ts2 => subtype Ts1 Ts2\n                    | _ => false\n                    end\n\n  | t_rfn_sel x1 L1 Ts1 T' => match T2 with\n                             | t_top => true\n                             | t_sel_low x L T => orb (subtype T1 T)\n                                                     (subtype T' T2)\n                             | t_sel_equ x L T => orb (subtype T1 T)\n                                                     (subtype T' T2)\n                             | t_rfn_top _ => subtype T' T2\n                             | t_rfn_sel x2 L2 Ts2 _ => orb (andb ((andb (eq_var x1 x2) (eq_label L1 L2)))\n                                                                 (subtype Ts1 Ts2))\n                                                           (subtype T' T2)\n                             | t_upp _ _ => false\n                             | t_low _ _ => false\n                             | t_equ _ _ => false\n                             | t_nom _ _ _ => false\n                             | t_nil => false\n                             | t_con _ _ => false\n                                             \n                             | _ => subtype T' T2\n                             end\n\n  | t_sha_top _ _ _ => match T2 with\n                      | t_top => true\n                      | t_sel_low x L T => subtype T1 T\n                      | t_sel_equ x L T => subtype T1 T\n                      | _ => false\n                      end\n\n  | t_sha_sel _ _ _ T' => match T2 with\n                         | t_top => true\n                         | t_sel_low x L T => orb (subtype T1 T)\n                                                 (subtype T' T2)\n                         | t_sel_equ x L T => orb (subtype T1 T)\n                                                 (subtype T' T2)\n                         | t_upp _ _ => false\n                         | t_low _ _ => false\n                         | t_equ _ _ => false\n                         | t_nom _ _ _ => false\n                         | t_nil => false\n                         | t_con _ _ => false\n                                         \n                         | _ => subtype T' T2\n                         end\n\n  | t_all Ta1 Tb1 => match T2 with\n                    | t_top => true\n                    | t_sel_low x L T => subtype T1 T\n                    | t_sel_equ x L T => subtype T1 T\n                    | t_all Ta2 Tb2 => andb (subtype Ta2 Ta1) (subtype Tb1 Tb2)\n                    | _ => false\n                    end\n\n  | t_upp L1 T1' => match T2 with\n                   | t_upp L2 T2' => andb (eq_label L1 L2)\n                                         (subtype T1' T2')\n                   | _ => false\n                   end\n\n  | t_low L1 T1' => match T2 with\n                   | t_low L2 T2' => andb (eq_label L1 L2)\n                                         (subtype T2' T1')\n                   | _ => false\n                   end\n\n  | t_equ L1 T1' => match T2 with\n                   | t_upp L2 T2' => andb (eq_label L1 L2)\n                                         (subtype T1' T2')\n                   | t_low L2 T2' => andb (eq_label L1 L2)\n                                         (subtype T2' T1')\n                   | t_equ L2 T2' => andb (eq_label L1 L2)\n                                         (andb (subtype T1' T2')\n                                               (subtype T2' T1'))\n                   | _ => false\n                   end\n\n  | t_nom L1 t1 T1' => match T2 with\n                   | t_upp L2 T2' => andb (eq_label L1 L2)\n                                         (subtype T1' T2')\n                   | t_nom L2 t2 T2' => (eq_label L1 L2) && eq_ty t1 t2\n                   | _ => false\n                   end\n\n  | t_nil => match T2 with\n            | t_nil => true\n            | _ => false\n            end\n\n  | t_con T1' Ts1 => match T2 with\n                   | t_nil => true\n                   | t_con T2' Ts2 => andb (subtype T1' T2') (subtype Ts1 Ts2)\n                   | _ => false\n                   end\n                     \n  end.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  simpl.\n  destruct T1'; crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  destruct T1'; crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  destruct T'; crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  destruct T';\n    crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\nNext Obligation.\n  crush.\nDefined.\n\nImport WfExtensionality.\n\nLemma subtype_top :\n  forall T, (forall L T', T <> t_upp L T') ->\n       (forall L T', T <> t_low L T') ->\n       (forall L T', T <> t_equ L T') ->\n       (forall L t' T', T <> t_nom L t' T') ->\n       (T <> t_nil) ->\n       (forall T' Ts, T <> t_con T' Ts) ->\n       subtype T t_top = true.\nProof.\n  intros.\n\n  unfold subtype, subtype_func;\n    simpl;\n    rewrite fix_sub_eq_ext;\n    simpl;\n    fold subtype_func;\n    auto.\n\n  destruct T; simpl; auto.\n  \n  contradiction (H l T); auto.\n  contradiction (H0 l T); auto.\n  contradiction (H1 l T); auto.\n  contradiction (H2 l t T); auto.\n  contradiction (H3); auto.\n  contradiction (H4 T1 T2); auto.\nQed.\n\nLemma subtype_bot :\n  forall T, (forall L T', T <> t_upp L T') ->\n       (forall L T', T <> t_low L T') ->\n       (forall L T', T <> t_equ L T') ->\n       (forall L t' T', T <> t_nom L t' T') ->\n       (T <> t_nil) ->\n       (forall T' Ts, T <> t_con T' Ts) ->\n       subtype t_bot T = true.\nProof.\n  intros.\n\n  unfold subtype, subtype_func;\n    simpl;\n    rewrite fix_sub_eq_ext;\n    simpl;\n    fold subtype_func;\n    auto.\n\n  destruct T; simpl; auto.\n  \n  contradiction (H l T); auto.\n  contradiction (H0 l T); auto.\n  contradiction (H1 l T); auto.\n  contradiction (H2 l t T); auto.\n  contradiction (H3); auto.\n  contradiction (H4 T1 T2); auto.\nQed.", "meta": {"author": "JulianMackay", "repo": "Wyvern_Formalism", "sha": "7072f2803b500c73c42347544740768e81a8beca", "save_path": "github-repos/coq/JulianMackay-Wyvern_Formalism", "path": "github-repos/coq/JulianMackay-Wyvern_Formalism/Wyvern_Formalism-7072f2803b500c73c42347544740768e81a8beca/wfix/rhs_mat_tree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878414043814, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.27879585168674464}}
{"text": "(*Inductive mFalse :=.\nCheck mFalse_rect.*)\nUnset Elimination Schemes.\nInductive mFalse :=.\n\nDefinition mFalse_rect : forall (P : mFalse -> Type) (m : mFalse), P m.\nintros P m.\ndestruct m.\nShow Proof.\n\nInductive mTrue \nUnset Elimination Schemes.\n", "meta": {"author": "georgydunaev", "repo": "TRASH", "sha": "36b24517b8c51817e1b8eb39df945d30c287162b", "save_path": "github-repos/coq/georgydunaev-TRASH", "path": "github-repos/coq/georgydunaev-TRASH/TRASH-36b24517b8c51817e1b8eb39df945d30c287162b/SHEN/FIRST_VARIANT/ELIM_SCHEMA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2786486858707342}}
{"text": "Require Import Coq.Strings.Ascii.\nRequire Import Fiat.Common.Enumerable.\nRequire Import Fiat.Common.Enumerable.BoolProp.\nRequire Import Fiat.Common.List.Operations.\nRequire Import Fiat.Common.List.FlattenList.\nRequire Import Fiat.Common.List.ListFacts.\nRequire Import Fiat.Common.Equality.\nRequire Import Fiat.Common.StringOperations.\nRequire Import Fiat.Common.StringFacts.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.ContextFreeGrammar.PreNotations.\nRequire Import Fiat.Common.Gensym.\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  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  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": "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/Carriers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.27864868002110077}}
{"text": "From Coqprime Require Import PocklingtonRefl.\nLocal Open Scope positive_scope.\nRequire Import  p11_0.\nRequire Import  p11_1.\nRequire Import  p11_2.\nRequire Import  p11_3.\nRequire Import  p11_4.\nRequire Import  p11_5.\nRequire Import  p11_6.\nRequire Import  p11_7.\nRequire Import  p11_8.\nRequire Import  p11_9.\nRequire Import  p11_10.\nRequire Import  p11_11.\nRequire Import  p11_12.\nRequire Import  p11_13.\nRequire Import  p11_14.\nRequire Import  p11_15.\nRequire Import  p11_16.\nRequire Import  p11_17.\nRequire Import  p11_18.\nRequire Import  p11_19.\nRequire Import  p11_20.\nRequire Import  p11_21.\nRequire Import  p11_22.\nRequire Import  p11_23.\nRequire Import  p11_24.\nRequire Import  p11_25.\nRequire Import  p11_26.\nRequire Import  p11_27.\nRequire Import  p11_28.\nRequire Import  p11_29.\nRequire Import  p11_30.\nRequire Import  p11_31.\nRequire Import  p11_32.\nRequire Import  p11_33.\nRequire Import  p11_34.\nRequire Import  p11_35.\nRequire Import  p11_36.\nRequire Import  p11_37.\nRequire Import  p11_38.\nRequire Import  p11_39.\nRequire Import  p11_40.\nRequire Import  p11_41.\nRequire Import  p11_42.\nRequire Import  p11_43.\nRequire Import  p11_44.\nRequire Import  p11_45.\nRequire Import  p11_46.\nRequire Import  p11_47.\nRequire Import  p11_48.\nRequire Import  p11_49.\nRequire Import  p11_50.\nRequire Import  p11_51.\nRequire Import  p11_52.\nRequire Import  p11_53.\nRequire Import  p11_54.\nRequire Import  p11_55.\nRequire Import  p11_56.\nRequire Import  p11_57.\nRequire Import  p11_58.\nRequire Import  p11_59.\nRequire Import  p11_60.\nRequire Import  p11_61.\nRequire Import  p11_62.\nRequire Import  p11_63.\nRequire Import  p11_64.\nRequire Import  p11_65.\nRequire Import  p11_66.\nRequire Import  p11_67.\nRequire Import  p11_68.\nRequire Import  p11_69.\nRequire Import  p11_70.\nRequire Import  p11_71.\nRequire Import  p11_72.\nRequire Import  p11_73.\nRequire Import  p11_74.\nRequire Import  p11_75.\nRequire Import  p11_76.\nRequire Import  p11_77.\nRequire Import  p11_78.\nRequire Import  p11_79.\nRequire Import  p11_80.\nRequire Import  p11_81.\nRequire Import  p11_82.\nRequire Import  p11_83.\nRequire Import  p11_84.\nRequire Import  p11_85.\nRequire Import  p11_86.\nRequire Import  p11_87.\nRequire Import  p11_88.\nRequire Import  p11_89.\nRequire Import  p11_90.\nRequire Import  p11_91.\nRequire Import  p11_92.\nRequire Import  p11_93.\nRequire Import  p11_94.\nRequire Import  p11_95.\nRequire Import  p11_96.\nRequire Import  p11_97.\nRequire Import  p11_98.\nRequire Import  p11_99.\nRequire Import  p11_100.\nRequire Import  p11_101.\nRequire Import  p11_102.\nRequire Import  p11_103.\nRequire Import  p11_104.\nRequire Import  p11_105.\nRequire Import  p11_106.\nRequire Import  p11_107.\nRequire Import  p11_108.\nRequire Import  p11_109.\nRequire Import  p11_110.\nRequire Import  p11_111.\nRequire Import  p11_112.\nRequire Import  p11_113.\nRequire Import  p11_114.\nRequire Import  p11_115.\nRequire Import  p11_116.\nRequire Import  p11_117.\nRequire Import  p11_118.\nRequire Import  p11_119.\nRequire Import  p11_120.\nRequire Import  p11_121.\nRequire Import  p11_122.\n\nLemma  primo: prime 3563460728101118298229371115865970481044819223675200285275488632043525832262132249539830178755274741587837088015967729069590355645254412149985554902590736107673878699603023839312818401354719067107751421298039868676536138879187429498361351047753425236506091250888523693233395165252850631412794910629424929608098207781383646407138888952240245227717506820102107998986149323111996203607988470169649137242461140780302116452239343784545884848055714409006993475687995140188893391435363343214421654991280601382598565844648511024684919160392624395401288646923527005429511313993248781257994597340472567957348232037403808167633263995759576462321510959968224378012092370943925101232418885996274881788074601638717665313611181497934117962479902901702277391997459499382130878521678662811797039134302560667298323527656111492988711007388606096914990586514343033859123027480915922660863474758445608891045651988847977972184220169617081550670659.\nProof.\nexact\n(primo0 (primo1 (primo2 (primo3 (primo4 (primo5 (primo6 (primo7 (primo8 (primo9 (primo10 (primo11 (primo12 (primo13 (primo14 (primo15 (primo16 (primo17 (primo18 (primo19 (primo20 (primo21 (primo22 (primo23 (primo24 (primo25 (primo26 (primo27 (primo28 (primo29 (primo30 (primo31 (primo32 (primo33 (primo34 (primo35 (primo36 (primo37 (primo38 (primo39 (primo40 (primo41 (primo42 (primo43 (primo44 (primo45 (primo46 (primo47 (primo48 (primo49 (primo50 (primo51 (primo52 (primo53 (primo54 (primo55 (primo56 (primo57 (primo58 (primo59 (primo60 (primo61 (primo62 (primo63 (primo64 (primo65 (primo66 (primo67 (primo68 (primo69 (primo70 (primo71 (primo72 (primo73 (primo74 (primo75 (primo76 (primo77 (primo78 (primo79 (primo80 (primo81 (primo82 (primo83 (primo84 (primo85 (primo86 (primo87 (primo88 (primo89 (primo90 (primo91 (primo92 (primo93 (primo94 (primo95 (primo96 (primo97 (primo98 (primo99 (primo100 (primo101 (primo102 (primo103 (primo104 (primo105 (primo106 (primo107 (primo108 (primo109 (primo110 (primo111 (primo112 (primo113 (primo114 (primo115 (primo116 (primo117 (primo118 (primo119 (primo120 (primo121 primo122)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))).\nQed.\n", "meta": {"author": "mukeshtiwari", "repo": "Formally_Verified_Verifiable_Group_Generator", "sha": "e80e8d43e81b5201d6ab82a8ebc07a5cef03476b", "save_path": "github-repos/coq/mukeshtiwari-Formally_Verified_Verifiable_Group_Generator", "path": "github-repos/coq/mukeshtiwari-Formally_Verified_Verifiable_Group_Generator/Formally_Verified_Verifiable_Group_Generator-e80e8d43e81b5201d6ab82a8ebc07a5cef03476b/primality/p11.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2786053499561816}}
{"text": "Require Export Db.Spec.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Export Coq.Program.Equality.\nRequire Export Coq.Program.Tactics.\n\nModule Type Kit.\n\n  Parameter TM: Type.\n  Declare Instance inst_vr: Vr TM.\n  Declare Instance inst_ap: ∀ Y {vrY: Vr Y} {wkY: Wk Y} {liftY: Lift Y TM}, Ap TM Y.\n\n  Declare Instance inst_ap_inj: LemApInj (apXY := inst_ap Ix) TM Ix.\n  Declare Instance inst_ap_vr:\n    ∀ Y {vrY: Vr Y} {wkY: Wk Y} {liftY: Lift Y TM}, LemApVr TM Y.\n  Parameter inst_ap_comp:\n    ∀ Y Z {vrY: Vr Y} {wkY: Wk Y} {liftY: Lift Y TM} {vrZ: Vr Z} {wkZ: Wk Z}\n      {liftZ: Lift Z TM} {apYZ: Ap Y Z} {compUpYZ: LemCompUp Y Z}\n      {apLiftYZTM: LemApLift Y Z TM}, LemApComp TM Y Z.\n  Parameter inst_ap_liftSub:\n    ∀ Y {vrY: Vr Y} {wkY: Wk Y} {liftY: Lift Y TM}, LemApLiftSub TM Y.\n  Parameter inst_ap_ixComp:\n    ∀ (t: TM) (ξ: Sub Ix) (ζ: Sub TM), t[ξ][ζ] = t[⌈ξ⌉ >=> ζ].\n\nEnd Kit.\n\nModule Inst (kit: Kit).\n\n  Local Ltac crush :=\n    intros; cbn in * |-;\n    repeat\n      (cbn;\n       repeat crushDbSyntaxMatchH;\n       rewrite ?ap_vr, ?ap_comp);\n    auto.\n\n  Import kit.\n  Existing Instance inst_ap.\n  Existing Instance inst_ap_vr.\n  Existing Instance inst_ap_inj.\n  Existing Instance inst_ap_comp.\n  Existing Instance inst_ap_liftSub.\n\n\n  Instance inst_apTMZTM {Z} {vrZ: Vr Z} {apTMZ: Ap TM Z} :\n    LemApLift TM Z TM := λ _ _, eq_refl.\n  Instance inst_apLiftIxIx: LemApLift Ix Ix TM := ap_vr.\n\n  #[refine] Instance compUpTMIx: LemCompUp TM Ix := {}.\n  Proof. intros; extensionality i; destruct i; crush. Qed.\n\n  Instance inst_wkApIx: LemApWk TM Ix := λ _, eq_refl.\n\n  #[refine] Instance compUpTM: LemCompUp TM TM := {}.\n  Proof.\n    intros; extensionality i; destruct i; crush.\n    rewrite inst_ap_ixComp; f_equal.\n    extensionality j; destruct j; crush.\n  Qed.\n\n  #[refine] Instance wkApTM: LemApWk TM TM := {}.\n  Proof.\n    crush.\n    rewrite  <- ap_liftSub.\n    f_equal.\n    extensionality i; crush.\n  Qed.\n\n  (* Instance sbTM: Subst TM := {}. *)\n\n  (* Automatically populate the infrastructure database for type TM with lemmas\n     for which the rewrite direction is certain. *)\n  (* Hint Rewrite (apply_wkm_comm TM Ix) : infrastructure. *)\n  (* Hint Rewrite (apply_wkm_beta1_cancel TM TM) : infrastructure. *)\n  (* Hint Rewrite (apply_beta1_comm TM TM) : infrastructure. *)\n\n  (* Hint Rewrite (apply_wkm_up_comm TM Ix) : infrastructure. *)\n  (* Hint Rewrite (apply_wkm_beta1_up_cancel TM TM) : infrastructure. *)\n  (* Hint Rewrite (apply_beta1_up_comm TM TM) : infrastructure. *)\n\n  (* Hint Rewrite (apply_wkm_up2_comm TM Ix) : infrastructure. *)\n  (* Hint Rewrite (apply_wkm_beta1_up2_cancel TM TM) : infrastructure. *)\n  (* Hint Rewrite (apply_beta1_up2_comm TM TM) : infrastructure. *)\n\n  (* Hint Rewrite (apply_wkm_ups_comm TM Ix) : infrastructure. *)\n  (* Hint Rewrite (apply_wkm_beta1_ups_cancel TM TM) : infrastructure. *)\n  (* Hint Rewrite (apply_beta1_ups_comm TM TM) : infrastructure. *)\n\n  (* Hint Rewrite (ap_liftSub' TM TM) : infrastructure. *)\n  (* Hint Rewrite (up_liftSub TM) : infrastructure. *)\n  (* Hint Rewrite (liftSub_wkm TM) : infrastructure. *)\n  (* Hint Rewrite (liftSub_wkms TM) : infrastructure. *)\n\n  (* Hint Rewrite (up_wk TM) : infrastructure. *)\n  (* Hint Rewrite (wk_ap TM) : infrastructure. *)\n\n  (* Set Printing  Implicit. *)\n  (* Unset Printing Notations. *)\n  (* Print Rewrite HintDb infrastructure. *)\n\n\nEnd Inst.\n", "meta": {"author": "dominiquedevriese", "repo": "facomp-stlc-coq", "sha": "77043e68813d3a7ed8926802191638f063de1544", "save_path": "github-repos/coq/dominiquedevriese-facomp-stlc-coq", "path": "github-repos/coq/dominiquedevriese-facomp-stlc-coq/facomp-stlc-coq-77043e68813d3a7ed8926802191638f063de1544/Db/Inst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.4921881357207955, "lm_q1q2_score": 0.2785876148278969}}
{"text": "Require Import Lia List.\nImport ListNotations.\nFrom Minirust.def Require Import ty encoding le.\nFrom Minirust.proof.lemma Require Import le wrap_abstract.\n\nSection unique_prov.\n\nContext {memory: Memory}.\n\nLemma unique_prov_cons2 {a} {b} {l} {p} (H: unique_prov (a :: b :: l) = Some p) :\n  unique_prov (b :: l) = Some p.\nProof.\n\ndestruct a.\n{ discriminate H. }\n\ndestruct o; cycle 1.\n{ discriminate H. }\n\ndestruct b.\n{ unfold unique_prov in H. simpl in H. destruct (P_EQ_REFLECT p0 p0); auto. }\n\ndestruct o; cycle 1.\n{ unfold unique_prov in H. simpl in H. destruct (P_EQ_REFLECT p0 p0); auto. }\n\ndestruct (P_EQ_REFLECT p0 p1).\n- unfold unique_prov in H.\n  simpl in H.\n  destruct (P_EQ_REFLECT p0 p0); cycle 1.\n  { exfalso. apply n. auto. }\n\n  destruct (P_EQ_REFLECT p1 p0); cycle 1.\n  { simpl in H. discriminate H. }\n\n  simpl in H.\n  unfold unique_prov.\n  rewrite <- H.\n  simpl.\n  f_equal; try auto.\n\n  destruct (P_EQ_REFLECT p1 p1); cycle 1.\n  { exfalso. apply n. auto. }\n\n  simpl.\n  rewrite <- e.\n  auto.\n- unfold unique_prov in H.\n  simpl in H.\n\n  destruct (P_EQ_REFLECT p0 p0); cycle 1.\n  { exfalso. apply n0. auto. }\n\n  destruct (P_EQ_REFLECT p1 p0); cycle 1.\n  { simpl in H. discriminate H. }\n\n  simpl in H.\n  exfalso.\n  apply n.\n  auto.\nQed.\n\nLemma unique_le {l1 l2: list AbstractByte} (Hle: le l1 l2) p (H: unique_prov l1 = Some p) :\n  unique_prov l2 = Some p.\nProof.\nassert (l1 = l2); cycle 1.\n{ rewrite <- H0. auto. }\n\ninduction (mk_le_list _ _ Hle) as [| ab1 ab2 l1 l2 HLe IH HLeAB _].\n{ auto. }\n\nassert (le l1 l2) as Hle'.\n{ simpl in Hle. inversion Hle. assumption. }\n\nassert (ab1 = ab2). {\n  destruct ab1.\n  { unfold unique_prov in H. simpl in H. discriminate H. }\n\n  destruct HLeAB.\n  - unfold unique_prov in H. discriminate H.\n  - unfold unique_prov in H. discriminate H.\n  - simpl in Hle. inversion Hle. inversion H0; auto.\n}\nrewrite <- H0. rewrite <- H0 in Hle,HLeAB. clear H0 ab2.\nf_equal.\n\ndestruct l1.\n- destruct l2.\n-- auto.\n-- contradiction Hle'.\n- apply IH.\n-- assumption.\n-- apply (unique_prov_cons2 H).\nQed.\n\nLemma unique_prov_dev {b} {p} {b0} {l} : unique_prov (Init b p :: Init b0 p :: l) = unique_prov (Init b0 p :: l).\nProof.\nunfold unique_prov.\nsimpl.\ndestruct p.\n- simpl.\n  destruct (P_EQ_REFLECT p p); auto.\n- simpl. auto.\nQed.\n\nLemma unique_wrap {l} {p} (H: length l > 0): unique_prov (wrap_abstract l p) = p.\nProof.\ninduction l as [|b l IH].\n- simpl in H.\n  assert (~(0 > 0)). { lia. }\n  exfalso.\n  apply H0.\n  assumption.\n- destruct l.\n-- unfold unique_prov.\n   simpl.\n   destruct p.\n--- simpl.\n    destruct (P_EQ_REFLECT p p); auto.\n    contradict n.\n    auto.\n--- simpl. auto.\n-- simpl.\n   simpl in IH.\n   rewrite unique_prov_dev.\n   apply IH.\n   lia.\nQed.\n\nLemma wrap_unique_le {bl l} (H: unwrap_abstract l = Some bl) : le (wrap_abstract bl (unique_prov l)) l.\nProof.\ndestruct (unique_prov l) eqn:Huniq; cycle 1.\n{ apply unwrap_le; assumption. }\n\nassert (wrap_abstract bl (Some p) = l); cycle 1.\n{ rewrite H0. apply (le_list_abstract_byte_refl l). }\n\ngeneralize dependent bl.\ninduction l as [|ab l IH].\n{ unfold unique_prov in Huniq. simpl in Huniq. discriminate Huniq. }\n\nintros bl H.\ndestruct bl. {\n  destruct ab.\n  - simpl in H. discriminate H.\n  - simpl in H. destruct (unwrap_abstract l); simpl in H; discriminate H.\n}\n\nsimpl.\nassert (Init b (Some p) = ab) as Hab. {\n  destruct ab.\n  { simpl in H. discriminate H. }\n\n  assert (b = b0). {\n    simpl in H.\n    destruct (unwrap_abstract l).\n    - simpl in H. inversion H. auto.\n    - simpl in H. discriminate H.\n  }\n\n  rewrite H0.\n  f_equal.\n\n  unfold unique_prov in Huniq.\n  destruct o; cycle 1.\n  { simpl in Huniq. discriminate Huniq. }\n\n  simpl in Huniq.\n  destruct ((P_EQ p0 p0 &&\n           forallb\n             (fun x : AbstractByte =>\n              match x with\n              | Init _ (Some a) =>\n                  P_EQ a p0\n              | _ => false\n              end) l))%bool eqn:E.\n  - simpl in Huniq. inversion Huniq. auto.\n  - simpl in Huniq. discriminate Huniq.\n}\n\nrewrite Hab.\nf_equal.\n\ndestruct l eqn:E. {\n  destruct ab.\n  { simpl in Hab. discriminate Hab. }\n\n  simpl in H. inversion H.\n  simpl. auto.\n}\n\napply IH.\n- apply (unique_prov_cons2 Huniq).\n- simpl in H.\n  destruct ab. { discriminate H. }\n-- destruct a.\n   { simpl in H. discriminate H. }\n\n   simpl in H. inversion H.\n   simpl.\n   destruct (unwrap_abstract l0).\n--- simpl. simpl in H. inversion H. auto.\n--- simpl in H. discriminate H.\nQed.\n\nEnd unique_prov.", "meta": {"author": "memoryleak47", "repo": "coq-minirust", "sha": "b5f0e4b7902c67cd83673272848850ad716cef32", "save_path": "github-repos/coq/memoryleak47-coq-minirust", "path": "github-repos/coq/memoryleak47-coq-minirust/coq-minirust-b5f0e4b7902c67cd83673272848850ad716cef32/proof/lemma/unique_prov.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961013, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.2785876076215847}}
{"text": "Load GradVer18LemmaHI.\nImport Semantics.\n\nLemma dynSemStarNotModifiesHx : forall ss H1 H2 r1 r2 A1 A2 A,\n  ~ In A A1 ->\n  H1 (fst A) <> None ->\n  dynSemStar\n    (H1, [(r1, A1, ss)])\n    (H2, [(r2, A2, [])]) ->\n  evalA'_d H1 A = evalA'_d H2 A.\nProof.\n  induction ss; intros; simpl in *.\n  - inversionx H4; try tauto.\n    inversionx H5.\n  - inversionx H4.\n    rename H5 into ds.\n    rename H6 into dss.\n    destruct A.\n    inversionx ds.\n    * eapply IHss in dss; eauto.\n      + unfold evalA'_d in *. simpl in *.\n        unfold HSubst in dss.\n        dec (o_dec o0 o1); try tauto.\n        destruct (H1 o1); try tauto.\n        destruct p0. simpl in *.\n        destruct o2; cut.\n        dec (string_dec f0 f1); cut.\n      + unfold HSubst. simpl in *.\n        dec (o_dec o0 o1); try tauto.\n        destruct (H1 o1); try tauto.\n        destruct p0.\n        discriminate.\n    * eapply IHss in dss; eauto.\n    * eapply IHss in dss; eauto.\n      + rewriteRev dss. clear dss.\n        unfold evalA'_d in *. simpl in *.\n        unfold Halloc.\n        rewrite H13.\n        dec (o_dec o1 o0); tauto.\n      + simpl in *. unfold not in *.\n        intros. contradict H0.\n        apply in_app_iff in H4.\n        intuition.\n        apply in_map_iff in H0. unf. inversionx H0.\n        tauto.\n      + unfold Halloc.\n        rewrite H13. simpl in *.\n        dec (o_dec o1 o0); tauto.\n    * eapply IHss in dss; eauto.\n    * admit.\n    * eapply IHss in dss; eauto.\n    * eapply IHss in dss; eauto.\n      unfold not in *. intros. contradict H0.\n      apply InAexcept in H4.\n      assumption.\n    * eapply IHss in dss; eauto.\n    * admit.\nAdmitted.\n\nLemma evalphiComposeDisjointFP : forall H r A1 A2 p1 p2,\n    disjoint A1 A2 ->\n    evalphi H r A1 p1 ->\n    evalphi H r A2 p2 ->\n    evalphi H r (A1 ++ A2) (p1 ++ p2).\nProof.\n  intros.\n  eapp evalphiAppRev.\n  - eapp evalphiIncl.\n    intuition.\n  - eapp evalphiIncl.\n    rewrite AexceptAppFirst.\n    rewrite (AexceptDisjoint A2).\n    * intuition.\n    * apply evalphiImpliesAccess in H2.\n      unfold disjoint, incl in *.\n      intros.\n      specialize (H1 x0).\n      specialize (H2 x0).\n      intuition.\nQed.\n\nLemma evalphiComposeDisjointFPx : forall H r A p1 p2,\n    disjoint (footprint H r p1) (footprint H r p2) ->\n    evalphi H r A p1 ->\n    evalphi H r A p2 ->\n    evalphi H r A (p1 ++ p2).\nProof.\n  intros.\n  eapp evalphiAppRev.\n  assert (incl (footprint H0 r p2) A).\n    eapp evalphiImpliesAccess.\n  eappIn evalphiNarrowAccess H3.\n  eapp evalphiIncl.\n  unfold incl, disjoint in *.\n  intro AA.\n  specialize (H1 AA).\n  specialize (H4 AA).\n  intuition.\n  eapp InAexceptConstr.\nQed.\n\nLemma dynSemStarNoAccessInventing : forall ss H1 H2 r1 r2 A1 A2 A,\n  dynSemStar\n    (H1, [(r1, A1, ss)])\n    (H2, [(r2, A2, [])]) ->\n  In A A2 ->\n  In A A1 \\/ H1 (fst A) = None.\nProof.\n  induction ss; intros; simpl in *.\n  - inversionx H0; try tauto.\n    inversionx H4.\n  - inversionx H0.\n    rename H4 into ds.\n    rename H5 into dss.\n    inversionx ds.\n    * eapply IHss in dss; eauto.\n      intuition.\n      unfold HSubst in H0. destruct A. simpl in *.\n      dec (o_dec o1 o0); try auto.\n      destruct (H1 o0); try auto.\n      destruct p0.\n      discriminate.\n    * eapply IHss in dss; eauto.\n    * eapply IHss in dss; eauto.\n      destruct A. simpl in *.\n      inversionx dss.\n      + apply in_app_iff in H0.\n        intuition.\n        apply in_map_iff in H4.\n        unf. inversionx H4.\n        auto.\n      + unfold Halloc in H0.\n        rewrite H12 in *.\n        dec (o_dec o0 o1); tauto.\n    * eapply IHss in dss; eauto.\n    * admit.\n    * eapply IHss in dss; eauto.\n    * eapply IHss in dss; eauto.\n      intuition.\n      apply InAexcept in H0.\n      auto.\n    * eapply IHss in dss; eauto.\n    * admit.\nAdmitted.\n\nLemma dynSemStarNotModifies : forall x ss H1 H2 r1 r2 A1 A2,\n  (∀ s', In s' ss → ¬ writesTo x s') ->\n  dynSemStar\n    (H1, [(r1, A1, ss)])\n    (H2, [(r2, A2, [])]) ->\n  r1 x = r2 x.\nProof.\n  induction ss; intros; simpl in *.\n  - inversionx H3; try tauto.\n    inversionx H4.\n  - inversionx H3.\n    rename H4 into ds.\n    rename H5 into dss.\n    assert (¬ writesTo x0 a) as wt1. apply H0. tauto.\n    assert (∀ s' : s, In s' ss → ¬ writesTo x0 s') as wt2. intros. apply H0. tauto.\n    inversionx ds; simpl in wt1.\n    * apply IHss in dss; auto.\n    * apply IHss in dss; auto.\n      unfold rhoSubst in dss.\n      dec (x_dec x0 x1); try tauto.\n      contradict wt1.\n      constructor.\n    * apply IHss in dss; auto.\n      unfold rhoSubst in dss.\n      dec (x_dec x0 x1); try tauto.\n      contradict wt1.\n      constructor.\n    * apply IHss in dss; auto.\n      unfold rhoSubst in dss.\n      dec (x_dec x0 xresult); try tauto.\n      contradict wt1.\n      constructor.\n    * admit.\n    * apply IHss in dss; auto.\n    * apply IHss in dss; auto.\n    * apply IHss in dss; auto.\n      unfold rhoSubst in dss.\n      dec (x_dec x0 x1); try tauto.\n      contradict wt1.\n      constructor.\n    * admit.\nAdmitted.\n\nLemma dynSemStarNotModifiesH : forall ss H1 H2 r1 r2 A1 A2 A v,\n  ~ In A A1 ->\n  dynSemStar\n    (H1, [(r1, A1, ss)])\n    (H2, [(r2, A2, [])]) ->\n  evalA'_d H1 A = Some v ->\n  evalA'_d H2 A = Some v.\nProof.\n  induction ss; intros; simpl in *.\n  - inversionx H3; try tauto.\n    inversionx H5.\n  - inversionx H3.\n    rename H5 into ds.\n    rename H6 into dss.\n    inversionx ds.\n    * eapply IHss in dss; eauto.\n      destruct A. unfold evalA'_d in *. simpl in *.\n      unfold HSubst.\n      dec (o_dec o1 o0); try tauto.\n      destruct (H1 o0); try discriminate.\n      destruct p0. simpl in *.\n      rewrite H4.\n      dec (string_dec f1 f0); try tauto.\n    * eapply IHss in dss; eauto.\n    * eapply IHss in dss; eauto.\n      + unfold not. intros.\n        apply in_app_iff in H3.\n        intuition.\n        apply in_map_iff in H5.\n        unf. subst.\n        unfold evalA'_d, HeapNotSetAt in *.\n        simpl in *.\n        rewrite H12 in *.\n        discriminate.\n      + unfold Halloc.\n        rewrite H13.\n        destruct A. unfold evalA'_d in *. simpl in *.\n        dec (o_dec o0 o1); try tauto.\n        unfold HeapNotSetAt in H12. rewrite H12 in *.\n        discriminate.\n    * eapply IHss in dss; eauto.\n    * admit.\n    * eapply IHss in dss; eauto.\n    * eapply IHss in dss; eauto.\n      unfold not in *. intros. contradict H0.\n      apply InAexcept in H3.\n      assumption.\n    * eapply IHss in dss; eauto.\n    * admit.\nAdmitted.\n(* \nLemma dynSemStarNotModifiesHX' : forall ss H1 H2 r1 r2 r A1 A2 A p,\n  disjoint (footprint H1 r1 p) A1 ->\n  dynSemStar\n    (H1, [(r1, A1, ss)])\n    (H2, [(r2, A2, [])]) ->\n  sfrmphi [] p ->\n  evalphi' H1 r A p ->\n  evalphi' H2 r A p.\nProof.\n   *)\n\nLemma evale'ChangeHeap : forall H1 H2 r e,\n  (forall A', In A' (staticFootprintXe e) ->\n    evalA'_s H1 r A' = evalA'_s H2 r A') ->\n  evale' H1 r e = evale' H2 r e.\nProof.\n  induction e0; intros; unfold evale in *; simpl in *; try tauto.\n  assert (evalA'_s H1 r (e0, f0) = evalA'_s H2 r (e0, f0))\n  as tracker.\n    eapp H0.\n  unfold evalA'_s, evalA'_d, A'_s2A'_d in tracker.\n  simpl in *.\n  destruct (evale' H1 r e0);\n  try destruct v0;\n  destruct (evale' H2 r e0);\n  try destruct v0;\n  try discriminate;\n  try tauto;\n  destruct v1;\n  try tauto.\nQed.\n\nLemma footprint'ChangeHeap : forall H1 H2 r p,\n  (forall A', In A' (staticFootprintX' p) ->\n    evalA'_s H1 r A' = evalA'_s H2 r A') ->\n  footprint' H1 r p = footprint' H2 r p.\nProof.\n  intros.\n  destruct p0; try tauto.\n  simpl in *.\n  erewrite evale'ChangeHeap; eauto.\nQed.\n\nLemma footprintChangeHeap : forall H1 H2 r p,\n  (forall A', In A' (staticFootprintX p) ->\n    evalA'_s H1 r A' = evalA'_s H2 r A') ->\n  footprint H1 r p = footprint H2 r p.\nProof.\n  induction p0; intros; simpl in *; try tauto.\n  erewrite IHp0, footprint'ChangeHeap; eauto;\n  intuition.\nQed.\n\nLemma evalphi'ChangeHeap : forall H1 H2 S1 S2 r A p,\n  dynSemStar (H1, S1) (H2, S2) ->\n  (forall A', In A' (staticFootprintX' p) ->\n    evalA'_s H1 r A' = evalA'_s H2 r A') ->\n  evalphi' H1 r A p ->\n  evalphi' H2 r A p.\nProof.\n  intros;\n  inversionx H4;\n  simpl in *.\n  - eca.\n  - eca;\n    unfold evale in *;\n    rewriteRev (evale'ChangeHeap H1 H2); eauto; intros; eapp H3; intuition.\n  - eca;\n    unfold evale in *;\n    rewriteRev (evale'ChangeHeap H1 H2); eauto; intros; eapp H3; intuition.\n  - assert (evale' H2 r e0 = Some (vo o0)) as ee.\n      rewriteRev (evale'ChangeHeap H1 H2); eauto; intros; eapp H3; intuition.\n    unfold evale in *.\n    simpl in *.\n    rewrite H6 in *.\n    destruct H1 eqn: eeH1; cut.\n    destruct p0.\n    eapply HeapGetsMoreSpecific in eeH1; eauto.\n    unf.\n    eca.\n    unfold evale. simpl. rewrite ee.\n    rewrite H4.\n    simpl.\n(*     HeapFieldsGetMoreSpecific. *)\n    admit.\nAdmitted.\n\nLemma evalphiChangeHeap : forall H1 H2 S1 S2 r p A,\n  dynSemStar (H1, S1) (H2, S2) ->\n  (forall A', In A' (staticFootprintX p) ->\n    evalA'_s H1 r A' = evalA'_s H2 r A') ->\n  evalphi H1 r A p ->\n  evalphi H2 r A p.\nProof.\n  induction p0; intros; simpl in *; try constructor.\n  inversionx H4.\n  rewrite (footprint'ChangeHeap H1 H2) in *; intuition.\n  eappIn IHp0 H15; intuition.\n  eappIn (evalphi'ChangeHeap H1 H2) H14; intuition.\n  eca.\nQed.\n\n\nLemma evale'ChangeRho : forall r1 r2 H e,\n  (forall x, In x (FVe e) -> r1 x = r2 x) ->\n  evale' H r1 e = evale' H r2 e.\nProof.\n  induction e0; intros; simpl in *.\n  - tauto.\n  - apply H1.\n    tauto.\n  - rewrite IHe0;\n    tauto.\nQed.\n\nLemma footprint'ChangeRho : forall r1 r2 H p,\n  (forall x, In x (FV' p) -> r1 x = r2 x) ->\n  footprint' H r1 p = footprint' H r2 p.\nProof.\n  intros.\n  destruct p0; try tauto.\n  simpl in *.\n  erewrite evale'ChangeRho; tauto.\nQed.\n\nLemma footprintChangeRho : forall r1 r2 H p,\n  (forall x, In x (FV p) -> r1 x = r2 x) ->\n  footprint H r1 p = footprint H r2 p.\nProof.\n  induction p0; intros; simpl in *; try tauto.\n  erewrite IHp0, footprint'ChangeRho; eauto;\n  intuition.\nQed.\n  \nLemma evalphi'ChangeRho : forall r1 r2 H p A,\n  (forall x, In x (FV' p) -> r1 x = r2 x) ->\n  evalphi' H r1 A p ->\n  evalphi' H r2 A p.\nProof.\n  intros; simpl in *.\n  inversionx H2.\n  - constructor.\n  - simpl in *.\n    eca; unfold evale in *;\n    erewrite evale'ChangeRho in H4, H5; eauto;\n    intros; intuition.\n  - simpl in *.\n    eca; unfold evale in *;\n    erewrite evale'ChangeRho in H4, H5; eauto;\n    intros; intuition.\n  - simpl in *.\n    unfold evale in *. simpl in *.\n    rewrite H4 in H5.\n    eca; unfold evale in *;\n    erewrite evale'ChangeRho in H4; eauto;\n    intros; intuition.\n    simpl. rewrite H4.\n    eauto.\nQed.\n\nLemma evalphiChangeRho : forall r1 r2 H p A,\n  (forall x, In x (FV p) -> r1 x = r2 x) ->\n  evalphi H r1 A p ->\n  evalphi H r2 A p.\nProof.\n  induction p0; intros; simpl in *; try constructor.\n  inversionx H2.\n  eca.\n  - rewrite (footprint'ChangeRho r1 r2) in H7; auto.\n    intros.\n    intuition.\n  - rewrite (footprint'ChangeRho r1 r2) in H12; auto.\n    * eapp (evalphi'ChangeRho r1 r2).\n      intros. intuition.\n    * intros. intuition.\n  - rewrite (footprint'ChangeRho r1 r2) in H13; auto.\n    * eapp IHp0.\n      intros. intuition.\n    * intros. intuition.\nQed.\n\n\nLemma evale'RemoveHSubst : forall o f v H r e,\n  ~ In (o, f) (footprintXe H r e) ->\n  evale' H r e = evale' (HSubst o f v H) r e.\nProof.\n  induction e0; intros; simpl in *; try tauto.\n  unfold footprintXe in *. simpl in *.\n  rewrite in_app_iff in H1.\n  apply not_or_and in H1. unf.\n  rewriteRev IHe0; auto.\n  unfold A'_s2A'_d in *. simpl in *.\n  destruct (evale' H0 r e0); try tauto.\n  destruct v1; try tauto.\n  simpl in *.\n  unfold HSubst.\n  dec (o_dec o1 o0); cut.\n  destruct (H0 o0); cut. destruct p0. simpl.\n  destruct o2; cut.\n  dec (string_dec f1 f0); cut.\n  contradict H2.\n  auto.\nQed.\n\nLemma footprint'RemoveHSubst : forall o f v H r p,\n  ~ In (o, f) (footprintX' H r p) ->\n  footprint' H r p = footprint' (HSubst o f v H) r p.\nProof.\n  intros.\n  destruct p0; try tauto.\n  unfold footprintX' in *.\n  simpl in *.\n  eappIn evale'RemoveHSubst H1.\n  rewriteRev H1.\n  tauto.\nQed.\n\nLemma evalphi'RemoveHSubst : forall o f v H r p A,\n  ~ In (o, f) (footprintX' H r p) ->\n  evalphi' H r A p <->\n  evalphi' (HSubst o f v H) r A p.\nProof.\n  intros.\n  unfold footprintX' in H1.\n  destruct p0; simpl in *;\n  try rewrite map_app in H1;\n  try rewrite oflattenApp in H1;\n  try rewrite in_app_iff in H1;\n  try apply not_or_and in H1;\n  unf.\n  - split; constructor.\n  - split; intros;\n    inversionx H1; eca; unfold evale in *;\n    try rewriteRev evale'RemoveHSubst; eauto;\n    try erewrite evale'RemoveHSubst; eauto.\n  - split; intros;\n    inversionx H1; eca; unfold evale in *;\n    try rewriteRev evale'RemoveHSubst; eauto;\n    try erewrite evale'RemoveHSubst; eauto.\n  - split; intros; inv H2; unfold evale in *;\n    simpl in *; rewrite H6 in *.\n    * erewrite evale'RemoveHSubst in H6; eauto.\n      eca.\n      unfold evale. simpl.\n      rewrite H6.\n      instantiate (1 := if o_decb o1 o0 && f_decb f1 f0 then v0 else v1).\n      unfold HSubst.\n      dec (o_dec o1 o0); eauto.\n      destruct H0; cut.\n      destruct p0.\n      simpl in *.\n      rewrite H10.\n      auto.\n    * rewriteRevIn evale'RemoveHSubst H6; eauto.\n      unfold HSubst in *.\n      dec (o_dec o1 o0).\n        Focus 2. eca. unfold evale. simpl. rewrite H6. eauto.\n      destruct H0 eqn: eeH0; cut.\n      destruct p0.\n      simpl in *.\n      destruct o2 eqn: eeo2; cut.\n      eca.\n      unfold evale. simpl. rewrite H6.\n      rewrite eeH0.\n      simpl.\n      eauto.\nQed.\n\nLemma evalphiRemoveHSubst : forall o f v H r p A,\n  ~ In (o, f) (footprintX H r p) ->\n  evalphi H r A p <->\n  evalphi (HSubst o f v H) r A p.\nProof.\n  induction p0; intros; simpl in *; split; try constructor; intros.\n  - inversionx H2.\n    unfold footprintX in H1.\n    simpl in H1.\n    rewrite map_app in H1.\n    rewrite oflattenApp in H1.\n    rewrite in_app_iff in H1.\n    apply not_or_and in H1.\n    eca.\n    * rewriteRev footprint'RemoveHSubst; eauto; try apply H1.\n    * rewriteRev footprint'RemoveHSubst; eauto; try apply H1.\n      rewriteRev evalphi'RemoveHSubst; try apply H1.\n      eauto.\n    * rewriteRev footprint'RemoveHSubst; eauto; try apply H1.\n      eapp IHp0.\n      tauto.\n  - inversionx H2.\n    unfold footprintX in H1.\n    simpl in H1.\n    rewrite map_app in H1.\n    rewrite oflattenApp in H1.\n    rewrite in_app_iff in H1.\n    apply not_or_and in H1.\n    eca.\n    * erewrite footprint'RemoveHSubst; eauto; try apply H1.\n    * erewrite footprint'RemoveHSubst; eauto; try apply H1.\n      erewrite evalphi'RemoveHSubst; try apply H1.\n      eauto.\n    * erewrite footprint'RemoveHSubst; eauto; try apply H1.\n      eapp IHp0.\n      tauto.\nQed.\n\n\nTheorem framedOff : forall ss H1 H2 r1 r2 A1 A2 r A p,\n  dynSemStar (H1, [(r1, A1, ss)]) (H2, [(r2, A2, [])]) ->\n  (forall A', In A' A -> exists v, H1 (fst A') = Some v) ->\n  disjoint A A1 ->\n  sfrmphi [] p ->\n  evalphi H1 r A p ->\n  evalphi H2 r (A ++ A2) p.\nProof.\n  induction ss; intros; simpl in *.\n  - inversionx H0; try inversionx H7.\n    eapp evalphiIncl.\n    intuition.\n  - inversionx H0.\n    inversionx H7.\n    * eappIn IHss H8.\n        intros.\n        apply H3 in H0. unf.\n        destruct A'. simpl in *.\n        unfold HSubst.\n        dec (o_dec o1 o0); try (eex; fail).\n        rewrite H7. destruct x1. eex.\n      apply evalphiRemoveHSubst; auto.\n      specialize (H4 (o0, f0)).\n      intuition.\n      eapply sfrmphiVSdfpX in H5. apply H5 in H0.\n      apply evalphiImpliesAccess in H6. apply H6 in H0.\n      tauto.\n    * eappIn IHss H8.\n    * assert (evalphi (Halloc o0 C0 H1) r A p0).\n        eapp evalphiRemoveHalloc.\n      eappIn IHss H8.\n        intros.\n        apply H3 in H7. unf.\n        destruct A'. simpl in *.\n        unfold Halloc.\n        rewrite H17.\n        dec (o_dec o0 o1); eex.\n      assert (disjoint A (map (λ cf' : T * f, (o0, snd cf')) Tfs)).\n        unfold disjoint. intros.\n        apply imply_to_or. intro.\n        unfold not. intro.\n        apply in_map_iff in H9. unf. subst.\n        apply H3 in H7. unf. simpl in *.\n        rewrite H16 in H9. discriminate.\n      unfold disjoint. intros.\n      specialize (H4 x1).\n      specialize (H7 x1).\n      rewrite in_app_iff. intuition.\n    * eappIn IHss H8.\n    * admit.\n    * eappIn IHss H8.\n    * eappIn IHss H8.\n      unfold disjoint. intros.\n      specialize (H4 x0).\n      intuition.\n      apply or_intror.\n      intro. contradict H0.\n      eapp InAexcept.\n    * eappIn IHss H8.\n    * admit.\nAdmitted.\n\n(*\nLemma dynSemStarSustainsHelper : forall ss H1 H2 r1 r2 A1 A2 r A,\n  ~ In (A'_s2A'_d H1 r1 A) (map Some A1) ->\n  dynSemStar\n    (H1, [(r1, A1, ss)])\n    (H2, [(r2, A2, [])]) ->\n  evalA'_s H1 r A = evalA'_s H2 r A.\nProof.\n  unfold evalA'_s, A'_s2A'_d.\n  induction ss; intros; simpl in *.\n  - inversionx H3; try tauto.\n    inversionx H4.\n  - inversionx H3.\n    inversionx H4.\n    * eapply IHss in H5; eauto.\n      + rewriteRev H5. clear H5.\n        \n      rewrite H0.\n      eauto.\n      destruct A. simpl in *.\n      destruct (evale' H1 r1 e0) eqn: ee.\n      \n  intros.\n  \n  Check dynSemStarNotModifiesH.\n  eapp (evalphiChangeHeap H1 H2).\n  \n\n\n\n\n\n\nLemma dynSemStarSustains : forall ss H1 H2 r1 r2 A1 A2 r p A,\n  disjoint A A1 ->\n  dynSemStar\n    (H1, [(r1, A1, ss)])\n    (H2, [(r2, A2, [])]) ->\n  evalphi H1 r A p ->\n  evalphi H2 r A p.\nProof.\n  intros.\n  eapp (evalphiChangeHeap H1 H2).\n  \n\n\n *)", "meta": {"author": "olydis", "repo": "GradVer", "sha": "b7c02206ea47e54975dfbb55ac2e4deed60c5292", "save_path": "github-repos/coq/olydis-GradVer", "path": "github-repos/coq/olydis-GradVer/GradVer-b7c02206ea47e54975dfbb55ac2e4deed60c5292/GradVer19Theorems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.27858760041527236}}
{"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 sep_lemma.\n  \nOpen Scope nat.\nOpen Scope code_scope.\nOpen Scope mem_scope.\n\n(*+ Auxiliary Definition +*)\nDefinition update_frame (fm : Frame) (n : nat) (v : Val) :=\n  match fm with\n  | consfm w0 w1 w2 w3 w4 w5 w6 w7 =>\n    match n with\n    | 0 => consfm v w1 w2 w3 w4 w5 w6 w7\n    | 1 => consfm w0 v w2 w3 w4 w5 w6 w7\n    | 2 => consfm w0 w1 v w3 w4 w5 w6 w7\n    | 3 => consfm w0 w1 w2 v w4 w5 w6 w7\n    | 4 => consfm w0 w1 w2 w3 v w5 w6 w7\n    | 5 => consfm w0 w1 w2 w3 w4 v w6 w7\n    | 6 => consfm w0 w1 w2 w3 w4 w5 v w7\n    | 7 => consfm w0 w1 w2 w3 w4 w5 w6 v\n    | _ => consfm w0 w1 w2 w3 w4 w5 w6 w7\n    end\n  end.\n\nDefinition get_frame_nth (fm : Frame) (n : nat) :=\n  match fm with\n  | consfm w0 w1 w2 w3 w4 w5 w6 w7 =>\n    match n with\n    | 0 => Some w0\n    | 1 => Some w1\n    | 2 => Some w2\n    | 3 => Some w3\n    | 4 => Some w4\n    | 5 => Some w5\n    | 6 => Some w6\n    | 7 => Some w7\n    | _ => None\n    end\n  end.\n\nDefinition get_frame_nth' (fm : Frame) (n : nat) :=\n  match fm with\n  | consfm w0 w1 w2 w3 w4 w5 w6 w7 =>\n    match n with\n    | 0 => w0\n    | 1 => w1\n    | 2 => w2\n    | 3 => w3\n    | 4 => w4\n    | 5 => w5\n    | 6 => w6\n    | 7 => w7\n    | _ => W ($ 0)\n    end\n  end.\n\nDefinition GenRegState : Type := Frame * Frame * Frame * Frame.\n\nFixpoint upd_genreg (greg_st : GenRegState) (rr : GenReg) (w : Val) : GenRegState :=\n  match greg_st with\n  | (fmg, fmo, fml, fmi) =>\n    match rr with\n    | r0 => (update_frame fmg 0 w, fmo, fml, fmi)\n    | r1 => (update_frame fmg 1 w, fmo, fml, fmi)\n    | r2 => (update_frame fmg 2 w, fmo, fml, fmi)\n    | r3 => (update_frame fmg 3 w, fmo, fml, fmi)\n    | r4 => (update_frame fmg 4 w, fmo, fml, fmi)\n    | r5 => (update_frame fmg 5 w, fmo, fml, fmi)\n    | r6 => (update_frame fmg 6 w, fmo, fml, fmi)\n    | r7 => (update_frame fmg 7 w, fmo, fml, fmi)\n    | r8 => (fmg, update_frame fmo 0 w, fml, fmi)\n    | r9 => (fmg, update_frame fmo 1 w, fml, fmi)\n    | r10 => (fmg, update_frame fmo 2 w, fml, fmi)\n    | r11 => (fmg, update_frame fmo 3 w, fml, fmi)\n    | r12 => (fmg, update_frame fmo 4 w, fml, fmi)\n    | r13 => (fmg, update_frame fmo 5 w, fml, fmi)\n    | r14 => (fmg, update_frame fmo 6 w, fml, fmi)\n    | r15 => (fmg, update_frame fmo 7 w, fml, fmi)\n    | r16 => (fmg, fmo, update_frame fml 0 w, fmi)\n    | r17 => (fmg, fmo, update_frame fml 1 w, fmi)\n    | r18 => (fmg, fmo, update_frame fml 2 w, fmi)\n    | r19 => (fmg, fmo, update_frame fml 3 w, fmi)\n    | r20 => (fmg, fmo, update_frame fml 4 w, fmi)\n    | r21 => (fmg, fmo, update_frame fml 5 w, fmi)\n    | r22 => (fmg, fmo, update_frame fml 6 w, fmi)\n    | r23 => (fmg, fmo, update_frame fml 7 w, fmi)\n    | r24 => (fmg, fmo, fml, update_frame fmi 0 w)\n    | r25 => (fmg, fmo, fml, update_frame fmi 1 w)\n    | r26 => (fmg, fmo, fml, update_frame fmi 2 w)\n    | r27 => (fmg, fmo, fml, update_frame fmi 3 w)\n    | r28 => (fmg, fmo, fml, update_frame fmi 4 w)\n    | r29 => (fmg, fmo, fml, update_frame fmi 5 w)\n    | r30 => (fmg, fmo, fml, update_frame fmi 6 w)\n    | r31 => (fmg, fmo, fml, update_frame fmi 7 w)\n    end\n  end.\n\nDefinition get_global_frame (fm : Frame) (rr : GenReg) :=\n  match rr with\n  | r0 => Some (W $ 0)\n  | r1 => get_frame_nth fm 1\n  | r2 => get_frame_nth fm 2\n  | r3 => get_frame_nth fm 3\n  | r4 => get_frame_nth fm 4\n  | r5 => get_frame_nth fm 5\n  | r6 => get_frame_nth fm 6\n  | r7 => get_frame_nth fm 7\n  | _ => None\n  end.\n\nDefinition get_out_frame (fm : Frame) (rr : GenReg) :=\n  match rr with\n  | r8 => get_frame_nth fm 0\n  | r9 => get_frame_nth fm 1\n  | r10 => get_frame_nth fm 2\n  | r11 => get_frame_nth fm 3\n  | r12 => get_frame_nth fm 4\n  | r13 => get_frame_nth fm 5\n  | r14 => get_frame_nth fm 6\n  | r15 => get_frame_nth fm 7\n  | _ => None\n  end.\n\nDefinition get_local_frame (fm : Frame) (rr : GenReg) :=\n  match rr with\n  | r16 => get_frame_nth fm 0\n  | r17 => get_frame_nth fm 1\n  | r18 => get_frame_nth fm 2\n  | r19 => get_frame_nth fm 3\n  | r20 => get_frame_nth fm 4\n  | r21 => get_frame_nth fm 5\n  | r22 => get_frame_nth fm 6\n  | r23 => get_frame_nth fm 7\n  | _ => None\n  end.\n\nDefinition get_in_frame (fm : Frame) (rr : GenReg) :=\n  match rr with\n  | r24 => get_frame_nth fm 0\n  | r25 => get_frame_nth fm 1\n  | r26 => get_frame_nth fm 2\n  | r27 => get_frame_nth fm 3\n  | r28 => get_frame_nth fm 4\n  | r29 => get_frame_nth fm 5\n  | r30 => get_frame_nth fm 6\n  | r31 => get_frame_nth fm 7\n  | _ => None\n  end.\n    \nFixpoint get_genreg_val (greg_st : GenRegState) (rr : GenReg) : Val :=\n  match greg_st with\n  | (fmg, fmo, fml, fmi) =>\n    match rr with\n    | r0 => (W $ 0)\n    | r1 => get_frame_nth' fmg 1\n    | r2 => get_frame_nth' fmg 2\n    | r3 => get_frame_nth' fmg 3\n    | r4 => get_frame_nth' fmg 4\n    | r5 => get_frame_nth' fmg 5\n    | r6 => get_frame_nth' fmg 6\n    | r7 => get_frame_nth' fmg 7\n    | r8 => get_frame_nth' fmo 0\n    | r9 => get_frame_nth' fmo 1\n    | r10 => get_frame_nth' fmo 2\n    | r11 => get_frame_nth' fmo 3\n    | r12 => get_frame_nth' fmo 4\n    | r13 => get_frame_nth' fmo 5\n    | r14 => get_frame_nth' fmo 6\n    | r15 => get_frame_nth' fmo 7\n    | r16 => get_frame_nth' fml 0\n    | r17 => get_frame_nth' fml 1\n    | r18 => get_frame_nth' fml 2\n    | r19 => get_frame_nth' fml 3\n    | r20 => get_frame_nth' fml 4\n    | r21 => get_frame_nth' fml 5\n    | r22 => get_frame_nth' fml 6\n    | r23 => get_frame_nth' fml 7\n    | r24 => get_frame_nth' fmi 0\n    | r25 => get_frame_nth' fmi 1\n    | r26 => get_frame_nth' fmi 2\n    | r27 => get_frame_nth' fmi 3\n    | r28 => get_frame_nth' fmi 4\n    | r29 => get_frame_nth' fmi 5\n    | r30 => get_frame_nth' fmi 6\n    | r31 => get_frame_nth' fmi 7\n    end\n  end.\n\nFixpoint get_genreg_val' (greg_st : GenRegState) (rr : GenReg) : Val :=\n  match greg_st with\n  | (fmg, fmo, fml, fmi) =>\n    match rr with\n    | r0 => get_frame_nth' fmg 0\n    | r1 => get_frame_nth' fmg 1\n    | r2 => get_frame_nth' fmg 2\n    | r3 => get_frame_nth' fmg 3\n    | r4 => get_frame_nth' fmg 4\n    | r5 => get_frame_nth' fmg 5\n    | r6 => get_frame_nth' fmg 6\n    | r7 => get_frame_nth' fmg 7\n    | r8 => get_frame_nth' fmo 0\n    | r9 => get_frame_nth' fmo 1\n    | r10 => get_frame_nth' fmo 2\n    | r11 => get_frame_nth' fmo 3\n    | r12 => get_frame_nth' fmo 4\n    | r13 => get_frame_nth' fmo 5\n    | r14 => get_frame_nth' fmo 6\n    | r15 => get_frame_nth' fmo 7\n    | r16 => get_frame_nth' fml 0\n    | r17 => get_frame_nth' fml 1\n    | r18 => get_frame_nth' fml 2\n    | r19 => get_frame_nth' fml 3\n    | r20 => get_frame_nth' fml 4\n    | r21 => get_frame_nth' fml 5\n    | r22 => get_frame_nth' fml 6\n    | r23 => get_frame_nth' fml 7\n    | r24 => get_frame_nth' fmi 0\n    | r25 => get_frame_nth' fmi 1\n    | r26 => get_frame_nth' fmi 2\n    | r27 => get_frame_nth' fmi 3\n    | r28 => get_frame_nth' fmi 4\n    | r29 => get_frame_nth' fmi 5\n    | r30 => get_frame_nth' fmi 6\n    | r31 => get_frame_nth' fmi 7\n    end\n  end.\n\nDefinition GlobalRegs (fm : Frame) :=\n  match fm with\n  | consfm w0 w1 w2 w3 w4 w5 w6 w7 =>\n    r0 |=> w0 ** r1 |=> w1 ** r2 |=> w2 ** r3 |=> w3 ** r4 |=> w4 **\n       r5 |=> w5 ** r6 |=> w6 ** r7 |=> w7\n  end.\n\nDefinition GenRegs (grst : GenRegState) : asrt :=\n  match grst with\n  | (fmg, fmo, fml, fmi) =>\n    GlobalRegs fmg ** OutRegs fmo ** LocalRegs fml ** InRegs fmi\n  end.\n\nDefinition eval_opexp_reg (grst : GenRegState) (a : OpExp) :=\n  match a with\n  | Or r => Some (get_genreg_val grst r)\n  | Ow w => if ($ (-4096)) <=ᵢ w && w <=ᵢ ($ 4095) then Some (W w) else None\n  end. \n\nDefinition eval_addrexp_reg (grst : GenRegState) (b : AddrExp) :=\n  match b with\n  | Ao a => eval_opexp_reg grst a\n  | Aro r a =>\n    match eval_opexp_reg grst a with\n    | Some v2 => val_add (get_genreg_val grst r) v2\n    | None => None\n    end\n  end.\n\nLemma get_global_frame_get_R :\n  forall fm p M R F D v (rr : GenReg),\n    (M, (R, F), D) |= GlobalRegs fm ** p ->\n    get_global_frame fm rr = Some v ->\n    get_R R rr = Some v.\nProof.\n  intros.\n  sep_star_split_tac.\n  simpl in H4.\n  simpljoin1.\n  unfolds GlobalRegs.\n  destruct fm.\n  destruct rr; simpl in H0; tryfalse;\n    try inversion H0; subst; try eapply get_R_merge_still; unfold get_R.\n\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 2.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 3.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 4.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 5.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 6.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 7.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 8.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\nQed.\n\nLemma get_out_frame_get_R :\n  forall fm p M R F D v (rr : GenReg),\n    (M, (R, F), D) |= OutRegs fm ** p ->\n    get_out_frame fm rr = Some v ->\n    get_R R rr = Some v.\nProof.\n  intros.\n  sep_star_split_tac.\n  simpl in H4.\n  simpljoin1.\n  unfolds OutRegs.\n  destruct fm.\n  destruct rr; simpl in H0; tryfalse;\n    try inversion H0; subst; try eapply get_R_merge_still; unfold get_R.\n \n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 2.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 3.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 4.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 5.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 6.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 7.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 8.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\nQed.\n\nLemma get_local_frame_get_R :\n  forall fm p M R F D v (rr : GenReg),\n    (M, (R, F), D) |= LocalRegs fm ** p ->\n    get_local_frame fm rr = Some v ->\n    get_R R rr = Some v.\nProof.\n  intros.\n  sep_star_split_tac.\n  simpl in H4.\n  simpljoin1.\n  unfolds LocalRegs.\n  destruct fm.\n  destruct rr; simpl in H0; tryfalse;\n    try inversion H0; subst; try eapply get_R_merge_still; unfold get_R.\n \n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 2.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 3.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 4.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 5.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 6.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 7.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 8.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\nQed.\n\nLemma get_in_frame_get_R :\n  forall fm p M R F D v (rr : GenReg),\n    (M, (R, F), D) |= InRegs fm ** p ->\n    get_in_frame fm rr = Some v ->\n    get_R R rr = Some v.\nProof.\n  intros.\n  sep_star_split_tac.\n  simpl in H4.\n  simpljoin1.\n  unfolds OutRegs.\n  destruct fm.\n  destruct rr; simpl in H0; tryfalse;\n    try inversion H0; subst; try eapply get_R_merge_still; unfold get_R.\n \n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 2.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 3.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 4.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 5.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 6.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 7.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\n\n  simpl_sep_liftn_in H 8.\n  eapply rn_st_v_eval_reg_v in H.\n  rewrite H; eauto.\nQed.\n  \nLemma getR_eq_get_genreg_val :\n  forall M R F D grst (rr : GenReg),\n    (M, (R, F), D) |= GenRegs grst ->\n    get_R R rr = Some (get_genreg_val grst rr).\nProof.\n  intros.\n  unfolds GenRegs.\n  destruct grst.\n  destruct p.\n  destruct p.\n  destruct f1, f2, f0, f.\n  destruct rr; simpl;\n    try solve [eapply get_global_frame_get_R; [eauto | simpl; eauto] ];\n    try solve [simpl_sep_liftn_in H 2;\n               eapply get_out_frame_get_R; [eauto | simpl; eauto] ];\n    try solve [simpl_sep_liftn_in H 3;\n               eapply get_local_frame_get_R; [eauto | simpl; eauto] ];\n    try solve [sliftn_in H 4;\n               eapply get_in_frame_get_R; [eauto | simpl; eauto] ].\nQed.\n\nLemma eval_opexp_reg_eq_eval_opexp :\n  forall M R F D grst oexp v,\n    (M, (R, F), D) |= GenRegs grst ->\n    eval_opexp_reg grst oexp = Some v ->\n    eval_opexp R oexp = Some v.\nProof.\n  intros.\n  unfolds GenRegs.\n  destruct grst.\n  destruct p.\n  destruct p. \n  destruct f1, f2, f0, f.\n  destruct oexp; simpl in H0.\n  destruct g; inversion H0; subst; simpl;\n    try solve [eapply get_global_frame_get_R; [eauto | simpl; eauto] ];\n    try solve [simpl_sep_liftn_in H 2;\n               eapply get_out_frame_get_R; [eauto | simpl; eauto] ];\n    try solve [simpl_sep_liftn_in H 3;\n               eapply get_local_frame_get_R; [eauto | simpl; eauto] ];\n    try solve [sliftn_in H 4;\n               eapply get_in_frame_get_R; [eauto | simpl; eauto] ].\n  destruct (($ (-4096)) <=ᵢ w && w <=ᵢ ($ 4095)) eqn:Heqe; eauto;\n    inversion H0; subst; eauto.\n  simpl; eauto.\n  rewrite Heqe; eauto.\nQed.\n\nLemma eval_aexp_reg_eq_eval_aexp :\n  forall M R F D grst aexp v,\n    (M, (R, F), D) |= GenRegs grst ->\n    eval_addrexp_reg grst aexp = Some v ->\n    eval_addrexp R aexp = Some v.\nProof.\n  intros. \n  destruct grst.\n  destruct p.\n  destruct p.\n  destruct f1, f2, f0, f.\n  destruct aexp.\n  simpl in H0.\n  eapply eval_opexp_reg_eq_eval_opexp; eauto.\n  lets Ht : H.\n\n  Ltac destruct_eval_opexp_reg :=\n    let Heqe := fresh in\n    match goal with\n    | H : context [eval_opexp_reg ?grst ?o] |- _ =>\n      destruct (eval_opexp_reg grst o) eqn:Heqe\n    | _ => idtac\n    end.\n\n  Ltac eval_opexp_reg_to_eval_opexp :=\n    match goal with\n    | H : eval_opexp_reg ?grst ?o = Some ?w |- _ =>\n      eapply eval_opexp_reg_eq_eval_opexp in H; [rewrite H; eauto | eauto]\n    | _ => idtac\n    end.\n  \n  destruct g; simpl in H0; simpl;\n  try solve [\n        eapply get_global_frame_get_R in H;\n        [\n          erewrite H; eauto; destruct_eval_opexp_reg; tryfalse;\n          eval_opexp_reg_to_eval_opexp\n        | simpl; eauto\n        ]\n      ];\n  try solve [\n        unfold GenRegs in H; simpl_sep_liftn_in H 2;\n        eapply get_out_frame_get_R in H;\n        [\n          erewrite H; eauto; destruct_eval_opexp_reg; tryfalse;\n          eval_opexp_reg_to_eval_opexp\n        | simpl; eauto\n        ]\n      ];\n  try solve [\n        unfold GenRegs in H; simpl_sep_liftn_in H 3;\n        eapply get_local_frame_get_R in H;\n        [\n          erewrite H; eauto; destruct_eval_opexp_reg; tryfalse;\n          eval_opexp_reg_to_eval_opexp\n        | simpl; eauto\n        ]\n      ];\n  try solve [\n        unfold GenRegs in H; sliftn_in H 4;\n        eapply get_in_frame_get_R in H;\n        [\n          erewrite H; eauto; destruct_eval_opexp_reg; tryfalse;\n          eval_opexp_reg_to_eval_opexp\n        | simpl; eauto\n        ]\n      ].\n  eapply get_global_frame_get_R in H;\n    [\n      erewrite H; eauto; destruct_eval_opexp_reg; tryfalse;\n      eval_opexp_reg_to_eval_opexp\n    | simpl; eauto\n    ].\n  destruct v32; simpl in H0; tryfalse; eauto.\nQed.\n  \nLtac asrt_to_line_in H t :=\n  match type of H with\n  | _ |= ?p1 ** ?p2 =>\n    eapply asrt_combine_to_line_stable with (n := t) in H;\n    unfold asrt_combine_to_line in H; fold asrt_combine_to_line in H\n  | _ => idtac\n  end.\n\nLtac asrt_to_line t :=\n  match goal with\n  | |- _ |= ?p1 ** ?p2 =>\n    eapply asrt_combine_to_line_stable_rev with (n := t);\n    unfold asrt_combine_to_line; fold asrt_combine_to_line\n  | _ => idtac\n  end.\n\nDefinition globalRegs_rm_one (fm : Frame) (rr : GenReg) :=\n  match fm with\n  | consfm w0 w1 w2 w3 w4 w5 w6 w7 =>\n    match rr with\n    | r0 =>\n      r1 |=> w1 ** r2 |=> w2 ** r3 |=> w3 **\n         r4 |=> w4 ** r5 |=> w5 ** r6 |=> w6 ** r7 |=> w7\n    | r1 =>\n      r0 |=> w0 ** r2 |=> w2 ** r3 |=> w3 **\n         r4 |=> w4 ** r5 |=> w5 ** r6 |=> w6 ** r7 |=> w7\n    | r2 =>\n      r0 |=> w0 ** r1 |=> w1 ** r3 |=> w3 **\n         r4 |=> w4 ** r5 |=> w5 ** r6 |=> w6 ** r7 |=> w7\n    | r3 =>\n      r0 |=> w0 ** r1 |=> w1 ** r2 |=> w2 **\n         r4 |=> w4 ** r5 |=> w5 ** r6 |=> w6 ** r7 |=> w7\n    | r4 =>\n      r0 |=> w0 ** r1 |=> w1 ** r2 |=> w2 **\n         r3 |=> w3 ** r5 |=> w5 ** r6 |=> w6 ** r7 |=> w7\n    | r5 =>\n      r0 |=> w0 ** r1 |=> w1 ** r2 |=> w2 **\n         r3 |=> w3 ** r4 |=> w4 ** r6 |=> w6 ** r7 |=> w7\n    | r6 =>\n      r0 |=> w0 ** r1 |=> w1 ** r2 |=> w2 **\n         r3 |=> w3 ** r4 |=> w4 ** r5 |=> w5 ** r7 |=> w7\n    | r7 =>\n      r0 |=> w0 ** r1 |=> w1 ** r2 |=> w2 **\n         r3 |=> w3 ** r4 |=> w4 ** r5 |=> w5 ** r6 |=> w6\n    | _ =>\n      r0 |=> w0 ** r1 |=> w1 ** r2 |=> w2 **\n         r3 |=> w3 ** r4 |=> w4 ** r5 |=> w5 ** r6 |=> w6 ** r7 |=> w7\n    end\n  end.\n\nDefinition outRegs_rm_one (fm : Frame) (rr : GenReg) :=\n  match fm with\n  | consfm w0 w1 w2 w3 w4 w5 w6 w7 =>\n    match rr with\n    | r8 =>\n      r9 |=> w1 ** r10 |=> w2 ** r11 |=> w3 **\n         r12 |=> w4 ** r13 |=> w5 ** r14 |=> w6 ** r15 |=> w7\n    | r9 =>\n      r8 |=> w0 ** r10 |=> w2 ** r11 |=> w3 **\n         r12 |=> w4 ** r13 |=> w5 ** r14 |=> w6 ** r15 |=> w7\n    | r10 =>\n      r8 |=> w0 ** r9 |=> w1 ** r11 |=> w3 **\n         r12 |=> w4 ** r13 |=> w5 ** r14 |=> w6 ** r15 |=> w7\n    | r11 =>\n      r8 |=> w0 ** r9 |=> w1 ** r10 |=> w2 **\n         r12 |=> w4 ** r13 |=> w5 ** r14 |=> w6 ** r15 |=> w7\n    | r12 =>\n      r8 |=> w0 ** r9 |=> w1 ** r10 |=> w2 **\n         r11 |=> w3 ** r13 |=> w5 ** r14 |=> w6 ** r15 |=> w7\n    | r13 =>\n      r8 |=> w0 ** r9 |=> w1 ** r10 |=> w2 **\n         r11 |=> w3 ** r12 |=> w4 ** r14 |=> w6 ** r15 |=> w7\n    | r14 =>\n      r8 |=> w0 ** r9 |=> w1 ** r10 |=> w2 **\n         r11 |=> w3 ** r12 |=> w4 ** r13 |=> w5 ** r15 |=> w7\n    | r15 =>\n      r8 |=> w0 ** r9 |=> w1 ** r10 |=> w2 **\n         r11 |=> w3 ** r12 |=> w4 ** r13 |=> w5 ** r14 |=> w6\n    | _ =>\n      r8 |=> w0 ** r9 |=> w1 ** r10 |=> w2 **\n         r11 |=> w3 ** r12 |=> w4 ** r13 |=> w5 ** r14 |=> w6 ** r15 |=> w7\n    end\n  end.\n\nDefinition localRegs_rm_one (fm : Frame) (rr : GenReg) :=\n  match fm with\n  | consfm w0 w1 w2 w3 w4 w5 w6 w7 =>\n    match rr with\n    | r16 =>\n      r17 |=> w1 ** r18 |=> w2 ** r19 |=> w3 **\n         r20 |=> w4 ** r21 |=> w5 ** r22 |=> w6 ** r23 |=> w7\n    | r17 =>\n      r16 |=> w0 ** r18 |=> w2 ** r19 |=> w3 **\n         r20 |=> w4 ** r21 |=> w5 ** r22 |=> w6 ** r23 |=> w7\n    | r18 =>\n      r16 |=> w0 ** r17 |=> w1 ** r19 |=> w3 **\n         r20 |=> w4 ** r21 |=> w5 ** r22 |=> w6 ** r23 |=> w7\n    | r19 =>\n      r16 |=> w0 ** r17 |=> w1 ** r18 |=> w2 **\n         r20 |=> w4 ** r21 |=> w5 ** r22 |=> w6 ** r23 |=> w7\n    | r20 =>\n      r16 |=> w0 ** r17 |=> w1 ** r18 |=> w2 **\n         r19 |=> w3 ** r21 |=> w5 ** r22 |=> w6 ** r23 |=> w7\n    | r21 =>\n      r16 |=> w0 ** r17 |=> w1 ** r18 |=> w2 **\n         r19 |=> w3 ** r20 |=> w4 ** r22 |=> w6 ** r23 |=> w7\n    | r22 =>\n      r16 |=> w0 ** r17 |=> w1 ** r18 |=> w2 **\n          r19 |=> w3 ** r20 |=> w4 ** r21 |=> w5 ** r23 |=> w7\n    | r23 =>\n      r16 |=> w0 ** r17 |=> w1 ** r18 |=> w2 **\n          r19 |=> w3 ** r20 |=> w4 ** r21 |=> w5 ** r22 |=> w6\n    | _ =>\n      r16 |=> w0 ** r17 |=> w1 ** r18 |=> w2 ** r19 |=> w3 **\n         r20 |=> w4 ** r21 |=> w5 ** r22 |=> w6 ** r23 |=> w7\n    end\n  end.\n\nDefinition inRegs_rm_one (fm : Frame) (rr : GenReg) :=\n  match fm with\n  | consfm w0 w1 w2 w3 w4 w5 w6 w7 =>\n    match rr with\n    | r24 =>\n      r25 |=> w1 ** r26 |=> w2 ** r27 |=> w3 **\n         r28 |=> w4 ** r29 |=> w5 ** r30 |=> w6 ** r31 |=> w7\n    | r25 =>\n      r24 |=> w0 ** r26 |=> w2 ** r27 |=> w3 **\n         r28 |=> w4 ** r29 |=> w5 ** r30 |=> w6 ** r31 |=> w7\n    | r26 =>\n      r24 |=> w0 ** r25 |=> w1 ** r27 |=> w3 **\n         r28 |=> w4 ** r29 |=> w5 ** r30 |=> w6 ** r31 |=> w7\n    | r27 =>\n      r24 |=> w0 ** r25 |=> w1 ** r26 |=> w2 **\n         r28 |=> w4 ** r29 |=> w5 ** r30 |=> w6 ** r31 |=> w7\n    | r28 =>\n      r24 |=> w0 ** r25 |=> w1 ** r26 |=> w2 **\n          r27 |=> w3 ** r29 |=> w5 ** r30 |=> w6 ** r31 |=> w7\n    | r29 =>\n      r24 |=> w0 ** r25 |=> w1 ** r26 |=> w2 **\n          r27 |=> w3 ** r28 |=> w4 ** r30 |=> w6 ** r31 |=> w7\n    | r30 =>\n      r24 |=> w0 ** r25 |=> w1 ** r26 |=> w2 **\n          r27 |=> w3 ** r28 |=> w4 ** r29 |=> w5 ** r31 |=> w7\n    | r31 =>\n      r24 |=> w0 ** r25 |=> w1 ** r26 |=> w2 **\n          r27 |=> w3 ** r28 |=> w4 ** r29 |=> w5 ** r30 |=> w6\n    | _ =>\n      r24 |=> w0 ** r25 |=> w1 ** r26 |=> w2 ** r27 |=> w3 **\n         r28 |=> w4 ** r29 |=> w5 ** r30 |=> w6 ** r31 |=> w7\n    end\n  end.\n\nDefinition GenRegs_rm_one (greg_st : GenRegState) (rr : GenReg) :=\n  match greg_st with\n  | (fmg, fmo, fml, fmi) =>\n    globalRegs_rm_one fmg rr ** outRegs_rm_one fmo rr **\n                      localRegs_rm_one fml rr ** inRegs_rm_one fmi rr\n  end.\n\nLemma GenRegs_split_one :\n  forall s grst p (rr : GenReg),\n    s |= GenRegs grst ** p ->\n    s |= rr |=> get_genreg_val' grst rr ** GenRegs_rm_one grst rr ** p.\nProof.\n  intros.\n  eapply astar_assoc_elim; eauto.\n  eapply astar_subst1; eauto.\n  clear H.\n  intros.\n  unfolds GenRegs.\n  destruct grst.\n  destruct p0.\n  destruct p0.\n  destruct f1, f2, f0, f.\n\n  Ltac simpl_reg_elim m :=\n    match goal with\n    | H : ?s |= _ |- ?s |= _ =>\n      asrt_to_ls; asrt_to_ls_in H;\n      simpl_sep_liftn_in H m; eauto\n    | _ => idtac\n    end.  \n  \n  destruct rr;\n    simpl get_genreg_val';\n    simpl GenRegs_rm_one;\n    unfold GlobalRegs, OutRegs, LocalRegs, InRegs in H.\n  simpl_reg_elim 1.\n  simpl_reg_elim 2.\n  simpl_reg_elim 3.\n  simpl_reg_elim 4.\n  simpl_reg_elim 5.\n  simpl_reg_elim 6.\n  simpl_reg_elim 7.\n  simpl_reg_elim 8.\n  simpl_reg_elim 9.\n  simpl_reg_elim 10.\n  simpl_reg_elim 11.\n  simpl_reg_elim 12.\n  simpl_reg_elim 13.\n  simpl_reg_elim 14.\n  simpl_reg_elim 15.\n  simpl_reg_elim 16.\n  simpl_reg_elim 17.\n  simpl_reg_elim 18.\n  simpl_reg_elim 19.\n  simpl_reg_elim 20. \n  simpl_reg_elim 21.\n  simpl_reg_elim 22.\n  simpl_reg_elim 23.\n  simpl_reg_elim 24.\n  simpl_reg_elim 25.\n  simpl_reg_elim 26. \n  simpl_reg_elim 27.\n  simpl_reg_elim 28.\n  simpl_reg_elim 29.\n  simpl_reg_elim 30.\n  simpl_reg_elim 31.\n  simpl_reg_elim 32.\nQed.\n\nLemma GenRegs_upd_combine_one :\n  forall s grst p (rr : GenReg) v,\n    s |= rr |=> v ** GenRegs_rm_one grst rr ** p ->\n    s |= GenRegs (upd_genreg grst rr v) ** p.\nProof.\n  intros.\n  eapply astar_assoc_intro in H; eauto.\n  eapply astar_subst1; eauto.\n  clear H.\n  intros.  \n  destruct grst.\n  destruct p0.\n  destruct p0.\n  destruct f1, f2, f0, f.\n\n  Ltac simpl_reg_elim1 m :=\n    match goal with\n    | H : ?s |= _ |- ?s |= _ =>\n      asrt_to_ls; asrt_to_ls_in H;\n      simpl_sep_liftn m; eauto\n    | _ => idtac\n    end.\n  \n  destruct rr;\n    simpl upd_genreg; simpls GenRegs_rm_one;\n    unfolds GenRegs,  GlobalRegs, OutRegs, LocalRegs, InRegs. \n  simpl_reg_elim1 1. \n  simpl_reg_elim1 2.\n  simpl_reg_elim1 3.\n  simpl_reg_elim1 4.\n  simpl_reg_elim1 5.\n  simpl_reg_elim1 6.\n  simpl_reg_elim1 7.\n  simpl_reg_elim1 8.\n  simpl_reg_elim1 9.\n  simpl_reg_elim1 10.\n  simpl_reg_elim1 11.\n  simpl_reg_elim1 12.\n  simpl_reg_elim1 13.\n  simpl_reg_elim1 14.\n  simpl_reg_elim1 15.\n  simpl_reg_elim1 16.\n  simpl_reg_elim1 17.\n  simpl_reg_elim1 18.\n  simpl_reg_elim1 19.\n  simpl_reg_elim1 20. \n  simpl_reg_elim1 21.\n  simpl_reg_elim1 22.\n  simpl_reg_elim1 23.\n  simpl_reg_elim1 24.\n  simpl_reg_elim1 25.\n  simpl_reg_elim1 26. \n  simpl_reg_elim1 27.\n  simpl_reg_elim1 28.\n  simpl_reg_elim1 29.\n  simpl_reg_elim1 30.\n  simpl_reg_elim1 31.\n  simpl_reg_elim1 32.\nQed.\n\nLemma Regs_Global_combine_GenRegs :\n  forall fmg fmo fml fmi p s,\n    s |= Regs fmo fml fmi ** GlobalRegs fmg ** p ->\n    s |= GenRegs (fmg, fmo, fml, fmi) ** p.\nProof.\n  intros.\n  unfold Regs in H.\n  unfold GenRegs.\n  sliftn_in H 5.\n  sliftn 5.\n  sep_cancel1 1 1.\n  sliftn_in H0 1.\n  sep_cancel1 1 2.\n  sliftn_in H 3.\n  sep_cancel1 1 1.\n  eauto.\nQed.\n\nLemma GenRegs_split_Regs_Global :\n  forall fmg fmo fml fmi p s,\n    s |= GenRegs (fmg, fmo, fml, fmi) ** p ->\n    s |= Regs fmo fml fmi ** GlobalRegs fmg ** p.\nProof.\n  intros.\n  unfold GenRegs in H.\n  eapply astar_assoc_elim in H.\n  sep_cancel1 1 2.\n  unfold Regs.\n  eauto.\nQed.\n \nTheorem add_rule_reg :\n  forall grst rs rd p oexp v1 v2 v,\n    Some v = val_add v1 v2 ->\n    get_genreg_val grst rs = v1 -> eval_opexp_reg grst oexp = Some v2 ->\n    |- {{ GenRegs grst ** p }} add rs oexp rd\n                              {{ GenRegs (upd_genreg grst rd v) ** p }}.\nProof.\n  introv Hres; intros.\n  eapply ins_conseq_rule.\n  eauto.\n  eapply add_rule; eauto.\n  {\n    intros.\n    simpl.\n    split.\n    {\n      sep_star_split_tac.\n      simpl in H5.\n      simpljoin1.\n      simpl.\n      eapply getR_eq_get_genreg_val in H1; eauto.\n      eapply get_R_merge_still; eauto.\n    }\n    {\n      sep_star_split_tac.\n      simpl in H5.\n      simpljoin1.\n      simpl.\n      eapply eval_opexp_merge_still; eauto.\n      eapply eval_opexp_reg_eq_eval_opexp; eauto.\n    }\n  }\n  {  \n    intros.\n    instantiate (2 := (get_genreg_val' grst rd)).\n    instantiate (1 := (GenRegs_rm_one grst rd ** p)).\n    eapply GenRegs_split_one; eauto.\n  }\n\n  intros.\n  eapply GenRegs_upd_combine_one; eauto.\nQed.\n\nTheorem sub_rule_reg :\n  forall grst rs rd p oexp v1 v2 v,\n    Some v = val_sub v1 v2 ->\n    get_genreg_val grst rs = v1 -> eval_opexp_reg grst oexp = Some v2 ->\n    |- {{ GenRegs grst ** p }} sub rs oexp rd\n                              {{ GenRegs (upd_genreg grst rd v) ** p }}.\nProof.\n  introv Hres; intros.\n  eapply ins_conseq_rule.\n  eauto.\n  eapply sub_rule; eauto.\n  {\n    intros.\n    simpl.\n    split.\n    {\n      sep_star_split_tac.\n      simpl in H5.\n      simpljoin1.\n      simpl.\n      eapply getR_eq_get_genreg_val in H1; eauto.\n      eapply get_R_merge_still; eauto.\n    }\n    {\n      sep_star_split_tac.\n      simpl in H5.\n      simpljoin1.\n      simpl.\n      eapply eval_opexp_merge_still; eauto.\n      eapply eval_opexp_reg_eq_eval_opexp; eauto.\n    }\n  }\n  {  \n    intros.\n    instantiate (2 := (get_genreg_val' grst rd)).\n    instantiate (1 := (GenRegs_rm_one grst rd ** p)).\n    eapply GenRegs_split_one; eauto.\n  }\n\n  intros.\n  eapply GenRegs_upd_combine_one; eauto.\nQed.\n\nTheorem and_rule_reg :\n  forall grst rs rd p oexp v1 v2,\n    get_genreg_val grst rs = W v1 -> eval_opexp_reg grst oexp = Some (W v2) ->\n    |- {{ GenRegs grst ** p }} and rs oexp rd\n                              {{ GenRegs (upd_genreg grst rd (W v1 &ᵢ v2)) ** p }}.\nProof.\n  intros.\n  eapply ins_conseq_rule.\n  eauto.\n  eapply and_rule; eauto.\n  {\n    intros.\n    simpl.\n    split.\n    { \n      instantiate (1 := v1).\n      sep_star_split_tac.\n      simpl in H5.\n      simpljoin1.\n      simpl.\n      eapply getR_eq_get_genreg_val in H1; eauto.\n      eapply get_R_merge_still; eauto.\n      rewrite H in H1; eauto.\n    }\n    {\n      instantiate (1 := v2).\n      sep_star_split_tac.\n      simpl in H5.\n      simpljoin1.\n      simpl.\n      eapply eval_opexp_merge_still; eauto.\n      eapply eval_opexp_reg_eq_eval_opexp; eauto.\n    }\n  }\n  {  \n    intros.\n    instantiate (2 := (get_genreg_val' grst rd)).\n    instantiate (1 := (GenRegs_rm_one grst rd ** p)).\n    eapply GenRegs_split_one; eauto.\n  }\n\n  intros.\n  eapply GenRegs_upd_combine_one; eauto.\nQed.\n\nTheorem or_rule_reg :\n  forall grst rs rd p oexp v1 v2,\n    get_genreg_val grst rs = W v1 -> eval_opexp_reg grst oexp = Some (W v2) ->\n    |- {{ GenRegs grst ** p }} or rs oexp rd\n                              {{ GenRegs (upd_genreg grst rd (W v1 |ᵢ v2)) ** p }}.\nProof.\n  intros.\n  eapply ins_conseq_rule.\n  eauto.\n  eapply or_rule; eauto.\n  {\n    intros.\n    simpl.\n    split.\n    {\n      instantiate (1 := v1).\n      sep_star_split_tac.\n      simpl in H5.\n      simpljoin1.\n      simpl.\n      eapply getR_eq_get_genreg_val in H1; eauto.\n      eapply get_R_merge_still; eauto.\n      rewrite H in H1; eauto.\n    }\n    {\n      instantiate (1 := v2).\n      sep_star_split_tac.\n      simpl in H5.\n      simpljoin1.\n      simpl.\n      eapply eval_opexp_merge_still; eauto.\n      eapply eval_opexp_reg_eq_eval_opexp; eauto.\n    }\n  }\n  {  \n    intros.\n    instantiate (2 := (get_genreg_val' grst rd)).\n    instantiate (1 := (GenRegs_rm_one grst rd ** p)).\n    eapply GenRegs_split_one; eauto.\n  }\n\n  intros.\n  eapply GenRegs_upd_combine_one; eauto.\nQed.\n\nTheorem sll_rule_reg :\n  forall grst rs rd p oexp v1 v2,\n    get_genreg_val grst rs = W v1 -> eval_opexp_reg grst oexp = Some (W v2) ->\n    |- {{ GenRegs grst ** p }} sll rs oexp rd\n                              {{ GenRegs (upd_genreg grst rd (W v1 <<ᵢ (get_range 0 4 v2))) ** p }}.\nProof.\n  intros.\n  eapply ins_conseq_rule.\n  eauto.\n  eapply sll_rule; eauto.\n  {\n    intros.\n    simpl.\n    split.\n    {\n      instantiate (1 := v1).\n      sep_star_split_tac.\n      simpl in H5.\n      simpljoin1.\n      simpl.\n      eapply getR_eq_get_genreg_val in H1; eauto.\n      eapply get_R_merge_still; eauto.\n      rewrite H in H1; eauto.\n    }\n    {\n      instantiate (1 := v2).\n      sep_star_split_tac.\n      simpl in H5.\n      simpljoin1.\n      simpl.\n      eapply eval_opexp_merge_still; eauto.\n      eapply eval_opexp_reg_eq_eval_opexp; eauto.\n    }\n  }\n  {  \n    intros.\n    instantiate (2 := (get_genreg_val' grst rd)).\n    instantiate (1 := (GenRegs_rm_one grst rd ** p)).\n    eapply GenRegs_split_one; eauto.\n  }\n\n  intros.\n  eapply GenRegs_upd_combine_one; eauto.\nQed.\n\nTheorem srl_rule_reg :\n  forall grst rs rd p oexp v1 v2,\n    get_genreg_val grst rs = W v1 -> eval_opexp_reg grst oexp = Some (W v2) ->\n    |- {{ GenRegs grst ** p }} srl rs oexp rd\n                              {{ GenRegs (upd_genreg grst rd (W v1 >>ᵢ (get_range 0 4 v2))) ** p }}.\nProof.\n  intros.\n  eapply ins_conseq_rule.\n  eauto. \n  eapply srl_rule; eauto.\n  {\n    intros.\n    simpl.\n    split.\n    {\n      instantiate (1 := v1).\n      sep_star_split_tac.\n      simpl in H5.\n      simpljoin1.\n      simpl.\n      eapply getR_eq_get_genreg_val in H1; eauto.\n      eapply get_R_merge_still; eauto.\n      rewrite H in H1; eauto.\n    }\n    {\n      instantiate (1 := v2).\n      sep_star_split_tac.\n      simpl in H5.\n      simpljoin1.\n      simpl.\n      eapply eval_opexp_merge_still; eauto.\n      eapply eval_opexp_reg_eq_eval_opexp; eauto.\n    }\n  }\n  {  \n    intros.\n    instantiate (2 := (get_genreg_val' grst rd)).\n    instantiate (1 := (GenRegs_rm_one grst rd ** p)).\n    eapply GenRegs_split_one; eauto.\n  }\n\n  intros.\n  eapply GenRegs_upd_combine_one; eauto.\nQed.\n\nTheorem set_rule_reg :\n  forall grst rd p w,\n    |- {{ GenRegs grst ** p }} sett w rd\n                              {{ GenRegs (upd_genreg grst rd w) ** p }}.\nProof.\n  intros.\n  eapply ins_conseq_rule.\n  eauto.\n  eapply set_rule; eauto.\n  {\n    instantiate (2 := (get_genreg_val' grst rd)).\n    instantiate (1 := (GenRegs_rm_one grst rd ** p)).\n    intros.\n    eapply GenRegs_split_one; eauto.\n  }\n  {\n    intros.\n    eapply GenRegs_upd_combine_one; eauto.\n  }\nQed.\n\nTheorem getcwp_rule_reg :\n  forall grst rd p id F,\n    |- {{ GenRegs grst ** {| id, F|} ** p }}\n        getcwp rd\n        {{ GenRegs (upd_genreg grst rd (W id)) ** {| id, F|} ** p }}.\nProof.\n  intros.\n  eapply ins_conseq_rule.\n  eauto.\n  eapply getcwp_rule; eauto.\n  {\n    intros.\n    simpl_sep_liftn 2.\n    instantiate (4 := (get_genreg_val' grst rd)).\n    instantiate (3 := id).\n    instantiate (2 := F).\n    instantiate (1 := (GenRegs_rm_one grst rd ** p)).\n    sep_cancel1 2 2. \n    eapply GenRegs_split_one; eauto. \n  }\n  {\n    intros. \n    sep_cancel1 1 2.\n    eapply GenRegs_upd_combine_one; eauto.\n  }\nQed.\n\nTheorem ld_rule_reg :\n  forall p aexp rd grst v l,\n    eval_addrexp_reg grst aexp = Some (Ptr l) ->\n    |- {{ GenRegs grst ** l |-> v ** p }}\n        ld aexp rd\n       {{ GenRegs (upd_genreg grst rd v) ** l |-> v ** p }}.\nProof.\n  intros.\n  eapply ins_conseq_rule.\n  eauto.\n  eapply ld_rule; eauto.\n  {\n    intros.\n    instantiate (1 := l).\n    simpl.\n    split; eauto.\n    sep_star_split_tac.\n    simpl in H3, H4.\n    simpljoin1.\n    simpl.\n    eapply eval_addrexp_merge_still; eauto.\n    eapply eval_aexp_reg_eq_eval_aexp; eauto.\n    sep_star_split_tac.\n    simpl in H3, H4.\n    simpljoin1.\n    simpl in H1.\n    simpljoin1; eauto.\n  }\n  {\n    intros.\n    instantiate (1 := GenRegs_rm_one grst rd ** p).\n    instantiate (1 := get_genreg_val' grst rd).\n    instantiate (1 := v).\n    sep_cancel1 2 1.\n    eapply GenRegs_split_one; eauto.\n  }\n  {\n    intros.\n    sep_cancel1 1 2.\n    eapply GenRegs_upd_combine_one; eauto.\n  }\nQed.\n\nTheorem st_rule_reg :\n  forall p aexp rs grst v v' l,\n    eval_addrexp_reg grst aexp = Some (Ptr l) -> get_genreg_val grst rs = v' ->\n    |- {{ GenRegs grst ** l |-> v ** p }}\n        st rs aexp\n        {{ GenRegs grst ** l |-> v' ** p }}.\nProof.\n  intros. \n  eapply ins_conseq_rule.\n  Focus 2.\n  instantiate (2 := l |-> v ** GenRegs grst ** p). \n  instantiate (1 := l |-> v' ** GenRegs grst ** p).\n  eapply st_rule; eauto.\n  intros.\n  simpl.\n  split.\n  simpl_sep_liftn_in H1 2.\n  sep_star_split_tac.\n  simpl in H4, H5.\n  simpljoin1.\n  simpl.\n  eapply get_R_merge_still; eauto.\n  eapply getR_eq_get_genreg_val; eauto.\n  split.\n  simpl_sep_liftn_in H1 2.\n  sep_star_split_tac.\n  simpl in H4, H5.\n  simpljoin1.\n  simpl.\n  eapply eval_addrexp_merge_still; eauto.\n  eapply eval_aexp_reg_eq_eval_aexp; eauto.\n  sep_star_split_tac.\n  simpl in H4.\n  simpl in H5. \n  simpljoin1.\n  simpl in H1.\n  simpljoin1; eauto.\n  intros.\n  sep_cancel1 1 2.\n  eauto.\n  intros.\n  sep_cancel1 2 1.\n  eauto.\nQed.\n\nTheorem save_rule_reg :\n  forall p (rs rd : GenReg) (id id' : Word) (F : FrameList)\n         (fm1 fm2 fmg fmo fml fmi : Frame) (v : Word) v1 v2 res (oexp : OpExp),\n    Some res = val_add v1 v2 ->\n    get_genreg_val (fmg, fmo, fml, fmi) rs = v1 ->\n    eval_opexp_reg (fmg, fmo, fml, fmi) oexp = Some v2 ->\n    id' = pre_cwp id -> win_masked id' v = false ->\n    |- {{ GenRegs (fmg, fmo, fml, fmi) ** Rwim |=> W v ** {| id, F ++ [fm1; fm2] |} ** p }}\n        save rs oexp rd\n      {{ GenRegs (upd_genreg (fmg, fm1, fm2, fmo) rd res) ** Rwim |=> W v **\n                 {| id', fml :: fmi :: F |} ** p }}.\nProof.\n  introv Hres; intros.\n  eapply ins_conseq_rule.\n  instantiate (1 := Rwim |=> W v ** GenRegs (fmg, fmo, fml, fmi) **\n                         {|id, F ++ [fm1; fm2]|} ** p).\n  intros.\n  sep_cancel1 2 1.\n  eauto.\n  eapply save_rule; eauto.\n  { \n    intros.\n    sep_star_split_tac.\n    simpl in H6, H7.\n    simpljoin1.\n    simpl sat.\n    split.\n    {\n      eapply getR_eq_get_genreg_val with (rr := rs) in H3; eauto.\n      clear - H3.\n      eapply get_R_merge_still; eauto.\n    }\n    {\n      eapply eval_opexp_merge_still; eauto.\n      eapply eval_opexp_reg_eq_eval_opexp; eauto.\n    }\n  }\n  {\n    intros.\n    instantiate (1 := GlobalRegs fmg ** p).\n    instantiate (3 := fmo).\n    instantiate (2 := fml).\n    instantiate (1 := fmi).\n    sep_cancel1 2 1.\n    eapply astar_comm in H4.\n    sliftn 3.\n    sep_cancel1 1 1.\n    unfold GenRegs in H3.\n    unfold Regs.\n    eapply astar_comm.\n    sep_cancel1 1 1.\n    eauto.\n  } \n  {\n    intros.\n    instantiate (1 := {|id', fml :: fmi :: F|} ** GenRegs_rm_one (fmg, fm1, fm2, fmo) rd ** p).\n    instantiate (1 := (get_genreg_val' (fmg, fm1, fm2, fmo) rd)).\n    sep_cancel1 1 2.\n    eapply GenRegs_split_one; eauto.\n    eapply Regs_Global_combine_GenRegs; eauto.\n  }\n  {\n    intros.\n    sep_cancel1 1 2.\n    sep_cancel1 2 2.\n    eapply GenRegs_upd_combine_one; eauto.\n  }\nQed.\n\nTheorem restore_rule_reg :\n  forall p (rs rd : GenReg) (id id' : Word) (F : FrameList)\n         (fm1 fm2 fmg fmo fml fmi : Frame) v1 v2 v (res : Val) (oexp : OpExp),\n    Some res = val_add v1 v2 ->\n    get_genreg_val (fmg, fmo, fml, fmi) rs = v1 ->\n    eval_opexp_reg (fmg, fmo, fml, fmi) oexp = Some v2 ->\n    id' = post_cwp id -> win_masked id' v = false ->\n    |- {{ GenRegs (fmg, fmo, fml, fmi) ** Rwim |=> W v ** {| id, fm1 :: fm2 :: F |} ** p }}\n        restore rs oexp rd\n      {{ GenRegs (upd_genreg (fmg, fmi, fm1, fm2) rd res) ** Rwim |=> W v **\n                 {| id', F ++ [fmo; fml] |} ** p }}.\nProof.\n  introv Hres; intros.\n  eapply ins_conseq_rule.\n  instantiate (1 := Rwim |=> W v ** GenRegs (fmg, fmo, fml, fmi) **\n                         {|id, fm1 :: fm2 :: F|} ** p).\n  intros.\n  sep_cancel1 1 2.\n  eauto.\n  eapply restore_rule; eauto.\n  {\n    intros.\n    simpl.\n    sep_star_split_tac.\n    simpl in H6, H7.\n    simpljoin1.\n    simpl getregs.\n    split.\n    eapply get_R_merge_still; eauto.\n    eapply getR_eq_get_genreg_val; eauto.\n    eapply eval_opexp_merge_still; eauto.\n    eapply eval_opexp_reg_eq_eval_opexp; eauto.\n  }\n  {\n    intros.\n    sep_cancel1 2 1.\n    instantiate (1 := GlobalRegs fmg ** p).\n    sliftn_in H4 2.\n    sliftn 3.\n    sep_cancel1 1 1.\n    unfold GenRegs in H3.\n    sliftn 2.\n    sep_cancel1 1 1.\n    unfold Regs.\n    eauto.\n  }\n  {\n    intros.\n    instantiate (1 := {|id', F ++ [fmo; fml]|} ** GenRegs_rm_one (fmg, fmi, fm1, fm2) rd ** p).\n    instantiate (1 := (get_genreg_val' (fmg, fmi, fm1, fm2) rd)).\n    sep_cancel1 1 2.\n    eapply Regs_Global_combine_GenRegs in H4.\n    eapply GenRegs_split_one; eauto.\n  }\n  {\n    intros.\n    sep_cancel1 1 2.\n    sep_cancel1 2 2.\n    eapply GenRegs_upd_combine_one; eauto.\n  }\nQed.\n\nTheorem subcc_rule_reg :\n  forall oexp (rs rd : GenReg) v1 v2 v grst vn vz p,\n    get_genreg_val grst rs = W v1 ->\n    eval_opexp_reg grst oexp = Some (W v2) -> v = v1 -ᵢ v2 ->\n    |- {{ GenRegs grst ** n |=> vn ** z |=> vz ** p  }}\n        subcc rs oexp rd\n      {{ GenRegs (upd_genreg grst rd (W v)) ** n |=> W (get_range 31 31 v) ** z |=> W (iszero v) ** p }}.\nProof.\n  intros.\n  eapply ins_conseq_rule.\n  eauto.\n  eapply subcc_rule.\n  {\n    introv Hs.\n    instantiate (2 := v1).\n    instantiate (1 := v2).\n    simpl.\n    split.\n    sep_star_split_tac.\n    simpl in H3, H5, H6.\n    simpljoin1.\n    simpl.\n    eapply get_R_merge_still; eauto. \n    eapply getR_eq_get_genreg_val in H4; rewrite H4, H; eauto.\n    sep_star_split_tac.\n    simpl in H3, H5, H6.\n    simpljoin1.\n    simpl.\n    eapply eval_opexp_merge_still; eauto.\n    eapply eval_opexp_reg_eq_eval_opexp; eauto.\n  }\n  {\n    eauto.\n  }\n  {\n    introv Hs.\n    instantiate (4 := (get_genreg_val' grst rd)).\n    instantiate (1 := (GenRegs_rm_one grst rd ** p)).\n    instantiate (1 := vz).\n    instantiate (1 := vn).\n    sep_cancel1 2 2.\n    sep_cancel1 2 2.\n    eapply GenRegs_split_one; eauto.\n  }\n  {\n    introv Hs.\n    sep_cancel1 2 2.\n    sep_cancel1 2 2.\n    eapply GenRegs_upd_combine_one; eauto.\n  }\nQed.\n\nTheorem andcc_rule_reg :\n  forall oexp (rs rd : GenReg) v1 v2 v grst vn vz p,\n    get_genreg_val grst rs = W v1 ->\n    eval_opexp_reg grst oexp = Some (W v2) -> v = v1 &ᵢ v2 ->\n    |- {{ GenRegs grst ** n |=> vn ** z |=> vz ** p  }}\n        andcc rs oexp rd\n      {{ GenRegs (upd_genreg grst rd (W v)) ** n |=> W (get_range 31 31 v) ** z |=> W (iszero v) ** p }}.\nProof.\n  intros.\n  eapply ins_conseq_rule.\n  eauto.\n  eapply andcc_rule; eauto.\n  {\n    introv Hs.\n    simpl.\n    split.\n    sep_star_split_tac.\n    simpl in H3, H5, H6.\n    simpljoin1.\n    simpl.\n    eapply get_R_merge_still; eauto.\n    eapply getR_eq_get_genreg_val in H4; eauto; rewrite H4, H; eauto.\n    sep_star_split_tac.\n    simpl in H3, H5, H6.\n    simpljoin1.\n    simpl.\n    eapply eval_opexp_merge_still; eauto.\n    eapply eval_opexp_reg_eq_eval_opexp; eauto.\n  }\n  {\n    introv Hs.\n    instantiate (4 := (get_genreg_val' grst rd)).\n    instantiate (1 := (GenRegs_rm_one grst rd ** p)).\n    instantiate (1 := vz).\n    instantiate (1 := vn).\n    sep_cancel1 2 2.\n    sep_cancel1 2 2.\n    eapply GenRegs_split_one; eauto.\n  }\n  {\n    introv Hs.\n    sep_cancel1 2 2.\n    sep_cancel1 2 2.\n    eapply GenRegs_upd_combine_one; eauto.\n  }\nQed.\n\nTheorem rd_rule_reg :\n  forall (rsp : SpReg) v (rr : GenReg) p grst,\n    |- {{ GenRegs grst ** rsp |=> W v ** p }}\n        rd rsp rr\n      {{ GenRegs (upd_genreg grst rr (W v)) ** rsp |=> W v ** p }}.\nProof.\n  intros.\n  eapply ins_conseq_rule with\n  (p1 := rsp |=> W v ** rr |=> get_genreg_val' grst rr ** GenRegs_rm_one grst rr ** p).\n  Focus 2.\n  eapply rd_rule; eauto.\n  introv Hs.\n  sep_cancel1 2 1.\n  eapply GenRegs_split_one; eauto.\n  introv Hs.\n  sep_cancel1 1 2.\n  eapply GenRegs_upd_combine_one; eauto.\nQed.\n\nTheorem wr_rule_reg :\n  forall oexp (rs : GenReg) v1 v2 v grst (rsp : SpReg) p,\n    get_genreg_val grst rs = W v1 ->\n    eval_opexp_reg grst oexp = Some (W v2) ->\n    |- {{ GenRegs grst ** rsp |=> v ** p }}\n        wr rs oexp rsp\n      {{ GenRegs grst ** 3 @ rsp |==> set_spec_reg rsp (v1 xor v2) ** p }}.\nProof.\n  intros. \n  eapply ins_conseq_rule with (p1 := rsp |=> v ** GenRegs grst ** p).\n  Focus 2.\n  eapply wr_rule; eauto.\n  instantiate (2 := v1).\n  instantiate (1 := v2).\n  introv Hs.\n  simpl_sep_liftn_in Hs 2.\n  simpl.\n  split.\n  \n    subst. \n    sep_star_split_tac.\n    simpl in H4, H5.\n    simpljoin1.\n    simpl.\n    eapply get_R_merge_still; eauto.\n    eapply getR_eq_get_genreg_val in H3; eauto; rewrite H3, H; eauto.  \n  \n    sep_star_split_tac.\n    simpl in H4, H5.\n    simpljoin1.\n    simpl.\n    eapply eval_opexp_merge_still; eauto.\n    eapply eval_opexp_reg_eq_eval_opexp; eauto.\n\n  introv Hs.\n  sep_cancel1 1 2.\n  eauto.\n  introv Hs.\n  sep_cancel1 2 1.\n  eauto.\nQed.\n", "meta": {"author": "jpzha", "repo": "VeriSparc", "sha": "7fc60fbc4b4357b93836d1b461d7d27c669e9f58", "save_path": "github-repos/coq/jpzha-VeriSparc", "path": "github-repos/coq/jpzha-VeriSparc/VeriSparc-7fc60fbc4b4357b93836d1b461d7d27c669e9f58/coqimp/example/lib/reg_lemma.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.27842270890852244}}
{"text": "(** * Simulation environment for the H-VHDL semantics. *)\n\n(** Module defining the components of the simulation environment.  *)\n\nRequire Import Setoid.\nRequire Import common.CoqLib.\nRequire Import common.NatMap.\nRequire Import common.NatSet.\nRequire Import common.ListPlus.\nRequire Import common.GlobalTypes.\n\nRequire Import hvhdl.AbstractSyntax.\nRequire Import hvhdl.SemanticalDomains.\nRequire Import hvhdl.HVhdlTypes.\n\nOpen Scope natset_scope.\n\n(** ** Miscellaneous Environment Definitions *)\n\n(** *** Equal Domains *)\n\n(** Defines the design environment describing H-VHDL design instances\n    in the semantical world. The design environment maps identifiers\n    of a certain category of constructs (e.g, constant identifiers) to\n    their declaration information (e.g, type and value for\n    constants). *)\n\n(** Definition of the [dom] function that yields a list of identifiers\n    corresponding to the definition domain of an IdMap. *)\n\nDefinition EqualDom {A} (m m' : NatMap.t A) : Prop := forall (k : nat), NatMap.In k m <-> NatMap.In k m'.\nDefinition dom {A : Type} (f : IdMap A) : list ident := fs (NatMap.elements f).\n\nDefinition EqualDom_refl : forall {A} (m : IdMap A), EqualDom m m. firstorder. Defined.\nDefinition EqualDom_trans : forall {A} (m m' m'' : IdMap A), EqualDom m m' -> EqualDom m' m'' -> EqualDom m m''.\n  unfold EqualDom; intros; transitivity (NatMap.In k m'); auto.\nDefined.\nDefinition EqualDom_sym : forall {A} (m m' : IdMap A), EqualDom m m' -> EqualDom m' m.\n  unfold EqualDom; symmetry; auto.\nDefined.\n\nAdd Parametric Relation {A : Type} : (IdMap A) (EqualDom)\n    reflexivity proved by EqualDom_refl\n    symmetry proved by EqualDom_sym\n    transitivity proved by EqualDom_trans\n      as EqualDom_rel.           \n\n#[export] Hint Resolve EqualDom_refl : hvhdl.\n#[export] Hint Resolve EqualDom_trans : hvhdl.\n#[export] Hint Resolve EqualDom_sym : hvhdl.\n\n(** Defines the relation stating that a set [idset] is the\n    differentiated intersection of two maps [m] and [m'] mapping\n    identifier to value.\n    \n    The differentiated intersection of two maps [m] and [m'] is the\n    set { x ∈ dom(m) ∩ dom(m') | m(x) ≠ m'(x) }. \n *)\n\nDefinition IsDiffInter (m m' : IdMap value) (idset : IdSet) :=\n  (forall id v v', NatSet.In id idset -> MapsTo id v m -> MapsTo id v' m' -> ~VEq v v') /\\\n  (forall id v v', MapsTo id v m -> MapsTo id v' m' -> ~VEq v v' -> NatSet.In id idset).\n\n(** Defines the relation stating that a map [ovunion] results of the\n    overriding union of two maps [ovridden] and [ovriding].\n\n    A map [m''] results of the overriding union of maps [m] and [m']\n    if m'' = λx. m'(x) if x ∈ dom(m') ∧ m(x) otherwise.\n\n    We add in the relation definition that the overridden map\n    [ovridden] and the resulting map [ovunion] must have the same\n    definition domains.  *)\n\nDefinition IsOverrUnion (ovridden ovriding ovunion : IdMap value) :=\n  EqualDom ovridden ovunion /\\\n  (forall id v, MapsTo id v ovriding -> MapsTo id v ovunion) /\\\n  (forall id v, ~NatMap.In id ovriding -> MapsTo id v ovridden -> MapsTo id v ovunion).\n\n(** ** Local Environment *)\n\n(** Defines a process local variable environment as a map from local\n    variable identifiers to couples (type * value).  *)\n\nDefinition LEnv := IdMap (type * value).\n\n(** Defines an empty process local variable environment. *)\n\nDefinition EmptyLEnv := NatMap.empty (type * value).\n\n\n(** ** Elaborated Design *)\n\n(** Elaborated design attributes *)\n\n(* Needed because the inductive definition of the [DesignAttribute]\n   type does not respect the strict positivity requirement.\n   \n   However, I am almost sure that it is not dangerous to do so. *)\n\nLocal Unset Positivity Checking.\n\n(** Defines an elaborated design as a mapping from identifiers to\n    [DesignAttribute]. *)\n\nInductive ElDesign : Type :=\n| MkElDesign :> NatMap.t DesignAttribute -> ElDesign\nwith DesignAttribute  :=\n| Generic (t : type) (v : value)\n| Input (t : type)\n| Output (t : type)\n| Internal (t : type)\n| Process (lenv : LEnv)\n| Component (Δ__c : ElDesign).\n\nCoercion ElDesign_to_IdMap (Δ : ElDesign) : NatMap.t DesignAttribute :=\n  match Δ with MkElDesign m => m end.\n\n(** Defines a bare elaborated design. *)\n\nDefinition EmptyElDesign := MkElDesign (NatMap.empty DesignAttribute).\n\n(** *** Identifiers qualification *)\n\nDefinition GenericOf (Δ : ElDesign) id :=\n  exists t v, MapsTo id (Generic t v) Δ.\n\nDefinition InputOf (Δ : ElDesign) id :=\n  exists t, MapsTo id (Input t) Δ.\n\nDefinition OutputOf (Δ : ElDesign) id :=\n  exists t, MapsTo id (Output t) Δ.\n\nDefinition InternalOf (Δ : ElDesign) id :=\n  exists t, MapsTo id (Internal t) Δ.\n\nDefinition ProcessOf (Δ : ElDesign) id :=\n  exists Λ, MapsTo id (Process Λ) Δ.\n\nDefinition CompOf (Δ : ElDesign) id :=\n  exists Δ__c, MapsTo id (Component Δ__c) Δ.\n\n(** ** Design State *)\n\n(** Defines the structure of design state composed of a signal store\n    [sstore], and a design instance store [cstore]. *)\n\nInductive DState : Type :=\n  MkDState {\n      sstore  : IdMap value;\n      cstore : IdMap DState;\n    }.\n\n(** Defines an empty design state. *)\n\nDefinition EmptyDState := MkDState (NatMap.empty value)\n                                   (NatMap.empty DState).\n\nDefinition EmptySStore := (NatMap.empty value).\n\n(** Macro to add, or to override, a mapping [id ⇒ value] in the\n    [sstore] of the design state [σ].  *)\n\nDefinition sstore_add (id : ident) (v : value) (σ : DState) : DState :=\n  MkDState (NatMap.add id v (sstore σ)) (cstore σ).\n\n(** Macro to add, or to override, a mapping [id__c ⇒ σ__c] in the [cstore]\n    of the design state [σ].  *)\n\nDefinition cstore_add (id__c : ident) (σ__c : DState) (σ : DState) : DState :=\n  MkDState (sstore σ) (NatMap.add id__c σ__c (cstore σ)).\n\n(** Defines the [InSStore] predicate that states that [id] is mapped\n    to a value in the [sstore] of design state [σ].\n\n    Wrapper around the [In] predicate.  *)\n\nDefinition InSStore (id : ident) (σ : DState) :=\n  NatMap.In id (sstore σ).\n\n\n(** Design state equality relation *)\n\nInductive DStateEq (σ1 σ2 : DState) : Prop :=\n  DSEq {\n      sstore_eq :\n      forall id v1 v2,\n        NatMap.MapsTo id v1 (sstore σ1) ->\n        NatMap.MapsTo id v2 (sstore σ2) ->\n        VEq v1 v2;\n\n      cstore_eq :\n      forall id σ__c1 σ__c2,\n        NatMap.MapsTo id σ__c1 (cstore σ1) ->\n        NatMap.MapsTo id σ__c2 (cstore σ2) ->\n        DStateEq σ__c1 σ__c2\n    }.\n\n(** DStateEq is decidable *)\n\nLemma DStateEq_dec : forall x y, {DStateEq x y} + {~DStateEq x y}. Admitted.\n\n(** Predicate stating that a DState [σ__m] results from the\n    interleaving of an origin DState [σ__o], and two DState\n    [σ'] and [σ''].\n\n    To understand the predicate, one can consider that the states\n    [σ'] and [σ''] result from the parallel execution of two\n    concurrent statements in the context of [σ__o].  \n\n*)\n\nRecord IsMergedDState (σ__o σ' σ'' σ__m : DState) : Prop :=\n  IMDS {\n\n      (* Describes the content of [(sstore σ__m)] *)\n      sstore1 :\n      forall id v1 v2,\n        NatMap.MapsTo id v1 (sstore σ') ->\n        NatMap.MapsTo id v2 (sstore σ__o) ->\n        VNEq v1 v2 ->\n        NatMap.MapsTo id v1 (sstore σ__m);\n\n      sstore2 :\n      forall id v1 v2,\n        NatMap.MapsTo id v1 (sstore σ'') ->\n        NatMap.MapsTo id v2 (sstore σ__o) ->\n        VNEq v1 v2 ->\n        NatMap.MapsTo id v1 (sstore σ__m);\n\n      sstore__o :\n      forall id v__o v1 v2,\n        NatMap.MapsTo id v__o (sstore σ__o) ->\n        NatMap.MapsTo id v1 (sstore σ') ->\n        NatMap.MapsTo id v2 (sstore σ'') ->\n        VEq v__o v1 ->\n        VEq v__o v2 ->\n        NatMap.MapsTo id v__o (sstore σ__m);\n\n      (* Describes the content of [(cstore σ__m)] *)\n      cstore1 :\n      forall id σ__c1 σ__c2,\n        NatMap.MapsTo id σ__c1 (cstore σ') ->\n        NatMap.MapsTo id σ__c2 (cstore σ__o) ->\n        ~DStateEq σ__c1 σ__c2 ->\n        NatMap.MapsTo id σ__c1 (cstore σ__m);\n\n      cstore2 :\n      forall id σ__c1 σ__c2,\n        NatMap.MapsTo id σ__c1 (cstore σ'') ->\n        NatMap.MapsTo id σ__c2 (cstore σ__o) ->\n        ~DStateEq σ__c1 σ__c2 ->\n        NatMap.MapsTo id σ__c1 (cstore σ__m);\n\n      cstore__o :\n      forall id σ__co σ__c1 σ__c2,\n        NatMap.MapsTo id σ__co (cstore σ__o) ->\n        NatMap.MapsTo id σ__c1 (cstore σ') ->\n        NatMap.MapsTo id σ__c2 (cstore σ'') ->\n        DStateEq σ__co σ__c1 ->\n        DStateEq σ__co σ__c2 ->\n        NatMap.MapsTo id σ__co (cstore σ__m)\n                      \n    }.\n\n(** Looks up the value associated to [id] in map [m1] and [m2] and\n    compares it to [v0]. If values are equal then the [v0] is\n    returned, otherwise the looked-up value is returned.\n\n    Note that if [id] is not bound in [m1] or [m2], [v0] is\n    returned instead of raising an error, in order to have a total\n    function.  *)\n\nDefinition get_freshest_value {A : Type}\n  {Aeq : A -> A -> Prop}\n  (Aeq_dec : forall x y, {Aeq x y} + {~Aeq x y})\n  (m1 m2 : IdMap A) (id : ident) (v0 : A) : A :=\n  match find id m1 with\n  | Some v1 =>\n      if Aeq_dec v0 v1 then\n        match find id m2 with\n        | Some v2 => if Aeq_dec v0 v2 then v0 else v2\n        (* Case [id] is not bound in [m1] *)\n        | None => v0\n        end\n      else v1\n  (* Case [id] is not bound in [m1] *)\n  | None => v0\n  end.\n\n(** Returns a new identifier map where the identifiers bound in [m0]\n    are associated with the freshest value either coming from [m1] or\n    [m2], or from [m0] if an identifier is associated with the same\n    value in the three maps. *)\n\nDefinition merge_idmap {A : Type}\n           {Aeq : A -> A -> Prop}\n           (Aeq_dec : forall x y, {Aeq x y} + {~Aeq x y})\n           (m0 m1 m2 : IdMap A) : IdMap A :=\n  NatMap.mapi (get_freshest_value Aeq_dec m1 m2) m0.\n\n(** Returns a new design state resulting from the merging of the\n    origin state [σ0] with the two states [σ1] and [σ2]. *)\n\nDefinition merge (σ0 σ1 σ2 : DState) : DState :=\n  MkDState\n    (merge_idmap value_eq_dec (sstore σ0) (sstore σ1) (sstore σ2))\n    (merge_idmap DStateEq_dec (cstore σ0) (cstore σ1) (cstore σ2)).\n\n(** Defines the relation stating that a design state [σ__i] is the\n    result of the \"injection\" of the values of map [m] in the\n    [sstore] of design state [σ__o]. *)\n\nDefinition IsInjectedDState (σ__o : DState) (m : IdMap value) (σ__i : DState) : Prop :=\n  IsOverrUnion (sstore σ__o) m (sstore σ__i).\n\n(** Overrides map [m0] with the values defined in map [m1] for all\n    identifiers mapped in [m0] and [m1]. *)\n\nDefinition inj_in_map {A : Type} (m0 m1 : IdMap A) :=\n  let overr_value id v := match find id m1 with\n                          | Some v1 => v1\n                          | None => v\n                          end in\n  NatMap.mapi overr_value m0.\n\n(** Overrides the signal store of state [σ] with the values of map\n    [m]. *)\n\nDefinition inj (σ : DState) (m : IdMap value) : DState :=\n  MkDState (inj_in_map (sstore σ) m) (cstore σ).\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/Environment.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2783581684962445}}
{"text": "Require Import oeuf.Common.\nRequire Import oeuf.Utopia.\n\nRequire Import oeuf.Metadata.\nRequire Import oeuf.Semantics.\nRequire Import oeuf.HighestValues.\nRequire Import oeuf.AllValues.\nRequire Import oeuf.OpaqueOps.\nRequire Import oeuf.ListLemmas.\n\n\nInductive expr :=\n| Value (v : value)\n| Arg\n| UpVar (idx : nat)\n| App (f : expr) (a : expr)\n| MkConstr (ctor : constr_name) (args : list expr)\n| MkClose (fname : nat) (free : list expr)\n| Elim (ty : type_name) (cases : list expr) (target : expr)\n| OpaqueOp (o : opaque_oper_name) (args : list expr)\n.\n\nInductive is_value : expr -> Prop :=\n| IsValue : forall v, is_value (Value v).\n\n\nInductive cont :=\n| KAppL (e2 : expr) (l : list value) (k : cont)\n| KAppR (e1 : expr) (l : list value) (k : cont)\n| KConstr (ctor : constr_name) (vs : list expr) (es : list expr)\n        (l : list value) (k : cont)\n| KClose (fname : nat) (vs : list expr) (es : list expr)\n        (l : list value) (k : cont)\n| KElim (ty : type_name) (cases : list expr) (l : list value) (k : cont)\n| KOpaqueOp (o : opaque_oper_name) (vs : list expr) (es : list expr)\n        (l : list value) (k : cont)\n| KStop\n.\n\nInductive state :=\n| Run (e : expr) (l : list value) (k : cont)\n| Stop (v : value)\n.\n\n\n(* helper function for proceeding into a continuation *)\nDefinition run_cont (k : cont) : value -> state :=\n    match k 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 (MkConstr ct (vs ++ Value v :: es)) l k\n    | KClose mb vs es l k =>\n            fun v => Run (MkClose mb (vs ++ Value v :: es)) l k\n    | KElim e cases l k =>\n            fun v => Run (Elim e cases (Value v)) l k\n    | KOpaqueOp o vs es l k =>\n            fun v => Run (OpaqueOp o (vs ++ Value v :: es)) l k\n    | KStop => fun v => Stop v\n    end.\n\n\n(* helper function for proceeding into an elim *)\nFixpoint unroll_elim' (case : expr)\n                      (ctor : constr_name)\n                      (args : list value)\n                      (mk_rec : expr -> expr)\n                      (idx : nat) : expr :=\n    match args with\n    | [] => case\n    | arg :: args =>\n            let case := App case (Value arg) in\n            let case := if ctor_arg_is_recursive ctor idx\n                then App case (mk_rec (Value arg)) else case in\n            unroll_elim' case ctor args mk_rec (S idx)\n    end.\n\nDefinition unroll_elim case ctor args mk_rec :=\n    unroll_elim' case ctor args mk_rec 0.\n\n(* the actual step relation *)\nInductive sstep (g : list expr) : state -> state -> Prop :=\n| SValue : forall v (l : list value) (k : cont),\n        sstep g (Run (Value v) l k)\n                (run_cont k v)\n\n| SArg : forall (l : list value) (k : cont) v,\n        nth_error l 0 = Some v ->\n        sstep g (Run (Arg) l k)\n                (Run (Value v) l k)\n\n| SUpVar : forall idx (l : list value) (k : cont) v,\n        nth_error l (S idx) = Some v ->\n        sstep g (Run (UpVar idx) l k)\n                (Run (Value v) l k)\n\n| SAppL : forall (e1 : expr) (e2 : expr) 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 (e1 : expr) (e2 : expr) 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 fname free arg l k body,\n        nth_error g fname = Some body ->\n        sstep g (Run (App (Value (Close fname free)) (Value arg)) l k)\n                (Run body (arg :: free) k)\n\n| SConstrStep : forall\n            (ctor : constr_name)\n            (vs : list expr)\n            (e : expr)\n            (es : list expr)\n            l k,\n        Forall is_value vs ->\n        ~ is_value e ->\n        sstep g (Run (MkConstr ctor (vs ++ e :: es)) l k)\n                (Run e l (KConstr ctor vs es l k))\n\n| SConstrDone : forall\n            (ctor : constr_name)\n            (vs : list value)\n            l k,\n        let es := map Value vs in\n        sstep g (Run (MkConstr ctor es) l k)\n                (Run (Value (Constr ctor vs)) l k)\n\n| SCloseStep : forall\n            (fname : nat)\n            (vs : list expr)\n            (e : expr)\n            (es : list expr)\n            l k,\n        Forall is_value vs ->\n        ~ is_value e ->\n        sstep g (Run (MkClose fname (vs ++ e :: es)) l k)\n                (Run e l (KClose fname vs es l k))\n\n| SCloseDone : forall\n            (fname : nat)\n            (vs : list value)\n            l k,\n        let es := map Value vs in\n        sstep g (Run (MkClose fname es) l k)\n                (Run (Value (Close fname vs)) l k)\n\n| SOpaqueOpStep : forall\n            (o : opaque_oper_name)\n            (vs : list expr)\n            (e : expr)\n            (es : list expr)\n            l k,\n        Forall is_value vs ->\n        ~ is_value e ->\n        sstep g (Run (OpaqueOp o (vs ++ e :: es)) l k)\n                (Run e l (KOpaqueOp o vs es l k))\n\n| SOpaqueOpDone : forall\n            (o : opaque_oper_name)\n            (vs : list value)\n            (v' : value)\n            l k,\n        let es := map Value vs in\n        opaque_oper_denote_highest o vs = Some v' ->\n        sstep g (Run (OpaqueOp o es) l k)\n                (Run (Value v') l k)\n\n| SElimTarget : forall\n            (ty : type_name)\n            (cases : list expr)\n            (target : expr)\n            l k,\n        ~ is_value target ->\n        sstep g (Run (Elim ty cases target) l k)\n                (Run target l (KElim ty cases l k))\n\n| SEliminate : forall\n            (ty : type_name)\n            (cases : list expr)\n            (ctor : constr_name)\n            (args : list value)\n            (case : expr)\n            (result : expr)\n            l k,\n        is_ctor_for_type ty ctor ->\n        constructor_arg_n ctor = length args ->\n        nth_error cases (constructor_index ctor) = Some case ->\n        unroll_elim case ctor args (Elim ty cases) = result ->\n        sstep g (Run (Elim ty cases (Value (Constr ctor args))) l k)\n                (Run result l k)\n.\n\n\n\nDefinition expr_rect_mut (P : expr -> Type) (Pl : list expr -> Type)\n    (HValue :   forall v, P (Value v))\n    (HArg :     P Arg)\n    (HUpVar :   forall idx, P (UpVar idx))\n    (HApp :     forall f a, P f -> P a -> P (App f a))\n    (HMkConstr : forall c args, Pl args -> P (MkConstr c args))\n    (HMkClose : forall f free, Pl free -> P (MkClose f free))\n    (HElim :    forall ty cases target, Pl cases -> P target -> P (Elim ty cases target))\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    (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        match e as e_ return P e_ with\n        | Value v => HValue v\n        | Arg => HArg\n        | UpVar idx => HUpVar idx\n        | App f a => HApp f a (go f) (go a)\n        | MkConstr c args => HMkConstr c args (go_list args)\n        | MkClose f free => HMkClose f free (go_list free)\n        | Elim ty cases target => HElim ty cases target (go_list cases) (go target)\n        | OpaqueOp o args => HOpaqueOp o args (go_list args)\n        end in go e.\n\nDefinition expr_rect_mut' (P : expr -> Type) (Pl : list expr -> Type)\n    HValue HArg HUpVar HApp HMkConstr HMkClose HElim HOpaqueOp Hnil Hcons\n    : (forall e, P e) * (forall es, Pl es) :=\n    let go := expr_rect_mut P Pl\n        HValue HArg HUpVar HApp HMkConstr HMkClose HElim HOpaqueOp Hnil Hcons\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    (go, go_list).\n\n\n\n(* semantics *)\n\nDefinition env := list expr.\nDefinition prog_type : Type := list expr * list metadata.\nDefinition val_level := VlHighest.\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        is_callstate prog fv av\n            (Run body (av :: free) KStop).\n\nInductive final_state (prog : prog_type) : state -> valtype -> Prop :=\n| FinalState : forall v,\n        HighestValues.public_value (snd prog) v ->\n        final_state prog (Stop v) v.\n\nDefinition semantics (prog : prog_type) : Semantics.semantics :=\n  @Semantics_gen state env val_level\n                 (is_callstate prog)\n                 (sstep)\n                 (final_state prog)\n                 (initial_env prog).\n\n\n\nDefinition no_values : expr -> Prop :=\n    let fix go e :=\n        let fix go_list es :=\n            match es with\n            | [] => True\n            | e :: es => go e /\\ go_list es\n            end in\n        match e with\n        | Value _ => False\n        | Arg => True\n        | UpVar _ => True\n        | App f a => go f /\\ go a\n        | MkConstr _ args => go_list args\n        | MkClose _ free => go_list free\n        | Elim _ cases target => go_list cases /\\ go target\n        | OpaqueOp _ args => go_list args\n        end in go.\n\nDefinition no_values_list : list expr -> Prop :=\n    let go := no_values in\n    let fix go_list es :=\n        match es with\n        | [] => True\n        | e :: es => go e /\\ go_list es\n        end in go_list.\n\nLtac refold_no_values :=\n    fold no_values_list in *.\n\nLemma no_values_list_is_Forall : forall es,\n    no_values_list es <-> Forall no_values es.\ninduction es; simpl; split; inversion 1; constructor; firstorder eauto.\nQed.\n\nDefinition no_values_dec e : { no_values e } + { ~ no_values e }.\ninduction e using expr_rect_mut with\n    (Pl := fun es => { no_values_list es } + { ~ no_values_list es });\nsimpl in *; refold_no_values;\ntry solve [ assumption | left; constructor | right; inversion 1 ].\n\n- destruct IHe1; [ | right; inversion 1; intuition ].\n  destruct IHe2; [ | right; inversion 1; intuition ].\n  left. constructor; auto.\n\n- destruct IHe; [ | right; inversion 1; intuition ].\n  destruct IHe0; [ | right; inversion 1; intuition ].\n  left. constructor; auto.\n\n- destruct IHe; [ | right; inversion 1; intuition ].\n  destruct IHe0; [ | right; inversion 1; intuition ].\n  left. constructor; auto.\nDefined.\n\nDefinition no_values_list_dec es : { no_values_list es } + { ~ no_values_list es }.\ninduction es.\n- left. constructor.\n- simpl; refold_no_values.  rename a into e.\n  destruct (no_values_dec e); [ | right; intuition ].\n  destruct IHes; [ | right; intuition ].\n  left. auto.\nDefined.\n\n\n\nDefinition cases_arent_values : expr -> Prop :=\n    let fix go e :=\n        let fix go_list es :=\n            match es with\n            | [] => True\n            | e :: es => go e /\\ go_list es\n            end in\n        match e with\n        | Value _ => True\n        | Arg => True\n        | UpVar _ => True\n        | App f a => go f /\\ go a\n        | MkConstr _ args => go_list args\n        | MkClose _ free => go_list free\n        | Elim _ cases target =>\n                Forall (fun e => ~ is_value e) cases /\\\n                go_list cases /\\ go target\n        | OpaqueOp _ args => go_list args\n        end in go.\n\nDefinition cases_arent_values_list : list expr -> Prop :=\n    let go := cases_arent_values in\n    let fix go_list es :=\n        match es with\n        | [] => True\n        | e :: es => go e /\\ go_list es\n        end in go_list.\n\nLtac refold_cases_arent_values :=\n    fold cases_arent_values_list in *.\n\nLemma cases_arent_values_list_is_Forall : forall es,\n    cases_arent_values_list es <-> Forall cases_arent_values es.\ninduction es; simpl; split; inversion 1; constructor; firstorder eauto.\nQed.\n\nInductive cases_arent_values_cont : cont -> Prop :=\n| CavkAppL : forall e2 l k,\n        cases_arent_values e2 ->\n        cases_arent_values_cont k ->\n        cases_arent_values_cont (KAppL e2 l k)\n| CavkAppR : forall e1 l k,\n        cases_arent_values e1 ->\n        cases_arent_values_cont k ->\n        cases_arent_values_cont (KAppR e1 l k)\n| CavkConstr : forall ctor vs es l k,\n        Forall cases_arent_values vs ->\n        Forall cases_arent_values es ->\n        cases_arent_values_cont k ->\n        cases_arent_values_cont (KConstr ctor vs es l k)\n| CavkClose : forall fname vs es l k,\n        Forall cases_arent_values vs ->\n        Forall cases_arent_values es ->\n        cases_arent_values_cont k ->\n        cases_arent_values_cont (KClose fname vs es l k)\n| CavkElim : forall ty cases l k,\n        Forall (fun e => ~ is_value e) cases ->\n        Forall cases_arent_values cases ->\n        cases_arent_values_cont k ->\n        cases_arent_values_cont (KElim ty cases l k)\n| CavkOpaqueOp : forall op vs es l k,\n        Forall cases_arent_values vs ->\n        Forall cases_arent_values es ->\n        cases_arent_values_cont k ->\n        cases_arent_values_cont (KOpaqueOp op vs es l k)\n| CavkStop : cases_arent_values_cont KStop\n.\n\nInductive cases_arent_values_state : state -> Prop :=\n| CavsRun : forall e l k,\n        cases_arent_values e ->\n        cases_arent_values_cont k ->\n        cases_arent_values_state (Run e l k)\n| CavsStop : forall v,\n        cases_arent_values_state (Stop v)\n.\n\n\n\nLtac i_ctor := intros; constructor; simpl; eauto.\nLtac i_lem H := intros; eapply H; simpl; eauto.\n\nLemma run_cont_cases_arent_values : forall k v,\n    cases_arent_values_cont k ->\n    cases_arent_values_state (run_cont k v).\ninduction k; intros0 Hcavk; invc Hcavk; i_ctor.\nall: fold cases_arent_values_list.\nall: rewrite cases_arent_values_list_is_Forall.\n\n- i_lem Forall_app. i_ctor.\n- i_lem Forall_app. i_ctor.\n- eauto.\n- i_lem Forall_app. i_ctor.\nQed.\n\nLemma unroll_elim'_cases_arent_values : forall case ctor args mk_rec idx,\n    cases_arent_values case ->\n    (forall e, cases_arent_values e -> cases_arent_values (mk_rec e)) ->\n    cases_arent_values (unroll_elim' case ctor args mk_rec idx).\nfirst_induction args; intros0 Hcase Hmk_rec; simpl; eauto.\n- break_match.\n  + i_lem IHargs. split; eauto. eapply Hmk_rec. i_ctor.\n  + i_lem IHargs.\nQed.\n\nLemma unroll_elim_cases_arent_values : forall case ctor args mk_rec,\n    cases_arent_values case ->\n    (forall e, cases_arent_values e -> cases_arent_values (mk_rec e)) ->\n    cases_arent_values (unroll_elim case ctor args mk_rec).\nintros. i_lem unroll_elim'_cases_arent_values.\nQed.\n\nLemma step_cases_arent_values : forall E s s',\n    Forall cases_arent_values E ->\n    cases_arent_values_state s ->\n    sstep E s s' ->\n    cases_arent_values_state s'.\nintros0 Henv Hcases Hstep; invc Hstep; invc Hcases;\nsimpl in *; refold_cases_arent_values.\nall: repeat break_and; try solve [repeat i_ctor].\nall: try rewrite cases_arent_values_list_is_Forall in *.\n\n- i_lem run_cont_cases_arent_values.\n- i_ctor. i_lem Forall_nth_error.\n- on _, invc_using Forall_3part_inv. i_ctor. i_ctor.\n- on _, invc_using Forall_3part_inv. i_ctor. i_ctor.\n- on _, invc_using Forall_3part_inv. i_ctor. i_ctor.\n- i_ctor. i_ctor.\n- i_ctor. i_lem unroll_elim_cases_arent_values; refold_cases_arent_values.\n  + i_lem Forall_nth_error.\n  + intros; split; eauto. split; eauto.\n    rewrite cases_arent_values_list_is_Forall. auto.\nQed.\n\n\nLemma no_values_not_value : forall e,\n    no_values e ->\n    ~ is_value e.\nintros. inversion 1. subst. simpl in *. auto.\nQed.\n\nLemma no_values_not_value_list : forall es,\n    Forall no_values es ->\n    Forall (fun e => ~ is_value e) es.\ninduction es; intros; simpl in *; eauto.\non >Forall, invc. eauto using no_values_not_value.\nQed.\n\nLemma no_values_cases_arent_values : forall e,\n    no_values e ->\n    cases_arent_values e.\ninduction e using expr_rect_mut with\n    (Pl := fun e =>\n        Forall no_values e ->\n        Forall cases_arent_values e);\nsimpl; intros0 Hnv; refold_no_values; refold_cases_arent_values.\nall: repeat break_and.\nall: try rewrite no_values_list_is_Forall in *;\n     try rewrite cases_arent_values_list_is_Forall in *.\nall: eauto.\n\n- split; eauto. i_lem no_values_not_value_list.\n\n- on >Forall, invc. i_ctor.\nQed.\n\nLemma no_values_cases_arent_values_list : forall es,\n    Forall no_values es ->\n    Forall cases_arent_values es.\ninduction es; intros; simpl in *; eauto.\non >Forall, invc. eauto using no_values_cases_arent_values.\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/Untyped4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2783581616753235}}
{"text": "(* Sanity theorems for ett. *)\n\nRequire config.\nRequire Import config_tactics.\n\n\nRequire Import syntax.\nRequire Import tt.\n\nRequire ptt.\nRequire ptt_sanity.\nRequire Import ett.\nRequire Import ett2ptt ptt2ett.\nRequire Import inversion.\n\nSection EttSanity.\n\nContext `{configReflection : config.Reflection}.\nContext `{configBinaryProdType : config.BinaryProdType}.\nContext `{configProdEta : config.ProdEta}.\nContext `{configUniverses : config.Universes}.\nContext `{configPropType : config.PropType}.\nContext `{configIdType : config.IdType}.\nContext `{configIdEliminator : config.IdEliminator}.\nContext `{configEmptyType : config.EmptyType}.\nContext `{configUnitType : config.UnitType}.\nContext `{configBoolType : config.BoolType}.\nContext `{configProdType : config.ProdType}.\nContext `{configSyntax : syntax.Syntax}.\n\nExisting Instance ptt.havePrecondition.\nContext {haveCtxExtendInversion : HaveCtxExtendInversion}.\nContext {haveTyIdInversion : HaveTyIdInversion}.\nContext {haveTyProdInversion : HaveTyProdInversion}.\nContext {haveTyBinaryProdInversion : HaveTyBinaryProdInversion}.\n\nTheorem sane_issubst sbs G D :\n  issubst sbs G D -> isctx G * isctx D.\nProof.\n  intro h. split\n  ; now apply ptt2ett.sane_isctx,\n              (ptt_sanity.sane_issubst sbs G D),\n              ett2ptt.sane_issubst.\nDefined.\n\nTheorem sane_istype G A :\n  istype G A -> isctx G.\nProof.\n  intro h.\n  now apply ptt2ett.sane_isctx,\n            (ptt_sanity.sane_istype G A),\n            ett2ptt.sane_istype.\nDefined.\n\nTheorem sane_isterm G u A :\n  isterm G u A -> isctx G * istype G A.\nProof.\n  intro h. split.\n  - now apply ptt2ett.sane_isctx,\n              (ptt_sanity.sane_isterm G u A),\n              ett2ptt.sane_isterm.\n  - now apply ptt2ett.sane_istype,\n              (ptt_sanity.sane_isterm G u A),\n              ett2ptt.sane_isterm.\nDefined.\n\nTheorem sane_eqctx G D :\n  eqctx G D -> isctx G * isctx D.\nProof.\n  intro h. split\n  ; now apply ptt2ett.sane_isctx,\n              (ptt_sanity.sane_eqctx G D),\n              ett2ptt.sane_eqctx.\nDefined.\n\nTheorem sane_eqtype G A B :\n  eqtype G A B -> isctx G * istype G A * istype G B.\nProof.\n  intro h.\n  (repeat split)\n  ; [ apply ptt2ett.sane_isctx | apply ptt2ett.sane_istype .. ]\n  ; now apply (ptt_sanity.sane_eqtype G A B),\n              ett2ptt.sane_eqtype.\nDefined.\n\nTheorem sane_eqsubst sbs sbt G D :\n  eqsubst sbs sbt G D -> isctx G * isctx D * issubst sbs G D * issubst sbt G D.\nProof.\n  intro h.\n  (repeat split)\n  ; [ apply ptt2ett.sane_isctx\n    | apply ptt2ett.sane_isctx\n    | apply ptt2ett.sane_issubst\n    | apply ptt2ett.sane_issubst\n    ]\n  ; now apply (ptt_sanity.sane_eqsubst sbs sbt G D),\n              ett2ptt.sane_eqsubst.\nDefined.\n\nTheorem sane_eqterm G u v A :\n  eqterm G u v A -> isctx G * istype G A * isterm G u A * isterm G v A.\nProof.\n  intro h.\n  (repeat split)\n  ; [ apply ptt2ett.sane_isctx\n    | apply ptt2ett.sane_istype\n    | apply ptt2ett.sane_isterm ..\n    ]\n  ; now apply (ptt_sanity.sane_eqterm G u v A),\n              ett2ptt.sane_eqterm.\nDefined.\n\nEnd EttSanity.\n", "meta": {"author": "TheoWinterhalter", "repo": "formal-type-theory", "sha": "93ac197dfde912d77af9b0f4fd9f7d2422ba7dfc", "save_path": "github-repos/coq/TheoWinterhalter-formal-type-theory", "path": "github-repos/coq/TheoWinterhalter-formal-type-theory/formal-type-theory-93ac197dfde912d77af9b0f4fd9f7d2422ba7dfc/src/ett_sanity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376236, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.27835815485440246}}
{"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 O E Eprime Eprimeprime A B C Bprime : Universe, ((wd_ O E /\\ (wd_ O Eprime /\\ (wd_ E Eprime /\\ (wd_ B O /\\ (wd_ A O /\\ (wd_ C O /\\ (wd_ O Eprimeprime /\\ (wd_ E Eprimeprime /\\ (wd_ B E /\\ (wd_ A E /\\ (wd_ Bprime O /\\ (wd_ Eprime Eprimeprime /\\ (wd_ Eprimeprime A /\\ (wd_ Eprime A /\\ (wd_ Eprime Bprime /\\ (wd_ Eprime C /\\ (wd_ A Bprime /\\ (wd_ A C /\\ (wd_ Bprime C /\\ (wd_ E Bprime /\\ (wd_ Eprime B /\\ (wd_ B Bprime /\\ (wd_ B Eprimeprime /\\ (wd_ Bprime Eprimeprime /\\ (col_ O E A /\\ (col_ O E B /\\ (col_ O E C /\\ (col_ O Eprime Bprime /\\ (col_ O Eprimeprime Bprime /\\ col_ E Eprime Eprimeprime))))))))))))))))))))))))))))) -> col_ B Bprime Eprime)).\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_1213.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.27830718136871935}}
{"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\nRequire Import PArray List Bool.\n(* Add LoadPath \"..\" as SMTCoq. *)\nRequire Import Misc State SMT_terms.\n\nImport Form.\n\nLocal Open Scope array_scope.\nLocal Open Scope int31_scope.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nDefinition or_of_imp args :=\n  let last := PArray.length args - 1 in\n  PArray.mapi (fun i l => if i == last then l else Lit.neg l) args.\nRegister or_of_imp as PrimInline.\n\nLemma length_or_of_imp : forall args,\n  PArray.length (or_of_imp args) = PArray.length args.\nProof. intro; apply length_mapi. Qed.\n\nLemma get_or_of_imp : forall args i,\n  i < (PArray.length args) - 1 -> (or_of_imp args).[i] = Lit.neg (args.[i]).\nProof.\n  unfold or_of_imp; intros args i H; case_eq (0 < PArray.length args).\n  intro Heq; rewrite get_mapi.\n  replace (i == PArray.length args - 1) with false; auto; symmetry; rewrite eqb_false_spec; intro; subst i; unfold is_true in H; rewrite ltb_spec, (to_Z_sub_1 _ _ Heq) in H; omega.\n  rewrite ltb_spec; unfold is_true in H; rewrite ltb_spec, (to_Z_sub_1 _ _ Heq) in H; omega.\n  rewrite ltb_negb_geb; case_eq (PArray.length args <= 0); try discriminate; intros Heq _; assert (H1: PArray.length args = 0).\n  apply to_Z_inj; rewrite leb_spec in Heq; destruct (to_Z_bounded (PArray.length args)) as [H1 _]; change [|0|] with 0%Z in *; omega.\n  rewrite !get_outofbound.\n  rewrite default_mapi, H1; auto.\n  rewrite H1; case_eq (i < 0); auto; intro H2; eelim ltb_0; eassumption.\n  rewrite length_mapi, H1; case_eq (i < 0); auto; intro H2; eelim ltb_0; eassumption.\nQed.\n\nLemma get_or_of_imp2 : forall args i, 0 < PArray.length args ->\n  i = (PArray.length args) - 1 -> (or_of_imp args).[i] = args.[i].\nProof.\n  unfold or_of_imp; intros args i Heq Hi; rewrite get_mapi; subst i.\n  rewrite Int31Axioms.eqb_refl; auto.\n  rewrite ltb_spec, (to_Z_sub_1 _ _ Heq); omega.\nQed.\n\n\nSection CHECKER.\n\n  Variable t_form : PArray.array form.\n  Local Notation get_hash := (PArray.get t_form) (only parsing).\n  Variable s : S.t.\n\n\n  (*  * true             : {true}  *)\n\n  Definition check_True := C._true.\n\n\n  (* * false             : {(not false)} *)\n\n  Definition check_False  := Lit.neg (Lit._false)::nil.\n\n\n  (* * and_neg          : {(and a_1 ... a_n) (not a_1) ... (not a_n)}\n     * or_pos           : {(not (or a_1 ... a_n)) a_1 ... a_n} \n     * implies_pos      : {(not (implies a b)) (not a) b}\n     * xor_pos1         : {(not (xor a b)) a b}\n     * xor_neg1         : {(xor a b) a (not b)}\n     * equiv_pos1       : {(not (iff a b)) a (not b)}\n     * equiv_neg1       : {(iff a b) (not a) (not b)}\n     * ite_pos1         : {(not (if_then_else a b c)) a c}\n     * ite_neg1         : {(if_then_else a b c) a (not c)} *)\n\n  Definition check_BuildDef l :=\n    match get_hash (Lit.blit l) with\n    | Fand args => \n      if Lit.is_pos l then l :: List.map Lit.neg (PArray.to_list args) \n      else C._true\n    | For args =>\n      if Lit.is_pos l then C._true\n      else l :: PArray.to_list args\n    | Fimp args =>\n      if Lit.is_pos l then C._true\n      else\n        let args := or_of_imp args in\n        l :: PArray.to_list args\n    | Fxor a b =>\n      if Lit.is_pos l then l::a::Lit.neg b::nil \n      else l::a::b::nil\n    | Fiff a b =>\n      if Lit.is_pos l then l::Lit.neg a::Lit.neg b::nil\n      else l::a::Lit.neg b::nil\n    | Fite a b c =>\n      if Lit.is_pos l then l::a::Lit.neg c::nil\n      else l::a::c::nil\n    | _ => C._true\n    end.\n\n \n  (* * not_and           : {(not (and a_1 ... a_n))} --> {(not a_1) ... (not a_n)}\n     * or                : {(or a_1 ... a_n)} --> {a_1 ... a_n}\n     * implies           : {(implies a b)} --> {(not a) b}\n     * xor1              : {(xor a b)} --> {a b}\n     * not_xor1          : {(not (xor a b))} --> {a (not b)}\n     * equiv2            : {(iff a b)} --> {a (not b)}\n     * not_equiv2        : {(not (iff a b))} --> {(not a) (not b)}\n     * ite1              : {(if_then_else a b c)} --> {a c}\n     * not_ite1          : {(not (if_then_else a b c))} --> {a (not c)} *)\n\n  Definition check_ImmBuildDef pos :=\n    match S.get s pos with\n    | l::nil =>\n      match get_hash (Lit.blit l) with\n      | Fand args => \n        if Lit.is_pos l then C._true\n        else List.map Lit.neg (PArray.to_list args) \n      | For args =>\n        if Lit.is_pos l then PArray.to_list args\n        else C._true\n      | Fimp args =>\n        if Lit.is_pos l then \n          let args := or_of_imp args in\n          PArray.to_list args\n        else C._true\n      | Fxor a b =>\n        if Lit.is_pos l then a::b::nil\n        else a::Lit.neg b::nil \n      | Fiff a b =>\n        if Lit.is_pos l then a::Lit.neg b::nil\n        else Lit.neg a::Lit.neg b::nil\n      | Fite a b c =>\n        if Lit.is_pos l then a::c::nil\n        else a::Lit.neg c::nil\n      | _ => C._true\n      end\n    | _ => C._true\n    end.\n\n\n  (* * xor_pos2          : {(not (xor a b)) (not a) (not b)}\n     * xor_neg2          : {(xor a b) (not a) b}\n     * equiv_pos2        : {(not (iff a b)) (not a) b}\n     * equiv_neg2        : {(iff a b) a b}\n     * ite_pos2          : {(not (if_then_else a b c)) (not a) b}\n     * ite_neg2          : {(if_then_else a b c) (not a) (not b)} *)\n\n  Definition check_BuildDef2 l :=\n    match get_hash (Lit.blit l) with\n    | Fxor a b =>\n      if Lit.is_pos l then l::Lit.neg a::b::nil\n      else l::Lit.neg a::Lit.neg b::nil\n    | Fiff a b =>\n      if Lit.is_pos l then l::a::b::nil\n      else l::Lit.neg a::b::nil\n    | Fite a b c =>\n      if Lit.is_pos l then l::Lit.neg a::Lit.neg b::nil\n      else l::Lit.neg a::b::nil\n    | _ => C._true\n    end.\n\n\n  (* * xor2              : {(xor a b)} --> {(not a) (not b)}\n     * not_xor2          : {(not (xor a b))} --> {(not a) b}\n     * equiv1            : {(iff a b)} --> {(not a) b}\n     * not_equiv1        : {(not (iff a b))} --> {a b}\n     * ite2              : {(if_then_else a b c)} --> {(not a) b}\n     * not_ite2          : {(not (if_then_else a b c))} --> {(not a) (not b)}\n     *)\n\n  Definition check_ImmBuildDef2 pos :=\n    match S.get s pos with\n    | l::nil =>\n      match get_hash (Lit.blit l) with\n      | Fxor a b =>\n        if Lit.is_pos l then Lit.neg a::Lit.neg b::nil\n        else Lit.neg a::b::nil\n      | Fiff a b =>\n        if Lit.is_pos l then Lit.neg a::b::nil\n        else a::b::nil\n      | Fite a b c =>\n        if Lit.is_pos l then Lit.neg a::b::nil\n        else Lit.neg a::Lit.neg b::nil\n      | _ => C._true\n      end\n    | _ => C._true\n    end.\n\n \n  (* * or_neg           : {(or a_1 ... a_n) (not a_i)}\n     * and_pos          : {(not (and a_1 ... a_n)) a_i} \n     * implies_neg1     : {(implies a b) a}\n     * implies_neg2     : {(implies a b) (not b)} *)\n\n  Definition check_BuildProj l i :=\n    let x := Lit.blit l in\n    match get_hash x with\n    | For args =>\n      if i < PArray.length args then Lit.lit x::Lit.neg (args.[i])::nil\n      else C._true\n    | Fand args =>\n      if i < PArray.length args then Lit.nlit x::(args.[i])::nil\n      else C._true\n    | Fimp args =>\n      let len := PArray.length args in\n      if i < len then\n        if i == len - 1 then Lit.lit x::Lit.neg (args.[i])::nil\n        else Lit.lit x::(args.[i])::nil\n      else C._true\n    | _ => C._true\n    end.\n\n\n  (* * and               : {(and a_1 ... a_n)} --> {a_i} \n     * not_or            : {(not (or a_1 ... a_n))} --> {(not a_i)}\n     * not_implies1      : {(not (implies a b))} --> {a}\n     * not_implies2      : {(not (implies a b))} --> {(not b)} *)\n\n  Definition check_ImmBuildProj pos i := \n    match S.get s pos with\n    | l::nil =>\n      let x := Lit.blit l in\n      match get_hash x with\n      | For args =>\n        if (i < PArray.length args) && negb (Lit.is_pos l) then Lit.neg (args.[i])::nil\n        else C._true\n      | Fand args =>\n        if (i < PArray.length args) && (Lit.is_pos l) then (args.[i])::nil\n        else C._true\n      | Fimp args =>\n        let len := PArray.length args in\n        if (i < len) && negb (Lit.is_pos l) then\n          if i == len - 1 then Lit.neg (args.[i])::nil\n          else (args.[i])::nil\n        else C._true\n      | _ => C._true\n      end\n    | _ => C._true\n    end.\n\n  (** The correctness proofs *)\n\n  Variable interp_atom : atom -> bool.\n\n  Hypothesis Hch_f : check_form t_form.\n\n  Local Notation rho := (Form.interp_state_var interp_atom t_form).\n\n  Let Hwfrho : Valuation.wf rho.\n  Proof.\n    destruct (check_form_correct interp_atom _ Hch_f) as (_, H);exact H. \n  Qed.\n\n  Lemma valid_check_True : C.valid rho check_True.\n  Proof. \n    apply C.interp_true;trivial.\n  Qed.\n\n  Lemma valid_check_False : C.valid rho check_False.\n  Proof.\n    unfold check_False, C.valid;simpl.\n    rewrite Lit.interp_neg.\n    assert (W:= Lit.interp_false _ Hwfrho).\n    destruct (Lit.interp rho Lit._false);trivial;elim W;red;trivial.\n  Qed.\n\n  Let rho_interp : forall x : int,\n    rho x = interp interp_atom t_form (t_form.[ x]).\n  Proof.\n    destruct (check_form_correct interp_atom _ Hch_f) as ((H,H0), _).\n    intros x;apply wf_interp_form;trivial.\n  Qed.\n\n  Ltac tauto_check :=\n   try (rewrite !Lit.interp_neg);\n   repeat \n     match goal with |- context [Lit.interp rho ?x] => \n     destruct (Lit.interp rho x);trivial end.\n\n\n  Lemma afold_left_and a :\n    afold_left bool int true andb (Lit.interp rho) a =\n    List.forallb (Lit.interp rho) (to_list a).\n  Proof.\n    case_eq (afold_left bool int true andb (Lit.interp rho) a); intro H; symmetry.\n      assert (H1:=afold_left_andb_true_inv _ _ _ H); clear H. rewrite forallb_forall. intros i H. apply In_to_list in H. destruct H as [j [H2 H3]]. subst. apply H1. auto.\n      apply afold_left_andb_false_inv in H. destruct H as [i [H H1]]. case_eq (forallb (Lit.interp rho) (to_list a)); auto. rewrite forallb_forall. intro H2. rewrite <- H1. symmetry. auto using to_list_In.\n  Qed.\n\n\n  Lemma afold_left_or a :\n    afold_left bool int false orb (Lit.interp rho) a =\n    C.interp rho (to_list a).\n  Proof.\n    case_eq (afold_left bool int false orb (Lit.interp rho) a); intro H; symmetry.\n      apply afold_left_orb_true_inv in H. destruct H as [i [H H1]]. unfold C.interp. rewrite existsb_exists. exists (a.[i]); split; auto using to_list_In.\n      assert (H1:=afold_left_orb_false_inv _ _ _ H); clear H. unfold C.interp. case_eq (existsb (Lit.interp rho) (to_list a)); auto. rewrite existsb_exists. intros [x [H H2]]. apply In_to_list in H. destruct H as [i [H H3]]. subst. rewrite <- H2. auto.\n  Qed.\n\n\n  Lemma afold_right_impb a :\n    (afold_right bool int false implb (Lit.interp rho) a) =\n    C.interp rho (to_list (or_of_imp a)).\n  Proof.\n    case_eq (afold_right bool int false implb (Lit.interp rho) a); intro H; symmetry.\n      apply afold_right_implb_true_inv in H. destruct H as [H [[i [H1 H2]]|H1]].\n        unfold C.interp. rewrite existsb_exists. exists (Lit.neg (a.[i])). split.\n          apply (to_list_In2 i).\n            rewrite length_or_of_imp, ltb_spec. rewrite ltb_spec, (to_Z_sub_1 _ 0) in H1; auto. omega.\n            unfold or_of_imp. rewrite get_mapi.\n              replace (i == PArray.length a - 1) with false; auto. symmetry. rewrite eqb_false_spec. intro H3. rewrite <- H3 in H1. apply (not_ltb_refl i). auto.\n              rewrite ltb_spec. rewrite ltb_spec, (to_Z_sub_1 _ 0) in H1; auto. omega.\n          rewrite Lit.interp_neg, H2; auto.\n        unfold C.interp. rewrite existsb_exists. exists (a.[PArray.length a - 1]). split.\n          apply (to_list_In2 (PArray.length a - 1)).\n            rewrite length_or_of_imp, ltb_spec, (to_Z_sub_1 _ 0); auto. omega.\n            unfold or_of_imp. rewrite get_mapi.\n              rewrite Int31Axioms.eqb_refl. auto.\n              rewrite ltb_spec, (to_Z_sub_1 _ 0); auto. omega.\n          apply H1. rewrite ltb_spec, (to_Z_sub_1 _ 0); auto. omega.\n      apply afold_right_implb_false_inv in H. destruct H as [H|[H H1]].\n        unfold C.interp. case_eq (existsb (Lit.interp rho) (to_list (or_of_imp a))); auto. rewrite existsb_exists. intros [x [H1 H2]]. apply In_to_list in H1. destruct H1 as [i [H1 _]]. rewrite length_or_of_imp, <- H in H1. eelim ltb_0; eauto.\n        unfold C.interp. case_eq (existsb (Lit.interp rho) (to_list (or_of_imp a))); auto. rewrite existsb_exists. intros [x [H2 H3]]. apply In_to_list in H2. destruct H2 as [i [H2 H4]]. subst. unfold or_of_imp in H3. rewrite get_mapi in H3.\n          case_eq (i == PArray.length a - 1); intro H4; rewrite H4 in H3.\n            rewrite eqb_spec in H4. subst. rewrite <- H3. auto.\n            rewrite Lit.interp_neg in H3. rewrite eqb_false_spec in H4. rewrite H in H3; try discriminate. case_eq (PArray.length a == 0).\n              rewrite eqb_spec. intro H5. rewrite length_or_of_imp, H5 in H2. eelim ltb_0; eauto.\n              rewrite eqb_false_spec. intro H5. rewrite ltb_spec, to_Z_sub_1_diff; auto. assert (H6:[|i|] <> ([|PArray.length a|] - 1)%Z).\n                intro H6. apply H4, to_Z_inj. rewrite to_Z_sub_1_diff; auto.\n                rewrite length_or_of_imp, ltb_spec in H2. omega.\n          rewrite length_or_of_imp in H2; auto.\n  Qed.\n\n\n  Lemma Cinterp_neg cl :\n     C.interp rho (map Lit.neg cl) = negb (forallb (Lit.interp rho) cl).\n  Proof.\n    unfold C.interp. case_eq (forallb (Lit.interp rho) cl); simpl.\n      rewrite forallb_forall. intro H. case_eq (existsb (Lit.interp rho) (map Lit.neg cl)); auto. rewrite existsb_exists. intros [l [H1 H2]]. rewrite in_map_iff in H1. destruct H1 as [x [H1 H3]]. subst l. rewrite <- H2, Lit.interp_neg, H; auto.\n      rewrite existsb_exists. induction cl as [ |l cl IHcl]; simpl; try discriminate.\n      rewrite andb_false_iff. intros [H|H].\n        exists (Lit.neg l). intuition. rewrite Lit.interp_neg, H. auto.\n        destruct (IHcl H) as [x [H1 H2]]. exists x; auto.\n  Qed.\n\n\n  Lemma valid_check_BuildDef : forall l, C.valid rho (check_BuildDef l).\n  Proof.\n   unfold check_BuildDef,C.valid;intros l.\n   case_eq (t_form.[Lit.blit l]);intros;auto using C.interp_true;\n   case_eq (Lit.is_pos l);intros Heq;auto using C.interp_true;simpl;\n   unfold Lit.interp at 1;rewrite Heq;unfold Var.interp; rewrite rho_interp, H;simpl;\n   tauto_check.\n   rewrite afold_left_and, Cinterp_neg;apply orb_negb_r.\n   rewrite afold_left_or, orb_comm;apply orb_negb_r.\n   rewrite afold_right_impb, orb_comm;apply orb_negb_r.\n  Qed.\n\n  Lemma valid_check_BuildDef2 : forall l, C.valid rho (check_BuildDef2 l).\n  Proof.\n   unfold check_BuildDef2,C.valid;intros l.\n   case_eq (t_form.[Lit.blit l]);intros;auto using C.interp_true;\n   case_eq (Lit.is_pos l);intros Heq;auto using C.interp_true;simpl;\n   unfold Lit.interp at 1;rewrite Heq;unfold Var.interp; rewrite rho_interp, H;simpl;\n   tauto_check.\n  Qed.\n\n  Lemma valid_check_BuildProj : forall l i, C.valid rho (check_BuildProj l i).\n  Proof.\n   unfold check_BuildProj,C.valid;intros l i.\n   case_eq (t_form.[Lit.blit l]);intros;auto using C.interp_true;\n   case_eq (i < PArray.length a);intros Hlt;auto using C.interp_true;simpl.\n\n   rewrite Lit.interp_nlit;unfold Var.interp;rewrite rho_interp, orb_false_r, H.\n   simpl;rewrite afold_left_and.\n   case_eq (forallb (Lit.interp rho) (to_list a));trivial.\n   rewrite forallb_forall;intros Heq;rewrite Heq;trivial.\n   apply to_list_In; auto.\n   rewrite Lit.interp_lit;unfold Var.interp;rewrite rho_interp, orb_false_r, H.\n   simpl;rewrite afold_left_or.\n      \n   unfold C.interp;case_eq (existsb (Lit.interp rho) (to_list a));trivial.\n   rewrite <-not_true_iff_false, existsb_exists, Lit.interp_neg.\n   case_eq (Lit.interp rho (a .[ i]));trivial.\n   intros Heq Hex;elim Hex;exists (a.[i]);split;trivial.\n   apply to_list_In; auto.\n   case_eq (i == PArray.length a - 1);intros Heq;simpl;\n   rewrite Lit.interp_lit;unfold Var.interp;rewrite rho_interp, H;simpl;\n   rewrite afold_right_impb; case_eq (C.interp rho (to_list (or_of_imp a)));trivial;\n   unfold C.interp;rewrite <-not_true_iff_false, existsb_exists;\n   try rewrite Lit.interp_neg; case_eq (Lit.interp rho (a .[ i]));trivial;\n   intros Heq' Hex;elim Hex.\n   exists (a.[i]);split;trivial.\n   assert (H1: 0 < PArray.length a) by (apply (leb_ltb_trans _ i _); auto; apply leb_0); rewrite Int31Properties.eqb_spec in Heq; rewrite <- (get_or_of_imp2 H1 Heq); apply to_list_In; rewrite length_or_of_imp; auto.\n   exists (Lit.neg (a.[i]));rewrite Lit.interp_neg, Heq';split;trivial.\n   assert (H1: i < PArray.length a - 1 = true) by (rewrite ltb_spec, (to_Z_sub_1 _ _ Hlt); rewrite eqb_false_spec in Heq; assert (H1: [|i|] <> ([|PArray.length a|] - 1)%Z) by (intro H1; apply Heq, to_Z_inj; rewrite (to_Z_sub_1 _ _ Hlt); auto); rewrite ltb_spec in Hlt; omega); rewrite <- (get_or_of_imp H1); apply to_list_In; rewrite length_or_of_imp; auto.\n  Qed.\n\n  Hypothesis Hs : S.valid rho s.\n\n  Lemma valid_check_ImmBuildDef : forall cid,\n     C.valid rho (check_ImmBuildDef cid).\n  Proof.\n   unfold check_ImmBuildDef,C.valid;intros cid.\n   generalize (Hs cid);unfold C.valid.\n   destruct (S.get s cid) as [ | l [ | _l _c]];auto using C.interp_true.\n   simpl;unfold Lit.interp, Var.interp; rewrite !rho_interp;\n   destruct (t_form.[Lit.blit l]);auto using C.interp_true;\n   case_eq (Lit.is_pos l);intros Heq;auto using C.interp_true;simpl;\n   tauto_check.\n   rewrite afold_left_and, Cinterp_neg, orb_false_r;trivial.\n   rewrite afold_left_or, orb_false_r;trivial.\n   rewrite afold_right_impb, orb_false_r;trivial.\n  Qed.\n\n  Lemma valid_check_ImmBuildDef2 : forall cid, C.valid rho (check_ImmBuildDef2 cid).\n  Proof.\n    unfold check_ImmBuildDef2,C.valid;intros cid.\n    generalize (Hs cid);unfold C.valid.\n    destruct (S.get s cid) as [ | l [ | _l _c]];auto using C.interp_true.\n    simpl;unfold Lit.interp, Var.interp; rewrite !rho_interp;\n    destruct (t_form.[Lit.blit l]);auto using C.interp_true;\n    case_eq (Lit.is_pos l);intros Heq;auto using C.interp_true;simpl;\n    tauto_check.\n  Qed.\n\n  Lemma valid_check_ImmBuildProj : forall cid i, C.valid rho (check_ImmBuildProj cid i).\n  Proof.\n   unfold check_ImmBuildProj,C.valid;intros cid i.\n   generalize (Hs cid);unfold C.valid.\n   destruct (S.get s cid) as [ | l [ | _l _c]];auto using C.interp_true.\n   simpl;unfold Lit.interp, Var.interp; rewrite !rho_interp;\n     destruct (t_form.[Lit.blit l]);auto using C.interp_true;\n       case_eq (i < PArray.length a); intros Hlt;auto using C.interp_true;\n       case_eq (Lit.is_pos l);intros Heq;auto using C.interp_true;simpl;\n       rewrite !orb_false_r.  \n   rewrite afold_left_and.\n   rewrite forallb_forall;intros H;apply H;auto.\n   apply to_list_In; auto.\n   rewrite negb_true_iff, <-not_true_iff_false, afold_left_or.\n   unfold C.interp;rewrite existsb_exists, Lit.interp_neg.\n   case_eq (Lit.interp rho (a .[ i]));trivial.\n   intros Heq' Hex;elim Hex;exists (a.[i]);split;trivial.\n   apply to_list_In; auto.\n   rewrite negb_true_iff, <-not_true_iff_false, afold_right_impb.\n   case_eq (i == PArray.length a - 1);intros Heq';simpl;\n     unfold C.interp;simpl;try rewrite Lit.interp_neg;rewrite orb_false_r,\n   existsb_exists;case_eq (Lit.interp rho (a .[ i]));trivial;\n   intros Heq2 Hex;elim Hex.\n   exists (a.[i]);split;trivial.\n   assert (H1: 0 < PArray.length a) by (apply (leb_ltb_trans _ i _); auto; apply leb_0); rewrite Int31Properties.eqb_spec in Heq'; rewrite <- (get_or_of_imp2 H1 Heq'); apply to_list_In; rewrite length_or_of_imp; auto.\n   exists (Lit.neg (a.[i]));rewrite Lit.interp_neg, Heq2;split;trivial.\n   assert (H1: i < PArray.length a - 1 = true) by (rewrite ltb_spec, (to_Z_sub_1 _ _ Hlt); rewrite eqb_false_spec in Heq'; assert (H1: [|i|] <> ([|PArray.length a|] - 1)%Z) by (intro H1; apply Heq', to_Z_inj; rewrite (to_Z_sub_1 _ _ Hlt); auto); rewrite ltb_spec in Hlt; omega); rewrite <- (get_or_of_imp H1); apply to_list_In; rewrite length_or_of_imp; auto.\n  Qed.\n\nEnd CHECKER.\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/cnf/Cnf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.2782495874508384}}
{"text": "(** * Autosubst wrapper for ssreflect *)\nRequire Export Autosubst.Autosubst_Basics.\nRequire Export Autosubst.Autosubst_MMap.\nRequire Export Autosubst.Autosubst_Classes.\nRequire Export Autosubst.Autosubst_Tactics.\nRequire Export Autosubst.Autosubst_Lemmas.\nRequire Export Autosubst.Autosubst_Derive.\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq.\nFrom Coq Require Import ssrfun.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection MMapInstances.\n\nVariable (A B C : Type).\nVariable (MMap_A_B : MMap A B).\nVariable (MMap_A_C : MMap A C).\nVariable (MMapLemmas_A_B : MMapLemmas A B).\nVariable (MMapLemmas_A_C : MMapLemmas A C).\nVariable (MMapExt_A_B : MMapExt A B).\nVariable (MMapExt_A_C : MMapExt A C).\n\n\nGlobal Instance MMap_option : MMap A (option B) := fun f => omap (mmap f).\nGlobal Instance MMapLemmas_option : MMapLemmas A (option B). derive. Qed.\nGlobal Instance MMapExt_option : MMapExt A (option B). derive. Defined.\n\n\nGlobal Instance MMap_pair : MMap A (B * C). derive. Defined.\nGlobal Instance MMapLemmas_pair : MMapLemmas A (B * C). derive. Qed.\nGlobal Instance MMapExt_pair : MMapExt A (B * C). derive. Defined.\n\n\nGlobal Instance mmap_seq : MMap A (seq B) := fun f => map (mmap f).\nGlobal Instance mmapLemmas_seq : MMapLemmas A (seq B). derive. Qed.\nGlobal Instance mmapExt_seq : MMapExt A (seq B). derive. Defined.\n\n\nGlobal Instance MMap_fun : MMap A (B -> C) := fun f g x => mmap f (g x).\n\nGlobal Instance MMapLemmas_fun : MMapLemmas A (B -> C).\nProof.\n  constructor; intros; f_ext; intros; [apply mmap_id|apply mmap_comp].\nQed.\n\nGlobal Instance MMapExt_fun : MMapExt A (B -> C).\nProof.\n  hnf. intros f g H h. f_ext. intro x. apply mmap_ext. exact H.\nDefined.\n\nEnd MMapInstances.\n", "meta": {"author": "qcfu-bu", "repo": "dtest-coq", "sha": "213952f2185d95c7b4ad1e9793ee471b9d384550", "save_path": "github-repos/coq/qcfu-bu-dtest-coq", "path": "github-repos/coq/qcfu-bu-dtest-coq/dtest-coq-213952f2185d95c7b4ad1e9793ee471b9d384550/theories/AutosubstSsr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.27824958745083833}}
{"text": "(* Author: Masaki Hara, 2014 *)\n(* Linear Logic Toy for Coq *)\nRequire Import LWeight LType_base LGoal.\n\n(*************************************************)\n(*       Conjunctive Exponential Modality        *)\n(*************************************************)\n\nRecord LOfcourseVal{E:LEnv} (A:LType) := {\n  lofcourseval : ltype A;\n  lofcourseval_nil : lweight lofcourseval = 0%LWeight\n}.\nArguments LOfcourseVal [E] A%LL.\nArguments Build_LOfcourseVal [E] [A] _ _.\nArguments lofcourseval [E] [A] _.\nArguments lofcourseval_nil [E] [A] _.\n\nDefinition LOfcourse{E:LEnv} (A:LType) : LType := {|\n  ltype := LOfcourseVal A;\n  lweight x := lweight (lofcourseval x)\n|}.\nNotation \"! A\" := (LOfcourse A%LL) : LL_scope.\n\nClass LOfcAutoPromotion{E:LEnv} (W:LWeight) := {\n  lofc_autopromotion_eqn : W = 0%LWeight\n}.\nInstance LOfcAutoPromotionZero{E:LEnv} : LOfcAutoPromotion 0%LWeight.\nProof.\n  exists; reflexivity.\nDefined.\nInstance LOfcAutoPromotionPlus{E:LEnv} {W0 W1:LWeight}\n    {H0:LOfcAutoPromotion W0} {H1:LOfcAutoPromotion W1}\n    : LOfcAutoPromotion (W0 + W1)%LWeight.\nProof.\n  exists.\n  rewrite (@lofc_autopromotion_eqn _ _ H0).\n  rewrite (@lofc_autopromotion_eqn _ _ H1).\n  apply LWeightZeroL.\nDefined.\nInstance LOfcAutoPromotionOfc{E:LEnv} (A:LType)\n  (v:ltype (!A)) : LOfcAutoPromotion v.\nProof.\n  exists; apply lofcourseval_nil.\nDefined.\n\n(* Promotion *)\nDefinition LOfcConstructor{E:LEnv} {A:LType} {W:LWeight}\n    {H:LOfcAutoPromotion W} : LGoal A W -> LGoal (!A) W.\nProof.\n  intros H0.\n  refine {|\n    lgoal_proof := {|\n      lofcourseval := H0\n    |} : ltype (!A);\n    lgoal_weight_eqn := {| lweight_eqn := _ |}\n  |}.\n  simpl.\n  apply lgoal_weight_eqn.\nGrab Existential Variables.\n  rewrite <-(lweight_eqn (lgoal_weight_eqn H0)).\n  apply (@lofc_autopromotion_eqn _ _ H).\nDefined.\n\n(* Dereliction *)\nDefinition LOfcDestructor{E:LEnv} {A B:LType} {W:LWeight}\n    : LGoal (A -o B) W -> LGoal (!A -o B) W.\nProof.\n  intros H0.\n  refine {|\n    lgoal_proof := {|\n      lfun_val := fun(oa:ltype (!A)) => (lgoal_proof H0) (lofcourseval oa);\n      lfun_weight := W\n    |} : ltype (!A -o B)\n  |}.\nGrab Existential Variables.\n  intros x; simpl; refine (lweight_eqn _).\nDefined.\n\n(* Contraction *)\nDefinition LOfcClone{E:LEnv} {A B:LType} {W:LWeight}\n    : LGoal (!A -o !A -o B) W -> LGoal (!A -o B) W.\nProof.\n  intros H0.\n  refine {|\n    lgoal_proof := {|\n      lfun_val := fun(oa:ltype (!A)) => (lgoal_proof H0) oa oa;\n      lfun_weight := W\n    |} : ltype (!A -o B)\n  |}.\nGrab Existential Variables.\n  intros x; simpl.\n  rewrite <-lfun_weight_eqn.\n  change (W + x = (lgoal_proof H0 x) + lofcourseval x)%LWeight.\n  rewrite lofcourseval_nil.\n  refine (lweight_eqn _).\nDefined.\n\n(* Weakening *)\nDefinition LOfcClear{E:LEnv} {A B:LType} {W:LWeight}\n    : LGoal B W -> LGoal (!A -o B) W.\nProof.\n  intros H0.\n  refine {|\n    lgoal_proof := {|\n      lfun_val := fun(oa:ltype (!A)) => lgoal_proof H0;\n      lfun_weight := W\n    |} : ltype (!A -o B)\n  |}.\nGrab Existential Variables.\n  intros x; simpl.\n  rewrite lofcourseval_nil.\n  refine (lweight_eqn _).\nDefined.\n\n\n\nLocal Ltac splitll_base ::=\n  apply LOfcConstructor ||\n  fail \"Constructor not found\".\nLocal Ltac destructll_base ::=\n  apply LOfcDestructor ||\n  fail \"Destructor not found\".\nLocal Ltac clonell_base ::=\n  apply LOfcClone ||\n  fail \"Destructor not found\".\nLocal Ltac clearll_base ::=\n  apply LOfcClear ||\n  fail \"Destructor not found\".\n\nLocal Open Scope LL_goal_scope.\n\nExample LOfcDig1{E:LEnv} (A:LType) :\n  (ILL |- (!!A) -o !A).\nProof.\n  introsll x.\n  destructll x as [x].\n  applyll x.\nDefined.\nExample LOfcDig2{E:LEnv} (A:LType) :\n  (ILL |- !A -o !!A).\nProof.\n  introsll x.\n  splitll.\n  applyll x.\nDefined.\nLocal Close Scope LL_goal_scope.\n", "meta": {"author": "qnighy", "repo": "LType-Coq", "sha": "dec99f40020271aab5d95daf56acae8ff231aa58", "save_path": "github-repos/coq/qnighy-LType-Coq", "path": "github-repos/coq/qnighy-LType-Coq/LType-Coq-dec99f40020271aab5d95daf56acae8ff231aa58/LOfcourse.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.27824958745083833}}
{"text": "(** printing ⊢k #&vdash;<sub>k</sub># *)\n(** printing ⊢s #&vdash;<sub>s</sub># *)\n(** printing ⊢! #&vdash;# *)\n(** printing k⊣ #&dashv;# *)\n(** printing |- #&vdash;# *)\n(** printing ↗! #&nearrow;# *)\n(** printing ↘! #&searrow;# *)\n(** printing ⦂ #:# *)\n(** printing <⦂ #<:# *)\n(** printing [<=] #&subseteq;# *)\n(** printing `union` #&cup;# *)\n(** printing \\u #&cup;# *)\n(** printing `notin` #&notin;# *)\n(** printing `in` #&in;# *)\n(** printing ⊆<⦂ #&subseteq;<sub>&lt;:</sub># *)\n\nSet Implicit Arguments.\nRequire Import Definitions.\n\n(** * Miscellaneous Definitions\n\n    This file defines well-formedness of contexts, and some structural measures. The\n definitions resembles those in D<:, so we do not repeat here.\n  *)\n\nInductive wf_env : env -> Prop :=\n| wf_nil : wf_env nil\n| wf_cons : forall {x T G}, x \\notin fv T \\u fv G ->\n                       fv T [<=] dom G ->\n                       wf_env G ->\n                       lc T ->\n                       wf_env (x ~ T ++ G).\nHint Constructors wf_env.\n\nLemma wf_decons : forall x T G, wf_env (x ~ T ++ G) -> x \\notin fv T.\nProof. routine. Qed.\n\nLemma wf_deapp : forall G1 G2, wf_env (G1 ++ G2) -> wf_env G2.\nProof. induction on env; routine. Qed.\n\nLemma wf_uniq : forall G, wf_env G -> uniq G.\nProof. induction on env; routine. Qed.\n\nLemma wf_var_in : forall G1 G2 v,\n    wf_env (G1 ++ G2) ->\n    v `in` dom G2 ->\n         v `notin` dom G1.\nProof.\n  induction G1; intros.\n  - routine.\n  - tidy_up. repeat rewrite dom_app in *.\n    destruct_notin.\n    rewrite AtomSetProperties.add_union_singleton.\n    intro Contra.\n    apply AtomSetImpl.union_1 in Contra.\n    destruct Contra.\n    + apply AtomSetImpl.singleton_1 in H1. subst.\n      intuition.\n    + eapply IHG1; eassumption.\nQed.        \n\nLemma wf_fv_is_dom : forall G,\n    wf_env G ->\n    fv G [=] dom G.\nProof.\n  induction on wf_env; set solve.\n  autorewrite with meta_ext.\n  rewrite IHwf_env.\n  simpl. fsetdec.\nQed.\n\nFixpoint typ_struct_measure (T : typ) :=\n  match T with\n  | typ_top => 1\n  | typ_var x => 2\n  | typ_fun T U => S $ typ_struct_measure T + typ_struct_measure U\n  | typ_all T U => S $ typ_struct_measure T + typ_struct_measure U\n  end.\n\nLocal Ltac simplify :=\n  intros; cbn in *; try lia.\n\nLocal Ltac finish :=\n  repeat match goal with\n         | H : context[forall _, _ = _] |- _ =>\n           rewrite H; clear H\n         end;\n  reflexivity.\n\nLemma open_typ_same_measure : forall T k u,\n    typ_struct_measure $ open_rec_typ k u T = typ_struct_measure T.\nProof.\n  induction T; simplify; finish.\nQed.\n\nLemma typ_struct_measure_ge_1 : forall T,\n    typ_struct_measure T >= 1.\nProof. destruct T; routine. Qed.\n\nDefinition total (ns : list nat) : nat :=\n  fold_right plus 0 ns.\n\nLemma total_app : forall ns1 ns2,\n    total (ns1 ++ ns2) = total ns1 + total ns2.\nProof.\n  unfold total.\n  induction on list; simpl in *; intros; trivial.\n  rewrite IHlist. lia.\nQed.\n\nDefinition env_measure (G : env) : nat :=\n  total (List.map (fun (tup : var * typ) =>\n        let (x, T) := tup in typ_struct_measure T) G).\n\nLemma env_measure_cons : forall x T G,\n    env_measure ((x, T) :: G) = typ_struct_measure T + env_measure G.\nProof. routine. Qed.\n\nLemma env_measure_app : forall G1 G2,\n    env_measure (G2 ++ G1) = env_measure G2 + env_measure G1.\nProof.\n  induction G2; simpl; trivial.\n  destruct a. rewrite! env_measure_cons.\n  rewrite IHG2. lia.\nQed.\n  \nArguments env_measure G : simpl never.\nCreate HintDb measures discriminated.\nHint Rewrite -> env_measure_cons env_measure_app total_app : measures.\nHint Rewrite -> open_typ_same_measure : measures.\n\nSection Predicates.\n\n  Definition is_top (T : typ) :=\n    match T with\n    | typ_top => True\n    | _ => False\n    end.\n\n  Definition is_top_dec (T : typ) : {is_top T} + {~is_top T}.\n  Proof. destruct T; simpl; auto. Defined.\n\n  Definition is_var (T : typ) :=\n    match T with\n    | typ_var _ => True\n    | _ => False\n    end.\n\n  Definition is_var_dec (T : typ) : {A | T = typ_var A } + {~is_var T}.\n  Proof. destruct T; simpl; eauto. Defined.\n  \n  Definition is_fun (T : typ) :=\n    match T with\n    | typ_fun _ _ => True\n    | _ => False\n    end.\n\n  Definition is_fun_dec (T : typ) : {S & { U | T = typ_fun S U } } + {~is_fun T}.\n  Proof. destruct T; simpl; eauto. Defined.\n\n  Definition is_all (T : typ) :=\n    match T with\n    | typ_all _ _ => True\n    | _ => False\n    end.\n\n  Definition is_all_dec (T : typ) : {S & { U | T = typ_all S U } } + {~is_all T}.\n  Proof. destruct T; simpl; eauto. Defined.\n\nEnd Predicates.\n", "meta": {"author": "HuStmpHrrr", "repo": "popl20-artifact", "sha": "48214a55ebb484fd06307df4320813d4a002535b", "save_path": "github-repos/coq/HuStmpHrrr-popl20-artifact", "path": "github-repos/coq/HuStmpHrrr-popl20-artifact/popl20-artifact-48214a55ebb484fd06307df4320813d4a002535b/fsub/Misc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.27824958031685837}}
{"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 [RRE] pass. *)\n\nRequire Import Axioms.\nRequire Import Coqlib.\nRequire Import AST.\nRequire Import Values.\nRequire Import Globalenvs.\nRequire Import Events.\nRequire Import Smallstep.\nRequire Import Op.\nRequire Import Locations.\nRequire Import Conventions.\nRequire Import Linear.\nRequire Import RRE.\n\n(** * Operations over equations *)\n\nLemma find_reg_containing_sound:\n  forall s r eqs, find_reg_containing s eqs = Some r -> In (mkeq r s) eqs.\nProof.\n  induction eqs; simpl; intros.\n  congruence.\n  destruct (slot_eq (e_slot a) s). inv H. left; destruct a; auto. right; eauto.\nQed.\n\nDefinition equations_hold (ls: locset) (eqs: equations) : Prop :=\n  forall e, In e eqs -> ls (S (e_slot e)) = ls (R (e_reg e)).\n\nLemma nil_hold:\n  forall ls, equations_hold ls nil.\nProof.\n  red; intros; contradiction.\nQed.\n\nLemma In_kill_loc:\n  forall e l eqs,\n  In e (kill_loc l eqs) ->\n  In e eqs /\\ Loc.diff (S (e_slot e)) l /\\ Loc.diff (R (e_reg e)) l.\nProof.\n  induction eqs; simpl kill_loc; simpl In; intros.\n  tauto.\n  destruct (Loc.diff_dec (S (e_slot a)) l).\n  destruct (Loc.diff_dec (R (e_reg a)) l).\n  simpl in H.  intuition congruence. \n  simpl in H.  intuition.\n  simpl in H.  intuition.\nQed.\n\nLemma kill_loc_hold:\n  forall ls eqs l v,\n  equations_hold ls eqs ->\n  equations_hold (Locmap.set l v ls) (kill_loc l eqs).\nProof.\n  intros; red; intros. \n  exploit In_kill_loc; eauto. intros [A [B C]].\n  repeat rewrite Locmap.gso; auto; apply Loc.diff_sym; auto.\nQed.\n\nLemma In_kill_locs:\n  forall e ll eqs,\n  In e (kill_locs ll eqs) ->\n  In e eqs /\\ Loc.notin (S (e_slot e)) ll /\\ Loc.notin (R (e_reg e)) ll.\nProof.\nOpaque Loc.diff.\n  induction ll; simpl; intros.\n  tauto.\n  exploit IHll; eauto. intros [A [B C]]. exploit In_kill_loc; eauto. intros [D [E F]]. \n  tauto.\nQed.\n\nLemma kill_locs_hold:\n  forall ll ls eqs,\n  equations_hold ls eqs ->\n  equations_hold (Locmap.undef ll ls) (kill_locs ll eqs).\nProof.\n  intros; red; intros. exploit In_kill_locs; eauto. intros [A [B C]]. \n  repeat rewrite Locmap.guo; auto. \nQed.\n\nLemma kill_temps_hold:\n  forall ls eqs,\n  equations_hold ls eqs ->\n  equations_hold (LTL.undef_temps ls) (kill_temps eqs).\nProof.\n  exact (kill_locs_hold temporaries).\nQed.\n\nLemma kill_at_move_hold:\n  forall ls eqs,\n  equations_hold ls eqs ->\n  equations_hold (undef_setstack ls) (kill_at_move eqs).\nProof.\n  exact (kill_locs_hold destroyed_at_move).\nQed.\n\nLemma kill_at_op_hold:\n  forall op ls eqs,\n  equations_hold ls eqs ->\n  equations_hold (undef_op op ls) (kill_op op eqs).\nProof.\n  intros op. \n  destruct op; exact kill_temps_hold || exact kill_at_move_hold.\nQed.\n\nLemma eqs_getstack_hold:\n  forall rs r s eqs,\n  equations_hold rs eqs ->\n  equations_hold (Locmap.set (R r) (rs (S s)) rs)\n                 (mkeq r s :: kill_loc (R r) eqs).\nProof.\nTransparent Loc.diff.\n  intros; red; intros. simpl in H0; destruct H0.\n  subst e. simpl. rewrite Locmap.gss; rewrite Locmap.gso; auto. red; auto.\n  exploit In_kill_loc; eauto. intros [D [E F]].\n  repeat rewrite Locmap.gso. auto. \n  apply Loc.diff_sym; auto. apply Loc.diff_sym; auto.\nQed.\n\nLemma eqs_movestack_hold:\n  forall rs r s eqs,\n  equations_hold rs eqs ->\n  equations_hold (Locmap.set (R r) (rs (S s)) (undef_setstack rs))\n                 (kill_at_move (mkeq r s :: kill_loc (R r) eqs)).\nProof.\n  unfold undef_setstack, kill_at_move; intros; red; intros.\n  exploit In_kill_locs; eauto. intros [A [B C]].\n  simpl in A; destruct A.\n  subst e. rewrite Locmap.gss. rewrite Locmap.gso. apply Locmap.guo. auto. \n  simpl; auto.\n  exploit In_kill_loc; eauto. intros [D [E F]].\n  repeat rewrite Locmap.gso. repeat rewrite Locmap.guo; auto.\n  apply Loc.diff_sym; auto. apply Loc.diff_sym; auto.\nQed.\n\nLemma eqs_setstack_hold:\n  forall rs r s eqs,\n  equations_hold rs eqs ->\n  equations_hold (Locmap.set (S s) (rs (R r)) (undef_setstack rs))\n                 (kill_at_move (mkeq r s :: kill_loc (S s) eqs)).\nProof.\n  unfold undef_setstack, kill_at_move; intros; red; intros.\n  exploit In_kill_locs; eauto. intros [A [B C]].\n  simpl in A; destruct A.\n  subst e. rewrite Locmap.gss. rewrite Locmap.gso. rewrite Locmap.guo. auto. \n  auto. simpl. destruct s; auto.\n  exploit In_kill_loc; eauto. intros [D [E F]].\n  repeat rewrite Locmap.gso. repeat rewrite Locmap.guo; auto.\n  apply Loc.diff_sym; auto. apply Loc.diff_sym; auto.\nQed.\n\nLemma locmap_set_reg_same:\n  forall rs r,\n  Locmap.set (R r) (rs (R r)) rs = rs.\nProof.\n  intros. apply extensionality; intros. \n  destruct (Loc.eq x (R r)).\n  subst x. apply Locmap.gss.\n  apply Locmap.gso. apply Loc.diff_reg_right; auto.\nQed.\n\n(** * Agreement between values of locations *)\n\n(** Values of locations may differ between the original and transformed\n  program: after a [Lgetstack] is optimized to a [Lop Omove], \n  the values of [destroyed_at_move] temporaries differ.  This\n  can only happen in parts of the code where the [safe_move_insertion]\n  function returns [true].  *)\n\nDefinition agree (sm: bool) (rs rs': locset) : Prop :=\n  forall l, sm = false \\/ Loc.notin l destroyed_at_move -> rs' l = rs l.\n\nLemma agree_false:\n  forall rs rs',\n  agree false rs rs' <-> rs' = rs.\nProof.\n  intros; split; intros.\n  apply extensionality; intros. auto.\n  subst rs'. red; auto. \nQed.\n\nLemma agree_slot:\n  forall sm rs rs' s,\n  agree sm rs rs' -> rs' (S s) = rs (S s).\nProof.\nTransparent Loc.diff.\n  intros. apply H. right. simpl; destruct s; tauto.\nQed.\n\nLemma agree_reg:\n  forall sm rs rs' r,\n  agree sm rs rs' ->\n  sm = false \\/ ~In r destroyed_at_move_regs -> rs' (R r) = rs (R r).\nProof.\n  intros. apply H. destruct H0; auto. right. \n  simpl in H0; simpl; intuition congruence.\nQed.\n\nLemma agree_regs:\n  forall sm rs rs' rl,\n  agree sm rs rs' ->\n  sm = false \\/ list_disjoint rl destroyed_at_move_regs -> reglist rs' rl = reglist rs rl.\nProof.\n  induction rl; intros; simpl. \n  auto.\n  decEq. apply agree_reg with sm. auto.\n    destruct H0. auto. right. eapply list_disjoint_notin; eauto with coqlib.\n  apply IHrl; auto. destruct H0; auto. right. eapply list_disjoint_cons_left; eauto.\nQed.\n\nLemma agree_set:\n  forall sm rs rs' l v,\n  agree sm rs rs' ->\n  agree sm (Locmap.set l v rs) (Locmap.set l v rs').\nProof.\n  intros; red; intros.\n  unfold Locmap.set. \n  destruct (Loc.eq l l0). auto. \n  destruct (Loc.overlap l l0). auto.\n  apply H; auto.\nQed. \n\nLemma agree_undef_move_1:\n  forall sm rs rs',\n  agree sm rs rs' ->\n  agree true rs (undef_setstack rs').\nProof.\n  intros. unfold undef_setstack. red; intros.\n  destruct H0. congruence. rewrite Locmap.guo; auto.\nQed.\n\nRemark locmap_undef_equal:\n  forall x ll rs rs',\n  (forall l, Loc.notin l ll -> rs' l = rs l) ->\n  Locmap.undef ll rs' x = Locmap.undef ll rs x.\nProof.\n  induction ll; intros; simpl.\n  apply H. simpl. auto.\n  apply IHll. intros. unfold Locmap.set. \n  destruct (Loc.eq a l). auto. destruct (Loc.overlap a l) eqn:?. auto. \n  apply H. simpl. split; auto. apply Loc.diff_sym. apply Loc.non_overlap_diff; auto.\nQed. \n\nLemma agree_undef_move_2:\n  forall sm rs rs',\n  agree sm rs rs' ->\n  agree false (undef_setstack rs) (undef_setstack rs').\nProof.\n  intros. rewrite agree_false.\n  apply extensionality; intros. unfold undef_setstack. apply locmap_undef_equal. auto.\nQed.\n\nLemma agree_undef_temps:\n  forall sm rs rs',\n  agree sm rs rs' ->\n  agree false (LTL.undef_temps rs) (LTL.undef_temps rs').\nProof.\n  intros. rewrite agree_false.\n  apply extensionality; intros. unfold LTL.undef_temps. apply locmap_undef_equal.\n  intros. apply H. right. simpl in H0; simpl; tauto.\nQed.\n\nLemma agree_undef_op:\n  forall op sm rs rs',\n  agree sm rs rs' ->\n  agree false (undef_op op rs) (undef_op op rs').\nProof.\n  intros op.\n  destruct op; exact agree_undef_temps || exact agree_undef_move_2.\nQed.\n\nLemma transl_find_label:\n  forall lbl c eqs,\n  find_label lbl (transf_code eqs c) =\n  option_map (transf_code nil) (find_label lbl c).\nProof.\n  induction c; simpl; intros.\n  auto.\n  destruct a; simpl; auto.\n  destruct (is_incoming s); simpl; auto.\n  destruct (contains_equation s m eqs); auto.\n  destruct (find_reg_containing s eqs); simpl; auto.\n  destruct (safe_move_insertion c); simpl; auto. \n  destruct (peq lbl l); simpl; auto.\nQed.\n\n(** * Semantic preservation *)\n\nSection PRESERVATION.\n\nVariable prog: program.\nLet tprog := transf_program prog.\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  Genv.find_funct tge v = Some (transf_fundef f).\nProof (@Genv.find_funct_transf _ _ _ transf_fundef prog).\n\nLemma function_ptr_translated:\n  forall v f,\n  Genv.find_funct_ptr ge v = Some f ->\n  Genv.find_funct_ptr tge v = Some (transf_fundef f).\nProof (@Genv.find_funct_ptr_transf _ _ _ transf_fundef prog).\n\nLemma symbols_preserved:\n  forall id,\n  Genv.find_symbol tge id = Genv.find_symbol ge id.\nProof (@Genv.find_symbol_transf _ _ _ transf_fundef prog).\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 _ _ _ transf_fundef prog).\n\nLemma sig_preserved:\n  forall f, funsig (transf_fundef f) = funsig f.\nProof.\n  destruct f; reflexivity.\nQed.\n\nLemma find_function_translated:\n  forall ros rs fd,\n  find_function ge ros rs = Some fd ->\n  find_function tge ros rs = Some (transf_fundef fd).\nProof.\n  intros. destruct ros; simpl in *. \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\nInductive match_frames: stackframe -> stackframe -> Prop :=\n  | match_frames_intro:\n      forall f sp rs c,\n      match_frames (Stackframe f sp rs c)\n                   (Stackframe (transf_function f) sp rs (transf_code nil c)).\n\nInductive match_states: state -> state -> Prop :=\n  | match_states_regular:\n      forall sm stk f sp c rs m stk' rs' eqs\n        (STK: list_forall2 match_frames stk stk')\n        (EQH: equations_hold rs' eqs)\n        (AG: agree sm rs rs')\n        (SAFE: sm = false \\/ safe_move_insertion c = true),\n      match_states (State stk f sp c rs m)\n                   (State stk' (transf_function f) sp (transf_code eqs c) rs' m)\n  | match_states_call:\n      forall stk f rs m stk'\n        (STK: list_forall2 match_frames stk stk'),\n      match_states (Callstate stk f rs m)\n                   (Callstate stk' (transf_fundef f) rs m)\n  | match_states_return:\n      forall stk rs m stk'\n        (STK: list_forall2 match_frames stk stk'),\n      match_states (Returnstate stk rs m)\n                   (Returnstate stk' rs m).\n\nDefinition measure (S: state) : nat :=\n  match S with\n  | State s f sp c rs m => List.length c\n  | _ => 0%nat\n  end.\n\nRemark match_parent_locset:\n  forall stk stk',\n  list_forall2 match_frames stk stk' ->\n  return_regs (parent_locset stk') = return_regs (parent_locset stk).\nProof.\n  intros. inv H; auto. inv H0; auto.\nQed.\n\nTheorem transf_step_correct:\n  forall S1 t S2, step ge S1 t S2 ->\n  forall S1' (MS: match_states S1 S1'),\n  (exists S2', step tge S1' t S2' /\\ match_states S2 S2')\n  \\/ (measure S2 < measure S1 /\\ t = E0 /\\ match_states S2 S1')%nat.\nProof.\nOpaque destroyed_at_move_regs.\n  induction 1; intros; inv MS; simpl.\n(** getstack *)\n  simpl in SAFE. \n  assert (SAFE': sm = false \\/ ~In r destroyed_at_move_regs /\\ safe_move_insertion b = true).\n    destruct (in_dec mreg_eq r destroyed_at_move_regs); simpl in SAFE; intuition congruence. \n  destruct (is_incoming sl) eqn:?.\n  (* incoming, stays as getstack *)\n  assert (UGS: forall rs, undef_getstack sl rs = Locmap.set (R IT1) Vundef rs).\n    destruct sl; simpl in Heqb0; discriminate || auto.\n  left; econstructor; split. constructor.\n  repeat rewrite UGS.\n  apply match_states_regular with sm. auto.\n  apply kill_loc_hold. apply kill_loc_hold; auto.\n  rewrite (agree_slot _ _ _ sl AG). apply agree_set. apply agree_set. auto.\n  tauto.\n  (* not incoming *)\n  assert (UGS: forall rs, undef_getstack sl rs = rs). \n    destruct sl; simpl in Heqb0; discriminate || auto.\n  unfold contains_equation. \n  destruct (in_dec eq_equation (mkeq r sl) eqs); simpl.\n  (* eliminated *)\n  right.  split. omega. split. auto. rewrite UGS.  \n  exploit EQH; eauto. simpl. intro EQ.\n  assert (EQ1: rs' (S sl) = rs (S sl)) by (eapply agree_slot; eauto).\n  assert (EQ2: rs' (R r) = rs (R r)) by (eapply agree_reg; eauto; tauto).\n  rewrite <- EQ1; rewrite EQ; rewrite EQ2. rewrite locmap_set_reg_same.\n  apply match_states_regular with sm; auto; tauto. \n  (* found an equation *)\n  destruct (find_reg_containing sl eqs) as [r'|] eqn:?.\n  exploit EQH. eapply find_reg_containing_sound; eauto. \n  simpl; intro EQ.\n  (* turned into a move *)\n  destruct (safe_move_insertion b) eqn:?. \n  left; econstructor; split. constructor. simpl; eauto. \n  rewrite UGS. rewrite <- EQ.\n  apply match_states_regular with true; auto. \n  apply eqs_movestack_hold; auto. \n  rewrite (agree_slot _ _ _ sl AG). apply agree_set. eapply agree_undef_move_1; eauto.\n  (* left as a getstack *)\n  left; econstructor; split. constructor.\n  repeat rewrite UGS.\n  apply match_states_regular with sm. auto. \n  apply eqs_getstack_hold; auto. \n  rewrite (agree_slot _ _ _ sl AG). apply agree_set. auto. \n  intuition congruence. \n  (* no equation, left as a getstack *)\n  left; econstructor; split. constructor.\n  repeat rewrite UGS.\n  apply match_states_regular with sm. auto. \n  apply eqs_getstack_hold; auto. \n  rewrite (agree_slot _ _ _ sl AG). apply agree_set. auto.\n  tauto.\n\n(* setstack *)\n  left; econstructor; split. constructor.\n  apply match_states_regular with false; auto.\n  apply eqs_setstack_hold; auto.\n  rewrite (agree_reg _ _ _ r AG). apply agree_set. eapply agree_undef_move_2; eauto. \n  simpl in SAFE. destruct (in_dec mreg_eq r destroyed_at_move_regs); simpl in SAFE; intuition congruence.\n\n(* op *)\n  left; econstructor; split. constructor. \n  instantiate (1 := v). rewrite <- H.\n  rewrite (agree_regs _ _ _ args AG). \n  apply eval_operation_preserved. exact symbols_preserved.\n  simpl in SAFE. destruct (list_disjoint_dec mreg_eq args destroyed_at_move_regs); simpl in SAFE; intuition congruence.\n  apply match_states_regular with false; auto.\n  apply kill_loc_hold; apply kill_at_op_hold; auto.\n  apply agree_set. eapply agree_undef_op; eauto.\n\n(* load *)\n  left; econstructor; split.\n  econstructor.  instantiate (1 := a).  rewrite <- H.\n  rewrite (agree_regs _ _ _ args AG). \n  apply eval_addressing_preserved.  exact symbols_preserved.\n  simpl in SAFE. destruct (list_disjoint_dec mreg_eq args destroyed_at_move_regs); simpl in SAFE; intuition congruence.\n  eauto.\n  apply match_states_regular with false; auto.\n  apply kill_loc_hold; apply kill_temps_hold; auto.\n  apply agree_set. eapply agree_undef_temps; eauto.\n\n(* store *)\nOpaque list_disjoint_dec.\n  simpl in SAFE.\n  assert (sm = false \\/ ~In src destroyed_at_move_regs /\\ list_disjoint args destroyed_at_move_regs).\n    destruct SAFE. auto. right. \n    destruct (list_disjoint_dec mreg_eq (src :: args) destroyed_at_move_regs); try discriminate.\n    split. eapply list_disjoint_notin; eauto with coqlib. eapply list_disjoint_cons_left; eauto. \n  left; econstructor; split.\n  econstructor.  instantiate (1 := a).  rewrite <- H.\n  rewrite (agree_regs _ _ _ args AG). \n  apply eval_addressing_preserved.  exact symbols_preserved.\n  tauto.\n  rewrite (agree_reg _ _ _ src AG).\n  eauto.\n  tauto.\n  apply match_states_regular with false; auto.\n  apply kill_temps_hold; auto.\n  eapply agree_undef_temps; eauto.\n\n(* call *)\n  simpl in SAFE. assert (sm = false) by intuition congruence. \n  subst sm. rewrite agree_false in AG. subst rs'. \n  left; econstructor; split.\n  constructor. eapply find_function_translated; eauto. \n  symmetry; apply sig_preserved.\n  constructor. constructor; auto. constructor. \n\n(* tailcall *)\n  simpl in SAFE. assert (sm = false) by intuition congruence. \n  subst sm. rewrite agree_false in AG. subst rs'. \n  left; econstructor; split.\n  constructor. eapply find_function_translated; eauto. \n  symmetry; apply sig_preserved. eauto. \n  reflexivity.\n  rewrite (match_parent_locset _ _ STK). constructor; auto.\n\n(* builtin *)\n  left; econstructor; split.\n  constructor.\n  rewrite (agree_regs _ _ _ args AG). \n  eapply external_call_symbols_preserved; eauto. \n  exact symbols_preserved. exact varinfo_preserved.\n  simpl in SAFE. destruct (list_disjoint_dec mreg_eq args destroyed_at_move_regs); simpl in SAFE; intuition congruence.\n  apply match_states_regular with false; auto.\n  apply kill_loc_hold; apply kill_temps_hold; auto.\n  apply agree_set. eapply agree_undef_temps; eauto.\n\n(* annot *)\n  simpl in SAFE. assert (sm = false) by intuition congruence. \n  subst sm. rewrite agree_false in AG. subst rs'. \n  left; econstructor; split.\n  econstructor. eapply external_call_symbols_preserved; eauto. \n  exact symbols_preserved. exact varinfo_preserved.\n  apply match_states_regular with false; auto.\n  rewrite agree_false; auto. \n\n(* label *)\n  left; econstructor; split. constructor.\n  apply match_states_regular with false; auto. \n  apply nil_hold.\n  simpl in SAFE. destruct SAFE. subst sm. auto. congruence.\n\n(* goto *)\n  generalize (transl_find_label lbl (fn_code f) nil).  rewrite H. simpl. intros.\n  left; econstructor; split. constructor; eauto.\n  apply match_states_regular with false; auto. \n  apply nil_hold.\n  simpl in SAFE. destruct SAFE. subst sm. auto. congruence.\n\n(* cond true *)\n  generalize (transl_find_label lbl (fn_code f) nil).  rewrite H0. simpl. intros.\n  left; econstructor; split.\n  apply exec_Lcond_true; auto.\n  rewrite (agree_regs _ _ _ args AG). auto.\n  simpl in SAFE. destruct (list_disjoint_dec mreg_eq args destroyed_at_move_regs); simpl in SAFE; intuition congruence.\n  eauto.\n  apply match_states_regular with false; auto.\n  apply nil_hold. \n  eapply agree_undef_temps; eauto.\n\n(* cond false *)\n  left; econstructor; split. apply exec_Lcond_false; auto.\n  rewrite (agree_regs _ _ _ args AG). auto.\n  simpl in SAFE. destruct (list_disjoint_dec mreg_eq args destroyed_at_move_regs); simpl in SAFE; intuition congruence.\n  apply match_states_regular with false; auto.\n  apply kill_temps_hold; auto.\n  eapply agree_undef_temps; eauto.\n\n(* jumptable *)\n  generalize (transl_find_label lbl (fn_code f) nil).  rewrite H1. simpl. intros.\n  left; econstructor; split. econstructor; eauto.\n  rewrite (agree_reg _ _ _ arg AG). auto.\n  simpl in SAFE. destruct (in_dec mreg_eq arg destroyed_at_move_regs); simpl in SAFE; intuition congruence.\n  apply match_states_regular with false; auto.\n  apply nil_hold.\n  eapply agree_undef_temps; eauto.\n\n(* return *)\n  simpl in SAFE. destruct SAFE; try discriminate. subst sm. rewrite agree_false in AG. subst rs'.\n  left; econstructor; split.\n  constructor. simpl. eauto. \n  reflexivity.\n  rewrite (match_parent_locset _ _ STK). \n  constructor; auto.\n\n(* internal *)\n  left; econstructor; split.\n  constructor. simpl; eauto.\n  reflexivity.\n  simpl. apply match_states_regular with false; auto. apply nil_hold. rewrite agree_false; auto.\n\n(* external *)\n  left; econstructor; split.\n  econstructor. eapply external_call_symbols_preserved; eauto. \n  exact symbols_preserved. exact varinfo_preserved. \n  auto. eauto. \n  constructor; auto. \n\n(* return *)\n  inv STK. inv H1. left; econstructor; split. constructor.\n  apply match_states_regular with false; auto.\n  apply nil_hold.\n  rewrite agree_false; 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  econstructor; split.\n  econstructor.\n  apply Genv.init_mem_transf; eauto.\n  rewrite symbols_preserved. eauto.\n  apply function_ptr_translated; eauto. \n  rewrite sig_preserved. auto.\n  econstructor; eauto. constructor.\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 STK. econstructor. auto.\nQed.\n\nTheorem transf_program_correct:\n  forward_simulation (Linear.semantics prog) (Linear.semantics tprog).\nProof.\n  eapply forward_simulation_opt.\n  eexact symbols_preserved.\n  eexact transf_initial_states.\n  eexact transf_final_states.\n  eexact transf_step_correct. \nQed.\n\nEnd PRESERVATION.\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/RREproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038302, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2782495803168583}}
{"text": "Require Import VST.msl.log_normalize.\nRequire Import VST.msl.ghost.\nRequire Import VST.msl.ghost_seplog.\nRequire Export VST.veric.base.\nRequire Import VST.veric.rmaps.\nRequire Import VST.veric.compcert_rmaps.\nRequire Import VST.veric.res_predicates.\n\nImport RML. Import R.\nLocal Open Scope pred.\n\nNotation ghost_approx m := (ghost_fmap (approx (level m)) (approx (level m))).\n\n(* Ownership construction based on \"Iris from the ground up\", Jung et al. *)\nProgram Definition ghost_is g: pred rmap :=\n  fun m => ghost_of m = ghost_approx m g.\nNext Obligation.\n  intros ???? Hg.\n  rewrite (age1_ghost_of _ _ H), Hg.\n  pose proof (age_level _ _ H).\n  rewrite ghost_fmap_fmap, approx_oo_approx', approx'_oo_approx by lia; eauto.\nQed.\n\nDefinition Own g: pred rmap := allp noat && ghost_is g.\n\nLemma Own_op: forall a b c, join a b c -> Own c = Own a * Own b.\nProof.\n  intros; apply pred_ext.\n  - intros w (Hno & Hg).\n    destruct (make_rmap (resource_at w) (ghost_approx w a) (level w))\n      as (wa & Hla & Hra & Hga).\n    { extensionality; apply resource_at_approx. }\n    { rewrite ghost_fmap_fmap, approx_oo_approx; auto. }\n    destruct (make_rmap (resource_at w) (ghost_approx w b) (level w))\n      as (wb & Hlb & Hrb & Hgb).\n    { extensionality; apply resource_at_approx. }\n    { rewrite ghost_fmap_fmap, approx_oo_approx; auto. }\n    exists wa, wb; split.\n    + apply resource_at_join2; auto.\n      * intro; rewrite Hra, Hrb.\n        apply identity_unit', Hno.\n      * rewrite Hg, Hga, Hgb.\n        apply ghost_fmap_join; auto.\n    + simpl; rewrite Hla, Hlb, Hra, Hrb, Hga, Hgb; simpl; eauto 6.\n  - intros w (w1 & w2 & J & (Hnoa & Hga) & (Hnob & Hgb)).\n    split.\n    + intro l; apply (resource_at_join _ _ _ l) in J.\n      simpl in *; rewrite <- (Hnoa _ _ _ J); auto.\n    + destruct (join_level _ _ _ J) as [Hl1 Hl2].\n      apply ghost_of_join in J.\n      rewrite Hga, Hgb in J.\n      eapply join_eq; eauto.\n      rewrite Hl1, Hl2; apply ghost_fmap_join; auto.\nQed.\n\nFixpoint make_join (a c : ghost) : ghost :=\n  match a, c with\n  | nil, _ => c\n  | _, nil => nil\n  | None :: a', x :: c' => x :: make_join a' c'\n  | _ :: a', None :: c' => None :: make_join a' c'\n  | Some (ga, pa) :: a', Some (gc, _) :: c' => Some (gc, pa) :: make_join a' c'\n  end.\n\nLemma make_join_nil : forall a, make_join a nil = nil.\nProof.\n  destruct a; auto.\n  destruct o as [[]|]; auto.\nQed.\n\nLemma make_join_nil_cons : forall o a c, make_join (o :: a) (None :: c) = None :: make_join a c.\nProof.\n  destruct o as [[]|]; auto.\nQed.\n\nLemma ghost_joins_approx: forall n a c,\n  joins (ghost_fmap (approx n) (approx n) a) (ghost_fmap (approx n) (approx n) c) ->\n  let c' := make_join a c in\n  joins (ghost_fmap (approx (S n)) (approx (S n)) a) (ghost_fmap (approx (S n)) (approx (S n)) c') /\\\n    forall b, joins b (ghost_fmap (approx (S n)) (approx (S n)) c') ->\n      joins (ghost_fmap (approx n) (approx n) b) (ghost_fmap (approx n) (approx n) c).\nProof.\n  intros ???; revert a; induction c; intros; subst c'; simpl.\n  - rewrite make_join_nil; split.\n    + eexists; constructor.\n    + eexists; constructor.\n  - destruct H; inv H.\n    + destruct a0; inv H1.\n      split.\n      { eexists; constructor. }\n      intros ? []; eexists.\n      apply ghost_fmap_join with (f := approx n)(g := approx n) in H.\n      rewrite ghost_fmap_fmap, approx_oo_approx', approx'_oo_approx in H by auto; eauto.\n    + destruct a0; inv H0.\n      destruct (IHc a0) as (H & Hc'); eauto.\n      inv H3.\n      * destruct o; inv H1.\n        split.\n        { destruct H; eexists; constructor; eauto; constructor. }\n        intros ? [? J]; inv J; [eexists; constructor|].\n        destruct (Hc' m1); eauto.\n        eexists; constructor; eauto.\n        instantiate (1 := option_map (fun '(a, b) => (a, preds_fmap (approx n) (approx n) b)) a3).\n        inv H3.\n        -- destruct a as [[]|]; [simpl | constructor].\n           rewrite preds_fmap_fmap, approx_oo_approx', approx'_oo_approx by auto; constructor; auto.\n        -- destruct a; inv H4; constructor.\n        -- destruct a as [[]|]; inv H1; constructor.\n           destruct a2, a5; inv H4; constructor; auto; simpl in *.\n           inv H2.\n           rewrite preds_fmap_fmap, approx_oo_approx', approx'_oo_approx by auto; constructor; auto.\n      * destruct a; inv H2.\n        rewrite make_join_nil_cons.\n        split.\n        { destruct H; eexists; constructor; eauto; constructor. }\n        intros ? [? J]; inv J; [eexists; constructor|].\n        destruct (Hc' m1); eauto.\n        eexists; constructor; eauto; constructor.\n      * destruct o as [[]|], a as [[]|]; inv H0; inv H1.\n        split.\n        { destruct H.\n          destruct a4; inv H2; simpl in *.\n          inv H1.\n          eexists (Some (_, _) :: _); constructor; eauto; constructor.\n          constructor; simpl; eauto; constructor; eauto. }\n        intros ? [? J]; inv J; [eexists; constructor|].\n        destruct (Hc' m1); eauto.\n        eexists; constructor; eauto.\n        instantiate (1 := option_map (fun '(a, b) => (a, preds_fmap (approx n) (approx n) b)) a3).\n        inv H4.\n        -- destruct a4; inv H2; simpl in *.\n           inv H3.\n           rewrite <- H2, preds_fmap_fmap, approx_oo_approx', approx'_oo_approx by auto; constructor.\n        -- constructor.\n           destruct a2, a4, a6; inv H2; inv H6; constructor; auto; simpl in *.\n           inv H3; inv H4.\n           rewrite <- H6, preds_fmap_fmap, approx_oo_approx', approx'_oo_approx by auto; constructor; auto.\nQed.\n\nProgram Definition bupd (P: pred rmap): pred rmap :=\n  fun m => forall c, joins (ghost_of m) (ghost_approx m c) ->\n    exists b, joins b (ghost_approx m c) /\\\n    exists m', level m' = level m /\\ resource_at m' = resource_at m /\\ ghost_of m' = b /\\ P m'.\nNext Obligation.\nProof.\n  repeat intro.\n  rewrite (age1_ghost_of _ _ H) in H1.\n  rewrite <- ghost_of_approx in H0.\n  destruct (ghost_joins_approx _ _ _ H1) as (J0 & Hc0).\n  rewrite <- (age_level _ _ H) in *.\n  specialize (H0 _ J0); destruct H0 as (b & J & Hrb).\n  pose proof (age_level _ _ H).\n  exists (ghost_approx a' b); split; auto.\n  destruct Hrb as (m' & Hl' & Hr' & Hg' & HP).\n  destruct (levelS_age m' (level a')) as (m'' & Hage' & Hl'').\n  { congruence. }\n  exists m''; repeat split; auto.\n  + extensionality l.\n    erewrite (age1_resource_at _ _ H l) by (symmetry; apply resource_at_approx).\n    erewrite (age1_resource_at _ _ Hage' l) by (symmetry; apply resource_at_approx).\n    congruence.\n  + rewrite (age1_ghost_of _ _ Hage').\n    rewrite Hg', <- Hl''; auto.\n  + eapply (proj2_sig P); eauto.\nQed.\n\nLemma bupd_intro: forall P, P |-- bupd P.\nProof.\n  repeat intro; eauto 7.\nQed.\n\nLemma bupd_mono: forall P Q, P |-- Q -> bupd P |-- bupd Q.\nProof.\n  repeat intro.\n  simpl in *.\n  destruct (H0 _ H1) as (b & ? & m' & ? & ? & ? & ?).\n  exists b; split; auto.\n  exists m'; repeat split; auto.\nQed.\n\nLemma bupd_frame_r: forall P Q, bupd P * Q |-- bupd (P * Q).\nProof.\n  repeat intro.\n  destruct H as (w1 & w2 & J & HP & HQ).\n  destruct (join_level _ _ _ J) as [Hl1 Hl2].\n  pose proof (ghost_of_join _ _ _ J) as Jg.\n  destruct H0 as [? J'].\n  destruct (join_assoc Jg J') as (c' & J1 & J2).\n  erewrite <- (ghost_same_level_gen (level a) (ghost_of w2) c c') in J2, J1\n    by (rewrite <- Hl2 at 1 2; rewrite ghost_of_approx; auto).\n  destruct (HP c') as (? & [? J1'] & w1' & ? & Hr' & ? & HP'); subst.\n  { rewrite Hl1; eauto. }\n  rewrite Hl1 in J1'; destruct (join_assoc (join_comm J1) (join_comm J1')) as (w' & ? & ?).\n  exists w'; split; [eexists; apply join_comm; eauto|].\n  destruct (make_rmap (resource_at a) w' (level a)) as (m' & ? & Hr'' & ?); subst.\n  { extensionality l; apply resource_at_approx. }\n  { eapply ghost_same_level_gen.\n    rewrite <- (ghost_of_approx w2), <- (ghost_of_approx w1'), H, Hl1, Hl2 in H0.\n    apply join_comm; eauto. }\n  exists m'; repeat split; auto.\n  exists w1', w2; repeat split; auto.\n  apply resource_at_join2; auto; try lia.\n  intro; rewrite Hr', Hr''.\n  apply resource_at_join; auto.\nQed.\n\nLemma bupd_frame_l: forall P Q, P * bupd Q |-- bupd (P * Q).\nProof.\n  intros; rewrite sepcon_comm, (sepcon_comm P Q); apply bupd_frame_r.\nQed.\n\nLemma bupd_trans: forall P, bupd (bupd P) |-- bupd P.\nProof.\n  repeat intro.\n  destruct (H _ H0) as (b & J & a' & Hl & Hr & ? & Ha'); subst.\n  rewrite <- Hl in J; destruct (Ha' _ J) as (b' & ? & Hm').\n  rewrite <- Hl, <- Hr; eauto.\nQed.\n\nLemma bupd_prop : forall P, bupd (!! P) = !! P.\nProof.\n  intros ?; apply pred_ext.\n  - intros ??; simpl in *.\n    destruct (H (core (ghost_of a))) as (? & ? & ? & ? & ? & ? & ?); auto.\n    eexists.\n    rewrite ghost_core; simpl; erewrite <- ghost_core.\n    apply join_comm, core_unit.\n  - intros ??.\n    do 2 eexists; eauto.\nQed.\n\nLemma subp_bupd: forall (G : pred nat) (P P' : pred rmap), G |-- P >=> P' ->\n    G |-- (bupd P >=> bupd P')%pred.\nProof.\n  repeat intro.\n  specialize (H3 _ H4) as (? & ? & ? & ? & ? & ? & HP).\n  do 2 eexists; eauto; do 2 eexists; eauto; repeat (split; auto).\n  pose proof (necR_level _ _ H2).\n  apply (H _ H0 x0 ltac:(lia) _ (necR_refl _)); auto.\nQed.\n\nLemma eqp_bupd: forall (G : pred nat) (P P' : pred rmap), G |-- P <=> P' ->\n    G |-- (bupd P <=> bupd P').\nProof.\n  intros.\n  rewrite fash_and in *.\n  apply andp_right; apply subp_bupd; eapply derives_trans; try apply H;\n    [apply andp_left1 | apply andp_left2]; apply derives_refl.\nQed.\n\nDefinition ghost_fp_update_ND a B :=\n  forall n c, joins (ghost_fmap (approx n) (approx n) a) c ->\n    exists b, B b /\\ joins (ghost_fmap (approx n) (approx n) b) c.\n\nLemma Own_update_ND: forall a B, ghost_fp_update_ND a B ->\n  Own a |-- bupd (EX b : _, !!(B b) && Own b).\nProof.\n  repeat intro.\n  destruct H0 as (Hno & Hg).\n  rewrite Hg in H1.\n  destruct H1 as [? J].\n  destruct (H (level a0) (ghost_approx a0 c)) as (g' & ? & J').\n  { eexists; eauto. }\n  exists (ghost_fmap (approx (level a0)) (approx (level a0)) g'); split; auto.\n  destruct (make_rmap (resource_at a0)\n    (ghost_fmap (approx (level a0)) (approx (level a0)) g') (level a0))\n    as (m' & Hl & Hr & Hg').\n  { extensionality; apply resource_at_approx. }\n  { rewrite ghost_fmap_fmap, approx_oo_approx; auto. }\n  exists m'; repeat split; auto.\n  exists g'; repeat split; auto.\n  - simpl in *; intro; rewrite Hr; auto.\n  - simpl; rewrite Hg', Hl; simpl; eauto.\nQed.\n\nDefinition ghost_fp_update (a b : ghost) :=\n  forall n c, joins (ghost_fmap (approx n) (approx n) a) c ->\n               joins (ghost_fmap (approx n) (approx n) b) c.\n\nInstance ghost_fp_update_preorder: RelationClasses.PreOrder ghost_fp_update.\nProof.\n  split; repeat intro; auto.\nQed.\n\nLemma ghost_fp_update_approx: forall a b n, ghost_fp_update a b ->\n  ghost_fp_update (ghost_fmap (approx n) (approx n) a) (ghost_fmap (approx n) (approx n) b).\nProof.\n  intros; intros m c J.\n  rewrite ghost_fmap_fmap in *.\n  replace (approx m oo approx n) with (approx (min m n)) in *.\n  replace (approx n oo approx m) with (approx (min m n)) in *.\n  auto.\n  { destruct (Min.min_spec m n) as [[? ->] | [? ->]];\n      [rewrite approx'_oo_approx | rewrite approx_oo_approx']; auto; lia. }\n  { destruct (Min.min_spec m n) as [[? ->] | [? ->]];\n      [rewrite approx_oo_approx' | rewrite approx'_oo_approx]; auto; lia. }\nQed.\n\nLemma Own_update: forall a b, ghost_fp_update a b ->\n  Own a |-- bupd (Own b).\nProof.\n  intros; eapply derives_trans.\n  - eapply (Own_update_ND _ (eq _)).\n    repeat intro.\n    eexists; split; [constructor|].\n    apply H; eauto.\n  - apply bupd_mono.\n    repeat (apply exp_left; intro).\n    apply prop_andp_left; intro X; inv X; auto.\nQed.\n\nLemma Own_unit: emp |-- EX a : _, !!(identity a) && Own a.\nProof.\n  intros w ?; simpl in *.\n  exists (ghost_of w); split; [|split].\n  - apply ghost_of_identity; auto.\n  - intro; apply resource_at_identity; auto.\n  - rewrite ghost_of_approx; auto.\nQed.\n\nLemma Own_dealloc: forall a, Own a |-- bupd emp.\nProof.\n  intros ? w [] ??.\n  exists (core ((ghost_approx w) c)); split; [eexists; apply core_unit|].\n  destruct (make_rmap (resource_at w) (core (ghost_approx w c)) (level w)) as (w' & ? & Hr & Hg).\n  { extensionality; apply resource_at_approx. }\n  { rewrite ghost_core; auto. }\n  exists w'; repeat split; auto.\n  apply all_resource_at_identity.\n  - rewrite Hr; auto.\n  - rewrite Hg; apply core_identity.\nQed.\n\nDefinition singleton {A} k (x : A) : list (option A) := repeat None k ++ Some x :: nil.\n\nDefinition gname := nat.\n\nDefinition own {RA: Ghost} (n: gname) (a: G) (pp: preds) :=\n  EX v : _, Own (singleton n (existT _ RA (exist _ a v), pp)).\n\nDefinition list_set {A} (m : list (option A)) k v : list (option A) :=\n  firstn k m ++ repeat None (k - length m) ++ Some v :: skipn (S k) m.\n\nLemma singleton_join_gen: forall k a c (m: ghost)\n  (Hjoin: join (Some a) (nth k m None) (Some c)),\n  join (singleton k a) m (list_set m k c).\nProof.\n  induction k; intros.\n  - destruct m; simpl in *; subst; inv Hjoin; constructor; constructor; auto.\n  - destruct m; simpl in *.\n    + inv Hjoin; constructor.\n    + constructor; [constructor | apply IHk; auto].\nQed.\n\nLemma map_repeat : forall {A B} (f : A -> B) x n, map f (repeat x n) = repeat (f x) n.\nProof.\n  induction n; auto; simpl.\n  rewrite IHn; auto.\nQed.\n\nLemma ghost_fmap_singleton: forall f g k v, ghost_fmap f g (singleton k v) =\n  singleton k (match v with (a, b) => (a, preds_fmap f g b) end).\nProof.\n  intros; unfold ghost_fmap, singleton.\n  rewrite map_app, map_repeat; auto.\nQed.\n\nLemma ghost_fmap_singleton_inv : forall f g a k v,\n  ghost_fmap f g a = singleton k v ->\n  exists v', a = singleton k v' /\\ v = let (a, b) := v' in (a, preds_fmap f g b).\nProof.\n  unfold singleton; induction a; simpl; intros.\n  - destruct k; discriminate.\n  - destruct a as [[]|]; simpl in *.\n    + destruct k; inv H.\n      destruct a0; inv H2.\n      simpl; eauto.\n    + destruct k; inv H.\n      edestruct IHa as (? & ? & ?); eauto; subst.\n      simpl; eauto.\nQed.\n\nLemma ghost_alloc: forall {RA: Ghost} a pp, ghost.valid a ->\n  emp |-- bupd (EX g: gname, own g a pp).\nProof.\n  intros.\n  eapply derives_trans; [apply Own_unit|].\n  apply exp_left; intro g0.\n  apply prop_andp_left; intro Hg0.\n  eapply derives_trans.\n  - apply Own_update_ND with (B := fun b => exists g, b = singleton g (existT _ RA (exist _ _ H), pp)).\n    intros ? c [? J]; exists (singleton (length c) (existT _ RA (exist _ _ H), pp)).\n    split; eauto.\n    rewrite (identity_core Hg0), ghost_core in J; inv J; [|eexists; constructor].\n    rewrite ghost_fmap_singleton; eexists; apply singleton_join_gen.\n    rewrite nth_overflow by auto; constructor.\n  - apply bupd_mono, exp_left; intro g'.\n    apply prop_andp_left; intros [g]; subst.\n    apply exp_right with g.\n    eapply exp_right; eauto.\nQed.\n\nLemma singleton_join: forall a b c k,\n  join (singleton k a) (singleton k b) (singleton k c) <-> join a b c.\nProof.\n  unfold singleton; induction k; simpl.\n  - split.\n    + inversion 1; subst.\n      inv H3; auto.\n    + intro; do 2 constructor; auto.\n  - rewrite <- IHk.\n    split; [inversion 1 | repeat constructor]; auto.\nQed.\n\nLemma singleton_join_inv: forall k a b c,\n  join (singleton k a) (singleton k b) c -> exists c', join a b c' /\\ c = singleton k c'.\nProof.\n  unfold singleton; induction k; inversion 1; subst.\n  - assert (m3 = nil) by (inv H6; auto).\n    inv H5; eauto.\n  - assert (a3 = None) by (inv H5; auto); subst.\n    edestruct IHk as (? & ? & ?); eauto; subst; eauto.\nQed.\n\nLemma ghost_valid_2: forall {RA: Ghost} g a1 a2 pp,\n  own g a1 pp * own g a2 pp |-- !!ghost.valid_2 a1 a2.\nProof.\n  intros.\n  intros w (? & ? & J%ghost_of_join & (? & ? & Hg1) & (? & ? & Hg2)).\n  rewrite Hg1, Hg2, !ghost_fmap_singleton in J.\n  apply singleton_join_inv in J as ([] & J & ?).\n  inv J; simpl in *.\n  inv H2; repeat inj_pair_tac.\n  eexists; eauto.\nQed.\n\nLemma ghost_op: forall {RA: Ghost} g (a1 a2 a3: G) pp, join a1 a2 a3 ->\n  own g a3 pp = own g a1 pp * own g a2 pp.\nProof.\n  intros; apply pred_ext.\n  - apply exp_left; intro.\n    erewrite Own_op; [apply sepcon_derives; eapply exp_right; eauto|].\n    apply singleton_join; constructor; constructor; auto.\n  - eapply derives_trans; [apply andp_right, derives_refl; apply ghost_valid_2|].\n    apply prop_andp_left; intros (? & J & ?).\n    eapply join_eq in H; eauto; subst.\n    unfold own; rewrite exp_sepcon1; apply exp_left; intro.\n    rewrite exp_sepcon2; apply exp_left; intro.\n    erewrite <- Own_op; [eapply exp_right; eauto|].\n    apply singleton_join; constructor; constructor; auto.\n  Unshelve.\n  eapply join_valid; eauto.\n  eapply join_valid; eauto.\n  auto.\nQed.\n\nLemma ghost_valid: forall {RA: Ghost} g a pp,\n  own g a pp |-- !!ghost.valid a.\nProof.\n  intros.\n  rewrite <- (normalize.andp_TT (!!_)).\n  erewrite ghost_op by apply core_unit.\n  eapply derives_trans; [apply andp_right, derives_refl; apply ghost_valid_2|].\n  apply prop_andp_left; intros (? & J & ?); apply prop_andp_right; auto.\n  apply core_identity in J; subst; auto.\nQed.\n\nLemma singleton_join_inv_gen: forall k a (b c: ghost),\n  join (singleton k a) b c ->\n  join (Some a) (nth k b None) (nth k c None) /\\\n    exists c', nth k c None = Some c' /\\ c = list_set b k c'.\nProof.\n  unfold singleton; induction k; inversion 1; subst; auto.\n  - split; simpl; eauto; constructor.\n  - split; auto.\n    unfold list_set; simpl.\n    rewrite <- (ghost_core m2) in H5.\n    apply (core_identity m2) in H5; subst.\n    inv H2; eauto.\n  - rewrite app_nth2; rewrite repeat_length; auto.\n    rewrite minus_diag; split; [constructor | simpl; eauto].\n  - assert (a2 = a3) by (inv H2; auto).\n    destruct (IHk _ _ _ H5) as (? & ? & ? & ?); subst; eauto.\nQed.\n\nLemma ghost_update_ND: forall {RA: Ghost} g (a: G) B pp,\n  fp_update_ND a B -> own g a pp |-- bupd (EX b : _, !!(B b) && own g b pp).\nProof.\n  intros.\n  apply exp_left; intro Hva.\n  eapply derives_trans.\n  - apply Own_update_ND with\n      (B := fun b => exists b' Hvb, B b' /\\ b = singleton g (existT _ RA (exist _ b' Hvb), pp)).\n    intros ?? [? J].\n    rewrite ghost_fmap_singleton in J.\n    destruct (singleton_join_inv_gen _ _ _ _ J) as [Jg _].\n    inv Jg.\n    + destruct (H (core a)) as (b & ? & Hv).\n      { eexists; split; [apply join_comm, core_unit | auto]. }\n      assert (ghost.valid b) as Hvb.\n      { destruct Hv as (? & ? & ?); eapply join_valid; eauto. }\n      exists (singleton g (existT _ RA (exist _ _ Hvb), pp)); split; eauto.\n      rewrite ghost_fmap_singleton.\n      eexists; apply singleton_join_gen.\n      rewrite <- H2; constructor.\n    + destruct a2, a3; inv H3; simpl in *.\n      inv H0; inj_pair_tac.\n      destruct (H b0) as (b & ? & Hv).\n      { eexists; eauto. }\n      destruct Hv as (? & ? & ?).\n      assert (ghost.valid b) as Hvb by (eapply join_valid; eauto).\n      exists (singleton g (existT _ RA (exist _ _ Hvb), pp)); split; eauto.\n      rewrite ghost_fmap_singleton.\n      eexists; apply singleton_join_gen.\n      instantiate (1 := (_, _)).\n      rewrite <- H1; constructor; constructor; [constructor|]; eauto.\n  - apply bupd_mono, exp_left; intro.\n    apply prop_andp_left; intros (b & ? & ? & ?); subst.\n    apply exp_right with b, prop_andp_right; auto.\n    eapply exp_right; auto.\n  Unshelve.\n  auto.\nQed.\n\nLemma ghost_update: forall {RA: Ghost} g (a b: G) pp,\n  fp_update a b -> own g a pp |-- bupd (own g b pp).\nProof.\n  intros; eapply derives_trans.\n  - apply (ghost_update_ND g a (eq b)).\n    intros ? J; destruct (H _ J).\n    do 2 eexists; [constructor | eauto].\n  - apply bupd_mono.\n    apply exp_left; intro; apply prop_andp_left; intro X; inv X; auto.\nQed.\n\nLemma ghost_dealloc: forall {RA: Ghost} g a pp,\n  own g a pp |-- bupd emp.\nProof.\n  intros; unfold own.\n  apply exp_left; intro; apply Own_dealloc.\nQed.\n\nLemma list_set_same : forall {A} n l (a : A), nth n l None = Some a ->\n  list_set l n a = l.\nProof.\n  unfold list_set; induction n; destruct l; simpl; try discriminate; intros; subst; auto.\n  f_equal; eauto.\nQed.\n\n(* The addition of ghost state means that there are rmaps that have only\n   cores for ghost state, but are not cores themselves (since they have ghost\n   state at all). An rmap of this sort is not emp, but is its own unit. *)\n\nDefinition cored: pred rmap := ALL P : pred rmap, ALL Q : pred rmap,\n  P && Q --> P * Q.\n\nProgram Definition is_w w: pred rmap := fun w' => necR w w'.\nNext Obligation.\nProof.\n  repeat intro.\n  eapply necR_trans; eauto.\n  constructor; auto.\nQed.\n\nLemma cored_unit: forall w, cored w = join w w w.\nProof.\n  intro; apply prop_ext; split; unfold cored; intro.\n  - edestruct (H (is_w w) (is_w w)) as (? & ? & J & Hw1 & Hw2).\n    { apply necR_refl. }\n    { split; apply necR_refl. }\n    simpl in *.\n    destruct (join_level _ _ _ J).\n    eapply necR_linear' in Hw1; try apply necR_refl; auto.\n    eapply necR_linear' in Hw2; try apply necR_refl; auto.\n    subst; auto.\n  - intros P Q ?? [HP HQ].\n    exists a', a'; repeat split; auto.\n    eapply nec_join in H as (? & ? & ? & Hw1 & Hw2); eauto.\n    destruct (join_level _ _ _ H).\n    eapply necR_linear' in Hw1; try apply H0; [|lia].\n    eapply necR_linear' in Hw2; try apply H0; [|lia].\n    subst; auto.\nQed.\n\nLemma cored_dup: forall P, P && cored |-- (P && cored) * (P && cored).\nProof.\n  intros.\n  rewrite <- (andp_dup cored) at 1.\n  rewrite <- andp_assoc.\n  intros; unfold cored at 2.\n  eapply modus_ponens.\n  + apply andp_left1, derives_refl.\n  + eapply andp_left2, allp_left, allp_left.\n    rewrite andp_dup; apply derives_refl.\nQed.\n\nLemma cored_core: forall w, cored (core w).\nProof.\n  intro; rewrite cored_unit.\n  apply identity_unit', core_identity.\nQed.\n\nLemma cored_duplicable: cored = cored * cored.\nProof.\n  apply pred_ext.\n  - rewrite <- andp_dup at 1.\n    eapply derives_trans; [apply cored_dup|].\n    apply sepcon_derives; apply andp_left1; auto.\n  - intros ? (? & ? & J & J1 & J2).\n    rewrite cored_unit in *.\n    destruct (join_assoc J1 J) as (? & J' & J1').\n    eapply join_eq in J'; [|apply J]; subst.\n    destruct (join_assoc J2 (join_comm J)) as (? & J' & J2').\n    eapply join_eq in J'; [|apply join_comm, J]; subst.\n    destruct (join_assoc (join_comm J1') (join_comm J2')) as (? & J' & ?).\n    eapply join_eq in J'; [|apply J]; subst; auto.\nQed.\n\nLemma cored_emp: cored |-- bupd emp.\nProof.\n  intro; rewrite cored_unit; intros J ??.\n  exists nil; split; [eexists; constructor|].\n  destruct (make_rmap (resource_at a) nil (level a)) as (m' & ? & Hr & Hg); auto.\n  { intros; extensionality; apply resource_at_approx. }\n  exists m'; repeat split; auto.\n  apply all_resource_at_identity.\n  - intro; rewrite Hr.\n    apply (resource_at_join _ _ _ l) in J.\n    inv J.\n    + apply join_self, identity_share_bot in RJ; subst.\n      apply NO_identity.\n    + apply join_self, identity_share_bot in RJ; subst.\n      contradiction shares.bot_unreadable.\n    + apply PURE_identity.\n  - rewrite Hg, <- (ghost_core nil); apply core_identity.\nQed.\n\nLemma emp_cored : emp |-- cored.\nProof.\n  repeat intro; simpl in *.\n  destruct H1.\n  eapply nec_identity, identity_unit' in H; eauto.\nQed.\n\nLemma join_singleton_inv: forall k a b RA c v pp,\n  join a b (singleton k (existT _ RA (exist _ (core c) v), pp)) ->\n  a = singleton k (existT _ RA (exist _ (core c) v), pp) \\/ b = singleton k (existT _ RA (exist _ (core c) v), pp).\nProof.\n  induction k; unfold singleton; intros; simpl in *.\n  - inv H; auto.\n    assert (m1 = nil /\\ m2 = nil) as [] by (inv H5; auto); subst.\n    inv H4; auto.\n    destruct a0, a3; inv H2; simpl in *.\n    inv H0; inv H.\n    inj_pair_tac.\n    pose proof (core_unit a0) as J.\n    erewrite join_core, core_idem in J by eauto.\n    unfold unit_for in J.\n    eapply join_positivity in J; eauto; subst.\n    left; repeat f_equal; apply proof_irr.\n  - inv H; auto.\n    edestruct IHk as [|]; eauto; [left | right]; f_equal; auto; inv H4; auto.\nQed.\n\nLemma own_cored: forall {RA: Ghost} g a pp, join a a a -> own g a pp |-- cored.\nProof.\n  intros; intros ? (? & ? & Hg).\n  rewrite cored_unit; simpl in *.\n  apply resource_at_join2; auto.\n  - intro; apply identity_unit'.\n    eapply necR_resource_at_identity; eauto.\n  - rewrite Hg, ghost_fmap_singleton.\n    apply singleton_join; repeat constructor; auto.\nQed.\n\nRequire Import VST.veric.tycontext.\nRequire Import VST.veric.Clight_seplog.\n \nLemma own_super_non_expansive: forall {RA: Ghost} n g a pp,\n  approx n (own g a pp) = approx n (own g a (preds_fmap (approx n) (approx n) pp)).\nProof.\n  intros; unfold own.\n  rewrite !approx_exp; f_equal; extensionality v.\n  unfold Own.\n  rewrite !approx_andp; f_equal.\n  apply pred_ext; intros ? [? Hg]; split; auto; simpl in *.\n  - rewrite <- ghost_of_approx, Hg.\n    rewrite !ghost_fmap_singleton, !preds_fmap_fmap.\n    rewrite approx_oo_approx, approx_oo_approx', approx'_oo_approx by lia; auto.\n  - rewrite ghost_fmap_singleton in *.\n    rewrite preds_fmap_fmap in Hg.\n    rewrite approx_oo_approx', approx'_oo_approx in Hg by lia; auto.\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/veric/own.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6584174871563662, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.27818443996627595}}
{"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(********************************************************************)\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 \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 \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 l r t\n    ,  get l se = Some (TRef r t)\n    -> KindT  ke sp       (TRef r t) KData       \n    -> TypeV  ke te se sp (VLoc l)   (TRef r 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 e2\n    -> TypeV  ke te         se sp (VLam t1 x2) (TFun t1 e2 t2)\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 (TBot KEffect)\n    -> TypeV ke          te            se   sp (VLAM k1 x2) (TForall k1 t2)\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 \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 private region. *)\n  | TxPrivate\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 (XPrivate x) tL eL\n\n  (* Extend an existing region. *)\n  | TxExtend\n    :  forall ke te se sp r1 x2 t e eL\n    ,  lowerTT 0 (maskOnVarT 0 e) = Some eL\n    -> KindT ke sp r1 KRegion\n    -> TypeX (ke :> KRegion) (liftTE 0 te) (liftTE 0 se) sp x2 t e\n    -> TypeX ke te se  sp (XExtend r1 x2) (substTT 0 r1 t) (TSum eL (TAlloc r1))\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\nHint Constructors TypeV.\nHint Constructors TypeX.\n\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 _ _ _ _ (XPrivate _)   _ _  |- _ ] => inverts H\n   | [ H: TypeX _ _ _ _ (XExtend  _ _) _ _  |- _ ] => 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": "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/Value/Relation/TyJudge.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.27818089902822424}}
{"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_Ф_constructor6 (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 intInc hmapPush.\n\n(* Check eval_state tvm_address _. *)\n\n(* Locate \"address\". *)\n\nLemma DePoolContract_Ф_constructor6_exec: forall  ( minStake validatorAssurance: Z )\n                                                  ( proxyCode: TvmCell ) \n                                                  ( validatorWallet : Z )\n                                                  ( participantRewardFraction : Z )\n                                                  ( l: Ledger ),\nlet lv := exec_state (↓ ValidatorBase_Ф_Constructor2 validatorWallet) l in \nlet lv := {$ lv With (RoundsBase_ι_m_roundQty, 0) $} in\nlet address := eval_state tvm_address l in \nlet wid := addressWid address in\n    let wid0 := wid =? 0 in\nlet tvm_pubkey := eval_state tvm_pubkey l in\nlet msg_pubkey := eval_state msg_pubkey l in\n    let pubkeys :=  msg_pubkey =? tvm_pubkey in\n    let tvm_pubkey0 := negb (tvm_pubkey =? 0) in\n    let minstake1 := minStake >=? x1_ton in\n    let minStakeValidator := minStake <=? validatorAssurance in\nlet proxy_code_hash := tvm_hash proxyCode in\nlet PROXY_CODE_HASH := DePool_ι_PROXY_CODE_HASH in \n    let proxyCodeSame := proxy_code_hash =? PROXY_CODE_HASH in \n    let validatorStdAddrWithoutAnyCast := isStdAddrWithoutAnyCast validatorWallet in\n   (*  let associationStdAddrWithoutAnyCast := isStdAddrWithoutAnyCast validatorWallet in  *)\n    let participantRewardFraction0 := ( ( participantRewardFraction >? 0 ) && \n                                        ( participantRewardFraction <? 100 ) )%bool in\nlet validatorRewardFraction := 100 - participantRewardFraction in\nlet CRITICAL_THRESHOLD := DePool_ι_CRITICAL_THRESHOLD in\n   (*  let if1 : bool := balanceThreshold >=? CRITICAL_THRESHOLD in *)\nlet balance := eval_state tvm_balance l in \nlet DEPOOL_CONSTRUCTOR_FEE :=  DePoolLib_ι_DEPOOL_CONSTRUCTOR_FEE in\nlet MIN_PROXY_BALANCE := DePoolLib_ι_MIN_PROXY_BALANCE in \nlet PROXY_CONSTRUCTOR_FEE := DePoolLib_ι_PROXY_CONSTRUCTOR_FEE in \n    let balance2 := balance >? CRITICAL_THRESHOLD + DEPOOL_CONSTRUCTOR_FEE + \n                                2 * ( MIN_PROXY_BALANCE + PROXY_CONSTRUCTOR_FEE ) in\n\n    let roundTimeParams := eval_state ConfigParamsBase_Ф_roundTimeParams l in\n    let curValidatorData := eval_state ConfigParamsBase_Ф_getCurValidatorData l in\n    let prevValidatorHash := eval_state ConfigParamsBase_Ф_getPrevValidatorHash l in\n\nlet sender := eval_state (↓ msg_sender) l in\nlet isDepool : bool := ((tvm_pubkey =? tvm_hash (toCell (builder_store default sender 0))) ||\n                       (tvm_pubkey =? tvm_hash (toCell (builder_store default sender 1))))%bool in    \n(*** end of require section ****)\nlet la := exec_state (↓ tvm_accept) lv in    \nlet address := eval_state (↓ tvm_address) la in \n\nlet b0 := builder_store default address 0 in\nlet b1 := builder_store default address 1 in\nlet pk0 := tvm_hash (toCell b0) in\nlet pk1 := tvm_hash (toCell b1) in\nlet data0 := tvm_buildEmptyData pk0 in\nlet data1 := tvm_buildEmptyData pk1 in\nlet stateInit0 := tvm_buildStateInit proxyCode data0 in\nlet stateInit1 := tvm_buildStateInit proxyCode data1 in\nlet m_proxies := eval_state (↑3 ε ProxyBase_ι_m_proxies) l in\nlet (epa0, lp0) := run (↓ tvm_newE DePoolProxyContractD \n                                {|| cmessage_wid ::= $ xInt0 !- $ xInt1 ,\n                                cmessage_value ::= $ DePoolLib_ι_MIN_PROXY_BALANCE !+ $ DePoolLib_ι_PROXY_CONSTRUCTOR_FEE ,\n                                cmessage_stateInit ::= $ stateInit0 ||}\n                                DePoolProxyContract_Ф_constructor5 ) la in\nlet (epa1, lp1) := run (↓ tvm_newE DePoolProxyContractD \n                                {|| cmessage_wid ::= $ xInt0 !- $ xInt1 ,\n                                cmessage_value ::= $ DePoolLib_ι_MIN_PROXY_BALANCE !+ $ DePoolLib_ι_PROXY_CONSTRUCTOR_FEE ,\n                                cmessage_stateInit ::= $ stateInit1 ||}\n                                DePoolProxyContract_Ф_constructor5 ) lp0 in\nlet pa0 := errorMapDefault Datatypes.id epa0 (-1) in\nlet pa1 := errorMapDefault Datatypes.id epa1 (-1) in\nlet lp1' := {$ lp1 With (DePoolContract_ι_m_poolClosed, false); \n                         (DePoolContract_ι_m_minStake, minStake); \n                         (DePoolContract_ι_m_validatorAssurance, validatorAssurance);\n                         (DePoolContract_ι_m_participantRewardFraction, participantRewardFraction);\n                         (DePoolContract_ι_m_validatorRewardFraction, validatorRewardFraction)  ;\n                         (ProxyBase_ι_m_proxies, hmapPush pa1 (hmapPush pa0 m_proxies)  )  $} in\n\nlet (r2, lr2) := run (↓ DePoolContract_Ф_generateRound) lp1' in\nlet (r1, lr1) := run (↓ DePoolContract_Ф_generateRound) lr2 in\nlet (r0, lr0) := run (↓ DePoolContract_Ф_generateRound) lr1 in\nlet (rpre0, lrpre0) := run (↓ DePoolContract_Ф_generateRound) lr0 in\n\nlet now := eval_state (↓ tvm_now) lrpre0 in\nlet validationEnd := errorMapDefaultF snd curValidatorData (fun _ => 0) in\nlet electionsStartBefore := errorMapDefaultF snd roundTimeParams (fun _ => 0) in\nlet areElectionsStarted := now >=? validationEnd - electionsStartBefore  in \nlet vhash := if areElectionsStarted then  (errorMapDefaultF (fst ∘ fst) curValidatorData (fun _ => 0)) else (errorMapDefaultF Datatypes.id prevValidatorHash (fun _ => 0)) in\n\n\nlet r0 := {$ r0 with (RoundsBase_ι_Round_ι_step, RoundsBase_ι_RoundStepP_ι_Pooling) $} in\nlet r2 := {$ r2 with (RoundsBase_ι_Round_ι_step, RoundsBase_ι_RoundStepP_ι_Completed);\n                     (RoundsBase_ι_Round_ι_completionReason, RoundsBase_ι_CompletionReasonP_ι_FakeRound);\n                     (RoundsBase_ι_Round_ι_unfreeze, 0)  $} in\nlet r1 := {$ r1 with (RoundsBase_ι_Round_ι_step, RoundsBase_ι_RoundStepP_ι_WaitingUnfreeze);\n                     (RoundsBase_ι_Round_ι_completionReason, RoundsBase_ι_CompletionReasonP_ι_FakeRound);\n                     (RoundsBase_ι_Round_ι_unfreeze, 0);\n                     (RoundsBase_ι_Round_ι_vsetHashInElectionPhase, vhash)  $} in \n                  \nlet lsetPre0 := exec_state (↓ RoundsBase_Ф_setRound (rpre0 ->> RoundsBase_ι_Round_ι_id) rpre0) lrpre0 in\nlet lset0 := exec_state (↓ RoundsBase_Ф_setRound (r0 ->> RoundsBase_ι_Round_ι_id) r0) lsetPre0 in\nlet lset1 := exec_state (↓ RoundsBase_Ф_setRound (r1 ->> RoundsBase_ι_Round_ι_id) r1) lset0 in\nlet lset2 := exec_state (↓ RoundsBase_Ф_setRound (r2 ->> RoundsBase_ι_Round_ι_id) r2) lset1 in\n                        \nexec_state (↓ DePoolContract_Ф_Constructor6 minStake validatorAssurance \n                                          proxyCode validatorWallet \n                                          participantRewardFraction) l = \nif (wid0) then \n    if (pubkeys) then \n        if (tvm_pubkey0) then  \n            if (minstake1) then \n                if (minStakeValidator) then  \n                    if (proxyCodeSame) then \n                        if (validatorStdAddrWithoutAnyCast) then\n                            if (participantRewardFraction0) then \n                                if (balance2) then \n                                    if isDepool then\n                                         if (errorValueIsValue roundTimeParams) then \n                                            if (errorValueIsValue curValidatorData) then \n                                                if (errorValueIsValue prevValidatorHash) then  lset2\n                                                 else lp1'\n                                            else lp1'\n                                        else lp1'     \n                                    else la\n                                else lv \n                            else lv\n                        else lv\n                    else lv\n                else lv\n            else lv\n        else lv\n    else lv\nelse lv. \n\nProof.\n    intros.\n    destructLedger l. \n    compute.\n\n    repeat rewrite letIf.  idtac.\n    repeat rewrite matchIf.  idtac.\n    repeat rewrite letIf.  idtac.\n    repeat rewrite matchIf.  idtac.\n    repeat rewrite letIf.  idtac. \n\n    all: repeat destructIf_solve2. (* idtac. *)\n    \n    (* idtac.*)\n\n   (* Require Import depoolContract.Lib.CommonStateProofs.\n    all: apply ledgerEq; auto. idtac.\n    simpl.\n\n    apply RoundsBaseEq; auto. idtac.\n    simpl. idtac.\n\n    all: try congruence. *)\n\nQed.\n\nLemma DePoolContract_Ф_constructor6_eval: forall  ( minStake validatorAssurance: Z )\n                                                  ( proxyCode: TvmCell ) \n                                                  ( validatorWallet : Z )\n                                                  ( participantRewardFraction : Z )\n                                                  ( l: Ledger ),\nlet address := eval_state tvm_address l in\nlet wid := addressWid address in\n    let wid0 := wid =? 0 in\nlet tvm_pubkey := eval_state tvm_pubkey l in\nlet msg_pubkey := eval_state msg_pubkey l in\n    let pubkeys :=  msg_pubkey =? tvm_pubkey in\n    let tvm_pubkey0 := negb (tvm_pubkey =? 0) in\n    let minstake1 := minStake >=? x1_ton in\n    let minStakeValidator := minStake <=? validatorAssurance in\nlet proxy_code_hash := tvm_hash proxyCode in\nlet PROXY_CODE_HASH :=  DePool_ι_PROXY_CODE_HASH in\n    let proxyCodeSame := proxy_code_hash =? PROXY_CODE_HASH in \n    let validatorStdAddrWithoutAnyCast := isStdAddrWithoutAnyCast validatorWallet in\n   (*  let associationStdAddrWithoutAnyCast := isStdAddrWithoutAnyCast validatorWallet in  *)\n    let participantRewardFraction0 := ( ( participantRewardFraction >? 0 ) && \n                                        ( participantRewardFraction <? 100 ) )%bool in\nlet validatorRewardFraction := 100 - participantRewardFraction in\nlet CRITICAL_THRESHOLD :=  DePool_ι_CRITICAL_THRESHOLD  in\n   (*  let if1 : bool := balanceThreshold >=? CRITICAL_THRESHOLD in *)\nlet balance := eval_state tvm_balance l in \nlet DEPOOL_CONSTRUCTOR_FEE := DePoolLib_ι_DEPOOL_CONSTRUCTOR_FEE  in\nlet MIN_PROXY_BALANCE :=  DePoolLib_ι_MIN_PROXY_BALANCE in \nlet PROXY_CONSTRUCTOR_FEE :=  DePoolLib_ι_PROXY_CONSTRUCTOR_FEE in \n    let balance2 := balance >? CRITICAL_THRESHOLD + DEPOOL_CONSTRUCTOR_FEE + \n                                2 * ( MIN_PROXY_BALANCE + PROXY_CONSTRUCTOR_FEE ) in\n\n    let roundTimeParams := eval_state ConfigParamsBase_Ф_roundTimeParams l in\n    let curValidatorData := eval_state ConfigParamsBase_Ф_getCurValidatorData l in\n    let prevValidatorHash := eval_state ConfigParamsBase_Ф_getPrevValidatorHash l in\n\nlet sender := eval_state (↓ msg_sender) l in\nlet isDepool : bool := ((tvm_pubkey =? tvm_hash (toCell (builder_store default sender 0))) ||\n                       (tvm_pubkey =? tvm_hash (toCell (builder_store default sender 1))))%bool in    \n\neval_state (↓ DePoolContract_Ф_Constructor6 minStake validatorAssurance \n                                          proxyCode validatorWallet \n                                          participantRewardFraction) l = \n\nif (wid0) then \n    if (pubkeys) then \n        if (tvm_pubkey0) then  \n            if (minstake1) then \n                if (minStakeValidator) then  \n                    if (proxyCodeSame) then \n                        if (validatorStdAddrWithoutAnyCast) then                          \n                            if (participantRewardFraction0) then \n                                if (balance2) then \n                                    if isDepool then\n                                        if (errorValueIsValue roundTimeParams) then \n                                            if (errorValueIsValue curValidatorData) then \n                                                if (errorValueIsValue prevValidatorHash) then Value I\n                                                else errorMapDefaultF (fun _ => Value I) prevValidatorHash (fun er => Error er)\n                                            else errorMapDefaultF (fun _ => Value I) curValidatorData (fun er => Error er) \n                                        else errorMapDefaultF (fun _ => Value I) roundTimeParams (fun er => Error er)      \n                                    else Error (eval_state (↑ε10 DePoolProxyContract_ι_ERROR_IS_NOT_DEPOOL) l)                    \n                                else Error (eval_state (↑ε7 Errors_ι_BAD_ACCOUNT_BALANCE) l )                               \n                            else Error (eval_state (↑ε7 Errors_ι_BAD_PART_REWARD) l)\n                        else Error (eval_state (↑ε7 Errors_ι_VALIDATOR_IS_NOT_STD) l)                         \n                    else Error (eval_state (↑ε7 Errors_ι_BAD_PROXY_CODE) l) \n                else Error (eval_state (↑ε7 Errors_ι_BAD_STAKES) l)   \n            else Error (eval_state (↑ε7 Errors_ι_BAD_STAKES) l)   \n        else Error (eval_state (↑ε7 Errors_ι_CONSTRUCTOR_NO_PUBKEY) l)       \n    else Error (eval_state (↑ε7 Errors_ι_IS_NOT_OWNER) l)    \nelse  Error (eval_state (↑ε7 Errors_ι_NOT_WORKCHAIN0) l) . \n\nProof.\n    intros.\n    destructLedger l. \n    compute.\n  \n    Time repeat destructIf_solve. idtac.\n\n    all: try congruence.\n\nQed.\n\n\nEnd DePoolContract_Ф_constructor6.", "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_constructor6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.27817431947707244}}
{"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\nRequire Import AdjustCWP.\n\nOpen Scope nat.\nOpen Scope code_scope.\nOpen Scope mem_scope.\n\nTheorem Ta0StartAdjustCWPProof :\n  forall vl,\n    spec |- {{ ta0_start_adjust_cwp_pre vl }}\n             ta0_start_adjust_cwp\n           {{ ta0_start_adjust_cwp_post vl }}.\nProof.\n  intros.\n  unfold ta0_start_adjust_cwp_pre.\n  unfold ta0_start_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, x'12 to vz, x'13 to vn.\n  renames x'7 to ll, x'8 to ct, x'9 to nt, x'10 to nctx, x'11 to nstk.\n  eapply Pure_intro_rule.\n  introv Hlglv.\n  hoare_lift_pre 13.\n  eapply Pure_intro_rule.\n  introv Hnctx.\n  hoare_lift_pre 13.\n  eapply Pure_intro_rule.\n  introv Hct.\n  unfold ta0_start_adjust_cwp.\n\n  eapply backward_rule.\n  introv Hs.\n  simpl_sep_liftn_in Hs 2.\n  eapply Regs_Global_combine_GenRegs in Hs; eauto.\n  destruct fmg, fmo, fml, fmi.\n  \n  (** getcwp g4 *)\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply getcwp_rule_reg_fm; eauto.\n  simpl upd_genreg.\n\n  (** rd wim g7 *)\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply rd_rule_reg_wim; eauto.\n  simpl upd_genreg.\n\n  (** set 1 g6 *)\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply set_rule_reg; eauto.\n  simpl upd_genreg.\n\n  (** sll g6 g4 g4 *)\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply sll_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.\n    destruct Hs; eauto.\n  }\n\n  eapply Pure_intro_rule.\n  introv Hid_inrange.\n  destruct Hid_inrange as [Hid_inrange Hvi_inrange].\n  rewrite get_range_0_4_stable; eauto.\n\n  eapply Seq_conseq_rule.\n  eapply Ta0AdjustCWPProof; eauto.\n  introv Hs.\n  unfold ta0_adjust_cwp_pre.\n  sep_ex_intro.\n  eapply sep_pure_l_intro; eauto.\n  simpl_sep_liftn 2.\n  eapply GenRegs_split_Regs_Global; eauto.\n  do 11 sep_cancel1 1 1.\n  instantiate (1 := Aemp).\n  eapply astar_emp_intro_r; eauto.\n  simpl get_frame_nth.\n  eapply sep_pure_l_intro; eauto.\n  split; eauto.\n  instantiate (1 := id).\n  split; eauto.\n  eapply rotate_end; eauto.\n  simpl; eauto.\n\n  introv Hs.\n  unfold ta0_adjust_cwp_post in Hs.\n  eauto.\nQed.\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/StartAdjustCWP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.629774621301746, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2781544498816435}}
{"text": "Set Implicit Arguments.\n\nRequire Import ADT.\n\nModule Make (Import E : ADT).\n\n  Require Import Inv.\n  Module Import InvMake := Make E.\n  Import Semantics.\n  Import SemanticsMake.\n  Require Import WordMap.\n  Require Import FMapFacts.\n  Module Properties := Properties WordMap.\n  Module Facts := Facts WordMap.\n\n  Lemma make_triples_Word : forall pairs outs, length outs = length pairs -> map (@Word _) (make_triples pairs outs) = map fst pairs.\n    induction pairs; destruct outs; simpl; intuition.\n    f_equal; auto.\n  Qed.\n\n  Lemma make_triples_Word_ADTIn : forall pairs outs, length outs = length pairs -> map (fun x => (Word x, ADTIn x)) (make_triples pairs outs) = pairs.\n    induction pairs; destruct outs; simpl; intuition.\n    f_equal; auto.\n  Qed.\n\n  Lemma make_triples_ADTIn : forall pairs outs, length outs = length pairs -> map (@ADTIn _) (make_triples pairs outs) = map snd pairs.\n    induction pairs; destruct outs; simpl; intuition.\n    f_equal; auto.\n  Qed.\n\n  Lemma make_triples_length : forall pairs outs, length outs = length pairs -> length (make_triples pairs outs) = length pairs.\n    induction pairs; destruct outs; simpl; intuition.\n  Qed.\n\n  Import WordMap.\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 Properties.F.In_m; eauto.\n  Qed.\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 s; auto.\n    erewrite <- Facts.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 Properties.F.add_m; auto.\n    apply Properties.F.remove_m; auto.\n  Qed.\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 heap_upd_option, Semantics.heap_upd_option; intros.\n    destruct b; auto.\n    apply Properties.F.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  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 Properties.F.Equal_sym; auto.\n    apply Properties.F.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 Properties.F.Equal_sym; auto.\n    apply Properties.F.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  Require Import RepInv.\n\n  Module Make(R : RepInv E).\n    Module Import Inner := InvMake.Make(R).\n\n    Require Import LayoutHintsUtil.\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  End Make.\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 store_out, Semantics.store_out; intros.\n    destruct a; simpl in *.\n    destruct ADTIn; auto.\n    destruct ADTOut; auto.\n    apply Properties.F.add_mapsto_iff;\n      apply Properties.F.add_mapsto_iff in H1; intuition subst.\n    eauto.\n\n    apply Properties.F.remove_mapsto_iff;\n      apply Properties.F.remove_mapsto_iff in H1; intuition subst.\n    eauto.\n  Qed.\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, inr v) ls.\n    induction ls; simpl; intuition.\n    apply IHls in H; intuition.\n    unfold store_pair in H0; simpl in H0.\n    destruct b; simpl in *; auto.\n    apply Properties.F.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, inr v) ls)\n    -> WordMap.In k (fold_left store_pair ls h).\n    induction ls; simpl; intuition.\n    firstorder.\n    destruct H0; intuition.\n    eauto.\n    eapply IHls.\n    unfold store_pair; simpl.\n    unfold heap_upd; simpl.\n    left.\n    apply Properties.F.add_in_iff.\n    auto.\n    destruct H0; intuition.\n    injection H0; clear H0; intros; subst.\n    apply IHls.\n    unfold store_pair; simpl.\n    unfold heap_upd; simpl.\n    left.\n    apply Properties.F.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, inr v) ls).\n    induction ls; simpl; intuition.\n    apply IHls in H; clear IHls; intuition.\n    unfold store_pair in H0; simpl in H0.\n    destruct b; simpl; auto.\n    unfold heap_upd in H0; simpl in H0.\n    apply Properties.F.add_in_iff in H0; intuition subst.\n    eauto.\n    destruct H0.\n    eauto.\n  Qed.\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 := inr a; ADTOut := o |} ls)\n    \\/ exists a, List.In {| Word := k; ADTIn := inr a; ADTOut := Some v |} ls.\n    induction ls; simpl; intuition.\n    apply IHls in H; intuition.\n\n    unfold store_out, 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 Properties.F.add_mapsto_iff in H; intuition subst.\n    eauto.\n    left; intuition.\n    eauto 2.\n    apply Properties.F.remove_mapsto_iff in H; intuition subst.\n    left; intuition.\n    eauto 2.\n    destruct H0.\n    eauto.\n  Qed.\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 (heap_merge (heap_diff h h1) (fold_left store_out triples h1))\n      (fold_left store_out triples h).\n    simpl; intros.\n    unfold heap_merge, heap_diff.\n    apply Properties.F.Equal_mapsto_iff; intuition.\n\n    apply Properties.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 Properties.F.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 Properties.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, inr a) pairs.\n      induction pairs; simpl; intuition.\n      apply IHpairs in H; intuition.\n      unfold store_pair in H0; simpl in H0.\n      destruct b; auto.\n      unfold heap_upd in H0.\n      apply Properties.F.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, inr a) pairs.\n      intros.\n      apply In_make_heap' in H; intuition eauto.\n      apply Properties.F.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 store_out, Semantics.store_out; simpl.\n      destruct a; simpl in *.\n      destruct a; auto.\n      destruct a0.\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 Properties.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 := inr 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 := inr x; ADTOut := Some e |})).\n      unfold store_out, Semantics.store_out; simpl.\n      apply WordMap.add_1; auto.\n      generalize dependent (store_out h {| Word := k; ADTIn := inr x; ADTOut := Some e |}).\n      assert (forall v, ~List.In (k, inr 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, @inr W _ 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 store_out, Semantics.store_out; simpl.\n      destruct a; simpl in *.\n      destruct a; auto.\n      destruct a0.\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 Properties.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 := inr 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 store_out, Semantics.store_out; simpl.\n      destruct b; auto.\n      destruct a0; 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, inr x) pairs\n      -> Semantics.disjoint_ptrs pairs\n      -> WordMap.MapsTo k x (fold_left store_pair pairs h).\n      induction pairs; simpl; 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, inr x))).\n      unfold store_pair; simpl.\n      apply WordMap.add_1; auto.\n      generalize dependent (store_pair h (k, inr x)).\n      induction pairs; simpl in *; intuition.\n      simpl in *; intuition subst.\n      apply IHpairs.\n      unfold 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 Properties.update_mapsto_iff; right; intuition.\n    apply Properties.diff_mapsto_iff; intuition.\n    apply Properties.F.not_mem_in_iff in H3; tauto.\n    assert (~WordMap.In k (make_heap pairs)).\n    intro.\n    apply Properties.F.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 := inr 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 store_out, Semantics.store_out in H0.\n      destruct a; simpl in *.\n      destruct ADTIn; auto.\n      destruct ADTOut.\n      apply Properties.F.add_in_iff in H0; intuition subst.\n      exfalso; eauto.\n      apply Properties.F.remove_in_iff in H0; intuition subst.\n    Qed.\n\n    eapply i_didn't_do_it; eauto.\n  Qed.\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/InvFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.27815444374356685}}
{"text": "From mathcomp Require Import\n     all_ssreflect.\n\nFrom PoS_NSB Require Import\n     Parameters.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** * Blocks\n    This file contain the basic record representing a block. \n**)\nRecord Block :=\n  MkBlock\n    { sl : Slot\n    ; pred : Hash\n    ; bid : Party }.\n\n(* Type synononym for blocks *)\nDefinition Chain := seq Block.\nDefinition Chains := seq Chain.\nDefinition BlockPool := seq Block.\n\n(* Decidable equality for Blocks *)\nDefinition eq_block (b b' : Block) :=\n  match b, b' with\n  | MkBlock sl pt bid, MkBlock sl' pt' bid' =>\n    [&& sl == sl', pt == pt' & bid == bid']\n  end.\n\nLemma eq_blockP : Equality.axiom eq_block.\nProof.\n  case => sl pt bid; case => sl' pt' bid' .\n  rewrite /eq_block.\n  do ! (case: _ /eqP; [move => -> |by constructor; case]).\n  by constructor.\nQed.\n\n(* Canonial structures for block *)\nCanonical Block_eqMixin := Eval hnf in EqMixin eq_blockP.\nCanonical Block_eqType := Eval hnf in EqType Block Block_eqMixin.\n\n(** Parameters for block *)\nParameter GenesisBlock : Block.\nParameter HashB : Block -> Hash.\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/Protocol/Blocks.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2781544437435668}}
{"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 recKind_valid : recKind_obligation.\n unfoldtop. autounfold with valid_hint.\n  intros G i k triv0 triv1 H0 H1.\n  valid_rewrite. \n  constructor.\n  assert (equivctx (hyp_tml (app Defs.kind i) :: G)\n                    (hyp_tml (kuniv i) :: G)) as Hctx.\n  {constructor. apply def_kindh_l. apply equivctx_refl. } \n  rewrite -> def_kind in * |- *.\n  apply tr_rec_kind_formation; eauto using deq_intro.\n  Qed.\n\nLemma recKindEq_valid : recKindEq_obligation.\n unfoldtop. autounfold with valid_hint.\n  intros G i k l triv0 triv1 H0 H1.\n  valid_rewrite. \n  constructor.\n  assert (equivctx (hyp_tml (app Defs.kind i) :: G)\n                    (hyp_tml (kuniv i) :: G)) as Hctx.\n  {constructor. apply def_kindh_l. apply equivctx_refl. } \n  rewrite -> def_kind in * |- *.\n  apply tr_rec_kind_formation; eauto using deq_intro.\nQed.\n\nLemma recForm_valid : recForm_obligation. \n unfoldtop. autounfold with valid_hint.\n  intros G a triv0 H.\n  valid_rewrite. \n  constructor.\n  eauto using deqtype_intro.\nQed.\n\n Lemma recEq_valid : recEq_obligation.\n unfoldtop. autounfold with valid_hint.\n  intros G a b triv0 H.\n  valid_rewrite. \n  constructor.\n  eauto using deqtype_intro.\n Qed.\n\nLemma recFormUniv_valid : recFormUniv_obligation. \n unfoldtop. autounfold with valid_hint.\n  intros G a i triv0 triv1 H0 H1.\n  valid_rewrite. \n  assert (equivctx (hyp_tml (app Defs.univ i) :: G)\n                    (hyp_tml (univ i) :: G)) as Hctx.\n  {constructor. apply def_univh_l. apply equivctx_refl. } \n  rewrite -> def_univ in * |- *.\n  constructor.\n  apply tr_rec_formation_univ; eauto using deq_intro.\n  Qed.\n\n  Lemma recEqUniv_valid : recEqUniv_obligation.\n unfoldtop. autounfold with valid_hint.\n  intros G a b i triv0 triv1 H0 H1.\n  valid_rewrite. \n  assert (equivctx (hyp_tml (app Defs.univ i) :: G)\n                    (hyp_tml (univ i) :: G)) as Hctx.\n  {constructor. apply def_univh_l. apply equivctx_refl. } \n  rewrite -> def_univ in * |- *.\n  constructor.\n  apply tr_rec_formation_univ; eauto using deq_intro.\nQed.\n\n\nLemma recUnroll_valid : recUnroll_obligation. \n unfoldtop. autounfold with valid_hint.\n intros G a triv0 H.\n valid_rewrite.\n apply tr_rec_unroll.\n eauto using deqtype_intro.\nQed.\n\nLemma recBisimilar_valid : recBisimilar_obligation.\n unfoldtop. autounfold with valid_hint.\n intros G a b triv0 triv1 H0.\n valid_rewrite. \n constructor; eauto using deqtype_intro.\nQed.\n\n\nHint Rewrite def_rec : prepare.\n\n\nLemma recUnrollUniv_valid : recUnrollUniv_obligation.\nProof.\nprepare.\nintros G a i ext1 ext0 Hi Ha.\napply tr_rec_unroll_univ; 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/ValidationRec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2781544376054901}}
{"text": "Require Import\n        Fiat.Computation\n        Fiat.Common.DecideableEnsembles\n        Fiat.Narcissus.Common.Specs\n        Fiat.Narcissus.Common.ComposeOpt\n        Fiat.Narcissus.Common.Notations\n        Fiat.Narcissus.Formats.Base.FMapFormat\n        Fiat.Narcissus.Formats.Base.LaxTerminalFormat.\n\nSection SequenceFormat.\n\n  Context {T : Type}. (* Target Type *)\n  Context {cache : Cache}. (* State Type *)\n  Context {monoid : Monoid T}. (* Target type is a monoid. *)\n\n  Definition sequence_Format\n             {S : Type}\n             (format1 format2 : FormatM S T)\n    := (fun s => compose _ (format1 s) (format2 s))%comp.\n\n  Definition sequence_Decode\n             {S S' T : Type}\n             {cache : Cache}\n             (decode1 : DecodeM (S' * T) T)\n             (decode2 : S' -> DecodeM (S * T) T)\n    : DecodeM (S * T) T :=\n    fun t env =>\n      `(s', t', env') <- decode1 t env;\n        decode2 s' t' env'.\n\n  Definition sequence_Decode'\n             {S S' : Type}\n             (decode1 : DecodeM (S' * T) T)\n             (decode2 : S' -> DecodeM (S * T) T)\n    : DecodeM (S' * S * T) T :=\n      fun t env =>\n      `(s', t', env') <- decode1 t env;\n      `(s, t', env'') <- decode2 s' t' env';\n      Ok ((s', s), t', env'').\n\n  Definition sequence_Encode\n             {S : Type}\n             (encode1 encode2 : EncodeM S T)\n    := (fun s env =>\n          `(t1, env') <- encode1 s env ;\n          `(t2, env'') <- encode2 s env';\n          Ok (mappend t1 t2, env'')).\n\n  Notation \"x ++ y\" := (sequence_Format x y) : format_scope .\n\n  Lemma CorrectEncoder_sequence\n        {S : Type}\n        (format1 format2 : FormatM S T)\n        (encode1 encode2 : EncodeM S T)\n        (encode1_correct : CorrectEncoder format1 encode1)\n        (encode1_consistent : (* If the first format produces *some*\n                                 environment that makes the second format\n                                 (and thus the composite format) non-empty,\n                                 the encoder must also produce an environment\n                                 that makes the second format non-empty. *)\n           forall s env tenv' tenv'',\n             format1 s env ∋ tenv'\n             -> format2 s (snd tenv') ∋ tenv''\n             -> exists tenv3 tenv4,\n                 encode1 s env = Ok tenv3\n                 /\\ format2 s (snd tenv3) ∋ tenv4)\n        (encode2_correct : CorrectEncoder format2 encode2)\n    : CorrectEncoder (format1 ++ format2)\n                     (sequence_Encode encode1 encode2).\n  Proof.\n    unfold CorrectEncoder, sequence_Encode, sequence_Format, compose,\n    DecodeBindOpt, BindOpt in *; intuition; intros.\n    - destruct (encode1 a env) as [ [t1 xxenv] | ] eqn: ? ;\n        simpl in *; try discriminate.\n      destruct (encode2 a xxenv) as [ [t2 xxxenv] | ] eqn: ? ;\n        simpl in *; try discriminate; injections.\n      repeat computes_to_econstructor; eauto.\n    -  unfold Bind2 in *; computes_to_inv; destruct v;\n         destruct v0; simpl in *.\n       destruct (encode1 a env) as [ [t1 xxenv] | ] eqn: ? ;\n         simpl in *.\n       2: { eapply H0; eauto. rewrite Heqh. constructor. }\n       eapply H2; try eassumption.\n       destruct (encode2 a xxenv) as [ [t2' xxxenv] | ] eqn: ? ;\n         simpl in *; injections.\n       + inversion H3.\n       + specialize (encode1_consistent _ _ _ _ H4 H4');\n           destruct_ex; split_and.\n         rewrite H6 in Heqh; injections; simpl in *.\n         destruct x0; elimtype False.\n         eapply H2.\n         rewrite Heqh0; constructor.\n         eassumption.\n  Qed.\n\n  Lemma Sequence_decode_correct\n        {S V1 V2 : Type}\n        {P : CacheDecode -> Prop}\n        {P_inv1 P_inv2 : (CacheDecode -> Prop) -> Prop}\n        (P_inv_pf : cache_inv_Property P (fun P => P_inv1 P /\\ P_inv2 P))\n        (view1 : S -> V1 -> Prop)\n        (view2 : V1 -> S -> V2 -> Prop)\n        (Source_Predicate : S -> Prop)\n        (View_Predicate2 : V1 -> V2 -> Prop)\n        (View_Predicate1 : V1 -> Prop)\n        (consistency_predicate : V1 -> S -> Prop)\n        (format1 format2 : FormatM S T )\n        (decode1 : DecodeM (V1 * T) T)\n        (view_format1 : FormatM V1 T)\n      (*consistency_predicate_refl :\n         forall a, consistency_predicate (proj' a) (proj a))\n      (proj_predicate_OK :\n         forall s, predicate (proj s)\n                   -> proj_predicate (proj' s) *)\n      (decode1_pf :\n         cache_inv_Property P P_inv1\n         -> CorrectDecoder monoid Source_Predicate View_Predicate1 view1 format1 decode1 P view_format1)\n      (*pred_pf : forall s, predicate s -> predicate' s *)\n      (consistency_predicate_OK :\n         forall s v1 t1 t2 env xenv xenv',\n           computes_to (format1 s env) (t1, xenv)\n           -> computes_to (view_format1 v1 env) (t2, xenv')\n           -> view1 s v1\n           -> consistency_predicate v1 s)\n\n      (decode2 : V1 -> DecodeM (V2 * T) T)\n      (view_format2 : V1 -> FormatM V2 T)\n      (view_format3 : FormatM (V1 * V2) T)\n      (decode2_pf : forall v1 : V1,\n          cache_inv_Property P P_inv2 ->\n          View_Predicate1 v1 ->\n          CorrectDecoder monoid (fun s => Source_Predicate s\n                                          /\\ consistency_predicate v1 s)\n                         (View_Predicate2 v1) (view2 v1) format2 (decode2 v1) P (view_format2 v1))\n      (view_format3_OK : forall v1 t1 env1 xenv1 v2 t2 xenv2,\n          view_format1 v1 env1 (t1, xenv1)\n          -> view_format2 v1 v2 xenv1 (t2, xenv2)\n          -> View_Predicate1 v1\n          -> view_format3 (v1, v2) env1 (mappend t1 t2, xenv2))\n    : CorrectDecoder\n      monoid\n      Source_Predicate\n      (fun v1v2 => View_Predicate1 (fst v1v2) /\\ View_Predicate2 (fst v1v2) (snd v1v2))\n      (fun s v1v2 => view1 s (fst v1v2) /\\ view2 (fst v1v2) s (snd v1v2))\n      (format1 ++ format2)\n      (sequence_Decode' decode1 decode2) P\n      view_format3.\nProof.\n  unfold cache_inv_Property, sequence_Decode, sequence_Format, compose in *;\n    split.\n  { intros env env' xenv s t ext ? env_pm pred_pm com_pf.\n    unfold compose, Bind2 in com_pf; computes_to_inv; destruct v;\n      destruct v0.\n    destruct (fun H => proj1 (decode1_pf (proj1 P_inv_pf)) _ _ _ _ _ (mappend t1 ext) env_OK env_pm H com_pf); eauto; destruct_ex; split_and; simpl in *; injections; eauto.\n    unfold sequence_Decode', DecodeBindOpt2, BindOpt.\n    setoid_rewrite <- mappend_assoc; rewrite H0.\n    pose proof (proj2 (decode1_pf H3) _ _ _ _ _ _ env_pm env_OK H0);\n      split_and; destruct_ex; split_and.\n    destruct (fun H => proj1 (decode2_pf x H5 H9)\n                             _ _ _ _ _ ext H4 H2 H com_pf').\n    split; try eassumption.\n    eauto.\n    destruct_ex; split_and.\n    simpl.\n    rewrite H12; eexists _, _; simpl; intuition eauto.\n    apply unfold_computes.\n    rewrite unfold_computes in H1.\n    eapply view_format3_OK; eauto.\n  }\n  { intros ? ? ? ? t; intros.\n    unfold sequence_Decode', DecodeBindOpt2, BindOpt in H1.\n    destruct (decode1 t env') as [ [ [? ?] ? ] | ] eqn : ? ;\n      simpl in *; try discriminate.\n    generalize Heqh; intros Heqh'.\n    eapply (proj2 (decode1_pf (proj1 P_inv_pf))) in Heqh; eauto.\n    split_and; destruct_ex; split_and.\n    subst.\n    destruct (decode2 v0 t0 c) as [ [ [? ?] ? ] | ] eqn : ? ;\n      simpl in *; try discriminate; injections.\n    eapply (proj2 (decode2_pf _ H5 H7)) in Heqh; eauto.\n    destruct Heqh as [? ?]; destruct_ex; split_and; subst.\n    setoid_rewrite mappend_assoc.\n    split; eauto.\n    eexists _, _; repeat split; eauto.\n    apply unfold_computes.\n    eapply view_format3_OK; try eassumption.\n    apply unfold_computes; eassumption.\n    apply unfold_computes; eassumption.\n  }\nQed.\n\nEnd SequenceFormat.\n\nNotation \"x ++ y\" := (sequence_Format x y) : format_scope .\n", "meta": {"author": "scuellar", "repo": "narcissus_errors", "sha": "8c547389030165e8620b43bb38ad87b9b65e5471", "save_path": "github-repos/coq/scuellar-narcissus_errors", "path": "github-repos/coq/scuellar-narcissus_errors/narcissus_errors-8c547389030165e8620b43bb38ad87b9b65e5471/src/Narcissus/Formats/Base/SequenceFormat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804478040617, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.27807537559395096}}
{"text": "Require Import floyd.proofauto.\n\nImport ListNotations.\nRequire sha.sha.\nRequire sha.SHA256.\nLocal Open Scope logic.\n\nRequire Import sha.spec_sha.\nRequire Import sha.HMAC_functional_prog.\nRequire Import sha.HMAC_refined_fp.\n\nRequire Import sha.hmac_sha256.\n\nRequire Import HMAC_definitions.\nRequire Import HMAC_lemmas.\n\nLemma loopbodyLE: forall Espec \n(A : ARGS)\n(a : HMAC_Refined.Args)\n(KV : val)\n(text' : name _text)\n(key' : name _key)\n(digest' : name _digest)\n(textlen' : name _text_len)\n(keylen' : name _key_len)\n(VALS : VALUES)\n(isByteKey : Forall isbyteZ (key a))\n(i : Z)\n(Delta := func_tycontext f_hmac_sha256 Vprog Gtot)\n(H : 0 <= i < 64),\n@semax Espec  (initialized _i Delta)\n  (PROP  ()\n   LOCAL  (`(eq (Vint (Int.repr i))) (eval_id _i);\n   `(eq (Vint (Int.repr 64))) (eval_expr (Econst_int (Int.repr 64) tint));\n   `(eq (TEXT A)) (eval_id _text); `(eq (KEY A)) (eval_id _key);\n   `(eq KV) (eval_var sha._K256 (tarray tuint 64));\n   `(eq (TEXTLEN A)) (eval_id _text_len);\n   `(eq (KEYLEN A)) (eval_id _key_len); `(eq (DIGEST A)) (eval_id _digest);\n   `(eq (k_ipad VALS)) (eval_var _k_ipad (tarray tuchar 65));\n   `(eq (k_opad VALS)) (eval_var _k_opad (tarray tuchar 65));\n   `(eq (tk VALS)) (eval_var _tk (tarray tuchar 32));\n   `(eq (tk2 VALS)) (eval_var _tk2 (tarray tuchar 32));\n   `(eq (bufferIn VALS)) (eval_var _bufferIn (tarray tuchar 1024));\n   `(eq (bufferOut VALS)) (eval_var _bufferOut (tarray tuchar 1024)))\n   SEP \n   (`(array_at tuchar Tsh\n        (cVint\n           (force_int\n            oo ZnthV tuchar\n                 (map Vint\n                    (map Int.repr\n                       (map Byte.unsigned\n                          (map Byte.repr (HMAC_FUN.mkKey (key a)))))))) i 64\n        (k_opad VALS));\n   `(array_at tuchar Tsh\n       (cVint\n          (force_int\n           oo ZnthV tuchar\n                (map Vint\n                   (map Int.repr\n                      (map Byte.unsigned\n                         (map Byte.repr (HMAC_FUN.mkKey (key a)))))))) i 64\n       (k_ipad VALS));\n   `(array_at tuchar Tsh\n       (cVint\n          (force_int\n           oo ZnthV tuchar\n                (map Vint\n                   (map Int.repr\n                      (map Byte.unsigned\n                         (HMAC_FUN.mkArg\n                            (map Byte.repr (HMAC_FUN.mkKey (key a))) Opad))))))\n       0 i (k_opad VALS));\n   `(array_at tuchar Tsh\n       (cVint\n          (force_int\n           oo ZnthV tuchar\n                (map Vint\n                   (map Int.repr\n                      (map Byte.unsigned\n                         (HMAC_FUN.mkArg\n                            (map Byte.repr (HMAC_FUN.mkKey (key a))) Ipad))))))\n       0 i (k_ipad VALS))))\n  (Ssequence\n     (Sassign\n        (Ederef\n           (Ebinop Oadd (Evar _k_ipad (tarray tuchar 65)) (Etempvar _i tint)\n              (tptr tuchar)) tuchar)\n        (Ebinop Oxor\n           (Ederef\n              (Ebinop Oadd (Evar _k_ipad (tarray tuchar 65))\n                 (Etempvar _i tint) (tptr tuchar)) tuchar)\n           (Econst_int (Int.repr 54) tint) tint))\n     (Sassign\n        (Ederef\n           (Ebinop Oadd (Evar _k_opad (tarray tuchar 65)) (Etempvar _i tint)\n              (tptr tuchar)) tuchar)\n        (Ebinop Oxor\n           (Ederef\n              (Ebinop Oadd (Evar _k_opad (tarray tuchar 65))\n                 (Etempvar _i tint) (tptr tuchar)) tuchar)\n           (Econst_int (Int.repr 92) tint) tint)))\n  (normal_ret_assert\n     (PROP  (0 <= i + 1 <= 64)\n      LOCAL  (`(eq (Vint (Int.repr i))) (eval_id _i);\n   `(eq (Vint (Int.repr 64))) (eval_expr (Econst_int (Int.repr 64) tint));\n   `(eq (TEXT A)) (eval_id _text); `(eq (KEY A)) (eval_id _key);\n   `(eq KV) (eval_var sha._K256 (tarray tuint 64));\n   `(eq (TEXTLEN A)) (eval_id _text_len);\n   `(eq (KEYLEN A)) (eval_id _key_len); `(eq (DIGEST A)) (eval_id _digest);\n   `(eq (k_ipad VALS)) (eval_var _k_ipad (tarray tuchar 65));\n   `(eq (k_opad VALS)) (eval_var _k_opad (tarray tuchar 65));\n   `(eq (tk VALS)) (eval_var _tk (tarray tuchar 32));\n   `(eq (tk2 VALS)) (eval_var _tk2 (tarray tuchar 32));\n   `(eq (bufferIn VALS)) (eval_var _bufferIn (tarray tuchar 1024));\n   `(eq (bufferOut VALS)) (eval_var _bufferOut (tarray tuchar 1024)))\n      SEP \n      (`(array_at tuchar Tsh\n           (cVint\n              (force_int\n               oo ZnthV tuchar\n                    (map Vint\n                       (map Int.repr\n                          (map Byte.unsigned\n                             (map Byte.repr (HMAC_FUN.mkKey (key a))))))))\n           (i + 1) 64 (k_opad VALS));\n      `(array_at tuchar Tsh\n          (cVint\n             (force_int\n              oo ZnthV tuchar\n                   (map Vint\n                      (map Int.repr\n                         (map Byte.unsigned\n                            (map Byte.repr (HMAC_FUN.mkKey (key a))))))))\n          (i + 1) 64 (k_ipad VALS));\n      `(array_at tuchar Tsh\n          (cVint\n             (force_int\n              oo ZnthV tuchar\n                   (map Vint\n                      (map Int.repr\n                         (map Byte.unsigned\n                            (HMAC_FUN.mkArg\n                               (map Byte.repr (HMAC_FUN.mkKey (key a))) Opad))))))\n          0 (i + 1) (k_opad VALS));\n      `(array_at tuchar Tsh\n          (cVint\n             (force_int\n              oo ZnthV tuchar\n                   (map Vint\n                      (map Int.repr\n                         (map Byte.unsigned\n                            (HMAC_FUN.mkArg\n                               (map Byte.repr (HMAC_FUN.mkKey (key a))) Ipad))))))\n          0 (i + 1) (k_ipad VALS))))).\nProof. intros. \n     remember (cVint\n             (force_int\n              oo ZnthV tuchar\n                   (map Vint\n                      (map Int.repr\n                         (map Byte.unsigned\n                            (map Byte.repr (HMAC_FUN.mkKey (key a)))))))) as KKEY.\n     remember (cVint\n            (force_int\n             oo ZnthV tuchar\n                  (map Vint\n                     (map Int.repr\n                        (map Byte.unsigned\n                           (HMAC_FUN.mkArg\n                              (map Byte.repr (HMAC_FUN.mkKey (key a))) Opad)))))) as OPAD.\n     remember (cVint\n            (force_int\n             oo ZnthV tuchar\n                  (map Vint\n                     (map Int.repr\n                        (map Byte.unsigned\n                           (HMAC_FUN.mkArg\n                              (map Byte.repr (HMAC_FUN.mkKey (key a))) Ipad)))))) as IPAD.\ndestruct (nth_mapVintZ i (map Byte.unsigned (map Byte.repr (HMAC_FUN.mkKey (key a))))) as [n Hn].\n    rewrite Zlength_correct, map_length. rewrite map_length, HMAC_FUN.mkKey_length. simpl. assumption.\nsimple eapply semax_seq'.\n\neapply semax_pre0; [ apply now_later | ].\n{ eapply semax_post_flipped'.\n   eapply NEWsemax_loadstore_array. \n     reflexivity. trivial. reflexivity. reflexivity. reflexivity.\n     { entailer; repeat instantiate_Vptr.\n       destruct (k_ipad VALS) eqn:?Hipad; try contradiction.\n       rewrite <- Hipad in *.\n       repeat apply andp_right; rel_expr. \n       intro; simpl. rewrite <- H0. rewrite Hipad. reflexivity.\n       simpl typeof. simpl.\n         instantiate (2:=Tsh). repeat rewrite sepcon_assoc. rewrite sepcon_comm.\n         erewrite (split3_array_at' i tuchar Tsh _ i _ (k_ipad VALS)). \n         rewrite array_at_emp. normalize. rewrite (sepcon_comm TT). repeat rewrite sepcon_assoc. \n         apply sepcon_derives. rewrite Hipad. unfold add_ptr_int. simpl. rewrite mul_repr, Z.mul_1_l. cancel.\n         entailer.\n         reflexivity. \n         reflexivity.\n         reflexivity.\n         reflexivity.\n         omega.\n         discriminate.\n         intros; simpl. \n           unfold ZnthV, cVint. simpl. if_tac. omega. \n           rewrite Hn. simpl. reflexivity.\n         reflexivity.\n     }\n     instantiate (5:=1%nat). reflexivity. \n     trivial. \n     trivial. \n     split; omega. \n\n   eapply derives_refl.\n}\n\n  normalize.\n\n   assert (Keyisbyte: Forall isbyteZ (HMAC_FUN.mkKey (key a))).\n     unfold HMAC_FUN.mkKey.\n     destruct (Zlength (key a) >? Z.of_nat SHA256_BlockSize);\n       apply zeropad_isbyteZ; trivial.\n     apply isbyte_sha.\neapply semax_pre0; [ apply now_later | ].\n{ eapply semax_post_flipped'.\n   eapply NEWsemax_loadstore_array. \n     reflexivity. trivial. reflexivity. reflexivity. reflexivity.\n     { entailer; repeat instantiate_Vptr.\n       destruct (k_opad VALS) eqn:?Hopad; try contradiction.\n       rewrite <- Hopad in *.\n       repeat apply andp_right; rel_expr.  \n       intro; simpl. rewrite <- H0. rewrite Hopad. reflexivity.\n       simpl typeof. simpl.\n         instantiate (2:=Tsh). repeat rewrite sepcon_assoc. rewrite sepcon_comm.\n         erewrite (split3_array_at' i tuchar Tsh _ i _ (k_opad VALS)); try reflexivity. \n         rewrite array_at_emp. normalize.\n         rewrite <- (sepcon_comm (array_at tuchar Tsh\n  (cVint\n     (force_int\n      oo ZnthV tuchar\n           (map Vint\n              (map Int.repr\n                 (map Byte.unsigned (map Byte.repr (HMAC_FUN.mkKey (key a))))))))\n  (Z.succ i) 64 (k_opad VALS))).\n         repeat rewrite <- sepcon_assoc. apply sepcon_derives. entailer.\n         rewrite Hopad. unfold add_ptr_int. simpl. rewrite mul_repr, Z.mul_1_l. cancel.\n         omega.\n         discriminate.\n         intros; simpl. \n           unfold ZnthV, cVint. simpl. if_tac. omega. \n           rewrite Hn. simpl. reflexivity.\n         reflexivity.\n     }\n     instantiate (5:=0%nat). reflexivity. \n     trivial. \n     trivial. \n     split; omega. \n\n   entailer. rewrite (split_array_at (i+1) tuchar Tsh _ i 64); try omega.\n   rewrite (split_array_at (i+1) tuchar Tsh _ i 64); try omega.\n   rewrite (split_array_at i tuchar Tsh _ 0 (i+1)); try omega.\n   rewrite (split_array_at i tuchar Tsh _ 0 (i+1)); try omega.\n   cancel. \n   assert (ARITH1: forall PAD BPAD \n     (HPAD: PAD = Byte.intval BPAD) k, i <= k < i+1 ->\n     (upd\n     (cVint\n        (force_int\n         oo ZnthV tuchar\n              (map Vint\n                 (map Int.repr\n                    (map Byte.unsigned\n                       (map Byte.repr (HMAC_FUN.mkKey (key a)))))))) i\n     (Vint (Int.zero_ext 8 (Int.xor n (Int.repr PAD))))) k\n     = (cVint\n         (force_int\n          oo ZnthV tuchar\n               (map Vint\n                  (map Int.repr\n                     (map Byte.unsigned\n                        (HMAC_FUN.mkArg\n                           (map Byte.repr (HMAC_FUN.mkKey (key a))) BPAD)))))) k).\n   { intros. unfold cVint, ZnthV, upd. if_tac. subst; simpl. 2: omega.\n     if_tac. omega. simpl. f_equal.\n\n    rewrite map_unsigned_Brepr_isbyte in Hn; trivial.\n    rewrite (nth_indep _ _ (Vint Int.zero)) in Hn.\n     erewrite mapnth' in Hn; try reflexivity.\n     inversion Hn; clear Hn.\n    rewrite H17.\n    eapply nthD_1 in H17. instantiate (1:=Z0) in H17.\n    destruct H17 as [z [KeyZ [NZ NN]]].\n    rewrite Forall_forall in Keyisbyte. apply Keyisbyte in KeyZ.\n     unfold HMAC_FUN.mkArg.\n     rewrite (nth_indep _ _ (Vint Int.zero)).\n     erewrite mapnth'. unfold force_int. 2: reflexivity.\n     erewrite mapnth'. simpl.\n     Focus 2. instantiate (1:=Z0). reflexivity.\n     erewrite mapnth'.\n     Focus 2. instantiate (1:=Byte.zero). reflexivity.\n     erewrite mapnth'. simpl.\n     Focus 2. instantiate (1:=(Byte.zero, Byte.zero)). reflexivity.  \n     rewrite combine_nth.\n     unfold sixtyfour. rewrite nth_Nlist. simpl. unfold Opad.\n     erewrite mapnth'.\n     Focus 2. instantiate (1:=0). reflexivity.\n     rewrite NZ. clear NZ. subst n.\n     apply Int.same_bits_eq. clear - KeyZ. intros.\n        unfold Int.zero_ext. (*, Int.Zzero_ext. simpl.*)\n     rewrite Int.testbit_repr; trivial.\n     rewrite Int.testbit_repr; trivial.\n     rewrite Int.Zzero_ext_spec; try omega.\n\n     rewrite sha_lemmas.Ztest_Inttest, Int.bits_xor; trivial.\n     rewrite Ztest_Bytetest.\n     if_tac.\n        assert (iB: 0 <= i < Byte.zwordsize).\n          unfold Byte.zwordsize; simpl; omega.\n        rewrite Byte.bits_xor; trivial.\n        repeat rewrite Int.testbit_repr; trivial. \n        repeat rewrite Byte.testbit_repr; trivial.\n     rewrite Byte.bits_above. trivial. apply H0.\n\n    destruct H as [_ H]. apply Z2Nat.inj_lt in H; try omega. apply H.\n    rewrite map_length. unfold sixtyfour. rewrite HMAC_FUN.mkKey_length, length_Nlist. reflexivity.\n    repeat rewrite map_length. rewrite combine_length. rewrite map_length.\n      unfold sixtyfour. rewrite HMAC_FUN.mkKey_length, length_Nlist. simpl.\n      destruct H as [_ H]. apply Z2Nat.inj_lt in H; try omega. apply H.\n    rewrite HMAC_FUN.mkKey_length. simpl.\n      destruct H as [_ H]. apply Z2Nat.inj_lt in H; try omega. apply H.\n    repeat rewrite map_length. rewrite HMAC_FUN.mkKey_length. simpl.\n      destruct H as [_ H]. apply Z2Nat.inj_lt in H; try omega. apply H.\n  }\n\n  assert (Arth92 := ARITH1 54 Ipad (eq_refl _)).\n  assert (Arth54 := ARITH1 92 Opad (eq_refl _)). clear ARITH1.\n  erewrite (array_at_ext tuchar Tsh _ _ i (i+1) Arth92).\n  erewrite (array_at_ext tuchar Tsh _ _ i (i+1) Arth54).\n  clear Arth54 Arth92; cancel.\n\n  assert (ARITH1: forall PAD k, i + 1 <= k < 64 ->\n    upd (cVint\n     (force_int\n      oo ZnthV tuchar\n           (map Vint\n              (map Int.repr\n                 (map Byte.unsigned (map Byte.repr (HMAC_FUN.mkKey (key a))))))))\n     i (Vint (Int.zero_ext 8 (Int.xor n (Int.repr PAD)))) k \n   = cVint (force_int\n      oo ZnthV tuchar\n        (map Vint\n           (map Int.repr\n              (map Byte.unsigned (map Byte.repr (HMAC_FUN.mkKey (key a)))))))\n    k).\n   { clear. intros. unfold upd. if_tac. subst. omega. trivial. }\n\n  rewrite (array_at_ext tuchar Tsh _ _ (i+1) 64 (ARITH1 92)).\n  rewrite (array_at_ext tuchar Tsh _ _ (i+1) 64 (ARITH1 54)). cancel.\n }\nQed.", "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/HMAC_LoopBodyLE.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.27807536927539545}}
{"text": "(**********************************************************************)\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 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(*                     SF-Calculus                                    *)\n(*                  as Wave Calculus                                  *)\n(*                                                                    *)\n(*                      Barry Jay                                     *)\n(*                                                                    *)\n(**********************************************************************)\n\n\n(** The operators S and F are enough, but more may be added in future. *) \n\nInductive operator := | Node . \n\n(** The terms of SF-calculus are either variables (given as de Bruijn indices), operators or applications. \nTerms are called combinations if they do not use any variables. *) \n\nInductive SF:  Set :=\n  | Ref : nat -> SF        \n  | Op  : operator -> SF   \n  | App : SF -> SF -> SF   \n.\n\n", "meta": {"author": "Barry-Jay", "repo": "Tree-calculus", "sha": "6959925d2b851020b6945036078a97c0b2a0d19f", "save_path": "github-repos/coq/Barry-Jay-Tree-calculus", "path": "github-repos/coq/Barry-Jay-Tree-calculus/Tree-calculus-6959925d2b851020b6945036078a97c0b2a0d19f/Tree_Terms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.27807536927539545}}
{"text": "Require Import Program.\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 View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import Behavior.\n\nRequire Import SimMemory.\nRequire Import Simulation.\n\nSet Implicit Arguments.\n\n\nLemma sim_adequacy\n      ths_src sc_src mem_src\n      ths_tgt sc_tgt mem_tgt\n      (WF_SRC: Configuration.wf (Configuration.mk ths_src sc_src mem_src))\n      (WF_TGT: Configuration.wf (Configuration.mk ths_tgt sc_tgt mem_tgt))\n      (CONSISTENT_SRC: Configuration.consistent (Configuration.mk ths_src sc_src mem_src))\n      (CONSISTENT_TGT: Configuration.consistent (Configuration.mk ths_tgt sc_tgt mem_tgt))\n      (SC: TimeMap.le sc_src sc_tgt)\n      (MEMORY: sim_memory mem_src mem_tgt)\n      (SIM: sim ths_src sc_src mem_src ths_tgt sc_tgt mem_tgt):\n  behaviors Configuration.step (Configuration.mk ths_tgt sc_tgt mem_tgt) <1=\n  behaviors Configuration.step (Configuration.mk ths_src sc_src mem_src).\nProof.\n  s. i.\n  revert WF_SRC WF_TGT CONSISTENT_SRC CONSISTENT_TGT SC MEMORY SIM.\n  revert ths_src sc_src mem_src.\n  dependent induction PR; i.\n  - punfold SIM. exploit SIM; eauto; try refl. i. des.\n    exploit TERMINAL0; eauto. i. des.\n    eapply rtc_tau_step_behavior; eauto.\n    econs 1. auto.\n  - destruct c2.\n    punfold SIM. exploit SIM; eauto; try refl. i. des.\n    exploit STEP0; eauto. i. des. inv SIM0; [|done].\n    eapply rtc_tau_step_behavior; eauto.\n    exploit Configuration.step_future; try apply STEP; eauto. i. des.\n    exploit Configuration.rtc_step_future; eauto. i. des.\n    inv STEP_SRC. econs 2; eauto.\n    exploit Configuration.step_future; try apply STEP1; eauto. i. des.\n    eapply IHPR; eauto.\n  - destruct c2.\n    punfold SIM. exploit SIM; eauto; try refl. i. des.\n    exploit STEP0; eauto. i. des. inv SIM0; [|done].\n    eapply rtc_tau_step_behavior; eauto.\n    exploit Configuration.step_future; try apply STEP; eauto. i. des.\n    exploit Configuration.rtc_step_future; eauto. i. des.\n    inv STEP_SRC.\n    + eapply IHPR; eauto.\n    + econs 3; eauto.\n      exploit Configuration.step_future; try apply STEP1; eauto. s. i. des.\n      eapply IHPR; 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/Adequacy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2780753629568398}}
{"text": "(** * Mapping predicates over [StringLike] things *)\nRequire Import Coq.Classes.Morphisms Coq.Classes.RelationClasses Coq.Program.Basics.\nRequire Import Coq.omega.Omega.\nRequire Import Coq.Numbers.Natural.Peano.NPeano.\nRequire Import Fiat.Parsers.StringLike.Core.\nRequire Import Fiat.Parsers.StringLike.Properties.\nRequire Import Fiat.Parsers.StringLike.ForallChars.\nRequire Import Fiat.Common.SetoidInstances.\nRequire Import Fiat.Common.\n\nSet Implicit Arguments.\nLocal Open Scope string_like_scope.\n\nSection for_first_char.\n  Context {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char} {HSLP : StringLikeProperties Char}.\n\n  Definition for_first_char (str : String) (P : Char -> Prop)\n    := forall ch,\n         take 1 str ~= [ ch ]\n         -> P ch.\n\n  Global Instance for_first_char_Proper\n  : Proper (beq ==> pointwise_relation _ impl ==> impl) for_first_char.\n  Proof.\n    unfold pointwise_relation, respectful, for_first_char, impl.\n    intros ?? H' ?? H'' H''' ? H.\n    rewrite <- H' in H.\n    eauto using is_char_Proper.\n  Qed.\n\n  Global Instance for_first_char_Proper_flip\n  : Proper (beq ==> pointwise_relation _ (flip impl) ==> flip impl) for_first_char.\n  Proof.\n    unfold pointwise_relation, respectful, for_first_char, flip, impl.\n    intros ?? H' ?? H'' H''' ? H.\n    rewrite H' in H.\n    eauto using is_char_Proper.\n  Qed.\n\n  Global Instance for_first_char_Proper_iff\n  : Proper (beq ==> pointwise_relation _ iff ==> iff) for_first_char.\n  Proof.\n    unfold pointwise_relation, respectful.\n    repeat intro; split;\n    apply for_first_char_Proper; try assumption; repeat intro;\n    match goal with\n      | [ H : _ |- _ ] => apply H; assumption\n    end.\n  Qed.\n\n  Lemma for_first_char_nil (str : String) P\n  : length str = 0 -> for_first_char str P.\n  Proof.\n    intros H ch H'.\n    apply length_singleton in H'.\n    rewrite ?take_length, ?drop_length, H in H'.\n    simpl in H'; omega.\n  Qed.\n\n  Lemma helper\n        (P : nat -> nat -> Type)\n        n\n        (H0 : forall n0, P (min 1 (n - n0)) n0)\n        (H1 : forall n0, P 1 (n0 + n))\n        {n0}\n  : P 1 n0.\n  Proof.\n    destruct (Compare_dec.le_dec n n0) as [H'|H'].\n    { specialize (H1 (n0 - n)).\n      rewrite Nat.sub_add in H1 by assumption; assumption. }\n    { apply Compare_dec.not_le in H'.\n      specialize (H0 n0).\n      destruct (n - n0) as [|[|]] eqn:?; simpl in *; trivial; omega. }\n  Defined.\n\n  Lemma for_first_char__take n (str : String) P\n  : for_first_char str P\n    <-> for_first_char (take (S n) str) P.\n  Proof.\n    unfold for_first_char; repeat (split || intro);\n    repeat match goal with\n                         | [ H : _ |- _ ] => setoid_rewrite drop_length in H\n                         | [ H : _ |- _ ] => setoid_rewrite take_length in H\n                         | [ H : _ |- _ ] => setoid_rewrite drop_take in H\n                         | [ H : _ |- _ ] => setoid_rewrite take_take in H\n                         | [ H : _ |- _ ] => setoid_rewrite drop_drop in H\n                         | [ H : _ /\\ _ |- _ ] => destruct H\n                         | [ H : context[min 1 ?x] |- _ ] => destruct x eqn:?; simpl in H\n                         | [ H : is_true (take 0 _ ~= [ _ ]) |- _ ] => exfalso; apply length_singleton in H\n                         | _ => omega\n                         | _ => progress simpl in *; omega\n                         | _ => solve [ eauto ]\n                         | _ => solve [ eapply (@helper (fun a b => take a (drop b str) ~= [ ch ] -> P ch)); eauto ]\n                       end.\n  Qed.\n\n  Lemma for_first_char_singleton (str : String) P ch\n  : str ~= [ ch ] -> (P ch <-> for_first_char str P).\n  Proof.\n    intro H.\n    pose proof (length_singleton _ _ H).\n    unfold for_first_char.\n    split; intro H'; repeat intro.\n    { repeat match goal with\n               | _ => intro\n               | _ => omega\n               | [ H : _ |- _ ] => rewrite drop_0 in H\n               | [ H : _, H' : _ |- _ ] => rewrite (singleton_take H') in H\n               | [ H : _ |- False ] => apply length_singleton in H\n               | [ H : _ |- _ ] => rewrite take_length in H\n               | [ H : _ |- _ ] => rewrite drop_length in H\n               | [ H : ?x = 1, H' : context[?x] |- _ ] => rewrite H in H'\n               | _ => erewrite singleton_unique; eassumption\n               | [ H : appcontext[min] |- _ ] => revert H; apply Min.min_case_strong\n             end. }\n    { match goal with\n        | [ H : _ |- _ ] => apply H\n      end.\n      rewrite take_long; trivial; omega. }\n  Qed.\n\n  Lemma for_first_char_singleton_length (str : String) P (H : length str = 1)\n  : for_first_char str P <-> (forall ch, str ~= [ ch ] -> P ch).\n  Proof.\n    split.\n    { intro H''.\n      intros ch' H'''.\n      apply (for_first_char_singleton _ _ _ H'''); assumption. }\n    { destruct (singleton_exists _ H) as [ch H'].\n      intro H''.\n      apply (for_first_char_singleton _ P ch H'); eauto. }\n  Qed.\n\n  Global Opaque for_first_char.\n\n  Lemma for_first_char_exists (str : String) P (H : length str >= 1)\n  : for_first_char str P <-> (exists ch, take 1 str ~= [ ch ] /\\ P ch).\n  Proof.\n    rewrite (for_first_char__take 0).\n    assert (H' : length (take 1 str) = 1)\n      by (rewrite take_length; apply Min.min_case_strong; omega).\n    destruct (singleton_exists _ H') as [ch H''].\n    rewrite for_first_char_singleton_length by exact H'.\n    split; intros.\n    { exists ch; split; eauto. }\n    { destruct_head ex.\n      destruct_head and.\n      repeat match goal with\n               | [ H : is_true (?str ~= [ ?ch ])%string_like, H' : is_true (?str ~= [ ?ch' ])%string_like |- _ ]\n                 => assert (ch = ch') by (eapply singleton_unique; eassumption);\n                   clear H'\n             end.\n      subst; assumption. }\n  Qed.\n\n  Lemma for_first_char_False (str : String) P\n  : (forall ch, ~P ch) -> for_first_char str P -> length str = 0.\n  Proof.\n    intros H' H.\n    case_eq (length str); trivial.\n    pose proof (singleton_exists (take 1 str)) as H''.\n    rewrite take_length in H''.\n    intros n H'''.\n    rewrite H''' in *.\n    specialize (H'' eq_refl).\n    destruct H'' as [ch H''].\n    apply (for_first_char__take 0) in H.\n    apply (for_first_char_singleton _ _ _ H'') in H.\n    specialize (H' ch).\n    exfalso; eauto.\n  Qed.\n\n  Lemma for_first_char_combine (str : String) (P P' : Char -> Prop) (T : Prop) (H : forall ch, P ch -> P' ch -> T)\n        (H0 : for_first_char str P)\n        (H1 : for_first_char str P')\n  : length str = 0 \\/ T.\n  Proof.\n    case_eq (length str).\n    { left; reflexivity. }\n    { intros n H'; right.\n      pose proof (singleton_exists (take 1 str)) as H''.\n      rewrite take_length, H' in H''.\n      specialize (H'' eq_refl).\n      destruct H'' as [ch H''].\n      specialize (H ch).\n      apply (for_first_char__take 0) in H0.\n      apply (for_first_char__take 0) in H1.\n      apply (for_first_char_singleton _ _ _ H'') in H0.\n      apply (for_first_char_singleton _ _ _ H'') in H1.\n      eauto. }\n  Qed.\n\n\n  Definition first_char_in (str : String) (ls : list Char)\n    := for_first_char str (fun ch => List.In ch ls).\n\n  Definition for_first_char__impl__first_char_in {str ls} {P : _ -> Prop}\n             (H : forall ch, P ch -> List.In ch ls)\n  : impl (for_first_char str P) (first_char_in str ls).\n  Proof.\n    unfold first_char_in.\n    apply for_first_char_Proper; trivial; reflexivity.\n  Qed.\n\n  Definition first_char_in__impl__for_first_char {str ls} {P : _ -> Prop}\n             (H : forall ch, List.In ch ls -> P ch)\n  : impl (first_char_in str ls) (for_first_char str P).\n  Proof.\n    unfold first_char_in.\n    apply for_first_char_Proper; trivial; reflexivity.\n  Qed.\n\n  Global Instance first_char_in__Proper\n  : Proper (beq ==> eq ==> impl) first_char_in.\n  Proof.\n    unfold pointwise_relation, respectful, first_char_in, impl.\n    repeat intro; subst.\n    match goal with\n      | [ H : _ |- _ ] => rewrite <- H; assumption\n    end.\n  Qed.\n\n  Global Instance first_char_in__Proper_iff\n  : Proper (beq ==> eq ==> iff) first_char_in.\n  Proof.\n    unfold pointwise_relation, respectful, first_char_in, impl.\n    repeat intro; subst.\n    match goal with\n      | [ H : _ |- _ ] => rewrite <- H; reflexivity\n    end.\n  Qed.\n\n  Lemma first_char_in__take n (str : String) ls\n  : first_char_in str ls\n    <-> first_char_in (take (S n) str) ls.\n  Proof.\n    unfold first_char_in; apply for_first_char__take.\n  Qed.\n\n  Lemma first_char_in_nil (str : String)\n  : first_char_in str nil <-> length str = 0.\n  Proof.\n    unfold first_char_in.\n    split.\n    { eapply for_first_char_False; simpl; eauto. }\n    { apply for_first_char_nil. }\n  Qed.\n\n  Lemma first_char_in_empty (str : String) (H : length str = 0) ls\n  : first_char_in str ls.\n  Proof.\n    unfold first_char_in.\n    apply for_first_char_nil; assumption.\n  Qed.\n\n  Lemma first_char_in_singleton_str (str : String) ls ch (H : str ~= [ ch ])\n  : first_char_in str ls <-> List.In ch ls.\n  Proof.\n    unfold first_char_in.\n    rewrite <- for_first_char_singleton; try eassumption; reflexivity.\n  Qed.\n\n  Lemma first_char_in__app_or_iff (str : String) (ls1 ls2 : list Char)\n  : first_char_in str (ls1 ++ ls2)\n    <-> (first_char_in str ls1 \\/ first_char_in str ls2).\n  Proof.\n    unfold first_char_in.\n    setoid_rewrite List.in_app_iff.\n    rewrite !(for_first_char__take 0 str).\n    generalize (singleton_exists (take 1 str)).\n    rewrite take_length.\n    case_eq (length str).\n    { intros H _.\n      split; intro H0;\n      [ left; apply first_char_in_empty\n      | apply for_first_char_nil ];\n      rewrite take_length, H; reflexivity. }\n    { intros ? ? H.\n      specialize (H eq_refl).\n      destruct H as [ch H].\n      rewrite <- !for_first_char_singleton by eassumption; tauto. }\n  Qed.\n\n  Lemma first_char_in__or_app (str : String) (ls1 ls2 : list Char)\n  : first_char_in str ls1 \\/ first_char_in str ls2 -> first_char_in str (ls1 ++ ls2).\n  Proof.\n    unfold first_char_in.\n    intros [?|?]; repeat intro;\n    (eapply for_first_char_Proper; [ .. | eassumption ]; [ reflexivity | ]; intros ??);\n    apply List.in_or_app; eauto.\n  Qed.\n\n  Global Opaque first_char_in.\n\n  Definition first_char_in__iff__for_first_char' {str ls} {P : _ -> Prop}\n             (H : forall ch, P ch <-> List.In ch ls)\n  : first_char_in str ls <-> for_first_char str P.\n  Proof.\n    split_iff.\n    split; first [ apply for_first_char__impl__first_char_in | apply first_char_in__impl__for_first_char ];\n    assumption.\n  Qed.\n\n  Definition first_char_in__iff__for_first_char {str ls}\n  : first_char_in str ls <-> for_first_char str (fun ch => List.In ch ls).\n  Proof.\n    apply first_char_in__iff__for_first_char'; reflexivity.\n  Qed.\n\n  Lemma first_char_in_exists (str : String) ls (H : length str >= 1)\n  : first_char_in str ls <-> (exists ch, take 1 str ~= [ ch ] /\\ List.In ch ls).\n  Proof.\n    erewrite first_char_in__iff__for_first_char, for_first_char_exists by assumption.\n    reflexivity.\n  Qed.\n\n  Lemma forall_chars__impl__for_first_char (str : String) P (H : forall_chars str P)\n  : for_first_char str P.\n  Proof.\n    case_eq (length str).\n    { apply for_first_char_nil. }\n    { intros n H'.\n      eapply forall_chars_take in H.\n      apply (for_first_char__take 0).\n      apply for_first_char_singleton_length.\n      { rewrite take_length, H'; reflexivity. }\n      { apply forall_chars_singleton_length.\n        { rewrite take_length, H'; reflexivity. }\n        { eassumption. } } }\n  Qed.\n\n  Lemma for_first_char__for_first_char__iff_short (str : String) P (H : length str <= 1)\n  : forall_chars str P <-> for_first_char str P.\n  Proof.\n    case_eq (length str).\n    { intro H'.\n      split; intro.\n      { apply for_first_char_nil; assumption. }\n      { apply forall_chars_nil; assumption. } }\n    { intros [|] H'; [ | exfalso; omega ].\n      rewrite forall_chars_singleton_length by assumption.\n      rewrite for_first_char_singleton_length by assumption.\n      reflexivity. }\n  Qed.\n\nEnd for_first_char.\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/StringLike/FirstChar.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2780753629568398}}
{"text": "(** Libraries. *)\nRequire Import String.\nRequire Import CoqlibC Errors ErrorsC.\nRequire Import AST Linking Smallstep.\n(** Command-line flags. *)\nRequire Import Compopts.\n(** newly added **)\nRequire Import BehaviorsC.\nRequire Export Compiler.\nRequire Import Simulation.\nRequire Import Sem SimProg Skeleton Mod ModSem SimMod SimModSem SimSymb SimMem Sound SimSymb.\nRequire Import SemProps AdequacyLocal.\n\nRequire SimMemInjInvC.\n\nRequire Import RUSC.\n\nRequire Import MutrecHeader.\nRequire Import MutrecAspec MutrecBspec MutrecABspec MutrecA MutrecB.\nRequire Import MutrecABproof MutrecAproof MutrecBproof.\n\nRequire IdSimAsmIdInv.\nRequire IdSimClightIdInv.\n\n\nDefinition mutrec_relations :=\n  fun r => exists P, r = mkPR (SimMemInjInvC.SimMemInjInv SimMemInjInv.top_inv P)\n                              (SimMemInjInvC.SimSymbIdInv P)\n                              SoundTop.Top.\n\nLemma asm_self_related (asm: Asm.program)\n  :\n    self_related mutrec_relations [(AsmC.module asm)].\nProof.\n  intros r RELIN. unfold mutrec_relations in *. ss.\n  des; clarify; eapply relate_single_program; intros WF.\n  exploit IdSimAsmIdInv.asm_inj_inv_id; ss; eauto.\nQed.\n\nLemma clight_self_related (cls: Clight.program)\n  :\n    self_related mutrec_relations [(ClightC.module2 cls)].\nProof.\n  intros r RELIN. unfold mutrec_relations in *. ss.\n  des; clarify; eapply relate_single_program; intros WF.\n  exploit IdSimClightIdInv.clight_inj_inv_id; ss; eauto.\nQed.\n\nLemma asms_self_related (asms: list Asm.program)\n  :\n    self_related mutrec_relations (map AsmC.module asms).\nProof.\n  induction asms; ss; ii.\n  exploit IHasms; ss; eauto. i.\n  eapply (@program_relation.horizontal _ [(AsmC.module a)] _ [(AsmC.module a)]); eauto.\n  eapply asm_self_related; eauto.\nQed.\n\nLemma clights_self_related (cls: list Clight.program)\n  :\n    self_related mutrec_relations (map ClightC.module2 cls).\nProof.\n  induction cls; ss; ii.\n  exploit IHcls; ss; eauto. i.\n  eapply (@program_relation.horizontal _ [(ClightC.module2 a)] _ [(ClightC.module2 a)]); eauto.\n  eapply clight_self_related; eauto.\nQed.\n\n\nRequire IdSimMutrecAIdInv.\n\nLemma specA_self_related\n  :\n    self_related mutrec_relations [MutrecAspec.module].\nProof.\n  intros r RELIN. unfold mutrec_relations in *. ss.\n  des; clarify; eapply relate_single_program; intros WF.\n  exploit IdSimMutrecAIdInv.a_inj_inv_id; ss; eauto.\nQed.\n\nRequire IdSimMutrecBIdInv.\n\nLemma specB_self_related\n  :\n    self_related mutrec_relations [MutrecBspec.module].\nProof.\n  intros r RELIN. unfold mutrec_relations in *. ss.\n  des; clarify; eapply relate_single_program; intros WF.\n  exploit IdSimMutrecBIdInv.b_inj_inv_id; ss; eauto.\nQed.\n\nLemma MutrecA_rusc\n  :\n    rusc mutrec_relations [MutrecAspec.module] [(ClightC.module2 MutrecA.prog)].\nProof.\n  eapply (@relate_single_rusc\n            _\n            (SimMemInjInvC.SimMemInjInv SimMemInjInv.top_inv MutrecAproof.memoized_inv)\n            (SimMemInjInvC.SimSymbIdInv MutrecAproof.memoized_inv)\n            SoundTop.Top).\n  - set MutrecAproof.sim_mod. unfold relate_single. i. esplits; ss; eauto.\n  - unfold mutrec_relations. eauto.\nQed.\n\nLemma MutrecB_rusc\n  :\n    rusc mutrec_relations [MutrecBspec.module] [(AsmC.module MutrecB.prog)].\nProof.\n  eapply (@relate_single_rusc\n            _\n            (SimMemInjInvC.SimMemInjInv SimMemInjInv.top_inv MutrecBproof.memoized_inv)\n            (SimMemInjInvC.SimSymbIdInv MutrecBproof.memoized_inv)\n            SoundTop.Top).\n  - set MutrecBproof.sim_mod. unfold relate_single. i. esplits; ss; eauto.\n  - unfold mutrec_relations. eauto.\nQed.\n\nTheorem MutrecAB_AB_rusc\n  :\n    rusc bot1 [(MutrecABspec.module)] [(MutrecAspec.module) ; (MutrecBspec.module)]\n.\nProof.\n  unfold rusc. i. eapply mutrecABcorrect.\nQed.\n\nLemma MutrecAB_impl_rusc\n :\n   rusc mutrec_relations\n        [MutrecABspec.module]\n        [(ClightC.module2 MutrecA.prog); (AsmC.module MutrecB.prog)].\nProof.\n etrans.\n - eapply rusc_mon; [|eapply MutrecAB_AB_rusc]; ss.\n - hexploit rusc_horizontal.\n   + eapply MutrecA_rusc.\n   + eapply MutrecB_rusc.\n   + eapply specA_self_related.\n   + eapply specB_self_related.\n   + eapply clight_self_related.\n   + eapply asm_self_related.\n   + i. eauto.\nQed.\n\nTheorem Mutrec_correct\n        (srcs: list Clight.program)\n        (hands: list Asm.program)\n  :\n    improves (sem ((map ClightC.module2 srcs) ++ (map AsmC.module hands) ++ [MutrecABspec.module]))\n             (sem ((map ClightC.module2 srcs) ++ (map AsmC.module hands) ++ [(ClightC.module2 MutrecA.prog); (AsmC.module MutrecB.prog)])).\nProof.\n  replace (map ClightC.module2 srcs ++ map AsmC.module hands ++ [MutrecABspec.module]) with\n      ((map ClightC.module2 srcs ++ map AsmC.module hands) ++ [MutrecABspec.module]); cycle 1.\n  { rewrite app_assoc. auto. }\n  replace (map ClightC.module2 srcs ++ map AsmC.module hands\n               ++ [ClightC.module2 MutrecA.prog; AsmC.module prog]) with\n      ((map ClightC.module2 srcs ++ map AsmC.module hands) ++ [ClightC.module2 MutrecA.prog; AsmC.module prog]); cycle 1.\n  { rewrite app_assoc. auto. }\n  eapply rusc_adequacy_left_ctx.\n  - eapply MutrecAB_impl_rusc.\n  - eapply self_related_horizontal.\n    + eapply clights_self_related.\n    + eapply asms_self_related.\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/demo/mutrec/MutrecRefinement.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2780753629568398}}
{"text": "From ch2o_compcert Require Export ch2o_lp64 ifs_ch2o.\nFrom ch2o Require Import stringmap frontend_sound.\n\nLocal Open Scope string_scope.\n\nDefinition alloc_program_result: frontend_state K.\nProof.\nset (a:=alloc_program (K:=K) decls ∅).\nassert (match a with inl _ => False | inr _ => True end). { exact I. }\ndestruct a. { elim H. }\ndestruct p.\nexact f.\nDefined.\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\nGoal env_t Γ = ∅.\nProof.\nreflexivity.\nQed.\n\nGoal stringmap_to_list (env_f Γ) = [(\"main\", ([], sintT%T))].\nreflexivity.\nQed.\n\n(*\n\nCompute stringmap_to_list δ.\n\n*)\n\nGoal stringmap_to_list δ = [\n  (\"main\",\n   if{# intV{sintT} 1} skip else skip ;;\n   if{# intV{sintT} 0} skip else skip ;;\n   ret\n     (cast{sintT%T} (\n        # intV{sintT} 17 / # intV{sintT} 2 /\n        (# intV{sintT} 15 / # intV{sintT} 5))))\n].\nProof.\nreflexivity.\nQed.\n\nLemma δ_main: δ !! (\"main\": funname) = Some (\n   if{# intV{sintT} 1} skip else skip ;;\n   if{# intV{sintT} 0} skip else skip ;;\n   ret\n     (cast{sintT%T} (\n        # intV{sintT} 17 / # intV{sintT} 2 /\n        (# intV{sintT} 15 / # intV{sintT} 5))) : stmt K).\nProof.\nreflexivity.\nQed.\n\nGoal m0 = ∅.\nProof.\nreflexivity.\nQed.\n\nGoal S0 = State [] (Call \"main\" []) m0.\nProof.\nreflexivity.\nQed.\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", "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/ifs_ch2o_core_c.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.2780627158291136}}
{"text": "(*\n * Taking another shot at adding new constructors.\n * \n * My conclusion: I think it's really cool that we can express adding\n * a constructor as an equivalence, like I suspected.\n * But I'm not trying to fool anyone into thinking the way that I do this\n * is useful yet. It just gives clear path to something useful, separating\n * out the hard work from the easy work. A lot of the other changes we handle,\n * we handle efficiently and usefully. Just being able to do this at all surprised\n * people, so I think it's cute still.\n *)\nRequire Import List.\nRequire Import String.\nRequire Import ZArith.\n\nImport ListNotations.\n\nRequire Import Ornamental.Ornaments.\nSet DEVOID search prove coherence.\nSet DEVOID search prove equivalence.\nSet DEVOID lift type.\nSet DEVOID search smart eliminators.\n\n(*\n * Let's do more of the REPLICA benchmark and see what happens.\n * We start with the swap from Swap.v, then add the bool constructor.\n *\n * This is going to walk through more steps than actually needed long-term,\n * just to show the thought process. For simplicity, we are going to start\n * with just the functions.\n *)\n\n(* --- Original --- *)\n\nDefinition Identifier := string.\nDefinition id_eq_dec := string_dec.\n\nModule Old.\n\nInductive Term : Set :=\n  | Var : Identifier -> Term\n  | Int : Z -> Term\n  | Eq : Term -> Term -> Term\n  | Plus : Term -> Term -> Term\n  | Times : Term -> Term -> Term\n  | Minus : Term -> Term -> Term\n  | Choose : Identifier -> Term -> Term.\n\nEnd Old.\n\nModule User5Session19.\n\nImport Old.\n\nFixpoint identity (t : Term) : Term :=\n  match t with\n  | Var x => Var x\n  | Int i => Int i\n  | Eq a b => Eq (identity a) (identity b)\n  | Plus a b => Plus (identity a) (identity b)\n  | Times a b => Times (identity a) (identity b)\n  | Minus a b => Minus (identity a) (identity b)\n  | Choose x P => Choose x (identity P)\n  end.\n\nFixpoint free_vars (t : Term) : list Identifier :=\n  match t with\n  | Var x => [x]\n  | Int _ => []\n  | Eq a b => free_vars a ++ free_vars b\n  | Plus a b => free_vars a ++ free_vars b\n  | Times a b => free_vars a ++ free_vars b\n  | Minus a b => free_vars a ++ free_vars b\n  | Choose x P =>\n      filter (fun y => if id_eq_dec x y then false else true) (free_vars P)\n  end.\n\nEnd User5Session19.\n\nPreprocess Module User5Session19 as OldProofs {\n  opaque\n    Coq.Init.Datatypes Coq.Strings.String Coq.Init.Logic Coq.Lists.List\n}.\n\n(* --- Swap --- *)\n\n(*\n * This is the same swap from Swap.v, just one part of the change.\n *)\n\nModule New.\n\nInductive Term : Set :=\n  | Var : Identifier -> Term\n  | Eq : Term -> Term -> Term\n  | Int : Z -> Term\n  | Plus : Term -> Term -> Term\n  | Times : Term -> Term -> Term\n  | Minus : Term -> Term -> Term\n  | Choose : Identifier -> Term -> Term.\n\nEnd New.\n\n(* failures below are just redundant attempts at repairing projections *) \nFind ornament Old.Term New.Term { mapping 0 }.\nRepair Module Old.Term New.Term in OldProofs as NewProofs.\n\n(* --- Add Bool --- *)\n\n(*\n * OK, now let's extend with Bool.\n *)\n\nModule AddBool.\n\nInductive Term : Set :=\n  | Var : Identifier -> Term\n  | Bool : bool -> Term\n  | Eq : Term -> Term -> Term\n  | Int : Z -> Term\n  | Plus : Term -> Term -> Term\n  | Times : Term -> Term -> Term\n  | Minus : Term -> Term -> Term\n  | Choose : Identifier -> Term -> Term.\n\nEnd AddBool.\n\n(* --- What's new? --- *)\n\n(*\n * To capture the new information, the first thing we are going to do is split\n * extended AddBool type in half: the left projection and the right projection,\n * essentially. We should be able to produce these automatically, I believe,\n * but for now let's write them manually.\n *)\n\n(*\n * The left projection is straightforward---just use the same structure as\n * the old type, but index by the new type. I think Conor McBride said this\n * is the reornament.\n *)\nInductive no_bools : AddBool.Term -> Type :=\n| nb1 : forall i, no_bools (AddBool.Var i)\n| nb2 : forall t1 t2, no_bools t1 -> no_bools t2 -> no_bools (AddBool.Eq t1 t2)\n| nb3 : forall z, no_bools (AddBool.Int z)\n| nb4 : forall t1 t2, no_bools t1 -> no_bools t2 -> no_bools (AddBool.Plus t1 t2)\n| nb5 : forall t1 t2, no_bools t1 -> no_bools t2 -> no_bools (AddBool.Times t1 t2)\n| nb6 : forall t1 t2, no_bools t1 -> no_bools t2 -> no_bools (AddBool.Minus t1 t2)\n| nb7 : forall a t, no_bools t -> no_bools (AddBool.Choose a t).\n\n(*\n * The right projection needs to handle the new case, plus all of the inductive\n * cases that may refer to the new case. There is some case explosion here\n * that we will need to make induction useful.\n *)\nInductive yes_bools : AddBool.Term -> Type :=\n| yb1 : forall b, yes_bools (AddBool.Bool b)\n| yb2left : forall t1, yes_bools t1 -> forall t2 : sigT no_bools, yes_bools (AddBool.Eq t1 (projT1 t2))\n| yb2right : forall t1 : sigT no_bools, forall t2, yes_bools t2 -> yes_bools (AddBool.Eq (projT1 t1) t2)\n| yb2 : forall t1 t2, yes_bools t1 -> yes_bools t2 -> yes_bools (AddBool.Eq t1 t2)\n| yb3left : forall t1, yes_bools t1 -> forall t2 : sigT no_bools, yes_bools (AddBool.Plus t1 (projT1 t2))\n| yb3right : forall t1 : sigT no_bools, forall t2, yes_bools t2 -> yes_bools (AddBool.Plus (projT1 t1) t2)\n| yb3 : forall t1 t2, yes_bools t1 -> yes_bools t2 -> yes_bools (AddBool.Plus t1 t2)\n| yb4left : forall t1, yes_bools t1 -> forall t2 : sigT no_bools, yes_bools (AddBool.Times t1 (projT1 t2))\n| yb4right : forall t1 : sigT no_bools, forall t2, yes_bools t2 -> yes_bools (AddBool.Times (projT1 t1) t2)\n| yb4 : forall t1 t2, yes_bools t1 -> yes_bools t2 -> yes_bools (AddBool.Times t1 t2)\n| yb5left : forall t1, yes_bools t1 -> forall t2 : sigT no_bools, yes_bools (AddBool.Minus t1 (projT1 t2))\n| yb5right : forall t1 : sigT no_bools, forall t2, yes_bools t2 -> yes_bools (AddBool.Minus (projT1 t1) t2)\n| yb5 : forall t1 t2, yes_bools t1 -> yes_bools t2 -> yes_bools (AddBool.Minus t1 t2)\n| yb6 : forall a t, yes_bools t -> yes_bools (AddBool.Choose a t).\n\n(*\n * The idea is that:\n * 1. New.Term is equivalent to sigT no_bools.\n * 2. There exists some non-indexed type Diff that is equivalent to sigT yes_bools.\n * 3. AddBool.Term is equivalent to sigT no_bools + sigT yes_bools.\n * 4. Thus, New.Term + Diff is equivalent to AddBool.Term.\n *\n * We are going to start by finding the ornaments that get us 1 and 2.\n *)\n\n(* --- 1. New.Term is equivalent to sigT no_bools --- *)\n\n(*\n * This is easy.\n * The left projection no_bools is an ornament. So we can easily do this:\n *)\nRepair Module New.Term no_bools in NewProofs as NoBoolProofs.\n(*\n * This proves the equivalence, and gives us all functions and proofs over\n * sigT no_bools.\n *)\n\n(* --- 2. There exists some non-indexed type Diff that is equivalent to sigT yes_bools --- *)\n\n(*\n * yes_bools must be the reornament of something.\n * We can just go in and remove the index.\n *)\nInductive Diff : Type :=\n| DiffBool : bool -> Diff\n| DiffEqLeft : Diff -> sigT no_bools -> Diff\n| DiffEqRight : sigT no_bools -> Diff -> Diff\n| DiffEq : Diff -> Diff -> Diff\n| DiffPlusLeft : Diff -> sigT no_bools -> Diff\n| DiffPlusRight : sigT no_bools -> Diff -> Diff\n| DiffPlus : Diff -> Diff -> Diff\n| DiffTimesLeft : Diff -> sigT no_bools -> Diff\n| DiffTimesRight : sigT no_bools -> Diff -> Diff\n| DiffTimes : Diff -> Diff -> Diff\n| DiffMinusLeft : Diff -> sigT no_bools -> Diff\n| DiffMinusRight : sigT no_bools -> Diff -> Diff\n| DiffMinus : Diff -> Diff -> Diff\n| DiffChoose : Identifier -> Diff -> Diff.\n\n(*\n * Let's prove things over diff and port it to yes_bools.\n * For now, we will leave EpsilonLogic alone.\n * We'll deal with that later, since it involves extending a second type.\n * I just want to see what happens to our simple functions.\n *)\nModule DiffProofs_fix.\n\nFixpoint identity (d : Diff) : Diff :=\n  match d with\n  | DiffBool b => DiffBool b\n  | DiffEqLeft t1 t2 => DiffEqLeft (identity t1) (NoBoolProofs.identity t2)\n  | DiffEqRight t1 t2 => DiffEqRight (NoBoolProofs.identity t1) (identity t2)\n  | DiffEq t1 t2 => DiffEq (identity t1) (identity t2)\n  | DiffPlusLeft t1 t2 => DiffPlusLeft (identity t1) (NoBoolProofs.identity t2)\n  | DiffPlusRight t1 t2 => DiffPlusRight (NoBoolProofs.identity t1) (identity t2)\n  | DiffPlus t1 t2 => DiffPlus (identity t1) (identity t2)\n  | DiffTimesLeft t1 t2 => DiffTimesLeft (identity t1) (NoBoolProofs.identity t2)\n  | DiffTimesRight t1 t2 => DiffTimesRight (NoBoolProofs.identity t1) (identity t2)\n  | DiffTimes t1 t2 => DiffTimes (identity t1) (identity t2)\n  | DiffMinusLeft t1 t2 => DiffMinusLeft (identity t1) (NoBoolProofs.identity t2)\n  | DiffMinusRight t1 t2 => DiffMinusRight (NoBoolProofs.identity t1) (identity t2)\n  | DiffMinus t1 t2 => DiffMinus (identity t1) (identity t2)\n  | DiffChoose i t => DiffChoose i (identity t)\n  end.\n\nFixpoint free_vars (d : Diff) : list Identifier :=\n  match d with\n  | DiffBool b => []\n  | DiffEqLeft t1 t2 => free_vars t1 ++ NoBoolProofs.free_vars t2\n  | DiffEqRight t1 t2 => NoBoolProofs.free_vars t1 ++ free_vars t2\n  | DiffEq t1 t2 => free_vars t1 ++ free_vars t2\n  | DiffPlusLeft t1 t2 => free_vars t1 ++ NoBoolProofs.free_vars t2\n  | DiffPlusRight t1 t2 => NoBoolProofs.free_vars t1 ++ free_vars t2\n  | DiffPlus t1 t2 => free_vars t1 ++ free_vars t2\n  | DiffTimesLeft t1 t2 => free_vars t1 ++ NoBoolProofs.free_vars t2\n  | DiffTimesRight t1 t2 => NoBoolProofs.free_vars t1 ++ free_vars t2\n  | DiffTimes t1 t2 => free_vars t1 ++ free_vars t2\n  | DiffMinusLeft t1 t2 => free_vars t1 ++ NoBoolProofs.free_vars t2\n  | DiffMinusRight t1 t2 => NoBoolProofs.free_vars t1 ++ free_vars t2\n  | DiffMinus t1 t2 => free_vars t1 ++ free_vars t2\n  | DiffChoose x t =>\n      filter (fun y => if id_eq_dec x y then false else true) (free_vars t)\n  end.\n\nEnd DiffProofs_fix.\n\nPreprocess Module DiffProofs_fix as DiffProofs {\n  opaque\n    Coq.Init.Datatypes Coq.Strings.String Coq.Init.Logic Coq.Lists.List\n}.\n\n(*\n * OK, then we port that to yes_bools:\n *)\nRepair Module Diff yes_bools in DiffProofs as YesBoolProofs.\n(*\n * Now we have proofs over sigT yes_bools.\n *)\n\n(* --- 3. AddBool.Term is equivalent to sigT no_bools + sigT yes_bools --- *)\n\n(*\n * We'll need a manual configuration for this one.\n * We'll start with a slow eliminator, and think about a fast eliminator later.\n * First we'll need this (should also be easy to automate at some point):\n *)\nLemma split:\n  forall (t : AddBool.Term), no_bools t + yes_bools t.\nProof.\n  intros. induction t.\n  - left. constructor.\n  - right. constructor.\n  - induction IHt1, IHt2.\n    + left. constructor; auto.\n    + right. apply (yb2right (existT _ t1 a) t2 y).\n    + right. apply (yb2left t1 b (existT _ t2 n)).\n    + right. constructor; auto.\n  - left. constructor.\n  - induction IHt1, IHt2.\n    + left. constructor; auto.\n    + right. apply (yb3right (existT _ t1 a) t2 y).\n    + right. apply (yb3left t1 b (existT _ t2 n)).\n    + right. constructor; auto.\n  - induction IHt1, IHt2.\n    + left. constructor; auto.\n    + right. apply (yb4right (existT _ t1 a) t2 y).\n    + right. apply (yb4left t1 b (existT _ t2 n)).\n    + right. constructor; auto.\n  - induction IHt1, IHt2.\n    + left. constructor; auto.\n    + right. apply (yb5right (existT _ t1 a) t2 y).\n    + right. apply (yb5left t1 b (existT _ t2 n)).\n    + right. constructor; auto.\n  - induction IHt.\n    + left. constructor. auto.\n    + right. constructor. auto.\nDefined.\n\nLemma split_OK_left:\n  forall (t : AddBool.Term) (H : no_bools t),\n    inl H = split t.\nProof.\n  intros. induction H; auto; simpl.\n  - rewrite <- IHno_bools1. rewrite <- IHno_bools2. auto.\n  - rewrite <- IHno_bools1. rewrite <- IHno_bools2. auto.\n  - rewrite <- IHno_bools1. rewrite <- IHno_bools2. auto.\n  - rewrite <- IHno_bools1. rewrite <- IHno_bools2. auto.\n  - rewrite <- IHno_bools. auto.\nDefined.\n\nLemma split_OK_right:\n  forall (t : AddBool.Term) (H : yes_bools t),\n    inr H = split t.\nProof.\n  intros. induction H; auto; simpl.\n  - induction t2. simpl.\n    rewrite <- IHyes_bools. rewrite <- split_OK_left with (H := p). auto.\n  - induction t1. simpl.\n    rewrite <- IHyes_bools. rewrite <- split_OK_left with (H := p). auto.\n  - rewrite <- IHyes_bools1. rewrite <- IHyes_bools2. auto.\n  - induction t2. simpl.\n    rewrite <- IHyes_bools. rewrite <- split_OK_left with (H := p). auto.\n  - induction t1. simpl.\n    rewrite <- IHyes_bools. rewrite <- split_OK_left with (H := p). auto.\n  - rewrite <- IHyes_bools1. rewrite <- IHyes_bools2. auto.\n  - induction t2. simpl.\n    rewrite <- IHyes_bools. rewrite <- split_OK_left with (H := p). auto.\n  - induction t1. simpl.\n    rewrite <- IHyes_bools. rewrite <- split_OK_left with (H := p). auto.\n  - rewrite <- IHyes_bools1. rewrite <- IHyes_bools2. auto.\n  - induction t2. simpl.\n    rewrite <- IHyes_bools. rewrite <- split_OK_left with (H := p). auto.\n  - induction t1. simpl.\n    rewrite <- IHyes_bools. rewrite <- split_OK_left with (H := p). auto.\n  - rewrite <- IHyes_bools1. rewrite <- IHyes_bools2. auto.\n  - rewrite <- IHyes_bools. auto.\nDefined.\n\n(*\n * Configuration follows easily.\n *)\nDefinition A : Type := sigT no_bools + sigT yes_bools.\nDefinition B : Type := AddBool.Term.\n\nDefinition dep_constr_A_0 (s : sigT no_bools) : A := inl s.\nDefinition dep_constr_A_1 (s : sigT yes_bools) : A := inr s.\n\nDefinition dep_constr_B_0 (s : sigT no_bools) : B := projT1 s.\nDefinition dep_constr_B_1 (s : sigT yes_bools) : B := projT1 s.\n\nDefinition eta_A (a : A) : A := a.\nDefinition eta_B (b : B) : B := b.\n\nProgram Definition dep_elim_A (P : A -> Type)\n  (f0 : forall s, P (dep_constr_A_0 s))\n  (f1 : forall s, P (dep_constr_A_1 s))\n  (a : A)\n: P a.\nProof.\n  induction a; auto.\nDefined.\n\nProgram Definition dep_elim_B (P : B -> Type)\n  (f0 : forall s, P (dep_constr_B_0 s))\n  (f1 : forall s, P (dep_constr_B_1 s))\n  (b : B)\n: P b.\nProof.\n  induction (split b).\n  - apply (f0 (existT _ b a)).\n  - apply (f1 (existT _ b b0)).\nDefined.\n\nProgram Definition iota_A_0 P f0 f1 s (Q : P (dep_constr_A_0 s) -> Type)\n: Q (dep_elim_A P f0 f1 (dep_constr_A_0 s)) -> Q (f0 s).\nProof.\n  intros. apply X.\nDefined.\n\nProgram Definition iota_A_1 P f0 f1 s (Q : P (dep_constr_A_1 s) -> Type)\n: Q (dep_elim_A P f0 f1 (dep_constr_A_1 s)) -> Q (f1 s).\nProof.\n  intros. apply X.\nDefined.\n\nProgram Definition iota_B_0 P f0 f1 s (Q : P (dep_constr_B_0 s) -> Type)\n: Q (dep_elim_B P f0 f1 (dep_constr_B_0 s)) -> Q (f0 s).\nProof.\n  intros. unfold dep_constr_B_0 in *. unfold dep_elim_B in X. \n  induction s. simpl in X.\n  rewrite <- (split_OK_left x p) in X. apply X.\nDefined.\n\nProgram Definition iota_B_1 P f0 f1 s (Q : P (dep_constr_B_1 s) -> Type)\n: Q (dep_elim_B P f0 f1 (dep_constr_B_1 s)) -> Q (f1 s).\nProof.\n  intros. unfold dep_constr_B_1 in *. unfold dep_elim_B in X.\n  induction s. simpl in X.\n  rewrite <- (split_OK_right x p) in X. apply X.\nDefined.\n\nProgram Definition f : A -> B.\nProof.\n  intros a. apply dep_elim_A with (P := fun _ => B); intros.\n  - apply (dep_constr_B_0 s).\n  - apply (dep_constr_B_1 s).\n  - apply a.\nDefined.\n\nProgram Definition g : B -> A.\nProof.\n  intros b. apply dep_elim_B with (P := fun _ => A); intros.\n  - apply (dep_constr_A_0 s).\n  - apply (dep_constr_A_1 s).\n  - apply b.\nDefined.\n\nSave equivalence A B { promote = f; forget = g }.\nConfigure Lift A B {\n  constrs_a = dep_constr_A_0 dep_constr_A_1;\n  constrs_b = dep_constr_B_0 dep_constr_B_1;\n  elim_a = dep_elim_A;\n  elim_b = dep_elim_B;\n  eta_a = eta_A;\n  eta_b = eta_B;\n  iota_a = iota_A_0 iota_A_1;\n  iota_b = iota_B_0 iota_B_1\n}.\n\n(*\n * Then we can write:\n *)\nModule SumProofs.\n\nProgram Definition identity (a : A) : A.\nProof.\n  apply dep_elim_A with (P := fun _ => A); intros.\n  - apply dep_constr_A_0. apply NoBoolProofs.identity. apply s.\n  - apply dep_constr_A_1. apply YesBoolProofs.identity. apply s.\n  - apply a.\nDefined.\n\nProgram Definition free_vars (a : A) : list Identifier.\nProof.\n  apply dep_elim_A with (P := fun _ => list Identifier); intros.\n  - apply NoBoolProofs.free_vars. apply s.\n  - apply YesBoolProofs.free_vars. apply s.\n  - apply a.\nDefined.\n\nEnd SumProofs.\n\nRepair Module A B in NoBoolProofs as NoBoolProofs'.\nRepair Module A B in YesBoolProofs as YesBoolProofs'.\nRepair Module A B in SumProofs as AddBoolProofs.\n\nPrint AddBoolProofs.identity.\nPrint AddBoolProofs.free_vars.\n\n(*\n * This works, but it gives you slow functions!\n * It does separate out the new information, though, and guarantee preservation\n * of the old behavior:\n *)\nModule Manual.\n\nImport AddBool.\n\n  Fixpoint identity (t : Term) : Term :=\n  match t with\n  | Var x => Var x\n  | Int i => Int i\n  | Bool b => Bool b\n  | Eq a b => Eq (identity a) (identity b)\n  | Plus a b => Plus (identity a) (identity b)\n  | Times a b => Times (identity a) (identity b)\n  | Minus a b => Minus (identity a) (identity b)\n  | Choose x P => Choose x (identity P)\n  end.\n\nFixpoint free_vars (t : Term) : list Identifier :=\n  match t with\n  | Var x => [x]\n  | Int _ => []\n  | Bool _ => []\n  | Eq a b => free_vars a ++ free_vars b\n  | Plus a b => free_vars a ++ free_vars b\n  | Times a b => free_vars a ++ free_vars b\n  | Minus a b => free_vars a ++ free_vars b\n  | Choose x P =>\n      filter (fun y => if id_eq_dec x y then false else true) (free_vars P)\n  end.\n\nEnd Manual.\n\nLemma identity_OK:\n  forall t, AddBoolProofs.identity t = Manual.identity t.\nProof.\n  intros t. induction t; auto; simpl.\n  - rewrite <- IHt1. rewrite <- IHt2.\n    unfold AddBoolProofs.identity. simpl.\n    induction (split t1), (split t2); reflexivity.\n  - rewrite <- IHt1. rewrite <- IHt2.\n    unfold AddBoolProofs.identity. simpl.\n    induction (split t1), (split t2); reflexivity.\n  - rewrite <- IHt1. rewrite <- IHt2.\n    unfold AddBoolProofs.identity. simpl.\n    induction (split t1), (split t2); reflexivity.\n  - rewrite <- IHt1. rewrite <- IHt2.\n    unfold AddBoolProofs.identity. simpl.\n    induction (split t1), (split t2); reflexivity.\n  - rewrite <- IHt.\n    unfold AddBoolProofs.identity. simpl.\n    induction (split t); reflexivity.\nDefined.\n\nLemma free_vars_OK:\n  forall t, AddBoolProofs.free_vars t = Manual.free_vars t.\nProof.\n  intros t. induction t; auto; simpl.\n  - rewrite <- IHt1. rewrite <- IHt2.\n    unfold AddBoolProofs.free_vars. simpl.\n    induction (split t1), (split t2); reflexivity.\n  - rewrite <- IHt1. rewrite <- IHt2.\n    unfold AddBoolProofs.free_vars. simpl.\n    induction (split t1), (split t2); reflexivity.\n  - rewrite <- IHt1. rewrite <- IHt2.\n    unfold AddBoolProofs.free_vars. simpl.\n    induction (split t1), (split t2); reflexivity.\n  - rewrite <- IHt1. rewrite <- IHt2.\n    unfold AddBoolProofs.free_vars. simpl.\n    induction (split t1), (split t2); reflexivity.\n  - rewrite <- IHt.\n    unfold AddBoolProofs.free_vars. simpl.\n    induction (split t); reflexivity.\nDefined.\n\n(*\n * Can we get faster functions and proofs?\n * Let's try working directly with the final equivalence.\n *)\n\n(* --- 4. Thus, New.Term + Diff is equivalent to AddBool.Term --- *)\n\n(*\n * We already have slow correct functions.\n * Down here I'm exploring if we can get fast ones.\n * The developer effort to get fast ones here is way too high,\n * so I think the answer is for now, not reasonably, and getting\n * slow versions and checking correctness is the better use case.\n * There may be a better equivalence and configuration that gets you there,\n * or this may be a place to compose with another tool since it involves\n * a very different eliminator transformation.\n * \n * Still, you can look at this equivalence if you are interested.\n * Long-term, I think we're going to chain our work with CoqEAL or something\n * to handle this case efficiently.\n *)\n\nDefinition A' : Type := New.Term + Diff.\nDefinition B' : Type := AddBool.Term.\n\nProgram Definition dep_constr_A_0' (i : Identifier) : A'.\nProof.\n  left. apply (New.Var i).\nDefined.\nProgram Definition dep_constr_A_1' (b : bool) : A'.\nProof.\n  right. apply (DiffBool b).\nDefined.\nProgram Definition dep_constr_A_2' (a1 a2 : A') : A'.\nProof.\n  induction a1, a2.\n  - left. apply (New.Eq a t).\n  - right. apply DiffEqLeft; auto using NoBoolProofs.Term_to_no_bools.\n  - right. apply DiffEqRight; auto using NoBoolProofs.Term_to_no_bools.\n  - right. apply (DiffEq b d). \nDefined.\nProgram Definition dep_constr_A_3' (z : Z) : A'.\nProof.\n  left. apply (New.Int z).\nDefined.\nProgram Definition dep_constr_A_4' (a1 a2 : A') : A'.\nProof.\n  induction a1, a2.\n  - left. apply (New.Plus a t).\n  - right. apply DiffPlusLeft; auto using NoBoolProofs.Term_to_no_bools.\n  - right. apply DiffPlusRight; auto using NoBoolProofs.Term_to_no_bools.\n  - right. apply (DiffPlus b d). \nDefined.\nProgram Definition dep_constr_A_5' (a1 a2 : A') : A'.\nProof.\n  induction a1, a2.\n  - left. apply (New.Times a t).\n  - right. apply DiffTimesLeft; auto using NoBoolProofs.Term_to_no_bools.\n  - right. apply DiffTimesRight; auto using NoBoolProofs.Term_to_no_bools.\n  - right. apply (DiffTimes b d).  \nDefined.\nProgram Definition dep_constr_A_6' (a1 a2 : A') : A'.\nProof.\n  induction a1, a2.\n  - left. apply (New.Minus a t).\n  - right. apply DiffMinusLeft; auto using NoBoolProofs.Term_to_no_bools.\n  - right. apply DiffMinusRight; auto using NoBoolProofs.Term_to_no_bools.\n  - right. apply (DiffMinus b d).  \nDefined.\nProgram Definition dep_constr_A_7' (i : Identifier) (a : A') : A'.\nProof.\n  induction a.\n  - left. apply (New.Choose i a).\n  - right. apply DiffChoose; auto.\nDefined.\nDefinition dep_constr_B_0' := AddBool.Var.\nDefinition dep_constr_B_1' := AddBool.Bool.\nDefinition dep_constr_B_2' := AddBool.Eq.\nDefinition dep_constr_B_3' := AddBool.Int.\nDefinition dep_constr_B_4' := AddBool.Plus.\nDefinition dep_constr_B_5' := AddBool.Times.\nDefinition dep_constr_B_6' := AddBool.Minus.\nDefinition dep_constr_B_7' := AddBool.Choose.\n\nDefinition eta_A' (a : A') : A' := a. (* should probably expand for real *)\nDefinition eta_B' (b : B') : B' := b.\n\nLemma dep_elim_A' (P : A' -> Type)\n  (f0 : forall i : Identifier, P (dep_constr_A_0' i))\n  (f1 : forall b : bool, P (dep_constr_A_1' b))\n  (f2 : forall t : A', P t -> forall t0 : A', P t0 -> P (dep_constr_A_2' t t0))\n  (f3 : forall z : Z, P (dep_constr_A_3' z))\n  (f4 : forall t : A', P t -> forall t0 : A', P t0 -> P (dep_constr_A_4' t t0))\n  (f5 : forall t : A', P t -> forall t0 : A', P t0 -> P (dep_constr_A_5' t t0))\n  (f6 : forall t : A', P t -> forall t0 : A', P t0 -> P (dep_constr_A_6' t t0))\n  (f7 : forall (i : Identifier) (t : A'), P t -> P (dep_constr_A_7' i t))\n  (t : A')\n: P t.\nProof.\n  assert (forall a, P (inl a)).\n  - intros a. induction a.\n    + apply f0.\n    + apply (f2 (inl a1) IHa1 (inl a2) IHa2).\n    + apply f3.\n    + apply (f4 (inl a1) IHa1 (inl a2) IHa2).\n    + apply (f5 (inl a1) IHa1 (inl a2) IHa2).\n    + apply (f6 (inl a1) IHa1 (inl a2) IHa2).\n    + apply (f7 i (inl a) IHa).\n  - induction t; auto. induction b.\n    + apply f1.\n    + rewrite <- (NoBoolProofs.Term_to_no_bools_retraction s).\n      apply (f2 (inl (NoBoolProofs.Term_to_no_bools_inv s)) (X (NoBoolProofs.Term_to_no_bools_inv s)) (inr b) IHb ).\n    + rewrite <- (NoBoolProofs.Term_to_no_bools_retraction s).\n      apply (f2 (inr b) IHb (inl (NoBoolProofs.Term_to_no_bools_inv s)) (X (NoBoolProofs.Term_to_no_bools_inv s))).\n    + apply (f2 (inr b1) IHb1 (inr b2) IHb2).\n    + rewrite <- (NoBoolProofs.Term_to_no_bools_retraction s).\n      apply (f4 (inl (NoBoolProofs.Term_to_no_bools_inv s)) (X (NoBoolProofs.Term_to_no_bools_inv s)) (inr b) IHb ).\n    + rewrite <- (NoBoolProofs.Term_to_no_bools_retraction s).\n      apply (f4 (inr b) IHb (inl (NoBoolProofs.Term_to_no_bools_inv s)) (X (NoBoolProofs.Term_to_no_bools_inv s))).\n    + apply (f4 (inr b1) IHb1 (inr b2) IHb2).\n    + rewrite <- (NoBoolProofs.Term_to_no_bools_retraction s).\n      apply (f5 (inl (NoBoolProofs.Term_to_no_bools_inv s)) (X (NoBoolProofs.Term_to_no_bools_inv s)) (inr b) IHb ).\n    + rewrite <- (NoBoolProofs.Term_to_no_bools_retraction s).\n      apply (f5 (inr b) IHb (inl (NoBoolProofs.Term_to_no_bools_inv s)) (X (NoBoolProofs.Term_to_no_bools_inv s))).\n    + apply (f5 (inr b1) IHb1 (inr b2) IHb2).\n    + rewrite <- (NoBoolProofs.Term_to_no_bools_retraction s).\n      apply (f6 (inl (NoBoolProofs.Term_to_no_bools_inv s)) (X (NoBoolProofs.Term_to_no_bools_inv s)) (inr b) IHb ).\n    + rewrite <- (NoBoolProofs.Term_to_no_bools_retraction s).\n      apply (f6 (inr b) IHb (inl (NoBoolProofs.Term_to_no_bools_inv s)) (X (NoBoolProofs.Term_to_no_bools_inv s))).\n    + apply (f6 (inr b1) IHb1 (inr b2) IHb2).\n    + apply (f7 i (inr b) IHb).\nDefined.\n\nDefinition dep_elim_B' := AddBool.Term_rect.\n\nDefinition section_adjoint := Adjoint.fg_id' NoBoolProofs.Term_to_no_bools_inv NoBoolProofs.Term_to_no_bools NoBoolProofs.Term_to_no_bools_retraction NoBoolProofs.Term_to_no_bools_section.\n\nLemma is_adjoint a : NoBoolProofs.Term_to_no_bools_retraction (NoBoolProofs.Term_to_no_bools a) = f_equal NoBoolProofs.Term_to_no_bools (section_adjoint a).\nProof.\n  apply Adjoint.g_adjoint.\nDefined.\n\nProgram Definition iota_A_0' P f0 f1 f2 f3 f4 f5 f6 f7 i Q\n: Q (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_A_0' i)) ->\n  Q (f0 i).\nProof.\n  intros. auto.\nDefined.\n\nProgram Definition iota_B_0' P f0 f1 f2 f3 f4 f5 f6 f7 i Q\n: Q (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_B_0' i)) ->\n  Q (f0 i).\nProof.\n  intros. auto.\nDefined.\n\nProgram Definition iota_A_1' P f0 f1 f2 f3 f4 f5 f6 f7 b Q\n: Q (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_A_1' b)) ->\n  Q (f1 b).\nProof.\n  intros. auto.\nDefined.\n\nProgram Definition iota_B_1' P f0 f1 f2 f3 f4 f5 f6 f7 b Q\n: Q (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_B_1' b)) ->\n  Q (f1 b).\nProof.\n  intros. auto.\nDefined.\n\nLemma iota_A_2'_aux P f0 f1 f2 f3 f4 f5 f6 f7 a1 a2:\n  dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_A_2' a1 a2) =\n  f2 a1 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a1) a2 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a2).\nProof.\n  induction a1, a2; auto.\n  - simpl. rewrite is_adjoint. destruct (section_adjoint a). auto.\n  - simpl. rewrite is_adjoint. destruct (section_adjoint t). auto.\nDefined.\n\nProgram Definition iota_A_2' P f0 f1 f2 f3 f4 f5 f6 f7 a1 a2 Q\n: Q (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_A_2' a1 a2)) ->\n  Q (f2 a1 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a1) a2 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a2)).\nProof.\n  intros. rewrite <- iota_A_2'_aux. auto.\nDefined.\n\nProgram Definition iota_B_2' P f0 f1 f2 f3 f4 f5 f6 f7 b1 b2 Q\n: Q (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_B_2' b1 b2)) ->\n  Q (f2 b1 (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 b1) b2 (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 b2)).\nProof.\n  intros. auto.\nDefined.\n\nProgram Definition iota_A_3' P f0 f1 f2 f3 f4 f5 f6 f7 z Q\n: Q (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_A_3' z)) ->\n  Q (f3 z).\nProof.\n  intros. auto.\nDefined.\n\nProgram Definition iota_B_3' P f0 f1 f2 f3 f4 f5 f6 f7 z Q\n: Q (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_B_3' z)) ->\n  Q (f3 z).\nProof.\n  intros. auto.\nDefined.\n\nLemma iota_A_4'_aux P f0 f1 f2 f3 f4 f5 f6 f7 a1 a2:\n  dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_A_4' a1 a2) =\n  f4 a1 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a1) a2 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a2).\nProof.\n  induction a1, a2; auto.\n  - simpl. rewrite is_adjoint. destruct (section_adjoint a). auto.\n  - simpl. rewrite is_adjoint. destruct (section_adjoint t). auto.\nDefined.\n\nProgram Definition iota_A_4' P f0 f1 f2 f3 f4 f5 f6 f7 a1 a2 Q\n: Q (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_A_4' a1 a2)) ->\n  Q (f4 a1 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a1) a2 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a2)).\nProof.\n  intros. rewrite <- iota_A_4'_aux. auto.\nDefined.\n\nProgram Definition iota_B_4' P f0 f1 f2 f3 f4 f5 f6 f7 b1 b2 Q\n: Q (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_B_4' b1 b2)) ->\n  Q (f4 b1 (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 b1) b2 (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 b2)).\nProof.\n  intros. auto.\nDefined.\n\nLemma iota_A_5'_aux P f0 f1 f2 f3 f4 f5 f6 f7 a1 a2:\n  dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_A_5' a1 a2) =\n  f5 a1 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a1) a2 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a2).\nProof.\n  induction a1, a2; auto.\n  - simpl. rewrite is_adjoint. destruct (section_adjoint a). auto.\n  - simpl. rewrite is_adjoint. destruct (section_adjoint t). auto.\nDefined.\n\nProgram Definition iota_A_5' P f0 f1 f2 f3 f4 f5 f6 f7 a1 a2 Q\n: Q (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_A_5' a1 a2)) ->\n  Q (f5 a1 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a1) a2 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a2)).\nProof.\n  intros. rewrite <- iota_A_5'_aux. auto.\nDefined.\n\nProgram Definition iota_B_5' P f0 f1 f2 f3 f4 f5 f6 f7 b1 b2 Q\n: Q (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_B_5' b1 b2)) ->\n  Q (f5 b1 (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 b1) b2 (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 b2)).\nProof.\n  intros. auto.\nDefined.\n\nLemma iota_A_6'_aux P f0 f1 f2 f3 f4 f5 f6 f7 a1 a2:\n  dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_A_6' a1 a2) =\n  f6 a1 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a1) a2 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a2).\nProof.\n  induction a1, a2; auto.\n  - simpl. rewrite is_adjoint. destruct (section_adjoint a). auto.\n  - simpl. rewrite is_adjoint. destruct (section_adjoint t). auto.\nDefined.\n\nProgram Definition iota_A_6' P f0 f1 f2 f3 f4 f5 f6 f7 a1 a2 Q\n: Q (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_A_6' a1 a2)) ->\n  Q (f6 a1 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a1) a2 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a2)).\nProof.\n  intros. rewrite <- iota_A_6'_aux. auto.\nDefined.\n\nProgram Definition iota_B_6' P f0 f1 f2 f3 f4 f5 f6 f7 b1 b2 Q\n: Q (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_B_6' b1 b2)) ->\n  Q (f6 b1 (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 b1) b2 (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 b2)).\nProof.\n  intros. auto.\nDefined.\n\nProgram Definition iota_A_7' P f0 f1 f2 f3 f4 f5 f6 f7 i a Q\n: Q (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_A_7' i a)) ->\n  Q (f7 i a (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a)).\nProof.\n  intros. induction a; apply X.\nDefined.\n\nProgram Definition iota_B_7' P f0 f1 f2 f3 f4 f5 f6 f7 i b Q\n: Q (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_B_7' i b)) ->\n  Q (f7 i b (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 b)).\nProof.\n  intros. auto.\nDefined.\n\nProgram Definition f' : A' -> B'.\nProof.\n  intros a. apply dep_elim_A' with (P := fun _ => B'); intros.\n  - apply (dep_constr_B_0' i).\n  - apply (dep_constr_B_1' b).\n  - apply (dep_constr_B_2' X X0).\n  - apply (dep_constr_B_3' z).\n  - apply (dep_constr_B_4' X X0).\n  - apply (dep_constr_B_5' X X0).\n  - apply (dep_constr_B_6' X X0).\n  - apply (dep_constr_B_7' i X).\n  - apply a.\nDefined.\n\nProgram Definition g' : B' -> A'.\nProof.\n  intros b. apply dep_elim_B' with (P := fun _ => A'); intros.\n  - apply (dep_constr_A_0' i).\n  - apply (dep_constr_A_1' b0).\n  - apply (dep_constr_A_2' X X0).\n  - apply (dep_constr_A_3' z).\n  - apply (dep_constr_A_4' X X0).\n  - apply (dep_constr_A_5' X X0).\n  - apply (dep_constr_A_6' X X0).\n  - apply (dep_constr_A_7' i X).\n  - apply b.\nDefined.\n\nSave equivalence A' B' { promote = f'; forget = g' }.\nConfigure Lift A' B' {\n  constrs_a = dep_constr_A_0' dep_constr_A_1' dep_constr_A_2' dep_constr_A_3' dep_constr_A_4' dep_constr_A_5' dep_constr_A_6' dep_constr_A_7';\n  constrs_b = dep_constr_B_0' dep_constr_B_1' dep_constr_B_2' dep_constr_B_3' dep_constr_B_4' dep_constr_B_5' dep_constr_B_6' dep_constr_B_7';\n  elim_a = dep_elim_A';\n  elim_b = dep_elim_B';\n  eta_a = eta_A';\n  eta_b = eta_B';\n  iota_a = iota_A_0' iota_A_1' iota_A_2' iota_A_3' iota_A_4' iota_A_5' iota_A_6' iota_A_7';\n  iota_b = iota_B_0' iota_B_1' iota_B_2' iota_B_3' iota_B_4' iota_B_5' iota_B_6' iota_B_7'\n}.\n\n(*\n * But writing functions and proofs this way isn't any easier.\n * We can backport from the fast version to show equivalent terms exist,\n * at least, but nobody would ever want to write these directly.\n *)\nPreprocess Module Manual as Manual'.\nRepair Module B' A' in Manual' as Backported.\nPrint Backported.identity.\nPrint Backported.free_vars.\n(* there may be a different configuration that gets you there and isn't this hard, but I don't know it *)\n\n\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/playground/add_constr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.27806271582911357}}
{"text": "(* -*- coding: utf-8 -*- *)\n(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\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(* File Eqdep.v created by Christine Paulin-Mohring in Coq V5.6, May 1992 *)\n(* Abstraction with respect to the eq_rect_eq axiom and creation of\n   EqdepFacts.v by Hugo Herbelin, Mar 2006 *)\n\n(** This file axiomatizes the invariance by substitution of reflexive\n    equality proofs [[Streicher93]] and exports its consequences, such\n    as the injectivity of the projection of the dependent pair.\n\n    [[Streicher93]] T. Streicher, Semantical Investigations into\n    Intensional Type Theory, Habilitationsschrift, LMU München, 1993.\n*)\n\nRequire Export EqdepFacts.\n\nModule Eq_rect_eq.\n\nAxiom eq_rect_eq :\n  forall (U:Type) (p:U) (Q:U -> Type) (x:Q p) (h:p = p), x = eq_rect p Q x p h.\n\nEnd Eq_rect_eq.\n\nModule EqdepTheory := EqdepTheory(Eq_rect_eq).\nExport EqdepTheory.\n\n(** Exported hints *)\n\nHint Resolve eq_dep_eq: eqdep.\nHint Resolve inj_pair2 inj_pairT2: eqdep.\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/theories/Logic/Eqdep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.5234203489363239, "lm_q1q2_score": 0.2780458033387206}}
{"text": "(** * Definition of grammar for expressions involving parentheses and plus *)\nRequire Import Fiat.Parsers.ContextFreeGrammar.Notations.\n\nDefinition plus_expr_pregrammar : pregrammar Ascii.ascii :=\n  [[[ \"expr\" ::== \"pexpr\" || \"pexpr\" \"+\" \"expr\";;\n      \"pexpr\" ::== \"number\" || \"(\" \"expr\" \")\";;\n      \"number\" ::== [0-9] || [0-9] \"number\"\n  ]]].\n\nDefinition plus_expr_grammar : grammar Ascii.ascii := plus_expr_pregrammar.\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/Grammars/ExpressionNumPlusParen.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.27804579556953757}}
{"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.\nLocal Transparent Archi.ptr64.\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  | 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 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  | Ointuoffloat: operation             (**r [rd = unsigned_int_of_float(r1)] (PPC64 only) *)\n  | Ofloatofint: operation              (**r [rd = float_of_signed_int(r1)] (PPC64 only) *)\n  | Ofloatofintu: operation             (**r [rd = float_of_unsigned_int(r1)] (PPC64 only *)\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\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; 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 Ptrofs.eq_dec ident_eq Float.eq_dec Float32.eq_dec  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 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  | _, _ => 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  | 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  | Ointuoffloat, v1::nil => Val.intuoffloat v1\n  | Ofloatofint, v1::nil => Val.floatofint v1\n  | Ofloatofintu, v1::nil => Val.floatofintu 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  | _, _ => 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  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  | 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  | Ointuoffloat => (Tfloat :: nil, Tint)\n  | Ofloatofint => (Tint :: nil, Tfloat)\n  | Ofloatofintu => (Tint :: nil, Tfloat)\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  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  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; simpl in H0; inv H0. destruct (Float.to_intu f); inv H2...\n  destruct v0; simpl in H0; inv H0...\n  destruct v0; simpl in H0; inv H0...\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...\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  repeat (destruct vl; auto).\n  repeat (destruct vl; auto). destruct (Val.maskzero_bool v i) as [[]|]; auto.\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 op_depends_on_memory (op: operation) : bool :=\n  match op with\n  | Ocmp (Ccompu _) => true\n  | Ocmp (Ccompuimm _ _) => 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. unfold eval_condition.\n  destruct c; simpl; auto; try discriminate.\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.\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; 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; simpl in H1; inv H1. simpl. destruct (Float.to_intu f0); simpl in H2; inv H2.\n  exists (Vint i); auto.\n  inv H4; simpl in H1; inv H1; simpl. TrivialExists.\n  inv H4; simpl in H1; inv H1; simpl. TrivialExists.\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.\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 Zplus_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 : 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      is_rlw_mask_rec m (rlw_transition s (Z.odd x)) (Z.div2 x)\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": "CertiKOS", "repo": "SingleStackCompCert", "sha": "04eb987a8cc0f428365edaa4dffb2237d02d9500", "save_path": "github-repos/coq/CertiKOS-SingleStackCompCert", "path": "github-repos/coq/CertiKOS-SingleStackCompCert/SingleStackCompCert-04eb987a8cc0f428365edaa4dffb2237d02d9500/powerpc/Op.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2780350852806656}}
{"text": "Require Import Omega.\nRequire Import FJ_tactics.\nRequire Import cFJ.\nRequire Import Cast.\nRequire Import Interface.\nRequire Import Generic.\nRequire Import Generic_Interface.\nRequire Import Generic_Cast.\n\nRequire Import List.\nRequire Import Arith.\n\nDefinition CL := cFJ.CL nat.\n\nInductive Ty : Set :=\n| N_Wrap : N -> Ty \n| Gty : GTy nat -> Ty\n  with \n    N : Set :=\n| cFJ_N : cFJ.FJ_Ty nat (@GTy_ext Ty FJ_ty_ext) -> N\n| I_N_Wrap : I_Ty nat (@GTy_ext Ty unit) -> N.\n\nDefinition ty_ext := @GTy_ext Ty FJ_ty_ext.\nDefinition md_ext := @MD_ext nat N FJ_md_ext.\nDefinition mty_ext := @mty_ext nat N FJ_mty_ext.\nDefinition cld_ext := @Generic.cld_ext nat N (@I_cld_ext nat ty_ext unit).\nDefinition m_call_ext := @MCall_ext Ty FJ_m_call_ext.\nDefinition I_cld_ext := @I_cld_ext nat ty_ext unit.\n\nDefinition TyP_List := Generic.TyP_List nat N.\n\nInductive E : Set :=\n| cFJ_E : FJ_E nat nat nat nat ty_ext E m_call_ext -> E\n| Cast_E : Cast.Cast_E nat ty_ext E -> E.\n\nDefinition FD := cFJ.FD nat Ty.\nDefinition MD := cFJ.MD nat nat Ty E md_ext.\nDefinition MTy := cFJ.Mty Ty mty_ext.\nDefinition mb_ext := FJ_mb_ext.\nDefinition MB := cFJ.MB nat E mb_ext.\n\nDefinition L := cFJ.L nat nat nat nat ty_ext Ty E md_ext cld_ext.\n\nDefinition Abs_Mty := Interface.Abs_Mty Ty mty_ext nat nat.\n\nDefinition Interface_ext := @GInterface_ext nat N unit.\nDefinition Interface := Interface.Interface nat Ty mty_ext nat nat Interface_ext.\n\nVariable (CT : nat -> option L)\n  (IT : nat -> option Interface).\n\nDefinition I_Ty_Wrap I := N_Wrap (I_N_Wrap I).\nDefinition FJ_Ty_Wrap := Generic.FJ_Ty_Wrap Ty ty_ext nat N N_Wrap cFJ_N.\n\nFixpoint Ty_trans (ty : Ty) (txs : list nat) (tys : list Ty) : Ty :=\n  match ty with \n    | N_Wrap (cFJ_N ty) => FJ_Ty_Trans _ _ _ _ N N_Wrap cFJ_N (GJ_TE_Trans _ _ Ty_trans _) ty txs tys\n    | N_Wrap (I_N_Wrap ty) => I_Ty_Trans _ _ _ _ _ N_Wrap I_N_Wrap (GJ_TE_Trans _ _ Ty_trans _) ty txs tys\n    | Gty gty => GTy_trans _ (eq_nat_dec) _ Gty gty txs tys \n  end.\n\nDefinition N_trans (n : N) (txs : list nat) (tys : list Ty) : N :=\n  match n with \n    | cFJ_N (ty_def te c)  => cFJ_N (ty_def _ _ ((GJ_TE_Trans _ _ Ty_trans _) te txs tys) c)\n    | I_N_Wrap (ity_def te i) => I_N_Wrap (ity_def _ _ ((GJ_TE_Trans _ _ Ty_trans _) te txs tys) i)\n  end.\n\nVariable (Context : Set)\n  (TLookup : Context -> nat -> N -> Prop)\n  (Empty : Context).\n\nDefinition implements (ce : cld_ext) := @I_implements nat ty_ext FJ_cld_ext (@snd _ _ ce).\n\nDefinition build_te := @GJ_build_te _ _ N Ty_trans _ _ (fun (ice : I_cld_ext) te te' te''=>\n  FJ_build_te (snd ice) te te' te'').\n\nDefinition isub_build_te := build_te.\n\nInductive subtype : Context -> Ty -> Ty -> Prop :=\n| cFJ_sub : forall gamma ty ty', \n  cFJ.FJ_subtype nat nat nat nat _ Ty FJ_Ty_Wrap \n  E md_ext cld_ext CT Context subtype build_te gamma ty ty' -> subtype gamma ty ty'\n| GJ_sub : forall gamma ty ty', Generic.GJ_subtype _ _ Gty N N_Wrap _\n  TLookup gamma ty ty' -> subtype gamma ty ty'\n| I_subtype_Wrap : forall gamma ty ty', Interface.I_subtype nat ty_ext Ty I_Ty_Wrap _ _ _ _ _ _ _ _ CT \n  isub_build_te implements FJ_Ty_Wrap gamma ty ty' -> subtype gamma ty ty'.\n\nVariables (Update : Context -> Var nat -> Ty -> Context)\n  (TUpdate : Context -> nat -> N -> Context)\n  (lookup : Context -> Var nat -> Ty -> Prop)\n  (lookup_update_eq : forall gamma X ty, lookup (Update gamma X ty) X ty) \n  (lookup_update_neq : forall gamma Y X ty ty', lookup gamma X ty -> X <> Y -> \n    lookup (Update gamma Y ty') X ty)\n  (lookup_update_neq' : forall gamma Y X ty ty', lookup (Update gamma Y ty') X ty -> X <> Y -> \n    lookup gamma X ty)\n  (lookup_Empty : forall X ty, ~ lookup Empty X ty)\n  (lookup_id : forall gamma X ty ty', lookup gamma X ty -> lookup gamma X ty' -> ty = ty')\n  (app_context : Context -> Context -> Context)\n    (Lookup_dec : forall gamma x, (exists ty, lookup gamma x ty) \\/ (forall ty, ~ lookup gamma x ty))\n    (Lookup_app : forall gamma delta x ty, lookup gamma x ty -> lookup (app_context gamma delta) x ty)\n    (Lookup_app' : forall gamma delta x ty, (forall ty', ~ lookup gamma x ty') -> lookup delta x ty -> \n      lookup (app_context gamma delta) x ty).\n\n\n  Definition update_list := cFJ.update_list nat Ty Context Update.\n  Definition update_Tlist := Generic.update_Tlist nat N Context TUpdate.\n\n  Variables \n    (TLookup_unique : forall gamma X ty ty', TLookup gamma X ty -> TLookup gamma X ty' -> ty = ty')\n    (TLookup_dec : forall gamma X, (exists ty, TLookup gamma X ty) \\/ (forall ty, ~TLookup gamma X ty))\n    (TLookup_app : forall gamma delta X ty, TLookup gamma X ty -> TLookup (app_context gamma delta) X ty)\n    (TLookup_app' : forall gamma delta X ty, (forall ty', ~ TLookup gamma X ty') -> TLookup delta X ty -> \n      TLookup (app_context gamma delta) X ty)\n    (TLookup_app'' : forall gamma delta X ty, (forall ty', ~ TLookup gamma X ty') ->  \n      TLookup (app_context gamma delta) X ty -> TLookup delta X ty)\n    (TLookup_Empty : forall X ty, ~ TLookup Empty X ty)\n    (subst_context : Context -> list nat -> list Ty -> Context)\n    (subst_context_nil : forall delta Us, subst_context delta nil Us = delta)\n    (subst_context_nil' : forall delta Xs, subst_context delta Xs nil = delta)\n    (TLookup_subst : forall gamma X ty Xs Us, TLookup gamma X ty -> \n      TLookup (subst_context gamma Xs Us) X (N_trans ty Xs Us))\n    (TLookup_update_eq : forall gamma X ty, TLookup (TUpdate gamma X ty) X ty) \n    (TLookup_update_neq : forall gamma Y X ty ty', TLookup gamma X ty -> X <> Y -> \n      TLookup (TUpdate gamma Y ty') X ty) \n    (TLookup_update_neq' : forall gamma Y X ty ty', X <> Y -> \n      TLookup (TUpdate gamma Y ty') X ty -> TLookup gamma X ty).\n\nDefinition wf_object_ext := @GJ_wf_object_ext Ty Context unit.\n\nDefinition wf_class_ext' WF_Type := @GJ_wf_class_ext nat Ty _ N_Wrap Context subtype Ty_trans \n  WF_Type I_cld_ext FJ_ty_ext.\n\nDefinition wf_int_ext' WF_Type := \n  @Generic_Interface.I_wf_int_ext nat Ty N Context \n  WF_Type subtype Ty_trans N_Wrap unit FJ_ty_ext.\n\nInductive WF_Type : Context -> Ty -> Prop :=\n  cFJ_WF_Type : forall gamma ty, cFJ.FJ_WF_Type _ _ _ _ _ _ FJ_Ty_Wrap\n    _ _ _ CT Context (wf_class_ext' WF_Type) wf_object_ext gamma ty -> WF_Type gamma ty\n| GJ_WF_Type : forall gamma ty, GJ_WF_Type _ _ Gty _ _ TLookup gamma ty -> WF_Type gamma ty\n| I_WF_Type_Wrap : forall gamma ty, Interface.I_WF_Type nat ty_ext Ty\n   I_Ty_Wrap mty_ext nat nat Interface_ext Context IT (wf_int_ext' WF_Type) gamma ty ->\n  WF_Type gamma ty.\n\nDefinition wf_class_ext := wf_class_ext' WF_Type.\nDefinition wf_int_ext := wf_int_ext' WF_Type.\n\nDefinition fields_build_te (ce : cld_ext) (te te' te'' : ty_ext) := \n  Generic.fields_build_te nat Ty _ Ty_trans (fun ice => FJ_fields_build_te (snd ice)) ce te te' te''.\n\nDefinition fields_build_tys (te : ty_ext) (ce : cld_ext) (tys tys' : list Ty) :=\n  Generic.fields_build_tys nat Ty _ Ty_trans \n  (fun te ice tys tys' => FJ_fields_build_tys Ty te (snd ice) tys tys') te ce tys tys'.\n\nInductive fields : Context -> Ty -> list FD -> Prop :=\n  FJ_fields : forall gamma ty fds, cFJ.FJ_fields _ _ _ _ _ Ty FJ_Ty_Wrap _ _ _\n    CT Context fields fields_build_te fields_build_tys gamma ty fds -> fields gamma ty fds.\n\nDefinition mtype_build_te (ce : cld_ext) (te te' te'' : ty_ext) :=\n  Generic.mtype_build_te nat Ty _ Ty_trans \n  (fun (ice : I_cld_ext) te te' te'' => FJ_mtype_build_te (snd ice) te te' te'') ce te te' te''.\n\nVariable build_fresh : list Ty -> Ty -> list Ty -> list nat -> TyP_List -> list nat -> Prop.\n\nDefinition mtype_build_tys (ce : cld_ext) (te : ty_ext) (ty : Ty) vds (mce : md_ext) (tys tys' : list Ty) :=\n  Generic.mtype_build_tys _ _ Gty _ Ty_trans _ build_fresh \n  (fun ice te ty vds mce tys tys' => FJ_mtype_build_tys nat _ (snd ice) te ty vds mce tys tys') \n  ce te ty vds mce tys tys'.\n\nDefinition N_Trans typs Us ty : N := N_trans ty (Extract_TyVar nat N typs) Us.\n\nDefinition mtype_build_mtye (ce : cld_ext) (te : ty_ext) (ty : Ty) vds (me : md_ext) (mtye : mty_ext) :=\n  Generic.mtype_build_mtye nat Ty Gty N nat build_fresh N_Trans (fun ce te me ty vds (mtye : unit) => True) \n  ce te ty vds me mtye.\n\nDefinition imtype_build_tys := imtype_build_tys nat Ty nat N Gty Ty_trans FJ_mty_ext build_fresh\n  (Interface.I_imtype_build_tys FJ_ty_ext Ty nat FJ_Interface_ext).\n\nDefinition imtype_build_mtye := imtype_build_mtye nat Ty _ N Gty FJ_mty_ext build_fresh\n  N_Trans (Interface.I_imtype_build_mtye FJ_ty_ext Ty FJ_mty_ext nat FJ_Interface_ext).\n\nInductive mtype : Context -> nat -> Ty -> MTy -> Prop :=\n| FJ_mtype : forall gamma m ty mty, cFJ.FJ_mtype _ _ _ _ _ Ty FJ_Ty_Wrap\n    _ _ _ _ CT Context mtype mtype_build_te \n    mtype_build_tys mtype_build_mtye gamma m ty mty -> mtype gamma m ty mty\n| I_mtype_Wrap : forall gamma m ty mty, Interface.I_mtype nat ty_ext Ty I_Ty_Wrap \n  mty_ext nat nat Interface_ext Context IT imtype_build_tys imtype_build_mtye gamma m ty mty ->\n  mtype gamma m ty mty.\n\nDefinition mbody_build_te (ce : cld_ext) (te te' te'' : ty_ext) :=\n  Generic.mbody_build_te _ Ty _ Ty_trans (fun ice te te' te'' => FJ_mbody_build_te (snd ice) te te' te'') \n  ce te te' te''.\n\nDefinition VD := VD Ty nat.\n\nDefinition mbody_m_call_map (XNs : TyP_List) (Us : list Ty) (mce mce': m_call_ext) :=\n  Generic.GJ_mbody_m_call_map nat Ty N Ty_trans _ XNs Us mce mce'.\n\nDefinition mbody_new_map (XNs : TyP_List) (Us : list Ty) (mce mce': m_call_ext) :=\n  Generic.GJ_mbody_new_map nat Ty N Ty_trans _ XNs Us mce mce'. \n\nInductive E_Ty_Trans : TyP_List -> list Ty -> E -> E -> Prop :=\n| Base_E_Ty_Trans : forall XNs Us e e', Generic.E_Ty_Trans _ _ _ _ _ _ _ _ _ _ cFJ_E mbody_m_call_map\n  mbody_new_map E_Ty_Trans XNs Us e e' -> E_Ty_Trans XNs Us e e'\n| Cast_E_Ty_Trans : forall XNs Us e e', \n  Generic_Cast.E_Ty_Trans _ _ Ty ty_ext E _ Cast_E (GJ_TE_Trans _ _ Ty_trans _) E_Ty_Trans XNs Us e e' ->\n  E_Ty_Trans XNs Us e e'.\n\nDefinition map_mbody : cld_ext -> ty_ext -> m_call_ext -> md_ext -> E -> E -> Prop :=\n  Generic.map_mbody _ _ _ _ _ _ _ _ E_Ty_Trans.\n\nDefinition build_mb_ext (ce : cld_ext) (te : ty_ext) (mce : m_call_ext) (mde : md_ext) := \n  Generic.build_mb_ext _ _ _ _ _ _ _ _ (fun ce te mce mde => FJ_build_mb_ext (snd ce) te mce mde)\n  ce te mce mde.\n\nInductive mbody : Context -> m_call_ext -> nat -> Ty -> MB -> Prop :=\n  FJ_mbody : forall gamma Vs m ct mb, cFJ.mbody _ _ _ _ _ Ty \n    (Generic.FJ_Ty_Wrap Ty ty_ext nat N N_Wrap cFJ_N) _ _ _ _ CT _ mbody_build_te \n    mb_ext (fun ce te mce mde mbe => True) map_mbody gamma Vs m ct mb -> mbody gamma Vs m ct mb.\n\nInductive Bound : Context -> Ty -> Ty -> Prop :=\n| GJ_Bound : forall gamma ty ty', Generic.GJ_Bound nat _ Gty N _ TLookup gamma ty ty' ->\n    Bound gamma ty (N_Wrap ty')\n| N_Bound : forall gamma ty ty', Generic.N_Bound _ _ N_Wrap _ gamma ty ty' -> Bound gamma ty ty'.\n\nDefinition WF_mtype_Us_map : Context -> m_call_ext -> mty_ext -> list Ty -> list Ty -> Prop := \n  GJ_WF_mtype_Us_map _ _ _ _ Ty_trans _ _ (FJ_WF_mtype_Us_map Ty Context).\n\nDefinition WF_mtype_U_map : Context -> m_call_ext -> mty_ext -> Ty -> Ty -> Prop :=\n  GJ_WF_mtype_U_map _ _ _ _ Ty_trans _ _ (FJ_WF_mtype_U_map Ty Context).\n\nDefinition WF_mtype_ext (gamma : Context) (mce : m_call_ext) (mtye : mty_ext) :=\n  GJ_WF_mtype_ext _ _ _ N_Wrap _ subtype Ty_trans WF_Type _ _ \n  (FJ_WF_mtype_ext _) gamma mce mtye.\n\nInductive E_WF : Context -> E -> Ty -> Prop :=\n  FJ_E_WF : forall gamma e ty, cFJ.FJ_E_WF _ _ _ _ _ Ty FJ_Ty_Wrap _ _ cFJ_E mty_ext Context subtype WF_Type\n    fields mtype E_WF lookup Bound Bound WF_mtype_Us_map WF_mtype_U_map \n    WF_mtype_ext Empty gamma e ty -> E_WF gamma e ty\n| Cast_E_WF : forall gamma e ty, \n  Cast.Cast_E_WF _ _ _ \n  (Generic.FJ_Ty_Wrap Ty ty_ext nat N N_Wrap cFJ_N) _ _ Cast_E E_WF Bound subtype gamma e ty ->\n  E_WF gamma e ty.\n\nDefinition ce_build_cte : cld_ext -> ty_ext -> Prop :=\n  Generic.GJ_ce_build_cte _ Ty Gty _ (fun ce te => True).\n\nDefinition Meth_build_context : cld_ext -> md_ext -> Context -> Context -> Prop :=\n  Generic.GJ_build_context _ N Context TUpdate (fun \n    (ice : I_cld_ext) mde gamma gamma' => FJ_Meth_build_context _ (snd ice) mde gamma gamma').\n\nDefinition Meth_WF_Ext : Context -> cld_ext -> md_ext -> Prop :=\n  Generic.GJ_Meth_WF_Ext _ _ N N_Wrap Context WF_Type \n  (fun gamma (fcld : _) => cFJ.FJ_Meth_WF_Ext Context gamma (snd fcld)).\n\nInductive L_build_context' (fcld : (@Interface.I_cld_ext nat ty_ext FJ_cld_ext)) : Context -> Prop :=\n  L_bld' : L_build_context' fcld Empty.\n\nDefinition L_build_context (fcld : cld_ext) := \n  Generic.L_build_context nat N _ TUpdate L_build_context' fcld.\n\nDefinition override := @Generic.override nat Ty Gty nat N N_Wrap Context Empty \n  subtype Ty_trans WF_Type nat nat build_fresh N_Trans TUpdate Update\n  (@Interface.I_cld_ext nat ty_ext FJ_cld_ext) Bound unit unit unit unit \n  (fun fcld te te' te'' => FJ_build_te (snd fcld) te te' te'') (FJ_WF_mtype_Us_map Ty Context) (FJ_WF_mtype_U_map Ty Context)\n  (FJ_WF_mtype_ext Context) (fun ce te me ty vds (mtye : unit) => True) L_build_context' \n  (fun ice te ty vds mce tys tys' => FJ_mtype_build_tys nat _ (snd ice) te ty vds mce tys tys')\n  (fun (ice : I_cld_ext) mde gamma gamma' => FJ_Meth_build_context _ (snd ice) mde gamma gamma')\n  (fun gamma ce mde => True) (Generic.FJ_Ty_Wrap Ty ty_ext nat N N_Wrap cFJ_N) mtype.\n\nInductive Meth_WF : nat -> MD -> Prop :=\n  FJ_Meth_WF : forall c md, cFJ.Meth_WF _ _ _ _ _ _ FJ_Ty_Wrap E _ _ CT Context subtype WF_Type \n    E_WF Empty Update ce_build_cte Meth_build_context Meth_WF_Ext override c md -> Meth_WF c md.\n\nDefinition ioverride := @I_ioverride _ Ty _ _ _ mtype _ FJ_Ty_Wrap.\n\nDefinition L_WF_Ext (gamma : Context) (ce : cld_ext) c := \n  Generic.L_WF_Ext nat Ty nat N N_Wrap _ WF_Type \n  (fun gamma (ie : I_cld_ext) c => FJ_L_WF_Ext _ _ gamma (@snd _ _ ie) c ) gamma ce c /\\\n  GI_L_WF_Ext _ Ty ty_ext N _ WF_Type N_Wrap I_N_Wrap _ implements Empty gamma ce /\\\n  I_L_WF_Ext _ _ _ I_Ty_Wrap _ _ _ mtype nat _ ioverride gamma (snd ce) c \n  (FJ_L_WF_Ext _ _) ce_build_cte.\n\nDefinition L_WF : L -> Prop :=\n  cFJ.L_WF _ _ _ _ _ _  FJ_Ty_Wrap _ _ _ CT _ subtype WF_Type \n  fields E_WF Empty Update ce_build_cte Meth_build_context Meth_WF_Ext override\n  L_WF_Ext L_build_context.\n\nDefinition Int_Meth_WF_Ext := GI_Int_Meth_WF_Ext nat _ _ _ WF_Type N_Wrap \n  (FJ_Meth_WF_Ext unit _).\n\nDefinition Int_Meth_build_context := GI_Int_Meth_build_context _ _ _ TUpdate\n  (I_Int_Meth_build_context unit _).\n\nDefinition Int_WF_Ext := GI_Int_WF_Ext _ nat _ _ _ WF_Type N_Wrap (I_Int_WF_Ext nat _).\n\nDefinition Int_build_context := GI_Int_build_context _ _ _ TUpdate (I_Int_build_context Context Empty).\n\nDefinition I_WF : Interface -> Prop :=\n  Interface.I_WF nat Ty mty_ext nat nat Interface_ext _ WF_Type Int_build_context Int_WF_Ext Int_Meth_WF_Ext\n  Int_Meth_build_context.\n\nFixpoint trans (e : E) (Vars : list (Var nat)) (Es : list E) : E :=\n  match e with \n    | cFJ_E fj_e => cFJ.FJ_E_trans _ _ _ _ _ _ _ cFJ_E trans eq_nat_dec fj_e Vars Es\n    | Cast_E cast_e => Cast_E (Cast.Cast_E_trans _ _ _ _ trans cast_e Vars Es)\n  end.\n\nInductive Reduce : E -> E -> Prop :=\n| FJ_S_Reduce : forall e e', FJ_Reduce _ _ _ _ _ _  (Generic.FJ_Ty_Wrap Ty ty_ext nat N N_Wrap cFJ_N) _ _\n  cFJ_E _ _ CT _ fields mbody_build_te mb_ext (fun ce te mce mde mbe => True) map_mbody\n  Empty trans e e' -> Reduce e e'\n| FJ_C_Reduce : forall e e', FJ_Congruence_Reduce _ _ _ _ ty_ext E _ cFJ_E Reduce \n  Congruence_List_Reduce e e' -> Reduce e e'\n| Cast_Reduce : forall e e', \n  Cast.Cast_Reduce _ _ _ (Generic.FJ_Ty_Wrap Ty ty_ext nat N N_Wrap cFJ_N) \n  _ _ Cast_E subtype nat nat nat m_call_ext cFJ_E Empty e e' ->\n  Reduce e e'\n| Cast_C_Reduce : forall e e', Cast_C_Reduce _ _ _ Cast_E Reduce e e' -> Reduce e e'\nwith Congruence_List_Reduce : list E -> list E -> Prop :=\n| FJ_Reduce_List : forall es es', Reduce_List _ Reduce Congruence_List_Reduce es es' -> Congruence_List_Reduce es es'.\n\nSection Preservation.\n\n  Variables (app_context : Context -> Context -> Context)\n    (TLookup_unique : forall gamma X ty ty', TLookup gamma X ty -> TLookup gamma X ty' -> ty = ty')\n    (TLookup_dec : forall gamma X, (exists ty, TLookup gamma X ty) \\/ (forall ty, ~TLookup gamma X ty))\n    (TLookup_app : forall gamma delta X ty, TLookup gamma X ty -> TLookup (app_context gamma delta) X ty)\n    (TLookup_app' : forall gamma delta X ty, (forall ty', ~ TLookup gamma X ty') -> TLookup delta X ty -> \n      TLookup (app_context gamma delta) X ty)\n    (TLookup_app'' : forall gamma delta X ty, (forall ty', ~ TLookup gamma X ty') ->  \n      TLookup (app_context gamma delta) X ty -> TLookup delta X ty)\n    (TLookup_Empty : forall X ty, ~ TLookup Empty X ty)\n    (subst_context : Context -> list nat -> list Ty -> Context)\n    (subst_context_nil : forall delta Us, subst_context delta nil Us = delta)\n    (subst_context_nil' : forall delta Xs, subst_context delta Xs nil = delta)\n    (TLookup_subst : forall gamma X ty Xs Us, TLookup gamma X ty -> \n      TLookup (subst_context gamma Xs Us) X (N_trans ty Xs Us))\n    (TLookup_update_eq : forall gamma X ty, TLookup (TUpdate gamma X ty) X ty) \n    (TLookup_update_neq : forall gamma Y X ty ty', TLookup gamma X ty -> X <> Y -> \n      TLookup (TUpdate gamma Y ty') X ty) \n    (TLookup_update_neq' : forall gamma Y X ty ty', X <> Y -> \n      TLookup (TUpdate gamma Y ty') X ty -> TLookup gamma X ty) \n    (TLookup_Update : forall gamma Y X ty ty',  \n      TLookup (Update gamma Y ty') X ty -> TLookup gamma X ty) \n    (TLookup_Update' : forall gamma Y X ty ty',  \n      TLookup gamma X ty -> TLookup (Update gamma Y ty') X ty) \n    (Lookup_dec : forall gamma x ty, lookup gamma x ty \\/ ~ lookup gamma x ty)\n    (Lookup_app : forall gamma delta x ty, lookup gamma x ty -> lookup (app_context gamma delta) x ty)\n    (Lookup_app' : forall gamma delta x ty, (forall ty', ~ lookup gamma x ty') -> lookup delta x ty -> \n      lookup (app_context gamma delta) x ty)\n    (WF_CT : forall (c : nat) l,\n      CT c = Some l -> L_WF l)\n    (WF_IT : forall i int, IT i = Some int -> I_WF int).\n\n  Definition Fields_eq_def gamma ty fds (fields_fds : fields gamma ty fds) := \n    forall gamma' fds', fields gamma' ty fds' -> fds = fds'.\n  \n  Lemma cFJ_inject : forall ty ty', FJ_Ty_Wrap ty = FJ_Ty_Wrap ty' -> ty = ty'.\n    intros ty ty' H; injection H; auto.\n  Qed.\n  \n  Lemma fields_invert : forall (gamma : Context) ty (fds : list (cFJ.FD nat Ty)),\n    fields gamma (FJ_Ty_Wrap ty) fds ->\n    cFJ.FJ_fields nat nat nat nat ty_ext Ty FJ_Ty_Wrap E md_ext\n    cld_ext CT Context fields fields_build_te fields_build_tys gamma\n    (FJ_Ty_Wrap ty) fds.\n    intros gamma ty fds fields_fds; inversion fields_fds; subst; assumption.\n  Qed.\n\n  Definition fields_build_te_id := \n    Generic.fields_build_te_id nat Ty N Ty_trans _ \n    (fun ice : I_cld_ext => FJ_fields_build_te_id (snd ice)).\n\n  Definition fields_build_tys_id := Generic.fields_build_tys_id nat Ty N Ty_trans _ \n    (fun te (ice : I_cld_ext) => FJ_fields_build_tys_id Ty te (snd ice)).\n\n  Fixpoint Fields_eq gamma ty fds (fields_fds : fields gamma ty fds) : Fields_eq_def _ _ _ fields_fds :=\n    match fields_fds return Fields_eq_def _ _ _ fields_fds with\n      FJ_fields gamma ty fds FJ_case => FJ_Fields_eq _ _ _ _ _ Ty _ _ _ _ CT Context\n      fields fields_build_te fields_build_tys FJ_fields cFJ_inject fields_invert\n      fields_build_te_id fields_build_tys_id _ _ _ FJ_case Fields_eq\n    end.\n\n  Definition fds_distinct_def gamma cl' fds (fields_fds : fields gamma cl' fds) :=\n    forall cl1 cl2 f m n fds',\n      map (fun fd' => match fd' with fd _ f => f end) fds' = map (fun fd' => match fd' with fd _ f => f end) fds ->\n      nth_error fds' m = Some (fd nat Ty cl1 f) -> nth_error fds n = Some (fd nat Ty cl2 f) -> m = n.\n\n  Definition Fields_Build_tys_len := Generic.Fields_Build_tys_len nat Ty N Ty_trans _ \n    (fun te (ice : I_cld_ext) => FJ_Fields_Build_tys_len Ty te (snd ice)).\n\n  Lemma Ty_Wrap_discriminate : forall ty ty', FJ_Ty_Wrap ty <> Gty ty'.\n    unfold FJ_Ty_Wrap; unfold Generic.FJ_Ty_Wrap; congruence.\n  Qed.\n\n  Definition WF_fields_map_id'  gamma ty ty' (bound : Bound gamma ty ty') :\n    forall (tye : GTy_ext Ty) (c : cFJ.CL nat),\n      ty = (FJ_Ty_Wrap (ty_def nat (GTy_ext Ty) tye c)) ->\n      exists tye' : GTy_ext Ty, ty' =  FJ_Ty_Wrap (ty_def nat (GTy_ext Ty) tye' c) :=\n        match bound in Bound gamma ty ty' return (forall (tye : GTy_ext Ty) (c : cFJ.CL nat),\n          ty = (FJ_Ty_Wrap (ty_def nat (GTy_ext Ty) tye c)) ->\n          exists tye' : GTy_ext Ty, ty' =  FJ_Ty_Wrap (ty_def nat (GTy_ext Ty) tye' c)) with \n          | GJ_Bound gamma' ty'' ty''' GJ_bound' => GJ_WF_fields_map_id' nat Ty _ Gty _ _ N_Wrap\n            cFJ_N _ TLookup Ty_Wrap_discriminate gamma' ty'' ty''' GJ_bound'\n          | N_Bound gamma' ty'' ty''' FJ_bound' => N_WF_fields_map_id' _ _ _ _ N_Wrap cFJ_N _ \n            gamma' ty'' ty''' FJ_bound'\n        end.\n\n  Definition WF_fields_map_id_def gamma cl' fds (fields_fds : fields gamma cl' fds) :=\n    forall tye c tye' fds' fds'', cl' = FJ_Ty_Wrap (ty_def nat ty_ext tye c) -> fds'' = fds -> \n      fields gamma (FJ_Ty_Wrap (ty_def nat ty_ext tye' c)) fds' -> \n      map (fun fd' => match fd' with fd _ f => f end) fds' = \n      map (fun fd' => match fd' with fd _ f => f end) fds.\n  \n  Fixpoint WF_fields_map_id gamma ty fds (fields_fds : fields gamma ty fds) :\n    WF_fields_map_id_def _ _ _ fields_fds :=\n    match fields_fds return WF_fields_map_id_def _ _ _ fields_fds with\n      FJ_fields gamma ty fds FJ_case => FJ_fields_map_id _ _ _ _ _ Ty _ _ _ _ CT Context\n      fields fields_build_te fields_build_tys FJ_fields cFJ_inject fields_invert\n      Fields_Build_tys_len  _ _ _ FJ_case WF_fields_map_id\n    end.\n\n  Definition parent_fields_names_eq_P := \n    cFJ.parent_fields_names_eq_P _ nat _ _ FJ_Ty_Wrap Context fields.\n\n  Fixpoint parent_fields_names_eq gamma ty fds (fields_fds : fields gamma ty fds) : \n    parent_fields_names_eq_P _ _ _ fields_fds :=\n    match fields_fds return parent_fields_names_eq_P _ _ _ fields_fds with\n      FJ_fields gamma ty fds FJ_case => FJ_parent_fields_names_eq _ _ _ _ _ Ty _ _ _ _ CT Context\n      fields fields_build_te fields_build_tys FJ_fields cFJ_inject fields_invert \n      Fields_Build_tys_len _ _ _ FJ_case parent_fields_names_eq\n    end.\n\n  Fixpoint fds_distinct gamma ty fds (fields_fds : fields gamma ty fds) : fds_distinct_def _ _ _ fields_fds :=\n    match fields_fds return fds_distinct_def _ _ _ fields_fds with\n      FJ_fields gamma ty fds FJ_case => FJ_fds_distinct _ _ _ _ _ Ty FJ_Ty_Wrap _ _ _ CT Context\n      subtype WF_Type fields fields_build_te fields_build_tys FJ_fields E_WF Empty Update\n      ce_build_cte Meth_build_context Meth_WF_Ext override L_WF_Ext L_build_context\n      WF_CT parent_fields_names_eq Fields_Build_tys_len _ _ _ FJ_case fds_distinct\n    end.\n\n  Definition Weakening_def e ty gamma (WF_e : E_WF gamma e ty) :=\n    forall gamma' vars, gamma = (update_list Empty vars) -> E_WF (update_list gamma' vars) e ty.\n\n  Fixpoint Weaken_Subtype_update_list gamma S T (sub_S_T : subtype gamma S T) :=\n    match sub_S_T return cFJ.Weaken_Subtype_update_list_P nat _ _ subtype Empty Update _ _ _ sub_S_T with\n      | cFJ_sub gamma S' T' sub_S_T' => FJ_Weaken_Subtype_update_list _ _ _ _ _ _ \n        _ _ _ _ CT _ subtype build_te cFJ_sub Empty Update _ _ _ sub_S_T' Weaken_Subtype_update_list\n      | GJ_sub gamma S' T' sub_S_T' => GJ_Weaken_Subtype_update_list _ _ Gty N _ _ Empty TLookup\n        subtype GJ_sub nat Update TLookup_Update TLookup_Empty _ _ _ sub_S_T'\n      | I_subtype_Wrap gamma S' T' sub_S_T' => I_Weaken_Subtype_update_list _ _ _ I_Ty_Wrap _ _ _ _ _ _ _ _ \n        CT isub_build_te implements FJ_Ty_Wrap subtype I_subtype_Wrap Empty Update \n        gamma S' T' sub_S_T'\n    end.\n\n  Definition Weaken_WF_Object_Ext := Generic.Weaken_WF_Object_Ext _ _ Empty _ Update unit.\n  \n  Section wf_class_ext_recursion.\n    \n    Definition map_List_P1 := fun (A : Type) (P Q : A -> Prop) (Map_P : forall a, P a -> Q a) => \n      fix map (As : list A) (PAs : List_P1 P As) : List_P1 Q As :=\n      match PAs in (List_P1 _ As'') return List_P1 Q As'' with\n        Nil => Nil Q\n        | Cons_a a As' Pa PAs' => Cons_a Q a As' (Map_P a Pa) (map As' PAs')\n      end.\n\n    Variables (P : forall gamma ty, WF_Type gamma ty -> Prop)\n      (Q' : forall gamma cld ty,\n        @GJ_wf_class_ext nat Ty N N_Wrap Context subtype\n        Ty_trans WF_Type I_cld_ext unit gamma cld ty -> Prop)\n      (Q'_P1 : forall gamma tys, List_P1 (WF_Type gamma) tys -> Prop)\n      (Q'' : forall (gamma : Context) (int : _) (ty : ty_ext), \n        wf_int_ext gamma int ty -> Prop).\n    \n    Hypothesis (H1 : forall gamma ce tys typs te P1 len P2, \n      Q'_P1 gamma tys P1 -> \n      Q' _ _ _ (@Generic.wf_class_ext nat Ty N _ Context subtype\n        Ty_trans WF_Type _ unit ce gamma typs tys te\n        P1 len P2))\n    (H2 : forall gamma, Q'_P1 gamma _ (Nil (WF_Type gamma)))\n    (H3 : forall gamma ty tys P_ty P_tys, P _ _ P_ty -> Q'_P1 _ tys P_tys -> \n      Q'_P1 gamma _ (Cons_a _ ty tys P_ty P_tys))\n    (H4 : forall ie delta typs tys te P1 len P2, \n      Q'_P1 delta tys P1 -> \n      (Q'' _ _ _ (i_wf_int_ext _ _ _ _ _ _ _ _ ie delta typs tys te P1 len P2))).\n    \n    Definition wf_class_ext_rect (WF_type_rect : forall gamma ty wf_ty, P gamma ty wf_ty) \n      gamma cld te (wf_te : wf_class_ext gamma cld te) : Q' _ _ _ wf_te :=\n      match wf_te return  Q' _ _ _ wf_te with\n        Generic.wf_class_ext ce gamma typs tys te P1 len P2 => \n        H1 gamma ce tys typs te P1 len P2 \n        ((fix map (As : list Ty) (PAs : List_P1 (WF_Type gamma) As) : Q'_P1 _ _ PAs :=\n          match PAs return Q'_P1 _ _ PAs with\n            Nil => H2 gamma\n            | Cons_a a As' Pa PAs' => H3 gamma a As' Pa PAs'\n              (WF_type_rect _ a Pa) (map As' PAs')\n          end) tys P1)\n      end.\n\n    Definition wf_int_ext_rect (WF_type_rect : forall gamma ty wf_ty, P gamma ty wf_ty) \n      gamma int te (wf_te : wf_int_ext gamma int te) : Q'' _ _ _ wf_te :=\n      match wf_te return  Q'' _ _ _ wf_te with\n        i_wf_int_ext ie delta typs tys te P1 len P2 => \n        H4 ie delta typs tys te P1 len P2 \n        ((fix map (As : list Ty) (PAs : List_P1 (WF_Type delta) As) : Q'_P1 _ _ PAs :=\n          match PAs return Q'_P1 _ _ PAs with\n            Nil => H2 delta\n            | Cons_a a As' Pa PAs' => H3 delta a As' Pa PAs'\n              (WF_type_rect _ a Pa) (map As' PAs')\n          end) tys P1)\n      end.\n\n    Variable (H5 : forall gamma ty (wf_ty : (Generic.GJ_WF_Type nat Ty Gty N Context TLookup gamma ty)), \n      P gamma ty (GJ_WF_Type _ _ wf_ty)).\n\n    Fixpoint WF_Type_rect' H1 H2 H3 gamma ty wf_ty : P gamma ty wf_ty := \n      match wf_ty return P _ _ wf_ty with \n        | cFJ_WF_Type gamma' ty' wf_ty' => \n          FJ_WF_Type_rect' nat nat nat nat ty_ext Ty _ E md_ext cld_ext CT Context \n          wf_class_ext wf_object_ext WF_Type cFJ_WF_Type P Q' H1 H2\n          (wf_class_ext_rect (WF_Type_rect' H1 H2 H3)) gamma' ty' wf_ty' \n        | GJ_WF_Type gamma ty wf_ty => H5 _ _ wf_ty\n        | I_WF_Type_Wrap gamma ty wf_ty => I_WF_Type_rect' nat ty_ext Ty  \n          I_Ty_Wrap mty_ext nat nat _ Context IT (wf_int_ext' WF_Type) WF_Type \n          I_WF_Type_Wrap P Q'' H3 (wf_int_ext_rect (WF_Type_rect' H1 H2 H3)) gamma ty wf_ty\n      end.\n\n  End wf_class_ext_recursion.\n\n  Fixpoint Weaken_WF_Type_update_list gamma ty (WF_ty : WF_Type gamma ty) :\n    FJ_Weaken_WF_Type_update_list_P _ _ _ WF_Type Empty Update gamma ty WF_ty :=\n    match WF_ty in WF_Type gamma ty return FJ_Weaken_WF_Type_update_list_P _ _ _ WF_Type Empty Update gamma ty WF_ty with \n      | cFJ_WF_Type gamma' ty' wf_ty' => \n        FJ_Weaken_WF_Type_update_list nat nat nat nat ty_ext Ty _ E md_ext cld_ext CT Context \n        wf_class_ext wf_object_ext WF_Type cFJ_WF_Type Empty Update Weaken_WF_Object_Ext\n        (Weaken_WF_Type_update_list_ext nat Ty N _ _ Empty subtype Ty_trans WF_Type\n          _ _ _ _ Weaken_Subtype_update_list Weaken_WF_Type_update_list) gamma' ty' wf_ty'\n      | GJ_WF_Type gamma' ty' wf_ty' => \n        GJ_Weaken_WF_Type_update_list _ _ _ _ _ _ _ _ GJ_WF_Type nat Update\n        TLookup_Update TLookup_Update' TLookup_Empty _ _ wf_ty'\n      | I_WF_Type_Wrap gamma' ty' wf_ty' => I_Weaken_WF_Type_update_list _ _ _ I_Ty_Wrap\n        _ _ _ _ _ IT _ WF_Type I_WF_Type_Wrap Empty Update\n        (wf_int_ext_rect _ _ (Weaken_WF_Int_Ext_Q _ _ _ _ _ _ _ _) \n          (Weaken_WF_Type_update_list_H2 _ _ _ _ _ _)\n          (Weaken_WF_Type_update_list_H3 _ _ _ _ _ _)\n          (I_Weaken_WF_update_list_ext _ _ _ _ _ _ _ _ _ _ _ _ _ Weaken_Subtype_update_list) \n        Weaken_WF_Type_update_list)\n        _ _ wf_ty'\n    end.\n  \n  Variables \n    (lookup_update_eq : forall gamma X ty, lookup (Update gamma X ty) X ty) \n    (lookup_update_neq : forall gamma Y X ty ty', lookup gamma X ty -> X <> Y -> \n      lookup (Update gamma Y ty') X ty)\n    (lookup_update_neq' : forall gamma Y X ty ty', lookup (Update gamma Y ty') X ty -> X <> Y -> \n      lookup gamma X ty)\n    (lookup_Empty : forall X ty, ~ lookup Empty X ty)\n    (lookup_id : forall gamma X ty ty', lookup gamma X ty -> lookup gamma X ty' -> ty = ty').\n\n  Definition WF_mtype_ty_0_map := Bound.\n  Definition WF_fields_map := Bound.\n\n  Definition Weaken_WF_fields_map gamma ty ty' (bound : Bound gamma ty ty') :=\n    match bound in Bound gamma ty ty' return (forall (gamma' : Context) (vars : list (Var nat * Ty)),\n      gamma = Generic.update_list Ty Context nat Update Empty vars ->\n      Bound (Generic.update_list Ty Context nat Update gamma' vars) ty ty')\n      with \n      | GJ_Bound gamma' ty'' ty''' GJ_bound' => GJ_Weaken_WF_fields_map nat Ty Gty _ N_Wrap\n        _ Empty TLookup _ Update TLookup_Update TLookup_Update' TLookup_Empty Bound GJ_Bound\n        gamma' ty'' ty''' GJ_bound'\n      | N_Bound gamma' ty'' ty''' FJ_bound' => FJ_Weaken_WF_fields_map Ty _ N_Wrap _ Empty _ \n        Update Bound N_Bound gamma' ty'' ty''' FJ_bound'\n    end.\n\n  Definition Weaken_WF_fields_map' gamma vars ty ty' bnd :=\n    Weaken_WF_fields_map _ ty ty' bnd gamma vars (refl_equal _).\n\n  Definition Weaken_WF_mtype_Us_map := \n    Generic.Weaken_WF_mtype_Us_map _ _ N _ Empty Ty_trans _ Update _ _\n    (FJ_WF_mtype_Us_map Ty Context) \n    (fun mce mtye tys tys' vars gamma => FJ_Weaken_WF_mtype_Us_map _ _ _ Empty Update gamma vars mce tys tys' mtye).\n  \n  Definition Weaken_WF_mtype_U_map := \n    Generic.Weaken_WF_mtype_U_map _ _ N _ Empty Ty_trans _ Update _ _\n    (FJ_WF_mtype_U_map Ty Context) \n    (fun gamma vars mce U U' mtye => FJ_Weaken_WF_mtype_U_map _ _ _ Empty Update gamma vars mce U U' mtye).\n  \n  Definition Weaken_WF_mtype_ext := \n    Generic.Weaken_WF_mtype_ext nat Ty N N_Wrap _ Empty subtype Ty_trans\n    WF_Type _ Update Weaken_Subtype_update_list Weaken_WF_Type_update_list unit unit\n    (FJ_WF_mtype_ext Context) (FJ_Weaken_WF_mtype_ext _ _ _ Empty Update).\n\n  Variable Ty_eq_dec : forall (S T : Ty), {S = T} + {S <> T}.\n  Variable subtype_dec : forall gamma S T, subtype gamma S T \\/ ~ subtype gamma S T.\n  \n  Fixpoint Weakening gamma e ty (WF_e : E_WF gamma e ty) : Weakening_def _ _ _ WF_e :=\n    match WF_e return Weakening_def _ _ _ WF_e with\n      | FJ_E_WF gamma e ty FJ_case => FJ_Weakening _ _ _ _ _ _ _ _ _ cFJ_E _ _\n        subtype WF_Type fields mtype\n        E_WF lookup Bound Bound WF_mtype_Us_map WF_mtype_U_map\n        WF_mtype_ext Empty FJ_E_WF Update eq_nat_dec lookup_update_eq\n        lookup_update_neq lookup_update_neq' lookup_Empty lookup_id Weaken_WF_fields_map'\n        Weaken_WF_fields_map' Weaken_WF_mtype_Us_map Weaken_WF_mtype_U_map\n        Weaken_Subtype_update_list Weaken_WF_mtype_ext Weaken_WF_Type_update_list _ _ _ \n        FJ_case Weakening\n      | Cast_E_WF gamma e ty Cast_case => \n        Cast_Weakening _ _ _ (Generic.FJ_Ty_Wrap Ty ty_ext nat N N_Wrap cFJ_N) _ _ Cast_E\n        E_WF Bound subtype Cast_E_WF _ _ _ _ _ CT build_te Empty Update cFJ_sub\n        Weaken_Subtype_update_list subtype_dec Ty_eq_dec Weaken_WF_fields_map' gamma e ty Cast_case Weakening\n    end.\n\n  Lemma E_trans_Wrap : forall e vars es', \n    trans (cFJ_E e) vars es' = cFJ.FJ_E_trans _ _ _ _ _ _ _ cFJ_E trans eq_nat_dec e vars es'.\n    simpl; reflexivity.\n  Qed.\n  \n  Definition WF_mtype_ty_0_map_Weaken_update_list delta T T' (Bnd : Bound delta T T') :=\n    match Bnd in (Bound delta T T') return (forall delta' vars, delta = update_list delta' vars -> \n      Bound delta' T T') with\n      | GJ_Bound delta T T' GJ_Bound' => Generic.GJ_Bound_Weaken_update_list _ _ Gty _ N_Wrap _ TLookup _ Update\n        TLookup_Update Bound GJ_Bound delta T T' GJ_Bound'\n      | N_Bound delta T T' N_Boun' => Generic.N_Bound_Weaken_update_list _ _ N_Wrap _ _ Update Bound N_Bound\n        delta T T' N_Boun'\n    end.\n  \n  Definition WF_mtype_U_map_Weaken_update_list := \n    GJ_WF_mtype_U_map_Weaken_update_list _ _ N _ Ty_trans _ Update _ _\n    id_map_3 (fun gamma vars mce U U' mtye => \n      FJ_WF_mtype_U_map_Weaken_update_list _ _ _ Update gamma vars mce mtye U U').\n  \n  Definition WF_mtype_Us_map_Weaken_update_list := \n    GJ_WF_mtype_Us_map_Weaken_update_list _ _ N _ Ty_trans _ Update _ _\n    id_map_3 (fun mce mtye tys tys' vars gamma => \n      FJ_WF_mtype_Us_map_Weaken_update_list _ _ _ Update gamma vars mce mtye tys tys').\n  \n  Definition Bound_total_def gamma S T (sub_S_T : subtype gamma S T) :=\n    forall T', Bound gamma T T' -> exists S' , Bound gamma S S'.\n\n  Fixpoint WF_mtype_ty_0_map_total gamma S T (sub_S_T : subtype gamma S T) := \n    match sub_S_T in subtype gamma S T return Bound_total_def gamma S T sub_S_T with\n      | cFJ_sub gamma' S' T' sub_S_T' => \n        FJ_Bound_total _ _ _ _ _ _ _ subtype _ _ _ _ Bound N_Bound _ _ CT \n        build_te cFJ_sub WF_mtype_ty_0_map_total gamma' S' T' sub_S_T'\n      | GJ_sub gamma' S' T' sub_S_T' => \n        GJ_Bound_total _ _ _ _ _ _ TLookup subtype GJ_sub Bound GJ_Bound gamma' S' T' sub_S_T'\n      | I_subtype_Wrap gamma' S' T' sub_S_T' => \n        I_Bound_total _ _ _ _ _ _ _ _ subtype N_Wrap I_N_Wrap _ _ cFJ_N Bound N_Bound _ _ _ CT _\n        I_subtype_Wrap gamma' S' T' sub_S_T'  \n    end.\n  \n  Fixpoint Subtype_Update_list_id gamma S T (sub_S_T : subtype gamma S T) := \n    match sub_S_T with\n      | cFJ_sub gamma' S' T' sub_S_T' => \n        FJ_Subtype_Update_list_id _ _ _ _ _ _ _ _ _ _ CT _ subtype build_te\n        cFJ_sub Update gamma' S' T' sub_S_T' Subtype_Update_list_id\n      | GJ_sub gamma' S' T' sub_S_T' => \n        GJ_Subtype_Update_list_id _ _ Gty N _ _ TLookup _ GJ_sub _ Update\n        TLookup_Update gamma' S' T' sub_S_T'\n      | I_subtype_Wrap gamma S' T' sub_S_T' => \n        I_Subtype_Update_list_id _ _ _ I_Ty_Wrap _ _ _ _ _ _ _ _ CT isub_build_te\n        implements _ subtype I_subtype_Wrap Update gamma S' T' sub_S_T'\n    end.\n  \n  Definition WF_Object_ext_Update_Vars_id := \n    GJ_WF_Object_ext_Update_Vars_id _ _ _ Update unit.\n\n  Fixpoint WF_Type_update_list_id gamma ty (WF_ty : WF_Type gamma ty) :\n    cFJ.WF_Type_update_list_id_P _ _ _ WF_Type Update gamma ty WF_ty :=\n    match WF_ty in WF_Type gamma ty return cFJ.WF_Type_update_list_id_P _ _ _ WF_Type Update gamma ty WF_ty with \n      | cFJ_WF_Type gamma' ty' wf_ty' => \n        FJ_WF_Type_update_list_id nat nat nat nat ty_ext Ty _ E md_ext cld_ext CT Context \n        wf_class_ext wf_object_ext WF_Type cFJ_WF_Type Update WF_Object_ext_Update_Vars_id\n        (WF_Type_update_list_id_ext nat Ty N _ _ subtype Ty_trans WF_Type\n          nat Update _ _  Subtype_Update_list_id WF_Type_update_list_id) gamma' ty' wf_ty'\n      | GJ_WF_Type gamma' ty' wf_ty' => \n        GJ_WF_Type_update_list_id _ _ Gty N _ TLookup WF_Type GJ_WF_Type _ Update \n        TLookup_Update _ _ wf_ty'\n      | I_WF_Type_Wrap _ _ wf_ty' => I_WF_Type_update_list_id _ _ _ _ _ _ _ _ _ IT\n        wf_int_ext _ I_WF_Type_Wrap Update \n        (wf_int_ext_rect _ _ (WF_int_ext_Update_Vars_id_Q _ _ _ _ _ _ _)\n          (WF_Type_update_list_id_H2 _ _ _ _ _)\n          (WF_Type_update_list_id_H3 _ _ _ _ _)\n          (WF_int_ext_update_list_id _ _ _ _ _ WF_Type subtype\n            Ty_trans N_Wrap Update _ _ Subtype_Update_list_id) WF_Type_update_list_id) _ _ wf_ty'\n   end.\n  \n  Definition WF_fields_map_tot := FJ_WF_fields_map_tot _ _ _ FJ_Ty_Wrap Context.\n  \n  Fixpoint fields_id gamma ty fds (ty_fields : fields gamma ty fds) := \n    match ty_fields with \n      | FJ_fields gamma' ty' fds' FJ_ty'_fields =>\n        FJ_fields_id _ _ _ _ _ _ _ _ _ _ CT Context fields fields_build_te \n        fields_build_tys FJ_fields cFJ_inject fields_invert  \n        fields_build_te_id fields_build_tys_id  gamma' ty' fds' FJ_ty'_fields fields_id\n    end.\n  \n  Definition WF_mtype_ext_update_list_id := FJ_WF_mtype_ext_update_list_id _ _ _ Update.\n  \n  Definition WF_mtype_ty_0_map_tot := FJ_WF_mtype_ty_0_map_tot Ty Context.\n  \n  Definition WF_mtype_ty_0_map_cl_id := \n    FJ_WF_mtype_ty_0_map_cl_id _ _ _ _ Context cFJ_inject.\n  \n  Definition WF_mtype_ty_0_map_cl_id' := \n    FJ_WF_mtype_ty_0_map_cl_id' _ _ _ FJ_Ty_Wrap Context. \n  \n  Definition m_eq_dec := eq_nat_dec.\n    \n  Definition WF_mtype_Us_map_len := FJ_WF_mtype_Us_map_len Ty Context.\n  \n  Definition mtype_build_tys_len (ce : I_cld_ext) := FJ_mtype_build_tys_len nat Ty (snd ce).\n  \n  Definition methods_build_te_id := FJ_methods_build_te_id.\n  \n  Definition WF_Type_par_Lem_P := cFJ.WF_Type_par_Lem_P\n    _ _ _ _ ty_ext Ty FJ_Ty_Wrap _ _ _ CT Context \n    wf_object_ext WF_Type mtype_build_te L_build_context.\n  \n   Lemma Ty_discriminate : forall ty ty', FJ_Ty_Wrap ty <> I_Ty_Wrap ty'.\n     unfold FJ_Ty_Wrap; unfold Generic.FJ_Ty_Wrap; unfold I_Ty_Wrap; intros.\n     congruence.\n   Qed.\n\n  Fixpoint WF_Type_par_Lem gamma ty (WF_ty : WF_Type gamma ty) :=\n    match WF_ty return WF_Type_par_Lem_P _ _ WF_ty with \n      | cFJ_WF_Type gamma ty WF_base => \n        FJ_WF_Type_par_Lem _ _ _ _ _ _ _ _ _ _ CT Context wf_class_ext\n        wf_object_ext WF_Type cFJ_WF_Type mtype_build_te\n        L_build_context cFJ_inject \n        (fun g g0 te0 te' te'' ce _ _ _ _ _ mty wf_obj _ _ => \n          WF_Obj_ext_Lem _ Ty N _ Ty_trans I_cld_ext _ \n          (fun ice te te' te'' => FJ_mtype_build_te (snd ice) te te' te'')\n            g g0 te0 te' te'' ce wf_obj mty) gamma ty WF_base\n      | GJ_WF_Type gamma ty WF_ty => (fun g te0 te' te'' ce _ _ _ _ _ _ mty wf_obj _ => \n        WF_Obj_ext_Lem _ Ty N _ Ty_trans I_cld_ext _ \n        (fun ice te te' te'' => FJ_mtype_build_te (snd ice) te te' te'')\n        gamma g te0 te' te'' ce wf_obj mty)\n      | I_WF_Type_Wrap gamma ty WF_int => \n        I_WF_Type_par_Lem _ _ _ I_Ty_Wrap _ _ _ _ _ IT _ _ _ _ _ CT\n        FJ_Ty_Wrap wf_int_ext WF_Type I_WF_Type_Wrap wf_object_ext \n        mtype_build_te L_build_context Ty_discriminate gamma ty WF_int\n    end.\n  \n  Definition WF_Type_par_Lem_P' := \n    cFJ.WF_Type_par_Lem_P' _ _ _ _ ty_ext Ty  FJ_Ty_Wrap E _ _ CT Context wf_class_ext\n    WF_Type mtype_build_te L_build_context.\n\n  Fixpoint Weakening_2_1_1 delta S T (sub_S_T : subtype delta S T) : \n    (Weakening_2_1_1_P _ _ subtype app_context _ _ _ sub_S_T) :=\n    match sub_S_T return (Weakening_2_1_1_P _ _ subtype app_context _ _ _ sub_S_T) with\n      | cFJ_sub delta S' T' sub_S_T' => \n        Weakening_2_1_1_FJ Ty ty_ext nat N N_Wrap cFJ_N _ subtype _ _ _ app_context\n        E _ _ CT build_te cFJ_sub Weakening_2_1_1 delta S' T' sub_S_T'\n      | GJ_sub delta S' T' sub_S_T' => Weakening_2_1_1_GJ _ _ Gty _ _ _ TLookup\n        subtype GJ_sub app_context TLookup_app delta S' T' sub_S_T'\n      | I_subtype_Wrap delta S' T' sub_S_T' => \n        I_Weakening_2_1_1 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ CT _ I_subtype_Wrap _ _ _ sub_S_T'\n    end.\n\n\n  Definition Weakening_2_1_2 :=\n    WF_Type_rect' (Weakening_2_1_2_P _ _ WF_Type app_context) \n    (Weakening_2_1_2_Q _ _ _ _ _ subtype Ty_trans WF_Type\n      app_context _ _)\n    (Weakening_2_1_2_P1 _ _ WF_Type app_context)\n    (Weakening_2_1_2_Q'' _ _ _ wf_int_ext app_context)\n    (Weakening_2_1_2_ext_H1 _ _ _ _ _ subtype Ty_trans WF_Type app_context _ _ Weakening_2_1_1)\n    (Weakening_2_1_2_ext_H2 _ _ WF_Type app_context)\n    (Weakening_2_1_2_ext_H3 _ _ WF_Type app_context)\n    (I_Weakening_2_1_2_ext _ _ _ _ WF_Type subtype _ _ _ _ _ Weakening_2_1_1)\n    (GJ_Weakening_2_1_2 _ _ Gty _ _ TLookup WF_Type GJ_WF_Type app_context TLookup_app)\n    (FJ_Weakening_2_1_2_H1 _ _ _ _ _ _ _ WF_Type nat nat nat app_context E _ _ CT\n      wf_class_ext wf_object_ext (Weakening_2_1_2_obj_ext _ _ app_context _) cFJ_WF_Type)\n    (FJ_Weakening_2_1_2_H2 _ _ _ _ _ _ _ WF_Type _ _ _ app_context E _ _ CT wf_class_ext\n      wf_object_ext cFJ_WF_Type)\n    (I_Weakening_2_1_2 _ _ _ _ _ _ _ _ _ WF_Type _ N_Wrap I_N_Wrap _ _ I_WF_Type_Wrap).\n\n  Definition WF_Bound_app_Weaken := GJ_WF_Bound_app_Weaken _ _ Gty _\n    _ TLookup app_context TLookup_app.\n  \n  Definition WF_mtype_Us_map_app_Weaken := \n    GJ_WF_mtype_Us_map_app_Weaken _ _ N Context Ty_trans _ app_context _ _\n    (FJ_WF_mtype_Us_map_app_Weaken _ _ app_context).\n  \n  Definition WF_mtype_U_map_app_Weaken := \n    GJ_WF_mtype_U_map_app_Weaken _ _ N Context Ty_trans _ app_context _ _\n    (FJ_WF_mtype_U_map_app_Weaken _ _ app_context).\n  \n  Definition WF_mtype_ext_app_Weaken := \n    Generic.GJ_WF_mtype_ext_app_Weaken _ _ _ N_Wrap _ \n    subtype Ty_trans WF_Type _ app_context\n    Weakening_2_1_1 Weakening_2_1_2 _ _ (FJ_WF_mtype_ext_app_Weaken _ app_context).\n\n  Definition WF_Bound_app_Weaken' (gamma : Context) (ty ty' : Ty) (Bnd : Bound gamma ty ty') :=\n    match Bnd in (Bound gamma ty ty') return (forall gamma', Bound (app_context gamma gamma') ty ty') with\n      | GJ_Bound gamma' ty'' ty''' GJ_bound' => GJ_WF_Bound_app_Weaken' _ _ Gty _ N_Wrap _ TLookup\n        app_context TLookup_app Bound GJ_Bound gamma' ty'' ty''' GJ_bound'\n      | N_Bound gamma' ty'' ty''' FJ_bound' => N_WF_Bound_app_Weaken' _ _ N_Wrap _ app_context\n        Bound N_Bound gamma' ty'' ty''' FJ_bound'\n    end.\n  \n  Fixpoint Weakening_2_1_3_1 delta e T (WF_e : E_WF delta e T) :\n    Generic.Weakening_2_1_3_1_P Ty Context app_context E E_WF delta e T WF_e :=\n    match WF_e in E_WF delta e T return Generic.Weakening_2_1_3_1_P _ _ app_context _ E_WF delta e T WF_e with \n      | FJ_E_WF gamma e ty FJ_case => Generic.Weakening_2_1_3_1 _ _ _ N N_Wrap _ _ Empty subtype\n        WF_Type _ fields _ _ _ mtype app_context _ Weakening_2_1_1\n        Weakening_2_1_2 _ cFJ_E E_WF lookup Bound WF_mtype_Us_map\n        WF_mtype_U_map WF_mtype_ext Bound Lookup_app FJ_E_WF \n        (fun g g' ty ty' bnd => WF_Bound_app_Weaken' g ty ty' bnd g')\n        (fun g g' ty ty' bnd => WF_Bound_app_Weaken' g ty ty' bnd g') WF_mtype_Us_map_app_Weaken\n        WF_mtype_U_map_app_Weaken WF_mtype_ext_app_Weaken Weakening_2_1_3_1 gamma e ty FJ_case\n      | Cast_E_WF gamma e ty Cast_case => Generic_Cast.Weakening_2_1_3_1 _ _ _ _ _ _ _ _ _ _ Cast_E _ app_context\n        E_WF Bound subtype Cast_E_WF WF_Bound_app_Weaken' Weakening_2_1_1 subtype_dec Ty_eq_dec _ _ CT\n        build_te cFJ_sub gamma e ty Cast_case Weakening_2_1_3_1\n    end.\n  \n  Inductive Free_Vars : Ty -> list nat -> Prop :=\n  | GJ_Free_Vars' : forall ty txs, GJ_Free_Vars _ _ Gty ty txs -> Free_Vars ty txs\n  | FJ_Free_Vars' : forall ty txs, FJ_Free_Vars _ _ _ nat N N_Wrap cFJ_N\n    (GJ_TE_Free_Vars _ _ _ Free_Vars) ty txs -> Free_Vars ty txs\n  | I_Free_Vars' : forall ty txs, I_Free_Vars _ _ _ _ _ N_Wrap I_N_Wrap\n    (GJ_TE_Free_Vars _ _ _ Free_Vars) ty txs -> Free_Vars ty txs.\n  \n  Definition TE_Free_Vars := (GJ_TE_Free_Vars _ _ unit Free_Vars).\n  \n  Lemma GJ_Free_Vars_invert : forall ty txs, Free_Vars (Gty ty) txs -> GJ_Free_Vars _ _ Gty (Gty ty) txs.\n    intros; inversion H; subst; first [apply H0 | inversion H0].\n  Qed.\n  \n  Lemma FJ_Free_Vars_invert : forall ty txs, Free_Vars (FJ_Ty_Wrap ty) txs -> \n    FJ_Free_Vars _ _ _ nat N N_Wrap cFJ_N (GJ_TE_Free_Vars _ _ _ Free_Vars) (FJ_Ty_Wrap ty) txs.\n    intros; inversion H; subst; first [apply H0 | inversion H0].\n  Qed.\n  \n  Lemma GJ_Ty_Wrap_inject : forall ty ty', Gty ty = Gty ty' -> ty = ty'.\n    intros; congruence.\n  Qed.\n  \n  Lemma FJ_Ty_Wrap_inject : forall ty ty', FJ_Ty_Wrap ty = FJ_Ty_Wrap ty' -> ty = ty'.\n    unfold FJ_Ty_Wrap; unfold Generic.FJ_Ty_Wrap; congruence.\n  Qed.\n  \n  Lemma GTy_ext_Wrap_inject : forall (te te' : ty_ext) , id te = id te' -> te = te'.\n    unfold id; auto.\n  Qed.\n  \n  Definition TE_trans := (GJ_TE_Trans _ _ Ty_trans unit).\n      \n  Section Ty_recursion.\n\n    Variables\n      (P : Ty -> Type)\n      (Q : ty_ext -> Type).\n\n    Hypotheses\n      (H1 : forall X, P (Gty (TyVar _ X)))\n      (H2 : forall te cl, Q te -> P (FJ_Ty_Wrap (ty_def _ _ te cl)))\n      (H3 : forall te cl, Q te -> P (I_Ty_Wrap (ity_def _ _ te cl)))\n      (H4 : forall te, Q (nil, te))\n      (H5 : forall ty tys te, Q (tys, te) -> P ty -> Q (ty :: tys, te)).\n\n    Fixpoint ty_rect (ty : Ty) : P ty :=\n      match ty with\n        | Gty (TyVar X) => H1 X\n        | N_Wrap (cFJ_N (ty_def (tys, te) c)) => H2 (tys, te) c \n          ((fix tys_rect tys : Q (tys, te) :=\n            match tys return Q (tys, te) with\n              | nil => H4 te\n              | ty :: tys' => H5 ty tys' te (tys_rect tys') (ty_rect ty)\n            end) tys)\n        | N_Wrap (I_N_Wrap (ity_def (tys, te) i)) => H3 (tys, te) i \n          ((fix tys_rect tys : Q (tys, te) :=\n            match tys return Q (tys, te) with\n              | nil => H4 te\n              | ty :: tys' => H5 ty tys' te (tys_rect tys') (ty_rect ty)\n            end) tys)\n      end.\n\n  End Ty_recursion.\n\n  Lemma FJ_Ty_trans_invert : forall ty txs tys,\n    Ty_trans (FJ_Ty_Wrap ty) txs tys = FJ_Ty_Trans _ _ _ _ _ FJ_Ty_Wrap id TE_trans ty txs tys.\n    reflexivity.\n  Qed.\n\n  Lemma GJ_Ty_trans_invert : \n    forall ty Xs Us, Ty_trans (Gty ty) Xs Us = GTy_trans nat eq_nat_dec Ty Gty ty Xs Us.\n    reflexivity.\n  Qed.\n\n  Lemma I_Ty_trans_invert : \n    forall ty txs tys, Ty_trans (I_Ty_Wrap ty) txs tys = I_Ty_Trans _ _ _ _ _ N_Wrap I_N_Wrap TE_trans ty txs tys.\n    reflexivity.\n  Qed.\n\n  Lemma GJ_TE_Trans_invert : forall (te : GTy_ext Ty) (Ys : list nat)\n    (Us : list Ty), TE_trans (id te) Ys Us = id (GJ_TE_Trans nat Ty Ty_trans _ te Ys Us).\n    reflexivity.\n  Qed.\n\n  Definition Ty_trans_nil :=\n    ty_rect (Ty_trans_nil_P _ _ Ty_trans)\n    (TE_trans_nil_P _ _ _ TE_trans)\n    (GJ_Ty_trans_nil _ eq_nat_dec _ Gty _ GJ_Ty_trans_invert)\n    (FJ_Ty_trans_nil _ _ _ _ N N_Wrap cFJ_N Ty_trans TE_trans \n      FJ_Ty_trans_invert)\n    (I_Ty_trans_nil _ _ _ _ _ _ _ _ _ I_Ty_trans_invert)\n    (TE_trans_nil_H1 _ _ _ _ _ id _ GJ_TE_Trans_invert)\n    (TE_trans_nil_H2 _ _ _ _ _ id _ (fun _ _ => id) GJ_TE_Trans_invert).\n\n  Definition Ty_trans_nil' :=\n    ty_rect (Ty_trans_nil'_P _ _ Ty_trans)\n    (TE_trans_nil'_P _ _ _ TE_trans)\n    (GJ_Ty_trans_nil' _ eq_nat_dec _ Gty _ GJ_Ty_trans_invert)\n    (FJ_Ty_trans_nil' _ _ _ _ N N_Wrap cFJ_N Ty_trans TE_trans \n      FJ_Ty_trans_invert)\n    (I_Ty_trans_nil' _ _ _ _ _ _ _ _ _ I_Ty_trans_invert)\n    (TE_trans_nil'_H1 _ _ _ _ _ id _ GJ_TE_Trans_invert)\n    (TE_trans_nil'_H2 _ _ _ _ _ id _ (fun _ _ => id) GJ_TE_Trans_invert).\n    \n  Definition Free_Vars_Subst_P (ty : Ty) := \n    forall (Xs Ys : list nat) (Us : list Ty),\n      (forall X, In X Xs -> ~ In X Ys) -> Free_Vars ty Xs -> Ty_trans ty Ys Us = ty.\n  \n  Definition Free_Vars_Subst_Q (te : ty_ext) :=\n    forall Ys Us Xs, \n      (forall X : nat, In X Xs -> ~ In X Ys) -> TE_Free_Vars te Xs -> TE_trans te Ys Us = te.\n    \n  Lemma GJ_TE_Free_Vars_invert : forall (te : GTy_ext Ty) (txs : list nat),\n    TE_Free_Vars (id te) txs -> GJ_TE_Free_Vars _ Ty _ Free_Vars te txs.\n    unfold id; unfold TE_Free_Vars; auto.\n  Qed.\n\n  Lemma I_Ty_Wrap_inject : forall ty ty' , I_Ty_Wrap ty = I_Ty_Wrap ty' -> ty = ty'.\n    unfold I_Ty_Wrap; intros; injection H; auto.\n  Qed.\n\n  Lemma I_Free_Vars_invert : forall (ty : I_Ty _ _) (txs : list _),\n    Free_Vars (I_Ty_Wrap ty) txs ->\n    I_Free_Vars _ _ _ ty_ext _ N_Wrap I_N_Wrap TE_Free_Vars (I_Ty_Wrap ty) txs.\n    intros; inversion H; inversion H0; subst; assumption.\n  Qed.\n\n  Definition Free_Vars_Subst :=\n    ty_rect Free_Vars_Subst_P Free_Vars_Subst_Q\n    (Free_Vars_Subst_H1 _ eq_nat_dec _ Gty Free_Vars GJ_Free_Vars_invert GJ_Ty_Wrap_inject)\n    (Free_Vars_Subst_H2 _ _ _ _ N N_Wrap cFJ_N FJ_Ty_Wrap_inject Free_Vars TE_Free_Vars FJ_Free_Vars_invert\n      TE_trans)\n    (I_Free_Vars_Subst _ _ _ _ _ _ _ _ _ _ I_Free_Vars_invert I_Ty_Wrap_inject)\n    (Free_Vars_Subst_H3 _ _ _ Ty_trans _ TE_Free_Vars id)\n    (Free_Vars_Subst_H4 _ _ _ Ty_trans _ Free_Vars TE_Free_Vars id GJ_TE_Free_Vars_invert \n      GJ_TE_Free_Vars_invert TE_trans GTy_ext_Wrap_inject GJ_TE_Trans_invert).\n  \n  Definition map_Ty_trans_P := map_Ty_trans_P _ _ N Ty_trans Free_Vars.\n  \n  Definition map_Ty_trans_Q := map_Ty_trans_Q _ _ _ N Ty_trans TE_Free_Vars TE_trans.\n  \n  Lemma NIn_Ty_trans : forall X Xs Us, ~In X Xs -> Ty_trans (Gty (TyVar _ X)) Xs Us = Gty (TyVar _ X).\n    simpl; eapply (GNIn_Ty_trans _ eq_nat_dec Ty Gty _ _ Empty build_fresh TUpdate).\n  Qed.\n    \n  Lemma Ty_trans_FJ : forall ty Xs Us, Ty_trans (FJ_Ty_Wrap ty) Xs Us = \n    FJ_Ty_Trans _ _ _ _ _  FJ_Ty_Wrap id TE_trans ty Xs Us.\n    simpl; reflexivity.\n  Qed.\n\n  Definition map_Ty_trans :=\n    ty_rect map_Ty_trans_P map_Ty_trans_Q\n    (map_Ty_trans_H1 _ eq_nat_dec _ Gty _ Ty_trans Free_Vars GJ_Free_Vars_invert\n      GJ_Ty_Wrap_inject NIn_Ty_trans)\n    (map_Ty_trans_H2 _ _ _ _ N N_Wrap cFJ_N Ty_trans FJ_Ty_Wrap_inject Free_Vars TE_Free_Vars \n      FJ_Free_Vars_invert TE_trans Ty_trans_FJ)\n    (I_map_Ty_trans _ _ _ _ _ _ N_Wrap I_N_Wrap _ _ _ I_Free_Vars_invert I_Ty_trans_invert I_Ty_Wrap_inject)\n    (map_Ty_trans_H3 _ _ _ _ Ty_trans _ TE_Free_Vars id)\n    (map_Ty_trans_H4 _ _ _ _ Ty_trans _ Free_Vars TE_Free_Vars id GJ_TE_Free_Vars_invert \n      GJ_TE_Free_Vars_invert TE_trans GTy_ext_Wrap_inject GJ_TE_Trans_invert).\n  \n  Definition map_Ty_trans_P' ty := \n    forall (Xs Ys : list _) (Us tys : list Ty) (typs : TyP_List),\n      Free_Vars ty Ys -> length typs = length tys -> \n      (forall X : _, In X Ys -> In X (Extract_TyVar _ _ typs)) ->\n      Ty_trans (Ty_trans ty (Extract_TyVar _ _ typs) tys) Xs Us =\n      Ty_trans ty (Extract_TyVar _ _ typs)\n      (map (fun ty0 : Ty => Ty_trans ty0 Xs Us) tys).\n  \n  Definition map_Ty_trans_Q' te := forall Xs Ys Us tys typs,\n    TE_Free_Vars te Ys -> length typs = length tys -> \n    (forall X : nat, In X Ys -> In X (Extract_TyVar _ N typs)) ->\n    TE_trans (TE_trans te (Extract_TyVar _ _ typs) tys) Xs Us =\n    TE_trans te (Extract_TyVar _ _ typs)\n    (map (fun ty0 : Ty => Ty_trans ty0 Xs Us) tys).\n  \n  Definition map_Ty_trans' :=\n    ty_rect map_Ty_trans_P' map_Ty_trans_Q'\n    (map_Ty_trans'_H1 _ eq_nat_dec _ Gty _ Ty_trans Free_Vars GJ_Free_Vars_invert\n      GJ_Ty_Wrap_inject)\n    (map_Ty_trans'_H2 _ _ _ _ N N_Wrap cFJ_N Ty_trans FJ_Ty_Wrap_inject Free_Vars TE_Free_Vars \n      FJ_Free_Vars_invert TE_trans Ty_trans_FJ)\n    (I_map_Ty_trans' _ _ _ _ _ _  N_Wrap I_N_Wrap _ _ _ I_Free_Vars_invert I_Ty_trans_invert I_Ty_Wrap_inject)\n    (map_Ty_trans'_H3 _ _ _ _ Ty_trans _ TE_Free_Vars id)\n    (map_Ty_trans'_H4 _ _ _ _ Ty_trans _ Free_Vars TE_Free_Vars (fun x => x) GJ_TE_Free_Vars_invert \n      GJ_TE_Free_Vars_invert TE_trans GTy_ext_Wrap_inject GJ_TE_Trans_invert).\n\n  Definition wf_free_vars_P := Generic.wf_free_vars_P _ _ _ _ Empty WF_Type TUpdate Free_Vars.\n\n  Definition wf_free_vars_Q := Generic.wf_free_vars_Q _ _ _ N N_Wrap _ Empty subtype\n    Ty_trans WF_Type TUpdate I_cld_ext unit TE_Free_Vars id.\n  \n  Definition wf_free_vars_Q_P1 := wf_free_vars_Q_P1 _ _ _ _ Empty WF_Type TUpdate Free_Vars.\n\n  Definition wf_free_vars_Q'' := wf_free_vars_Q'' _ _ _ _ _ wf_int_ext TUpdate Empty TE_Free_Vars.\n  \n  Variables (TLookup_TUpdate_eq : forall (gamma : Context) (X : _) (ty : _), TLookup (TUpdate gamma X ty) X ty)\n    (TLookup_TUpdate_neq' : forall (gamma : Context) (Y X : _) (ty ty' : _),\n      TLookup (TUpdate gamma Y ty') X ty -> X <> Y -> TLookup gamma X ty)\n    (TLookup_id : forall (gamma : Context) (X : _) (ty ty' : _),\n      TLookup gamma X ty -> TLookup gamma X ty' -> ty = ty').\n\n  Definition wf_free_vars :=\n    WF_Type_rect' wf_free_vars_P wf_free_vars_Q wf_free_vars_Q_P1 wf_free_vars_Q''\n    (wf_free_vars_ext_H1 _ _ _ _ _ _ Empty subtype Ty_trans WF_Type TUpdate\n      _ _ Free_Vars TE_Free_Vars id GJ_TE_Free_Vars_invert)\n    (wf_free_vars_ext_H2 _ _ _ _ Empty WF_Type TUpdate Free_Vars)\n    (wf_free_vars_ext_H3 _ _ _ _ Empty WF_Type TUpdate Free_Vars)\n    (I_wf_free_vars_ext _ _ N _ WF_Type subtype Ty_trans N_Wrap TUpdate Empty \n      unit _ Free_Vars)\n    (GJ_wf_free_vars _ eq_nat_dec _ Gty _ _ Empty TLookup WF_Type\n      GJ_WF_Type TUpdate TLookup_Empty Free_Vars GJ_Free_Vars_invert GJ_Ty_Wrap_inject\n      TLookup_TUpdate_eq TLookup_TUpdate_neq' TLookup_id)\n    (FJ_wf_free_vars_H1 _ _ _ _ _ N_Wrap _ _ Empty WF_Type _ _ _ TUpdate _ FJ_Ty_Wrap_inject md_ext \n      cld_ext CT wf_class_ext wf_object_ext cFJ_WF_Type Free_Vars TE_Free_Vars\n      FJ_Free_Vars_invert (GJ_TE_Free_Vars_obj _ _ _ _ Free_Vars))\n    (FJ_wf_free_vars_H2 _ _ _ _ _ N_Wrap _ _ Empty WF_Type _ _ _ TUpdate _ FJ_Ty_Wrap_inject\n      _ _ CT wf_class_ext wf_object_ext cFJ_WF_Type Free_Vars TE_Free_Vars\n      FJ_Free_Vars_invert)\n    (I_wf_free_vars _ _ _ _ _ _ _ _ N _ WF_Type wf_int_ext N_Wrap I_N_Wrap _ _ IT I_WF_Type_Wrap _ _ \n      I_Free_Vars_invert I_Ty_Wrap_inject).\n\n  Definition exists_Free_Vars :=\n    ty_rect (exists_Free_Vars_P nat Ty Free_Vars) (exists_Free_Vars_Q nat _ TE_Free_Vars)\n    (exists_Free_Vars_H1 _ _ Gty _ GJ_Free_Vars')\n    (exists_Free_Vars_H2 _ _ _ _ _ _ _ _ _ FJ_Free_Vars')\n    (I_exists_Free_Vars _ _ _ _ _ N_Wrap I_N_Wrap _ _ I_Free_Vars')\n    (exists_Free_Vars_H3 _ _ _ _ Free_Vars TE_Free_Vars id (fun _ _ => id))\n    (exists_Free_Vars_H4 _ _ _ _ Free_Vars TE_Free_Vars id (fun _ _ => id) (fun _ _ => id)).\n  \n  Lemma L_build_context'_Empty_1 : forall ce  (gamma : Context)\n    (XNs : Generic.TyP_List nat N) (T : Ty),\n    L_build_context' ce gamma ->\n    WF_Type (update_Tlist gamma XNs) T ->\n    WF_Type (update_Tlist Empty XNs) T.\n    intros; inversion H; subst; assumption.\n  Qed.\n    \n  Definition Type_Subst_Sub_2_5_P := \n    Generic.Type_Subst_Sub_2_5_P nat Ty N N_Wrap Context TLookup\n    subtype Ty_trans WF_Type TUpdate app_context Free_Vars N_trans subst_context.\n  \n  Lemma Ty_trans_eq_NTy_trans : forall (N0 : N) (Xs : list _) (Us : list Ty),\n    N_Wrap (N_trans N0 Xs Us) = Ty_trans (N_Wrap N0) Xs Us.\n    intros; destruct N0; simpl.\n    destruct f; simpl; unfold Generic.FJ_Ty_Wrap; reflexivity.\n    destruct i; simpl; unfold I_Ty_Wrap; reflexivity.\n  Qed.\n  \n  Lemma N_Wrap_inject : forall n n' : N, N_Wrap n = N_Wrap n' -> n = n'.\n    intros; injection H; auto.\n  Qed.\n  \n  Lemma FJ_WF_Type_Wrap_invert : forall delta S, WF_Type delta ( FJ_Ty_Wrap S) ->\n    cFJ.FJ_WF_Type _ _ _ _ _ _  FJ_Ty_Wrap _ _ _ CT Context \n    (wf_class_ext' WF_Type) wf_object_ext delta ( FJ_Ty_Wrap S).\n    intros; inversion H; subst; try eapply H0.\n    inversion H0.\n    inversion H0.\n  Qed.\n\n  Lemma I_WF_Type_invert : forall (gamma : Context) (ity : I_Ty _ ty_ext),\n    WF_Type gamma (I_Ty_Wrap ity) -> Interface.I_WF_Type nat ty_ext Ty\n    I_Ty_Wrap mty_ext nat nat Interface_ext Context IT wf_int_ext gamma (I_Ty_Wrap ity).\n    intros; inversion H; inversion H0; subst; auto.\n  Qed.\n\n  Lemma L_build_context_unique : forall ce gamma gamma', \n    L_build_context ce gamma -> L_build_context ce gamma' -> gamma = gamma'.\n    intros; inversion H; inversion H0; subst; injection H5; intros; subst.\n    inversion H1; inversion H4; subst; reflexivity.\n  Qed.\n\n  Lemma L_WF_GI_L_WF_Ext : forall (gamma : Context) (ce : cld_ext) (c : nat)\n    (ty : cFJ.FJ_Ty nat (GTy_ext Ty)) (fs : list (cFJ.FD nat Ty))\n    (k' : K nat nat Ty) (ms : list (cFJ.MD nat nat Ty E md_ext)),\n  Generic.L_build_context nat N Context TUpdate L_build_context' ce gamma ->\n  Generic_Interface.L_WF nat Ty (GTy_ext Ty) nat nat N Context WF_Type\n    subtype N_Wrap cld_ext ce_build_cte cFJ_N Empty Update nat E md_ext CT\n    fields E_WF\n    (Generic.L_build_context nat N Context TUpdate L_build_context') override\n    L_WF_Ext Meth_build_context Meth_WF_Ext\n    (cld (GTy_ext Ty) Ty nat nat nat nat E md_ext cld_ext ce c ty fs k' ms) ->\n    GI_L_WF_Ext _ Ty ty_ext N _ WF_Type N_Wrap I_N_Wrap _ implements Empty gamma ce.\n    intros; inversion H; inversion H0; inversion H18; subst.\n    rewrite (L_build_context_unique _ _ _ H10 H) in H20; tauto.\n  Qed.\n\n  Lemma L_WF_GI_L_WF_Ext' : forall c cld, \n    CT c = Some cld -> \n    Generic_Interface.L_WF _ Ty ty_ext _ _ N Context WF_Type subtype N_Wrap cld_ext ce_build_cte cFJ_N\n    Empty Update _ _ md_ext CT fields E_WF (Generic.L_build_context nat N Context TUpdate L_build_context')\n    override L_WF_Ext Meth_build_context Meth_WF_Ext cld.\n    intros; generalize (WF_CT _ _ H); intros; inversion H0; subst.\n    econstructor; try eassumption; reflexivity.\n  Qed.\n\n  Fixpoint Type_Subst_Sub_2_5 delta S T (sub_S_T : subtype delta S T) : \n    Type_Subst_Sub_2_5_P delta S T sub_S_T :=\n    match sub_S_T in (subtype delta S T) return (Type_Subst_Sub_2_5_P delta S T sub_S_T) with\n      | cFJ_sub delta S' T' sub_S_T' => Type_Subst_Sub_2_5_FJ _ _ _ _ N N_Wrap cFJ_N\n        _ Empty TLookup subtype Ty_trans\n        WF_Type _ fields _ _ TUpdate app_context Update _ FJ_Ty_Wrap_inject _ _ CT\n        build_te cFJ_sub wf_class_ext wf_object_ext E_WF Free_Vars TE_trans FJ_Ty_trans_invert \n        exists_Free_Vars N_trans subst_context\n        ce_build_cte Meth_build_context Meth_WF_Ext L_WF_Ext L_build_context override\n        FJ_WF_Type_Wrap_invert WF_CT (@Generic.GJ_Type_Subst_Sub_2_5_TE _ _ _ N_Wrap _\n           Empty subtype Ty_trans WF_Type TUpdate _ _ Free_Vars exists_Free_Vars\n          N_trans wf_free_vars map_Ty_trans' _ L_build_context'_Empty_1 \n          _)\n        (@GJ_Type_Subst_Sub_2_5_TE' _ _ _ _ _ subtype Ty_trans _ _ _ _ _ _ _)\n        Type_Subst_Sub_2_5 delta S' T' sub_S_T'\n      | GJ_sub delta S' T' sub_S_T' => Type_Subst_Sub_2_5_GJ _ eq_nat_dec _ Gty _ _ _ TLookup subtype\n        GJ_sub Ty_trans WF_Type TUpdate app_context TLookup_app Weakening_2_1_1\n        Free_Vars GJ_Free_Vars' GJ_Ty_trans_invert Ty_trans_nil NIn_Ty_trans exists_Free_Vars \n        N_Wrap_inject N_trans\n        subst_context TLookup_subst map_Ty_trans TLookup_dec TLookup_unique TLookup_app'\n        TLookup_app'' TLookup_update_eq TLookup_update_neq' Free_Vars_Subst Ty_trans_eq_NTy_trans\n        delta S' T' sub_S_T'\n      | I_subtype_Wrap delta S' T' sub_S_T' => I_Type_Subst_Sub_2_5 _ _ _ _ _ _ _ _ _ N _\n        TLookup WF_Type subtype Ty_trans wf_int_ext N_Wrap I_N_Wrap TUpdate cld_ext ce_build_cte\n        implements cFJ_N Empty Update _ _ _ _ CT _ I_subtype_Wrap IT _ _ I_Ty_trans_invert\n        I_Ty_Wrap_inject FJ_Ty_trans_invert _ _ _ _ _ override _ _ _ \n        (@Generic_Interface.GJ_Type_Subst_Sub_2_5_TE _ _ _ _ WF_Type \n          subtype Ty_trans N_Wrap TUpdate Empty _ _ Free_Vars N_trans _ \n          _ exists_Free_Vars map_Ty_trans' wf_free_vars L_build_context'_Empty_1 _)\n        L_WF_GI_L_WF_Ext' I_WF_Type_invert L_WF_GI_L_WF_Ext delta S' T' sub_S_T'\n    end.\n\n  Definition Type_Subst_WF_2_6_P := Generic.Type_Subst_WF_2_6_P _ _ _ N_Wrap\n    _ TLookup subtype Ty_trans WF_Type TUpdate app_context Free_Vars N_trans subst_context.\n\n  Definition cld_typs (cld' : cFJ.L nat nat nat nat ty_ext Ty E md_ext cld_ext) :=\n    match cld' with cFJ.cld (typs, _) _ _ _ _ _  => typs\n    end.\n  \n  Definition Type_Subst_WF_2_6_Q := Type_Subst_WF_2_6_Q _ _ _ _ N_Wrap\n    _ TLookup subtype WF_Type TUpdate app_context _ \n    wf_class_ext Free_Vars TE_trans N_trans subst_context (@fst _ _).\n  \n  Definition Type_Subst_WF_2_6_P1 := Generic.Type_Subst_WF_2_6_P1 _ _ _  N_Wrap _ \n    TLookup subtype Ty_trans WF_Type TUpdate app_context Free_Vars N_trans subst_context.\n\n  Definition Type_Subst_WF_2_6_Q'' := Type_Subst_WF_2_6_Q'' _ _ _ _ N _ \n    TLookup WF_Type subtype wf_int_ext N_Wrap TUpdate app_context  \n    Free_Vars TE_trans N_trans subst_context (@fst _ _).\n\n  Definition Ty_trans_trans_subst :=\n    ty_rect (Ty_trans_trans_subst_P _ _ Ty_trans Free_Vars)\n  (Ty_trans_trans_subst_Q _ _ _ Ty_trans TE_Free_Vars TE_trans)\n  (fun n => (GJ_Ty_trans_trans_subst _ eq_nat_dec _ Gty _ Ty_trans build_fresh\n    Free_Vars GJ_Free_Vars_invert GJ_Ty_Wrap_inject GJ_Ty_trans_invert (TyVar _ n)))\n  (FJ_Ty_trans_trans_subst _ _ _ _ _ N_Wrap _ Ty_trans FJ_Ty_Wrap_inject Free_Vars TE_Free_Vars FJ_Free_Vars_invert\n    TE_trans FJ_Ty_trans_invert)\n  (I_Ty_trans_trans_subst _ _ _ _ _ Ty_trans N_Wrap I_N_Wrap _ _ _ I_Free_Vars_invert\n    I_Ty_trans_invert I_Ty_Wrap_inject)\n  (Ty_trans_trans_subst_H3 _ _ _ Ty_trans _ Free_Vars id GTy_ext_Wrap_inject)\n  (Ty_trans_trans_subst_H4 _ _ _ _ Ty_trans build_fresh _ \n    Free_Vars TE_Free_Vars id (fun _ _ => id) TE_trans\n    GTy_ext_Wrap_inject GJ_TE_Trans_invert).\n \n  Lemma Int_build_context'_Empty_1 : forall ce gamma XNs T, (I_Int_build_context Context Empty) ce gamma -> \n    WF_Type (update_Tlist gamma XNs) T -> WF_Type (update_Tlist Empty XNs) T.\n    intros; inversion H; subst; assumption.\n  Qed.\n\n  Lemma Int_WF_bound : forall int, I_WF int -> exists Ys,\n      List_P2' (fun (typ : _ * N) => Free_Vars (N_Wrap (snd typ))) (fst (Interface_ie _ _ _ _ _ _ int)) Ys /\\\n      forall Y, In Y (fold_right (@app _) nil Ys) -> \n        In Y (Extract_TyVar _ _ (fst (Interface_ie _ _ _ _ _ _ int))).\n    intros; inversion H; subst; simpl.\n    eapply GI_I_WF_bound.\n    apply exists_Free_Vars.\n    eapply wf_free_vars.\n    Focus 2.\n    apply H0.\n    apply Int_build_context'_Empty_1.\n    apply H2.\n  Qed.\n\n  Definition cld_typs' : cld_ext -> Generic.TyP_List nat N := (@fst _ _).\n\nLemma L_WF_bound : forall cld : cFJ.L nat nat nat nat ty_ext Ty E md_ext cld_ext,\n  Generic.L_WF Ty ty_ext nat N N_Wrap cFJ_N Context Empty subtype WF_Type\n    nat fields nat nat Update E md_ext cld_ext CT E_WF ce_build_cte\n    Meth_build_context Meth_WF_Ext L_WF_Ext L_build_context override cld ->\n  exists Ys : list (list nat),\n    List_P2' (fun typ : Generic.GTy nat * N => Free_Vars (N_Wrap (snd typ)))\n      (Generic.cld_typs' nat Ty ty_ext nat N nat nat nat E md_ext cld_ext\n         cld_typs' cld) Ys /\\\n    (forall Y : nat,\n     In Y (fold_right (@app _) nil Ys) ->\n     In Y\n       (Extract_TyVar nat N\n          (Generic.cld_typs' nat Ty ty_ext nat N nat nat nat E md_ext cld_ext\n             cld_typs' cld))).\n    intros; inversion H; subst; simpl.\n    eapply GJ_L_WF_bound.\n    apply exists_Free_Vars.\n    eapply wf_free_vars.\n    Focus 2.\n    apply H0.\n    intros; inversion H1; subst; assumption.\n    apply H8.\n  Qed.\n\n\n  Definition Type_Subst_WF_2_6 :=\n    WF_Type_rect' Type_Subst_WF_2_6_P Type_Subst_WF_2_6_Q Type_Subst_WF_2_6_P1\n    Type_Subst_WF_2_6_Q''\n    (Type_Subst_WF_2_6_ext_H1 _ _ N N_Wrap\n      _ TLookup subtype Ty_trans WF_Type TUpdate app_context _ _\n      Free_Vars N_trans subst_context Type_Subst_Sub_2_5 Ty_trans_trans_subst)\n    (Type_Subst_WF_2_6_ext_H2 _ _ _ _ _ TLookup subtype Ty_trans WF_Type TUpdate app_context\n      Free_Vars N_trans subst_context)\n    (Type_Subst_WF_2_6_ext_H3 _ _ _ _ _ TLookup subtype Ty_trans WF_Type TUpdate app_context\n      Free_Vars N_trans  subst_context)\n    (I_Type_Subst_WF_2_6_ext _ _ _ _ TLookup _ _ _ N_Wrap TUpdate _ _ app_context\n      Free_Vars N_trans subst_context Type_Subst_Sub_2_5 Ty_trans_trans_subst)\n    (GJ_Type_Subst_WF_2_6 _ eq_nat_dec _ Gty _ _ _ TLookup subtype\n      Ty_trans WF_Type GJ_WF_Type TUpdate app_context TLookup_app Weakening_2_1_2\n      Free_Vars GJ_Ty_trans_invert Ty_trans_nil Ty_trans_nil' N_trans subst_context\n      TLookup_subst TLookup_dec TLookup_app' TLookup_app''\n       TLookup_update_neq')\n    (FJ_Type_Subst_WF_2_6_H1 _ _ _ _ _ N_Wrap _ _ TLookup subtype Ty_trans\n      WF_Type _ _ _ TUpdate app_context _ _ _ CT wf_class_ext wf_object_ext\n      cFJ_WF_Type Free_Vars TE_trans FJ_Ty_trans_invert N_trans subst_context \n      (GJ_Type_Subst_WF_2_6_obj_ext _ _ _ Ty_trans app_context _ subst_context))\n    (FJ_Type_Subst_WF_2_6_H2 _ _ _ _ _ N_Wrap _ _ Empty TLookup subtype Ty_trans\n      WF_Type _ fields _ _ TUpdate app_context Update _ _ _ CT wf_class_ext \n      wf_object_ext cFJ_WF_Type E_WF Free_Vars TE_trans FJ_Ty_trans_invert N_trans subst_context \n      _ _ _ _ _ override WF_CT cld_typs' L_WF_bound)\n    (I_Type_Subst_WF_2_6 _ _ _ _ _ _ _ _ _ _ _ _ _ _ wf_int_ext N_Wrap I_N_Wrap _ _ IT\n      I_WF_Type_Wrap _ _ I_Ty_trans_invert N_trans _ (@fst _ _) _ _ _ _ WF_IT Int_WF_bound).\n\n  Variable (subst_context_Empty : forall Xs Us, subst_context Empty Xs Us = Empty)\n    (app_context_Empty : forall gamma, app_context gamma Empty = gamma).\n  \n  Fixpoint Ty_rename ty n : Ty :=\n    match ty with \n      | N_Wrap (I_N_Wrap ty) => I_Ty_rename _ _ _ _ _ N_Wrap I_N_Wrap (GJ_TE_rename nat _ unit Ty_rename) ty n\n      | N_Wrap (cFJ_N ty) => FJ_Ty_rename _ _ _ _ N N_Wrap cFJ_N (GJ_TE_rename nat _ unit Ty_rename) ty n\n      | Gty ty' => GJ_Ty_rename _ _ Gty plus ty' n\n    end.\n  \n  Definition TE_rename := GJ_TE_rename nat _ unit Ty_rename.\n  \n  Definition NTy_rename n n' : N := \n    match n with \n      | I_N_Wrap ty => I_Ty_rename _ _ _ _ _ I_N_Wrap id (GJ_TE_rename nat _ unit Ty_rename) ty n'\n      | cFJ_N ty => FJ_Ty_rename _ _ _ _ N id cFJ_N (GJ_TE_rename nat _ unit Ty_rename) ty n'\n    end.\n  \n  Variables (rename_context : Context -> nat -> Context)\n    (TLookup_rename_context : forall gamma x ty n, \n      TLookup gamma x ty -> TLookup (rename_context gamma n) (x + n) (NTy_rename ty n))\n    (TLookup_rename_context' : forall gamma x ty n, \n      TLookup (rename_context gamma n) x ty -> exists x', exists ty', x = x' + n /\\ \n        ty = NTy_rename ty' n /\\ TLookup gamma x' ty').\n  \n  Lemma rename_X_eq : forall Y Y' X', plus Y X' = plus Y' X' -> Y = Y'.\n    intros; omega.\n  Qed.\n  \n  Lemma GJ_Ty_rename_invert : forall ty Y, Ty_rename (Gty ty) Y = GJ_Ty_rename _ _ Gty plus ty Y.\n    reflexivity.\n  Qed.\n  \n  Lemma I_Ty_rename_invert : forall (ty : _) Y, \n    Ty_rename (I_Ty_Wrap ty) Y = I_Ty_rename _ _ _ _ N N_Wrap I_N_Wrap TE_rename ty Y.\n    reflexivity.\n  Qed.\n\n  Definition Ty_rename_Ty_trans :=\n    ty_rect (Generic.Ty_rename_Ty_trans_P _ _ Ty_trans plus Ty_rename)\n    (Generic.Ty_rename_Ty_trans_Q _ _ _ TE_trans plus Ty_rename TE_rename)\n    (GJ_Ty_rename_Ty_trans _ eq_nat_dec _ Gty Ty_trans GJ_Ty_trans_invert Ty_trans_nil' \n      plus Ty_rename rename_X_eq GJ_Ty_rename_invert)\n    (FJ_Ty_rename_Ty_trans _ _ _ _ _ _ _ Ty_trans TE_trans FJ_Ty_trans_invert plus Ty_rename\n      TE_rename (fun _ _ => refl_equal _))\n    (I_Ty_rename_Ty_trans _ _ _ _ _ _ _ _ _ I_Ty_trans_invert _ _ plus I_Ty_rename_invert)\n    (Ty_rename_Ty_trans_H3 _ _ Ty_trans _ plus Ty_rename)\n    (Ty_rename_Ty_trans_H4 _ _ _ Ty_trans _ id TE_trans GTy_ext_Wrap_inject \n      GJ_TE_Trans_invert plus Ty_rename TE_rename (fun _ _ => refl_equal _)).     \n  \n  Definition FV_subst_tot := ty_rect (FV_subst_tot_P _ _ Ty_trans Free_Vars)\n    (FV_subst_tot_Q _ _ _ Free_Vars TE_Free_Vars TE_trans)\n    (GJ_FV_subst_tot _ eq_nat_dec _ Gty Ty_trans Free_Vars GJ_Free_Vars_invert\n      GJ_Ty_Wrap_inject GJ_Ty_trans_invert)\n    (FJ_FV_subst_tot _ _ _ _ _ N_Wrap cFJ_N Ty_trans FJ_Ty_Wrap_inject Free_Vars TE_Free_Vars\n      FJ_Free_Vars' FJ_Free_Vars_invert TE_trans FJ_Ty_trans_invert)\n    (I_FV_subst_tot _ _ _ _ _ _ _ _ _ _ _ I_Free_Vars' I_Free_Vars_invert I_Ty_trans_invert\n      I_Ty_Wrap_inject)\n    (FV_subst_tot_H3 _ _ Ty_trans _ Free_Vars)\n    (FV_subst_tot_H4 _ _ _ Ty_trans _ Free_Vars TE_Free_Vars id (fun _ _ => id) \n      (fun _ _  => id) TE_trans GJ_TE_Trans_invert).\n\n  Definition Ty_rename_eq_Ty_trans := ty_rect \n    (Generic.Ty_rename_eq_Ty_trans_P _ _ Gty Ty_trans Free_Vars plus Ty_rename)\n    (Generic.Ty_rename_eq_Ty_trans_Q _ _ _ Gty TE_Free_Vars TE_trans plus TE_rename)\n    (GJ_Ty_rename_eq_Ty_trans _ eq_nat_dec _ Gty Ty_trans Free_Vars GJ_Free_Vars_invert\n      GJ_Ty_Wrap_inject GJ_Ty_trans_invert plus Ty_rename GJ_Ty_rename_invert)\n    (FJ_Ty_rename_eq_Ty_trans _ _ _ Gty _ _ N_Wrap cFJ_N Ty_trans FJ_Ty_Wrap_inject Free_Vars TE_Free_Vars\n      FJ_Free_Vars_invert TE_trans FJ_Ty_trans_invert plus Ty_rename\n      TE_rename (fun _ _ => refl_equal _))\n    (I_Ty_rename_eq_Ty_trans _ _ _ _ _ _ _ N_Wrap I_N_Wrap _ _ _ \n      I_Free_Vars_invert I_Ty_trans_invert I_Ty_Wrap_inject\n      Ty_rename TE_rename plus I_Ty_rename_invert)\n    (Ty_rename_eq_Ty_trans_H3 _ _ Gty Ty_trans _ Free_Vars plus Ty_rename)\n    (Ty_rename_eq_Ty_trans_H4 _ _ _ Gty Ty_trans _ Free_Vars TE_Free_Vars id (fun _ _ => id)\n      TE_trans (fun _ _ => id) (fun _ _ _ => refl_equal _) plus Ty_rename TE_rename (fun _ _ => refl_equal _)).\n\n  Lemma Ty_rename_eq_NTy_rename : forall (n : N) (X : _), Ty_rename (N_Wrap n) X = N_Wrap (NTy_rename n X).\n    destruct n.\n    simpl; unfold FJ_Ty_rename; unfold Generic.FJ_Ty_rename; intros; destruct f;\n      unfold Generic.FJ_Ty_Wrap; unfold id; reflexivity.\n    simpl; unfold I_Ty_rename; intros; destruct i; unfold I_Ty_Wrap; reflexivity.\n  Qed.\n\n  Lemma FJ_Ty_rename_invert : forall (ty : cFJ.FJ_Ty nat ty_ext) Y,\n    Ty_rename (FJ_Ty_Wrap ty) Y =\n    Generic.FJ_Ty_rename _ Ty ty_ext nat N N_Wrap cFJ_N TE_rename ty Y.\n    reflexivity.\n  Qed.\n\n  Lemma L_WF_GI_L_WF_Ext'' : forall (gamma : Context) (ce : cld_ext) \n    (c : _) (ty : cFJ.FJ_Ty _ ty_ext) (fs : list (cFJ.FD _ Ty)) (k' : K _ _ Ty)\n    (ms : list (cFJ.MD _ _ Ty E md_ext)),\n    L_build_context ce gamma ->\n    Generic_Interface.L_WF _ Ty ty_ext _ _ N Context\n    WF_Type subtype N_Wrap cld_ext ce_build_cte cFJ_N\n    Empty Update _ E md_ext CT fields E_WF L_build_context override L_WF_Ext Meth_build_context\n    Meth_WF_Ext (cld ty_ext Ty _ _ _ _ _ md_ext cld_ext ce c ty fs k' ms) ->\n    GI_L_WF_Ext _ Ty ty_ext N Context WF_Type N_Wrap\n    I_N_Wrap cld_ext implements Empty gamma ce.\n    intros; inversion H; inversion H0; inversion H18; subst.\n    rewrite (L_build_context_unique _ _ _ H10 H) in H20.\n    tauto.\n  Qed.\n\n  Fixpoint Ty_rename_subtype delta S T (sub_S_T : subtype delta S T) :=\n    match sub_S_T in (subtype delta S T) return (Ty_rename_subtype_P _ _ _ subtype Ty_rename rename_context delta S T sub_S_T) with\n      | cFJ_sub delta S' T' sub_S_T' => \n        FJ_Ty_rename_subtype nat Ty ty_ext nat N  N_Wrap cFJ_N Context Empty\n        subtype WF_Type nat fields nat nat Update E FJ_Ty_Wrap_inject md_ext cld_ext CT\n        build_te cFJ_sub wf_class_ext wf_object_ext E_WF \n        ce_build_cte Meth_build_context Meth_WF_Ext L_WF_Ext \n        L_build_context override FJ_WF_Type_Wrap_invert WF_CT Ty_rename\n        TE_rename rename_context (fun _ _ => refl_equal _) \n        (fun (gamma : Context) (ce : cld_ext) (c : nat) \n          (te te'' te' : GTy_ext Ty) (n : nat) cld' (bld : L_build_context ce gamma)\n          (L_WF_E : L_WF_Ext gamma ce c) H1 H2 => \n          @GJ_rename_build_te nat Ty Gty nat N N_Wrap Context Empty subtype Ty_trans\n          WF_Type TUpdate _ _ Free_Vars exists_Free_Vars wf_free_vars\n          L_build_context' L_build_context'_Empty_1 Ty_trans_trans_subst plus\n          Ty_rename Ty_rename_eq_Ty_trans FV_subst_tot _\n          (fun gamma (ie : I_cld_ext) c => FJ_L_WF_Ext _ _ gamma (@snd _ _ ie) c)\n          gamma ce c te te'' te' n cld' bld (match L_WF_E with conj H3 _ => H3 end) H1 H2)\n        (fun (gamma : Context) (ce : cld_ext) (c : nat) \n          (te te'' te' : GTy_ext Ty) (n : nat) (bld : L_build_context ce gamma)\n          (L_WF_E : L_WF_Ext gamma ce c) => \n          @GJ_rename_build_te_obj _ _ _ _ N_Wrap _ Ty_trans WF_Type TUpdate _ _ L_build_context' Ty_rename\n          (fun (ice : I_cld_ext) te te' te'' => FJ_build_te (snd ice) te te' te'') \n          (fun gamma (ie : I_cld_ext) c => FJ_L_WF_Ext _ _ gamma (@snd _ _ ie) c )\n          gamma ce c te te'' te' n bld (match L_WF_E with conj H3 _ => H3 end)) \n        Ty_rename_subtype delta S' T' sub_S_T'\n      | GJ_sub delta S' T' sub_S_T' => GJ_Ty_rename_subtype _ _ Gty _ _ _ TLookup subtype \n        GJ_sub plus Ty_rename NTy_rename Ty_rename_eq_NTy_rename rename_context \n        TLookup_rename_context GJ_Ty_rename_invert delta S' T' sub_S_T'\n      | I_subtype_Wrap delta S' T' sub_S_T' => I_Ty_rename_subtype _ _ _ _ _ _ _ _ _ N\n        Context WF_Type subtype wf_int_ext N_Wrap I_N_Wrap _ ce_build_cte implements cFJ_N\n        Empty Update _ _ _ CT\n        isub_build_te I_subtype_Wrap IT I_Ty_Wrap_inject fields E_WF Ty_rename TE_rename\n        L_build_context override L_WF_Ext\n        Meth_build_context Meth_WF_Ext WF_CT I_WF_Type_invert\n        L_WF_GI_L_WF_Ext'' rename_context I_Ty_rename_invert FJ_Ty_rename_invert\n        (fun (gamma : Context) (ce : cld_ext) (ie : GInterface_ext nat N)\n          (c : nat) (te te'' te' : GTy_ext Ty) (n : nat)\n          (H : L_build_context ce gamma) (H0 : L_WF_Ext gamma ce c)\n          (H1 : wf_int_ext gamma ie te') (H2 : isub_build_te ce te te' te'') =>\n          I_rename_isub_build_te nat nat Ty N Gty Context WF_Type subtype Ty_trans\n          N_Wrap TUpdate Empty unit unit Free_Vars Ty_rename I_cld_ext\n          L_build_context' exists_Free_Vars wf_free_vars L_build_context'_Empty_1\n          Ty_trans_trans_subst plus Ty_rename_eq_Ty_trans FV_subst_tot gamma ce ie\n          c te te'' te' n H match H0 with\n                              | conj H3 _ => H3\n                            end H1 H2) _ _ _ sub_S_T'\n    end.\n\n  Definition Free_Vars_id := ty_rect\n    (Free_Vars_id_P _ _ Free_Vars) (Free_Vars_id_Q _ _ TE_Free_Vars)\n    (GJ_Free_Vars_id _ _ Gty Free_Vars GJ_Free_Vars_invert GJ_Ty_Wrap_inject)\n    (FJ_Free_Vars_id _ _ _ _ _ N_Wrap cFJ_N FJ_Ty_Wrap_inject Free_Vars TE_Free_Vars FJ_Free_Vars_invert)\n    (I_Free_Vars_id _ _ _ _ _ _ _ _ _ I_Free_Vars_invert I_Ty_Wrap_inject)\n    (Free_Vars_id_H3 _ _ _ Free_Vars)\n    (Free_Vars_id_H4 _ _ _ _ Free_Vars TE_Free_Vars id (fun _ _ => id)).\n\n  Definition Ty_rename_WF_Type := WF_Type_rect' \n    (Ty_rename_WF_Type_P _ _ _ WF_Type Ty_rename rename_context)\n    (Ty_rename_WF_Type_Q _ _ _ _ N_Wrap _ _ wf_class_ext Free_Vars cld_typs' TE_rename \n      rename_context)\n    (Ty_rename_WF_Type_P1 _ _ _ WF_Type Ty_rename rename_context)\n    (Ty_rename_WF_Type_Q'' _ _ _ _ _ _ wf_int_ext N_Wrap Free_Vars TE_rename (@fst _ _) rename_context)\n    (Ty_rename_WF_Type_ext_H1 _ _ Gty N N_Wrap _ subtype Ty_trans WF_Type _ _ Free_Vars\n      exists_Free_Vars Ty_trans_trans_subst plus Ty_rename rename_context Ty_rename_eq_Ty_trans \n      FV_subst_tot Ty_rename_subtype Free_Vars_id)\n    (Ty_rename_WF_Type_ext_H2 _ _ _ WF_Type Ty_rename rename_context)\n    (Ty_rename_WF_Type_ext_H3 _ _ _ WF_Type Ty_rename rename_context)\n    (I_Ty_rename_WF_Type_ext _ _ _ Gty _ WF_Type _ Ty_trans N_Wrap _ _ Free_Vars\n    Ty_rename exists_Free_Vars Ty_trans_trans_subst plus rename_context Ty_rename_eq_Ty_trans\n    FV_subst_tot Free_Vars_id Ty_rename_subtype)\n    (GJ_Ty_rename_WF_Type _ _ Gty _ _ TLookup WF_Type GJ_WF_Type plus Ty_rename _ rename_context \n      TLookup_rename_context GJ_Ty_rename_invert)\n    (FJ_Ty_rename_WF_Type_H1 _ _ _ _ _ N_Wrap cFJ_N _ WF_Type _ _ _ _ _ _ CT wf_class_ext\n      wf_object_ext cFJ_WF_Type Ty_rename TE_rename rename_context (fun _ _ => refl_equal _)\n      (GJ_Ty_rename_WF_object _ _ _ _ Ty_rename rename_context))\n    (FJ_Ty_rename_WF_Type_H2 _ _ _ _ _ N_Wrap cFJ_N _ Empty subtype WF_Type _ fields _ _ Update\n      _ _ _ CT wf_class_ext wf_object_ext cFJ_WF_Type E_WF Free_Vars\n      ce_build_cte Meth_build_context Meth_WF_Ext L_WF_Ext L_build_context override\n      WF_CT cld_typs' L_WF_bound Ty_rename TE_rename rename_context (fun _ _ => refl_equal _))\n    (I_Ty_rename_WF_Type _ _ _ _ _ _ _ _ _ _ WF_Type wf_int_ext N_Wrap I_N_Wrap\n      IT I_WF_Type_Wrap Free_Vars Ty_rename TE_rename (@fst _ _) rename_context \n      I_Ty_rename_invert _ _ _ _ WF_IT Int_WF_bound).\n  \n  Fixpoint subtype_context_shuffle delta S T (sub_S_T : subtype delta S T) {struct sub_S_T} :=\n    match sub_S_T in subtype delta S T return \n      (subtype_context_shuffle_P _ _ _ _ TLookup subtype app_context delta S T sub_S_T) with\n      | cFJ_sub gamma S' T' sub_S_T' => FJ_subtype_context_shuffle _ _ _ _ _ _ _ _ TLookup\n        subtype _ _ _ app_context _ _ _ CT build_te cFJ_sub subtype_context_shuffle\n        _ _ _ sub_S_T'\n      | GJ_sub gamma S' T' sub_S_T' => GJ_subtype_context_shuffle _ _ Gty _ _ _ \n        TLookup subtype GJ_sub app_context TLookup_app TLookup_dec\n        TLookup_unique TLookup_app' TLookup_app'' _ _ _ sub_S_T'\n      | I_subtype_Wrap _ _ _ sub_S_T' => I_subtype_context_shuffle _ _ _ _ _ _ _ _ _\n        TLookup subtype N_Wrap I_N_Wrap _ implements cFJ_N app_context _ _ _ CT\n        isub_build_te I_subtype_Wrap _ _ _ sub_S_T'\n    end.\n    \n  Definition WF_context_shuffle := WF_Type_rect' \n    (WF_context_shuffle_P _ _ _ _ TLookup WF_Type app_context)\n    (Generic.WF_context_shuffle_Q _ _ _ _ TLookup app_context _ wf_class_ext)\n    (WF_context_shuffle_P1 _ _ _ _ TLookup WF_Type app_context)\n    (WF_context_shuffle_Q'' _ _ _ _ _ TLookup wf_int_ext app_context)    \n    (WF_context_shuffle_ext_H1 _ _ _ N_Wrap _ TLookup subtype Ty_trans WF_Type \n      app_context _ _ subtype_context_shuffle)\n    (WF_context_shuffle_ext_H2 _ _ _ _ TLookup WF_Type app_context)\n    (WF_context_shuffle_ext_H3 _ _ _ _ TLookup WF_Type app_context)\n    (I_WF_context_shuffle_ext _ _ N _ TLookup WF_Type subtype Ty_trans N_Wrap\n      _ _ app_context subtype_context_shuffle)\n    (GJ_WF_context_shuffle _ _ Gty _ _ TLookup WF_Type GJ_WF_Type app_context\n      TLookup_app TLookup_dec TLookup_app' TLookup_app'')\n    (FJ_WF_context_shuffle_H1 _ _ _ _ _ _ _ _ TLookup WF_Type _ _ _ app_context _\n      _ _ CT wf_class_ext wf_object_ext cFJ_WF_Type \n      (GJ_WF_context_shuffle_obj_ext _ _ app_context _))\n    (FJ_WF_context_shuffle_H2 _ _ _ _ _ _ _ _ TLookup WF_Type _ _ _ app_context _ _ _ CT\n      wf_class_ext wf_object_ext cFJ_WF_Type)\n    (I_WF_context_shuffle _ _ _ _ _ _ _ _ _ _ TLookup WF_Type wf_int_ext\n      N_Wrap I_N_Wrap app_context IT I_WF_Type_Wrap).\n      \n  Lemma rename_X_inject : forall X Y n, plus X n = plus Y n -> X = Y.\n    clear; intros; omega.\n  Qed.\n    \n  Lemma Ty_Wrap_discriminate' : forall ty ty',Generic_Interface.FJ_Ty_Wrap _ Ty ty_ext N N_Wrap\n    cFJ_N ty <> I_Ty_Wrap ty'.\n    unfold FJ_Ty_Wrap; unfold not; intros; discriminate.\n  Qed.\n\n  Lemma Ty_Wrap_discriminate'' : forall (ty : GTy _) (ty' : I_Ty _ ty_ext), Gty ty <> I_Ty_Wrap ty'.\n    unfold not; intros; discriminate.\n  Qed.\n\n  Definition Ty_rename_FJ_Ty_Wrap_eq ty :=\n    match ty return (Generic.Ty_rename_FJ_Ty_Wrap_eq_P _ Ty _ _ N N_Wrap cFJ_N Ty_rename\n      TE_rename ty) with\n      | N_Wrap (cFJ_N (ty_def te c)) => FJ_Ty_rename_FJ_Ty_Wrap_eq _ _ _ _ _ N_Wrap _ FJ_Ty_Wrap_inject \n        Ty_rename TE_rename FJ_Ty_rename_invert te c\n      | Gty (TyVar X) => GJ_Ty_rename_FJ_Ty_Wrap_eq _ _ _ Gty _ _ N_Wrap _ Ty_Wrap_discriminate \n        plus Ty_rename TE_rename GJ_Ty_rename_invert X \n      | N_Wrap (I_N_Wrap (ity_def te i)) => I_Ty_rename_FJ_Ty_Wrap_eq _ _ _ _ _ _ N_Wrap I_N_Wrap cFJ_N\n        _ _ I_Ty_rename_invert Ty_Wrap_discriminate' te i\n    end.\n\n  Definition Ty_rename_GJ_Ty_Wrap_eq ty :=\n    match ty return (Ty_rename_GJ_Ty_Wrap_eq_P _ _ Gty Ty_rename ty) with\n      | N_Wrap (cFJ_N (ty_def te c)) => FJ_Ty_rename_GJ_Ty_Wrap_eq _ _ _ Gty _ _ N_Wrap _ \n        Ty_Wrap_discriminate Ty_rename TE_rename FJ_Ty_rename_invert te c\n      | Gty (TyVar X) => GJ_Ty_rename_GJ_Ty_Wrap_eq _ _ Gty plus Ty_rename \n        GJ_Ty_rename_invert X \n      | N_Wrap (I_N_Wrap (ity_def te i)) => I_Ty_rename_GJ_Ty_Wrap_eq _ _ _ _ _ Gty \n        N_Wrap I_N_Wrap _ _ I_Ty_rename_invert Ty_Wrap_discriminate'' te i\n    end.\n\n  Definition Ty_rename_I_Ty_Wrap_eq ty :=\n    match ty return (Ty_rename_I_Ty_Wrap_eq_P _ _ _ _ _ N_Wrap I_N_Wrap Ty_rename ty) with\n      | N_Wrap (cFJ_N ty') => FJ_Ty_rename_I_Ty_Wrap_eq _ _ _ _ _ N\n        N_Wrap I_N_Wrap cFJ_N Ty_rename TE_rename FJ_Ty_rename_invert Ty_Wrap_discriminate' ty'\n      | Gty ty' => GJ_Ty_rename_I_Ty_Wrap_eq _ _ _ _ _ Gty _ _ _ plus \n        Ty_Wrap_discriminate'' GJ_Ty_rename_invert ty'\n      | N_Wrap (I_N_Wrap (ity_def te i)) => I_Ty_rename_I_Ty_Wrap_eq _ _ _ _ _ _\n        I_N_Wrap _ _ I_Ty_rename_invert te i\n    end.\n\n  Definition Ty_rename_inject := ty_rect\n    (Ty_rename_inject_P _ _ Ty_rename)\n    (Ty_rename_inject_Q _ _ TE_rename)\n    (GJ_Ty_rename_inject _ _ Gty GJ_Ty_Wrap_inject plus Ty_rename rename_X_inject (fun _ _ => refl_equal _)\n      Ty_rename_GJ_Ty_Wrap_eq)\n    (FJ_Ty_rename_inject _ _ _ _ _ _ id Ty_rename TE_rename FJ_Ty_rename_invert Ty_rename_FJ_Ty_Wrap_eq)\n    (I_Ty_rename_inject _ _ _ _ _ N_Wrap I_N_Wrap I_Ty_Wrap_inject _ _ I_Ty_rename_invert Ty_rename_I_Ty_Wrap_eq)\n    (Ty_rename_inject_H3 _ _ _ Ty_rename)\n    (Ty_rename_inject_H4 _ _ _ _ id GTy_ext_Wrap_inject Ty_rename\n      TE_rename (fun _ _ => refl_equal _)).\n  \n  Fixpoint ex_Ty_rename_subtype delta S T (sub_S_T : subtype delta S T) :=\n    match sub_S_T in subtype delta S T return\n      (ex_Ty_rename_subtype_P_r _ _ _ subtype Ty_rename rename_context delta S T sub_S_T) with\n      | cFJ_sub gamma S' T' sub_S_T' => FJ_ex_Ty_rename_subtype_P_r _ _ _ _ _ N_Wrap cFJ_N\n        _ Empty subtype WF_Type _ fields _ _ Update _ FJ_Ty_Wrap_inject _ _ CT build_te\n        cFJ_sub wf_class_ext wf_object_ext E_WF _ _ _ _ _ \n        override FJ_WF_Type_Wrap_invert WF_CT Ty_rename TE_rename rename_context\n        FJ_Ty_rename_invert Ty_rename_FJ_Ty_Wrap_eq\n        (fun gamma ce c te te' te''  n ce' (bld : L_build_context ce gamma) (E_WF_Ext : L_WF_Ext gamma ce c) => \n          GJ_TE_rename_build_te _ _ Gty _ _ N_Wrap _ Empty subtype Ty_trans WF_Type\n          TUpdate _ _ Free_Vars exists_Free_Vars wf_free_vars _ L_build_context'_Empty_1\n          Ty_trans_trans_subst plus Ty_rename Ty_rename_eq_Ty_trans FV_subst_tot\n        gamma ce c te te' te''  n ce' bld (match E_WF_Ext with | conj H3 _ => H3 end))\n        (GJ_TE_rename_build_obj_te _ _ _ _ Ty_trans _ _ Ty_rename)\n        ex_Ty_rename_subtype gamma S' T' sub_S_T'\n      | GJ_sub gamma S' T' sub_S_T' => GJ_ex_Ty_rename_subtype_P_r \n        _ _ Gty _ _ _ TLookup subtype GJ_sub plus Ty_rename NTy_rename\n        Ty_rename_eq_NTy_rename rename_context TLookup_rename_context' gamma S' T' sub_S_T'\n      | I_subtype_Wrap _ _ _ sub_S_T' => I_ex_Ty_rename_subtype _ _ _ _ _ _ _ _ _ N\n        _ WF_Type subtype wf_int_ext N_Wrap I_N_Wrap _ _ _ cFJ_N Empty Update\n        _ _ _ CT isub_build_te I_subtype_Wrap IT I_Ty_Wrap_inject fields E_WF _ _ \n        L_build_context _ _ _ _ WF_CT I_WF_Type_invert L_WF_GI_L_WF_Ext'' rename_context\n        I_Ty_rename_invert Ty_rename_FJ_Ty_Wrap_eq \n        (fun gamma ce c te te' te'' n int (bld : L_build_context ce gamma) (E_WF_Ext : L_WF_Ext gamma ce c)=>\n          I_TE_rename_build_te _ _ _ _ Gty _ _ _ Ty_trans N_Wrap TUpdate Empty\n          _ _ Free_Vars Ty_rename _ L_build_context' exists_Free_Vars wf_free_vars\n          L_build_context'_Empty_1 Ty_trans_trans_subst plus Ty_rename_eq_Ty_trans\n          FV_subst_tot gamma ce int c te te'' te' n bld \n          (match E_WF_Ext with | conj H3 _ => H3 end)) _ _ _ sub_S_T'\n    end.\n  \n  Fixpoint Ty_rename_subtype' delta S T (sub_S_T : subtype delta S T) :=\n    match sub_S_T in subtype delta S T return \n      (Ty_rename_subtype_P' _ _ _ subtype Ty_rename rename_context delta S T sub_S_T) with\n      | cFJ_sub gamma S' T' sub_S_T' => FJ_Ty_rename_subtype' _ _ _ _ _ N_Wrap cFJ_N _ \n        Empty subtype WF_Type _ fields _ _ Update _ FJ_Ty_Wrap_inject _ _ CT build_te cFJ_sub\n        wf_class_ext wf_object_ext E_WF _ _ _ _ _ override\n        FJ_WF_Type_Wrap_invert WF_CT Ty_rename TE_rename rename_context \n        Ty_rename_FJ_Ty_Wrap_eq Ty_rename_inject \n        (fun gamma ce c te te' te''  n ce' (bld : L_build_context ce gamma) (E_WF_Ext : L_WF_Ext gamma ce c) =>\n          GJ_TE_rename_build_te' _ _ Gty nat _ _ _ Empty subtype\n          Ty_trans WF_Type TUpdate _ _ Free_Vars exists_Free_Vars\n          wf_free_vars L_build_context' L_build_context'_Empty_1 Ty_trans_trans_subst plus Ty_rename \n          Ty_rename_eq_Ty_trans FV_subst_tot Ty_rename_inject \n          gamma ce c te te' te''  n ce' bld (match E_WF_Ext with | conj H3 _ => H3 end))\n        (GJ_TE_rename_build_obj_te' _ _ _ _ Ty_trans _ _ Ty_rename)\n        ex_Ty_rename_subtype\n        Ty_rename_subtype' _ _ _ sub_S_T'\n      | GJ_sub gamma S' T' sub_S_T' => GJ_Ty_rename_subtype' _ _ Gty _ _ _ TLookup\n        subtype GJ_sub GJ_Ty_Wrap_inject plus Ty_rename NTy_rename Ty_rename_eq_NTy_rename\n        rename_X_inject rename_context TLookup_rename_context' GJ_Ty_rename_invert \n        Ty_rename_GJ_Ty_Wrap_eq Ty_rename_inject _ _ _ sub_S_T'\n      | I_subtype_Wrap _ _ _ sub_S_T' => I_Ty_rename_subtype' _ _ _ _ _ _ _ _ _ _ \n        _ WF_Type subtype wf_int_ext N_Wrap I_N_Wrap _ _ _ cFJ_N _ Update _ _ _ CT\n        isub_build_te I_subtype_Wrap IT I_Ty_Wrap_inject fields E_WF _ _\n        _ _ _ _ _ WF_CT I_WF_Type_invert L_WF_GI_L_WF_Ext'' _ I_Ty_rename_invert\n        Ty_rename_I_Ty_Wrap_eq Ty_rename_FJ_Ty_Wrap_eq\n        (fun gamma ce c te te' te'' n int (bld : L_build_context ce gamma) (E_WF_Ext : L_WF_Ext gamma ce c)=>\n          I_TE_rename_build_te _ _ _ _ Gty _ _ _ Ty_trans N_Wrap TUpdate Empty\n          _ _ Free_Vars Ty_rename _ L_build_context' exists_Free_Vars wf_free_vars\n          L_build_context'_Empty_1 Ty_trans_trans_subst plus Ty_rename_eq_Ty_trans\n          FV_subst_tot gamma ce int c te te'' te' n bld \n          (match E_WF_Ext with | conj H3 _ => H3 end))\n        (fun gamma ce c te te' te'' n int (bld : L_build_context ce gamma) (E_WF_Ext : L_WF_Ext gamma ce c)=>\n          I_TE_rename_build_te' _ _ _ _ Gty _ _ _ Ty_trans N_Wrap TUpdate Empty\n          _ _ Free_Vars Ty_rename _ L_build_context' exists_Free_Vars wf_free_vars\n          L_build_context'_Empty_1 Ty_trans_trans_subst plus Ty_rename_eq_Ty_trans\n          FV_subst_tot Ty_rename_inject gamma ce int c te te'' te' n bld \n          (match E_WF_Ext with | conj H3 _ => H3 end)) _ _ _ sub_S_T'\n    end.\n  \n  Definition Ty_rename_WF_Type' := WF_Type_rect' \n    (Ty_rename_WF_Type'_P _ _ _ WF_Type Ty_rename rename_context)\n    (Ty_rename_WF_Type'_Q _ _ _ _ N_Wrap _ _ wf_class_ext Free_Vars cld_typs'\n      TE_rename rename_context)\n    (Ty_rename_WF_Type'_P1 _ _ _ WF_Type Ty_rename rename_context)\n    (Ty_rename_WF_Type'_Q'' _ _ _ _ _ _ wf_int_ext N_Wrap Free_Vars TE_rename\n      (@fst _ _) rename_context)\n    (Ty_rename_WF_Type_ext'_H1 _ _ Gty _ N_Wrap _ subtype Ty_trans WF_Type\n      _ _ Free_Vars exists_Free_Vars Ty_trans_trans_subst plus Ty_rename\n      rename_context Ty_rename_eq_Ty_trans FV_subst_tot Ty_rename_subtype'\n      Free_Vars_id)\n    (Ty_rename_WF_Type_ext'_H2 _ _ _ WF_Type Ty_rename rename_context)\n    (Ty_rename_WF_Type_ext'_H3 _ _ _ WF_Type Ty_rename rename_context)\n    (I_Ty_rename_WF_Type_ext' _ _ _ Gty _ _ _ _ N_Wrap _ _ _ _ exists_Free_Vars\n      Ty_trans_trans_subst _ _ Ty_rename_eq_Ty_trans FV_subst_tot Free_Vars_id Ty_rename_subtype')\n    (GJ_Ty_rename_WF_Type' _ _ Gty _ _ TLookup WF_Type GJ_WF_Type\n      GJ_Ty_Wrap_inject plus Ty_rename NTy_rename rename_X_inject rename_context\n      TLookup_rename_context' GJ_Ty_rename_invert Ty_rename_GJ_Ty_Wrap_eq)\n    (FJ_Ty_rename_WF_Type'_H1 _ _ _ _ _ _ id _ WF_Type _ _ _ _ _ _ CT\n      wf_class_ext wf_object_ext cFJ_WF_Type Ty_rename TE_rename rename_context\n      Ty_rename_FJ_Ty_Wrap_eq \n      (GJ_Ty_rename_WF_object' _ _ _ _ Ty_rename rename_context))\n    (FJ_Ty_rename_WF_Type'_H2 _ _ _ _ _ N_Wrap cFJ_N _ Empty subtype WF_Type _ fields\n      _ _ Update _ _ _ CT wf_class_ext wf_object_ext cFJ_WF_Type E_WF Free_Vars\n      _ _ _ _ _ _ WF_CT cld_typs' L_WF_bound Ty_rename TE_rename rename_context\n      Ty_rename_FJ_Ty_Wrap_eq)\n    (I_Ty_rename_WF_Type' _ _ _ _ _ _ _ _ _ _ WF_Type wf_int_ext N_Wrap I_N_Wrap\n      IT I_WF_Type_Wrap _ I_Ty_Wrap_inject _ _ (@fst _ _) _ I_Ty_rename_invert _ _ _ _ WF_IT\n      Int_WF_bound Ty_rename_I_Ty_Wrap_eq).\n    \n  Variable (Finite_Context : forall gamma : Context, exists n,\n    forall X ty ty' Ys, TLookup gamma X ty -> Free_Vars (Ty_rename ty' n) Ys -> ~ In X Ys).\n\n  Definition Type_Subst_Sub_2_5_P' := Generic.Type_Subst_Sub_2_5_P' _ _ N N_Wrap _ Empty subtype Ty_trans\n    WF_Type TUpdate app_context subst_context.\n\n  Fixpoint Type_Subst_Sub_2_5' delta S T (sub_S_T : subtype delta S T) : \n    Type_Subst_Sub_2_5_P' delta S T sub_S_T :=\n    match sub_S_T in (subtype delta S T) return (Type_Subst_Sub_2_5_P' delta S T sub_S_T) with\n      | cFJ_sub delta S' T' sub_S_T' => \n        FJ_Type_Subst_Sub_2_5' _ _ _ _ N N_Wrap\n        _ _ Empty subtype Ty_trans\n        WF_Type _ fields _ _ TUpdate app_context Update _ FJ_Ty_Wrap_inject _ _ CT\n        build_te cFJ_sub wf_class_ext wf_object_ext E_WF Free_Vars TE_trans FJ_Ty_trans_invert\n        exists_Free_Vars N_trans subst_context\n        ce_build_cte Meth_build_context Meth_WF_Ext L_WF_Ext L_build_context override\n        FJ_WF_Type_Wrap_invert WF_CT (@Generic.GJ_Type_Subst_Sub_2_5_TE _ _ _ N_Wrap\n          _ Empty subtype Ty_trans WF_Type TUpdate _ _ Free_Vars exists_Free_Vars\n          N_trans wf_free_vars map_Ty_trans' _ L_build_context'_Empty_1 \n          _) (@GJ_Type_Subst_Sub_2_5_TE' _ _ _ _ _ subtype Ty_trans _ _ _ _ _ _ _)\n        Ty_trans_eq_NTy_trans Type_Subst_Sub_2_5' delta S' T' sub_S_T'\n      | GJ_sub delta S' T' sub_S_T' => GJ_Type_Subst_Sub_2_5' _ eq_nat_dec _ Gty _ _ _ Empty TLookup subtype\n        GJ_sub Ty_trans WF_Type GJ_WF_Type TUpdate app_context Free_Vars\n        GJ_Free_Vars' GJ_Ty_trans_invert TLookup_TUpdate_eq TLookup_TUpdate_neq' wf_free_vars subst_context \n        TLookup_unique Ty_rename subst_context_Empty app_context_Empty Finite_Context\n        delta S' T' sub_S_T'\n      | I_subtype_Wrap delta S' T' sub_S_T' => I_Type_Subst_Sub_2_5' _ _ _ _ _ _ _ _ _ N _\n        WF_Type subtype Ty_trans wf_int_ext N_Wrap I_N_Wrap TUpdate cld_ext ce_build_cte\n        implements cFJ_N Empty Update _ _ _ _ CT _ I_subtype_Wrap IT _ I_Ty_trans_invert\n        I_Ty_Wrap_inject FJ_Ty_trans_invert _ _ _ _ _ override _ _ _ \n        (@Generic_Interface.GJ_Type_Subst_Sub_2_5_TE _ _ _ _ WF_Type \n          subtype Ty_trans N_Wrap TUpdate Empty _ _ Free_Vars N_trans _ \n          _ exists_Free_Vars map_Ty_trans' wf_free_vars L_build_context'_Empty_1 _)\n        L_WF_GI_L_WF_Ext' I_WF_Type_invert L_WF_GI_L_WF_Ext Ty_trans_eq_NTy_trans _ _ _ sub_S_T'\n    end.\n\n  Definition Free_Vars_Ty_Rename := ty_rect\n    (Generic.Free_Vars_Ty_Rename_P _ _ Free_Vars plus Ty_rename)\n    (Generic.Free_Vars_TE_Rename_P _ _ TE_Free_Vars plus TE_rename)\n    (GJ_Free_Vars_Ty_Rename _ _ Gty Free_Vars GJ_Free_Vars_invert\n      GJ_Ty_Wrap_inject plus Ty_rename GJ_Ty_rename_invert)\n    (FJ_Free_Vars_Ty_Rename _ _ _ _ _ N_Wrap cFJ_N FJ_Ty_Wrap_inject Free_Vars TE_Free_Vars FJ_Free_Vars_invert _\n    Ty_rename TE_rename FJ_Ty_rename_invert)\n    (I_Free_Vars_Ty_Rename _ _ _ _ N N_Wrap I_N_Wrap _ _ I_Free_Vars_invert I_Ty_Wrap_inject _ _ plus \n      I_Ty_rename_invert)\n    (Free_Vars_Ty_Rename_H3 _ _ _ _ _ _)\n    (Free_Vars_Ty_Rename_H4 _ _ _ _ Free_Vars TE_Free_Vars id\n      (fun _ _ => id) plus Ty_rename TE_rename (fun _ _ => refl_equal _)).\n\n  Definition Type_Subst_WF_2_6' := Generic.Type_Subst_WF_2_6' _ eq_nat_dec _ Gty _ _ _ Empty\n    TLookup subtype Ty_trans WF_Type TUpdate app_context Weakening_2_1_2 Free_Vars GJ_Free_Vars' \n    exists_Free_Vars N_trans wf_free_vars subst_context TLookup_update_eq\n    TLookup_update_neq TLookup_update_neq' Ty_trans_eq_NTy_trans Ty_trans_trans_subst\n    plus Ty_rename NTy_rename Ty_rename_eq_NTy_rename rename_context TLookup_rename_context'\n    GJ_Ty_rename_invert Ty_rename_eq_Ty_trans FV_subst_tot Ty_rename_subtype\n    subst_context_Empty app_context_Empty Finite_Context Ty_rename_WF_Type\n    Ty_rename_WF_Type' WF_context_shuffle Free_Vars_Ty_Rename Type_Subst_WF_2_6.\n\n  Variable (CT_eq : forall c ce c' d fds k' mds,\n           CT c = Some (cFJ.cld nat nat nat nat ty_ext Ty E md_ext cld_ext ce c' d fds k' mds) ->\n           c = c').\n\n  Lemma L_build_context'_Empty_2 : forall (ce : _) (gamma : Context)\n    (XNs : Generic.TyP_List _ _) (S T : Ty),\n    L_build_context' ce gamma ->\n    subtype (Generic.update_Tlist _ _ Context TUpdate gamma XNs) S T ->\n    subtype (Generic.update_Tlist _ _ Context TUpdate Empty XNs) S T.\n    intros; inversion H; subst.\n    assumption.\n  Qed.\n\n  Definition WF_cld_ext_Lem := Generic.WF_cld_ext_Lem _ _ _ _ N N_Wrap cFJ_N _ Empty subtype\n    WF_Type _ fields _ _ Update _ _ _ CT wf_class_ext E_WF Free_Vars ce_build_cte\n    Meth_build_context Meth_WF_Ext L_WF_Ext L_build_context override\n    WF_CT cld_typs' L_WF_bound _ \n    (fun gamma ce te wf_e te'' c c1 gamma' gamma'' gamma''' ce' te' c1_WF c_WF =>\n      GJ_WF_cld_ext_Lem' _ eq_nat_dec _ Gty nat _ N_Wrap _ Empty TLookup subtype\n      Ty_trans WF_Type TUpdate app_context _ _ Weakening_2_1_2 Free_Vars\n      GJ_Free_Vars' exists_Free_Vars N_trans wf_free_vars subst_context map_Ty_trans'\n      _ L_build_context'_Empty_1 L_build_context'_Empty_2 TLookup_update_eq\n      TLookup_update_neq TLookup_update_neq' Ty_trans_eq_NTy_trans Ty_trans_trans_subst\n      plus Ty_rename NTy_rename Ty_rename_eq_NTy_rename rename_context TLookup_rename_context'\n      GJ_Ty_rename_invert Ty_rename_eq_Ty_trans FV_subst_tot Ty_rename_subtype\n      subst_context_Empty app_context_Empty Finite_Context Ty_rename_WF_Type Ty_rename_WF_Type'\n      Type_Subst_Sub_2_5' WF_context_shuffle Free_Vars_Ty_Rename Type_Subst_WF_2_6 \n      (fun (ice : I_cld_ext) te te' te'' => FJ_mtype_build_te (snd ice) te te' te'')\n      gamma ce te wf_e te'' c c1 gamma' gamma'' gamma''' ce' te' \n      (match c1_WF with | conj H3 _ => H3 end) (match c_WF with | conj H3 _ => H3 end)).\n\n  Definition WF_Type_par_Lem' delta ty (WF_ty : WF_Type delta ty) :\n    WF_Type_par_Lem_P' delta ty WF_ty := \n    match WF_ty in (WF_Type delta ty) return WF_Type_par_Lem_P' delta ty WF_ty with \n      | cFJ_WF_Type gamma ty WF_base => \n        FJ_WF_Type_par_Lem' _ _ _ _ _ _ _\n        _ _ _ CT Context wf_class_ext wf_object_ext WF_Type cFJ_WF_Type\n        mtype_build_te L_build_context cFJ_inject\n        WF_cld_ext_Lem\n        gamma ty WF_base\n      | GJ_WF_Type gamma ty WF_ty => GJ_WF_Type_par_Lem' _ _ _ _ _ _ N_Wrap _\n        _ _ _ GJ_WF_Type _ _ _ _  Ty_Wrap_discriminate _ _ CT wf_class_ext L_build_context\n        _ _ _ WF_ty\n      | I_WF_Type_Wrap _ _ WF_ty => I_WF_Type_par_Lem' _ _ _ _ _ _ _ _ _ _ WF_Type\n        wf_int_ext N_Wrap I_N_Wrap _ cFJ_N _ _ _ CT IT I_WF_Type_Wrap _ _ Ty_Wrap_discriminate'\n        mtype_build_te _ _ WF_ty\n    end.     \n    \n  Lemma WF_fields_map_id''' : forall (gamma : Context) (ty ty' ty'' : Ty),\n    WF_fields_map gamma ty ty' -> WF_fields_map gamma ty ty'' -> ty' = ty''.\n    intros; inversion H; inversion H0; inversion H1; inversion H5; subst;\n      try discriminate.\n    injection H15; intros; subst; rewrite (TLookup_id _ _ _ _ H13 H9); \n      reflexivity.\n    injection H13; intros; subst; reflexivity.\n  Qed.\n\n  Lemma N_Bound'_invert : forall (delta : Context) (n : N) (ty : Ty),\n    Bound delta (N_Wrap n) ty -> Generic.N_Bound Ty N  N_Wrap Context delta (N_Wrap n) ty.\n    intros; inversion H; inversion H0; subst; assumption.\n  Qed.\n\n  Lemma fields_build_te_id'' : forall ce te te' te'' te''',\n    build_te ce te te' te'' -> fields_build_te ce te te' te''' -> te'' = te'''.\n    intros; inversion H; inversion H0; inversion H7; subst.\n    injection H11; injection H10; injection H9; intros; subst.\n    destruct te'0; destruct te'1; reflexivity.\n  Qed.\n\n  Lemma FJ_N_Ty_Wrap_inject : forall n n', cFJ_N n = cFJ_N n' -> n = n'.\n    intros; injection H; auto.\n  Qed.\n\n  Lemma fields_build_te_id' : forall (gamma : Context) (ty : cFJ.FJ_Ty nat ty_ext),\n    Bound gamma (Generic.FJ_Ty_Wrap Ty ty_ext nat N N_Wrap cFJ_N ty)\n    (Generic.FJ_Ty_Wrap Ty ty_ext nat N N_Wrap cFJ_N ty).\n    intros; constructor 2; unfold Generic.FJ_Ty_Wrap; unfold id; constructor.\n  Qed.\n\n  Lemma GJ_Bound'_invert : forall (delta : Context) (n : GTy _) (ty : N),\n    Bound delta (Gty n) (N_Wrap ty) ->\n    Generic.GJ_Bound _ Ty Gty N Context TLookup delta (Gty n) ty.\n    intros; inversion H; subst; try assumption; inversion H0.\n  Qed.\n\n  Lemma GJ_Bound_ty : forall (delta : Context) (ty : GTy _) (ty' : Ty),\n    Bound delta (Gty ty) ty' -> exists n : N, ty' = N_Wrap n.\n    intros; inversion H; subst; try (inversion H0; fail);\n      exists ty'0; reflexivity.\n  Qed.\n\n  Lemma GJ_Bound'_invert' : forall (delta : Context) (Y : GTy _) (ty : Ty),\n    Bound delta (Gty Y) ty -> exists n, ty = N_Wrap n /\\ \n      Generic.GJ_Bound nat _ Gty N _ TLookup delta (Gty Y) n.\n    intros; inversion H; inversion H0; subst; exists ty'; split; auto.\n  Qed.\n\n  Definition Bound_id gamma ty ty' (Bnd : Bound gamma ty ty') :=\n    match Bnd in (Bound gamma ty ty') return (forall ty'', Bound gamma ty ty'' -> ty' = ty'') with\n      | GJ_Bound _ _ _ Bnd' => GJ_Bound_id _ _ Gty _ _ _ TLookup Bound\n        GJ_Ty_Wrap_inject TLookup_unique GJ_Bound'_invert GJ_Bound'_invert' _ _ _ Bnd'\n      | N_Bound _ _ _ Bnd' => N_Bound_id _ _ _ _ Bound N_Bound'_invert _ _ _ Bnd'\n    end.\n\n  Definition Bound_id' ty :=\n    match ty return Bound'_id_P _ _ Bound ty with \n      | N_Wrap (cFJ_N ty') => FJ_Bound'_id _ _ _ _ _ _ _ Bound N_Wrap_inject N_Bound'_invert ty'\n      | N_Wrap (I_N_Wrap ty) => Generic_Interface.Bound_id' _ _ _ _ _ N_Wrap I_N_Wrap Bound\n        N_Bound'_invert ty\n      | Gty ty' => GJ_Bound'_id _ _ Gty _ _ _ TLookup Bound GJ_Ty_Wrap_inject TLookup_id\n        GJ_Bound'_invert' ty'\n    end.\n    \n  Lemma N_Bound'_invert' : forall (delta : Context) (n : N) (ty : Ty),\n    Bound delta (N_Wrap n) ty ->\n    Generic_Interface.N_Bound Ty N Context N_Wrap delta (N_Wrap n) ty.\n    intros; inversion H; inversion H0; subst.\n    unfold FJ_Ty_Wrap; unfold id; constructor.\n  Qed.\n\n  Lemma FJ_Fields_Ity_False : forall gamma ity fds,  \n    ~ fields gamma (Generic_Interface.I_Ty_Wrap nat Ty (GTy_ext Ty) N N_Wrap I_N_Wrap ity) fds.\n    unfold not; intros.\n    inversion H; subst.\n    eapply (FJ_Fields_Ity_False _ _ _ _ _ _ _ _ N_Wrap I_N_Wrap \n            _ cFJ_N _ _ _ CT fields Ty_Wrap_discriminate' fields_build_te \n            fields_build_tys); eauto.\n  Qed.\n\n  Definition bld_te_eq_fields_build_te := Generic.bld_te_eq_fields_build_te nat Ty N Ty_trans _ _\n    (fun ce : I_cld_ext => cFJ.FJ_bld_te_eq_fields_build_te (snd ce)).\n\n  Definition WF_mtype_ty_0_map_refl := Generic.GJ_WF_mtype_ty_0_map_refl _ _ _ _ N_Wrap cFJ_N _ \n    Bound N_Bound.\n\n  Definition fields_build_tys_tot := GJ_fields_build_tys_tot nat Ty N Ty_trans \n    (fun (ice : I_cld_ext) te te' te''=> FJ_build_te (snd ice) te te' te'')\n    (fun te ice tys tys' => FJ_fields_build_tys Ty te (snd ice) tys tys')\n    (fun te ce => cFJ.FJ_fields_build_tys_tot Ty te (snd ce)).\n\n  Fixpoint Lem_2_8' delta S T sub_S_T : \n    cFJ.Lem_2_8_P nat Ty Context subtype fields Bound Empty delta S T sub_S_T :=\n    match sub_S_T in (subtype delta S T) return \n      (cFJ.Lem_2_8_P nat Ty Context subtype fields Bound Empty delta S T sub_S_T) with\n      | cFJ_sub gamma' S' T' sub_S_T' =>\n        FJ_Lem_2_8 nat nat nat nat ty_ext Ty _ E _ _\n        CT Context subtype build_te cFJ_sub fields fields_build_te\n        fields_build_tys FJ_fields Bound Empty \n        (Bound_tot _ _ _ _ _ _ _ Bound N_Bound) fields_build_tys_tot Bound_id'\n        (fun gamma ty => N_Bound _ _ _ (N_bound _ _ N_Wrap _ gamma (cFJ_N ty)))\n        bld_te_eq_fields_build_te gamma' S' T' sub_S_T' Lem_2_8'\n      | GJ_sub gamma' S' T' sub_S_T' => \n        GJ_Lem_2_8 _ _ Gty N N_Wrap _ Empty TLookup \n        subtype GJ_sub _ fields Bound GJ_Bound N_Wrap_inject N_Bound'_invert'\n        gamma' S' T' sub_S_T'\n      | I_subtype_Wrap _ _ _ sub_S_T' => I_Lem_2_8 _ _ _ I_Ty_Wrap _ _ _ _ _ _ _ _\n        CT isub_build_te _ FJ_Ty_Wrap subtype I_subtype_Wrap _ fields Bound\n        (FJ_Map_Fields_Ity_False _ _ _ _ _ N_Wrap I_N_Wrap Bound _ fields\n        N_Bound'_invert FJ_Fields_Ity_False) _ _ _ sub_S_T'\n    end.\n      \n  Variable build_fresh_id : forall tys ty tys' Xs Ys Xs' Xs'', build_fresh tys ty tys' Xs Ys Xs' -> \n    build_fresh tys ty tys' Xs Ys Xs'' -> Xs' = Xs''.\n\n  Definition build_V' gamma1 m ty mde' Ws W (H : override gamma1 m ty mde' Ws W) := H.\n\n  Definition WF_Bound_id delta S T T' (Bound_S : Bound delta S T) :=\n    match Bound_S in Bound delta S T return Bound delta S T' -> T = T' with\n      | GJ_Bound delta' S' T'' Bound_S' => GJ_Bound_id _ _ Gty _ N_Wrap _ \n        TLookup Bound GJ_Ty_Wrap_inject TLookup_unique GJ_Bound'_invert\n        GJ_Bound'_invert' _ _ _ Bound_S' T'\n      | N_Bound delta' S' T'' Bound_S' => N_Bound_id _ _ N_Wrap _ Bound\n        N_Bound'_invert _ _ _ Bound_S' T'\n    end.\n      \n  Definition In_m_mds_dec := cFJ.In_m_mds_dec _ nat Ty E md_ext eq_nat_dec.\n   \n  Definition WF_mtype_ty_0_map_TLookup := GJ_WF_mtype_ty_0_map_TLookup _ _ Gty _ \n    N_Wrap _ TLookup Bound GJ_Bound.\n\n  Variable build_fresh_len : forall tys ty vds Xs Ws Ys, \n    build_fresh tys ty vds Xs Ws Ys -> length Ws = length Ys.\n\n  Variable build_fresh_tot : forall tys ty tys' Xs Ys, exists Xs', build_fresh tys ty tys' Xs Ys Xs'.\n\n  Definition mtype_build_mtye_tot := Generic.mtype_build_mtye_tot _ _ Gty _ Ty_trans _ _ \n    build_fresh N_Trans _ _ _ build_fresh_tot build_fresh_len _ \n    (fun ce te me ty vds (mtye : unit) => True) (fun ce : I_cld_ext => FJ_mtype_build_mtye_tot nat Ty (snd ce)). \n\n  Definition mtype_build_tys_tot := Generic.mtype_build_tys_tot _ _ Gty _ Ty_trans _ build_fresh\n    N_Trans _ _ _ build_fresh_tot build_fresh_len _ \n    (fun (ice : I_cld_ext) te ty vds mce tys tys' => FJ_mtype_build_tys nat _ (snd ice) te ty vds mce tys tys')\n    (fun ce : I_cld_ext => FJ_mtype_build_tys_tot nat Ty (snd ce)).\n\n  Lemma N_Wrap_inject' : forall n n', \n    N_Wrap (cFJ_N n) = N_Wrap (cFJ_N n') -> n = n'.\n    intros; injection H; auto.\n  Qed.\n\n  Definition WF_mtype_ty_0_map_id := Bound_id'.\n\n  Definition build_te_build_mtye_te'' := \n    Generic.GJ_build_te_build_mtye_te'' _ _ N Ty_trans _ _ \n    (fun (ice : I_cld_ext) te te' te'' => FJ_mtype_build_te (snd ice) te te' te'')\n    (fun (ice : I_cld_ext) te te' te''=>  FJ_build_te (snd ice) te te' te'') \n    (fun ce : I_cld_ext => FJ_build_te_build_mtye_te'' (snd ce)).\n\n  Definition build_te_build_ty_0_id := Generic.build_te_build_ty_0_id _ _ _ _ _ _ _\n    FJ_Ty_Wrap_inject _ build_te WF_mtype_ty_0_map mtype_build_te WF_mtype_ty_0_map_id\n    WF_mtype_ty_0_map_refl build_te_build_mtye_te''.\n\n  Definition mtype_build_tys_len' := Generic.mtype_build_tys_len' _ _ _ Gty N Ty_trans _ build_fresh _\n    _ (fun (ice : I_cld_ext) te ty vds mce tys tys' => FJ_mtype_build_tys nat _ (snd ice) te ty vds mce tys tys')\n    mtype_build_tys_len.\n\n  Lemma WF_Type_invert : forall (delta : Context) (S : cFJ.FJ_Ty _ ty_ext), \n    WF_Type delta (N_Wrap (cFJ_N S)) ->\n    cFJ.FJ_WF_Type _ _ _ _ ty_ext Ty (Generic.FJ_Ty_Wrap Ty ty_ext nat N N_Wrap cFJ_N) E md_ext cld_ext CT Context \n    wf_class_ext wf_object_ext delta (N_Wrap (cFJ_N S)).\n    intros; inversion H; subst; auto; inversion H0.\n  Qed.\n\n  Variable I_Lem_2_9 : forall gamma S T sub_S_T, \n    cFJ.Lem_2_9_P _ _ _ _ _ subtype mtype Bound WF_mtype_Us_map WF_mtype_U_map WF_mtype_ext Empty _ _ _ \n    (I_subtype_Wrap gamma S T sub_S_T).\n\n  Fixpoint Lem_2_9 gamma S T (sub_S_T : subtype gamma S T) : \n    cFJ.Lem_2_9_P _ _ _ _ _ subtype mtype Bound WF_mtype_Us_map WF_mtype_U_map WF_mtype_ext Empty _ _ _ sub_S_T :=\n    match sub_S_T return cFJ.Lem_2_9_P _ _ _ _ _ subtype mtype Bound \n      WF_mtype_Us_map WF_mtype_U_map WF_mtype_ext Empty _ _ _ sub_S_T with\n      | cFJ_sub gamma S' T' sub_S_T' => cFJ.FJ_Lem_2_9 _ _ _ _ _ _ FJ_Ty_Wrap\n        _ _ _ _ _ CT _ subtype build_te cFJ_sub wf_class_ext wf_object_ext\n        WF_Type fields mtype mtype_build_te mtype_build_tys\n        mtype_build_mtye FJ_mtype E_WF Bound WF_mtype_Us_map WF_mtype_U_map WF_mtype_ext Empty\n        Update ce_build_cte Meth_build_context Meth_WF_Ext override L_WF_Ext L_build_context\n        WF_CT FJ_Ty_Wrap_inject WF_mtype_ty_0_map_total mtype_build_tys_len' \n        WF_Type_invert (fun g S T T' Bnd => Bound_id g S T Bnd T') eq_nat_dec\n        build_te_build_ty_0_id WF_mtype_ty_0_map_refl mtype_build_tys_tot \n        mtype_build_mtye_tot build_V' gamma S' T' sub_S_T' Lem_2_9\n      | GJ_sub gamma S' T' sub_S_T' => Generic.GJ_Lem_2_9 _ _ _ Gty _ _ N_Wrap\n        _ _ Empty TLookup subtype GJ_sub _ _ _ _ mtype _ _ _ CT build_te \n        cFJ_sub _ Bound WF_mtype_Us_map WF_mtype_U_map WF_mtype_ext \n        WF_mtype_ty_0_map_id (fun gamma ty => N_Bound _ _ _ (N_bound _ _ N_Wrap _ gamma (ty)))\n        WF_mtype_ty_0_map_TLookup gamma S' T' sub_S_T'\n      | I_subtype_Wrap gamma' S' T' sub_S_T' => I_Lem_2_9 gamma' S' T' sub_S_T'\n    end.\n\n  Fixpoint Subtype_Weaken gamma S T (sub_S_T : subtype gamma S T) :=\n    match sub_S_T in (subtype gamma S T) return (Subtype_Weaken_P Ty Context subtype Empty gamma S T sub_S_T) with\n      | cFJ_sub gamma' S' T' sub_S_T' => \n        FJ_Subtype_Weaken _ _ _ _ _ _ _ _ _ _ CT _ subtype build_te\n        cFJ_sub Empty gamma' S' T' sub_S_T' Subtype_Weaken\n      | GJ_sub gamma' S' T' sub_S_T' => \n        GJ_Subtype_Weaken _ _ Gty _ _ _ Empty TLookup _ GJ_sub TLookup_Empty _ _ _ sub_S_T'\n      | I_subtype_Wrap _ _ _ sub_S_T' => I_Subtype_Weaken _ _ _ _ _ _ _ _ subtype N_Wrap I_N_Wrap\n        _ _ cFJ_N _ _ _ _ CT isub_build_te I_subtype_Wrap _ _ _ sub_S_T'\n    end.\n\n  Variable TLookup_TUpdate_neq : forall gamma Y X ty ty', TLookup gamma X ty -> X <> Y -> \n       TLookup (TUpdate gamma Y ty') X ty.\n\n  Fixpoint Weaken_subtype_app_TList delta S T (sub_S_T : subtype delta S T) :=\n    match sub_S_T return (Weaken_subtype_app_TList_P _ _ _ _  Empty subtype TUpdate _ _ _ sub_S_T) with\n      | cFJ_sub delta S' T' sub_S_T' => \n        FJ_Weaken_subtype_app_TList _ _ _ _ _ N_Wrap cFJ_N _ Empty subtype _ _ _ TUpdate\n        _ _ _ CT build_te cFJ_sub Weaken_subtype_app_TList delta S' T' sub_S_T'\n      | GJ_sub delta S' T' sub_S_T' => GJ_Weaken_subtype_app_TList _ eq_nat_dec _ Gty _ _\n        _ Empty TLookup subtype GJ_sub TUpdate TLookup_Empty TLookup_TUpdate_eq TLookup_TUpdate_neq\n        TLookup_TUpdate_neq' TLookup_id delta S' T' sub_S_T'\n      | I_subtype_Wrap delta S' T' sub_S_T' => I_Weaken_subtype_app_TList _ _ _ _ _ _ _ _ _ subtype N_Wrap\n        I_N_Wrap TUpdate _ implements cFJ_N Empty _ _ _ CT isub_build_te I_subtype_Wrap _ _ _ sub_S_T'\n    end.\n\n  Definition Weaken_WF_Type_app_TList :=\n    WF_Type_rect' (Weaken_WF_Type_app_TList_P _ _ _ _ Empty WF_Type TUpdate)\n    (Weaken_WF_Type_app_TList_Q _ _ _ _ _ Empty subtype Ty_trans WF_Type TUpdate _ _)\n    (Weaken_WF_Type_app_TList_P1 _ _ _ _ Empty WF_Type TUpdate)\n    (Weaken_WF_Type_app_TList_Q'' _ _ _ _ _ wf_int_ext TUpdate Empty)\n    (Weaken_WF_Type_app_TList_ext_H1 _ _ _ _ _ Empty subtype Ty_trans WF_Type TUpdate _ _ \n      Weaken_subtype_app_TList)\n    (Weaken_WF_Type_app_TList_ext_H2 _ _ _ _ Empty WF_Type TUpdate)\n    (Weaken_WF_Type_app_TList_ext_H3 _ _ _ _ Empty WF_Type TUpdate)\n    (Weaken_WF_Type_app_TList_int_ext _ _ _ _ WF_Type subtype Ty_trans N_Wrap TUpdate Empty\n      _ _ Weaken_subtype_app_TList)\n    (GJ_Weaken_WF_Type_app_TList _ eq_nat_dec _ Gty _ _ Empty TLookup WF_Type \n      GJ_WF_Type TUpdate TLookup_Empty TLookup_TUpdate_eq TLookup_TUpdate_neq TLookup_TUpdate_neq'\n      TLookup_id)\n    (FJ_Weaken_WF_Type_app_TList_H1 _ _ _ _ _ _ _ _ Empty WF_Type _ _ _ TUpdate _ _ _ CT wf_class_ext\n      wf_object_ext cFJ_WF_Type (Weaken_WF_Type_app_TList_obj_ext _ _ _ _ Empty TUpdate _))\n    (FJ_Weaken_WF_Type_app_TList_H2 _ _ _ _ _ _ _ _ Empty WF_Type _ _ _ TUpdate _ _ _\n      CT wf_class_ext wf_object_ext cFJ_WF_Type)\n    (I_Weaken_WF_Type_app_TList_int _ _ _ _ _ _ _ _ _ _ WF_Type wf_int_ext N_Wrap\n      I_N_Wrap TUpdate Empty IT I_WF_Type_Wrap).\n          \n  Definition FJ_NTy_trans_invert (ty : Generic.Base_Ty ty_ext nat) (txs : list nat) (tys : list Ty) : \n    Ty_trans ((Generic.FJ_Ty_Wrap Ty ty_ext nat N N_Wrap cFJ_N) (id ty)) txs tys =\n    FJ_Ty_Trans _ Ty ty_ext _ N N_Wrap cFJ_N TE_trans ty txs tys :=\n    refl_equal _.\n\n  Definition Bound'_Trans := Generic.Bound'_Trans _ _ _ _ _ Ty_trans Bound N_Bound\n    N_trans Ty_trans_eq_NTy_trans.\n\n  Lemma GJ_WF_Type_invert : forall gamma ty , WF_Type gamma (Gty ty) ->\n    Generic.GJ_WF_Type _ Ty Gty N Context TLookup gamma (Gty ty).\n    intros; inversion H; subst; auto; inversion H0.\n  Qed.\n\n  Fixpoint ex_WF_Bound' (S : Ty) := \n    match S return ex_WF_Bound'_P Ty N N_Wrap Context WF_Type Bound S with\n      | N_Wrap (cFJ_N (ty_def te c)) => FJ_ex_WF_Bound' _ _ _ _ N_Wrap cFJ_N _ WF_Type Bound N_Bound te c\n      | Gty (TyVar X) => GJ_ex_WF_Bound' _ _ Gty _ _ _ TLookup WF_Type Bound GJ_Bound GJ_Ty_Wrap_inject\n        GJ_WF_Type_invert X\n      | N_Wrap (I_N_Wrap i) => I_ex_WF_Bound' _ _ _ _ _ WF_Type N_Wrap I_N_Wrap Bound N_Bound i\n      end.\n\n  Fixpoint sub_Bound delta S T (sub_S_T : subtype delta S T) : \n    (sub_Bound'_P _ _ subtype Bound _ _ _ sub_S_T) :=\n    match sub_S_T return (sub_Bound'_P _ _ subtype Bound  _ _ _ sub_S_T) with\n      | cFJ_sub delta S' T' sub_S_T' => \n        FJ_sub_Bound' _ _ _ _ _ _\n        _ subtype _ _ _ _ Bound _ _ CT build_te cFJ_sub\n        N_Wrap_inject N_Bound'_invert WF_mtype_ty_0_map_total Bound_id'\n        sub_Bound delta S' T' sub_S_T'\n      | GJ_sub delta S' T' sub_S_T' => \n        GJ_sub_Bound' _ _ _ Gty _ _ _ _ _ TLookup subtype GJ_sub _ _ _ _ \n        Bound _ _ CT build_te cFJ_sub GJ_Ty_Wrap_inject TLookup_id\n        N_Wrap_inject N_Bound'_invert' GJ_Bound'_invert' delta S' T' sub_S_T'\n      | I_subtype_Wrap delta S' T' sub_S_T' => I_sub_Bound _ _ _ _ _ _ _ _ subtype N_Wrap I_N_Wrap _\n        implements cFJ_N Bound _ _ _ CT isub_build_te I_subtype_Wrap N_Bound'_invert _ _ _ sub_S_T'\n    end.\n\n  Definition Lem_2_7 (T :Ty) :=\n    match T return Generic.Lem_2_7_P _ _ _ N_Wrap\n      _ Empty subtype Ty_trans WF_Type _ TUpdate Update Bound T with \n      | N_Wrap (cFJ_N (ty_def te c)) => FJ_Lem_2_7 _ _ _ _ _ _ _\n        Context Empty subtype Ty_trans WF_Type _ _ _ TUpdate Update _ Bound\n        N_Bound _ _ CT build_te cFJ_sub TE_trans FJ_Ty_trans_invert\n        N_Wrap_inject N_Bound'_invert FJ_NTy_trans_invert te c\n      | Gty (TyVar X) => GJ_Lem_2_7 _ eq_nat_dec _ Gty _ _\n        _ Empty TLookup subtype Ty_trans WF_Type _ TUpdate Update TLookup_Update\n        TLookup_Empty Bound N_Bound GJ_Ty_Wrap_inject GJ_Ty_trans_invert \n        TLookup_TUpdate_eq TLookup_TUpdate_neq TLookup_TUpdate_neq' TLookup_id \n        _ Ty_trans_eq_NTy_trans GJ_Bound'_invert' sub_Bound ex_WF_Bound' X\n      | N_Wrap (I_N_Wrap i) => I_Lem_2_7 _ _ _ _ _ _ _ _ _ WF_Type subtype Ty_trans\n        N_Wrap I_N_Wrap TUpdate _ cFJ_N Empty Update Bound N_Bound _ _ _ CT TE_trans\n        I_Ty_trans_invert N_Bound'_invert N_Wrap_inject build_te cFJ_sub i\n    end.\n\n  Lemma map_e_invert : forall XNs Us e e',\n    E_Ty_Trans XNs Us (cFJ_E e) e' -> Generic.E_Ty_Trans _ _ _ _ _ _ _ _ _ _\n    cFJ_E mbody_m_call_map mbody_new_map E_Ty_Trans XNs Us (cFJ_E e) e'.\n    intros; inversion H; subst; auto; inversion H0.\n  Qed.\n\n  Definition WF_fields_map_sub (X : Ty) : Bound'_sub_P _ _ subtype Bound X :=\n    match X return Bound'_sub_P _ _ subtype Bound X with\n      | N_Wrap (cFJ_N ty) => N_Bound'_sub _ _ _ _ N_Wrap _ _ subtype _ _ _ _ Bound _ _ CT\n      _ cFJ_sub N_Bound'_invert ty\n      | Gty ty => GJ_Bound'_sub _ _ Gty _ _ _ TLookup subtype GJ_sub Bound\n        GJ_Ty_Wrap_inject GJ_Bound'_invert' ty\n      | N_Wrap (I_N_Wrap i) => I_Bound'_sub _ _ _ _ _ _ _ _ subtype N_Wrap I_N_Wrap _ \n        cFJ_N Bound _ _ _ CT N_Bound'_invert build_te cFJ_sub i\n    end.\n    \n  Variable lookup_TUpdate : forall gamma X N x ty, lookup (TUpdate gamma X N) x ty -> lookup gamma x ty.\n  Variable lookup_TUpdate' : forall gamma X N x ty, lookup gamma x ty -> lookup (TUpdate gamma X N) x ty.\n    \n  Lemma EWrap_inject : forall e e', cFJ_E e = cFJ_E e' -> e = e'.\n    intros; injection H; intros; assumption.\n  Qed.\n\n  Definition WF_mtype_map_sub gamma ty ty' (Bnd : Bound gamma ty ty') :=\n    match Bnd in Bound gamma ty ty' return (WF_mtype_mab_sub_def Ty Context subtype Bound gamma ty ty' Bnd) with \n      | N_Bound _ _ _ Bnd' => N_WF_mtype_map_sub _ _ _ _ _ _ _ subtype _ _ _ _ Bound N_Bound _ _ \n        CT build_te cFJ_sub _ _ _ Bnd'\n      | GJ_Bound _ _ _ Bnd' => GJ_WF_mtype_map_sub _ _ _ _ _ _ TLookup _ GJ_sub Bound GJ_Bound _ _ _ Bnd'\n    end.\n  \n  Fixpoint Trans_Bound' T :=\n    match T return Trans_Bound'_P _ _ _ Ty_trans Bound T with\n      | N_Wrap (cFJ_N T') => FJ_Trans_Bound' _ _ _ _ _ _ _ _ Ty_trans Bound N_Bound \n        TE_trans FJ_Ty_trans_invert N_Wrap_inject N_Bound'_invert T'\n      | Gty T' => GJ_Trans_Bound' _ _ Gty _ _ _ TLookup Ty_trans Bound N_Bound GJ_Ty_Wrap_inject\n        _ Ty_trans_eq_NTy_trans GJ_Bound'_invert' T'\n      | N_Wrap (I_N_Wrap i) => I_Trans_Bound' _ _ _ _ _ _ Ty_trans N_Wrap I_N_Wrap Bound N_Bound \n        N_trans Ty_trans_eq_NTy_trans N_Bound'_invert i\n    end.\n\n  Definition Trans_WF_mtype_map := Trans_Bound'.\n  Definition Trans_WF_fields_map := Trans_Bound'.\n\n  Variable Ty_trans_mtype : forall (delta : Context) (m : _) \n    (S : Ty) (mty' : Mty Ty _)\n    (mtype_S : mtype delta m S mty'),\n    Ty_trans_mtype_P _ Ty N N_Wrap Context Empty subtype\n    Ty_trans WF_Type _ _ _ mtype TUpdate Update\n    m_call_ext WF_mtype_Us_map WF_mtype_U_map WF_mtype_ext\n    mbody_m_call_map delta m S mty' mtype_S.\n\n  Fixpoint Bound_total gamma S T (sub_S_T : subtype gamma S T) :=\n    match sub_S_T return Bound_total_P _ _ subtype Bound _ _ _ sub_S_T with \n      | cFJ_sub gamma' S' T' sub_S_T' => FJ_Bound_total _ _ _ _ _ _ _ subtype _ _ _ _ \n        Bound N_Bound _ _ CT build_te cFJ_sub Bound_total _ _ _ sub_S_T'\n      | GJ_sub gamma' S' T' sub_S_T' => GJ_Bound_total _ _ Gty _ _ \n        _ TLookup subtype GJ_sub Bound GJ_Bound _ _ _ sub_S_T'\n      | I_subtype_Wrap gamma' S' T' sub_S_T' => I_Bound_total _ _ _ _ _ _ _ _ subtype N_Wrap\n        I_N_Wrap _ implements cFJ_N _ N_Bound _ _ _ CT isub_build_te I_subtype_Wrap _ _ _ sub_S_T'\n    end.\n\n  Fixpoint Lem_2_7'' (S : Ty) :=\n    match S return Lem_2_7''_P _ _ _ _ _ Empty subtype Ty_trans WF_Type _ TUpdate Update Bound S with\n      | N_Wrap (cFJ_N S') => FJ_Lem_2_7'' _ _ _ _ _ _ _ _ Empty subtype Ty_trans WF_Type _ _ _ \n        TUpdate Update _ Bound N_Bound _ _ CT build_te cFJ_sub TE_trans FJ_Ty_trans_invert\n        N_Wrap_inject N_Bound'_invert S'\n      | Gty S' => GJ_Lem_2_7'' _ eq_nat_dec _ Gty _ _ _ Empty TLookup subtype Ty_trans\n        WF_Type _ TUpdate Update TLookup_Update TLookup_Update' TLookup_Empty Bound\n        GJ_Ty_Wrap_inject GJ_Ty_trans_invert TLookup_TUpdate_eq TLookup_TUpdate_neq\n        TLookup_TUpdate_neq' TLookup_id Bound_total GJ_Bound'_invert' Trans_Bound'\n        sub_Bound S'\n      | N_Wrap (I_N_Wrap i) => I_Lem_2_7'' _ _ _ _ _ _ _ _ _ WF_Type subtype Ty_trans N_Wrap \n        I_N_Wrap TUpdate _ cFJ_N Empty Update Bound N_Bound _ _ _ CT N_trans Ty_trans_eq_NTy_trans \n        N_Bound'_invert build_te cFJ_sub i\n    end.\n\n  Fixpoint subtype_update_list_id' delta S T (sub_S_T : subtype delta S T) :=\n    match sub_S_T return subtype_update_list_id'_P _ _ subtype _ Update _ _ _ sub_S_T with\n      | cFJ_sub delta' S' T' sub_S_T' => FJ_subtype_update_list_id' _ _ _ _ _ _ _ \n        subtype _ _ _ Update _ _ _ CT build_te cFJ_sub subtype_update_list_id' _ _ _ sub_S_T'\n      | GJ_sub delta' S' T' sub_S_T' => GJ_subtype_update_list_id' _ _ _ _ _ _ \n        TLookup subtype GJ_sub _ Update TLookup_Update' _ _ _ sub_S_T'\n      | I_subtype_Wrap delta' S' T' sub_S_T' => I_subtype_update_list_id' _ _ _ _ _ _ _ _ subtype N_Wrap \n        I_N_Wrap _ implements cFJ_N Update _ _ _ CT isub_build_te I_subtype_Wrap _ _ _ sub_S_T'\n    end.\n\n    Definition WF_Type_update_list_id' :=\n    WF_Type_rect' (WF_Type_update_list_id'_P _ _ WF_Type _ Update)\n    (WF_Type_update_list_id'_Q _ _ _ _ _ subtype Ty_trans WF_Type _ Update _ _)\n    (WF_Type_update_list_id'_P1 _ _ WF_Type _ Update)\n    (WF_Type_update_list_id'_Q'' _ _ _ _ _ wf_int_ext Update)\n    (WF_Type_update_list_id'_ext_H1 _ _ _ _ _ subtype Ty_trans WF_Type _ Update _ _ \n      subtype_update_list_id')\n    (WF_Type_update_list_id'_ext_H2 _ _ WF_Type _ Update)\n    (WF_Type_update_list_id'_ext_H3 _ _ WF_Type _ Update)\n    (WF_Type_update_list_id'_int_ext _ _ _ _ _ WF_Type subtype Ty_trans N_Wrap Update _ \n      subtype_update_list_id')\n    (GJ_WF_Type_update_list_id' _ _ Gty _ _ TLookup WF_Type GJ_WF_Type _ Update TLookup_Update')\n    (FJ_WF_Type_update_list_id'_H1 _ _ _ _ _ _ _ WF_Type _ _ _ Update _ _ _ CT wf_class_ext\n      wf_object_ext cFJ_WF_Type (WF_Type_update_list_id'_obj_ext _ _ _ Update _))\n    (FJ_WF_Type_update_list_id'_H2 _ _ _ _ _ _ _ WF_Type _ _ _ Update _ _ _ CT wf_class_ext wf_object_ext\n      cFJ_WF_Type)\n    (I_WF_Type_update_list_id' _ _ _ _ _ _ _ _ _ WF_Type wf_int_ext N_Wrap I_N_Wrap Update IT\n      I_WF_Type_Wrap).\n\n  Definition WF_mtype_ext_update_list := GJ_WF_mtype_ext_update_list _ _ N N_Wrap _ subtype Ty_trans\n    WF_Type _ _ Update _ (FJ_WF_mtype_ext Context) subtype_update_list_id' WF_Type_update_list_id'\n    (FJ_WF_mtype_ext_update_list _ _ _ _ ).\n\n  Definition WF_mtype_Us_map_update_list := Generic.GJ_WF_mtype_Us_map_update_list _ _ N _ Ty_trans\n    _ _ Update _ (FJ_WF_mtype_Us_map Ty Context) (FJ_WF_mtype_Us_map_update_list _ _ _ Update).\n\n  Definition WF_mtype_U_map_update_list := Generic.GJ_WF_mtype_U_map_update_list _ _ N _ Ty_trans\n    _ _ Update _ (FJ_WF_mtype_U_map Ty Context) (FJ_WF_mtype_U_map_update_list _ _ _ Update).\n\n    Definition Strengthen_Bound (S : Ty) := \n      match S return Strengthen_Bound''_P _ _ _ Update Bound S with \n        | N_Wrap (cFJ_N (ty_def te' c')) => \n          FJ_Strengthen_Bound'' _ _ _ _ _ cFJ_N _ _ Update Bound N_Bound N_Wrap_inject N_Bound'_invert te' c'\n        | Gty (TyVar X) => GJ_Strengthen_Bound'' _ _ Gty _ _ _ TLookup _ Update TLookup_Update' Bound \n          GJ_Bound GJ_Ty_Wrap_inject GJ_Bound'_invert' X\n        | N_Wrap (I_N_Wrap i) => I_Strengthen_Bound'' _ _ _ _ _ _ N_Wrap I_N_Wrap Update Bound N_Bound \n          N_Bound'_invert i\n      end.\n\n    Definition Strengthen_Bound' (S : Ty) := \n      match S return Strengthen_Bound'_P _ _ _ Update Bound S with \n        | N_Wrap (cFJ_N (ty_def te' c')) => \n          FJ_Strengthen_Bound' _ _ _ _ _ cFJ_N _ _ Update Bound N_Bound N_Wrap_inject N_Bound'_invert te' c'\n        | Gty (TyVar X) => GJ_Strengthen_Bound' _ _ Gty _ _ _ TLookup _ Update TLookup_Update Bound \n          GJ_Bound GJ_Ty_Wrap_inject GJ_Bound'_invert' X\n          | N_Wrap (I_N_Wrap i) => I_Strengthen_Bound' _ _ _ _ _ _ N_Wrap I_N_Wrap Update Bound N_Bound \n          N_Bound'_invert i\n      end.\n\n  Definition update_list_WF_mtype_ty_0_map := Strengthen_Bound.\n\n  Fixpoint subtype_update_Tupdate delta S T (sub_S_T : subtype delta S T) :=\n    match sub_S_T return subtype_update_Tupdate_P _ _ _ _ subtype _ TUpdate Update _ _ _ sub_S_T with\n      | cFJ_sub delta' S' T' sub_S_T' => FJ_subtype_update_Tupdate _ _ _ _ _ _ _ _ subtype\n        _ _ _ TUpdate Update _ _ _ CT build_te cFJ_sub subtype_update_Tupdate _ _ _ sub_S_T'\n      | GJ_sub delta' S' T' sub_S_T' => GJ_subtype_update_Tupdate _ eq_nat_dec _ Gty _ _ _ TLookup\n        subtype GJ_sub _ TUpdate Update TLookup_Update TLookup_Update' TLookup_TUpdate_eq\n        TLookup_TUpdate_neq TLookup_TUpdate_neq' TLookup_id _ _ _ sub_S_T'\n      | I_subtype_Wrap delta' S' T' sub_S_T' => I_subtype_update_Tupdate _ _ _ _ _ _ _ _ _ subtype N_Wrap\n        I_N_Wrap TUpdate _ implements cFJ_N Update _ _ _ CT isub_build_te I_subtype_Wrap _ _ _ sub_S_T'\n    end.\n\n    Definition WF_Type_update_Tupdate :=\n    WF_Type_rect' (WF_Type_update_Tupdate_P _ _ _ _ WF_Type _ TUpdate Update)\n    (WF_Type_update_Tupdate_Q _ _ _ _ _ subtype Ty_trans WF_Type _ TUpdate Update _ _)\n    (WF_Type_update_Tupdate_P1 _ _ _ _ WF_Type _ TUpdate Update)\n    (WF_Type_update_Tupdate_Q'' _ _ _ _ _ _ _ wf_int_ext TUpdate Update)\n    (WF_Type_update_Tupdate_ext_H1 _ _ _ _ _ subtype Ty_trans WF_Type _ TUpdate Update _ _ \n      subtype_update_Tupdate)\n    (WF_Type_update_Tupdate_ext_H2 _ _ _ _ WF_Type _ TUpdate Update)\n    (WF_Type_update_Tupdate_ext_H3 _ _ _ _ WF_Type _ TUpdate Update)\n    (WF_Type_update_Tupdate_int_ext _ _ _ _ _ WF_Type subtype Ty_trans N_Wrap TUpdate Update _\n      subtype_update_Tupdate)\n    (GJ_WF_Type_update_Tupdate _ eq_nat_dec _ Gty _ _ TLookup WF_Type GJ_WF_Type _ \n      TUpdate Update TLookup_Update TLookup_Update' TLookup_TUpdate_eq TLookup_TUpdate_neq\n      TLookup_TUpdate_neq' TLookup_id)\n    (FJ_WF_Type_update_Tupdate_H1 _ _ _ _ _ _ _ _ WF_Type _ _ _ TUpdate Update _ _ _ CT \n      wf_class_ext wf_object_ext cFJ_WF_Type \n      (WF_Type_update_Tupdate_obj_ext _ _ _ _ _ TUpdate Update _))\n    (FJ_WF_Type_update_Tupdate_H2 _ _ _ _ _ _ _ _ WF_Type _ _ _ TUpdate Update _ _ _ \n      CT wf_class_ext wf_object_ext cFJ_WF_Type)\n    (I_WF_Type_update_Tupdate _ _ _ _ _ _ _ _ _ _ WF_Type wf_int_ext N_Wrap I_N_Wrap TUpdate Update IT\n      I_WF_Type_Wrap).\n\n    Definition WF_fields_build_tys' gamma te (ce : I_cld_ext) := \n      Generic.FJ_WF_fields_build_tys Ty Context WF_Type gamma te (snd ce).\n\n    Fixpoint Ty_trans_fields delta S fds (fields_S : fields delta S fds) :=\n      match fields_S return Ty_trans_fields_P _ _ _ Empty Ty_trans _ fields _ _ _ fields_S with\n        | FJ_fields gamma ty fds FJ_case => FJ_fields_rect' _ _ _ _ _ _ _ _ _ _ CT \n          _ fields fields_build_te fields_build_tys FJ_fields \n          (Ty_trans_fields_P _ _ _ Empty Ty_trans _ fields)\n          (Ty_trans_fields_H1 _ _ _ _ _ _ _ _ Empty Ty_trans _ fields _ _ _ _ _ CT \n          TE_trans FJ_Ty_trans_invert _ _ FJ_fields)\n          (Ty_trans_fields_H2 _ _ _ _ _ _ _\n            _ Empty subtype Ty_trans WF_Type _ fields _ _ Update\n          _ FJ_Ty_Wrap_inject _ _ CT wf_class_ext wf_object_ext E_WF TE_trans FJ_Ty_trans_invert\n          ce_build_cte Meth_build_context Meth_WF_Ext L_WF_Ext L_build_context override WF_CT\n          fields_build_te fields_build_tys\n          (Generic.GJ_obj_TE_trans_fields_build_te' _ _ _ _ Ty_trans TUpdate _ _ _ _)\n          (Generic.GJ_class_TE_trans_fields_build_te' _ _ _ _ _ _ Empty subtype Ty_trans\n            WF_Type TUpdate _ _ Free_Vars TE_Free_Vars id (fun te txs FV => FV) \n            (fun te txs FV => FV) TE_trans (fun te te' eq => eq) GJ_TE_Trans_invert\n            exists_Free_Vars wf_free_vars map_Ty_trans' _ L_build_context'_Empty_1 _)\n          (GJ_TE_trans_fields_build_tys' _ _ _ _ _ Empty Ty_trans WF_Type TUpdate _ _ Free_Vars\n            TE_Free_Vars id (fun te txs FV => FV) \n            (fun te txs FV => FV) TE_trans (fun te te' eq => eq) GJ_TE_Trans_invert\n            exists_Free_Vars wf_free_vars map_Ty_trans' _ L_build_context'_Empty_1 _ _ \n            WF_fields_build_tys')\n          FJ_fields WF_Type_invert) _ _ _ FJ_case Ty_trans_fields\n      end.\n\n    Definition Strengthen_WF_Cast_map := Strengthen_Bound.\n\n    Definition WF_Cast_Map_total := Bound_total.\n\n    Definition WF_Cast_map_sub := WF_mtype_map_sub.\n\n    Lemma Cast_E_inject : forall e e', Cast_E e = Cast_E e' -> e = e'.\n      intros; congruence.\n    Qed.\n\n    Lemma Cast_map_e_invert : forall XNs (Us : list Ty) (e : Generic_Cast.Cast_E nat ty_ext E) (e' : E),\n      E_Ty_Trans XNs Us (Cast_E e) e' ->\n      Generic_Cast.E_Ty_Trans nat nat Ty ty_ext E _ Cast_E TE_trans E_Ty_Trans XNs\n      Us (Cast_E e) e'.\n      intros; inversion H; subst; try (inversion H0; fail); eauto.\n    Qed.\n\n  Fixpoint Lem_2_11 gamma e T (WF_e : E_WF gamma e T) :\n    Generic.Lem_2_11_P _ _ _ _ _ Empty subtype Ty_trans WF_Type _ TUpdate\n    Update E E_WF E_Ty_Trans gamma e T WF_e :=\n    match WF_e in E_WF gamma e T return Generic.Lem_2_11_P _ _ _ _ _ Empty subtype Ty_trans WF_Type _ \n      TUpdate Update E E_WF E_Ty_Trans gamma e T WF_e with\n      | Cast_E_WF gamma e ty Cast_case => Generic_Cast.Cast_Lem_2_11 _ _ _ _ _ _ _ _     \n        _ _ _ Ty_trans Cast_E TE_trans\n        _ app_context E_WF Bound subtype Cast_E_WF subtype_dec \n        Ty_eq_dec _ _ CT build_te cFJ_sub Update E_Ty_Trans TUpdate\n        WF_Type Empty Cast_map_e_invert Cast_E_inject WF_mtype_ty_0_map_total\n        Trans_WF_mtype_map Subtype_Update_list_id subtype_update_Tupdate\n        subst_context Type_Subst_Sub_2_5' WF_Cast_map_sub\n        subst_context_Empty app_context_Empty Strengthen_WF_Cast_map subtype_update_list_id'\n        sub_Bound FJ_NTy_trans_invert gamma e ty Cast_case Lem_2_11\n      | FJ_E_WF gamma e ty FJ_case => Generic.FJ_Lem_2_11 _ eq_nat_dec _ _ Gty _ _ \n        N_Wrap _ _ Empty TLookup subtype Ty_trans\n        WF_Type _ fields _ _ _ mtype TUpdate app_context Update _ Subtype_Update_list_id\n        _ _ CT build_te cFJ_sub Weakening_2_1_2 _ cFJ_E E_WF lookup\n        Bound WF_mtype_Us_map WF_mtype_U_map WF_mtype_ext Bound FJ_E_WF Free_Vars\n        GJ_Free_Vars' TE_trans FJ_Ty_trans_invert exists_Free_Vars\n        N_trans wf_free_vars subst_context TLookup_update_eq TLookup_update_neq\n        TLookup_update_neq' Ty_trans_eq_NTy_trans Ty_trans_trans_subst plus Ty_rename NTy_rename\n        Ty_rename_eq_NTy_rename rename_context TLookup_rename_context' GJ_Ty_rename_invert\n        Ty_rename_eq_Ty_trans FV_subst_tot Ty_rename_subtype subst_context_Empty app_context_Empty\n        Finite_Context Ty_rename_WF_Type Ty_rename_WF_Type' Type_Subst_Sub_2_5'\n        WF_context_shuffle Free_Vars_Ty_Rename Type_Subst_WF_2_6\n        subtype_update_Tupdate subtype_update_list_id' WF_Type_update_list_id' WF_Type_update_Tupdate\n        mbody_m_call_map mbody_new_map Lem_2_7 E_Ty_Trans map_e_invert\n        EWrap_inject lookup_TUpdate lookup_update_eq lookup_update_neq\n        lookup_update_neq' lookup_Empty lookup_id eq_nat_dec WF_fields_map_sub\n        Lem_2_8' Strengthen_Bound  Ty_trans_fields Trans_WF_fields_map\n        (Generic.GJ_mbody_new_map_TE_Trans _ _ _ Ty_trans _) \n        WF_Type_update_list_id  \n        update_list_WF_mtype_ty_0_map WF_mtype_U_map_update_list\n        WF_mtype_Us_map_update_list WF_mtype_ext_update_list Lem_2_7''\n        WF_mtype_map_sub WF_mtype_ty_0_map_total Ty_trans_mtype Lem_2_9 Trans_WF_mtype_map\n        _ _ _ FJ_case Lem_2_11\n    end.\n        \n  Definition Ty_trans_app :=\n    ty_rect (Ty_trans_app_P _ _ Ty_trans Free_Vars)\n    (TE_trans_app_Q _ _ _ TE_Free_Vars TE_trans)\n    (GJ_Ty_trans_app _ eq_nat_dec _ Gty _ _ GJ_Free_Vars_invert GJ_Ty_Wrap_inject GJ_Ty_trans_invert)\n    (FJ_Ty_trans_app _ _ _ _ _ N_Wrap cFJ_N _ FJ_Ty_Wrap_inject _ _ FJ_Free_Vars_invert _ FJ_Ty_trans_invert)\n    (I_Ty_trans_app _ _ _ _ _ Ty_trans N_Wrap I_N_Wrap Free_Vars TE_Free_Vars TE_trans I_Free_Vars_invert\n      I_Ty_trans_invert I_Ty_Wrap_inject)\n    (TE_trans_app_H1 _ _ _ _ Free_Vars)\n    (TE_trans_app_H2 _ _ _ _ _ ).\n\n  Definition build_cte_Free_Vars := Generic.build_cte_Free_Vars _ _ Gty N _ _ Free_Vars\n    GJ_Free_Vars_invert GJ_Ty_Wrap_inject (fun ce : I_cld_ext => FJ_ce_build_cte (snd ce)).\n\n  Definition GJ_TE_Free_Vars_Wrap (te : GTy_ext Ty) (txs : list _) :\n                          GJ_TE_Free_Vars _ _ _ Free_Vars te txs ->\n                          TE_Free_Vars (id te) txs := id.\n\n  Definition Ty_trans_no_op := ty_rect\n    (Ty_trans_no_op_P _  _ Ty_trans Free_Vars)\n    (Ty_trans_no_op_Q _ _ _ TE_Free_Vars TE_trans)\n    (GJ_Ty_trans_no_op _ eq_nat_dec _ Gty Ty_trans Free_Vars GJ_Free_Vars_invert \n      GJ_Ty_Wrap_inject GJ_Ty_trans_invert)\n    (FJ_Ty_trans_no_op _ _ _ _ _ N_Wrap cFJ_N Ty_trans FJ_Ty_Wrap_inject Free_Vars\n      TE_Free_Vars FJ_Free_Vars_invert TE_trans FJ_Ty_trans_invert)\n    (I_Ty_trans_no_op _ _ _ _ _ Ty_trans N_Wrap I_N_Wrap Free_Vars TE_Free_Vars TE_trans\n      I_Free_Vars_invert I_Ty_trans_invert I_Ty_Wrap_inject)\n    (Ty_trans_no_op_H3 _ _ _ Ty_trans _ Free_Vars id GTy_ext_Wrap_inject)\n    (Ty_trans_no_op_H4 _ _ _ Ty_trans _ Free_Vars TE_Free_Vars id GJ_TE_Free_Vars_Wrap\n      TE_trans GTy_ext_Wrap_inject GJ_TE_Trans_invert).\n\n  Definition GJ_Free_Vars_Wrap := GJ_Free_Vars'.\n\n  Definition  Ty_trans_fresh_vars :=\n    ty_rect (Ty_trans_fresh_vars_P _ _ Gty Ty_trans Free_Vars)\n    ( Ty_trans_fresh_vars_Q _ _ _ Gty Free_Vars TE_Free_Vars TE_trans)\n    (GJ_Ty_trans_fresh_vars _ eq_nat_dec _ Gty Ty_trans Free_Vars GJ_Free_Vars_Wrap\n      GJ_Free_Vars_invert GJ_Ty_Wrap_inject GJ_Ty_trans_invert Ty_trans_nil Free_Vars_Subst\n      Ty_trans_trans_subst Ty_trans_app Ty_trans_no_op)\n    (FJ_Ty_trans_fresh_vars _ _ _ Gty _ _ N_Wrap cFJ_N Ty_trans FJ_Ty_Wrap_inject Free_Vars\n      TE_Free_Vars FJ_Free_Vars_invert TE_trans FJ_Ty_trans_invert)\n    (I_Ty_trans_fresh_vars _ _ _ _ _ Ty_trans N_Wrap I_N_Wrap Gty _ _ _ \n      I_Free_Vars_invert I_Ty_trans_invert I_Ty_Wrap_inject)\n    (Ty_trans_fresh_vars_H3 _ _ _ Gty Ty_trans _ Free_Vars TE_Free_Vars id TE_trans\n      GJ_TE_Trans_invert)\n    (Ty_trans_fresh_vars_H4 _ _ _ Gty Ty_trans _ Free_Vars TE_Free_Vars id GJ_TE_Free_Vars_Wrap\n      GJ_TE_Free_Vars_invert TE_trans GTy_ext_Wrap_inject GJ_TE_Trans_invert).\n\n  Lemma Ty_trans_eq_N_Trans : forall N0 XNs Us,\n    N_Wrap (N_Trans XNs Us N0) = Ty_trans (N_Wrap N0) (Extract_TyVar _ N XNs) Us.\n    destruct N0; simpl; first [destruct f | destruct i]; reflexivity.\n  Qed.\n\n  Definition WF_mtype_U_map'_id := Generic.FJ_WF_mtype_U_map'_id Ty Context.\n\n  Definition WF_mtype_Us_map'_id := Generic.FJ_WF_mtype_Us_map'_id Ty Context.\n\n  Definition mtype_build_tys'_id (ce : I_cld_ext) := Generic.FJ_mtype_build_tys'_id Ty nat (snd ce).\n\n  Definition TE_trans_app (te : ty_ext) := GJ_TE_trans_app _ _ Ty_trans _ Free_Vars Ty_trans_app te.\n\n  Definition exists_TE_Free_Vars (te : ty_ext) := GJ_exists_TE_Free_Vars _ _ _ Free_Vars exists_Free_Vars te.\n \n  Fixpoint Strengthen_subtype_update_TList delta S T (sub_S_T : subtype delta S T) :=\n    match sub_S_T return Strengthen_subtype_update_TList_P _ _ subtype _ Update _ _ _ sub_S_T with\n      | cFJ_sub delta' S' T' sub_S_T' => FJ_Strengthen_subtype_update_TList _ _ _ _ _ _ _ \n        subtype _ _ _ Update _ _ _ CT build_te cFJ_sub Strengthen_subtype_update_TList _ _ _ sub_S_T'\n      | GJ_sub delta' S' T' sub_S_T' => GJ_Strengthen_subtype_update_TList _ _ Gty _ _ _ TLookup \n        subtype GJ_sub _ Update TLookup_Update _ _ _ sub_S_T'\n      | I_subtype_Wrap delta' S' T' sub_S_T' => I_Strengthen_subtype_update_TList _ _ _ _ _ _ _ _ subtype\n        N_Wrap I_N_Wrap _ implements cFJ_N Update _ _ _ CT isub_build_te I_subtype_Wrap _ _ _ sub_S_T'\n    end.\n\n  Definition Strengthen_WF_Type_update_TList :=\n    WF_Type_rect' (Strengthen_WF_Type_update_TList_P _ _ WF_Type _ Update)\n    (Strengthen_WF_Type_update_TList_Q _ _ _ _ _ subtype Ty_trans WF_Type _ Update _ _)\n    (Strengthen_WF_Type_update_TList_P1 _ _ WF_Type _ Update)\n    (Strengthen_WF_Type_update_TList_Q'' _ _ _ _ _ wf_int_ext Update)\n    (Strengthen_WF_Type_update_TList_ext_H1 _ _ _ _ _ subtype Ty_trans WF_Type _ Update _ _\n      Strengthen_subtype_update_TList)\n    (Strengthen_WF_Type_update_TList_ext_H2 _ _ WF_Type _ Update)\n    (Strengthen_WF_Type_update_TList_ext_H3 _ _ WF_Type _ Update)\n    (Strengthen_WF_Type_update_TList_int_ext _ _ _ _ _ WF_Type subtype Ty_trans N_Wrap \n      Update _ Strengthen_subtype_update_TList)\n    (GJ_Strengthen_WF_Type_update_TList _ _ Gty _ _ TLookup WF_Type GJ_WF_Type\n      _ Update TLookup_Update)\n    (FJ_Strengthen_WF_Type_update_TList_H1 _ _ _ _ _ _ _ WF_Type _ _ _ Update _ _ _\n      CT wf_class_ext wf_object_ext cFJ_WF_Type\n    (Strengthen_WF_Type_update_TList_obj_ext _ _ _ Update _))\n    (FJ_Strengthen_WF_Type_update_TList_H2 _ _ _ _ _ _ _ WF_Type _ _ _ \n      Update _ _ _ CT wf_class_ext wf_object_ext cFJ_WF_Type)\n    (I_Strengthen_WF_Type_update_TList _ _ _ _ _ _ _ _ _ WF_Type wf_int_ext N_Wrap I_N_Wrap \n      Update IT I_WF_Type_Wrap).\n\n  Definition build_context'_Empty_1 (ce : I_cld_ext) me vds gamma := \n    FJ_build_context'_Empty_1 _ _ _ _ Empty WF_Type _ TUpdate Update (snd ce) me vds gamma.\n  \n  Definition build_context'_Empty_2  (ce : I_cld_ext) me vds gamma :=\n    FJ_build_context'_Empty_2 _ _ _ _ Empty subtype _ TUpdate Update (snd ce) me vds gamma.\n\n  Definition build_context'_Empty_3 (ce : I_cld_ext) me vds gamma := \n    FJ_build_context'_Empty_3 _ _ _ _ Empty _ TUpdate Update _ E_WF (snd ce) me vds gamma.\n\n  Variable build_fresh_distinct : forall tys ty vds Xs Ys Zs, \n    build_fresh tys ty vds Xs Ys Zs -> distinct Zs.\n  Variable build_fresh_new : forall tys ty vds Zs Xs Ws Ys, List_P2' (Free_Vars) tys Zs -> \n    build_fresh tys ty vds Xs Ws Ys -> List_P1 (fun Zs' => forall Y, In Y Ys -> ~ In Y Zs') Zs.\n  Variable build_fresh_new' : forall tys ty vds Zs Xs Ws Ys, List_P2' (Free_Vars) vds Zs -> \n    build_fresh tys ty vds Xs Ws Ys -> List_P1 (fun Zs' => forall Y, In Y Ys -> ~ In Y Zs') Zs.\n  Variable build_fresh_new'' : forall tys ty vds Ws Xs Ys Zs, Free_Vars ty Ws ->\n    build_fresh tys ty vds Xs Ys Zs -> forall Y, In Y Zs -> ~ In Y Ws.\n  Variable build_fresh_new''' : forall tys ty vds Xs Ys Zs, \n    build_fresh tys ty vds Xs Ys Zs -> forall Y, In Y Zs -> ~ In Y Xs.\n  Variable build_fresh_new''''' : forall tys ty vds Ws Xs Ys Zs, \n    List_P2' Free_Vars (map (fun n => N_Wrap (snd n)) Ys) Ws ->\n    build_fresh tys ty vds Xs Ys Zs -> \n    List_P1 (fun Zs' => forall Y, In Y Zs -> ~ In Y Zs') Ws.\n\n  Definition Build_S0''' : forall (ce : cld_ext) (me : md_ext)\n                   (gamma gamma' : Context) (te te' : ty_ext) \n                   (c : _) (vds : list (Generic.VD Ty _)) \n                   (S0 T0 : Ty) (delta : Context) (e e' : E) \n                   (D D' : Ty) (mtye : mty_ext) \n                   (mce : m_call_ext) (Ds Ds' : list Ty)\n                   (Vars : list (Var _ * Ty))\n                 (H : L_WF_Ext gamma' ce c),\n                 L_build_context ce gamma' ->\n                 Meth_WF_Ext gamma ce me ->\n                 ce_build_cte ce te' ->\n                 (forall (Y : _) (Zs : list _),\n                  TE_Free_Vars te' Zs ->\n                  In Y Zs ->\n                  In Y (Extract_TyVar _ N (fst ce))) ->\n                 Meth_build_context ce me\n                   (cFJ.update_list _ Ty Context Update Empty\n                      ((this _,\n                        Generic.FJ_Ty_Wrap Ty ty_ext _ N N_Wrap cFJ_N\n                         (ty_def _ ty_ext te' (cl _ c)))\n                       :: map\n                            (fun Tx : Generic.VD Ty _ =>\n                             match Tx with\n                             | vd ty x => (var _ x, ty)\n                             end) vds)) gamma ->\n                 E_WF gamma e S0 ->\n                 subtype gamma S0 T0 ->\n                 wf_class_ext delta ce te ->\n                 mtype_build_mtye ce te T0 vds me mtye ->\n                 map_mbody ce te mce me e e' ->\n                 mtype_build_tys ce te T0 vds me (T0 :: nil) (D :: nil) ->\n                 WF_mtype_U_map delta mce mtye D D' ->\n                 WF_mtype_ext delta mce mtye ->\n                 WF_mtype_Us_map delta mce mtye Ds Ds' ->\n                 List_P1\n                   (fun Tx : Generic.VD Ty _ =>\n                    match Tx with\n                    | vd ty _ => WF_Type gamma ty\n                    end) vds ->\n                 zip\n                   (this _\n                    :: map\n                         (fun Tx : Generic.VD Ty _ =>\n                          match Tx with\n                          | vd _ x => var _ x\n                          end) vds)\n                   (Generic.FJ_Ty_Wrap Ty ty_ext _ N N_Wrap cFJ_N\n                      (ty_def _ ty_ext\n                         (TE_trans te'\n                            (Extract_TyVar _ N (fst ce))\n                            (fst te))\n                         (cl _ c)) :: Ds') (@pair _ _) = Some Vars ->\n                 mtype_build_tys ce te T0 vds me\n                   (map\n                      (fun vd' : Generic.VD Ty _ =>\n                       match vd' with\n                       | vd ty _ => ty\n                       end) vds) Ds ->\n                 exists S0'' : Ty,\n                   subtype delta S0'' D' /\\\n                   E_WF (cFJ.update_list _ Ty Context Update delta Vars) e'\n                     S0'' :=\n    (fun ce me gamma gamma' te te' c vds S0 T0 delta e e' D D' mtye mce Ds Ds' Vars H => \n      Generic.GJ_Build_S0''' _ _ _ Gty _ _ N_Wrap cFJ_N\n      _ Empty subtype Ty_trans WF_Type _ _ _ build_fresh N_Trans TUpdate\n      app_context Update _ _ _ Subtype_Update_list_id _ _ CT build_te\n      cFJ_sub E_WF Free_Vars TE_Free_Vars TE_trans FJ_Ty_trans_invert exists_Free_Vars\n      wf_free_vars subst_context L_build_context' L_build_context'_Empty_1 Free_Vars_id subst_context_Empty\n      app_context_Empty Type_Subst_Sub_2_5' (@id_map_2 _ _ FJ_ty_ext) build_fresh_len subtype_update_Tupdate Ty_trans_app\n      TE_trans_app WF_Type_update_Tupdate Strengthen_WF_Type_update_TList E_Ty_Trans _ _ _ _\n      (fun gamma (ie : I_cld_ext) c => FJ_L_WF_Ext _ _ gamma (@snd _ _ ie) c )\n      (fun (ice : I_cld_ext) mde gamma gamma' => FJ_Meth_build_context _ (snd ice) mde gamma gamma') _ \n      (fun ice te ty vds mce tys tys' => FJ_mtype_build_tys nat _ (snd ice) te ty vds mce tys tys') _ _\n      (FJ_WF_mtype_Us_map Ty Context) _ _ \n      mtype_build_tys_len Weaken_WF_Type_app_TList build_context'_Empty_1\n      build_context'_Empty_2 build_context'_Empty_3 Ty_trans_eq_N_Trans\n      Lem_2_11 build_fresh_distinct build_fresh_id Ty_trans_fresh_vars build_fresh_new build_fresh_new' \n      build_fresh_new'' build_fresh_new''' build_fresh_new''''' WF_mtype_U_map'_id \n      WF_mtype_Us_map'_id mtype_build_tys'_id exists_TE_Free_Vars id \n      ce me gamma gamma' te te' c vds S0 T0 delta e e' D D' mtye mce Ds Ds' Vars (proj1 H)).\n\n  Lemma WF_class_ext_TE_trans (gamma delta : Context) (c : nat) (ce : cld_ext) \n    (te te' : ty_ext) (_ : ce_build_cte ce te') (_ : L_WF_Ext gamma ce c)\n    (wf_c : wf_class_ext delta ce te) : \n    te = TE_trans te' (Extract_TyVar _ _ (fst (ce))) (fst (te)) .\n    eapply GJ_WF_class_ext_TE_trans.\n    apply GJ_Ty_trans_invert.\n    destruct te0; destruct te'0; reflexivity.\n    unfold wf_class_ext in wf_c; unfold wf_class_ext' in wf_c.\n    unfold id; apply wf_c.\n    unfold id; apply H0.\n    apply H.\n  Qed.\n\n\n  Definition Build_S0'' :=\n    Generic.Build_S0'' _ _ _ _ _ N_Wrap cFJ_N _ \n    Empty subtype WF_Type _ _ Update _ I_cld_ext _ _ wf_class_ext\n    m_call_ext E_WF WF_mtype_Us_map WF_mtype_U_map WF_mtype_ext TE_Free_Vars TE_trans ce_build_cte \n    Meth_build_context Meth_WF_Ext L_WF_Ext L_build_context FJ_ty_ext id mtype_build_mtye\n    id build_cte_Free_Vars WF_class_ext_TE_trans map_mbody mtype_build_tys\n    Build_S0'''.  \n  \n  Definition Term_subst_pres_typ_def := \n    cFJ.Term_subst_pres_typ_P _ _ _ _ subtype E_WF Update trans.\n  \n  Fixpoint Weaken_subtype_Update_list delta S T sub_S_T :=\n    match sub_S_T in (subtype delta S T) return \n      (Generic.Weaken_subtype_Update_list_P _ _ subtype _ Update delta S T sub_S_T) with\n      | cFJ_sub gamma' S' T' sub_S_T' =>\n        FJ_Weaken_subtype_Update_list _ _ _ _ _ _ _ subtype _ _ _ Update _ _ _ CT\n        build_te cFJ_sub Weaken_subtype_Update_list _ _ _ sub_S_T'\n      | GJ_sub gamma' S' T' sub_S_T' => \n        GJ_Weaken_subtype_Update_list\n        _ _ _ _ _ _ TLookup subtype GJ_sub _ Update TLookup_Update _ _ _ sub_S_T'\n      | I_subtype_Wrap _ _ _ sub_S_T' =>\n        I_Weaken_subtype_Update_list _ _ _ _ _ _ N _ _ N_Wrap I_N_Wrap _ _ cFJ_N _ _ _ _ CT\n        _ I_subtype_Wrap _ _ _ sub_S_T'\n    end.\n\n  Definition Weaken_WF_Update_list :=\n    WF_Type_rect' (Generic.Weaken_WF_Update_list_P _ _ WF_Type _ Update)\n    (Weaken_WF_Update_list_Q _ _ _ _ Update _ wf_class_ext)\n    (Generic.Weaken_WF_Update_list_P1 _ _ WF_Type _ Update)\n    (Weaken_WF_Update_list_Q'' _ _ _ _ _ wf_int_ext Update)\n    (Weaken_WF_Update_list_ext_H1 _ _ _ _ _ subtype Ty_trans WF_Type _ Update\n      _ _ Weaken_subtype_Update_list)\n    (Weaken_WF_Update_list_ext_H2 _ _ _ _ _)\n    (Weaken_WF_Update_list_ext_H3 _ _ _ _ _)\n    (I_Weaken_WF_Update_list_ext _ _ _ _ _ _ _ Ty_trans N_Wrap _ _ _ Weaken_subtype_Update_list)\n    (GJ_Weaken_WF_Update_list _ _ Gty _ _ TLookup _ GJ_WF_Type _ Update TLookup_Update)\n    (FJ_Weaken_WF_Update_list_H1 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ CT _ _ cFJ_WF_Type\n      (GJ_Weaken_WF_Update_list_obj_ext _ _ _ Update _))\n    (FJ_Weaken_WF_Update_list_H2 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ cFJ_WF_Type)\n    (I_Weaken_WF_Update_list _ _ _ _ _ _ _ _ _ _ _ N_Wrap I_N_Wrap _ IT\n      I_WF_Type_Wrap).\n\n  Definition WF_mtype_ext_update_list_id' := Generic.WF_mtype_ext_update_list_id' _ _ N N_Wrap _ \n    subtype Ty_trans WF_Type _ Update Weaken_subtype_Update_list\n    Weaken_WF_Update_list _ _ _ \n    (fun delta mce mtye vars => FJ_WF_mtype_ext_update_list_id _ _ _ Update delta vars mce mtye).\n  \n  Definition Term_subst_pres_typ_P := \n    cFJ.Term_subst_pres_typ_P _ _ _ _ subtype E_WF Update trans.\n\n  Definition WF_mtype_ext_Weaken_update_list gamma vars mce mtye := \n    WF_mtype_ext_update_list_id' gamma mce mtye vars.\n\n  Lemma Cast_E_trans_Wrap : forall (e : Cast.Cast_E nat ty_ext E) (vars : list (Var nat)) (es' : list E),\n    trans (Cast_E e) vars es' =\n    Cast_E (Cast_E_trans nat ty_ext E nat trans e vars es').\n    simpl; reflexivity.\n  Qed.\n\n  Fixpoint Subtype_Update_list_id'' gamma S T (sub_S_T : subtype gamma S T) :=\n    match sub_S_T in (subtype gamma S T) return \n      (Cast.Subtype_Update_list_id'_P _ _ subtype nat Update gamma S T sub_S_T) with\n      | cFJ_sub gamma' S' T' sub_S_T' => \n        FJ_Subtype_Update_list_id' _ _ _ _ _ _ subtype _ _ _ _ _ CT\n        build_te Update cFJ_sub gamma' S' T' sub_S_T' Subtype_Update_list_id''\n      | GJ_sub gamma' S' T' sub_S_T' => \n        Generic_Cast.Subtype_Update_list_id' _ _ _ _ _\n        _ subtype TLookup Gty GJ_sub Update TLookup_Update' gamma' S' T' sub_S_T'\n      | I_subtype_Wrap gamma' S' T' sub_S_T' => I_Subtype_Update_list_id'\n        _ _ _ I_Ty_Wrap  _ _ _ _ _ _ _ _ CT isub_build_te implements FJ_Ty_Wrap subtype\n        I_subtype_Wrap Update _ _ _ sub_S_T'\n    end.\n\n  Fixpoint Term_subst_pres_typ gamma e T (WF_e : E_WF gamma e T) :\n    Term_subst_pres_typ_P gamma e T WF_e :=\n    match WF_e with \n      | Cast_E_WF gamma e ty Cast_case => Cast_Term_subst_pres_typ _ _ _ _\n        _ _ Cast_E E_WF Bound subtype Cast_E_WF _ _ _ _ _ CT build_te Update\n        cFJ_sub subtype_dec Ty_eq_dec trans Cast_E_trans_Wrap \n        Subtype_Update_list_id Subtype_Update_list_id''\n        WF_mtype_ty_0_map_Weaken_update_list WF_mtype_ty_0_map_total sub_Bound _ _ _ \n        Cast_case Term_subst_pres_typ        \n      | FJ_E_WF gamma e ty FJ_case => FJ_Term_subst_pres_typ _ _ _ _ _ _ \n        _ _ _ cFJ_E mty_ext _ _ CT _ subtype build_te\n        cFJ_sub WF_Type fields mtype \n        E_WF lookup Bound Bound WF_mtype_Us_map\n        WF_mtype_U_map WF_mtype_ext Empty FJ_E_WF Update\n        trans eq_nat_dec lookup_update_eq lookup_update_neq'\n        lookup_id E_trans_Wrap Lem_2_8' Lem_2_9 \n        (fun d v ty ty' B => WF_mtype_ty_0_map_Weaken_update_list _ _ _ B d v (refl_equal _))\n        (fun d v ty ty' B => WF_mtype_ty_0_map_Weaken_update_list _ _ _ B d v (refl_equal _))\n        (fun g v mc mty u u' => WF_mtype_U_map_Weaken_update_list g v mc u u' mty)\n        (fun d v mc mt us us' => WF_mtype_Us_map_Weaken_update_list d v mc us us' mt)\n        WF_mtype_ext_Weaken_update_list WF_mtype_ty_0_map_total \n        Subtype_Update_list_id WF_Type_update_list_id gamma e ty FJ_case Term_subst_pres_typ\n    end.\n\n  Definition build_te_id' :=\n    build_te_id' _ _ N Ty_trans _ _ (fun (ice : I_cld_ext) te te' te''=> FJ_mbody_build_te (snd ice) te te' te'') \n    (fun (ice : I_cld_ext) te te' te'' => FJ_build_te (snd ice) te te' te'') (fun ice => FJ_build_te_id (snd ice)).\n     \n  Lemma mtype_invert : forall (gamma : Context) (m0 : nat) (te : ty_ext) \n    (c : nat) (mty : Mty Ty mty_ext),\n    mtype gamma m0 (FJ_Ty_Wrap (ty_def nat ty_ext te (cl nat c))) mty ->\n    cFJ.FJ_mtype nat nat nat nat ty_ext Ty FJ_Ty_Wrap E mty_ext\n    md_ext cld_ext CT Context mtype mtype_build_te mtype_build_tys\n    mtype_build_mtye gamma m0\n    (FJ_Ty_Wrap (ty_def nat ty_ext te (cl nat c))) mty.\n    intros; inversion H; subst; try assumption.\n    inversion H0.\n  Qed.\n  \n  Definition WF_mtype_Us_map_len' := WF_mtype_Us_map_len' _ _ N _ Ty_trans _ _ \n    _ (FJ_WF_mtype_Us_map_len _ Context).\n\n  Lemma Base_inject : forall ty ty', FJ_Ty_Wrap ty = FJ_Ty_Wrap ty' -> ty = ty'.\n    intros ty ty' H; injection H; auto.\n  Qed.\n\n  Definition methods_build_te_id' := methods_build_te_id' _ _ _ N Ty_trans _ _ _ \n    (fun (ce : I_cld_ext) te te' te'' => FJ_methods_build_te_id (snd ce) te te' te'').\n\n   Definition WF_Type_par delta ty (WF_ty : WF_Type delta ty) := \n     match WF_ty in (WF_Type delta ty) return \n       cFJ.WF_Type_par_P _ _ _ _ ty_ext Ty FJ_Ty_Wrap E _ _ CT _ WF_Type mtype_build_te\n       L_build_context delta ty WF_ty with \n       | I_WF_Type_Wrap gamma ty WF_int => \n         Interface.WF_Type_par _ _ _ I_Ty_Wrap _ _ _ _ _ IT _ _ _ _ cld_ext CT\n         (Generic.FJ_Ty_Wrap Ty ty_ext nat N N_Wrap cFJ_N) \n         wf_int_ext WF_Type I_WF_Type_Wrap mtype_build_te L_build_context \n         Ty_discriminate gamma ty WF_int\n       | cFJ_WF_Type gamma ty WF_base => \n         FJ_WF_Type_par _ _ _ _ _ _ _ _ _ _ CT Context \n         wf_class_ext wf_object_ext WF_Type cFJ_WF_Type mtype_build_te\n         L_build_context Base_inject WF_Type_par_Lem WF_Type_par_Lem' gamma ty WF_base\n       | GJ_WF_Type delta ty WF_ty => GJ_WF_Type_par _ _ _ Gty _ _ N_Wrap _ _ \n         TLookup WF_Type GJ_WF_Type _ _ _ _ Ty_Wrap_discriminate _ _ CT L_build_context \n         _ delta ty WF_ty\n     end.\n\n  Definition WF_mb_ext (gamma : Context) (mbe : mb_ext) : Prop := True.\n\n  Lemma WF_Build_mb_ext : forall (ce : cld_ext) (me : md_ext) \n                       (gamma : Context) (te te' : ty_ext) \n                       (c : _) (vds : list (cFJ.VD _ Ty)) \n                       (T0 : Ty) (delta : Context) \n                       (D D' : Ty) (mtye : mty_ext) \n                       (mce : m_call_ext) (mbe : mb_ext) \n                       (Ds Ds' : list Ty) (te'' : ty_ext)\n                       (Vars : list (Var _ * Ty)),\n                     Meth_WF_Ext gamma ce me ->\n                     Meth_build_context ce me\n                       (update_list Empty\n                          ((this _, FJ_Ty_Wrap (ty_def _ ty_ext te' (cl _ c)))\n                           :: map\n                                (fun Tx : cFJ.VD _ Ty =>\n                                 match Tx with\n                                 | vd ty x => (var _ x, ty)\n                                 end) vds)) gamma ->\n                     WF_Type delta (FJ_Ty_Wrap (ty_def _ ty_ext te (cl _ c))) ->\n                     build_mb_ext ce te mce me mbe ->\n                     mtype_build_tys ce te T0 vds me (T0 :: nil) (D :: nil) ->\n                     WF_mtype_U_map delta mce mtye D D' ->\n                     WF_mtype_ext delta mce mtye ->\n                     WF_mtype_Us_map delta mce mtye Ds Ds' ->\n                     List_P1\n                       (fun Tx : cFJ.VD _ Ty =>\n                        match Tx with\n                        | vd ty _ => WF_Type gamma ty\n                        end) vds ->\n                     zip\n                       (this _\n                        :: map\n                             (fun Tx : cFJ.VD _ Ty =>\n                              match Tx with\n                              | vd _ x => var _ x\n                              end) vds)\n                       (FJ_Ty_Wrap (ty_def _ ty_ext te'' (cl _ c)) :: Ds') (@pair _ _) =\n                     Some Vars ->\n                     mtype_build_tys ce te'' T0 vds me\n                       (map\n                          (fun vd'  =>\n                           match vd' with\n                           | vd ty _ => ty\n                           end) vds) Ds ->\n                     WF_mb_ext\n                       (update_list delta Vars) mbe.\n    intros; constructor.\n  Qed.\n\n  Definition Lem_2_12 := FJ_Lem_2_12 _ _ _ _ _ _ _ _ _ _ _ _ CT \n    Context subtype build_te cFJ_sub _ _ WF_Type cFJ_WF_Type fields mtype mtype_build_te\n    mtype_build_tys mtype_build_mtye mbody_build_te\n    mb_ext build_mb_ext map_mbody\n    E_WF Bound WF_mtype_Us_map WF_mtype_U_map WF_mtype_ext Empty Update\n    ce_build_cte Meth_build_context Meth_WF_Ext\n    override L_WF_Ext L_build_context WF_CT Base_inject \n    Build_S0''  WF_mb_ext WF_Build_mb_ext WF_mtype_Us_map_len' mtype_build_tys_len' methods_build_te_id' WF_Type_par\n    build_te_id' mtype_invert \n    (WF_mtype_ty_0_map_cl_id'' _ _ _ _ _ _ _ Bound N_Bound'_invert) \n    (WF_mtype_ty_0_map_tot' _ _ _ _ _ _ _ Bound N_Bound) WF_Type_invert.\n\n  Lemma FJ_E_WF_invert : forall gamma (e : FJ_E _ _ _ _ _ _ _ ) c0, \n    E_WF gamma (cFJ_E e) c0 -> cFJ.FJ_E_WF _ _ _ _ _ Ty (Generic.FJ_Ty_Wrap Ty ty_ext nat N N_Wrap cFJ_N)\n    _ _ cFJ_E mty_ext\n    Context subtype WF_Type fields mtype\n    E_WF lookup Bound Bound WF_mtype_Us_map WF_mtype_U_map \n    WF_mtype_ext Empty gamma (cFJ_E e) c0.\n    intros; inversion H; subst; try assumption; inversion H0.\n  Qed.\n  \n  Definition preservation_def := cFJ.preservation Ty E Context subtype E_WF Reduce.\n  \n  Definition Reduce_List_preservation es es' (red_es : Congruence_List_Reduce es es') :=\n    cFJ.Reduce_List_preservation _ _ _ subtype E_WF Congruence_List_Reduce es es' red_es.\n        \n  Definition WF_fields_map_sub' := \n    WF_fields_map_sub' _ _ _ _ _ _ _ Empty subtype _ fields _ _ _ Bound _ _ CT build_te\n    cFJ_sub N_Wrap_inject N_Bound'_invert FJ_N_Ty_Wrap_inject fields_id.\n  \n    Lemma FJ_E_WF_new_invert : forall gamma e T T0, \n      E_WF gamma (cFJ_E (cFJ.new nat nat nat nat ty_ext E m_call_ext T e)) T0 ->\n      N_Wrap (cFJ_N T) = T0.\n      intros; inversion H; subst.\n      inversion H0; subst.\n      destruct te; reflexivity.\n      inversion H0.\n    Qed.\n\n    Lemma Cast_E_WF_invert : forall gamma e c0, E_WF gamma (Cast_E e) c0 -> \n      Cast.Cast_E_WF _ _ _  (Generic.FJ_Ty_Wrap Ty ty_ext nat N N_Wrap cFJ_N) _ _ \n      Cast_E E_WF Bound subtype gamma (Cast_E e) c0.\n      intros; inversion H; subst.\n      inversion H0.\n      assumption.\n    Qed.\n\n  Fixpoint preservation e e' (red_e : Reduce e e') : preservation_def _ _ red_e :=\n    match red_e with \n      |  FJ_S_Reduce t t' red_t => FJ_pres _ _ _ _ _ _ _ _ _ \n        cFJ_E _ _ _ CT _ subtype build_te cFJ_sub WF_Type fields\n        mtype mbody_build_te mb_ext build_mb_ext\n        map_mbody E_WF lookup\n        Bound Bound WF_mtype_Us_map WF_mtype_U_map\n        WF_mtype_ext Empty FJ_E_WF Update trans\n        Reduce FJ_S_Reduce FJ_E_WF_invert EWrap_inject\n        Fields_eq fds_distinct WF_fields_map_id \n        (fun g tye c ty' Bnd => WF_fields_map_id' g _ _ Bnd tye c (refl_equal _))\n        WF_fields_map_sub' Subtype_Weaken WF_mtype_map_sub Term_subst_pres_typ WF_mb_ext Lem_2_12\n        t t' red_t\n      | Cast_Reduce e e' cast_red_e => Cast_preservation' _ _ _ \n        (Generic.FJ_Ty_Wrap Ty ty_ext nat N N_Wrap cFJ_N) _ _ Cast_E\n        E_WF Bound subtype Reduce _ _ _ _ _ _ cFJ_E CT build_te Empty Cast_Reduce \n        cFJ_sub Cast_E_WF_invert Cast_E_inject FJ_E_WF_new_invert\n        Subtype_Weaken WF_mtype_map_sub e e' cast_red_e\n      | Cast_C_Reduce e e' cast_c_red_e => Cast_C_preservation' _ _ _ _ _ _ Cast_E\n        E_WF Bound subtype Cast_E_WF _ _ _ _ _ CT build_te Reduce Cast_C_Reduce\n        cFJ_sub subtype_dec Ty_eq_dec WF_mtype_ty_0_map_total sub_Bound Cast_E_WF_invert Cast_E_inject\n        e e' cast_c_red_e preservation       \n      | FJ_C_Reduce e e' fj_red_e' => FJ_C_preservation _ _ _ _ ty_ext _ _ _ _ cFJ_E _ _ _ CT\n        _ subtype build_te cFJ_sub WF_Type fields mtype E_WF lookup Bound\n        Bound WF_mtype_Us_map WF_mtype_U_map WF_mtype_ext Empty FJ_E_WF \n        Reduce Congruence_List_Reduce FJ_C_Reduce FJ_E_WF_invert EWrap_inject\n        Lem_2_8' Lem_2_9 WF_mtype_ty_0_map_total e e' fj_red_e'\n        preservation (fix preservation_list (es es' : list E) (red_es : Congruence_List_Reduce es es') : \n          Reduce_List_preservation _ _ red_es :=\n          match red_es return Reduce_List_preservation _ _ red_es with\n            FJ_Reduce_List es es' red_es' => FJ_C_List_preservation _ _ _ _ _ _ _ _ _ _ \n            CT _ subtype build_te cFJ_sub E_WF Reduce\n            Congruence_List_Reduce FJ_Reduce_List es es' red_es' preservation preservation_list end)      \n    end.\n\n  Inductive subexpression : E -> E -> Prop :=\n    FJ_subexpression_Wrap : forall e e', FJ_subexpression _ _ _ _ _ _ _ cFJ_E subexpression subexpression_list e e' -> subexpression e e'\n  | Cast_subexpression_Wrap : forall e e', Cast_subexpression _ _ _ Cast_E subexpression e e' -> subexpression e e'\n  with subexpression_list : E -> list E -> Prop :=\n    subexpression_list_Wrap : forall e es, FJ_subexpression_list _ subexpression subexpression_list e es ->\n      subexpression_list e es.\n\n  Definition progress_1_P := cFJ.progress_1_P _ _ _ _ _ _ (Generic.FJ_Ty_Wrap Ty ty_ext nat N N_Wrap cFJ_N)\n    _ _ cFJ_E _ fields E_WF Empty subexpression.\n  \n  Definition progress_1_list_P := cFJ.progress_1_list_P _ _ _ _ _ _ \n    (Generic.FJ_Ty_Wrap Ty ty_ext nat N N_Wrap cFJ_N) _ _ cFJ_E \n    _ fields E_WF Empty subexpression_list.\n  \n  Lemma subexp_invert : forall (e : E) e',\n    subexpression e (cFJ_E e') ->\n    FJ_subexpression nat nat nat nat ty_ext E m_call_ext cFJ_E subexpression subexpression_list e (cFJ_E e').\n    clear; intros; inversion H; subst; auto; inversion H0.\n  Qed.\n  \n  Lemma subexpression_list_nil : forall e : E, ~ subexpression_list e nil.\n    clear; unfold not; intros; inversion H; subst;\n      eapply (FJ_subexpression_list_nil E subexpression subexpression_list _ H0).\n  Qed.\n  \n  Lemma subexpression_list_destruct : forall e e' es, subexpression_list e (e' :: es) -> \n    (subexpression e e') \\/ (subexpression_list e es).\n    clear; intros; inversion H; subst; eapply FJ_subexpression_list_destruct; eassumption.\n  Qed.\n\n  Lemma FJ_Cast_discriminate : forall (e : FJ_E _ _ _ _ ty_ext E m_call_ext)\n    (S : cFJ.FJ_Ty _ ty_ext) (e' : E), cFJ_E e <> Cast_E (cast _ ty_ext E S e').\n    congruence.\n  Qed.\n  \n  Lemma Cast_subexp_invert : forall (e : E) S e',\n    subexpression e (Cast_E (cast _ _ _ S e')) -> \n    Cast_subexpression _ _ _ Cast_E subexpression e (Cast_E (cast _ _ _ S e')) \\/ e = Cast_E (cast _ _ _ S e').\n    clear; intros; inversion H; subst; auto; inversion H0; tauto.\n  Qed.\n\n  Fixpoint progress_1 gamma e T (WF_e : E_WF gamma e T) :\n    progress_1_P gamma e T WF_e :=\n    match WF_e with \n      | FJ_E_WF gamma e ty FJ_case => cFJ.progress_1 _ _ _ _ _ _ _ _ _ cFJ_E _ _ subtype\n        WF_Type fields mtype E_WF lookup Bound Bound WF_mtype_Us_map\n        WF_mtype_U_map WF_mtype_ext Empty FJ_E_WF FJ_E_WF_invert EWrap_inject\n        WF_fields_map_id (fun g tye c ty' Bnd => WF_fields_map_id' g _ _ Bnd tye c (refl_equal _))\n        subexpression subexpression_list \n        subexp_invert subexpression_list_nil subexpression_list_destruct gamma e ty FJ_case progress_1\n      | Cast_E_WF gamma e ty Cast_case => Cast_progress_1 _ _ _ _\n        _ _ Cast_E E_WF Bound subtype Cast_E_WF _ _ _ _ cFJ_E Empty Cast_E_inject fields \n        subexpression Cast_subexp_invert FJ_Cast_discriminate gamma e ty Cast_case progress_1\n    end.\n  \n  Definition progress_2_P := cFJ.progress_2_P _ _ _ _ _ _ \n    (Generic.FJ_Ty_Wrap Ty ty_ext nat N N_Wrap cFJ_N) _ _ cFJ_E _ _ CT _ \n    mbody_build_te mb_ext build_mb_ext map_mbody E_WF Empty subexpression.\n  \n  Definition progress_2_list_P := cFJ.progress_2_list_P _ _ _ _ _ _ \n    (Generic.FJ_Ty_Wrap Ty ty_ext nat N N_Wrap cFJ_N) _ _ cFJ_E _ _ \n    CT _ mbody_build_te mb_ext build_mb_ext map_mbody E_WF Empty \n    subexpression_list.\n  \n  Definition WF_mtype_ty_0_map_Empty_refl := FJ_WF_mtype_ty_0_map_Empty_refl _ _ _ \n    (Generic.FJ_Ty_Wrap Ty ty_ext nat N N_Wrap cFJ_N) Context.\n  \n  Definition build_mb_ext_tot := Generic.build_mb_ext_tot _ _ Gty N Ty_trans _ build_fresh _ _ _ _ _ \n    (fun (ice : I_cld_ext) => FJ_build_mb_ext (snd ice))\n    (fun (ice : I_cld_ext) te ty vds mce tys tys' => FJ_mtype_build_tys nat _ (snd ice) te ty vds mce tys tys')\n    (fun ice => FJ_build_mb_ext_tot nat Ty (snd ice)).\n\n  Definition mbody_m_call_map_tot := GJ_mbody_m_call_map_tot _ _ N Ty_trans FJ_m_call_ext.\n    \n  Definition mbody_new_map_tot := GJ_mbody_new_map_tot _ _ N Ty_trans FJ_ty_ext.\n\n  Fixpoint E_Ty_trans_tot (e : E) :=\n    match e return E_Ty_Trans_tot_P _ _ _ _ E_Ty_Trans e with\n      | cFJ_E e' => FJ_E_Ty_Trans_tot _ _ _ _ _ _ _ _ _ _ cFJ_E mbody_m_call_map mbody_new_map\n        E_Ty_Trans Base_E_Ty_Trans mbody_m_call_map_tot mbody_new_map_tot E_Ty_trans_tot e'\n      | Cast_E e' => Cast_E_Ty_Trans_tot _ _ _ _ _ _ Cast_E TE_trans _ Cast_E_Ty_Trans E_Ty_trans_tot e'\n    end.\n\n  Definition map_mbody_tot := Generic.map_mbody_tot _ _ Gty _ Ty_trans _ build_fresh _ _ FJ_m_call_ext _ _ _ \n    (fun (ice : I_cld_ext) te ty vds mce tys tys' => FJ_mtype_build_tys nat _ (snd ice) te ty vds mce tys tys')\n    E_Ty_trans_tot.\n  \n  Definition mtype_mbody_build_te := mtype_mbody_build_te _ _ _ N Ty_trans I_cld_ext \n    (fun (ice : I_cld_ext) te te' te'' => FJ_mtype_build_te (snd ice) te te' te'') _ \n    (fun ice => FJ_mtype_mbody_build_te (snd ice)).\n\n  Fixpoint mtype_implies_mbody gamma m ty mty (mtype_m : mtype gamma m ty mty) :=\n    match mtype_m with \n      | FJ_mtype gamma' m' ty' mty' fj_mtype_m => \n        FJ_mtype_implies_mbody _ _ _ _ _ _ _\n        _ _ _ _ _ CT _ mtype mtype_build_te mtype_build_tys mtype_build_mtye\n        FJ_mtype mbody_build_te mb_ext build_mb_ext map_mbody\n        Empty cFJ_inject mtype_build_tys_len' map_mbody_tot\n        mtype_mbody_build_te build_mb_ext_tot gamma' m' ty' mty' fj_mtype_m mtype_implies_mbody\n      | I_mtype_Wrap gamma' m' ty' mty' i_mtype_m' => I_mtype_implies_mbody _ _ _ I_Ty_Wrap\n        _ _ _ _ _ IT imtype_build_tys imtype_build_mtye mtype I_mtype_Wrap _ _ _ _ _ CT\n        (Generic.FJ_Ty_Wrap Ty ty_ext nat N N_Wrap cFJ_N) \n        Empty Ty_discriminate m_call_ext mbody_build_te mb_ext \n        (fun ty mce ty' mde mbe => True) map_mbody gamma' m' ty' mty' i_mtype_m'\n    end.\n    \n  Fixpoint progress_2 gamma e T (WF_e : E_WF gamma e T) :\n    progress_2_P gamma e T WF_e :=\n    match WF_e with \n      | FJ_E_WF gamma e ty FJ_case => FJ_progress_2 _ _ _ _ _ _ _ _ _ cFJ_E \n        _ _ _ CT _ subtype WF_Type fields mtype mbody_build_te mb_ext\n        build_mb_ext map_mbody E_WF lookup Bound Bound\n        WF_mtype_Us_map WF_mtype_U_map WF_mtype_ext Empty FJ_E_WF FJ_E_WF_invert\n        EWrap_inject WF_mtype_Us_map_len' subexpression subexpression_list\n        subexp_invert subexpression_list_nil subexpression_list_destruct\n        (WF_mtype_ty_0_map_Empty_refl' _ _ _ _ _ _ _ Bound N_Bound'_invert) \n        mtype_implies_mbody gamma e ty FJ_case progress_2\n      | Cast_E_WF gamma e ty Cast_case => Cast_progress_2 _ _ _ _\n        _ _ Cast_E E_WF Bound subtype Cast_E_WF _ _ _ _ _ _ cFJ_E CT Empty Cast_E_inject  \n        subexpression mbody_build_te mb_ext (fun ce te mce mde mbe => True) map_mbody\n        Cast_subexp_invert FJ_Cast_discriminate gamma e ty Cast_case progress_2\n  end.\n\nEnd Preservation.\n", "meta": {"author": "shrouxm", "repo": "sca-proof", "sha": "40b66d53d269f32b8d7515d7ba0784574c3acaa1", "save_path": "github-repos/coq/shrouxm-sca-proof", "path": "github-repos/coq/shrouxm-sca-proof/sca-proof-40b66d53d269f32b8d7515d7ba0784574c3acaa1/PLoTs/FiGJ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.27803507475977385}}
{"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 Process.\n\n\n(* Pair of states *)\nInductive pstate SX SY :=\n| pstate_two (l : SX) (r : SY)\n| pstate_left (l : SX)\n| pstate_right (r : SY).\nArguments pstate_two [SX] [SY] _ _.\nArguments pstate_left [SX] [SY] _.\nArguments pstate_right [SX] [SY] _.\n\nDefinition opt_states2pstate\n           {SX SY}\n           (sx : option SX)\n           (sy : option SY) : option (pstate SX SY) :=\n  match sx, sy with\n  | Some x, Some y => Some (pstate_two x y)\n  | Some x, None => Some (pstate_left x)\n  | None, Some y => Some (pstate_right y)\n  | None, None => None\n  end.\n", "meta": {"author": "vrahli", "repo": "Velisarios", "sha": "6fb353b18610cd79210755fcc90123536c367aaa", "save_path": "github-repos/coq/vrahli-Velisarios", "path": "github-repos/coq/vrahli-Velisarios/Velisarios-6fb353b18610cd79210755fcc90123536c367aaa/components/PairState.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.2779950353112608}}
{"text": "(* -*- company-coq-local-symbols: ((\"|=\" . ?⊨) (\"=|\" . ?⫤) (\"->>\" . ?↠) (\"=~\" . ?≈) (\"<|\" . ?⟨) (\"|>\" . ?⟩) ); -*- *)\nSet Warnings \"-notation-overridden\".\n\nRequire Import Prelude.Prelude.\n\nRequire Import Coq.FSets.FSetProperties.\n\nRequire Import Defs.Env.\nRequire Import Defs.List.\nRequire Import Defs.Obj.\nRequire Import Defs.Set.\n\n(*** Notation, tactics etc*)\nTheorem FrA_app_split : forall (a1 a2 : A) (env : Env),\n    FrA (a2 ++ a1) env\n  <-> (FrA a2 (env ::a a1) /\\ FrA a1 env).\nProof.\n  introv. split; induction a2; rewr. 1,3:crush.\n  - split; inverts H. 2:{ apply IHa2. assumption. }\n    constructor. crush. rewr*. intros. apply FR. fsetdec.\n  - intros. destr. inverts H. destr. constructor. eauto.\n    rewr*. intros. apply FR. fsetdec.\nQed.\n\nLtac inv_FrA_ :=\n  let H := fresh \"H\" in\n  let FR1 := fresh \"FR\" in\n  let FR2 := fresh \"FR\" in\n  match goal with\n    | [ H  : FrA nil _ |- _ ] => clear H\n    | [ H  : FrA (cons _ _) _ |- _ ] => inverts H\n    | [ H  : FrA ([_]) _ |- _ ] => inverts H\n    (* | [ H  : FrA (?a2 ++ ?a1) ?env |- _ ] => assert (H' := H); apply FrA_app_split in H'; destruct H' as [FR1 FR2] *)\n    | [ H  : FrA (?a2 ++ ?a1) ?env |- _ ] => apply FrA_app_split in H; destruct H as [FR1 FR2]\n  end.\nLtac inv_FrA := repeat inv_FrA_.\n\n(*** Inversion *)\nTheorem FrA_inv : forall (exA : var) (a : A) (env : Env),\n    FrA (exA :: a) env\n  -> FrA a env\n  /\\ exA \\notin Env_Obj_exvars (env ::a a).\nProof. inversion 1. jauto. Qed.\nCorollary FrA_inv__proj1 : forall (exA : var) (a : A) (env : Env),\n    FrA (exA :: a) env\n  -> FrA        a  env.\nProof. apply FrA_inv. Qed.\nCorollary FrA_inv__proj2 : forall (exA : var) (a : A) (env : Env),\n    FrA (exA :: a) env\n  -> exA \\notin Env_Obj_exvars (env ::a a).\nProof. apply FrA_inv. Qed.\n#[export] Hint Resolve FrA_inv__proj1 FrA_inv__proj2 : core.\n\nLtac indestr := rewr*; autorewrite with in_disj in *; destr.\nTactic Notation \"indestr\" \"in\" hyp(H) := rewr in H; autorewrite with in_disj in H.\n\nTheorem FrA_in_inv : forall (exA : var) (a : A) (env : Env),\n    FrA a env\n  -> exA \\in varl a\n  -> exA \\notin Env_Obj_exvars env.\nProof.\n  induction a. crush. intros. indestr. eauto. rewr*. subst.\n  forwards: FrA_inv__proj2. eassumption. unfold not in *. crush.\nQed.\n\n(* (*** Things for in list *) *)\n(* #[export] Hint Constructors NoDup'. *)\n\n(* Theorem list_to_varl : forall (exA : exvar) (a : A), *)\n(*     In exA a <-> exA \\in varl a. *)\n(* Proof. *)\n(*   intros. induction a. crush. *)\n(*   destruct (a == exA). *)\n(*   - crush. *)\n(*   - crush. right. apply H0. fsetdec. *)\n(* Qed. *)\n(* Corollary list_to_varl1 : forall (exA : exvar) (a : A), *)\n(*     In exA a -> exA \\in varl a. *)\n(* Proof. apply list_to_varl. Qed. *)\n(* Corollary list_to_varl2 : forall (exA : exvar) (a : A), *)\n(*     exA \\in varl a -> In exA a. *)\n(* Proof. apply list_to_varl. Qed. *)\n(* #[export] Hint Resolve list_to_varl1 list_to_varl2 : core. *)\n\n(* Theorem incl_list_sub : forall (a1 a2 : A), *)\n(*     incl a1 a2 *)\n(*   -> a1 [<=]l a2. *)\n(* Proof. intros. autounfold. unfold AtomSetImpl.Subset. crush. Qed. *)\n(* #[export] Hint Resolve incl_list_sub : core. *)\n\n(* Lemma Nodup_incl: forall (a1 a2 : A) (env1 : Env), *)\n(*     NoDup' a1 *)\n(*   -> incl a2 a1 *)\n(*   -> NoDup' a2. *)\n(* OK this doesn't work we need proper sublists *)\n\n(*** For in Env *)\n(* Lemma Env_sub__proj1 : forall (env1 env2 : Env), *)\n(*     env1 [<=]e env2 *)\n(*   -> Env_skvars env1 [<=] Env_skvars env2. *)\n(* Proof. autounfold. intros. jauto. Qed. *)\n(* #[export] Hint Resolve Env_sub__proj1 : core. *)\n(* Lemma Env_sub__proj2 : forall (env1 env2 : Env), *)\n(*     env1 [<=]e env2 *)\n(*   -> Env_exvars env1 [<=] Env_exvars env2. *)\n(* Proof. autounfold. intros. jauto. Qed. *)\n(* #[export] Hint Resolve Env_sub__proj2 : core. *)\n\n(* Lemma Env_eq_proj1 : forall (env1 env2 : Env), *)\n(*     env1 [=]e env2 *)\n(*   -> Env_skvars env1 [=] Env_skvars env2. *)\n(* Proof. autounfold. intros. jauto. Qed. *)\n(* #[export] Hint Resolve Env_eq_proj1 : core. *)\n(* Lemma Env_eq_proj2 : forall (env1 env2 : Env), *)\n(*     env1 [=]e env2 *)\n(*   -> Env_exvars env1 [=] Env_exvars env2. *)\n(* Proof. autounfold. intros. jauto. Qed. *)\n(* #[export] Hint Resolve Env_eq_proj2 : core. *)\n\n(* Lemma Env_fr_sub_proj1 : forall (env1 env2 : Env), *)\n(*     env1 [<=]e# env2 *)\n(*   -> Env_skvars env1 [<=] Env_skvars env2. *)\n(* Proof. autounfold. intros. jauto. Qed. *)\n(* #[export] Hint Resolve Env_fr_sub_proj1 : core. *)\n(* Lemma Env_fr_sub_proj2 : forall (env1 env2 : Env), *)\n(*     env1 [<=]e# env2 *)\n(*   -> Env_Obj_exvars env1 [<=] Env_Obj_exvars env2. *)\n(* Proof. autounfold. intros. jauto. Qed. *)\n(* #[export] Hint Resolve Env_fr_sub_proj2 : core. *)\n\n(* Lemma Env_fr_eq_proj1 : forall (env1 env2 : Env), *)\n(*     env1 [=]e# env2 *)\n(*   -> Env_skvars env1 [=] Env_skvars env2. *)\n(* Proof. autounfold. intros. jauto. Qed. *)\n(* #[export] Hint Resolve Env_fr_eq_proj1 : core. *)\n(* Lemma Env_fr_eq_proj2 : forall (env1 env2 : Env), *)\n(*     env1 [=]e# env2 *)\n(*   -> Env_Obj_exvars env1 [=] Env_Obj_exvars env2. *)\n(* Proof. autounfold. intros. jauto. Qed. *)\n(* #[export] Hint Resolve Env_fr_eq_proj2 : core. *)\n\n(*** Props *)\nTheorem FrA_props : forall (a : A) (env : Env),\n    FrA a env\n  <-> varl a [><] Env_Obj_exvars env\n  /\\ NoDup' a.\nProof.\n  intros. split.\n  - induction 1. crush. destr. split.\n    + rewr. apply disjoint_extend'. crush. eassumption.\n    + constructor. crush. assumption.\n  - intros [? ND]. induction ND. crush.\n    constructor. rewr in H.\n    apply IHND. assert (SUB: varl a [<=] varl a \\u singleton exA). fsetdec.\n    rewrite SUB. eassumption.\n    rewr. intros. indestr. eauto using in_disjoint_impl. crush.\nQed.\nCorollary FrA_props1 : forall (a : A) (env : Env),\n    FrA a env\n  -> varl a [><] Env_Obj_exvars env\n  /\\ NoDup' a.\nProof. apply FrA_props. Qed.\nCorollary FrA_props2 : forall (a : A) (env : Env),\n    varl a [><] Env_Obj_exvars env\n  -> NoDup' a\n  -> FrA a env.\nProof. intros. apply FrA_props. crush. Qed.\nCorollary FrA_props3 : forall (a : A) (env : Env),\n    FrA a env\n  -> varl a [><] Env_Obj_exvars env.\nProof. apply FrA_props. Qed.\nCorollary FrA_props4 : forall (a : A) (env : Env),\n    FrA a env\n  -> NoDup' a.\nProof. apply FrA_props. Qed.\n\n(*** Rewriting *)\nTheorem FrA_rewr : forall (a1 a2 : A) (env1 env2 : Env),\n    FrA a1 env1\n  -> a2 [<=]lu a1\n  -> env2 [<=]e# env1\n  -> FrA a2 env2.\nProof.\n  introv FRA SUB__l SUB__e. rewrite FrA_props in *.\n  split.\n  - applys disj_subset_proper. 3:jauto. crush. rewr. conv. unfold Env_fr_sub in SUB__e. jauto.\n  - jauto.\nQed.\n#[export] Hint Resolve FrA_rewr : core.\n\n#[export] Instance FrA_rewr_proper : Proper (flip list_uni_sub ==> flip Env_fr_sub ==> impl) FrA.\nProof. unfold Proper, respectful, impl, flip. intros. eauto. Qed.\n\nCorollary FrA_Env_sub : forall (env1 env2 : Env) (a : A),\n    FrA a env1\n  -> env2 [<=]e# env1\n  -> FrA a env2.\nProof. eauto. Qed.\nCorollary FrA_sublist : forall (a1 a2 : A) (env : Env),\n    FrA a1 env\n  -> a2 [<=]lu a1\n  -> FrA a2 env.\nProof. eauto. Qed.\n\n(*** Unsorted *)\nTheorem FrA_Obj : forall (env : Env) (a1 a2 : A) (sch : Sch),\n    FrA a2 (env ::o ⟦⟨a1⟩ sch⟧)\n  <-> FrA a2 (env ::a a1).\nProof. split; introv FR; eapply FrA_rewr; try apply FR; try reflexivity; eauto. rewr.\n       unfold Env_fr_sub. crush.\n       unfold Env_fr_sub. crush.\nQed.\n\nLemma FrA_cons_shift: forall (exA : exvar) (a : list exvar) (env : Env),\n    FrA (exA :: a) env\n  -> FrA a (env ::a [exA]).\nProof.\n  introv FR. listind a. crush. constructor. apply IHa.\n  constructor. eauto. inv_FrA. intros. apply FR0. rewr*. fsetdec.\n  inv_FrA. intros. indestr in H. destr. apply FR. rewr. fsetdec. rewr in H. crush. apply FR. rewr. fsetdec.\nQed.\n", "meta": {"author": "rogerbosman", "repo": "hdm-fully-grounding", "sha": "master", "save_path": "github-repos/coq/rogerbosman-hdm-fully-grounding", "path": "github-repos/coq/rogerbosman-hdm-fully-grounding/hdm-fully-grounding-main/coq/Defs/FrA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.2779950353112608}}
{"text": "(** * Definition of the string-like type *)\nRequire Coq.Lists.List.\nRequire Import Coq.Relations.Relation_Definitions (* for [relation] *).\nRequire Import Coq.Classes.Morphisms (* for [==>] / [respectful] *).\nRequire Export Fiat.Common.Coq__8_4__8_5__Compat.\n\nLocal Coercion is_true : bool >-> Sortclass.\n\nSet Implicit Arguments.\nGeneralizable All Variables.\n\n(** Something is string-like if it has a type of characters, and can\n    be split. *)\n\nReserved Notation \"[ x ]\".\n\nModule Export StringLike.\n  Class StringLikeMin {Char : Type} :=\n    {\n      String :> Type;\n      char_at_matches : nat -> String -> (Char -> bool) -> bool;\n      unsafe_get : nat -> String -> Char;\n      length : String -> nat\n    }.\n\n  Class StringLike {Char : Type} {HSLM : @StringLikeMin Char} :=\n    {\n      is_char : String -> Char -> bool;\n      take : nat -> String -> String;\n      drop : nat -> String -> String;\n      get : nat -> String -> option Char;\n      bool_eq : String -> String -> bool;\n      beq : relation String := fun x y => bool_eq x y\n    }.\n\n  Class StringIso {Char} {HSLM : @StringLikeMin Char} :=\n    {\n      of_string : list Char -> String\n    }.\n\n  Arguments StringLikeMin : clear implicits.\n  Arguments StringLike Char {HSLM}.\n  Arguments StringIso Char {HSLM}.\n  Bind Scope string_like_scope with String.\n  Delimit Scope string_like_scope with string_like.\n  Infix \"=s\" := (@beq _ _ _) (at level 70, no associativity) : type_scope.\n  Infix \"=s\" := (@bool_eq _ _ _) (at level 70, no associativity) : string_like_scope.\n  Notation \"s ~= [ ch ]\" := (is_char s ch) (at level 70, no associativity) : string_like_scope.\n  Local Open Scope string_like_scope.\n  Local Open Scope type_scope.\n\n  Definition fold' {Char} {HSLM} {HSL : @StringLike Char HSLM} {A}\n             (f : Char -> A -> A)\n             (init : A)\n             (str : String) (len : nat)\n  : A\n    := nat_rect\n         (fun _ => A)\n         init\n         (fun len' acc\n          => match get (length str - S len') str with\n               | Some ch => f ch acc\n               | None => init\n             end)\n         len.\n\n  Definition fold {Char} {HSLM} {HSL : @StringLike Char HSLM} {A}\n             (f : Char -> A -> A)\n             (init : A)\n             (str : String)\n  : A\n    := fold' f init str (length str).\n\n  Definition fold_lookahead' {Char} {HSLM} {HSL : @StringLike Char HSLM} {A}\n             (f : Char -> option Char -> A -> A)\n             (init : A)\n             (str : String) (len : nat)\n  : A\n    := nat_rect\n         (fun _ => A)\n         init\n         (fun len' acc\n          => match get (length str - S len') str with\n               | Some ch => f ch (get (length str - len') str) acc\n               | None => init\n             end)\n         len.\n\n  Definition fold_lookahead {Char} {HSLM} {HSL : @StringLike Char HSLM} {A}\n             (f : Char -> option Char -> A -> A)\n             (init : A)\n             (str : String)\n  : A\n    := fold_lookahead' f init str (length str).\n\n  Notation to_string str := (fold (@List.cons _) (@List.nil _) str).\n\n  Definition str_le `{@StringLike Char HSLM} (s1 s2 : String)\n    := length s1 < length s2 \\/ s1 =s s2.\n  Infix \"≤s\" := str_le (at level 70, right associativity).\n\n  Notation substring n m str := (take m (drop n str)).\n\n  Class StringLikeProperties (Char : Type) `{StringLike Char} :=\n    {\n      singleton_unique : forall s ch ch', s ~= [ ch ] -> s ~= [ ch' ] -> ch = ch';\n      singleton_exists : forall s, length s = 1 -> exists ch, s ~= [ ch ];\n      char_at_matches_correct : forall s n P ch, get n s = Some ch -> (char_at_matches n s P = P ch);\n      get_0 : forall s ch, take 1 s ~= [ ch ] <-> get 0 s = Some ch;\n      get_S : forall n s, get (S n) s = get n (drop 1 s);\n      unsafe_get_correct : forall n s ch, get n s = Some ch -> unsafe_get n s = ch;\n      length_singleton : forall s ch, s ~= [ ch ] -> length s = 1;\n      bool_eq_char : forall s s' ch, s ~= [ ch ] -> s' ~= [ ch ] -> s =s s';\n      is_char_Proper :> Proper (beq ==> eq ==> eq) is_char;\n      length_Proper :> Proper (beq ==> eq) length;\n      take_Proper :> Proper (eq ==> beq ==> beq) take;\n      drop_Proper :> Proper (eq ==> beq ==> beq) drop;\n      bool_eq_Equivalence :> Equivalence beq;\n      bool_eq_empty : forall str str', length str = 0 -> length str' = 0 -> str =s str';\n      take_short_length : forall str n, n <= length str -> length (take n str) = n;\n      take_long : forall str n, length str <= n -> take n str =s str;\n      take_take : forall str n m, take n (take m str) =s take (min n m) str;\n      drop_length : forall str n, length (drop n str) = length str - n;\n      drop_0 : forall str, drop 0 str =s str;\n      drop_drop : forall str n m, drop n (drop m str) =s drop (n + m) str;\n      drop_take : forall str n m, drop n (take m str) =s take (m - n) (drop n str);\n      take_drop : forall str n m, take n (drop m str) =s drop m (take (n + m) str);\n      bool_eq_from_get : forall str str', (forall n, get n str = get n str') -> str =s str'\n    }.\n\n  Class StringIsoProperties {Char} {HSLM} {HSL : @StringLike Char HSLM} {HSI : @StringIso Char HSLM} :=\n    {\n      get_of_string : forall n str, get n (of_string str) = List.nth_error str n\n    }.\n\n  Class StringEqProperties {Char} {HSLM} {HSL : @StringLike Char HSLM} :=\n    {\n      bool_eq_bl : forall s s', s =s s' -> s = s';\n      bool_eq_lb : forall s s', s = s' -> s =s s'\n    }.\n\n  Global Existing Instance Equivalence_Reflexive.\n  Global Existing Instance Equivalence_Symmetric.\n  Global Existing Instance Equivalence_Transitive.\n\n  Arguments StringLikeProperties Char {_ _}.\n  Arguments StringIsoProperties Char {_ _ _}.\n  Arguments StringEqProperties Char {_ _}.\nEnd StringLike.\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/StringLike/Core.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213070736461, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.2779950350531513}}
{"text": "(*\nCopyright 2013 IMDEA Software Institute\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n    http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*)\n\n(******************************************************************************)\n(* This file contains axioms that are used in some parts of the library.      *)\n(* The selected set of axioms is known to be consistent with Coq's logic.     *)\n(* These axioms are:                                                          *)\n(*   - propositional extensionality (pext);                                   *)\n(*   - functional extensionality (fext).                                      *)\n(* This file also defines the dynamic type as an alias for sigT and           *)\n(* Jonh Major equality via equality cast.                                     *)\n(******************************************************************************)\n\nFrom Coq Require Import ssreflect ssrfun Eqdep ClassicalFacts.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n  \n(*****************************)\n(* Axioms and extensionality *)\n(*****************************)\n\n(* extensionality is needed for domains *)\nAxiom pext : forall p1 p2 : Prop, (p1 <-> p2) -> p1 = p2.\nAxiom fext : forall A (B : A -> Type) (f1 f2 : forall x, B x), \n               (forall x, f1 x = f2 x) -> f1 = f2.\n\nLemma pf_irr (P : Prop) (p1 p2 : P) : p1 = p2.\nProof. by apply/ext_prop_dep_proof_irrel_cic/pext. Qed.\n\nLemma eta A (B : A -> Type) (f : forall x, B x) : f = [eta f].\nProof. by apply: fext. Qed.   \n\nLemma sval_inj A P : injective (@sval A P).\nProof.\nmove=>[x Hx][y Hy] /= H; move: Hx Hy; rewrite H=>*. \ncongr exist; apply: pf_irr.\nQed.\n\nLemma svalE A (P : A -> Prop) x H : sval (exist P x H) = x.\nProof. by []. Qed.\n\nLemma compf1 A B (f : A -> B) : f = f \\o id.\nProof. by apply: fext. Qed.\n\nLemma comp1f A B (f : A -> B) : f = id \\o f.\nProof. by apply: fext. Qed.\n\n(*****************************************)\n(* Cast and John Major Equality via cast *)\n(*****************************************)\n\nSection Cast.\nVariable (C : Type) (interp : C -> Type).\n\nDefinition cast A B (pf : A = B) (v : interp B) : interp A :=\n  ecast _ _ (esym pf) v.\n\nLemma eqc A (pf : A = A) (v : interp A) : cast pf v = v.\nProof. by move: pf; apply: Streicher_K. Qed.\n\nDefinition jmeq A B (v : interp A) (w : interp B) := forall pf, v = cast pf w.\n\nLemma jmrefl A (v : interp A) : jmeq v v.\nProof. by move=>pf; rewrite eqc. Qed.\n\nLemma jmsym A B (v : interp A) (w : interp B) : jmeq v w -> jmeq w v.\nProof.\nmove=> H pf; rewrite (H (esym pf)).\nby move: (pf); rewrite pf in w H * => {pf} pf; rewrite !eqc.\nQed.\n\nLemma jmE A (v w : interp A) : jmeq v w <-> v = w.\nProof. by split=>[/(_ erefl) //|->]; apply: jmrefl. Qed.\n\nLemma castE A B (pf1 pf2 : A = B) (v1 v2 : interp B) :\n        v1 = v2 <-> cast pf1 v1 = cast pf2 v2.\nProof. by move: (pf1) pf2; rewrite pf1 =>*; rewrite !eqc. Qed.\n\nEnd Cast.\n\nArguments cast {C} interp [A][B] pf v.\nArguments jmeq {C} interp [A][B] v w.\nHint Resolve jmrefl : core.\n(* special notation for the common case when interp = id *)\nNotation icast pf v := (@cast _ id _ _ pf v).\nNotation ijmeq v w := (@jmeq _ id _ _ v w).\n\n(* type dynamic is sigT *)\n\nSection Dynamic.\nVariables (A : Type) (P : A -> Type).\n\n(** eta expand definitions to prevent universe inconsistencies when using\n    the injectivity of constructors of datatypes depending on [[dynamic]] *)\n\nDefinition dynamic := sigT P.\nDefinition dyn := existT P.\nDefinition dyn_tp := @projT1 _ P.\nDefinition dyn_val := @projT2 _ P.\nDefinition dyn_eta := @sigT_eta _ P.\nDefinition dyn_injT := @eq_sigT_fst _ P.\nDefinition dyn_inj := @inj_pair2 _ P.\n\nEnd Dynamic.\n\nPrenex Implicits dyn_tp dyn_val dyn_injT dyn_inj.\nArguments dyn {C} interp {A} _ : rename.\nNotation idyn v := (@dyn _ id _ v).\n\nLemma dynE (A B : Type) interp (pf : A = B) (v : interp A) (w : interp B) :\n        jmeq interp v w <-> dyn interp v = dyn interp w.\nProof. by rewrite -pf in w *; rewrite jmE; split => [->|/dyn_inj]. 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/fcsl-pcm/pcm/axioms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.27791048282710323}}
{"text": "Require Import Bag.\nRequire Import WellFormed.\n\nRequire Import Proofs.GHC.Base.\nRequire Import Proofs.GHC.List.\nRequire Import Proofs.Data.Foldable.\nRequire Import Proofs.Data.OldList.\n\nRequire Import Coq.Lists.List.\nImport ListNotations.\nRequire Import ListUtils.\nRequire Import Coq.ZArith.ZArith.\n\nRequire Data.Traversable.\nImport GHC.Base.\nImport Data.Functor.\n\nRequire Import Coq.Setoids.Setoid.\nRequire Import Coq.Classes.Morphisms.\n\nRequire Import Coq.Logic.FunctionalExtensionality.\n\nRequire Import Correctness.\n\nFrom Coq Require Import ssreflect ssrfun ssrbool.\nSet Bullet Behavior \"Strict Subproofs\".\n\n(***** Operators *****)\n\nInfix \"<$>\" := Data.Functor.op_zlzdzg__ : hs_op_scope.\nInfix \"<*>\" := GHC.Base.op_zlztzg__ : hs_op_scope.\nInfix \">>=\" := GHC.Base.op_zgzgze__ : hs_op_scope.\nInfix \">>\" := GHC.Base.op_zgzg__ : hs_op_scope.\nOpen Scope hs_op_scope.\n\n(***** Working with extensionality *****)\n\n(* Like the \"extensionality\" tactic, but doesn't intro -- nicer with ssreflect *)\nLtac funext :=\n  match goal with\n    [ |- ?X = ?Y ] =>\n    (apply (@functional_extensionality _ _ X Y) ||\n     apply (@functional_extensionality_dep _ _ X Y) ||\n     apply forall_extensionalityP ||\n     apply forall_extensionalityS ||\n     apply forall_extensionality)\n  end.\n\n(* From https://stackoverflow.com/a/43853467/237428 *)\nInstance pointwise_eq_ext {A B : Type} {RB : relation B} `(sb : subrelation B RB eq)\n  : subrelation (pointwise_relation A RB) eq.\nProof. intros f g Hfg. apply functional_extensionality. intro x; apply sb, (Hfg x). Qed.\n\n(***** Bag correctness theorems *****)\n\nTheorem mapBagM_ok {M A B} `{MonadLaws M} (f : A -> M B) (b : Bag A) :\n  GHC.Base.fmap bagToList (mapBagM f b) = Data.Traversable.mapM f (bagToList b).\nProof.\n  rewrite /Data.Traversable.mapM /Traversable.Traversable__list /Data.Traversable.mapM__\n          /=\n          /Data.Traversable.Traversable__list_mapM\n          /Data.Traversable.Traversable__list_traverse.\n  replace (fmap bagToList (mapBagM f b)) with\n          (_++_ <$> (fmap bagToList (mapBagM f b)) <*> pure [])\n          by by unfold \"<$>\";\n                rewrite functor_composition !applicative_fmap applicative_interchange\n                        -applicative_composition !applicative_homomorphism;\n                do 2 f_equal; funext=> ?; unfold \"∘\"; rewrite app_nil_r.\n  generalize (pure ([] : list B)) => z.\n  elim: b z => [| x | l IHl r IHr | xs] z //=.\n  - rewrite applicative_fmap -monad_applicative_pure applicative_homomorphism.\n    unfold \"<$>\"; rewrite applicative_fmap applicative_homomorphism.\n    replace [eta app _] with (@GHC.Base.id (list B)) by by funext.\n    apply applicative_identity.\n  - unfold \"<$>\"; rewrite\n      applicative_liftA2 !applicative_fmap !monad_applicative_ap /ap !monad_applicative_pure !monad_left_id\n      -!monad_composition.\n    by f_equal; funext => ?; rewrite !monad_left_id.\n  - rewrite bagToList_TwoBags hs_coq_foldr_base fold_right_app -!hs_coq_foldr_base.\n    rewrite -IHr -IHl.\n    unfold \"<$>\"; rewrite\n      !functor_composition !applicative_fmap\n      !monad_applicative_ap /ap !monad_applicative_pure !monad_left_id -!monad_composition.\n    f_equal; funext=> ?.\n    rewrite !monad_left_id -!monad_composition.\n    f_equal; funext=> ?.\n    rewrite !monad_left_id -!monad_composition.\n    f_equal; funext=> ?.\n    rewrite monad_left_id.\n    f_equal.\n    by unfold \"∘\"; rewrite /= bagToList_TwoBags app_assoc.\n  - rewrite bagToList_ListBag\n            /Data.Traversable.mapM /Traversable.Traversable__list /Data.Traversable.mapM__\n            /Data.Traversable.Traversable__list_mapM\n            /Data.Traversable.Traversable__list_traverse.\n    unfold \"<$>\"; rewrite\n      functor_composition applicative_fmap\n      !monad_applicative_ap /ap monad_applicative_pure monad_left_id.\n    rewrite -!monad_composition.\n    elim: xs z => [|x xs IH] z /=.\n    + rewrite monad_applicative_pure !monad_left_id.\n      replace (fun _ : list B => return_ _) with (return_ : list B -> M (list B));\n        first by apply monad_right_id.\n      by funext.\n    + rewrite -(IH z).\n      rewrite !applicative_liftA2 !applicative_fmap !monad_applicative_ap /ap monad_applicative_pure\n              !monad_left_id -!monad_composition.\n      f_equal; funext=> ?.\n      rewrite !monad_left_id -!monad_composition.\n      f_equal; funext=> ?.\n      rewrite -!monad_composition !monad_left_id -!monad_composition.\n      f_equal; funext=> ?.\n      by rewrite !monad_left_id.\nQed.\n\nTheorem foldr_app {A B} (f : A -> B -> B) (z : B) (xs ys : list A) :\n  foldr f z (xs ++ ys) = foldr f (foldr f z ys) xs.\nProof. by rewrite hs_coq_foldr_base fold_right_app -!hs_coq_foldr_base. Qed.\n\nLemma monad_bind_return_fmap {M A B} `{MonadLaws M} (f : A -> B) (mx : M A) :\n  (mx >>= fun x : A => return_ (f x)) = (f <$> mx).\nProof.\n  by unfold \"<$>\"; rewrite applicative_fmap monad_applicative_ap monad_applicative_pure /ap\n                           monad_left_id.\nQed.\n\nLemma monad_bind_return_fmap2 {M A B C} `{MonadLaws M} (f : A -> B -> C) (mx : M A) (my : M B) :\n  (mx >>= fun x => (my >>= fun y => return_ (f x y))) = (f <$> mx <*> my).\nProof.\n  unfold \"<$>\".\n  rewrite applicative_fmap !monad_applicative_ap monad_applicative_pure /ap.\n  rewrite monad_left_id -monad_composition.\n  f_equal; funext; intros.\n  rewrite monad_left_id.\n  reflexivity.\nQed.\n\nLemma monad_bind_fmap_ap {M A B C} `{MonadLaws M} (f : A -> B -> C) (mx : M A) (my : M B) :\n  (mx >>= fun x : A => fmap (f x) my) = (f <$> mx <*> my).\nProof.\n  unfold \"<$>\";\n    setoid_rewrite ->applicative_fmap;\n    repeat setoid_rewrite ->monad_applicative_ap;\n    setoid_rewrite ->monad_applicative_pure;\n    unfold ap.\n  by rewrite -!monad_composition monad_left_id -!monad_composition.\nQed.\n\nLemma applicative_fmap_pure {F A B} `{ApplicativeLaws F} (f : A -> B) (x : A) :\n  fmap f (pure x) = pure (f x) :> F B.\nProof. by rewrite applicative_fmap applicative_homomorphism. Qed.\n\nLemma monad_fmap_return {M A B} `{MonadLaws M} (f : A -> B) (x : A) :\n  fmap f (return_ x) = return_ (f x) :> M B.\nProof. by rewrite -!monad_applicative_pure applicative_fmap_pure. Qed.\n\nTheorem mapBagM_ok' {M A B} `{MonadLaws M} (f : A -> M B) (b : Bag A) :\n  GHC.Base.fmap bagToList (mapBagM f b) = Data.Traversable.mapM f (bagToList b).\nProof.\n  rewrite /Data.Traversable.mapM /Traversable.Traversable__list /Data.Traversable.mapM__ /=\n          /Data.Traversable.Traversable__list_mapM\n          /Data.Traversable.Traversable__list_traverse.\n  replace (fmap bagToList (mapBagM f b)) with\n          (_++_ <$> (fmap bagToList (mapBagM f b)) <*> pure [])\n          by by unfold \"<$>\";\n                rewrite functor_composition !applicative_fmap applicative_interchange\n                        -applicative_composition !applicative_homomorphism;\n                do 2 f_equal; funext=> ?; unfold \"∘\"; rewrite app_nil_r.\n  generalize (pure ([] : list B)) => z.\n  elim: b z => [| x | l IHl r IHr | xs] z //=.\n  - by unfold \"<$>\";\n       rewrite functor_composition monad_fmap_return -monad_applicative_pure\n               applicative_identity.\n  - by rewrite applicative_liftA2 monad_bind_return_fmap; unfold \"<$>\"; rewrite !functor_composition.\n  - setoid_rewrite ->monad_bind_return_fmap; setoid_rewrite ->monad_bind_fmap_ap.\n    rewrite bagToList_TwoBags foldr_app -IHl -IHr.\n    unfold \"<$>\"; rewrite !functor_composition.\n    rewrite !applicative_fmap -!applicative_composition !applicative_homomorphism; f_equal.\n    rewrite !applicative_interchange -!applicative_fmap functor_composition; do 2 f_equal.\n    funext=> l'; funext=> r'; funext=> z'.\n    by unfold \"∘\"; rewrite bagToList_TwoBags app_assoc.\n  - rewrite bagToList_ListBag\n            /Data.Traversable.mapM /Traversable.Traversable__list /Data.Traversable.mapM__\n            /Data.Traversable.Traversable__list_mapM\n            /Data.Traversable.Traversable__list_traverse.\n    rewrite monad_bind_return_fmap; unfold \"<$>\"; rewrite !functor_composition.\n    elim: xs => [|x xs IH] /=.\n    + by rewrite applicative_fmap_pure applicative_identity.\n    + rewrite -IH.\n      rewrite !applicative_liftA2 !applicative_fmap -!applicative_composition !applicative_homomorphism.\n      by rewrite applicative_interchange -applicative_composition !applicative_homomorphism.\nQed.\n\nLtac applicative_normalize :=\n  simpl;\n  unfold \"<$>\"; rewrite ?applicative_liftA2 ?applicative_fmap -?monad_applicative_pure;\n  repeat (rewrite applicative_identity     ||\n          rewrite applicative_homomorphism ||\n          rewrite applicative_interchange  ||\n          rewrite -applicative_composition).\n\nLtac applicative_equal :=\n  match goal with\n    | |- (pure _    = pure _)    => f_equal\n    | |- ((_ <*> _) = (_ <*> _)) => progress f_equal; applicative_equal\n    | |- (_ = _)                 => idtac\n  end.\n\nLtac applicative_normalize_equal :=\n  applicative_normalize=> //; applicative_equal=> //; repeat funext=> ? //.\n\nLtac anf       := applicative_normalize.\nLtac anf_equal := applicative_normalize_equal.\n\nTheorem mapBagM_ok'' {M A B} `{MonadLaws M} (f : A -> M B) (b : Bag A) :\n  GHC.Base.fmap bagToList (mapBagM f b) = Data.Traversable.mapM f (bagToList b).\nProof.\n  rewrite /Data.Traversable.mapM /Data.Traversable.mapM /Traversable.Traversable__list /Data.Traversable.mapM__ /=\n          /Data.Traversable.Traversable__list_mapM\n          /Data.Traversable.Traversable__list_traverse.\n  replace (fmap bagToList (mapBagM f b)) with\n          (_++_ <$> (fmap bagToList (mapBagM f b)) <*> pure [])\n          by by anf_equal; unfold \"∘\"; rewrite app_nil_r.\n  generalize (pure ([] : list B)) => z.\n  elim: b z => [| x | l IHl r IHr | xs] z //=.\n  - anf_equal.\n  - rewrite applicative_liftA2 monad_bind_return_fmap; anf_equal.\n  - rewrite bagToList_TwoBags foldr_app -IHl -IHr.\n    setoid_rewrite ->monad_bind_return_fmap; setoid_rewrite ->monad_bind_fmap_ap.\n    by anf_equal; unfold \"∘\"; rewrite bagToList_TwoBags app_assoc.\n  - rewrite bagToList_ListBag\n            /Data.Traversable.mapM /Data.Traversable.mapM /Traversable.Traversable__list /Data.Traversable.mapM__\n            /Data.Traversable.Traversable__list_mapM\n            /Data.Traversable.Traversable__list_traverse.\n    rewrite monad_bind_return_fmap; anf.\n    elim: xs => [|x xs /= <-];  anf_equal.\nQed.\n\n  (* I forget what I was trying to do with this. —ASZ *)\nTheorem mapBagM_ok''' {M A B} `{MonadLaws M} (f : A -> M B) (b : Bag A) :\n  GHC.Base.fmap bagToList (mapBagM f b) = Data.Traversable.traverse f (bagToList b).\nProof.\n(*\n  rewrite /Data.Traversable.traverse /Traversable.Traversable__list /Data.Traversable.traverse__\n         /= /Data.Traversable.Traversable__list_traverse.\n  replace (fmap bagToList (mapBagM f b)) with\n          (_++_ <$> (fmap bagToList (mapBagM f b)) <*> pure [])\n          by by unfold \"<$>\";\n                rewrite functor_composition !applicative_fmap applicative_interchange\n                        -applicative_composition !applicative_homomorphism;\n                do 2 f_equal; funext=> ?; unfold \"∘\"; rewrite app_nil_r.\n  generalize (pure ([] : list B)) => z.\n  elim: b z => [| x | l IHl r IHr | xs] z //=.\n  - rewrite applicative_fmap -monad_applicative_pure applicative_homomorphism.\n    unfold \"<$>\"; rewrite applicative_fmap applicative_homomorphism.\n    replace [eta app _] with (@GHC.Base.id (list B)) by by funext.\n    apply applicative_identity.\n  - unfold \"<$>\". rewrite\n      !applicative_fmap !monad_applicative_ap /ap !monad_applicative_pure.\n *)\nAbort.\n\nLemma mapM_nil {M A B} `{MonadLaws M} (f : A -> M B):\n  Traversable.mapM f [] = pure [].\nProof.\n  by rewrite /Traversable.mapM /Traversable.Traversable__list /Traversable.mapM__.\nQed.\n\nLemma mapM_cons {M A B} `{MonadLaws M} (f : A -> M B) x xs:\n  Traversable.mapM f (x::xs) = ((cons <$> f x) <*> Traversable.mapM f xs).\nProof.\n  rewrite /Traversable.mapM /Traversable.Traversable__list /Traversable.mapM__.\n  simpl.\n  rewrite applicative_liftA2.\n  reflexivity.\nQed.\n\nLemma mapM_app {M A B} `{MonadLaws M} (f : A -> M B) l1 l2:\n  Traversable.mapM f (l1 ++ l2) = (app <$> Traversable.mapM f l1 <*> Traversable.mapM f l2).\nProof.\n  intros. induction l1.\n  * rewrite /Traversable.mapM /Traversable.Traversable__list /Traversable.mapM__.\n    anf. reflexivity.\n  * rewrite /= !mapM_cons IHl1.\n    anf. reflexivity.\nQed.\n\nLemma monad_fmap_bind1 {M A B C} `{MonadLaws M} (f : B -> C) (a : M A) k:\n  fmap f (a >>= k) = (a >>= (fun x => fmap f (k x))).\nProof.\n  (* Get LHS into monad-only land *)\n  rewrite !applicative_fmap !monad_applicative_ap /ap monad_applicative_pure.\n  (* Clean up a bit *)\n  rewrite monad_left_id -monad_composition.\n  f_equal; funext; intros.\n  (* Get RHS into monad-only land *)\n  rewrite !applicative_fmap !monad_applicative_ap /ap monad_applicative_pure.\n  rewrite monad_left_id.\n  reflexivity.\nQed.\n\nLemma monad_fmap_bind2 {M A B C} `{MonadLaws M} (f : A -> B) (a : M A) (k : B -> M C):\n  (fmap f a >>= k) = (a >>= (fun x => k (f x))).\nProof.\n  (* Get LHS into monad-only land *)\n  rewrite !applicative_fmap !monad_applicative_ap /ap monad_applicative_pure.\n  (* Clean up a bit *)\n  rewrite monad_left_id -monad_composition.\n  f_equal; funext; intros.\n  rewrite monad_left_id.\n  reflexivity.\nQed.\n\nTheorem mapMBag_ok''' {M A B} `{MonadLaws M} (f : A -> M B) (b : Bag A) :\n  GHC.Base.fmap bagToList (mapBagM f b) = Data.Traversable.mapM f (bagToList b).\nProof.\n  induction b.\n  * rewrite /= emptyBag_ok mapM_nil -monad_applicative_pure.\n    anf_equal.\n  * rewrite /= monad_bind_return_fmap bagToList_UnitBag mapM_cons mapM_nil.\n    anf_equal.\n  * rewrite /= bagToList_TwoBags.\n    rewrite monad_bind_return_fmap2.\n    rewrite mapM_app.\n    rewrite -IHb1 -IHb2.\n    anf_equal.\n    by rewrite /op_z2218U__ bagToList_TwoBags.\n  * rewrite /= monad_bind_return_fmap bagToList_ListBag.\n    anf_equal.\n    replace (_∘_ bagToList Mk_ListBag) with (@id (list B)).\n    anf_equal.\n    funext; intros.\n    by rewrite /op_z2218U__ bagToList_ListBag.\nQed.\n\n(* TODO mapBagM_ mapAndUnzipBagM *)\n\n\n(* we need to add that to MonadLaws *)\nAxiom extra_monad_then_bind:\n  forall {M A B} `{Monad M} (x:M A) (y: M B),\n    (x >> y) = (x >>= (fun _ => y)).\n\n\nLemma fold_right_then {M A B} `{MonadLaws M}\n      (x : M B) (l: list (M A)):\n    fold_right _>>_ x l =\n     _>>_ (fold_right _>>_ (return_ tt) l) x.\nProof.\n  induction l; simpl.\n  - rewrite extra_monad_then_bind.\n    rewrite monad_left_id.\n    reflexivity.\n  - rewrite IHl.\n    rewrite !extra_monad_then_bind.\n    rewrite monad_composition.\n    reflexivity.\nQed.\n\nTheorem mapBagM_is_ok {M A B} `{MonadLaws M} (f : A -> M B) (b : Bag A) :\n  (mapBagM_ f b) =\n  Data.Foldable.mapM_ f (bagToList b).\nProof.\n  rewrite /Data.Foldable.mapM_ /=\n          /Foldable.Foldable__list_foldr\n          /Foldable.foldr /Foldable.Foldable__list\n          /Foldable.foldr__\n          /Foldable.Foldable__list_foldr.\n  induction b; simpl; try reflexivity.\n  - rewrite bagToList_TwoBags foldr_app.\n    rewrite -IHb2.\n    rewrite !hs_coq_foldr_base -fold_right_map.\n    rewrite fold_right_then.\n    rewrite  fold_right_map -hs_coq_foldr_base.\n    rewrite -IHb1. reflexivity.\n  - rewrite /Foldable.mapM_\n            hs_coq_foldr_list hs_coq_foldr_base.\n    rewrite bagToList_ListBag. reflexivity.\nQed.\n\n\nTheorem mapAndUnzipBagM_ok {M A B C} `{MonadLaws M}\n        (f : A -> M (B*C)%type) (b : Bag A) :\n  GHC.Base.fmap bagToList (GHC.Base.fmap (fst) (mapAndUnzipBagM f b)) =\n  GHC.Base.fmap (map fst) (Data.Traversable.mapM f (bagToList b)) /\\\n  GHC.Base.fmap bagToList (GHC.Base.fmap (snd) (mapAndUnzipBagM f b)) =\n  GHC.Base.fmap (map snd) (Data.Traversable.mapM f (bagToList b)).\nProof.\n  rewrite\n    /Data.Traversable.mapM\n    /Traversable.Traversable__list\n    /Data.Traversable.mapM__\n    /Data.Traversable.Traversable__list_mapM\n    /Data.Traversable.Traversable__list_traverse.\n  induction b; simpl;\n    [split; anf_equal | | |].\n  - split;\n      assert (Hr: (fun x : B * C =>\n                   let (r, s) := x in\n                   return_ (Mk_UnitBag r, Mk_UnitBag s)) =\n                (fun x : B * C =>\n                  return_ (Mk_UnitBag x.1, Mk_UnitBag x.2)));\n      solve [funext; \n             intros x;  destruct x;\n             reflexivity |\n             rewrite Hr;\n             rewrite monad_bind_return_fmap;\n             anf_equal].\n  - destruct IHb1 as [IHb11 IHb12].\n    destruct IHb2 as [IHb21 IHb22].\n    rewrite bagToList_TwoBags.\n    split.\n    + assert (Hr: (fun x : Bag B * Bag C =>\n         let (r1, s1) := x in\n         mapAndUnzipBagM f b2 >>=\n         (fun y: Bag B * Bag C =>\n          let (r2, s2) := y in\n          return_ (Mk_TwoBags r1 r2, Mk_TwoBags s1 s2))) =\n         (fun x : Bag B * Bag C =>\n         mapAndUnzipBagM f b2 >>=\n         (fun y: Bag B * Bag C =>\n          return_ (Mk_TwoBags x.1 y.1, Mk_TwoBags x.2 y.2))));\n      try solve [funext; intros x; destruct x; f_equal;\n                 funext; intros y; destruct y; reflexivity].\n      rewrite Hr.\n      rewrite monad_bind_return_fmap2.\n      rewrite <- monad_bind_fmap_ap.\n    (*  setoid_rewrite \n      rewrite bagToList_TwoBags foldr_app -IHl -IHr.\n    unfold \"<$>\"; rewrite !functor_composition.\n    rewrite !applicative_fmap -!applicative_composition !applicative_homomorphism; f_equal.\n    rewrite !applicative_interchange -!applicative_fmap functor_composition; do 2 f_equal.\n    funext=> l'; funext=> r'; funext=> z'.\n    by unfold \"∘\"; rewrite bagToList_TwoBags app_assoc.\n\n*)  \nAdmitted.\n \n(* TODO foldrBagM foldlBagM *)\n(*\nCheck foldrBagM.\nPrint GHC.Base.fmap.\nCheck mapBagM.\nSearch foldr.\n*)\n(*\nTheorem foldrBagM_ok {M A B C} `{MonadLaws M}\n        (f : A -> B -> M B) (d : B) (b : Bag A):\n  (GHC.Base.fmap bagToList (foldrBagM f d b) =\n  (fold_right f (bagToList b))).\nProof.\n\nAdmitted.\n*)\n(* TODO flatMapBagM flatMapBagPairM *)\n\n(* TODO filterBagM *)\n\n(* TODO anyBagM *)\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/bag/MonadicCorrectness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.2779104828271032}}
{"text": "From iris.algebra Require Export cmra.\nFrom iris.algebra Require Import updates local_updates.\nFrom stdpp Require Export collections coPset.\nSet Default Proof Using \"Type\".\n(** This is pretty much the same as algebra/gset, but I was not able to\ngeneralize the construction without breaking canonical structures. *)\n\n(* The union CMRA *)\nSection coPset.\n  Implicit Types X Y : coPset.\n\n  Canonical Structure coPsetC := discreteC coPset.\n\n  Instance coPset_valid : Valid coPset := λ _, True.\n  Instance coPset_unit : Unit coPset := (∅ : coPset).\n  Instance coPset_op : Op coPset := union.\n  Instance coPset_pcore : PCore coPset := Some.\n\n  Lemma coPset_op_union X Y : X ⋅ Y = X ∪ Y.\n  Proof. done. Qed.\n  Lemma coPset_core_self X : core X = X.\n  Proof. done. Qed.\n  Lemma coPset_included X Y : X ≼ Y ↔ X ⊆ Y.\n  Proof.\n    split.\n    - intros [Z ->]. rewrite coPset_op_union. set_solver.\n    - intros (Z&->&?)%subseteq_disjoint_union_L. by exists Z.\n  Qed.\n\n  Lemma coPset_ra_mixin : RAMixin coPset.\n  Proof.\n    apply ra_total_mixin; eauto.\n    - solve_proper.\n    - solve_proper.\n    - solve_proper.\n    - intros X1 X2 X3. by rewrite !coPset_op_union assoc_L.\n    - intros X1 X2. by rewrite !coPset_op_union comm_L.\n    - intros X. by rewrite coPset_core_self idemp_L.\n  Qed.\n  Canonical Structure coPsetR := discreteR coPset coPset_ra_mixin.\n\n  Global Instance coPset_cmra_discrete : CmraDiscrete coPsetR.\n  Proof. apply discrete_cmra_discrete. Qed.\n\n  Lemma coPset_ucmra_mixin : UcmraMixin coPset.\n  Proof. split. done. intros X. by rewrite coPset_op_union left_id_L. done. Qed.\n  Canonical Structure coPsetUR := UcmraT coPset coPset_ucmra_mixin.\n\n  Lemma coPset_opM X mY : X ⋅? mY = X ∪ default ∅ mY.\n  Proof. destruct mY; by rewrite /= ?right_id_L. Qed.\n\n  Lemma coPset_update X Y : X ~~> Y.\n  Proof. done. Qed.\n\n  Lemma coPset_local_update X Y X' : X ⊆ X' → (X,Y) ~l~> (X',X').\n  Proof.\n    intros (Z&->&?)%subseteq_disjoint_union_L.\n    rewrite local_update_unital_discrete=> Z' _ /leibniz_equiv_iff->.\n    split. done. rewrite coPset_op_union. set_solver.\n  Qed.\nEnd coPset.\n\n(* The disjoiny union CMRA *)\nInductive coPset_disj :=\n  | CoPset : coPset → coPset_disj\n  | CoPsetBot : coPset_disj.\n\nSection coPset_disj.\n  Arguments op _ _ !_ !_ /.\n  Canonical Structure coPset_disjC := leibnizC coPset_disj.\n\n  Instance coPset_disj_valid : Valid coPset_disj := λ X,\n    match X with CoPset _ => True | CoPsetBot => False end.\n  Instance coPset_disj_unit : Unit coPset_disj := CoPset ∅.\n  Instance coPset_disj_op : Op coPset_disj := λ X Y,\n    match X, Y with\n    | CoPset X, CoPset Y => if decide (X ## Y) then CoPset (X ∪ Y) else CoPsetBot\n    | _, _ => CoPsetBot\n    end.\n  Instance coPset_disj_pcore : PCore coPset_disj := λ _, Some ε.\n\n  Ltac coPset_disj_solve :=\n    repeat (simpl || case_decide);\n    first [apply (f_equal CoPset)|done|exfalso]; set_solver by eauto.\n\n  Lemma coPset_disj_included X Y : CoPset X ≼ CoPset Y ↔ X ⊆ Y.\n  Proof.\n    split.\n    - move=> [[Z|]]; simpl; try case_decide; set_solver.\n    - intros (Z&->&?)%subseteq_disjoint_union_L.\n      exists (CoPset Z). coPset_disj_solve.\n  Qed.\n  Lemma coPset_disj_valid_inv_l X Y :\n    ✓ (CoPset X ⋅ Y) → ∃ Y', Y = CoPset Y' ∧ X ## Y'.\n  Proof. destruct Y; repeat (simpl || case_decide); by eauto. Qed.\n  Lemma coPset_disj_union X Y : X ## Y → CoPset X ⋅ CoPset Y = CoPset (X ∪ Y).\n  Proof. intros. by rewrite /= decide_True. Qed.\n  Lemma coPset_disj_valid_op X Y : ✓ (CoPset X ⋅ CoPset Y) ↔ X ## Y.\n  Proof. simpl. case_decide; by split. Qed.\n\n  Lemma coPset_disj_ra_mixin : RAMixin coPset_disj.\n  Proof.\n    apply ra_total_mixin; eauto.\n    - intros [?|]; destruct 1; coPset_disj_solve.\n    - by constructor.\n    - by destruct 1.\n    - intros [X1|] [X2|] [X3|]; coPset_disj_solve.\n    - intros [X1|] [X2|]; coPset_disj_solve.\n    - intros [X|]; coPset_disj_solve.\n    - exists (CoPset ∅); coPset_disj_solve.\n    - intros [X1|] [X2|]; coPset_disj_solve.\n  Qed.\n  Canonical Structure coPset_disjR := discreteR coPset_disj coPset_disj_ra_mixin.\n\n  Global Instance coPset_disj_cmra_discrete : CmraDiscrete coPset_disjR.\n  Proof. apply discrete_cmra_discrete. Qed.\n\n  Lemma coPset_disj_ucmra_mixin : UcmraMixin coPset_disj.\n  Proof. split; try apply _ || done. intros [X|]; coPset_disj_solve. Qed.\n  Canonical Structure coPset_disjUR := UcmraT coPset_disj coPset_disj_ucmra_mixin.\nEnd coPset_disj.\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/coPset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.2779104828271032}}
{"text": "(** This file provides a construction to lift a PROP-level binary relation to\nits reflexive transitive closure. *)\nFrom iris.bi.lib Require Export fixpoint.\nFrom iris.proofmode Require Import tactics.\nFrom iris.prelude Require Import options.\n\n(* The sections add extra BI assumptions, which is only picked up with \"Type\"*. *)\nSet Default Proof Using \"Type*\".\n\nDefinition bi_rtc_pre `{!BiInternalEq PROP}\n    {A : ofe} (R : A → A → PROP)\n    (x2 : A) (rec : A → PROP) (x1 : A) : PROP :=\n  (<affine> (x1 ≡ x2) ∨ ∃ x', R x1 x' ∗ rec x')%I.\n\nGlobal Instance bi_rtc_pre_mono `{!BiInternalEq PROP}\n    {A : ofe} (R : A → A → PROP) `{NonExpansive2 R} (x : A) :\n  BiMonoPred (bi_rtc_pre R x).\nProof.\n  constructor; [|solve_proper].\n  iIntros (rec1 rec2) \"#H\". iIntros (x1) \"[Hrec | Hrec]\".\n  { by iLeft. }\n  iRight.\n  iDestruct \"Hrec\" as (x') \"[HP Hrec]\".\n  iDestruct (\"H\" with \"Hrec\") as \"Hrec\". eauto with iFrame.\nQed.\n\nDefinition bi_rtc `{!BiInternalEq PROP}\n    {A : ofe} (R : A → A → PROP) (x1 x2 : A) : PROP :=\n  bi_least_fixpoint (bi_rtc_pre R x2) x1.\n\nGlobal Instance: Params (@bi_rtc) 3 := {}.\nTypeclasses Opaque bi_rtc.\n\nGlobal Instance bi_rtc_ne `{!BiInternalEq PROP} {A : ofe} (R : A → A → PROP) :\n  NonExpansive2 (bi_rtc R).\nProof.\n  intros n x1 x2 Hx y1 y2 Hy. rewrite /bi_rtc Hx. f_equiv=> rec z.\n  solve_proper.\nQed.\n\nGlobal Instance bi_rtc_proper `{!BiInternalEq PROP} {A : ofe} (R : A → A → PROP)\n  : Proper ((≡) ==> (≡) ==> (⊣⊢)) (bi_rtc R).\nProof. apply ne_proper_2. apply _. Qed.\n\nSection bi_rtc.\n  Context `{!BiInternalEq PROP}.\n  Context {A : ofe}.\n  Context (R : A → A → PROP) `{NonExpansive2 R}.\n\n  Lemma bi_rtc_unfold (x1 x2 : A) :\n    bi_rtc R x1 x2 ≡ bi_rtc_pre R x2 (λ x1, bi_rtc R x1 x2) x1.\n  Proof. by rewrite /bi_rtc; rewrite -least_fixpoint_unfold. Qed.\n\n  Lemma bi_rtc_strong_ind_l x2 Φ :\n    NonExpansive Φ →\n    □ (∀ x1, <affine> (x1 ≡ x2) ∨ (∃ x', R x1 x' ∗ (Φ x' ∧ bi_rtc R x' x2)) -∗ Φ x1) -∗\n    ∀ x1, bi_rtc R x1 x2 -∗ Φ x1.\n Proof.\n    iIntros (?) \"#IH\". rewrite /bi_rtc.\n    by iApply (least_fixpoint_strong_ind (bi_rtc_pre R x2) with \"IH\").\n  Qed.\n\n  Lemma bi_rtc_ind_l x2 Φ :\n    NonExpansive Φ →\n    □ (∀ x1, <affine> (x1 ≡ x2) ∨ (∃ x', R x1 x' ∗ Φ x') -∗ Φ x1) -∗\n    ∀ x1, bi_rtc R x1 x2 -∗ Φ x1.\n  Proof.\n    iIntros (?) \"#IH\". rewrite /bi_rtc.\n    by iApply (least_fixpoint_ind (bi_rtc_pre R x2) with \"IH\").\n  Qed.\n\n  Lemma bi_rtc_refl x : ⊢ bi_rtc R x x.\n  Proof. rewrite bi_rtc_unfold. by iLeft. Qed.\n\n  Lemma bi_rtc_l x1 x2 x3 : R x1 x2 -∗ bi_rtc R x2 x3 -∗ bi_rtc R x1 x3.\n  Proof.\n    iIntros \"H1 H2\".\n    iEval (rewrite bi_rtc_unfold /bi_rtc_pre). iRight.\n    iExists x2. iFrame.\n  Qed.\n\n  Lemma bi_rtc_once x1 x2 : R x1 x2 -∗ bi_rtc R x1 x2.\n  Proof. iIntros \"H\". iApply (bi_rtc_l with \"H\"). iApply bi_rtc_refl. Qed.\n\n  Lemma bi_rtc_trans x1 x2 x3 : bi_rtc R x1 x2 -∗ bi_rtc R x2 x3 -∗ bi_rtc R x1 x3.\n  Proof.\n    iRevert (x1).\n    iApply bi_rtc_ind_l.\n    { solve_proper. }\n    iIntros \"!>\" (x1) \"[H | H] H2\".\n    { by iRewrite \"H\". }\n    iDestruct \"H\" as (x') \"[H IH]\".\n    iApply (bi_rtc_l with \"H\").\n    by iApply \"IH\".\n  Qed.\n\nEnd bi_rtc.\n", "meta": {"author": "jtassarotti", "repo": "iris-inv-hierarchy", "sha": "b25fe890d72ecb5bafa9db422ece3939d99882ab", "save_path": "github-repos/coq/jtassarotti-iris-inv-hierarchy", "path": "github-repos/coq/jtassarotti-iris-inv-hierarchy/iris-inv-hierarchy-b25fe890d72ecb5bafa9db422ece3939d99882ab/iris/bi/lib/relations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.27787839534973285}}
{"text": "Require Export ComponentSM6.\n\n\nHint Resolve implies_wf_procs_procs2byz : comp.\nHint Resolve implies_are_procs_n_procs_procs2byz : comp.\nHint Rewrite @procs2byz_procs2byz : comp.\nHint Resolve wf_procs_implies_no_dup : comp.\nHint Resolve wf_procs_implies_ordered : comp.\n\n\nSection ComponentSM9.\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  Context { base_fun_io       : baseFunIO }.\n  Context { base_state_fun    : baseStateFun }.\n  Context { trusted_state_fun : trustedStateFun }.\n\n  Lemma incr_n_proc_update_state_m :\n    forall {n} {cn} (p : n_proc n cn) s,\n      incr_n_proc (update_state_m p s)\n      = update_state_m (incr_n_proc p) s.\n  Proof.\n    induction n; introv; simpl; tcsp.\n  Qed.\n\n  Lemma trusted_run_sm_on_inputs_incr_n_proc :\n    forall {n} cn s (p : n_proc n (pre2trusted cn)) l,\n      trusted_run_sm_on_inputs s (incr_n_proc p) l\n      = trusted_run_sm_on_inputs s p l.\n  Proof.\n    introv.\n    unfold trusted_run_sm_on_inputs.\n    pose proof (snd_run_sm_on_inputs_incr_n_proc_eq l (update_state_m p s) []) as w.\n    unfold decr_n_procs in w; simpl in w.\n    rewrite incr_n_proc_update_state_m in w.\n    simpl in *; rewrite w; clear w; tcsp.\n  Qed.\n  Hint Rewrite @trusted_run_sm_on_inputs_incr_n_proc : comp.\n\n  Lemma implies_similar_subs_procs2byz :\n    forall {n} (l k : n_procs n),\n      similar_subs l k\n      -> similar_subs (procs2byz l) (procs2byz k).\n  Proof.\n    introv sim; induction sim; simpl in *; tcsp.\n    inversion simp; subst; simpl in *; GC.\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 h2; subst; eauto 3 with comp.\n    unfold is_trusted in *; simpl in *; dest_cases w.\n  Qed.\n  Hint Resolve implies_similar_subs_procs2byz : comp.\n\n  Lemma M_byz_run_ls_on_this_one_event_preserves_subs_byz :\n    forall {eo : EventOrdering} e {L S} (ls1 ls2 : LocalSystem L S),\n      wf_procs ls1\n      -> are_procs_n_procs ls1\n      -> M_byz_run_ls_on_this_one_event ls1 e = ls2\n      -> (wf_procs ls2\n          /\\ are_procs_n_procs ls2\n          /\\ similar_subs (procs2byz ls1) (procs2byz ls2)).\n  Proof.\n    introv wf aps run.\n    unfold M_byz_run_ls_on_this_one_event in run; simpl in *.\n    unfold M_byz_run_ls_on_one_event in run; simpl in *.\n    remember (M_byz_run_ls_on_input ls1 (msg_comp_name S) (trigger e)) as h; repnd;\n      simpl in *; subst; symmetry in Heqh.\n    remember (trigger e) as trig.\n    destruct trig; simpl in *; tcsp; GC.\n\n    { pose proof (M_byz_run_ls_on_this_one_event_M_nt_preserves_subs e ls1 ls2) as q.\n      repeat (autodimp q hyp).\n      { unfold isCorrect, trigger_op; allrw <-; simpl; auto. }\n      { unfold M_byz_run_ls_on_this_one_event, M_byz_run_ls_on_one_event.\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 <- Heqtrig; simpl; introv q.\n        rewrite Heqh in q; ginv. }\n      { repnd.\n        dands; eauto 2 with comp. } }\n\n    { destruct h; tcsp; ginv; dands; autorewrite with comp in *; eauto 3 with comp. }\n\n    { unfold M_run_ls_on_trusted in Heqh.\n      pose proof (M_run_ls_on_input_preserves_subs\n                    (pre2trusted (it_name i))\n                    (it_input i)\n                    (procs2byz ls1)\n                    ls2 h) as q.\n      repeat (autodimp q hyp); eauto 3 with comp; repnd.\n      apply implies_similar_subs_procs2byz in q2; autorewrite with comp in *.\n      dands; auto; eauto 3 with comp. }\n  Qed.\n\n  Lemma M_byz_run_ls_before_event_preserves_subs_byz :\n    forall {eo : EventOrdering} e {L S} (ls1 ls2 : LocalSystem L S),\n      wf_procs ls1\n      -> are_procs_n_procs ls1\n      -> M_byz_run_ls_before_event ls1 e = ls2\n      -> (wf_procs ls2\n          /\\ are_procs_n_procs ls2\n          /\\ similar_subs (procs2byz ls1) (procs2byz ls2)).\n  Proof.\n    intros eo e.\n    induction e as [e ind] using predHappenedBeforeInd; introv wf aps run.\n    rewrite M_byz_run_ls_before_event_unroll in run.\n\n    destruct (dec_isFirst e) as [d|d]; ginv; auto;[|].\n    { subst; dands; eauto 3 with comp. }\n\n    remember (M_byz_run_ls_before_event ls1 (local_pred e)) as ls'; simpl in *; symmetry in Heqls'.\n    pose proof (ind (local_pred e)) as ind; autodimp ind hyp; eauto 3 with eo;[].\n    pose proof (ind L S ls1 ls') as ind.\n    repeat (autodimp ind hyp); eauto 3 with eo; repnd;[].\n    clear Heqls'.\n\n    apply M_byz_run_ls_on_this_one_event_preserves_subs_byz in run; auto.\n    repnd; dands; eauto 3 with comp.\n  Qed.\n\n  Lemma M_byz_run_ls_on_this_one_event_preserves_subs_byz2 :\n    forall {eo : EventOrdering} e {L S} (ls1 ls2 : LocalSystem L S),\n      wf_procs ls1\n      -> are_procs_n_procs ls1\n      -> M_byz_run_ls_on_this_one_event ls1 e = ls2\n      -> (wf_procs ls2\n          /\\ are_procs_n_procs ls2\n          /\\ (similar_subs ls1 ls2 \\/ similar_subs (procs2byz ls1) ls2)).\n  Proof.\n    introv wf aps run.\n    unfold M_byz_run_ls_on_this_one_event in run; simpl in *.\n    unfold M_byz_run_ls_on_one_event in run; simpl in *.\n    remember (M_byz_run_ls_on_input ls1 (msg_comp_name S) (trigger e)) as h; repnd;\n      simpl in *; subst; symmetry in Heqh.\n    remember (trigger e) as trig.\n    destruct trig; simpl in *; tcsp; GC.\n\n    { pose proof (M_byz_run_ls_on_this_one_event_M_nt_preserves_subs e ls1 ls2) as q.\n      repeat (autodimp q hyp).\n      { unfold isCorrect, trigger_op; allrw <-; simpl; auto. }\n      { unfold M_byz_run_ls_on_this_one_event, M_byz_run_ls_on_one_event.\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 <- Heqtrig; simpl; introv q.\n        rewrite Heqh in q; ginv. }\n      { repnd.\n        dands; eauto 2 with comp. } }\n\n    { destruct h; tcsp; ginv; dands; autorewrite with comp in *; eauto 3 with comp. }\n\n    { unfold M_run_ls_on_trusted in Heqh.\n      pose proof (M_run_ls_on_input_preserves_subs\n                    (pre2trusted (it_name i))\n                    (it_input i)\n                    (procs2byz ls1)\n                    ls2 h) as q.\n      repeat (autodimp q hyp); eauto 3 with comp; repnd.\n      applydup @implies_similar_subs_procs2byz in q2; autorewrite with comp in *.\n      dands; auto; eauto 3 with comp. }\n  Qed.\n\n  Lemma M_byz_run_ls_before_event_preserves_subs_byz2 :\n    forall {eo : EventOrdering} e {L S} (ls1 ls2 : LocalSystem L S),\n      wf_procs ls1\n      -> are_procs_n_procs ls1\n      -> M_byz_run_ls_before_event ls1 e = ls2\n      -> (wf_procs ls2\n          /\\ are_procs_n_procs ls2\n          /\\ (similar_subs ls1 ls2 \\/ similar_subs (procs2byz ls1) ls2)).\n  Proof.\n    intros eo e.\n    induction e as [e ind] using predHappenedBeforeInd; introv wf aps run.\n    rewrite M_byz_run_ls_before_event_unroll in run.\n\n    destruct (dec_isFirst e) as [d|d]; ginv; auto;[|].\n    { subst; dands; eauto 3 with comp. }\n\n    remember (M_byz_run_ls_before_event ls1 (local_pred e)) as ls'; simpl in *; symmetry in Heqls'.\n    pose proof (ind (local_pred e)) as ind; autodimp ind hyp; eauto 3 with eo;[].\n    pose proof (ind L S ls1 ls') as ind.\n    repeat (autodimp ind hyp); eauto 3 with eo; repnd;[].\n    clear Heqls'.\n\n    apply M_byz_run_ls_on_this_one_event_preserves_subs_byz2 in run; auto.\n    repnd; dands; eauto 3 with comp;[].\n\n    repndors; tcsp; eauto 4 with comp.\n    apply implies_similar_subs_procs2byz in ind; autorewrite with comp in *; eauto 3 with comp.\n  Qed.\n\n  Definition M_break_mon {n} {S}\n             (sm   : M_n n S)\n             (subs : n_procs n) : n_procs n :=\n    M_break sm subs (fun subs' _ => subs').\n\n  Definition M_break_out {n} {S}\n             (sm   : M_n n S)\n             (subs : n_procs n) : S :=\n    M_break sm subs (fun _ out => out).\n\n  Definition is_M_break_mon {n} {S}\n             (sm    : M_n n S)\n             (subs  : n_procs n)\n             (subs' : n_procs n) :=\n    M_break_mon sm subs = subs'.\n\n  Definition is_M_break_out {n} {S}\n             (sm   : M_n n S)\n             (subs : n_procs n)\n             (s    : S) :=\n    M_break_out sm subs = s.\n\n  Lemma fold_is_M_break_mon :\n    forall {n} {S}\n           (sm    : M_n n S)\n           (subs  : n_procs n)\n           (subs' : n_procs n),\n      M_break_mon sm subs = subs'\n      <-> is_M_break_mon sm subs subs'.\n  Proof.\n    tcsp.\n  Qed.\n\n  Lemma fold_is_M_break_out :\n    forall {n} {S}\n           (sm   : M_n n S)\n           (subs : n_procs n)\n           (s    : S),\n      M_break_out sm subs = s\n      <-> is_M_break_out sm subs s.\n  Proof.\n    tcsp.\n  Qed.\n\n  Lemma is_M_break_mon_preserves_subs :\n    forall {n} {cn} (p : n_proc_at n cn) (l k : n_procs (S n)) i,\n      wf_procs l\n      -> is_proc_n_proc_at p\n      -> are_procs_n_procs l\n      -> is_M_break_mon (lift_M_1 (app_n_proc_at p i)) l k\n      -> similar_subs l k.\n  Proof.\n    introv wf isp aps h.\n    unfold is_M_break_mon, M_break_mon, M_break in h; simpl in h.\n\n    pose proof (app_m_proc_some2 (at2sm p) i l) as q.\n    simpl in q; repeat (autodimp q hyp); eauto 3 with comp.\n    rewrite q in h; clear q.\n\n    remember (sm_update p (sm_state p) i (select_n_procs n l)) as z;\n      symmetry in Heqz; repnd; simpl in *; subst; simpl in *.\n    fold (M_StateMachine n) in *; fold (n_proc n) in *; rewrite Heqz.\n\n    pose proof (are_procs_implies_preserves_sub p (sm_state p) i (select_n_procs n l)) as h.\n    repeat (autodimp h hyp); eauto 3 with comp;[].\n    unfold M_break in h.\n    rewrite Heqz in h; repnd.\n\n    rewrite raise_to_n_procs_as_incr_n_procs.\n    rewrite <- decr_n_procs_as_select_n_procs in h0.\n    eapply similar_subs_trans;\n      [|apply implies_similar_subs_app;\n        [apply implies_similar_subs_remove_subs;[apply similar_subs_refl|eauto]\n        |apply implies_similar_subs_incr_n_procs;eauto]\n      ].\n    rewrite @remove_subs_decr_n_procs_as_keep_highest_subs; eauto 3 with comp.\n    pose proof (incr_n_procs_decr_n_procs_as_rm_highest l) as rm; simpl in *; rewrite rm; clear rm.\n    rewrite <- split_as_rm_highest_keep_highest; eauto 3 with comp.\n  Qed.\n\n  Lemma implies_is_proc_n_proc_at_0 :\n    forall (l : n_procs 1) {cn} (p : n_proc_at 0 cn),\n      are_procs_n_procs l\n      -> find_name cn l = Some (sm_or_at p)\n      -> is_proc_n_proc_at (sm2p0 p).\n  Proof.\n    introv aps fn.\n    apply @are_procs_n_procs_find_name in fn; auto.\n  Qed.\n  Hint Resolve implies_is_proc_n_proc_at_0 : comp.\n\n  Lemma is_M_break_out_preserves_subs :\n    forall {n} {cn} (p : n_proc_at n cn) (l : n_procs (S n)) i a b,\n      is_proc_n_proc_at p\n      -> is_M_break_out (lift_M_1 (app_n_proc_at p i)) l (a,b)\n      -> exists q, a = Some q /\\ similar_sms (at2sm p) q.\n  Proof.\n    introv isp h.\n    unfold is_M_break_out, M_break_out, M_break in h; simpl in h.\n\n    unfold lift_M_1, M_on_decr, app_n_proc_at, bind_pair, bind in h; simpl in h.\n    remember (sm_update p (sm_state p) i (decr_n_procs l)) as z; symmetry in Heqz; repnd; simpl in *; ginv.\n\n    unfold is_proc_n_proc_at in isp; exrepnd.\n    rewrite isp0 in Heqz; simpl in *.\n    unfold proc2upd in Heqz.\n    rewrite interp_s_proc_as in Heqz.\n    unfold bind_pair, bind in Heqz; simpl in *.\n\n    remember (interp_proc (p0 (sm_state p) i) (decr_n_procs l)) as w; symmetry in Heqw; repnd; simpl in *.\n    rewrite Heqw in Heqz; simpl in *; ginv.\n    inversion Heqz; subst; simpl in *; tcsp.\n    eexists; dands; eauto; simpl; tcsp.\n  Qed.\n\n  Lemma in_replace_name_implies :\n    forall {n} {cn} (p : n_proc n cn) subs q,\n      In q (replace_name p subs)\n      -> q = MkPProc cn p \\/ In q subs.\n  Proof.\n    induction subs; introv i; simpl in *; tcsp.\n    destruct a; simpl in *; tcsp; dest_cases w; simpl in *; repndors; ginv; tcsp.\n    apply IHsubs in i; repndors; subst; tcsp.\n  Qed.\n\n  Lemma implies_are_procs_n_procs_replace_name :\n    forall {n} {cn} (subs : n_procs n) (p : n_proc n cn),\n      are_procs_n_procs subs\n      -> is_proc_n_proc p\n      -> are_procs_n_procs (replace_name p subs).\n  Proof.\n    introv aps ips i.\n    apply in_replace_name_implies in i; repndors; subst; tcsp.\n  Qed.\n  Hint Resolve implies_are_procs_n_procs_replace_name : comp.\n\n  Lemma implies_similar_sms_sm_or_at :\n    forall {cn} (p q : n_proc_at 0 cn),\n      similar_sms_at p q\n      -> similar_sms (at2sm p) (at2sm q).\n  Proof.\n    tcsp.\n  Qed.\n\n  Lemma similar_sms_at2sm_sm2p0 :\n    forall {cn} (a : n_proc_at 0 cn) q,\n      similar_sms (at2sm (sm2p0 a)) q\n      -> exists b, q = at2sm b /\\ similar_sms_at a b.\n  Proof.\n    introv h; simpl in *; destruct q; simpl in *; tcsp.\n    exists a0; dands; auto.\n  Qed.\n\n  Definition has_sim_comp {cn} {n} (p : n_proc n cn) (ls : n_procs n) :=\n    exists comp, find_name cn ls = Some comp /\\ similar_sms comp p.\n\n  Lemma similar_subs_replace_name_right :\n    forall {n} {cn} (p : n_proc n cn) (subs1 subs2 : n_procs n),\n      has_sim_comp p subs2\n      -> similar_subs subs1 subs2\n      -> similar_subs subs1 (replace_name p subs2).\n  Proof.\n    induction subs1; introv hc sim; destruct subs2; simpl in *; tcsp;\n      inversion sim; subst; tcsp; clear sim.\n    destruct n0 as [cn' p']; simpl in *; dest_cases w; subst; tcsp.\n\n    { constructor; auto.\n      unfold has_sim_comp in *; exrepnd; simpl in *; dest_cases w.\n      rewrite (UIP_refl_CompName _ w) in hc1; simpl in *; ginv.\n      eapply similar_procs_trans;eauto. }\n\n    { constructor; auto.\n      apply IHsubs1; auto.\n      unfold has_sim_comp in *; exrepnd; simpl in *; dest_cases w; eauto. }\n  Qed.\n\n  Lemma similar_subs_preserves_has_sim_comp :\n    forall {n} {cn} (p : n_proc n cn) (l k : n_procs n),\n      similar_subs l k\n      -> has_sim_comp p l\n      -> has_sim_comp p k.\n  Proof.\n    introv sim h.\n    unfold has_sim_comp in *; exrepnd.\n    eapply ComponentSM.similar_subs_preserves_find_name in h1; eauto; exrepnd.\n    exists s'; dands; eauto 3 with comp.\n  Qed.\n  Hint Resolve similar_subs_preserves_has_sim_comp : comp.\n\n  Lemma similar_sms_at_preserves_has_sim_comp :\n    forall {n} {cn} (a b : n_proc_at n cn) subs,\n      similar_sms_at a b\n      -> has_sim_comp (at2sm a) subs\n      -> has_sim_comp (at2sm b) subs.\n  Proof.\n    introv sim h; unfold has_sim_comp in *; exrepnd.\n    destruct comp; simpl in *; tcsp.\n    eexists; dands; eauto; simpl; eauto 3 with comp.\n  Qed.\n  Hint Resolve similar_sms_at_preserves_has_sim_comp : comp.\n\n  Lemma find_name_implies_has_sim_comp_at2sm :\n    forall {cn} (a : n_proc_at 0 cn) (l : n_procs 1),\n      find_name cn l = Some (sm_or_at a)\n      -> has_sim_comp (at2sm a) l.\n  Proof.\n    introv h; eexists; dands; eauto; eauto 3 with comp.\n  Qed.\n  Hint Resolve find_name_implies_has_sim_comp_at2sm : comp.\n\n  Lemma find_name_replace_name_diff :\n    forall {cn1} {cn2} {n} (p : n_proc n cn2) l,\n      cn1 <> cn2\n      -> find_name cn1 (replace_name p l) = find_name cn1 l.\n  Proof.\n    induction l; introv d; simpl in *; tcsp.\n    destruct a; simpl in *; tcsp; repeat (dest_cases w; subst; simpl in *; tcsp).\n  Qed.\n  Hint Resolve find_name_replace_name_diff : comp.\n\n  Lemma implies_has_name_replace_name_same :\n    forall {cn} {n} (p : n_proc n cn) l x,\n      find_name cn l = Some x\n      -> find_name cn (replace_name p l) = Some p.\n  Proof.\n    induction l; introv h; simpl in *; tcsp.\n    destruct a; simpl in *; repeat (dest_cases w; subst; simpl in *; tcsp).\n    { rewrite (UIP_refl_CompName _ w); tcsp. }\n    eapply IHl; eauto.\n  Qed.\n  Hint Resolve implies_has_name_replace_name_same : comp.\n\n  Lemma implies_has_simp_comp_replace_name_same :\n    forall {cn} {n} (a b : n_proc n cn) l,\n      has_sim_comp a l\n      -> has_sim_comp b l\n      -> has_sim_comp a (replace_name b l).\n  Proof.\n    introv h q.\n    unfold has_sim_comp in *; exrepnd.\n    rewrite h1 in q1; ginv.\n    exists b; dands; eauto 3 with comp.\n  Qed.\n  Hint Resolve implies_has_simp_comp_replace_name_same : comp.\n\n  Lemma implies_has_name_replace_name_diff :\n    forall cn1 {cn2} {n} (p : n_proc n cn2) l x,\n      cn1 <> cn2\n      -> find_name cn1 l = Some x\n      -> find_name cn1 (replace_name p l) = Some x.\n  Proof.\n    induction l; introv d h; simpl in *; tcsp.\n    destruct a; simpl in *; repeat (dest_cases w; subst; simpl in *; tcsp).\n    rewrite (UIP_refl_CompName _ w); tcsp.\n  Qed.\n  Hint Resolve implies_has_name_replace_name_diff : comp.\n\n  Lemma implies_has_simp_comp_replace_name_diff :\n    forall {cn1} {cn2} {n} (a : n_proc n cn1) (b : n_proc n cn2) l,\n      cn1 <> cn2\n      -> has_sim_comp a l\n      -> has_sim_comp a (replace_name b l).\n  Proof.\n    introv h q.\n    unfold has_sim_comp in *; exrepnd.\n    exists comp; dands; eauto 3 with comp.\n  Qed.\n  Hint Resolve implies_has_simp_comp_replace_name_diff : comp.\n\n  Lemma find_name_replace_name_same :\n    forall {n} {cn} (p : n_proc n cn) l,\n      has_comp cn l\n      -> find_name cn (replace_name p l) = Some p.\n  Proof.\n    induction l; introv h; simpl in *; tcsp; unfold has_comp in *; exrepnd; simpl in *; tcsp.\n    destruct a; simpl in *; tcsp; repeat (dest_cases w; subst; simpl in *; tcsp).\n    { rewrite (UIP_refl_CompName _ w); tcsp. }\n    apply IHl; eauto.\n  Qed.\n  Hint Resolve find_name_replace_name_same : comp.\n\n  Lemma implies_has_comp_replace_name :\n    forall cn' {n} {cn} (p : n_proc n cn) l,\n      has_comp cn' l\n      -> has_comp cn' (replace_name p l).\n  Proof.\n    induction l; introv h; unfold has_comp in *; exrepnd; simpl in *; tcsp.\n    destruct a; simpl in *; repeat (dest_cases w; subst; simpl in *; tcsp; ginv); eauto.\n  Qed.\n  Hint Resolve implies_has_comp_replace_name : comp.\n\n  Lemma at2sm_eq_sm_or_at_implies :\n    forall {cn} (a b : n_proc_at 0 cn),\n      at2sm a = sm_or_at b -> a = b.\n  Proof.\n    introv h; inversion h; auto.\n  Qed.\n\n  Lemma replace_name_twice :\n    forall {n} {cn} (p q : n_proc n cn) l,\n      replace_name p (replace_name q l) = replace_name p l.\n  Proof.\n    induction l; introv; simpl in *; tcsp.\n    destruct a; simpl in *; tcsp; repeat (dest_cases w; subst; simpl in *; tcsp).\n  Qed.\n  Hint Rewrite @replace_name_twice : comp.\n\n  Lemma lower_head_replace_name_twice :\n    forall n {m} {cn} (p q : n_proc m cn) l,\n      lower_head n (replace_name p (replace_name q l))\n      = lower_head n (replace_name p l).\n  Proof.\n    introv; autorewrite with comp; auto.\n  Qed.\n  Hint Rewrite lower_head_replace_name_twice : comp.\n\n  Lemma implies_wf_procs_replace_name_twice :\n    forall {n} {cn} (p q : n_proc n cn) l,\n      wf_procs (replace_name p l)\n      -> wf_procs (replace_name p (replace_name q l)).\n  Proof.\n    introv; autorewrite with comp; auto.\n  Qed.\n  Hint Resolve implies_wf_procs_replace_name_twice : comp.\n\nEnd ComponentSM9.\n\n\nHint Rewrite @replace_name_twice : comp.\nHint Rewrite @trusted_run_sm_on_inputs_incr_n_proc : comp.\nHint Rewrite @lower_head_replace_name_twice : comp.\n\n\nHint Resolve implies_similar_subs_procs2byz : comp.\nHint Resolve implies_is_proc_n_proc_at_0 : comp.\nHint Resolve implies_are_procs_n_procs_replace_name : comp.\nHint Resolve similar_subs_preserves_has_sim_comp : comp.\nHint Resolve similar_sms_at_preserves_has_sim_comp : comp.\nHint Resolve find_name_implies_has_sim_comp_at2sm : comp.\nHint Resolve find_name_replace_name_diff : comp.\nHint Resolve implies_has_name_replace_name_same : comp.\nHint Resolve implies_has_simp_comp_replace_name_same : comp.\nHint Resolve implies_has_name_replace_name_diff : comp.\nHint Resolve implies_has_simp_comp_replace_name_diff : comp.\nHint Resolve find_name_replace_name_same : comp.\nHint Resolve implies_has_comp_replace_name : comp.\nHint Resolve implies_wf_procs_replace_name_twice : 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/model/ComponentSM9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2778783953497328}}
{"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 map.Map.\n\n(* Why3 assumption *)\nDefinition unit := unit.\n\n(* Why3 assumption *)\nInductive ref (a:Type) {a_WT:WhyType a} :=\n  | mk_ref : a -> ref a.\nAxiom ref_WhyType : forall (a:Type) {a_WT:WhyType a}, WhyType (ref a).\nExisting Instance ref_WhyType.\nImplicit Arguments mk_ref [[a] [a_WT]].\n\n(* Why3 assumption *)\nDefinition contents {a:Type} {a_WT:WhyType a} (v:(ref a)): a :=\n  match v with\n  | (mk_ref x) => x\n  end.\n\n(* Why3 assumption *)\nInductive array\n  (a:Type) {a_WT:WhyType a} :=\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] [a_WT]].\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\n(* Why3 goal *)\nTheorem WP_parameter_max_sum : forall (a:Z) (n:Z), forall (a1:(map.Map.map Z\n  Z)), ((0%Z <= a)%Z /\\ ((n = a) /\\ forall (i:Z), ((0%Z <= i)%Z /\\\n  (i < n)%Z) -> (0%Z <= (map.Map.get a1 i))%Z)) -> let o := (n - 1%Z)%Z in\n  ((0%Z <= o)%Z -> forall (max:Z) (sum:Z), forall (i:Z), ((0%Z <= i)%Z /\\\n  (i <= o)%Z) -> ((sum <= (i * max)%Z)%Z -> (((0%Z <= i)%Z /\\ (i < a)%Z) ->\n  ((max < (map.Map.get a1 i))%Z -> (((0%Z <= i)%Z /\\ (i < a)%Z) ->\n  forall (max1:Z), (max1 = (map.Map.get a1 i)) -> (((0%Z <= i)%Z /\\\n  (i < a)%Z) -> forall (sum1:Z), (sum1 = (sum + (map.Map.get a1 i))%Z) ->\n  (sum1 <= ((i + 1%Z)%Z * max1)%Z)%Z)))))).\nintros a n a1 (h1,(h2,h3)) o h4 max sum i (h5,h6) h7 (h8,h9) h10\n        (h11,h12) max1 h13 (h14,h15) sum1 h16.\nsubst o.\nring_simplify.\nsubst.\napply Zplus_le_compat_r.\napply Zle_trans with (i * max)%Z; auto.\nauto with *.\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/vstte10_max_sum/vstte10_max_sum_MaxAndSum_WP_parameter_max_sum_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.27787838828863515}}
{"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| 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\nDefinition pop f n :=\n    Frame (arg f) (self f) (skipn n (stack f)).\n\nDefinition pop_push f n v :=\n    push (pop f n) v.\n\nDefinition top f :=\n    match stack f with\n    | [] => Constr 0 []\n    | v :: _ => v\n    end.\n\n\n\nInductive cont :=\n| Kret (code : list insn) (f : frame) (k : cont)\n(* keeping the original `stk` lets us enforce that each branch pushes\n * exactly one value before running SContSwitch *)\n| Kswitch (code : list insn) (stk : list value) (k : cont)\n| Kstop.\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| SArg : forall is f k,\n        sstep E (Run (Arg :: is) f k)\n                (Run is (push f (arg f)) k)\n| SSelf : forall is f k,\n        sstep E (Run (Self :: is) f k)\n                (Run is (push f (self f)) k)\n\n| SDerefinateConstr : forall off is f k  tag args v,\n        length (stack f) >= 1 ->\n        top f = Constr tag args ->\n        nth_error args off = Some v ->\n        sstep E (Run (Deref off :: is) f k)\n                (Run is (pop_push f 1 v) k)\n| SDerefinateClose : forall off is f k  fname free v,\n        length (stack f) >= 1 ->\n        top f = Close fname free ->\n        nth_error free off = Some v ->\n        sstep E (Run (Deref off :: is) f k)\n                (Run is (pop_push f 1 v) k)\n\n| SConstrDone : forall tag nargs is f k,\n        length (stack f) >= nargs ->\n        sstep E (Run (MkConstr tag nargs :: is) f k)\n                (Run is (pop_push f nargs (Constr tag (rev (firstn nargs (stack f))))) k)\n| SCloseDone : forall fname nfree is f k,\n        length (stack f) >= nfree ->\n        sstep E (Run (MkClose fname nfree :: is) f k)\n                (Run is (pop_push f nfree (Close fname (rev (firstn nfree (stack f))))) k)\n| SOpaqueOpDone : forall op nargs is f k v,\n        length (stack f) >= nargs ->\n        opaque_oper_denote_higher op (rev (firstn nargs (stack f))) = Some v ->\n        sstep E (Run (OpaqueOp op nargs :: is) f k)\n                (Run is (pop_push f nargs v) k)\n\n| SMakeCall : forall is f k  fname free body,\n        length (stack f) >= 2 ->\n        nth_error (stack f) 1 = Some (Close fname free) ->\n        nth_error E fname = Some body ->\n        sstep E (Run (Call :: is) f k)\n                (Run body (Frame (top f) (Close fname free) [])\n                    (Kret is (pop f 2) k))\n\n(* NB: `Switch` still has an implicit target of `Arg` *)\n| SSwitchinate : forall cases is f k  tag args case,\n        arg f = Constr tag args ->\n        nth_error cases tag = Some case ->\n        sstep E (Run (Switch cases :: is) f k)\n                (Run case f (Kswitch is (stack f) k))\n\n| SContRet : forall code f f' k,\n        length (stack f) = 1 ->\n        sstep E (Run [] f (Kret code f' k))\n                (Run code (push f' (top f)) k)\n| SContSwitch : forall code f stk k v,\n        stack f = v :: stk ->\n        sstep E (Run [] f (Kswitch code stk k))\n                (Run code f k)\n| SContStop : forall f,\n        length (stack f) = 1 ->\n        sstep E (Run [] f Kstop)\n                (Stop (top f))\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                 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 (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\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 :     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        | 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    (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        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    (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            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/StackFlatter2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2778365467729137}}
{"text": "(* Copyright (c) 2014, Robert Dockins *)\n\nRequire Import String.\nRequire Import List.\nRequire Import Arith.\nRequire Import Lia.\n\nRequire Import basics.\nRequire Import preord.\nRequire Import categories.\nRequire Import sets.\nRequire Import finsets.\nRequire Import esets.\nRequire Import effective.\nRequire Import directed.\nRequire Import plotkin.\nRequire Import joinable.\nRequire Import approx_rels.\nRequire Import cpo.\nRequire Import profinite.\nRequire Import profinite_adj.\nRequire Import strict_utils.\nRequire Import fixes.\nRequire Import flat.\n\n(** * Soundness and adequacy simply-typed SKI with booleans and fixpoints.\n\n    The adequacy proof goes via a standard logical-relations argument.\n    As a corollary of the main logical-relations lemma, we show that\n    nonvalues are denoted by ⊥.\n  *)\n\n\n(**  We have arrow types and a single base type of booleans. *)\nInductive ty :=\n  | ty_bool\n  | ty_arrow : ty -> ty -> ty.\n\nDelimit Scope ty_scope with ty.\nNotation \"2\" := ty_bool : ty_scope.\nNotation \"x ⇒ y\" := (ty_arrow (x)%ty (y)%ty) : ty_scope.\nBind Scope ty_scope with ty.\n\nDelimit Scope ski_scope with ski.\nOpen Scope ski_scope.\n\n(**  Terms are boolean constants, the standard combinators S, K and I,\n     and an IF/THEN/ELSE combinator; and applications.  We also have\n     the call-by-value fixpoint combinator Y.  As usual for the CBV\n     fixpoint operator, it only calculates fixpoints at function types.\n  *)\nInductive term : ty -> Type :=\n  | tbool : forall b:bool,\n                term 2\n\n  | tapp : forall σ₁ σ₂,\n                term (σ₁ ⇒ σ₂) ->\n                term σ₁ ->\n                term σ₂\n\n  | tI : forall σ,\n                term (σ ⇒ σ)\n\n  | tK : forall σ₁ σ₂,\n                term (σ₁ ⇒ σ₂ ⇒ σ₁)\n\n  | tS : forall σ₁ σ₂ σ₃,\n                term ((σ₁ ⇒ σ₂ ⇒ σ₃) ⇒ (σ₁ ⇒ σ₂) ⇒ σ₁ ⇒ σ₃)\n\n  | tIF : forall σ,\n                term (2 ⇒ σ ⇒ σ ⇒ σ)\n\n  | tY : forall σ₁ σ₂,\n                term ( ((σ₁ ⇒ σ₂) ⇒ (σ₁ ⇒ σ₂)) ⇒ (σ₁ ⇒ σ₂) ).\n\nArguments tapp [_ _] _ _.\nNotation \"x • y\" := (tapp x y) \n  (at level 52, left associativity, format \"x • y\") : ski_scope.\n\n(**  The operational semantics is given in a big-step style, with the specification\n     of redexes split out into a separate relation.\n  *)\nInductive redex : forall σ₁ σ₂, term (σ₁ ⇒ σ₂) -> term σ₁ -> term σ₂ -> Prop :=\n  | redex_I : forall σ x,\n                  redex _ _ (tI σ) x x\n  | redex_K : forall σ₁ σ₂ x y,\n                  redex σ₂ σ₁ (tK σ₁ σ₂ • y) x y\n  | redex_S : forall σ₁ σ₂ σ₃ f g x,\n                  redex _ _ (tS σ₁ σ₂ σ₃ • f • g)\n                            x\n                            ((f•x)•(g•x))\n  | redex_IFtrue : forall σ th el,\n                  redex _ _ (tIF σ • tbool true • th) el th\n  | redex_IFfalse : forall σ th el,\n                  redex _ _ (tIF σ • tbool false • th) el el\n\n  | redex_Y : forall σ₁ σ₂ (f:term ((σ₁ ⇒ σ₂) ⇒ (σ₁ ⇒ σ₂))) x,\n                  redex _ _ (tY σ₁ σ₂ • f) x\n                            (f•(tY σ₁ σ₂ • f)•x).\n\nInductive eval : forall τ, term τ -> term τ -> Prop :=\n  | ebool : forall b, eval 2 (tbool b) (tbool b)\n  | eI   : forall σ, eval _ (tI σ) (tI _)\n  | eK   : forall σ₁ σ₂, eval _ (tK σ₁ σ₂) (tK _ _)\n  | eS   : forall σ₁ σ₂ σ₃, eval _ (tS σ₁ σ₂ σ₃) (tS _ _ _)\n  | eIF  : forall σ, eval _ (tIF σ) (tIF σ)\n  | eY   : forall σ₁ σ₂, eval _ (tY σ₁ σ₂) (tY _ _)\n  | eapp1 : forall σ₁ σ₂ m₁ m₂ n₁ n₂ r z,\n             eval (σ₁ ⇒ σ₂) m₁ n₁ ->\n             eval σ₁ m₂ n₂ ->\n             redex σ₁ σ₂ n₁ n₂ r ->\n             eval σ₂ r z ->\n             eval σ₂ (m₁ • m₂) z\n  | eapp2 : forall σ₁ σ₂ m₁ m₂ n₁ n₂,\n             eval (σ₁ ⇒ σ₂) m₁ n₁ ->\n             eval σ₁ m₂ n₂ ->\n             ~(exists r, redex σ₁ σ₂ n₁ n₂ r) ->\n             eval σ₂ (m₁ • m₂) (n₁ • n₂).\n\n\n(**  Syntactic types have decicable equality, which\n     implies injectivity for dependent pairs with\n     (syntactic) types as the type being depended upon.\n  *)\nLemma inj_pair2_ty : forall (F:ty -> Type) τ x y,\n  existT F τ x = existT F τ y -> x = y.\nProof.\n  intros.\n  apply Eqdep_dec.inj_pair2_eq_dec in H. auto.\n  decide equality.\nQed.\n\nLtac inj_ty :=\n  repeat match goal with\n           [ H : existT _ _ ?x = existT _ _ ?y |- _ ] =>\n             apply inj_pair2_ty in H; subst\n           end.\n\nLtac inv H :=\n  inversion H; subst; inj_ty; subst.\n\n\n(** Values are terms that evaluate to themselves.\n  *)\nDefinition value σ (t:term σ) := eval _ t t.\nArguments value [σ] t.\n\n(**  Here are some basic techincal results  \n     about the operational semantics.\n  *)\nLemma eval_value τ x y :\n  eval τ x y -> value y.\nProof.\n  intro H. induction H.\n  apply ebool.\n  apply eI.\n  apply eK.\n  apply eS.\n  apply eIF.\n  apply eY.\n  auto.\n  apply eapp2; auto.\nQed.\n\nLemma redex_eq τ₁ τ₂ x y z1 z2 :\n  redex τ₁ τ₂ x y z1 ->\n  redex τ₁ τ₂ x y z2 ->\n  z1 = z2.\nProof.\n  intros; inv H; inv H; inv H0; auto.\nQed.\n\nLemma eval_eq τ x y1 y2 :\n  eval τ x y1 -> eval τ x y2 -> y1 = y2.\nProof.\n  intro H. revert y2.\n  induction H.\n\n  intros. inv H. auto.\n  intros. inv H. auto.\n  intros. inv H. auto.\n  intros. inv H. auto.\n  intros. inv H. auto.\n  intros. inv H. auto.\n\n  intros. inv H3.\n  apply IHeval1 in H9.\n  apply IHeval2 in H10.\n  subst n₁0 n₂0.\n  assert (r = r0).\n  eapply redex_eq; eauto.\n  subst r0.\n  apply IHeval3; auto.\n  apply IHeval1 in H9.\n  apply IHeval2 in H10.\n  subst n₁0 n₂0.\n  elim H11; eauto.\n\n  intros. inv H2.\n  apply IHeval1 in H8.\n  apply IHeval2 in H9.\n  subst n₁0 n₂0.\n  elim H1. eauto.\n  f_equal; auto.\nQed.\n\nLemma eval_trans τ x y z :\n  eval τ x y -> eval τ y z -> eval τ x z.\nProof.\n  intros.\n  replace z with y; auto.\n  eapply eval_eq with y; auto.\n  eapply eval_value; eauto.\nQed.\n\nLemma eval_app_congruence σ₁ σ₂ : forall x x' y y' z,\n  (forall q, eval _ x q -> eval _ x' q) ->\n  (forall q, eval _ y q -> eval _ y' q) ->\n  eval _ (@tapp σ₁ σ₂ x y) z ->\n  eval _ (@tapp σ₁ σ₂ x' y') z.\nProof.\n  intros.\n  inv H1.\n  apply H in H7.\n  apply H0 in H8.\n  eapply eapp1; eauto.\n  apply eapp2; auto.\nQed.\n\nLemma eval_no_redex : forall σ₁ σ₂ x x',\n  eval σ₂ x x' ->\n  forall m₁ m₂ n₁ n₂ r,\n    x' = @tapp σ₁ σ₂ m₁ m₂ ->\n    eval _ m₁ n₁ -> eval _ m₂ n₂ -> redex _ _ n₁ n₂ r -> False.\nProof.\n  do 5 intro. induction H; intros; try discriminate; subst.\n  eapply IHeval3; eauto.\n  inv H2.\n  assert (m₂0 = n₂0).\n  eapply eval_eq; eauto.\n  apply eval_trans with m₂0; auto.\n  assert (m₁0 = n₁0).\n  eapply eval_eq; eauto.\n  apply eval_trans with m₁0; auto.\n  subst.\n  apply H1. eauto.\nQed.\n\n\nLemma value_app_inv σ₁ σ₂ x y :\n  value (@tapp σ₁ σ₂ x y) ->\n  value x /\\ value y.\nProof.\n  intros. inv H.\n  elimtype False.\n  eapply eval_no_redex.\n  apply H8. reflexivity. eauto. eauto. eauto.\n  split; auto.\nQed.  \n\n(*\nLemma eval_app_inv σ₁ σ₂ x y z :\n  eval _ (@tapp σ₁ σ₂ x y) z ->\n  exists x', exists y',\n    eval _ x x' /\\ eval _ y y' /\\\n    eval _ (x' • y') z.\nProof.\n  intros. inv H.\n  exists n₁. exists n₂.\n  intuition.\n  eapply eapp1.\n  eapply eval_value; eauto.\n  eapply eval_value; eauto.\n  eauto. auto.\n  exists n₁. exists n₂.\n  intuition.\n  apply eapp2.\n  eapply eval_value; eauto.\n  eapply eval_value; eauto.\n  auto.\nQed.\n*)\n\n(**  \"Inert\" terms are those that will not evaluate if applied to\n     one more argument.  We prove that every term at function type\n     is either intert or forms a redex if applied to another term.\n  *)\nInductive inert : forall σ₁ σ₂, term (σ₁ ⇒ σ₂) -> Prop :=\n  | inert_K : forall σ₁ σ₂,\n                  inert _ _ (tK σ₁ σ₂)\n  | inert_S1 : forall σ₁ σ₂ σ₃,\n                  inert _ _ (tS σ₁ σ₂ σ₃)\n  | inert_S2 : forall σ₁ σ₂ σ₃ x,\n                  inert _ _ (tS σ₁ σ₂ σ₃ • x)\n  | inert_IF1 : forall σ,\n                  inert _ _ (tIF σ)\n  | inert_IF2 : forall σ x,\n                  inert _ _ (tIF σ • x)\n  | inert_Y : forall σ₁ σ₂,\n                  inert _ _ (tY σ₁ σ₂).\n\n\nFixpoint tmsize τ (x:term τ) : nat :=\n  match x with\n  | tapp a b => (1 + tmsize _ a + tmsize _ b)%nat\n  | _ => 1%nat\n  end.\n\nLemma redex_inert_false : forall σ₁ σ₂ f g r,\n  redex σ₁ σ₂ f g r ->\n  inert σ₁ σ₂ f ->\n  False.\nProof.\n  intros. inv H; inv H0.\nQed.\n\nLemma redex_or_inert' n : \n  forall τ (x:term τ) σ₁ σ₂ (f:term (σ₁ ⇒ σ₂))\n    (Hτ : τ = (σ₁ ⇒ σ₂)%ty)\n    (Hx : eq_rect τ term x _ Hτ = f)\n    (Hsz : tmsize τ x = n),\n    value f ->\n    (forall g, exists r, redex σ₁ σ₂ f g r) \\/ inert σ₁ σ₂ f.\nProof.\n  induction n using (well_founded_induction lt_wf).\n  intros τ x. rename H into Hind.\n  destruct x; intros; try discriminate.\n\n  subst σ₂. simpl in *. subst n f.\n  destruct (value_app_inv _ _ _ _ H).\n  assert (Hx1:tmsize _ x1 < S (tmsize _ x1 + tmsize _ x2)).\n  lia.\n  generalize (Hind (tmsize _ x1) Hx1 _ _ _ _ x1\n    (refl_equal _) (refl_equal _) (refl_equal _) H0).\n  intros. destruct H2. \n  destruct (H2 x2).\n  elimtype False. eapply eval_no_redex.\n  apply H. reflexivity. apply H0. apply H1. eauto.\n  inv H2. \n  left; intros. econstructor. econstructor.\n  right. constructor.\n  left; intros. econstructor. econstructor.\n  right. constructor.\n  destruct (value_app_inv _ _ _ _ H0).\n  inv H4.\n  left; intros. destruct b.\n  econstructor. econstructor.\n  econstructor. econstructor.\n  simpl in *.\n  inv H13.\n  elimtype False. eapply eval_no_redex.\n  apply H13. reflexivity. eauto. eauto. eauto.\n  assert (Hm₁ : tmsize _ m₁ <\n         S (S (S (S (tmsize (σ₁ ⇒ ty_bool) m₁ + tmsize σ₁ m₂ + tmsize σ₂0 x2))))).\n  lia.\n  destruct (value_app_inv _ _ _ _ H4).\n  generalize (Hind _ Hm₁ _ _ _ _ m₁ \n    (refl_equal _) (refl_equal _) (refl_equal _) H5).\n  intros. destruct H11. destruct (H11 m₂).\n  elimtype False. eapply eval_no_redex.\n  apply H4. reflexivity. eauto. eauto. eauto.\n  inv H11.\n  assert (Hn₁ : tmsize _ n₁ <\n         S (S (S (S (tmsize (σ₁ ⇒ ty_bool) n₁ + tmsize σ₁ n₂ + tmsize σ₂0 x2))))).\n  lia.\n  destruct (value_app_inv _ _ _ _ H4). simpl in Hind.\n  generalize (Hind _ Hn₁ _ _ _ _ n₁\n    (refl_equal _) (refl_equal _) (refl_equal _) H6).\n  intros. destruct H13. destruct (H13 n₂).\n  elimtype False. eapply eval_no_redex.\n  apply H4. reflexivity. eauto. eauto. eauto.\n  inv H13.\n\n  left; intros. econstructor. econstructor.\n\n  inv Hτ.\n  replace Hτ with (refl_equal (σ₂ ⇒ σ₂)%ty). simpl.\n  left; intros. econstructor. econstructor.\n  apply Eqdep_dec.UIP_dec. decide equality.\n\n  inv Hτ. \n  replace Hτ with (refl_equal (σ₁0 ⇒ σ₂ ⇒ σ₁0)%ty). simpl.\n  right. constructor.\n  apply Eqdep_dec.UIP_dec. decide equality.\n  \n  inv Hτ.\n  replace Hτ with (refl_equal ((σ₁ ⇒ σ₂ ⇒ σ₃) ⇒ (σ₁ ⇒ σ₂) ⇒ σ₁ ⇒ σ₃)%ty).\n  simpl.\n  right. constructor.\n  apply Eqdep_dec.UIP_dec. decide equality.\n\n  inv Hτ.\n  replace Hτ with (refl_equal (ty_bool ⇒ σ ⇒ σ ⇒ σ)%ty).\n  simpl.\n  right. constructor.\n  apply Eqdep_dec.UIP_dec. decide equality.\n\n  inv Hτ.\n  replace Hτ with (refl_equal (((σ₁ ⇒ σ₂) ⇒ σ₁ ⇒ σ₂) ⇒ σ₁ ⇒ σ₂)%ty).\n  simpl.\n  right. constructor.\n  apply Eqdep_dec.UIP_dec. decide equality.\nQed.\n\nLemma redex_or_inert : \n  forall σ₁ σ₂ (f:term (σ₁ ⇒ σ₂)),\n    value f ->\n    (forall g, exists r, redex σ₁ σ₂ f g r) \\/ inert σ₁ σ₂ f.\nProof.\n  intros. \n  apply (redex_or_inert' (tmsize _ f) _ f _ _ f (refl_equal _));\n    simpl; auto.\nQed.\n\nLemma canonical_bool : forall x,\n  eval 2 x x -> \n  x = tbool true \\/ x = tbool false.\nProof.\n  intros. inv H.\n  destruct b; auto.\n\n  elimtype False.\n  eapply eval_no_redex.\n  apply H6. reflexivity. eauto. eauto. eauto.\n  inv H0. clear H0.\n  destruct (redex_or_inert _ _ n₁); auto.\n  elim H5; apply H0.\n  inv H0.\nQed.\n\n\n(**  Types are interpreted as pointed domains.  Booleans\n     are the flat domain over booleans and the arrow type\n     is the lifted strict function space.\n  *)\nFixpoint tydom (τ:ty) : ∂PLT :=\n  match τ with\n  | ty_bool => flat enumbool\n  | ty_arrow τ₁ τ₂ => colift (tydom τ₁ ⊸ tydom τ₂)\n  end.\n\n(**  Here we define the semantics of the Y combinator.\n  *)\nSection Ydefn.\n  Variables σ₁ σ₂:ty.\n\n  Definition Ybody\n    : U (colift (tydom (σ₁ ⇒ σ₂) ⊸ tydom (σ₁ ⇒ σ₂)))\n       → PLT.exp (U (tydom (σ₁ ⇒ σ₂))) (U (tydom (σ₁ ⇒ σ₂)))\n\n       (*w : U (colift (tydom (σ₁ ⇒ σ₂) ⊸ tydom (σ₁ ⇒ σ₂))) *)\n    := PLT.curry (*x:U (tydom (σ₁ ⇒ σ₂)))*) (strict_curry' (*y:U tydom σ₁ *)\n\n                                                          (* w *)    (* x *)    (*y*)\n        (strict_app' ∘ 〈strict_app' ∘ 〈π₁ ∘ π₁, π₂ ∘ π₁〉, π₂〉)\n       ).\n\n  Lemma Ybody_unroll : forall Γ \n    (f:Γ → U (tydom ((σ₁ ⇒ σ₂) ⇒ (σ₁ ⇒ σ₂))))\n    (x:Γ → U (tydom σ₁)),\n\n    semvalue x ->\n\n    let Yf := (fixes Ybody) ∘ f in\n\n    strict_app' ∘ 〈Yf, x〉 ≈\n    strict_app' ∘ 〈strict_app' ∘ 〈f,Yf〉 , x〉.\n  Proof.\n    intros. unfold Yf at 1.\n    rewrite fixes_unroll. unfold Ybody at 1.\n    rewrite PLT.curry_apply2.\n    rewrite <- (cat_assoc PLT).\n    rewrite strict_curry_app2'.\n    rewrite (PLT.pair_compose_commute false).\n    rewrite <- (cat_assoc PLT).\n    apply cat_respects. auto.\n    rewrite (PLT.pair_compose_commute false).\n    rewrite <- (cat_assoc PLT).\n    rewrite (PLT.pair_compose_commute false).\n    rewrite <- (cat_assoc PLT).\n    rewrite PLT.pair_commute1.        \n    rewrite PLT.pair_commute2.\n    rewrite PLT.pair_commute1.        \n    rewrite <- (cat_assoc PLT).\n    rewrite PLT.pair_commute1.        \n    rewrite PLT.pair_commute2.\n    rewrite (cat_ident2 PLT).    \n    apply PLT.pair_eq. auto. auto.\n    auto.\n  Qed.\n\n  Definition Ysem Γ \n    : Γ → U (tydom (((σ₁ ⇒ σ₂) ⇒ (σ₁ ⇒ σ₂)) ⇒ (σ₁ ⇒ σ₂)))\n    := strict_curry' (fixes Ybody ∘ π₂).\nEnd Ydefn.\n\nNotation \"'Λ' f\" := (strict_curry' f) : ski_scope.\n\n(**  The denotation of terms.  The denotation of\n     the S, K and I combinators a straightforward interpretation of the\n     usual lambda term into the strict lambda and strict application \n     denotation functions.\n  *)\nFixpoint denote (τ:ty) (m:term τ) : 1 → U (tydom τ) :=\n  match m in term τ return 1 → U (tydom τ) with\n  | tbool b => flat_elem' b\n  | tapp m₁ m₂ => strict_app' ∘ 〈〚m₁〛,〚m₂〛〉\n  | tI σ => Λ(π₂)\n  | tK σ₁ σ₂ => Λ(Λ(π₂ ∘ π₁))\n  | tS σ₁ σ₂ σ₃ => Λ(Λ(Λ(\n                     strict_app' ∘\n                       〈 strict_app' ∘ 〈π₂ ∘ π₁ ∘ π₁, π₂〉\n                       , strict_app' ∘ 〈π₂ ∘ π₁, π₂〉\n                       〉\n                      )))\n  | tIF σ => Λ(flat_cases' (fun b:bool =>\n                if b then Λ(Λ(π₂ ∘ π₁))\n                     else Λ(Λ(π₂))\n                ))\n  | tY σ₁ σ₂ => Ysem σ₁ σ₂ 1\n  end\n where \"〚 m 〛\" := (denote _ m) : ski_scope.\n\n\n(**  This mutual induction shows that operational\n     values have semantic values as denotations,\n     and that inert operational values yield \n     semantic values when applied to any semantic value.\n  *)\nLemma value_inert_semvalue : forall n,\n  (forall σ x,\n    tmsize _ x = n ->\n    eval σ x x -> semvalue 〚x〛) /\\\n  (forall σ₁ σ₂ x (y:1 → U (tydom σ₁)),\n    tmsize _ x = n ->\n    value x ->\n    inert σ₁ σ₂ x ->\n    semvalue y ->\n    semvalue (strict_app' ∘ 〈〚x〛, y〉)).\nProof.\n  intro n. induction n using (well_founded_induction lt_wf).\n\n  split; intros. \n  inv H1; simpl.\n  apply flat_elem'_semvalue.\n\n  apply strict_curry'_semvalue.  \n  apply strict_curry'_semvalue.  \n  apply strict_curry'_semvalue.  \n  apply strict_curry'_semvalue.  \n  unfold Ysem. apply strict_curry'_semvalue.\n\n  elimtype False.\n  eapply eval_no_redex.\n  apply H8. reflexivity. eauto. eauto. eauto.\n\n  inv H2. clear H2.\n  destruct (redex_or_inert _ _ n₁); auto.\n  elim H7; auto.\n  simpl in H.\n  assert (Hm1 : (tmsize _ n₁) < S (tmsize _ n₁ + tmsize _ n₂)).\n  lia.\n  destruct (H _ Hm1).\n  apply H3; auto.\n  clear H2 H3.\n  assert (Hm2 : (tmsize _ n₂) < S (tmsize _ n₁ + tmsize _ n₂)).\n  lia.\n  destruct (H _ Hm2).\n  apply H2; auto.\n\n\n  inv H2; simpl.\n\n  rewrite strict_curry_app'; auto.\n  apply strict_curry'_semvalue2.\n\n  rewrite strict_curry_app'; auto.\n  apply strict_curry'_semvalue2.\n\n  rewrite strict_curry_app'; auto.\n  rewrite strict_curry_app2'; auto.\n  apply strict_curry'_semvalue2.\n  destruct (value_app_inv _ _ _ _ H1); auto.\n  simpl in H.\n  assert (tmsize _ x0 < S (S (tmsize _ x0))). lia.\n  destruct (H _ H5). apply (H6 _ x0); auto.\n\n  rewrite strict_curry_app'; auto.\n  destruct (flat_elem_canon enumbool y H3) as [b ?].\n  rewrite H0.\n  simpl.\n  rewrite flat_cases_elem'.\n  destruct b.\n  apply strict_curry'_semvalue2.\n  apply strict_curry'_semvalue2.\n\n  rewrite strict_curry_app'; auto.\n  destruct (value_app_inv _ _ _ _ H1); auto.\n  destruct (canonical_bool x0); auto; subst x0; simpl.\n  rewrite flat_cases_elem'.\n  rewrite strict_curry_app2'; auto.\n  apply strict_curry'_semvalue2.\n  rewrite flat_cases_elem'.\n  rewrite strict_curry_app2'; auto.\n  apply strict_curry'_semvalue2.\n\n  destruct (value_app_inv _ _ _ _ H1); auto.\n  simpl in H.\n  assert (tmsize _ x0 < S (S (tmsize _ x0))). lia.\n  destruct (H _ H5). apply (H6 _ x0); auto.\n  \n  unfold Ysem.\n  rewrite strict_curry_app'; auto.\n  rewrite (fixes_unroll _ _ (Ybody σ₁0 σ₂0)).\n  unfold Ybody at 1.\n  rewrite PLT.curry_apply2.\n  rewrite <- (cat_assoc PLT).\n  rewrite <- (cat_assoc PLT).\n  apply strict_curry'_semvalue2.\nQed.\n\nLemma value_semvalue : forall σ (x:term σ),\n  value x -> semvalue 〚x〛.\nProof.\n  intros. destruct (value_inert_semvalue (tmsize _ x)); auto.\nQed.\n\nLemma inert_semvalue σ₁ σ₂ x y :    \n  value x -> inert σ₁ σ₂ x -> semvalue y ->\n  semvalue (strict_app' ∘ 〈〚x〛, y 〉).\nProof.\n  intros.\n  destruct (value_inert_semvalue (tmsize _ x)).\n  apply H3; auto.\nQed.\n\nHint Resolve value_semvalue.\n\n\n(**  Now we can show the soundness of redexes.\n  *)\nLemma redex_soundness : forall σ₁ σ₂ x y z,\n  value x ->\n  value y ->\n  redex σ₁ σ₂ x y z ->\n  strict_app' ∘ 〈〚x〛,〚y〛〉 ≈ 〚z〛.\nProof.\n  intros. inv H1.\n\n  inv H1. simpl.\n  rewrite strict_curry_app'; auto.\n  rewrite PLT.pair_commute2. auto.\n  \n  simpl.\n  rewrite strict_curry_app'; auto.\n  rewrite strict_curry_app2'; auto.\n  rewrite <- (cat_assoc PLT).\n  rewrite PLT.pair_commute1.\n  rewrite PLT.pair_commute2. auto.\n  destruct (value_app_inv _ _ _ _ H); auto.\n  \n  destruct (value_app_inv _ _ _ _ H).\n  destruct (value_app_inv _ _ _ _ H2). clear H4.\n  simpl.\n  rewrite strict_curry_app'; auto.\n  rewrite strict_curry_app2'; auto.\n  rewrite strict_curry_app2'; auto.\n  repeat rewrite <- (cat_assoc PLT).\n  rewrite (PLT.pair_compose_commute false).\n  repeat rewrite <- (cat_assoc PLT).\n  rewrite (PLT.pair_compose_commute false).\n  repeat rewrite <- (cat_assoc PLT).\n  repeat rewrite PLT.pair_commute1.\n  repeat rewrite PLT.pair_commute2.\n  rewrite (PLT.pair_compose_commute false).\n  repeat rewrite <- (cat_assoc PLT).\n  repeat rewrite PLT.pair_commute1.\n  repeat rewrite PLT.pair_commute2.\n  auto.\n  apply (value_semvalue _ g); auto.\n  apply (value_semvalue _ f); auto.\n  \n  destruct (value_app_inv _ _ _ _ H). clear H2.\n  simpl.\n  rewrite strict_curry_app'; auto.\n  rewrite flat_cases_elem'.\n  rewrite strict_curry_app2'; auto.\n  rewrite strict_curry_app2'; auto.\n  repeat rewrite <- (cat_assoc PLT).\n  repeat rewrite PLT.pair_commute1.\n  repeat rewrite PLT.pair_commute2. auto.\n  apply flat_elem'_semvalue.\n  \n  destruct (value_app_inv _ _ _ _ H). clear H2.\n  inv H1.\n  simpl.\n  rewrite strict_curry_app'; auto.\n  rewrite flat_cases_elem'.\n  rewrite strict_curry_app2'; auto.\n  rewrite strict_curry_app2'; auto.\n  repeat rewrite PLT.pair_commute2. auto.\n  apply flat_elem'_semvalue.\n\n  destruct (value_app_inv _ _ _ _ H). clear H1 H2.\n  simpl.    \n  unfold Ysem.\n  rewrite strict_curry_app'; auto.\n  rewrite fixes_unroll at 1. unfold Ybody at 1.\n  rewrite PLT.curry_apply2.\n  rewrite <- (cat_assoc PLT).\n  rewrite PLT.pair_commute2.\n  rewrite <- (cat_assoc PLT).\n  rewrite strict_curry_app2'; auto.\n  rewrite <- (cat_assoc PLT).\n  apply cat_respects. auto.\n  rewrite (PLT.pair_compose_commute false).\n  rewrite PLT.pair_commute2.\n  apply PLT.pair_eq. 2: auto.\n  rewrite <- (cat_assoc PLT).\n  apply cat_respects. auto.\n  rewrite (PLT.pair_compose_commute false).\n  apply PLT.pair_eq.\n  rewrite <- (cat_assoc PLT).\n  rewrite PLT.pair_commute1.\n  rewrite (cat_assoc PLT).\n  rewrite PLT.pair_commute1.\n  apply cat_ident2.\n  rewrite <- (cat_assoc PLT).\n  rewrite PLT.pair_commute1.\n  rewrite (cat_assoc PLT).\n  rewrite PLT.pair_commute2.\n  rewrite <- (cat_assoc PLT).\n  rewrite PLT.pair_commute2.\n  auto.\n  apply (value_semvalue _ f). auto.\nQed.\n\n(** This leads easily into the soundness of evaluation.\n  *)\nLemma soundness : forall τ (m z:term τ),\n  eval τ m z -> 〚m〛≈〚z〛.\nProof.\n  intros. induction H; simpl; auto.\n  rewrite IHeval1.\n  rewrite IHeval2.\n  rewrite <- IHeval3.\n  apply redex_soundness.\n  eapply eval_value; eauto.\n  eapply eval_value; eauto.\n  auto.\n  rewrite IHeval1.\n  rewrite IHeval2.\n  auto.\nQed.\n\n\n(** * The logical relations lemma\n\n    Now define the logical relation for adequacy.  It is defined\n    by induction on the structure of types, in a standard way.    \n  *)\nFixpoint LR (τ:ty) : \n  term τ -> (1 → U (tydom τ)) -> Prop :=\n  match τ as τ' return \n    term τ' -> (1 → U (tydom τ')) -> Prop\n  with\n  | ty_bool => fun m h => exists b:bool,\n        m = tbool b /\\ h ≈ flat_elem' b\n  | ty_arrow σ₁ σ₂ => fun m h =>\n        forall n h',\n          LR σ₁ n h' -> value n -> semvalue h' ->\n          semvalue (strict_app' ∘ 〈h, h'〉) ->\n          exists z,\n            eval _ (m • n) z /\\\n            LR σ₂ z (strict_app' ∘ 〈h, h'〉)\n  end.\n\nLemma LR_equiv τ : forall m h h',\n  h ≈ h' -> LR τ m h -> LR τ m h'.\nProof.\n  induction τ; simpl. intros.\n  destruct H0 as [b [??]]. exists b; split; auto.\n  rewrite <- H; auto.\n  simpl; intros.\n  destruct (H0 n h'0 H1 H2 H3) as [z [??]]; auto.\n  revert H4. apply semvalue_equiv.\n  apply cat_respects; auto.\n  apply PLT.pair_eq; auto.\n  exists z.\n  split; auto.\n  revert H6. apply IHτ2.\n  apply cat_respects; auto.\n  apply PLT.pair_eq; auto.\nQed.\n\n(**  Now we need a host of auxilary definitions to state\n     the main lemmas regarding the logical relation.  These\n     definitions allow us to apply an arbitrary number of\n     arguments to a syntactic term and to the denotation of terms.\n  *)\nFixpoint lrtys (ts:list ty) (z:ty) :=\n  match ts with\n  | nil => z\n  | t::ts' => (t ⇒ (lrtys ts' z))%ty\n  end.\n\nFixpoint lrsyn (ts:list ty) : Type :=\n  match ts with\n  | nil => unit\n  | t::ts' => prod (lrsyn ts') (term t)\n  end.\n\nFixpoint lrsem (ts:list ty) : Type :=\n  match ts with\n  | nil => unit\n  | t::ts' => prod (lrsem ts') (1 → U (tydom t))\n  end.\n\nFixpoint lrhyps (ls:list ty) : lrsyn ls -> lrsem ls -> Prop :=\n  match ls with\n  | nil => fun _ _ => True\n  | t::ts => fun xs ys =>\n    (eval _ (snd xs) (snd xs) /\\ semvalue (snd ys)) /\\\n    LR t (snd xs) (snd ys) /\\ lrhyps ts (fst xs) (fst ys)\n  end.\n\nFixpoint lrapp (ls:list ty) z : lrsyn ls -> term (lrtys ls z) -> term z :=\n  match ls as ls' return lrsyn ls' -> term (lrtys ls' z) -> term z with\n  | nil => fun _ m => m\n  | t::ts => fun xs m => lrapp ts _ (fst xs) (m • (snd xs))\n  end.\n\nFixpoint lrsemapp (ls:list ty) z :\n  lrsem ls -> (1 → U (tydom (lrtys ls z))) -> (1 → U (tydom z)) :=\n  match ls as ls' return\n    lrsem ls' -> (1 → U (tydom (lrtys ls' z)))  -> (1 → U (tydom z))\n  with\n  | nil => fun _ h => h\n  | t::ts => fun ys h => lrsemapp ts _ (fst ys) (strict_app' ∘ 〈h, snd ys〉)\n  end.\n\nLemma eval_lrapp_congruence ls : forall xs τ m m' z,\n  (forall q, eval _ m q -> eval _ m' q) ->\n  eval τ (lrapp ls τ xs m) z ->\n  eval τ (lrapp ls τ xs m') z.\nProof.\n  induction ls; simpl; intros.\n  apply H. auto.\n  fold lrtys in *.\n\n  revert H0. apply IHls.\n  intros.\n  inv H0.\n  apply H in H6.\n  eapply eapp1; eauto.\n  eapply eapp2; eauto.\nQed.\n\nLemma lrsemapp_equiv ls : forall τ ys h h',\n  h ≈ h' -> lrsemapp ls τ ys h ≈ lrsemapp ls τ ys h'.\nProof.\n  induction ls; simpl; intros; auto.\n  apply IHls.\n  apply cat_respects; auto.\n  apply PLT.pair_eq; auto.\nQed.\n\nLemma semvalue_lrsemapp_out ls : forall τ ys h,\n   semvalue (lrsemapp ls τ ys h) -> semvalue h.\nProof.\n  induction ls; simpl; intros; auto.\n  apply IHls in H.\n  apply semvalue_app_out1' in H. auto.\nQed.\n\n(**  This fact is important in the base cases of the fundamental lemma; it allows\n     unwind a stack of applications.\n  *)\nLemma LR_under_apply ls :\n   forall (τ : ty) (m z0 : term (lrtys ls τ)) (xs : lrsyn ls) \n     (ys : lrsem ls) (h : 1 → U (tydom (lrtys ls τ))),\n   eval (lrtys ls τ) m z0 ->\n   lrhyps ls xs ys ->\n   semvalue (lrsemapp ls τ ys h) ->\n   LR (lrtys ls τ) z0 h ->\n   exists z : term τ,\n     eval τ (lrapp ls τ xs m) z /\\ LR τ z (lrsemapp ls τ ys h).\nProof.\n  induction ls; simpl; intros.\n  exists z0. split; auto.\n  destruct xs as [xs x].\n  destruct ys as [ys y]. simpl in *.\n  destruct H0 as [[??][??]].\n  destruct (H2 x y) as [z1 [??]]; auto.\n  apply semvalue_lrsemapp_out in H1. auto.\n\n  generalize (IHls τ (tapp z0 x) z1 xs ys (strict_app' ∘ PLT.pair h y)\n     H6 H5 H1 H7).\n  intros [q [??]].\n  exists q; split; auto.\n  revert H8.\n  apply eval_lrapp_congruence. intro.\n  apply eval_app_congruence; auto.\n  fold lrtys. intros.\n  apply eval_trans with z0; auto.\nQed.\n\n\n(**  If a sup is a semantic value, then there is some element of the\n     set is a semantic value.\n  *)\nLemma semvalue_sup (B:∂PLT) (XS:dirset (PLT.homset_cpo _ 1 (U B))) : \n  semvalue (∐XS) -> exists x, x ∈ XS /\\ semvalue x.\nProof.\n  intros.\n  destruct (H tt) as [q ?].\n  simpl in H0.\n  apply union_axiom in H0.\n  destruct H0 as [q' [??]].\n  apply image_axiom2 in H0.\n  destruct H0 as [q'' [??]].\n  simpl in *.\n  exists q''. split; auto.\n  red; intro. destruct g.\n  exists q. rewrite <- H2; auto.\nQed.\n\n(**  The logical relation is admissible.  This is key to the\n     fundamental lemma case for Y.\n  *)\nLemma LR_admissible τ : \n  forall m (XS:dirset (PLT.homset_cpo _ 1 (U (tydom τ)))),\n  semvalue (∐XS) ->\n  (forall x, x ∈ XS -> semvalue x -> LR τ m x) -> LR τ m (∐XS).\nProof.\n  induction τ; simpl. intros.\n\n  apply semvalue_sup in H. destruct H as [x [??]].\n  destruct (H0 x) as [b [??]]; auto.\n  subst m. exists b. split; auto.\n  split.\n  apply CPO.sup_is_least.\n  hnf; simpl; intros.\n  destruct (proj2_sig XS (x::x0::nil)). hnf; auto.\n  hnf; intros. apply cons_elem in H4.\n  destruct H4. rewrite H4. auto.\n  rewrite (cons_elem _ x0 nil a) in H4.\n  destruct H4. rewrite H4. auto.\n  apply nil_elem in H4. elim H4.\n  destruct H4.\n  assert (x1 ≈ x).  \n  assert (x ≤ x1). apply H4. apply cons_elem; auto.\n  split; auto.\n  hnf; intros.\n  rewrite H3 in H6.\n  assert ((tt,Some b : U (flat enumbool)) ∈ PLT.hom_rel x1).\n  apply H6.\n  unfold flat_elem'.\n  apply PLT.compose_hom_rel. exists (Some tt).\n  split. simpl. apply adj_unit_rel_elem. auto.\n  apply U_hom_rel. right.\n  exists tt. exists b. split; auto.\n  apply PLT.compose_hom_rel; auto.\n  exists tt. split.\n  simpl. apply eprod_elem. split; simpl.\n  apply eff_complete. apply single_axiom; auto.\n  simpl. apply single_axiom; auto.\n  destruct H3. apply H9.\n  destruct a. unfold flat_elem'.\n  apply PLT.compose_hom_rel.\n  exists (Some tt). split.\n  simpl. apply adj_unit_rel_elem; simpl; auto.\n  destruct c; auto.\n  apply U_hom_rel.\n  destruct c0; auto. right.\n  exists tt. exists c0. split; auto.\n  apply PLT.compose_hom_rel.\n  exists tt.\n  split. simpl.\n  apply eprod_elem. split.\n  apply eff_complete. apply single_axiom; auto.\n  simpl. apply single_axiom; auto.\n  cut (c0 = b). intros. subst c0; auto.\n  destruct c.\n  destruct (PLT.hom_directed _ _ _ x1 tt ((Some c0::Some b::nil))).\n  hnf; auto.\n  red; intros.\n  rewrite (cons_elem _ _ _ a) in H10. destruct H10. rewrite H10.\n  apply erel_image_elem. auto.\n  apply cons_elem in H10. destruct H10. rewrite H10.\n  apply erel_image_elem. auto.\n  apply nil_elem in H10. elim H10.\n  destruct H10.\n  assert (Some c0 ≤ x2).\n  apply H10. apply cons_elem; auto.\n  assert (Some (b:enumbool) ≤ x2).\n  apply H10. apply cons_elem. right. apply cons_elem; auto.\n  destruct x2. hnf in H12. hnf in H13.\n  subst c0. subst b. auto.\n  elim H12.\n\n  rewrite <- H3. rewrite <- H6.\n  apply H4.\n  apply cons_elem. right.\n  apply (cons_elem _ x0). auto.\n  apply CPO.sup_is_ub. rewrite <- H3. auto.\n\n  simpl; intros.\n  set (g := (postcompose _ strict_app' ∘ pair_left (U (tydom (τ1 ⇒ τ2))) h')).\n  assert (strict_app' ∘ PLT.pair (∐XS) h' ≈ g (∐XS)).\n  simpl; auto.\n  assert (strict_app' ∘ PLT.pair (∐XS) h' ≈ ∐(image g XS)).\n  rewrite H5.\n  apply CPO.continuous_sup'.\n  apply continuous_sequence.\n  apply postcompose_continuous.\n  apply pair_left_continuous.\n\n  assert (exists q, q ∈ XS /\\\n    semvalue (strict_app' ∘ PLT.pair q h')).\n  rewrite H6 in H4.\n  destruct (H4 tt) as [q ?].\n  simpl.\n  simpl in H7.\n  apply union_axiom in H7.\n  destruct H7 as [q' [??]].\n  apply image_axiom2 in H7.\n  destruct H7 as [q'' [??]].\n  apply image_axiom2 in H7.\n  destruct H7 as [q''' [??]].\n  exists q'''. split; auto.\n  rewrite H9 in H8.\n  rewrite H10 in H8.\n  red; intros.\n  exists q. auto.\n  destruct H7 as [q [??]].\n  assert (semvalue q).\n  apply semvalue_app_out1' in H8. auto.\n  destruct (H0 q H7 H9 n h' H1 H2 H3 H8) as [z [??]].\n  exists z. split; auto.\n  cut (LR τ2 z (∐(image g XS))).\n  apply LR_equiv; auto.\n  apply IHτ2; auto.\n  rewrite <- H6. auto.\n\n  intros.\n  apply image_axiom2 in H12. destruct H12 as [y [??]].\n  rewrite H14 in H13.\n  simpl in H13.\n  assert (semvalue y).\n  apply semvalue_app_out1' in H13. auto.\n  destruct (H0 y H12 H15 n h' H1 H2 H3) as [z' [??]]; auto.\n  assert (z = z').\n  eapply eval_eq; eauto. subst z'.\n  revert H17.\n  apply LR_equiv; auto.\nQed.\n\n(**  Here we prove fundamental lemma case for he main body\n     of Y combinator. This proof goes by Scott induction.\n  *)\nLemma LR_Ybody σ₁ σ₂\n  (f:term ((σ₁ ⇒ σ₂) ⇒ σ₁ ⇒ σ₂)) hf :\n  LR _ f hf -> value f -> semvalue hf ->\n\n  forall (x:term σ₁) hx,\n    LR σ₁ x hx -> value x -> semvalue hx ->\n    semvalue (strict_app' ∘ 〈fixes (Ybody σ₁ σ₂) ∘ hf, hx〉) ->\n    exists z:term σ₂,\n      eval _ (tY σ₁ σ₂ • f • x) z /\\\n      LR _ z (strict_app' ∘ 〈fixes (Ybody σ₁ σ₂) ∘ hf, hx〉).\nProof.\n  intros Hf1 Hf2 Hf3. unfold fixes.\n  apply scott_induction.\n  split.\n\n  intros.\n  apply semvalue_app_out1' in H2.\n  destruct (H2 tt) as [q ?].\n  apply (PLT.compose_hom_rel _ _ _ _ hf ⊥ tt (Some q : (colift _))) in H3.\n  destruct H3 as [?[??]].  \n  elimtype False. revert H4.\n  clear. simpl bottom.\n  intros.\n  unfold plt_hom_adj' in H4; simpl in H4.\n  apply PLT.compose_hom_rel in H4.\n  destruct H4 as [?[??]].\n  simpl in H.\n  (* FIXME: In 8.6, Coq gets stuck in a reduction loop if we do not apply this\n     generalized lemma *)\n  assert (aurl : forall (X : PLT) (x : X) (x' : U (L X)),\n             (x, x') ∈ adj_unit_rel X (PLT.effective X) <-> x' ≤ Some x).\n  { intros Y y y'. exact (@adj_unit_rel_elem (PLT.ord Y) _ y y'). }\n  apply aurl in H. clear aurl.\n  apply U_hom_rel in H0.\n  destruct H0. discriminate.\n  destruct H0 as [? [? [?[??]]]].\n  subst x. inv H2.\n  simpl in H0.\n  apply union_axiom in H0.\n  destruct H0 as [?[??]].\n  apply image_axiom2 in H0.\n  destruct H0 as [?[??]].\n  apply empty_elem in H0. elim H0.\n\n  intros.\n  set (g := (postcompose _ strict_app' \n            ∘ pair_left (U (tydom (σ₁ ⇒ σ₂))) hx\n            ∘ precompose _ hf)).\n  assert (strict_app' ∘ PLT.pair (∐XS ∘ hf) hx ≈ g (∐XS)). auto.\n  assert (strict_app' ∘ PLT.pair (∐XS ∘ hf) hx ≈ ∐(image g XS)).\n  rewrite H5.\n\n  apply CPO.continuous_sup'.\n  apply continuous_sequence.\n  apply continuous_sequence.\n  apply postcompose_continuous.\n  apply pair_left_continuous.\n  apply precompose_continuous.\n\n  assert (exists q, q ∈ XS /\\\n    semvalue (strict_app' ∘ PLT.pair (q ∘ hf) hx)).\n  rewrite H6 in H4.\n  apply semvalue_sup in H4.\n  destruct H4 as [q [??]].\n  apply image_axiom2 in H4 as [q' [??]].\n  exists q'. split; auto.\n  simpl in H8. rewrite <- H8. auto.\n\n  destruct H7 as [q [??]].\n  destruct (H0 q H7 x hx H1 H2 H3) as [z [??]]; auto.\n  exists z.\n  split; auto.\n  cut (LR σ₂ z (∐(image g XS))).  \n  apply LR_equiv; auto.\n  apply LR_admissible.\n  rewrite <- H6; auto.\n  intros.\n  apply image_axiom2 in H11. destruct H11 as [y [??]].\n  simpl in H13. rewrite H13 in H12.\n  destruct (H0 y H11 x hx) as [z' [??]]; auto.\n  assert (z = z'). eapply eval_eq; eauto. subst z'.\n  revert H15; apply LR_equiv; auto.  \n\n  intros.\n  destruct (H0 x0 hx H1 H2 H3) as [z [??]]. rewrite H; auto.\n  exists z; split; auto.\n  revert H6. apply LR_equiv. rewrite <- H; auto.\n\n  intros.\n  simpl in H3. unfold fixes_step in H3.\n  unfold Ybody in H3.\n  rewrite PLT.curry_apply2 in H3.\n  rewrite <- (cat_assoc PLT) in H3.\n  rewrite (PLT.pair_compose_commute false) in H3.\n  rewrite strict_curry_app2' in H3.\n  rewrite <- (cat_assoc PLT) in H3.\n  rewrite (PLT.pair_compose_commute false) in H3.\n  rewrite PLT.pair_commute2 in H3.  \n  rewrite <- (cat_assoc PLT) in H3.\n  rewrite (PLT.pair_compose_commute false) in H3.\n  rewrite <- (cat_assoc PLT) in H3.\n  rewrite PLT.pair_commute1 in H3.\n  rewrite PLT.pair_commute1 in H3.\n  rewrite <- (cat_assoc PLT) in H3.\n  rewrite PLT.pair_commute1 in H3.\n  rewrite PLT.pair_commute2 in H3.\n  rewrite (cat_ident2 PLT) in H3.    \n\n  simpl in Hf1.\n  destruct (Hf1 (tapp (tY _ _) f) (x ∘ hf)) as [q [??]]; auto.\n  apply eapp2. apply eY. auto.\n  intros [? Hr]; inv Hr.\n  apply semvalue_app_out1' in H3.\n  apply semvalue_app_out2' in H3. auto.\n  apply semvalue_app_out1' in H3. auto.\n  destruct (H5 x0 hx) as [q' [?]]; auto.\n  exists q'. split.\n  eapply eapp1.\n  apply eapp2. apply eY. eauto.\n  intros [? Hr]; inv Hr. eauto.\n  apply redex_Y.\n  revert H6. apply eval_app_congruence; intros; auto.\n  apply eval_trans with q; auto.\n  revert H7. apply LR_equiv.\n  simpl. unfold fixes_step. unfold Ybody.\n  symmetry.\n\n  rewrite PLT.curry_apply2.\n  rewrite <- (cat_assoc PLT).\n  rewrite (PLT.pair_compose_commute false).\n  rewrite strict_curry_app2'.\n  rewrite <- (cat_assoc PLT).\n  rewrite (PLT.pair_compose_commute false).\n  rewrite PLT.pair_commute2.\n  rewrite <- (cat_assoc PLT).\n  rewrite (PLT.pair_compose_commute false).\n  rewrite <- (cat_assoc PLT).\n  rewrite PLT.pair_commute1.\n  rewrite PLT.pair_commute1.\n  rewrite <- (cat_assoc PLT).\n  rewrite PLT.pair_commute1.\n  rewrite PLT.pair_commute2.\n  rewrite (cat_ident2 PLT).\n  auto.\n  apply semvalue_app_out2' in H3. auto.\n  auto.\nQed.\n\n(**  Now we can prove the fundamental lemma cases for\n     each of the system combinators.\n  *)\n\nLemma LR_I σ : LR _ (tI σ) 〚tI σ〛.\nProof.\n  simpl. intros.\n  exists n. split.\n  eapply eapp1.\n  apply eI. apply H0.\n  apply redex_I. auto.\n  revert H. apply LR_equiv. rewrite strict_curry_app'.\n  rewrite PLT.pair_commute2; auto. auto.\nQed.\n\nLemma LR_K σ₁ σ₂ : LR _ (tK σ₁ σ₂) 〚tK σ₁ σ₂〛.\nProof.\n  simpl. intros.\n\n  exists (tapp (tK _ _) n). split.\n  apply eapp2. apply eK. auto.\n  intros [? Hr]. inv Hr.\n  intros.\n  exists n. split.\n  eapply eapp1. \n  apply eapp2. apply eK. eauto.\n  intros [? Hr]. inv Hr. eauto.\n  apply redex_K. auto.\n  revert H.\n  apply LR_equiv.\n  rewrite strict_curry_app'.\n  rewrite strict_curry_app2'.\n  rewrite <- (cat_assoc PLT).\n  rewrite PLT.pair_commute1.\n  rewrite PLT.pair_commute2.\n  auto. auto. auto.\nQed.\n\nLemma LR_S σ₁ σ₂ σ₃ : LR _ (tS σ₁ σ₂ σ₃) 〚tS σ₁ σ₂ σ₃〛.\nProof.\n  simpl; intros.\n  exists (tapp (tS _ _ _) n). split.\n  apply eapp2. apply eS. auto.\n  intros [? Hr]; inversion Hr.\n  intros.\n  exists (tapp (tapp (tS _ _ _) n) n0). split.\n  apply eapp2. apply eapp2. apply eS. auto.\n  intros [? Hr]; inversion Hr. auto.\n  intros [? Hr]; inversion Hr. intros.\n\n  assert ( (strict_app'\n           ∘ PLT.pair\n               (strict_app'\n                ∘ PLT.pair\n                    (strict_app'\n                     ∘ PLT.pair\n                         (strict_curry'\n                            (strict_curry'\n                               (strict_curry'\n                                  (strict_app'\n                                   ∘ PLT.pair\n                                       (strict_app'\n                                        ∘ PLT.pair (π₂ ∘ π₁ ∘ π₁) π₂)\n                                       (strict_app'\n                                        ∘ PLT.pair (π₂ ∘ π₁) π₂))))) h')\n                    h'0) h'1)\n     ≈\n     strict_app' ∘ PLT.pair\n       (strict_app' ∘ PLT.pair h' h'1)\n       (strict_app' ∘ PLT.pair h'0 h'1)).\n  clear -H9 H5 H1.\n\n  rewrite strict_curry_app'; auto.\n  rewrite strict_curry_app2'; auto.\n  rewrite strict_curry_app2'; auto.\n  rewrite <- (cat_assoc PLT).\n  apply cat_respects. auto.\n  rewrite <- (cat_assoc PLT).\n  rewrite (PLT.pair_compose_commute false).\n  apply PLT.pair_eq.\n  rewrite <- (cat_assoc PLT).\n  rewrite (PLT.pair_compose_commute false).\n  apply cat_respects. auto.\n  apply PLT.pair_eq.\n  rewrite <- (cat_assoc PLT).\n  rewrite <- (cat_assoc PLT).\n  rewrite PLT.pair_commute1.\n  rewrite PLT.pair_commute1.\n  rewrite PLT.pair_commute2.\n  auto.\n  rewrite PLT.pair_commute2.\n  auto.\n  rewrite <- (cat_assoc PLT).\n  apply cat_respects; auto.\n  rewrite (PLT.pair_compose_commute false).\n  apply PLT.pair_eq; auto.\n  rewrite <- (cat_assoc PLT).\n  rewrite PLT.pair_commute1.\n  rewrite PLT.pair_commute2.\n  auto.\n  rewrite PLT.pair_commute2.\n  auto.\n\n  rewrite H11 in H10.\n\n  destruct (H3 n1 h'1) as [z0 [??]]; auto; clear H3.\n  apply semvalue_app_out2' in H10. auto.\n  \n  destruct (H n1 h'1) as [z1 [??]]; auto; clear H.\n  apply semvalue_app_out1' in H10. auto.\n  \n  destruct (H14 z0 (strict_app' ∘ PLT.pair h'0 h'1)) as [z2 [??]]; auto; clear H14.\n  eapply eval_value; eauto.\n  apply semvalue_app_out2' in H10. auto.\n  exists z2. split.\n  eapply eapp1. \n  apply eapp2. apply eapp2. apply eS. eauto.\n  intros [? Hr]; inv Hr. eauto.\n  intros [? Hr]; inv Hr. eauto.\n  apply redex_S.\n  revert H.\n  apply eval_app_congruence.\n  intros. apply eval_trans with z1; auto.\n  intros. apply eval_trans with z0; auto.\n  revert H15. apply LR_equiv. auto.\nQed.\n\nLemma LR_Y σ₁ σ₂ : LR _ (tY σ₁ σ₂) 〚tY σ₁ σ₂〛.\nProof.\n  simpl; intros.\n  exists (tapp (tY _ _) n).\n  split. apply eapp2. apply eY. auto.\n  intros [? Hr]; inv Hr.\n  intros.  \n  unfold Ysem in H6.\n  rewrite strict_curry_app' in H6.\n  rewrite <- (cat_assoc PLT) in H6.\n  rewrite PLT.pair_commute2 in H6.\n  destruct (LR_Ybody σ₁ σ₂ n h' H H0 H1 n0 h'0 H3 H4 H5 H6) as [z [??]].\n  exists z. split; auto.\n  revert H8. apply LR_equiv.\n  unfold Ysem.\n  rewrite strict_curry_app'.\n  rewrite <- (cat_assoc PLT).\n  rewrite PLT.pair_commute2.\n  auto.\n  auto.\n  auto.\nQed.\n\nLemma LR_IF σ : LR _ (tIF σ) 〚tIF σ〛.\nProof.\n  simpl. intros.\n  exists (tapp (tIF σ) n). split. apply eapp2.\n  apply eIF. auto.\n  intros [? Hr]. inv Hr.\n  intros.\n  exists (tapp (tapp (tIF σ) n) n0). split. apply eapp2. apply eapp2.\n  apply eIF. auto.\n  intros [? Hr]. inv Hr. auto.\n  intros [? Hr]. inv Hr.\n  intros.\n  destruct H as [b [??]]. subst n.\n  destruct b.\n  exists n0. split.\n  eapply eapp1. apply eapp2. apply eapp2.\n  apply eIF. apply ebool.\n  intros [? Hr]. inv Hr. eauto.\n  intros [? Hr]. inv Hr. eauto.\n  econstructor. auto.\n  revert H3. apply LR_equiv.\n  rewrite H11.\n  rewrite strict_curry_app'; auto.\n  rewrite flat_cases_elem'.\n  rewrite strict_curry_app2'; auto.\n  rewrite strict_curry_app2'; auto.\n  rewrite <- (cat_assoc PLT).\n  rewrite PLT.pair_commute1.\n  rewrite PLT.pair_commute2. auto.\n  apply flat_elem'_semvalue.  \n  exists n1.\n  split.\n  eapply eapp1. apply eapp2. apply eapp2.\n  apply eIF. apply ebool.\n  intros [? Hr]. inv Hr. eauto.\n  intros [? Hr]. inv Hr. eauto.\n  econstructor. auto.\n  revert H7. apply LR_equiv.\n  rewrite H11.\n  rewrite strict_curry_app'; auto.\n  rewrite flat_cases_elem'.\n  rewrite strict_curry_app2'; auto.\n  rewrite strict_curry_app2'; auto.\n  rewrite PLT.pair_commute2. auto.\n  apply flat_elem'_semvalue.  \nQed.\n\n(**  Now the fundamental lemma follows by induction on terms.\n  *)\nLemma fundamental_lemma : forall σ (n:term σ) ls τ m xs ys\n  (Hσ : σ = lrtys ls τ),\n  eq_rect σ term n (lrtys ls τ) Hσ = m ->\n  lrhyps ls xs ys ->\n  semvalue (lrsemapp ls τ ys 〚m〛) ->\n  exists z,\n    eval _ (lrapp ls τ xs m) z /\\\n    LR τ z (lrsemapp ls τ ys 〚m〛).\nProof.\n  induction n; intros.\n\n  (* bool case *)\n  destruct ls; simpl in *. subst τ.\n  simpl in H. subst m.\n  exists (tbool b).\n  split. apply ebool.\n  simpl.\n  exists b. split; auto.\n  inv Hσ.\n\n  (* application case *)\n  subst σ₂. simpl in H. subst m.\n\n  destruct (IHn2 nil σ₁ n2 tt tt (Logic.refl_equal _) (Logic.refl_equal _) I)\n    as [q2[??]]; auto.\n  simpl.\n  apply semvalue_lrsemapp_out in H1. simpl in H1.\n  apply semvalue_app_out2' in H1. auto.\n\n  destruct (IHn1 (σ₁::ls) _ n1 (xs, q2) (ys, denote σ₁ q2)\n    (Logic.refl_equal _) (Logic.refl_equal _)) as [q1 [??]].\n  simpl; intuition. eapply eval_value; eauto.\n  apply value_semvalue; auto.  eapply eval_value; eauto.\n  revert H2. apply LR_equiv.\n  simpl. simpl in H. apply soundness; auto.\n  simpl. revert H1.\n  apply semvalue_equiv.\n  apply lrsemapp_equiv.\n  simpl. apply cat_respects; auto.\n  apply PLT.pair_eq; auto.\n  apply soundness; auto.\n  exists q1. split.\n  revert H3.\n  simpl. apply eval_lrapp_congruence.\n  intro q. apply eval_app_congruence; intros; auto.\n  apply eval_trans with q2; auto.\n  revert H4.\n  apply LR_equiv. simpl.\n  apply lrsemapp_equiv.\n  simpl. apply cat_respects; auto.\n  apply PLT.pair_eq; auto.\n  symmetry.\n  apply soundness; auto.\n  \n  (* I case *)\n  cut (exists z : term (σ ⇒ σ),\n     eval (σ ⇒ σ) (tI σ) z /\\ LR (σ ⇒ σ) z (denote _ (tI _))).\n  revert H.\n  generalize (tI σ).\n  generalize Hσ.\n  rewrite Hσ. intro H.\n  replace H with (refl_equal (lrtys ls τ)). simpl. intros.\n  subst t. clear H Hσ. \n  destruct H3 as [z0 [??]].\n  eapply LR_under_apply; eauto.\n  apply Eqdep_dec.UIP_dec. decide equality.\n\n  exists (tI σ). split. apply eI. apply LR_I.\n\n  (* K case *)\n  cut (exists z,\n     eval _ (tK σ₁ σ₂) z /\\ LR _ z (denote _ (tK _ _))).\n  revert H.\n  generalize (tK σ₁ σ₂).\n  generalize Hσ.\n  rewrite Hσ. intro H.\n  replace H with (refl_equal (lrtys ls τ)). simpl. intros.\n  subst t. clear H Hσ. \n  destruct H3 as [z0 [??]].\n  eapply LR_under_apply; eauto.\n  apply Eqdep_dec.UIP_dec. decide equality.\n\n  exists (tK _ _). split. apply eK. apply LR_K.\n\n  (* S case *)\n  cut (exists z,\n     eval _ (tS σ₁ σ₂ σ₃) z /\\ LR _ z (denote _ (tS _ _ _))).\n  revert H.\n  generalize (tS σ₁ σ₂ σ₃).\n  generalize Hσ.\n  rewrite Hσ. intro H.\n  replace H with (refl_equal (lrtys ls τ)). simpl. intros.\n  subst t. clear H Hσ. \n  destruct H3 as [z0 [??]].\n  eapply LR_under_apply; eauto.\n  apply Eqdep_dec.UIP_dec. decide equality.\n\n  exists (tS _ _ _).\n  split. simpl. apply eS. apply LR_S.\n\n  (* IF case *)\n  cut (exists z,\n     eval _ (tIF σ) z /\\ LR _ z (denote _ (tIF _))).\n  revert H.\n  generalize (tIF σ).\n  generalize Hσ.\n  rewrite Hσ. intro H.\n  replace H with (refl_equal (lrtys ls τ)). simpl. intros.\n  subst t. clear H Hσ. \n  destruct H3 as [z0 [??]].\n  eapply LR_under_apply; eauto.\n  apply Eqdep_dec.UIP_dec. decide equality.\n\n  exists (tIF σ). split. apply eIF.\n  apply LR_IF.\n\n  (* Y case *)\n  cut (exists z,\n     eval _ (tY σ₁ σ₂) z /\\ LR _ z (denote _ (tY σ₁ σ₂))).\n  revert H.\n  generalize (tY σ₁ σ₂).\n  generalize Hσ.\n  rewrite Hσ. intro H.\n  replace H with (refl_equal (lrtys ls τ)). simpl. intros.\n  subst t. clear H Hσ. \n  destruct H3 as [z0 [??]].\n  eapply LR_under_apply; eauto.\n  apply Eqdep_dec.UIP_dec. decide equality.\n\n  exists (tY σ₁ σ₂). split. apply eY. apply LR_Y.\nQed.\n\n(**  A specialization of the fundamental lemma to empty contexts\n  *)\nLemma fundamental_lemma' : forall τ (m:term τ),\n  semvalue 〚m〛 ->\n  exists z, eval τ m z /\\ LR τ z 〚m〛.\nProof.\n  intros.\n  apply (fundamental_lemma τ m nil τ m tt tt (refl_equal _) (refl_equal _) I).\n  simpl. auto.\nQed.\n\n(** * Contextual equivalance and the adequacy theorem.\n\n     Now we define contextual equivalance.  Contexts here are\n     given in \"inside-out\" form, which makes the induction in the\n     adequacy proof significantly easier.\n  *)\nInductive context τ : ty -> Type :=\n  | cxt_top : context τ τ\n  | cxt_appl : forall σ₁ σ₂,\n                    term σ₁ ->\n                    context τ σ₂ ->\n                    context τ (σ₁ ⇒ σ₂)\n  | cxt_appr : forall σ₁ σ₂,\n                    term (σ₁ ⇒ σ₂) ->\n                    context τ σ₂ ->\n                    context τ σ₁.\n\nFixpoint plug τ σ (C:context τ σ) : term σ -> term τ :=\n  match C in context _ σ return term σ -> term τ with\n  | cxt_top _ => fun x => x\n  | cxt_appl _ σ₁ σ₂ t C' => fun x => plug τ _ C' (tapp x t)\n  | cxt_appr _ σ₁ σ₂ t C' => fun x => plug τ _ C' (tapp t x)\n  end.\n\nDefinition cxt_eq τ σ (m n:term σ):=\n  forall (C:context τ σ) (z:term τ),\n    eval τ (plug τ σ C m) z <-> eval τ (plug τ σ C n) z.\n\n(**  Adequacy means that terms with equivalant denotations\n     are contextually equivalant in any boolean context.\n  *)\nTheorem adequacy : forall τ (m n:term τ),\n  〚m〛≈〚n〛 -> cxt_eq 2 τ m n.\nProof.\n  intros. intro.\n  revert n m H.\n  induction C.\n\n  simpl; intros.\n  split; intros.\n  destruct (fundamental_lemma' _ m) as [zm [??]].\n  simpl.\n  apply semvalue_equiv with (denote _ z).\n  symmetry. apply soundness. auto.\n  apply value_semvalue. eapply eval_value; eauto.\n  destruct (fundamental_lemma' _ n) as [zn [??]].\n  simpl.\n  apply semvalue_equiv with (denote _ z).\n  symmetry. rewrite <- H.\n  apply soundness. auto.\n  apply value_semvalue. eapply eval_value; eauto.\n  destruct H2 as [b [??]].\n  destruct H4 as [b' [??]].\n  simpl in *.\n  rewrite H in H5. rewrite H5 in H6.\n  assert (b = b').\n  apply flat_elem'_inj in H6. auto.\n  exact tt.\n  subst b'.\n  subst zm zn.\n  assert (z = (tbool b)).\n  eapply eval_eq; eauto.\n  subst z. auto.\n\n  destruct (fundamental_lemma' _ m) as [zm [??]].\n  simpl.\n  apply semvalue_equiv with (denote _ z).\n  symmetry. rewrite H. apply soundness. auto.\n  apply value_semvalue. eapply eval_value; eauto.\n  destruct (fundamental_lemma' _ n) as [zn [??]].\n  simpl.\n  apply semvalue_equiv with (denote _ z).\n  symmetry. apply soundness. auto.\n  apply value_semvalue. eapply eval_value; eauto.\n  destruct H2 as [b [??]].\n  destruct H4 as [b' [??]].\n  simpl in *.\n  rewrite H in H5. rewrite H5 in H6.\n  assert (b = b').\n  apply flat_elem'_inj in H6. auto.\n  exact tt.\n  subst b'.\n  subst zm zn.\n  assert (z = (tbool b)).\n  eapply eval_eq; eauto.\n  subst z. auto.\n\n  simpl. intros.\n  apply IHC. simpl.\n  apply cat_respects; auto.\n  apply PLT.pair_eq; auto.\n\n  simpl; intros.\n  apply IHC. simpl.\n  apply cat_respects; auto.\n  apply PLT.pair_eq; auto.\nQed.\n\n(** Every term fails to evaluate iff the denotation is bottom. *)\nCorollary denote_bottom_nonvalue : forall τ (m:term τ),\n  (~exists z, eval τ m z) <-> 〚m〛 ≈ ⊥.\nProof.\n  intros. split; intro.\n\n  split. 2: apply bottom_least.\n  hnf. intros [u x] Hx. destruct x.\n  elimtype False.\n  destruct (fundamental_lemma' τ m) as [z [??]].\n  red; intros. destruct g. simpl.\n  exists c. auto.\n  elim H. eauto.\n  apply PLT.compose_hom_rel.    \n  simpl. exists None.\n  split.\n  apply adj_unit_rel_elem. hnf; auto.\n  apply U_hom_rel. auto.\n\n  intros [z ?].\n  assert (denote τ z ≈ ⊥).\n  rewrite <- soundness; eauto.\n  assert (value z).\n  eapply eval_value; eauto.\n  apply value_semvalue in H2.\n  hnf in H2.\n  destruct (H2 tt) as [x ?].\n  destruct H1. apply H1 in H3.\n  simpl bottom in H3.\n  apply (PLT.compose_hom_rel) in H3.\n  destruct H3 as [q [??]].\n  apply U_hom_rel in H5.\n  destruct H5.\n  inversion H5.\n  destruct H5 as [q' [?[??]]].\n  simpl in H5.\n  apply union_axiom in H5.\n  destruct H5 as [?[??]].\n  apply image_axiom2 in H5. destruct H5 as [? [??]].\n  apply empty_elem in H5. elim H5.\nQed.   \n\n(** These should print \"Closed under the global context\", meaning these\n    theorems hold without the use of any axioms.\n  *)\nPrint Assumptions adequacy.\nPrint Assumptions denote_bottom_nonvalue.\n", "meta": {"author": "robdockins", "repo": "domains", "sha": "6feea4ed576f8aa849af9fa102633d5df1191360", "save_path": "github-repos/coq/robdockins-domains", "path": "github-repos/coq/robdockins-domains/domains-6feea4ed576f8aa849af9fa102633d5df1191360/skiy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2778365467729137}}
{"text": "From mathcomp\nRequire Import all_ssreflect ssralg fingroup zmodp poly ssrnum.\nFrom mathcomp\nRequire Import matrix mxalgebra vector falgebra ssrnum algC algnum.\nFrom mathcomp\nRequire Import fieldext.\nFrom mathcomp Require Import vector.\n\n(* From mathcomp Require classfun. *)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLocal Open Scope ring_scope.\nImport GRing.Theory Num.Theory.\n\nReserved Notation \"'[ u , v ]\"\n  (at level 2, format \"'[hv' ''[' u , '/ '  v ] ']'\").\nReserved Notation \"'[ u , v ]_ M\"\n         (at level 2, format \"'[hv' ''[' u , '/ '  v ]_ M ']'\").\nReserved Notation \"'[ u ]_ M\" (at level 2, format \"''[' u ]_ M\").\nReserved Notation \"'[ u ]\" (at level 2, format \"''[' u ]\").\nReserved Notation \"u '``_' i\"\n    (at level 3, i at level 2, left associativity, format \"u '``_' i\").\nReserved Notation \"A ^_|_\"    (at level 8, format \"A ^_|_\").\nReserved Notation \"A _|_ B\" (at level 69, format \"A  _|_  B\").\nReserved Notation \"eps_theta .-sesqui\" (at level 2, format \"eps_theta .-sesqui\").\n\nNotation \"u '``_' i\" := (u (GRing.zero (Zp_zmodType O)) i) : ring_scope.\nNotation \"''e_' i\" := (delta_mx 0 i)\n (format \"''e_' i\", at level 3) : ring_scope.\n\nLocal Notation \"M ^ phi\" := (map_mx phi M).\nLocal Notation \"M ^t phi\" := (map_mx phi (M ^T)) (phi at level 30, at level 30).\n\nStructure revop X Y Z (f : Y -> X -> Z) := RevOp {\n  fun_of_revop :> X -> Y -> Z;\n  _ : forall x, f x =1 fun_of_revop^~ x\n}.\n\nLemma eq_map_mx (R S : ringType) m n (M : 'M[R]_(m,n))\n      (g f : R -> S) : f =1 g -> M ^ f = M ^ g.\nProof. by move=> eq_fg; apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma map_mx_id (R : ringType) m n (M : 'M[R]_(m,n)) : M ^ id = M.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma eq_map_mx_id (R : ringType) m n (M : 'M[R]_(m,n)) (f : R -> R) :\n  f =1 id -> M ^ f = M.\nProof. by move=> /eq_map_mx->; rewrite map_mx_id. Qed.\n\nModule Bilinear.\n\nSection ClassDef.\n\nVariables (R : ringType) (U U' : lmodType R) (V : zmodType) (s s' : R -> V -> V).\nImplicit Type phUU'V : phant (U -> U' -> V).\n\nLocal Coercion GRing.Scale.op : GRing.Scale.law >-> Funclass.\nDefinition axiom (f : U -> U' -> V) (s_law : GRing.Scale.law s) (eqs : s = s_law)\n                                    (s'_law : GRing.Scale.law s') (eqs' : s' = s'_law) :=\n  ((forall u', GRing.Linear.axiom (f^~ u') eqs)\n  * (forall u, GRing.Linear.axiom (f u) eqs'))%type.\n\nRecord class_of (f : U -> U' -> V) : Prop := Class {\n  basel : forall u', GRing.Linear.class_of s (f^~ u');\n  baser : forall u, GRing.Linear.class_of s' (f u)\n}.\n\nLemma class_of_axiom f s_law s'_law Ds Ds' :\n   @axiom f s_law Ds s'_law Ds' -> class_of f.\nProof.\nby pose coa := GRing.Linear.class_of_axiom; move=> [/(_ _) /coa ? /(_ _) /coa].\nQed.\n\nStructure map phUU'V := Pack {apply; _ : class_of apply}.\nLocal Coercion apply : map >-> Funclass.\n\nDefinition class (phUU'V : _)  (cF : map phUU'V) :=\n   let: Pack _ c as cF' := cF return class_of cF' in c.\n\nCanonical additiver phU'V phUU'V (u : U) cF := GRing.Additive.Pack phU'V\n  (baser (@class phUU'V cF) u).\nCanonical linearr phU'V  phUU'V (u : U) cF := GRing.Linear.Pack phU'V\n  (baser (@class phUU'V cF) u).\n\n(* Fact applyr_key : unit. Proof. exact. Qed. *)\nDefinition applyr_head t (f : U -> U' -> V) u v := let: tt := t in f v u.\nNotation applyr := (@applyr_head tt).\n\nCanonical additivel phUV phUU'V (u' : U') (cF : map _) :=\n  @GRing.Additive.Pack _ _ phUV (applyr cF u') (basel (@class phUU'V cF) u').\nCanonical linearl phUV phUU'V  (u' : U') (cF : map _) :=\n  @GRing.Linear.Pack _ _ _ _ phUV (applyr cF u') (basel (@class phUU'V cF) u').\n\nDefinition pack (phUV : phant (U -> V)) (phU'V : phant (U' -> V))\n           (revf : U' -> U -> V) (rf : revop revf) f (g : U -> U' -> V) of (g = fun_of_revop rf) :=\n  fun (bFl : U' -> GRing.Linear.map s phUV) flc of (forall u', revf u' = bFl u') &\n      (forall u', phant_id (GRing.Linear.class (bFl u')) (flc u')) =>\n  fun (bFr : U -> GRing.Linear.map s' phU'V) frc of (forall u, g u = bFr u) &\n      (forall u, phant_id (GRing.Linear.class (bFr u)) (frc u)) =>\n  @Pack (Phant _) f (Class flc frc).\n\n\n(* (* Support for right-to-left rewriting with the generic linearZ rule. *) *)\n(* Notation mapUV := (map (Phant (U -> U' -> V))). *)\n(* Definition map_class := mapUV. *)\n(* Definition map_at (a : R) := mapUV. *)\n(* Structure map_for a s_a := MapFor {map_for_map : mapUV; _ : s a = s_a}. *)\n(* Definition unify_map_at a (f : map_at a) := MapFor f (erefl (s a)). *)\n(* Structure wrapped := Wrap {unwrap : mapUV}. *)\n(* Definition wrap (f : map_class) := Wrap f. *)\n\nEnd ClassDef.\n\nModule Exports.\nDelimit Scope linear_ring_scope with linR.\nNotation bilinear_for s s' f := (axiom f (erefl s) (erefl s')).\nNotation bilinear f := (bilinear_for *:%R *:%R f).\nNotation biscalar f := (bilinear_for *%R *%R f).\nNotation bilmorphism_for s s' f := (class_of s s' f).\nNotation bilmorphism f := (bilmorphism_for *:%R *:%R f).\nCoercion class_of_axiom : axiom >-> bilmorphism_for.\nCoercion baser : bilmorphism_for >-> Funclass.\nCoercion apply : map >-> Funclass.\nNotation \"{ 'bilinear' fUV | s & s' }\" := (map s s' (Phant fUV))\n  (at level 0, format \"{ 'bilinear'  fUV  |  s  &  s' }\") : ring_scope.\nNotation \"{ 'bilinear' fUV | s }\" := (map s.1 s.2 (Phant fUV))\n  (at level 0, format \"{ 'bilinear'  fUV  |  s }\") : ring_scope.\nNotation \"{ 'bilinear' fUV }\" := {bilinear fUV | *:%R & *:%R}\n  (at level 0, format \"{ 'bilinear'  fUV }\") : ring_scope.\nNotation \"{ 'biscalar' U }\" := {bilinear U -> U -> _ | *%R & *%R}\n  (at level 0, format \"{ 'biscalar'  U }\") : ring_scope.\nNotation \"[ 'bilinear' 'of' f 'as' g ]\" :=\n  (@pack  _ _ _ _ _ _ _ _ _ _ f g erefl _ _\n         (fun=> erefl) (fun=> idfun) _ _ (fun=> erefl) (fun=> idfun)).\nNotation \"[ 'bilinear' 'of' f ]\" :=  [bilinear of f as f]\n  (at level 0, format \"[ 'bilinear'  'of'  f ]\") : form_scope.\nCoercion additiver : map >-> GRing.Additive.map.\nCoercion linearr : map >->  GRing.Linear.map.\nCanonical additiver.\nCanonical linearr.\nCanonical additivel.\nCanonical linearl.\nNotation applyr := (@applyr_head _ _ _ _ tt).\n(* Canonical additive. *)\n(* (* Support for right-to-left rewriting with the generic linearZ rule. *) *)\n(* Coercion map_for_map : map_for >-> map. *)\n(* Coercion unify_map_at : map_at >-> map_for. *)\n(* Canonical unify_map_at. *)\n(* Coercion unwrap : wrapped >-> map. *)\n(* Coercion wrap : map_class >-> wrapped. *)\n(* Canonical wrap. *)\nEnd Exports.\n\nEnd Bilinear.\nInclude Bilinear.Exports.\n\nSection BilinearTheory.\n\nVariable R : ringType.\n\nSection GenericProperties.\n\nVariables (U U' : lmodType R) (V : zmodType) (s : R -> V -> V) (s' : R -> V -> V).\nVariable f : {bilinear U -> U' -> V | s & s'}.\n\nLemma linear0r z : f z 0 = 0. Proof. by rewrite raddf0. Qed.\nLemma linearNr z : {morph f z : x / - x}. Proof. exact: raddfN. Qed.\nLemma linearDr z : {morph f z : x y / x + y}. Proof. exact: raddfD. Qed.\nLemma linearBr z : {morph f z : x y / x - y}. Proof. exact: raddfB. Qed.\nLemma linearMnr z n : {morph f z : x / x *+ n}. Proof. exact: raddfMn. Qed.\nLemma linearMNnr z n : {morph f z : x / x *- n}. Proof. exact: raddfMNn. Qed.\nLemma linear_sumr z I r (P : pred I) E :\n  f z (\\sum_(i <- r | P i) E i) = \\sum_(i <- r | P i) f z (E i).\nProof. exact: raddf_sum. Qed.\n\nLemma linearZr_LR z : scalable_for s' (f z). Proof. exact: linearZ_LR. Qed.\nLemma linearPr z a : {morph f z : u v / a *: u + v >-> s' a u + v}.\nProof. exact: linearP. Qed.\n\nLemma applyrE x : applyr f x =1 f^~ x. Proof. by []. Qed.\n\nLemma linear0l z : f 0 z = 0. Proof. by rewrite -applyrE raddf0. Qed.\nLemma linearNl z : {morph f^~ z : x / - x}.\nProof. by move=> ?; rewrite -applyrE raddfN. Qed.\nLemma linearDl z : {morph f^~ z : x y / x + y}.\nProof. by move=> ??; rewrite -applyrE raddfD. Qed.\nLemma linearBl z : {morph f^~ z : x y / x - y}.\nProof. by move=> ??; rewrite -applyrE raddfB. Qed.\nLemma linearMnl z n : {morph f^~ z : x / x *+ n}.\nProof. by move=> ?; rewrite -applyrE raddfMn. Qed.\nLemma linearMNnl z n : {morph f^~ z : x / x *- n}.\nProof. by move=> ?; rewrite -applyrE raddfMNn. Qed.\nLemma linear_suml z I r (P : pred I) E :\n  f (\\sum_(i <- r | P i) E i) z = \\sum_(i <- r | P i) f (E i) z.\nProof. by rewrite -applyrE raddf_sum. Qed.\n\nLemma linearZl_LR z : scalable_for s (f^~ z).\nProof. by move=> ??; rewrite -applyrE linearZ_LR. Qed.\nLemma linearPl z a : {morph f^~ z : u v / a *: u + v >-> s a u + v}.\nProof. by move=> ??; rewrite -applyrE linearP. Qed.\n\nEnd GenericProperties.\n\nSection BidirectionalLinearZ.\n\nVariables (U : lmodType R) (V : zmodType) (s : R -> V -> V).\nVariables (S : ringType) (h : S -> V -> V) (h_law : GRing.Scale.law h).\n\n(* Lemma linearZr z c a (h_c := GRing.Scale.op h_law c) (f : GRing.Linear.map_for U s a h_c) u : *)\n(*   f z (a *: u) = h_c (GRing.Linear.wrap (f z) u). *)\n(* Proof. by rewrite linearZ_LR; case: f => f /= ->. Qed. *)\n\nEnd BidirectionalLinearZ.\n\nEnd BilinearTheory.\n\nCanonical rev_mulmx (R : ringType) m n p := @RevOp _ _ _ (@mulmxr R m n p)\n  (@mulmx R m n p) (fun _ _ => erefl).\n\nCanonical mulmx_bilinear (R : comRingType) m n p := [bilinear of @mulmx R m n p].\n\n(* Section classfun. *)\n(* Import mathcomp.character.classfun. *)\n\n(* Canonical rev_cfdot (gT : finGroupType) (B : {set gT}) :=  *)\n(*   @RevOp _ _ _ (@cfdotr_head gT B tt) *)\n(*   (@cfdot gT B) (fun _ _ => erefl). *)\n\n(* Section Cfdot. *)\n(* Variables (gT : finGroupType) (G : {group gT}). *)\n(* Lemma cfdot_is_linear xi : linear_for (@conjC _ \\; *%R) (cfdot xi : 'CF(G) -> algC^o). *)\n(* Proof. *)\n(* move=> /= a phi psi; rewrite cfdotC -cfdotrE linearD linearZ /=. *)\n(* by rewrite !['[_, xi]]cfdotC rmorphD rmorphM !conjCK. *)\n(* Qed. *)\n(* Canonical cfdot_additive xi := Additive (cfdot_is_linear xi). *)\n(* Canonical cfdot_linear xi := Linear (cfdot_is_linear xi). *)\n(* End Cfdot. *)\n\n(* Canonical cfdot_bilinear (gT : finGroupType) (B : {group gT}) := *)\n(*   [bilinear of @cfdot gT B]. *)\n(* End classfun. *)\n\nSection BilinearForms.\n\nVariables (R : fieldType) (theta : {rmorphism R -> R}).\nVariables (n : nat) (M : 'M[R]_n).\nImplicit Types (a b : R) (u v : 'rV[R]_n) (N P Q : 'M[R]_n).\n\nDefinition form u v := (u *m M *m (v ^t theta)) 0 0.\n\nLocal Notation \"''[' u , v ]\" := (form u%R v%R) : ring_scope.\nLocal Notation \"''[' u ]\" := '[u, u] : ring_scope.\n\nLemma form0l u : '[0, u] = 0.\nProof. by rewrite /form !mul0mx mxE. Qed.\n\nLemma form0r u : '[u, 0] = 0.\nProof. by rewrite /form trmx0 map_mx0 mulmx0 mxE. Qed.\n\nLemma formDl u v w : '[u + v, w] = '[u, w] + '[v, w].\nProof. by rewrite /form !mulmxDl mxE. Qed.\n\nLemma formDr u v w : '[u, v + w] = '[u, v] + '[u, w].\nProof. by rewrite /form linearD !map_mxD !mulmxDr mxE. Qed.\n\nLemma formZr a u v : '[u, a *: v] = theta a * '[u, v].\nProof. by rewrite /form !(linearZ, map_mxZ) /= mxE. Qed.\n\nLemma formZl a u v : '[a *: u, v] = a * '[u, v].\nProof.\nby do !rewrite /form  -[_ *: _ *m _]/(mulmxr _ _) linearZ /=; rewrite mxE.\nQed.\n\nLemma formNl u v : '[- u, v] = - '[u, v].\nProof. by rewrite -scaleN1r formZl mulN1r. Qed.\n\nLemma formNr u v : '[u, - v] = - '[u, v].\nProof. by rewrite -scaleN1r formZr rmorphN1 mulN1r. Qed.\n\nLemma formee i j : '['e_i, 'e_j] = M i j.\nProof.\nrewrite /form -rowE -map_trmx map_delta_mx -[M in LHS]trmxK.\nby rewrite -tr_col -trmx_mul -rowE !mxE.\nQed.\n\nLemma form0_eq0 : M = 0 -> forall u v, '[u, v] = 0.\nProof. by rewrite/form=> -> u v; rewrite mulmx0 mul0mx mxE. Qed.\n\nEnd BilinearForms.\n\nSection Sesquilinear.\n\nVariable R : fieldType.\nVariable n : nat.\nImplicit Types (a b : R) (u v : 'rV[R]_n) (N P Q : 'M[R]_n).\n\nSection Def.\nVariable eps_theta : (bool * {rmorphism R -> R}).\n\nDefinition sesqui :=\n  [qualify M : 'M_n | M == ((-1) ^+ eps_theta.1) *: M ^t eps_theta.2].\nFact sesqui_key : pred_key sesqui. Proof. by []. Qed.\nCanonical sesqui_keyed := KeyedQualifier sesqui_key.\nEnd Def.\n\nLocal Notation \"eps_theta .-sesqui\" := (sesqui eps_theta).\n\nVariables (eps : bool) (theta : {rmorphism R -> R}).\nVariables (M : 'M[R]_n).\nLocal Notation \"''[' u , v ]\" := (form theta M u%R v%R) : ring_scope.\nLocal Notation \"''[' u ]\" := '[u, u] : ring_scope.\n\nLemma sesquiE : (M \\is (eps,theta).-sesqui) = (M == (-1) ^+ eps *: M ^t theta).\nProof. by rewrite qualifE. Qed.\n\nLemma sesquiP : reflect (M = (-1) ^+ eps *: M ^t theta)\n                        (M \\is (eps,theta).-sesqui).\nProof. by rewrite sesquiE; apply/eqP. Qed.\n\nHypothesis (thetaK : involutive theta).\nHypothesis (M_sesqui : M \\is (eps, theta).-sesqui).\n\nLemma trmx_sesqui : M^T = (-1) ^+ eps *: M ^ theta.\nProof.\nrewrite [in LHS](sesquiP _) // -mul_scalar_mx trmx_mul.\nby rewrite tr_scalar_mx mul_mx_scalar map_trmx trmxK.\nQed.\n\nLemma maptrmx_sesqui : M^t theta = (-1) ^+ eps *: M.\nProof.\nby rewrite trmx_sesqui map_mxZ rmorph_sign -map_mx_comp eq_map_mx_id.\nQed.\n\nLemma formC u v : '[u, v] = (-1) ^+ eps * theta '[v, u].\nProof.\nrewrite /form [M in LHS](sesquiP _) // -mulmxA !mxE rmorph_sum mulr_sumr.\napply: eq_bigr => /= i _; rewrite !(mxE, mulr_sumr, mulr_suml, rmorph_sum).\napply: eq_bigr => /= j _; rewrite !mxE !rmorphM  mulrCA -!mulrA.\nby congr (_ * _); rewrite mulrA mulrC thetaK.\nQed.\n\nLemma form_eq0C u v : ('[u, v] == 0) = ('[v, u] == 0).\nProof. by rewrite formC mulf_eq0 signr_eq0 /= fmorph_eq0. Qed.\n\nDefinition ortho m (B : 'M_(m,n)) := (kermx (M *m (B ^t theta))).\nLocal Notation \"B ^_|_\" := (ortho B) : ring_scope.\nLocal Notation \"A _|_ B\" := (A%MS <= B^_|_)%MS : ring_scope.\n\nLemma normalE u v : (u _|_ v) = ('[u, v] == 0).\nProof.\nby rewrite (sameP sub_kermxP eqP) mulmxA [_ *m _^t _]mx11_scalar fmorph_eq0.\nQed.\n\nLemma form_eq0P {u v} : reflect ('[u, v] = 0) (u _|_ v).\nProof. by rewrite normalE; apply/eqP. Qed.\n\nLemma normalP p q (A : 'M_(p, n)) (B :'M_(q, n)) :\n  reflect (forall (u v : 'rV_n), (u <= A)%MS -> (v <= B)%MS -> u _|_ v)\n          (A _|_ B).\nProof.\napply: (iffP idP) => AnB.\n  move=> u v uA vB; rewrite (submx_trans uA) // (submx_trans AnB) //.\n  apply/sub_kermxP; have /submxP [w ->] := vB.\n  rewrite trmx_mul map_mxM !mulmxA -[kermx _ *m _ *m _]mulmxA.\n  by rewrite [kermx _ *m _](sub_kermxP _) // mul0mx.\napply/rV_subP => u /AnB /(_ _) /sub_kermxP uMv; apply/sub_kermxP.\nsuff: forall m (v : 'rV[R]_m),\n  (forall i, v *m 'e_i ^t theta = 0 :> 'M_1) -> v = 0.\n  apply => i; rewrite !mulmxA -!mulmxA -map_mxM -trmx_mul uMv //.\n  by apply/submxP; exists 'e_i.\nmove=> /= m v Hv; apply: (can_inj (@trmxK _ _ _)).\nrewrite trmx0; apply/row_matrixP=> i; rewrite row0 rowE.\napply: (can_inj (@trmxK _ _ _)); rewrite trmx0 trmx_mul trmxK.\nby rewrite -(map_delta_mx theta) map_trmx Hv.\nQed.\n\nLemma normalC p q (A : 'M_(p, n)) (B :'M_(q, n)) : (A _|_ B) = (B _|_ A).\nProof.\ngen have nC : p q A B / A _|_ B -> B _|_ A; last by apply/idP/idP; apply/nC.\nmove=> AnB; apply/normalP => u v ? ?; rewrite normalE.\nrewrite formC mulf_eq0 ?fmorph_eq0 ?signr_eq0 /=.\nby rewrite -normalE (normalP _ _ AnB).\nQed.\n\nLemma normal_ortho_mx p (A : 'M_(p, n)) : ((A^_|_) _|_ A).\nProof. by []. Qed.\n\nLemma normal_mx_ortho p (A : 'M_(p, n)) : (A _|_ (A^_|_)).\nProof. by rewrite normalC. Qed.\n\nLemma rank_normal u : (\\rank (u ^_|_) >= n.-1)%N.\nProof.\nrewrite mxrank_ker -subn1 leq_sub2l //.\nby rewrite (leq_trans (mxrankM_maxr  _ _)) // rank_leq_col.\nQed.\n\nDefinition rad := 1%:M^_|_.\n\nLemma rad_ker : rad = kermx M.\nProof. by rewrite /rad /ortho trmx1 map_mx1 mulmx1. Qed.\n\n(* Pythagore *)\nTheorem formDd u v : u _|_ v -> '[u + v] = '[u] + '[v].\nProof.\nmove=> uNv; rewrite formDl !formDr ['[v, u]]formC.\nby rewrite ['[u, v]](form_eq0P _) // rmorph0 mulr0 addr0 add0r.\nQed.\n\nLemma formZ a u : '[a *: u]= (a * theta a) * '[u].\nProof. by rewrite formZl formZr mulrA. Qed.\n\nLemma formN u : '[- u] = '[u].\nProof. by rewrite formNr formNl opprK. Qed.\n\nLemma form_sign m u : '[(-1) ^+ m *: u] = '[u].\nProof. by rewrite -signr_odd scaler_sign; case: odd; rewrite ?formN. Qed.\n\nLemma formD u v : let d := '[u, v] in\n  '[u + v] = '[u] + '[v] + (d + (-1) ^+ eps * theta d).\nProof. by rewrite formDl !formDr ['[v, _]]formC [_ + '[v]]addrC addrACA. Qed.\n\nLemma formB u v : let d := '[u, v] in\n  '[u - v] = '[u] + '[v] - (d + (-1) ^+ eps * theta d).\nProof. by rewrite formD formN !formNr rmorphN mulrN -opprD. Qed.\n\nLemma formBd u v : u _|_ v -> '[u - v] = '[u] + '[v].\nProof.\nby move=> uTv; rewrite formDd ?formN // normalE formNr oppr_eq0 -normalE.\nQed.\n\n(* Lemma formJ u v : '[u ^ theta, v ^ theta] = (-1) ^+ eps * theta '[u, v]. *)\n(* Proof. *)\n(* rewrite {1}/form -map_trmx -map_mx_comp (@eq_map_mx _ _ _ _ _ id) ?map_mx_id //. *)\n(* set x := (_ *m _); have -> : x 0 0 = theta ((x^t theta) 0 0) by rewrite !mxE. *)\n(* rewrite !trmx_mul trmxK map_trmx mulmxA !map_mxM. *)\n(* rewrite maptrmx_sesqui -!scalemxAr -scalemxAl mxE rmorphM rmorph_sign. *)\n\n(* Lemma formJ u : '[u ^ theta] = (-1) ^+ eps * '[u]. *)\n(* Proof.  *)\n(* rewrite {1}/form -map_trmx -map_mx_comp (@eq_map_mx _ _ _ _ _ id) ?map_mx_id //. *)\n(* set x := (_ *m _); have -> : x 0 0 = theta ((x^t theta) 0 0) by rewrite !mxE. *)\n(* rewrite !trmx_mul trmxK map_trmx mulmxA !map_mxM. *)\n(* rewrite maptrmx_sesqui -!scalemxAr -scalemxAl mxE rmorphM rmorph_sign. *)\n(* rewrite !map_mxM. *)\n(* rewrite -map_mx_comp eq_map_mx_id //. *)\n(*  !linearZr_LR /=. linearZ. *)\n(*  linearZl. *)\n(* rewrite trmx_sesqui. *)\n\n\n(* rewrite mapmx. *)\n(* rewrite map *)\n(* apply/matrixP.  *)\n\n(* rewrite formC. *)\n(* Proof. by rewrite cfdot_conjC geC0_conj // cfnorm_ge0. Qed. *)\n\n(* Lemma cfCauchySchwarz u v : *)\n(*   `|'[u, v]| ^+ 2 <= '[u] * '[v] ?= iff ~~ free (u :: v). *)\n(* Proof. *)\n(* rewrite free_cons span_seq1 seq1_free -negb_or negbK orbC. *)\n(* have [-> | nz_v] /= := altP (v =P 0). *)\n(*   by apply/lerifP; rewrite !cfdot0r normCK mul0r mulr0. *)\n(* without loss ou: u / '[u, v] = 0. *)\n(*   move=> IHo; pose a := '[u, v] / '[v]; pose u1 := u - a *: v. *)\n(*   have ou: '[u1, v] = 0. *)\n(*     by rewrite cfdotBl cfdotZl divfK ?cfnorm_eq0 ?subrr. *)\n(*   rewrite (canRL (subrK _) (erefl u1)) rpredDr ?rpredZ ?memv_line //. *)\n(*   rewrite cfdotDl ou add0r cfdotZl normrM (ger0_norm (cfnorm_ge0 _)). *)\n(*   rewrite exprMn mulrA -cfnormZ cfnormDd; last by rewrite cfdotZr ou mulr0. *)\n(*   by have:= IHo _ ou; rewrite mulrDl -lerif_subLR subrr ou normCK mul0r. *)\n(* rewrite ou normCK mul0r; split; first by rewrite mulr_ge0 ?cfnorm_ge0. *)\n(* rewrite eq_sym mulf_eq0 orbC cfnorm_eq0 (negPf nz_v) /=. *)\n(* apply/idP/idP=> [|/vlineP[a {2}->]]; last by rewrite cfdotZr ou mulr0. *)\n(* by rewrite cfnorm_eq0 => /eqP->; apply: rpred0. *)\n(* Qed. *)\n\nEnd Sesquilinear.\n\nNotation \"eps_theta .-sesqui\" := (sesqui _ eps_theta) : ring_scope.\n\nNotation symmetric_form := (false, [rmorphism of idfun]).-sesqui.\nNotation skew := (true, [rmorphism of idfun]).-sesqui.\nNotation hermitian := (false, @conjC _).-sesqui.\n\n(* Section ClassificationForm. *)\n\n(* Variables (F : fieldType) (L : fieldExtType) (theat : 'Aut()) *)\n\n(* Notation \"''[' u , v ]_ M\" := (form M%R u%R v%R) : ring_scope. *)\n(* Notation \"''[' u ]_ M\" := (form M%R u%R u%R) : ring_scope. *)\n\n(* Hypothesis (thetaK : involutive theta). *)\n\n(* Lemma sesqui_test M : (forall u v, '[v, u]_M = 0 -> '[u, v]_M = 0) -> *)\n(*                       {eps | eps^+2 = 1 & M \\is (eps,theta).-sesqui}. *)\n(* Proof. *)\n(* pose  *)\n\n\n(*                       [/\\ forall u, '[u] = 0, theta =1 id & eps = -1] *)\n(*                       \\/ ((exists u, '[u] != 0) /\\ (eps = 1)). *)\n(* Proof. *)\n(* move=> M_neq0 form_eq0. *)\n(* have [] := boolP [forall i : 'I_n, '['e_i] == 0]; last first. *)\n(*   rewrite negb_forall => /existsP [i ei_neq0]. *)\n(*   right; split; first by exists ('e_i). *)\n(*   apply/eqP; *)\n\n(*  contraT *)\n\n\n(* suff [f_eq0|] : (forall u, '[u] = 0) \\/ (exists u, '[u] != 0). *)\n(*   left; split=> //. *)\n\n(* have [] := boolP [forall i : 'I_n, '['e_i] == 0]. *)\n\n(* suff /eqP : eps ^+ 2 = 1. *)\n(*   rewrite -subr_eq0 subr_sqr_1 mulf_eq0. *)\n(*   move => /orP[]; rewrite addr_eq0 ?opprK=> /eqP eps_eq. *)\n(*     right; split=> //. *)\n\n(* have [] := boolP [forall i : 'I_n, '['e_i] == 0]. *)\n\n(* have := sesquiC u u. *)\n\n\n(* rewrite !linearZ /= -[eps *: _ *m _]/(mulmxr _ _) linearZ /= mxE; congr (_ * _). *)\n(* have : u = map_mx theta (map_mx theta u). *)\n(*   apply/rowP=> i; rewrite !mxE. *)\n(* rewrite -[in LHS]mulmxA -map_mxM. *)\n(* rewrite  *)\n(*  !mxE rmorph_sum; apply: eq_bigr => /= i _; rewrite !mxE. *)\n(* rewrite !rmorphM thetaK rmorph_sum. *)\n\n(* Hypothesis (M_sesqui : M \\is (eps, theta).-sesqui). *)\n\n(* rewrite -[a *: u *m _]/(mulmxr _ _). *)\n(* rewrite linearZ. *)\n\n(* Variables (R : fieldType) (n : nat). *)\n\n(* Local Notation \"A _|_ B\" := (A%MS <= kermx B%MS^T)%MS. *)\n\n(* Lemma normal_sym k m (A : 'M[R]_(k,n)) (B : 'M[R]_(m,n)) : *)\n(*   A _|_ B = B _|_ A. *)\n(* Proof. *)\n(* rewrite !(sameP sub_kermxP eqP) -{1}[A]trmxK -trmx_mul. *)\n(* by rewrite -{1}trmx0 (inj_eq (@trmx_inj _ _ _)). *)\n(* Qed. *)\n\n(* Lemma normalNm k m (A : 'M[R]_(k,n)) (B : 'M[R]_(m,n)) : (- A) _|_ B = A _|_ B. *)\n(* Proof. by rewrite eqmx_opp. Qed. *)\n\n(* Lemma normalmN k m (A : 'M[R]_(k,n)) (B : 'M[R]_(m,n)) : A _|_ (- B) = A _|_ B. *)\n(* Proof. by rewrite ![A _|_ _]normal_sym normalNm. Qed. *)\n\n(* Lemma normalDm k m p (A : 'M[R]_(k,n)) (B : 'M[R]_(m,n)) (C : 'M[R]_(p,n)) : *)\n(*   (A + B _|_ C) = (A _|_ C) && (B _|_ C). *)\n(* Proof. by rewrite addsmxE !(sameP sub_kermxP eqP) mul_col_mx col_mx_eq0. Qed. *)\n\n(* Lemma normalmD  k m p (A : 'M[R]_(k,n)) (B : 'M[R]_(m,n)) (C : 'M[R]_(p,n)) : *)\n(*   (A _|_ B + C) = (A _|_ B) && (A _|_ C). *)\n(* Proof. by rewrite ![A _|_ _]normal_sym normalDm. Qed. *)\n\n(* Definition dot (u v : 'rV[R]_n) : R := (u *m v^T) 0 0. *)\n\n(* Notation \"''[' u , v ]\" := (dot u v) : ring_scope. *)\n(* Notation \"''[' u ]\" := '[u, u]%MS : ring_scope. *)\n\n(* Lemma dotmulE (u v : 'rV[R]_n) : '[u, v] = \\sum_k u``_k * v``_k. *)\n(* Proof. by rewrite [LHS]mxE; apply: eq_bigr=> i; rewrite mxE. Qed. *)\n\n(* Lemma normalvv (u v : 'rV[R]_n) : (u _|_ v) = ('[u, v] == 0). *)\n(* Proof. by rewrite (sameP sub_kermxP eqP) [_ *m _^T]mx11_scalar fmorph_eq0. Qed. *)\n\n(* End Normal. *)\n\n(* Local Notation \"''[' u , v ]\" := (form u v) : ring_scope. *)\n(* Local Notation \"''[' u ]\" := '[u%R, u%R] : ring_scope. *)\n(* Local Notation \"A _|_ B\" := (A%MS <= kermx B%MS^T)%MS. *)\n", "meta": {"author": "math-comp", "repo": "analysis", "sha": "ee12aba894e8949a32daa9d2ee72b3a440c0609f", "save_path": "github-repos/coq/math-comp-analysis", "path": "github-repos/coq/math-comp-analysis/analysis-ee12aba894e8949a32daa9d2ee72b3a440c0609f/theories/forms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2778365400273305}}
{"text": "From Undecidability.TRAKHTENBROT Require Import bpcp red_undec fo_sig.\nFrom Undecidability.Synthetic Require Import Undecidability ReducibilityFacts.\nFrom Undecidability.FOL.Syntax Require Import Core.\nFrom Undecidability.FOL.Semantics.FiniteTarski Require Fragment Full DoubleNegation.\nFrom Undecidability.FOL.Undecidability Require Import Reductions.FSATd_to_FSATdc Reductions.TRAKHTENBROT_to_FSAT.\n\nSection Full.\n  Import Full.\n\n  Theorem FSAT_undec :\n    undecidable FSAT.\n  Proof.\n    apply (undecidability_from_reducibility BPCP_problem_undec).\n    eapply reduces_transitive; [| apply reduction].\n    apply (@FULL_TRAKHTENBROT_non_informative (Σrel 2)). left. exists tt. auto.\n  Qed.\n\n  Theorem FSATd_undec :\n    undecidable FSATd.\n  Proof.\n    apply (undecidability_from_reducibility BPCP_problem_undec).\n    eapply reduces_transitive; try apply reduction_disc.\n    eapply reduces_transitive; try apply (@FULL_TRAKHTENBROT_non_informative (Σrel 2)).\n    - left. exists tt. auto.\n    - exists (fun phi => phi). intros phi. apply red_utils.fo_form_fin_dec_SAT_discr_equiv.\n  Qed.\n\n  Theorem FSATdc_undec :\n    undecidable FSATdc.\n  Proof.\n   apply (undecidability_from_reducibility FSATd_undec).\n   apply FSATd_to_FSATdc.reduction.\n  Qed.\nEnd Full.\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/FOL/Undecidability/FSAT_undec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.41111086923216805, "lm_q1q2_score": 0.27781417789028867}}
{"text": "Require Import Coq.ZArith.ZArith. Local Open Scope Z_scope.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List. Import ListNotations.\nRequire Import coqutil.Tactics.Tactics.\nRequire Import riscv.Spec.Machine.\nRequire Import riscv.Platform.Memory.\nRequire Import riscv.Spec.CSRFile.\nRequire Import riscv.Utility.Utility.\nRequire Import coqutil.Datatypes.RecordSetters. Export OCamlLikeNotations.\nRequire Import coqutil.Z.Lia.\nRequire Import coqutil.Map.Interface.\nRequire Import riscv.Platform.MaterializeRiscvProgram.\n\nModule map.\n  (* Swap argument order to enable usage of partially applied `map.set k v` as an updater *)\n  Definition set{key value}{map: map.map key value}(k: key)(v: value)(m: map): map :=\n    map.put m k v.\nEnd map.\n\nSection Riscv.\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 Z word}.\n\n  (* (memory before call, call name, arg values) and (memory after call, return values) *)\n  Definition LogItem: Type := (Mem * string * list word) * (Mem * list word).\n\n  Record State := mkState {\n    regs: Registers;\n    pc: word;\n    nextPc: word;\n    mem: Mem;\n    log: list LogItem;\n    csrs: CSRFile\n  }.\n\n  (* TODO: add XAddrs tracking so that executing an instruction written in a previous cycle\n     (which potentially is already in the pipeline) is not allowed *)\n\n  Definition store(n: nat)(ctxid: SourceType)(a: word) v (mach: State)(post: State -> Prop) :=\n    match Memory.store_bytes n mach.(mem) a v with\n    | Some m => post { mach with mem := m }\n    | None => False\n    end.\n\n  Definition load(n: nat)(ctxid: SourceType)(a: word)(mach: State)(post: _ -> _ -> Prop) :=\n    match Memory.load_bytes n mach.(mem) a with\n    | Some v => post v mach\n    | None => False\n    end.\n\n  Definition updatePc(mach: State): State :=\n    { mach with pc := mach.(nextPc); nextPc ::= word.add (word.of_Z 4) }.\n\n  Definition getReg(regs: Registers)(reg: Z): word :=\n    if ((0 <? reg) && (reg <? 32))%bool 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))%bool then map.put regs reg v else regs.\n\n  Definition run_primitive(a: riscv_primitive)(mach: State):\n             (primitive_result a -> State -> Prop) -> (State -> Prop) -> Prop :=\n    match a with\n    | GetRegister reg => fun postF postA => postF (getReg mach.(regs) reg) mach\n    | SetRegister reg v => fun postF postA => postF tt { mach with regs ::= setReg reg v }\n    | GetPC => fun postF postA => postF mach.(pc) mach\n    | SetPC newPC => fun postF postA => postF tt { mach with nextPc := newPC }\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 { mach with nextPc := word.add mach.(pc) (word.of_Z 4) }\n    | EndCycleNormal => fun postF postA => postF tt (updatePc mach)\n    | EndCycleEarly _ => fun postF postA => postA (updatePc mach) (* ignores postF containing the continuation *)\n    | GetCSRField f => fun postF postA =>\n                         match map.get mach.(csrs) f with\n                         | Some v => postF v mach\n                         | None => False\n                         end\n    | SetCSRField f v => fun postF postA =>\n                           (* only allow setting CSR fields that are supported (not None) on this machine *)\n                           match map.get mach.(csrs) f with\n                           | Some _ => postF tt { mach with csrs ::= map.set f v }\n                           | None => False\n                           end\n    | GetPrivMode => fun postF postA => postF Machine mach\n    | SetPrivMode mode => fun postF postA =>\n                            match mode with\n                            | Machine => postF tt mach\n                            | User | Supervisor => False\n                            end\n    | MakeReservation _\n    | ClearReservation _\n    | CheckReservation _\n    | Fence _ _\n        => fun postF postA => False\n    end.\n\n  Lemma weaken_load: forall n c a m (post1 post2:_->_->Prop),\n      (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    unfold load. intros. destruct (load_bytes n m.(mem) a); intuition eauto.\n  Qed.\n\n  Lemma weaken_store: forall n c a v m (post1 post2:_->Prop),\n      (forall s, post1 s -> post2 s) ->\n      store n c a v m post1 -> store n c a v m post2.\n  Proof.\n    unfold store. intros. destruct (store_bytes n m.(mem) a v); intuition eauto.\n  Qed.\n\n  Lemma weaken_run_primitive: forall 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, run_primitive a s postF1 postA1 -> run_primitive a s postF2 postA2.\n  Proof.\n    destruct a; cbn; intros; try solve [intuition eauto using weaken_load, weaken_store];\n      destruct_one_match; eauto.\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/MinimalCSRs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.2778077253027184}}
{"text": "Add LoadPath \"..\".\nRequire Import List.\nRequire Import base.\nRequire Import uf.UF_interface.\nRequire Import uf.UF_implementation.\nRequire Import rbt.MMapRBT.\nRequire Import rbt.MMapInterface.\nRequire Import partition_base.\nRequire Import partition_interface.\n\nModule Internal_Structures (Import Input : INPUT) \n                           (Import ot : OrderedType with Definition t := Input.e\n                                                    with Definition eq := @Logic.eq Input.e).\n\n  Module UF := Union_Find Input ot.\n  Module UFL := UnionFind_Lemmas Input UF. Import UFL.\n  Module RBT := Make ot.  \n\n  Definition var := ot.t.\n\n  (*Implementation section*)\n  Definition emptyUF := UF.empty.\n  Definition add_singleton2uf (uf : UF.t) (v : var) : \n   (UF.t * var) :=\n   match (UF.find uf v) with\n   | (Some v', uf') => (uf', v')\n   | (None, uf')    => (UF.singleton uf' v,v)\n   end.\n  Definition add_singleton2uf_t p v := fst (add_singleton2uf p v).\n  Definition add_singleton2uf_v p v := snd (add_singleton2uf p v).\n  Definition union_singleton2uf (v : var) (p : (UF.t * option var)):\n   (UF.t * option var):=\n   let (uf,ov)  := p in\n   let (uf',v') := add_singleton2uf uf v in\n   match ov with\n   | None     => (uf', Some v')\n   | Some v'' => let uf'' := UF.union uf' v' v'' in (uf'',UF.find_e uf'' v')\n   end.\n  Definition union_singleton2uf_t v p := fst (union_singleton2uf v p).\n  Definition union_singleton2uf_v v p := snd (union_singleton2uf v p).\n  Definition add_list2uf (uf : UF.t) (l : list var)  : (UF.t * option var):=\n   fold_right union_singleton2uf (uf,None) l. \n  Definition add_list2uf_t uf l := fst (add_list2uf uf l).\n  Definition add_list2uf_v uf l := snd (add_list2uf uf l). \n  Definition eqn2uf {A : Type} `{VAB : varsable A var} (uf : UF.t) (eqn : A) :=\n   add_list2uf uf (vars eqn) .\n  Implicit Arguments eqn2uf [A VAB].\n  Definition eqn2uf_t {A : Type} `{VAB : varsable A var} (uf : UF.t) (eqn : A) := fst (eqn2uf uf eqn).\n  Implicit Arguments eqn2uf_t [A VAB].\n  Definition eqn2uf_v {A : Type} `{VAB : varsable A var} uf eqn:= snd (eqn2uf uf eqn).\n  Implicit Arguments eqn2uf_v [A VAB].\n  Definition eqnlist2uf {A : Type} `{VAB : varsable A var} (l : list A) : UF.t :=\n   fold_right (fun eqn uf => eqn2uf_t uf eqn) emptyUF l.\n  Definition get_t {A : Type} (p : (UF.t * A)) := fst p.\n  Definition get_v {A : Type} (p : (UF.t * A)) := snd p.\n\n  Definition emptyRBT (A : Type):= @RBT.empty A.\n  Definition find_var {A : Type } `{VAB : varsable A var} (uf : UF.t)  (eqn : A) : \n  (option var * UF.t) :=\n   match (vars eqn) with\n   | nil  => (None,uf)\n   | v::l => UF.find uf v\n   end.\n  Definition find_var_v {A : Type } `{VAB : varsable A var} (uf : UF.t) (eqn : A) : \n   option var := fst (find_var uf eqn). \n  Definition find_var_uf {A : Type } `{VAB : varsable A var} (uf : UF.t)  (eqn : A) : \n   UF.t := snd (find_var uf eqn). \n  Definition find_add {B: Type} \n  (a : var) (b : B) (rbt : RBT.map_of (list B)) : RBT.map_of (list B):=\n   match RBT.find a rbt with\n   | Some l => RBT.add a (b::l) rbt\n   | None   => RBT.add a (b::nil) rbt\n   end.\n  Definition find_list_rbt {B : Type} (a : var) (rbt : RBT.map_of (list B)) : list B :=\n   match RBT.find a rbt with\n   | None => nil\n   | Some l => l\n   end.\n  (*Precondition: all vars were already in uf*)\n  Definition add_equation2RBT {A : Type} `{VAB : varsable A var}\n  (eqn : A) (uf : UF.t) (rbt : RBT.map_of (list A)) (l : list A) : \n  (list A * (RBT.map_of (list A)))%type:=\n   match find_var_v uf eqn with\n   | None   => match (vars eqn) with\n               | nil    => (eqn::l,rbt)\n               | v'::l' => (l,rbt) (*should never happen*)\n               end\n   | Some v => (l,find_add v eqn rbt)\n   end.\n  Definition add_equation2RBT_l {A : Type} `{VAB : varsable A var} (eqn:A) uf rbt l := \n   fst (add_equation2RBT eqn uf rbt l).\n  Implicit Arguments add_equation2RBT_l [A VAB].\n  Definition add_equation2RBT_rbt {A : Type} `{VAB : varsable A var} (eqn:A) uf rbt l := \n   snd (add_equation2RBT eqn uf rbt l).\n  Implicit Arguments add_equation2RBT_rbt [A VAB].\n  Definition get_list {A B : Type} (p : (list A * RBT.map_of B)%type) := fst p.\n  Definition get_rbt {A B : Type} (p : (list A * RBT.map_of B)%type) := snd p.\n  (*Precondition: all vars were already in uf*)\n  Definition eqnlist2RBT {A : Type} `{VAB : varsable A var}\n  (l : list A) (uf : UF.t) : (list A * RBT.map_of (list A))%type :=\n   fold_right (fun eqn p => add_equation2RBT eqn uf (snd p) (fst p)) \n              (nil,emptyRBT (list A)) l.\n  Definition eqnlist2RBT_l {A : Type} `{VAB : varsable A var} (l : list A) uf :=\n   fst (eqnlist2RBT l uf).\n  Implicit Arguments eqnlist2RBT_l [A VAB].\n  Definition eqnlist2RBT_rbt {A : Type} `{VAB : varsable A var} (l : list A) uf :=\n   snd (eqnlist2RBT l uf).\n  Implicit Arguments eqnlist2RBT_rbt [A VAB].\n  (*Conditions for UF section*)\n  Definition UF_in_cond {A : Type} `{VAB : varsable A var} (uf : UF.t) (l : A)  : Prop :=\n   forall v', In v' (vars l) -> UF.In uf v'.\n  Definition UF_component_cond {A : Type} `{VAB : varsable A var} (uf : UF.t)  (eqn : A): Prop :=\n   (vars eqn) <> nil ->\n   (exists v, forall v', In v' (vars eqn) -> UF.find_e uf v' = Some v).\n  Definition UF_lcomponents_cond {A : Type} `{VAB : varsable A var} uf (l : list A) : Prop :=\n   forall eqn, In eqn l -> UF_component_cond uf eqn.\n  Definition UF_set_of_cond {A : Type} `{VAB:varsable A var}(uf : UF.t) (eqn : A) : Prop :=\n   forall v1 v2, In v1 (vars eqn) -> In v2 (vars eqn) -> UF.In uf v1 /\\ UF.set_of uf v1 v2.\n\n  Lemma UF_set_of_cond_equiv: forall {A : Type} `{VAB:varsable A var} uf (eqn : A),\n   UF_set_of_cond uf eqn <-> UF_component_cond uf eqn.\n  Proof.\n   intros. split;repeat intro.\n   unfold UF_set_of_cond in H.\n   remember (vars eqn).\n   icase l. tauto.\n   assert (In v (v::l)). left;trivial.\n   destruct (H v v H1 H1).\n   apply In_Some in H2.\n   destruct H2. exists x. intros.\n   destruct (H v v' H1 H4). congruence.\n   unfold UF_component_cond in H.\n   detach H. destruct H.\n   generalize (H _ H0);intro.\n   generalize (H _ H1);intro.\n   split. apply In_Some. exists x;trivial.\n   congruence.\n   intro. unfold var in H. unfold t in *.\n   rewrite H in H0. inv H0.\n  Qed.\n\n  Lemma UF_in_cond_prop1 : forall {A : Type} `{VAB : varsable A var} (a : A) l uf,\n   UF_in_cond uf  (a::l) <-> UF_in_cond uf a /\\ UF_in_cond uf l.\n  Proof.\n   repeat intro.\n   unfold UF_in_cond.\n   simpl. split;intros.\n   split;intros;\n   spec H v'; rewrite in_app_iff in H; tauto.\n   rewrite in_app_iff in H0.\n   destruct H.\n   spec H v'. spec H1 v'. tauto.\n  Qed.\n\n  Lemma UF_in_cond_prop2: forall (A : Type) (VAB : varsable A var) (l : list A) (a : A)  uf,\n   UF_in_cond uf l -> In a l-> UF_in_cond uf a.\n  Proof.\n   induction l;intros. inversion H0.\n   apply UF_in_cond_prop1 in H.\n   destruct H0. subst. tauto.\n   apply IHl;trivial. tauto.\n  Qed.\n\n  Lemma UF_component_cond_prop1: forall {A : Type} `{VAB : varsable A var} (a : A) l uf,\n   UF_component_cond uf (a::l)  -> UF_component_cond uf a /\\ UF_component_cond uf l.\n  Proof. \n   intros.\n   unfold UF_component_cond in *.\n   split;intros.\n   detach H. destruct H.\n   exists x;intros. apply H.\n   simpl. rewrite in_app_iff. left;trivial.\n   simpl. intro. apply H0. apply app_eq_nil in H. tauto.\n   detach H. destruct H.\n   exists x;intros. apply H.\n   simpl. rewrite in_app_iff. right;trivial.\n   simpl. intro. apply H0. apply app_eq_nil in H. tauto.\n  Qed.\n\n  Lemma UF_component_cond_prop2: forall {A : Type} `{VAB : varsable A var} (a : A) uf,\n   UF_component_cond uf a -> UF_in_cond uf a.\n  Proof.\n   intros.\n   unfold UF_in_cond,UF_component_cond in *.\n   intros.\n   detach H. destruct H. spec H v' H0.\n   unfold UF.In. rewrite H. simpl. trivial.\n   intro. unfold var in *. unfold t in *. \n   rewrite H in H0. inv H0.\n  Qed.\n\n  Lemma UF_lcomponents_cond_prop1: forall {A : Type} `{VAB : varsable A var} (a : A) l uf,\n   UF_lcomponents_cond uf (a::l) <-> UF_component_cond uf a /\\ UF_lcomponents_cond uf l.\n  Proof.\n   intros.\n   unfold UF_lcomponents_cond,UF_component_cond in *.\n   split;intros.\n   split;intros.\n   apply H;trivial. left;trivial.\n   apply H;trivial. right;trivial.\n   destruct H.\n   destruct H0. subst a. apply H. trivial.\n   apply H2;trivial.\n  Qed.\n\n  Lemma UF_lcomponents_cond_prop2: forall {A : Type} `{VAB: varsable A var} (l : list A) uf,\n   UF_component_cond uf l -> UF_lcomponents_cond uf l.\n  Proof.\n   intros.\n   unfold UF_lcomponents_cond, UF_component_cond in *.\n   intros.\n   detach H. destruct H.\n   exists x. intros. apply H. eapply sublist_vars.\n   apply H0. apply H2.\n   intro. apply H1. apply sublist_vars in H0. rewrite H in H0.\n   apply sublist_nil;trivial.\n  Qed.\n\n  Lemma UF_lcomponents_cond_prop3: forall {A : Type} `{VAB: varsable A var} (l : list A) uf,\n   UF_lcomponents_cond uf l -> UF_in_cond uf l.\n  Proof.\n   intros.\n   unfold UF_lcomponents_cond,UF_component_cond,UF_in_cond in *.\n   intros.\n   apply var_list_exist in H0.\n   destruct H0 as [? [? ?]].\n   spec H x H0. detach H. destruct H.\n   spec H v' H1.\n   unfold UF.In. rewrite H. simpl;trivial.\n   intro. rewrite H in H1. inversion H1.\n  Qed.\n\n  Lemma UF_lcomponents_cond_prop4: forall {A : Type} `{VAB: varsable A var} (l l' : list A) uf,\n   UF_lcomponents_cond uf l -> sublist l' l -> UF_lcomponents_cond uf l'.\n  Proof.\n   intros.\n   unfold UF_lcomponents_cond in *.\n   intros. apply H. apply H0. apply H1.\n  Qed.\n\n\n  (*UF Lemmas section*)\n  Lemma find_rewrite: forall uf uf' e e',\n   (e',uf') = UF.find uf e -> uf' = UF.find_t uf e /\\ e' = UF.find_e uf e.\n  Proof.\n   intros.\n   unfold UF.find_t,UF.find_e. \n   rewrite<-H;simpl. tauto.\n  Qed.\n\n  Lemma add_singleton2uf_rewrite: forall uf uf' v v',\n   (uf',v') = add_singleton2uf uf v -> \n   uf' = add_singleton2uf_t uf v /\\ v' = add_singleton2uf_v uf v.\n  Proof.\n   intros.\n   unfold add_singleton2uf_t,add_singleton2uf_v.\n   rewrite<- H. simpl;tauto.\n  Qed.\n\n  Lemma add_singleton2uf_not_In: forall uf v ,\n   ~UF.In uf v -> \n   UF.set_in (add_singleton2uf_t uf v) (set_singleton v).\n  Proof.\n   intros.\n   unfold add_singleton2uf_t,add_singleton2uf .\n   remember (UF.find uf v). icase p.\n   apply find_rewrite in Heqp. destruct Heqp;subst.\n   remember (UF.find_e uf v). icase o;simpl.\n   elimtype False. apply H.\n   apply In_Some. exists e0. rewrite Heqo;trivial.\n   apply UF.singleton_set_in_refl. intro. apply H.\n   rewrite In_find_reduce in H0. trivial.\n  Qed.\n\n  Lemma add_singleton2uf_In: forall uf v1 v2,\n   UF.In uf v1 -> UF.set_of uf v1 v2 ->\n   forall v, UF.In (add_singleton2uf_t uf v) v1 /\\ \n             UF.set_of (add_singleton2uf_t uf v) v1 v2 .\n  Proof.\n   intros.\n   unfold add_singleton2uf_t,add_singleton2uf.\n   remember (UF.find uf v). icase p.\n   apply find_rewrite in Heqp.\n   destruct Heqp;subst.\n   remember (UF.find_e uf v). icase o;simpl.\n   split. apply In_find_reduce. trivial.\n   rewrite set_of_find_reduce. trivial.\n   assert (~UF.In (UF.find_t uf v) v).\n    rewrite In_find_reduce. intro.\n    apply In_Some in H1. destruct H1. rewrite H1 in Heqo. inv Heqo.\n   apply singleton_set_of;trivial.\n   apply In_find_reduce. trivial.\n   rewrite set_of_find_reduce. trivial.\n  Qed.\n\n  Lemma add_singleton2uf_set_of: forall uf v,\n   UF.In (add_singleton2uf_t uf v) (add_singleton2uf_v uf v) /\\ \n   UF.set_of (add_singleton2uf_t uf v) (add_singleton2uf_v uf v) v.\n  Proof.\n   intros.\n   unfold add_singleton2uf_t,add_singleton2uf_v,add_singleton2uf.\n   remember (UF.find uf v). icase p.\n   apply find_rewrite in Heqp.\n   destruct Heqp;subst.\n   remember (UF.find_e uf v). icase o;simpl.\n   split. apply In_find_reduce. apply find_In with v.\n   rewrite Heqo;trivial.\n   rewrite set_of_find_reduce.\n   apply set_of_comm.\n   apply Some_set_of.\n   rewrite Heqo;trivial.\n   split. apply In_Some.\n   exists v. symmetry in Heqo. \n   apply set_singleton_find. \n   apply UF.singleton_set_in_refl.\n   rewrite In_find_reduce.\n   apply In_None. trivial.\n   apply set_of_refl.\n  Qed.\n\n  Lemma union_singleton2uf_rewrite: forall uf uf' v v',\n   (uf',v') = union_singleton2uf uf v -> \n   uf' = union_singleton2uf_t uf v /\\ v' = union_singleton2uf_v uf v.\n  Proof.\n   intros.\n   unfold union_singleton2uf_t,union_singleton2uf_v.\n   rewrite<- H. simpl;tauto.\n  Qed.\n   \n  Lemma union_singleton2uf_In: forall uf v v' v1 v2, \n   UF.In uf v ->\n   UF.In uf v1 ->\n   UF.set_of uf v1 v2 -> \n   UF.In (union_singleton2uf_t v' (uf,Some v)) v1 /\\ \n   UF.set_of (union_singleton2uf_t v' (uf,Some v) ) v1 v2. \n  Proof.\n   intros.\n   unfold union_singleton2uf_t,union_singleton2uf.\n   remember (add_singleton2uf uf v'). icase p;simpl.\n   apply add_singleton2uf_rewrite in Heqp.\n   destruct Heqp;subst.\n   generalize (add_singleton2uf_set_of uf v);intro.\n   destruct H2. \n   generalize (add_singleton2uf_In _ _ _ H0 H1 v);intro.\n   simpl.\n   destruct H4.\n   apply union_set_of.\n   apply add_singleton2uf_set_of.\n   eapply add_singleton2uf_In.\n   apply H. apply set_of_refl.\n   eapply add_singleton2uf_In.\n   apply H0. apply set_of_refl.\n   apply add_singleton2uf_In;trivial.\n  Qed.\n\n  Lemma union_singleton2uf_None: forall uf v,\n   union_singleton2uf v (uf,None) = \n  (add_singleton2uf_t uf v, Some (add_singleton2uf_v uf v)).\n  Proof.\n   intros.\n   unfold union_singleton2uf.\n   unfold add_singleton2uf_v,add_singleton2uf_t.\n   remember (add_singleton2uf uf v).\n   destruct p. simpl. trivial.\n  Qed.\n\n  Lemma union_singleton2uf_Some: forall uf a a' v,\n   UF.In uf a ->\n   union_singleton2uf_v a' (uf,Some a) = Some v ->\n   UF.In (union_singleton2uf_t a' (uf,Some a)) v /\\ \n   UF.set_of (union_singleton2uf_t a' (uf,Some a)) a' v.\n  Proof.\n   intros.\n   unfold union_singleton2uf_t.\n   unfold union_singleton2uf_v in H0.\n   unfold union_singleton2uf in *.\n   remember (add_singleton2uf uf a'). icase p.\n   apply add_singleton2uf_rewrite in Heqp.\n   destruct Heqp;subst. simpl in *.\n   split. eapply find_In. apply H0.\n   apply set_of_trans with (e':=add_singleton2uf_v uf a').\n   eapply union_set_of.\n   apply add_singleton2uf_set_of.\n   eapply add_singleton2uf_In;trivial.\n   apply set_of_refl.\n   destruct (add_singleton2uf_set_of uf a').\n   apply In_Some in H1. destruct H1.\n   apply In_Some. exists x. congruence.\n   apply set_of_comm. apply add_singleton2uf_set_of.\n   apply Some_set_of in H0. apply H0.\n  Qed.   \n\n  Lemma union_singleton2uf_combine: forall uf a v,\n   UF.In uf a ->\n   UF.In (union_singleton2uf_t v (uf, Some a)) a /\\ \n   UF.set_of (union_singleton2uf_t v (uf, Some a)) v a.\n  Proof.\n   intros.\n   unfold union_singleton2uf_t,union_singleton2uf.\n   remember (add_singleton2uf uf v). icase p. simpl.\n   apply add_singleton2uf_rewrite in Heqp. destruct Heqp. subst.\n   split. eapply union_set_of.\n   apply add_singleton2uf_set_of.\n   eapply add_singleton2uf_In;trivial.\n   apply set_of_refl.\n   eapply add_singleton2uf_In;trivial.\n   apply set_of_refl.\n   apply set_of_refl.\n   apply set_of_trans with (add_singleton2uf_v uf v).\n   eapply union_set_of.\n   apply add_singleton2uf_set_of.\n   eapply add_singleton2uf_In;trivial.\n   apply set_of_refl.\n   destruct (add_singleton2uf_set_of uf v).\n   apply In_Some in H0. destruct H0.\n   apply In_Some. exists x.\n   rewrite<- H0.\n   generalize (set_of_rewrite);intro.\n   rewrite H2 in H1. congruence.\n   apply set_of_comm. apply add_singleton2uf_set_of.\n   apply union_combine.\n   apply add_singleton2uf_set_of.\n   eapply add_singleton2uf_In;trivial.\n   apply set_of_refl.\n  Qed.\n\n  Lemma union_singleton2uf_exist_Some: forall {A : Type} `{VAB:varsable A var} uf a v,\n   UF.In uf a ->\n   exists v', union_singleton2uf_v v (uf,Some a) = Some v'.\n  Proof.\n   intros.\n   unfold union_singleton2uf_v,union_singleton2uf.\n   remember (add_singleton2uf uf v).\n   icase p. apply add_singleton2uf_rewrite in Heqp.\n   destruct Heqp;subst. simpl.\n   apply In_Some.\n   eapply union_set_of.\n   apply add_singleton2uf_set_of.\n   eapply add_singleton2uf_In;trivial.\n   apply set_of_refl.\n   apply add_singleton2uf_set_of.\n   apply set_of_refl.\n  Qed.\n\n  Lemma add_list2uf_rewrite: forall uf uf' a' l,\n   (uf',a') = add_list2uf uf l -> \n   uf' = add_list2uf_t uf l /\\ a' = add_list2uf_v uf l.\n  Proof.\n   intros.\n   unfold add_list2uf_t,add_list2uf_v;rewrite<-H.\n   simpl;auto.\n  Qed.\n\n  Lemma add_list2uf_step_rewrite: forall uf a l,\n   add_list2uf uf (a::l) = union_singleton2uf a (add_list2uf uf l).\n  Proof.\n   intros. simpl. tauto.\n  Qed.\n\n  Lemma add_list2uf_single: forall uf a,\n   add_list2uf uf (a::nil) = union_singleton2uf a (uf,None).\n  Proof.\n   intros. simpl. tauto.\n  Qed.\n\n  Lemma add_list2uf_Some: forall {A : Type} `{VAB:varsable A var} l uf a,\n    add_list2uf_v uf l = Some a -> UF.In (add_list2uf_t uf l) a .\n  Proof.\n   induction l;intros.\n   unfold add_list2uf_v in H. inv H.\n   unfold add_list2uf_t.\n   unfold add_list2uf_v in H.\n   rewrite add_list2uf_step_rewrite in *.\n   remember (add_list2uf uf l).\n   remember (union_singleton2uf a p).\n   icase p0.\n   apply union_singleton2uf_rewrite in Heqp0.\n   destruct Heqp0;subst t0 o. simpl in *.\n   icase p. apply add_list2uf_rewrite in Heqp.\n   destruct Heqp;subst.\n   remember (add_list2uf_v uf l). icase o.\n   symmetry in Heqo. apply IHl in Heqo.\n   destruct (union_singleton2uf_combine _ _ a Heqo).\n   apply union_singleton2uf_Some;trivial.\n   unfold union_singleton2uf_v,union_singleton2uf_t in *.\n   rewrite union_singleton2uf_None in *. simpl in *.\n   inv H. apply add_singleton2uf_set_of.\n  Qed.\n\n  Lemma add_list2uf_None: forall {A : Type} `{VAB:varsable A var} l uf,\n   add_list2uf_v uf l = None <-> l = nil.\n  Proof.\n   induction l;intros;\n   unfold add_list2uf_v.\n   simpl;tauto.\n   rewrite add_list2uf_step_rewrite.\n   split;intros.\n   remember (add_list2uf uf l). icase p.\n   apply add_list2uf_rewrite in Heqp.\n   destruct Heqp;subst.\n   remember (add_list2uf_v uf l). \n   icase o;symmetry in Heqo.\n   apply add_list2uf_Some in Heqo.\n   apply union_singleton2uf_exist_Some with (v:=a) in Heqo.\n   destruct Heqo. \n   unfold union_singleton2uf_v in H0.\n   unfold var in *. unfold t in *. rewrite H0 in H. inv H.\n   apply IHl in Heqo. subst.\n   unfold add_list2uf_t in H. simpl in H.\n   destruct (add_singleton2uf uf a);inv H.\n   inv H.\n  Qed.\n\n  Lemma add_list2uf_In: forall {A : Type} `{VAB:varsable A var} l uf a a',\n   UF.In uf a ->\n   UF.set_of uf a a' ->\n   UF.In (add_list2uf_t uf l) a /\\ UF.set_of (add_list2uf_t uf l) a a'.\n  Proof.\n   induction l;intros.\n   unfold add_list2uf_t;simpl. tauto.\n   unfold add_list2uf_t.\n   rewrite add_list2uf_step_rewrite.\n   remember (add_list2uf uf l).\n   remember (union_singleton2uf a p).\n   icase p0. \n   apply union_singleton2uf_rewrite in Heqp0.\n   destruct Heqp0;subst. simpl.\n   remember (add_list2uf uf l).\n   icase p.\n   apply add_list2uf_rewrite in Heqp. destruct Heqp.\n   icase o;subst.\n   apply union_singleton2uf_In.\n   apply add_list2uf_Some. rewrite H2;trivial.\n   eapply IHl;trivial. apply H0.\n   apply IHl;trivial.\n   unfold union_singleton2uf_t.\n   rewrite union_singleton2uf_None. simpl.\n   apply add_singleton2uf_In.\n   eapply IHl;trivial. apply H0.\n   apply IHl;trivial.\n  Qed.  \n\n  Lemma add_list2uf_set_of: forall {A : Type} `{VAB:varsable A var} l uf a v,\n   In v l -> \n   add_list2uf_v uf l = Some a ->\n   UF.set_of (add_list2uf_t uf l) a v.\n  Proof.\n   induction l;intros. inv H.\n   generalize (add_list2uf_Some _ _ _ H0);intro.\n   unfold add_list2uf_t. unfold add_list2uf_v,add_list2uf_t in H0,H1.\n   rewrite add_list2uf_step_rewrite in *.\n   remember (union_singleton2uf a (add_list2uf uf l)).\n   destruct p. apply union_singleton2uf_rewrite in Heqp.\n   destruct Heqp. subst. simpl in *.\n   apply set_of_comm.\n   remember (add_list2uf uf l).\n   icase p. apply add_list2uf_rewrite in Heqp.\n   destruct Heqp. subst.\n   remember (add_list2uf_v uf l).\n   symmetry in Heqo. icase o.\n   destruct H;subst.\n   apply union_singleton2uf_Some;trivial.\n   apply add_list2uf_Some;trivial.\n   generalize (IHl _ _ _ H Heqo);intro.\n   apply add_list2uf_Some in Heqo.\n   remember (add_list2uf_t uf l) as uf'.\n   apply set_of_comm.\n   apply set_of_trans with (e':=v0).\n   apply set_of_trans with (e':=a).\n   apply set_of_comm.\n   apply union_singleton2uf_Some;trivial.\n   apply union_singleton2uf_combine;trivial.\n   apply union_singleton2uf_In;trivial.\n\n   unfold union_singleton2uf_t,union_singleton2uf_v in *.\n   rewrite union_singleton2uf_None in *. simpl in *. inv H0.\n   destruct H;subst.\n   apply set_of_comm. apply add_singleton2uf_set_of.\n   apply add_list2uf_None in Heqo. subst. inv H.\n  Qed.\n\n  Lemma eqn2uf_component_cond: forall {A : Type} `{VAB:varsable A var} \n  (a : A) (uf : UF.t),\n   UF_component_cond (eqn2uf_t uf a) a.\n  Proof.\n   intros. apply UF_set_of_cond_equiv.\n   repeat intro.\n   unfold eqn2uf_t,eqn2uf.\n   remember (add_list2uf uf (vars a)).\n   icase p. apply add_list2uf_rewrite in Heqp.\n   destruct Heqp;subst. simpl.\n   remember (add_list2uf_v uf (vars a)).\n   symmetry in Heqo. icase o.\n   apply add_list2uf_set_of with (uf:=uf) (a:=v) in H;trivial.\n   apply add_list2uf_set_of with (uf:=uf) (a:=v) in H0;trivial.\n   apply add_list2uf_Some in Heqo.\n   apply In_Some in Heqo. destruct Heqo.\n   split. apply In_Some. exists x. \n   unfold var in *;unfold t in *;congruence.\n   unfold var in *;unfold t in *;congruence.\n   apply add_list2uf_None in Heqo.\n   unfold var in *;unfold t in *;rewrite Heqo in H. inv H.\n  Qed.\n\n  Lemma eqnlist2uf_lcomponents_cond: forall {A : Type} `{VAB:varsable A var} (l : list A),\n   UF_lcomponents_cond (eqnlist2uf l) l.\n  Proof.\n   induction l;intros.\n   unfold UF_lcomponents_cond. intros. inversion H.\n   rewrite UF_lcomponents_cond_prop1. split.\n   apply eqn2uf_component_cond. simpl.\n   do 2 intro.\n   apply UF_set_of_cond_equiv.\n   spec IHl eqn H.\n   apply UF_set_of_cond_equiv in IHl.\n   repeat intro.\n   destruct (IHl v1 v2 H0 H1).\n   unfold eqn2uf_t,eqn2uf.\n   apply add_list2uf_In;trivial.\n  Qed.\n\n\n  (*RBT Lemmas section*)\n\n  Lemma find_list_rbt_spec: forall {B : Type} rbt a (b : list B),\n   RBT.MapsTo a b rbt -> find_list_rbt a rbt = b.\n  Proof.\n   intros.\n   unfold find_list_rbt.\n   rewrite<- RBT.find_spec in H.\n   rewrite H. trivial.\n  Qed.\n  Lemma find_add_spec1: forall {A : Type} `{VAB : varsable A var} \n   (eqn : A) v rbt,\n   RBT.MapsTo v (eqn::(find_list_rbt v rbt)) (find_add v eqn rbt).\n  Proof.\n   intros.\n   unfold find_list_rbt,find_add.\n   remember (RBT.find v rbt). \n   icase o;\n   apply RBT.add_spec1.\n  Qed.\n  Lemma find_add_spec2: forall {A : Type} `{VAB : varsable A var}\n   (eqn : A) v v' l rbt,\n   v' <> v ->\n   (RBT.MapsTo v' l (find_add v eqn rbt) <-> RBT.MapsTo v' l rbt). \n  Proof.\n   intros.\n   unfold find_add.\n   remember (RBT.find v rbt).\n   icase o;apply RBT.add_spec2;trivial.\n  Qed.\n\n  Lemma find_var_v_spec1: forall {A : Type} `{VAB : varsable A var} (eqn : A) uf,\n   UF_in_cond uf eqn ->\n   vars eqn <> nil ->\n   exists v, find_var_v uf eqn = Some v.\n  Proof.\n   intros.\n   unfold find_var_v,find_var.\n   unfold UF_in_cond in H.\n   remember (vars eqn). icase l. tauto.\n   spec H v. detach H. unfold UF.In,UF.find_e in H.\n   icase (UF.find uf v). icase o. exists e0. trivial.\n   left;trivial.\n  Qed.\n  \n  Lemma add_equation2RBT_rewrite : forall {A : Type} `{VAB :varsable A var} (eqn : A) rbt rbt' uf l l',\n   (l',rbt') = add_equation2RBT eqn rbt uf l ->\n   l' = add_equation2RBT_l eqn rbt uf l /\\\n   rbt' = add_equation2RBT_rbt eqn rbt uf l.\n  Proof.  \n   intros.\n   unfold add_equation2RBT_l,add_equation2RBT_rbt.\n   rewrite <-H;simpl. tauto.\n  Qed.\n\n  Lemma add_equation2RBT_spec1 : forall {A : Type} `{VAB :varsable A var} v (eqn : A) rbt uf l,\n   find_var_v uf eqn = Some v -> \n   RBT.MapsTo v (eqn::(find_list_rbt v rbt)) \n                (add_equation2RBT_rbt eqn uf rbt l).\n  Proof with auto.\n   intros.\n   unfold add_equation2RBT_rbt,add_equation2RBT in *.\n   icase (find_var_v uf eqn). inv H.\n   apply find_add_spec1.\n  Qed.\n\n  Lemma add_equation2RBT_spec2 : forall {A : Type} `{VAB :varsable A var} v v' eqn rbt uf l l',\n   find_var_v uf eqn = Some v -> \n   v' <> v ->\n   (RBT.MapsTo v' l' (add_equation2RBT_rbt eqn uf rbt l) <-> \n    RBT.MapsTo v' l' rbt).\n  Proof.\n   intros.\n   unfold add_equation2RBT_rbt,add_equation2RBT.\n   remember (find_var_v uf eqn). icase o. inv H.\n   apply find_add_spec2;trivial.\n  Qed.\n\n  Lemma add_equation2RBT_spec3: forall {A : Type} `{VAB :varsable A var} v eqn rbt uf l,\n   find_var_v uf eqn = Some v -> \n   add_equation2RBT_l eqn uf rbt l = l.\n  Proof.\n   intros.\n   unfold add_equation2RBT_l,add_equation2RBT.\n   icase (find_var_v uf eqn).\n  Qed.\n\n  Lemma add_equation2RBT_spec4 : forall {A : Type} `{VAB :varsable A var} (eqn : A) rbt uf l,\n   vars eqn = nil ->\n   add_equation2RBT eqn uf rbt l = (eqn::l,rbt).\n  Proof.\n   intros.\n   unfold add_equation2RBT.\n   unfold find_var_v,find_var.\n   remember (vars eqn). icase l0.\n  Qed.\n\n  Lemma add_equation2RBT_spec5 : forall {A : Type} `{VAB : varsable A var} (eqn : A) rbt uf l,\n   add_equation2RBT_l eqn uf rbt l = eqn::l ->\n   vars eqn = nil.\n  Proof.\n   intros.\n   unfold add_equation2RBT_l,add_equation2RBT in H.\n   unfold find_var_v,find_var in H.\n   remember (vars eqn). icase l0.\n   assert (forall {A : Type} (l' : list A) a, l' = a::l' -> False).\n    induction l'; repeat intro. inv H0.\n    spec IHl' a. apply IHl'. inversion H0. subst a;trivial.\n   elimtype False.\n   icase (UF.find uf v). \n   icase o;inversion H;\n   apply H0 with A l eqn;trivial.\n  Qed.\n\n  Lemma add_equation2RBT_spec6 : forall {A : Type} `{VAB : varsable A var} (eqn : A) rbt uf l l' v,\n   find_var_v uf eqn = Some v -> l' <> nil ->\n   RBT.MapsTo v (eqn::l') (add_equation2RBT_rbt eqn uf rbt l) ->\n   RBT.MapsTo v l' rbt.\n  Proof.\n   intros.\n   unfold add_equation2RBT_rbt,add_equation2RBT in H1.\n   remember (find_var_v uf eqn). icase o. inv H.\n   unfold find_add in H1.\n   remember (RBT.find v rbt). icase o. simpl in H1.\n   assert (eqn::l' = eqn::l0). \n    eapply RBT.MapsTo_spec2. apply H1. apply RBT.add_spec1.\n   inv H.\n   symmetry in Heqo0. apply RBT.find_spec. trivial.\n   assert (eqn::l' = eqn::nil).\n    eapply RBT.MapsTo_spec2. apply H1. apply RBT.add_spec1.\n   inv H. tauto.\n  Qed.\n\n  Lemma eqnlist2RBT_rewrite: forall {A} `{VAB : varsable A var} (l l' : list A) uf rbt,\n   (l',rbt) = eqnlist2RBT l uf ->\n   l' = eqnlist2RBT_l l uf/\\\n   rbt = eqnlist2RBT_rbt l uf.\n  Proof.\n   intros.\n   unfold eqnlist2RBT_l,eqnlist2RBT_rbt.\n   rewrite <- H. simpl. tauto.\n  Qed.\n\n  Lemma eqnlist2RBT_step_rewrite: forall {A} `{VAB : varsable A var} (eqn : A) l uf,\n   eqnlist2RBT (eqn::l) uf = add_equation2RBT eqn uf (eqnlist2RBT_rbt l uf) (eqnlist2RBT_l l uf).\n  Proof.\n   intros. simpl. trivial.\n  Qed.\n\n  Lemma eqnlist2RBT_spec1: forall {A} `{VAB : varsable A var} l (eqn : A) uf v,\n   UF_in_cond uf l-> \n   In eqn l -> find_var_v uf eqn = Some v -> \n   exists l', RBT.MapsTo v l' (eqnlist2RBT_rbt l uf) /\\ In eqn l'.\n  Proof.\n   induction l;intros. inv H0.\n   destruct H0. subst a.\n   simpl.\n   exists (eqn::(find_list_rbt v (eqnlist2RBT_rbt l uf))).\n   split.\n   apply add_equation2RBT_spec1;trivial.\n   left;trivial.\n   rewrite UF_in_cond_prop1 in H.\n   destruct H.\n   spec IHl eqn uf v H2 H0.\n   spec IHl H1.\n   destruct IHl as [? [? ?]].\n   simpl. \n   unfold eqnlist2RBT_rbt. rewrite eqnlist2RBT_step_rewrite.\n   generalize (list_eq_dec e_eq_dec (vars a) nil);intros.\n   (*a is in list*)\n   destruct H5.\n   rewrite add_equation2RBT_spec4;trivial. simpl.\n   exists x. tauto.\n   (*a is in rbt*)\n   generalize (find_var_v_spec1 _ _ H n);intro.\n   destruct H5.\n   generalize (e_eq_dec v x0);intro.\n   (*Same principle element*)\n   destruct H6. subst x0.\n   assert (find_list_rbt v (get_rbt (eqnlist2RBT l uf)) = x).\n    apply find_list_rbt_spec;trivial.\n   exists (a::x).\n   rewrite<-H6.\n   split. apply add_equation2RBT_spec1;trivial.\n   right. congruence.\n   (*Different principle elements*)\n   exists x. eapply add_equation2RBT_spec2 in n0; trivial.\n   unfold add_equation2RBT_rbt in n0. rewrite n0.\n   split;trivial. apply H5.\n  Qed.\n\n  Lemma list2RBT_spec2 : forall {A} `{VAB : varsable A var} (l l' : list A) uf v,\n   UF_in_cond uf l ->\n   RBT.MapsTo v l' (eqnlist2RBT_rbt l uf) ->\n   sublist l' l.\n  Proof.\n   induction l;repeat intro.\n   simpl in H.\n   assert (RBT.Empty (emptyRBT (list A))).\n    apply RBT.empty_spec.\n   spec H2 v l'. contradiction.\n   simpl in H0.\n   generalize (list_eq_dec e_eq_dec (vars a) nil);intro.\n   rewrite UF_in_cond_prop1 in H. destruct H.\n   unfold eqnlist2RBT_rbt in H0.\n   rewrite eqnlist2RBT_step_rewrite in H0.\n   (*a is in list*)\n   destruct H2. \n   rewrite add_equation2RBT_spec4 in H0;trivial.\n   spec IHl l' uf v H3 H0.\n   right. apply IHl. trivial.\n   (*a is in rbt*)\n   generalize (find_var_v_spec1 _ _ H n);intro.\n   destruct H2. \n   generalize (e_eq_dec v x);intro.\n   destruct H4.\n   (*Same principle element*)\n   subst x.\n   assert (l' = a :: find_list_rbt v (get_rbt (eqnlist2RBT l uf))).\n    eapply RBT.MapsTo_spec2. apply H0. apply add_equation2RBT_spec1;trivial.\n   rewrite H4 in *.\n   destruct H1. subst a. left;trivial.\n   apply add_equation2RBT_spec6 in H0;trivial.\n   spec IHl (find_list_rbt v (get_rbt (eqnlist2RBT l uf))) uf v H3 H0.\n   right. apply IHl. trivial.\n   intro. rewrite H5 in H1. inv H1.\n   (*Different priciple elements*)\n   generalize (add_equation2RBT_spec2 _ _ _ (eqnlist2RBT_rbt l uf) _ (eqnlist2RBT_l l uf) l' H2 n0);intro.\n   rewrite H4 in H0.\n   spec IHl l' uf v H3 H0.\n   right. apply IHl;trivial.\n  Qed.\n\n  Lemma list2RBT_spec3: forall {A} `{VAB : varsable A var} (l : list A) eqn uf,\n   UF_in_cond uf l -> \n   ((In eqn l /\\ vars eqn = nil) <-> In eqn (eqnlist2RBT_l l uf)).\n  Proof with try tauto.\n   induction l;intros.\n   simpl. tauto.\n   rewrite UF_in_cond_prop1 in H. destruct H.\n   spec IHl eqn uf H0. destruct IHl.\n   simpl.\n   unfold eqnlist2RBT_l. rewrite eqnlist2RBT_step_rewrite.\n   generalize (list_eq_dec e_eq_dec (vars a) nil);intro.\n   destruct H3.\n   (*a is in list*)\n   rewrite add_equation2RBT_spec4;trivial.\n   simpl. split;intros... destruct H3... subst...\n   (*a is in rbt*)\n   apply find_var_v_spec1 in H;trivial.\n   destruct H.\n   remember (add_equation2RBT a uf (eqnlist2RBT_rbt l uf) (eqnlist2RBT_l l uf)).\n   icase p. apply add_equation2RBT_rewrite in Heqp.\n   destruct Heqp;subst.\n   rewrite add_equation2RBT_spec3 with (v:=x);trivial.\n   split;intros... destruct H3. destruct H3... subst...\n  Qed.\n\n  Lemma list2RBT_spec4: forall {A} `{VAB : varsable A var} (l l' :list A) uf eqn v,\n   UF_in_cond uf l ->\n   RBT.MapsTo v l' (eqnlist2RBT_rbt l uf) ->\n   In eqn l' ->\n   find_var_v uf eqn = Some v.\n  Proof.\n   induction l;intros. \n   simpl in H0. \n   assert (RBT.Empty (emptyRBT (list A))).\n    apply RBT.empty_spec.\n   spec H2 v l'. contradiction.\n   simpl in H0. rewrite UF_in_cond_prop1 in H.\n   destruct H.\n   generalize (list_eq_dec e_eq_dec (vars a) nil);intro.\n   unfold eqnlist2RBT_rbt in H0.\n   rewrite eqnlist2RBT_step_rewrite in H0.\n   destruct H3.\n   rewrite add_equation2RBT_spec4 in H0;trivial.\n   apply IHl with l';trivial.\n   apply find_var_v_spec1 in H;trivial.\n   destruct H.\n   generalize (e_eq_dec v x);intro.\n   destruct H3. subst x.\n   assert ( l' = a::(find_list_rbt v (get_rbt (eqnlist2RBT l uf)))).\n    eapply RBT.MapsTo_spec2. apply H0. apply add_equation2RBT_spec1;trivial.\n   rewrite H3 in *.\n   destruct H1. subst a. trivial.\n   eapply IHl;trivial.\n   eapply add_equation2RBT_spec6. apply H.\n   assert (find_list_rbt v (get_rbt (eqnlist2RBT l uf)) <> nil).\n    intro. rewrite H4 in H1. inversion H1.\n   apply H4. apply H0. apply H1.\n   remember (add_equation2RBT a uf (eqnlist2RBT_rbt l uf) (eqnlist2RBT_l l uf)).\n   icase p. apply add_equation2RBT_rewrite in Heqp.\n   destruct Heqp;subst. simpl in H0.\n   rewrite add_equation2RBT_spec2 in H0;trivial.\n   eapply IHl;trivial. apply H0. apply H1. apply H. apply n0.\n  Qed.  \n\n  Lemma list2RBT_spec5: forall {A} `{VAB : varsable A var} (l l' : list A) v uf,\n   UF_in_cond uf l ->\n   RBT.MapsTo v l' (eqnlist2RBT_rbt l uf) ->\n   vars l' <> nil.\n  Proof.\n   induction l;intros.\n   simpl in H0.\n   unfold eqnlist2RBT_rbt in H0. simpl in H0.\n   assert (RBT.Empty (emptyRBT (list A))).\n    apply RBT.empty_spec.\n   spec H1 v l'. contradiction.\n   rewrite UF_in_cond_prop1 in H.\n   destruct H.\n   simpl in H0.\n   unfold eqnlist2RBT_rbt in H0.\n   rewrite eqnlist2RBT_step_rewrite in H0.\n   generalize (list_eq_dec e_eq_dec (vars a) nil);intro.\n   destruct H2.\n   rewrite add_equation2RBT_spec4 in H0;trivial.\n   eapply IHl. apply H1. apply H0.\n   eapply find_var_v_spec1 in n;try apply H.\n   destruct n.\n   generalize (e_eq_dec v x);intro.\n   destruct H3. subst x.\n   assert (l' = a::(find_list_rbt v (get_rbt (eqnlist2RBT l uf)))).\n    eapply RBT.MapsTo_spec2. apply H0. apply add_equation2RBT_spec1;trivial.\n   intro. rewrite H3 in H4. simpl in H4.\n   apply app_eq_nil in H4. destruct H4.\n   unfold find_var_v,find_var in H2.\n   unfold var in *. unfold t in *;rewrite H4 in H2. inversion H2.\n   remember (add_equation2RBT a uf (eqnlist2RBT_rbt l uf) (eqnlist2RBT_l l uf)).\n   icase p. apply add_equation2RBT_rewrite in Heqp.\n   destruct Heqp;subst. simpl in H0.\n   rewrite add_equation2RBT_spec2 in H0.\n   eapply IHl. apply H1. apply H0.\n   apply H2. apply n.\n  Qed.\n\n  Lemma list2RBT_spec6: forall {A} `{VAB : varsable A var} (l : list A) l1 l2 v1 v2 uf,\n   UF_lcomponents_cond uf l ->\n   RBT.MapsTo v1 l1 (eqnlist2RBT_rbt l uf) ->\n   RBT.MapsTo v2 l2 (eqnlist2RBT_rbt l uf) ->\n   (v1 <> v2 <-> disjoint (vars l1) (vars l2)).\n  Proof.\n   intros. split;repeat intro.\n   destruct H3.\n   copy H. apply UF_lcomponents_cond_prop3 in H5.\n   copy H0. copy H1.\n   apply list2RBT_spec2 in H0;trivial.\n   apply list2RBT_spec2 in H1;trivial.\n   apply var_list_exist in H3.\n   apply var_list_exist in H4.\n   destruct H3 as [? [? ?]]. destruct H4 as [? [? ?]].\n   apply list2RBT_spec4 with (eqn:= x0) in H6;trivial.\n   apply list2RBT_spec4 with (eqn:= x1) in H7;trivial.\n   generalize (H x0 (H0 _ H3));intro.\n   generalize (H x1 (H1 _ H4));intro.\n   unfold UF_component_cond in *.\n   detach H11. detach H10.\n   destruct H11;destruct H10.\n   unfold find_var_v,find_var in *.\n   remember (vars x0). icase l0.\n   remember (vars x1). icase l3.\n   generalize (H10 x H8);intro.\n   generalize (H11 x H9);intro.\n   generalize (H11 v0);intro. detach H14.\n   generalize (H10 v);intro. detach H15.\n   unfold UF.find_e in *. unfold var in *. unfold t in *;congruence.\n   left;trivial. left;trivial.\n   intro. rewrite H10 in H8. inversion H8.\n   intro. rewrite H11 in H9. inversion H9.\n   (*The other direction*)\n   subst v2.\n   assert (l1 = l2).\n    eapply RBT.MapsTo_spec2. apply H0. apply H1.\n   subst l2.\n   apply list2RBT_spec5 in H1. \n   icase (vars l1). spec H2 v. apply H2.\n   split;left;trivial.\n   apply UF_lcomponents_cond_prop3;trivial.\n  Qed.\n\n  Lemma list2RBT_spec7: forall {A} `{VAB : varsable A var} (l : list A) uf,\n   UF_in_cond uf l ->\n   vars (eqnlist2RBT_l l uf) = nil.\n  Proof.\n   intros.\n   assert (forall eqn, In eqn (eqnlist2RBT_l l uf) -> vars eqn = nil).\n    intros.\n    generalize (list2RBT_spec3 l  eqn uf);intro.\n    apply H1;trivial.\n   remember (eqnlist2RBT_l l uf). clear Heql0 H.\n   induction l0. trivial.\n   simpl. simpl in IHl0;rewrite IHl0.\n   rewrite H0. trivial.\n   left;trivial.\n   intros. apply H0. right;trivial.\n  Qed.\n\n\n  (*Other Lemmas section*)\n  \n  Lemma InA_Kvpeq_In: forall {A : Type} l k (val : A),\n   InA RBT.Kvpeq (k,val) l <-> In (k,val) l.\n  Proof.\n   induction l;intros. simpl.\n   apply InA_nil.\n   simpl.\n   rewrite InA_cons.\n   split;intro. \n   destruct H. left.\n   destruct a. compute in H. \n   destruct H;subst;trivial.\n   right. apply IHl;trivial.\n   destruct H. subst.\n   left. compute. tauto.\n   right. apply IHl;trivial.\n  Qed.\n\n  Lemma NoDupA_Kvpeq_NoDup: forall {A: Type} (l :list (var*A)),\n   NoDupA RBT.Kvpeq l <-> NoDup l.\n  Proof.\n   induction l;intros.\n   split;intros. apply NoDup_nil.\n   apply NoDupA_nil.\n   split;intros.\n   inv H.\n   apply NoDup_cons.\n   intro. apply H2. destruct a. apply InA_Kvpeq_In;trivial.\n   apply IHl;trivial.\n   inv H.\n   apply NoDupA_cons.\n   intro. apply H2. destruct a. apply InA_Kvpeq_In;trivial.\n   apply IHl;trivial.\n  Qed.\n\n  Lemma RBT_elements_diff: forall {A : Type} (rbt : RBT.map_of A) i j v v' a a',\n   nth_op i (RBT.elements rbt) = Some (v,a) ->\n   nth_op j (RBT.elements rbt) = Some (v',a') ->\n   (i <> j <-> v <> v').\n  Proof.\n   intros.\n   assert (InA RBT.Kvpeq (v,a) (RBT.elements rbt)).\n    apply InA_Kvpeq_In. apply nth_op_In. exists i;trivial.\n   assert (InA RBT.Kvpeq (v',a') (RBT.elements rbt)).\n    apply InA_Kvpeq_In. apply nth_op_In. exists j;trivial.\n   copy H1;copy H2.\n   apply RBT.elements_spec1 in H1.\n   apply RBT.elements_spec1 in H2.\n   generalize (RBT.elements_spec3 rbt);intro.\n   apply NoDupA_Kvpeq_NoDup in H5.\n   apply InA_Kvpeq_In in H3.\n   apply InA_Kvpeq_In in H4.\n   generalize (NoDup_nth_op_diff _ _ _ _ _ H5 H H0);intro.\n   split;repeat intro;subst.\n   apply H6 in H7. apply H7. f_equal.\n   eapply RBT.MapsTo_spec2.\n   apply H1. apply H2.\n   rewrite H0 in H. inv H. tauto.\n  Qed.\n   \n  Lemma remove_1st_spec2: forall {A: Type} (rbt : RBT.map_of (list A)) l,\n   (In l (remove_1st (RBT.elements rbt)) <-> \n   exists v, RBT.MapsTo v l rbt).\n  Proof.\n   intros.\n   rewrite remove_1st_spec1.\n   split;intros. destruct H.\n   exists x. apply RBT.elements_spec1.\n   apply InA_Kvpeq_In;trivial.\n   destruct H. exists x.\n   apply InA_Kvpeq_In.\n   apply RBT.elements_spec1;trivial.\n  Qed.\n\nEnd Internal_Structures.                ", "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/part/partition_ibase.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.27779216365272413}}
{"text": "Require 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(** * Program Logic *)\n\nModule Type Assertions\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\nExport doms procs heaps progs models.\n\n(** ** Assertion Language *)\n\nInductive Assn :=\n  | Aplain(B: Cond)\n  | Aex(f: Val -> Assn)\n  | Adisj(A1 A2: Assn)\n  | Astar(A1 A2: Assn)\n  | Awand(A1 A2: Assn)\n  | Apointsto(q: Qc)(E1 E2: Expr)\n  | Aproc(AP: AbstrProc)\n  | Abisim (AP AQ: AbstrProc).\n\nAdd Search Blacklist \"Assn_rect\".\nAdd Search Blacklist \"Assn_ind\".\nAdd Search Blacklist \"Assn_rec\".\n\nDefinition Atrue: Assn := Aplain (Bconst true).\nDefinition Afalse: Assn := Aplain (Bconst false).\n\nLemma assn_aex_ext : forall f g, f = g -> Aex f = Aex g.\nProof. intuition vauto. Qed.\n\nFixpoint Aiter (xs: list Assn): Assn :=\n  match xs with\n    | nil => Atrue\n    | A :: xs' => Astar A (Aiter xs')\n  end.\n\nFixpoint assn_fv (A: Assn)(x: Var): Prop :=\n  match A with\n    | Aplain B => In x (cond_fv B)\n    | Aex f => exists v: Val, assn_fv (f v) x\n    | Adisj A1 A2\n    | Astar A1 A2\n    | Awand A1 A2 => assn_fv A1 x \\/ assn_fv A2 x\n    | Apointsto _ E1 E2 => In x (expr_fv E1) \\/ In x (expr_fv E2)\n    | Aproc AP => aproc_fv AP x\n    | Abisim AP AQ => aproc_fv AP x \\/ aproc_fv AQ x\n  end.\n\nLemma assn_fv_iter :\n  forall (xs: list Assn)(x: Var),\n  assn_fv (Aiter xs) x <-> exists A, In A xs /\\ assn_fv A x.\nProof.\n  induction xs as [|A xs IH]; intro x.\n  - split; intro H; desf.\n  - split; intro H.\n    + simpl in H. destruct H as [H | H].\n      * exists A. split; vauto.\n      * rewrite IH in H. destruct H as (A' & H1 & H2).\n        exists A'. split; auto. by apply in_cons.\n    + destruct H as (A' & H1 & H2).\n      simpls. destruct H1 as [H1 | H1]; vauto.\n      right. rewrite IH. exists A'. split; vauto.\nQed.\n\nFixpoint assn_subst (x: Var)(E: Expr)(A: Assn): Assn :=\n  match A with\n    | Aplain B => Aplain (cond_subst x E B)\n    | Aex f => Aex (fun v => assn_subst x E (f v))\n    | Adisj A1 A2 => Adisj (assn_subst x E A1) (assn_subst x E A2)\n    | Astar A1 A2 => Astar (assn_subst x E A1) (assn_subst x E A2)\n    | Awand A1 A2 => Awand (assn_subst x E A1) (assn_subst x E A2)\n    | Apointsto q E1 E2 => Apointsto q (expr_subst x E E1) (expr_subst x E E2)\n    | Aproc AP =>  Aproc (aproc_subst x E AP)\n    | Abisim AP AQ => Abisim (aproc_subst x E AP) (aproc_subst x E AQ)\n  end.\n\nDefinition Aexists (x: Var)(A: Assn): Assn :=\n  Aex (fun v => assn_subst x (Econst v) A).\n\nLemma assn_subst_pres :\n  forall A x E, ~ assn_fv A x -> assn_subst x E A = A.\nProof.\n  induction A; intros x E H1; simpls.\n  - rewrite cond_subst_pres; auto.\n  - apply assn_aex_ext. extensionality y. rewrite H; auto.\n    intro H2. apply H1. by exists y.\n  - rewrite IHA1, IHA2; auto.\n  - rewrite IHA1, IHA2; auto.\n  - rewrite IHA1, IHA2; auto.\n  - repeat rewrite expr_subst_pres; auto.\n  - rewrite aproc_subst_pres; auto.\n  - repeat rewrite aproc_subst_pres; auto.\nQed.\n\n(** ** Sematics of Assertions *)\n\nFixpoint sat (ph: PermHeap)(P: Proc)(s: Store)(A: Assn): Prop :=\n  match A with\n    (* non-spatial assertions *)\n    | Aplain B => cond_eval B s = true\n    (* existential quantifiers *)\n    | Aex f => exists v, sat ph P s (f v)\n    (* disjunction *)\n    | Adisj A1 A2 => sat ph P s A1 \\/ sat ph P s A2\n     (* separating conjunction *)\n    | Astar A1 A2 =>\n        exists ph1 ph2,\n          permheap_disj ph1 ph2 /\\\n          permheap_add ph1 ph2 = ph /\\\n        exists P1 P2,\n          bisim (Ppar P1 P2) P /\\\n          sat ph1 P1 s A1 /\\\n          sat ph2 P2 s A2\n    (* magic wand *)\n    | Awand A1 A2 =>\n        forall ph' P',\n        permheap_disj ph ph' ->\n        sat ph' P' s A1 ->\n        sat (permheap_add ph ph') (Ppar P P') s A2\n    (* heap ownership *)\n    | Apointsto q E1 E2 =>\n        let l := expr_eval E1 s in\n        let v := expr_eval E2 s in\n        phc_leq (PHCcell q v) (ph l)\n    (* process ownership *)\n    | Aproc AP =>\n        let P1 := aproc_conv AP s in\n        exists P2, bisim P (Ppar P1 P2)\n    (* process bisimulation *)\n    | Abisim AP AQ => bisim (aproc_conv AP s) (aproc_conv AQ s)\n  end.\n\nLemma sat_pproc_eq :\n  forall A ph P1 P2 s, bisim P1 P2 -> sat ph P1 s A -> sat ph P2 s A.\nProof.\n  induction A; intros ph P1 P2 s H1 H2; vauto.\n  (* existential quantifiers *)\n  - simpl in H2. destruct H2 as (v & H2).\n    exists v. by apply H with P1.\n  (* disjunction *)\n  - simpls. destruct H2 as [H2 | H2].\n    left. by apply IHA1 with P1.\n    right. by apply IHA2 with P1.\n  (* separating conjunction *)\n  - simpls.\n    destruct H2 as (ph1 & ph2 & D1 & H2 & P3 & P4 & H3 & SAT1 & SAT2).\n    exists ph1, ph2. intuition.\n    exists P3, P4. intuition. by rewrite <- H1.\n  (* magic wand *)\n  - simpls. intros ph' P' H3 H4.\n    apply IHA2 with (Ppar P1 P').\n    + rewrite H1. reflexivity.\n    + apply H2; auto.\n  (* process ownership *)\n  - unfold sat in *.\n    destruct H2 as (P & H2).\n    exists P. rewrite <- H2. intuition.\nQed.\n\nAdd Parametric Morphism : sat\n  with signature eq ==> bisim ==> eq ==> eq ==> iff\n    as assn_sat_procmap_mor.\nProof.\n  intros ph P1 P2 H1 s A. split; intro H2.\n  - apply sat_pproc_eq with P1; auto.\n  - apply sat_pproc_eq with P2; auto.\nQed.\n\nLemma sat_subst :\n  forall A ph P s x E,\n  sat ph P s (assn_subst x E A) <->\n  sat ph P (updatestore s x (expr_eval E s)) A.\nProof.\n  induction A; intros ph P s y E'; auto.\n  (* non-spatial assertions *)\n  - split; intro H; simpls.\n    + by rewrite <- cond_eval_subst.\n    + by rewrite cond_eval_subst.\n  (* existential quantifiers *)\n  - split; intro H1; simpls.\n    + destruct H1 as (v & H1).\n      exists v. by apply H.\n    + destruct H1 as (v & H1).\n      exists v. by apply <- H.\n  (* disjunction *)\n  - split; intro H; simpls.\n    + destruct H as [H | H].\n      * left. by rewrite <- IHA1.\n      * right. by rewrite <- IHA2.\n    + destruct H as [H | H].\n      * left. by rewrite IHA1.\n      * right. by rewrite IHA2.\n  (* separating conjunction *)\n  - split; intro H; simpls.\n    + destruct H as (ph1 & ph2 & D1 & H1 & P1 & P2 & H2 & SAT1 & SAT2).\n      exists ph1, ph2. intuition.\n      exists P1, P2. intuition.\n      * by apply IHA1.\n      * by apply IHA2.\n    + destruct H as (ph1 & ph2 & D1 & H1 & P1 & P2 & H2 & SAT1 & SAT2).\n      exists ph1, ph2. intuition.\n      exists P1, P2. intuition.\n      * by apply <- IHA1.\n      * by apply <- IHA2.\n  (* magic wands *)\n  - split; intro H; simpls.\n    + intros ph' P' D1 SAT.\n      apply IHA2, H; auto.\n      by apply IHA1.\n    + intros ph' P' D1 SAT.\n      apply IHA2, H; auto.\n      by apply IHA1.\n  (* heap ownership *)\n  - split; intro H.\n    + simpl. repeat rewrite <- expr_eval_subst in *. vauto.\n    + simpl. repeat rewrite expr_eval_subst in *. vauto.\n  (* process ownership *)\n  - split; intro H.\n    + destruct H as (P' & H1). exists P'.\n      rewrite H1. apply bisim_par; auto.\n      by apply aproc_conv_subst.\n    + destruct H as (P' & H1). exists P'.\n      rewrite H1. apply bisim_par; auto.\n      symmetry. by apply aproc_conv_subst.\n  (* process bisimulation *)\n  - split; intro H.\n    + simpls. by repeat rewrite <- aproc_conv_subst.\n    + simpls. by repeat rewrite aproc_conv_subst.\nQed.\n\nLemma sat_agree :\n  forall A ph P s1 s2,\n    (forall x, assn_fv A x -> s1 x = s2 x) ->\n  sat ph P s1 A -> sat ph P s2 A.\nProof.\n  induction A; intros ph P s1 s2 H1.\n  (* plain assertions *)\n  - intro H2. simpls.\n    rewrite <- cond_agree with (s1 := s1); vauto.\n  (* existential quantifiers *)\n  - intro H2. simpls. destruct H2 as (v & H2).\n    exists v. apply H with s1; auto.\n    intros x H3. apply H1. by exists v.\n  (* disjunction *)\n  - intro H2. simpls.\n    destruct H2 as [H2 | H2].\n    + left. apply IHA1 with s1; auto.\n    + right. apply IHA2 with s1; auto.\n  (* separating conjunction *)\n  - intro H2; simpls.\n    destruct H2 as (ph1 & ph2 & D1 & H2 & P1 & P2 & H3 & SAT1 & SAT2).\n    exists ph1, ph2. intuition.\n    exists P1, P2. intuition.\n    * apply IHA1 with s1; auto.\n    * apply IHA2 with s1; auto.\n  (* magic wand *)\n  - intro H2. simpls.\n    intros ph' P' H3 H4.\n    apply IHA2 with s1; auto.\n    apply H2; auto. apply IHA1 with s2; auto.\n    intros x H6. symmetry. apply H1. by left.\n  (* heap ownership *)\n  - intro H2. unfold sat in *.\n    rewrite <- expr_agree with E1 s1 s2, <- expr_agree with E2 s1 s2; auto.\n    + red. intros x H3. apply H1. simpl. by right.\n    + red. intros x H3. apply H1. simpl. by left.\n  (* process ownership *)\n  - intro H2. unfold sat in *.\n    destruct H2 as (P' & H2). exists P'.\n    rewrite aproc_conv_agree with AP s2 s1; auto.\n    intros x H4. symmetry. apply H1. simpl. done.\n  (* process bisimulation *)\n  - intro H2. simpls.\n    rewrite aproc_conv_agree with AP s2 s1, aproc_conv_agree with AQ s2 s1; auto.\n    + intros x H3. symmetry. apply H1. by right.\n    + intros x H3. symmetry. apply H1. by left.\nQed.\n\nLemma sat_weaken :\n  forall A ph1 ph2 P1 P2 s,\n  permheap_disj ph1 ph2 ->\n  sat ph1 P1 s A ->\n  sat (permheap_add ph1 ph2) (Ppar P1 P2) s A.\nProof.\n  induction A; intros ph1 ph2 P1 P2 s H1 H2; auto.\n  (* existential quantifiers *)\n  - simpls. destruct H2 as (v & H2).\n    exists v. by apply H.\n  (* disjunction *)\n  - simpls. destruct H2 as [H2 | H2].\n    + left. by apply IHA1.\n    + right. by apply IHA2.\n  (* separating conjunction *)\n  - simpls.\n    destruct H2 as (ph3 & ph4 & D1 & H2 & P3 & P4 & H3 & SAT1 & SAT2).\n    clarify. exists ph3, (permheap_add ph4 ph2). intuition.\n    { by apply permheap_disj_assoc_l. }\n    { by rewrite permheap_add_assoc. }\n    exists P3, (Ppar P4 P2). intuition.\n    { rewrite par_assoc; auto. by rewrite H3. }\n    apply IHA2; auto. by apply permheap_disj_add_l with ph3.\n  (* magic wand *)\n  - simpls. intros ph' P' H4 H5.\n    rewrite permheap_add_assoc, <- par_assoc.\n    apply H2.\n    { by apply permheap_disj_assoc_l. }\n    rewrite permheap_add_comm, par_comm.\n    apply IHA1; auto.\n    apply permheap_disj_add_r with ph1; auto.\n    symmetry. by rewrite permheap_add_comm.\n  (* heap ownership *)\n  - unfold sat in *. rewrite <- permheap_add_cell.\n    apply phc_leq_weaken; vauto.\n  (* process ownership *)\n  - unfold sat in *. destruct H2 as (P & H2).\n    exists (Ppar P P2). by rewrite par_assoc, <- H2.\nQed.\n\nLemma sat_iter_permut :\n  forall xs ys,\n  Permutation xs ys ->\n  forall ph P s,\n  sat ph P s (Aiter xs) ->\n  sat ph P s (Aiter ys).\nProof.\n  intros xs ys PERM.\n  induction PERM; intros ph P s SAT; simpls.\n  - destruct SAT as (ph1 & ph2 & D1 & H1 & P1 & P2 & H2 & SAT1 & SAT2).\n    exists ph1, ph2. intuition.\n    exists P1, P2. intuition.\n  - destruct SAT as (ph1 & ph2 & D1 & H1 & P1 & P2 & H2 & SAT1 & SAT).\n    destruct SAT as (ph3 & ph4 & D2 & H3 & P3 & P4 & H4 & SAT3 & SAT4).\n    clarify.\n    exists ph3, (permheap_add ph1 ph4). intuition.\n    { apply permheap_disj_assoc_l.\n      + symmetry. by apply permheap_disj_add_r with ph4.\n      + rewrite permheap_add_comm.\n        by apply permheap_disj_assoc_r. }\n    { rewrite <- permheap_add_assoc.\n      rewrite permheap_add_comm with ph3 ph1.\n      by rewrite permheap_add_assoc. }\n    exists P3, (Ppar P1 P4). intuition.\n    { rewrite par_assoc.\n      rewrite par_comm with (P := P3)(Q := P1).\n      rewrite <- par_assoc.\n      by rewrite <- H2, <- H4. }\n    exists ph1, ph4. intuition.\n    { apply permheap_disj_add_r with ph3; auto.\n      by rewrite permheap_add_comm. }\n    exists P1, P4. intuition.\n  - by apply IHPERM2, IHPERM1.\nQed.\n\n(** ** Logical consequence *)\n\nDefinition entails (A1 A2: Assn): Prop :=\n  forall ph P s,\n    permheap_valid ph -> sat ph P s A1 -> sat ph P s A2.\nDefinition entails_rev (A1 A2: Assn): Prop := entails A2 A1.\nDefinition equiv (A1 A2: Assn): Prop := entails A1 A2 /\\ entails A2 A1.\n\nInstance entails_refl : Reflexive entails.\nProof. intro. red. intuition. Qed.\nInstance entails_trans : Transitive entails.\nProof. unfold entails. intuition. Qed.\nInstance entails_rev_refl : Reflexive entails_rev.\nProof. intro. red. intuition. Qed.\nInstance entails_rev_trans : Transitive entails_rev.\nProof. unfold entails_rev. intros ?????. by transitivity y. Qed.\nInstance equiv_refl : Reflexive equiv.\nProof. red. ins. split; vauto. Qed.\nInstance equiv_symm : Symmetric equiv.\nProof. red. intros A1 A2 (H1&H2). split; auto. Qed.\nInstance equiv_trans : Transitive equiv.\nProof. red. intros A1 A2 A3 (H1&H2) (H3&H4). split; by transitivity A2. Qed.\nInstance equiv_eq : Equivalence equiv.\nProof. split; intuition. Qed.\n\nHint Resolve entails_refl entails_rev_refl equiv_refl.\n\nLemma entails_flip : forall A1 A2, entails A1 A2 <-> entails_rev A2 A1.\nProof. ins. Qed.\n\n(** *** Congruence *)\n\nAdd Parametric Morphism : Adisj\n  with signature entails ==> entails ==> entails as adisj_entails_mor.\nProof.\n  intros A1 A1' ENT1 A2 A2' ENT2.\n  red. intros ph P s H1 [SAT | SAT]; simpls.\n  - left. apply ENT1; auto.\n  - right. apply ENT2; auto.\nQed.\n\nAdd Parametric Morphism : Adisj\n  with signature equiv ==> equiv ==> entails as adisj_equiv_ent_mor.\nProof. intros A1 A2 (H1&_) A3 A4 (H2&_). by rewrite H1, H2. Qed.\n\nAdd Parametric Morphism : Adisj\n  with signature equiv ==> equiv ==> equiv as adisj_equiv_mor.\nProof.\n  intros A1 A2 (H1&H2) A3 A4 (H3&H4). split.\n  - by rewrite H1, H3.\n  - by rewrite H2, H4.\nQed.\n\nAdd Parametric Morphism : Astar\n  with signature entails ==> entails ==> entails\n    as astar_entails_mor.\nProof.\n  intros A1 A1' ENT1 A2 A2' ENT2.\n  red. intros ph P s H1 SAT. simpls.\n  destruct SAT as (ph1 & ph2 & D1 & H2 & P1 & P2 & H3 & SAT1 & SAT2).\n  exists ph1, ph2. intuition.\n  exists P1, P2. intuition.\n  - apply ENT1; auto. by apply permheap_disj_valid_l in D1.\n  - apply ENT2; auto. by apply permheap_disj_valid_r in D1.\nQed.\n\nAdd Parametric Morphism : Astar\n  with signature equiv ==> equiv ==> entails as astar_equiv_ent_mor.\nProof. intros A1 A2 (H1&_) A3 A4 (H2&_). by rewrite H1, H2. Qed.\n\nAdd Parametric Morphism : Astar\n  with signature equiv ==> equiv ==> equiv as astar_equiv_mor.\nProof.\n  intros A1 A2 (H1&H2) A3 A4 (H3&H4). split.\n  - by rewrite H1, H3.\n  - by rewrite H2, H4.\nQed.\n\nAdd Parametric Morphism : Awand\n  with signature entails_rev ==> entails ==> entails as awand_entails_mor.\nProof.\n  intros A1 A1' ENT1 A2 A2' ENT2.\n  red. intros ph P s H1 WAND. simpls.\n  intros ph' P' D1 SAT1.\n  apply ENT2; auto. apply WAND; auto.\n  apply ENT1; auto. by apply permheap_disj_valid_r in D1.\nQed.\n\nAdd Parametric Morphism : Awand\n  with signature equiv ==> equiv ==> equiv as awand_equiv_mor.\nProof.\n  intros A1 A2 (H1&H2) A3 A4 (H3&H4). split.\n  - rewrite entails_flip in H2. by rewrite H2, H3.\n  - rewrite entails_flip in H1. by rewrite H1, H4.\nQed.\n\n(** *** Weakening rule *)\n\n(** The weakening rule shows that our separation logic is _intuitionistic_. *)\n\nLemma sat_star_combine :\n  forall ph1 ph2 P1 P2 s A1 A2,\n  permheap_disj ph1 ph2 ->\n  sat ph1 P1 s A1 ->\n  sat ph2 P2 s A2 ->\n  sat (permheap_add ph1 ph2) (Ppar P1 P2) s (Astar A1 A2).\nProof.\n  intros ph1 ph2 P1 P2 s A1 A2 D1 H1 H2.\n  exists ph1, ph2. repeat split; auto.\n  exists P1, P2. intuition.\nQed.\n\nLemma sat_star_weaken :\n  forall ph P s A1 A2,\n  sat ph P s (Astar A1 A2) -> sat ph P s A1.\nProof.\n  intros ph P s A1 A2 SAT.\n  destruct SAT as (ph1 & ph2 & D1 & H1 & P1 & P2 & H2 & SAT1 & SAT2).\n  rewrite <- H1, <- H2. by apply sat_weaken.\nQed.\n\nTheorem assn_weaken :\n  forall A1 A2, entails (Astar A1 A2) A1.\nProof.\n  intros A1 A2 ph P s H1 H2.\n  by apply sat_star_weaken with A2.\nQed.\n\n(** *** Separating conjunction *)\n\n(** Soundness of the axioms of _associativity_ and _commutativity_. *)\n\nLemma sat_star_assoc_l :\n  forall ph P s A1 A2 A3,\n  sat ph P s (Astar A1 (Astar A2 A3)) ->\n  sat ph P s (Astar (Astar A1 A2) A3).\nProof.\n  intros ph P s A1 A2 A3 SAT.\n  destruct SAT as (ph1 & ph1' & D1 & H1 & P1 & P1' & H2 & SAT1 & SAT2).\n  destruct SAT2 as (ph2 & ph3 & D3 & H3 & P2 & P3 & H4 & SAT2 & SAT3).\n  exists (permheap_add ph1 ph2), ph3. repeat split; vauto.\n  { by apply permheap_disj_assoc_r. }\n  { by rewrite permheap_add_assoc. }\n  exists (Ppar P1 P2), P3. intuition.\n  { rewrite <- par_assoc. by rewrite H4. }\n  exists ph1, ph2. repeat split; vauto.\n  apply permheap_disj_add_r with ph3; auto.\nQed.\n\nTheorem star_assoc_l :\n  forall A1 A2 A3,\n  entails (Astar A1 (Astar A2 A3)) (Astar (Astar A1 A2) A3).\nProof.\n  intros A1 A2 A3 ph P s H1 H2.\n  by apply sat_star_assoc_l.\nQed.\n\nLemma sat_star_assoc_r :\n  forall ph P s A1 A2 A3,\n  sat ph P s (Astar (Astar A1 A2) A3) ->\n  sat ph P s (Astar A1 (Astar A2 A3)).\nProof.\n  intros ph P s A1 A2 A3 SAT.\n  destruct SAT as (ph1' & ph3 & D1 & H1 & P1' & P3 & H2 & SAT1 & SAT2).\n  destruct SAT1 as (ph1 & ph2 & D3 & H3 & P1 & P2 & H4 & SAT1 & SAT3).\n  exists ph1, (permheap_add ph2 ph3). repeat split; vauto.\n  { by apply permheap_disj_assoc_l. }\n  { by rewrite permheap_add_assoc. }\n  exists P1, (Ppar P2 P3). intuition.\n  { rewrite par_assoc; auto. by rewrite H4. }\n  exists ph2, ph3. repeat split; vauto.\n  apply permheap_disj_add_l with ph1; auto.\nQed.\n\nTheorem star_assoc_r :\n  forall A1 A2 A3,\n  entails (Astar (Astar A1 A2) A3) (Astar A1 (Astar A2 A3)).\nProof.\n  intros A1 A2 A3 ph P s H1 H2.\n  by apply sat_star_assoc_r.\nQed.\n\nTheorem star_assoc :\n  forall A1 A2 A3,\n  equiv (Astar (Astar A1 A2) A3) (Astar A1 (Astar A2 A3)).\nProof.\n  ins. split; [apply star_assoc_r|apply star_assoc_l].\nQed.\n\nLemma sat_star_comm :\n  forall ph P s A1 A2,\n  sat ph P s (Astar A1 A2) -> sat ph P s (Astar A2 A1).\nProof.\n  intros ph P s A1 A2 SAT.\n  destruct SAT as (ph1 & ph2 & D1 & H1 & P1 & P2 & H2 & SAT1 & SAT2).\n  exists ph2, ph1. repeat split; auto.\n  - by rewrite permheap_add_comm.\n  - exists P2, P1. intuition. by rewrite par_comm.\nQed.\n\nTheorem star_comm :\n  forall A1 A2, entails (Astar A1 A2) (Astar A2 A1).\nProof.\n  intros A1 A2 ph P s H1 H2.\n  by apply sat_star_comm.\nQed.\n\nTheorem star_comm_equiv :\n  forall A1 A2, equiv (Astar A1 A2) (Astar A2 A1).\nProof.\n  ins. split; by apply star_comm.\nQed.\n\nCorollary star_weaken_r :\n  forall A1 A2, entails (Astar A1 A2) A2.\nProof.\n  intros A1 A2. transitivity (Astar A2 A1).\n  apply star_comm. apply assn_weaken.\nQed.\n\nCorollary star_weaken_l :\n  forall A1 A2, entails (Astar A1 A2) A1.\nProof.\n  intros A1 A2. rewrite star_comm.\n  by apply star_weaken_r.\nQed.\n\nLemma sat_star_true :\n  forall ph P s A,\n  permheap_valid ph -> sat ph P s A -> sat ph P s (Astar A Atrue).\nProof.\n  intros ph P s A H1 SAT.\n  exists ph, permheap_iden. repeat split; auto.\n  { by rewrite permheap_add_iden_l. }\n  exists P, Pepsilon. intuition vauto.\n  by rewrite par_epsilon_r.\nQed.\n\nTheorem star_true :\n  forall A, entails A (Astar A Atrue).\nProof.\n  intros A ph P s H1 SAT.\n  by apply sat_star_true.\nQed.\n\nLemma sat_star_swap_l :\n  forall ph P s A1 A2 A3,\n  sat ph P s (Astar A1 (Astar A2 A3)) ->\n  sat ph P s (Astar A2 (Astar A1 A3)).\nProof.\n  intros ph P s A1 A2 A3 SAT.\n  apply sat_star_assoc_r.\n  apply sat_star_assoc_l in SAT.\n  destruct SAT as (ph1 & ph2 & D1 & H1 & P1 & P2 & H2 & SAT1 & SAT2).\n  exists ph1, ph2. repeat split; vauto.\n  exists P1, P2. intuition. by apply sat_star_comm.\nQed.\n\nLemma star_swap_l :\n  forall A1 A2 A3,\n  entails (Astar A1 (Astar A2 A3)) (Astar A2 (Astar A1 A3)).\nProof.\n  intros A1 A2 A3. rewrite star_assoc_l.\n  rewrite star_comm with (A1 := A1)(A2 := A2).\n  by rewrite star_assoc_r.\nQed.\n\nLemma sat_star_swap_r :\n  forall ph P s A1 A2 A3,\n  sat ph P s (Astar (Astar A1 A2) A3) ->\n  sat ph P s (Astar (Astar A1 A3) A2).\nProof.\n  intros ph P s A1 A2 A3 SAT.\n  apply sat_star_assoc_l.\n  apply sat_star_assoc_r in SAT.\n  destruct SAT as (ph1 & ph2 & D1 & H1 & P1 & P2 & H2 & SAT1 & SAT2).\n  exists ph1, ph2. repeat split; vauto.\n  exists P1, P2. intuition. by apply sat_star_comm.\nQed.\n\nLemma star_swap_r :\n  forall A1 A2 A3,\n  entails (Astar (Astar A1 A2) A3) (Astar (Astar A1 A3) A2).\nProof.\n  intros A1 A2 A3. rewrite star_assoc_r.\n  rewrite star_comm with (A1 := A2)(A2 := A3).\n  by rewrite star_assoc_l.\nQed.\n\nTheorem star_add_l :\n  forall A1 A2 A3, entails A2 A3 -> entails (Astar A1 A2) (Astar A1 A3).\nProof.\n  intros ??? ENT. by rewrite ENT.\nQed.\n\nTheorem star_add_r :\n  forall A1 A2 A3, entails A2 A3 -> entails (Astar A2 A1) (Astar A3 A1).\nProof.\n  intros ??? ENT. by rewrite ENT.\nQed.\n\nLemma star_disj_l :\n  forall A1 A2 A3,\n  entails (Astar A1 (Adisj A2 A3)) (Adisj (Astar A1 A2) (Astar A1 A3)).\nProof.\n  intros A1 A2 A3 ph P s H1 SAT.\n  destruct SAT as (ph1 & ph2 & H2 & H3 & P1 & P2 & H4 & SAT1 & SAT2).\n  destruct SAT2 as [SAT2 | SAT2].\n  - left. exists ph1, ph2. intuition. exists P1, P2. intuition.\n  - right. exists ph1, ph2. intuition. exists P1, P2. intuition.\nQed.\n\nLemma star_disj_r :\n  forall A1 A2 A3,\n  entails (Adisj (Astar A1 A2) (Astar A1 A3)) (Astar A1 (Adisj A2 A3)).\nProof.\n  intros A1 A2 A3 ph P s H1 [SAT | SAT];\n  destruct SAT as (ph1 & ph2 & H2 & H3 & P1 & P2 & H4 & SAT1 & SAT2).\n  - exists ph1, ph2. intuition. exists P1, P2. intuition. by left.\n  - exists ph1, ph2. intuition. exists P1, P2. intuition. by right.\nQed.\n\nLemma star_disj :\n  forall A1 A2 A3,\n  equiv (Astar A1 (Adisj A2 A3)) (Adisj (Astar A1 A2) (Astar A1 A3)).\nProof.\n  ins. split; [by apply star_disj_l|by apply star_disj_r].\nQed.\n\n(** *** Iterated separating conjunction *)\n\nTheorem aiter_permut :\n  forall xs ys, Permutation xs ys -> entails (Aiter xs) (Aiter ys).\nProof.\n  intros xs ys H. red. intros ph p s H1 SAT.\n  by apply sat_iter_permut with xs.\nQed.\n\nAdd Parametric Morphism : Aiter\n  with signature @Permutation Assn ==> entails as iter_permut_mor.\nProof.\n  ins. by apply aiter_permut.\nQed.\n\nLemma sat_aiter_cons_l :\n  forall ph p s A xs,\n  sat ph p s (Astar A (Aiter xs)) -> sat ph p s (Aiter (A :: xs)).\nProof.\n  intuition vauto.\nQed.\n\nTheorem aiter_cons_l :\n  forall A xs, entails (Astar A (Aiter xs)) (Aiter (A :: xs)).\nProof.\n  intuition vauto.\nQed.\n\nLemma sat_aiter_cons_r :\n  forall ph p s A xs,\n  sat ph p s (Aiter (A :: xs)) -> sat ph p s (Astar A (Aiter xs)).\nProof.\n  intuition vauto.\nQed.\n\nTheorem aiter_cons_r :\n  forall A xs, entails (Aiter (A :: xs)) (Astar A (Aiter xs)).\nProof.\n  intuition vauto.\nQed.\n\nLemma sat_aiter_add_l :\n  forall (xs ys : list Assn) ph P s,\n  sat ph P s (Astar (Aiter xs) (Aiter ys)) -> sat ph P s (Aiter (xs ++ ys)).\nProof.\n  induction xs as [|A xs IH]; intros ys ph P s SAT.\n  - simpl (Aiter []) in SAT. rewrite app_nil_l.\n    by apply sat_star_comm, sat_star_weaken in SAT.\n  - simpl (Aiter (A :: xs)) in SAT.\n    replace ((A :: xs) ++ ys) with (A :: (xs ++ ys)); auto.\n    apply sat_aiter_cons_l. apply sat_star_assoc_r in SAT.\n    destruct SAT as (ph1 & ph2 & H1 & H2 & P1 & P2 & H3 & SAT1 & SAT2).\n    exists ph1, ph2. repeat split; vauto.\n    exists P1, P2. intuition.\nQed.\n\nTheorem aiter_add_l :\n  forall xs ys, entails (Astar (Aiter xs) (Aiter ys)) (Aiter (xs ++ ys)).\nProof.\n  intros xs ys ph P s H SAT.\n  by apply sat_aiter_add_l.\nQed.\n\nLemma sat_aiter_add_r :\n  forall (xs ys : list Assn) ph P s,\n  permheap_valid ph ->\n  sat ph P s (Aiter (xs ++ ys)) ->\n  sat ph P s (Astar (Aiter xs) (Aiter ys)).\nProof.\n  induction xs as [|A xs IH]; intros ys ph P s H1 SAT.\n  - simpl (Aiter []). rewrite app_nil_l in SAT.\n    apply sat_star_comm. by apply sat_star_true.\n  - simpl (Aiter (A :: xs)).\n    replace ((A :: xs) ++ ys) with (A :: (xs ++ ys)) in SAT; auto.\n    apply sat_aiter_cons_r in SAT. apply sat_star_assoc_l.\n    destruct SAT as (ph1 & ph2 & H2 & H3 & P1 & P2 & H4 & SAT1 & SAT2).\n    exists ph1, ph2. repeat split; vauto.\n    exists P1, P2. intuition. apply IH; vauto.\n    by apply permheap_disj_valid_r in H2.\nQed.\n\nTheorem aiter_add_r :\n  forall xs ys, entails (Aiter (xs ++ ys)) (Astar (Aiter xs) (Aiter ys)).\nProof.\n  induction xs; intro ys; simpls.\n  - rewrite <- star_comm. by rewrite <- star_true.\n  - rewrite <- star_assoc_l. by rewrite <- IHxs.\nQed.\n\nLemma sat_aiter_star_l :\n  forall ph p s A1 A2 (xs : list Assn),\n  sat ph p s (Aiter (Astar A1 A2 :: xs)) ->\n  sat ph p s (Aiter (A1 :: A2 :: xs)).\nProof.\n  intros ph p s A1 A2 xs SAT.\n  simpl (Aiter (A1 :: A2 :: xs)).\n  by apply sat_star_assoc_r.\nQed.\n\nTheorem aiter_star_l :\n  forall A1 A2 xs,\n  entails (Aiter (Astar A1 A2 :: xs)) (Aiter (A1 :: A2 :: xs)).\nProof.\n  intros A1 A2 xs. simpls.\n  by rewrite star_assoc_r.\nQed.\n\nLemma sat_aiter_star_r :\n  forall ph P s A1 A2 (xs : list Assn),\n  sat ph P s (Aiter (A1 :: A2 :: xs)) ->\n  sat ph P s (Aiter (Astar A1 A2 :: xs)).\nProof.\n  intros ph P s A1 A2 xs SAT.\n  simpl (Aiter (A1 :: A2 :: xs)) in SAT.\n  by apply sat_star_assoc_l.\nQed.\n\nTheorem aiter_star_r :\n  forall A1 A2 xs,\n  entails (Aiter (A1 :: A2 :: xs)) (Aiter (Astar A1 A2 :: xs)).\nProof.\n  intros A1 A2 xs. simpls.\n  by rewrite star_assoc_l.\nQed.\n\nLemma sat_aiter_weaken :\n  forall ph P s A (xs : list Assn),\n  sat ph P s (Aiter (A :: xs)) -> sat ph P s (Aiter xs).\nProof.\n  intros ph P s A xs SAT.\n  simpl (Aiter (A :: xs)) in SAT.\n  apply sat_star_weaken with A.\n  by apply sat_star_comm.\nQed.\n\nCorollary aiter_weaken :\n  forall A xs, entails (Aiter (A :: xs)) (Aiter xs).\nProof.\n  intros A xs.\n  rewrite aiter_cons_r.\n  rewrite star_comm.\n  by rewrite assn_weaken.\nQed.\n\n(** *** Plain assertions *)\n\nTheorem atrue_intro :\n  forall A, entails A Atrue.\nProof.\n  red. simpls.\nQed.\n\nTheorem afalse_elim :\n  forall A1 A2, entails A1 Afalse -> entails A1 A2.\nProof.\n  unfold entails.\n  intros A1 A2 H1 ph P s H2 H4.\n  apply H1 in H4; vauto.\nQed.\n\nLemma aplain_tauto :\n  forall E,\n  entails (Aplain (Beq E E)) Atrue /\\\n  entails Atrue (Aplain (Beq E E)).\nProof.\n  intros E. split.\n  - red. ins.\n  - red. ins. desf.\nQed.\n\n(** Plain assertions can freely be duplicated. *)\n\nLemma aplain_dupl :\n  forall B, entails (Aplain B) (Astar (Aplain B) (Aplain B)).\nProof.\n  intros B. red. intros ph P s H3 H4. simpls.\n  exists permheap_iden, ph. intuition.\n  { apply permheap_add_iden_r. }\n  exists Pepsilon, P. intuition.\n  apply par_epsilon_l.\nQed.\n\n(** *** Existential quantifiers *)\n\nTheorem aexists_intro :\n  forall A1 A2 x v,\n  entails A1 (assn_subst x (Econst v) A2) ->\n  entails A1 (Aexists x A2).\nProof.\n  intros A1 A2 x v H ph P s H1 H2.\n  exists v. by apply H.\nQed.\n\n(** *** Disjunction *)\n\nLemma sat_adisj_elim_l :\n  forall ph P s A1 A2, sat ph P s A1 -> sat ph P s (Adisj A1 A2).\nProof.\n  intros ph p s A1 A2 SAT. simpl. by left.\nQed.\n\nLemma sat_adisj_elim_r :\n  forall ph P s A1 A2, sat ph P s A2 -> sat ph P s (Adisj A1 A2).\nProof.\n  intros ph P s A1 A2 SAT. simpl. by right.\nQed.\n\nTheorem adisj_elim_l :\n  forall A A1 A2, entails A A1 -> entails A (Adisj A1 A2).\nProof.\n  intros A A1 A2 H ph P s H1 SAT.\n  by apply sat_adisj_elim_l, H.\nQed.\n\nTheorem adisj_elim_r :\n  forall A A1 A2, entails A A2 -> entails A (Adisj A1 A2).\nProof.\n  intros A A1 A2 H ph P s H1 SAT.\n  by apply sat_adisj_elim_r, H.\nQed.\n\nLemma adisj_idemp :\n  forall A, entails A (Adisj A A) /\\ entails (Adisj A A) A.\nProof.\n  intro A. split; ins; vauto. red. ins. desf.\nQed.\n\n(** *** Magic wand *)\n\nTheorem awand_intro :\n  forall A1 A2 A3, entails (Astar A1 A2) A3 -> entails A1 (Awand A2 A3).\nProof.\n  intros A1 A2 A3 H1 ph P s H2 H3 ph' P' H4 H5.\n  apply H1; auto.\n  exists ph, ph'. intuition.\n  exists P, P'. intuition.\nQed.\n\nTheorem awand_elim :\n  forall A1 A2 A A',\n  entails A1 (Awand A A') -> entails A2 A -> entails (Astar A1 A2) A'.\nProof.\n  intros A1 A2 A A' H1 H2 ph P s H3 H4.\n  simpls. desf. rewrite <- H5.\n  apply H1; auto.\n  { by apply permheap_disj_valid_l in H4. }\n  apply H2; auto.\n  by apply permheap_disj_valid_r in H4.\nQed.\n\n(** *** Heap ownership *)\n\n(** *** Process ownership *)\n\nTheorem aproc_bisim :\n  forall AP1 AP2, abisim AP1 AP2 -> entails (Aproc AP1) (Aproc AP2).\nProof.\n  intros AP1 AP2 H ph P s H2 H3.\n  unfold sat in *. destruct H3 as (P' & H3).\n  exists P'. rewrite H3. by rewrite H.\nQed.\n\nTheorem aproc_split :\n  forall AP1 AP2,\n  entails (Aproc (APpar AP1 AP2)) (Astar (Aproc AP1) (Aproc AP2)).\nProof.\n  intros AP1 AP2 ph P s H1 (P' & H2). rewrite H2.\n  exists permheap_iden, ph. intuition.\n  { by apply permheap_add_iden_r. }\n  exists (aproc_conv AP1 s), (Ppar (aproc_conv AP2 s) P').\n  intuition vauto.\n  - rewrite par_assoc. simpl. done.\n  - exists Pepsilon. by rewrite par_epsilon_r.\nQed.\n\nTheorem aproc_merge :\n  forall AP1 AP2,\n  entails (Astar (Aproc AP1) (Aproc AP2)) (Aproc (APpar AP1 AP2)).\nProof.\n  intros AP1 AP2 ph P s H1 H2. unfold sat in H2.\n  destruct H2 as (ph1 & ph2 & D1 & H2 & P1 & P2 & H3 & SAT1 & SAT2).\n  destruct SAT1 as (P1' & H4). destruct SAT2 as (P2' & H5).\n  exists (Ppar P1' P2'). intuition clarify.\n  simpl (aproc_conv (APpar AP1 AP2) s). rewrite <- H3, H4, H5.\n  repeat rewrite <- par_assoc.\n  apply bisim_par; auto.\n  repeat rewrite par_assoc.\n  apply bisim_par; auto.\n  by rewrite par_comm with (P := P1').\nQed.\n\nTheorem aproc_weaken :\n  forall AP1 AP2, entails (Aproc (APpar AP1 AP2)) (Aproc AP1).\nProof.\n  intros AP1 AP2.\n  transitivity (Astar (Aproc AP1) (Aproc AP2)).\n  - by apply aproc_split.\n  - apply assn_weaken.\nQed.\n\n(** *** Process bisimulation *)\n\nTheorem abisim_proc :\n  forall AP AQ, entails (Astar (Aproc AP) (Abisim AP AQ)) (Aproc AQ).\nProof.\n  intros AP AQ. red. intros ph P s H1 H2.\n  destruct H2 as (ph1 & ph2 & D1 & H2 & P1 & P2 & H3 & SAT1 & SAT2).\n  clarify. simpls. destruct SAT1 as (P1' & H4).\n  exists (Ppar P1' P2). rewrite <- SAT2, <- H3.\n  rewrite par_assoc. by rewrite <- H4.\nQed.\n\nTheorem abisim_closed :\n  forall AP AQ, abisim AP AQ -> entails (Atrue) (Abisim AP AQ).\nProof.\n  intros AP AQ H1. red. intros ph P s H2 H3. simpls.\nQed.\n\nTheorem abisim_cond_true :\n  forall B AP, entails (Aplain B) (Abisim (APcond B AP) AP).\nProof.\n  intros B AP. red. intros ph P s H1 H2. simpls.\n  transitivity (Pcond (PBconst true) (aproc_conv AP s)).\n  - apply bisim_cond_eval; vauto. simpls.\n    by rewrite <- cond_conv_eval.\n  - by apply pcond_true.\nQed.\n\nTheorem abisim_cond_false :\n  forall B AP, entails (Aplain (Bnot B)) (Abisim (APcond B AP) APdelta).\nProof.\n  intros B AP. red. intros ph P s H1 H2. simpls.\n  unfold negb in H2. desf. clear H2.\n  transitivity (Pcond (PBconst false) (aproc_conv AP s)).\n  - apply bisim_cond_eval; vauto. simpls.\n    by rewrite <- cond_conv_eval.\n  - by apply pcond_false.\nQed.\n\nTheorem abisim_sigma_cond :\n  forall x B AP,\n  ~ In x (cond_fv B) ->\n  entails (Atrue) (Abisim (APsigma x (APcond B AP)) (APcond B (APsigma x AP))).\nProof.\n  intros x B AP H1. red. intros ph P s H2 _. simpls.\n  set (f := fun v => aproc_conv (aproc_subst x (Econst v) AP) s).\n  set (g := fun v => Pcond (cond_conv B s) (f v)).\n  transitivity (Psum g).\n  - subst g f. apply bisim_sum. red. intro v.\n    rewrite cond_subst_pres; vauto.\n  - subst g f. apply bisim_sum_cond.\nQed.\n\n(** Likewise to [bisim], also [Abisim] resembles an equivalence relation and\n    is a congruence for all connectives defined for [AbstrProc]. *)\n\nTheorem abisim_refl :\n  forall AP, entails Atrue (Abisim AP AP).\nProof.\n  intros AP. red. intros ph P s H1 H2. simpls.\nQed.\n\nTheorem abisim_symm :\n  forall AP AQ, entails (Abisim AP AQ) (Abisim AQ AP).\nProof.\n  intros AP AQ. red. intros ph P s H1 H2. simpls. auto.\nQed.\n\nTheorem abisim_trans :\n  forall AP AQ AR, entails (Astar (Abisim AP AQ) (Abisim AQ AR)) (Abisim AP AR).\nProof.\n  intros AP AQ AR. red. intros ph P s H1 H2. simpls.\n  destruct H2 as (ph1 & ph2 & H3 & H2 & P1 & P2 & H4 & SAT1 & SAT2).\n  transitivity (aproc_conv AQ s); auto.\nQed.\n\nTheorem abisim_seq :\n  forall AP AP' AQ AQ',\n  entails (Astar (Abisim AP AP') (Abisim AQ AQ')) (Abisim (APseq AP AQ) (APseq AP' AQ')).\nProof.\n  intros AP AP' AQ AQ'. red. intros ph P s H1 H2. simpls.\n  destruct H2 as (ph1 & ph2 & H3 & H2 & P1 & P2 & H4 & SAT1 & SAT2).\n  apply bisim_seq; auto.\nQed.\n\nTheorem abisim_alt :\n  forall AP AP' AQ AQ',\n  entails (Astar (Abisim AP AP') (Abisim AQ AQ')) (Abisim (APalt AP AQ) (APalt AP' AQ')).\nProof.\n  intros AP AP' AQ AQ'. red. intros ph P s H1 H2. simpls.\n  destruct H2 as (ph1 & ph2 & H3 & H2 & P1 & P2 & H4 & SAT1 & SAT2).\n  apply bisim_alt; auto.\nQed.\n\nTheorem abisim_par :\n  forall AP AP' AQ AQ',\n  entails (Astar (Abisim AP AP') (Abisim AQ AQ')) (Abisim (APpar AP AQ) (APpar AP' AQ')).\nProof.\n  intros AP AP' AQ AQ'. red. intros ph P s H1 H2. simpls.\n  destruct H2 as (ph1 & ph2 & H3 & H2 & P1 & P2 & H4 & SAT1 & SAT2).\n  apply bisim_par; auto.\nQed.\n\nTheorem abisim_sum :\n  forall AP AQ x,\n  ~ aproc_fv AP x ->\n  ~ aproc_fv AQ x ->\n  entails (Abisim AP AQ) (Abisim (APsigma x AP) (APsigma x AQ)).\nProof.\n  intros AP AQ x H1 H2. red. intros ph P s H3 H4. simpls.\n  apply bisim_sum. red. intro v.\n  repeat rewrite aproc_subst_pres; auto.\nQed.\n\nTheorem abisim_cond :\n  forall AP AQ b,\n  entails (Abisim AP AQ) (Abisim (APcond b AP) (APcond b AQ)).\nProof.\n  intros AP AQ b. red. intros ph P s H3 H4. simpls.\n  apply bisim_cond; auto.\nQed.\n\nTheorem abisim_iter :\n  forall AP AQ,\n  entails (Abisim AP AQ) (Abisim (APiter AP) (APiter AQ)).\nProof.\n  intros AP AQ. red. intros ph P s H3 H4. simpls.\n  apply bisim_iter; auto.\nQed.\n\nEnd Assertions.\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/Assertions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.27778515289042915}}
{"text": "From VST Require Import floyd.proofauto.\n\nFrom appliedfm Require Import Int63.model.int63.\nFrom appliedfm Require Import Int63.vst.clightgen.int63.\n\n\nDefinition encode_int63_spec: ident * funspec :=\n  DECLARE _encode_int63\n  WITH x: Z, gv: globals\n  PRE [ tlong ]\n      PROP ( )\n      PARAMS (Vlong (Int64.repr x))\n      GLOBALS(gv)\n      SEP ( )\n  POST [ tlong ]\n      PROP ( )\n      RETURN (Vlong (Int64.repr (encode_Z x)))\n      SEP ( ).\n\nDefinition decode_int63_spec: ident * funspec :=\n  DECLARE _decode_int63\n  WITH x: Z, gv: globals\n  PRE [ tlong ]\n      PROP (Int64.min_signed <= encode_Z x <= Int64.max_signed)\n      PARAMS (Vlong (Int64.repr (encode_Z x)))\n      GLOBALS(gv)\n      SEP ( )\n  POST [ tlong ]\n      PROP ( )\n      RETURN (Vlong (Int64.repr x))\n      SEP ( ).\n\n\nDefinition int63_zero_spec: ident * funspec :=\n  DECLARE _int63_zero\n  WITH gv: globals\n  PRE [ ]\n      PROP ()\n      PARAMS ()\n      GLOBALS(gv)\n      SEP ( )\n  POST [ tlong ]\n      PROP ( )\n      RETURN (Vlong (Int64.repr (encode_Z 0)))\n      SEP ( ).\n\nDefinition int63_one_spec: ident * funspec :=\n  DECLARE _int63_one\n  WITH gv: globals\n  PRE [ ]\n      PROP ()\n      PARAMS ()\n      GLOBALS(gv)\n      SEP ( )\n  POST [ tlong ]\n      PROP ( )\n      RETURN (Vlong (Int64.repr (encode_Z 1)))\n      SEP ( ).\n\nDefinition int63_neg_spec: ident * funspec :=\n  DECLARE _int63_neg\n  WITH x: Z, gv: globals\n  PRE [ tlong ]\n      PROP (\n          Int64.min_signed <= encode_Z x <= Int64.max_signed;\n          Int64.min_signed <= encode_Z (- x) <= Int64.max_signed\n      )\n      PARAMS (Vlong (Int64.repr (encode_Z x)))\n      GLOBALS(gv)\n      SEP ( )\n  POST [ tlong ]\n      PROP ( )\n      RETURN (Vlong (Int64.repr (encode_Z (- x))))\n      SEP ( ).\n\nDefinition int63_abs_spec: ident * funspec :=\n  DECLARE _int63_abs\n  WITH x: Z, gv: globals\n  PRE [ tlong ]\n      PROP (\n          Int64.min_signed <= encode_Z x <= Int64.max_signed;\n          Int64.min_signed <= encode_Z (- x) <= Int64.max_signed\n      )\n      PARAMS (Vlong (Int64.repr (encode_Z x)))\n      GLOBALS(gv)\n      SEP ( )\n  POST [ tlong ]\n      PROP ( )\n      RETURN (Vlong (Int64.repr (encode_Z (Z.abs x))))\n      SEP ( ).\n\nDefinition int63_add_spec: ident * funspec :=\n  DECLARE _int63_add\n  WITH x: Z, y: Z, gv: globals\n  PRE [ tlong, tlong ]\n      PROP (\n          Int64.min_signed <= encode_Z x <= Int64.max_signed;\n          Int64.min_signed <= encode_Z y <= Int64.max_signed;\n          Int64.min_signed <= encode_Z (x + y) < Int64.max_signed\n      )\n      PARAMS (\n          Vlong (Int64.repr (encode_Z x));\n          Vlong (Int64.repr (encode_Z y))\n      )\n      GLOBALS(gv)\n      SEP ( )\n  POST [ tlong ]\n      PROP ( )\n      RETURN (Vlong (Int64.repr (encode_Z (x + y))))\n      SEP ( ).\n\nDefinition int63_sub_spec: ident * funspec :=\n  DECLARE _int63_sub\n  WITH x: Z, y: Z, gv: globals\n  PRE [ tlong, tlong ]\n      PROP (\n          Int64.min_signed <= encode_Z x <= Int64.max_signed;\n          Int64.min_signed <= encode_Z y <= Int64.max_signed;\n          Int64.min_signed <= encode_Z (x - y) <= Int64.max_signed\n      )\n      PARAMS (\n          Vlong (Int64.repr (encode_Z x));\n          Vlong (Int64.repr (encode_Z y))\n      )\n      GLOBALS(gv)\n      SEP ( )\n  POST [ tlong ]\n      PROP ( )\n      RETURN (Vlong (Int64.repr (encode_Z (x - y))))\n      SEP ( ).\n\nDefinition int63_mul_spec: ident * funspec :=\n  DECLARE _int63_mul\n  WITH x: Z, y: Z, gv: globals\n  PRE [ tlong, tlong ]\n      PROP (\n          Int64.min_signed <= encode_Z x <= Int64.max_signed;\n          Int64.min_signed <= encode_Z y <= Int64.max_signed;\n          Int64.min_signed <= encode_Z (x * y) <= Int64.max_signed\n      )\n      PARAMS (\n          Vlong (Int64.repr (encode_Z x));\n          Vlong (Int64.repr (encode_Z y))\n      )\n      GLOBALS(gv)\n      SEP ( )\n  POST [ tlong ]\n      PROP ( )\n      RETURN (Vlong (Int64.repr (encode_Z (x * y))))\n      SEP ( ).\n\nDefinition int63_div_spec: ident * funspec :=\n  DECLARE _int63_div\n  WITH x: Z, y: Z, gv: globals\n  PRE [ tlong, tlong ]\n      PROP (\n          Int64.min_signed <= encode_Z x <= Int64.max_signed;\n          Int64.min_signed <= encode_Z y <= Int64.max_signed;\n          y <> 0\n      )\n      PARAMS (\n          Vlong (Int64.repr (encode_Z x));\n          Vlong (Int64.repr (encode_Z y))\n      )\n      GLOBALS(gv)\n      SEP ( )\n  POST [ tlong ]\n      PROP ( )\n      RETURN (Vlong (Int64.repr (encode_Z (Z.quot x y))))\n      SEP ( ).\n\nDefinition int63_rem_spec: ident * funspec :=\n  DECLARE _int63_rem\n  WITH x: Z, y: Z, gv: globals\n  PRE [ tlong, tlong ]\n      PROP (\n          Int64.min_signed <= encode_Z x <= Int64.max_signed;\n          Int64.min_signed <= encode_Z y <= Int64.max_signed;\n          y <> 0\n      )\n      PARAMS (\n          Vlong (Int64.repr (encode_Z x));\n          Vlong (Int64.repr (encode_Z y))\n      )\n      GLOBALS(gv)\n      SEP ( )\n  POST [ tlong ]\n      PROP ( )\n      RETURN (Vlong (Int64.repr (encode_Z (Z.rem x y))))\n      SEP ( ).\n\nDefinition int63_shiftl_spec: ident * funspec :=\n  DECLARE _int63_shiftl\n  WITH x: Z, y: Z, gv: globals\n  PRE [ tlong, tlong ]\n      PROP (\n          Int64.min_signed <= encode_Z x <= Int64.max_signed;\n          Int64.min_signed <= encode_Z y <= Int64.max_signed;\n          0 <= x;\n          0 <= y < Int64.zwordsize\n      )\n      PARAMS (\n          Vlong (Int64.repr (encode_Z x));\n          Vlong (Int64.repr (encode_Z y))\n      )\n      GLOBALS(gv)\n      SEP ( )\n  POST [ tlong ]\n      PROP ( )\n      RETURN (Vlong (Int64.repr (encode_Z (Z.shiftl x y))))\n      SEP ( ).\n\nDefinition int63_shiftr_spec: ident * funspec :=\n  DECLARE _int63_shiftr\n  WITH x: Z, y: Z, gv: globals\n  PRE [ tlong, tlong ]\n      PROP (\n          Int64.min_signed <= encode_Z x <= Int64.max_signed;\n          Int64.min_signed <= encode_Z y <= Int64.max_signed;\n          0 <= y < Int64.zwordsize\n      )\n      PARAMS (\n          Vlong (Int64.repr (encode_Z x));\n          Vlong (Int64.repr (encode_Z y))\n      )\n      GLOBALS(gv)\n      SEP ( )\n  POST [ tlong ]\n      PROP ( )\n      RETURN (Vlong (Int64.repr (encode_Z (Z.shiftr x y))))\n      SEP ( ).\n\nDefinition int63_or_spec: ident * funspec :=\n  DECLARE _int63_or\n  WITH x: Z, y: Z, gv: globals\n  PRE [ tlong, tlong ]\n      PROP (\n          Int64.min_signed <= encode_Z x <= Int64.max_signed;\n          Int64.min_signed <= encode_Z y <= Int64.max_signed\n      )\n      PARAMS (\n          Vlong (Int64.repr (encode_Z x));\n          Vlong (Int64.repr (encode_Z y))\n      )\n      GLOBALS(gv)\n      SEP ( )\n  POST [ tlong ]\n      PROP ( )\n      RETURN (Vlong (Int64.repr (encode_Z (Z.lor x y))))\n      SEP ( ).\n\nDefinition int63_and_spec: ident * funspec :=\n  DECLARE _int63_and\n  WITH x: Z, y: Z, gv: globals\n  PRE [ tlong, tlong ]\n      PROP (\n          Int64.min_signed <= encode_Z x <= Int64.max_signed;\n          Int64.min_signed <= encode_Z y <= Int64.max_signed\n      )\n      PARAMS (\n          Vlong (Int64.repr (encode_Z x));\n          Vlong (Int64.repr (encode_Z y))\n      )\n      GLOBALS(gv)\n      SEP ( )\n  POST [ tlong ]\n      PROP ( )\n      RETURN (Vlong (Int64.repr (encode_Z (Z.land x y))))\n      SEP ( ).\n\nDefinition int63_xor_spec: ident * funspec :=\n  DECLARE _int63_xor\n  WITH x: Z, y: Z, gv: globals\n  PRE [ tlong, tlong ]\n      PROP (\n          Int64.min_signed <= encode_Z x <= Int64.max_signed;\n          Int64.min_signed <= encode_Z y <= Int64.max_signed\n      )\n      PARAMS (\n          Vlong (Int64.repr (encode_Z x));\n          Vlong (Int64.repr (encode_Z y))\n      )\n      GLOBALS(gv)\n      SEP ( )\n  POST [ tlong ]\n      PROP ( )\n      RETURN (Vlong (Int64.repr (encode_Z (Z.lxor x y))))\n      SEP ( ).\n\nDefinition int63_not_spec: ident * funspec :=\n  DECLARE _int63_not\n  WITH x: Z, gv: globals\n  PRE [ tlong ]\n      PROP (Int64.min_signed <= encode_Z x <= Int64.max_signed)\n      PARAMS (Vlong (Int64.repr (encode_Z x)))\n      GLOBALS(gv)\n      SEP ( )\n  POST [ tlong ]\n      PROP ( )\n      RETURN (Vlong (Int64.repr (encode_Z (Z.lnot x))))\n      SEP ( ).\n\nModule int63__specs.\n  Definition exports: funspecs :=\n    [ decode_int63_spec\n    ; encode_int63_spec\n    ; int63_zero_spec\n    ; int63_one_spec\n    ; int63_neg_spec\n    ; int63_abs_spec\n    ; int63_add_spec\n    ; int63_sub_spec\n    ; int63_mul_spec\n    ; int63_div_spec\n    ; int63_rem_spec\n    ; int63_shiftl_spec\n    ; int63_shiftr_spec\n    ; int63_or_spec\n    ; int63_and_spec\n    ; int63_xor_spec\n    ; int63_not_spec\n  ].\n  Definition externs: funspecs := [].\n  Definition imports: funspecs := [].\n  Definition private: funspecs := [].\n  Definition internals: funspecs := private ++ exports.\n  Definition gprog: funspecs := imports ++ internals.\n  Definition vprog: varspecs := ltac:(mk_varspecs prog).\nEnd int63__specs.\n", "meta": {"author": "appliedfm", "repo": "coq-vsu-int63", "sha": "132c571a068cdae93d7c27bcdd02eabfc1f809ed", "save_path": "github-repos/coq/appliedfm-coq-vsu-int63", "path": "github-repos/coq/appliedfm-coq-vsu-int63/coq-vsu-int63-132c571a068cdae93d7c27bcdd02eabfc1f809ed/theories/Int63/vst/spec/spec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2777851528904291}}
{"text": "(* Contribution to the Coq Library   V6.3 (July 1999)                    *)\n\n(****************************************************************************)\n(*                 The Calculus of Inductive Constructions                  *)\n(*                                                                          *)\n(*                                Projet Coq                                *)\n(*                                                                          *)\n(*                     INRIA                        ENS-CNRS                *)\n(*              Rocquencourt                        Lyon                    *)\n(*                                                                          *)\n(*                                Coq V5.10                                 *)\n(*                              Nov 25th 1994                               *)\n(*                                                                          *)\n(****************************************************************************)\n(*                              commutation.v                               *)\n(****************************************************************************)\n\n(*****************************************************************************)\n(*          Projet Coq  - Calculus of Inductive Constructions V5.8           *)\n(*****************************************************************************)\n(*                                                                           *)\n(*      Meta-theory of the explicit substitution calculus lambda-env         *)\n(*      Amokrane Saibi                                                       *)\n(*                                                                           *)\n(*      September 1993                                                       *)\n(*                                                                           *)\n(*****************************************************************************)\n\n\n                 (*  SL commute avec B|| de la maniere suivante:\n      \n                                           B||\n                                       x ---------> z\n                                       |            |\n                                    SL |            |SL*\n                                       |            | \n                                       V            V\n                                       y ----------> u\n                                         SL*B||SL*              *)\nRequire Import sur_les_relations.\nRequire Import TS.\nRequire Import egaliteTS.\nRequire Import sigma_lift.\nRequire Import betapar.\nRequire Import SLstar_bpar_SLstar.\nRequire Import determinePC_SL.\n\nDefinition e_diag1 (b : wsort) (x y : TS b) :=\n  forall z : TS b,\n  e_beta_par _ x z ->\n  exists u : TS b, e_slstar_bp_slstar _ y u /\\ e_relSLstar _ z u.\n\nNotation diag1 := (e_diag1 _) (only parsing).\n(* <Warning> : Syntax is discontinued *)\n\n\n(* les regles du systeme sigma-lift (SL) verifient le diagramme *)\n\nGoal forall x y : terms, reg_app x y -> e_diag1 _ x y.\nsimple induction 1; red in |- *; intros a b0 s z H0.\npattern z in |- *; apply case_benv with (app a b0) s.\n2: assumption.\nintros x' s' H1 H2; pattern x' in |- *; apply case_bapp with a b0.\n3: assumption.\n(* 1-regle B||: app *)\nintros a' b0' H3 H4; exists (app (env a' s') (env b0' s')); auto 6.\n (* (a[s])(b0[s]) SL*B||SL* (a'[s'])(b0'[s']) *)\n (* (a'b0')[s'] SL* (a'[s'])(b0'[s']) *)\n(* 2-regle B||: beta *)\nintros a1 a1' b0' H3 H4 H5; rewrite H3.\nexists (env a1' (cons (env b0' s') s')); split.\n (* ((L a1)[s])(b0[s]) SL*B||SL* a1'[b0'[s'].s'] *)\nred in |- *; apply comp_2rel with (app (lambda (env a1 (lift s))) (env b0 s)).\n   (* ((L a1)[s])(b0[s]) SL* (L (a1[||S]))(b0[s]) *) \nauto 6.\n   (* (L (a1[||S]))(b0[s]) B|| (a1'[||s'])[b0'[s'].id] *)\napply comp_2rel with (env (env a1' (lift s')) (cons (env b0' s') id)).\nauto.\n   (* (a1'[||s'])[b0'[s'].id] SL* a1'[b0'[s'].s'] *)\nred in |- *;\n apply star_trans1 with (env a1' (comp (lift s') (cons (env b0' s') id))).\nauto.\napply star_trans1 with (env a1' (cons (env b0' s') (comp s' id))); auto 6.\n (* (a1'[b0'id])[s'] SL* a1'[b0'[s'].s'] *)\nred in |- *; apply star_trans1 with (env a1' (comp (cons b0' id) s')).\nauto.\napply star_trans1 with (env a1' (cons (env b0' s') (comp id s'))); auto 6.\nSave commut_app.\nHint Resolve commut_app.\n\nGoal forall x y : terms, reg_lambda x y -> e_diag1 _ x y.\nsimple induction 1; red in |- *; intros a s z H0.\npattern z in |- *; apply case_benv with (lambda a) s.\n2: assumption.\nintros x' s' H1 H2; pattern x' in |- *; apply case_blambda with a.\n2: assumption.\nintros a' H3; exists (lambda (env a' (lift s'))); auto 6.\n(* L(a[||s]) SL*B||*SL L(a'[||s']) *)\n(* (L a0')[s'] SL* L(a0'[||s']) *)\nSave commut_lambda.\nHint Resolve commut_lambda.\n\nGoal forall x y : terms, reg_clos x y -> e_diag1 _ x y.\nsimple induction 1; red in |- *; intros a s t z H0.\npattern z in |- *; apply case_benv with (env a s) t.\n2: assumption.\nintros x' t' H1 H2; pattern x' in |- *; apply case_benv with a s.\n2: assumption.\nintros a' s' H3 H4; exists (env a' (comp s' t')); auto 6.\n(*  a[sot] SL*B||SL* a'[s'ot'] *)\n(* (a'[s'])[t'] SL* a'[s'ot'] *)\nSave commut_clos.\nHint Resolve commut_clos.\n\nGoal forall x y : terms, reg_varshift1 x y -> e_diag1 _ x y.\nsimple induction 1; red in |- *; intros n z H0.\npattern z in |- *; apply case_benv with (var n) shift.\n2: assumption.\nintros x' s' H1 H2; pattern x' in |- *; apply case_bvar with n.\n2: assumption.\npattern s' in |- *; apply case_bshift.\n2: assumption.\nexists (var (S n)); auto 6.\n(* n+1 SL*B||SL* n+1 *)\n(* n[|] SL* n+1 *)\nSave commut_varshift1.\nHint Resolve commut_varshift1.\n\nGoal forall x y : terms, reg_varshift2 x y -> e_diag1 _ x y.\nsimple induction 1; red in |- *; intros n s z H0.\npattern z in |- *; apply case_benv with (var n) (comp shift s).\n2: assumption.\nintros x' y' H1 H2; pattern x' in |- *; apply case_bvar with n.\n2: assumption.\npattern y' in |- *; apply case_bcomp with shift s.\n2: assumption.\nintros t' s' H3 H4; pattern t' in |- *; apply case_bshift.\n2: assumption.\nexists (env (var (S n)) s'); auto 6.\n(* n+1[s] SL*B||SL* n+1[s'] *)\n(* n[|os'] SL* n+1[s'] *)\nSave commut_varshift2.\nHint Resolve commut_varshift2.\n\nGoal forall x y : terms, reg_fvarcons x y -> e_diag1 _ x y.\nsimple induction 1; red in |- *; intros a s z H0.\npattern z in |- *; apply case_benv with (var 0) (cons a s).\n2: assumption.\nintros x' y' H1 H2; pattern x' in |- *; apply case_bvar with 0.\n2: assumption.\npattern y' in |- *; apply case_bcons with a s.\n2: assumption.\nintros a' s' H3 H4; exists a'; auto 6.\n(* a SL*B||SL* a' *)\n(* 0[a'.s'] SL* a' *)\nSave commut_fvarcons.\nHint Resolve commut_fvarcons.\n\nGoal forall x y : terms, reg_fvarlift1 x y -> e_diag1 _ x y.\nsimple induction 1; red in |- *; intros s z H0.\npattern z in |- *; apply case_benv with (var 0) (lift s).\n2: assumption.\nintros x' y' H1 H2; pattern x' in |- *; apply case_bvar with 0.\n2: assumption.\npattern y' in |- *; apply case_blift with s.\n2: assumption.\nintros s' H3; exists (var 0); auto 6.\n(* 0 SL*B||SL* 0 *)\n(* 0[||s'] SL* 0 *)\nSave commut_fvarlift1.\nHint Resolve commut_fvarlift1.\n\nGoal forall x y : terms, reg_fvarlift2 x y -> e_diag1 _ x y.\nsimple induction 1; red in |- *; intros s t z H0.\npattern z in |- *; apply case_benv with (var 0) (comp (lift s) t).\n2: assumption.\nintros x' y' H1 H2; pattern x' in |- *; apply case_bvar with 0.\n2: assumption.\npattern y' in |- *; apply case_bcomp with (lift s) t.\n2: assumption.\nintros z' t' H3 H4; pattern z' in |- *; apply case_blift with s.\n2: assumption.\nintros s' H5; exists (env (var 0) t'); auto 6.\n(* 0[t] SL*B||SL* 0[t'] *)\n(* 0[||s'ot'] SL* 0[t'] *)\nSave commut_fvarlift2.\nHint Resolve commut_fvarlift2.\n\nGoal forall x y : terms, reg_rvarcons x y -> e_diag1 _ x y.\nsimple induction 1; red in |- *; intros n a s z H0.\npattern z in |- *; apply case_benv with (var (S n)) (cons a s).\n2: assumption.\nintros x' y' H1 H2; pattern x' in |- *; apply case_bvar with (S n).\n2: assumption.\npattern y' in |- *; apply case_bcons with a s.\n2: assumption.\nintros a' s' H3 H4; exists (env (var n) s'); auto 6.\n(* n[s] SL*B||SL* n[s'] *)\n(* n+1[a'.s'] SL* n[s'] *)\nSave commut_rvarcons.\nHint Resolve commut_rvarcons.\n\nGoal forall x y : terms, reg_rvarlift1 x y -> e_diag1 _ x y.\nsimple induction 1; red in |- *; intros n s z H0.\npattern z in |- *; apply case_benv with (var (S n)) (lift s).\n2: assumption.\nintros x' y' H1 H2; pattern x' in |- *; apply case_bvar with (S n).\n2: assumption.\npattern y' in |- *; apply case_blift with s.\n2: assumption.\nintros s' H3; exists (env (var n) (comp s' shift)); auto 6.\n(* n[so|] SL*B||SL* n[s'o|] *)\n(* n+1[||s'] SL* n[s'o|] *)\nSave commut_rvarlift1.\nHint Resolve commut_rvarlift1.\n\nGoal forall x y : terms, reg_rvarlift2 x y -> e_diag1 _ x y.\nsimple induction 1; red in |- *; intros n s t z H0.\npattern z in |- *; apply case_benv with (var (S n)) (comp (lift s) t).\n2: assumption.\nintros x' y' H1 H2; pattern x' in |- *; apply case_bvar with (S n).\n2: assumption.\npattern y' in |- *; apply case_bcomp with (lift s) t.\n2: assumption.\nintros z' t' H3 H4; pattern z' in |- *; apply case_blift with s.\n2: assumption.\nintros s' H5; exists (env (var n) (comp s' (comp shift t'))); auto 6.\n(* n[so(|ot)] SL*B||SL* n[s'o(|ot')] *)\n(* n+1[||s'ot'] SL* n[s'o(|ot')] *)\nSave commut_rvarlift2.\nHint Resolve commut_rvarlift2.\n\nGoal forall x y : sub_explicits, reg_assenv x y -> e_diag1 _ x y.\nsimple induction 1; red in |- *; intros s t u z H0.\npattern z in |- *; apply case_bcomp with (comp s t) u.\n2: assumption.\nintros x' u' H1 H2; pattern x' in |- *; apply case_bcomp with s t.\n2: assumption.\nintros s' t' H3 H4; exists (comp s' (comp t' u')); auto 6.\n(* so(tou) SL*B||SL* s'o(t'ou') *)\n(*  (s'ot')ou' SL* s'o(t'ou') *)\nSave commut_assenv.\nHint Resolve commut_assenv.\n\nGoal forall x y : sub_explicits, reg_mapenv x y -> e_diag1 _ x y.\nsimple induction 1; red in |- *; intros a s t z H0.\npattern z in |- *; apply case_bcomp with (cons a s) t.\n2: assumption.\nintros x' t' H1 H2; pattern x' in |- *; apply case_bcons with a s.\n2: assumption.\nintros a' s' H3 H4; exists (cons (env a' t') (comp s' t')); auto 6.\n(* a[t].(sot) SL*B||SL a'[t'].(s'ot') *)\n(* (a'.s')ot' SL* a'[t'].(s'ot') *)\nSave commut_mapenv.\nHint Resolve commut_mapenv.\n\nGoal forall x y : sub_explicits, reg_shiftcons x y -> e_diag1 _ x y.\nsimple induction 1; red in |- *; intros a s z H0.\npattern z in |- *; apply case_bcomp with shift (cons a s).\n2: assumption.\nintros x' y' H1 H2; pattern x' in |- *; apply case_bshift.\n2: assumption.\npattern y' in |- *; apply case_bcons with a s.\n2: assumption.\nintros a' s' H3 H4; exists s'; auto 6.\n(* s SL*B||SL* s' *)\n(* shift o(a'.s') SL* s' *)\nSave commut_shiftcons.\nHint Resolve commut_shiftcons.\n\nGoal forall x y : sub_explicits, reg_shiftlift1 x y -> e_diag1 _ x y.\nsimple induction 1; red in |- *; intros s z H0.\npattern z in |- *; apply case_bcomp with shift (lift s).\n2: assumption.\nintros x' y' H1 H2; pattern x' in |- *; apply case_bshift.\n2: assumption.\npattern y' in |- *; apply case_blift with s.\n2: assumption.\nintros s' H3; exists (comp s' shift); auto 6.\n(* so| SL*B||SL* s'o| *)\n(* |o(|| s') SL* s'o| *)\nSave commut_shiftlift1.\nHint Resolve commut_shiftlift1.\n\nGoal forall x y : sub_explicits, reg_shiftlift2 x y -> e_diag1 _ x y.\nsimple induction 1; red in |- *; intros s t z H0.\npattern z in |- *; apply case_bcomp with shift (comp (lift s) t).\n2: assumption.\nintros x' y' H1 H2; pattern x' in |- *; apply case_bshift.\n2: assumption.\npattern y' in |- *; apply case_bcomp with (lift s) t.\n2: assumption.\nintros z' t' H3 H4; pattern z' in |- *; apply case_blift with s.\n2: assumption.\nintros s' H5; exists (comp s' (comp shift t')); auto 6.\n(* so(|ot) SL*B||SL* s'o(|ot') *)\n(* (|| s')ot' SL* s'o(|ot') *)\nSave commut_shiftlift2.\nHint Resolve commut_shiftlift2.\n\nGoal forall x y : sub_explicits, reg_lift1 x y -> e_diag1 _ x y.\nsimple induction 1; red in |- *; intros s t z H0.\npattern z in |- *; apply case_bcomp with (lift s) (lift t).\n2: assumption.\nintros x' y' H1 H2; pattern x' in |- *; apply case_blift with s.\n2: assumption.\nintros s' H3; pattern y' in |- *; apply case_blift with t.\n2: assumption.\nintros t' H4; exists (lift (comp s' t')); auto 6.\n(* ||(sot) SL*B||SL* ||(s'ot') *)\n(* ||s' o ||t' SL* ||(s'ot') *)\nSave commut_lift1.\nHint Resolve commut_lift1.\n\nGoal forall x y : sub_explicits, reg_lift2 x y -> e_diag1 _ x y.\nsimple induction 1; red in |- *; intros s t u z H0.\npattern z in |- *; apply case_bcomp with (lift s) (comp (lift t) u).\n2: assumption.\nintros x' y' H1 H2; pattern x' in |- *; apply case_blift with s.\n2: assumption.\nintros s' H3; pattern y' in |- *; apply case_bcomp with (lift t) u.\n2: assumption.\nintros z' u' H4 H5; pattern z' in |- *; apply case_blift with t.\n2: assumption.\nintros t' H6; exists (comp (lift (comp s' t')) u'); auto 6.\n(* ||(sot)ou SL*B||SL* ||(s'ot')ou' *) \n(* ||s'o(||t'ou') SL* ||(s'ot')ou' *) \nSave commut_lift2.\nHint Resolve commut_lift2.\n\nGoal forall x y : sub_explicits, reg_liftenv x y -> e_diag1 _ x y.\nsimple induction 1; red in |- *; intros a s t z H0.\npattern z in |- *; apply case_bcomp with (lift s) (cons a t).\n2: assumption.\nintros x' y' H1 H2; pattern x' in |- *; apply case_blift with s.\n2: assumption.\nintros s' H3; pattern y' in |- *; apply case_bcons with a t.\n2: assumption.\nintros a' t' H4 H5; exists (cons a' (comp s' t')); auto 6.\n(* a.(sot) SL*B||SL* a'.(s'ot') *)\n(* ||s'o(a'.t') SL* a'.(s'ot') *)\nSave commut_liftenv.\nHint Resolve commut_liftenv.\n\nGoal forall x y : sub_explicits, reg_idl x y -> e_diag1 _ x y.\nsimple induction 1; red in |- *; intros s z H0.\npattern z in |- *; apply case_bcomp with id s.\n2: assumption.\nintros x' s' H1 H2; pattern x' in |- *; apply case_bid.\n2: assumption.\nexists s'; auto 6.\n(* s SL*B||SL* s' *)\n(* idos' SL* s' *)\nSave commut_idl.\nHint Resolve commut_idl.\n\nGoal forall x y : sub_explicits, reg_idr x y -> e_diag1 _ x y.\nsimple induction 1; red in |- *; intros s z H0.\npattern z in |- *; apply case_bcomp with s id.\n2: assumption.\nintros s' x' H1 H2; pattern x' in |- *; apply case_bid.\n2: assumption.\nexists s'; auto 6.\n(* s SL*B||SL* s' *)\n(* s'oid SL* s' *)\nSave commut_idr.\nHint Resolve commut_idr.\n\nGoal forall x y : sub_explicits, reg_liftid x y -> e_diag1 _ x y.\nsimple induction 1; red in |- *; intros z H0.\npattern z in |- *; apply case_blift with id.\n2: assumption.\nintros x' H1; pattern x' in |- *; apply case_bid.\n2: assumption.\nexists id; auto 6.\n(* id SL*B||SL* id *)\n(* ||id SL* id *)\nSave commut_liftid.\nHint Resolve commut_liftid.\n\nGoal forall x y : terms, reg_id x y -> e_diag1 _ x y.\nsimple induction 1; red in |- *; intros a z H0.\npattern z in |- *; apply case_benv with a id.\n2: assumption.\nintros a' x' H1 H2; pattern x' in |- *; apply case_bid.\n2: assumption.\nexists a'; auto 6.\n(* a SLB||SL* a' *)\n(* a'[id] SL* a' *)\nSave commut_id.\nHint Resolve commut_id.\n \nGoal forall (b : wsort) (x y : TS b), e_systemSL _ x y -> e_diag1 _ x y.\nsimple induction 1; intros; auto.\nSave commut_systemSL.\n\n(* lemmes techniques *)\n\nGoal\nforall (P : terms -> Prop) (a : terms),\n(forall a' : terms, e_relSLstar _ a a' -> P (lambda a')) ->\nforall M N : terms, e_relSLstar _ N M -> N = lambda a -> P M.\nintros P a H M N H0; generalize a H; elim H0.\nintros x a0 H1 H2; rewrite H2; apply (H1 a0); red in |- *; apply star_refl.\nintros x y z H1 H2 H3 a0 H4 H5; generalize H1; rewrite H5; intro H6.\ncut (y = y).\n2: trivial.\npattern y at 2 in |- *; apply case_SLlambda with a0.\n2: assumption.\nintros a0' H7 H8; apply (H3 a0').\nintros a' H9; apply H4; red in |- *; apply star_trans1 with a0'; assumption.\nassumption.\nSave case_SLstar_lambda'.\n\nGoal\nforall (P : terms -> Prop) (a : terms),\n(forall a' : terms, e_relSLstar _ a a' -> P (lambda a')) ->\nforall M : terms, e_relSLstar _ (lambda a) M -> P M.\nintros; pattern M in |- *; apply case_SLstar_lambda' with a (lambda a);\n auto 6.\nSave case_SLstar_lambda.\n\nGoal\nforall (P : terms -> Prop) (a : terms),\n(forall a' : terms, e_slstar_bp_slstar _ a a' -> P (lambda a')) ->\nforall M : terms, e_slstar_bp_slstar _ (lambda a) M -> P M.\nintros P a H M H0.\nelim\n (comp_case terms (e_relSLstar wt)\n    (explicit_comp_rel _ (e_beta_par wt) (e_relSLstar wt)) \n    (lambda a) M H0).\nintros x H1; elim H1; intros H2.\npattern x in |- *; apply case_SLstar_lambda with a.\n2: assumption.\nintros a' H3 H4.\nelim (comp_case terms (e_beta_par wt) (e_relSLstar wt) (lambda a') M H4).\nintros y H5; elim H5; intros H6.\npattern y in |- *; apply case_blambda with a'.\n2: assumption.\nintros a'' H7 H8.\npattern M in |- *; apply case_SLstar_lambda with a''.\n2: assumption.\nintros a_ H9; apply H.\nred in |- *; apply comp_2rel with a'.\nassumption.\napply comp_2rel with a''; assumption.\nSave case_slbpsl_lambda.\n\nGoal forall a a' : terms, e_diag1 _ (lambda a) (lambda a') -> e_diag1 _ a a'.\nred in |- *; intros a a' H z H0.\nelim (H (lambda z)).\n2: apply lambda_bpar; assumption.\nintros u1 H1; elim H1; intros H2 H3.\ncut (u1 = u1).\n2: trivial.\npattern u1 at 1 in |- *; apply case_SLstar_lambda with z.\n2: assumption.\nintros z' H4; pattern u1 in |- *; apply case_slbpsl_lambda with a'.\n2: assumption.\nintros a'' H5 H6; exists a''; split.\nassumption.\nelim (proj_lambda z' a'' H6); assumption.\nSave diag1_lambda.\n\nTheorem commut :\n forall (b : wsort) (x y : TS b), e_relSL _ x y -> e_diag1 _ x y.\nsimple induction 1; intros.\n(* regles de reecriture *)\napply commut_systemSL; assumption.\n(* contexte app droit *)\nred in |- *; intros z H2; generalize H0 H1.\npattern z in |- *; apply case_bapp with a b0.\n3: assumption.\n (* regle B||: app *)\nintros a'' b0'' H3 H4 H5 H6.\nelim (H6 a'' H3); intros a_ H7; elim H7; intros H8 H9.\nexists (app a_ b0''); auto.\n (* regle B||: beta *)\nintros a1 a1'' b0'' H3 H4 H5; rewrite H3.\nintro H6; pattern a' in |- *; apply case_SLlambda with a1.\n2: assumption.\nintros a1' H7 H8.\nelim (diag1_lambda a1 a1' H8 a1'' H4); intros a_ H9; elim H9; intros H10 H11.\nexists (env a_ (cons b0'' id)); auto.\n(* contexte app gauche *)\nred in |- *; intros z H2; pattern z in |- *; apply case_bapp with a b0.\n3: assumption.\n (* regle B||: app *)\nintros a'' b0'' H3 H4.\nelim (H1 b0'' H4); intros b0_ H5; elim H5; intros H6 H7.\nexists (app a'' b0_); auto.\n (* regle B||: beta *)\nintros a1 a1'' b0'' H3 H4 H5; rewrite H3.\nelim (H1 b0'' H5); intros b0_ H6; elim H6; intros H7 H8.\nexists (env a1'' (cons b0_ id)); auto.\n(* contexte lambda *)\nred in |- *; intros z H2.\npattern z in |- *; apply case_blambda with a.\n2: assumption.\nintros a'' H3.\nelim (H1 a'' H3); intros a_ H4; elim H4; intros H5 H6.\nexists (lambda a_); auto.\n(* contexte env droit *)\nred in |- *; intros z H2.\npattern z in |- *; apply case_benv with a s.\n2: assumption.\nintros a'' s'' H3 H4.\nelim (H1 a'' H3); intros a_ H5; elim H5; intros H6 H7.\nexists (env a_ s''); auto.\n(* contexte env gauche *)\nred in |- *; intros z H2.\npattern z in |- *; apply case_benv with a s.\n2: assumption.\nintros a'' s'' H3 H4.\nelim (H1 s'' H4); intros s_ H5; elim H5; intros H6 H7.\nexists (env a'' s_); auto.\n(* contexte cons droit *)\nred in |- *; intros z H2.\npattern z in |- *; apply case_bcons with a s.\n2: assumption.\nintros a'' s'' H3 H4.\nelim (H1 a'' H3); intros a_ H5; elim H5; intros H6 H7.\nexists (cons a_ s''); auto.\n(* contexte cons gauche *)\nred in |- *; intros z H2.\npattern z in |- *; apply case_bcons with a s.\n2: assumption.\nintros a'' s'' H3 H4.\nelim (H1 s'' H4); intros s_ H5; elim H5; intros H6 H7.\nexists (cons a'' s_); auto.\n(* contexte comp droit *)\nred in |- *; intros z H2.\npattern z in |- *; apply case_bcomp with s t.\n2: assumption.\nintros s'' t'' H3 H4.\nelim (H1 s'' H3); intros s_ H5; elim H5; intros H6 H7.\nexists (comp s_ t''); auto.\n(* contexte comp gauche *)\nred in |- *; intros z H2.\npattern z in |- *; apply case_bcomp with s t.\n2: assumption.\nintros s'' t'' H3 H4.\nelim (H1 t'' H4); intros t_ H5; elim H5; intros H6 H7.\nexists (comp s'' t_); auto.\n(* contexte lift *)\nred in |- *; intros z H2.\npattern z in |- *; apply case_blift with s.\n2: assumption.\nintros s'' H3.\nelim (H1 s'' H3); intros s_ H4; elim H4; intros H5 H6.\nexists (lift s_); auto.\nQed.\n\n\n(***************************************************)\n(*    SL verifie le diagramme ci-dessus            *)\n(***************************************************)\n\nTheorem commutation :\n forall (b : wsort) (x y z : TS b),\n e_relSL _ x y ->\n e_beta_par _ x z ->\n exists u : TS b, e_relSLstar _ z u /\\ e_slstar_bp_slstar _ y u.\nintros b x y z H H0; apply Ex_PQ; generalize z H0.\nchange (e_diag1 _ x y) in |- *.\napply commut; assumption.\nQed.\n\n", "meta": {"author": "coq-contribs", "repo": "subst", "sha": "7b4f4d1df839443cb67f38bf780274abeb9de047", "save_path": "github-repos/coq/coq-contribs-subst", "path": "github-repos/coq/coq-contribs-subst/subst-7b4f4d1df839443cb67f38bf780274abeb9de047/commutation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2777851463943965}}
{"text": "\n(* This file constructs a notion of N-ary parallel composition for IPDL protocols, rather than only binary. We then lift \nour reasoning to be about N-ary composition (with prefix 'pars').\n*)\n\n\nFrom mathcomp Require Import ssreflect ssrbool ssrnat eqtype ssrfun seq tuple fintype.\nFrom mathcomp Require Import choice path bigop.\nRequire Import FunctionalExtensionality Classes.Equivalence.\nRequire Import Lib.SeqOps.\nRequire Import Lib.Base Ipdl.Exp Lib.TupleLems Lib.setoid_bigop.\nRequire Import Lib.Set Core.\n\nDefinition pars_def {C} (r : list (@ipdl C)) : ipdl := foldr Par (prot0) r.\n\nDefinition pars {C} r := (nosimpl (@pars_def C r)).\n\n\nNotation \"[pars xs ]\" := (pars xs) (format \"[pars  xs ]\").\nNotation \"[|| x1 ]\" := (pars (x1 :: [::]))\n  (at level 0, format \"[||  x1 ]\") : seq_scope.\n\nNotation \"[|| x1 ; x2 ; .. ; xn ]\" := (pars (x1 :: x2 :: .. [:: xn] ..))\n  (at level 0, format \"[||  '[' x1 ; '/' x2 ; '/' .. ; '/' xn ']' ]\"\n  ) : ipdl_scope.\n\nArguments pars : simpl never.\n\nSection Pars.\n  Context {chan : Type -> Type}.\n  Local Notation EqProt := (@EqProt chan).\n\n\nLemma pars_cons r rs : \n  EqProt (pars (r :: rs)) (r ||| pars rs).\n  rewrite //=.\nQed.\n\nLemma pars_prot0 (rs : seq (ipdl)) :\n  EqProt (pars (prot0 :: rs)) (pars rs).\n  rewrite pars_cons -eq_0par //=.\nQed.\n\nLemma pars_cons_cong r1 r2 rs1 rs2 :\n  EqProt r1 r2 ->\n  EqProt (pars rs1) (pars rs2) ->\n  EqProt (pars (r1 :: rs1)) (pars (r2 :: rs2)).\n  intros; rewrite !pars_cons.\n  apply EqCong; done.\nQed.\n\nLemma pars_rcons rs r :\n  EqProt (pars rs ||| r) (pars (rcons rs r)).\n  induction rs.\n  rewrite //=.\n  rewrite EqCompComm; reflexivity.\n  rewrite //= !pars_cons.\n  rewrite -IHrs.\n  rewrite EqCompAssoc.\n  reflexivity.\nQed.\n\nLemma pars_nil : @pars chan nil = prot0.\n  rewrite /pars //=.\nQed.\n\nLemma pars_cat rs1 rs2 : \n  EqProt (pars (rs1 ++ rs2)) (pars rs1 ||| pars rs2).\n  move:rs2; induction rs1; rewrite //=; intro.\n  rewrite pars_nil -eq_0par //=.\n  rewrite !pars_cons.\n  rewrite IHrs1 EqCompAssoc; reflexivity.\nQed.\n\nLemma pars1 r : EqProt (pars [:: r]) r.\n  rewrite /pars //= -eq_par0 //=.\nQed.\n\nLemma pars_pars rs rs' : EqProt (pars (pars rs :: rs')) (pars (rs ++ rs')).\n  rewrite pars_cons.\n  rewrite pars_cat.\n  reflexivity.\nQed.\n\n  Lemma pars2 r1 r2 :\n    EqProt (pars [:: r1; r2]) (r1 ||| r2).\n    rewrite !pars_cons /pars -eq_par0 //=.\n  Qed.\n\nLemma Perm_pars (xs ys : seq ipdl) :\n  Permutation.Permutation xs ys ->\n  EqProt (pars xs) (pars ys).\n  elim.\n  reflexivity.\n  intros.\n  rewrite !pars_cons //= H0; reflexivity.\n  intros.\n  rewrite !pars_cons //= EqCompAssoc (EqCompComm y) -EqCompAssoc; reflexivity.\n  intros.\n  rewrite (H0); done.\nQed.\n\n   Lemma pars_split (n : nat) (ps : seq ipdl) :\n     EqProt (pars ps) (pars (take n ps) ||| pars (drop n ps)).\n    rewrite -pars_cat.\n    rewrite cat_take_drop //=.\n   Qed.\n\n   Lemma par_in_pars r1 r2 rs :\n     EqProt (pars ((r1 ||| r2) :: rs))\n                (pars (r1 :: r2 :: rs)).\n     rewrite !pars_cons EqCompAssoc //=.\n   Qed.\n\n    Lemma par_in_pars2 r rs r1 r2 :\n        EqProt (pars (r :: (r1 ||| r2) :: rs))\n                    (pars (r :: r1 :: r2 :: rs)).\n        rewrite !pars_cons.\n        apply EqCong; rewrite //=.\n        rewrite EqCompAssoc; done.\n    Qed.\n\n    Lemma par_in_pars3 r r' rs r1 r2 :\n        EqProt (pars (r :: r' :: (r1 ||| r2) :: rs))\n                    (pars (r :: r' :: r1 :: r2 :: rs)).\n        rewrite !pars_cons.\n        apply EqCong; rewrite //=.\n        apply EqCong; rewrite //=.\n        rewrite EqCompAssoc; done.\n    Qed.\n\n    Lemma par_in_pars4 r r' r'' rs r1 r2 :\n        EqProt (pars (r :: r' :: r'' :: (r1 ||| r2) :: rs))\n                    (pars (r :: r' :: r'' :: r1 :: r2 :: rs)).\n        rewrite !pars_cons.\n        apply EqCong; rewrite //=.\n        apply EqCong; rewrite //=.\n        apply EqCong; rewrite //=.\n        rewrite EqCompAssoc; done.\n    Qed.\n\n\nLemma cat_nil_nil {A : eqType} (x y : seq A) :\n  x = nil ->\n  y = nil ->\n  (x ++ y = nil).\n  move => -> ->; done.\nQed.\n\nLemma filter_none {A} (xs : seq A) (P : pred A) :\n  all (fun x => ~~ (P x)) xs ->\n  filter P xs = nil.\n  intros; induction xs; rewrite //=.\n  simpl in H; destruct (andP H).\n  rewrite (negbTE H0) IHxs //=.\nQed.\n\nLemma New_in_pars t k rs :\n  pars [:: New t k & rs] =p @New chan t (fun x => pars [:: k x & rs]).\n  rewrite pars_cons.\n  rewrite EqCompNew.\n  apply EqCongNew; intros.\n  rewrite pars_cons //=.\nQed.\n\n(* Rewriting in pars *)\n\nInductive list_eqprot : list ipdl -> list ipdl -> Prop :=\n  | nil_equiv : list_eqprot nil nil\n  | cons_equiv x y s t : EqProt x y -> list_eqprot s t -> list_eqprot (x :: s) (y :: t).\n\nInstance list_eqprot_refl : Reflexive list_eqprot.\n   intro.\n   induction x.\n   constructor.\n   constructor.\n   done.\n   done.\nQed.\n\nInstance list_eqprot_tr : Transitive list_eqprot.\n   intro; intros.\n   move: z H0; induction H; intros.\n   done.\n   inversion H1; subst.\n   constructor.\n   rewrite H //=.\n   apply IHlist_eqprot.\n   done.\nQed.\n\nInstance list_eqprot_sym : Symmetric list_eqprot.\n   intro; intros.\n   induction H.\n   done.\n   constructor.\n   rewrite H //=.\n   done.\nQed.\n\n\n\nLemma swapE  n k rs :\n  EqProt (pars rs) (pars (swap n k rs)).\n  apply Perm_pars.\n  apply Perm_swap.\nQed.\n\nLemma pars_fold t1 t2 (a : chan t1) (r : rxn t2)\n      (k : t2 -> rxn t1) rs :\n  EqProt \n         (New t2 (fun c => pars [:: Out a (x <-- Read c ;; k x), Out c r & rs]))\n         (pars [:: Out a (x <-- r ;; k x) & rs]).\n  etransitivity.\n  apply EqCongNew => c.\n  rewrite !pars_cons.\n  rewrite EqCompAssoc.\n  apply EqRefl.\n  rewrite -EqCompNew.\n  setoid_rewrite EqCompComm at 2.\n  rewrite EqFold. \n  rewrite -pars_cons //=.\nQed.\n\n(* Tactics for basic permutations / editing *)\n\nLemma pars_edit' r1 r2 rs :\n  EqProt r1 r2 ->\n  EqProt (pars (r1 :: rs)) (pars (r2 :: rs)).\n  intros.\n  rewrite //=.\n  apply EqCong.\n  done.\n  reflexivity.\nQed.\n\nOpen Scope bool_scope.\n\nLemma pars_edit n r1 r2 rs : \n  EqProt r1 r2 ->\n  List.nth_error rs n = Some r1 ->\n  EqProt (pars rs) (pars (lset rs n r2)).\n  intros.\n  destruct (eqVneq n 0); subst.\n  destruct rs.\n  rewrite //=.\n  simpl in H.\n  inversion H0; subst.\n  erewrite pars_edit'.\n  rewrite lset_0_cons.\n  reflexivity.\n  done.\n  \n  etransitivity.\n  apply (swapE 0 n).\n  destruct rs; simpl in *.\n  destruct n; done.\n  erewrite swap0E; last first.\n  apply H0.\n  done.\n  done.\n  erewrite pars_edit'; last by apply H.\n  etransitivity.\n  apply (swapE 0 n).\n  simpl.\n  have -> : swap 0 n (r2 :: lset rs n.-1 i0) =\n           lset (i0 :: rs) n (r2).\n  apply nth_error_eqP => j.\n  rewrite nth_error_swap //=.\n  rewrite nth_error_lset.\n  destruct (eqVneq n j); subst.\n  rewrite size_lset.\n  have: List.nth_error (i0 :: rs) j by rewrite H0.\n  rewrite nth_error_size_lt => ->.\n  rewrite (negbTE i) //=.\n  rewrite -nth_error_size_lt.\n  destruct j.\n  done.\n  simpl.\n  simpl in H0.\n  rewrite H0 //=.\n  rewrite size_lset; last first.\n  rewrite -nth_error_size_lt.\n  destruct n.\n  done.\n  simpl in *; rewrite H0 //=.\n  destruct n.\n  done.\n  simpl in *.\n  have -> : (n.+1 < (size rs).+1) = (n < size rs) by done.\n  rewrite -nth_error_size_lt H0 //=.\n  destruct j; simpl.\n  rewrite nth_error_lset.\n  rewrite eq_refl //=.\n  rewrite -nth_error_size_lt H0 //=.\n  rewrite nth_error_lset.\n  rewrite eqE //= in i1. \n  have hnj: n != j by done.\n  rewrite (negbTE hnj); done.\n  rewrite -nth_error_size_lt H0 //=.\n  rewrite -nth_error_size_lt H0 //=.\n  reflexivity.\nQed.\n\nLemma pars_edit_out n m (cm : chan m) (r1 r2 : rxn m) (rs : seq (ipdl)) : \n  r1 =r r2 ->\n  List.nth_error rs n = Some (Out cm r1) ->\n  EqProt (pars rs) (pars (lset rs n (Out cm r2))).\n  intros.\n  eapply pars_edit.\n  apply EqCongReact.\n  apply H.\n  done.\nQed.\n\n   Lemma inline {t} {t'} (b : chan t') (c : chan t) k r :\n     isDet _ r ->\n     EqProt (Out b (x <-- Read c ;; k x) ||| Out c r)\n                      (Out b (x <-- r ;; k x) ||| Out c r).\n     intros.\n     rewrite EqCompComm.\n     rewrite EqSubst //=.\n     rewrite EqCompComm.\n     done.\n   Qed.\n\n   Lemma pars_inline {t} {t'} (b : chan t') (c : chan t) k r rs :\n     isDet _ r ->\n     EqProt (pars [:: (Out b (x <-- Read c ;; k x)), Out c r & rs])\n                      (pars [:: (Out b (x <-- r ;; k x)), Out c r & rs]).\n     intros.\n     rewrite !pars_cons.\n     rewrite !EqCompAssoc.\n     rewrite inline.\n     done.\n     done.\n   Qed.\n\nLemma pars_mkdep {t1 t2} (c : chan t1) (d : chan t2) r1 r2 rs :\n  (forall t (c0 : chan t), can_read c0 r2 -> reads_from c0 r1) ->\n  pars [::\n          c ::= r1, d ::= r2 & rs] =p\n  pars [::\n          c ::= (_ <-- Read d ;; r1), d ::= r2 & rs].\n  intros.\n  symmetry.\n  rewrite pars_cons.\n  rewrite pars_cons.\n  rewrite EqCompAssoc.\n  rewrite EqCompComm.\n  etransitivity.\n  apply EqCongComp.\n  rewrite EqCompComm.\n  apply EqUnused.\n  done.\n  symmetry; rewrite !pars_cons.\n  symmetry.\n  rewrite EqCompComm.\n  rewrite EqCompAssoc.\n  rewrite (EqCompComm (c ::= r1)).\n  done.\nQed.\n\nLemma pars_unused {t1 t2} (c1 : chan t1) (c2 : chan t2) rs r r' :\n  (forall (t : Type) (c0 : chan t), can_read c0 r -> reads_from c0 r') ->\n  (pars [:: Out c2 (_ <-- Read c1;; r'), Out c1 r & rs]) =p\n  (pars [:: Out c2 (r'), Out c1 r & rs]).\n  intros.\n  rewrite -pars_mkdep.\n  done.\n  done.\nQed.\n\n\nLemma pars_tr {t1 t2 t3} (c : chan t1) (d : chan t3) k1 (e : chan t2) k2 rs :\n  pars [::\n          c ::= (x <-- Read d ;; k1 x),\n          e ::= (x <-- Read c ;; k2 x) & rs]\n  =p\n  pars [::\n          c ::= (x <-- Read d ;; k1 x),\n          e ::= (_ <-- Read d ;; x <-- Read c ;; k2 x) & rs].\n  intros; rewrite !pars_cons !EqCompAssoc.\n  rewrite EqSubsume; last first.\n  done.\nQed.\n\nLemma new_pars_remove {t1} (r : chan t1 -> rxn t1) rs :\n  (a <- new t1 ;; pars [:: Out a (r a) & rs]) =p pars rs.\n  intros.\n  setoid_rewrite pars_cons.\n  rewrite RRemove; done.\nQed.\n\nLemma generalize_pars_eq2_1 r1 r2 r1' r2' :\n  (forall rs, pars [:: r1, r2 & rs] =p pars [:: r1', r2' & rs] ) ->\n  forall rs1 rs2,\n    @pars chan ([:: r1] ++ rs1 ++ [:: r2] ++ rs2) =p pars (r1' :: rs1 ++ [:: r2'] ++ rs2).\n  intros.\n  induction rs1.\n  simpl.\n  rewrite H.\n  done.\n  simpl.\n  rewrite (swapE 0 1); rewrite /swap /lset //=.\n  rewrite insert_0.\n  rewrite (pars_split 1); simpl.\n  rewrite IHrs1.\n  rewrite -pars_cat; simpl.\n  rewrite (swapE 0 1); rewrite /swap /lset //=.\n  rewrite insert_0.\n  done.\nQed.\n\n\nEnd Pars.\n\nAdd Parametric Relation {C} : (list (@ipdl C)) (list_eqprot ) \n                                       reflexivity proved by (list_eqprot_refl )\n                                       symmetry proved by (list_eqprot_sym )\n                                           transitivity proved by (list_eqprot_tr ) as list_eqprot_rel.\n\nClose Scope bool_scope.\nRequire Import Setoid Relation_Definitions Morphisms.\n\nAdd Parametric Morphism {C} : (@pars C) with signature\n    list_eqprot ==> EqProt as pars_mor.\n  intros.\n  induction H.\n  done.\n  rewrite !pars_cons.\n  rewrite H.\n  rewrite IHlist_eqprot.\n  done.\nQed.\n\nAdd Parametric Morphism {C} : cons with signature\n    (@EqProt C) ==> list_eqprot ==> list_eqprot as cons_mor.\n  intros.\n  constructor; done.\nQed.\n\n\nLtac find_in_pars_rec p rs acc :=\n  lazymatch eval simpl in rs with\n    | nil => acc\n    | (?r :: ?rs') =>\n      lazymatch r with\n        | context[p] => acc\n        | _ => find_in_pars_rec p rs' (S acc)\n      end\n   end.\n\nLtac find_in_pars p rs := find_in_pars_rec p rs 0.\n\nLtac get_idx nxx :=\n  let t := type of nxx in\n  lazymatch eval simpl in t with\n    | nat => constr:(nxx)\n    | _ =>\n      match goal with\n      | [ |- EqProt (pars ?rs) _ ] =>\n        let j := find_in_pars nxx rs in j\n      end\n  end.\n\nLtac swap_tac nxx mxx :=\n  let m___ := get_idx mxx in\n  setoid_rewrite (swapE nxx m___) at 1; rewrite /swap /lset /=.\n\nLtac split_tac n :=\n    match goal with\n      | [ |- @EqProt  _ _ ] => setoid_rewrite (pars_split n _) at 1; rewrite /= end.\n\nLtac join_tac :=\n    match goal with\n      | [ |- EqProt  _ ] => setoid_rewrite <- (pars_cat _ _ ) at 1; rewrite /= end.\n\n\n\nLemma nth_errorP {T} (xs : seq T) x n :\n  List.nth_error xs n = Some x ->\n  exists xs1 xs2,\n    (xs = xs1 ++ [:: x] ++ xs2) /\\ (size xs1 = n).\n  move: xs x; induction n.\n  intros.\n  destruct xs.\n  done.\n  simpl in *.\n  inversion H; subst.\n  exists nil.\n  simpl.\n  exists xs; split; done.\n  intros.\n  destruct xs.\n  done.\n  simpl in *.\n  move/IHn: H => [A [B [h1 h2]]].\n  subst.\n  exists (t :: A).\n  exists B.\n  simpl.\n  split; done.\nQed.\n\n\n  \n", "meta": {"author": "ipdl", "repo": "ipdl", "sha": "d41b022c9a216acfefaefcbd0ede9e52e350ab8a", "save_path": "github-repos/coq/ipdl-ipdl", "path": "github-repos/coq/ipdl-ipdl/ipdl-d41b022c9a216acfefaefcbd0ede9e52e350ab8a/theories/Pars.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.27778514639439644}}
{"text": "From SSL_Iris Require Import core.\nFrom iris.program_logic Require Export weakestpre.\nFrom iris.proofmode Require Export tactics coq_tactics ltac_tactics reduction.\nFrom iris.heap_lang Require Import lang notation proofmode.\nRequire Import common.\nFrom iris_string_ident Require Import ltac2_string_ident.\nFrom Hammer Require Import Hammer.\nContext `{!heapG Σ}.\nSet Default Proof Using \"Type\".\n\n\nDefinition sll_append : val :=\nrec: \"sll_append\" \"x1\" \"r\" :=\nlet: \"x22\" := ! (\"r\") in\n#();; \nif: \"x1\" = #null_loc\nthen (\n#()\n)\nelse (\nlet: \"vx12\" := ! (\"x1\") in\n#();; \nlet: \"nxtx12\" := ! (\"x1\" +ₗ #1) in\n#();; \n\"sll_append\" \"nxtx12\" \"r\";; \nlet: \"y12\" := ! (\"r\") in\n#();; \n(\"x1\" +ₗ #1) <- (\"y12\");; \n(\"r\") <- (\"x1\");; \n#()\n).\n\n\nLemma sll_append_spec :\n∀ (r : loc) (x2 : loc) (s2 : (list Z)) (_alpha_531 : sll_card) (x1 : loc) (s1 : (list Z)) (_alpha_530 : sll_card),\n{{{ (sll x1 s1 _alpha_530) ∗ (sll x2 s2 _alpha_531) ∗ r ↦ #x2 }}}\n  sll_append #x1 #r\n{{{ RET #(); ∃ (y : loc) (_alpha_532 : sll_card) (s : (list Z)), ⌜(s = (s1 ++ s2))⌝ ∗ (sll y s _alpha_532) ∗ r ↦ #y }}}.\nProof.\niIntros (r x2 s2 _alpha_531 x1 s1 _alpha_530 ϕ) \"(iH1 & iH2 & iH3) Post\".\niRewriteHyp.\niLöb as \"sll_append\" forall (r x2 s2 _alpha_531 x1 s1 _alpha_530 ϕ).\nssl_begin.\ntry rename x2 into x22.\nssl_load.\niRename select ((sll x1 s1 _alpha_530))%I into \"iH4\".\nssl_if Cond_iH4.\n\niDestruct (sll_card_0_learn with \"iH4\") as \"[iH4 %iH4_eqn]\".\nrewrite iH4_eqn; last by safeDispatchPure.\ntac_except_post ltac:(rewrite sll_card_0_open).\niDestruct \"iH4\" as  \"(%iH5 & %iH6)\".\ntry wp_pures.\niFindApply.\niExists x22.\niExists _alpha_531.\niExists ([] ++ s2).\nssl_finish.\n\n\niDestruct (sll_card_1_learn with \"iH4\") as \"[iH4 %iH4_eqn]\".\n\nedestruct iH4_eqn as [_alpha_529x1 ->]; first by safeDispatchPure.\ntac_except_post ltac:(rewrite sll_card_1_open).\niDestruct \"iH4\" as (vx1 s1x1 nxtx1) \"((%iH7 & %iH8) & (iH9 & iH10 & iH11 & iH12))\".\ntry rename vx1 into vx12.\nssl_load.\ntry rename nxtx1 into nxtx12.\nssl_load.\nwp_apply (\"sll_append\" $! (r) (x22) (s2) (_alpha_531) (nxtx12) (s1x1) (_alpha_529x1) with \"[$] [$] [$]\").\n\n\niIntros  \"iH16\".\niDestruct \"iH16\" as (y1 _alpha_5321 s3) \"(%iH13 & (iH14 & iH15))\".\ntry wp_pures.\ntry rename y1 into y12.\nssl_load.\nssl_store.\nssl_store.\ntry wp_pures.\niFindApply.\niExists x1.\niExists (sll_card_1 _alpha_5321 : sll_card).\niExists (([vx12] ++ s1x1) ++ s2).\nssl_finish.\nssl_rewrite_first_heap sll_card_1_open.\npull_out_exist.\niExists vx12.\npull_out_exist.\niExists (s1x1 ++ s2).\npull_out_exist.\niExists y12.\nssl_finish.\nQed.\n", "meta": {"author": "TyGuS", "repo": "ssl-iris", "sha": "becdbae4151083b75eaf5790892ce437276f6b1a", "save_path": "github-repos/coq/TyGuS-ssl-iris", "path": "github-repos/coq/TyGuS-ssl-iris/ssl-iris-becdbae4151083b75eaf5790892ce437276f6b1a/benchmarks/sll/sll_append.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.27778514639439644}}
{"text": "Require Import PeanoNat.\n\nRequire Export SystemFR.NormalizationSing.\nRequire Export SystemFR.SubtypeList.\nRequire Export SystemFR.InferMatch.\nRequire Export SystemFR.CloseLemmas.\n\nOpaque reducible_values.\n\nLemma open_nmatch_3: forall Γ T2 T3 t t',\n  is_erased_type T2 ->\n  is_erased_type T3 ->\n  wf T2 0 ->\n  wf T3 2 ->\n  subset (fv T2) (support Γ) ->\n  subset (fv T3) (support Γ) ->\n  [ Γ ⊨ t ⤳* t' ] ->\n  [ Γ ⊫ List_Match t T2 T3 = List_Match t' T2 T3 ].\nProof.\n  eauto using open_sub_list_match_scrut, delta_beta_obs_equiv.\nQed.\n\nLemma nmatch_nil: forall ρ T2 T3,\n  valid_interpretation ρ ->\n  [ ρ ⊨ List_Match tnil T2 T3 = T2 ].\nProof.\n  unfold equivalent_types, List_Match;\n    repeat step || simp_red_top_level_goal || simp_red_top_level_hyp || open_none;\n    eauto using reducible_values_closed.\n\n  - apply_anywhere equivalent_value_left; steps; eauto with closing values.\n  - left; repeat step || simp_red || exists uu;\n      eauto using reducible_values_closed;\n      eauto using equivalent_refl.\nQed.\n\nOpaque List.\n\nLemma nmatch_cons: forall ρ t ts T2 T3,\n  valid_interpretation ρ ->\n  wf t 0 ->\n  wf ts 0 ->\n  is_erased_term t ->\n  is_erased_term ts ->\n  pfv t term_var = nil ->\n  pfv ts term_var = nil ->\n  wf T3 2 ->\n  pfv T3 term_var = nil ->\n  is_erased_type T3 ->\n  [ ρ ⊨ t : T_top ] ->\n  [ ρ ⊨ ts : List ] ->\n  [ ρ ⊨ List_Match (tcons t ts) T2 T3 = open 0 (open 1 T3 t) ts ].\nProof.\n  unfold equivalent_types, List_Match;\n    repeat step || simp_red_top_level_goal || simp_red_top_level_hyp || open_none;\n    eauto using reducible_values_closed;\n    eauto 3 using right_left_equivalence with exfalso values.\n\n  - apply_anywhere tright_equiv; eauto with closing values.\n    eapply reducibility_open_equivalent2; try eassumption; steps;\n      eauto 3 using equivalent_sym, pair_equiv_1, pair_equiv_2 with closing.\n\n  - right; repeat step.\n    apply reducible_expr_value; eauto with values.\n    apply reducible_exists with t;\n      repeat step || list_utils || rewrite open_list || open_none; eauto with fv wf erased.\n    apply reducible_exists with ts;\n      repeat step || list_utils || open_none; eauto with fv wf erased.\n    apply reducible_type_refine with uu; repeat step || open_none || list_utils;\n      eauto with fv wf erased;\n      eauto using reducible_value_expr.\n    apply reducible_value_expr; repeat step || simp_red_goal.\n    apply equivalent_refl; repeat step || list_utils.\nQed.\n\nOpaque List_Match.\n\nLemma open_nmatch_nil: forall Θ Γ T2 T3,\n  [ Θ; Γ ⊨ List_Match tnil T2 T3 = T2 ].\nProof.\n  unfold open_equivalent_types; repeat step || rewrite substitute_List_Match;\n    eauto with wf;\n    eauto using nmatch_nil.\nQed.\n\nLemma open_nmatch_1: forall Γ T2 T2' T3 t,\n  is_erased_type T2 ->\n  is_erased_type T3 ->\n  wf T2 0 ->\n  wf T3 2 ->\n  subset (fv T2) (support Γ) ->\n  subset (fv T3) (support Γ) ->\n  [ Γ ⊨ t ⤳* tnil ] ->\n  [ Γ ⊫ T2 = T2' ] ->\n  [ Γ ⊫ List_Match t T2 T3 = T2' ].\nProof.\n  intros.\n  eapply open_equivalent_types_trans; try apply open_nmatch_3;\n    eauto using open_equivalent_types_trans, open_nmatch_nil.\nQed.\n\nLemma open_nmatch_cons: forall Θ Γ T2 T3 t1 t2,\n  wf t1 0 ->\n  wf t2 0 ->\n  wf T3 2 ->\n  is_erased_term t1 ->\n  is_erased_term t2 ->\n  is_erased_type T3 ->\n  subset (fv t1) (support Γ) ->\n  subset (fv t2) (support Γ) ->\n  subset (fv T3) (support Γ) ->\n  [ Θ; Γ ⊨ t1 : T_top ] ->\n  [ Θ; Γ ⊨ t2 : List ] ->\n  [ Θ; Γ ⊨ List_Match (tcons t1 t2) T2 T3 = open 0 (open 1 T3 t1) t2 ].\nProof.\n  unfold open_equivalent_types, open_reducible;\n    repeat step || rewrite substitute_List_Match || t_substitutions ||\n           t_instantiate_sat3 || apply nmatch_cons;\n    eauto with wf erased fv.\nQed.\n\nLemma reducibility_subst_equiv:\n  forall ρ v T x t1 t2,\n    [ ρ ⊨ v : psubstitute T ((x, t1) :: nil) term_var ]v ->\n    valid_interpretation ρ ->\n    wf T 0 ->\n    is_erased_type T ->\n    subset (fv T) (x :: nil) ->\n    [ t1 ≡ t2 ] ->\n    [ ρ ⊨ v : psubstitute T ((x, t2) :: nil) term_var ]v.\nProof.\n  intros; repeat rewrite <- (open_close _ _ _ 0) in * by auto.\n  rewrite <- (open_close _ _ _ 0) in H by auto.\n  eapply reducibility_open_equivalent; eauto; repeat step;\n    eauto with erased wf;\n    eauto using fv_close_nil2.\nQed.\n\nLemma reducibility_subst_equiv2:\n  forall ρ T x t1 t2,\n    valid_interpretation ρ ->\n    wf T 0 ->\n    is_erased_type T ->\n    subset (fv T) (x :: nil) ->\n    [ t1 ≡ t2 ] ->\n    [ ρ ⊨ psubstitute T ((x, t1) :: nil) term_var = psubstitute T ((x, t2) :: nil) term_var ].\nProof.\n  unfold equivalent_types; steps;\n    eauto using reducibility_subst_equiv, equivalent_sym.\nQed.\n\nLemma subset_diff:\n  forall s1 x s2,\n    subset s1 (x :: s2) ->\n    subset (s1 -- (x :: nil)) s2.\nProof.\n  unfold subset; repeat step || instantiate_any || rewrite in_remove in *.\nQed.\n\nOpaque diff.\n\nLemma subset_diff2:\n  forall s1 x s2,\n    subset s1 (x :: s2) ->\n    subset (s1 -- s2) (x :: nil).\nProof.\n  unfold subset; repeat step || instantiate_any || rewrite in_diff in *.\nQed.\n\nLemma closed_mapping_fv2:\n  forall l tag,\n    pclosed_mapping l tag ->\n    pfv_range l tag = nil.\nProof.\n  induction l; repeat step || list_utils.\nQed.\n\nLemma reducibility_subst_equiv3:\n  forall ρ T x l t1 t2,\n    valid_interpretation ρ ->\n    wf T 0 ->\n    is_erased_type T ->\n    ~ x ∈ support l ->\n    wfs l 0 ->\n    erased_terms l ->\n    pclosed_mapping l term_var ->\n    subset (fv T) (x :: support l) ->\n    [ t1 ≡ t2 ] ->\n    [ ρ ⊨ psubstitute T ((x, t1) :: l) term_var = psubstitute T ((x, t2) :: l) term_var ].\nProof.\n  intros.\n  repeat rewrite (substitute_cons4 _ T); steps.\n  apply reducibility_subst_equiv2; steps; eauto with wf erased fv.\n  eapply subset_transitive; eauto using fv_subst2;\n    repeat step || sets || rewrite closed_mapping_fv2 by auto;\n    eauto using subset_diff2;\n    eauto with sets.\nQed.\n\nLemma in_support_in_context:\n  forall P Γ l x,\n    x ∈ support l ->\n    satisfies P Γ l ->\n    x ∈ pfv_context Γ term_var.\nProof.\n  intros; apply fv_context_support; erewrite satisfies_same_support; eauto.\nQed.\n\nLemma open_instantiate:\n  forall Θ Γ x t T T1 T2,\n    ~ x ∈ fv T ->\n    ~ x ∈ fv_context Γ ->\n    wf T1 0 ->\n    wf T2 0 ->\n    is_erased_type T1 ->\n    is_erased_type T2 ->\n    subset (fv T1) (x :: support Γ) ->\n    subset (fv T2) (x :: support Γ) ->\n    [ Θ; Γ ⊨ t : T ] ->\n    [ Θ; (x, T) :: Γ ⊨ T1 = T2 ] ->\n    [ Θ; Γ ⊨ psubstitute T1 ((x, t) :: nil) term_var = psubstitute T2 ((x, t) :: nil) term_var ].\nProof.\n  unfold open_equivalent_types, open_reducible; repeat step || t_instantiate_sat3.\n  top_level_unfold reduces_to; steps.\n  unshelve epose proof (H8 ρ ((x, v) :: l) _ _);\n    repeat step || apply SatCons || (rewrite <- substitute_cons3 by steps);\n    eauto with fv wf twf erased.\n\n  eapply equivalent_types_trans; try eapply reducibility_subst_equiv3;\n    repeat step || erewrite satisfies_same_support in * by eauto;\n    try solve [ equivalent_star ];\n    eauto using in_support_in_context;\n    eauto with wf erased fv.\n\n  eapply equivalent_types_trans; eauto; apply equivalent_types_sym.\n\n  apply reducibility_subst_equiv3;\n    repeat step || erewrite satisfies_same_support in * by eauto;\n    try solve [ equivalent_star ];\n    eauto using in_support_in_context;\n    eauto with wf erased fv.\nQed.\n\nLemma open_reducible_weaken:\n  forall Θ Γ x A t B,\n    ~ x ∈ fv t ->\n    ~ x ∈ fv B ->\n    [ Θ; Γ ⊨ t : B ] ->\n    [ Θ; (x, A) :: Γ ⊨ t : B ].\nProof.\n  unfold open_reducible; repeat step || step_inversion satisfies || t_substitutions.\nQed.\n\nLemma open_nmatch_2: forall Γ T2 T3 T3' t t1 t2 x y,\n  is_erased_term t1 ->\n  is_erased_term t2 ->\n  is_erased_type T2 ->\n  is_erased_type T3 ->\n  is_erased_type T3' ->\n  wf t1 0 ->\n  wf t2 0 ->\n  wf T2 0 ->\n  wf T3 2 ->\n  wf T3' 0 ->\n  subset (fv t1) (support Γ) ->\n  subset (fv t2) (support Γ) ->\n  subset (fv T2) (support Γ) ->\n  subset (fv T3) (support Γ) ->\n  subset (fv T3') (support Γ) ->\n  ~ x ∈ fv t1 ->\n  ~ x ∈ fv t2 ->\n  ~ x ∈ fv T3 ->\n  ~ x ∈ fv T3' ->\n  ~ x ∈ fv_context Γ ->\n  ~ y ∈ fv t1 ->\n  ~ y ∈ fv t2 ->\n  ~ y ∈ fv T3 ->\n  ~ y ∈ fv T3' ->\n  ~ y ∈ fv_context Γ ->\n  x <> y ->\n  [ Γ ⊫ t1 : T_top ] ->\n  [ Γ ⊫ t2 : List ] ->\n  [ Γ ⊨ t ⤳* tcons t1 t2 ] ->\n  [ (x, T_singleton T_top t1) :: (y, T_singleton List t2) :: Γ ⊫\n    open 0 (open 1 T3 (fvar x term_var)) (fvar y term_var) = T3' ] ->\n  [ Γ ⊫ List_Match t T2 T3 = T3' ].\nProof.\n  intros.\n  eapply open_equivalent_types_trans; try apply open_nmatch_3; try eassumption; steps.\n  eapply open_equivalent_types_trans; try apply open_nmatch_cons; steps.\n  apply (open_instantiate _ _ _ t1) in H28;\n    repeat step || list_utils || apply wf_open || apply is_erased_type_open ||\n           rewrite pfv_shift2 in *;\n    eauto with fv wf erased;\n    eauto using subset_add2.\n  - apply (open_instantiate _ _ _ t2) in H28;\n      repeat step || list_utils || apply wf_open || apply wf_subst || t_substitutions ||\n             apply is_erased_type_open || apply subst_erased_type ||\n             rewrite pfv_shift2 in *;\n      eauto with fv wf erased;\n      eauto using subset_add2;\n      eauto using open_reducible_singleton.\n\n    + rewrite (substitute_nothing2 T3') in *; repeat step || rewrite substitute_nothing3 in *.\n      rewrite (substitute_nothing2 T3') in *; repeat step || rewrite substitute_nothing3 in *.\n\n    + eapply subset_transitive; eauto using fv_open; repeat step || sets.\n      eapply subset_transitive; eauto using fv_open; repeat step || sets;\n        eauto using subset_add2.\n\n  - eapply subset_transitive; eauto using fv_open; repeat step || sets.\n    eapply subset_transitive; eauto using fv_open; repeat step || sets;\n      eauto using subset_add2.\n  - apply open_reducible_weaken; repeat step || rewrite pfv_shift2 in *;\n      eauto using open_reducible_singleton.\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/NormalizationMatch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.27778514639439644}}
{"text": "Add LoadPath \"/users/paulkline/Documents/coqs/protosynth\".\nAdd LoadPath \"/home/paul/Documents/coqs/protosynth/cpdt/src\" as Cpdt.  \nRequire Import MyShortHand.\n\nInductive Noun : Set:=\n  | VirusChecker\n  | PCR.\nTheorem eq_dec_Noun : equality Noun.\ncrush_equal. \nDefined. \nHint Resolve eq_dec_Noun : eq_dec_db. \n(* Now we define what it is we would like to know about these nouns. *)\nInductive Attribute : Set :=\n  | Name : Attribute\n  | Hash : Attribute\n  | Index : nat -> Attribute\n  | Version : Attribute.\nTheorem eq_dec_Attribute : equality Attribute. \ncrush_equal. Defined. \nHint Resolve eq_dec_Attribute : eq_dec_db. \n(*We only want to disallow nonsensical combinations, like a (PCR, version),\n hence this relation. *)\nInductive DescriptionR : Noun -> Attribute -> Set :=\n  | pcrMR : forall n, DescriptionR PCR (Index n)\n  | virusCheckerNameR : DescriptionR VirusChecker Name\n  | virusCheckerVersionR : DescriptionR VirusChecker Version.\nTheorem eq_dec_DescriptionR {n} {a}:  equality (DescriptionR n a).\ncrush_equal. \nDefined.\nHint Resolve eq_dec_DescriptionR : eq_dec_db.  \nHint Resolve eq_dec_DescriptionR.\n \n(* This 'extra step' is done simply so that comparison between descriptors\nis 'easy.'It is much more involved to be able to compare indexed types. *)\nInductive Description : Set :=\n  | descriptor {n : Noun} {a : Attribute} : DescriptionR n a -> Description.\nTheorem eq_dec_Description : equality Description.\ncrush_equal. \nDefined.\nHint Resolve eq_dec_Description : eq_dec_db. \n\n(*This defines what the type of measuring these things should be. *)\nDefinition measurementDenote (d: Description) :=\nmatch d with\n | descriptor r => (match r with\n    | pcrMR n => nat\n    | virusCheckerNameR => nat\n    | virusCheckerVersionR => nat\n    end)\nend.\n\n(* Here we begin specificiation of requirements. So not only do I want a particular measurment,\n   but I want it to be certain values. *) \nInductive Requirement (d : Description) :=\n| requirement : ( (measurementDenote d) -> bool) -> Requirement d.\nRequire Import FunctionalExtensionality. \nTheorem eq_dec_f {A} {B} : forall (a b : (A -> B)), a =<> b.\nProof. intros.\nspecialize functional_extensionality with a b. intros.\n Admitted.\nHint Resolve eq_dec_f : eq_dec_db. \nTheorem eq_dec_Requirement : forall d (x y : Requirement d), x =<> y.\nProof. intros. \ndestruct d. \ndestruct d; \ncrush_equal. \nDefined. \nHint Resolve eq_dec_Requirement : eq_dec_db.\n\n\n\n(* This begins the defining of what a privacy policy is. First we define a rule.\n    A rule regulates the release of a measurement. We could decide to release information if\n    some counter condition holds; we could release it for free; we could explicitly never release it; \n    or some combination of and-ing and or-ing rules.\n    Note that at this point we've allowed for nonsensical release rules like, \"never release or release for free\",\n     \"release for free and never release\".\n    NOTE: If we can't request something twice, what if duplicate occurs in rule req?\n          todo: keep all received measurements and check those first for the value *) \nInductive Rule (mything : Description) :=  \n| rule  {your : Description} : (Requirement your) -> Rule mything\n| free : Rule mything\n| never : Rule mything.\n(*| multiReqAnd : Rule mything ->Rule mything -> Rule mything\n| multiReqOr : Rule mything -> Rule mything -> Rule mything.\n*)\nTheorem eq_dec_Rule : forall x, equality (Rule x).\nProof.   \n\n\nintros. intro_equals. \ndestruct x.  \ndestruct d;\ngeneralize dependent x0; \ninduction y;\nintro_equals; \ndestruct x0; try first [decidable |  \ncrush_equal].\n(* rest is for and and or case included *)\n(*\nspecialize IHy1 with x0_1. \nspecialize IHy2 with x0_2.\ndestruct IHy1.  subst. \ndestruct IHy2.  subst. decidable. \ndecidable.  decidable.\nspecialize IHy1 with x0_1. \nspecialize IHy2 with x0_2.\ndestruct IHy1.  subst. \ndestruct IHy2.  subst. decidable.\ncrush_equal. decidable.\nspecialize IHy1 with x0_1. \nspecialize IHy2 with x0_2.\ndestruct IHy1.  subst. \ndestruct IHy2.  subst. decidable. \ndecidable.  decidable.\nspecialize IHy1 with x0_1. \nspecialize IHy2 with x0_2.\ndestruct IHy1.  subst. \ndestruct IHy2.  subst. decidable.\ncrush_equal. decidable.\n\nspecialize IHy1 with x0_1. \nspecialize IHy2 with x0_2.\ndestruct IHy1.  subst. \ndestruct IHy2.  subst. decidable. \ndecidable.  decidable.\nspecialize IHy1 with x0_1. \nspecialize IHy2 with x0_2.\ndestruct IHy1.  subst. \ndestruct IHy2.  subst. decidable.\ncrush_equal. decidable.\n*)\nDefined.\nHint Resolve eq_dec_Rule : eq_dec_db. \n(* simply a list of rules. *)\nInductive PrivacyPolicy :=\n| EmptyPolicy : PrivacyPolicy\n| ConsPolicy {d :Description}: \n    Rule d -> \n    PrivacyPolicy -> PrivacyPolicy.\nTheorem eq_dec_PrivacyPolicy : equality PrivacyPolicy.\nintro_equals.\ngeneralize dependent x. \ninduction y; try\ncrush_equal + decidable.\nintros. destruct x; decidable.\nintros. destruct x. decidable. \n specialize IHy with x.\n destruct IHy.  subst. crush_equal.  \n crush_equal.\nDefined.\nHint Resolve eq_dec_PrivacyPolicy : eq_dec_db. \nInductive Action : Set :=\n | ASend : Action\n | AReceive : Action.\nTheorem eq_dec_Action : equality Action. \ncrush_equal. \nDefined.\nHint Resolve eq_dec_Action : eq_dec_db. \n(*A RequestItem is used to compose a list of the items and requirements upon \nthose items in an attestation *)\nInductive RequestItem : Set :=\n | requestItem (d : Description) : (Requirement d) -> RequestItem.\nTheorem eq_dec_RequestItem : equality RequestItem.\nintro_equals.\ngeneralize dependent x.\ninduction y;  intros. destruct x; try crush_equal.\nDefined.\nHint Resolve eq_dec_RequestItem : eq_dec_db.\n \nInductive RequestLS : Set :=\n | emptyRequestLS : RequestLS\n | ConsRequestLS : RequestItem -> RequestLS -> RequestLS.\nTheorem eq_dec_RequestLS : equality RequestLS.\ncrush_equal. \nDefined.\nHint Resolve eq_dec_RequestLS : eq_dec_db.   \n\nInductive Role : Set :=\n | Appraiser\n | Attester.\nTheorem eq_dec_Role : equality Role. \ncrush_equal. \nDefined. \n", "meta": {"author": "paul-kline", "repo": "protosynth", "sha": "1b66397cea554f086cf4bdc95d61bfa269da890a", "save_path": "github-repos/coq/paul-kline-protosynth", "path": "github-repos/coq/paul-kline-protosynth/protosynth-1b66397cea554f086cf4bdc95d61bfa269da890a/ProtoSynthDataTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.2777851463943964}}
{"text": "Require Import Helix.LLVMGen.Correctness_Prelude.\nRequire Import Helix.LLVMGen.Correctness_Invariants.\nRequire Import Helix.LLVMGen.Correctness_NExpr.\nRequire Import Helix.LLVMGen.Correctness_MExpr.\nRequire Import Helix.LLVMGen.Correctness_AExpr.\nRequire Import Helix.LLVMGen.IdLemmas.\nRequire Import Helix.LLVMGen.StateCounters.\nRequire Import Helix.LLVMGen.VariableBinding.\nRequire Import Helix.LLVMGen.BidBound.\nRequire Import Helix.LLVMGen.LidBound.\nRequire Import Helix.LLVMGen.StateCounters.\nRequire Import Helix.LLVMGen.Context.\nRequire Import Helix.LLVMGen.Correctness_While.\n\nImport ProofMode.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nOpaque dropVars.\nOpaque newLocalVar.\nOpaque resolve_PVar.\nOpaque incBlockNamed.\nOpaque incVoid.\nOpaque incLocal.\nOpaque genWhileLoop.\n\nImport ListNotations.\nImport MonadNotation.\nLocal Open Scope monad_scope.\nLocal Open Scope nat_scope.\n\nSection DSHPower_is_tfor.\n\n  Definition DSHPower_tfor_body (σ : evalContext) (f : AExpr) (x y : mem_block) (xoffset yoffset : nat) (acc : mem_block) :=\n    xv <- lift_Derr (mem_lookup_err \"Error reading 'xv' memory in denoteDSHBinOp\" xoffset x) ;;\n    yv <- lift_Derr (mem_lookup_err \"Error reading 'yv' memory in denoteDSHBinOp\" yoffset acc) ;;\n    v' <- denoteBinCType σ f yv xv ;;\n    ret (mem_add yoffset v' acc).\n\n  Definition DSHPower_tfor\n             (σ: evalContext)\n             (n: nat)\n             (f: AExpr)\n             (x y: mem_block)\n             (xoffset yoffset: nat) :\n    itree Event mem_block\n    :=\n      tfor (fun i acc =>\n              DSHPower_tfor_body σ f x y xoffset yoffset acc\n           ) 0 n y.\n\n  Definition DSHPower_interpreted_tfor\n             {E}\n             (σ: evalContext)\n             (n: nat)\n             (f: AExpr)\n             (x y: mem_block)\n             (xoffset yoffset: nat) m\n    : itree E (option (memoryH * mem_block))\n    :=\n      tfor (fun i acc =>\n              match acc with\n              | None => Ret None\n              | Some (m',acc) =>\n                interp_helix (DSHPower_tfor_body σ f x y xoffset yoffset acc) m'\n              end\n           ) 0 n (Some (m, y)).\n\n  Lemma denoteDSHPower_as_tfor :\n    forall (σ: evalContext)\n      (n: nat)\n      (f: AExpr)\n      (x y: mem_block)\n      (xoffset yoffset: nat),\n      denoteDSHPower σ n f x y xoffset yoffset\n                     ≈\n                     DSHPower_tfor σ n f x y xoffset yoffset.\n  Proof.\n    intros σ n; revert σ.\n    induction n; unfold DSHPower_tfor; intros σ f x y xoffset yoffset.\n    - cbn.\n      rewrite tfor_0.\n      reflexivity.\n    - cbn.\n      rewrite tfor_unroll_down; [|lia|].\n      + cbn.\n        unfold mem_lookup_err.\n        repeat setoid_rewrite bind_bind.\n        eapply eutt_clo_bind; [reflexivity|].\n        intros u1 u2 H; subst.\n        eapply eutt_clo_bind; [reflexivity|].\n        intros u0 u3 H0; subst.\n        eapply eutt_clo_bind; [reflexivity|].\n        intros u1 u0 H.\n        rewrite bind_ret_l.\n        unfold DSHPower_tfor in IHn.\n        subst.\n        apply IHn.\n      + intros x0 i j.\n        reflexivity.\n  Qed.\n\n  Lemma DSHPower_as_tfor : forall σ ne x_p xoffset y_p yoffset f initial,\n      denoteDSHOperator σ (DSHPower ne (x_p,xoffset) (y_p,yoffset) f initial)\n                        ≈\n          '(x_i,x_size) <- denotePExpr σ x_p ;;\n          '(y_i,y_size) <- denotePExpr σ y_p ;;\n          lift_Serr (assert_nat_neq \"DSHPower 'x' must not be equal 'y'\" x_i y_i);;\n          x <- trigger (MemLU \"Error looking up 'x' in DSHPower\" x_i) ;;\n          y <- trigger (MemLU \"Error looking up 'y' in DSHPower\" y_i) ;;\n          n <- denoteNExpr σ ne ;; (* [n] denoteuated once at the beginning *)\n          xoff <- denoteNExpr σ xoffset ;;\n          yoff <- denoteNExpr σ yoffset ;;\n          lift_Derr (assert_NT_lt \"DSHPower 'y' offset out of bounds\" yoff y_size) ;;\n          let y' := mem_add (MInt64asNT.to_nat yoff) initial y in\n          y'' <- DSHPower_tfor (protect_p σ y_p) (MInt64asNT.to_nat n) f x y' (MInt64asNT.to_nat xoff) (MInt64asNT.to_nat yoff) ;;\n          trigger (MemSet y_i y'').\n  Proof.\n    intros σ ne x_p xoffset y_p yoffset f initial.\n    unfold denoteDSHOperator.\n    cbn.\n    repeat (eapply eutt_clo_bind_returns; [reflexivity|intros; try break_match_goal; subst]).\n    rewrite denoteDSHPower_as_tfor.\n    reflexivity.\n  Qed.\n\n  Lemma DSHPower_intepreted_as_tfor : forall σ ne x_p xoffset y_p yoffset f initial E m,\n      interp_helix (E := E) (denoteDSHOperator σ (DSHPower ne (x_p,xoffset) (y_p,yoffset) f initial)) m\n                        ≈\n      interp_helix (E := E)\n      ('(x_i,x_size) <- denotePExpr σ x_p ;;\n       '(y_i,y_size) <- denotePExpr σ y_p ;;\n        _ <- lift_Serr (assert_nat_neq \"DSHPower 'x' must not be equal 'y'\" x_i y_i);;\n       x <- trigger (MemLU \"Error looking up 'x' in DSHPower\" x_i) ;;\n       y <- trigger (MemLU \"Error looking up 'y' in DSHPower\" y_i) ;;\n       n <- denoteNExpr σ ne ;; (* [n] denoteuated once at the beginning *)\n       xoff <- denoteNExpr σ xoffset ;;\n       yoff <- denoteNExpr σ yoffset ;;\n       lift_Derr (assert_NT_lt \"DSHPower 'y' offset out of bounds\" yoff y_size) ;;\n       let y' := mem_add (MInt64asNT.to_nat yoff) initial y in\n       y'' <- DSHPower_tfor (protect_p σ y_p) (MInt64asNT.to_nat n) f x y' (MInt64asNT.to_nat xoff) (MInt64asNT.to_nat yoff) ;;\n       trigger (MemSet y_i y'')) m.\n  Proof.\n    intros σ ne x_p xoffset y_p yoffset f initial E m.\n\n    rewrite DSHPower_as_tfor.\n    reflexivity.\n  Qed.\n\n  Definition DSHPower_code (px py xv yv : raw_id) (xtyp xptyp : typ) (x : ident) (src_nexpr : exp typ) (fexpr : exp typ) (fexpcode : code typ) (storeid1 : int) :=\n    ([\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 xv, INSTR_Load false TYPE_Double\n                        (TYPE_Pointer TYPE_Double,\n                         (EXP_Ident (ID_Local px)))\n                        (ret 8%Z));\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      ])%list.\n\n  Definition DSHPower_block body_block_id loopcontblock (px py xv yv : raw_id) (xtyp xptyp : typ) (x : ident) (src_nexpr : exp typ) (fexpr : exp typ) (fexpcode : code typ) (storeid1 : int) : LLVMAst.block typ :=\n    {|\n    blk_id    := body_block_id ;\n    blk_phis  := [];\n    blk_code  := DSHPower_code px py xv yv xtyp xptyp x src_nexpr fexpr fexpcode storeid1;\n    blk_term  := TERM_Br_1 loopcontblock;\n    blk_comments := None\n    |}.\n\n  (* be careful about local_scope_modif *)\n  Lemma DSHPower_body_eutt :\n    forall σ f x y xoffset yoffset acc px py xvid yv xtyp xptyp x_c src_nexpr fexpr fexpcode storeid loopcontblock g li mV mH _label body_entry,\n          eutt\n            (fun x y => True)\n            (interp_helix (DSHPower_tfor_body σ f x y xoffset yoffset acc) mH)\n            (interp_cfg (denote_ocfg (convert_typ [] [(DSHPower_block body_entry loopcontblock px py xvid yv xtyp xptyp x_c src_nexpr fexpr fexpcode storeid)]) (_label, body_entry)) g li mV).\n  Proof.\n    intros σ f x y xoffset yoffset acc px py xvid yv xtyp xptyp x_c src_nexpr fexpr fexpcode storeid\n           loopcontblock g li mV mH _label body_entry.\n    cbn* in *; simp.\n    break_match_goal; simp.\n    - admit.\n    - break_match_goal; simp.\n      + admit.\n      + unfold DSHPower_block. cbn.\n        unfold fmap. unfold Fmap_block.\n        cbn.\n        rewrite denote_ocfg_unfold_in.\n        2: { apply find_block_eq; auto. }\n\n        cbn.\n        rewrite denote_block_unfold.\n        cbn.\n        vstep.\n        hstep.\n        rewrite denote_no_phis.\n        rewrite bind_ret_l.\n        vstep.\n        rewrite denote_code_cons.\n  Admitted.\n\n\nEnd DSHPower_is_tfor.\n\n(* The result is a branch *)\nDefinition branches (to : block_id) (mh : memoryH * ()) (c : config_cfg_T (block_id * block_id + uvalue)) : Prop :=\n  match c with\n  | (m,(l,(g,res))) => exists from, res ≡ inl (from, to)\n  end.\n\nDefinition genIR_post (σ : evalContext) (s1 s2 : IRState) (to : block_id) (li : local_env)\n  : Rel_cfg_T unit ((block_id * block_id) + uvalue) :=\n  lift_Rel_cfg (state_invariant σ s2) ⩕\n               branches to ⩕\n               (fun sthf stvf => local_scope_modif s1 s2 li (fst (snd stvf))).\n\n\n(* TODO: probably want to move this ltac *)\nLtac get_mem_eqs :=\n  cbn in *;\n  repeat match goal with\n         | H: (lift_Rel_cfg (state_invariant ?σ1 ?s3) ⩕ genNExpr_post ?e ?σ2 ?s1 ?s2 ?mh (mk_config_cfg ?mv ?l ?g)) (?mh', ?t) (?mv', (?l', (?g', ()))) |- _\n           => apply genNExpr_memoryV in H\n         end.\n\nLtac solve_mem_eq :=\n  get_mem_eqs; subst;\n  reflexivity.\n\nLtac solve_dtyp_fits_mem_eq :=\n  match goal with\n  | H: dtyp_fits ?m1 ?ptr ?τ\n    |- dtyp_fits ?m2 ?ptr ?τ\n    => let MEM := fresh \"MEM\" in assert (m2 ≡ m1) as MEM by solve_mem_eq; rewrite MEM; assumption\n  end.\n\n(* TODO: expand this. Just trying to figure out this case first *)\nLtac solve_dtyp_fits :=\n  first [ solve_dtyp_fits_mem_eq\n        | eapply dtyp_fits_array_elem; [eauto|eassumption|eauto]\n        ].\n\n\nLemma DSHPower_correct:\n  ∀ (n : NExpr) (src dst : MemRef) (f : AExpr) (initial : binary64) (s1 s2 : IRState) (σ : evalContext) (memH : memoryH) (nextblock bid_in bid_from : block_id) (bks : list (LLVMAst.block typ)) (g : global_env) \n    (l : local_env) (memV : memoryV),\n    genIR (DSHPower n src dst f initial) nextblock s1 ≡ inr (s2, (bid_in, bks))\n    → bid_bound s1 nextblock\n    → state_invariant σ s1 memH (memV, (l, g))\n    → Gamma_safe σ s1 s2\n    → no_failure (E := E_cfg) (interp_helix (denoteDSHOperator σ (DSHPower n src dst f initial)) memH)\n    → eutt (succ_cfg (genIR_post σ s1 s2 nextblock l)) (interp_helix (denoteDSHOperator σ (DSHPower n src dst f initial)) memH) (interp_cfg (denote_ocfg (convert_typ [] bks) (bid_from, bid_in)) g l memV).\nProof.\n  intros n src dst f initial s1 s2 σ memH nextblock bid_in bid_from bks g l memV GEN NEXT PRE GAM NOFAIL.\n\n  pose proof generates_wf_ocfg_bids _ NEXT GEN as WFOCFG.\n  pose proof inputs_bound_between _ _ _ GEN as INPUTS_BETWEEN.\n  pose proof genWhileLoop_entry_in_scope _ _ _ GEN as ENTRY_IN.\n\n  cbn in * |-; simp.\n  rewrite DSHPower_as_tfor; cbn.\n  inv_resolve_PVar Heqs0.\n  inv_resolve_PVar Heqs1.\n  unfold denotePExpr in *.\n  cbn* in *.\n  destruct u.\n  simp; try_abs.\n\n  assert (incLocalNamed \"Power_i\" i21\n                        ≡ inr\n                        ({|\n                            block_count := block_count i21;\n                            local_count := S (local_count i21);\n                            void_count := void_count i21;\n                            Γ := Γ i21 |}, Name (\"Power_i\" @@ string_of_nat (local_count i21)))) as LC_Gen by reflexivity.\n\n  repeat apply no_failure_Ret in NOFAIL.\n  break_match_hyp; try_abs.\n  repeat apply no_failure_Ret in NOFAIL.\n  rename Heqs0 into NO_ALIAS_XY.\n\n  do 2 (apply no_failure_helix_LU in NOFAIL; destruct NOFAIL as (? & NOFAIL & ?); cbn in NOFAIL).\n\n  (* Symbolically reducing the concrete prefix on the Helix side *)\n  hred.\n  rewrite NO_ALIAS_XY.\n  hred.\n  hstep; [eassumption |].\n  hred; hstep; [eassumption |].\n  hred.\n\n  rename l0 into loop_blocks.\n\n  assert (wf_ocfg_bid loop_blocks) as WF_loop_blocks.\n  { eapply wf_ocfg_bid_add_comment; eauto.\n  }\n  assert (free_in_cfg loop_blocks nextblock) as FREE_loop_blocks_nextblock.\n  {\n    rewrite Forall_forall in INPUTS_BETWEEN. intros IN. subst.\n    rewrite inputs_convert_typ, add_comment_inputs in INPUTS_BETWEEN.\n    apply INPUTS_BETWEEN in IN; clear INPUTS_BETWEEN.\n    eapply not_bid_bound_between; eauto.\n  }\n\n  assert (~ (b ≡ bid_in \\/ False)) as BBID_IN. (* easier than writing out all the body blocks *)\n  { (* entry_id (bid_in), is not in the outputs of body_blocks *)\n    intros [CONTRA | []].\n    subst.\n\n    Set Nested Proofs Allowed.\n    eapply genWhileLoop_entry_block in Heqs2.\n    inv Heqs2.\n    Transparent incBlockNamed.\n    inv Heqs.\n    Opaque incBlockNamed.\n  }\n\n  (* body_etry (* b0 *) is in inputs body_blocks *)\n  assert (b0 ≡ b0 ∨ False) as B0B0 by auto.\n  epose proof @genWhileLoop_init' _ _ _ _ _ _ _ _ _ _ _ _ _ bid_from Heqs2 WF_loop_blocks BBID_IN FREE_loop_blocks_nextblock B0B0 as INIT.\n  cbn in INIT.\n  destruct INIT as (body_bks' & GEN' & INIT & WF_BODY_BKS' & FREE_BODY_BKS'_NEXTBLOCK).\n  clear Heqs2.\n\n  (* TODO: use matches to get sb1 / sb2 *)\n  match goal with\n  | H: genWhileLoop ?prefix ?x ?y ?loopvar ?loopcontblock ?body_entry ?body_blocks [] ?nextblock ?s1 ≡ inr (?s2, (?bid_in, ?bks)) |- _\n    => epose proof @genWhileLoop_tfor_correct_nexpr prefix loopvar loopcontblock body_entry body_blocks nextblock bid_in σ {|\n           block_count := block_count i21;\n           local_count := S (local_count i21);\n           void_count := void_count i21;\n           Γ := Γ i21 |} s2 i16 {|\n           block_count := block_count i21;\n           local_count := S (local_count i21);\n           void_count := void_count i21;\n           Γ := Γ i21 |} bks as LOOPTFOR\n  end.\n\n  (* s1 s2 sb1 sb2\n\n     sb1 << sb2\n     local_count sb2 ≡ local_count s1\n\n     What's modified in l_loop and l_AExpr?\n\n   *)\n\n  assert (In b0\n               (inputs\n                  [{| blk_id := b0;\n                      blk_phis := [];\n                      blk_code :=\n                        (IId r2, INSTR_Load false TYPE_Double (TYPE_Pointer TYPE_Double, (EXP_Ident (ID_Local r))) (Some 8%Z))\n                          :: c2 ++\n                          [(IVoid i15,\n                            INSTR_Store false (TYPE_Double, e2)\n                                        (TYPE_Pointer TYPE_Double, (EXP_Ident (ID_Local r))) (Some 8%Z)) : (instr_id * instr typ)];\n                      blk_term := TERM_Br_1 b;\n                      blk_comments := None\n                   |}])) as Inb0 by auto.\n\n  assert (is_correct_prefix \"Power\") as PREF_POWER by solve_prefix.\n\n  assert (lid_bound_between i16 {|\n           block_count := block_count i21;\n           local_count := S (local_count i21);\n           void_count := void_count i21;\n           Γ := Γ i21 |}\n                            (\"Power_i\" @@ string_of_nat (local_count i21))) as LID_BOUND_BETWEEN_POWER_I by solve_lid_bound_between.\n\n  specialize (LOOPTFOR Inb0 PREF_POWER WF_BODY_BKS' LID_BOUND_BETWEEN_POWER_I).\n  specialize (LOOPTFOR FREE_BODY_BKS'_NEXTBLOCK).\n\n  clear LID_BOUND_BETWEEN_POWER_I.\n  assert (lid_bound_between i21 {|\n           block_count := block_count i21;\n           local_count := S (local_count i21);\n           void_count := void_count i21;\n           Γ := Γ i21 |}\n                            (\"Power_i\" @@ string_of_nat (local_count i21))) as LID_BOUND_BETWEEN_POWER_I by solve_lid_bound_between.\n  \n\n  (* Need to know how many times we loop, this is determined by the\n  result of evaluating the expression e1 *)\n  pose proof Heqs7 as LOOP_END.\n\n  (* Clean up LLVM side a bit *)\n  setoid_rewrite add_comment_eutt.\n\n  (* Substitute blocks *)\n  rewrite INIT.\n\n  rename r0 into src_ptr_id.\n  rename r1 into src_val_id.\n  rename r into dst_ptr_id.\n  rename r2 into dst_val_id.\n\n  rename e0 into xoff_exp.\n  rename e1 into yoff_exp.\n  rename e into loop_end_exp.\n  rename c0 into xoff_code.\n  rename c1 into yoff_code.\n  rename c into loop_end_code.\n\n  rename n0 into xoff_nexpr.\n  rename n1 into yoff_nexpr.\n  rename n into loop_end_nexpr.\n\n  rename n4 into dst_addr_h.\n  rename i into dst_size_h.\n  rename n5 into src_addr_h.\n  rename i2 into src_size_h.\n\n  assert (Γ s1 ≡ Γ s2) as Γ_S1S2.\n  { get_gammas.\n    apply dropVars_Γ' in Heqs15.\n    rewrite <- Heqs14 in Heqs15.\n    solve_gamma.\n  }\n\n  (* Need to reorder the nexprs to line things up.\n\n     In helix we evaluate:\n\n     1) loop_end\n     2) xoff\n     3) yoff\n\n     In LLVM the loop_end is calculated last:\n\n     1) xoff\n     2) yoff\n     3) loop_end\n\n     I should be able to commute loop_end_code in order to match it up\n     with denoteNExpr σ loop_end_nexpr.\n   *)\n\n  repeat rewrite convert_typ_code_app.\n  repeat setoid_rewrite denote_code_app.\n\n  vstep.\n  vred.\n\n  (* loop_end *)\n  eapply eutt_clo_bind_returns.\n  { eapply genNExpr_correct; [eauto|solve_state_invariant|solve_gamma_safe|eauto].\n  }\n\n  intros [[m_loopend t_loopend] |] [mV_loopend [l_loopend [g_loopend []]]] PostLoopEnd RetLoopNExp RetLoopCode; [|inversion PostLoopEnd].\n  destruct PostLoopEnd as [PostLoopEndSINV PostLoopEndNExpr]. cbn in PostLoopEndSINV.\n  pose proof (Correctness_NExpr.is_almost_pure PostLoopEndNExpr) as [MHPURE [MVPURE GPURE]]; subst.\n  vred; hred; vred.\n\n  pose proof NOFAIL as NOFAIL_loopend.\n  eapply no_failure_helix_bind_prefix in NOFAIL_loopend.\n  eapply no_failure_helix_bind_continuation in NOFAIL; [eauto|eassumption].  \n\n  pose proof NOFAIL as NOFAIL_xoff.\n  eapply no_failure_helix_bind_prefix in NOFAIL_xoff.\n\n  (* xoff *)\n   eapply eutt_clo_bind_returns.\n  { eapply genNExpr_correct; [eauto|solve_state_invariant|solve_gamma_safe|eauto].\n  }\n\n  intros [[m_xoff xoff_res] |] [mV_xoff [l_xoff [g_xoff []]]] PostXoff RetXoffNExp RetXoffCode; [|inversion PostXoff].\n  destruct PostXoff as [PostXoffSINV PostXoffNExpr]. cbn in PostXoffSINV.\n  pose proof (Correctness_NExpr.is_almost_pure PostXoffNExpr) as [MHPURE [MVPURE GPURE]]; subst.\n  vred; hred; vred.\n\n  eapply no_failure_helix_bind_continuation in NOFAIL; [eauto|eassumption].\n  pose proof NOFAIL as NOFAIL_yoff.\n  eapply no_failure_helix_bind_prefix in NOFAIL_yoff.\n\n  (* yoff *)\n  eapply eutt_clo_bind_returns.\n  { eapply genNExpr_correct; [eauto|solve_state_invariant|solve_gamma_safe|eauto].\n  }\n\n  intros [[m_yoff yoff_res] |] [mV_yoff [l_yoff [g_yoff []]]] PostYoff RetYoffNExp RetYoffCode; [|inversion PostYoff].\n  destruct PostYoff as [PostYoffSINV PostYoffNExpr]. cbn in PostYoffSINV.\n  pose proof (Correctness_NExpr.is_almost_pure PostYoffNExpr) as [MHPURE [MVPURE GPURE]]; subst.\n\n  Ltac nexpr_modifs :=\n    repeat\n      match goal with\n      | POST : genNExpr_post _ _ _ _ _ _ _ _ |- _\n        => eapply Correctness_NExpr.extends in POST; cbn in POST\n      end.\n\n  assert (local_scope_modif i5 i7 l l_xoff /\\ local_scope_modif i5 i8 l l_yoff) as [LSM_xoff LSM_yoff].\n  {\n    nexpr_modifs.\n    epose proof local_scope_modif_trans'' PostLoopEndNExpr PostXoffNExpr as LSM_xoff.\n    repeat (forward LSM_xoff; solve_local_count).\n    epose proof local_scope_modif_trans'' LSM_xoff PostYoffNExpr as LSM_yoff.\n    repeat (forward LSM_yoff; solve_local_count).\n    auto.\n  }\n\n  assert (WF_IRState σ i5) as WFi5.\n  { eapply WF_IRState_Γ; eauto.\n    solve_gamma.\n  }\n\n  assert (gamma_bound i5) as GBi5.\n  { eapply gamma_bound_mono.\n    { eapply st_gamma_bound in PRE. apply PRE. }\n    solve_local_count.\n    solve_gamma.\n  }\n\n\n  hred.\n\n  eapply no_failure_helix_bind_continuation in NOFAIL; [eauto|eassumption].\n  pose proof NOFAIL as NOFAIL_Assert.\n  eapply no_failure_helix_bind_prefix in NOFAIL_Assert.\n\n  (* TODO: I feel like I should be able to automate all of this no failure stuff. *)\n  break_match_goal.\n  { exfalso; eapply failure_helix_throw; eassumption. }\n  rewrite bind_ret_l in NOFAIL.\n\n  hred.\n\n  match goal with\n  | H: assert_NT_lt _ _ _ ≡ inr _ |- _\n    =>\n    unfold assert_NT_lt, assert_true_to_err in H;\n      break_if; inv H\n  end.\n\n  match goal with\n  | H: (_ <? _) ≡ true |- _\n    => rename H into LT_yoff\n  end.\n\n  (* Need to figure out the corresponding pointer for id (i3).\n\n     Need to get this from the memory_invariant *)\n\n  pose proof state_invariant_memory_invariant PRE as MINV_YOFF.\n  pose proof state_invariant_memory_invariant PRE as MINV_XOFF.\n  unfold memory_invariant in MINV_YOFF.\n  unfold memory_invariant in MINV_XOFF.\n  specialize (MINV_YOFF n3 _ _ _ _ Heqo0 LUn0).\n  specialize (MINV_XOFF n2 _ _ _ _ Heqo LUn).\n  cbn in MINV_YOFF, MINV_XOFF.\n\n  destruct MINV_YOFF as (ptrll_yoff & τ_yoff & TEQ_yoff & FITS_yoff & INLG_yoff & MLUP_yoff).\n  specialize (MLUP_yoff eq_refl) as (bkh_yoff & MLUP_yoff & GETARRAYCELL_yoff).\n\n  destruct MINV_XOFF as (ptrll_xoff & τ_xoff & TEQ_xoff & FITS_xoff & INLG_xoff & MLUP_xoff).\n  specialize (MLUP_xoff eq_refl) as (bkh_xoff & MLUP_xoff & GETARRAYCELL_xoff).\n\n  rewrite MLUP_xoff in H; symmetry in H; inv H.\n  rewrite MLUP_yoff in H0; symmetry in H0; inv H0.\n\n  inv TEQ_yoff. inv TEQ_xoff. cbn. vred.\n\n  edestruct denote_instr_gep_array_no_read with (m:=mV_yoff) (g:=g_yoff) (l:=l_yoff) (size:=(Z.to_N (Int64.intval i1))) (τ:=DTYPE_Double) (i:=src_ptr_id) (ptr := @EXP_Ident dtyp i0) (a:= ptrll_xoff) (e_ix:=convert_typ [] xoff_exp) (ix:=(MInt64asNT.to_nat xoff_res)).\n\n  { destruct i0.\n    { rewrite denote_exp_GR.\n      change (UVALUE_Addr ptrll_xoff) with (dvalue_to_uvalue (DVALUE_Addr ptrll_xoff)).\n      reflexivity.\n      auto.\n    }\n    { assert (lid_bound s1 id) as LID_BOUND0 by (eapply st_gamma_bound; solve_lid_bound).\n      rewrite denote_exp_LR.\n      change (UVALUE_Addr ptrll_yoff) with (dvalue_to_uvalue (DVALUE_Addr ptrll_yoff)).\n      reflexivity.\n      cbn.\n\n      nexpr_modifs.\n      Ltac solve_alist_in_yoff upper :=\n        erewrite <- local_scope_modif_bound_before with (s2:=upper); eauto;\n        repeat (eapply local_scope_modif_add'; [solve_lid_bound_between|]);\n        match goal with\n        | LSM1 : local_scope_modif ?s1 ?s2 _ ?l2,\n          LSM2 : local_scope_modif ?s12 ?s22 ?l1 _\n          |- local_scope_modif _ _ ?l1 ?l2\n          => eapply (@local_scope_modif_shrink _ s12 s2); [solve_local_scope_modif| |]; solve_local_count\n        end.\n\n\n      solve_alist_in_yoff s2.\n    }\n  }\n\n  { apply Correctness_NExpr.exp_correct in PostXoffNExpr.\n    cbn in PostXoffNExpr.\n    rewrite repr_of_nat_to_nat.\n    destruct PostYoffNExpr.\n\n    eapply PostXoffNExpr; [solve_local_scope_preserved | solve_gamma_preserved].\n  }\n\n  { typ_to_dtyp_simplify.\n    erewrite <- from_N_intval; eauto.\n  }\n\n  rename x into src_addr.\n  destruct H as [HSRC_GEP HSRC_GEP_EUTT].\n  cbn.\n\n  replace (match i0 with | ID_Global rid => ID_Global rid | ID_Local lid => ID_Local lid end) with (i0) by (destruct i0; auto).\n\n  rewrite HSRC_GEP_EUTT.\n\n  vred; hred; vred.\n\n  edestruct denote_instr_gep_array_no_read with (m:=mV_yoff) (g:=g_yoff) (l:=(alist_add src_ptr_id (UVALUE_Addr src_addr) l_yoff)) (size:=(Z.to_N (Int64.intval i4))) (τ:=DTYPE_Double) (i:=dst_ptr_id) (ptr := @EXP_Ident dtyp i3) (a:= ptrll_yoff) (e_ix:=fmap (typ_to_dtyp []) yoff_exp) (ix:=(MInt64asNT.to_nat yoff_res)).\n  { destruct i3 as [id | id].\n    { rewrite denote_exp_GR.\n      change (UVALUE_Addr ptrll_yoff) with (dvalue_to_uvalue (DVALUE_Addr ptrll_yoff)).\n      reflexivity.\n      auto.\n    }\n    { assert (lid_bound s1 id) as LID_BOUND0 by (eapply st_gamma_bound; solve_lid_bound).\n      rewrite denote_exp_LR.\n      change (UVALUE_Addr ptrll_yoff) with (dvalue_to_uvalue (DVALUE_Addr ptrll_yoff)).\n      reflexivity.\n      cbn.\n\n      nexpr_modifs.\n      solve_alist_in_yoff s2.\n    }\n  }\n\n  { apply Correctness_NExpr.exp_correct in PostYoffNExpr.\n    cbn in PostYoffNExpr.\n    rewrite repr_of_nat_to_nat.\n\n    eapply PostYoffNExpr; [solve_local_scope_preserved | solve_gamma_preserved].\n  }\n\n\n  { typ_to_dtyp_simplify.\n    erewrite <- from_N_intval; eauto.\n  }\n\n  rename x into dst_addr.\n  destruct H as [HDST_GEP HDST_GEP_EUTT].\n  cbn.\n\n  replace (match i3 with | ID_Global rid => ID_Global rid | ID_Local lid => ID_Local lid end) with (i3) by (destruct i3; auto).\n\n  rewrite HDST_GEP_EUTT.\n\n  vred; hred; vred.\n\n  (* Store for the initial value *)\n  edestruct denote_instr_store_exists with (a := dst_addr) (m:=mV_yoff).\n\n  { cbn.\n    apply denote_exp_double.\n  }\n\n  { apply denote_exp_LR.\n    apply alist_find_add_eq.\n  }\n\n  { reflexivity.\n  }\n\n  { constructor.\n  }\n\n  { typ_to_dtyp_simplify.\n    epose proof (vellvm_helix_ptr_size _ LUn0 Heqo0 PRE); subst.\n\n    pose proof (from_N_intval _ EQsz0) as EQ.\n    apply Znat.Z2N.inj in EQ; [|apply Int64_intval_pos|apply Int64_intval_pos].\n\n    rewrite <- EQ in *.\n    eapply dtyp_fits_array_elem; [eapply FITS_yoff|..]; eauto.\n\n    rewrite Znat.Z2N.id; [|apply Int64_intval_pos].\n    apply NPeano.Nat.ltb_lt in LT_yoff.\n    pose proof Znat.inj_lt _ _ LT_yoff as LT.\n    unfold MInt64asNT.to_nat in LT.\n    rewrite Znat.Z2Nat.id in LT; [|apply Int64_intval_pos].\n    rewrite Znat.Z2Nat.id in LT; [|apply Int64_intval_pos].\n\n    rewrite repr_of_nat_to_nat.\n    apply LT.\n  }\n\n  rename x into mV_init.\n  destruct H as [WRITE_INIT STORE_INIT].\n  cbn in STORE_INIT.\n  cbn.\n  rewrite STORE_INIT.\n\n  vred.\n\n  cbn in PostLoopEndNExpr.\n  pose proof Correctness_NExpr.exp_correct PostLoopEndNExpr as PostLoopEndNExprCorrect.\n  cbn in PostLoopEndNExprCorrect.\n\n  epose proof (denote_exp_i64 t_loopend) as T_LOOPEND_EUTT.\n  assert (eutt Logic.eq (interp_cfg (translate exp_to_instr (denote_exp (Some (DTYPE_I (Npos 64))) (EXP_Integer (Integers.Int64.intval t_loopend)))) g_yoff l_loopend mV_yoff)\n               (interp_cfg\n                  (translate exp_to_instr\n                             (denote_exp (Some (DTYPE_I (Npos 64)))\n                                         (convert_typ [] loop_end_exp))) g_yoff l_loopend mV_yoff)) as EUTT_INT.\n  rewrite T_LOOPEND_EUTT.\n  rewrite PostLoopEndNExprCorrect.\n  reflexivity.\n\n  solve_local_scope_preserved.\n  solve_gamma_preserved.\n\n  specialize (LOOPTFOR loop_end_nexpr i5 i6 m_yoff m_yoff loop_end_exp loop_end_code WFi5 GBi5 Heqs3).\n  repeat (forward LOOPTFOR; [solve_local_count|]).\n  specialize (LOOPTFOR t_loopend RetLoopNExp).\n\n  forward LOOPTFOR. eauto.\n\n  (* TODO: may be able to separate this out into the DSHPower_body_eutt lemma *)\n  unfold DSHPower_tfor.\n  rewrite interp_helix_tfor; [|lia].\n\n  match goal with\n    |- eutt _ (ITree.bind' _ (tfor ?bod _ _ _)) _ => specialize (LOOPTFOR _ bod)\n  end.\n\n  (* Will need to set up loop invariants and such, just like loop case *)\n  (* Invariant at each iteration *)\n\n  set (I := (fun (k : nat) (mH : option (memoryH * mem_block)) (stV : memoryV * (local_env * global_env)) =>\n               match mH with\n               | None => False\n               | Some (mH,mb) =>\n                 match stV with\n                 | (mV, (l, g)) =>\n                   state_invariant (protect σ n3) s2 mH stV /\\\n                   alist_find dst_ptr_id l ≡ Some (UVALUE_Addr dst_addr) /\\\n                   alist_find src_ptr_id l ≡ Some (UVALUE_Addr src_addr) /\\\n                   local_scope_modif i16 s2 (alist_add dst_ptr_id (UVALUE_Addr dst_addr) (alist_add src_ptr_id (UVALUE_Addr src_addr) l_yoff)) l /\\\n                   g ≡ g_yoff /\\\n                   allocated ptrll_yoff mV /\\\n                   (* Not sure if this is the right block *)\n                   Returns (Some (mH, mb))\n                           (@interp_helix _ E_cfg (tfor\n                                                     (λ (_ : nat) (acc : mem_block),\n                                                      DSHPower_tfor_body (protect σ n3) f bkh_xoff\n                                                                         (mem_add (MInt64asNT.to_nat yoff_res) initial bkh_yoff)\n                                                                         (MInt64asNT.to_nat xoff_res) (MInt64asNT.to_nat yoff_res) acc) 0 k\n                                                     (mem_add (MInt64asNT.to_nat yoff_res) initial bkh_yoff)) m_yoff) /\\\n                   (forall y, y ≢ (MInt64asNT.to_nat yoff_res) -> mem_lookup y mb ≡ mem_lookup y bkh_yoff) /\\\n                   exists v, mem_lookup (MInt64asNT.to_nat yoff_res) mb ≡ Some v /\\\n                        ext_memory mV_init dst_addr DTYPE_Double (UVALUE_Double v) mV\n                 end\n               end)).\n\n  (* Precondition *)\n  set (P := (fun (mH : option (memoryH * mem_block)) (stV : memoryV * (local_env * global_env)) =>\n               match mH with\n               | None => False\n               | Some (mH,mb) =>\n                 match stV with\n                 | (mV, (l, g)) =>\n                   state_invariant (protect σ n3) s2 mH stV /\\\n                   alist_find dst_ptr_id l ≡ Some (UVALUE_Addr dst_addr) /\\\n                   alist_find src_ptr_id l ≡ Some (UVALUE_Addr src_addr) /\\\n                   local_scope_modif i16 s2 (alist_add dst_ptr_id (UVALUE_Addr dst_addr) (alist_add src_ptr_id (UVALUE_Addr src_addr) l_yoff)) l /\\\n                   g ≡ g_yoff /\\\n                   mH ≡ m_yoff /\\\n                   mb ≡ mem_add (MInt64asNT.to_nat yoff_res) initial bkh_yoff /\\\n                   mV ≡ mV_init\n                 end\n               end)).\n\n  (* Postcondition *)\n  set (Q := (fun (mH : option (memoryH * mem_block)) (stV : memoryV * (local_env * global_env)) =>\n               match mH with\n               | None => False\n               | Some (mH,mb) => state_invariant σ s2 (memory_set mH dst_addr_h mb) stV\n               end)).\n\n  specialize (LOOPTFOR I P Q (Some (m_yoff, mem_add (MInt64asNT.to_nat yoff_res) initial bkh_yoff))).\n\n  (* Relating iterations of the bodies *)\n  forward LOOPTFOR.\n  { intros g_loop l_loop mV_loop [[mH_loop mb_loop] |] k _label [HI [POWERI [LOOPEND_EXPID [BOUND RETURNS]]]]; [|inv HI].\n    cbn in HI.\n    destruct HI as [LINV_SINV [LINV_DST_PTR_ID [LINV_SRC_PTR_ID [LINV_LSM [LINV_GLOBALS [LINV_ALLOC [LINV_RET [LINV_HELIX_MB_OLD [v [LINV_HELIX_MB_NEW LINV_MEXT]]]]]]]]]].\n    pose proof LINV_MEXT as [LINV_MEXT_NEW LINV_MEXT_OLD].\n    unfold DSHPower_tfor_body.\n    \n    unfold mem_lookup_err.\n    unfold trywith.\n\n    rewrite denoteDSHPower_as_tfor in NOFAIL.\n    unfold DSHPower_tfor in NOFAIL.\n\n    eapply no_failure_helix_bind_prefix in NOFAIL.\n    rewrite interp_helix_tfor in NOFAIL; [|lia].\n    eapply no_failure_tfor with (k0:=k) in NOFAIL; [|lia|eauto].\n    cbn in NOFAIL.\n\n    break_match_goal.\n    2: { unfold mem_lookup_err in *.\n         rewrite Heqo1 in NOFAIL.\n         cbn in NOFAIL.\n         eapply no_failure_bind_prefix in NOFAIL.\n         eapply no_failure_helix_bind_prefix in NOFAIL.\n         eapply failure_helix_throw in NOFAIL.\n         inv NOFAIL.\n    }\n    rename Heqo1 into MEMLUP_xoff.\n\n    unfold mem_lookup_err in NOFAIL.\n    rewrite MEMLUP_xoff in NOFAIL.\n\n\n    rewrite LINV_HELIX_MB_NEW in NOFAIL.\n    cbn in NOFAIL.\n    repeat rewrite bind_ret_l in NOFAIL.\n    rewrite LINV_HELIX_MB_NEW.\n    cbn.\n    repeat rewrite bind_ret_l.\n\n    rewrite denote_ocfg_unfold_in.\n    2: {\n      apply find_block_eq; auto.\n    }\n\n    cbn; vred.\n\n    rewrite denote_no_phis.\n    vred; cbn.\n\n    rewrite denote_code_cons.\n    vred.\n\n    pose proof (write_correct WRITE_INIT) as [WRITE_ALLOCATED WRITE_WRITTEN].\n    specialize (WRITE_WRITTEN DTYPE_Double).\n    forward WRITE_WRITTEN; [constructor|].\n    destruct WRITE_WRITTEN as [MEXT_INIT_NEW MEXT_INIT_OLD].\n\n    assert (allocated ptrll_xoff mV_yoff) as PTRLL_XOFF_ALLOCATED_mV_yoff by solve_allocated.\n    assert (allocated src_addr mV_yoff) as SRC_ALLOCATED_mV_yoff by solve_allocated.\n\n    assert (no_overlap_dtyp dst_addr DTYPE_Double src_addr DTYPE_Double) as NOALIAS.\n    { pose proof NO_ALIAS_XY.\n      clear NO_ALIAS_XY.\n      rename H into NO_ALIAS_XY.\n      unfold assert_nat_neq in NO_ALIAS_XY.\n\n      destruct (src_addr_h =? dst_addr_h) eqn:EQ.\n      - inv NO_ALIAS_XY.\n      - apply beq_nat_false in EQ.\n        destruct PRE.\n\n        (* TODO: should this be a lemma? *)\n        assert (i0 ≢ i3) as ID_NEQ.\n        { intros CONTRA.\n          rewrite CONTRA in LUn.\n          epose proof (st_no_id_aliasing _ _ _ _ _ _ _ Heqo Heqo0 LUn LUn0).\n          subst.\n\n          rewrite Heqo0 in Heqo.\n          inv Heqo.\n          contradiction.\n        }\n\n        unfold no_overlap_dtyp.\n        unfold no_overlap.\n        left.\n\n        rewrite <- (handle_gep_addr_array_same_block _ _ _ _ HDST_GEP).\n        rewrite <- (handle_gep_addr_array_same_block _ _ _ _ HSRC_GEP).\n        intros BLOCKS; symmetry in BLOCKS; revert BLOCKS.\n\n        cbn in st_no_llvm_ptr_aliasing.\n        eapply st_no_llvm_ptr_aliasing.\n        5: eauto.\n        3-4: eauto.\n        all: eauto.\n    }\n\n    (* Load src *)\n    rewrite denote_instr_load.\n    2: {\n      apply denote_exp_LR.\n\n      cbn.\n      eauto.\n    }\n    2: {\n      erewrite LINV_MEXT_OLD; eauto; [|solve_allocated].\n      erewrite MEXT_INIT_OLD; eauto.\n\n      solve_read.\n    }\n\n    vred.\n    rewrite map_app.\n    cbn.\n    typ_to_dtyp_simplify.\n    rewrite denote_code_cons.\n    vred; hred.\n\n    (* Load dst *)\n    rewrite denote_instr_load; [|apply denote_exp_LR; cbn; solve_alist_in|solve_read].\n\n    cbn.\n    vred.\n\n    rewrite denote_code_app.\n    vred.\n    rewrite bind_bind.\n\n    change (map (λ '(id1, i), (Endo_instr_id id1, Fmap_instr typ dtyp (typ_to_dtyp []) i)) c2) with (convert_typ [] c2).\n\n    eapply eutt_clo_bind_returns.\n    {\n      eapply genAExpr_correct.\n      eauto.\n      { eapply state_invariant_enter_scope_DSHCType' with (s1:={| block_count := block_count i19; local_count := local_count i19; void_count := void_count i19; Γ := (ID_Local dst_val_id, TYPE_Double) :: Γ i19 |}); cbn; eauto.\n\n        eapply lid_bound_before; [solve_lid_bound | solve_local_count].\n        2: solve_alist_in.\n\n        { pose proof GAM.\n          unfold Gamma_safe in H.\n          assert (~ in_Gamma σ s1 src_val_id) by solve_not_in_gamma.\n          assert (Γ s1 ≡ Γ i19) by solve_gamma.\n\n          eapply not_in_gamma_cons; [cbn; eauto; try solve_gamma | solve_not_in_gamma |].\n\n          (* TODO: add this to solve_not_in_gamma? *)\n          intros CONTRA; subst.\n\n          match goal with\n          | H1: incLocal _ ≡ inr (_, dst_val_id),\n                H2: incLocal _ ≡ inr (_, dst_val_id) |- _\n            => eapply lid_bound_between_incLocal in H1;\n                eapply lid_bound_between_incLocal in H2;\n                eapply state_bound_between_id_separate;[|eapply H1|eapply H2|solve_local_count];\n                  eapply incLocalNamed_count_gen_injective\n          end.\n        }\n\n        eapply state_invariant_enter_scope_DSHCType'; cbn.\n        eauto.\n        eauto.\n        3: solve_local_count.\n        \n        eapply lid_bound_before; [solve_lid_bound | solve_local_count].\n        eapply not_in_Gamma_Gamma_eq with (s1 := s1); [solve_gamma|solve_not_in_gamma].\n\n        { solve_alist_in.\n        }\n\n        eapply state_invariant_same_Γ' with (s1:=s2); eauto.\n        solve_gamma.\n        { get_gamma_bounds.\n          assert (Γ i8 ≡ Γ i19) by solve_gamma.\n          eapply gamma_bound_mono.\n          apply PostYoffSINV.\n          solve_local_count.\n          eauto.\n        }\n\n        { eapply not_in_Gamma_Gamma_eq; eauto.\n          eapply not_in_gamma_protect.\n          eapply GAM.\n          solve_lid_bound_between.\n        }\n\n        eapply state_invariant_same_Γ with (s1:=s2); eauto.\n        { eapply not_in_Gamma_Gamma_eq; eauto.\n          eapply not_in_gamma_protect.\n          eapply GAM.\n          solve_lid_bound_between.\n        }\n        \n      }\n\n      { eapply Gamma_safe_Context_extend.\n        eapply Gamma_safe_Context_extend.\n        9: { cbn.\n             change ((ID_Local dst_val_id, TYPE_Double) :: Γ i19) with (Γ {| block_count := block_count i19; local_count := local_count i19; void_count := void_count i19; Γ := (ID_Local dst_val_id, TYPE_Double) :: Γ i19 |}).\n             reflexivity.\n        }\n        4: {\n          cbn.\n          reflexivity.\n        }\n\n        { eapply Gamma_safe_protect.\n          eapply Gamma_safe_shrink; eauto.\n          solve_gamma.\n          solve_local_count.\n        }\n        3: {\n          instantiate (1 := {| block_count := block_count i20; local_count := local_count i20; void_count := void_count i20; Γ := (ID_Local dst_val_id, TYPE_Double) :: Γ i19 |}).\n          cbn.\n          solve_gamma.\n        }\n\n        all: try (solve [cbn; solve_local_count]).\n\n        { intros ? ?.\n          solve_id_neq.\n        }\n\n        cbn.\n        solve_gamma.\n\n        { intros ? ?.\n          solve_id_neq.\n        }\n      }\n\n      { unfold denoteBinCType in NOFAIL.\n        eapply no_failure_bind_prefix in NOFAIL.\n        eapply no_failure_helix_bind_prefix in NOFAIL.\n        eauto.\n      }\n    }\n\n    intros [[mH_Aexpr t_Aexpr]|] [mV_Aexpr [l_Aexpr [g_Aexpr []]]] POST RetAexp RetAexpCode; [|inv POST].\n    destruct POST as [POSTAEXPRSINV POSTAEXPR].\n\n    hred.\n    vred.\n\n    forward LINV_MEXT_NEW; [cbn; lia|].\n    edestruct (@read_write_succeeds mV_loop dst_addr _ _ (DVALUE_Double t_Aexpr) LINV_MEXT_NEW) as [mV' WRITE]; [constructor|].\n\n    erewrite denote_instr_store; eauto.\n\n    2: {\n      destruct POSTAEXPR.\n      cbn in exp_correct.\n      cbn in POSTAEXPRSINV.\n      eapply exp_correct.\n      solve_local_scope_preserved.\n      solve_gamma_preserved.\n    }\n    3: {\n      cbn. reflexivity.\n    }\n    3: {\n      destruct POSTAEXPR; cbn in is_almost_pure.\n      assert (mV_Aexpr ≡ mV_loop) by intuition; subst.\n      apply WRITE.\n    }\n    2: {\n      eapply denote_exp_LR.\n      destruct POSTAEXPR.\n\n      cbn in extends.\n      cbn.\n\n      erewrite local_scope_modif_out.\n      4: eapply extends.\n      3: solve_lid_bound_between; cbn; solve_local_count.\n      2: cbn; solve_local_count.\n\n      solve_alist_in.\n    }\n\n    vred.\n    rewrite denote_term_br_1.\n    vred.\n\n    cbn.\n    rename b into jump_label.\n    rewrite denote_ocfg_unfold_not_in.\n    vred.\n    2: {\n      cbn.\n      assert (b0 ≢ jump_label) as NEQ by solve_id_neq.\n      rewrite find_block_ineq; eauto.\n    }\n\n    apply eqit_Ret.\n    split; [|split; [|split]].\n    - destruct POSTAEXPR.\n      cbn in *.\n      destruct Mono_IRState.\n      + eapply local_scope_preserve_modif_up in extends.\n        unfold local_scope_preserved in extends.\n        rewrite extends.\n        rewrite alist_find_neq.\n        2: { intros ID; symmetry in ID; revert ID.\n             eapply state_bound_between_separate.\n             eapply incLocalNamed_count_gen_injective.\n             solve_lid_bound_between.\n             solve_lid_bound_between.\n             solve_local_count.\n        }\n        2: { unfold lid_bound_between.\n             unfold state_bound_between.\n             exists \"Power_i\". eexists. eexists.\n             repeat split; eauto.\n             2: solve_local_count.\n             instantiate (1 := {|\n                             block_count := block_count i21;\n                             local_count := S (local_count i21);\n                             void_count := void_count i21;\n                             Γ := Γ i21 |}).\n             solve_local_count.\n        }\n        solve_alist_in.\n      + subst.\n        (* Brutally long *)\n        solve_alist_in.\n    - exists b0. reflexivity.\n    - (* I *)\n      Opaque mem_lookup. (* TODO: HMMM *)\n      cbn.\n      split.\n      { (* TODO: destruct POSTAEXPR in like one place? Maybe\n               automate pulling out almost_pure? *)\n        pose proof POSTAEXPR as PUREAEXPR.\n        apply is_almost_pure in PUREAEXPR.\n        cbn in PUREAEXPR. destruct PUREAEXPR as [? [? ?]].\n        subst.\n        eauto.\n\n        pose proof POSTAEXPR as AEXPR_LSM.\n        eapply extends in AEXPR_LSM.\n        cbn in AEXPR_LSM.\n\n        destruct POSTAEXPR.\n        cbn in POSTAEXPRSINV.\n\n        destruct POSTAEXPRSINV.\n        cbn in st_no_llvm_ptr_aliasing.\n\n        destruct LINV_SINV.\n        eauto.\n\n        split; auto.\n        (* TODO: can I pull these out into lemmas? *)\n        (* TODO: probably similar to state_invariant_escape_scope, but with a write *)\n        (* TODO: might want to not destruct and look at the state_invariant_write_double stuff? *)\n        - cbn in extends.\n          unfold memory_invariant.\n          pose proof mem_is_inv as MINV.\n          unfold memory_invariant in MINV.\n          intros n v0 b τ x NTH_σ NTH_Γ.\n\n          pose proof NTH_σ as NTH_σ_orig.\n          pose proof NTH_Γ as NTH_Γ_orig.\n          do 2 erewrite <- nth_error_Sn in NTH_σ.\n          do 2 erewrite <- nth_error_Sn in NTH_Γ.\n\n          pose proof Heqo0 as NTH_σ_dst.\n          apply nth_error_protect_eq' in NTH_σ_dst.\n          do 2 erewrite <- nth_error_Sn in NTH_σ_dst.\n\n          cbn in Gamma_cst.\n          assert (Γ s2 ≡ Γ i19) as Γ_s2i19 by solve_gamma.\n\n          pose proof LUn0 as NTH_Γ_dst.\n          do 2 erewrite <- nth_error_Sn in NTH_Γ_dst.\n          rewrite Γ_S1S2 in NTH_Γ_dst.\n          rewrite Γ_s2i19 in NTH_Γ_dst.\n          rewrite <- Gamma_cst in NTH_Γ_dst.\n\n          rewrite Γ_s2i19 in NTH_Γ.\n          rewrite <- Gamma_cst in NTH_Γ.\n\n          specialize (MINV _ _ _ _ _ NTH_σ NTH_Γ).\n\n          (* TODO: automate this? *)\n          assert (local_scope_modif s1 s2 l l_Aexpr) as LSM_FULL.\n          { nexpr_modifs.\n            Ltac solve_single_trans_local_scope_modif :=\n              match goal with\n              | L1 : local_scope_modif ?s1 ?s2 ?l1 ?l2,\n                     L2 : local_scope_modif ?s2 ?s3 ?l2 ?l3\n                |- local_scope_modif ?s1 ?s3 ?l1 ?l3\n                => eapply (local_scope_modif_trans'' L1 L2); solve_local_count\n              end.\n            Hint Extern 1 (local_scope_modif _ _ _ _) => solve_single_trans_local_scope_modif : LSM.\n\n            pose proof LINV_LSM as LSM'.\n            eapply local_scope_modif_shrink with (s1 := i8) (s4:= s2) in LSM'; solve_local_count.\n            eapply local_scope_modif_sub'_l in LSM'; [|solve_lid_bound_between].\n            eapply local_scope_modif_sub'_l in LSM'; [|solve_lid_bound_between].\n            epose proof local_scope_modif_trans'' LSM_yoff LSM'.\n            repeat (forward H; solve_local_count).\n            pose proof extends.\n            eapply local_scope_modif_shrink with (s1 := i8) (s4:= s2) in H0; solve_local_count.\n            eapply local_scope_modif_sub'_l in H0; [|solve_lid_bound_between].\n            eapply local_scope_modif_sub'_l in H0; [|solve_lid_bound_between].\n            epose proof local_scope_modif_trans'' H H0.\n            repeat (forward H4; solve_local_count).\n            solve_local_scope_modif.\n          }\n\n          destruct x, v0; eauto.\n          + cbn in MINV. cbn.\n            destruct MINV as (ptr & τ' & TEQ & FIND & READ).\n            exists ptr. exists τ'.\n            repeat split; eauto.\n\n            pose proof (IRState_is_WF _ _ _ NTH_σ) as (id' & NTH_Γ').\n            (* id can not be id_addr because of the different\n                     type, and thus must be in a different block *)\n\n            (* Find τ' *)\n            rewrite NTH_Γ in NTH_Γ'; inv NTH_Γ'.\n            cbn in H1. inv H1.\n\n            eapply write_different_blocks; eauto.\n            2: reflexivity.\n            2-3: typ_to_dtyp_simplify; constructor.\n\n            rewrite <- (handle_gep_addr_array_same_block _ _ _ _ HDST_GEP); eauto.\n\n            intros EQ; symmetry in EQ; revert EQ.\n            eapply st_no_llvm_ptr_aliasing.\n            eapply NTH_σ.\n            { do 2 rewrite nth_error_Sn.\n              apply (nth_error_protect_eq' n3 _ Heqo0).\n            }\n            eapply NTH_Γ.\n            rewrite Gamma_cst.\n            do 2 rewrite nth_error_Sn.\n            rewrite <- Γ_s2i19. rewrite <- Γ_S1S2.\n            eauto.\n            { intros CONTRA; inv CONTRA.\n              epose proof (st_no_id_aliasing _ _ _ _ _ _ _ NTH_σ NTH_σ_dst NTH_Γ NTH_Γ_dst) as EQ; inv EQ.\n\n              rewrite NTH_Γ in NTH_Γ_dst; inv NTH_Γ_dst.\n            }\n            eauto.\n            { destruct i3.\n              - eauto.\n              - assert (lid_bound s1 id0) as LID_BOUND0 by (eapply Correctness_Invariants.st_gamma_bound; solve_lid_bound).\n                cbn; erewrite <- local_scope_modif_bound_before with (s2:=s2); eauto.\n            }\n          + cbn in MINV. cbn.\n            destruct MINV as (ptr & τ' & TEQ & FIND & READ).\n            exists ptr. exists τ'.\n            repeat split; eauto.\n\n            pose proof (IRState_is_WF _ _ _ NTH_σ) as (id' & NTH_Γ').\n            (* id can not be id_addr because of the different\n                     type, and thus must be in a different block *)\n\n            (* Find τ' *)\n            rewrite NTH_Γ in NTH_Γ'; inv NTH_Γ'.\n            cbn in H1. inv H1.\n\n            eapply write_different_blocks; eauto.\n            2: reflexivity.\n            2-3: typ_to_dtyp_simplify; constructor.\n\n            rewrite <- (handle_gep_addr_array_same_block _ _ _ _ HDST_GEP); eauto.\n\n            intros EQ; symmetry in EQ; revert EQ.\n            eapply st_no_llvm_ptr_aliasing.\n            eapply NTH_σ.\n            { do 2 rewrite nth_error_Sn.\n              apply (nth_error_protect_eq' n3 _ Heqo0).\n            }\n            eapply NTH_Γ.\n            rewrite Gamma_cst.\n            do 2 rewrite nth_error_Sn.\n            rewrite <- Γ_s2i19. rewrite <- Γ_S1S2.\n            eauto.\n            { intros CONTRA; inv CONTRA.\n\n              epose proof (st_no_id_aliasing _ _ _ _ _ _ _ NTH_σ NTH_σ_dst NTH_Γ NTH_Γ_dst) as EQ; inv EQ.\n\n              rewrite NTH_Γ in NTH_Γ_dst; inv NTH_Γ_dst.\n            }\n            eauto.\n            { destruct i3.\n              - eauto.\n              - assert (lid_bound s1 id0) as LID_BOUND0 by (eapply Correctness_Invariants.st_gamma_bound; solve_lid_bound).\n                cbn; erewrite <- local_scope_modif_bound_before with (s2:=s2); eauto.\n            }\n          + (* Global vector *)\n            cbn in MINV.\n            destruct MINV as (ptr & τ' & TEQ & FITS & INLG' & LUP).\n            inv TEQ.\n            exists ptr. exists τ'.\n            repeat split; eauto.\n            eapply dtyp_fits_after_write; eauto.\n            intros H; destruct b; inv H.\n            specialize (LUP eq_refl).\n            destruct LUP as (bkh & MLUP_bk & GETARRAYCELL).\n            exists bkh.\n            split; eauto.\n            intros i v0 H.\n            specialize (GETARRAYCELL _ _ H).\n\n            erewrite write_untouched_ptr_block_get_array_cell; eauto.\n\n            rewrite <- (handle_gep_addr_array_same_block _ _ _ _ HDST_GEP); eauto.\n\n            eapply st_no_llvm_ptr_aliasing.\n            eapply NTH_σ.\n            eapply NTH_σ_dst.\n            eapply NTH_Γ.\n            eapply NTH_Γ_dst.\n            2-3: eauto.\n            intros CONTRA; inv CONTRA.\n            assert (S (S n) ≡ S (S n3)).\n            { eapply st_no_id_aliasing; eauto. }\n            inv H0.\n            apply protect_eq_true in NTH_σ_orig.\n            inv NTH_σ_orig.\n            { destruct i3.\n              - eauto.\n              - assert (lid_bound s1 id0) as LID_BOUND0 by (eapply Correctness_Invariants.st_gamma_bound; solve_lid_bound).\n                cbn; erewrite <- local_scope_modif_bound_before with (s2:=s2); eauto.\n            }\n          + (* Local vector *)\n            cbn in MINV.\n            destruct MINV as (ptr & τ' & TEQ & FITS & INLG' & LUP).\n            inv TEQ.\n            exists ptr. exists τ'.\n            repeat split; eauto.\n            eapply dtyp_fits_after_write; eauto.\n            intros H; destruct b; inv H.\n            specialize (LUP eq_refl).\n            destruct LUP as (bkh & MLUP_bk & GETARRAYCELL).\n            exists bkh.\n            split; eauto.\n            intros i v0 H.\n            specialize (GETARRAYCELL _ _ H).\n\n            erewrite write_untouched_ptr_block_get_array_cell; eauto.\n\n            rewrite <- (handle_gep_addr_array_same_block _ _ _ _ HDST_GEP); eauto.\n\n            eapply st_no_llvm_ptr_aliasing.\n            eapply NTH_σ.\n            eapply NTH_σ_dst.\n            eapply NTH_Γ.\n            eapply NTH_Γ_dst.\n\n            intros CONTRA; inv CONTRA.\n            assert (S (S n3) ≡ S (S n)).\n            { eapply st_no_id_aliasing; eauto. }\n            inv H0.\n            apply protect_eq_true in NTH_σ_orig.\n            inv NTH_σ_orig.\n            { destruct i3.\n              - eauto.\n              - assert (lid_bound s1 id0) as LID_BOUND0 by (eapply Correctness_Invariants.st_gamma_bound; solve_lid_bound).\n                cbn; erewrite <- local_scope_modif_bound_before with (s2:=s2); eauto.\n            }\n            { destruct i3.\n              - eauto.\n              - assert (lid_bound s1 id0) as LID_BOUND0 by (eapply Correctness_Invariants.st_gamma_bound; solve_lid_bound).\n                cbn; erewrite <- local_scope_modif_bound_before with (s2:=s2); eauto.\n            }\n        - eapply no_llvm_ptr_aliasing_cons2; eauto.\n          { cbn in Gamma_cst.\n            rewrite Gamma_cst.\n            apply ListUtil.tail_eq.\n            apply ListUtil.tail_eq.\n            solve_gamma.\n          }\n      }\n\n      destruct POSTAEXPR. cbn in extends.\n      cbn in Mono_IRState.\n\n      split.\n      { (* dst_ptr_id *)\n        destruct Mono_IRState; subst; solve_alist_in.\n      }\n\n      split.\n      { (* src_ptr_id *)\n        destruct Mono_IRState; subst; solve_alist_in.\n      }\n\n      split.\n      { eapply local_scope_modif_trans'. (* TODO: automate this? *)\n        solve_local_scope_modif.\n\n        eapply local_scope_modif_sub'_l with (r := src_val_id).\n        solve_lid_bound_between.\n\n        eapply local_scope_modif_sub'_l with (r := dst_val_id).\n        solve_lid_bound_between.\n\n        solve_local_scope_modif.\n      }\n\n      split.\n      { cbn in is_almost_pure.\n        destruct is_almost_pure as [_ [_ G]].\n        subst.\n        auto.\n      }\n\n      split.\n      { eapply write_preserves_allocated; eauto.\n      }\n\n      split.\n      { (* Returns... *)\n        rewrite tfor_split with (i := 0) (j:= k) (k0:= S k); try lia.\n        rewrite interp_helix_bind.\n        eapply Returns_bind; eauto.\n        cbn.\n\n        rewrite tfor_unroll; [|lia].\n        rewrite interp_helix_bind.\n        \n        eapply mem_lookup_err_inr_Some_eq in MEMLUP_xoff.\n        erewrite MEMLUP_xoff.\n        cbn.\n        rewrite bind_ret_l.\n        unfold denoteBinCType.\n\n        eapply Returns_bind.\n\n        { rewrite interp_helix_bind.\n          eapply Returns_bind; eauto.\n          unfold mem_lookup_err.\n          rewrite LINV_HELIX_MB_NEW.\n          cbn.\n          rewrite interp_helix_ret.\n          cbn.\n\n          constructor.\n          reflexivity.\n\n          rewrite interp_helix_bind.\n          eapply Returns_bind; eauto.\n          cbn.\n\n          rewrite interp_helix_ret.\n          cbn.\n\n          constructor.\n          reflexivity.\n        }\n\n        cbn.\n        rewrite tfor_0.\n        rewrite interp_helix_ret.\n        cbn.\n        constructor.\n        reflexivity.\n      }\n\n      split.\n      { (* Helix memory old *)\n        intros y H.\n        rewrite mem_lookup_mem_add_neq; eauto.\n      }\n\n      exists t_Aexpr.\n      split.\n      { (* Helix memory extended *)\n        rewrite mem_lookup_mem_add_eq; eauto.\n      }\n\n      { eapply write_correct in WRITE.\n        destruct WRITE as [ALLOCATED WRITTEN].\n\n        eapply ext_memory_trans; eauto.\n        eapply WRITTEN. constructor.\n      }\n\n    - (* local_scope_modif sb1 sb2 li l *)\n      destruct POSTAEXPR. cbn in extends.\n\n      cbn in Mono_IRState.\n      cbn in Gamma_cst.\n\n      eapply local_scope_modif_sub'_l with (r:=src_val_id).\n      solve_lid_bound_between.\n\n      eapply local_scope_modif_sub'_l with (r:=dst_val_id).\n      solve_lid_bound_between.\n\n      solve_local_scope_modif.\n  }\n\n  (* TODO: Might want to do more forward reasoning first *)\n  match goal with\n  | H: _ |- eutt ?R ?x (interp_cfg ?y ?g ?l ?m)\n    => rewrite <- (bind_ret_r y)\n  end.\n\n  setoid_rewrite interp_cfg3_bind.\n  eapply eutt_clo_bind.\n  eapply LOOPTFOR.\n\n  all: solve_local_count.\n\n  6: {\n    intros [[mH_post mb_post]|] [mV_post [l_post [g_post x_pos]]] [POST [Q_POST LSM_POST]]; [|inv Q_POST].\n    rewrite interp_helix_MemSet.\n    cbn.\n    vred.\n\n    apply eutt_Ret.\n    unfold genIR_post.\n    split; cbn.\n\n    cbn in Q_POST.\n    { (* State invariant preserved *)\n      split; eauto.\n      eapply st_no_id_aliasing; eauto.\n      eapply st_no_dshptr_aliasing; eauto.\n      eapply st_no_llvm_ptr_aliasing; eauto.\n\n      (* memory_invariant and id_allocated are the only things that care\n             about the altered memory\n       *)\n      { unfold id_allocated.\n        intros n addr0 val H.\n\n        eapply st_id_allocated in Q_POST.\n        eauto.\n      }\n\n      get_gamma_bounds; solve_gamma_bound.\n    }\n\n    split.\n    { (* branches *)\n      cbn.\n      inv POST; eexists; eauto.\n    }\n\n    { (* local_scope_modif *)\n      cbn.\n\n      (* TODO: incorporate this into solve_local_scope_modif? *)\n      repeat\n        match goal with\n        | POST: genNExpr_post _ _ _ _ _ _ _ _ |- _\n          =>  apply Correctness_NExpr.extends in POST; cbn in POST\n        end.\n\n      eapply local_scope_modif_shrink with (s3:=s2) (s4:=s2) (s1:=i8) in LSM_POST; [|solve_local_count|solve_local_count].\n      apply local_scope_modif_sub'_l in LSM_POST; [|solve_lid_bound_between].\n      apply local_scope_modif_sub'_l in LSM_POST; [|solve_lid_bound_between].\n\n      solve_local_scope_modif_trans.\n    }\n  }\n\n  (* TODO: bunch of stuff to deal with here...\n\n         Better nail down the other admits first so we're more\n         confident in the loop invariant.\n   *)\n\n  { (* Invariant is stable under the administrative bookkeeping that the loop performs *)\n    intros k a l' mV g id1 v BOUND HI.\n    unfold I in *.\n    destruct a; try inv HI.\n    destruct p.\n    destruct HI as [HI_SINV [HI_DST_PTR_ID [HI_SRC_PTR_ID [HI_LSM [HI_G [HI_ALLOC [HI_RET [HI_HELIX_MB_OLD [HI_v [HI_HELIX_MB_NEW HI_MEXT]]]]]]]]]].\n    pose proof HI_MEXT as [HI_MEXT_NEW HI_MEXT_OLD].\n    split.\n    { destruct BOUND.\n      - eapply state_invariant_same_Γ with (s1 := s2); eauto.\n\n        (* No variables were bound between i21 and s2, so H should give us a contradiction *)\n        eapply not_in_Gamma_Gamma_eq; eauto.\n        eapply not_in_gamma_protect.\n        eapply GAM.\n        eapply lid_bound_between_shrink_down.\n        2: eapply H.\n        cbn.\n        solve_local_count.\n      - eapply state_invariant_same_Γ with (s1 := s2); eauto.\n\n        (* No variables were bound between i21 and s2, so H should give us a contradiction *)\n        eapply not_in_Gamma_Gamma_eq; eauto.\n        eapply not_in_gamma_protect.\n        eapply GAM.\n        eapply lid_bound_between_shrink.\n        eauto.\n        solve_local_count.\n        cbn; solve_local_count.\n    }\n\n    split.\n    { destruct BOUND.\n      solve_alist_in.\n      erewrite alist_find_neq.\n      solve_alist_in.\n\n      (* TODO: automate this *)\n      eapply state_bound_between_separate.\n      eapply incLocalNamed_count_gen_injective.\n      solve_lid_bound_between.\n      solve_lid_bound_between.\n      cbn; solve_local_count.\n    }\n    split.\n    { destruct BOUND.\n      solve_alist_in.\n      erewrite alist_find_neq.\n      solve_alist_in.\n\n      (* TODO: automate this *)\n      eapply state_bound_between_separate.\n      eapply incLocalNamed_count_gen_injective.\n      solve_lid_bound_between.\n      solve_lid_bound_between.\n      solve_local_count.\n    }\n\n    repeat split; auto.\n\n    { destruct BOUND.\n      - eapply local_scope_modif_add'.\n        eapply lid_bound_between_shrink. (* TODO: fix lid_bound_between *)\n        eauto.\n        solve_local_count.\n        solve_local_count.\n        solve_local_scope_modif.\n      - eapply local_scope_modif_add'.\n        eapply lid_bound_between_shrink; [solve_lid_bound_between | | ]; eauto; solve_local_count.\n        solve_local_scope_modif.\n    }\n\n    exists HI_v.\n    auto.\n  }\n\n  (* TODO: May need to modify P / Q here *)\n  { (* P -> I 0 *)\n    unfold imp_rel. intros a b2 PR.\n    red. red in PR.\n    destruct a. 2: inv PR.\n    destruct p as [mH mb].\n    destruct b2 as [mV [l' g]].\n    destruct PR as [SINV [DST [SRC [LSM [G [MH [MB MV]]]]]]].\n\n    split.\n    solve [eauto].\n\n    subst.\n    repeat split; eauto.\n\n    { assert (allocated ptrll_yoff mV_yoff); [solve_allocated|].\n      eapply write_preserves_allocated; eauto.\n    }\n\n    { rewrite tfor_0.\n      rewrite interp_helix_ret. cbn.\n      constructor.\n      reflexivity.\n    }\n\n    { intros y H.\n      rewrite mem_lookup_mem_add_neq; eauto.\n    }\n\n    { exists initial.\n      pose proof (write_correct WRITE_INIT) as [WRITE_ALLOCATED WRITE_EXT].\n      split.\n      - apply mem_lookup_mem_add_eq.\n      - (* extended LLVM memory *)\n        specialize (WRITE_EXT DTYPE_Double).\n        forward WRITE_EXT; [constructor|].\n        destruct WRITE_EXT as [WRITE_NEW WRITE_OLD].            \n        split; eauto.\n    }\n  }\n\n  { (* I loop_end -> Q *)\n    unfold imp_rel. intros a b2 H.\n    red. red in H.\n    break_match; try inv H.\n    break_match_hyp.\n    break_match_hyp.\n    break_match_hyp.\n    destruct H as [SINV [DST [SRC [LSM [G [ALLOCI [RET [MEMH_OLD [v [MEMH_NEW EXT_MEM]]]]]]]]]].\n    subst.\n\n    eapply state_invariant_write_double_result with (sz:=sz0); eauto.\n    3: { intros i v0 H H0.\n         pose proof GETARRAYCELL_yoff.\n         pose proof get_array_cell_mlup_ext.\n\n         pose proof (write_correct WRITE_INIT) as [ALLOC WRITE_EXT].\n         specialize (WRITE_EXT DTYPE_Double).\n         forward WRITE_EXT; [constructor|].\n\n         (* GETARRAYCELL_yoff starts at mV_yoff. mV_init extends that, and m1 extends mV_init *)\n         epose proof get_array_cell_mlup_ext bkh_yoff ptrll_yoff _ _ _ _ WRITE_EXT.\n         forward H3. solve_allocated.\n\n         epose proof @get_array_cell_mlup_ext' bkh_yoff ptrll_yoff _ _ _ mV_init m1.\n         epose proof @get_array_cell_mlup_ext' bkh_yoff ptrll_yoff _ _ _ mV_init m1 v H3.\n\n         eapply H5; eauto.\n         rewrite repr_of_nat_to_nat; eauto.\n    }\n    rewrite <- Γ_S1S2; eauto.\n    eauto.\n\n    { (* Should be able to use INLG_yoff *)\n      cbn. cbn in INLG_yoff.\n\n      (* TODO: another automation candidate. *)\n      nexpr_modifs.\n      epose proof local_scope_modif_trans'' PostLoopEndNExpr PostXoffNExpr.\n      repeat (forward H; solve_local_count).\n      epose proof local_scope_modif_trans'' H PostYoffNExpr.\n      repeat (forward H0; solve_local_count).\n      pose proof LSM.\n      eapply local_scope_modif_shrink with (s1 := i8) (s4:= s2) in H1; solve_local_count.\n      eapply local_scope_modif_sub'_l in H1; [|solve_lid_bound_between].\n      eapply local_scope_modif_sub'_l in H1; [|solve_lid_bound_between].\n      epose proof local_scope_modif_trans'' H0 H1.\n      repeat (forward H2; solve_local_count).\n\n      { destruct i3.\n        - eauto.\n        - assert (lid_bound s1 id) as LID_BOUND0 by (eapply Correctness_Invariants.st_gamma_bound; solve_lid_bound).\n          cbn; erewrite <- local_scope_modif_bound_before with (s2:=s2); eauto.\n          solve_lid_bound.\n      }\n    }\n  }\n\n  { (* IDENT *)\n    intros x H; inv H.\n    pose proof (genNExpr_ident_bound _ Heqs3 GBi5).\n    repeat (rewrite alist_find_neq); try solve_id_neq.\n    pose proof PostLoopEndNExpr.\n    destruct H0.\n    cbn in *.\n    (* This is where I need exp_in_scope... *)\n    pose proof (exp_in_scope x eq_refl).\n    destruct H0 as [[INL BOUNDX] | [INL [BOUNDX LT]]]; unfold alist_In in INL.\n    -\n\n      edestruct lid_bound_before_bound_between with (s2 := i5) (id:=x).\n      solve_lid_bound.\n      solve_local_count.\n\n      destruct Mono_IRState.\n      + erewrite local_scope_preserve_modif.\n        eauto.\n        2: solve_local_scope_modif.\n        solve_local_count.\n        eauto.\n      + subst.\n        erewrite local_scope_preserve_modif; eauto.\n    - nexpr_modifs.\n      epose proof local_scope_modif_trans'' PostXoffNExpr PostYoffNExpr as LSM_yoff'.\n      repeat (forward LSM_yoff'; solve_local_count).\n      \n      erewrite local_scope_preserve_modif.\n      eauto.\n      2: eauto.\n      solve_local_scope_modif.\n  }\n  \n  { (* P holds initially *)\n    red.\n    split.\n    { (* State invariant *)\n      repeat\n        (eapply state_invariant_same_Γ'; cycle 1;\n         [get_gamma_bounds; solve_gamma_bound | solve_not_in_gamma | | solve_gamma]).\n\n      assert (Γ s2 ≡ Γ i8) as Γ_s2i8 by solve_gamma.\n      eapply state_invariant_Γ' with (s1:=i8); [eauto|eauto|get_gamma_bounds; solve_gamma_bound].\n      { destruct i3.\n        { eapply write_state_invariant with (ptrll := ptrll_yoff) (dst_addr := dst_addr).\n          eauto.\n          assert (Γ s1 ≡ Γ i8) as Γ_s1i8 by solve_gamma.\n          rewrite <- Γ_s1i8. eauto.\n          eauto.\n          eauto.\n          eapply handle_gep_addr_array_same_block; eauto.\n          eauto.\n          constructor.\n        }\n        { eapply write_state_invariant with (ptrll := ptrll_yoff) (dst_addr := dst_addr).\n          eauto.\n          assert (Γ s1 ≡ Γ i8) as Γ_s1i8 by solve_gamma.\n          rewrite <- Γ_s1i8. eauto.\n          eauto.\n          { (* another alist in thing *)\n            assert (lid_bound s1 id) as LID_BOUND0 by (eapply Correctness_Invariants.st_gamma_bound; solve_lid_bound).\n            cbn. cbn in INLG_yoff.\n\n            nexpr_modifs.\n            epose proof local_scope_modif_trans'' PostLoopEndNExpr PostXoffNExpr.\n            repeat (forward H; solve_local_count).\n            epose proof local_scope_modif_trans'' H PostYoffNExpr.\n            repeat (forward H0; solve_local_count).\n            cbn; erewrite <- local_scope_modif_bound_before with (s2:=i8); eauto.\n            solve_lid_bound.\n          }\n          eapply handle_gep_addr_array_same_block; eauto.\n          eauto.\n          constructor.\n        }\n      }\n    }\n\n    (* Local environments *)\n    repeat split; solve_alist_in.\n  }\n\n  Unshelve.\n  all: eauto.\n  all: eapply from_N_intval in EQsz0; subst; auto.\nQed.\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_Power.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631556226292, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.2777851398983638}}
{"text": "From compcert Require Import Smallstep Clight Integers Events Behaviors.\nRequire Import Coqlib.\nRequire Import ImpPrelude.\nRequire Import STS.\nRequire Import Behavior.\nRequire Import Imp.\nRequire Import Imp2Csharpminor.\nFrom Ordinal Require Import Ordinal.\n\nSet Implicit Arguments.\n\n\n\n\n\nSection Beh.\n\n  Inductive match_val : eventval -> Z -> Prop :=\n  | match_val_intro :\n      forall v, match_val (EVlong v) (Int64.signed v).\n\n  Inductive match_event : Events.event -> STS.event -> Prop :=\n  | match_event_intro\n      name eargs uargs er ur\n      (MV: Forall2 match_val eargs uargs)\n      (MV: match_val er ur)\n    :\n      match_event (Event_syscall name eargs er) (event_sys name uargs↑ ur↑)\n  .\n\n  Variant _match_beh (match_beh: _ -> _ -> Prop) (tgtb : program_behavior) (srcb : Tr.t) : Prop :=\n  | match_beh_Terminates\n      tr mtr r\n      (MT : Forall2 match_event tr mtr)\n      (TB : tgtb = Terminates tr r)\n      (SB : srcb = Tr.app mtr (Tr.done r.(Int.intval)↑))\n    :\n      _match_beh match_beh tgtb srcb\n  | match_beh_Diverges\n      tr mtr\n      (MT : Forall2 match_event tr mtr)\n      (TB : tgtb = Diverges tr)\n      (SB : srcb = Tr.app mtr (Tr.spin))\n    :\n      _match_beh match_beh tgtb srcb\n  | match_beh_Reacts\n      ev mev trinf mtrinf\n      (ME : match_event ev mev)\n      (MB : match_beh (Reacts trinf) mtrinf)\n      (TB : tgtb = Reacts (Econsinf ev trinf))\n      (SB : srcb = Tr.cons mev mtrinf)\n    :\n      _match_beh match_beh tgtb srcb\n  | match_beh_ub_trace\n      mtr tr\n      (SB : srcb = Tr.app mtr (Tr.ub))\n      (MT : Forall2 match_event tr mtr)\n      (TB : behavior_prefix tr tgtb)\n    :\n      _match_beh match_beh tgtb srcb.\n\n  Definition match_beh : _ -> _ -> Prop := paco2 _match_beh bot2.\n\n  Lemma match_beh_mon : monotone2 _match_beh.\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\nEnd Beh.\nHint Constructors _match_beh.\nHint Unfold match_beh.\nHint Resolve match_beh_mon: paco.\n\n\n\n\n\n\n\nDefinition improves2 {L0 L1} (st_src0: L0.(STS.state)) (st_tgt0: L1.(Smallstep.state)): Prop :=\n  forall tr_tgt (BEH: state_behaves L1 st_tgt0 tr_tgt),\n  exists tr_src, (<<BEH: (Beh.of_state L0 st_src0) tr_src>>) /\\\n                 (<<SIM: match_beh tr_tgt tr_src>>)\n.\n\nDefinition improves2_program (L0: STS.semantics) (L1: Smallstep.semantics) : Prop :=\n  forall tr_tgt (BEH: program_behaves L1 tr_tgt),\n  exists tr_src, (<<BEH: (Beh.of_state L0 L0.(initial_state)) tr_src>>) /\\\n                 (<<SIM: match_beh tr_tgt tr_src>>)\n.\n\nDefinition improves (L0 L1: STS.semantics): Prop :=\n  Beh.improves (Beh.of_program L0) (Beh.of_program L1)\n.\n\nLemma improves_combine: forall (S I: STS.semantics) (A: Smallstep.semantics),\n    improves S I -> improves2_program I A -> improves2_program S A.\nProof.\n  i. ii. exploit H0; et. i; des. exists tr_src. esplits; et. eapply H; et.\nQed.\n\n\n\n\n\n(************************ Coq Aux ****************************)\n(************************ Coq Aux ****************************)\n(************************ Coq Aux ****************************)\nFixpoint sequence X (xs: list (option X)): option (list X) :=\n  match xs with\n  | nil => Some nil\n  | Some hd :: tl => do tl <- (sequence tl); Some (hd :: tl)\n  | None :: _ => None\n  end\n.\n\n(*** it is basically sequence with return type (Err (list X) (list X)). ***)\n(*** i.e., fails with information ***)\nFixpoint squeeze X (es: list (option X)): ((list X) * bool) :=\n  match es with\n  | [] => ([], true)\n  | Some e :: tl => let '(es, succ) := squeeze tl in ((e :: es), succ)\n  | _ => ([], false)\n  end\n.\n\nLemma squeeze_app X (l0 l1: list (option X))\n  :\n    squeeze (l0 ++ l1) =\n    let '(l0', b0) := squeeze l0 in\n    if b0\n    then let '(l1', b1) := squeeze l1 in (l0'++l1', b1)\n    else (l0', false).\nProof.\n  revert l1. induction l0; ss.\n  { i. des_ifs. }\n  { i. des_ifs.\n    { rewrite IHl0 in Heq. rewrite Heq1 in *. clarify. }\n    { rewrite IHl0 in Heq. clarify. }\n  }\nQed.\n\nDefinition option_to_list X (x: option X): list X :=\n  match x with\n  | Some x => [x]\n  | _ => []\n  end\n.\nCoercion option_to_list: option >-> list.\nHint Constructors Forall2.\n\n(************************ Tgt Aux ****************************)\n(************************ Tgt Aux ****************************)\n(************************ Tgt Aux ****************************)\nDefinition single_events_at (L: Smallstep.semantics) (s:L.(Smallstep.state)) : Prop :=\n  forall t s', Step L s t s' -> (t = E0).\n\nRecord wf_at (L: Smallstep.semantics) (s:L.(Smallstep.state)) : Prop :=\n  Wf_at {\n      wf_at_determ:\n        forall s1 t2 s2\n               (STEP0: Step L s E0 s1)\n               (STEP1 :Step L s t2 s2),\n          (<<EQ: s1 = s2 /\\ t2 = E0>>);\n      wf_at_final:\n        forall tr s' retv\n               (FINAL: Smallstep.final_state L s retv)\n               (STEP: Step L s tr s'),\n          False;\n      wf_at_final_determ:\n        forall retv0 retv1\n               (FINAL0: Smallstep.final_state L s retv0)\n               (FINAL1: Smallstep.final_state L s retv1),\n          (<<EQ: retv0 = retv1>>);\n    }.\n\nDefinition wf_semantics (L: Smallstep.semantics) : Prop :=\n  forall st, wf_at L st.\n\n(* Record strict_determinate_at (L: Smallstep.semantics) (s:L.(Smallstep.state)) : Prop := *)\n(*   Strict_determinate_at { *)\n(*       ssd_determ_at: forall t1 s1 t2 s2 *)\n(*         (STEP0: Step L s t1 s1) *)\n(*         (STEP1 :Step L s t2 s2), *)\n(*         <<EQ: s1 = s2>>; *)\n(*     ssd_determ_at_final: forall tr s' retv *)\n(*         (FINAL: Smallstep.final_state L s retv) *)\n(*         (STEP: Step L s tr s'), *)\n(*         False; *)\n(*     ssd_traces_at: *)\n(*       single_events_at L s *)\n(*   }. *)\n\n(************************ Src Aux ****************************)\n(************************ Src Aux ****************************)\n(************************ Src Aux ****************************)\n\n\n\nDefinition wf (L: semantics) (st0: L.(state)): Prop :=\n  forall (ANG: L.(state_sort) st0 = angelic),\n  forall st1 st1' (STEP: step L st0 None st1) (STEP: step L st0 None st1'), st1 = st1'\n.\n\n\n\nSection STAR.\n  Variable L: semantics.\n  Variable P: L.(state) -> Prop.\n  Inductive pstar: L.(state) -> list event -> L.(state) -> Prop :=\n  | star_refl: forall st_src0, pstar st_src0 [] st_src0\n  | star_step: forall\n      st_src0 es0 st_src1 es1 st_src2\n      (P: P st_src0)\n      (HD: step L st_src0 es0 st_src1)\n      (TL: pstar st_src1 es1 st_src2)\n    ,\n      pstar st_src0 (es0 ++ es1) st_src2\n  .\nEnd STAR.\nHint Constructors pstar.\nDefinition dstar L := pstar L (fun st_src0 => L.(state_sort) st_src0 = demonic).\nDefinition star L := pstar L (wf L).\n\nLemma star_trans\n      L\n      st0 st1 st2 es0 es1\n      (STEPS0: star L st0 es0 st1)\n      (STEPS1: star L st1 es1 st2)\n  :\n    star L st0 (es0 ++ es1) st2.\nProof.\n  revert es1 st2 STEPS1. induction STEPS0; et.\n  i. rewrite <- List.app_assoc.\n  econs; et. eapply IHSTEPS0. et.\nQed.\n\nLemma star_des\n      L\n      st0 e es st2\n      (STAR: star L st0 (e :: es) st2)\n  :\n    exists st1, <<HD: star L st0 [e] st1>> /\\ <<TL: star L st1 es st2>>\n.\nProof.\n  remember (e :: es) as x. revert Heqx. revert e es.\n  induction STAR; ii; ss.\n  destruct es0; ss.\n  - clarify. esplits; et. change [e] with ((option_to_list (Some e)) ++ []).\n    econs; ss; et.\n  - subst. exploit IHSTAR; et. i; des. esplits; et.\n    change [e] with ((@option_to_list event None) ++ [e]).\n    econs; ss; et.\nQed.\n\nLemma star_event_ind\n      L\n      (P: L.(state) -> list event -> L.(state) -> Prop)\n      (BASE: forall st0 st1, star L st0 [] st1 -> P st0 [] st1)\n      (SUCC: forall e es st0 st1 st2, star L st0 [e] st1 -> star L st1 es st2 ->\n                                      P st1 es st2 -> P st0 (e :: es) st2)\n  :\n    forall st0 es st1, star L st0 es st1 -> P st0 es st1\n.\nProof.\n  fix IH 2.\n  i.\n  destruct es; ss.\n  - eapply BASE. ss.\n  - eapply star_des in H. des. rename st2 into st_mid.\n    eapply SUCC.\n    { et. }\n    { et. }\n    eapply IH.\n    eapply TL.\nQed.\n\nLemma star_single_exact\n      L0 st0 st3 e0\n      (STAR: star L0 st0 [e0] st3)\n  :\n    exists st1 st2, (<<STAR: star L0 st0 [] st1>>) /\\\n                    (<<VIS: step L0 st1 (Some e0) st2>>) /\\\n                    (<<STAR: star L0 st2 [] st3>>)\n.\nProof.\n  dependent induction STAR; ii; ss.\n  destruct es0; ss.\n  { destruct es1; ss. clarify. esplits; et. econs. }\n  clarify.\n  exploit IHSTAR; et. i; des. esplits; try apply VIS; et.\n  replace [] with ((@option_to_list event None) ++ []) by ss.\n  econs; et.\nQed.\n\nDefinition NoStuck L (st_src0: state L): Prop :=\n  L.(state_sort) st_src0 = angelic ->\n  (<<NOSTUCK: exists ev st_src1, step L st_src0 ev st_src1>>)\n(* (<<DTM: forall st_src1 st_src1', *)\n(*     step L st_src0 None st_src1 -> *)\n(*     step L st_src0 None st_src1' -> *)\n(*     st_src1 = st_src1'>>) *)\n.\n\n\n\n(* Definition wf (L: semantics): Prop := *)\n(*   forall (st0: L.(state)) (ANG: L.(state_sort) st0 = angelic), *)\n(*   forall st1 st1' (STEP: step L st0 None st1) (STEP: step L st0 None st1'), st1 = st1' *)\n(* . *)\n\n\nSection BEH.\n\nVariable L: semantics.\n(* Hypothesis WFSRC: wf L. *)\n(* Hypothesis WFSRC: forall st, (state_sort L st = angelic) -> wf L st. *)\n\n(*** TODO: move to proper place? ***)\nLemma _beh_astep_rev\n      r tr st0 ev st1\n      (SRT: _.(state_sort) st0 = angelic)\n      (WFSRC: wf _ st0)\n      (STEP: _.(step) st0 ev st1)\n      (BEH: paco2 (Beh._of_state L) r st1 tr)\n  :\n    <<BEH: paco2 (Beh._of_state L) r st0 tr>>\n.\nProof.\n  exploit wf_angelic; et. i; clarify.\n  pfold. econsr; ss; et. rr. ii. exploit wf_angelic; et. i; des. subst.\n  exploit WFSRC; [..|apply STEP|apply STEP0|]; ss. i; subst. esplits; et.\n  punfold BEH.\nQed.\n\nLemma beh_of_state_star\n      r st_src0 st_src1 es0 tr1\n      (BEH: paco2 (Beh._of_state L) r st_src1 tr1)\n      (STAR: star L st_src0 es0 st_src1)\n  :\n    <<BEH: paco2 (Beh._of_state L) r st_src0 (Tr.app es0 tr1)>>\n.\nProof.\n  revert BEH. revert tr1.\n  induction STAR; ii; ss.\n  exploit IHSTAR; et.\n  intro U; des.\n  destruct (state_sort L st_src0) eqn:T.\n  - exploit wf_angelic; et. i; subst. ss.\n    eapply _beh_astep_rev; et.\n  - exploit wf_demonic; et. i; subst. ss.\n    pfold. econs; ss; et. rr. esplits; ss; et. punfold U.\n  - exploit wf_final; et. ss.\n  - destruct es0; ss; cycle 1.\n    { exploit wf_vis_event; et. ss. }\n    pfold; econs; ss; et.\nQed.\n\nVariant starC (r: (state L -> Tr.t -> Prop)): (state L -> Tr.t -> Prop) :=\n| starC_intro\n    st0 st1 tr\n    (STAR: star L st0 [] st1)\n    (SIM: r st1 tr)\n  :\n    starC r st0 tr\n.\n\nHint Constructors starC: core.\n\nLemma starC_mon\n      r1 r2\n      (LE: r1 <2= r2)\n  :\n    starC r1 <2= starC r2\n.\nProof. ii. destruct PR; econs; et. Qed.\n\nHint Resolve starC_mon: paco.\n\nLemma starC_prespectful: prespectful2 (Beh._of_state L) starC.\nProof.\n  econs; eauto with paco.\n  ii. rename x0 into st0. rename x1 into tr.\n  inv PR. rename st2 into st1.\n  apply GF in SIM.\n  { change tr with (Tr.app [] tr). eapply beh_of_state_star; et. pfold.\n    eapply Beh.of_state_mon; et.\n  }\nQed.\n\nLemma starC_spec: starC <3= gupaco2 (Beh._of_state L) (cpn2 (Beh._of_state L)).\nProof. intros. eapply prespect2_uclo; eauto with paco. eapply starC_prespectful. Qed.\n\nVariant starC2 (r: (state L -> Tr.t -> Prop)): (state L -> Tr.t -> Prop) :=\n| starC2_intro\n    st0 st1 tr0 tr1\n    (STAR: star L st0 tr0 st1)\n    (SIM: r st1 tr1)\n  :\n    starC2 r st0 (Tr.app tr0 tr1)\n.\n\nHint Constructors starC2: core.\n\nLemma starC2_mon\n      r1 r2\n      (LE: r1 <2= r2)\n  :\n    starC2 r1 <2= starC2 r2\n.\nProof. ii. destruct PR; econs; et. Qed.\n\nHint Resolve starC2_mon: paco.\n\nLemma starC2_prespectful: prespectful2 (Beh._of_state L) starC2.\nProof.\n  econs; eauto with paco.\n  ii. rename x0 into st0. rename x1 into tr.\n  inv PR. rename st2 into st1.\n  apply GF in SIM.\n  { eapply beh_of_state_star; ss; et. pfold.\n    eapply Beh.of_state_mon; et.\n  }\nQed.\n\nLemma starC2_spec: starC2 <3= gupaco2 (Beh._of_state L) (cpn2 (Beh._of_state L)).\nProof. intros. eapply prespect2_uclo; eauto with paco. eapply starC2_prespectful. Qed.\n\n\nEnd BEH.\n\n(************************ Decompile ****************************)\n(************************ Decompile ****************************)\n(************************ Decompile ****************************)\n\nDefinition decompile_eval (ev: eventval): option Z :=\n  match ev with\n  | EVlong i => Some (Int64.signed i)\n  | _ => None\n  end\n.\n\nDefinition decompile_event (ev: Events.event): option event :=\n  match ev with\n  | Event_syscall fn evs ev =>\n    do vs <- sequence (List.map decompile_eval evs);\n    do v <- decompile_eval ev;\n    Some (event_sys fn vs↑ v↑)\n  | _ => None\n  end.\n\n(* Definition _decompile_trinf decompile_trinf (tr: traceinf): Tr.t := *)\n(*   match tr with *)\n(*   | Econsinf ev tr => *)\n(*     match decompile_event ev with *)\n(*     | Some ev => Tr.cons ev (decompile_trinf tr) *)\n(*     | _ => Tr.ub *)\n(*     end *)\n(*   end *)\n(* . *)\n\n(* CoFixpoint decompile_trinf (tr: traceinf): Tr.t := *)\n(*   _decompile_trinf decompile_trinf tr. *)\nCoFixpoint decompile_trinf (tr: traceinf): Tr.t :=\n  match tr with\n  | Econsinf ev tr =>\n    match decompile_event ev with\n    | Some ev => Tr.cons ev (decompile_trinf tr)\n    | _ => Tr.ub\n    end\n  end\n.\n\nVariant _Tr: Type :=\n| _Tr_done (retv: Any.t)\n| _Tr_spin\n| _Tr_ub\n| _Tr_nb\n| _Tr_cons (hd: event) (tl: Tr.t)\n.\n\nDefinition match_Tr (tr: Tr.t) :=\n  match tr with\n  | Tr.done retv => _Tr_done retv\n  | Tr.spin => _Tr_spin\n  | Tr.ub => _Tr_ub\n  | Tr.nb => _Tr_nb\n  | Tr.cons hd tl => _Tr_cons hd tl\n  end.\n\nLemma Tr_eta (tr0 tr1: Tr.t)\n      (EQ: match_Tr tr0 = match_Tr tr1)\n  :\n    tr0 = tr1.\nProof.\n  destruct tr0, tr1; ss; clarify.\nQed.\n\nLemma unfold_decompile_trinf\n      tr\n  :\n    (decompile_trinf tr) =\n    (match tr with\n     | Econsinf ev tr =>\n       match decompile_event ev with\n       | Some ev => Tr.cons ev (decompile_trinf tr)\n       | _ => Tr.ub\n       end\n     end)\n.\nProof.\n  destruct tr. eapply Tr_eta. ss.\nQed.\n\nLemma decompile_trinf_app\n      tr_tgt tr_src T\n      (MB: squeeze (List.map decompile_event tr_tgt) = (tr_src, true))\n  :\n    (decompile_trinf (tr_tgt *** T)) = Tr.app tr_src (decompile_trinf T)\n.\nProof.\n  ginduction tr_tgt; ii; ss; clarify.\n  des_ifs. ss.\n  rewrite unfold_decompile_trinf. des_ifs. f_equal.\n  eapply IHtr_tgt; ss.\nQed.\n\nDefinition transl_beh (p: program_behavior): Tr.t :=\n  match p with\n  | Terminates tr i =>\n    let '(es, succ) := squeeze (List.map decompile_event tr) in\n    Tr.app es (if succ then (Tr.done (Int.unsigned i)↑) else Tr.ub)\n  | Diverges tr =>\n    let '(es, succ) := squeeze (List.map decompile_event tr) in\n    Tr.app es (if succ then (Tr.spin) else Tr.ub)\n  | Reacts tr => (decompile_trinf tr)\n  | Goes_wrong tr =>\n    let '(es, succ) := squeeze (List.map decompile_event tr) in\n    Tr.app es Tr.ub\n  end\n.\n\nLemma decompile_match_val v0 v1\n      (SEQ: decompile_eval v0 = Some v1)\n  :\n    match_val v0 v1.\nProof.\n  unfold decompile_eval in *. des_ifs.\nQed.\n\nLemma decompile_match_vals l0 l1\n      (SEQ: sequence (List.map decompile_eval l0) = Some l1)\n  :\n    Forall2 match_val l0 l1.\nProof.\n  revert l1 SEQ. induction l0; ss.\n  { i. clarify. }\n  { i. uo. des_ifs. econs; et.\n    eapply decompile_match_val; et. }\nQed.\n\nLemma decompile_match_event\n      e0 e1\n      (D: decompile_event e0 = Some e1)\n  :\n    <<M: match_event e0 e1>>\n.\nProof.\n  destruct e0; ss. uo. des_ifs. econs.\n  { eapply decompile_match_vals; et. }\n  { eapply decompile_match_val; et. }\nQed.\n\nLemma match_val_iff v0 v1\n  :\n    decompile_eval v0 = Some v1 <->\n    match_val v0 v1.\nProof.\n  split.\n  { eapply decompile_match_val. }\n  i. inv H. ss.\nQed.\n\nLemma match_vals_iff l0 l1\n  :\n    sequence (List.map decompile_eval l0) = Some l1 <->\n    Forall2 match_val l0 l1.\nProof.\n  split.\n  { eapply decompile_match_vals. }\n  revert l1. induction l0; ss.\n  { i. inv H. ss. }\n  { i. inv H. hexploit IHl0; et. i.\n    uo. rewrite H.\n    eapply match_val_iff in H2. rewrite H2. ss. }\nQed.\n\nLemma match_event_iff\n      e_src e_tgt\n  :\n    decompile_event e_tgt = Some e_src <->\n    match_event e_tgt e_src\n.\nProof.\n  split.\n  { eapply decompile_match_event. }\n  i. inv H. ss. uo.\n  eapply match_vals_iff in MV. rewrite MV.\n  eapply match_val_iff in MV0. rewrite MV0. ss.\nQed.\n\nLemma match_event_squeeze\n      e_src e_tgt\n  :\n    squeeze [decompile_event e_tgt] = ([e_src], true) <->\n    match_event e_tgt e_src\n.\nProof.\n  split; i.\n  - ss. des_ifs. eapply match_event_iff; et.\n  - eapply match_event_iff in H; et. ss. des_ifs.\nQed.\n\nLemma match_events_squeeze\n      es_src es_tgt\n  :\n    squeeze (List.map decompile_event es_tgt) = (es_src, true) <->\n    Forall2 match_event es_tgt es_src\n.\nProof.\n  revert es_tgt. induction es_src; ss.\n  { i. split.\n    { destruct es_tgt; ss. des_ifs. }\n    { i. inv H. ss. }\n  }\n  { i. split.\n    { i. destruct es_tgt; ss. des_ifs.\n      hexploit IHes_src; et. i. econs.\n      { eapply match_event_squeeze. ss. rewrite Heq. ss. }\n      { eapply H. et. }\n    }\n    { i. inv H. eapply IHes_src in H4. ss.\n      eapply match_event_iff in H3. rewrite H3.\n      rewrite H4. ss.\n    }\n  }\nQed.\n\nTheorem decompile_trinf_spec\n        tr\n  :\n    match_beh (Reacts tr) (decompile_trinf tr)\n.\nProof.\n  revert tr.\n  pcofix CIH.\n  i. destruct tr; ss.\n  rewrite unfold_decompile_trinf. des_ifs.\n  - eapply match_event_iff in Heq. dup Heq. inv Heq.\n    pfold. eapply match_beh_Reacts; et.\n  - pfold. econsr; ss; et.\n    r. esplits; ss; et. rewrite behavior_app_E0. ss.\nQed.\n\n\n\n\n\n\n\n\n\nSection SIM.\n\n  Variable L0: STS.semantics.\n  Variable L1: Smallstep.semantics.\n  Let idx := Ord.t.\n  Let ord := Ord.lt.\n\n  Local Open Scope smallstep_scope.\n\n  Variant _sim sim (i0: idx) (st_src0: L0.(STS.state)) (st_tgt0: L1.(Smallstep.state)): Prop :=\n  | sim_fin\n      retv\n      (RANGE: (0 <= retv <= Int.max_unsigned)%Z)\n      (* (RANGE: (Int.min_signed <= retv <= Int.max_signed)%Z) *)\n      (SRT: _.(state_sort) st_src0 = final retv↑)\n      (SRT: _.(Smallstep.final_state) st_tgt0 (Int.repr retv))\n      (* (DTM: True) (*** TODO: copy-paste sd_final_determ in Smallstep.v ***) *)\n    :\n      _sim sim i0 st_src0 st_tgt0\n\n  | sim_vis\n      (SRT: _.(state_sort) st_src0 = vis)\n      (SRT: exists _ev_tgt _st_tgt1, Step L1 st_tgt0 [_ev_tgt] _st_tgt1)\n      (SIM: forall ev_tgt st_tgt1\n          (STEP: Step L1 st_tgt0 ev_tgt st_tgt1)\n        ,\n          exists st_src1 ev_src (STEP: _.(step) st_src0 (Some ev_src) st_src1),\n            (<<MATCH: Forall2 match_event ev_tgt [ev_src]>>) /\\\n            (<<SIM: exists i1, sim i1 st_src1 st_tgt1>>))\n    :\n      _sim sim i0 st_src0 st_tgt0\n\n  | sim_demonic_src\n      (SRT: _.(state_sort) st_src0 = demonic)\n      (SIM: exists st_src1\n          (STEP: _.(step) st_src0 None st_src1)\n        ,\n          exists i1, <<ORD: ord i1 i0>> /\\ <<SIM: sim i1 st_src1 st_tgt0>>)\n    :\n      _sim sim i0 st_src0 st_tgt0\n  | sim_demonic_tgt_dtm\n      (*** WRONG DEF, Note: UB in tgt ***)\n      (* (SIM: forall st_tgt1 *)\n      (*     (STEP: Step L1 st_tgt0 E0 st_tgt1) *)\n      (*   , *)\n      (*     exists i1, <<ORD: ord i1 i0>> /\\ <<SIM: sim i1 st_src0 st_tgt1>>) *)\n      (SIM: exists st_tgt1\n          (STEP: Step L1 st_tgt0 E0 st_tgt1)\n        ,\n          exists i1, <<ORD: ord i1 i0>> /\\ <<SIM: sim i1 st_src0 st_tgt1>>)\n      (*** equivalent def ***)\n      (* st_tgt1 *)\n      (* (STEP: Step L1 st_tgt0 E0 st_tgt1) *)\n      (* i1 *)\n      (* (ORD: ord i1 i0) *)\n      (* (SIM: sim i1 st_src0 st_tgt1) *)\n    :\n      _sim sim i0 st_src0 st_tgt0\n  | sim_angelic_src\n      (SRT: _.(state_sort) st_src0 = angelic)\n      (DTM: forall st1 st2, (<<DTM1: _.(step) st_src0 None st1>>) -> (<<DTM2: _.(step) st_src0 None st2>>) -> st1 = st2)\n      (SIM: forall st_src1\n          (STEP: _.(step) st_src0 None st_src1)\n        ,\n          exists i1, <<ORD: ord i1 i0>> /\\ <<SIM: sim i1 st_src1 st_tgt0>>)\n    :\n      _sim sim i0 st_src0 st_tgt0\n\n\n  | sim_demonic_both\n      (SRT: _.(state_sort) st_src0 = demonic)\n      (SIM: exists st_tgt1\n          (STEP: Step L1 st_tgt0 E0 st_tgt1)\n        ,\n          exists st_src1 (STEP: _.(step) st_src0 None st_src1),\n            <<SIM: exists i1, sim i1 st_src1 st_tgt1>>)\n    :\n      _sim sim i0 st_src0 st_tgt0\n  .\n\n  Definition sim: _ -> _ -> _ -> Prop := paco3 _sim bot3.\n\n  Lemma sim_mon: monotone3 _sim.\n  Proof.\n    ii. inv IN.\n\n    - econs 1; et.\n    - econs 2; et. i. exploit SIM; et. i; des. esplits; et.\n    - econs 3; et. des. esplits; et.\n    - econs 4; et. des. esplits; et.\n    - econs 5; et. i. exploit SIM; et. i; des. esplits; et.\n    - econs 6; et. des. esplits; et.\n  Qed.\n\n  Hint Constructors _sim.\n  Hint Unfold sim.\n  Hint Resolve sim_mon: paco.\n\n\n  Variant ordC (r: idx -> L0.(STS.state) -> L1.(Smallstep.state) -> Prop):\n    idx -> L0.(STS.state) -> L1.(Smallstep.state) -> Prop :=\n  | ordC_intro\n      o0 o1 st_src st_tgt\n      (ORD: Ord.le o0 o1)\n      (SIM: r o0 st_src st_tgt)\n    :\n      ordC r o1 st_src st_tgt\n  .\n\n  Lemma ordC_mon\n        r1 r2\n        (LE: r1 <3= r2)\n    :\n      ordC r1 <3= ordC r2\n  .\n  Proof. ii. destruct PR; econs; et. Qed.\n\n  Hint Resolve ordC_mon: paco.\n\n  Lemma ordC_compatible: compatible3 (_sim) ordC.\n  Proof.\n    econs; eauto with paco.\n    ii. inv PR. rename x0 into o1. rename x1 into st_src. rename x2 into st_tgt. inv SIM.\n    - econs 1; eauto.\n    - econs 2; eauto. i. hexploit SIM0; et. i. des. esplits; et. econs; [|et]. refl.\n    - econs 3; eauto. des. esplits; et. { eapply Ord.lt_le_lt; et. } econs; et. refl.\n    - econs 4; eauto. des. esplits; et. { eapply Ord.lt_le_lt; et. } econs; et. refl.\n    - econs 5; eauto. i. hexploit SIM0; et. i. des. esplits; et.\n      { eapply Ord.lt_le_lt; et. } econs; et. refl.\n    - econs 6; eauto. des. esplits; et. econs; [|et]. refl.\n  Qed.\n\n  Lemma ordC_spec: ordC <4= gupaco3 (_sim) (cpn3 _sim).\n  Proof.\n    intros. gclo. econs.\n    { eapply ordC_compatible. }\n    eapply ordC_mon; [|et]. i. gbase. auto.\n  Qed.\n\n  Record simulation: Prop := mk_simulation {\n    sim_init: forall st_tgt0 (INITT: L1.(Smallstep.initial_state) st_tgt0),\n        exists i0, (<<SIM: sim i0 L0.(initial_state) st_tgt0>>);\n    (* sim_init: exists i0 st_tgt0, (<<SIM: sim i0 L0.(initial_state) st_tgt0>>) /\\ *)\n    (*                              (<<INITT: L1.(Smallstep.initial_state) st_tgt0>>); *)\n    (* sim_dtm: True; *)\n  }\n  .\n\n  Hypothesis WF: well_founded ord.\n  Hypothesis WFSEM: wf_semantics L1.\n\n  Ltac pc H := rr in H; desH H; ss.\n\n  Definition safe_along_events (st_src0: state L0) (tr: list Events.event): Prop := forall\n      st_src1\n      tx ty tx_src\n      (STAR: star L0 st_src0 tx_src st_src1)\n      (MB: squeeze (List.map decompile_event tx) = (tx_src, true))\n      (PRE: tx ++ ty = tr)\n    ,\n      <<SAFE: NoStuck L0 st_src1>>\n  .\n\n  Definition safe_along_trace (st_src0: state L0) (tr: program_behavior) : Prop := forall\n      thd\n      (BEH: behavior_prefix thd tr)\n    ,\n      safe_along_events st_src0 thd\n  .\n\n  Lemma match_beh_cons\n        b0 b1\n        e0 e1\n        b0_ b1_\n        (B0_: b0_ = (behavior_app [e0] b0))\n        (B1_: b1_ = (Tr.app [e1] b1))\n        (M0: match_beh b0 b1)\n        (M1: match_event e0 e1)\n    :\n      <<M: match_beh b0_ b1_>>\n  .\n  Proof.\n    subst.\n    revert_until b0. revert b0.\n    pcofix CIH. i. punfold M0. inv M0.\n    - pfold. econs 1; try refl; ss; et.\n    - pfold. econs 2; try refl; ss; et.\n    - pfold. econs 3; try refl; ss; et. pclearbot. right.\n      change (Reacts (Econsinf ev trinf)) with (behavior_app [ev] (Reacts trinf)).\n      eapply CIH; et.\n    - pfold. econs 4.\n      { instantiate (1:=e1 :: mtr). ss; et. }\n      { econs; ss; et. }\n      rr in TB. des. subst.\n      rr. esplits; ss; et. rewrite <- behavior_app_assoc. ss.\n  Qed.\n\n  Lemma match_val_inj\n        v_tgt0 v_src0 v_src1\n        (M0: match_val v_tgt0 v_src0)\n        (M1: match_val v_tgt0 v_src1)\n    :\n      v_src0 = v_src1\n  .\n  Proof. inv M0. inv M1. ss. Qed.\n\n  Lemma match_event_inj\n        e_tgt0 e_src0 e_src1\n        (M0: match_event e_tgt0 e_src0)\n        (M1: match_event e_tgt0 e_src1)\n    :\n      e_src0 = e_src1\n  .\n  Proof.\n    inv M0. inv M1. f_equal.\n    { f_equal. clear - MV MV1. ginduction MV; ii; ss.\n      { inv MV1; ss. }\n      inv MV1; ss.\n      f_equal; et.\n      eapply match_val_inj; et.\n    }\n    f_equal. eapply match_val_inj; et.\n  Qed.\n\n  Lemma safe_along_events_step_some\n        st_src0 st_src1 e_src e0 es0\n        (WFSRC: wf L0 st_src0)\n        (STEP: step L0 st_src0 (Some e_src) st_src1)\n        (MB: decompile_event e0 = Some e_src)\n        (SAFE: safe_along_events st_src0 ([e0] ++ es0))\n    :\n      <<SAFE: safe_along_events st_src1 es0>>\n  .\n  Proof.\n    ii. des; clarify. eapply SAFE; ss.\n    { econs; et. }\n    { instantiate (1 := e0 :: _). ss. des_ifs. rewrite MB0 in *; clarify. }\n    { ss. }\n  Qed.\n\n  Lemma safe_along_events_step_none\n        st_src0 st_src1 es0\n        (WFSRC: wf L0 st_src0)\n        (STEP: step L0 st_src0 None st_src1)\n        (SAFE: safe_along_events st_src0 es0)\n    :\n      <<SAFE: safe_along_events st_src1 es0>>\n  .\n  Proof.\n    ii. des; clarify. eapply SAFE; ss.\n    { econs; et. }\n    { ss. }\n  Qed.\n\n  Lemma safe_along_events_star\n        st_src0 st_src1 es0_src es0 es1\n        (STAR: star L0 st_src0 es0_src st_src1)\n        (MB: squeeze (List.map decompile_event es0) = (es0_src, true))\n        (SAFE: safe_along_events st_src0 (es0 ++ es1))\n    :\n      <<SAFE: safe_along_events st_src1 es1>>\n  .\n  Proof.\n    revert st_src0 st_src1 es0_src es1 STAR MB SAFE. induction es0; ss.\n    { i. clarify. ii. subst. exploit SAFE; [..|et|et].\n      { instantiate (1:=tx_src).\n        change tx_src with ([] ++ tx_src). eapply star_trans; et. }\n      { et. }\n      { et. }\n    }\n    { i. des_ifs. ii. subst. exploit SAFE; [..|et|et].\n      { instantiate (1:=_ ++ _). eapply star_trans; et. }\n      { instantiate (1:=a :: es0 ++ tx). ss. rewrite Heq.\n        rewrite List.map_app. rewrite squeeze_app.\n        rewrite MB. des_ifs. }\n      { instantiate (1:=ty). ss. rewrite ! List.app_assoc. auto. }\n    }\n  Qed.\n\n  (* Hypothesis WFSRC: wf L0. *)\n\n  Lemma simulation_star\n        i0 st_src0 tr_tgt st_tgt1 st_tgt0\n        (* (MATCH: Forall2 match_event tr_tgt tr_src) *)\n        (STEP: Star L1 st_tgt0 tr_tgt st_tgt1)\n        (SIM: sim i0 st_src0 st_tgt0)\n        (SAFE: safe_along_events st_src0 tr_tgt)\n    :\n      exists i1 st_src1 tr_src,\n        (<<MB: squeeze (List.map decompile_event tr_tgt) = (tr_src, true)>>) /\\\n        (<<STEP: star L0 st_src0 tr_src st_src1>>) /\\\n        (<<SIM: sim i1 st_src1 st_tgt1>>)\n  .\n  Proof.\n    revert SAFE. revert SIM. depgen st_src0. revert i0.\n    induction STEP; ii; ss.\n    { esplits; et. econs; ss. }\n    subst. rename s1 into st_tgt0. rename s2 into st_tgt1. rename s3 into st_tgt2.\n    rename t1 into tr_tgt0. rename t2 into tr_tgt1.\n\n    revert_until i0. pattern i0. eapply well_founded_ind; et. clear i0. intros i0 IH. i.\n\n    punfold SIM. inv SIM.\n    - (* fin *)\n      exploit wf_at_final; [apply WFSEM|..]; et. ss.\n    - (* vis *)\n      clear SRT0. exploit SIM0; et. i; des. pclearbot.\n      inv MATCH; ss. inv H4; ss. rename H3 into MB. eapply match_event_iff in MB. des_ifs.\n      exploit IHSTEP; et.\n      { eapply safe_along_events_step_some; et. unfold wf. i. rewrite ANG in SRT. ss. }\n      i; des. clarify.\n      esplits; et. rewrite cons_app.\n      change [ev_src] with (option_to_list (Some ev_src)).\n      econs; et.\n      unfold wf. i. rewrite ANG in SRT. ss.\n    - (* dsrc *)\n      des. pclearbot. exploit IH; et.\n      { eapply safe_along_events_step_none; et. unfold wf. i. rewrite ANG in SRT. ss. }\n      i; des.\n      esplits; et.\n      rewrite <- (app_nil_l tr_src).\n      change [] with (@option_to_list event None).\n      econs; et.\n      unfold wf. i. rewrite ANG in SRT. ss. \n    - (* dtgt *)\n      des. pclearbot. exploit wf_at_determ;[apply WFSEM|apply STEP0|apply H|]. i; des. subst.\n      exploit IHSTEP; et.\n    - (* asrc *)\n      exploit SAFE; try apply SRT.\n      { econs; et. }\n      { instantiate (1:=[]). ss. }\n      { ss. }\n      i; des.\n      exploit wf_angelic; et. i; subst.\n      exploit SIM0; et. i; des. pclearbot.\n      exploit IH; et.\n      { eapply safe_along_events_step_none; et. unfold wf. i. apply DTM; eauto. }\n      i; des.\n      esplits; et.\n      rewrite <- (app_nil_l tr_src).\n      change [] with (@option_to_list event None).\n      econs; et.\n      unfold wf. i. apply DTM; eauto.\n    - (* dboth *)\n      des. pclearbot.\n      exploit wf_at_determ;[apply WFSEM|apply STEP0|apply H|]. i; des. subst.\n      exploit IHSTEP; et.\n      { eapply safe_along_events_step_none; et. unfold wf. i. rewrite ANG in SRT. ss. }\n      i; des.\n      esplits; et. rewrite <- (app_nil_l tr_src).\n      change [] with (@option_to_list event None).\n      econs; et.\n      unfold wf. i. rewrite ANG in SRT. ss.\n  Qed.\n\n  Lemma sim_forever_silent\n        i st_src st_tgt\n        (SIM: sim i st_src st_tgt)\n        (SILENT: Forever_silent L1 st_tgt)\n    :\n      Beh.state_spin L0 st_src.\n  Proof.\n    revert i st_src st_tgt SIM SILENT. pcofix CIH.\n    intros i. induction (WF i). rename x into i. rename H0 into IH. clear H.\n    i. inv SILENT. punfold SIM. inv SIM.\n    { exploit wf_at_final; [apply WFSEM|..]; et. ss. }\n    { des. hexploit wf_at_determ; [apply WFSEM|apply H|apply SRT0|]. i. des. clarify. }\n    { des. inv SIM; ss. pfold. econs 2; et. esplits; et. right.\n      eapply CIH; et. econs; et. }\n    { des. inv SIM; ss. eapply IH; et.\n      hexploit wf_at_determ; [apply WFSEM|apply STEP|apply H|]. i. des. clarify. }\n    { pfold. econs 1; et. i.\n      hexploit wf_angelic; et. i. subst.\n      hexploit SIM0; et. i. des. inv SIM; ss. right. eapply CIH; et. econs; et. }\n    { pfold. des. inv SIM; ss.\n      hexploit wf_at_determ; [apply WFSEM|apply STEP|apply H|]. i. des. clarify.\n      econs 2; et. esplits; et. }\n  Qed.\n\n  Lemma sim_goes_wrong\n        i st_src st_tgt\n        (SIM: sim i st_src st_tgt)\n        (NOSTEP: Nostep L1 st_tgt)\n        (NOFINAL: forall r, ~ L1.(Smallstep.final_state) st_tgt r)\n    :\n      Beh.of_state L0 st_src Tr.ub.\n  Proof.\n    ginit.\n    { eapply cpn2_wcompat. eapply Beh.of_state_mon. }\n    revert st_src st_tgt SIM NOSTEP NOFINAL.\n    induction (WF i). rename x into i. rename H0 into IH. clear H.\n    i. punfold SIM. inv SIM; ss.\n    { exfalso. eapply NOFINAL; et. }\n    { des. exfalso. eapply NOSTEP; et. }\n    { des. inv SIM; ss.\n      guclo starC_spec. econs.\n      { instantiate (1:=st_src1).\n        change ([]: list event) with (None ++ []: list event). econs; et.\n        unfold wf; i. rewrite ANG in SRT; ss.\n      }\n      { eapply IH; et. }\n    }\n    { des. exfalso. eapply NOSTEP; et. }\n    { destruct (classic (exists ev st_src1, step L0 st_src ev st_src1)).\n      { des. exploit wf_angelic; et. i; subst. exploit SIM0; et. i; des. inv SIM; ss.\n      guclo starC_spec. econs.\n      { instantiate (1:=st_src1).\n        change ([]: list event) with (None ++ []: list event). econs; et.\n        unfold wf; i. eapply DTM; eauto.\n      }\n      { eapply IH; et. }\n      }\n      { gstep. econs 6; et. ii. exfalso. eapply H. et. }\n    }\n    { des. exfalso. eapply NOSTEP; et. }\n  Qed.\n\n  Lemma adequacy\n        i0 st_src0 st_tgt0\n        (SIM: sim i0 st_src0 st_tgt0)\n    :\n      <<IMPR: improves2 st_src0 st_tgt0>>\n  .\n  Proof.\n    ii.\n    (* set (transl_beh tr_tgt) as tr_src in *. *)\n    destruct (classic (safe_along_trace st_src0 tr_tgt)); rename H into SAFE.\n    { (*** safe ***)\n      exists (transl_beh tr_tgt).\n      inv BEH.\n      - (rename t into tr; rename H into STAR; rename s' into st_tgt1; rename H0 into FIN).\n        esplits; et.\n        + ss. des_ifs_safe.\n          hexploit simulation_star; try apply STAR; et.\n          { eapply SAFE. exists (Terminates [] r). ss. unfold Eapp. rewrite app_nil_r; ss. }\n          i; des.\n          rewrite MB in *. clarify.\n\n\n\n          (*** 1. Lemma: star + Beh.of_state -> Beh.of_state app ***)\n          (*** 2. wf induction on i1 ***)\n          eapply beh_of_state_star; ss; et.\n          cut (Beh.of_state L0 st_src1 (Tr.done (Int.unsigned r)↑)); ss.\n          (* assert(SAFE0: safe_along_trace st_src1 (Terminates tr r)). *)\n          assert(SAFE0: safe_along_events st_src1 []).\n          { clear - SAFE STEP MB.\n            r in SAFE. specialize (SAFE tr).\n            hexploit1 SAFE.\n            { eexists (Terminates nil _). ss. unfold Eapp. rewrite List.app_nil_r. ss. }\n            eapply safe_along_events_star; et.\n            rewrite List.app_nil_r. ss.\n          }\n          clear - SAFE0 FIN WF SIM0 WFSEM.\n          revert_until i1. pattern i1. eapply well_founded_ind; et. clear i1. intros i0 IH.\n          i. punfold SIM0. inv SIM0.\n          * pfold. econs; ss; et.\n            exploit wf_at_final_determ; [eapply WFSEM|eapply SRT0|eapply FIN|].\n            i. des. clarify.\n            rewrite SRT. rewrite Int.unsigned_repr; auto.\n          * des. exploit wf_at_final; [apply WFSEM|..]; et. ss.\n          * des. pclearbot.\n            exploit IH; et.\n            { eapply safe_along_events_step_none; et. unfold wf; i. rewrite ANG in SRT; ss. }\n            intro U.\n            eapply Beh.beh_dstep; ss; et.\n          * des. exploit wf_at_final; [apply WFSEM|..]; et. ss.\n          * destruct (classic (exists ev st_src2, step L0 st_src1 ev st_src2)).\n            { des. exploit wf_angelic; et. i; subst. exploit SIM; et. i; des.\n              pclearbot.\n              exploit IH; et.\n              { eapply safe_along_events_step_none; et. unfold wf; i. eapply DTM; eauto. }\n              i; des.\n              eapply _beh_astep_rev; ss; et. unfold wf; i. eapply DTM; eauto. }\n            contradict H. eapply SAFE0; et.\n            { econs; ss; et. }\n            { instantiate (1:=[]). ss. }\n            { esplits; ss. }\n          * des. exploit wf_at_final; [apply WFSEM|..]; et. ss.\n        + ss. clear.\n          induction tr; ii; ss.\n          { pfold. econs; ss; et. }\n          destruct (decompile_event a) eqn:T.\n          * des_ifs_safe.\n            eapply match_beh_cons; ss.\n            { instantiate (1:=Terminates tr r). instantiate (1:=a). ss. }\n            { ss. }\n            { eapply decompile_match_event; ss. }\n          * des_ifs_safe. ss. pfold; econsr; et; ss. r. esplits; et.\n            rewrite behavior_app_E0; et.\n\n      - (* diverge *)\n        (rename t into tr).\n        esplits; et.\n        + rename H0 into BEH. ss.\n          ginit. { eapply cpn2_wcompat; eauto with paco. } revert_until WFSEM. gcofix CIH. i.\n          inv BEH.\n          rename s2 into st_tgt1. rename tr into tr_tgt. rename H into STAR.\n          hexploit simulation_star; try apply STAR; et.\n          { eapply SAFE. exists (Diverges []). ss. rewrite E0_right. auto. }\n          i; des.\n          rewrite MB.\n          guclo starC2_spec. econs; et.\n          gfinal. right. pfold. econs 2.\n          eapply sim_forever_silent; et. econs; et.\n        + ss. clear.\n          induction tr; ii; ss.\n          { pfold. econs 2; ss; et. }\n          destruct (decompile_event a) eqn:T.\n          * des_ifs_safe.\n            eapply match_beh_cons; ss.\n            { instantiate (1:=Diverges tr). instantiate (1:=a). ss. }\n            { ss. }\n            { eapply decompile_match_event; ss. }\n          * des_ifs_safe. ss. pfold; econsr; et; ss. r. esplits; et.\n            rewrite behavior_app_E0; et.\n\n      - (* forever_reactive *)\n        (rename T into tr).\n        esplits; et.\n        + rename H into BEH. ss.\n          ginit. { eapply cpn2_wcompat; eauto with paco. } revert_until WFSEM. gcofix CIH. i.\n          (* revert_until WFSRC. pcofix CIH. i. *)\n          inv BEH.\n          rename s2 into st_tgt1. rename t into tr_tgt. rename H into STAR.\n          hexploit simulation_star; try apply STAR; et.\n          { eapply SAFE. exists (Reacts T). ss. }\n          i; des.\n\n          erewrite decompile_trinf_app; et.\n\n          exploit CIH; et.\n          { clear - SAFE MB STEP. r. i. eapply safe_along_events_star; et.\n            eapply SAFE. r in BEH. des. r. exists beh'. rewrite behavior_app_assoc.\n            rewrite <- BEH. ss. }\n          intro KNOWLEDGE.\n          assert(PROG: tr_src <> []).\n          { ii; subst; ss. destruct tr_tgt; ss. des_ifs. }\n          clear - KNOWLEDGE PROG STEP.\n          induction STEP using star_event_ind; ss.\n          clear_tac. spc IHSTEP1.\n          eapply star_single_exact in STEP1. des.\n          guclo starC_spec. econs; et.\n          gstep. econs; et.\n          { destruct (state_sort L0 st3) eqn:SORT; auto.\n            - exfalso. hexploit wf_angelic; et; ss.\n            - exfalso. hexploit wf_demonic; et; ss.\n            - exfalso. hexploit wf_final; et; ss.\n          }\n          guclo starC_spec. econs; et.\n          destruct es; ss.\n          * guclo starC_spec. econs; et. gbase. et.\n          * exploit IHSTEP1; ss; et. intro U. eapply gpaco2_mon; et. ii; ss.\n        + eapply decompile_trinf_spec.\n\n      - (* goes wrong *)\n        (rename t into tr).\n        esplits; et.\n        + rename H0 into BEH. ss.\n          ginit. { eapply cpn2_wcompat; eauto with paco. } revert_until WFSEM. gcofix CIH. i.\n          hexploit simulation_star; try apply STAR; et.\n          { eapply SAFE. exists (Goes_wrong []). ss. rewrite E0_right. auto. }\n          i; des.\n          rewrite MB.\n          guclo starC2_spec. econs; et.\n          gfinal. right. eapply paco2_mon.\n          { eapply sim_goes_wrong; et. }\n          { ss. }\n        + ss. clear.\n          induction tr; ii; ss.\n          { pfold. econs 4; ss; et. ss. exists (Goes_wrong []). ss. }\n          destruct (decompile_event a) eqn:T.\n          * des_ifs_safe.\n            eapply match_beh_cons; ss.\n            { instantiate (1:=Goes_wrong tr). instantiate (1:=a). ss. }\n            { ss. }\n            { eapply decompile_match_event; ss. }\n          * des_ifs_safe. ss. pfold; econsr; et; ss. r. esplits; et.\n            rewrite behavior_app_E0; et.\n    }\n    { (*** unsafe ***)\n      assert(NOTSAFE:\n               exists st_src1 thd thd_tgt,\n                 (<<B: behavior_prefix thd_tgt tr_tgt>>)\n                 /\\ (<<MB: squeeze (List.map decompile_event thd_tgt) = (thd, true)>>)\n                 /\\ (<<STAR: star L0 st_src0 thd st_src1>>)\n                 /\\ (<<STUCK: ~NoStuck L0 st_src1>>)).\n      { unfold safe_along_trace in SAFE. Psimpl. des.\n        unfold safe_along_events in *. Psimpl. des.\n        Psimpl. des. Psimpl. des.\n        subst.\n        esplits; try apply SAFE1; ss; et.\n        clear - SAFE.\n        r in SAFE. des; subst. r. eexists (behavior_app _ _).\n        rewrite <- behavior_app_assoc. ss; et.\n      }\n      des.\n      exists (Tr.app thd Tr.ub). esplits; ss.\n      - clear - STAR STUCK.\n        eapply beh_of_state_star; et. unfold NoStuck in *.\n        repeat (Psimpl; des; unfold NW in *). clears st_src0. clear st_src0.\n        pfold. econsr; ss; et. ii. exploit wf_angelic; ss; et. i; subst. exfalso.\n        exploit STUCK0; ss; et.\n      - r in B. des. subst. clear - MB.\n        ginduction thd_tgt; ii; ss; clarify.\n        { ss. pfold. econsr; ss; et.\n          { r. esplits; ss; et. }\n        }\n        des_ifs. ss.\n        eapply match_event_iff in Heq.\n        eapply match_beh_cons; ss; et. rewrite <- behavior_app_assoc. ss.\n    }\n  Qed.\n\nEnd SIM.\nHint Constructors _sim.\nHint Unfold sim.\nHint Resolve sim_mon: paco.\n", "meta": {"author": "alxest", "repo": "CCR", "sha": "edcda8faae6580581e8e5b28050d755bcb29f55f", "save_path": "github-repos/coq/alxest-CCR", "path": "github-repos/coq/alxest-CCR/CCR-edcda8faae6580581e8e5b28050d755bcb29f55f/imp/compiler_proof/SimSTS2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.27778513989836373}}
{"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\nRequire Import Event.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import Behavior.\n\nSet Implicit Arguments.\n\n\nSection Simulation.\n  Definition SIM := forall (c1_src c1_tgt: Configuration.t), Prop.\n\n  Definition _sim (sim: SIM) (c1_src c1_tgt:Configuration.t): Prop :=\n    forall (WF_SRC: Configuration.wf c1_src)\n      (WF_TGT: Configuration.wf c1_tgt),\n      <<TERMINAL:\n        forall (TERMINAL_TGT: Threads.is_terminal (Configuration.threads c1_tgt)),\n        exists c2_src,\n          <<STEPS_SRC: rtc Configuration.tau_step c1_src c2_src>> /\\\n          <<TERMINAL_SRC: Threads.is_terminal (Configuration.threads c2_src)>>>> /\\\n      <<STEP:\n        forall e tid c2_tgt\n          (STEP_TGT: Configuration.step e tid c1_tgt c2_tgt),\n        exists c2_src,\n          <<STEP_SRC: Configuration.opt_step e tid c1_src c2_src>> /\\\n          <<SIM: sim c2_src c2_tgt>>>>\n  .\n\n  Lemma _sim_mon: monotone2 _sim.\n  Proof.\n    ii. exploit IN; eauto. i. des.\n    econs; eauto. ii.\n    exploit STEP; eauto. i. des. eauto.\n  Qed.\n  Hint Resolve _sim_mon: paco.\n\n  Definition sim: SIM := paco2 _sim bot2.\nEnd Simulation.\nHint Resolve _sim_mon: paco.\n\n\nLemma sim_adequacy\n      c_src c_tgt\n      (WF_SRC: Configuration.wf c_src)\n      (WF_TGT: Configuration.wf c_tgt)\n      (SIM: sim c_src c_tgt):\n  behaviors Configuration.step c_tgt <1= behaviors Configuration.step c_src.\nProof.\n  i. revert c_src WF_SRC WF_TGT SIM.\n  induction PR; i.\n  - punfold SIM0. exploit SIM0; eauto. i. des.\n    hexploit TERMINAL0; eauto. i. des.\n    eapply rtc_tau_step_behavior; eauto.\n    econs 1. eauto.\n  - punfold SIM0. exploit SIM0; eauto. i. des.\n    exploit STEP0; eauto. i. des.\n    exploit Configuration.step_future; try exact STEP; eauto. i. des.\n    exploit Configuration.opt_step_future; try exact STEP_SRC; eauto. i. des.\n    inv SIM1; ss. inv STEP_SRC.\n    econs 2; eauto.\n  - punfold SIM0. exploit SIM0; eauto. i. des.\n    exploit STEP0; eauto. i. des.\n    exploit Configuration.step_future; try exact STEP; eauto. i. des.\n    exploit Configuration.opt_step_future; try exact STEP_SRC; eauto. i. des.\n    inv SIM1; ss. inv STEP_SRC.\n    econs 3; eauto.\n  - punfold SIM0. exploit SIM0; eauto. i. des.\n    exploit STEP0; eauto. i. des.\n    exploit Configuration.step_future; try exact STEP; eauto. i. des.\n    exploit Configuration.opt_step_future; try exact STEP_SRC; eauto. i. des.\n    inv SIM1; ss. inv STEP_SRC; eauto.\n    econs 4; 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/SimpleSimulation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2776866489885571}}
{"text": "From trace_program_logic.prelude Require Import classical.\nFrom trace_program_logic.traces Require Import trace.\nFrom trace_program_logic.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": "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/trace_program_logic/theories/events/event.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2776866432179873}}
{"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 AST.\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_shift_correct:\n  forall s n, eval_shift s (Vint n) = Vint (eval_static_shift s n).\nProof.\n  intros. destruct s; simpl; rewrite s_range; auto.\nQed.\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; try (rewrite eval_static_shift_correct); 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\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); try (rewrite eval_static_shift_correct); auto.\n  destruct (propagate_float_constants tt); simpl; auto.\n  rewrite shift_symbol_address; auto. \n  rewrite shift_symbol_address; auto.\n  rewrite Val.add_assoc; auto.\n  rewrite Val.add_assoc; auto.\n  fold (Val.add (Vint n1) (symbol_address ge s2 n2)).\n  rewrite Int.add_commut. rewrite Val.add_commut. rewrite shift_symbol_address; auto.\n  fold (Val.add (Vint n1) (Val.add sp (Vint n2))). \n  rewrite Val.add_permut. auto.\n  rewrite shift_symbol_address. auto.\n  rewrite Val.add_assoc. auto.\n  rewrite Int.sub_add_opp. rewrite shift_symbol_address. rewrite Val.sub_add_opp. auto.\n  rewrite Val.sub_add_opp. rewrite Val.add_assoc. rewrite Int.sub_add_opp. 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.ltu n2 Int.iwordsize); simpl; auto.\n  destruct (Int.ltu n2 Int.iwordsize); simpl; auto.\n  destruct (Int.ltu n2 Int.iwordsize); simpl; auto.\n  unfold eval_static_intoffloat. destruct (Float.intoffloat n1); simpl in H0; inv H0; simpl; auto.\n  unfold eval_static_intuoffloat. destruct (Float.intuoffloat n1); simpl in H0; inv H0; simpl; auto.\n  destruct (propagate_float_constants tt); simpl; auto.\n  destruct (propagate_float_constants tt); simpl; auto.\n  unfold eval_static_condition_val, Val.of_optbool.\n  destruct (eval_static_condition c vl0) eqn:?.\n  rewrite (eval_static_condition_correct _ _ _ m _ H Heqo).\n  destruct b; simpl; auto. \n  simpl; 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); try (rewrite eval_static_shift_correct); 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. apply Val.add_commut.\n  repeat rewrite Val.add_assoc. auto.\n  fold (Val.add (Vint n1) (Val.add sp (Vint ofs))).\n  rewrite Val.add_permut. decEq. rewrite Val.add_commut. auto.\n  rewrite shift_symbol_address. auto.\n  rewrite Val.add_assoc. 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  rewrite H. rewrite eval_static_shift_correct. auto.\n  rewrite H. rewrite eval_static_shift_correct. auto.\n  auto.\n  destruct (Float.eq_dec n1 Float.zero); simpl; auto.\n  rewrite H0; subst n1. destruct (rs#r2); simpl; auto. rewrite Float.cmp_swap. auto.\n  destruct (Float.eq_dec n2 Float.zero); simpl; auto.\n  congruence.\n  destruct (Float.eq_dec n1 Float.zero); simpl; auto.\n  rewrite H0; subst n1. destruct (rs#r2); simpl; auto. rewrite Float.cmp_swap. auto.\n  destruct (Float.eq_dec n2 Float.zero); simpl; auto.\n  congruence.\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 r2,\n  rs#r2 = Vint n ->\n  let (op, args) := make_shlimm n r1 r2 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  Opaque mk_shift_amount.\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  destruct (Int.ltu n Int.iwordsize) eqn:?; intros.\n  econstructor; split. simpl; eauto.  rewrite mk_shift_amount_eq; auto. \n  econstructor; split; eauto. simpl. congruence.\nQed.\n\nLemma make_shrimm_correct:\n  forall n r1 r2,\n  rs#r2 = Vint n ->\n  let (op, args) := make_shrimm n r1 r2 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  destruct (Int.ltu n Int.iwordsize) eqn:?; intros.\n  econstructor; split. simpl; eauto.  rewrite mk_shift_amount_eq; auto. \n  econstructor; split; eauto. simpl. congruence.\nQed.\n\nLemma make_shruimm_correct:\n  forall n r1 r2,\n  rs#r2 = Vint n ->\n  let (op, args) := make_shruimm n r1 r2 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  destruct (Int.ltu n Int.iwordsize) eqn:?; intros.\n  econstructor; split. simpl; eauto.  rewrite mk_shift_amount_eq; auto. \n  econstructor; split; eauto. simpl. congruence.\nQed.\n\nLemma make_mulimm_correct:\n  forall n r1 r2,\n  rs#r2 = Vint n ->\n  let (op, args) := make_mulimm n r1 r2 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  exploit Int.is_power2_range; eauto. intros R.\n  econstructor; split. simpl; eauto. rewrite mk_shift_amount_eq; auto.  \n  rewrite (Val.mul_pow2 rs#r1 _ _ Heqo). auto.\n  econstructor; split; eauto. simpl. congruence.\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  econstructor; split. simpl. rewrite mk_shift_amount_eq. eauto. \n  eapply Int.is_power2_range; eauto. auto.\n  eapply Val.divu_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  predSpec Int.eq Int.eq_spec n Int.mone; intros.\n  subst n. exists (Val.notint (rs#r)); split. auto.\n  destruct (rs#r); simpl; 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(* add *)\n  InvApproxRegs. SimplVMA. inv H0. rewrite H1. rewrite Val.add_commut. apply make_addimm_correct.\n  InvApproxRegs. SimplVMA. inv H0. rewrite H. apply make_addimm_correct.\n(* addshift *)\n  InvApproxRegs. SimplVMA. inv H0. rewrite H. rewrite eval_static_shift_correct. apply make_addimm_correct.\n(* sub *)\n  InvApproxRegs; SimplVMA. inv H0. rewrite H1. econstructor; split; eauto. \n  InvApproxRegs; SimplVMA. inv H0. rewrite H. rewrite Val.sub_add_opp. apply make_addimm_correct.\n(* subshift *)\n  InvApproxRegs; SimplVMA. inv H0. rewrite H. rewrite eval_static_shift_correct. rewrite Val.sub_add_opp. apply make_addimm_correct.\n(* rsubshift *)\n  InvApproxRegs; SimplVMA. inv H0. rewrite H. rewrite eval_static_shift_correct. econstructor; split; eauto.\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(* and *)\n  InvApproxRegs. SimplVMA. inv H0. rewrite H1. rewrite Val.and_commut. apply make_andimm_correct.\n  InvApproxRegs. SimplVMA. inv H0. rewrite H. apply make_andimm_correct.\n(* andshift *)\n  InvApproxRegs. SimplVMA. inv H0. rewrite H. rewrite eval_static_shift_correct. apply make_andimm_correct.\n(* or *)\n  InvApproxRegs. SimplVMA. inv H0. rewrite H1. rewrite Val.or_commut. apply make_orimm_correct.\n  InvApproxRegs. SimplVMA. inv H0. rewrite H. apply make_orimm_correct.\n(* orshift *)\n  InvApproxRegs. SimplVMA. inv H0. rewrite H. rewrite eval_static_shift_correct. apply make_orimm_correct.\n(* xor *)\n  InvApproxRegs. SimplVMA. inv H0. rewrite H1. rewrite Val.xor_commut. apply make_xorimm_correct.\n  InvApproxRegs. SimplVMA. inv H0. rewrite H. apply make_xorimm_correct.\n(* xorshift *)\n  InvApproxRegs. SimplVMA. inv H0. rewrite H. rewrite eval_static_shift_correct. apply make_xorimm_correct.\n(* bic *)\n  InvApproxRegs. SimplVMA. inv H0. rewrite H. apply make_andimm_correct.\n(* bicshift *)\n  InvApproxRegs. SimplVMA. inv H0. rewrite H. rewrite eval_static_shift_correct. apply make_andimm_correct.\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(* cmp *)\n  generalize (cond_strength_reduction_correct c args0 vl0). \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 \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 H; rewrite H0. rewrite Val.add_assoc; auto.\n  rewrite H; rewrite H0. rewrite Val.add_permut; auto. \n  rewrite H0. rewrite Val.add_commut. auto.\n  rewrite H. auto.\n  rewrite H; rewrite H0. rewrite Val.add_assoc. rewrite eval_static_shift_correct. auto.\n  rewrite H. rewrite eval_static_shift_correct. auto.\n  rewrite H. rewrite Val.add_assoc. auto.\n  auto.\nQed.\n\nEnd STRENGTH_REDUCTION.\n\nEnd ANALYSIS.\n", "meta": {"author": "PrincetonUniversity", "repo": "compcomp", "sha": "eebb7d5a95fed97775cef7f014399be78abbe7bf", "save_path": "github-repos/coq/PrincetonUniversity-compcomp", "path": "github-repos/coq/PrincetonUniversity-compcomp/compcomp-eebb7d5a95fed97775cef7f014399be78abbe7bf/arm/ConstpropOpproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2776401202318738}}
{"text": "From Undecidability.Shared.Libs.PSL Require Import Vectors VectorForall.\nRequire Import Undecidability.SOL.SOL.\nFrom Undecidability.SOL.Util Require Import Subst Syntax.\nRequire Import Arith Lia Vector.\n\nImport SubstNotations.\nUnset Implicit Arguments.\n\nSet Default Proof Using \"Type\".\n\nArguments eval_function {_ _ _ _ _}.\nArguments eval_predicate {_ _ _ _ _}.\nArguments eval {_ _ _ _}.\nArguments sat {_ _ _ _}.\nArguments new_env {_} _ _ _.\nArguments get_indi {_} _ _.\nArguments get_func {_} _ _.\nArguments get_pred {_} _ _.\n\nNotation \"⟨ a , b , c ⟩\" := (new_env a b c).\n\n(* Type class for ⊨ notations *)\nClass Ent X Y `{funcs_signature, preds_signature} := ent : X -> Y -> Prop.\nNotation \"X ⊨ phi\" := (ent X phi) (at level 20).\nClass Ent' X `{funcs_signature, preds_signature} := ent' : forall M : Model, env (M_domain M) -> X -> Prop.\nNotation \"( M , rho ) ⊨ phi\" := (ent' M rho phi) (at level 0).\n\n#[global] Instance ent_env `{funcs_signature, preds_signature} domain I : Ent (env domain) form := \n  @sat _ _ domain I.\n#[global] Instance ent'_form `{funcs_signature, preds_signature} : Ent' form :=\n  fun M rho phi => @sat _ _ (M_domain M) (M_interp M) rho phi.\n#[global] Instance ent_model `{funcs_signature, preds_signature} : Ent Model form := \n  fun M phi => forall rho, @sat _ _ (M_domain M) (M_interp M) rho phi.\n#[global] Instance ent_model_theory `{funcs_signature, preds_signature} : Ent Model (form -> Prop) := \n  fun M T => forall phi, T phi -> M ⊨ phi.\n#[global] Instance ent_theory `{funcs_signature, preds_signature} : Ent (form -> Prop) form := \n  fun T phi => forall (M : Model) rho, (forall psi, T psi -> (M, rho) ⊨ psi) -> (M, rho) ⊨ phi.\n#[global] Instance ent'_theory `{funcs_signature, preds_signature} : Ent' (form -> Prop) :=\n  fun M rho T => forall phi, T phi -> (M, rho) ⊨ phi.\n#[global] Instance ent'_form' `{funcs_signature, preds_signature} : Ent' form :=\n  fun M rho phi => @sat _ _ (M_domain M) (M_interp M) rho phi.\n\n\nSection Environment.\n\n  Variable domain : Type.\n\n  Definition env_equiv (rho1 : env domain) rho2 := forall n,\n        get_indi rho1 n = get_indi rho2 n\n    /\\ forall ar v, get_func rho1 n ar v = get_func rho2 n ar v\n                /\\ (get_pred rho1 n ar v <-> get_pred rho2 n ar v).\n  Notation \"rho1 ≡ rho2\" := (env_equiv rho1 rho2) (at level 30).\n\n  Lemma env_equiv_symm rho1 rho2 :\n    rho1 ≡ rho2 -> rho2 ≡ rho1.\n  Proof.\n    intros H. intros n. specialize (H n). split. easy. \n    intros ar v. destruct H as [_ H]. specialize (H ar v). easy.\n  Qed.\n\n  Lemma env_equiv_cons_i rho1 rho2 x :\n  rho1 ≡ rho2 -> ⟨ x .: get_indi rho1, get_func rho1, get_pred rho1 ⟩ ≡ ⟨ x .: get_indi rho2, get_func rho2, get_pred rho2 ⟩.\n  Proof.\n    intros H n. split. 2:split. destruct n. all: firstorder.\n  Qed.\n\n  Lemma env_equiv_cons_f rho1 rho2 ar (f : vec domain ar -> domain) f' :\n    rho1 ≡ rho2 -> (forall v, f v = f' v) \n    -> ⟨ get_indi rho1, f .: get_func rho1, get_pred rho1 ⟩ ≡ ⟨ get_indi rho2, f' .: get_func rho2, get_pred rho2 ⟩.\n  Proof.\n    intros H Hf n. split. 2:split.\n    - apply H.\n    - destruct n; cbn; destruct (Nat.eq_dec ar ar0) as [->|]; firstorder.\n    - apply H.\n  Qed.\n\n  Lemma env_equiv_cons_p rho1 rho2 ar (P : vec domain ar -> Prop) :\n    rho1 ≡ rho2 -> ⟨ get_indi rho1, get_func rho1, P .: get_pred rho1 ⟩ ≡ ⟨ get_indi rho2, get_func rho2, P .: get_pred rho2 ⟩.\n  Proof.\n    intros H n. split. 2:split.\n    - apply H.\n    - apply H.\n    - destruct n; cbn; destruct (Nat.eq_dec ar ar0) as [->|]. all: firstorder.\n  Qed.\n\nEnd Environment.\n\nNotation \"rho1 ≡ rho2\" := (env_equiv _ rho1 rho2) (at level 30).\n\n\n\nSection SatExt.\n\n  Context {Σ_funcs : funcs_signature}.\n  Context {Σ_preds : preds_signature}.\n  Variable domain : Type.\n  Context {I : interp domain}.\n\n  Lemma eval_function_ext rho1 rho2 ar (f : function ar) :\n    (forall n ar v, get_func rho1 n ar v = get_func rho2 n ar v)\n      -> forall v, eval_function rho1 f v = eval_function rho2 f v.\n  Proof.\n    intros H v. destruct f; cbn. apply H. reflexivity.\n  Qed.\n\n  Lemma eval_predicate_ext rho1 rho2 ar (P : predicate ar) :\n    (forall n ar v, get_pred rho1 n ar v <-> get_pred rho2 n ar v)\n      -> forall v, eval_predicate rho1 P v <-> eval_predicate rho2 P v.\n  Proof.\n    intros H v. destruct P; cbn. apply H. reflexivity.\n  Qed.\n\n  Lemma eval_ext rho1 rho2 t :\n    (forall n, get_indi rho1 n = get_indi rho2 n) \n    -> (forall n ar v, get_func rho1 n ar v = get_func rho2 n ar v)\n    -> eval rho1 t = eval rho2 t.\n  Proof.\n    intros H1 H2. induction t.\n    - apply H1.\n    - cbn. enough (map (eval rho1) v = map (eval rho2) v) as -> by apply H2.\n      now apply map_ext_forall.\n    - cbn. f_equal. now apply map_ext_forall.\n  Qed.\n\n  Lemma sat_ext rho1 rho2 phi :\n    rho1 ≡ rho2 -> sat rho1 phi <-> sat rho2 phi.\n  Proof.\n    revert rho1 rho2. induction phi; cbn; intros rho1 rho2 H.\n    - easy.\n    - destruct p. \n      + rename t into v. enough (map (eval rho1) v = map (eval rho2) v) as <- by apply H.\n        apply map_ext. induction v; firstorder. apply eval_ext; apply H.\n      + rename t into v. enough (map (eval rho1) v = map (eval rho2) v) as <- by easy.\n        apply map_ext. induction v; firstorder. apply eval_ext; apply H.\n    - specialize (IHphi1 rho1 rho2); specialize (IHphi2 rho1 rho2).\n      destruct b; cbn; firstorder.\n    - destruct q; split; cbn.\n      + intros H1 x. eapply IHphi. 2: apply H1. now apply env_equiv_symm, env_equiv_cons_i.\n      + intros H1 x. eapply IHphi. 2: apply H1. now apply env_equiv_cons_i.\n      + intros [d H1]. exists d. eapply IHphi. 2: apply H1. now apply env_equiv_symm, env_equiv_cons_i.\n      + intros [d H1]. exists d. eapply IHphi. 2: apply H1. now apply env_equiv_cons_i.\n    - destruct q; split; cbn.\n      + intros H1 f. eapply IHphi. 2: apply H1. now apply env_equiv_symm, env_equiv_cons_f.\n      + intros H1 f. eapply IHphi. 2: apply H1. now apply env_equiv_cons_f.\n      + intros [f H1]. exists f. eapply IHphi. 2: apply H1. now apply env_equiv_symm, env_equiv_cons_f.\n      + intros [f H1]. exists f. eapply IHphi. 2: apply H1. now apply env_equiv_cons_f.\n    - destruct q; split; cbn.\n      + intros H1 P. eapply IHphi. 2: apply H1. now apply env_equiv_symm, env_equiv_cons_p.\n      + intros H1 P. eapply IHphi. 2: apply H1. now apply env_equiv_cons_p.\n      + intros [P H1]. exists P. eapply IHphi. 2: apply H1. now apply env_equiv_symm, env_equiv_cons_p.\n      + intros [P H1]. exists P. eapply IHphi. 2: apply H1. now apply env_equiv_cons_p.\n  Qed.\n\nEnd SatExt.\n\n\n\nSection BoundedSat.\n\n  Context {Σ_funcs : funcs_signature}.\n  Context {Σ_preds : preds_signature}.\n  Variable domain : Type.\n  Context {I : interp domain}.\n\n  Lemma sat_ext_bounded_term t rho sigma :\n    (forall x, ~ bounded_indi_term x t -> get_indi rho x = get_indi sigma x)\n    -> (forall x ar, ~ bounded_func_term ar x t -> get_func rho x ar = get_func sigma x ar)\n    -> eval rho t = eval sigma t.\n  Proof.\n    intros H1 H2. induction t; cbn.\n    - apply H1. cbn. lia.\n    - rewrite H2. f_equal. apply map_ext_in. intros t H. eapply Forall_in in IH.\n      apply IH. intros x H3. apply H1. cbn. intros H4. apply H3. eapply Forall_in in H4. \n      apply H4. trivial. intros x ar' H3. apply H2. cbn. intros [H4 H5]. apply H3. eapply Forall_in in H5.\n      apply H5. easy. easy. cbn. lia.\n    - f_equal. apply map_ext_in. intros t H. eapply Forall_in in IH.\n      apply IH. intros x H3. apply H1. cbn. intros H4. apply H3. eapply Forall_in in H4. \n      apply H4. trivial. intros x ar' H3. apply H2. cbn. intros H4. apply H3. eapply Forall_in in H4.\n      apply H4. easy. easy.\n  Qed.\n\n  Lemma sat_ext_bounded phi rho sigma :\n    (forall x, ~ bounded_indi x phi -> get_indi rho x = get_indi sigma x)\n    -> (forall x ar, ~ bounded_func ar x phi -> get_func rho x ar = get_func sigma x ar)\n    -> (forall x ar, ~ bounded_pred ar x phi -> get_pred rho x ar = get_pred sigma x ar)\n    -> sat rho phi <-> sat sigma phi.\n  Proof.\n    revert rho sigma. induction phi; cbn; intros rho sigma H1 H2 H3.\n    - reflexivity.\n    - erewrite map_ext_in with (g := eval sigma); revgoals.\n      intros ? H. apply sat_ext_bounded_term. intros x H4. apply H1. intros H5. apply H4.\n      eapply Forall_in in H5. apply H5. easy. intros x ar' H4. apply H2. intros H5. apply H4.\n      eapply Forall_in in H5. apply H5. easy. destruct p; cbn.\n      + rewrite H3. reflexivity. cbn. lia.\n      + reflexivity.\n    - specialize (IHphi1 rho sigma). specialize (IHphi2 rho sigma).\n      destruct b; cbn; setoid_rewrite IHphi1; try setoid_rewrite IHphi2; try reflexivity; clear IHphi1 IHphi2; firstorder.\n    - destruct q; split.\n      + intros H d. eapply IHphi. 4: apply (H d). intros []. all: firstorder.\n      + intros H d. eapply IHphi. 4: apply (H d). intros []. all: firstorder.\n      + intros [d H]. exists d. eapply IHphi. 4: apply H. intros []. all: firstorder.\n      + intros [d H]. exists d. eapply IHphi. 4: apply H. intros []. all: firstorder.\n    - destruct q; split.\n      + intros H f. eapply IHphi. 4: eapply (H f); trivial. 2: intros [] ar H4; cbn; destruct Nat.eq_dec as [->|]. all: firstorder.\n      + intros H f. eapply IHphi. 4: eapply (H f); trivial. 2: intros [] ar H4; cbn; destruct Nat.eq_dec as [->|]. all: firstorder.\n      + intros [f H]. exists f. eapply IHphi. 4: eapply H; trivial. 2: intros [] ar H4; cbn; destruct Nat.eq_dec as [->|]. all: firstorder.\n      + intros [f H]. exists f. eapply IHphi. 4: eapply H; trivial. 2: intros [] ar H4; cbn; destruct Nat.eq_dec as [->|]. all: firstorder.\n    - destruct q; split.\n      + intros H P. eapply IHphi. 4: eapply (H P); trivial. 3: intros [] ar H4; cbn; destruct Nat.eq_dec as [->|]. all: firstorder.\n      + intros H P. eapply IHphi. 4: eapply (H P); trivial. 3: intros [] ar H4; cbn; destruct Nat.eq_dec as [->|]. all: firstorder.\n      + intros [P H]. exists P. eapply IHphi. 4: eapply H; trivial. 3: intros [] ar H4; cbn; destruct Nat.eq_dec as [->|]. all: firstorder.\n      + intros [P H]. exists P. eapply IHphi. 4: eapply H; trivial. 3: intros [] ar H4; cbn; destruct Nat.eq_dec as [->|]. all: firstorder.\n  Qed.\n\n  Lemma sat_ext_closed phi rho sigma :\n    bounded_indi 0 phi -> (forall ar, bounded_func ar 0 phi) -> (forall ar, bounded_pred ar 0 phi) \n    -> (sat rho phi <-> sat sigma phi).\n  Proof.\n    intros Bi Bf Bp. apply sat_ext_bounded.\n    - intros x H. exfalso. apply H. eapply bounded_indi_up. 2: apply Bi. lia.\n    - intros x ar H. exfalso. apply H. eapply bounded_func_up. 2: apply Bf. lia.\n    - intros x ar H. exfalso. apply H. eapply bounded_pred_up. 2: apply Bp. lia.\n  Qed.\n\n  Lemma sat_ext_closed_funcfree phi rho sigma :\n    funcfree phi -> bounded_indi 0 phi -> (forall ar, bounded_pred ar 0 phi) \n    -> (sat rho phi <-> sat sigma phi).\n  Proof.\n    intros F Bi Bp. apply sat_ext_bounded.\n    - intros x H. exfalso. apply H. eapply bounded_indi_up. 2: apply Bi. lia.\n    - intros x ar H. exfalso. apply H. apply funcfree_bounded_func, F.\n    - intros x ar H. exfalso. apply H. eapply bounded_pred_up. 2: apply Bp. lia.\n  Qed.\n\n  Lemma sat_ext_closed_FO phi rho sigma :\n    first_order phi -> bounded_indi 0 phi -> (sat rho phi <-> sat sigma phi).\n  Proof.\n    intros F B. apply sat_ext_bounded.\n    - intros x H. exfalso. apply H. eapply bounded_indi_up. 2: apply B. lia.\n    - intros x ar H. exfalso. apply H. apply funcfree_bounded_func, firstorder_funcfree, F.\n    - intros x ar H. exfalso. apply H. apply firstorder_bounded_pred, F.\n  Qed.\n\nEnd BoundedSat.\n\n\n\n\nSection Subst.\n\n  Context {Σ_funcs : funcs_signature}.\n  Context {Σ_preds : preds_signature}.\n  Variable domain : Type.\n  Context {I : interp domain}.\n\n  Lemma eval_function_subst_cons_shift_f (rho : env domain) ar (f : function ar) ar' (g : vec domain ar' -> domain) :\n    eval_function rho f = eval_function ⟨ get_indi rho, g .: get_func rho, get_pred rho ⟩ (f[↑ ar']f).\n  Proof.\n    destruct f.\n    - unfold econs, econs_func, econs_ar, shift, shift_f; cbn.\n      destruct Nat.eq_dec as [->|]; cbn. now destruct Nat.eq_dec.\n      destruct n. destruct Nat.eq_dec; try easy. now destruct Nat.eq_dec.\n    - reflexivity.\n  Qed.\n\n  Lemma eval_predicate_subst_cons_shift_p (rho : env domain) ar (P : predicate ar) ar' (Q : vec domain ar' -> Prop) :\n    eval_predicate rho P = eval_predicate ⟨ get_indi rho, get_func rho, Q .: get_pred rho ⟩ (P[↑ ar']p).\n  Proof.\n    destruct P.\n    - unfold econs, econs_pred, econs_ar, shift, shift_p; cbn.\n      destruct Nat.eq_dec as [->|]; cbn. now destruct Nat.eq_dec.\n      destruct n. destruct Nat.eq_dec; try easy. now destruct Nat.eq_dec.\n    - reflexivity.\n  Qed.\n\n  Lemma eval_subst_cons_shift_f (rho : env domain) ar (f : vec domain ar -> domain) t :\n    eval rho t = eval ⟨get_indi rho, f .: get_func rho, get_pred rho⟩ t[↑ ar]f.\n  Proof.\n    induction t; cbn [eval].\n    - reflexivity.\n    - rewrite eval_function_subst_cons_shift_f with (g := f).\n      cbn. f_equal. rewrite map_map. apply map_ext_forall, IH.\n    - cbn. f_equal. rewrite map_map. apply map_ext_forall, IH.\n  Qed.\n\n  Lemma eval_comp_i (rho : env domain) σ t :\n    eval rho (t[σ]i) = eval ⟨σ >> eval rho, get_func rho, get_pred rho⟩ t.\n  Proof.\n    induction t; cbn. reflexivity. all: f_equal; rewrite map_map; apply map_ext_forall, IH.\n  Qed.\n\n  Lemma eval_comp_f (rho : env domain) σ t :\n    eval rho (t[σ]f) = eval ⟨get_indi rho, σ >>> eval_function rho, get_pred rho⟩ t.\n  Proof.\n    induction t; cbn. reflexivity. all: f_equal; rewrite map_map; apply map_ext_forall, IH.\n  Qed.\n\n  Lemma sat_comp_i rho σ phi :\n    sat rho (phi[σ]i) <-> sat ⟨σ >> eval rho, get_func rho, get_pred rho⟩ phi.\n  Proof.\n    induction phi in rho, σ |- *; cbn.\n    - reflexivity.\n    - destruct p; cbn; erewrite map_map, map_ext; try reflexivity;\n      induction t; firstorder using eval_comp_i.\n    - specialize (IHphi1 rho σ); specialize (IHphi2 rho σ).\n      destruct b; cbn; firstorder.\n    - destruct q.\n      + setoid_rewrite IHphi. split; intros H d; eapply sat_ext.\n        2, 4: apply (H d). all: intros []; split; try easy;\n        cbn; erewrite eval_comp_i; now destruct rho.\n      + setoid_rewrite IHphi. split; intros [d H]; exists d; eapply sat_ext.\n        2, 4: apply H. all: intros []; split; try easy;\n        cbn; erewrite eval_comp_i; now destruct rho.\n    - destruct q.\n      + setoid_rewrite IHphi; split; intros H f; eapply sat_ext.\n        2, 4: apply (H f). all: split; try easy. 2: symmetry.\n        all: apply eval_subst_cons_shift_f.\n      + setoid_rewrite IHphi; split; intros [f H]; exists f; eapply sat_ext.\n        2, 4: apply H. all: split; try easy. 2: symmetry.\n        all: apply eval_subst_cons_shift_f.\n    - destruct q.\n      + setoid_rewrite IHphi; split; intros H P; eapply sat_ext.\n        2, 4: apply (H P). all: split; try easy; now apply eval_ext.\n      + setoid_rewrite IHphi; split; intros [P H]; exists P; eapply sat_ext.\n        2, 4: apply H. all: split; try easy; now apply eval_ext.\n  Qed.\n\n  Lemma sat_comp_f rho σ phi :\n    sat rho (phi[σ]f) <-> sat ⟨get_indi rho, σ >>> eval_function rho, get_pred rho⟩ phi.\n  Proof.\n    induction phi in rho, σ |- *; cbn.\n    - reflexivity.\n    - destruct p; cbn; erewrite map_map, map_ext; try reflexivity;\n      induction t; firstorder using eval_comp_f.\n    - specialize (IHphi1 rho σ); specialize (IHphi2 rho σ).\n      destruct b; cbn; firstorder.\n    - destruct q.\n      + setoid_rewrite IHphi. split; intros H d; eapply sat_ext.\n        2, 4: apply (H d). all: easy.\n      + setoid_rewrite IHphi. split; intros [d H]; exists d; eapply sat_ext.\n        2, 4: apply H. all: easy.\n    - destruct q.\n      + setoid_rewrite IHphi; split; intros H f; eapply sat_ext.\n        2, 4: apply (H f). \n        all: intros []; repeat split; try easy; cbn; destruct Nat.eq_dec as [->|]; cbn.\n        1, 5: destruct Nat.eq_dec; try easy; rewrite Eqdep_dec.UIP_dec with (p1 := e) (p2 := eq_refl); try easy; decide equality.\n        1-3: now rewrite eval_function_subst_cons_shift_f with (g := f).\n        all: now rewrite <- eval_function_subst_cons_shift_f with (g := f).\n      + setoid_rewrite IHphi; split; intros [f H]; exists f; eapply sat_ext.\n        2, 4: apply H.\n        all: intros []; repeat split; try easy; cbn; destruct Nat.eq_dec as [->|]; cbn.\n        1, 5: destruct Nat.eq_dec; try easy; rewrite Eqdep_dec.UIP_dec with (p1 := e) (p2 := eq_refl); try easy; decide equality.\n        1-3: now rewrite eval_function_subst_cons_shift_f with (g := f).\n        all: now rewrite <- eval_function_subst_cons_shift_f with (g := f).\n    - destruct q.\n      + setoid_rewrite IHphi; split; intros H P; eapply sat_ext.\n        2, 4: apply (H P). all: intros; split; try easy; now apply eval_ext.\n      + setoid_rewrite IHphi; split; intros [P H]; exists P; eapply sat_ext.\n        2, 4: apply H. all: intros; split; try easy; now apply eval_ext.\n  Qed.\n\n  Lemma sat_comp_p rho σ phi :\n    sat rho (phi[σ]p) <-> sat ⟨get_indi rho, get_func rho, σ >>> eval_predicate rho⟩ phi.\n  Proof.\n    induction phi in rho, σ |- *; cbn.\n    - reflexivity.\n    - destruct p; cbn; rename t into v;\n      enough (map (eval rho) v = map (eval ⟨get_indi rho, get_func rho, σ >>> eval_predicate rho⟩) v) as -> by reflexivity;\n      apply map_ext_forall; induction v; firstorder; now apply eval_ext.\n    - specialize (IHphi1 rho σ); specialize (IHphi2 rho σ).\n      destruct b; cbn; firstorder.\n    - destruct q.\n      + setoid_rewrite IHphi. split; intros H d; eapply sat_ext.\n        2, 4: apply (H d). all: easy.\n      + setoid_rewrite IHphi. split; intros [d H]; exists d; eapply sat_ext.\n        2, 4: apply H. all: easy.\n    - destruct q.\n      + setoid_rewrite IHphi. split; intros H f; eapply sat_ext.\n        2, 4: apply (H f). all: easy.\n      + setoid_rewrite IHphi. split; intros [f H]; exists f; eapply sat_ext.\n        2, 4: apply H. all: easy.\n    - destruct q.\n      + setoid_rewrite IHphi; split; intros H P; eapply sat_ext.\n        2, 4: apply (H P). \n        all: intros []; split; try easy; split; try easy; cbn; destruct Nat.eq_dec as [->|]; cbn.\n        1, 5: destruct Nat.eq_dec; try easy; rewrite Eqdep_dec.UIP_dec with (p1 := e) (p2 := eq_refl); try easy; decide equality.\n        1-3: now rewrite eval_predicate_subst_cons_shift_p with (Q := P).\n        all: now rewrite <- eval_predicate_subst_cons_shift_p with (Q := P).\n      + setoid_rewrite IHphi; split; intros [P H]; exists P; eapply sat_ext.\n        2, 4: apply H. \n        all: intros []; split; try easy; split; try easy; cbn; destruct Nat.eq_dec as [->|]; cbn.\n        1, 5: destruct Nat.eq_dec; try easy; rewrite Eqdep_dec.UIP_dec with (p1 := e) (p2 := eq_refl); try easy; decide equality.\n        1-3: now rewrite eval_predicate_subst_cons_shift_p with (Q := P).\n        all: now rewrite <- eval_predicate_subst_cons_shift_p with (Q := P).\n  Qed.\n\nEnd Subst.\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/SOL/Util/Tarski.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.27764011273100625}}
{"text": "\n(*Require Import Coq.Logic.FunctionalExtensionality.*)\nRequire Import Coq.Logic.Eqdep.\n\nRequire Import CatSem.AXIOMS.functional_extensionality.\n\nRequire Export CatSem.CAT.retype_functor. \nRequire Export CatSem.CAT.ind_potype.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Transparent Obligations.\nUnset Automatic Introduction.\n\n(** define an order on the retyped V, dependent on order on V *)\n\nSection retype_ord.\n\nVariables T U : Type.\nVariable f : T -> U.\n\nInductive retype_ord (V : IPO T) : forall u, relation (retype f V (u)) :=\n  | ctype_ord : forall t (x y : V t), x <<< y \n            -> retype_ord  (ctype f x) (ctype f y).\n\nProgram Instance retype_ipo_s (V : IPO T) : \n      ipo_obj_struct (retype f V) := {\n  IRel := @retype_ord V\n}.\nNext Obligation.\nProof.\n  constructor.\n  unfold Reflexive.\n  intro x;\n  destruct x as [t x].\n  constructor.\n  apply IRel_refl.\n\n  unfold Transitive.\n  intros x y z H1 H2.\n  generalize dependent z.\n  induction H1.\n  intros z H'.\n  \n  inversion H'.\n  subst.\n  assert (H44:=inj_pair2 _ _ _ _ _ H4).\n  assert (H55:=inj_pair2 _ _ _ _ _ H5).\n  subst.\n  constructor.\n  transitivity y; auto.\nQed.\n\nDefinition retype_ipo V : IPO U := Build_ipo_obj (retype_ipo_s V).\n\nSection retype_po_hom.\n\nVariables V W : IPO T.\nVariable m : V ---> W.\n\nProgram Instance ret_po_mor_s : ipo_mor_struct \n    (a:=retype_ipo V) (b:=retype_ipo W) (retype_map m).\nNext Obligation.\nProof.\n  unfold Proper;\n  red.\n  intros x y H.\n  induction H.\n  simpl.\n  constructor.\n  apply m.\n  auto.\nQed.\n\nDefinition retype_po_mor := Build_ipo_mor ret_po_mor_s.\n\nEnd retype_po_hom.\n\nObligation Tactic := idtac.\n\nProgram Instance retype_po_func : \n    Functor_struct (Fobj := retype_ipo) retype_po_mor.\nNext Obligation.\nProof.\n  intros a b.\n  unfold Proper;\n  red.\n  intros g g' H t z.\n  destruct z as [t z];\n  simpl.\n  rewrite H;\n  auto.\nQed.\nNext Obligation.\nProof.\n  simpl.\n  intros a t z.\n  destruct z as [t z];\n  auto.\nQed.\nNext Obligation.\nProof.\n  simpl.\n  intros a b c g g' t z;\n  destruct z as [t z];\n  auto.\nQed.\n\nDefinition RETYPE_PO := Build_Functor retype_po_func.\n  \nEnd retype_ord.\n\n(** now natural transformations with SM_ipo *)\nSection nattrans.\n\nVariables T U : Type.\nVariable f : T -> U.\n\n(*\nDefinition bla2 c:\n(forall t : U,\n  (sm_ipo (T:=U) (retype f c)) t -> (retype_ipo f (sm_ipo (T:=T) c)) t) .\nintros c t x.\nsimpl in *.\napply x.\n*)\n\nProgram Instance id_ccs c :\nipo_mor_struct \n (a:=sm_ipo (T:=U) (retype f c)) \n (b:=retype_ipo f (sm_ipo (T:=T) c)) (fun t x => x).\nNext Obligation.\nProof.\n  unfold Proper.\n  red.\n  intros x y H.\n  induction H.\n  apply retype_ipo_s.\nQed.\n\nDefinition id_cc c := Build_ipo_mor (id_ccs c).\n\nProgram Instance RT_NTs : NT_struct\n    (F:=IDelta U O RETYPE f) \n    (G:=RETYPE_PO f O IDelta T) \n    (fun c => id_cc c).\n\nDefinition RT_NT := Build_NT RT_NTs.\n\nProgram Instance id_dds c :\nipo_mor_struct \n (b:=sm_ipo (T:=U) (retype f c)) \n (a:=retype_ipo f (sm_ipo (T:=T) c)) (fun t x => x).\nNext Obligation.\nProof.\n  unfold Proper;\n  red.\n  intros x y H.\n  induction H.\n  simpl.\n  induction H.\n  constructor.\nQed.\n\nDefinition id_dd c := Build_ipo_mor (id_dds c).\n\nProgram Instance NNNT2s : NT_struct\n    (G:=IDelta U O RETYPE f) \n    (F:=RETYPE_PO f O IDelta T) \n    (fun c => id_dd c).\n\nDefinition NNNT2 := Build_NT NNNT2s.\n\nEnd nattrans.\n\nSection Transp_po.\n\nVariables U U': Type.\nVariables f g : U -> U'.\nHypothesis H : forall t, g t = f t.\n\nObligation Tactic := idtac.\n\nProgram Instance transp_po_s (V : IPO U) :\n  ipo_mor_struct (a:=RETYPE_PO (fun t : U => f t) V)\n                 (b:=RETYPE_PO (fun t : U => g t) V) \n          (transp H (V:=V)).\nNext Obligation.\nProof.\n  intros V t.\n  assert (Ha : f = g) by\n    (apply functional_extensionality; auto).\n  unfold Proper;\n  red.\n  unfold transp.\n  subst.\n  intros x y H'.\n  induction H';\n  simpl.\n  rewrite (UIP_refl _ _ (H t)).\n  simpl.\n  constructor;\n  auto.\nQed.\n\nDefinition transp_po : forall V : IPO U,\n     (RETYPE_PO (fun t : U => f t)) V ---> \n     (RETYPE_PO (fun t : U => g t)) V :=\n     fun V => Build_ipo_mor (transp_po_s V).\n\n\nProgram Instance transp_po_NT : \n    NT_struct (F:=RETYPE_PO (fun t => f t)) \n           (G := RETYPE_PO (fun t => g t)) transp_po.\nNext Obligation.\nProof.\n  simpl.\n  intros V W f' t y.\n  induction y.\n  simpl.\n  rewrite <- H.\n  simpl.\n  auto.\nQed.\n\nDefinition Transp_ord : NT (RETYPE_PO (fun t => f t)) \n         (RETYPE_PO (fun t => g t)) := Build_NT transp_po_NT.\n\nEnd Transp_po.\n\n\nSection transp_po_id.\n\n(** retyping with the identity function is the identity *)\n\nVariables U U' : Type.\nVariable f : U -> U'.\nVariable H : forall t, f t = f t.\n\nLemma transp_po_id : forall V, transp_po H (V) == id _.\nProof.\n  simpl.\n  intros V t y.\n  rewrite transp_id.\n  auto.\nQed.\n\nEnd transp_po_id.\n\nSection id_retype_po.\n\nVariable T : Type.\nVariable V : IPO T.\n\nProgram Instance id_retype_po_s : ipo_mor_struct (a:=V)\n  (b:=retype_ipo (fun t => t) V) (id_retype(V:=V)).\nNext Obligation.\nProof.\n  unfold Proper;\n  red.\n  intros x y H.\n  unfold id_retype.\n  assert (H':=ctype_ord (fun t => t) H).\n  auto.\nQed.\n\nEnd id_retype_po.\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/CAT/retype_functor_po.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.2774742166309714}}
{"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 logrel.compat_lemmas 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  Lemma auto_related_typed_expr Γ (e : expr) τ (pe : typed Γ e τ) :\n    open_exprel_typed s Γ e e τ.\n  Proof.\n    induction pe.\n    - by apply compat_Var.\n    - by apply compat_Unit.\n    - by apply compat_Bool.\n    - by apply compat_Int.\n    - by apply compat_BinOp.\n    - by apply compat_Seq.\n    - by apply compat_Pair.\n    - by eapply compat_Fst.\n    - by eapply compat_Snd.\n    - by apply compat_InjL.\n    - by apply compat_InjR.\n    - by eapply compat_Case.\n    - by apply compat_If.\n    - by eapply compat_LetIn.\n    - by apply compat_Lam.\n    - by eapply compat_App.\n    - by apply compat_Fold.\n    - by apply compat_Unfold.\n  Qed.\n\n  Lemma auto_related_ctx_item_typed Γ τ Γ' τ' (Ci : ctx_item) (pCi :  typed_ctx_item Ci Γ τ Γ' τ') :\n    ctx_item_rel_typed s Ci Ci Γ τ Γ' τ'.\n  Proof.\n    destruct pCi; intros e e' pe pe' Hee'; simpl.\n    - by apply compat_Lam.\n    - eapply compat_App; auto; eauto. by apply auto_related_typed_expr.\n    - eapply compat_App; eauto. by apply auto_related_typed_expr.\n    - eapply compat_LetIn; eauto. by apply auto_related_typed_expr.\n    - eapply compat_LetIn; eauto. by apply auto_related_typed_expr.\n    - apply compat_Pair; auto. by apply auto_related_typed_expr.\n    - apply compat_Pair; auto. by apply auto_related_typed_expr.\n    - by eapply compat_Fst.\n    - by eapply compat_Snd.\n    - by eapply compat_InjL.\n    - by eapply compat_InjR.\n    - eapply compat_Case; eauto; by apply auto_related_typed_expr.\n    - eapply compat_Case; eauto; by apply auto_related_typed_expr.\n    - eapply compat_Case; eauto; by apply auto_related_typed_expr.\n    - apply compat_If; eauto; by apply auto_related_typed_expr.\n    - apply compat_If; auto; by apply auto_related_typed_expr.\n    - apply compat_If; auto; by apply auto_related_typed_expr.\n    - eapply compat_BinOp; eauto. by apply auto_related_typed_expr.\n    - eapply compat_BinOp; eauto. by apply auto_related_typed_expr.\n    - by apply compat_Fold.\n    - by apply compat_Unfold.\n  Qed.\n\n  Lemma auto_related_ctx_typed Γ τ Γ' τ' (C : ctx) (pC : typed_ctx C Γ τ Γ' τ') :\n    ctx_rel_typed s C C Γ τ Γ' τ'.\n  Proof.\n    induction pC.\n    - by intros e e' Hee'.\n    - intros e e' pe pe' Hee'. simpl. apply (auto_related_ctx_item_typed _ _ _ _ k H).\n      eapply scoped_ctx_fill. eauto. by eapply ctx_typed_scoped.\n      eapply scoped_ctx_fill. eauto. by eapply ctx_typed_scoped.\n      by apply IHpC.\n  Qed.\n\nEnd definition.\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/fundamental.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2774742096432722}}
{"text": "Require Import Declarative.BasicProperties.\nRequire Import Declarative.KindProperties.\nRequire Import Declarative.OccurenceReasoning.\nRequire Import Declarative.FSetReasoning.\nRequire Import Extraction.\n\nRequire Import Program.Tactics.\n\nLemma binds_subst : forall Γ1 Γ2 x x' A B e,\n    ⊢ Γ1, x' : B,, Γ2 ->\n    x : A ∈ Γ1, x' : B,, Γ2 -> x <> x' -> x : [e / x'] A ∈ Γ1 ,, [e // x'] Γ2.\nProof.\n  induction Γ2; simpl; intros.\n  - destruct H0.\n    + inversion H0. subst. contradiction.\n    + inversion H. subst.\n      assert (x' # A) by (eapply notin_dom_bind_fresh; eauto).\n      rewrite fresh_subst_eq; auto.\n  - destruct a. destruct H0.\n    + inversion H0. subst. auto.\n    + right. inversion H. apply IHΓ2 with B; auto.\nQed.\n\nLemma subst_ctx_distr_cons : forall Γ x A y e,\n    [e // y] Γ , x : [e / y] A = [e // y] (Γ , x : A).\nProof. reflexivity. Qed.\n\nLemma ctx_app_cons_assoc : forall (Γ1 Γ2 : context) x A,\n    Γ1 ,, Γ2 , x : A = Γ1 ,, (Γ2 , x : A).\nProof. reflexivity. Qed.\n\nHint Rewrite ctx_app_cons_assoc : substitution.\nHint Rewrite subst_ctx_distr_cons : substitution.\nHint Rewrite subst_open_var_assoc : substitution.\nHint Rewrite subst_extract : substitution.\n\nLtac crush_lc :=\n  repeat\n    match goal with\n    | |- forall x, x `notin` _ -> lc_expr _ => intros\n    | _ => first\n            [ progress auto\n            | progress eauto using lc_subst, lc_open_preserve\n            | progress autorewrite with assoc; auto ]\n    | H : lc_expr ?T |- lc_expr (?e ^^ _) =>\n      match T with\n      | context [e] => inversion H; subst\n      end\n    | |- lc_expr ([_ / _] _) => apply lc_subst\n    end\n.\n\nHint Extern 1 (lc_expr _) => crush_lc : lc.\nHint Extern 1 (forall x, x `notin` _ -> lc_expr _) => crush_lc : lc.\n\nLemma value_subst : forall e x v,\n    lc_expr v -> value e -> value ([v / x] e).\nProof.\n  intros * Lc V. induction V; simpl; eauto 4 with lc.\nQed.\n\nHint Resolve mono_lc : mono.\nHint Resolve subst_mono : mono.\nHint Resolve value_subst : value.\n\nLemma reduction_substitution : forall A B,\n    A ⟶ B -> forall x e, mono_type e -> ([e / x] A) ⟶ ([e / x] B).\nProof with try rewrite subst_open_distr; eauto 4 with lc mono value.\n  intros A B Hr.\n  induction Hr; simpl; intros...\n  - simpl. constructor. crush_lc.\n    inversion H0; subst.\n    apply lc_e_mu with (add x L); crush_lc.\nQed.\n\nLemma dom_subst_equal : forall Γ x v,\n    dom ([v // x] Γ) = dom Γ.\nProof.\n  induction Γ; intros.\n  + reflexivity.\n  + destruct a. simpl. now rewrite (IHΓ x v).\nQed.\n\nLtac subst_gather_helper e :=\n  match type of e with\n  | mono_type ?t => constr:(fv_eexpr (extract t))\n  end\n.\n\nLtac gather_for_substitution :=\n  let L1 := gather_atoms_with (fun L : atoms => L) in\n  let L2 := gather_atoms_with (fun x : atom => singleton x) in\n  let L3 := gather_atoms_with_tactic subst_gather_helper in\n  constr:(L1 `union` L2 `union` L3).\n\nLtac substitution_strategy :=\n  match goal with\n  | _ => solve [auto 3]\n  | _ => progress autorewrite with substitution\n  | |- _ ⊢ e_app _ _ <: e_app _ _ : [_ / _] _ ^^ _ =>\n    (* [v / x] A ^^ e = [v / x] A ^^ [v / x] e *)\n    rewrite -> subst_open_distr\n  | |- _ ⊢ ([?v / ?x] ?e1) ^^ _ <: _ : _ =>\n    rewrite <- subst_open_distr\n  | |- _ `notin` fv_eexpr _ => solve [eauto 4 using fv_subst_inclusion]\n  | |- _ ⟶ _ => solve [eauto using reduction_substitution]\n  | _ => try_constructors\n  | _ => solve [eauto]\n  end\n.\n\nLtac apply_substitution_strategy :=\n  repeat (intros; substitution_strategy).\n\nLtac solve_subst :=\n  solve [\n      adjust_cofinites_for gather_for_substitution;\n      apply_substitution_strategy].\n\nTheorem substitution : forall Γ1 Γ2 x A B e1 e2 e3,\n  Γ1 , x : B ,, Γ2 ⊢ e1 <: e2 : A ->\n  Γ1 ⊢ e3 : B -> mono_type e3 ->\n  Γ1 ,, [e3 // x] Γ2 ⊢ [e3 / x] e1 <: [e3 / x] e2 : [e3 / x] A.\nProof.\n  intros until e3. intros Hsub Hsub3 Mono.\n  remember (Γ1 , x : B ,, Γ2) as Γ.\n  generalize dependent HeqΓ.\n  generalize x Γ2. clear x Γ2.\n  apply sub_mut with\n      (P := fun Γ e1 e2 A => fun (_ : Γ ⊢ e1 <: e2 : A) =>\n         forall x Γ2, Γ = Γ1, x : B,, Γ2 ->\n         Γ1 ,, [e3 // x] Γ2 ⊢ [e3 / x] e1 <: [e3 / x] e2 : [e3 / x] A)\n      (P0 := fun Γ => fun (_ : ⊢ Γ) =>\n         forall x Γ2, Γ = Γ1 , x : B,, Γ2 -> ⊢ Γ1 ,, [e3 // x] Γ2);\n      simpl; intros; subst.\n  - destruct (x == x0).\n    + subst. assert (A0 = B) by (eapply binds_type_equal; eauto). subst.\n      rewrite fresh_subst_eq. apply weakening_app; auto.\n      apply prefix_wf in w. inversion w. subst.\n      eapply fresh_ctx_fresh_expr; eauto.\n    + apply s_var. auto. apply binds_subst with B; auto.\n  - solve_subst.\n  - solve_subst.\n  - solve_subst.\n  - solve_subst.\n  - solve_subst.\n  - solve_subst.\n  - solve_subst.\n  - adjust_cofinites_for gather_for_substitution.\n    eapply s_mu.\n    + inversion m. subst.\n      pick fresh x' and apply mono_mu; autorewrite with assoc; eauto.\n    + apply_substitution_strategy.\n    + apply_substitution_strategy.\n  - solve_subst.\n  - solve_subst.\n  - apply s_forall_l with (add x L) ([e3 / x] t) k;\n      apply_substitution_strategy.\n  - solve_subst.\n  - solve_subst.\n  - solve_subst.\n\n  - destruct Γ2; inversion H.\n  - destruct Γ2; inversion H1; subst; simpl in *.\n    + auto.\n    + apply wf_cons with k; auto.\n      rewrite dom_app. rewrite dom_subst_equal.\n      eauto using dom_insert_subset.\n  - assumption.\nQed.\n\nCorollary substitution_cons : forall Γ x A B e1 e2 e3,\n    Γ, x : B ⊢ e1 <: e2 : A ->\n    Γ ⊢ e3 : B -> mono_type e3 ->\n    Γ ⊢ [e3 / x] e1 <: [e3 / x] e2 : [e3 / x] A.\nProof.\n  intros *.\n  replace (Γ , x : B) with (Γ ,, one (pair x B) ,, nil) by reflexivity.\n  intros.\n  replace Γ with (Γ ,, [e3 // x] nil) by reflexivity.\n  eapply substitution; simpl in *; eauto.\nQed.\n\nLemma ctx_type_correct : forall Γ x A,\n    ⊢ Γ -> x : A ∈ Γ -> exists k, Γ ⊢ A : e_kind k.\nProof.\n  intros * Wf.\n  induction Wf; simpl; intros.\n  - inversion H.\n  - destruct H1.\n    + inversion H1. subst.\n      eauto.\n    + destruct (IHWf H1) as [k0 IH].\n      eauto.\nQed.\n\nTheorem type_correctness : forall Γ e1 e2 A,\n    Γ ⊢ e1 <: e2 : A -> A = BOX \\/ exists k, Γ ⊢ A : e_kind k.\nProof.\n  intros * Sub.\n  induction Sub; eauto with wf.\n  - eauto 3 using ctx_type_correct.\n  - pick fresh x.\n    destruct (H2 x Fr) as [H' | [k H']].\n    + auto.\n    + apply kind_sub_inversion_l in H' as (E1 & E2 & E3). subst. eauto with wf.\n  - destruct IHSub2 as [H0 | [k H0]]. inversion H0.\n    dependent induction H0.\n    + clear H1 H3 IHusub IHusub.\n      pick fresh x for (L `union` fv_expr B).\n      assert (Fr2 : x `notin` L) by auto.\n      specialize (H2 x Fr2).\n      right. exists k.\n      rewrite open_subst_eq with (x := x); auto.\n      replace (e_kind k) with ([t / x] e_kind k) by reflexivity.\n      eapply substitution_cons; eauto.\n    + apply IHusub1 with A k; auto.\n      apply kind_sub_inversion_l in H0_0 as (E1 & E2 & E3). now subst.\nQed.\n\nLtac conclude_type_refl H :=\n  match type of H with\n  | ?G ⊢ _ <: _ : ?A =>\n    let k := fresh \"k\" in\n    let H := fresh \"H\" in\n    let EBox := fresh \"Ebox\" in\n    assert (A = BOX \\/ exists k, G ⊢ A : e_kind k) as [Ebox | [k H]]\n        by (eapply type_correctness; eassumption);\n    [inversion EBox; subst |]\n  end\n.\n", "meta": {"author": "VinaLx", "repo": "dependent-polymorphic-subtyping", "sha": "1a00b61a07e0198d417cf12727067bb1cf7187eb", "save_path": "github-repos/coq/VinaLx-dependent-polymorphic-subtyping", "path": "github-repos/coq/VinaLx-dependent-polymorphic-subtyping/dependent-polymorphic-subtyping-1a00b61a07e0198d417cf12727067bb1cf7187eb/src/proofs/Properties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2774742096432722}}
{"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 List.\n\nRequire Import misc.\nRequire Import bool_fun.\nRequire Import myMap.\n\nSection BDD_config_1.\n\nDefinition BDDzero := N0.\nDefinition BDDone := Npos 1.\nDefinition BDDstate := Map (BDDvar * (ad * ad)).\nDefinition BDDsharing_map := Map (Map (Map ad)).\nDefinition BDDfree_list := list ad.\nDefinition BDDneg_memo := Map ad.\nDefinition BDDor_memo := Map (Map ad).\nDefinition BDDuniv_memo := Map (Map ad).\nDefinition BDDconfig :=\n  (BDDstate *\n   (BDDsharing_map *\n    (BDDfree_list * (ad * (BDDneg_memo * (BDDor_memo * BDDuniv_memo))))))%type.\n\nDefinition initBDDstate := newMap (BDDvar * (ad * ad)).\nDefinition initBDDsharing_map := newMap (Map (Map ad)).\nDefinition initBDDfree_list := nil (A:=ad).\nDefinition initBDDneg_memo := newMap ad.\nDefinition initBDDor_memo := newMap (Map ad).\nDefinition initBDDuniv_memo := newMap (Map ad).\nDefinition initBDDconfig :=\n  (initBDDstate,\n  (initBDDsharing_map,\n  (initBDDfree_list,\n  (Npos 2, (initBDDneg_memo, (initBDDor_memo, initBDDuniv_memo)))))).\n\nDefinition bs_node_height (bs : BDDstate) (node : ad) :=\n  match MapGet _ bs node with\n  | None => N0\n  | Some (x, (l, r)) => ad_S x\n  end.\n\nDefinition node_height (cfg : BDDconfig) (node : ad) :=\n  bs_node_height (fst cfg) node.\n\nFixpoint bool_fun_of_BDD_1 (bs : BDDstate) (node : ad) \n (bound : nat) {struct bound} : bool_fun :=\n  match bound with\n  | O => (* Error *)  bool_fun_zero\n  | S bound' =>\n      match MapGet _ bs node with\n      | None => if Neqb node BDDzero then bool_fun_zero else bool_fun_one\n      | Some (x, (l, r)) =>\n          bool_fun_if x (bool_fun_of_BDD_1 bs r bound')\n            (bool_fun_of_BDD_1 bs l bound')\n      end\n  end.\n\nDefinition bool_fun_of_BDD_bs (bs : BDDstate) (node : ad) :=\n  bool_fun_of_BDD_1 bs node (S (nat_of_N (bs_node_height bs node))).\n\nDefinition bool_fun_of_BDD (cfg : BDDconfig) := bool_fun_of_BDD_bs (fst cfg).\n\nDefinition nodes_preserved_bs (bs bs' : BDDstate) :=\n  forall (x : BDDvar) (l r node : ad),\n  MapGet _ bs node = Some (x, (l, r)) ->\n  MapGet _ bs' node = Some (x, (l, r)).\n\nDefinition nodes_preserved (cfg cfg' : BDDconfig) :=\n  nodes_preserved_bs (fst cfg) (fst cfg').\n\nInductive nodes_reachable (bs : BDDstate) : ad -> ad -> Prop :=\n  | nodes_reachable_0 : forall node : ad, nodes_reachable bs node node\n  | nodes_reachable_1 :\n      forall (node node' l r : ad) (x : BDDvar),\n      MapGet _ bs node = Some (x, (l, r)) ->\n      nodes_reachable bs l node' -> nodes_reachable bs node node'\n  | nodes_reachable_2 :\n      forall (node node' l r : ad) (x : BDDvar),\n      MapGet _ bs node = Some (x, (l, r)) ->\n      nodes_reachable bs r node' -> nodes_reachable bs node node'.\n\nDefinition node_preserved_bs (bs bs' : BDDstate) (node : ad) :=\n  forall (x : BDDvar) (l r node' : ad),\n  nodes_reachable bs node node' ->\n  MapGet _ bs node' = Some (x, (l, r)) ->\n  MapGet _ bs' node' = Some (x, (l, r)).\n\nDefinition node_preserved (cfg cfg' : BDDconfig) :=\n  node_preserved_bs (fst cfg) (fst cfg').\n\nDefinition used_node_bs (bs : BDDstate) (ul : list ad) \n  (node : ad) :=\n  exists node' : ad, In node' ul /\\ nodes_reachable bs node' node. \n\nDefinition used_node'_bs (bs : BDDstate) (ul : list ad) \n  (node : ad) := node = BDDzero \\/ node = BDDone \\/ used_node_bs bs ul node. \n\nDefinition used_node (cfg : BDDconfig) := used_node_bs (fst cfg).\n\nDefinition used_node' (cfg : BDDconfig) := used_node'_bs (fst cfg).\n\nDefinition node_OK (bs : BDDstate) (node : ad) :=\n  node = BDDzero \\/ node = BDDone \\/ in_dom _ node bs = true.\n\nDefinition config_node_OK (cfg : BDDconfig) := node_OK (fst cfg).\n\nDefinition no_new_node_bs (bs bs' : BDDstate) :=\n  forall (x : BDDvar) (l r node : ad),\n  MapGet _ bs' node = Some (x, (l, r)) ->\n  MapGet _ bs node = Some (x, (l, r)).\n\nDefinition no_new_node (cfg cfg' : BDDconfig) :=\n  no_new_node_bs (fst cfg) (fst cfg').\n\nInductive BDDbounded (bs : BDDstate) : ad -> BDDvar -> Prop :=\n  | BDDbounded_0 : forall n : BDDvar, BDDbounded bs BDDzero n\n  | BDDbounded_1 : forall n : BDDvar, BDDbounded bs BDDone n\n  | BDDbounded_2 :\n      forall (node : ad) (n x : BDDvar) (l r : ad),\n      MapGet _ bs node = Some (x, (l, r)) ->\n      BDDcompare x n = Datatypes.Lt ->\n      Neqb l r = false ->\n      BDDbounded bs l x -> BDDbounded bs r x -> BDDbounded bs node n.\n\nDefinition BDD_OK (bs : BDDstate) (node : ad) :=\n  match MapGet _ bs node with\n  | None => node = BDDzero \\/ node = BDDone\n  | Some (n, _) => BDDbounded bs node (ad_S n)\n  end.\n\nDefinition BDDstate_OK (bs : BDDstate) :=\n  MapGet _ bs BDDzero = None /\\\n  MapGet _ bs BDDone = None /\\\n  (forall a : ad, in_dom _ a bs = true -> BDD_OK bs a).\n\nDefinition BDDsharing_OK (bs : BDDstate) (share : BDDsharing_map) :=\n  forall (x : BDDvar) (l r a : ad),\n  MapGet3 _ share l r x = Some a <-> MapGet _ bs a = Some (x, (l, r)).\n\nDefinition BDDfree_list_OK (bs : BDDstate) (fl : BDDfree_list) \n  (cnt : ad) :=\n  no_dup_list _ fl /\\\n  (forall node : ad,\n   In node fl <->\n   Nleb (Npos 2) node = true /\\\n   Nleb (ad_S node) cnt = true /\\ MapGet _ bs node = None).\n\nDefinition cnt_OK (bs : BDDstate) (cnt : ad) :=\n  Nleb (Npos 2) cnt = true /\\\n  (forall a : ad, Nleb cnt a = true -> MapGet _ bs a = None).\n\nDefinition BDDneg_memo_OK (bs : BDDstate) (negm : BDDneg_memo) :=\n  forall node node' : ad,\n  MapGet _ negm node = Some node' ->\n  node_OK bs node /\\\n  node_OK bs node' /\\\n  Neqb (bs_node_height bs node') (bs_node_height bs node) = true /\\\n  bool_fun_eq (bool_fun_of_BDD_bs bs node')\n    (bool_fun_neg (bool_fun_of_BDD_bs bs node)).\n\nDefinition BDDor_memo_OK (bs : BDDstate) (orm : BDDor_memo) :=\n  forall node1 node2 node : ad,\n  MapGet2 _ orm node1 node2 = Some node ->\n  node_OK bs node1 /\\\n  node_OK bs node2 /\\\n  node_OK bs node /\\\n  Nleb (bs_node_height bs node)\n    (BDDvar_max (bs_node_height bs node1) (bs_node_height bs node2)) = true /\\\n  bool_fun_eq (bool_fun_of_BDD_bs bs node)\n    (bool_fun_or (bool_fun_of_BDD_bs bs node1) (bool_fun_of_BDD_bs bs node2)).\n\nDefinition BDDuniv_memo_OK (bs : BDDstate) (um : BDDuniv_memo) :=\n  forall (x : BDDvar) (node node' : ad),\n  MapGet2 _ um node x = Some node' ->\n  node_OK bs node /\\\n  node_OK bs node' /\\\n  Nleb (bs_node_height bs node') (bs_node_height bs node) = true /\\\n  bool_fun_eq (bool_fun_of_BDD_bs bs node')\n    (bool_fun_forall x (bool_fun_of_BDD_bs bs node)).\n\nDefinition BDDconfig_OK (cfg : BDDconfig) :=\n  BDDstate_OK (fst cfg) /\\\n  BDDsharing_OK (fst cfg) (fst (snd cfg)) /\\\n  BDDfree_list_OK (fst cfg) (fst (snd (snd cfg))) (fst (snd (snd (snd cfg)))) /\\\n  cnt_OK (fst cfg) (fst (snd (snd (snd cfg)))) /\\\n  BDDneg_memo_OK (fst cfg) (fst (snd (snd (snd (snd cfg))))) /\\\n  BDDor_memo_OK (fst cfg) (fst (snd (snd (snd (snd (snd cfg)))))) /\\\n  BDDuniv_memo_OK (fst cfg) (snd (snd (snd (snd (snd (snd cfg)))))).\n\nDefinition used_list_OK_bs (bs : BDDstate) (ul : list ad) :=\n  forall node : ad, In node ul -> node_OK bs node.\n\nDefinition used_list_OK (cfg : BDDconfig) := used_list_OK_bs (fst cfg).\n\nDefinition used_nodes_preserved_bs (bs bs' : BDDstate) \n  (ul : list ad) :=\n  forall node : ad, In node ul -> node_preserved_bs bs bs' node.\n\nDefinition used_nodes_preserved (cfg cfg' : BDDconfig) :=\n  used_nodes_preserved_bs (fst cfg) (fst cfg').\n\nDefinition gc_OK (gc : BDDconfig -> list ad -> BDDconfig) :=\n  forall (cfg : BDDconfig) (ul : list ad),\n  BDDconfig_OK cfg ->\n  used_list_OK cfg ul ->\n  BDDconfig_OK (gc cfg ul) /\\\n  used_nodes_preserved cfg (gc cfg ul) ul /\\ no_new_node cfg (gc cfg ul).\n\nLemma initBDDstate_OK : BDDstate_OK initBDDstate.\nProof.\n  unfold BDDstate_OK, initBDDstate in |- *.  split.  simpl in |- *.  trivial.  split.  simpl in |- *.\n  trivial.  intros.  compute in H.  discriminate H.  \nQed.\n\nLemma initBDDsharing_map_OK : BDDsharing_OK initBDDstate initBDDsharing_map.\nProof.\n  unfold BDDsharing_OK, initBDDstate, initBDDsharing_map in |- *. split. intros.\n  compute in H. discriminate H. intros. compute in H. discriminate H.\nQed.\n\nLemma initBDDfree_list_OK :\n BDDfree_list_OK initBDDstate initBDDfree_list (Npos 2).\nProof.\n  unfold BDDfree_list_OK, initBDDstate, initBDDfree_list in |- *.  simpl in |- *.  split.\n  apply no_dup_nil.  split.  tauto.  intro.  elim H; clear H; intros.\n  elim H0; clear H0; intros.  cut (Nleb (ad_S node) node = true).  intro.\n  cut (Neqb node node = false).  rewrite (Neqb_correct node).\n  intro; discriminate.  apply ad_S_le_then_neq.  assumption.\n  apply Nleb_trans with (b := Npos 2).  assumption.  assumption.\nQed.\n\nLemma initBDDneg_memo_OK :\n forall bs : BDDstate, BDDneg_memo_OK bs initBDDneg_memo.\nProof.\n  unfold BDDneg_memo_OK, initBDDneg_memo in |- *.  simpl in |- *.  intros; discriminate.\nQed.\n\nLemma initBDDor_memo_OK :\n forall bs : BDDstate, BDDor_memo_OK bs initBDDor_memo.\nProof.\n  unfold BDDor_memo_OK, initBDDor_memo in |- *.  simpl in |- *.  intros; discriminate.\nQed.\n\nLemma initBDDuniv_memo_OK :\n forall bs : BDDstate, BDDuniv_memo_OK bs initBDDuniv_memo.\nProof.\n  unfold BDDuniv_memo_OK, initBDDuniv_memo in |- *.  intros; discriminate.\nQed.\n\nLemma initBDDconfig_OK : BDDconfig_OK initBDDconfig.\nProof.\n  unfold BDDconfig_OK, initBDDconfig in |- *.  simpl in |- *.  split.  apply initBDDstate_OK.\n  split.  exact initBDDsharing_map_OK.  split.  exact initBDDfree_list_OK.\n  split.  split; reflexivity.  split.  apply initBDDneg_memo_OK.\n  split.  apply initBDDor_memo_OK.  apply initBDDuniv_memo_OK.\nQed.\n\nLemma config_OK_zero :\n forall cfg : BDDconfig,\n BDDconfig_OK cfg -> MapGet _ (fst cfg) BDDzero = None.\nProof.\n  intro.  elim cfg.  clear cfg.  intros bs y.  elim y.  intros share cnt.\n  intros.  elim H.  intros.  elim H0.  intros.  simpl in |- *.  exact H2.\nQed.\n\nLemma config_OK_one :\n forall cfg : BDDconfig,\n BDDconfig_OK cfg -> MapGet _ (fst cfg) BDDone = None.\nProof.\n  intro.  elim cfg.  clear cfg.  intros bs y.  elim y.  intros share cnt.\n  intros.  elim H.  intros.  elim H0.  intros.  simpl in |- *.  exact (proj1 H3).\nQed.\n\nLemma zero_OK : forall cfg : BDDconfig, config_node_OK cfg BDDzero.\nProof.\n  intro.  left; reflexivity.\nQed.\n\nLemma one_OK : forall cfg : BDDconfig, config_node_OK cfg BDDone.\nProof.\n  intro.  right; left; reflexivity.\nQed.\n\nLemma node_height_zero :\n forall cfg : BDDconfig,\n BDDconfig_OK cfg -> Neqb (node_height cfg BDDzero) N0 = true.\nProof.\n  intros.  unfold node_height in |- *.  unfold bs_node_height in |- *.  rewrite (config_OK_zero cfg H).\n  reflexivity.\nQed.\n\nLemma node_height_one :\n forall cfg : BDDconfig,\n BDDconfig_OK cfg -> Neqb (node_height cfg BDDone) N0 = true.\nProof.\n  intros.  unfold node_height in |- *.  unfold bs_node_height in |- *.  rewrite (config_OK_one cfg H).\n  reflexivity.\nQed.\n\nLemma nodes_preserved_bs_trans :\n forall bs1 bs2 bs3 : BDDstate,\n nodes_preserved_bs bs1 bs2 ->\n nodes_preserved_bs bs2 bs3 -> nodes_preserved_bs bs1 bs3.\nProof.\n  intros.  unfold nodes_preserved_bs in |- *.  intros.  apply H0.  apply H.  assumption.\nQed.\n\nLemma nodes_preserved_bs_refl :\n forall bs : BDDstate, nodes_preserved_bs bs bs.\nProof.\n  unfold nodes_preserved_bs in |- *.  tauto.  \nQed.\n\nLemma nodes_preserved_trans :\n forall cfg1 cfg2 cfg3 : BDDconfig,\n nodes_preserved cfg1 cfg2 ->\n nodes_preserved cfg2 cfg3 -> nodes_preserved cfg1 cfg3.\nProof.\n  unfold nodes_preserved in |- *.  intros.  apply nodes_preserved_bs_trans with (bs2 := fst cfg2); assumption.\nQed.\n\nLemma nodes_preserved_refl : forall cfg : BDDconfig, nodes_preserved cfg cfg.\nProof.\n  unfold nodes_preserved in |- *.  intro.  apply nodes_preserved_bs_refl.\nQed.\n\nLemma increase_bound :\n forall (bs : BDDstate) (n n' : BDDvar) (node : ad),\n BDDbounded bs node n ->\n BDDcompare n n' = Datatypes.Lt -> BDDbounded bs node n'.\nProof.\n  intro.  intro.  intro.  intro.  intro.  elim H.  intros.  apply BDDbounded_0.\n  intros.  apply BDDbounded_1. intros.  apply BDDbounded_2 with (x := x) (l := l) (r := r).\n  assumption.  apply BDDcompare_trans with (y := n0).  assumption.  assumption.\n  assumption. assumption. assumption.\nQed.\n\nLemma nodes_preserved_bounded :\n forall (bs bs' : BDDstate) (n : BDDvar) (node : ad),\n nodes_preserved_bs bs bs' -> BDDbounded bs node n -> BDDbounded bs' node n.\nProof.\n  intros. elim H0. intro. apply BDDbounded_0. intro.  apply BDDbounded_1.\n  intros.  apply BDDbounded_2 with (x := x) (l := l) (r := r).  apply H.\n  assumption.  assumption.  assumption.  assumption.  assumption.\nQed.\n\nLemma BDDbounded_lemma :\n forall (bs : BDDstate) (node : ad) (n : BDDvar),\n BDDbounded bs node n ->\n node = BDDzero \\/\n node = BDDone \\/\n (exists x : BDDvar,\n    (exists l : BDDvar,\n       (exists r : BDDvar,\n          MapGet _ bs node = Some (x, (l, r)) /\\\n          BDDcompare x n = Datatypes.Lt /\\\n          Neqb l r = false /\\ BDDbounded bs l x /\\ BDDbounded bs r x))).\nProof.\n  intro.  intro.  intro.  intro.  elim H.  intros.  left.  trivial.  intros.\n  right.  left.  trivial.  intros.  right.  right.  split with x.  split with l.\n  split with r.  split.  assumption.  split.  assumption.  split.  assumption.\n  split.  assumption.  assumption.\nQed.\n\nLemma BDD_OK_node_OK :\n forall (bs : BDDstate) (node : ad), BDD_OK bs node -> node_OK bs node.\nProof.\n  intros.  unfold BDD_OK in H.  elim (option_sum _ (MapGet (BDDvar * (ad * ad)) bs node)).\n  intro y.  elim y; clear y; intros x y.  right; right.  unfold in_dom in |- *.  simpl in |- *.\n  rewrite y.  reflexivity.  intro y.  rewrite y in H.  elim H; intro.\n  left; assumption.  right; left; assumption.  \nQed.\n\nLemma node_OK_BDD_OK :\n forall (bs : BDDstate) (node : ad),\n BDDstate_OK bs -> node_OK bs node -> BDD_OK bs node.\nProof.\n  intros.  unfold BDD_OK in |- *.  elim H0; intro.  rewrite H1.  unfold BDDstate_OK in H.\n  rewrite (proj1 H).  left; reflexivity.  elim H1; intro.  rewrite H2.\n  rewrite (proj1 (proj2 H)).  right; reflexivity.  fold (BDD_OK bs node) in |- *.\n  unfold BDDstate_OK in H.  apply (proj2 (proj2 H)).  assumption.\nQed.\n\nLemma bs_node_height_left :\n forall (bs : BDDstate) (node l r : ad) (x : BDDvar),\n BDDstate_OK bs ->\n MapGet _ bs node = Some (x, (l, r)) ->\n BDDcompare (bs_node_height bs l) (bs_node_height bs node) = Datatypes.Lt.\nProof.\n  intros.  intros.  unfold BDDstate_OK in H.  unfold BDD_OK in H.\n  elim H; clear H; intros.  elim H1; clear H1; intros.\n  cut (BDDbounded bs node (ad_S x)).  intro.\n  elim (BDDbounded_lemma bs node (ad_S x) H3).  intro.  rewrite H4 in H0.\n  rewrite H0 in H; discriminate.  intro.  elim H4; clear H4; intro.\n  rewrite H4 in H0; rewrite H0 in H1; discriminate.  inversion H4.\n  clear H4; inversion H5.  clear H5; inversion H4.  clear H4; inversion H5.\n  clear H5.  rewrite H0 in H4.  injection H4.  intros.  rewrite <- H5 in H6.\n  rewrite <- H7 in H6.  rewrite <- H8 in H6.\n  elim (BDDbounded_lemma bs l x (proj1 (proj2 (proj2 H6)))).\n  intro.  unfold bs_node_height in |- *.  rewrite H9.  rewrite H.  rewrite H0.  unfold ad_S in |- *.\n  elim x.  reflexivity.  reflexivity.  intro.  elim H9; clear H9; intro.\n  rewrite H9.  unfold bs_node_height in |- *.  rewrite H0.  rewrite H1.  unfold ad_S in |- *.  elim x.\n  reflexivity.  reflexivity.  inversion H9.  inversion H10.  inversion H11.\n  inversion H12.  inversion H14.  unfold bs_node_height in |- *.  rewrite H0.  rewrite H13.\n  rewrite <- (ad_S_compare x3 x).  assumption.  lapply (H2 node).  rewrite H0.\n  trivial.  unfold in_dom in |- *.  rewrite H0.  reflexivity.\nQed.\n\nLemma bs_node_height_right :\n forall (bs : BDDstate) (node l r : ad) (x : BDDvar),\n BDDstate_OK bs ->\n MapGet _ bs node = Some (x, (l, r)) ->\n BDDcompare (bs_node_height bs r) (bs_node_height bs node) = Datatypes.Lt.\nProof.\n  intros.  intros.  unfold BDDstate_OK in H.  unfold BDD_OK in H.\n  elim H; clear H; intros.  elim H1; clear H1; intros.\n  cut (BDDbounded bs node (ad_S x)).  intro.\n  elim (BDDbounded_lemma bs node (ad_S x) H3).  intro.  rewrite H4 in H0.\n  rewrite H0 in H; discriminate.  intro.  elim H4; clear H4; intro.\n  rewrite H4 in H0; rewrite H0 in H1; discriminate.  inversion H4.\n  clear H4; inversion H5.  clear H5; inversion H4.  clear H4; inversion H5.\n  clear H5.  rewrite H0 in H4.  injection H4.  intros.  rewrite <- H5 in H6.\n  rewrite <- H7 in H6.  rewrite <- H8 in H6.\n  elim (BDDbounded_lemma bs r x (proj2 (proj2 (proj2 H6)))).\n  intro.  unfold bs_node_height in |- *.  rewrite H9.  rewrite H.  rewrite H0.  unfold ad_S in |- *.\n  elim x.  reflexivity.  reflexivity.  intro.  elim H9; clear H9; intro.\n  rewrite H9.  unfold bs_node_height in |- *.  rewrite H0.  rewrite H1.  unfold ad_S in |- *.  elim x.\n  reflexivity.  reflexivity.  inversion H9.  inversion H10.  inversion H11.\n  inversion H12.  inversion H14.  unfold bs_node_height in |- *.  rewrite H0.  rewrite H13.\n  rewrite <- (ad_S_compare x3 x).  assumption.  lapply (H2 node).  rewrite H0.\n  trivial.  unfold in_dom in |- *.  rewrite H0.  reflexivity.\nQed.\n\nLemma internal_node_lemma :\n forall (bs : BDDstate) (x : BDDvar) (l r node : ad),\n BDDstate_OK bs ->\n MapGet _ bs node = Some (x, (l, r)) ->\n Neqb l r = false /\\ BDDbounded bs l x /\\ BDDbounded bs r x.\nProof.\n  intros.  cut (BDD_OK bs node).  unfold BDD_OK in |- *.  rewrite H0.  intros.\n  elim (BDDbounded_lemma bs node (ad_S x) H1).  intro.  rewrite H2 in H0.\n  unfold BDDstate_OK in H.  rewrite (proj1 H) in H0.  discriminate.  intro.\n  elim H2; clear H2; intro.  rewrite H2 in H0.  unfold BDDstate_OK in H.\n  rewrite (proj1 (proj2 H)) in H0.  discriminate.  inversion H2.\n  inversion H3.  inversion H4.  rewrite H0 in H5.  inversion H5.  injection H6; intros.\n  rewrite <- H8 in H7.  rewrite <- H9 in H7.  rewrite <- H10 in H7.  split.\n  exact (proj1 (proj2 H7)).  exact (proj2 (proj2 H7)).  \n  unfold BDDstate_OK in H.  apply (proj2 (proj2 H)).  unfold in_dom in |- *.\n  rewrite H0.  reflexivity.\nQed.\n\nLemma high_bounded :\n forall (bs : BDDstate) (x : BDDvar) (l r node : ad),\n BDDstate_OK bs -> MapGet _ bs node = Some (x, (l, r)) -> BDDbounded bs r x.\nProof.\nintros.  exact (proj2 (proj2 (internal_node_lemma bs x l r node H H0))).\nQed.\n\nLemma low_bounded :\n forall (bs : BDDstate) (x : BDDvar) (l r node : ad),\n BDDstate_OK bs -> MapGet _ bs node = Some (x, (l, r)) -> BDDbounded bs l x.\nProof.\nintros.  exact (proj1 (proj2 (internal_node_lemma bs x l r node H H0))).\nQed.\n\nLemma BDDbounded_node_OK :\n forall (bs : BDDstate) (node : ad) (n : BDDvar),\n BDDbounded bs node n -> node_OK bs node.\nProof.\n  intros.  elim (BDDbounded_lemma bs node n H).  intro.  rewrite H0.\n  left; reflexivity.  intro.  elim H0; clear H0; intro.  rewrite H0.\n  right; left; reflexivity.  inversion H0.  inversion H1.  inversion H2.\n  unfold node_OK in |- *.  right; right; unfold in_dom in |- *; rewrite (proj1 H3); reflexivity.\nQed.\n\nLemma high_OK :\n forall (bs : BDDstate) (x : BDDvar) (l r node : ad),\n BDDstate_OK bs -> MapGet _ bs node = Some (x, (l, r)) -> node_OK bs r.\nProof.\n  intros.  cut (BDDbounded bs r x).  intros.  apply BDDbounded_node_OK with (n := x).\n  assumption.  unfold BDDstate_OK in H.  apply high_bounded with (node := node) (l := l).\n  assumption.  assumption.\nQed.\n\nLemma low_OK :\n forall (bs : BDDstate) (x : BDDvar) (l r node : ad),\n BDDstate_OK bs -> MapGet _ bs node = Some (x, (l, r)) -> node_OK bs l.\nProof.\n  intros.  cut (BDDbounded bs l x).  intros.  apply BDDbounded_node_OK with (n := x).\n  assumption.  unfold BDDstate_OK in H.  apply low_bounded with (node := node) (r := r).\n  assumption.  assumption.\nQed.\n\nLemma low_high_neq :\n forall (cfg : BDDconfig) (x : BDDvar) (l r node : ad),\n BDDconfig_OK cfg ->\n MapGet _ (fst cfg) node = Some (x, (l, r)) -> Neqb l r = false.\nProof.\n  intros.  exact (proj1 (internal_node_lemma (fst cfg) x l r node (proj1 H) H0)).\nQed.\n\nLemma bs_node_height_left_le :\n forall bs : BDDstate,\n BDDstate_OK bs ->\n forall (x : BDDvar) (l r node : ad),\n MapGet _ bs node = Some (x, (l, r)) ->\n Nleb (bs_node_height bs l) x = true.\nProof.\n  intros.  unfold Nleb in |- *.  apply leb_correct.  apply lt_n_Sm_le.\n  rewrite <- (ad_S_is_S x).  replace (ad_S x) with (bs_node_height bs node).\n  apply BDDcompare_lt.  apply bs_node_height_left with (x := x) (r := r).  assumption.\n  assumption.  unfold bs_node_height in |- *.  rewrite H0.  reflexivity.\nQed.\n\nLemma bs_node_height_right_le :\n forall bs : BDDstate,\n BDDstate_OK bs ->\n forall (x : BDDvar) (l r node : ad),\n MapGet _ bs node = Some (x, (l, r)) ->\n Nleb (bs_node_height bs r) x = true.\nProof.\n  intros.  unfold Nleb in |- *.  apply leb_correct.  apply lt_n_Sm_le.\n  rewrite <- (ad_S_is_S x).  replace (ad_S x) with (bs_node_height bs node).\n  apply BDDcompare_lt.  apply bs_node_height_right with (x := x) (l := l).  assumption.\n  assumption.  unfold bs_node_height in |- *.  rewrite H0.  reflexivity.\nQed.\n\nLemma no_duplicate_node :\n forall (bs : BDDstate) (share : BDDsharing_map),\n BDDstate_OK bs ->\n BDDsharing_OK bs share ->\n forall (x : BDDvar) (l r node1 node2 : ad),\n MapGet _ bs node1 = Some (x, (l, r)) ->\n MapGet _ bs node2 = Some (x, (l, r)) -> node1 = node2.\nProof.\n  intros.  cut (MapGet3 _ share l r x = Some node1).\n  cut (MapGet3 _ share l r x = Some node2).  intros.  rewrite H3 in H4.\n  injection H4.  intro.  rewrite H5; reflexivity.  unfold BDDsharing_OK in H0.\n  apply (proj2 (H0 x l r node2)).  assumption.  apply (proj2 (H0 x l r node1)).\n  assumption.\nQed.\n\nLemma int_node_gt_1 :\n forall (bs : BDDstate) (node : ad),\n BDDstate_OK bs -> in_dom _ node bs = true -> Nleb (Npos 2) node = true.\nProof.\n  intros.  apply ad_gt_1_lemma.  unfold not in |- *; intro.  unfold BDDstate_OK in H.\n  unfold BDDzero in H.  rewrite <- H1 in H.  unfold in_dom in H0.\n  rewrite (proj1 H) in H0.  discriminate.  unfold not in |- *; intro.\n  unfold BDDstate_OK in H.  unfold BDDone in H.  rewrite <- H1 in H.\n  unfold in_dom in H0.  rewrite (proj1 (proj2 H)) in H0.  discriminate.\nQed.\n\nLemma int_node_lt_cnt :\n forall (bs : BDDstate) (cnt node : ad),\n cnt_OK bs cnt -> in_dom _ node bs = true -> Nleb (ad_S node) cnt = true.\nProof.\n  intros.  unfold cnt_OK in H.  apply Nltb_lebmma.  apply not_true_is_false.\n  unfold not in |- *; intro.  unfold in_dom in H0.  unfold Nleb in |- *.\n  rewrite (proj2 H node H1) in H0.  discriminate.\nQed.\n\nLemma nodes_preserved_bs_node_OK :\n forall (bs1 bs2 : BDDstate) (node : ad),\n nodes_preserved_bs bs1 bs2 -> node_OK bs1 node -> node_OK bs2 node.\nProof.\n  intros.  elim H0; intro.  rewrite H1; left; reflexivity.\n  elim H1; intro.  rewrite H2; right; left; reflexivity.  right; right.\n  unfold in_dom in |- *.  unfold nodes_preserved_bs in H.\n  elim (option_sum _ (MapGet _ bs1 node)).  intro y.  elim y.  intro x.  elim x.\n  intros y0 y1.  elim y1; intros y2 y3 y4.  rewrite (H y0 y2 y3 node y4).\n  reflexivity.  intro y.  unfold in_dom in H2.  rewrite y in H2; discriminate.\nQed.\n\nLemma nodes_preserved_config_node_OK :\n forall (cfg1 cfg2 : BDDconfig) (node : ad),\n nodes_preserved cfg1 cfg2 ->\n config_node_OK cfg1 node -> config_node_OK cfg2 node.\nProof.\n  intros.  unfold config_node_OK in |- *.\n  apply nodes_preserved_bs_node_OK with (bs1 := fst cfg1).  assumption.  assumption.\nQed.\n\nLemma nodes_preserved_bs_node_height_eq :\n forall (bs1 bs2 : BDDstate) (node : ad),\n nodes_preserved_bs bs1 bs2 ->\n BDDstate_OK bs1 ->\n BDDstate_OK bs2 ->\n node_OK bs1 node ->\n Neqb (bs_node_height bs2 node) (bs_node_height bs1 node) = true.\nProof.\n  intros.  elim H2; intro.  rewrite H3.  unfold bs_node_height in |- *.\n  unfold BDDstate_OK in H0.  rewrite (proj1 H0).  rewrite (proj1 H1).\n  apply Neqb_correct.  elim H3; intros.  rewrite H4.  unfold bs_node_height in |- *.\n  rewrite (proj1 (proj2 H0)).  rewrite (proj1 (proj2 H1)).\n  apply Neqb_correct.  elim (option_sum _ (MapGet _ bs1 node)).  intro y.\n  elim y.  intro.  elim x.  intros y0 y1.  elim y1.  intros y2 y3 y4.  unfold bs_node_height in |- *.\n  rewrite y4.  unfold nodes_preserved_bs in H.  rewrite (H y0 y2 y3 node y4).\n  apply Neqb_correct.  intro y.  unfold in_dom in H4.  rewrite y in H4.\n  discriminate.\nQed.\n\nLemma nodes_preserved_node_height_eq :\n forall (cfg1 cfg2 : BDDconfig) (node : ad),\n BDDconfig_OK cfg1 ->\n BDDconfig_OK cfg2 ->\n nodes_preserved cfg1 cfg2 ->\n config_node_OK cfg1 node ->\n Neqb (node_height cfg2 node) (node_height cfg1 node) = true.\nProof.\n  intros.  unfold node_height in |- *.  apply nodes_preserved_bs_node_height_eq.  assumption.\n  exact (proj1 H).  exact (proj1 H0).  assumption.  \nQed.\n\n  Section Components.\n\n  Variable cfg : BDDconfig.\n  Hypothesis cfg_OK : BDDconfig_OK cfg.\n\n  Definition bs_of_cfg := fst cfg.\n  Definition share_of_cfg := fst (snd cfg).\n  Definition fl_of_cfg := fst (snd (snd cfg)).\n  Definition cnt_of_cfg := fst (snd (snd (snd cfg))).\n  Definition negm_of_cfg := fst (snd (snd (snd (snd cfg)))).\n  Definition orm_of_cfg := fst (snd (snd (snd (snd (snd cfg))))).\n  Definition um_of_cfg := snd (snd (snd (snd (snd (snd cfg))))).\n\n  Lemma cfg_comp :\n   cfg =\n   (bs_of_cfg,\n   (share_of_cfg,\n   (fl_of_cfg, (cnt_of_cfg, (negm_of_cfg, (orm_of_cfg, um_of_cfg)))))).\n  Proof.\n    unfold bs_of_cfg, share_of_cfg, fl_of_cfg, cnt_of_cfg, negm_of_cfg,\n     orm_of_cfg, um_of_cfg in |- *.  elim cfg.  intros y y0.  elim y0.  intros y1 y2.  elim y2.\n    intros y3 y4.  elim y4.  intros y5 y6.  elim y6.  intros y7 y8.  elim y8.  intros.\n    reflexivity.\n  Qed.\n\n  Lemma bs_of_cfg_OK : BDDstate_OK bs_of_cfg.\n  Proof.\n    exact (proj1 cfg_OK).\n  Qed.\n\n  Lemma share_of_cfg_OK : BDDsharing_OK bs_of_cfg share_of_cfg.\n  Proof.\n    exact (proj1 (proj2 cfg_OK)).\n  Qed.\n\n  Lemma fl_of_cfg_OK : BDDfree_list_OK bs_of_cfg fl_of_cfg cnt_of_cfg.\n  Proof.\n    exact (proj1 (proj2 (proj2 cfg_OK))).\n  Qed.\n\n  Lemma cnt_of_cfg_OK : cnt_OK bs_of_cfg cnt_of_cfg.\n  Proof.\n    exact (proj1 (proj2 (proj2 (proj2 cfg_OK)))).\n  Qed.\n\n  Lemma negm_of_cfg_OK : BDDneg_memo_OK bs_of_cfg negm_of_cfg.\n  Proof.\n    exact (proj1 (proj2 (proj2 (proj2 (proj2 cfg_OK))))).\n  Qed.\n\n  Lemma orm_of_cfg_OK : BDDor_memo_OK bs_of_cfg orm_of_cfg.\n  Proof.\n    exact (proj1 (proj2 (proj2 (proj2 (proj2 (proj2 cfg_OK)))))).\n  Qed.\n \n  Lemma um_of_cfg_OK : BDDuniv_memo_OK bs_of_cfg um_of_cfg.\n  Proof.\n    exact (proj2 (proj2 (proj2 (proj2 (proj2 (proj2 cfg_OK)))))).\n  Qed.\n\n  End Components.\n\nLemma nodes_reachable_lemma_1 :\n forall (bs : BDDstate) (node node' : ad),\n nodes_reachable bs node node' ->\n node = node' \\/\n (exists x : BDDvar,\n    (exists l : ad,\n       (exists r : ad,\n          MapGet _ bs node = Some (x, (l, r)) /\\\n          (nodes_reachable bs l node' \\/ nodes_reachable bs r node')))).\nProof.\n  intros.  elim H.  left.  reflexivity.  intros.  right.  split with x.\n  split with l.  split with r.  split.  assumption.  left; assumption.\n  intros.  right.  split with x; split with l; split with r; split;\n   [ assumption | right; assumption ].\nQed.\n\nLemma nodes_reachable_trans :\n forall (bs : BDDstate) (node1 node2 node3 : ad),\n nodes_reachable bs node1 node2 ->\n nodes_reachable bs node2 node3 -> nodes_reachable bs node1 node3.\nProof.\n  intros bs node1 node2 node3.  simple induction 1.  trivial.  intros.\n  apply nodes_reachable_1 with (x := x) (l := l) (r := r).  assumption.  apply H2.\n  assumption.  intros.  apply nodes_reachable_2 with (x := x) (l := l) (r := r).\n  assumption.  apply H2.  assumption.\nQed.\n\nLemma reachable_node_OK_1 :\n forall (bs : BDDstate) (n : nat) (node1 node2 : ad),\n BDDstate_OK bs ->\n n = nat_of_N (bs_node_height bs node1) ->\n node_OK bs node1 -> nodes_reachable bs node1 node2 -> node_OK bs node2.\nProof.\n  intros bs n.  apply\n   lt_wf_ind\n    with\n      (P := fun n : nat =>\n            forall node1 node2 : ad,\n            BDDstate_OK bs ->\n            n = nat_of_N (bs_node_height bs node1) ->\n            node_OK bs node1 ->\n            nodes_reachable bs node1 node2 -> node_OK bs node2).\n  intros.  elim (nodes_reachable_lemma_1 _ _ _ H3).  intro.\n  rewrite <- H4; assumption.  intros.  elim H4; clear H4; intros.\n  elim H4; clear H4; intros.  elim H4; clear H4; intros.\n  elim H4; clear H4; intros.  elim H5; clear H5; intros.\n  apply H with (m := nat_of_N (bs_node_height bs x0)) (node1 := x0).  rewrite H1.\n  apply BDDcompare_lt.  apply bs_node_height_left with (x := x) (r := x1).  assumption.\n  assumption.  assumption.  reflexivity.  apply low_OK with (node := node1) (x := x) (r := x1).\n  assumption.  assumption.  assumption.  apply H with (m := nat_of_N (bs_node_height bs x1)) (node1 := x1).\n  rewrite H1.  apply BDDcompare_lt.  apply bs_node_height_right with (x := x) (l := x0).\n  assumption.  assumption.  assumption.  reflexivity.  \n  apply high_OK with (node := node1) (x := x) (l := x0).  assumption.  assumption.\n  assumption.\nQed.\n\nLemma reachable_node_OK :\n forall (bs : BDDstate) (node1 node2 : ad),\n BDDstate_OK bs ->\n node_OK bs node1 -> nodes_reachable bs node1 node2 -> node_OK bs node2.\nProof.\n  intros.  apply\n   reachable_node_OK_1\n    with\n      (n := nat_of_N (bs_node_height bs node1))\n      (node1 := node1)\n      (bs := bs).\n  assumption.  reflexivity.  assumption.  assumption.  \nQed.\n\nLemma nodes_reachableBDDzero :\n forall (bs : BDDstate) (node : ad),\n BDDstate_OK bs -> nodes_reachable bs BDDzero node -> node = BDDzero.\nProof.\n  intros.  elim (nodes_reachable_lemma_1 _ _ _ H0).  intro.  rewrite H1.\n  reflexivity.  intros.  inversion H1.  inversion H2.  inversion H3.\n  inversion H4.  rewrite (proj1 H) in H5.  discriminate.\nQed.\n\nLemma nodes_reachableBDDone :\n forall (bs : BDDstate) (node : ad),\n BDDstate_OK bs -> nodes_reachable bs BDDone node -> node = BDDone.\nProof.\n  intros.  elim (nodes_reachable_lemma_1 _ _ _ H0).  intro.  rewrite H1.\n  reflexivity.  intros.  inversion H1.  inversion H2.  inversion H3.\n  inversion H4.  rewrite (proj1 (proj2 H)) in H5.  discriminate.\nQed.\n\nLemma used_node'_used_node_bs :\n forall (bs : BDDstate) (ul : list ad) (node : ad),\n used_node_bs bs ul node -> used_node'_bs bs ul node.\nProof.\n  unfold used_node'_bs in |- *.  tauto.\nQed.\n\nLemma high_used_bs :\n forall (bs : BDDstate) (ul : list ad) (x : BDDvar) (l r node : ad),\n used_node_bs bs ul node ->\n MapGet _ bs node = Some (x, (l, r)) -> used_node_bs bs ul r.\nProof.\n  unfold used_node_bs in |- *.  intros.  elim H.  intros.  split with x0.  split.\n  exact (proj1 H1).  apply nodes_reachable_trans with (node2 := node).\n  exact (proj2 H1).  apply nodes_reachable_2 with (x := x) (l := l) (r := r).\n  assumption.  apply nodes_reachable_0.\nQed.\n\nLemma high_used'_bs :\n forall (bs : BDDstate) (ul : list ad) (x : BDDvar) (l r node : ad),\n BDDstate_OK bs ->\n used_node'_bs bs ul node ->\n MapGet _ bs node = Some (x, (l, r)) -> used_node'_bs bs ul r.\nProof.\n  unfold used_node'_bs in |- *.  intros.  elim H0.  intro.  rewrite H2 in H1.\n  rewrite (proj1 H) in H1.  discriminate.  intro.  elim H2.  intro.\n  rewrite H3 in H1.  rewrite (proj1 (proj2 H)) in H1.  discriminate.\n  intros.  right.  right.  apply high_used_bs with (x := x) (l := l) (node := node).\n  assumption.  assumption.  \nQed.\n\nLemma low_used_bs :\n forall (bs : BDDstate) (ul : list ad) (x : BDDvar) (l r node : ad),\n used_node_bs bs ul node ->\n MapGet _ bs node = Some (x, (l, r)) -> used_node_bs bs ul l.\nProof.\n  unfold used_node_bs in |- *.  intros.  elim H.  intros.  split with x0.  split.\n  exact (proj1 H1).  apply nodes_reachable_trans with (node2 := node).\n  exact (proj2 H1).  apply nodes_reachable_1 with (x := x) (l := l) (r := r).\n  assumption.  apply nodes_reachable_0.\nQed.\n\nLemma low_used'_bs :\n forall (bs : BDDstate) (ul : list ad) (x : BDDvar) (l r node : ad),\n BDDstate_OK bs ->\n used_node'_bs bs ul node ->\n MapGet _ bs node = Some (x, (l, r)) -> used_node'_bs bs ul l.\nProof.\n  unfold used_node'_bs in |- *.  intros.  elim H0.  intro.  rewrite H2 in H1.\n  rewrite (proj1 H) in H1.  discriminate.  intro.  elim H2.  intro.\n  rewrite H3 in H1.  rewrite (proj1 (proj2 H)) in H1.  discriminate.\n  intros.  right.  right.  apply low_used_bs with (x := x) (r := r) (node := node).\n  assumption.  assumption.  \nQed.\n\nLemma high_used :\n forall (cfg : BDDconfig) (ul : list ad) (x : BDDvar) (l r node : ad),\n used_node cfg ul node ->\n MapGet _ (fst cfg) node = Some (x, (l, r)) -> used_node cfg ul r.\nProof.\n  unfold used_node in |- *.  intros.  apply high_used_bs with (x := x) (l := l) (node := node).\n  assumption.  assumption.\nQed.\n\nLemma high_used' :\n forall (cfg : BDDconfig) (ul : list ad) (x : BDDvar) (l r node : ad),\n BDDconfig_OK cfg ->\n used_node' cfg ul node ->\n MapGet _ (fst cfg) node = Some (x, (l, r)) -> used_node' cfg ul r.\nProof.\n  unfold used_node' in |- *.  intros.  apply high_used'_bs with (x := x) (l := l) (node := node).\n  exact (proj1 H).  assumption.  assumption.\nQed.\n\nLemma low_used :\n forall (cfg : BDDconfig) (ul : list ad) (x : BDDvar) (l r node : ad),\n used_node cfg ul node ->\n MapGet _ (fst cfg) node = Some (x, (l, r)) -> used_node cfg ul l.\nProof.\n  unfold used_node in |- *.  intros.  apply low_used_bs with (x := x) (r := r) (node := node).\n  assumption.  assumption.\nQed.\n\nLemma low_used' :\n forall (cfg : BDDconfig) (ul : list ad) (x : BDDvar) (l r node : ad),\n BDDconfig_OK cfg ->\n used_node' cfg ul node ->\n MapGet _ (fst cfg) node = Some (x, (l, r)) -> used_node' cfg ul l.\nProof.\n  unfold used_node' in |- *.  intros.  apply low_used'_bs with (x := x) (r := r) (node := node).\n  exact (proj1 H).  assumption.  assumption.\nQed.\n\nLemma used_node_OK_bs :\n forall (bs : BDDstate) (ul : list ad) (node : ad),\n BDDstate_OK bs ->\n used_list_OK_bs bs ul -> used_node_bs bs ul node -> node_OK bs node.\nProof.\n  intros.  elim H1.  intros.  elim H2; intros.\n  apply reachable_node_OK with (bs := bs) (node1 := x).  assumption.  apply H0.\n  assumption.  assumption.\nQed.\n\nLemma used_node'_OK_bs :\n forall (bs : BDDstate) (ul : list ad) (node : ad),\n BDDstate_OK bs ->\n used_list_OK_bs bs ul -> used_node'_bs bs ul node -> node_OK bs node.\nProof.\n  intros.  elim H1.  intros.  elim H2; intros.  left.  assumption. \n  intro.  elim H2.  intros.  right.  left.  assumption.  intro.\n  elim H3.  intros.  elim H4.  intros.\n  apply reachable_node_OK with (bs := bs) (node1 := x).  assumption.  apply H0.\n  assumption.  assumption.\nQed.\n\n\nLemma used_node_OK :\n forall (cfg : BDDconfig) (ul : list ad) (node : ad),\n BDDconfig_OK cfg ->\n used_list_OK cfg ul -> used_node cfg ul node -> config_node_OK cfg node.\nProof.\n  unfold config_node_OK in |- *.  intros.  apply used_node_OK_bs with (ul := ul).\n  exact (proj1 H).  assumption.  assumption.\nQed.\n\nLemma used_node'_OK :\n forall (cfg : BDDconfig) (ul : list ad) (node : ad),\n BDDconfig_OK cfg ->\n used_list_OK cfg ul -> used_node' cfg ul node -> config_node_OK cfg node.\nProof.\n  unfold config_node_OK in |- *.  intros.  apply used_node'_OK_bs with (ul := ul).\n  exact (proj1 H).  assumption.  assumption.\nQed.\n\nLemma nodes_preserved_used_nodes_preserved :\n forall (cfg cfg' : BDDconfig) (ul : list ad),\n nodes_preserved cfg cfg' -> used_nodes_preserved cfg cfg' ul.\nProof.\n  unfold nodes_preserved, used_nodes_preserved in |- *.\n  unfold nodes_preserved_bs, used_nodes_preserved_bs in |- *.  intros.\n  unfold node_preserved_bs in |- *.  intros.  apply H.  assumption.\nQed.\n\nLemma node_preserved_bs_reachable_1 :\n forall bs bs' : BDDstate,\n BDDstate_OK bs ->\n forall (n : nat) (node node' : ad),\n n = nat_of_N (bs_node_height bs node) ->\n node_preserved_bs bs bs' node ->\n nodes_reachable bs node node' -> nodes_reachable bs' node node'.\nProof.\n  intros bs bs' H00 n.\n  apply\n   lt_wf_ind\n    with\n      (P := fun n : nat =>\n            forall node node' : ad,\n            n = nat_of_N (bs_node_height bs node) ->\n            node_preserved_bs bs bs' node ->\n            nodes_reachable bs node node' -> nodes_reachable bs' node node').\n  clear n.  intros.  elim (nodes_reachable_lemma_1 bs node node' H2).\n  intro.  rewrite H3.  apply nodes_reachable_0.  intro.  inversion H3.\n  inversion H4.  inversion H5.  inversion H6.  elim H8.  intro.\n  apply nodes_reachable_1 with (x := x) (l := x0) (r := x1).  apply H1.\n  apply nodes_reachable_0.  assumption.\n  apply H with (m := nat_of_N (bs_node_height bs x0)).  rewrite H0.\n  apply BDDcompare_lt.  apply bs_node_height_left with (x := x) (r := x1).  assumption.\n  assumption.  reflexivity.  unfold node_preserved_bs in |- *.  intros.  apply H1.\n  apply nodes_reachable_1 with (x := x) (l := x0) (r := x1).  assumption.  assumption.\n  assumption.  assumption.  intro.\n  apply nodes_reachable_2 with (x := x) (l := x0) (r := x1).  apply H1.\n  apply nodes_reachable_0.  assumption.  \n  apply H with (m := nat_of_N (bs_node_height bs x1)).  rewrite H0.\n  apply BDDcompare_lt.  apply bs_node_height_right with (x := x) (l := x0).  assumption.  \n  assumption.  reflexivity.  unfold node_preserved_bs in |- *.  intros.  apply H1.\n  apply nodes_reachable_2 with (x := x) (l := x0) (r := x1).  assumption.  assumption.\n  assumption.  assumption.  \nQed.\n\nLemma node_preserved_bs_reachable :\n forall (bs bs' : BDDstate) (node node' : ad),\n BDDstate_OK bs ->\n node_preserved_bs bs bs' node ->\n nodes_reachable bs node node' -> nodes_reachable bs' node node'.\nProof.\n  intros.  apply\n   node_preserved_bs_reachable_1\n    with (n := nat_of_N (bs_node_height bs node)) (bs := bs).\n  assumption.  reflexivity.  assumption.  assumption.\nQed.\n\nLemma node_preserved_bs_trans :\n forall (bs1 bs2 bs3 : BDDstate) (node : ad),\n BDDstate_OK bs1 ->\n node_preserved_bs bs1 bs2 node ->\n node_preserved_bs bs2 bs3 node -> node_preserved_bs bs1 bs3 node.\nProof.\n  unfold node_preserved_bs in |- *.  intros.  apply H1.\n  apply node_preserved_bs_reachable with (bs := bs1).  assumption.  assumption.  \n  assumption.  apply H0.  assumption.  assumption.\nQed.\n\nLemma used_nodes_preserved_trans :\n forall (cfg1 cfg2 cfg3 : BDDconfig) (ul : list ad),\n BDDconfig_OK cfg1 ->\n used_nodes_preserved cfg1 cfg2 ul ->\n used_nodes_preserved cfg2 cfg3 ul -> used_nodes_preserved cfg1 cfg3 ul.\nProof.\n  unfold used_nodes_preserved in |- *.  unfold used_nodes_preserved_bs in |- *.  intros.\n  apply node_preserved_bs_trans with (bs2 := fst cfg2).  exact (proj1 H).\n  apply H0.  assumption.  apply H1.  assumption.\nQed.\n\nLemma used_nodes_preserved_refl :\n forall (cfg : BDDconfig) (ul : list ad), used_nodes_preserved cfg cfg ul.\nProof.\n  unfold used_nodes_preserved in |- *.  unfold used_nodes_preserved_bs in |- *.\n  unfold node_preserved_bs in |- *.  tauto.\nQed.\n\nLemma BDDzero_preserved :\n forall bs bs' : BDDstate, BDDstate_OK bs -> node_preserved_bs bs bs' BDDzero.\nProof.\n  intros.  unfold node_preserved_bs in |- *.  intros.\n  rewrite (nodes_reachableBDDzero _ _ H H0) in H1.  rewrite (proj1 H) in H1.\n  discriminate.\nQed.\n\nLemma BDDone_preserved :\n forall bs bs' : BDDstate, BDDstate_OK bs -> node_preserved_bs bs bs' BDDone.\nProof.\n  intros.  unfold node_preserved_bs in |- *.  intros.\n  rewrite (nodes_reachableBDDone _ _ H H0) in H1.\n  rewrite (proj1 (proj2 H)) in H1.  discriminate.\nQed.\n\nLemma used_nodes_preserved_preserved_bs :\n forall (bs bs' : BDDstate) (ul : list ad) (node : ad),\n used_nodes_preserved_bs bs bs' ul ->\n used_node_bs bs ul node -> node_preserved_bs bs bs' node.\nProof.\n  intros.  elim H0.  intros.  elim H1; intros.  unfold node_preserved_bs in |- *.\n  intros.  cut (node_preserved_bs bs bs' x).  intro.  apply H6.\n  apply nodes_reachable_trans with (node2 := node).  assumption.  assumption.\n  assumption.  apply H.  assumption.\nQed.\n\nLemma used_nodes_preserved_preserved'_bs :\n forall (bs bs' : BDDstate) (ul : list ad) (node : ad),\n BDDstate_OK bs ->\n used_nodes_preserved_bs bs bs' ul ->\n used_node'_bs bs ul node -> node_preserved_bs bs bs' node.\nProof.\n  intros.  elim H1.  intros.  rewrite H2.  apply BDDzero_preserved.\n  assumption.  intro.  elim H2.  intro.  rewrite H3.  apply BDDone_preserved.\n  assumption.  intro.  apply used_nodes_preserved_preserved_bs with (ul := ul).\n  assumption.  assumption. \nQed.\n\n\nLemma node_preserved_OK_bs :\n forall (bs bs' : BDDstate) (node : ad),\n node_OK bs node -> node_preserved_bs bs bs' node -> node_OK bs' node.\nProof.\n  unfold node_preserved_bs in |- *.  intros.  elim H.  left.  assumption.  intro.\n  elim H1; intro.  right; left; assumption.  right; right.  unfold in_dom in |- *.\n  elim (option_sum _ (MapGet (BDDvar * (ad * ad)) bs node)).  intro y.  elim y; intro.\n  elim x.  intros y0 y1.  elim y1; intros y2 y3 y4.\n  rewrite (H0 _ _ _ _ (nodes_reachable_0 bs node) y4).  reflexivity.  intro y.\n  unfold in_dom in H2.  rewrite y in H2.  discriminate.\nQed.\n\nLemma used_nodes_preserved_list_OK_bs :\n forall (bs bs' : BDDstate) (ul : list ad),\n used_list_OK_bs bs ul ->\n used_nodes_preserved_bs bs bs' ul -> used_list_OK_bs bs' ul.\nProof.\n  unfold used_list_OK_bs, used_nodes_preserved_bs in |- *.  intros.\n  apply node_preserved_OK_bs with (bs := bs).  apply H.  assumption.  apply H0.\n  assumption.\nQed.\n\nLemma used_nodes_preserved_list_OK :\n forall (cfg cfg' : BDDconfig) (ul : list ad),\n used_list_OK cfg ul ->\n used_nodes_preserved cfg cfg' ul -> used_list_OK cfg' ul.\nProof.\n  unfold used_list_OK in |- *.  intros.\n  apply used_nodes_preserved_list_OK_bs with (bs := fst cfg).  assumption.\n  assumption.\nQed.\n\nLemma used_node_cons_node_ul :\n forall (cfg : BDDconfig) (ul : list ad) (node : ad),\n used_node cfg (node :: ul) node.\nProof.\n  unfold used_node in |- *.  unfold used_node_bs in |- *.  intros.  split with node.\n  split.  simpl in |- *.  left.  reflexivity.  apply nodes_reachable_0.\nQed.\n\nLemma used_node'_cons_node_ul :\n forall (cfg : BDDconfig) (ul : list ad) (node : ad),\n used_node' cfg (node :: ul) node.\nProof.\n  unfold used_node' in |- *.  unfold used_node'_bs in |- *.  right.  right.  intros.\n  split with node.  split.  simpl in |- *.  left.  reflexivity.\n  apply nodes_reachable_0.\nQed.\n\nLemma used_node_cons_node'_ul :\n forall (cfg : BDDconfig) (ul : list ad) (node node' : ad),\n used_node cfg ul node -> used_node cfg (node' :: ul) node.\nProof.\n  unfold used_node in |- *.  unfold used_node_bs in |- *.  intros.  elim H.  intros.\n  split with x.  split.  simpl in |- *.  right.  exact (proj1 H0).\n  exact (proj2 H0).\nQed.\n\nLemma used_node'_cons_node'_ul :\n forall (cfg : BDDconfig) (ul : list ad) (node node' : ad),\n used_node' cfg ul node -> used_node' cfg (node' :: ul) node.\nProof.\n  intros.  elim H.  intro.  left.  assumption.  intro.  elim H0.  intro.\n  right.  left.  assumption.  intro.  right.  right.\n  fold (used_node cfg (node' :: ul) node) in |- *.  apply used_node_cons_node'_ul.\n  assumption.\nQed.\n\nLemma used_nodes_preserved_bs_cons :\n forall (bs bs' : BDDstate) (ul : list ad) (node : ad),\n used_nodes_preserved_bs bs bs' (node :: ul) ->\n used_nodes_preserved_bs bs bs' ul.\nProof.\n  unfold used_nodes_preserved_bs in |- *.  intros.  apply H.  simpl in |- *.  right.\n  assumption.\nQed.\n\nLemma used_nodes_preserved_cons :\n forall (cfg cfg' : BDDconfig) (ul : list ad) (node : ad),\n used_nodes_preserved cfg cfg' (node :: ul) ->\n used_nodes_preserved cfg cfg' ul.\nProof.\n  unfold used_nodes_preserved in |- *.  unfold used_nodes_preserved_bs in |- *.  intros.\n  apply H.  simpl in |- *.  right.  assumption.\nQed.\n\n\nLemma node_OK_list_OK_bs :\n forall (bs : BDDstate) (ul : list ad) (node : ad),\n node_OK bs node -> used_list_OK_bs bs ul -> used_list_OK_bs bs (node :: ul).\nProof.\n  unfold used_list_OK_bs in |- *.  intros.  elim (in_inv H1).  intro.\n  rewrite <- H2; assumption.  intro.  apply H0; assumption.\nQed.\n\nLemma node_OK_list_OK :\n forall (cfg : BDDconfig) (ul : list ad) (node : ad),\n config_node_OK cfg node ->\n used_list_OK cfg ul -> used_list_OK cfg (node :: ul).\nProof.\n  unfold used_list_OK in |- *.  intros.  apply node_OK_list_OK_bs.  assumption.\n  assumption.\nQed.\n\nLemma used_nodes_preserved_node_OK :\n forall (cfg cfg' : BDDconfig) (ul : list ad) (node : ad),\n BDDconfig_OK cfg ->\n used_list_OK cfg ul ->\n used_node cfg ul node ->\n used_nodes_preserved cfg cfg' ul -> config_node_OK cfg' node.\nProof.\n  intros.  unfold config_node_OK in |- *.\n  apply node_preserved_OK_bs with (bs := fst cfg).\n  apply used_node_OK_bs with (ul := ul).  exact (proj1 H).  assumption.\n  assumption.  apply used_nodes_preserved_preserved_bs with (ul := ul).\n  assumption.  assumption.\nQed.\n\nLemma used_nodes_preserved_node_OK' :\n forall (cfg cfg' : BDDconfig) (ul : list ad) (node : ad),\n BDDconfig_OK cfg ->\n used_list_OK cfg ul ->\n used_node' cfg ul node ->\n used_nodes_preserved cfg cfg' ul -> config_node_OK cfg' node.\nProof.\n  intros.  unfold config_node_OK in |- *.\n  apply node_preserved_OK_bs with (bs := fst cfg).\n  apply used_node'_OK_bs with (ul := ul).  exact (proj1 H).  assumption.\n  assumption.  apply used_nodes_preserved_preserved'_bs with (ul := ul).\n  exact (proj1 H).  assumption.  assumption.\nQed.\n\nLemma used_nodes_preserved_used_node :\n forall (cfg cfg' : BDDconfig) (ul : list ad) (node : ad),\n BDDconfig_OK cfg ->\n used_nodes_preserved cfg cfg' ul ->\n used_node cfg ul node -> used_node cfg' ul node.\nProof.\n  unfold used_node in |- *.  unfold used_node_bs in |- *.  intros.  inversion H1.  split with x.\n  split.  exact (proj1 H2).\n  apply node_preserved_bs_reachable with (bs := fst cfg).  exact (proj1 H).\n  apply used_nodes_preserved_preserved_bs with (ul := ul).  assumption.\n  split with x.  split.  exact (proj1 H2).  apply nodes_reachable_0.\n  exact (proj2 H2).\nQed.\n\nLemma used_nodes_preserved_used_node' :\n forall (cfg cfg' : BDDconfig) (ul : list ad) (node : ad),\n BDDconfig_OK cfg ->\n used_nodes_preserved cfg cfg' ul ->\n used_node' cfg ul node -> used_node' cfg' ul node.\nProof.\n  intros.  elim H1.  intro.  left.  assumption.  intro.  elim H2.  intro.\n  right.  left.  assumption.  intro.  right.  right.\n  fold (used_node cfg' ul node) in |- *.\n  apply used_nodes_preserved_used_node with (cfg := cfg).  assumption.\n  assumption.  assumption.\nQed.\n\nLemma bool_fun_of_BDD_1_change_bound :\n forall bs : BDDstate,\n BDDstate_OK bs ->\n forall (bound : nat) (node : ad),\n nat_of_N (bs_node_height bs node) < bound ->\n bool_fun_eq (bool_fun_of_BDD_1 bs node bound)\n   (bool_fun_of_BDD_1 bs node (S (nat_of_N (bs_node_height bs node)))).\nProof.\n  intros bs H bound.  apply\n   lt_wf_ind\n    with\n      (P := fun bound : nat =>\n            forall node : ad,\n            nat_of_N (bs_node_height bs node) < bound ->\n            bool_fun_eq (bool_fun_of_BDD_1 bs node bound)\n              (bool_fun_of_BDD_1 bs node\n                 (S (nat_of_N (bs_node_height bs node))))).\n  intro.  elim n.  intros.  absurd (nat_of_N (bs_node_height bs node) < 0).\n  apply lt_n_O.  assumption.  clear n bound.  intros.  simpl in |- *.\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 H3.\n  rewrite H3.  cut (nat_of_N (bs_node_height bs l) < nat_of_N (bs_node_height bs node)).\n  cut (nat_of_N (bs_node_height bs r) < nat_of_N (bs_node_height bs node)).  intros.\n  apply bool_fun_if_preserves_eq.  apply\n   bool_fun_eq_trans\n    with (bool_fun_of_BDD_1 bs r (S (nat_of_N (bs_node_height bs r)))).\n  apply H1.  unfold lt in |- *.  apply le_n.  apply lt_trans_1 with (y := nat_of_N (bs_node_height bs node)).\n  assumption.  assumption.  apply bool_fun_eq_sym.  apply H1.  assumption.\n  assumption.  apply\n   bool_fun_eq_trans\n    with (bool_fun_of_BDD_1 bs l (S (nat_of_N (bs_node_height bs l)))).\n  apply H1.  unfold lt in |- *.  apply le_n.  apply lt_trans_1 with (y := nat_of_N (bs_node_height bs node)).\n  assumption.  assumption.  apply bool_fun_eq_sym.  apply H1.  assumption.\n  assumption.  apply BDDcompare_lt.  apply bs_node_height_right with (x := x) (l := l).\n  assumption.  assumption.  apply BDDcompare_lt.  apply bs_node_height_left with (x := x) (r := r).\n  assumption.  assumption.  intro y.  rewrite y.  apply bool_fun_eq_refl.\nQed.\n\nLemma bool_fun_of_BDD_bs_zero :\n forall bs : BDDstate,\n BDDstate_OK bs -> bool_fun_eq (bool_fun_of_BDD_bs bs BDDzero) bool_fun_zero.\nProof.\n  intros.  unfold bool_fun_eq in |- *.  intros.  unfold bool_fun_of_BDD_bs in |- *.  simpl in |- *.\n  unfold BDDstate_OK in H.  rewrite (proj1 H).  reflexivity.\nQed.\n\nLemma bool_fun_of_BDD_bs_one :\n forall bs : BDDstate,\n BDDstate_OK bs -> bool_fun_eq (bool_fun_of_BDD_bs bs BDDone) bool_fun_one.\nProof.\n  intros.  unfold bool_fun_eq in |- *.  intros.  unfold bool_fun_of_BDD_bs in |- *.  simpl in |- *.\n  unfold BDDstate_OK in H.  rewrite (proj1 (proj2 H)).  reflexivity.\nQed.\n\nLemma bool_fun_of_BDD_bs_int :\n forall bs : BDDstate,\n BDDstate_OK bs ->\n forall (x : BDDvar) (l r node : ad),\n MapGet _ bs node = Some (x, (l, r)) ->\n bool_fun_eq (bool_fun_of_BDD_bs bs node)\n   (bool_fun_if x (bool_fun_of_BDD_bs bs r) (bool_fun_of_BDD_bs bs l)).\nProof.\n  intros.  unfold bool_fun_of_BDD_bs at 1 in |- *.  simpl in |- *.  rewrite H0.  apply bool_fun_if_preserves_eq.\n  unfold bool_fun_of_BDD_bs in |- *.  apply bool_fun_of_BDD_1_change_bound.  assumption.\n  apply BDDcompare_lt.  apply bs_node_height_right with (x := x) (l := l).  assumption.\n  assumption.  unfold bool_fun_of_BDD_bs in |- *.  apply bool_fun_of_BDD_1_change_bound.\n  assumption.  apply BDDcompare_lt.  apply bs_node_height_left with (x := x) (r := r).\n  assumption.  assumption.\nQed.\n\nLemma bool_fun_of_BDD_one :\n forall cfg : BDDconfig,\n BDDconfig_OK cfg -> bool_fun_eq (bool_fun_of_BDD cfg BDDone) bool_fun_one.\nProof.\n  unfold bool_fun_of_BDD in |- *.  intros.  apply bool_fun_of_BDD_bs_one.\n  exact (proj1 H).\nQed.\n\nLemma bool_fun_of_BDD_zero :\n forall cfg : BDDconfig,\n BDDconfig_OK cfg -> bool_fun_eq (bool_fun_of_BDD cfg BDDzero) bool_fun_zero.\nProof.\n  unfold bool_fun_of_BDD in |- *.  intros.  apply bool_fun_of_BDD_bs_zero.\n  exact (proj1 H).\nQed.\n\nLemma bool_fun_of_BDD_int :\n forall (cfg : BDDconfig) (x : BDDvar) (l r node : ad),\n BDDconfig_OK cfg ->\n MapGet _ (fst cfg) node = Some (x, (l, r)) ->\n bool_fun_eq (bool_fun_of_BDD cfg node)\n   (bool_fun_if x (bool_fun_of_BDD cfg r) (bool_fun_of_BDD cfg l)).\nProof.\n  unfold bool_fun_of_BDD in |- *.  intros.  apply bool_fun_of_BDD_bs_int.\n  exact (proj1 H).  assumption.\nQed.\n\nLemma bool_fun_of_BDD_1_ext :\n forall (bound : nat) (bs : BDDstate) (node : ad),\n bool_fun_ext (bool_fun_of_BDD_1 bs node bound).\nProof.\n  simple induction bound.  intros.  simpl in |- *.  exact bool_fun_ext_zero.  simpl in |- *.  intros.\n  elim (MapGet _ bs node).  Focus 2. elim (Neqb node BDDzero).  exact bool_fun_ext_zero.\n  exact bool_fun_ext_one.  intro a.  elim a.  intros y y0.  elim y0.  intros.\n  apply bool_fun_ext_if.  apply H.  apply H.\nQed.\n\nLemma bool_fun_of_BDD_bs_ext :\n forall (bs : BDDstate) (node : ad),\n bool_fun_ext (bool_fun_of_BDD_bs bs node).\nProof.\n  intros.  unfold bool_fun_of_BDD_bs in |- *.  apply bool_fun_of_BDD_1_ext.\nQed.\n\nLemma BDDvar_independent_1 :\n forall bs : BDDstate,\n BDDstate_OK bs ->\n forall (n : nat) (node : ad) (x : BDDvar),\n n = nat_of_N (bs_node_height bs node) ->\n node_OK bs node ->\n Nleb (bs_node_height bs node) x = true ->\n bool_fun_independent (bool_fun_of_BDD_bs bs node) x.\nProof.\n  intros bs H n.  apply\n   lt_wf_ind\n    with\n      (P := fun n : nat =>\n            forall (node : ad) (x : BDDvar),\n            n = nat_of_N (bs_node_height bs node) ->\n            node_OK bs node ->\n            Nleb (bs_node_height bs node) x = true ->\n            bool_fun_independent (bool_fun_of_BDD_bs bs node) x).\n  intros.  elim H2; intro.  rewrite H4.  apply bool_fun_eq_independent with (bf1 := bool_fun_zero).\n  apply bool_fun_eq_sym.  apply bool_fun_of_BDD_bs_zero.  assumption.\n  apply bool_fun_independent_zero.  elim H4; clear H4; intro.  rewrite H4.\n  apply bool_fun_eq_independent with (bf1 := bool_fun_one).  apply bool_fun_eq_sym.\n  apply bool_fun_of_BDD_bs_one.  assumption.  apply bool_fun_independent_one.\n  elim (option_sum _ (MapGet _ bs node)).  intro y.  elim y; clear y; intro x0.\n  elim x0; clear x0.  intros x' y.  elim y; clear y; intros l r H5.\n  apply\n   bool_fun_eq_independent\n    with\n      (bf1 := bool_fun_if x' (bool_fun_of_BDD_bs bs r)\n                (bool_fun_of_BDD_bs bs l)).\n  apply bool_fun_eq_sym.  apply bool_fun_of_BDD_bs_int.  assumption.  assumption.\n  apply bool_fun_independent_if.  apply H0 with (m := nat_of_N (bs_node_height bs r)).\n  rewrite H1.  apply BDDcompare_lt.  apply bs_node_height_right with (x := x') (l := l).\n  assumption.  assumption.  reflexivity.  apply high_OK with (x := x') (l := l) (node := node).\n  assumption.  assumption.  unfold Nleb in |- *.  apply leb_correct.  apply lt_le_weak.\n  apply lt_le_trans with (m := nat_of_N (bs_node_height bs node)).  apply BDDcompare_lt.\n  apply bs_node_height_right with (x := x') (l := l).  assumption.  assumption.\n  apply leb_complete.  assumption.  apply H0 with (m := nat_of_N (bs_node_height bs l)).\n  rewrite H1.  apply BDDcompare_lt.  apply bs_node_height_left with (x := x') (r := r).\n  assumption.  assumption.  reflexivity.  apply low_OK with (x := x') (r := r) (node := node).\n  assumption.  assumption.  unfold Nleb in |- *.  apply leb_correct.  apply lt_le_weak.\n  apply lt_le_trans with (m := nat_of_N (bs_node_height bs node)).  apply BDDcompare_lt.\n  apply bs_node_height_left with (x := x') (r := r).  assumption.  assumption.\n  apply leb_complete.  assumption.  unfold bs_node_height in H3.  rewrite H5 in H3.\n  rewrite (Neqb_comm x x').  apply ad_S_le_then_neq.  assumption.  intro y.\n  unfold in_dom in H4.  rewrite y in H4; discriminate.\nQed.\n\nLemma BDDvar_independent_bs :\n forall bs : BDDstate,\n BDDstate_OK bs ->\n forall (node : ad) (x : BDDvar),\n node_OK bs node ->\n Nleb (bs_node_height bs node) x = true ->\n bool_fun_independent (bool_fun_of_BDD_bs bs node) x.\nProof.\n  intros.  apply BDDvar_independent_1 with (n := nat_of_N (bs_node_height bs node)).\n  assumption.  reflexivity.  assumption.  assumption.\nQed.\n\nLemma BDDvar_independent_low :\n forall bs : BDDstate,\n BDDstate_OK bs ->\n forall (x : BDDvar) (l r node : ad),\n MapGet _ bs node = Some (x, (l, r)) ->\n bool_fun_independent (bool_fun_of_BDD_bs bs l) x.\nProof.\n  intros.  apply BDDvar_independent_1 with (n := nat_of_N (bs_node_height bs l)).\n  assumption.  reflexivity.  apply low_OK with (x := x) (r := r) (node := node).\n  assumption.  assumption.  apply bs_node_height_left_le with (node := node) (r := r).\n  assumption.  assumption.\nQed.\n\nLemma BDDvar_independent_high :\n forall bs : BDDstate,\n BDDstate_OK bs ->\n forall (x : BDDvar) (l r node : ad),\n MapGet _ bs node = Some (x, (l, r)) ->\n bool_fun_independent (bool_fun_of_BDD_bs bs r) x.\nProof.\n  intros.  apply BDDvar_independent_1 with (n := nat_of_N (bs_node_height bs r)).\n  assumption.  reflexivity.  apply high_OK with (x := x) (l := l) (node := node).\n  assumption.  assumption.  apply bs_node_height_right_le with (node := node) (l := l).\n  assumption.  assumption.\nQed.\n\n\nLemma bool_fun_of_BDD_bs_high :\n forall bs : BDDstate,\n BDDstate_OK bs ->\n forall (x : BDDvar) (l r node : ad),\n MapGet _ bs node = Some (x, (l, r)) ->\n bool_fun_eq (bool_fun_of_BDD_bs bs r)\n   (bool_fun_restrict (bool_fun_of_BDD_bs bs node) x true).\nProof.\n  intros.  apply\n   bool_fun_eq_trans\n    with\n      (bool_fun_restrict\n         (bool_fun_if x (bool_fun_of_BDD_bs bs r) (bool_fun_of_BDD_bs bs l))\n         x true).\n  apply bool_fun_eq_sym.  apply bool_fun_if_restrict_true_independent.\n  apply BDDvar_independent_high with (node := node) (l := l).  assumption.  assumption.\n  apply bool_fun_restrict_preserves_eq.  apply bool_fun_eq_sym.\n  apply bool_fun_of_BDD_bs_int.  assumption.  assumption.\nQed.\n\n\nLemma bool_fun_of_BDD_bs_low :\n forall bs : BDDstate,\n BDDstate_OK bs ->\n forall (x : BDDvar) (l r node : ad),\n MapGet _ bs node = Some (x, (l, r)) ->\n bool_fun_eq (bool_fun_of_BDD_bs bs l)\n   (bool_fun_restrict (bool_fun_of_BDD_bs bs node) x false).\nProof.\n  intros.  apply\n   bool_fun_eq_trans\n    with\n      (bool_fun_restrict\n         (bool_fun_if x (bool_fun_of_BDD_bs bs r) (bool_fun_of_BDD_bs bs l))\n         x false).\n  apply bool_fun_eq_sym.  apply bool_fun_if_restrict_false_independent.\n  apply BDDvar_independent_low with (node := node) (r := r).  assumption.  assumption.\n  apply bool_fun_restrict_preserves_eq.  apply bool_fun_eq_sym.\n  apply bool_fun_of_BDD_bs_int.  assumption.  assumption.\nQed.\n\nLemma BDDunique_1 :\n forall (bs : BDDstate) (share : BDDsharing_map),\n BDDstate_OK bs ->\n BDDsharing_OK bs share ->\n forall (n : nat) (node1 node2 : ad),\n n =\n max (nat_of_N (bs_node_height bs node1))\n   (nat_of_N (bs_node_height bs node2)) ->\n node_OK bs node1 ->\n node_OK bs node2 ->\n bool_fun_eq (bool_fun_of_BDD_bs bs node1) (bool_fun_of_BDD_bs bs node2) ->\n node1 = node2.\nProof.\n  intros bs share H H00 n.  apply\n   lt_wf_ind\n    with\n      (P := fun n : nat =>\n            forall node1 node2 : ad,\n            n =\n            max (nat_of_N (bs_node_height bs node1))\n              (nat_of_N (bs_node_height bs node2)) ->\n            node_OK bs node1 ->\n            node_OK bs node2 ->\n            bool_fun_eq (bool_fun_of_BDD_bs bs node1)\n              (bool_fun_of_BDD_bs bs node2) -> node1 = node2).\n  intros.  elim H2; intro.  elim H3; intro.  rewrite H5.  rewrite H6.\n  reflexivity.  elim H6; clear H6; intro.  absurd (bool_fun_eq bool_fun_zero bool_fun_one).\n  unfold not, bool_fun_eq, bool_fun_zero, bool_fun_one in |- *.  intro.  absurd (false = true).\n  unfold not in |- *; intro; discriminate.  apply H7.  exact (fun _ : BDDvar => true).\n  apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD_bs bs node1).\n  apply bool_fun_eq_sym.  rewrite H5.  apply bool_fun_of_BDD_bs_zero.  assumption.\n  apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD_bs bs node2).  assumption.\n  rewrite H6.  apply bool_fun_of_BDD_bs_one.  assumption.\n  elim (option_sum _ (MapGet _ bs node2)).  intro y.  elim y; clear y; intro x.\n  elim x; clear x.  intros x2 y.  elim y; clear y; intros l2 r2 H7.\n  absurd (l2 = r2).  unfold not in |- *; intro.  cut (Neqb l2 r2 = true).  intro.\n  rewrite (proj1 (internal_node_lemma bs x2 l2 r2 node2 H H7)) in H9.\n  discriminate.  rewrite H8.  apply Neqb_correct.\n  apply\n   H0\n    with\n      (m := max (nat_of_N (bs_node_height bs l2))\n              (nat_of_N (bs_node_height bs r2))).\n  rewrite H1.  apply lt_max_2.  apply BDDcompare_lt.  apply bs_node_height_left with (x := x2) (r := r2).\n  assumption.  assumption.  apply BDDcompare_lt.  apply bs_node_height_right with (x := x2) (l := l2).\n  assumption.  assumption.  reflexivity.  apply low_OK with (node := node2) (x := x2) (r := r2).\n  assumption.  assumption.  apply high_OK with (node := node2) (x := x2) (l := l2).\n  assumption.  assumption.\n  apply\n   bool_fun_eq_trans\n    with (bool_fun_restrict (bool_fun_of_BDD_bs bs node2) x2 false).\n  apply bool_fun_of_BDD_bs_low with (r := r2).  assumption.  assumption.\n  apply\n   bool_fun_eq_trans\n    with (bool_fun_restrict (bool_fun_of_BDD_bs bs node2) x2 true).\n  apply\n   bool_fun_eq_trans\n    with (bf2 := bool_fun_restrict (bool_fun_of_BDD_bs bs node1) x2 false).\n  apply bool_fun_restrict_preserves_eq.  apply bool_fun_eq_sym.  assumption.\n  apply\n   bool_fun_eq_trans\n    with (bf2 := bool_fun_restrict (bool_fun_of_BDD_bs bs node1) x2 true).\n  rewrite H5.  apply\n   bool_fun_eq_trans with (bf2 := bool_fun_restrict bool_fun_zero x2 false).\n  apply bool_fun_restrict_preserves_eq.  apply bool_fun_of_BDD_bs_zero.\n\n  assumption.  apply bool_fun_eq_trans with (bf2 := bool_fun_zero).\n  apply bool_fun_restrict_zero.\n  apply\n   bool_fun_eq_trans with (bf2 := bool_fun_restrict bool_fun_zero x2 true).\n  apply bool_fun_eq_sym.  apply bool_fun_restrict_zero.  apply bool_fun_restrict_preserves_eq.\n  apply bool_fun_eq_sym.  apply bool_fun_of_BDD_bs_zero.  assumption.\n  apply bool_fun_restrict_preserves_eq.  assumption.  apply bool_fun_eq_sym.\n  apply bool_fun_of_BDD_bs_high with (l := l2).  assumption.  assumption.  intro y.\n  unfold in_dom in H6.  rewrite y in H6.  discriminate.  elim H5; clear H5; intro.\n  elim H3; intro.  absurd (bool_fun_eq bool_fun_one bool_fun_zero).\n  unfold not in |- *; intro.  unfold bool_fun_eq, bool_fun_one, bool_fun_zero in H7.\n  cut (true = false).  intro.  discriminate.  apply H7.  exact (fun _ : BDDvar => true).\n  apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD_bs bs node1).  rewrite H5.\n  apply bool_fun_eq_sym.  apply bool_fun_of_BDD_bs_one.  assumption.\n  apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD_bs bs node2).  assumption.\n  rewrite H6.  apply bool_fun_of_BDD_bs_zero.  assumption.  elim H6; clear H6; intro.\n  rewrite H5.  rewrite H6.  reflexivity.  elim (option_sum _ (MapGet _ bs node2)).\n  intro y.  elim y; clear y; intro.  elim x; clear x.  intros x2 y.\n  elim y; clear y; intros l2 r2 H7.  absurd (l2 = r2).  unfold not in |- *; intro.\n  cut (Neqb l2 r2 = true).  intro.\n  rewrite (proj1 (internal_node_lemma bs x2 l2 r2 node2 H H7)) in H9.\n  discriminate.  rewrite H8.  apply Neqb_correct.\n  apply\n   H0\n    with\n      (m := max (nat_of_N (bs_node_height bs l2))\n              (nat_of_N (bs_node_height bs r2))).\n  rewrite H1.  apply lt_max_2.  apply BDDcompare_lt.  apply bs_node_height_left with (x := x2) (r := r2).\n  assumption.  assumption.  apply BDDcompare_lt.  apply bs_node_height_right with (x := x2) (l := l2).\n  assumption.  assumption.  reflexivity.  apply low_OK with (node := node2) (x := x2) (r := r2).\n  assumption.  assumption.  apply high_OK with (node := node2) (x := x2) (l := l2).\n  assumption.  assumption.  apply\n   bool_fun_eq_trans\n    with (bool_fun_restrict (bool_fun_of_BDD_bs bs node2) x2 false).\n  apply bool_fun_of_BDD_bs_low with (r := r2).  assumption.  assumption.\n  apply\n   bool_fun_eq_trans\n    with (bool_fun_restrict (bool_fun_of_BDD_bs bs node2) x2 true).\n  apply\n   bool_fun_eq_trans\n    with (bf2 := bool_fun_restrict (bool_fun_of_BDD_bs bs node1) x2 false).\n  apply bool_fun_restrict_preserves_eq.  apply bool_fun_eq_sym.  assumption.\n  apply\n   bool_fun_eq_trans\n    with (bf2 := bool_fun_restrict (bool_fun_of_BDD_bs bs node1) x2 true).\n  rewrite H5.  apply\n   bool_fun_eq_trans with (bf2 := bool_fun_restrict bool_fun_one x2 false).\n  apply bool_fun_restrict_preserves_eq.  apply bool_fun_of_BDD_bs_one.\n  assumption.  apply bool_fun_eq_trans with (bf2 := bool_fun_one).\n  apply bool_fun_restrict_one.  apply\n   bool_fun_eq_trans with (bf2 := bool_fun_restrict bool_fun_one x2 true).\n  apply bool_fun_eq_sym.  apply bool_fun_restrict_one.  apply bool_fun_restrict_preserves_eq.\n  apply bool_fun_eq_sym.  apply bool_fun_of_BDD_bs_one.  assumption.\n  apply bool_fun_restrict_preserves_eq.  assumption.  apply bool_fun_eq_sym.\n  apply bool_fun_of_BDD_bs_high with (l := l2).  assumption.  assumption.  intro y.\n  unfold in_dom in H6.  rewrite y in H6.  discriminate.  elim (option_sum _ (MapGet _ bs node1)).\n  intro y.  elim y; clear y; intro.  elim x; clear x.  intros x1 y.  elim y; clear y.\n  intros l1 r1 H6.  elim H3; intro.  absurd (l1 = r1).  unfold not in |- *; intro.\n  cut (Neqb l1 r1 = true).  intro.  rewrite (proj1 (internal_node_lemma bs x1 l1 r1 node1 H H6)) in H9.\n  discriminate.  rewrite H8.  apply Neqb_correct.\n  apply\n   H0\n    with\n      (m := max (nat_of_N (bs_node_height bs l1))\n              (nat_of_N (bs_node_height bs r1))).\n  rewrite H1.  apply lt_max_1.  apply BDDcompare_lt.  apply bs_node_height_left with (x := x1) (r := r1).\n  assumption.  assumption.  apply BDDcompare_lt.  apply bs_node_height_right with (x := x1) (l := l1).\n  assumption.  assumption.  reflexivity.  apply low_OK with (node := node1) (x := x1) (r := r1).\n  assumption.  assumption.  apply high_OK with (node := node1) (x := x1) (l := l1).\n  assumption.  assumption.  apply\n   bool_fun_eq_trans\n    with (bf2 := bool_fun_restrict (bool_fun_of_BDD_bs bs node1) x1 false).\n  apply bool_fun_of_BDD_bs_low with (r := r1).  assumption.  assumption.\n  apply\n   bool_fun_eq_trans\n    with (bf2 := bool_fun_restrict (bool_fun_of_BDD_bs bs node2) x1 false).\n  apply bool_fun_restrict_preserves_eq.  assumption.  rewrite H7.\n  apply\n   bool_fun_eq_trans with (bf2 := bool_fun_restrict bool_fun_zero x1 false).\n  apply bool_fun_restrict_preserves_eq.  apply bool_fun_of_BDD_bs_zero.\n  assumption.  apply\n   bool_fun_eq_trans\n    with (bf2 := bool_fun_restrict (bool_fun_of_BDD_bs bs node1) x1 true).\n  apply\n   bool_fun_eq_trans\n    with (bf2 := bool_fun_restrict (bool_fun_of_BDD_bs bs node2) x1 true).\n  rewrite H7.  apply\n   bool_fun_eq_trans with (bf2 := bool_fun_restrict bool_fun_zero x1 true).\n  apply bool_fun_eq_trans with (bf2 := bool_fun_zero).  apply bool_fun_restrict_zero.\n  apply bool_fun_eq_sym.  apply bool_fun_restrict_zero.  apply bool_fun_restrict_preserves_eq.\n  apply bool_fun_eq_sym.  apply bool_fun_of_BDD_bs_zero.  assumption.\n  apply bool_fun_restrict_preserves_eq.  apply bool_fun_eq_sym.  assumption.\n  apply bool_fun_eq_sym.  apply bool_fun_of_BDD_bs_high with (l := l1).  assumption.\n  assumption.  elim H7; clear H7; intro.  absurd (l1 = r1).  unfold not in |- *; intro.\n  cut (Neqb l1 r1 = true).  intro.\n  rewrite (proj1 (internal_node_lemma bs x1 l1 r1 node1 H H6)) in H9.\n  discriminate.  rewrite H8.  apply Neqb_correct.\n  apply\n   H0\n    with\n      (m := max (nat_of_N (bs_node_height bs l1))\n              (nat_of_N (bs_node_height bs r1))).\n  rewrite H1.  apply lt_max_1.  apply BDDcompare_lt.  apply bs_node_height_left with (x := x1) (r := r1).\n  assumption.  assumption.  apply BDDcompare_lt.  apply bs_node_height_right with (x := x1) (l := l1).\n  assumption.  assumption.  reflexivity.  apply low_OK with (node := node1) (x := x1) (r := r1).\n  assumption.  assumption.  apply high_OK with (node := node1) (x := x1) (l := l1).\n  assumption.  assumption.\n  apply\n   bool_fun_eq_trans\n    with (bf2 := bool_fun_restrict (bool_fun_of_BDD_bs bs node1) x1 false).\n  apply bool_fun_of_BDD_bs_low with (r := r1).  assumption.  assumption.\n  apply\n   bool_fun_eq_trans\n    with (bf2 := bool_fun_restrict (bool_fun_of_BDD_bs bs node2) x1 false).\n  apply bool_fun_restrict_preserves_eq.  assumption.  rewrite H7.\n  apply\n   bool_fun_eq_trans with (bf2 := bool_fun_restrict bool_fun_one x1 false).\n  apply bool_fun_restrict_preserves_eq.  apply bool_fun_of_BDD_bs_one.  assumption.\n  apply\n   bool_fun_eq_trans\n    with (bf2 := bool_fun_restrict (bool_fun_of_BDD_bs bs node1) x1 true).\n  apply\n   bool_fun_eq_trans\n    with (bf2 := bool_fun_restrict (bool_fun_of_BDD_bs bs node2) x1 true).\n  rewrite H7.  apply\n   bool_fun_eq_trans with (bf2 := bool_fun_restrict bool_fun_one x1 true).\n  apply bool_fun_eq_trans with (bf2 := bool_fun_one).  apply bool_fun_restrict_one.\n  apply bool_fun_eq_sym.  apply bool_fun_restrict_one.  apply bool_fun_restrict_preserves_eq.\n  apply bool_fun_eq_sym.  apply bool_fun_of_BDD_bs_one.  assumption.\n  apply bool_fun_restrict_preserves_eq.  apply bool_fun_eq_sym.  assumption.\n  apply bool_fun_eq_sym.  apply bool_fun_of_BDD_bs_high with (l := l1).  assumption.\n  assumption.  elim (option_sum _ (MapGet _ bs node2)).  intro y.  elim y; clear y; intro.\n  elim x; clear x.  intros x2 y.  elim y; clear y; intros l2 r2 H8.\n  elim (relation_sum (BDDcompare x1 x2)).  intro y.  elim y; clear y; intro y.\n  apply\n   no_duplicate_node\n    with (x := x1) (l := l1) (r := r1) (bs := bs) (share := share).\n  assumption.  assumption.  assumption.  rewrite H8.  cut (l1 = l2).  cut (r1 = r2).\n  intros.  rewrite H9.  rewrite H10.  rewrite (BDD_EGAL_complete _ _ y).\n  reflexivity.  apply\n   H0\n    with\n      (m := max (nat_of_N (bs_node_height bs r1))\n              (nat_of_N (bs_node_height bs r2))).\n  rewrite H1.  apply lt_max_1_2.  apply BDDcompare_lt.  apply bs_node_height_right with (x := x1) (l := l1).\n  assumption.  assumption.  apply BDDcompare_lt.  apply bs_node_height_right with (x := x2) (l := l2).\n  assumption.  assumption.  reflexivity.  apply high_OK with (node := node1) (x := x1) (l := l1).\n  assumption.  assumption.  apply high_OK with (node := node2) (x := x2) (l := l2).  assumption.\n  assumption.  apply\n   bool_fun_eq_trans\n    with (bf2 := bool_fun_restrict (bool_fun_of_BDD_bs bs node1) x1 true).\n  apply bool_fun_of_BDD_bs_high with (l := l1).  assumption.  assumption.\n  apply\n   bool_fun_eq_trans\n    with (bf2 := bool_fun_restrict (bool_fun_of_BDD_bs bs node2) x2 true).\n  rewrite (BDD_EGAL_complete _ _ y).  apply bool_fun_restrict_preserves_eq.\n  assumption.  apply bool_fun_eq_sym.  apply bool_fun_of_BDD_bs_high with (l := l2).\n  assumption.  assumption.  apply\n   H0\n    with\n      (m := max (nat_of_N (bs_node_height bs l1))\n              (nat_of_N (bs_node_height bs l2))).\n  rewrite H1.  apply lt_max_1_2.  apply BDDcompare_lt.  apply bs_node_height_left with (x := x1) (r := r1).\n  assumption.  assumption.  apply BDDcompare_lt.  apply bs_node_height_left with (x := x2) (r := r2).\n  assumption.  assumption.  reflexivity.  apply low_OK with (node := node1) (x := x1) (r := r1).\n  assumption.  assumption.  apply low_OK with (node := node2) (x := x2) (r := r2).\n  assumption.  assumption.  apply\n   bool_fun_eq_trans\n    with (bf2 := bool_fun_restrict (bool_fun_of_BDD_bs bs node1) x1 false).\n  apply bool_fun_of_BDD_bs_low with (r := r1).  assumption.  assumption.\n  apply\n   bool_fun_eq_trans\n    with (bf2 := bool_fun_restrict (bool_fun_of_BDD_bs bs node2) x2 false).\n  rewrite (BDD_EGAL_complete _ _ y).  apply bool_fun_restrict_preserves_eq.\n  assumption.  apply bool_fun_eq_sym.  apply bool_fun_of_BDD_bs_low with (r := r2).\n  assumption.  assumption.  absurd (l2 = r2).  unfold not in |- *; intro.  cut (Neqb l2 r2 = true).\n  intro.  rewrite (proj1 (internal_node_lemma bs x2 l2 r2 node2 H H8)) in H10.\n  discriminate.  rewrite H9.  apply Neqb_correct.\n  apply\n   H0\n    with\n      (m := max (nat_of_N (bs_node_height bs l2))\n              (nat_of_N (bs_node_height bs r2))).\n  rewrite H1.  apply lt_max_2.  apply BDDcompare_lt.  apply bs_node_height_left with (x := x2) (r := r2).\n  assumption.  assumption.  apply BDDcompare_lt.  apply bs_node_height_right with (x := x2) (l := l2).\n  assumption.  assumption.  reflexivity.  apply low_OK with (node := node2) (x := x2) (r := r2).\n  assumption.  assumption.  apply high_OK with (node := node2) (x := x2) (l := l2).\n  assumption.  assumption.  apply\n   bool_fun_eq_trans\n    with (bool_fun_restrict (bool_fun_of_BDD_bs bs node2) x2 false).\n  apply bool_fun_of_BDD_bs_low with (r := r2).  assumption.  assumption.\n  cut (bool_fun_independent (bool_fun_of_BDD_bs bs node2) x2).  intro.\n  apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD_bs bs node2).  apply H9.\n  apply\n   bool_fun_eq_trans\n    with (bf2 := bool_fun_restrict (bool_fun_of_BDD_bs bs node2) x2 true).\n  apply bool_fun_eq_sym.  apply H9.  apply bool_fun_eq_sym.\n  apply bool_fun_of_BDD_bs_high with (l := l2).  assumption.  assumption.\n  apply bool_fun_eq_independent with (bf1 := bool_fun_of_BDD_bs bs node1).\n  assumption.  apply BDDvar_independent_bs.  assumption.  assumption.\n  unfold Nleb in |- *.  apply leb_correct.  unfold bs_node_height in |- *.  rewrite H6.\n  rewrite (ad_S_is_S x1).  apply lt_le_S.  apply BDDcompare_lt.  assumption.\n  intro.  absurd (l1 = r1).  unfold not in |- *; intro.  cut (Neqb l1 r1 = true).  intro.\n  rewrite (proj1 (internal_node_lemma bs x1 l1 r1 node1 H H6)) in H10.\n  discriminate.  rewrite H9.  apply Neqb_correct.\n  apply\n   H0\n    with\n      (m := max (nat_of_N (bs_node_height bs l1))\n              (nat_of_N (bs_node_height bs r1))).\n  rewrite H1.  apply lt_max_1.  apply BDDcompare_lt.  apply bs_node_height_left with (x := x1) (r := r1).\n  assumption.  assumption.  apply BDDcompare_lt.  apply bs_node_height_right with (x := x1) (l := l1).\n  assumption.  assumption.  reflexivity.  apply low_OK with (node := node1) (x := x1) (r := r1).\n  assumption.  assumption.  apply high_OK with (node := node1) (x := x1) (l := l1).\n  assumption.  assumption.  apply\n   bool_fun_eq_trans\n    with (bool_fun_restrict (bool_fun_of_BDD_bs bs node1) x1 false).\n  apply bool_fun_of_BDD_bs_low with (r := r1).  assumption.  assumption.\n  cut (bool_fun_independent (bool_fun_of_BDD_bs bs node1) x1).  intro.\n  apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD_bs bs node1).  apply H9.\n  apply\n   bool_fun_eq_trans\n    with (bf2 := bool_fun_restrict (bool_fun_of_BDD_bs bs node1) x1 true).\n  apply bool_fun_eq_sym.  apply H9.  apply bool_fun_eq_sym.\n  apply bool_fun_of_BDD_bs_high with (l := l1).  assumption.  assumption.\n  apply bool_fun_eq_independent with (bf1 := bool_fun_of_BDD_bs bs node2).\n  apply bool_fun_eq_sym.  assumption.  apply BDDvar_independent_bs.  assumption.\n  assumption.  unfold Nleb in |- *.  apply leb_correct.  unfold bs_node_height in |- *.\n  rewrite H8.  rewrite (ad_S_is_S x2).  apply lt_le_S.  apply BDDcompare_lt.\n  apply BDDcompare_sup_inf.  assumption.  intro y.  unfold in_dom in H7.\n  rewrite y in H7; discriminate.  intro y.  unfold in_dom in H5.\n  rewrite y in H5; discriminate.\nQed.\n\nLemma BDDunique :\n forall (cfg : BDDconfig) (node1 node2 : ad),\n BDDconfig_OK cfg ->\n config_node_OK cfg node1 ->\n config_node_OK cfg node2 ->\n bool_fun_eq (bool_fun_of_BDD cfg node1) (bool_fun_of_BDD cfg node2) ->\n Neqb node1 node2 = true.\nProof.\n  intros.  cut (node1 = node2).  intro.  rewrite H3.  apply Neqb_correct.\n  apply\n   BDDunique_1\n    with\n      (bs := fst cfg)\n      (share := fst (snd cfg))\n      (n := max (nat_of_N (bs_node_height (fst cfg) node1))\n              (nat_of_N (bs_node_height (fst cfg) node2))).\n  exact (proj1 H).  exact (proj1 (proj2 H)).  reflexivity.\n  assumption.  assumption.  assumption.\nQed.\n\nLemma nodes_preserved_bs_bool_fun_1 :\n forall (bs1 bs2 : BDDstate) (n : nat) (node : ad),\n n = nat_of_N (bs_node_height bs1 node) ->\n BDDstate_OK bs1 ->\n BDDstate_OK bs2 ->\n nodes_preserved_bs bs1 bs2 ->\n node_OK bs1 node ->\n bool_fun_eq (bool_fun_of_BDD_bs bs2 node) (bool_fun_of_BDD_bs bs1 node).\nProof.\n  intros bs1 bs2 n.  apply\n   lt_wf_ind\n    with\n      (P := fun n : nat =>\n            forall node : ad,\n            n = nat_of_N (bs_node_height bs1 node) ->\n            BDDstate_OK bs1 ->\n            BDDstate_OK bs2 ->\n            nodes_preserved_bs bs1 bs2 ->\n            node_OK bs1 node ->\n            bool_fun_eq (bool_fun_of_BDD_bs bs2 node)\n              (bool_fun_of_BDD_bs bs1 node)).\n  intros.  elim H4; intro.  rewrite H5.\n  apply bool_fun_eq_trans with (bf2 := bool_fun_zero).  apply bool_fun_of_BDD_bs_zero.\n  assumption.  apply bool_fun_eq_sym.  apply bool_fun_of_BDD_bs_zero.\n  assumption.  elim H5; intro.  rewrite H6.\n  apply bool_fun_eq_trans with (bf2 := bool_fun_one).  apply bool_fun_of_BDD_bs_one.\n  assumption.  apply bool_fun_eq_sym.  apply bool_fun_of_BDD_bs_one.\n  assumption.  elim (option_sum _ (MapGet _ bs1 node)).  intro y.\n  elim y; clear y.  intro.  elim x; clear x; intros x y.\n  elim y; clear y; intros l r H7.  cut (MapGet _ bs2 node = Some (x, (l, r))).\n  intro.  cut (bool_fun_eq (bool_fun_of_BDD_bs bs2 l) (bool_fun_of_BDD_bs bs1 l)).\n  cut (bool_fun_eq (bool_fun_of_BDD_bs bs2 r) (bool_fun_of_BDD_bs bs1 r)).  intros.\n  apply\n   bool_fun_eq_trans\n    with\n      (bf2 := bool_fun_if x (bool_fun_of_BDD_bs bs2 r)\n                (bool_fun_of_BDD_bs bs2 l)).\n  apply bool_fun_of_BDD_bs_int.  assumption.  assumption.\n  apply\n   bool_fun_eq_trans\n    with\n      (bf2 := bool_fun_if x (bool_fun_of_BDD_bs bs1 r)\n                (bool_fun_of_BDD_bs bs1 l)).\n  apply bool_fun_if_preserves_eq.  assumption.  assumption.  apply bool_fun_eq_sym.\n  apply bool_fun_of_BDD_bs_int.  assumption.  assumption.\n  apply H with (m := nat_of_N (bs_node_height bs1 r)).  rewrite H0.  apply BDDcompare_lt.\n  apply bs_node_height_right with (x := x) (l := l).  assumption.  assumption.  reflexivity.\n  assumption.  assumption.  assumption.  apply high_OK with (x := x) (l := l) (node := node).\n  assumption.  assumption.  apply H with (m := nat_of_N (bs_node_height bs1 l)).\n  rewrite H0.  apply BDDcompare_lt.  apply bs_node_height_left with (x := x) (r := r).\n  assumption.  assumption.  reflexivity.  assumption.  assumption.  assumption.\n  apply low_OK with (x := x) (r := r) (node := node).  assumption.  assumption.  apply H3.\n  assumption.  intro y.  unfold in_dom in H6.  rewrite y in H6; discriminate.\nQed.\n\n\nLemma nodes_preserved_bs_bool_fun :\n forall (bs1 bs2 : BDDstate) (node : ad),\n BDDstate_OK bs1 ->\n BDDstate_OK bs2 ->\n nodes_preserved_bs bs1 bs2 ->\n node_OK bs1 node ->\n bool_fun_eq (bool_fun_of_BDD_bs bs2 node) (bool_fun_of_BDD_bs bs1 node).\nProof.\n  intros.  apply\n   nodes_preserved_bs_bool_fun_1\n    with (n := nat_of_N (bs_node_height bs1 node)).\n  reflexivity.  assumption.  assumption.  assumption.  assumption.\nQed.\n\nLemma nodes_preserved_bool_fun :\n forall (cfg1 cfg2 : BDDconfig) (node : ad),\n BDDconfig_OK cfg1 ->\n BDDconfig_OK cfg2 ->\n nodes_preserved cfg1 cfg2 ->\n config_node_OK cfg1 node ->\n bool_fun_eq (bool_fun_of_BDD cfg2 node) (bool_fun_of_BDD cfg1 node).\nProof.\n  intros.  unfold bool_fun_of_BDD in |- *.  apply nodes_preserved_bs_bool_fun.\n  exact (proj1 H).  exact (proj1 H0).  assumption.  assumption.\nQed.\n\nLemma nodes_preserved_neg_memo_OK :\n forall (bs bs' : BDDstate) (negm : BDDneg_memo),\n nodes_preserved_bs bs bs' ->\n BDDstate_OK bs ->\n BDDstate_OK bs' -> BDDneg_memo_OK bs negm -> BDDneg_memo_OK bs' negm.\nProof.\n  intros.  unfold BDDneg_memo_OK in |- *.  unfold BDDneg_memo_OK in H2.  intros.\n  cut\n   (node_OK bs node /\\\n    node_OK bs node' /\\\n    Neqb (bs_node_height bs node') (bs_node_height bs node) = true /\\\n    bool_fun_eq (bool_fun_of_BDD_bs bs node')\n      (bool_fun_neg (bool_fun_of_BDD_bs bs node))).\n  intros.  split.  apply nodes_preserved_bs_node_OK with (bs1 := bs).  assumption.\n  exact (proj1 H4).  split.  apply nodes_preserved_bs_node_OK with (bs1 := bs).\n  assumption.  exact (proj1 (proj2 H4)).  split.\n  cut (Neqb (bs_node_height bs' node') (bs_node_height bs node') = true).  intro.\n  cut (Neqb (bs_node_height bs' node) (bs_node_height bs node) = true).  intro.\n  rewrite (Neqb_complete _ _ H5).  rewrite (Neqb_complete _ _ H6).\n  exact (proj1 (proj2 (proj2 H4))).  apply nodes_preserved_bs_node_height_eq.\n  assumption.  assumption.  assumption.  exact (proj1 H4).\n  apply nodes_preserved_bs_node_height_eq.  assumption.  assumption.  assumption.  \n  exact (proj1 (proj2 H4)).\n  apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD_bs bs node').\n  apply nodes_preserved_bs_bool_fun.  assumption.  assumption.  assumption.\n  exact (proj1 (proj2 H4)).\n  apply\n   bool_fun_eq_trans with (bf2 := bool_fun_neg (bool_fun_of_BDD_bs bs node)).\n  exact (proj2 (proj2 (proj2 H4))).  apply bool_fun_eq_sym.\n  apply bool_fun_neg_preserves_eq.  apply nodes_preserved_bs_bool_fun.\n  assumption.  assumption.  assumption.  exact (proj1 H4).  apply H2.  assumption.\nQed.\n\nLemma nodes_preserved_or_memo_OK :\n forall (bs bs' : BDDstate) (orm : BDDor_memo),\n nodes_preserved_bs bs bs' ->\n BDDstate_OK bs ->\n BDDstate_OK bs' -> BDDor_memo_OK bs orm -> BDDor_memo_OK bs' orm.\nProof.\n  unfold BDDor_memo_OK in |- *.  intros.\n  cut\n   (node_OK bs node1 /\\\n    node_OK bs node2 /\\\n    node_OK bs node /\\\n    Nleb (bs_node_height bs node)\n      (BDDvar_max (bs_node_height bs node1) (bs_node_height bs node2)) = true /\\\n    bool_fun_eq (bool_fun_of_BDD_bs bs node)\n      (bool_fun_or (bool_fun_of_BDD_bs bs node1)\n         (bool_fun_of_BDD_bs bs node2))).\n  intro.  elim H4; clear H4; intros.  elim H5; clear H5; intros.\n  elim H6; clear H6; intros.  elim H7; clear H7; intros.  split.\n  apply nodes_preserved_bs_node_OK with (bs1 := bs).  assumption.  assumption.\n  split.  apply nodes_preserved_bs_node_OK with (bs1 := bs).  assumption.\n  assumption.  split.  apply nodes_preserved_bs_node_OK with (bs1 := bs).\n  assumption.  assumption.  split.\n  cut (Neqb (bs_node_height bs' node1) (bs_node_height bs node1) = true).\n  cut (Neqb (bs_node_height bs' node2) (bs_node_height bs node2) = true).\n  cut (Neqb (bs_node_height bs' node) (bs_node_height bs node) = true).  intros.\n  rewrite (Neqb_complete _ _ H9).  rewrite (Neqb_complete _ _ H10).\n  rewrite (Neqb_complete _ _ H11).  assumption.  apply nodes_preserved_bs_node_height_eq.\n  assumption.  assumption.  assumption.  assumption.  apply nodes_preserved_bs_node_height_eq.\n  assumption.  assumption.  assumption.  assumption.  apply nodes_preserved_bs_node_height_eq.\n  assumption.  assumption.  assumption.  assumption.  \n  apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD_bs bs node).\n  apply nodes_preserved_bs_bool_fun.  assumption.  assumption.  assumption.\n  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_or_preserves_eq.  apply bool_fun_eq_sym.\n  apply nodes_preserved_bs_bool_fun.  assumption.  assumption.  assumption.\n  assumption.  apply bool_fun_eq_sym.  apply nodes_preserved_bs_bool_fun.\n  assumption.  assumption.  assumption.  assumption.  apply H2.  assumption.\nQed.\n\nLemma nodes_preserved_um_OK :\n forall (bs bs' : BDDstate) (um : BDDuniv_memo),\n nodes_preserved_bs bs bs' ->\n BDDstate_OK bs ->\n BDDstate_OK bs' -> BDDuniv_memo_OK bs um -> BDDuniv_memo_OK bs' um.\nProof.\n  intros.  unfold BDDuniv_memo_OK in |- *.  unfold BDDuniv_memo_OK in H2.  intros.\n  cut\n   (node_OK bs node /\\\n    node_OK bs node' /\\\n    Nleb (bs_node_height bs node') (bs_node_height bs node) = true /\\\n    bool_fun_eq (bool_fun_of_BDD_bs bs node')\n      (bool_fun_forall x (bool_fun_of_BDD_bs bs node))).\n  intros.  split.  apply nodes_preserved_bs_node_OK with (bs1 := bs).  assumption.\n  exact (proj1 H4).  split.  apply nodes_preserved_bs_node_OK with (bs1 := bs).\n  assumption.  exact (proj1 (proj2 H4)).  split.\n  cut (Neqb (bs_node_height bs' node') (bs_node_height bs node') = true).  intro.\n  cut (Neqb (bs_node_height bs' node) (bs_node_height bs node) = true).  intro.\n  rewrite (Neqb_complete _ _ H5).  rewrite (Neqb_complete _ _ H6).\n  exact (proj1 (proj2 (proj2 H4))).  apply nodes_preserved_bs_node_height_eq.\n  assumption.  assumption.  assumption.  exact (proj1 H4).\n  apply nodes_preserved_bs_node_height_eq.  assumption.  assumption.  assumption.\n  exact (proj1 (proj2 H4)).\n  apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD_bs bs node').\n  apply nodes_preserved_bs_bool_fun.  assumption.  assumption.  assumption.\n  exact (proj1 (proj2 H4)).\n  apply\n   bool_fun_eq_trans\n    with (bf2 := bool_fun_forall x (bool_fun_of_BDD_bs bs node)).\n  exact (proj2 (proj2 (proj2 H4))).  apply bool_fun_eq_sym.\n  apply bool_fun_forall_preserves_eq.  apply nodes_preserved_bs_bool_fun.\n  assumption.  assumption.  assumption.  exact (proj1 H4).  apply H2.  assumption.\nQed.\n\nLemma node_preserved_bs_bool_fun_1 :\n forall (n : nat) (bs bs' : BDDstate) (node : ad),\n BDDstate_OK bs ->\n BDDstate_OK bs' ->\n node_preserved_bs bs bs' node ->\n node_OK bs node ->\n n = nat_of_N (bs_node_height bs node) ->\n bool_fun_eq (bool_fun_of_BDD_bs bs' node) (bool_fun_of_BDD_bs bs node).\nProof.\n  intro.  apply\n   lt_wf_ind\n    with\n      (P := fun n : nat =>\n            forall (bs bs' : BDDstate) (node : ad),\n            BDDstate_OK bs ->\n            BDDstate_OK bs' ->\n            node_preserved_bs bs bs' node ->\n            node_OK bs node ->\n            n = nat_of_N (bs_node_height bs node) ->\n            bool_fun_eq (bool_fun_of_BDD_bs bs' node)\n              (bool_fun_of_BDD_bs bs node)).\n  clear n.  intros.  elim H3.  intro.  rewrite H5.\n  apply bool_fun_eq_trans with (bf2 := bool_fun_zero).\n  apply bool_fun_of_BDD_bs_zero.  assumption.  apply bool_fun_eq_sym.\n  apply bool_fun_of_BDD_bs_zero.  assumption.  intro.  elim H5; intro.\n  rewrite H6.  apply bool_fun_eq_trans with (bf2 := bool_fun_one).\n  apply bool_fun_of_BDD_bs_one.  assumption.  apply bool_fun_eq_sym.\n  apply bool_fun_of_BDD_bs_one.  assumption.\n  elim (option_sum _ (MapGet _ bs node)).  intro y.  elim y; clear y.  intro.\n  elim x; clear x.  intros x y.  elim y; clear y; intros l r H7.\n  cut\n   (MapGet (BDDvar * (ad * ad)) bs' node =\n    Some (x, (l, r))).  intro.\n  apply\n   bool_fun_eq_trans\n    with\n      (bf2 := bool_fun_if x (bool_fun_of_BDD_bs bs' r)\n                (bool_fun_of_BDD_bs bs' l)).\n  apply bool_fun_of_BDD_bs_int.  assumption.  assumption.  \n  apply\n   bool_fun_eq_trans\n    with\n      (bf2 := bool_fun_if x (bool_fun_of_BDD_bs bs r)\n                (bool_fun_of_BDD_bs bs l)).\n  apply bool_fun_if_preserves_eq.  apply H with (m := nat_of_N (bs_node_height bs r)).\n  rewrite H4.  apply BDDcompare_lt.  apply bs_node_height_right with (x := x) (l := l).\n  assumption.  assumption.  assumption.  assumption.  unfold node_preserved_bs in |- *.\n  intros.  apply H2.  apply nodes_reachable_trans with (node2 := r).\n  apply nodes_reachable_2 with (x := x) (l := l) (r := r).  assumption.\n  apply nodes_reachable_0.  assumption.  assumption.  \n  apply high_OK with (x := x) (l := l) (node := node).  assumption.  assumption.  \n  reflexivity.  apply H with (m := nat_of_N (bs_node_height bs l)).  rewrite H4.\n  apply BDDcompare_lt.  apply bs_node_height_left with (x := x) (r := r).  assumption.  \n  assumption.  assumption.  assumption.  unfold node_preserved_bs in |- *.  intros.\n  apply H2.  apply nodes_reachable_trans with (node2 := l).\n  apply nodes_reachable_1 with (x := x) (l := l) (r := r).  assumption.\n  apply nodes_reachable_0.  assumption.  assumption.  \n  apply low_OK with (x := x) (r := r) (node := node).  assumption.  assumption.\n  reflexivity.  apply bool_fun_eq_sym.  apply bool_fun_of_BDD_bs_int.\n  assumption.  assumption.  apply H2.  apply nodes_reachable_0.  assumption.\n  intro y.  unfold in_dom in H6.  rewrite y in H6.  discriminate.\nQed.\n\nLemma node_preserved_bs_bool_fun :\n forall (bs bs' : BDDstate) (node : ad),\n BDDstate_OK bs ->\n BDDstate_OK bs' ->\n node_preserved_bs bs bs' node ->\n node_OK bs node ->\n bool_fun_eq (bool_fun_of_BDD_bs bs' node) (bool_fun_of_BDD_bs bs node).\nProof.\n  intros.  apply\n   node_preserved_bs_bool_fun_1\n    with (n := nat_of_N (bs_node_height bs node)).\n  assumption.  assumption.  assumption.  assumption.  reflexivity.  \nQed.\n\nLemma node_preserved_bs_node_height_eq :\n forall (bs bs' : BDDstate) (node : ad),\n BDDstate_OK bs ->\n BDDstate_OK bs' ->\n node_preserved_bs bs bs' node ->\n node_OK bs node ->\n Neqb (bs_node_height bs' node) (bs_node_height bs node) = true.\nProof.\n  intros.  unfold bs_node_height in |- *.  elim H2; intros.  rewrite H3.\n  rewrite (proj1 H).  rewrite (proj1 H0).  reflexivity.\n  elim H3; intros.  rewrite H4.  rewrite (proj1 (proj2 H0)).\n  rewrite (proj1 (proj2 H)).  reflexivity.\n  elim (option_sum _ (MapGet (BDDvar * (ad * ad)) bs node)).  intro y.  elim y.  intro x.\n  elim x.  intros y0 y1.  elim y1.  intros y2 y3 y4.  rewrite y4.\n  rewrite (H1 y0 y2 y3 node (nodes_reachable_0 bs node)).  apply Neqb_correct.\n  assumption.  intro y.  unfold in_dom in H4.  rewrite y in H4.  discriminate.\nQed.\n\nLemma node_preserved_node_height_eq :\n forall (cfg cfg' : BDDconfig) (node : ad),\n BDDconfig_OK cfg ->\n BDDconfig_OK cfg' ->\n node_preserved cfg cfg' node ->\n config_node_OK cfg node ->\n Neqb (node_height cfg' node) (node_height cfg node) = true.\nProof.\n  intros.  unfold node_height in |- *.  apply node_preserved_bs_node_height_eq.  exact (proj1 H).\n  exact (proj1 H0).  assumption.  assumption.\nQed.\n\nLemma used_nodes_preserved_node_height_eq :\n forall (cfg cfg' : BDDconfig) (ul : list ad) (node : ad),\n BDDconfig_OK cfg ->\n BDDconfig_OK cfg' ->\n used_nodes_preserved cfg cfg' ul ->\n used_list_OK cfg ul ->\n used_node cfg ul node ->\n Neqb (node_height cfg' node) (node_height cfg node) = true.\nProof.\n  intros.  apply node_preserved_node_height_eq.  assumption.  assumption.\n  unfold node_preserved in |- *.  apply used_nodes_preserved_preserved_bs with (ul := ul).\n  assumption.  assumption.  unfold config_node_OK in |- *.\n  apply used_node_OK_bs with (ul := ul).  exact (proj1 H).  assumption.\n  assumption.\nQed.\n\nLemma used_nodes_preserved'_node_height_eq :\n forall (cfg cfg' : BDDconfig) (ul : list ad) (node : ad),\n BDDconfig_OK cfg ->\n BDDconfig_OK cfg' ->\n used_nodes_preserved cfg cfg' ul ->\n used_list_OK cfg ul ->\n used_node' cfg ul node ->\n Neqb (node_height cfg' node) (node_height cfg node) = true.\nProof.\n  intros.  elim H3.  intro.  rewrite H4.\n  rewrite (Neqb_complete _ _ (node_height_zero cfg H)).\n  rewrite (Neqb_complete _ _ (node_height_zero cfg' H0)).  reflexivity.  intro.\n  elim H4.  intro.  rewrite H5.  rewrite (Neqb_complete _ _ (node_height_one cfg H)).\n  rewrite (Neqb_complete _ _ (node_height_one cfg' H0)).  reflexivity.  intro.\n  apply used_nodes_preserved_node_height_eq with (ul := ul).  assumption.  assumption.\n  assumption.  assumption.  assumption.\nQed.\n\nLemma used_nodes_preserved_bs_bool_fun :\n forall (bs bs' : BDDstate) (ul : list ad) (node : ad),\n BDDstate_OK bs ->\n BDDstate_OK bs' ->\n used_nodes_preserved_bs bs bs' ul ->\n used_list_OK_bs bs ul ->\n used_node_bs bs ul node ->\n bool_fun_eq (bool_fun_of_BDD_bs bs' node) (bool_fun_of_BDD_bs bs node).\nProof.\n  intros.  apply node_preserved_bs_bool_fun.  assumption.  assumption.\n  apply used_nodes_preserved_preserved_bs with (ul := ul).  assumption.  assumption.\n  apply used_node_OK_bs with (ul := ul).  assumption.  assumption.  assumption.\nQed.\n\nLemma used_nodes_preserved'_bs_bool_fun :\n forall (bs bs' : BDDstate) (ul : list ad) (node : ad),\n BDDstate_OK bs ->\n BDDstate_OK bs' ->\n used_nodes_preserved_bs bs bs' ul ->\n used_list_OK_bs bs ul ->\n used_node'_bs bs ul node ->\n bool_fun_eq (bool_fun_of_BDD_bs bs' node) (bool_fun_of_BDD_bs bs node).\nProof.\n  intros.  apply node_preserved_bs_bool_fun.  assumption.  assumption.\n  apply used_nodes_preserved_preserved'_bs with (ul := ul).  assumption.\n  assumption.  assumption.  apply used_node'_OK_bs with (ul := ul).  assumption.\n  assumption.  assumption.\nQed.\n\nLemma used_nodes_preserved_bool_fun :\n forall (cfg cfg' : BDDconfig) (ul : list ad) (node : ad),\n BDDconfig_OK cfg ->\n BDDconfig_OK cfg' ->\n used_nodes_preserved cfg cfg' ul ->\n used_list_OK cfg ul ->\n used_node cfg ul node ->\n bool_fun_eq (bool_fun_of_BDD cfg' node) (bool_fun_of_BDD cfg node).\nProof.\n  intros.  unfold bool_fun_of_BDD in |- *.\n  apply used_nodes_preserved_bs_bool_fun with (ul := ul).  exact (proj1 H).\n  exact (proj1 H0).  assumption.  assumption.  assumption.\nQed.\n\nLemma used_nodes_preserved'_bool_fun :\n forall (cfg cfg' : BDDconfig) (ul : list ad) (node : ad),\n BDDconfig_OK cfg ->\n BDDconfig_OK cfg' ->\n used_nodes_preserved cfg cfg' ul ->\n used_list_OK cfg ul ->\n used_node' cfg ul node ->\n bool_fun_eq (bool_fun_of_BDD cfg' node) (bool_fun_of_BDD cfg node).\nProof.\n  intros.  unfold bool_fun_of_BDD in |- *.\n  apply used_nodes_preserved'_bs_bool_fun with (ul := ul).  exact (proj1 H).\n  exact (proj1 H0).  assumption.  assumption.  assumption.\nQed.\n\nDefinition BDDneg_memo_put (cfg : BDDconfig) (node node' : ad) :=\n  match cfg with\n  | (bs, (share, (fl, (cnt, (negm, z))))) =>\n      (bs, (share, (fl, (cnt, (MapPut _ negm node node', z)))))\n  end.\n\nLemma BDDnegm_put_OK :\n forall (cfg : BDDconfig) (node node' : ad),\n BDDconfig_OK cfg ->\n config_node_OK cfg node ->\n config_node_OK cfg node' ->\n Neqb (node_height cfg node') (node_height cfg node) = true ->\n bool_fun_eq (bool_fun_of_BDD cfg node')\n   (bool_fun_neg (bool_fun_of_BDD cfg node)) ->\n BDDconfig_OK (BDDneg_memo_put cfg node node').\nProof.\n  unfold BDDneg_memo_put in |- *.  intro cfg.  elim cfg.  intros y y0.  elim y0.  intros y1 y2.\n  elim y2.  intros y3 y4.  elim y4.  intros y5 y6.  elim y6.  intros y7 y8 node node' H.\n  unfold BDDconfig_OK in |- *.  unfold BDDconfig_OK in H.  split.\n  exact (proj1 H).  split.  exact (proj1 (proj2 H)).  split.\n  exact (proj1 (proj2 (proj2 H))).  split.\n  exact (proj1 (proj2 (proj2 (proj2 H)))).  simpl in |- *.  simpl in H.\n  split.  unfold BDDneg_memo_OK in |- *.  intros node0 node'0 H4.\n  rewrite (MapPut_semantics ad y7 node node' node0) in H4.\n  elim (sumbool_of_bool (Neqb node node0)).  intro y9.  rewrite y9 in H4.\n  injection H4.  intro H5.  rewrite <- H5.  split.  unfold config_node_OK in H0, H1.\n  simpl in H0, H1.  rewrite <- (Neqb_complete _ _ y9).  assumption.  split.\n  assumption.  split.  rewrite <- (Neqb_complete _ _ y9).  assumption.\n  rewrite <- (Neqb_complete _ _ y9).  assumption.  intro y9.  rewrite y9 in H4.\n  apply (proj1 (proj2 (proj2 (proj2 (proj2 H))))).\n  assumption.  exact (proj2 (proj2 (proj2 (proj2 (proj2 H))))).\nQed.\n\nDefinition BDDor_memo_put (cfg : BDDconfig) (node1 node2 node' : ad) :=\n  match cfg with\n  | (bs, (share, (fl, (cnt, (negm, (orm, um)))))) =>\n      (bs,\n      (share, (fl, (cnt, (negm, (MapPut2 _ orm node1 node2 node', um))))))\n  end.\n\nLemma BDDorm_put_nodes_preserved :\n forall (cfg : BDDconfig) (node1 node2 node' : ad),\n nodes_preserved cfg (BDDor_memo_put cfg node1 node2 node').\nProof.\n  unfold BDDor_memo_put in |- *.  intros.  elim cfg.  unfold nodes_preserved in |- *.  intros y y0.\n  elim y0.  intros y1 y2.  elim y2.  intros y3 y4.  elim y4.  intros y5 y6.  elim y6.  intros y7 y8.\n  elim y8.  intros.  simpl in |- *.  apply nodes_preserved_bs_refl.\nQed.\n\nLemma BDDorm_put_OK :\n forall (cfg : BDDconfig) (node1 node2 node' : ad),\n BDDconfig_OK cfg ->\n config_node_OK cfg node1 ->\n config_node_OK cfg node2 ->\n config_node_OK cfg node' ->\n Nleb (node_height cfg node')\n   (BDDvar_max (node_height cfg node1) (node_height cfg node2)) = true ->\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 BDDconfig_OK (BDDor_memo_put cfg node1 node2 node').\nProof.\n  unfold BDDor_memo_put in |- *.  intro.  elim cfg.  intros y y0.  elim y0.\n  intros y1 y2.  elim y2.  intros y3 y4.  elim y4.  intros y5 y6.  elim y6.\n  intros y7 y8.  elim y8.  intros y9 y10 node1 node2 node'.  intros. unfold BDDconfig_OK in |- *.  unfold BDDconfig_OK in H.\n  split.  exact (proj1 H).  split.  exact (proj1 (proj2 H)).  split.\n  exact (proj1 (proj2 (proj2 H))).  split.\n  exact (proj1 (proj2 (proj2 (proj2 H)))).  split.\n  exact (proj1 (proj2 (proj2 (proj2 (proj2 H))))).  simpl in |- *.\n  simpl in H.  unfold BDDor_memo_OK in |- *.  split.  intros.\n  rewrite (MapPut2_semantics ad y9 node1 node2 node0 node3 node') in H5.\n  elim (sumbool_of_bool (Neqb node1 node0 && Neqb node2 node3)).  intro y11.\n  rewrite y11 in H5.  injection H5.  intro H6.  rewrite <- H6.\n  elim (andb_prop _ _ y11).  intros H7 H8.  rewrite <- (Neqb_complete _ _ H7).\n  rewrite <- (Neqb_complete _ _ H8).  split.  assumption.  split.  assumption.\n  split.  assumption.  split.  assumption.  assumption.  intro y11.\n  rewrite y11 in H5.\n  apply (proj1 (proj2 (proj2 (proj2 (proj2 (proj2 H)))))).\n  assumption.\n  exact (proj2 (proj2 (proj2 (proj2 (proj2 (proj2 H)))))).\n\nQed.\n\nLemma BDDnegm_put_nodes_preserved :\n forall (cfg : BDDconfig) (node node' : ad),\n nodes_preserved cfg (BDDneg_memo_put cfg node node').\nProof.\n  unfold BDDneg_memo_put in |- *.  intros.  elim cfg.  unfold nodes_preserved in |- *.  intros y y0.\n  elim y0.  intros y1 y2.  elim y2.  intros y3 y4.  elim y4.  intros y5 y6.  elim y6.  intros.\n  simpl in |- *.  apply nodes_preserved_bs_refl.\nQed.\n\nDefinition BDDuniv_memo_put (cfg : BDDconfig) (x : BDDvar)\n  (node node' : ad) :=\n  match cfg with\n  | (bs, (share, (fl, (cnt, (negm, (orm, um)))))) =>\n      (bs, (share, (fl, (cnt, (negm, (orm, MapPut2 ad um node x node'))))))\n  end.\n\nLemma BDDum_put_nodes_preserved :\n forall (cfg : BDDconfig) (x : BDDvar) (node node' : ad),\n nodes_preserved cfg (BDDuniv_memo_put cfg x node node').\nProof.\n  unfold BDDuniv_memo_put in |- *.  intros.  elim cfg.  unfold nodes_preserved in |- *.  intros y y0.\n  elim y0.  intros y1 y2.  elim y2.  intros y3 y4.  elim y4.  intros y5 y6.  elim y6.  intros y7 y8.\n  elim y8.  intros.  simpl in |- *.  apply nodes_preserved_bs_refl.\nQed.\n\nLemma BDDum_put_OK :\n forall (cfg : BDDconfig) (x : BDDvar) (node node' : ad),\n BDDconfig_OK cfg ->\n config_node_OK cfg node ->\n config_node_OK cfg node' ->\n Nleb (node_height cfg node') (node_height cfg node) = true ->\n bool_fun_eq (bool_fun_of_BDD cfg node')\n   (bool_fun_forall x (bool_fun_of_BDD cfg node)) ->\n BDDconfig_OK (BDDuniv_memo_put cfg x node node').\nProof.\n  unfold BDDuniv_memo_put in |- *.  intro cfg.  elim cfg.  intro y.  intro y0.  elim y0.  intro y1.\n  intro y2.  elim y2.  intro y3.  intro y4.  elim y4.  intro y5.  intro y6.  elim y6.  intro y7.\n  intro y8.  intro x.  elim y8.  intros y9 y10.  intros. unfold BDDconfig_OK in |- *.  \n  unfold BDDconfig_OK in H.  split.\n  exact (proj1 H).  split.  exact (proj1 (proj2 H)).  split.\n  exact (proj1 (proj2 (proj2 H))).  split.\n  exact (proj1 (proj2 (proj2 (proj2 H)))).  simpl in |- *.  simpl in H.\n  split.  exact (proj1 (proj2 (proj2 (proj2 (proj2 H))))).\n  split.  exact (proj1 (proj2 (proj2 (proj2 (proj2 (proj2 H)))))).\n  unfold BDDuniv_memo_OK in |- *.  intros x0 node0 node'0 H4.\n  rewrite (MapPut2_semantics ad y10 node x node0 x0 node') in H4.\n  elim (sumbool_of_bool (Neqb node node0 && Neqb x x0)).\n  intro y11.  rewrite y11 in H4.  injection H4.  intro H5.  rewrite <- H5.\n  elim (andb_prop _ _ y11).  intros H6 H7.  rewrite <- (Neqb_complete _ _ H6).\n  rewrite <- (Neqb_complete _ _ H7).  split.  assumption.  split.  assumption. \n  split.  assumption.  assumption.  intro y11.  rewrite y11 in H4.\n  apply (proj2 (proj2 (proj2 (proj2 (proj2 (proj2 H)))))).\n  assumption.\nQed.\n\n\nLemma not_zero_is_one :\n forall (cfg : BDDconfig) (node : ad),\n config_node_OK cfg node ->\n in_dom _ node (fst cfg) = false ->\n Neqb node BDDzero = false -> Neqb node BDDone = true.\nProof.\n  intros.  elim H.  intro.  rewrite H2 in H1.  simpl in H1.  discriminate.\n  intro.  elim H2.  intro.  rewrite H3.  reflexivity.  intro.  rewrite H0 in H3.\n  discriminate.  \nQed.\n\nLemma used'_zero :\n forall (cfg : BDDconfig) (ul : list ad), used_node' cfg ul BDDzero.\nProof.\n  left.  reflexivity.\nQed.\n\nLemma used'_one :\n forall (cfg : BDDconfig) (ul : list ad), used_node' cfg ul BDDone.\nProof.\n  right.  left.  reflexivity.\nQed.\n\nLemma cons_OK_list_OK :\n forall (cfg : BDDconfig) (ul : list ad) (node : ad),\n used_list_OK cfg (node :: ul) -> used_list_OK cfg ul.\nProof.\n  unfold used_list_OK in |- *.  unfold used_list_OK_bs in |- *.  intros.  apply H.\n  apply in_cons.  assumption.\nQed.\n\nEnd BDD_config_1.", "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/config.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.2774742096432721}}
{"text": "Require 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.predicates_sl.\nRequire Import VST.msl.subtypes.\n\nLocal Open Scope pred.\n\n\nLemma unfash_derives {A} `{agA : ageable A}:\n  forall {P Q}, (P |-- Q) -> @derives A _ (! P) (! Q).\nProof.\nintros. intros w ?. simpl in *. apply H. auto.\nQed.\n\nLemma subp_sepcon {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A} : forall G P P' Q Q',\n  G |-- P >=> P' ->\n  G |-- Q >=> Q' ->\n  G |-- P * Q >=> P' * Q'.\nProof.\n  pose proof I.\n  repeat intro.\n  specialize (H0 _ H2).\n  specialize (H1 _ H2).\n  clear G H2.\n  destruct H5 as [w1 [w2 [? [? ?]]]].\n  exists w1; exists w2; split; auto.\n  split.\n  eapply H0; auto.\n  assert (level w1 = level a').\n  apply comparable_fashionR.  eapply join_sub_comparable; eauto.\n apply necR_level in H4. omega.\n  eapply H1; auto.\n  assert (level w2 = level a').\n  apply comparable_fashionR. eapply join_sub_comparable; eauto.\n apply necR_level in H4. omega.\nQed.\n\nLemma sub_wand {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A} : forall G P P' Q Q',\n  G |-- P' >=> P ->\n  G |-- Q >=> Q' ->\n  G |-- (P -* Q) >=> (P' -* Q').\nProof.\n  pose proof I.\n  repeat intro.\n  specialize (H0 _ H2); specialize (H1 _ H2); clear G H2; pose (H2:=True).\n  eapply H0 in H8; try apply necR_refl.\n  eapply H1; try apply necR_refl.\n  apply necR_level in H4. apply necR_level in H6. apply join_comparable in H7.\n  apply comparable_fashionR in H7. unfold fashionR in H7. omega.\n  eapply H5; eauto.\n  apply necR_level in H4. apply necR_level in H6.\n   apply join_comparable2 in H7.\n  apply comparable_fashionR in H7. unfold fashionR in H7. omega.\nQed.\n\nLemma find_superprecise {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A}:\n   forall Q, Q |-- EX P:_, P && !(P >=> Q) && !!superprecise (P).\nProof.\nintros.\nintros w ?.\nexists (exactly w).\nsplit; auto.\nsplit; auto.\nhnf; apply necR_refl.\nintros w' ? w'' ? ?.\nhnf in H2.\napply pred_nec_hereditary with w; auto.\ndo 3 red.\napply superprecise_exactly.\nQed.\n\nLemma sepcon_subp' {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A}:\n  forall (P P' Q Q' : pred A) (st: nat),\n    (P >=> P') st ->\n    (Q >=> Q') st ->\n    (P * Q >=> P' * Q') st.\nProof.\n pose proof I.\nintros.\nintros w' ? w'' ? [w1 [w2 [? [? ?]]]].\ndestruct (nec_join4 _ _ _ _ H4 H3) as [w1' [w2' [? [? ?]]]].\nexists w1; exists w2; repeat split; auto.\neapply (H0 w1'); eauto.\nsimpl in *.\nsubst.\nreplace (level w1') with (level w'); auto.\nsymmetry; apply comparable_fashionR; eapply join_comparable; eauto.\neapply (H1 w2'); eauto.\nreplace (level w2') with (level w'); auto.\nsymmetry. apply comparable_fashionR.\neapply join_comparable; eauto.\nQed.\n\nLemma subp_refl'  {A} `{agA : ageable A} :  forall (Q: pred A) (st: nat), (Q >=> Q) st.\nProof.\nintros.\nintros ? ? ? ?; auto.\nQed.\n\nLemma subp_trans' {A} `{agA : ageable A}:\n  forall (B C D: pred A) (w: nat), (B >=> C)%pred w -> (C >=> D)% pred w -> (B >=> D)%pred w.\nProof.\nintros.\nintros w' ? w'' ? ?.\neapply H0; eauto.\neapply H; eauto.\nQed.\n\nLemma andp_subp'  {A} `{agA : ageable A} :\n forall (P P' Q Q': pred A) (w: nat), (P >=> P') w -> (Q >=> Q') w -> (P && Q >=> P' && Q') w.\nProof.\nintros.\nintros w' ? w'' ? [? ?]; split.\neapply H; eauto.\neapply H0; eauto.\nQed.\n\nLemma allp_subp' {A} `{agA : ageable A}: forall T (F G: T -> pred A) (w: nat),\n   (forall x,  (F x >=> G x) w) -> (allp (fun x:T => (F x >=> G x)) w).\nProof.\nintros.\nintro x; apply H; auto.\nQed.\n\n\nLemma pred_eq_e1 {A} `{agA : ageable A}: forall (P Q: pred A) w,\n       ((P <=> Q) w -> (P >=> Q) w).\nProof.\nintros.\nintros w' ? w'' ? ?.\neapply H; eauto.\nQed.\n\nLemma pred_eq_e2 {A} `{agA : ageable A}: forall (P Q: pred A)  w,\n     ((P <=> Q) w -> (Q >=> P) w).\nProof.\nProof.\nintros.\nintros w' ? w'' ? ?.\neapply H; eauto.\nQed.\n\nHint Resolve @sepcon_subp'.\nHint Resolve @subp_refl'.\nHint Resolve @andp_subp'.\nHint Resolve @allp_subp'.\nHint Resolve @derives_subp.\nHint Resolve @pred_eq_e1.\nHint Resolve @pred_eq_e2.\n\n\nLemma allp_imp2_later_e2 {B}{A}{agA: ageable A}:\n   forall (P Q: B -> pred A) (y: B) ,\n      (ALL x:B, |> P x <=> |> Q x) |-- |> Q y >=> |> P y.\nProof.\n  intros.  intros w ?. specialize (H y). apply pred_eq_e2. auto.\nQed.\nLemma allp_imp2_later_e1 {B}{A}{agA: ageable A}:\n   forall (P Q: B -> pred A) (y: B) ,\n      (ALL x:B, |> P x <=> |> Q x) |-- |> P y >=> |> Q y.\nProof.\n  intros.  intros w ?. specialize (H y). apply pred_eq_e1. auto.\nQed.\n\n(*\nLemma subp_later {A} `{agA:  ageable A} (SS: natty A):\n forall (P Q: pred A), |> (P >=> Q) |-- |> P >=> |> Q.\nProof.\nintros.\nrewrite later_fash; auto.\napply fash_derives.\napply axiomK.\nQed.\n*)\n\nLemma extend_unfash {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A} : forall (P: pred nat), boxy extendM (! P).\nProof.\nintros.\napply boxy_i; auto; intros.\nunfold unfash in *.\nsimpl in H. destruct H.\nhnf in H0|-*.\nreplace (level w') with (level w); auto.\napply comparable_fashionR.\neapply join_comparable; eauto.\nQed.\n\nHint Resolve @extend_unfash.\n\nLemma subp_unfash {A} `{Age_alg A}:\n  forall (P Q : pred nat) (n: nat), (P >=> Q) n -> ( ! P >=> ! Q) n.\nProof.\nintros.\nintros w ?. specialize (H0 _ H1).\nintros w' ? ?. apply (H0 _ (necR_level' H2)).\nauto.\nQed.\nHint Resolve @subp_unfash.\n\n\nLemma unfash_sepcon_distrib:\n        forall {T}{agT: ageable T}{JoinT: Join T}{PermT: Perm_alg T}{SepT: Sep_alg T}{AgeT: Age_alg T}\n           (P: pred nat) (Q R: pred T),\n               unfash P && (Q*R) = (unfash P && Q) * (unfash P && R).\nProof.\nintros.\napply pred_ext.\nintros w [? [w1 [w2 [? [? ?]]]]].\nexists w1; exists w2; repeat split; auto.\napply join_level in H0. destruct H0.\nhnf in H|-*. congruence.\napply join_level in H0. destruct H0.\nhnf in H|-*. congruence.\nintros w [w1 [w2 [? [[? ?] [? ?]]]]].\nsplit.\napply join_level in H. destruct H.\nhnf in H0|-*. congruence.\nexists w1; exists w2; repeat split; 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/msl/subtypes_sl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2774544490319686}}
{"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(*\nDefinition dec_aux_struct_field (denv: PTree.t dec_type) (i: positive) (m: members): dec_type :=\n  match field_type i m, field_offset cenv_cs i m with\n  | Errors.OK t, Errors.OK ofs => existT (fun P: Z -> Prop => forall z: Z, {P z} + {~ P z}) (fun z => projT1 (dec_aux denv t) (z + ofs)) (fun z => projT2 (dec_aux denv t) (z + ofs))\n  | _, _ => dec_False\n  end.\n\nDefinition dec_aux_union_field (denv: PTree.t dec_type) (i: positive) (m: members): dec_type :=\n  match field_type i m with\n  | Errors.OK t => dec_aux denv t\n  | _ => dec_False\n  end.\n\nFixpoint dec_aux_struct_composite (denv: PTree.t dec_type) (m_rec m: members): dec_type :=\n  match m_rec with\n  | nil => dec_True\n  | (i, _) :: m_rec' => existT (fun P: Z -> Prop => forall z: Z, {P z} + {~ P z}) (fun z => projT1 (dec_aux_struct_field denv i m) z /\\ projT1 (dec_aux_struct_composite denv m_rec' m) z) (fun z => sumbool_dec_and (projT2 (dec_aux_struct_field denv i m) z) (projT2 (dec_aux_struct_composite denv m_rec' m) z))\n  end.\n\nFixpoint dec_aux_union_composite (denv: PTree.t dec_type) (m_rec m: members): dec_type :=\n  match m_rec with\n  | nil => dec_True\n  | (i, _) :: m_rec' => existT (fun P: Z -> Prop => forall z: Z, {P z} + {~ P z}) (fun z => projT1 (dec_aux_union_field denv i m) z /\\ projT1 (dec_aux_union_composite denv m_rec' m) z) (fun z => sumbool_dec_and (projT2 (dec_aux_union_field denv i m) z) (projT2 (dec_aux_union_composite denv m_rec' m) z))\n  end.\n\n\nDefinition dec_aux: type -> dec_type.\n  refine (type_func (fun _ => dec_type) _ _ _ _).\n  + intro t.\n    exact (match access_mode t with\n           | By_value ch => dec_by_value ch\n           | _ => dec_False\n           end).\n  + intros t' n _ d.\n    exact (existT (fun P: Z -> Prop => forall z: Z, {P z} + {~ P z}) (fun z => forall i, 0 <= i < n -> projT1 d (z + sizeof t' * i)) (fun z => Zrange_pred_dec (fun i => projT1 d (z + sizeof t' * i)) (fun i => projT2 d (z + sizeof t' * i)) 0 n)).\n  + intros id _ D.\n    unfold FT_aux in D.\n    \n\n\nDefinition dec_aux_composite (denv: PTree.t dec_type) (su: struct_or_union) (m: members): dec_type :=\n  match su with\n  | Struct => dec_aux_struct_composite denv m m\n  | Union => dec_aux_union_composite denv m m\n  end.\n\nDefinition dec_aux_env : PTree.t dec_type :=\n  let l := composite_reorder.rebuild_composite_elements cenv in\n  fold_right (fun (ic: positive * composite) (T0: PTree.t dec_type) => let (i, co) := ic in let T := T0 in PTree.set i (dec_aux_composite T (co_su co) (co_members co)) T) (PTree.empty _) l.\n\n *)\n\nLemma align_compatible_rec_dec: forall t z, {align_compatible_rec cenv_cs t z} + {~ align_compatible_rec cenv_cs t z}.\nAdmitted.\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.\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/align_compatible_dec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.27732401641140564}}
{"text": "\nRequire Import null_listat1_spec.\n\n\n\nDefinition type_LF_155 :=  PLAN ->  nat ->  nat ->  nat -> (Prop * (List.list term)).\n\nDefinition F_155 : type_LF_155:= (fun   u1 u2 _ _ => (u1 = Nil -> (listAt u1 u2) = Nil, (model_PLAN u1)::(Term id_Nil nil)::(Term id_listAt ((model_PLAN u1):: (model_nat u2)::nil))::(Term id_Nil nil)::nil)).\nDefinition F_167 : type_LF_155:= (fun    _  _ _ _ => (Nil = Nil -> Nil = Nil, (Term id_Nil nil)::(Term id_Nil nil)::(Term id_Nil nil)::(Term id_Nil nil)::nil)).\nDefinition F_173 : type_LF_155:= (fun   u5 u2 u6 u7 => ((Cons (C u6 u7) u5) = Nil -> (le (time (C u6 u7)) u2) = true -> (Cons (C u6 u7) u5) = Nil, (Term id_Cons ((Term id_C ((model_nat u6):: (model_nat u7)::nil)):: (model_PLAN u5)::nil))::(Term id_Nil nil)::(Term id_le ((Term id_time ((Term id_C ((model_nat u6):: (model_nat u7)::nil))::nil)):: (model_nat u2)::nil))::(Term id_true nil)::(Term id_Cons ((Term id_C ((model_nat u6):: (model_nat u7)::nil)):: (model_PLAN u5)::nil))::(Term id_Nil nil)::nil)).\nDefinition F_179 : type_LF_155:= (fun   u5 u2 u6 u7 => ((Cons (C u6 u7) u5) = Nil -> (le (time (C u6 u7)) u2) = false -> (listAt u5 u2) = Nil, (Term id_Cons ((Term id_C ((model_nat u6):: (model_nat u7)::nil)):: (model_PLAN u5)::nil))::(Term id_Nil nil)::(Term id_le ((Term id_time ((Term id_C ((model_nat u6):: (model_nat u7)::nil))::nil)):: (model_nat u2)::nil))::(Term id_false nil)::(Term id_listAt ((model_PLAN u5):: (model_nat u2)::nil))::(Term id_Nil nil)::nil)).\n\nDefinition LF_155 := [F_155, F_167, F_173, F_179].\n\n\nFunction f_155 (u1: PLAN) (u2: nat) {struct u1} : PLAN :=\n match u1, u2 with\n| Nil, _ => Nil\n| (Cons (C u6 u7) u5), _ => Nil\nend.\n\nLemma main_155 : forall F, In F LF_155 -> forall u1, forall u2, forall u3, forall u4, (forall F', In F' LF_155 -> 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 [ 155 ] *)\n\nrename u1 into _u1. rename u2 into _u2. rename u3 into d_u3. rename u4 into d_u4. \nrename _u1 into u1. rename _u2 into u2. \n\nrevert Hind.\n\npattern u1, u2, (f_155 u1 u2). apply f_155_ind.\n\n(* case [ 167 ] *)\n\nintros _u1 _u2.  intro eq_1. intro. intro Heq2. rewrite <- Heq2.  intro HFabs0.\nassert (Hind := HFabs0 F_167). clear HFabs0.\nassert (HFabs0 : fst (F_167 Nil 0 0 0)).\napply Hind. trivial_in 1. unfold snd. unfold F_167. unfold F_155. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_155. unfold F_167.\nauto.\n\n\n\nintros _u1 _u2. intro u6. intro u7. intro u5.  intro eq_1. intro. intro Heq2. rewrite <- Heq2.  intro HFabs0.\ncase_eq (le (time (C u6 u7)) _u2); [intro H | intro H].\n\n(* case [ 173 ] *)\n\nassert (Hind := HFabs0 F_173). clear HFabs0.\nassert (HFabs0 : fst (F_173 u5 _u2 u6 u7)).\napply Hind. trivial_in 2. unfold snd. unfold F_173. unfold F_155. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_155. unfold F_173. 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 [ 179 ] *)\n\nassert (Hind := HFabs0 F_179). clear HFabs0.\nassert (HFabs0 : fst (F_179 u5 _u2 u6 u7)).\napply Hind. trivial_in 3. unfold snd. unfold F_179. unfold F_155. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_155. unfold F_179. 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 [ 167 ] *)\n\nunfold fst. unfold F_167.\nauto.\n\n\n\n\t(* TAUTOLOGY on [ 173 ] *)\n\nunfold fst. unfold F_173.\nauto.\n\n\n\n\t(* NEGATIVE CLASH on [ 179 ] *)\n\nunfold fst. unfold F_179. intros. try discriminate.\n\n\n\nQed.\n\n\n\n(* the set of all formula instances from the proof *)\nDefinition S_155 := fun f => exists F, In F LF_155 /\\ exists e1, exists e2, exists e3, exists e4, f = F e1 e2 e3 e4.\n\nTheorem all_true_155: forall F, In F LF_155 -> 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_155);\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_155;\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_155: forall (u1: PLAN) (u2: nat), u1 = Nil -> (listAt u1 u2) = Nil.\nProof.\ndo 2 intro.\napply (all_true_155 F_155);\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_listat1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2773218980182812}}
{"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 type_sys_useful.\nRequire Export etype_family.\nRequire Import dest_close.\n\n\n\n\nLemma close_type_system_isect :\n  forall (ts : candidate-type-system)\n         T T'\n         (eq : per)\n         A A' v v' B B' eqa eqa' eqb\n         f f' g g',\n    type_system ts\n    -> defines_only_universes ts\n    -> computes_to_valc T (mkc_eisect A v B)\n    -> computes_to_valc T' (mkc_eisect A' v' B')\n    -> close ts A A eqa\n    -> close ts A' A' eqa'\n    -> (forall (a : CTerm) (e : eqa a a),\n          close ts (substc a v B) (substc (f a e) v' B') (eqb a (f a e) e (g a e)))\n    -> (forall (a : CTerm) (e : eqa a a),\n          type_system ts\n          -> defines_only_universes ts\n          -> type_sys_props (close ts) (substc a v B) (substc (f a e) v' B')\n                            (eqb a (f a e) e (g a e)))\n    -> (forall (a' : CTerm) (e' : eqa' a' a'),\n          close ts (substc (f' a' e') v B) (substc a' v' B') (eqb (f' a' e') a' (g' a' e') e'))\n    -> (forall (a' : CTerm) (e' : eqa' a' a'),\n          type_system ts\n          -> defines_only_universes ts\n          -> type_sys_props (close ts) (substc (f' a' e') v B) (substc a' v' B')\n                            (eqb (f' a' e') a' (g' a' e') e'))\n    -> (eq <=2=> (eisect_eq eqa eqa' eqb))\n    -> per_eisect (close ts) T T' eq\n    -> type_sys_props (close ts) A A eqa\n    -> type_sys_props (close ts) A' A' eqa'\n    -> type_sys_props (close ts) T T' eq.\nProof.\n  introv tysys dou c1 c2 cla cla' clb tspb clb' tspb'.\n  introv eqiff perTT' IHa IHa'.\n\n  rw type_sys_props_iff_type_sys_props2.\n  prove_type_sys_props2 SCase; intros.\n\n  + SCase \"uniquely_valued\".\n    dclose cl cl; dclose_lr.\n\n    * SSCase \"CL_isect\".\n      allunfold per_eisect; exrepd.\n      apply eq_term_equals_trans with (eq2 := eisect_eq eqa0 eqa'0 eqb0);\n        try (complete (apply eq_term_equals_sym; auto)).\n      apply eq_term_equals_trans with (eq2 := eisect_eq eqa eqa' eqb); auto.\n\nXXXXXXXXXX\n\n      generalize (eq_term_equals_type_family T T3 eqa0 eqa eqb0 eqb (close ts) A v B A' v' B' mkc_isect); intro i.\n      repeat (autodimp i hyp; try (complete (introv e; eqconstr e; sp))); repnd.\n\n      unfold eq_term_equals; sp.\n      rw t0; rw eqiff; split; sp.\n\n      duplicate e as e'; rw <- i0 in e.\n      generalize (i1 a a' e' e); intro k.\n      rw k; sp.\n\n      duplicate e as e'; rw i0 in e.\n      generalize (i1 a a' e e'); intro k.\n      rw <- k; sp.\n\n    * SSCase \"CL_isect\".\n      allunfold per_isect; exrepd.\n      generalize (eq_term_equals_type_family T' T3 eqa0 eqa eqb0 eqb (close ts) A' v' B' A v B mkc_isect); intro i.\n      repeat (autodimp i hyp; try (complete (introv e; eqconstr e; sp))); repnd.\n      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\n      unfold eq_term_equals; sp.\n      rw t0; rw eqiff; split; sp.\n\n      duplicate e as e'; rw <- i0 in e.\n      generalize (i1 a a' e' e); intro k.\n      rw k; sp.\n\n      duplicate e as e'; rw i0 in e.\n      generalize (i1 a a' e e'); intro k.\n      rw <- k; sp.\n\n  + SCase \"type_symmetric\"; repdors; subst; dclose_lr;\n    apply CL_isect;\n    clear per;\n    allunfold per_isect; exrepd;\n    unfold per_isect;\n    exists eqa0 eqb0; sp;\n    allrw <-; sp.\n\n  + SCase \"type_value_respecting\"; repdors; subst;\n    apply CL_isect; unfold per_isect; exists eqa eqb; sp.\n\n    duplicate c1 as ct.\n    apply cequivc_mkc_isect 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_isect 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; sp.\n    onedtsp e p p0 p1 c t t0 t3 tygs tygt dum.\n    apply eqiff; sp.\n    assert (eqa a a) as eqaa by (apply t0 with (t2 := a'); auto).\n    assert (eqa a' a) as e' by auto.\n    assert (eq t1 t2) as eq12 by auto.\n    apply eqiff with (a := a') (a' := a) (e := e') in eq12; auto.\n\n    generalize (eq_term_equals_sym_tsp (close ts) eqa eqb a a' eqaa e0 e'\n                                       v B v' B'); intro i.\n    autodimp i h; repnd.\n\n    (* Now we prove the equality between the applies *)\n    unfold eq_term_equals in i.\n    apply i in eq12.\n    generalize (recb a a' e0); sp.\n    onedtsp X5 X6 X7 X8 X9 X10 X11 X4 tygs1 tygt1 dum1; sp.\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    apply eqiff with (a := a) (a' := a') (e := e) in eq12; auto.\n    apply eqiff with (a := a) (a' := a') (e := e) in eq23; auto.\n\n    onedtsp IHX0 IHX2 IHX3 IHX4 IHX5 IHX6 IHX7 IHX8 tygs tygt dum.\n\n    generalize (recb a a' e); intro tsp.\n    unfold type_sys_props in tsp; sp.\n    apply tsp6 with (t2 := t2); 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 with (a := a) (a' := a') (e := e) in eqtt; auto.\n\n    generalize (recb a a' e); sp.\n    onedtsp X5 X6 X7 X8 X9 X10 X11 X4 tygs1 tygt1 dum1; sp.\n\n  + SCase \"type_gsymmetric\"; repdors; subst; split; sp; dclose_lr;\n    apply CL_isect;\n    clear per;\n    allunfold per_isect; exrepd.\n\n    (* 1 *)\n    generalize (eq_term_equals_type_family\n                  T T3 eqa0 eqa eqb0 eqb (close ts)\n                  A v B A' v' B' mkc_isect); intro i.\n    repeat (autodimp i hyp; try (complete (introv e; eqconstr e; sp))).\n    repnd.\n\n    unfold per_isect.\n    exists eqa eqb; sp.\n\n    rw t0; split; intro k; sp.\n\n    duplicate e as e'.\n    rw i0 in e.\n    generalize (k a a' e); intro j.\n    generalize (i1 a a' e e'); intro eqt.\n    rw eqt in j; sp.\n\n    duplicate e as e'.\n    rw <- i0 in e.\n    generalize (k a a' e); intro j.\n    generalize (i1 a a' e' e); intro eqt.\n    rw <- eqt in j; sp.\n\n    (* 2 *)\n    generalize (eq_term_equals_type_family2\n                  T3 T eqa0 eqa eqb0 eqb (close ts)\n                  A v B A' v' B' mkc_isect); intro i;\n    repeat (autodimp i hyp; try (complete (introv e; eqconstr e; sp)));\n    repnd.\n\n    unfold per_isect.\n    exists eqa eqb; sp.\n\n    rw t0; split; intro k; sp.\n\n    duplicate e as e'.\n    rw i0 in e.\n    generalize (k a a' e); intro j.\n    generalize (i1 a a' e e'); intro eqt.\n    rw eqt in j; sp.\n\n    duplicate e as e'.\n    rw <- i0 in e.\n    generalize (k a a' e); intro j.\n    generalize (i1 a a' e' e); intro eqt.\n    rw <- eqt in j; sp.\n\n    (* 3 *)\n    generalize (eq_term_equals_type_family\n                  T' T3 eqa0 eqa eqb0 eqb (close ts)\n                  A' v' B' A v B mkc_isect); intro i.\n    repeat (autodimp i hyp;\n            try (complete (introv e; eqconstr e; 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    unfold per_isect.\n    exists eqa eqb; sp.\n\n    rw t0; split; intro k; sp.\n\n    duplicate e as e'.\n    rw i0 in e.\n    generalize (k a a' e); intro j.\n    generalize (i1 a a' e e'); intro eqt.\n    rw eqt in j; sp.\n\n    duplicate e as e'.\n    rw <- i0 in e.\n    generalize (k a a' e); intro j.\n    generalize (i1 a a' e' e); intro eqt.\n    rw <- eqt in j; sp.\n\n    (* 4 *)\n    generalize (eq_term_equals_type_family2\n                  T3 T' eqa0 eqa eqb0 eqb (close ts)\n                  A' v' B' A v B mkc_isect); intro i;\n    repeat (autodimp i hyp;\n            try (complete (introv e; eqconstr e; 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    unfold per_isect.\n    exists eqa eqb; sp.\n\n    rw t0; split; intro k; sp.\n\n    duplicate e as e'.\n    rw i0 in e.\n    generalize (k a a' e); intro j.\n    generalize (i1 a a' e e'); intro eqt.\n    rw eqt in j; sp.\n\n    duplicate e as e'.\n    rw <- i0 in e.\n    generalize (k a a' e); intro j.\n    generalize (i1 a a' e' e); intro eqt.\n    rw <- eqt in j; sp.\n\n  + SCase \"type_gtransitive\"; sp.\n\n  + SCase \"type_mtransitive\".\n    repdors; subst; dclose_lr;\n    try (move_term_to_top (per_isect (close ts) T T4 eq2));\n    try (move_term_to_top (per_isect (close ts) T' T4 eq2)).\n\n    (* 1 *)\n    clear per.\n    allunfold per_isect; exrepd.\n\n    generalize (eq_term_equals_type_family2\n                  T3 T eqa1 eqa eqb1 eqb (close ts)\n                  A v B A' v' B' mkc_isect); intro i.\n    repeat (autodimp i hyp; try (complete (introv e; eqconstr e; sp))).\n    repnd.\n\n    generalize (type_family_trans2\n                  mkc_isect (close ts) T3 T T4 eqa eqb eqa0 eqb0 A v B A' v' B'); intro j.\n    repeat (autodimp j hyp; try (complete (introv e; eqconstr e; sp))).\n    repnd.\n\n    dands; apply CL_isect; unfold per_isect; exists eqa eqb; sp; allrw.\n\n    split; intro p; sp.\n\n    assert (eqa1 a a') as e' by (rw <- i0; auto).\n    generalize (p a a' e'); intro k.\n    generalize (i1 a a' e' e); intro l.\n    rw <- l; sp.\n\n    assert (eqa a a') as e' by (rw i0; auto).\n    generalize (p a a' e'); intro k.\n    generalize (i1 a a' e e'); intro l.\n    rw l; sp.\n\n    split; intro p; sp.\n\n    assert (eqa0 a a') as e' by (rw <- j0; auto).\n    generalize (p a a' e'); intro k.\n    generalize (j1 a a' e e'); intro l.\n    rw l; sp.\n\n    assert (eqa a a') as e' by (rw j0; auto).\n    generalize (p a a' e'); intro k.\n    generalize (j1 a a' e' e); intro l.\n    rw <- l; sp.\n\n    split; intro p; sp.\n\n    assert (eqa1 a a') as e' by (rw <- i0; auto).\n    generalize (p a a' e'); intro k.\n    generalize (i1 a a' e' e); intro l.\n    rw <- l; sp.\n\n    assert (eqa a a') as e' by (rw i0; auto).\n    generalize (p a a' e'); intro k.\n    generalize (i1 a a' e e'); intro l.\n    rw l; sp.\n\n    (* 2 *)\n    clear per.\n    allunfold per_isect; exrepd.\n\n    generalize (eq_term_equals_type_family2\n                  T3 T' eqa1 eqa eqb1 eqb (close ts)\n                  A' v' B' A v B mkc_isect); intro i.\n    repeat (autodimp i hyp;\n            try (complete (introv e; eqconstr e; 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                  mkc_isect (close 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 e; eqconstr e; 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_isect; unfold per_isect; exists eqa eqb; sp; allrw.\n\n    split; intro p; sp.\n\n    assert (eqa1 a a') as e' by (rw <- i0; auto).\n    generalize (p a a' e'); intro k.\n    generalize (i1 a a' e' e); intro l.\n    rw <- l; sp.\n\n    assert (eqa a a') as e' by (rw i0; auto).\n    generalize (p a a' e'); intro k.\n    generalize (i1 a a' e e'); intro l.\n    rw l; sp.\n\n    split; intro p; sp.\n\n    assert (eqa0 a a') as e' by (rw <- j0; auto).\n    generalize (p a a' e'); intro k.\n    generalize (j1 a a' e e'); intro l.\n    rw l; sp.\n\n    assert (eqa a a') as e' by (rw j0; auto).\n    generalize (p a a' e'); intro k.\n    generalize (j1 a a' e' e); intro l.\n    rw <- l; sp.\n\n    split; intro p; sp.\n\n    assert (eqa1 a a') as e' by (rw <- i0; auto).\n    generalize (p a a' e'); intro k.\n    generalize (i1 a a' e' e); intro l.\n    rw <- l; sp.\n\n    assert (eqa a a') as e' by (rw i0; auto).\n    generalize (p a a' e'); intro k.\n    generalize (i1 a a' e e'); intro l.\n    rw l; 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/close/close_type_sys_per_eisect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2773218980182812}}
{"text": "From isla Require Import opsem.\n\nDefinition a24 : isla_trace :=\n  Smt (DeclareConst 0%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"PC\" [] (RegVal_Base (Val_Symbolic 0%Z)) Mk_annot :t:\n  Smt (DefineConst 1%Z (Manyop (Bvmanyarith Bvadd) [Val (Val_Symbolic 0%Z) Mk_annot; Val (Val_Bits (BV 64%N 0x4%Z)) Mk_annot] Mk_annot)) Mk_annot :t:\n  Smt (DeclareConst 13%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"x13\" [] (RegVal_Base (Val_Symbolic 13%Z)) Mk_annot :t:\n  Smt (DefineConst 14%Z (Manyop (Bvmanyarith Bvadd) [Val (Val_Symbolic 13%Z) Mk_annot; Val (Val_Bits (BV 64%N 0x0%Z)) Mk_annot] Mk_annot)) Mk_annot :t:\n  WriteReg \"x18\" [] (RegVal_Base (Val_Symbolic 14%Z)) Mk_annot :t:\n  WriteReg \"PC\" [] (RegVal_Base (Val_Symbolic 1%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/binary_search_riscv64/a24.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.27728271358748385}}
{"text": "Require Import GL4ip_PSGL4ip_calcs.\nRequire Import List.\nExport ListNotations.\n\nRequire Import genT gen.\nRequire Import ddT.\nRequire Import gen_tacs.\nRequire Import gen_seq.\nRequire Import List_lemmasT.\nRequire Import existsT.\nRequire Import univ_gen_ext.\nRequire Import GL4ip_PSGL4ip_list_lems.\nRequire Import dd_fc.\nRequire Import PeanoNat.\nRequire Import strong_inductionT.\nRequire Import GL4ip_exch.\nRequire Import GL4ip_wkn.\nRequire Import GL4ip_PSGL4ip_remove_list.\nRequire Import GL4ip_PSGL4ip_dec.\nRequire Import GL4ip_ImpL_adm.\nRequire Import GL4ip_inv_ImpR.\nRequire Import Lia.\n\n\nTheorem ImpImpL_inv_L :  forall n s (D0 : derrec GL4ip_rules (fun _ => False) s) A B C D Γ0 Γ1,\n                              (n = derrec_height D0) ->\n                              (s = (Γ0 ++ (A  → B) → D :: Γ1, C)) ->\n                              derrec GL4ip_rules (fun _ => False) (Γ0 ++ A :: B → D :: B → D :: Γ1, C).\nProof.\nassert (DersNilF: dersrec GL4ip_rules (fun _ : (list (MPropF V)) *(MPropF V)  => False) []).\napply dersrec_nil.\n(* Setting up the strong induction on the height. *)\npose (strong_inductionT (fun (x:nat) => forall s (D0 : derrec GL4ip_rules (fun _ => False) s) A B C D Γ0 Γ1,\n                              (x = derrec_height D0) ->\n                              (s = (Γ0 ++ (A  → B) → D :: Γ1, C)) ->\n                              derrec GL4ip_rules (fun _ => False) (Γ0 ++ A :: B → D :: B → D :: Γ1, C))).\napply d. intros n IH. clear d.\n(* Now we do the actual proof-theoretical work. *)\nintros s D0. remember D0 as D0'. destruct D0.\n(* D0 is a leaf *)\n- destruct f.\n(* D0 is ends with an application of rule *)\n- intros A B C D Γ0 Γ1 hei eq. inversion g ; subst.\n  (* IdP *)\n  * inversion H. subst. assert (InT # P (Γ0 ++  (A  → B) → D :: Γ1)).\n    rewrite <- H2. apply InT_or_app. right. apply InT_eq. assert (InT # P (Γ0 ++ A :: B → D :: B → D :: Γ1)).\n    apply InT_app_or in H0. destruct H0. apply InT_or_app. auto. apply InT_or_app. right. inversion i.\n    subst. inversion H1. subst. repeat apply InT_cons. auto.\n    apply InT_split in H1. destruct H1. destruct s. rewrite e. assert (IdPRule [] (x ++ # P :: x0, # P)).\n    apply IdPRule_I. apply IdP in H1.\n    pose (derI (rules:=GL4ip_rules) (prems:=fun _ : (list (MPropF V)) *(MPropF V) => False)\n    (ps:=[]) (x ++ # P :: x0, # P) H1 DersNilF). auto.\n  (* BotL *)\n  * inversion H. subst. assert (InT (Bot V) (Γ0 ++  (A  → B) → D :: Γ1)).\n    rewrite <- H2. apply InT_or_app. right. apply InT_eq. assert (InT (Bot V) (Γ0 ++ A :: B → D :: B → D :: Γ1)).\n    apply InT_app_or in H0. destruct H0. apply InT_or_app. auto. apply InT_or_app. right. inversion i.\n    subst. inversion H1. subst. repeat apply InT_cons. auto. apply InT_split in H1. destruct H1. destruct s. rewrite e.\n    assert (BotLRule [] (x ++ Bot V :: x0, C)). apply BotLRule_I. apply BotL in H1.\n    pose (derI (rules:=GL4ip_rules) (prems:=fun _ : (list (MPropF V)) *(MPropF V) => False)\n    (ps:=[]) (x ++ Bot V :: x0, C) H1 DersNilF). auto.\n   (* AndR *)\n  * inversion H. subst. assert (J30: dersrec_height d = dersrec_height d). reflexivity.\n    pose (@dersrec_derrec2_height (dersrec_height d) _ _ _ _ _ d J30). repeat destruct s. simpl.\n    simpl in IH.\n    assert (J2: derrec_height x < S (dersrec_height d)). lia.\n    assert (J3: derrec_height x = derrec_height x). reflexivity.\n    assert (J4 : (Γ0 ++  (A  → B) → D :: Γ1, A0) = (Γ0 ++  (A  → B) → D :: Γ1, A0)). auto.\n    pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n    assert (J5: derrec_height x0 < S (dersrec_height d)). lia.\n    assert (J6: derrec_height x0 = derrec_height x0). reflexivity.\n    assert (J7 : (Γ0 ++  (A  → B) → D :: Γ1, B0) = (Γ0 ++  (A  → B) → D :: Γ1, B0)). auto.\n    pose (IH _ J5 _ x0 _ _ _ _ _ _ J6 J7).\n    assert (AndRRule [(Γ0 ++ A :: B → D :: B → D :: Γ1, A0); (Γ0 ++ A :: B → D :: B → D :: Γ1, B0)]\n    (Γ0 ++ A :: B → D :: B → D :: Γ1, A0 ∧ B0)). apply AndRRule_I. pose (dlCons d1 DersNilF). pose (dlCons d0 d2).\n    apply AndR in H0.\n    pose (derI (rules:=GL4ip_rules) (prems:=fun _ : (list (MPropF V)) *(MPropF V) => False)\n   (ps:=[(Γ0 ++ A :: B → D :: B → D :: Γ1, A0); (Γ0 ++ A :: B → D :: B → D :: Γ1, B0)])\n    (Γ0 ++ A :: B → D :: B → D :: Γ1, A0 ∧ B0) H0 d3). auto.\n  (* AndL *)\n  * inversion H. subst. apply list_split_form in H2. destruct H2. repeat destruct s ; repeat destruct p ; subst.\n   + inversion e0.\n   + assert (J30: dersrec_height d = dersrec_height d). reflexivity.\n      pose (@dersrec_derrec_height (dersrec_height d) _ _ _ _ d J30). destruct s.\n      assert (J2: derrec_height x < S (dersrec_height d)). lia.\n      assert (J3: derrec_height x = derrec_height x). reflexivity.\n      assert (J4 : (((Γ0 ++ [ (A  → B) → D]) ++ x0) ++ A0 :: B0 :: Γ3, C) = (Γ0 ++  (A  → B) → D :: x0 ++ A0 :: B0 :: Γ3, C)).\n      repeat rewrite <- app_assoc. auto.\n      pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n      assert (AndLRule [((Γ0 ++ A :: B → D :: B → D :: x0) ++ A0 :: B0 :: Γ3, C)]\n       ((Γ0 ++ A :: B → D :: B → D :: x0) ++ A0 ∧ B0 :: Γ3, C)). apply AndLRule_I. repeat rewrite <- app_assoc in H0. simpl in H0.\n       pose (dlCons d0 DersNilF). apply AndL in H0.\n       pose (derI (rules:=GL4ip_rules) (prems:=fun _ : (list (MPropF V)) *(MPropF V) => False)\n       (ps:=[(Γ0 ++ A :: B → D :: B → D :: x0 ++ A0 :: B0 :: Γ3, C)])\n       (Γ0 ++ A :: B → D :: B → D :: x0 ++ A0 ∧ B0 :: Γ3, C) H0 d1). auto.\n  +  repeat destruct s. repeat destruct p ; subst.\n      assert (J30: dersrec_height d = dersrec_height d). reflexivity.\n      pose (@dersrec_derrec_height (dersrec_height d) _ _ _ _ d J30). destruct s.\n      assert (J2: derrec_height x0 < S (dersrec_height d)). lia.\n      assert (J3: derrec_height x0 = derrec_height x0). reflexivity.\n      assert (J4 : (Γ2 ++ A0 :: B0 :: x ++  (A  → B) → D :: Γ1, C) = ((Γ2 ++ A0 :: B0 :: x) ++  (A  → B) → D :: Γ1, C)).\n      repeat rewrite <- app_assoc. auto. pose (IH _ J2 _ x0 _ _ _ _ _ _ J3 J4).\n      pose (dlCons d0 DersNilF).\n      assert (AndLRule [((Γ2 ++ A0 :: B0 :: x) ++ A :: B → D :: B → D :: Γ1, C)]\n       ((Γ2 ++ A0 ∧ B0 :: x) ++ A :: B → D :: B → D :: Γ1, C)). repeat rewrite <- app_assoc. apply AndLRule_I.\n       apply AndL in H0.\n      pose (derI (rules:=GL4ip_rules) (prems:=fun _ : (list (MPropF V)) *(MPropF V) => False)\n      (ps:=[((Γ2 ++ A0 :: B0 :: x) ++ A :: B → D :: B → D :: Γ1, C)])\n      ((Γ2 ++ A0 ∧ B0 :: x) ++ A :: B → D :: B → D :: Γ1, C) H0 d1). auto.\n  (* OrR1 *)\n  * inversion H. subst. assert (J30: dersrec_height d = dersrec_height d). reflexivity.\n    pose (@dersrec_derrec_height (dersrec_height d) _ _ _ _ d J30). repeat destruct s. simpl.\n    assert (J2: derrec_height x < S (dersrec_height d)). lia.\n    assert (J3: derrec_height x = derrec_height x). reflexivity.\n    assert (J4 : (Γ0 ++  (A  → B) → D :: Γ1, A0) = (Γ0 ++  (A  → B) → D :: Γ1, A0)). auto.\n    pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n    assert (OrR1Rule [(Γ0 ++ A :: B → D :: B → D :: Γ1, A0)]\n    (Γ0 ++ A :: B → D :: B → D :: Γ1, Or A0 B0)). apply OrR1Rule_I. pose (dlCons d0 DersNilF).\n    apply OrR1 in H0.\n    pose (derI (rules:=GL4ip_rules) (prems:=fun _ : (list (MPropF V)) *(MPropF V) => False)\n    (ps:=[(Γ0 ++ A :: B → D :: B → D :: Γ1, A0)])\n    (Γ0 ++ A :: B → D :: B → D  :: Γ1, Or A0 B0) H0 d1). auto.\n  (* OrR2 *)\n  * inversion H. subst. assert (J30: dersrec_height d = dersrec_height d). reflexivity.\n    pose (@dersrec_derrec_height (dersrec_height d) _ _ _ _ d J30). repeat destruct s. simpl.\n    assert (J2: derrec_height x < S (dersrec_height d)). lia.\n    assert (J3: derrec_height x = derrec_height x). reflexivity.\n    assert (J4 : (Γ0 ++  (A  → B) → D :: Γ1, B0) = (Γ0 ++  (A  → B) → D :: Γ1, B0)). auto.\n    pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n    assert (OrR2Rule [(Γ0 ++ A :: B → D :: B → D :: Γ1, B0)]\n    (Γ0 ++ A :: B → D :: B → D :: Γ1, Or A0 B0)). apply OrR2Rule_I. pose (dlCons d0 DersNilF).\n    apply OrR2 in H0.\n    pose (derI (rules:=GL4ip_rules) (prems:=fun _ : (list (MPropF V)) *(MPropF V) => False)\n    (ps:=[(Γ0 ++ A :: B → D :: B → D :: Γ1, B0)])\n    (Γ0 ++ A :: B → D :: B → D  :: Γ1, Or A0 B0) H0 d1). auto.\n  (* OrL *)\n  * inversion H. subst. apply list_split_form in H2. destruct H2. repeat destruct s ; repeat destruct p ; subst.\n   + inversion e0.\n   + assert (J30: dersrec_height d = dersrec_height d). reflexivity.\n      pose (@dersrec_derrec2_height (dersrec_height d) _ _ _ _ _ d J30). repeat destruct s. simpl.\n      assert (J2: derrec_height x < S (dersrec_height d)). lia.\n      assert (J3: derrec_height x = derrec_height x). reflexivity.\n      assert (J4 : (((Γ0 ++ [ (A  → B) → D]) ++ x0) ++ A0 :: Γ3, C) = (Γ0 ++  (A  → B) → D :: (x0 ++ A0 :: Γ3), C)). repeat rewrite <- app_assoc. auto.\n      pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n      assert (J5: derrec_height x1 < S (dersrec_height d)). lia.\n      assert (J6: derrec_height x1 = derrec_height x1). reflexivity.\n      assert (J7 : (((Γ0 ++ [ (A  → B) → D]) ++ x0) ++ B0 :: Γ3, C) = (Γ0 ++  (A  → B) → D :: (x0 ++ B0 :: Γ3), C)). repeat rewrite <- app_assoc. auto.\n      pose (IH _ J5 _ x1 _ _ _ _ _ _ J6 J7).\n      assert (OrLRule [((Γ0 ++ A :: B → D :: B → D :: x0) ++ A0 :: Γ3, C);((Γ0 ++ A :: B → D :: B → D :: x0) ++ B0 :: Γ3, C)]\n      ((Γ0 ++ A :: B → D :: B → D :: x0) ++ A0 ∨ B0 :: Γ3, C)). apply OrLRule_I. apply OrL in H0.\n      repeat rewrite <- app_assoc in H0. simpl in H0.\n      pose (dlCons d1 DersNilF). pose (dlCons d0 d2).\n      pose (derI (rules:=GL4ip_rules) (prems:=fun _ : (list (MPropF V)) *(MPropF V) => False)\n      (ps:=[(Γ0 ++ A :: B → D :: B → D :: x0 ++ A0 :: Γ3, C); (Γ0 ++ A :: B → D :: B → D :: x0 ++ B0 :: Γ3, C)])\n      (Γ0 ++ A :: B → D :: B → D :: x0 ++ A0 ∨ B0 :: Γ3, C) H0 d3). auto.\n   + repeat destruct s. repeat destruct p ; subst. assert (J30: dersrec_height d = dersrec_height d). reflexivity.\n      pose (@dersrec_derrec2_height (dersrec_height d) _ _ _ _ _ d J30). repeat destruct s.\n      assert (J2: derrec_height x0 < S (dersrec_height d)). lia.\n      assert (J3: derrec_height x0 = derrec_height x0). reflexivity.\n      assert (J4 :(Γ2 ++ A0 :: x ++  (A  → B) → D :: Γ1, C) = ((Γ2 ++ A0 :: x) ++  (A  → B) → D :: Γ1, C)). repeat rewrite <- app_assoc. auto.\n      pose (IH _ J2 _ x0 _ _ _ _ _ _ J3 J4).\n      assert (J5: derrec_height x1 < S (dersrec_height d)). lia.\n      assert (J6: derrec_height x1 = derrec_height x1). reflexivity.\n      assert (J7 : (Γ2 ++ B0 :: x ++  (A  → B) → D :: Γ1, C) = ((Γ2 ++ B0 :: x) ++  (A  → B) → D :: Γ1, C)). repeat rewrite <- app_assoc. auto.\n      pose (IH _ J5 _ x1 _ _ _ _ _ _ J6 J7).\n      assert (OrLRule [((Γ2 ++ A0 :: x) ++ A :: B → D :: B → D :: Γ1, C);((Γ2 ++ B0 :: x) ++ A :: B → D :: B → D :: Γ1, C)]\n      ((Γ2 ++ A0 ∨ B0 :: x) ++ A :: B → D :: B → D :: Γ1, C)). repeat rewrite <- app_assoc. apply OrLRule_I. apply OrL in H0.\n      pose (dlCons d1 DersNilF). pose (dlCons d0 d2).\n      pose (derI (rules:=GL4ip_rules) (prems:=fun _ : (list (MPropF V)) *(MPropF V) => False)\n      (ps:=[((Γ2 ++ A0 :: x) ++ A :: B → D :: B → D :: Γ1, C); ((Γ2 ++ B0 :: x) ++ A :: B → D :: B → D :: Γ1, C)])\n      ((Γ2 ++ A0 ∨ B0 :: x) ++ A :: B → D :: B → D :: Γ1, C) H0 d3). auto.\n  (* ImpR *)\n  * inversion H. subst. assert (J30: dersrec_height d = dersrec_height d). reflexivity.\n    pose (@dersrec_derrec_height (dersrec_height d) _ _ _ _ d J30). destruct s.\n    assert (J50: derrec_height x = derrec_height x). auto.\n    assert (J51: list_exch_L (Γ2 ++ A0 :: Γ3, B0) (A0 :: Γ0 ++  (A  → B) → D :: Γ1, B0)).\n    assert (Γ2 ++ A0 :: Γ3 = [] ++ [] ++ Γ2 ++ [A0] ++ Γ3). auto. rewrite H0.\n    assert (A0 :: Γ0 ++  (A  → B) → D :: Γ1 = [] ++ [A0] ++ Γ2 ++ [] ++ Γ3). rewrite <- H2. auto. rewrite H1.\n    apply list_exch_LI.\n    pose (GL4ip_hpadm_list_exch_L (derrec_height x) _ x J50 _ J51). destruct s.\n    assert (J2: derrec_height x0 < S (dersrec_height d)). lia.\n    assert (J3: derrec_height x0 = derrec_height x0). reflexivity.\n    assert (J4: (A0 :: Γ0 ++  (A  → B) → D :: Γ1, B0) = ((A0 :: Γ0) ++  (A  → B) → D :: Γ1, B0)). repeat rewrite <- app_assoc. auto.\n    pose (IH _ J2 _ x0 _ _ _ _ _ _ J3 J4).\n    assert (ImpRRule [(([] ++ A0 :: Γ0) ++ A :: B → D :: B → D :: Γ1, B0)] ([] ++ Γ0 ++ A :: B → D :: B → D :: Γ1, A0 → B0)). repeat rewrite <- app_assoc. apply ImpRRule_I.\n    simpl in H0. apply ImpR in H0. pose (dlCons d0 DersNilF).\n    pose (derI (rules:=GL4ip_rules) (prems:=fun _ : (list (MPropF V)) *(MPropF V) => False)\n    (ps:=[((A0 :: Γ0) ++ A :: B → D :: B → D :: Γ1, B0)]) (Γ0 ++ A :: B → D :: B → D :: Γ1, A0 → B0) H0 d1). auto.\n  (* AtomImpL1 *)\n  * inversion H. subst. assert (J30: dersrec_height d = dersrec_height d). reflexivity.\n    pose (@dersrec_derrec_height (dersrec_height d) _ _ _ _ d J30). destruct s.\n    apply list_split_form in H2. destruct H2. repeat destruct s ; repeat destruct p ; subst.\n   + inversion e1.\n   + assert (J2: derrec_height x < S (dersrec_height d)). lia.\n       assert (J3: derrec_height x = derrec_height x). reflexivity.\n       assert (J4: (((Γ0 ++ [ (A  → B) → D]) ++ x1) ++ # P :: Γ3 ++ A0 :: Γ4, C) = (Γ0 ++  (A  → B) → D :: x1 ++ # P :: Γ3 ++ A0 :: Γ4, C)). repeat rewrite <- app_assoc. auto.\n       pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n       assert (AtomImpL1Rule [((Γ0 ++ A :: B → D :: B → D :: x1) ++ # P :: Γ3 ++ A0 :: Γ4, C)]\n       ((Γ0 ++ A :: B → D :: B → D :: x1) ++ # P :: Γ3 ++ # P → A0 :: Γ4, C)). apply AtomImpL1Rule_I.\n       repeat rewrite <- app_assoc in H0. apply AtomImpL1 in H0.\n       pose (dlCons d0 DersNilF).\n       pose (derI (rules:=GL4ip_rules) (prems:=fun _ : (list (MPropF V)) *(MPropF V) => False)\n       (ps:=[(Γ0 ++ A :: B → D :: B → D :: x1 ++ # P :: Γ3 ++ A0 :: Γ4, C)])\n       (Γ0 ++ A :: B → D :: B → D :: x1 ++ # P :: Γ3 ++ # P → A0 :: Γ4, C) H0 d1). auto.\n   + repeat destruct s. repeat destruct p ; subst.\n      apply list_split_form in e1. destruct e1. repeat destruct s ; repeat destruct p ; subst.\n      { inversion e1. }\n      { assert (J2: derrec_height x < S (dersrec_height d)). lia.\n         assert (J3: derrec_height x = derrec_height x). reflexivity.\n         assert (J4: (Γ2 ++ # P :: ((x0 ++ [ (A  → B) → D]) ++ x2) ++ A0 :: Γ4, C) = ((Γ2 ++ # P :: x0) ++  (A  → B) → D :: x2 ++ A0 :: Γ4, C)). repeat rewrite <- app_assoc. auto.\n         pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n         assert (AtomImpL1Rule [((Γ2 ++ # P :: x0) ++ A :: B → D :: B → D :: x2 ++ A0 :: Γ4, C)]\n         ((Γ2 ++ # P :: x0) ++ A :: B → D :: B → D :: x2 ++ # P → A0 :: Γ4, C)).\n         assert ((Γ2 ++ # P :: x0) ++ A :: B → D :: B → D :: x2 ++ A0 :: Γ4 = Γ2 ++ # P :: (x0 ++ A :: B → D :: B → D :: x2) ++ A0 :: Γ4). repeat rewrite <- app_assoc. auto.\n         rewrite H0.\n         assert ((Γ2 ++ # P :: x0) ++ A :: B → D :: B → D :: x2 ++ # P → A0 :: Γ4 = Γ2 ++ # P :: (x0 ++ A :: B → D :: B → D :: x2) ++ # P → A0 :: Γ4). repeat rewrite <- app_assoc. auto.\n         rewrite H1. apply AtomImpL1Rule_I. apply AtomImpL1 in H0. pose (dlCons d0 DersNilF).\n         pose (derI (rules:=GL4ip_rules) (prems:=fun _ : (list (MPropF V)) *(MPropF V) => False)\n         (ps:=[((Γ2 ++ # P :: x0) ++ A :: B → D :: B → D :: x2 ++ A0 :: Γ4, C)])\n         ((Γ2 ++ # P :: x0) ++ A :: B → D :: B → D :: x2 ++ # P → A0 :: Γ4, C) H0 d1). auto. }\n      { repeat destruct s. repeat destruct p ; subst.\n         assert (J2: derrec_height x < S (dersrec_height d)). lia.\n         assert (J3: derrec_height x = derrec_height x). reflexivity.\n         assert (J4: (Γ2 ++ # P :: Γ3 ++ A0 :: x1 ++  (A  → B) → D :: Γ1, C) = ((Γ2 ++ # P :: Γ3 ++ A0 :: x1) ++  (A  → B) → D :: Γ1, C)).\n         repeat rewrite <- app_assoc ; simpl ; repeat rewrite <- app_assoc ; auto.\n         pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n         assert (AtomImpL1Rule [((Γ2 ++ # P :: Γ3 ++ A0 :: x1) ++ A :: B → D :: B → D :: Γ1, C)]\n         ((Γ2 ++ # P :: Γ3 ++ # P → A0 :: x1) ++ A :: B → D :: B → D :: Γ1, C)). repeat rewrite <- app_assoc. simpl. repeat rewrite <- app_assoc.\n         apply AtomImpL1Rule_I. apply AtomImpL1 in H0. pose (dlCons d0 DersNilF).\n         pose (derI (rules:=GL4ip_rules) (prems:=fun _ : (list (MPropF V)) *(MPropF V) => False)\n         (ps:=[((Γ2 ++ # P :: Γ3 ++ A0 :: x1) ++ A :: B → D :: B → D :: Γ1, C)])\n         ((Γ2 ++ # P :: Γ3 ++ # P → A0 :: x1) ++ A :: B → D :: B → D :: Γ1, C) H0 d1). auto. }\n  (* AtomImpL2 *)\n  * inversion H. subst. assert (J30: dersrec_height d = dersrec_height d). reflexivity.\n    pose (@dersrec_derrec_height (dersrec_height d) _ _ _ _ d J30). destruct s.\n    apply list_split_form in H2. destruct H2. repeat destruct s ; repeat destruct p ; subst.\n   + inversion e1.\n   + assert (J2: derrec_height x < S (dersrec_height d)). lia.\n       assert (J3: derrec_height x = derrec_height x). reflexivity.\n       assert (J4: (((Γ0 ++ [ (A  → B) → D]) ++ x1) ++ A0 :: Γ3 ++ # P :: Γ4, C) = (Γ0 ++  (A  → B) → D :: x1 ++ A0 :: Γ3 ++ # P :: Γ4, C)). repeat rewrite <- app_assoc. auto.\n       pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n       assert (AtomImpL2Rule [((Γ0 ++ A :: B → D :: B → D :: x1) ++ A0 :: Γ3 ++ # P :: Γ4, C)]\n       ((Γ0 ++ A :: B → D :: B → D :: x1) ++ # P → A0 :: Γ3 ++ # P :: Γ4, C)). apply AtomImpL2Rule_I.\n       repeat rewrite <- app_assoc in H0. apply AtomImpL2 in H0.\n       pose (dlCons d0 DersNilF).\n       pose (derI (rules:=GL4ip_rules) (prems:=fun _ : (list (MPropF V)) *(MPropF V) => False)\n       (ps:=[(Γ0 ++ A :: B → D :: B → D :: x1 ++ A0 :: Γ3 ++ # P :: Γ4, C)])\n       (Γ0 ++ A :: B → D :: B → D :: x1 ++ # P → A0 :: Γ3 ++ # P :: Γ4, C) H0 d1). auto.\n   + repeat destruct s. repeat destruct p ; subst.\n      apply list_split_form in e1. destruct e1. repeat destruct s ; repeat destruct p ; subst.\n      { inversion e1. }\n      { assert (J2: derrec_height x < S (dersrec_height d)). lia.\n         assert (J3: derrec_height x = derrec_height x). reflexivity.\n         assert (J4: (Γ2 ++ A0 :: ((x0 ++ [ (A  → B) → D]) ++ x2) ++ # P :: Γ4, C) = ((Γ2 ++ A0 :: x0) ++  (A  → B) → D :: x2 ++ # P :: Γ4, C)). repeat rewrite <- app_assoc. auto.\n         pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n         assert (AtomImpL2Rule [((Γ2 ++ A0 :: x0) ++ A :: B → D :: B → D :: x2 ++ # P :: Γ4, C)]\n         ((Γ2 ++ # P → A0 :: x0) ++ A :: B → D :: B → D :: x2 ++ # P :: Γ4, C)).\n         assert ((Γ2 ++ A0 :: x0) ++ A :: B → D :: B → D :: x2 ++ # P :: Γ4 = Γ2 ++ A0 :: (x0 ++ A :: B → D :: B → D :: x2) ++ # P :: Γ4). repeat rewrite <- app_assoc. auto.\n         rewrite H0.\n         assert ((Γ2 ++ # P → A0 :: x0) ++ A :: B → D :: B → D :: x2 ++ # P  :: Γ4 = Γ2 ++ # P → A0 :: (x0 ++ A :: B → D :: B → D :: x2) ++ # P :: Γ4). repeat rewrite <- app_assoc. auto.\n         rewrite H1. apply AtomImpL2Rule_I. apply AtomImpL2 in H0. pose (dlCons d0 DersNilF).\n         pose (derI (rules:=GL4ip_rules) (prems:=fun _ : (list (MPropF V)) *(MPropF V) => False)\n         (ps:=[((Γ2 ++ A0 :: x0) ++ A :: B → D :: B → D :: x2 ++ # P :: Γ4, C)])\n         ((Γ2 ++ # P → A0 :: x0) ++ A :: B → D :: B → D :: x2 ++ # P :: Γ4, C) H0 d1). auto. }\n      { repeat destruct s. repeat destruct p ; subst.\n         assert (J2: derrec_height x < S (dersrec_height d)). lia.\n         assert (J3: derrec_height x = derrec_height x). reflexivity.\n         assert (J4: (Γ2 ++ A0 :: Γ3 ++ # P :: x1 ++  (A  → B) → D :: Γ1, C) = ((Γ2 ++ A0 :: Γ3 ++ # P :: x1) ++  (A  → B) → D :: Γ1, C)).\n         repeat rewrite <- app_assoc ; simpl ; repeat rewrite <- app_assoc ; auto.\n         pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n         assert (AtomImpL2Rule [((Γ2 ++ A0 :: Γ3 ++ # P :: x1) ++ A :: B → D :: B → D :: Γ1, C)]\n         ((Γ2 ++ # P → A0 :: Γ3 ++ # P :: x1) ++ A :: B → D :: B → D :: Γ1, C)). repeat rewrite <- app_assoc. simpl. repeat rewrite <- app_assoc.\n         apply AtomImpL2Rule_I. apply AtomImpL2 in H0. pose (dlCons d0 DersNilF).\n         pose (derI (rules:=GL4ip_rules) (prems:=fun _ : (list (MPropF V)) *(MPropF V) => False)\n         (ps:=[((Γ2 ++ A0 :: Γ3 ++ # P :: x1) ++ A :: B → D :: B → D :: Γ1, C)])\n         ((Γ2 ++ # P → A0 :: Γ3 ++ # P :: x1) ++ A :: B → D :: B → D :: Γ1, C) H0 d1). auto. }\n (* AndImpL *)\n  * inversion H. subst. assert (J30: dersrec_height d = dersrec_height d). reflexivity.\n    pose (@dersrec_derrec_height (dersrec_height d) _ _ _ _ d J30). destruct s.\n    apply list_split_form in H2. destruct H2. repeat destruct s ; repeat destruct p ; subst.\n   + inversion e1.\n   +  assert (J2: derrec_height x < S (dersrec_height d)). lia.\n       assert (J3: derrec_height x = derrec_height x). reflexivity.\n       assert (J4: (((Γ0 ++ [ (A  → B) → D]) ++ x1) ++ A0 → B0 → C0 :: Γ3, C) = (Γ0 ++  (A  → B) → D :: x1 ++ A0 → B0 → C0 :: Γ3, C)). repeat rewrite <- app_assoc. auto.\n       pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n       assert (AndImpLRule [((Γ0 ++ A :: B → D :: B → D :: x1) ++ A0 → B0 → C0 :: Γ3, C)]\n       ((Γ0 ++ A :: B → D :: B → D :: x1) ++ (A0 ∧ B0) → C0 :: Γ3, C)). apply AndImpLRule_I.\n       repeat rewrite <- app_assoc in H0. apply AndImpL in H0.\n       pose (dlCons d0 DersNilF).\n       pose (derI (rules:=GL4ip_rules) (prems:=fun _ : (list (MPropF V)) *(MPropF V) => False)\n       (ps:=[(Γ0 ++ A :: B → D :: B → D :: x1 ++ A0 → B0 → C0 :: Γ3, C)])\n       (Γ0 ++ A :: B → D :: B → D :: x1 ++ (A0 ∧ B0) → C0 :: Γ3, C) H0 d1). auto.\n   +  repeat destruct s. repeat destruct p ; subst.\n       assert (J2: derrec_height x < S (dersrec_height d)). lia.\n       assert (J3: derrec_height x = derrec_height x). reflexivity.\n       assert (J4: (Γ2 ++ A0 → B0 → C0 :: x0 ++  (A  → B) → D :: Γ1, C) = ((Γ2 ++ A0 → B0 → C0 :: x0) ++  (A  → B) → D :: Γ1, C)). repeat rewrite <- app_assoc. auto.\n       pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n       assert (AndImpLRule [((Γ2 ++ A0 → B0 → C0 :: x0) ++ A :: B → D :: B → D :: Γ1, C)]\n       ((Γ2 ++ (A0 ∧ B0) → C0 :: x0) ++ A :: B → D :: B → D :: Γ1, C)). repeat rewrite <- app_assoc. apply AndImpLRule_I.\n       apply AndImpL in H0. pose (dlCons d0 DersNilF).\n       pose (derI (rules:=GL4ip_rules) (prems:=fun _ : (list (MPropF V)) *(MPropF V) => False)\n       (ps:=[((Γ2 ++ A0 → B0 → C0 :: x0) ++ A :: B → D :: B → D :: Γ1, C)])\n       ((Γ2 ++ (A0 ∧ B0) → C0 :: x0) ++ A :: B → D :: B → D :: Γ1, C) H0 d1). auto.\n  (* OrImpL *)\n  * inversion H. subst. assert (J30: dersrec_height d = dersrec_height d). reflexivity. simpl.\n     pose (@dersrec_derrec_height (dersrec_height d) _ _ _ _ d J30). destruct s.\n     apply list_split_form in H2. destruct H2. repeat destruct s ; repeat destruct p ; subst.\n   + inversion e1.\n   +  assert (J2: derrec_height x < S (dersrec_height d)). lia.\n       assert (J3: derrec_height x = derrec_height x). reflexivity.\n       assert (J4: (((Γ0 ++ [ (A  → B) → D]) ++ x1) ++ A0 → C0 :: Γ3 ++ B0 → C0 :: Γ4, C) = (Γ0 ++  (A  → B) → D ::  x1 ++ A0 → C0 :: Γ3 ++ B0 → C0 :: Γ4, C)).\n       repeat rewrite <- app_assoc. auto.\n       pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n       assert (OrImpLRule [((Γ0 ++ A :: B → D :: B → D :: x1) ++ A0 → C0 :: Γ3 ++ B0 → C0 :: Γ4, C)]\n       ((Γ0 ++ A :: B → D :: B → D :: x1) ++ (A0 ∨ B0) → C0 :: Γ3 ++ Γ4, C)). apply OrImpLRule_I.\n       repeat rewrite <- app_assoc in H0. apply OrImpL in H0.\n       pose (dlCons d0 DersNilF).\n       pose (derI (rules:=GL4ip_rules) (prems:=fun _ : (list (MPropF V)) *(MPropF V) => False)\n       (ps:=[(Γ0 ++ A :: B → D :: B → D :: x1 ++ A0 → C0 :: Γ3 ++ B0 → C0 :: Γ4, C)])\n       (Γ0 ++ A :: B → D :: B → D :: x1 ++ (A0 ∨ B0) → C0 :: Γ3 ++ Γ4, C) H0 d1). auto.\n   +  repeat destruct s. repeat destruct p ; subst.\n       assert (J50: derrec_height x = derrec_height x). auto.\n       assert (J51: list_exch_L (Γ2 ++ A0 → C0 :: Γ3 ++ B0 → C0 :: Γ4, C) (Γ2 ++ A0 → C0 :: B0 → C0 :: x0 ++  (A  → B) → D :: Γ1, C)).\n       assert (Γ2 ++ A0 → C0 :: Γ3 ++ B0 → C0 :: Γ4 = (Γ2 ++ [A0 → C0]) ++ [] ++ Γ3 ++ [B0 → C0] ++ Γ4).\n       repeat rewrite <- app_assoc. auto. rewrite H0.\n       assert (Γ2 ++ A0 → C0 :: B0 → C0 :: x0 ++  (A  → B) → D :: Γ1 = (Γ2 ++ [A0 → C0]) ++ [B0 → C0] ++ Γ3 ++ [] ++ Γ4).\n       rewrite <- e1 ; repeat rewrite <- app_assoc ; auto. rewrite H1. apply list_exch_LI.\n       pose (GL4ip_hpadm_list_exch_L (derrec_height x) _ x J50 _ J51). destruct s.\n       assert (J2: derrec_height x1 < S (dersrec_height d)). lia.\n       assert (J3: derrec_height x1 = derrec_height x1). reflexivity.\n       assert (J4: (Γ2 ++ A0 → C0 :: B0 → C0 :: x0 ++  (A  → B) → D :: Γ1, C) = ((Γ2 ++ A0 → C0 :: B0 → C0 :: x0) ++  (A  → B) → D :: Γ1, C)). repeat rewrite <- app_assoc. auto.\n       pose (IH _ J2 _ x1 _ _ _ _ _ _ J3 J4).\n       assert (OrImpLRule [((Γ2 ++ A0 → C0 :: B0 → C0 :: x0) ++ A :: B → D :: B → D :: Γ1, C)]\n       ((Γ2 ++ (A0 ∨ B0) → C0 :: x0) ++ A :: B → D :: B → D :: Γ1, C)).\n       assert ((Γ2 ++ A0 → C0 :: B0 → C0 :: x0) ++ A :: B → D :: B → D :: Γ1 = Γ2 ++ A0 → C0 :: [] ++ B0 → C0 :: x0 ++ A :: B → D :: B → D :: Γ1).\n       repeat rewrite <- app_assoc ; simpl ; repeat rewrite <- app_assoc ; auto. rewrite H0.\n       assert ((Γ2 ++ (A0 ∨ B0) → C0 :: x0) ++ A :: B → D :: B → D :: Γ1 = Γ2 ++ (A0 ∨ B0) → C0 :: [] ++ x0 ++ A :: B → D :: B → D :: Γ1).\n       repeat rewrite <- app_assoc ; simpl ; repeat rewrite <- app_assoc ; auto. rewrite H1.\n       apply OrImpLRule_I.  apply OrImpL in H0. pose (dlCons d0 DersNilF).\n       pose (derI (rules:=GL4ip_rules) (prems:=fun _ : (list (MPropF V)) *(MPropF V) => False)\n       (ps:=[((Γ2 ++ A0 → C0 :: B0 → C0 :: x0) ++ A :: B → D :: B → D :: Γ1, C)])\n       ((Γ2 ++ (A0 ∨ B0) → C0 :: x0) ++ A :: B → D :: B → D :: Γ1, C) H0 d1). auto.\n  (* ImpImpL *)\n * inversion H. subst. assert (J30: dersrec_height d = dersrec_height d). reflexivity.\n    pose (@dersrec_derrec2_height (dersrec_height d) _ _ _ _ _ d J30). repeat destruct s. simpl.\n    apply list_split_form in H2. destruct H2. repeat destruct s ; repeat destruct p ; subst.\n   + inversion e1. subst.\n      assert (J1: ImpRRule [(Γ0 ++ A:: B → D :: Γ1, B)] (Γ0 ++ B → D :: Γ1, A → B)). apply ImpRRule_I.\n      pose (ImpR_inv _ _ x J1).\n      assert (J2: wkn_L (B → D) (Γ0 ++ D :: Γ1, C) (Γ0 ++ B → D :: D :: Γ1, C)). apply wkn_LI.\n      pose (GL4ip_adm_wkn_L x0 J2).\n      assert (J3: wkn_L A (Γ0 ++ B → D :: D :: Γ1, C) ((Γ0 ++ A :: [B → D]) ++ D :: Γ1, C)). repeat rewrite <- app_assoc. apply wkn_LI.\n      pose (GL4ip_adm_wkn_L d1 J3).\n      assert (Γ0 ++ A :: B → D :: Γ1 = (Γ0 ++ A :: [B → D]) ++ Γ1). repeat rewrite <- app_assoc ; simpl ; auto. rewrite H0 in d0.\n      assert (J4: derrec_height d0 = derrec_height d0). auto.\n      assert (J5: ((Γ0 ++ [A; B → D]) ++ Γ1, B) = ((Γ0 ++ [A; B → D]) ++ Γ1, B)). auto.\n      pose (ImpL_adm _ _ _ _ _ _ _ _ J4 J5 d2). repeat rewrite <- app_assoc in d3 ; simpl in d3. auto.\n   +  assert (J2: derrec_height x < S (dersrec_height d)). lia.\n       assert (J3: derrec_height x = derrec_height x). reflexivity.\n       assert (J4: (((Γ0 ++ [ (A  → B) → D]) ++ x2) ++ B0 → C0 :: Γ3, A0 → B0) = (Γ0 ++  (A  → B) → D :: x2 ++ B0 → C0 :: Γ3, A0 → B0)).\n       repeat rewrite <- app_assoc. auto.\n       pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n       assert (J5: derrec_height x0 < S (dersrec_height d)). lia.\n       assert (J6: derrec_height x0 = derrec_height x0). reflexivity.\n       assert (J7: (((Γ0 ++ [ (A  → B) → D]) ++ x2) ++ C0 :: Γ3, C) = (Γ0 ++  (A  → B) → D :: x2 ++ C0 :: Γ3, C)).\n       repeat rewrite <- app_assoc. auto.\n       pose (IH _ J5 _ x0 _ _ _ _ _ _ J6 J7).\n       assert (ImpImpLRule [((Γ0 ++ A :: B → D :: B → D :: x2) ++ B0 → C0 :: Γ3, A0 → B0);((Γ0 ++ A :: B → D :: B → D :: x2) ++ C0 :: Γ3, C)]\n       ((Γ0 ++ A :: B → D :: B → D :: x2) ++ (A0 → B0) → C0 :: Γ3, C)). apply ImpImpLRule_I.\n       repeat rewrite <- app_assoc in H0. apply ImpImpL in H0.\n       pose (dlCons d1 DersNilF). pose (dlCons d0 d2).\n       pose (derI (rules:=GL4ip_rules) (prems:=fun _ : (list (MPropF V)) *(MPropF V) => False)\n       (ps:=[(Γ0 ++ A :: B → D :: B → D :: x2 ++ B0 → C0 :: Γ3, A0 → B0); (Γ0 ++ A :: B → D :: B → D :: x2 ++ C0 :: Γ3, C)])\n       (Γ0 ++ A :: B → D :: B → D :: x2 ++ (A0 → B0) → C0 :: Γ3, C) H0 d3). auto.\n   +  repeat destruct s. repeat destruct p ; subst.\n       assert (J2: derrec_height x < S (dersrec_height d)). lia.\n       assert (J3: derrec_height x = derrec_height x). reflexivity.\n       assert (J4: (Γ2 ++ B0 → C0 :: x1 ++  (A  → B) → D :: Γ1, A0 → B0) = ((Γ2 ++ B0 → C0 :: x1) ++  (A  → B) → D :: Γ1, A0 → B0)). repeat rewrite <- app_assoc. auto.\n       pose (IH _ J2 _ x _ _ _ _ _ _ J3 J4).\n       assert (J5: derrec_height x0 < S (dersrec_height d)). lia.\n       assert (J6: derrec_height x0 = derrec_height x0). reflexivity.\n       assert (J7: (Γ2 ++ C0 :: x1 ++  (A  → B) → D :: Γ1, C) = ((Γ2 ++ C0 :: x1) ++  (A  → B) → D :: Γ1, C)).\n       repeat rewrite <- app_assoc. auto.\n       pose (IH _ J5 _ x0 _ _ _ _ _ _ J6 J7).\n       assert (ImpImpLRule [((Γ2 ++ B0 → C0 :: x1) ++ A :: B → D :: B → D :: Γ1, A0 → B0);((Γ2 ++ C0 :: x1) ++ A :: B → D :: B → D :: Γ1, C)]\n       ((Γ2 ++ (A0 → B0) → C0 :: x1) ++ A :: B → D :: B → D :: Γ1, C)). repeat rewrite <- app_assoc. apply ImpImpLRule_I.\n       apply ImpImpL in H0. pose (dlCons d1 DersNilF). pose (dlCons d0 d2).\n       pose (derI (rules:=GL4ip_rules) (prems:=fun _ : (list (MPropF V)) *(MPropF V) => False)\n       (ps:=[((Γ2 ++ B0 → C0 :: x1) ++ A :: B → D :: B → D :: Γ1, A0 → B0); ((Γ2 ++ C0 :: x1) ++ A :: B → D :: B → D :: Γ1, C)])\n       ((Γ2 ++ (A0 → B0) → C0 :: x1) ++ A :: B → D :: B → D :: Γ1, C) H0 d3). auto.\n  (* BoxImpL *)\n * inversion X. subst. assert (J30: dersrec_height d = dersrec_height d). reflexivity.\n    pose (@dersrec_derrec2_height (dersrec_height d) _ _ _ _ _ d J30). repeat destruct s. simpl.\n    apply univ_gen_ext_splitR in X0. destruct X0. destruct s. repeat destruct p ; subst.\n    apply list_split_form in H. destruct H. repeat destruct s ; repeat destruct p ; subst.\n   + inversion e1.\n   +  apply univ_gen_ext_splitR in u. destruct u. destruct s. repeat destruct p ; subst.\n       apply univ_gen_ext_splitR in u. destruct u. destruct s. repeat destruct p ; subst.\n       inversion u2. subst. exfalso. assert (In ( (A  → B) → D) (((x1 ++  (A  → B) → D :: l) ++ x5) ++ x2)).\n       apply in_or_app ; left ; apply in_or_app ; left ; apply in_or_app ; right ; apply in_eq.\n       apply H1 in H. destruct H. inversion H. subst. inversion X0. subst.\n       assert (J5: derrec_height x0 < S (dersrec_height d)). lia.\n       assert (J6: derrec_height x0 = derrec_height x0). reflexivity.\n       assert (J7: (((Γ0 ++ [ (A  → B) → D]) ++ x4) ++ B0 :: Γ3, C) = (Γ0 ++  (A  → B) → D :: x4 ++ B0 :: Γ3, C)).\n       repeat rewrite <- app_assoc. auto.\n       pose (IH _ J5 _ x0 _ _ _ _ _ _ J6 J7).\n       assert (BoxImpLRule [(XBoxed_list (x1 ++ (top_boxes [A]) ++ x5 ++ x2) ++ [Box A0], A0);((Γ0 ++ A :: B → D :: B → D :: x4) ++ B0 :: Γ3, C)]\n       ((Γ0 ++ A :: B → D :: B → D :: x4) ++ Box A0 → B0 :: Γ3, C)).\n       { destruct (dec_is_boxedT A).\n          - apply BoxImpLRule_I ; auto. destruct i. subst. simpl. repeat rewrite <- app_assoc in H1 ; simpl in H1.\n            intro. intros. apply in_app_or in H. destruct H. apply H1. apply in_or_app ; auto.\n            inversion H. subst. exists x3. auto. apply in_app_or in H0 ; destruct H0. apply H1.\n            apply in_or_app ; right ; apply in_or_app ; auto. apply H1.\n            apply in_or_app ; right ; apply in_or_app ;  auto.\n            assert (top_boxes [A] = [A]). destruct i ; subst ; simpl ; auto.\n            rewrite H. simpl. repeat rewrite <- app_assoc ; simpl. repeat apply univ_gen_ext_combine ; auto.\n            apply univ_gen_ext_cons ; auto. repeat apply univ_gen_ext_extra ; try intro ; try destruct X1 ; try inversion H0 ; auto.\n            apply univ_gen_ext_combine ; auto.\n          - assert (top_boxes [A] = []).\n            destruct A ; auto ; exfalso ; apply f ; exists A ; auto. rewrite H ; auto. simpl.\n            apply BoxImpLRule_I ; simpl  ; repeat rewrite <- app_assoc in H1 ; simpl in H1 ; auto.\n            rewrite <- app_assoc ; simpl.\n            repeat apply univ_gen_ext_combine ; auto. repeat apply univ_gen_ext_extra ; auto.\n            intro. destruct X1. inversion H0. intro. destruct X1. inversion H0. apply univ_gen_ext_combine ; auto. }\n       assert (existsT2 (D2 : derrec GL4ip_rules (fun _ : list (MPropF V) * MPropF V => False) (XBoxed_list (x1 ++ top_boxes [A] ++ x5 ++ x2) ++ [Box A0], A0)),\n       derrec_height D2 <= derrec_height x).\n       { destruct (dec_is_boxedT A).\n          - assert (top_boxes [A] = [A]). destruct i. subst ; auto. rewrite H. repeat rewrite XBox_app_distrib. repeat rewrite <- app_assoc.\n            assert (J1: derrec_height x = derrec_height x). auto.\n            pose (@GL4ip_list_wkn_L _ _ _ _ _ J1 (XBoxed_list [A])). destruct s.\n            assert (J2: derrec_height x3 = derrec_height x3). auto.\n            assert (J3: list_exch_L (XBoxed_list (((x1 ++ []) ++ x5) ++ x2) ++ XBoxed_list [A] ++ [Box A0], A0) (XBoxed_list x1 ++ XBoxed_list [A] ++ XBoxed_list x5 ++ XBoxed_list x2 ++ [Box A0], A0)).\n            repeat rewrite XBox_app_distrib. repeat rewrite <- app_assoc.\n            assert (XBoxed_list x1 ++ XBoxed_list [] ++ XBoxed_list x5 ++ XBoxed_list x2 ++ XBoxed_list [A] ++ [Box A0] = XBoxed_list x1 ++ [] ++ (XBoxed_list x5 ++ XBoxed_list x2) ++ XBoxed_list [A] ++ [Box A0]).\n            repeat rewrite <- app_assoc ; simpl ; auto. rewrite H0.\n            assert (XBoxed_list x1 ++ XBoxed_list [A] ++ XBoxed_list x5 ++ XBoxed_list x2 ++ [Box A0] = XBoxed_list x1 ++ XBoxed_list [A] ++ (XBoxed_list x5 ++ XBoxed_list x2) ++ [] ++ [Box A0]).\n            repeat rewrite <- app_assoc ; simpl ; auto. rewrite H3. apply list_exch_LI.\n            pose (GL4ip_hpadm_list_exch_L _ _ _ J2 _ J3). destruct s. exists x6. lia.\n          - assert (top_boxes [A] = []).\n            destruct A ; auto ; exfalso ; apply f ; exists A ; auto. rewrite H ; auto. simpl.\n            assert (x1 ++ x5 ++ x2 = ((x1 ++ []) ++ x5) ++ x2). repeat rewrite <- app_assoc ; simpl ; auto. rewrite H0.\n            exists x. lia. }\n       destruct X2. apply BoxImpL in X1.\n       pose (dlCons d0 DersNilF). pose (dlCons x3 d1). repeat rewrite <- app_assoc in X1.\n       pose (derI (rules:=GL4ip_rules) (prems:=fun _ : (list (MPropF V)) *(MPropF V) => False)\n       (ps:=[(XBoxed_list (x1 ++ top_boxes [A] ++ x5 ++ x2) ++ [Box A0], A0); (Γ0 ++ A :: B → D :: B → D :: x4 ++ B0 :: Γ3, C)])\n       (Γ0 ++ A :: B → D :: B → D :: x4 ++ Box A0 → B0 :: Γ3, C) X1 d2). auto.\n   +  repeat destruct s. repeat destruct p ; subst.\n       apply univ_gen_ext_splitR in u0. destruct u0. destruct s. repeat destruct p ; subst.\n       inversion u1. subst. exfalso. assert (In ( (A  → B) → D) (x1 ++ x4 ++  (A  → B) → D :: l)).\n       apply in_or_app ; right ; apply in_or_app ; right ; apply in_eq.\n       apply H1 in H. destruct H. inversion H. subst.\n       assert (J5: derrec_height x0 < S (dersrec_height d)). lia.\n       assert (J6: derrec_height x0 = derrec_height x0). reflexivity.\n       assert (J7: (Γ2 ++ B0 :: x3 ++  (A  → B) → D :: Γ1, C) = ((Γ2 ++ B0 :: x3) ++  (A  → B) → D :: Γ1, C)).\n       repeat rewrite <- app_assoc. auto.\n       pose (IH _ J5 _ x0 _ _ _ _ _ _ J6 J7).\n       assert (BoxImpLRule [(XBoxed_list (x1 ++ x4 ++ (top_boxes [A]) ++ x5) ++ [Box A0], A0);((Γ2 ++ B0 :: x3) ++ A :: B → D :: B → D :: Γ1, C)]\n       ((Γ2 ++ Box A0 → B0 :: x3) ++ A :: B → D :: B → D :: Γ1, C)).\n       { destruct (dec_is_boxedT A).\n          - repeat rewrite <- app_assoc. simpl. apply BoxImpLRule_I ; auto. destruct i. subst. simpl.\n            intro. intros. apply in_app_or in H. destruct H. apply H1. apply in_or_app ; auto.\n            apply in_app_or in H ; destruct H. apply H1.\n            apply in_or_app ; right ; apply in_or_app ; auto. inversion H. subst. exists x2. auto. apply H1.\n            apply in_or_app ; right ; apply in_or_app ;  auto.\n            assert (match A with\n                     | Box A1 => [Box A1]\n                     | _ => []\n                     end = [A]). destruct i ; subst ; simpl ; auto.\n            rewrite H. simpl. repeat rewrite <- app_assoc ; simpl. repeat apply univ_gen_ext_combine ; auto.\n            apply univ_gen_ext_cons ; auto. repeat apply univ_gen_ext_extra ; try intro ; try destruct X1 ; try inversion H0 ; auto.\n          - assert (top_boxes [A] = []).\n            destruct A ; auto ; exfalso ; apply f ; exists A ; auto. rewrite H ; auto. simpl. repeat rewrite <- app_assoc ; simpl.\n            apply BoxImpLRule_I ; simpl  ; repeat rewrite <- app_assoc in H1 ; simpl in H1 ; auto.\n            repeat apply univ_gen_ext_combine ; auto. repeat apply univ_gen_ext_extra ; auto.\n            intro. destruct X1. inversion H0. intro. destruct X1. inversion H0. }\n       assert (existsT2 (D2 : derrec GL4ip_rules (fun _ : list (MPropF V) * MPropF V => False) (XBoxed_list (x1 ++ x4 ++ top_boxes [A] ++ x5) ++ [Box A0], A0)),\n       derrec_height D2 <= derrec_height x).\n       { destruct (dec_is_boxedT A).\n          - assert (top_boxes [A] = [A]). destruct i. subst ; auto. rewrite H. repeat rewrite XBox_app_distrib. repeat rewrite <- app_assoc.\n            assert (J1: derrec_height x = derrec_height x). auto.\n            pose (@GL4ip_list_wkn_L _ _ _ _ _ J1 (XBoxed_list [A])). destruct s.\n            assert (J2: derrec_height x2 = derrec_height x2). auto.\n            assert (J3: list_exch_L (XBoxed_list (x1 ++ x4 ++ x5) ++ XBoxed_list [A] ++ [Box A0], A0) (XBoxed_list x1 ++ XBoxed_list x4 ++ XBoxed_list [A] ++ XBoxed_list x5 ++ [Box A0], A0)).\n            repeat rewrite XBox_app_distrib. repeat rewrite <- app_assoc.\n            assert (XBoxed_list x1 ++ XBoxed_list x4 ++ XBoxed_list x5 ++ XBoxed_list [A] ++ [Box A0] = (XBoxed_list x1 ++ XBoxed_list x4) ++ [] ++ XBoxed_list x5 ++ XBoxed_list [A] ++ [Box A0]).\n            repeat rewrite <- app_assoc ; simpl ; auto. rewrite H0.\n            assert (XBoxed_list x1 ++ XBoxed_list x4 ++ XBoxed_list [A] ++ XBoxed_list x5 ++ [Box A0] = (XBoxed_list x1 ++ XBoxed_list x4) ++ XBoxed_list [A] ++ XBoxed_list x5 ++ [] ++ [Box A0]).\n            repeat rewrite <- app_assoc ; simpl ; auto. rewrite H3. apply list_exch_LI.\n            pose (GL4ip_hpadm_list_exch_L _ _ _ J2 _ J3). destruct s. exists x6. lia.\n          - assert (top_boxes [A] = []).\n            destruct A ; auto ; exfalso ; apply f ; exists A ; auto. rewrite H ; auto. simpl. exists x. lia. }\n       destruct X2. apply BoxImpL in X1.\n       pose (dlCons d0 DersNilF). pose (dlCons x2 d1). repeat rewrite <- app_assoc in X1. repeat rewrite <- app_assoc. simpl. simpl in X1.\n       assert (match A with\n                                  | Box A => [Box A]\n                                  | _ => []\n                                  end = top_boxes [A]). simpl. auto. rewrite H in X1. repeat rewrite <- app_assoc in d2.\n       pose (derI (rules:=GL4ip_rules) (prems:=fun _ : (list (MPropF V)) *(MPropF V) => False)\n       (ps:=[(XBoxed_list (x1 ++ x4 ++ top_boxes [A] ++ x5) ++ [Box A0], A0); (Γ2 ++ B0 :: x3 ++ A :: B → D :: B → D :: Γ1, C)])\n       (Γ2 ++ Box A0 → B0 :: x3 ++ A :: B → D :: B → D :: Γ1, C) X1 d2). auto.\n  (* GLR *)\n  * inversion X. subst. simpl. apply univ_gen_ext_splitR in X0. destruct X0. destruct s. repeat destruct p ; subst.\n    inversion u0. subst. exfalso. assert (In ( (A  → B) → D) (x ++  (A  → B) → D :: l)). apply in_or_app ; right ; apply in_eq.\n    apply H1 in H. destruct H. inversion H. subst.\n    assert (GLRRule [(XBoxed_list (x ++ x0) ++ [Box A0], A0)] (Γ0 ++ Γ1, Box A0)). apply GLRRule_I ; auto.\n    apply univ_gen_ext_combine ; auto. apply GLR in X1.\n    pose (derI (rules:=GL4ip_rules) (prems:=fun _ : (list (MPropF V)) *(MPropF V) => False)\n    (ps:=[(XBoxed_list (x ++ x0) ++ [Box A0], A0)]) (Γ0 ++ Γ1, Box A0) X1 d).\n    assert (J1: wkn_L (B → D) (Γ0 ++ Γ1, Box A0) (Γ0 ++ B → D :: Γ1, Box A0)). apply wkn_LI.\n    pose (@GL4ip_adm_wkn_L _ d0 _ _ J1).\n    assert (J2: wkn_L (B → D) (Γ0 ++ B → D :: Γ1, Box A0) (Γ0 ++ B → D :: B → D :: Γ1, Box A0)). apply wkn_LI.\n    pose (@GL4ip_adm_wkn_L _ d1 _ _ J2).\n    assert (J3: wkn_L A (Γ0 ++ B → D :: B → D :: Γ1, Box A0) (Γ0 ++ A :: B → D :: B → D :: Γ1, Box A0)). apply wkn_LI.\n    pose (@GL4ip_adm_wkn_L _ d2 _ _ J3). auto.\nQed.\n\n\n\n\n\n\n\n", "meta": {"author": "ianshil", "repo": "CE_GL4ip", "sha": "199cde58e85cafe738a7085192a185aaeb164833", "save_path": "github-repos/coq/ianshil-CE_GL4ip", "path": "github-repos/coq/ianshil-CE_GL4ip/CE_GL4ip-199cde58e85cafe738a7085192a185aaeb164833/GL4ip/GL4ip_inv_ImpImpL_L.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.27728270024771284}}
{"text": "From Parsec Require Export\n     Parser.\nFrom ExtLib Require Export\n     Extras.\nFrom JSON Require Export\n     Jpath.\nFrom Coq Require Export\n     ssr.ssrfun.\nFrom AsyncTest Require Export\n     Trace\n     Common.\nExport\n  FunNotation.\nOpen Scope parser_scope.\n\nInductive jexp :=\n  Jexp__Const  : IR                               -> jexp\n| Jexp__Array  : list jexp                        -> jexp\n| Jexp__Object : list (string * jexp)             -> jexp\n| Jexp__Ref    : labelT -> jpath -> (IR -> IR)       -> jexp.\n\nDefinition nth_weak (n : nat) (j : IR)\n  : option IR :=\n  if j is JSON__Array l then\n    get_nth n j <|> last (map Some l) None\n  else None.\n\nFixpoint jget_weak (p : jpath) (j : IR) : option IR :=\n  match p with\n  | Jpath__This        => Some j\n  | Jpath__Array  p' n => jget_weak p' j >>= nth_weak n\n  | Jpath__Object p' s => jget_weak p' j >>= get_json' s\n  end.\n\nExample tget_strong (l : labelT) (p : jpath) (t : traceT) : IR :=\n  odflt (JSON__Object []) $ packet__payload <$> get l t >>= jget p.\n\nDefinition tget_weak' (jget : jpath -> IR -> option IR)\n           (l : labelT) (p : jpath) (t : traceT) : IR :=\n  odflt (last (pick_some $ map (jget p ∘ packet__payload ∘ snd) t) $ JSON__Object []) $\n        packet__payload <$> get l t >>= jget p.\n\nDefinition tget_weak : labelT -> jpath -> traceT -> IR := tget_weak' jget_weak.\n\nFixpoint jexp_to_IR' (tget : labelT -> jpath -> traceT -> IR)\n         (t : traceT) (e : jexp) : IR :=\n  match e with\n  | Jexp__Const  j => j\n  | Jexp__Array  l => JSON__Array  $ map     (jexp_to_IR' tget t) l\n  | Jexp__Object m => JSON__Object $ map_snd (jexp_to_IR' tget t) m\n  | Jexp__Ref  l p f => f $ tget l p t\n  end.\n\nExample jexp_to_IR_strong : traceT -> jexp -> IR := jexp_to_IR' tget_strong.\n\nDefinition jexp_to_IR_weak : traceT -> jexp -> IR := jexp_to_IR' tget_weak.\n\nDefinition findpath' (p : jpath) : traceT -> list labelT :=\n  fmap fst ∘ filter (fun lj => if jget_weak p (packet__payload $ snd lj) is Some _\n                          then true else false).\n\nDefinition findpath (p : jpath) (f : IR -> IR) (t : traceT) : list jexp :=\n  l <- findpath' p t;; [Jexp__Ref l p f].\n\nFixpoint IR_to_jexp (j : IR) : jexp :=\n  match j with\n  | JSON__Array l  => Jexp__Array  (map     IR_to_jexp l)\n  | JSON__Object l => Jexp__Object (map_snd IR_to_jexp l)\n  | _            => Jexp__Const   j\n  end.\n\nFixpoint normalise (e : jexp) : jexp :=\n  match e with\n  | Jexp__Const  j => IR_to_jexp  j\n  | Jexp__Array  l => Jexp__Array  (map     normalise l)\n  | Jexp__Object l => Jexp__Object (map_snd normalise l)\n  | _            => e\n  end.\n", "meta": {"author": "liyishuai", "repo": "coq-async-test", "sha": "adb8f18433482f951419e0c7f66b78270fdcb22d", "save_path": "github-repos/coq/liyishuai-coq-async-test", "path": "github-repos/coq/liyishuai-coq-async-test/coq-async-test-adb8f18433482f951419e0c7f66b78270fdcb22d/theories/Jexp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2772352398423698}}
{"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\nRequire Import ComhCoq.Extras.LibTactics.\n\nRequire Import ComhCoq.LanguageFoundations.\nRequire Import ComhCoq.ComhBasics.\nRequire Import ComhCoq.GenTacs.\nRequire Import ComhCoq.StandardResults.\n\n(***************** Timed lists *****************)\n\n(** A timed element is a vector of base values, along with a timestamp.*)\nRecord TimedEl : Type := mkTimedEl\n{\n  msg : list BaseType;\n  stamp : Time\n}.\nNotation \"<( m , t )>\" := (mkTimedEl m t) (at level 40).\n\n(** Equality is decidable on timed elements.*)\nLemma eqDecTimedEl : eqDec TimedEl. unfold eqDec.\n  destruct x1, x2. addHyp (eqDecTime stamp0 stamp1).\n  invertClear H. addHyp (list_eq_dec eqDecBase msg0 msg1).\n  invertClear H. left. subst. reflexivity. right.\n  unfold not. intros. apply H1. inversion H. reflexivity.\n  right. unfold not. intros. apply H0. inversion H. reflexivity.\n  Qed.\n\n(** A timed list is a list of timed elements.*)\nDefinition TimedList : Type := list TimedEl.\n\n(**An action is either a delay, an input or an output.*)\nInductive ActTimedList :=\n  | atlDel :> Delay -> ActTimedList\n  | atlIn : list BaseType -> ActTimedList\n  | atlOut : list BaseType -> ActTimedList.\n\nNotation \"v ?? \" := (atlIn v) (at level 30).\nNotation \"v !! \" := (atlOut v) (at level 30).\n\nReserved Notation \"l -tl- a -tl> l'\" (at level 75). \n\n(** The operational semantics for timed lists. Note that the law \"buff\" will have\nto be defined separately for each of the sub-type lists individually,\nbecause it is parametrised on a time T.*)\nInductive stepTimedList : TimedList -> ActTimedList -> TimedList -> Prop :=\n  (** If the head of the list has timed out (zero time) then it can be output.*)\n  | stepTlFwdHd : forall (v : list BaseType) (l : TimedList),\n    <(v, zeroTime)> :: l -tl- v!! -tl> l \n  (** If the tail can evolve by outputting an element, then the whole list can evolve as\n  such.*)\n  | stepTlFwd : forall (l l' : TimedList) (v1 : list BaseType) (e : TimedEl),\n    l -tl- v1!! -tl> l' -> e :: l -tl- v1!! -tl> e :: l'\n  (** The empty list can delay by any amount and stay as the empty list.*)\n  | stepTlDelEmp : forall d : Delay, [] -tl- d -tl> [] \n  (** If the tail can delay by d, and the timestamp on the head is t + d, then the\n  whole list evolves by the tail delaying and the head element timestap reducing to t.\n  Note that this differs slightly from the formulation on paper, which asserts that the\n  timestamp of the head element is t >= d, and then the resulting timestamp is t - d.\n  The reason for this alternative formulation is to avoid subtraction of delays/times.*)\n  | stepTlDel : forall (l l' : TimedList) (d : Delay) (v : list BaseType) (t t' : Time),\n    l -tl- d -tl> l' -> t = t' +dt+ d -> <(v, t)> :: l -tl- d -tl> \n    <(v, t')> :: l'\n  where \"l -tl- a -tl> l'\" := (stepTimedList l a l').\n\n(** The delay action preserves the size of a timed list.*)\nLemma delPresSizeTL : forall (l l' : TimedList) (d : Delay),\n  l -tl- d -tl> l' -> length l = length l'. intros.\n  remember (atlDel d) as a. induction H. inversion Heqa.\n  apply IHstepTimedList in Heqa. simpl. rewrite Heqa. reflexivity.\n  reflexivity. apply IHstepTimedList in Heqa. simpl.\n  rewrite Heqa. reflexivity. Qed.\n\n(** If [] delays to l', then l' = []*)\nLemma empLeftDelTL : forall (l' : TimedList) (d : Delay),\n  [] -tl- d -tl> l' -> l' = []. intros. apply delPresSizeTL in H.\n  destruct l'. reflexivity. inversion H. Qed.\n\n(** If l delays to [], then l = []*)\nLemma empRightDelTL : forall (l : TimedList) (d : Delay),\n  l -tl- d -tl> [] -> l = []. intros. apply delPresSizeTL in H.\n  destruct l. reflexivity. inversion H. Qed.\n\n(** If a timed list l can delay by d to l' which in turn can delay by d' to l'',\nthen l can delay by d+d' to l''.*)\nLemma delAddTL : forall (l l' l'' : TimedList) (d d' : Delay),\n  l -tl- d -tl> l' -> l' -tl- d' -tl> l'' ->\n  l -tl- d +d+ d' -tl> l''. induction l; intros.\n  erewrite empLeftDelTL. constructor. assert (l' = []).\n  eapply empLeftDelTL. apply H. rewrite H1 in H0. apply H0.\n  destruct a. destruct l'. apply empRightDelTL in H. inversion H.\n  rename t into a. destruct a. inversion H. destruct l''.\n  apply empRightDelTL in H0. inversion H0.\n  destruct t0. inversion H0. rewrite H18 in H9.\n  rewrite delTimeAddAssoc in H9. rewrite timeDelAddSwitch in H9.\n  rewrite addDelayComm in H9. rewrite H9. constructor.\n  eapply IHl. apply H3. assumption. reflexivity. Qed.\n\nLemma timedList_timeout_enabled v l :\n  <( v, zeroTime )> _: l -> exists l', l -tl- v !! -tl> l'.\n  introz U. induction l; inversion U. subst.\n  exists l. constructor. apply IHl in H.\n  ex_flat. eexists. eapply stepTlFwd. eassumption. Qed.\n\nLemma timedList_del_le l l' d v t q :\n   l -tl- atlDel d -tl> l' -> <( v, t )> _: l ->\n  <( v, minusTime t d q )> _: l'. Admitted.\n\n\n(***************** Input, Output & Notification lists *****************)\n(*These will be syntactically the same as timed lists, with the exception of\na wrapper. Each will then diverege in their extension of the semantics of timed lists:\nlifting the timed list relation and then adding some new laws specific to the type of list\n(input, output or notification).*)\n\nReserved Notation \"l -il- a -il> l'\" (at level 75). \nReserved Notation \"l -ol- a -ol> l'\" (at level 75). \nReserved Notation \"l -nl- a -nl> l'\" (at level 75). \n\n(** Syntactially, an input list is essentially a timed list.*)\nRecord InputList : Type := mkInputList {inList : TimedList}.\n\n(** Syntactially, an input list is essentially a timed list.*)\nRecord OutputList : Type := mkOutputList {outList : TimedList}.\n\n(** Syntactially, an input list is essentially a timed list.*)\nRecord NotifList : Type := mkNotifList {notifList : TimedList}.\n\n(** Semantics for the input list.*)\nInductive stepInputList : InputList -> ActTimedList -> InputList -> Prop :=\n  (** Buffer a message and stamp it with zero time.*)\n  | stepIlBuff : forall (l : TimedList) (v : list BaseType),\n    mkInputList l -il- v ?? -il> mkInputList (<(v, zeroTime)> :: l)\n  (** Delay causes all the messages in the list to be lost. In other words,\n  any list can delay and become the empty list.*)\n  | stepIlDel : forall (l : InputList) (d : Delay),\n    l -il- d -il> mkInputList []\n  (** Lift the timed list semantics to these specialised semantics.*)\n  | stepIlLift : forall (l l' : TimedList) (a : ActTimedList),\n    l -tl- a -tl> l' -> mkInputList l -il- a -il> mkInputList l'\n  where \"l -il- a -il> l'\" := (stepInputList l a l').\n\nOpen Scope nat_scope.\n\n(** The size of a list is non-increasing for an input list.*)\nLemma delNonIncSizeIL : forall (l l' : InputList) (d : Delay),\n  l -il- d -il> l' -> length (inList l') <= length (inList l).\n  intros. inversion H. simpl. apply le_0_n.\n  apply delPresSizeTL in H0. simpl. rewrite H0.\n  constructor. Qed.\n\n(** If an input list l can delay by d to l' which in turn can delay by d' to l'',\nthen l can delay by d+d' to l''.*)\nLemma delAddInput : forall (l l' l'' : InputList) (d d' : Delay),\n  l -il- d -il> l' -> l' -il- d' -il> l'' ->\n  l -il- d +d+ d' -il> l''. intros. destruct l''.\n  destruct inList0. constructor. rename t into a.\n  destruct l'. destruct inList1. apply delNonIncSizeIL in H0.\n  inversion H0. rename t into b. destruct l. destruct inList2.\n  apply delNonIncSizeIL in H. inversion H. rename t into c.\n  inversion H. inversion H0.\n  constructor. eapply delAddTL. apply H4. assumption. Qed.\n  \n(** An input list l is action enabled for the action a iff\nthere is some derivative list l' such that l transitions to l' via a.*)\nDefinition actEnabledInList (l : InputList) (a : ActTimedList) : Prop :=\n  exists l', l -il- a -il> l'.\n\n(** An input list can always input a message.*)\nLemma inListInEnabled : forall (l : InputList) (v : list BaseType),\n  actEnabledInList l (v??). intros. destruct l as [l].\n  exists (mkInputList (<(v, zeroTime)> :: l)). constructor. Qed.\n\n(**Semantics for the output list.*)\nInductive stepOutputList : OutputList -> ActTimedList -> OutputList -> Prop :=\n  (** Buffer a message and stamp it with a timestamp of msgLatency.*)\n  | stepOlBuff : forall (l : TimedList) (v : list BaseType),\n    mkOutputList l -ol- v?? -ol> mkOutputList (<(v, msgLatency)> :: l)\n  (** Lift the timed list semantics to these specialised semantics.*)\n  | stepOlLift : forall (l l' : TimedList) (a : ActTimedList),\n    l -tl- a -tl> l' -> mkOutputList l -ol- a -ol> mkOutputList l'\n  where \"l -ol- a -ol> l'\" := (stepOutputList l a l').\n\nLemma delAddOutput : forall (l l' l'' : OutputList) (d d' : Delay),\n  l -ol- d -ol> l' -> l' -ol- d' -ol> l'' ->\n  l -ol- d +d+ d' -ol> l''. intros. inversion H.\n  rewrite <- H4 in H0. inversion H0. constructor.\n  eapply delAddTL. apply H1. assumption. Qed.\n\n(**Semantics for the notification list.*)\nInductive stepNotifList : NotifList -> ActTimedList -> NotifList -> Prop :=\n  (** Buffer a message and stamp it with a timestamp of adaptNotif.*)\n  | stepNlBuff : forall (l : TimedList) (v : list BaseType),\n    mkNotifList l -nl- v?? -nl> mkNotifList (<(v, adaptNotif)> :: l)\n  (** If the tail can delay to some l', and the head has timed out, then the whole\n  list can delay to l', essentially dropping the head.*)\n  | stepNlDrop : forall (l : TimedList) (l' : NotifList)\n    (d : Delay) (v : list BaseType), mkNotifList l -nl- d -nl> l' ->\n    mkNotifList (<(v, zeroTime)> :: l) -nl- d -nl> l'\n  | stepNlDelAdd : forall (l l' l'' : NotifList) (d d' : Delay),\n    l -nl- d -nl> l' -> l' -nl- d' -nl> l'' ->\n    l -nl- (d +d+ d') -nl> l''\n  (** Lift the timed list semantics to these specialised semantics.*)\n  | stepNlLift : forall (l l' : TimedList) (a : ActTimedList),\n    l -tl- a -tl> l' -> mkNotifList l -nl- a -nl> mkNotifList l'\n  where \"l -nl- a -nl> l'\" := (stepNotifList l a l').\n\n  Open Scope R_scope.\n\nLemma notifList_del_le ln ln' d v t q :\n  ln -nl- atlDel d -nl> ln' -> <( v, t )> _: notifList ln ->\n  <( v, minusTime t d q )> _: notifList ln'. introz U.\n  (*Proof: Induction on the proof of the delay of the notifList.*)\n  remember (atlDel d). generalize dependent d.\n  generalize dependent t. induction U; intros t U0 d2 q EQ; subst.\n  (*Eliminate the input case, which is clearly contradictory to the delay.*)\n  inversion EQ.\n  (*Next case follows by induction and the fact that t is positive.*)\n  apply IHU. inversion U0. inversion H.\n  clear IHU. rewrite <- H2 in q. false. eapply Rle_not_lt.\n  apply q. delPos. assumption. assumption.\n  (*The additive case also follows by induction. We basically thread\n  one inductive case to the other.*)\n  inversion EQ. generalize dependent q. rewrite <- H0.\n  intro q. clear EQ H0.\n  assert (atlDel d = atlDel d) as EQD; [ reflexivity |].\n  assert (atlDel d' = atlDel d') as EQD'; [ reflexivity |].\n  assert (d <= t) as DLE. eapply Rle_trans; [ | apply q].\n  simpl. Rplus_le_tac. apply Rlt_le. delPos.\n  lets IH1 : IHU1 U0 DLE EQD.\n  assert (d' <= minusTime t d DLE) as DLE'. simpl.\n  apply Rplus_le_swap_lr. rewrite Rplus_comm. apply q.\n  lets IH2 : IHU2 IH1 DLE' EQD'. my_applys_eq IH2.\n  f_equal. apply timeEqR. simpl. ring.\n  (*Finally we have the lifting case, in which case we lift a similar\n  (analogous) result for timed lists.*)\n  eapply timedList_del_le; eassumption. Qed.\n\nLemma timeSplit_inputList l l'' (d d' d'' : Delay) :\n  l -il- d'' -il> l'' -> d'' = d +d+ d' ->\n  exists l', l -il- d -il> l' /\\ l' -il- d' -il> l''.\n  Admitted. (*#timeSplit-timedList*)\n\nLemma timeSplit_outputList l l'' (d d' d''  : Delay) :\n  l -ol- d'' -ol> l'' -> d'' = d +d+ d' ->\n  exists l', l -ol- d -ol> l' /\\ l' -ol- d' -ol> l''.\n  Admitted. (*#timeSplit-timedList*)\n\nLemma timeSplit_notifList l l'' (d d' d''  : Delay) :\n  l -nl- d'' -nl> l'' -> d'' = d +d+ d' ->\n  exists l', l -nl- d -nl> l' /\\ l' -nl- d' -nl> l''.\n  Admitted. (*#timeSplit-timedList*)\n\n(***************** Interface Syntax & Semantics *****************)\n\nRecord Interface : Type := mkInterface\n{\n  li : InputList;\n  lo : OutputList;\n  ln : NotifList\n}.\n\n(** Equality is decidable on interfaces.*)\nLemma eqDecInterface : eqDec Interface.\n  unfold eqDec. destruct x1, x2.\n  destruct li0, lo0, ln0, li1, lo1, ln1.\n  addHyp (list_eq_dec eqDecTimedEl inList0 inList1).\n  addHyp (list_eq_dec eqDecTimedEl outList0 outList1).\n  addHyp (list_eq_dec eqDecTimedEl notifList0 notifList1).\n  invertClear H. invertClear H0. invertClear H1. left.\n  subst. reflexivity. right. unfold not. intros.\n  apply H0. invertClear H1. reflexivity. right. unfold not.\n  intros. apply H. invertClear H0. reflexivity. right.\n  unfold not. intros. apply H2. invertClear H. reflexivity.\n  Qed.\n\n(** Actions for the interface semantics. We have delay, input of a list of base values\non a channel, output of the same, and finally output of a list of base values on a\nchannel augmented with coverage information.*)\nInductive ActInter :=\n  | aiDel :> Delay -> ActInter \n  | aiIn : Channel -> list BaseType -> ActInter\n  | aiOut : Channel -> list BaseType -> ActInter\n  (** The final parameter is the coverage.*)\n  | aiOutCov : Channel -> list BaseType -> Distance -> ActInter.\n\nNotation \"c !I!\" := (aiOut c []) (at level 30).\nNotation \"c {? v\" := (aiIn c v) (at level 30).\nNotation \"c {! v\" := (aiOut c v) (at level 30).\nNotation \"c _! v !_ r\" := (aiOutCov c v r) (at level 30).\n\nReserved Notation \"i -i- a -i> i'\" (at level 75).\n\n(** The semantics for the interface.*)\nInductive stepInter : Interface -> ActInter -> Interface -> Prop :=\n  | stepIntDel : forall (l1 l1': InputList) (l2 l2': OutputList)\n    (l3 l3' : NotifList) (d : Delay), l1 -il- d -il> l1' ->\n    l2 -ol- d -ol> l2' -> l3 -nl- d -nl> l3' ->\n    (mkInterface l1 l2 l3) -i- d -i> (mkInterface l1' l2' l3')\n  | stepIntBuffIn : forall (l1 l1': InputList) (l2 : OutputList)\n    (l3 : NotifList) (v : list BaseType), l1 -il- v?? -il> l1' ->\n    (mkInterface l1 l2 l3) -i- chanIOEnv {? v -i> (mkInterface l1' l2 l3)\n  | stepIntFwdIn : forall (l1 l1': InputList) (l2 : OutputList)\n    (l3 : NotifList) (v : list BaseType), l1 -il- v!! -il> l1' ->\n    (mkInterface l1 l2 l3) -i- chanInProc {! v -i> (mkInterface l1' l2 l3)\n  | stepIntBuffOut : forall (l1 : InputList) (l2 l2' : OutputList)\n    (l3 : NotifList) (v : list BaseType), l2 -ol- v?? -ol> l2' ->\n    (mkInterface l1 l2 l3) -i- chanOutProc {? v -i> (mkInterface l1 l2' l3)\n  | stepIntFwdOut : forall (l1 : InputList) (l2 l2' : OutputList)\n    (l3 l3' : NotifList) (v : list BaseType) (r : Distance),\n    l2 -ol- v!! -ol> l2' -> l3 -nl- ((baseDistance r) :: v) ?? -nl> l3' ->\n    (mkInterface l1 l2 l3) -i- chanIOEnv _! v !_ r -i> (mkInterface l1 l2' l3')\n  | stepIntFwdNotif : forall (l1 : InputList) (l2 : OutputList)\n    (l3 l3' : NotifList) (v : list BaseType), l3 -nl- v!! -nl> l3' ->\n    (mkInterface l1 l2 l3) -i- chanAN {! v -i> (mkInterface l1 l2 l3')\n  where \"i -i- a -i> i'\" := (stepInter i a i').\n\n(** An interface i is action enabled for the action a iff\nthere is some derivative interface i' such that i transitions to i' via a.*)\nDefinition actEnabledInter (i : Interface) (a : ActInter) : Prop :=\n  exists i', i -i- a -i> i'.\n\n(** incomingInter v i means v is in the incoming list of the interface i.*)\nInductive incomingInter (v : list BaseType) : Interface -> Prop :=\n  iciWitness (li : InputList) (lo : OutputList) (ln : NotifList) :\n  <( v, zeroTime )> _: inList li ->\n  incomingInter v (mkInterface li lo ln).\n\n(** An interface is enabled on a discrete action if it can perform a corresponding\naction. The actions in question can be input or output, but there will be no case\nfor tau because interfaces can't do a tau action.*)\nInductive discActEnabledInter : DiscAct -> Interface -> Prop :=\n  | daeiIn : forall (c : Channel) (v : list BaseType) (i i' : Interface),\n    i -i- c {? v -i> i' -> discActEnabledInter (c ;? v) i\n  | daeiOut : forall (c : Channel) (v : list BaseType) (i i' : Interface),\n    i -i- c {! v -i> i' -> discActEnabledInter (c ;! v) i.\n\n(***************** Results *****************)\n\n(** An interface is always enabled on an input on the channel chanIOEnv.*)\nTheorem interfaceInEnabled : forall (i : Interface) (v : list BaseType),\n  actEnabledInter i (chanIOEnv {? v). destruct i. intros.\n  addHyp (inListInEnabled li0 v). invertClear H. rename x into l'.\n  exists ({| li := l'; lo := lo0; ln := ln0 |}). constructor.\n  assumption. Qed.\n\nLemma delAddInter : forall (i i' i'' : Interface) (d d' : Delay),\n  i -i- d -i> i' -> i' -i- d' -i> i'' ->\n  i -i- d +d+ d' -i> i''. destruct i as [l1 l2 l3]. intros.\n  destruct i' as [l1' l2' l3']. destruct i'' as [l1'' l2'' l3''].\n  invertClear H. invertClear H0. constructor.\n  eapply delAddInput. apply H6. assumption.\n  eapply delAddOutput. apply H9. assumption.\n  eapply stepNlDelAdd. apply H10. assumption. Qed.\n\nConjecture outList_received_in : forall (l l' : OutputList) (v : list BaseType),\n  l -ol- v ?? -ol> l' -> <(v, msgLatency)> _: outList l'.\n(**Proof: Obvious from outList semantics*)\n\nConjecture inList_received_in : forall (l l' : InputList) (v : list BaseType),\n  l -il- v ?? -il> l' -> <(v, msgLatency)> _: inList l'.\n(**Proof: Obvious from inList semantics*)\n\nConjecture notifList_received_in : forall (l l' : NotifList) (v : list BaseType),\n  l -nl- v ?? -nl> l' -> <(v, msgLatency)> _: notifList l'.\n(**Proof: Obvious from notifList semantics*)\n\n(*LOCAL TIDY*)\n\nLemma inList_pres_input v l l' a :\n  <( v, zeroTime )> _: inList l -> l -il- a -il> l' ->\n  <( v, zeroTime )> _: inList l' \\/ a = v !!. Admitted. (*5*)\n\n(*-LOCAL TIDY*)\n\n(*If the interface component does a step, and there's some timed out message in the input\nlist, then that message is either still there, or the action was an output of the value in\nquestion on the input channel for the software component.*)\nLemma inList_inter_pres_input v lix lox lnx lix' lox' lnx' a :\n  (forall d, a <> aiDel d) -> <(v, zeroTime )> _: inList lix ->\n  mkInterface lix lox lnx -i- a -i> mkInterface lix' lox' lnx' ->\n  <(v, zeroTime )> _: inList lix' \\/\n  a = chanInProc{! v. intros.\n  (*Proof: Case analyse the interface transition.*)\n  inversion H1;\n  (*In most of the remaining cases, the input list is preserved, giving the LHS.\n  The only cases in which itis not preserved is if an element is buffered or if an\n  element leaves the list.*)\n  try (subst; left; assumption).\n  (*Delay contradicts one of our hypotheses.*)\n  false.\n  (*Finally we just use an auxiliary result on inList to prove the remaining\n  cases.*)\n  lets IPI : inList_pres_input H0 H6. elim_intro IPI IL VEQ;\n  [left | right; inversion VEQ]; assumption.\n  lets IPI : inList_pres_input H0 H6. elim_intro IPI IL VEQ;\n  [left | right; inversion VEQ]. assumption. reflexivity.\n  Qed.\n\nLemma timeSplit_inter (h h'' : Interface) (d d' d'' : Delay) :\n  h -i- d'' -i> h'' -> d'' = d +d+ d' ->\n  exists h', h -i- d -i> h' /\\ h' -i- d' -i> h''.\n  (*Proof: Follows from time-split results on timed lists*)\n  intros. inversion H.\n  lets TSI : timeSplit_inputList H2 H0.\n  lets TSO : timeSplit_outputList H3 H0.\n  lets TSN : timeSplit_notifList H5 H0.\n  ex_flat. or_flat. and_flat.\n  exists ({| li := x1; lo := x0; ln := x |}).\n  split; constructor; eassumption. Qed.\n\n(*A notification list with a timed-out element can output that element.*)\nLemma notif_timeout_enabled_aux v lnx :\n  <( v, zeroTime )> _: notifList lnx ->\n  exists lnx', lnx -nl- (v !!) -nl> lnx'.\n  (*Proof: Lift a more general result on timed lists*)\n  introz U. lets TTE : timedList_timeout_enabled U.\n  ex_flat. destruct lnx. simpl in H. eexists.\n  econstructor. eassumption. Qed.\n\nLemma notif_timeout_enabled v lix lox lnx :\n  <( v, zeroTime )> _: notifList lnx ->\n  discActEnabledInter (chanAN ;! v) (mkInterface lix lox lnx).\n  (*Proof: Follows from the timeout rule of timed lists\n  and the interface semantics.*)\n  introz U.\n  (*First thing is that we show the transition is possible on the\n  notification list.*)\n  assert (exists lnx', lnx -nl- (v !!) -nl> lnx') as EXL.\n  apply notif_timeout_enabled_aux; assumption. ex_flat.\n  eapply daeiOut. eapply stepIntFwdNotif. eassumption.\n  Qed.\n\n(*LOCAL TIDY*)\n\nLemma interface_outProc_in (h : Interface) (v : list BaseType) :\n  discActEnabledInter (chanOutProc ;? v) h.\n  (*Proof: Obvious from semantics*)\n  destruct h. destruct lo0. repeat econstructor. Qed.\n\nLemma inter_mStable_in_not h h' : h -i- chanMStable {! [] -i> h' -> False.\n  introz U. inversion U. Qed.\n\nLemma inter_abort_in_not h h' :\n  h -i- chanAbort {?[] -i> h' -> False.\n  introz U. inversion U. Qed.\n\nLemma outList_in_input_pres v u t lo lo' :\n  <( v, t )> _: outList lo -> outList lo -tl- u ?? -tl> outList lo' ->\n  <( v, t )> _: outList lo'. Admitted. (*6*)\n(*Prove in bulk: #interface-linking*)\n\nLemma outList_in_output_pres v u t lo lo' :\n  <( v, t )> _: outList lo -> outList lo -tl- u !! -tl> outList lo' ->\n  0 < t -> <( v, t )> _: outList lo'. Admitted. (*6*)\n(*Prove in bulk: #interface-linking*)\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/InterfaceLanguage.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5, "lm_q1q2_score": 0.27723523248021364}}
{"text": "Require Import ExtLib.Data.Monads.OptionMonad.\nRequire Import ExtLib.Structures.Monads.\n\nFrom CHKC Require Import Tactics ListUtil Map.\n\n(** * Document Conventions *)\n\n(** It is common when defining syntax for a language on paper to associate one or many\n    _metavariables_ with each syntactic class. For example, the metavariables <<x>>, <<y>>,\n    and <<z>> are often used to represent the syntactic class of program variables. It is\n    understood that wherever these metavariables appear they indicate an implicit universal\n    quantification over all members of the syntactic class they represent. In Coq, however,\n\n\n    we have no such issue -- all quantification must be made explicit. However, we must still\n    grapple with the hardest problem in computer science: naming our quantified variables.\n    To ameliorate this problem, we maintain two stylistic invariants.\n\n    - (1) Whenever a new piece of syntax is introduced we we will include, in parentheses,\n          its associated metavariable. We will then use this as the naming convention for\n          naming universally quantified variables in the future.\n    - (2) Whenever syntax, semantics, or proofs appear in the associated paper\n          (\"Checked C for Safety, Gradually\") we take this to be an authoritative source\n          for naming. *)\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. *)\n\nRequire Import Arith.\nRequire Import ZArith.\nRequire Import ZArith.BinIntDef.\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.\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 : Set :=\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\nInductive type : Set :=\n  | TNat : type\n  | TPtr : mode -> type -> type\n  | TStruct : struct -> type\n  | TArray : Z -> Z -> type -> type.\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\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\nInductive type_wf (D : structdef) : type -> Prop :=\n  | WFTNat : type_wf D TNat\n  | WFTPtr : forall m 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      (*l <= 0 /\\ h > 0 ->*)\n      word_type t ->\n      type_wf D t ->\n      type_wf D (TArray 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.\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(** Expressions, [e], compose to form programs in Checked C. It is a core, imperative\n    calculus of explicit memory management based on C. Literals, [ELit], are annotated\n    with their word type. Memory allocation, [EMalloc], is annotated with a type rather\n    than a number (as in C). The amount of memory to be allocated can then be computed\n    from the type. Unchecked regions, [EUnchecked], are used to delimit code which may\n    perform unsafe (as defined by the type system) operations. The rest of the language\n    is standard.\n\n    Expressions also have a well-formedness predicate, parameterized by a structdef. This\n    says that any (word or compound) types cannot reference structures that are not defined\n    by the structdef.\n\n    Finally, we define a function [subst] over expressions which takes a variable, [x], an\n    expression, [v], and an expression, [e], and returns [e] with [v] substituted for [x].\n    Even though [v] can be an arbitrary expression, it is expected that callers will only\n    ever provide a value (defined below). *)\n\nInductive expression : Set :=\n  | ELit : Z -> type -> expression\n  | EVar : var -> 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\n  | EAssign : expression -> expression -> expression\n  | EUnchecked : expression -> expression.\n\nInductive expr_wf (D : structdef) : expression -> Prop :=\n  | WFELit : forall n t,\n    word_type t ->\n    type_wf D t ->\n    expr_wf D (ELit n t)\n  | WFEVar : forall x,\n      expr_wf D (EVar x)\n  | WFELet : forall x e1 e2,\n      expr_wf D e1 ->\n      expr_wf D e2 ->\n      expr_wf D (ELet x e1 e2)\n  | WFEMalloc : forall w,\n      type_wf D w ->\n      expr_wf D (EMalloc w)\n  | WFECast : forall t e,\n      word_type t ->\n      type_wf D t ->\n      expr_wf D e ->\n      expr_wf D (ECast t e)\n  | WFEPlus : forall e1 e2,\n      expr_wf D e1 ->\n      expr_wf D e2 ->\n      expr_wf D (EPlus e1 e2)\n  | WFEFieldAddr : forall e f,\n      expr_wf D e ->\n      expr_wf D (EFieldAddr e f)\n  | WFEDeref : forall e,\n      expr_wf D e ->\n      expr_wf D (EDeref e)\n  | WFEAssign : forall e1 e2,\n      expr_wf D e1 ->\n      expr_wf D e2 ->\n      expr_wf D (EAssign e1 e2)\n  | WFEUnchecked : forall e,\n      expr_wf D e ->\n      expr_wf D (EUnchecked e).\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 *)\nFixpoint subst (x : var) (v : expression) (e : expression) : expression :=\n  match e with\n  | ELit _ _ => e\n  | EVar y => if var_eq_dec x y then v else e\n  | ELet x' e1 e2 =>\n    if var_eq_dec x x' then ELet x' (subst x v e1) e2 else ELet x' (subst x v e1) (subst x v e2)\n  | EMalloc _ => e\n  | ECast t e' => ECast t (subst x v e')\n  | EPlus e1 e2 => EPlus (subst x v e1) (subst x v e2)\n  | EFieldAddr e' f => EFieldAddr (subst x v e') f\n  | EDeref e' => EDeref (subst x v e')\n  | EAssign e1 e2 => EAssign (subst x v e1) (subst x v e2)\n  | EUnchecked e' => EUnchecked (subst x v e')\n  end.\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    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.\n\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 l h T =>\n    Some (l, Zreplicate (h - l) 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 : Set :=\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 : Set :=\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  | CCast : type -> context -> context\n  | CDeref : context -> context\n  | CAssignL : context -> expression -> context\n  | CAssignR : Z -> type -> context -> 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  | 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  | CUnchecked E' => EUnchecked (in_hole e E')\n  end.\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  | CCast _ E' => mode_of E'\n  | CDeref E' => mode_of E'\n  | CAssignL E' _ => mode_of E'\n  | CAssignR _ _ E' => 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  | 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  | 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\nInductive step (D : structdef) : heap -> expression -> heap -> result -> Prop :=\n  | SPlusChecked : forall H n1 h l t n2,\n      n1 > 0 ->\n      step D\n        H (EPlus (ELit n1 (TPtr Checked (TArray l h t))) (ELit n2 TNat))\n        H (RExpr (ELit (n1 + n2) (TPtr Checked (TArray (l - n2) (h - n2) t))))\n  | SPlus : forall H n1 t1 n2 t2,\n      (forall l h t, t1 <> TPtr Checked (TArray l h t)) -> \n      step D\n        H (EPlus (ELit n1 t1) (ELit n2 t2))\n        H (RExpr (ELit (n1 + n2) t1))\n  | SPlusNull : forall H n1 l h t n2,\n      n1 <= 0 ->\n      step D\n        H (EPlus (ELit n1 (TPtr Checked (TArray l h t))) (ELit n2 TNat))\n        H RNull\n  | SCast : forall H t n t',\n      step D\n        H (ECast t (ELit n t'))\n        H (RExpr (ELit n t))\n  | SDeref : forall H n n1 t1 t,\n      (expr_wf D (ELit n1 t1)) ->\n      Heap.MapsTo n (n1, t1) H ->\n      (forall l h t', t = TPtr Checked (TArray l h t') -> h > 0 /\\ l <= 0) ->\n      step D\n        H (EDeref (ELit n t))\n        H (RExpr (ELit n1 t1))\n  | SDerefHighOOB : forall H n t t1 l h,\n      h <= 0 ->\n      t = TPtr Checked (TArray l h t1) ->\n      step D\n        H (EDeref (ELit n t))\n        H RBounds\n  | SDerefLowOOB : forall H n t t1 l h,\n      l > 0 ->\n      t = TPtr Checked (TArray l h t1) ->\n      step D\n        H (EDeref (ELit n t))\n        H RBounds\n  | SAssign : forall H n t n1 t1 H',\n      Heap.In n H ->\n      (forall l h t', t = TPtr Checked (TArray l h t') -> h > 0 /\\ l <= 0) -> \n      H' = Heap.add n (n1, t1) H ->\n      step D\n        H  (EAssign (ELit n t) (ELit n1 t1))\n        H' (RExpr (ELit n1 t1))\n  | SFieldAddrChecked : forall 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\n        H (EFieldAddr (ELit n t) fi)\n        H (RExpr (ELit n0 t0))\n  | SFieldAddrNull : forall H (fi : field) n T,\n      n <= 0 ->\n      step D\n        H (EFieldAddr (ELit n (TPtr Checked (TStruct T))) fi)\n        H RNull\n  | SFieldAddr : forall 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\n        H (EFieldAddr (ELit n t) fi)\n        H (RExpr (ELit n0 t0))\n  | SMalloc : forall H w H' n1,\n      allocate D H w = Some (n1, H') ->\n      step D\n        H (EMalloc w)\n        H' (RExpr (ELit n1 (TPtr Checked w)))\n  | SLet : forall H x n t e,\n      step D\n        H (ELet x (ELit n t) e)\n        H (RExpr (subst x (ELit n t) e))\n  | SUnchecked : forall H n t,\n      step D\n        H (EUnchecked (ELit n t))\n        H (RExpr (ELit n t))\n  | SAssignHighOOB : forall H n t n1 t1 l h,\n      h <= 0 ->\n      t = TPtr Checked (TArray l h t1) ->\n      step D\n        H (EAssign (ELit n t) (ELit n1 t1))\n        H RBounds\n  | SAssignLowOOB : forall H n t n1 t1 l h,\n      l > 0 ->\n      t = TPtr Checked (TArray l h t1) ->\n      step D\n        H (EAssign (ELit n t) (ELit n1 t1))\n        H RBounds\n  | SDerefNull : forall H t n w,\n      n <= 0 ->\n      t = TPtr Checked w ->\n      step D\n        H (EDeref (ELit n t))\n        H RNull\n  | SAssignNull : forall H t w n n1 t',\n      n1 <= 0 ->\n      t = TPtr Checked w ->\n      step D\n        H (EAssign (ELit n1 t) (ELit n t'))\n        H RNull.\n\nHint Constructors step.\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]. *)\n\nInductive reduce (D : structdef) : heap -> expression -> mode -> heap -> result -> Prop :=\n  | RSExp : forall H e m H' e' E,\n      step D H e H' (RExpr e') ->\n      m = mode_of(E) ->\n      reduce D\n        H (in_hole e E)\n        m\n        H' (RExpr (in_hole e' E))\n  | RSHaltNull : forall H e m H' E,\n      step D H e H' RNull ->\n      m = mode_of(E) ->\n      reduce D\n        H (in_hole e E)\n        m\n        H' RNull\n  | RSHaltBounds : forall H e m H' E,\n      step D H e H' RBounds ->\n      m = mode_of(E) ->\n      reduce D\n        H (in_hole e E)\n        m\n        H' RBounds.\n\nHint Constructors reduce.\n\nDefinition reduces (D : structdef) (H : heap) (e : expression) : Prop :=\n  exists (m : mode) (H' : heap) (r : result), reduce D H e m H' r.\n\nHint Unfold reduces.\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\n\nInductive well_typed_lit (D : structdef) (H : heap) : scope -> Z -> type -> Prop :=\n  | TyLitInt : forall s n,\n      well_typed_lit D H s n TNat\n  | TyLitU : forall s n w,\n      well_typed_lit D H s n (TPtr Unchecked w)\n  | TyLitZero : forall s t,\n      well_typed_lit D H s 0 t\n  | TyLitRec : forall s n w,\n      set_In (n, TPtr Checked w) s ->\n      well_typed_lit D H s n (TPtr Checked w)\n  | TyLitC : forall s n w b ts,\n      Some (b, ts) = allocate_meta D w ->\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 H (set_add eq_dec_nt (n, TPtr Checked w) s) n' t') ->\n      well_typed_lit D H s n (TPtr Checked w).\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) (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), set_In (n, TPtr Checked w) s -> P s n (TPtr Checked w)) ->\n       (forall (s : scope) (n : Z) (w : type) (ts : list type) (b : Z),\n        Some (b, ts) = allocate_meta D w ->\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 H (set_add eq_dec_nt (n, TPtr Checked w) s) n' t' /\\\n           P (set_add eq_dec_nt (n, TPtr Checked w) s) n' t') ->\n        P s n (TPtr Checked w)) -> forall (s : scope) (n : Z) (w : type), well_typed_lit D H s n w -> P s n w.\nProof.\n  intros D 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' Hscope => HTyLitRec s' n' w' Hscope\n            | TyLitC _ _ s' n' w' b ts Hts IH =>\n              HTyLitC s' n' w' ts b Hts (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' (conj Ht' (conj Hheap (conj Hwt (F (set_add eq_dec_nt (_ , TPtr Checked w') s') n' t' Hwt)))))\n                                               end\n                                             end\n                                           end\n                                         end)\n            end).\nQed.\n\n(** Expression Typing *)\nModule Env := Map.Make Nat_as_OT.\n\nDefinition env := Env.t type.\n\nDefinition empty_env := @Env.empty type.\n\nInductive well_typed { D : structdef } { H : heap } : env -> mode -> expression -> type -> Prop :=\n  | TyLit : forall env m n t,\n      @well_typed_lit D H empty_scope n t ->\n      well_typed env m (ELit n t) t\n  | TyVar : forall env m x t,\n      Env.MapsTo x t env ->\n      well_typed env m (EVar x) t\n  | TyLet : forall env m x e1 t1 e2 t,\n      well_typed env m e1 t1 ->\n      well_typed (Env.add x t1 env) m e2 t ->\n      well_typed env m (ELet x e1 e2) t\n  | TyFieldAddr : forall env m e m' T fs i fi ti,\n      well_typed env 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 m (EFieldAddr e fi) (TPtr m' ti)\n  | TyPlus : forall env m e1 e2,\n      well_typed env m e1 TNat ->\n      well_typed env m e2 TNat ->\n      well_typed env m (EPlus e1 e2) TNat\n  | TyMalloc : forall env m w,\n      (forall l h t, w = TArray l h t -> l = 0 /\\ h > 0) ->\n      well_typed env m (EMalloc w) (TPtr Checked w)\n  | TyUnchecked : forall env m e t,\n      well_typed env Unchecked e t ->\n      well_typed env m (EUnchecked e) t\n  | TyCast : forall env m t e t',\n      (m = Checked -> forall w, t <> TPtr Checked w) ->\n      well_typed env m e t' ->\n      well_typed env m (ECast t e) t\n  | TyDeref : forall env m e m' t l h t',\n      well_typed env m e (TPtr m' t) ->\n      ((word_type t /\\ t = t') \\/ (t = TArray l h t' /\\ word_type t' /\\ type_wf D t')) ->\n      (m' = Unchecked -> m = Unchecked) ->\n      well_typed env m (EDeref e) t'\n  | TyIndex : forall env m e1 m' l h t e2,\n      word_type t -> type_wf D t ->\n      well_typed env m e1 (TPtr m' (TArray l h t)) ->\n      well_typed env m e2 TNat ->\n      (m' = Unchecked -> m = Unchecked) ->\n      well_typed env m (EDeref (EPlus e1 e2)) t\n  | TyAssign : forall env m e1 m' t l h t' e2,\n      well_typed env m e1 (TPtr m' t) ->\n      well_typed env m e2 t' ->\n      ((word_type t /\\ t = t') \\/ (t = TArray l h t' /\\ word_type t' /\\ type_wf D t')) ->\n      (m' = Unchecked -> m = Unchecked) ->\n      well_typed env m (EAssign e1 e2) t'\n  | TyIndexAssign : forall env m e1 m' l h t e2 e3,\n      word_type t -> type_wf D t ->\n      well_typed env m e1 (TPtr m' (TArray l h t)) ->\n      well_typed env m e2 TNat ->\n      well_typed env m e3 t ->\n      (m' = Unchecked -> m = Unchecked) ->\n      well_typed env m (EAssign (EPlus e1 e2) e3) t.\n\nHint Constructors well_typed.\n\n(** ** Metatheory *)\n\n(** *** Automation *)\n\n(* TODO: write a function decompose : expr -> (context * expr) *)\n\n\nLtac clean :=\n  try (match goal with\n       | [ H : expr_wf _ _ |- _ ] => inv H\n       | [ H : type_wf _ _ |- _ ] => inv H\n       end);\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 } (H' : heap) (H : heap) : Prop :=\n  forall n t,\n    @well_typed_lit D H empty_scope n t->\n    @well_typed_lit D 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 H e H' r,\n    @step D H e H' r ->\n    reduces D 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 H e0 e,\n    (exists E, in_hole e0 E = e) ->\n    reduces D H e0 ->\n    reduces D H e.\nProof.\n  intros.\n  destruct H0 as [ E Hhole ].\n  destruct H1 as [ H' [ m' [ r HRed ] ] ].\n  inv HRed as [ ? e0' ? ? e0'' E' | ? e0' ? ? E' | ? e0' ? ? E' ]; 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\nRequire Import Omega.\n\n(*changed THIS!! REMEMBER*)\n\nOpen Scope Z.\nLemma wf_implies_allocate_meta :\n  forall (D : structdef) (w : type),\n    (forall l h t, w = TArray l h t -> l = 0 /\\ h > 0) ->\n    type_wf D w -> exists b allocs, allocate_meta D w = Some (b, allocs).\nProof.\n  intros D w HL HT.\n  destruct w; simpl in *; eauto.\n  - inv HT. destruct H0.\n    apply StructDef.find_1 in H.\n    rewrite -> H.\n    eauto.\nQed.\n\nLemma wf_implies_allocate :\n  forall (D : structdef) (w : type) (H : heap),\n    (forall l h t, w = TArray l h t -> l = 0 /\\ h > 0) ->\n    type_wf D w -> exists n H', allocate D H w = Some (n, H').\nProof.\n  intros D w H HL 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\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  - edestruct HL; eauto.\n    subst; eauto.\nQed.\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 EnvFacts := WFacts_fun Env.E Env.\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  omega.\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.\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    + omega.\n    + simpl in *.\n      apply IHn in H.\n      omega.\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. omega.\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*)\nLemma progress : forall D H m e t,\n    structdef_wf D ->\n    heap_wf D H ->\n    expr_wf D e ->\n    @well_typed D H empty_env m e t ->\n    value D e \\/\n    reduces D H e \\/\n    unchecked m e.\nProof with eauto 20 with Progress.\n  intros D H m e t HDwf HHwf Hewf Hwt.\n  remember empty_env as env.\n  induction Hwt as [\n                     env m n t HTyLit                                       | (* Literals *)\n                     env m x t HVarInEnv                                    | (* Variables *)\n                     env m x e1 t1 e2 t HTy1 IH1 HTy2 IH2                   | (* Let-Expr *)\n                     env m e m' T fs i fi ti HTy IH HWf1 HWf2               | (* Field Addr *)\n                     env m e1 e2 HTy1 IH1 HTy2 IH2                          | (* Addition *)\n                     env m w                                                | (* Malloc *)\n                     env m e t HTy IH                                       | (* Unchecked *)\n                     env m t e t' HChkPtr HTy IH                            | (* Cast *)\n                     env m e m' w l h t HTy IH HPtrType HMode                 | (* Deref *)\n                     env m e1 m' l h t e2 WT Twf HTy1 IH1 HTy2 IH2 HMode             | (* Index *)\n                     env m e1 m' w l h t e2 HTy1 IH1 HTy2 IH2 HPtrType HMode  | (* Assign *)\n                     env m e1 m' l h t e2 e3 WT Twf HTy1 IH1 HTy2 IH2 HTy3 IH3 HMode   (* IndAssign *)\n                   ]; clean.\n\n  (* Case: TyLit *)\n  - (* Holds trivially, since literals are values *)\n    left...\n  (* Case: TyVar *)\n  - (* Impossible, since environment is empty *)\n    inversion HVarInEnv.\n  (* Case: TyLet *)\n  - (* `ELet x e1 e2` is not a value *)\n    right.\n    (* Invoke the IH on `e1` *)\n    destruct IH1 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 (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: TyFieldAddr *)\n  - (* `EFieldAddr e fi` isn't a value *)\n    right.\n    (* Invoke the IH on `e` *)\n    destruct IH 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      (* 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    (* 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: TyPlus *)\n  - (* `EPlus e1 e2` isn't a value *)\n    right.\n    (* Invoke the IH on `e1` *)\n    destruct IH1 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      destruct IH2 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; eauto.\n        apply SPlus.\n        intros l h t Eq; subst.\n        inv HTy1.\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: TyMalloc *)\n  - (* `EMalloc w` isn't a value *)\n    right.\n    (* Allocation always succeeds, according to SMalloc *)\n    left.\n    (* LEO: Where is H1 created from? Match goal style for maintainability *)\n    destruct (wf_implies_allocate D w H H0 H2) as [ n [ H' HAlloc]]...\n  (* Case: TyUnchecked *)\n  - (* `EUnchecked e` isn't a value *)\n    right.\n    (* Invoke the IH on `e` *)\n    destruct IH 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: TyCast *)\n  - (* `ECast t e` isn't a value *)\n    right.\n    (* Invoke the IH on `e` *)\n    destruct IH as [ HVal | [ HRed | HUnchk ] ].\n    (* Case: `e` is a value *)\n    + (* We can step according to SCast *)\n      left.\n      inv HVal...\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  (* 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\n    (* Invoke the IH on `e` *)\n    destruct IH 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        { (* We now proceed by case analysis on '|- n0 : ptr_C w' *)\n          inversion H7.\n          (* Case: TyLitZero *)\n          {\n           (* Impossible, since n > 0 *)\n           exfalso. omega.\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            subst.\n            destruct H8 with (k := 0) as [ n' [ t' [ Ht'tk [ Hheap Hwtn' ] ] ] ];\n            [ inv H2; subst; inv H3; inv H4; simpl; omega | ].\n            rewrite Z.add_0_r in Hheap;\n            inv Ht'tk. \n            left.\n            eapply step_implies_reduces.\n            apply SDeref; eauto.\n            - destruct H2; subst.\n              inv H2; simpl in *; inv H4; simpl in *; subst; eauto;\n                inv H5; repeat constructor.\n            - intros.\n              destruct H2 as [Hyp1 Hyp2].\n              subst.\n              inv H3.\n              inv Hyp1.\n          }\n        }\n        (* Case: n <= 0 *)\n        { (* We can step according to SDerefNull *)\n          subst... }\n\n      (* Case: `w` is an array pointer *)\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          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 H2 as [Hyp1 [Hyp2 Hyp3]]; subst.\n            (* should this also be on ' h > 0' instead? DP*)\n            destruct (Z_gt_dec h 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              subst.\n              inv H4.\n              destruct (Z_gt_dec l 0).\n\n              (* if l > 0 we have a bounds error*)\n              {\n                eapply step_implies_reduces. eapply SDerefLowOOB. eapply g. eauto.\n              }\n              \n              (* if l <= 0 we can step according to SDeref. *)\n\n              assert (Hhl : h - l > 0). {\n                destruct h. inv Hneq0. omega. inv Hneq0.\n              }\n              destruct (h - l) as [| p | ?] eqn:Hp; zify; [omega | |omega].\n              simpl in *.\n              rewrite replicate_length in *.\n              assert (HL: l + Z.of_nat (Pos.to_nat p) = h) by (zify; omega).\n              rewrite HL in *; try omega.\n\n              destruct H8 with (k := 0) as [ n' [ t' [ Ht'tk [ Hheap Hwtn' ] ] ] ].\n              { (split;  omega). }\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 omega.\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              apply SDeref; eauto.\n              - repeat constructor; eauto.\n              - intros l' h' t' HT.\n                injection HT; intros ? ? ?; subst h l t.\n                split; zify; omega.\n            }\n            (* Case: h <= 0 *)\n            { (* We can step according to SDerefOOB *)\n              subst. left. eapply step_implies_reduces. \n              eapply SDerefHighOOB. eauto. eauto.\n            } \n          }\n        } \n        (* Case: n <= 0 *)\n        { (* We can step according to SDerefNull *)\n          subst... }\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  - right.\n    destruct m'; [> | right; eauto 20 with Progress].\n    clear HMode.\n    (* Leo: This is becoming hacky *)\n    inv H1.\n    specialize (IH1 H3 eq_refl).\n    specialize (IH2 H4 eq_refl).\n    destruct IH1 as [ HVal1 | [ HRed1 | HUnchk1 ] ]; eauto.\n    + inv HVal1 as [ n1 t1 ].\n      destruct IH2 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        exists Checked.\n        exists H.\n        { destruct (Z_gt_dec n1 0).\n          - (* n1 > 0 *)\n            exists (RExpr (EDeref (ELit (n1 + n) (TPtr Checked (TArray (l - n) (h - n) t))))).\n            ctx (EDeref (ELit (n1 + n) (TPtr Checked (TArray (l - n) (h - n) t))))\n                (in_hole (ELit (n1 + n) (TPtr Checked (TArray (l - n) (h - n) t))) (CDeref CHole)).\n            rewrite HCtx.\n            rewrite HCtx0.\n            inv HTy2.\n            eapply RSExp; eauto.\n          - (* n1 <= 0 *)\n            exists RNull.\n            subst.\n            rewrite HCtx.\n            eapply RSHaltNull; eauto.\n            inv HTy2.\n            eapply SPlusNull. omega.\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  - (* 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    destruct IH1 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      inv IH2 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          destruct HPtrType as [Hw | Hw]; eauto.\n          - inv Hw; subst.\n            inv HTy1; eauto.\n            match goal with\n            | [ H : well_typed_lit _ _ _ _ _ |- _ ] => inv H\n            end...\n            + (*This is weird, why is 0 a case? DP*)\n              left. eapply step_implies_reduces with (H' := H) (r := RNull).\n              apply (SAssignNull D H (TPtr Checked t) t n2' 0 t2').\n              omega. reflexivity.\n            + solve_empty_scope.\n            + left.\n              inv H0; inv H2;\n              destruct (H5 0) as [x [xT [HNth [HMap HWT]]]]; simpl in*;\n                try (zify; omega);\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          - inv HTy1; eauto.\n            match goal with\n            | [ H : well_typed_lit _ _ _ _ _ |- _ ] => inv H\n            end...\n            + (*Same issue here as above DP*)\n              left. eapply step_implies_reduces with (H' := H) (r := RNull).\n              apply (SAssignNull D H (TPtr Checked w) w n2' 0 t2').\n              omega. reflexivity.\n            + solve_empty_scope.\n            + left.\n              destruct Hw as [? [? ?]]; subst.\n              destruct (Z_gt_dec h 0).\n              * (* h > 0 - Assign  *)\n                destruct (Z_gt_dec l 0).\n                { (* l > 0 *)\n                eapply step_implies_reduces.\n                eapply SAssignLowOOB; eauto... inv HTy2. eauto. }\n                { (* l <= 0 *)\n                  eapply step_implies_reduces.\n                  eapply SAssign; eauto...  inv H1.\n                  assert (Hpos : exists p, (h - l) = Z.pos p).\n                  {\n                    destruct (h - l)eqn:P.\n                    -omega.\n                    -exists p. reflexivity.\n                    -zify. omega.\n                  }\n                  destruct (H4 0) as [n' [t' [HNth [HMap HWT]]]]; eauto.\n                  + destruct Hpos. rewrite H0. simpl. \n                    symmetry in H0.\n                    assert (Hsucc : exists n, Pos.to_nat x = S n) by eapply pos_succ.\n                    destruct Hsucc. rewrite H1. simpl. zify.\n                    rewrite replicate_length.\n                    rewrite <- H1.\n                    rewrite H0.\n                    omega.\n                  + inv HNth. \n                    rewrite Z.add_0_r in HMap. destruct Hpos.\n                      rewrite H0 in H1. assert (Hsucc : exists n, Pos.to_nat x = S n) by eapply pos_succ.\n                      destruct Hsucc. simpl in H1. rewrite H5 in H1. simpl in H1.\n                      inv H1.\n                      eexists; eauto.\n                    + intros. inv H0. omega.\n                }\n              * (* h <= 0 *)\n                eapply step_implies_reduces.\n                eapply SAssignHighOOB; eauto... inv HTy2. eauto.\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  (* T-IndAssign *)\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\n    inv H2.\n\n    (* Invoke IH on e1 *)\n    destruct IH1 as [ HVal1 | [ HRed1 | [| HUnchk1 ] ] ]; idtac...\n    + (* Case: e1 is a value *)\n      inv HVal1.\n      (* Invoke IH on e2 *)\n      destruct IH2 as [ HVal2 | [ HRed2 | [| HUnchk2 ] ] ]; idtac...\n      * inv HVal2.\n        ctx (EAssign (EPlus (ELit n t0) (ELit n0 t1)) e3) (in_hole (EPlus (ELit n t0) (ELit n0 t1)) (CAssignL CHole e3)).\n        inv HTy1.\n        inv HTy2.\n        {\n          inv H11; inv H12; (eauto 20 with Progress); \n            try solve_empty_scope.\n          - destruct IH3 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 3 eexists.\n              * eapply RSHaltNull... eapply SPlusNull. omega.\n              * eapply RSHaltNull... eapply SPlusNull. omega.\n            + destruct HRed3 as [H' [? [r HRed3]]].\n              rewrite HCtx; left; eexists; eexists; eexists.\n              eapply RSHaltNull... eapply SPlusNull. omega. \n            + destruct HUnchk3 as [ e' [ E [ He2 HEUnchk ]]]; subst.\n              rewrite HCtx; left; eexists; eexists; eexists.\n              * eapply RSHaltNull... eapply SPlusNull. omega.\n          - destruct IH3 as [ HVal3 | [ HRed3 | [| HUnchk3]]]; idtac...\n            + inv HVal3.\n              inv HTy3.\n              destruct (Z_gt_dec n 0); rewrite HCtx; left; eexists; eexists; eexists.\n              * eapply RSHaltNull... eapply SPlusNull. omega.\n              * eapply RSHaltNull... eapply SPlusNull. omega.\n            + destruct HRed3 as [H' [? [r HRed3]]].\n              rewrite HCtx; left; eexists; eexists; eexists.\n              * eapply RSHaltNull... eapply SPlusNull. omega.\n            + destruct HUnchk3 as [ e' [ E [ He2 HEUnchk ]]]; subst.\n              rewrite HCtx; left; eexists; eexists; eexists.\n              * eapply RSHaltNull... eapply SPlusNull. omega.\n          - destruct (Z_gt_dec n 0); rewrite HCtx; left; do 3 eexists.\n              * eapply RSExp. eapply SPlusChecked. omega. eauto.\n              * eapply RSHaltNull. eapply SPlusNull. omega. eauto.\n          -  destruct (Z_gt_dec n 0); rewrite HCtx; left; do 3 eexists.\n              * eapply RSExp. eapply SPlusChecked. omega. eauto.\n              * eapply RSHaltNull. eapply SPlusNull. omega. eauto.\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))...\nQed.\n\n(* ... for Preservation *)\n\nLemma weakening : forall D H env m n t,\n    @well_typed D H env m (ELit n t) t ->\n    forall x t', @well_typed D H (Env.add x t' env) m (ELit n t) t.\nProof.\n  intros D H env m e t HWT.\n  inv HWT; clear H3.\n  inv H5; eauto.\nQed.\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_wt : forall D H env1 env2 m e t,\n    Env.Equal env1 env2 ->\n    @well_typed D H env1 m e t ->\n    @well_typed D H env2 m e t.\nProof.\n  intros.\n  generalize dependent env2.\n  induction H1; eauto 20.\n  - intros.\n    apply TyVar.\n    unfold Env.Equal in H1.\n    apply Env.find_2.\n    rewrite <- H1.\n    apply Env.find_1.\n    assumption.\n  - intros.\n    eapply TyLet.\n    apply IHwell_typed1.\n    assumption.\n    apply IHwell_typed2.\n    apply equiv_env_add.\n    auto.\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\nLemma substitution :\n  forall D H env m x v e t1 t2,\n    literal v ->\n  @well_typed D H env m v t1 ->\n  @well_typed D H (Env.add x t1 env) m e t2 ->\n  @well_typed D H env m (subst x v e) t2.\nProof.\n  intros D H env m x v e t1 t2 Hvalue HWTv HWTe.\n  generalize dependent v.\n  remember (Env.add x t1 env) as env'.\n  assert (Eq: Env.Equal env' (Env.add x t1 env))\n    by (subst; apply EnvFacts.Equal_refl).\n  clear Heqenv'.\n  generalize dependent env.\n  induction HWTe; subst; simpl; eauto 20.\n  - intros. destruct (var_eq_dec x x0); subst.\n    + eapply Env.mapsto_equal in Eq; eauto.\n      apply env_maps_add in Eq; subst. assumption.\n    + apply TyVar.\n      eapply Env.mapsto_equal in Eq; eauto.\n      apply Env.add_3 in Eq. assumption. assumption.\n  - intros. destruct (var_eq_dec x x0); subst.\n    + eapply TyLet.\n      * apply IHHWTe1; eauto.\n      * eapply equiv_env_wt; eauto.\n        eapply env_shadow_eq; eauto.\n    + eapply TyLet.\n      * apply IHHWTe1; eauto. \n      * {\n          apply IHHWTe2; eauto.\n          - apply env_neq_commute_eq; eauto.\n          - inv Hvalue as [n' t'].\n            inv HWTv. eapply TyLit; eauto.\n        } \n  - intros. subst. apply TyUnchecked. apply IHHWTe; eauto.\n    inv Hvalue as [n' t'].\n    destruct m.\n      * inv HWTv.\n        apply TyLit.\n        assumption.\n      * assumption.\nQed.\n\nHint Resolve substitution : Preservation.\n\nLemma heapWF :\n  forall D H H' env m e t,\n    @well_typed D H env m e t ->\n    @heap_consistent D H' H ->\n    @well_typed D H' env m e t.\nProof.\n  intros D H H' env m e t WT HC.\n  generalize dependent H'.\n  induction WT; intros; eauto.\nQed.  \n\nHint Resolve heapWF : Preservation.\n\n(*\nLemma wf_empty_scope : forall D H, scope_wf D H empty_scope.\nProof.\n  intros D H x T Contra.\n  inversion Contra.\nQed.\n\nHint Resolve wf_empty_scope.\nHint Resolve wf_empty_scope : Preservation.\n *)\n(* Automate this*)\nLemma length_nth : forall {A} (l : list A) (k : nat),\n    0 <= Z.of_nat(k) < Z.of_nat(length l) -> exists n, nth_error l k = Some n.\nProof.\n  intros A l; induction l; intros k Hyp; simpl in *.\n  - omega.\n  - destruct k; simpl.\n    + exists a; eauto.\n    + assert (H: 0 <= Z.of_nat(k) < Z.of_nat(S k)). {split.\n      *omega. \n      *zify. omega. }\n     destruct H. assert (H2: Z.of_nat(k) < Z.of_nat (length l)). {zify. omega. }\n     assert (H3: 0 <= Z.of_nat(k) < Z.of_nat (length l)). {split; assumption. }\n     apply (IHl k H3).\nQed.      \n\nLemma nth_length : forall {A} (l : list A) (k : nat) n,\n    nth_error l k = Some n -> 0 <= Z.of_nat(k) < Z.of_nat(length l).\nProof.\n  intros A l; induction l; intros k n Hyp; simpl in *.\n  - apply nth_error_In in Hyp; inv Hyp.\n  - destruct k; simpl in *.\n    +zify. omega.\n    + edestruct IHl; eauto. zify.\n      omega.\nQed.\n\nRequire Import Coq.Program.Equality.\n  \nLemma heap_wf_maps_nonzero : forall D H n v, heap_wf D H -> Heap.MapsTo n v H -> n <> 0.\nProof.\n  intros D H n v Hwf HMap.\n  destruct (Hwf n) as [ _ HIn ]. \n  destruct n; eauto.\n    -exfalso. destruct HIn; try eexists; eauto; \n     inversion H0.\n    -zify. omega.\n    -zify. omega.\nQed.\n\n(*\nLemma scope_wf_heap_weakening :\n  forall s D H x v,\n    ~ Heap.In x H ->\n    scope_wf D H s -> scope_wf D (Heap.add x v H) s.\nProof.\n  intros s D H x v HNotIn HSwf.\n  intros x' t' HS.\n  destruct (HSwf x' t') as [x0 [HA Hx0]]; eauto.\n  exists x0.\n  split; auto.\n  intros k Hk.\n  destruct (Hx0 k Hk) as [n' [T [HT HM]]].\n  exists n'. exists T.\n  split; auto.\n  apply Heap.add_2; eauto.\n  intro Contra; subst.\n  apply HNotIn.\n  eexists; eauto.\nQed.\n\nHint Resolve scope_wf_heap_weakening.\n*)\nLemma cardinal_not_in :\n  forall D H, heap_wf D H -> ~ Heap.In (Z.of_nat(Heap.cardinal H) + 1) H.\n  intros D H Hwf Contra.\n  destruct (Hwf (Z.of_nat(Heap.cardinal H) + 1)) as [H1 H2].\n  specialize (H2 Contra).\n  omega.\nQed.\n\n\nLemma well_typed_preserved : forall D H t, heap_wf D H ->\n  @heap_consistent D (Heap.add (Z.of_nat(Heap.cardinal H) + 1) (0, t) H) H.\nProof.\n  intros D H t0 Hwf n t HT.\n  induction HT using well_typed_lit_ind'; pose proof (cardinal_not_in D H Hwf); eauto.\n  eapply TyLitC; eauto.\n  intros k HK.  \n  destruct (H1 k HK) as [n' [t' [HNth [HMap HWT]]]].\n  exists n'. exists t'.\n  repeat split; eauto.\n  + apply Heap.add_2; eauto.\n    destruct (Hwf (n+k)) as [ _ HIn ].\n    destruct HIn; try eexists; eauto.\n    omega.\n  + inv HWT; eauto.\nQed.\n\n\n  \nLemma heap_add_preserves_wf : forall D H n v, heap_wf D H ->\n  heap_wf D (Heap.add (Z.of_nat(Heap.cardinal H) + 1) (n, v) H).\nProof.\n  intros D H n v Hwf.\n  split; intros; simpl; eauto.\n  * rewrite cardinal_plus_one in H0.\n    - assert (Hyp: 0 < addr <= Z.of_nat(Heap.cardinal H) \\/ addr = Z.of_nat(Heap.cardinal H) + 1). {zify. omega. } \n      inv Hyp.\n      + destruct (Hwf addr) as [ HIn _ ].\n        specialize (HIn H1).\n        inv HIn. exists x.\n        apply Heap.add_2; eauto.\n        omega.\n      + eexists; eapply Heap.add_1; eauto.\n    - intros Contra.\n      destruct (Hwf (Z.of_nat(Heap.cardinal H) + 1)) as [? ?].\n      specialize (H2 Contra).\n      omega.\n  * apply HeapFacts.add_in_iff in H0.\n    inv H0.\n    - rewrite cardinal_plus_one; try (zify; omega).\n      intro Contra.\n      destruct (Hwf (Z.of_nat(Heap.cardinal H) + 1)) as [? ?].\n      specialize (H1 Contra).\n      omega.\n    - rewrite cardinal_plus_one.\n      + destruct (Hwf addr) as [_ H2]; specialize (H2 H1); zify; omega.\n      + intro Contra.\n        destruct (Hwf (Z.of_nat(Heap.cardinal H) + 1)) as [H2 H3].\n        specialize (H3 Contra).\n        omega.\nQed.\n\nLemma backwards_consistency :\n  forall D H' H v,\n    @heap_consistent D H' (Heap.add (Z.of_nat(Heap.cardinal H) + 1) v H) ->\n    heap_wf D H ->\n    @heap_consistent D H' H.\nProof.\n  intros D H' H v HC Hwf.\n  intros n t HWT.\n  eapply HC; eauto.\n  induction HWT using well_typed_lit_ind'; pose proof (cardinal_not_in D H Hwf); eauto.\n  eapply TyLitC; eauto.\n  intros k HK.\n  destruct (H1 k HK) as [n' [t' [HN [HM HW]]]].\n  exists n'. exists t'.\n  repeat split; eauto.\n  - apply Heap.add_2; eauto.\n    intro Contra.\n    destruct (Hwf (n + k)) as [ _ Hyp ].\n    destruct Hyp; [eexists; eauto | omega].\n  - inv HW; eauto.\nQed.\n      \nLemma fold_preserves_consistency : forall l D H ptr, heap_wf D H ->\n  let (_, H') :=\n      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))\n        l\n        (Z.of_nat(Heap.cardinal H), H) in\n  Some ((Z.of_nat(Heap.cardinal H) + 1), H') = Some (ptr, H') ->\n  @heap_consistent D H' H.\nProof.\n  intro l; induction l; intros; simpl; eauto.\n  assert (Hwf : heap_wf D (Heap.add (Z.of_nat(Heap.cardinal H) + 1) (0, a) H))\n    by (apply heap_add_preserves_wf; auto).\n  specialize (IHl D (Heap.add (Z.of_nat(Heap.cardinal H) + 1) (0, a) H) (ptr + 1) Hwf).\n  remember (Heap.add (Z.of_nat(Heap.cardinal H) + 1) (0, a) H) as H1.\n\n  \n  Set Printing All.\n  remember ((fun (acc : prod Z heap) (t : type) =>\n             match acc return (prod Z heap) with\n             | pair sizeAcc heapAcc =>\n                 @pair Z (Heap.t (prod Z type)) (sizeAcc + 1)\n                   (@Heap.add (prod Z type) (sizeAcc + 1) \n                      (@pair Z type 0 t) heapAcc)\n             end)) as fold_fun.\n  Unset Printing All.\n  clear Heqfold_fun. \n  assert (Z.of_nat(Heap.cardinal H1) = (Z.of_nat(Heap.cardinal H) + 1)).\n  {\n    subst; apply cardinal_plus_one; eauto.\n    intro Contra. \n    destruct (H0 (Z.of_nat(Heap.cardinal H) + 1)) as [H1 H2].\n    specialize (H2 Contra).\n    omega.\n  } \n  rewrite H2 in IHl.\n\n  assert (HEq:\n      (  fold_left fold_fun l\n            (@pair Z heap (Z.of_nat(Heap.cardinal H) + 1) H1) ) =\n      (    @fold_left (prod Z heap) type fold_fun l\n                      (@pair Z (Heap.t (prod Z type)) (Z.of_nat(Heap.cardinal H) + 1) H1))\n    ). {zify. eauto. }\n\n\n  rewrite HEq in IHl.\n\n\n  match goal with\n  | |- (match ?X with _ => _ end) => destruct X\n  end.\n  intro Hyp.\n  inv Hyp.\n   \n  assert (Z.of_nat(Heap.cardinal H) + 1 + 1 = Z.of_nat((Heap.cardinal H + 1)) + 1) by (zify; omega).\n  rewrite H1 in IHl.\n\n  specialize (IHl eq_refl).\n\n\n  eapply backwards_consistency; eauto.\nQed.\n\n\n  \n(* This could probably be merged with the previous one *)\nLemma fold_summary : forall l D H ptr,\n  heap_wf D H ->\n  let (_, H') :=\n      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))\n        l\n        (Z.of_nat(Heap.cardinal  H), H) in\n  Some (Z.of_nat(Heap.cardinal  H)+ 1, H') = Some (ptr, H') ->\n  heap_wf D H' /\\\n  ptr = Z.of_nat(Heap.cardinal  H) + 1 /\\\n  (Heap.cardinal  H') = ((Heap.cardinal H) + length l)%nat /\\\n  (forall (k : nat) v,\n      (0 <= k < (length l))%nat -> nth_error l k = Some v ->\n               Heap.MapsTo (Z.of_nat(Heap.cardinal  H) + 1 + Z.of_nat(k)) (0,v) H') /\\\n  forall x v, Heap.MapsTo x v H -> Heap.MapsTo x v H'.                                               \nProof.\n  intro l; induction l; simpl; intros D H ptr Hwf.\n  - intros Eq. inv Eq; repeat (split; eauto).\n    intros k v Contra _.\n    inv Contra.\n    inv H1.\n  - remember \n      (fun (acc : prod Z heap) (t : type) =>\n         match acc return (prod Z heap) with\n         | pair sizeAcc heapAcc =>\n           @pair Z (Heap.t (prod Z type)) (sizeAcc + 1)\n                 (@Heap.add (prod Z type) (sizeAcc + 1)\n                            (@pair Z type 0 t) heapAcc)\n         end) as fold_fun.\n    clear Heqfold_fun.\n\n    assert (Hwf' : heap_wf D (Heap.add (Z.of_nat(Heap.cardinal H) + 1) (0, a) H))\n      by (apply heap_add_preserves_wf; eauto).\n    specialize (IHl D (Heap.add (Z.of_nat(Heap.cardinal H) + 1) (0, a) H) (ptr + 1) Hwf').\n\n    \n    remember (Heap.add (Z.of_nat(Heap.cardinal H) +1) (0, a) H) as H1.\n\n    assert (Z.of_nat(Heap.cardinal H1) = Z.of_nat(Heap.cardinal H) + 1).\n    {\n      subst; apply cardinal_plus_one; eauto.\n      intro Contra.\n      destruct (Hwf (Z.of_nat(Heap.cardinal H) + 1)) as [H1 H2].\n      specialize (H2 Contra).\n      omega.\n    } \n    rewrite H0 in IHl.\n\n    assert (HEq:\n        (  @fold_left (prod Z heap) type fold_fun l\n              (@pair Z heap ((Z.of_nat(@Heap.cardinal (prod Z type) H)) + 1) H1) ) =\n        (    @fold_left (prod Z heap) type fold_fun l\n                        (@pair Z (Heap.t (prod Z type)) (Z.of_nat(@Heap.cardinal (prod Z type) H) + 1) H1))\n      ) by auto.\n   \n    rewrite HEq in IHl.\n\n  Set Printing All.\n\n  remember (\n    @fold_left (prod Z heap) type fold_fun l\n               (@pair Z (Heap.t (prod Z type)) ( Z.of_nat(@Heap.cardinal (prod Z type) H) + 1) H1)\n    ) as fold_call.\n\n  Unset Printing All.\n\n  clear Heqfold_call.\n  destruct fold_call.\n  intro Hyp.\n  inv Hyp.\n\n  assert (Z.of_nat(Heap.cardinal H) + 1 + 1 = ((Z.of_nat(Heap.cardinal H)) + 1) + 1) by omega.\n  (*rewrite H1 in IHl.*)\n  destruct (IHl eq_refl) as [hwf [Card [Card' [HField HMap]]]].\n\n  repeat (split; eauto).\n  + omega.\n  + intros k v Hk HF.\n    destruct k.\n    * simpl in *.\n      inv HF.\n      specialize (HMap (Z.of_nat(Heap.cardinal H) + 1) (0,v)).\n      rewrite Z.add_0_r.\n      eapply HMap.\n      apply Heap.add_1; eauto.\n    * simpl in *.\n      assert (HS: (Z.of_nat(Heap.cardinal H) + 1 + Z.pos (Pos.of_succ_nat k)) = (Z.of_nat(Heap.cardinal H) + 1 + 1 + Z.of_nat(k))). {\n      zify. omega. }\n      rewrite HS.\n      apply HField; eauto.\n      omega.\n  + intros x v HM.\n    eapply HMap.\n    apply Heap.add_2; eauto.\n    intro Contra.\n    destruct (Hwf x) as [_ Contra'].\n    destruct Contra'; [eexists; eauto | ].\n    omega.\nQed.\n\nPrint length_nth.\n\nLemma Zlength_nth : forall {A} (l : list A) (z : Z),\n0 <= z < Z.of_nat(length l) -> exists n, nth_error l (Z.to_nat z) = Some n.\nProof.\nintros. destruct z.\n  -apply (length_nth l (Z.to_nat 0) H).\n  -assert (H1: Z.of_nat (Z.to_nat (Z.pos p)) = (Z.pos p)).\n    {destruct (Z.pos p) eqn:P; inv P.\n      +simpl. rewrite positive_nat_Z. reflexivity. }\n   rewrite <- H1 in H. apply (length_nth l (Z.to_nat (Z.pos p)) H).\n  -exfalso. inv H. apply H0. simpl. reflexivity.\nQed.\n\nLemma alloc_correct : forall w D env H ptr H',\n    allocate D H w = Some (ptr, H') ->\n    structdef_wf D ->\n    heap_wf D H ->\n    @heap_consistent D H' H /\\\n    @well_typed D H' env Checked (ELit ptr (TPtr Checked w)) (TPtr Checked w) /\\\n    heap_wf D H'.\nProof.\n  intros w D env H ptr H' Alloc HSd HWf.\n  unfold allocate in *.\n  unfold allocate_meta in *.\n  unfold bind in *; simpl in *.\n  destruct w; simpl in *; eauto; inv Alloc; simpl in *; eauto.\n  - split; [| split].\n    * apply well_typed_preserved; eauto.\n    * apply TyLit; eauto.\n      eapply TyLitC; simpl; eauto.\n      intros k HK.\n      simpl in HK.\n      assert (k = 0) by omega; subst; clear HK.\n      exists 0. exists TNat.\n      repeat split; eauto.\n      apply Heap.add_1; eauto. omega.\n    * apply heap_add_preserves_wf; auto.\n  - split; [ | split].\n    * apply well_typed_preserved; eauto.\n    * apply TyLit; eauto.\n      eapply TyLitC; simpl; eauto.\n      intros k HK.\n      simpl in HK.\n      assert (k = 0) by omega; subst; clear HK.\n      exists 0. exists (TPtr m w).\n      repeat split; eauto.\n      apply Heap.add_1; eauto. omega.\n    * apply heap_add_preserves_wf; auto.\n  - split.\n\n    *unfold allocate in H1.\n      unfold allocate_meta_no_bounds, allocate_meta in H1.\n      destruct (StructDef.find s D) eqn:Find; simpl in *; try congruence.\n\n      remember (Fields.elements f) as l.\n\n      pose proof (fold_preserves_consistency (map snd l) D H ptr HWf).\n      \n      remember (fold_left\n            (fun (acc : Z * heap) (t : type) =>\n             let (sizeAcc, heapAcc) := acc in (sizeAcc + 1, Heap.add (sizeAcc + 1) (0, t) heapAcc))\n            (map snd l) (Z.of_nat(Heap.cardinal H), H)) as p.\n      \n      destruct p.\n      clear Heqp.      \n      inv H1.\n      eauto.\n    \n    * unfold allocate_meta_no_bounds, allocate_meta in H1.\n\n      simpl in *.\n      destruct (StructDef.find s D) eqn:Find; try congruence.\n\n      pose proof (fold_summary (map snd (Fields.elements f)) D H ptr HWf) as Hyp.\n\n      remember\n        (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))\n           (map snd (Fields.elements (elt:=type) f))\n           (Z.of_nat(Heap.cardinal H), H)) as p.\n      destruct p as [z h].\n      clear Heqp.\n      inv H1.\n\n      destruct Hyp as [H'wf  [Card1 [Card2 [HF HM]]]]; eauto.\n\n      split; auto.\n      constructor.\n      eapply TyLitC; simpl in *; eauto; [ rewrite Find | ]; eauto.\n\n      intros k HK.\n      apply StructDef.find_2 in Find.\n      remember Find as Fwf; clear HeqFwf.\n      apply HSd in Fwf.\n\n      assert (HOrd: 0 < Z.of_nat(Heap.cardinal H) + 1 + k <= Z.of_nat(Heap.cardinal H')) by omega.\n      pose proof (H'wf (Z.of_nat(Heap.cardinal H) + 1 + k)) as Hyp.\n      apply Hyp in HOrd.\n      destruct HOrd as [[n' t'] HM'].\n      (*This bit is very annoying, quite a bit of converting back and forth\n        between ints and nats. This could definately be more automated DP*)\n      exists n'. exists t'.\n      rewrite Z.sub_0_r in *.\n      destruct (Zlength_nth (map snd (Fields.elements f)) k HK) as [x Hnth].\n      assert (HK': (0 <= (Z.to_nat k) < (length (map snd (Fields.elements (elt:=type) f))))%nat). {\n        destruct k.\n          +zify. simpl. assumption.\n          +simpl. zify. omega.\n          +exfalso. inv HK. apply H0. simpl. reflexivity. }\n      specialize (HF (Z.to_nat k) x HK' Hnth).\n      assert (K0 : k = Z.of_nat (Z.to_nat k)). {\n      destruct k.\n        +simpl. reflexivity.\n        +simpl. zify. reflexivity.\n        +inv HK. exfalso. apply H0. simpl. reflexivity. }\n      rewrite <- K0 in HF.\n      pose proof (HeapFacts.MapsTo_fun HM' HF) as Eq.\n      inv Eq.\n      repeat (split; eauto).\n  - split.\n    * unfold allocate in H1.\n      unfold allocate_meta_no_bounds, allocate_meta in H1.\n      simpl in H1.\n\n      remember (Zreplicate (z0 - z) w) as l.\n      pose proof (fold_preserves_consistency l D H ptr HWf) as H0.\n\n      remember (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))\n         l\n         (Z.of_nat (Heap.cardinal (elt:=Z * type) H), H)) as p.\n      \n      destruct p as (n1, h). (*n0 already used???*)\n      clear Heqp.\n      destruct z; inv H1.\n      apply H0; eauto.\n    * unfold allocate in H1.\n      unfold allocate_meta_no_bounds, allocate_meta in H1.\n      simpl in *.\n\n      remember (Zreplicate (z0 - z) w) as l.\n\n      pose proof (fold_summary l D H ptr HWf) as Hyp.\n      remember\n        (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)) l\n          (Z.of_nat (Heap.cardinal (elt:=Z * type) H), H)) as p.\n      destruct p.\n      clear Heqp.\n      inv H1.\n\n      destruct z; inv H2; eauto.\n      destruct Hyp as [H'wf  [Card1 [Card2 [HF HM]]]]; eauto.\n\n      \n      split; auto.\n      constructor.\n      eapply TyLitC; simpl in *; eauto.\n      intros k HK.\n      simpl in *.\n      pose proof (H'wf (Z.of_nat(Heap.cardinal H) + 1 + k)) as Hyp.\n      rewrite Z.sub_0_r in *.\n\n      remember (Heap.cardinal H ) as c.\n      remember (Heap.cardinal H') as c'.\n      \n      assert (HOrd : 0 < Z.of_nat c + 1 + k <= Z.of_nat c')\n        by (zify; omega).\n      \n      destruct Hyp as [HIn Useless].\n      destruct (HIn HOrd) as [[n' t'] HM'].\n\n      destruct HK as [HP1 HP2].\n\n      destruct z0 as [ | p | ?]; simpl in *; [ omega | | omega].\n      rewrite replicate_length in *.\n\n      destruct (length_nth (replicate (Pos.to_nat p) w) (Z.to_nat k)) as [t Hnth].\n      { rewrite replicate_length ; zify; split; try omega. \n        (*This should go through with omega but it doesn't*)\n        assert (Hk : Z.of_nat (Z.to_nat k) = k). {\n        destruct k; simpl.\n          + reflexivity.\n          + zify. omega.\n          + exfalso. zify. apply HP1. simpl. reflexivity. }\n        rewrite Hk. assumption.\n      }\n\n      rewrite Z.sub_0_r in *.\n      \n      rewrite Hnth.\n      remember Hnth as Hyp; clear HeqHyp.\n      apply replicate_nth in Hnth. rewrite Hnth in *; clear Hnth.\n        \n      exists n'; exists t.\n      split; [ reflexivity | ].\n\n      specialize (HF (Z.to_nat k) t).\n      assert (HF1 : (0 <= Z.to_nat k < Pos.to_nat p)%nat). {\n        split; zify; (try omega). destruct k; simpl; zify; omega.\n      }\n\n      specialize (HF HF1 Hyp).\n\n      assert (HId: Z.of_nat (Z.to_nat k) = k). {\n        destruct k; simpl.\n          + reflexivity.\n          + zify. omega.\n          + exfalso. zify. omega. }\n      rewrite HId in HF.\n      \n      pose proof (HeapFacts.MapsTo_fun HM' HF) as Eq.\n      inv Eq.\n      split; auto.\nQed.\n\nLemma values_are_nf : forall D H e,\n    value D e ->\n    ~ exists H' m r, @reduce D H e m H' r.\nProof.\n  intros D H e Hv contra.\n  inv Hv.\n  destruct contra as [H' [ m [ r contra ] ] ].\n  inv contra; destruct E; inversion H4; simpl in *; subst; try congruence.\nQed.\n\nLemma lit_are_nf : forall D H n t,\n    ~ exists H' m r, @reduce D H (ELit n t) m H' r.\nProof.\n  intros D H n t contra.\n  destruct contra as [H' [ m [ r contra ] ] ].\n  inv contra; destruct E; inversion H2; simpl in *; subst; try congruence.\nQed.\n\nLemma var_is_nf : forall D H x,\n    ~ exists H' m r, @reduce D H (EVar x) m H' r.\nProof.\n  intros.\n  intros contra.\n  destruct contra as [H' [ m [ r contra ] ] ].\n  inv contra; destruct E; inversion H1; simpl in *; subst; inv H2.\nQed.\n\n\nLtac maps_to_fun :=\n  match goal with\n  | [ H1 : Heap.MapsTo ?X (?V1, ?T1) ?H \n    , H2 : Heap.MapsTo ?X (?V2, ?T2) ?H\n      |- _ ] =>\n    let H := fresh \"Eq\" in     \n    assert (H : (V1,T1) = (V2, T2)) by (eapply HeapFacts.MapsTo_fun; eauto);\n    inv H\n  | _ => idtac\n  end.\n\nLtac solve_map :=\n  match goal with\n  | [ |- Heap.MapsTo ?x ?T (Heap.add ?x ?T _) ] => apply Heap.add_1; auto\n  | _ => idtac\n  end.\n\n\n(*\nLemma HeapUpd:\n  Suppose H(i) = n^T and G |- n'^T' : T' under heap H.\n  If H' = H[i |--> k^T] and G |- k^T : T under H' then G |- n'^T' under heap H'\n  (In short: H' |- H)\nProof.\n  The proof is by induction on G |- n'^T' : T' under H.\n  Case T-Int and T-VConst apply as before\n  Case T-PtrC\n    G |- n'^(ptr^c W) under H\n    where\n      types(D,W) = T0,...,T(j-1)\n      G,n'^(ptr^c W) |-m H(n'+x) : Tx for 0 <= x < j under H\n    We want to prove\n      G,n'^(ptr^c W) |-m H'(n'+x) : Tx for 0 <= x < j under H'\n    Two cases\n      n'+x == i: So H'(i) = k^T and we are given G |- k^T under H'. Follows by weakening\n      n'+x != i. So H'(i) = H(i) and the result follows by induction.\n *)\n\nDefinition set_equal (s1 s2 : scope) :=\n  forall x, set_In x s1 <-> set_In x s2.\n\nLemma set_equal_add (s1 s2 : scope) (v : Z * type) :\n  set_equal s1 s2 -> \n  set_equal (set_add eq_dec_nt v s1) (set_add eq_dec_nt v s2).\nProof.  \n  intros Eq x.\n  split; intros.\n  - destruct (eq_dec_nt x v).\n    + subst; apply set_add_intro2; auto.\n    + apply set_add_intro1; auto.\n      apply set_add_elim2 in H; eauto.\n      apply Eq; auto.\n  - destruct (eq_dec_nt x v).\n    + subst; apply set_add_intro2; auto.\n    + apply set_add_intro1; auto.\n      apply set_add_elim2 in H; eauto.\n      apply Eq; auto.\nQed.      \n\nLemma scope_replacement :\n  forall D H s n t,\n    @well_typed_lit D H s n t ->\n  (forall s', \n    set_equal s s' ->\n    @well_typed_lit D H s' n t).\nProof.\n  intros D H ss n t HWT.\n  induction HWT using well_typed_lit_ind'; eauto.\n  - (* Replacement, TyRec *)\n    intros s' HEq.\n    constructor; apply HEq; auto.\n  - (* Replacement, TyLitC *)\n    intros s' Heq.\n    eapply TyLitC; eauto.\n    intros k Hk.\n    destruct (H1 k Hk) as [n' [t' [HNth [HMap [HWt1 HRepl]]]]].\n    exists n'. exists t'.\n    repeat (split; eauto).\n    eapply HRepl; eauto.\n    apply set_equal_add; auto.\nQed.\n\nLemma set_equal_add_add (s1 s2 : scope) (v1 v2 : Z * type) :\n  set_equal s1 s2 -> \n  set_equal (set_add eq_dec_nt v1 (set_add eq_dec_nt v2 s1))\n            (set_add eq_dec_nt v2 (set_add eq_dec_nt v1 s1)).\nProof.  \n  intros Eq x.\n  split; intros;\n    destruct (eq_dec_nt x v1); destruct (eq_dec_nt x v2); subst;\n      try solve [apply set_add_intro2; auto];\n      try solve [apply set_add_intro1; auto;\n                 apply set_add_intro2; auto];\n    (do 2 (apply set_add_intro1; auto);\n     do 2 (apply set_add_elim2 in H; auto)).\nQed.\n\nLemma set_equal_refl (s : scope) : set_equal s s.\n  intros x; split; auto.\nQed.\n\nLemma scope_weakening :\n  forall D H s n t,\n    @well_typed_lit D H s n t ->\n  forall x,\n    @well_typed_lit D H (set_add eq_dec_nt x s) n t.\nProof.\n  intros D H ss n t HWT.\n  induction HWT using well_typed_lit_ind'; eauto.\n  - (* Weakening, TyRec *)\n    intros x.\n    constructor.\n    apply set_add_intro1; auto.\n  - (* Weakening, TyLitC *)\n    intros x.\n    eapply TyLitC; eauto.\n    intros k Hk.\n    destruct (H1 k Hk) as [n' [t' [HNth [HMap [HWt1 HWeak]]]]].\n    exists n'. exists t'.\n    repeat (split; eauto).\n    eapply scope_replacement; [eapply HWeak; eauto |].\n    eapply set_equal_add_add; eauto.\n    eapply set_equal_refl; eauto.\nQed.\n\nLemma set_equal_add_cons :\n  forall x y s,\n      set_equal (x :: set_add eq_dec_nt y s)\n                (set_add eq_dec_nt y (x :: s)).\n  intros x y s z; split; intros H;\n  destruct (eq_dec_nt z y); destruct (eq_dec_nt z x);\n    subst; try congruence.\n  - apply set_add_intro2; auto.\n  - apply set_add_intro2; auto.\n  - apply set_add_intro1; left; auto.\n  - inv H; try congruence.\n    apply set_add_elim in H0.\n    inv H0; try congruence.\n    apply set_add_intro1; auto.\n    right; auto.\n  - left; auto. \n  - right; apply set_add_intro2; auto.\n  - left; auto.\n  - apply set_add_elim in H.\n    inv H; try congruence.\n    inv H0; try congruence.\n    right; apply set_add_intro1; auto.\nQed.\n\nLemma scope_weakening_cons :\n  forall D H n t s,\n    @well_typed_lit D H s n t ->\n  forall x, @well_typed_lit D H (x :: s) n t.\nProof.\n  intros D H n t s HWT.\n  induction HWT using well_typed_lit_ind'; eauto; intros x.\n  - constructor.\n    right; auto.\n  - eapply TyLitC; eauto.\n    intros k Hk.\n    destruct (H1 k Hk) as [n' [t' [HNth [HMap [HWt1 HWeak]]]]].\n    exists n'. exists t'.\n    repeat (split; eauto).\n    eapply scope_replacement; [eapply (HWeak x); eauto |].\n    apply set_equal_add_cons.\nQed.\n\nCorollary scope_weakening' :\n  forall D H n t,\n    @well_typed_lit D H empty_scope n t ->\n  forall s, @well_typed_lit D H s n t.\nProof.  \n  intros D H n t HWT s.\n  induction s; auto.\n  apply scope_weakening_cons; auto.\nQed.  \n  \n  (*\nLemma scope_wf_heap_consistent_weakening :\n  forall s D H x v T v',\n    Heap.MapsTo x (v,T) H ->\n    scope_wf D H s -> scope_wf D (Heap.add x (v',T) H) s.\nProof.\n  intros s D H x v T v' HMap HSwf.\n  intros x' t' HS.\n  destruct (HSwf x' t'); eauto.\n  destruct (Nat.eq_dec x x').\n  - subst; maps_to_fun.\n    exists v'.\n    eapply Heap.add_1; eauto.\n  - exists x0.\n    eapply Heap.add_2; eauto.\nQed.\n\nHint Resolve scope_wf_heap_consistent_weakening.\n *)\n     \nLemma HeapUpd : forall D i n T H k,\n  Heap.MapsTo i (n,T) H ->\n  @well_typed_lit D (Heap.add i (k,T) H) empty_scope k T ->\n  @heap_consistent D (Heap.add i (k,T) H) H.\nProof.\n  intros D i n T H k HMap Hwtk n' t' HWT.\n  induction HWT using well_typed_lit_ind'; eauto.\n  (* T-PtrC *)\n  eapply TyLitC; eauto.\n  intros x Hx.\n  destruct (H1 x Hx) as [n' [t' [HNth [HMap' [HWt1 HWt2]]]]].\n  destruct (Z.eq_dec (n0+x) i).\n  - exists k. exists t'.\n    subst. maps_to_fun.\n    repeat (split; eauto).\n    + apply Heap.add_1; eauto.\n    + apply scope_weakening; eauto.\n  - exists n'. exists t'.\n    repeat (split; eauto).\n      + apply Heap.add_2; eauto.\n      + eapply HWt2.\n        eapply scope_weakening; eauto.\nQed.\n\nHint Constructors value.\n\nLemma types_are_not_infinite :\n  forall w, TPtr Checked w = w -> False.\nProof.\n  induction w; intros; try congruence.\nQed.\n\n(* Custom remove to avoid NoDup? *)\nFixpoint set_remove_all v (x : scope) := \n    match x with\n    | nil => empty_scope\n    | v' :: vs => if eq_dec_nt v v' then\n                    set_remove_all v vs\n                  else\n                    v' :: set_remove_all v vs\n    end.\n\nLemma set_remove_all_intro : forall a b l,\n    set_In a l -> a <> b -> set_In a (set_remove_all b l).\nProof.\n  intros a b l.\n  induction l; intros; simpl.\n  - inv H.\n  - destruct (eq_dec_nt b a0).\n    + subst.\n      inv H; try congruence.\n      eapply IHl; eauto.\n    + destruct (eq_dec_nt a a0).\n      * subst; left; auto.\n      * inv H; try congruence.\n        simpl.\n        right.\n        eauto.\nQed.\n\nLemma set_remove_all_elim1:\n  forall a b l, set_In a (set_remove_all b l) -> a <> b.\nProof.  \n  intros; induction l.\n  - inv H.\n  - intro Contra; subst.\n    simpl in H.\n    destruct (eq_dec_nt b a0).\n    + subst.\n      apply IHl; eauto.\n    + simpl in *.\n      inv H; try congruence.\n      eapply IHl; eauto.\nQed.\n\nLemma set_remove_all_elim2:\n  forall a b l, set_In a (set_remove_all b l) -> set_In a l.\nProof.\n  intros; induction l.\n  - inv H.\n  - simpl in H.\n    destruct (eq_dec_nt b a0).\n    + subst.\n      right; apply IHl; eauto.\n    + simpl in *.\n      inv H.\n      * left; auto.\n      * right; eapply IHl; eauto.\nQed.\n  \nLemma set_equal_add_remove (s : scope) (v1 v2 : Z * type) :\n  v1 <> v2 ->\n  set_equal (set_add eq_dec_nt v1 (set_remove_all v2 s))\n            (set_remove_all v2 (set_add eq_dec_nt v1 s)).\nProof.\n  intros H x.\n  split; intro In.\n  * destruct (eq_dec_nt x v1); destruct (eq_dec_nt x v2); try congruence; subst;\n      unfold not in *.\n    - apply set_remove_all_intro; eauto.\n      apply set_add_intro2; auto.\n    - apply set_add_elim in In; destruct In; try congruence.\n      eapply set_remove_all_elim1 in H0.\n      congruence.\n    - apply set_remove_all_intro; eauto.\n      apply set_add_elim in In; destruct In; try congruence.\n      apply set_remove_all_elim2 in H0.\n      apply set_add_intro1; auto.\n  * destruct (eq_dec_nt x v1); destruct (eq_dec_nt x v2); try congruence; subst.\n    - apply set_add_intro2; auto.\n    - apply set_remove_all_elim1 in In.\n      try congruence.\n    - apply set_remove_all_elim2 in In.\n      apply set_add_elim in In.\n      inv In; try congruence.\n      apply set_add_intro1; auto.\n      apply set_remove_all_intro; eauto.\nQed.      \n\nDefinition type_eq_dec (t1 t2 : type): {t1 = t2} + {~ t1 = t2}.\n  repeat decide equality.\nDefined.\n\nLemma set_remove_add :\n  forall x s, set_equal (set_remove_all x (set_add eq_dec_nt x s)) (set_remove_all x s).\nProof.\n  intros x s y; split; intros H; destruct (eq_dec_nt x y); subst; eauto.\n  - apply set_remove_all_elim1 in H; congruence.\n  - apply set_remove_all_elim2 in H.\n    apply set_add_elim in H.\n    inv H; try congruence.\n    apply set_remove_all_intro; auto.\n  - apply set_remove_all_elim1 in H; congruence.\n  - apply set_remove_all_intro; auto.\n    apply set_remove_all_elim2 in H.\n    apply set_add_intro1; auto.\nQed.\n\nLemma set_equal_symmetry : forall (s1 s2 : scope),\n    set_equal s1 s2 -> set_equal s2 s1.\nProof.  \n  intros s1 s2 Eq x; split; intro H;\n  apply Eq; auto.\nQed.  \n  \nLemma scope_swap :\n  forall D H x y s N T,\n    @well_typed_lit D H (set_remove_all x (set_add eq_dec_nt y s)) N T ->\n    @well_typed_lit D H (set_add eq_dec_nt y (set_remove_all x s)) N T.\nProof.\n  intros D H x y s N T HWT.\n  destruct (eq_dec_nt x y).\n  - subst.\n    pose proof (set_remove_add y s).\n    apply scope_replacement with (s' := set_remove_all y s) in HWT; auto.\n    apply scope_weakening; auto.\n  - assert (Neq: y <> x) by auto.\n    pose proof (set_equal_add_remove s y x Neq) as Hyp.\n    eapply scope_replacement.\n    + eapply HWT.\n    + apply set_equal_symmetry.\n      auto.\nQed.\n\nLemma scope_strengthening :\n  forall D H n tn s,\n    @well_typed_lit D H s n tn ->\n    heap_wf D H ->\n    forall m tm,\n      @well_typed_lit D H empty_scope m tm ->\n      @well_typed_lit D H (set_remove_all (m, tm) s) n tn.\nProof.\n  intros D H n' t s HWT.\n  remember HWT as Backup; clear HeqBackup.\n  induction HWT using well_typed_lit_ind';\n  (* intros HHwf m HMap HSetIn HWT; eauto. *)\n    intros HHwf m tm Hwt; eauto.\n  - destruct (Z.eq_dec n m).\n    + subst.\n      destruct (type_eq_dec tm (TPtr Checked w)).\n      * subst.\n        apply scope_weakening'; auto.\n      * constructor.\n        apply set_remove_all_intro; auto.\n        intro Contra; inv Contra.\n        eauto.\n    + constructor.\n      apply set_remove_all_intro; auto.\n      congruence.\n  - eapply TyLitC; eauto.\n    intros k Hk.\n    destruct (H1 k Hk) as [N [T [HNth [HMap' [Hwt' IH]]]]].\n\n    exists N; exists T; eauto.\n    repeat (split; eauto).\n\n    specialize (IH Hwt' HHwf m tm Hwt).\n    apply scope_swap; auto.\nQed.\n\n\nLemma preservation_fieldaddr : forall (D : structdef) H n T (fs : fields),\n  @well_typed_lit D H empty_scope n (TPtr Checked (TStruct T)) ->\n  forall i fi ti,\n  n <> 0 ->\n  StructDef.MapsTo T fs D ->\n  Fields.MapsTo fi ti fs ->\n  nth_error (Fields.this fs) i = Some (fi, ti) ->\n  heap_wf D H ->\n  structdef_wf D ->\n  fields_wf D fs ->\n  word_type ti ->\n  @well_typed_lit D H empty_scope (n + (Z.of_nat i)) (TPtr Checked ti).\nProof.\n  intros D H n T fs HWT.\n  inversion HWT;\n  intros i fi ti Hn HS HF Hnth Hhwf HDwf Hfwf Hwt; eauto.\n  - exfalso ; eauto.\n  - destruct (H4  (Z.of_nat i)) as [N' [T' [HNth [HMap HWT']]]]; subst.\n    + simpl in H1.\n      destruct (StructDef.find T D) eqn:Find; try congruence.\n      inv H1.\n      rewrite map_length.\n      apply StructDef.find_2 in Find.\n      assert (f = fs).\n      { eapply StructDefFacts.MapsTo_fun; eauto. }\n      subst.\n      apply nth_length in Hnth.\n      rewrite <- Fields.cardinal_1.\n      eauto.\n    + simpl in *.\n      destruct (@StructDef.find _ T D) eqn:Find; try congruence.\n      inv H1.\n\n      apply StructDef.find_2 in Find.\n      assert (f = fs).\n      { eapply StructDefFacts.MapsTo_fun; eauto. }\n      subst.\n\n      eapply map_nth_error with (f := snd) in Hnth.\n      assert (Hyp: Fields.this fs = Fields.elements fs) by auto.\n      rewrite Hyp in Hnth.\n\n      (* I hate these types... *)\n      assert (\n          Hnth' : @eq (option type)\n                      (@nth_error type\n              (@map (prod Fields.key type) type (@snd Fields.key type)\n                 (@Fields.elements type fs)) i)\n           (@Some type (@snd nat type (@pair Fields.key type fi ti)))\n        ) by auto.\n      assert (Hi : (Z.to_nat (Z.of_nat i)) = i). {\n        destruct i.\n          +simpl. reflexivity.\n          +simpl. zify. omega. }\n      simpl in *.\n      rewrite Z.sub_0_r in *. rewrite Hi in HNth.\n      rewrite <- HNth in Hnth'.\n      inv Hnth'.\n      inv Hwt.\n      * eapply TyLitC; simpl in *; eauto.\n        intros k Hk; simpl in *.\n        assert (k = 0) by omega; subst.\n        exists N'. exists TNat.\n        repeat (split; eauto).\n        rewrite Z.add_0_r; eauto.\n      * eapply TyLitC; simpl in *; eauto.\n        intros k Hk; simpl in *.\n        assert (k = 0) by omega; subst.\n        exists N'. exists (TPtr m w).\n        repeat (split; eauto).\n        rewrite Z.add_0_r; eauto.\n\n        assert (HEmpty : empty_scope = set_remove_all (n, TPtr Checked (TStruct T))\n                                             ((n, TPtr Checked (TStruct T)) :: nil)).\n        { unfold set_remove_all.\n          destruct (eq_dec_nt (n, TPtr Checked (TStruct T)) (n, TPtr Checked (TStruct T))); auto.\n          congruence.\n        }\n\n        eapply scope_strengthening in HWT'; eauto.\n        rewrite <- HEmpty in HWT'.\n        apply scope_weakening_cons.\n        auto.\nQed.\n\n(*\n\nDef: H' |- H iff for all i\n  H(i) = n^T such that . |- n^T : T under H implies\n  H'(i) = n'^T such that . |- n'^T : T under H'.\n\nLemma PtrUpdA:\n  Suppose H(i) = n^T and G |- n'^T' : T' under heap H.\n  Then H' = H[i |--> k^T] implies that G,k^T |- n'^T' under heap H'\n    when T = ptr^c W (i.e., it's a checked pointer type)\nProof\n  Proof by induction on G |- n'^T' : T' under heap H.\n  Case T-Int: Then T'=int and G,k^T |- n'^int under heap H' by T-Int\n  Case T-VConst: Then G,k^T |- n'^T' under heap H' by T-VConst as well (since n'^T' \\in G)\n  Case T-PtrC: Three cases:\n    n'^T' = k^T. Follows from T-VConst\n    Otherwise\n      T' = ptr^c W'\n      types(D,W') = T0,...,T(j-1)\n      G,n'^(ptr^c W') |-m H(n'+x) : Tx for 0 <= x < j under H\n    We want to show\n      G,n'^(ptr^c W'),k^T |-m H(n'+x) : Tx for 0 <= x < j under H'\n    When n'+x != i then the result follows from T-Int, T-VConst, or T-PtrC and induction.\n    When n'+x = i it follows by H-Visited, since H'(i) = k^T and k^T \\in G,k^T\n      (and H(i) = n^T --- that is the old and new value had the same annotation)\n*)\n\nLemma PtrUpdA :\n  forall D H s n' T',\n    @well_typed_lit D H s n' T' ->\n    forall i k m w,\n      Heap.MapsTo i (m,TPtr Checked w) H ->\n      @well_typed_lit D (Heap.add i (k,TPtr Checked w) H) (set_add eq_dec_nt (k,TPtr Checked w) s) n' T'.\nProof.\n  intros D H s n' T' HWT'.\n  remember HWT' as Backup; clear HeqBackup.\n  induction HWT' using well_typed_lit_ind'; eauto;\n    intros i k m T HMap.\n  - constructor.\n    apply set_add_intro; auto.\n  - eapply TyLitC; eauto.\n    intros x Hx.\n    destruct (H1 x Hx) as [N' [T' [HNth [HMap' [HWT'' IH]]]]].\n    destruct (Z.eq_dec (n + x) i).\n    + subst.\n      maps_to_fun.\n      exists k; exists (TPtr Checked T); eauto.\n      repeat (split; eauto).\n      * apply Heap.add_1; auto.\n      * apply TyLitRec; auto.\n        apply set_add_intro1;\n        apply set_add_intro2; auto.\n    + exists N'; exists T'; eauto.\n      repeat (split; eauto).\n      * apply Heap.add_2; auto.\n      * eapply scope_replacement; eauto.\n        eapply set_equal_add_add; eauto.\n        eapply set_equal_refl.\nQed.\n\n        (*\nLemma A: If G |- n^T : T where T = Ptr^c W such that W is an array\nor word type, then G |- H(n) : T' where types(D,W) = T',...\nProof by induction on G |- n^T.\nWe have G,n^T |- H(n) : T' by inversion on H-PtrC. Consider the\nderivation of this, and let k^T' = H(n).\n  H-Int: Then G |- k^Int : Int as well\n  H-Visited: There are two cases:\n   k^T' \\in G: In that case G |- k^T' : T' by H-Visited\n   k^T' = n^T: In this case we can simply reuse the derivation we were\n   given, i.e., G |- n^T : T.\n H-PtrC: Holds by induction.\n\n\n\nCorollary PtrUpd:\n  Suppose H(i) = n^T and G |- n'^T : T under heap H.\n  Then H' = H[i |--> n'^T] implies that G |- n'^T under heap H'\nProof.\n  If T is not a checked pointer it follows directly (same logic is PtrUpdA)\n  Else by inversion we have\n      T = ptr^c W \n      types(D,W) = T0,...,T(j-1)\n      G,n'^(ptr^c W) |-m H(n'+k) : Tk for 0 <= k < j under H\n    We want to prove\n      G,n'^(ptr^c W) |-m H'(n'+k) : Tk for 0 <= k < j under H'\n    Two cases\n      n'+k == i. Then H'(i) = n'^T. The result follows from T-VConst.\n      n'+k != i. Then H'(n'+k) = H(n'+k) = n''^Tk.\n        By Lemma A we have G |-m H(n'+k) : Tk for 0 <= k < j under H\n        By PtrUpdA we have G, n'^(ptr^c W) |-m H'(n'+k) : Tk for 0 <= k < j under H'\n\n *)\n\n\nLemma PtrUpd : forall i n T H D n',\n    heap_wf D H ->\n    Heap.MapsTo i (n, T) H ->\n    @well_typed_lit D H empty_scope n' T ->\n    @well_typed_lit D (Heap.add i (n',T) H) empty_scope n' T.\nProof.\n  intros i n T H D n' Hwf HMap HWT.\n  remember HWT as Backup; clear HeqBackup.\n  inv HWT; eauto.\n  eapply TyLitC; eauto.\n  intros x Hx.\n  destruct (H1 x Hx) as [x' [Tx [HNth [HMap' HWt1]]]].\n  destruct (Z.eq_dec (n'+x) i).\n  - subst.\n    maps_to_fun.\n    exists n'. exists (TPtr Checked w).\n    repeat (split; eauto).\n    + solve_map.\n    + eapply TyLitRec; eauto.\n      apply set_add_intro2; auto.\n  - exists x'. exists Tx.\n    repeat (split; eauto).\n    + eapply Heap.add_2; eauto.\n    + eapply PtrUpdA; eauto.\n\n      assert (HEmpty : empty_scope = set_remove_all (n', TPtr Checked w)\n                                                    ((n', TPtr Checked w) :: nil)).\n      {\n        unfold set_remove_all.\n        destruct (eq_dec_nt (n', TPtr Checked w) (n', TPtr Checked w)); auto.\n        congruence.\n      } \n\n      rewrite HEmpty.\n      eapply scope_strengthening; eauto.\nQed.\n\nLemma well_typed_heap_in : forall n D H w,\n  heap_wf D H ->\n  Heap.In n H ->\n  word_type w ->\n  @well_typed_lit D H empty_scope n (TPtr Checked w) ->\n  exists x, Heap.MapsTo n (x, w) H.\nProof.\n  intros n D H w Hwf HIn Hwt HWT.\n  inv HWT.\n  - destruct (Hwf 0) as [_ Contra].\n    apply Contra in HIn.\n    omega.\n  - inv H3.\n  - inv Hwt; simpl in *; inv H1.\n    + destruct (H4 0) as [n' [t' [HNth [HMap HWT]]]]; auto.\n      *simpl. omega.\n      *\n      rewrite Z.add_0_r in HMap.\n      inv HNth.\n      exists n'; eauto.\n    + destruct (H4 0) as [n' [t' [HNth [HMap HWT]]]]; auto.\n      *simpl. omega.\n      *rewrite Z.add_0_r in HMap.\n       inv HNth.\n       exists n'; eauto.\nQed.\n\nLemma well_typed_heap_in_array : forall n D H l h w,\n  heap_wf D H ->\n  Heap.In n H ->\n  h > 0 ->\n  l <= 0 ->\n  @well_typed_lit D H empty_scope n (TPtr Checked (TArray l h w)) ->\n  exists x, Heap.MapsTo n (x, w) H.\nProof.\n  intros n D H l h w Hwf HIn Hl Hh HWT.\n  inv HWT.\n  - destruct (Hwf 0) as [_ Contra].\n    apply Contra in HIn.\n    omega.\n  - inv H3.\n  - inv H1.\n    destruct l.\n    + destruct (H4 0) as [n' [t' [HNth [HMap HWT]]]]; auto.\n      * simpl. destruct h; inv Hl. simpl.\n        assert (Hyp : exists s, Pos.to_nat(p) = S s).\n        { apply pos_succ. }\n        inv Hyp.\n        rewrite replicate_length.\n        simpl. omega.\n      * rewrite Z.sub_0_r in *.\n        inv HNth.\n        exists n'; eauto.\n        assert (H3 : t' = w). {\n          destruct h; inv Hl. inv H1. \n          assert (HP: exists s, Pos.to_nat(p) = S s) by apply pos_succ.\n          inv HP.\n          rewrite H0 in H2. simpl in H2. inv H2. reflexivity.\n        }\n        rewrite <- H3. rewrite Z.add_0_r in *. assumption.\n    + zify; omega.\n    + assert (H1: (h - (Z.neg p)) > 0) by (zify; omega).\n      assert (H2: exists n, (h - (Z.neg p)) = Z.pos n). {\n        destruct (h - (Z.neg p)); inv H1. exists p0. reflexivity.\n      }\n      destruct H2 as [pos Hpos].\n      assert (Hpos': exists n, Pos.to_nat pos = S n) by apply pos_succ.\n      destruct Hpos' as [N HN].\n      destruct (H4 0) as [n' [t' [HNth [HMap HWT]]]]; auto.\n      rewrite Hpos. simpl. rewrite HN.\n      rewrite replicate_length.\n      simpl. split.\n        * zify. omega.\n        * rewrite Z.pos_sub_gt. \n          { zify. omega. }\n          { zify. omega. }\n        * rewrite Z.add_0_r in HMap.\n          rewrite Hpos in HNth. simpl in HNth.\n          rewrite HN in HNth. \n          assert (w = t').\n              {\n                eapply replicate_nth; eauto.\n              }\n              subst w.\n          exists n'. assumption.\nQed.\n\nLemma preservation : forall D H env e t H' e',\n    @structdef_wf D ->\n    heap_wf D H ->\n    expr_wf D e ->\n    @well_typed D H env Checked e t ->\n    @reduce D H e Checked H' (RExpr e') ->\n    @heap_consistent D H' H /\\ @well_typed D H' env Checked e' t.\nProof with eauto 20 with Preservation.\n  intros D H env e t H' e' HDwf HEwf HHwf Hwt.\n  generalize dependent H'. generalize dependent e'.\n  remember Checked as m.\n  induction Hwt as [\n                    env m n t HTyLit                                      | (* Literals *)\n                    env m x t HVarInEnv                                   | (* Variables *)\n                    env m x e1 t1 e2 t HTy1 IH1 HTy2 IH2                  | (* Let-Expr *)\n                    env m e m' T fs i fi ti HTy IH HWf1 HWf2              | (* Field Addr *)\n                    env m e1 e2 HTy1 IH1 HTy2 IH2                         | (* Addition *)\n                    env m w                                               | (* Malloc *)\n                    env m e t HTy IH                                      | (* Unchecked *)\n                    env m t e t' HChkPtr HTy IH                           | (* Cast *)\n                    env m e m' w l h t HTy IH HPtrType HMode                | (* Deref *)\n                    env m e1 m' l h t e2 WT Twf HTy1 IH1 HTy2 IH2 HMode            | (* Index *)\n                    |\n                    ]; intros e' H' Hreduces; subst.\n  (* T-Lit, impossible because values do not step *)\n  - exfalso. eapply lit_are_nf...\n  (* T-Var *)\n  - exfalso. eapply var_is_nf...\n  (* T-Let *)\n  - inv Hreduces.\n    destruct E; inversion H1; simpl in *; subst.\n    + clear H0. clear H7. rename e'0 into e'.\n      inv H4... (* Uses substitution lemma *)\n    + clear H1. edestruct IH1... (* Uses heap_wf *)\n      inv HHwf; eauto.\n  (* T-FieldAddr *)\n  - inv Hreduces.\n    destruct E; inversion H2; simpl in *; subst.\n    + clear H0. clear H8. inv H5.\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. clear H8.\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    + subst.\n      clear IH.\n      inv H5.\n      split; eauto.\n      destruct HPtrType as [[Hw Eq] | Hw]; subst.\n      * { inv HTy.\n          remember H7 as Backup; clear HeqBackup.\n          inv H7.\n          - exfalso.\n            eapply heap_wf_maps_nonzero; eauto.\n          - inversion H4.\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              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          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 H2.\n          - simpl in H0. subst.\n            destruct Hw as [? [? ?]]; subst.\n            inv H0; simpl in *.\n            destruct l.\n              *destruct h.\n                 { exfalso.\n                 assert (Hf : 0 > 0). {apply (H11 0 0 t). reflexivity. }\n                 omega. }\n                { assert (H4 : exists x, Pos.to_nat p = S x) by apply pos_succ.\n                  destruct (H3 0) as [N [T' [HT' [HM' HWT']]]]; [ simpl; inv H4; rewrite H; simpl; zify; omega | ].\n                  inv HT'.  rewrite Z.add_0_r in HM'.\n                  maps_to_fun. inv H4. rewrite H in H0. inv H0.\n                  constructor.\n                  assert (Hyp: set_remove_all (n, TPtr Checked (TArray 0 (Z.pos p) t))\n                                        ((n,TPtr Checked (TArray 0 (Z.pos p) t))::nil) = empty_scope).\n                    { \n                      destruct (eq_dec_nt (n, TPtr Checked (TArray 0 (Z.pos p) t))\n                                    (n, TPtr Checked (TArray 0 (Z.pos p) 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                { exfalso.\n                 assert (Hf : Z.neg p > 0). {apply (H11 0 (Z.neg p) t). reflexivity. }\n                 zify. omega. }\n              *exfalso.\n                 assert (Hf : Z.pos p <= 0). {apply (H11 (Z.pos p) h t). reflexivity. }\n                 zify. omega.\n              *destruct h.\n               { exfalso.\n                 assert (Hf : 0 > 0).\n                 { apply (H11 (Z.neg p) 0 t). reflexivity. }\n                 omega.\n               }\n               { assert (Hgt : Z.pos p0 - Z.neg p > 0).\n                 { zify. omega. }\n                 assert (Hpos : exists x, Z.pos x = Z.pos p0 - Z.neg p ).\n                 { destruct (Z.pos p0 - Z.neg p). zify. omega.\n                   exists p1. reflexivity. zify. omega.\n                 }\n                 destruct (H3 0) as [N [T' [HT' [HM' HWT']]]]; [ | ].\n                 + destruct Hpos.\n                   assert (exists n, Pos.to_nat x = S n) by apply pos_succ. destruct H0.\n                   rewrite <- H. simpl. rewrite H0. simpl. zify.\n                   rewrite replicate_length.\n                   rewrite Z.pos_sub_gt.\n                   { zify; omega. } \n                   zify; omega.\n                 + destruct Hpos as [x Hx].\n                   rewrite <- Hx in HT'. simpl in HT'. \n\n                   rewrite Z.add_0_r in HM'.\n\n                   assert (t = T').\n                   { \n                     eapply replicate_nth; eauto.\n                   } \n                   subst T'.\n\n                   maps_to_fun.\n                   constructor.\n                   assert (Hyp: set_remove_all (n, TPtr Checked (TArray (Z.neg p) (Z.pos p0) t))\n                                        ((n,TPtr Checked (TArray (Z.neg p) (Z.pos p0) t))::nil) = empty_scope).\n                        { \n                          destruct (eq_dec_nt (n, TPtr Checked (TArray (Z.neg p) (Z.pos p0) t))\n                                        (n, TPtr Checked (TArray (Z.neg p) (Z.pos p0) 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                { exfalso.\n                 assert (Hf : Z.neg p > 0). {apply (H11 (Z.neg p) (Z.neg p0) t). reflexivity. }\n                 zify. omega. }\n        }\n    + subst.\n      destruct (IH (in_hole e'0 c) H') as [HC HWT]; eauto. \n  - inv HHwf.\n\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: h - n2 - (l - n2) = h - l) by omega.\n            rewrite Hyp in * ; clear Hyp.\n            \n            destruct (H6 (n2 + k)) as [n' [t' [HNth [HMap HWT]]]]; [omega | ].\n\n            exists n'. exists t'.\n\n            rewrite Z.add_assoc in HMap.\n\n            split; [ | split]; auto.\n            + destruct (h - l) eqn:HHL; simpl in *.\n              * rewrite Z.add_0_r in Hk.\n                destruct (Z.to_nat (n2 + k - l)); inv HNth.\n              * assert (HR: k - (l - n2) = n2 + k - l) by (zify; omega).\n                rewrite HR.\n                auto.\n              * destruct (Z.to_nat (n2 + k - l)); 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 l h t))\n                                     empty_scope =\n                             (n1, TPtr Checked (TArray l h 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 l h t)) \n                                             ((n1, TPtr Checked (TArray l h t)) :: nil)).\n              {\n                unfold set_remove_all.\n                destruct (eq_dec_nt (n1, TPtr Checked (TArray l h t))\n                                    (n1, TPtr Checked (TArray l h t))); auto.\n                congruence.\n              }\n              rewrite <- HEmpty in HWT.\n              auto.\n          - inv HTy1.\n            destruct m'.\n            + exfalso; eapply H10; eauto.\n            + specialize (HMode eq_refl). inv HMode.\n        }\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...\n      * specialize (IH2 H4 eq_refl (in_hole e'0 E) H').\n        destruct IH2 as [HC HWT]; eauto.\n        split; eauto...\n  (* T-Assign *)\n  - inv Hreduces.\n    inv HHwf.\n    destruct E; inversion H3; simpl in *; subst.\n    + clear H9. clear H2.\n      inv H6.\n      inv Hwt2.\n      inv Hwt1.\n      destruct H0 as [[HW Eq] | Eq]; subst.\n      * { destruct m'; [| specialize (H1 eq_refl); inv H1].\n          eapply well_typed_heap_in in H10; eauto.\n          destruct H10 as [N HMap].\n          split.\n          - apply HeapUpd with (n := N); eauto...\n            eapply PtrUpd; eauto.\n          - constructor.\n            eapply PtrUpd; eauto. \n        } \n      * destruct Eq as [? [? ?]]; subst.\n        { destruct m'; [| specialize (H1 eq_refl); inv H1].\n          eapply (well_typed_heap_in_array n D H l h) in H10; eauto.\n          destruct H10 as [N HMap].\n          split.\n          - apply HeapUpd with (n := N); eauto...\n            eapply PtrUpd; eauto.\n          - constructor.\n            eapply PtrUpd; eauto.\n          - eapply (H12 l h). eauto.\n          - eapply H12. eauto.\n        } \n    + destruct (IHHwt1 H5 eq_refl (in_hole e'0 E) H') as [HC HWT]; eauto.\n      split; eauto...\n    + destruct (IHHwt2 H7 eq_refl (in_hole e'0 E) H') as [HC HWT]; eauto.\n      split; eauto...\n  - inv Hreduces.\n    inv HHwf.\n    inv H6.\n    destruct E; inv H4; subst; simpl in*; subst; eauto.\n    + inv H7.\n    + destruct E; inversion H5; simpl in *; subst.\n      * { (* Plus step *)\n          inv H7; 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: h - n2 - (l - n2) = h - l) by omega.\n            rewrite Hyp in * ; clear Hyp.\n            \n            destruct (H5 (n2 + k)) as [n' [t' [HNth [HMap HWT]]]]; [omega | ].\n\n            exists n'. exists t'.\n\n            rewrite Z.add_assoc in HMap.\n\n            split; [ | split]; auto.\n            + destruct (h - l) eqn:HHL; simpl in *.\n              * rewrite Z.add_0_r in Hk.\n                destruct (Z.to_nat (n2 + k - l)); inv HNth.\n              * assert (HR: k - (l - n2) = n2 + k - l) by (zify; omega).\n                rewrite HR.\n                auto.\n              * destruct (Z.to_nat (n2 + k - l)); 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 l h t))\n                                     empty_scope =\n                             (n1, TPtr Checked (TArray l h 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 l h t)) \n                                             ((n1, TPtr Checked (TArray l h t)) :: nil)).\n              {\n                unfold set_remove_all.\n                destruct (eq_dec_nt (n1, TPtr Checked (TArray l h t))\n                                    (n1, TPtr Checked (TArray l h t))); auto.\n                congruence.\n              }\n              rewrite <- HEmpty in HWT.\n              auto.\n          - inv Hwt1.\n            destruct m'.\n            + exfalso; eapply H14; eauto.\n            + specialize (H2 eq_refl). eapply TyAssign; eauto.\n         }\n      * destruct (IHHwt1 H9 eq_refl (in_hole e'0 E) H') as [HC HWT]; eauto.\n        split ; eauto...\n      * destruct (IHHwt2 H11 eq_refl (in_hole e'0 E) H') as [HC HWT]; eauto.\n        split; eauto...\nQed.\n\n(* ... for Blame *)\n\nCreate HintDb Blame.\n\nPrint heap_add_in_cardinal.\n\nLemma heap_wf_step : forall D H e H' e',\n    @structdef_wf D ->\n    heap_wf D H ->\n    @step D H e H' (RExpr e') ->\n    heap_wf D H'.\nProof.\n  intros D H e H' e' HD HHwf HS.\n  induction HS; eauto.\n  - assert (Heap.cardinal H' = Heap.cardinal H).\n      { rewrite H2. apply heap_add_in_cardinal. auto. }\n    intro addr; split; intro Hyp.\n    + rewrite H2.\n      rewrite H3 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, t1); auto.\n        eapply Heap.add_1; eauto.\n      * exists v.\n        eapply Heap.add_2; eauto.\n    + rewrite H2 in Hyp.\n      destruct Hyp as [v Hv].\n      destruct (Z.eq_dec addr n).\n      * subst.\n        rewrite H3.\n        apply HHwf; auto.\n      * rewrite H3.\n        apply HHwf.\n        exists v.\n        apply Heap.add_3 in Hv; auto.\n  - apply alloc_correct in H0; eauto.\n    apply Env.empty.\nQed.\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\nLemma expr_wf_step : forall D H e H' e',\n    @expr_wf D e ->\n    @step D H e H' (RExpr e') ->\n    @expr_wf D e'.\nProof.\n  intros D H e H' e' Hwf HS.\n  inv HS; inv Hwf; eauto; try solve [repeat (constructor; eauto)].\n  - inv H1; constructor; eauto.\n  - apply expr_wf_subst; eauto.\nQed.\n\nLemma expr_wf_reduce : forall D H m e H' e',\n    @expr_wf D e ->\n    @reduce D H e m H' (RExpr e') ->\n    @expr_wf D e'.\nProof.\n  intros D H m e H' e' Hwf 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 } (H : heap) (e : expression) : Prop :=\n  ~ exists m' H' r, @reduce D H e m' H' r.\n\nDefinition stuck { D : structdef } (H : heap) (r : result) : Prop :=\n  match r with\n  | RBounds => True\n  | RNull => True\n  | RExpr e => @normal D H e /\\ ~ value D e\n  end.\n\nInductive eval { D : structdef } : heap -> expression -> mode -> heap -> result -> Prop :=\n  | eval_refl   : forall H e m, eval H e m H (RExpr e)\n  | eval_transC : forall H H' H'' e e' r,\n      @reduce D H e Checked H' (RExpr e') ->\n      eval H' e' Checked H'' r ->\n      eval H e Checked H'' r\n  | eval_transU : forall H H' H'' m' e e' r,\n      @reduce D H e Unchecked H' (RExpr e') ->\n      eval H' e' m' H'' r ->\n      eval H e Unchecked H'' r.\n\nLemma wt_dec : forall D H env m e t, { @well_typed D H env m e t } + { ~ @well_typed D H env m e t }.\n  (* This is a biggy *)\nAdmitted.\n\nTheorem blame : forall D H e t m H' r,\n    @structdef_wf D ->\n    heap_wf D H ->\n    @expr_wf D e ->\n    @well_typed D H empty_env Checked e t ->\n    @eval D H e m H' r ->\n    @stuck D H' r ->\n    m = Unchecked \\/ (exists E e0, r = RExpr (in_hole e0 E) /\\ mode_of E = Unchecked).\nProof.\n  intros D H e t m H' r HDwf HHwf Hewf Hwt Heval Hstuck.\n  destruct r.\n  - pose proof (wt_dec D H' empty_env Checked e0 t).\n    destruct H0.\n    (* e0 is well typed *)\n    + remember (RExpr e0) as r.\n      induction Heval; subst.\n      * inv Heqr.\n        assert (value D e0 \\/ reduces D H e0 \\/ unchecked Checked e0).\n        { apply progress with (t := t); eauto. }\n        destruct H0.\n        unfold stuck in Hstuck.\n        destruct Hstuck.\n        exfalso. apply H2. assumption.\n        destruct H0.\n        unfold stuck in Hstuck.\n        destruct Hstuck.\n        unfold normal in H1.\n        unfold reduces in H0.\n        exfalso. apply H1.\n        assumption.\n        unfold unchecked in H0.\n        destruct H0.\n        inversion H0.\n        right. destruct H0. destruct H0. destruct H0.\n        exists x0.\n        exists x.\n        split.\n        rewrite H0. reflexivity.\n        assumption.\n      * apply IHHeval.\n        inv H0. eapply heap_wf_step; eauto.\n        eapply expr_wf_reduce; eauto.\n        assert (@heap_consistent D H' H /\\ @well_typed D H' empty_env Checked e' t).\n        { apply preservation with (e := e); assumption. }\n        destruct H1.\n        assumption.\n        reflexivity.\n        assumption.\n        assumption.\n      * left. reflexivity.\n    (* e0 is not well typed *)\n    + remember (RExpr e0) as r.\n      induction Heval; subst.\n      * inv Heqr.\n        exfalso.\n        apply n.\n        assumption.\n      * apply IHHeval.\n        inv H0. eapply heap_wf_step; eauto.\n        eapply expr_wf_reduce; eauto.\n        assert (@heap_consistent D H' H /\\ @well_typed D H' empty_env Checked e' t).\n        { apply preservation with (e := e); assumption. }\n        destruct H1.\n        assumption.\n        reflexivity.\n        assumption.\n        assumption.\n      * left. reflexivity.\n  - left.\n    clear Hstuck.\n    remember RNull as r.\n    induction Heval; subst.\n    + inversion Heqr.\n    + apply IHHeval; try reflexivity.\n      inv H0.\n      eapply heap_wf_step; eauto.\n      eapply expr_wf_reduce; eauto.\n      assert (@heap_consistent D H' H /\\ @well_typed D H' empty_env Checked e' t).\n      { apply preservation with (e := e); eauto. }\n      destruct H1.\n      apply H2.\n    + reflexivity.\n  - left.\n    clear Hstuck.\n    remember RBounds as r.\n    induction Heval; subst.\n    + inversion Heqr.\n    + apply IHHeval; try reflexivity.\n      inv H0.\n      eapply heap_wf_step; eauto.\n      eapply expr_wf_reduce; eauto.\n      assert (@heap_consistent D H' H /\\ @well_typed D H' empty_env Checked e' t).\n      { apply preservation with (e := e); eauto. }\n      destruct H1.\n      apply H2.\n    + reflexivity.\nQed. \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/BoundCheckedC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5, "lm_q1q2_score": 0.27723523248021364}}
{"text": "Require Import\n  MathClasses.interfaces.abstract_algebra MathClasses.interfaces.functors.\n\nDefinition Empty_map {A: Empty_set → Type} : ∀ x : Empty_set, A x := λ x, match x with end.\nLocal Notation E := Empty_map.\n\nInstance: Arrows Empty_set := E.\nInstance: CatComp Empty_set := E.\nInstance: CatId Empty_set := E.\nInstance: ∀ x y, Equiv (x ⟶ y) := E.\nInstance: ∀ x y, Setoid (x ⟶ y) := E.\nInstance: Category Empty_set.\nProof. constructor; exact E. Qed.\n\nSection another_category.\n  Context `{Category C}.\n\n  Global Instance: Fmap (E: _ → C) := E.\n\n  Global Instance: Functor (E: _ → C) E.\n  Proof. constructor; exact E || typeclasses eauto. Qed.\nEnd another_category.\n", "meta": {"author": "agumonkey", "repo": "cats", "sha": "9f12c5090c2a75fe14eb72c1a806723e38dbb03c", "save_path": "github-repos/coq/agumonkey-cats", "path": "github-repos/coq/agumonkey-cats/cats-9f12c5090c2a75fe14eb72c1a806723e38dbb03c/coq/math-classes/categories/empty.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2771450623502205}}
{"text": "From iris.proofmode Require Import proofmode.\nFrom lrust.lang Require Import heap.\nFrom lrust.typing Require Export type.\nFrom lrust.typing Require Import util lft_contexts type_context programs.\nFrom iris.prelude Require Import options.\n\nSection uniq_bor.\n  Context `{!typeGS Σ}.\n\n  Program Definition uniq_bor (κ:lft) (ty:type) :=\n    {| ty_size := 1;\n       ty_own tid vl :=\n         match vl return _ with\n         | [ #(LitLoc l) ] => &{κ} (l ↦∗: ty.(ty_own) tid)\n         | _ => False\n         end;\n       ty_shr κ' tid l :=\n         ∃ l':loc, &frac{κ'}(λ q', l ↦{q'} #l') ∗\n           □ ∀ F q, ⌜↑shrN ∪ ↑lftN ⊆ F⌝ -∗ q.[κ⊓κ']\n               ={F}[F∖↑shrN]▷=∗ ty.(ty_shr) (κ⊓κ') tid l' ∗ q.[κ⊓κ']\n    |}%I.\n  Next Obligation. by iIntros (q ty tid [|[[]|][]]) \"H\". Qed.\n  Next Obligation.\n    move=> κ ty N κ' l tid ??/=. iIntros \"#LFT Hshr Htok\".\n    iMod (bor_exists with \"LFT Hshr\") as ([|[[|l'|]|][]]) \"Hb\"; first solve_ndisj;\n      (iMod (bor_sep with \"LFT Hb\") as \"[Hb1 Hb2]\"; first solve_ndisj);\n      try (iMod (bor_persistent with \"LFT Hb2 Htok\") as \"[>[] _]\"; solve_ndisj).\n    iFrame. iExists l'. subst. rewrite heap_mapsto_vec_singleton.\n    iMod (bor_fracture (λ q, l ↦{q} #l')%I with \"LFT Hb1\") as \"$\"; first solve_ndisj.\n    iApply delay_sharing_nested; try done. iApply lft_incl_refl.\n  Qed.\n  Next Obligation.\n    intros κ0 ty κ κ' tid l. iIntros \"#Hκ #H\".\n    iDestruct \"H\" as (l') \"[Hfb Hvs]\". iAssert (κ0⊓κ' ⊑ κ0⊓κ)%I as \"#Hκ0\".\n    { iApply lft_intersect_mono; last done. iApply lft_incl_refl. }\n    iExists l'. iSplit; first by iApply (frac_bor_shorten with \"[]\").\n    iIntros \"!> %F %q % Htok\". iApply (step_fupd_mask_mono F _ (F∖↑shrN)); try solve_ndisj.\n    iMod (lft_incl_acc with \"Hκ0 Htok\") as (q') \"[Htok Hclose]\"; first solve_ndisj.\n    iMod (\"Hvs\" with \"[%] Htok\") as \"Hvs'\"; first solve_ndisj. iModIntro. iNext.\n    iMod \"Hvs'\" as \"[#Hshr Htok]\". iMod (\"Hclose\" with \"Htok\") as \"$\".\n    by iApply (ty_shr_mono with \"Hκ0\").\n  Qed.\n\n  Global Instance uniq_bor_wf κ ty `{!TyWf ty} : TyWf (uniq_bor κ ty) :=\n    { ty_lfts := [κ]; ty_wf_E := ty_wf_E ty ++ ty_outlives_E ty κ }.\n\n  Lemma uniq_type_incl κ1 κ2 ty1 ty2 :\n    κ2 ⊑ κ1 -∗\n    ▷ type_equal ty1 ty2 -∗\n    type_incl (uniq_bor κ1 ty1) (uniq_bor κ2 ty2).\n  Proof.\n    iIntros \"#Hlft #Hty\". iSplit; first done.\n    iSplit; iModIntro.\n    - iIntros (? [|[[]|][]]) \"H\"; try done.\n      iApply (bor_shorten with \"Hlft\"). iApply bor_iff; last done.\n      iNext. iModIntro.\n      iDestruct \"Hty\" as \"(_ & Hty & _)\".\n      iSplit; iIntros \"H\"; iDestruct \"H\" as (vl) \"[??]\";\n      iExists vl; iFrame; by iApply \"Hty\".\n    - iIntros (κ ??) \"H\". iAssert (κ2 ⊓ κ ⊑ κ1 ⊓ κ)%I as \"#Hincl'\".\n      { iApply lft_intersect_mono; first done. iApply lft_incl_refl. }\n      iDestruct \"H\" as (l') \"[Hbor #Hupd]\". iExists l'. iIntros \"{$Hbor}!> %%% Htok\".\n      iMod (lft_incl_acc with \"Hincl' Htok\") as (q') \"[Htok Hclose]\"; first solve_ndisj.\n      iMod (\"Hupd\" with \"[%] Htok\") as \"Hupd'\"; try done. iModIntro. iNext.\n      iMod \"Hupd'\" as \"[H Htok]\". iMod (\"Hclose\" with \"Htok\") as \"$\".\n      iDestruct \"Hty\" as \"(_ & _ & Hty)\".\n      iApply ty_shr_mono; last by iApply \"Hty\".\n      done.\n  Qed.\n\n  Global Instance uniq_mono E L :\n    Proper (flip (lctx_lft_incl E L) ==> eqtype E L ==> subtype E L) uniq_bor.\n  Proof.\n    intros κ1 κ2 Hκ ty1 ty2. rewrite eqtype_unfold=>Hty. iIntros (??) \"HL\".\n    iDestruct (Hty with \"HL\") as \"#Hty\". iDestruct (Hκ with \"HL\") as \"#Hκ\".\n    iIntros \"!> #HE\".\n    iApply uniq_type_incl.\n    - iDestruct (\"Hκ\" with \"HE\") as %H.\n      apply lft_incl_syn_sem in H. iApply H.\n    - iNext. iApply \"Hty\". done.\n  Qed.\n  Global Instance uniq_mono_flip E L :\n    Proper (lctx_lft_incl E L ==> eqtype E L ==> flip (subtype E L)) uniq_bor.\n  Proof. intros ??????. apply uniq_mono; first done. by symmetry. Qed.\n  Global Instance uniq_proper E L :\n    Proper (lctx_lft_eq E L ==> eqtype E L ==> eqtype E L) uniq_bor.\n  Proof. intros ??[]; split; by apply uniq_mono. Qed.\n\n  Global Instance uniq_type_contractive κ : TypeContractive (uniq_bor κ).\n  Proof. solve_type_proper. Qed.\n\n  Global Instance uniq_ne κ : NonExpansive (uniq_bor κ).\n  Proof. apply type_contractive_ne, _. Qed.\n\n  Global Instance uniq_send κ ty :\n    Send ty → Send (uniq_bor κ ty).\n  Proof.\n    iIntros (Hsend tid1 tid2 [|[[]|][]]) \"H\"; try done.\n    iApply bor_iff; last done. iNext. iModIntro. iApply bi.equiv_iff.\n    do 3 f_equiv. iSplit; iIntros \".\"; by iApply Hsend.\n  Qed.\n\n  Global Instance uniq_sync κ ty :\n    Sync ty → Sync (uniq_bor κ ty).\n  Proof.\n    iIntros (Hsync κ' tid1 tid2 l) \"H\". iDestruct \"H\" as (l') \"[Hm #Hshr]\".\n    iExists l'. iFrame \"Hm\". iModIntro. iIntros (F q) \"% Htok\".\n    iMod (\"Hshr\" with \"[] Htok\") as \"Hfin\"; first done. iClear \"Hshr\".\n    iModIntro. iNext. iMod \"Hfin\" as \"[Hshr $]\". iApply Hsync. done.\n  Qed.\nEnd uniq_bor.\n\nNotation \"&uniq{ κ }\" := (uniq_bor κ) (format \"&uniq{ κ }\") : lrust_type_scope.\n\nSection typing.\n  Context `{!typeGS Σ}.\n\n  Lemma uniq_mono' E L κ1 κ2 ty1 ty2 :\n    lctx_lft_incl E L κ2 κ1 → eqtype E L ty1 ty2 →\n    subtype E L (&uniq{κ1}ty1) (&uniq{κ2}ty2).\n  Proof. by intros; apply uniq_mono. Qed.\n  Lemma uniq_proper' E L κ1 κ2 ty1 ty2 :\n    lctx_lft_eq E L κ1 κ2 → eqtype E L ty1 ty2 → eqtype E L (&uniq{κ1}ty1) (&uniq{κ2}ty2).\n  Proof. by intros; apply uniq_proper. Qed.\n\n  Lemma tctx_reborrow_uniq E L p ty κ κ' :\n    lctx_lft_incl E L κ' κ →\n    tctx_incl E L [p ◁ &uniq{κ}ty] [p ◁ &uniq{κ'}ty; p ◁{κ'} &uniq{κ}ty].\n  Proof.\n    iIntros (Hκκ' tid ??) \"#LFT HE HL H\". iDestruct (Hκκ' with \"HL HE\") as %H.\n    iDestruct (lft_incl_syn_sem κ' κ H) as \"Hκκ'\".\n    iFrame. rewrite tctx_interp_singleton tctx_interp_cons tctx_interp_singleton.\n    iDestruct \"H\" as ([[]|]) \"[% Hb]\"; try done.\n    iMod (rebor with \"LFT Hκκ' Hb\") as \"[Hb Hext]\"; first done. iModIntro.\n    iSplitL \"Hb\"; iExists _; auto.\n  Qed.\n\n  Lemma tctx_extract_hasty_reborrow E L p ty ty' κ κ' T :\n    lctx_lft_incl E L κ' κ → eqtype E L ty ty' →\n    tctx_extract_hasty E L p (&uniq{κ'}ty) ((p ◁ &uniq{κ}ty')::T)\n                       ((p ◁{κ'} &uniq{κ}ty')::T).\n  Proof.\n    intros. apply (tctx_incl_frame_r _ [_] [_;_]). rewrite tctx_reborrow_uniq //.\n    by apply (tctx_incl_frame_r _ [_] [_]), subtype_tctx_incl, uniq_mono'.\n  Qed.\n\n  Lemma read_uniq E L κ ty :\n    Copy ty → lctx_lft_alive E L κ → ⊢ typed_read E L (&uniq{κ}ty) ty (&uniq{κ}ty).\n  Proof.\n    rewrite typed_read_eq. iIntros (Hcopy Halive) \"!>\".\n    iIntros ([[]|] tid F qmax qL ?) \"#LFT #HE Htl HL Hown\"; try done.\n    iMod (Halive with \"HE HL\") as (q) \"[Hκ Hclose]\"; first solve_ndisj.\n    iMod (bor_acc with \"LFT Hown Hκ\") as \"[H↦ Hclose']\"; first solve_ndisj.\n    iDestruct \"H↦\" as (vl) \"[>H↦ #Hown]\".\n    iDestruct (ty_size_eq with \"Hown\") as \"#>%\". iIntros \"!>\".\n    iExists _, _, _. iSplit; first done. iFrame \"∗#\". iIntros \"H↦\".\n    iMod (\"Hclose'\" with \"[H↦]\") as \"[$ Htok]\"; first by iExists _; iFrame.\n    by iMod (\"Hclose\" with \"Htok\") as \"($ & $ & $)\".\n  Qed.\n\n  Lemma write_uniq E L κ ty :\n    lctx_lft_alive E L κ → ⊢ typed_write E L (&uniq{κ}ty) ty (&uniq{κ}ty).\n  Proof.\n    rewrite typed_write_eq. iIntros (Halive) \"!>\".\n    iIntros ([[]|] tid F qmax qL ?) \"#LFT HE HL Hown\"; try done.\n    iMod (Halive with \"HE HL\") as (q) \"[Htok Hclose]\"; first solve_ndisj.\n    iMod (bor_acc with \"LFT Hown Htok\") as \"[H↦ Hclose']\"; first solve_ndisj.\n    iDestruct \"H↦\" as (vl) \"[>H↦ Hown]\". rewrite ty.(ty_size_eq).\n    iDestruct \"Hown\" as \">%\". iModIntro. iExists _, _. iSplit; first done.\n    iFrame. iIntros \"Hown\". iDestruct \"Hown\" as (vl') \"[H↦ Hown]\".\n    iMod (\"Hclose'\" with \"[H↦ Hown]\") as \"[$ Htok]\"; first by iExists _; iFrame.\n    by iMod (\"Hclose\" with \"Htok\") as \"($ & $ & $)\".\n  Qed.\nEnd typing.\n\nGlobal Hint Resolve uniq_mono' uniq_proper' write_uniq read_uniq : lrust_typing.\nGlobal Hint Resolve tctx_extract_hasty_reborrow | 10 : 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/uniq_bor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.27714506235022046}}
{"text": "(* * Syntax and semantics of the Jasmin source language *)\n\n(* ** Imports and settings *)\nRequire Export ZArith Setoid Morphisms.\nFrom mathcomp Require Import all_ssreflect all_algebra.\nFrom mathcomp Require Import word_ssrZ.\nRequire Import Psatz xseq.\nRequire Export utils array gen_map type word memory_model.\nImport Utf8 ZArith.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nVariant arr_access := \n  | AAdirect\n  | AAscale.\n\nScheme Equality for arr_access.\n\nLemma arr_access_eq_axiom : Equality.axiom arr_access_beq.\nProof.\n  move=> x y;apply:(iffP idP).\n  + by apply: internal_arr_access_dec_bl.\n  by apply: internal_arr_access_dec_lb.\nQed.\n\nDefinition arr_access_eqMixin     := Equality.Mixin arr_access_eq_axiom.\nCanonical  arr_access_eqType      := Eval hnf in EqType arr_access arr_access_eqMixin.\n\nLocal Open Scope Z_scope.\n\nDefinition arr_size (ws:wsize) (len:positive)  := \n   (wsize_size ws * len).\n\nLemma arr_sizeE ws len : arr_size ws len = (wsize_size ws * len).\nProof. done. Qed.\n\nLemma ge0_arr_size ws len : 0 <= arr_size ws len.\nProof. rewrite arr_sizeE; have := wsize_size_pos ws; nia. Qed.\n\nOpaque arr_size.\n\nDefinition mk_scale (aa:arr_access) ws := \n  if aa is AAscale then wsize_size ws else 1.\n\nModule WArray.\n\n  Record array (s:positive)  :=\n    { arr_data : Mz.t u8 }.\n\n  Definition empty (s:positive) : array s :=\n    {| arr_data := Mz.empty _ |}.\n\n  Local Notation pointer := [eqType of Z].\n\n  (* We set the priority to 1, so that memory_model.Pointer is selected by\n     default.\n  *)\n#[global]\n  Instance PointerZ : pointer_op pointer | 1.\n  Proof.\n    refine {| add x y := (x + y)%Z\n            ; sub x y := (x - y)%Z\n            ; p_to_z x := x        |}.\n    - abstract (move => /= ??; ring).\n    - abstract (move => /= ???; ring).\n    - abstract (move => /= ?; ring).\n  Defined.\n\n  Lemma addE x y : add x y = (x + y)%Z.\n  Proof. by []. Qed.\n\n  Lemma subE x y : sub x y = (x - y)%Z.\n  Proof. by []. Qed.\n\n  Lemma p_to_zE x : p_to_z x = x.\n  Proof. by []. Qed.\n\n  Global Opaque PointerZ.\n\n  Section WITH_POINTER_DATA.\n  Context {pd: PointerData}.\n\n  Lemma is_align_scale (p:pointer) ws : is_align (p * mk_scale AAscale ws)%Z ws.\n  Proof. by rewrite /is_align /mk_scale /= Z_mod_mult. Qed.\n\n  Lemma arr_is_align i ws :\n    is_align (wrepr Uptr i) ws = is_align i ws.\n  Proof.\n    by rewrite /is_align p_to_zE memory_model.p_to_zE wunsigned_repr mod_wbase_wsize_size.\n  Qed.\n\n  Section CM.\n    Variable (s:positive).\n\n    Definition in_bound (_:array s) p := (0 <=? p) && (p <? s).\n   \n    Lemma in_boundP m p : reflect (0 <= p < s) (in_bound m p).\n    Proof. by apply (iffP andP); rewrite !zify. Qed.\n\n    Definition is_init (m:array s) (i:pointer) :=\n      match Mz.get m.(arr_data) i with \n      | Some _ => true \n      | None   => false\n      end.\n\n    Definition get8 (m:array s) (i:pointer) :=\n      Let _ := assert (in_bound m i) ErrOob in\n      Let _ := assert (is_init m i) ErrAddrUndef in\n      ok (odflt 0%R (Mz.get m.(arr_data) i)).\n\n    Definition set8 (m:array s) (i:pointer) (v:u8) : result _ (array s):=\n      Let _ := assert (in_bound m i) ErrOob in\n      ok {| arr_data := Mz.set m.(arr_data) i v |}.\n\n    Lemma valid8P m p w : reflect (exists m', set8 m p w = ok m') (in_bound m p).\n    Proof.\n      by (rewrite /set8; case: in_bound => /=; constructor); [eexists; eauto | move=> []].\n    Qed.\n \n    Lemma get_valid8 m p w : get8 m p = ok w -> in_bound m p.\n    Proof. by rewrite /get8; t_xrbindP. Qed.\n\n    Lemma valid8_set m p w m' p' : set8 m p w = ok m' -> in_bound m' p' = in_bound m p'.\n    Proof. by rewrite /set8; t_xrbindP => _ <-. Qed.\n\n    Lemma set8P m p w p' m' :\n      set8 m p w = ok m' ->\n      get8 m' p' = if p == p' then ok w else get8 m p'.\n    Proof.\n      rewrite /get8 /set8 => /dup[] /valid8_set ->; t_xrbindP => hb <-.\n      case heq: in_bound => //=; last by case: eqP => // h;move: heq; rewrite -h hb.\n      by rewrite /is_init /= Mz.setP; case: eqP.\n    Qed.\n\n    Global Instance array_CM : coreMem pointer (array s) :=\n      CoreMem set8P valid8P get_valid8 valid8_set.\n\n    Definition in_range (p:pointer) (ws:wsize) :=\n      ((0 <=? p) && (p + wsize_size ws <=? s))%Z.\n\n    Lemma in_rangeP p ws:\n      reflect (0 <= p /\\ p + wsize_size ws <= s)%Z (in_range p ws).\n    Proof.\n      rewrite /in_range; case: andP => h; constructor; move: h; rewrite !zify; Psatz.nia.\n    Qed.\n\n    Lemma validw_in_range m p ws : validw m p ws = (is_align p ws && in_range p ws).\n    Proof.\n      apply (sameP (validwP m p ws)).\n      apply (iffP andP).\n      + move=> [] ? /in_rangeP ?;split => // k hk.\n        by rewrite -valid8_validw /valid8 /= /in_bound !zify !addE; Psatz.lia.\n      move=> [] ? h; split => //; apply /in_rangeP.\n      move: (wsize_size_pos ws) (h 0) (h (wsize_size ws - 1)).\n      by rewrite add_0 addE -!valid8_validw /array_CM /valid8 /in_bound !zify; Psatz.lia.\n    Qed.\n\n  End CM.\n\n  Definition get len (aa:arr_access) ws (a:array len) (p:Z) :=\n    CoreMem.read a (p * mk_scale aa ws)%Z ws.\n \n  Definition set {len ws} (a:array len) aa p (v:word ws) : exec (array len) :=   \n    CoreMem.write a (p * mk_scale aa ws)%Z v.\n\n  Definition fcopy ws len (a t: WArray.array len) i j := \n    foldM (fun i t => \n             Let w := get AAscale ws a i in set t AAscale i w) t\n          (ziota i j).\n\n  Definition copy ws p (a:array (Z.to_pos (arr_size ws p))) := \n    fcopy ws a (WArray.empty _) 0 p.\n\n  Definition fill len (l:list u8) : exec (array len) := \n    Let _ := assert (Pos.to_nat len == size l) ErrType in \n    Let pt := \n      foldM (fun w pt =>\n             Let t := set pt.2 AAscale pt.1 w in\n             ok (pt.1 + 1, t)) (0%Z, empty len) l in\n    ok pt.2.\n\n  Definition get_sub_data (aa:arr_access) ws len (a:Mz.t u8) p := \n     let size := arr_size ws len in \n     let start := (p * mk_scale aa ws)%Z in\n     foldr (fun i data => \n       match Mz.get a (start + i) with\n       | None => Mz.remove data i\n       | Some w => Mz.set data i w\n       end) (Mz.empty _) (ziota 0 size).\n\n  Definition get_sub lena (aa:arr_access) ws len (a:array lena) p  : exec (array (Z.to_pos (arr_size ws len))) := \n     let size := arr_size ws len in \n     let start := (p * mk_scale aa ws)%Z in\n     if (0 <=? start) && (start + size <=? lena) then\n       ok (Build_array (Z.to_pos size) (get_sub_data aa ws len (arr_data a) p))\n     else Error ErrOob.\n\n  Definition set_sub_data (aa:arr_access) ws len (a:Mz.t u8) p (b:Mz.t u8) := \n    let size := arr_size ws len in \n    let start := (p * mk_scale aa ws)%Z in\n    foldr (fun i data => \n      match Mz.get b i with\n      | None => Mz.remove data (start + i)\n      | Some w => Mz.set data (start + i) w\n      end) a (ziota 0 size).\n\n  Definition set_sub lena (aa:arr_access) ws len (a:array lena) p (b:array (Z.to_pos (arr_size ws len))) : exec (array lena) := \n    let size := arr_size ws len in \n    let start := (p * mk_scale aa ws)%Z in\n    if (0 <=? start) && (start + size <=? lena) then\n      ok (Build_array lena (set_sub_data aa ws len (arr_data a) p (arr_data b)))\n    else Error ErrOob.\n\n  Definition cast len len' (a:array len) : result error (array len') :=\n    if (len' <=? len)%Z then ok {| arr_data := a.(arr_data) |}\n    else type_error.\n\n  Definition uincl {len1 len2} (a1 : array len1) (a2 : array len2) :=\n    (len1 <= len2)%Z /\\\n    ∀ i w, read a1 i U8 = ok w -> read a2 i U8 = ok w.\n\n  Lemma uincl_refl len (a: array len) : uincl a a.\n  Proof. by split => //; reflexivity. Qed.\n\n  Lemma uincl_trans {len1 len2 len3} \n    (a2: array len2) (a1: array len1) (a3: array len3) :\n    uincl a1 a2 -> uincl a2 a3 -> uincl a1 a3. \n  Proof.\n    move=> [l1 h1] [l2 h2]; split; first by lia.\n    by move=> ?? /h1 /h2.\n  Qed.\n\n  End WITH_POINTER_DATA.\n\n  Lemma castK len (a:array len) : WArray.cast len a = ok a.\n  Proof. by rewrite /cast Z.leb_refl; case: a. Qed.\n\n  Lemma cast_len len1 len2 (t2:WArray.array len2) t1: WArray.cast len1 t2 = ok t1 -> len1 <= len2.\n  Proof. by rewrite /cast; case: ZleP. Qed.\n\n  Lemma cast_empty len1 len2 : \n    WArray.cast len1 (empty len2) = if len1 <=? len2 then ok (empty len1) else type_error.\n  Proof. by rewrite /WArray.cast. Qed.\n\n  Lemma cast_empty_ok len1 len2 t: \n    WArray.cast len1 (empty len2) = ok t -> t = empty len1.\n  Proof. by move=> /dup[]/cast_len/ZleP; rewrite cast_empty => -> [<-]. Qed.\n\n  Lemma cast_get8 len1 len2 (m : array len2) m' :\n    cast len1 m = ok m' ->\n    forall k,\n      read m' k U8 = \n        if k <? len1 then read m k U8 else Error ErrOob.\n  Proof.\n    rewrite /cast; case: ZleP => // hle [<-] k.\n    rewrite -!get_read8 /memory_model.get /= /get8 /is_init /in_bound /=.\n    by case: ZleP => /=; case: ZltP => //=; case: ZltP => //; lia.\n  Qed.\n\n  Lemma cast_uincl len1 len2 (t2 : WArray.array len2) t1 : \n    cast len1 t2 = ok t1 -> uincl t1 t2.\n  Proof.\n    move=> hc; split; first by apply: cast_len hc.\n    by move=> i w; rewrite (cast_get8 hc); case: ifP.\n  Qed.\n\n  Lemma uincl_cast len1 len2 (a1: array len1) (a2:array len2) len a1' : \n    uincl a1 a2 ->\n    cast len a1 = ok a1' ->\n    exists a2', cast len a2 = ok a2' /\\ uincl a1' a2'.\n  Proof.\n    move=> [hle hu] hc.\n    have:= (cast_get8 hc). have:= @cast_get8 len len2 a2.\n    move: hc; rewrite /cast; case: ZleP => // hle1 _. \n    case: ZleP => hle2 hg2 hg1; last lia.\n    eexists;split; first by eauto.\n    split; first by lia.\n    by move=> ??; rewrite hg1 hg2 //; case: ifP => // _ /hu.\n  Qed.\n\n  Lemma mk_scale_U8 aa : mk_scale aa U8 = 1%Z.\n  Proof. by rewrite /mk_scale wsize8; case aa. Qed.\n\n  Lemma get8_read len (m : array len) aa k :\n    get aa U8 m k = read m k U8.\n  Proof. by rewrite /get mk_scale_U8 Z.mul_1_r. Qed.\n\n  Lemma set_get8 len (m m':array len) aa p ws (v: word ws) :\n    set m aa p v = ok m' ->\n    forall k,\n      read m' k U8 = \n        let i := (k - p * mk_scale aa ws)%Z in\n         if ((0 <=? i) && (i <? wsize_size ws))%Z then ok (LE.wread8 v i)\n         else read m k U8.\n  Proof. by apply: write_read8. Qed.\n\n  Lemma setP len (m m':array len) p1 p2 ws (v: word ws) :\n    set m AAscale p1 v = ok m' -> \n    get AAscale ws m' p2 = if p1 == p2 then ok v else get AAscale ws m p2.\n  Proof. \n    rewrite /set /get; case:eqP => [<- | hne hw]; first by apply writeP_eq.\n    apply: (CoreMem.writeP_neq hw); move=> ??; rewrite !addE /mk_scale;nia. \n  Qed.\n\n  Lemma setP_eq len (m m':array len) p1 ws (v: word ws) :\n    set m AAscale p1 v = ok m' -> \n    get AAscale ws m' p1 = ok v.\n  Proof. by move=> /setP ->; rewrite eqxx. Qed.\n\n  Lemma setP_neq len (m m':array len) p1 p2 ws (v: word ws) :\n    p1 != p2 ->\n    set m AAscale p1 v = ok m' -> \n    get AAscale ws m' p2 = get AAscale ws m p2.\n  Proof. by move=> /negPf h /setP ->; rewrite h. Qed.\n\n  Lemma mk_scale_bound aa ws : (1 <= mk_scale aa ws <= wsize_size ws)%Z.\n  Proof. rewrite /mk_scale; have := wsize_size_pos ws; case:aa; lia. Qed.\n \n  Lemma get_bound ws len aa (t:array len) i w :\n    get aa ws t i = ok w -> \n    [/\\ 0 <= i * mk_scale aa ws,\n        i * mk_scale aa ws + wsize_size ws <= len &\n        is_align (i * mk_scale aa ws) ws]%Z.\n  Proof.\n    move=> hg; assert (h := readV hg); move: h.\n    by rewrite validw_in_range => /andP [] ? /in_rangeP [].\n  Qed.\n\n  Lemma set_bound ws len aa (a t:array len) i (w:word ws) :\n    set a aa i w = ok t -> \n    [/\\ 0 <= i * mk_scale aa ws,\n        i * mk_scale aa ws +  wsize_size ws <= len &\n        is_align (i * mk_scale aa ws) ws]%Z.\n  Proof.\n    move=> hs; have : validw a (i * mk_scale aa ws) ws by apply /(writeV w); exists t.\n    by rewrite validw_in_range => /andP [] ? /in_rangeP [].\n  Qed.\n\n  Lemma get_empty (n:positive) off : \n    read (empty n) off U8 = if (0 <=? off) && (off <? n) then Error ErrAddrUndef else Error ErrOob.\n  Proof.\n    by rewrite -get_read8 /memory_model.get /= /get8 /in_bound /is_init /=; case: ifP.\n  Qed.\n\n  Lemma get0 (n:positive) off : (0 <= off ∧ off < n)%Z -> \n    read (empty n) off U8 = Error ErrAddrUndef.\n  Proof. by rewrite get_empty => -[/ZleP -> /ZltP ->]. Qed.\n\n  Lemma uincl_empty len len' (t:array len') : \n    Zpos len <= len' -> uincl (empty len) t.\n  Proof.  \n    split; first Psatz.lia.\n    by move=> i w; rewrite get_empty; case: ifP.\n  Qed.\n\n  Lemma uincl_validw {len1 len2} (a1 : array len1) (a2 : array len2) ws i :\n    uincl a1 a2 -> validw a1 i ws -> validw a2 i ws.\n  Proof.\n    move=> [h1 _]; rewrite !validw_in_range => /andP [] -> /= /in_rangeP ?; apply /in_rangeP; lia.\n  Qed.\n\n  Lemma uincl_get {len1 len2} (a1 : array len1) (a2 : array len2) aa ws i w :\n    uincl a1 a2 ->\n    get aa ws a1 i = ok w ->\n    get aa ws a2 i = ok w.\n  Proof.\n    rewrite /get => -[_ hu] hr; have {hr}[ha hr] := read_read8 hr.\n    by rewrite (read8_read (v:=w)) ?ha // => k /hr /hu.\n  Qed.\n  \n  Lemma uincl_set {ws len1 len2} (a1 a1': array len1) (a2: array len2) aa i (w:word ws) :\n    uincl a1 a2 ->\n    set a1 aa i w = ok a1' ->\n    exists a2', set a2 aa i w = ok a2' /\\ uincl a1' a2'.\n  Proof.\n    rewrite /set; set k := _ * _ => hu hw1. \n    have /(writeV w) [a2' hw2]: validw a2 k ws by apply /(uincl_validw hu) /(writeV w); exists a1'.\n    exists a2'; split => //.\n    case: hu => hle hu; split => //.\n    move=> j wj; rewrite (write_read8 hw1) (write_read8 hw2) /=.\n    by case:ifP => // _; apply: hu.\n  Qed.\n\n  Lemma fcopy_uincl ws len (a t1 t2 a1 : array len) i j: \n    uincl t1 t2 -> \n    fcopy ws a t1 i j = ok a1 -> \n    exists2 a2, fcopy ws a t2 i j = ok a2 & uincl a1 a2.\n  Proof.\n    rewrite /fcopy; elim: (ziota i j) t1 t2 => {i j} [ | i il hrec] t1 t2 hu /=.\n    + by move=> [<-]; exists t2.\n    t_xrbindP => t1' w -> hset hfold /=.    \n    by have [t2' [-> /hrec ]] /= := uincl_set hu hset; apply.\n  Qed.\n\n  Lemma uincl_copy ws p a1 a2 a1' :\n     uincl a1 a2 -> \n     @copy ws p a1 = ok a1' ->\n     @copy ws p a2 = ok a1'.\n  Proof.\n    move=> hu; rewrite /copy /fcopy.\n    elim: ziota (empty _) => [ | i il hrec] a //=.\n    t_xrbindP => a' w /(uincl_get hu) -> /= ->; apply: hrec.\n  Qed.\n\n  Definition fill_size len l a :\n    fill len l = ok a ->\n    Pos.to_nat len = size l.\n  Proof. by rewrite /fill; t_xrbindP => /eqP. Qed.\n\n  Lemma fill_get8 len l a :\n    fill len l = ok a ->\n    forall k,\n      read a k U8 =\n        if (0 <=? k) && (k <? len) then ok (nth 0%R l (Z.to_nat k))\n        else Error ErrOob.\n  Proof.\n    rewrite /fill; t_xrbindP=> /eqP hsize -[z {a}a] /= hfold <- k.\n    have: forall z0 a0,\n      foldM (fun w pt => Let t := set pt.2 AAscale pt.1 w in ok (pt.1 + 1, t)) (z0, a0) l = ok (z, a) ->\n      read a k U8 =\n        let i := k - z0 in\n        if (0 <=? i) && (i <? Z.of_nat (size l)) then ok (nth 0%R l (Z.to_nat i))\n        else read a0 k U8;\n      last first.\n    + move=> /(_ _ _ hfold) ->.\n      rewrite Z.sub_0_r get_empty /=.\n      rewrite -hsize positive_nat_Z.\n      by case: andb.\n    elim: l {hsize hfold} => [ | w l ih] z0 a0 /=.\n    + move=> [_ <-].\n      by case: ifP => //; rewrite !zify; lia.\n    t_xrbindP=> _ a1 hset <- /ih -> /=.\n    have ->:\n      (0 <=? k - z0) && (k - z0 <? Pos.of_succ_nat (size l)) =\n      (k == z0) || (0 <=? k - (z0 + 1)) && (k - (z0 + 1) <? Z.of_nat (size l)).\n    + by apply /idP/idP; rewrite !zify (rwR2 (@eqP _)); lia.\n    have := setP k hset; rewrite !get8_read => ->.\n    rewrite orbC.\n    case: ifP => /=.\n    + rewrite !zify => h.\n      by have ->: Z.to_nat (k - z0) = S (Z.to_nat (k - (z0+1))) by lia.\n    move=> _.\n    rewrite eq_sym.\n    case: eqP => [<- | //].\n    by rewrite Z.sub_diag.\n  Qed.\n\n  Lemma set_sub_data_get8 aa ws a len p t k: \n    Mz.get (@set_sub_data aa ws len a p t) k = \n      let i := (k - p * mk_scale aa ws)%Z in\n      if (0 <=? i) && (i <? arr_size ws len) then Mz.get t i \n      else Mz.get a k.\n  Proof.\n    rewrite /set_sub_data. \n    elim /natlike_ind: (arr_size ws len) a; last by apply ge0_arr_size.\n    + move=> data; rewrite ziota0 /=; case: andP => // -[]; rewrite !zify; lia.\n    move=> sz hsz ih data; rewrite ziotaS_cat // foldr_cat Z.add_0_l /= ih.\n    case: ifPn; rewrite !zify => h3; case: ifPn; rewrite !zify => h4 //.\n    + nia. \n    + case heq: (Mz.get t) => [w|].\n      + rewrite Mz.setP; case: eqP => [<- | ?]; last nia.\n        rewrite -heq; f_equal; ring. \n      rewrite Mz.removeP; case eqP => [<- | ?]; last nia.\n      rewrite -heq; f_equal; ring.\n    case heq: (Mz.get t) => [w|].\n    + rewrite Mz.setP; case: eqP => [? | //]; lia.\n    rewrite Mz.removeP; case eqP => [? | //]; lia.\n  Qed.\n\n  Lemma set_sub_get8 aa ws lena a len p t a' : \n    @set_sub lena aa ws len a p t = ok a' -> \n    forall k,\n      read a' k U8 = \n        let i := (k - p * mk_scale aa ws)%Z in\n        if (0 <=? i) && (i <? arr_size ws len) then read t i U8\n        else read a k U8.\n  Proof.\n    rewrite /set_sub; case: andP => // -[/ZleP h1 /ZleP h2] [<-] /= k.\n    rewrite -!get_read8 /memory_model.get /= /get8 /is_init /in_bound set_sub_data_get8 /=.\n    case: andP; rewrite !zify //= => ?; case: andP; rewrite !zify //= => ?; lia.\n  Qed.\n\n  Lemma set_sub_bound aa ws lena a len p t a' :\n    @set_sub lena aa ws len a p t = ok a' ->\n    0 <= p * mk_scale aa ws /\\ p * mk_scale aa ws + arr_size ws len <= lena.\n  Proof. by rewrite /set_sub; case: ifP => //; rewrite !zify. Qed.\n\n  Lemma get_sub_data_get8 aa ws a len p k: \n    Mz.get (get_sub_data aa ws len a p) k = \n      let start := (p * mk_scale aa ws)%Z in\n      if (0 <=? k) && (k <? arr_size ws len) then Mz.get a (start + k) \n      else None.\n  Proof.\n    rewrite /get_sub_data -(Mz.get0 u8 k).\n    elim /natlike_ind: (arr_size ws len) (Mz.empty u8); last by apply ge0_arr_size.\n    + move => b; rewrite ziota0 /=; case: andP => //; rewrite !zify; lia.\n    move=> sz hsz ih b; rewrite ziotaS_cat // foldr_cat Z.add_0_l /= ih.\n    case: ifPn; rewrite !zify => h3; case: ifPn; rewrite !zify => h4 //.\n    + nia. \n    + case heq: (Mz.get a) => [w|].\n      + by rewrite Mz.setP; case: eqP => [<- | ]; [rewrite heq | nia].\n      by rewrite Mz.removeP; case: eqP => [<- | ]; [rewrite heq | nia].\n    case heq: (Mz.get a) => [w|].\n    + by rewrite Mz.setP; case: eqP => //; nia.\n    by rewrite Mz.removeP; case: eqP => //; nia.\n  Qed.\n\n  Lemma get_sub_get8 aa ws lena a len p a' : \n    @get_sub lena aa ws len a p = ok a' -> \n    forall k,\n      read a' k U8 = \n        let start := (p * mk_scale aa ws)%Z in\n        if (0 <=? k) && (k <? arr_size ws len) then read a (start + k) U8\n        else Error ErrOob.\n  Proof.\n    rewrite /get_sub; case: andP => // -[/ZleP h1 /ZleP h2] [<-] /= k.\n    rewrite -!get_read8 /memory_model.get /= /get8 /is_init /in_bound get_sub_data_get8 /=.\n    case: andP; rewrite !zify //= => ?; case: andP; rewrite !zify //= => ?; lia.\n  Qed.\n\n  Lemma get_sub_bound aa ws lena a len p a' :\n    @get_sub lena aa ws len a p = ok a' ->\n    0 <= p * mk_scale aa ws /\\ p * mk_scale aa ws + arr_size ws len <= lena.\n  Proof. by rewrite /get_sub; case: ifP => //; rewrite !zify. Qed.\n\n  Lemma uincl_get_sub {len1 len2} (a1 : array len1) (a2 : array len2) \n      aa ws len i t1 :\n    uincl a1 a2 ->\n    get_sub aa ws len a1 i = ok t1 ->\n    exists2 t2, get_sub aa ws len a2 i = ok t2 & uincl t1 t2.\n  Proof. \n    move=> [hlen hu] hget.\n    have := get_sub_get8 hget.\n    have := @get_sub_get8 aa ws len2 a2 len i _.\n    move: hget; rewrite /get_sub; case: andP => // -[/ZleP h1 /ZleP h2] [_].\n    case: andP; rewrite !zify => h3; last by lia.\n    move=> /(_ _ refl_equal) hr2 hr1; eexists => //; split; first by lia.\n    by move=> k w; rewrite hr1 hr2; case: ifP => // ? /hu.\n  Qed.\n\n  Lemma uincl_set_sub {ws len1 len2 len} (a1 a1': array len1) (a2: array len2) aa i \n        (t1 t2:array (Z.to_pos (arr_size ws len))) :\n    uincl a1 a2 -> uincl t1 t2 ->\n    set_sub aa a1 i t1 = ok a1' ->\n    exists2 a2', set_sub aa a2 i t2 = ok a2' & uincl a1' a2'.\n  Proof.\n    move=> [hlen1 hget1] [hlen2 hget2] hset.\n    have := set_sub_get8 hset.\n    have := @set_sub_get8 aa ws len2 a2 len i _.\n    move: hset; rewrite /set_sub; case: andP => // -[/ZleP h1 /ZleP h2] [_].\n    case: andP; rewrite !zify => h3; last by lia.\n    move=> /(_ _ _ refl_equal) hr2 hr1; eexists => //; split; first by lia.\n    by move=> k w; rewrite hr1 hr2; case: ifP => // [ ? /hget2| ? /hget1].\n  Qed.\n\nEnd WArray.\n\n#[global]\nHint Resolve WArray.uincl_refl : core.\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/warray_.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.27711612947756287}}
{"text": "Lemma and_commutative : forall A B, A /\\ B -> B /\\ A.\nProof.\n  intros.\n  elim H.\n  split.\n  exact H1.\n  exact H0.\nQed.\n\nLemma or_commutative : forall A B, A \\/ B -> B \\/ A.\nProof.\n  intros.\n  destruct H.\n  right; exact H.\n  left; exact H.\nQed.s", "meta": {"author": "Riib11", "repo": "Coq-Work", "sha": "e163edd331fd15549910f0fe0a361bc93ca951d7", "save_path": "github-repos/coq/Riib11-Coq-Work", "path": "github-repos/coq/Riib11-Coq-Work/Coq-Work-e163edd331fd15549910f0fe0a361bc93ca951d7/Practice/PredicateLogics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2771161294775628}}
{"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\n   dependent *)\n\nRequire Export reduce.\nRequire Export DistributedReferenceCounting.machine3.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/machine3/cardinal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.27711612305860034}}
{"text": "Require Import Coq.omega.Omega.\nRequire Import Bedrock.Platform.AutoSep.\n\nRequire Import Bedrock.Platform.Malloc Bedrock.Platform.Cito.examples.Seq.\n\nModule Type ADT.\n  Parameter arr : list W -> W -> HProp.\n\n  Axiom arr_fwd : forall ws self, arr ws self ===> [| self <> 0 |] * [| freeable self (2 + length ws) |]\n    * [| goodSize (2 + length ws) |]\n    * (Ex junk, self ==*> $ (length ws), junk)\n    * array ws (self ^+ $8).\n  Axiom arr_bwd : forall ws (self : W), [| self <> 0 |] * [| freeable self (2 + length ws) |]\n    * [| goodSize (2 + length ws) |]\n    * (Ex junk, self ==*> $ (length ws), junk)\n    * array ws (self ^+ $8) ===> arr ws self.\nEnd ADT.\n\nModule Adt : ADT.\n  Open Scope Sep_scope.\n\n  Definition arr (ws : list W) (self : W) : HProp :=\n    [| self <> 0 |] * [| freeable self (2 + length ws) |] * [| goodSize (2 + length ws) |]\n    * (Ex junk, self ==*> $ (length ws), junk)\n    * array ws (self ^+ $8).\n\n  Theorem arr_fwd : forall ws self, arr ws self ===> [| self <> 0 |] * [| freeable self (2 + length ws) |]\n    * [| goodSize (2 + length ws) |]\n    * (Ex junk, self ==*> $ (length ws), junk)\n    * array ws (self ^+ $8).\n    unfold arr; sepLemma.\n  Qed.\n\n  Theorem arr_bwd : forall ws (self : W), [| self <> 0 |] * [| freeable self (2 + length ws) |]\n    * [| goodSize (2 + length ws) |]\n    * (Ex junk, self ==*> $ (length ws), junk)\n    * array ws (self ^+ $8) ===> arr ws self.\n    unfold arr; sepLemma.\n  Qed.\nEnd Adt.\n\nImport Adt.\nExport Adt.\n\nLemma allocated_out'' : forall p len offset,\n  allocated p offset len ===> Ex ws, ptsto32m' nil p offset ws * [| length ws = len |].\n  induction len; sepLemmaLhsOnly.\n  apply himp_ex_c; exists nil; sepLemma.\n  etransitivity; [ apply himp_star_frame; [ apply IHlen | reflexivity ] | ].\n  sepLemmaLhsOnly.\n  apply himp_ex_c; exists (x :: x0); sepLemma.\n  destruct offset; sepLemma.\nQed.\n\nLemma allocated_out' : forall p len offset,\n  allocated p offset len ===> Ex ws, ptsto32m nil p offset ws * [| length ws = len |].\n  intros; eapply Himp_trans; [ apply allocated_out'' | ].\n  apply Himp_ex; intro.\n  apply Himp_star_frame; try apply Himp_refl.\n  apply ptsto32m'_out.\nQed.\n\nInductive view_shift (n : nat) := ViewShift.\nLocal Hint Constructors view_shift.\n\nLemma allocated_out : forall p offset len,\n  view_shift offset\n  -> allocated p offset len ===> Ex ws, array ws (p ^+ $ (offset)) * [| length ws = len |].\n  intros; eapply Himp_trans; [ apply allocated_out' | ].\n  apply Himp_ex; intro.\n  apply Himp_star_frame; try apply Himp_refl.\n  eapply Himp_trans; [ apply ptsto32m_shift_base' | ].\n  instantiate (1 := offset); auto.\n  rewrite Minus.minus_diag; apply Himp_refl.\nQed.\n\nLemma allocated_in'' : forall p len offset,\n  (Ex ws, ptsto32m' nil p offset ws * [| length ws = len |]) ===> allocated p offset len.\n  induction len; sepLemmaLhsOnly.\n  destruct x; sepLemma.\n  destruct x; sepLemma.\n  apply himp_star_frame.\n  etransitivity; [ | apply IHlen ].\n  sepLemma.\n  destruct offset; sepLemma.\nQed.\n\nLemma allocated_in' : forall p len offset,\n  (Ex ws, ptsto32m nil p offset ws * [| length ws = len |]) ===> allocated p offset len.\n  intros; eapply Himp_trans; [ | apply allocated_in'' ].\n  apply Himp_ex; intro.\n  apply Himp_star_frame; try apply Himp_refl.\n  apply Arrays.ptsto32m'_in.\nQed.\n\nLemma allocated_in : forall p ws,\n  goodSize (S (S (length ws)))\n  -> p =?> 2 * array ws (p ^+ $8) ===> p =?> wordToNat (natToW (S (S (length ws)))).\n  intros.\n\n  replace (wordToNat (natToW (S (S (length ws))))) with (S (S (length ws))).\n  eapply Himp_trans; [ | apply allocated_join ].\n  apply Himp_star_frame; try apply Himp_refl.\n  2: auto.\n  simpl.\n  eapply Himp_trans; [ | apply allocated_in' ].\n  sepLemma.\n  instantiate (1 := ws); omega.\n  etransitivity; [ | apply ptsto32m_shift_base ].\n  instantiate (1 := 8); reflexivity.\n  auto.\n  rewrite wordToNat_natToWord_idempotent; auto.\nQed.\n\nDefinition hints : TacPackage.\n  prepare (arr_fwd, allocated_out) (arr_bwd, allocated_in).\nDefined.\n\nDefinition newS := newS arr 8.\nDefinition deleteS := deleteS arr 7.\nDefinition readS := readS arr 0.\nDefinition writeS := writeS arr 0.\n\nDefinition m := bimport [[ \"malloc\"!\"malloc\" @ [mallocS], \"malloc\"!\"free\" @ [freeS] ]]\n  bmodule \"ArraySeq\" {{\n    bfunction \"new\"(\"extra_stack\", \"len\", \"x\") [newS]\n      \"x\" <- 2 + \"len\";;\n      \"x\" <-- Call \"malloc\"!\"malloc\"(0, \"x\")\n      [PRE[V, R] R =?> (2 + wordToNat (V \"len\"))\n        * [| R <> 0 |] * [| freeable R (2 + wordToNat (V \"len\")) |]\n        * [| goodSize (2 + wordToNat (V \"len\")) |] * mallocHeap 0\n       POST[R'] Ex ws, arr ws R' * [| length ws = wordToNat (V \"len\") |] * mallocHeap 0];;\n\n      \"x\" *<- \"len\";;\n      Note [view_shift 8];;\n      Return \"x\"\n    end\n\n    with bfunction \"delete\"(\"extra_stack\", \"self\", \"x\") [deleteS]\n      \"x\" <-* \"self\";;\n      \"x\" <- 2 + \"x\";;\n      Call \"malloc\"!\"free\"(0, \"self\", \"x\")\n      [PRE[_] Emp\n       POST[_] Emp];;\n\n      Return 0\n    end\n\n    with bfunction \"read\"(\"extra_stack\", \"self\", \"n\") [readS]\n      \"n\" <- 4 * \"n\";;\n      \"self\" <- \"self\" + 8;;\n      \"self\" <-* \"self\" + \"n\";;\n      Return \"self\"\n    end\n\n    with bfunction \"write\"(\"extra_stack\", \"self\", \"n\", \"v\") [writeS]\n      \"n\" <- 4 * \"n\";;\n      \"self\" <- \"self\" + 8;;\n      \"self\" + \"n\" *<- \"v\";;\n      Return 0\n    end\n  }}.\n\nLocal Hint Extern 1 (@eq W _ _) => words.\n\nLemma twoPlus_le : forall w,\n  goodSize (2 + wordToNat w)\n  -> natToW 2 <= natToW 2 ^+ w.\n  intros.\n  rewrite <- (natToWord_wordToNat w).\n  rewrite <- natToWord_plus.\n  apply le_goodSize; auto.\nQed.\n\nLocal Hint Immediate twoPlus_le.\n\nLocal Hint Extern 1 (himp _ _ _) =>\n  match goal with\n    | [ H : _ = wordToNat _ |- _ ] =>\n      rewrite H; unfold natToW; rewrite natToWord_wordToNat; solve [ step auto_ext ]\n  end.\n\nLemma twoPlus_freeable : forall w len,\n  freeable w (S (S len))\n  -> goodSize (S (S len))\n  -> freeable w (wordToNat (natToW (S (S len)))).\n  intros; rewrite wordToNat_natToWord_idempotent; auto.\nQed.\n\nLocal Hint Immediate twoPlus_freeable.\n\nSection hints.\n  Hint Rewrite wordToNat_wplus using assumption : sepFormula.\n\n  Theorem ok : moduleOk m.\n    vcgen; abstract (sep hints; auto).\n  Qed.\nEnd hints.\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/examples/ArraySeq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2771117214475442}}
{"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 IEEE.\n\nDefinition t := Single.\n\nDefinition m := Rounding_nearest.\n\nDefinition test_add (x y : diadic) :=\n  (Dadd x y,\n  diadic_of_abstract t\n    (fst\n       (abstract_add t m (abstract_of_diadic t m x)\n          (abstract_of_diadic t m y)))).\n\nDefinition verif (x y : diadic) := let (s1, s2) := test_add x y in Deq s1 s2.\n\nDefinition t1 := Diadic 10456 0.\nDefinition t2 := Diadic 10456 1.", "meta": {"author": "coq-contribs", "repo": "ieee754", "sha": "9764c31bae03182ba9ada4cc877f411c11edc02d", "save_path": "github-repos/coq/coq-contribs-ieee754", "path": "github-repos/coq/coq-contribs-ieee754/ieee754-9764c31bae03182ba9ada4cc877f411c11edc02d/tests.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.2770372241015033}}
{"text": "Require Import Coq.Program.Equality.\nRequire Import Coq.Sets.Ensembles.\nRequire Import Coq.FSets.FMapAVL. \nRequire Import Coq.Structures.OrderedTypeEx.\nRequire Import Coq.Arith.Peano_dec.\nRequire Import Ascii String.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.Arith.Mult.\nRequire Import Coq.Arith.Plus.\nRequire Import Coq.Arith.Minus.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Arith.Compare_dec.\n\nAdd LoadPath \".\" as Top0.\nRequire Import Top0.Keys.\nRequire Import Top0.Heap.\nRequire Import Top0.Environment.\nRequire Import Top0.Definitions.\nRequire Import Top0.CorrectnessLemmas.\n\nLemma Seq_Left_Pres :\n  forall phi1 phi1' heap1 heap1' n1 phi2,\n    (phi1, heap1) =a=>* (phi1', heap1', n1) ->\n    (Phi_Seq phi1 phi2, heap1) =a=>* (Phi_Seq phi1' phi2, heap1', n1).\nProof.\n  intros phi1 phi1' heap1 heap1' n1 phi2 HSteps.\n  dependent induction HSteps; repeat econstructor; eassumption.\nQed.\n\nLemma Seq_Right_Pres :\n  forall phi2 phi2' heap2 heap2' n2,\n    (phi2, heap2) =a=>* (phi2', heap2', n2) ->\n    (Phi_Seq Phi_Nil phi2, heap2) =a=>* (Phi_Seq Phi_Nil phi2', heap2', n2).\nProof.\n  intros phi2 phi2' heap2 heap2' n2 HSteps.\n  dependent induction HSteps; repeat econstructor; eassumption.\nQed.\n\nLemma Par_Left_Pres :\n  forall phi1 phi1' heap1 heap1' n1 phi2,\n    (phi1, heap1) =a=>* (phi1', heap1', n1) ->\n    (Phi_Par phi1 phi2, heap1) =a=>* (Phi_Par phi1' phi2, heap1', n1).\nProof.\n  intros phi1 phi1' heap1 heap1' n1 phi2 HSteps.\n  dependent induction HSteps; repeat econstructor; eassumption.\nQed.\n\nLemma Par_Right_Pres :\n  forall phi2 phi2' heap2 heap2' n2 phi1 ,\n    (phi2, heap2) =a=>* (phi2', heap2', n2) ->\n    (Phi_Par phi1 phi2, heap2) =a=>* (Phi_Par phi1 phi2', heap2', n2).\nProof.\n  intros phi2 phi2' heap2 heap2' n2 phi1 HSteps.\n  dependent induction HSteps; repeat econstructor; eassumption.\nQed.\n\n\n\nLemma H_same_key:\n  forall t x v e, \n    H.find (elt := t) x (H.add x v e) = Some v.\nProof.\n  intros. rewrite <- HMapP.find_mapsto_iff. rewrite -> HMapP.add_mapsto_iff.\n  left. intuition. \nQed.  \n\nLemma H_diff_key_1:\n  forall t a b v v' e,   \n    a <> b ->\n    H.find (elt := t) a (H.add b v e) = Some v' -> \n    H.find (elt := t) a e = Some v'.\nProof.\n  intros. \n  rewrite <- HMapP.find_mapsto_iff in H0. rewrite -> HMapP.add_mapsto_iff in H0.\n  destruct H0 as [ [[? ?] ?] |  [ ? ?]].\n  - destruct a. destruct b. simpl in *. destruct H. subst. reflexivity.\n  - rewrite -> HMapP.find_mapsto_iff in H1. assumption. \nQed.\n\nLemma H_diff_key_2:\n  forall t a b v v' e,   \n    b <> a ->\n    H.find (elt := t) a e = Some v' ->\n    H.find (elt := t) a (H.add b v e) = Some v'.\nProof.\n  intros. \n  rewrite <- HMapP.find_mapsto_iff.  rewrite -> HMapP.add_mapsto_iff.\n  right; split.\n  - intuition. apply H. destruct a. destruct b. simpl in *. subst. reflexivity.\n  - now rewrite HMapP.find_mapsto_iff.\nQed.\n\nLemma H_same_key_add_twice_1 :\n  forall r0 l0 r l v v0 heap, \n    H.find (elt:=Val) (r0, l0) (H.add (r0, l0) v0 (H.add (r, l) v heap)) = H.find (elt:=Val) (r0, l0) (H.add (r0, l0) v0 heap).\nProof.\n  intros. rewrite H_same_key. rewrite H_same_key. reflexivity.\nQed. \n\nLemma H_same_key_add_twice_2 :\n  forall k k0 v v0 heap,\n    k <> k0 ->\n    H.find (elt:=Val) k0 (H.add k v (H.add k0 v0 heap)) = H.find (elt:=Val) k0 (H.add k0 v0 heap).\nProof.\n  intros. rewrite H_same_key. apply H_diff_key_2; [assumption | apply H_same_key]. \nQed.\n\nLemma H_same_key_add_twice_3 :\n  forall k k0 v v0 heap,\n    H.find (elt:=Val) k0 (H.add k0 v0 (H.add k v heap)) = H.find (elt:=Val) k0 (H.add k0 v0 heap).\nProof.\n  intros. rewrite H_same_key. symmetry. apply H_same_key. \nQed. \n\nLemma H_diff_key_add_twice_1 :\n  forall k0 k heap (v v0 e: Val), \n    H.find (elt:=Val) k0 (H.add k0 v0 heap) = Some e ->\n    H.find (elt:=Val) k0 (H.add k0 v0 (H.add k v heap)) = Some e.\nProof.\n  intros k0 k heap v v0 e H.\n  rewrite H_same_key_add_twice_3. assumption.\nQed.\n\nLemma H_diff_key_add_twice_2 :\n  forall k0 k heap (v v0 e: Val),\n    k <> k0 ->\n    H.find (elt:=Val) k (H.add k v heap) = Some e ->\n    H.find (elt:=Val) k (H.add k v (H.add k0 v0 heap)) = Some e.\nProof.\n  intros k0 k heap v v0 e H. intro. \n  rewrite H_same_key_add_twice_3. auto. \nQed.\n\nLemma H_diff_key_add_comm_1:\n  forall k k1 k0 heap e v v0,\n    k1 <> k ->\n    k <> k0 ->\n    H.find (elt:=Val) k (H.add k0 v0 (H.add k1 v heap)) = Some e ->\n    H.find (elt:=Val) k (H.add k1 v heap) = Some e. \nProof.\n  intros  k k1 k0 heap e v v0 H1 H2 H3.\n  rewrite <- HMapP.find_mapsto_iff.  rewrite -> HMapP.add_mapsto_iff.\n  right. split.\n  - contradict H1. destruct k1; destruct k.  unfold fst, snd in *. intuition.\n  - apply  H_diff_key_1 in H3; auto. apply  H_diff_key_1 in H3; auto. now rewrite HMapP.find_mapsto_iff.\nQed.\n\nLemma H_diff_key_add_comm_2:\n  forall k k1 k0 heap e v v0,\n    k1 <> k ->\n    k <> k0 ->\n    H.find (elt:=Val) k (H.add k1 v heap) = Some e ->\n    H.find (elt:=Val) k (H.add k1 v (H.add k0 v0 heap)) = Some e. \nProof.\n  intros  k k1 k0 heap e v v0 H1 H2 H3.\n  rewrite <- HMapP.find_mapsto_iff.  rewrite -> HMapP.add_mapsto_iff.\n  right. split.\n  - contradict H1. destruct k1; destruct k.  unfold fst, snd in *. intuition.\n  - apply  H_diff_key_1 in H3; auto. rewrite HMapP.find_mapsto_iff. apply  H_diff_key_2; auto. \nQed.\n\n\nLemma H_diff_keys_same_outer_k_2 :\n  forall r r0 r1 l l0 l1 v v0  heap e, \n    (r0, l0) <> (r, l) -> \n    H.find (elt:=Val) (r1, l1) (H.add (r, l) v (H.add (r0, l0) v0 heap)) = Some e ->\n    H.find (elt:=Val) (r1, l1) (update_H (r0, l0, v0) (update_H (r, l, v) heap)) = Some e.\nProof.\n  intros  r r0 r1 l l0 l1 v v0 heap e H1 H2. \n  destruct (RegionVars.eq_dec (r1, l1) (r0, l0)); destruct (RegionVars.eq_dec (r1, l1) (r, l)).\n  - destruct e0. simpl in *. subst. unfold update_H in *; simpl in *.\n    apply  H_diff_key_add_twice_2; auto.\n    apply  H_diff_key_1 in H2; auto.\n  - destruct e0. simpl in *. rewrite H in *.  rewrite H0 in *.\n    apply  H_diff_key_1 in H2; auto. apply H_diff_key_add_twice_2; auto.\n  - destruct e0. simpl in *. rewrite H in *.  rewrite H0 in *.\n    apply  H_diff_key_2; auto.\n    rewrite  H_same_key_add_twice_3 in H2; auto.\n  - apply  H_diff_key_2; auto. \n    + unfold  RegionVars.eq in n. contradict n. inversion n. intuition.\n    + apply  H_diff_key_2; auto.\n      * unfold  RegionVars.eq in n0. contradict n0. inversion n0. intuition.\n      * apply  H_diff_key_1 in H2. apply  H_diff_key_1 in H2; auto.\n        { unfold  RegionVars.eq in n. contradict n. inversion n. intuition. }\n        { unfold  RegionVars.eq in n0. contradict n0. inversion n0. intuition. }\nQed.\n\nLemma Read_Preserved :\n  forall r1 l1 v1 phi2 phi2' heap0 heap2',\n    H.find (r1, l1) heap0 = Some v1 ->\n    Disjoint_Traces (phi_as_list (Phi_Elem (DA_Read r1 l1 v1))) (phi_as_list phi2) ->\n    (phi2, heap0) ===> (phi2', heap2') ->\n    H.find (r1, l1) heap2' = Some v1.\nProof.\n  intros r1 l1 v1 phi2 phi2' heap0 heap2' HFind HDisj HStep.\n  dependent induction HStep.\n  - assert (Disjoint_Dynamic (DA_Read r1 l1 v1) (DA_Alloc r l v))\n      by (inversion HDisj; apply H; simpl; intuition).\n    inversion H; subst.\n    apply H_diff_key_2; auto.\n  - assumption.\n  - assert (Disjoint_Dynamic (DA_Read r1 l1 v1) (DA_Write r l v))\n      by (inversion HDisj; apply H0; simpl; intuition).\n    inversion H0; subst.\n    apply H_diff_key_2; auto.\n  - eapply IHHStep; try reflexivity.\n    + eassumption.\n    + replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0) in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj; intuition.\n  - eapply IHHStep; try reflexivity.\n    + eassumption.\n    + replace (phi_as_list (Phi_Seq Phi_Nil phi0)) with (phi_as_list Phi_Nil ++ phi_as_list phi0) in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj; intuition.\n  - assumption.\n  - eapply IHHStep; try reflexivity.\n    + eassumption.\n    + replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0) in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj; intuition.\n  - eapply IHHStep; try reflexivity.\n    + eassumption.\n    + replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0) in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj; intuition.\n  - assumption.\nQed.\n\nLemma Disjointness_Preserves_Update_Alloc:\n  forall phi1 phi1' heap heap' r l v, \n  (phi1, heap) ===> (phi1', heap') ->\n  Disjoint_Traces (DA_Alloc r l v :: nil) (phi_as_list phi1) ->\n  exists heapA,\n    H.Equal heapA (update_H (r, l, v) heap') /\\\n    (phi1, update_H (r, l, v) heap) ===> (phi1', heapA).\nProof.\n  intros phi1 phi1' heap heap' r l v H1 H2.\n  generalize dependent r.\n  generalize dependent l.\n  generalize dependent v. \n  dependent induction H1; intros; inversion H2; subst; simpl in H.\n  - assert (Disjoint_Dynamic (DA_Alloc r0 l0 v0) (DA_Alloc r l v)) by (apply H; intuition).\n    inversion H0; subst. \n    exists (update_H (r, l, v) (update_H (r0, l0, v0) heap)). split. \n    + apply HMapP.Equal_mapsto_iff; intros. split; intros. \n      * apply HMapP.find_mapsto_iff. apply HMapP.find_mapsto_iff in H1.\n        destruct k; apply H_diff_keys_same_outer_k_2; auto.\n      * apply HMapP.find_mapsto_iff. apply HMapP.find_mapsto_iff in H1.\n        destruct k.  apply H_diff_keys_same_outer_k_2; auto.\n    + constructor.\n  - assert (Disjoint_Dynamic (DA_Alloc r0 l0 v0) (DA_Read r l v)) by (apply H0; apply in_eq).\n    inversion H1; subst. exists ( update_H (r0, l0, v0) heap'). split.\n    + apply HMapP.Equal_refl.\n    + constructor.\n      apply  H_diff_key_2; [ simpl | ]; assumption.\n  - assert (Disjoint_Dynamic (DA_Alloc r0 l0 v0) (DA_Write r l v)) by (apply H0; apply in_eq).\n    inversion H1; subst. unfold update_H; simpl. \n    exists (H.add (r, l) v ( H.add (r0, l0) v0 heap)). split. \n    + apply HMapP.Equal_mapsto_iff; intros. split; intros. \n      * apply HMapP.find_mapsto_iff. apply HMapP.find_mapsto_iff in H3.\n        destruct k; apply H_diff_keys_same_outer_k_2; auto.\n      * apply HMapP.find_mapsto_iff. apply HMapP.find_mapsto_iff in H3.\n        destruct k; apply H_diff_keys_same_outer_k_2; auto.\n    + constructor.\n      apply HMapP.add_neq_in_iff; auto. simpl. intuition.\n      (*eapply H_diff_key_2; eauto.*)\n  - simpl in H2. replace (DA_Alloc r l v :: nil) with (phi_as_list (Phi_Elem (DA_Alloc r l v))) in H2\n      by (simpl; reflexivity).\n    apply Disjointness_app_app_and_l in H2. destruct H2.\n    destruct (IHPhi_Heap_Step  v l r H0). exists x; intuition.\n    constructor; assumption.\n  - destruct (IHPhi_Heap_Step  v l r H2). exists x; intuition.\n    constructor; assumption.\n  - exists (update_H (r, l, v) heap'). split; [apply HMapP.Equal_refl | constructor ].\n  - simpl in H2. replace (DA_Alloc r l v :: nil) with (phi_as_list (Phi_Elem (DA_Alloc r l v))) in H2\n      by (simpl; reflexivity).\n    apply Disjointness_app_app_and_l in H2. destruct H2.\n    destruct (IHPhi_Heap_Step  v l r H0). exists x; intuition.\n    constructor; assumption.\n  -  simpl in H2. replace (DA_Alloc r l v :: nil) with (phi_as_list (Phi_Elem (DA_Alloc r l v))) in H2\n      by (simpl; reflexivity).\n    apply Disjointness_app_app_and_l in H2. destruct H2.\n    destruct (IHPhi_Heap_Step  v l r H2). exists x; intuition.\n    constructor; assumption.\n  - exists (update_H (r, l, v) heap'). split; [apply HMapP.Equal_refl | constructor ].\nQed.\n\nLemma Disjointness_Preserves_Update_Write:\n  forall phi1 phi1' heap heap' r l v, \n  (phi1, heap) ===> (phi1', heap') ->\n  Disjoint_Traces (DA_Write r l v :: nil) (phi_as_list phi1) ->\n  exists heapA,\n    H.Equal heapA (update_H (r, l, v) heap') /\\\n    (phi1, update_H (r, l, v) heap) ===> (phi1', heapA).\nProof.\n  intros phi1 phi1' heap heap' r l v H1 H2.\n  generalize dependent r.\n  generalize dependent l.\n  generalize dependent v.\n  dependent induction H1; intros; inversion H2; subst; simpl in H.\n  - assert (Disjoint_Dynamic (DA_Write r0 l0 v0) (DA_Alloc r l v)) by (apply H; intuition).\n    inversion H0; subst. \n    exists (update_H (r, l, v) (update_H (r0, l0, v0) heap)). split. \n    + apply HMapP.Equal_mapsto_iff; intros. split; intros. \n      * apply HMapP.find_mapsto_iff. apply HMapP.find_mapsto_iff in H1.\n        destruct k; apply H_diff_keys_same_outer_k_2; auto.\n      * apply HMapP.find_mapsto_iff. apply HMapP.find_mapsto_iff in H1.\n        destruct k.  apply H_diff_keys_same_outer_k_2; auto.\n    + constructor.\n  - assert (Disjoint_Dynamic (DA_Write r0 l0 v0) (DA_Read r l v)) by (apply H0; apply in_eq).\n    inversion H1; subst. exists ( update_H (r0, l0, v0) heap'). split.\n    + apply HMapP.Equal_refl.\n    + constructor.\n      apply  H_diff_key_2; [ intuition | assumption ]. \n  - assert (Disjoint_Dynamic (DA_Write r0 l0 v0) (DA_Write r l v)) by (apply H0; apply in_eq).\n    inversion H1; subst. unfold update_H; simpl. \n    exists (H.add (r, l) v ( H.add (r0, l0) v0 heap)). split. \n    + apply HMapP.Equal_mapsto_iff; intros. split; intros. \n      * apply HMapP.find_mapsto_iff. apply HMapP.find_mapsto_iff in H3.\n        destruct k; apply H_diff_keys_same_outer_k_2; auto.\n      * apply HMapP.find_mapsto_iff. apply HMapP.find_mapsto_iff in H3.\n        destruct k; apply H_diff_keys_same_outer_k_2; auto.\n    + constructor.\n      apply HMapP.add_neq_in_iff; auto. simpl. intuition.\n      (*eapply H_diff_key_2; eauto.*)\n  - simpl in H2. replace (DA_Write r l v :: nil) with (phi_as_list (Phi_Elem (DA_Write r l v))) in H2\n      by (simpl; reflexivity).\n    apply Disjointness_app_app_and_l in H2. destruct H2.\n    destruct (IHPhi_Heap_Step  v l r H0). exists x; intuition.\n    constructor; assumption.\n  - destruct (IHPhi_Heap_Step  v l r H2). exists x; intuition.\n    constructor; assumption.\n  - exists (update_H (r, l, v) heap'). split; [apply HMapP.Equal_refl | constructor ].\n  - simpl in H2. replace (DA_Write r l v :: nil) with (phi_as_list (Phi_Elem (DA_Write r l v))) in H2\n      by (simpl; reflexivity).\n    apply Disjointness_app_app_and_l in H2. destruct H2.\n    destruct (IHPhi_Heap_Step  v l r H0). exists x; intuition.\n    constructor; assumption.\n  -  simpl in H2. replace (DA_Write r l v :: nil) with (phi_as_list (Phi_Elem (DA_Write r l v))) in H2\n      by (simpl; reflexivity).\n    apply Disjointness_app_app_and_l in H2. destruct H2.\n    destruct (IHPhi_Heap_Step  v l r H2). exists x; intuition.\n    constructor; assumption.\n  - exists (update_H (r, l, v) heap'). split; [apply HMapP.Equal_refl | constructor ].\nQed.\n\nLemma Aux_Aux_Step_Ext_Heap :\nforall phi heapA heapB phi' heapA',\n   (phi, heapA) ===> (phi', heapA') ->\n   H.Equal heapA heapB ->\n   exists heapB',\n     H.Equal heapA' heapB' /\\\n     (phi, heapB) ===> (phi', heapB').\nProof.\n  intros phi heapA heapB phi' heapA' HStep.\n  generalize dependent heapB.\n  dependent induction HStep; intros heapB HEqual.\n  - { exists (update_H (r, l, v) heapB). split.\n      - unfold H.Equal in *; unfold update_H in *; simpl in *.\n        intros [r' l'].\n        destruct (RegionVars.eq_dec (r', l') (r, l)).\n        * inversion_clear e; simpl in *; subst.\n          do 2 rewrite H_same_key_1. reflexivity.\n        * unfold RegionVars.eq in *; simpl in *.\n          rewrite HMapP.add_neq_o by (contradict n; intuition).\n          rewrite HMapP.add_neq_o by (contradict n; intuition).\n          apply HEqual.\n      - constructor. }\n  - { exists heapB. split.\n      - assumption.\n      - constructor.\n        unfold find_H in *. unfold H.Equal in HEqual.\n        rewrite <- H. symmetry. apply HEqual. }\n  - { exists (update_H (r, l, v) heapB). split.\n      - unfold H.Equal in *; unfold update_H in *; simpl in *.\n        intros [r' l'].\n        destruct (RegionVars.eq_dec (r', l') (r, l)).\n        * inversion_clear e; simpl in *; subst.\n          do 2 rewrite H_same_key_1. reflexivity.\n        * unfold RegionVars.eq in *; simpl in *.\n          rewrite HMapP.add_neq_o by (contradict n; intuition).\n          rewrite HMapP.add_neq_o by (contradict n; intuition).\n          apply HEqual.\n      - constructor.\n        eapply Heap.HMapP.In_m; eauto using HMapP.Equal_sym. }\n  - destruct (IHHStep heapB HEqual) as [heapB' [? ?]].\n    exists heapB'; split; [assumption | constructor; auto].\n  - destruct (IHHStep heapB HEqual) as [heapB' [? ?]].\n    exists heapB'; split; [assumption | constructor; auto].\n  - exists heapB; split; [assumption | constructor].\n  - destruct (IHHStep heapB HEqual) as [heapB' [? ?]].\n    exists heapB'; split; [assumption | constructor; auto].\n  - destruct (IHHStep heapB HEqual) as [heapB' [? ?]].\n    exists heapB'; split; [assumption | constructor; auto].\n  - exists heapB; split; [assumption | constructor].\nQed.\n\nLemma Aux_Step_Ext_Heap :\nforall phi heapA heapB phi' heapA' n',\n   (phi, heapA) =a=>* (phi', heapA', n') ->\n   H.Equal heapA heapB ->\n   exists heapB',\n     H.Equal heapA' heapB' /\\\n     (phi, heapB) =a=>* (phi', heapB', n').\nProof.\n  intros  phi heapA heapB phi' heapA' n' H1 H2 .  \n  generalize dependent heapB. \n  dependent induction H1; intros.\n  - { exists heapB. intuition. constructor. }\n  - edestruct Aux_Aux_Step_Ext_Heap as [heapB' [? ?]]; eauto.\n    exists heapB'; split; [assumption | constructor; assumption].\n  - edestruct (IHPhi_Heap_StepsAux1 heapB H2) as [heap1 [? ?]].\n    edestruct (IHPhi_Heap_StepsAux2 heap1 H) as [heap2 [? ?]].\n    exists heap2. intuition.\n    replace (S (n'0 + n'')) with (1 + n'0 + n'') by (simpl; reflexivity).\n    econstructor. eassumption. assumption.\nQed.\n\nLemma Par_Step_Alloc_Alloc :\n  forall phi1 r1 l1 v1 phi2 r2 l2 v2 phi1' phi2' heapa heapb heap1' heap2',\n    phi1 = Phi_Elem (DA_Alloc r1 l1 v1) ->\n    phi2 = Phi_Elem (DA_Alloc r2 l2 v2) ->\n    Det_Trace phi1 ->\n    Det_Trace phi2 ->\n    Disjoint_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    H.Equal heapa heapb ->\n    (phi1, heapa) ===> (phi1', heap1') ->\n    (phi2, heapb) ===> (phi2', heap2') ->\n    exists heapA, exists heapB,\n      H.Equal heapA heapB /\\\n      (Phi_Par phi1' phi2, heap1') ===> (Phi_Par phi1' phi2', heapA) /\\\n      (Phi_Par phi1 phi2', heap2') ===> (Phi_Par phi1' phi2', heapB).\nProof.\n  intros  phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2'\n          H1 H2 Det1 HDet2 HDisj HConf HEqual HStep1 HStep2; subst.\n  inversion HStep1; inversion HStep2; subst.\n  exists (update_H (r0, l0, v0) (update_H (r, l, v) heapa)). exists (update_H (r, l, v) (update_H (r0, l0, v0) heapb)). repeat split. \n  - inversion HDisj; subst. simpl in H. \n    assert (Disjoint_Dynamic (DA_Alloc r l v) (DA_Alloc r0 l0 v0)) by (apply H; left; reflexivity).\n    inversion H0; subst. unfold update_H in *. simpl in *.\n    inversion H0; subst. unfold update_H in *. simpl in *. \n\n    destruct (RegionVars.eq_dec (r, l) (r0, l0)).\n    + inversion e. unfold fst, snd in *; subst.\n      destruct H2. reflexivity.\n    + clear n. \n      apply HMapP.Equal_mapsto_iff; intros. destruct k.\n      destruct (RegionVars.eq_dec (n, n0) (r0, l0)); destruct (RegionVars.eq_dec (n, n0) (r, l)); split.\n      * inversion e0; inversion e1. unfold fst, snd in *; subst.\n        destruct H2. subst; reflexivity.\n      * inversion e0; inversion e1. unfold fst, snd in *; subst.\n        destruct H2. subst; reflexivity.\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.\n        intro. apply  HMapP.find_mapsto_iff in H1.\n        rewrite H_same_key_add_twice_1 in H1. rewrite H_same_key in H1.\n        apply HMapP.add_mapsto_iff. right; simpl. split; [ intuition | ].\n        apply HMapP.find_mapsto_iff. rewrite H_same_key. assumption.\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst. \n        intro. apply  HMapP.find_mapsto_iff in H1. rewrite H_same_key_add_twice_2 in H1; [| assumption].\n        { rewrite H_same_key in H1.  apply  HMapP.find_mapsto_iff.\n          inversion H1; subst. rewrite H_same_key_add_twice_1. rewrite H_same_key. assumption. }\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.  \n        intro. apply HMapP.add_mapsto_iff. left. simpl. split; auto.   \n        apply  HMapP.find_mapsto_iff in H1.  rewrite H_same_key_add_twice_2 in H1; [| intuition].\n        rewrite HMapP.add_o in H1. \n        destruct (HMapP.eq_dec (r, l) (r, l)) in H1. \n        { inversion H1; subst. auto.  }\n        { simpl in *. contradict n. auto. } \n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst. \n        intro.  apply HMapP.add_mapsto_iff. right. split; simpl; [intuition |].\n        apply HMapP.add_mapsto_iff. left; simpl; split; auto.\n        apply HMapP.add_mapsto_iff in H1.\n        destruct H1 as [[? ?]| ?]; [assumption | destruct H1 as [? ?  ?]; contradict H1; auto].\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst.\n        intro. apply  HMapP.find_mapsto_iff in H1.\n        apply  HMapP.find_mapsto_iff.\n        { eapply H_diff_key_add_comm_2.\n          - contradict n2. inversion n2. auto.\n          - contradict n1. inversion n1. auto.\n          - apply H_diff_key_2.\n            + contradict n2. inversion n2. auto.\n            + rewrite <- H1. unfold H.Equal in HEqual. rewrite <- HEqual.\n              rewrite H1. apply H_diff_key_1 in H1.\n              * apply H_diff_key_1 in H1; [assumption | contradict n1; inversion n1; intuition].\n              * contradict n1; inversion n1; intuition.\n        }\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst.\n        intro. apply  HMapP.find_mapsto_iff in H1.\n        apply  HMapP.find_mapsto_iff.\n        { eapply H_diff_key_add_comm_2.\n          - contradict n1. inversion n1. auto.\n          - contradict n2. inversion n2. auto.\n          - apply H_diff_key_2.\n            + contradict n1. inversion n1. auto.\n            + rewrite <- H1. unfold H.Equal in HEqual. rewrite HEqual.\n              rewrite H1. apply H_diff_key_1 in H1.\n              * apply H_diff_key_1 in H1; [assumption | contradict n1; inversion n1; intuition].\n              * contradict n1; inversion n1; intuition.\n        }\n  - do 2 constructor.    \n  - econstructor. inversion HDisj; subst.\n    assert (Disjoint_Dynamic (DA_Alloc r l v) (DA_Alloc r0 l0 v0)) by (apply H; simpl; auto). \n    constructor.\nQed.\n\nLemma Par_Step_Write_Write :\n  forall phi1 r1 l1 v1 phi2 r2 l2 v2 phi1' phi2' heapa heapb heap1' heap2',\n    phi1 = Phi_Elem (DA_Write r1 l1 v1) ->\n    phi2 = Phi_Elem (DA_Write r2 l2 v2) ->\n    Det_Trace phi1 ->\n    Det_Trace phi2 ->\n    Disjoint_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    H.Equal heapa heapb ->\n    (phi1, heapa) ===> (phi1', heap1') ->\n    (phi2, heapb) ===> (phi2', heap2') ->\n    exists heapA, exists heapB,\n      H.Equal heapA heapB /\\\n      (Phi_Par phi1' phi2, heap1') ===> (Phi_Par phi1' phi2', heapA) /\\\n      (Phi_Par phi1 phi2', heap2') ===> (Phi_Par phi1' phi2', heapB).\nProof.\n  intros  phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2'\n          H1 H2 Det1 HDet2 HDisj HConf HEqual HStep1 HStep2; subst.\n  inversion HStep1; inversion HStep2; subst.\n  exists (update_H (r0, l0, v0) (update_H (r, l, v) heapa)). exists (update_H (r, l, v) (update_H (r0, l0, v0) heapb)). repeat split. \n  -  inversion HDisj; subst. simpl in H. \n    assert (Disjoint_Dynamic (DA_Write r l v) (DA_Write r0 l0 v0)) by (apply H; left; reflexivity).\n    inversion H1; subst. unfold update_H in *. simpl in *.\n    inversion H1; subst. unfold update_H in *. simpl in *. \n    destruct (RegionVars.eq_dec (r, l) (r0, l0)).\n    + inversion e. unfold fst, snd in *; subst.\n      inversion H1; subst. contradict H5. intuition.\n    + clear n. \n      apply HMapP.Equal_mapsto_iff; intros. destruct k.\n      destruct (RegionVars.eq_dec (n, n0) (r0, l0)); destruct (RegionVars.eq_dec (n, n0) (r, l)); split.\n      * inversion e0; inversion e1. unfold fst, snd in *; subst.\n        inversion H1; subst. contradict H5. intuition.\n      * inversion e0; inversion e1. unfold fst, snd in *; subst.\n        inversion H1; subst. contradict H5. intuition.\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.\n        intro. apply  HMapP.find_mapsto_iff in H2.\n        rewrite H_same_key_add_twice_1 in H2. rewrite H_same_key in H2.\n        apply HMapP.add_mapsto_iff. right; simpl. split; [ intuition | ].\n        apply HMapP.find_mapsto_iff. rewrite H_same_key. assumption.\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.\n        intro. apply  HMapP.find_mapsto_iff in H2. rewrite H_same_key_add_twice_2 in H2.\n        { rewrite H_same_key in H2.  apply  HMapP.find_mapsto_iff.\n          inversion H2; subst. rewrite H_same_key_add_twice_1. rewrite H_same_key. assumption. }\n        { contradict n1. inversion n1. intuition. }\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.\n        intro. apply  HMapP.find_mapsto_iff in H2. rewrite H_same_key_add_twice_2 in H2.\n        { apply HMapP.add_mapsto_iff. left. simpl. split; auto.\n          rewrite HMapP.add_o in H2. \n          destruct (HMapP.eq_dec (r, l) (r, l)) in H2;\n          [inversion H2; subst;  reflexivity |  simpl in n; contradict n; auto]. }\n        { contradict n1. inversion n1. intuition. }\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.\n        intro. apply  HMapP.find_mapsto_iff in H2. rewrite H_same_key_add_twice_1 in H2. apply  HMapP.find_mapsto_iff in H2.  \n        apply  HMapP.find_mapsto_iff.\n        apply H_diff_key_2; [contradict H3; assumption | ].\n        apply HMapP.find_mapsto_iff.\n        apply HMapP.add_mapsto_iff. left; simpl. split; auto.\n        apply HMapP.add_mapsto_iff in H2.\n        destruct H2 as [ [ ?  ?] | [? ?] ]; [assumption | contradict H2; intuition]. \n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst.\n        intro. apply  HMapP.find_mapsto_iff in H2.\n        apply  HMapP.find_mapsto_iff.\n        { eapply H_diff_key_add_comm_2.\n          - contradict n2. inversion n2. auto.\n          - contradict n1. inversion n1. auto.\n          - apply H_diff_key_2.\n            + contradict n2. inversion n2. auto.\n            + unfold H.Equal in HEqual. rewrite <- HEqual.\n              apply H_diff_key_1 in H2.\n              * apply H_diff_key_1 in H2; [assumption | contradict n2; inversion n2; auto]. \n              * contradict n1; inversion n1; auto.\n        }\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst.\n        intro. apply  HMapP.find_mapsto_iff in H2.\n        apply  HMapP.find_mapsto_iff.\n        { eapply H_diff_key_add_comm_2.\n          - contradict n1. inversion n1. auto.\n          - contradict n2. inversion n2. auto.\n          - apply H_diff_key_2.\n            + contradict n1. inversion n1. auto.\n            +unfold H.Equal in HEqual. rewrite HEqual.\n              apply H_diff_key_1 in H2.\n              * apply H_diff_key_1 in H2; [assumption | contradict n1; inversion n1; intuition].\n              * contradict n1; inversion n1; intuition.\n        }        \n  - do 2 constructor.\n    inversion HDisj; subst. simpl in H. \n    assert (Disjoint_Dynamic (DA_Write r l v) (DA_Write r0 l0 v0)) by (apply H; left; reflexivity).\n    inversion H1; subst. apply HMapP.add_neq_in_iff; auto; [simpl; intuition | ].\n    apply HMapP.Equal_Equiv in HEqual. inversion HEqual. apply H2. assumption.\n  - do 2 constructor.\n    inversion HDisj; subst. simpl in H. \n    assert (Disjoint_Dynamic (DA_Write r l v) (DA_Write r0 l0 v0)) by (apply H; left; reflexivity).\n    inversion H1; subst. apply HMapP.add_neq_in_iff; auto; [simpl; intuition | ].\n    apply HMapP.Equal_Equiv in HEqual. inversion HEqual. apply H2. assumption.\nQed.\n\nLemma Par_Step_Alloc_Read :\n  forall phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2',\n    phi1 = Phi_Elem (DA_Alloc r l v) ->\n    phi2 = Phi_Elem (DA_Read r0 l0 v0) -> \n    Det_Trace phi1 ->\n    Det_Trace phi2 ->\n    Disjoint_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    H.Equal heapa heapb ->\n    (phi1, heapa) ===> (phi1', heap1') ->\n    (phi2, heapb) ===> (phi2', heap2') ->\n    exists heapA heapB,\n      H.Equal heapA heapB /\\\n      (Phi_Par phi1' phi2, heap1') ===> (Phi_Par phi1' phi2', heapA) /\\\n      (Phi_Par phi1 phi2', heap2') ===> (Phi_Par phi1' phi2', heapB).\nProof.\n  intros  phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2'\n          H1 H2 Det1 HDet2 HDisj HConf HEqual HStep1 HStep2; subst.\n  inversion HStep1; inversion HStep2; subst.\n  edestruct Aux_Aux_Step_Ext_Heap as [heapB' [? ?]]; eauto. \n  exists (update_H (r, l, v) heapa); exists heapB'; repeat split.\n  - assumption.\n  - do 2 constructor.\n    inversion HDisj; subst. simpl in H. \n    assert (Disjoint_Dynamic (DA_Alloc r l v) (DA_Read r0 l0 v0)) by (apply H1; left; reflexivity).\n    inversion H2; subst. eapply H_diff_key_2; eauto.\n    unfold H.Equal in HEqual. rewrite HEqual. assumption.\n  - constructor. assumption.\nQed.\n\nLemma Par_Step_Write_Read :\n  forall phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2',\n    phi1 = Phi_Elem (DA_Write r l v) ->\n    phi2 = Phi_Elem (DA_Read r0 l0 v0) -> \n    Det_Trace phi1 ->\n    Det_Trace phi2 ->\n    Disjoint_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    H.Equal heapa heapb ->\n    (phi1, heapa) ===> (phi1', heap1') ->\n    (phi2, heapb) ===> (phi2', heap2') ->\n    exists heapA heapB,\n      H.Equal heapA heapB /\\\n      (Phi_Par phi1' phi2, heap1') ===> (Phi_Par phi1' phi2', heapA) /\\\n      (Phi_Par phi1 phi2', heap2') ===> (Phi_Par phi1' phi2', heapB).\nProof.\n  intros  phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2'\n          H1 H2 Det1 HDet2 HDisj HConf HEqual HStep1 HStep2; subst.\n  inversion HStep1; inversion HStep2; subst.\n  edestruct Aux_Aux_Step_Ext_Heap as [heapB' [? ?]]; eauto. \n  exists (update_H (r, l, v) heapa); exists heapB'; repeat split.\n  - assumption.\n  - do 2 constructor. \n    inversion HDisj; subst. simpl in H. \n    assert (Disjoint_Dynamic (DA_Write r l v) (DA_Read r0 l0 v0)) by (apply H2; left; reflexivity).\n    inversion H3; subst. eapply H_diff_key_2; eauto.\n    unfold H.Equal in HEqual. rewrite HEqual. assumption.\n  - constructor. assumption.\nQed.\n\nLemma Par_Step_Read_Alloc :\n  forall phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2',\n    phi1 = Phi_Elem (DA_Read r l v) ->\n    phi2 = Phi_Elem (DA_Alloc r0 l0 v0) -> \n    Det_Trace phi1 ->\n    Det_Trace phi2 ->\n    Disjoint_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    H.Equal heapa heapb ->\n    (phi1, heapa) ===> (phi1', heap1') ->\n    (phi2, heapb) ===> (phi2', heap2') ->\n    exists heapA heapB,\n      H.Equal heapA heapB /\\\n      (Phi_Par phi1' phi2, heap1') ===> (Phi_Par phi1' phi2', heapA) /\\\n      (Phi_Par phi1 phi2', heap2') ===> (Phi_Par phi1' phi2', heapB).\nProof.\n  intros  phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2'\n          H1 H2 Det1 HDet2 HDisj HConf HEqual HStep1 HStep2; subst.\n  inversion HStep1; inversion HStep2; subst. \n  edestruct Aux_Aux_Step_Ext_Heap as [heapB' [? ?]]; eauto.\n  apply HMapP.Equal_sym in HEqual. assert (H.Equal heapb heapB') by (eapply HMapP.Equal_trans; eauto).\n  exists (update_H (r0, l0, v0) heap1'); exists (update_H (r0, l0, v0) heapb); repeat split.\n  - unfold H.Equal; intros [r1 l1]. apply HMapP.Equal_sym in HEqual. unfold H.Equal in HEqual.\n    destruct (RegionVars.eq_dec (r1, l1) (r0, l0));  unfold update_H; simpl.\n    + inversion e; simpl in *; subst. rewrite H_same_key. rewrite H_same_key. reflexivity.\n    + unfold RegionVars.eq in n.  simpl in n.\n      rewrite HMapP.add_neq_o.\n      * rewrite HMapP.add_neq_o; simpl; [apply HEqual | contradict n; intuition].\n      * contradict n; intuition.\n  - inversion HDisj; subst. simpl in H. \n    assert (Disjoint_Dynamic (DA_Read r l v) (DA_Alloc r0 l0 v0)) by (apply H3; left; reflexivity).\n    inversion H4; subst. constructor. constructor.\n  - do 2 constructor. inversion HStep2; subst.\n    inversion HDisj; subst. simpl in H. \n    assert (Disjoint_Dynamic (DA_Read r l v) (DA_Alloc r0 l0 v0)) by (apply H3; left; reflexivity).\n    inversion H4; subst.\n    eapply H_diff_key_2; auto.\n    unfold H.Equal in HEqual. rewrite HEqual. assumption.\nQed.\n\nLemma Par_Step_Read_Write :\n  forall phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2',\n    phi1 = Phi_Elem (DA_Read r l v) ->\n    phi2 = Phi_Elem (DA_Write r0 l0 v0) -> \n    Det_Trace phi1 ->\n    Det_Trace phi2 ->\n    Disjoint_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    H.Equal heapa heapb ->\n    (phi1, heapa) ===> (phi1', heap1') ->\n    (phi2, heapb) ===> (phi2', heap2') ->\n    exists heapA heapB,\n      H.Equal heapA heapB /\\\n      (Phi_Par phi1' phi2, heap1') ===> (Phi_Par phi1' phi2', heapA) /\\\n      (Phi_Par phi1 phi2', heap2') ===> (Phi_Par phi1' phi2', heapB).\nProof.\n  intros  phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2'\n          H1 H2 Det1 HDet2 HDisj HConf HEqual HStep1 HStep2; subst.\n  inversion HStep1; inversion HStep2; subst.\n  edestruct Aux_Aux_Step_Ext_Heap as [heapB' [? ?]]; eauto.\n  exists (update_H (r0, l0, v0) heap1'); exists (update_H (r0, l0, v0) heapb); repeat split.\n  -  unfold H.Equal; intros [r1 l1]. unfold H.Equal in HEqual.\n    destruct (RegionVars.eq_dec (r1, l1) (r0, l0));  unfold update_H; simpl.\n    + inversion e; simpl in *; subst. rewrite H_same_key. rewrite H_same_key. reflexivity.\n    + unfold RegionVars.eq in n.  simpl in n.\n      rewrite HMapP.add_neq_o.\n      * rewrite HMapP.add_neq_o; simpl; [apply HEqual | contradict n; intuition].\n      * contradict n; intuition.\n  - inversion HDisj; subst. simpl in H. \n    assert (Disjoint_Dynamic (DA_Read r l v) (DA_Write r0 l0 v0)) by (apply H2; left; reflexivity).\n    inversion H3; subst. constructor.  constructor.\n    apply HMapP.Equal_sym in HEqual.\n    apply HMapP.Equal_Equiv in HEqual. inversion HEqual. now apply HEqual.\n  - do 2 constructor. inversion HStep2; subst.\n    inversion HDisj; subst. simpl in H. \n    assert (Disjoint_Dynamic (DA_Read r l v) (DA_Write r0 l0 v0)) by (apply H2; left; reflexivity).\n    inversion H4; subst.\n    eapply H_diff_key_2; auto. unfold H.Equal in HEqual. rewrite <- H0.\n    symmetry; apply HEqual.\nQed.\n\nLemma Par_Step_Alloc_Write :\n  forall phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2',\n    phi1 = Phi_Elem (DA_Alloc r l v) ->\n    phi2 = Phi_Elem (DA_Write r0 l0 v0) -> \n    Det_Trace phi1 ->\n    Det_Trace phi2 ->\n    Disjoint_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    H.Equal heapa heapb ->\n    (phi1, heapa) ===> (phi1', heap1') ->\n    (phi2, heapb) ===> (phi2', heap2') ->\n    exists heapA heapB,\n      H.Equal heapA heapB /\\\n      (Phi_Par phi1' phi2, heap1') ===> (Phi_Par phi1' phi2', heapA) /\\\n      (Phi_Par phi1 phi2', heap2') ===> (Phi_Par phi1' phi2', heapB).\nProof.\n  intros  phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2'\n          H1 H2 Det1 HDet2 HDisj HConf HEqual HStep1 HStep2; subst.\n  inversion HStep1; inversion HStep2; subst. \n  exists (update_H (r0, l0, v0) (update_H (r, l, v) heapa)). exists (update_H (r, l, v) (update_H (r0, l0, v0) heapb)). repeat split.\n  - inversion HDisj; subst. \n    assert (Disjoint_Dynamic (DA_Alloc r l v) (DA_Write r0 l0 v0)) by (apply H; left; reflexivity).\n    inversion H0; subst. unfold update_H in *. simpl in *. \n    destruct (RegionVars.eq_dec (r, l) (r0, l0)).\n    + inversion e. unfold fst, snd in *; subst.\n      contradict H2. intuition.\n    + clear n. \n      apply HMapP.Equal_mapsto_iff; intros. destruct k.\n      destruct (RegionVars.eq_dec (n, n0) (r0, l0)); destruct (RegionVars.eq_dec (n, n0) (r, l)); split.\n      * inversion e0; inversion e1. unfold fst, snd in *; do 2 subst. \n        contradict H2. intuition.\n      * inversion e0; inversion e1. unfold fst, snd in *; do 2subst.\n        contradict H2. intuition.\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.\n        intro. apply  HMapP.find_mapsto_iff in H1.\n        rewrite H_same_key_add_twice_1 in H1. rewrite H_same_key in H1.\n        apply HMapP.add_mapsto_iff. right. intuition. inversion H1; subst.\n        apply HMapP.find_mapsto_iff. apply H_same_key.\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.\n        intro. apply  HMapP.find_mapsto_iff in H1. rewrite H_same_key_add_twice_2 in H1.\n        rewrite H_same_key in H1.\n        apply HMapP.find_mapsto_iff. inversion H1. rewrite <- H4.\n        apply H_same_key. assumption.\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.\n        intro. apply  HMapP.find_mapsto_iff in H1. rewrite H_same_key_add_twice_2 in H1.\n        { apply HMapP.add_mapsto_iff. left; simpl. split; auto.\n          rewrite HMapP.add_o in H1. \n          destruct (HMapP.eq_dec (r, l) (r, l)) in H1; [inversion H1; subst |  simpl in n; contradict n; auto].\n          reflexivity.\n        }\n        { contradict n1. inversion n1. intuition. }\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.\n        intro. apply  HMapP.find_mapsto_iff in H1. rewrite H_same_key_add_twice_1 in H1. \n        apply  HMapP.find_mapsto_iff in H1.  \n        apply  HMapP.find_mapsto_iff. \n        apply H_diff_key_2; [ contradict H2; auto | ].\n        apply HMapP.find_mapsto_iff.\n        apply HMapP.add_mapsto_iff. left; simpl. split; auto.\n        apply HMapP.add_mapsto_iff in H1.\n        destruct H1 as [ [ ?  ?] | [? ?] ]; [assumption | contradict H2; intuition]. \n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst.\n        intro. apply  HMapP.find_mapsto_iff in H1.\n        apply  HMapP.find_mapsto_iff.\n        { eapply H_diff_key_add_comm_2. \n          - contradict n1. inversion n1. intuition.\n          - contradict n2. inversion n2. intuition.\n          - apply H_diff_key_2.\n            + contradict n1. inversion n1. intuition.\n            + unfold H.Equal in HEqual. rewrite <- HEqual.\n              apply H_diff_key_1 in H1.\n              * apply H_diff_key_1 in H1; [assumption | contradict n2; inversion n2; auto]. \n              * contradict n1; inversion n1; auto.\n        }\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst.\n        intro. apply  HMapP.find_mapsto_iff in H1.\n        apply  HMapP.find_mapsto_iff.\n        { eapply H_diff_key_add_comm_2.\n          - contradict n1. inversion n1. auto.\n          - contradict n2. inversion n2. auto.\n          - apply H_diff_key_2.\n            + contradict n1. inversion n1. auto.\n            +unfold H.Equal in HEqual. rewrite HEqual.\n              apply H_diff_key_1 in H1.\n              * apply H_diff_key_1 in H1; [assumption | contradict n1; inversion n1; intuition].\n              * contradict n1; inversion n1; intuition.\n        }  \n  - inversion HDisj; subst.\n    assert (Disjoint_Dynamic (DA_Alloc r l v) (DA_Write r0 l0 v0)) by (apply H; left; reflexivity).\n    inversion H0; subst. unfold update_H in *. simpl in *. \n    constructor. constructor.\n    apply HMapP.Equal_sym in HEqual. apply HMapP.Equal_Equiv in HEqual. inversion HEqual.\n    apply HEqual in H6. apply HMapP.add_neq_in_iff; intuition.\n  - inversion HDisj; subst. simpl in H. constructor. constructor.\nQed.    \n\nLemma Par_Step_Write_Alloc :\n  forall phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2',\n    phi1 = Phi_Elem (DA_Write r l v) ->\n    phi2 = Phi_Elem (DA_Alloc r0 l0 v0) -> \n    Det_Trace phi1 ->\n    Det_Trace phi2 ->\n    Disjoint_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    H.Equal heapa heapb ->\n    (phi1, heapa) ===> (phi1', heap1') ->\n    (phi2, heapb) ===> (phi2', heap2') ->\n    exists heapA heapB,\n      H.Equal heapA heapB /\\\n      (Phi_Par phi1' phi2, heap1') ===> (Phi_Par phi1' phi2', heapA) /\\\n      (Phi_Par phi1 phi2', heap2') ===> (Phi_Par phi1' phi2', heapB).\nProof.\n  intros  phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2'\n          H1 H2 Det1 HDet2 HDisj HConf HEqual HStep1 HStep2; subst.\n  inversion HStep1; inversion HStep2; subst. \n  exists (update_H (r0, l0, v0) (update_H (r, l, v) heapa)). exists (update_H (r, l, v) (update_H (r0, l0, v0) heapb)). repeat split.\n  - inversion HDisj; subst. \n    assert (Disjoint_Dynamic (DA_Write r l v) (DA_Alloc r0 l0 v0)) by (apply H; left; reflexivity).\n    inversion H1; subst. unfold update_H in *. simpl in *. \n    destruct (RegionVars.eq_dec (r, l) (r0, l0)).\n    + inversion e. simpl in *. subst. contradict H3. reflexivity.\n    + clear n. \n      apply HMapP.Equal_mapsto_iff; intros. destruct k. \n      destruct (RegionVars.eq_dec (n, n0) (r0, l0)); destruct (RegionVars.eq_dec (n, n0) (r, l)); split.\n      * inversion e0; inversion e1.  unfold fst, snd in *; subst. rewrite H6 in *. rewrite H5 in *.\n        inversion H1; subst. contradict H4. intuition.\n      * inversion e0; inversion e1. unfold fst, snd in *; subst. rewrite H6 in H1. rewrite H5 in H1.\n        inversion H1; subst. contradict H4. intuition.\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.\n        intro. apply  HMapP.find_mapsto_iff in H2. rewrite H_same_key_add_twice_1 in H2. rewrite H_same_key in H2.\n        apply HMapP.add_mapsto_iff. right; simpl. split; [ intuition | ].\n        apply HMapP.find_mapsto_iff. rewrite H_same_key. assumption.\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.\n        intro. apply  HMapP.find_mapsto_iff in H2. rewrite H_same_key_add_twice_2 in H2.\n        { rewrite H_same_key in H2.  apply  HMapP.find_mapsto_iff.\n          inversion H2; subst. rewrite H_same_key_add_twice_1. rewrite H_same_key. assumption. }\n        { contradict n1. inversion n1. intuition. }\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.\n        intro. apply  HMapP.find_mapsto_iff in H2. rewrite H_same_key_add_twice_2 in H2. \n        { apply HMapP.add_mapsto_iff. left; simpl. split; auto.\n          rewrite HMapP.add_o in H2. \n          destruct (HMapP.eq_dec (r, l) (r, l)) in H2; [inversion H2; subst |  simpl in n; contradict n; auto].\n          reflexivity.\n        }\n        { contradict n1. inversion n1. intuition. }\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.\n        intro. apply  HMapP.find_mapsto_iff in H2. rewrite H_same_key_add_twice_1 in H2. \n        apply  HMapP.find_mapsto_iff in H2.  \n        apply  HMapP.find_mapsto_iff. \n        apply H_diff_key_2; [ contradict H2; auto | ].\n        apply HMapP.find_mapsto_iff.\n        apply HMapP.add_mapsto_iff. left; simpl. split; auto.\n        apply HMapP.add_mapsto_iff in H2.\n        destruct H2 as [ [ ?  ?] | [? ?] ]; [assumption | contradict H2; intuition]. \n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst.\n        intro. apply  HMapP.find_mapsto_iff in H2.\n        apply  HMapP.find_mapsto_iff.\n        { eapply H_diff_key_add_comm_2.\n          - contradict n2. inversion n2. auto.\n          - contradict n1. inversion n1. auto.\n          - apply H_diff_key_2.\n            + contradict n1. inversion n1. intuition.\n            + unfold H.Equal in HEqual. rewrite <- HEqual.\n              apply H_diff_key_1 in H2.\n              * apply H_diff_key_1 in H2; [assumption | contradict n2; inversion n2; auto]. \n              * contradict n1; inversion n1; auto.\n        }\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst.\n        intro. apply  HMapP.find_mapsto_iff in H2.\n        apply  HMapP.find_mapsto_iff.\n        { eapply H_diff_key_add_comm_2.\n          - contradict n1. inversion n1. auto.\n          - contradict n2. inversion n2. auto.\n          - apply H_diff_key_2.\n            + contradict n1. inversion n1. auto.\n            +unfold H.Equal in HEqual. rewrite HEqual.\n              apply H_diff_key_1 in H2.\n              * apply H_diff_key_1 in H2; [assumption | contradict n1; inversion n1; intuition].\n              * contradict n1; inversion n1; intuition.\n        }\n  - inversion HDisj; subst. \n    assert (Disjoint_Dynamic (DA_Write r l v)  (DA_Alloc r0 l0 v0)) by (apply H; left; reflexivity).\n    inversion H1; subst. unfold update_H in *. simpl in *.\n    constructor. constructor.\n  - constructor. constructor.\n    inversion HDisj; subst. \n    assert (Disjoint_Dynamic (DA_Write r l v)  (DA_Alloc r0 l0 v0)) by (apply H; left; reflexivity).\n    inversion H1; subst. unfold update_H in *. simpl in *.\n    apply HMapP.Equal_sym in HEqual. apply HMapP.Equal_Equiv in HEqual. inversion HEqual.\n    apply HEqual in H0. apply HMapP.add_neq_in_iff; intuition.\nQed.    \n    \nLemma Phi_Heap_Step_Progress :\n  forall phi heap heap',\n    (phi, heap) ===> (phi, heap') ->\n    False.\nProof.\n  induction phi; intros heap heap' HStep.\n  + inversion HStep.\n  + inversion HStep.\n  + inversion HStep; subst.\n    - eapply IHphi1; eassumption.\n    - eapply IHphi2; eassumption.\n  + inversion HStep; subst.\n    - eapply IHphi1; eassumption.\n    - eapply IHphi2; eassumption.\nQed.\n\n\nLemma Par_Step_Equal :\n   forall phi1 phi2 phi1' phi2' heap0 heap1' heap2',\n    Det_Trace phi1 ->\n    Det_Trace phi2 ->\n    Disjoint_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    (phi1, heap0) ===> (phi1', heap1') ->\n    (phi2, heap0) ===> (phi2', heap2') ->\n    exists heapA, exists heapB,\n      H.Equal heapA heapB /\\\n      (Phi_Par phi1' phi2, heap1') ===> (Phi_Par phi1' phi2', heapA) /\\\n      (Phi_Par phi1 phi2', heap2') ===> (Phi_Par phi1' phi2', heapB).\nProof.\n  intros phi1 phi2 phi1' phi2' heap0 heap1' heap2' HDet1 HDet2 HDisj HConf HStep1 HStep2.\n  generalize dependent phi2.\n  dependent induction HStep1; intros.\n  - dependent destruction HStep2. \n    + eapply Par_Step_Alloc_Alloc; eauto || econstructor.\n    + eapply Par_Step_Alloc_Read; eauto  || econstructor; assumption.\n    + eapply Par_Step_Alloc_Write; eauto || econstructor; assumption.\n    + replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Alloc in HStep2; eauto.\n      destruct HStep2 as [? [? ?]].\n      { exists x. exists (update_H (r, l, v) heap2'); repeat split.\n        - assumption.\n        - do 2 constructor; assumption.\n        - do 2 constructor. }\n    + replace (phi_as_list (Phi_Seq Phi_Nil phi0)) with (phi_as_list Phi_Nil ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Alloc in HStep2; eauto.\n      destruct HStep2 as [? [? ?]].\n      { exists x. exists (update_H (r, l, v) heap2'); repeat split.\n        - assumption.\n        - do 2 constructor; assumption.\n        - do 2 constructor. }\n    + { exists (update_H (r, l, v) heap2'). exists (update_H (r, l, v) heap2'); repeat split; do 2  constructor. }\n    + replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Alloc in HStep2; eauto.\n      destruct HStep2 as [? [? ?]].\n      { exists x. exists (update_H (r, l, v) heap2'); repeat split.\n        - assumption.\n        - do 2 constructor; assumption.\n        - do 2 constructor.   }\n    + replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Alloc in HStep2; eauto.\n      destruct HStep2 as [? [? ?]].\n      { exists x. exists  (update_H (r, l, v) heap2'); repeat split.\n        - assumption.\n        - do 2 constructor; assumption.\n        - do 2 constructor.  }            \n    + { exists (update_H (r, l, v) heap2'). exists (update_H (r, l, v) heap2'); repeat split; do 2  constructor. }\n  - dependent destruction HStep2. \n    + eapply Par_Step_Read_Alloc; eauto || econstructor; assumption.\n    + { exists heap2'. exists heap2'; repeat split; do 2 constructor; assumption. }\n    + eapply Par_Step_Read_Write; eauto || econstructor; assumption.\n    + { exists heap2'. exists heap2'. repeat split.\n        - do 2 constructor; assumption.\n        - do 2 constructor.\n          replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n            in HDisj by (simpl; reflexivity).\n          apply Disjointness_app_app_and_l in HDisj. destruct HDisj as [HD1 ?].\n          replace (phi_as_list (Phi_Elem (DA_Read r l v))) with (DA_Read r l v :: nil)\n            in HD1 by (simpl; reflexivity).\n          eapply Read_Preserved.\n          eapply H.\n          eapply HD1.\n          eapply HStep2. }\n    + { exists heap2'. exists heap2'. repeat split.\n        - do 2 constructor; assumption.\n        - do 2 constructor.\n          replace (phi_as_list (Phi_Seq Phi_Nil phi0)) with (phi_as_list Phi_Nil ++ phi_as_list phi0)\n            in HDisj by (simpl; reflexivity).\n          apply Disjointness_app_app_and_l in HDisj. destruct HDisj as [? HD1].\n          replace (phi_as_list (Phi_Elem (DA_Read r l v))) with (DA_Read r l v :: nil)\n            in HD1 by (simpl; reflexivity).\n          eapply Read_Preserved.\n          eapply H.\n          eapply HD1.\n          eapply HStep2. }\n    + exists heap2'. exists heap2'. repeat split; do 2 constructor. assumption.\n    + { exists heap2'. exists heap2'. repeat split.\n        - do 2 constructor; assumption.\n        - do 2 constructor.\n          replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n            in HDisj by (simpl; reflexivity).\n          apply Disjointness_app_app_and_l in HDisj. destruct HDisj as [HD1 ?].\n          replace (phi_as_list (Phi_Elem (DA_Read r l v))) with (DA_Read r l v :: nil)\n            in HD1 by (simpl; reflexivity).\n          eapply Read_Preserved.\n          eapply H.\n          eapply HD1.\n          eapply HStep2. }\n    + { exists heap2'. exists heap2'. repeat split.\n        - do 2 constructor; assumption.\n        - do 2 constructor.\n          replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n            in HDisj by (simpl; reflexivity).\n          apply Disjointness_app_app_and_l in HDisj. destruct HDisj as [? HD1].\n          replace (phi_as_list (Phi_Elem (DA_Read r l v))) with (DA_Read r l v :: nil)\n            in HD1 by (simpl; reflexivity).\n          eapply Read_Preserved.\n          eapply H.\n          eapply HD1.\n          eapply HStep2. }\n    + { exists heap2'. exists heap2'. repeat split; do 2 constructor. assumption. }\n  - dependent destruction HStep2. \n    + eapply Par_Step_Write_Alloc; eauto || econstructor; assumption.\n    + eapply Par_Step_Write_Read; eauto || econstructor; assumption.\n    + eapply Par_Step_Write_Write; eauto || econstructor; assumption.\n    + eapply monotonic_heap_updates in H; eauto.\n      replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Write in HStep2; eauto.\n      destruct HStep2 as [? [? ?]].   \n      { exists x. exists (update_H (r, l, v) heap2'); repeat split.\n        - assumption.\n        - do 2 constructor. assumption.\n        - constructor. constructor. assumption.\n      }\n    + eapply monotonic_heap_updates in H; eauto.\n      replace (phi_as_list (Phi_Seq Phi_Nil phi0)) with (phi_as_list Phi_Nil ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Write in HStep2; eauto.\n      destruct HStep2 as [? [? ?]].\n      { exists x.  exists (update_H (r, l, v) heap2'); repeat split.\n        - assumption.\n        - do 2 constructor; assumption.\n        - constructor. constructor. assumption. }\n    + { exists (update_H (r, l, v) heap2'). exists (update_H (r, l, v) heap2'); repeat split; do 2  constructor; assumption. }\n    + eapply monotonic_heap_updates in H; eauto.\n      replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Write in HStep2; eauto.\n      destruct HStep2 as [? [? ?]].\n      { exists x. exists (update_H (r, l, v) heap2'); repeat split.\n        - assumption.\n        - do 2 constructor; assumption.\n        - constructor. constructor. assumption. }\n    + eapply monotonic_heap_updates in H; eauto.\n      replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Write in HStep2; eauto.\n      destruct HStep2 as [? [? ?]].\n      { exists x. exists (update_H (r, l, v) heap2'); repeat split.\n        - assumption.\n        - do 2 constructor; assumption.\n        - constructor. constructor. assumption.  }            \n    + { exists (update_H (r, l, v) heap2'). exists (update_H (r, l, v) heap2'); repeat split; do 2  constructor; assumption. }\n  - inversion HDet1; subst. \n    edestruct (IHHStep1 H1 phi1 HDet2) as [heapA [heapB [? [? ?]]]].\n    + simpl in HDisj. apply Disjointness_app_app_and_r in HDisj. destruct HDisj. assumption.\n    + simpl in HConf. inversion HDet1.\n      apply Conflictness_app_and_r in HConf; [ destruct HConf  | | | ]; assumption.\n    + assumption.\n    + exists heapA. exists heapB. repeat split.\n      * assumption.\n      * inversion H0; subst.\n        { apply Phi_Heap_Step_Progress in HStep2. contradiction. }\n        { constructor. assumption. }\n      * inversion H3; subst.\n        { constructor. constructor. assumption. }\n        { apply Phi_Heap_Step_Progress in H3. contradiction. }\n  - inversion HDet1; subst.\n    edestruct (IHHStep1 H2 phi0 HDet2) as [heapA [heapB [? [? ?]]]].\n    + simpl in HDisj. assumption.\n    + simpl in HConf. assumption.\n    + assumption.\n    + exists heapA. exists heapB. repeat split.\n      * assumption.\n      * inversion H0; subst.\n        { apply Phi_Heap_Step_Progress in HStep2. contradiction. }\n        { constructor. assumption. }\n      * inversion H3; subst.\n        { constructor. constructor. assumption. }\n        { apply Phi_Heap_Step_Progress in H3. contradiction. }\n  - exists heap2'. exists heap2'. repeat split.\n     * constructor; assumption.\n     * constructor; constructor.\n  - inversion HDet1; subst.\n    edestruct (IHHStep1 H1 phi1 HDet2) as [heapA [heapB [? [? ?]]]].\n    + simpl in HDisj. apply Disjointness_app_app_and_r in HDisj. destruct HDisj. assumption.\n    + simpl in HConf. inversion HDet1.\n      apply Conflictness_app_and_r in HConf; [ destruct HConf  | | | ]; assumption.\n    + assumption.\n    + exists heapA. exists heapB. repeat split.\n      * assumption.\n      * inversion H0; subst.\n        { apply Phi_Heap_Step_Progress in HStep2. contradiction. }\n        { constructor. assumption. }\n      * inversion H4; subst.\n        { constructor. constructor. assumption. }\n        { apply Phi_Heap_Step_Progress in H4. contradiction. }\n  - inversion HDet1; subst.\n    edestruct (IHHStep1 H2 phi1 HDet2) as [heapA [heapB [? [? ?]]]].\n    + simpl in HDisj. apply Disjointness_app_app_and_r in HDisj. destruct HDisj. assumption.\n    + simpl in HConf. inversion HDet1.\n      apply Conflictness_app_and_r in HConf; [ destruct HConf  | | | ]; assumption.\n    + assumption.\n    + exists heapA. exists heapB. repeat split.\n      * assumption.\n      * inversion H0; subst.\n        { apply Phi_Heap_Step_Progress in HStep2. contradiction. }\n        { constructor. assumption. }\n      * inversion H4; subst.\n        { constructor. constructor. assumption. }\n        { apply Phi_Heap_Step_Progress in H4. contradiction. }\n  - exists heap2'. exists heap2'. repeat split.\n     * constructor; assumption.\n     * constructor; constructor.\nQed.\n\nLemma Par_Step_Equal_new :\n   forall phi1 phi2 phi1' phi2' heapa heapb heap1' heap2',\n    Det_Trace phi1 ->\n    Det_Trace phi2 ->\n    Disjoint_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    H.Equal heapa heapb ->\n    (phi1, heapa) ===> (phi1', heap1') ->\n    (phi2, heapb) ===> (phi2', heap2') ->\n    exists heapA, exists heapB,\n      H.Equal heapA heapB /\\\n      (Phi_Par phi1' phi2, heap1') ===> (Phi_Par phi1' phi2', heapA) /\\\n      (Phi_Par phi1 phi2', heap2') ===> (Phi_Par phi1' phi2', heapB).\nProof.\n  intros phi1 phi2 phi1' phi2' heapa heapb heap1' heap2' HDet1 HDet2 HDisj HConf HEqual HStep1 HStep2.\n  generalize dependent phi2.\n  dependent induction HStep1; intros.\n  - dependent destruction HStep2.  \n    + eapply Par_Step_Alloc_Alloc; eauto || econstructor.\n    + eapply Par_Step_Alloc_Read; eauto  || econstructor; assumption.\n    + eapply Par_Step_Alloc_Write; eauto || econstructor; assumption.\n    + apply HMapP.Equal_sym in HEqual. \n      edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n       as [heap2'' [HEqual' HStep2']]. clear HStep2.\n      replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Alloc in HStep2'; eauto.  \n      destruct HStep2' as [heapa' [? ?]]. \n      { exists heapa'. exists (update_H (r, l, v) heap2'); repeat split. \n        - unfold H.Equal in *; unfold update_H in *; simpl in *.\n          intros [r' l'].\n          destruct (RegionVars.eq_dec (r', l') (r, l)).\n          * inversion_clear e; simpl in *; subst.\n            rewrite H1. do 2 rewrite H_same_key. reflexivity.\n          * unfold RegionVars.eq in *; simpl in *.\n            rewrite HMapP.add_neq_o. \n            { rewrite H1. rewrite HEqual'. rewrite HMapP.add_neq_o; [reflexivity | contradict n; intuition]. }\n            { simpl. contradict n. intuition. } \n        - do 2 constructor. assumption.\n        - do 2 constructor. }\n    + apply HMapP.Equal_sym in HEqual.\n      edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n       as [heap2'' [HEqual' HStep2']]. clear HStep2.\n      replace (phi_as_list (Phi_Seq Phi_Nil phi0)) with (phi_as_list Phi_Nil ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Alloc in HStep2'; eauto.\n      destruct HStep2' as [? [? ?]].\n      { exists x. exists (update_H (r, l, v) heap2'); repeat split.\n        - unfold H.Equal in *; unfold update_H in *; simpl in *.\n          intros [r' l'].\n          destruct (RegionVars.eq_dec (r', l') (r, l)).\n          * inversion_clear e; simpl in *; subst.\n            rewrite H1. do 2 rewrite H_same_key. reflexivity.\n          * unfold RegionVars.eq in *; simpl in *.\n            rewrite HMapP.add_neq_o. \n            { rewrite H1. rewrite HEqual'. rewrite HMapP.add_neq_o; [reflexivity | contradict n; intuition]. }\n            { simpl. contradict n. intuition. } \n        - do 2 constructor; assumption.\n        - do 2 constructor. }\n    + { exists (update_H (r, l, v) heapa). exists (update_H (r, l, v) heap2'); repeat split.\n        - unfold H.Equal in *; unfold update_H in *; simpl in *.\n          intros [r' l']. \n          destruct (RegionVars.eq_dec (r', l') (r, l)).\n          * inversion_clear e; simpl in *; subst.\n            do 2 rewrite H_same_key. reflexivity.\n          * unfold RegionVars.eq in *; simpl in *.\n            rewrite HMapP.add_neq_o. \n            { rewrite HEqual. rewrite HMapP.add_neq_o; [reflexivity | contradict n; intuition]. }\n            { simpl. contradict n. intuition. } \n        - do 2  constructor.\n        - do 2 constructor. }\n    + apply HMapP.Equal_sym in HEqual.\n      edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n        as [heap2'' [HEqual' HStep2']]. clear HStep2.\n      replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Alloc in HStep2'; eauto.\n      destruct HStep2' as [? [? ?]].\n      { exists x. exists (update_H (r, l, v) heap2'); repeat split.\n        - unfold H.Equal in *; unfold update_H in *; simpl in *.\n          intros [r' l'].\n          destruct (RegionVars.eq_dec (r', l') (r, l)).\n          * inversion_clear e; simpl in *; subst.\n            rewrite H1. do 2 rewrite H_same_key. reflexivity.\n          * unfold RegionVars.eq in *; simpl in *.\n            rewrite HMapP.add_neq_o. \n            { rewrite H1. rewrite HEqual'. rewrite HMapP.add_neq_o; [reflexivity | contradict n; intuition]. }\n            { simpl. contradict n. intuition. } \n        - do 2 constructor; assumption.\n        - do 2 constructor.   }\n    + apply HMapP.Equal_sym in HEqual.\n      edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n        as [heap2'' [HEqual' HStep2']]. clear HStep2.\n      replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Alloc in HStep2'; eauto.\n      destruct HStep2' as [? [? ?]].\n      { exists x. exists  (update_H (r, l, v) heap2'); repeat split.\n        -  unfold H.Equal in *; unfold update_H in *; simpl in *.\n          intros [r' l'].\n          destruct (RegionVars.eq_dec (r', l') (r, l)).\n          * inversion_clear e; simpl in *; subst.\n            rewrite H1. do 2 rewrite H_same_key. reflexivity.\n          * unfold RegionVars.eq in *; simpl in *.\n            rewrite HMapP.add_neq_o. \n            { rewrite H1. rewrite HEqual'. rewrite HMapP.add_neq_o; [reflexivity | contradict n; intuition]. }\n            { simpl. contradict n. intuition. } \n        - do 2 constructor; assumption.\n        - do 2 constructor.  }            \n    + { exists (update_H (r, l, v) heapa). exists (update_H (r, l, v) heap2'); repeat split; try (do 2  constructor). \n        unfold H.Equal in *; unfold update_H in *; simpl in *.\n          intros [r' l']. \n          destruct (RegionVars.eq_dec (r', l') (r, l)).\n          * inversion_clear e; simpl in *; subst.\n            do 2 rewrite H_same_key. reflexivity.\n          * unfold RegionVars.eq in *; simpl in *.\n            rewrite HMapP.add_neq_o. \n            { rewrite HEqual. rewrite HMapP.add_neq_o; [reflexivity | contradict n; intuition]. }\n            { simpl. contradict n. intuition. }\n       }  \n  - dependent destruction HStep2. \n    + eapply Par_Step_Read_Alloc; eauto || econstructor; assumption.\n    + { exists heap1'; exists heap2'; repeat split.\n        - assumption.\n        - constructor. constructor. unfold H.Equal in HEqual. rewrite <- H0. apply HEqual.\n        - constructor. constructor. unfold H.Equal in HEqual. rewrite <- HEqual. assumption.\n      }\n    + eapply Par_Step_Read_Write; eauto || econstructor; assumption.\n    + { apply HMapP.Equal_sym in HEqual.\n        edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n        as [heap2'' [HEqual' HStep2']].\n        exists heap2''. exists heap2'. repeat split.\n        - apply HMapP.Equal_sym. assumption.\n        - do 2 constructor. assumption.\n        - do 2 constructor. \n          replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n            in HDisj by (simpl; reflexivity).\n          apply Disjointness_app_app_and_l in HDisj. destruct HDisj as [HD1 ?].\n          replace (phi_as_list (Phi_Elem (DA_Read r l v))) with (DA_Read r l v :: nil)\n            in HD1 by (simpl; reflexivity).\n          unfold H.Equal in HEqual'. rewrite HEqual'.\n          eapply Read_Preserved.\n          eapply H.\n          eapply HD1.\n          eapply HStep2'. }\n    + { apply HMapP.Equal_sym in HEqual.\n        edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n          as [heap2'' [HEqual' HStep2']]. clear HStep2.\n        exists heap2''. exists heap2'. repeat split.\n        - apply HMapP.Equal_sym. assumption.\n        - do 2 constructor; assumption.\n        - do 2 constructor.\n          replace (phi_as_list (Phi_Seq Phi_Nil phi0)) with (phi_as_list Phi_Nil ++ phi_as_list phi0)\n            in HDisj by (simpl; reflexivity).\n          apply Disjointness_app_app_and_l in HDisj. destruct HDisj as [? HD1].\n          replace (phi_as_list (Phi_Elem (DA_Read r l v))) with (DA_Read r l v :: nil)\n            in HD1 by (simpl; reflexivity).\n          unfold H.Equal in HEqual'. rewrite HEqual'. eapply Read_Preserved.\n          eapply H.\n          eapply HD1.\n          eapply HStep2'. }\n    + { exists heap1'. exists heap2'. repeat split; auto.\n        - do 2 constructor.\n        - do 2 constructor.\n          rewrite <- H. unfold H.Equal in HEqual. symmetry; apply HEqual.\n      }\n    + { apply HMapP.Equal_sym in HEqual.\n        edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n           as [heap2'' [HEqual' HStep2']]. clear HStep2.\n        exists heap2''. exists heap2'. repeat split.\n        - apply HMapP.Equal_sym. assumption.\n        - do 2 constructor; assumption.\n        - do 2 constructor.\n          replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n            in HDisj by (simpl; reflexivity).\n          apply Disjointness_app_app_and_l in HDisj. destruct HDisj as [HD1 ?].\n          replace (phi_as_list (Phi_Elem (DA_Read r l v))) with (DA_Read r l v :: nil)\n            in HD1 by (simpl; reflexivity).\n          unfold H.Equal in HEqual'. rewrite HEqual'.  eapply Read_Preserved.\n          eapply H.\n          eapply HD1.\n          eapply HStep2' . }\n    + { apply HMapP.Equal_sym in HEqual.\n        edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n          as [heap2'' [HEqual' HStep2']]. clear HStep2.\n        exists heap2''. exists heap2'. repeat split.\n        - apply HMapP.Equal_sym. assumption.\n        - do 2 constructor; assumption.\n        - do 2 constructor.\n          replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n            in HDisj by (simpl; reflexivity).\n          apply Disjointness_app_app_and_l in HDisj. destruct HDisj as [? HD1].\n          replace (phi_as_list (Phi_Elem (DA_Read r l v))) with (DA_Read r l v :: nil)\n            in HD1 by (simpl; reflexivity).\n          unfold H.Equal in HEqual'. rewrite HEqual'. eapply Read_Preserved.\n          eapply H.\n          eapply HD1.\n          eapply HStep2'. }\n    + { exists heap1'. exists heap2'. repeat split; auto.\n        - do 2 constructor.\n        - do 2 constructor.\n          rewrite <- H. unfold H.Equal in HEqual. symmetry; apply HEqual.\n      }\n  - dependent destruction HStep2. \n    + eapply Par_Step_Write_Alloc; eauto || econstructor; assumption.\n    + eapply Par_Step_Write_Read; eauto || econstructor; assumption.\n    + eapply Par_Step_Write_Write; eauto || econstructor; assumption.\n    + apply HMapP.Equal_sym in HEqual.\n      edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n        as [heap2'' [HEqual' HStep2']]. clear HStep2.\n      eapply monotonic_heap_updates in H; eauto.\n      replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Write in HStep2'; eauto.\n      destruct HStep2' as [? [? ?]].   \n      { exists x. exists (update_H (r, l, v) heap2'); repeat split.\n        -  unfold H.Equal in *; unfold update_H in *; simpl in *.\n          intros [r' l'].\n          destruct (RegionVars.eq_dec (r', l') (r, l)).\n          * inversion_clear e; simpl in *; subst.\n            rewrite H2. do 2 rewrite H_same_key. reflexivity.\n          * unfold RegionVars.eq in *; simpl in *.\n            rewrite HMapP.add_neq_o. \n            { rewrite H2. rewrite HEqual'. rewrite HMapP.add_neq_o; [reflexivity | contradict n; intuition]. }\n            { simpl. contradict n. intuition. } \n        - do 2 constructor. assumption.\n        - constructor. constructor.  apply HMapP.Equal_Equiv in HEqual'. inversion HEqual'. apply H4. assumption. \n      }\n    + apply HMapP.Equal_sym in HEqual.\n      edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n         as [heap2'' [HEqual' HStep2']]. clear HStep2.\n      eapply monotonic_heap_updates in H; eauto.\n      replace (phi_as_list (Phi_Seq Phi_Nil phi0)) with (phi_as_list Phi_Nil ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Write in HStep2'; eauto.\n      destruct HStep2' as [? [? ?]].\n      { exists x.  exists (update_H (r, l, v) heap2'); repeat split.\n        -  unfold H.Equal in *; unfold update_H in *; simpl in *.\n          intros [r' l'].\n          destruct (RegionVars.eq_dec (r', l') (r, l)).\n          * inversion_clear e; simpl in *; subst.\n            rewrite H2. do 2 rewrite H_same_key. reflexivity.\n          * unfold RegionVars.eq in *; simpl in *.\n            rewrite HMapP.add_neq_o. \n            { rewrite H2. rewrite HEqual'. rewrite HMapP.add_neq_o; [reflexivity | contradict n; intuition]. }\n            { simpl. contradict n. intuition. } \n        - do 2 constructor; assumption.\n        - constructor. constructor.  apply HMapP.Equal_Equiv in HEqual'. inversion HEqual'. apply H4. assumption. }\n    + { exists (update_H (r, l, v) heapa). exists (update_H (r, l, v) heap2'); repeat split.\n        -  unfold H.Equal in *; unfold update_H in *; simpl in *.\n          intros [r' l'].\n          destruct (RegionVars.eq_dec (r', l') (r, l)).\n          * inversion_clear e; simpl in *; subst.\n            do 2 rewrite H_same_key. reflexivity.\n          * unfold RegionVars.eq in *; simpl in *.\n            rewrite HMapP.add_neq_o. \n            { rewrite HEqual. rewrite HMapP.add_neq_o; [reflexivity | contradict n; intuition]. }\n            { simpl. contradict n. intuition. } \n        - constructor. constructor.\n        - do 2 constructor. apply HMapP.Equal_Equiv in HEqual. inversion HEqual. apply H0. assumption.  }\n    + apply HMapP.Equal_sym in HEqual.\n      edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n        as [heap2'' [HEqual' HStep2']]. clear HStep2.\n      eapply monotonic_heap_updates in H; eauto.\n      replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Write in HStep2'; eauto.\n      destruct HStep2' as [? [? ?]].\n      { exists x. exists (update_H (r, l, v) heap2'); repeat split.\n        -  unfold H.Equal in *; unfold update_H in *; simpl in *.\n          intros [r' l'].\n          destruct (RegionVars.eq_dec (r', l') (r, l)).\n          * inversion_clear e; simpl in *; subst.\n             rewrite H2. do 2 rewrite H_same_key. reflexivity.\n          * unfold RegionVars.eq in *; simpl in *.\n            rewrite HMapP.add_neq_o. \n            { rewrite H2. rewrite HEqual'. rewrite HMapP.add_neq_o; [reflexivity | contradict n; intuition]. }\n            { simpl. contradict n. intuition. } \n        - do 2 constructor; assumption.\n        - constructor. constructor. apply HMapP.Equal_Equiv in HEqual'. inversion HEqual'. apply H4. assumption. }\n    +  apply HMapP.Equal_sym in HEqual.\n      edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n         as [heap2'' [HEqual' HStep2']]. clear HStep2.\n      eapply monotonic_heap_updates in H; eauto.\n      replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Write in HStep2'; eauto.\n      destruct HStep2' as [? [? ?]].\n      { exists x. exists (update_H (r, l, v) heap2'); repeat split.\n        - unfold H.Equal in *; unfold update_H in *; simpl in *.\n          intros [r' l'].\n          destruct (RegionVars.eq_dec (r', l') (r, l)).\n          * inversion_clear e; simpl in *; subst.\n             rewrite H2. do 2 rewrite H_same_key. reflexivity.\n          * unfold RegionVars.eq in *; simpl in *.\n            rewrite HMapP.add_neq_o. \n            { rewrite H2. rewrite HEqual'. rewrite HMapP.add_neq_o; [reflexivity | contradict n; intuition]. }\n            { simpl. contradict n. intuition. } \n        - do 2 constructor; assumption.\n        - constructor. constructor. apply HMapP.Equal_Equiv in HEqual'. inversion HEqual'. apply H4. assumption.  }            \n    +  { exists (update_H (r, l, v) heapa). exists (update_H (r, l, v) heap2'); repeat split.\n        -  unfold H.Equal in *; unfold update_H in *; simpl in *.\n          intros [r' l'].\n          destruct (RegionVars.eq_dec (r', l') (r, l)).\n          * inversion_clear e; simpl in *; subst.\n            do 2 rewrite H_same_key. reflexivity.\n          * unfold RegionVars.eq in *; simpl in *.\n            rewrite HMapP.add_neq_o. \n            { rewrite HEqual. rewrite HMapP.add_neq_o; [reflexivity | contradict n; intuition]. }\n            { simpl. contradict n. intuition. } \n        - constructor. constructor.\n        - do 2 constructor. apply HMapP.Equal_Equiv in HEqual. inversion HEqual. apply H0. assumption.  }\n  - inversion HDet1; subst. clear H2.\n    edestruct IHHStep1 with (phi2:=phi1)  as [heapA [heapB [? [? ?]]]]; eauto.\n    + simpl in HDisj. apply Disjointness_app_app_and_r in HDisj. destruct HDisj. assumption.\n    + simpl in HConf. inversion HDet1.\n      apply Conflictness_app_and_r in HConf; [ destruct HConf  | | | ]; assumption.\n    + exists heapA. exists heapB. repeat split.\n      * assumption.\n      * inversion H0; subst.\n        { apply Phi_Heap_Step_Progress in HStep2. contradiction. }\n        { constructor. assumption. }\n      * inversion H2; subst.\n        { constructor. constructor. assumption. }\n        { apply Phi_Heap_Step_Progress in H2. contradiction. }\n  - inversion HDet1; subst. clear H1.\n    edestruct IHHStep1 with (phi2:=phi0) as [heapA [heapB [? [? ?]]]]; eauto.\n    + exists heapA. exists heapB. repeat split.\n      * assumption.\n      * inversion H0; subst.\n        { apply Phi_Heap_Step_Progress in HStep2. contradiction. }\n        { constructor. assumption. }\n      * inversion H1; subst.\n        { constructor. constructor. assumption. }\n        { apply Phi_Heap_Step_Progress in H1. contradiction. }\n  -  apply HMapP.Equal_sym in HEqual.\n     edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n       as [heap2'' [HEqual' HStep2']]. clear HStep2.\n     exists heap2''. exists heap2'. repeat split.\n     * apply HMapP.Equal_sym. assumption.\n     * constructor; assumption.\n     * constructor; constructor.\n  - inversion HDet1; subst. clear H2.\n    edestruct IHHStep1 with (phi2:=phi1) as [heapA [heapB [? [? ?]]]]; eauto.\n    + simpl in HDisj. apply Disjointness_app_app_and_r in HDisj. destruct HDisj. assumption.\n    + simpl in HConf. inversion HDet1.\n      apply Conflictness_app_and_r in HConf; [ destruct HConf  | | | ]; assumption.\n    + exists heapA. exists heapB. repeat split.\n      * assumption.\n      * inversion H0; subst.\n        { apply Phi_Heap_Step_Progress in HStep2. contradiction. }\n        { constructor. assumption. }\n      * inversion H2; subst.\n        { constructor. constructor. assumption. }\n        { apply Phi_Heap_Step_Progress in H2. contradiction. }\n  - inversion HDet1; subst. \n    edestruct IHHStep1 with (phi2:=phi1) as [heapA [heapB [? [? ?]]]]; eauto.\n    + simpl in HDisj. apply Disjointness_app_app_and_r in HDisj. destruct HDisj. assumption.\n    + simpl in HConf. inversion HDet1.\n      apply Conflictness_app_and_r in HConf; [ destruct HConf  | | | ]; assumption.\n    + exists heapA. exists heapB. repeat split.\n      * assumption.\n      * inversion H0; subst.\n        { apply Phi_Heap_Step_Progress in HStep2. contradiction. }\n        { constructor. assumption. }\n      * inversion H4; subst.\n        { constructor. constructor. assumption. }\n        { apply Phi_Heap_Step_Progress in H4. contradiction. }\n   -  apply HMapP.Equal_sym in HEqual.\n      edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n        as [heap2'' [HEqual' HStep2']]. clear HStep2.\n      exists heap2''. exists heap2'. repeat split.\n     * apply HMapP.Equal_sym. assumption. \n     * constructor; assumption.\n     * constructor; constructor.\nQed.\n\n\n\nLemma Diamond_Step :\n  forall phi0 phi1 phi2 heap0 heap1 heap2,\n    Det_Trace phi0 ->\n    (phi0, heap0) ===> (phi1, heap1) ->\n    (phi0, heap0) ===> (phi2, heap2) ->\n    exists phi3, exists heap3, exists heap4, exists n13, exists n23,\n      H.Equal heap3 heap4 /\\                                                     \n      (phi1, heap1) =a=>* (phi3, heap3, n13) /\\\n      (phi2, heap2) =a=>* (phi3, heap4, n23) /\\\n      (n13 <= 1) /\\ (n23 <= 1).\nProof.\n  induction phi0; intros phi1 phi2 heap0 heap1 heap2 HDet H0_1 H0_2.\n  + inversion H0_1.\n  + destruct d; inversion H0_1; subst; inversion H0_2; subst;\n    repeat eexists; repeat econstructor.\n  + inversion H0_1; subst; inversion H0_2; subst.\n  - inversion HDet; subst.\n      edestruct (IHphi0_1 phi1' phi1'0) as [phi3 [heap3 [heap4 [n13 [n23 [? [? [? ?]]]]]]]]; try eassumption.\n      exists (Phi_Par phi3 phi0_2). exists heap3. exists heap4.  exists n13. exists n23; repeat split;\n         try (solve [assumption | destruct H7; eassumption | eapply Par_Left_Pres; assumption]) .\n    - inversion HDet; subst. destruct H5.\n      edestruct (Par_Step_Equal phi0_1 phi0_2) as [heap3 [heap4 [? [? ?]]]]; try eassumption.\n      exists (Phi_Par phi1' phi2'). exists heap3. exists heap4.\n      repeat eexists; try (eapply PHT_Step; eassumption); repeat constructor. assumption.\n    - inversion H0.\n    - inversion HDet; subst. destruct H5.\n      edestruct (Par_Step_Equal phi0_1 phi0_2 phi1' phi2') as [heap3 [heap4 [? [? ?]]]]; try eassumption.\n      exists (Phi_Par phi1' phi2'). exists heap4. exists heap3. \n      repeat eexists; try (eapply PHT_Step; eassumption); repeat constructor.\n      apply HMapP.Equal_sym; assumption.\n    - inversion HDet; subst.\n      edestruct (IHphi0_2 phi2' phi2'0) as [phi3 [heap3 [heap4 [n13 [n23 [? [? [? ?]]]]]]]]; try eassumption.\n      exists (Phi_Par phi0_1 phi3). exists heap3. exists heap4. exists n13. exists n23; repeat split;\n        try (solve [assumption | destruct H7; eassumption | eapply Par_Right_Pres; assumption]) .\n    - inversion H0.\n    - inversion H0.\n    - inversion H0.\n    - exists Phi_Nil. exists heap2. repeat eexists; repeat econstructor.\n  + inversion H0_1; subst; inversion H0_2; subst.\n    - inversion HDet; subst.\n      edestruct (IHphi0_1 phi1' phi1'0) as [phi3 [heap3 [heap4 [n13 [n23 [? [? [? ?]]]]]]]]; try eassumption.\n      exists (Phi_Seq phi3 phi0_2). exists heap3. exists heap4. exists n13. exists n23. repeat split;\n        try (solve [assumption | destruct H6; eassumption | eapply Seq_Left_Pres; assumption]) .\n    - inversion H0.\n    - inversion H0.\n    - inversion H1.\n    - inversion HDet; subst.\n      edestruct (IHphi0_2 phi2' phi2'0) as [phi3 [heap3 [heap4 [n13 [n23 [? [? [? ?]]]]]]]]; try eassumption.\n      exists (Phi_Seq Phi_Nil phi3). exists heap3. exists heap4. exists n13. exists n23; repeat split;\n        try (solve [assumption | destruct H6; eassumption | eapply Seq_Right_Pres; assumption]) .\n    - inversion H0.\n    - inversion H0.\n    - inversion H0.\n    - exists Phi_Nil. exists heap2. repeat eexists; repeat econstructor.\nQed.\n\nLemma Diamond_Step_new :\n  forall phi0 phi1 phi2 heapa heapb heap1 heap2,\n    Det_Trace phi0 ->\n    H.Equal heapa heapb ->\n    (phi0, heapa) ===> (phi1, heap1) ->\n    (phi0, heapb) ===> (phi2, heap2) ->\n    exists phi3, exists heap3, exists heap4, exists n13, exists n23,\n      H.Equal heap3 heap4 /\\                                                     \n      (phi1, heap1) =a=>* (phi3, heap3, n13) /\\\n      (phi2, heap2) =a=>* (phi3, heap4, n23) /\\\n      (n13 <= 1) /\\ (n23 <= 1).\nProof.\n  induction phi0; intros phi1 phi2 heapa heapb heap1 heap2 HDet HEqual H0_1 H0_2.\n  + inversion H0_1.\n  + destruct d; inversion H0_1; subst; inversion H0_2; subst; exists Phi_Nil.\n    - exists (update_H (r, n, v) heapa); exists (update_H (r, n, v) heapb).\n      repeat eexists; repeat econstructor.\n      unfold H.Equal in *; unfold update_H in *; simpl in *.\n      intros [r' n'].\n      destruct (RegionVars.eq_dec (r', n') (r, n)).\n        * inversion_clear e; simpl in *; subst.\n          do 2 rewrite H_same_key_1. reflexivity.\n        * unfold RegionVars.eq in *; simpl in *.\n          rewrite HMapP.add_neq_o by (contradict n0; intuition).\n          rewrite HMapP.add_neq_o by (contradict n0; intuition).\n          apply HEqual.\n    - exists heap1; exists heap2; repeat eexists; repeat econstructor.\n      assumption.\n    - exists (update_H (r, n, v) heapa); exists (update_H (r, n, v) heapb).\n      repeat eexists; repeat econstructor.\n      unfold H.Equal in *; unfold update_H in *; simpl in *.\n      intros [r' n'].\n      destruct (RegionVars.eq_dec (r', n') (r, n)).\n        * inversion_clear e; simpl in *; subst.\n          do 2 rewrite H_same_key_1. reflexivity.\n        * unfold RegionVars.eq in *; simpl in *.\n          rewrite HMapP.add_neq_o by (contradict n0; intuition).\n          rewrite HMapP.add_neq_o by (contradict n0; intuition).\n          apply HEqual.\n  + inversion H0_1; subst; inversion H0_2; subst.\n  - inversion HDet; subst.\n      edestruct (IHphi0_1 phi1' phi1'0) as [phi3 [heap3 [heap4 [n13 [n23 [? [? [? ?]]]]]]]]; try eassumption.\n      exists (Phi_Par phi3 phi0_2). exists heap3. exists heap4.  exists n13. exists n23; repeat split;\n         try (solve [assumption | destruct H7; eassumption | eapply Par_Left_Pres; assumption]) .\n    - inversion HDet; subst. destruct H5.\n      edestruct (Par_Step_Equal_new phi0_1 phi0_2) as [heap3 [heap4 [? [? ?]]]]; try eassumption.\n      exists (Phi_Par phi1' phi2'). exists heap3. exists heap4.\n      repeat eexists; try (eapply PHT_Step; eassumption); repeat constructor. assumption.\n    - inversion H0.\n    - inversion HDet; subst. destruct H5.\n      assert (HEqual': H.Equal heapb heapa) by (eauto using HMapP.Equal_sym).\n      edestruct (Par_Step_Equal_new phi0_1 phi0_2 phi1' phi2') as [heap3 [heap4 [? [? ?]]]]; try eassumption.\n      exists (Phi_Par phi1' phi2'). exists heap4. exists heap3. \n      repeat eexists; try (eapply PHT_Step; eassumption); repeat constructor.\n      apply HMapP.Equal_sym; assumption.\n    - inversion HDet; subst.\n      edestruct (IHphi0_2 phi2' phi2'0) as [phi3 [heap3 [heap4 [n13 [n23 [? [? [? ?]]]]]]]]; try eassumption.\n      exists (Phi_Par phi0_1 phi3). exists heap3. exists heap4. exists n13. exists n23; repeat split;\n        try (solve [assumption | destruct H7; eassumption | eapply Par_Right_Pres; assumption]) .\n    - inversion H0.\n    - inversion H0.\n    - inversion H0.\n    - exists Phi_Nil. exists heap1. exists heap2. repeat eexists; repeat econstructor; assumption.\n  + inversion H0_1; subst; inversion H0_2; subst.\n    - inversion HDet; subst.\n      edestruct (IHphi0_1 phi1' phi1'0) as [phi3 [heap3 [heap4 [n13 [n23 [? [? [? ?]]]]]]]]; try eassumption.\n      exists (Phi_Seq phi3 phi0_2). exists heap3. exists heap4. exists n13. exists n23. repeat split;\n        try (solve [assumption | destruct H6; eassumption | eapply Seq_Left_Pres; assumption]) .\n    - inversion H0.\n    - inversion H0.\n    - inversion H1.\n    - inversion HDet; subst.\n      edestruct (IHphi0_2 phi2' phi2'0) as [phi3 [heap3 [heap4 [n13 [n23 [? [? [? ?]]]]]]]]; try eassumption.\n      exists (Phi_Seq Phi_Nil phi3). exists heap3. exists heap4. exists n13. exists n23; repeat split;\n        try (solve [assumption | destruct H6; eassumption | eapply Seq_Right_Pres; assumption]) .\n    - inversion H0.\n    - inversion H0.\n    - inversion H0.\n    - exists Phi_Nil. exists heap1. exists heap2. repeat eexists; repeat econstructor; assumption.\nQed.\n\nTheorem Phi_Heap_Step__Preserves_DAs :\n  forall phi phi' heap heap',\n    (phi, heap) ===> (phi', heap') ->\n    (forall da,\n       In da (phi_as_list phi') ->\n       In da (phi_as_list phi)).\nProof.\n  intros phi phi' heap heap' HStep.\n  dependent induction HStep; intros da HIn; simpl phi_as_list in *.\n  - inversion HIn.\n  - inversion HIn.\n  - inversion HIn.\n  - apply in_or_app.\n    apply in_app_or in HIn; destruct HIn.\n    + left; apply IHHStep; assumption.\n    + right; assumption.\n  - apply IHHStep; assumption.\n  - assumption.\n  - apply in_or_app.\n    apply in_app_or in HIn; destruct HIn.\n    + left; apply IHHStep; assumption.\n    + right; assumption.\n  - apply in_or_app.\n    apply in_app_or in HIn; destruct HIn.\n    + left; assumption.\n    + right; apply IHHStep; assumption.\n  - assumption.\nQed.\n\nLemma Det_Pres_Par_Conf_1:\n  forall phi1 phi1' phi2 heap heap',\n    (phi1, heap) ===> (phi1', heap') ->\n    Det_Trace (Phi_Par phi1 phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1') (phi_as_list phi2).\nProof.\n  intros. inversion H0; subst. destruct H5.\n  intro. inversion H5; subst. apply H1.\n  econstructor; eauto using Phi_Heap_Step__Preserves_DAs.\nQed.\n\nLemma Det_Pres_Par_Conf_1_aux:\n  forall phi1 phi1' phi2 heap heap',\n    (phi1, heap) ===> (phi1', heap') ->\n    Det_Trace phi1' ->\n    Det_Trace (Phi_Par phi1 phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1') (phi_as_list phi2).\nProof.\n  intros phi1 phi1' phi2 heap heap' H1 H2 H3.\n  inversion_clear H3; subst. destruct H4. clear H4.\n  generalize dependent phi2.  \n  dependent induction H1; intros; subst; simpl in *.\n  - intro. inversion H1. trivial.\n  - intro. inversion H4. trivial.\n  - intro. inversion H4. trivial.\n  - inversion H2; inversion H; subst.  \n    apply Conflictness_app_and_r in H3; auto. destruct H3.\n    apply Conflictness_and_app_r; auto.\n  - apply IHPhi_Heap_Step; auto; inversion H2; inversion H; assumption.\n  - apply H3.\n  - inversion H2; inversion H; subst.\n    apply Conflictness_app_and_r in H3; auto. destruct H3.\n    apply Conflictness_and_app_r; auto.\n  - inversion H2; inversion H; subst.\n    destruct H8.\n    apply Conflictness_app_and_r in H3; auto. destruct H3.\n    apply Conflictness_and_app_r; auto.\n  - intro; now apply H3.\nQed.\n\nLemma Det_Pres_Par_Conf_2:\n  forall phi1 phi1' phi2 heap heap',\n    (phi1, heap) ===> (phi1', heap') ->\n    Det_Trace (Phi_Par phi1 phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1') (phi_as_list phi2).\nProof.\n  intros. inversion H0; subst. destruct H5.\n  intro. inversion H5; subst. apply H1. \n  econstructor; eauto using Phi_Heap_Step__Preserves_DAs.\nQed.\n\nLemma Det_Pres_Par_Conf_2_aux:\n  forall phi1 phi2 phi2' heap heap',\n    (phi2, heap) ===> (phi2', heap') ->\n    Det_Trace phi2' ->\n    Det_Trace (Phi_Par phi1 phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1) (phi_as_list phi2').\nProof.\n  intros phi1 phi2 phi2' heap heap' H1 H2 H3.\n   inversion_clear H3; subst. destruct H4. clear H4.  \n   generalize dependent phi1. \n   dependent induction H1; intros; inversion H0; subst; simpl in *.\n   - intro. inversion H1; trivial.\n   - intro. inversion H4; trivial.\n   - intro. inversion H4; trivial.\n   - inversion H2; inversion H0; subst.\n     eapply Conflictness_app_and_l in H3; auto.  destruct H3. \n     apply Conflictness_and_app_l; auto.\n   - apply IHPhi_Heap_Step; auto. inversion H2; inversion H0; assumption.\n   - apply H3.\n   - inversion H2; inversion H0; subst.\n     destruct H8.\n     apply Conflictness_app_and_l in H3; auto. destruct H3.\n     apply Conflictness_and_app_l; auto. \n   - inversion H2; inversion H0; subst.\n     destruct H8.\n     apply Conflictness_app_and_l in H3; auto. destruct H3.\n     apply Conflictness_and_app_l; auto. \n   - intro. inversion H1; trivial.\nQed.\n\n\nLemma Det_Pres_Par_Disj_1:\n  forall phi1 phi1' phi2 heap heap',\n    (phi1, heap) ===> (phi1', heap') ->\n    Det_Trace phi1' ->\n    Det_Trace (Phi_Par phi1 phi2) ->\n    Disjoint_Traces (phi_as_list phi1') (phi_as_list phi2).\nProof.\n  intros phi1 phi1' phi2 heap heap' H1 H2 H3.\n  inversion H3; subst; simpl. destruct H6.\n  inversion H0; subst. econstructor; intros. apply H6; auto.\n  eapply Phi_Heap_Step__Preserves_DAs; eauto.\nQed.    \n \nLemma Det_Pres_Par_Disj_1_aux:\n  forall phi1 phi1' phi2 heap heap',\n    (phi1, heap) ===> (phi1', heap') ->\n    Det_Trace phi1' ->\n    Det_Trace (Phi_Par phi1 phi2) ->\n    Disjoint_Traces (phi_as_list phi1') (phi_as_list phi2).\nProof.\n  intros phi1 phi1' phi2 heap heap' H1 H2 H3.\n  inversion_clear H3; subst. destruct H4. clear H3.\n  generalize dependent phi2.     \n  dependent induction H1; intros; simpl; try (solve [constructor]).\n  inversion H4; subst;\n  simpl in *; try (solve [econstructor ]).\n  - econstructor; intros. apply H1; [inversion H3 | assumption].\n  - econstructor; intros. inversion H3.\n  - econstructor; intros. inversion H3.\n  - inversion H2; inversion H; subst.\n    apply Disjointness_and_app_r. simpl in H4.\n    apply Disjointness_app_app_and_r in H4. destruct H4.\n    split; [ apply IHPhi_Heap_Step; eauto | assumption].\n  - inversion H2; inversion H. simpl in H4.\n    apply IHPhi_Heap_Step; eauto.\n  - econstructor; intros. inversion H1. \n  - inversion H2; inversion H; subst.\n    apply Disjointness_and_app_r. simpl in H4.\n    apply Disjointness_app_app_and_r in H4. destruct H4.\n    split; [ apply IHPhi_Heap_Step; eauto | assumption].\n  - inversion H2; inversion H; subst.\n    apply Disjointness_and_app_r. simpl in H4.\n    apply Disjointness_app_app_and_r in H4. destruct H4.\n    split; [ assumption | apply IHPhi_Heap_Step; eauto].\n  -  econstructor; intros. inversion H1.    \nQed.\n\nLemma Det_Pres_Par_Disj_2:\n  forall phi2 phi2' phi1 heap heap',\n    (phi2, heap) ===> (phi2', heap') ->\n    Det_Trace phi2' ->\n    Det_Trace (Phi_Par phi1 phi2) ->\n    Disjoint_Traces (phi_as_list phi1) (phi_as_list phi2').\nProof.\n  intros phi2 phi2' phi1 heap heap' H1 H2 H3.\n   inversion H3; subst; simpl. destruct H6.\n  inversion H0; subst. econstructor; intros. apply H6; auto.\n  eapply Phi_Heap_Step__Preserves_DAs; eauto.\nQed.   \n\nLemma Det_Pres_Par_Disj_2_aux:\n  forall phi2 phi2' phi1 heap heap',\n    (phi2, heap) ===> (phi2', heap') ->\n    Det_Trace phi2' ->\n    Det_Trace (Phi_Par phi1 phi2) ->\n    Disjoint_Traces (phi_as_list phi1) (phi_as_list phi2').\nProof.\n  intros phi2 phi2' phi1 heap heap' H1 H2 H3.\n  inversion_clear H3; subst. destruct H4. clear H3.\n  generalize dependent phi1.     \n  dependent induction H1; intros; simpl in *;\n  try (solve [constructor |\n              econstructor; intros; inversion H5 |\n              econstructor; intros; inversion H3\n             ]).\n  - inversion H2; inversion H0; subst.\n    apply Disjointness_and_app_l. simpl in H4.\n    apply Disjointness_app_app_and_l in H4. destruct H4.\n    split; [apply IHPhi_Heap_Step; eauto | assumption].\n  - inversion H2; inversion H0. \n    apply IHPhi_Heap_Step; eauto.\n  - inversion H2; inversion H0; subst.\n    apply Disjointness_and_app_l. simpl in H4.\n    apply Disjointness_app_app_and_l in H4. destruct H4.\n    split; [apply IHPhi_Heap_Step; eauto | assumption].\n  -  inversion H2; inversion H0; subst.\n    apply Disjointness_and_app_l. simpl in H4.\n    apply Disjointness_app_app_and_l in H4. destruct H4.\n    split; [assumption | apply IHPhi_Heap_Step; eauto].\nQed.\n\nTheorem Det_Pres_Aux :\n   forall phi phi' heap heap',\n     (phi, heap) ===> (phi', heap') ->\n     Det_Trace phi ->\n     Det_Trace phi'.\nProof.\n  intros phi phi' heap heap' H1 H2.\n  dependent induction H1; intros; try (solve [constructor]).\n  - inversion H2; econstructor; [ apply IHPhi_Heap_Step; assumption | assumption].\n  - inversion H2; econstructor. constructor. apply IHPhi_Heap_Step; assumption. \n  - inversion H2; subst; econstructor; [ apply IHPhi_Heap_Step; assumption | inversion H2; assumption |].\n    destruct H5. split.\n    + intro; inversion H5; subst.\n      apply H; econstructor; eauto using Phi_Heap_Step__Preserves_DAs.\n    + constructor; intros.\n      inversion H0; subst.\n      apply H7; eauto using Phi_Heap_Step__Preserves_DAs.\n  - inversion H2; subst; econstructor; [assumption | apply IHPhi_Heap_Step; assumption |].\n    destruct H5. split.\n    + intro; inversion H5; subst.\n      apply H; econstructor; eauto using Phi_Heap_Step__Preserves_DAs.\n    + constructor; intros.\n      inversion H0; subst.\n      apply H7; eauto using Phi_Heap_Step__Preserves_DAs.\nQed.    \n\nTheorem Det_Pres :\n   forall phi phi' heap heap' n',\n     (phi, heap) =a=>* (phi', heap', n') ->\n     Det_Trace phi ->\n     Det_Trace phi'.\nProof.\n   intros phi phi' heap heap' n' HSteps.\n   dependent induction HSteps; intro HDet.\n   - assumption.\n   - eapply Det_Pres_Aux; eassumption.\n   - apply IHHSteps2; apply IHHSteps1; assumption.\nQed.\n\n\nRequire Import Omega.\n    \nTheorem Diamond_Walk_Aux : \n  forall n n1 n2,\n    n = n1 + n2 ->\n    forall phi0 phi1 phi2 heap0 heap1 heap2,\n    forall (H0_1: (phi0, heap0) =a=>* (phi1, heap1, n1)),\n    forall (H0_2: (phi0, heap0) =a=>* (phi2, heap2, n2)),\n      Det_Trace phi0 ->\n      exists phi3, exists heap3, exists heap4, exists n13, exists n23,\n        H.Equal heap3 heap4 /\\                                                             \n        (phi1, heap1) =a=>* (phi3, heap3, n13) /\\\n        (phi2, heap2) =a=>* (phi3, heap4, n23) /\\\n        (n13 <= n2) /\\ (n23 <= n1).\nProof.\n  induction n using Wf_nat.lt_wf_ind.\n  intros n1 n2 HSum.\n  intros phi0 phi1 phi2 heap0 heap1 heap2 H0_1 H0_2 HDet. \n  dependent destruction H0_1.\n  - exists phi2; exists heap2; exists heap2; exists n2; exists 0.\n   repeat split; try (solve [omega]).\n   + assumption.  (* phi1 walks into phi1 in n2 steps *)\n   + apply PHT_Refl.  (* phi2 takes 0 steps *)\n  -  rename H0 into H0_1.  \n    dependent destruction H0_2.\n    + exists phi1. exists heap1. exists heap1. exists 0. exists 1.\n      repeat split; try (solve [omega]).\n      * apply PHT_Refl. (* phi1 takes 0 steps *)\n      * apply PHT_Step; assumption. (* phi2 walks into phi1 in 1 step *)\n    + rename H0 into H0_2.\n      destruct (Diamond_Step phi0 phi1 phi2 heap0 heap1 heap2 HDet H0_1 H0_2)\n        as [phi3 [heap3 [heap4 [n13 [n23 [Heq [H1_3 [H2_3 [? ?]]]]]]]]].\n      exists phi3. exists heap3. exists heap4. exists n13. exists n23. (* n13 and n23 are the remaining steps *)\n      repeat split;  try (solve [omega]). \n      * assumption. (* context provided by Diamond_Step *)\n      * assumption. (* context provided by Diamond_Step *)\n      * assumption.\n    + rename phi' into phi2'. rename heap' into heap2'. \n      rename H0_2_1 into H0_2'. rename H0_2_2 into H2'_2. \n      edestruct (H (1 + n')) as [phi3 [heap3 [heap4 [n1_3 [n2'_3 [Heq [H1_3 [H2'_3 [? ?]]]]]]]]]. (* transitivity on phi2 *)\n      * omega. (* phi2 took n' intermediate steps *)\n      * reflexivity.\n      * eapply PHT_Step; eassumption.  (* phi1 steps 1 *)\n      * eassumption. (* by induction *)\n      * eassumption. (* by induction *)  \n      * { edestruct (H (n2'_3 + n'')) as [phi4 [heap5 [heap6 [n3_4 [n2_4 [Heq' [H3_4 [H2_4 [? ?]]]]]]]]].\n          - omega.  (* phi2 took n'' intermediate steps *)\n          - reflexivity.\n          - eassumption. (* by induction *)\n          - eassumption. (* by induction *)\n          - eapply Det_Pres; eassumption.\n          - apply Aux_Step_Ext_Heap with (heapB:=heap3) in H3_4; [ | apply HMapP.Equal_sym; assumption].\n            destruct H3_4 as [heap5' [? ?]].\n            exists phi4. exists heap5'. exists heap6. exists (1 + n1_3 + n3_4). exists n2_4.\n            repeat split; try (solve [omega]).\n            + eapply HMapP.Equal_trans in Heq'; eauto. apply HMapP.Equal_sym; assumption.  \n            + eapply PHT_Trans. eassumption. assumption.\n            + assumption. }\n  - rename phi' into phi1'. rename heap' into heap1'.\n    rename H0_1_1 into H0_1'. rename H0_1_2 into H1'_1.\n    edestruct (H (n' + n2)) as [phi3 [heap3 [heap4 [n1'_3 [n2_3 [Heq [H1'_3 [H2_3 [? ?]]]]]]]]].\n    + omega.  (* phi1 took n' intermediate steps *)\n    + reflexivity.\n    + eassumption.\n    + eassumption.\n    + assumption.\n    + edestruct (H (n'' + n1'_3)) as [phi4 [heap5 [heap6 [n1_4 [n3_4 [Heq' [H1_4 [H3_4 [? ?]]]]]]]]].\n      * omega. (* phi1 took the remaining n'' intermediate steps *)\n      * reflexivity. \n      * eassumption.\n      * eassumption.\n      * eapply Det_Pres; eassumption.\n      * apply Aux_Step_Ext_Heap with (heapB:=heap4) in H3_4; [ |assumption].\n        destruct H3_4 as [heap6' [? ?]]. \n        exists phi4. exists heap5. exists heap6'. exists n1_4. exists (1 + n2_3 + n3_4).\n        repeat split;  try (solve [omega]).\n        { eapply HMapP.Equal_trans in H4; eauto. }\n        { assumption. }\n        { eapply PHT_Trans. eassumption. assumption. }\nQed.\n\nTheorem Diamond_Walk_Aux_new : \n  forall n n1 n2,\n    n = n1 + n2 ->\n    forall phi0 phi1 phi2 heapa heapb heap1 heap2,\n    H.Equal heapa heapb ->\n    forall (H0_1: (phi0, heapa) =a=>* (phi1, heap1, n1)),\n    forall (H0_2: (phi0, heapb) =a=>* (phi2, heap2, n2)),\n      Det_Trace phi0 ->\n      exists phi3, exists heap3, exists heap4, exists n13, exists n23,\n        H.Equal heap3 heap4 /\\\n        (phi1, heap1) =a=>* (phi3, heap3, n13) /\\\n        (phi2, heap2) =a=>* (phi3, heap4, n23) /\\\n        (n13 <= n2) /\\ (n23 <= n1).\nProof.\n  induction n using Wf_nat.lt_wf_ind.\n  intros n1 n2 HSum.\n  intros phi0 phi1 phi2 heapa heapb heap1 heap2 HEqual H0_1 H0_2 HDet. \n  dependent destruction H0_1.\n  - assert (HEqual' : H.Equal heapb heap1) by (eauto using HMapP.Equal_sym).\n    edestruct (Aux_Step_Ext_Heap _ _ _ _ _ _ H0_2 HEqual')\n     as [heap2' [HEqual'' ?]].\n    exists phi2; exists heap2'; exists heap2; exists n2; exists 0.\n    repeat split; try (solve [omega]).\n    + eauto using HMapP.Equal_sym.  \n    + assumption. (* phi1 walks into phi2 in n2 steps *)\n    + apply PHT_Refl.  (* phi2 takes 0 steps *)\n  - rename H0 into H0_1.  \n    dependent destruction H0_2.\n    + edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ H0_1 HEqual)\n       as [heap1' [HEqual' H0_1']].\n      exists phi1. exists heap1. exists heap1'. exists 0. exists 1.\n      repeat split; try (solve [omega]).\n      * assumption.\n      * apply PHT_Refl. (* phi1 takes 0 steps *)\n      * apply PHT_Step; assumption. (* phi2 walks into phi1 in 1 step *)\n    + rename H0 into H0_2.\n      destruct (Diamond_Step_new phi0 phi1 phi2 heapa heapb heap1 heap2 HDet HEqual H0_1 H0_2)\n        as [phi3 [heap3 [heap4 [n13 [n23 [Heq [H1_3 [H2_3 [? ?]]]]]]]]].\n      exists phi3. exists heap3. exists heap4. exists n13. exists n23. (* n13 and n23 are the remaining steps *)\n      repeat split;  try (solve [omega]). \n      * assumption.\n      * assumption. (* context provided by Diamond_Step *)\n      * assumption. (* context provided by Diamond_Step *)\n    + rename phi' into phi2'. rename heap' into heap2'. \n      rename H0_2_1 into H0_2'. rename H0_2_2 into H2'_2. \n      edestruct (H (1 + n')) as [phi3 [heap3 [heap4 [n1_3 [n2'_3 [Heq [H1_3 [H2'_3 [? ?]]]]]]]]]. (* transitivity on phi2 *)\n      * omega. (* phi2 took n' intermediate steps *)\n      * reflexivity.\n      * eassumption.\n      * eapply PHT_Step; eassumption.  (* phi1 steps 1 *)\n      * eassumption. (* by induction *)\n      * eassumption. (* by induction *)  \n      * { edestruct (H (n2'_3 + n'')) as [phi4 [heap5 [heap6 [n3_4 [n2_4 [Heq' [H3_4 [H2_4 [? ?]]]]]]]]].\n          - omega.  (* phi2 took n'' intermediate steps *)\n          - reflexivity.\n          - apply HMapP.Equal_refl.\n          - eassumption. (* by induction *)\n          - eassumption. (* by induction *)\n          - eapply Det_Pres; eassumption.\n          - apply Aux_Step_Ext_Heap with (heapB:=heap3) in H3_4; [ | apply HMapP.Equal_sym; assumption].\n            destruct H3_4 as [heap5' [? ?]].\n            exists phi4. exists heap5'. exists heap6. exists (1 + n1_3 + n3_4). exists n2_4.\n            repeat split; try (solve [omega]).\n            + eapply HMapP.Equal_trans in Heq'; eauto. apply HMapP.Equal_sym; assumption.  \n            + eapply PHT_Trans. eassumption. assumption.\n            + assumption. }\n  - rename phi' into phi1'. rename heap' into heap1'.\n    rename H0_1_1 into H0_1'. rename H0_1_2 into H1'_1.\n    edestruct (H (n' + n2)) as [phi3 [heap3 [heap4 [n1'_3 [n2_3 [Heq [H1'_3 [H2_3 [? ?]]]]]]]]].\n    + omega.  (* phi1 took n' intermediate steps *)\n    + reflexivity.\n    + eassumption.\n    + eassumption.\n    + eassumption.\n    + assumption.\n    + edestruct (H (n'' + n1'_3)) as [phi4 [heap5 [heap6 [n1_4 [n3_4 [Heq' [H1_4 [H3_4 [? ?]]]]]]]]].\n      * omega. (* phi1 took the remaining n'' intermediate steps *)\n      * reflexivity. \n      * apply HMapP.Equal_refl.\n      * eassumption.\n      * eassumption.\n      * eapply Det_Pres; eassumption.\n      * apply Aux_Step_Ext_Heap with (heapB:=heap4) in H3_4; [ |assumption].\n        destruct H3_4 as [heap6' [? ?]]. \n        exists phi4. exists heap5. exists heap6'. exists n1_4. exists (1 + n2_3 + n3_4).\n        repeat split;  try (solve [omega]).\n        { eapply HMapP.Equal_trans in H4; eauto. }\n        { assumption. }\n        { eapply PHT_Trans. eassumption. assumption. }\nQed.\n\nTheorem Diamond_Walk : \n  forall phi0 phi1 phi2 heap0 heap1 heap2,\n    (phi0, heap0) ==>* (phi1, heap1) ->\n    (phi0, heap0) ==>* (phi2, heap2) ->\n    Det_Trace phi0 ->\n    exists phi3, exists heap3, exists heap4,\n      H.Equal heap3 heap4 /\\                           \n      (phi1, heap1) ==>* (phi3, heap3) /\\\n      (phi2, heap2) ==>* (phi3, heap4).\nProof.\n  intros phi0 phi1 phi2 heap0 heap1 heap2 H0_1 H0_2 HDet.\n  unfold Phi_Heap_Steps in *.\n  destruct H0_1 as [n0_1 H0_1].\n  destruct H0_2 as [n0_2 H0_2].\n  edestruct (Diamond_Walk_Aux (n0_1 + n0_2) n0_1 n0_2) as [phi3 [heap3 [heap4 [n1_3 [n2_3 [Heq [H1_3 [H2_3 [? ?]]]]]]]]]; eauto.\n  exists phi3. exists heap3. exists heap4. repeat split;[ assumption | |]; eexists; eassumption.\nQed.\n\nTheorem Diamond_Walk_new : \n  forall phi0 phi1 phi2 heapa heapb heap1 heap2,\n    H.Equal heapa heapb ->\n    (phi0, heapa) ==>* (phi1, heap1) ->\n    (phi0, heapb) ==>* (phi2, heap2) ->\n    Det_Trace phi0 ->\n    exists phi3, exists heap3, exists heap4,\n      H.Equal heap3 heap4 /\\                           \n      (phi1, heap1) ==>* (phi3, heap3) /\\\n      (phi2, heap2) ==>* (phi3, heap4).\nProof.\n  intros phi0 phi1 phi2 heapa heapb heap1 heap2 HEqual H0_1 H0_2 HDet.\n  unfold Phi_Heap_Steps in *.\n  destruct H0_1 as [n0_1 H0_1].\n  destruct H0_2 as [n0_2 H0_2].\n  edestruct (Diamond_Walk_Aux_new (n0_1 + n0_2) n0_1 n0_2) as [phi3 [heap3 [heap4 [n1_3 [n2_3 [Heq [H1_3 [H2_3 [? ?]]]]]]]]]; eauto.\n  exists phi3. exists heap3. exists heap4. repeat split;[ assumption | |]; eexists; eassumption.\nQed.\n\nLemma Term_Walk_Idemp :\n  forall heap phi' heap' n,\n    (Phi_Nil, heap) =a=>* (phi', heap', n) ->\n    phi' = Phi_Nil /\\ heap = heap'.\nProof.\n  intros heap phi' heap' n HStep.\n  dependent induction HStep.\n  + split; reflexivity.\n  + inversion H.\n  + eapply IHHStep2.\n    - destruct IHHStep1; subst; reflexivity.\n    - reflexivity.\nQed.\n\nTheorem Diamond_Term_Walk : \n  forall phi0 heap0 heap1 heap2,\n    (phi0, heap0) ==>* (Phi_Nil, heap1) ->\n    (phi0, heap0) ==>* (Phi_Nil, heap2) ->\n    Det_Trace phi0 ->\n    H.Equal heap1 heap2.\nProof.\n  intros phi0 heap0 heap1 heap2 HDet HStep1 HStep2.\n  edestruct (Diamond_Walk phi0 Phi_Nil Phi_Nil heap0 heap1 heap2) as [phi3 [heap3 [heap4 [Heq [H1 H2]]]]]; try eassumption.\n  destruct H1 as [n1 H1]. destruct H2 as [n2 H2].\n  edestruct (Term_Walk_Idemp heap1 phi3 heap3 n1) as [? ?]; try eassumption.\n  edestruct (Term_Walk_Idemp heap2 phi3 heap4 n2) as [? ?]; try eassumption.\n  subst. assumption.\nQed.\n\nTheorem Diamond_Term_Walk_new : \n  forall phi0 heapa heapb heap1 heap2,\n    H.Equal heapa heapb ->\n    (phi0, heapa) ==>* (Phi_Nil, heap1) ->\n    (phi0, heapb) ==>* (Phi_Nil, heap2) ->\n    Det_Trace phi0 ->\n    H.Equal heap1 heap2.\nProof.\n  intros phi0 heapa heapb heap1 heap2 HEqual HStep1 HStep2 HDet.\n  edestruct (Diamond_Walk_new phi0 Phi_Nil Phi_Nil heapa heapb heap1 heap2) as [phi3 [heap3 [heap4 [Heq [H1 H2]]]]]; try eassumption.\n  destruct H1 as [n1 H1]. destruct H2 as [n2 H2].\n  edestruct (Term_Walk_Idemp heap1 phi3 heap3 n1) as [? ?]; try eassumption.\n  edestruct (Term_Walk_Idemp heap2 phi3 heap4 n2) as [? ?]; try eassumption.\n  subst. assumption.\nQed.\n\nLemma Ext_disjoint_sets :\n  forall e1 acts a,\n    Disjoint_Sets_Computed_Actions e1 (set_union acts a) ->\n    Disjoint_Sets_Computed_Actions e1 acts /\\ Disjoint_Sets_Computed_Actions e1 a.\nProof.\n  intros e1 acts a H. \n  split; inversion H; subst.\n  - econstructor; intros. apply H0; auto. unfold set_elem, set_union. apply Union_introl. assumption.\n  - econstructor. intros. apply H0; auto. unfold set_elem, set_union. apply Union_intror. assumption.\nQed.\n\nLemma Ext_disjoint_sets_2 :\n  forall e1 acts a,\n    Disjoint_Sets_Computed_Actions (set_union acts a) e1 ->\n    Disjoint_Sets_Computed_Actions acts e1 /\\ Disjoint_Sets_Computed_Actions a e1.\nProof.\n  intros e1 acts a H. \n  split; inversion H; subst.\n  - econstructor; intros. apply H0; auto. unfold set_elem, set_union. apply Union_introl. assumption.\n  - econstructor. intros. apply H0; auto. unfold set_elem, set_union. apply Union_intror. assumption.\nQed.\n\nLemma Disjoint_da_in_theta :\n  forall e1 e2 p1 p2,\n    Disjoint_Sets_Computed_Actions e1 e2 ->\n    DA_in_Theta p1 (Some e1) ->\n    DA_in_Theta p2 (Some e2) ->\n    Disjoint_Dynamic p1 p2.\nProof.\n  intros e1 e2 p1 p2 H1 H2 H3.\n  generalize dependent p2. \n  dependent induction H2; intros.\n  - generalize dependent e1. \n    dependent induction H3; intros; inversion H1; subst.  \n    + assert (HD : Disjoint_Computed_Actions (CA_AllocAbs s) (CA_AllocAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H5. inversion H5. reflexivity.\n    + assert (HD : Disjoint_Computed_Actions (CA_AllocAbs s) (CA_ReadAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H5; inversion H5; reflexivity.\n    + assert (HD : Disjoint_Computed_Actions (CA_AllocAbs s) (CA_ReadConc s0 l0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor; contradict H5; inversion H5; reflexivity.\n    + assert (HD : Disjoint_Computed_Actions (CA_AllocAbs s) (CA_WriteAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H5. inversion H5. reflexivity.\n    + assert (HD : Disjoint_Computed_Actions (CA_AllocAbs s) (CA_WriteConc s0 l0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H5. inversion H5. reflexivity.\n    + eapply IHDA_in_Theta; eauto.\n      apply Ext_disjoint_sets in H1; destruct H1; assumption.\n    + eapply IHDA_in_Theta; eauto.\n      apply Ext_disjoint_sets in H1; destruct H1; assumption.\n  - generalize dependent e1.  \n    dependent induction H3; intros; inversion H1; subst.\n    + assert (HD : Disjoint_Computed_Actions (CA_ReadAbs s) (CA_AllocAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H5; inversion H5; reflexivity.\n    + assert (HD : Disjoint_Computed_Actions (CA_ReadAbs s) (CA_ReadAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. \n    + assert (HD : Disjoint_Computed_Actions (CA_ReadAbs s) (CA_ReadConc s0 l0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor.\n    + assert (HD : Disjoint_Computed_Actions (CA_ReadAbs s) (CA_WriteAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H5; inversion H5; reflexivity.\n    + assert (HD : Disjoint_Computed_Actions (CA_ReadAbs s) (CA_WriteConc s0 l0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H5; inversion H5; reflexivity.\n    + eapply IHDA_in_Theta; eauto.\n      apply Ext_disjoint_sets in H1; destruct H1; assumption.\n    + eapply IHDA_in_Theta; eauto.\n      apply Ext_disjoint_sets in H1; destruct H1; assumption. \n  - generalize dependent e1.  \n    dependent induction H3; intros; inversion H1; subst.\n    + assert (HD : Disjoint_Computed_Actions (CA_ReadConc s l) (CA_AllocAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H4; inversion H4; reflexivity.\n    + assert (HD : Disjoint_Computed_Actions (CA_ReadConc s l) (CA_ReadAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor.\n    + assert (HD : Disjoint_Computed_Actions (CA_ReadConc s l) (CA_ReadConc s0 l0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor.\n    + assert (HD : Disjoint_Computed_Actions (CA_ReadConc s l) (CA_WriteAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H4; inversion H4; reflexivity.\n    + assert (HD : Disjoint_Computed_Actions (CA_ReadConc s l) (CA_WriteConc s0 l0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H6; inversion H6; reflexivity.\n    + eapply IHDA_in_Theta; eauto.\n      apply Ext_disjoint_sets in H1; destruct H1; assumption.\n    + eapply IHDA_in_Theta; eauto.\n      apply Ext_disjoint_sets in H1; destruct H1; assumption.  \n  - generalize dependent e1.  \n    dependent induction H3; intros; inversion H1; subst.\n    + assert (HD : Disjoint_Computed_Actions (CA_WriteAbs s) (CA_AllocAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H5; inversion H5; reflexivity.\n    + assert (HD : Disjoint_Computed_Actions (CA_WriteAbs s) (CA_ReadAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H5; inversion H5; reflexivity.\n    + assert (HD : Disjoint_Computed_Actions (CA_WriteAbs s) (CA_ReadConc s0 l0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H5; inversion H5; reflexivity.\n    + assert (HD : Disjoint_Computed_Actions (CA_WriteAbs s) (CA_WriteAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H5; inversion H5; reflexivity.\n    + assert (HD : Disjoint_Computed_Actions (CA_WriteAbs s) (CA_WriteConc s0 l0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H5; inversion H5; reflexivity.\n    + eapply IHDA_in_Theta; eauto.\n      apply Ext_disjoint_sets in H1; destruct H1; assumption.\n    + eapply IHDA_in_Theta; eauto.\n      apply Ext_disjoint_sets in H1; destruct H1; assumption.\n  - generalize dependent e1.  \n    dependent induction H3; intros; inversion H1; subst.\n    + assert (HD : Disjoint_Computed_Actions (CA_WriteConc s l) (CA_AllocAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H4; inversion H4; reflexivity.\n    +  assert (HD : Disjoint_Computed_Actions (CA_WriteConc s l) (CA_ReadAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H4; inversion H4; reflexivity. \n    + assert (HD : Disjoint_Computed_Actions (CA_WriteConc s l) (CA_ReadConc s0 l0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H6. inversion H6. reflexivity.\n    + assert (HD : Disjoint_Computed_Actions (CA_WriteConc s l) (CA_WriteAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n    + assert (HD : Disjoint_Computed_Actions (CA_WriteConc s l) (CA_WriteConc s0 l0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H6. inversion H6. reflexivity.\n    + eapply IHDA_in_Theta; eauto.\n      apply Ext_disjoint_sets in H1; destruct H1; assumption.\n    + eapply IHDA_in_Theta; eauto.\n      apply Ext_disjoint_sets in H1; destruct H1; assumption.\n  -  apply Ext_disjoint_sets_2 in H1; destruct H1.\n     eapply IHDA_in_Theta with (e1:=acts); eauto.\n  -  apply Ext_disjoint_sets_2 in H1; destruct H1.\n     eapply IHDA_in_Theta with (e1:=acts); eauto.  \nQed.\n    \nLemma Disjoint_computed_disjoint_dynamic_action:\n  forall e1 e2 phi1 phi2 p1 p2,\n    phi1 ⊑ Some e1 ->\n    phi2 ⊑ Some e2 ->\n    Disjoint_Sets_Computed_Actions e1 e2 -> \n    In p1 (phi_as_list phi1) ->\n    In p2 (phi_as_list phi2) -> \n    Disjoint_Dynamic p1 p2.\nProof.\n  intros e1 e2 phi1 phi2 p1 p2 H1 H2 H3 H4 H5.\n  generalize dependent phi2.\n  dependent induction H1; intros; simpl in *.\n  - contradiction.\n  - destruct H4; subst.\n    + dependent induction H2; simpl in H5.\n      * contradiction.\n      * destruct H5; [subst | contradiction ].\n        eapply Disjoint_da_in_theta; eauto.\n      * apply in_app_or in H5. destruct H5.\n        { eapply  IHPhi_Theta_Soundness1; eauto. }\n        { eapply  IHPhi_Theta_Soundness2; eauto. }\n      * apply in_app_or in H5. destruct H5.\n        { eapply  IHPhi_Theta_Soundness1; eauto. }\n        { eapply  IHPhi_Theta_Soundness2; eauto. }\n    + contradiction.\n  - apply in_app_or in H4. destruct H4.\n    + eapply  IHPhi_Theta_Soundness1; eauto.\n    + eapply  IHPhi_Theta_Soundness2; eauto.\n  - apply in_app_or in H4. destruct H4.\n    + eapply  IHPhi_Theta_Soundness1; eauto.\n    + eapply  IHPhi_Theta_Soundness2; eauto.\nQed.\n\n\nLemma Ext_Conflict_sets_1 :\n  forall e acts a,\n    Conflict_Sets_Computed_Actions e acts \\/ Conflict_Sets_Computed_Actions e a ->\n    Conflict_Sets_Computed_Actions e (set_union acts a).\nProof.\n  intros e acts a H. destruct H.\n  - inversion H; subst.\n    econstructor; eauto. apply Union_introl. assumption.\n  - inversion H; subst.\n    econstructor; eauto. apply Union_intror. assumption. \nQed.\n\nLemma Ext_Conflict_sets_2 :\n  forall e acts a,\n    Conflict_Sets_Computed_Actions acts e \\/ Conflict_Sets_Computed_Actions a e ->\n    Conflict_Sets_Computed_Actions (set_union acts a) e.\nProof.\n  intros e acts a H. destruct H.\n  - inversion H; subst.\n    econstructor; eauto. apply Union_introl. assumption.\n  - inversion H; subst.\n    econstructor; eauto. apply Union_intror. assumption. \nQed.\n\nLemma Conflict_da_in_theta_read :\n  forall r l v e0 e,\n    DA_in_Theta (DA_Write r l v) (Some e0) ->\n    DA_in_Theta (DA_Read r l v) (Some e) ->\n    Conflict_Sets_Computed_Actions e e0. \nProof.\n  intros.\n  generalize dependent e0.\n  dependent induction H0; intros.\n  - dependent induction H0; intros.\n    + econstructor; eauto. constructor.\n    + econstructor; eauto. constructor. \n    + apply Ext_Conflict_sets_1. left. eapply IHDA_in_Theta; eauto.\n    + apply Ext_Conflict_sets_1. right. eapply IHDA_in_Theta; eauto.\n  - dependent induction H0; intros.\n    + econstructor; eauto. constructor.\n    + econstructor; eauto. constructor. \n    + apply Ext_Conflict_sets_1. left. eapply IHDA_in_Theta; eauto.\n    + apply Ext_Conflict_sets_1. right. eapply IHDA_in_Theta; eauto.\n  - apply Ext_Conflict_sets_2.  left. eapply IHDA_in_Theta; eauto.\n  - apply Ext_Conflict_sets_2.  right. eapply IHDA_in_Theta; eauto.\nQed.\n\nLemma Conflict_da_in_theta_write :\n  forall r l v e0 e,\n    DA_in_Theta (DA_Write r l v) (Some e0) ->\n    DA_in_Theta (DA_Write r l v) (Some e) ->\n    Conflict_Sets_Computed_Actions e e0. \nProof.\n  intros.\n  generalize dependent e0.\n  dependent induction H0; intros.\n  - dependent induction H0; intros.\n    + econstructor; eauto. constructor.\n    + econstructor; eauto. constructor. \n    + apply Ext_Conflict_sets_1. left. eapply IHDA_in_Theta; eauto.\n    + apply Ext_Conflict_sets_1. right. eapply IHDA_in_Theta; eauto.\n  - dependent induction H0; intros.\n    + econstructor; eauto. constructor.\n    + econstructor; eauto. constructor. \n    + apply Ext_Conflict_sets_1. left. eapply IHDA_in_Theta; eauto.\n    + apply Ext_Conflict_sets_1. right. eapply IHDA_in_Theta; eauto.\n  - apply Ext_Conflict_sets_2.  left. eapply IHDA_in_Theta; eauto.\n  - apply Ext_Conflict_sets_2.  right. eapply IHDA_in_Theta; eauto.\nQed.\n\nLemma Conflict_computed_conflict_dynamic_action_write:\n  forall phi1 phi2 e e0 r l v,\n  phi1 ⊑ Some e ->\n  phi2 ⊑ Some e0 ->\n  In (DA_Write r l v) (phi_as_list phi1) ->\n  In (DA_Write r l v) (phi_as_list phi2) ->\n  Conflict_Sets_Computed_Actions e e0.\nProof.\n  intros. generalize dependent phi2.\n  dependent induction phi1; simpl in *.\n  - contradiction.\n  - intuition; subst.\n    dependent induction H1; simpl in *.\n    + contradiction.\n    + intuition; subst. inversion H0; subst.\n      eapply Conflict_da_in_theta_write; eauto.\n    + apply in_app_or in H2. destruct H2; [eapply IHPhi_Theta_Soundness1 | eapply IHPhi_Theta_Soundness2] ; eauto.\n    + apply in_app_or in H2. destruct H2; [eapply IHPhi_Theta_Soundness1 | eapply IHPhi_Theta_Soundness2] ; eauto.   \n  - inversion H; apply in_app_or in H1. destruct H1; [eapply IHphi1_1 | eapply IHphi1_2] ; eauto.\n  - inversion H; apply in_app_or in H1. destruct H1; [eapply IHphi1_1 | eapply IHphi1_2] ; eauto.\nQed.\n\nLemma Conflict_computed_conflict_dynamic_action_read:\n  forall phi1 phi2 e e0 r l v,\n  phi1 ⊑ Some e ->\n  phi2 ⊑ Some e0 ->\n  In (DA_Write r l v) (phi_as_list phi2) ->\n  In (DA_Read r l v) (phi_as_list phi1) ->\n  Conflict_Sets_Computed_Actions e e0.\nProof.\n  intros. generalize dependent phi2.\n  dependent induction phi1; simpl in *.\n  - contradiction.\n  - intuition; subst.\n    dependent induction H1; simpl in *.\n    + contradiction.\n    + intuition; subst. inversion H0; subst.\n      eapply Conflict_da_in_theta_read; eauto.\n    + apply in_app_or in H2. destruct H2; [eapply IHPhi_Theta_Soundness1 | eapply IHPhi_Theta_Soundness2] ; eauto.\n    + apply in_app_or in H2. destruct H2; [eapply IHPhi_Theta_Soundness1 | eapply IHPhi_Theta_Soundness2] ; eauto.   \n  - inversion H; apply in_app_or in H2. destruct H2; [eapply IHphi1_1 | eapply IHphi1_2] ; eauto.\n  - inversion H; apply in_app_or in H2. destruct H2; [eapply IHphi1_1 | eapply IHphi1_2] ; eauto.\nQed.\n\nLemma Det_trace_from_readonly :\n  forall phi,\n    ReadOnlyPhi phi ->\n    Det_Trace phi.\nProof.\n  intros phi H.\n  dependent induction H.\n  - constructor.\n  - constructor.\n  - constructor; auto.\n  - constructor; auto. split. \n    + generalize dependent phi2.\n      dependent induction IHReadOnlyPhi1; intros.\n      * intro. inversion H1. inversion H2.\n      * { dependent induction IHReadOnlyPhi2.\n          - intro. inversion H1. inversion H3.\n          - inversion H; inversion H0; subst.\n            intro. simpl in H1. inversion H1; subst.\n            inversion H2; subst; [ | inversion H5].  inversion H3; subst; [ | inversion H5].\n            inversion H4.\n          - simpl in *. replace (da :: nil) with (phi_as_list (Phi_Elem da))  by (simpl; reflexivity).\n            inversion H0; subst.\n            apply Conflictness_and_app_l. split; [apply IHIHReadOnlyPhi2_1 | apply IHIHReadOnlyPhi2_2]; assumption.\n          - simpl in *. replace (da :: nil) with (phi_as_list (Phi_Elem da))  by (simpl; reflexivity).\n            inversion H0; subst.\n            apply Conflictness_and_app_l. split; [apply IHIHReadOnlyPhi2_1 | apply IHIHReadOnlyPhi2_2]; assumption. }\n      * inversion H; subst.\n        apply Conflictness_and_app_r. split; [apply IHIHReadOnlyPhi1_1 | apply IHIHReadOnlyPhi1_2]; assumption.\n      * inversion H; subst.\n        apply Conflictness_and_app_r. split; [apply IHIHReadOnlyPhi1_1 | apply IHIHReadOnlyPhi1_2]; assumption.\n    + generalize dependent phi2.\n      dependent induction IHReadOnlyPhi1; intros.\n      * constructor. intros. inversion H1.\n      * { dependent induction IHReadOnlyPhi2.\n          - constructor. intros. inversion H2.\n          - inversion H; inversion H0; subst.\n            constructor. intros. simpl in *. intuition; subst.\n            constructor.\n          - simpl.  replace (da :: nil) with (phi_as_list (Phi_Elem da))  by (simpl; reflexivity).\n            inversion H0; subst.\n            apply Disjointness_and_app_l.  split; [apply IHIHReadOnlyPhi2_1 | apply IHIHReadOnlyPhi2_2]; assumption.\n          - simpl.  replace (da :: nil) with (phi_as_list (Phi_Elem da))  by (simpl; reflexivity).\n            inversion H0; subst.\n            apply Disjointness_and_app_l.  split; [apply IHIHReadOnlyPhi2_1 | apply IHIHReadOnlyPhi2_2]; assumption. }\n      * inversion H; subst.\n        apply Disjointness_and_app_r. split; [apply IHIHReadOnlyPhi1_1 | apply IHIHReadOnlyPhi1_2]; assumption.\n      * inversion H; subst.\n        apply Disjointness_and_app_r. split; [apply IHIHReadOnlyPhi1_1 | apply IHIHReadOnlyPhi1_2]; assumption.  \nQed.\n\nLemma Read_only_no_conflicts:\n  forall phi1 phi2,\n    ReadOnlyPhi phi1 ->\n    ReadOnlyPhi phi2 ->\n   ~ Conflict_Traces (phi_as_list phi1) (phi_as_list phi2).\nProof.\n  intros phi1 phi2 H1 H2.\n  generalize dependent phi2.\n  dependent induction phi1; intros.\n  - intro. dependent destruction H. inversion H.\n  - generalize dependent d.\n    dependent induction H2; intros.\n    + intro. inversion H. inversion H2.\n    + intro. inversion H1; subst. simpl in H.\n      inversion H; subst.\n      inversion H0; subst; [ | inversion H4].\n      inversion H2; subst; [ | inversion H4].\n      inversion H3.\n    + simpl. replace (d :: nil) with (phi_as_list (Phi_Elem d)) by (simpl; reflexivity).\n      apply Conflictness_and_app_l. split; [apply IHReadOnlyPhi1 | apply IHReadOnlyPhi2]; assumption.\n    + simpl. replace (d :: nil) with (phi_as_list (Phi_Elem d)) by (simpl; reflexivity).\n      apply Conflictness_and_app_l. split; [apply IHReadOnlyPhi1 | apply IHReadOnlyPhi2]; assumption.\n  - simpl. apply Conflictness_and_app_r.\n    inversion H1; subst.\n    split; [apply IHphi1_1 | apply IHphi1_2]; assumption.  \n  - simpl. apply Conflictness_and_app_r.\n    inversion H1; subst.\n    split; [apply IHphi1_1 | apply IHphi1_2]; assumption.\nQed.\n\nLemma Read_only_disjointness:\n  forall phi1 phi2,\n    ReadOnlyPhi phi1 ->\n    ReadOnlyPhi phi2 ->\n    Disjoint_Traces (phi_as_list phi1) (phi_as_list phi2).\nProof.\n  intros phi1 phi2 H. generalize phi2.\n  dependent induction H; intros.\n  - constructor. intros. inversion H0.\n  - constructor. dependent induction H; intros; simpl in *.\n    + inversion H0.\n    + intuition; subst. constructor.\n    + intuition; subst. apply in_app_or in H2. destruct H2; [apply IHReadOnlyPhi1 | apply IHReadOnlyPhi2]; intuition.\n    + intuition; subst. apply in_app_or in H2. destruct H2; [apply IHReadOnlyPhi1 | apply IHReadOnlyPhi2]; intuition.\n  - simpl. apply Disjointness_and_app_r. split; auto.\n  - simpl. apply Disjointness_and_app_r. split; auto.\nQed.    \n  \nLemma Det_par_trace_from_readonly :\n  forall phi1 phi2,\n    ReadOnlyPhi phi1 ->\n    ReadOnlyPhi phi2 ->\n    Det_Trace (Phi_Par phi1 phi2).\nProof.\n  intros phi1 phi2 H1 H2.\n  generalize dependent phi2.\n  dependent induction H1; intros; constructor.\n  - constructor.\n  - dependent induction phi2.\n    + constructor.\n    + constructor; assumption.\n    + inversion H2; constructor; [apply IHphi2_1 | apply IHphi2_2 |]; try assumption.\n      split; [apply Read_only_no_conflicts | apply Read_only_disjointness]; assumption.\n    + inversion H2; constructor; [apply IHphi2_1 | apply IHphi2_2 ]; assumption.\n  - split; simpl.\n    + intro. inversion H; subst. inversion H0.\n    + econstructor; intros. inversion H.\n  - constructor.\n  - dependent induction H2; try (solve [constructor; auto]).\n    constructor; auto.\n    split; [apply Read_only_no_conflicts | apply Read_only_disjointness]; assumption.\n  - split; simpl.\n    + dependent induction H2.\n      * intro. inversion H. inversion H1.\n      * intro. simpl in H. inversion H; subst.\n        { inversion H2; subst.\n          - inversion H1; inversion H3.\n          - inversion H1; inversion H3. }\n      * simpl. replace (DA_Read r a v :: nil) with (phi_as_list (Phi_Elem (DA_Read r a v))) by (simpl; reflexivity).\n        apply Conflictness_and_app_l. split; auto.\n      * simpl. replace (DA_Read r a v :: nil) with (phi_as_list (Phi_Elem (DA_Read r a v))) by (simpl; reflexivity).\n        apply Conflictness_and_app_l. split; auto.\n    + dependent induction H2; simpl.\n      * constructor; intros. inversion H0.\n      * econstructor; intros.\n        inversion H; subst; [| inversion H1]. inversion H0; subst; [| inversion H1]. constructor.\n      * simpl. replace (DA_Read r a v :: nil) with (phi_as_list (Phi_Elem (DA_Read r a v))) by (simpl; reflexivity).\n        apply Disjointness_and_app_l.  split; auto.\n      * simpl. replace (DA_Read r a v :: nil) with (phi_as_list (Phi_Elem (DA_Read r a v))) by (simpl; reflexivity).\n        apply Disjointness_and_app_l.  split; auto.\n  - constructor; apply Det_trace_from_readonly; auto.\n  - apply Det_trace_from_readonly; auto.\n  - split; simpl.\n    + dependent induction H2.\n      * intro. inversion H. inversion H1.\n      * intro. simpl in H. inversion H; subst.\n        { inversion H2; subst.\n          - inversion H1; inversion H3.\n          - inversion H1; inversion H3. }\n      * replace (phi_as_list phi1 ++ phi_as_list phi2) with (phi_as_list (Phi_Seq phi1 phi2)) by (simpl; reflexivity).\n        apply Conflictness_and_app_l. split; auto.\n      * replace (phi_as_list phi1 ++ phi_as_list phi2) with (phi_as_list (Phi_Seq phi1 phi2)) by (simpl; reflexivity).\n        apply Conflictness_and_app_l. split; auto.\n    + dependent induction H2; simpl.\n      * constructor; intros. inversion H0.\n      * replace (DA_Read r a v :: nil) with (phi_as_list (Phi_Elem (DA_Read r a v))) by (simpl; reflexivity). \n        assert (ReadOnlyPhi (Phi_Elem (DA_Read r a v))) by constructor.\n        apply IHReadOnlyPhi1 in H. inversion H; subst.\n        destruct H4; apply  Disjointness_and_app_r. split; [ auto | ].\n        assert (ReadOnlyPhi (Phi_Elem (DA_Read r a v))) by constructor.\n        apply IHReadOnlyPhi2 in H4. inversion H4; subst.\n        destruct H9. auto.\n      * replace (phi_as_list phi1 ++ phi_as_list phi2) with (phi_as_list (Phi_Seq phi1 phi2)) by (simpl; reflexivity).\n        apply Disjointness_and_app_l.  split; auto.\n      * replace (phi_as_list phi1 ++ phi_as_list phi2) with (phi_as_list (Phi_Seq phi1 phi2)) by (simpl; reflexivity).\n        apply Disjointness_and_app_l.  split; auto.\n  - apply IHReadOnlyPhi1 in H1_0. assumption.\n  - apply Det_trace_from_readonly; auto.\n  - split; simpl. \n    + dependent induction H2.\n      * intro. inversion H. inversion H1.\n      * intro. simpl in H. inversion H; subst.\n        { inversion H2; subst.\n          - inversion H1; inversion H3.\n          - inversion H1; inversion H3. }\n      * replace (phi_as_list phi1 ++ phi_as_list phi2) with (phi_as_list (Phi_Par phi1 phi2)) by (simpl; reflexivity).\n        apply Conflictness_and_app_l. split; auto.\n      * replace (phi_as_list phi1 ++ phi_as_list phi2) with (phi_as_list (Phi_Par phi1 phi2)) by (simpl; reflexivity).\n        apply Conflictness_and_app_l. split; auto.\n     + dependent induction H2; simpl.\n      * constructor; intros. inversion H0.\n      * replace (DA_Read r a v :: nil) with (phi_as_list (Phi_Elem (DA_Read r a v))) by (simpl; reflexivity).\n        assert (ReadOnlyPhi (Phi_Elem (DA_Read r a v))) by constructor.\n        apply IHReadOnlyPhi1 in H. inversion H; subst. destruct H4.\n        apply Disjointness_and_app_r. split; [auto |].\n        assert (ReadOnlyPhi (Phi_Elem (DA_Read r a v))) by constructor.\n        apply IHReadOnlyPhi2 in H4. inversion H4; subst. destruct H9.\n        assumption.        \n      * replace (phi_as_list phi1 ++ phi_as_list phi2) with (phi_as_list (Phi_Par phi1 phi2)) by (simpl; reflexivity).\n        apply Disjointness_and_app_l.  split; auto.\n      * replace (phi_as_list phi1 ++ phi_as_list phi2) with (phi_as_list (Phi_Par phi1 phi2)) by (simpl; reflexivity).\n        apply Disjointness_and_app_l.  split; auto.\nQed.\n     \n\nLemma Det_trace_from_theta :\n  forall theta1 theta2 phi1 phi2,\n    phi1 ⊑ theta1 ->\n    phi2 ⊑ theta2 ->\n    Disjointness theta1 theta2 /\\ not (Conflictness theta1 theta2) -> \n    Det_Trace phi1 ->\n    Det_Trace phi2 ->\n    Det_Trace (Phi_Par phi1 phi2).\nProof.\n  intros theta1 theta2 phi1 phi2 H1 H2 [HDisj HConf] HDet1 HDet2.\n  constructor; [assumption | assumption | split].\n  - intro. dependent induction H. inversion H3; subst. apply HConf.\n    + destruct theta1; destruct theta2; constructor.\n      eapply Conflict_computed_conflict_dynamic_action_read; eauto. \n    + destruct theta1 ; [ | apply HConf; constructor ].\n      destruct theta2 ; [ | apply HConf; constructor ].    \n      apply HConf. constructor. eapply Conflict_computed_conflict_dynamic_action_write; eauto.\n  - destruct theta1; [ | dependent destruction HDisj].\n    destruct theta2; [ | dependent destruction HDisj]. \n    dependent destruction HDisj. constructor; intros.\n    eapply Disjoint_computed_disjoint_dynamic_action with (e1:=e) (e2:=e0); eauto.\nQed.\n\nLemma unique_heap :\n  forall (heap heap1 heap2: Heap) (acts_mu1 acts_mu2: Phi) (theta1 theta2 : Theta),\n    acts_mu1 ⊑ theta1 ->\n    acts_mu2 ⊑ theta2 ->\n    Disjointness theta1 theta2 /\\ not (Conflictness theta1 theta2) ->\n    Det_Trace acts_mu1 ->\n    Det_Trace acts_mu2 ->\n    (Phi_Par acts_mu1 acts_mu2, heap) ==>* (Phi_Nil, heap2) ->\n    (Phi_Par acts_mu1 acts_mu2, heap) ==>* (Phi_Nil, heap1) ->\n    H.Equal heap1 heap2.\nProof.\n  intros.\n  eapply Diamond_Term_Walk; eauto.\n  eapply Det_trace_from_theta; eauto.\nQed.\n\nLemma unique_heap_new :\n  forall (heapa heapb heap1 heap2: Heap) (acts_mu1 acts_mu2: Phi) (theta1 theta2 : Theta),\n    acts_mu1 ⊑ theta1 ->\n    acts_mu2 ⊑ theta2 ->\n    Disjointness theta1 theta2 /\\ not (Conflictness theta1 theta2) ->\n    Det_Trace acts_mu1 ->\n    Det_Trace acts_mu2 ->\n    H.Equal heapa heapb ->\n    (Phi_Par acts_mu1 acts_mu2, heapa) ==>* (Phi_Nil, heap1) ->\n    (Phi_Par acts_mu1 acts_mu2, heapb) ==>* (Phi_Nil, heap2) ->\n    H.Equal heap1 heap2.\nProof.\n  intros.\n  eapply Diamond_Term_Walk_new; eauto.\n  eapply Det_trace_from_theta; eauto.\nQed.\n\n", "meta": {"author": "esmifro", "repo": "SurfaceEffects", "sha": "3450e4b771de4062ab73ee20947adf3f9de579ba", "save_path": "github-repos/coq/esmifro-SurfaceEffects", "path": "github-repos/coq/esmifro-SurfaceEffects/SurfaceEffects-3450e4b771de4062ab73ee20947adf3f9de579ba/Determinism.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2770372241015033}}
{"text": "\nRequire Import FiatFormal.Language.Preservation.\nRequire Export FiatFormal.Language.Step.\nRequire Export FiatFormal.Language.SubstExpExp.\nRequire Export FiatFormal.Language.SubstTypeExp.\nRequire Import FiatFormal.Language.TyJudge.\nRequire Export FiatFormal.Language.Exp.\n\n\n(********************************************************************)\n(* Big Step Evaluation\n   This is also called 'Natural Semantics'.\n   It provides a relation between the expression to be reduced\n   and its final value.\n *)\nInductive EVAL : exp -> exp -> Prop :=\n | EVDone\n   :  forall v2\n   ,  wnfX v2\n   -> EVAL v2 v2.\n\nHint Constructors EVAL.\n\n\n(* A terminating big-step evaluation always produces a wnf.\n   The fact that the evaluation terminated is implied by the fact\n   that we have a finite proof of EVAL to pass to this lemma.\n *)\nLemma eval_produces_wnfX\n :  forall x1 v1\n ,  EVAL   x1 v1\n -> wnfX  v1.\nProof.\n intros. induction H; eauto.\nQed.\nHint Resolve eval_produces_wnfX.\n\n\n(********************************************************************)\n(* Convert a big-step evaluation into a list of small steps. *)\n(* Lemma steps_of_eval *)\n(*  :  forall x1 t1 x2 *)\n(*  ,  TYPE nil nil x1 t1 *)\n(*  -> EVAL  x1 x2 *)\n(*  -> STEPS x1 x2. *)\n(* Proof. *)\n(*  intros x1 t1 v2 HT HE. gen t1. *)\n\n(*  (* Induction over the form of (EVAL x1 x2) *) *)\n(*  induction HE. *)\n(*  Case \"EVDone\". *)\n(*   intros. apply ESNone. *)\n\n(*  (* Case \"EVLAMAPP\". *) *)\n(*  (*  intros. inverts HT. *) *)\n(*  (*  lets E1: IHHE1 H3. clear IHHE1. *) *)\n(*  (*  lets T1: preservation_steps H3 E1. inverts keep T1. *) *)\n(*  (*  lets T2: subst_type_value H4 H5. *) *)\n(*  (*   simpl in T2. *) *)\n(*  (*  lets E2: IHHE2 T2. *) *)\n(*  (*  eapply ESAppend. *) *)\n(*  (*   apply steps_APP1. eauto. *) *)\n(*  (*  eapply ESAppend. *) *)\n(*  (*   eapply ESStep. *) *)\n(*  (*    eapply ESLAMAPP. auto. *) *)\n\n(*  Case \"EVLamApp\". *)\n(*   intros. inverts HT. *)\n(*   lets E1: IHHE1 H3. *)\n(*   lets E2: IHHE2 H5. *)\n(*   lets T1: preservation_steps H3 E1. inverts keep T1. *)\n(*   lets T2: preservation_steps H5 E2. *)\n(*   lets T3: subst_value_value H8 T2. *)\n(*   lets E3: IHHE3 T3. *)\n(*   eapply ESAppend. *)\n(*     eapply steps_app1. eauto. *)\n(*    eapply ESAppend. *)\n(*     eapply steps_app2. eauto. eauto. *)\n(*    eapply ESAppend. *)\n(*     eapply ESStep. *)\n(*      eapply ESLamApp. eauto. *)\n(*    eauto. *)\n(* Qed. *)\n\n\n(* (********************************************************************) *)\n(* (* Convert a list of small steps to a big-step evaluation. The main *)\n(*    part of this is the expansion lemma, which we use to build up the *)\n(*    overall big-step evaluation one small-step at a time. The other *)\n(*   lemmas are used to feed it small-steps. *)\n(*  *) *)\n\n(* (* Given an existing big-step evalution, we can produce a new one *)\n(*    that does an extra step before returning the original value. *)\n(*  *) *)\n(* Lemma eval_expansion *)\n(*  :  forall ke te x1 t1 x2 v3 *)\n(*  ,  TYPE ke te x1 t1 *)\n(*  -> STEP x1 x2 -> EVAL x2 v3 *)\n(*  -> EVAL x1 v3. *)\n(* Proof. *)\n(*  intros. gen ke te t1 v3. *)\n\n(*  (* Induction over the form of (STEP x1 x2) *) *)\n(*  induction H0; intros. *)\n\n(*  Case \"XApp\". *)\n(*   SCase \"value app\". *)\n(*    eapply EVLamApp. *)\n(*    eauto. *)\n(*    inverts H. *)\n(*    apply EVDone. auto. auto. *)\n\n(*   SCase \"x1 steps\". *)\n(*    inverts H. inverts H1. *)\n(*     inverts H. *)\n(*     eapply EVLamApp; eauto. *)\n\n(*   SCase \"x2 steps\". *)\n(*    inverts H1. inverts H2. *)\n(*    inverts H1. *)\n(*    eapply EVLamApp; eauto. *)\n\n(*  (* Case \"XAPP\". *) *)\n(*  (*  SCase \"type app\". *) *)\n(*  (*   eapply EVLAMAPP. *) *)\n(*  (*   eauto. *) *)\n(*  (*   inverts H. *) *)\n(*  (*   auto. *) *)\n\n(*  (*  SCase \"x1 steps\". *) *)\n(*  (*   inverts H. inverts H1. *) *)\n(*  (*    inverts H. *) *)\n(*  (*    eapply EVLAMAPP; eauto. *) *)\n(* Qed. *)\n\n\n(* (* Convert a list of small steps to a big-step evaluation. *) *)\n(* Lemma eval_of_stepsl *)\n(*  :  forall x1 t1 v2 *)\n(*  ,  TYPE nil nil x1 t1 *)\n(*  -> STEPSL x1 v2 -> value v2 *)\n(*  -> EVAL   x1 v2. *)\n(* Proof. *)\n(*  intros. *)\n(*  induction H0. *)\n\n(*  Case \"ESLNone\". *)\n(*    apply EVDone. inverts H1. auto. *)\n\n(*  Case \"ESLCons\". *)\n(*   eapply eval_expansion. *)\n(*    eauto. eauto. *)\n(*    apply IHSTEPSL. *)\n(*    eapply preservation. eauto. auto. auto. *)\n(* Qed. *)\n\n\n(* (* Convert a multi-step evaluation to a big-step evaluation. *)\n(*    We use stepsl_of_steps to flatten out the append constructors *)\n(*    in the multi-step evaluation, leaving a list of individual *)\n(*    small-steps. *)\n(*  *) *)\n(* Lemma eval_of_steps *)\n(*  :  forall x1 t1 v2 *)\n(*  ,  TYPE nil nil x1 t1 *)\n(*  -> STEPS x1 v2 -> value v2 *)\n(*  -> EVAL  x1 v2. *)\n(* Proof. *)\n(*  intros. *)\n(*  eapply eval_of_stepsl; eauto. *)\n(*  apply  stepsl_of_steps; auto. *)\n(* Qed. *)\n", "meta": {"author": "paulkrog", "repo": "formalized-fiat", "sha": "8f9022980c038f500aeea9b2f85062f0bfc33eb6", "save_path": "github-repos/coq/paulkrog-formalized-fiat", "path": "github-repos/coq/paulkrog-formalized-fiat/formalized-fiat-8f9022980c038f500aeea9b2f85062f0bfc33eb6/FiatFormal/Language/Eval.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.27703721718768454}}
{"text": "Require Export Coq.Program.Equality.\nRequire Export Coq.Program.Tactics.\nRequire Export DeclarationEvaluation.\nRequire Export DeclarationTyping.\n\n(******************************************************************************)\n(* Weakening lemmas                                                           *)\n(******************************************************************************)\n\nLemma PTyping_domainEnv_subhvl_tm {Γ p T Δ} :\n  PTyping Γ p T Δ → subhvl_tm (domainEnv Δ).\nProof.\n  induction 1; isimpl; eauto with infra.\nQed.\nHint Resolve PTyping_domainEnv_subhvl_tm : infra shift subst wf.\n\nLemma PTyping_bindPat_domainEnv {Γ p T Δ} :\n  PTyping Γ p T Δ → bindPat p = domainEnv Δ.\nProof.\n  induction 1; isimpl; try congruence; eauto.\nQed.\n\nLemma shift_etvar_ptyping {Γ1 p T Δ} (wt: PTyping Γ1 p T Δ) :\n  ∀ {c Γ2}, shift_etvar c Γ1 Γ2 →\n    PTyping Γ2 (tshiftPat c p) (tshiftTy c T) (tshiftEnv c Δ).\nProof.\n  induction wt; isimpl; econstructor; isimpl;\n    autorewrite with weaken_shift; eauto with shift.\nQed.\n\nLemma shift_etvar_typing {Γ1 t T} (wt: Typing Γ1 t T) :\n  ∀ {c Γ2}, shift_etvar c Γ1 Γ2 → Typing Γ2 (tshiftTm c t) (tshiftTy c T).\nProof.\n  induction wt; isimpl; econstructor;\n    eauto using shift_etvar_ptyping with shift.\n  - rewrite (PTyping_bindPat_domainEnv H); isimpl;\n    autorewrite  with weaken_shift; eauto with shift.\nQed.\n\nLemma shift_evar_ptyping {Γ1 p T Δ} (wp: PTyping Γ1 p T Δ) :\n  ∀ {c Γ2}, shift_evar c Γ1 Γ2 → PTyping Γ2 p T Δ.\nProof.\n  induction wp; simpl; econstructor; eauto with infra.\nQed.\n\nLemma shift_evar_typing {Γ1 t T} (wt: Typing Γ1 t T) :\n  ∀ {c Γ2}, shift_evar c Γ1 Γ2 → Typing Γ2 (shiftTm c t) T.\nProof.\n  induction wt; simpl; econstructor; eauto using shift_evar_ptyping with shift.\n  - rewrite (PTyping_bindPat_domainEnv H); isimpl; eauto with shift.\nQed.\n\nLemma weaken_typing {Γ} Δ : ∀ {t T}, Typing Γ t T →\n  Typing (appendEnv Γ Δ) (weakenTm t (domainEnv Δ)) (weakenTy T (domainEnv Δ)).\nProof.\n  induction Δ; simpl;\n    eauto using shift_evar_typing, shift_etvar_typing with shift.\nQed.\n\nLemma shift_value {t} :\n  ∀ {c}, Value t → Value (shiftTm c t).\nProof.\n  induction t; simpl; intros; try contradiction; destruct_conjs; auto.\nQed.\n\nLemma tshift_value {t} :\n  ∀ {c}, Value t → Value (tshiftTm c t).\nProof.\n  induction t; simpl; intros; try contradiction; destruct_conjs; auto.\nQed.\n\nLemma weaken_value u :\n  ∀ {t}, Value t → Value (weakenTm t u).\nProof.\n  induction u as [|[]]; simpl; auto using shift_value, tshift_value.\nQed.\n\n(******************************************************************************)\n(* Well-formedness                                                            *)\n(******************************************************************************)\n\nLemma typing_wf {Γ t T} (wt: Typing Γ t T) : wfTy (domainEnv Γ) T.\nProof.\n  induction wt; isimpl; eauto with infra.\nQed.\n\n(******************************************************************************)\n(* Substitution lemmas                                                        *)\n(******************************************************************************)\n\nLemma subst_etvar_ptyping {Γ S Γ1 p T Δ}\n  (wfS: wfTy (domainEnv Γ) S) (wt: PTyping Γ1 p T Δ) :\n  ∀ {X Γ2}, subst_etvar Γ S X Γ1 Γ2 →\n     PTyping Γ2 (tsubstPat X S p) (tsubstTy X S T) (tsubstEnv X S Δ).\nProof.\n  induction wt; simpl; intros; isimpl; econstructor; eauto with subst.\n  - rewrite weakenPat_tsubstPat, weakenTy_tsubstTy; isimpl; eauto with subst.\nQed.\n\nLemma subst_etvar_typing {Γ S Γ1 t T} (wS: wfTy (domainEnv Γ) S)\n  (wt: Typing Γ1 t T) :\n  ∀ {X Γ2}, subst_etvar Γ S X Γ1 Γ2 →\n     Typing Γ2 (tsubstTm X S t) (tsubstTy X S T).\nProof.\n  induction wt; simpl; intros;\n    try (isimpl; econstructor; eauto with infra; fail).\n  - simpl; eapply T_Abs; eauto with infra.\n    (* Urgs, ugly. *)\n    replace (tsubstTy X S T2) with (tsubstTy (XS tm X) S T2)\n      by apply tsubstTy_tm; eauto with infra.\n  - eapply T_Let; eauto using subst_etvar_ptyping with infra.\n    rewrite (PTyping_bindPat_domainEnv H); isimpl;\n      autorewrite with weaken_subst; eauto with subst.\nQed.\n\nLemma subst_evar_ptyping {Γ s S} (wts: Typing Γ s S)\n  {Γ1 p T Δ} (wtp: PTyping Γ1 p T Δ) :\n  ∀ {x Γ2}, subst_evar Γ S s x Γ1 Γ2 → PTyping Γ2 p T Δ.\nProof.\n  induction wtp; simpl; econstructor; eauto with subst.\nQed.\n\nLemma subst_evar_lookup_evar {Γ s S x Γ1 Γ2} (ws: Typing Γ s S)\n  (esub: subst_evar Γ S s x Γ1 Γ2) :\n  ∀ {y T}, lookup_evar Γ1 y T → Typing Γ2 (substIndex x s y) T.\nProof.\n  induction esub; inversion 1; subst; simpl;\n    eauto using T_Var, shift_evar_typing, shift_etvar_typing with subst.\nQed.\n\nLemma subst_evar_typing {Γ s S Γ1 t T} (ws: Typing Γ s S) (wt: Typing Γ1 t T) :\n  ∀ {x Γ2}, subst_evar Γ S s x Γ1 Γ2 → Typing Γ2 (substTm x s t) T.\nProof.\n  induction wt; simpl; eauto using subst_evar_lookup_evar;\n    econstructor; eauto using subst_evar_ptyping with subst.\n  - rewrite (PTyping_bindPat_domainEnv H); eauto with subst.\nQed.\n\n(******************************************************************************)\n(* Progress                                                                   *)\n(******************************************************************************)\n\nLemma can_form_tarr {Γ t T1 T2} (v: Value t) (wt: Typing Γ t (tarr T1 T2)) :\n  ∃ t2, t = abs T1 t2.\nProof.\n  depind wt; try contradiction; exists t; reflexivity.\nQed.\n\nLemma can_form_tall {Γ t T} (v: Value t) (wt: Typing Γ t (tall T)) :\n  ∃ t1, t = tabs t1.\nProof.\n  depind wt; try contradiction; exists t; reflexivity.\nQed.\n\nLemma can_form_tprod {Γ t T1 T2} (v: Value t) (wt: Typing Γ t (tprod T1 T2)) :\n  ∃ t1 t2, t = prod t1 t2 ∧ Typing Γ t1 T1 ∧ Typing Γ t2 T2.\nProof.\n  depind wt; try contradiction; exists t1, t2; auto.\nQed.\n\nLemma matching_defined {Γ p T1 Δ} (wp: PTyping Γ p T1 Δ) :\n  ∀ {t1}, Value t1 → Typing Γ t1 T1 → ∀ t2, ∃ t2', Match p t1 t2 t2'.\nProof.\n  induction wp; intros t1 v1 wt1 t2.\n  - exists (substTm X0 t1 t2).\n    refine M_Var.\n  - destruct (can_form_tprod v1 wt1) as (t11 & t12 & eq & wt11 & wt12); subst.\n    destruct v1 as [v11 v12].\n    apply (weaken_typing Δ1) in wt12.\n    assert (val12' : Value (weakenTm t12 (domainEnv Δ1)))\n       by (apply weaken_value; auto).\n    destruct (IHwp2 (weakenTm t12 (domainEnv Δ1)) val12' wt12 t2) as [t2' m2].\n    destruct (IHwp1 _ v11 wt11 t2') as [t2'' m1].\n    rewrite <- (PTyping_bindPat_domainEnv wp1) in m2.\n    exists t2''.\n    exact (M_Prod m2 m1).\nQed.\n\nLemma progress {t U} (wt: Typing empty t U) :\n  Value t ∨ ∃ t', red t t'.\nProof with destruct_conjs; subst; eauto using red.\n  depind wt; simpl; auto.\n  - inversion H.\n  - destruct IHwt1 as [v1|[t1' r1]]...\n    destruct IHwt2 as [v2|[t2' r2]]...\n    destruct (can_form_tarr v1 wt1)...\n  - destruct IHwt as [vt|[t1' r1]]...\n    destruct (can_form_tall vt wt)...\n  - destruct IHwt1 as [v1|[t1' r1]]...\n    destruct IHwt2 as [v2|[t2' r2]]...\n  - destruct IHwt1 as [v1|[t1' r1]]...\n    destruct (matching_defined H v1 wt1 t2)...\nQed.\n\n(******************************************************************************)\n(* Preservation                                                               *)\n(******************************************************************************)\n\nLemma local_preservation_lett {p t1 t2 t2'} (m: Match p t1 t2 t2') :\n  ∀ {Γ T1 T2 Δ}, PTyping Γ p T1 Δ → Typing Γ t1 T1 →\n    Typing (appendEnv Γ Δ) t2 (weakenTy T2 (domainEnv Δ)) →\n    Typing Γ t2' T2.\nProof.\n  induction m; intros Γ T1 T2 Δ wp wt1 wt2.\n  - dependent destruction wp; simpl in *.\n    eauto using subst_evar_typing with infra.\n  - dependent destruction wp.\n    dependent destruction wt1.\n    rewrite (PTyping_bindPat_domainEnv wp1) in *.\n    rewrite appendEnv_assoc, domainEnv_appendEnv, <- weakenTy_append in wt2.\n    eauto using weaken_typing.\nQed.\n\nLemma preservation {Γ t U} (wt: Typing Γ t U) :\n  ∀ {t'}, red t t' → Typing Γ t' U.\nProof.\n  induction wt; intros t' r; inversion r; subst; eauto using Typing.\n  - dependent destruction wt1; eauto using subst_evar_typing with subst.\n  - dependent destruction wt; eauto using subst_etvar_typing with subst.\n  - eauto using local_preservation_lett.\nQed.\n", "meta": {"author": "skeuchel", "repo": "metatheory", "sha": "d0df292cbd764f8afeba088e1c9459f0a4298b47", "save_path": "github-repos/coq/skeuchel-metatheory", "path": "github-repos/coq/skeuchel-metatheory/metatheory-d0df292cbd764f8afeba088e1c9459f0a4298b47/fprod/MetaTheory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.27703721718768454}}
{"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 handle_id_sysreg_trap_spec0 (rec: Pointer) (esr: Z64) (adt: RData) : option RData :=\n    match rec, esr with\n    | (_rec_base, _rec_ofst), VZ64 _esr =>\n      rely is_int64 (Z.land _esr 4193310);\n      rely is_int (Z.land _esr 4193310);\n      let _idreg := (Z.land _esr 4193310) in\n      let _mask := 0 in\n      rely is_int64 _esr;\n      when _t'1 == ESR_EL2_SYSREG_IS_WRITE_spec (VZ64 _esr) adt;\n      rely is_int _t'1;\n      rely is_int (1 - _t'1);\n      when adt == assert_cond_spec (1 - _t'1) adt;\n      if (_idreg =? 3276812) then\n        let _mask := 255 in\n        when _t'2 == ESR_EL2_SYSREG_ISS_RT_spec (VZ64 _esr) adt;\n        rely is_int _t'2;\n        rely is_int _idreg;\n        when' _t'3 == read_idreg_spec _idreg adt;\n        rely is_int64 _t'3;\n        rely is_int64 (18446744073709551615 - _mask);\n        rely is_int64 (Z.land _t'3 (18446744073709551615 - _mask));\n        when adt == set_rec_regs_spec (_rec_base, _rec_ofst) _t'2 (VZ64 (Z.land _t'3 (18446744073709551615 - _mask))) adt;\n        Some adt\n      else\n        when _t'2 == ESR_EL2_SYSREG_ISS_RT_spec (VZ64 _esr) adt;\n        rely is_int _t'2;\n        rely is_int _idreg;\n        when' _t'3 == read_idreg_spec _idreg adt;\n        rely is_int64 _t'3;\n        rely is_int64 (18446744073709551615 - _mask);\n        rely is_int64 (Z.land _t'3 (18446744073709551615 - _mask));\n        when adt == set_rec_regs_spec (_rec_base, _rec_ofst) _t'2 (VZ64 (Z.land _t'3 (18446744073709551615 - _mask))) 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/RealmSyncHandlerAux/LowSpecs/handle_id_sysreg_trap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.276926332795645}}
{"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 NatStructs.\nFrom Fairness Require Import pind LPCM World WFLib.\nFrom Fairness Require Export Mod ModSimNoSync ModSimStutter.\n\nSet Implicit Arguments.\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  Let ident_src := @ident_src _ident_src.\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 _geno\n          (tid: thread_id) R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel)\n          (geno: bool -> bool -> URA.car -> ((@wf_stt R_src R_tgt).(T) * itree srcE R_src) -> itree tgtE R_tgt -> shared_rel)\n    :\n    bool -> bool -> URA.car -> ((@wf_stt R_src R_tgt).(T) * itree srcE R_src) -> itree tgtE R_tgt -> shared_rel :=\n  | geno_ret\n      f_src f_tgt r_ctx o o0\n      ths im_src im_tgt st_src st_tgt\n      r_src r_tgt\n      (LT: wf_stt.(lt) o0 o)\n      (GENO: RR r_src r_tgt r_ctx (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, Ret r_src) (Ret r_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n\n  | geno_tauL\n      f_src f_tgt r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      itr_src itr_tgt\n      (GENO: geno true f_tgt r_ctx (o, itr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, Tau itr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | geno_chooseL\n      f_src f_tgt r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      X ktr_src itr_tgt\n      (GENO: exists x, geno true f_tgt r_ctx (o, ktr_src x) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, trigger (Choose X) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | geno_rmwL\n      f_src f_tgt r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      X rmw ktr_src itr_tgt\n      (GENO: geno true f_tgt r_ctx (o, ktr_src (snd (rmw st_src) : X)) itr_tgt (ths, im_src, im_tgt, fst (rmw st_src), st_tgt))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, trigger (Rmw rmw) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | geno_tidL\n      f_src f_tgt r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      ktr_src itr_tgt\n      (GENO: geno true f_tgt r_ctx (o, ktr_src tid) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, trigger (GetTid) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | geno_UB\n      f_src f_tgt r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      ktr_src itr_tgt\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, trigger (Undefined) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | geno_fairL\n      f_src f_tgt r_ctx o\n      ths im_src0 im_tgt st_src st_tgt\n      f ktr_src itr_tgt\n      (GENO: exists im_src1,\n             (<<FAIR: fair_update im_src0 im_src1 (prism_fmap inrp f)>>) /\\\n               (<<GENO: geno true f_tgt r_ctx (o, ktr_src tt) itr_tgt (ths, im_src1, im_tgt, st_src, st_tgt)>>))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, trigger (Fair f) >>= ktr_src) itr_tgt (ths, im_src0, im_tgt, st_src, st_tgt)\n\n  | geno_tauR\n      f_src f_tgt r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      itr_src itr_tgt\n      (GENO: geno f_src true r_ctx (o, itr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, itr_src) (Tau itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | geno_chooseR\n      f_src f_tgt r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      X itr_src ktr_tgt\n      (GENO: forall x, geno f_src true r_ctx (o, itr_src) (ktr_tgt x) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, itr_src) (trigger (Choose X) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | geno_rmwR\n      f_src f_tgt r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      X rmw itr_src ktr_tgt\n      (GENO: geno f_src true r_ctx (o, itr_src) (ktr_tgt (snd (rmw st_tgt) : X)) (ths, im_src, im_tgt, st_src, fst (rmw st_tgt)))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, itr_src) (trigger (Rmw rmw) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | geno_tidR\n      f_src f_tgt r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      itr_src ktr_tgt\n      (GENO: geno f_src true r_ctx (o, itr_src) (ktr_tgt tid) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, itr_src) (trigger (GetTid) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | geno_fairR\n      f_src f_tgt r_ctx o\n      ths im_src im_tgt0 st_src st_tgt\n      f itr_src ktr_tgt\n      (GENO: forall im_tgt1 (FAIR: fair_update im_tgt0 im_tgt1 (prism_fmap inrp f)),\n          (<<GENO: geno f_src true r_ctx (o, itr_src) (ktr_tgt tt) (ths, im_src, im_tgt1, st_src, st_tgt)>>))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, itr_src) (trigger (Fair f) >>= ktr_tgt) (ths, im_src, im_tgt0, st_src, st_tgt)\n\n  | geno_observe\n      f_src f_tgt r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      fn args ktr_src ktr_tgt\n      (GENO: forall ret,\n             geno true true r_ctx (o, ktr_src ret) (ktr_tgt ret) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, trigger (Observe fn args) >>= ktr_src) (trigger (Observe fn args) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n\n  | geno_call\n      f_src f_tgt r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      fn args ktr_src itr_tgt\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o, trigger (Call fn args) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n\n  | geno_yieldR\n      f_src f_tgt r_ctx0 o0\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      o1\n      (STUTTER: wf_stt.(lt) o1 o0)\n      (GENO: 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          (<<GENO: geno f_src true r_ctx1 (o1, trigger (Yield) >>= ktr_src) (ktr_tgt tt) (ths1, im_src1, im_tgt2, st_src1, st_tgt1)>>))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx0 (o0, trigger (Yield) >>= ktr_src) (trigger (Yield) >>= ktr_tgt) (ths0, im_src0, im_tgt0, st_src0, st_tgt0)\n\n  | geno_yieldL\n      f_src f_tgt r_ctx o0\n      ths im_src0 im_tgt st_src st_tgt\n      ktr_src itr_tgt\n      (GENO: exists im_src1 o1,\n          (<<FAIR: fair_update im_src0 im_src1 (prism_fmap inlp (tids_fmap tid ths))>>) /\\\n            (<<GENO: geno true f_tgt r_ctx (o1, ktr_src tt) itr_tgt (ths, im_src1, im_tgt, st_src, st_tgt)>>))\n    :\n    _geno tid RR geno f_src f_tgt r_ctx (o0, trigger (Yield) >>= ktr_src) itr_tgt (ths, im_src0, im_tgt, st_src, st_tgt)\n\n  | geno_progress\n      r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      itr_src itr_tgt\n      (GENO: ModSimNoSync.lsim I tid RR false false r_ctx itr_src itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _geno tid RR geno true true r_ctx (o, itr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  .\n\n  Definition geno (tid: thread_id)\n             R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel):\n    bool -> bool -> URA.car -> (wf_stt.(T) * itree srcE R_src) -> itree tgtE R_tgt -> shared_rel :=\n    pind6 (_geno tid RR) top6.\n\n  Lemma geno_mon tid R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel): monotone6 (_geno tid RR).\n  Proof.\n    ii. inv IN; try (econs; eauto; fail).\n    { des. econs; eauto. }\n    { des. econs; eauto. }\n    { econs; eauto. i. eapply LE. eapply GENO. eauto. }\n    { econs; eauto. i. specialize (GENO _ _ _ _ _ _ _ INV0 VALID0 _ TGT). des. esplits; eauto. }\n    { des. econs; esplits; eauto. }\n  Qed.\n\n  Local Hint Constructors _geno: core.\n  Local Hint Unfold geno: core.\n  Local Hint Resolve geno_mon: paco.\n\n  Lemma geno_ord_weak\n        tid R0 R1 (LRR: R0 -> R1 -> URA.car -> shared_rel)\n        ps pt r_ctx src tgt (shr: shared) o0 o1\n        (LT: wf_stt.(lt) o0 o1)\n        (GENO: geno tid LRR ps pt r_ctx (o0, src) tgt shr)\n    :\n    geno tid LRR ps pt r_ctx (o1, src) tgt shr.\n  Proof.\n    remember (o0, src) as osrc.\n    move GENO before tid. revert_until GENO.\n    pattern ps, pt, r_ctx, osrc, tgt, shr.\n    revert ps pt r_ctx osrc tgt shr GENO. apply pind6_acc.\n    intros rr DEC IH. clear DEC. intros ps pt r_ctx osrc tgt shr GENO.\n    i; clarify.\n    eapply pind6_unfold in GENO; eauto with paco.\n    inv GENO.\n\n    { eapply pind6_fold. eapply geno_ret; eauto. }\n    { eapply pind6_fold. eapply geno_tauL; eauto.\n      destruct GENO0 as [GENO IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind6_fold. eapply geno_chooseL; eauto.\n      des. destruct GENO0 as [GENO IND]. eapply IH in IND; eauto. esplits; eauto.\n      split; ss; eauto.\n    }\n    { eapply pind6_fold. eapply geno_rmwL; eauto.\n      destruct GENO0 as [GENO IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind6_fold. eapply geno_tidL; eauto.\n      destruct GENO0 as [GENO IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind6_fold. eapply geno_UB; eauto. }\n    { eapply pind6_fold. eapply geno_fairL; eauto.\n      des. destruct GENO as [GENO IND]. eapply IH in IND; eauto. esplits; eauto.\n      split; ss; eauto.\n    }\n\n    { eapply pind6_fold. eapply geno_tauR; eauto.\n      destruct GENO0 as [GENO IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind6_fold. eapply geno_chooseR; eauto.\n      i. specialize (GENO0 x).\n      destruct GENO0 as [GENO IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind6_fold. eapply geno_rmwR; eauto.\n      destruct GENO0 as [GENO IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind6_fold. eapply geno_tidR; eauto.\n      destruct GENO0 as [GENO IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind6_fold. eapply geno_fairR; eauto.\n      i. specialize (GENO0 _ FAIR).\n      destruct GENO0 as [GENO IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind6_fold. eapply geno_observe; eauto.\n      i. specialize (GENO0 ret).\n      destruct GENO0 as [GENO IND]. eapply IH in IND; eauto. split; ss.\n    }\n\n    { eapply pind6_fold. eapply geno_call; eauto. }\n\n    { eapply pind6_fold. eapply geno_yieldR; eauto.\n      i. specialize (GENO0 _ _ _ _ _ _ _ INV0 VALID0 _ TGT). des. esplits; eauto.\n      destruct GENO0 as [GENO IND]. eapply IH in IND; eauto. split; ss.\n    }\n\n    { eapply pind6_fold. eapply geno_yieldL; eauto.\n      des. esplits; eauto.\n      eapply upind6_mon; eauto. ss.\n    }\n\n    { eapply pind6_fold. eapply geno_progress; eauto. }\n\n  Qed.\n\n  Lemma nosync_geno\n        tid R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel)\n        ps pt r_ctx src tgt shr\n        (LSIM: ModSimNoSync.lsim I tid RR ps pt r_ctx src tgt shr)\n    :\n    exists o, geno tid RR ps pt r_ctx (o, src) 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 (fzero:= fun _: (A R0 R1) => @ord_tree_base (A R0 R1)). set (one:= ord_tree_cons fzero).\n    inv LSIM.\n\n    { exists one. eapply pind6_fold. eapply geno_ret; eauto.\n      instantiate (1:=fzero (ps, pt, r_ctx, Ret r_src, Ret r_tgt, (ths, im_src, im_tgt, st_src, st_tgt))); ss.\n    }\n\n    { destruct LSIM0 as [LSIM IND]. eapply IH in IND. des.\n      exists o. eapply pind6_fold. eapply geno_tauL; eauto. split; ss.\n    }\n    { des. destruct LSIM0 as [LSIM IND]. eapply IH in IND. des.\n      exists o. eapply pind6_fold. eapply geno_chooseL; eauto. eexists. split; ss. eauto.\n    }\n    { destruct LSIM0 as [LSIM IND]. eapply IH in IND. des.\n      exists o. eapply pind6_fold. eapply geno_rmwL; eauto. split; ss.\n    }\n    { destruct LSIM0 as [LSIM IND]. eapply IH in IND. des.\n      exists o. eapply pind6_fold. eapply geno_tidL; auto. split; ss.\n    }\n    { exists one. eapply pind6_fold. eapply geno_UB; eauto. }\n    { des. destruct LSIM as [LSIM IND]. eapply IH in IND. des.\n      exists o. eapply pind6_fold. eapply geno_fairL; eauto. esplits; eauto. split; ss.\n    }\n\n    { destruct LSIM0 as [LSIM IND]. eapply IH in IND. des. exists o.\n      eapply pind6_fold. eapply geno_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                           geno tid RR ps pt rs (o, src) tgt shr).\n        eauto.\n      }\n      intro JOIN. des. exists o1.\n      eapply pind6_fold. eapply geno_chooseR.\n      i. specialize (LSIM0 x). destruct LSIM0 as [LSIM IND].\n      specialize (JOIN (ps, true, r_ctx, src, (ktr_tgt x), (ths, im_src, im_tgt, st_src, st_tgt))).\n      destruct JOIN; auto. des. split; ss.\n      eapply geno_ord_weak; eauto.\n    }\n\n    { destruct LSIM0 as [LSIM IND]. eapply IH in IND. des. exists o.\n      eapply pind6_fold. eapply geno_rmwR; eauto. ss.\n    }\n    { destruct LSIM0 as [LSIM IND]. eapply IH in IND. des. exists o.\n      eapply pind6_fold. eapply geno_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                           geno tid RR ps pt rs (o, src) tgt shr).\n        eauto.\n      }\n      intro JOIN. des. exists o1.\n      eapply pind6_fold. eapply geno_fairR.\n      i. specialize (LSIM0 _ FAIR). destruct LSIM0 as [LSIM IND].\n      specialize (JOIN (ps, true, r_ctx, src, (ktr_tgt ()), (ths, im_src, im_tgt1, st_src, st_tgt))).\n      destruct JOIN; auto. des. split; ss.\n      eapply geno_ord_weak; 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                           geno tid RR ps pt rs (o, src) tgt shr).\n        eauto.\n      }\n      intro JOIN. des. exists o1.\n      eapply pind6_fold. eapply geno_observe.\n      i. specialize (LSIM0 ret). destruct LSIM0 as [LSIM IND].\n      specialize (JOIN (true, true, r_ctx, ktr_src ret, ktr_tgt ret, (ths, im_src, im_tgt, st_src, st_tgt))).\n      destruct JOIN; auto. des. split; ss.\n      eapply geno_ord_weak; 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                           geno tid RR ps pt rs (o, src) tgt shr).\n        eauto.\n      }\n      intro JOIN. des.\n      set (fo1:= fun _: A R0 R1 => o1). exists (ord_tree_cons fo1).\n      eapply pind6_fold. eapply geno_call.\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                           geno tid RR ps pt rs (o, src) tgt shr).\n        eauto.\n      }\n      intro JOIN. des.\n      set (fo1:= fun _: A R0 R1 => o1). exists (ord_tree_cons fo1).\n      eapply pind6_fold. eapply geno_yieldR.\n      1,2: eauto.\n      { instantiate (1:=fo1 (ps, pt, r_ctx, (x <- trigger Yield;; ktr_src x), (x <- trigger Yield;; ktr_tgt x), (ths0, im_src0, im_tgt0, st_src0, st_tgt0))). ss.\n      }\n      i. specialize (LSIM0 _ _ _ _ _ _ _ INV0 VALID0 _ TGT). destruct LSIM0 as [LSIM IND].\n      specialize (JOIN (ps, true, r_ctx1, (x <- trigger Yield;; ktr_src x), ktr_tgt (), (ths1, im_src1, im_tgt2, st_src1, st_tgt1))).\n      destruct JOIN; auto. des. subst fo1. ss. split; ss. eapply geno_ord_weak; eauto.\n    }\n\n    { des. destruct LSIM as [LSIM IND]. eapply IH in IND. des. exists o.\n      eapply pind6_fold. eapply geno_yieldL; eauto. esplits; eauto.\n      split; ss. eauto.\n    }\n\n    { exists one. eapply pind6_fold. eapply geno_progress. pclearbot. auto. }\n\n  Qed.\n\nEnd GENORDER.\n#[export] Hint Constructors _geno: core.\n#[export] Hint Unfold geno: core.\n#[export] Hint Resolve geno_mon: paco.\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  Let ident_src := @ident_src _ident_src.\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 :=\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  Definition lift_wf (wf: WF): WF := sum_WF wf (option_WF wf).\n\n  Definition mk_o (wf: WF) R (o: wf.(T)) (ps: bool) (itr_src: itree srcE R): (lift_wf wf).(T) :=\n    if ps\n    then match (observe itr_src) with\n         | VisF (((|Yield)|)|)%sum _ => (inr (Some o))\n         | _ => (inr None)\n         end\n    else match (observe itr_src) with\n         | VisF (((|Yield)|)|)%sum _ => (inl o)\n         | _ => (inr None)\n         end.\n\n  Let A R0 R1 := (bool * bool * URA.car * (itree srcE R0) * (itree tgtE R1) * shared)%type.\n  Let wf_ot R0 R1 := @ord_tree_WF (A R0 R1).\n  Let wf_stt R0 R1 := lift_wf (@wf_ot R0 R1).\n\n  Lemma nosync_implies_stutter\n        tid\n        R0 R1 (LRR: R0 -> R1 -> URA.car -> shared_rel)\n        ps pt r_ctx src tgt\n        (shr: shared)\n        (LSIM: ModSimNoSync.lsim I tid LRR ps pt r_ctx src tgt shr)\n    :\n    exists (o: (@wf_stt R0 R1).(T)),\n      ModSimStutter.lsim (wf_stt) I tid LRR ps pt r_ctx (o, src) tgt shr.\n  Proof.\n    eapply nosync_geno in LSIM. des.\n    exists (mk_o (@wf_ot R0 R1) o ps src).\n    ginit. eapply cpn6_wcompat. eapply lsim_mon.\n    revert_until LRR. gcofix CIH; i.\n    remember (o, src) as osrc.\n    move LSIM before CIH. revert_until LSIM.\n    pattern ps, pt, r_ctx, osrc, tgt, shr.\n    revert ps pt r_ctx osrc tgt shr LSIM. apply pind6_acc.\n    intros rr DEC IH. clear DEC. intros ps pt r_ctx osrc tgt shr LSIM.\n    intros src o Eosrc. clarify.\n    eapply pind6_unfold in LSIM; eauto with paco.\n    inv LSIM.\n\n    { guclo lsim_indC_spec. econs 1; eauto.\n      instantiate (1:=(inl o1)). ss.\n      unfold mk_o. des_ifs. all: econs 3.\n    }\n\n    { destruct GENO as [GENO IND]. eapply IH in IND; eauto.\n      guclo lsim_indC_spec. econs 2; eauto.\n      guclo lsim_ord_weakC_spec. econs; eauto.\n      unfold mk_o. des_ifs; try reflexivity.\n      - right. ss. do 2 econs.\n      - right. ss. do 2 econs.\n    }\n    { des. destruct GENO as [GENO IND]. eapply IH in IND; eauto.\n      guclo lsim_indC_spec. econs 3; eauto. exists x.\n      guclo lsim_ord_weakC_spec. econs; eauto.\n      unfold mk_o. des_ifs; try reflexivity.\n      - right. ss. do 2 econs.\n      - right. ss. do 2 econs.\n    }\n    { destruct GENO as [GENO IND]. eapply IH in IND; eauto.\n      guclo lsim_indC_spec. econs 4; eauto.\n      guclo lsim_ord_weakC_spec. econs; eauto.\n      unfold mk_o. des_ifs; try reflexivity.\n      - right. ss. do 2 econs.\n      - right. ss. do 2 econs.\n    }\n    { destruct GENO as [GENO IND]. eapply IH in IND; eauto.\n      guclo lsim_indC_spec. econs 5; eauto.\n      guclo lsim_ord_weakC_spec. econs; eauto.\n      unfold mk_o. des_ifs; try reflexivity.\n      - right. ss. do 2 econs.\n      - right. ss. do 2 econs.\n    }\n    { guclo lsim_indC_spec. econs 6; eauto. }\n    { des. destruct GENO0 as [GENO IND]. eapply IH in IND; eauto.\n      guclo lsim_indC_spec. econs 7; eauto. esplits; eauto.\n      guclo lsim_ord_weakC_spec. econs; eauto.\n      unfold mk_o. des_ifs; try reflexivity.\n      - right. ss. do 2 econs.\n      - right. ss. do 2 econs.\n    }\n\n    { destruct GENO as [GENO IND]. eapply IH in IND; eauto.\n      guclo lsim_indC_spec. econs 8; eauto.\n    }\n    { guclo lsim_indC_spec. econs 9; eauto. i. specialize (GENO x).\n      destruct GENO as [GENO IND]. eapply IH in IND; eauto.\n    }\n    { destruct GENO as [GENO IND]. eapply IH in IND; eauto.\n      guclo lsim_indC_spec. econs 10; eauto.\n    }\n    { destruct GENO as [GENO IND]. eapply IH in IND; eauto.\n      guclo lsim_indC_spec. econs 11; eauto.\n    }\n    { guclo lsim_indC_spec. econs 12; eauto. i. specialize (GENO _ FAIR).\n      destruct GENO as [GENO IND]. eapply IH in IND; eauto.\n    }\n\n    { guclo lsim_indC_spec. econs 13; eauto. i. specialize (GENO ret).\n      destruct GENO as [GENO IND]. eapply IH in IND; eauto.\n      guclo lsim_ord_weakC_spec. econs; eauto.\n      unfold mk_o. ss. des_ifs; try reflexivity.\n      - right. ss. do 2 econs.\n      - right. ss. do 2 econs.\n    }\n\n    { guclo lsim_indC_spec. econs 14. }\n\n    { guclo lsim_indC_spec. econs 15; eauto.\n      2:{ i. specialize (GENO _ _ _ _ _ _ _ INV0 VALID0 _ TGT). des.\n          destruct GENO as [GENO IND]. eapply IH in IND; eauto.\n          esplits.\n          guclo lsim_resetC_spec. econs; eauto.\n      }\n      unfold mk_o; ss. rewrite !bind_trigger. ss.\n      des_ifs.\n      - do 2 econs. auto.\n      - econs. auto.\n    }\n\n    { des. destruct GENO0 as [GENO IND]. eapply IH in IND; eauto.\n      guclo lsim_indC_spec. econs 16; eauto.\n    }\n\n    { eapply nosync_geno in GENO. des.\n      guclo lsim_ord_weakC_spec. econs.\n      instantiate (1:=mk_o (@wf_ot R0 R1) o0 false src).\n      gfinal. right. pfold. eapply pind6_fold. econs 17. right. eapply CIH. auto.\n      ss. des_ifs; try reflexivity. right. ss. do 2 econs.\n    }\n\n  Qed.\n\nEnd PROOF.\n\nSection MODSIM.\n\n  Lemma nosync_implies_stutter_mod\n        md_src md_tgt\n        (MDSIM: ModSimNoSync.ModSim.mod_sim md_src md_tgt)\n    :\n    ModSimStutter.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 := programE _ident_src state_src).\n    set (tgtE := programE _ident_tgt state_tgt).\n    set (ident_src := @ident_src _ident_src).\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 (wf_stt:=fun R0 R1 => lift_wf (@ord_tree_WF (bool * bool * URA.car * (itree srcE R0) * (itree tgtE R1) * shared)%type)).\n    econs; eauto. instantiate (1:=wf_stt).\n    i. specialize (init im_tgt). des. rename init0 into funs. exists I. esplits; eauto.\n    i. specialize (funs fn args). des_ifs.\n    unfold ModSimNoSync.local_sim in funs.\n    ii. specialize (funs _ _ _ _ _ _ _ INV tid _ THS VALID _ UPD).\n    des. esplits; eauto. instantiate (1:=inr None).\n    i. specialize (funs1 _ _ _ _ _ _ _ INV1 VALID1 _ TGT).\n    des. esplits; eauto. i. specialize (LSIM fs ft).\n    eapply nosync_implies_stutter in LSIM. des.\n    eapply stutter_ord_weak. 2: eapply LSIM.\n    clear. destruct o.\n    { right. econs. }\n    destruct t.\n    { right. do 2 econs. }\n    { left. auto. }\n  Qed.\n\nEnd MODSIM.\n\nSection USERSIM.\n\n  Lemma nosync_implies_stutter_user\n        md_src md_tgt p_src p_tgt\n        (MDSIM: ModSimNoSync.UserSim.sim md_src md_tgt p_src p_tgt)\n    :\n    ModSimStutter.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 := programE _ident_src state_src).\n    set (tgtE := programE _ident_tgt state_tgt).\n    set (ident_src := @ident_src _ident_src).\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 (wf_stt:=fun R0 R1 => lift_wf (@ord_tree_WF (bool * bool * URA.car * (itree srcE R0) * (itree tgtE R1) * shared)%type)).\n    econs; eauto. instantiate (1:=wf_stt).\n    i. specialize (funs im_tgt). des. exists I. esplits; eauto.\n    instantiate (1:=NatMap.map (fun _ => inr None) p_src).\n    eapply nm_find_some_implies_forall4.\n    { apply nm_forall2_wf_pair. eapply list_forall3_implies_forall2_2; eauto. clear. i. des. des_ifs. des; clarify. }\n    { apply nm_forall2_wf_pair. eapply list_forall3_implies_forall2_3; eauto. clear. i. des. des_ifs. des; clarify. }\n    { unfold nm_wf_pair. unfold key_set. rewrite nm_map_unit1_map_eq. ss. }\n    i. eapply nm_forall3_implies_find_some in SIM; eauto.\n    unfold ModSimNoSync.local_sim_init in SIM. unfold local_sim_init.\n    i. specialize (SIM _ _ _ _ _ _ _ INV VALID _ FAIR). des. esplits; eauto.\n    i. specialize (SIM0 fs ft). eapply nosync_implies_stutter in SIM0. des.\n    rewrite NatMapP.F.map_o in FIND4. unfold option_map in FIND4. des_ifs.\n    eapply stutter_ord_weak. 2: eapply SIM0.\n    clear. destruct o.\n    { right. econs. }\n    destruct t.\n    { right. do 2 econs. }\n    { left. auto. }\n  Qed.\n\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/NoSync2Stutter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.276926332795645}}
{"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.machine2.invariant5.\nRequire Export DistributedReferenceCounting.machine2.invariant7.\n\nUnset Standard Proposition Elimination Names.\n\n(* changes:\n   In safety1 and safety2, I had to use \n   sigma_but_strictly_positive, instead of sigma_strictly_positive.\n\n   In safety2, the case ~s2=owner should not be isolated\n*)\n\n\nLemma direct_son_is_positive :\n forall c : Config,\n legal c ->\n forall s : Site,\n direct_son c s ->\n (Int (rt c s) + reduce Message dec_count (bm c s owner) +\n  reduce Message copy_count (bm c owner s) -\n  reduce Message new_inc_count (bm c s owner) > 0)%Z.\n\n\nProof.\n  intros.\n  elim H0.\n  intros.\n  rewrite H2; unfold Int in |- *.\n  generalize (not_inc_dec_in (bm c s0 owner) H3); intro.\n  generalize (copy_count_is_positive (bm c owner s0)).\n  intro.\n  generalize (dec_count_is_positive (bm c s0 owner)); intro.\n  cut (reduce Message new_inc_count (bm c s0 owner) = 0%Z).\n  intro.\n  omega.\n  \n  generalize H4.\n  elim (bm c s0 owner).\n  simpl in |- *; auto.\n  \n  intro.\n  case d.\n  simpl in |- *.\n  intros.\n  rewrite H7.\n  auto.\n  \n  intro.\n  generalize (H8 s1).\n  intuition.\n  \n  intros.\n  elim (H8 s1); simpl in |- *.\n  left; auto.\n  \n  simpl in |- *; intros.\n  rewrite H7.\n  omega.\n  \n  intro.\n  generalize (H8 s1).\n  intuition.\nQed.\n\nRemark add_reduce : forall x : Z, (x > 0)%Z -> (x + 1 - 1 > 0)%Z.\nProof.\n  intro; omega.\nQed.\n\nLemma safety1 :\n forall c : Config,\n legal c ->\n forall s : Site, s <> owner -> rt c s = true -> (st c owner > 0)%Z.\n\nProof.\n  intros.\n  rewrite (invariant4 c H).\n  rewrite other_definition_for_sigma_receive_table.\n  rewrite <- sigma_same_table.\n  rewrite <- sigma_same_table.\n  rewrite <- sigma_same_table2.\n  unfold Z_id in |- *.\n  unfold fun_minus in |- *.\n  unfold fun_sum in |- *.\n  rewrite sigma_sigma_but_owner.\n  rewrite owner_rt_true.\n  rewrite empty_q_to_me.\n  simpl in |- *.\n  simpl in |- *.\n  elim (direct_or_indirect_son1 c s H0 H1); intro.\n  unfold sigma_table_but_owner in |- *.\n  apply add_reduce.\n  apply sigma_but_strictly_positive with (x := s).\n  apply in_s_LS.\n  \n  auto.\n  \n  intro; apply invariant5; auto.\n  \n  apply direct_son_is_positive; auto.\n  \n  apply add_reduce.\n  elim (parent_invariant c H s b).\n  intros.\n  decompose [and] H2.\n  unfold sigma_table_but_owner in |- *.\n  apply sigma_but_strictly_positive with (x := x).\n  apply in_s_LS.\n  \n  elim H3.\n  intros; auto.\n  \n  intro; apply invariant5; auto.\n  \n  apply direct_son_is_positive; auto.\n  \n  auto.\n  \n  auto.\nQed.\n\n\nLemma safety2 :\n forall c : Config,\n legal c ->\n forall s1 s2 : Site,\n In_queue Message copy (bm c s1 s2) -> (st c owner > 0)%Z.\nProof.\n  intros.\n  elim (decide_inc_dec_in_queue c s2); intro.\n  elim a; intros.\n  apply safety1 with (s := x).\n  auto.\n  \n  apply (not_owner_inc3 c s2 owner H x).\n  apply inc_dec_in; auto.\n  \n  generalize (inc_dec_in x (bm c s2 owner) p).\n  intro.\n  generalize (not_owner_inc3 c s2 owner H x H1).\n  intro.\n  generalize (positive_st c x s2 H2 H H1).\n  intro.\n  generalize (st_rt c x H H2 H3).\n  auto.\n  \n  case (eq_site_dec s1 owner); intro.\n  rewrite (invariant4 c H).\n  rewrite other_definition_for_sigma_receive_table.\n  rewrite <- sigma_same_table.\n  rewrite <- sigma_same_table.\n  rewrite <- sigma_same_table2.\n  unfold Z_id in |- *.\n  unfold fun_minus in |- *.\n  unfold fun_sum in |- *.\n  rewrite sigma_sigma_but_owner.\n  rewrite owner_rt_true.\n  rewrite empty_q_to_me.\n  simpl in |- *.\n  apply add_reduce.\n  unfold sigma_table_but_owner in |- *.\n  apply sigma_but_strictly_positive with (x := s2).\n  apply in_s_LS.\n  \n  unfold not in |- *; intro; generalize H0.\n  rewrite e; rewrite H1; rewrite empty_q_to_me; simpl in |- *.\n  auto.\n  \n  auto.\n  \n  intro; apply invariant5; auto.\n  \n  generalize (dec_count_is_positive (bm c s2 owner)); intro.\n  cut (Int (rt c s2) >= 0)%Z.\n  intro.\n  cut (reduce Message new_inc_count (bm c s2 owner) = 0%Z).\n  intro.\n  cut (reduce Message copy_count (bm c owner s2) > 0)%Z.\n  intro.\n  omega.\n  \n  apply reduce_in_queue_strictly_positive with (x := copy).\n  intro; unfold copy_count in |- *.\n  case a; intros.\n  omega.\n  \n  omega.\n  \n  omega.\n  \n  exact eq_message_dec.\n  \n  unfold copy_count in |- *; simpl in |- *.\n  omega.\n  \n  rewrite <- e; auto.\n  \n  generalize (not_inc_dec_in (bm c s2 owner) b).\n  intros.\n  apply reduce_in_queue_null.\n  intro.\n  case x; simpl in |- *; intros.\n  auto.\n  \n  elim (H3 s); auto.\n  \n  auto.\n  \n  unfold Int in |- *.\n  case (eq_bool_dec (rt c s2)).\n  intro.\n  rewrite e0; simpl in |- *; omega.\n  \n  intro; rewrite e0; simpl in |- *; omega.\n  \n  auto.\n  \n  auto.\n  \n  apply safety1 with (s := s1).\n  auto.\n  \n  auto.\n  \n  apply st_rt.\n  auto.\n  \n  auto.\n  \n  rewrite invariant2.\n  unfold sigma_rooted in |- *.\n  apply sigma2_strictly_positive with (x := s1) (y := s2).\n  exact eq_site_dec.\n  \n  apply in_s_LS.\n  \n  apply in_s_LS.\n  \n  unfold rooted in |- *; intros.\n  apply reduce_positive_or_null.\n  intros.\n  apply rooted_fun_positive_or_null.\n  \n  unfold rooted in |- *.\n  apply reduce_in_queue_strictly_positive with (x := copy).\n  intro.\n  apply rooted_fun_positive_or_null.\n  \n  exact eq_message_dec.\n  \n  unfold rooted_fun in |- *.\n  case (eq_site_dec s1 s1); intro.\n  omega.\n  \n  elim n0.\n  auto.\n  \n  auto.\n  \n  auto.\n  \n  auto.\nQed.\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/invariant8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850154599562, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2769054557450028}}
{"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 6\n*)\n\n(** 1 Mutual Coinduction *)\n\nSection Arg6_1.\n\nDefinition monotone6 T0 T1 T2 T3 T4 T5 (gf: rel6 T0 T1 T2 T3 T4 T5 -> rel6 T0 T1 T2 T3 T4 T5) :=\n  forall x0 x1 x2 x3 x4 x5 r r' (IN: gf r x0 x1 x2 x3 x4 x5) (LE: r <6= r'), gf r' x0 x1 x2 x3 x4 x5.\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 gf : rel6 T0 T1 T2 T3 T4 T5 -> rel6 T0 T1 T2 T3 T4 T5.\nImplicit Arguments gf [].\n\nTheorem paco6_acc: forall\n  l r (OBG: forall rr (INC: r <6= rr) (CIH: l <_paco_6= rr), l <_paco_6= paco6 gf rr),\n  l <6= paco6 gf r.\nProof.\n  intros; assert (SIM: paco6 gf (r \\6/ l) x0 x1 x2 x3 x4 x5) by eauto.\n  clear PR; repeat (try left; do 7 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco6_mon: monotone6 (paco6 gf).\nProof. paco_cofix_auto; repeat (left; do 7 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco6_mult_strong: forall r,\n  paco6 gf (upaco6 gf r) <6= paco6 gf r.\nProof. paco_cofix_auto; repeat (left; do 7 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco6_mult: forall r,\n  paco6 gf (paco6 gf r) <6= paco6 gf r.\nProof. intros; eapply paco6_mult_strong, paco6_mon; eauto. Qed.\n\nTheorem paco6_fold: forall r,\n  gf (upaco6 gf r) <6= paco6 gf r.\nProof. intros; econstructor; [ |eauto]; eauto. Qed.\n\nTheorem paco6_unfold: forall (MON: monotone6 gf) r,\n  paco6 gf r <6= gf (upaco6 gf r).\nProof. unfold monotone6; intros; destruct PR; eauto. Qed.\n\nEnd Arg6_1.\n\nHint Unfold monotone6.\nHint Resolve paco6_fold.\n\nImplicit Arguments paco6_acc            [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_mon            [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_mult_strong    [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_mult           [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_fold           [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_unfold         [ T0 T1 T2 T3 T4 T5 ].\n\nInstance paco6_inst  T0 T1 T2 T3 T4 T5 (gf : rel6 T0 T1 T2 T3 T4 T5->_) r x0 x1 x2 x3 x4 x5 : paco_class (paco6 gf r x0 x1 x2 x3 x4 x5) :=\n{ pacoacc    := paco6_acc gf;\n  pacomult   := paco6_mult gf;\n  pacofold   := paco6_fold gf;\n  pacounfold := paco6_unfold gf }.\n\n(** 2 Mutual Coinduction *)\n\nSection Arg6_2.\n\nDefinition monotone6_2 T0 T1 T2 T3 T4 T5 (gf: rel6 T0 T1 T2 T3 T4 T5 -> rel6 T0 T1 T2 T3 T4 T5 -> rel6 T0 T1 T2 T3 T4 T5) :=\n  forall x0 x1 x2 x3 x4 x5 r_0 r_1 r'_0 r'_1 (IN: gf r_0 r_1 x0 x1 x2 x3 x4 x5) (LE_0: r_0 <6= r'_0)(LE_1: r_1 <6= r'_1), gf r'_0 r'_1 x0 x1 x2 x3 x4 x5.\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 gf_0 gf_1 : rel6 T0 T1 T2 T3 T4 T5 -> rel6 T0 T1 T2 T3 T4 T5 -> rel6 T0 T1 T2 T3 T4 T5.\nImplicit Arguments gf_0 [].\nImplicit Arguments gf_1 [].\n\nTheorem paco6_2_0_acc: forall\n  l r_0 r_1 (OBG: forall rr (INC: r_0 <6= rr) (CIH: l <_paco_6= rr), l <_paco_6= paco6_2_0 gf_0 gf_1 rr r_1),\n  l <6= paco6_2_0 gf_0 gf_1 r_0 r_1.\nProof.\n  intros; assert (SIM: paco6_2_0 gf_0 gf_1 (r_0 \\6/ l) r_1 x0 x1 x2 x3 x4 x5) by eauto.\n  clear PR; repeat (try left; do 7 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco6_2_1_acc: forall\n  l r_0 r_1 (OBG: forall rr (INC: r_1 <6= rr) (CIH: l <_paco_6= rr), l <_paco_6= paco6_2_1 gf_0 gf_1 r_0 rr),\n  l <6= paco6_2_1 gf_0 gf_1 r_0 r_1.\nProof.\n  intros; assert (SIM: paco6_2_1 gf_0 gf_1 r_0 (r_1 \\6/ l) x0 x1 x2 x3 x4 x5) by eauto.\n  clear PR; repeat (try left; do 7 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco6_2_0_mon: monotone6_2 (paco6_2_0 gf_0 gf_1).\nProof. paco_cofix_auto; repeat (left; do 7 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco6_2_1_mon: monotone6_2 (paco6_2_1 gf_0 gf_1).\nProof. paco_cofix_auto; repeat (left; do 7 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco6_2_0_mult_strong: forall r_0 r_1,\n  paco6_2_0 gf_0 gf_1 (upaco6_2_0 gf_0 gf_1 r_0 r_1) (upaco6_2_1 gf_0 gf_1 r_0 r_1) <6= paco6_2_0 gf_0 gf_1 r_0 r_1.\nProof. paco_cofix_auto; repeat (left; do 7 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco6_2_1_mult_strong: forall r_0 r_1,\n  paco6_2_1 gf_0 gf_1 (upaco6_2_0 gf_0 gf_1 r_0 r_1) (upaco6_2_1 gf_0 gf_1 r_0 r_1) <6= paco6_2_1 gf_0 gf_1 r_0 r_1.\nProof. paco_cofix_auto; repeat (left; do 7 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco6_2_0_mult: forall r_0 r_1,\n  paco6_2_0 gf_0 gf_1 (paco6_2_0 gf_0 gf_1 r_0 r_1) (paco6_2_1 gf_0 gf_1 r_0 r_1) <6= paco6_2_0 gf_0 gf_1 r_0 r_1.\nProof. intros; eapply paco6_2_0_mult_strong, paco6_2_0_mon; eauto. Qed.\n\nCorollary paco6_2_1_mult: forall r_0 r_1,\n  paco6_2_1 gf_0 gf_1 (paco6_2_0 gf_0 gf_1 r_0 r_1) (paco6_2_1 gf_0 gf_1 r_0 r_1) <6= paco6_2_1 gf_0 gf_1 r_0 r_1.\nProof. intros; eapply paco6_2_1_mult_strong, paco6_2_1_mon; eauto. Qed.\n\nTheorem paco6_2_0_fold: forall r_0 r_1,\n  gf_0 (upaco6_2_0 gf_0 gf_1 r_0 r_1) (upaco6_2_1 gf_0 gf_1 r_0 r_1) <6= paco6_2_0 gf_0 gf_1 r_0 r_1.\nProof. intros; econstructor; [ | |eauto]; eauto. Qed.\n\nTheorem paco6_2_1_fold: forall r_0 r_1,\n  gf_1 (upaco6_2_0 gf_0 gf_1 r_0 r_1) (upaco6_2_1 gf_0 gf_1 r_0 r_1) <6= paco6_2_1 gf_0 gf_1 r_0 r_1.\nProof. intros; econstructor; [ | |eauto]; eauto. Qed.\n\nTheorem paco6_2_0_unfold: forall (MON: monotone6_2 gf_0) (MON: monotone6_2 gf_1) r_0 r_1,\n  paco6_2_0 gf_0 gf_1 r_0 r_1 <6= gf_0 (upaco6_2_0 gf_0 gf_1 r_0 r_1) (upaco6_2_1 gf_0 gf_1 r_0 r_1).\nProof. unfold monotone6_2; intros; destruct PR; eauto. Qed.\n\nTheorem paco6_2_1_unfold: forall (MON: monotone6_2 gf_0) (MON: monotone6_2 gf_1) r_0 r_1,\n  paco6_2_1 gf_0 gf_1 r_0 r_1 <6= gf_1 (upaco6_2_0 gf_0 gf_1 r_0 r_1) (upaco6_2_1 gf_0 gf_1 r_0 r_1).\nProof. unfold monotone6_2; intros; destruct PR; eauto. Qed.\n\nEnd Arg6_2.\n\nHint Unfold monotone6_2.\nHint Resolve paco6_2_0_fold.\nHint Resolve paco6_2_1_fold.\n\nImplicit Arguments paco6_2_0_acc            [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_2_1_acc            [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_2_0_mon            [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_2_1_mon            [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_2_0_mult_strong    [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_2_1_mult_strong    [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_2_0_mult           [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_2_1_mult           [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_2_0_fold           [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_2_1_fold           [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_2_0_unfold         [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_2_1_unfold         [ T0 T1 T2 T3 T4 T5 ].\n\nInstance paco6_2_0_inst  T0 T1 T2 T3 T4 T5 (gf_0 gf_1 : rel6 T0 T1 T2 T3 T4 T5->_) r_0 r_1 x0 x1 x2 x3 x4 x5 : paco_class (paco6_2_0 gf_0 gf_1 r_0 r_1 x0 x1 x2 x3 x4 x5) :=\n{ pacoacc    := paco6_2_0_acc gf_0 gf_1;\n  pacomult   := paco6_2_0_mult gf_0 gf_1;\n  pacofold   := paco6_2_0_fold gf_0 gf_1;\n  pacounfold := paco6_2_0_unfold gf_0 gf_1 }.\n\nInstance paco6_2_1_inst  T0 T1 T2 T3 T4 T5 (gf_0 gf_1 : rel6 T0 T1 T2 T3 T4 T5->_) r_0 r_1 x0 x1 x2 x3 x4 x5 : paco_class (paco6_2_1 gf_0 gf_1 r_0 r_1 x0 x1 x2 x3 x4 x5) :=\n{ pacoacc    := paco6_2_1_acc gf_0 gf_1;\n  pacomult   := paco6_2_1_mult gf_0 gf_1;\n  pacofold   := paco6_2_1_fold gf_0 gf_1;\n  pacounfold := paco6_2_1_unfold gf_0 gf_1 }.\n\n(** 3 Mutual Coinduction *)\n\nSection Arg6_3.\n\nDefinition monotone6_3 T0 T1 T2 T3 T4 T5 (gf: rel6 T0 T1 T2 T3 T4 T5 -> rel6 T0 T1 T2 T3 T4 T5 -> rel6 T0 T1 T2 T3 T4 T5 -> rel6 T0 T1 T2 T3 T4 T5) :=\n  forall x0 x1 x2 x3 x4 x5 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) (LE_0: r_0 <6= r'_0)(LE_1: r_1 <6= r'_1)(LE_2: r_2 <6= r'_2), gf r'_0 r'_1 r'_2 x0 x1 x2 x3 x4 x5.\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 gf_0 gf_1 gf_2 : rel6 T0 T1 T2 T3 T4 T5 -> rel6 T0 T1 T2 T3 T4 T5 -> rel6 T0 T1 T2 T3 T4 T5 -> rel6 T0 T1 T2 T3 T4 T5.\nImplicit Arguments gf_0 [].\nImplicit Arguments gf_1 [].\nImplicit Arguments gf_2 [].\n\nTheorem paco6_3_0_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_0 <6= rr) (CIH: l <_paco_6= rr), l <_paco_6= paco6_3_0 gf_0 gf_1 gf_2 rr r_1 r_2),\n  l <6= paco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco6_3_0 gf_0 gf_1 gf_2 (r_0 \\6/ l) r_1 r_2 x0 x1 x2 x3 x4 x5) by eauto.\n  clear PR; repeat (try left; do 7 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco6_3_1_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_1 <6= rr) (CIH: l <_paco_6= rr), l <_paco_6= paco6_3_1 gf_0 gf_1 gf_2 r_0 rr r_2),\n  l <6= paco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco6_3_1 gf_0 gf_1 gf_2 r_0 (r_1 \\6/ l) r_2 x0 x1 x2 x3 x4 x5) by eauto.\n  clear PR; repeat (try left; do 7 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco6_3_2_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_2 <6= rr) (CIH: l <_paco_6= rr), l <_paco_6= paco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 rr),\n  l <6= paco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 (r_2 \\6/ l) x0 x1 x2 x3 x4 x5) by eauto.\n  clear PR; repeat (try left; do 7 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco6_3_0_mon: monotone6_3 (paco6_3_0 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 7 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco6_3_1_mon: monotone6_3 (paco6_3_1 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 7 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco6_3_2_mon: monotone6_3 (paco6_3_2 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 7 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco6_3_0_mult_strong: forall r_0 r_1 r_2,\n  paco6_3_0 gf_0 gf_1 gf_2 (upaco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <6= paco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 7 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco6_3_1_mult_strong: forall r_0 r_1 r_2,\n  paco6_3_1 gf_0 gf_1 gf_2 (upaco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <6= paco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 7 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco6_3_2_mult_strong: forall r_0 r_1 r_2,\n  paco6_3_2 gf_0 gf_1 gf_2 (upaco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <6= paco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 7 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco6_3_0_mult: forall r_0 r_1 r_2,\n  paco6_3_0 gf_0 gf_1 gf_2 (paco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <6= paco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco6_3_0_mult_strong, paco6_3_0_mon; eauto. Qed.\n\nCorollary paco6_3_1_mult: forall r_0 r_1 r_2,\n  paco6_3_1 gf_0 gf_1 gf_2 (paco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <6= paco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco6_3_1_mult_strong, paco6_3_1_mon; eauto. Qed.\n\nCorollary paco6_3_2_mult: forall r_0 r_1 r_2,\n  paco6_3_2 gf_0 gf_1 gf_2 (paco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <6= paco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco6_3_2_mult_strong, paco6_3_2_mon; eauto. Qed.\n\nTheorem paco6_3_0_fold: forall r_0 r_1 r_2,\n  gf_0 (upaco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <6= paco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco6_3_1_fold: forall r_0 r_1 r_2,\n  gf_1 (upaco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <6= paco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco6_3_2_fold: forall r_0 r_1 r_2,\n  gf_2 (upaco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <6= paco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco6_3_0_unfold: forall (MON: monotone6_3 gf_0) (MON: monotone6_3 gf_1) (MON: monotone6_3 gf_2) r_0 r_1 r_2,\n  paco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2 <6= gf_0 (upaco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2).\nProof. unfold monotone6_3; intros; destruct PR; eauto. Qed.\n\nTheorem paco6_3_1_unfold: forall (MON: monotone6_3 gf_0) (MON: monotone6_3 gf_1) (MON: monotone6_3 gf_2) r_0 r_1 r_2,\n  paco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2 <6= gf_1 (upaco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2).\nProof. unfold monotone6_3; intros; destruct PR; eauto. Qed.\n\nTheorem paco6_3_2_unfold: forall (MON: monotone6_3 gf_0) (MON: monotone6_3 gf_1) (MON: monotone6_3 gf_2) r_0 r_1 r_2,\n  paco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2 <6= gf_2 (upaco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2).\nProof. unfold monotone6_3; intros; destruct PR; eauto. Qed.\n\nEnd Arg6_3.\n\nHint Unfold monotone6_3.\nHint Resolve paco6_3_0_fold.\nHint Resolve paco6_3_1_fold.\nHint Resolve paco6_3_2_fold.\n\nImplicit Arguments paco6_3_0_acc            [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_3_1_acc            [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_3_2_acc            [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_3_0_mon            [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_3_1_mon            [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_3_2_mon            [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_3_0_mult_strong    [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_3_1_mult_strong    [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_3_2_mult_strong    [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_3_0_mult           [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_3_1_mult           [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_3_2_mult           [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_3_0_fold           [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_3_1_fold           [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_3_2_fold           [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_3_0_unfold         [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_3_1_unfold         [ T0 T1 T2 T3 T4 T5 ].\nImplicit Arguments paco6_3_2_unfold         [ T0 T1 T2 T3 T4 T5 ].\n\nInstance paco6_3_0_inst  T0 T1 T2 T3 T4 T5 (gf_0 gf_1 gf_2 : rel6 T0 T1 T2 T3 T4 T5->_) r_0 r_1 r_2 x0 x1 x2 x3 x4 x5 : paco_class (paco6_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2 x0 x1 x2 x3 x4 x5) :=\n{ pacoacc    := paco6_3_0_acc gf_0 gf_1 gf_2;\n  pacomult   := paco6_3_0_mult gf_0 gf_1 gf_2;\n  pacofold   := paco6_3_0_fold gf_0 gf_1 gf_2;\n  pacounfold := paco6_3_0_unfold gf_0 gf_1 gf_2 }.\n\nInstance paco6_3_1_inst  T0 T1 T2 T3 T4 T5 (gf_0 gf_1 gf_2 : rel6 T0 T1 T2 T3 T4 T5->_) r_0 r_1 r_2 x0 x1 x2 x3 x4 x5 : paco_class (paco6_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2 x0 x1 x2 x3 x4 x5) :=\n{ pacoacc    := paco6_3_1_acc gf_0 gf_1 gf_2;\n  pacomult   := paco6_3_1_mult gf_0 gf_1 gf_2;\n  pacofold   := paco6_3_1_fold gf_0 gf_1 gf_2;\n  pacounfold := paco6_3_1_unfold gf_0 gf_1 gf_2 }.\n\nInstance paco6_3_2_inst  T0 T1 T2 T3 T4 T5 (gf_0 gf_1 gf_2 : rel6 T0 T1 T2 T3 T4 T5->_) r_0 r_1 r_2 x0 x1 x2 x3 x4 x5 : paco_class (paco6_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2 x0 x1 x2 x3 x4 x5) :=\n{ pacoacc    := paco6_3_2_acc gf_0 gf_1 gf_2;\n  pacomult   := paco6_3_2_mult gf_0 gf_1 gf_2;\n  pacofold   := paco6_3_2_fold gf_0 gf_1 gf_2;\n  pacounfold := paco6_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/paco6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.2767862659953361}}
{"text": "Require Import Functors.\nRequire Import List.\nRequire Import Names.\nRequire Import FunctionalExtensionality.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.Bool.Bool.\n\nSection PNames.\n\n  (* ============================================== *)\n  (* TYPES                                          *)\n  (* ============================================== *)\n\n  (** SuperFunctor for Types. **)\n  Variable D : Set -> Set.\n  Context {Fun_D : Functor D}.\n\n  (* ============================================== *)\n  (* VALUES                                         *)\n  (* ============================================== *)\n\n  (** SuperFunctor for Values. **)\n  Variable V : Set -> Set.\n  Context {Fun_V : Functor V}.\n\n  Context {Sub_StuckValue_V : StuckValue :<: V}.\n  Context {WF_SubStuckValue_V : WF_Functor _ _ Sub_StuckValue_V}.\n  Context {Sub_BotValue_V : BotValue :<: V}.\n  Context {WF_SubBotValue_V : WF_Functor _ _ Sub_BotValue_V}.\n\n  (* ============================================== *)\n  (* EXPRESSIONS                                    *)\n  (* ============================================== *)\n\n  (** SuperFunctor for Expressions. **)\n  Variable E : Set -> Set -> Set.\n  Context {Fun_E : forall A, Functor (E A)}.\n\n  (* ============================================== *)\n  (* OPERATIONS                                     *)\n  (* ============================================== *)\n\n  (** TYPING **)\n\n  Context {Typeof_E : forall T,\n    FAlgebra TypeofName T (typeofR D) (E (typeofR D))}.\n\n  Context {eval_E : forall T, FAlgebra EvalName T (evalR V) (E nat)}.\n  Context {beval_E : FAlgebra EvalName (Exp (E nat)) (evalR V) (E nat)}.\n\n  (* ============================================== *)\n  (* EXPRESSION EQUIVALENCE RELATION                *)\n  (* ============================================== *)\n\n  Section eqv_Section.\n\n    Record eqv_i (A B : Set) : Set := mk_eqv_i\n      {env_A : Env A;\n        env_B : Env B;\n        eqv_a : UP'_F (E A);\n        eqv_b : UP'_F (E B)}.\n\n    (** SuperFunctor for Equivalence Relation. **)\n    Variable EQV_E : forall A B,\n      (@eqv_i A B -> Prop) -> eqv_i A B -> Prop.\n\n    Definition E_eqv A B := iFix (EQV_E A B).\n    Definition E_eqvC {A B : Set} gamma gamma' e e' :=\n      E_eqv _ _ (mk_eqv_i A B gamma gamma' e e').\n\n    Variable (NP : Set -> Set).\n    Context {Fun_NP : Functor NP}.\n    Context {sub_NP_F : forall A, NP :<: E A}.\n\n    Inductive NP_Functor_eqv\n      (A B : Set)\n      (C : eqv_i A B -> Prop)\n      : eqv_i A B -> Prop :=\n    | NP_eqv_0 : forall (gamma : Env A) (gamma' : Env B)\n      e e' (np : forall D : Set, NP D),\n      proj1_sig e = inject (subGF := sub_NP_F A) (np _) ->\n      proj1_sig e' = inject (subGF := sub_NP_F B) (np _) ->\n      (forall (A' B' C' : Set) (f : A' -> C') (g : B' -> C'),\n        fmap f (np A') = fmap g (np B')) ->\n      NP_Functor_eqv A B C (mk_eqv_i _ _ gamma gamma' e e')\n    | NP_eqv_1 : forall (gamma : Env A) (gamma' : Env B)\n      e e' (np : forall D : Set, D -> NP D)\n      a a',\n      proj1_sig e = inject (subGF := sub_NP_F A) (np _ a) ->\n      proj1_sig e' = inject (subGF := sub_NP_F B) (np _ a') ->\n      C (mk_eqv_i _ _ gamma gamma' a a') ->\n      (forall (A' B' C' : Set) (f : A' -> C') (g : B' -> C')\n        (a' : A') (b' : B'), f a' = g b' ->\n        fmap f (np A' a') = fmap g (np B' b')) ->\n      NP_Functor_eqv A B C (mk_eqv_i _ _ gamma gamma' e e')\n    | NP_eqv_2 : forall (gamma : Env A) (gamma' : Env B)\n      e e' (np : forall D : Set, D -> D -> NP D)\n      a a' b b',\n      proj1_sig e = inject (subGF := sub_NP_F A) (np _ a b) ->\n      proj1_sig e' = inject (subGF := sub_NP_F B) (np _ a' b') ->\n      C (mk_eqv_i _ _ gamma gamma' a a') ->\n      C (mk_eqv_i _ _ gamma gamma' b b') ->\n      (forall (A' B' C' : Set) (f : A' -> C') (g : B' -> C')\n        (a' a'' : A') (b' b'' : B'), f a' = g b' -> f a'' = g b'' ->\n        fmap f (np A' a' a'') = fmap g (np B' b' b'')) ->\n      NP_Functor_eqv A B C (mk_eqv_i _ _ gamma gamma' e e')\n    | NP_eqv_3 : forall (gamma : Env A) (gamma' : Env B)\n      e e' (np : forall D : Set, D -> D -> D -> NP D)\n      a a' b b' c c',\n      proj1_sig e = inject (subGF := sub_NP_F A) (np _ a b c) ->\n      proj1_sig e' = inject (subGF := sub_NP_F B) (np _ a' b' c') ->\n      C (mk_eqv_i _ _ gamma gamma' a a') ->\n      C (mk_eqv_i _ _ gamma gamma' b b') ->\n      C (mk_eqv_i _ _ gamma gamma' c c') ->\n      (forall (A' B' C' : Set) (f : A' -> C') (g : B' -> C')\n        (a' a'' a''' : A') (b' b'' b''' : B'),\n        f a' = g b' -> f a'' = g b'' -> f a''' = g b''' ->\n        fmap f (np A' a' a'' a''') = fmap g (np B' b' b'' b''')) ->\n      NP_Functor_eqv A B C (mk_eqv_i _ _ gamma gamma' e e').\n\n    Definition ind_alg_NP_Functor_eqv\n      (A B : Set)\n      (P : eqv_i A B -> Prop)\n      (H : forall gamma gamma' e e' np e_eq e'_eq wf_np,\n        P (mk_eqv_i _ _ gamma gamma' e e'))\n      (H0 : forall gamma gamma' e e' np a a' e_eq e'_eq\n        (IHa : P (mk_eqv_i _ _  gamma gamma' a a')) wf_np,\n        P (mk_eqv_i _ _  gamma gamma' e e'))\n      (H1 : forall gamma gamma' e e' np a a' b b' e_eq e'_eq\n        (IHa : P (mk_eqv_i _ _  gamma gamma' a a'))\n        (IHb : P (mk_eqv_i _ _  gamma gamma' b b')) wf_np,\n        P (mk_eqv_i _ _  gamma gamma' e e'))\n      (H2 : forall gamma gamma' e e' np a a' b b' c c' e_eq e'_eq\n        (IHa : P (mk_eqv_i _ _  gamma gamma' a a'))\n        (IHb : P (mk_eqv_i _ _  gamma gamma' b b'))\n        (IHc : P (mk_eqv_i _ _  gamma gamma' c c')) wf_np,\n        P (mk_eqv_i _ _  gamma gamma' e e'))\n      i (e : NP_Functor_eqv A B P i) : P i :=\n      match e in NP_Functor_eqv _ _ _  i return P i with\n        | NP_eqv_0 gamma gamma' e e' np e_eq e'_eq wf_np =>\n          H gamma gamma' e e' np e_eq e'_eq wf_np\n        | NP_eqv_1 gamma gamma' e e' np a a' e_eq e'_eq a_eqv wf_np =>\n          H0 gamma gamma' e e' np a a' e_eq e'_eq a_eqv wf_np\n        | NP_eqv_2 gamma gamma' e e' np a a' b b' e_eq e'_eq a_eqv b_eqv wf_np =>\n          H1 gamma gamma' e e' np a a' b b' e_eq e'_eq a_eqv b_eqv wf_np\n        | NP_eqv_3 gamma gamma' e e' np a a' b b' c c' e_eq e'_eq a_eqv b_eqv c_eqv wf_np  =>\n          H2 gamma gamma' e e' np a a' b b' c c' e_eq e'_eq a_eqv b_eqv c_eqv wf_np\n      end.\n\n    Definition NP_Functor_eqv_ifmap\n      (A B : Set)\n      (A' B' : eqv_i A B -> Prop) i (f : forall i, A' i -> B' i)\n      (eqv_a : NP_Functor_eqv A B A' i) :\n      NP_Functor_eqv A B B' i :=\n      match eqv_a in NP_Functor_eqv _ _ _ i return NP_Functor_eqv _ _ _ i with\n        | NP_eqv_0 gamma gamma' e e' np e_eq e'_eq wf_np =>\n          NP_eqv_0 _ _ _ gamma gamma' e e' np e_eq e'_eq wf_np\n        | NP_eqv_1 gamma gamma' e e' np a a' e_eq e'_eq a_eqv wf_np =>\n          NP_eqv_1 _ _ _ gamma gamma' e e' np a a' e_eq e'_eq (f _ a_eqv) wf_np\n        | NP_eqv_2 gamma gamma' e e' np a a' b b' e_eq e'_eq a_eqv b_eqv wf_np =>\n          NP_eqv_2 _ _ _ gamma gamma' e e' np a a' b b' e_eq e'_eq (f _ a_eqv) (f _ b_eqv) wf_np\n        | NP_eqv_3 gamma gamma' e e' np a a' b b' c c' e_eq e'_eq a_eqv b_eqv c_eqv wf_np =>\n          NP_eqv_3 _ _ _ gamma gamma' e e' np a a' b b' c c' e_eq e'_eq (f _ a_eqv) (f _ b_eqv) (f _ c_eqv) wf_np\n      end.\n\n    Global Instance iFun_Arith_eqv A B : iFunctor (NP_Functor_eqv A B).\n      constructor 1 with (ifmap := NP_Functor_eqv_ifmap A B).\n      destruct a; simpl; intros; reflexivity.\n      destruct a; simpl; intros; reflexivity.\n    Defined.\n\n    (* Projection doesn't affect Equivalence Relation.*)\n\n    Definition EQV_proj1_P A B (i : eqv_i A B) :=\n     forall a' b' H H0, a' = proj1_sig (eqv_a _ _ i) ->\n       b' = proj1_sig (eqv_b _ _ i) ->\n       E_eqvC (env_A _ _ i) (env_B _ _ i) (exist _ a' H) (exist _ b' H0).\n\n    Inductive EQV_proj1_Name := eqv_proj1_name.\n    Context {EQV_proj1_EQV : forall A B,\n      iPAlgebra EQV_proj1_Name (@EQV_proj1_P A B) (EQV_E A B)}.\n    Context {Fun_EQV_E : forall A B, iFunctor (EQV_E A B)}.\n\n    Definition EQV_proj1 A B:=\n      ifold_ (EQV_E A B) _ (ip_algebra (iPAlgebra := EQV_proj1_EQV A B)).\n\n    Variable Sub_NP_Functor_eqv_EQV_E : forall A B,\n      Sub_iFunctor (NP_Functor_eqv A B) (EQV_E A B).\n\n    Global Instance EQV_proj1_NP_Functor_eqv :\n      forall A B,\n        iPAlgebra EQV_proj1_Name (EQV_proj1_P A B) (NP_Functor_eqv _ _).\n    Proof.\n      intros; econstructor; unfold iAlgebra; intros.\n      eapply ind_alg_NP_Functor_eqv; unfold EQV_proj1_P; simpl; intros.\n      apply inject_i; econstructor; simpl; eauto.\n      rewrite H2; rewrite e_eq; eauto.\n      rewrite H3; rewrite e'_eq; eauto.\n      apply inject_i; econstructor 2; simpl; eauto.\n      rewrite H2; rewrite e_eq; eauto.\n      rewrite H3; rewrite e'_eq; eauto.\n      destruct a; destruct a'; apply IHa; auto.\n      apply inject_i; econstructor 3; simpl; eauto.\n      rewrite H2; rewrite e_eq; eauto.\n      rewrite H3; rewrite e'_eq; eauto.\n      destruct a; destruct a'; apply IHa; auto.\n      destruct b; destruct b'; apply IHb; auto.\n      apply inject_i; econstructor 4; simpl; eauto.\n      rewrite H2; rewrite e_eq; eauto.\n      rewrite H3; rewrite e'_eq; eauto.\n      destruct a; destruct a'; apply IHa; auto.\n      destruct b; destruct b'; apply IHb; auto.\n      destruct c; destruct c'; apply IHc; auto.\n      assumption.\n    Defined.\n\n  End eqv_Section.\n\n  Variable EQV_E : forall A B, (@eqv_i A B -> Prop) -> eqv_i A B -> Prop.\n  Context {Fun_EQV_E : forall A B, iFunctor (EQV_E A B)}.\n  Variable WFV : (WFValue_i D V -> Prop) -> WFValue_i D V -> Prop.\n  Context {funWFV : iFunctor WFV}.\n\n  Definition WF_eqv_environment_P (env_A_B : Env (typeofR D) * Env nat) gamma'' :=\n    (forall m b : nat,\n      lookup (snd env_A_B) m = Some b ->\n      exists T, lookup (fst env_A_B) b = Some T) /\\\n    Datatypes.length (fst env_A_B) = Datatypes.length (snd env_A_B) /\\\n    (forall m b : nat, lookup (snd env_A_B) m = Some b -> b = m) /\\\n    WF_Environment _ _ WFV gamma'' (fst env_A_B).\n\n  Definition eqv_eval_alg_Soundness'_P\n    (typeof_rec : Exp (E (typeofR D)) -> typeofR D)\n    (eval_rec : Exp (E nat) -> evalR V)\n    (typeof_F : Mixin (Exp (E (typeofR D))) (E (typeofR D)) (typeofR D))\n    (eval_F : Mixin (Exp (E nat)) (E nat) (evalR V))\n    i :=\n    E_eqv EQV_E _ _ i /\\\n    eval_alg_Soundness_P D V (E nat) WFV\n    _ WF_eqv_environment_P\n    (E (typeofR D)) _ (env_A _ _ i, env_B _ _ i) typeof_rec eval_rec\n    typeof_F eval_F\n    (proj1_sig (eqv_a _ _ i), proj1_sig (eqv_b _ _ i))\n    (conj (proj2_sig (eqv_a _ _ i)) (proj2_sig (eqv_b _ _ i))).\n\n  Lemma WF_eqv_environment_P_insert : forall gamma gamma' gamma'' v T,\n    WF_eqv_environment_P (gamma, gamma') gamma'' ->\n    WFValueC _ _ WFV v T ->\n    WF_eqv_environment_P (insert _ (Some T) gamma, insert _ (Datatypes.length gamma') gamma')\n    (insert _ v gamma'').\n  Proof.\n    intros; destruct H as [WF_gamma [WF_gamma2 [WF_gamma' WF_gamma'']]].\n    unfold WF_eqv_environment_P; simpl in *|-*; repeat split.\n    rewrite <- WF_gamma2.\n    revert WF_gamma; clear; simpl; induction gamma';\n      destruct m; simpl; intros; try discriminate.\n    injection H; intros; subst.\n    clear; induction gamma; simpl; eauto; eexists.\n    injection H; intros; subst.\n    generalize b (WF_gamma 0 _ (eq_refl _)); clear; induction gamma; simpl; intros b H;\n      destruct H as [T' lookup_T']; try discriminate.\n    destruct b; eauto.\n    eapply IHgamma'.\n    intros n0 b0 H0; eapply (WF_gamma (S n0) _ H0).\n    eassumption.\n    assert (exists m', Datatypes.length gamma' = m') as m'_eq\n      by (eexists _; reflexivity); destruct m'_eq as [m' m'_eq].\n    rewrite m'_eq; generalize m' gamma' WF_gamma2; clear; induction gamma;\n      destruct gamma'; intros; simpl; try discriminate;\n        try injection H7; intros; eauto.\n    simpl in *|-*.\n    intro; caseEq (beq_nat m (Datatypes.length gamma')).\n    assert (exists m', m' = Datatypes.length gamma') as ex_m' by\n      (eexists _; reflexivity); destruct ex_m' as [m' m'_eq];\n        rewrite <- m'_eq in H at 1.\n    rewrite <- WF_gamma2 in H1.\n    rewrite (beq_nat_true _ _ H).\n    rewrite (beq_nat_true _ _ H), m'_eq in H1.\n    rewrite <- WF_gamma2 in m'_eq; rewrite m'_eq.\n    generalize m' b H1; clear.\n    induction gamma'; simpl; intros; try discriminate.\n    injection H1; auto.\n    eauto.\n    eapply WF_gamma'.\n    rewrite <- WF_gamma2 in H1.\n    assert (exists m', m' = Datatypes.length gamma') as ex_m' by\n    (eexists _; reflexivity); destruct ex_m' as [m' m'_eq].\n    generalize m' m (beq_nat_false _ _ H) H1; clear;\n      induction gamma'; simpl; destruct m; intros;\n        try discriminate; eauto.\n    elimtype False; eauto.\n    eapply P2_Env_insert.\n    eauto.\n    apply H0.\n  Qed.\n\n  Section NP_beval_Soundness.\n\n    Variable (NP : Set -> Set).\n    Context {Fun_NP : Functor NP}.\n    Context {sub_NP_F : forall A, NP :<: E A}.\n    Context {WF_sub_NP_F_V : forall A, WF_Functor _ _ (sub_NP_F A)}.\n\n    Variable Sub_NP_Functor_eqv_EQV_E : forall A B,\n      Sub_iFunctor (NP_Functor_eqv NP A B) (EQV_E A B).\n\n    Context {eval_Soundness_alg_NP : forall pb typeof_rec eval_rec,\n      PAlgebra eval_Soundness_alg_Name (sig (UP'_P2 (eval_alg_Soundness_P D V (E nat) WFV\n        _ WF_eqv_environment_P (E (typeofR D)) _ pb typeof_rec eval_rec\n        (f_algebra (FAlgebra := Typeof_E _)) (f_algebra (FAlgebra := beval_E))))) NP}.\n    (* Context {WF_Ind_eval_Soundness_alg : forall pb typeof_rec eval_rec,\n      @WF_Ind2 (E _) (E _) NP eval_Soundness_alg_Name (Fun_E _) (Fun_E _) Fun_NP\n      (UP'_P2 (eval_alg_Soundness_P D V (E nat) WFV _ _\n        (E (typeofR D)) _ pb typeof_rec eval_rec _ _)) _ _ (eval_Soundness_alg_NP pb _ _)}. *)\n\n    Variable WF_WFV_Bot_WFV : Sub_iFunctor (WFValue_Bot D V) WFV.\n\n    Inductive eqv_eval_SoundnessName : Set := eqv_eval_soundnessname.\n\n    Context {Typeof_NP : forall T, FAlgebra TypeofName T (typeofR D) NP}.\n    Context {beval_NP : FAlgebra EvalName (Exp (E nat)) (evalR V) NP}.\n    Context {WF_eval_F : @WF_FAlgebra EvalName _ _ NP (E _)\n      (sub_NP_F _) beval_NP (eval_E _)}.\n    Context {WF_typeof_F : @WF_FAlgebra TypeofName _ _ NP (E _)\n      (sub_NP_F _) (Typeof_NP _) (Typeof_E (Fix (E (typeofR D))))}.\n\n    Global Instance eqv_eval_Soundness typeof_rec eval_rec :\n      forall (WF_Ind_eval_Soundness_alg : forall pb,\n        @WF_Ind2 (E _) (E _) NP eval_Soundness_alg_Name (Fun_E _) (Fun_E _) Fun_NP\n        (UP'_P2 (eval_alg_Soundness_P D V (E nat) WFV _ _\n          (E (typeofR D)) _ pb typeof_rec eval_rec _ _)) _ _ (eval_Soundness_alg_NP pb _ _)),\n      iPAlgebra eqv_eval_SoundnessName\n      (eqv_eval_alg_Soundness'_P typeof_rec eval_rec\n        (f_algebra (FAlgebra := Typeof_E _))\n        (f_algebra (FAlgebra := beval_E))) (NP_Functor_eqv _ _ _).\n    Proof.\n      econstructor; unfold iAlgebra; intros.\n      eapply ind_alg_NP_Functor_eqv; try eassumption;\n        unfold eqv_eval_alg_Soundness'_P; simpl; intros.\n      split.\n      apply inject_i; econstructor; eauto.\n      (* generalize (proj1_eq (WF_Ind2 := WF_Ind_eval_Soundness_alg\n        (gamma, gamma') typeof_rec eval_rec) (np _)). *)\n      generalize (proj1_eq (WF_Ind2 := WF_Ind_eval_Soundness_alg\n        (gamma, gamma')) (np _)).\n      generalize (proj2_eq (WF_Ind2 := WF_Ind_eval_Soundness_alg\n        (gamma, gamma')) (np _)).\n      intros e1_eq e2_eq.\n      destruct (p_algebra (PAlgebra := eval_Soundness_alg_NP\n        (gamma, gamma') typeof_rec eval_rec)) as\n      [[e1 e2] [[UP_e1 UP_e2] sound_e1]]; auto; simpl in *|-*.\n      destruct e as [e e_UP]; destruct e' as [e' e'_UP]; simpl.\n      simpl in *|-*.\n      revert sound_e1.\n      unfold eval_alg_Soundness_P; simpl.\n      repeat rewrite e_eq, e'_eq, e1_eq, e2_eq; simpl.\n      intros sound_e1 proj1_eval gamma'' WF_gamma'' IHa T;\n        generalize (sound_e1 proj1_eval gamma'' WF_gamma'' IHa T); intros.\n      unfold inject; simpl.\n      rewrite wf_functor.\n      erewrite wf_np.\n      apply H0.\n      erewrite wf_np.\n      unfold inject in H1; simpl in H1; rewrite wf_functor in H1.\n      apply H1.\n      destruct IHa as [eqv_a IHa]; split; intros.\n      apply inject_i; econstructor 2; eauto.\n      assert (UP'_P2\n        (eval_alg_Soundness_P D V (E nat) WFV\n          _ WF_eqv_environment_P (E (typeofR D))\n          (Fun_E (typeofR D)) (gamma, gamma') typeof_rec eval_rec f_algebra f_algebra)\n        (proj1_sig a, proj1_sig a')).\n      unfold UP'_P2; intros.\n      econstructor.\n      instantiate (1 := conj (proj2_sig _) (proj2_sig _)).\n      unfold eval_alg_Soundness_P; intros.\n      apply IHa; auto.\n      generalize (proj1_eq (WF_Ind2 := WF_Ind_eval_Soundness_alg\n        (gamma, gamma'))\n      (np _ (exist _ (proj1_sig a, proj1_sig a') H0))).\n      generalize (proj2_eq (WF_Ind2 := WF_Ind_eval_Soundness_alg\n        (gamma, gamma'))\n        (np _ (exist _(proj1_sig a, proj1_sig a') H0))).\n      intros e1_eq e2_eq.\n      destruct (p_algebra (PAlgebra := eval_Soundness_alg_NP\n        (gamma, gamma') typeof_rec eval_rec)) as\n        [[e1 e2] [[UP_e1 UP_e2] sound_e1]]; auto; simpl in *|-*.\n      destruct e as [e e_UP]; destruct e' as [e' e'_UP]; simpl.\n      simpl in *|-*.\n      revert sound_e1.\n      unfold eval_alg_Soundness_P; simpl.\n      repeat rewrite e_eq, e'_eq, e1_eq, e2_eq; simpl.\n      intros sound_e1 eval_rec_proj typeof_rec_proj gamma'' WF_gamma'' IHa0 T;\n        generalize (sound_e1 eval_rec_proj typeof_rec_proj gamma'' WF_gamma'' IHa0 T).\n      intros; unfold inject; simpl.\n      rewrite wf_functor.\n      erewrite wf_np.\n      apply H1.\n      erewrite wf_np.\n      unfold inject in H2; simpl in H2; rewrite wf_functor in H2.\n      apply H2.\n      simpl; auto.\n      simpl; auto.\n      destruct IHa as [a_eqv IHa]; destruct IHb as [b_eqv IHb].\n      split; intros.\n      apply inject_i; econstructor 3; eauto.\n      assert (UP'_P2\n        (eval_alg_Soundness_P D V (E nat) WFV\n          _ WF_eqv_environment_P (E (typeofR D)) (Fun_E (typeofR D))\n          (gamma, gamma') typeof_rec eval_rec f_algebra f_algebra)\n        (proj1_sig a, proj1_sig a')).\n      unfold UP'_P2; intros.\n      econstructor.\n      instantiate (1 := conj (proj2_sig _) (proj2_sig _)).\n      apply IHa; auto.\n      assert (UP'_P2\n        (eval_alg_Soundness_P D V (E nat) WFV _ WF_eqv_environment_P\n          (E (typeofR D)) (Fun_E (typeofR D))\n          (gamma, gamma') typeof_rec eval_rec f_algebra f_algebra)\n        (proj1_sig b, proj1_sig b')).\n      unfold UP'_P2; intros.\n      econstructor.\n      instantiate (1 := conj (proj2_sig _) (proj2_sig _)).\n      apply IHb; auto.\n      generalize (proj1_eq (WF_Ind2 := WF_Ind_eval_Soundness_alg\n        (gamma, gamma'))\n      (np _ (exist _ (proj1_sig a, proj1_sig a') H0)\n        (exist _ (proj1_sig b, proj1_sig b') H1))).\n      generalize (proj2_eq (WF_Ind2 := WF_Ind_eval_Soundness_alg\n        (gamma, gamma'))\n      (np _ (exist _ (proj1_sig a, proj1_sig a') H0)\n        (exist _ (proj1_sig b, proj1_sig b') H1))).\n      simpl.\n      intros e1_eq e2_eq.\n      destruct (p_algebra (PAlgebra := eval_Soundness_alg_NP\n        (gamma, gamma') typeof_rec eval_rec)) as\n        [[e1 e2] [[UP_e1 UP_e2] sound_e1]]; auto; simpl in *|-*.\n      destruct e as [e e_UP]; destruct e' as [e' e'_UP]; simpl.\n      simpl in *|-*.\n      revert sound_e1.\n      unfold eval_alg_Soundness_P; simpl.\n      repeat rewrite e_eq, e'_eq, e1_eq, e2_eq; simpl.\n      intros sound_e1 eval_rec_proj typeof_rec_proj gamma'' WF_gamma'' IHa0 T;\n        generalize (sound_e1 eval_rec_proj typeof_rec_proj gamma'' WF_gamma'' IHa0  T); intros.\n      unfold inject; simpl.\n      rewrite wf_functor.\n      erewrite wf_np; try apply H2; simpl; auto.\n      erewrite wf_np; simpl; auto.\n      unfold inject in H3; simpl in H3; rewrite wf_functor in H3; apply H3.\n      destruct IHa as [a_eqv IHa]; destruct IHb as [b_eqv IHb]; destruct IHc as [c_eqv IHc].\n      split; intros.\n      apply inject_i; econstructor 4; eauto.\n      assert (UP'_P2\n        (eval_alg_Soundness_P D V (E nat) WFV _ WF_eqv_environment_P\n          (E (typeofR D)) (Fun_E (typeofR D))\n          (gamma, gamma') typeof_rec eval_rec f_algebra f_algebra)\n        (proj1_sig a, proj1_sig a')).\n      unfold UP'_P2; intros.\n      econstructor.\n      instantiate (1 := conj (proj2_sig _) (proj2_sig _)).\n      apply IHa; auto.\n      assert (UP'_P2\n        (eval_alg_Soundness_P D V (E nat) WFV _ WF_eqv_environment_P\n          (E (typeofR D)) (Fun_E (typeofR D))\n          (gamma, gamma')  typeof_rec eval_rec f_algebra f_algebra)\n        (proj1_sig b, proj1_sig b')).\n      unfold UP'_P2; intros.\n      econstructor.\n      instantiate (1 := conj (proj2_sig _) (proj2_sig _)).\n      apply IHb; auto.\n      assert (UP'_P2\n        (eval_alg_Soundness_P D V (E nat) WFV _ WF_eqv_environment_P\n          (E (typeofR D)) (Fun_E (typeofR D))\n          (gamma, gamma') typeof_rec eval_rec f_algebra f_algebra)\n        (proj1_sig c, proj1_sig c')).\n      unfold UP'_P2; intros.\n      econstructor.\n      instantiate (1 := conj (proj2_sig _) (proj2_sig _)).\n      apply IHc; auto.\n      generalize (proj1_eq (WF_Ind2 := WF_Ind_eval_Soundness_alg\n        (gamma, gamma'))\n        (np _ (exist _ (proj1_sig a, proj1_sig a') H0)\n          (exist _ (proj1_sig b, proj1_sig b') H1)\n          (exist _ (proj1_sig c, proj1_sig c') H2))).\n      generalize (proj2_eq (WF_Ind2 := WF_Ind_eval_Soundness_alg\n        (gamma, gamma'))\n        (np _ (exist _ (proj1_sig a, proj1_sig a') H0)\n          (exist _ (proj1_sig b, proj1_sig b') H1)\n          (exist _ (proj1_sig c, proj1_sig c') H2))).\n      simpl.\n      intros e1_eq e2_eq.\n      destruct (p_algebra (PAlgebra := eval_Soundness_alg_NP\n        (gamma, gamma') typeof_rec eval_rec)) as\n      [[e1 e2] [[UP_e1 UP_e2] sound_e1]]; auto; simpl in *|-*.\n      destruct e as [e e_UP]; destruct e' as [e' e'_UP]; simpl.\n      simpl in *|-*.\n      revert sound_e1.\n      unfold eval_alg_Soundness_P; simpl.\n      repeat rewrite e_eq, e'_eq, e1_eq, e2_eq; simpl.\n      intros sound_e1 eval_rec_proj typeof_rec_proj gamma'' WF_gamma'' IHa0 T;\n        generalize (sound_e1 eval_rec_proj typeof_rec_proj gamma'' WF_gamma'' IHa0 T); intros.\n      unfold inject; simpl.\n      rewrite wf_functor.\n      erewrite wf_np; try apply H3; simpl; auto.\n      erewrite wf_np; simpl; auto.\n      unfold inject in H4; simpl in H4; rewrite wf_functor in H4; apply H4.\n    Qed.\n\n    Context {eqv_eval_soundness_alg : forall typeof_rec eval_rec,\n      iPAlgebra eqv_eval_SoundnessName\n      (eqv_eval_alg_Soundness'_P\n        typeof_rec eval_rec\n        (f_algebra (FAlgebra := Typeof_E _))\n        (f_algebra (FAlgebra := eval_E _))) (EQV_E _ _)}.\n\n    Definition eqv_eval_soundness_P (i : eqv_i (typeofR D) nat) :=\n      forall (gamma'' : Env _)\n        (WF_gamma : forall n b, lookup (env_B _ _ i) n = Some b ->\n          exists T, lookup (env_A _ _ i) b = Some T)\n        (WF_gamma2 : List.length (env_A _ _ i) = List.length (env_B _ _ i))\n        (WF_gamma' : forall n b, lookup (env_B _ _ i) n = Some b -> b = n)\n        (WF_gamma'' : WF_Environment _ _ WFV gamma'' (env_A _ _ i)) T,\n        typeof _ _ (proj1_sig (eqv_a _ _ i)) = Some T ->\n        WFValueC _ _ WFV (eval (eval_E := eval_E)\n          V _ (proj1_sig (eqv_b _ _ i)) gamma'') T.\n\n    Variable (WF_MAlg_typeof : WF_MAlgebra Typeof_E).\n    Variable (WF_MAlg_eval : WF_MAlgebra eval_E).\n\n    Lemma eqv_eval_soundness' : forall gamma gamma' e' e'',\n      E_eqvC EQV_E gamma gamma' e' e'' ->\n      eqv_eval_soundness_P (mk_eqv_i _ _ gamma gamma' e' e'').\n    Proof.\n      intros; generalize (ifold_ (EQV_E _ _) _\n        (ip_algebra (iPAlgebra := eqv_eval_soundness_alg\n          (fun e => typeof D (E (typeofR D)) (proj1_sig e))\n          (fun e => eval V (E nat) (proj1_sig e)))) (mk_eqv_i _ _ gamma gamma' e' e'') H).\n      unfold eqv_eval_alg_Soundness'_P, eqv_eval_soundness_P; simpl;\n        intros.\n      revert H1.\n      destruct e' as [e' e'_UP]; destruct e'' as [e'' e''_UP];\n        simpl in *|-*.\n      rewrite <- (@in_out_UP'_inverse _ _ e'' _).\n      simpl; unfold typeof, eval, fold_, mfold, in_t.\n      rewrite wf_malgebra; unfold mfold.\n      unfold eval_alg_Soundness_P in H0.\n      intros; eapply H0; unfold WF_eqv_environment_P.\n      intro; rewrite (@in_out_UP'_inverse _ _ (proj1_sig e) (proj2_sig _)); reflexivity.\n      intro; rewrite (@in_out_UP'_inverse _ _ (proj1_sig e) (proj2_sig _)); reflexivity.\n      split; eauto.\n      intros; simpl; unfold eval, mfold, in_t.\n      rewrite wf_malgebra; eapply H2; eauto.\n      rewrite <- (@in_out_UP'_inverse _ _ (proj1_sig (fst a)) (proj2_sig _)) in H3.\n      simpl in H3; unfold typeof, mfold, in_t in H3.\n      rewrite <- wf_malgebra;  apply H3.\n      rewrite <- (@in_out_inverse _ _ e' _) in H1; unfold in_t in H1.\n      simpl; rewrite <- wf_malgebra.\n      simpl; unfold out_t_UP'.\n      rewrite Fusion with (g := (fmap in_t)).\n      apply H1.\n      auto.\n      intros; repeat rewrite fmap_fusion; reflexivity.\n    Qed.\n\n    Lemma eqv_eval_soundness : forall gamma gamma' e' e'',\n        E_eqvC EQV_E gamma gamma' e' e'' ->\n      forall (gamma'' : Env _)\n        (WF_gamma : forall n b, lookup (gamma') n = Some b ->\n          exists T, lookup (gamma) b = Some T)\n        (WF_gamma2 : List.length (gamma) = List.length (gamma'))\n        (WF_gamma' : forall n b, lookup (gamma') n = Some b -> b = n)\n        (WF_gamma'' : WF_Environment _ _ WFV gamma'' (gamma)) T,\n        typeof _ _ (proj1_sig e') = Some T ->\n        WFValueC _ _ WFV (eval (eval_E := eval_E)\n          V _ (proj1_sig (e'')) gamma'') T.\n    Proof.\n      intros; eapply eqv_eval_soundness'; eauto.\n    Qed.\n\n    Definition soundness_X'_P\n      (typeof_rec : Exp (E (typeofR D)) -> typeofR D)\n      (eval_rec : Exp (E nat) -> evalR V)\n      (typeof_F : Mixin (Exp (E (typeofR D))) (E (typeofR D)) (typeofR D))\n      (eval_F : Mixin (Exp (E nat)) (E nat) (evalR V))\n      i :=\n      forall (IH : forall (e : Exp _) (e' : Exp _)\n        pb gamma'' (WF_gamma'' : WF_eqv_environment_P pb gamma'')\n        T,\n        E_eqvC EQV_E (fst pb) (snd pb) e e' ->\n        typeof_rec e = Some T ->\n        WFValueC _ _ WFV (eval_rec (in_t_UP' _ _ (out_t_UP' _ _ (proj1_sig e'))) gamma'') T),\n      E_eqv EQV_E _ _ i /\\\n      eval_alg_Soundness_P D V (E nat) WFV\n      _ WF_eqv_environment_P\n      (E (typeofR D)) _ (env_A _ _ i, env_B _ _ i) typeof_rec eval_rec\n      typeof_F eval_F\n      (proj1_sig (eqv_a _ _ i), proj1_sig (eqv_b _ _ i))\n      (conj (proj2_sig (eqv_a _ _ i)) (proj2_sig (eqv_b _ _ i))).\n\n    Inductive soundness_XName : Set := soundness_Xname.\n\n    Global Instance Lift_soundness_X_alg\n      typeof_rec eval_rec typeof_alg eval_alg\n      EQV_G {fun_EQV_G : iFunctor EQV_G}\n      {EQV_G_EQV_Alg : iPAlgebra eqv_eval_SoundnessName\n        (eqv_eval_alg_Soundness'_P typeof_rec eval_rec typeof_alg eval_alg) EQV_G} :\n        iPAlgebra soundness_XName\n        (soundness_X'_P\n          typeof_rec eval_rec typeof_alg eval_alg) EQV_G.\n    Proof.\n      intros; econstructor; generalize (ip_algebra); unfold iAlgebra; intros.\n      unfold soundness_X'_P; intros.\n      assert (EQV_G (eqv_eval_alg_Soundness'_P typeof_rec eval_rec typeof_alg eval_alg) i).\n      eapply ifmap; try eapply H0.\n      intros; apply H1; apply IH.\n      apply (H _ H1).\n    Defined.\n\n    Context {soundness_X_alg : forall eval_rec,\n      iPAlgebra soundness_XName\n      (soundness_X'_P\n        (fun e => typeof _ _ (proj1_sig e)) eval_rec\n        (f_algebra (FAlgebra := Typeof_E _))\n        (f_algebra (FAlgebra := beval_E))) (EQV_E _ _)}.\n    Variable Sub_WFV_Bot_WFV : Sub_iFunctor (WFValue_Bot _ _) WFV.\n\n    Definition soundness_X_P (i : eqv_i (typeofR D) nat) :=\n      forall n (gamma'' : Env _)\n        (WF_gamma : forall n b, lookup (env_B _ _ i) n = Some b ->\n          exists T, lookup (env_A _ _ i) b = Some T)\n        (WF_gamma2 : List.length (env_A _ _ i) = List.length (env_B _ _ i))\n        (WF_gamma' : forall n b, lookup (env_B _ _ i) n = Some b -> b = n)\n        (WF_gamma'' : WF_Environment _ _ WFV gamma'' (env_A _ _ i)) T,\n        typeof _ _ (proj1_sig (eqv_a _ _ i)) = Some T ->\n        WFValueC _ _ WFV (beval V (E _) n (beval_E := beval_E)\n          (eqv_b _ _ i) gamma'') T.\n\n    Lemma soundness_X' :\n      forall eval_rec gamma gamma' e' e'',\n        E_eqvC EQV_E gamma gamma' e' e'' ->\n        soundness_X'_P (fun e => typeof _ _ (proj1_sig e)) eval_rec\n        (f_algebra (FAlgebra := Typeof_E _))\n        (f_algebra (FAlgebra := beval_E)) (mk_eqv_i _ _ gamma gamma' e' e'').\n    Proof.\n      intros; apply (ifold_ (EQV_E _ _ )); try assumption.\n      apply ip_algebra.\n    Qed.\n\n    Variable SV : (SubValue_i V -> Prop) -> SubValue_i V -> Prop.\n    Variable funSV : iFunctor SV.\n    Variable Sub_SV_Bot_SV : Sub_iFunctor (SubValue_Bot V) SV.\n    Variable Sub_SV_refl_SV : Sub_iFunctor (SubValue_refl V) SV.\n\n    Context {WF_Value_continous_alg :\n      iPAlgebra WFV_ContinuousName (WF_Value_continuous_P D V WFV) SV}.\n    Context {eval_continuous_Exp_E : PAlgebra EC_ExpName\n      (sig (UP'_P (eval_continuous_Exp_P V (E _) SV))) (E nat)}.\n    Context {WF_Ind_EC_Exp : WF_Ind eval_continuous_Exp_E}.\n\n    Lemma soundness_X :\n      forall n gamma gamma' gamma'' e' e'',\n        E_eqvC EQV_E gamma gamma' e' e'' ->\n        forall (WF_gamma : forall n b, lookup gamma' n = Some b ->\n          exists T, lookup gamma b = Some T)\n        (WF_gamma2 : List.length gamma = List.length gamma')\n        (WF_gamma' : forall n b, lookup gamma' n = Some b -> b = n)\n        (WF_gamma'' : WF_Environment _ _ WFV gamma'' gamma) T,\n        typeof _ _ (proj1_sig e') = Some T ->\n        WFValueC _ _ WFV (beval V (E _) n (beval_E := beval_E)\n          e'' gamma'') T.\n    Proof.\n      induction n; simpl;\n          intros; unfold beval; simpl in *|-*.\n      apply (inject_i (subGF := Sub_WFV_Bot_WFV)); econstructor; eauto.\n      generalize (soundness_X' (beval V (E _) n) _ _ _ _ H).\n      unfold soundness_X'_P;\n        unfold eval_alg_Soundness_P; simpl; intros.\n      apply H1; auto.\n      unfold beval; intros; erewrite bF_UP_in_out.\n      instantiate (1 := proj2_sig _).\n      destruct e'0; simpl; auto.\n      destruct WF_gamma''0 as [WF_pb [WF_pb2 [WF_pb' WF_gamma''0]]].\n      eapply IHn; eauto.\n      intro; destruct e; unfold beval; erewrite bF_UP_in_out;\n        auto.\n      intro; rewrite <- (@in_out_UP'_inverse _ _ (proj1_sig e) (proj2_sig _)) at 1;\n        reflexivity.\n      repeat split; auto.\n      intros.\n      destruct a as [[a a_UP'] [a' a'_UP']].\n      unfold beval; erewrite (@bF_UP_in_out _ _ _ _ _ _ _ a'_UP').\n      apply (WF_Value_beval D V (E _) SV _ _ _ _ WFV n (S n) _ gamma''0); auto.\n      apply Sub_Environment_refl; auto.\n      unfold beval; simpl.\n      simpl in H2.\n      unfold beval in H2; apply H2.\n      simpl in H3.\n      unfold typeof in H3.\n      rewrite <- (@in_out_UP'_inverse _ _ a a_UP') in H3.\n      simpl in H3; unfold typeof, mfold, in_t in H3.\n      rewrite <- wf_malgebra; apply H3.\n      rewrite <- wf_malgebra.\n      rewrite <- (@in_out_UP'_inverse _ _ _ (proj2_sig e')) in H0.\n      simpl in H0; unfold typeof, mfold, in_t in H0.\n      apply H0.\n    Qed.\n\n  End NP_beval_Soundness.\n\nEnd PNames.\n\n(*\n*** Local Variables: ***\n*** coq-prog-args: (\"-emacs-U\" \"-impredicative-set\") ***\n*** End: ***\n*)\n", "meta": {"author": "skeuchel", "repo": "mtc", "sha": "cf3c295664ce019fa370fc2dc73bd05eae94f64b", "save_path": "github-repos/coq/skeuchel-mtc", "path": "github-repos/coq/skeuchel-mtc/mtc-cf3c295664ce019fa370fc2dc73bd05eae94f64b/PNames.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2766969109607446}}
{"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\n(* Converted imports: *)\n\nRequire Control.Applicative.\nRequire Coq.Program.Basics.\nRequire Data.Foldable.\nRequire Data.Functor.\nRequire Data.Functor.Identity.\nRequire Data.Maybe.\nRequire Data.Monoid.\nRequire Data.OldList.\nRequire Data.Traversable.\nRequire Data.Tuple.\nRequire GHC.Base.\nRequire GHC.Num.\nRequire GHC.Prim.\nRequire GHC.Tuple.\nImport Data.Functor.Notations.\nImport GHC.Base.Notations.\nImport GHC.Num.Notations.\n\n(* Converted type declarations: *)\n\nInductive State s a : Type := Mk_State : (s -> (s * a)%type) -> State s a.\n\nInductive Split t a : Type := Mk_Split : t -> a -> t -> Split t a.\n\n(* Make nat instead of Int. *)\nRecord Sized__Dict a := Sized__Dict_Build {\n  size__ : a -> nat }.\n\nDefinition Sized a :=\n  forall r, (Sized__Dict a -> r) -> r.\n\nExisting Class Sized.\n\nDefinition size `{g : Sized a} : a -> nat :=\n  g _ (size__ a).\n\nInductive Place a : Type := Mk_Place : nat -> a -> Place a.\n\nInductive PQL e : Type := Nil : PQL e\n                       |  op_ZCza__ : (PQueue e) -> PQL e -> PQL e\nwith PQueue e : Type := Mk_PQueue : e -> (PQL e) -> PQueue e.\n\nInductive Node a : Type := Node2 : nat -> a -> a -> Node a\n                        |  Node3 : nat -> a -> a -> a -> Node a.\n\nInductive Maybe2 a b : Type := Nothing2 : Maybe2 a b\n                            |  Just2 : a -> b -> Maybe2 a b.\n\nInductive Elem a : Type := Mk_Elem : a -> Elem a.\n\nDefinition Digit23 :=\n  Node%type.\n\nInductive Digit12 a : Type := One12 : a -> Digit12 a\n                           |  Two12 : a -> a -> Digit12 a.\n\nInductive Thin a : Type := EmptyTh : Thin a\n                        |  SingleTh : a -> Thin a\n                        |  DeepTh : nat -> (Digit12 a) -> (Thin (Node a)) -> (Digit12 a) -> Thin\n                                    a.\n\nInductive Rigid a : Type := Mk_Rigid : nat -> (Digit23 a) -> (Thin (Node a)) -> (Digit23 a) -> Rigid a.\n\nInductive Rigidified a : Type := RigidEmpty : Rigidified a\n                              |  RigidOne : a -> Rigidified a\n                              |  RigidTwo : a -> a -> Rigidified a\n                              |  RigidThree : a -> a -> a -> Rigidified a\n                              |  RigidFull : (Rigid a) -> Rigidified a.\n\nInductive Digit a : Type := One : a -> Digit a\n                         |  Two : a -> a -> Digit a\n                         |  Three : a -> a -> a -> Digit a\n                         |  Four : a -> a -> a -> a -> Digit a.\n\nInductive FingerTree a : Type := Empty : FingerTree a\n                              |  Single : a -> FingerTree a\n                              |  Deep : nat -> (Digit a) -> (FingerTree (Node a)) -> (Digit a) -> FingerTree a.\n\nInductive Seq a : Type := Mk_Seq : (FingerTree (Elem a)) -> Seq a.\n\nInductive ViewL a : Type := EmptyL : ViewL a\n                         |  op_ZCzl__ : a -> Seq a -> ViewL a.\n\nInductive ViewR a : Type := EmptyR : ViewR a\n                         |  op_ZCzg__ : Seq a -> a -> ViewR a.\n\nArguments Mk_State {_} {_} _.\n\nArguments Mk_Split {_} {_} _ _ _.\n\nArguments Mk_Place {_} _ _.\n\nArguments Nil {_}.\n\nArguments op_ZCza__ {_} _ _.\n\nArguments Mk_PQueue {_} _ _.\n\nArguments Node2 {_} _ _ _.\n\nArguments Node3 {_} _ _ _ _.\n\nArguments Nothing2 {_} {_}.\n\nArguments Just2 {_} {_} _ _.\n\nArguments Mk_Elem {_} _.\n\nArguments One12 {_} _.\n\nArguments Two12 {_} _ _.\n\nArguments EmptyTh {_}.\n\nArguments SingleTh {_} _.\n\nArguments DeepTh {_} _ _ _ _.\n\nArguments Mk_Rigid {_} _ _ _ _.\n\nArguments RigidEmpty {_}.\n\nArguments RigidOne {_} _.\n\nArguments RigidTwo {_} _ _.\n\nArguments RigidThree {_} _ _ _.\n\nArguments RigidFull {_} _.\n\nArguments One {_} _.\n\nArguments Two {_} _ _.\n\nArguments Three {_} _ _ _.\n\nArguments Four {_} _ _ _ _.\n\nArguments Empty {_}.\n\nArguments Single {_} _.\n\nArguments Deep {_} _ _ _ _.\n\nArguments Mk_Seq {_} _.\n\nArguments EmptyL {_}.\n\nArguments op_ZCzl__ {_} _ _.\n\nArguments EmptyR {_}.\n\nArguments op_ZCzg__ {_} _ _.\n\nDefinition runState {s} {a} (arg_0__ : State s a) :=\n  match arg_0__ with\n    | Mk_State runState => runState\n  end.\n\nDefinition getElem {a} (arg_1__ : Elem a) :=\n  match arg_1__ with\n    | Mk_Elem getElem => getElem\n  end.\n(* Midamble *)\nRequire Import Omega.\n\n(*  ----------------------------------------------------------- *)\n\nRecord Foldable1__Dict (t : Type -> Type) := Foldable1__Dict_Build {\n  foldl1__ : forall {a}, (a -> a -> a) -> t a -> a  }.\n\nDefinition Foldable1 a :=\n  forall r, (Foldable1__Dict a -> r) -> r.\n\nExisting Class Foldable1.\n\nDefinition foldl1 `{g : Foldable1 t} : forall {a}, (a -> a -> a) -> t a -> a :=\n  g _ (foldl1__ t).\n\nDefinition Digit_foldl1 {a} (f : a -> a -> a) (t : Digit a) : a :=\n  match t with\n  | One x => x\n  | Two x y => f x y\n  | Three x y z => f (f x y) z\n  | Four x y z w => f (f (f x y) z) w\n  end.\n\nProgram Instance Foldable1_Digit : Foldable1 Digit := fun _ k =>\n  k {| foldl1__ := fun {a} => Digit_foldl1 |}.\n\n(*  ----------------------------------------------------------- *)\n\nInstance Unpeel_Elem a : GHC.Prim.Unpeel (Elem a) a :=\n  GHC.Prim.Build_Unpeel _ _ (fun x => match x with Mk_Elem y => y end) Mk_Elem.\n\n(*  ----------------------------------------------------------- *)\n\nLocal Definition Functor__Digit_fmap : forall {a} {b},\n                                         (a -> b) -> Digit a -> Digit b :=\n  fun {a} {b} =>\n    fun arg_0__ arg_1__ =>\n      match arg_0__ , arg_1__ with\n        | f , One a => One (f a)\n        | f , Two a b => Two (f a) (f b)\n        | f , Three a b c => Three (f a) (f b) (f c)\n        | f , Four a b c d => Four (f a) (f b) (f c) (f d)\n      end.\n\nLocal Definition Functor__Digit_op_zlzd__ : forall {a} {b},\n                                              a -> Digit b -> Digit a :=\n  fun {a} {b} => fun x => Functor__Digit_fmap (GHC.Base.const x).\n\nProgram Instance Functor__Digit : GHC.Base.Functor Digit := fun _ k =>\n    k {|GHC.Base.op_zlzd____ := fun {a} {b} => Functor__Digit_op_zlzd__ ;\n      GHC.Base.fmap__ := fun {a} {b} => Functor__Digit_fmap |}.\n\n(*  ----------------------------------------------------------- *)\n\nLocal Definition Sized__FingerTree_size {inst_a} `{Sized inst_a} : (FingerTree inst_a) -> nat :=\n  fun arg_0__ =>\n    match arg_0__ with\n      | Empty => 0\n      | Single x => size x\n      | Deep v _ _ _ => v\n    end.\n\nProgram Instance Sized__FingerTree {a} `{Sized a} : Sized (FingerTree a) :=\n  fun _ k => k {|size__ := Sized__FingerTree_size |}.\n\nLocal Definition Sized__Digit_size {inst_a} `{Sized inst_a} : (Digit inst_a) -> nat :=\n  foldl1 (fun x y => x + y)  GHC.Base.∘ GHC.Base.fmap size.\n\nProgram Instance Sized__Digit {a} `{Sized a} : Sized (Digit a) := fun _ k =>\n    k {|size__ := Sized__Digit_size |}.\n\nLocal Definition Sized__Node_size {inst_a} : (Node inst_a) -> nat :=\n  fun arg_0__ => match arg_0__ with | Node2 v _ _ => v | Node3 v _ _ _ => v end.\n\nProgram Instance Sized__Node {a} : Sized (Node a) := fun _ k =>\n    k {|size__ := Sized__Node_size |}.\n\nLocal Definition Sized__Elem_size {inst_a} : (Elem inst_a) -> nat :=\n  fun arg_0__ => 1.\n\nProgram Instance Sized__Elem {a} : Sized (Elem a) := fun _ k =>\n    k {|size__ := Sized__Elem_size |}.\n\n\n(*  ----------------------------------------------------------- *)\n\nNotation \"'_:<_'\" := (op_ZCzl__).\n\nInfix \":<\" := (_:<_) (at level 99).\n\nNotation \"'_:>_'\" := (op_ZCzg__).\n\nInfix \":>\" := (_:>_) (at level 99).\n\nNotation \"'_:&_'\" := (op_ZCza__).\n\nInfix \":&\" := (_:&_) (at level 99).\n\n\n(*  ----------------------------------------------------------- *)\n(* CHANGE to Default.panic *)\n\nParameter error : forall {a}, a.\n\n(* Move to base: missing record selectors *)\nDefinition runIdentity {a} (x: Data.Functor.Identity.Identity a) : a :=\n  match x with\n  | Data.Functor.Identity.Mk_Identity y => y\n  end.\n\nDefinition unwrapMonad {m}{a} (x: Control.Applicative.WrappedMonad m a) :=\n  match x with\n  | Control.Applicative.WrapMonad y => y\n  end.\n\n(*  ----------------------------------------------------------- *)\n\nDefinition map_elem {a} : list a -> list (Elem a) := fun xs => GHC.Prim.coerce xs.\n\nDefinition getNodes {a} : nat -> a -> list a -> (list (Node a) * Digit a)%type :=\n    fix getNodes arg_1__ arg_2__ arg_3__\n          := let j_9__ :=\n               match arg_1__ , arg_2__ , arg_3__ with\n                 | _ , x1 , nil => pair nil (One x1)\n                 | _ , x1 , cons x2 nil => pair nil (Two x1 x2)\n                 | _ , x1 , cons x2 (cons x3 nil) => pair nil (Three x1 x2 x3)\n                 | s , x1 , cons x2 (cons x3 (cons x4 xs)) =>\n                   match getNodes s x4 xs with\n                   | pair ns d => pair (cons (Node3 s x1 x2 x3) ns) d\n                   end\n               end in\n             match arg_1__ , arg_2__ , arg_3__ with\n             | arg , _ , _ => j_9__\n             end.\n\nLemma getNodes_length:\n  forall {a} s x (xs : list a),\n  length (fst (getNodes s x xs)) <= length xs.\nProof.\n  fix IH 4.\n  intros.\n  destruct xs as [|? xs]; simpl; auto.\n  destruct xs as [|? xs]; simpl; auto.\n  destruct xs as [|? xs]; simpl; auto.\n  specialize (IH _ s a2 xs).\n  destruct (getNodes _ _ _).\n  simpl in *.\n  omega.\nQed.\n\nProgram Fixpoint  mkTree {a} `{(Sized a)} (s:nat) (x : list a) {measure (length x)} : FingerTree a :=\n    match x with\n    | nil => Empty\n    | cons x1 nil => Single x1\n    | cons x1 (cons x2 nil) => Deep (2 * s) (One x1) Empty (One x2)\n    | cons x1 (cons x2 (cons x3 nil)) => Deep (3 * s) (One x1) Empty (Two x2 x3)\n    | cons x1 (cons x2 (cons x3 (cons x4 xs))) =>\n      match getNodes (3 * s) x4 xs with\n      | pair ns sf => match mkTree (3 * s) ns with\n                     | m => GHC.Prim.seq m (Deep (((3 * size x1)\n                                                    + size m)\n                                                   + size sf)\n                                                (Three x1 x2 x3) m sf)\n                     end\n      end\n    end.\nObligation 1.\n  clear mkTree.\n  pose proof (getNodes_length (s + (s + (s + 0))) x4 xs).\n  destruct (getNodes _ _ _). simpl in *. inversion_clear Heq_anonymous. omega.\nQed.\n\n\nDefinition fromList {a} : list a -> Seq a :=\n  Mk_Seq GHC.Base.∘ ((@mkTree (Elem a) _ 1) GHC.Base.∘ map_elem).\n\n(*  ----------------------------------------------------------- *)\n\nDefinition  mapWithIndexNode {a} {b} `{Sized a}\n                             : (nat -> a -> b) -> nat -> Node a -> Node b :=\n                             fun arg_2__ arg_3__ arg_4__ =>\n                               match arg_2__ , arg_3__ , arg_4__ with\n                                 | f , s , Node2 ns a b => let sPsa := s + size a in\n                                                           GHC.Prim.seq sPsa (Node2 ns (f s a) (f sPsa b))\n                                 | f , s , Node3 ns a b c => let sPsa := s + size a in\n                                                             let sPsab := sPsa + size b in\n                                                             GHC.Prim.seq sPsa (GHC.Prim.seq sPsab (Node3 ns (f s a) (f\n                                                                                                                     sPsa\n                                                                                                                     b)\n                                                                                             (f sPsab c)))\n                               end.\n\nDefinition  mapWithIndexDigit {a} {b} `{Sized a}\n  : (nat -> a -> b) -> nat -> Digit a -> Digit b :=\n  fun arg_11__ arg_12__ arg_13__ =>\n    match arg_11__ , arg_12__ , arg_13__ with\n    | f , s , One a => One (f s a)\n    | f , s , Two a b => let sPsa := s + size a in\n                        GHC.Prim.seq sPsa (Two (f s a) (f sPsa b))\n    | f , s , Three a b c => let sPsa := s + size a in\n                            let sPsab := sPsa + size b in\n                            GHC.Prim.seq sPsa (GHC.Prim.seq sPsab (Three (f s a) (f sPsa\n                                                                                    b) (f\n                                                                                          sPsab\n                                                                                          c)))\n    | f , s , Four a b c d => let sPsa := s + size a in\n                             let sPsab := sPsa + size b in\n                             let sPsabc := sPsab + size c in\n                             GHC.Prim.seq sPsa (GHC.Prim.seq sPsab (GHC.Prim.seq sPsabc\n                                                                                 (Four (f\n                                                                                          s\n                                                                                          a)\n                                                                                       (f sPsa\n                                                                                          b) (f\n                                                                                                sPsab\n                                                                                                c) (f\n                                                                                                      sPsabc\n                                                                                                      d))))\n    end.\n\n\nFixpoint mapWithIndexTree {a} {b} `{Sized a} (f : nat -> a -> b) (s : nat) (ft: FingerTree a) : FingerTree b :=\n  match ft with\n  | Empty => GHC.Prim.seq s Empty\n  | Single xs => Single GHC.Base.$ f s xs\n  | Deep n pr m sf =>\n    let sPsprm := (s + n) - size sf in\n    let sPspr := s + size pr in\n    GHC.Prim.seq sPspr (GHC.Prim.seq sPsprm\n                                     (Deep n  (mapWithIndexDigit\n                                                                              f s pr)\n                                                                           (mapWithIndexTree\n                                                                              (mapWithIndexNode\n                                                                                 f) sPspr m)\n                                                                           (mapWithIndexDigit\n                                                                              f sPsprm sf)))\n  end.\n\nDefinition mapWithIndex {a} {b} : (nat -> a -> b) -> Seq a -> Seq b :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__ , arg_1__ with\n      | f' , Mk_Seq xs' =>  Mk_Seq GHC.Base.$ mapWithIndexTree (fun arg_34__ arg_35__ =>\n                                                                match arg_34__ , arg_35__ with\n                                                                  | s , Mk_Elem a => Mk_Elem (f' s a)\n                                                                end) (id 0) xs'\n    end.\n\n(* ---------------------------------------- *)\n\n\n(* Converted value declarations: *)\n\n(* Translating `instance forall {a}, forall `{Control.DeepSeq.NFData a},\n   Control.DeepSeq.NFData (Data.Sequence.Seq a)' failed: OOPS! Cannot find\n   information for class Qualified \"Control.DeepSeq\" \"NFData\" unsupported *)\n\n(* Translating `instance GHC.Base.MonadPlus Data.Sequence.Seq' failed: OOPS!\n   Cannot find information for class Qualified \"GHC.Base\" \"MonadPlus\"\n   unsupported *)\n\n(* Translating `instance GHC.Base.Alternative Data.Sequence.Seq' failed: OOPS!\n   Cannot find information for class Qualified \"GHC.Base\" \"Alternative\"\n   unsupported *)\n\n(* Translating `instance forall {a}, forall `{GHC.Show.Show a}, GHC.Show.Show\n   (Data.Sequence.Seq a)' failed: OOPS! Cannot find information for class Qualified\n   \"GHC.Show\" \"Show\" unsupported *)\n\n(* Translating `instance forall {a}, forall `{GHC.Read.Read a}, GHC.Read.Read\n   (Data.Sequence.Seq a)' failed: OOPS! Cannot find information for class Qualified\n   \"GHC.Read\" \"Read\" unsupported *)\n\n(* Skipping instance Monoid__Seq *)\n\n(* Translating `instance forall {a}, Data.Semigroup.Semigroup (Data.Sequence.Seq\n   a)' failed: OOPS! Cannot find information for class Qualified \"Data.Semigroup\"\n   \"Semigroup\" unsupported *)\n\n(* Translating `instance forall {a}, forall `{Data.Data.Data a}, Data.Data.Data\n   (Data.Sequence.Seq a)' failed: OOPS! Cannot find information for class Qualified\n   \"Data.Data\" \"Data\" unsupported *)\n\n\n(* Translating `instance forall {a}, forall `{Control.DeepSeq.NFData a},\n   Control.DeepSeq.NFData (Data.Sequence.FingerTree a)' failed: OOPS! Cannot find\n   information for class Qualified \"Control.DeepSeq\" \"NFData\" unsupported *)\n\nLocal Definition Foldable__Digit_foldMap : forall {m} {a},\n                                             forall `{GHC.Base.Monoid m}, (a -> m) -> Digit a -> m :=\n  fun {m} {a} `{GHC.Base.Monoid m} =>\n    fun arg_0__ arg_1__ =>\n      match arg_0__ , arg_1__ with\n        | f , One a => f a\n        | f , Two a b => GHC.Base.mappend (f a) (f b)\n        | f , Three a b c => GHC.Base.mappend (f a) (GHC.Base.mappend (f b) (f c))\n        | f , Four a b c d => GHC.Base.mappend (f a) (GHC.Base.mappend (f b)\n                                                                       (GHC.Base.mappend (f c) (f d)))\n      end.\n\nLocal Definition Foldable__Digit_product : forall {a},\n                                             forall `{GHC.Num.Num a}, Digit a -> a :=\n  fun {a} `{GHC.Num.Num a} =>\n    Data.Foldable.hash_compose Data.Monoid.getProduct (Foldable__Digit_foldMap\n                               Data.Monoid.Mk_Product).\n\nLocal Definition Foldable__Digit_sum : forall {a},\n                                         forall `{GHC.Num.Num a}, Digit a -> a :=\n  fun {a} `{GHC.Num.Num a} =>\n    Data.Foldable.hash_compose Data.Monoid.getSum (Foldable__Digit_foldMap\n                               Data.Monoid.Mk_Sum).\n\nLocal Definition Foldable__Digit_fold : forall {m},\n                                          forall `{GHC.Base.Monoid m}, Digit m -> m :=\n  fun {m} `{GHC.Base.Monoid m} => Foldable__Digit_foldMap GHC.Base.id.\n\nLocal Definition Foldable__Digit_elem : forall {a},\n                                          forall `{GHC.Base.Eq_ a}, a -> Digit a -> bool :=\n  fun {a} `{GHC.Base.Eq_ a} =>\n    Coq.Program.Basics.compose (fun arg_69__ =>\n                                 match arg_69__ with\n                                   | p => Coq.Program.Basics.compose Data.Monoid.getAny (Foldable__Digit_foldMap\n                                                                     (Coq.Program.Basics.compose Data.Monoid.Mk_Any p))\n                                 end) _GHC.Base.==_.\n\nLocal Definition Foldable__Digit_foldl : forall {b} {a},\n                                           (b -> a -> b) -> b -> Digit a -> b :=\n  fun {b} {a} =>\n    fun arg_0__ arg_1__ arg_2__ =>\n      match arg_0__ , arg_1__ , arg_2__ with\n        | f , z , One a => f z a\n        | f , z , Two a b => f (f z a) b\n        | f , z , Three a b c => f (f (f z a) b) c\n        | f , z , Four a b c d => f (f (f (f z a) b) c) d\n      end.\n\nLocal Definition Foldable__Digit_foldr' : forall {a} {b},\n                                            (a -> b -> b) -> b -> Digit a -> b :=\n  fun {a} {b} =>\n    fun arg_9__ arg_10__ arg_11__ =>\n      match arg_9__ , arg_10__ , arg_11__ with\n        | f , z0 , xs => let f' :=\n                           fun arg_12__ arg_13__ arg_14__ =>\n                             match arg_12__ , arg_13__ , arg_14__ with\n                               | k , x , z => _GHC.Base.$!_ k (f x z)\n                             end in\n                         Foldable__Digit_foldl f' GHC.Base.id xs z0\n      end.\n\nLocal Definition Foldable__Digit_foldr : forall {a} {b},\n                                           (a -> b -> b) -> b -> Digit a -> b :=\n  fun {a} {b} =>\n    fun arg_0__ arg_1__ arg_2__ =>\n      match arg_0__ , arg_1__ , arg_2__ with\n        | f , z , One a => f a z\n        | f , z , Two a b => f a (f b z)\n        | f , z , Three a b c => f a (f b (f c z))\n        | f , z , Four a b c d => f a (f b (f c (f d z)))\n      end.\n\nLocal Definition Foldable__Digit_null : forall {a}, Digit a -> bool :=\n  fun {a} => Foldable__Digit_foldr (fun arg_61__ arg_62__ => false) true.\n\nLocal Definition Foldable__Digit_toList : forall {a}, Digit a -> list a :=\n  fun {a} =>\n    fun arg_54__ =>\n      match arg_54__ with\n        | t => GHC.Base.build (fun arg_55__ arg_56__ =>\n                                match arg_55__ , arg_56__ with\n                                  | c , n => Foldable__Digit_foldr c n t\n                                end)\n      end.\n\nLocal Definition Foldable__Digit_foldl' : forall {b} {a},\n                                            (b -> a -> b) -> b -> Digit a -> b :=\n  fun {b} {a} =>\n    fun arg_24__ arg_25__ arg_26__ =>\n      match arg_24__ , arg_25__ , arg_26__ with\n        | f , z0 , xs => let f' :=\n                           fun arg_27__ arg_28__ arg_29__ =>\n                             match arg_27__ , arg_28__ , arg_29__ with\n                               | x , k , z => _GHC.Base.$!_ k (f z x)\n                             end in\n                         Foldable__Digit_foldr f' GHC.Base.id xs z0\n      end.\n\n\nLocal Definition Foldable__Digit_length : forall {a}, Digit a -> GHC.Num.Int :=\n  fun {a} d =>\n    Z.of_nat (Foldable__Digit_foldl' (fun arg_64__ arg_65__ =>\n                             match arg_64__ , arg_65__ with\n                               | c , _ => c + (id 1)\n                             end) (id 0) d).\n\nProgram Instance Foldable__Digit : Data.Foldable.Foldable Digit := fun _ k =>\n    k {|Data.Foldable.elem__ := fun {a} `{GHC.Base.Eq_ a} => Foldable__Digit_elem ;\n      Data.Foldable.fold__ := fun {m} `{GHC.Base.Monoid m} => Foldable__Digit_fold ;\n      Data.Foldable.foldMap__ := fun {m} {a} `{GHC.Base.Monoid m} =>\n        Foldable__Digit_foldMap ;\n      Data.Foldable.foldl__ := fun {b} {a} => Foldable__Digit_foldl ;\n      Data.Foldable.foldl'__ := fun {b} {a} => Foldable__Digit_foldl' ;\n      Data.Foldable.foldr__ := fun {a} {b} => Foldable__Digit_foldr ;\n      Data.Foldable.foldr'__ := fun {a} {b} => Foldable__Digit_foldr' ;\n      Data.Foldable.length__ := fun {a} => Foldable__Digit_length ;\n      Data.Foldable.null__ := fun {a} => Foldable__Digit_null ;\n      Data.Foldable.product__ := fun {a} `{GHC.Num.Num a} => Foldable__Digit_product ;\n      Data.Foldable.sum__ := fun {a} `{GHC.Num.Num a} => Foldable__Digit_sum ;\n      Data.Foldable.toList__ := fun {a} => Foldable__Digit_toList |}.\n\n\nLocal Definition Traversable__Digit_traverse : forall {f} {a} {b},\n                                                 forall `{GHC.Base.Applicative f},\n                                                   (a -> f b) -> Digit a -> f (Digit b) :=\n  fun {f} {a} {b} `{GHC.Base.Applicative f} =>\n    fun arg_0__ arg_1__ =>\n      match arg_0__ , arg_1__ with\n        | f , One a => One Data.Functor.<$> f a\n        | f , Two a b => (Two Data.Functor.<$> f a) GHC.Base.<*> f b\n        | f , Three a b c => ((Three Data.Functor.<$> f a) GHC.Base.<*> f b)\n                             GHC.Base.<*> f c\n        | f , Four a b c d => (((Four Data.Functor.<$> f a) GHC.Base.<*> f b)\n                              GHC.Base.<*> f c) GHC.Base.<*> f d\n      end.\n\nLocal Definition Traversable__Digit_sequenceA : forall {f} {a},\n                                                  forall `{GHC.Base.Applicative f}, Digit (f a) -> f (Digit a) :=\n  fun {f} {a} `{GHC.Base.Applicative f} =>\n    Traversable__Digit_traverse GHC.Base.id.\n\nLocal Definition Traversable__Digit_sequence : forall {m} {a},\n                                                 forall `{GHC.Base.Monad m}, Digit (m a) -> m (Digit a) :=\n  fun {m} {a} `{GHC.Base.Monad m} => Traversable__Digit_sequenceA.\n\nLocal Definition Traversable__Digit_mapM : forall {m} {a} {b},\n                                             forall `{GHC.Base.Monad m}, (a -> m b) -> Digit a -> m (Digit b) :=\n  fun {m} {a} {b} `{GHC.Base.Monad m} => Traversable__Digit_traverse.\n\nProgram Instance Traversable__Digit : Data.Traversable.Traversable Digit :=\n  fun _ k =>\n    k {|Data.Traversable.mapM__ := fun {m} {a} {b} `{GHC.Base.Monad m} =>\n        Traversable__Digit_mapM ;\n      Data.Traversable.sequence__ := fun {m} {a} `{GHC.Base.Monad m} =>\n        Traversable__Digit_sequence ;\n      Data.Traversable.sequenceA__ := fun {f} {a} `{GHC.Base.Applicative f} =>\n        Traversable__Digit_sequenceA ;\n      Data.Traversable.traverse__ := fun {f} {a} {b} `{GHC.Base.Applicative f} =>\n        Traversable__Digit_traverse |}.\n\n(* Translating `instance forall {a}, forall `{Control.DeepSeq.NFData a},\n   Control.DeepSeq.NFData (Data.Sequence.Digit a)' failed: OOPS! Cannot find\n   information for class Qualified \"Control.DeepSeq\" \"NFData\" unsupported *)\n\n\nLocal Definition Foldable__Node_foldMap : forall {m} {a},\n                                            forall `{GHC.Base.Monoid m}, (a -> m) -> Node a -> m :=\n  fun {m} {a} `{GHC.Base.Monoid m} =>\n    fun arg_0__ arg_1__ =>\n      match arg_0__ , arg_1__ with\n        | f , Node2 _ a b => GHC.Base.mappend (f a) (f b)\n        | f , Node3 _ a b c => GHC.Base.mappend (f a) (GHC.Base.mappend (f b) (f c))\n      end.\n\nLocal Definition Foldable__Node_product : forall {a},\n                                            forall `{GHC.Num.Num a}, Node a -> a :=\n  fun {a} `{GHC.Num.Num a} =>\n    Data.Foldable.hash_compose Data.Monoid.getProduct (Foldable__Node_foldMap\n                               Data.Monoid.Mk_Product).\n\nLocal Definition Foldable__Node_sum : forall {a},\n                                        forall `{GHC.Num.Num a}, Node a -> a :=\n  fun {a} `{GHC.Num.Num a} =>\n    Data.Foldable.hash_compose Data.Monoid.getSum (Foldable__Node_foldMap\n                               Data.Monoid.Mk_Sum).\n\nLocal Definition Foldable__Node_fold : forall {m},\n                                         forall `{GHC.Base.Monoid m}, Node m -> m :=\n  fun {m} `{GHC.Base.Monoid m} => Foldable__Node_foldMap GHC.Base.id.\n\nLocal Definition Foldable__Node_elem : forall {a},\n                                         forall `{GHC.Base.Eq_ a}, a -> Node a -> bool :=\n  fun {a} `{GHC.Base.Eq_ a} =>\n    Coq.Program.Basics.compose (fun arg_69__ =>\n                                 match arg_69__ with\n                                   | p => Coq.Program.Basics.compose Data.Monoid.getAny (Foldable__Node_foldMap\n                                                                     (Coq.Program.Basics.compose Data.Monoid.Mk_Any p))\n                                 end) _GHC.Base.==_.\n\nLocal Definition Foldable__Node_foldl : forall {b} {a},\n                                          (b -> a -> b) -> b -> Node a -> b :=\n  fun {b} {a} =>\n    fun arg_0__ arg_1__ arg_2__ =>\n      match arg_0__ , arg_1__ , arg_2__ with\n        | f , z , Node2 _ a b => f (f z a) b\n        | f , z , Node3 _ a b c => f (f (f z a) b) c\n      end.\n\nLocal Definition Foldable__Node_foldr' : forall {a} {b},\n                                           (a -> b -> b) -> b -> Node a -> b :=\n  fun {a} {b} =>\n    fun arg_9__ arg_10__ arg_11__ =>\n      match arg_9__ , arg_10__ , arg_11__ with\n        | f , z0 , xs => let f' :=\n                           fun arg_12__ arg_13__ arg_14__ =>\n                             match arg_12__ , arg_13__ , arg_14__ with\n                               | k , x , z => _GHC.Base.$!_ k (f x z)\n                             end in\n                         Foldable__Node_foldl f' GHC.Base.id xs z0\n      end.\n\nLocal Definition Foldable__Node_foldr : forall {a} {b},\n                                          (a -> b -> b) -> b -> Node a -> b :=\n  fun {a} {b} =>\n    fun arg_0__ arg_1__ arg_2__ =>\n      match arg_0__ , arg_1__ , arg_2__ with\n        | f , z , Node2 _ a b => f a (f b z)\n        | f , z , Node3 _ a b c => f a (f b (f c z))\n      end.\n\nLocal Definition Foldable__Node_null : forall {a}, Node a -> bool :=\n  fun {a} => Foldable__Node_foldr (fun arg_61__ arg_62__ => false) true.\n\nLocal Definition Foldable__Node_toList : forall {a}, Node a -> list a :=\n  fun {a} =>\n    fun arg_54__ =>\n      match arg_54__ with\n        | t => GHC.Base.build (fun arg_55__ arg_56__ =>\n                                match arg_55__ , arg_56__ with\n                                  | c , n => Foldable__Node_foldr c n t\n                                end)\n      end.\n\nLocal Definition Foldable__Node_foldl' : forall {b} {a},\n                                           (b -> a -> b) -> b -> Node a -> b :=\n  fun {b} {a} =>\n    fun arg_24__ arg_25__ arg_26__ =>\n      match arg_24__ , arg_25__ , arg_26__ with\n        | f , z0 , xs => let f' :=\n                           fun arg_27__ arg_28__ arg_29__ =>\n                             match arg_27__ , arg_28__ , arg_29__ with\n                               | x , k , z => _GHC.Base.$!_ k (f z x)\n                             end in\n                         Foldable__Node_foldr f' GHC.Base.id xs z0\n      end.\n\nLocal Definition Foldable__Node_length : forall {a}, Node a -> GHC.Num.Int :=\n  fun {a} n =>\n    Z.of_nat (Foldable__Node_foldl' (fun arg_64__ arg_65__ =>\n                            match arg_64__ , arg_65__ with\n                              | c , _ => c + 1\n                            end) 0 n).\n\nProgram Instance Foldable__Node : Data.Foldable.Foldable Node := fun _ k =>\n    k {|Data.Foldable.elem__ := fun {a} `{GHC.Base.Eq_ a} => Foldable__Node_elem ;\n      Data.Foldable.fold__ := fun {m} `{GHC.Base.Monoid m} => Foldable__Node_fold ;\n      Data.Foldable.foldMap__ := fun {m} {a} `{GHC.Base.Monoid m} =>\n        Foldable__Node_foldMap ;\n      Data.Foldable.foldl__ := fun {b} {a} => Foldable__Node_foldl ;\n      Data.Foldable.foldl'__ := fun {b} {a} => Foldable__Node_foldl' ;\n      Data.Foldable.foldr__ := fun {a} {b} => Foldable__Node_foldr ;\n      Data.Foldable.foldr'__ := fun {a} {b} => Foldable__Node_foldr' ;\n      Data.Foldable.length__ := fun {a} => Foldable__Node_length ;\n      Data.Foldable.null__ := fun {a} => Foldable__Node_null ;\n      Data.Foldable.product__ := fun {a} `{GHC.Num.Num a} => Foldable__Node_product ;\n      Data.Foldable.sum__ := fun {a} `{GHC.Num.Num a} => Foldable__Node_sum ;\n      Data.Foldable.toList__ := fun {a} => Foldable__Node_toList |}.\n\nFixpoint Foldable__FingerTree_foldMap {m} {a} `{_ : GHC.Base.Monoid m} (f\n                                        : a -> m) (t : FingerTree a) : m\n           := match t with\n                | Empty => GHC.Base.mempty\n                | Single x => f x\n                | Deep _ pr m sf => GHC.Base.mappend (Data.Foldable.foldMap f pr)\n                                                     (GHC.Base.mappend (Foldable__FingerTree_foldMap\n                                                                       (Data.Foldable.foldMap f) m)\n                                                                       (Data.Foldable.foldMap f sf))\n              end.\n\nFixpoint Foldable__FingerTree_foldl {b} {a} (f : b -> a -> b) (z : b) (t\n                                      : FingerTree a) : b\n           := match t with\n                | Empty => z\n                | Single x => f z x\n                | Deep _ pr m sf => Data.Foldable.foldl f (Foldable__FingerTree_foldl\n                                                        (Data.Foldable.foldl f) (Data.Foldable.foldl f z pr) m) sf\n              end.\n\nFixpoint Foldable__FingerTree_foldr {a} {b} (f : a -> b -> b) (z : b) (t\n                                      : FingerTree a) : b\n           := match t with\n                | Empty => z\n                | Single x => f x z\n                | Deep _ pr m sf => Data.Foldable.foldr f (Foldable__FingerTree_foldr\n                                                        (GHC.Base.flip (Data.Foldable.foldr f)) (Data.Foldable.foldr f z\n                                                                                                                     sf)\n                                                        m) pr\n              end.\n\nLocal Definition Foldable__FingerTree_null : forall {a}, FingerTree a -> bool :=\n  fun {a} => Foldable__FingerTree_foldr (fun arg_61__ arg_62__ => false) true.\n\nLocal Definition Foldable__FingerTree_toList : forall {a},\n                                                 FingerTree a -> list a :=\n  fun {a} =>\n    fun arg_54__ =>\n      match arg_54__ with\n        | t => GHC.Base.build (fun arg_55__ arg_56__ =>\n                                match arg_55__ , arg_56__ with\n                                  | c , n => Foldable__FingerTree_foldr c n t\n                                end)\n      end.\n\nLocal Definition Foldable__FingerTree_foldl' : forall {b} {a},\n                                                 (b -> a -> b) -> b -> FingerTree a -> b :=\n  fun {b} {a} =>\n    fun arg_24__ arg_25__ arg_26__ =>\n      match arg_24__ , arg_25__ , arg_26__ with\n        | f , z0 , xs => let f' :=\n                           fun arg_27__ arg_28__ arg_29__ =>\n                             match arg_27__ , arg_28__ , arg_29__ with\n                               | x , k , z => _GHC.Base.$!_ k (f z x)\n                             end in\n                         Foldable__FingerTree_foldr f' GHC.Base.id xs z0\n      end.\n\nLocal Definition Foldable__FingerTree_length : forall {a},\n                                                 FingerTree a -> GHC.Num.Int :=\n  fun {a} t =>\n    Z.of_nat (Foldable__FingerTree_foldl' (fun arg_64__ arg_65__ =>\n                                  match arg_64__ , arg_65__ with\n                                    | c , _ => c + 1\n                                  end) 0 t).\n\nLocal Definition Foldable__FingerTree_foldr' : forall {a} {b},\n                                                 (a -> b -> b) -> b -> FingerTree a -> b :=\n  fun {a} {b} =>\n    fun arg_9__ arg_10__ arg_11__ =>\n      match arg_9__ , arg_10__ , arg_11__ with\n        | f , z0 , xs => let f' :=\n                           fun arg_12__ arg_13__ arg_14__ =>\n                             match arg_12__ , arg_13__ , arg_14__ with\n                               | k , x , z => _GHC.Base.$!_ k (f x z)\n                             end in\n                         Foldable__FingerTree_foldl f' GHC.Base.id xs z0\n      end.\n\nLocal Definition Foldable__FingerTree_product : forall {a},\n                                                  forall `{GHC.Num.Num a}, FingerTree a -> a :=\n  fun {a} `{GHC.Num.Num a} =>\n    Data.Foldable.hash_compose Data.Monoid.getProduct (Foldable__FingerTree_foldMap\n                               Data.Monoid.Mk_Product).\n\nLocal Definition Foldable__FingerTree_sum : forall {a},\n                                              forall `{GHC.Num.Num a}, FingerTree a -> a :=\n  fun {a} `{GHC.Num.Num a} =>\n    Data.Foldable.hash_compose Data.Monoid.getSum (Foldable__FingerTree_foldMap\n                               Data.Monoid.Mk_Sum).\n\nLocal Definition Foldable__FingerTree_fold : forall {m},\n                                               forall `{GHC.Base.Monoid m}, FingerTree m -> m :=\n  fun {m} `{GHC.Base.Monoid m} => Foldable__FingerTree_foldMap GHC.Base.id.\n\nLocal Definition Foldable__FingerTree_elem : forall {a},\n                                               forall `{GHC.Base.Eq_ a}, a -> FingerTree a -> bool :=\n  fun {a} `{GHC.Base.Eq_ a} =>\n    Coq.Program.Basics.compose (fun arg_69__ =>\n                                 match arg_69__ with\n                                   | p => Coq.Program.Basics.compose Data.Monoid.getAny\n                                                                     (Foldable__FingerTree_foldMap\n                                                                     (Coq.Program.Basics.compose Data.Monoid.Mk_Any p))\n                                 end) _GHC.Base.==_.\n\nLocal Definition Functor__Node_fmap : forall {a} {b},\n                                        (a -> b) -> Node a -> Node b :=\n  fun {a} {b} =>\n    fun arg_0__ arg_1__ =>\n      match arg_0__ , arg_1__ with\n        | f , Node2 v a b => Node2 v (f a) (f b)\n        | f , Node3 v a b c => Node3 v (f a) (f b) (f c)\n      end.\n\nLocal Definition Functor__Node_op_zlzd__ : forall {a} {b},\n                                             a -> Node b -> Node a :=\n  fun {a} {b} => fun x => Functor__Node_fmap (GHC.Base.const x).\n\nProgram Instance Functor__Node : GHC.Base.Functor Node := fun _ k =>\n    k {|GHC.Base.op_zlzd____ := fun {a} {b} => Functor__Node_op_zlzd__ ;\n      GHC.Base.fmap__ := fun {a} {b} => Functor__Node_fmap |}.\n\nFixpoint Functor__FingerTree_fmap {a} {b} (f : a -> b) (t : FingerTree a)\n           : FingerTree b\n           := match t with\n                | Empty => Empty\n                | Single x => Single (f x)\n                | Deep v pr m sf => Deep v (GHC.Base.fmap f pr) (Functor__FingerTree_fmap\n                                         (GHC.Base.fmap f) m) (GHC.Base.fmap f sf)\n              end.\n\nLocal Definition Functor__FingerTree_op_zlzd__ : forall {a} {b},\n                                                   a -> FingerTree b -> FingerTree a :=\n  fun {a} {b} => fun x => Functor__FingerTree_fmap (GHC.Base.const x).\n\nProgram Instance Functor__FingerTree : GHC.Base.Functor FingerTree := fun _ k =>\n    k {|GHC.Base.op_zlzd____ := fun {a} {b} => Functor__FingerTree_op_zlzd__ ;\n      GHC.Base.fmap__ := fun {a} {b} => Functor__FingerTree_fmap |}.\n\nLocal Definition Traversable__Node_traverse : forall {f} {a} {b},\n                                                forall `{GHC.Base.Applicative f}, (a -> f b) -> Node a -> f (Node b) :=\n  fun {f} {a} {b} `{GHC.Base.Applicative f} =>\n    fun arg_0__ arg_1__ =>\n      match arg_0__ , arg_1__ with\n        | f , Node2 v a b => (Node2 v Data.Functor.<$> f a) GHC.Base.<*> f b\n        | f , Node3 v a b c => ((Node3 v Data.Functor.<$> f a) GHC.Base.<*> f b)\n                               GHC.Base.<*> f c\n      end.\n\nLocal Definition Traversable__Node_sequenceA : forall {f} {a},\n                                                 forall `{GHC.Base.Applicative f}, Node (f a) -> f (Node a) :=\n  fun {f} {a} `{GHC.Base.Applicative f} => Traversable__Node_traverse GHC.Base.id.\n\nLocal Definition Traversable__Node_sequence : forall {m} {a},\n                                                forall `{GHC.Base.Monad m}, Node (m a) -> m (Node a) :=\n  fun {m} {a} `{GHC.Base.Monad m} => Traversable__Node_sequenceA.\n\nLocal Definition Traversable__Node_mapM : forall {m} {a} {b},\n                                            forall `{GHC.Base.Monad m}, (a -> m b) -> Node a -> m (Node b) :=\n  fun {m} {a} {b} `{GHC.Base.Monad m} => Traversable__Node_traverse.\n\nProgram Instance Traversable__Node : Data.Traversable.Traversable Node := fun _\n                                                                              k =>\n    k {|Data.Traversable.mapM__ := fun {m} {a} {b} `{GHC.Base.Monad m} =>\n        Traversable__Node_mapM ;\n      Data.Traversable.sequence__ := fun {m} {a} `{GHC.Base.Monad m} =>\n        Traversable__Node_sequence ;\n      Data.Traversable.sequenceA__ := fun {f} {a} `{GHC.Base.Applicative f} =>\n        Traversable__Node_sequenceA ;\n      Data.Traversable.traverse__ := fun {f} {a} {b} `{GHC.Base.Applicative f} =>\n        Traversable__Node_traverse |}.\n\nFixpoint Traversable__FingerTree_traverse {t : Type -> Type} {a} {b} `{_\n                                            : GHC.Base.Applicative t} (f : a -> t b) (ft : FingerTree a) : t (FingerTree\n                                                                                                             b)\n           := match ft with\n                | Empty => GHC.Base.pure Empty\n                | Single x => GHC.Base.fmap Single (f x)\n                | Deep v pr m sf => _GHC.Base.<*>_ (_GHC.Base.<*>_ (GHC.Base.fmap (Deep v)\n                                                                                  (Data.Traversable.traverse f pr))\n                                                                   (Traversable__FingerTree_traverse\n                                                                   (Data.Traversable.traverse f) m))\n                                                   (Data.Traversable.traverse f sf)\n              end.\n\nLocal Definition Traversable__FingerTree_sequenceA : forall {f} {a},\n                                                       forall `{GHC.Base.Applicative f},\n                                                         FingerTree (f a) -> f (FingerTree a) :=\n  fun {f} {a} `{GHC.Base.Applicative f} =>\n    Traversable__FingerTree_traverse GHC.Base.id.\n\nLocal Definition Traversable__FingerTree_sequence : forall {m} {a},\n                                                      forall `{GHC.Base.Monad m},\n                                                        FingerTree (m a) -> m (FingerTree a) :=\n  fun {m} {a} `{GHC.Base.Monad m} => Traversable__FingerTree_sequenceA.\n\nLocal Definition Traversable__FingerTree_mapM : forall {m} {a} {b},\n                                                  forall `{GHC.Base.Monad m},\n                                                    (a -> m b) -> FingerTree a -> m (FingerTree b) :=\n  fun {m} {a} {b} `{GHC.Base.Monad m} => Traversable__FingerTree_traverse.\n\n(* Translating `instance forall {a}, forall `{Control.DeepSeq.NFData a},\n   Control.DeepSeq.NFData (Data.Sequence.Node a)' failed: OOPS! Cannot find\n   information for class Qualified \"Control.DeepSeq\" \"NFData\" unsupported *)\n\n\nLocal Definition Functor__Elem_fmap : forall {a} {b},\n                                        (a -> b) -> Elem a -> Elem b :=\n  fun {a} {b} => GHC.Prim.coerce.\n\nLocal Definition Functor__Elem_op_zlzd__ : forall {a} {b},\n                                             a -> Elem b -> Elem a :=\n  fun {a} {b} => fun x => Functor__Elem_fmap (GHC.Base.const x).\n\nProgram Instance Functor__Elem : GHC.Base.Functor Elem := fun _ k =>\n    k {|GHC.Base.op_zlzd____ := fun {a} {b} => Functor__Elem_op_zlzd__ ;\n      GHC.Base.fmap__ := fun {a} {b} => Functor__Elem_fmap |}.\n\nLocal Definition Foldable__Elem_foldMap : forall {m} {a},\n                                            forall `{GHC.Base.Monoid m}, (a -> m) -> Elem a -> m :=\n  fun {m} {a} `{GHC.Base.Monoid m} =>\n    fun arg_0__ arg_1__ => match arg_0__ , arg_1__ with | f , Mk_Elem x => f x end.\n\nLocal Definition Foldable__Elem_product : forall {a},\n                                            forall `{GHC.Num.Num a}, Elem a -> a :=\n  fun {a} `{GHC.Num.Num a} =>\n    Data.Foldable.hash_compose Data.Monoid.getProduct (Foldable__Elem_foldMap\n                               Data.Monoid.Mk_Product).\n\nLocal Definition Foldable__Elem_sum : forall {a},\n                                        forall `{GHC.Num.Num a}, Elem a -> a :=\n  fun {a} `{GHC.Num.Num a} =>\n    Data.Foldable.hash_compose Data.Monoid.getSum (Foldable__Elem_foldMap\n                               Data.Monoid.Mk_Sum).\n\nLocal Definition Foldable__Elem_fold : forall {m},\n                                         forall `{GHC.Base.Monoid m}, Elem m -> m :=\n  fun {m} `{GHC.Base.Monoid m} => Foldable__Elem_foldMap GHC.Base.id.\n\nLocal Definition Foldable__Elem_elem : forall {a},\n                                         forall `{GHC.Base.Eq_ a}, a -> Elem a -> bool :=\n  fun {a} `{GHC.Base.Eq_ a} =>\n    Coq.Program.Basics.compose (fun arg_69__ =>\n                                 match arg_69__ with\n                                   | p => Coq.Program.Basics.compose Data.Monoid.getAny (Foldable__Elem_foldMap\n                                                                     (Coq.Program.Basics.compose Data.Monoid.Mk_Any p))\n                                 end) _GHC.Base.==_.\n\nLocal Definition Foldable__Elem_foldl : forall {b} {a},\n                                          (b -> a -> b) -> b -> Elem a -> b :=\n  fun {b} {a} =>\n    fun arg_0__ arg_1__ arg_2__ =>\n      match arg_0__ , arg_1__ , arg_2__ with\n        | f , z , Mk_Elem x => f z x\n      end.\n\nLocal Definition Foldable__Elem_foldr' : forall {a} {b},\n                                           (a -> b -> b) -> b -> Elem a -> b :=\n  fun {a} {b} =>\n    fun arg_9__ arg_10__ arg_11__ =>\n      match arg_9__ , arg_10__ , arg_11__ with\n        | f , z0 , xs => let f' :=\n                           fun arg_12__ arg_13__ arg_14__ =>\n                             match arg_12__ , arg_13__ , arg_14__ with\n                               | k , x , z => _GHC.Base.$!_ k (f x z)\n                             end in\n                         Foldable__Elem_foldl f' GHC.Base.id xs z0\n      end.\n\nLocal Definition Foldable__Elem_foldr : forall {a} {b},\n                                          (a -> b -> b) -> b -> Elem a -> b :=\n  fun {a} {b} =>\n    fun arg_0__ arg_1__ arg_2__ =>\n      match arg_0__ , arg_1__ , arg_2__ with\n        | f , z , Mk_Elem x => f x z\n      end.\n\nLocal Definition Foldable__Elem_null : forall {a}, Elem a -> bool :=\n  fun {a} => Foldable__Elem_foldr (fun arg_61__ arg_62__ => false) true.\n\nLocal Definition Foldable__Elem_toList : forall {a}, Elem a -> list a :=\n  fun {a} =>\n    fun arg_54__ =>\n      match arg_54__ with\n        | t => GHC.Base.build (fun arg_55__ arg_56__ =>\n                                match arg_55__ , arg_56__ with\n                                  | c , n => Foldable__Elem_foldr c n t\n                                end)\n      end.\n\nLocal Definition Foldable__Elem_foldl' : forall {b} {a},\n                                           (b -> a -> b) -> b -> Elem a -> b :=\n  fun {b} {a} =>\n    fun arg_24__ arg_25__ arg_26__ =>\n      match arg_24__ , arg_25__ , arg_26__ with\n        | f , z0 , xs => let f' :=\n                           fun arg_27__ arg_28__ arg_29__ =>\n                             match arg_27__ , arg_28__ , arg_29__ with\n                               | x , k , z => _GHC.Base.$!_ k (f z x)\n                             end in\n                         Foldable__Elem_foldr f' GHC.Base.id xs z0\n      end.\n\nLocal Definition Foldable__Elem_length : forall {a}, Elem a -> GHC.Num.Int :=\n  fun {a} e =>\n    Z.of_nat (Foldable__Elem_foldl' (fun arg_64__ arg_65__ =>\n                            match arg_64__ , arg_65__ with\n                              | c , _ => c + 1\n                            end) 0 e).\n\nProgram Instance Foldable__Elem : Data.Foldable.Foldable Elem := fun _ k =>\n    k {|Data.Foldable.elem__ := fun {a} `{GHC.Base.Eq_ a} => Foldable__Elem_elem ;\n      Data.Foldable.fold__ := fun {m} `{GHC.Base.Monoid m} => Foldable__Elem_fold ;\n      Data.Foldable.foldMap__ := fun {m} {a} `{GHC.Base.Monoid m} =>\n        Foldable__Elem_foldMap ;\n      Data.Foldable.foldl__ := fun {b} {a} => Foldable__Elem_foldl ;\n      Data.Foldable.foldl'__ := fun {b} {a} => Foldable__Elem_foldl' ;\n      Data.Foldable.foldr__ := fun {a} {b} => Foldable__Elem_foldr ;\n      Data.Foldable.foldr'__ := fun {a} {b} => Foldable__Elem_foldr' ;\n      Data.Foldable.length__ := fun {a} => Foldable__Elem_length ;\n      Data.Foldable.null__ := fun {a} => Foldable__Elem_null ;\n      Data.Foldable.product__ := fun {a} `{GHC.Num.Num a} => Foldable__Elem_product ;\n      Data.Foldable.sum__ := fun {a} `{GHC.Num.Num a} => Foldable__Elem_sum ;\n      Data.Foldable.toList__ := fun {a} => Foldable__Elem_toList |}.\n\nProgram Instance Foldable__FingerTree : Data.Foldable.Foldable FingerTree :=\n  fun _ k =>\n    k {|Data.Foldable.elem__ := fun {a} `{GHC.Base.Eq_ a} =>\n        Foldable__FingerTree_elem ;\n      Data.Foldable.fold__ := fun {m} `{GHC.Base.Monoid m} =>\n        Foldable__FingerTree_fold ;\n      Data.Foldable.foldMap__ := fun {m} {a} `{GHC.Base.Monoid m} =>\n        Foldable__FingerTree_foldMap ;\n      Data.Foldable.foldl__ := fun {b} {a} => Foldable__FingerTree_foldl ;\n      Data.Foldable.foldl'__ := fun {b} {a} => Foldable__FingerTree_foldl' ;\n      Data.Foldable.foldr__ := fun {a} {b} => Foldable__FingerTree_foldr ;\n      Data.Foldable.foldr'__ := fun {a} {b} => Foldable__FingerTree_foldr' ;\n      Data.Foldable.length__ := fun {a} => Foldable__FingerTree_length ;\n      Data.Foldable.null__ := fun {a} => Foldable__FingerTree_null ;\n      Data.Foldable.product__ := fun {a} `{GHC.Num.Num a} =>\n        Foldable__FingerTree_product ;\n      Data.Foldable.sum__ := fun {a} `{GHC.Num.Num a} => Foldable__FingerTree_sum ;\n      Data.Foldable.toList__ := fun {a} => Foldable__FingerTree_toList |}.\n\nLocal Definition Foldable__Seq_foldMap : forall {m} {a},\n                                           forall `{GHC.Base.Monoid m}, (a -> m) -> Seq a -> m :=\n  fun {m} {a} `{GHC.Base.Monoid m} =>\n    fun arg_0__ arg_1__ =>\n      match arg_0__ , arg_1__ with\n        | f , Mk_Seq xs => Data.Foldable.foldMap (Data.Foldable.foldMap f) xs\n      end.\n\nLocal Definition Foldable__Seq_foldl : forall {b} {a},\n                                         (b -> a -> b) -> b -> Seq a -> b :=\n  fun {b} {a} =>\n    fun arg_0__ arg_1__ arg_2__ =>\n      match arg_0__ , arg_1__ , arg_2__ with\n        | f , z , Mk_Seq xs => Data.Foldable.foldl (Data.Foldable.foldl f) z xs\n      end.\n\nLocal Definition Foldable__Seq_foldr : forall {a} {b},\n                                         (a -> b -> b) -> b -> Seq a -> b :=\n  fun {a} {b} =>\n    fun arg_0__ arg_1__ arg_2__ =>\n      match arg_0__ , arg_1__ , arg_2__ with\n        | f , z , Mk_Seq xs => Data.Foldable.foldr (GHC.Base.flip (Data.Foldable.foldr\n                                                                  f)) z xs\n      end.\n\nLocal Definition Foldable__Seq_toList : forall {a}, Seq a -> list a :=\n  fun {a} =>\n    fun arg_54__ =>\n      match arg_54__ with\n        | t => GHC.Base.build (fun arg_55__ arg_56__ =>\n                                match arg_55__ , arg_56__ with\n                                  | c , n => Foldable__Seq_foldr c n t\n                                end)\n      end.\n\nLocal Definition Foldable__Seq_foldl' : forall {b} {a},\n                                          (b -> a -> b) -> b -> Seq a -> b :=\n  fun {b} {a} =>\n    fun arg_24__ arg_25__ arg_26__ =>\n      match arg_24__ , arg_25__ , arg_26__ with\n        | f , z0 , xs => let f' :=\n                           fun arg_27__ arg_28__ arg_29__ =>\n                             match arg_27__ , arg_28__ , arg_29__ with\n                               | x , k , z => _GHC.Base.$!_ k (f z x)\n                             end in\n                         Foldable__Seq_foldr f' GHC.Base.id xs z0\n      end.\n\nLocal Definition Foldable__Seq_foldr' : forall {a} {b},\n                                          (a -> b -> b) -> b -> Seq a -> b :=\n  fun {a} {b} =>\n    fun arg_9__ arg_10__ arg_11__ =>\n      match arg_9__ , arg_10__ , arg_11__ with\n        | f , z0 , xs => let f' :=\n                           fun arg_12__ arg_13__ arg_14__ =>\n                             match arg_12__ , arg_13__ , arg_14__ with\n                               | k , x , z => _GHC.Base.$!_ k (f x z)\n                             end in\n                         Foldable__Seq_foldl f' GHC.Base.id xs z0\n      end.\n\nLocal Definition Foldable__Seq_product : forall {a},\n                                           forall `{GHC.Num.Num a}, Seq a -> a :=\n  fun {a} `{GHC.Num.Num a} =>\n    Data.Foldable.hash_compose Data.Monoid.getProduct (Foldable__Seq_foldMap\n                               Data.Monoid.Mk_Product).\n\nLocal Definition Foldable__Seq_sum : forall {a},\n                                       forall `{GHC.Num.Num a}, Seq a -> a :=\n  fun {a} `{GHC.Num.Num a} =>\n    Data.Foldable.hash_compose Data.Monoid.getSum (Foldable__Seq_foldMap\n                               Data.Monoid.Mk_Sum).\n\nLocal Definition Foldable__Seq_fold : forall {m},\n                                        forall `{GHC.Base.Monoid m}, Seq m -> m :=\n  fun {m} `{GHC.Base.Monoid m} => Foldable__Seq_foldMap GHC.Base.id.\n\nLocal Definition Foldable__Seq_elem : forall {a},\n                                        forall `{GHC.Base.Eq_ a}, a -> Seq a -> bool :=\n  fun {a} `{GHC.Base.Eq_ a} =>\n    Coq.Program.Basics.compose (fun arg_69__ =>\n                                 match arg_69__ with\n                                   | p => Coq.Program.Basics.compose Data.Monoid.getAny (Foldable__Seq_foldMap\n                                                                     (Coq.Program.Basics.compose Data.Monoid.Mk_Any p))\n                                 end) _GHC.Base.==_.\n\nLocal Definition Traversable__Elem_traverse : forall {f} {a} {b},\n                                                forall `{GHC.Base.Applicative f}, (a -> f b) -> Elem a -> f (Elem b) :=\n  fun {f} {a} {b} `{GHC.Base.Applicative f} =>\n    fun arg_0__ arg_1__ =>\n      match arg_0__ , arg_1__ with\n        | f , Mk_Elem x => Mk_Elem Data.Functor.<$> f x\n      end.\n\nLocal Definition Traversable__Elem_sequenceA : forall {f} {a},\n                                                 forall `{GHC.Base.Applicative f}, Elem (f a) -> f (Elem a) :=\n  fun {f} {a} `{GHC.Base.Applicative f} => Traversable__Elem_traverse GHC.Base.id.\n\nLocal Definition Traversable__Elem_sequence : forall {m} {a},\n                                                forall `{GHC.Base.Monad m}, Elem (m a) -> m (Elem a) :=\n  fun {m} {a} `{GHC.Base.Monad m} => Traversable__Elem_sequenceA.\n\nLocal Definition Traversable__Elem_mapM : forall {m} {a} {b},\n                                            forall `{GHC.Base.Monad m}, (a -> m b) -> Elem a -> m (Elem b) :=\n  fun {m} {a} {b} `{GHC.Base.Monad m} => Traversable__Elem_traverse.\n\nProgram Instance Traversable__Elem : Data.Traversable.Traversable Elem := fun _\n                                                                              k =>\n    k {|Data.Traversable.mapM__ := fun {m} {a} {b} `{GHC.Base.Monad m} =>\n        Traversable__Elem_mapM ;\n      Data.Traversable.sequence__ := fun {m} {a} `{GHC.Base.Monad m} =>\n        Traversable__Elem_sequence ;\n      Data.Traversable.sequenceA__ := fun {f} {a} `{GHC.Base.Applicative f} =>\n        Traversable__Elem_sequenceA ;\n      Data.Traversable.traverse__ := fun {f} {a} {b} `{GHC.Base.Applicative f} =>\n        Traversable__Elem_traverse |}.\n\nProgram Instance Traversable__FingerTree : Data.Traversable.Traversable\n                                           FingerTree := fun _ k =>\n    k {|Data.Traversable.mapM__ := fun {m} {a} {b} `{GHC.Base.Monad m} =>\n        Traversable__FingerTree_mapM ;\n      Data.Traversable.sequence__ := fun {m} {a} `{GHC.Base.Monad m} =>\n        Traversable__FingerTree_sequence ;\n      Data.Traversable.sequenceA__ := fun {f} {a} `{GHC.Base.Applicative f} =>\n        Traversable__FingerTree_sequenceA ;\n      Data.Traversable.traverse__ := fun {f} {a} {b} `{GHC.Base.Applicative f} =>\n        Traversable__FingerTree_traverse |}.\n\nLocal Definition Traversable__Seq_traverse : forall {f} {a} {b},\n                                               forall `{GHC.Base.Applicative f}, (a -> f b) -> Seq a -> f (Seq b) :=\n  fun {f} {a} {b} `{GHC.Base.Applicative f} =>\n    fun arg_0__ arg_1__ =>\n      match arg_0__ , arg_1__ with\n        | f , Mk_Seq xs => Mk_Seq Data.Functor.<$> Data.Traversable.traverse\n                           (Data.Traversable.traverse f) xs\n      end.\n\nLocal Definition Traversable__Seq_sequenceA : forall {f} {a},\n                                                forall `{GHC.Base.Applicative f}, Seq (f a) -> f (Seq a) :=\n  fun {f} {a} `{GHC.Base.Applicative f} => Traversable__Seq_traverse GHC.Base.id.\n\nLocal Definition Traversable__Seq_sequence : forall {m} {a},\n                                               forall `{GHC.Base.Monad m}, Seq (m a) -> m (Seq a) :=\n  fun {m} {a} `{GHC.Base.Monad m} => Traversable__Seq_sequenceA.\n\nLocal Definition Traversable__Seq_mapM : forall {m} {a} {b},\n                                           forall `{GHC.Base.Monad m}, (a -> m b) -> Seq a -> m (Seq b) :=\n  fun {m} {a} {b} `{GHC.Base.Monad m} => Traversable__Seq_traverse.\n\n(* Translating `instance forall {a}, forall `{Control.DeepSeq.NFData a},\n   Control.DeepSeq.NFData (Data.Sequence.Elem a)' failed: OOPS! Cannot find\n   information for class Qualified \"Control.DeepSeq\" \"NFData\" unsupported *)\n\nLocal Definition Monad__State_op_zgzgze__ {inst_s} : forall {a} {b},\n                                                       (State inst_s) a -> (a -> (State inst_s) b) -> (State inst_s)\n                                                       b :=\n  fun {a} {b} =>\n    fun m k =>\n      Mk_State GHC.Base.$ (fun s =>\n        match runState m s with\n          | pair s' x => runState (k x) s'\n        end).\n\nLocal Definition Applicative__State_pure {inst_s} : forall {a},\n                                                      a -> (State inst_s) a :=\n  fun {a} => fun x => Mk_State GHC.Base.$ (fun s => pair s x).\n\nDefinition Functor__State_fmap : forall {inst_s} {a} {b},\n                                   (a -> b) -> State inst_s a -> State inst_s b :=\n  fun {inst_s} {a} {b} f sa =>\n    Monad__State_op_zgzgze__ sa (fun a => Applicative__State_pure (f a)).\n\nLocal Definition Functor__State_op_zlzd__ {inst_s} : forall {a} {b},\n                                                       a -> (State inst_s) b -> (State inst_s) a :=\n  fun {a} {b} => fun x => Functor__State_fmap (GHC.Base.const x).\n\nProgram Instance Functor__State {s} : GHC.Base.Functor (State s) := fun _ k =>\n    k {|GHC.Base.op_zlzd____ := fun {a} {b} => Functor__State_op_zlzd__ ;\n      GHC.Base.fmap__ := fun {a} {b} => Functor__State_fmap |}.\n\nDefinition Applicative__State_op_zlztzg__ : forall {s} {a} {b},\n                                              State s (a -> b) -> State s a -> State s b :=\n  fun {s} {a} {b} =>\n    fun m1 m2 =>\n      Monad__State_op_zgzgze__ m1 (fun x1 =>\n                                 Monad__State_op_zgzgze__ m2 (fun x2 => Applicative__State_pure (x1 x2))).\n\nLocal Definition Applicative__State_op_ztzg__ {inst_s} : forall {a} {b},\n                                                           (State inst_s) a -> (State inst_s) b -> (State inst_s) b :=\n  fun {a} {b} =>\n    fun x y =>\n      Applicative__State_op_zlztzg__ (GHC.Base.fmap (GHC.Base.const GHC.Base.id) x) y.\n\nProgram Instance Applicative__State {s} : GHC.Base.Applicative (State s) :=\n  fun _ k =>\n    k {|GHC.Base.op_ztzg____ := fun {a} {b} => Applicative__State_op_ztzg__ ;\n      GHC.Base.op_zlztzg____ := fun {a} {b} => Applicative__State_op_zlztzg__ ;\n      GHC.Base.pure__ := fun {a} => Applicative__State_pure |}.\n\nLocal Definition Monad__State_op_zgzg__ {inst_s} : forall {a} {b},\n                                                     (State inst_s) a -> (State inst_s) b -> (State inst_s) b :=\n  fun {a} {b} => _GHC.Base.*>_.\n\nLocal Definition Monad__State_return_ {inst_s} : forall {a},\n                                                   a -> (State inst_s) a :=\n  fun {a} => GHC.Base.pure.\n\nProgram Instance Monad__State {s} : GHC.Base.Monad (State s) := fun _ k =>\n    k {|GHC.Base.op_zgzg____ := fun {a} {b} => Monad__State_op_zgzg__ ;\n      GHC.Base.op_zgzgze____ := fun {a} {b} => Monad__State_op_zgzgze__ ;\n      GHC.Base.return___ := fun {a} => Monad__State_return_ |}.\n\nLocal Definition Foldable__ViewR_null : forall {a}, ViewR a -> bool :=\n  fun {a} =>\n    fun arg_0__ => match arg_0__ with | EmptyR => true | op_ZCzg__ _ _ => false end.\n\n(* Translating `instance forall {a}, GHC.Exts.IsList (Data.Sequence.Seq a)'\n   failed: OOPS! Cannot find information for class Qualified \"GHC.Exts\" \"IsList\"\n   unsupported *)\n\n(* Translating `instance Data.String.IsString (Data.Sequence.Seq GHC.Char.Char)'\n   failed: OOPS! Cannot find information for class Qualified \"Data.String\"\n   \"IsString\" unsupported *)\n\n(* Translating `instance forall {a}, forall `{Data.Data.Data a}, Data.Data.Data\n   (Data.Sequence.ViewR a)' failed: OOPS! Cannot find information for class\n   Qualified \"Data.Data\" \"Data\" unsupported *)\n\n(* Translating `instance forall {a}, forall `{GHC.Read.Read a}, GHC.Read.Read\n   (Data.Sequence.ViewR a)' failed: OOPS! Cannot find information for class\n   Qualified \"GHC.Read\" \"Read\" unsupported *)\n\n(* Translating `instance forall {a}, forall `{GHC.Show.Show a}, GHC.Show.Show\n   (Data.Sequence.ViewR a)' failed: OOPS! Cannot find information for class\n   Qualified \"GHC.Show\" \"Show\" unsupported *)\n\n(* Translating `instance forall {a}, forall `{Data.Data.Data a}, Data.Data.Data\n   (Data.Sequence.ViewL a)' failed: OOPS! Cannot find information for class\n   Qualified \"Data.Data\" \"Data\" unsupported *)\n\n(* Translating `instance forall {a}, forall `{GHC.Read.Read a}, GHC.Read.Read\n   (Data.Sequence.ViewL a)' failed: OOPS! Cannot find information for class\n   Qualified \"GHC.Read\" \"Read\" unsupported *)\n\n(* Translating `instance forall {a}, forall `{GHC.Show.Show a}, GHC.Show.Show\n   (Data.Sequence.ViewL a)' failed: OOPS! Cannot find information for class\n   Qualified \"GHC.Show\" \"Show\" unsupported *)\n\nDefinition adjustDigit {a} `{Sized a}\n    : (nat -> a -> a) -> nat -> Digit a -> Digit a :=\n  fun arg_0__ arg_1__ arg_2__ =>\n    match arg_0__ , arg_1__ , arg_2__ with\n      | f , i , One a => One (f i a)\n      | f , i , Two a b => let sa := size a in\n                           if Nat.ltb i sa : bool\n                           then Two (f i a) b\n                           else Two a (f (i - sa) b)\n      | f , i , Three a b c => let sa := size a in\n                               let sab := sa + size b in\n                               if Nat.ltb i sa : bool\n                               then Three (f i a) b c\n                               else if Nat.ltb i sab : bool\n                                    then Three a (f (i - sa) b) c\n                                    else Three a b (f (i - sab) c)\n      | f , i , Four a b c d => let sa := size a in\n                                let sab := sa + size b in\n                                let sabc := sab + size c in\n                                if Nat.ltb i sa : bool\n                                then Four (f i a) b c d\n                                else if Nat.ltb i sab : bool\n                                     then Four a (f (i - sa) b) c d\n                                     else if Nat.ltb i sabc : bool\n                                          then Four a b (f (i - sab) c) d\n                                          else Four a b c (f (i - sabc) d)\n    end.\n\nDefinition adjustNode {a} `{Sized a}\n    : (nat -> a -> a) -> nat -> Node a -> Node a :=\n  fun arg_0__ arg_1__ arg_2__ =>\n    match arg_0__ , arg_1__ , arg_2__ with\n      | f , i , Node2 s a b => let sa := size a in\n                               if Nat.ltb i sa : bool\n                               then Node2 s (f i a) b\n                               else Node2 s a (f (i - sa) b)\n      | f , i , Node3 s a b c => let sa := size a in\n                                 let sab := sa + size b in\n                                 if Nat.ltb i sa : bool\n                                 then Node3 s (f i a) b c\n                                 else if Nat.ltb i sab : bool\n                                      then Node3 s a (f (i - sa) b) c\n                                      else Node3 s a b (f (i - sab) c)\n    end.\n\nFixpoint adjustTree {a} `{_ : Sized a} (f : nat -> a -> a) (i\n                      : nat) (ft : FingerTree a) : FingerTree a\n           := match ft with\n                | Empty => error\n                | Single x => Single (f i x)\n                | Deep s pr m sf => let spr := size pr in\n                                    let spm := spr + (size m) in\n                                    if Nat.ltb i spr then Deep s (adjustDigit f i pr) m sf else if Nat.ltb\n                                       i spm then Deep s pr (adjustTree (adjustNode f) (i - spr) m) sf else\n                                       Deep s pr m (adjustDigit f (i - spm) sf)\n              end.\n\nDefinition adjust {a} : (a -> a) -> nat -> Seq a -> Seq a :=\n  fun arg_0__ arg_1__ arg_2__ =>\n    match arg_0__ , arg_1__ , arg_2__ with\n      | f , i , Mk_Seq xs => if andb (Nat.leb 0 i) (Nat.ltb i (size xs)) : bool\n                             then Mk_Seq (adjustTree (GHC.Base.const (GHC.Base.fmap f)) i xs)\n                             else Mk_Seq xs\n    end.\n\nDefinition update {a} : nat -> a -> Seq a -> Seq a :=\n  fun i x => adjust (GHC.Base.const x) i.\n\nDefinition deep {a} `{Sized a} : Digit a -> FingerTree (Node a) -> Digit\n                                 a -> FingerTree a :=\n  fun pr m sf => Deep ((size pr + size m) + size sf) pr m sf.\n\nDefinition digitToTree {a} `{Sized a} : Digit a -> FingerTree a :=\n  fun arg_0__ =>\n    match arg_0__ with\n      | One a => Single a\n      | Two a b => deep (One a) Empty (One b)\n      | Three a b c => deep (Two a b) Empty (One c)\n      | Four a b c d => deep (Two a b) Empty (Two c d)\n    end.\n\nDefinition digit12ToDigit {a} : Digit12 a -> Digit a :=\n  fun arg_0__ => match arg_0__ with | One12 a => One a | Two12 a b => Two a b end.\n\nDefinition digitToTree' {a} : nat -> Digit a -> FingerTree a :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__ , arg_1__ with\n      | n , Four a b c d => Deep n (Two a b) Empty (Two c d)\n      | n , Three a b c => Deep n (Two a b) Empty (One c)\n      | n , Two a b => Deep n (One a) Empty (One b)\n      | n , One a => GHC.Prim.seq n (Single a)\n    end.\n\nDefinition empty {a} : Seq a :=\n  Mk_Seq Empty.\n\nDefinition execState {s} {a} : State s a -> s -> a :=\n  fun m x => Data.Tuple.snd (runState m x).\n\nDefinition fmapSeq {a} {b} : (a -> b) -> Seq a -> Seq b :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__ , arg_1__ with\n      | f , Mk_Seq xs => Mk_Seq (Functor__FingerTree_fmap (GHC.Base.fmap f) xs)\n    end.\n\nLocal Definition Functor__Seq_fmap : forall {a} {b},\n                                       (a -> b) -> Seq a -> Seq b :=\n  fun {a} {b} => fmapSeq.\n\nDefinition getSingleton {a} : Seq a -> a :=\n  fun arg_0__ =>\n    match arg_0__ with\n      | Mk_Seq (Single (Mk_Elem a)) => a\n      | Mk_Seq Empty => error (GHC.Base.hs_string__ \"getSingleton: Empty\")\n      | _ => error (GHC.Base.hs_string__ \"getSingleton: Not a singleton.\")\n    end.\n\nDefinition initsDigit {a} : Digit a -> Digit (Digit a) :=\n  fun arg_0__ =>\n    match arg_0__ with\n      | One a => One (One a)\n      | Two a b => Two (One a) (Two a b)\n      | Three a b c => Three (One a) (Two a b) (Three a b c)\n      | Four a b c d => Four (One a) (Two a b) (Three a b c) (Four a b c d)\n    end.\n\nDefinition initsNode {a} : Node a -> Node (Digit a) :=\n  fun arg_0__ =>\n    match arg_0__ with\n      | Node2 s a b => Node2 s (One a) (Two a b)\n      | Node3 s a b c => Node3 s (One a) (Two a b) (Three a b c)\n    end.\n\nDefinition length {a} : Seq a -> nat :=\n  fun arg_0__ => match arg_0__ with | Mk_Seq xs => size xs end.\n\nLocal Definition Foldable__Seq_length : forall {a}, Seq a -> GHC.Num.Int :=\n  fun {a} s => Z.of_nat (length s).\n\nDefinition listToMaybe' {a} : list a -> option a :=\n  Data.Foldable.foldr (fun arg_0__ arg_1__ =>\n                        match arg_0__ , arg_1__ with\n                          | x , _ => Some x\n                        end) None.\n\nDefinition lookupDigit {a} `{Sized a} : nat -> Digit a -> Place a :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__ , arg_1__ with\n      | i , One a => Mk_Place i a\n      | i , Two a b => let sa := size a in\n                       if Nat.ltb i sa : bool\n                       then Mk_Place i a\n                       else Mk_Place (i - sa) b\n      | i , Three a b c => let sa := size a in\n                           let sab := sa + size b in\n                           if Nat.ltb i sa : bool\n                           then Mk_Place i a\n                           else if Nat.ltb i sab : bool\n                                then Mk_Place (i - sa) b\n                                else Mk_Place (i - sab) c\n      | i , Four a b c d => let sa := size a in\n                            let sab := sa + size b in\n                            let sabc := sab + size c in\n                            if Nat.ltb i sa : bool\n                            then Mk_Place i a\n                            else if Nat.ltb i sab : bool\n                                 then Mk_Place (i - sa) b\n                                 else if Nat.ltb i sabc : bool\n                                      then Mk_Place (i - sab) c\n                                      else Mk_Place (i - sabc) d\n    end.\n\nDefinition lookupNode {a} `{Sized a} : nat -> Node a -> Place a :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__ , arg_1__ with\n      | i , Node2 _ a b => let sa := size a in\n                           if Nat.ltb i sa : bool\n                           then Mk_Place i a\n                           else Mk_Place (i - sa) b\n      | i , Node3 _ a b c => let sa := size a in\n                             let sab := sa + size b in\n                             if Nat.ltb i sa : bool\n                             then Mk_Place i a\n                             else if Nat.ltb i sab : bool\n                                  then Mk_Place (i - sa) b\n                                  else Mk_Place (i - sab) c\n    end.\n\nFixpoint lookupTree {a} `{_ : Sized a} (i : nat) (ft : FingerTree a)\n           : Place a\n           := match ft with\n                | Empty => error\n                | Single x => Mk_Place i x\n                | Deep totalSize pr m sf => let spm := totalSize - (size sf) in\n                                            let spr := size pr in\n                                            if Nat.ltb i spr then lookupDigit i pr else if Nat.ltb i spm then\n                                               (match lookupTree (i - spr) m with\n                                                 | Mk_Place i' xs => lookupNode i' xs\n                                               end) else lookupDigit (i - spm) sf\n              end.\n\nDefinition index {a} : Seq a -> nat -> a :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__ , arg_1__ with\n      | Mk_Seq xs , i => if andb (Nat.leb 0 i) (Nat.leb i\n                                 (size xs)) : bool\n                         then match lookupTree i xs with\n                                | Mk_Place _ (Mk_Elem x) => x\n                              end\n                         else error (GHC.Base.hs_string__ \"index out of bounds\")\n    end.\n\nDefinition mapMulNode {a} {b} : nat -> (a -> b) -> Node a -> Node b :=\n  fun arg_0__ arg_1__ arg_2__ =>\n    match arg_0__ , arg_1__ , arg_2__ with\n      | mul , f , Node2 s a b => Node2 (mul * s) (f a) (f b)\n      | mul , f , Node3 s a b c => Node3 (mul * s) (f a) (f b) (f c)\n    end.\n\nFixpoint mapMulFT {a} {b} (mul : nat) (f : a -> b) (ft : FingerTree a)\n           : FingerTree b\n           := match ft with\n                | Empty => Empty\n                | Single a => Single (f a)\n                | Deep s pr m sf => Deep (mul * s) (GHC.Base.fmap f pr) (mapMulFT mul (mapMulNode mul f) m)\n                                         (GHC.Base.fmap f sf)\n              end.\n\nDefinition ap3FT {a} {b} : (a -> b) -> FingerTree (Elem (a -> b)) -> (a -> b) -> (a * a * a)%type -> FingerTree (Elem b) :=\n  fun arg_0__ arg_1__ arg_2__ arg_3__ =>\n    match arg_0__ , arg_1__ , arg_2__ , arg_3__ with\n      | firstf , fs , lastf , pair (pair x y) z => Deep ((size fs *\n                                                         3) +  6) (Three\n                                                                                                                (Mk_Elem\n                                                                                                                GHC.Base.$\n                                                                                                                firstf\n                                                                                                                x)\n                                                                                                                (Mk_Elem\n                                                                                                                GHC.Base.$\n                                                                                                                firstf\n                                                                                                                y)\n                                                                                                                (Mk_Elem\n                                                                                                                GHC.Base.$\n                                                                                                                firstf\n                                                                                                                z))\n                                                   (mapMulFT ( 3) (fun arg_4__ =>\n                                                                                       match arg_4__ with\n                                                                                         | Mk_Elem f => Node3\n                                                                                                        (\n                                                                                                        3) (Mk_Elem (f\n                                                                                                                    x))\n                                                                                                        (Mk_Elem (f y))\n                                                                                                        (Mk_Elem (f z))\n                                                                                       end) fs) (Three (Mk_Elem\n                                                                                                       GHC.Base.$ lastf\n                                                                                                       x) (Mk_Elem\n                                                                                                          GHC.Base.$\n                                                                                                          lastf y)\n                                                                                                (Mk_Elem GHC.Base.$\n                                                                                                lastf z))\n    end.\n\nDefinition ap2FT {a} {b} : (a -> b) -> FingerTree (Elem\n                                                  (a -> b)) -> (a -> b) -> (a * a)%type -> FingerTree (Elem b) :=\n  fun arg_0__ arg_1__ arg_2__ arg_3__ =>\n    match arg_0__ , arg_1__ , arg_2__ , arg_3__ with\n      | firstf , fs , lastf , pair x y => Deep ((size fs * id\n                                               2) + id 4) (Two (Mk_Elem GHC.Base.$ firstf x)\n                                                                                   (Mk_Elem GHC.Base.$ firstf y))\n                                          (mapMulFT (id 2) (fun arg_4__ =>\n                                                                              match arg_4__ with\n                                                                                | Mk_Elem f => Node2\n                                                                                               (id 2)\n                                                                                               (Mk_Elem (f x)) (Mk_Elem\n                                                                                                               (f y))\n                                                                              end) fs) (Two (Mk_Elem GHC.Base.$ lastf x)\n                                                                                       (Mk_Elem GHC.Base.$ lastf y))\n    end.\n\n\nDefinition mergePQ {a} : (a -> a -> comparison) -> PQueue a -> PQueue\n                         a -> PQueue a :=\n  fun arg_0__ arg_1__ arg_2__ =>\n    match arg_0__ , arg_1__ , arg_2__ with\n      | cmp , (Mk_PQueue x1 ts1 as q1) , (Mk_PQueue x2 ts2 as q2) => if cmp x1 x2\n                                                                        GHC.Base.== Gt : bool\n                                                                     then Mk_PQueue x2 (q1 :& ts2)\n                                                                     else Mk_PQueue x1 (q2 :& ts1)\n    end.\n\nDefinition node2 {a} `{Sized a} : a -> a -> Node a :=\n  fun a b => Node2 (size a + size b) a b.\n\nDefinition node3 {a} `{Sized a} : a -> a -> a -> Node a :=\n  fun a b c => Node3 ((size a + size b) + size c) a b c.\n\nDefinition squashL {a} : Digit23 a -> Digit12 (Node a) -> Digit23 (Node a) :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__ , arg_1__ with\n      | m , One12 n => node2 m n\n      | m , Two12 n1 n2 => node3 m n1 n2\n    end.\n\nDefinition squashR {a} : Digit12 (Node a) -> Digit23 a -> Digit23 (Node a) :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__ , arg_1__ with\n      | One12 n , m => node2 n m\n      | Two12 n1 n2 , m => node3 n1 n2 m\n    end.\n\nFixpoint consTree {a} `{_ : Sized a} (arg_0__ : a) (ft : FingerTree a)\n           : FingerTree a\n           := match arg_0__ , ft with\n                | a , Empty => Single a\n                | a , Single b => deep (One a) Empty (One b)\n                | a , Deep s (Four b c d e) m sf => GHC.Prim.seq m (Deep ((size a) + s) (Two a b) (consTree (node3 c d\n                                                                                                                    e)\n                                                                                                             m) sf)\n                | a , Deep s (Three b c d) m sf => Deep ((size a) + s) (Four a b c d)\n                                                        m sf\n                | a , Deep s (Two b c) m sf => Deep ((size a) + s) (Three a b c) m sf\n                | a , Deep s (One b) m sf => Deep ((size a) + s) (Two a b) m sf\n              end.\n\nDefinition op_zlzb__ {a} : a -> Seq a -> Seq a :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__ , arg_1__ with\n      | x , Mk_Seq xs => Mk_Seq (consTree (Mk_Elem x) xs)\n    end.\n\nNotation \"'_<|_'\" := (op_zlzb__).\n\nInfix \"<|\" := (_<|_) (at level 99).\n\n\nDefinition nodeToDigit {a} : Node a -> Digit a :=\n  fun arg_0__ =>\n    match arg_0__ with\n      | Node2 _ a b => Two a b\n      | Node3 _ a b c => Three a b c\n    end.\n\nFixpoint viewLTree {a} `{Sized a} ( arg_0__ : FingerTree a) : Maybe2 a (FingerTree a) :=\n  let pullL {a} : nat -> FingerTree (Node a) -> Digit\n                       a -> FingerTree a :=\n  fun s m sf =>\n    match viewLTree m with\n      | Nothing2 => digitToTree' s sf\n      | Just2 pr m' => Deep s (nodeToDigit pr) m' sf\n    end in\n\n    match arg_0__ with\n      | Empty => Nothing2\n      | Single a => Just2 a Empty\n      | Deep s (One a) m sf => Just2 a (pullL (s - size a) m sf)\n      | Deep s (Two a b) m sf => Just2 a (Deep (s - size a) (One b) m sf)\n      | Deep s (Three a b c) m sf => Just2 a (Deep (s - size a) (Two b c) m\n                                             sf)\n      | Deep s (Four a b c d) m sf => Just2 a (Deep (s - size a) (Three b c d)\n                                              m sf)\n    end.\n\nFixpoint viewRTree {a} `{Sized a} (arg_0__ : FingerTree a) : Maybe2 (FingerTree a) a :=\n  let pullR {a} : nat -> Digit a -> FingerTree (Node\n                                                            a) -> FingerTree a :=\n  fun s pr m =>\n    match viewRTree m with\n      | Nothing2 => digitToTree' s pr\n      | Just2 m' sf => Deep s pr m' (nodeToDigit sf)\n    end in\n\n    match arg_0__ with\n      | Empty => Nothing2\n      | Single z => Just2 Empty z\n      | Deep s pr m (One z) => Just2 (pullR (s - size z) pr m) z\n      | Deep s pr m (Two y z) => Just2 (Deep (s - size z) pr m (One y)) z\n      | Deep s pr m (Three x y z) => Just2 (Deep (s - size z) pr m (Two x y))\n                                     z\n      | Deep s pr m (Four w x y z) => Just2 (Deep (s - size z) pr m (Three w x\n                                                                            y)) z\n    end.\n\n\n\nFixpoint initsTree {a} {b} `{_:Sized a} (f : (FingerTree a) -> b) (arg_1__ : FingerTree a) : FingerTree b :=\n      match arg_1__ with\n             | Empty => Empty\n             | Single x => Single (f (Single x))\n             | Deep n pr m sf =>\n                let f' := fun ms =>\n                            (match viewRTree ms with\n                            | Just2 m' node => GHC.Base.fmap (fun sf' => f (deep pr m' sf')) (initsNode node)\n                            | Nothing2 => error\n                            end) in\n                Deep n (GHC.Base.fmap (f GHC.Base.∘ digitToTree) (initsDigit pr)) (initsTree f' m)\n                     (GHC.Base.fmap (f GHC.Base.∘ deep pr m) (initsDigit sf))\n           end.\n\nDefinition inits {a} : Seq a -> Seq (Seq a) :=\n  fun arg_0__ =>\n    match arg_0__ with\n      | Mk_Seq xs => empty <| Mk_Seq (initsTree (Mk_Elem GHC.Base.∘ Mk_Seq) xs)\n    end.\n\n\nDefinition pullL {a} : nat -> FingerTree (Node a) -> Digit\n                       a -> FingerTree a :=\n  fun s m sf =>\n    match viewLTree m with\n      | Nothing2 => digitToTree' s sf\n      | Just2 pr m' => Deep s (nodeToDigit pr) m' sf\n    end.\n\nDefinition deepL {a} `{Sized a} : option (Digit a) -> FingerTree (Node\n                                                                 a) -> Digit a -> FingerTree a :=\n  fun arg_0__ arg_1__ arg_2__ =>\n    match arg_0__ , arg_1__ , arg_2__ with\n      | None , m , sf => pullL (size m + size sf) m sf\n      | Some pr , m , sf => deep pr m sf\n    end.\n\nDefinition pullR {a} : nat -> Digit a -> FingerTree (Node\n                                                            a) -> FingerTree a :=\n  fun s pr m =>\n    match viewRTree m with\n      | Nothing2 => digitToTree' s pr\n      | Just2 m' sf => Deep s pr m' (nodeToDigit sf)\n    end.\n\nDefinition deepR {a} `{Sized a} : Digit a -> FingerTree (Node a) -> option\n                                  (Digit a) -> FingerTree a :=\n  fun arg_0__ arg_1__ arg_2__ =>\n    match arg_0__ , arg_1__ , arg_2__ with\n      | pr , m , None => pullR (size m + size pr) pr m\n      | pr , m , Some sf => deep pr m sf\n    end.\n\nDefinition null {a} : Seq a -> bool :=\n  fun arg_0__ => match arg_0__ with | Mk_Seq Empty => true | _ => false end.\n\nLocal Definition Foldable__Seq_null : forall {a}, Seq a -> bool :=\n  fun {a} => null.\n\nProgram Fixpoint applicativeTree {f} {a} `{GHC.Base.Applicative f}\n        (n : nat) (mSize : nat) (m : f a) { measure n } : f (FingerTree a) :=\n        let emptyTree : f (FingerTree (Node a)) := GHC.Base.pure Empty in\n        let mSize' := Nat.mul 3 mSize in\n        let n3     := GHC.Base.liftA3 (Node3 mSize') m m m in\n        let deepA  : f (Digit a) -> f (FingerTree (Node a)) -> f (Digit a)\n                     -> f (FingerTree a)\n                   := GHC.Base.liftA3 (@Deep a (Nat.mul n mSize)) in\n        let three  : f (Digit a) := GHC.Base.liftA3 Three m m m in\n        let two    : f (Digit a) := GHC.Base.liftA2 Two m m in\n        let one    : f (Digit a) := GHC.Base.fmap One m in\n        let j_24__ : f (FingerTree a) :=\n            let q := (Nat.div n 3)    in\n            let n := (Nat.modulo n 3) in\n            let j_18__ :=\n               deepA three (applicativeTree (Nat.sub q 1) mSize' n3) two in\n            let j_20__ :=\n               if Nat.eqb n 1 : bool\n               then deepA two (applicativeTree (Nat.sub q 1) mSize' n3) two\n               else j_18__ in\n            if Nat.eqb n 0 : bool\n            then deepA three (applicativeTree (Nat.sub q 2) mSize' n3) three\n            else j_20__\n            in\n        let j_26__ :=\n            if Nat.eqb n 6 : bool\n            then deepA three emptyTree three\n            else j_24__\n        in\n        let j_28__ :=\n            if Nat.eqb n 5 : bool\n            then deepA three emptyTree two\n            else j_26__\n        in\n        let j_30__ :=\n            if Nat.eqb n 4 : bool\n            then deepA two emptyTree two\n            else j_28__\n        in\n        let j_32__ :=\n            if Nat.eqb n 3 : bool\n            then deepA two emptyTree one\n            else j_30__\n        in\n        let j_34__ :=\n            if Nat.eqb n 2 : bool\n            then deepA one emptyTree one\n            else j_32__\n        in\n        let j_36__ :=\n            if Nat.eqb n  1 : bool\n            then GHC.Base.fmap Single m\n            else j_34__\n        in\n        if Nat.eqb n 0 : bool\n        then GHC.Base.pure Empty\n        else j_36__\n.\nNext Obligation.\nAdmitted.\nNext Obligation.\nAdmitted.\nNext Obligation.\nAdmitted.\n\nDefinition replicateA {f} {a} `{GHC.Base.Applicative f} : nat -> f\n                                                          a -> f (Seq a) :=\n  fun n x =>\n    if negb (Nat.ltb n 0) : bool\n    then Mk_Seq Data.Functor.<$> applicativeTree n (id 1) (Mk_Elem\n                                                                           Data.Functor.<$> x)\n    else error (GHC.Base.hs_string__\n               \"replicateA takes a nonnegative integer argument\").\n\nDefinition replicateM {m} {a} `{GHC.Base.Monad m} : nat -> m a -> m (Seq\n                                                                            a) :=\n  fun n x =>\n    if negb (Nat.ltb n 0) : bool\n    then unwrapMonad (replicateA n (Control.Applicative.WrapMonad x))\n    else error (GHC.Base.hs_string__\n               \"replicateM takes a nonnegative integer argument\").\n\nDefinition replicate {a} : nat -> a -> Seq a :=\n  fun n x =>\n    if negb (Nat.ltb n 0) : bool\n    then runIdentity (replicateA n (Data.Functor.Identity.Mk_Identity x))\n    else error (GHC.Base.hs_string__\n               \"replicate takes a nonnegative integer argument\").\n\nLocal Definition Functor__Seq_op_zlzd__ : forall {a} {b}, a -> Seq b -> Seq a :=\n  fun {a} {b} => fun x s => replicate (length s) x.\n\nProgram Instance Functor__Seq : GHC.Base.Functor Seq := fun _ k =>\n    k {|GHC.Base.op_zlzd____ := fun {a} {b} => Functor__Seq_op_zlzd__ ;\n      GHC.Base.fmap__ := fun {a} {b} => Functor__Seq_fmap |}.\n\nProgram Instance Foldable__Seq : Data.Foldable.Foldable Seq := fun _ k =>\n    k {|Data.Foldable.elem__ := fun {a} `{GHC.Base.Eq_ a} => Foldable__Seq_elem ;\n      Data.Foldable.fold__ := fun {m} `{GHC.Base.Monoid m} => Foldable__Seq_fold ;\n      Data.Foldable.foldMap__ := fun {m} {a} `{GHC.Base.Monoid m} =>\n        Foldable__Seq_foldMap ;\n      Data.Foldable.foldl__ := fun {b} {a} => Foldable__Seq_foldl ;\n      Data.Foldable.foldl'__ := fun {b} {a} => Foldable__Seq_foldl' ;\n      Data.Foldable.foldr__ := fun {a} {b} => Foldable__Seq_foldr ;\n      Data.Foldable.foldr'__ := fun {a} {b} => Foldable__Seq_foldr' ;\n      Data.Foldable.length__ := fun {a} => Foldable__Seq_length ;\n      Data.Foldable.null__ := fun {a} => Foldable__Seq_null ;\n      Data.Foldable.product__ := fun {a} `{GHC.Num.Num a} => Foldable__Seq_product ;\n      Data.Foldable.sum__ := fun {a} `{GHC.Num.Num a} => Foldable__Seq_sum ;\n      Data.Foldable.toList__ := fun {a} => Foldable__Seq_toList |}.\n\nLocal Definition Ord__Seq_compare {inst_a} `{GHC.Base.Ord inst_a} : (Seq\n                                                                    inst_a) -> (Seq inst_a) -> comparison :=\n  fun xs ys =>\n    GHC.Base.compare (Data.Foldable.toList xs) (Data.Foldable.toList ys).\n\nDefinition foldrWithIndex {a} {b} : (nat -> a -> b -> b) -> b -> Seq\n                                    a -> b :=\n  fun f z xs =>\n    Data.Foldable.foldr (fun x g i =>\n                          GHC.Prim.seq i (f i x (g (i + id 1)))) (GHC.Base.const\n                                                                                          z) xs (id 0).\n\nDefinition foldlWithIndex {b} {a} : (b -> nat -> a -> b) -> b -> Seq\n                                    a -> b :=\n  fun f z xs =>\n    Data.Foldable.foldl (fun g x i =>\n                          GHC.Prim.seq i (f (g (i - id 1)) i x)) (GHC.Base.const\n                                                                                          z) xs (length xs -\n                                                                                                id 1).\n\nDefinition findIndicesR {a} : (a -> bool) -> Seq a -> list nat :=\n  fun p xs =>\n    GHC.Base.build (fun c n =>\n                     let g := fun z i x => if p x : bool then c i z else z in foldlWithIndex g n xs).\n\nDefinition findIndexR {a} : (a -> bool) -> Seq a -> option nat :=\n  fun p => listToMaybe' GHC.Base.∘ findIndicesR p.\n\nDefinition elemIndexR {a} `{GHC.Base.Eq_ a} : a -> Seq a -> option\n                                              nat :=\n  fun x => findIndexR (fun arg_0__ => x GHC.Base.== arg_0__).\n\nDefinition elemIndicesR {a} `{GHC.Base.Eq_ a} : a -> Seq a -> list\n                                                nat :=\n  fun x => findIndicesR (fun arg_0__ => x GHC.Base.== arg_0__).\n\nLocal Definition Eq___Seq_op_zeze__ {inst_a} `{GHC.Base.Eq_ inst_a} : (Seq\n                                                                      inst_a) -> (Seq inst_a) -> bool :=\n  fun xs ys =>\n    andb (Nat.eqb (length xs) (length ys)) (Data.Foldable.toList xs GHC.Base.==\n         Data.Foldable.toList ys).\n\nLocal Definition Eq___Seq_op_zsze__ {inst_a} `{GHC.Base.Eq_ inst_a} : (Seq\n                                                                      inst_a) -> (Seq inst_a) -> bool :=\n  fun x y => negb (Eq___Seq_op_zeze__ x y).\n\nProgram Instance Eq___Seq {a} `{GHC.Base.Eq_ a} : GHC.Base.Eq_ (Seq a) := fun _\n                                                                              k =>\n    k {|GHC.Base.op_zeze____ := Eq___Seq_op_zeze__ ;\n      GHC.Base.op_zsze____ := Eq___Seq_op_zsze__ |}.\n\nDefinition findIndicesL {a} : (a -> bool) -> Seq a -> list nat :=\n  fun p xs =>\n    GHC.Base.build (fun c n =>\n                     let g := fun i x z => if p x : bool then c i z else z in foldrWithIndex g n xs).\n\nDefinition findIndexL {a} : (a -> bool) -> Seq a -> option nat :=\n  fun p => listToMaybe' GHC.Base.∘ findIndicesL p.\n\nDefinition elemIndexL {a} `{GHC.Base.Eq_ a} : a -> Seq a -> option\n                                              nat :=\n  fun x => findIndexL (fun arg_0__ => x GHC.Base.== arg_0__).\n\nDefinition elemIndicesL {a} `{GHC.Base.Eq_ a} : a -> Seq a -> list\n                                                nat :=\n  fun x => findIndicesL (fun arg_0__ => x GHC.Base.== arg_0__).\n\nLocal Definition Ord__Seq_op_zg__ {inst_a} `{GHC.Base.Ord inst_a} : (Seq\n                                                                    inst_a) -> (Seq inst_a) -> bool :=\n  fun x y => _GHC.Base.==_ (Ord__Seq_compare x y) Gt.\n\nLocal Definition Ord__Seq_op_zgze__ {inst_a} `{GHC.Base.Ord inst_a} : (Seq\n                                                                      inst_a) -> (Seq inst_a) -> bool :=\n  fun x y => _GHC.Base./=_ (Ord__Seq_compare x y) Lt.\n\nLocal Definition Ord__Seq_op_zl__ {inst_a} `{GHC.Base.Ord inst_a} : (Seq\n                                                                    inst_a) -> (Seq inst_a) -> bool :=\n  fun x y => _GHC.Base.==_ (Ord__Seq_compare x y) Lt.\n\nLocal Definition Ord__Seq_op_zlze__ {inst_a} `{GHC.Base.Ord inst_a} : (Seq\n                                                                      inst_a) -> (Seq inst_a) -> bool :=\n  fun x y => _GHC.Base./=_ (Ord__Seq_compare x y) Gt.\n\nLocal Definition Ord__Seq_max {inst_a} `{GHC.Base.Ord inst_a} : (Seq\n                                                                inst_a) -> (Seq inst_a) -> (Seq inst_a) :=\n  fun x y => if Ord__Seq_op_zlze__ x y : bool then y else x.\n\nLocal Definition Ord__Seq_min {inst_a} `{GHC.Base.Ord inst_a} : (Seq\n                                                                inst_a) -> (Seq inst_a) -> (Seq inst_a) :=\n  fun x y => if Ord__Seq_op_zlze__ x y : bool then x else y.\n\nProgram Instance Ord__Seq {a} `{GHC.Base.Ord a} : GHC.Base.Ord (Seq a) := fun _\n                                                                              k =>\n    k {|GHC.Base.op_zl____ := Ord__Seq_op_zl__ ;\n      GHC.Base.op_zlze____ := Ord__Seq_op_zlze__ ;\n      GHC.Base.op_zg____ := Ord__Seq_op_zg__ ;\n      GHC.Base.op_zgze____ := Ord__Seq_op_zgze__ ;\n      GHC.Base.compare__ := Ord__Seq_compare ;\n      GHC.Base.max__ := Ord__Seq_max ;\n      GHC.Base.min__ := Ord__Seq_min |}.\n\nLocal Definition Eq___ViewR_op_zeze__ {inst_a} `{GHC.Base.Eq_ inst_a} : ViewR\n                                                                        inst_a -> ViewR inst_a -> bool :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__ , arg_1__ with\n      | EmptyR , EmptyR => true\n      | op_ZCzg__ a1 a2 , op_ZCzg__ b1 b2 => (andb ((a1 GHC.Base.== b1)) ((a2\n                                                   GHC.Base.== b2)))\n      | _ , _ => false\n    end.\n\nLocal Definition Eq___ViewL_op_zeze__ {inst_a} `{GHC.Base.Eq_ inst_a} : ViewL\n                                                                        inst_a -> ViewL inst_a -> bool :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__ , arg_1__ with\n      | EmptyL , EmptyL => true\n      | op_ZCzl__ a1 a2 , op_ZCzl__ b1 b2 => (andb ((a1 GHC.Base.== b1)) ((a2\n                                                   GHC.Base.== b2)))\n      | _ , _ => false\n    end.\n\nLocal Definition Eq___ViewL_op_zsze__ {inst_a} `{GHC.Base.Eq_ inst_a} : ViewL\n                                                                        inst_a -> ViewL inst_a -> bool :=\n  fun a b => negb (Eq___ViewL_op_zeze__ a b).\n\nProgram Instance Eq___ViewL {a} `{GHC.Base.Eq_ a} : GHC.Base.Eq_ (ViewL a) :=\n  fun _ k =>\n    k {|GHC.Base.op_zeze____ := Eq___ViewL_op_zeze__ ;\n      GHC.Base.op_zsze____ := Eq___ViewL_op_zsze__ |}.\n\nLocal Definition Eq___ViewR_op_zsze__ {inst_a} `{GHC.Base.Eq_ inst_a} : ViewR\n                                                                        inst_a -> ViewR inst_a -> bool :=\n  fun a b => negb (Eq___ViewR_op_zeze__ a b).\n\nProgram Instance Eq___ViewR {a} `{GHC.Base.Eq_ a} : GHC.Base.Eq_ (ViewR a) :=\n  fun _ k =>\n    k {|GHC.Base.op_zeze____ := Eq___ViewR_op_zeze__ ;\n      GHC.Base.op_zsze____ := Eq___ViewR_op_zsze__ |}.\n\nLocal Definition Ord__ViewR_compare {inst_a} `{GHC.Base.Ord inst_a} : ViewR\n                                                                      inst_a -> ViewR inst_a -> comparison :=\n  fun a b =>\n    match a with\n      | EmptyR => match b with\n                    | EmptyR => Eq\n                    | _ => Lt\n                  end\n      | op_ZCzg__ a1 a2 => match b with\n                             | op_ZCzg__ b1 b2 => match (GHC.Base.compare a1 b1) with\n                                                    | Lt => Lt\n                                                    | Eq => (GHC.Base.compare a2 b2)\n                                                    | Gt => Gt\n                                                  end\n                             | _ => Gt\n                           end\n    end.\n\nLocal Definition Ord__ViewL_compare {inst_a} `{GHC.Base.Ord inst_a} : ViewL\n                                                                      inst_a -> ViewL inst_a -> comparison :=\n  fun a b =>\n    match a with\n      | EmptyL => match b with\n                    | EmptyL => Eq\n                    | _ => Lt\n                  end\n      | op_ZCzl__ a1 a2 => match b with\n                             | op_ZCzl__ b1 b2 => match (GHC.Base.compare a1 b1) with\n                                                    | Lt => Lt\n                                                    | Eq => (GHC.Base.compare a2 b2)\n                                                    | Gt => Gt\n                                                  end\n                             | _ => Gt\n                           end\n    end.\n\nLocal Definition Ord__ViewR_op_zlze__ {inst_a} `{_ : GHC.Base.Ord inst_a}\n    : ViewR inst_a -> ViewR inst_a -> bool :=\n  fun a b =>\n    match a with\n      | EmptyR => match b with\n                    | EmptyR => true\n                    | _ => true\n                  end\n      | op_ZCzg__ a1 a2 => match b with\n                             | op_ZCzg__ b1 b2 => match GHC.Base.compare a1 b1 with\n                                                    | Lt => true\n                                                    | Eq => _GHC.Base.<=_ a2 b2\n                                                    | Gt => false\n                                                  end\n                             | _ => false\n                           end\n    end.\n\nDefinition Ord__ViewR_op_zl__ {inst_a} `{_ : GHC.Base.Ord inst_a} : ViewR\n                                                                    inst_a -> ViewR inst_a -> bool :=\n  fun a b =>\n    match a with\n      | EmptyR => match b with\n                    | EmptyR => false\n                    | _ => true\n                  end\n      | op_ZCzg__ a1 a2 => match b with\n                             | op_ZCzg__ b1 b2 => match GHC.Base.compare a1 b1 with\n                                                    | Lt => true\n                                                    | Eq => _GHC.Base.<_ a2 b2\n                                                    | Gt => false\n                                                  end\n                             | _ => false\n                           end\n    end.\n\nLocal Definition Ord__ViewR_op_zg__ {inst_a} `{_ : GHC.Base.Ord inst_a} : ViewR\n                                                                          inst_a -> ViewR inst_a -> bool :=\n  fun a b =>\n    match a with\n      | EmptyR => match b with\n                    | EmptyR => false\n                    | _ => false\n                  end\n      | op_ZCzg__ a1 a2 => match b with\n                             | op_ZCzg__ b1 b2 => match GHC.Base.compare a1 b1 with\n                                                    | Lt => false\n                                                    | Eq => _GHC.Base.>_ a2 b2\n                                                    | Gt => true\n                                                  end\n                             | _ => true\n                           end\n    end.\n\nLocal Definition Ord__ViewR_op_zgze__ {inst_a} `{_ : GHC.Base.Ord inst_a}\n    : ViewR inst_a -> ViewR inst_a -> bool :=\n  fun a b =>\n    match a with\n      | EmptyR => match b with\n                    | EmptyR => true\n                    | _ => false\n                  end\n      | op_ZCzg__ a1 a2 => match b with\n                             | op_ZCzg__ b1 b2 => match GHC.Base.compare a1 b1 with\n                                                    | Lt => false\n                                                    | Eq => _GHC.Base.>=_ a2 b2\n                                                    | Gt => true\n                                                  end\n                             | _ => true\n                           end\n    end.\n\nDefinition Ord__ViewL_op_zlze__ {inst_a} `{_ : GHC.Base.Ord inst_a} : ViewL\n                                                                      inst_a -> ViewL inst_a -> bool :=\n  fun a b =>\n    match a with\n      | EmptyL => match b with\n                    | EmptyL => true\n                    | _ => true\n                  end\n      | op_ZCzl__ a1 a2 => match b with\n                             | op_ZCzl__ b1 b2 => match GHC.Base.compare a1 b1 with\n                                                    | Lt => true\n                                                    | Eq => _GHC.Base.<=_ a2 b2\n                                                    | Gt => false\n                                                  end\n                             | _ => false\n                           end\n    end.\n\nDefinition Ord__ViewL_op_zl__ {inst_a} `{_ : GHC.Base.Ord inst_a} : ViewL\n                                                                    inst_a -> ViewL inst_a -> bool :=\n  fun a b =>\n    match a with\n      | EmptyL => match b with\n                    | EmptyL => false\n                    | _ => true\n                  end\n      | op_ZCzl__ a1 a2 => match b with\n                             | op_ZCzl__ b1 b2 => match GHC.Base.compare a1 b1 with\n                                                    | Lt => true\n                                                    | Eq => _GHC.Base.<_ a2 b2\n                                                    | Gt => false\n                                                  end\n                             | _ => false\n                           end\n    end.\n\nDefinition Ord__ViewL_op_zg__ {inst_a} `{_ : GHC.Base.Ord inst_a} : ViewL\n                                                                    inst_a -> ViewL inst_a -> bool :=\n  fun a b =>\n    match a with\n      | EmptyL => match b with\n                    | EmptyL => false\n                    | _ => false\n                  end\n      | op_ZCzl__ a1 a2 => match b with\n                             | op_ZCzl__ b1 b2 => match GHC.Base.compare a1 b1 with\n                                                    | Lt => false\n                                                    | Eq => _GHC.Base.>_ a2 b2\n                                                    | Gt => true\n                                                  end\n                             | _ => true\n                           end\n    end.\n\nDefinition Ord__ViewL_op_zgze__ {inst_a} `{_ : GHC.Base.Ord inst_a} : ViewL\n                                                                      inst_a -> ViewL inst_a -> bool :=\n  fun a b =>\n    match a with\n      | EmptyL => match b with\n                    | EmptyL => true\n                    | _ => false\n                  end\n      | op_ZCzl__ a1 a2 => match b with\n                             | op_ZCzl__ b1 b2 => match GHC.Base.compare a1 b1 with\n                                                    | Lt => false\n                                                    | Eq => _GHC.Base.>=_ a2 b2\n                                                    | Gt => true\n                                                  end\n                             | _ => true\n                           end\n    end.\n\nLocal Definition Ord__ViewL_max {inst_a} `{GHC.Base.Ord inst_a} : ViewL\n                                                                  inst_a -> ViewL inst_a -> ViewL inst_a :=\n  fun x y => if Ord__ViewL_op_zlze__ x y : bool then y else x.\n\nLocal Definition Ord__ViewL_min {inst_a} `{GHC.Base.Ord inst_a} : ViewL\n                                                                  inst_a -> ViewL inst_a -> ViewL inst_a :=\n  fun x y => if Ord__ViewL_op_zlze__ x y : bool then x else y.\n\nProgram Instance Ord__ViewL {a} `{GHC.Base.Ord a} : GHC.Base.Ord (ViewL a) :=\n  fun _ k =>\n    k {|GHC.Base.op_zl____ := Ord__ViewL_op_zl__ ;\n      GHC.Base.op_zlze____ := Ord__ViewL_op_zlze__ ;\n      GHC.Base.op_zg____ := Ord__ViewL_op_zg__ ;\n      GHC.Base.op_zgze____ := Ord__ViewL_op_zgze__ ;\n      GHC.Base.compare__ := Ord__ViewL_compare ;\n      GHC.Base.max__ := Ord__ViewL_max ;\n      GHC.Base.min__ := Ord__ViewL_min |}.\n\nLocal Definition Ord__ViewR_max {inst_a} `{GHC.Base.Ord inst_a} : ViewR\n                                                                  inst_a -> ViewR inst_a -> ViewR inst_a :=\n  fun x y => if Ord__ViewR_op_zlze__ x y : bool then y else x.\n\nLocal Definition Ord__ViewR_min {inst_a} `{GHC.Base.Ord inst_a} : ViewR\n                                                                  inst_a -> ViewR inst_a -> ViewR inst_a :=\n  fun x y => if Ord__ViewR_op_zlze__ x y : bool then x else y.\n\nProgram Instance Ord__ViewR {a} `{GHC.Base.Ord a} : GHC.Base.Ord (ViewR a) :=\n  fun _ k =>\n    k {|GHC.Base.op_zl____ := Ord__ViewR_op_zl__ ;\n      GHC.Base.op_zlze____ := Ord__ViewR_op_zlze__ ;\n      GHC.Base.op_zg____ := Ord__ViewR_op_zg__ ;\n      GHC.Base.op_zgze____ := Ord__ViewR_op_zgze__ ;\n      GHC.Base.compare__ := Ord__ViewR_compare ;\n      GHC.Base.max__ := Ord__ViewR_max ;\n      GHC.Base.min__ := Ord__ViewR_min |}.\n\nProgram Instance Traversable__Seq : Data.Traversable.Traversable Seq := fun _\n                                                                            k =>\n    k {|Data.Traversable.mapM__ := fun {m} {a} {b} `{GHC.Base.Monad m} =>\n        Traversable__Seq_mapM ;\n      Data.Traversable.sequence__ := fun {m} {a} `{GHC.Base.Monad m} =>\n        Traversable__Seq_sequence ;\n      Data.Traversable.sequenceA__ := fun {f} {a} `{GHC.Base.Applicative f} =>\n        Traversable__Seq_sequenceA ;\n      Data.Traversable.traverse__ := fun {f} {a} {b} `{GHC.Base.Applicative f} =>\n        Traversable__Seq_traverse |}.\n\nDefinition scanl {a} {b} : (a -> b -> a) -> a -> Seq b -> Seq a :=\n  fun f z0 xs =>\n    z0 <| Data.Tuple.snd (Data.Traversable.mapAccumL (fun x z =>\n                                                       let x' := f x z in pair x' x') z0 xs).\n\nLocal Definition Functor__ViewL_fmap : forall {a} {b},\n                                         (a -> b) -> ViewL a -> ViewL b :=\n  fun {a} {b} =>\n    fun arg_0__ arg_1__ =>\n      match arg_0__ , arg_1__ with\n        | _ , EmptyL => EmptyL\n        | f , op_ZCzl__ x xs => f x :< GHC.Base.fmap f xs\n      end.\n\nLocal Definition Functor__ViewL_op_zlzd__ : forall {a} {b},\n                                              a -> ViewL b -> ViewL a :=\n  fun {a} {b} => fun x => Functor__ViewL_fmap (GHC.Base.const x).\n\nProgram Instance Functor__ViewL : GHC.Base.Functor ViewL := fun _ k =>\n    k {|GHC.Base.op_zlzd____ := fun {a} {b} => Functor__ViewL_op_zlzd__ ;\n      GHC.Base.fmap__ := fun {a} {b} => Functor__ViewL_fmap |}.\n\nLocal Definition Functor__ViewR_fmap : forall {a} {b},\n                                         (a -> b) -> ViewR a -> ViewR b :=\n  fun {a} {b} =>\n    fun arg_0__ arg_1__ =>\n      match arg_0__ , arg_1__ with\n        | _ , EmptyR => EmptyR\n        | f , op_ZCzg__ xs x => GHC.Base.fmap f xs :> f x\n      end.\n\nLocal Definition Traversable__ViewL_traverse : forall {f} {a} {b},\n                                                 forall `{GHC.Base.Applicative f},\n                                                   (a -> f b) -> ViewL a -> f (ViewL b) :=\n  fun {f} {a} {b} `{GHC.Base.Applicative f} =>\n    fun arg_0__ arg_1__ =>\n      match arg_0__ , arg_1__ with\n        | _ , EmptyL => GHC.Base.pure EmptyL\n        | f , op_ZCzl__ x xs => (_:<_ Data.Functor.<$> f x) GHC.Base.<*>\n                                Data.Traversable.traverse f xs\n      end.\n\nLocal Definition Foldable__ViewL_foldr : forall {a} {b},\n                                           (a -> b -> b) -> b -> ViewL a -> b :=\n  fun {a} {b} =>\n    fun arg_0__ arg_1__ arg_2__ =>\n      match arg_0__ , arg_1__ , arg_2__ with\n        | _ , z , EmptyL => z\n        | f , z , op_ZCzl__ x xs => f x (Data.Foldable.foldr f z xs)\n      end.\n\nLocal Definition Foldable__ViewL_foldl : forall {b} {a},\n                                           (b -> a -> b) -> b -> ViewL a -> b :=\n  fun {b} {a} =>\n    fun arg_0__ arg_1__ arg_2__ =>\n      match arg_0__ , arg_1__ , arg_2__ with\n        | _ , z , EmptyL => z\n        | f , z , op_ZCzl__ x xs => Data.Foldable.foldl f (f z x) xs\n      end.\n\n\nLocal Definition Functor__ViewR_op_zlzd__ : forall {a} {b},\n                                              a -> ViewR b -> ViewR a :=\n  fun {a} {b} => fun x => Functor__ViewR_fmap (GHC.Base.const x).\n\nProgram Instance Functor__ViewR : GHC.Base.Functor ViewR := fun _ k =>\n    k {|GHC.Base.op_zlzd____ := fun {a} {b} => Functor__ViewR_op_zlzd__ ;\n      GHC.Base.fmap__ := fun {a} {b} => Functor__ViewR_fmap |}.\n\nLocal Definition Foldable__ViewR_foldMap : forall {m} {a},\n                                             forall `{GHC.Base.Monoid m}, (a -> m) -> ViewR a -> m :=\n  fun {m} {a} `{GHC.Base.Monoid m} =>\n    fun arg_0__ arg_1__ =>\n      match arg_0__ , arg_1__ with\n        | _ , EmptyR => GHC.Base.mempty\n        | f , op_ZCzg__ xs x => GHC.Base.mappend (Data.Foldable.foldMap f xs) (f x)\n      end.\n\nLocal Definition Foldable__ViewR_foldl : forall {b} {a},\n                                           (b -> a -> b) -> b -> ViewR a -> b :=\n  fun {b} {a} =>\n    fun arg_0__ arg_1__ arg_2__ =>\n      match arg_0__ , arg_1__ , arg_2__ with\n        | _ , z , EmptyR => z\n        | f , z , op_ZCzg__ xs x => f (Data.Foldable.foldl f z xs) x\n      end.\n\nLocal Definition Foldable__ViewR_foldr : forall {a} {b},\n                                           (a -> b -> b) -> b -> ViewR a -> b :=\n  fun {a} {b} =>\n    fun arg_0__ arg_1__ arg_2__ =>\n      match arg_0__ , arg_1__ , arg_2__ with\n        | _ , z , EmptyR => z\n        | f , z , op_ZCzg__ xs x => Data.Foldable.foldr f (f x z) xs\n      end.\n\nLocal Definition Traversable__ViewR_traverse : forall {f} {a} {b},\n                                                 forall `{GHC.Base.Applicative f},\n                                                   (a -> f b) -> ViewR a -> f (ViewR b) :=\n  fun {f} {a} {b} `{GHC.Base.Applicative f} =>\n    fun arg_0__ arg_1__ =>\n      match arg_0__ , arg_1__ with\n        | _ , EmptyR => GHC.Base.pure EmptyR\n        | f , op_ZCzg__ xs x => (_:>_ Data.Functor.<$> Data.Traversable.traverse f xs)\n                                GHC.Base.<*> f x\n      end.\n\nLocal Definition Traversable__ViewR_sequenceA : forall {f} {a},\n                                                  forall `{GHC.Base.Applicative f}, ViewR (f a) -> f (ViewR a) :=\n  fun {f} {a} `{GHC.Base.Applicative f} =>\n    Traversable__ViewR_traverse GHC.Base.id.\n\nLocal Definition Traversable__ViewR_sequence : forall {m} {a},\n                                                 forall `{GHC.Base.Monad m}, ViewR (m a) -> m (ViewR a) :=\n  fun {m} {a} `{GHC.Base.Monad m} => Traversable__ViewR_sequenceA.\n\nLocal Definition Traversable__ViewR_mapM : forall {m} {a} {b},\n                                             forall `{GHC.Base.Monad m}, (a -> m b) -> ViewR a -> m (ViewR b) :=\n  fun {m} {a} {b} `{GHC.Base.Monad m} => Traversable__ViewR_traverse.\n\n\nLocal Definition Foldable__ViewR_toList : forall {a}, ViewR a -> list a :=\n  fun {a} =>\n    fun arg_54__ =>\n      match arg_54__ with\n        | t => GHC.Base.build (fun arg_55__ arg_56__ =>\n                                match arg_55__ , arg_56__ with\n                                  | c , n => Foldable__ViewR_foldr c n t\n                                end)\n      end.\n\nLocal Definition Foldable__ViewR_foldl' : forall {b} {a},\n                                            (b -> a -> b) -> b -> ViewR a -> b :=\n  fun {b} {a} =>\n    fun arg_24__ arg_25__ arg_26__ =>\n      match arg_24__ , arg_25__ , arg_26__ with\n        | f , z0 , xs => let f' :=\n                           fun arg_27__ arg_28__ arg_29__ =>\n                             match arg_27__ , arg_28__ , arg_29__ with\n                               | x , k , z => _GHC.Base.$!_ k (f z x)\n                             end in\n                         Foldable__ViewR_foldr f' GHC.Base.id xs z0\n      end.\n\nLocal Definition Foldable__ViewR_foldr' : forall {a} {b},\n                                            (a -> b -> b) -> b -> ViewR a -> b :=\n  fun {a} {b} =>\n    fun arg_9__ arg_10__ arg_11__ =>\n      match arg_9__ , arg_10__ , arg_11__ with\n        | f , z0 , xs => let f' :=\n                           fun arg_12__ arg_13__ arg_14__ =>\n                             match arg_12__ , arg_13__ , arg_14__ with\n                               | k , x , z => _GHC.Base.$!_ k (f x z)\n                             end in\n                         Foldable__ViewR_foldl f' GHC.Base.id xs z0\n      end.\n\nLocal Definition Foldable__ViewR_length : forall {a}, ViewR a -> GHC.Num.Int :=\n  fun {a} v =>\n    Z.of_nat (Foldable__ViewR_foldr' (fun arg_0__ arg_1__ =>\n                             match arg_0__ , arg_1__ with\n                               | _ , k => k + id 1\n                             end) (id 0) v).\n\nLocal Definition Foldable__ViewR_product : forall {a},\n                                             forall `{GHC.Num.Num a}, ViewR a -> a :=\n  fun {a} `{GHC.Num.Num a} =>\n    Data.Foldable.hash_compose Data.Monoid.getProduct (Foldable__ViewR_foldMap\n                               Data.Monoid.Mk_Product).\n\nLocal Definition Foldable__ViewR_sum : forall {a},\n                                         forall `{GHC.Num.Num a}, ViewR a -> a :=\n  fun {a} `{GHC.Num.Num a} =>\n    Data.Foldable.hash_compose Data.Monoid.getSum (Foldable__ViewR_foldMap\n                               Data.Monoid.Mk_Sum).\n\nLocal Definition Foldable__ViewR_fold : forall {m},\n                                          forall `{GHC.Base.Monoid m}, ViewR m -> m :=\n  fun {m} `{GHC.Base.Monoid m} => Foldable__ViewR_foldMap GHC.Base.id.\n\nLocal Definition Foldable__ViewR_elem : forall {a},\n                                          forall `{GHC.Base.Eq_ a}, a -> ViewR a -> bool :=\n  fun {a} `{GHC.Base.Eq_ a} =>\n    Coq.Program.Basics.compose (fun arg_69__ =>\n                                 match arg_69__ with\n                                   | p => Coq.Program.Basics.compose Data.Monoid.getAny (Foldable__ViewR_foldMap\n                                                                     (Coq.Program.Basics.compose Data.Monoid.Mk_Any p))\n                                 end) _GHC.Base.==_.\n\nProgram Instance Foldable__ViewR : Data.Foldable.Foldable ViewR := fun _ k =>\n    k {|Data.Foldable.elem__ := fun {a} `{GHC.Base.Eq_ a} => Foldable__ViewR_elem ;\n      Data.Foldable.fold__ := fun {m} `{GHC.Base.Monoid m} => Foldable__ViewR_fold ;\n      Data.Foldable.foldMap__ := fun {m} {a} `{GHC.Base.Monoid m} =>\n        Foldable__ViewR_foldMap ;\n      Data.Foldable.foldl__ := fun {b} {a} => Foldable__ViewR_foldl ;\n      Data.Foldable.foldl'__ := fun {b} {a} => Foldable__ViewR_foldl' ;\n      Data.Foldable.foldr__ := fun {a} {b} => Foldable__ViewR_foldr ;\n      Data.Foldable.foldr'__ := fun {a} {b} => Foldable__ViewR_foldr' ;\n      Data.Foldable.length__ := fun {a} => Foldable__ViewR_length ;\n      Data.Foldable.null__ := fun {a} => Foldable__ViewR_null ;\n      Data.Foldable.product__ := fun {a} `{GHC.Num.Num a} => Foldable__ViewR_product ;\n      Data.Foldable.sum__ := fun {a} `{GHC.Num.Num a} => Foldable__ViewR_sum ;\n      Data.Foldable.toList__ := fun {a} => Foldable__ViewR_toList |}.\n\nProgram Instance Traversable__ViewR : Data.Traversable.Traversable ViewR :=\n  fun _ k =>\n    k {|Data.Traversable.mapM__ := fun {m} {a} {b} `{GHC.Base.Monad m} =>\n        Traversable__ViewR_mapM ;\n      Data.Traversable.sequence__ := fun {m} {a} `{GHC.Base.Monad m} =>\n        Traversable__ViewR_sequence ;\n      Data.Traversable.sequenceA__ := fun {f} {a} `{GHC.Base.Applicative f} =>\n        Traversable__ViewR_sequenceA ;\n      Data.Traversable.traverse__ := fun {f} {a} {b} `{GHC.Base.Applicative f} =>\n        Traversable__ViewR_traverse |}.\n\n\nLocal Definition Traversable__ViewL_sequenceA : forall {f} {a},\n                                                  forall `{GHC.Base.Applicative f}, ViewL (f a) -> f (ViewL a) :=\n  fun {f} {a} `{GHC.Base.Applicative f} =>\n    Traversable__ViewL_traverse GHC.Base.id.\n\nLocal Definition Traversable__ViewL_sequence : forall {m} {a},\n                                                 forall `{GHC.Base.Monad m}, ViewL (m a) -> m (ViewL a) :=\n  fun {m} {a} `{GHC.Base.Monad m} => Traversable__ViewL_sequenceA.\n\nLocal Definition Traversable__ViewL_mapM : forall {m} {a} {b},\n                                             forall `{GHC.Base.Monad m}, (a -> m b) -> ViewL a -> m (ViewL b) :=\n  fun {m} {a} {b} `{GHC.Base.Monad m} => Traversable__ViewL_traverse.\n\n\nLocal Definition Foldable__ViewL_null : forall {a}, ViewL a -> bool :=\n  fun {a} => Foldable__ViewL_foldr (fun arg_61__ arg_62__ => false) true.\n\nLocal Definition Foldable__ViewL_toList : forall {a}, ViewL a -> list a :=\n  fun {a} =>\n    fun arg_54__ =>\n      match arg_54__ with\n        | t => GHC.Base.build (fun arg_55__ arg_56__ =>\n                                match arg_55__ , arg_56__ with\n                                  | c , n => Foldable__ViewL_foldr c n t\n                                end)\n      end.\n\nLocal Definition Foldable__ViewL_foldl' : forall {b} {a},\n                                            (b -> a -> b) -> b -> ViewL a -> b :=\n  fun {b} {a} =>\n    fun arg_24__ arg_25__ arg_26__ =>\n      match arg_24__ , arg_25__ , arg_26__ with\n        | f , z0 , xs => let f' :=\n                           fun arg_27__ arg_28__ arg_29__ =>\n                             match arg_27__ , arg_28__ , arg_29__ with\n                               | x , k , z => _GHC.Base.$!_ k (f z x)\n                             end in\n                         Foldable__ViewL_foldr f' GHC.Base.id xs z0\n      end.\n\nLocal Definition Foldable__ViewL_length : forall {a}, ViewL a -> GHC.Num.Int :=\n  fun {a} v =>\n    Z.of_nat (Foldable__ViewL_foldl' (fun arg_64__ arg_65__ =>\n                             match arg_64__ , arg_65__ with\n                               | c , _ => c + 1\n                             end) (id 0) v).\n\nLocal Definition Foldable__ViewL_foldMap : forall {m} {a},\n                                             forall `{GHC.Base.Monoid m}, (a -> m) -> ViewL a -> m :=\n  fun {m} {a} `{GHC.Base.Monoid m} =>\n    fun arg_1__ =>\n      match arg_1__ with\n        | f => Foldable__ViewL_foldr (Coq.Program.Basics.compose GHC.Base.mappend f)\n               GHC.Base.mempty\n      end.\n\nLocal Definition Foldable__ViewL_product : forall {a},\n                                             forall `{GHC.Num.Num a}, ViewL a -> a :=\n  fun {a} `{GHC.Num.Num a} =>\n    Data.Foldable.hash_compose Data.Monoid.getProduct (Foldable__ViewL_foldMap\n                               Data.Monoid.Mk_Product).\n\nLocal Definition Foldable__ViewL_sum : forall {a},\n                                         forall `{GHC.Num.Num a}, ViewL a -> a :=\n  fun {a} `{GHC.Num.Num a} =>\n    Data.Foldable.hash_compose Data.Monoid.getSum (Foldable__ViewL_foldMap\n                               Data.Monoid.Mk_Sum).\n\nLocal Definition Foldable__ViewL_fold : forall {m},\n                                          forall `{GHC.Base.Monoid m}, ViewL m -> m :=\n  fun {m} `{GHC.Base.Monoid m} => Foldable__ViewL_foldMap GHC.Base.id.\n\nLocal Definition Foldable__ViewL_elem : forall {a},\n                                          forall `{GHC.Base.Eq_ a}, a -> ViewL a -> bool :=\n  fun {a} `{GHC.Base.Eq_ a} =>\n    Coq.Program.Basics.compose (fun arg_69__ =>\n                                 match arg_69__ with\n                                   | p => Coq.Program.Basics.compose Data.Monoid.getAny (Foldable__ViewL_foldMap\n                                                                     (Coq.Program.Basics.compose Data.Monoid.Mk_Any p))\n                                 end) _GHC.Base.==_.\n\nLocal Definition Foldable__ViewL_foldr' : forall {a} {b},\n                                            (a -> b -> b) -> b -> ViewL a -> b :=\n  fun {a} {b} =>\n    fun arg_9__ arg_10__ arg_11__ =>\n      match arg_9__ , arg_10__ , arg_11__ with\n        | f , z0 , xs => let f' :=\n                           fun arg_12__ arg_13__ arg_14__ =>\n                             match arg_12__ , arg_13__ , arg_14__ with\n                               | k , x , z => _GHC.Base.$!_ k (f x z)\n                             end in\n                         Foldable__ViewL_foldl f' GHC.Base.id xs z0\n      end.\n\nProgram Instance Foldable__ViewL : Data.Foldable.Foldable ViewL := fun _ k =>\n    k {|Data.Foldable.elem__ := fun {a} `{GHC.Base.Eq_ a} => Foldable__ViewL_elem ;\n      Data.Foldable.fold__ := fun {m} `{GHC.Base.Monoid m} => Foldable__ViewL_fold ;\n      Data.Foldable.foldMap__ := fun {m} {a} `{GHC.Base.Monoid m} =>\n        Foldable__ViewL_foldMap ;\n      Data.Foldable.foldl__ := fun {b} {a} => Foldable__ViewL_foldl ;\n      Data.Foldable.foldl'__ := fun {b} {a} => Foldable__ViewL_foldl' ;\n      Data.Foldable.foldr__ := fun {a} {b} => Foldable__ViewL_foldr ;\n      Data.Foldable.foldr'__ := fun {a} {b} => Foldable__ViewL_foldr' ;\n      Data.Foldable.length__ := fun {a} => Foldable__ViewL_length ;\n      Data.Foldable.null__ := fun {a} => Foldable__ViewL_null ;\n      Data.Foldable.product__ := fun {a} `{GHC.Num.Num a} => Foldable__ViewL_product ;\n      Data.Foldable.sum__ := fun {a} `{GHC.Num.Num a} => Foldable__ViewL_sum ;\n      Data.Foldable.toList__ := fun {a} => Foldable__ViewL_toList |}.\n\nProgram Instance Traversable__ViewL : Data.Traversable.Traversable ViewL :=\n  fun _ k =>\n    k {|Data.Traversable.mapM__ := fun {m} {a} {b} `{GHC.Base.Monad m} =>\n        Traversable__ViewL_mapM ;\n      Data.Traversable.sequence__ := fun {m} {a} `{GHC.Base.Monad m} =>\n        Traversable__ViewL_sequence ;\n      Data.Traversable.sequenceA__ := fun {f} {a} `{GHC.Base.Applicative f} =>\n        Traversable__ViewL_sequenceA ;\n      Data.Traversable.traverse__ := fun {f} {a} {b} `{GHC.Base.Applicative f} =>\n        Traversable__ViewL_traverse |}.\n\nDefinition fromList2 {a} : nat -> list a -> Seq a :=\n  fun n =>\n    let ht :=\n      fun arg_0__ =>\n        match arg_0__ with\n          | cons x xs => pair xs x\n          | nil => error (GHC.Base.hs_string__ \"fromList2: short list\")\n        end in\n    execState (replicateA n (Mk_State ht)).\n\nDefinition sortBy {a} : (a -> a -> comparison) -> Seq a -> Seq a :=\n  fun cmp xs =>\n    fromList2 (length xs) (Data.OldList.sortBy cmp (Data.Foldable.toList xs)).\n\nDefinition sort {a} `{GHC.Base.Ord a} : Seq a -> Seq a :=\n  sortBy GHC.Base.compare.\n\n(*\nProgram Fixpoint unrollPQ {e} (cmp : e -> e -> comparison) (pq : PQueue e)  {measure (size pq)} : list e :=\n    let mergePQs0 mergePQs :=\n      fun arg_4__ =>\n        match arg_4__ with\n          | Nil => nil\n          | op_ZCza__ t Nil => unrollPQ cmp t\n          | op_ZCza__ t1 (op_ZCza__ t2 ts) => mergePQs (mergePQ cmp t1 t2) ts\n        end in\n    let fix mergePQs t ts :=\n        (match ts with\n         | Nil => unrollPQ cmp t\n         | op_ZCza__ t1 Nil => unrollPQ cmp (mergePQ cmp t t1)\n         | op_ZCza__ t1 (op_ZCza__ t2 ts') => mergePQs (mergePQ cmp t (mergePQ cmp t1 t2)) ts'\n         end) in\n    match pq with\n    | Mk_PQueue x ts => cons x (mergePQs0 mergePQs ts)\n    end.\n\n\nDefinition toPQ {e} {a} : (e -> e -> comparison) -> (a -> PQueue e) -> FingerTree a -> option (PQueue e) :=\n  fix toPQ arg_0__ arg_1__ arg_2__\n        := match arg_0__ , arg_1__ , arg_2__ with\n             | _ , _ , Empty => None\n             | _ , f , Single x => Some (f x)\n             | cmp , f , Deep _ pr m sf => let lop_zlzpzg__ := mergePQ cmp in\n                                           let fDigit :=\n                                             fun digit =>\n                                               match GHC.Base.fmap f digit with\n                                                 | One a => a\n                                                 | Two a b => mergePQ cmp a b\n                                                 | Three a b c => mergePQ cmp (mergePQ cmp a b) c\n                                                 | Four a b c d => mergePQ cmp (mergePQ cmp a b) (mergePQ cmp c d)\n                                               end in\n                                           let fNode := fDigit GHC.Base.∘ nodeToDigit in\n                                           let pr' := fDigit pr in\n                                           let sf' := fDigit sf in\n                                           Some (Data.Maybe.maybe (mergePQ cmp pr' sf') (fun arg_14__ =>\n                                                                                           mergePQ cmp (mergePQ cmp\n                                                                                                        pr' sf')\n                                                                                                        arg_14__) (toPQ\n                                                                                                                  cmp\n                                                                                                                  fNode\n                                                                                                                  m))\n           end.\n\n\nDefinition unstableSortBy {a} : (a -> a -> comparison) -> Seq a -> Seq a :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__ , arg_1__ with\n      | cmp , Mk_Seq xs => fromList2 (size xs) GHC.Base.$ (Data.Maybe.maybe nil\n                           (unrollPQ cmp) GHC.Base.$ toPQ cmp (fun arg_2__ =>\n                                                                match arg_2__ with\n                                                                  | Mk_Elem x => Mk_PQueue x Nil\n                                                                end) xs)\n    end.\n\nDefinition unstableSort {a} `{GHC.Base.Ord a} : Seq a -> Seq a :=\n  unstableSortBy GHC.Base.compare.\n*)\n\nDefinition iterateN {a} : nat -> (a -> a) -> a -> Seq a :=\n  fun n f x =>\n    if negb (Nat.ltb n 0) : bool\n    then execState (replicateA n (Mk_State (fun y => pair (f y) y))) x\n    else error (GHC.Base.hs_string__\n               \"iterateN takes a nonnegative integer argument\").\n\nDefinition reverseDigit {a} : (a -> a) -> Digit a -> Digit a :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__ , arg_1__ with\n      | f , One a => One (f a)\n      | f , Two a b => Two (f b) (f a)\n      | f , Three a b c => Three (f c) (f b) (f a)\n      | f , Four a b c d => Four (f d) (f c) (f b) (f a)\n    end.\n\nDefinition reverseNode {a} : (a -> a) -> Node a -> Node a :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__ , arg_1__ with\n      | f , Node2 s a b => Node2 s (f b) (f a)\n      | f , Node3 s a b c => Node3 s (f c) (f b) (f a)\n    end.\n\n(* polyrec *)\nDefinition reverseTree : forall {a}, (a -> a) -> FingerTree a -> FingerTree a :=\n  fix reverseTree {a} arg_0__ arg_1__\n        := match arg_0__ , arg_1__ with\n             | _ , Empty => Empty\n             | f , Single x => Single (f x)\n             | f , Deep s pr m sf => Deep s (reverseDigit f sf) (reverseTree (reverseNode f)\n                                                                m) (reverseDigit f pr)\n           end.\n\nDefinition reverse {a} : Seq a -> Seq a :=\n  fun arg_0__ =>\n    match arg_0__ with\n      | Mk_Seq xs => Mk_Seq (reverseTree GHC.Base.id xs)\n    end.\n\nDefinition singleton {a} : a -> Seq a :=\n  fun x => Mk_Seq (Single (Mk_Elem x)).\n\nLocal Definition Applicative__Seq_pure : forall {a}, a -> Seq a :=\n  fun {a} => singleton.\n\nFixpoint snocTree {a} `{_ : Sized a} (arg_0__ : FingerTree a) (arg_1__ : a)\n           : FingerTree a\n           := match arg_0__ , arg_1__ with\n                | Empty , a => Single a\n                | Single a , b => deep (One a) Empty (One b)\n                | Deep s pr m (Four a b c d) , e => GHC.Prim.seq m (Deep (s + (size\n                                                                                      e)) pr (snocTree m (node3 a b c))\n                                                                         (Two d e))\n                | Deep s pr m (Three a b c) , d => Deep (s + (size d)) pr m (Four a b\n                                                                                            c d)\n                | Deep s pr m (Two a b) , c => Deep (s + (size c)) pr m (Three a b c)\n                | Deep s pr m (One a) , b => Deep (s + (size b)) pr m (Two a b)\n              end.\n\nDefinition op_zbzg__ {a} : Seq a -> a -> Seq a :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__ , arg_1__ with\n      | Mk_Seq xs , x => Mk_Seq (snocTree xs (Mk_Elem x))\n    end.\n\nNotation \"'_|>_'\" := (op_zbzg__).\n\nInfix \"|>\" := (_|>_) (at level 99).\n\nDefinition scanr {a} {b} : (a -> b -> b) -> b -> Seq a -> Seq b :=\n  fun f z0 xs =>\n    Data.Tuple.snd (Data.Traversable.mapAccumR (fun z x =>\n                                                 let z' := f x z in pair z' z') z0 xs) |> z0.\n\nDefinition filter {a} : (a -> bool) -> Seq a -> Seq a :=\n  fun p =>\n    Data.Foldable.foldl (fun xs x => if p x : bool then xs |> x else xs) empty.\n\nDefinition partition {a} : (a -> bool) -> Seq a -> (Seq a * Seq a)%type :=\n  fun p =>\n    let part :=\n      fun arg_0__ arg_1__ =>\n        match arg_0__ , arg_1__ with\n          | pair xs ys , x => if p x : bool\n                              then pair (xs |> x) ys\n                              else pair xs (ys |> x)\n        end in\n    Data.Foldable.foldl part (pair empty empty).\n\n(*\nDefinition unfoldr {b} {a} : (b -> option (a * b)%type) -> b -> Seq a :=\n  fun f =>\n    let fix unfoldr' as_ b\n              := Data.Maybe.maybe as_ (fun arg_0__ =>\n                                        match arg_0__ with\n                                          | pair a b' => unfoldr' (as_ |> a) b'\n                                        end) (f b) in\n    unfoldr' empty.\n*)\n\nDefinition thin12 {a} `{Sized a} thin (s  : nat) (pr : Digit12 a) (m: FingerTree (Node a))\n         (dd: Digit a) : Thin a :=\n    match dd with\n      | One a => DeepTh s pr (thin m) (One12 a)\n      | Two a b => DeepTh s pr (thin m) (Two12 a b)\n      | Three a b c => DeepTh s pr (thin (snocTree m (node2 a b))) (One12 c)\n      | Four a b c d => DeepTh s pr (thin (snocTree m (node2 a b))) (Two12 c d)\n    end.\n\n\nProgram Fixpoint thin {a} `{Sized a} (ft : FingerTree a) { measure  (size ft) } : Thin a :=\n    let thin12 {a} `{Sized a} (s  : nat) (pr : Digit12 a) (m: FingerTree (Node a)) (dd: Digit a) : Thin a :=\n    match dd with\n      | One a => DeepTh s pr (thin m) (One12 a)\n      | Two a b => DeepTh s pr (thin m) (Two12 a b)\n      | Three a b c => DeepTh s pr (thin (snocTree m (node2 a b))) (One12 c)\n      | Four a b c d => DeepTh s pr (thin (snocTree m (node2 a b))) (Two12 c d)\n    end in\n    (match ft with\n      | Empty => EmptyTh\n      | Single a => SingleTh a\n      | Deep s pr m sf =>\n        match pr with\n        | One a => thin12 s (One12 a) m sf\n        | Two a b => thin12 s (Two12 a b) m sf\n        | Three a b c => thin12 s (One12 a) (consTree (node2 b c) m) sf\n        | Four a b c d => thin12 s (Two12 a b) (consTree (node2 c d) m) sf\n        end\n    end).\nNext Obligation.\nunfold size, Sized__FingerTree, size__, Sized__FingerTree_size.\nAdmitted.\nNext Obligation.\nAdmitted.\nNext Obligation.\nAdmitted.\nNext Obligation.\nAdmitted.\n\n\nDefinition rigidifyRight {a} : nat -> Digit23 (Elem a) -> FingerTree\n                               (Node (Elem a)) -> Digit (Elem a) -> Rigidified (Elem a) :=\n  fun arg_0__ arg_1__ arg_2__ arg_3__ =>\n    match arg_0__ , arg_1__ , arg_2__ , arg_3__ with\n      | s , pr , m , Two a b => RigidFull GHC.Base.$ Mk_Rigid s pr (thin m) (node2 a b)\n      | s , pr , m , Three a b c => RigidFull GHC.Base.$ Mk_Rigid s pr (thin m) (node3\n                                                                                a b c)\n      | s , pr , m , Four a b c d => RigidFull GHC.Base.$ Mk_Rigid s pr (thin\n                                                                        GHC.Base.$ snocTree m (node2 a b)) (node2 c d)\n      | s , pr , m , One e => match viewRTree m with\n                                | Just2 m' (Node2 _ a b) => RigidFull GHC.Base.$ Mk_Rigid s pr (thin m') (node3\n                                                                                                         a b e)\n                                | Just2 m' (Node3 _ a b c) => RigidFull GHC.Base.$ Mk_Rigid s pr (thin\n                                                                                                 GHC.Base.$ snocTree m'\n                                                                                                                     (node2\n                                                                                                                     a\n                                                                                                                     b))\n                                                              (node2 c e)\n                                | Nothing2 => match pr with\n                                                | Node2 _ a b => RigidThree a b e\n                                                | Node3 _ a b c => RigidFull GHC.Base.$ Mk_Rigid s (node2 a b) EmptyTh\n                                                                   (node2 c e)\n                                              end\n                              end\n    end.\n\nDefinition rigidify {a} : FingerTree (Elem a) -> Rigidified (Elem a) :=\n  fun arg_0__ =>\n    match arg_0__ with\n      | Empty => RigidEmpty\n      | Single q => RigidOne q\n      | Deep s (Two a b) m sf => rigidifyRight s (node2 a b) m sf\n      | Deep s (Three a b c) m sf => rigidifyRight s (node3 a b c) m sf\n      | Deep s (Four a b c d) m sf => rigidifyRight s (node2 a b) (consTree (node2 c\n                                                                            d) m) sf\n      | Deep s (One a) m sf => match viewLTree m with\n                                 | Just2 (Node2 _ b c) m' => rigidifyRight s (node3 a b c) m' sf\n                                 | Just2 (Node3 _ b c d) m' => rigidifyRight s (node2 a b) (consTree (node2 c d)\n                                                                                                     m') sf\n                                 | Nothing2 => match sf with\n                                                 | One b => RigidTwo a b\n                                                 | Two b c => RigidThree a b c\n                                                 | Three b c d => RigidFull GHC.Base.$ Mk_Rigid s (node2 a b) EmptyTh\n                                                                  (node2 c d)\n                                                 | Four b c d e => RigidFull GHC.Base.$ Mk_Rigid s (node3 a b c) EmptyTh\n                                                                   (node2 d e)\n                                               end\n                               end\n    end.\n\nParameter rigid_metric : forall {c}, Rigid c -> nat.\n\nProgram Fixpoint cycleNMiddle {c} (n:nat) (r : Rigid c) {measure (rigid_metric r)} : FingerTree (Node c) :=\n  match r with\n  | Mk_Rigid s pr (DeepTh sm prm mm sfm) sf =>\n    Deep (sm + (s * (n + 1)))  (* -- note: sm = s - size pr - size sf *)\n         (digit12ToDigit prm)\n         (cycleNMiddle n (Mk_Rigid s (squashL pr prm) mm (squashR sfm sf)))\n         (digit12ToDigit sfm)\n  | Mk_Rigid s pr EmptyTh sf =>\n    let converted := node2 pr sf in\n    deep (One sf) (runIdentity GHC.Base.$ applicativeTree n s\n                               (Data.Functor.Identity.Mk_Identity converted)) (One pr)\n  | Mk_Rigid s pr (SingleTh q) sf =>\n    let converted := node3 pr q sf in\n    deep (Two q sf) (runIdentity GHC.Base.$ applicativeTree n s\n                                 (Data.Functor.Identity.Mk_Identity converted))\n         (Two pr q)\n  end.\nNext Obligation.\nAdmitted.\n\n\nDefinition cycleN {a} : nat -> Seq a -> Seq a :=\n  fun arg_0__ arg_1__ =>\n    let j_11__ :=\n      match arg_0__ , arg_1__ with\n        | n , Mk_Seq xsFT => match rigidify xsFT with\n                               | RigidEmpty => empty\n                               | RigidOne (Mk_Elem x) => replicate n x\n                               | RigidTwo x1 x2 => let pair_ := Two x1 x2 in\n                                                   Mk_Seq GHC.Base.$ Deep (n * id 2) pair_\n                                                   (runIdentity GHC.Base.$ applicativeTree (n -\n                                                                                           id 2)\n                                                   (id 2) (Data.Functor.Identity.Mk_Identity (node2 x1\n                                                                                                              x2)))\n                                                   pair_\n                               | RigidThree x1 x2 x3 => let triple := Three x1 x2 x3 in\n                                                        Mk_Seq GHC.Base.$ Deep (n * id 3)\n                                                        triple (runIdentity GHC.Base.$ applicativeTree (n -\n                                                                                                       id\n                                                                                                       2)\n                                                               (id 3)\n                                                               (Data.Functor.Identity.Mk_Identity (node3 x1 x2 x3)))\n                                                        triple\n                               | RigidFull (Mk_Rigid s pr _m sf as r) => Mk_Seq GHC.Base.$ Deep (n * s)\n                                                                         (nodeToDigit pr) (cycleNMiddle (n -\n                                                                                                        id\n                                                                                                        2) r)\n                                                                         (nodeToDigit sf)\n                             end\n      end in\n    match arg_0__ , arg_1__ with\n      | n , xs => if Nat.ltb n 0 : bool\n                  then error (GHC.Base.hs_string__ \"cycleN takes a nonnegative integer argument\")\n                  else if Nat.eqb n 0 : bool\n                       then empty\n                       else if Nat.eqb n 1 : bool\n                            then xs\n                            else j_11__\n    end.\n\nLocal Definition Applicative__Seq_op_ztzg__ : forall {a} {b},\n                                                Seq a -> Seq b -> Seq b :=\n  fun {a} {b} => fun xs ys => cycleN (length xs) ys.\n\n\nDefinition addDigits4 {a} appendTree2 appendTree3 appendTree4 :\n       FingerTree (Node (Node a))  ->\n       Digit (Node a) -> Node a -> Node a -> Node a -> Node a -> Digit (Node a) -> FingerTree (Node (Node a)) -> FingerTree\n                            (Node (Node a)) :=\n  fun ft arg_1__ arg_2__ arg_3__ arg_4__ arg_5__ arg_6__ arg_7__ =>\n    match ft\n        , arg_1__\n        , arg_2__\n        , arg_3__\n        , arg_4__\n        , arg_5__\n        , arg_6__\n        , arg_7__ with\n      | m1 , One a , b , c , d , e , One f , m2 => appendTree2 m1 (node3 a b c) (node3\n                                                                                d e f) m2\n      | m1 , One a , b , c , d , e , Two f g , m2 => appendTree3 m1 (node3 a b c)\n                                                     (node2 d e) (node2 f g) m2\n      | m1 , One a , b , c , d , e , Three f g h , m2 => appendTree3 m1 (node3 a b c)\n                                                         (node3 d e f) (node2 g h) m2\n      | m1 , One a , b , c , d , e , Four f g h i , m2 => appendTree3 m1 (node3 a b c)\n                                                          (node3 d e f) (node3 g h i) m2\n      | m1 , Two a b , c , d , e , f , One g , m2 => appendTree3 m1 (node3 a b c)\n                                                     (node2 d e) (node2 f g) m2\n      | m1 , Two a b , c , d , e , f , Two g h , m2 => appendTree3 m1 (node3 a b c)\n                                                       (node3 d e f) (node2 g h) m2\n      | m1 , Two a b , c , d , e , f , Three g h i , m2 => appendTree3 m1 (node3 a b\n                                                                          c) (node3 d e f) (node3 g h i) m2\n      | m1 , Two a b , c , d , e , f , Four g h i j , m2 => appendTree4 m1 (node3 a b\n                                                                           c) (node3 d e f) (node2 g h) (node2 i j) m2\n      | m1 , Three a b c , d , e , f , g , One h , m2 => appendTree3 m1 (node3 a b c)\n                                                         (node3 d e f) (node2 g h) m2\n      | m1 , Three a b c , d , e , f , g , Two h i , m2 => appendTree3 m1 (node3 a b\n                                                                          c) (node3 d e f) (node3 g h i) m2\n      | m1 , Three a b c , d , e , f , g , Three h i j , m2 => appendTree4 m1 (node3 a\n                                                                              b c) (node3 d e f) (node2 g h) (node2 i j)\n                                                               m2\n      | m1 , Three a b c , d , e , f , g , Four h i j k , m2 => appendTree4 m1 (node3\n                                                                               a b c) (node3 d e f) (node3 g h i) (node2\n                                                                                                                  j k)\n                                                                m2\n      | m1 , Four a b c d , e , f , g , h , One i , m2 => appendTree3 m1 (node3 a b c)\n                                                          (node3 d e f) (node3 g h i) m2\n      | m1 , Four a b c d , e , f , g , h , Two i j , m2 => appendTree4 m1 (node3 a b\n                                                                           c) (node3 d e f) (node2 g h) (node2 i j) m2\n      | m1 , Four a b c d , e , f , g , h , Three i j k , m2 => appendTree4 m1 (node3\n                                                                               a b c) (node3 d e f) (node3 g h i) (node2\n                                                                                                                  j k)\n                                                                m2\n      | m1 , Four a b c d , e , f , g , h , Four i j k l , m2 => appendTree4 m1 (node3\n                                                                                a b c) (node3 d e f) (node3 g h i)\n                                                                 (node3 j k l) m2\n    end.\n\nDefinition addDigits2 {a} appendTree2 appendTree3 appendTree4 :\n  FingerTree (Node (Node a)) -> Digit (Node a) -> Node a -> Node a -> Digit (Node a)\n  -> FingerTree (Node (Node a)) -> FingerTree (Node (Node a)) :=\n  fun ft arg_1__ arg_2__ arg_3__ arg_4__ arg_5__ =>\n    match ft , arg_1__ , arg_2__ , arg_3__ , arg_4__ , arg_5__ with\n      | m1 , One a , b , c , One d , m2 => appendTree2 m1 (node2 a b) (node2 c d) m2\n      | m1 , One a , b , c , Two d e , m2 => appendTree2 m1 (node3 a b c) (node2 d e)\n                                             m2\n      | m1 , One a , b , c , Three d e f , m2 => appendTree2 m1 (node3 a b c) (node3 d\n                                                                              e f) m2\n      | m1 , One a , b , c , Four d e f g , m2 => appendTree3 m1 (node3 a b c) (node2\n                                                                               d e) (node2 f g) m2\n      | m1 , Two a b , c , d , One e , m2 => appendTree2 m1 (node3 a b c) (node2 d e)\n                                             m2\n      | m1 , Two a b , c , d , Two e f , m2 => appendTree2 m1 (node3 a b c) (node3 d e\n                                                                            f) m2\n      | m1 , Two a b , c , d , Three e f g , m2 => appendTree3 m1 (node3 a b c) (node2\n                                                                                d e) (node2 f g) m2\n      | m1 , Two a b , c , d , Four e f g h , m2 => appendTree3 m1 (node3 a b c)\n                                                    (node3 d e f) (node2 g h) m2\n      | m1 , Three a b c , d , e , One f , m2 => appendTree2 m1 (node3 a b c) (node3 d\n                                                                              e f) m2\n      | m1 , Three a b c , d , e , Two f g , m2 => appendTree3 m1 (node3 a b c) (node2\n                                                                                d e) (node2 f g) m2\n      | m1 , Three a b c , d , e , Three f g h , m2 => appendTree3 m1 (node3 a b c)\n                                                       (node3 d e f) (node2 g h) m2\n      | m1 , Three a b c , d , e , Four f g h i , m2 => appendTree3 m1 (node3 a b c)\n                                                        (node3 d e f) (node3 g h i) m2\n      | m1 , Four a b c d , e , f , One g , m2 => appendTree3 m1 (node3 a b c) (node2\n                                                                               d e) (node2 f g) m2\n      | m1 , Four a b c d , e , f , Two g h , m2 => appendTree3 m1 (node3 a b c)\n                                                    (node3 d e f) (node2 g h) m2\n      | m1 , Four a b c d , e , f , Three g h i , m2 => appendTree3 m1 (node3 a b c)\n                                                        (node3 d e f) (node3 g h i) m2\n      | m1 , Four a b c d , e , f , Four g h i j , m2 => appendTree4 m1 (node3 a b c)\n                                                         (node3 d e f) (node2 g h) (node2 i j) m2\n    end.\n\nDefinition addDigits3 {a} appendTree2 appendTree3 appendTree4 :\n  FingerTree (Node (Node a)) -> Digit (Node a) -> Node\n                                                  a -> Node a -> Node a -> Digit (Node a) -> FingerTree (Node (Node\n                                                                                        a)) -> FingerTree (Node (Node\n                                                                                                                a)) :=\n  fun ft arg_1__ arg_2__ arg_3__ arg_4__ arg_5__ arg_6__ =>\n    match ft , arg_1__ , arg_2__ , arg_3__ , arg_4__ , arg_5__ , arg_6__ with\n      | m1 , One a , b , c , d , One e , m2 => appendTree2 m1 (node3 a b c) (node2 d\n                                                                            e) m2\n      | m1 , One a , b , c , d , Two e f , m2 => appendTree2 m1 (node3 a b c) (node3 d\n                                                                              e f) m2\n      | m1 , One a , b , c , d , Three e f g , m2 => appendTree3 m1 (node3 a b c)\n                                                     (node2 d e) (node2 f g) m2\n      | m1 , One a , b , c , d , Four e f g h , m2 => appendTree3 m1 (node3 a b c)\n                                                      (node3 d e f) (node2 g h) m2\n      | m1 , Two a b , c , d , e , One f , m2 => appendTree2 m1 (node3 a b c) (node3 d\n                                                                              e f) m2\n      | m1 , Two a b , c , d , e , Two f g , m2 => appendTree3 m1 (node3 a b c) (node2\n                                                                                d e) (node2 f g) m2\n      | m1 , Two a b , c , d , e , Three f g h , m2 => appendTree3 m1 (node3 a b c)\n                                                       (node3 d e f) (node2 g h) m2\n      | m1 , Two a b , c , d , e , Four f g h i , m2 => appendTree3 m1 (node3 a b c)\n                                                        (node3 d e f) (node3 g h i) m2\n      | m1 , Three a b c , d , e , f , One g , m2 => appendTree3 m1 (node3 a b c)\n                                                     (node2 d e) (node2 f g) m2\n      | m1 , Three a b c , d , e , f , Two g h , m2 => appendTree3 m1 (node3 a b c)\n                                                       (node3 d e f) (node2 g h) m2\n      | m1 , Three a b c , d , e , f , Three g h i , m2 => appendTree3 m1 (node3 a b\n                                                                          c) (node3 d e f) (node3 g h i) m2\n      | m1 , Three a b c , d , e , f , Four g h i j , m2 => appendTree4 m1 (node3 a b\n                                                                           c) (node3 d e f) (node2 g h) (node2 i j) m2\n      | m1 , Four a b c d , e , f , g , One h , m2 => appendTree3 m1 (node3 a b c)\n                                                      (node3 d e f) (node2 g h) m2\n      | m1 , Four a b c d , e , f , g , Two h i , m2 => appendTree3 m1 (node3 a b c)\n                                                        (node3 d e f) (node3 g h i) m2\n      | m1 , Four a b c d , e , f , g , Three h i j , m2 => appendTree4 m1 (node3 a b\n                                                                           c) (node3 d e f) (node2 g h) (node2 i j) m2\n      | m1 , Four a b c d , e , f , g , Four h i j k , m2 => appendTree4 m1 (node3 a b\n                                                                            c) (node3 d e f) (node3 g h i) (node2 j k)\n                                                             m2\n    end.\n\n\n\nFixpoint appendTree4 {a} (ft: FingerTree (Node a)) : Node a -> Node a -> Node\n                             a -> Node a -> FingerTree (Node a) -> FingerTree (Node a) :=\n  fun arg_1__ arg_2__ arg_3__ arg_4__ arg_5__ =>\n    match ft , arg_1__ , arg_2__ , arg_3__ , arg_4__ , arg_5__ with\n      | Empty , a , b , c , d , xs => consTree a (consTree b (consTree c (consTree d\n                                                                                   xs)))\n      | xs , a , b , c , d , Empty => snocTree (snocTree (snocTree (snocTree xs a) b)\n                                                         c) d\n      | Single x , a , b , c , d , xs => consTree x (consTree a (consTree b (consTree\n                                                                          c (consTree d xs))))\n      | xs , a , b , c , d , Single x => snocTree (snocTree (snocTree (snocTree\n                                                                      (snocTree xs a) b) c) d) x\n      | Deep s1 pr1 m1 sf1 , a , b , c , d , Deep s2 pr2 m2 sf2 => Deep (((((s1\n                                                                        + size a) + size b) +\n                                                                        size c) + size d) + s2) pr1\n                                                                   (addDigits4 appendTree2 appendTree3 appendTree4\n                                                                               m1 sf1 a b c d pr2 m2) sf2\n    end\nwith appendTree2 {a} (ft : FingerTree (Node a)) : Node a -> Node\n                             a -> FingerTree (Node a) -> FingerTree (Node a) :=\n  fun arg_1__ arg_2__ arg_3__ =>\n    match ft , arg_1__ , arg_2__ , arg_3__ with\n      | Empty , a , b , xs => consTree a (consTree b xs)\n      | xs , a , b , Empty => snocTree (snocTree xs a) b\n      | Single x , a , b , xs => consTree x (consTree a (consTree b xs))\n      | xs , a , b , Single x => snocTree (snocTree (snocTree xs a) b) x\n      | Deep s1 pr1 m1 sf1 , a , b , Deep s2 pr2 m2 sf2 => Deep (((s1 + size\n                                                                a) + size b) + s2) pr1\n                                                               (addDigits2 appendTree2 appendTree3 appendTree4 m1\n                                                                                                       sf1 a b pr2 m2)\n                                                           sf2\n    end\nwith appendTree3 {a} (ft : FingerTree (Node a)) : Node a -> Node a -> Node\n                             a -> FingerTree (Node a) -> FingerTree (Node a) :=\n  fun arg_1__ arg_2__ arg_3__ arg_4__ =>\n    match ft , arg_1__ , arg_2__ , arg_3__ , arg_4__ with\n      | Empty , a , b , c , xs => consTree a (consTree b (consTree c xs))\n      | xs , a , b , c , Empty => snocTree (snocTree (snocTree xs a) b) c\n      | Single x , a , b , c , xs => consTree x (consTree a (consTree b (consTree c\n                                                                                  xs)))\n      | xs , a , b , c , Single x => snocTree (snocTree (snocTree (snocTree xs a) b)\n                                                        c) x\n      | Deep s1 pr1 m1 sf1 , a , b , c , Deep s2 pr2 m2 sf2 => Deep ((((s1 +\n                                                                    size a) + size b) + size c)\n                                                                    + s2) pr1 (addDigits3 appendTree2 appendTree3 appendTree4 m1 sf1 a b c pr2 m2)\n                                                               sf2\n    end.\n\n\nDefinition addDigits1 {a} appendTree1 : FingerTree (Node (Node a)) -> Digit (Node a) -> Node\n                            a -> Digit (Node a) -> FingerTree (Node (Node a)) -> FingerTree (Node (Node\n                                                                                                  a)) :=\n  fun ft arg_1__ arg_2__ arg_3__ arg_4__ =>\n    match ft , arg_1__ , arg_2__ , arg_3__ , arg_4__ with\n      | m1 , One a , b , One c , m2 => appendTree1 m1 (node3 a b c) m2\n      | m1 , One a , b , Two c d , m2 => appendTree2 m1 (node2 a b) (node2 c d) m2\n      | m1 , One a , b , Three c d e , m2 => appendTree2 m1 (node3 a b c) (node2 d e)\n                                             m2\n      | m1 , One a , b , Four c d e f , m2 => appendTree2 m1 (node3 a b c) (node3 d e\n                                                                           f) m2\n      | m1 , Two a b , c , One d , m2 => appendTree2 m1 (node2 a b) (node2 c d) m2\n      | m1 , Two a b , c , Two d e , m2 => appendTree2 m1 (node3 a b c) (node2 d e) m2\n      | m1 , Two a b , c , Three d e f , m2 => appendTree2 m1 (node3 a b c) (node3 d e\n                                                                            f) m2\n      | m1 , Two a b , c , Four d e f g , m2 => appendTree3 m1 (node3 a b c) (node2 d\n                                                                             e) (node2 f g) m2\n      | m1 , Three a b c , d , One e , m2 => appendTree2 m1 (node3 a b c) (node2 d e)\n                                             m2\n      | m1 , Three a b c , d , Two e f , m2 => appendTree2 m1 (node3 a b c) (node3 d e\n                                                                            f) m2\n      | m1 , Three a b c , d , Three e f g , m2 => appendTree3 m1 (node3 a b c) (node2\n                                                                                d e) (node2 f g) m2\n      | m1 , Three a b c , d , Four e f g h , m2 => appendTree3 m1 (node3 a b c)\n                                                    (node3 d e f) (node2 g h) m2\n      | m1 , Four a b c d , e , One f , m2 => appendTree2 m1 (node3 a b c) (node3 d e\n                                                                           f) m2\n      | m1 , Four a b c d , e , Two f g , m2 => appendTree3 m1 (node3 a b c) (node2 d\n                                                                             e) (node2 f g) m2\n      | m1 , Four a b c d , e , Three f g h , m2 => appendTree3 m1 (node3 a b c)\n                                                    (node3 d e f) (node2 g h) m2\n      | m1 , Four a b c d , e , Four f g h i , m2 => appendTree3 m1 (node3 a b c)\n                                                     (node3 d e f) (node3 g h i) m2\n    end.\n\n\nFixpoint appendTree1 {a} ( ft : FingerTree (Node a)) : Node a -> FingerTree (Node\n                                                                         a) -> FingerTree (Node a) :=\n  fun arg_1__ arg_2__ =>\n    match ft , arg_1__ , arg_2__ with\n      | Empty , a , xs => consTree a xs\n      | xs , a , Empty => snocTree xs a\n      | Single x , a , xs => consTree x (consTree a xs)\n      | xs , a , Single x => snocTree (snocTree xs a) x\n      | Deep s1 pr1 m1 sf1 , a , Deep s2 pr2 m2 sf2 => Deep ((s1 + size a)\n                                                            + s2) pr1 (addDigits1 appendTree1 m1 sf1 a pr2 m2) sf2\n    end.\n\n\nDefinition addDigits0 {a} `{Sized a} (ft : FingerTree (Node a)) : Digit a -> Digit\n                                       a -> FingerTree (Node a) -> FingerTree (Node a) :=\n  fun arg_1__ arg_2__ arg_3__ =>\n    match ft , arg_1__ , arg_2__ , arg_3__ with\n      | m1 , One a , One b , m2 => appendTree1 m1 (node2 a b) m2\n      | m1 , One a , Two b c , m2 => appendTree1 m1 (node3 a b c) m2\n      | m1 , One a , Three b c d , m2 => appendTree2 m1 (node2 a b) (node2 c d) m2\n      | m1 , One a , Four b c d e , m2 => appendTree2 m1 (node3 a b c) (node2 d e) m2\n      | m1 , Two a b , One c , m2 => appendTree1 m1 (node3 a b c) m2\n      | m1 , Two a b , Two c d , m2 => appendTree2 m1 (node2 a b) (node2 c d) m2\n      | m1 , Two a b , Three c d e , m2 => appendTree2 m1 (node3 a b c) (node2 d e) m2\n      | m1 , Two a b , Four c d e f , m2 => appendTree2 m1 (node3 a b c) (node3 d e f)\n                                            m2\n      | m1 , Three a b c , One d , m2 => appendTree2 m1 (node2 a b) (node2 c d) m2\n      | m1 , Three a b c , Two d e , m2 => appendTree2 m1 (node3 a b c) (node2 d e) m2\n      | m1 , Three a b c , Three d e f , m2 => appendTree2 m1 (node3 a b c) (node3 d e\n                                                                            f) m2\n      | m1 , Three a b c , Four d e f g , m2 => appendTree3 m1 (node3 a b c) (node2 d\n                                                                             e) (node2 f g) m2\n      | m1 , Four a b c d , One e , m2 => appendTree2 m1 (node3 a b c) (node2 d e) m2\n      | m1 , Four a b c d , Two e f , m2 => appendTree2 m1 (node3 a b c) (node3 d e f)\n                                            m2\n      | m1 , Four a b c d , Three e f g , m2 => appendTree3 m1 (node3 a b c) (node2 d\n                                                                             e) (node2 f g) m2\n      | m1 , Four a b c d , Four e f g h , m2 => appendTree3 m1 (node3 a b c) (node3 d\n                                                                              e f) (node2 g h) m2\n    end.\n\nFixpoint appendTree0 {a} ( ft : FingerTree (Elem a)) : FingerTree (Elem\n                                                               a) -> FingerTree (Elem a) :=\n  fun arg_1__ =>\n    match ft , arg_1__ with\n      | Empty , xs => xs\n      | xs , Empty => xs\n      | Single x , xs => consTree x xs\n      | xs , Single x => snocTree xs x\n      | Deep s1 pr1 m1 sf1 , Deep s2 pr2 m2 sf2 => Deep (s1 + s2) pr1\n                                                   (addDigits0 m1 sf1 pr2 m2) sf2\n    end.\n\nDefinition op_zgzl__ {a} : Seq a -> Seq a -> Seq a :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__ , arg_1__ with\n      | Mk_Seq xs , Mk_Seq ys => Mk_Seq (appendTree0 xs ys)\n    end.\n\nNotation \"'_><_'\" := (op_zgzl__).\n\nInfix \"><\" := (_><_) (at level 99).\n\nLocal Definition Monad__Seq_op_zgzgze__ : forall {a} {b},\n                                            Seq a -> (a -> Seq b) -> Seq b :=\n  fun {a} {b} =>\n    fun xs f =>\n      let add := fun ys x => ys >< f x in Data.Foldable.foldl' add empty xs.\n\nDefinition splitDigit {a} `{Sized a} : nat -> Digit a -> Split (option\n                                                                       (Digit a)) a :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__ , arg_1__ with\n      | i , One a => GHC.Prim.seq i (Mk_Split None a None)\n      | i , Two a b => let sa := size a in\n                       if Nat.ltb i sa : bool\n                       then Mk_Split None a (Some (One b))\n                       else Mk_Split (Some (One a)) b None\n      | i , Three a b c => let sa := size a in\n                           let sab := sa + size b in\n                           if Nat.ltb i sa : bool\n                           then Mk_Split None a (Some (Two b c))\n                           else if Nat.ltb i sab : bool\n                                then Mk_Split (Some (One a)) b (Some (One c))\n                                else Mk_Split (Some (Two a b)) c None\n      | i , Four a b c d => let sa := size a in\n                            let sab := sa + size b in\n                            let sabc := sab + size c in\n                            if Nat.ltb i sa : bool\n                            then Mk_Split None a (Some (Three b c d))\n                            else if Nat.ltb i sab : bool\n                                 then Mk_Split (Some (One a)) b (Some (Two c d))\n                                 else if Nat.ltb i sabc : bool\n                                      then Mk_Split (Some (Two a b)) c (Some (One d))\n                                      else Mk_Split (Some (Three a b c)) d None\n    end.\n\nDefinition splitMap {s} {a} {b} : (nat -> s -> (s * s)%type) -> (s -> a -> b) -> s -> Seq a -> Seq b :=\n  fun splt' =>\n    let splitMapNode {a} {s} {b} `{Sized a} : (nat -> s -> (s *\n                                              s)%type) -> (s -> a -> b) -> s -> Node a -> Node b :=\n      fun arg_0__ arg_1__ arg_2__ arg_3__ =>\n        match arg_0__ , arg_1__ , arg_2__ , arg_3__ with\n          | splt , f , s , Node2 ns a b => match splt (size a) s with\n                                             | pair first second => Node2 ns (f first a) (f second b)\n                                           end\n          | splt , f , s , Node3 ns a b c => match splt (size a) s with\n                                               | pair first r => match splt (size b) r with\n                                                                   | pair second third => Node3 ns (f first a) (f second\n                                                                                                               b) (f\n                                                                                                                  third\n                                                                                                                  c)\n                                                                 end\n                                             end\n        end in\n    let splitMapDigit {a} {s} {b} `{Sized a} : (nat -> s -> (s * s)%type) -> (s -> a -> b) -> s -> Digit a -> Digit b :=\n      fun arg_10__ arg_11__ arg_12__ arg_13__ =>\n        match arg_10__ , arg_11__ , arg_12__ , arg_13__ with\n          | _ , f , s , One a => One (f s a)\n          | splt , f , s , Two a b => match splt (size a) s with\n                                        | pair first second => Two (f first a) (f second b)\n                                      end\n          | splt , f , s , Three a b c => match splt (size a) s with\n                                            | pair first r => match splt (size b) r with\n                                                                | pair second third => Three (f first a) (f second b) (f\n                                                                                                                      third\n                                                                                                                      c)\n                                                              end\n                                          end\n          | splt , f , s , Four a b c d => match splt (size a) s with\n                                             | pair first s' => match splt (size b + size c) s' with\n                                                                  | pair middle fourth => match splt (size b)\n                                                                                                  middle with\n                                                                                            | pair second third => Four\n                                                                                                                   (f\n                                                                                                                   first\n                                                                                                                   a) (f\n                                                                                                                      second\n                                                                                                                      b)\n                                                                                                                   (f\n                                                                                                                   third\n                                                                                                                   c) (f\n                                                                                                                      fourth\n                                                                                                                      d)\n                                                                                          end\n                                                                end\n                                           end\n        end in\n    let splitMapTree : forall {a} {s} {b} `{Sized a} , (nat -> s -> (s *\n                                              s)%type) -> (s -> a -> b) -> s -> FingerTree a -> FingerTree b :=\n      fix splitMapTree {a} {s} {b} `{Sized a} arg_25__ arg_26__ arg_27__ arg_28__\n            := match arg_25__ , arg_26__ , arg_27__ , arg_28__ with\n                 | _ , _ , _ , Empty => Empty\n                 | _ , f , s , Single xs => Single GHC.Base.$ f s xs\n                 | splt , f , s , Deep n pr m sf => match splt (size pr) s with\n                                                      | pair prs r => match splt ((n - size pr) - size\n                                                                                 sf) r with\n                                                                        | pair ms sfs => Deep n (splitMapDigit splt f\n                                                                                                prs pr) (splitMapTree\n                                                                                                        splt\n                                                                                                        (splitMapNode\n                                                                                                        splt f) ms m)\n                                                                                         (splitMapDigit splt f sfs sf)\n                                                                      end\n                                                    end\n               end in\n    let go :=\n      fun arg_34__ arg_35__ arg_36__ =>\n        match arg_34__ , arg_35__ , arg_36__ with\n          | f , s , Mk_Seq xs => Mk_Seq (splitMapTree splt' (fun arg_37__\n                                                                           arg_38__ =>\n                                                                        match arg_37__ , arg_38__ with\n                                                                          | s' , Mk_Elem a => Mk_Elem (f s' a)\n                                                                        end) s xs)\n        end in\n    go.\n\nDefinition splitNode {a} `{Sized a} : nat -> Node a -> Split (option\n                                                                     (Digit a)) a :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__ , arg_1__ with\n      | i , Node2 _ a b => let sa := size a in\n                           if Nat.ltb i sa : bool\n                           then Mk_Split None a (Some (One b))\n                           else Mk_Split (Some (One a)) b None\n      | i , Node3 _ a b c => let sa := size a in\n                             let sab := sa + size b in\n                             if Nat.ltb i sa : bool\n                             then Mk_Split None a (Some (Two b c))\n                             else if Nat.ltb i sab : bool\n                                  then Mk_Split (Some (One a)) b (Some (One c))\n                                  else Mk_Split (Some (Two a b)) c None\n    end.\n\nDefinition splitTree : forall {a} `{Sized a} , nat -> FingerTree a -> Split\n                                      (FingerTree a) a :=\n  fix splitTree {a} `{Sized a} arg_0__ arg_1__ {struct arg_1__ }\n        := match arg_0__ , arg_1__ with\n             | _ , Empty => error (GHC.Base.hs_string__ \"splitTree of empty tree\")\n             | i , Single x => GHC.Prim.seq i (Mk_Split Empty x Empty)\n             | i , Deep _ pr m sf => let spr := size pr in\n                                     let spm := spr + size m in\n                                     let im := i - spr in\n                                     if Nat.ltb i spr : bool\n                                     then match splitDigit i pr with\n                                            | Mk_Split l x r => Mk_Split (Data.Maybe.maybe Empty digitToTree l) x (deepL\n                                                                                                                  r m\n                                                                                                                  sf)\n                                          end\n                                     else if Nat.ltb i spm : bool\n                                          then match splitTree im m with\n                                                 | Mk_Split ml xs mr => match splitNode (im - size ml) xs with\n                                                                          | Mk_Split l x r => Mk_Split (deepR pr ml l) x\n                                                                                              (deepL r mr sf)\n                                                                        end\n                                               end\n                                          else match splitDigit (i - spm) sf with\n                                                 | Mk_Split l x r => Mk_Split (deepR pr m l) x (Data.Maybe.maybe Empty\n                                                                                               digitToTree r)\n                                               end\n           end.\n\nDefinition split {a} : nat -> FingerTree (Elem a) -> (FingerTree (Elem a) * FingerTree (Elem a))%type :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__ , arg_1__ with\n      | i , Empty => GHC.Prim.seq i (pair Empty Empty)\n      | i , xs => if negb (Nat.leb (size xs) i) : bool\n                  then match splitTree i xs with\n                         | Mk_Split l x r => pair l (consTree x r)\n                       end\n                  else pair xs Empty\n    end.\n\nDefinition splitAt {a} : nat -> Seq a -> (Seq a * Seq a)%type :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__ , arg_1__ with\n      | i , Mk_Seq xs => match split i xs with\n                           | pair l r => pair (Mk_Seq l) (Mk_Seq r)\n                         end\n    end.\n\nDefinition breakr {a} : (a -> bool) -> Seq a -> (Seq a * Seq a)%type :=\n  fun p xs =>\n    let flipPair := fun arg_0__ => match arg_0__ with | pair x y => pair y x end in\n    Data.Foldable.foldr (fun arg_3__ arg_4__ =>\n                          match arg_3__ , arg_4__ with\n                            | i , _ => flipPair (splitAt (i + id 1) xs)\n                          end) (pair xs empty) (findIndicesR p xs).\n\nDefinition spanr {a} : (a -> bool) -> Seq a -> (Seq a * Seq a)%type :=\n  fun p => breakr (negb GHC.Base.∘ p).\n\nDefinition dropWhileR {a} : (a -> bool) -> Seq a -> Seq a :=\n  fun p => Data.Tuple.snd GHC.Base.∘ spanr p.\n\nDefinition takeWhileR {a} : (a -> bool) -> Seq a -> Seq a :=\n  fun p => Data.Tuple.fst GHC.Base.∘ spanr p.\n\nDefinition breakl {a} : (a -> bool) -> Seq a -> (Seq a * Seq a)%type :=\n  fun p xs =>\n    Data.Foldable.foldr (fun arg_0__ arg_1__ =>\n                          match arg_0__ , arg_1__ with\n                            | i , _ => splitAt i xs\n                          end) (pair xs empty) (findIndicesL p xs).\n\nDefinition spanl {a} : (a -> bool) -> Seq a -> (Seq a * Seq a)%type :=\n  fun p => breakl (negb GHC.Base.∘ p).\n\nDefinition dropWhileL {a} : (a -> bool) -> Seq a -> Seq a :=\n  fun p => Data.Tuple.snd GHC.Base.∘ spanl p.\n\nDefinition takeWhileL {a} : (a -> bool) -> Seq a -> Seq a :=\n  fun p => Data.Tuple.fst GHC.Base.∘ spanl p.\n\nDefinition splitAt' {a} : nat -> Seq a -> (Seq a * Seq a)%type :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__ , arg_1__ with\n      | i , Mk_Seq xs => match split i xs with\n                           | pair l r => pair (Mk_Seq l) (Mk_Seq r)\n                         end\n    end.\n\nDefinition drop {a} : nat -> Seq a -> Seq a :=\n  fun i => Data.Tuple.snd GHC.Base.∘ splitAt' i.\n\nDefinition take {a} : nat -> Seq a -> Seq a :=\n  fun i => Data.Tuple.fst GHC.Base.∘ splitAt' i.\n\nDefinition zipWith' {a} {b} {c} : (a -> b -> c) -> Seq a -> Seq b -> Seq c :=\n  fun f s1 s2 => splitMap splitAt' (fun s a => f a (getSingleton s)) s2 s1.\n\n\nDefinition zipWith {a} {b} {c} : (a -> b -> c) -> Seq a -> Seq b -> Seq c :=\n  fun f s1 s2 =>\n    let minLen := min (length s1) (length s2) in\n    let s1' := take minLen s1 in let s2' := take minLen s2 in zipWith' f s1' s2'.\n\n\n(* chooses type instead of term for some reason *)\nDefinition zip {a} {b} : Seq a -> Seq b -> Seq (a * b)%type :=\n  zipWith GHC.Tuple.pair2.\n\n\nDefinition minimum_ne {t: Type -> Type} `{Data.Foldable.Foldable t}\n           (x : nat) (y : t nat) : nat :=\n  Data.Foldable.foldr min x y.\n\nDefinition zipWith3 {a} {b} {c} {d} : (a -> b -> c -> d) -> Seq a -> Seq\n                                      b -> Seq c -> Seq d :=\n  fun f s1 s2 s3 =>\n    let minLen :=\n      minimum_ne (length s1) ((cons (length s2) (cons (length s3) nil))) in\n    let s1' := take minLen s1 in\n    let s2' := take minLen s2 in\n    let s3' := take minLen s3 in zipWith' _GHC.Base.$_ (zipWith' f s1' s2') s3'.\n\nDefinition zip3 {a} {b} {c} : Seq a -> Seq b -> Seq c -> Seq (a * b * c)%type :=\n  zipWith3 GHC.Tuple.pair3.\n\nDefinition zipWith3' {a} {b} {c} {d} : (a -> b -> c -> d) -> Seq a -> Seq\n                                       b -> Seq c -> Seq d :=\n  fun f s1 s2 s3 => zipWith' _GHC.Base.$_ (zipWith' f s1 s2) s3.\n\nDefinition zipWith4 {a} {b} {c} {d} {e} : (a -> b -> c -> d -> e) -> Seq\n                                          a -> Seq b -> Seq c -> Seq d -> Seq e :=\n  fun f s1 s2 s3 s4 =>\n    let minLen :=\n      minimum_ne (length s1) ((cons (length s2) (cons (length s3)\n                                                                      (cons (length s4) nil)))) in\n    let s1' := take minLen s1 in\n    let s2' := take minLen s2 in\n    let s3' := take minLen s3 in\n    let s4' := take minLen s4 in\n    zipWith' _GHC.Base.$_ (zipWith3' f s1' s2' s3') s4'.\n\nDefinition zip4 {a} {b} {c} {d} : Seq a -> Seq b -> Seq c -> Seq d -> Seq (a * b\n                                                                          * c * d)%type :=\n  zipWith4 GHC.Tuple.pair4.\n\nDefinition tailsDigit {a} : Digit a -> Digit (Digit a) :=\n  fun arg_0__ =>\n    match arg_0__ with\n      | One a => One (One a)\n      | Two a b => Two (Two a b) (One b)\n      | Three a b c => Three (Three a b c) (Two b c) (One c)\n      | Four a b c d => Four (Four a b c d) (Three b c d) (Two c d) (One d)\n    end.\n\nDefinition tailsNode {a} : Node a -> Node (Digit a) :=\n  fun arg_0__ =>\n    match arg_0__ with\n      | Node2 s a b => Node2 s (Two a b) (One b)\n      | Node3 s a b c => Node3 s (Three a b c) (Two b c) (One c)\n    end.\n\n\nDefinition tailsTree : forall {a} {b} `{Sized a} (arg_0__ : FingerTree a -> b),\n  FingerTree a -> FingerTree b :=\n  fix tailsTree {a} {b} `{Sized a} arg_0__ arg_1__\n        := match arg_0__ , arg_1__ with\n             | _ , Empty => Empty\n             | f , Single x => Single (f (Single x))\n             | f , Deep n pr m sf =>\n               let f' :=\n                   fun ms  =>\n                     match viewLTree ms with\n                     | Just2 node m' =>\n                       GHC.Base.fmap (fun pr' => f (deep pr' m' sf)) (tailsNode node)\n                     | Nothing2 => error\n                     end in\n               Deep n (GHC.Base.fmap (fun pr' => f (deep pr' m sf)) (tailsDigit pr))\n                    (tailsTree f' m)\n                    (GHC.Base.fmap (f GHC.Base.∘ digitToTree) (tailsDigit sf))\n           end.\n\nDefinition tails {a} : Seq a -> Seq (Seq a) :=\n  fun arg_0__ =>\n    match arg_0__ with\n      | Mk_Seq xs => Mk_Seq (tailsTree (Mk_Elem GHC.Base.∘ Mk_Seq) xs) |> empty\n    end.\n\nDefinition viewl {a} : Seq a -> ViewL a :=\n  fun arg_0__ =>\n    match arg_0__ with\n      | Mk_Seq xs => match viewLTree xs with\n                       | Nothing2 => EmptyL\n                       | Just2 (Mk_Elem x) xs' => x :< Mk_Seq xs'\n                     end\n    end.\n\nDefinition scanl1 {a} : (a -> a -> a) -> Seq a -> Seq a :=\n  fun f xs =>\n    match viewl xs with\n      | EmptyL => error (GHC.Base.hs_string__\n                        \"scanl1 takes a nonempty sequence as an argument\")\n      | op_ZCzl__ x xs' => scanl f x xs'\n    end.\n\nDefinition viewr {a} : Seq a -> ViewR a :=\n  fun arg_0__ =>\n    match arg_0__ with\n      | Mk_Seq xs => match viewRTree xs with\n                       | Nothing2 => EmptyR\n                       | Just2 xs' (Mk_Elem x) => Mk_Seq xs' :> x\n                     end\n    end.\n\nDefinition scanr1 {a} : (a -> a -> a) -> Seq a -> Seq a :=\n  fun f xs =>\n    match viewr xs with\n      | EmptyR => error (GHC.Base.hs_string__\n                        \"scanr1 takes a nonempty sequence as an argument\")\n      | op_ZCzg__ xs' x => scanr f x xs'\n    end.\n\n\nDefinition aptyMiddle {c} {d} {a} {b}\n    (firstf : (c -> d)) (lastf : (c -> d)) (map23 : (a -> b) -> c -> d) (fs : FingerTree (Elem (a -> b))) (r : Rigid c)\n   (* { measure (rigid_metric r)} *) : FingerTree (Node d) := error.\n\n(*\n  match r with\n  | Mk_Rigid s pr (DeepTh sm prm mm sfm) sf => Deep\n                                                (sm + (s * ((size fs) + 1)))\n                                                (GHC.Base.fmap (@GHC.Base.fmap Digit23 _ _ _ firstf)\n                                                               (digit12ToDigit prm))\n                                                (aptyMiddle (GHC.Base.fmap firstf)\n                                                            (GHC.Base.fmap lastf)\n                                                            (GHC.Base.fmap GHC.Base.∘ map23)\n                                                            fs (Mk_Rigid s (squashL pr prm) mm (squashR sfm sf)))\n                                                (GHC.Base.fmap (GHC.Base.fmap lastf)\n                                                               (digit12ToDigit sfm))\n  | Mk_Rigid s pr EmptyTh sf =>\n    let converted : Node (Digit23 c) := node2 pr sf in\n    deep (One (GHC.Base.fmap firstf sf)) (mapMulFT\n                                            s\n                                            (fun arg_7__ =>\n                                               match arg_7__ with\n                                               | Mk_Elem f =>\n                                                 @GHC.Base.fmap Node _ _ _\n                                                   (@GHC.Base.fmap Digit23 _ _ _ (map23 f))\n                                                   converted\n                                               end) fs)\n         (One (GHC.Base.fmap lastf pr))\n  | Mk_Rigid s pr (SingleTh q) sf =>\n    let converted : Node (Digit23 c) := node3 pr q sf in\n    deep (Two (GHC.Base.fmap firstf q) (GHC.Base.fmap firstf sf))\n         (mapMulFT s\n                   (fun arg_12__ =>\n                      match arg_12__ with\n                      | Mk_Elem f => @GHC.Base.fmap Node _ _ _ (@GHC.Base.fmap Digit23 _ _ _ (map23 f))\n                                      converted\n                      end) fs) (Two (GHC.Base.fmap lastf pr)\n                                    (GHC.Base.fmap lastf q))\n  end. *)\n\nLocal Definition Applicative__Seq_op_zlztzg__ : forall {a} {b}, Seq (a -> b) -> Seq a -> Seq b := error. (*\n  fun {a} {b} arg_0__ arg_1__ =>\n      match arg_0__ , arg_1__ with\n        | fs , (Mk_Seq xsFT as xs) =>\n          match viewl fs with\n          | EmptyL => empty\n          | op_ZCzl__ firstf fs' =>\n            match viewr fs' with\n            | EmptyR => GHC.Base.fmap firstf xs\n            | op_ZCzg__ (Mk_Seq fs''FT) lastf =>\n              match rigidify xsFT with\n              | RigidEmpty => empty\n              | RigidOne (Mk_Elem x) => GHC.Base.fmap   (fun arg_6__ => arg_6__ x) fs\n              | RigidTwo (Mk_Elem x1) (Mk_Elem x2) =>\n                Mk_Seq\n                  GHC.Base.$\n                  ap2FT\n                  firstf\n                  fs''FT\n                  lastf (pair x1 x2)\n              | RigidThree (Mk_Elem x1) (Mk_Elem x2) (Mk_Elem x3) =>\n                Mk_Seq\n                  GHC.Base.$\n                  ap3FT\n                  firstf\n                  fs''FT\n                  lastf (pair\n                           (pair\n                              x1\n                              x2)\n                           x3)\n              | RigidFull (Mk_Rigid s pr _m sf as r) =>\n                (* firstf : a -> b\n                   lastf : a -> b\n                   fs''FT : FingerTree (Elem (a -> b))\n                   r : Rigid (Elem a)\n                 *)\n                Mk_Seq\n                  (Deep (s * length fs)\n                        (GHC.Base.fmap (GHC.Base.fmap firstf) (nodeToDigit pr))  (* Digit (Elem b) *)\n                        (@aptyMiddle (Elem a) (Elem b) a b   (* FingerTree (Node (Elem b)) *)\n                           (GHC.Base.fmap firstf)\n                           (GHC.Base.fmap  lastf)\n                           GHC.Base.fmap\n                           fs''FT\n                           r)\n                        (GHC.Base.fmap (GHC.Base.fmap  lastf) (nodeToDigit sf))) (* Digit (Elem b) *)\n              end\n            end\n          end\n      end. *)\n\nProgram Instance Applicative__Seq : GHC.Base.Applicative Seq := fun _ k =>\n    k {|GHC.Base.op_ztzg____ := fun {a} {b} => Applicative__Seq_op_ztzg__ ;\n      GHC.Base.op_zlztzg____ := fun {a} {b} => Applicative__Seq_op_zlztzg__ ;\n      GHC.Base.pure__ := fun {a} => Applicative__Seq_pure |}.\n\nLocal Definition Monad__Seq_op_zgzg__ : forall {a} {b},\n                                          Seq a -> Seq b -> Seq b :=\n  fun {a} {b} => _GHC.Base.*>_.\n\nLocal Definition Monad__Seq_return_ : forall {a}, a -> Seq a :=\n  fun {a} => GHC.Base.pure.\n\nProgram Instance Monad__Seq : GHC.Base.Monad Seq := fun _ k =>\n    k {|GHC.Base.op_zgzg____ := fun {a} {b} => Monad__Seq_op_zgzg__ ;\n      GHC.Base.op_zgzgze____ := fun {a} {b} => Monad__Seq_op_zgzgze__ ;\n      GHC.Base.return___ := fun {a} => Monad__Seq_return_ |}.\n\nModule Notations.\nNotation \"'_Data.Sequence.<|_'\" := (op_zlzb__).\nInfix \"Data.Sequence.<|\" := (_<|_) (at level 99).\nNotation \"'_Data.Sequence.|>_'\" := (op_zbzg__).\nInfix \"Data.Sequence.|>\" := (_|>_) (at level 99).\nNotation \"'_Data.Sequence.><_'\" := (op_zgzl__).\nInfix \"Data.Sequence.><\" := (_><_) (at level 99).\nEnd Notations.\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/SequenceManual.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2766969109607446}}
{"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\nRequire Export cequiv.\nRequire Export arith_props.\n\n\nLemma reduces_to_add_integer {o} :\n  forall lib (k1 k2 : Z),\n    @reduces_to o lib (mk_add (mk_integer k1) (mk_integer k2)) (mk_integer (k1 + k2)).\nProof.\n  introv.\n  apply reduces_to_if_step.\n  csunf; simpl; dcwf h; simpl; auto.\nQed.\n\nLemma cequiv_mk_add_integer {o} :\n  forall lib (k1 k2 : Z),\n    @cequiv o lib (mk_add (mk_integer k1) (mk_integer k2)) (mk_integer (k1 + k2)).\nProof.\n  introv.\n  apply reduces_to_implies_cequiv; eauto 3 with slow.\n  apply isprogram_eq; apply isprog_add_implies; eauto 3 with slow.\nQed.\n\nLemma cequivc_mkc_add_integer {o} :\n  forall lib (k1 k2 : Z),\n    @cequivc o lib (mkc_add (mkc_integer k1) (mkc_integer k2)) (mkc_integer (k1 + k2)).\nProof.\n  introv.\n  unfold cequivc; simpl.\n  apply cequiv_mk_add_integer.\nQed.\n\nLemma implies_approx_add {p} :\n  forall lib f g a b,\n    approx lib f g\n    -> @approx p lib a b\n    -> approx lib (mk_add f a) (mk_add 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  unfold mk_add.\n  repeat (prove_approx);sp.\nQed.\n\nLemma implies_cequivc_mkc_add {o} :\n  forall lib (a b c d : @CTerm o),\n    cequivc lib a c\n    -> cequivc lib b d\n    -> cequivc lib (mkc_add a b) (mkc_add c d).\nProof.\n  introv c1 c2; destruct_cterms; allunfold @cequivc; allsimpl.\n  destruct c1, c2.\n  split; apply implies_approx_add; auto.\nQed.\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/cequiv_arith_props.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.27669690436688293}}
{"text": "Require Import monad.\n\nInductive Exceptional (e a : Type) :=\n  | success : a -> Exceptional e a\n  | exception : e -> Exceptional e a.\n\nParameter e : Type.\n\nInstance Exceptional_Monad : Monad (Exceptional e) := {\n  bind a b i f := \n    match i with\n      | success k   => f k\n      | exception l => exception e b l\n    end;\n  ret a := success e a\n}.\n\nProof.\n  reflexivity.\n\n  intros a m'; destruct m'; reflexivity.\n\n  intros a b c i f g; destruct i; reflexivity.\nDefined.\n\nParameter a : Type.\nDefinition throw := exception.\nDefinition catch (g : Exceptional e a) (h : e -> Exceptional e a)  : Exceptional e a :=\n  match g with\n    | exception l => h l\n    | _ => g\n  end.\n", "meta": {"author": "heades", "repo": "examples", "sha": "30f2f4811828870820f34253ed5a51c76723eef1", "save_path": "github-repos/coq/heades-examples", "path": "github-repos/coq/heades-examples/examples-30f2f4811828870820f34253ed5a51c76723eef1/coq/monads/exception.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.2766966039170212}}
{"text": "(* DEC1 language development.\n   Paolo Torrini, with David Nowak\n   Universite' Lille-1 - CRIStAL-CNRS\n*)\n(* proofs about determinism *)\n\nRequire Export Basics.\n\nRequire Export EnvLibA.\nRequire Export RelLibA.\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 Coq.Logic.ProofIrrelevance.\n\nRequire Import StaticSemA.\nRequire Import DynamicSemA.\nRequire Import TRInductA.\nRequire Import WeakenA.\nRequire Import TSoundnessA.\nRequire Import SReducA.\n\nRequire Import Coq.Logic.EqdepFacts.\n\nModule Determ (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 SReducI := SReduc IdT.\nExport SReducI.\n\n\n(** stepwise determinism *)\n\nDefinition UniqueEStep \n                     (fenv: funEnv) (env: valEnv)\n                     (n n1 n2: W) (e e1 e2: Exp) :=\n    EStep fenv env (Conf Exp n e) ((Conf Exp n1 e1)) ->\n    EStep fenv env (Conf Exp n e) ((Conf Exp n2 e2)) -> \n        (n1 = n2) /\\ (e1 = e2).\n\n\nDefinition UniquePStep\n                     (fenv: funEnv) (env: valEnv)\n                     (n n1 n2: W) (ps ps1 ps2: Prms) :=\n    PrmsStep fenv env (Conf Prms n ps) ((Conf Prms n1 ps1)) ->\n    PrmsStep fenv env (Conf Prms n ps) ((Conf Prms n2 ps2)) -> \n        (n1 = n2) /\\ (ps1 = ps2).\n\n\nDefinition UniqueQFStep\n                         (fenv: funEnv) \n                         (n n1 n2: W) (q q1 q2: QFun) :=\n    QFStep fenv (Conf QFun n q) ((Conf QFun n1 q1)) ->\n    QFStep fenv (Conf QFun n q) ((Conf QFun n2 q2)) -> \n        (n1 = n2) /\\ (q1 = q2).\n\n\nDefinition UniqueQVStep \n                         (env: valEnv)\n                         (n n1 n2: W) (q q1 q2: QValue) :=\n    QVStep env (Conf QValue n q) ((Conf QValue n1 q1)) ->\n    QVStep env (Conf QValue n q) ((Conf QValue n2 q2)) -> \n        (n1 = n2) /\\ (q1 = q2).\n\n\n\n(*******************************************************)\n\nDefinition DPar_E :=\n  fun (ftenv: funTC) (tenv: valTC) (fenv: funEnv)\n      (e: Exp) (t: VTyp) \n      (p: ExpTyping ftenv tenv fenv e t) =>\n  FEnvTyping fenv ftenv ->\n  forall (env: valEnv),                      \n    EnvTyping env tenv ->\n  forall (n n1 n2: W) (e1 e2: Exp), \n         UniqueEStep fenv env n n1 n2 e e1 e2.\n\n\nDefinition DPar_P :=\n  fun (ftenv: funTC) (tenv: valTC) (fenv: funEnv)\n                (ps: Prms) (pt: PTyp) \n                (p: PrmsTyping ftenv tenv fenv ps pt) => \n  FEnvTyping fenv ftenv ->\n  forall (env: valEnv),                      \n    EnvTyping env tenv ->\n    forall (n n1 n2: W) (ps1 ps2: Prms),  \n          UniquePStep fenv env n n1 n2 ps ps1 ps2.\n\n\nDefinition DPar_F := fun (f: Fun) (ft: FTyp) \n   (p: FunTyping f ft) =>\n   (forall (fps: valTC) (t: VTyp),\n    ft = FT fps t ->      \n    forall (i: nat) (fenv': funEnv) \n           (x: Id) (e0 e1: Exp), \n       f = FC fenv' fps e0 e1 x i -> \n       forall (n: W) (env: valEnv), \n       EnvTyping env fps -> \n       match i with \n         | 0 => forall (n1 n2: W) (e01 e02: Exp),\n                  UniqueEStep fenv' env n n1 n2 e0 e01 e02\n         | S j => forall (n1 n2: W) (e11 e12: Exp),\n                  UniqueEStep (updateE fenv' x (FC fenv' fps e0 e1 x j))\n                                 env n n1 n2 e1 e11 e12\n        end).\n   \n\nDefinition DPar_Q :=\n   fun (ftenv: funTC) (fenv: funEnv)\n          (qf: QFun) (ft: FTyp) \n   (p: QFunTyping ftenv fenv qf ft) =>\n   FEnvTyping fenv ftenv ->\n   forall (n n1 n2: W) (qf qf1 qf2: QFun),                        \n   UniqueQFStep fenv n n1 n2 qf qf1 qf2.\n\n\nDefinition ExpTypingDet_rect :=\n  ExpTyping_str_rect DPar_F DPar_Q DPar_E DPar_P.\n\n\n(************************************************************************)\n\nDefinition UniqueVal \n                     (fenv: funEnv) (env: valEnv)\n                     (n n1: W) (e: Exp) (v1: Value) :=\n  forall (n2: W) (v2: Value),\n     EClosure fenv env (Conf Exp n e) ((Conf Exp n2 (Val v2))) -> \n        (n2 = n1) /\\ (v2 = v1).\n\n\nDefinition UniquePVal \n                      (fenv: funEnv) (env: valEnv)\n                      (n n1: W) (ps: Prms) (vs1: list Exp) :=\n  forall (n2: W) (vs2: list Exp),\n    isValueList vs1 ->\n    isValueList vs2 ->\n    PrmsClosure fenv env (Conf Prms n ps)\n                              ((Conf Prms n2 (PS vs2))) -> \n        (n2 = n1) /\\ (vs2 = vs1).\n\n\nLemma QVDeterminism :\n  forall (env: valEnv) (n n1 n2: W) (q q1 q2: QValue), \n    QVStep env (Conf QValue n q) ((Conf QValue n1 q1)) ->\n    QVStep env (Conf QValue n q) ((Conf QValue n2 q2)) -> \n        (n1 = n2) /\\ (q1 = q2).\nProof.\n  intros.\n  inversion X0; subst.\n  inversion X; subst.\n  inversion X1; subst.\n  inversion X2; subst.\n  rewrite H in H0.\n  inversion H0; subst.\n  auto.\nDefined.  \n\n\nLemma QFDeterminism :\n  forall (fenv: funEnv) (n n1 n2: W) (qf qf1 qf2: QFun), \n         UniqueQFStep fenv n n1 n2 qf qf1 qf2.\nProof.\n  intros.\n  unfold UniqueQFStep.\n  intros.\n  inversion X; subst.\n  inversion X0; subst.\n  inversion X1; subst.\n  inversion X2; subst.\n  rewrite H in H0.\n  inversion H0; subst.\n  auto.\nDefined.  \n\n\nLemma deterAux1 (n1 n2: W) (v1 v2: Value) (e3 e4 e5 e6: Exp) :\n  Conf Exp n1 (IfThenElse (Val v1) e3 e4) =\n  Conf Exp n2 (IfThenElse (Val v2) e5 e6) ->\n  v1 = v2.\n  intros.\n  inversion H; subst.\n  auto.\n Defined.\n\nLemma deterAux2 (n1 n2: W) (e1 e2 e3 e4 e5 e6: Exp) :\n  Conf Exp n1 (IfThenElse e1 e3 e4) =\n  Conf Exp n2 (IfThenElse e2 e5 e6) ->\n  e1 = e2.\n  intros.\n  inversion H; subst.\n  auto.\n Defined.\n\n\nLemma ExpDeterminism :\n  forall (ftenv: funTC) (tenv: valTC) (fenv: funEnv)\n         (e: Exp) (t: VTyp),   \n      ExpTyping ftenv tenv fenv e t -> \n      FEnvTyping fenv ftenv ->\n  forall (env: valEnv),                      \n    EnvTyping env tenv ->\n  forall (n n1 n2: W) (e1 e2: Exp), \n         UniqueEStep fenv env n n1 n2 e e1 e2.\n\nProof.\neapply ExpTypingDet_rect.\n- (* SLL *)\n  unfold Par_SSL, DPar_E.\n  unfold UniqueEStep.\n  constructor.\n- (* SLL *)\n  unfold Par_SSL, DPar_E.\n  intros.\n  constructor.\n  assumption.\n  assumption.\n  assumption.\n- (* SSA *)  \n  unfold Par_SSA, DPar_F.\n  constructor.\n- unfold Par_SSA, DPar_F.\n  intros.\n  constructor.\n  assumption.\n  assumption.\n  assumption.\n- (* SSB *)\n  unfold Par_SSB, Par_SSA, DPar_F.\n  intros.\n  econstructor.\n  exact m0.\n  exact m1.\n  assumption.\n  assumption.\n  assumption.\n  assumption.\n  assumption.\n  assumption.\n- (* Par_F *)\n  unfold DPar_E, DPar_F.\n  intros.\n  inversion H0; subst.\n  inversion H1; subst. \n  intros.\n  eauto.\n- (* Par_F *)\n  unfold DPar_E, DPar_F.\n  intros ftenv tenv fenv.\n  intros e0 e1 x n t.\n  intros K1 K2 K3 HP1 HP2.\n  intros fps t0 E3.\n  intros i fenv1 x0 e2 e3 E4 n0 env H.\n  inversion E3; subst.\n  inversion E4; subst.\n  eapply HP1.\n  eapply updateFEnvLemma.\n  assumption.\n  assumption.\n  assumption.\n- (* Par_Q - QF *)\n  unfold DPar_F, DPar_Q.\n  intros.\n  eapply QFDeterminism.\n- (* Par_Q - FVar *)  \n  unfold DPar_F,  DPar_Q.\n  intros.\n  eapply QFDeterminism.\n- (* modify *)\n  unfold DPar_E.\n  unfold UniqueEStep.\n  intros ftenv tenv fenv T1 T2 VT1 VT2 XF q K H0 env H0'.\n  intros n n1 n2 e1 e2.\n  intros.  \n  inversion X; subst.\n  assert (VT4 = VT1).\n  eapply loc_pi.\n  subst.\n  assert (VT5 = VT2).\n  eapply loc_pi.\n  subst.\n  eapply inj_pair2 in H6.\n  eapply inj_pair2 in H6; subst.\n  clear XF2.\n  inversion X0; subst.\n  eapply inj_pair2 in H8; subst.\n  eapply inj_pair2 in H6.\n  eapply inj_pair2 in H6; subst.\n  auto.\n  inversion X1; subst.\n  assert (VT4 = VT1).\n  eapply loc_pi.\n  subst.\n  assert (VT5 = VT2).\n  eapply loc_pi.\n  subst.\n  eapply inj_pair2 in H6.\n  eapply inj_pair2 in H6; subst.  \n  clear XF2.\n  inversion X0; subst.\n  clear XF2.\n  clear VT4.\n  clear VT5.\n  eapply inj_pair2 in H6.\n  eapply inj_pair2 in H6; subst.  \n  inversion X1; subst.  \n  assert (VT4 = VT1).\n  eapply loc_pi.\n  subst.\n  assert (VT5 = VT2).\n  eapply loc_pi.\n  subst.\n  eapply inj_pair2 in H6.\n  eapply inj_pair2 in H6; subst.  \n  inversion X1; subst.\n  inversion X2; subst.\n  inversion X3; subst.  \n  inversion X4; subst.\n  rewrite H in H1.\n  inversion H1; subst.\n  auto.\n  (* return *)\n- unfold DPar_E.\n  unfold UniqueEStep.\n  intros G ftenv tenv fenv q t k1.\n  intros H0 env H0'.\n  intros n n1 n2 e1 e2.\n  intros X X0.\n  inversion X; subst.\n  inversion X0; subst.\n  auto.\n  inversion X1; subst.\n  inversion X1; subst.\n  inversion X0; subst.\n  inversion X3; subst.\n  inversion X2; subst.\n  inversion X4; subst.\n  rewrite H in H1.\n  inversion H1; subst.\n  auto.\n(* bindN *)\n- unfold DPar_E.\n  unfold UniqueEStep.\n  intros ftenv tenv fenv e1 e2 t1 t2 K1 K2 HP1 HP2 H0 env H0'.\n  intros n n1 n2 e0 e3.\n  intros.\n  inversion X; subst.\n  + inversion X0; subst.\n    * auto.\n    * inversion X1. \n  + inversion X0; subst.\n    * inversion X1. \n    * rename e1'0 into e2'.\n      assert (n1 = n2 /\\ e1' = e2'). \n      eapply HP1.\n      assumption.\n      eassumption.\n      eassumption.\n      assumption.\n      destruct H.\n      rewrite H1.\n      auto.\n(* bindS *)        \n- unfold DPar_E.\n  unfold UniqueEStep.\n  intros ftenv tenv fenv x e1 e2 t1 t2.\n  intros K1 K2 HP1 HP2 H0 env H0'.\n  intros n n1 n2 e0 e3.\n  intros.\n  inversion X; subst.\n    + inversion X0; subst.\n      * auto.\n      * inversion X1.\n    + inversion X0; subst.\n      * inversion X1.\n      * rename e1'0 into e2'.\n        assert (n1 = n2 /\\ e1' = e2'). \n        eapply HP1.\n        assumption.\n        eassumption.\n        eassumption.\n        assumption.\n        destruct H.\n        rewrite H1.\n        auto.\n(* bindMS *)        \n  - unfold DPar_E.\n    unfold UniqueEStep.\n    intros ftenv ftenvP ftenv' tenv tenvP tenv' fenv fenvP fenv' envP.\n    intros e t.\n    intros K1 K2 K3 K4 K5 K6 K7 HP.\n    intros H0 env H0'.\n    intros n n1 n2 e1 e2.\n    intros.\n    inversion X; subst.\n    + inversion X0; subst.\n      * auto.\n      * inversion X1.\n    + inversion X0; subst.\n      inversion X1.\n      rename e'0 into e''.\n      assert (n1 = n2 /\\ e' = e'').\n      eapply HP.\n      eapply overrideEnvLemmaT.\n      assumption.\n      assumption.\n      eapply overrideEnvLemmaT.\n      eassumption.\n      eassumption.\n      eassumption.\n      assumption.\n      destruct H.\n      rewrite H1.\n      auto.\n(* apply *)        \n  - unfold DPar_P, DPar_Q, DPar_E.\n    unfold UniqueEStep.\n    unfold UniqueQFStep.\n    unfold UniquePStep.\n    intros ftenv tenv fps fenv.\n    intros q ps pt t.\n    intros K1 K2 K3 K4 HP1 HP2.\n    intros H0 env H0'.\n    intros n n1 n2 e1 e2.\n    intros.\n    inversion X; subst.\n    + inversion X0; subst.\n      * inversion H6; subst.\n        inversion H5; subst.\n        eapply vlaMapEq in H.  \n        rewrite H.\n        auto.\n      * destruct ps'.\n        eapply NoPrmsStep in X1.\n        intuition X1.\n        apply isValueList2IsValueT in H6.\n        assumption.\n      * inversion X1.\n    + inversion X0; subst.\n      * inversion H6; subst.\n        inversion H5; subst.\n        eapply vlaMapEq in H.  \n        rewrite H.\n        auto.\n      * destruct ps'.\n        eapply NoPrmsStep in X1.\n        intuition X1.\n        apply isValueList2IsValueT in H6.\n        assumption.\n      * inversion X1.\n    + inversion X0; subst.\n      * destruct ps'.\n        eapply NoPrmsStep in X1.\n        intuition X1.\n        apply isValueList2IsValueT in H6.\n        assumption.\n      * destruct ps'.\n        eapply NoPrmsStep in X1.\n        intuition X1.\n        apply isValueList2IsValueT in H6.\n        assumption.\n      * rename ps'0 into ps''.\n        assert (n1 = n2 /\\ ps' = ps'').\n        eapply HP2.\n        assumption.\n        eassumption.\n        eassumption.\n        assumption.\n        destruct H.\n        rewrite H1.\n        auto.\n      * inversion X2.\n    + inversion X0; subst.\n      * inversion X1.\n      * inversion X1.\n      * inversion X1.\n      * rename qf'0 into qf''.\n        assert (n1 = n2 /\\ qf' = qf'').\n        eapply HP1.\n        assumption.\n        eassumption.\n        assumption.\n        destruct H.\n        rewrite H1.\n        auto.\n(* val *)\n  - unfold DPar_E.\n    unfold UniqueEStep.\n    intros ftenv tenv fenv.\n    intros v t.\n    intros K H0 env H0'.\n    intros n n1 n2 e1 e2.\n    intros.\n    inversion X.\n  - (* ifthenelse *)\n    unfold DPar_E.\n    intros.\n    unfold UniqueEStep.\n    intros.\n    inversion X1; subst.\n    inversion X2; subst.\n    auto.\n    eapply deterAux1 in H4.\n    unfold cst in H4.\n    eapply inj_pair2 in H4.\n    inversion H4.\n    inversion X2; subst.\n    rewrite <- H9.\n    rewrite <- H9.\n    auto.\n    inversion X3.\n    inversion X4.\n    inversion X2; subst.\n    eapply deterAux1 in H4.\n    unfold cst in H4.\n    eapply inj_pair2 in H4.\n    inversion H4.\n    auto.\n    inversion X3.\n    inversion X2; subst.\n    inversion X3.\n    inversion X1; subst.\n    inversion X3.\n    rewrite H9 at 2.\n    auto.\n    inversion X4.\n    unfold UniqueEStep in H.\n    rename e'0 into e''. \n    assert (n1 = n2 /\\ e' = e'').\n    eapply H.\n    assumption.\n    eassumption.\n    eassumption.\n    assumption.\n    destruct H2.\n    rewrite H2.\n    rewrite H3.\n    auto.\n  - (* SLL *)\n    unfold Par_SSL, DPar_P, DPar_E.\n    unfold UniquePStep, UniqueEStep.\n    intros ftenv tenv fenv.\n    intros es ts K HP H0 env H0'.\n    intros n n1 n2 ps1 ps2.\n    intros.\n    revert K.\n    dependent induction HP.\n    inversion X0.\n    intro K.\n    inversion X0; subst.\n    inversion X; subst. \n    rename es'0 into es''.\n    assert (n1 = n2 /\\ PS es'' = PS es').\n    eapply IHHP.\n    assumption.\n    eassumption.\n    eassumption.\n    assumption.\n    inversion K; subst.\n    assumption.\n    destruct H.\n    inversion H1; subst.\n    auto.\n    (**)\n    inversion X2.\n    (**)\n    inversion X; subst.\n    inversion X1.\n    rename e'0 into e''.    \n    assert (n1 = n2 /\\ e'' = e').\n    eapply p0.\n    assumption.\n    eassumption.\n    eassumption.\n    assumption.\n    destruct H.\n    rewrite H1.\n    auto.\nDefined.\n\n(*********************************************************************)\n\nDefinition PrmsTypingDet_rect :=\n  PrmsTyping_str_rect DPar_F DPar_Q DPar_E DPar_P.\n\n\nLemma PrmsDeterminism :\n  forall (ftenv: funTC) (tenv: valTC) (fenv: funEnv)\n         (ps: Prms) (pt: PTyp),   \n      PrmsTyping ftenv tenv fenv ps pt -> \n      FEnvTyping fenv ftenv ->\n  forall (env: valEnv),                      \n    EnvTyping env tenv ->\n  forall (n n1 n2: W) (ps1 ps2: Prms), \n         UniquePStep fenv env n n1 n2 ps ps1 ps2.\n\nProof.\neapply PrmsTypingDet_rect.\n- (* SLL *)\n  unfold Par_SSL, DPar_E.\n  unfold UniqueEStep.\n  constructor.\n- (* SLL *)\n  unfold Par_SSL, DPar_E.\n  intros.\n  constructor.\n  assumption.\n  assumption.\n  assumption.\n- (* SSA *)  \n  unfold Par_SSA, DPar_F.\n  constructor.\n- unfold Par_SSA, DPar_F.\n  intros.\n  constructor.\n  assumption.\n  assumption.\n  assumption.\n- (* SSB *)\n  unfold Par_SSB, Par_SSA, DPar_F.\n  intros.\n  econstructor.\n  exact m0.\n  exact m1.\n  assumption.\n  assumption.\n  assumption.\n  assumption.\n  assumption.\n  assumption.\n- (* Par_F *)\n  unfold DPar_E, DPar_F.\n  intros.\n  inversion H0; subst.\n  inversion H1; subst. \n  intros.\n  eauto.\n- (* Par_F *)\n  unfold DPar_E, DPar_F.\n  intros ftenv tenv fenv.\n  intros e0 e1 x n t.\n  intros K1 K2 K3 HP1 HP2.\n  intros fps t0 E3.\n  intros i fenv1 x0 e2 e3 E4 n0 env H.\n  inversion E3; subst.\n  inversion E4; subst.\n  eapply HP1.\n  eapply updateFEnvLemma.\n  assumption.\n  assumption.\n  assumption.\n- (* Par_Q - QF *)\n  unfold DPar_F, DPar_Q.\n  intros.\n  eapply QFDeterminism.\n- (* Par_Q - FVar *)  \n  unfold DPar_F,  DPar_Q.\n  intros.\n  eapply QFDeterminism.\n- (* modify *)\n  unfold DPar_E.\n  unfold UniqueEStep.\n  intros ftenv tenv fenv T1 T2 VT1 VT2 XF q K H0 env H0'.\n  intros n n1 n2 e1 e2.\n  intros.  \n  inversion X; subst.\n  assert (VT4 = VT1).\n  eapply loc_pi.\n  subst.\n  assert (VT5 = VT2).\n  eapply loc_pi.\n  subst.\n  eapply inj_pair2 in H6.\n  eapply inj_pair2 in H6; subst.\n  clear XF2.\n  inversion X0; subst.\n  eapply inj_pair2 in H8; subst.\n  eapply inj_pair2 in H6.\n  eapply inj_pair2 in H6; subst.\n  auto.\n  inversion X1; subst.\n  assert (VT4 = VT1).\n  eapply loc_pi.\n  subst.\n  assert (VT5 = VT2).\n  eapply loc_pi.\n  subst.\n  eapply inj_pair2 in H6.\n  eapply inj_pair2 in H6; subst.  \n  clear XF2.\n  inversion X0; subst.\n  clear XF2.\n  clear VT4.\n  clear VT5.\n  eapply inj_pair2 in H6.\n  eapply inj_pair2 in H6; subst.  \n  inversion X1; subst.  \n  assert (VT4 = VT1).\n  eapply loc_pi.\n  subst.\n  assert (VT5 = VT2).\n  eapply loc_pi.\n  subst.\n  eapply inj_pair2 in H6.\n  eapply inj_pair2 in H6; subst.  \n  inversion X1; subst.\n  inversion X2; subst.\n  inversion X3; subst.  \n  inversion X4; subst.\n  rewrite H in H1.\n  inversion H1; subst.\n  auto.\n  (* return *)\n- unfold DPar_E.\n  unfold UniqueEStep.\n  intros G ftenv tenv fenv q t k1.\n  intros H0 env H0'.\n  intros n n1 n2 e1 e2.\n  intros X X0.\n  inversion X; subst.\n  inversion X0; subst.\n  auto.\n  inversion X1; subst.\n  inversion X1; subst.\n  inversion X0; subst.\n  inversion X3; subst.\n  inversion X2; subst.\n  inversion X4; subst.\n  rewrite H in H1.\n  inversion H1; subst.\n  auto.\n(* bindN *)\n- unfold DPar_E.\n  unfold UniqueEStep.\n  intros ftenv tenv fenv e1 e2 t1 t2 K1 K2 HP1 HP2 H0 env H0'.\n  intros n n1 n2 e0 e3.\n  intros.\n  inversion X; subst.\n  + inversion X0; subst.\n    * auto.\n    * inversion X1. \n  + inversion X0; subst.\n    * inversion X1. \n    * rename e1'0 into e2'.\n      assert (n1 = n2 /\\ e1' = e2'). \n      eapply HP1.\n      assumption.\n      eassumption.\n      eassumption.\n      assumption.\n      destruct H.\n      rewrite H1.\n      auto.\n(* bindS *)        \n- unfold DPar_E.\n  unfold UniqueEStep.\n  intros ftenv tenv fenv x e1 e2 t1 t2.\n  intros K1 K2 HP1 HP2 H0 env H0'.\n  intros n n1 n2 e0 e3.\n  intros.\n  inversion X; subst.\n    + inversion X0; subst.\n      * auto.\n      * inversion X1.\n    + inversion X0; subst.\n      * inversion X1.\n      * rename e1'0 into e2'.\n        assert (n1 = n2 /\\ e1' = e2'). \n        eapply HP1.\n        assumption.\n        eassumption.\n        eassumption.\n        assumption.\n        destruct H.\n        rewrite H1.\n        auto.\n(* bindMS *)        \n  - unfold DPar_E.\n    unfold UniqueEStep.\n    intros ftenv ftenvP ftenv' tenv tenvP tenv' fenv fenvP fenv' envP.\n    intros e t.\n    intros K1 K2 K3 K4 K5 K6 K7 HP.\n    intros H0 env H0'.\n    intros n n1 n2 e1 e2.\n    intros.\n    inversion X; subst.\n    + inversion X0; subst.\n      * auto.\n      * inversion X1.\n    + inversion X0; subst.\n      inversion X1.\n      rename e'0 into e''.\n      assert (n1 = n2 /\\ e' = e'').\n      eapply HP.\n      eapply overrideEnvLemmaT.\n      assumption.\n      assumption.\n      eapply overrideEnvLemmaT.\n      eassumption.\n      eassumption.\n      eassumption.\n      assumption.\n      destruct H.\n      rewrite H1.\n      auto.\n(* apply *)        \n  - unfold DPar_P, DPar_Q, DPar_E.\n    unfold UniqueEStep.\n    unfold UniqueQFStep.\n    unfold UniquePStep.\n    intros ftenv tenv fps fenv.\n    intros q ps pt t.\n    intros K1 K2 K3 K4 HP1 HP2.\n    intros H0 env H0'.\n    intros n n1 n2 e1 e2.\n    intros.\n    inversion X; subst.\n    + inversion X0; subst.\n      * inversion H6; subst.\n        inversion H5; subst.\n        eapply vlaMapEq in H.  \n        rewrite H.\n        auto.\n      * destruct ps'.\n        eapply NoPrmsStep in X1.\n        intuition X1.\n        apply isValueList2IsValueT in H6.\n        assumption.\n      * inversion X1.\n    + inversion X0; subst.\n      * inversion H6; subst.\n        inversion H5; subst.\n        eapply vlaMapEq in H.  \n        rewrite H.\n        auto.\n      * destruct ps'.\n        eapply NoPrmsStep in X1.\n        intuition X1.\n        apply isValueList2IsValueT in H6.\n        assumption.\n      * inversion X1.\n    + inversion X0; subst.\n      * destruct ps'.\n        eapply NoPrmsStep in X1.\n        intuition X1.\n        apply isValueList2IsValueT in H6.\n        assumption.\n      * destruct ps'.\n        eapply NoPrmsStep in X1.\n        intuition X1.\n        apply isValueList2IsValueT in H6.\n        assumption.\n      * rename ps'0 into ps''.\n        assert (n1 = n2 /\\ ps' = ps'').\n        eapply HP2.\n        assumption.\n        eassumption.\n        eassumption.\n        assumption.\n        destruct H.\n        rewrite H1.\n        auto.\n      * inversion X2.\n    + inversion X0; subst.\n      * inversion X1.\n      * inversion X1.\n      * inversion X1.\n      * rename qf'0 into qf''.\n        assert (n1 = n2 /\\ qf' = qf'').\n        eapply HP1.\n        assumption.\n        eassumption.\n        assumption.\n        destruct H.\n        rewrite H1.\n        auto.\n(* val *)\n  - unfold DPar_E.\n    unfold UniqueEStep.\n    intros ftenv tenv fenv.\n    intros v t.\n    intros K H0 env H0'.\n    intros n n1 n2 e1 e2.\n    intros.\n    inversion X.\n  - (* ifthenelse *)\n    unfold DPar_E.\n    intros.\n    unfold UniqueEStep.\n    intros.\n    inversion X1; subst.\n    inversion X2; subst.\n    auto.\n    eapply deterAux1 in H4.\n    unfold cst in H4.\n    eapply inj_pair2 in H4.\n    inversion H4.\n    inversion X2; subst.\n    rewrite <- H9.\n    rewrite <- H9.\n    auto.\n    inversion X3.\n    inversion X4.\n    inversion X2; subst.\n    eapply deterAux1 in H4.\n    unfold cst in H4.\n    eapply inj_pair2 in H4.\n    inversion H4.\n    auto.\n    inversion X3.\n    inversion X2; subst.\n    inversion X3.\n    inversion X1; subst.\n    inversion X3.\n    rewrite H9 at 2.\n    auto.\n    inversion X4.\n    unfold UniqueEStep in H.\n    rename e'0 into e''. \n    assert (n1 = n2 /\\ e' = e'').\n    eapply H.\n    assumption.\n    eassumption.\n    eassumption.\n    assumption.\n    destruct H2.\n    rewrite H2.\n    rewrite H3.\n    auto.\n  - (* SLL *)\n    unfold Par_SSL, DPar_P, DPar_E.\n    unfold UniquePStep, UniqueEStep.\n    intros ftenv tenv fenv.\n    intros es ts K HP H0 env H0'.\n    intros n n1 n2 ps1 ps2.\n    intros.\n    revert K.\n    dependent induction HP.\n    inversion X0.\n    intro K.\n    inversion X0; subst.\n    inversion X; subst. \n    rename es'0 into es''.\n    assert (n1 = n2 /\\ PS es'' = PS es').\n    eapply IHHP.\n    assumption.\n    eassumption.\n    eassumption.\n    assumption.\n    inversion K; subst.\n    assumption.\n    destruct H.\n    inversion H1; subst.\n    auto.\n    (**)\n    inversion X2.\n    (**)\n    inversion X; subst.\n    inversion X1.\n    rename e'0 into e''.    \n    assert (n1 = n2 /\\ e'' = e').\n    eapply p0.\n    assumption.\n    eassumption.\n    eassumption.\n    assumption.\n    destruct H.\n    rewrite H1.\n    auto.\nDefined.\n\n\n(************************************************************************)\n\n(** Confluence of evaluation *)\n\nDefinition UniEStep \n                     (fenv: funEnv) (env: valEnv)\n                     (p p1 p2 : AConfig Exp) :=\n    EStep fenv env p p1 ->\n    EStep fenv env p p2 -> \n        p1 = p2.\n\n\nLemma ExpDeterminismA :\n  forall (ftenv: funTC) (tenv: valTC) (fenv: funEnv)\n         (e: Exp) (t: VTyp),   \n      ExpTyping ftenv tenv fenv e t -> \n      FEnvTyping fenv ftenv ->\n  forall (env: valEnv),                      \n    EnvTyping env tenv ->\n  forall (n: W) (p1 p2 : AConfig Exp), \n         UniEStep fenv env (Conf Exp n e) p1 p2.\nintros.\nunfold UniEStep.  \ndestruct p1.\ndestruct p2.\nintros.\nassert (state = state0 /\\ qq = qq0). \neapply ExpDeterminism.\nexact X.\nexact X0.\nexact X1.\nexact X2.\nexact X3.\ndestruct H.\nsubst.\nauto.\nDefined.\n\n\n\nDefinition UniqueEClos (fenv: funEnv) (env: valEnv)\n                        (n n1 n2: W) (e : Exp) (v1 v2: Value) :=\n    EClosure fenv env (Conf Exp n e) ((Conf Exp n1 (Val v1))) ->\n    EClosure fenv env (Conf Exp n e) ((Conf Exp n2 (Val v2))) -> \n        (n1 = n2) /\\ (v1 = v2).\n\n\nLemma ExpConfluence :\n  forall (ftenv: funTC) (tenv: valTC) (fenv: funEnv)\n         (e: Exp) (t: VTyp),   \n      ExpTyping ftenv tenv fenv e t -> \n      FEnvTyping fenv ftenv ->\n  forall (env: valEnv),                      \n    EnvTyping env tenv ->\n  forall (n n1 n2: W) (v1 v2: Value), \n         UniqueEClos fenv env n n1 n2 e v1 v2.\n\nProof.\n  unfold UniqueEClos.\n  intros.\n  revert X3.  \n  dependent induction X2.\n  intros.\n  inversion X3; subst.\n  auto.\n  dependent destruction X4.\n  inversion X2.\n  inversion X2.\n  intros.\n  dependent destruction X3.\n  inversion e0.\n\n  assert (p0 = p2).\n  destruct p0.\n  destruct p2.\n  eapply ExpDeterminismA.\n  exact X.\n  assumption.\n  exact X1.\n  eassumption.\n  assumption.\n  rewrite H in *; clear H.\n\n  (* need subject reduction *)\n  destruct p2.\n\n  assert (ExpTyping ftenv tenv fenv qq t).\n  eapply ExpSubjectRed.\n  exact X.\n  exact X0.\n  exact X1.\n  exact e1.\n   \n  eapply IHX2.\n  exact X4.\n  exact X0.\n  exact X1.\n  reflexivity.  \n  reflexivity.\n  exact X3.\nDefined.\n\n\nDefinition UniPStep \n                     (fenv: funEnv) (env: valEnv)\n                     (p p1 p2 : AConfig Prms) :=\n    PrmsStep fenv env p p1 ->\n    PrmsStep fenv env p p2 -> \n        p1 = p2.\n\n\nLemma PrmsDeterminismA :\n  forall (ftenv: funTC) (tenv: valTC) (fenv: funEnv)\n         (ps: Prms) (pt: PTyp),   \n      PrmsTyping ftenv tenv fenv ps pt -> \n      FEnvTyping fenv ftenv ->\n  forall (env: valEnv),                      \n    EnvTyping env tenv ->\n  forall (n: W) (p1 p2 : AConfig Prms), \n         UniPStep fenv env (Conf Prms n ps) p1 p2.\nintros.\nunfold UniPStep.  \ndestruct p1.\ndestruct p2.\nintros.\nassert (state = state0 /\\ qq = qq0). \neapply PrmsDeterminism.\nexact X.\nexact X0.\nexact X1.\nexact X2.\nexact X3.\ndestruct H.\nsubst.\nauto.\nDefined.\n\n\nDefinition UniquePClos (fenv: funEnv) (env: valEnv)\n                        (n n1 n2: W) (ps : Prms) (vs1 vs2: list Value) :=\n  PrmsClosure fenv env (Conf Prms n ps) ((Conf Prms n1 (PS (map Val vs1)))) ->\n  PrmsClosure fenv env (Conf Prms n ps) ((Conf Prms n2 (PS (map Val vs2)))) -> \n        (n1 = n2) /\\ (vs1 = vs2).\n\n\nLemma PrmsConfluence :\n  forall (ftenv: funTC) (tenv: valTC) (fenv: funEnv)\n         (ps: Prms) (pt: PTyp),   \n      PrmsTyping ftenv tenv fenv ps pt -> \n      FEnvTyping fenv ftenv ->\n  forall (env: valEnv),                      \n    EnvTyping env tenv ->\n  forall (n n1 n2: W) (vs1 vs2: list Value), \n         UniquePClos fenv env n n1 n2 ps vs1 vs2.\n\nProof.\n  unfold UniquePClos.\n  intros.\n  revert X3.  \n  dependent induction X2.\n  intros.\n  inversion X3; subst.\n  eapply mapEq in H4.\n  auto.\n  dependent destruction X4.\n  eapply NoPrmsStep in X2.\n  intuition X2.\n  eapply isValueListT_triv.\n\n  destruct p1.\n  destruct qq.\n  eapply NoPrmsStep in X2.\n  intuition X2.\n  eapply isValueListT_triv.\n  \n  intros.\n  dependent destruction X3.\n  destruct p2.\n  destruct qq.\n  eapply NoPrmsStep in p.\n  intuition p.\n  eapply isValueListT_triv.\n  \n  assert (p0 = p2).\n  destruct p0.\n  destruct p2.\n  eapply PrmsDeterminismA.\n  exact X.\n  assumption.\n  exact X1.\n  eassumption.\n  assumption.\n  rewrite H in *; clear H.\n\n  (* need subject reduction *)\n  destruct p2.\n\n  assert (PrmsTyping ftenv tenv fenv qq pt).\n  eapply PrmsSubjectRed.\n  exact X.\n  exact X0.\n  exact X1.\n  exact p4.\n   \n  eapply IHX2.\n  exact X4.\n  exact X0.\n  exact X1.\n  reflexivity.  \n  reflexivity.\n  exact X3.\nDefined.\n\n\n(************************************************************************)\n\n(** extractors from the TS proof *)\n\nDefinition extractRunValue (ftenv: funTC) (tenv: valTC) (fenv: funEnv)\n   (e: Exp) (t: VTyp)\n   (k: ExpTyping ftenv tenv fenv e t)\n   (m1: MatchEnvsT FunTyping fenv ftenv)\n   (env: valEnv)                      \n   (m2: MatchEnvsT ValueTyping env tenv)\n   (s: W) : Value := projT1 (sigT_of_sigT2\n                           (ExpEval ftenv tenv fenv e t k m1 env m2 s)). \n\nDefinition extractRunState (ftenv: funTC) (tenv: valTC) (fenv: funEnv)\n   (e: Exp) (t: VTyp)\n   (k: ExpTyping ftenv tenv fenv e t)\n   (m1: MatchEnvsT FunTyping fenv ftenv)\n   (env: valEnv)                      \n   (m2: MatchEnvsT ValueTyping env tenv)\n   (s: W) : W := projT1 (projT3 (ExpEval ftenv tenv fenv e t k m1 env m2 s)). \n\nDefinition extractRunTyping (ftenv: funTC) (tenv: valTC) (fenv: funEnv)\n   (e: Exp) (t: VTyp)\n   (k: ExpTyping ftenv tenv fenv e t)\n   (m1: MatchEnvsT FunTyping fenv ftenv)\n   (env: valEnv)                      \n   (m2: MatchEnvsT ValueTyping env tenv)\n   (s: W) : ValueTyping\n              (extractRunValue ftenv tenv fenv e t k m1 env m2 s) t :=\n         projT2 (sigT_of_sigT2\n                       (ExpEval ftenv tenv fenv e t k m1 env m2 s)). \n\n(* SOS intepreter *)\nDefinition extractRunShallow (ftenv: funTC) (tenv: valTC) (fenv: funEnv)\n   (e: Exp) (t: VTyp)\n   (k: ExpTyping ftenv tenv fenv e t)\n   (m1: MatchEnvsT FunTyping fenv ftenv)\n   (env: valEnv)                      \n   (m2: MatchEnvsT ValueTyping env tenv)\n   (s: W) : (projT1 (extractRunValue ftenv tenv fenv e t k m1 env m2 s) * W) :=\n  let r := ExpEval ftenv tenv fenv e t k m1 env m2 s in\n  (cstExt (projT1 (sigT_of_sigT2 r)), projT1 (projT3 r)).    \n\nDefinition extractTyping (ftenv: funTC) (tenv: valTC) (fenv: funEnv)\n           (e: Exp) (k: sigT (ExpTyping ftenv tenv fenv e)) : VTyp :=\n            projT1 k.  \n\n\nDefinition extractPRunValue (ftenv: funTC) (tenv: valTC) (fenv: funEnv)\n   (ps: Prms) (pt: PTyp)\n   (k: PrmsTyping ftenv tenv fenv ps pt)\n   (m1: MatchEnvsT FunTyping fenv ftenv)\n   (env: valEnv)                      \n   (m2: MatchEnvsT ValueTyping env tenv)\n   (s: W) : list Value := projT1 (sigT_of_sigT2\n                    (projT2 (PrmsEval ftenv tenv fenv ps pt k m1 env m2 s))). \n\n\nDefinition extractPRunEValue (ftenv: funTC) (tenv: valTC) (fenv: funEnv)\n   (ps: Prms) (pt: PTyp)\n   (k: PrmsTyping ftenv tenv fenv ps pt)\n   (m1: MatchEnvsT FunTyping fenv ftenv)\n   (env: valEnv)                      \n   (m2: MatchEnvsT ValueTyping env tenv)\n   (s: W) : list Exp :=\n                    (projT1 (PrmsEval ftenv tenv fenv ps pt k m1 env m2 s)). \n\nDefinition extractPRunState (ftenv: funTC) (tenv: valTC) (fenv: funEnv)\n   (ps: Prms) (pt: PTyp)\n   (k: PrmsTyping ftenv tenv fenv ps pt)\n   (m1: MatchEnvsT FunTyping fenv ftenv)\n   (env: valEnv)                      \n   (m2: MatchEnvsT ValueTyping env tenv)\n   (s: W) : W := projT1 (snd (projT3 (projT2\n                        (PrmsEval ftenv tenv fenv ps pt k m1 env m2 s)))). \n\n\nDefinition extractPRunTyping (ftenv: funTC) (tenv: valTC) (fenv: funEnv)\n   (ps: Prms) (pt: PTyp)\n   (k: PrmsTyping ftenv tenv fenv ps pt)\n   (m1: MatchEnvsT FunTyping fenv ftenv)\n   (env: valEnv)                      \n   (m2: MatchEnvsT ValueTyping env tenv)\n   (s: W) : PrmsTyping  emptyE emptyE emptyE \n    (PS (projT1 (PrmsEval ftenv tenv fenv ps pt k m1 env m2 s))) pt :=\n         fst (projT3  \n                 (projT2 (PrmsEval ftenv tenv fenv ps pt k m1 env m2 s))). \n\n\n(*************************************************************************)\n\nLemma extractPRunCons  (ftenv: funTC) (tenv: valTC) (fenv: funEnv)\n   (ps: Prms) (pt: PTyp)\n   (k: PrmsTyping ftenv tenv fenv ps pt)\n   (m1: MatchEnvsT FunTyping fenv ftenv)\n   (env: valEnv)                      \n   (m2: MatchEnvsT ValueTyping env tenv)\n   (s: W) :\n  extractPRunEValue ftenv tenv fenv ps pt k m1 env m2 s =\n  map Val (extractPRunValue ftenv tenv fenv ps pt k m1 env m2 s).\n  generalize (projT2 (sigT_of_sigT2 \n                (projT2 (PrmsEval ftenv tenv fenv ps pt k m1 env m2 s)))).\n  intros.\n  inversion H; subst.\n  unfold extractPRunEValue, extractPRunValue.\n  auto.\nDefined.  \n\n\n(***********************************************************************)\n\nLemma EvalIntro \n   (ftenv: funTC) (tenv: valTC) (fenv: funEnv)\n   (e: Exp) (t: VTyp)\n   (k: ExpTyping ftenv tenv fenv e t)\n   (m1: MatchEnvsT FunTyping fenv ftenv)\n   (env: valEnv)                      \n   (m2: MatchEnvsT ValueTyping env tenv)\n   (s: W) :\n  EClosure fenv env (Conf Exp s e)\n           (Conf Exp (extractRunState ftenv tenv fenv e t k m1 env m2 s)\n                     (Val (extractRunValue ftenv tenv fenv e t k m1 env m2 s))).\n  unfold extractRunState.\n  unfold extractRunValue.\n  simpl. \n  destruct (ExpEval ftenv tenv fenv e t k m1 env m2 s).\n  destruct s0.\n  simpl.\n  auto.\nDefined.\n  \n\nLemma EvalElim \n   (ftenv: funTC) (tenv: valTC) (fenv: funEnv)\n   (e: Exp) (t: VTyp)\n   (k: ExpTyping ftenv tenv fenv e t)\n   (m1: MatchEnvsT FunTyping fenv ftenv)\n   (env: valEnv)                      \n   (m2: MatchEnvsT ValueTyping env tenv)\n   (s: W) :\n  forall (s': W) (v: Value), \n    EClosure fenv env (Conf Exp s e) (Conf Exp s' (Val v)) ->\n    (s' = extractRunState ftenv tenv fenv e t k m1 env m2 s) /\\\n    (v = extractRunValue ftenv tenv fenv e t k m1 env m2 s).\n  intros.\n  unfold extractRunState.\n  unfold extractRunValue.\n  eapply  ExpConfluence.\n  exact k.\n  exact m1.\n  exact m2.\n  exact X.\n  eapply EvalIntro.\nDefined.\n  \n\nLemma PEvalIntro \n   (ftenv: funTC) (tenv: valTC) (fenv: funEnv)\n   (ps: Prms) (pt: PTyp)\n   (k: PrmsTyping ftenv tenv fenv ps pt)\n   (m1: MatchEnvsT FunTyping fenv ftenv)\n   (env: valEnv)                      \n   (m2: MatchEnvsT ValueTyping env tenv)\n   (s: W) :\n  PrmsClosure fenv env (Conf Prms s ps)\n     (Conf Prms (extractPRunState ftenv tenv fenv ps pt k m1 env m2 s)\n        (PS (map Val (extractPRunValue ftenv tenv fenv ps pt k m1 env m2 s)))).\n  unfold extractPRunState.\n  unfold extractPRunValue.\n  simpl. \n  destruct (PrmsEval ftenv tenv fenv ps pt k m1 env m2 s).\n  destruct s0.\n  simpl.\n  destruct p.\n  inversion i; subst.\n  simpl in *.  \n  destruct s0.\n  auto.\nDefined.\n  \n\nLemma PEvalElim \n   (ftenv: funTC) (tenv: valTC) (fenv: funEnv)\n   (ps: Prms) (pt: PTyp)\n   (k: PrmsTyping ftenv tenv fenv ps pt)\n   (m1: MatchEnvsT FunTyping fenv ftenv)\n   (env: valEnv)                      \n   (m2: MatchEnvsT ValueTyping env tenv)\n   (s: W) :\n  forall (s': W) (vs: list Value), \n    PrmsClosure fenv env (Conf Prms s ps) (Conf Prms s' (PS (map Val vs))) ->\n    (s' = extractPRunState ftenv tenv fenv ps pt k m1 env m2 s) /\\\n    (vs = extractPRunValue ftenv tenv fenv ps pt k m1 env m2 s).\n  intros.\n  unfold extractPRunState.\n  unfold extractPRunValue.\n  eapply  PrmsConfluence.\n  exact k.\n  exact m1.\n  exact m2.\n  exact X.\n  eapply PEvalIntro.\nDefined.\n  \n\nEnd Determ.\n", "meta": {"author": "2xs", "repo": "dec", "sha": "79290ae2f92d437fe365a1b366a30e1eb2b83d19", "save_path": "github-repos/coq/2xs-dec", "path": "github-repos/coq/2xs-dec/dec-79290ae2f92d437fe365a1b366a30e1eb2b83d19/src/DEC1/DetermA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.27669660391702117}}
{"text": "(** * Basic Attention Token contract *)\n(** Proofs for BAToken contract defined in [ConCert.Examples.BAT.BATFixed]. *)\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 BATFixed.\nFrom ConCert.Examples.EIP20 Require EIP20Token.\nFrom ConCert.Examples.EIP20 Require EIP20TokenCorrect.\n\n\n\n(** * Contract properties *)\nSection Theories.\n  (* begin 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    | H : Blockchain.receive _ _ _ _ _ = Ok _ |- _ => unfold Blockchain.receive in H; cbn in H\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) 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    (isFinalized state) = true ->\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 * finalized.\n    unfold balances. cbn.\n    rewrite finalized. 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 account account_not_from.\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 account account_not_sender.\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    (isFinalized state) = true ->\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 * sender_amount_zero finalized.\n    unfold balances, allowances, get_allowance_. cbn.\n    rewrite finalized. 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 account account_not_sender.\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 account account_not_delegate.\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 /\\ (isFinalized state) = true <-> isOk (receive chain ctx state (Some (approve delegate amount))) = true.\n  Proof.\n    intros.\n    cbn.\n    destruct_match eqn:finalized_check;\n      destruct_throw_if finalized_check; split.\n    - intros (sender_amount_zero & finalized).\n      destruct_match eqn:receive.\n      + reflexivity.\n      + now erewrite EIP20TokenCorrect.try_approve_is_some, receive in sender_amount_zero.\n    - destruct_match eqn:receive; try discriminate.\n      split.\n      + now erewrite EIP20TokenCorrect.try_approve_is_some, receive.\n      + now rewrite Bool.negb_false_iff in finalized_check.\n    - intros (sender_amount_zero & finalized).\n      now rewrite finalized in finalized_check.\n    - discriminate.\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    /\\ (ctx_from ctx) <> (batFundDeposit 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      try now destruct_address_eq.\n    - rename H5 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      now destruct_address_eq.\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      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_batfund.\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  (** ** EIP20 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.\n    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  (** ** Init validation *)\n  Lemma deployed_implies_constants_valid bstate caddr :\n    reachable bstate ->\n    env_contracts bstate caddr = Some (contract : WeakContract) ->\n    exists cstate,\n      contract_state bstate caddr = Some cstate\n      /\\ (cstate.(fundingStart) < cstate.(fundingEnd))%nat\n      /\\ cstate.(tokenCreationMin) <= cstate.(tokenCreationCap)\n      /\\ cstate.(initSupply) <= cstate.(tokenCreationCap)\n      /\\ cstate.(tokenExchangeRate) <> 0\n      /\\ cstate.(tokenExchangeRate) <= cstate.(tokenCreationCap) - cstate.(tokenCreationMin)\n      /\\ cstate.(batFundDeposit) <> caddr\n      /\\ cstate.(fundDeposit) <> caddr.\n  Proof.\n    contract_induction; intros; auto.\n    - contract_simpl. cbn.\n      propify.\n      now destruct_address_eq.\n    - destruct_message;\n      now contract_simpl.\n    - destruct_message;\n      now contract_simpl.\n    - solve_facts.\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      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);\n      intros *; clear trace bstate caddr.\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 (BATFixed.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 (BATFixed.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      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' |- _=> 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 BATFixed.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        * easy.\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 (BATFixed.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      /\\ ((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      /\\ ~ In (batFundDeposit deployed_cstate) accounts)\n        ->\n        exists bstate, reachable_through deployed_bstate bstate\n          /\\ emptyable (chain_state_queue bstate)\n          /\\ exists cstate,\n          env_contracts bstate caddr = Some (BATFixed.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      funding_period_started & funding_period_not_over &\n      fund_deposit_not_contract & bat_fund_not_in_accounts);\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. inversion serialize_prev_state. subst.\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' |- _=> 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 finalized\n              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        apply not_in_cons in bat_fund_not_in_accounts as [bat_fund_not_in_accounts bat_fund_not_in_accounts'].\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          specialize deployed_implies_constants_valid as\n              (cstate' & contract_state' & _ & _ & _ & echange_rate_nonzero & can_hit_fund_min); eauto.\n          cbn in contract_state'.\n          rewrite contract_state in contract_state'.\n          setoid_rewrite deserialize_serialize in contract_state'.\n          inversion contract_state'. subst cstate'.\n          clear contract_state'.\n\n          (* Now we know that the action is valid we need to evaluate it *)\n          evaluate_action BATFixed.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_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_sender in receive_some; destruct_throw_if match_sender.\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_sender in receive_some; destruct_throw_if match_sender.\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          --- (* Prove contradiction between match_sender, bat_fund_not_in_accounts *)\n              now destruct_address_eq.\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 can_hit_fund_min;\n              only 11: (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                    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    setup.(_batFund) <= setup.(_tokenCreationCap) ->\n    ~ In setup.(_batFundDeposit) accounts ->\n    setup.(_batFundDeposit) <> caddr ->\n    setup.(_fundDeposit) <> caddr ->\n    exists bstate',\n      reachable_through bstate bstate'\n      /\\ emptyable (chain_state_queue bstate')\n      /\\ exists cstate,\n      env_contracts bstate' caddr = Some (BATFixed.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          init_supply_le_cap\n          batfund_not_in_accounts\n          batfund_not_caddr\n          ethfund_not_caddr.\n\n    add_block [(deploy_act setup BATFixed.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 BATFixed.contract; eauto; try lia;\n      try now apply account_balance_nonnegative.\n    { (* Prove that init returns some *)\n      cbn.\n      destruct_match eqn:requirements; eauto.\n      destruct_throw_if requirements.\n      repeat apply Bool.orb_prop in requirements as [requirements | requirements].\n      - now apply Nat.leb_le in requirements.\n      - now apply Nat.ltb_lt in requirements.\n      - now apply N.ltb_lt in requirements.\n      - now apply N.ltb_lt in requirements.\n      - now apply N.eqb_eq in requirements.\n      - now apply N.ltb_lt in requirements.\n      - now destruct_address_eq.\n      - now destruct_address_eq.\n    }\n    specialize constants_are_constant as\n      (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  (** ** BAToken outgoing acts facts *)\n\n  (** BAToken never calls itself *)\n  Lemma bat_no_self_calls 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 to _ => (to =? caddr)%address = false\n      | _ => False\n      end) (outgoing_acts bstate caddr).\n  Proof.\n    contract_induction; intros; auto.\n    - now inversion IH.\n    - apply Forall_app; split; auto.\n      clear IH.\n      instantiate (CallFacts := fun _ ctx state _ _ => fundDeposit state <> ctx_contract_address ctx).\n      destruct_message;\n        try now erewrite eip20_new_acts_correct by eauto.\n      + now contract_simpl.\n      + contract_simpl.\n        constructor; auto.\n        now destruct_address_eq.\n      + contract_simpl.\n        constructor; auto.\n        now destruct_address_eq.\n    - inversion_clear IH as [|? ? head_not_me tail_not_me].\n      apply Forall_app; split; auto.\n      clear tail_not_me.\n      destruct head; try contradiction.\n      destruct action_facts as [? _].\n      now destruct_address_eq.\n    - now rewrite <- perm.\n    - solve_facts.\n      apply deployed_implies_constants_valid in deployed0; auto.\n      now destruct_hyps.\n      now constructor.\n  Qed.\n\n  Lemma bat_no_self_calls' : forall bstate origin from_addr to_addr amount msg acts,\n    reachable bstate ->\n    env_contracts bstate to_addr = Some (contract : WeakContract) ->\n    chain_state_queue bstate = {|\n      act_origin := origin;\n      act_from := from_addr;\n      act_body :=\n        match msg with\n        | Some msg => act_call to_addr amount msg\n        | None => act_transfer to_addr amount\n        end\n    |} :: acts ->\n    from_addr <> to_addr.\n  Proof.\n    intros * reach deployed queue.\n    apply bat_no_self_calls in deployed as no_self_calls; auto.\n    unfold outgoing_acts in no_self_calls.\n    rewrite queue in no_self_calls.\n    cbn in no_self_calls.\n    destruct_address_eq; auto.\n    inversion_clear no_self_calls as [|? ? hd _].\n    destruct msg.\n    * congruence.\n    * now rewrite address_eq_refl in hd.\n  Qed.\n\n  (** BAToken only produces transfer acts *)\n  Lemma outgoing_acts_are_transfers : forall 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 _ _ => True\n      | _ => False\n      end) (outgoing_acts bstate caddr).\n  Proof.\n    intros * reach deployed.\n    apply (lift_outgoing_acts_prop contract); auto.\n    intros * receive_some.\n    destruct_message;\n      (* m = EIP msg *)\n      try now erewrite eip20_new_acts_correct.\n    - (* m = create_tokens *)\n      now erewrite try_create_tokens_acts_correct.\n    - (* m = finalize *)\n      now erewrite try_finalize_acts_correct.\n    - (* m = refund *)\n      now erewrite try_refund_acts_correct.\n  Qed.\n\n  (** BAToken only produces transfer acts *)\n  Lemma outgoing_acts_positive_amount : forall bstate caddr,\n    reachable bstate ->\n    env_contracts bstate caddr = Some (contract : WeakContract) ->\n    Forall (fun act_body => 0 <= act_body_amount act_body)%Z (outgoing_acts bstate caddr).\n  Proof.\n    contract_induction; intros; auto.\n    - now inversion IH.\n    - instantiate (CallFacts := fun _ ctx _ _ _ =>\n        (0 <= (ctx_contract_balance ctx))%Z /\\\n        ctx_from ctx <> ctx_contract_address ctx).\n      destruct facts as (contract_balance_positive & _).\n      destruct_message;\n        (* m = EIP msg *)\n        try now (apply eip20_new_acts_correct in receive_some; subst).\n      + (* m = create_tokens *)\n        apply try_create_tokens_acts_correct in receive_some.\n        now subst.\n      + (* m = finalize *)\n        apply try_finalize_acts_correct in receive_some.\n        subst.\n        now constructor.\n      + (* m = refund *)\n        apply try_refund_acts_correct in receive_some.\n        subst.\n        constructor; auto.\n        apply N2Z.is_nonneg.\n    - now destruct facts.\n    - eapply forall_respects_permutation; eauto.\n    - solve_facts.\n      split.\n      + (* Prove call fact: 0 <= ctx_contract_balance ctx *)\n        destruct_address_eq; subst; try easy.\n        * lia.\n        * apply Z.add_nonneg_nonneg; try lia.\n          now apply Z.ge_le, account_balance_nonnegative.\n      + (* Prove call fact: ctx_from ctx <> ctx_contract_address ctx *)\n        eapply bat_no_self_calls'; eauto.\n        now constructor.\n  Qed.\n\n\n\n  (** ** batFundDeposit cannot refund *)\n\n  (** batFundDeposit starts with initSupply tokens and should not be allowed\n      to refund them. Therefore, if the token is not finalized then the\n      token balance of batFundDeposit should be equal to initSupply *)\n  Lemma no_init_supply_refund : 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      /\\ (isFinalized cstate = false ->\n          FMap.find cstate.(batFundDeposit) (balances cstate) = Some cstate.(initSupply)).\n  Proof.\n    intros *.\n    apply (lift_contract_state_prop contract);\n      intros *; clear bstate caddr.\n    - intros init_some not_finalized.\n      contract_simpl. cbn.\n      apply FMap.find_add.\n    - intros IH receive_some not_finalized.\n      unfold Blockchain.receive in receive_some.\n      cbn in receive_some.\n      destruct msg. destruct m.\n      + apply eip_only_changes_token_state in receive_some as finalized_unchanged.\n        rewrite <- finalized_unchanged in not_finalized.\n        contract_simpl.\n        rename H into finalized.\n        now setoid_rewrite not_finalized in finalized.\n      + eapply try_create_tokens_preserves_other_balances in receive_some as balance_preserved.\n        apply try_create_tokens_only_change_token_state in receive_some as finalized_unchanged.\n        rewrite <- finalized_unchanged in *. cbn.\n        now rewrite <- balance_preserved.\n        specialize try_create_tokens_is_some as (_ & (_ & _ & _ & _ & _ & from_not_batfund)); eauto.\n      + now apply try_finalize_isFinalized_correct in receive_some.\n      + eapply try_refund_preserves_other_balances in receive_some as balance_preserved.\n        apply try_refund_only_change_token_state in receive_some as finalized_unchanged.\n        rewrite <- finalized_unchanged in *. cbn.\n        now rewrite <- balance_preserved.\n        specialize try_refund_is_some as (_ & (_ & _ & _ & _ & from_not_batfund & _)); eauto.\n      + now contract_simpl.\n  Qed.\n\n\n\n  (** ** Total balance lower bound *)\n\n  (** The total supply should never go under the initial supply since\n      batFundDeposit is not allowed to refund the initial supply *)\n  Lemma total_supply_lower_bound : 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      /\\ initSupply cstate <= total_supply cstate.\n  Proof.\n    contract_induction; intros; auto.\n    - cbn in init_some.\n      now contract_simpl.\n    - instantiate (CallFacts := fun _ ctx state _ _ =>\n        total_supply state = sum_balances state /\\\n        (isFinalized state = false -> FMap.find state.(batFundDeposit) (balances state) = Some state.(initSupply)) /\\\n        ctx_from ctx <> ctx_contract_address ctx).\n      destruct facts as (sum_balances_eq_total_supply & no_init_supply_refund & _).\n      destruct_message;\n        try apply eip_only_changes_token_state in receive_some as init_supply_unchanged.\n      + apply try_transfer_preserves_total_supply in receive_some as supply_unchanged.\n        now rewrite <- supply_unchanged, <- init_supply_unchanged.\n      + apply try_transfer_from_preserves_total_supply in receive_some as supply_unchanged.\n        now rewrite <- supply_unchanged, <- init_supply_unchanged.\n      + apply try_approve_preserves_total_supply in receive_some as supply_unchanged.\n        now rewrite <- supply_unchanged, <- init_supply_unchanged.\n      + contract_simpl.\n        cbn.\n        rewrite N.add_comm.\n        now apply N_add_le.\n      + now contract_simpl.\n      + specialize try_refund_is_some as (_ & (_ & not_finalized & _ & _ & from_not_batfund & _)); eauto.\n        apply receive_preserves_constants in receive_some as constants_unchanged.\n        destruct constants_unchanged as (_ & _ & _ & _ & _ & _ & _ & init_supply_unchanged).\n        erewrite <- try_refund_total_supply_correct, <- init_supply_unchanged; eauto.\n        rewrite sum_balances_eq_total_supply in *.\n        apply N.le_trans with (m := with_default 0 (FMap.find prev_state.(batFundDeposit) (balances prev_state))).\n        * now rewrite no_init_supply_refund.\n        * now apply balance_le_sum_balances_ne.\n    - now destruct facts.\n    - solve_facts.\n      destruct_and_split.\n      + now apply sum_balances_eq_total_supply in deployed0 as\n          (cstate' & deployed_state' & ?).\n      + apply no_init_supply_refund in deployed0 as\n          (cstate' & deployed_cstate' & ?); auto.\n        rewrite deployed_cstate' in deployed_state0.\n        inversion deployed_state0.\n        now subst cstate'.\n        now constructor.\n      + eapply bat_no_self_calls'; eauto.\n        now constructor.\n  Qed.\n\n\n\n  (** ** No outgoing acts produces while funding *)\n\n  Lemma funding_period_no_acts : 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      /\\ (isFinalized cstate = false /\\\n          ((current_slot bstate <= fundingEnd cstate)%nat \\/ tokenCreationMin cstate <= total_supply cstate) ->\n          outgoing_acts bstate caddr = []).\n  Proof.\n    contract_induction; intros; auto; try rename H into not_finalized.\n    - now specialize (IH not_finalized).\n    - destruct_message;\n        try (\n          apply eip_only_changes_token_state in receive_some as finalized_unchanged;\n          apply eip20_new_acts_correct in receive_some as no_new_acts).\n      + apply try_transfer_preserves_total_supply in receive_some as supply_unchanged.\n        rewrite <- supply_unchanged, <- finalized_unchanged in not_finalized.\n        now rewrite IH, no_new_acts.\n      + apply try_transfer_from_preserves_total_supply in receive_some as supply_unchanged.\n        rewrite <- supply_unchanged, <- finalized_unchanged in not_finalized.\n        now rewrite IH, no_new_acts.\n      + apply try_approve_preserves_total_supply in receive_some as supply_unchanged.\n        rewrite <- supply_unchanged, <- finalized_unchanged in not_finalized.\n        now rewrite IH, no_new_acts.\n      + apply try_create_tokens_only_change_token_state in receive_some as finalized_unchanged.\n        apply try_create_tokens_acts_correct in receive_some as no_new_acts.\n        specialize try_create_tokens_is_some as (_ & (_ & _ & _ & funding_active & _)); eauto.\n        rewrite <- finalized_unchanged in not_finalized.\n        destruct not_finalized as [not_finalized _].\n        rewrite no_new_acts, IH; auto.\n      + apply try_finalize_isFinalized_correct in receive_some as finalized.\n        now destruct not_finalized as [not_finalized _].\n      + apply try_refund_only_change_token_state in receive_some as finalized_unchanged.\n        apply try_refund_total_supply_correct in receive_some as new_supply.\n        specialize try_refund_is_some as\n          (_ & (_ & _ & funding_over%Nat.lt_nge & goal_not_hit & _)); eauto.\n        destruct not_finalized as [_ [funding_not_over | goal_hit]].\n        * now rewrite <- finalized_unchanged in funding_not_over.\n        * rewrite <- new_supply, <- finalized_unchanged in goal_hit.\n          now cbn in goal_hit.\n    - now instantiate (CallFacts := fun _ ctx _ _ _ => ctx_from ctx <> ctx_contract_address ctx).\n    - apply IH in not_finalized. subst.\n      now apply Permutation.Permutation_nil in perm.\n    - solve_facts.\n      eapply bat_no_self_calls'; eauto.\n      now constructor.\n  Qed.\n\n\n\n  (** ** Token balances divisible by exchange rate *)\n\n  Lemma token_balances_divisible : 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      /\\ (forall addr, addr <> batFundDeposit cstate ->\n          isFinalized cstate = false ->\n          with_default 0 (FMap.find addr (balances cstate)) mod tokenExchangeRate cstate = 0).\n  Proof.\n    contract_induction; intros; auto;\n      try rename H into addr_not_batfund;\n      try rename H0 into not_finalized.\n    - cbn in init_some.\n      destruct_match in init_some; try congruence.\n      inversion init_some. subst. cbn in *.\n      setoid_rewrite FMap.find_add_ne; auto.\n    - instantiate (CallFacts := fun _ ctx state _ _ =>\n        tokenExchangeRate state <> 0 /\\\n        ctx_from ctx <> ctx_contract_address ctx).\n      destruct facts as (exchange_rate_nonzero & _).\n      unfold Blockchain.receive in receive_some.\n      cbn in receive_some.\n      destruct msg. destruct m.\n      + apply eip_only_changes_token_state in receive_some as finalize_unchanged.\n        rewrite <- finalize_unchanged in not_finalized.\n        contract_simpl.\n        rename H into finalized.\n        now setoid_rewrite not_finalized in finalized.\n      + eapply try_create_tokens_only_change_token_state in receive_some as finalized_unchanged.\n        rewrite <- finalized_unchanged in *. cbn.\n        destruct (address_eqb addr (ctx_from ctx)) eqn:addr_from; destruct_address_eq; try easy.\n        * contract_simpl.\n          rewrite <- H. cbn.\n          setoid_rewrite EIP20TokenCorrect.add_is_partial_alter_plus; auto.\n          subst. clear addr_from.\n          setoid_rewrite FMap.find_add. cbn.\n          now rewrite N.add_mod, IH, N.add_mod_idemp_r, N.mod_add by assumption.\n        * erewrite <- try_create_tokens_preserves_other_balances; eauto.\n      + now apply try_finalize_isFinalized_correct in receive_some.\n      + eapply try_refund_only_change_token_state in receive_some as finalized_unchanged.\n        rewrite <- finalized_unchanged in *. cbn.\n        destruct (address_eqb addr (ctx_from ctx)) eqn:addr_from; destruct_address_eq; try easy.\n        * subst. clear addr_from.\n          erewrite try_refund_balance_correct; eauto.\n        * erewrite <- try_refund_preserves_other_balances; eauto.\n      + now contract_simpl.\n    - now destruct facts.\n    - solve_facts.\n      split.\n      * specialize deployed_implies_constants_valid as\n          (cstate' & deployed_state' & _ & _ & _ & exchange_rate_nonzero & _); eauto.\n        now constructor.\n        easy.\n      * eapply bat_no_self_calls'; eauto.\n        now constructor.\n  Qed.\n\n\n\n  (** ** Contract balance bound *)\n\n  Lemma contract_balance_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 deploy_info,\n      contract_state bstate caddr = Some cstate\n      /\\ deployment_info Setup trace caddr = Some deploy_info\n      /\\ (isFinalized cstate = true -> effective_balance = 0)%Z\n      /\\ (isFinalized cstate = false ->\n        (effective_balance - deploy_info.(deployment_amount)) * (Z.of_N cstate.(tokenExchangeRate)) =\n        (Z.of_N ((total_supply cstate) - cstate.(initSupply))))%Z.\n  Proof.\n    intros *.\n    unfold effective_balance.\n    contract_induction; intros; auto; try destruct IH as [IH_finalized IH_funding].\n    - cbn in *.\n      destruct_match in init_some; try congruence.\n      inversion init_some. cbn.\n      split; intros.\n      + discriminate.\n      + lia.\n    - cbn in *.\n      split; intros.\n      + now rewrite <- IH_finalized by assumption.\n      + now rewrite <- IH_funding by assumption.\n    - instantiate (CallFacts := fun chain ctx state out_acts _ =>\n        (0 <= ctx_amount ctx)%Z /\\\n        initSupply state <= total_supply state /\\\n        tokenExchangeRate state <> 0 /\\\n        (isFinalized state = false -> ctx_from ctx <> batFundDeposit state ->\n          N.modulo (with_default 0 (FMap.find ctx.(ctx_from) (balances state))) state.(tokenExchangeRate) = 0) /\\\n        (isFinalized state = false -> ctx_from ctx <> batFundDeposit state ->\n          (with_default 0 (FMap.find ctx.(ctx_from) (balances state))) <= total_supply state - initSupply state) /\\\n        (isFinalized state = false /\\\n                      ((current_slot chain <= fundingEnd state)%nat \\/\n                      tokenCreationMin state <= total_supply state) -> out_acts = []) /\\\n        ctx_from ctx <> ctx_contract_address ctx).\n      destruct facts as (ctx_amount_positive &\n                        supply_bound &\n                        exchange_rate_nonzero &\n                        tokens_modulo_exchange_rate &\n                        tokens_bound &\n                        funding_no_outgoing_acts &\n                        _).\n      clear CallFacts AddBlockFacts DeployFacts.\n      destruct msg. destruct m.\n      + apply eip_only_changes_token_state in receive_some as finalized_unchanged.\n        apply eip20_new_acts_correct in receive_some as no_new_acts.\n        apply eip20_not_payable in receive_some as not_payable.\n        apply Z.le_antisymm in ctx_amount_positive; auto.\n        rewrite ctx_amount_positive, Z.sub_0_r in IH_finalized, IH_funding.\n        destruct m.\n        * apply try_transfer_preserves_total_supply in receive_some as supply_unchanged.\n          now rewrite no_new_acts, <- supply_unchanged, <- finalized_unchanged.\n        * apply try_transfer_from_preserves_total_supply in receive_some as supply_unchanged.\n          now rewrite no_new_acts, <- supply_unchanged, <- finalized_unchanged.\n        * apply try_approve_preserves_total_supply in receive_some as supply_unchanged.\n          now rewrite no_new_acts, <- supply_unchanged, <- finalized_unchanged.\n      + apply try_create_tokens_amount_correct in receive_some as payable.\n        contract_simpl.\n        subst. cbn in *.\n        rename H0 into requirements_check.\n        propify.\n        destruct requirements_check as (((not_finalized & _) & _) & _).\n        split; intros finalized_state.\n        * congruence.\n        * apply IH_funding in finalized_state.\n          rewrite N.add_sub_swap, N2Z.inj_add by assumption.\n          lia.\n      + contract_simpl.\n        subst. cbn in *.\n        rename H into not_payable.\n        rewrite Z.gtb_ltb, Z.ltb_ge in not_payable.\n        apply Z.le_antisymm in ctx_amount_positive; auto.\n        rewrite ctx_amount_positive, Z.sub_0_r in IH_finalized, IH_funding.\n        split; intros finalized_state.\n        * rewrite Z.sub_add_distr, Z.sub_diag, Z.sub_0_l, <- Z.opp_0, Z.opp_inj_wd.\n          rename H0 into requirements_check.\n          rewrite !Bool.orb_false_iff in requirements_check.\n          destruct requirements_check as ((not_finalized & _) & funding_hit%N.ltb_ge).\n          now rewrite funding_no_outgoing_acts.\n        * congruence.\n      + contract_simpl.\n        subst. cbn in *.\n        rename H into not_payable.\n        rewrite Z.gtb_ltb, Z.ltb_ge in not_payable.\n        apply Z.le_antisymm in ctx_amount_positive; auto.\n        rewrite ctx_amount_positive, Z.sub_0_r in IH_finalized, IH_funding.\n        rename H0 into requirements_check.\n        rename H1 into from_ne_batfund.\n        rename H2 into from_balance.\n        rewrite !Bool.orb_false_iff in requirements_check.\n        destruct requirements_check as ((finalized_sate & _) & _).\n        split; intros finalized_state.\n        * congruence.\n        * apply IH_funding in finalized_state.\n          update (ctx_from ctx <> batFundDeposit prev_state) in from_ne_batfund by now destruct_address_eq.\n          rewrite <- Z.sub_add_distr, (Z.add_comm _ (sumZ _ _)), Z.add_comm,\n                  !Z.sub_add_distr, Z.mul_sub_distr_r, <- N2Z.inj_mul.\n          result_to_option.\n          rewrite <- from_balance in *.\n          apply tokens_bound in from_ne_batfund as tokens_bound'; auto.\n          apply tokens_modulo_exchange_rate in from_ne_batfund as tokens_modulo_exchange_rate'; auto.\n          rewrite <- N.div_exact, N.mul_comm, from_balance in tokens_modulo_exchange_rate' by auto.\n          setoid_rewrite <- tokens_modulo_exchange_rate'.\n          rewrite from_balance in *.\n          cbn in *.\n          lia.\n      + now contract_simpl.\n    - now destruct facts as (_ & _ & _ & _ & _ & no_self_calls).\n    - now erewrite sumZ_permutation in IH_finalized, IH_funding by eauto.\n    - solve_facts.\n      destruct_and_split.\n      + now apply Z.ge_le.\n      + now apply total_supply_lower_bound in deployed0 as\n          (cstate' & deployed_state' & ?).\n      + now apply deployed_implies_constants_valid in deployed0 as\n        (cstate' & deployed_state' & _ & _ & _ & exchange_rate_nonzero & _).\n      + intros not_finalized from_not_batfund.\n        specialize token_balances_divisible as (cstate' & deployed_cstate' & ?); eauto.\n        now constructor.\n        rewrite deployed_state0 in deployed_cstate'.\n        inversion deployed_cstate'.\n        now subst cstate'.\n      + intros not_finalized from_not_batfund.\n        specialize no_init_supply_refund as (cstate' & deployed_cstate' & batfund_balance); eauto.\n        now constructor.\n        rewrite deployed_state0 in deployed_cstate'.\n        inversion deployed_cstate'.\n        subst cstate'. clear deployed_cstate'.\n        specialize sum_balances_eq_total_supply as (cstate' & deployed_cstate' & sum_eq_total); eauto.\n        now constructor.\n        rewrite deployed_state0 in deployed_cstate'.\n        inversion deployed_cstate'.\n        subst cstate'. clear deployed_cstate'.\n        replace (initSupply cstate) with (with_default 0 (FMap.find (batFundDeposit cstate) (balances cstate))) by\n          now rewrite batfund_balance.\n        rewrite sum_eq_total.\n        now apply balance_le_sum_balances_ne.\n      + intros.\n        specialize funding_period_no_acts as (cstate' & deployed_state' & no_acts); eauto.\n        now constructor.\n        now apply no_acts.\n      + eapply bat_no_self_calls'; eauto.\n        now constructor.\n  Qed.\n\n\n\n  (** ** outgoing acts are valid *)\n\n  (** Prove that all outgoing acts produced by the contract can be evaluated *)\n  Lemma outgoing_acts_evaluable : forall bstate caddr,\n    reachable bstate ->\n    env_contracts bstate caddr = Some (contract : WeakContract) ->\n    Forall (fun act_body => receiver_can_receive_transfer bstate act_body) (outgoing_acts bstate caddr) ->\n    Forall (fun act_body => forall origin, exists bstate_new, inhabited (ActionEvaluation bstate (build_act origin caddr act_body) bstate_new [])) (outgoing_acts bstate caddr).\n  Proof.\n    intros * reach deployed can_receive_funds.\n    assert (trace := reach).\n    destruct trace as [trace].\n    specialize contract_balance_bound as\n      (cstate & dep_info & deployed_state & deployed_info &\n      contract_balance_bound_finalized & contract_balance_bound); eauto.\n    apply deployment_amount_nonnegative in deployed_info as dep_amount_nonnegative.\n    specialize deployed_implies_constants_valid as\n      (cstate' & deployed_state' & _ & _ & _ & exchange_rate_nonzero & _); eauto.\n    rewrite deployed_state in deployed_state'.\n    inversion deployed_state'.\n    subst cstate'. clear deployed_state'.\n    eapply outgoing_acts_are_transfers in reach as acts_are_transfers; eauto.\n    eapply outgoing_acts_positive_amount in reach as acts_amount_positive; eauto.\n    apply Forall_forall.\n    intros act HIn.\n    eapply Forall_forall in acts_are_transfers; eauto.\n    eapply Forall_forall in acts_amount_positive as act_amount_positive; eauto.\n    eapply Forall_forall in can_receive_funds; eauto.\n    destruct act; try now exfalso.\n    clear acts_are_transfers.\n    assert (enough_balance : (act_body_amount (act_transfer to amount) <= env_account_balances bstate caddr)%Z).\n    { destruct (isFinalized cstate).\n      - apply Zminus_eq in contract_balance_bound_finalized; auto.\n        rewrite contract_balance_bound_finalized.\n        apply sumZ_in_le; eauto.\n        now apply Forall_forall.\n      - apply Z_div_mult in contract_balance_bound; auto; try lia.\n        eapply Z.add_cancel_r in contract_balance_bound.\n        rewrite Z.sub_add, <- N2Z.inj_div in contract_balance_bound.\n        assert (H : (forall n m p, 0 <= p -> n - m = p -> m <= n)%Z).\n        { intros. subst p. now apply Z.le_0_sub. }\n        apply H in contract_balance_bound.\n        -- eapply Z.le_trans; try apply contract_balance_bound.\n          apply sumZ_in_le; eauto.\n          now apply Forall_forall.\n        -- apply Z.add_nonneg_nonneg; auto.\n          apply N2Z.is_nonneg.\n    }\n    intros origin.\n    destruct can_receive_funds as [receive_not_contract | (wc & cstate' & deployed' & deployed_state' & new_state & receive_some )].\n    - eexists.\n      constructor.\n      eapply eval_transfer; auto.\n      + now apply Z.le_ge.\n      + now replace amount with (act_body_amount (act_transfer to amount)); auto.\n      + assumption.\n      + now constructor.\n    - eexists.\n      constructor.\n      eapply eval_call with (msg := None); eauto; cycle -1.\n      + now constructor.\n      + apply Z.le_ge.\n        apply act_amount_positive.\n      + cbn.\n        replace (env_account_balances (set_contract_state to new_state (transfer_balance caddr to amount bstate)) to)\n          with (((env_account_balances bstate to) + amount)%Z).\n        * apply receive_some.\n        * apply bat_no_self_calls in deployed; auto.\n          eapply Forall_forall in deployed; eauto.\n          cbn in *.\n          destruct_address_eq; easy.\n      + eauto.\n    Unshelve. auto.\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/BATFixedCorrect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2766966039170211}}
{"text": "Require Import Coq.Lists.List\n        Coq.Strings.String\n        Coq.Arith.Arith\n        Coq.omega.Omega\n        Fiat.Common.ilist2\n        Fiat.Common.StringBound\n        Fiat.ADT\n        Fiat.ADT.ComputationalADT\n        Fiat.ADTNotation\n        Fiat.ADTRefinement\n        Fiat.ADTRefinement.BuildADTRefinements\n        Fiat.QueryStructure.Specification.Representation.Notations\n        Fiat.QueryStructure.Specification.Representation.Heading2\n        Fiat.QueryStructure.Specification.Representation.Tuple2.\n\n(* Computational ADT definitions for Tuples. *)\nSection TupleADT2.\n\n  Open Scope string_scope.\n  Open Scope methSig_scope.\n  Open Scope consSig_scope.\n  Open Scope cMethDefParsing_scope.\n  Open Scope cConsDef_scope.\n\n  Variable heading : Heading2.   (* The heading of the tuple. *)\n\n  (* Tuple2 Initialization *)\n  Definition Tuple2_Init := \"Init\".\n\n  Definition InitTuple2Dom := @Tuple2 heading.\n\n  Definition InitTuple2Sig : consSig :=\n      Constructor Tuple2_Init : InitTuple2Dom -> rep.\n\n  Definition InitTuple2 : InitTuple2Dom -> Tuple2 := id.\n\n  Definition InitTuple2Def :=\n    let _ := {| rep := Tuple2 |} in\n    Def Constructor1 Tuple2_Init (inits : InitTuple2Dom) : rep :=\n      InitTuple2 inits.\n\n  (* Getters and Setters for Tuple2s *)\n\n  Definition GetTuple2Sig id aType :=\n    Method (\"Get\" ++ id) : rep -> rep * aType.\n\n  Definition SetTuple2Sig id aType :=\n    Method (\"Set\" ++ id) : rep * aType -> rep.\n\n  Definition Tuple2Sigs'\n             {n'}\n             (HeadingTypes : Vector.t Type n')\n             (HeadingNames : Vector.t string n')\n    : Vector.t methSig (n' * 2) :=\n    Vector.rect2\n      (fun (n : nat) (_ : Vector.t Type n) (_ : Vector.t string n) =>\n         Vector.t methSig (n * 2)) (Vector.nil methSig)\n      (fun (n : nat) (_ : Vector.t Type n) (_ : Vector.t string n)\n           (Tuple2Sigs' : Vector.t methSig (n * 2)) (aType : Type)\n           (id : string) =>\n         Vector.cons methSig (GetTuple2Sig id aType) (S (n * 2))\n                     (Vector.cons methSig (SetTuple2Sig id aType) (n * 2) Tuple2Sigs'))\n      HeadingTypes HeadingNames.\n\n  Definition Tuple2Sigs :=\n    Tuple2Sigs' (AttrList2 heading)\n               (HeadingNames2 heading).\n\n  Definition GetTuple2Def\n             (attr : Fin.t (NumAttr2 heading)) :\n    cMethDef (Rep := @Tuple2 heading) (GetTuple2Sig (Vector.nth (HeadingNames2 heading) attr)\n                                                  (Vector.nth (AttrList2 heading) attr)) :=\n    Def Method0 _ (msg : @Tuple2 heading)\n    : rep * (Vector.nth (AttrList2 heading) attr) :=\n      (msg, ith2 msg attr).\n\n  Definition SetTuple2Def\n             (attr : Fin.t (NumAttr2 heading)) :\n    cMethDef (Rep := @Tuple2 heading) (SetTuple2Sig (Vector.nth (HeadingNames2 heading) attr)\n                                                  (Vector.nth (AttrList2 heading) attr)) :=\n    Def Method1 _ (msg : @Tuple2 heading) (val : Vector.nth (AttrList2 heading) attr) : rep :=\n      replace_Index2 _ msg attr val.\n\n  Definition Tuple2Defs'\n           {n'}\n           (HeadingTypes : Vector.t Type n')\n           (HeadingNames2 : Vector.t string n')\n    : (forall (attr : Fin.t n'),\n          cMethDef (Rep := @Tuple2 heading) (GetTuple2Sig (Vector.nth HeadingNames2 attr)\n                                                        (Vector.nth HeadingTypes attr)))\n      -> (forall (attr : Fin.t n'),\n             cMethDef (Rep := @Tuple2 heading) (SetTuple2Sig (Vector.nth HeadingNames2 attr)\n                                                           (Vector.nth HeadingTypes attr)))\n      -> ilist (B := cMethDef (Rep := @Tuple2 heading))\n            (Tuple2Sigs' HeadingTypes HeadingNames2) :=\n    Vector.rect2\n      (fun n HeadingTypes HeadingNames2 =>\n         (forall (attr : Fin.t n),\n             cMethDef (Rep := @Tuple2 heading) (GetTuple2Sig (Vector.nth HeadingNames2 attr)\n                                                           (Vector.nth HeadingTypes attr)))\n         -> (forall (attr : Fin.t n),\n                cMethDef (Rep := @Tuple2 heading) (SetTuple2Sig (Vector.nth HeadingNames2 attr)\n                                                              (Vector.nth HeadingTypes attr)))\n         -> ilist (n := n * 2) (B := cMethDef (Rep := @Tuple2 heading))\n                  (Tuple2Sigs' HeadingTypes HeadingNames2)) (fun _ _ => ())\n      (fun n HeadingTypes HeadingNames2\n           Tuple2Defs' aType id\n           GetTuple2Def' SetTuple2Def' =>\n         icons (GetTuple2Def' Fin.F1)\n               (icons (SetTuple2Def' Fin.F1)\n                      (Tuple2Defs' (fun n => GetTuple2Def' (Fin.FS n))\n                                  (fun n => SetTuple2Def' (Fin.FS n)))))\n      HeadingTypes HeadingNames2.\n\n    Definition Tuple2Defs :=\n      Tuple2Defs' (AttrList2 heading) (HeadingNames2 heading)\n                 GetTuple2Def SetTuple2Def.\n\n    (* Tuple2 ADT Definitions *)\n    Definition Tuple2ADTSig : ADTSig :=\n      BuildADTSig (Vector.cons _ InitTuple2Sig _ (Vector.nil _))\n                  Tuple2Sigs.\n\n    (*Definition Tuple2ADT : cADT Tuple2ADTSig :=\n      BuildcADT (icons InitTuple2Def inil) Tuple2Defs. *)\n\n    (* Support for building messages. *)\n\n\n    (*Definition ConstructTuple2 subtopics :=\n      CallConstructor Tuple2ADT Tuple2_Init subtopics. *)\n\n    (* Support for calling message getters. *)\n    Lemma BuildGetTuple2MethodID_ibound'\n          {n'}\n          (HeadingTypes : Vector.t Type n')\n          (HeadingNames2 : Vector.t string n')\n      : forall (idx : Fin.t n'),\n        Vector.nth (Vector.map methID (Tuple2Sigs' HeadingTypes HeadingNames2))\n                   (Fin.depair idx Fin.F1) =\n        (\"Get\" ++ Vector.nth HeadingNames2 idx)%string.\n    Proof.\n      pattern n', HeadingTypes, HeadingNames2.\n      eapply Vector.rect2.\n      - intro; inversion idx.\n      - intros; generalize dependent idx; intro; revert v1 v2 H.\n        pattern n, idx.\n        eapply Fin.rectS; simpl; intros; eauto.\n    Qed.\n\n    Definition BuildGetTuple2MethodID\n               (idx : Fin.t (NumAttr2 heading))\n    : BoundedString (Vector.map methID Tuple2Sigs) :=\n      {| bindex := (\"Get\" ++ (Vector.nth (HeadingNames2 heading) idx))%string;\n         indexb := {| ibound := Fin.depair idx (@Fin.F1 1);\n                      boundi := BuildGetTuple2MethodID_ibound' _ _ idx |}\n      |}.\n\n    (*Definition CallTuple2GetMethod\n               (r : Tuple2)\n               idx\n      := cMethods Tuple2ADT (ibound (indexb (BuildGetTuple2MethodID idx))) r. *)\n\n    (* Support for calling message setters. *)\n    Lemma BuildSetTuple2MethodID_ibound\n          {n'}\n          (HeadingTypes : Vector.t Type n')\n          (HeadingNames2 : Vector.t string n')\n      : forall (idx : Fin.t n'),\n        Vector.nth (Vector.map methID (Tuple2Sigs' HeadingTypes HeadingNames2))\n                   (Fin.depair idx (Fin.FS Fin.F1)) =\n        (\"Set\" ++ Vector.nth HeadingNames2 idx)%string.\n    Proof.\n      pattern n', HeadingTypes, HeadingNames2.\n      eapply Vector.rect2.\n      - intro; inversion idx.\n      - intros; generalize dependent idx; intro; revert v1 v2 H.\n        pattern n, idx.\n        eapply Fin.rectS; simpl; intros; eauto.\n    Qed.\n\n    Definition BuildSetTuple2MethodID\n               (idx : Fin.t (NumAttr2 heading))\n    : BoundedString (Vector.map methID Tuple2Sigs) :=\n      {| bindex := (\"Set\" ++ (Vector.nth (HeadingNames2 heading) idx))%string;\n         indexb := {| ibound := Fin.depair idx (Fin.FS Fin.F1);\n                      boundi := BuildSetTuple2MethodID_ibound _ _ idx |}\n      |}.\n\n    (*Definition CallTuple2SetMethod\n               (r : Tuple2)\n               idx\n      := cMethods Tuple2ADT (ibound (indexb (BuildSetTuple2MethodID idx))) r. *)\n\nEnd TupleADT2.\n\n(*Definition CallDecTuple2GetMethod\n           {n attrs}\n           (r : @DecTuple2 n attrs)\n           idx\n  := cMethods (Tuple2ADT _) (ibound (indexb (BuildGetTuple2MethodID _ idx))) r. *)\n\n(* Notation \"t ! R\" :=\n  (@CallDecTuple2GetMethod _ _ t%Tuple2 (ibound (indexb ((@Build_BoundedIndex _ _ _ R%string _)))) ())\n  : Tuple2_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/TupleADT2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2766966039170211}}
{"text": "Require Import MirrorCore.Reify.Reify.\nRequire Import MirrorCore.Lambda.Expr.\nRequire Import MirrorCore.ExprI.\nRequire Import MirrorCore.RTac.RTac.\nRequire Import MirrorCore.Subst.FMapSubst.\n\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.\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.\nRequire Import ExtLib.Tactics.\n\nRequire Import Coq.PArith.BinPos.\n\nSection Tactics.\n  Context {fs : Environment}.\n\nDefinition exprD_Prop (uvar_env var_env : 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 : 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  \nDefinition run_tac tac goal :=\n  runOnGoals tac nil nil 0 0 (CTop nil nil) \n    (ctx_empty (typ := typ) (expr := expr typ func)) goal.\n\nLemma run_rtac_More tac s goal e\n  (Hsound : rtac_sound tac) \n  (Hres : run_tac tac (GGoal e) = More_ s goal) :\n  goalD_Prop nil nil goal -> exprD_Prop nil nil e.\nProof.\n  intros He'.\n  apply runOnGoals_sound_ind with (g := GGoal e) (ctx := CTop nil nil) \n  \t(s0 := TopSubst (expr typ func) nil nil) in Hsound.\n  unfold rtac_spec in Hsound. simpl in Hsound.\n  unfold run_tac in Hres. simpl in Hres.\n  rewrite Hres in Hsound.\n  assert (WellFormed_Goal nil nil (GGoal (typ := typ) e)) as H1 by constructor.\n  assert (WellFormed_ctx_subst (TopSubst (expr typ func) nil (@nil typ))) as H2 by constructor.\n  specialize (Hsound H1 H2).\n  destruct Hsound as [Hwfs [Hwfg Hsound]].\n  unfold Ctx.propD, exprD'_typ0 in Hsound.\n  simpl in Hsound. unfold exprD_Prop, exprD; simpl.\n  forward; inv_all; subst.\n\n  destruct Hsound.\n  inversion Hwfs; subst.\n  simpl in H0; inv_all; subst.\n  unfold pctxD in H0; inv_all; subst.\n  apply H5.\n  unfold goalD_Prop in He'. simpl in He'. forward; inv_all; subst.\nQed.\n\nLemma run_rtac_Solved tac s e\n  (Hsound : rtac_sound tac) \n  (Hres : run_tac tac (GGoal e) = Solved s) :\n  exprD_Prop nil nil e.\nProof.\n  unfold run_tac in Hres.\n  unfold rtac_sound in Hsound.\n  assert (WellFormed_Goal nil nil (GGoal (typ := typ) e)) as H1 by constructor.\n  assert (WellFormed_ctx_subst (TopSubst (expr typ func) nil (@nil typ))) as H2 by constructor.\n  specialize (Hsound _ _ _ _ Hres H1 H2).\n  destruct Hsound as [Hwfs Hsound].\n  simpl in Hsound.\n  unfold Ctx.propD, exprD'_typ0 in Hsound.\n  unfold exprD_Prop.\n  \n  simpl in Hsound. unfold exprD. simpl. forward.\n  destruct Hsound. \n  SearchAbout pctxD.\n  inversion Hwfs; subst. simpl in H8. inv_all; subst.\n  admit.\nQed.\n\nEnd Tactics.\n\nLtac cbv_denote :=\n          cbv [\n          goalD_aux\n          \n\t\t  (* ExprD' *)\n          exprD' funcAs  typeof_sym typeof_expr type_cast type_cast_typ\n          exprD'_simul func_simul\n          ExprD.Expr_expr\n          ExprDsimul.ExprDenote.exprD'\n          (* RSym *)\n          \n          SymSum.RSym_sum Rcast Relim Rsym eq_sym symD(* RSym_env*)\n          Rcast_val eq_rect_r eq_rect Datatypes.id\n          \n          (* Monad *)\n          \n          Monad.bind Monad.ret\n          \n          OptionMonad.Monad_option\n          \n          (* HList *)\n          \n          HList.hlist_hd HList.hlist_tl\n          \n          (* TypesI *)\n          \n          TypesI.typD \n          typ2_match typ2 typ2_cast\n          typ0_match typ0 typ0_cast SubstTypeD_typ\n          (* ExprI *)\n          \n          MirrorCore.VariablesI.Var ExprVariables.ExprVar_expr\n          MirrorCore.VariablesI.UVar\n          MirrorCore.Lambda.ExprVariables.ExprUVar_expr\n          ExprI.exprT_Inj ExprI.exprT_UseV ExprI.exprT_UseU\n          exprT_App ExprI.exprT OpenT\n          nth_error_get_hlist_nth\n          \n          exprT_GetVAs exprT_GetUAs\n          \n          (* Denotation *)\n          \n          Charge.ModularFunc.Denotation.fun_to_typ\n          Charge.ModularFunc.Denotation.fun_to_typ2\n          Charge.ModularFunc.Denotation.fun_to_typ3\n          Charge.ModularFunc.Denotation.fun_to_typ4\n          \n          Charge.ModularFunc.Denotation.typ_to_fun\n          Charge.ModularFunc.Denotation.typ_to_fun2\n          Charge.ModularFunc.Denotation.typ_to_fun3\n\n          \n          (* ILogicFunc*)\n          \n          ILogicFunc.mkEntails ILogicFunc.mkTrue ILogicFunc.mkFalse \n          ILogicFunc.mkAnd ILogicFunc.mkOr ILogicFunc.mkImpl\n          ILogicFunc.mkExists ILogicFunc.mkForall\n          \n          ILogicFunc.fEntails ILogicFunc.fTrue ILogicFunc.fFalse ILogicFunc.fAnd \n          ILogicFunc.fOr ILogicFunc.fImpl ILogicFunc.fExists ILogicFunc.fForall\n          ILogicFuncSumL ILogicFuncSumR ILogicFuncExpr\n          ILogicFunc.RSym_ilfunc \n          Charge.ModularFunc.ILogicFunc.ILogicFuncInst\n          \n          ILogicFunc.funcD ILogicFunc.typ2_cast_quant\n\t\t  Charge.ModularFunc.ILogicFunc.trueD\n\t\t  Charge.ModularFunc.ILogicFunc.falseD\n\t\t  Charge.ModularFunc.ILogicFunc.andD\n\t\t  Charge.ModularFunc.ILogicFunc.orD\n\t\t  Charge.ModularFunc.ILogicFunc.implD\n          \n          (* BILogicFunc *)\n          \n          BILogicFunc.mkEmp BILogicFunc.mkStar BILogicFunc.mkWand\n          \n          BILogicFunc.fEmp BILogicFunc.fStar BILogicFunc.fWand\n          \n          BILogicFuncSumL BILogicFuncSumR BILogicFuncExpr\n          BILogicFunc.RSym_bilfunc BILogicFunc.BILogicFuncInst\n          \n\t\t  Charge.ModularFunc.BILogicFunc.empD\n\t\t  Charge.ModularFunc.BILogicFunc.starD\n\t\t  Charge.ModularFunc.BILogicFunc.wandD\n          \n          BILogicFunc.typeof_bilfunc\n          \n          (* LaterFunc *)\n          \n          LaterFunc.mkLater\n          \n          LaterFunc.fLater\n          \n          LaterFunc.LaterFuncSumL LaterFunc.LaterFuncSumR LaterFunc.LaterFuncExpr          \n          LaterFunc.RSym_later_func LaterFunc.LaterFuncInst\n          \n          LaterFunc.funcD LaterFunc.typ2_cast'\n          \n          LaterFunc.typeof_later_func\n          \n          (* EmbedFunc *)\n          \n          EmbedFunc.mkEmbed\n          \n          EmbedFunc.fEmbed\n          \n          EmbedFunc.EmbedFuncSumL EmbedFunc.EmbedFuncSumR EmbedFuncExpr\n          EmbedFunc.RSym_embed_func EmbedFunc.EmbedFuncInst\n          \n          EmbedFunc.funcD \n          \n\t\t  Charge.ModularFunc.EmbedFunc.embedD\n\n          EmbedFunc.typeof_embed_func\n          \n          (* BaseFunc *)\n          \n          BaseFunc.BaseFuncSumL BaseFunc.BaseFuncSumR BaseFunc.BaseFuncExpr\n          \n          BaseFunc.BaseFuncInst\n          BaseFunc.mkNat BaseFunc.mkString BaseFunc.mkBool\n          BaseFunc.mkEq BaseFunc.mkPair\n          \n          BaseFunc.fConst\n          BaseFunc.fEq BaseFunc.fPair\n          \n          BaseFunc.RSym_BaseFunc\n          \n          BaseFunc.typeof_base_func BaseFunc.base_func_eq BaseFunc.base_func_symD\n          \n          (* ListFunc *)\n          \n          ListFunc.ListFuncSumL ListFunc.ListFuncSumR ListFunc.ListFuncExpr\n          \n          ListFunc.ListFuncInst\n          ListFunc.mkNil ListFunc.mkCons ListFunc.mkLength \n          ListFunc.mkZip ListFunc.mkMap ListFunc.mkFold\n          \n          ListFunc.fNil ListFunc.fCons ListFunc.fLength\n          ListFunc.fZip ListFunc.fMap ListFunc.fFold\n          \n          ListFunc.typeof_list_func ListFunc.list_func_eq ListFunc.list_func_symD\n          ListFunc.RelDec_list_func\n          \n          ListFunc.nilD ListFunc.consD ListFunc.mapD ListFunc.zipD ListFunc.NoDupD ListFunc.foldD\n          ListFunc.listD ListFunc.listD_sym\n          \n\t\t  (* OpenFunc *)\n\t\t  \n\t\t  OpenFunc.mkConst OpenFunc.mkAp OpenFunc.mkNull OpenFunc.mkStackGet\n\t\t  OpenFunc.mkStackSet OpenFunc.mkApplySubst OpenFunc.mkSingleSubst OpenFunc.mkSubst\n\t\t  OpenFunc.mkTruncSubst\n\t\t    \n\t\t  OpenFunc.fConst OpenFunc.fAp OpenFunc.fNull OpenFunc.fStackGet\n\t\t  OpenFunc.fApplySubst OpenFunc.fSingleSubst OpenFunc.fSubst OpenFunc.fTruncSubst\n\t\t  \n\t\t  OpenFunc.OpenFuncSumL OpenFunc.OpenFuncSumR OpenFunc.OpenFuncExpr\n\t\t  OpenFunc.OpenFuncInst OpenFunc.open_func_symD\n\t\t  \n\t\t  OpenFunc.typeof_open_func OpenFunc.RSym_OpenFunc\n\t\t  OpenFunc.RelDec_open_func\n\n\t\t  Charge.ModularFunc.OpenFunc.constD\n\t\t  Charge.ModularFunc.OpenFunc.apD\n\t\t  Charge.ModularFunc.OpenFunc.stack_getD\n\t\t  Charge.ModularFunc.OpenFunc.stack_setD\n\t\t  Charge.ModularFunc.OpenFunc.applySubstD\n\t\t  Charge.ModularFunc.OpenFunc.singleSubstD\n\n\n\t\t  \n          (* BaseType *)\n          \n          BaseType.tyPair BaseType.tyNat BaseType.tyString BaseType.tyBool\n          BaseType.btPair BaseType.btNat BaseType.btBool BaseType.btString\n          \n          BaseType.natD BaseType.boolD BaseType.stringD BaseType.pairD\n          BaseType.natD_sym BaseType.boolD_sym BaseType.stringD_sym BaseType.pairD_sym\n          \n          (* ListType *)\n          \n          ListType.tyList ListType.btList\n          \n          (* SubstType *)\n          \n          SubstType.tyVal SubstType.tySubst\n          SubstType.stSubst\n          \n          (* JavaType *)\n         \n          Typ2_Fun Typ0_Prop RType_typ typD\n          should_not_be_necessary should_also_not_be_necessary\n         \n          JavaType.BaseType_typ JavaType.BaseTypeD_typ JavaType.ListType_typ\n          JavaType.ListTypeD_typ JavaType.bilops JavaType.ilops\n          JavaType.eops JavaType.lops\n          \n       (*   JavaType.typD *)\n\t\t (* JavaFunc *)\n          \n          ilops is_pure func RSym_JavaFunc typeof_java_func java_func_eq\n          java_func_symD RelDec_java_func typeof_ilfunc\n                   \n          RSym_ilfunc RSym_open_func RSym_OpenFunc RSym_ListFunc\n          JavaFunc.RSym_bilfunc JavaFunc.RSym_embed_func JavaFunc.RSym_later_func\n          JavaFunc.RSym_ilfunc\n          JavaFunc.Expr_expr\n          mkPointstoVar\n          JavaFunc.RSym_func JavaFunc.java_env\n          JavaFunc.mkVal JavaFunc.mkFields\n          JavaFunc.mkProg JavaFunc.mkCmd JavaFunc.mkDExpr JavaFunc.mkFields\n          JavaFunc.fMethodSpec JavaFunc.fProgEq JavaFunc.fTriple JavaFunc.fTypeOf\n          JavaFunc.fFieldLookup JavaFunc.fPointsto JavaFunc.mkNull\n          JavaFunc.fPlus JavaFunc.fMinus JavaFunc.fTimes JavaFunc.fAnd\n          JavaFunc.fOr JavaFunc.fNot JavaFunc.fLt JavaFunc.fValEq\n          JavaFunc.mkTriple JavaFunc.mkFieldLookup JavaFunc.mkTypeOf\n          JavaFunc.mkProgEq JavaFunc.mkExprList JavaFunc.evalDExpr\n          \n(* OTHER *)\n  \n          SubstType_typ\n          \n          goalD Ctx.propD propD exprD'_typ0 exprD split_env\n          \n          amap_substD\n          substD\n          SUBST.raw_substD\n          UVarMap.MAP.fold\n          FMapPositive.PositiveMap.fold\n          FMapPositive.PositiveMap.xfoldi\n          FMapPositive.append\n          UVarMap.MAP.from_key\n          pred\n          plus\n          Pos.to_nat\n          Pos.iter_op\n          app\n          HList.hlist_app\n          Quant._foralls\n          Quant._exists\n          goalD_Prop\n          ].\n\nLet elem_ctor : forall x : typ, typD x -> @SymEnv.function _ _ :=\n  @SymEnv.F _ _.\n\nLtac reify_aux reify term_table e n :=\n  let k fs e :=\n      pose e as n in\n  reify_expr reify k\n             [ (fun (y : @mk_dvar_map _ _ _ _ term_table elem_ctor) => True) ]\n             [ e ].\n\nLtac run_rtac reify term_table tac_sound :=\n  match type of tac_sound with\n    | rtac_sound ?tac =>\n\t  let name := fresh \"e\" in\n\t  match goal with\n\t    | |- ?P => \n\t      reify_aux reify term_table P name;\n\t      let t := eval vm_compute in (typeof_expr nil nil name) in\n\t      let goal := eval unfold name in name in\n\t      match t with\n\t        | Some ?t =>\n\t          let goal_result := constr:(run_tac tac (GGoal name)) in \n\t          let result := eval vm_compute in goal_result in\n\t          match result with\n\t            | More_ ?s ?g => \n\t              cut (goalD_Prop nil nil g); [\n\t                let goal_resultV := g in\n\t               (* change (goalD_Prop nil nil goal_resultV -> exprD_Prop nil nil name);*)\n\t                exact_no_check (@run_rtac_More _ tac _ _ _ tac_sound\n\t                \t(@eq_refl (Result (CTop nil nil)) (More_ s goal_resultV) <:\n\t                \t   run_tac tac (GGoal goal) = (More_ s goal_resultV)))\n\t                | cbv_denote\n\t              ]\n\t            | Solved ?s =>\n\t              exact_no_check (@run_rtac_Solved _ tac s name tac_sound \n\t                (@eq_refl (Result (CTop nil nil)) (Solved s) <: run_tac tac (GGoal goal) = Solved s))\n\t            | Fail => idtac \"Tactic\" tac \"failed.\"\n\t            | _ => idtac \"Error: run_rtac could not resolve the result from the tactic :\" tac\n\t          end\n\t        | None => idtac \"expression \" goal \"is ill typed\" t\n\t      end\n\t  end\n\t| _ => idtac tac_sound \"is not a soudness theorem.\"\n  end.\n\nLtac run_rtac_debug reify term_table tac_sound :=\n  match type of tac_sound with\n    | rtac_sound ?tac =>\n\t  let name := fresh \"e\" in\n\t  match goal with\n\t    | |- ?P => \n\t      reify_aux reify term_table P name;\n\t      let t := eval vm_compute in (typeof_expr nil nil name) in\n\t      let goal := eval unfold name in name in\n\t      match t with\n\t        | Some ?t =>\n\t          let goal_result := constr:(run_tac tac (GGoal name)) in \n\t          let result := eval vm_compute in goal_result in\n\t          idtac result;\n\t          match result with\n\t            | More_ ?s ?g => \n\t              cut (goalD_Prop nil nil g); [\n\t                let goal_resultV := g in\n\t               (* change (goalD_Prop nil nil goal_resultV -> exprD_Prop nil nil name);*)\n\t                exact_no_check (@run_rtac_More _ tac _ _ _ tac_sound\n\t                \t(@eq_refl (Result (CTop nil nil)) (More_ s goal_resultV) <:\n\t                \t   run_tac tac (GGoal goal) = (More_ s goal_resultV)))\n\t                | cbv_denote\n\t              ]\n\t            | Solved ?s =>\n\t              exact_no_check (@run_rtac_Solved _ tac s name tac_sound \n\t                (@eq_refl (Result (CTop nil nil)) (Solved s) <: run_tac tac (GGoal goal) = Solved s))\n\t            | Fail => idtac \"Tactic\" tac \"failed.\"\n\t            | _ => idtac \"Error: run_rtac could not resolve the result from the tactic :\" tac\n\t          end\n\t        | None => idtac \"expression \" goal \"is ill typed\" t\n\t      end\n\t  end\n\t| _ => idtac tac_sound \"is not a soudness theorem.\"\n  end.\n \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/Tactics/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2766966039170211}}
{"text": "Require Import Crypto.Compilers.SmartMap.\nRequire Import Crypto.Compilers.Named.Context.\nRequire Import Crypto.Compilers.Named.Syntax.\nRequire Import Crypto.Compilers.Named.MapCast.\nRequire Import Crypto.Compilers.Named.InterpretToPHOAS.\nRequire Import Crypto.Compilers.Named.Compile.\nRequire Import Crypto.Compilers.Named.PositiveContext.\nRequire Import Crypto.Compilers.Named.PositiveContext.Defaults.\nRequire Import Crypto.Compilers.Syntax.\n\n(** N.B. This procedure only works when there are no nested lets,\n    i.e., nothing like [let x := let y := z in w] in the PHOAS syntax\n    tree.  This is a limitation of [compile]. *)\n\nSection language.\n  Context {base_type_code : Type}\n          {op : flat_type base_type_code -> flat_type base_type_code -> Type}\n          (base_type_code_beq : base_type_code -> base_type_code -> bool)\n          (base_type_code_bl_transparent : forall x y, base_type_code_beq x y = true -> x = y)\n          (failb : forall var t, @Syntax.exprf base_type_code op var (Tbase t))\n          {interp_base_type_bounds : base_type_code -> Type}\n          (interp_op_bounds : forall src dst, op src dst -> interp_flat_type interp_base_type_bounds src -> interp_flat_type interp_base_type_bounds dst)\n          (pick_typeb : forall t, interp_base_type_bounds t -> base_type_code).\n  Local Notation pick_type v := (SmartFlatTypeMap pick_typeb v).\n  Context (cast_op : forall t tR (opc : op t tR) args_bs,\n              op (pick_type args_bs) (pick_type (interp_op_bounds t tR opc args_bs))).\n\n  Local Notation PContext var := (PositiveContext _ var _ base_type_code_bl_transparent).\n\n  Section MapCast.\n    Context {t} (e : Expr base_type_code op t)\n            (input_bounds : interp_flat_type interp_base_type_bounds (domain t)).\n\n    Definition MapCastCompile\n      := compile (e _) (DefaultNamesFor e).\n    Definition MapCastDoCast (e' : option (Named.expr base_type_code op BinNums.positive t))\n      := option_map\n           (fun e'' => map_cast\n                         interp_op_bounds pick_typeb cast_op\n                         (BoundsContext:=PContext _)\n                         empty\n                         e''\n                         input_bounds)\n           e'.\n    Definition MapCastDoInterp\n               (e' : option\n                       (option\n                          { output_bounds : interp_flat_type interp_base_type_bounds (codomain t) &\n                                           Named.expr _ _ _ (Arrow (pick_type input_bounds) (pick_type output_bounds)) }))\n      : option { output_bounds : interp_flat_type interp_base_type_bounds (codomain t)\n                                 & Expr base_type_code op (Arrow (pick_type input_bounds) (pick_type output_bounds)) }\n      := match e' with\n         | Some (Some (existT output_bounds e''))\n           => Some (existT _ output_bounds (InterpToPHOAS (Context:=fun var => PContext var) failb e''))\n         | Some None | None => None\n         end.\n    Definition MapCast\n      : option { output_bounds : interp_flat_type interp_base_type_bounds (codomain t)\n                                 & Expr base_type_code op (Arrow (pick_type input_bounds) (pick_type output_bounds)) }\n      := MapCastDoInterp (MapCastDoCast MapCastCompile).\n  End MapCast.\nEnd language.\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/MapCastByDeBruijn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2766965966962596}}
{"text": "Require Import VST.msl.log_normalize.\nRequire Import VST.msl.ghost.\nRequire Import VST.msl.ghost_seplog.\nRequire Export VST.veric.base.\nRequire Import VST.veric.rmaps.\nRequire Import VST.veric.compcert_rmaps.\nRequire Import VST.veric.res_predicates.\n\nImport RML. Import R.\nLocal Open Scope pred.\n\nNotation ghost_approx m := (ghost_fmap (approx (level m)) (approx (level m))).\n\n(* Ownership construction based on \"Iris from the ground up\", Jung et al. *)\nProgram Definition ghost_is g: pred rmap :=\n  fun m => ghost_of m = ghost_approx m g.\nNext Obligation.\n  intros ???? Hg.\n  rewrite (age1_ghost_of _ _ H), Hg.\n  pose proof (age_level _ _ H).\n  rewrite ghost_fmap_fmap, approx_oo_approx', approx'_oo_approx by omega; eauto.\nQed.\n\nDefinition Own g: pred rmap := allp noat && ghost_is g.\n\nLemma Own_op: forall a b c, join a b c -> Own c = Own a * Own b.\nProof.\n  intros; apply pred_ext.\n  - intros w (Hno & Hg).\n    destruct (make_rmap (resource_at w) (ghost_approx w a) (level w))\n      as (wa & Hla & Hra & Hga).\n    { extensionality; apply resource_at_approx. }\n    { rewrite ghost_fmap_fmap, approx_oo_approx; auto. }\n    destruct (make_rmap (resource_at w) (ghost_approx w b) (level w))\n      as (wb & Hlb & Hrb & Hgb).\n    { extensionality; apply resource_at_approx. }\n    { rewrite ghost_fmap_fmap, approx_oo_approx; auto. }\n    exists wa, wb; split.\n    + apply resource_at_join2; auto.\n      * intro; rewrite Hra, Hrb.\n        apply identity_unit', Hno.\n      * rewrite Hg, Hga, Hgb.\n        apply ghost_fmap_join; auto.\n    + simpl; rewrite Hla, Hlb, Hra, Hrb, Hga, Hgb; simpl; eauto 6.\n  - intros w (w1 & w2 & J & (Hnoa & Hga) & (Hnob & Hgb)).\n    split.\n    + intro l; apply (resource_at_join _ _ _ l) in J.\n      simpl in *; rewrite <- (Hnoa _ _ _ J); auto.\n    + destruct (join_level _ _ _ J) as [Hl1 Hl2].\n      apply ghost_of_join in J.\n      rewrite Hga, Hgb in J.\n      eapply join_eq; eauto.\n      rewrite Hl1, Hl2; apply ghost_fmap_join; auto.\nQed.\n\nFixpoint make_join (a c : ghost) : ghost :=\n  match a, c with\n  | nil, _ => c\n  | _, nil => nil\n  | None :: a', x :: c' => x :: make_join a' c'\n  | _ :: a', None :: c' => None :: make_join a' c'\n  | Some (ga, pa) :: a', Some (gc, _) :: c' => Some (gc, pa) :: make_join a' c'\n  end.\n\nLemma make_join_nil : forall a, make_join a nil = nil.\nProof.\n  destruct a; auto.\n  destruct o as [[]|]; auto.\nQed.\n\nLemma make_join_nil_cons : forall o a c, make_join (o :: a) (None :: c) = None :: make_join a c.\nProof.\n  destruct o as [[]|]; auto.\nQed.\n\nLemma ghost_joins_approx: forall n a c,\n  joins (ghost_fmap (approx n) (approx n) a) (ghost_fmap (approx n) (approx n) c) ->\n  let c' := make_join a c in\n  joins (ghost_fmap (approx (S n)) (approx (S n)) a) (ghost_fmap (approx (S n)) (approx (S n)) c') /\\\n    forall b, joins b (ghost_fmap (approx (S n)) (approx (S n)) c') ->\n      joins (ghost_fmap (approx n) (approx n) b) (ghost_fmap (approx n) (approx n) c).\nProof.\n  intros ???; revert a; induction c; intros; subst c'; simpl.\n  - rewrite make_join_nil; split.\n    + eexists; constructor.\n    + eexists; constructor.\n  - destruct H; inv H.\n    + destruct a0; inv H1.\n      split.\n      { eexists; constructor. }\n      intros ? []; eexists.\n      apply ghost_fmap_join with (f := approx n)(g := approx n) in H.\n      rewrite ghost_fmap_fmap, approx_oo_approx', approx'_oo_approx in H by auto; eauto.\n    + destruct a0; inv H0.\n      destruct (IHc a0) as (H & Hc'); eauto.\n      inv H3.\n      * destruct o; inv H1.\n        split.\n        { destruct H; eexists; constructor; eauto; constructor. }\n        intros ? [? J]; inv J; [eexists; constructor|].\n        destruct (Hc' m1); eauto.\n        eexists; constructor; eauto.\n        instantiate (1 := option_map (fun '(a, b) => (a, preds_fmap (approx n) (approx n) b)) a3).\n        inv H3.\n        -- destruct a as [[]|]; [simpl | constructor].\n           rewrite preds_fmap_fmap, approx_oo_approx', approx'_oo_approx by auto; constructor; auto.\n        -- destruct a; inv H4; constructor.\n        -- destruct a as [[]|]; inv H1; constructor.\n           destruct a2, a5; inv H4; constructor; auto; simpl in *.\n           inv H2.\n           rewrite preds_fmap_fmap, approx_oo_approx', approx'_oo_approx by auto; constructor; auto.\n      * destruct a; inv H2.\n        rewrite make_join_nil_cons.\n        split.\n        { destruct H; eexists; constructor; eauto; constructor. }\n        intros ? [? J]; inv J; [eexists; constructor|].\n        destruct (Hc' m1); eauto.\n        eexists; constructor; eauto; constructor.\n      * destruct o as [[]|], a as [[]|]; inv H0; inv H1.\n        split.\n        { destruct H.\n          destruct a4; inv H2; simpl in *.\n          inv H1.\n          eexists (Some (_, _) :: _); constructor; eauto; constructor.\n          constructor; simpl; eauto; constructor; eauto. }\n        intros ? [? J]; inv J; [eexists; constructor|].\n        destruct (Hc' m1); eauto.\n        eexists; constructor; eauto.\n        instantiate (1 := option_map (fun '(a, b) => (a, preds_fmap (approx n) (approx n) b)) a3).\n        inv H4.\n        -- destruct a4; inv H2; simpl in *.\n           inv H3.\n           rewrite <- H2, preds_fmap_fmap, approx_oo_approx', approx'_oo_approx by auto; constructor.\n        -- constructor.\n           destruct a2, a4, a6; inv H2; inv H6; constructor; auto; simpl in *.\n           inv H3; inv H4.\n           rewrite <- H6, preds_fmap_fmap, approx_oo_approx', approx'_oo_approx by auto; constructor; auto.\nQed.\n\nProgram Definition bupd (P: pred rmap): pred rmap :=\n  fun m => forall c, joins (ghost_of m) (ghost_approx m c) ->\n    exists b, joins b (ghost_approx m c) /\\\n    exists m', level m' = level m /\\ resource_at m' = resource_at m /\\ ghost_of m' = b /\\ P m'.\nNext Obligation.\nProof.\n  repeat intro.\n  rewrite (age1_ghost_of _ _ H) in H1.\n  rewrite <- ghost_of_approx in H0.\n  destruct (ghost_joins_approx _ _ _ H1) as (J0 & Hc0).\n  rewrite <- (age_level _ _ H) in *.\n  specialize (H0 _ J0); destruct H0 as (b & J & Hrb).\n  pose proof (age_level _ _ H).\n  exists (ghost_approx a' b); split; auto.\n  destruct Hrb as (m' & Hl' & Hr' & Hg' & HP).\n  destruct (levelS_age m' (level a')) as (m'' & Hage' & Hl'').\n  { congruence. }\n  exists m''; repeat split; auto.\n  + extensionality l.\n    erewrite (age1_resource_at _ _ H l) by (symmetry; apply resource_at_approx).\n    erewrite (age1_resource_at _ _ Hage' l) by (symmetry; apply resource_at_approx).\n    congruence.\n  + rewrite (age1_ghost_of _ _ Hage').\n    rewrite Hg', <- Hl''; auto.\n  + eapply (proj2_sig P); eauto.\nQed.\n\nLemma bupd_intro: forall P, P |-- bupd P.\nProof.\n  repeat intro; eauto 7.\nQed.\n\nLemma bupd_mono: forall P Q, P |-- Q -> bupd P |-- bupd Q.\nProof.\n  repeat intro.\n  simpl in *.\n  destruct (H0 _ H1) as (b & ? & m' & ? & ? & ? & ?).\n  exists b; split; auto.\n  exists m'; repeat split; auto.\nQed.\n\nLemma bupd_frame_r: forall P Q, bupd P * Q |-- bupd (P * Q).\nProof.\n  repeat intro.\n  destruct H as (w1 & w2 & J & HP & HQ).\n  destruct (join_level _ _ _ J) as [Hl1 Hl2].\n  pose proof (ghost_of_join _ _ _ J) as Jg.\n  destruct H0 as [? J'].\n  destruct (join_assoc Jg J') as (c' & J1 & J2).\n  erewrite <- (ghost_same_level_gen (level a) (ghost_of w2) c c') in J2, J1\n    by (rewrite <- Hl2 at 1 2; rewrite ghost_of_approx; auto).\n  destruct (HP c') as (? & [? J1'] & w1' & ? & Hr' & ? & HP'); subst.\n  { rewrite Hl1; eauto. }\n  rewrite Hl1 in J1'; destruct (join_assoc (join_comm J1) (join_comm J1')) as (w' & ? & ?).\n  exists w'; split; [eexists; apply join_comm; eauto|].\n  destruct (make_rmap (resource_at a) w' (level a)) as (m' & ? & Hr'' & ?); subst.\n  { extensionality l; apply resource_at_approx. }\n  { eapply ghost_same_level_gen.\n    rewrite <- (ghost_of_approx w2), <- (ghost_of_approx w1'), H, Hl1, Hl2 in H0.\n    apply join_comm; eauto. }\n  exists m'; repeat split; auto.\n  exists w1', w2; repeat split; auto.\n  apply resource_at_join2; auto; try omega.\n  intro; rewrite Hr', Hr''.\n  apply resource_at_join; auto.\nQed.\n\nLemma bupd_frame_l: forall P Q, P * bupd Q |-- bupd (P * Q).\nProof.\n  intros; rewrite sepcon_comm, (sepcon_comm P Q); apply bupd_frame_r.\nQed.\n\nLemma bupd_trans: forall P, bupd (bupd P) |-- bupd P.\nProof.\n  repeat intro.\n  destruct (H _ H0) as (b & J & a' & Hl & Hr & ? & Ha'); subst.\n  rewrite <- Hl in J; destruct (Ha' _ J) as (b' & ? & Hm').\n  rewrite <- Hl, <- Hr; eauto.\nQed.\n\nLemma bupd_prop : forall P, bupd (!! P) = !! P.\nProof.\n  intros ?; apply pred_ext.\n  - intros ??; simpl in *.\n    destruct (H (core (ghost_of a))) as (? & ? & ? & ? & ? & ? & ?); auto.\n    eexists.\n    rewrite ghost_core; simpl; erewrite <- ghost_core.\n    apply join_comm, core_unit.\n  - intros ??.\n    do 2 eexists; eauto.\nQed.\n\nLemma subp_bupd: forall (G : pred nat) (P P' : pred rmap), G |-- P >=> P' ->\n    G |-- (bupd P >=> bupd P')%pred.\nProof.\n  repeat intro.\n  specialize (H3 _ H4) as (? & ? & ? & ? & ? & ? & HP).\n  do 2 eexists; eauto; do 2 eexists; eauto; repeat (split; auto).\n  pose proof (necR_level _ _ H2).\n  apply (H _ H0 x0 ltac:(omega) _ (necR_refl _)); auto.\nQed.\n\nLemma eqp_bupd: forall (G : pred nat) (P P' : pred rmap), G |-- P <=> P' ->\n    G |-- (bupd P <=> bupd P').\nProof.\n  intros.\n  rewrite fash_and in *.\n  apply andp_right; apply subp_bupd; eapply derives_trans; try apply H;\n    [apply andp_left1 | apply andp_left2]; apply derives_refl.\nQed.\n\nDefinition ghost_fp_update_ND a B :=\n  forall n c, joins (ghost_fmap (approx n) (approx n) a) c ->\n    exists b, B b /\\ joins (ghost_fmap (approx n) (approx n) b) c.\n\nLemma Own_update_ND: forall a B, ghost_fp_update_ND a B ->\n  Own a |-- bupd (EX b : _, !!(B b) && Own b).\nProof.\n  repeat intro.\n  destruct H0 as (Hno & Hg).\n  rewrite Hg in H1.\n  destruct H1 as [? J].\n  destruct (H (level a0) (ghost_approx a0 c)) as (g' & ? & J').\n  { eexists; eauto. }\n  exists (ghost_fmap (approx (level a0)) (approx (level a0)) g'); split; auto.\n  destruct (make_rmap (resource_at a0)\n    (ghost_fmap (approx (level a0)) (approx (level a0)) g') (level a0))\n    as (m' & Hl & Hr & Hg').\n  { extensionality; apply resource_at_approx. }\n  { rewrite ghost_fmap_fmap, approx_oo_approx; auto. }\n  exists m'; repeat split; auto.\n  exists g'; repeat split; auto.\n  - simpl in *; intro; rewrite Hr; auto.\n  - simpl; rewrite Hg', Hl; simpl; eauto.\nQed.\n\nDefinition ghost_fp_update (a b : ghost) :=\n  forall n c, joins (ghost_fmap (approx n) (approx n) a) c ->\n               joins (ghost_fmap (approx n) (approx n) b) c.\n\nInstance ghost_fp_update_preorder: RelationClasses.PreOrder ghost_fp_update.\nProof.\n  split; repeat intro; auto.\nQed.\n\nLemma ghost_fp_update_approx: forall a b n, ghost_fp_update a b ->\n  ghost_fp_update (ghost_fmap (approx n) (approx n) a) (ghost_fmap (approx n) (approx n) b).\nProof.\n  intros; intros m c J.\n  rewrite ghost_fmap_fmap in *.\n  replace (approx m oo approx n) with (approx (min m n)) in *.\n  replace (approx n oo approx m) with (approx (min m n)) in *.\n  auto.\n  { destruct (Min.min_spec m n) as [[? ->] | [? ->]];\n      [rewrite approx'_oo_approx | rewrite approx_oo_approx']; auto; omega. }\n  { destruct (Min.min_spec m n) as [[? ->] | [? ->]];\n      [rewrite approx_oo_approx' | rewrite approx'_oo_approx]; auto; omega. }\nQed.\n\nLemma Own_update: forall a b, ghost_fp_update a b ->\n  Own a |-- bupd (Own b).\nProof.\n  intros; eapply derives_trans.\n  - eapply (Own_update_ND _ (eq _)).\n    repeat intro.\n    eexists; split; [constructor|].\n    apply H; eauto.\n  - apply bupd_mono.\n    repeat (apply exp_left; intro).\n    apply prop_andp_left; intro X; inv X; auto.\nQed.\n\nLemma Own_unit: emp |-- EX a : _, !!(identity a) && Own a.\nProof.\n  intros w ?; simpl in *.\n  exists (ghost_of w); split; [|split].\n  - apply ghost_of_identity; auto.\n  - intro; apply resource_at_identity; auto.\n  - rewrite ghost_of_approx; auto.\nQed.\n\nLemma Own_dealloc: forall a, Own a |-- bupd emp.\nProof.\n  intros ? w [] ??.\n  exists (core ((ghost_approx w) c)); split; [eexists; apply core_unit|].\n  destruct (make_rmap (resource_at w) (core (ghost_approx w c)) (level w)) as (w' & ? & Hr & Hg).\n  { extensionality; apply resource_at_approx. }\n  { rewrite ghost_core; auto. }\n  exists w'; repeat split; auto.\n  apply all_resource_at_identity.\n  - rewrite Hr; auto.\n  - rewrite Hg; apply core_identity.\nQed.\n\nDefinition singleton {A} k (x : A) : list (option A) := repeat None k ++ Some x :: nil.\n\nDefinition gname := nat.\n\nDefinition own {RA: Ghost} (n: gname) (a: G) (pp: preds) :=\n  EX v : _, Own (singleton n (existT _ RA (exist _ a v), pp)).\n\nDefinition list_set {A} (m : list (option A)) k v : list (option A) :=\n  firstn k m ++ repeat None (k - length m) ++ Some v :: skipn (S k) m.\n\nLemma singleton_join_gen: forall k a c (m: ghost)\n  (Hjoin: join (Some a) (nth k m None) (Some c)),\n  join (singleton k a) m (list_set m k c).\nProof.\n  induction k; intros.\n  - destruct m; simpl in *; subst; inv Hjoin; constructor; constructor; auto.\n  - destruct m; simpl in *.\n    + inv Hjoin; constructor.\n    + constructor; [constructor | apply IHk; auto].\nQed.\n\nLemma map_repeat : forall {A B} (f : A -> B) x n, map f (repeat x n) = repeat (f x) n.\nProof.\n  induction n; auto; simpl.\n  rewrite IHn; auto.\nQed.\n\nLemma ghost_fmap_singleton: forall f g k v, ghost_fmap f g (singleton k v) =\n  singleton k (match v with (a, b) => (a, preds_fmap f g b) end).\nProof.\n  intros; unfold ghost_fmap, singleton.\n  rewrite map_app, map_repeat; auto.\nQed.\n\nLemma ghost_fmap_singleton_inv : forall f g a k v,\n  ghost_fmap f g a = singleton k v ->\n  exists v', a = singleton k v' /\\ v = let (a, b) := v' in (a, preds_fmap f g b).\nProof.\n  unfold singleton; induction a; simpl; intros.\n  - destruct k; discriminate.\n  - destruct a as [[]|]; simpl in *.\n    + destruct k; inv H.\n      destruct a0; inv H2.\n      simpl; eauto.\n    + destruct k; inv H.\n      edestruct IHa as (? & ? & ?); eauto; subst.\n      simpl; eauto.\nQed.\n\nLemma ghost_alloc: forall {RA: Ghost} a pp, ghost.valid a ->\n  emp |-- bupd (EX g: gname, own g a pp).\nProof.\n  intros.\n  eapply derives_trans; [apply Own_unit|].\n  apply exp_left; intro g0.\n  apply prop_andp_left; intro Hg0.\n  eapply derives_trans.\n  - apply Own_update_ND with (B := fun b => exists g, b = singleton g (existT _ RA (exist _ _ H), pp)).\n    intros ? c [? J]; exists (singleton (length c) (existT _ RA (exist _ _ H), pp)).\n    split; eauto.\n    rewrite (identity_core Hg0), ghost_core in J; inv J; [|eexists; constructor].\n    rewrite ghost_fmap_singleton; eexists; apply singleton_join_gen.\n    rewrite nth_overflow by auto; constructor.\n  - apply bupd_mono, exp_left; intro g'.\n    apply prop_andp_left; intros [g]; subst.\n    apply exp_right with g.\n    eapply exp_right; eauto.\nQed.\n\nLemma singleton_join: forall a b c k,\n  join (singleton k a) (singleton k b) (singleton k c) <-> join a b c.\nProof.\n  unfold singleton; induction k; simpl.\n  - split.\n    + inversion 1; subst.\n      inv H3; auto.\n    + intro; do 2 constructor; auto.\n  - rewrite <- IHk.\n    split; [inversion 1 | repeat constructor]; auto.\nQed.\n\nLemma singleton_join_inv: forall k a b c,\n  join (singleton k a) (singleton k b) c -> exists c', join a b c' /\\ c = singleton k c'.\nProof.\n  unfold singleton; induction k; inversion 1; subst.\n  - assert (m3 = nil) by (inv H6; auto).\n    inv H5; eauto.\n  - assert (a3 = None) by (inv H5; auto); subst.\n    edestruct IHk as (? & ? & ?); eauto; subst; eauto.\nQed.\n\nLemma ghost_valid_2: forall {RA: Ghost} g a1 a2 pp,\n  own g a1 pp * own g a2 pp |-- !!ghost.valid_2 a1 a2.\nProof.\n  intros.\n  intros w (? & ? & J%ghost_of_join & (? & ? & Hg1) & (? & ? & Hg2)).\n  rewrite Hg1, Hg2, !ghost_fmap_singleton in J.\n  apply singleton_join_inv in J as ([] & J & ?).\n  inv J; simpl in *.\n  inv H2; repeat inj_pair_tac.\n  eexists; eauto.\nQed.\n\nLemma ghost_op: forall {RA: Ghost} g (a1 a2 a3: G) pp, join a1 a2 a3 ->\n  own g a3 pp = own g a1 pp * own g a2 pp.\nProof.\n  intros; apply pred_ext.\n  - apply exp_left; intro.\n    erewrite Own_op; [apply sepcon_derives; eapply exp_right; eauto|].\n    apply singleton_join; constructor; constructor; auto.\n  - eapply derives_trans; [apply andp_right, derives_refl; apply ghost_valid_2|].\n    apply prop_andp_left; intros (? & J & ?).\n    eapply join_eq in H; eauto; subst.\n    unfold own; rewrite exp_sepcon1; apply exp_left; intro.\n    rewrite exp_sepcon2; apply exp_left; intro.\n    erewrite <- Own_op; [eapply exp_right; eauto|].\n    apply singleton_join; constructor; constructor; auto.\n  Unshelve.\n  eapply join_valid; eauto.\n  eapply join_valid; eauto.\n  auto.\nQed.\n\nLemma ghost_valid: forall {RA: Ghost} g a pp,\n  own g a pp |-- !!ghost.valid a.\nProof.\n  intros.\n  rewrite <- (normalize.andp_TT (!!_)).\n  erewrite ghost_op by apply core_unit.\n  eapply derives_trans; [apply andp_right, derives_refl; apply ghost_valid_2|].\n  apply prop_andp_left; intros (? & J & ?); apply prop_andp_right; auto.\n  apply core_identity in J; subst; auto.\nQed.\n\nLemma singleton_join_inv_gen: forall k a (b c: ghost),\n  join (singleton k a) b c ->\n  join (Some a) (nth k b None) (nth k c None) /\\\n    exists c', nth k c None = Some c' /\\ c = list_set b k c'.\nProof.\n  unfold singleton; induction k; inversion 1; subst; auto.\n  - split; simpl; eauto; constructor.\n  - split; auto.\n    unfold list_set; simpl.\n    rewrite <- (ghost_core m2) in H5.\n    apply (core_identity m2) in H5; subst.\n    inv H2; eauto.\n  - rewrite app_nth2; rewrite repeat_length; auto.\n    rewrite minus_diag; split; [constructor | simpl; eauto].\n  - assert (a2 = a3) by (inv H2; auto).\n    destruct (IHk _ _ _ H5) as (? & ? & ? & ?); subst; eauto.\nQed.\n\nLemma ghost_update_ND: forall {RA: Ghost} g (a: G) B pp,\n  fp_update_ND a B -> own g a pp |-- bupd (EX b : _, !!(B b) && own g b pp).\nProof.\n  intros.\n  apply exp_left; intro Hva.\n  eapply derives_trans.\n  - apply Own_update_ND with\n      (B := fun b => exists b' Hvb, B b' /\\ b = singleton g (existT _ RA (exist _ b' Hvb), pp)).\n    intros ?? [? J].\n    rewrite ghost_fmap_singleton in J.\n    destruct (singleton_join_inv_gen _ _ _ _ J) as [Jg _].\n    inv Jg.\n    + destruct (H (core a)) as (b & ? & Hv).\n      { eexists; split; [apply join_comm, core_unit | auto]. }\n      assert (ghost.valid b) as Hvb.\n      { destruct Hv as (? & ? & ?); eapply join_valid; eauto. }\n      exists (singleton g (existT _ RA (exist _ _ Hvb), pp)); split; eauto.\n      rewrite ghost_fmap_singleton.\n      eexists; apply singleton_join_gen.\n      rewrite <- H2; constructor.\n    + destruct a2, a3; inv H3; simpl in *.\n      inv H0; inj_pair_tac.\n      destruct (H b0) as (b & ? & Hv).\n      { eexists; eauto. }\n      destruct Hv as (? & ? & ?).\n      assert (ghost.valid b) as Hvb by (eapply join_valid; eauto).\n      exists (singleton g (existT _ RA (exist _ _ Hvb), pp)); split; eauto.\n      rewrite ghost_fmap_singleton.\n      eexists; apply singleton_join_gen.\n      instantiate (1 := (_, _)).\n      rewrite <- H1; constructor; constructor; [constructor|]; eauto.\n  - apply bupd_mono, exp_left; intro.\n    apply prop_andp_left; intros (b & ? & ? & ?); subst.\n    apply exp_right with b, prop_andp_right; auto.\n    eapply exp_right; auto.\n  Unshelve.\n  auto.\nQed.\n\nLemma ghost_update: forall {RA: Ghost} g (a b: G) pp,\n  fp_update a b -> own g a pp |-- bupd (own g b pp).\nProof.\n  intros; eapply derives_trans.\n  - apply (ghost_update_ND g a (eq b)).\n    intros ? J; destruct (H _ J).\n    do 2 eexists; [constructor | eauto].\n  - apply bupd_mono.\n    apply exp_left; intro; apply prop_andp_left; intro X; inv X; auto.\nQed.\n\nLemma ghost_dealloc: forall {RA: Ghost} g a pp,\n  own g a pp |-- bupd emp.\nProof.\n  intros; unfold own.\n  apply exp_left; intro; apply Own_dealloc.\nQed.\n\nLemma list_set_same : forall {A} n l (a : A), nth n l None = Some a ->\n  list_set l n a = l.\nProof.\n  unfold list_set; induction n; destruct l; simpl; try discriminate; intros; subst; auto.\n  f_equal; eauto.\nQed.\n\n(* The addition of ghost state means that there are rmaps that have only\n   cores for ghost state, but are not cores themselves (since they have ghost\n   state at all). An rmap of this sort is not emp, but is its own unit. *)\n\nDefinition cored: pred rmap := ALL P : pred rmap, ALL Q : pred rmap,\n  P && Q --> P * Q.\n\nProgram Definition is_w w: pred rmap := fun w' => necR w w'.\nNext Obligation.\nProof.\n  repeat intro.\n  eapply necR_trans; eauto.\n  constructor; auto.\nQed.\n\nLemma cored_unit: forall w, cored w = join w w w.\nProof.\n  intro; apply prop_ext; split; unfold cored; intro.\n  - edestruct (H (is_w w) (is_w w)) as (? & ? & J & Hw1 & Hw2).\n    { apply necR_refl. }\n    { split; apply necR_refl. }\n    simpl in *.\n    destruct (join_level _ _ _ J).\n    eapply necR_linear' in Hw1; try apply necR_refl; auto.\n    eapply necR_linear' in Hw2; try apply necR_refl; auto.\n    subst; auto.\n  - intros P Q ?? [HP HQ].\n    exists a', a'; repeat split; auto.\n    eapply nec_join in H as (? & ? & ? & Hw1 & Hw2); eauto.\n    destruct (join_level _ _ _ H).\n    eapply necR_linear' in Hw1; try apply H0; [|omega].\n    eapply necR_linear' in Hw2; try apply H0; [|omega].\n    subst; auto.\nQed.\n\nLemma cored_dup: forall P, P && cored |-- (P && cored) * (P && cored).\nProof.\n  intros.\n  rewrite <- (andp_dup cored) at 1.\n  rewrite <- andp_assoc.\n  intros; unfold cored at 2.\n  eapply modus_ponens.\n  + apply andp_left1, derives_refl.\n  + eapply andp_left2, allp_left, allp_left.\n    rewrite andp_dup; apply derives_refl.\nQed.\n\nLemma cored_core: forall w, cored (core w).\nProof.\n  intro; rewrite cored_unit.\n  apply identity_unit', core_identity.\nQed.\n\nLemma cored_duplicable: cored = cored * cored.\nProof.\n  apply pred_ext.\n  - rewrite <- andp_dup at 1.\n    eapply derives_trans; [apply cored_dup|].\n    apply sepcon_derives; apply andp_left1; auto.\n  - intros ? (? & ? & J & J1 & J2).\n    rewrite cored_unit in *.\n    destruct (join_assoc J1 J) as (? & J' & J1').\n    eapply join_eq in J'; [|apply J]; subst.\n    destruct (join_assoc J2 (join_comm J)) as (? & J' & J2').\n    eapply join_eq in J'; [|apply join_comm, J]; subst.\n    destruct (join_assoc (join_comm J1') (join_comm J2')) as (? & J' & ?).\n    eapply join_eq in J'; [|apply J]; subst; auto.\nQed.\n\nLemma cored_emp: cored |-- bupd emp.\nProof.\n  intro; rewrite cored_unit; intros J ??.\n  exists nil; split; [eexists; constructor|].\n  destruct (make_rmap (resource_at a) nil (level a)) as (m' & ? & Hr & Hg); auto.\n  { intros; extensionality; apply resource_at_approx. }\n  exists m'; repeat split; auto.\n  apply all_resource_at_identity.\n  - intro; rewrite Hr.\n    apply (resource_at_join _ _ _ l) in J.\n    inv J.\n    + apply join_self, identity_share_bot in RJ; subst.\n      apply NO_identity.\n    + apply join_self, identity_share_bot in RJ; subst.\n      contradiction shares.bot_unreadable.\n    + apply PURE_identity.\n  - rewrite Hg, <- (ghost_core nil); apply core_identity.\nQed.\n\nLemma join_singleton_inv: forall k a b RA c v pp,\n  join a b (singleton k (existT _ RA (exist _ (core c) v), pp)) ->\n  a = singleton k (existT _ RA (exist _ (core c) v), pp) \\/ b = singleton k (existT _ RA (exist _ (core c) v), pp).\nProof.\n  induction k; unfold singleton; intros; simpl in *.\n  - inv H; auto.\n    assert (m1 = nil /\\ m2 = nil) as [] by (inv H5; auto); subst.\n    inv H4; auto.\n    destruct a0, a3; inv H2; simpl in *.\n    inv H0; inv H.\n    inj_pair_tac.\n    pose proof (core_unit a0) as J.\n    erewrite join_core, core_idem in J by eauto.\n    unfold unit_for in J.\n    eapply join_positivity in J; eauto; subst.\n    left; repeat f_equal; apply proof_irr.\n  - inv H; auto.\n    edestruct IHk as [|]; eauto; [left | right]; f_equal; auto; inv H4; auto.\nQed.\n\nLemma own_cored: forall {RA: Ghost} g a pp, join a a a -> own g a pp |-- cored.\nProof.\n  intros; intros ? (? & ? & Hg).\n  rewrite cored_unit; simpl in *.\n  apply resource_at_join2; auto.\n  - intro; apply identity_unit'.\n    eapply necR_resource_at_identity; eauto.\n  - rewrite Hg, ghost_fmap_singleton.\n    apply singleton_join; repeat constructor; auto.\nQed.\n\nRequire Import VST.veric.tycontext.\nRequire Import VST.veric.Clight_seplog.\n \nLemma own_super_non_expansive: forall {RA: Ghost} n g a pp,\n  approx n (own g a pp) = approx n (own g a (preds_fmap (approx n) (approx n) pp)).\nProof.\n  intros; unfold own.\n  rewrite !approx_exp; f_equal; extensionality v.\n  unfold Own.\n  rewrite !approx_andp; f_equal.\n  apply pred_ext; intros ? [? Hg]; split; auto; simpl in *.\n  - rewrite <- ghost_of_approx, Hg.\n    rewrite !ghost_fmap_singleton, !preds_fmap_fmap.\n    rewrite approx_oo_approx, approx_oo_approx', approx'_oo_approx by omega; auto.\n  - rewrite ghost_fmap_singleton in *.\n    rewrite preds_fmap_fmap in Hg.\n    rewrite approx_oo_approx', approx'_oo_approx in Hg by omega; 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/veric/own.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2766960640272847}}
{"text": "From iris_examples.logrel.stlc Require Export fundamental.\nFrom iris.proofmode Require Import proofmode.\nFrom iris.program_logic Require Import adequacy.\nFrom iris.prelude Require Import options.\n\nLemma wp_soundness `{irisGS stlc_lang Σ} e τ : [] ⊢ₜ e : τ → ⊢ WP e {{ ⟦ τ ⟧ }}.\nProof.\n  iIntros (?).\n  replace e with e.[env_subst[]] by by asimpl.\n  iApply fundamental; eauto. iApply interp_env_nil.\nQed.\n\nTheorem soundness e τ e' thp :\n  [] ⊢ₜ e : τ → rtc erased_step ([e], ()) (thp, ()) → e' ∈ thp → not_stuck e' ().\nProof.\n  set (Σ := invΣ). intros.\n  cut (adequate NotStuck e () (λ _ _, True));\n    first by intros [_ Hsafe]; eapply Hsafe; eauto.\n  eapply (wp_adequacy Σ _). iIntros (Hinv ?).\n  iModIntro. iExists (λ _ _, True%I), (λ _, True%I). iSplit=>//.\n  set (HΣ := IrisG _ _ Hinv (λ _ _ _ _, True)%I (λ _, True)%I).\n  iApply (wp_wand with \"[]\"); first by iApply wp_soundness. eauto.\nQed.\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/logrel/stlc/soundness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2766521687738848}}
{"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 A B C D Aprime Bprime Cprime Dprime X Y E Z Eprime : Universe, ((wd_ X A /\\ (wd_ X Aprime /\\ (wd_ X C /\\ (wd_ X Cprime /\\ (wd_ Y B /\\ (wd_ Y Bprime /\\ (wd_ Y D /\\ (wd_ Y Dprime /\\ (wd_ A C /\\ (wd_ B D /\\ (wd_ A Aprime /\\ (wd_ A E /\\ (wd_ X Y /\\ (wd_ X B /\\ (wd_ A Y /\\ (wd_ A B /\\ (wd_ E Z /\\ (wd_ B C /\\ (wd_ Bprime Cprime /\\ (wd_ A D /\\ (wd_ Aprime Dprime /\\ (wd_ Aprime Bprime /\\ (col_ X A C /\\ (col_ X A Aprime /\\ (col_ X A Cprime /\\ (col_ Y B D /\\ (col_ Y B Bprime /\\ (col_ Y B Dprime /\\ (col_ E A B /\\ (col_ E C D /\\ (col_ Eprime Aprime Bprime /\\ (col_ Eprime E Z /\\ (col_ A D E /\\ col_ A B D))))))))))))))))))))))))))))))))) -> col_ A Y B)).\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_1128.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.2765957132979401}}
{"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 PSCIAux.Spec.\nRequire Import RVIC2.Specs.find_lock_map_target_rec.\nRequire Import RVIC2.LowSpecs.find_lock_map_target_rec.\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       mpidr_to_rec_idx_spec\n       get_rec_rec_idx_spec\n       get_rec_g_rec_spec\n       granule_lock_spec\n       granule_map_spec\n       set_target_rec_spec\n       get_rec_g_rd_spec\n       get_rec_g_rec_list_spec\n       find_lock_rec_spec\n       buffer_unmap_spec\n       is_null_spec\n       null_ptr_spec\n    .\n\n  Lemma find_lock_map_target_rec_spec_exists:\n    forall habd habd'  labd rec target\n           (Hspec: find_lock_map_target_rec_spec rec target habd = Some habd')\n            (Hrel: relate_RData habd labd),\n    exists labd', find_lock_map_target_rec_spec0 rec target labd = Some labd' /\\ relate_RData habd' labd'.\n  Proof.\n    Local Opaque ptr_eq.\n    intros. inv Hrel. destruct rec.\n    unfold find_lock_map_target_rec_spec, find_lock_map_target_rec_spec0 in *.\n    repeat autounfold in *. simpl in *.\n    hsimpl_hyp Hspec; inv Hspec; simpl_query_oracle; extract_prop_dec;\n      repeat destruct_con; simpl in *; srewrite; repeat grewrite; simpl; bool_rel;\n        repeat (simpl_htarget; srewrite; simpl in * );\n        repeat (solve_bool_range; grewrite); try solve_peq;\n          try solve[eexists; split; [reflexivity|constructor;reflexivity]].\n    ptr_ne 3%positive 3%positive. inversion e1. contra.\n    repeat (simpl_htarget; grewrite; simpl in * ).\n    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/RVIC2/RefProof/find_lock_map_target_rec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032313, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.27656764774341136}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Relations.Relation_Definitions.\nRequire Import \"Misc/Library\".\nRequire Import \"Misc/Tactics\".\nRequire Import \"Calculus/Sets\".\nRequire Import \"Calculus/Definitions\".\nRequire Import \"Calculus/MultiStaged/Definitions\".\nRequire Import \"Calculus/MultiStaged/DataGathering\".\nRequire Import \"Calculus/MultiStaged/Monad\".\n\n(**\n  There are two kind of variables:\n  - Source variables, corresponding to variables\n  already existing in expression\n  - Hole variables, corresponding to variables\n  created to put unbox content outside expression.\n\n  hole_var and source_var enable us to have disjoint sets\n *)\nDefinition hole_var (x:nat) : nat := (2*x+1)%nat.\nDefinition source_var (x:nat) : nat := (2*x)%nat.\n\nModule Type Context (R:Replacement) (S:ReplacementCalculus R) \n  (T:StagedCalculus) (DG:DataGathering R S) (M:Monad R S T DG).\n\n  Import T.\n  Import M.\n  Import DG.\n\n  Definition t : Type := list (expr * S.var).\n  Definition t_stack : Type := list t.\n\n  Definition empty : list t := nil.\n\n  Fixpoint fill (dg:dg_t) (c:t) (e:expr) :=\n    match c with\n    | nil => e\n    | (e1, x) :: c => M.bind dg e1 (fun v => \n        M.cast_eapp dg (M.cast_eabs dg (M.cast_var (hole_var x)) \n          (fill dg c e)) v)\n    end.\n\n  Fixpoint merge (cs1 cs2:t_stack) :=\n    match cs1, cs2 with\n    | nil, _ => cs2\n    | _, nil => cs1\n    | c1::cs1, c2::cs2 => \n       (c1 ++ c2) :: merge cs1 cs2\n    end.\n\n  Fixpoint shift (cs:t_stack) : t * t_stack :=\n    match cs with\n    | nil => (nil, nil)\n    | a :: nil => (a, nil)\n    | a :: cs => let (c, cs) := shift cs in\n       (c, a :: cs)\n    end.\n\n  Fixpoint unshift (cs:t_stack) (c:t) : t_stack :=\n    match cs with\n    | nil => c :: nil\n    | a :: cs => a :: (unshift cs c)\n    end.\n\n  Fixpoint context_hole_set (c:t) : VarSet.t :=\n    match c with\n    | nil => VarSet.empty\n    | (e1, x) :: c => VarSet.add x (context_hole_set c)\n    end.\n\n  Fixpoint stack_hole_set (cs:t_stack) : VarSet.t :=\n    match cs with\n    | nil => VarSet.empty\n    | c :: cs => VarSet.union (context_hole_set c) (stack_hole_set cs)\n    end.\n\n  Inductive congr_context (rel:relation expr) : relation t :=\n    | CongrCtx_nil: congr_context rel nil nil\n    | CongrCtx_cons: forall (k1 k2:t) (e1 e2:expr) (x:S.var),\n        congr_context rel k1 k2 -> rel e1 e2 -> \n        congr_context rel ((e1,x)::k1) ((e2,x)::k2).\n\n  Inductive congr_stack (rel:relation expr) : relation t_stack :=\n    | CongrStack_empty: congr_stack rel nil nil\n    | CongrStack_context: forall (s1 s2:t_stack) (k1 k2:t),\n       congr_stack rel s1 s2 -> congr_context rel k1 k2 ->\n       congr_stack rel (k1::s1) (k2::s2).\n\n  Fixpoint ssubst_context (n:nat) (ss:StageSet.t) \n    (x:S.var) (c:t) (v:expr) : t :=\n    match c with\n    | nil => nil\n    | (eh,h) :: c => (ssubst n ss (M.cast_var x) eh v, h) ::\n        (ssubst_context n (if beq_nat x (hole_var h)\n        then (StageSet.add n ss) else ss) x c v)\n    end.\n\n  Fixpoint ssubst_stack (n:nat) (ss:StageSet.t) \n    (x:S.var) (cs:t_stack) (v:expr) : t_stack :=\n    match cs with\n    | nil => nil\n    | c :: cs => (ssubst_context n ss x c v) ::\n       (ssubst_stack (pred n) (StageSet.remove n ss) x cs v)\n    end.\n\nEnd Context.\n\nModule ContextImpl (R:Replacement) (S:ReplacementCalculus R) \n    (T:StagedCalculus) (DG:DataGathering R S) (M:Monad R S T DG) : \n    Context R S T DG M.\n  Include Context R S T DG M.\nEnd ContextImpl.\n\n(* Translation R S T <: StagedTranslation S T. *)\nModule Type Translation (R:Replacement) (S:ReplacementCalculus R)\n    (T:StagedCalculus) (DG:DataGathering R S) \n    (DGP:DataGatheringPredicates R S DG)\n    (DGR:DataGatheringRequirements R S DG DGP) (M:Monad R S T DG). \n\n  Module Context := ContextImpl R S T DG M.\n  Module DGValid := DataGatheringProperties R S DG DGP DGR.\n  Import S.CRaw.\n  Import DG.\n\n  Fixpoint booker (e:S.expr) (n:nat) : nat :=\n    match e with \n    | EConst _ => 0\n    | EVar _ => 0\n    | EAbs _ e => booker e n\n    | EFix _ _ e => booker e n\n    | EApp e1 e2 => (booker e1 n + booker e2 n)%nat\n    | ELoc _ => 0\n    | ERef e => booker e n\n    | EDeref e => booker e n\n    | EAssign e1 e2 => (booker e1 n + booker e2 n)%nat\n    | EBox e => booker e (S n)\n    | EUnbox e => match n with\n       | 0 => 1\n       | S n => booker e n\n       end\n    | ERun e => booker e n\n    | ELift e => booker e n\n    end.\n\n  Definition map_iter_booker (e:S.expr) (bs:list nat) (n:nat) :=\n    List2.map_iter (fun b n => (b+booker e n)%nat) bs n.\n\n  Fixpoint trans (e:S.expr) (bs:list nat) (dg:dg_t) (dgs:list dg_t) : T.expr * Context.t_stack :=\n    match e with\n    | EConst i => (M.ret dg (M.cast_econst dg i), Context.empty)\n    | EVar y => (M.ret dg (M.cast_evar dg (M.cast_var (source_var y))), Context.empty)\n    | EAbs y e => \n        let (e,cs) := trans e bs (dg_eabs dg y) dgs in\n        (M.ret dg (M.cast_eabs dg (M.cast_var (source_var y)) e), cs)\n    | EFix f y e => \n        let (e,cs) := trans e bs (dg_efix dg f y) dgs in\n        (M.ret dg (M.cast_efix dg\n            (M.cast_var (source_var f)) \n            (M.cast_var (source_var y)) e), cs)\n    | EApp e1 e2 => \n        let bs2 := map_iter_booker e2 bs 0 in\n        let (e1', cs1) := trans e1 bs2 (dg_eapp_l dg) dgs in\n        let (e2', cs2) := trans e2 bs (dg_eapp_r dg) dgs in\n          (if svalueb 0 e1 then\n\t   M.bind dg e2' (fun v2 => M.cast_eapp dg \n             (phi e1 bs2 (dg_eapp_l dg) dgs) v2)\n\t   else M.bind dg e1' (fun v1 => M.bind dg e2'\n          (fun v2 => M.cast_eapp dg v1 v2)), \n          Context.merge cs1 cs2)\n    | ELoc l => (M.ret dg (M.cast_eloc dg l), Context.empty)\n    | ERef e => \n        let (e,cs) := trans e bs (dg_eref dg) dgs in\n        (M.bind dg e (fun v => M.cast_eref dg v), cs)\n    | EDeref e => \n        let (e,cs) := trans e bs (dg_ederef dg) dgs in\n        (M.bind dg e (fun v => M.cast_ederef dg v), cs)\n    | EAssign e1 e2 => \n\tlet bs2 := map_iter_booker e2 bs 0 in\n        let (e1', cs1) := trans e1 bs2 (dg_eassign_l dg) dgs in\n        let (e2', cs2) := trans e2 bs (dg_eassign_r dg) dgs in\n          (if svalueb 0 e1 then\n\t   M.bind dg e2' (fun v2 => M.cast_eassign dg \n             (phi e1 bs2 (dg_eassign_l dg) dgs) v2)\n\t   else M.bind dg e1' (fun v1 => M.bind dg e2'\n          (fun v2 => M.cast_eassign dg v1 v2)), \n          Context.merge cs1 cs2)\n    | EBox e => \n        let (e, cs) := trans e (0 :: bs) (dg_ebox dg) (dg::dgs) in\n        match cs with\n        | nil => (M.ret dg (M.cast_ebox dg e), Context.empty)\n        | c :: cs => (Context.fill dg c (M.ret dg (M.cast_ebox dg e)), cs)\n        end\n    | EUnbox e =>\n        let (b, bs) := List2.hd_cons bs 0 in\n        let (dg', dgs') := List2.hd_cons dgs dg_empty in\n        let (e', cs) := trans e bs dg' dgs' in\n           (M.cast_eunbox dg (M.cast_evar dg \n\t   (M.cast_var (hole_var b))), ((e', b) :: nil) :: cs)\n    | ERun e =>\n        let (e,cs) := trans e bs (dg_erun dg) dgs in\n        (M.bind dg e (fun v => M.cast_erun dg v), cs)\n    | ELift e =>\n        let (e,cs) := trans e bs (dg_elift dg) dgs in\n        (M.bind dg e (fun v => M.cast_elift dg v), cs)\n    end\n\n  with phi (e:S.expr) (bs:list nat) (dg:dg_t) (dgs:list dg_t) : T.expr :=\n    match e with\n    | EConst i => M.cast_econst dg i\n    | EVar y => M.cast_evar dg (M.cast_var (source_var y))\n    | EAbs y e => \n        let (e, _) := trans e bs (dg_eabs dg y) dgs in\n        M.cast_eabs dg (M.cast_var (source_var y)) e\n    | EFix f y e => \n        let (e, _) := trans e bs (dg_efix dg f y) dgs in\n        M.cast_efix dg\n            (M.cast_var (source_var f)) \n            (M.cast_var (source_var y)) e\n    | ELoc l => M.cast_eloc dg l\n    | EBox e => \n        let (e, _) := trans e (0 :: bs) (dg_ebox dg) (dg::dgs) in\n        M.cast_ebox dg e\n    | _ => M.cast_econst dg 0\n    end.\n\n  Definition trans_expr (e:S.expr) (bs:list nat) (dg:dg_t) (dgs:list dg_t) : T.expr :=\n    let (e, _) := trans e bs dg dgs in e.\n\n  Fixpoint trans_mem (m:S.Memory.t) (bs:list nat) (dg:dg_t) (dgs:list dg_t) : T.Memory.t :=\n    match m with\n    | nil => nil\n    | e :: m => (phi e bs dg dgs) :: (trans_mem m bs dg dgs)\n    end.\n\n  (** ** Administrative Reduction Step *)\n  Inductive admin : relation T.expr :=\n    | Admin_refl : forall (e:T.expr), admin e e\n    | Admin_trans : forall (e1 e2 e3:T.expr), \n        admin e1 e2 -> admin e2 e3 -> admin e1 e3\n    | Admin_abs : forall (x:T.var) (e1 e2:T.expr) (dg:dg_t),\n        admin e1 e2 -> admin (M.cast_eabs dg x e1) (M.cast_eabs dg x e2)\n    | Admin_fix : forall (f x:T.var) (e1 e2:T.expr) (dg:dg_t),\n        admin e1 e2 -> admin (M.cast_efix dg f x e1) (M.cast_efix dg f x e2)\n    | Admin_app : forall (e1 e2 e3 e4:T.expr) (dg:dg_t),\n        admin e1 e3 -> admin e2 e4 -> \n        admin (M.cast_eapp dg e1 e2) (M.cast_eapp dg e3 e4)\n    | Admin_ref : forall (e1 e2:T.expr) (dg:dg_t),\n        admin e1 e2 -> admin (M.cast_eref dg e1) (M.cast_eref dg e2)\n    | Admin_deref : forall (e1 e2:T.expr) (dg:dg_t),\n        admin e1 e2 -> admin (M.cast_ederef dg e1) (M.cast_ederef dg e2)\n    | Admin_assign : forall (e1 e2 e3 e4:T.expr) (dg:dg_t),\n        admin e1 e3 -> admin e2 e4 -> \n        admin (M.cast_eassign dg e1 e2) (M.cast_eassign dg e3 e4)\n    | Admin_box : forall (e1 e2:T.expr) (dg:dg_t),\n        admin e1 e2 -> admin (M.cast_ebox dg e1) (M.cast_ebox dg e2)\n    | Admin_unbox : forall (e1 e2:T.expr) (dg:dg_t),\n        admin e1 e2 -> admin (M.cast_eunbox dg e1) (M.cast_eunbox dg e2)\n    | Admin_run : forall (e1 e2:T.expr) (dg:dg_t),\n        admin e1 e2 -> admin (M.cast_erun dg e1) (M.cast_erun dg e2)\n    | Admin_lift : forall (e1 e2:T.expr) (dg:dg_t),\n        admin e1 e2 -> admin (M.cast_elift dg e1) (M.cast_elift dg e2)\n    | Admin_ret : forall (e1 e2:T.expr) (dg:dg_t),\n        admin e1 e2 -> admin (M.ret dg e1) (M.ret dg e2)\n    | Admin_bind : forall (e1 e2:T.expr) (f1 f2:T.expr -> T.expr) (dg:dg_t),\n        admin e1 e2 -> (forall e3:T.expr, admin (f1 e3) (f2 e3)) ->\n        admin (M.bind dg e1 f1) (M.bind dg e2 f2)\n   | Admin_unbox_box : forall (e:expr) (*(bs:list nat)*) (dg:dg_t) (dgs:list dg_t),\n        svalue 1 e ->\n        DGValid.valid_dgs 1 dg (dg_empty :: dgs) ->\n        admin (M.cast_eunbox dg (M.cast_ebox dg_empty\n          (trans_expr e (0::nil) dg (dg_empty :: dgs)))) \n          (trans_expr e (0::nil) dg (dg_empty :: dgs))\n   | Admin_bind_app_phi : forall (v:expr) (e:T.expr) (bs:list nat) (dg:dg_t) (dgs:list dg_t), \n       svalue 0 v -> \n       let f := fun v0 => M.bind dg e (fun v1 => M.cast_eapp dg v0 v1) in\n       admin (M.bind dg (M.ret (dg_eapp_l dg) (phi v bs (dg_eapp_l dg) dgs)) f) (f (phi v bs (dg_eapp_l dg) dgs))\n  | Admin_bind_assign_phi : forall (v:expr) (e:T.expr) (bs:list nat) (dg:dg_t) (dgs:list dg_t), \n       svalue 0 v ->\n       let f := fun v0 => M.bind dg e (fun v1 => M.cast_eassign dg v0 v1) in\n       admin (M.bind dg (M.ret (dg_eassign_l dg) (phi v bs (dg_eassign_l dg) dgs)) f) (f (phi v bs (dg_eassign_l dg) dgs)).\n\n  Definition admin_context :  relation Context.t := \n    Context.congr_context admin.\n  Definition admin_stack : relation Context.t_stack := \n    Context.congr_stack admin.\n\n  (** ** Relative Abstract Reduction Step *)\n  Inductive rstep : relation T.state :=\n    | Rel_step : forall (s:T.state) (e1 e2:T.expr) (M:T.Memory.t),\n        M.astep s (M,e1) -> admin e1 e2 -> rstep s (M,e2).\n\nEnd Translation.\n\nModule TranslationImpl (R:Replacement) \n   (S:ReplacementCalculus R) (T:StagedCalculus) \n   (DG:DataGathering R S) (DGP:DataGatheringPredicates R S DG)  \n   (DGR:DataGatheringRequirements R S DG DGP) \n   (M:Monad R S T DG) <: Translation R S T DG DGP DGR M.\n  Include Translation R S T DG DGP DGR M.\nEnd TranslationImpl.\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/Translation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.27656764774341125}}
{"text": "(** Strong normalization of the model of CC+NAT in the type-based\n    termination presentation.\n\n    This is a copy of SN_W, but in a simpler case.\n*)\nRequire Import basic Models.\nRequire SN_ECC_Real.\nImport ZFgrothendieck.\nImport ZF ZFsum ZFnats ZFrelations ZFord ZFfix.\nRequire Import ZFfunext ZFfixrec ZFcoc ZFecc SATtypes SATnat_real.\n\nImport ZFuniv_real SN_ECC_Real.\nOpaque Real.\nImport Sat Sat.SatSet.\n\n(** Ordinals *)\n\nRequire Import SN_ord.\n\nDefinition infty := cst omega.\n\nLemma typ_infty : forall e, typ_ord e infty.\nsplit; simpl; auto.\nexact Lc.sn_K.\nQed.\n\nHint Resolve typ_infty.\n\n(** Judgments with variance *)\n\nRequire Import SN_variance.\n\n(*Definition push e T o dom :=\n  Build_fenv (T::tenv e) (B.cons o (ords e)) (OT.cons dom (fixs e)).\nLemma val_mono_shift1 e i j i' j' T  o dom :\n  val_mono (push e T o dom) i j i' j' ->\n  val_mono e (V.shift 1 i) (I.shift 1 j) (V.shift 1 i') (I.shift 1 j').\nAdmitted.*)\n(*Lemma typ_impl_varS e n T o dom U U' :\n  typ_impl e (Ref n) U ->\n  eq_term (lift 1 U) U' ->\n  typ_impl (push e T o dom) (Ref (S n)) U'.\nAdmitted.*)\n\n\nModule Make (M:SizedNats).\n\n  Module SATN := SATnat_real.Make M.\n  Import SATN.\n\n(** NAT *)\n\nSection NAT_typing.\n\nDefinition NatI (O:term) : term.\n(*begin show*)\nleft; exists (fun i => mkTY (TI NATf' (int O i)) cNAT)\n             (fun j => tm O j).\n(*end show*)\n do 2 red; intros.\n apply mkTY_ext; intros.\n  apply TI_morph_gen; auto with *.\n\n  apply Fmono_morph; auto with *.\n\n   apply int_morph; auto with *.\n\n  apply cNAT_morph; trivial.\n (**)\n do 2 red; intros.\n rewrite H; reflexivity.\n (**)\n red; intros.\n rewrite <- tm_liftable.\n reflexivity.\n (**)\n red; intros.\n rewrite <- tm_substitutive.\n reflexivity.\nDefined.\n\nGlobal Instance NatI_morph : Proper (eq_term==>eq_term) NatI.\ndo 2 red; intros.\napply eq_term_intro; simpl; trivial; intros.\n apply mkTY_ext.\n  rewrite H; reflexivity.\n\n  intros.\n  apply cNAT_morph; trivial.\n\n rewrite H; reflexivity.\nQed.\nLemma eq_sb_NatI A k O :\n     eq_term (subst_rec A k (NatI O)) (NatI (subst_rec A k O)).\napply eq_term_intro; simpl; trivial.\n intros; apply mkTY_ext; intros.\n  rewrite int_subst_rec_eq; reflexivity.\n\n  apply cNAT_morph; trivial.\n\n intros.\n rewrite tm_subst_rec_eq; trivial.\nQed.\nLemma eq_lft_NatI n k O :\n     eq_term (lift_rec n k (NatI O)) (NatI (lift_rec n k O)).\napply eq_term_intro; simpl; trivial.\n intros; apply mkTY_ext; intros.\n  rewrite int_lift_rec_eq; reflexivity.\n\n  apply cNAT_morph; trivial.\n\n intros.\n rewrite tm_lift_rec_eq; trivial.\nQed.\n\nLemma El_int_NatI O i :\n  El (int (NatI O) i) == cc_bot (TI NATf' (int O i)).\nsimpl.\nrewrite El_def; reflexivity.\nQed.\nLemma Real_int_NatI O i x :\n  x ∈ cc_bot (TI NATf' (int O i)) ->\n  eqSAT (Real (int (NatI O) i) x) (cNAT x).\nsimpl; intros.\nrewrite Real_def; auto with *.\nintros.\nrewrite H1; reflexivity.\nQed.\n\nLemma typ_NatI e O :\n  typ_ord e O ->\n  typ e (NatI O) kind.\nintros tyO i j valok; simpl.\nred in tyO; specialize tyO with (1:=valok).\nsplit;[|split].\n discriminate.\n\n exists nil; exists (NatI O);[reflexivity|].\n exists empty; simpl; auto.\n(* red; auto.*)\n\n simpl.\n apply tyO.\nQed.\n\nLemma typ_NatI_type e n O :\n  typ_ord e O ->\n  typ e (NatI O) (type n).\nintros tyO i j is_val; simpl.\nred in tyO; specialize tyO with (1:=is_val).\ndestruct tyO as (o_o,osn).\napply in_int_intro;[discriminate|discriminate|].\napply and_split; intros.\n red; change (int (type n) i) with (sn_sort (ecc (S n))).\n simpl int.\n apply sn_sort_intro.\n  intros.\n  apply cNAT_morph; auto with *.\n\n  apply G_incl with NAT'; trivial.\n   apply G_TI; auto with *.\n    intros.\n    apply G_NATf'; auto.\n\n    apply TI_pre_fix; auto with *.\n    unfold NAT'; rewrite <- NAT_eqn; reflexivity.\n\n red in H.\n change (int (type n) i) with (sn_sort (ecc (S n))).\n rewrite Real_sort_sn; trivial.\nQed.\n\nLemma NatI_sub_infty e O :\n  typ_ord e O ->\n  sub_typ e (NatI O) (NatI infty).\nred; intros.\ndestruct H with (1:=H0).\ndestruct H1.\nred in H1; simpl in H1; rewrite El_def in H1.\napply and_split.\n red; simpl; rewrite El_def.\n revert H1; apply cc_bot_mono.\n apply TI_pre_fix; auto with *.\n rewrite <- NAT_eqn; auto with *.\n\n simpl in *; intros.\n red in H5; rewrite El_def in H5.\n rewrite Real_def in H4|-*; trivial.\n  intros; apply cNAT_morph; trivial.\n  intros; apply cNAT_morph; trivial.\nQed.\n\nLemma NatI_sub_osucc e O :\n  typ_ord e O ->\n  sub_typ e (NatI O) (NatI (OSucc O)).\nred; intros.\ndestruct H with (1:=H0).\ndestruct H1.\nred in H1; simpl in H1; rewrite El_def in H1.\napply and_split.\n red; simpl; rewrite El_def.\n revert H1; apply cc_bot_mono.\n apply TI_mono; auto with *.\n red; intros; apply isOrd_trans with (int O i); auto with *.\n\n simpl in *; intros.\n red in H5; rewrite El_def in H5.\n rewrite Real_def in H4|-*; trivial.\n  intros; apply cNAT_morph; trivial.\n  intros; apply cNAT_morph; trivial.\nQed.\n\n  Lemma NatI_sub e O :\n    typ_ord (tenv e) O ->\n    fx_subval e O ->\n    fx_sub e (NatI O).\nunfold fx_sub, fx_subval.\nintros tyO subO i i' j j' val_m x t (xreal,xsat).\ndestruct tyO with (1:=proj1 val_m).\ndestruct tyO with (1:=proj1 (proj2 val_m)).\nspecialize subO with (1:=val_m).\nred in xreal; simpl in xreal; rewrite El_def in xreal.\nrewrite Real_int_NatI in xsat; trivial.\nassert (cc_bot (TI NATf' (int O i)) ⊆ cc_bot (TI NATf' (int O i'))).\n apply cc_bot_mono.\n apply TI_mono; auto with *.\nsplit.\n red; simpl; rewrite El_def; auto with *.\n\n rewrite Real_int_NatI; auto.\nQed.\n\n\n(** Constructors *)\n\nDefinition Zero : term.\n(* begin show *)\nleft; exists (fun i => M.zero)\n             (fun j => ZE).\n(* end show *)\n do 2 red; intros; reflexivity.\n (**)\n do 2 red; intros; reflexivity.\n (**)\n red; intros.\n reflexivity.\n (**)\n red; intros.\n reflexivity.\nDefined.\n\n\nLemma typ_0 e O :\n  typ_ord e O ->\n  typ e Zero (NatI (OSucc O)).\nred; intros.\napply in_int_intro; try discriminate.\nred in H; specialize H with (1:=H0); destruct H as (oo,osn).\nassert (M.zero ∈ TI NATf' (osucc (int O i))).\n apply TI_intro with (int O i); auto with *.\n apply M.zero_typ. \nsplit.\n red; rewrite El_int_NatI; auto.\n\n rewrite Real_int_NatI; auto.\n simpl.\n rewrite cNAT_eq.\n  apply Real_ZERO_gen.\n\n  unfold NAT'; rewrite NAT_eqn; apply zero_typ.\nQed.\n\nDefinition Succ (O:term) : term.\n(* begin show *)\nleft; exists (fun i => lam (mkTY (TI NATf' (int O i)) cNAT) succ)\n             (fun j => Lc.App2 Lc.K (Lc.Abs (SU (Lc.Ref 0))) (tm O j)).\n(* end show *)\n do 2 red; intros; apply cc_lam_morph; auto with *.\n  rewrite !El_def.\n  rewrite H; reflexivity.\n  apply succ_morph.\n (**)\n do 2 red; intros.\n rewrite H; reflexivity.\n (**)\n red; intros.\n simpl.\n rewrite <- tm_liftable.\n reflexivity.\n (**)\n red; intros.\n simpl.\n rewrite <- tm_substitutive.\n reflexivity.\nDefined.\n\n\nLemma typ_S e O :\n  typ_ord e O ->\n  typ e (Succ O) (Prod (NatI O) (lift 1 (NatI (OSucc O)))).\nred; intros tyO i j valok.\nred in tyO; specialize tyO with (1:=valok); destruct tyO as (oo,snO).\napply in_int_intro; try discriminate.\nassert (lam (mkTY (TI NATf' (int O i)) cNAT) succ ∈\n        cc_arr (cc_bot (TI NATf' (int O i))) (cc_bot (TI NATf' (osucc (int O i))))).\n eapply in_reg.\n 2:apply cc_arr_intro.\n  apply cc_lam_ext.\n   rewrite El_def; reflexivity.\n\n   do 2 red; intros; apply succ_morph.\n   exact H0.\n\n  do 2 red; intros; apply succ_morph; trivial.\n\n  intros.\n  apply cc_bot_intro.\n  apply TI_intro with (int O i); auto with *.\n  apply succ_typ; trivial.\napply and_split.\n red; simpl.\n rewrite El_prod.\n revert H; apply in_set_morph; auto with *.\n apply cc_prod_ext.\n  rewrite El_def; reflexivity.\n\n  red; intros.\n  rewrite El_def.\n  rewrite V.lams0.\n  reflexivity.\n do 2 red; intros.\n apply mkTY_ext; intros.\n  rewrite !V.lams0; reflexivity.\n  apply cNAT_morph; trivial.\n\n intros tyS.\n simpl.\n rewrite Real_prod; trivial.\n 2:do 2 red; intros; apply mkTY_ext; [\n  rewrite !V.lams0; reflexivity |\n  intros; apply cNAT_morph; trivial].\n apply piSAT0_intro'.\n 2:exists empty; auto.\n intros.\n rewrite El_def in H0.\n eapply inSAT_context.\n  intros.\n  apply KSAT_intro; trivial.\n  exact H2.\n rewrite Real_def in H1; trivial.\n 2:intros; apply cNAT_morph; trivial.\n assert (cc_app (lam (mkTY (TI NATf' (int O i)) cNAT) succ) x == succ x).\n  apply beta_eq.\n   do 2 red; intros; apply succ_morph; trivial.\n   red; rewrite El_def; trivial.\n rewrite H2.\n rewrite Real_def.\n 2:intros; apply cNAT_morph; trivial.\n\n apply inSAT_exp.\n  apply sat_sn in H1; auto.\n unfold Lc.subst; simpl.\n apply Real_SUCC_cNAT; trivial.\n revert H0; apply cc_bot_mono.\n apply TI_pre_fix; auto with *.\n unfold NAT'; rewrite <- NAT_eqn; reflexivity.\n\n apply cc_bot_intro.\n rewrite V.lams0.\n apply TI_intro with (int O i); auto with *.\n apply succ_typ; trivial.\nQed.\n\nLemma ext_S e O :\n  typ_ord (tenv e) O ->\n  fx_subval e O ->\n  fx_extends e (NatI O) (Succ O).\nred; red; simpl; intros.\nrewrite beta_eq; trivial.\n2:red; intros; apply succ_morph; trivial.\nrewrite beta_eq; auto with *.\n red; intros; apply succ_morph; trivial.\nred; rewrite El_def in H2|-*.\nrevert H2; apply cc_bot_mono.\ndestruct H with (1:=proj1 H1) as (?,_).\ndestruct H with (1:=proj1 (proj2 H1)) as (?,_).\napply TI_mono; auto.\napply H0 with (1:=H1).\nQed.\n\n(* Case analysis *)\n\nDefinition NatCase (b0 bS n : term) : term.\n(*begin show*)\nleft; exists (fun i => natcase (int b0 i) (fun x => int bS (V.cons x i)) (int n i))\n             (fun j => NCASE (tm b0 j) (Lc.Abs (tm bS (Lc.ilift j))) (tm n j)).\n(*end show*)\ndo 2 red; intros.\napply natcase_morph.\n rewrite H; reflexivity.\n\n red; intros.\n rewrite H,H0; reflexivity.\n\n rewrite H; reflexivity.\n(**)\ndo 2 red; intros.\nrewrite H; reflexivity.\n(**)\nunfold NCASE; red; intros; simpl.\napply f_equal3 with (f:=Lc.App2).\n rewrite <- (tm_liftable j n); reflexivity.\n\n rewrite (tm_liftable _ b0).\n rewrite Lc.permute_lift.\n reflexivity.\n\n rewrite <- (tm_liftable _ bS).\n rewrite !Lc.ilift_binder_lift.\n reflexivity.\n(**)\nunfold NCASE; red; intros; simpl.\napply f_equal3 with (f:=Lc.App2).\n rewrite <- (tm_substitutive _ n); reflexivity.\n\n rewrite (tm_substitutive _ b0).\n rewrite Lc.commut_lift_subst.\n reflexivity.\n\n rewrite <- (tm_substitutive _ bS).\n rewrite Lc.ilift_binder.\n reflexivity.\nDefined.\n\nInstance NatCase_morph :\n  Proper (eq_term ==> eq_term ==> eq_term ==> eq_term) NatCase.\nsplit; red; simpl; intros.\n apply natcase_morph.\n  apply int_morph; trivial.\n\n  red; intros.\n  apply int_morph; trivial.\n  apply V.cons_morph; trivial.\n\n  apply int_morph; trivial.\n\n rewrite H.\n rewrite H0.\n rewrite H1.\n rewrite H2.\n reflexivity.\nQed.\n\n\nLemma NatCase_iota_0 e B0 BS :\n  eq_typ e (NatCase B0 BS Zero) B0.\nred; intros.\nsimpl.\nrewrite natcase_zero; reflexivity.\nQed.\n\n\nLemma NatCase_iota_S e B0 BS O N :\n  typ e N (NatI O) ->\n  eq_typ e (NatCase B0 BS (App (Succ O) N)) (subst N BS).\nred; intros.\nsimpl.\nred.\nassert (BSm : morph1 (fun x => int BS (V.cons x i))).\n do 2 red; intros.\n rewrite H1; reflexivity.\neapply transitivity.\n apply natcase_morph.\n  reflexivity.\n\n  intros ? ? h.\n  apply int_morph;[reflexivity|].\n  apply V.cons_morph;[exact h|reflexivity].\n\n  apply beta_eq.\n   do 2 red; intros; apply succ_morph; trivial.\n  apply H in H0.\n  apply in_int_not_kind in H0.\n  2:discriminate.\n  destruct H0; trivial.\nrewrite natcase_succ; trivial.\napply int_subst_eq.\nQed.\n\nLemma typ_NatCase e P O B0 BS n :\n  typ_ord e O ->\n  typ e B0 (App P Zero) ->\n  typ (NatI O::e) BS (App (lift 1 P) (App (lift 1 (Succ O)) (Ref 0))) ->\n  typ e n (NatI (OSucc O)) ->\n  typ e (NatCase B0 BS n) (App P n).\nred; intros tyO tyB0 tyBS tyn i j valok.\nred in tyO; specialize tyO with (1:=valok); destruct tyO as (oo,osn).\nred in tyB0; specialize tyB0 with (1:=valok).\napply in_int_not_kind in tyB0;[|discriminate].\ndestruct tyB0 as (tyB0,satB0); red in tyB0.\nred in tyn; specialize tyn with (1:=valok).\napply in_int_not_kind in tyn;[|discriminate].\ndestruct tyn as (tyN,satN); red in tyN.\nassert (BSm : morph1 (fun x => int BS (V.cons x i))).\n do 2 red; intros.\n rewrite H; reflexivity.\nassert (ok' : forall x u, x ∈ cc_bot (TI NATf' (int O i)) -> inSAT u (cNAT x) ->\n  val_ok (NatI O::e) (V.cons x i) (I.cons u j)).\n intros.\n apply vcons_add_var; auto.\n 2:discriminate.\n split.\n  red; rewrite El_int_NatI; trivial.\n  rewrite Real_int_NatI; trivial.\napply in_int_intro; try discriminate.\nrewrite El_int_NatI in tyN.\nrewrite Real_int_NatI in satN; trivial.\napply and_split; intros.\n red; simpl.\n apply neutr_dec' in tyN; simpl; auto with *.\n destruct tyN.\n  (* constructor case *)\n  simpl in H; rewrite TI_mono_succ in H; auto with *.\n  apply NATf'_elim in H; destruct H.\n   rewrite H.\n   rewrite natcase_zero.\n   trivial.\n\n   destruct H.\n   rewrite H0.\n   rewrite natcase_succ; auto with *.\n   specialize ok' with (1:=H) (2:=varSAT _).\n   red in tyBS; specialize tyBS with (1:=ok').\n   apply in_int_not_kind in tyBS;[|discriminate].\n   destruct tyBS as (tyBS,_).    \n   revert tyBS; apply eq_elim.\n   apply El_morph.\n   apply cc_app_morph.\n    rewrite int_lift_eq; reflexivity.\n   simpl.\n   apply beta_eq.\n    do 2 red; intros; apply succ_morph; trivial.\n\n    red; rewrite El_def; trivial.\n    rewrite V.lams0.\n    trivial.\n\n  (* neutral case *)\n  apply in_reg with empty; auto.\n  symmetry; apply natcase_outside.\n  red; intros.\n  apply H; exists X0; trivial.\n\n (* Reducibility *)\n simpl in H|-*.\n apply neutr_dec' in tyN; simpl; auto with *.\n destruct tyN.\n  (* regular case *)\n  apply Real_NATCASE with (o:=int O i)(C:=fun k =>Real (app (int P i) k)\n    (natcase (int B0 i) (fun x => int BS (V.cons x i)) k)); auto.\n   do 2 red; intros.\n   apply Real_morph.\n    rewrite H1; reflexivity.\n\n    apply natcase_morph; auto with *.\n\n   rewrite fNATi_stages; auto with *.\n\n   rewrite natcase_zero.\n   trivial.\n\n   apply piSAT0_intro'.\n   2:exists empty; auto.\n   intros.\n   apply inSAT_exp.\n    apply sat_sn in H2; auto.\n   rewrite <- tm_subst_cons.\n   rewrite fNATi_stages in H2; auto.\n   specialize ok' with (1:=H1) (2:=H2).\n   red in tyBS; specialize tyBS with (1:=ok').\n   apply in_int_not_kind in tyBS;[|discriminate].\n   destruct tyBS as (tyBS,satBS).\n   revert satBS; apply inSAT_morph; auto with *.\n   apply Real_morph.\n    simpl.\n    rewrite int_lift_eq.\n    apply cc_app_morph; [reflexivity|].\n    rewrite beta_eq; auto with *.\n     red; intros; apply succ_morph; trivial.\n\n     red; rewrite El_def.     \n     rewrite V.lams0.\n     trivial.\n\n    rewrite natcase_succ; auto with *.\n\n  (* neutral case *)\n(*  rewrite H0 in satN.*)\n  eapply prodSAT_elim.\n   eapply prodSAT_elim.\n    apply neuSAT_def.\n    rewrite fNATi_neutral' with (o:=omega) in satN; trivial.\n\n    apply prodSAT_intro with (A:=snSAT).\n    intros.\n    unfold Lc.subst; rewrite Lc.simpl_subst, Lc.lift0; auto with arith.\n    apply satB0.\n\n   apply prodSAT_intro.\n   intros.\n   unfold Lc.subst; simpl.\n   fold (Lc.subst v (tm BS (Lc.ilift j))).\n   rewrite <- tm_subst_cons.\n   assert (ty_mt : empty ∈ cc_bot (TI NATf' (int O i))) by auto.\n   specialize ok' with (1:=ty_mt) (2:=H1).\n   red in tyBS; specialize tyBS with (1:=ok').\n   apply in_int_not_kind in tyBS;[|discriminate].\n   destruct tyBS as (_,satBS).\n   exact satBS.\nQed.\n\nLemma typ_NatCase' e P O B0 BS n T :\n  T <> kind ->\n  typ_ord e O ->\n  sub_typ e (App P n) T ->\n  typ e B0 (App P Zero) ->\n  typ (NatI O::e) BS (App (lift 1 P) (App (lift 1 (Succ O)) (Ref 0))) ->\n  typ e n (NatI (OSucc O)) ->\n  typ e (NatCase B0 BS n) T.\nintros.\napply typ_subsumption with (App P n); auto.\n2:discriminate.\napply typ_NatCase with O; trivial.\nQed.\n\nLemma impl_NatCase e O b0 bS n P :\n  typ_ord_mono e O ->\n  typ_impl e b0 (App P Zero) ->\n  typ_impl (push_var e (NatI O)) bS (App (lift 1 P) (App (lift 1 (Succ O)) (Ref 0))) ->\n  typ_impl e n (NatI (OSucc O)) ->\n  typ_impl e (NatCase b0 bS n) (App P n).\nintros.\nsplit.\n red; simpl; intros.\n apply natcase_ext with (o:=int O i); auto with *.\n  do 2 red; intros.\n  rewrite H4; reflexivity.\n\n  do 2 red; intros.\n  rewrite H4; reflexivity.\n\n  apply H with (1:=proj1 H3).\n\n  destruct H2.\n  assert (aux := H4 _ _ (proj1 H3)).\n  apply in_int_not_kind in aux;[|discriminate].\n  destruct aux.\n  simpl in H5; red in H5; rewrite El_def in H5; trivial.\n\n  apply (proj1 H2 _ _ _ _ H3).\n\n  apply (proj1 H0 _ _ _ _ H3).\n\n  red; intros.\n  destruct H1.\n  apply H1 with (I.cons daimon j) (I.cons daimon j').\n  apply val_push_var; trivial.\n   split;[|apply varSAT].\n   red; simpl; rewrite El_def; trivial.\n\n   split;[|apply varSAT].\n   red; simpl; rewrite El_def; trivial.\n   rewrite <- H5; revert H4; apply cc_bot_mono.\n   destruct H.\n   apply TI_mono; auto with *.\n    apply H4 with (1:=proj1 (proj2 H3)).\n    apply H4 with (1:=proj1 H3).\n    apply H with (1:=H3).\n\n   discriminate.\n\n eapply typ_NatCase with (1:=proj2 H).\n  apply H0.\n  apply H1.\n  apply H2.\nQed.\n\nLemma impl_NatCase' e O0 b0 bS n P :\n   P <> kind ->\n   typ_ord_mono e O0 ->\n       typ_impl e b0 (subst Zero P) ->\n       typ_impl (push_var e (NatI O0)) bS\n         (subst (App (lift 1 (Succ O0)) (Ref 0)) (lift1 1 P)) ->\n       typ_impl e n (NatI (OSucc O0)) ->\n       typ_impl e (NatCase b0 bS n) (subst n P).\nintros Pnk tyO tyb0 tybS tyn.\napply typ_impl_subsumption with (App (Abs (NatI (OSucc O0)) P) n).\n3:discriminate.\n3:destruct P;[discriminate|elim Pnk; trivial].\n \n apply impl_NatCase with (O0:=O0); trivial.\n  apply typ_impl_subsumption with (subst Zero P); trivial.\n  2:destruct P;[discriminate|elim Pnk; trivial].\n  2:discriminate.\n  apply sub_refl.\n  symmetry; apply eq_typ_betar.\n  2:discriminate.\n  apply typ_0.\n  apply tyO.\n\n  apply typ_impl_subsumption with\n    (subst (App (lift 1 (Succ O0)) (Ref 0)) (lift1 1 P)); trivial.\n  2:destruct P;[discriminate|elim Pnk; trivial].\n  2:discriminate.\n  unfold lift at 2.\n  rewrite red_lift_abs.\n  apply sub_refl.\n  symmetry; apply eq_typ_betar.\n  2:discriminate.\n  apply typ_subsumption with (subst (Ref 0)(lift 1 (lift 1 (NatI (OSucc O0))))).\n  3:discriminate.\n  3:discriminate.\n   apply typ_app with (lift 1 (NatI O0)).\n   3:discriminate.\n   3:discriminate.\n    apply typ_var.\n    reflexivity.\n\n    eapply typ_subsumption.\n    apply weakening.\n    apply typ_S.\n    apply tyO.\n    2:discriminate.\n    2:discriminate.\n    apply sub_refl; apply eq_term_eq_typ.\n    unfold lift; rewrite red_lift_prod.\n    apply Prod_morph; auto with *.\n    apply eq_term_intro; [| |simpl; trivial].\n     intros; rewrite !int_lift_rec_eq.\n     apply int_morph; auto with *.\n     intros [|k]; reflexivity.\n\n     intros; rewrite !tm_lift_rec_eq.\n     apply tm_morph; auto with *.\n     intros [|k]; reflexivity.\n\napply sub_refl; apply eq_term_eq_typ.\nfold (lift 1 (NatI (OSucc O0))).\napply eq_term_intro.\n intros i.\n rewrite <- int_subst_eq.\n rewrite !int_lift_eq.\n apply int_morph; auto with *.\n reflexivity.\n\n intros j.\n unfold subst; rewrite tm_subst_rec_eq.\n unfold lift; rewrite !tm_lift_rec_eq. \n apply tm_morph; auto with *.\n rewrite !I.lams0.\n reflexivity.\n\n exact I.\n\n apply sub_refl.\n apply eq_typ_betar; trivial.\n apply tyn.\n discriminate.\nQed.\n\nEnd NAT_typing.\n\n(*****************************************************************************)\n(** Recursor (without case analysis) *)\n\n(* NatFix O M is a fixpoint of domain NatI O with body M *)\nDefinition NatFix (O M:term) : term.\n(*begin show*)\nleft.\nexists (fun i =>\n         natfix (fun o' f => int M (V.cons f (V.cons o' i))) (int O i))\n       (fun j => NATFIX (Lc.Abs (tm M (Lc.ilift (I.cons (tm O j) j))))).\n(*end show*)\n do 2 red; intros.\n apply natfix_morph.\n  do 2 red; intros.\n  apply int_morph; auto with *.\n  apply V.cons_morph; trivial.\n  apply V.cons_morph; trivial.\n\n  apply int_morph; auto with *.\n\n (* *)\n do 2 red; intros.\n rewrite H; reflexivity.\n\n (* *)\n red; intros.\n replace (Lc.lift_rec 1\n     (NATFIX (Lc.Abs (tm M (Lc.ilift (I.cons (tm O j) j))))) k) with\n   (NATFIX (Lc.lift_rec 1 (Lc.Abs (tm M (Lc.ilift (I.cons (tm O j) j)))) k)).\n  simpl.\n  f_equal.\n  f_equal.\n  rewrite <- tm_liftable.\n  apply tm_morph; auto with *.\n  rewrite <- Lc.ilift_binder_lift.\n  apply Lc.ilift_morph.\n  intros [|k']; simpl; trivial.\n  apply tm_liftable.\n\n  generalize  (Lc.Abs (tm M (Lc.ilift (I.cons (tm O j) j)))); intro.\n  unfold NATFIX, FIXP; simpl.\n  rewrite <- Lc.permute_lift.\n  reflexivity.\n\n (* *)\n red; intros.\n replace (Lc.subst_rec u\n     (NATFIX (Lc.Abs (tm M (Lc.ilift (I.cons (tm O j) j))))) k) with\n   (NATFIX (Lc.subst_rec u (Lc.Abs (tm M (Lc.ilift (I.cons (tm O j) j)))) k)).\n  simpl.\n  f_equal.\n  f_equal.\n  rewrite <- tm_substitutive.\n  apply tm_morph; auto with *.\n  rewrite <- Lc.ilift_binder.\n  apply Lc.ilift_morph.\n  intros [|k']; simpl; trivial.\n  apply tm_substitutive.\n\n  generalize  (Lc.Abs (tm M (Lc.ilift (I.cons (tm O j) j)))); intro.\n  unfold NATFIX, FIXP; simpl.\n  rewrite <- Lc.commut_lift_subst.\n  reflexivity.\nDefined.\n\n\n(** Typing rules of NatFix *)\n\nSection NatFixRules.\n\n  Variable E : fenv.\n  Let e := tenv E.\n  Variable O U M : term.\n\n  Hypothesis ty_O : typ_ord e O.\n  Hypothesis ty_M : typ (Prod (NatI (Ref 0)) U::OSucct O::e)\n    M (Prod (NatI (OSucc (Ref 1)))\n         (lift_rec 1 1 (subst_rec (OSucc (Ref 0)) 1 (lift_rec 1 2 U)))).\n\n  Hypothesis stab : fx_extends\n    (push_fun (push_ord E (OSucct O)) (NatI (Ref 0)) U)\n    (NatI (OSucc (Ref 1)))\n    M.\n\n  Let Nati o := cc_bot (TI NATf' o).\n  Let F i := fun o' f => squash (int M (V.cons f (V.cons o' i))).\n  Let U' i := fun o' x => El (int U (V.cons x (V.cons o' i))).\n  Notation F' i := (fun o' f => int M (V.cons f (V.cons o' i))).\n\n  Local Instance U'morph : forall i, morph2 (U' i).\ndo 3 red; intros; unfold U'.\nrewrite H; rewrite H0; reflexivity.\nQed.\n  Instance morph_fix_body : forall i, morph2 (F i).\nunfold F; do 3 red; intros.\napply squash_morph.\nrewrite H; rewrite H0; reflexivity.\nQed.\n  Lemma ext_fun_ty : forall o i,\n    ext_fun (Nati o) (U' i o).\ndo 2 red; intros.\nrewrite H0;reflexivity.\nQed.\n  Hint Resolve U'morph morph_fix_body ext_fun_ty.\n\n\n  Hypothesis fx_sub_U :\n    fx_sub (push_var (push_ord E (OSucct O)) (NatI (OSucc (Ref 0)))) U.\n\n\n  Lemma val_mono_1 i i' j j' y y' f g:\n    val_mono E i j i' j' ->\n    isOrd (int O i) ->\n    isOrd (int O i') ->\n    int O i ⊆ int O i' ->\n    isOrd y ->\n    isOrd y' ->\n    y ⊆ int O i ->\n    y' ⊆ int O i' ->\n    y ⊆ y' ->\n    f ∈ cc_prod (Nati y) (U' i y) ->\n    g ∈ cc_prod (Nati y') (U' i' y') ->\n    fcompat (Nati y) f g ->\n    val_mono (push_fun (push_ord E (OSucct O)) (NatI (Ref 0)) U)\n      (V.cons f (V.cons y i)) (I.cons daimon (I.cons daimon j))\n      (V.cons g (V.cons y' i')) (I.cons daimon (I.cons daimon j')).\nintros is_val Oo Oo' oo' yo y'o yO y'O yy' fty gty eqfg.\napply val_push_fun.\n apply val_push_ord; auto.\n 3:discriminate.\n  split;[|apply varSAT].\n  red; rewrite El_int_osucc.\n  apply ole_lts; trivial.\n\n  split;[|apply varSAT].\n  red; rewrite El_int_osucc.\n  apply ole_lts; trivial.\n\n split;[|apply varSAT].\n red; rewrite El_int_prod.\n revert fty; apply eq_elim; apply cc_prod_ext; intros.\n  simpl; rewrite El_def; auto with *.\n  reflexivity.\n\n  apply ext_fun_ty.\n\n split;[|apply varSAT].\n red; rewrite El_int_prod.\n revert gty; apply eq_elim; apply cc_prod_ext; intros.\n  simpl; rewrite El_def; auto with *.\n  reflexivity.\n\n  apply ext_fun_ty.\n\n simpl; rewrite El_def; auto with *.\nQed.\n\n  Lemma val_mono_2 i j y y' n n':\n    val_ok e i j ->\n    isOrd (int O i) ->\n    isOrd y ->\n    isOrd y' ->\n    y ⊆ y' ->\n    y' ⊆ int O i ->\n    n ∈ Nati y ->\n    n == n' ->\n    val_mono (push_var (push_ord E (OSucct O)) (NatI (OSucc (Ref 0))))\n      (V.cons n (V.cons y i)) (I.cons daimon (I.cons daimon j))\n      (V.cons n' (V.cons y' i)) (I.cons daimon (I.cons daimon j)).\nProof.\nintros.\napply val_push_var; auto with *.\n 4:discriminate.\n apply val_push_ord; auto with *.\n  4:discriminate.\n  apply val_mono_refl; trivial.\n\n  split;[|apply varSAT].\n  red; rewrite El_int_osucc.\n  apply ole_lts; auto.\n  transitivity y'; trivial.\n\n  split;[|apply varSAT].\n  red; rewrite El_int_osucc.\n  apply ole_lts; auto.\n\n split;[|apply varSAT].\n red; simpl; rewrite El_def.\n revert H5; apply cc_bot_mono.\n apply TI_incl; simpl; auto.\n\n split;[|apply varSAT].\n red; simpl; rewrite El_def.\n rewrite <- H6.\n revert H5; apply cc_bot_mono.\n apply TI_incl; simpl; auto.\n apply ole_lts; trivial.\nQed.\n\n\nLet F2m : forall i T, morph2 (fun o' f => int T (V.cons f (V.cons o' i))).\ndo 3 red; intros.\napply int_morph; [reflexivity|].\nrepeat apply V.cons_morph; trivial.\nreflexivity.\nQed.\nLet U2m : forall i T, morph2 (fun o' f => El (int T (V.cons f (V.cons o' i)))).\ndo 3 red; intros.\napply El_morph; apply F2m; trivial.\nQed.\nSet Implicit Arguments.\n\nLet Unmt : forall i o x, empty ∈ U' i o x.\nunfold U'; auto.\nQed.\nLet Mty i j :\n isOrd (int O i) ->\n val_ok e i j ->\n forall o',\n isOrd o' ->\n o' ⊆ int O i ->\n forall f,\n f ∈ cc_prod (Nati o') (U' i o') ->\n int M (V.cons f (V.cons o' i)) ∈ cc_prod (Nati (osucc o')) (U' i (osucc o')).\nintros ordo ok o' oo' leo f tyf.\nassert (lto : o' ∈ osucc (int O i)).\n apply le_lt_trans with (int O i); auto.\n apply ole_lts; trivial.\nassert (ok': val_ok (Prod (NatI (Ref 0)) U :: OSucct O :: e)\n          (V.cons f (V.cons o' i)) (I.cons daimon (I.cons daimon j))).\n apply vcons_add_var_daimon; [| |discriminate].\n  apply vcons_add_var_daimon; [trivial| |discriminate].\n  red; simpl; rewrite El_def; auto.\n\n  red; rewrite El_int_prod.\n  revert tyf; apply eq_elim; apply cc_prod_ext.\n   simpl; rewrite El_def; reflexivity.\n\n   apply ext_fun_ty.\napply ty_M in ok'.\napply in_int_not_kind in ok'.\n2:discriminate.\ndestruct ok' as (ok',_).\nred in ok'; rewrite El_int_prod in ok'.\nrevert ok'; apply eq_elim; apply cc_prod_ext.\n simpl; rewrite El_def; reflexivity.\n\n red; intros.\n rewrite int_lift_rec_eq.\n rewrite int_subst_rec_eq.\n rewrite int_lift_rec_eq.\n apply El_morph; apply int_morph; auto with *.\n intros [|[|k]].\n  compute; trivial.\n  simpl; reflexivity.\n  compute; fold minus.\n  replace (k-0) with k; auto with *.\nQed.\n(*\nLet Mirr : forall i j,\n  val_ok e i j ->\n  NAT_ord_irrel' (int O i)\n     (fun o' f => int M (V.cons f (V.cons o' i))) \n     (U' i).\nred; intros.\ndestruct ty_O with (1:=H) as (Oo,_).\nassert (val_mono (push_fun (push_ord E (OSucct O)) (NatI (Ref 0)) U)\n         (V.cons f (V.cons o i)) (I.cons daimon (I.cons daimon j))\n         (V.cons g (V.cons o' i)) (I.cons daimon (I.cons daimon j))).\n apply val_mono_1; auto with *.\n  apply val_mono_refl; trivial.\n\n  transitivity o'; trivial.\n\napply stab in H7.\nsimpl in H7; rewrite El_def in H7; trivial.\nQed.\n*)\nLet Mirr : forall i j,\n val_ok e i j ->\n forall o' o'' f g,\n isOrd o' ->\n o' ⊆ o'' ->\n o'' ∈ osucc (int O i) ->\n f ∈ cc_prod (Nati o') (U' i o') ->\n g ∈ cc_prod (Nati o'') (U' i o'') ->\n fcompat (Nati o') f g ->\n fcompat (Nati (osucc o')) (int M (V.cons f (V.cons o' i))) (int M (V.cons g (V.cons o'' i))).\nintros.\nassert (Oo: isOrd (int O i)).\n apply ty_O with (1:=H).\nassert (o'' ⊆ int O i).\n apply olts_le in H2; trivial.\nassert (val_mono (push_fun (push_ord E (OSucct O)) (NatI (Ref 0)) U)\n         (V.cons f (V.cons o' i)) (I.cons daimon (I.cons daimon j))\n         (V.cons g (V.cons o'' i)) (I.cons daimon (I.cons daimon j))).\n apply val_mono_1; auto with *.\n  apply val_mono_refl; trivial.\n\n  eauto using isOrd_inv.\n\n  transitivity o''; auto.\napply stab in H7.\nsimpl in *.\nrewrite El_def in H7; trivial.\nQed.\nLet Usub : forall i j,\n val_ok e i j ->\n forall o' o'' x,\n isOrd o' ->\n o' ⊆ o'' ->\n o'' ∈ osucc (int O i) ->\n x ∈ Nati o' ->\n U' i o' x ⊆ U' i o'' x.\nintros.\ndestruct ty_O with (1:=H) as (Oo,_).\nassert (o'' ⊆ int O i).\n apply olts_le in H2; trivial.\neapply El_sub with (1:=fx_sub_U).\napply val_mono_2; auto with *.\n apply val_mono_refl; eexact H.\n\n eauto using isOrd_inv.\nQed.\n\nLemma Mok i j :\n  val_ok e i j ->\n  natfix_hyps (int O i) (F' i) (U' i).\nintros.\nassert (Oo: isOrd (int O i)).\n apply ty_O with (1:=H).\nsplit; trivial.\n intros; apply Mty with (2:=H); trivial.\n  apply isOrd_inv with (osucc (int O i)); auto.  \n\n  apply olts_le in H0; trivial.\n\n intros.\n apply Mirr with (1:=H); trivial.\n\n intros.\n apply Usub with (1:=H); trivial.\nQed.\n\n\nLemma typ_natfix :\n  typ e (NatFix O M) (Prod (NatI O) (subst_rec O 1 U)).\nred; intros.\ndestruct ty_O with (1:=H).\napply in_int_intro.\ndiscriminate.\ndiscriminate.\napply and_split; intros.\n red; rewrite El_int_prod.\n eapply eq_elim.\n 2:simpl; apply natfix_typ with (1:=Mok H); auto with *.\n apply cc_prod_ext.\n  simpl; rewrite El_def; reflexivity.\n\n  red; intros.\n  rewrite int_subst_rec_eq.\n  rewrite <- V.cons_lams.\n  2:apply V.cons_morph; reflexivity.\n  rewrite V.lams0.\n  rewrite H3; reflexivity.\n\n(**)\n set (m:=Lc.Abs (tm M (Lc.ilift (I.cons (tm O j) j)))).\n red in H2; rewrite El_int_prod in H2.\n rewrite Real_int_prod; trivial.\n cut (inSAT (NATFIX m)\n       (piSAT0 (fun x => x ∈ Nati (int O i))\n         (fNATi (int O i))\n         (fun x =>\n            Real (int U (V.cons x (V.cons (int O i) i))) \n              (cc_app (natfix (F' i) (int O i)) x)))).\n  apply piSAT0_morph; intros; auto with *.\n   red; simpl; intros; rewrite El_def; reflexivity.\n\n   rewrite Real_int_NatI; auto with *.\n   symmetry; apply fNATi_stages; auto.\n\n   apply Real_morph; simpl;[|reflexivity].\n   rewrite int_subst_rec_eq.\n   apply int_morph; auto with *.\n   intros [|[|k]]; reflexivity.\n\n apply NATFIX_sat with\n   (X:=fun o n => Real (int U (V.cons n (V.cons o i)))\n     (cc_app (natfix (F' i) o) n)); trivial.\n  red; intros.\n  apply cc_bot_intro in H7.\n  apply fx_sub_U with (V.cons n (V.cons y i))\n     (I.cons daimon (I.cons daimon j)) (I.cons daimon (I.cons daimon j)).\n   apply val_mono_2; auto with *.\n\n   assert (cc_app (natfix (F' i) y) n == cc_app (natfix (F' i) y') n).\n    apply natfix_irr with (1:=Mok H); eauto with *.\n   apply and_split; intros.\n    red; rewrite <- H9.\n    apply cc_prod_elim with (dom:=Nati y) (F:=U' i y); trivial.\n    apply natfix_typ with (1:=Mok H);eauto with *.\n    transitivity y'; trivial.\n\n    rewrite <- H9; trivial.\n\n  (* sat body *)\n  apply piSAT0_intro'.\n  2:exists (int O i).\n  2:apply lt_osucc; auto.\n  intros o' u lto satu.\n  apply inSAT_exp.\n   right; apply sat_sn in satu; trivial.\n  rewrite <- tm_subst_cons.\n  assert (ok': val_ok (Prod (NatI (Ref 0)) U::OSucct O::e)\n            (V.cons (natfix (F' i) o') (V.cons o' i)) (I.cons u (I.cons (tm O j) j))).\n   apply vcons_add_var.\n   3:discriminate.\n    apply vcons_add_var; trivial.\n    2:discriminate.\n    split.\n     red; rewrite El_int_osucc; trivial.\n\n     simpl; rewrite Real_def; auto with *.\n\n     assert (natfix (F' i) o' ∈ cc_prod (Nati o') (U' i o')).\n      apply natfix_typ with (1:=Mok H); eauto with *.\n       apply isOrd_inv with (2:=lto); auto.\n       apply olts_le in lto; trivial.\n     apply and_split; intros.\n      red; rewrite El_int_prod.\n      revert H3; apply eq_elim; apply cc_prod_ext.\n       simpl; rewrite El_def; reflexivity.\n\n       apply ext_fun_ty.\n\n      red in H4; rewrite El_int_prod in H4; trivial.\n      rewrite Real_int_prod; trivial.\n      revert satu; apply piSAT0_morph; intros; auto with *.\n       red; simpl; intros; rewrite El_def; reflexivity.\n\n       rewrite Real_int_NatI; trivial.\n       rewrite fNATi_stages; auto with *.\n       apply isOrd_inv with (2:=lto); auto.\n assert (ty_M' := ty_M _ _ ok').\n apply in_int_not_kind in ty_M'.\n 2:discriminate.\n destruct ty_M' as (ty_M',sat_M').\n red in ty_M'; rewrite El_int_prod in ty_M'.\n rewrite Real_int_prod in sat_M'; trivial.\n apply piSAT0_intro.\n  apply sat_sn in sat_M'; trivial.\n intros x v tyx satv.\n rewrite natfix_unfold with (1:=Mok H); eauto with *.\n 2:eauto using isOrd_inv.\n 2:apply olts_le; trivial.\n apply piSAT0_elim' in sat_M'; red in sat_M'.\n specialize sat_M' with (x:=x) (u0:=v).\n eapply Real_morph.\n 3:apply sat_M'.\n  rewrite int_lift_rec_eq.\n  rewrite int_subst_rec_eq.\n  rewrite int_lift_rec_eq.\n  apply int_morph; auto with *.\n  intros [|[|k]]; unfold V.lams,V.shift; simpl; try reflexivity.\n   replace (k-0) with k; auto with *.\n\n  reflexivity.\n\n  simpl; rewrite El_def; auto.\n\n  rewrite Real_int_NatI; auto.\n  rewrite fNATi_stages in satv; auto.\n  apply isOrd_succ; apply isOrd_inv with (2:=lto); auto.\nQed.\n\n(** Fixpoint equation holds only when applied to a constructor,\n    because of the realizability part of the interpretation.\n *)\nLemma natfix_eq_0 :\n  let N := Zero in\n  typ e N (NatI O) ->\n  eq_typ e (App (NatFix O M) N)\n           (App (subst O (subst (lift 1 (NatFix O M)) M)) N).\nintros N tyN.\nred; intros.\ndestruct ty_O with (1:=H).\n\nchange\n (app (natfix (F' i) (int O i)) (int N i) ==\n  app (int (subst O (subst (lift 1 (NatFix O M)) M)) i) (int N i)).\ndo 2 rewrite <- int_subst_eq.\nrewrite int_cons_lift_eq.\napply natfix_eqn with (1:=Mok H); eauto with *.\nred in tyN; specialize tyN with (1:=H).\napply in_int_not_kind in tyN.\n2:discriminate.\ndestruct tyN as (tyN,satN).\nred in tyN.\nsimpl in tyN; rewrite El_def in tyN.\napply neutr_dec' in tyN; trivial.\ndestruct tyN; trivial.\nelim H2; exists empty.\napply zero_typ.\nQed.\n\nLemma natfix_eq_S : forall X,\n  let N := App (Succ O) X in\n  typ e X (NatI O) ->\n  typ e N (NatI O) ->\n  eq_typ e (App (NatFix O M) N)\n           (App (subst O (subst (lift 1 (NatFix O M)) M)) N).\nintros X N tyX tyN.\nred; intros.\ndestruct ty_O with (1:=H).\nchange\n (app (natfix (F' i) (int O i)) (int N i) ==\n  app (int (subst O (subst (lift 1 (NatFix O M)) M)) i) (int N i)).\ndo 2 rewrite <- int_subst_eq.\nrewrite int_cons_lift_eq.\napply natfix_eqn with (1:=Mok H); eauto with *.\nred in tyN; specialize tyN with (1:=H).\napply in_int_not_kind in tyN.\n2:discriminate.\ndestruct tyN as (tyN,satN).\nred in tyN.\nsimpl in tyN; rewrite El_def in tyN.\napply neutr_dec' in tyN; trivial.\ndestruct tyN; trivial.\nelim H2; exists (TI NATf' (int O i)).\nassert (int X i ∈ cc_bot (TI NATf' (int O i))).\n red in tyX; specialize tyX with (1:=H).\n apply in_int_not_kind in tyX.\n 2:discriminate.\n destruct tyX as (tyX,satX).\n simpl in tyX.\n red in tyX; rewrite El_def in tyX; trivial.\nrewrite beta_eq; auto with *.\n apply succ_typ; trivial.\n\n red; intros; apply succ_morph; trivial.\n\n red; rewrite El_def; trivial.\nQed.\n\nLemma natfix_extend :\n  fx_subval E O ->\n  fx_extends E (NatI O) (NatFix O M).\nintro subO.\ndo 2 red; intros.\nsimpl in H0; rewrite El_def in H0.\nassert (isval := proj1 H).\nassert (isval' := proj1 (proj2 H)).\ndestruct ty_O with (1:=isval) as (oo,_).\ndestruct ty_O with (1:=isval') as (oo',_).\nassert (inclo: int O i ⊆ int O i').\n apply subO in H; trivial.\nclear subO.\nsimpl.\napply natfix_ext with (4:=Mok isval) (5:=Mok isval'); trivial.\nintros.\nred; intros.\ndo 2 red in stab; eapply stab.\n apply val_mono_1 with (1:=H); auto with *.\n transitivity (int O i); trivial.\n\n simpl.\n rewrite El_def; auto.\nQed.\n\nLemma natfix_equals :\n  fx_equals E O ->\n  fx_equals E (NatFix O M).\nred; intros.\nassert (isval := proj1 H0).\nassert (isval' := proj1 (proj2 H0)).\nassert (Oo : isOrd (int O i)).\n apply ty_O with (1:=isval).\nassert (fxs: fx_subval E O).\n apply fx_equals_subval; trivial.\nred in H; specialize H with (1:=H0).\napply natfix_extend in fxs.\nred in fxs.\nspecialize fxs with (1:=H0).\napply fcompat_typ_eq with (3:=fxs).\n rewrite El_int_NatI.\n eapply cc_prod_is_cc_fun.\n apply natfix_typ with (1:=Mok isval); auto with *.\n\n rewrite El_int_NatI.\n simpl.\n rewrite H in Oo|-*.\n eapply cc_prod_is_cc_fun.\n apply natfix_typ with (1:=Mok isval'); auto with *.\nQed.\n\nEnd NatFixRules.\n\n\nLemma typ_natfix' : forall e O U M T,\n       T <> kind ->\n       typ_ord e O ->\n       typ (Prod (NatI (Ref 0)) U :: OSucct O :: e) M\n         (Prod (NatI (OSucc (Ref 1)))\n         (lift_rec 1 1 (subst_rec (OSucc (Ref 0)) 1 (lift_rec 1 2 U)))) ->\n       fx_extends (push_fun (push_ord (tinj e) (OSucct O)) (NatI (Ref 0)) U)\n         (NatI (OSucc (Ref 1))) M ->\n       fx_sub (push_var (push_ord (tinj e) (OSucct O)) (NatI (OSucc (Ref 0)))) U ->\n       sub_typ e (Prod (NatI O) (subst_rec O 1 U)) T ->\n       typ e (NatFix O M) T.\nintros.\napply typ_subsumption with (Prod (NatI O) (subst_rec O 1 U)); auto.\n2:discriminate.\nchange e with (tenv (tinj e)).\napply typ_natfix; trivial.\nQed.\n\n\nLemma typ_natfix'' e O U M T :\n       T <> kind ->\n       sub_typ (tenv e) (Prod (NatI O) (subst_rec O 1 U)) T ->\n       typ_ord (tenv e) O ->\n       typ_mono (push_var (push_ord e (OSucct O)) (NatI (OSucc (Ref 0)))) U ->\n       typ_ext (push_fun (push_ord e (OSucct O)) (NatI (Ref 0)) U)\n         M (NatI (OSucc (Ref 1)))\n           (lift_rec 1 1 (subst_rec (OSucc (Ref 0)) 1 (lift_rec 1 2 U))) ->\n       typ (tenv e) (NatFix O M) T.\nintros.\ndestruct H2; destruct H3.\napply typ_subsumption with (2:=H0); trivial.\n2:discriminate.\napply typ_natfix; trivial.\nQed.\n\n(** Variance results *)\n\n  Lemma typ_ext_fix e O U M :\n    typ_ord_mono e O ->\n    typ_ext (push_fun (push_ord e (OSucct O)) (NatI (Ref 0)) U) M\n      (NatI (OSucc (Ref 1)))\n      (lift_rec 1 1 (subst_rec (OSucc (Ref 0)) 1 (lift_rec 1 2 U))) ->\n    fx_sub (push_var (push_ord e (OSucct O)) (NatI (OSucc (Ref 0)))) U ->\n    typ_ext e (NatFix O M) (NatI O) (subst_rec O 1 U).\nintros tyO tyM tyU.\ndestruct tyO as (inclO,tyO).\ndestruct tyM as (extM,tyM).\nassert (tyF: typ (tenv e) (NatFix O M) (Prod (NatI O) (subst_rec O 1 U))).\n apply typ_natfix; trivial.\nsplit; trivial.\nred; intros.\ngeneralize i i' j j' H; change (fx_extends e (NatI O) (NatFix O M)).\napply natfix_extend with U; trivial.\nQed.\n\n  Lemma typ_impl_fix e O U M :\n    typ_ord_impl e O ->\n    typ_ext (push_fun (push_ord e (OSucct O)) (NatI (Ref 0)) U) M\n      (NatI (OSucc (Ref 1)))\n      (lift_rec 1 1 (subst_rec (OSucc (Ref 0)) 1 (lift_rec 1 2 U))) ->\n    fx_sub (push_var (push_ord e (OSucct O)) (NatI (OSucc (Ref 0)))) U ->\n    typ_impl e (NatFix O M) (Prod (NatI O) (subst_rec O 1 U)).\nintros (inclO,tyO) (extM,tyM) tyU.\nassert (tyF: typ (tenv e) (NatFix O M) (Prod (NatI O) (subst_rec O 1 U))).\n apply typ_natfix; trivial.\nsplit; trivial.\nred; intros.\ngeneralize i i' j j' H; change (fx_equals e (NatFix O M)).\napply natfix_equals with U; trivial.\nQed.\n\n\nModule Examples.\n\n(************************************************************************)\n(** Two examples of derived principles:\n    - the standard recursor for Nat\n    - subtraction with size information\n*)\nSection Example.\n\n\nDefinition nat_ind_typ :=\n   Prod (Prod (NatI infty) prop) (* P : nat -> Prop *)\n  (Prod (App (Ref 0) Zero)\n  (Prod (Prod (NatI infty) (Prod (App (Ref 2) (Ref 0))\n                        (App (Ref 3) (App (Succ infty) (Ref 1)))))\n  (Prod (NatI infty) (App (Ref 3) (Ref 0))))).\n\nDefinition nat_ind :=\n   Abs (*P*)(Prod (NatI infty) prop) (* P : nat -> Prop *)\n  (Abs (*fZ*) (App (Ref 0) Zero)\n  (Abs (*fS*) (Prod (*n*)(NatI infty) (Prod (App (Ref 2) (Ref 0))\n                                   (App (Ref 3) (App (Succ infty) (Ref 1)))))\n  (NatFix infty\n    (*o,Hrec*)\n    (Abs (*n*)(NatI (OSucc (Ref 1)))\n      (NatCase\n        (Ref 4)\n        (*k*)(App (App (Ref 4) (Ref 0))\n                  (App (Ref 2) (Ref 0)))\n        (Ref 0)))))).\n\n\n\nLemma nat_ind_def :\n  forall e, typ e nat_ind nat_ind_typ.\nunfold nat_ind, nat_ind_typ; intros.\napply typ_abs; try discriminate.\n left.\n apply typ_prod; auto.\n  left.\n  apply typ_NatI; trivial.\n\n  apply typ_prop.\napply typ_abs; try discriminate.\n right.\n apply typ_subsumption with (subst Zero prop); try discriminate.\n  apply typ_app with (NatI infty); try discriminate.\n   apply typ_subsumption with (NatI (OSucc infty)); try discriminate.\n    apply typ_0; trivial.\n\n    apply sub_refl.\n    red; simpl; intros.\n    apply mkTY_ext.\n     rewrite TI_mono_succ; auto with *.\n     rewrite <- NAT_eqn; auto with *.\n\n     intros.\n     rewrite H1; reflexivity.\n\n    apply typ_var0.\n    split;[discriminate|].\n    apply sub_refl; apply eq_term_eq_typ.\n    apply eq_term_intro; simpl; auto; try reflexivity.\n\n    apply sub_refl; apply eq_term_eq_typ.\n    apply eq_term_intro; simpl; auto; try reflexivity.\n(*\n left.\n split;[discriminate|].\n split;[apply kind_ok_trivial|].\n simpl. \n destruct (H 0 _ eq_refl) as (_,?).\n simpl in H0. \n destruct rprod_elim with (2:=H0) (x:=zero)(u:=ZE).\n  red; reflexivity.\n\n  admit.\n\n  apply sat_sn in H2; trivial.*)\napply typ_abs; try discriminate.\n right.\n apply typ_prod; auto.\n  left.\n  apply typ_NatI; trivial.\n apply typ_prod; auto.\n  right.\n  eapply typ_subsumption with (subst (Ref 0) prop); try discriminate.\n   apply typ_app with (NatI infty); try discriminate.\n    apply typ_var0.\n    split;[discriminate|].\n    apply sub_refl; apply eq_term_eq_typ.\n    split; simpl; red; intros; auto with *.\n\n    apply typ_var0.\n    split;[discriminate|].\n    apply sub_refl; apply eq_term_eq_typ.\n    apply eq_term_intro; simpl; auto; try reflexivity.\n\n   apply sub_refl; apply eq_term_eq_typ.\n   apply eq_term_intro; simpl; auto; try reflexivity.\n\n  eapply typ_subsumption with (subst (App (Succ infty) (Ref 1)) prop); try discriminate.\n   apply typ_app with (NatI infty); try discriminate.\n    eapply typ_subsumption with (subst (Ref 1) (lift 1 (NatI (OSucc infty)))); try discriminate.\n     apply typ_app with (NatI infty); try discriminate.\n      apply typ_var0.\n      split;[discriminate|].\n      apply sub_refl; apply eq_term_eq_typ.\n      apply eq_term_intro; simpl; auto; try reflexivity.\n\n      apply typ_S; trivial.\n\n     apply sub_refl; apply eq_term_eq_typ.\n     apply eq_term_intro; intros; simpl; auto; try reflexivity.\n     apply mkTY_ext; trivial.\n      rewrite TI_mono_succ; auto with *.\n      rewrite <- NAT_eqn; auto with *.\n\n      intros; apply cNAT_morph; trivial.\n\n    apply typ_var0.\n    split;[discriminate|].\n    apply sub_refl; apply eq_term_eq_typ.\n    apply eq_term_intro; intros; simpl; auto; try reflexivity.\n\n   apply sub_refl; apply eq_term_eq_typ.\n   split; simpl; red; intros; auto with *.\n\nset (E0 := Prod (NatI infty)\n                 (Prod (App (Ref 2) (Ref 0))\n                    (App (Ref 3) (App (Succ infty) (Ref 1))))\n               :: App (Ref 0) Zero :: Prod (NatI infty) prop :: e) in |-*.\nchange E0 with (tenv (tinj E0)).\napply typ_natfix'' with (U:=App (Ref 4) (Ref 0)); auto.\n discriminate.\n\n (* sub *)\n apply sub_refl.\n apply eq_typ_prod.\n 3:discriminate.\n  reflexivity.\n  apply eq_term_eq_typ.\n  rewrite red_sigma_app.\n  rewrite red_sigma_var_gt; auto with arith.\n  rewrite red_sigma_var_lt; auto with arith.\n  reflexivity.\n\n (* codom mono *)\n split.\n  apply fx_equals_sub.\n  apply fx_eq_noc.\n  apply noc_app.\n   apply noc_var; reflexivity.\n   apply noc_var; reflexivity.\n\n  right.\n  eapply typ_subsumption with (subst (Ref 0) prop); try discriminate.\n   apply typ_app with (NatI infty); try discriminate.\n    apply typ_var0.\n    split;[discriminate|].\n    apply sub_trans with (NatI (OSucc (Ref 1))).\n     apply sub_refl; apply eq_term_eq_typ.\n     split; red; simpl; intros.\n      apply mkTY_ext.\n      apply TI_morph; auto with *.\n      apply osucc_morph.\n      apply H.\n\n      intros; apply cNAT_morph; trivial.\n\n      apply H.\n\n     apply NatI_sub_infty.\n     apply OSucc_typ.\n     apply typ_ord_varS.\n     apply typ_ord_var0; trivial.\n\n    apply typ_var0.\n    split;[discriminate|].\n    apply sub_refl; apply eq_term_eq_typ.\n    apply eq_term_intro; intros; simpl; auto; try reflexivity.\n\n   apply sub_refl; apply eq_term_eq_typ.\n   apply eq_term_intro; intros; simpl; auto; try reflexivity.\n\n (* fix body *)\n apply ext_abs; try discriminate.\n  split.\n   apply NatI_sub.\n    apply OSucc_typ.\n    red; simpl; intros.\n    destruct (H 1 _ eq_refl).\n    simpl in H1.\n    destruct H1.\n    red in H1; rewrite El_def in H1.\n    rewrite Real_def in H2; trivial.\n    2:reflexivity.\n    apply sat_sn in H2; split; trivial.\n    apply cc_bot_ax in H1; destruct H1.\n     rewrite H1; auto.\n     apply isOrd_inv with (osucc omega); auto.\n\n    apply OSucc_subval.\n     apply typ_ord_varS.\n     apply typ_ord_var0; trivial.\n\n   apply var_sub; simpl; trivial.\n\n  left.\n  apply typ_NatI; auto.\n  apply OSucc_typ.\n  apply typ_ord_varS.\n  apply typ_ord_var0; trivial.\n\nrewrite red_lift_app.\nrewrite eq_term_lift_ref_fv; auto with arith.\n\nrewrite red_lift_ref_bound; auto with arith.\nrewrite red_sigma_app.\nrewrite red_sigma_var_gt; auto with arith.\nrewrite red_sigma_var_lt; auto with arith.\nrewrite red_lift_app.\nrewrite eq_term_lift_ref_fv; auto with arith.\nrewrite red_lift_ref_bound; auto with arith.\n\n  apply impl_NatCase with (O0:=Ref 2); auto.\n   split.\n    apply var_sub; simpl; trivial.\n   apply typ_ord_varS.\n   apply typ_ord_varS.\n   apply typ_ord_var0; trivial.\n\n   (* branch 0 *)\n   eapply typ_var_impl.\n    compute; reflexivity.\n    simpl nth_error.\n    reflexivity.\n    discriminate.\n    discriminate.\n\n    apply sub_refl; red; simpl; intros.\n    unfold V.lams, V.shift; simpl.\n    reflexivity.\n(*\n  apply typ_impl_varS with (App (Ref 4) Zero).\n  apply typ_impl_varS with (App (Ref 3) Zero).\n  apply typ_impl_varS with (App (Ref 2) Zero).\n  apply typ_impl_inj.\n  apply typ_var0.\n  split.\n   discriminate.\n   apply sub_refl.\n   apply eq_term_eq_typ.\n   unfold lift; rewrite red_lift_app.\n   apply App_morph.\n    rewrite eq_term_lift_ref_fv; auto with *.\n    reflexivity.\n\n    simpl; split; red; auto with *.\n\n   unfold lift; rewrite red_lift_app, eq_term_lift_ref_fv; auto with arith;\n     apply App_morph;[reflexivity|split;red;simpl; auto with *].\n   unfold lift; rewrite red_lift_app, eq_term_lift_ref_fv; auto with arith;\n     apply App_morph;[reflexivity|split;red;simpl; auto with *].\n   unfold lift; rewrite red_lift_app, eq_term_lift_ref_fv; auto with arith;\n     apply App_morph;[reflexivity|split;red;simpl; auto with *].*)\n\n   (* branch S *)\n   apply impl_app with (App (Ref 6) (Ref 0)) (* P n *)\n     (App (Ref 7) (App (Succ (Ref 4)) (Ref 1))); (* P (S n) *)\n     try discriminate.\n    apply sub_refl; red; intros; simpl.\n    unfold V.lams, V.shift; simpl.\n    reflexivity.\n\n    apply impl_app with (NatI infty)\n     (Prod (App (Ref 7) (Ref 0)) (App (Ref 8) (App (Succ infty) (Ref 1))));\n      try discriminate.\n     apply sub_refl.\n     unfold subst; rewrite red_sigma_prod, !red_sigma_app, !red_sigma_ref; try discriminate.\n     simpl lt_eq_lt_dec; cbv beta iota; simpl Peano.pred.\n     rewrite lift0.\n     apply eq_typ_prod; [| |discriminate].\n      apply refl.\n     apply eq_typ_app; [apply refl|].\n     apply trans with (App (Succ infty) (Ref 1)).\n      apply eq_term_eq_typ.\n      split; simpl; red; intros.\n       apply app_ext; auto with *.\n       apply H.\n\n       rewrite <- (H 1); reflexivity.\n\n     red; intros; simpl.\n     assert (i 1 ∈ cc_bot (TI NATf' (i 4))).\n      destruct (H 1 _ eq_refl) as (_,(?,_)).\n      red in H0; simpl in H0.\n      rewrite El_def in H0.\n      trivial.\n     (* Succ irrel: *)\n     rewrite beta_eq. 2:red; intros; apply succ_morph; trivial.\n     rewrite beta_eq. 2:red; intros; apply succ_morph; trivial.\n      reflexivity.\n\n      red; rewrite El_def; trivial.\n\n      destruct (H 4 _ eq_refl) as (_,(?,_)).\n      red in H1; simpl in H1; rewrite El_def in H1.\n      assert (i 4 ∈ osucc omega).\n       apply cc_bot_ax in H1; destruct H1; trivial.\n       rewrite H1; apply ole_lts; auto.\n      red; rewrite El_def.\n      revert H0; apply cc_bot_mono.\n      apply TI_mono; auto with *.\n       apply isOrd_inv with (osucc omega); auto.\n       apply olts_le; trivial.\n\n     eapply typ_var_impl.\n      compute; reflexivity.\n      simpl; reflexivity.\n      discriminate.\n      discriminate.\n\n      apply sub_refl.\n      apply eq_term_eq_typ.\n      unfold lift; rewrite !red_lift_prod, !red_lift_app, !red_lift_ref.\n      simpl Ref.\n      apply Prod_morph.\n       split; red; simpl; auto with *.\n      apply Prod_morph; auto with *.\n      apply App_morph; auto with *.\n      apply App_morph; auto with *.\n      split; red; simpl; auto with *.\n\n     eapply typ_var_impl.\n      compute; reflexivity.\n      simpl; reflexivity.\n      discriminate.\n      discriminate.\n\n      apply sub_trans with (NatI (Ref 3)).\n       apply sub_refl; apply eq_term_eq_typ.\n       split; red; simpl; intros.\n        apply mkTY_ext.\n         apply TI_morph; auto with *.\n         apply H.\n\n         intros; apply cNAT_morph; trivial.\n\n        apply H.\n\n     apply NatI_sub_infty.\n     apply typ_ord_varS.\n     apply typ_ord_varS.\n     apply typ_ord_varS.\n     apply typ_ord_var0; trivial.\n\n    eapply impl_call.\n     compute; trivial.\n     simpl; reflexivity.\n     discriminate.\n     discriminate.\n     2:simpl; reflexivity.\n     discriminate.\n\n     apply sub_refl; apply eq_term_eq_typ.\n     unfold subst; rewrite red_lift_app, red_sigma_app.\n     rewrite !red_lift_ref, !red_sigma_ref; try discriminate.\n     simpl lt_eq_lt_dec; cbv beta iota.\n     rewrite lift0.\n     reflexivity.\n\n     eapply typ_var_impl.\n      compute; reflexivity.\n      simpl; reflexivity.\n      discriminate.\n      discriminate.\n\n      apply sub_refl; red; intros; simpl.\n      reflexivity.\n\n   (* Scrutinee *)\n   eapply typ_var_impl.\n    compute; reflexivity.\n    simpl; reflexivity.\n    discriminate.\n    discriminate.\n\n    apply sub_refl; red; intros; simpl.\n    reflexivity.\nQed.\n\n\n(* Subtraction *)\n\nDefinition minus O :=\n  NatFix O\n    (*o,Hrec*)\n    (Abs (*n*) (NatI (OSucc (Ref 1)))\n    (Abs (*m*) (NatI infty)\n    (NatCase\n       Zero\n       (*n'*)\n       (NatCase\n         (Ref 2)\n         (*m'*)\n         (App (App (Ref 4) (Ref 1)) (Ref 0))\n         (Ref 1))\n       (Ref 1)))).\n\nDefinition minus_typ O := Prod (NatI O) (Prod (NatI infty) (NatI (lift 2 O))).\n\n(*\n\nLemma minus_def :\n  forall e infty O,\n  isOrd infty ->\n  typ e O (Ord infty) ->\n  typ e (minus O) (minus_typ O).\nintros.\nunfold minus, minus_typ.\nchange e with (tenv (tinj e)).\napply typ_nat_fix'' with infty (Prod (NatI infty) (NatI (Ref 2))); auto.\n (* sub *)\n apply sub_refl.\n apply eq_typ_prod.\n  reflexivity.\n\n  rewrite eq_subst_prod.\n  apply eq_typ_prod.\n   red; intros; simpl; reflexivity.\n\n   red; intros; simpl.\n   unfold lift; rewrite int_lift_rec_eq.\n   rewrite V.lams0.\n   unfold V.lams, V.shift; simpl; reflexivity.\n\n (* codom mono *)\n split;[|red; intros; simpl; exact I].\n apply fx_sub_prod.\n  apply fx_eq_noc.\n  red; simpl; reflexivity.\n\n  apply NATi_sub with infty; trivial.\n  simpl.\n  apply typ_var0; split; [discriminate|].\n  red; intros; simpl.\n  unfold lift in H2; rewrite int_lift_rec_eq in H2.\n  rewrite V.lams0 in H2.\n  simpl in H2.\n  apply le_lt_trans with (2:=H2); trivial.\n  apply H0.\n  red; intros.\n  generalize (H1 (3+n) _ H3).\n  destruct T as [(T,Tm)|]; simpl; trivial.\n\n  apply var_sub.\n  compute; reflexivity.\n\n (* fix body *)\n apply ext_abs; try discriminate.\n  apply NATi_fx_sub with (o:=osucc infty); auto.\n  apply OSucc_fx_sub; auto.\n  eapply typ_var_mono.\n   compute; reflexivity.\n   simpl; reflexivity.\n   discriminate.\n  red; simpl; intros; trivial.\n  apply weakening0 in H0; apply weakeningS with (A:=OSucct O) in H0.\n  apply weakeningS with (A:=Prod(NatI(Ref 0))(Prod(NatIinfty)(NatI(Ref 2)))) in H0.\n  apply H0 in H1.\n  simpl in H1.\n  unfold lift in H1; rewrite int_lift_rec_eq in H1.\n  apply le_lt_trans with (3:=H1); trivial.\n\n rewrite eq_lift_prod.\n rewrite eq_subst_prod.\n unfold lift1; rewrite eq_lift_prod.\n apply impl_abs.\n  discriminate.\n\n  red; intros; simpl.\n  reflexivity.\n\n  red; intros; simpl; auto with *.\n\n match goal with |- typ_impl ?e _ _ => set (E:=e) end.\n assert (typ_impl E (Ref 1) (NatI (OSucc (Ref 3)))).\n  eapply typ_var_impl.\n   compute; reflexivity.\n   simpl; reflexivity.\n   discriminate.\n  apply sub_refl.\n  red; intros; simpl; reflexivity.\n apply impl_natcase with infty (Ref 3)\n    (Abs (NatI (OSucc (Ref 3))) (NatI (OSucc (Ref 4)))); auto.\n  Focus 2.\n  apply sub_refl.\n  rewrite eq_typ_betar.\n  3:discriminate.\n   red; intros; simpl.\n   unfold V.lams, V.shift; simpl.\n   reflexivity.\n\n   apply H1.\n\n  (* ord *)\n  eapply typ_var_mono.\n   compute;reflexivity.\n   simpl; reflexivity.\n   discriminate.\n  red; intros; simpl.\n  unfold lift in H3; rewrite int_lift_rec_eq in H3.\n  rewrite V.lams0 in H3.\n  simpl in H3.\n  apply le_lt_trans with (2:=H3); trivial.\n  apply H0.\n  red; intros.\n  generalize (H2 (4+n) _ H4).\n  destruct T as [(T,Tm)|]; simpl; auto.\n\n  (* branch 0 *)\n  split.\n   red; intros; simpl; reflexivity.\n  assert (tyz : typ (tenv E) Zero (NatI (OSucc (Ref 3)))).\n    apply typ_Zero with infty; trivial.\n    apply typ_var0; split; [discriminate|].\n    red; intros; simpl.\n    unfold lift in H3; rewrite int_lift_rec_eq in H3.\n    rewrite V.lams0 in H3.\n    simpl in H3.\n    apply le_lt_trans with (2:=H3); trivial.\n    apply H0.\n    red; intros.\n    generalize (H2 (4+n) _ H4).\n    destruct T as [(T,Tm)|]; simpl; trivial.\n  apply typ_conv with (NatI (OSucc (Ref 3))); trivial.\n  2:discriminate.\n  rewrite eq_typ_betar; trivial.\n  2:discriminate.\n  red; intros; simpl.\n  reflexivity.\n\n  (* branch S *)\n  assert (typ_impl (push_var E (NatI (Ref 3))) (Ref 1) (NatI (Ord (osucc omega)))).\n   eapply typ_var_impl.\n    compute; reflexivity.\n    simpl; reflexivity.\n    discriminate.\n   apply sub_refl.\n   red; intros; simpl.\n   unfold NATi at 2; rewrite TI_mono_succ; auto.\n   apply NAT_eq.\n  apply impl_natcase with (osucc omega) infty\n     (Abs (NatI (OSucct infty)) (NatI (OSucc (Ref 5)))); auto.\n   Focus 2.\n   apply sub_refl.\n   rewrite eq_typ_betar.\n   3:discriminate.\n    unfold lift; rewrite eq_lift_abs.\n    rewrite eq_typ_betar.\n    3:discriminate.\n     red; intros; simpl; reflexivity.\n     apply typ_conv with (NatI (OSucc (lift_rec 1 0 (Ref 3)))).\n     3:discriminate.\n      apply typ_SuccI with (o:=infty); trivial.\n      apply typ_var0; split;[discriminate|].\n      red; intros; simpl.\n      unfold lift in H4; rewrite int_lift_rec_eq in H4.\n      rewrite V.lams0 in H4.\n      simpl in H4.\n      apply le_lt_trans with (2:=H4); trivial.\n      apply H0.\n      red; intros.\n      generalize (H3 (5+n) _ H5).\n      destruct T as [(T,Tm)|]; simpl; trivial.\n\n      apply typ_var0; split;[discriminate|].\n      apply sub_refl; red; intros; simpl.\n      reflexivity.\n\n     red; intros; simpl.\n     reflexivity.\n\n     apply H2.\n\n   (* ord *)\n   split.\n    red; intros; simpl; reflexivity.\n\n    red; intros; simpl.\n    apply lt_osucc; trivial.\n\n  (* branch 0 *)\n  eapply typ_var_impl.\n   compute; reflexivity.\n   simpl; reflexivity.\n   discriminate.\n  apply sub_refl.\n  rewrite eq_typ_betar.\n  3:discriminate.\n   red; intros; simpl.\n   unfold V.lams, V.shift; simpl; reflexivity.\n\n   eapply typ_Zero with (osucc omega); auto.\n   red; intros; simpl.\n   apply lt_osucc; trivial.\n\n  (* branch S *)    \n  apply impl_app with (NatI infty) (NatI (OSucc (Ref 6))).\n   discriminate.\n   discriminate.\n\n   unfold lift; rewrite eq_lift_abs.\n   apply sub_refl.\n   rewrite eq_typ_betar.\n   3:discriminate.\n    red; intros; simpl.\n    unfold V.lams, V.shift; simpl.\n    reflexivity.\n\n    apply typ_conv with (NatI (OSucc (lift_rec 1 0 infty))).\n    3:discriminate.\n     apply typ_SuccI with (o:=osucc omega); auto.\n      red; intros; simpl.\n      apply lt_osucc; trivial.\n\n      apply typ_var0; split;[discriminate|].\n      apply sub_refl; red; intros; simpl.\n      reflexivity.\n\n     red; intros; simpl.\n     reflexivity.\n\n   eapply impl_call.\n    compute; reflexivity.\n    simpl; reflexivity.\n    discriminate.\n    2:simpl; reflexivity.\n    discriminate.\n\n    unfold subst, lift1; rewrite eq_lift_prod.\n    rewrite eq_subst_prod.\n    apply sub_typ_covariant.\n     red; intros; simpl; reflexivity.\n\n     red; intros; simpl.\n     rewrite int_subst_rec_eq in H4.\n     simpl in H4; unfold V.lams, V.shift in H4; simpl in H4.\n     assert (isOrd (i 6)).\n      generalize (H3 6 _ (reflexivity _)).\n      simpl; intro.\n      rewrite V.lams0 in H5.\n      apply isOrd_inv with (2:=H5).      \n      apply isOrd_succ.\n      assert (val_ok e (V.shift 7 i)).\n       red; intros.\n       generalize (H3 (7+n) _ H6).\n       destruct T as [(T,Tm)|]; simpl; auto.\n      apply H0 in H6.\n      simpl in H6.\n      apply isOrd_inv with infty; trivial.\n     revert H4; apply TI_incl; auto.\n\n    eapply typ_var_impl.\n     compute; reflexivity.\n     simpl; reflexivity.\n     discriminate.\n\n     apply sub_refl.\n     red; intros; simpl.\n     reflexivity.\n\n     eapply typ_var_impl.\n      compute; reflexivity.\n      simpl; reflexivity.\n      discriminate.\n\n      apply sub_refl.\n      red; intros; simpl.\n      reflexivity.\nQed.\n\nEnd Example.\n\nPrint Assumptions minus_def.\n*)\n\n(* \"Map\" is size-preserving *)\n\nDefinition map O :=\n  NatFix O\n    (*o,Hrec*)\n    (Abs (*n*) (NatI (OSucc (Ref 1)))\n    (NatCase\n       Zero\n       (*n'*)\n       (App(Succ (Ref 3)) (App (Ref 2) (Ref 0))) (* S(Hrec n') *)\n       (Ref 0))).\n\nDefinition map_typ O := Prod (NatI O) (NatI (lift 1 O)).\n\nLemma map_def e O :\n  O <> kind ->\n  typ_ord e O ->\n  typ e (map O) (map_typ O).\nunfold map, map_typ; intros Onk tyO.\nchange e with (tenv (tinj e)).\napply typ_natfix'' with (U:=NatI (Ref 1)); auto.\n discriminate.\n\n (* sub *)\n apply sub_refl; apply eq_term_eq_typ.\n apply Prod_morph;[reflexivity|].\n rewrite eq_sb_NatI.\n apply NatI_morph; rewrite red_sigma_ref; trivial.\n reflexivity.\n\n (* codom mono *)\n split.\n  apply NatI_sub.\n   apply typ_ord_varS.\n   apply typ_ord_var0_ord; trivial.\n\n   apply var_sub; reflexivity.\n\n  left.\n  apply typ_NatI.   \n  apply typ_ord_varS.\n  apply typ_ord_var0_ord; trivial.\n\n (* fix body *)\n apply ext_abs; try discriminate.\n  split.\n   apply NatI_sub.\n    apply OSucc_typ.\n    apply typ_ord_varS.\n    apply typ_ord_var0_ord; trivial.\n\n    apply OSucc_subval.\n     apply typ_ord_varS.\n     apply typ_ord_var0_ord; trivial.\n\n     apply var_sub; reflexivity.\n\n   left.\n   apply typ_NatI.   \n   apply OSucc_typ.\n   apply typ_ord_varS.\n   apply typ_ord_var0_ord; trivial.\n\n apply typ_impl_subsumption with (subst (Ref 0) (NatI(OSucc(Ref 3)))).\n 3:discriminate.\n 3:discriminate.\n  apply impl_NatCase' with (O0:=Ref 2).\n   discriminate.\n\n  (* ord mono *)\n  split.\n   apply var_sub; simpl; trivial.\n\n   apply typ_ord_varS.\n   apply typ_ord_varS.\n   apply typ_ord_var0_ord; trivial.\n \n  (* branch 0 *)\n  split.\n   apply fx_eq_noc.\n   red; simpl; reflexivity.\n\n   apply typ_subsumption with (NatI (OSucc (Ref 2))).\n   3:discriminate.\n   3:discriminate.\n    apply typ_0.\n    apply typ_ord_varS.\n    apply typ_ord_varS.\n    apply typ_ord_var0_ord; trivial.\n\n    apply sub_refl; apply eq_term_eq_typ.\n    unfold subst; rewrite eq_sb_NatI; apply NatI_morph.\n    apply eq_term_intro; simpl; trivial.    \n    reflexivity.\n\n  (* branch S *)\n  split.\n  apply fx_eq_app_irr with (NatI (Ref 3)).\n    discriminate.\n   apply ext_S.\n    apply typ_ord_varS.\n    apply typ_ord_varS.\n    apply typ_ord_varS.\n    apply typ_ord_var0_ord; trivial.\n   apply var_sub; reflexivity.\n\n   apply fx_eq_rec_call with (NatI (Ref 0)) (NatI (Ref 4)); trivial.\n    discriminate.\n\n    apply typ_var0; split;[discriminate|].\n    apply sub_refl; apply eq_term_eq_typ.\n    unfold lift; rewrite red_lift_prod.\n    apply Prod_morph.\n     apply eq_term_intro; trivial; reflexivity.\n     apply eq_term_intro; trivial; reflexivity.\n   \n    apply fx_eq_noc; apply noc_var; auto.\n   \n    apply typ_var0; split;[discriminate|].\n    apply sub_refl; apply eq_term_eq_typ.\n    apply eq_term_intro; trivial; reflexivity.\n\n    eapply typ_subsumption.\n     eapply typ_app.\n      apply typ_var; reflexivity.\n    apply typ_var0; split;[discriminate|].\n    apply sub_refl; apply eq_term_eq_typ.\n    unfold lift; rewrite red_lift_prod.\n    apply Prod_morph;[|reflexivity].\n    apply eq_term_intro; trivial; reflexivity.\n     discriminate.\n     discriminate.\n     2:discriminate.\n     2:discriminate.\n\n    apply sub_refl; apply eq_term_eq_typ.\n    apply eq_term_intro; trivial; reflexivity.\n\n  eapply typ_subsumption.\n   eapply typ_app.\n   2:apply typ_S.  \n3:discriminate.\n3:discriminate.\n4:discriminate.\n4:discriminate.\n    2:apply typ_ord_varS.\n    2:apply typ_ord_varS.\n    2:apply typ_ord_varS.\n    2:apply typ_ord_var0_ord; trivial.\n\n  eapply typ_subsumption.\n   eapply typ_app.\n    eapply typ_var;reflexivity.\n2:discriminate.\n5:discriminate.\napply typ_var0.\nsplit.\n discriminate.\n  apply sub_refl; apply eq_term_eq_typ.\n   unfold lift; rewrite red_lift_prod.\n   apply Prod_morph;[|reflexivity].\n2:discriminate.\n3:discriminate.   \n  apply eq_term_intro; trivial; reflexivity.\n\n  apply sub_refl; apply eq_term_eq_typ.\n  apply eq_term_intro; trivial; reflexivity.\n\n  apply sub_refl; apply eq_term_eq_typ.\n  apply eq_term_intro; trivial; reflexivity.\n  \n  (* scrutinee *)\n  eapply typ_var_impl. 2:reflexivity.\n  2:discriminate.\n  2:discriminate.\n  reflexivity.\n\n  apply sub_refl; apply eq_term_eq_typ.\n  apply eq_term_intro; simpl; auto.\n  reflexivity.\n\n (* sub case pred *)\n apply sub_refl; apply eq_term_eq_typ.\n apply eq_term_intro; trivial; reflexivity.\nQed.\n\nEnd Example.\nEnd Examples.\n\nEnd Make.\n\n(** Create an instance of SizedNats based on ZFind_natbot *)\nModule NATM <: SizedNats.\n\nRequire Import ZFind_natbot.\n\nDefinition NATf' := NATf'.\nDefinition NATf'_mono := NATf'_mono.\nExisting Instance NATf'_mono.\n\n  (** N is the type of natural numbers including neutral values.\n      Nbot is a decidable subet of N. *)\n(*  Parameter N Nbot : set.\n  Parameter N_Nbot : N ⊆ Nbot.\n  Parameter Ndec : forall n, n ∈ Nbot -> n∈N \\/ ~n∈N.*)\n\nDefinition zero := ZERO.\nDefinition succ := SUCC.\nDefinition succ_morph : morph1 succ := inr_morph.\nExisting Instance succ_morph.\n\n  (** Constructors produce non-neutral values *)\nLemma zero_typ : forall X, zero ∈ NATf' X.\nintros.\napply ZERO_typ_gen.\nQed.\nLemma succ_typ : forall X n, n ∈ cc_bot X -> succ n ∈ NATf' X.\nintros.\napply SUCC_typ_gen; trivial.\nQed.\n\nLemma NATf'_elim : forall n X,\n    n ∈ NATf' X ->\n    n == zero \\/ exists2 x, x ∈ cc_bot X & n == succ x.\nintros.\napply sum_ind with (3:=H); [left|right]; eauto.\napply ZFind_basic.unit_elim in H0.\nrewrite H0 in H1; trivial.\nQed.\n\nLemma neutr_dec' : forall n o,\n    isOrd o ->\n    n ∈ cc_bot (TI NATf' o) ->\n    n ∈ TI NATf' o \\/ ~ exists Y, n ∈ NATf' Y.\nintros.\napply cc_bot_ax in H0; destruct H0; auto.\nright; intros (X,tyn).\nunfold NATf' in tyn.\nrewrite H0 in tyn.\napply NATf_case with (3:=tyn); intros.\n apply discr_mt_couple in H1; trivial.\n apply discr_mt_couple in H2; trivial.\nQed.\n\n  Lemma NAT_eqn : TI NATf' omega == NATf' (TI NATf' omega).\nProof NAT'_eq.\n\nDefinition natcase : set -> (set -> set) -> set -> set := NATCASE.\nInstance natcase_morph : Proper (eq_set==>(eq_set==>eq_set)==>eq_set==>eq_set) natcase.\nProof NATCASE_morph.\n\nLemma natcase_zero : forall b0 bS,\n  natcase b0 bS zero == b0.\napply NATCASE_ZERO.\nQed.\n\nLemma natcase_succ : forall n b0 bS,\n  morph1 bS ->\n  natcase b0 bS (succ n) == bS n.\nintros.\napply NATCASE_SUCC.\nintros.\napply H; trivial.\nQed.\n\nLemma natcase_outside : forall b0 bS n,\n  (forall X, ~ n ∈ NATf' X) ->\n  natcase b0 bS n == empty.\nintros.\nunfold natcase, NATCASE.\napply empty_ext; red; intros.\nrewrite union2_ax in H0; do 2 rewrite cond_set_ax in H0.\ndestruct H0 as [(_,?)|(_,(k,?))].\n (* ~ empty == ZERO *)\n apply H with empty.\n rewrite H0; apply zero_typ.\n\n (* ~ empty == SUCC _ *)\n apply H with (singl k).\n rewrite H0.\n apply succ_typ.\n apply cc_bot_intro.\n apply singl_intro.\nQed.\n\n\nDefinition natfix : (set -> set -> set) -> set -> set := NATREC'.\n\nLemma natfix_morph : Proper ((eq_set ==> eq_set ==> eq_set) ==> eq_set ==> eq_set) natfix.\ndo 3 red; intros.\napply NATREC_morph; trivial.\ndo 2 red; intros.\napply squash_morph.\napply H; trivial.\nQed.\n\nRequire Import ZFfunext.\n  Record natfix_hyps O M U : Prop := natfix_intro {\n    Wo : isOrd O;\n    WMm : morph2 M;\n    WUm : morph2 U;\n    WU_mt : forall o x, empty ∈ U o x;\n    WMtyp : forall o,\n        o ∈ osucc O ->\n        forall f,\n        f ∈ (Π x ∈ cc_bot (TI NATf' o), U o x) ->\n        M o f\n        ∈ (Π x ∈ cc_bot (TI NATf' (osucc o)), U (osucc o) x);\n    WMirr : forall o o' f g,\n        isOrd o ->\n        o ⊆ o' ->\n        o' ∈ osucc O ->\n        f ∈ (Π x ∈ cc_bot (TI NATf' o), U o x) ->\n        g ∈ (Π x ∈ cc_bot (TI NATf' o'), U o' x) ->\n        fcompat (cc_bot (TI NATf' o)) f g ->\n        fcompat (cc_bot (TI NATf' (osucc o))) (M o f) (M o' g);\n    WUmono : forall o o' x,\n        isOrd o ->\n        o ⊆ o' ->\n        o' ∈ osucc O ->\n        x ∈ cc_bot (TI NATf' o) ->\n        U o x ⊆ U o' x\n  }.\n\nLemma natfix_typ : forall O M U,\n    natfix_hyps O M U ->\n    forall o, isOrd o -> o ⊆ O ->\n    natfix M o ∈ (Π x ∈ cc_bot (TI NATf' o), U o x).\nintros.\neapply NATREC'_typ.\n apply (Wo _ _ _ H).\n apply (WMm _ _ _ H).\n apply (WUm _ _ _ H).\n apply (WU_mt _ _ _ H).\n\n intros.\n apply (WMtyp _ _ _ H); trivial.\n apply ole_lts; trivial.\n\n red; intros.\n apply (WMirr _ _ _ H); trivial.\n apply ole_lts; trivial.\n\n intros.\n apply (WUmono _ _ _ H); trivial.\n\n trivial.\n trivial.\nQed.\n\nLemma natfix_irr : forall O M U,\n    natfix_hyps O M U ->\n    forall o o' x, isOrd o -> isOrd o' -> o ⊆ o' -> o' ⊆ O ->\n    x ∈ cc_bot (TI NATf' o) ->\n    cc_app (natfix M o) x == cc_app (natfix M o') x.\nintros.\neapply NATREC'_irr.\n apply (Wo _ _ _ H).\n apply (WMm _ _ _ H).\n apply (WUm _ _ _ H).\n apply (WU_mt _ _ _ H).\n\n intros.\n apply (WMtyp _ _ _ H); trivial.\n apply ole_lts; trivial.\n\n red; intros.\n apply (WMirr _ _ _ H); trivial.\n apply ole_lts; trivial.\n\n intros.\n apply (WUmono _ _ _ H); trivial.\n\n trivial.\n trivial.\n trivial.\n trivial.\n trivial.\nQed.\n\nLemma natfix_unfold : forall O M U,\n    natfix_hyps O M U ->\n    forall o n, isOrd o -> o ⊆ O ->\n    n ∈ TI NATf' (osucc o) ->\n    cc_app (natfix M (osucc o)) n == cc_app (M o (natfix M o)) n.\nintros.\neapply NATREC'_unfold.\n apply (Wo _ _ _ H).\n apply (WMm _ _ _ H).\n apply (WUm _ _ _ H).\n apply (WU_mt _ _ _ H).\n\n intros.\n apply (WMtyp _ _ _ H); trivial.\n apply ole_lts; trivial.\n\n red; intros.\n apply (WMirr _ _ _ H); trivial.\n apply ole_lts; trivial.\n\n intros.\n apply (WUmono _ _ _ H); trivial.\n\n trivial.\n trivial.\n trivial.\nQed.\n\n\nLemma natfix_strict : forall O M U n,\n    natfix_hyps O M U ->\n    ~ (exists X, n ∈ NATf' X) ->\n    forall o,\n       isOrd o -> o ⊆ O -> cc_app (natfix M o) n == empty.\nintros.\neapply NATREC'_strict.\n apply (Wo _ _ _ H).\n apply (WMm _ _ _ H).\n apply (WUm _ _ _ H).\n apply (WU_mt _ _ _ H).\n\n intros.\n apply (WMtyp _ _ _ H); trivial.\n apply ole_lts; trivial.\n\n red; intros.\n apply (WMirr _ _ _ H); trivial.\n apply ole_lts; trivial.\n\n intros.\n apply (WUmono _ _ _ H); trivial.\n\n trivial.\n trivial.\n intro h; apply H0; apply TI_elim in h; auto with *.\n destruct h as (o',?,tyn).\n econstructor; exact tyn.\nQed.\n\nLemma G_NATf' : forall U X, grot_univ U -> X ∈ U -> NATf' X ∈ U.\nintros; apply G_NATf'; trivial.\nQed.\n\nEnd NATM.\n\n(** The final instantiation *)\n\nModule NAT_SN := Make NATM.\nExport NAT_SN.\n\nDefinition test := (\n  typ_NatCase,\n  typ_natfix,\n  natfix_extend,\n  natfix_eq_S,\n  Examples.nat_ind_def,\n  Examples.map_def\n).\n\nPrint Assumptions test.\n", "meta": {"author": "barras", "repo": "cic-model", "sha": "dcc38f3104048aa50d230f819085131b16702d3d", "save_path": "github-repos/coq/barras-cic-model", "path": "github-repos/coq/barras-cic-model/cic-model-dcc38f3104048aa50d230f819085131b16702d3d/SN_NAT_sized.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.27654215343838406}}
{"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.\nRequire Import LLIR.LLIR.\nRequire Import LLIR.Dom.\n\n\nInductive LiveAt: func -> reg -> node -> Prop :=\n  | live_at:\n    forall\n      (f: func) (r: reg) (n: node) (use: node) (p: list node)\n      (PATH: ReversePath f n p use)\n      (NO_DEF: forall (def: node), In def (tl p) -> ~DefinedAt f def r)\n      (USE: UsedAt f use r),\n      LiveAt f r n.\n\nTheorem live_at_succ:\n  forall (f: func) (r: reg) (n: node),\n    LiveAt f r n ->\n    UsedAt f n r\n    \\/\n    exists (s: node), SuccOf f n s /\\ LiveAt f r s.\nProof.\n  intros f r n Hlive; inversion Hlive; subst.\n  inversion PATH; subst.\n  { left; auto. }\n  {\n    right; exists next; split; auto.\n    apply live_at with use p0; auto.\n    intros def Hin.\n    destruct p0; [inversion Hin|].\n    simpl in NO_DEF; simpl in Hin.\n    apply NO_DEF; right; assumption.\n  }\nQed.\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/Liveness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283035, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2765421472757155}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Strings.String.\n\nModule Syntax.\n\nInductive baseCapability : Type :=\n  | iso\n  | trn\n  | ref\n  | val\n  | box\n  | tag.\n\nInductive capability : Type :=\n  | base : baseCapability -> capability\n  | isohat : capability\n  | trnhat : capability. \n\nReserved Notation \"k <; k'\" (at level 80).\n\nInductive subcapability : capability -> capability -> Prop :=\n  | subcap_refl (k : capability) : k <; k\n  | subcap_trans (k k' k'' : capability) : k <; k' -> k' <; k'' -> k <; k''\n  | subcap_isohat_iso : isohat <; base iso\n  | subcap_isohat_trnhat : isohat <; trnhat\n  | subcap_trnhat_trn : trnhat <; base trn\n  | subcap_trnhat_ref : trnhat <; base ref\n  | subcap_trnhat_val : trnhat <; base val\n  | subcap_trn_box : base trn <; base box\n  | subcap_ref_box : base ref <; base box\n  | subcap_val_box : base val <; base box\n  | subcap_iso_tag : base iso <; base tag\n  | subcap_box_tag : base box <; base tag\nwhere \"k <; k'\" := (subcapability k k').\n\nExample all_subcap_tag (k : capability) : k <; base tag :=\n  match k with\n    | isohat => subcap_trans isohat (base iso) (base tag) (subcap_isohat_iso) (subcap_iso_tag)\n    | trnhat => subcap_trans trnhat (base trn) (base tag) (subcap_trnhat_trn) (subcap_trans (base trn) (base box) (base tag) (subcap_trn_box) (subcap_box_tag))\n    | base iso => subcap_iso_tag\n    | base trn => subcap_trans (base trn) (base box) (base tag) (subcap_trn_box) (subcap_box_tag)\n    | base ref => subcap_trans (base ref) (base box) (base tag) (subcap_ref_box) (subcap_box_tag)\n    | base val => subcap_trans (base val) (base box) (base tag) (subcap_val_box) (subcap_box_tag)\n    | base box => subcap_box_tag\n    | base tag => subcap_refl (base tag)\n  end.\n\nDefinition alias (cap : capability) : capability :=\n  match cap with\n    | isohat => base iso\n    | trnhat => base trn\n    | base iso => base tag\n    | base trn => base box\n    | base b => base b\n  end.\n\nInductive sendable : baseCapability -> Prop :=\n  | sendable_tag : sendable tag\n  | sendable_val : sendable val\n  | sendable_iso : sendable iso.\n\nDefinition isSendable (cap : baseCapability) : bool :=\n  match cap with\n    | tag => true\n    | val => true\n    | iso => true\n    | _   => false\n  end.\n\nInductive classId : Type :=\n  | cId : string -> classId.\n\nInductive actorId : Type :=\n  | aId : string -> actorId.\n\nDefinition typeId : Type := classId + actorId.\n\nDefinition classTypeId (C : classId) : typeId := (inl C).\nDefinition actorTypeId (A : actorId) : typeId := (inr A).\n\nInductive ponyType : Type :=\n  | type (s : typeId) (k : capability).\n\nInductive aliasedType : Type :=\n  | aType (s : typeId) (b : baseCapability).\n\nDefinition asPonyType (aT : aliasedType) : ponyType :=\n  match aT with\n    | aType s b => type s (base b)\n  end.\n\nDefinition hatCap (b : baseCapability) : capability :=\n  match b with\n  | iso => isohat\n  | trn => trnhat\n  | b   => base b\n  end.\n\nDefinition hat (aT : aliasedType) : ponyType :=\n  match aT with\n    | aType s b => type s (hatCap b)\n  end.\n\nLemma hat_preserves_type_id :\n  forall S S' : typeId,\n  forall b : baseCapability,\n  forall k : capability,\n  hat (aType S b) = type S' k\n    -> S = S'.\nProof.\n  intros S S' b k.\n  (* Case analysis of b, compute the value of hat, introduce the hat equality,\n  * argue by constructors that the type IDs are equal *)\n  destruct b; compute; intro H; inversion H; reflexivity.\n  Qed.\n\nInductive var : Type :=\n  | variable : string -> var.\n\nOpen Scope string_scope.\n\nDefinition this : var := variable \"this\".\n\nClose Scope string_scope.\n\nInductive temp : Type :=\n  | temporary : string -> temp.\n\nInductive path : Type :=\n  | use (x : var)\n  | consume (x : var)\n  | useTemp (t : temp).\n\nInductive fieldId : Type :=\n  | fId : string -> fieldId.\n\nDefinition fieldOfPath : Type := prod path fieldId.\n\nInductive methodId : Type :=\n  | mId : string -> methodId.\n\nInductive behaviourId : Type :=\n  | bId : string -> behaviourId.\n\nInductive constructorId : Type :=\n  | cnId : string -> constructorId.\n\nInductive aliased { X : Type } : Type :=\n  | aliasOf (x : X).\n\nInductive rhs : Type :=\n  | rhsPath (p : path)\n  | fieldAssign (pf : fieldOfPath) (ap : @aliased path)\n  | methodCall (rcvr : @aliased path) (m : methodId) (args : list (@aliased path))\n  | behaviourCall (rcvr : @aliased path) (b : behaviourId) (args : list (@aliased path))\n  | constructorCall (rcvrType : typeId) (k : constructorId) (args : list (@aliased path)).\n\nInductive expression : Type :=\n  | varDecl (x : var)\n  | assign (x : var) (arhs : @aliased rhs)\n  | tempAssign (t : temp) (pf : fieldOfPath).\n\nInductive expressionSeq : Type :=\n  | final : path -> expressionSeq\n  | seq : expression -> expressionSeq -> expressionSeq.\n\n(* Closed-world encoding used for polymorphic judgements *)\nInductive cw_encoding : Type :=\n  | ePath : path -> cw_encoding\n  | eFieldOfPath : fieldOfPath -> cw_encoding\n  | eAlias : cw_encoding -> cw_encoding\n  | eExpr : expression -> cw_encoding\n  | eRhs : rhs -> cw_encoding.\n\nDefinition eAPaths (aPaths : list (@aliased path)) : list cw_encoding := map (fun ap => match ap with | aliasOf p =>  eAlias (ePath p) end) aPaths.\n\nEnd Syntax.\n\nRequire Import Coq.Structures.Equalities.\n\nModule DecidableVar.\nInclude (UsualDecidableTypeBoth with Definition t := Syntax.var).\nScheme Equality for Syntax.var.\nEnd DecidableVar.\n\nModule DecidableTemp.\nInclude (UsualDecidableTypeBoth with Definition t := Syntax.temp).\nScheme Equality for Syntax.temp.\nEnd DecidableTemp.\n\nModule DecidableVarTemp.\nInclude (UsualDecidableTypeBoth with Definition t := sum Syntax.var Syntax.temp).\nEnd DecidableVarTemp.\n\nModule DecidableField.\nInclude (UsualDecidableTypeBoth with Definition t := Syntax.fieldId).\nScheme Equality for Syntax.fieldId.\nEnd DecidableField.\n\nModule DecidableConstructor.\nInclude (UsualDecidableTypeBoth with Definition t := Syntax.constructorId).\nScheme Equality for Syntax.constructorId.\nEnd DecidableConstructor.\n\nModule DecidableMethod.\nInclude (UsualDecidableTypeBoth with Definition t := Syntax.methodId).\nScheme Equality for Syntax.methodId.\nEnd DecidableMethod.\n\nModule DecidableBehaviour.\nInclude (UsualDecidableTypeBoth with Definition t := Syntax.behaviourId).\nScheme Equality for Syntax.behaviourId.\nEnd DecidableBehaviour.\n\nModule DecidableClass.\nInclude (UsualDecidableTypeBoth with Definition t := Syntax.classId).\nScheme Equality for Syntax.classId.\nEnd DecidableClass.\n\nModule DecidableActor.\nInclude (UsualDecidableTypeBoth with Definition t := Syntax.actorId).\nScheme Equality for Syntax.actorId.\nEnd DecidableActor.\n\nRequire Import Coq.FSets.FMapInterface.\nRequire Import Coq.FSets.FMapFacts.\n\nFrom Pony Require Import ArrayMap.\n\nModule ArrayVarMap := ArrayMap DecidableVar.\nDefinition arrayVarMap := ArrayVarMap.t.\n\nModule Program (Map : WSfun).\n\nExport Syntax.\n\nDefinition argValues (avMap : arrayVarMap Syntax.aliasedType) : list Syntax.ponyType :=\n  map Syntax.asPonyType (map snd (ArrayVarMap.elements avMap)).\n\nModule FieldMap := Map DecidableField.\nDefinition fieldMap := FieldMap.t.\nModule FieldMapFacts := WFacts_fun DecidableField FieldMap.\n\nModule ConstructorMap := Map DecidableConstructor.\nDefinition constructorMap := ConstructorMap.t.\n\nModule MethodMap := Map DecidableMethod.\nDefinition methodMap := MethodMap.t.\n\nModule BehaviourMap := Map DecidableBehaviour.\nDefinition behaviourMap := BehaviourMap.t.\n\nModule ClassMap := Map DecidableClass.\nDefinition classMap := ClassMap.t.\nModule ClassMapFacts := WFacts_fun DecidableClass ClassMap.\n\nModule ActorMap := Map DecidableActor.\nDefinition actorMap := ActorMap.t.\nModule ActorMapFacts := WFacts_fun DecidableActor ActorMap.\n\nInductive constructorDef : Type :=\n  | cnDef (args : arrayVarMap Syntax.aliasedType) (body : Syntax.expressionSeq).\n\nInductive methodDef : Type :=\n  | mDef\n      (receiverCap : Syntax.baseCapability)\n      (args : arrayVarMap Syntax.aliasedType)\n      (returnType : Syntax.ponyType)\n      (body : Syntax.expressionSeq).\n\nInductive behaviourDef : Type :=\n  | bDef (args : arrayVarMap Syntax.aliasedType) (body : Syntax.expressionSeq).\n\nRecord classDef : Type :=\n  cDef\n  { classFields : fieldMap Syntax.aliasedType\n  ; classConstructors : constructorMap constructorDef\n  ; classMethods : methodMap methodDef\n  }.\n\nRecord actorDef : Type :=\n  aDef \n  { actorFields : fieldMap Syntax.aliasedType\n  ; actorConstructors : constructorMap constructorDef\n  ; actorMethods : methodMap methodDef\n  ; actorBehaviours : behaviourMap behaviourDef\n  }.\n\nRecord program : Type :=\n  prog\n  { classes : classMap classDef\n  ; actors : actorMap actorDef\n  }.\n\nDefinition fieldLookup { P : program } (s : Syntax.typeId) (f : Syntax.fieldId) (t : Syntax.aliasedType) : Prop\n  := (exists (c : Syntax.classId) (cd : classDef), s = inl c /\\ ClassMap.MapsTo c cd (classes P) /\\ FieldMap.MapsTo f t (classFields cd))\n      \\/ (exists (a : Syntax.actorId) (ad : actorDef), s = inr a /\\ ActorMap.MapsTo a ad (actors P) /\\ FieldMap.MapsTo f t (actorFields ad)).\n\nLemma fieldLookup_func :\n  forall P : program,\n  forall s : Syntax.typeId,\n  forall f : Syntax.fieldId,\n  forall t1 t2 : Syntax.aliasedType,\n  @fieldLookup P s f t1\n    -> @fieldLookup P s f t2\n    -> t1 = t2.\nProof.\n  intros P s f t1 t2.\n  unfold fieldLookup.\n  intros lookup_s_f_t1 lookup_s_f_t2.\n\n  destruct (lookup_s_f_t1, lookup_s_f_t2) as [ [ t1_c | t1_a ] [ t2_c | t2_a ] ].\n  { destruct (t1_c, t2_c) as [ [ c1 [ cd1 [ c_eq_c1 [ c1_MapsTo_cd1 f_MapsTo_t1 ] ] ] ] [ c2 [ cd2 [ c_eq_c2 [ c2_MapsTo_cd2 f_MapsTo_t2 ] ] ] ] ].\n    \n    assert (c1 = c2) as c1_eq_c2.\n    { assert (inl c1 = inl c2) as H by (transitivity s; auto).\n      now inversion H.\n    } \n\n    assert (cd1 = cd2) as cd1_eq_cd2.\n    { apply ClassMapFacts.MapsTo_fun with (m:=classes P) (x:=c1).\n      assumption.\n      rewrite c1_eq_c2.\n      assumption.\n    }\n\n    apply FieldMapFacts.MapsTo_fun with (m:=classFields cd1) (x:=f).\n    assumption.\n    rewrite cd1_eq_cd2.\n    assumption.\n  }\n  { destruct t1_c as [ c [ _ [ bad1 _ ] ] ].\n    destruct t2_a as [ a [ _ [ bad2 _ ] ] ].\n    assert (inl c = inr a) as bad by (transitivity s; auto).\n    contradict bad.\n    discriminate.\n  }\n  { destruct t1_a as [ a [ _ [ bad1 _ ] ] ].\n    destruct t2_c as [ c [ _ [ bad2 _ ] ] ].\n    assert (inl c = inr a) as bad by (transitivity s; auto).\n    contradict bad.\n    discriminate.\n  }\n  { destruct (t1_a, t2_a) as [ [ a1 [ ad1 [ a_eq_a1 [ a1_MapsTo_ad1 f_MapsTo_t1 ] ] ] ] [ a2 [ ad2 [ a_eq_a2 [ a2_MapsTo_ad2 f_MapsTo_t2 ] ] ] ] ].\n    \n    assert (a1 = a2) as a1_eq_a2.\n    { assert (inr a1 = inr a2) as H by (transitivity s; auto).\n      now inversion H.\n    } \n\n    assert (ad1 = ad2) as ad1_eq_ad2.\n    { apply ActorMapFacts.MapsTo_fun with (m:=actors P) (x:=a1).\n      assumption.\n      rewrite a1_eq_a2.\n      assumption.\n    }\n\n    apply FieldMapFacts.MapsTo_fun with (m:=actorFields ad1) (x:=f).\n    assumption.\n    rewrite ad1_eq_ad2.\n    assumption.\n  }\nQed.\n\nDefinition methodLookup { P : program } (s : Syntax.typeId) (mId : Syntax.methodId) (mDef : methodDef) : Prop\n  := exists (c : Syntax.classId) (cd : classDef), s = inl c /\\ ClassMap.MapsTo c cd (classes P) /\\ MethodMap.MapsTo mId mDef (classMethods cd)\n      \\/ exists (a : Syntax.actorId) (ad : actorDef), s = inr a /\\ ActorMap.MapsTo a ad (actors P) /\\ MethodMap.MapsTo mId mDef (actorMethods ad).\n\nDefinition behaviourLookup { P : program } (s : Syntax.typeId) (bId : Syntax.behaviourId) (bDef : behaviourDef) : Prop\n  := exists (a : Syntax.actorId) (ad : actorDef), s = inr a /\\ ActorMap.MapsTo a ad (actors P) /\\ BehaviourMap.MapsTo bId bDef (actorBehaviours ad).\n\nDefinition constructorLookup { P : program } (s : Syntax.typeId) (kId : Syntax.constructorId) (kDef : constructorDef) : Prop\n  := exists (c : Syntax.classId) (cd : classDef), s = inl c /\\ ClassMap.MapsTo c cd (classes P) /\\ ConstructorMap.MapsTo kId kDef (classConstructors cd)\n      \\/ exists (a : Syntax.actorId) (ad : actorDef), s = inr a /\\ ActorMap.MapsTo a ad (actors P) /\\ ConstructorMap.MapsTo kId kDef (actorConstructors ad).\n\nEnd Program.\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/Language.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.27654214727571547}}
{"text": "Require Import Coqlib.\nRequire Import Any.\nRequire Import STS.\nRequire Import Behavior.\nRequire Import ModSem.\nRequire Import Skeleton.\nRequire Import PCM.\nRequire Import HoareDef.\nRequire Import ProofMode.\nRequire Import SimModSem.\nRequire Import STB.\n\nSet Implicit Arguments.\n\n\n\n\n\n\n\nSection AUX.\n  Definition invRA: URA.t := Excl.t unit.\n\n  Definition inv_token: (@URA.car invRA) := Some tt.\n\n  Context `{Σ: GRA.t}.\n  Context `{@GRA.inG invRA Σ}.\n\n  Definition inv_closed: iProp := OwnM inv_token%I.\n\n  Lemma inv_closed_unique\n    :\n      inv_closed -∗ inv_closed -∗ False\n  .\n  Proof.\n    unfold inv_closed, inv_token.\n    iIntros \"H0 H1\".\n    iCombine \"H0 H1\" as \"H\". iOwnWf \"H\" as WF. exfalso.\n    repeat ur in WF. ss.\n  Qed.\n\n  Definition inv_le\n             A (le: A -> A -> Prop)\n    :\n      (A + Any.t * Any.t) -> (A + Any.t * Any.t) -> Prop :=\n    fun x0 x1 =>\n      match x0, x1 with\n      | inl a0, inl a1 => le a0 a1\n      | inr st0, inr st1 => st0 = st1\n      | _, _ => False\n      end.\n\n  Lemma inv_le_PreOrder A (le: A -> A -> Prop)\n        (PREORDER: PreOrder le)\n    :\n      PreOrder (inv_le le).\n  Proof.\n    econs.\n    { ii. destruct x; ss. refl. }\n    { ii. destruct x, y, z; ss.\n      { etrans; et. }\n      { subst. auto. }\n    }\n  Qed.\n\n  Definition mk_fspec_inv (fsp: fspec): fspec :=\n    @mk_fspec\n      _\n      (meta fsp)\n      fsp.(measure)\n      (fun mn x varg_src varg_tgt =>\n         inv_closed ** (precond fsp) mn x varg_src varg_tgt)\n      (fun mn x vret_src vret_tgt =>\n         inv_closed ** (postcond fsp) mn x vret_src vret_tgt).\n\n  Lemma fspec_weaker_fspec_inv_weakker (fsp0 fsp1: fspec)\n        (WEAKER: fspec_weaker fsp0 fsp1)\n    :\n      fspec_weaker (mk_fspec_inv fsp0) (mk_fspec_inv fsp1).\n  Proof.\n    ii. exploit WEAKER. i. des. exists x_tgt. esplits; ss; et.\n    { ii. iIntros \"[INV H]\". iSplitL \"INV\"; ss.\n      iApply PRE. iExact \"H\". }\n    { ii. iIntros \"[INV H]\". iSplitL \"INV\"; ss.\n      iApply POST. iExact \"H\". }\n  Qed.\n\nEnd AUX.\n", "meta": {"author": "alxest", "repo": "CCR", "sha": "edcda8faae6580581e8e5b28050d755bcb29f55f", "save_path": "github-repos/coq/alxest-CCR", "path": "github-repos/coq/alxest-CCR/CCR-edcda8faae6580581e8e5b28050d755bcb29f55f/spc/Invariant.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241632752916, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2765421411130468}}
{"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_giveup.\nRequire Import bst.giveup_lib.\nRequire Import bst.giveup_traverse.\nRequire Import VST.atomics.verif_lock_atomic.\nRequire Import VST.floyd.library.\n\n(* Write insert_spec following the template style.\nWe need to write some specs of helper functions: insertOp, traverse and findnext\n1) insert_spec:\n           ∀ t. <bst_ref p | bst t>  insert2 (treebox t, int x, void *value)\n                <t'. bst_ref p | bst t' ∧ insert t k v = t' >\n2) insertOp_spec:\n          {N /\\  x \\in range} insertOp(pn *pn, int x, void *value)\n          {t'. N ∧ t' = (<[x:=k]> t) }\n3) traverse_spec:\n          < ...  | bst t> traverse(pn *pn, int x, void *value)\n          <v. bst t /\\ lock_inv >\n4) findnext_spec:\n          {x \\in range  /\\ ...} findNext(pn *pn, int x, void *value)\n          {v. ((v = 1 /\\ ....) \\/ (v = 0 /\\  ...)) /\\  ... } *)\n\n(* insert spec *)\nProgram Definition lookup_spec :=\n  DECLARE _lookup\n  ATOMIC TYPE (rmaps.ConstType (val * share * val * 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; 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) | (tree_rep g g_root M)\n  POST[ tptr tvoid ]\n  EX ret: val,\n    PROP ()\n    LOCAL ()\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 spawn_spec := DECLARE _spawn spawn_spec.\n\nDefinition Gprog : funspecs :=\n    ltac:(with_library prog [acquire_spec; release_spec; makelock_spec;\n     surely_malloc_spec; inrange_spec; lookup_spec;\n     traverse_spec; findnext_spec; treebox_new_spec]).\n\nCheck empty_range.\n\nCheck range_incl.\nLemma range_info_incl: forall tg o ri rn r_root,\n  range_info_in_tree ((ri, rn), o) r_root tg -> keys_in_range_ghost tg r_root -> sorted_ghost_tree tg ->\n  range_incl rn r_root = true.\nProof.\n  induction 1; intros.\n  - inv H. apply range_incl_refl.\n  - inv H. apply range_incl_refl.\n  - apply keys_in_range_ghost_subtrees in H0 as (? & ? & ?); auto.\n    inv H1.\n    unfold range_incl in *; destruct rn, range; simpl in *.\n    apply andb_prop in IHrange_info_in_tree as [->]; auto.\n    eapply less_than_equal_trans; first eassumption.\n    apply less_than_to_less_than_equal.\n    apply andb_prop in H0 as [_ ?]; auto.\n  - apply keys_in_range_ghost_subtrees in H0 as (? & ? & ?); auto.\n    inv H1.\n    unfold range_incl in *; destruct rn, range; simpl in *.\n    apply andb_prop in IHrange_info_in_tree as [? ->]; auto.\n    rewrite andb_true_r.\n    eapply less_than_equal_trans; last eassumption.\n    apply less_than_to_less_than_equal.\n    apply andb_prop in H0 as [? _]; auto.\nQed.\n\nLemma range_info_not_in_gmap: forall tg x ri rn r_root,\n    sorted_ghost_tree tg -> key_in_range x rn = true ->\n    keys_in_range_ghost tg r_root ->\n    range_info_in_tree ((ri, rn), Some None) r_root tg -> tree_to_gmap tg !! x = None.\nProof.\n  induction tg; intros; simpl.\n  { apply lookup_empty. }\n  apply keys_in_range_ghost_subtrees in H1 as (? & ? & ?); auto.\n  inv H; inv H2.\n  - inv H5.\n  - exploit range_info_incl; eauto; intros Hrange.\n    pose proof (key_in_range_incl _ _ _ H0 Hrange) as Hx.\n    apply andb_prop in Hx as []; simpl in *.\n    rewrite -> lookup_insert_ne by lia.\n    rewrite lookup_union_None; split.\n    + eapply IHtg1; eauto.\n    + destruct (eq_dec (tree_to_gmap tg2 !! x) None); auto.\n      apply In_tree_to_gmap, Hltr in n; lia.\n  - exploit range_info_incl; eauto; intros Hrange.\n    pose proof (key_in_range_incl _ _ _ H0 Hrange) as Hx.\n    apply andb_prop in Hx as []; simpl in *.\n    rewrite -> lookup_insert_ne by lia.\n    rewrite lookup_union_None; split.\n    + destruct (eq_dec (tree_to_gmap tg1 !! x) None); auto.\n      apply In_tree_to_gmap, Hgtl in n; lia.\n    + eapply IHtg2; eauto.\nQed.\n\nLemma range_info_in_tree_In: forall tg x v ga gb rn r_root,\n    range_info_in_tree (rn, Some (Some (x, v, ga, gb))) r_root tg ->\n    In_ghost x tg.\nProof.\n  induction tg; intros.\n  { inv H. inv H0. }\n  inv H.\n  - inv H1. now constructor 1.\n  - constructor 2. eapply IHtg1; eauto.\n  - constructor 3. eapply IHtg2; eauto.\nQed.\n\nLemma range_info_in_gmap: forall x v ga gb tg rn r_root,\n    sorted_ghost_tree tg ->\n    range_info_in_tree (rn, Some (Some (x, v, ga, gb))) r_root tg ->\n    tree_to_gmap tg !! x = Some v.\nProof.\n  induction tg; intros; simpl.\n  { inv H0. inv H1. }\n  inv H. inv H0.\n  - inv H1. apply lookup_insert.\n  - exploit Hgtl. { eapply range_info_in_tree_In; eauto. }\n    intros; rewrite -> lookup_insert_ne by lia.\n    eapply lookup_union_Some_l, IHtg1; eauto.\n  - exploit Hltr. { eapply range_info_in_tree_In; eauto. }\n    intros; rewrite -> lookup_insert_ne by lia.\n    rewrite lookup_union_r.\n    + eapply IHtg2; eauto.\n    + destruct (eq_dec (tree_to_gmap tg1 !! x) None); auto.\n      apply In_tree_to_gmap, Hgtl in n; lia.\nQed.\n\nLemma ghost_tree_rep_public_half_ramif: forall tg g_root p lk pn lockn r_root g g_in,\n    find_ghost_set tg g_root p lk !! g_in = Some (pn, lockn) ->\n    ghost_tree_rep tg p g_root lk g r_root |--\n    EX r a, !! (range_info_in_tree ((p, lk, r), a) r_root tg) &&\n                       (ghost_tree_rep tg p g_root lk g r_root).\nProof.\n  intros.\n  generalize dependent g_root.\n  generalize dependent lk.\n  generalize dependent p.\n  induction tg; intros p lk g_root; simpl in *; intros; unfold ltree. \n  - destruct (decide(g_root = g_in)).\n    + subst.\n      rewrite lookup_singleton in H.\n      subst.\n      iIntros \"(H1 & H2)\".\n      iExists _, _. iFrame.\n      iPureIntro. (split; auto); by econstructor.\n    + eapply lookup_singleton_None with (x:= (p, lk)) in n.\n      rewrite H in n. inversion n.\n  - destruct r_root.\n    destruct (decide(g_root = g_in)); Intros pt.\n    + subst.\n      apply lookup_insert_rev in H.\n      inversion H; subst.\n      iIntros \"(((H & H1) & H2) & H3)\".\n      iExists _, _. iFrame \"H2 H3\".\n      iSplit. iPureIntro. by econstructor.\n      iExists _. iFrame.\n    + apply lookup_insert_Some in H.\n      destruct H.\n      * destruct H; rewrite H in n1; contradiction.\n      * destruct H.\n        rewrite lookup_union_Some_raw in H0.\n        destruct H0.\n        ** destruct tg1. destruct tg2.\n           simpl in *; unfold ltree.\n           *** rewrite lookup_singleton_Some in H0.\n               iIntros \"(((H & H1) & H2) & (H3 & H4))\".\n               iExists _, _. iFrame \"H2 H3 H4\".\n               iSplit. iPureIntro. by constructor. \n               iExists _. iFrame \"H H1\".\n           *** simpl in *; unfold ltree.\n               rewrite lookup_singleton_Some in H0.\n               destruct H0. inversion H1. subst.\n               iIntros \"(((H & H1) & (H2 & H3)) & H4)\".\n               iExists _, _.\n               iSplit. iPureIntro. by constructor. \n               iExists _. iFrame \"H H1 H2 H3 H4\".\n           *** simpl in *; unfold ltree. clear IHtg2.\n               specialize (IHtg1 v v0 g0).\n               specialize (IHtg1 H0).\n               simpl in IHtg1.\n               iIntros \"(((H & H1) & H2) & H4)\".\n               iExists _, _.\n               iSplit. iPureIntro. by constructor. \n               iExists _. iFrame \"H H1 H2 H4\".\n        ** destruct H0. clear IHtg1.\n           specialize (IHtg2 v2 v3 g1).\n           specialize (IHtg2 H1).\n           iIntros \"(((H & H1) & H2) & H3)\".\n           iExists _, _.\n           iSplit. iPureIntro. by constructor. \n           iExists _. iFrame \"H H1 H2 H3\".\nQed.\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.\n  Intros np.\n  forward_call (t_struct_pn, gv).\n  Intros nb.\n  Intros lsh.\n  forward.\n  forward.\n  sep_apply in_tree_duplicate.\n  set (AS := atomic_shift _ _ _ _ _).\n  set Q1:= fun (b : ( bool * (val * (share * (gname * node_info))))%type) =>\n              if b.1 then AS else AS.\n  (* traverse(pn, x, value) *)\n  forward_call (nb, np, lock, x, nullval, gv, g, g_root, Q1).\n  {\n    Exists Vundef. entailer !.\n    iIntros \"(((H1 & H2) & H3) & H4)\". iCombine \"H2 H1 H3 H4\" as \"H\".\n    iVST.\n    apply sepcon_derives; [| cancel_frame].\n    iIntros \"AU\".\n    unfold atomic_shift; iAuIntro; unfold atomic_acc; simpl.\n    iMod \"AU\" as (m) \"[Hm HClose]\".\n    iModIntro. iExists _. iFrame.\n    iSplit; iFrame.\n    iIntros \"H1\".\n    iSpecialize (\"HClose\" with \"H1\"). auto.\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  Intros pt.\n  destruct pt as (fl & (p & (gsh & (g_in & r)))).\n  simpl in H5.\n  destruct fl.\n  destruct H5 as (HGh & HP).\n  - unfold Q1.\n    forward_if(\n        PROP ( )\n          LOCAL (temp _v nullval; temp _t'2 Vtrue; temp _t'7 np; temp _pn__2 nb; gvars gv;\n            temp _t b; temp _x (vint x))\n          SEP (AS * mem_mgr gv * \n                 data_at Ews t_struct_pn (p, p) nb * in_tree g g_in p r.1.1.2 *\n                 in_tree g g_root np lock * malloc_token Ews t_struct_pn nb *\n                 data_at sh (tptr t_struct_tree_t) np b *\n                 field_at lsh t_struct_tree_t (DOT _lock) lock np * \n                 node_lock_inv_pred g p g_in r)).\n    + pose proof (Int.one_not_zero); easy.\n    + simpl. forward. entailer !.\n    + unfold node_lock_inv_pred, node_rep, tree_rep_R.\n      rewrite -> if_true by auto.\n      Intros.\n      forward.\n      (* alloc a pointer of lock for pointer p*)\n      gather_SEP AS (in_tree g g_in p _).\n      viewshift_SEP 0 (AS * (in_tree g g_in p r.1.1.2) * (EX lsh, !!(readable_share lsh) &&\n                       field_at lsh t_struct_tree_t (DOT _lock) r.1.1.2 p)).\n      { go_lower. apply lock_alloc. }\n      Intros lsh1.\n      forward.\n      forward_call (r.1.1.2, Q nullval).\n      {\n        iIntros \"(((((((((((((((AU & H1) & H2) & H3) & H4) & H5) & H6) & H7) & H8) & H9) & G1) & G2) & G3) & G4) & G5) & _)\".\n        iCombine \"AU H1 H2\" as \"HH1\".\n        iCombine \"G1 G2 H9 G3 G4 G5\" as \"HH2\".\n        iCombine \"HH1 HH2\" as \"HH3\".\n        iVST.\n        rewrite <- 5sepcon_assoc; rewrite <- sepcon_comm.\n        apply sepcon_derives; [| cancel_frame].\n        unfold atomic_shift; iIntros \"((AU & (#H1 & H2)) & (H3 & (H4 & (H5 & (H6 & (H7 & _))))))\"\n        ; iAuIntro; unfold atomic_acc; simpl.\n        iMod \"AU\" as (m) \"[Hm HClose]\".\n        iModIntro.\n        iPoseProof (tree_rep_insert _ g g_root g_in p r.1.1.2 with \"[$Hm $H1]\") as \"InvLock\".\n        iDestruct \"InvLock\" as (R O) \"((K1 & K2) & K3)\".\n        iDestruct \"K2\" as (lsh2) \"(% & (K2 & KInv))\".\n        iDestruct \"KInv\" as (bl) \"(KAt & KInv)\".\n        destruct bl.\n        ++ iExists (). iFrame \"KAt\".\n           iSplit.\n           {\n             iIntros \"H\".\n             iFrame.\n             iAssert (ltree g g_in p r.1.1.2 (node_lock_inv_pred g p g_in (R, Some O)))\n               with \"[H K2]\" as \"HInv\".\n             { iExists _. iSplit; try done. iFrame \"K2\". iExists true. iFrame. }\n             iSpecialize (\"K3\" with \"[$HInv $K1]\").\n             iDestruct \"K3\" as \"(K3 & _)\".\n             iSpecialize (\"HClose\" with \"K3\").\n             iFrame.\n           }\n           iIntros (_) \"(H & _)\".\n           iDestruct \"K3\" as \"[_ K3]\".\n           iPoseProof (public_agree g_in r (R, Some O) with \"[$K1 $H5]\") as \"%Hx\".\n           destruct r.\n           inversion Hx; subst.\n           simpl.\n           (* join lsh1 with lsh2 = Lsh *)\n           destruct H10 as (Hf & Hrs).\n           iPoseProof (lock_join with \"[$H2 $K2]\") as \"K2\"; try iSplit; auto.\n           iDestruct \"K2\" as (Lsh) \"(% & K2)\".\n           (* done pushing back pointer of lock into ltree *)\n           iAssert (ltree g g_in p R.1.2 (node_lock_inv_pred g p g_in (R, Some O)))\n             with \"[H3 H4 H5 H6 H7 K2 H]\" as \"LT\".\n           { \n             iExists Lsh. iFrame. iSplit; try done.\n             iExists false; iFrame \"H1 H H3 H4 H5 H6 H7\".\n             iSplit. try done. \n             unfold tree_rep_R. rewrite -> if_true; auto.\n           }\n            unfold ltree.\n            iSpecialize (\"K3\" with \"[$K1 $LT]\").\n            iDestruct \"K3\" as \"(K3 & _)\".\n            iDestruct \"HClose\" as \"(_ & HClose)\".\n            iSpecialize (\"HClose\" $! nullval).\n            iApply \"HClose\".\n            unfold tree_rep at 1.\n            iDestruct \"K3\" as (tg p1 lk1) \"((%K3 & K4) & K5)\".\n            destruct K3 as (K31 & K32 & K33 & K34).\n            iPoseProof (node_exist_in_tree g (find_ghost_set tg g_root p1 lk1) p \n                         with \"[H1 K5]\") as \"%Hy\". \n            { iFrame \"H1\". iFrame. }\n            iPoseProof (ghost_tree_rep_public_half_ramif _ _ _ _ _ _ (Neg_Infinity, Pos_Infinity)\n                                                         with \"[$K4]\") as \"GT\".\n            { apply Hy. }\n            iDestruct \"GT\" as (r a) \"(%GT1 & GT2)\".\n            (*r : range, a : ghost_info === Some None \\/ Some (Some....) *)\n            simpl in *.\n            iFrame.\n            iSplit.\n            iPureIntro.\n            simpl in *. \n            subst.\n            Check range_info_not_in_gmap.\n            erewrite -> (range_info_not_in_gmap _ _ _ r (Neg_Infinity, Pos_Infinity)); eauto. \n            eapply key_in_range_incl. apply H1.\n            assert (range_incl R.2 r = true). admit. auto.\n            assert (a = Some None). admit.\n            subst; eauto.\n            (* need to have range_incl R.2 r = true --- R.2 in r *)\n            Check @sepalg.join node_info (@Join_G node_ghost) (R, Some O) _ (p1, lk1, r, a).\n            assert ((∃ x : node_info, @sepalg.join node_info (@Join_G node_ghost) (R, Some O) x (p1, lk1, r, a))). {\n              Search sepalg.join .\n              unfold sepalg.join. unfold Join_G. auto.\n              admit.\n           }\n           iExists _, _, _. iFrame. iSplit; done. \n         ++ (* contradiction *)\n           unfold node_lock_inv_pred at 1.\n           iDestruct \"KInv\" as \"(? & KInv)\".\n           unfold node_rep.\n           iDestruct \"KInv\" as \"((((((? & KInv) & ?) & ?) & ?) & ?) & ?)\".\n           iPoseProof (field_at_conflict Ews t_struct_tree_t (DOT _t) p\n                      with \"[$H3 $KInv]\") as \"HF\"; eauto; simpl; lia.\n      }\n     (* free *)\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.\n     Exists nullval np lsh. entailer !.\n  - simpl in H2.\n    unfold Q1.\n    destruct H5 as ( ?  & v2 & g21 & g22 & ?).\n    simpl.\n    forward_if (\n        PROP ( )\n     LOCAL (temp _v v2;temp _t'2 Vfalse; temp _t'7 np; temp _pn__2 nb; gvars gv; temp _t b; \n     temp _x (vint x))\n     SEP (AS; mem_mgr gv; seplog.emp; data_at Ews t_struct_pn (p, p) nb; in_tree g g_in p r.1.1.2;\n     my_half g_in Tsh r *\n       (!! (repable_signed (number2Z r.1.2.1)\n          ∧ repable_signed (number2Z r.1.2.2) ∧ is_pointer_or_null r.1.1.2) &&\n          field_at Ews t_struct_tree_t (DOT _t) r.1.1.1 p * \n     field_at Ews t_struct_tree_t (DOT _min) (vint (number2Z r.1.2.1)) p *\n     field_at Ews t_struct_tree_t (DOT _max) (vint (number2Z r.1.2.2)) p *\n     malloc_token Ews t_struct_tree_t p * in_tree g g_in p r.1.1.2 *\n     (EX (ga gb : gname) (x0 : Z) (v0 pa pb locka lockb : val),\n       !! (r.2 = Some (Some (x0, v0, ga, gb))\n           ∧ Int.min_signed ≤ x0 ≤ Int.max_signed\n             ∧ is_pointer_or_null pa\n               ∧ is_pointer_or_null locka\n                 ∧ is_pointer_or_null pb\n                   ∧ is_pointer_or_null lockb ∧ tc_val (tptr Tvoid) v0 ∧ key_in_range x0 r.1.2 = true) &&\n     data_at Ews t_struct_tree (vint x0, (v0, (pa, pb))) r.1.1.1 *\n     malloc_token Ews t_struct_tree r.1.1.1 * in_tree g ga pa locka * in_tree g gb pb lockb *\n     in_tree g g_root np lock * malloc_token Ews t_struct_pn nb * data_at sh (tptr t_struct_tree_t) np b* \n     field_at lsh t_struct_tree_t (DOT _lock) lock np)))).\n    + unfold node_lock_inv_pred, node_rep, tree_rep_R.\n      rewrite -> if_false; auto.\n      simpl in H1, H2, H3, H4. simpl.\n      Intros g1' g2' x1 v1' p1 p2 lock1 lock2.\n      forward. forward. forward.\n      Exists g1' g2' x1 v1' p1 p2 lock1 lock2.\n      entailer !. apply derives_refl.\n    + pose proof Int.one_not_zero; easy.\n    + Intros g1 g2 x1 v1 p1 p2 lock1 lock2.\n      forward.\n      gather_SEP AS (in_tree g g_in p _).\n      viewshift_SEP 0 (AS * (in_tree g g_in p r.1.1.2) * (EX lsh, !!(readable_share lsh) &&\n                       field_at lsh t_struct_tree_t (DOT _lock) r.1.1.2 p)).\n      { go_lower. apply lock_alloc. }\n      Intros lsh1.\n      forward.\n      forward_call (r.1.1.2, Q v2).\n      {\n        iIntros \"(((((((((((((((((((AU & H1) & H2) & H3) & _) & H4) & H5) & H6) & H7) & H8) & H9) & G1) & G2) & G3) & G4) & G5) & G6) & G7) & G8) & G9)\".\n        iCombine \"AU H1 H2 H5 H6 H7 H8 H9 G2 G3 G4 G5\" as \"HH\".\n        iVST.\n        rewrite <- 6sepcon_assoc; rewrite <- sepcon_comm.\n        apply sepcon_derives; [| cancel_frame].\n        unfold atomic_shift; iIntros \"(AU & (#HT & (H1 & (H2 & (H3 & (H4 & (H5 & (H6 & (H7 & (H8 & (#HT1 & #HT2)))))))))))\"; iAuIntro; unfold atomic_acc; simpl.\n        iMod \"AU\" as (m) \"[Hm HClose]\".\n        iModIntro.\n        iPoseProof (tree_rep_insert _ g g_root g_in p r.1.1.2 x v2 p1 p2 lock1 lock2 with \"[$Hm $HT]\") as \"InvLock\".\n        iDestruct \"InvLock\" as (R O) \"((K1 & K2) & K3)\".\n        iDestruct \"K2\" as (lsh2) \"(% & (K2 & KInv))\".\n        iDestruct \"KInv\" as (bl) \"(KAt & KInv)\".\n        destruct bl.\n        + iExists ().\n          iFrame \"KAt\".\n          iSplit.\n          { iIntros \"H\". iFrame.\n            iAssert (ltree g g_in p r.1.1.2 (node_lock_inv_pred g p g_in (R, Some O)))\n              with \"[H K2]\" as \"HInv\".\n            { iExists _; iSplit; iFrame; try done. iExists true; iFrame. }\n            iSpecialize (\"K3\" with \"[$HInv $K1]\").\n            iDestruct \"K3\" as \"(K3 & _)\".\n            iSpecialize (\"HClose\" with \"K3\"); auto.\n          }\n          iIntros (_) \"(H & _)\".\n          iDestruct \"K3\" as \"[_ K3]\".\n          iDestruct \"HClose\" as \"(_ & HClose)\".\n          iSpecialize (\"HClose\" $! v2).\n          simpl.\n          iApply \"HClose\".\n          unfold tree_rep at 1.\n          iPoseProof (public_agree g_in r (R, Some O) with \"[$K1 $H2]\") as \"%Hx\".\n          destruct r.\n          inversion Hx. subst.\n          rewrite H6 in H10.\n          inversion H10; subst x1 v2 g21 g22.\n          destruct H15 as (Hf & Hrs).\n          (* join lsh1 with lsh2 = Lsh *)\n          iPoseProof (lock_join with \"[$H1 $K2]\") as \"K2\"; try iSplit; auto.\n           iDestruct \"K2\" as (Lsh) \"(% & K2)\".\n           (* done pushing back pointer of lock into ltree *)\n           iAssert (ltree g g_in p (R, Some O).1.1.2 (node_lock_inv_pred g p g_in (R, Some O)) )\n             with \"[H2 H3 H4 H5 H6 H7 H8 K2 H]\" as \"LT\".\n           {\n             iExists Lsh; iFrame. iSplit; try done.\n             iExists false. iFrame \"HT H H2 H3 H4 H5 H6\". \n             iSplit; try done.\n             unfold tree_rep_R.\n             rewrite -> if_false; auto.\n             iExists g1, g2, x, v1, p1, p2, lock1, lock2.\n             iFrame \"HT1 HT2 H7 H8\".\n             iPureIntro.\n             repeat (split; auto).\n           }\n           iSpecialize (\"K3\" with \"[$K1 $LT]\").\n           iDestruct \"K3\" as \"(K3 & K4)\".\n           iDestruct \"K3\" as (tg pk lk) \"((%K3 & K34) & K35)\".\n           destruct K3 as (K31 & K32 & K33 & K34).\n            iPoseProof (node_exist_in_tree g (find_ghost_set tg g_root pk lk) p \n                         with \"[K4 K35]\") as \"%Hy\". \n            { iFrame \"HT\". iFrame. }\n            iPoseProof (ghost_tree_rep_public_half_ramif _ _ _ _ _ _ (Neg_Infinity, Pos_Infinity)\n                                                         with \"[$K34]\") as \"GT\".\n            { apply Hy. }\n            iDestruct \"GT\" as (r a) \"(%GT1 & GT2)\".\n            iSplit. iPureIntro.\n            simpl in *.\n            subst.\n            Check range_info_in_gmap _ _ _ _ _ _ (Neg_Infinity, Pos_Infinity).\n            erewrite (range_info_in_gmap _ _ _ _ _ _ (Neg_Infinity, Pos_Infinity)); eauto.\n            assert (a = Some (Some (x, v1, g1, g2))). admit. \n            subst. eauto. \n            unfold tree_rep.\n            iExists _, _, _. iFrame. iPureIntro. (split; auto).\n        + unfold node_lock_inv_pred at 1, node_rep.\n          iDestruct \"KInv\" as \"(? & KInv)\".\n          iDestruct \"KInv\" as \"((((((? & KInv) & ?) & ?) & ?) & ?) & ?)\".\n          iPoseProof (field_at_conflict Ews t_struct_tree_t (DOT _t) p\n                      with \"[$H3 $KInv]\") as \"HF\"; try easy; auto.\n     }\n     (* free *)\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 v2 np lsh.\n     entailer !.  by iIntros \"_\".\nAdmitted.\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/giveup_lookup.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.4339814648038986, "lm_q1q2_score": 0.27645956329489385}}
{"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 SeqLib.\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nModule CalculatorProtocol.\nSection CalculatorProtocol.\n\nDefinition input := seq nat.\n\n(* Partially defined function, e.g., \n   addition or multiplication require precisely two arguments *)\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\n(* Calculator nodes *)\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:\n\n- \"Clients\" can send messages with requests as long as the request\n  satisfies the precondition prec.\n\n- \"Clients\" can receive messages from \"servers\" (i.e., calculators).\n\n- \"Servers\" can receive messages as long as they satisfy the\n  precondition and record the sender and the arguments in the\n  permission list.\n\n- \"Servers\" can respond to clients accordingly, given that the result\n  satisfies the arguments.\n\n*)\n\n\n(* Defining state-space *)\n\n(* Calculator server state *)\nDefinition st := ptr_nat 1.\n(* \nCalculator state: \n  - client node id\n  - server node id\n  - client-provided id (e.g., hash of the input)\n  - client input\n*)\n\nDefinition perm := (nid * nat * (seq nat))%type.\nDefinition cstate := seq perm.\n\nDefinition all_valid (s : cstate) := all (fun e => prec e.2) s.\n\n(* Local state coherence *)\nDefinition localCoh (n : nid) : Pred heap :=\n  [Pred h | exists (s : cstate), h = st :-> s /\\ all_valid s].\n\n\n(* Tags *)\nDefinition req : nat := 0.\nDefinition resp : nat := 1.\n\nDefinition tags := [:: req; resp].\n\n(* Coherent messages *)\nDefinition cohMsg (ms: msg TaggedMessage) : Prop :=\n  let body := content ms in\n  if tag body == resp then\n    [/\\ from ms \\in cs, to ms \\in cls &\n        exists v args, tms_cont body = [:: v] ++ args]\n  else [/\\ tag body == req,\n        from ms \\in cls, to ms \\in cs &\n        exists args,\n          tms_cont body = args /\\\n          prec args].\n\nDefinition soupCoh : Pred soup :=\n  [Pred s | valid s /\\ forall m ms, find m s = Some ms -> cohMsg ms].\n\nDefinition calcoh d : Prop :=\n  let: dl := dstate d in\n  let: ds := dsoup d in\n  [/\\ soupCoh ds, dom dl =i nodes,\n   valid dl &\n   forall n, n \\in nodes -> localCoh n (getLocal n d)].\n\n(* Axioms of the coherence predicate *)\nLemma l1 d: calcoh d -> valid (dstate d).\nProof. by case. Qed.\n\nLemma l2 d: calcoh d -> valid (dsoup d).\nProof. by case; case. Qed.\n\nLemma l3 d: calcoh d -> dom (dstate d) =i nodes.\nProof. by case. Qed.\n\n(* Wrapping up the coherence predicate *)\nDefinition CalCoh := CohPred (CohPredMixin l1 l2 l3).\n\n(* TODO: This lemma seems very generic, it is exactly the same in TPC.\n   Refactor it! *)\nLemma consume_coh d m : CalCoh d -> soupCoh (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 trans_updDom this d s :\n  this \\in nodes -> CalCoh 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\n(****************************************************)\n(********* Getter lemmas for local state ************)\n(****************************************************)\n\nLemma cs_in_nodes n : n \\in cs -> n \\in nodes.\nProof. by rewrite mem_cat=>->. Qed.\n\nLemma cohSt n d (C : CalCoh d) s:\n  find st (getLocal n d) = Some s ->\n  dyn_tp s = cstate.\nProof.\ncase: (C)=>_ _ _ G; case H: (n \\in nodes).\n- by move:(G _ H); case=>s'[]->_; rewrite findPt//=; case=><-.\nrewrite /getLocal; rewrite -(cohDom C) in H.\nby case: dom_find H=>//->; rewrite find0E.\nQed.\n\nDefinition getSt n d (C : CalCoh d) : cstate :=\n  match find st (getLocal n d) as f return _ = f -> _ with\n    Some v => fun epf => icast (sym_eq (cohSt C epf)) (dyn_val v) \n  | _ => fun epf => [::]\n  end (erefl _).\n\nLemma getStK n d (C : CalCoh d)  s :\n  getLocal n d = st :-> s -> getSt n C = s.\nProof.\nmove=>E; rewrite /getSt/=.\nmove: (cohSt C); rewrite !E/==>H. \nby apply: eqc.\nQed.\n\nLemma getStE n i j C C' (pf : n \\in nodes) :\n  getLocal n j = getLocal n i ->\n  @getSt n j C' = @getSt n i C.\nProof.\ncase: {-1}(C)=>_ _ _/(_ _ pf).\nby move=>[s][E]_; rewrite (getStK C E) E; move/(getStK C' )->.\nQed.\n\nLemma getStE' n i j C C' (pf : n \\in nodes) :\n  @getSt n j C' = @getSt n i C ->\n  getLocal n j = getLocal n i.\nProof.\ncase: {-1}(C)=>_ _ _/(_ _ pf).\nmove=>[s][E]_; rewrite (getStK C E) E=>H.\ncase: {-1}(C')=>_ _ _/(_ _ pf)=>[][s'][E']_.\nby rewrite (getStK C' E') in H; subst s'. \nQed.\n\n(****************************************************)\n\nNotation coh := CalCoh.\n\n(*** Server Transitions ***)\n\nSection ServerReceiveTransition.\n\nDefinition sr_wf d (_ : coh d) (this from : nid) msg :=\n  prec msg.\n\nDefinition sr_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 cs\n    then let s := getSt this pf in\n         st :-> ((from, this, m) :: s)\n    else getLocal this d.\n\n(* This looks extremely similar to TPC, so, perhaps this should be\n   refactored as well. *)\nLemma sr_step_coh : r_step_coh_t sr_wf req sr_step.\nProof.\nmove=>d from this m C pf tms D F Wf T/=.\nrewrite /sr_step; case X: (this \\in cs); last first.\n- split=>/=; first by apply: consume_coh.\n  + by apply: trans_updDom.\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: trans_updDom.  \n- by rewrite validU; apply: cohVl C.\nmove=>n Ni/=; rewrite /localCoh/=.\nrewrite /getLocal/=findU; case: ifP=>B/=; last by case: (C)=>_ _ _/(_ n Ni). \nmove/eqP: B X=>Z/eqP X; subst n; rewrite (cohVl C)/=.\nhave Y: all_valid (getSt this C).\nby case: {-1}(C)=>_ _ _/(_ _ pf)[]s[]/(getStK C)->.\nexists ((from, this, tms_cont tms) :: (getSt this C)); split=>//. \nrewrite /all_valid/= in Y *; rewrite Y.\nby rewrite /sr_wf in Wf; rewrite Wf.\nQed.\n\nDefinition server_recv_trans := ReceiveTrans sr_step_coh.\n\nEnd ServerReceiveTransition.\n\nSection ServerSendTransition.\n\nDefinition entry_finder (to : nid) msg :=\n  let: ans := head 0 msg in\n  fun e : perm => \n    let: (n, _, args) := e in\n    [&& n == to, f args == Some ans &\n        msg == ans :: args].\n\nDefinition can_send (s : cstate) to msg :=\n  has (entry_finder to msg) s.\n\nDefinition ss_safe (this to : nid)\n           (d : dstatelet) (msg : seq nat) :=\n  to \\in cls /\\ this \\in cs /\\\n  exists (C : coh d), \n  has (entry_finder to msg) (getSt this C).         \n\nLemma ss_safe_coh this to d m : ss_safe this to d m -> coh d.\nProof. by case=>_[]_[]. Qed.\n\nLemma ss_safe_in this to d m : ss_safe this to d m ->\n                             this \\in nodes /\\ to \\in nodes.\nProof.\nby rewrite !mem_cat; case=>->[->]_; split=>//; rewrite orbC.\nQed.\n\nLemma ss_safe_this this to d m :\n  ss_safe this to d m -> this \\in cs.\nProof. by case=>_[?][]. Qed.\n\nDefinition ss_step (this to : nid) (d : dstatelet)\n           (msg : seq nat)\n           (pf : ss_safe this to d msg) :=\n  let C := ss_safe_coh pf in \n  let s := getSt this C in\n  Some (st :-> remove_elem s (to, this, (behead msg))).\n\nLemma ss_step_coh : s_step_coh_t coh resp ss_step.\nProof.\nmove=>this to d msg pf h[]->{h}.\nhave C : (coh d) by case: pf=>?[_][].\nsplit=>/=.\n- split=>[|i ms/=]; first by rewrite valid_fresh (cohVs C).\n  rewrite findUnL; last by rewrite valid_fresh (cohVs C). \n  case: ifP=>E; first by case: C=>[[Vs]]H _ _ _; move/H.\n  move/findPt_inv=>[Z G]; subst i ms.\n  split; rewrite ?(proj2 (ss_safe_in pf))?(ss_safe_this pf)//.\n  case: pf=>?[C'][tf]/hasP[]=>[[[n]]]h args\n             _/andP[/eqP]Z1/andP[/eqP Z2]/eqP Z3//=.\n  case: pf=>[_][_][C']/hasP[[[x1] x2]]x3 H/andP[Z1]/andP[Z2]/eqP->.\n  by exists (head 0 msg), x3. \n- move=>z.\n  move: (getSt this (ss_safe_coh pf) )=>G.\n  rewrite -(cohDom C) domU inE/= (cohVl C).\n  by case: ifP=>///eqP->{z}; rewrite (cohDom C)(proj1 (ss_safe_in pf)). \n- by rewrite validU; apply: cohVl C.\nmove=>n Ni. rewrite /localCoh/=.\nrewrite /getLocal/=findU; case: ifP=>B/=; last by case: C=>_ _ _/(_ n Ni). \nmove/eqP: B=>Z; subst n; rewrite (cohVl C).\nexists (remove_elem (getSt this (ss_safe_coh pf)) (to, this, behead msg)).\nsplit=>//; apply: remove_elem_all.\nby case: {-1}(ss_safe_coh pf)=>_ _ _/(_ _ Ni)[]s[]/(getStK (ss_safe_coh pf))->.\nQed.\n\nLemma ss_safe_def this to d msg :\n      ss_safe this to d msg <->\n      exists b pf, @ss_step this to d msg pf = Some b.\nProof.\nsplit=>[pf/=|]; last by case=>?[]. \nset b := let C := ss_safe_coh pf in \n         let s := getSt this C in\n         st :-> remove_elem s (to, this, (behead msg)).\nby exists b, pf. \nQed.\n\nDefinition server_send_trans :=\n  SendTrans ss_safe_coh ss_safe_in ss_safe_def ss_step_coh.\n\nEnd ServerSendTransition.\n\n(**************************)\n(*** Client transitions ***)\n(**************************)\n\nSection ClientSendTransition.\n\nDefinition cs_safe (this to : nid)\n           (d : dstatelet) (msg : seq nat) :=\n  [/\\ to \\in cs, this \\in cls, coh d & prec msg].         \n\nLemma cs_safe_coh this to d m : cs_safe this to d m -> coh d.\nProof. by case=>_[]. Qed.\n\nLemma cs_safe_in this to d m : cs_safe this to d m ->\n                             this \\in nodes /\\ to \\in nodes.\nProof.\nby rewrite !mem_cat; case=>->->/=_ _; split=>//; rewrite orbC. \nQed.\n\nDefinition cs_step (this to : nid) (d : dstatelet)\n           (msg : seq nat)\n           (pf : cs_safe this to d msg) :=\n  let C := cs_safe_coh pf in \n  let s := getSt this C in\n  Some (st :-> ((this, to, msg)::s)).\n\n\nLemma cs_step_coh : s_step_coh_t coh req cs_step.\nProof.\nmove=>this to d msg pf h[]->{h}.\nhave C : (coh d) by case: pf=>?[].\nsplit=>/=.\n- split=>[|i ms/=]; first by rewrite valid_fresh (cohVs C).\n  rewrite findUnL; last by rewrite valid_fresh (cohVs C). \n  case: ifP=>E; first by case: C=>[[Vs]]H _ _ _; move/H.\n  move/findPt_inv=>[Z G]; subst i ms.\n  split=>//; rewrite ?(proj2 (cs_safe_in pf));\n  rewrite ?(proj2 (cs_safe_in pf))?(cs_safe_this pf)//=;\n  by case: pf=>// _ _ _; exists msg.\n- move=>z; move: (getSt this (cs_safe_coh pf))=>G.\n  rewrite -(cohDom C) domU inE/= (cohVl C).\n  by case: ifP=>///eqP->{z}; rewrite (cohDom C)(proj1 (cs_safe_in pf)). \n- by rewrite validU; apply: cohVl C.\nmove=>n Ni. rewrite /localCoh/=.\nrewrite /getLocal/=findU; case: ifP=>B; last by case: C=>_ _ _/(_ n Ni). \nmove/eqP: B=>Z; subst n; rewrite (cohVl C)/=.\nexists ((this, to, msg) :: getSt this (cs_safe_coh pf)); split=>//.\nhave Y: all_valid (getSt this (cs_safe_coh pf)).\nby case: {-1}(cs_safe_coh pf)=>_ _ _/(_ _ Ni)[]s[]/(getStK (cs_safe_coh pf))->.\nby rewrite /=Y andbC/=; case: (pf).\nQed.\n\nLemma cs_safe_def this to d msg :\n      cs_safe this to d msg <->\n      exists b pf, @cs_step this to d msg pf = Some b.\nProof.\nsplit=>[pf/=|]; last by case=>?[]. \nset b := let C := cs_safe_coh pf in \n         let s := getSt this C in\n         st :-> ((this, to, msg)::s).\nby exists b, pf. \nQed.\n\nDefinition client_send_trans :=\n  SendTrans cs_safe_coh cs_safe_in cs_safe_def cs_step_coh.\n\nEnd ClientSendTransition.\n\nSection ClientReceiveTransition.\n\nDefinition cr_wf d (C : coh d) this from (msg : seq nat) :=\n  let s := getSt this C in\n  let: args := (behead msg) in\n  [&& (this, from, args) \\in s &\n     size msg > 2].\n\nDefinition cr_step : receive_step_t coh := \n  fun this (from : nid) (m : seq nat) d (pf : coh d) (pt : this \\in nodes) =>\n    let s := getSt this pf : seq perm in\n    st :-> remove_elem s (this, from, (behead m) : seq nat).\n\nLemma cr_step_coh : r_step_coh_t cr_wf resp cr_step.\nProof.\nmove=>d from this m C pf tms D F Wf T/=.\nrewrite /sr_step; case X: (this \\in cs); last first.\n- split=>/=; first by apply: consume_coh.\n  + by apply: trans_updDom.\n  + by rewrite validU; apply: cohVl C.\n  move=>n Ni/=; rewrite /localCoh/=.\n  rewrite /getLocal/=findU; case: ifP=>B/=; last by case: (C)=>_ _ _/(_ n Ni). \n  move/eqP: B X=>Z/eqP X; subst n; rewrite (cohVl C)/=.\n  exists (remove_elem (getSt this C) (this, from, behead tms)).  \n  split=>//; apply: remove_elem_all.\n  by case: {-1}(C)=>_ _ _/(_ _ Ni)[]s[]/(getStK (C))->.  \nsplit=>/=; first by apply: consume_coh.\n- by apply: trans_updDom.  \n- by rewrite validU; apply: cohVl C.\nmove=>n Ni/=; rewrite /localCoh/=.\nrewrite /getLocal/=findU; case: ifP=>B/=; last by case: (C)=>_ _ _/(_ n Ni). \nmove/eqP: B X=>Z/eqP X; subst n; rewrite (cohVl C)/=.\nexists (remove_elem (getSt this C) (this, from, behead tms)).  \nsplit=>//; apply: remove_elem_all.\nby case: {-1}(C)=>_ _ _/(_ _ Ni)[]s[]/(getStK (C))->.  \nQed.\n\nDefinition client_recv_trans := ReceiveTrans cr_step_coh.\n\nEnd ClientReceiveTransition.\n\n\nSection Protocol.\n\nVariable l : Label.\n\nDefinition cal_sends :=    [:: server_send_trans; client_send_trans].\nDefinition cal_receives := [:: server_recv_trans; client_recv_trans].\n\nProgram Definition CalculatorProtocol : protocol :=\n  @Protocol _ l _ cal_sends cal_receives _ _.\n\nEnd Protocol.\nEnd CalculatorProtocol.\n\nModule Exports.\n\nDefinition CalculatorProtocol := CalculatorProtocol.\n\nDefinition CalCoh := CalCoh.\n\nDefinition server_send_trans := server_send_trans.\nDefinition server_recv_trans := server_recv_trans.\nDefinition client_send_trans := client_send_trans.\nDefinition client_recv_trans := client_recv_trans.\n\nDefinition req := req.\nDefinition resp := resp.\nNotation input := (seq nat).\nDefinition cstate := cstate.\n\nDefinition getSt := getSt.\nDefinition getStK := getStK.\nDefinition getStE := getStE.\nDefinition getStE' := getStE'.\n\nEnd Exports.\n\nEnd CalculatorProtocol.\n\n(**************************************************)\n(*\nOverall Implementation effort:\n\n4 person-hours\n\n*)\n(**************************************************)\n \nExport CalculatorProtocol.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/Calculator/CalculatorProtocol.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2764595573137879}}
{"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.\n\nRequire Import Lia.\n\nFrom Undecidability Require Import Shared.ListAutomation.\nImport ListAutomationNotations.\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 [<-|[<-|[<-|[<-|[<-|[]]]]]]. 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-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/FOL/Undecidability/Reductions/ZF_to_HF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160666, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2764159518176446}}
{"text": "Set Implicit Arguments.\n\nRequire Import Coq.Lists.List.\nRequire Import Coq.Relations.Relations.\nRequire Import Common.Types.\nRequire Import Bag.TotalOrder.\nRequire Import Bag.Bag2.\nRequire Import Common.AllDiff.\nRequire Import Common.Bisimulation.\nRequire Import FwOF.FwOFSignatures.\n\nLocal Open Scope list_scope.\nLocal Open Scope equiv_scope.\nLocal Open Scope bag_scope.\n\n(** This is a really trivial functor. RELATION_DEFINITIONS is just a bunch of definitions. *)\nModule Make (Import AtomsAndController : ATOMS_AND_CONTROLLER) <: RELATION_DEFINITIONS.\n\n  Import AtomsAndController.\n  Import Machine.\n  Import Atoms.\n\n  Definition affixSwitch (sw : switchId) (ptpk : portId * packet) :=\n    match ptpk with\n      | (pt,pk) => (sw,pt,pk)\n    end.\n\n  Definition ConsistentDataLinks (links : list dataLink) : Prop :=\n    forall (lnk : dataLink),\n      In lnk links ->\n      topo (src lnk) = Some (dst lnk).\n\n  Definition LinkHasSrc (sws : bag switch_le) (link : dataLink) : Prop :=\n    exists switch,\n      In switch (to_list sws) /\\\n      fst (src link) = swId switch /\\\n      In (snd (src link)) (pts switch).\n\n  Definition LinkHasDst (sws : bag switch_le) (link : dataLink) : Prop :=\n    exists switch,\n      In switch (to_list sws) /\\\n      fst (dst link) = swId switch /\\\n      In (snd (dst link)) (pts switch).\n\n  Definition LinksHaveSrc (sws : bag switch_le) (links : list dataLink) :=\n    forall link, In link links -> LinkHasSrc sws link.\n\n  Definition LinksHaveDst (sws : bag switch_le) (links : list dataLink) :=\n    forall link, In link links -> LinkHasDst sws link.\n\n  Definition UniqSwIds (sws : bag switch_le) := AllDiff swId (to_list sws).\n\n  Definition ofLinkHasSw (sws : bag switch_le) (ofLink : openFlowLink) :=\n    exists sw,\n      In sw (to_list sws) /\\\n      of_to ofLink = swId sw.\n\n  Definition OFLinksHaveSw (sws : bag switch_le) (ofLinks : list openFlowLink) :=\n    forall ofLink, In ofLink ofLinks -> ofLinkHasSw sws ofLink.\n\n  Definition DevicesFromTopo (devs : state) :=\n    forall swId0 swId1 pt0 pt1,\n      Some (swId0,pt0) = topo (swId1,pt1) ->\n      exists sw0 sw1 lnk,\n        (* TODO(arjun): might as well be lists now. *)\n        In sw0 (to_list (switches devs)) /\\ \n        In sw1 (to_list (switches devs)) /\\\n        In lnk (links devs) /\\\n        swId sw0 = swId0 /\\\n        swId sw1 = swId1 /\\\n        src lnk = (swId1,pt1) /\\\n        dst lnk = (swId0, pt0).\n\n  Definition NoBarriersInCtrlm (sws : bag switch_le) :=\n    forall sw,\n      In sw (to_list sws) ->\n      forall m,\n        In m (to_list (ctrlm sw)) ->\n        NotBarrierRequest m.\n\n\n  Record concreteState := ConcreteState {\n    devices : state;\n    concreteState_flowTableSafety : FlowTablesSafe (switches devices);\n    concreteState_consistentDataLinks : ConsistentDataLinks (links devices);\n    linksHaveSrc : LinksHaveSrc (switches devices) (links devices);\n    linksHaveDst : LinksHaveDst (switches devices) (links devices);\n    uniqSwIds : UniqSwIds (switches devices);\n    ctrlP : P (switches devices) (ofLinks devices) (ctrl devices);\n    uniqOfLinkIds : AllDiff of_to (ofLinks devices);\n    ofLinksHaveSw : OFLinksHaveSw (switches devices) (ofLinks devices);\n    devicesFromTopo : DevicesFromTopo devices;\n    swsHaveOFLinks : SwitchesHaveOpenFlowLinks (switches devices) (ofLinks devices);\n    noBarriersInCtrlm : NoBarriersInCtrlm (switches devices)\n  }.\n\n  Implicit Arguments ConcreteState [].\n\n  Definition concreteStep (st : concreteState) (obs : option observation)\n    (st0 : concreteState) :=\n    step (devices st) obs (devices st0).\n\n  Inductive abstractStep : abst_state -> option observation -> abst_state -> \n    Prop := \n  | AbstractStep : forall sw pt pk lps,\n    abstractStep\n      ({| (sw,pt,pk) |} <+> lps)\n      (Some (sw,pt,pk))\n      (unions (map (transfer sw) (abst_func sw pt pk)) <+> lps).\n\n  Definition relate_switch (sw : switch) : abst_state :=\n    match sw with\n      | Switch swId _ tbl inp outp ctrlm switchm =>\n        from_list (map (affixSwitch swId) (to_list inp)) <+>\n        unions (map (transfer swId) (to_list outp)) <+>\n        unions (map (select_packet_out swId) (to_list ctrlm)) <+>\n        unions (map (select_packet_in swId) (to_list switchm))\n    end.\n\n  Definition relate_dataLink (link : dataLink) : abst_state :=\n    match link with\n      | DataLink _ pks (sw,pt) =>\n        from_list (map (fun pk => (sw,pt,pk)) pks)\n    end.\n\n  Definition relate_openFlowLink (link : openFlowLink) : abst_state :=\n    match link with\n      | OpenFlowLink sw switchm ctrlm =>\n        unions (map (select_packet_out sw) ctrlm) <+>\n        unions (map (select_packet_in sw) switchm)\n    end.\n\n  Definition relate (st : state) : abst_state :=\n    unions (map relate_switch (to_list (switches st))) <+>\n    unions (map relate_dataLink (links st)) <+>\n    unions (map relate_openFlowLink (ofLinks st)) <+>\n    relate_controller (ctrl st).\n\n  Definition bisim_relation : relation concreteState abst_state :=\n    fun (st : concreteState) (ast : abst_state) => \n      ast = (relate (devices st)).\n\n  Module AtomsAndController := AtomsAndController.\n\nEnd Make.\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/FwOF/FwOFRelationDefinitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.2764159518176446}}
{"text": "Require Import Verdi.TraceRelations.\n\nRequire Import VerdiRaft.Raft.\nRequire Import VerdiRaft.CommonTheorems.\nRequire Import VerdiRaft.LogMatchingInterface.\nRequire Import VerdiRaft.StateMachineSafetyInterface.\nRequire Import VerdiRaft.AppliedEntriesMonotonicInterface.\nRequire Import VerdiRaft.MaxIndexSanityInterface.\nRequire Import VerdiRaft.StateMachineCorrectInterface.\nRequire Import VerdiRaft.LastAppliedCommitIndexMatchingInterface.\nRequire Import VerdiRaft.TraceUtil.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nRequire Import VerdiRaft.SortedInterface.\n\nRequire Import VerdiRaft.OutputGreatestIdInterface.\n\nSection OutputGreatestId.\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 {lmi : log_matching_interface}.\n  Context {si : sorted_interface}.\n  Context {aemi : applied_entries_monotonic_interface}.\n  Context {smsi : state_machine_safety_interface}.\n  Context {misi : max_index_sanity_interface}.\n  Context {smci : state_machine_correct_interface}.\n  Context {lacimi : lastApplied_commitIndex_match_interface}.\n\n  Lemma in_output_changed :\n    forall client id tr o,\n      ~ key_in_output_trace client id tr ->\n      key_in_output_trace client id (tr ++ o) ->\n      key_in_output_trace client id o.\n  Proof using. \n    intros. unfold key_in_output_trace in *.\n    break_exists_exists.\n    intuition. do_in_app; intuition.\n    exfalso. eauto.\n  Qed.\n\n  Lemma key_in_output_list_split :\n    forall client id l l',\n      key_in_output_list client id (l ++ l') ->\n      key_in_output_list client id l \\/ key_in_output_list client id l'.\n  Proof using. \n    intros.\n    unfold key_in_output_list in *.\n    break_exists; do_in_app; intuition eauto.\n  Qed.\n\n  Lemma key_in_output_list_empty :\n    forall client id,\n      ~ key_in_output_list client id [].\n  Proof using. \n    intuition.\n    unfold key_in_output_list in *.\n    break_exists; intuition.\n  Qed.\n\n  Lemma doLeader_key_in_output_list :\n    forall st h out st' m client id,\n      doLeader st h = (out, st', m) ->\n      ~ key_in_output_list client id out.\n  Proof using. \n    intros. unfold doLeader, advanceCommitIndex in *.\n    repeat break_match; find_inversion; intuition;\n    find_apply_lem_hyp key_in_output_list_empty; auto.\n  Qed.\n\n  Lemma handleInput_key_in_output_list :\n    forall st h i out st' m client id,\n      handleInput h i st = (out, st', m) ->\n      ~ key_in_output_list client id out.\n  Proof using. \n    intros. unfold handleInput, handleTimeout, handleClientRequest, tryToBecomeLeader in *.\n    repeat break_match; find_inversion; intuition eauto using key_in_output_list_empty;\n    unfold key_in_output_list in *; break_exists; simpl in *; intuition; congruence.\n  Qed.\n\n  Lemma has_key_own_key :\n    forall e,\n      has_key (eClient e) (eId e) e = true.\n  Proof using. \n    intros. unfold has_key. break_match; subst; simpl in *.\n    break_if; repeat (do_bool; intuition).\n  Qed.\n\n  Lemma has_key_true_necessary :\n    forall client id e,\n      has_key client id e = true ->\n      eClient e = client /\\ eId e = id.\n  Proof using. \n    intros. unfold has_key in *. break_match.\n    simpl in *. subst.\n    break_if; repeat (do_bool; intuition); try congruence.\n  Qed.\n\n  Lemma applyEntries_cache :\n    forall l h st os st' o client id id' o',\n      id < id' ->\n      applyEntries h st l = (os, st') ->\n      In (ClientResponse client id o) os ->\n      getLastId st client <> Some (id', o').\n  Proof using. \n    induction l; intros; simpl in *; intuition.\n    - find_inversion. simpl in *. intuition.\n    - unfold cacheApplyEntry, applyEntry in *.\n      repeat break_match; repeat find_inversion; simpl in *; intuition; eauto;\n      try solve \n          [find_inversion; find_rewrite; find_inversion; do_bool; lia];\n      try solve [find_inversion; repeat find_rewrite; congruence].\n      + do_bool. destruct (clientId_eq_dec (eClient a) client).\n        * subst. find_rewrite. find_inversion.\n          eapply IHl; [eapply Nat.lt_le_trans; eauto|idtac|idtac|]; eauto.\n          unfold getLastId.\n          simpl. eauto using get_set_same.\n        * eapply IHl; eauto.\n          unfold getLastId in *.\n          simpl. rewrite get_set_diff; eauto.\n      + do_bool. destruct (clientId_eq_dec (eClient a) client).\n        * repeat find_rewrite. congruence.\n        * eapply IHl; eauto.\n          unfold getLastId in *.\n          simpl. rewrite get_set_diff; eauto.\n      + do_bool. destruct (clientId_eq_dec (eClient a) client).\n        * repeat find_rewrite. find_inversion.\n          eapply IHl; [eapply Nat.lt_le_trans; eauto|idtac|idtac|]; eauto.\n          unfold getLastId.\n          simpl. eauto using get_set_same.\n        * eapply IHl; eauto.\n          unfold getLastId in *.\n          simpl. rewrite get_set_diff; eauto.\n      + do_bool. destruct (clientId_eq_dec (eClient a) client).\n        * repeat find_rewrite. congruence.\n        * eapply IHl; eauto.\n          unfold getLastId in *.\n          simpl. rewrite get_set_diff; eauto.\n  Qed.\n  \n  Lemma applyEntries_before :\n    forall l h st os st' o client id id',\n      id < id' ->\n      applyEntries h st l = (os, st') ->\n      In (ClientResponse client id o) os ->\n      before_func (has_key client id) (has_key client id') l.\n  Proof using.\n    induction l; intros; simpl in *; intuition.\n    - find_inversion. simpl in *. intuition.\n    - repeat break_match.\n      + subst.\n        find_inversion. do_in_app. intuition.\n        * do_in_map. find_inversion. eauto using has_key_own_key.\n        * { destruct (has_key client id' a) eqn:?; eauto.\n            exfalso.\n            unfold cacheApplyEntry, applyEntry in *.\n            find_apply_lem_hyp has_key_true_necessary. intuition.\n            repeat break_match; repeat find_rewrite; find_inversion; do_bool; subst_max.\n            - find_eapply_lem_hyp applyEntries_cache; eauto; lia.\n            - find_eapply_lem_hyp applyEntries_cache; eauto; lia.\n            - find_eapply_lem_hyp applyEntries_cache; eauto;\n              unfold getLastId in *; simpl in *; eauto using get_set_same.\n            - find_eapply_lem_hyp applyEntries_cache; eauto;\n              unfold getLastId in *; simpl in *; eauto using get_set_same.\n          }\n      + simpl in *. find_inversion.\n        { destruct (has_key client id' a) eqn:?; eauto.\n          exfalso.\n          unfold cacheApplyEntry, applyEntry in *.\n          find_apply_lem_hyp has_key_true_necessary. intuition.\n          repeat break_match; repeat find_rewrite; find_inversion; do_bool; subst.\n            - find_eapply_lem_hyp applyEntries_cache; eauto; lia.\n            - find_eapply_lem_hyp applyEntries_cache; eauto; lia.\n            - eapply applyEntries_cache in Heqp0; eauto;\n                unfold getLastId in *; simpl in *; eauto using get_set_same.\n            - eapply applyEntries_cache in Heqp0; eauto;\n                unfold getLastId in *; simpl in *; eauto using get_set_same.\n          }\n  Qed.\n\n  Lemma entries_contiguous :\n    forall net,\n      raft_intermediate_reachable net ->\n      (forall h, contiguous_range_exact_lo (log (nwState net h)) 0).\n  Proof using lmi. \n    intros. find_apply_lem_hyp log_matching_invariant.\n    unfold log_matching, log_matching_hosts in *.\n    intuition.\n    unfold contiguous_range_exact_lo. intuition; eauto.\n    find_apply_hyp_hyp. lia.\n  Qed.\n  \n  Lemma doGenericServer_key_in_output_list :\n    forall net h os st' ms id' client id,\n      raft_intermediate_reachable net ->\n      doGenericServer h (nwState net h) = (os, st', ms) ->\n      key_in_output_list client id os ->\n      id < id' ->\n      before_func (has_key client id) (has_key client id') (applied_entries (update name_eq_dec (nwState net) h st')).\n  Proof using lacimi smci si lmi. \n    intros.\n    find_copy_apply_lem_hyp logs_sorted_invariant.\n    pose proof entries_contiguous.\n    match goal with\n      | H : context [contiguous_range_exact_lo] |- _ =>\n        specialize (H net)\n    end.\n    concludes. simpl in *.\n    find_copy_apply_lem_hyp state_machine_correct_invariant.\n    unfold state_machine_correct in *. intuition.\n    unfold logs_sorted in *. intuition.\n    unfold key_in_output_list in *.\n    match goal with | H : exists _, _ |- _ => destruct H as [o] end.\n    unfold doGenericServer in *. break_let. simpl in *.\n    find_inversion. simpl in *.\n    pose proof Heqp as Heqp'.\n    eapply applyEntries_before in Heqp; eauto.\n    match goal with\n      | H : before_func _ _ ?l |- _=>\n        eapply before_func_prepend with\n        (l' := (rev (removeAfterIndex (log (nwState net h))\n                                      (lastApplied (nwState net h)))))\n          in H\n    end; eauto;\n    [|intros;\n       find_apply_lem_hyp In_rev;\n       apply Bool.not_true_iff_false;\n       intuition; unfold has_key in *;\n       break_match; break_if; repeat (do_bool; intuition); simpl in *;\n       eapply_prop_hyp client_cache_complete In; eauto;\n       break_exists; intuition; simpl in *;\n       subst;\n       match goal with\n         | Ha : context [applyEntries], Hg : getLastId _ _ = Some (?x, _) |- _ =>\n           eapply applyEntries_cache with (id' := x) in Ha\n       end; eauto; lia;\n       intuition; find_rewrite; repeat find_rewrite].\n    rewrite <- rev_app_distr in *.\n    eapply before_func_prefix; eauto.\n    use_applyEntries_spec. subst. simpl in *.\n    break_if.\n    - do_bool.\n        erewrite findGtIndex_removeAfterIndex_i_lt_i' in *; eauto.\n        match goal with\n          | |- context [applied_entries (update _ ?sigma ?h ?st)] =>\n            pose proof applied_entries_update sigma h st\n        end. conclude_using intuition.\n        intuition; simpl in *;\n        unfold raft_data in *; simpl in *; find_rewrite; auto using Prefix_refl.\n        unfold applied_entries in *.\n        break_exists. intuition. repeat find_rewrite.\n        eapply contiguous_sorted_subset_prefix; eauto using removeAfterIndex_contiguous, removeAfterIndex_sorted.\n        intros.\n        find_copy_apply_lem_hyp removeAfterIndex_In_le; eauto.\n        find_apply_lem_hyp removeAfterIndex_in.\n        apply removeAfterIndex_le_In; eauto; try lia.\n        find_copy_apply_lem_hyp commitIndex_lastApplied_match_invariant.\n        unfold commitIndex_lastApplied_match in *. simpl in *.\n        match goal with\n          | _ : ?x >= ?y |- _ =>\n            assert (y <= x) by lia\n        end.\n        eapply_prop_hyp le le; eauto. intuition.\n     - do_bool.\n        erewrite findGtIndex_removeAfterIndex_i'_le_i in *; eauto.\n        match goal with\n          | |- context [applied_entries (update _ ?sigma ?h ?st)] =>\n            pose proof applied_entries_update sigma h st\n        end. conclude_using intuition.\n        intuition; simpl in *;\n        unfold raft_data in *; simpl in *; find_rewrite; auto using Prefix_refl.\n        unfold applied_entries in *.\n        break_exists. intuition. repeat find_rewrite.\n        eapply contiguous_sorted_subset_prefix; eauto using removeAfterIndex_contiguous, removeAfterIndex_sorted.\n        intros.\n        find_copy_apply_lem_hyp removeAfterIndex_In_le; eauto.\n        find_apply_lem_hyp removeAfterIndex_in.\n        apply removeAfterIndex_le_In; eauto; try lia.\n        find_copy_apply_lem_hyp lastApplied_lastApplied_match_invariant.\n        unfold lastApplied_lastApplied_match in *. simpl in *.\n        match goal with\n          | _ : ?x >= ?y |- _ =>\n            assert (y <= x) by lia\n        end.\n        eapply_prop_hyp le le; eauto. intuition.\n  Qed.\n  \n  Lemma output_implies_greatest :\n    forall failed net failed' net' o client id id',\n      raft_intermediate_reachable net ->\n      @step_failure _ _ failure_params (failed, net) (failed', net') o ->\n      key_in_output_trace client id o ->\n      id < id' ->\n      before_func (has_key client id) (has_key client id') (applied_entries (nwState net')).\n  Proof using lacimi smci si lmi. \n    intros.\n    invcs H0; simpl in *;\n    try match goal with\n          | _ : key_in_output_trace _ _ [] |- _ =>\n            unfold key_in_output_trace in *; break_exists; simpl in *; intuition\n        end.\n    - unfold key_in_output_trace in *.\n      break_exists; simpl in *; intuition.\n      find_inversion.\n      unfold RaftNetHandler in *.\n      repeat break_let. repeat find_inversion. simpl in *.\n      find_eapply_lem_hyp RIR_handleMessage; eauto.\n      find_copy_eapply_lem_hyp RIR_doLeader; simpl in *; rewrite_update; eauto.\n      find_apply_lem_hyp key_in_output_list_split.\n      intuition; [exfalso; eapply doLeader_key_in_output_list; eauto|].\n      match goal with\n        | _ : doLeader ?st ?h = _, _ : doGenericServer _ ?d = _ |- _ =>\n          replace st with ((update name_eq_dec (nwState net) h st) h) in *;\n            [|rewrite_update; auto]\n      end.\n      find_apply_lem_hyp doLeader_appliedEntries.\n      rewrite_update. repeat find_rewrite_lem update_overwrite.\n      unfold data in *. simpl in *.\n      match goal with\n        | _ : raft_intermediate_reachable (mkNetwork ?ps ?st),\n              H : doGenericServer ?h ?r = _ |- _ =>\n          replace r with (nwState (mkNetwork ps st) h) in H by (simpl in *; rewrite_update; auto)\n      end.\n      find_eapply_lem_hyp doGenericServer_key_in_output_list; [|idtac|eauto|]; eauto.\n      simpl in *. find_rewrite_lem update_overwrite. auto.\n    - unfold key_in_output_trace in *.\n      break_exists; simpl in *; intuition.\n      find_inversion.\n      unfold RaftInputHandler in *.\n      repeat break_let. repeat find_inversion. simpl in *.\n      find_copy_eapply_lem_hyp RIR_handleInput; eauto.\n      find_copy_eapply_lem_hyp RIR_doLeader; simpl in *; rewrite_update; eauto.\n      find_apply_lem_hyp key_in_output_list_split.\n      intuition; [exfalso; eapply handleInput_key_in_output_list; eauto|].\n      find_apply_lem_hyp key_in_output_list_split.\n      intuition; [exfalso; eapply doLeader_key_in_output_list; eauto|].\n      match goal with\n        | _ : doLeader ?st ?h = _, _ : doGenericServer _ ?d = _ |- _ =>\n          replace st with ((update name_eq_dec (nwState net) h st) h) in *;\n            [|rewrite_update; auto]\n      end.\n      find_apply_lem_hyp doLeader_appliedEntries.\n      rewrite_update. repeat find_rewrite_lem update_overwrite.\n      unfold data in *. simpl in *.\n      match goal with\n        | _ : raft_intermediate_reachable (mkNetwork ?ps ?st),\n              H : doGenericServer ?h ?r = _ |- _ =>\n          replace r with (nwState (mkNetwork ps st) h) in H by (simpl in *; rewrite_update; auto)\n      end.\n      find_eapply_lem_hyp doGenericServer_key_in_output_list; [|idtac|eauto|]; eauto.\n      simpl in *. find_rewrite_lem update_overwrite. auto.\n  Qed.\n\n  Section inner.\n    Variable client : clientId.\n    Variables id id' : nat.\n    Variable id_lt_id' : id < id'.\n\n    Program Instance TR : TraceRelation step_failure :=\n      {\n        init := step_failure_init;\n        T := key_in_output_trace client id ;\n        T_dec := key_in_output_trace_dec client id ;\n        R := fun s => before_func (has_key client id) (has_key client id') (applied_entries (nwState (snd s)))\n      }.\n    Next Obligation.\n      simpl in *.\n      find_apply_lem_hyp step_failure_star_raft_intermediate_reachable.\n      find_eapply_lem_hyp applied_entries_monotonic'; eauto.\n      break_exists; repeat find_rewrite.\n      eauto using before_func_app.\n    Defined.\n    Next Obligation.\n      unfold key_in_output_trace in *. intuition.\n      break_exists; intuition.\n    Defined.\n    Next Obligation.\n      find_apply_lem_hyp step_failure_star_raft_intermediate_reachable.\n      find_apply_lem_hyp in_output_changed; auto.\n      eauto using output_implies_greatest.\n    Defined.\n\n  Theorem output_greatest_id :\n    forall failed net tr,\n      step_failure_star step_failure_init (failed, net) tr ->\n      key_in_output_trace client id tr ->\n      before_func (has_key client id) (has_key client id') (applied_entries (nwState net)).\n  Proof using id_lt_id' lacimi smci aemi si lmi. \n    intros. pose proof (trace_relations_work (failed, net) tr).\n    concludes. intuition.\n  Qed.\n  End inner.\n\n  Instance ogii : output_greatest_id_interface.\n  Proof.\n    split. unfold greatest_id_for_client. intros.\n    eauto using output_greatest_id.\n  Qed.\nEnd OutputGreatestId.\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/OutputGreatestIdProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160666, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.2764159518176446}}
{"text": "From iris.base_logic.lib Require Export invariants 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_fractionnal γ : Fractional (cinv_own γ).\n  Proof. intros ??. by rewrite -own_op. Qed.\n  Global Instance cinv_own_as_fractionnal γ 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\". iNext. iAlways. iSplit.\n    - iIntros \"?\". iApply \"HP''\". iApply \"HP'\". done.\n    - iIntros \"?\". iApply \"HP'\". iApply \"HP''\". done.\n  Qed.\n\n  Lemma cinv_alloc E N P : ▷ P ={E}=∗ ∃ γ, cinv N γ P ∗ cinv_own γ 1.\n  Proof.\n    iIntros \"HP\".\n    iMod (own_alloc 1%Qp) as (γ) \"H1\"; first done.\n    iMod (inv_alloc N _ (P ∨ own γ 1%Qp)%I with \"[HP]\"); first by eauto.\n    iExists _. iFrame. iExists _. iFrame. iIntros \"!> !# !>\". iSplit; by iIntros \"?\".\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γ\". iDestruct \"Hinv\" as (P') \"[#HP' Hinv]\".\n    iInv N as \"[HP|>Hγ']\" \"Hclose\".\n    - iMod (\"Hclose\" with \"[Hγ]\") as \"_\"; first by eauto. iModIntro. iNext.\n      iApply \"HP'\". done.\n    - iDestruct (cinv_own_1_l with \"Hγ Hγ'\") as %[].\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γ\". 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\". iApply \"Hclose\". iLeft. iNext. by iApply \"HP'\".\n    - iDestruct (cinv_own_1_l with \"Hγ' Hγ\") as %[].\n  Qed.\nEnd proofs.\n\nTypeclasses Opaque cinv_own cinv.\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/cancelable_invariants.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878414043816, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.27641594547595727}}
{"text": "Require Import ClassicalExtras.\n\nRequire Import TraceModel.\nRequire Import Stream.\nRequire Import Properties.\nRequire Import Galois.\n\nRequire Import FunctionalExtensionality.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\n\nSection UndefBehavior.\n  Variable event : Events.\n\n  Variable endstate : Endstates.\n\n  Definition undef := unit.\n  Definition endstateUB : Endstates :=\n    {| es := (es endstate + undef);\n       an_es := inr tt\n    |}.\n  Definition UB : es endstateUB := inr tt.\n  Hint Unfold UB.\n\n  Definition endstateS := endstateUB.\n  Definition endstateT := endstateUB.\n\n  Definition traceS := @trace event endstateS.\n  Definition traceT := @trace event endstateT.\n  Definition finprefS := @finpref event endstateS.\n  Definition finprefT := @finpref event endstateT.\n\n  Definition propS := @prop traceS.\n  Definition propT := @prop traceT.\n  Definition fpropS := @fprop event endstateS.\n  Definition fpropT := @fprop event endstateT.\n\n  (* Definition prefixST (m__s : finprefS) (t__t : traceT) : Prop := *)\n  (*   match m__s with *)\n  (*   | fstop l__t (inl e__t) => *)\n  (*     match t__t with *)\n  (*     | tstop l__s e__s => e__t = e__s /\\ l__t = l__s *)\n  (*     | _ => False *)\n  (*     end *)\n  (*   | fstop _ (inr _) => False *)\n  (*   | ftbd l__t => *)\n  (*     match t__t with *)\n  (*     | tstop l__s _ | tsilent l__s => Stream.list_list_prefix l__t l__s *)\n  (*     | tstream s__s => Stream.list_stream_prefix l__t s__s *)\n  (*     end *)\n  (*   end. *)\n\n  Definition rel : traceS -> traceT -> Prop :=\n    fun t__s t__t => t__s = t__t \\/ exists m, (t__s = tstop m UB /\\ prefix (ftbd m) t__t).\n  Hint Unfold rel.\n\n  Definition GC_traceT_traceS : Galois_Connection traceT traceS :=\n    induced_connection rel.\n\n  Definition τ : propS -> propT := α GC_traceT_traceS.\n  Lemma τ_def : forall πS t__t,\n      (τ πS) t__t <-> (exists t__s, t__s = t__t /\\ πS t__s) \\/ (exists m, prefix (ftbd m) t__t /\\ πS (tstop m UB)).\n  Proof.\n    intros πS t__t.\n    unfold τ, GC_traceT_traceS, induced_connection, low_rel; simpl.\n    split.\n    - intros H.\n      destruct H as [t__s [H1 H2]].\n      destruct H2 as [H2 | H2].\n      + left; eexists; split; eauto.\n      + destruct H2 as [m [H2 H3]]; subst.\n        right.\n        eexists; split; try split; eauto.\n    - intros H.\n      destruct H as [[t__s [H1 H2]] | [m [H2 H3]]].\n      + eexists; split; eauto.\n      + eexists; split; eauto.\n  Qed.\n\n  Definition σ : propT -> propS := γ GC_traceT_traceS.\n\n  Lemma σ_def : forall πT t__s,\n      (σ πT) t__s <-> (forall t__t, t__s = t__t -> πT t__t) /\\ (forall t__t m, t__s = tstop m UB -> (prefix (ftbd m) t__t -> πT t__t)).\n  Proof.\n    intros πT t__s.\n    unfold σ, GC_traceT_traceS, induced_connection, up_rel; simpl.\n    split.\n    - intros H.\n      split.\n      + eauto.\n      + intros t__t m H0 H1; subst.\n        apply H.\n        right.\n        exists m. split; auto.\n    - intros H x Hrel.\n      destruct H as [H1 H2].\n      inversion Hrel.\n      + eauto.\n      + destruct H as [m [Hm1 Hm2]].\n        subst.\n        eauto.\n  Qed.\n\n  Lemma σ_def' : forall πT t__s,\n      (σ πT) t__s <-> (exists t__t, (forall m, t__s <> tstop m UB) /\\ t__s = t__t /\\ πT t__t) \\/\n                    (exists m, t__s = tstop m UB /\\ (forall t__t, prefix (ftbd m) t__t -> πT t__t)).\n  Proof.\n    intros πT t__s.\n    rewrite σ_def.\n    split.\n    - intros H. destruct H.\n      destruct t__s as [l [e | []] | l | s]; eauto;\n        now (left; eexists; split; eauto).\n    - intros H. destruct H.\n      + destruct H as [t__t [Hdiff [Heq H]]]; subst.\n        split.\n        * intros t__t0 H0; subst; eauto.\n        * intros t__t0 m H0 H1. subst.\n          now specialize (Hdiff m).\n      + destruct H as [m [Heq H]]; subst.\n        split.\n        * intros t__t H0; subst.\n          apply H; simpl.\n          now apply list_list_prefix_ref.\n        * intros t__t m0 H0 H1; subst; inversion H0; subst.\n          now auto.\n  Qed.\n\n  Lemma τ_preserves_dense : forall (π : propS),\n      Dense π -> Dense (τ π).\n  Proof.\n    unfold Dense, τ, GC_traceT_traceS, induced_connection, low_rel; simpl.\n    intros π HDense.\n    intros t__t Hfin.\n    destruct t__t as [l e | l | s].\n    - exists (tstop l e). split.\n      apply HDense. econstructor; eexists; eauto.\n      left; eauto.\n    - destruct Hfin as [l' [e' Hn]].\n      inversion Hn.\n    - destruct Hfin as [l' [e' Hn]].\n      inversion Hn.\n  Qed.\n\n  Lemma σ_does_not_preserve_dense : exists (π : propT),\n      Dense π /\\ not (Dense (σ π)).\n  Proof.\n    exists (fun t__t => exists m e, t__t = tstop m e).\n    split.\n    - unfold Dense.\n      intros t Hfin.\n      inversion Hfin; now auto.\n    - unfold Dense, σ, GC_traceT_traceS, induced_connection, up_rel; simpl.\n      intros Hn.\n      specialize (Hn (tstop nil UB)).\n      assert (finite (tstop (nil : list (ev event)) UB)) by (econstructor; now eauto).\n      specialize (Hn H (tsilent nil)).\n      assert (rel (tstop nil UB) (tsilent nil)) by (right; eexists; now eauto).\n      specialize (Hn H0).\n      destruct Hn as [? [? Hn]].\n      inversion Hn.\n  Qed.\n\n\nEnd UndefBehavior.\n", "meta": {"author": "secure-compilation", "repo": "different_traces", "sha": "2319e1db2cc9ab1690badb04fc591d1744e1e09b", "save_path": "github-repos/coq/secure-compilation-different_traces", "path": "github-repos/coq/secure-compilation-different_traces/different_traces-2319e1db2cc9ab1690badb04fc591d1744e1e09b/UndefBehaviorCompCert.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878414043814, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.27641594547595727}}
{"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 int.Abs.\nRequire int.ComputerDivision.\nRequire map.Map.\n\n(* Why3 assumption *)\nDefinition unit := unit.\n\nAxiom t : Type.\nParameter t_WhyType : WhyType t.\nExisting Instance t_WhyType.\n\nParameter max: Z.\n\nParameter to_int: t -> Z.\n\n(* Why3 assumption *)\nDefinition in_bounds (n:Z): Prop := (0%Z <= n)%Z /\\ (n <= max)%Z.\n\nAxiom to_int_in_bounds : forall (n:t), (in_bounds (to_int n)).\n\nAxiom extensionality : forall (x:t) (y:t), ((to_int x) = (to_int y)) ->\n  (x = y).\n\nParameter zero_unsigned: t.\n\nAxiom zero_unsigned_is_zero : ((to_int zero_unsigned) = 0%Z).\n\nAxiom address : Type.\nParameter address_WhyType : WhyType address.\nExisting Instance address_WhyType.\n\nParameter to_int1: address -> Z.\n\n(* Why3 assumption *)\nDefinition in_bounds1 (n:Z): Prop := (0%Z <= n)%Z /\\\n  (n <= 1461501637330902918203684832716283019655932542975%Z)%Z.\n\nAxiom to_int_in_bounds1 : forall (n:address), (in_bounds1 (to_int1 n)).\n\nAxiom extensionality1 : forall (x:address) (y:address),\n  ((to_int1 x) = (to_int1 y)) -> (x = y).\n\nParameter zero_unsigned1: address.\n\nAxiom zero_unsigned_is_zero1 : ((to_int1 zero_unsigned1) = 0%Z).\n\nAxiom uint256 : Type.\nParameter uint256_WhyType : WhyType uint256.\nExisting Instance uint256_WhyType.\n\nParameter to_int2: uint256 -> Z.\n\n(* Why3 assumption *)\nDefinition in_bounds2 (n:Z): Prop := (0%Z <= n)%Z /\\\n  (n <= 115792089237316195423570985008687907853269984665640564039457584007913129639935%Z)%Z.\n\nAxiom to_int_in_bounds2 : forall (n:uint256), (in_bounds2 (to_int2 n)).\n\nAxiom extensionality2 : forall (x:uint256) (y:uint256),\n  ((to_int2 x) = (to_int2 y)) -> (x = y).\n\nParameter zero_unsigned2: uint256.\n\nAxiom zero_unsigned_is_zero2 : ((to_int2 zero_unsigned2) = 0%Z).\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 goal *)\nTheorem WP_parameter_transfer : forall (usfrom:address) (usto:address)\n  (usval:uint256) (usorig:Z) (usorig1:(map.Map.map Z uint256)),\n  ((0%Z <= usorig)%Z /\\ (((to_int1 usto) < usorig)%Z /\\\n  (((to_int1 usfrom) < usorig)%Z /\\\n  ((to_int2 usval) <= (to_int2 (map.Map.get usorig1 (to_int1 usto))))%Z))) ->\n  let o := (to_int1 usfrom) in (((0%Z <= o)%Z /\\ (o < usorig)%Z) ->\n  (in_bounds2 ((to_int2 (map.Map.get usorig1 o)) - (to_int2 usval))%Z)).\n(* Why3 intros usfrom usto usval usorig usorig1 (h1,(h2,(h3,h4))) o (h5,h6). *)\nintros usfrom usto usval usorig usorig1 (h1,(h2,(h3,h4))) o (h5,h6).\n\nQed.\n\n", "meta": {"author": "pirapira", "repo": "token_why3", "sha": "f451c1b2f66afa56ffee0a4c274b4ce3416ac118", "save_path": "github-repos/coq/pirapira-token_why3", "path": "github-repos/coq/pirapira-token_why3/token_why3-f451c1b2f66afa56ffee0a4c274b4ce3416ac118/why3-by-hand/token/token_TokenContract_WP_parameter_transfer_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.27640286926193675}}
{"text": "(*** Implementing Large Bounded Arithmetic via pairs *)\nRequire Import Coq.ZArith.ZArith.\nRequire Import Crypto.LegacyArithmetic.Interface.\nRequire Import Crypto.LegacyArithmetic.InterfaceProofs.\nRequire Import Crypto.Util.Tuple.\nRequire Import Crypto.Util.ListUtil.\nRequire Import Crypto.Util.Notations.\nRequire Import Crypto.Util.LetIn.\nImport Bug5107WorkAround.\n\nRequire Crypto.LegacyArithmetic.BaseSystem.\nRequire Crypto.LegacyArithmetic.Pow2Base.\n\nLocal Open Scope nat_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\n\nLocal Coercion Z.of_nat : nat >-> Z.\nLocal Notation eta x := (fst x, snd x).\n\n(** The list is low to high; the tuple is low to high *)\nDefinition tuple_decoder {n W} {decode : decoder n W} {k : nat} : decoder (k * n) (tuple W k)\n  := {| decode w := BaseSystem.decode (Pow2Base.base_from_limb_widths (repeat n k))\n                                      (List.map decode (List.rev (Tuple.to_list _ w))) |}.\nGlobal Arguments tuple_decoder : simpl never.\nHint Extern 3 (decoder _ (tuple ?W ?k)) => let kv := (eval simpl in (Z.of_nat k)) in apply (fun n decode => (@tuple_decoder n W decode k : decoder (kv * n) (tuple W k))) : typeclass_instances.\n\nSection ripple_carry_definitions.\n  (** tuple is high to low ([to_list] reverses) *)\n  Fixpoint ripple_carry_tuple' {T} (f : T -> T -> bool -> bool * T) k\n    : forall (xs ys : tuple' T k) (carry : bool), bool * tuple' T k\n    := match k return forall (xs ys : tuple' T k) (carry : bool), bool * tuple' T k with\n       | O => f\n       | S k' => fun xss yss carry => dlet xss := xss in\n                                      dlet yss := yss in\n                                      let (xs, x) := eta xss in\n                                      let (ys, y) := eta yss in\n                                      dlet addv := (@ripple_carry_tuple' _ f k' xs ys carry) in\n                                      let (carry, zs) := eta addv in\n                                      dlet fxy := (f x y carry) in\n                                      let (carry, z) := eta fxy in\n                                      (carry, (zs, z))\n       end.\n\n  Definition ripple_carry_tuple {T} (f : T -> T -> bool -> bool * T) k\n    : forall (xs ys : tuple T k) (carry : bool), bool * tuple T k\n    := match k return forall (xs ys : tuple T k) (carry : bool), bool * tuple T k with\n       | O => fun xs ys carry => (carry, tt)\n       | S k' => ripple_carry_tuple' f k'\n       end.\nEnd ripple_carry_definitions.\n\nGlobal Instance ripple_carry_adc\n       {W} (adc : add_with_carry W) {k}\n  : add_with_carry (tuple W k)\n  := { adc := ripple_carry_tuple adc k }.\n\nGlobal Instance ripple_carry_subc\n       {W} (subc : sub_with_carry W) {k}\n  : sub_with_carry (tuple W k)\n  := { subc := ripple_carry_tuple subc k }.\n\n(** constructions on [tuple W 2] *)\nSection tuple2.\n  Section select_conditional.\n    Context {W}\n            {selc : select_conditional W}.\n\n    Definition select_conditional_double (b : bool) (x : tuple W 2) (y : tuple W 2) : tuple W 2\n      := dlet x := x in\n         dlet y := y in\n         let (x1, x2) := eta x in\n         let (y1, y2) := eta y in\n         (selc b x1 y1, selc b x2 y2).\n\n    Global Instance selc_double : select_conditional (tuple W 2)\n      := { selc := select_conditional_double }.\n  End select_conditional.\n\n  Section load_immediate.\n    Context (n : Z) {W}\n            {ldi : load_immediate W}.\n\n    Definition load_immediate_double (r : Z) : tuple W 2\n      := (ldi (r mod 2^n), ldi (r / 2^n)).\n\n    (** Require a [decoder] instance to aid typeclass search in\n        resolving [n] *)\n    Global Instance ldi_double {decode : decoder n W} : load_immediate (tuple W 2)\n      := { ldi := load_immediate_double }.\n  End load_immediate.\n\n  Section bitwise_or.\n    Context {W}\n            {or : bitwise_or W}.\n\n    Definition bitwise_or_double (x : tuple W 2) (y : tuple W 2) : tuple W 2\n      := dlet x := x in\n         dlet y := y in\n         let (x1, x2) := eta x in\n         let (y1, y2) := eta y in\n         (or x1 y1, or x2 y2).\n\n    Global Instance or_double : bitwise_or (tuple W 2)\n      := { or := bitwise_or_double }.\n  End bitwise_or.\n\n  Section bitwise_and.\n    Context {W}\n            {and : bitwise_and W}.\n\n    Definition bitwise_and_double (x : tuple W 2) (y : tuple W 2) : tuple W 2\n      := dlet x := x in\n         dlet y := y in\n         let (x1, x2) := eta x in\n         let (y1, y2) := eta y in\n         (and x1 y1, and x2 y2).\n\n    Global Instance and_double : bitwise_and (tuple W 2)\n      := { and := bitwise_and_double }.\n  End bitwise_and.\n\n  Section spread_left.\n    Context (n : Z) {W}\n            {ldi : load_immediate W}\n            {shl : shift_left_immediate W}\n            {shr : shift_right_immediate W}.\n\n    Definition spread_left_from_shift (r : W) (count : Z) : tuple W 2\n      := dlet r := r in\n         (shl r count, if count =? 0 then ldi 0 else shr r (n - count)).\n\n    (** Require a [decoder] instance to aid typeclass search in\n        resolving [n] *)\n    Global Instance sprl_from_shift {decode : decoder n W} : spread_left_immediate W\n      := { sprl := spread_left_from_shift }.\n  End spread_left.\n\n  Section shl_shr.\n    Context (n : Z) {W}\n            {ldi : load_immediate W}\n            {shl : shift_left_immediate W}\n            {shr : shift_right_immediate W}\n            {or : bitwise_or W}.\n\n    Definition shift_left_immediate_double (r : tuple W 2) (count : Z) : tuple W 2\n      := dlet r := r in\n         let (r1, r2) := eta r in\n         (if count =? 0\n          then r1\n          else if count <? n\n               then shl r1 count\n               else ldi 0,\n          if count =? 0\n          then r2\n          else if count <? n\n               then or (shr r1 (n - count)) (shl r2 count)\n               else shl r1 (count - n)).\n\n    Definition shift_right_immediate_double (r : tuple W 2) (count : Z) : tuple W 2\n      := dlet r := r in\n         let (r1, r2) := eta r in\n         (if count =? 0\n          then r1\n          else if count <? n\n               then or (shr r1 count) (shl r2 (n - count))\n               else shr r2 (count - n),\n          if count =? 0\n          then r2\n          else if count <? n\n               then shr r2 count\n               else ldi 0).\n\n    (** Require a [decoder] instance to aid typeclass search in\n        resolving [n] *)\n    Global Instance shl_double {decode : decoder n W} : shift_left_immediate (tuple W 2)\n      := { shl := shift_left_immediate_double }.\n    Global Instance shr_double {decode : decoder n W} : shift_right_immediate (tuple W 2)\n      := { shr := shift_right_immediate_double }.\n  End shl_shr.\n\n  Section shrd.\n    Context (n : Z) {W}\n            {ldi : load_immediate W}\n            {shrd : shift_right_doubleword_immediate W}.\n\n    Definition shift_right_doubleword_immediate_double (high low : tuple W 2) (count : Z) : tuple W 2\n      := dlet high := high in\n         dlet low := low in\n         let (high1, high2) := eta high in\n         let (low1, low2) := eta low in\n         (if count =? 0\n          then low1\n          else if count <? n\n               then shrd low2 low1 count\n               else if count <? 2 * n\n                    then shrd high1 low2 (count - n)\n                    else shrd high2 high1 (count - 2 * n),\n          if count =? 0\n          then low2\n          else if count <? n\n               then shrd high1 low2 count\n               else if count <? 2 * n\n                    then shrd high2 high1 (count - n)\n                    else shrd (ldi 0) high2 (count - 2 * n)).\n\n    (** Require a [decoder] instance to aid typeclass search in\n        resolving [n] *)\n    Global Instance shrd_double {decode : decoder n W} : shift_right_doubleword_immediate (tuple W 2)\n      := { shrd := shift_right_doubleword_immediate_double }.\n  End shrd.\n\n  Section double_from_half.\n    Context {half_n : Z} {W}\n            {mulhwll : multiply_low_low W}\n            {mulhwhl : multiply_high_low W}\n            {mulhwhh : multiply_high_high W}\n            {adc : add_with_carry W}\n            {shl : shift_left_immediate W}\n            {shr : shift_right_immediate W}\n            {ldi : load_immediate W}.\n\n    Definition mul_double (a b : W) : tuple W 2\n      := dlet a              := a in\n         dlet b              := b in\n         let out : tuple W 2 := (mulhwll a b, mulhwhh a b) in\n         dlet out            := out in\n         dlet tmp            := mulhwhl a b in\n         dlet addv           := (ripple_carry_adc adc out (shl tmp half_n, shr tmp half_n) false) in\n         let (_, out)        := eta addv in\n         dlet tmp            := mulhwhl b a in\n         dlet addv           := (ripple_carry_adc adc out (shl tmp half_n, shr tmp half_n) false) in\n         let (_, out)        := eta addv in\n         out.\n\n    (** Require a dummy [decoder] for these instances to allow\n            typeclass inference of the [half_n] argument *)\n    Global Instance mul_double_multiply {decode : decoder (2 * half_n) W} : multiply_double W\n      := { muldw a b := mul_double a b }.\n  End double_from_half.\n\n  Global Instance mul_double_multiply_low_low {W} {muldw : multiply_double W}\n    : multiply_low_low (tuple W 2)\n    := { mulhwll a b := muldw (fst a) (fst b) }.\n  Global Instance mul_double_multiply_high_low {W} {muldw : multiply_double W}\n    : multiply_high_low (tuple W 2)\n    := { mulhwhl a b := muldw (snd a) (fst b) }.\n  Global Instance mul_double_multiply_high_high {W} {muldw : multiply_double W}\n    : multiply_high_high (tuple W 2)\n    := { mulhwhh a b := muldw (snd a) (snd b) }.\nEnd tuple2.\n\nGlobal Arguments mul_double half_n {_ _ _ _ _ _ _} _ _.\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/LegacyArithmetic/Double/Core.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.27637745216592735}}
{"text": "Require Import sepcomp.semantics.\nRequire Import sepcomp.semantics_lemmas.\n\n(** * Cooperating Interaction Semantics *)\n\n(** Cooperating semantics impose additional constraints; in particular, they\n   specialize interaction semantics to CompCert memories and require that the\n   memories produced by coresteps are [forward] wrt. the initial memory. See\n   [core/mem_lemmas.v] for the defn. of [mem_forward]. *)\n\nRequire Import compcert.common.Memory.\nRequire Import sepcomp.mem_lemmas.\nRecord CoopCoreSem {G C} :=\n  { coopsem :> CoreSemantics G C mem\n  ; corestep_fwd :\n      forall g c m c' m' (CS: corestep coopsem g c m c' m'),\n      mem_forward m m'\n  ; corestep_rdonly:\n      forall g c m c' m' (CS: corestep coopsem g c m c' m') b,\n      Mem.valid_block m b -> readonly m b m'}.\n\nImplicit Arguments CoopCoreSem [].\n\n\nDefinition MemSem2CoopCoreSem {G C} (s:@MemSem G C): @CoopCoreSem G C.\nProof.\neapply Build_CoopCoreSem with (coopsem := s).\napply semantics_lemmas.corestep_fwd.\napply semantics_lemmas.corestep_rdonly.\nDefined.\n\nSection CoopCoreSemLemmas.\nContext {G C: Type}.\nVariable coopsem: CoopCoreSem G C.\n\nLemma corestepN_fwd: forall ge c m c' m' n,\n  corestepN coopsem ge n c m c' m' ->\n  mem_forward m m'.\nProof.\nintros until n; revert c m.\ninduction n; simpl; auto.\ninversion 1; apply mem_forward_refl; auto.\nintros c m [c2 [m2 [? ?]]].\napply mem_forward_trans with (m2 := m2).\napply corestep_fwd in H; auto.\neapply IHn; eauto.\nQed.\n\nLemma corestep_star_fwd: forall g c m c' m'\n  (CS:corestep_star coopsem g c m c' m'),\n  mem_forward m m'.\nProof.\n  intros. destruct CS.\n  eapply corestepN_fwd.\n  apply H.\nQed.\n\nLemma corestep_plus_fwd: forall g c m c' m'\n  (CS:corestep_plus coopsem g c m c' m'),\n  mem_forward m m'.\nProof.\n   intros. destruct CS.\n   eapply corestepN_fwd.\n   apply H.\nQed.\n\nLemma corestepN_rdonly: forall ge c m c' m' n,\n  corestepN coopsem ge n c m c' m' -> forall b\n  (VB: Mem.valid_block m b), readonly m b m'.\nProof.\nintros until n; revert c m.\ninduction n; simpl; auto.\ninversion 1; intros. apply readonly_refl.\nintros c m [c2 [m2 [? ?]]].\nintros. apply readonly_trans with (m2 := m2).\neapply corestep_rdonly; eauto.\neapply IHn; eauto. eapply corestep_fwd; eauto.\nQed.\n\nLemma corestep_plus_rdonly ge c m c' m'\n  (CS: corestep_plus coopsem ge c m c' m') b\n  (VB: Mem.valid_block m b): readonly m b m'.\nProof.\n  destruct CS. eapply corestepN_rdonly; eauto.\nQed.\n\nLemma corestep_star_rdonly ge c m c' m'\n  (CS: corestep_star coopsem ge c m c' m') b\n  (VB: Mem.valid_block m b): readonly m b m'.\nProof.\n  destruct CS. eapply corestepN_rdonly; eauto.\nQed.\n\nEnd CoopCoreSemLemmas.\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/CoopCoreSem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2763774521659273}}
{"text": "(* ** Imports and settings *)\nFrom mathcomp Require Import all_ssreflect all_algebra.\nFrom mathcomp Require Import word_ssrZ.\nRequire Import xseq.\nRequire Export xseq ZArith strings word utils var type warray_.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLocal Unset Elimination Schemes.\n\n(* ---------------------------------------------------------------------- *)\n\nVariant glob_value := \n  | Gword : forall (ws:wsize), word ws -> glob_value\n  | Garr  : forall (p:positive), WArray.array p -> glob_value.\n\n(* ---------------------------------------------------------------------- *)\n\nDefinition glob_decl := (var * glob_value)%type.\n\nNotation glob_decls  := (seq glob_decl).\n\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/lang/global.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.2763774450167858}}
{"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 A B C G Aprime Aprimeprime Bprime Cprime Bprimeprime Bprimeprimeprime : Universe, ((wd_ A B /\\ (wd_ B C /\\ (wd_ A C /\\ (wd_ Bprime A /\\ (wd_ Bprime C /\\ (wd_ Aprime B /\\ (wd_ Aprime C /\\ (wd_ Cprime A /\\ (wd_ Cprime B /\\ (wd_ Aprimeprime Bprimeprime /\\ (wd_ Aprime Bprimeprimeprime /\\ (wd_ Aprime Bprime /\\ (wd_ Bprime Bprimeprimeprime /\\ (wd_ G Aprime /\\ (wd_ G Aprimeprime /\\ (wd_ G Bprimeprime /\\ (wd_ Aprime Bprimeprime /\\ (wd_ Bprimeprime Bprimeprimeprime /\\ (wd_ G Bprimeprimeprime /\\ (wd_ Aprime Aprimeprime /\\ (wd_ B G /\\ (wd_ Bprimeprime B /\\ (wd_ A G /\\ (wd_ Aprimeprime A /\\ (col_ Aprime Bprime Bprimeprimeprime /\\ (col_ G Bprimeprime Bprimeprimeprime /\\ (col_ Bprimeprime B G /\\ (col_ Cprime A B /\\ (col_ Bprime A C /\\ (col_ G Aprime Aprimeprime /\\ (col_ Aprimeprime A G /\\ (col_ Aprime B C /\\ (col_ Aprime Bprimeprime Aprime /\\ (col_ A Aprimeprime Aprime /\\ col_ A B G)))))))))))))))))))))))))))))))))) -> 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_1123.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2763347322761048}}
{"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 type_sys_useful.\nRequire Import dest_close.\n\n\nLemma close_type_system_func {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_function A v B)\n    -> computes_to_valc lib T' (mkc_function 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' <=> (forall (a a' : CTerm) (e : eqa a a'), eqb a a' e (mkc_apply t a) (mkc_apply t' a')))\n    -> per_func 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\n    SSCase \"CL_func\".\n    allunfold @per_func; 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_function); intro i.\n    repeat (autodimp i hyp; try (complete (introv e; eqconstr e; sp))); repnd.\n\n    unfold eq_term_equals; sp.\n    rw t0; rw eqiff; split; sp.\n\n    duplicate e as e'; rw <- i0 in e.\n    generalize (i1 a a' e' e); intro k.\n    rw k; sp.\n\n    duplicate e as e'; rw i0 in e.\n    generalize (i1 a a' e e'); intro k.\n    rw <- k; sp.\n\n  + SCase \"type_symmetric\"; repdors; subst;\n    dclose_lr;\n    apply CL_func;\n    clear per;\n    allunfold @per_func; exrepd;\n    unfold per_func;\n    exists eqa0 eqb0; sp;\n    allrw <-; sp.\n\n  + SCase \"type_value_respecting\"; repdors; subst;\n    apply CL_func; unfold per_func; exists eqa eqb; sp.\n\n    duplicate c1 as ct.\n    apply @cequivc_mkc_function 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_function 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; sp.\n    onedtsp e pp p0 p1 c t t0 t3 tygs tygt dum.\n    apply eqiff; sp.\n    assert (eqa a a) as eqaa by (apply t0 with (t2 := a'); auto).\n    assert (eqa a' a) as e' by auto.\n    assert (eq t1 t2) as eq12 by auto.\n    apply eqiff with (a := a') (a' := a) (e := e') in eq12; auto.\n\n    generalize (eq_term_equals_sym_tsp lib (close lib ts) eqa eqb a a' eqaa e0 e'\n                                       v B v' B'); intro i.\n    autodimp i h; repnd.\n\n    (* Now we prove the equality between the applies *)\n    unfold eq_term_equals in i.\n    apply i in eq12.\n    generalize (recb a a' e0); sp.\n    onedtsp X5 X6 X7 X8 X9 X10 X11 X4 tygs1 tygt1 dum1; sp.\n\n  + SCase \"term_transitive\".\n    unfold term_equality_transitive; sp.\n    apply eqiff; sp.\n    assert (eq t1 t2) as eqt12 by auto.\n    assert (eq t2 t3) as eqt23 by auto.\n    assert (eq t1 t2) as eq12 by auto.\n    assert (eq t2 t3) as eq23 by auto.\n    apply eqiff with (a := a) (a' := a') (e := e) in eqt12; auto.\n    apply eqiff with (a := a) (a' := a') (e := e) in eqt23; auto.\n\n    assert (eqb a a' e (mkc_apply t2 a') (mkc_apply t2 a));\n      try (complete (generalize (recb a a' e); sp;\n                     onedtsp X6 X7 X8 X9 X10 X11 X12 X5 tygs1 tygt1 dum1; sp;\n                     apply X12 with (mkc_apply t2 a'); auto;\n                     apply X12 with (mkc_apply t2 a); auto)).\n\n    assert (eq t2 t2) as eqt2;\n      try (complete (apply eqiff with (a := a) (a' := a') (e := e) in eqt2; auto;\n                     generalize (recb a a' e); sp;\n                     allunfold @type_sys_props; sp)).\n\n    apply eqiff; sp.\n    duplicate eq23 as eq2.\n    apply eqiff with (a := a0) (a' := a'0) (e := e0) in eq23; auto.\n    assert (eqa a'0 a'0) as eqa'\n           by (unfold type_sys_props in IHX1; sp; apply IHX7 with (t2 := a0); sp).\n    apply eqiff with (a := a'0) (a' := a'0) (e := eqa') in eq2; auto.\n\n    assert (eq_term_equals (eqb a0 a'0 e0) (eqb a'0 a'0 eqa')) as eqteq;\n      try (complete (unfold eq_term_equals in eqteq;\n                     apply eqteq in eq2;\n                     generalize (recb a0 a'0 e0); sp;\n                     onedtsp X6 X7 X8 X9 X10 X11 X12 X5 tygs1 tygt1 dum1; sp;\n                     apply X12 with (t2 := mkc_apply t3 a'0); sp)).\n\n    allunfold @per_func; exrepd.\n    generalize (eq_term_equals_type_family\n                  lib T T' eqa0 eqa eqb0 eqb (close lib ts)\n                  A v B A' v' B' mkc_function); intro i.\n    repeat (autodimp i hyp; try (complete (introv f; eqconstr f; sp))).\n    repnd.\n    apply eq_term_equals_sym; sp.\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 with (a := a) (a' := a') (e := e) in eqtt; auto.\n\n    generalize (recb a a' e); sp.\n    onedtsp X5 X6 X7 X8 X9 X10 X11 X4 tygs1 tygt1 dum1; sp.\n    apply X11 with (t2 := mkc_apply t a'); auto.\n    apply X4.\n    apply term_equality_refl with (t2 := mkc_apply t a); auto.\n\n    spcast; apply sp_implies_cequivc_apply; sp.\n\n  + SCase \"type_gsymmetric\"; repdors; subst; split; sp; dclose_lr;\n    apply CL_func;\n    clear per;\n    allunfold @per_func; 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_function); intro i.\n    repeat (autodimp i hyp; try (complete (introv e; eqconstr e; sp))).\n    repnd.\n\n    unfold per_func.\n    exists eqa eqb; sp.\n\n    rw t0; split; intro pp; sp.\n\n    duplicate e as e'.\n    rw i0 in e.\n    generalize (pp a a' e); intro j.\n    generalize (i1 a a' e e'); intro eqt.\n    rw eqt in j; sp.\n\n    duplicate e as e'.\n    rw <- i0 in e.\n    generalize (pp a a' e); intro j.\n    generalize (i1 a a' e' e); intro eqt.\n    rw <- eqt in j; sp.\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_function); intro i;\n    repeat (autodimp i hyp; try (complete (introv e; eqconstr e; sp)));\n    repnd.\n\n    unfold per_func.\n    exists eqa eqb; sp.\n\n    rw t0; split; intro pp; sp.\n\n    duplicate e as e'.\n    rw i0 in e.\n    generalize (pp a a' e); intro j.\n    generalize (i1 a a' e e'); intro eqt.\n    rw eqt in j; sp.\n\n    duplicate e as e'.\n    rw <- i0 in e.\n    generalize (pp a a' e); intro j.\n    generalize (i1 a a' e' e); intro eqt.\n    rw <- eqt in j; sp.\n\n  + SCase \"type_gtransitive\"; sp.\n\n  + SCase \"type_mtransitive\".\n    repdors; subst; dclose_lr;\n    try (move_term_to_top (per_func lib (close lib ts) T T4 eq2));\n    try (move_term_to_top (per_func lib (close lib ts) T' T4 eq2)).\n\n    (* 1 *)\n    clear per.\n    allunfold @per_func; 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_function); intro i.\n    repeat (autodimp i hyp; try (complete (introv e; eqconstr e; sp))).\n    repnd.\n\n    generalize (type_family_trans2\n                  lib mkc_function (close lib ts) T3 T T4 eqa eqb eqa0 eqb0 A v B A' v' B');\n      intro j.\n    repeat (autodimp j hyp; try (complete (introv e; eqconstr e; sp))).\n    repnd.\n\n    dands; apply CL_func; unfold per_func; exists eqa eqb; sp; allrw.\n\n    split; intro pp; sp.\n\n    assert (eqa1 a a') as e' by (rw <- i0; auto).\n    generalize (pp a a' e'); intro k.\n    generalize (i1 a a' e' e); intro l.\n    rw <- l; sp.\n\n    assert (eqa a a') as e' by (rw i0; auto).\n    generalize (pp a a' e'); intro k.\n    generalize (i1 a a' e e'); intro l.\n    rw l; sp.\n\n    split; intro pp; sp.\n\n    assert (eqa0 a a') as e' by (rw <- j0; auto).\n    generalize (pp a a' e'); intro k.\n    generalize (j1 a a' e e'); intro l.\n    rw l; sp.\n\n    assert (eqa a a') as e' by (rw j0; auto).\n    generalize (pp a a' e'); intro k.\n    generalize (j1 a a' e' e); intro l.\n    rw <- l; sp.\n\n    (* 2 *)\n    clear per.\n    allunfold @per_func; 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_function); intro i.\n    repeat (autodimp i hyp;\n            try (complete (introv e; eqconstr e; 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_function (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 e; eqconstr e; 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_func; unfold per_func; exists eqa eqb; sp; allrw.\n\n    split; intro pp; sp.\n\n    assert (eqa1 a a') as e' by (rw <- i0; auto).\n    generalize (pp a a' e'); intro k.\n    generalize (i1 a a' e' e); intro l.\n    rw <- l; sp.\n\n    assert (eqa a a') as e' by (rw i0; auto).\n    generalize (pp a a' e'); intro k.\n    generalize (i1 a a' e e'); intro l.\n    rw l; sp.\n\n    split; intro pp; sp.\n\n    assert (eqa0 a a') as e' by (rw <- j0; auto).\n    generalize (pp a a' e'); intro k.\n    generalize (j1 a a' e e'); intro l.\n    rw l; sp.\n\n    assert (eqa a a') as e' by (rw j0; auto).\n    generalize (pp a a' e'); intro k.\n    generalize (j1 a a' e' e); intro l.\n    rw <- l; 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_func.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2761703679267699}}
{"text": "From Tweetnacl.Libs Require Import Export.\nFrom Tweetnacl.Gen Require Import AMZubSqSel.\nFrom Tweetnacl.Gen Require Import AMZubSqSel_Prop.\nFrom Tweetnacl.Gen Require Import ABCDEF.\nFrom Tweetnacl.Gen Require Import ABCDEF_eq.\nFrom Tweetnacl.Gen Require Import abstract_fn_rev.\nFrom Tweetnacl.Gen Require Import Get_abcdef.\nRequire Import ssreflect.\n\nOpen Scope Z.\n\nSection Abstract_Fn_Rev_Eq_Thm.\n\nContext {T : Type}.\nContext {T' : Type}.\nContext {U : Type}.\nContext {ModT : T -> T}.\nContext {Mod : U -> U}.\nContext {TO : Ops T T' ModT}.\nContext {UO : Ops U U Mod}.\nContext {UTO : @Ops_Mod_P T T' U Mod ModT TO UO}.\n\nTheorem abstract_fn_rev_eq : forall (m p:Z) (z:T') (a b c d e f x a' b' c' d' e' f':T) (a'' b'' c'' d'' e'' f'': U),\n  0 <= m ->\n  (a',b',c',d',e',f') = (abstract_fn_rev m p z a b c d e f x) -> \n  (a'',b'',c'',d'',e'',f'') = (abstract_fn_rev m p (P' z) (P a) (P b) (P c) (P d) (P e) (P f) (P x))\n ->\n  Mod (P a') = Mod a'' /\\\n  Mod (P b') = Mod b'' /\\\n  Mod (P c') = Mod c'' /\\\n  Mod (P d') = Mod d'' /\\\n  Mod (P e') = Mod e'' /\\\n  Mod (P f') = Mod f''.\nProof.\n  intros m p z a b c d e f x a' b' c' d' e' f' a'' b'' c'' d'' e'' f'' Hm.\n  gen a'' b'' c'' d'' e'' f''.\n  gen a' b' c' d' e' f'.\n  gen p z a b c d e f x.\n  pattern m.\n  eapply natlike_ind.\n  3: omega.\n  move=> p z a b c d e f x a' b' c' d' e' f' a'' b'' c'' d'' e'' f''.\n  rewrite abstract_fn_rev_equation Zle_imp_le_bool.\n  rewrite abstract_fn_rev_equation Zle_imp_le_bool.\n  2,3: omega. go.\n  clear m Hm.\n  intros m Hm IHm.\n  intros p z a b c d e f x a' b' c' d' e' f' a'' b'' c'' d'' e'' f''.\n  change (Z.succ m) with (m + 1).\n  intros H' H''.\n  rewrite abstract_fn_rev_equation in H'.\n  rewrite abstract_fn_rev_equation in H''.\n  replace (m + 1 - 1) with m in H' by omega.\n  replace (m + 1 - 1) with m in H'' by omega.\n  remember (abstract_fn_rev m p z a b c d e f x) as k'.\n  remember (abstract_fn_rev m p (P' z) (P a) (P b) (P c) (P d) (P e) (P f) (P x)) as k''.\n  destruct k' as (((((a0',b0'),c0'),d0'),e0'),f0').\n  destruct k'' as (((((a0'',b0''),c0''),d0''),e0''),f0'').\n  replace (m + 1 <=? 0) with false in H'.\n  replace (m + 1 <=? 0) with false in H''.\n  2,3: symmetry ; apply Z.leb_gt ; omega.\n  inversion H'.\n  inversion H''.\n  assert(Ht:= IHm p z a b c d e f x a0' b0' c0' d0' e0' f0' a0'' b0'' c0'' d0'' e0'' f0'' Heqk' Heqk'').\n  jauto_set.\n  all: rewrite -?fa_eq -?fb_eq -?fc_eq -?fd_eq -?fe_eq -?ff_eq ?Getbit_eq.\n  all: try assumption.\n  1: rewrite fa_eq_mod ; try assumption ; symmetry ; rewrite fa_eq_mod ; try assumption.\n  2: rewrite fb_eq_mod ; try assumption ; symmetry ; rewrite fb_eq_mod ; try assumption.\n  3: rewrite fc_eq_mod ; try assumption ; symmetry ; rewrite fc_eq_mod ; try assumption.\n  4: rewrite fd_eq_mod ; try assumption ; symmetry ; rewrite fd_eq_mod ; try assumption.\n  5: rewrite fe_eq_mod ; try assumption ; symmetry ; rewrite fe_eq_mod ; try assumption.\n  6: rewrite ff_eq_mod ; try assumption ; symmetry ; rewrite ff_eq_mod ; try assumption.\n  all: symmetry ; f_equal ; f_equal ; assumption.\nQed.\n\nCorollary abstract_fn_rev_eq_a : forall (m p:Z) (z:T') (a b c d e f x: T),\n  0 <= m ->\n  Mod (P (get_a (abstract_fn_rev m p z a b c d e f x))) = Mod (get_a (abstract_fn_rev m p (P' z) (P a) (P b) (P c) (P d) (P e) (P f) (P x))).\nProof.\n  intros.\n  assert(H': exists a' b' c' d' e' f', (a',b',c',d',e',f') = (abstract_fn_rev m p z a b c d e f x)).\n  {\n  rewrite abstract_fn_rev_equation.\n  remember (abstract_fn_rev (m - 1) p z a b c d e f x) as k.\n  destruct k as (((((a0',b0'),c0'),d0'),e0'),f0').\n  flatten; do 6 eexists ; reflexivity.\n  }\n  assert(H'': exists a'' b'' c'' d'' e'' f'', (a'',b'',c'',d'',e'',f'') = (abstract_fn_rev m p (P' z) (P a) (P b) (P c) (P d) (P e) (P f) (P x))).\n  {\n  rewrite abstract_fn_rev_equation.\n  remember (abstract_fn_rev (m - 1) p (P' z) (P a) (P b) (P c) (P d) (P e) (P f) (P x)) as k.\n  destruct k as (((((a0',b0'),c0'),d0'),e0'),f0').\n  flatten; do 6 eexists ; reflexivity.\n  }\n  destruct H' as [a' [b' [c' [d' [e' [f' H']]]]]].\n  destruct H'' as [a'' [b'' [c'' [d'' [e'' [f'' H'']]]]]].\n  assert(H''':= abstract_fn_rev_eq _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H H' H'').\n  destruct H''' as [Ha [_ [Hc _]]].\n  apply (f_equal get_a) in H'.\n  apply (f_equal get_a) in H''.\n  simpl in H'.\n  simpl in H''.\n  subst.\n  assumption.\nQed.\n\nCorollary abstract_fn_rev_eq_c : forall (m p:Z) (z:T') (a b c d e f x: T),\n  0 <= m ->\n  Mod (P (get_c (abstract_fn_rev m p z a b c d e f x))) = Mod (get_c (abstract_fn_rev m p (P' z) (P a) (P b) (P c) (P d) (P e) (P f) (P x))).\nProof.\n  intros.\n  assert(H': exists a' b' c' d' e' f', (a',b',c',d',e',f') = (abstract_fn_rev m p z a b c d e f x)).\n  {\n  rewrite abstract_fn_rev_equation.\n  remember (abstract_fn_rev (m - 1) p z a b c d e f x) as k.\n  destruct k as (((((a0',b0'),c0'),d0'),e0'),f0').\n  flatten; do 6 eexists ; reflexivity.\n  }\n  assert(H'': exists a'' b'' c'' d'' e'' f'', (a'',b'',c'',d'',e'',f'') = (abstract_fn_rev m p (P' z) (P a) (P b) (P c) (P d) (P e) (P f) (P x))).\n  {\n  rewrite abstract_fn_rev_equation.\n  remember (abstract_fn_rev (m - 1) p (P' z) (P a) (P b) (P c) (P d) (P e) (P f) (P x)) as k.\n  destruct k as (((((a0',b0'),c0'),d0'),e0'),f0').\n  flatten; do 6 eexists ; reflexivity.\n  }\n  destruct H' as [a' [b' [c' [d' [e' [f' H']]]]]].\n  destruct H'' as [a'' [b'' [c'' [d'' [e'' [f'' H'']]]]]].\n  assert(H''':= abstract_fn_rev_eq _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H H' H'').\n  destruct H''' as [Ha [_ [Hc _]]].\n  apply (f_equal get_c) in H'.\n  apply (f_equal get_c) in H''.\n  simpl in H'.\n  simpl in H''.\n  subst.\n  assumption.\nQed.\n\nEnd Abstract_Fn_Rev_Eq_Thm.\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/Gen/abstract_fn_rev_eq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2761703679267699}}
{"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 RunAux.Spec.\nRequire Import RunComplete.Specs.complete_mmio_emulation.\nRequire Import RunComplete.LowSpecs.complete_mmio_emulation.\nRequire Import RunComplete.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_run_is_emulated_mmio_spec\n       get_rec_last_run_info_esr_spec\n       esr_srt_spec\n       esr_is_write_spec\n       emulate_mmio_read_spec\n       get_rec_pc_spec\n       set_rec_pc_spec\n    .\n\n  Lemma complete_mmio_emulation_spec_exists:\n    forall habd habd'  labd rec res\n           (Hspec: complete_mmio_emulation_spec rec habd = Some (habd', res))\n            (Hrel: relate_RData habd labd),\n    exists labd', complete_mmio_emulation_spec0 rec labd = Some (labd', res) /\\ relate_RData habd' labd'.\n    Proof.\n      intros. destruct Hrel. destruct rec.\n      unfold complete_mmio_emulation_spec, complete_mmio_emulation_spec0 in *.\n      repeat autounfold in *. simpl in *. unfold ref_accessible in *.\n      hsimpl_hyp Hspec; inv Hspec; simpl_query_oracle; extract_prop_dec;\n        repeat destruct_con; repeat destruct_dis; simpl in *; srewrite; repeat simpl_update_reg; simpl;\n          repeat (repeat grewrite; simpl; simpl_htarget);\n          repeat (solve_bool_range; grewrite; simpl);\n          try solve[eexists; split;\n                    [reflexivity|\n                     constructor; repeat (repeat simpl_field; repeat swap_fields);\n                     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/RunComplete/RefProof/complete_mmio_emulation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2761703679267699}}
{"text": "Require Import Coq.omega.Omega.\nRequire Import Coq.Arith.Arith Coq.Bool.Bool Bedrock.EqdepClass Coq.Lists.List.\n\nRequire Import Bedrock.Heaps.\nRequire Import Bedrock.Expr Bedrock.ExprUnify Bedrock.Folds.\nRequire Import Bedrock.SepExpr Bedrock.SepHeap Bedrock.SepLemma.\nRequire Import Bedrock.Prover.\nRequire Import Bedrock.Env.\nRequire Import Bedrock.Reflection Bedrock.Tactics Bedrock.ListFacts.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nRequire Bedrock.NatMap.\n\nModule FM := NatMap.IntMap.\n\nRemove Hints FM.Raw.Proofs.L.PX.eqk_refl FM.Raw.Proofs.L.PX.eqk_sym\n  FM.Raw.Proofs.L.PX.eqk_trans\n  FM.Raw.Proofs.PX.eqk_refl FM.Raw.Proofs.PX.eqk_sym FM.Raw.Proofs.PX.eqk_trans\n  FM.Raw.Proofs.L.PX.eqke_refl FM.Raw.Proofs.L.PX.eqke_sym FM.Raw.Proofs.L.PX.eqke_trans\n  FM.Raw.Proofs.PX.eqke_refl FM.Raw.Proofs.PX.eqke_sym FM.Raw.Proofs.PX.eqke_trans\n  FM.Raw.Proofs.L.PX.MO.lt_eq FM.Raw.Proofs.L.PX.MO.eq_lt FM.Raw.Proofs.L.MX.lt_eq\n  FM.Raw.Proofs.L.MX.eq_lt FM.Raw.Proofs.PX.MO.lt_eq FM.Raw.Proofs.PX.MO.eq_lt\n  FM.Raw.Proofs.MX.lt_eq FM.Raw.Proofs.MX.eq_lt\n  FM.Raw.Proofs.L.PX.eqk_ltk FM.Raw.Proofs.L.PX.ltk_eqk FM.Raw.Proofs.L.PX.ltk_trans\n  FM.Raw.Proofs.PX.eqk_ltk FM.Raw.Proofs.PX.ltk_eqk FM.Raw.Proofs.PX.ltk_trans\n  FM.Raw.Proofs.L.PX.MO.lt_antirefl\n  FM.Raw.Proofs.L.MX.lt_antirefl FM.Raw.Proofs.PX.MO.lt_antirefl FM.Raw.Proofs.MX.lt_antirefl\n  FM.Raw.Proofs.L.PX.eqk_not_ltk FM.Raw.Proofs.L.PX.ltk_not_eqke\n  FM.Raw.Proofs.L.PX.ltk_not_eqk FM.Raw.Proofs.L.PX.MO.lt_not_gt\n  FM.Raw.Proofs.L.PX.MO.eq_not_gt FM.Raw.Proofs.L.PX.MO.eq_neq\n  FM.Raw.Proofs.L.PX.MO.neq_eq FM.Raw.Proofs.L.PX.MO.eq_le\n  FM.Raw.Proofs.L.PX.MO.le_eq FM.Raw.Proofs.L.PX.MO.eq_not_lt\n  FM.Raw.Proofs.L.PX.MO.gt_not_eq FM.Raw.Proofs.L.MX.lt_not_gt\n  FM.Raw.Proofs.L.MX.eq_not_gt FM.Raw.Proofs.L.MX.eq_neq\n  FM.Raw.Proofs.L.MX.neq_eq FM.Raw.Proofs.L.MX.eq_le\n  FM.Raw.Proofs.L.MX.le_eq FM.Raw.Proofs.L.MX.eq_not_lt\n  FM.Raw.Proofs.L.MX.gt_not_eq FM.Raw.Proofs.PX.eqk_not_ltk\n  FM.Raw.Proofs.PX.ltk_not_eqke FM.Raw.Proofs.PX.ltk_not_eqk\n  FM.Raw.Proofs.PX.MO.lt_not_gt FM.Raw.Proofs.PX.MO.eq_not_gt\n  FM.Raw.Proofs.PX.MO.eq_neq FM.Raw.Proofs.PX.MO.neq_eq\n  FM.Raw.Proofs.PX.MO.eq_le FM.Raw.Proofs.PX.MO.le_eq\n  FM.Raw.Proofs.PX.MO.eq_not_lt FM.Raw.Proofs.PX.MO.gt_not_eq\n  FM.Raw.Proofs.MX.lt_not_gt FM.Raw.Proofs.MX.eq_not_gt\n  FM.Raw.Proofs.MX.eq_neq FM.Raw.Proofs.MX.neq_eq\n  FM.Raw.Proofs.MX.eq_le FM.Raw.Proofs.MX.le_eq\n  FM.Raw.Proofs.MX.eq_not_lt FM.Raw.Proofs.MX.gt_not_eq\n  FM.Raw.Proofs.L.PX.Sort_Inf_NotIn FM.Raw.Proofs.PX.Sort_Inf_NotIn\n  FM.Raw.Proofs.L.PX.Inf_eq FM.Raw.Proofs.L.PX.MO.Inf_lt\n  FM.Raw.Proofs.L.MX.Inf_lt FM.Raw.Proofs.PX.Inf_eq\n  FM.Raw.Proofs.PX.MO.Inf_lt FM.Raw.Proofs.MX.Inf_lt\n  FM.Raw.Proofs.L.PX.Inf_lt FM.Raw.Proofs.L.PX.MO.Inf_lt\n  FM.Raw.Proofs.L.MX.Inf_lt FM.Raw.Proofs.PX.Inf_lt\n  FM.Raw.Proofs.PX.MO.Inf_lt FM.Raw.Proofs.MX.Inf_lt\n  FM.Raw.InRight FM.Raw.InLeft FM.Raw.InRoot\n  FM.Raw.Proofs.L.PX.InA_eqke_eqk FM.Raw.Proofs.L.PX.MO.In_eq\n  FM.Raw.Proofs.L.PX.MO.ListIn_In FM.Raw.Proofs.L.MX.In_eq\n  FM.Raw.Proofs.L.MX.ListIn_In FM.Raw.Proofs.PX.InA_eqke_eqk\n  FM.Raw.Proofs.PX.MO.In_eq FM.Raw.Proofs.PX.MO.ListIn_In\n  FM.Raw.Proofs.MX.In_eq FM.Raw.Proofs.MX.ListIn_In\n  FM.Raw.Proofs.L.PX.In_inv_3 FM.Raw.Proofs.PX.In_inv_3\n  FM.Raw.Proofs.L.PX.In_inv_2 FM.Raw.Proofs.PX.In_inv_2\n  FM.Raw.MapsRight FM.Raw.MapsLeft\n  FM.Raw.MapsRoot FM.Raw.Proofs.L.PX.MO.Sort_NoDup\n  FM.Raw.Proofs.L.MX.Sort_NoDup FM.Raw.Proofs.PX.MO.Sort_NoDup\n  FM.Raw.Proofs.MX.Sort_NoDup\n  FM.Raw.BSLeaf FM.Raw.BSNode FM.Raw.Leaf FM.Raw.Node\n  FM.E.lt_trans FM.E.lt_not_eq FM.E.eq_refl\n  FM.E.eq_sym FM.E.eq_trans.\n\n\nModule Make (SH : SepHeap) (U : SynUnifier).\n  Module Import SE := SH.SE.\n  Import SH.\n  Module HEAP_FACTS := SepHeapFacts SH.\n  Import HEAP_FACTS.\n  Module ST_EXT := SepTheoryX.SepTheoryX_Ext SE.ST.\n  Module Import LEM := SepLemma.Make SE.\n\n  Module B := SE.ST.H.\n\n  Section env.\n    Variable types : list type.\n    Variable funcs : functions types.\n\n    Variable pcType : tvar.\n    Variable stateType : tvar.\n    Variable stateMem : tvarD types stateType -> B.mem.\n\n    Variable preds : predicates types pcType stateType.\n\n    (** * Some substitution functions *)\n\n    Section openForUnification.\n      Variable U : nat. (** **)\n\n      Definition ERROR : expr types.\n      refine (Var 0).\n      Qed.\n\n      Fixpoint openForUnification (e : expr types) : expr types :=\n        match e with\n          | Expr.Const _ _ => e\n          | Var v => UVar (U + v)\n          | UVar _ => e (** contradiction **)\n          | Expr.Func f es => Expr.Func f (List.map openForUnification es)\n          | Equal t l r => Equal t (openForUnification l) (openForUnification r)\n          | Not e => Not (openForUnification e)\n        end.\n\n    End openForUnification.\n\n    Section instantiate.\n      Variable doQuant : nat -> expr types.\n      Variable U_or_G : bool.\n      Variable U : nat.\n      Variable G : nat.\n      Variable G' : nat.\n      Variable sub : U.Subst types.\n\n      Fixpoint liftInstantiate (e : expr types) : expr types :=\n        match e with\n          | Expr.Const _ _ => e\n          | Var v =>\n            if NPeano.ltb v G' then (if U_or_G then UVar (v + U) else Var (v + G))\n            else let idx := U + v - G' in\n                 match U.Subst_lookup idx sub with\n                   | None => UVar idx (** contradiction **)\n                   | Some e => e\n                 end\n          | UVar v => match U.Subst_lookup v sub with (** contradiction **)\n                        | None => UVar v\n                        | Some e => e\n                      end\n          | Expr.Func f es => Expr.Func f (List.map liftInstantiate es)\n          | Equal t l r => Equal t (liftInstantiate l) (liftInstantiate r)\n          | Not e => Not (liftInstantiate e)\n        end.\n\n    End instantiate.\n\n(*\n    Definition applySHeap (F : expr types -> expr types) (sh : SHeap types pcType stateType) : SHeap types pcType stateType :=\n      {| impures := MM.mmap_map (map F) (impures sh)\n       ; pures := map F (pures sh)\n       ; other := other sh\n       |}.\n*)\n\n    (** Preprocessed databases of hints *)\n\n    Definition hintSide := list (lemma types pcType stateType).\n    (* A complete set of unfolding hints of a single sidedness (see below) *)\n\n    Definition hintSideD := Forall (lemmaD funcs preds nil nil).\n\n    Record hintsPayload := {\n      Forward : hintSide;\n      (* Apply on the lefthand side of an implication *)\n      Backward : hintSide\n      (* Apply on the righthand side *)\n    }.\n\n    Definition default_hintsPayload : hintsPayload :=\n      {| Forward := nil\n       ; Backward := nil\n       |}.\n\n    Definition composite_hintsPayload (l r : hintsPayload) : hintsPayload :=\n      {| Forward := Forward l ++ Forward r\n       ; Backward := Backward l ++ Backward r\n       |}.\n\n    Record hintsSoundness (Payload : hintsPayload) : Prop := {\n      ForwardOk : hintSideD (Forward Payload);\n      BackwardOk : hintSideD (Backward Payload)\n    }.\n\n    Theorem hintsSoundness_default : hintsSoundness default_hintsPayload.\n    Proof.\n      econstructor; constructor.\n    Qed.\n\n    Theorem hintsSoundness_composite l r (L : hintsSoundness l) (R : hintsSoundness r)\n      : hintsSoundness (composite_hintsPayload l r).\n    Proof.\n      econstructor; simpl; eapply Folds.Forall_app; solve [ eapply ForwardOk; auto | eapply BackwardOk; auto ].\n    Qed.\n\n    (** Applying up to a single hint to a hashed separation formula *)\n\n    Fixpoint find A B (f : A -> option B) (ls : list A) : option B :=\n      match ls with\n        | nil => None\n        | x :: ls' => match f x with\n                        | None => find f ls'\n                        | v => v\n                      end\n      end.\n\n    Lemma findOk : forall A B (f : A -> option B) ls res,\n      find f ls = Some res ->\n      exists a, In a ls /\\ f a = Some res.\n    Proof.\n      clear. induction ls; intros; simpl in *; try congruence.\n      revert H. consider (f a); intros. inversion H0; subst; exists a; intuition.\n      eapply IHls in H0. destruct H0; intuition. eauto.\n    Qed.\n\n    Fixpoint findWithRest' A B (f : A -> list A -> option B) (ls acc : list A) : option B :=\n      match ls with\n        | nil => None\n        | x :: ls' => match f x (rev_append acc ls') with\n                        | None => findWithRest' f ls' (x :: acc)\n                        | v => v\n                      end\n      end.\n\n    Lemma findWithRest'Ok : forall A B (f : A -> list A -> option B) ls acc res,\n      findWithRest' f ls acc = Some res ->\n      exists xs x xs', ls = xs ++ x :: xs' /\\ f x (rev acc ++ xs ++ xs') = Some res.\n    Proof.\n      clear.\n      induction ls; intros; simpl in *; try congruence.\n      revert H; consider (f a (rev_append acc ls)); intros.\n      inversion H0; clear H0; subst. exists nil. exists a. exists ls. simpl. rewrite rev_append_rev in H; auto.\n      eapply IHls in H0. do 3 destruct H0. intuition. subst. clear H. simpl in *. rewrite app_ass in H2. simpl in *.\n      exists (a :: x). simpl. exists x0. exists x1. intuition.\n    Qed.\n\n    Definition findWithRest A B (f : A -> list A -> option B) (ls : list A) : option B :=\n      findWithRest' f ls nil.\n\n    Lemma findWithRestOk : forall A B (f : A -> list A -> option B) ls res,\n      findWithRest f ls = Some res ->\n      exists xs x xs', ls = xs ++ x :: xs' /\\ f x (xs ++ xs') = Some res.\n    Proof.\n      clear. unfold findWithRest; simpl. intros. eapply findWithRest'Ok in H. eauto.\n    Qed.\n\n    (* As we iterate through unfolding, we modify this sort of state. *)\n    Record unfoldingState := {\n      Vars : variables;\n      UVars : variables;\n      Heap : SH.SHeap types pcType stateType\n    }.\n\n    Section unfoldOne.\n      Variable unify_bound : nat.\n\n      Variable prover : ProverT types.\n      (* This prover must discharge all pure obligations of an unfolding lemma, if it is to be applied. *)\n      Variable facts : Facts prover.\n\n      Variable hs : hintSide.\n      (* Use these hints to unfold impure predicates. *)\n\n      Fixpoint Subst_to_env U G (s : U.Subst types) (ts : variables) (cur : uvar) : option (env types) :=\n        match ts with\n          | nil => Some nil\n          | t :: ts =>\n            match U.Subst_lookup cur s with\n              | None => None\n              | Some e =>\n                match Subst_to_env U G s ts (S cur) with\n                  | None => None\n                  | Some env =>\n                    match exprD funcs U G e t with\n                      | None => None\n                      | Some v => Some (@existT _ _ t v :: env)\n                    end\n                end\n            end\n        end.\n\n      Fixpoint checkAllInstantiated (from : nat) (ts : variables) (sub : U.Subst types) : bool :=\n        match ts with\n          | nil => true\n          | _ :: ts => if U.Subst_lookup from sub then checkAllInstantiated (S from) ts sub else false\n        end.\n\n      (** Determine if a lemma is applicable.\n       ** - [firstUVar] an index larger than the largest unification variable\n       ** - [lem] is the lemma to apply\n       ** - [args] is the outside\n       ** - [key] is the patterns (closed by [Foralls lem]) that need to unify with [args])\n       **)\n      Definition applicable U_or_G (firstUvar firstVar : nat) (lem : lemma types pcType stateType) (args key : exprs types)\n        : option (U.Subst types) :=\n        let numForalls := length (Foralls lem) in\n        (** NOTE: it is important that [key] is first because of the way the unification algorithm works **)\n        match fold_left_2_opt (U.exprUnify unify_bound) (map (openForUnification firstUvar) key) args (U.Subst_empty _) with\n          | None => None\n          | Some subst =>\n            if EqNat.beq_nat (U.Subst_size subst) numForalls && checkAllInstantiated firstUvar (Foralls lem) subst\n            then (* Now we must make sure all of the lemma's pure obligations are provable. *)\n                 if allb (Prove prover facts) (map (liftInstantiate U_or_G firstUvar firstVar 0 subst) (Hyps lem))\n                 then Some subst\n                 else None\n            else None\n        end.\n\n      (* Returns [None] if no unfolding opportunities are found.\n       * Otherwise, return state after one unfolding. *)\n      Definition unfoldForward (s : unfoldingState) : option unfoldingState :=\n        let imps := SH.impures (Heap s) in\n        let firstUvar  := length (UVars s) in\n        let firstVar   := length (Vars s) in\n        find (fun h =>\n          match Lhs h with\n            | Func f args' =>\n              match FM.find f imps with\n                | None => None\n                | Some argss =>\n                  let numForalls := length (Foralls h) in\n                  findWithRest (fun args argss =>\n                    (* We must tweak the arguments by substituting unification variables for\n                     * [forall]-quantified variables from the lemma statement. *)\n                    match applicable false firstUvar firstVar h args args' with\n                      | None => None\n                      | Some subs =>\n                        (* Remove the current call from the state, as we are about to replace\n                         * it with a simplified set of pieces. *)\n                        let impures' := FM.add f argss (impures (Heap s)) in\n                        let sh := {| impures := impures'\n                                   ; pures := pures (Heap s)\n                                   ; other := other (Heap s) |} in\n\n                        (* Time to hash the hint RHS, to (among other things) get the new existential variables it creates. *)\n                        let (exs, sh') := hash (Rhs h) in\n\n                        (* Apply the substitution that unification gave us. *)\n                        let sh' := applySHeap (liftInstantiate false firstUvar firstVar (length exs) subs) sh' in\n\n                        (* The final result is obtained by joining the hint RHS with the original symbolic heap. *)\n                        Some {| Vars := Vars s ++ rev exs\n                              ; UVars := UVars s\n                              ; Heap := star_SHeap sh sh'\n                              |}\n                    end\n                  ) argss\n              end\n            | _ => None\n          end) hs.\n\n      Definition unfoldBackward (s : unfoldingState) : option unfoldingState :=\n        let imps       := SH.impures (Heap s) in\n        let firstUvar  := length (UVars s) in\n        let firstVar   := length (Vars s) in\n        find (fun h =>\n          match Rhs h with\n            | Func f args' =>\n              match FM.find f imps with\n                | None => None\n                | Some argss =>\n                  findWithRest (fun args argss =>\n                    match applicable true firstUvar firstVar h args args' with\n                      | None => None\n                      | Some subs =>\n                        (* Remove the current call from the state, as we are about to replace it with a\n                         * simplified set of pieces. *)\n                        let impures' := FM.add f argss (impures (Heap s)) in\n                        let sh := {| impures := impures'\n                                   ; pures := pures (Heap s)\n                                   ; other := other (Heap s) |} in\n\n                        (* Time to hash the hint LHS, to (among other things) get the new existential variables it creates. *)\n                        let (exs, sh') := hash (Lhs h) in\n\n                        (* Newly introduced variables must be replaced with unification variables, and\n                         * universally quantified variables must be substituted for. *)\n                        let sh' := applySHeap (liftInstantiate true firstUvar firstVar (length exs) subs) sh' in\n\n                        (* The final result is obtained by joining the hint LHS with the original symbolic heap. *)\n                        Some {| Vars := Vars s\n                              ; UVars := UVars s ++ rev exs\n                              ; Heap := star_SHeap sh sh'\n                              |}\n                    end\n                  ) argss\n              end\n            | _ => None\n          end) hs.\n\n    End unfoldOne.\n\n    Section unfolder.\n      Definition unify_bound := 5.\n      Variable hs : hintsPayload.\n      Variable prover : ProverT types.\n\n      (* Perform up to [bound] simplifications, based on [hs]. *)\n      Fixpoint forward (bound : nat) (facts : Facts prover) (s : unfoldingState) : unfoldingState * nat :=\n        match bound with\n          | O => (s, bound)\n          | S bound' =>\n            match unfoldForward unify_bound prover facts (Forward hs) s with\n              | None => (s, bound)\n              | Some s' => forward bound' facts s'\n            end\n        end.\n\n      Fixpoint backward (bound : nat) (facts : Facts prover) (s : unfoldingState) : unfoldingState * nat :=\n        match bound with\n          | O => (s, bound)\n          | S bound' =>\n            match unfoldBackward unify_bound prover facts (Backward hs) s with\n              | None => (s, bound)\n              | Some s' => backward bound' facts s'\n            end\n        end.\n\n      Hypothesis hsOk : hintsSoundness hs.\n      Hypothesis PC : ProverT_correct prover funcs.\n\n      Lemma Subst_to_env_env : forall U G S' TS cur e0,\n        Subst_to_env U G S' TS cur = Some e0 ->\n        map (@projT1 _ _) e0 = TS.\n      Proof.\n        induction TS; simpl; intros;\n          repeat match goal with\n                   | [ H : Some _ = Some _ |- _ ] => inversion H; clear H; subst\n                   | [ H : context [ match ?X with _ => _ end ] |- _ ] =>\n                     revert H ; case_eq X ; intros; try congruence\n                   | [ |- _ ] => progress ( simpl in * )\n                   | [ |- _ ] => progress subst\n                 end; try solve [ intuition ].\n        f_equal. eauto.\n      Qed.\n\n      Lemma Subst_to_env_nth_error_lookup : forall F U G sub x v CUR,\n        Subst_to_env U G sub (typeof_env F) CUR = Some F ->\n        nth_error F x = Some v ->\n        exists e, U.Subst_lookup (CUR + x) sub = Some e /\\\n          exprD funcs U G e (projT1 v) = Some (projT2 v).\n      Proof.\n        induction F; simpl; intros; think.\n        { destruct x; simpl in *; unfold error in *; congruence. }\n        { destruct a; simpl in *. think. apply inj_pair2 in H5. subst.\n          destruct x; simpl in *.\n          { inversion H0; clear H0; subst. rewrite Plus.plus_0_r. eexists; intuition eauto. }\n          { rewrite Plus.plus_comm. simpl. rewrite Plus.plus_comm. eapply IHF in H1. simpl in H1. eapply H1. auto. } }\n      Qed.\n      Lemma Subst_to_env_typeof_env : forall U G sub ts CUR F,\n        Subst_to_env U G sub ts CUR = Some F ->\n        ts = typeof_env F.\n      Proof.\n        induction ts; simpl; intros.\n        { think. reflexivity. }\n        { consider (Subst_to_env U G sub ts (S CUR)). intros. eapply IHts in H. think. simpl. auto.\n          intros; think. }\n      Qed.\n\n      Lemma nth_error_typeof_funcs : forall f t s,\n        nth_error (typeof_funcs funcs) f = Some t ->\n        nth_error funcs f = Some s ->\n        TRange t = Range s /\\ TDomain t = Domain s.\n      Proof.\n        unfold typeof_funcs. intros. erewrite map_nth_error in H by eauto. think. unfold typeof_sig; intuition.\n      Qed.\n\n      Theorem openForUnification_spec : forall F U G e t ,\n        is_well_typed (typeof_funcs funcs) nil (typeof_env F) e t = true ->\n        exprD funcs nil F e t = exprD funcs (U ++ F) G (openForUnification (length U) e) t.\n      Proof.\n        induction e; simpl; unfold lookupAs; intros; think;\n          repeat match goal with\n                   | [ H : nth_error _ _ = Some _ |- _ ] =>\n                     eapply WellTyped_env_nth_error_Some in H; [ | solve [ eauto using typeof_env_WellTyped_env ] ] ; destruct H\n                   | [ |- _ ] => rewrite nth_error_app_R by omega\n                   | [ |- _ ] => rewrite nth_error_app_L by omega\n                   | [ H : nth_error ?L ?n = _ |- context [ nth_error ?L ?n' ] ] =>\n                     cutrewrite (n' = n); [ | omega ]\n                   | [ H : nth_error nil ?X = Some _ |- _ ] =>\n                     clear - H ; abstract (exfalso ; destruct X ; simpl in *; unfold error in *; congruence)\n                   | [ |- match ?X with _ => _ end = match ?X with _ => _ end ] =>\n                     consider X; intros; try reflexivity\n                 end; think; auto.\n        { unfold typeof_funcs in H0. rewrite map_nth_error_full in H0. rewrite H3 in H0. inversion H0; clear H0; subst.\n          destruct s; simpl in *; subst; clear - H H2. rewrite applyD_map.\n          revert H2. generalize dependent Domain. clear - H.\n          induction H; destruct Domain; intros; simpl in *; think; auto.\n          consider (exprD funcs (U ++ F) G (openForUnification (length U) x) t); intros; auto. }\n      Qed.\n\n      Theorem openForUnification_typed : forall F U G e t ,\n        is_well_typed (typeof_funcs funcs) nil F e t = true ->\n        is_well_typed (typeof_funcs funcs) (U ++ F) G (openForUnification (length U) e) t = true.\n      Proof.\n        induction e; simpl; unfold lookupAs; intros; think;\n          repeat match goal with\n                   | [ H : nth_error _ _ = Some _ |- _ ] =>\n                     eapply WellTyped_env_nth_error_Some in H; [ | solve [ eauto using typeof_env_WellTyped_env ] ] ; destruct H\n                   | [ |- _ ] => rewrite nth_error_app_R by omega\n                   | [ |- _ ] => rewrite nth_error_app_L by omega\n                   | [ H : nth_error ?L ?n = _ |- context [ nth_error ?L ?n' ] ] =>\n                     cutrewrite (n' = n); [ | omega ]\n                   | [ H : nth_error nil ?X = Some _ |- _ ] =>\n                     clear - H ; abstract (exfalso ; destruct X ; simpl in *; unfold error in *; congruence)\n                   | [ |- match ?X with _ => _ end = match ?X with _ => _ end ] =>\n                     consider X; intros; try reflexivity\n                 end; think; auto.\n        { rewrite tvar_seqb_refl. reflexivity. }\n        { destruct t0; simpl in *. clear H0. generalize dependent TDomain. induction H; destruct TDomain; simpl in *; auto.\n          intros; think; auto. }\n      Qed.\n\n      Definition quant T (b : bool) (B E : list T) : list T := if b then B ++ E else B.\n\n      Theorem liftInstantiate_spec : forall U_or_G U G G' F e t sub ts,\n          is_well_typed (typeof_funcs funcs) nil (typeof_env G' ++ typeof_env F) e t = true ->\n          Subst_to_env U G sub ts (length U) = Some F ->\n          exprD funcs nil (G' ++ F) e t =\n          exprD funcs (quant U_or_G U G') (quant (negb U_or_G) G G') (liftInstantiate U_or_G (length U) (length G) (length G') sub e) t.\n      Proof.\n        induction e; repeat progress (simpl in *; unfold lookupAs in *; intros;\n          repeat match goal with\n                   | [ H : nth_error _ _ = Some _ |- _ ] =>\n                     eapply WellTyped_env_nth_error_Some in H; [ | solve [ eauto using typeof_env_WellTyped_env ] ] ; destruct H\n                   | [ |- _ ] => rewrite nth_error_app_R by (try rewrite typeof_env_length in *; omega)\n                   | [ |- _ ] => rewrite nth_error_app_L by (try rewrite typeof_env_length in *; omega)\n                   | [ |- _ ] => rewrite nth_error_app_R in * by (try rewrite typeof_env_length in *; omega)\n                   | [ |- _ ] => rewrite nth_error_app_L in * by (try rewrite typeof_env_length in *; omega)\n                   | [ H : nth_error ?L ?n = _ |- context [ nth_error ?L ?n' ] ] =>\n                     cutrewrite (n' = n); [ | omega ]\n                   | [ H : nth_error nil ?X = Some _ |- _ ] =>\n                     clear - H ; abstract (exfalso ; destruct X ; simpl in *; unfold error in *; congruence)\n                   | [ |- match ?X with _ => _ end = match ?X with _ => _ end ] =>\n                     consider X; intros; try reflexivity\n                   | [ |- context [ NPeano.ltb ?X ?Y ] ] => consider (NPeano.ltb X Y); intros\n                 end; think); auto.\n        { rewrite EquivDec_refl_left. destruct U_or_G; simpl; unfold lookupAs; simpl;\n          rewrite nth_error_app_R by omega. cutrewrite (x + length U - length U = x); [ | omega ].\n          rewrite H. simpl. rewrite EquivDec_refl_left. auto.\n          cutrewrite (x + length G - length G = x); [ | omega ]; rewrite H. simpl. rewrite EquivDec_refl_left. auto. }\n        { rewrite typeof_env_length in *. rewrite H. simpl. rewrite EquivDec_refl_left.\n          generalize (Subst_to_env_typeof_env _ _ _ _ _ H0); intros; subst.\n          eapply Subst_to_env_nth_error_lookup in H; eauto. destruct H. intuition.\n          cutrewrite (length U + x - length G' = length U + (x - length G')); [ | omega ]. rewrite H2.\n          simpl in *. symmetry; destruct U_or_G; simpl.\n          rewrite <- app_nil_r with (l := G); eauto using exprD_weaken.\n          rewrite <- app_nil_r with (l := U); eauto using exprD_weaken. }\n        { unfold typeof_funcs in H0; rewrite map_nth_error_full in H0. rewrite H2 in H0. inversion H0; clear H0; subst.\n          destruct s; simpl in *. revert H5 H1. clear - H. generalize dependent Domain.\n          induction H; destruct Domain; simpl in *; intros; think; auto.\n          erewrite <- H; eauto. destruct (exprD funcs nil (G' ++ F) x t); auto. }\n      Qed.\n\n      Lemma checkAllInstantiated_app : forall sub ts ts' from,\n        checkAllInstantiated from (ts ++ ts') sub =\n        checkAllInstantiated from ts sub && checkAllInstantiated (length ts + from) ts' sub.\n      Proof.\n        clear. induction ts; simpl; intros; think; eauto; simpl.\n        consider (U.Subst_lookup from sub); intros; auto.\n        f_equal. rewrite Plus.plus_comm. simpl. rewrite Plus.plus_comm. reflexivity.\n      Qed.\n\n      Lemma checkAllInstantiated_dropU : forall tU tG tfuncs sub ts ts',\n        checkAllInstantiated (length tU) ts sub = true ->\n        U.Subst_WellTyped tfuncs (tU ++ ts ++ ts') tG sub ->\n        forall e t n,\n          n >= length tU ->\n          is_well_typed tfuncs (tU ++ ts) tG e t = true ->\n          U.Subst_lookup n sub = Some e ->\n          is_well_typed tfuncs tU tG e t = true.\n      Proof.\n        clear. induction ts using rev_ind; simpl; intros; think; eauto.\n        rewrite app_nil_r in *. auto.\n        rewrite checkAllInstantiated_app in H. simpl in *; think.\n        eapply IHts; eauto. rewrite app_ass in H0. simpl in *; eauto.\n        eapply is_well_typed_not_mentionsU_last. rewrite app_ass. eassumption.\n        eapply U.exprInstantiate_Removes. rewrite app_length. rewrite Plus.plus_comm; eauto.\n        instantiate (1 := e). eapply U.exprInstantiate_instantiated. eauto.\n      Qed.\n\n      Lemma checkAllInstantiated_domain : forall sub F cU,\n        checkAllInstantiated cU F sub = true ->\n        forall u, cU <= u -> u < cU + length F -> U.Subst_lookup u sub <> None.\n      Proof.\n        clear. induction F; simpl in *; intros; think. exfalso. omega.\n        consider (EqNat.beq_nat cU u); intros. subst.\n        intro. congruence. eapply IHF; eauto. omega. omega.\n      Qed.\n\n\n      Theorem liftInstantiate_typed : forall U_or_G U G G' e t sub F,\n        is_well_typed (typeof_funcs funcs) nil (G' ++ F) e t = true ->\n        U.Subst_WellTyped (typeof_funcs funcs) (U ++ F) G sub ->\n        checkAllInstantiated (length U) F sub = true ->\n        is_well_typed (typeof_funcs funcs) (quant U_or_G U G') (quant (negb U_or_G) G G')\n          (liftInstantiate U_or_G (length U) (length G) (length G') sub e) t = true.\n      Proof.\n        clear. induction e; repeat progress (simpl in *; unfold lookupAs in *; intros;\n          repeat match goal with\n                   | [ H : nth_error _ _ = Some _ |- _ ] =>\n                     eapply WellTyped_env_nth_error_Some in H; [ | solve [ eauto using typeof_env_WellTyped_env ] ] ; destruct H\n                   | [ |- _ ] => rewrite nth_error_app_R by (try rewrite typeof_env_length in *; omega)\n                   | [ |- _ ] => rewrite nth_error_app_L by (try rewrite typeof_env_length in *; omega)\n                   | [ |- _ ] => rewrite nth_error_app_R in * by (try rewrite typeof_env_length in *; omega)\n                   | [ |- _ ] => rewrite nth_error_app_L in * by (try rewrite typeof_env_length in *; omega)\n                   | [ H : nth_error ?L ?n = _ |- context [ nth_error ?L ?n' ] ] =>\n                     cutrewrite (n' = n); [ | omega ]\n                   | [ H : nth_error nil ?X = Some _ |- _ ] =>\n                     clear - H ; abstract (exfalso ; destruct X ; simpl in *; unfold error in *; congruence)\n                   | [ |- match ?X with _ => _ end = match ?X with _ => _ end ] =>\n                     consider X; intros; try reflexivity\n                   | [ |- context [ NPeano.ltb ?X ?Y ] ] => consider (NPeano.ltb X Y); intros\n                 end; think); auto.\n        { destruct U_or_G; simpl; rewrite nth_error_app_R by omega.\n          cutrewrite (x + length U - length U = x); [ | omega ]. rewrite H. rewrite tvar_seqb_refl; auto.\n          cutrewrite (x + length G - length G = x); [ | omega ]. rewrite H. rewrite tvar_seqb_refl; auto. }\n        { consider (U.Subst_lookup (length U + x - length G') sub); intros.\n          generalize H4. eapply U.WellTyped_lookup in H4; eauto. destruct H4. intuition.\n          assert (is_well_typed (typeof_funcs funcs) U G e x0 = true).\n          { eapply checkAllInstantiated_dropU. eauto. instantiate (1 := nil). rewrite app_nil_r. auto.\n            2: eauto. 2: eauto. omega. }\n          clear H7.\n          rewrite nth_error_app_R in H6 by omega.\n          cutrewrite (length U + x - length G' - length U = x - length G') in H6; [ | omega ].\n          rewrite H in H6; inversion H6; clear H6; subst. destruct U_or_G; simpl.\n          rewrite <- app_nil_r with (l := G); eapply is_well_typed_weaken; eauto.\n          rewrite <- app_nil_r with (l := U); eapply is_well_typed_weaken; eauto.\n\n          simpl. exfalso. apply nth_error_Some_length in H. eapply checkAllInstantiated_domain in H1.\n          apply H1. eassumption. omega. omega. }\n        { rewrite all2_map_1. destruct t0. clear H0. simpl in *. generalize dependent TDomain.\n          induction H; destruct TDomain; simpl in *; intros; think; auto. }\n      Qed.\n\n\n      Lemma openForUnification_liftInstantiate : forall quant sub U G e,\n        U.exprInstantiate sub (openForUnification U e) = liftInstantiate quant U G 0 sub e.\n      Proof.\n        induction e; simpl; intros; think;\n          repeat (rewrite U.exprInstantiate_Const ||\n                  rewrite U.exprInstantiate_Equal ||\n                  rewrite U.exprInstantiate_Func ||\n                  rewrite U.exprInstantiate_Not ||\n                  rewrite U.exprInstantiate_Var ||\n                  rewrite U.exprInstantiate_UVar);\n          think; auto.\n        { rewrite <- minus_n_O. reflexivity. }\n        { clear - H. f_equal. induction H; simpl; intros; think; auto. }\n      Qed.\n\n      Lemma typeof_funcs_WellTyped_funcs_eq : forall tfuncs funcs,\n        WellTyped_funcs (types := types) tfuncs funcs ->\n        tfuncs = typeof_funcs funcs.\n      Proof.\n        clear. induction 1; auto. simpl. f_equal; auto. unfold WellTyped_sig, typeof_sig in *.\n        destruct r; destruct l; intuition; f_equal; auto.\n      Qed.\n\n      Lemma Subst_to_env_app : forall U G sub ts ts' from,\n        Subst_to_env U G sub (ts ++ ts') from =\n        match Subst_to_env U G sub ts from , Subst_to_env U G sub ts' (length ts + from) with\n          | Some l , Some r => Some (l ++ r)\n          | _ , _ => None\n        end.\n      Proof.\n        induction ts; intros; simpl; think; auto.\n        destruct (Subst_to_env U G sub ts' from); auto.\n        cutrewrite (S (length ts + from) = length ts + S from); [ | omega ].\n        repeat match goal with\n                 | [ |- context [ match ?X with _ => _ end ] ] =>\n                   match X with\n                     | match _ with _ => _ end => fail 1\n                     | _ => destruct X\n                   end\n               end; auto.\n      Qed.\n\n      Lemma checkAllInstantiated_Subst_to_env_success : forall U G tU tG tfuncs,\n        WellTyped_env tU U ->\n        WellTyped_env tG G ->\n        WellTyped_funcs tfuncs funcs ->\n        forall sub ts ts',\n          checkAllInstantiated (length tU) (ts ++ ts') sub = true ->\n          U.Subst_WellTyped tfuncs (tU ++ ts ++ ts') tG sub ->\n          exists env, Subst_to_env U G sub ts (length tU) = Some env.\n      Proof.\n        clear; induction ts using rev_ind; simpl; intros; think; eauto.\n        { rewrite app_ass in *. simpl in *. generalize H2. eapply IHts in H2. 2: eauto.\n          destruct H2. rewrite Subst_to_env_app. rewrite H2. simpl.\n          intro XX. generalize XX. rewrite checkAllInstantiated_app in XX. simpl in XX. think.\n          generalize H5. eapply U.WellTyped_lookup in H5; eauto. destruct H5. intuition.\n          eapply checkAllInstantiated_dropU in XX. 5: eapply H7. 4: eauto.\n          3: omega. Focus 2. instantiate (1 := nil). repeat rewrite app_ass. simpl. rewrite app_nil_r. auto.\n          repeat rewrite nth_error_app_R in H8 by omega. repeat rewrite typeof_env_length in H8.\n          cutrewrite (length ts + length U - length U - length ts = 0) in H8; [ | omega ]. inversion H8. subst.\n          eapply is_well_typed_correct in XX.\n          4: eauto. 2: unfold WellTyped_env in *; auto. 2: unfold WellTyped_env in *; auto.\n          destruct XX. rewrite H5. eauto. }\n      Qed.\n\n\n      (** TODO: lift this outside **)\n      Lemma fold_left_2_opt_unify : forall tU tG ts args args' sub sub',\n        U.Subst_WellTyped (types := types) (typeof_funcs funcs) tU tG sub ->\n        all2 (is_well_typed (typeof_funcs funcs) tU tG) args ts = true ->\n        all2 (is_well_typed (typeof_funcs funcs) tU tG) args' ts = true ->\n        fold_left_2_opt (U.exprUnify unify_bound) args args' sub = Some sub' ->\n        U.Subst_WellTyped (typeof_funcs funcs) tU tG sub' /\\\n        U.Subst_Extends sub' sub /\\\n        map (U.exprInstantiate sub') args = map (U.exprInstantiate sub') args'.\n      Proof.\n        clear. induction ts; destruct args; destruct args'; intros; simpl in *; think;\n        try (congruence || solve [ intuition (eauto; reflexivity) ]).\n        do 2 generalize H2. apply U.exprUnify_sound in H2. intro. eapply U.exprUnify_Extends in H6.\n        intro. eapply U.exprUnify_WellTyped in H7; eauto. eapply IHts in H3; eauto. destruct H3.\n        intuition. etransitivity; eauto. rewrite H10. f_equal.\n        assert (U.exprInstantiate sub' (U.exprInstantiate s e) = U.exprInstantiate sub' (U.exprInstantiate s e0)).\n        rewrite H2. reflexivity. repeat rewrite U.exprInstantiate_Extends in H8 by eauto. auto.\n      Qed.\n\n      Lemma exprD_weaken_quant : forall U U' G G' ug ug' a t v,\n        exprD funcs U G a t = Some v ->\n        exprD funcs (quant ug U U') (quant ug' G G') a t = Some v.\n      Proof.\n        clear; destruct ug; destruct ug'; simpl; intros;\n          [ | rewrite <- app_nil_r with (l := G) | rewrite <- app_nil_r with (l := U) | auto ];\n          apply exprD_weaken; auto.\n      Qed.\n\n      Lemma liftInstantiate_lemmaD : forall U_or_G U G lem sub env,\n        Subst_to_env U G sub (Foralls lem) (length U) = Some env ->\n        lemmaD funcs preds nil nil lem ->\n        implyEach funcs (map (liftInstantiate U_or_G (length U) (length G) 0 sub) (Hyps lem)) U G\n        (forall specs : PropX.codeSpec (tvarD types pcType) (tvarD types stateType),\n          himp funcs preds nil env specs (Lhs lem) (Rhs lem)).\n      Proof.\n        clear. destruct 2; simpl in *. eapply forallEachR_sem in H1; eauto using Subst_to_env_env.\n        eapply implyEach_sem. intros. eapply implyEach_sem in H1; eauto.\n\n        clear H1 specs. unfold WellTyped_lemma in *. think. generalize dependent (Hyps lem).\n        induction l; simpl; intros; auto. think. intuition. clear H5 H7.\n        unfold Provable in *.\n        generalize (liftInstantiate_spec U_or_G U G nil (F := env)). simpl. erewrite <- Subst_to_env_typeof_env by eassumption.\n        intro. eapply H5 in H; eauto. rewrite H.\n        consider (exprD funcs U G (liftInstantiate U_or_G (length U) (length G) 0 sub a) tvProp); try contradiction; intros.\n        erewrite exprD_weaken_quant by eauto. auto.\n      Qed.\n      Lemma allb_AllProvable : forall U G facts hyps,\n        Valid PC U G facts ->\n        allb (fun x => is_well_typed (typeof_funcs funcs) (typeof_env U) (typeof_env G) x tvProp) hyps = true ->\n        allb (Prove prover facts) hyps = true ->\n        AllProvable funcs U G hyps.\n      Proof.\n        clear. induction hyps; simpl; intros; think; auto.\n        intuition; eauto. eapply Prove_correct; eauto. unfold ValidProp.\n        eapply is_well_typed_correct; eauto using typeof_env_WellTyped_env, typeof_funcs_WellTyped_funcs.\n      Qed.\n      Lemma himp_existsEach_ST_EXT_existsEach : forall cs U P vars G,\n        ST.heq cs (sexprD funcs preds U G (SE.existsEach vars P))\n        (ST_EXT.existsEach vars (fun env => sexprD funcs preds U (rev env ++ G) P)).\n      Proof.\n        Opaque ST_EXT.existsEach.\n        induction vars; simpl; intros. rewrite ST_EXT.existsEach_nil. simpl. reflexivity.\n        change (a :: vars) with ((a :: nil) ++ vars). rewrite ST_EXT.existsEach_app.\n        rewrite ST_EXT.existsEach_cons. apply ST.heq_ex. intros. rewrite ST_EXT.existsEach_nil. rewrite IHvars.\n        simpl. eapply ST_EXT.heq_existsEach. intros. rewrite app_ass. reflexivity.\n      Qed.\n      Lemma exprInstantiate_noop : forall sub (e : expr types),\n        (forall u, mentionsU u e = true -> U.Subst_lookup u sub = None) ->\n        U.exprInstantiate sub e = e.\n      Proof.\n        clear; induction e; simpl in *; intros;\n          repeat (rewrite U.exprInstantiate_Const ||\n            rewrite U.exprInstantiate_Equal ||\n              rewrite U.exprInstantiate_Func ||\n                rewrite U.exprInstantiate_Not ||\n                  rewrite U.exprInstantiate_Var ||\n                    rewrite U.exprInstantiate_UVar); think; try congruence; auto.\n        { rewrite H; auto. consider (beq_nat x x); auto. }\n        { f_equal. revert H0. induction H; simpl; intros; think; auto.\n          erewrite IHForall; try erewrite H; eauto; intros; eapply H1; think; auto using orb_true_r. }\n        { erewrite IHe1; try erewrite IHe2; eauto; intros; eapply H; think; auto using orb_true_r. }\n      Qed.\n\n      Fixpoint fromTo (start count : nat) : list nat :=\n        match count with\n          | 0 => nil\n          | S count => start :: fromTo (S start) count\n        end.\n\n      Lemma fromTo_length : forall b a, length (fromTo a b) = b.\n      Proof.\n        clear; induction b; simpl; intros; eauto.\n      Qed.\n\n      Lemma fromTo_none_less : forall b a c,\n        c < a -> ~In c (fromTo a b).\n      Proof.\n        clear; induction b; simpl; intros; auto. intro. destruct H0. omega. eapply IHb. 2: eauto. omega.\n      Qed.\n\n      Lemma checkAllInstantiated_perm : forall sub F cU,\n        checkAllInstantiated cU F sub = true ->\n        exists p, Permutation.Permutation (fromTo cU (length F) ++ p) (U.Subst_domain sub).\n      Proof.\n        clear. induction F; simpl in *; eauto; intros.\n        consider (U.Subst_lookup cU sub); auto; intros. cut (In cU (U.Subst_domain sub)); intros.\n        eapply IHF in H0. destruct H0.\n        cut (In cU x); intros. cut (exists p, Permutation.Permutation x (cU :: p)); intros.\n        destruct H3. exists x0.\n        rewrite <- H0. rewrite Permutation.Permutation_middle. apply Permutation.Permutation_app. reflexivity.\n        symmetry; auto.\n        clear -H2. induction x; inversion H2. subst. eauto. specialize (IHx H). destruct IHx. exists (a :: x0).\n        rewrite H0. apply Permutation.perm_swap.\n\n        cut (~In cU (fromTo (S cU) (length F))); intro.\n        symmetry in H0; eapply Permutation.Permutation_in in H1. 2: eauto. eapply in_app_iff in H1. destruct H1; auto.\n        exfalso; auto. eapply fromTo_none_less. 2: eauto. omega.\n\n        apply U.Subst_domain_iff. eauto.\n      Qed.\n\n\n      Lemma independent_well_typed : forall sub F cU,\n        beq_nat (U.Subst_size sub) (length F) = true ->\n        checkAllInstantiated cU F sub = true ->\n        forall u, u < cU -> U.Subst_lookup u sub = None.\n      Proof.\n        clear. intros. symmetry in H. apply beq_nat_eq in H.\n        rewrite U.Subst_size_cardinal in H. cut (~In u (U.Subst_domain sub)).\n        intros. consider (U.Subst_lookup u sub); auto. intros. exfalso. apply H2. eapply U.Subst_domain_iff. eauto.\n\n        apply checkAllInstantiated_perm in H0. destruct H0.\n        intro. eapply Permutation.Permutation_in in H2. 2: symmetry; eauto. apply in_app_or in H2. destruct H2.\n        eapply fromTo_none_less in H2; eauto.\n        apply Permutation.Permutation_length in H0. rewrite app_length in H0. rewrite fromTo_length in H0. rewrite <- H in H0.\n        destruct x. inversion H2. unfold uvar in *. simpl in *. omega.\n      Qed.\n\n      Lemma is_well_typed_mentionsU : forall U G (e : expr types) t,\n        is_well_typed (typeof_funcs funcs) U G e t = true ->\n        forall u, mentionsU u e = true -> u < length U.\n      Proof.\n        clear. induction e; simpl; intros; try solve [ think; auto ].\n        think. apply nth_error_Some_length in H. auto.\n        { consider (nth_error (typeof_funcs funcs) f). intros. consider (equiv_dec t (TRange t0)); think; intros.\n          clear H0. destruct t0; simpl in *. generalize dependent TDomain. revert H1.\n          induction H; try congruence; destruct TDomain; simpl in *; think; try congruence; intros.\n          consider (is_well_typed (typeof_funcs funcs) U G x t); intros. apply orb_true_iff in H1. destruct H1.\n          eapply H; eauto. eapply IHForall; eauto. }\n        { destruct t0. apply andb_true_iff in H. apply orb_true_iff in H0. destruct H. destruct H0; eauto. congruence. }\n        { destruct t; try congruence. eapply IHe; eauto. }\n      Qed.\n\n(*\n      (** TODO : Move to Expr **)\n      Lemma typeof_env_app : forall l r,\n        typeof_env (types := types) l ++ typeof_env r = typeof_env (l ++ r).\n      Proof.\n        clear; induction l; simpl; intros; think; auto.\n      Qed.\n\n      Lemma typeof_env_rev : forall g,\n        typeof_env (types := types) (rev g) = rev (typeof_env g).\n      Proof.\n        clear. induction g; simpl; auto. rewrite <- typeof_env_app. simpl. rewrite IHg. auto.\n      Qed.\n*)\n\n      Lemma quant_nil : forall T ug U, quant (T := T) ug U nil = U.\n      Proof.\n        clear; destruct ug; simpl; intros; try reflexivity. rewrite app_nil_r; auto.\n      Qed.\n\n(*\n      Lemma applySHeap_typed : forall U G U' G' s F,\n        (forall e t,\n          is_well_typed (typeof_funcs funcs) U G e t = true ->\n          is_well_typed (typeof_funcs funcs) U' G' (F e) t = true) ->\n        WellTyped_sheap (typeof_funcs funcs) (typeof_preds preds) U G s = true ->\n        WellTyped_sheap (typeof_funcs funcs) (typeof_preds preds) U' G' (applySHeap F s) = true.\n      Proof.\n        clear. intros. rewrite WellTyped_sheap_eq in *. destruct s; unfold applySHeap; simpl in *.\n        think. apply andb_true_iff; split.\n        rewrite WellTyped_impures_eq in H0. apply WellTyped_impures_eq. intros.\n        unfold MM.mmap_map in *. rewrite MM.FACTS.map_o in H2. unfold MM.FACTS.option_map in H2.\n        consider (SepHeap.FM.find (elt:=list (list (expr types))) k impures0); intros. think.\n        specialize (H0 _ _ H2). Opaque allb. destruct l; simpl in *; auto. Transparent allb.\n        change (map F l :: map (map F) l0) with (map (map F) (l :: l0)). generalize dependent (l :: l0); intros.\n        think. revert H3. clear - H. induction l1; simpl in *; intros; think; auto.\n        rewrite all2_map_1. erewrite all2_impl; eauto. congruence.\n        rewrite allb_map. eapply allb_impl; eauto.\n      Qed.\n*)\n\n      Theorem applicableOk : forall U_or_G U G cs facts lem args args' sub TS,\n        lemmaD funcs preds nil nil lem ->\n        Valid PC U G facts ->\n        all2 (is_well_typed (typeof_funcs funcs) (typeof_env (types := types) U) (typeof_env G)) args TS = true ->\n        all2 (is_well_typed (typeof_funcs funcs) nil (Foralls lem)) args' TS = true ->\n(*        allb (fun e => is_well_typed (typeof_funcs funcs) nil (Foralls lem) e tvProp) (Hyps lem) = true -> *)\n        applicable unify_bound prover facts U_or_G (length U) (length G) lem args args' = Some sub ->\n        args = map (liftInstantiate U_or_G (length U) (length G) 0 sub) args' /\\\n        let (lq,lh) := hash (Lhs lem) in\n        let (rq,rh) := hash (Rhs lem) in\n        ST.himp cs (ST_EXT.existsEach lq (fun lq =>\n                       sexprD funcs preds (quant U_or_G U (rev lq)) (quant (negb U_or_G) G (rev lq))\n                       (sheapD (applySHeap (liftInstantiate U_or_G (length U) (length G) (length lq) sub) lh))))\n                   (ST_EXT.existsEach rq (fun rq =>\n                       sexprD funcs preds (quant U_or_G U (rev rq)) (quant (negb U_or_G) G (rev rq))\n                       (sheapD (applySHeap (liftInstantiate U_or_G (length U) (length G) (length rq) sub) rh))))\n        /\\ WellTyped_sheap (typeof_funcs funcs) (typeof_preds preds)\n              (quant U_or_G (typeof_env U) (rev lq)) (quant (negb U_or_G) (typeof_env G) (rev lq))\n                (applySHeap (liftInstantiate U_or_G (length U) (length G) (length lq) sub) lh) = true\n        /\\ WellTyped_sheap (typeof_funcs funcs) (typeof_preds preds)\n              (quant U_or_G (typeof_env U) (rev rq)) (quant (negb U_or_G) (typeof_env G) (rev rq))\n                (applySHeap (liftInstantiate U_or_G (length U) (length G) (length rq) sub) rh) = true.\n      Proof.\n        unfold applicable; intros.\n        repeat match goal with\n                 | [ H : match ?X with _ => _ end = _ |- _ ] =>\n                   consider X; try congruence; intros\n                 | [ H : Some _ = Some _ |- _ ] => inversion H; clear H; subst\n               end.\n        eapply fold_left_2_opt_unify in H3. 2: apply U.Subst_empty_WellTyped.\n        Focus 3. eapply all2_impl. eassumption. intros. eapply is_well_typed_weaken with (u' := Foralls lem) (g' := nil).\n        eassumption.\n        Focus 2. rewrite all2_map_1. eapply all2_impl. eassumption. intros.\n        rewrite <- typeof_env_length. eapply openForUnification_typed. eauto.\n        think. split.\n        { erewrite map_ext.\n          2: intro; rewrite <- openForUnification_liftInstantiate; reflexivity.\n          think. generalize (independent_well_typed _ _ H4 H6).\n          revert H8. revert H1. clear. revert args'; revert TS.\n          induction args; destruct args'; destruct TS; simpl in *; intros; think; try congruence.\n          inversion H8. erewrite <- IHargs; eauto. f_equal. rewrite H3. symmetry. eapply exprInstantiate_noop; eauto.\n          intros. eapply H.\n          eapply is_well_typed_mentionsU in H2. 2: eauto. rewrite typeof_env_length in H2. omega. }\n        { consider (hash (Lhs lem)); consider (hash (Rhs lem)); intros; think.\n          generalize (@checkAllInstantiated_Subst_to_env_success _ _ _ _ _\n            (typeof_env_WellTyped_env U) (typeof_env_WellTyped_env G) (typeof_funcs_WellTyped_funcs funcs) sub (Foralls lem) nil).\n          rewrite app_nil_r in *. intro. destruct H11. rewrite typeof_env_length; auto. auto.\n\n          rewrite typeof_env_length in H11. generalize H.\n          eapply liftInstantiate_lemmaD with (U_or_G := U_or_G) (U := U) (G := G) in H; eauto. intro.\n          eapply implyEach_sem in H.\n          { specialize (H cs).\n            rewrite SH.hash_denote in H. rewrite H10 in H.\n            rewrite SH.hash_denote with (s := Rhs lem) in H. rewrite H9 in H. simpl in H.\n\n            destruct H12. clear H13. unfold WellTyped_lemma in *. think.\n            unfold himp in H.\n            rewrite himp_existsEach_ST_EXT_existsEach in H.\n            rewrite himp_existsEach_ST_EXT_existsEach in H.\n            split.\n            { etransitivity. etransitivity; [ | eapply H ].\n              apply ST_EXT.himp_existsEach; intros.\n\n              erewrite <- applySHeap_wt_spec. reflexivity. intros. eauto. rewrite <- rev_length with (l := G0).\n              eapply liftInstantiate_spec; eauto. rewrite <- typeof_env_app. auto.\n              cutrewrite (s0 = snd (hash (Lhs lem))). rewrite typeof_env_app.\n              rewrite typeof_env_rev.\n              cutrewrite (typeof_env G0 = fst (hash (Lhs lem))).\n              rewrite <- WellTyped_hash. simpl typeof_env. apply Subst_to_env_typeof_env in H11. rewrite <- H11. auto.\n              rewrite H10; auto. rewrite H10; auto.\n\n              apply ST_EXT.himp_existsEach. intros.\n              rewrite <- applySHeap_wt_spec. reflexivity. intros. rewrite <- rev_length with (l := G0).\n              eapply liftInstantiate_spec; eauto. rewrite <- typeof_env_app. auto.\n\n              cutrewrite (s = snd (hash (Rhs lem))). rewrite typeof_env_app. rewrite typeof_env_rev.\n              cutrewrite (typeof_env G0 = v). cutrewrite (v  = fst (hash (Rhs lem))).\n              rewrite <- WellTyped_hash. simpl. apply Subst_to_env_typeof_env in H11. rewrite <- H11. auto.\n              rewrite H9. auto. subst. reflexivity. rewrite H9. reflexivity. }\n            { rewrite WellTyped_hash in H14. rewrite WellTyped_hash in H13. think. simpl in *.\n              rewrite (Subst_to_env_typeof_env _ _ _ _ _ H11) in *.\n              split; (eapply applySHeap_typed_impl; [ | eauto ]).\n              intros.\n              eapply liftInstantiate_typed with (U_or_G := U_or_G) (U := typeof_env U) (G := typeof_env G) (sub := sub) in H15.\n              rewrite rev_length in H15. repeat rewrite typeof_env_length in H15. eapply H15. eassumption.\n              rewrite typeof_env_length. eassumption.\n              intros.\n              eapply liftInstantiate_typed with (U_or_G := U_or_G) (U := typeof_env U) (G := typeof_env G) (sub := sub) in H15.\n              rewrite rev_length in H15. repeat rewrite typeof_env_length in H15. eapply H15. eassumption.\n              rewrite typeof_env_length. eassumption. } }\n          { destruct H12. clear H13. unfold WellTyped_lemma in H12. eapply allb_AllProvable; eauto.\n            apply andb_true_iff in H12. destruct H12. apply andb_true_iff in H12. destruct H12.\n            rewrite allb_map. eapply allb_impl. eauto. intros.\n            simpl in *. generalize (@liftInstantiate_typed U_or_G (typeof_env U) (typeof_env G) nil x0 tvProp sub (Foralls lem)).\n            simpl. rewrite (Subst_to_env_typeof_env _ _ _ _ _ H11) in *. intro. apply H16 in H15; auto.\n\n            repeat rewrite quant_nil in *. repeat rewrite typeof_env_length in *. auto.\n            rewrite typeof_env_length. auto. } }\n      Qed.\n\n      Theorem applicable_WellTyped : forall U_or_G tU tG facts lem args args' sub TS,\n        WellTyped_lemma (typeof_funcs funcs) (typeof_preds preds) lem = true ->\n        all2 (is_well_typed (typeof_funcs funcs) tU tG) args TS = true ->\n        all2 (is_well_typed (typeof_funcs funcs) nil (Foralls lem)) args' TS = true ->\n        applicable unify_bound prover facts U_or_G (length tU) (length tG) lem args args' = Some sub ->\n        args = map (liftInstantiate U_or_G (length tU) (length tG) 0 sub) args' /\\\n        let (lq,lh) := hash (Lhs lem) in\n        let (rq,rh) := hash (Rhs lem) in\n           WellTyped_sheap (typeof_funcs funcs) (typeof_preds preds)\n             (quant U_or_G tU (rev lq)) (quant (negb U_or_G) tG (rev lq))\n                (applySHeap (liftInstantiate U_or_G (length tU) (length tG) (length lq) sub) lh) = true\n        /\\ WellTyped_sheap (typeof_funcs funcs) (typeof_preds preds)\n             (quant U_or_G tU (rev rq)) (quant (negb U_or_G) tG (rev rq))\n                (applySHeap (liftInstantiate U_or_G (length tU) (length tG) (length rq) sub) rh) = true.\n      Proof.\n        unfold applicable; intros.\n        repeat match goal with\n                 | [ H : match ?X with _ => _ end = _ |- _ ] =>\n                   consider X; try congruence; intros\n                 | [ H : Some _ = Some _ |- _ ] => inversion H; clear H; subst\n               end.\n        eapply fold_left_2_opt_unify in H2. 2: apply U.Subst_empty_WellTyped.\n        Focus 3. eapply all2_impl. eassumption. intros. eapply is_well_typed_weaken with (u' := Foralls lem) (g' := nil).\n        eassumption.\n        Focus 2. rewrite all2_map_1. eapply all2_impl. eassumption. intros.\n        eapply openForUnification_typed. eauto. intuition.\n        { erewrite map_ext.\n          2: intro; rewrite <- openForUnification_liftInstantiate; reflexivity. apply andb_true_iff in H3.\n          think. generalize (independent_well_typed _ _ H3 H6).\n          revert H7. revert H0. clear. revert args'; revert TS.\n          induction args; destruct args'; destruct TS; simpl in *; intros; think; try congruence.\n          inversion H7. erewrite <- IHargs; eauto. f_equal. rewrite H3. symmetry. eapply exprInstantiate_noop; eauto.\n          intros. eapply H.\n          eapply is_well_typed_mentionsU in H2. 2: eauto. omega. }\n        { consider (hash (Lhs lem)); consider (hash (Rhs lem)); intros; think.\n          unfold WellTyped_lemma in *.\n          repeat match goal with\n                   | H : _ && _ = true |- _ => apply andb_true_iff in H; destruct H\n                 end.\n          { rewrite WellTyped_hash in H11. rewrite WellTyped_hash in H10. rewrite H6 in *; rewrite H8 in *. simpl in *.\n            rewrite app_nil_r in *.\n            split; (eapply applySHeap_typed_impl; [ | eauto ]).\n            intros.\n            eapply liftInstantiate_typed with (U_or_G := U_or_G) (U := tU) (G := tG) (sub := sub) in H12; eauto.\n            rewrite rev_length in *. auto.\n            intros.\n            eapply liftInstantiate_typed with (U_or_G := U_or_G) (U := tU) (G := tG) (sub := sub) in H12; eauto.\n            rewrite rev_length in *. auto. } }\n      Qed. (** TODO: This is duplicated from the full lemma **)\n\n      Lemma ST_himp_heq_L : forall cs U G P Q S,\n        heq funcs preds U G cs P Q ->\n        ST.himp cs (sexprD funcs preds U G Q) S ->\n        ST.himp cs (sexprD funcs preds U G P) S.\n      Proof.\n        clear. intros. rewrite H. auto.\n      Qed.\n\n      Lemma Equal_remove_add_remove : forall T k (v : T) m,\n        FM.Equal (FM.remove k (FM.add k v m)) (FM.remove k m).\n      Proof.\n        clear. intros. red. intros.\n        repeat (rewrite MM.FACTS.add_o || rewrite MM.FACTS.remove_o).\n        consider (MF.FACTS.eq_dec k y); auto.\n      Qed.\n\n      Lemma unfoldForward_vars : forall unify_bound facts P Q,\n        unfoldForward unify_bound prover facts (Forward hs) P = Some Q ->\n        exists vars_ext, Vars Q = Vars P ++ vars_ext /\\ UVars Q = UVars P.\n      Proof.\n        unfold unfoldForward. intros.\n        repeat match goal with\n                 | [ H : _ = Some _ |- _ ] => eapply findOk in H || eapply findWithRestOk in H\n                 | [ H : Some _ = Some _ |- _ ] => inversion H; clear H; subst\n                 | [ H : exists x, _ |- _ ] => destruct H\n                 | [ H : _ /\\ _ |- _ ] => destruct H\n                 | [ H : context [ match ?X with _ => _ end ] |- _ ] =>\n                   (revert H; consider X; intros; try congruence) ; []\n               end; simpl. eexists; intuition.\n      Qed.\n\n      Lemma hintSideD_In : forall hs,\n        hintSideD hs -> forall x, In x hs -> lemmaD funcs preds nil nil x.\n      Proof.\n        clear. induction 1. inversion 1.\n        intros. inversion H1; subst; auto.\n      Qed.\n\n(*\n      Lemma applySHeap_singleton : forall meta_env vars_env cs F f l,\n        heq funcs preds meta_env vars_env cs\n        (sheapD (applySHeap F\n          {| impures := MM.mmap_add f l (MM.empty (list (expr types)))\n            ; pures := nil\n            ; other := nil |}))\n        (sheapD\n          {| impures := MM.mmap_add f (map F l) (MM.empty (list (expr types)))\n            ; pures := nil\n            ; other := nil |}).\n      Proof.\n        clear. intros. unfold applySHeap; simpl. repeat rewrite SH.sheapD_def; simpl.\n        heq_canceler. unfold MM.mmap_add. repeat rewrite MM.FACTS.empty_o.\n        rewrite impuresD_Add with (f := f) (argss := map F l :: nil) (i := MM.empty _). symmetry.\n        rewrite impuresD_Add with (f := f) (argss := map F l :: nil) (i := MM.empty _). reflexivity.\n        red; reflexivity. intro; eapply MM.FACTS.empty_in_iff; eassumption.\n        red; reflexivity. intro; eapply MM.FACTS.empty_in_iff; eassumption.\n      Qed.\n*)\n\n      Opaque ST_EXT.existsEach.\n\n      Lemma WellTyped_impures_find_fst_last : forall tfuncs tpreds tU tG imps x0 x1 x2 k,\n        WellTyped_impures tfuncs tpreds tU tG imps = true ->\n        FM.find (elt:=list (exprs types)) k imps = Some (x0 ++ x1 :: x2) ->\n        match x0 ++ x2 with\n          | nil => True\n          | _ :: _ =>\n            match nth_error tpreds k with\n              | Some ts =>\n                allb (fun argss : list (expr types) =>\n                  all2 (is_well_typed tfuncs tU tG) argss ts) (x0 ++ x2) = true\n              | None => False\n            end\n        end.\n      Proof.\n        clear. intros.\n        rewrite WellTyped_impures_eq in H. specialize (H _ _ H0).\n        destruct x0; simpl in *; destruct (nth_error tpreds k); think; auto. destruct x2; auto. contradiction.\n        rewrite allb_app. rewrite allb_app in H1. think. simpl in *. think.\n      Qed.\n\n      Lemma with_left : forall (P Q R : Prop),\n        (R -> P) ->\n        R /\\ Q ->\n        P /\\ Q.\n      Proof. clear. firstorder. Qed.\n\n      Lemma unfoldForward_WellTyped : forall facts P Q,\n        unfoldForward unify_bound prover facts (Forward hs) P = Some Q ->\n        WellTyped_sheap (typeof_funcs funcs) (typeof_preds preds) (UVars P) (Vars P) (Heap P) = true ->\n        WellTyped_sheap (typeof_funcs funcs) (typeof_preds preds) (UVars Q) (Vars Q) (Heap Q) = true.\n      Proof.\n        unfold unfoldForward; intros.\n        repeat match goal with\n                 | [ H : _ = Some _ |- _ ] => eapply findOk in H || eapply findWithRestOk in H\n                 | [ H : Some _ = Some _ |- _ ] => inversion H; clear H; subst\n                 | [ H : exists x, _ |- _ ] => destruct H\n                 | [ H : _ /\\ _ |- _ ] => destruct H\n                 | [ H : context [ match ?X with _ => _ end ] |- _ ] =>\n                   (revert H; consider X; intros; try congruence) ; []\n               end; simpl.\n        eapply hintSideD_In in H; eauto using ForwardOk. destruct H. clear H3.\n        rewrite WellTyped_sheap_eq in H0. apply andb_true_iff in H0. destruct H0.\n        generalize (WellTyped_impures_find_fst_last _ _ _ _ H0 H2).\n        rewrite WellTyped_impures_eq in H0. eapply H0 in H2.\n        assert (match nth_error (typeof_preds preds) f with\n           | Some ts =>\n               allb\n                 (fun argss : list (expr types) =>\n                  all2\n                    (is_well_typed (typeof_funcs funcs) (UVars P) (Vars P))\n                    argss ts) (x0 ++ x1 :: x2) = true\n           | None => False\n           end). destruct x0; simpl in *; auto. clear H2.\n        intros. rewrite <- WellTyped_sheap_star. apply andb_true_iff.  split.\n        { rewrite WellTyped_sheap_eq; simpl. apply andb_true_iff; split.\n          { rewrite WellTyped_impures_eq. intros.\n            rewrite MF.FACTS.add_o in H7. destruct (MF.FACTS.eq_dec f k).\n            { inversion H7; clear H7; subst; auto. destruct (x0 ++ x2); auto.\n              generalize dependent (e :: l0). intros. destruct (nth_error (typeof_preds preds) k); auto.\n              eapply allb_impl; try eassumption. simpl; intros. eapply all2_impl; try eassumption.\n              intros. rewrite <- app_nil_r with (l := UVars P). eapply is_well_typed_weaken. auto. }\n            { eapply H0 in H7. destruct v0; auto. destruct (nth_error (typeof_preds preds) k); auto.\n              eapply allb_impl; try eassumption. simpl; intros. eapply all2_impl; try eassumption.\n              intros; rewrite <- app_nil_r with (l := UVars P). eapply is_well_typed_weaken. auto. } }\n          { eapply allb_impl; try eassumption. simpl; intros.\n            rewrite <- app_nil_r with (l := UVars P). eapply is_well_typed_weaken. auto. } }\n        { consider (nth_error (typeof_preds preds) f); try contradiction; intros.\n          eapply applicable_WellTyped with (TS := t)in H4; try eassumption. intuition.\n          rewrite H5 in *. rewrite H1 in *. rewrite hash_Func in H9. intuition.\n          rewrite allb_app in H6; simpl in H6. apply andb_true_iff in H6. destruct H6.\n          consider (all2 (is_well_typed (typeof_funcs funcs) (UVars P) (Vars P)) x1 t); try congruence.\n          unfold WellTyped_lemma in *.\n          repeat match goal with\n                   | H : _ && _ = _ |- _ => apply andb_true_iff in H; destruct H\n                 end.\n          rewrite H1 in *. simpl in H9. rewrite H2 in H9. auto. }\n      Qed.\n\n\n      Lemma unfoldForwardOk : forall meta_env vars_env cs facts P Q,\n        WellTyped_env (UVars P) meta_env ->\n        WellTyped_env (Vars P) vars_env ->\n        Valid PC meta_env vars_env facts ->\n        unfoldForward unify_bound prover facts (Forward hs) P = Some Q ->\n        forall (WT : WellTyped_sheap (typeof_funcs funcs) (typeof_preds preds) (typeof_env meta_env) (typeof_env vars_env) (Heap P) = true),\n        ST.himp cs (sexprD funcs preds meta_env vars_env (sheapD (Heap P)))\n                   (ST_EXT.existsEach (skipn (length vars_env) (Vars Q))\n                     (fun vars_ext : list {t : tvar & tvarD types t} =>\n                       sexprD funcs preds meta_env (vars_env ++ vars_ext) (sheapD (Heap Q))))\n        /\\ WellTyped_sheap (typeof_funcs funcs) (typeof_preds preds) (UVars Q) (Vars Q) (Heap Q) = true.\n      Proof.\n        unfold unfoldForward. intros.\n        repeat match goal with\n                 | [ H : _ = Some _ |- _ ] => eapply findOk in H || eapply findWithRestOk in H\n                 | [ H : Some _ = Some _ |- _ ] => inversion H; clear H; subst\n                 | [ H : exists x, _ |- _ ] => destruct H\n                 | [ H : _ /\\ _ |- _ ] => destruct H\n                 | [ H : context [ match ?X with _ => _ end ] |- _ ] =>\n                   (revert H; consider X; intros; try congruence) ; []\n               end.\n        destruct P; simpl in *.\n\n        destruct Heap0; simpl in *.\n        eapply with_left. intro.\n        eapply ST_himp_heq_L with (Q := Star (SH.sheapD {| impures := FM.add f (x0 ++ x2) impures0\n          ; pures := pures0\n          ; other := other0\n        |})\n        (Func f x1)). 2: eapply H5.\n          { repeat rewrite SH.sheapD_def. simpl.\n            rewrite SH.impuresD_Add with (f := f) (argss := x0 ++ x2) (i := FM.remove f (FM.add f (x0 ++ x2) impures0))\n              (i' := FM.add f (x0 ++ x2) impures0).\n            rewrite SH.impuresD_Add with (f := f) (argss := x0 ++ x1 :: x2) (i := FM.remove f impures0).\n            heq_canceler.\n            symmetry. rewrite impuresD_Equiv.\n            2: rewrite Equal_remove_add_remove; reflexivity. reflexivity.\n            red; intros. repeat (rewrite MM.FACTS.add_o || rewrite MM.FACTS.remove_o).\n            destruct (MF.FACTS.eq_dec f y). subst; auto. auto. intro. apply MM.FACTS.remove_in_iff in H8. intuition congruence.\n            red. intros. repeat (rewrite MM.FACTS.add_o || rewrite MM.FACTS.remove_o). consider (MF.FACTS.eq_dec f y); subst; auto.\n            intro. apply MM.FACTS.remove_in_iff in H8. intuition congruence. }\n\n          rewrite SEP_FACTS.heq_star_comm.\n          assert (WellTyped_sexpr (typeof_funcs funcs) (typeof_preds preds) (typeof_env meta_env) (typeof_env vars_env)\n            (SH.SE.Func (types := types) (pcType := pcType) (stateType := stateType) f x1) = true).\n          { rewrite WellTyped_sheap_eq in WT. apply andb_true_iff in WT; intuition.\n            rewrite WellTyped_impures_eq in H5. simpl in *. specialize (H5 _ _ H4).\n            consider (x0 ++ x1 :: x2). intros. exfalso; destruct x0; simpl in *; congruence. intros.\n            destruct (nth_error (typeof_preds preds) f); try contradiction. rewrite <- H4 in *. rewrite allb_app in H9.\n            simpl in *. think. }\n          cut (WellTyped_sexpr (typeof_funcs funcs) (typeof_preds preds) (typeof_env meta_env) (typeof_env vars_env)\n            (sheapD {| impures := FM.add f (x0 ++ x2) impures0; pures := pures0; other := other0 |}) = true); intros.\n\n          eapply hintSideD_In in H2; eauto using ForwardOk.\n          assert (length UVars0 = length meta_env).\n          { unfold WellTyped_env in *. subst. rewrite typeof_env_length. auto. }\n          rewrite H9 in *.\n          simpl in H5. consider (nth_error (typeof_preds preds) f); intros.\n          rewrite H0 in H6. rewrite typeof_env_length in H6. eapply applicableOk with (cs := cs) in H6; [ | eauto | eauto | eauto | ].\n          Focus 2. destruct H2. unfold WellTyped_lemma in H2. think. simpl in H13. rewrite H5 in H13. eapply H13.\n          { destruct H6. rewrite H3 in *. rewrite SH.hash_Func in *. rewrite H7 in *.\n            rewrite ST_EXT.existsEach_nil in *.\n            rewrite SH.hash_denote with (s := Func f x1). rewrite SH.hash_Func.\n            unfold fst, snd, SE.existsEach. subst.\n            rewrite HEAP_FACTS.applySHeap_singleton in *. simpl in *. rewrite app_nil_r in *. destruct H11. rewrite H6. clear H6.\n            rewrite ST.heq_star_comm. rewrite ST_EXT.heq_pushIn. rewrite rw_skipn_app; eauto with list_length.\n            rewrite ST_EXT.existsEach_rev. split.\n            { eapply ST.heq_defn. eapply ST_EXT.heq_existsEach; intros.\n              rewrite <- star_SHeap_denote. simpl. apply ST.heq_star_frame.\n              { generalize dependent (sheapD {| impures := FM.add f (x0 ++ x2) impures0;\n                pures := pures0;\n                other := other0 |}). clear; intros.\n                generalize (SEP_FACTS.sexprD_weaken_wt funcs preds cs meta_env nil G s vars_env).\n                rewrite app_nil_r. intro. rewrite H; try reflexivity. auto. }\n              { rewrite rev_involutive. unfold WellTyped_env in *. subst. repeat rewrite typeof_env_length.\n                cutrewrite (length v = length (rev G)). reflexivity.\n                rewrite <- rev_length. rewrite <- H6. rewrite map_length. rewrite rev_length. reflexivity. } }\n            { rewrite <- WellTyped_sheap_star. apply andb_true_iff. split.\n              repeat rewrite WellTyped_sheap_eq in *; simpl in *. apply andb_true_iff in WT; destruct WT.\n              apply andb_true_iff; split; auto.\n              { apply WellTyped_impures_eq. intros. rewrite MM.FACTS.add_o in H13.\n                consider (MF.FACTS.eq_dec f k); subst; intros. inversion H13; clear H13; subst.\n\n                eapply WellTyped_impures_find_fst_last in H4; [ | eassumption ]. destruct (x0 ++ x2); auto.\n                destruct (nth_error (typeof_preds preds) k); auto. eapply allb_impl; try eassumption.\n                rewrite H in *. rewrite H0 in *. clear; intros; simpl in *. unfold typeof_env in *.\n                rewrite <- app_nil_r with (l := map (@projT1 _ _) meta_env).\n                eapply all2_impl; try eassumption. intros. eapply is_well_typed_weaken. auto.\n                rewrite WellTyped_impures_eq in H6. specialize (H6 _ _ H13). destruct v0; auto.\n                destruct (nth_error (typeof_preds preds) k); auto.\n                generalize dependent (e :: v0). rewrite H. rewrite H0. clear. intros.\n                eapply allb_impl; try eassumption; intros. eapply all2_impl; try eapply H; intros.\n                rewrite <- app_nil_r with (l := typeof_env meta_env). eapply is_well_typed_weaken. auto. }\n              { eapply allb_impl; try eassumption; intros. rewrite <- app_nil_r with (l := UVars0).\n                eapply is_well_typed_weaken. rewrite H0. rewrite H. eapply H13. }\n              { destruct H11. unfold WellTyped_env in *. rewrite H. rewrite H0. rewrite typeof_env_length. apply H11. } }\n            rewrite H0. rewrite typeof_env_length. reflexivity. }\n          { clear - WT H4. rewrite <- WellTyped_sheap_WellTyped_sexpr. rewrite WellTyped_sheap_eq in *. think. simpl in *.\n            apply andb_true_iff. split; auto. apply WellTyped_impures_eq; intros.\n            rewrite MM.FACTS.add_o in H1. destruct (MF.FACTS.eq_dec f k). think.\n            rewrite WellTyped_impures_eq in H. specialize (H _ _ H4). destruct x0; simpl in *. destruct x2; auto.\n            destruct (nth_error (typeof_preds preds) k); auto. simpl in *. think.\n            destruct (nth_error (typeof_preds preds) k); auto. simpl in *. think. rewrite allb_app in *. simpl in H1. think; auto.\n            rewrite WellTyped_impures_eq in H. apply H; auto. }\n      Qed.\n\n      Lemma ST_himp_heq_R : forall (cs : PropX.codeSpec (tvarD types pcType) (tvarD types stateType))\n        (U G : env types) (P Q : sexpr types pcType stateType)\n        (S : ST.hprop (tvarD types pcType) (tvarD types stateType) nil),\n        heq funcs preds U G cs P Q ->\n        ST.himp cs S (sexprD funcs preds U G Q) ->\n        ST.himp cs S (sexprD funcs preds U G P).\n      Proof.\n        clear. intros. rewrite H0. rewrite H. reflexivity.\n      Qed.\n\n      Lemma unfoldBackward_WellTyped : forall facts P Q,\n        unfoldBackward unify_bound prover facts (Backward hs) P = Some Q ->\n        WellTyped_sheap (typeof_funcs funcs) (typeof_preds preds) (UVars P) (Vars P) (Heap P) = true ->\n        WellTyped_sheap (typeof_funcs funcs) (typeof_preds preds) (UVars Q) (Vars Q) (Heap Q) = true.\n      Proof.\n        unfold unfoldBackward; intros.\n        repeat match goal with\n                 | [ H : _ = Some _ |- _ ] => eapply findOk in H || eapply findWithRestOk in H\n                 | [ H : Some _ = Some _ |- _ ] => inversion H; clear H; subst\n                 | [ H : exists x, _ |- _ ] => destruct H\n                 | [ H : _ /\\ _ |- _ ] => destruct H\n                 | [ H : context [ match ?X with _ => _ end ] |- _ ] =>\n                   (revert H; consider X; intros; try congruence) ; []\n               end; simpl.\n        eapply hintSideD_In in H; eauto using BackwardOk. destruct H. clear H3.\n        rewrite WellTyped_sheap_eq in H0. apply andb_true_iff in H0. destruct H0.\n        generalize (WellTyped_impures_find_fst_last _ _ _ _ H0 H2).\n        rewrite WellTyped_impures_eq in H0. eapply H0 in H2.\n        assert (match nth_error (typeof_preds preds) f with\n           | Some ts =>\n               allb\n                 (fun argss : list (expr types) =>\n                  all2\n                    (is_well_typed (typeof_funcs funcs) (UVars P) (Vars P))\n                    argss ts) (x0 ++ x1 :: x2) = true\n           | None => False\n           end). destruct x0; simpl in *; auto. clear H2.\n        intros. rewrite <- WellTyped_sheap_star. apply andb_true_iff.  split.\n        { rewrite WellTyped_sheap_eq; simpl. apply andb_true_iff; split.\n          { rewrite WellTyped_impures_eq. intros.\n            rewrite MF.FACTS.add_o in H7. destruct (MF.FACTS.eq_dec f k).\n            { inversion H7; clear H7; subst; auto. destruct (x0 ++ x2); auto.\n              generalize dependent (e :: l0). intros. destruct (nth_error (typeof_preds preds) k); auto.\n              eapply allb_impl; try eassumption. simpl; intros. eapply all2_impl; try eassumption.\n              intros. rewrite <- app_nil_r with (l := Vars P). eapply is_well_typed_weaken. auto. }\n            { eapply H0 in H7. destruct v0; auto. destruct (nth_error (typeof_preds preds) k); auto.\n              eapply allb_impl; try eassumption. simpl; intros. eapply all2_impl; try eassumption.\n              intros; rewrite <- app_nil_r with (l := Vars P). eapply is_well_typed_weaken. auto. } }\n          { eapply allb_impl; try eassumption. simpl; intros.\n            rewrite <- app_nil_r with (l := Vars P). eapply is_well_typed_weaken. auto. } }\n        { consider (nth_error (typeof_preds preds) f); try contradiction; intros.\n          eapply applicable_WellTyped with (TS := t)in H4; try eassumption. intuition.\n          rewrite H5 in *. rewrite H1 in *. rewrite hash_Func in H9. intuition.\n          rewrite allb_app in H6; simpl in H6. apply andb_true_iff in H6. destruct H6.\n          consider (all2 (is_well_typed (typeof_funcs funcs) (UVars P) (Vars P)) x1 t); try congruence.\n          unfold WellTyped_lemma in *.\n          repeat match goal with\n                   | H : _ && _ = _ |- _ => apply andb_true_iff in H; destruct H\n                 end.\n          rewrite H1 in *. simpl in H8. rewrite H2 in H8. auto. }\n      Qed.\n\n      Lemma unfoldBackwardOk : forall meta_env vars_env cs facts P Q,\n        WellTyped_env (UVars P) meta_env ->\n        WellTyped_env (Vars P) vars_env ->\n        Valid PC meta_env vars_env facts ->\n        unfoldBackward unify_bound prover facts (Backward hs) P = Some Q ->\n        forall (WT : WellTyped_sheap (typeof_funcs funcs) (typeof_preds preds) (typeof_env meta_env) (typeof_env vars_env) (Heap P) = true),\n        ST.himp cs (ST_EXT.existsEach (skipn (length meta_env) (UVars Q))\n                     (fun meta_ext : list {t : tvar & tvarD types t} =>\n                       sexprD funcs preds (meta_env ++ meta_ext) vars_env (sheapD (Heap Q))))\n                   (sexprD funcs preds meta_env vars_env (sheapD (Heap P)))\n        /\\ WellTyped_sheap (typeof_funcs funcs) (typeof_preds preds) (UVars Q) (Vars Q) (Heap Q) = true.\n      Proof.\n        unfold unfoldBackward. intros.\n        repeat match goal with\n                 | [ H : _ = Some _ |- _ ] => eapply findOk in H || eapply findWithRestOk in H\n                 | [ H : Some _ = Some _ |- _ ] => inversion H; clear H; subst\n                 | [ H : exists x, _ |- _ ] => destruct H\n                 | [ H : _ /\\ _ |- _ ] => destruct H\n                 | [ H : context [ match ?X with _ => _ end ] |- _ ] =>\n                   (revert H; consider X; intros; try congruence) ; []\n               end.\n        destruct P; simpl in *.\n\n        destruct Heap0; simpl in *.\n        eapply with_left. intro.\n        eapply ST_himp_heq_R with (Q := Star (SH.sheapD {| impures := FM.add f (x0 ++ x2) impures0\n          ; pures := pures0\n          ; other := other0\n        |})\n        (Func f x1)). 2: eapply H5.\n          { repeat rewrite SH.sheapD_def. simpl.\n            rewrite SH.impuresD_Add with (f := f) (argss := x0 ++ x2) (i := FM.remove f (FM.add f (x0 ++ x2) impures0))\n              (i' := FM.add f (x0 ++ x2) impures0).\n            rewrite SH.impuresD_Add with (f := f) (argss := x0 ++ x1 :: x2) (i := FM.remove f impures0).\n            heq_canceler.\n            symmetry. rewrite impuresD_Equiv.\n            2: rewrite Equal_remove_add_remove; reflexivity. reflexivity.\n            red; intros. repeat (rewrite MM.FACTS.add_o || rewrite MM.FACTS.remove_o).\n            destruct (MF.FACTS.eq_dec f y). subst; auto. auto. intro. apply MM.FACTS.remove_in_iff in H8. intuition congruence.\n            red. intros. repeat (rewrite MM.FACTS.add_o || rewrite MM.FACTS.remove_o). consider (MF.FACTS.eq_dec f y); subst; auto.\n            intro. apply MM.FACTS.remove_in_iff in H8. intuition congruence. }\n\n          rewrite SEP_FACTS.heq_star_comm.\n          assert (WellTyped_sexpr (typeof_funcs funcs) (typeof_preds preds) (typeof_env meta_env) (typeof_env vars_env)\n            (SH.SE.Func (types := types) (pcType := pcType) (stateType := stateType) f x1) = true).\n          { rewrite WellTyped_sheap_eq in WT. apply andb_true_iff in WT; intuition.\n            rewrite WellTyped_impures_eq in H5. simpl in *. specialize (H5 _ _ H4).\n            consider (x0 ++ x1 :: x2). intros. exfalso; destruct x0; simpl in *; congruence. intros.\n            destruct (nth_error (typeof_preds preds) f); try contradiction. rewrite <- H4 in *. rewrite allb_app in H9.\n            simpl in *. think. }\n          cut (WellTyped_sexpr (typeof_funcs funcs) (typeof_preds preds) (typeof_env meta_env) (typeof_env vars_env)\n            (sheapD {| impures := FM.add f (x0 ++ x2) impures0; pures := pures0; other := other0 |}) = true); intros.\n\n          eapply hintSideD_In in H2; eauto using BackwardOk.\n          assert (length UVars0 = length meta_env).\n          { unfold WellTyped_env in *. subst. rewrite typeof_env_length. auto. }\n          rewrite H9 in *.\n          simpl in H5. consider (nth_error (typeof_preds preds) f); intros.\n          rewrite H0 in H6. rewrite typeof_env_length in H6. eapply applicableOk with (cs := cs) in H6; [ | eauto | eauto | eauto | ].\n          Focus 2. destruct H2. unfold WellTyped_lemma in H2. think. simpl in H12. rewrite H5 in H12. eapply H12.\n          { destruct H6. rewrite H3 in *. rewrite SH.hash_Func in *. rewrite H7 in *.\n            rewrite ST_EXT.existsEach_nil in *.\n            rewrite SH.hash_denote with (s := Func f x1). rewrite SH.hash_Func.\n            unfold fst, snd, SE.existsEach. subst.\n            rewrite applySHeap_singleton in *. simpl in *. rewrite app_nil_r in *. destruct H11. rewrite <- H6. clear H6.\n            rewrite ST.heq_star_comm. rewrite ST_EXT.heq_pushIn. rewrite rw_skipn_app; eauto with list_length.\n            rewrite ST_EXT.existsEach_rev. split.\n            { eapply ST.heq_defn. rewrite rev_involutive. eapply ST_EXT.heq_existsEach; intros.\n              rewrite <- star_SHeap_denote. simpl. apply ST.heq_star_frame.\n              { generalize dependent (sheapD {| impures := FM.add f (x0 ++ x2) impures0;\n                pures := pures0;\n                other := other0 |}). clear; intros.\n                generalize (SEP_FACTS.sexprD_weaken_wt funcs preds cs meta_env (rev G) nil s vars_env).\n                rewrite app_nil_r. intro. rewrite H; try reflexivity. auto. }\n              { unfold WellTyped_env in *. subst. repeat rewrite map_length.\n                rewrite typeof_env_length. reflexivity. } }\n            { rewrite <- WellTyped_sheap_star. apply andb_true_iff. split.\n              repeat rewrite WellTyped_sheap_eq in *; simpl in *. apply andb_true_iff in WT; destruct WT.\n              apply andb_true_iff; split; auto.\n              { apply WellTyped_impures_eq. intros. rewrite MM.FACTS.add_o in H13.\n                consider (MF.FACTS.eq_dec f k); subst; intros. inversion H13; clear H13; subst.\n\n                eapply WellTyped_impures_find_fst_last in H4; [ | eassumption ]. destruct (x0 ++ x2); auto.\n                destruct (nth_error (typeof_preds preds) k); auto. eapply allb_impl; try eassumption.\n                rewrite H in *. rewrite H0 in *. clear; intros; simpl in *. unfold typeof_env in *.\n                rewrite <- app_nil_r with (l := map (@projT1 _ _) vars_env).\n                eapply all2_impl; try eassumption. intros. eapply is_well_typed_weaken. auto.\n                rewrite WellTyped_impures_eq in H6. specialize (H6 _ _ H13). destruct v0; auto.\n                destruct (nth_error (typeof_preds preds) k); auto.\n                generalize dependent (e :: v0). rewrite H. rewrite H0. clear. intros.\n                eapply allb_impl; try eassumption; intros. eapply all2_impl; try eapply H; intros.\n                rewrite <- app_nil_r with (l := typeof_env vars_env). eapply is_well_typed_weaken. auto. }\n              { eapply allb_impl; try eassumption; intros. rewrite <- app_nil_r with (l := Vars0).\n                eapply is_well_typed_weaken. rewrite H0. rewrite H. eapply H13. }\n              { destruct H11. unfold WellTyped_env in *. rewrite H. rewrite H0. rewrite typeof_env_length.\n                eapply H6. } } }\n          { clear - WT H4. rewrite <- WellTyped_sheap_WellTyped_sexpr. rewrite WellTyped_sheap_eq in *. think. simpl in *.\n            apply andb_true_iff. split; auto. apply WellTyped_impures_eq; intros.\n            rewrite MM.FACTS.add_o in H1. destruct (MF.FACTS.eq_dec f k). think.\n            rewrite WellTyped_impures_eq in H. specialize (H _ _ H4). destruct x0; simpl in *. destruct x2; auto.\n            destruct (nth_error (typeof_preds preds) k); auto. simpl in *. think.\n            destruct (nth_error (typeof_preds preds) k); auto. simpl in *. think. rewrite allb_app in *. simpl in H1. think; auto.\n            rewrite WellTyped_impures_eq in H. apply H; auto. }\n      Qed.\n\n      Lemma forwardLength : forall bound facts P Q r,\n        forward bound facts P = (Q,r) ->\n        exists vars_ext (* meta_ext *),\n          Vars Q = Vars P ++ vars_ext /\\\n          UVars Q = UVars P (* ++ meta_ext *).\n      Proof.\n        clear. induction bound; intros; simpl in *; eauto.\n        { inversion H; clear H; subst; exists nil; repeat rewrite app_nil_r; auto. }\n        { consider (unfoldForward unify_bound prover facts (Forward hs) P); intros.\n          { eapply IHbound in H0. eapply unfoldForward_vars in H.\n            repeat match goal with\n                     | [ H : exists x, _ |- _ ] => destruct H\n                     | [ H : _ /\\ _ |- _ ] => destruct H\n                     | [ H : _ = _ |- _ ] => rewrite H\n                   end. repeat rewrite app_ass. eauto. }\n          { inversion H0; clear H0; subst. exists nil; repeat rewrite app_nil_r; eauto. } }\n      Qed.\n\n      Lemma unfoldBackward_vars : forall unify_bound facts P Q,\n        unfoldBackward unify_bound prover facts (Backward hs) P = Some Q ->\n        exists meta_ext, Vars Q = Vars P /\\ UVars Q = UVars P ++ meta_ext.\n      Proof.\n        unfold unfoldBackward. intros.\n        repeat match goal with\n                 | [ H : _ = Some _ |- _ ] => eapply findOk in H || eapply findWithRestOk in H\n                 | [ H : Some _ = Some _ |- _ ] => inversion H; clear H; subst\n                 | [ H : exists x, _ |- _ ] => destruct H\n                 | [ H : _ /\\ _ |- _ ] => destruct H\n                 | [ H : context [ match ?X with _ => _ end ] |- _ ] =>\n                   (revert H; consider X; intros; try congruence) ; []\n               end; simpl. eexists; intuition.\n      Qed.\n\n      Lemma backwardLength : forall bound facts P Q r,\n        backward bound facts P = (Q,r) ->\n        exists meta_ext,\n          Vars Q = Vars P /\\\n          UVars Q = UVars P ++ meta_ext.\n      Proof.\n        clear. induction bound; intros; simpl in *; eauto.\n        { inversion H; clear H; subst; exists nil; repeat rewrite app_nil_r; auto. }\n        { consider (unfoldBackward unify_bound prover facts (Backward hs) P); intros.\n          { eapply IHbound in H0. eapply unfoldBackward_vars in H.\n            repeat match goal with\n                     | [ H : exists x, _ |- _ ] => destruct H\n                     | [ H : _ /\\ _ |- _ ] => destruct H\n                     | [ H : _ = _ |- _ ] => rewrite H\n                   end. repeat rewrite app_ass. eauto. }\n          { inversion H0; clear H0; subst. exists nil; repeat rewrite app_nil_r; eauto. } }\n      Qed.\n\n      Theorem forward_WellTyped : forall bound facts P Q r,\n        forward bound facts P = (Q,r) ->\n        WellTyped_sheap (typeof_funcs funcs) (typeof_preds preds) (UVars P) (Vars P) (Heap P) = true ->\n        WellTyped_sheap (typeof_funcs funcs) (typeof_preds preds) (UVars Q) (Vars Q) (Heap Q) = true.\n      Proof.\n        induction bound; simpl; intros; try subst; auto;\n          repeat match goal with\n                   | [ H : (_,_) = (_,_) |- _ ] => inversion H; clear H; subst\n                   | [ H : context [ match ?X with _ => _ end ] |- _ ] =>\n                     consider X; intros\n                 end; auto.\n        eapply unfoldForward_WellTyped in H; try eassumption. eapply IHbound; eauto.\n      Qed.\n\n      Theorem forwardOk : forall cs bound facts P Q r,\n        forward bound facts P = (Q,r) ->\n        forall meta_env vars_env,\n        WellTyped_env (UVars P) meta_env -> (** meta_env instantiates the uvars **)\n        WellTyped_env (Vars P) vars_env ->\n        forall (WT : WellTyped_sheap (typeof_funcs funcs) (typeof_preds preds) (UVars P) (Vars P) (Heap P) = true),\n        Valid PC meta_env vars_env facts ->\n        ST.himp cs (sexprD funcs preds meta_env vars_env (sheapD (Heap P)))\n                   (ST_EXT.existsEach (skipn (length vars_env) Q.(Vars)) (fun vars_ext : list { t : tvar & tvarD types t } =>\n                     (sexprD funcs preds meta_env (vars_env ++ vars_ext) (sheapD (Heap Q))))).\n      Proof.\n        induction bound; simpl; intros.\n        { inversion H; clear H; subst; repeat split; try reflexivity.\n          cutrewrite (skipn (length vars_env) (Vars Q) = nil).\n          rewrite ST_EXT.existsEach_nil. rewrite app_nil_r. reflexivity.\n          rewrite H1. rewrite <- typeof_env_length. eauto with list_length. }\n        { revert H; case_eq (unfoldForward unify_bound prover facts (Forward hs) P); intros.\n          { subst. generalize H. eapply unfoldForwardOk with (cs := cs) in H; eauto.\n            { destruct H. rewrite H.\n              intros. eapply unfoldForward_vars in H5. do 2 destruct H5.\n(*              remember (forward bound facts u). symmetry in Hequ0. *)\n              specialize (IHbound _ _ _ _ H3).\n              eapply forwardLength in H3.\n              assert (length vars_env = length (Vars P)). rewrite H1. rewrite typeof_env_length. reflexivity.\n              repeat match goal with\n                       | [ H : _ = _ |- _ ] => rewrite H\n                       | [ H : exists x, _ |- _ ] => destruct H\n                       | [ H : _ /\\ _ |- _ ] => destruct H\n                       | [ |- _ ] => rewrite app_ass in *\n                       | [ |- _ ] => rewrite rw_skipn_app by eauto with list_length\n                     end.\n              rewrite ST_EXT.existsEach_app; intros.\n              eapply ST_EXT.himp_existsEach. intros.\n              rewrite IHbound; try solve [  repeat match goal with\n                                                     | [ H : _ = _ |- _ ] => rewrite H\n                                                   end; auto ].\n              think. rewrite rw_skipn_app.\n              apply ST_EXT.himp_existsEach; intros.\n              repeat (rewrite app_nil_r || rewrite app_ass). reflexivity.\n              repeat rewrite app_length. rewrite typeof_env_length. subst. rewrite map_length. reflexivity.\n              rewrite H5. repeat rewrite app_length. subst. rewrite H1. repeat rewrite map_length.\n              unfold WellTyped_env. rewrite typeof_env_app. f_equal.\n\n              repeat match goal with\n                       | [ H : _ = _ |- _ ] => rewrite H in *\n                     end. auto.\n              rewrite <- app_nil_r with (l := meta_env); eapply Valid_weaken; eauto. }\n            { rewrite <- WT. f_equal. rewrite H0. reflexivity. rewrite H1. reflexivity. } }\n          { inversion H3; clear H3; subst. erewrite skipn_length_all.\n            rewrite ST_EXT.existsEach_nil. rewrite app_nil_r. reflexivity.\n            unfold WellTyped_env in *. rewrite H1. unfold typeof_env. reflexivity. } }\n      Qed.\n\n      Theorem backward_WellTyped : forall bound facts P Q r,\n        backward bound facts P = (Q,r) ->\n        WellTyped_sheap (typeof_funcs funcs) (typeof_preds preds) (UVars P) (Vars P) (Heap P) = true ->\n        WellTyped_sheap (typeof_funcs funcs) (typeof_preds preds) (UVars Q) (Vars Q) (Heap Q) = true.\n      Proof.\n        induction bound; simpl; intros; try subst; auto;\n          repeat match goal with\n                   | [ H : (_,_) = (_,_) |- _ ] => inversion H; clear H; subst\n                   | [ H : context [ match ?X with _ => _ end ] |- _ ] =>\n                     consider X; intros\n                 end; auto.\n        eapply unfoldBackward_WellTyped in H; try eassumption. eapply IHbound; eauto.\n      Qed.\n\n      Theorem backwardOk : forall cs bound facts P Q meta_env vars_env r,\n        backward bound facts P = (Q,r) ->\n        WellTyped_env (UVars P) meta_env -> (** meta_env instantiates the uvars **)\n        WellTyped_env (Vars P) vars_env ->\n        WellTyped_sheap (typeof_funcs funcs) (typeof_preds preds) (UVars P) (Vars P) (Heap P) = true ->\n        Valid PC meta_env vars_env facts ->\n        ST.himp cs (ST_EXT.existsEach (skipn (length meta_env) Q.(UVars)) (fun meta_ext : env types =>\n                      (sexprD funcs preds (meta_env ++ meta_ext) vars_env (sheapD (Heap Q)))))\n                   (sexprD funcs preds meta_env vars_env (sheapD (Heap P))).\n      Proof.\n        induction bound; simpl; intros.\n        { inversion H; clear H; subst. cutrewrite (skipn (length meta_env) (UVars Q) = nil). rewrite ST_EXT.existsEach_nil.\n          rewrite app_nil_r. reflexivity. rewrite H0. rewrite <- typeof_env_length. eauto with list_length. }\n        { consider (unfoldBackward unify_bound prover facts (Backward hs) P); intros.\n          { generalize H.\n            eapply unfoldBackwardOk with (cs := cs) in H; eauto. intro.\n            apply unfoldBackward_vars in H5. think.\n            generalize (backwardLength _ _ _ H4); intro. think.\n            rewrite app_ass. rewrite rw_skipn_app by (rewrite <- typeof_env_length; eauto with list_length).\n            rewrite <- H. rewrite <- H7 in H6. rewrite <- H5 in H6. erewrite rw_skipn_app.\n            2: rewrite <- typeof_env_length; reflexivity.\n            rewrite ST_EXT.existsEach_app. eapply ST_EXT.himp_existsEach. intros.\n            eapply IHbound in H4.\n            Focus 2. rewrite H7. instantiate (1 := meta_env ++ G). unfold WellTyped_env. rewrite typeof_env_app.\n            f_equal. symmetry; auto.\n            Focus 2. rewrite H5. apply typeof_env_WellTyped_env.\n            Focus 2. apply H6.\n            Focus 2. rewrite <- app_nil_r with (l := vars_env). eapply Valid_weaken; auto.\n            think. rewrite <- H4.\n            rewrite rw_skipn_app. apply ST_EXT.himp_existsEach. intros. rewrite app_ass. reflexivity.\n            repeat rewrite app_length. rewrite typeof_env_length. subst. rewrite map_length. reflexivity.\n            rewrite <- H2. f_equal. symmetry; apply H0. symmetry; apply H1. }\n          { inversion H4; clear H4; subst. cutrewrite (skipn (length meta_env) (UVars Q) = nil). rewrite ST_EXT.existsEach_nil.\n            rewrite app_nil_r. reflexivity.  rewrite H0. rewrite <- typeof_env_length. eauto with list_length. } }\n      Qed.\n\n    End unfolder.\n  End env.\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/src/Unfolder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.27607941565709304}}
{"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.\nRequire Import Mapping.\nRequire Import PFConsistent.\nRequire Import Certify.\n\nRequire Import SrcToIRThread.\n\nSet Implicit Arguments.\n\n\nModule FutureCertify.\nSection FutureCertify.\n  Variable lang: language.\n\n  Lemma future_get_inv\n        mem1 mem2\n        loc from to msg\n        (FUTURE: Memory.future mem1 mem2)\n        (GET2: Memory.get loc to mem2 = Some (from, msg)):\n    forall f m\n           (GET1: Memory.get loc to mem1 = Some (f, m)),\n      f = from /\\ m = msg \\/ m = Message.reserve.\n  Proof.\n    induction FUTURE; i.\n    { rewrite GET1 in *. inv GET2. auto. }\n    destruct m; auto.\n    exploit Memory.future_get1; try exact GET1.\n    { econs 2; try exact H. refl. }\n    i. des.\n    exploit IHFUTURE; eauto.\n  Qed.\n\n  Lemma future_get\n        rsv mem1 mem2\n        loc from to msg\n        (FUTURE: Memory.messages_le mem1 mem2)\n        (LE1: Memory.le rsv mem1)\n        (LE2: Memory.le rsv mem2)\n        (GET1: Memory.get loc to mem1 = Some (from, msg))\n        (MSG: msg <> Message.reserve \\/\n                exists f m, Memory.get loc to rsv = Some (f, m)):\n    Memory.get loc to mem2 = Some (from, msg).\n  Proof.\n    des.\n    - destruct msg; ss. eauto.\n    - exploit LE1; eauto. i.\n      rewrite x0 in GET1. inv GET1. eauto.\n  Qed.\n\n  Lemma map_get_merge\n        rsv mem loc ts\n        (LE: Memory.le rsv mem)\n        (GET: (exists from to val released na,\n                  Memory.get loc to mem = Some (from, Message.message val released na) /\\\n                  __guard__ (ts = from \\/ ts = to)) \\/\n              (exists from to msg,\n                  Memory.get loc to rsv = Some (from, msg) /\\\n                   __guard__ (ts = from \\/ ts = to))):\n    exists from to msg,\n      Memory.get loc to mem = Some (from, msg) /\\\n      __guard__ (ts = from \\/ ts = to).\n  Proof.\n    des; eauto. exploit LE; eauto.\n  Qed.\n\n  Lemma future_map\n        rsv mem mem_future fmem\n        mem_cap\n        (ONLY: Memory.reserve_only rsv)\n        (LE: Memory.le rsv mem)\n        (CLOSED: Memory.closed mem)\n        (FUTURE: Memory.messages_le mem mem_future)\n        (FUTURE_LE: Memory.le rsv mem_future)\n        (SIM: SrcToIRThread.sim_memory fmem mem_future)\n        (CAP: Memory.cap mem mem_cap):\n    exists f,\n      (<<F: f = fun loc ts fts =>\n                  ts = fts /\\\n                  ((exists from to val released na,\n                       Memory.get loc to mem = Some (from, Message.message val released na) /\\\n                       __guard__ (ts = from \\/ ts = to)) \\/\n                   (exists from to msg,\n                       Memory.get loc to rsv = Some (from, msg) /\\\n                       __guard__ (ts = from \\/ ts = to))) \\/\n                  ts = Time.incr (Memory.max_ts loc mem) /\\\n                  fts = Time.join\n                          (Time.incr (Memory.max_ts loc mem))\n                          (Time.incr (Memory.max_ts loc fmem))>>) /\\\n      (<<MAP_WF: map_wf f>>) /\\\n      (<<MAP: memory_map f rsv mem_cap fmem>>).\n  Proof.\n    esplits; [refl|..].\n    { (* map_wf *)\n      econs; ii; subst.\n      { left. splits; ss. left.\n        esplits; try eapply CLOSED; ss. left. ss.\n      }\n      { exists ((Time.incr (Memory.max_ts loc mem)) ::\n                (List.concat\n                   (List.map (fun e => [fst e; fst (snd e)]) (DOMap.elements (Cell.raw (mem loc)))))).\n        i. des.\n        - right. exploit DOMap.elements_correct; eauto. i.\n          remember (DOMap.elements (Cell.raw (mem loc))) as l.\n          clear - l x0 MAP1.\n          revert ts from to val released na MAP1 x0.\n          induction l; ss; i. des; eauto.\n          subst. ss. unguard. des; auto.\n        - right. exploit LE; eauto. i. clear MAP0.\n          exploit DOMap.elements_correct; eauto. i.\n          remember (DOMap.elements (Cell.raw (mem loc))) as l.\n          clear - l x1 MAP1.\n          revert ts from to msg MAP1 x1.\n          induction l; ss; i. des; eauto.\n          subst. ss. unguard. des; auto.\n        - left. subst. ss.\n      }\n      { inv MAP1; inv MAP2; try by (des; subst; ss).\n        - exfalso.\n          inv H. exploit map_get_merge; try exact H2; ss. i. clear H2. des. subst.\n          exploit Memory.max_ts_spec; eauto. i. des. clear GET.\n          unguard. des; subst.\n          + exploit Memory.get_ts; eauto. i. des.\n            { exploit Time.incr_spec. rewrite x1. i. timetac. }\n            eapply Time.lt_strorder.\n            etrans; [|exact x1].\n            eapply TimeFacts.le_lt_lt; [|apply Time.incr_spec]. ss.\n          + eapply Time.lt_strorder.\n            eapply TimeFacts.le_lt_lt; eauto. apply Time.incr_spec.\n        - exfalso.\n          inv H0. exploit map_get_merge; try exact H2; ss. i. clear H2. des. subst.\n          exploit Memory.max_ts_spec; eauto. i. des. clear GET.\n          unguard. des; subst.\n          + exploit Memory.get_ts; eauto. i. des.\n            { exploit Time.incr_spec. rewrite x1. i. timetac. }\n            eapply Time.lt_strorder.\n            etrans; [|exact x1].\n            eapply TimeFacts.le_lt_lt; [|apply Time.incr_spec]. ss.\n          + eapply Time.lt_strorder.\n            eapply TimeFacts.le_lt_lt; eauto. apply Time.incr_spec.\n      }\n      { inv MAP1; inv MAP2; try by (des; subst; ss).\n        - exfalso. inv H. inv H0.\n          exploit map_get_merge; try exact H2; ss. i. clear H2. des.\n          exploit Memory.max_ts_spec; eauto. i. des.\n          unguard. des; subst.\n          + eapply Time.lt_strorder.\n            eapply TimeFacts.le_lt_lt; try exact MAX.\n            exploit Memory.get_ts; try exact x0. i. des.\n            { rewrite x2, <- x1.\n              eapply TimeFacts.lt_le_lt; [|apply Time.join_l].\n              apply Time.incr_spec.\n            }\n            etrans; eauto.\n            eapply TimeFacts.lt_le_lt; [|apply Time.join_l].\n            apply Time.incr_spec.\n          + eapply Time.lt_strorder.\n            eapply TimeFacts.le_lt_lt; try exact MAX.\n            eapply TimeFacts.lt_le_lt; [|apply Time.join_l].\n            apply Time.incr_spec.\n        - exfalso. inv H. inv H0.\n          exploit map_get_merge; try exact H1; ss. i. clear H1. des.\n          exploit Memory.max_ts_spec; eauto. i. des.\n          unguard. des; subst.\n          + eapply Time.lt_strorder.\n            eapply TimeFacts.le_lt_lt; try exact MAX.\n            exploit Memory.get_ts; try exact x0. i. des.\n            { rewrite x2, <- x1.\n              eapply TimeFacts.lt_le_lt; [|apply Time.join_l].\n              apply Time.incr_spec.\n            }\n            etrans; eauto.\n            eapply TimeFacts.lt_le_lt; [|apply Time.join_l].\n            apply Time.incr_spec.\n          + eapply Time.lt_strorder.\n            eapply TimeFacts.le_lt_lt; try exact MAX.\n            eapply TimeFacts.lt_le_lt; [|apply Time.join_l].\n            apply Time.incr_spec.\n      }\n      { inv MAP1; inv MAP2; try by (des; subst; ss).\n        - inv H. inv H0.\n          exploit map_get_merge; try exact H2; ss. i. clear H2. des.\n          exploit Memory.max_ts_spec; eauto. i. des. clear GET.\n          unguard. des; subst.\n          + exploit Memory.get_ts_le; eauto. i.\n            ett; try exact x1.\n            ett; try exact MAX.\n            tet; try apply Time.join_l.\n            apply Time.incr_spec.\n          + ett; try exact MAX.\n            tet; try apply Time.join_l.\n            apply Time.incr_spec.\n        - exfalso. inv H. inv H0.\n          exploit map_get_merge; try exact H1; ss. i. clear H1. des.\n          exploit Memory.max_ts_spec; eauto. i. des. clear GET.\n          unguard. des; subst.\n          + exploit Memory.get_ts_le; eauto. i.\n            eapply Time.lt_strorder.\n            ett; try exact x1.\n            ett; try exact MAX.\n            etrans; eauto.\n            apply Time.incr_spec.\n          + eapply Time.lt_strorder.\n            ett; try exact MAX.\n            etrans; eauto.\n            apply Time.incr_spec.\n        - des. subst. timetac.\n      }\n      { inv MAP1; inv MAP2; try by (des; subst; ss).\n        - inv H. inv H0.\n          exploit map_get_merge; try exact H2; ss. i. clear H2. des.\n          exploit Memory.max_ts_spec; eauto. i. des. clear GET.\n          unguard. des; subst.\n          + exploit Memory.get_ts_le; eauto. i.\n            ett; try exact x1.\n            ett; try exact MAX.\n            apply Time.incr_spec.\n          + ett; try exact MAX.\n            apply Time.incr_spec.\n        - exfalso. inv H. inv H0.\n          exploit map_get_merge; try exact H1; ss. i. clear H1. des.\n          exploit Memory.max_ts_spec; eauto. i. des. clear GET.\n          unguard. des; subst.\n          + exploit Memory.get_ts_le; eauto. i.\n            eapply Time.lt_strorder.\n            ett; try exact x1.\n            ett; try exact MAX.\n            etrans; eauto.\n            tet; try apply Time.incr_spec.\n            apply Time.join_l.\n          + eapply Time.lt_strorder.\n            ett; try exact MAX.\n            etrans; eauto.\n            tet; try apply Time.incr_spec.\n            apply Time.join_l.\n        - des. subst. timetac.\n      }\n    }\n\n    { (* memory_map *)\n      econs; i.\n      { destruct msg; auto. right.\n        exploit Memory.cap_inv; try exact GET; eauto. i. des; ss.\n        exploit Memory.future_get1; try exact x0; eauto. i. des.\n        inv SIM. exploit COMPLETE; eauto. i.\n        esplits; try exact x2.\n        - left. splits; ss.\n          left. esplits; eauto. left. ss.\n        - left. splits; ss.\n          left. esplits; eauto. right. ss.\n        - inv CLOSED. exploit CLOSED0; eauto. i. des.\n          eapply closed_message_map; eauto. i.\n          left. splits; ss.\n          left. esplits; eauto. right. ss.\n      }\n\n      { destruct fmsg; cycle 1.\n        { inv SIM. exploit GRESERVES; eauto. ss. }\n        inv SIM. exploit SOUND; eauto. intro GET_FUTURE.\n        specialize (Memory.min_exists\n                      (fun to =>\n                         Time.le fto to /\\\n                         (exists from msg,\n                             Memory.get loc to mem = Some (from, msg) /\\\n                             __guard__ (\n                                 msg <> Message.reserve \\/\n                                 exists f m, Memory.get loc to rsv = Some (f, m))))\n                      loc mem). i. des.\n        { (* future message after lastest *)\n          specialize (Memory.max_exists\n                        (fun to =>\n                           (exists from msg,\n                             Memory.get loc to mem = Some (from, msg) /\\\n                             __guard__ (\n                                 msg <> Message.reserve \\/\n                                 exists f m, Memory.get loc to rsv = Some (f, m))))\n                        loc mem). i. des.\n          { exfalso. eapply NONE0; try apply CLOSED.\n            esplits; try apply CLOSED. left. ss.\n          }\n          rewrite SAT in GET. inv GET.\n          destruct (TimeFacts.le_lt_dec fto to_max).\n          { exploit NONE; try exact SAT; ss. esplits; eauto. }\n          exists to_max.\n          exists (Time.join\n                    (Time.incr (Memory.max_ts loc mem))\n                    (Time.incr (Memory.max_ts loc fmem))).\n          exists to_max.\n          exists (Time.incr (Memory.max_ts loc mem)).\n          splits.\n          - exploit future_get; try exact SAT; eauto. i.\n            exploit Memory.lt_get; try exact l; try exact x0; eauto.\n          - exploit Memory.max_ts_spec; try exact FGET. i. des.\n            etrans; eauto. etrans; [|apply Time.join_r].\n            econs. apply Time.incr_spec.\n          - left. split; ss. unguard. des.\n            + left. destruct msg_max; ss. esplits; try exact SAT. auto.\n            + right. esplits; try exact SAT0. auto.\n          - right. ss.\n          - i. eapply cap_covered; eauto.\n            eapply Interval.le_mem; try exact ITV.\n            econs; s; try refl. apply Time.bot_spec.\n          - i. exploit LE; try exact GET. i.\n            exploit MAX; try exact x0.\n            { esplits; try exact x0. right. eauto. }\n            ii. inv LHS. inv RHS. ss.\n            exploit TimeFacts.lt_le_lt; try exact FROM0; try exact TO. i. timetac.\n        }\n\n        (* future message before latest *)\n        rewrite SAT0 in GET. inv GET. inv SAT; cycle 1.\n        { inv H. exploit future_get; try exact SAT0; eauto. i.\n          exploit SOUND; eauto. i.\n          rewrite x0 in *. inv x1.\n          unguard. des; cycle 1.\n          { exploit ONLY; eauto. i. subst.\n            exploit LE; eauto. i. congr.\n          }\n          esplits; [refl|refl|..].\n          - left. split; try refl. left. esplits; eauto.\n          - left. split; try refl. left. esplits; eauto.\n          - inv CAP. exploit SOUND0; eauto. i. econs; eauto.\n          - i. exploit ONLY; eauto. i. subst.\n            exploit LE; eauto. i.\n            exploit Memory.get_disjoint; [exact x1|exact SAT0|]. i. des; ss.\n        }\n        exploit Memory.lt_get; try apply H; i.\n        { eapply SOUND; eauto. }\n        { eapply future_get; eauto. }\n        specialize (Memory.max_exists\n                      (fun to =>\n                         Time.lt to fto /\\\n                         (exists from msg,\n                             Memory.get loc to mem = Some (from, msg) /\\\n                             __guard__ (\n                                 msg <> Message.reserve \\/\n                                 exists f m, Memory.get loc to rsv = Some (f, m))))\n                      loc mem). i. des.\n        { exfalso.\n          destruct (Time.eq_dec fto Time.bot); subst.\n          - exploit MIN; try apply CLOSED.\n            { esplits; try refl; try apply CLOSED. left. ss. }\n            i. exploit TimeFacts.lt_le_lt; try exact H; try exact x1. timetac.\n          - eapply NONE; try apply CLOSED.\n            esplits; try apply CLOSED; try (left; ss).\n            specialize (Time.bot_spec fto). i. inv H0; ss. congr.\n        }\n        rewrite SAT2 in GET. inv GET; i.\n        exploit Memory.lt_get; try exact SAT.\n        { eapply future_get; try exact SAT2; eauto. }\n        { eapply SOUND; eauto. }\n        exists to_max, from_min, to_max, from_min.\n        splits; ss.\n        - left. split; ss. unguardH SAT3. des.\n          + left. destruct msg_max; ss.\n            esplits; try exact SAT2. right. ss.\n          + right. esplits; try exact SAT3. right. ss.\n        - left. split; ss. unguardH SAT1. des.\n          + left. destruct msg_min; ss.\n            esplits; try exact SAT0. left. ss.\n          + exploit LE; eauto. i.\n            rewrite x2 in *. inv SAT0.\n            right. esplits; try exact SAT1. left. ss.\n        - i. eapply cap_covered; eauto.\n          eapply Interval.le_mem; try exact ITV.\n          econs; s; try apply Time.bot_spec.\n          exploit Memory.max_ts_spec; try exact SAT0. i. des.\n          etrans; [|econs; apply Time.incr_spec].\n          etrans; try exact MAX0.\n          exploit Memory.get_ts; try exact SAT0. i. des; timetac.\n        - ii. inv LHS. inv RHS. ss.\n          exploit LE; eauto. i.\n          destruct (TimeFacts.le_lt_dec fto t).\n          + exploit MIN; try exact x3.\n            { split; ss. esplits; eauto. right. eauto. }\n            i. inv x4.\n            * exploit Memory.lt_get; try exact H0; eauto. i.\n              exploit TimeFacts.lt_le_lt; try exact FROM; try exact TO0. i.\n              exploit Memory.get_ts; try exact SAT0. i. des; timetac.\n              rewrite x6 in x5. timetac.\n            * inv H0. rewrite x3 in *. inv SAT0. timetac.\n          + exploit MAX; try exact x3.\n            { split; ss. esplits; eauto. right. eauto. }\n            i. exploit TimeFacts.lt_le_lt; try exact FROM0; try exact TO. i. timetac.\n      }\n    }\n  Qed.\n\n  Lemma future_certify\n        fth\n        th loc mem_future\n        (STATE: Thread.state th = Thread.state fth)\n        (TVIEW: Local.tview (Thread.local th) = Local.tview (Thread.local fth))\n        (FPROMISES: Local.promises (Thread.local fth) = BoolMap.bot)\n        (FUTURE: Memory.messages_le (Global.memory (Thread.global th)) mem_future)\n        (SIM: SrcToIRThread.sim_memory (Global.memory (Thread.global fth)) mem_future)\n        (LC_WF: Local.wf (Thread.local th) (Thread.global th))\n        (GL_WF: Global.wf (Thread.global th))\n        (LE_FUTURE: Memory.le (Local.reserves (Thread.local th)) mem_future)\n        (FLC_WF: Local.wf (Thread.local fth) (Thread.global fth))\n        (FGL_WF: Global.wf (Thread.global fth))\n        (CERTIFY: certify loc (Thread.cap_of th)):\n    @pf_certify lang loc fth.\n  Proof.\n    exploit Thread.cap_wf; try exact LC_WF; eauto. i. des.\n    exploit future_map; try exact FUTURE; try exact SIM;\n      try apply LC_WF; try apply GL_WF; ss.\n    { apply Memory.cap_of_cap. }\n    i. des.\n    eapply map_certify; try exact CERTIFY; eauto.\n    econs; ss.\n    econs. rewrite <- TVIEW.\n    eapply closed_tview_map; try apply LC_WF; eauto.\n    i. subst. left. split; ss.\n    left. esplits; eauto. right. ss.\n  Qed.\nEnd FutureCertify.\nEnd FutureCertify.\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/src2ir/FutureCertify.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.27607807280503616}}
{"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_icc_el1_sysreg_trap_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      when gidx == (buffer (priv adt)) @ (offset rec);\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      if __ESR_EL2_SYSREG_IS_WRITE esr then\n        Some adt\n      else\n        let g' := gn {grec: (grec gn) {g_regs: set_reg rt 0 (g_regs (grec gn))}} in\n        Some adt {share: (share adt) {gs: (gs (share adt)) # gidx == g'}}\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/RealmSyncHandlerAux/Specs/handle_icc_el1_sysreg_trap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.2760780728050361}}
{"text": "(** * Implementation of Section 3.8 *)\nRequire Import Rpos.\nRequire Import RL.hr.term.\nRequire Import RL.hr.semantic.\nRequire Import RL.hr.hseq.\nRequire Import RL.hr.hr.\nRequire Import RL.hr.invertibility.\nRequire Import RL.hr.M_elim.\nRequire Import RL.hr.hr_perm_lemmas.\n\nRequire Import CMorphisms.\nRequire Import Lra.\n\nRequire Import RL.OLlibs.List_more.\nRequire Import RL.OLlibs.List_Type.\nRequire Import RL.OLlibs.Permutation_Type.\nRequire Import RL.OLlibs.Permutation_Type_more.\nRequire Import RL.OLlibs.Permutation_Type_solve.\n\nLocal Open Scope R_scope.\n\n(** Proof of Lemma 3.43 \n    \n    L is the list (((r_i, s_i), (r'_i, s'_i)), T_i) *)\nLemma hrr_atomic_can_elim_gen : forall L n,\n    Forall_inf (fun x => sum_vec (fst (fst (fst x))) - sum_vec (snd (fst (fst x))) = sum_vec (fst (snd (fst x))) - sum_vec (snd (snd (fst x)))) L ->\n    HR_T (map (fun x => (vec (fst (fst (fst x))) (HR_covar n) ++ vec (snd (fst (fst x))) (HR_var n) ++ snd x)) L) ->\n    HR_T (map (fun x => (vec (fst (snd (fst x))) (HR_covar n) ++ vec (snd (snd (fst x))) (HR_var n) ++ snd x)) L).\nProof.\n  intros L n H.\n  remember (map (fun x => (vec (fst (fst (fst x))) (HR_covar n) ++ vec (snd (fst (fst x))) (HR_var n) ++ snd x)) L) as G.\n  assert (Allperm G (map (fun x => (vec (fst (fst (fst x))) (HR_covar n) ++ vec (snd (fst (fst x))) (HR_var n) ++ snd x)) L)) by (rewrite <- HeqG; clear; induction G; try now constructor).\n  clear HeqG.\n  intro pi; revert L H X; induction pi; intros L Hsum Hperm.\n  - destruct L; [ | destruct L]; inversion Hperm; try inversion X0; subst.\n    apply Permutation_Type_nil in X; destruct p as [[[s1 r1] [s2 r2]] T1]; destruct s1; destruct r1; destruct T1; inversion X; simpl.\n    apply hrr_ID.\n    { inversion Hsum; simpl in *.\n      nra. }\n    apply hrr_INIT.\n  - destruct L; inversion Hperm; subst.\n    simpl.\n    apply hrr_W.\n    apply IHpi.\n    + inversion Hsum; assumption.\n    + assumption.\n  - destruct L; inversion Hperm; subst.\n    simpl.\n    apply hrr_C; try assumption.\n    change ((vec (fst (snd (fst p))) (HR_covar n) ++ vec (snd (snd (fst p))) (HR_var n) ++ snd p)\n              :: (vec (fst (snd (fst p))) (HR_covar n) ++ vec (snd (snd (fst p))) (HR_var n) ++ snd p)\n              :: map\n              (fun x  => vec (fst (snd (fst x))) (HR_covar n) ++ vec (snd (snd (fst x))) (HR_var n) ++ snd x)\n              L)\n      with\n        (map (fun x  => vec (fst (snd (fst x))) (HR_covar n) ++ vec (snd (snd (fst x))) (HR_var n) ++ snd x)\n           (p :: p :: L)).\n    apply IHpi.\n    + inversion Hsum.\n      repeat (apply Forall_inf_cons); assumption.\n    + simpl.\n      do 2 (apply Forall2_inf_cons; try assumption).\n  - destruct L; [ | destruct L]; inversion Hperm; try inversion X0; subst.\n    destruct p as [[[p1 p2] [p3 p4]] p5];\n      destruct p0 as [[[p1' p2'] [p3' p4']] p5'];\n      simpl in *;\n      remember ((((p1 ++ p1'), (p2 ++ p2')) , ((p3 ++ p3') , (p4 ++ p4'))), (p5 ++ p5')) as p'';\n      apply hrr_S;\n      (apply hrr_ex_seq with (vec (fst (snd (fst p''))) (HR_covar n) ++ vec (snd (snd (fst p''))) (HR_var n) ++snd p'') ; [ rewrite Heqp''; simpl; rewrite ? vec_app; Permutation_Type_solve | ]);\n      change ((vec (fst (snd (fst p''))) (HR_covar n) ++ vec (snd (snd (fst p''))) (HR_var n) ++snd p'') :: map (fun x  => vec (fst (snd (fst x))) (HR_covar n) ++ vec (snd (snd (fst x))) (HR_var n) ++ snd x) (L))\n        with (map (fun x  => vec (fst (snd (fst x))) (HR_covar n) ++ vec (snd (snd (fst x))) (HR_var n) ++ snd x) (p'' :: L));\n      (apply IHpi ;\n       [ subst;\n           inversion Hsum; inversion X3;\n           repeat (try apply Forall_inf_cons);\n           try assumption;\n           simpl in *;\n           rewrite ? sum_vec_app;\n           nra | ]);\n      simpl; apply Forall2_inf_cons;\n           [ rewrite Heqp'';simpl; rewrite ? vec_app ; Permutation_Type_solve |  assumption].\n  - inversion f.\n  - destruct L; inversion Hperm; subst.\n    simpl.\n    apply hrr_T with r; try assumption.\n    destruct p as ([[r1 r2] [s1 s2]] , T'); simpl in *.\n    apply hrr_ex_seq with (vec (mul_vec r s1) (HR_covar n) ++ vec (mul_vec r s2) (HR_var n) ++ seq_mul r T').\n    { rewrite <- ? seq_mul_vec_mul_vec.\n      rewrite ? seq_mul_app.\n      reflexivity. }\n    change ((vec (mul_vec r s1) (HR_covar n) ++ vec (mul_vec r s2) (HR_var n) ++ seq_mul r T') :: map (fun x  => vec (fst (snd (fst x))) (HR_covar n) ++ vec (snd (snd (fst x))) (HR_var n) ++ snd x) L)\n      with\n        (map (fun x  => vec (fst (snd (fst x))) (HR_covar n) ++ vec (snd (snd (fst x))) (HR_var n) ++ snd x) ((((mul_vec r r1, mul_vec r r2) , (mul_vec r s1 , mul_vec r s2)), seq_mul r T') :: L)).\n    apply IHpi.\n    + subst; inversion Hsum; subst; simpl in *.\n      apply Forall_inf_cons ; try assumption; simpl.\n      rewrite ? mul_vec_sum_vec; nra.\n    + simpl.\n      apply Forall2_inf_cons; [ | try assumption].\n      rewrite <- ? seq_mul_vec_mul_vec; rewrite <- ? seq_mul_app.\n      apply seq_mul_perm; assumption.\n  - destruct L; inversion Hperm; subst.\n    simpl.\n    case_eq (n =? n0); [intros Heqn; apply Nat.eqb_eq in Heqn | intros Hneqn; apply Nat.eqb_neq in Hneqn].\n    + subst.\n      destruct p as [[[s1 r1] [s1' r1']] T1]; simpl in *.\n      destruct (perm_decomp_vec_eq_2 T T1 r1 s1 r s (HR_var n0) (HR_covar n0)) as [[[[[[[[a1 b1] c1] a2] b2] c2] T'] D'] [H1' [[[[[H2' H3'] H4'] H5'] H6']]]]; [ now auto | apply X | ].\n      apply hrr_ex_seq with (vec (c2 ++ s1') (HR_covar n0) ++ vec (c1 ++ r1') (HR_var n0) ++ T').\n      { rewrite ? vec_app.\n        transitivity (vec s1' (HR_covar n0) ++ vec r1' (HR_var n0) ++ (vec c2 (HR_covar n0) ++ vec c1 (HR_var n0) ++ T')); try Permutation_Type_solve. }\n      change ((vec (c2 ++ s1') (HR_covar n0) ++ vec (c1 ++ r1') (HR_var n0) ++ T')\n                :: map\n                (fun x : list Rpos * list Rpos * (list Rpos * list Rpos) * list (Rpos * term) =>\n                   vec (fst (snd (fst x))) (HR_covar n0) ++ vec (snd (snd (fst x))) (HR_var n0) ++ snd x)\n                L)\n        with\n          (map (fun x : list Rpos * list Rpos * (list Rpos * list Rpos) * list (Rpos * term) =>\n                   vec (fst (snd (fst x))) (HR_covar n0) ++ vec (snd (snd (fst x))) (HR_var n0) ++ snd x)\n               ((((a2,a1),(c2 ++ s1', c1 ++ r1')), T')::L)).\n      apply IHpi.\n      * inversion Hsum; simpl in*.\n        apply Forall_inf_cons ; [ | try assumption].\n        simpl; rewrite ? sum_vec_app.\n        transitivity (sum_vec c2 + sum_vec s1 - (sum_vec c1 + sum_vec r1)); try nra.\n        replace (sum_vec s1) with (sum_vec (a2 ++ b2)).\n        2:{ apply sum_vec_perm; Permutation_Type_solve. }\n        replace (sum_vec r1) with (sum_vec (a1 ++ b1)) by (apply sum_vec_perm; Permutation_Type_solve).\n        rewrite ? sum_vec_app.\n        replace (sum_vec r) with (sum_vec (b1 ++ c1)) in e by (apply sum_vec_perm; Permutation_Type_solve).\n        replace (sum_vec s) with (sum_vec (b2 ++ c2)) in e by (apply sum_vec_perm; Permutation_Type_solve).\n        rewrite ? sum_vec_app in e.\n        nra.\n      * simpl; apply Forall2_inf_cons; [ | try assumption].\n        Permutation_Type_solve.\n    + destruct p as [[[s1 r1] [s1' r1']] T1]; simpl in *.\n      subst.\n      destruct (perm_decomp_vec_neq_2 T T1 r s r1 s1 n0 n (not_eq_sym Hneqn) X) as [[T' D'] [H1' [H2' H3']]].\n      apply hrr_ex_seq with (vec s (HR_covar n0) ++ vec r (HR_var n0) ++ vec s1' (HR_covar n) ++ vec r1' (HR_var n) ++ T').\n      { Permutation_Type_solve. }\n      apply hrr_ID; try assumption.\n      change ((vec s1' (HR_covar n) ++ vec r1' (HR_var n) ++ T')\n                :: map\n                (fun x : list Rpos * list Rpos * (list Rpos * list Rpos) * list (Rpos * term) =>\n                   vec (fst (snd (fst x))) (HR_covar n) ++ vec (snd (snd (fst x))) (HR_var n) ++ snd x)\n                L)\n        with\n          (map\n             (fun x : list Rpos * list Rpos * (list Rpos * list Rpos) * list (Rpos * term) =>\n                vec (fst (snd (fst x))) (HR_covar n) ++ vec (snd (snd (fst x))) (HR_var n) ++ snd x)\n             ((((s1,r1),(s1',r1')),T')::L)).\n      apply IHpi.\n      * inversion Hsum.\n        apply Forall_inf_cons ; [ | try assumption].\n        simpl in *; nra.\n      * simpl; apply Forall2_inf_cons; [ | try assumption].\n        Permutation_Type_solve.      \n  - destruct L; inversion Hperm; subst.\n    simpl.\n    destruct p as [r1 T1]; simpl in *.\n    assert (HR_zero <> HR_covar n) as Hnc by now auto.\n    assert (HR_zero <> HR_var n) as Hnv by now auto.\n    apply Permutation_Type_sym in X.\n    destruct (perm_decomp_vec_ID_case _ _ _ _ _ _ _ Hnc Hnv X) as [ [[[Ta Tb] Da ] Db] [H1' [[[H2' H3'] H4'] H5']]].\n    apply hrr_ex_seq with (vec r HR_zero ++ vec (fst (snd r1)) (HR_covar n) ++ vec (snd (snd r1)) (HR_var n) ++ Db).\n    { etransitivity; [ apply Permutation_Type_app_comm | ].\n      rewrite <- ? app_assoc.\n      repeat (try apply Permutation_Type_app; try reflexivity).\n      etransitivity; [ apply Permutation_Type_app_comm | ].\n      etransitivity ; [ | symmetry; apply H1'].\n      apply Permutation_Type_app; Permutation_Type_solve. }\n    apply hrr_Z; try assumption.\n    change ((vec (fst (snd r1)) (HR_covar n) ++ vec (snd (snd r1)) (HR_var n) ++ Db) :: map (fun x  => vec (fst (snd (fst x))) (HR_covar n) ++ vec (snd (snd (fst x))) (HR_var n) ++ snd x) L)\n      with\n        (map (fun x  => vec (fst (snd (fst x))) (HR_covar n) ++ vec (snd (snd (fst x))) (HR_var n) ++ snd x) ((r1, Db) :: L)).\n    apply IHpi.\n    + inversion Hsum.\n      apply Forall_inf_cons; simpl in *; try assumption.\n    + simpl.\n      apply Forall2_inf_cons; [ | assumption].\n      Permutation_Type_solve.\n  - destruct L; inversion Hperm; subst.\n    simpl.\n    destruct p as [r1 T1]; simpl in *.\n    assert (A +S B <> HR_covar n) as Hnc by now auto.\n    assert (A +S B <> HR_var n) as Hnv by now auto.\n    apply Permutation_Type_sym in X.\n    destruct (perm_decomp_vec_ID_case _ _ _ _ _ _ _ Hnc Hnv X) as [ [[[Ta Tb] Da ] Db] [H1' [[[H2' H3'] H4'] H5']]].\n    apply hrr_ex_seq with (vec r (A +S B) ++ vec (fst (snd r1)) (HR_covar n) ++ vec (snd (snd r1)) (HR_var n) ++ Db).\n    { etransitivity ; [ apply Permutation_Type_app_comm | ]; rewrite <- ? app_assoc; repeat (try apply Permutation_Type_app; try reflexivity).\n      etransitivity ; [ | symmetry; apply H1' ].\n      etransitivity ; [ apply Permutation_Type_app_comm | ].\n      Permutation_Type_solve. }\n    apply hrr_plus; try assumption.\n    apply hrr_ex_seq with (vec (fst (snd r1)) (HR_covar n) ++ vec (snd (snd r1)) (HR_var n) ++ vec r A ++ vec r B ++ Db); [ Permutation_Type_solve | ].\n    change ((vec (fst (snd r1)) (HR_covar n) ++ vec (snd (snd r1)) (HR_var n) ++ vec r A ++ vec r B ++ Db) :: map (fun x  => vec (fst (snd (fst x))) (HR_covar n) ++ vec (snd (snd (fst x))) (HR_var n) ++ snd x) L)\n      with\n        (map (fun x  => vec (fst (snd (fst x))) (HR_covar n) ++ vec (snd (snd (fst x))) (HR_var n) ++ snd x) ((r1, vec r A ++ vec r B ++ Db) :: L)).\n    apply IHpi.\n    + inversion Hsum.\n      apply Forall_inf_cons; simpl in *; try assumption.\n    + simpl.\n      apply Forall2_inf_cons; [ | assumption].\n      Permutation_Type_solve.\n  - destruct L; inversion Hperm; subst.\n    simpl.\n    destruct p as [r1 T1]; simpl in *.\n    assert (r0 *S A <> HR_covar n) as Hnc by now auto.\n    assert (r0 *S A <> HR_var n) as Hnv by now auto.\n    apply Permutation_Type_sym in X.\n    destruct (perm_decomp_vec_ID_case _ _ _ _ _ _ _ Hnc Hnv X) as [ [[[Ta Tb] Da ] Db] [H1' [[[H2' H3'] H4'] H5']]].\n    apply hrr_ex_seq with (vec r (r0 *S A) ++ vec (fst (snd r1)) (HR_covar n) ++ vec (snd (snd r1)) (HR_var n) ++ Db).\n    { etransitivity ; [ apply Permutation_Type_app_comm | ]; rewrite <- ? app_assoc; repeat (try apply Permutation_Type_app; try reflexivity).\n      etransitivity ; [ | symmetry; apply H1' ].\n      etransitivity ; [ apply Permutation_Type_app_comm | ].\n      Permutation_Type_solve. }\n    apply hrr_mul; try assumption.\n    apply hrr_ex_seq with (vec (fst (snd r1)) (HR_covar n) ++ vec (snd (snd r1)) (HR_var n) ++ vec (mul_vec r0 r) A ++ Db).\n    { Permutation_Type_solve. }\n    change ((vec (fst (snd r1)) (HR_covar n) ++ vec (snd (snd r1)) (HR_var n) ++ vec (mul_vec r0 r) A ++ Db) :: map (fun x  => vec (fst (snd (fst x))) (HR_covar n) ++ vec (snd (snd (fst x))) (HR_var n) ++ snd x) L)\n      with\n        (map (fun x  => vec (fst (snd (fst x))) (HR_covar n) ++ vec (snd (snd (fst x))) (HR_var n) ++ snd x) ((r1, vec (mul_vec r0 r) A ++ Db) :: L)).\n    apply IHpi.\n    + inversion Hsum.\n      apply Forall_inf_cons; simpl in *; try assumption.\n    +  simpl.\n       apply Forall2_inf_cons; [ | assumption].\n       Permutation_Type_solve.\n  - destruct L; inversion Hperm; subst.\n    simpl.\n    destruct p as [r1 T1]; simpl in *.\n    assert (A \\/S B <> HR_covar n) as Hnc by now auto.\n    assert (A \\/S B <> HR_var n) as Hnv by now auto.\n    apply Permutation_Type_sym in X.\n    destruct (perm_decomp_vec_ID_case _ _ _ _ _ _ _ Hnc Hnv X) as [ [[[Ta Tb] Da ] Db] [H1' [[[H2' H3'] H4'] H5']]].\n    apply hrr_ex_seq with (vec r (A \\/S B) ++ vec (fst (snd r1)) (HR_covar n) ++ vec (snd (snd r1)) (HR_var n) ++ Db).\n    { etransitivity ; [ apply Permutation_Type_app_comm | ]; rewrite <- ? app_assoc; repeat (try apply Permutation_Type_app; try reflexivity).\n      etransitivity ; [ | symmetry; apply H1' ].\n      etransitivity ; [ apply Permutation_Type_app_comm | ].\n      Permutation_Type_solve. }\n    apply hrr_max; try assumption.\n    eapply hrr_ex_hseq ; [ apply Permutation_Type_swap | ].\n    apply hrr_ex_seq with (vec (fst (snd r1)) (HR_covar n) ++ vec (snd (snd r1)) (HR_var n) ++ vec r A ++ Db).\n    { Permutation_Type_solve. }\n    eapply hrr_ex_hseq ; [ apply Permutation_Type_swap | ].\n    apply hrr_ex_seq with (vec (fst (snd r1)) (HR_covar n) ++ vec (snd (snd r1)) (HR_var n) ++ vec r B ++  Db).\n    { Permutation_Type_solve. }\n    change ((vec (fst (snd r1)) (HR_covar n) ++ vec (snd (snd r1)) (HR_var n) ++ vec r B ++ Db) :: (vec (fst (snd r1)) (HR_covar n) ++ vec (snd (snd r1)) (HR_var n) ++ vec r A ++ Db) :: map (fun x  => vec (fst (snd (fst x))) (HR_covar n) ++ vec (snd (snd (fst x))) (HR_var n) ++ snd x) L)\n      with\n        (map (fun x  => vec (fst (snd (fst x))) (HR_covar n) ++ vec (snd (snd (fst x))) (HR_var n) ++ snd x) ((r1, vec r B ++ Db) :: (r1, vec r A ++ Db) :: L)).\n    apply IHpi.\n    + inversion Hsum.\n      repeat (try apply Forall_inf_cons); simpl in *; try assumption.\n    + simpl.\n      apply Forall2_inf_cons; [ | apply Forall2_inf_cons ; [ | assumption] ]; Permutation_Type_solve.\n  - destruct L; inversion Hperm; subst.\n    simpl.\n    destruct p as [r1 T1]; simpl in *.\n    assert (A /\\S B <> HR_covar n) as Hnc by now auto.\n    assert (A /\\S B <> HR_var n) as Hnv by now auto.\n    apply Permutation_Type_sym in X.\n    destruct (perm_decomp_vec_ID_case _ _ _ _ _ _ _ Hnc Hnv X) as [ [[[Ta Tb] Da ] Db] [H1' [[[H2' H3'] H4'] H5']]].\n    apply hrr_ex_seq with (vec r (A /\\S B) ++ vec (fst (snd r1)) (HR_covar n) ++ vec (snd (snd r1)) (HR_var n) ++ Db).\n    { etransitivity ; [ apply Permutation_Type_app_comm | ]; rewrite <- ? app_assoc; repeat (try apply Permutation_Type_app; try reflexivity).\n      etransitivity ; [ | symmetry; apply H1' ].\n      etransitivity ; [ apply Permutation_Type_app_comm | ].\n      Permutation_Type_solve. }\n    apply hrr_min; try assumption.\n    + apply hrr_ex_seq with (vec (fst (snd r1)) (HR_covar n) ++ vec (snd (snd r1)) (HR_var n) ++ vec r A ++ Db).\n      { Permutation_Type_solve. }\n      change ((vec (fst (snd r1)) (HR_covar n) ++ vec (snd (snd r1)) (HR_var n) ++ vec r A ++ Db) :: map (fun x  => vec (fst (snd (fst x))) (HR_covar n) ++ vec (snd (snd (fst x))) (HR_var n) ++ snd x) L)\n        with\n          (map (fun x  => vec (fst (snd (fst x))) (HR_covar n) ++ vec (snd (snd (fst x))) (HR_var n) ++ snd x) ((r1, vec r A ++ Db) :: L)).\n      apply IHpi1.\n      * inversion Hsum.\n        repeat (try apply Forall_inf_cons); simpl in *; try assumption.\n      * simpl.\n        apply Forall2_inf_cons; [ | assumption]; Permutation_Type_solve.\n    + apply hrr_ex_seq with (vec (fst (snd r1)) (HR_covar n) ++ vec (snd (snd r1)) (HR_var n) ++ vec r B ++ Db).\n      { Permutation_Type_solve. }\n      change ((vec (fst (snd r1)) (HR_covar n) ++ vec (snd (snd r1)) (HR_var n) ++ vec r B ++ Db) :: map (fun x  => vec (fst (snd (fst x))) (HR_covar n) ++ vec (snd (snd (fst x))) (HR_var n) ++ snd x) L)\n        with\n          (map (fun x  => vec (fst (snd (fst x))) (HR_covar n) ++ vec (snd (snd (fst x))) (HR_var n) ++ snd x) ((r1, vec r B ++ Db) :: L)).\n      apply IHpi2.\n      * inversion Hsum.\n        repeat (try apply Forall_inf_cons); simpl in *; try assumption.\n      * simpl.\n        apply Forall2_inf_cons; [ | try assumption]; Permutation_Type_solve.\n  - destruct L; inversion Hperm; subst.\n    apply IHpi; try assumption.\n    simpl; apply Forall2_inf_cons; try assumption.\n    transitivity T2; assumption.    \n  - destruct (Permutation_Type_Forall2_inf (Permutation_Type_sym p) Hperm).\n    destruct (Permutation_Type_map_inv _ _ (Permutation_Type_sym p0)) as [L' Heq Hperm1].\n    eapply hrr_ex_hseq ; [ apply Permutation_Type_map; symmetry; apply Hperm1 | ].\n    apply IHpi; [ | rewrite Heq in f; apply f].\n    clear - Hperm1 Hsum.\n    revert Hsum; induction Hperm1; intros Hsum.\n    + apply Forall_inf_nil.\n    + inversion Hsum; subst.\n      apply Forall_inf_cons; [ | apply IHHperm1];try assumption.\n    + inversion Hsum; inversion X; subst.\n      apply Forall_inf_cons ; [ | apply Forall_inf_cons]; try assumption.\n    + apply IHHperm1_2; apply IHHperm1_1; apply Hsum.\n  - inversion f.\nQed.\n\n(** Proof of Lemma 3.41 *)\nLemma hrr_atomic_can_elim : forall G T n r s,\n    sum_vec r = sum_vec s ->\n    HR_T ((vec s (HR_covar n) ++ vec r (HR_var n) ++ T) :: G) ->\n    HR_T (T :: G).\nProof.\n  intros G T n r s Heq pi.\n  assert ({ L & prod\n                  ( G = map (fun x  => vec (fst (fst (fst x))) (HR_covar n) ++ vec (snd (fst (fst x))) (HR_var n) ++ snd x) L)\n                  (( G =  map (fun x  => vec (fst (snd (fst x))) (HR_covar n) ++ vec (snd (snd (fst x))) (HR_var n) ++ snd x) L) *\n                   (Forall_inf\n                      (fun x : list Rpos * list Rpos * (list Rpos * list Rpos) * list (Rpos * term) => sum_vec (fst (fst (fst x))) - sum_vec (snd (fst (fst x))) = sum_vec (fst (snd (fst x))) - sum_vec (snd (snd (fst x))))  L))}) as [L [H1 [H2 H3]]].\n  { clear - G ; induction G.\n    - split with nil; repeat split; try reflexivity.\n      apply Forall_inf_nil.\n    - destruct IHG as [ L [ H1 [H2 H3]] ].\n      split with ((((nil,nil),(nil,nil)), a) :: L).\n      repeat split; simpl; [rewrite H1 | rewrite H2 | ]; try reflexivity.\n      apply Forall_inf_cons; try assumption.\n      simpl; nra. }\n  rewrite H2.\n  change (T :: map (fun x : list Rpos * list Rpos * (list Rpos * list Rpos) * list (Rpos * term) => vec (fst (snd (fst x))) (HR_covar n) ++ vec (snd (snd (fst x))) (HR_var n) ++ snd x) L) with\n      (map (fun x : list Rpos * list Rpos * (list Rpos * list Rpos) * list (Rpos * term) => vec (fst (snd (fst x))) (HR_covar n) ++ vec (snd (snd (fst x))) (HR_var n) ++ snd x) ( (((s , r) , (nil, nil)) , T) :: L)).\n  apply hrr_atomic_can_elim_gen.\n  - simpl; apply Forall_inf_cons; try assumption; simpl; nra.\n  - simpl; rewrite <- H1.\n    apply pi.\nQed.\n\nLemma hrr_can_2 : forall G T A r s,\n    sum_vec r = sum_vec s ->\n    HR_T ((vec s (-S A) ++ vec r A ++ T) :: G) ->\n    HR_T (T :: G).\nProof.\n  intros G T A; revert G T; induction A; intros G T r' s' Heq pi.\n  - apply hrr_atomic_can_elim with n r' s'; try assumption.\n  - apply hrr_atomic_can_elim with n s' r'; try nra.\n    eapply hrr_ex_seq ; [ | apply pi].\n    Permutation_Type_solve.\n  - apply hrr_M_elim.\n    apply hrr_Z_inv with r'.\n    apply hrr_Z_inv with s'.\n    apply HR_le_frag with (hr_frag_T); auto.\n    repeat split.\n  - apply (IHA1 G T r' s' Heq).\n    apply (IHA2 G (vec s' (-S A1) ++ vec r' A1 ++ T) r' s' Heq).\n    apply hrr_M_elim.\n    apply hrr_ex_seq with (vec r' A1 ++ vec r' A2 ++ vec s' (-S A2) ++ vec s' (-S A1) ++ T); [ Permutation_Type_solve | ].\n    apply hrr_plus_inv.\n    apply hrr_ex_seq with (vec s' (-S A1) ++ vec s' (-S A2) ++ vec r' (A1 +S A2) ++ T); [ Permutation_Type_solve | ].\n    apply hrr_plus_inv.\n    apply HR_le_frag with hr_frag_T; try assumption.\n    repeat split.\n  - apply (IHA G T (mul_vec r r') (mul_vec r s')).\n    { rewrite ? mul_vec_sum_vec; nra. }\n    apply hrr_M_elim.\n    apply hrr_mul_inv.\n    apply hrr_ex_seq with (vec (mul_vec r r') A ++ vec s' (r *S (-S A)) ++ T) ; [ Permutation_Type_solve | ].\n    apply hrr_mul_inv.\n    apply HR_le_frag with hr_frag_T; try (repeat split).\n    eapply hrr_ex_seq ; [ | apply pi].\n    Permutation_Type_solve.\n  - apply hrr_C; try reflexivity.\n    apply (IHA2 (T :: G) T r' s' Heq).\n    eapply hrr_ex_hseq; [ apply Permutation_Type_swap | ].\n    apply (IHA1 ((vec s' (-S A2) ++ vec r' A2 ++ T) :: G) T r' s' Heq).\n    apply hrr_M_elim.\n    apply hrr_min_inv_l with (-S A2).\n    apply hrr_ex_seq with (vec r' A1 ++ vec s' (-S (A1 \\/S A2)) ++ T); [Permutation_Type_solve | ].\n    eapply hrr_ex_hseq; [ apply Permutation_Type_swap | ].\n    apply hrr_min_inv_r with (-S A1).\n    apply hrr_ex_seq with (vec r' A2 ++ vec s' (-S (A1 \\/S A2)) ++ T); [Permutation_Type_solve | ].\n    apply hrr_max_inv.\n    apply HR_le_frag with hr_frag_T; try (repeat split).\n    eapply hrr_ex_seq ; [ | apply pi].\n    Permutation_Type_solve.\n  - apply hrr_C; try reflexivity.\n    apply (IHA2 (T :: G) T r' s' Heq).\n    eapply hrr_ex_hseq; [ apply Permutation_Type_swap | ].\n    apply (IHA1 ((vec s' (-S A2) ++ vec r' A2 ++ T) :: G) T r' s' Heq).\n    apply hrr_M_elim.\n    apply hrr_ex_seq with (vec r' A1 ++ vec s' (-S A1) ++ T); [ Permutation_Type_solve | ].\n    apply hrr_min_inv_l with A2.\n    apply hrr_ex_seq with (vec s' (-S A1) ++ vec r' (A1 /\\S A2) ++ T); [Permutation_Type_solve | ].\n    eapply hrr_ex_hseq; [ apply Permutation_Type_swap | ].\n    apply hrr_ex_seq with (vec r' A2 ++ vec s' (-S A2) ++ T); [ Permutation_Type_solve | ].\n    apply hrr_min_inv_r with A1.\n    apply hrr_ex_seq with (vec s' (-S A2) ++ vec r' (A1 /\\S A2) ++ T); [Permutation_Type_solve | ].\n    apply hrr_max_inv.\n    apply HR_le_frag with hr_frag_T; try (repeat split).\n    apply pi.\nQed.\n\n(** Proof of Theorem 3.13 *)\nLemma hrr_can_elim : forall G,\n    HR_full G ->\n    HR_T_M G.\nProof.\n  intros G pi; induction pi; try now constructor.\n  - now apply hrr_T with r.\n  - now apply hrr_ex_seq with T1.\n  - now apply hrr_ex_hseq with G.\n  - apply HR_le_frag with hr_frag_T; try repeat split.\n    apply hrr_can_2 with A r s; try assumption.\n    apply hrr_M_elim.\n    apply IHpi.\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/hr/can_elim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2760657113907823}}
{"text": "Require Import Vloc.Lib.core.\nRequire Import Vloc.Lib.pure.\n\n(* NOTE: I feel like this should exist somewhere? *)\nLemma share_split_nonempty sh:\n  sh ≠ emptyshare -> fst (Share.split sh) ≠ emptyshare /\\ snd (Share.split sh) ≠ emptyshare.\nProof.\n  intros Hne.\n  remember ((Share.split sh).1) as shl.\n  remember ((Share.split sh).2) as shr.\n    split.\n    (* weirdly, connecting these via ; instead of 1,2: does not work *)\n    1,2: intros Hfalse;\n      specialize (Share.split_nontrivial) with shl shr sh; intros Hsnontriv;\n      subst;\n      specialize surjective_pairing with _ _ (Share.split sh); intros Hspliteq;\n      apply Hsnontriv in Hspliteq; last auto;\n      contradiction.\nQed.\n\nSection heap.\n\n\nContext `{ref_ctx: refines_ctx}.\n(* Some helper lemmas *)\n(* NOTE: what is the equivalent of cmra.included? *)\n  Lemma tpool_singleton_included (tp : list iexp) (j : nat) (e : iexp) :\n    join_sub {[j := Some e]} (to_tpool tp) → tp !! j = Some e.\n  Proof.\n    unfold join_sub.\n    intros [g Hjoin].\n    Set Printing Implicit.\n    unfold tpool_ghost in *.\n    (* We cannot reach such heights of perfection.  It was not intended for us *)\n    (*apply (join_ord (PCM_order := gmap_order (A_order := discrete_order))) in Hjoin.*)\n    specialize (Hjoin j).\n    rewrite lookup_singleton in Hjoin.\n    inv Hjoin; auto.\n    inv H2; auto.\n    contradiction.\n  Qed.\n    (*move=> /singleton_included_l [ex [/leibniz_equiv_iff]].*)\n    (*rewrite tpool_lookup fmap_Some=> [[e' [-> ->]] /Excl_included ?]. by f_equal.*)\n  (*Qed.*)\n  Lemma tpool_singleton_included' tp j e :\n    join_sub {[j := Some e]} (to_tpool tp) → to_tpool tp !! j = (Some (Some e)).\n  Proof. rewrite tpool_lookup. by move=> /tpool_singleton_included=> ->. Qed.\n\n  (* If any part of the tpool has a thread in it, the overall thread pool has that in it *)\n  Lemma tpool_ref_sub_lookup j v sh gName (tp' : @G tpool_ghost) (σ' : @G heap_ghost) tp σ:\n    ghost_part (P:=spec_ghost) sh (tp', σ') gName \n    * ghost_reference (P:=spec_ghost) (to_tpool tp, to_heap (heap σ)) gName \n     |-- (!! ((tp' !! j = Some (Some v) -> (to_tpool tp) !! j = Some (Some v)))).\n  Proof.\n    iIntros  \"[Part Ref]\".\n    iDestruct (ref_sub (P := spec_ghost) with \"[$Part $Ref]\") as \"%Hjoin\".\n    iPureIntro.\n    if_tac in Hjoin.\n    - inversion Hjoin; subst; auto.\n    - intros Hsome.\n      inv Hjoin. \n      inv H0.\n      specialize (H1 j).\n      inv H1.\n      (* impossible case *)\n      { rewrite Hsome in H3; inv H3. }\n      (* actual case *)\n      rewrite Hsome in H5; auto.\n      (* show that we can't have any other possibility *)\n      inv H5.\n      + rewrite Hsome in H0; inv H0.\n      + rewrite Hsome in H0; rewrite H0 in H4; auto.\n      + inv H1.\n  Qed.\n\n\n  (* If a part of the heap has a value in it, the rest of the heap has to as well *)\n  Lemma heap_ref_sub_lookup (l : loc) v vsh' gName (sh : Share.t) (tp' : @G tpool_ghost) (σ' : @G heap_ghost) tp σ:\n    ghost_part (P:=spec_ghost) sh (tp', σ') gName \n    * ghost_reference (P:=spec_ghost) (to_tpool tp, to_heap (heap σ)) gName \n     |-- (!! (\n      (σ' !! l = Some (Some (vsh', v))) -> (exists vsh, (to_heap (heap σ)) !! l = Some (Some (vsh, v))))).\n  Proof.\n    iIntros \"[Part Ref]\".\n    iDestruct (ref_sub (P := spec_ghost) with \"[$Part $Ref]\") as \"%Hjoin\".\n    iPureIntro.\n    intros Hsome.\n    if_tac in Hjoin.\n    (* full share means they agree by default *)\n    { exists vsh'; inv Hjoin; subst; auto. }\n    (* if we don't have full share, we have to show they agree *)\n    inv Hjoin; inv H0.\n    specialize (H2 l); inv H2.\n    (* same set of cases, essentially *)\n    { rewrite Hsome in H3; inv H3. } (* None != Some *)\n    { rewrite Hsome in H5; exists vsh'; auto. } (* other joined piece is None, so equal *)\n\n    (* Both x and our ghost_part are pieces and join *)\n    (* here we prove that no matter what share we have or what x is, we get the same value v in the heap *)\n    destruct a1; [|rewrite Hsome in H0; inv H0]. (* Hone != Some but different *)\n    assert (p = (vsh', v)) by (rewrite Hsome in H0; inv H0; auto); subst. (* we already know what p is *)\n    (* What values can the overall heap store at l? *)\n    destruct a3.\n    - destruct p.\n      exists s.\n      apply eq_sym in H4; rewrite H4.\n      destruct a2.\n      + destruct p.\n        inv H5; destruct H6 as [Hs0NE [Hshjoin Hvjoin]].\n        inv Hvjoin.\n        reflexivity.\n      + inv H5.\n        reflexivity.\n    (* in this case, we show that we can't somehow get None from Some, but again *)\n    - destruct a2.\n      + destruct p.\n        inv H5.\n      + inv H5.\n  Qed.\n\n\n(* taken and modified from theories/logic/spec_rules.v *)\n(* Questions:\n    - Is (pos_to_Qp 1) equivalent to top?\n    - \n   Notes:\n    ref is notation for (AllocN (Val (LitV 1%Z)))\n *)\n  Lemma step_alloc E j K e v :\n    IntoVal e v →\n    nclose nspace ⊆ E →\n    spec_ctx ∗ tpool_mapsto j (fill K (AllocN (Val (LitV (LitInt 1%Z))) e)) ={E}=∗ ∃ l, spec_ctx ∗ tpool_mapsto j (fill K (Val (LitV (LitLoc l)))) ∗ (heapS_mapsto fullshare l v).\n  Proof.\n    iIntros (<-?) \"[#Hinv Hj]\". iFrame \"Hinv\".\n    iDestruct \"Hj\" as (sh) \"[Hne Hj]\".\n    iPure \"Hne\" as shNE.\n    rewrite /spec_ctx /tpool_mapsto /=. \n    iDestruct \"Hinv\" as (ρ) \"Hinv\".\n    iInv nspace as (tp σ) \">[% Hown]\" \"Hclose\".\n    destruct (exist_fresh (dom (heap σ))) as [l Hl%not_elem_of_dom].\n\n    (* modification to use VST's update semantics rather than iris *)\n\n    (* we need to know later that j is in the thread pool, \n       so we prove it now while we have Hj and Hown around *)\n    iDestruct (tpool_ref_sub_lookup j with \"[$Hj $Hown]\") as \"%HhasJ\"; \n      rewrite lookup_singleton in HhasJ;\n      specialize (HhasJ eq_refl).\n\n    iCombine \"Hj Hown\" as \"Hown\".\n\n    iDestruct (ghost_part_ref_join (P:= spec_ghost) with \"Hown\") as \"Hown\".\n    (*NOTE: updating heap! *)\n    iDestruct ((part_ref_update (P:= spec_ghost) _ _ _ _\n      (({[j := Some (fill K (Val (LitV (LitLoc l))))]}), {[ l := Some (fullshare, Some v) ]}) \n      ((<[ j := Some (fill K (Val (LitV (LitLoc l)))) ]> (to_tpool tp)),  \n      (* NOTE: We need the \"post-to-heap\" version of the update here, not the original, so we include the share *)\n      (<[l := Some (fullshare, Some v) ]> (to_heap (heap σ)))))\n        with \"Hown\") as \">Hown\". \n      (* NOTE: This is nearly the same as pure at the start, how do I generalize it? *)\n    {\n      intros (tp_frame, heap_frame) Hjoin.\n      split.\n      - destruct Hjoin as [Htp Hheap].\n        split; simpl in *.\n        * iIntros (k).\n          destruct (eq_dec k j).\n          + subst.\n            rewrite lookup_singleton.\n            specialize (Htp j).\n            rewrite lookup_singleton in Htp; rewrite lookup_insert.\n            inv Htp; constructor.\n            inv H4; constructor.\n            inv H5.\n          + rewrite ! lookup_insert_ne; auto.\n            rewrite lookup_empty.\n            pose proof Htp k as Htpk.\n            rewrite lookup_singleton_ne in Htpk; auto.\n        * intros index. \n          destruct (decide (index = l)); subst.\n          + specialize (Hheap l).\n            rewrite lookup_fmap in Hheap. \n            rewrite lookup_fmap in Hheap. \n            rewrite Hl in Hheap.\n            rewrite lookup_singleton lookup_insert.\n            (* NOTE: what is the difference here? *)\n            inv Hheap; [rewrite H1|]; apply lower_None2.\n          + rewrite lookup_singleton_ne.\n            rewrite lookup_insert_ne; auto.\n            (* This does so much work I didn't believe it *)\n            specialize (Hheap index); auto.\n            auto.\n      - intros Oldg.\n        inv Oldg.\n        rewrite insert_singleton.\n        unfold to_heap.\n        setoid_rewrite fmap_empty.\n        rewrite insert_empty.\n        reflexivity.\n    }\n    iDestruct (ghost_part_ref_join (P:= spec_ghost) with \"[$Hown]\") as \"[Hj Hown]\".\n    (*iDestruct (own_valid_2 with \"Hown Hj\")*)\n      (*as %[[?%tpool_singleton_included' _]%prod_included ?]%auth_both_valid_discrete.*)\n    (*iMod (own_update_2 with \"Hown Hj\") as \"[Hown Hj]\".*)\n    (*{ by eapply auth_update, prod_local_update_1,*)\n        (*singleton_local_update, (exclusive_local_update _ (Excl (fill K (#l)%E))). }*)\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,to_agree (Some v : leibnizO _))); last done.*)\n      (*by apply lookup_to_heap_None. }*)\n    iExists l. \n    rewrite /UsrGhost /heapS_mapsto.\n    destruct (Share.split sh) as [shl shr] eqn:Hshplit.\n    (* Split Hj into two pieces, one for the heap and one for the map *)\n    (*remember ((Share.split sh).1) as shl.*)\n    (*remember ((Share.split sh).2) as shr.*)\n    (* prove that the shares can't be empty; we need this fact in multiple places *)\n    specialize (share_split_nonempty sh shNE).\n    rewrite Hshplit.\n    simpl.\n    intros HshrsNE; destruct HshrsNE as [HshlNE HshrNE].\n    (* now we know the shares are not empty everywhere *)\n    iDestruct (ghost_part_join (P:=spec_ghost) shl shr sh\n      ({[j := Some (fill K (Val (LitV (LitLoc l))))]}, to_heap gmap_empty)\n      (to_tpool [], {[l := Some (fullshare, Some v)]})\n      ({[j := Some (fill K (Val (LitV (LitLoc l))))]}, {[l := Some (fullshare, Some v)]})\n      gName\n    ) as \"[_ Himpl ]\"; eauto.\n    { \n      apply split_join.\n      auto.\n    }\n    (* prove that the update joins properly *)\n    { \n      split; intros index; \n      setoid_rewrite fmap_empty; rewrite lookup_empty; simpl.\n      - apply lower_None2.\n      - apply lower_None1.\n    }\n\n    (* Above gives us an implication to follow which we have to apply and break apart *)\n    iDestruct (\"Himpl\" with \"Hj\") as \"[Htp Hheap]\".\n    iClear \"Himpl\".\n\n    iApply fupd_frame_l.\n    iSplitL \"Htp\".\n    (* not an empty share *)\n    { iExists shl; iFrame; auto. }\n    rewrite /heapS_mapsto /=.\n    iExists shr.\n    rewrite /UsrGhost.\n    (* also not an empty share *)\n    iApply fupd_frame_l; iSplitR; auto. \n    iFrame \"Hheap\".\n    iApply \"Hclose\". iNext.\n    iExists (<[j:=fill K (Val (LitV (LitLoc l)))]> tp), (state_upd_heap <[l:=Some v]> σ).\n\n    (* we need the HhasJ here for to_tpool_insert' *)\n    rewrite to_heap_insert to_tpool_insert'; last auto. \n    iFrame; iSplit; auto. iPureIntro.\n    eapply rtc_r, step_insert_no_fork; eauto.\n    rewrite -state_init_heap_singleton. eapply AllocNS; first by lia.\n    intros. assert (i = 0) as -> by lia. by rewrite loc_add_0.\n  Qed.\n\n\n  Lemma ref_right_alloc E ctx K e v:\n    IntoVal e v →\n    nclose nspace ⊆ E →\n    refines_right ctx (fill K (AllocN (Val (LitV (LitInt 1%Z))) e))\n    |-- |={E}=> EX l, refines_right ctx (fill K (Val (LitV (LitLoc l)))) * l |-> v.\n  Proof.\n    intros HIV Hnspace.\n    iIntros \"[Rctx Rtp]\".\n    rewrite <- fill_app.\n    iDestruct (step_alloc with \"[Rctx Rtp]\") as \"Rstepped\"; first apply Hnspace.\n    { iFrame. }\n    iMod \"Rstepped\".\n    iDestruct \"Rstepped\" as (l) \"[Rctx [Rtp Rpt]]\".\n    iModIntro.\n    iExists l.\n    iFrame.\n    rewrite <- fill_app.\n    auto.\n  Qed.\n\n  \n  Lemma step_load E j K l hSh v:\n    nclose nspace ⊆ E → \n    spec_ctx ∗ (tpool_mapsto j (fill K (Load (Val (LitV (LitLoc l)))))) ∗ (heapS_mapsto hSh l v)\n    ={E}=∗ (spec_ctx ∗ (tpool_mapsto j (fill K (of_val v))) ∗ (heapS_mapsto hSh l v)).\n  Proof.\n    iIntros (?) \"(#Hinv & [[%sj [Hsjne Hj]] [%sl [Hslne Hl]]])\". iFrame \"Hinv\".\n    iDestruct \"Hsjne\" as %Hsjne.\n    iDestruct \"Hslne\" as %Hslne.\n    rewrite /spec_ctx /spec_inv /tpool_mapsto.\n    iDestruct \"Hinv\" as (ρ) \"Hinv\".\n    rewrite /heapS_mapsto /=.\n    iInv nspace as (tp σ) \">[% Hown]\" \"Hclose\".\n    rewrite /UsrGhost.\n    (* before we do any updates, we want to pull out that both things are in the main heap *)\n    iDestruct (tpool_ref_sub_lookup j with \"[$Hown $Hj]\") as \"%HtpJ\"; \n      rewrite lookup_singleton in HtpJ;\n      specialize (HtpJ eq_refl).\n    iDestruct (heap_ref_sub_lookup l with \"[$Hown $Hl]\") as \"%Hheapl\";\n      rewrite lookup_singleton in Hheapl;\n      specialize (Hheapl eq_refl);\n      destruct Hheapl as [valueShare Hheapl].\n\n    (* Now we can update the load to the value *)\n    iCombine \"Hj Hown\" as \"Hown\".\n    iDestruct (ghost_part_ref_join (P:= spec_ghost) with \"Hown\") as \"Hown\".\n    iDestruct (part_ref_update (P:= spec_ghost) _ _ _ _\n    ({[j := Some (fill K (Val v))]}, to_heap gmap_empty)\n     (<[j := Some (fill K (Val v)) ]> (to_tpool tp), to_heap (heap σ)) with \"Hown\") as \">Hown\".\n    {\n      intros g Hjoin.\n      split.\n      (* the new values can join *)\n      - inv Hjoin; simpl in H1, H2.\n        pose proof (H1 j) as Hj.\n        rewrite lookup_singleton HtpJ in Hj.\n        inv Hj; subst.\n        (* g does not cointain j *)\n        { \n          split; auto.  (* heap doesn't change *)\n          intros thread.\n          destruct (eq_dec thread j); subst.\n          - simpl.\n            rewrite lookup_singleton.\n            rewrite lookup_insert.\n            rewrite <- H5.\n            apply lower_None2.\n          - simpl.\n            rewrite lookup_singleton_ne; auto.\n            rewrite lookup_insert_ne; auto.\n            pose proof (H1 thread) as Htd.\n            inv Htd; first apply lower_None1.\n            {\n              rewrite lookup_singleton_ne; auto.\n              apply lower_None1.\n            }\n            {\n              rewrite lookup_singleton_ne in H3; auto.\n              inv H3.\n            }\n        }\n        (* g contains j *)\n        {\n          split; auto.\n          intros thread.\n          destruct (decide (thread = j)); subst.\n          - simpl.\n            rewrite lookup_singleton.\n            rewrite lookup_insert.\n            inv H6.\n            { rewrite <- H4; apply lower_Some; apply lower_None2. }\n            { inv H8. }\n          - rewrite lookup_singleton_ne; auto.\n            rewrite lookup_insert_ne; auto.\n            pose proof (H1 thread) as Htd.\n            inv Htd. \n            { rewrite H8; apply lower_None1. }\n            { \n              rewrite lookup_singleton_ne in H8; auto.\n              (* It didn't want to let me rewrite None = _ equations so we do this *)\n              rewrite H8 in H7.\n              rewrite H7.\n              apply lower_None1.\n            }\n            inv H8.\n            { rewrite H5 in H7; rewrite H7; apply lower_None1. }\n            { rewrite lookup_singleton_ne in H3; auto; inv H3. }\n            inv H9.\n        }\n      (* show that if this is the only piece they're equal *)\n      - intros Hsub.\n        inv Hsub; subst.\n        rewrite insert_singleton.\n        reflexivity.\n    }\n    iDestruct (ghost_part_ref_join (P:= spec_ghost) with \"[$Hown]\") as \"[Hj Hown]\".\n    iMod (\"Hclose\" with \"[Hown]\") as \"_\".\n    { \n    iNext.\n    iExists (<[j:=fill K (of_val v)]> tp), σ.\n    rewrite to_tpool_insert'; last eauto. iFrame. iPureIntro.\n    split; auto.\n    eapply rtc_r, step_insert_no_fork; eauto. econstructor; eauto.\n    rewrite /to_heap in Hheapl.\n    rewrite lookup_fmap in Hheapl.\n    destruct (heap σ !! l) eqn:Hpos; rewrite Hpos in Hheapl; simpl; try discriminate.\n    simpl in Hheapl.\n    inv Hheapl.\n    reflexivity.\n    }\n    iModIntro.\n    iSplitL \"Hj\".\n    { iExists sj; iFrame; iPureIntro; auto. }\n    iExists sl. \n    iSplitR; first (iPureIntro; auto).\n    iFrame.\n  Qed.\n\n  Lemma ref_right_load E ctx K l sh v:\n    nclose nspace ⊆ E → \n    (refines_right ctx (fill K (Load (Val (LitV (LitLoc l))))) * (heapS_mapsto sh l v) \n     |-- |={E}=> refines_right ctx (fill K (of_val v)) * (heapS_mapsto sh l v))%logic.\n  Proof.\n    intros Hnspace.\n    unfold refines_right.\n    iIntros \"[[Rctx Rtp] Rlv]\".\n    iPoseProof (step_load with \"[Rctx Rtp Rlv]\") as \"Rstep\"; first apply Hnspace.\n    {\n      iFrame \"Rctx\".\n      rewrite <- fill_app.\n      iSplitL \"Rtp\".\n      iApply \"Rtp\".\n      iApply \"Rlv\".\n    }\n    iMod \"Rstep\".\n    iDestruct \"Rstep\" as \"(Rctx & Rtp & Rpt)\".\n    iModIntro.\n    rewrite <- fill_app.\n    iFrame.\n  Qed.\n   \n\n\nLemma step_store E j K l v' e v:\n    IntoVal e v →\n    nclose nspace ⊆ E →\n    spec_ctx ∗ (tpool_mapsto j (fill K (Store (Val (LitV (LitLoc l))) e))) ∗ (heapS_mapsto fullshare l v')\n    ={E}=∗ spec_ctx ∗ (tpool_mapsto j (fill K (Val (LitV LitUnit)))) ∗ (heapS_mapsto fullshare l v).\n  Proof.\n    iIntros (<-?) \"(#Hinv & [[%sj [Hsjne Hj]] [%sl [Hslne Hl]]])\". iFrame \"Hinv\".\n    iDestruct \"Hsjne\" as %Hsjne.\n    iDestruct \"Hslne\" as %Hslne.\n    rewrite /spec_ctx /tpool_mapsto.\n    iDestruct \"Hinv\" as (ρ) \"Hinv\".\n    iInv nspace as (tp σ) \">[% Hown]\" \"Hclose\".\n    rewrite /heapS_mapsto /=.\n\n    (* we probably need the fact that the things in the heap exist *)\n    iDestruct (tpool_ref_sub_lookup j with \"[$Hown $Hj]\") as \"%HtpJ\";\n      rewrite lookup_singleton in HtpJ;\n      specialize (HtpJ eq_refl).\n    iDestruct (heap_ref_sub_lookup l with \"[$Hown $Hl]\") as \"%Hheapl\";\n      rewrite lookup_singleton in Hheapl;\n      specialize (Hheapl eq_refl);\n      destruct Hheapl as [valueShare Hheapl].\n\n    (* we need to update both \"Hj\" and \"Hl\" and the heap and thread pool *)\n    (* First the \"tpool_mapsto\" *)\n    iCombine \"Hj Hown\" as \"Hown\".\n    iDestruct (ghost_part_ref_join (P:= spec_ghost) with \"Hown\") as \"Hown\".\n    iDestruct (part_ref_update (P:= spec_ghost) _ _ _ _\n    ({[j := Some (fill K (Val (LitV LitUnit)))]}, to_heap gmap_empty)\n    (<[j := Some (fill K (Val (LitV LitUnit))) ]> (to_tpool tp), to_heap (heap σ)) with \"Hown\") as \">Hown\".\n    {\n      intros g Hj.\n      split.\n      (* these values join properly *)\n      {\n        destruct Hj as [Htp Hheap].\n        split; auto. (* we only changed the thread pool here *)\n        simpl.\n        clear Hheap.\n        (* now we prove this joins for any arbitrary thread *)\n        intros thread.\n        specialize (Htp thread).\n        destruct (eq_dec thread j); subst.\n        - rewrite lookup_singleton in Htp.\n          rewrite lookup_singleton.\n          rewrite lookup_insert.\n          inv Htp. \n          { apply lower_None2. }\n          inv H4.\n          { apply lower_Some; apply lower_None2. }\n          inv H5.\n        - rewrite ? lookup_insert_ne; auto.\n          rewrite ? lookup_insert_ne in Htp; auto.\n      }\n      (* if this is the only piece, it still joins *)\n      {\n        intros Heq; inv Heq.\n        rewrite insert_singleton.\n        reflexivity.\n      }\n    }\n    (* don't forget to break up the ghost_part_ref *)\n    iDestruct (ghost_part_ref_join (P:= spec_ghost) with \"[$Hown]\") as \"[Hj Hown]\".\n\n    (* now the \"heapS_mapsto\" *)\n    iCombine \"Hl Hown\" as \"Hown\".\n    iDestruct (ghost_part_ref_join (P:= spec_ghost) with \"Hown\") as \"Hown\".\n    (* NOTE: we include the prior update in this!!!  We'd be \"removing\" otherwise if we could even prove it *)\n    iDestruct (part_ref_update (P:= spec_ghost) _ _ _ _\n    (to_tpool [], {[l := Some (fullshare, Some v)]})\n    (<[j:=Some (fill K (Val (LitV LitUnit)))]> (to_tpool tp), <[l := Some (fullshare, Some v)]> (to_heap (heap σ))) with \"Hown\") as \">Hown\".\n    {\n      intros g Hhp.\n      split.\n      (* The update joins *)\n      {\n        destruct Hhp as [Htp Hhp].\n        simpl in Htp, Hhp. \n        simpl.\n        split; auto.\n        clear Htp. (* we don't care about the thread pool since it's static *)\n        intros loc.\n        simpl.\n        destruct (decide (loc = l)); subst.\n        (* loc = l *)\n        - specialize (Hhp l).\n          rewrite ? lookup_insert in Hhp.\n          rewrite ? lookup_insert.\n          inv Hhp.\n          { apply lower_None2. }\n          apply lower_Some.\n          destruct a3.\n          { \n            destruct p.\n            destruct a2.\n            - destruct p.\n              inv H4.\n              destruct H5; destruct H5.\n              apply join_Tsh in H5.\n              inv H5.\n              contradiction.\n            - unfold sepalg.join.\n              reflexivity.\n          }\n          {\n            destruct a2.\n            - destruct p.\n              inv H4.\n            - inv H4.\n          }\n        (* loc ≠ l *)\n        - specialize (Hhp loc).\n          rewrite ? lookup_insert_ne; auto.\n          rewrite ? lookup_insert_ne in Hhp; auto.\n      }\n      (* if this is the only piece it is the full *)\n      {\n        intros Heq.\n        inv Heq.\n        rewrite insert_singleton.\n        rewrite H2.\n        reflexivity.\n      }\n    }\n    iDestruct (ghost_part_ref_join (P:= spec_ghost) with \"[$Hown]\") as \"[Hl Hown]\".\n    rewrite /UsrGhost.\n    iMod (\"Hclose\" with \"[Hown]\") as \"_\".\n    {\n    iNext.\n    rewrite /spec_inv.\n    iExists (<[j:=fill K (Val (LitV LitUnit))]> tp), (state_upd_heap <[l:=Some v]> σ).\n    rewrite to_heap_insert to_tpool_insert'; last eauto. iFrame. iPureIntro; split; auto.\n    eapply rtc_r, step_insert_no_fork; eauto. econstructor; eauto.\n\n    (* show we *did* in fact have something in the heap *)\n    (* NOTE: if I find a better way to do this, update it here too! *)\n    rewrite /to_heap in Hheapl.\n    rewrite lookup_fmap in Hheapl.\n    destruct (heap σ !! l) eqn:Hpos; rewrite Hpos in Hheapl; simpl.\n    { \n      simpl in Hheapl.\n      inv Hheapl.\n      auto.\n    }\n    {\n      simpl in Hheapl.\n      inv Hheapl.\n    }\n    }\n    iModIntro.\n    iSplitL \"Hj\".\n    { iExists sj; iFrame; iPureIntro; auto. }\n    iExists sl.\n    iSplitR; first (iPureIntro; auto).\n    iFrame.\n  Qed.\n\n    (*IntoVal e v →*)\n    (*nclose nspace ⊆ E →*)\n    (*spec_ctx ∗ (tpool_mapsto j (fill K (Store (Val (LitV (LitLoc l))) e))) ∗ (heapS_mapsto fullshare l v')*)\n    (*={E}=∗ spec_ctx ∗ (tpool_mapsto j (fill K (Val (LitV LitUnit)))) ∗ (heapS_mapsto fullshare l v).*)\n\n  Lemma ref_right_store E ctx K l e v' v:\n    IntoVal e v →\n    nclose nspace ⊆ E → \n    (refines_right ctx (fill K (Store (Val (LitV (LitLoc l))) e)) * (heapS_mapsto fullshare l v') \n     |-- |={E}=> refines_right ctx (fill K (Val (LitV LitUnit))) * (heapS_mapsto fullshare l v))%logic.\n  Proof.\n    iIntros (Hiv Hnspace) \"[[Rctx Rtp] Rlv]\".\n    unfold refines_right.\n    do 2 rewrite <- fill_app.\n    iPoseProof (step_store with \"[$Rctx $Rtp $Rlv]\") as \"Rstep\"; first apply Hnspace.\n    iMod \"Rstep\".\n    iDestruct \"Rstep\" as \"(Rctx & Rtp & Rpt)\".\n    iModIntro.\n    iFrame.\n  Qed.\n\nEnd heap.\n", "meta": {"author": "Baricus", "repo": "vloc", "sha": "b8cdbc81abf5f187a27466e97dd510f5dbf6dd3d", "save_path": "github-repos/coq/Baricus-vloc", "path": "github-repos/coq/Baricus-vloc/vloc-b8cdbc81abf5f187a27466e97dd510f5dbf6dd3d/Lib/heap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2760657046260359}}
{"text": "Require Import Fiat.Common Fiat.Computation Coq.Sets.Ensembles.\nRequire Import Fiat.ADT.ADTSig Fiat.ADT.Core Fiat.ADTRefinement.Core.\n\n(** Definitions for integrating [refineADT] into the setoid rewriting\n    framework. *)\n\n#[global]\nInstance refineConstructor_refl rep Dom\n: Reflexive (@refineConstructor rep rep eq Dom).\nProof.\n  induction Dom; simpl.\n  - intro; simpl; intros; subst; computes_to_econstructor; eauto.\n  - intro; simpl; intros; subst; apply IHDom.\nQed.\n\n#[global]\nInstance refineMethod_refl rep Dom Cod\n: Reflexive (@refineMethod rep rep eq Dom Cod).\nProof.\n  unfold refineMethod, methodType; intro; simpl; intros; subst.\n  remember (x r_n); clear.\n  induction Dom.\n  - destruct Cod; intro; simpl; intros; subst;\n    repeat computes_to_econstructor; try destruct v; eauto.\n  - intro; simpl; intros; subst; apply IHDom.\nQed.\n\nLemma refineConstructor_trans\n      rep rep' rep'' Dom\n      AbsR AbsR'\n  : forall c c' c'',\n    @refineConstructor rep rep' AbsR Dom c c'\n    -> @refineConstructor rep' rep'' AbsR' Dom c' c''\n    -> refineConstructor\n         (fun r_o r_n => exists r_o', AbsR r_o r_o' /\\ AbsR' r_o' r_n)\n         c c''.\nProof.\n  induction Dom.\n  - intro; simpl; intros; subst; intros v Comp_v.\n    apply H0 in Comp_v; computes_to_inv; subst.\n    apply H in Comp_v; computes_to_inv; subst; eauto.\n  - simpl; intros; eapply IHDom; simpl in *.\n    apply H.\n    eapply H0.\nQed.\n\nLemma refineConstructor_eq_trans\n      rep rep' Dom\n      AbsR\n  : forall c c' c'',\n    @refineConstructor rep rep' AbsR Dom c c'\n    -> @refineConstructor_eq rep' Dom c' c''\n    -> refineConstructor AbsR c c''.\nProof.\n  induction Dom.\n  - intro; simpl; intros; subst; intros v Comp_v.\n    apply H0 in Comp_v; computes_to_inv; subst.\n    apply H in Comp_v; computes_to_inv; subst; eauto.\n  - simpl; intros; eapply IHDom; simpl in *.\n    apply H.\n    eapply H0.\nQed.\n\n#[global]\nInstance refineConstructor_trans' rep Dom\n: Transitive (@refineConstructor rep rep eq Dom).\nProof.\n  induction Dom.\n  - intro; intros.\n    pose proof (refineConstructor_trans nil eq eq x y z H H0);\n      unfold refineConstructor, refine; intros.\n    eapply H1 in H2; computes_to_inv; subst.\n    destruct_ex; intuition; subst; eauto.\n  - simpl; intro; intros.\n    eapply IHDom.\n    apply H.\n    apply H0.\nQed.\n\nLemma refineMethod_trans rep rep' rep'' Dom Cod\n      AbsR AbsR'\n  : forall m m' m'',\n    @refineMethod rep rep' AbsR Dom Cod m m'\n    -> @refineMethod rep' rep'' AbsR' Dom Cod m' m''\n    -> refineMethod (fun r_o r_n => exists r_o', AbsR r_o r_o' /\\ AbsR' r_o' r_n)\n                         m m''.\nProof.\n  unfold refineMethod, methodType; induction Dom.\n  - intro; simpl; intros; destruct Cod; subst; intros v Comp_v.\n    + destruct_ex; intuition.\n      eapply H0 in Comp_v; eauto; computes_to_inv; subst.\n      eapply H in Comp_v; eauto; computes_to_inv; subst; eauto.\n      repeat computes_to_econstructor; eauto.\n    + destruct_ex; intuition.\n      eapply H0 in Comp_v; eauto; computes_to_inv; subst.\n      eapply H in Comp_v; eauto; computes_to_inv; subst; eauto.\n  - simpl; intros.\n    destruct_ex; intuition.\n    eapply (IHDom (fun d' => m r_o d)\n                  (fun d' => m' x d)\n                  (fun d' => m'' r_n d)); eauto.\nQed.\n\nLemma refineMethod_eq_trans rep rep' Dom Cod\n      AbsR\n  : forall m m' m'',\n    @refineMethod rep rep' AbsR Dom Cod m m'\n    -> @refineMethod_eq rep' Dom Cod m' m''\n    -> refineMethod AbsR m m''.\nProof.\n  unfold refineMethod, methodType; induction Dom.\n  - intro; simpl; intros; destruct Cod; subst; intros v Comp_v.\n    + destruct_ex; intuition.\n      eapply H0 in Comp_v; eauto; computes_to_inv; subst.\n      eapply H in Comp_v; eauto; computes_to_inv; subst; eauto.\n    + destruct_ex; intuition.\n      eapply H0 in Comp_v; eauto; computes_to_inv; subst.\n      eapply H in Comp_v; eauto; computes_to_inv; subst; eauto.\n  - simpl; intros.\n    destruct_ex; intuition.\n    unfold refineMethod_eq in *.\n    eapply (IHDom (fun r_o => m r_o d)\n                  (fun r_n => m' r_n d)\n                  (fun r_n => m'' r_n d)); eauto.\n    intros; eapply H0.\nQed.\n\n#[global]\nInstance refineMethod_trans' rep Dom Cod\n: Transitive (@refineMethod rep rep eq Dom Cod).\nProof.\n  unfold refineMethod, methodType; subst; induction Dom.\n  - intro; intros.\n    pose proof (refineMethod_trans H H0);\n      unfold refineMethod, refineMethod', refine in *; destruct Cod; intros; subst.\n    + eapply H2 in H3; eauto; computes_to_inv; subst.\n      destruct_ex; intuition; subst; eauto.\n    + eapply H2 in H3; eauto; computes_to_inv; subst.\n      destruct_ex; intuition; subst; eauto.\n  - intro; simpl; intros; subst.\n    eapply (IHDom (fun d' => x r_n d)\n                  (fun d' => y r_n d)\n                  (fun d' => z r_n d)) with (r_o := r_n); 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' ? ?].\n    econstructor 1 with\n      (AbsR := fun x z => exists y, AbsR x y /\\ AbsR' y z);\n      simpl in *; intros.\n    + eauto using refineConstructor_trans.\n    + eauto using refineMethod_trans.\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": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/ADTRefinement/SetoidMorphisms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526368038302, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.27602526824050105}}
{"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 cequiv_bind.\nRequire Export sequents2.\nRequire Export sequents_lib.\nRequire Export sequents_tacs.\nRequire Export sequents_tacs2.\nRequire Export per_props_equality.\nRequire Export per_can.\nRequire Export subst_tacs_aeq.\nRequire Export cequiv_tacs.\n\n\n(**\n\n<<\n   H |- a ~ b\n     no subgoals\n\n     if alpha_eq(a,b)\n>>\n *)\n\nDefinition rule_cequiv_alpha_eq_concl {o} (H : @bhyps o) a b :=\n  mk_baresequent H (mk_conclax (mk_cequiv a b)).\n\nDefinition rule_cequiv_alpha_eq {o}\n           (H : @barehypotheses o)\n           (a b : NTerm) :=\n  mk_rule (rule_cequiv_alpha_eq_concl H a b) [] [].\n\nLemma rule_cequiv_alpha_eq_true3 {o} :\n  forall lib (H  : @barehypotheses o) (a b : NTerm) (aeq : alpha_eq a b),\n    rule_true3 lib (rule_cequiv_alpha_eq H a b).\nProof.\n  intros.\n  unfold rule_cequiv_alpha_eq, rule_true3, wf_bseq, closed_type_baresequent, closed_extract_baresequent; simpl.\n  intros.\n  clear cargs hyps.\n\n  match goal with\n  | [ |- sequent_true2 _ ?s ] => assert (wf_csequent s) as wfc by prove_seq\n  end.\n  exists wfc.\n  unfold wf_csequent, wf_sequent, wf_concl in wfc; allsimpl; repnd; proof_irr; GC.\n\n  vr_seq_true.\n  lsubst_tac.\n  rw @member_eq.\n  rw <- @member_cequiv_iff; sp.\n\n  - apply tequality_mkc_cequiv; split; intro h; spcast.\n\n    + apply alphaeqc_implies_cequivc.\n      unfold alphaeqc; simpl.\n      apply lsubst_alpha_congr2; auto.\n\n    + apply alphaeqc_implies_cequivc.\n      unfold alphaeqc; simpl.\n      apply lsubst_alpha_congr2; auto.\n\n  - spcast.\n    apply alphaeqc_implies_cequivc.\n    unfold alphaeqc; simpl.\n    apply lsubst_alpha_congr2; auto.\nQed.\n\nLemma rule_cequiv_alpha_eq_true_ext_lib {o} :\n  forall lib (H  : @barehypotheses o) (a b : NTerm) (aeq : alpha_eq a b),\n    rule_true_ext_lib lib (rule_cequiv_alpha_eq H a b).\nProof.\n  introv aeq.\n  apply rule_true3_implies_rule_true_ext_lib.\n  introv.\n  apply rule_cequiv_alpha_eq_true3; auto.\nQed.\n\nLemma rule_cequiv_alpha_eq_wf2 {o} :\n  forall (H  : @barehypotheses o) (a b : NTerm),\n    wf_rule2 (rule_cequiv_alpha_eq H a b).\nProof.\n  introv wf j; allsimpl; repndors; subst; tcsp;\n    allunfold @wf_bseq; repnd; allsimpl; wfseq.\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/rules_squiggle9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.27600820650761076}}
{"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(** * Restriction of a code (only the keys of a message appears)\n\n- Key definitions: [restrict_code]\n- Initial author: Laurent.Thery@inria.fr (2003)\n\n*)\n\nFrom Coq Require Import Sorting.Permutation.\nFrom Huffman Require Export Code Frequency ISort UniqueKey PBTree2BTree.\n\nSet Default Proof Using \"Type\".\n\nSection Restrict.\nVariable A : Type.\nVariable empty : A.\nVariable A_eq_dec : forall a b : A, {a = b} + {a <> b}.\nVariable m : list A.\n\n(** Restrict the code putting only codes of element in the frequency list *)\nDefinition restrict_code (m : list A) (c : code A) : code A :=\n  map (fun x => (fst x, find_code A_eq_dec (fst x) c))\n    (frequency_list A_eq_dec m).\n\n(** The restriction has unique keys *)\nTheorem restrict_code_unique_key :\n forall c : code A, unique_key (restrict_code m c).\nProof.\nintros c; apply NoDup_unique_key.\nunfold restrict_code in |- *.\nreplace\n (map (fst (B:=_))\n    (map (fun x : A * nat => (fst x, find_code A_eq_dec (fst x) c))\n       (frequency_list A_eq_dec m))) with\n (map (fst (B:=_)) (frequency_list A_eq_dec m)).\napply unique_key_NoDup; auto.\nelim (frequency_list A_eq_dec m); simpl in |- *; auto with datatypes.\nintros a l H; apply f_equal2 with (f := cons (A:=A)); auto.\nQed.\n\n(** Doing the restriction does not change the codes *) \nTheorem restrict_code_in :\n forall (a : A) (c : code A),\n In a m -> find_code A_eq_dec a c = find_code A_eq_dec a (restrict_code m c).\nProof.\nintros a c H.\napply sym_equal; apply find_code_correct2; auto.\napply restrict_code_unique_key.\ngeneralize (in_frequency_map _ A_eq_dec m a H).\nunfold restrict_code in |- *; elim (frequency_list A_eq_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\n(**\n  The restriction does not change the encoding for messages in\n  the same alphabet\n*)\nTheorem restrict_code_encode_incl :\n forall (m1 : list A) (c : code A),\n incl m1 m -> encode A_eq_dec c m1 = encode A_eq_dec (restrict_code m c) m1.\nProof.\nintros 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\n(** The restriction does not change the encoding of the initial message *)\nTheorem restrict_code_encode :\n forall c : code A, encode A_eq_dec c m = encode A_eq_dec (restrict_code m c) m.\nProof.\nintros c; apply restrict_code_encode_incl; auto with datatypes.\nQed.\n\n(** \n  The restriction does not change the unique prefix property if\n  the message is in the alphabet\n*)\nTheorem restrict_unique_prefix :\n forall c : code A,\n not_null c ->\n in_alphabet m c -> unique_prefix c -> unique_prefix (restrict_code m c).\nProof.\nintros c HH HH0 (HH1, HH2); split.\nintros a1 a2 lb1 lb2 H0 H1 H2; apply HH1 with (lb1 := lb1) (lb2 := lb2); auto.\nunfold restrict_code in H0.\ncase (proj1 (in_map_iff _ _ _)) with (1 := H0).\nintros x; case x; simpl in |- *.\nintros a0 n (HP2, HP1).\nrewrite <- HP2.\ncase (HH0 a0); auto.\napply frequency_list_in with (1 := HP1).\nintros x0 H; rewrite find_code_correct2 with (2 := H); auto.\nunfold restrict_code in H1.\ncase (proj1 (in_map_iff _ _ _)) with (1 := H1).\nintros x; case x; simpl in |- *.\nintros a0 n (HP2, HP1).\nrewrite <- HP2.\ncase (HH0 a0); auto.\napply frequency_list_in with (1 := HP1).\nintros x0 H; rewrite find_code_correct2 with (2 := H); auto.\nunfold restrict_code in |- *.\napply unique_key_map; auto.\nQed.\n\n(** Restricting do not change the frequency list *)\nTheorem frequency_list_restric_code_map :\n forall c,\n map (fst (B:=_)) (frequency_list A_eq_dec m) =\n map (fst (B:=_)) (restrict_code m c).\nProof.\nintros c; unfold restrict_code in |- *; elim (frequency_list A_eq_dec m);\n simpl in |- *; auto.\nintros a0 l H; apply f_equal2 with (f := cons (A:=A)); auto.\nQed.\n\n(** If the message is not null, so is the restriction *)\nTheorem restrict_not_null : forall c, m <> [] -> restrict_code m c <> [].\nProof.\ncase m; simpl in |- *; auto.\nunfold restrict_code in |- *.\nintros a0 l c H H1.\nabsurd\n (In\n    ((fun x : A * nat => (fst x, find_code A_eq_dec (fst x) c))\n       (a0, number_of_occurrences A_eq_dec a0 (a0 :: l))) []);\n auto with datatypes.\nrewrite <- H1.\napply\n in_map with (f := fun x : A * nat => (fst x, find_code A_eq_dec (fst x) c)).\napply frequency_number_of_occurrences; auto with datatypes.\nQed.\n\n(** \n  The leaves of the build tree from the restrict code are the keys\n  of the frequency list\n*) \nTheorem restrict_code_pbbuild :\n forall c : code A,\n not_null c ->\n unique_prefix c ->\n in_alphabet m c ->\n m <> [] ->\n Permutation (map fst (frequency_list A_eq_dec m))\n   (all_pbleaves (pbbuild empty (restrict_code m c))).\nProof.\nintros c H H0 H1 H2.\nrewrite frequency_list_restric_code_map with (c := c).\napply all_pbleaves_pbbuild; auto.\napply restrict_not_null; auto.\napply restrict_unique_prefix; auto.\nQed.\n \nEnd Restrict.\n\nArguments restrict_code [A].\n", "meta": {"author": "coq-community", "repo": "huffman", "sha": "0857dc9ac31c5bfb71b398c9df62a39eda1fd675", "save_path": "github-repos/coq/coq-community-huffman", "path": "github-repos/coq/coq-community-huffman/huffman-0857dc9ac31c5bfb71b398c9df62a39eda1fd675/theories/Restrict.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.27600819866722237}}
{"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 List Classical.\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq.\nRequire Import ZArith_ext Max_ext ssrnat_ext seq_ext.\nRequire Import bipl seplog.\nRequire Import frag_list_entail.\n\nLocal Close Scope Z_scope.\nLocal Close Scope positive_scope.\nRequire Import integral_type.\n\nRequire Import expr_b_dp.\nImport seplog_Z_m.assert_m.\nImport seplog_Z_m.assert_m.expr_m.\nImport seplog_Z_m.\n\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\nInductive wpAssrt : Type :=\n| wpElt : Assrt -> wpAssrt\n| wpSubst : list (var.v * expr) -> wpAssrt -> wpAssrt\n| wpLookup : var.v -> expr -> wpAssrt -> wpAssrt\n| wpMutation : expr -> expr -> wpAssrt -> wpAssrt\n| wpIf : expr_b -> wpAssrt -> wpAssrt -> wpAssrt.\n\nFixpoint wpAssrt_interp (a: wpAssrt) : assert :=\n  match a with\n    wpElt a1 => Assrt_interp a1\n    | wpSubst l L => wp_assigns l (wpAssrt_interp L)\n    | wpLookup x e L => (fun s h => exists e0, (e |~> e0 ** (e |~> e0 -* (wp_assign x e0 (wpAssrt_interp L)))) s h)\n    | wpMutation e1 e2 L => (fun s h => exists e0, (e1 |~> e0 ** (e1 |~> e2 -* (wpAssrt_interp L))) s h)\n    | wpIf b L1 L2 =>\n      (fun s h => ([ b ]b_ s -> wpAssrt_interp L1 s h) /\\\n                  (~~ [ b ]b_ s -> wpAssrt_interp L2 s h))\n  end.\n\nLocal Open Scope entail_scope.\n\nFixpoint subst_Sigma (a : Sigma) (x : var.v) (e : expr) {struct a} : Sigma :=\n  match a with\n    | singl e1 e2 => singl (subst_e e1 (var_e x) e) (subst_e e2 (var_e x) e)\n    | frag_list_entail.emp => frag_list_entail.emp\n    | s1 \\** s2 => subst_Sigma s1 x e \\** subst_Sigma s2 x e\n    | cell e1 => cell (subst_e e1 (var_e x) e)\n    | lst e1 e2 => lst (subst_e e1 (var_e x) e) (subst_e e2 (var_e x) e)\n  end.\n\nDefinition subst_assrt (a : assrt) (x : var.v) (e : expr) : assrt :=\n  match a with\n    (pi, sigm) => (subst_b pi (var_e x) e, subst_Sigma sigm x e)\n  end.\n\nFixpoint subst_Assrt (a : Assrt) (x : var.v) (e : expr) {struct a} : Assrt :=\n  match a with\n    | nil => nil\n    | hd :: tl => subst_assrt hd x e :: subst_Assrt tl x e\n  end.\n\nFixpoint subst_assrt_lst (l : list (var.v * expr)) (a : assrt) {struct l} : assrt :=\n  match l with\n    | nil => a\n    | (x, e) :: tl => subst_assrt_lst tl (subst_assrt a x e)\n  end.\n\nFixpoint subst_Assrt_lst (l : list (var.v * expr)) (a : Assrt) {struct l} : Assrt :=\n  match l with\n    | nil => a\n    | (x, e) :: tl => subst_Assrt_lst tl (subst_Assrt a x e)\n  end.\n\n(** properties of substitution functions *)\n\nLemma subst_Sigma2store_update : forall sigm s h x v,\n  Sigma_interp (subst_Sigma sigm x v) s h ->\n  Sigma_interp sigm (store.upd x (eval v s) s) h.\nProof.\ninduction sigm; simpl; intros; auto.\n- case : H => H0 H1.\n  split.\n  Mapsto; by rewrite -!eval_upd_subst.\n  by rewrite !eval_upd_subst.\n  case: H => H0 H1.\n  split.\n  case: H0 => x0 H.\n  exists x0.\n  Mapsto; by rewrite -!eval_upd_subst.\n  by rewrite !eval_upd_subst.\n- case_sepcon H.\n  Compose_sepcon h1 h2.\n  by apply IHsigm1.\n  by apply IHsigm2.\n- eapply Lst_equiv'.\n  apply H.\n  by rewrite -!eval_upd_subst.\n  by rewrite -!eval_upd_subst.\nQed.\n\nLemma subst_Sigma2store_update': forall sigm s h x v,\n  Sigma_interp sigm (store.upd x (eval v s) s) h ->\n  Sigma_interp (subst_Sigma sigm x v) s h.\nProof.\ninduction sigm; simpl; intros; auto.\n- inversion_clear H.\n  split.\n  Mapsto; by rewrite -!eval_upd_subst.\n  by rewrite -!eval_upd_subst.\n- case : H => H0 H1.\n  case : H0 => x0 H.\n  split.\n  exists x0.\n  Mapsto; by rewrite !eval_upd_subst.\n  by rewrite -!eval_upd_subst.\n- case_sepcon H.\n  Compose_sepcon h1 h2.\n  by apply IHsigm1.\n  by apply IHsigm2.\n- eapply Lst_equiv'.\n  apply H.\n  by rewrite -!eval_upd_subst.\n  by rewrite !eval_upd_subst.\nQed.\n\nLemma subst_Assert2store_update : forall A s h x v,\n  Assrt_interp (subst_Assrt A x v) s h ->\n  Assrt_interp A (store.upd x (eval v s) s) h.\nProof.\ninduction A; simpl; auto.\nintros.\ninversion_clear H.\nleft.\ndestruct a.\nsimpl; simpl in H0.\ninversion_clear H0.\nsplit.\nby rewrite eval_b_upd_subst.\nby apply subst_Sigma2store_update.\nright.\nby apply IHA.\nQed.\n\nLemma wp_assigns_assrt_interp: forall l s h pi sigm,\n  assrt_interp (subst_assrt_lst l (pi, sigm)) s h ->\n  wp_assigns l (assrt_interp (pi, sigm)) s h.\nProof.\ninduction l; simpl; intros; auto.\ninduction a; simpl.\nmove: (IHl _ _ _ _ H) => H0.\nrewrite (_ :  wp_assign a b\n  (fun s0 (h0 : assert_m.heap.t) =>\n    [ pi ]b_ s0 /\\ Sigma_interp sigm s0 h0) =\n  assrt_interp (subst_b pi (var_e a) b, subst_Sigma sigm a b)) //.\nrewrite /wp_assign /=.\napply assert_m.assert_ext => s0 h0; split => [ [H1 H2] | [H1 H2] ].\n- rewrite eval_b_upd_subst in H1.\n  split; first by [].\n  by apply subst_Sigma2store_update'.\n- rewrite -eval_b_upd_subst in H1.\n  split; first by [].\n  by apply subst_Sigma2store_update.\nQed.\n\nLemma wp_assigns_Assrt_interp: forall l A s h,\n  Assrt_interp (subst_Assrt_lst l A) s h ->\n  wp_assigns l (Assrt_interp A) s h.\nProof.\ninduction l; simpl; intros; auto.\ninduction a; simpl.\nmove: (IHl _ _ _ H) => H0.\neapply entails_wp_assigns; [idtac | eapply H0].\nrewrite/while.entails /wp_assign; intros.\nby apply subst_Assert2store_update.\nQed.\n\n(* a module for fresh variables (w.r.t. syntactic constructs) *)\nModule Type FRESH.\n\nParameter fresh_Sigma : var.v -> Sigma -> bool.\n\nParameter fresh_assrt : var.v -> assrt -> bool.\n\nParameter fresh_wpAssrt : var.v -> wpAssrt -> bool.\n\nParameter fresh_cmd : var.v -> @while.cmd cmd0 expr_b -> bool.\n\nParameter fresh_wpAssrt_inde: forall L x , fresh_wpAssrt x L ->\n  inde (x::nil) (wpAssrt_interp L).\n\nEnd FRESH.\n\nModule Fresh <: FRESH.\n\nFixpoint var_max_Sigma (s: Sigma) : var.v :=\n  match s with\n    | singl e1 e2 => max (max_lst (vars e1)) (max_lst (vars e2))\n    | frag_list_entail.emp => 0\n    | s1 \\** s2 => max (var_max_Sigma s1) (var_max_Sigma s2)\n    | cell e1 => max_lst (vars e1)\n    | lst e1 e2 => max (max_lst (vars e1)) (max_lst (vars e2))\n  end.\n\nDefinition var_max_assrt (a: assrt) : var.v :=\n  match a with\n    (pi, sigm) => max (max_lst (vars_b pi)) (var_max_Sigma sigm)\n  end.\n\nFixpoint var_max_Assrt (a: Assrt) : var.v :=\n  match a with\n    | nil => 0\n    | hd::tl => max (var_max_assrt hd) (var_max_Assrt tl)\n  end.\n\nFixpoint var_max_wpAssrt (a: wpAssrt) : var.v :=\n  match a with\n    wpElt a1 => var_max_Assrt a1\n    | wpSubst l L => max (var_max_lst l) (var_max_wpAssrt L)\n    | wpLookup x e L=> max (max x (max_lst (vars e))) (var_max_wpAssrt L)\n    | wpMutation e1 e2 L => max (max (max_lst (vars e1)) (max_lst (vars e2))) (var_max_wpAssrt L)\n    | wpIf b L1 L2 => max (max (var_max_wpAssrt L1) (var_max_wpAssrt L2)) (max_lst (vars_b b))\n  end.\n\nFixpoint var_max_cmd (c: @while.cmd cmd0 expr_b) : var.v :=\n  match c with\n    skip => 0\n    | assign x e => max (max_lst (vars e)) x\n    | lookup x e => max (max_lst (vars e)) x\n    | mutation e1 e2 => max (max_lst (vars e1)) (max_lst (vars e2))\n    | malloc x e => max (max_lst (vars e)) x\n    | free e => max_lst (vars e)\n    | while.while b c' => max (max_lst (vars_b b)) (var_max_cmd c')\n    | while.seq c1 c2 => max (var_max_cmd c1) (var_max_cmd c2)\n    | while.ifte b c1 c2 => max (max (var_max_cmd c1) (var_max_cmd c2)) (max_lst (vars_b b))\n  end.\n\nDefinition fresh_Sigma x s := var_max_Sigma s < x.\n\nDefinition fresh_assrt x a := var_max_assrt a < x.\n\nDefinition fresh_Assrt x a := var_max_Assrt a < x.\n\nDefinition fresh_wpAssrt x L := var_max_wpAssrt L < x.\n\nDefinition fresh_cmd x c := var_max_cmd c < x.\n\nLtac open_fresh_frag_list :=\n  open_fresh_frag_list_hypo; open_fresh_frag_list_goal\nwith\n  open_fresh_frag_list_hypo := match goal with\n    | H: is_true (fresh_e _ _) |- _ => unfold fresh_e in H; simpl in H; open_fresh_frag_list_hypo\n    | H: is_true (fresh_b _ _)  |- _ => unfold fresh_b in H; simpl in H; open_fresh_frag_list_hypo\n    | H: is_true (fresh_Sigma _ _) |- _ => unfold fresh_Sigma in H; simpl in H; open_fresh_frag_list_hypo\n    | H: is_true (fresh_assrt _ _) |- _ => unfold fresh_assrt in H; simpl in H; open_fresh_frag_list_hypo\n    | H: is_true (fresh_lst _ _) |- _ => unfold fresh_lst in H; simpl in H; open_fresh_frag_list_hypo\n    | H: is_true (fresh_wpAssrt _ _) |- _ => unfold fresh_wpAssrt in H; simpl in H; open_fresh_frag_list_hypo\n    | H: context [ var_max_assrt _ ] |- _ => unfold var_max_assrt  in H; simpl in H; open_fresh_frag_list_hypo\n    | |- _ =>  idtac\n  end\nwith\n  open_fresh_frag_list_goal :=\n  match goal with\n    | |- is_true (fresh_e _ _) => rewrite /fresh_e /=; open_fresh_frag_list_goal\n    | |- is_true (fresh_b _ _) => rewrite /fresh_b /=; open_fresh_frag_list_goal\n    | |- is_true (fresh_Sigma _ _) => rewrite /fresh_Sigma /=; open_fresh_frag_list_goal\n    | |- is_true (fresh_assrt _ _) => rewrite /fresh_assrt /=; open_fresh_frag_list_goal\n    | |- is_true (fresh_lst _ _) => rewrite /fresh_lst /=; open_fresh_frag_list_goal\n    | |- is_true (fresh_wpAssrt _ _) => rewrite /fresh_wpAssrt /=; open_fresh_frag_list_goal\n    | |- context [var_max_assrt _ ] => rewrite /var_max_assrt /=; open_fresh_frag_list_goal\n    | |- _ => idtac\n  end.\n\nLtac Max_inf_resolve := open_fresh_frag_list; Resolve_lt_max.\n\n(** relations between freshness predicates and the independence predicate (\"inde\") *)\n\nLemma var_max_Sigma_inde : forall sigm x, fresh_Sigma x sigm ->\n  inde (x :: nil) (Sigma_interp sigm).\nProof.\nelim.\n- move=> e e0 x H; rewrite /inde => s h x0 v; rewrite mem_seq1 => /eqP ?; subst x0; split => /= H1.\n  + case : H1 => [[x1 H1] H3]; split.\n    * exists x1.\n      rewrite fresh_e_eval; last by Max_inf_resolve.\n      rewrite fresh_e_eval //; by Max_inf_resolve.\n    * rewrite fresh_e_eval //; by Max_inf_resolve.\n  + case : H1 => [[x1 [H2 H4]] H3]; split.\n    * exists x1.\n      rewrite fresh_e_eval // in H2; last by Max_inf_resolve.\n      rewrite fresh_e_eval // in H4; by Max_inf_resolve.\n    * rewrite fresh_e_eval // in H3; by Max_inf_resolve.\n- intros; red; simpl; split; intros; rewrite mem_seq1 in H0; move/eqP in H0; subst x0.\n  + case : H1 => [ [x1 [x2 [H2 H4]] ] H3]; split.\n    * exists x1, x2.\n      rewrite fresh_e_eval //; by Max_inf_resolve.\n    * rewrite fresh_e_eval //; by Max_inf_resolve.\n  + case : H1 => [ [x1 [ x2 H2] ] H3]; split.\n    * exists x1, x2.\n      rewrite fresh_e_eval // in H2; by Max_inf_resolve.\n    * rewrite fresh_e_eval // in H3; by Max_inf_resolve.\n- intros; red; simpl; split; intros.\n  + red in H1; by rewrite H1.\n  + by rewrite H1.\n- move=> s1 IH1 s2 IH2 x H; rewrite /inde => s h x0 v; rewrite mem_seq1 => /eqP ?; subst x0; split => /= H1.\n  + case_sepcon H1.\n    Compose_sepcon h1 h2.\n    * have /IH1 : fresh_Sigma x s1 by Max_inf_resolve.\n      move/(_ s h1 x v); rewrite mem_seq1 eqxx => /(_ isT); tauto.\n    * have /IH2 : fresh_Sigma x s2 by Max_inf_resolve.\n      move/(_ s h2 x v); rewrite mem_seq1 eqxx => /(_ isT); tauto.\n  + case_sepcon H1.\n    Compose_sepcon h1 h2.\n    * have /IH1 : fresh_Sigma x s1 by Max_inf_resolve.\n      move/(_ s h1 x v); rewrite mem_seq1 eqxx => /(_ isT); tauto.\n    * have /IH2 : fresh_Sigma x s2 by Max_inf_resolve.\n      move/(_ s h2 x v); rewrite mem_seq1 eqxx => /(_ isT); tauto.\n- intros; red; simpl; split; intros; rewrite mem_seq1 in H0; move/eqP in H0; subst x0.\n  + rewrite /fresh_Sigma /= in H.\n    eapply Lst_equiv'.\n    by apply H1.\n    rewrite fresh_e_eval //; by Max_inf_resolve.\n    rewrite fresh_e_eval //; by Max_inf_resolve.\n  + rewrite /fresh_Sigma /= in H.\n    eapply Lst_equiv'.\n    by apply H1.\n    rewrite fresh_e_eval //; by Max_inf_resolve.\n    rewrite fresh_e_eval //; by Max_inf_resolve.\nQed.\n\nLemma fresh_assrt_inde: forall a x , fresh_assrt x a ->\n  inde (x::nil) (assrt_interp a).\nProof.\ncase => a b /= x H.\nhave H0 : fresh_b x a by Max_inf_resolve.\nhave H1 : fresh_Sigma x b by Max_inf_resolve.\nred; simpl; split.\n- intros. case : H3 => H4 H5; split.\n  case: (fresh_b_inde a x true H0 s h x0 v H2) => H3 _; by apply H3.\n  case: (var_max_Sigma_inde b x H1 s h x0 v H2) => H3 _; by apply H3.\n- intros. case : H3 => H4 H5; split.\n  case: (fresh_b_inde a x true H0 s h x0 v H2) => H3; by apply.\n  case: (var_max_Sigma_inde b x H1 s h x0 v H2) => H3; by apply.\nQed.\n\nLemma fresh_Assrt_inde : forall a x, fresh_Assrt x a ->\n  inde (x::nil) (Assrt_interp a).\nProof.\ninduction a; simpl; intros; auto.\n- red in H; red; split; simpl; intros; contradiction.\n- rewrite /fresh_Assrt /= in H.\n  red; simpl; split; intros; rewrite mem_seq1 in H0; move/eqP in H0; subst x0.\n  + inversion_clear H1.\n    * left.\n      have H1 : fresh_assrt x a by Max_inf_resolve.\n      apply (fresh_assrt_inde a x H1 s h x) => //; by rewrite mem_seq1.\n    * right.\n      have H1 : fresh_Assrt x a0 by rewrite /fresh_Assrt /=; Max_inf_resolve.\n      apply (IHa x H1 s h x v) => //; by rewrite mem_seq1.\n  - case : H1 => H2.\n    * left.\n      have H1 : fresh_assrt x a by rewrite /fresh_Assrt /=; by Max_inf_resolve.\n      apply (fresh_assrt_inde a x H1 s h x v) => //; by rewrite mem_seq1.\n    * right.\n      have H0 : fresh_Assrt x a0 by rewrite /fresh_Assrt /=; by Max_inf_resolve.\n      apply (IHa x H0 s h x v) => //; by rewrite mem_seq1.\nQed.\n\nLemma fresh_wpAssrt_inde: forall L x , fresh_wpAssrt x L ->\n  inde (x::nil) (wpAssrt_interp L).\nProof.\ninduction L.\n- simpl.\n  red; simpl; split; intros.\n  move: (fresh_Assrt_inde a x H s h x0 v H0); by intuition.\n  move: (fresh_Assrt_inde a x H s h x0 v H0); by intuition.\n- red; simpl; split; intros.\n  have H2 : inde (x::nil) (wpAssrt_interp L) by apply IHL; Max_inf_resolve.\n  have H3 : fresh_lst x l by Max_inf_resolve.\n  case: (fresh_lst_inde _ _ _ H2 H3 s h x0 v H0); by intuition.\n  have H2 : inde (x::nil) (wpAssrt_interp L) by apply IHL; Max_inf_resolve.\n  have H3 : fresh_lst x l by Max_inf_resolve.\n  case: (fresh_lst_inde _ _ _ H2 H3 s h x0 v H0); by intuition.\n- red; simpl; split; intros; rewrite mem_seq1 in H0; move/eqP in H0; subst x0.\n  inversion_clear H1.\n  case_sepcon H0.\n  exists (cst_e (eval x0 s0)).\n  Compose_sepcon h1 h2.\n  Mapsto.\n  rewrite fresh_e_eval //; by Max_inf_resolve.\n  move=> h1' [X1 X2] h' Hh'.\n  red in H0_h2.\n  have H8 : h2 # h1' /\\ (e |~> x0) s0 h1'.\n    split => //.\n    Mapsto.\n    rewrite fresh_e_eval //; by Max_inf_resolve.\n  generalize (H0_h2 h1' H8 _ Hh') => H1.\n  rewrite /wp_assign in H1 *.\n  rewrite /= store.upd_upd; last by Max_inf_resolve.\n  have H10 : fresh_wpAssrt x L by Max_inf_resolve.\n  move: (IHL _ H10 (store.upd s (eval x0 s0) s0) h' x v) => X; apply X => //.\n  by rewrite mem_seq1.\n  case : H1 => x1 H2.\n  case_sepcon H2.\n  exists (cst_e (eval x1 (store.upd x v s0))).\n  Compose_sepcon h1 h2.\n  Mapsto.\n  rewrite fresh_e_eval //; by Max_inf_resolve.\n  move=> h1' [X1 X2] h' Hh'.\n  red in H2_h2.\n  have H8 : h2 # h1' /\\ (e |~> x1) (store.upd x v s0) h1'.\n    split; first by [].\n    Mapsto.\n    rewrite fresh_e_eval //; by Max_inf_resolve.\n  generalize (H2_h2 h1' H8 _ Hh') => H1.\n  rewrite /wp_assign in H1 *.\n  rewrite /=.\n  rewrite store.upd_upd in H1; last by Max_inf_resolve.\n  have H10 : fresh_wpAssrt x L by Max_inf_resolve.\n  move: (IHL _ H10 (store.upd s (eval x1 (store.upd x v s0)) s0) h' x v) => X; apply X => //.\n  by rewrite mem_seq1.\n- red; simpl; split; intros; rewrite mem_seq1 in H0; move/eqP in H0; subst x0.\n  inversion_clear H1.\n  case_sepcon H0.\n  exists (cst_e (eval x0 s)).\n  Compose_sepcon h1 h2.\n  Mapsto.\n  rewrite fresh_e_eval //; by Max_inf_resolve.\n  move=> h1' [X1 X2] h' Hh'.\n  red in H0_h2.\n  have H8 : h2 # h1' /\\ (e |~> e0) s h1'.\n    split; first by [].\n    Mapsto.\n    rewrite fresh_e_eval //; by Max_inf_resolve.\n    rewrite fresh_e_eval //; by Max_inf_resolve.\n  generalize (H0_h2 _ H8 _ Hh'); intro H1.\n  have H10 : fresh_wpAssrt x L by Max_inf_resolve.\n  apply (IHL _ H10 s h' x v) => //; by rewrite mem_seq1.\n  inversion_clear H1.\n  case_sepcon H0.\n  exists (cst_e (eval x0 (store.upd x v s))).\n  Compose_sepcon h1 h2.\n  Mapsto.\n  rewrite fresh_e_eval //; by Max_inf_resolve.\n  move=> h1' [X1 X2] h' Hh'.\n  red in H0_h2.\n  have H8 : h2 # h1' /\\ (e |~> e0) (store.upd x v s) h1'.\n    split; first by [].\n    Mapsto.\n    rewrite fresh_e_eval //; by Max_inf_resolve.\n    rewrite fresh_e_eval //; by Max_inf_resolve.\n  generalize (H0_h2 _ H8 _ Hh') => H1.\n  have H10 : fresh_wpAssrt x L by Max_inf_resolve.\n  move: (IHL _ H10 s h' x v) => X; apply X => //.\n  by rewrite mem_seq1.\n- red; simpl; split; intros; rewrite mem_seq1 in H0; move/eqP in H0; subst x0.\n    case : H1 => H2 H3.\n    split.\n    intros.\n    have H4 : fresh_wpAssrt x L1 by Max_inf_resolve.\n    move: (IHL1 _ H4 s h x v) => H5; apply H5 => //.\n    by rewrite mem_seq1.\n    apply H2.\n    have H7 : fresh_b x e by Max_inf_resolve.\n    move: (fresh_b_inde e x true H7 s h x v) => X.\n    apply X => //.\n    by rewrite mem_seq1.\n    have H4 : fresh_wpAssrt x L2 by Max_inf_resolve.\n    move: (IHL2 _ H4 s h x v) => H5 H6.\n    apply H5 => //.\n    by rewrite mem_seq1.\n    apply H3.\n    have H7 : fresh_b x e by Max_inf_resolve.\n    move: (fresh_b_inde e x false H7 s h x v) => X.\n    apply/negbT/X.\n    by rewrite mem_seq1.\n    by apply/negbTE.\n  case : H1 => H2 H3.\n  split.\n  intros.\n  have H4 : fresh_wpAssrt x L1 by Max_inf_resolve.\n  move: (IHL1 _ H4 s h x v) => H5.\n  apply H5 => //.\n  by rewrite mem_seq1.\n  apply H2.\n  have H7 : fresh_b x e by Max_inf_resolve.\n  move: (fresh_b_inde e x true H7 s h x v) => H6; apply H6 => //.\n  by rewrite mem_seq1.\n  intros.\n  have H4 : fresh_wpAssrt x L2 by Max_inf_resolve.\n  move: (IHL2 _ H4 s h x v) => H5.\n  apply H5.\n  by rewrite mem_seq1.\n  apply H3.\n  have H7 : fresh_b x e by Max_inf_resolve.\n  move: (fresh_b_inde e x false H7 s h x v) => X.\n  apply/negbT/X => //.\n  by rewrite mem_seq1.\n  by apply/negbTE.\nQed.\n\nEnd Fresh.\n\nImport Fresh.\n\n(** replace a substitution (e/x) by two substitutions (x/x')(e/x') with x' fresh *)\nLemma intro_fresh_var : forall l x x' e s h L,\n  fresh_lst x' l -> fresh_wpAssrt x' L -> fresh_e x' (var_e x) ->\n  wp_assigns\n  l (fun s' h' => wpAssrt_interp L (store.upd x (eval (var_e x') s') s') h') (store.upd x' (eval e s) s) h ->\n  wp_assigns\n  l (fun s' h' => wpAssrt_interp L (store.upd x (eval e s) s') h') s h.\nProof.\nintros.\napply intro_fresh_var' with x' => //.\nby apply fresh_wpAssrt_inde.\nQed.\n\nDefinition triple_fresh (P : assrt) (L : wpAssrt) (x : var.v) : Prop := fresh_assrt x P /\\ fresh_wpAssrt x L.\n\n(** weakest pre-condition generator and its soudness *)\n\nFixpoint wp_frag (Q: option wpAssrt) (c: @while.cmd cmd0 expr_b) {struct c}: option wpAssrt :=\n  match c with\n    | skip => match Q with\n                | None => None\n                | Some Q' => Some Q'\n              end\n    | assign v e => match Q with\n                      | None => None\n                      | Some Q' => Some (wpSubst ((v, e) :: nil) Q')\n                    end\n    | lookup v e => match Q with\n                      | None => None\n                      | Some Q' => Some (wpLookup v e Q')\n\t\t    end\n    | mutation e1 e2 => match Q with\n                          | None => None\n                          | Some Q' => Some (wpMutation e1 e2 Q')\n\t\t\tend\n    | while.seq c1 c2 => wp_frag (wp_frag Q c2) c1\n    | while.ifte b c1 c2 => match wp_frag Q c1 with\n                                      | None => None\n                                      | Some Q1 => match (wp_frag Q c2) with\n                                                     None => None\n                                                     | Some Q2 => Some (wpIf b Q1 Q2)\n                                                   end\n                                    end\n    | while.while a c => None\n    | malloc v e => None\n    | free e => None\n  end.\n\nLemma wp_frag_None_is_None : forall c, wp_frag None c = None.\nProof. elim=> //; first by case. by move=> c H c' /= ->. by move=> e c /= ->. Qed.\n\nLemma wp_frag_soudness : forall c Q Q',\n  wp_frag (Some Q) c = Some Q' -> {{ wpAssrt_interp Q' }} c {{ wpAssrt_interp Q }}.\nProof.\ninduction c => //=.\n- induction c => //=; intros.\n  + case: H => H; subst Q'.\n    by apply while.hoare_hoare0, hoare0_skip.\n  + case : H => H /=; subst Q'.\n    by apply while.hoare_hoare0, hoare0_assign.\n  + case : H => H /=; subst Q'.\n    by apply hoare_lookup_back.\n  + case : H => H /=; subst Q'.\n    by apply hoare_mutation_backwards.\n- intros.\n  have H0 : (exists v, wp_frag (Some Q) c2 = Some v) \\/ wp_frag (Some Q) c2 = None.\n    elim wp_frag.\n    intros; left; exists a.\n    auto.\n    by right.\n  inversion_clear H0.\n  + inversion_clear H1.\n    rewrite H0 in H.\n    apply while.hoare_seq with (wpAssrt_interp x).\n    by apply IHc1.\n    by apply IHc2.\n  + rewrite H1 in H.\n    rewrite wp_frag_None_is_None in H.\n    by inversion H.\n- move=> Q Q' H.\n  have [H1 | H1] : (exists v, wp_frag (Some Q) c1 = Some v) \\/ wp_frag (Some Q) c1 = None.\n    elim wp_frag.\n    intros; left; by exists a.\n    by right.\n  + case: H1 => x H0.\n    rewrite H0 in H.\n    have [H2 | H2] : (exists v, wp_frag (Some Q) c2 = Some v) \\/ wp_frag (Some Q) c2 = None.\n      elim wp_frag.\n      intros; left; by exists a.\n      by right.\n    * case : H2 => x0 H1.\n      rewrite H1 in H.\n      case : H => H; subst Q'.\n      apply while.hoare_ifte.\n      - apply hoare_prop_m.hoare_stren with (wpAssrt_interp x).\n        red => /=; tauto.\n        by apply IHc1.\n      - apply hoare_prop_m.hoare_stren with (wpAssrt_interp x0).\n        red => /=; tauto.\n        by apply IHc2.\n    * by rewrite H2 in H.\n  + by rewrite H1 in H.\nQed.\n\nLocal Open Scope entail_scope.\n\nInductive tritra : assrt -> wpAssrt -> Prop :=\n  | tritra_incons : forall pi sig Q,\n    (forall s h, (assrt_interp (pi, sig) s h) -> False) ->\n    tritra (pi, sig) Q\n\n  | tritra_entail : forall P Q,\n    assrt_interp P ===> Assrt_interp Q ->\n    tritra P (wpElt Q)\n\n  | tritra_precond_stre : forall L1 L1' L2,\n    assrt_interp L1 ===> assrt_interp L1' ->\n    tritra L1' L2 ->\n    tritra L1 L2\n\n  | tritra_if : forall pi1 sig1 L1 L2 b,\n    tritra (pi1 \\&& b, sig1)  L1 ->\n    tritra (pi1 \\&& (neg_b b), sig1) L2 ->\n    tritra (pi1, sig1) (wpIf b L1 L2)\n\n  | tritra_mutation : forall pi1 sig1 e1 e2 e3 e4 L,\n    (forall s, [ pi1 ]b_ s -> [ e1 \\= e3 ]b_ s ) ->\n    tritra (pi1, sig1 \\** singl e1 e4) L ->\n    tritra (pi1, sig1 \\** singl e1 e2) (wpMutation e3 e4 L)\n\n  | tritra_mutation' : forall pi1 sig1 e1 e3 e4 L,\n    (forall s, [ pi1 ]b_ s -> [ e1 \\= e3 ]b_ s ) ->\n    tritra (pi1, sig1 \\** singl e1 e4) L ->\n    tritra (pi1, sig1 \\** cell e1) (wpMutation e3 e4 L)\n\n  | tritra_lookup : forall pi1 sig1 e1 e2 e x L,\n    (forall s, [ pi1 ]b_ s -> eval_b (e1 \\= e) s ) ->\n    tritra (pi1, sig1 \\** singl e1 e2) (wpSubst ((x, e2) :: nil) L) ->\n    tritra (pi1, sig1 \\** singl e1 e2) (wpLookup x e L)\n\n  | tritra_lookup' : forall pi1 sig1 e1 e x L x',\n    (forall s, eval_b pi1 s -> [ e1 \\= e ]b_ s ) ->\n    fresh_assrt x' (pi1, sig1 \\** cell e1) ->\n    fresh_wpAssrt x' (wpLookup x e L) ->\n    tritra (pi1, sig1 \\** (singl e1 (var_e x'))) (wpSubst ((x,var_e x')::nil) L) ->\n    tritra (pi1, sig1 \\** cell e1) (wpLookup x e L)\n\n  | tritra_subst_elt : forall pi1 sig1 l L,\n    tritra (pi1, sig1) (wpElt (subst_Assrt_lst l L)) ->\n    tritra (pi1, sig1) (wpSubst l (wpElt L))\n\n  | tritra_subst_subst : forall pi1 sig1 l1 l2 L,\n    tritra (pi1, sig1) (wpSubst (l2 ++ l1) L) ->\n    tritra (pi1, sig1) (wpSubst l1 (wpSubst l2 L))\n\n  | tritra_subst_lookup : forall pi1 sig1 e1 e2 e x x' l L,\n    (forall s, eval_b pi1 s -> [ e1 \\= subst_e_lst l e ]b_ s ) ->\n    fresh_lst x' l ->\n    fresh_wpAssrt x' L ->\n    fresh_e x' (var_e x) ->\n    tritra (pi1, sig1 \\** singl e1 e2) (wpSubst ((x, var_e x') :: l ++ ((x', e2) :: nil)) L) ->\n    tritra (pi1, sig1 \\** singl e1 e2) (wpSubst l (wpLookup x e L))\n\n  | tritra_subst_lookup' : forall pi1 sig1 e1 e x x' l L x'',\n    (forall s, eval_b pi1 s -> [ e1 \\= subst_e_lst l e ]b_ s ) ->\n    fresh_lst x' l ->\n    fresh_wpAssrt x' L ->\n    fresh_e x' (var_e x) ->\n    fresh_wpAssrt x'' (wpSubst l (wpLookup x e L)) ->\n    fresh_assrt x'' (pi1, sig1 \\** cell e1) ->\n    tritra (pi1, sig1 \\** singl e1 (var_e x'')) (wpSubst ((x, var_e x') :: l ++ ((x', var_e x'')::nil)) L) ->\n    tritra (pi1, sig1 \\** cell e1) (wpSubst l (wpLookup x e L))\n\n  | tritra_subst_mutation : forall pi1 sig1 e1 e2 l L,\n    tritra (pi1, sig1) (wpMutation (subst_e_lst l e1) (subst_e_lst l e2) (wpSubst l L)) ->\n    tritra (pi1, sig1) (wpSubst l (wpMutation e1 e2 L))\n\n  | tritra_subst_if : forall pi1 sig1 l b L1 L2,\n    tritra (pi1, sig1) (wpIf (subst_b_lst l b) (wpSubst l L1) (wpSubst l L2)) ->\n    tritra (pi1, sig1) (wpSubst l (wpIf b L1 L2))\n\n  (* regle generale pour prouver de maniere plus simple les 4 du dessous *)\n\n  | tritra_destruct_lst : forall pi1 sig1 e1 e2 L x',\n    (forall s, [ pi1 ]b_ s -> [ e1 \\!= e2 ]b_ s ) ->\n    fresh_assrt x' (pi1, sig1 \\** lst e1 e2) ->\n    fresh_wpAssrt x' L ->\n    tritra (pi1 \\&& e1 \\!= var_e x' \\&& var_e x' \\= nat_e 0,\n      sig1 \\** ((singl e1 (var_e x') \\** (cell (e1 \\+ nat_e 1))) \\** (lst (var_e x') e2))) L ->\n    tritra (pi1 \\&& e1 \\!= var_e x' \\&& var_e x' \\!= nat_e 0,\n      sig1 \\** ((singl e1 (var_e x') \\** cell (e1 \\+ nat_e 1)) \\** lst (var_e x') e2)) L ->\n    tritra (pi1, sig1 \\** lst e1 e2) L.\n\nLocal Close Scope entail_scope.\n\nLemma tritra_soundness P Q : tritra P Q -> assrt_interp P ===> wpAssrt_interp Q.\nProof.\ninduction 1.\n- rewrite /while.entails => s h; by move/H.\n- rewrite /=; exact H.\n- by apply (hoare_prop_m.entails_trans _ _ _ H IHtritra).\n- rewrite /while.entails /= in IHtritra1 IHtritra2 *; intros.\n  split=> [X|H2].\n  + apply IHtritra1; by rewrite X andbC.\n  + apply IHtritra2; split; [by rewrite (proj1 H1) /= H2 | exact (proj2 H1)].\n- rewrite /while.entails /= => s h [pi1_true H3].\n  case_sepcon H3.\n  case : H3_h2 => H3_h2 H3_h2'.\n  exists e2.\n  move: {H}(H _ pi1_true) => H.\n  Compose_sepcon h2 h1.\n  by Mapsto.\n  rewrite /imp => h2' [X1 X2] h' Hh'.\n  apply IHtritra.\n  split; first by exact pi1_true.\n  Compose_sepcon h1 h2'; first by [].\n  split; [by Mapsto | exact H3_h2'].\n- rewrite /while.entails /= in IHtritra * => s h [pi1_true H3].\n  case_sepcon H3.\n  move: {H}(H _ pi1_true) => e1_e3.\n  case : H3_h2 => [ [ v Hv] H3_h2].\n  exists (cst_e v).\n  Compose_sepcon h2 h1.\n  by Mapsto.\n  rewrite /imp => h2' [X1 X2] h' Hh'.\n  apply IHtritra; split; first by exact pi1_true.\n  Compose_sepcon h1 h2'; first by assumption.\n  split; [by Mapsto | exact H3_h2].\n- rewrite /while.entails /= in IHtritra * => s h [H2 H3].\n  move: {H}(H _ H2) => H.\n  case_sepcon H3.\n  case : H3_h2 => H3_h2 H3_h2'.\n  exists e2.\n  Compose_sepcon h2 h1.\n  by Mapsto.\n  rewrite /imp => h2' [X1 X2] h' Hh'.\n  apply IHtritra; split; first by [].\n  Compose_sepcon h1 h2'; first by [].\n  split; [by Mapsto | exact H3_h2'].\n- rewrite /while.entails /= => s h [H4 H5].\n  rewrite /while.entails in IHtritra.\n  case_sepcon H5.\n  case : H5_h2 => [ [x0 H5_h2] H5_h2'].\n  have H7 : assrt_interp (pi1, star sig1 (singl e1 (var_e x'))) (store.upd x' x0 s) h.\n    rewrite /=.\n    split.\n    + have Hx' : fresh_b x' pi1 by Max_inf_resolve.\n      have : x' \\in x'::nil by rewrite mem_seq1.\n      case/(fresh_b_inde pi1 _ true Hx' s h x' x0) => X _; by apply X.\n    + Compose_sepcon h1 h2.\n      have Hx' : fresh_Sigma x' sig1 by Max_inf_resolve.\n      have : x' \\in x' :: nil by rewrite mem_seq1.\n      case/(var_max_Sigma_inde sig1 _ Hx' s h1 x' x0)=> X _; by apply X.\n      have Hx' : fresh_e x' e1 by Max_inf_resolve.\n      split.\n      Mapsto; by rewrite fresh_e_eval.\n      by rewrite fresh_e_eval.\n  move: (IHtritra _ _ H7) => /= H10.\n  exists (cst_e (eval (var_e x') (store.upd x' x0 s))) => /=.\n  Store_upd.\n  Compose_sepcon h2 h1.\n  + move: (H s H4) => H3; by Mapsto.\n  + rewrite /imp => h' [X1 X2] h'' Hh''.\n    rewrite /wp_assign /= in H10 *.\n    rewrite store.get_upd' store.upd_upd in H10.\n    have Hx' : fresh_wpAssrt x' L by Max_inf_resolve.\n    have H12 : x' \\in x' :: nil by rewrite mem_seq1.\n    apply (proj2 (fresh_wpAssrt_inde L _ Hx' (store.upd x x0 s) h'' x' x0 H12)).\n    have ? : h' = h2.\n      apply (singl_equal _ _ _ _ _ _ _ X2 H5_h2) => //.\n      move: (H s H4) => ?; by omegab.\n    subst h'.\n    by rewrite (_ : h'' = h); last by map_tac_m.Equal.\n    by Max_inf_resolve.\n- (* case tritra_subst_elt *) eapply hoare_prop_m.entails_trans; first by apply IHtritra.\n  move=> s h; by move/ wp_assigns_Assrt_interp.\n- (* case tritra_subst_subst *) rewrite /while.entails /= in IHtritra * => s h.\n  move/IHtritra. by move/wp_assigns_app.\n- (* case tritra_subst_lookup *) rewrite /while.entails /= in IHtritra * => s h [H7 H8].\n  move: {IHtritra}(IHtritra _ _ (conj H7 H8)) => IHtritra.\n  case_sepcon H8.\n  case : H8_h2 => H8_h2 H8_h2'.\n  apply (wp_assigns_exists l\n    (fun e0 s h => (e |~> e0 ** (e |~> e0 -* wp_assign x e0 (wpAssrt_interp L))) s h)\n    s h).\n  exists (cst_e (eval e2 s)).\n  have -> : (fun s0 h0 =>\n    (e |~> cst_e (eval e2 s) ** (e |~> cst_e (eval e2 s) -* wp_assign x (cst_e (eval e2 s)) (wpAssrt_interp L))) s0 h0)\n    =\n    (e |~> cst_e (eval e2 s) ** (e |~> cst_e (eval e2 s) -* wp_assign x (cst_e (eval e2 s)) (wpAssrt_interp L))).\n    apply assert_m.assert_ext.\n    by intuition.\n  apply wp_assigns_sepcon.\n  move: (H _  H7) => H6.\n  Compose_sepcon h2 h1.\n  + apply wp_assigns_mapsto.\n    Mapsto.\n    by rewrite subst_e_lst_cst_e.\n  + apply wp_assigns_sepimp.\n    rewrite /imp => h2' [X1 X2] h' Hh'.\n    rewrite /wp_assign /=.\n    have ? : h2 = h2'.\n      apply (singl_equal _ _ _ _ _ _ _ H8_h2 (wp_assigns_mapsto_inv _ _ _ _ _ X2)).\n      by omegab.\n      by rewrite subst_e_lst_cst_e.\n    subst h2'.\n    have <- : h = h' by map_tac_m.Equal.\n    move/wp_assigns' : IHtritra => IHtritra.\n    by apply intro_fresh_var with x'.\n- (** case tritra_subst_lookup' *) rewrite /while.entails in IHtritra * => s h [H7 H8].\n  rewrite /= in H8; case_sepcon H8.\n  case : H8_h2 => [ [x0 H8_h2] H8_h2'].\n  have H10 : assrt_interp (pi1, star sig1 (singl e1 (var_e x''))) (store.upd x'' x0 s) h.\n    simpl.\n    split.\n    have H10 : fresh_b x'' pi1 by Max_inf_resolve.\n    have H13 : x'' \\in x'' :: nil by rewrite mem_seq1.\n    by rewrite <- (fresh_b_inde pi1 x'' true H10 s h x'' x0 H13).\n    Compose_sepcon h1 h2.\n    have H10 : fresh_Sigma x'' sig1 by Max_inf_resolve.\n    have H13 : x'' \\in x'' :: nil by rewrite mem_seq1.\n    by rewrite <- (var_max_Sigma_inde sig1 x'' H10 s h1 x'' x0 H13).\n    have H10 : fresh_e x'' e1 by Max_inf_resolve.\n    have H123 : In x'' (x''::nil) by left.\n    split.\n    Mapsto; by rewrite fresh_e_eval.\n    by rewrite fresh_e_eval.\n  move/IHtritra : H10 => H13.\n  cut (wpAssrt_interp (wpSubst l (wpLookup x e L)) (store.upd x'' x0 s) h).\n    move=> H10.\n    have H14 : x'' \\in x'' :: nil by rewrite mem_seq1.\n    by rewrite -> (fresh_wpAssrt_inde (wpSubst l (wpLookup x e L)) x'' H3 s h x'' x0 H14).\n  simpl.\n  apply (wp_assigns_exists l\n    (fun e0 s h => (e |~> e0 ** (e |~> e0 -* wp_assign x e0 (wpAssrt_interp L))) s h)\n    (store.upd x'' x0 s) h).\n  exists (cst_e x0).\n  have -> : (fun s0 h0 =>\n      (e |~> cst_e x0 ** (e |~> cst_e x0 -* wp_assign x (cst_e x0) (wpAssrt_interp L))) s0 h0)\n    =\n      (e |~> cst_e x0 ** (e |~> cst_e x0 -* wp_assign x (cst_e x0) (wpAssrt_interp L))).\n    apply assert_m.assert_ext.\n    by intuition.\n  apply wp_assigns_sepcon.\n  Compose_sepcon h2 h1.\n  have H10 : inde (x''::nil) (e |~> cst_e x0).\n    rewrite /inde; intros.\n    rewrite mem_seq1 in H6; move/eqP in H6; subst x1.\n    split; intros; Mapsto.\n    rewrite fresh_e_eval //; by Max_inf_resolve.\n    rewrite fresh_e_eval //; by Max_inf_resolve.\n  have H14 : fresh_lst x'' l by Max_inf_resolve.\n  have H15 : x'' \\in x'' :: nil by rewrite mem_seq1.\n  apply (proj1 (fresh_lst_inde l (e |~> cst_e x0) x'' H10 H14 s h2 x'' x0 H15)).\n  apply wp_assigns_mapsto.\n  move: (H s H7) => H16.\n  Mapsto; by rewrite subst_e_lst_cst_e.\n  apply wp_assigns_sepimp.\n  rewrite /imp => h2' [X1 X2] h' Hh'.\n  rewrite /wp_assign /=.\n  have ? : h2 = h2'.\n    have H16 : (e1 |~> cst_e x0) (store.upd x'' x0 s) h2.\n      Mapsto.\n      rewrite fresh_e_eval //; by Max_inf_resolve.\n    apply (singl_equal _ _ _ _ _ _ _ H16 (wp_assigns_mapsto_inv _ _ _ _ _ X2)).\n    rewrite fresh_e_eval; last by Max_inf_resolve.\n    rewrite subst_e_lst_eval; last 2 first.\n      by Max_inf_resolve.\n      by Max_inf_resolve.\n    generalize (H s H7) => ?; by omegab.\n    by rewrite subst_e_lst_cst_e.\n  subst h2'.\n  have <- : h = h' by map_tac_m.Equal.\n  rewrite /= in H13.\n  move/wp_assigns' : H13 => H15.\n  rewrite /wp_assign /= store.get_upd' in H15.\n  suff : wp_assigns l\n    (fun s0 h0 => wpAssrt_interp L (store.upd x ([ cst_e x0 ]e_ (store.upd x'' x0 s)) s0) h0)\n    (store.upd x'' x0 s) h by [].\n  by apply intro_fresh_var with x'.\n- (** case tritra_subst_mutation *) rewrite /while.entails /= in IHtritra * => s h.\n  move/IHtritra. by apply wp_assigns_lookup.\n- (** case tritra_subst_if *) rewrite /while.entails /= in IHtritra * => s h.\n  case/IHtritra => H2 H3.\n  apply (wp_assigns_and l\n    (fun s h => [ b ]b_ s  -> wpAssrt_interp L1 s h)\n    (fun s h => ~~ [ b ]b_ s -> wpAssrt_interp L2 s h) s h).\n  split.\n  apply (wp_assigns_imp l (fun s h => eval_b b s) (fun s h => wpAssrt_interp L1 s h) s h) => H0.\n  move: (H2 (wp_assigns_subst_b_lst true _ _ _ _ H0)) => H4.\n  suff <- : wpAssrt_interp L1 = (fun s => fun h => wpAssrt_interp L1 s h) by [].\n  apply assert_m.assert_ext; rewrite /while.equiv /=; tauto.\n  apply (wp_assigns_imp l (fun s h => ~~ eval_b b s) (fun s h => wpAssrt_interp L2 s h) s h) => H0.\n  move: (H3 (wp_assigns_subst_b_lst false _ _ _ _ H0)) => H4.\n  suff <- : wpAssrt_interp L2 = (fun s => fun h => wpAssrt_interp L2 s h) by [].\n  apply assert_m.assert_ext; rewrite /while.equiv /=; tauto.\n- (** case regle generale *) rewrite /while.entails /= => s h {H2 H3} [H2 H3].\n  case_sepcon H3.\n  destruct H3_h2.\n    move: (H _ H2) => H5; by omegab.\n  case/boolP : (eval e2 s == 0%Z) => [/eqP X1|X1].\n  + rewrite /assrt_interp /= in IHtritra1.\n    cut (wpAssrt_interp L (store.upd x' (eval e2 s) s) h).\n      move=> H13.\n      have H14 : x' \\in x' :: nil by rewrite mem_seq1.\n      by apply (proj2 (fresh_wpAssrt_inde L x' H1 s h x' (eval e2 s) H14)).\n    apply IHtritra1; split.\n    have H13 : fresh_b x' pi1 by Max_inf_resolve.\n    have H14 : x' \\in x' :: nil by rewrite mem_seq1.\n    apply/andP; split.\n    apply/andP; split.\n    by apply (proj1 (fresh_b_inde pi1 x' true H13 s h x' (eval e2 s) H14)).\n    rewrite fresh_e_eval; last by Max_inf_resolve.\n    rewrite store.get_upd'.\n    have H15 : eval e1 s <> eval e2 s.\n      destruct H3_h2.\n      rewrite X1 //.\n      case_sepcon H8.\n      case_sepcon H16.\n      apply (singl_disj_neq _ _ _ _ _ _ _ H8_h21 H16_h41); by map_tac_m.Disj.\n    exact/eqP.\n    Store_upd.\n    by rewrite X1; apply/eqP.\n    Compose_sepcon h1 h0.\n    * have H13 : fresh_Sigma x' sig1 by Max_inf_resolve.\n      have H14 : x' \\in x' :: nil by rewrite mem_seq1.\n      by apply (proj1 (var_max_Sigma_inde sig1 _ H13 s h1 x' (eval e2 s) H14)).\n    * Compose_sepcon h2 h3.\n      - case_sepcon H8.\n        Compose_sepcon h21 h22.\n        + split.\n          * Mapsto; rewrite fresh_e_eval //; by Max_inf_resolve.\n          * rewrite fresh_e_eval //; by Max_inf_resolve.\n        + split.\n          * exists (eval e4 s).\n            Mapsto; rewrite fresh_e_eval //; by Max_inf_resolve.\n          * rewrite fresh_e_eval //; by Max_inf_resolve.\n        apply (Lst_equiv' _ _ _ _ H3_h2).\n        rewrite /=; by Store_upd.\n        rewrite fresh_e_eval //; by Max_inf_resolve.\n  + rewrite /while.entails /= in IHtritra2.\n    cut (wpAssrt_interp L (store.upd x' ([ e2 ]e_ s) s) h).\n      move=> H13.\n      have H14 : x' \\in x' :: nil by rewrite mem_seq1.\n      by apply (proj2 (fresh_wpAssrt_inde L x' H1 s h x' (eval e2 s) H14)).\n    apply IHtritra2; split.\n    have H13 : fresh_b x' pi1 by Max_inf_resolve.\n    have H14 : x' \\in x' :: nil by rewrite mem_seq1.\n    apply/andP; split.\n    apply/andP; split.\n    by apply (proj1 (fresh_b_inde pi1 x' true H13 s h x' (eval e2 s) H14)).\n    rewrite fresh_e_eval; last by Max_inf_resolve.\n    rewrite store.get_upd'.\n    have H15 : eval e1 s <> eval e2 s.\n      destruct H3_h2.\n      by rewrite H9.\n      case_sepcon H8.\n      case_sepcon H16.\n      apply (singl_disj_neq _ _ _ _ _ _ _ H8_h21 H16_h41); by map_tac_m.Disj.\n    exact/eqP.\n    rewrite store.get_upd' //.\n    Compose_sepcon h1 h0.\n    have H13 : fresh_Sigma x' sig1 by Max_inf_resolve.\n    have H14 : x' \\in x' :: nil by rewrite mem_seq1.\n    by apply (proj1 (var_max_Sigma_inde sig1 _ H13 s h1 x' (eval e2 s) H14)).\n    Compose_sepcon h2 h3.\n    * case_sepcon H8.\n      Compose_sepcon h21 h22.\n      - split.\n        + Mapsto; rewrite fresh_e_eval //; by Max_inf_resolve.\n        + rewrite fresh_e_eval //; by Max_inf_resolve.\n      - split.\n        + exists (eval e4 s).\n          Mapsto; rewrite fresh_e_eval //; by Max_inf_resolve.\n        + rewrite fresh_e_eval //; by Max_inf_resolve.\n    * apply (Lst_equiv' _ _ _ _ H3_h2).\n      by rewrite /= store.get_upd'.\n      rewrite fresh_e_eval //; by Max_inf_resolve.\nQed.\n\nDefinition triple_vfresh (a : assrt) (L : wpAssrt) := (max (var_max_assrt a) (var_max_wpAssrt L)) + 1.\n\nLemma tritra_lookup_lst pi1 sig1 e1 e2 e x L x' :\n  (forall s, eval_b pi1 s -> (eval_b (e1 \\= e) s /\\ eval_b (e1 \\!= e2) s)) ->\n  x' = triple_vfresh  (pi1, star sig1 (lst e1 e2)) (wpLookup x e L) ->\n  tritra (pi1 \\&& e1 \\!= var_e x' \\&& var_e x' \\= nat_e 0,\n    star (star sig1 (star (lst (var_e x') e2) (cell (e1 \\+ nat_e 1)))) (singl e1 (var_e x'))) (wpLookup x e L) ->\n  tritra (pi1 \\&& e1 \\!= var_e x' \\&& var_e x' \\!= nat_e 0,\n    star (star sig1 (star (lst (var_e x') e2) (cell (e1 \\+ nat_e 1)))) (singl e1 (var_e x'))) (wpLookup x e L) ->\n  tritra (pi1, star sig1 (lst e1 e2)) (wpLookup x e L).\nProof.\nmove=> H H0 H1 H2.\nunfold triple_vfresh in H0.\napply tritra_destruct_lst with (x' := x').\n- move=> s; by case/H.\n- rewrite /fresh_assrt.\n  subst x'.\n  simpl.\n  by Resolve_le_max.\n- rewrite /fresh_wpAssrt.\n  subst x'.\n  simpl.\n  by Resolve_le_max.\n- eapply tritra_precond_stre; [idtac | by apply H1].\n  rewrite /while.entails => s h [H4 H5].\n  split; first by [].\n  simpl in H5; case_sepcon H5.\n  case_sepcon H5_h2.\n  case_sepcon H5_h2_h21.\n  simpl.\n  Compose_sepcon (h212 \\U h22 \\U h1) h211; auto.\n  Compose_sepcon h1 (h212 \\U h22); auto.\n  by Compose_sepcon h22 h212.\n- eapply tritra_precond_stre; [idtac | by apply H2].\n  rewrite /while.entails => s h [H4 H5].\n  split; first by [].\n  simpl in H5.\n  case_sepcon H5.\n  case_sepcon H5_h2.\n  case_sepcon H5_h2_h21.\n  simpl.\n  Compose_sepcon (h212 \\U h22 \\U h1) h211; last by [].\n  Compose_sepcon h1 (h212 \\U h22); first by [].\n  by Compose_sepcon h22 h212.\nQed.\n\nLemma tritra_lookup_lst' : forall pi1 sig1 e1 e2 e x L x',\n  (forall s, eval_b pi1 s -> (eval_b (e1 \\+ nat_e 1 \\= e) s  /\\ [ e1 \\!= e2 ]b_ s )) ->\n  x' = triple_vfresh  (pi1, star sig1 (lst e1 e2)) (wpLookup x e L) ->\n  tritra (pi1 \\&& e1 \\!= var_e x' \\&& (var_e x' \\= nat_e 0),\n    star (star sig1 (star (lst (var_e x') e2) (cell (e1 \\+ nat_e 1)))) (singl e1 (var_e x'))) (wpLookup x e L) ->\n  tritra (pi1 \\&& (e1 \\!= var_e x') \\&& (var_e x' \\!= nat_e 0),\n    star (star sig1 (star (lst (var_e x') e2) (cell (e1 \\+ nat_e 1)))) (singl e1 (var_e x'))) (wpLookup x e L) ->\n  tritra (pi1, star sig1 (lst e1 e2)) (wpLookup x e L).\nProof.\nintros.\nunfold triple_vfresh in H0.\napply tritra_destruct_lst with (x' := x').\n- move=> s; by case/H.\n- rewrite /fresh_assrt.\n  subst x'.\n  simpl.\n  by Resolve_le_max.\n- rewrite /fresh_wpAssrt.\n  subst x'.\n  simpl.\n  by Resolve_le_max.\n- eapply tritra_precond_stre; last by apply H1.\n  rewrite /while.entails => s h [H4 H5].\n  split; first by [].\n  simpl in H5.\n  case_sepcon H5.\n  case_sepcon H5_h2.\n  case_sepcon H5_h2_h21.\n  simpl.\n  Compose_sepcon (h212 \\U h22 \\U h1) h211; auto.\n  Compose_sepcon h1 (h212 \\U h22); auto.\n  by Compose_sepcon h22 h212.\n- eapply tritra_precond_stre; [idtac | by apply H2].\n  rewrite /while.entails => s h [H4 H5].\n  split; auto.\n  simpl in H5.\n  case_sepcon H5.\n  case_sepcon H5_h2.\n  case_sepcon H5_h2_h21.\n  simpl.\n  Compose_sepcon (h212 \\U h22 \\U h1) h211; last by [].\n  Compose_sepcon h1 (h212 \\U h22); first by [].\n  by Compose_sepcon h22 h212.\nQed.\n\nLocal Open Scope entail_scope.\n\nLemma tritra_subst_lookup_lst : forall pi1 sig1 e1 e2 e x L l x',\n  (forall s, eval_b pi1 s  -> (eval_b (e1 \\= (subst_e_lst l e)) s /\\ [ e1 \\!= e2 ]b_ s )) ->\n  x' = triple_vfresh  (pi1, star sig1 (lst e1 e2)) (wpSubst l (wpLookup x e L)) ->\n  tritra (pi1 \\&& e1 \\!= var_e x' \\&& var_e x' \\= nat_e 0,\n    (star sig1 (star (lst (var_e x') e2) (cell (e1 \\+ nat_e 1)))) \\** singl e1 (var_e x')) (wpSubst l (wpLookup x e L)) ->\n  tritra (pi1 \\&& e1 \\!= var_e x' \\&& var_e x' \\!= nat_e 0,\n    (star sig1 (star (lst (var_e x') e2) (cell (e1 \\+ nat_e 1)))) \\** singl e1 (var_e x')) (wpSubst l (wpLookup x e L)) ->\n  tritra (pi1, star sig1 (lst e1 e2)) (wpSubst l (wpLookup x e L)).\nProof.\nintros.\nunfold triple_vfresh in H0.\neapply tritra_destruct_lst with (x' := x').\n- move=> s; by case/H.\n- rewrite /fresh_assrt.\n  subst x'.\n  simpl.\n  by Resolve_le_max.\n- rewrite /fresh_wpAssrt.\n  subst x'.\n  simpl.\n  by Resolve_le_max.\n- eapply tritra_precond_stre; [idtac | by apply H1].\n  rewrite /while.entails => s h [H4 H5].\n  split; first by [].\n  simpl in H5.\n  case_sepcon H5.\n  case_sepcon H5_h2.\n  case_sepcon H5_h2_h21.\n  simpl.\n  Compose_sepcon (h212 \\U h22 \\U h1) h211; last by [].\n  Compose_sepcon h1 (h212 \\U h22); first by [].\n  by Compose_sepcon h22 h212.\n- eapply tritra_precond_stre; [idtac | by apply H2].\n  rewrite /while.entails => s h [H4 H5].\n  split; first by [].\n  simpl in H5.\n  case_sepcon H5.\n  case_sepcon H5_h2.\n  case_sepcon H5_h2_h21.\n  simpl.\n  Compose_sepcon (h212 \\U h22 \\U h1) h211; last by [].\n  Compose_sepcon h1 (h212 \\U h22); first by [].\n  by Compose_sepcon h22 h212.\nQed.\n\nLemma tritra_subst_lookup_lst' : forall pi1 sig1 e1 e2 e x L l x',\n  (forall s, eval_b pi1 s -> eval_b (e1 \\+ nat_e 1 \\= (subst_e_lst l e)) s /\\ eval_b (e1 \\!= e2) s ) ->\n  x' = triple_vfresh  (pi1,star sig1 (lst e1 e2)) (wpSubst l (wpLookup x e L)) ->\n  tritra (pi1 \\&& e1 \\!= var_e x' \\&& var_e x' \\= nat_e 0,\n    star (star sig1 (star (lst (var_e x') e2) (singl e1 (var_e x')))) (cell (e1 \\+ nat_e 1))) (wpSubst l (wpLookup x e L)) ->\n  tritra (pi1 \\&& (e1 \\!= var_e x') \\&& (var_e x' \\!= nat_e 0),\n    star (star sig1 (star (lst (var_e x') e2) (singl e1 (var_e x')))) (cell (e1 \\+ nat_e 1))) (wpSubst l (wpLookup x e L)) ->\n  tritra (pi1,star sig1 (lst e1 e2)) (wpSubst l (wpLookup x e L)).\nProof.\nintros.\nunfold triple_vfresh in H0.\napply tritra_destruct_lst with (x' := x').\n- move=> s; by case/H.\n- rewrite /fresh_assrt.\n  subst x'.\n  simpl.\n  by Resolve_le_max.\n- rewrite /fresh_wpAssrt.\n  subst x'.\n  simpl.\n  by Resolve_le_max.\n- eapply tritra_precond_stre; [idtac | by apply H1].\n  rewrite /while.entails => s h [H4 H5].\n  split; first by [].\n  simpl in H5.\n  case_sepcon H5.\n  case_sepcon H5_h2.\n  case_sepcon H5_h2_h21.\n  simpl.\n  Compose_sepcon (h211 \\U h22 \\U h1) h212; last by [].\n  Compose_sepcon h1 (h211 \\U h22); first by [].\n  by Compose_sepcon h22 h211.\n- eapply tritra_precond_stre; [idtac | by apply H2].\n  rewrite /while.entails => s h [H4 H5].\n  split; first by [].\n  simpl in H5.\n  case_sepcon H5.\n  case_sepcon H5_h2.\n  case_sepcon H5_h2_h21.\n  simpl.\n  Compose_sepcon (h211 \\U h22 \\U h1) h212; last by [].\n  Compose_sepcon h1 (h211 \\U h22); first by [].\n  by Compose_sepcon h22 h211.\nQed.\n\nLemma tritra_mutation_lst : forall pi1 sig1 e1 e2 e3 e4 L x',\n  (forall s, eval_b pi1 s -> (eval_b (e1 \\= e3) s  /\\ eval_b (e1 \\!= e2) s )) ->\n  x' = triple_vfresh (pi1, star sig1 (lst e1 e2)) (wpMutation e3 e4 L) ->\n  tritra (pi1 \\&& (e1 \\!= var_e x') \\&& (var_e x' \\= nat_e 0),\n    star (star sig1 (star (lst (var_e x') e2) (cell (e1 \\+ nat_e 1)))) (singl e1 (var_e x'))) (wpMutation e3 e4 L) ->\n  tritra (pi1 \\&& (e1 \\!= var_e x') \\&& (var_e x' \\!= nat_e 0),\n    star (star sig1 (star (lst (var_e x') e2) (cell (e1 \\+ nat_e 1)))) (singl e1 (var_e x'))) (wpMutation e3 e4 L) ->\n  tritra (pi1,star sig1 (lst e1 e2)) (wpMutation e3 e4 L).\nProof.\nintros.\nunfold triple_vfresh in H0.\napply tritra_destruct_lst with (x' := x').\n- move=> s; by case/H.\n- rewrite /fresh_assrt.\n  subst x'.\n  simpl.\n  by Resolve_le_max.\n- rewrite /fresh_wpAssrt.\n  subst x'.\n  simpl.\n  by Resolve_le_max.\n- eapply tritra_precond_stre; [idtac | by apply H1].\n  rewrite /while.entails => s h [H4 H5].\n  split; auto.\n  simpl in H5.\n  case_sepcon H5.\n  case_sepcon H5_h2.\n  case_sepcon H5_h2_h21.\n  simpl.\n  Compose_sepcon (h212 \\U h22 \\U h1) h211; auto.\n  Compose_sepcon h1 (h212 \\U h22); auto.\n  by Compose_sepcon h22 h212.\n- eapply tritra_precond_stre; last by apply H2.\n  rewrite /while.entails => s h [H4 H5].\n  split; first by [].\n  simpl in H5.\n  case_sepcon H5.\n  case_sepcon H5_h2.\n  case_sepcon H5_h2_h21.\n  simpl.\n  Compose_sepcon (h212 \\U h22 \\U h1) h211; auto.\n  Compose_sepcon h1 (h212 \\U h22); auto.\n  by Compose_sepcon h22 h212.\nQed.\n\nLemma tritra_mutation_lst' : forall pi1 sig1 e1 e2 e3 e4 L x',\n  (forall s, eval_b pi1 s -> (eval_b (e1 \\+ nat_e 1 \\= e3) s /\\ eval_b (e1 \\!= e2) s )) ->\n  x' = triple_vfresh (pi1, star sig1 (lst e1 e2)) (wpMutation e3 e4 L) ->\n  tritra (pi1 \\&& e1 \\!= var_e x' \\&& var_e x' \\= nat_e 0,\n    star (star sig1 (star (lst (var_e x') e2) (singl e1 (var_e x')))) (cell (e1 \\+ nat_e 1))) (wpMutation e3 e4 L) ->\n  tritra (pi1 \\&& (e1 \\!= var_e x') \\&& (var_e x' \\!= nat_e 0),\n    star (star sig1 (star (lst (var_e x') e2) (singl e1 (var_e x')))) (cell (e1 \\+ nat_e 1))) (wpMutation e3 e4 L) ->\n  tritra (pi1, star sig1 (lst e1 e2)) (wpMutation e3 e4 L).\nProof.\nintros.\nunfold triple_vfresh in H0.\napply tritra_destruct_lst with (x' := x').\n- move=> s; by case/H.\n- rewrite /fresh_assrt.\n  subst x'.\n  simpl.\n  by Resolve_le_max.\n- rewrite /fresh_wpAssrt.\n  subst x'.\n  simpl.\n  by Resolve_le_max.\n- eapply tritra_precond_stre; [idtac | by apply H1].\n  rewrite /while.entails => s h [H4 H5].\n  split; auto.\n  simpl in H5.\n  case_sepcon H5.\n  case_sepcon H5_h2.\n  case_sepcon H5_h2_h21.\n  simpl.\n  Compose_sepcon (h211 \\U h22 \\U h1) h212; auto.\n  Compose_sepcon h1 (h211 \\U h22); auto.\n  by Compose_sepcon h22 h211.\n- eapply tritra_precond_stre; [idtac | by apply H2].\n  rewrite /while.entails => s h [H4 H5].\n  split; auto.\n  simpl in H5.\n  case_sepcon H5.\n  case_sepcon H5_h2.\n  case_sepcon H5_h2_h21.\n  simpl.\n  Compose_sepcon (h211 \\U h22 \\U h1) h212; last by [].\n  Compose_sepcon h1 (h211 \\U h22); first by [].\n  by Compose_sepcon h22 h211.\nQed.\n\nLemma tritra_subst_mutation_lst : forall pi1 sig1 e1 e2 e3 e4 L l x',\n  (forall s, eval_b pi1 s  -> (eval_b (e1 \\= (subst_e_lst l e3)) s  /\\ eval_b (e1 \\!= e2) s )) ->\n  x' = triple_vfresh (pi1,star sig1 (lst e1 e2)) (wpSubst l (wpMutation e3 e4 L))->\n  tritra (pi1 \\&& (e1 \\!= var_e x') \\&& (var_e x' \\= nat_e 0),\n    star (star sig1 (star (lst (var_e x') e2) (cell (e1 \\+ nat_e 1)))) (singl e1 (var_e x'))) (wpSubst l (wpMutation e3 e4 L)) ->\n  tritra (pi1 \\&& (e1 \\!= var_e x') \\&& (var_e x' \\!= nat_e 0),\n    star (star sig1 (star (lst (var_e x') e2) (cell (e1 \\+ nat_e 1)))) (singl e1 (var_e x'))) (wpSubst l (wpMutation e3 e4 L)) ->\n  tritra (pi1,star sig1 (lst e1 e2)) (wpSubst l (wpMutation e3 e4 L)).\nProof.\nintros.\nunfold triple_vfresh in H0.\napply tritra_destruct_lst with (x' := x').\n- move=> s; by case/H.\n- rewrite /fresh_assrt.\n  subst x'.\n  simpl.\n  by Resolve_le_max.\n- rewrite /fresh_wpAssrt.\n  subst x'.\n  simpl.\n  by Resolve_le_max.\n- eapply tritra_precond_stre; last by apply H1.\n  rewrite /while.entails => s h [H4 H5].\n  split; auto.\n  simpl in H5.\n  case_sepcon H5.\n  case_sepcon H5_h2.\n  case_sepcon H5_h2_h21.\n  simpl.\n  Compose_sepcon (h212 \\U h22 \\U h1) h211; auto.\n  Compose_sepcon h1 (h212 \\U h22); auto.\n  by Compose_sepcon h22 h212.\n- eapply tritra_precond_stre; last by apply H2.\n  rewrite /while.entails => s h [H4 H5].\n  split; auto.\n  simpl in H5.\n  case_sepcon H5.\n  case_sepcon H5_h2.\n  case_sepcon H5_h2_h21.\n  simpl.\n  Compose_sepcon (h212 \\U h22 \\U h1) h211; auto.\n  Compose_sepcon h1 (h212 \\U h22); auto.\n  by Compose_sepcon h22 h212.\nQed.\n\nLemma tritra_subst_mutation_lst' : forall pi1 sig1 e1 e2 e3 e4 L l x',\n  (forall s, eval_b pi1 s -> (eval_b ((e1 \\+ nat_e 1) \\= (subst_e_lst l e3)) s  /\\ eval_b (e1 \\!= e2) s )) ->\n  x' = triple_vfresh (pi1,star sig1 (lst e1 e2)) (wpSubst l (wpMutation e3 e4 L)) ->\n  tritra (pi1 \\&& (e1 \\!= var_e x')  \\&& (var_e x' \\= nat_e 0),\n    star (star sig1 (star (lst (var_e x') e2) (singl e1 (var_e x')))) (cell (e1 \\+ nat_e 1))) (wpSubst l (wpMutation e3 e4 L)) ->\n  tritra (pi1 \\&& (e1 \\!= var_e x')  \\&& (var_e x' \\!= nat_e 0),\n    star (star sig1 (star (lst (var_e x') e2) (singl e1 (var_e x')))) (cell (e1 \\+ nat_e 1))) (wpSubst l (wpMutation e3 e4 L)) ->\n  tritra (pi1,star sig1 (lst e1 e2)) (wpSubst l (wpMutation e3 e4 L)).\nProof.\nintros.\nunfold triple_vfresh in H0.\napply tritra_destruct_lst with (x' := x').\n- move=> s; by case/H.\n- rewrite /fresh_assrt.\n  subst x'.\n  simpl.\n  by Resolve_le_max.\n- rewrite /fresh_wpAssrt.\n  subst x'.\n  simpl.\n  by Resolve_le_max.\n- eapply tritra_precond_stre; [idtac | by apply H1].\n  rewrite /while.entails => s h [H4 H5].\n  split; auto.\n  simpl in H5.\n  case_sepcon H5.\n  case_sepcon H5_h2.\n  case_sepcon H5_h2_h21.\n  simpl.\n  Compose_sepcon (h211 \\U h22 \\U h1) h212; auto.\n  Compose_sepcon h1 (h211 \\U h22); auto.\n  by Compose_sepcon h22 h211.\n- eapply tritra_precond_stre; [idtac | by apply H2].\n  rewrite /while.entails => s h [H4 H5].\n  split; auto.\n  simpl in H5.\n  case_sepcon H5.\n  case_sepcon H5_h2.\n  case_sepcon H5_h2_h21.\n  simpl.\n  Compose_sepcon (h211 \\U h22 \\U h1) h212; auto.\n  Compose_sepcon h1 (h211 \\U h22); auto.\n  by Compose_sepcon h22 h211.\nQed.\n\n(** Tactics to resolve tritra goals *)\n\n(** Resolution tactic *)\n\nLemma tritra_use: forall c P Q R, wp_frag (Some (wpElt Q)) c = Some R ->\n  tritra P R -> {{ assrt_interp P }} c {{ Assrt_interp Q }}.\nProof.\nmove=> c P Q R.\nmove/wp_frag_soudness => /= H1 H0.\napply hoare_prop_m.hoare_stren with (wpAssrt_interp R); [by apply tritra_soundness | done].\nQed.\n\n(** the following lemma replaces the constructor tritra_subst_lookup in the tactic,\n  the difference is that it introduces a way to compute fresh variables *)\nLemma tritra_subst_lookup2 : forall pi1 sig1 e1 e2 e x x' l L,\n  (forall s, eval_b pi1 s -> (eval_b (e1 \\= (subst_e_lst l e))) s) ->\n  x' = triple_vfresh (pi1,star sig1 (singl e1 e2)) (wpSubst l (wpLookup x e L)) ->\n  tritra (pi1,star sig1 (singl e1 e2)) (wpSubst ((x,(var_e x'))::l ++ ((x',e2)::nil)) L) ->\n  tritra (pi1,star sig1 (singl e1 e2)) (wpSubst l (wpLookup x e L)).\nProof.\nintros.\nunfold triple_vfresh in H0.\napply tritra_subst_lookup with x'.\nexact H.\nrewrite /fresh_lst H0 /=; by Resolve_le_max.\nrewrite /fresh_wpAssrt H0 /=; by Resolve_le_max.\nrewrite /fresh_e H0 /= /max_lst /max_list /=.\nby Resolve_le_max.\nassumption.\nQed.\n\nLtac Rotate_tritra_sig_lhs :=\n  match goal with\n    | |- tritra (?pi,?sig) ?L' =>\n      eapply tritra_precond_stre with (\n        (pi, remove_empty_heap pi (star_assoc_left (star_com sig) frag_list_entail.emp))\n      ); [apply entail_soundness; simpl; Entail| simpl]\n  end.\n\nLemma Decompose_Assrt_interp : forall a hd tl,\n  (assrt_interp a ===> assrt_interp hd) \\/ (assrt_interp a ===> Assrt_interp tl) ->\n  (assrt_interp a ===> Assrt_interp (hd :: tl)).\nProof.\nrewrite /while.entails /=; intros; by intuition.\nQed.\n\nLtac Resolve_entails :=\n  eapply Decompose_Assrt_interp; ((left; apply entail_soundness; Entail) || (right; Resolve_entails)).\n\nLtac tritra_resolve :=\n  match goal with\n    | |- tritra (?pi1, ?sig1) ?L => eapply tritra_entail; Resolve_entails\n\n    | |- tritra (?pi1, star ?sig1 (singl ?e1 ?e2)) (wpMutation ?e3 ?e4 ?L') =>\n      (apply tritra_mutation; [(do 2 intro; omegab) | tritra_resolve] || Rotate_tritra_sig_lhs; idtac)\n\n    | |- tritra (?pi1, star ?sig1 (cell ?e1)) (wpMutation ?e3 ?e4 ?L') =>\n      (eapply tritra_mutation'; [(do 2 intro; omegab) | tritra_resolve] || Rotate_tritra_sig_lhs; idtac)\n\n    | |- tritra (?pi1, star ?sig1 (singl ?e1 ?e2)) (wpLookup ?x ?e ?L') =>\n      (apply tritra_lookup; [(do 2 intro; omegab) | tritra_resolve] || Rotate_tritra_sig_lhs; idtac)\n\n    | |- tritra ?L (wpSubst ?l (wpElt ?L')) => eapply tritra_subst_elt; simpl; idtac\n    | |- tritra ?L (wpSubst ?l (wpSubst ?l' ?L')) => eapply tritra_subst_subst; simpl; idtac\n\n    | |- tritra ?L (wpSubst ?l (wpLookup ?x ?e ?L')) =>\n      (eapply tritra_subst_lookup2;\n        [(do 2 intro; omegab) | simpl; intuition | tritra_resolve] ||\n         Rotate_tritra_sig_lhs; idtac)\n\n    | |- tritra ?L (wpSubst ?l (wpMutation ?e1 ?e2 ?L')) => eapply tritra_subst_mutation; simpl; idtac\n    | |- tritra ?L (wpSubst ?l (wpIf ?b ?L1 ?L2)) => eapply tritra_subst_if; simpl; idtac\n    | |- tritra ?L (wpIf ?b ?L1 ?L2) => eapply tritra_if; simpl; idtac\n  end.\n\nLtac Tritra := Rotate_tritra_sig_lhs; repeat tritra_resolve.\n\n(** pi,sig is the pre-condition\n   A is the current post-condition\n   the result is a list of pre/post-conditions left to be proved *)\nDefinition tritra_step' (pi : expr_b) (sig : Sigma) (A : wpAssrt) : option (list ((expr_b * Sigma) * wpAssrt)) :=\n  match A with\n    | wpElt L =>\n      match entail_fun (pi, sig) L nil with\n        | Good => Some nil\n        | Error _ => None\n      end\n    | wpSubst l L =>\n      match L with\n        | wpElt L' => Some (((pi, sig), wpElt (subst_Assrt_lst l L')) :: nil)\n        | wpSubst l' L' => Some (((pi, sig), wpSubst (l' ++ l) L') :: nil)\n        | wpLookup x e L' =>\n          match sig with\n            | star s1 (singl e1 e2) =>\n              if expr_b_dp (pi =b> (e1 \\= subst_e_lst l e)) then\n                let x' := (max (max (var_max_lst l) (var_max_wpAssrt L')) x) + 1 in\n                  Some (((pi, sig), wpSubst ((x, var_e x') :: l ++ ((x', e2) :: nil)) L') :: nil)\n                else\n                  Some (((pi, remove_empty_heap pi (star_assoc_left (star_com sig) frag_list_entail.emp)), A) :: nil)\n            | star s1 (cell e1) =>\n              if expr_b_dp (pi =b> (e1 \\= subst_e_lst l e)) then\n                let x' := (max (max (var_max_lst l) (var_max_wpAssrt L')) x) + 1 in\n                  let x'' := (max (var_max_assrt (pi,sig)) (var_max_wpAssrt A)) + 1 in\n                    Some (((pi, star s1 (singl e1 (var_e x''))), wpSubst ((x, var_e x')::l ++ ((x', var_e x'') :: nil)) L')::nil)\n                else\n                  Some (((pi, remove_empty_heap pi (star_assoc_left (star_com sig) frag_list_entail.emp)),A)::nil)\n            | star s1 (lst e1 e2) =>\n              if expr_b_dp (pi =b> ((e1 \\!= e2) \\&& (e1 \\= subst_e_lst l e))) then\n                let x' := triple_vfresh (pi,sig) A in\n                  Some ((pi \\&& (e1 \\!= var_e x') \\&& (var_e x' \\= nat_e 0),\n                    star (star s1 (star (lst (var_e x') e2) (cell (e1 \\+ nat_e 1)))) (singl e1 (var_e x')), A)::\n                      (pi \\&& (e1 \\!= var_e x') \\&& (var_e x' \\!= nat_e 0),\n                        star (star s1 (star (lst (var_e x') e2) (cell (e1 \\+ nat_e 1)))) (singl e1 (var_e x')), A)::\n                      nil)\n                else\n              if expr_b_dp (pi =b> ((e1 \\!= e2) \\&& ((e1 \\+ nat_e 1) \\= subst_e_lst l e))) then\n                let x' := triple_vfresh (pi,sig) A in\n                  Some (\n                       (((pi \\&& (e1 \\!= var_e x')) \\&& (var_e x' \\= nat_e 0),\n                       star (star s1 (star (lst (var_e x') e2) (singl e1 (var_e x'))))\n                       (cell (e1 \\+ nat_e 1))), A)::\n                       (((pi \\&& (e1 \\!= var_e x')) \\&& (var_e x' \\!= nat_e 0),\n                       star (star s1 (star (lst (var_e x') e2) (singl e1 (var_e x'))))\n                       (cell (e1 \\+ nat_e 1))), A)::\n                      nil)\n                else\n                  Some (((pi, remove_empty_heap pi (star_assoc_left (star_com sig) frag_list_entail.emp)), A)::nil)\n            | (singl e1 e2) => Some ((pi, star frag_list_entail.emp sig, A)::nil)\n            | (cell e1) => Some ((pi, star frag_list_entail.emp sig, A)::nil)\n            | (lst e1 e2) => Some ((pi, star frag_list_entail.emp sig, A)::nil)\n            | _ => Some (((pi, remove_empty_heap pi (star_assoc_left (star_com sig) frag_list_entail.emp)), A)::nil)\n          end\n        | wpMutation e1 e2 L' =>\n          Some (((pi,sig), wpMutation (subst_e_lst l e1) (subst_e_lst l e2) (wpSubst l L'))::nil)\n        | wpIf b L1 L2 =>\n          Some (((pi,sig), wpIf (subst_b_lst l b) (wpSubst l L1) (wpSubst l L2))::nil)\n      end\n    (* *)\n    | wpIf b L1 L2 => Some (((pi \\&& b, sig), L1) :: ((pi \\&& (\\~ b), sig), L2) :: nil)\n    (* *)\n    | wpLookup x e L =>\n      match sig with\n        | star s1 (singl e1 e2) =>\n          if expr_b_dp (pi =b> (e1 \\= e)) then\n            Some (((pi, sig), wpSubst ((x, e2) :: nil) L) :: nil)\n            else\n              Some (((pi, remove_empty_heap pi (star_assoc_left (star_com sig) frag_list_entail.emp)), A) :: nil)\n        | star s1 (cell e1) =>\n          if expr_b_dp (pi =b> (e1 \\= e)) then\n            let x' := (max (var_max_assrt (pi, sig)) (var_max_wpAssrt A)) + 1 in\n               Some (((pi, star s1 (singl e1 (var_e x'))), wpSubst ((x, var_e x') :: nil) L) :: nil)\n            else\n              Some (((pi, remove_empty_heap pi (star_assoc_left (star_com sig) frag_list_entail.emp)), A) :: nil)\n        | star s1 (lst e1 e2) =>\n          if expr_b_dp (pi =b> ((e1 \\!= e2) \\&& (e1 \\= e))) then\n            let x' := triple_vfresh (pi,sig) A in\n              Some (((pi \\&& (e1 \\!= var_e x') \\&& (var_e x' \\= nat_e 0),\n                star (star s1 (star (lst (var_e x') e2) (cell (e1 \\+ nat_e 1)))) (singl e1 (var_e x'))), A) ::\n              ((pi \\&& (e1 \\!= var_e x') \\&& (var_e x' \\!= nat_e 0),\n                star (star s1 (star (lst (var_e x') e2) (cell (e1 \\+ nat_e 1)))) (singl e1 (var_e x'))), A) ::\n                  nil)\n            else\n          if expr_b_dp (pi =b> ((e1 \\!= e2) \\&& ((e1 \\+ nat_e 1) \\= e))) then\n            let x' := triple_vfresh (pi,sig) A in\n              Some (((pi \\&& (e1 \\!= var_e x') \\&& (var_e x' \\= nat_e 0),\n                star (star s1 (star (lst (var_e x') e2) (cell (e1 \\+ nat_e 1)))) (singl e1 (var_e x'))), A)::\n                  ((pi \\&& (e1 \\!= var_e x') \\&& (var_e x' \\!= nat_e 0),\n                    star (star s1 (star (lst (var_e x') e2) (cell (e1 \\+ nat_e 1)))) (singl e1 (var_e x'))), A)::\n                  nil)\n            else Some (((pi, remove_empty_heap pi (star_assoc_left (star_com sig) frag_list_entail.emp)),A)::nil)\n        | (singl e1 e2) => Some ((pi, star frag_list_entail.emp sig, A)::nil)\n        | (cell e1) => Some ((pi, star frag_list_entail.emp sig, A)::nil)\n        | (lst e1 e2) => Some ((pi, star frag_list_entail.emp sig, A)::nil)\n        | _ => Some (((pi, remove_empty_heap pi (star_assoc_left (star_com sig) frag_list_entail.emp)), A)::nil)\n      end\n      (**)\n    | wpMutation e1 e2 L =>\n      match sig with\n        | star s1 (cell e3) =>\n          if expr_b_dp (pi =b> (e1 \\= e3)) then\n            Some (((pi, star s1 (singl e3 e2)),L)::nil)\n            else\n              Some (((pi, remove_empty_heap pi (star_assoc_left (star_com sig) frag_list_entail.emp)), A)::nil)\n        | star s1 (singl e3 e4) =>\n          if expr_b_dp (pi =b> (e1 \\= e3)) then\n            Some (((pi, star s1 (singl e3 e2)), L) :: nil)\n            else\n              Some (((pi, remove_empty_heap pi (star_assoc_left (star_com sig) frag_list_entail.emp)), A)::nil)\n        | star s1 (lst e3 e4) =>\n              if expr_b_dp (pi =b> ((e1 \\= e3) \\&& (e3 \\!= e4))) then\n                let x' := triple_vfresh (pi,sig) A in\n                  Some (\n                  (((pi \\&& (e3 \\!= var_e x')) \\&& (var_e x' \\= nat_e 0),\n                  star (star s1 (star (lst (var_e x') e4) (cell (e3 \\+ nat_e 1))))\n                  (singl e3 (var_e x'))), A)::\n                  (((pi \\&& (e3 \\!= var_e x')) \\&& (var_e x' \\!= nat_e 0),\n                  star (star s1 (star (lst (var_e x') e4) (cell (e3 \\+ nat_e 1))))\n                  (singl e3 (var_e x'))),A)::\n                  nil)\n                else if expr_b_dp (pi =b> (((e3 \\+ (nat_e 1)) \\= e1) \\&& (e3 \\!= e4))) then\n                  let x' := triple_vfresh (pi,sig) A in\n                    Some (\n                    (((pi \\&& (e3 \\!= var_e x')) \\&& (var_e x' \\= nat_e 0),\n                    star (star s1 (star (lst (var_e x') e4) (singl e3 (var_e x'))))\n                    (cell (e3 \\+ nat_e 1))), A)::\n                    (((pi \\&& (e3 \\!= var_e x')) \\&& (var_e x' \\!= nat_e 0),\n                    star (star s1 (star (lst (var_e x') e4) (singl e3 (var_e x'))))\n                    (cell (e3 \\+ nat_e 1))), A)::\n                    nil)\n                else Some (((pi, remove_empty_heap pi (star_assoc_left (star_com sig) frag_list_entail.emp)), A)::nil)\n        | (singl e1 e2) => Some ((pi, star frag_list_entail.emp sig, A)::nil)\n        | (cell e1) => Some ((pi, star frag_list_entail.emp sig, A)::nil)\n        | (lst e1 e2) => Some ((pi, star frag_list_entail.emp sig, A)::nil)\n        | _ => Some (((pi, remove_empty_heap pi (star_assoc_left (star_com sig) frag_list_entail.emp)), A)::nil)\n      end\n\n  end.\n\nOpaque entail_fun.\nOpaque remove_empty_heap.\nOpaque star_assoc_left.\n\nLemma tritra_step'_correct : forall A pi sig l,\n  tritra_step' pi sig A = Some l ->\n  (forall pi' sig' A', In ((pi', sig'), A') l -> tritra (pi', sig') A') ->\n  tritra (pi, sig) A.\nProof.\ndestruct A; simpl; intros.\n- (* wpElt *) generalize (entail_fun_correct a (pi, sig) nil); intros.\n  destruct (entail_fun (pi, sig) a nil); try discriminate.\n  injection H; clear H; intros; subst l.\n  eapply tritra_entail.\n  by apply H1; auto.\n- (* wpSubst *) destruct A.\n  + (* wpElt *) injection H; clear H; intros; subst l0.\n    eapply tritra_subst_elt.\n    eapply H0; simpl; left; auto.\n  + (* wpSubst *)injection H; clear H; intros; subst l0.\n    eapply tritra_subst_subst.\n    eapply H0; simpl; left; auto.\n  + (* wpLookup *) destruct sig.\n    * eapply tritra_precond_stre with\n        (pi, star frag_list_entail.emp (singl e0 e1)).\n      eapply entail_soundness; Entail.\n      eapply H0.\n      injection H; intros; subst l0.\n      simpl; left; auto.\n    * eapply tritra_precond_stre with\n        (pi, star frag_list_entail.emp (cell e0)).\n      eapply entail_soundness; Entail.\n      eapply H0.\n      injection H; intros; subst l0.\n      simpl; left; auto.\n    * apply tritra_precond_stre with (pi,\n        remove_empty_heap pi (star_assoc_left (star_com frag_list_entail.emp) frag_list_entail.emp)).\n      done.\n      apply H0.\n      case : H => H; subst l0.\n      by left.\n    * destruct sig2.\n      - move: (expr_b_dp_correct (pi =b> e0 \\= subst_e_lst l e)) => H1.\n        destruct (expr_b_dp (pi =b> e0 \\= subst_e_lst l e)).\n        case: H => ?; subst l0.\n        apply tritra_subst_lookup with (x' := (max (max (var_max_lst l) (var_max_wpAssrt A)) s + 1)).\n        move=> s0 H; move: (H1 (refl_equal _) s0) => H2; by omegab.\n        rewrite /fresh_lst /=; by Resolve_le_max.\n        rewrite /fresh_wpAssrt /=; by Resolve_le_max.\n        rewrite /fresh_e /= /max_lst /max_list /=; by Resolve_le_max.\n        apply H0; by left.\n        clear H1.\n        apply tritra_precond_stre with (pi,\n          remove_empty_heap pi (star_assoc_left (star_com (star sig1 (singl e0 e1))) frag_list_entail.emp)).\n        rewrite /while.entails => s0 h [H2 H3].\n        split; first by [].\n        apply remove_empty_heap_correct' => //.\n        apply star_assoc_left_correct'.\n        Compose_sepcon h assert_m.heap.emp; last by [].\n        by apply star_com_correct'.\n        apply H0.\n        case: H => ?; subst l0.\n        by left.\n      - move: (expr_b_dp_correct (pi =b> e0 \\= subst_e_lst l e)) => H1.\n        destruct (expr_b_dp (pi =b> e0 \\= subst_e_lst l e)).\n        + case : H => ?; subst l0.\n          apply tritra_subst_lookup' with (x' := (max (max (var_max_lst l) (var_max_wpAssrt A)) s + 1)) (x'' := (max\n            (max (max_lst (vars_b pi))\n              (var_max_Sigma (star sig1 (cell e0))))\n            (max (var_max_lst l) (var_max_wpAssrt (wpLookup s e A))) +\n            1)).\n          intros; move: (H1 (refl_equal _) s0) => H2; by omegab.\n          rewrite /fresh_lst /=; by Resolve_le_max.\n          rewrite /fresh_wpAssrt /=; by Resolve_le_max.\n          rewrite /fresh_e /= /max_lst /max_list /=; by Resolve_le_max.\n          rewrite /fresh_wpAssrt /=; by Resolve_le_max.\n          rewrite /fresh_assrt /=; by Resolve_le_max.\n          apply H0 => /=; by left.\n        + clear H1.\n          apply tritra_precond_stre with (pi,\n            remove_empty_heap pi(star_assoc_left (star_com (star sig1 (cell e0))) frag_list_entail.emp)).\n          rewrite /while.entails => s0 h [H2 H3].\n          split; auto.\n          apply remove_empty_heap_correct' => //.\n          apply star_assoc_left_correct'.\n          Compose_sepcon h assert_m.heap.emp; last by [].\n          by apply star_com_correct'.\n          apply H0.\n          case : H => ?; subst l0.\n          by left.\n      - apply tritra_precond_stre with (pi,\n        remove_empty_heap pi (star_assoc_left (star_com (star sig1 frag_list_entail.emp)) frag_list_entail.emp)).\n        + rewrite /while.entails => s0 h [H2 H3].\n          split; auto.\n          apply remove_empty_heap_correct' => //.\n          apply star_assoc_left_correct'.\n          Compose_sepcon h assert_m.heap.emp; last by [].\n          by apply star_com_correct'.\n        + apply H0.\n          case : H => ?; subst l0.\n          by left.\n      - apply tritra_precond_stre with (pi,\n        remove_empty_heap pi (star_assoc_left (star_com (star sig1 (star sig2_1 sig2_2))) frag_list_entail.emp)).\n        + rewrite /while.entails => s0 h [H2 H3].\n          split; auto.\n          apply remove_empty_heap_correct' => //.\n          apply star_assoc_left_correct'.\n          Compose_sepcon h assert_m.heap.emp; last by [].\n          by apply star_com_correct'.\n        + apply H0.\n          case : H => ?; subst l0.\n          by left.\n      - move: (expr_b_dp_correct (pi =b> (e0 \\!= e1) \\&& (e0 \\= subst_e_lst l e))) => H1.\n        destruct (expr_b_dp (pi =b> (e0 \\!= e1) \\&& (e0 \\= subst_e_lst l e))).\n        + eapply tritra_subst_lookup_lst with (x' :=\n            triple_vfresh (pi, star sig1 (lst e0 e1)) (wpSubst l (wpLookup s e A))).\n          intros; generalize (H1 (refl_equal _) s0); intros.\n          split; by omegab.\n          reflexivity.\n          apply H0.\n          case : H => ?; subst l0.\n          rewrite /=; by left.\n          apply H0.\n          case : H => ?; subst l0.\n          rewrite /=; by right; left.\n        + move: (expr_b_dp_correct (pi =b> (e0 \\!= e1) \\&& ((e0 \\+ nat_e 1) \\= subst_e_lst l e))) => {}H1.\n          destruct (expr_b_dp (pi =b> (e0 \\!= e1) \\&& ((e0 \\+ nat_e 1) \\= subst_e_lst l e))); try discriminate.\n          * apply tritra_subst_lookup_lst' with (x' :=\n              triple_vfresh (pi, star sig1 (lst e0 e1)) (wpSubst l (wpLookup s e A))).\n            intros; move: (H1 (refl_equal _) s0) => H3; split; by omegab.\n            reflexivity.\n            apply H0.\n            case : H => ?; subst l0.\n            rewrite /=; by left.\n            apply H0.\n            case : H => ?; subst l0.\n            rewrite /=; by right; left.\n          * clear H1.\n            apply tritra_precond_stre with (pi,\n              remove_empty_heap pi (star_assoc_left (star_com (star sig1 (lst e0 e1))) frag_list_entail.emp)).\n            - rewrite /while.entails => s0 h [H2 H3].\n              split; auto.\n              apply remove_empty_heap_correct' => //.\n              apply star_assoc_left_correct'.\n              Compose_sepcon h assert_m.heap.emp; last by [].\n              by apply star_com_correct'.\n            - apply H0.\n              case : H => ?; subst l0.\n              by left.\n    * apply tritra_precond_stre with (pi, star frag_list_entail.emp (lst e0 e1)).\n      apply entail_soundness; by Entail.\n      case: H => ?; subst l0.\n      apply H0; by left.\n  + (* wpMutation *)apply tritra_subst_mutation.\n    case: H => ?; subst l0.\n    apply H0 => /=; by left.\n  + (* wpIf *) apply tritra_subst_if.\n    case: H => ?; subst l0.\n    apply H0 => /=; by left.\n- (* wpLookup *) destruct sig.\n  + eapply tritra_precond_stre with\n      (pi, star frag_list_entail.emp (singl e0 e1)).\n    eapply entail_soundness; Entail.\n    eapply H0.\n    injection H; intros; subst l.\n    simpl; by left.\n  + eapply tritra_precond_stre with\n      (pi, star frag_list_entail.emp (cell e0)).\n    eapply entail_soundness; Entail.\n    eapply H0.\n    injection H; intros; subst l.\n    by left.\n  + simpl in H.\n    eapply tritra_precond_stre with (pi,\n      remove_empty_heap pi (star_assoc_left frag_list_entail.emp frag_list_entail.emp)).\n    rewrite /while.entails => s0 h [H2 H3].\n    split; auto.\n    apply H0.\n    case : H => H; subst l.\n    by left.\n  + destruct sig2.\n    * move: (expr_b_dp_correct (pi =b> (e0 \\= e))) => H1.\n      destruct (expr_b_dp (pi =b> (e0 \\= e))).\n      - apply tritra_lookup.\n        move=> s0 H2; move: (H1 (refl_equal _) s0) => H3.\n        by omegab.\n        apply H0.\n        case: H => ?; subst l.\n        rewrite /=; by left.\n      - clear H1.\n        apply tritra_precond_stre with (pi,\n          remove_empty_heap pi (star_assoc_left (star_com (star sig1 (singl e0 e1))) frag_list_entail.emp)).\n       rewrite /while.entails => s0 h [H2 h3]; split; first by [].\n       apply remove_empty_heap_correct' => //.\n       apply star_assoc_left_correct'.\n       Compose_sepcon h assert_m.heap.emp; last by [].\n       by apply star_com_correct'.\n       apply H0.\n       case: H => ?; subst l.\n       by left.\n    * move: (expr_b_dp_correct (pi =b> e0 \\= e)) => H1.\n      destruct (expr_b_dp (pi =b> e0 \\= e)).\n      - case: H => ?; subst l.\n        apply tritra_lookup' with (max (max (max_lst (vars_b pi))\n            (max (var_max_Sigma sig1) (max_lst (vars e0))))\n          (max (max s (max_lst (vars e))) (var_max_wpAssrt A)) + 1).\n        move=> s0 H; move: (H1 (refl_equal _) s0) => H2; by omegab.\n        rewrite /fresh_assrt /=; by Resolve_le_max.\n        rewrite /fresh_wpAssrt /=; by Resolve_le_max.\n        apply H0 => /=; by left.\n      - clear H1.\n        apply tritra_precond_stre with (pi,\n          remove_empty_heap pi (star_assoc_left (star_com (star sig1 (cell e0))) frag_list_entail.emp)).\n        rewrite /while.entails => s0 h [H2 H3].\n        split; first by [].\n        apply remove_empty_heap_correct' => //.\n        apply star_assoc_left_correct'.\n        Compose_sepcon h assert_m.heap.emp; last by [].\n        by apply star_com_correct'.\n        case: H => ?; subst l.\n        apply H0; by left.\n    * apply tritra_precond_stre with (pi,\n       remove_empty_heap pi (star_assoc_left (star_com (star sig1 frag_list_entail.emp)) frag_list_entail.emp)).\n      rewrite /while.entails => s0 h [H2 H3].\n      split; first by [].\n      apply remove_empty_heap_correct' => //.\n      apply star_assoc_left_correct'.\n      Compose_sepcon h assert_m.heap.emp; last by [].\n      by apply star_com_correct'.\n      case: H => ?; subst l.\n      apply H0; by left.\n    * apply tritra_precond_stre with (pi,\n        remove_empty_heap pi (star_assoc_left (star_com (star sig1 (star sig2_1 sig2_2))) frag_list_entail.emp)).\n      rewrite /while.entails => s0 h [H2 H3].\n      split; first by [].\n      apply remove_empty_heap_correct' => //.\n      apply star_assoc_left_correct'.\n      Compose_sepcon h assert_m.heap.emp; last by [].\n      by apply star_com_correct'.\n      case : H => ?; subst l.\n      apply H0; by left.\n    * move: (expr_b_dp_correct (pi =b> (e0 \\!= e1) \\&& (e0 \\= e))) => H1.\n      destruct (expr_b_dp (pi =b> (e0 \\!= e1) \\&& (e0 \\= e))).\n      - case: H => ?; subst l.\n        eapply tritra_lookup_lst.\n        move=> s0 H2; move: (H1 (refl_equal _) s0) => H3.\n        split; by omegab.\n        reflexivity.\n        apply H0 => /=; by left.\n        apply H0 => /=; by right; left.\n      - move: (expr_b_dp_correct (pi =b> (e0 \\!= e1) \\&& ((e0 \\+ nat_e 1) \\= e))) => {}H1.\n        destruct (expr_b_dp (pi =b> (e0 \\!= e1) \\&& ((e0 \\+ nat_e 1) \\= e))).\n        + case: H => ?; subst l.\n          eapply tritra_lookup_lst'.\n          move=> s0 H2; move: (H1 (refl_equal _) s0) => H3.\n          split; by omegab.\n          reflexivity.\n          apply H0 => /=; by left.\n          apply H0 => /=; by right; left.\n        + clear H1.\n          apply tritra_precond_stre with (pi,\n            remove_empty_heap pi (star_assoc_left (star_com (star sig1 (lst e0 e1))) frag_list_entail.emp)).\n          rewrite /while.entails => s0 h [H2 H3].\n          split; first by [].\n          apply remove_empty_heap_correct' => //.\n          apply star_assoc_left_correct'.\n          Compose_sepcon h assert_m.heap.emp; last by [].\n          by apply star_com_correct'.\n          case: H => ?; subst l.\n          apply H0; by left.\n  + apply tritra_precond_stre with (pi, star frag_list_entail.emp (lst e0 e1)).\n    * apply entail_soundness; by Entail.\n    * case : H => ?; subst l.\n      apply H0; by left.\n- (* wpMutation *) destruct sig.\n  + apply tritra_precond_stre with (pi, star frag_list_entail.emp (singl e1 e2)).\n    eapply entail_soundness; by Entail.\n    case : H => ?; subst l.\n    apply H0; by left.\n  + eapply tritra_precond_stre with (pi, star frag_list_entail.emp (cell e1)).\n    eapply entail_soundness; by Entail.\n    case : H => ?; subst l.\n    apply H0; by left.\n  + apply tritra_precond_stre with (pi,\n      remove_empty_heap pi (star_assoc_left (star_com frag_list_entail.emp) frag_list_entail.emp)) => //.\n    case : H => ?; subst l.\n    apply H0; by left.\n  + destruct sig2.\n    * move: (expr_b_dp_correct (pi =b> (e \\= e1))) => H1.\n      destruct (expr_b_dp (pi =b> (e \\= e1))).\n      - apply tritra_mutation.\n        move=> s H2; move: (H1 (refl_equal _) s) => H3.\n        have : [ e \\= e1 ]b_s by omegab.\n        move/eqP => H4.\n        exact/eqP.\n        case: H => ?; subst l.\n        apply H0 => /=; by left.\n      - clear H1.\n        apply tritra_precond_stre with (pi,\n          remove_empty_heap pi\n          (star_assoc_left (star_com (star sig1 (singl e1 e2))) frag_list_entail.emp)).\n        rewrite /while.entails => s h [H2 H3].\n        split; first by [].\n        apply remove_empty_heap_correct' => //.\n        apply star_assoc_left_correct'.\n        Compose_sepcon h assert_m.heap.emp; last by [].\n        by apply star_com_correct'.\n        case : H => ?; subst l.\n        apply H0; by left.\n    * move: (expr_b_dp_correct (pi =b> (e \\= e1))) => H1.\n      destruct (expr_b_dp (pi =b> (e \\= e1))).\n      - apply tritra_mutation'.\n        move=> s H2; move: (H1 (refl_equal _) s) => H3.\n        have : [ e \\= e1 ]b_s by omegab.\n        move/eqP => H4.\n        exact/eqP.\n        case: H => ?; subst l.\n        apply H0 => /=; by left.\n      - apply tritra_precond_stre with (pi, remove_empty_heap pi\n          (star_assoc_left (star_com (star sig1 (cell e1))) frag_list_entail.emp)).\n        rewrite /while.entails => s h [H3 H4].\n        split; first by [].\n        apply remove_empty_heap_correct' => //.\n        apply star_assoc_left_correct'.\n        Compose_sepcon h assert_m.heap.emp; last by [].\n        by apply star_com_correct'.\n        case: H => ?; subst l.\n        apply H0; by left.\n    * apply tritra_precond_stre with (pi,\n        remove_empty_heap pi\n        (star_assoc_left (star_com (star sig1 frag_list_entail.emp)) frag_list_entail.emp)).\n      rewrite /while.entails => s h [H2 H3].\n      split; first by [].\n      apply remove_empty_heap_correct' => //.\n      apply star_assoc_left_correct'.\n      Compose_sepcon h assert_m.heap.emp; last by [].\n      by apply star_com_correct'.\n      case: H => ?; subst l.\n      apply H0; by left.\n    * apply tritra_precond_stre with (pi,\n        remove_empty_heap pi\n        (star_assoc_left (star_com (star sig1 (star sig2_1 sig2_2))) frag_list_entail.emp)).\n      rewrite /while.entails => s h [H2 H3].\n      split; first by [].\n      apply remove_empty_heap_correct' => //.\n      apply star_assoc_left_correct'.\n      Compose_sepcon h assert_m.heap.emp; last by [].\n      by apply star_com_correct'.\n      case: H => ?; subst l.\n      apply H0; by left.\n    * move: (expr_b_dp_correct (pi =b> (e \\= e1) \\&& (e1 \\!= e2))) => H1.\n      destruct (expr_b_dp (pi =b> (e \\= e1) \\&& (e1 \\!= e2))).\n      - case : H => ?; subst l.\n        eapply tritra_mutation_lst.\n        move=> s H2; move: (H1 (refl_equal _) s) => H3; split; last by omegab.\n        have : [ e \\= e1 ]b_s by omegab.\n        move/eqP => H4.\n        exact/eqP.\n        reflexivity.\n        apply H0 => /=; by left.\n        apply H0 => /=; by right; left.\n      - move: (expr_b_dp_correct (pi =b> ((e1 \\+ nat_e 1) \\= e) \\&& (e1 \\!= e2))) => {}H1.\n        destruct (expr_b_dp (pi =b> ((e1 \\+ nat_e 1) \\= e) \\&& (e1 \\!= e2))).\n        + case : H => ?; subst l.\n          eapply tritra_mutation_lst'.\n          move=> s H2; move: (H1 (refl_equal _) s) => H3; split; by omegab.\n          reflexivity.\n          apply H0 => /=; by left.\n          apply H0 => /=; by right; left.\n        + clear H1.\n          apply tritra_precond_stre with (pi,\n            remove_empty_heap pi\n            (star_assoc_left (star_com (star sig1 (lst e1 e2))) frag_list_entail.emp)).\n          rewrite /while.entails => s h [H2 H3].\n          split; first by [].\n          apply remove_empty_heap_correct' => //.\n          apply star_assoc_left_correct'.\n          Compose_sepcon h assert_m.heap.emp; last by [].\n          by apply star_com_correct'.\n          case: H => ?; subst l.\n          apply H0; by left.\n  * apply tritra_precond_stre with (pi, star frag_list_entail.emp (lst e1 e2)).\n    + apply entail_soundness; by Entail.\n    + case: H => ?; subst l.\n      apply H0 => /=; by left.\n- (* wpIf *) case: H => ?; subst l.\n  apply tritra_if; apply H0 => /=; by [left | right; left].\nQed.\n\nDefinition tritra_step (pi : expr_b) (sig : Sigma) (A : wpAssrt) : option (list ((expr_b * Sigma) * wpAssrt)) :=\n  if expr_b_dp (\\~ pi) then\n    Some nil\n  else\n    tritra_step' pi sig A.\n\nLemma tritra_step_correct: forall A pi sig l,\n  tritra_step pi sig A = Some l ->\n  (forall pi' sig' A', In ((pi', sig'), A') l -> tritra (pi', sig') A') ->\n  tritra (pi, sig) A.\nProof.\nmove=> A pi sig l H H0.\nrewrite /tritra_step in H.\nmove: (expr_b_dp_correct (\\~ pi)) => H1.\ndestruct (expr_b_dp (\\~ pi)).\n- apply tritra_incons => s h [H3 h4].\n  move: (H1 (refl_equal _) s).\n  by rewrite /= H3.\n- clear H1.\n  by apply tritra_step'_correct with l.\nQed.\n\nFixpoint tritra_list (l : list ((expr_b * Sigma) * wpAssrt)) : option (list ((expr_b * Sigma) * wpAssrt)) :=\n  match l with\n    | nil => Some nil\n    | ((pi, sg), A) :: tl =>\n      match tritra_step pi sg A with\n        | None => None\n        | Some l' =>\n          match tritra_list tl with\n            | None => None\n            | Some l'' => Some (l' ++ l'')\n          end\n      end\n  end.\n\nLemma tritra_list_correct : forall l l', tritra_list l = Some l' ->\n  (forall pi sig A, In ((pi, sig), A) l' -> tritra (pi, sig) A) ->\n  (forall pi sig A, In ((pi, sig), A) l -> tritra (pi, sig) A).\nProof.\ninduction l; simpl; intros; auto.\n- contradiction.\n- destruct a.\n  destruct p as [p s].\n  generalize (tritra_step_correct w p s); intros.\n  destruct (tritra_step p s w); try discriminate.\n  generalize (H2 l0 (refl_equal _)); clear H2; intros.\n  destruct (tritra_list l); try discriminate.\n  generalize (IHl l1 (refl_equal _)); clear IHl; intros.\n  injection H; clear H; intros; subst l'.\n  case : H1.\n  + case => ? ? ?; subst p s w.\n    apply H2 => pi' sig' A' H.\n    apply H0, in_or_app; by left.\n  + apply H3 => pi0 sig0 A0 H.\n    apply H0, in_or_app; by right.\nQed.\n\nFixpoint tritra_list_rec (l: list ((expr_b * Sigma) * wpAssrt)) (size:nat) {struct size} : option (list ((expr_b * Sigma) * wpAssrt)) :=\n  match size with\n    | 0 => Some l\n    | S size' =>\n      match tritra_list l with\n        | None => None\n        | Some l' =>\n          match l' with\n            | nil => Some nil\n            | _ =>  tritra_list_rec l' size'\n          end\n      end\n  end.\n\nLemma tritra_list_rec_correct : forall n l l',\n  tritra_list_rec l n = Some l' ->\n  (forall pi sig A, In ((pi, sig), A) l' -> tritra (pi, sig) A) ->\n  (forall pi sig A, In ((pi, sig), A) l -> tritra (pi, sig) A).\nProof.\ninduction n; simpl; intros; auto.\ncase : H => ?; subst l.\nintuition.\nmove: (tritra_list_correct l) => H2.\ndestruct (tritra_list l); try discriminate.\ndestruct l0.\n- apply (H2 _ (refl_equal _)).\n  intros.\n  simpl in H3; contradiction.\n  assumption.\n- apply (H2 _ (refl_equal _)); last by assumption.\n  move=> pi0 sig0 A0 H3; by apply (IHn _ _ H H0).\nQed.\n\nLemma tritra_list_rec_correct': forall n l, tritra_list_rec l n = Some nil ->\n  (forall pi sig A, In ((pi, sig), A) l ->\n    assrt_interp (pi, sig) ===> wpAssrt_interp A).\nProof.\nmove=> n l H pi sig A H0; by apply tritra_soundness, (tritra_list_rec_correct _ _ _ H).\nQed.\n\nFixpoint wpAssrt_size (A : wpAssrt) : nat :=\n  match A with\n    | wpElt P => 2\n    | wpSubst l P => 2 + wpAssrt_size P\n    | wpLookup x e P => 2 + wpAssrt_size P\n    | wpMutation e1 e2 P  => 2 + wpAssrt_size P\n    | wpIf b L1 L2 => 2 + wpAssrt_size L1 + wpAssrt_size L2\n  end.\n\nDefinition triple_transformation_complexity (pi: expr_b) (sig: Sigma) (L: wpAssrt) : nat :=\n  (Expr_B_size pi) * (sigma_size sig) * (wpAssrt_size L).\n\n(** entry point *)\nFixpoint triple_transformation (P: Assrt) (Q: wpAssrt) {struct P} : option (list ((expr_b * Sigma) * wpAssrt)) :=\n  match P with\n    | nil => Some nil\n    | (pi, sig) :: tl =>\n      match tritra_list_rec\n        (((compute_constraints (cell_loc_not_null pi sig) sig, sig), Q) :: nil)\n        (triple_transformation_complexity pi sig Q) with\n        | Some l =>\n          match triple_transformation tl Q with\n            | Some l' => Some (l ++ l')\n            | None => None\n          end\n        | None =>\n          match triple_transformation tl Q with\n            | Some l' => Some (((pi, sig), Q) :: l')\n            | None => None\n          end\n      end\n  end.\n\nLemma triple_transformation_correct: forall P Q,\n  triple_transformation P Q = Some nil  ->\n  Assrt_interp P ===> wpAssrt_interp Q.\nProof.\ninduction P; rewrite /= /while.entails; intros; try contradiction.\ndestruct a as [p s0].\nmove: (tritra_list_rec_correct' (triple_transformation_complexity p s0 Q) ((compute_constraints (cell_loc_not_null p s0) s0, s0, Q) :: nil)) => H1.\ndestruct (tritra_list_rec ((compute_constraints (cell_loc_not_null p s0) s0, s0, Q) :: nil) (triple_transformation_complexity p s0 Q)); try discriminate.\n- move: (IHP Q) => H2.\n  rewrite /while.entails {IHP} in H2.\n  destruct (triple_transformation P Q); try discriminate.\n  destruct l; destruct l0; try discriminate.\n  case: H0 => H3.\n  + red in H1; eapply H1.\n    reflexivity.\n    simpl; by left.\n    apply compute_constraints_correct.\n    by apply cell_loc_not_null_correct.\n  + by eapply H2; auto.\n- move: (IHP Q) => H2.\n  rewrite /while.entails {IHP} in H2.\n  by destruct (triple_transformation P Q).\nQed.\n\n(*\nFixpoint triple_transformation (P: Assrt) (Q: wpAssrt) {struct P} : option (list ((Pi * Sigma) * wpAssrt)) :=\n  match P with\n    | nil => Some nil\n    | (pi,sig)::tl =>\n      match (tritra_list_rec (((pi,sig),Q)::nil) (triple_transformation_complexity pi sig Q)) with\n        | Some l =>\n          match triple_transformation tl Q with\n            | Some l' => Some (l ++ l')\n            | None => None\n          end\n        | None =>\n          match triple_transformation tl Q with\n            | Some l' => Some (((pi,sig),Q)::l')\n            | None => None\n          end\n\n      end\n  end.\n\nLemma triple_transformation_correct: forall P Q,\n  triple_transformation P Q = Some nil  ->\n  (Assrt_interp P) ===> (wpAssrt_interp Q).\n  induction P; simpl; red; intros; try contradiction.\n  destruct a.\n  generalize (tritra_list_rec_correct' (triple_transformation_complexity p s0 Q) ((p, s0, Q) :: nil)); intros.\n  destruct (tritra_list_rec ((p, s0, Q) :: nil) (triple_transformation_complexity p s0 Q)); try discriminate.\n  generalize (IHP Q); intros.\n  red in H2.\n  clear IHP.\n  destruct (triple_transformation P Q); try discriminate.\n  destruct l; destruct l0; try discriminate.\n  inversion_clear H0.\n  red in H1; eapply H1.\n  auto.\n  simpl; left; auto.\n  auto.\n  eapply H2; auto.\n  generalize (IHP Q); intros.\n  red in H2.\n  clear IHP.\n  destruct (triple_transformation P Q); try discriminate.\nQed.\n*)\n\nFixpoint triple_transformation2 (P : Assrt) (Q : wpAssrt) {struct P} : bool :=\n  match P with\n    | nil => true\n    | (pi, sig) :: tl =>\n      match tritra_list_rec (((pi, sig), Q) :: nil) (triple_transformation_complexity pi sig Q) with\n        | Some nil =>\n          triple_transformation2 tl Q\n        | _ => false\n      end\n  end.\n\nLemma triple_transformation2_correct : forall P Q, triple_transformation2 P Q ->\n  Assrt_interp P ===> wpAssrt_interp Q.\nProof.\ninduction P; rewrite /= /while.entails; intros; try contradiction.\ndestruct a as [p s0].\nmove: (tritra_list_rec_correct' (triple_transformation_complexity p s0 Q) ((p, s0, Q) :: nil)) => H1.\ndestruct (tritra_list_rec ((p, s0, Q) :: nil) (triple_transformation_complexity p s0 Q)); try discriminate.\ndestruct l; try discriminate.\ncase : H0 => H0.\n- eapply (H1 (refl_equal _)); last by apply H0.\n  by left.\n- by apply IHP.\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/frag_list_triple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.27600819866722226}}
{"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.  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 terms5.\nRequire Export computation7.\nRequire Export computation_exc.\n\n\nDefinition isccan {o} (t : @NTerm o) :=\n  match t with\n    | oterm (Can _) _ => True\n    | _ => False\n  end.\n\nDefinition isccanc {o} (t : @CTerm o) := isccan (get_cterm t).\n\n\nLemma dec_ex_reduces_in_atmost_k_steps_exc {o} :\n  forall lib k (t : @NTerm o),\n    decidable {v : NTerm & reduces_in_atmost_k_steps_exc lib t v k}.\nProof.\n  introv.\n  remember (compute_at_most_k_steps_exc lib k t) as c; symmetry in Heqc.\n  destruct c.\n  - left.\n    exists n; auto.\n  - right; intro r; exrepnd; rw r0 in Heqc; ginv.\nQed.\n\nLemma dec_ex_reduces_in_atmost_k_steps_excc {o} :\n  forall lib k (t : @CTerm o),\n    decidable {v : CTerm & reduces_in_atmost_k_steps_excc lib t v k}.\nProof.\n  introv.\n  destruct_cterms.\n  unfold reduces_in_atmost_k_steps_excc; simpl.\n  pose proof (dec_ex_reduces_in_atmost_k_steps_exc lib k x) as h.\n  destruct h as [h|h];[left|right].\n  - exrepnd.\n    applydup @reduces_in_atmost_k_steps_preserves_isprog in h0; auto.\n    exists (mk_ct v h1); simpl; auto.\n  - intro q; exrepnd.\n    destruct h.\n    destruct_cterms; allsimpl.\n    exists x0; auto.\nQed.\n\nLemma dec_iscan {o} :\n  forall (t : @NTerm o), decidable (iscan t).\nProof.\n  introv.\n  destruct t as [v|f|op bs]; simpl; tcsp; try (complete (right; sp)).\n  dopid op as [can|ncan|exc|abs] Case; tcsp; try (complete (right; sp)).\nQed.\n\nLemma dec_iscanc {o} :\n  forall (t : @CTerm o), decidable (iscanc t).\nProof.\n  introv.\n  destruct_cterms.\n  unfold iscanc; simpl.\n  apply dec_iscan.\nQed.\n\nDefinition noconst  {o} (t : @NTerm o) := assert (no_const t).\nDefinition noconstb {o} (b : @BTerm o) := assert (no_const_b b).\nDefinition noconsto {o} (op : @Opid o) := assert (no_const_o op).\n\nDefinition noseq  {o} (t : @NTerm o) := assert (no_seq t).\nDefinition noseqb {o} (b : @BTerm o) := assert (no_seq_b b).\nDefinition noseqo {o} (op : @Opid o) := assert (no_seq_o op).\n\nDefinition no_constc {o} (t : @CTerm o) := no_const (get_cterm t).\nDefinition noconstc  {o} (t : @CTerm o) := assert (no_constc t).\n\nDefinition no_seqc   {o} (t : @CTerm o) := no_seq (get_cterm t).\nDefinition noseqc    {o} (t : @CTerm o) := assert (no_seqc t).\n\nLemma decidable_eq_bool :\n  forall (a b : bool),\n    decidable (a = b).\nProof.\n  introv.\n  destruct a, b; tcsp; right; intro xx; ginv.\nQed.\n\nLemma decidable_noseqc {o} :\n  forall (t : @CTerm o),\n    decidable (noseqc t).\nProof.\n  introv.\n  destruct_cterms.\n  unfold noseqc; simpl.\n  apply decidable_eq_bool.\nQed.\n\nLemma decidable_noconstc {o} :\n  forall (t : @CTerm o),\n    decidable (noconstc t).\nProof.\n  introv.\n  destruct_cterms.\n  unfold noconstc; simpl.\n  apply decidable_eq_bool.\nQed.\n\nLemma noconstb_bterm {o} :\n  forall l (t : @NTerm o),\n    noconstb (bterm l t) <=> noconst t.\nProof.\n  introv; sp.\nQed.\n\nLemma noconst_oterm {o} :\n  forall op (bs : list (@BTerm o)),\n    noconst (oterm op bs)\n    <=> (noconsto op # forall b, LIn b bs -> noconstb b).\nProof.\n  introv; unfold noconst; simpl.\n  rw @assert_of_andb.\n  rw @assert_ball_map; sp.\nQed.\n\nLemma noseq_oterm {o} :\n  forall op (bs : list (@BTerm o)),\n    noseq (oterm op bs)\n    <=> (noseqo op # forall b, LIn b bs -> noseqb b).\nProof.\n  introv; unfold noseq; simpl.\n  rw @assert_of_andb.\n  rw @assert_ball_map; sp.\nQed.\n\nLemma noseqb_bterm {o} :\n  forall l (t : @NTerm o),\n    noseqb (bterm l t) <=> noseq t.\nProof.\n  introv; sp.\nQed.\n\nLemma decidable_eq_list :\n  forall T (l1 l2 : list T),\n    (forall a b, LIn (a,b) (combine l1 l2) -> decidable (a = b))\n    -> decidable (l1 = l2).\nProof.\n  induction l1; destruct l2; introv imp; allsimpl; tcsp;\n  try (complete (right; intro xx; ginv; tcsp)).\n  pose proof (imp a t) as q; autodimp q hyp.\n  destruct q as [q|q]; subst;\n  try (complete (right; intro xx; ginv; tcsp)).\n  pose proof (IHl1 l2) as h; clear IHl1; autodimp h hyp.\n  destruct h as [h|h]; subst; tcsp;\n  try (complete (right; intro xx; ginv; tcsp)).\nQed.\n\nLemma dec_eq_terms {o} :\n  forall (a b : @NTerm o),\n    noconst a\n    -> noseq a\n    -> decidable (a = b).\nProof.\n  nterm_ind a as [v1|f1|op1 bs1 imp] Case; introv noc nos;\n  destruct b as [v2|f2|op2 bs2];\n  try (complete (right; intro xx; ginv; tcsp)).\n\n  - Case \"vterm\".\n    destruct (deq_nvar v1 v2); subst; tcsp.\n    right; intro xx; ginv; tcsp.\n\n  - Case \"oterm\".\n    allrw @noconst_oterm; repnd.\n    allrw @noseq_oterm; repnd.\n    destruct (opid_dec_no_const op1 op2) as [d|d]; auto; subst;\n    try (complete (right; intro xx; ginv; tcsp));[].\n\n    assert (decidable (bs1 = bs2)) as dbs.\n    { apply decidable_eq_list.\n      introv i.\n      destruct a as [l1 t1].\n      destruct b as [l2 t2].\n      applydup in_combine in i; repnd.\n      applydup noc in i1.\n      allrw @noconstb_bterm.\n      applydup nos in i1.\n      allrw @noseqb_bterm.\n      pose proof (imp t1 l1) as h; autodimp h hyp; clear imp.\n      pose proof (h t2) as ih; clear h; repeat (autodimp ih hyp).\n      destruct ih as [ih|ih]; auto; subst;\n      try (complete (right; intro xx; ginv; tcsp));[].\n\n      assert (decidable (l1 = l2)) as dl.\n      { apply decidable_eq_list.\n        introv j.\n        destruct (deq_nvar a b); subst; tcsp. }\n\n      destruct dl as [dl|dl]; subst; tcsp;\n      try (complete (right; intro xx; ginv; tcsp)).\n    }\n\n    destruct dbs as [d|d]; subst; tcsp;\n    try (complete (right; intro xx; ginv; tcsp)).\nQed.\n\nLemma dec_eq_cterms {o} :\n  forall (a b : @CTerm o),\n    noconstc a\n    -> noseqc a\n    -> decidable (a = b).\nProof.\n  introv nc ns; destruct_cterms.\n  unfold noconstc, no_constc in nc; allsimpl.\n  unfold noseqc, no_seqc in ns; allsimpl.\n  destruct (dec_eq_terms x0 x nc) as [d|d]; subst; tcsp; clear_irr; tcsp.\n  right; intro xx.\n  inversion xx; subst; 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/computation/computation_dec1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.27600819866722226}}
{"text": "From Coq Require Import\n     ssreflect\n.\n\nFrom ExtensibleCompiler Require Import\n     Semantics.Static.TypeOf\n     Syntax.Terms.Unit\n     Syntax.Types.UnitType\n     Theory.Algebra\n     Theory.Functor\n     Theory.ProgramAlgebra\n     Theory.SubFunctor\n     Theory.Types\n     Theory.UniversalProperty\n.\n\nLocal Open Scope SubFunctor.\n\nSection UnitType.\n\n  Context\n    {T}\n    `{Functor T}\n    `{! T supports UnitType}\n  .\n\n  Definition typeOf__UnitType\n  : forall R, MixinAlgebra Unit R (TypeOfResult T)\n    := fun _ rec '(Unit) => Some unitType'.\n\n  Global Instance TypeOf__Unit\n    : forall R, ProgramAlgebra ForTypeOf Unit R (TypeOfResult T)\n    := fun _ => {| programAlgebra := typeOf__UnitType _ |}.\n\n  Global Instance WellFormedMendlerProgramAlgebra__TypeOf__Unit\n    : WellFormedMendlerProgramAlgebra TypeOf__Unit.\n  Proof.\n    constructor.\n    move => T' T'' f rec [] //.\n  Qed.\n\nEnd UnitType.\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/Semantics/Static/TypeOf/Unit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.2760043447065937}}
{"text": "(*\n(C) Copyright 2010, COQTAIL team\n\nProject Info: http://sourceforge.net/projects/coqtail/\n\nThis library is free software; you can redistribute it and/or modify it\nunder the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation; either version 2.1 of the License, or\n(at your option) any later version.\n\nThis library is distributed in the hope that it will be useful, but\nWITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\nor FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\nLicense for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,\nUSA.\n*)\n\nRequire Export Complex.\nRequire Import Cpow_plus.\n\n\nLemma Rdiv_1 : forall r : R, (r/1)%R = r.\nProof.\nintros. field.\nQed.\n\nLtac ring_simpl1 :=  \nmatch goal with\n | id : _|- _ => (ring_simplify in id) ; generalize dependent id\nend\nwith ring_simpl := unfold Rdiv in * ; unfold Cdiv in * ;\ndo 10 (try ring_simpl1) ; intros ; try ring_simplify.\n\nLtac apply_tactic1 := fun tactic => \nmatch goal with\n | id : _|- _ => (apply tactic in id)\nend.\n\n(* begin hide *)\n(** Tactic CusingR2 to simplify some expressions and to go in R *)\n(*\n********************************************\nWarning ! these tactics were written to avoid very long\nnormalization. It should be improved or deleted !\nThe reader is strongly advised not to use this tactic because \nof very long computation.\n********************************************\n*)\nLtac CusingRR2 := simpl in * ;\ntry rewrite <- Ceq in * ; unfold Cdiv in * ; unfold Cconj in * ; unfold Cminus in * ;\nunfold Rdiv in * ;\ntry rewrite Rplus_0_l ; try rewrite Rplus_0_r ;\ntry rewrite Cadd_0_l ; try rewrite Cadd_0_r ;\ntry rewrite Rmult_0_l ; try rewrite Rmult_0_r ; \ntry rewrite Cmult_0_l ; try rewrite Cmult_0_r ; \ntry rewrite Rmult_0_l ; try rewrite Rmult_0_r ; \ntry rewrite <- Cre_add_compat in * ;\ntry rewrite Cim_add_compat in * ; try rewrite Cre_INC_INR in * ;\ntry rewrite <- Cre_opp_compat in * ; try rewrite Cim_INC in * ;\ntry rewrite Cpow_Cim_0 in * ; \ntry rewrite Cpow_Cre_0 in * ; \ntry rewrite Cim_inv_INC in * \nwith CusingRR3 := repeat CusingRR2.\n\nLtac CusingR_rec2 := unfold not in *;\nmatch goal with\n(* destruct complex *)\n     | id:C |- _ => destruct id ; try CusingR_rec2\n(* logical destruct in goal *)\n     | id: _|- _ -> _ => intros ; try CusingR_rec2\n     | id: _|- _ /\\ _ => split ; try CusingR_rec2\n     | id: _ /\\ _ |- _ => destruct id ; CusingRR3 ; try CusingR_rec2\n     | id: _ \\/ _ |- _ => destruct id ; CusingRR3 ; try CusingR_rec2\n(* false*)\n     | id: _ |- False => (apply id ; CusingR2) \n\n\n     | id: _|- _ \\/ _ => try ((left ; CusingR2 ; fail) || (right ; CusingR2 ; fail)) ; simpl in *\n     | _ => simpl in *\nend\nwith\nCusingR2 := intros ; CusingRR3 ; CusingR_rec2 ; subst.\n(* end hide *)\n\n(** Proof of existence of a squareroot *)\n\n(* begin hide*)\nLemma Rle_Rminus: forall a b : R, a <= b -> 0 <= b - a.\nProof.\nintuition. unfold \"<=\" in *. elim H ; intros. left ; apply Rlt_Rminus. assumption.\nright. rewrite H0. ring. \nQed.\n\n\nLemma Croot_sqrt_pos : forall a b : R, 0 <= (sqrt (a * a + b * b) - a) / 2.\nProof.\nintros.\nunfold Rdiv. replace 0%R with (0 * /2)%R by field. apply Rmult_le_compat_r.\nfourier. apply Rle_Rminus.\napply Rle_trans with (Rabs a).\nsplit_Rabs. fourier. intuition.\napply Rsqr_incr_0_var. rewrite Rsqr_sqrt.\nrewrite <- Rsqr_abs. replace (Rsqr a) with (a * a)%R by intuition.\nreplace (a * a)%R with ((a * a) + 0)%R by intuition. \nrewrite Rplus_assoc. apply Rplus_le_compat_l. \nreplace (0 + b * b)%R with (Rsqr b) by intuition.\nintuition. apply (Cnorm_sqr_pos a b). apply sqrt_positivity.\napply (Cnorm_sqr_pos a b).\nQed.\n\nLemma Croot_sqrt_pos_plus : forall a b : R, 0 <= (sqrt (a * a + b * b) + a) / 2.\nProof.\nintros.\nunfold Rdiv. replace 0%R with (0 * /2)%R by field. apply Rmult_le_compat_r.\nfourier. replace a with (--a)%R by intuition. apply Rle_Rminus.\napply Rle_trans with (Rabs a).\nsplit_Rabs. fourier. intuition. fourier.\nreplace (--a)%R with a by intuition.\napply Rsqr_incr_0_var. rewrite Rsqr_sqrt.\nrewrite <- Rsqr_abs. replace (Rsqr a) with (a * a)%R by intuition. \nreplace (a * a)%R with ((a * a) + 0)%R by intuition. \nrewrite Rplus_assoc. apply Rplus_le_compat_l. \nreplace (0 + b * b)%R with (Rsqr b) by intuition.\nintuition. apply (Cnorm_sqr_pos a b). apply sqrt_positivity.\napply (Cnorm_sqr_pos a b).\nQed.\n\nLemma sqrt_square2 : forall a : R, (a >= 0 -> (sqrt a) ^ 2 = a)%R.\nProof.\nintros.\nsimpl. rewrite Rmult_1_r. apply sqrt_sqrt. intuition.\nQed.\n(* end hide *)\n\nLemma Croot_pol_2 : forall z : C, {z1 | z1 ^ 2 = z}.\nProof.\nintros. \ndestruct z as (a, b).\ndestruct (Rlt_le_dec b 0).\n(* case b < 0 *)\nexists (sqrt ( (sqrt ( a * a + b * b) + a)/2),\n- sqrt ( (sqrt ( a * a + b * b) - a)/2))%R.\nCusingR_simpl ; ring_simplify.\n(* real part *)\nrepeat rewrite sqrt_square2. field. destruct (Croot_sqrt_pos a b). intuition. intuition.\ndestruct (Croot_sqrt_pos_plus a b). intuition. intuition.\n(* imaginary part *)\nrewrite Rmult_assoc. rewrite <- sqrt_mult.\nfield_simplify ((sqrt (a * a + b * b) + a) / 2 * ((sqrt (a * a + b * b) - a) / 2))%R.\nrewrite sqrt_square2. field_simplify ((a * a + b * b - a ^ 2) / 4)%R.\nunfold Rdiv. replace (/4)%R with (/2 * /2)%R by field. rewrite sqrt_mult. \nreplace (sqrt (/2 * /2))%R with (/2)%R by (rewrite sqrt_square ; try reflexivity ; fourier).\nreplace (b ^ 2)%R with (-b * -b)%R by ring. rewrite sqrt_square. \nfield. fourier. \nreplace (b ^ 2)%R with (Rsqr b) by (simpl ; rewrite Rmult_1_r ; intuition).\nintuition. fourier. apply Rle_ge . apply (Cnorm_sqr_pos a b).\napply Croot_sqrt_pos_plus. apply Croot_sqrt_pos.\n(* case b >= 0 *)\nexists (sqrt ( (sqrt ( a * a + b * b) + a)/2),\nsqrt ( (sqrt ( a * a + b * b) - a)/2))%R.\nCusingR_simpl ; ring_simplify.\n(* real part *)\nrepeat rewrite sqrt_square2. field.\napply Rle_ge. apply Croot_sqrt_pos.\napply Rle_ge. apply Croot_sqrt_pos_plus.\n(* imaginary part *)\nrewrite Rmult_assoc. \nrepeat rewrite <- sqrt_mult.\nfield_simplify ((sqrt (a * a + b * b) + a) / 2 * ((sqrt (a * a + b * b) - a) / 2))%R.\nrepeat rewrite sqrt_square2.\nfield_simplify ((a * a + b * b - a ^ 2) / 4)%R.\nunfold Rdiv. replace (/4)%R with (/2 * /2)%R by field. rewrite sqrt_mult. \nreplace (sqrt (/2 * /2))%R with (/2)%R by (rewrite sqrt_square ; try reflexivity ; fourier).\nreplace (b ^ 2)%R with (b * b)%R by ring. rewrite sqrt_square. \nfield. fourier.  \nreplace (b ^ 2)%R with (Rsqr b) by (simpl ; rewrite Rmult_1_r ; intuition).\nintuition. fourier. apply Rle_ge . apply (Cnorm_sqr_pos a b).\napply Croot_sqrt_pos_plus. apply Croot_sqrt_pos.\nQed.\n\n(* begin hide*)\nLemma sum_f_R0_eq_seq : forall (n : nat) (f g : nat -> R),\n        (forall m : nat, (m <= n)%nat -> f m = g m) -> \n\tsum_f_R0 f n = sum_f_R0 g n.\nProof.\nintros n f g H.\ninduction n.\nsimpl. apply H. intuition.\nsimpl. rewrite IHn. rewrite H with (S n). reflexivity. intuition. intros m H2. apply H. intuition. \nQed.\n\nLemma Cnorm_sqr_real : forall r9 r10, \n(r9 +i r10) <> 0 ->\n((r9 + r9) * (r9 + r9) + (r10 + r10) * (r10 + r10))%R <> 0%R.\nProof.\nintros a b H Habs.\napply (HC0_norm_R0 ((a + a)%R +i (b + b)%R)) in Habs.\napply H. replace ((a + a)%R +i (b + b)%R) with ((2 +i 0%R) * (a +i b)) in Habs by CusingR_f.\napply Cmult_integral in Habs. destruct Habs ; \nassert (H1 : (2 +i 0%R) = 0 -> False) ; CusingR2 ; (fourier || intuition).\nQed.\n\nLemma Rpow_2_inf_0 : forall x, (x^2 < 0 -> False)%R.\nProof.\nintros. \nreplace (x ^ 2)%R with (Rsqr x) in * by (unfold Rsqr ; simpl ; ring).\nassert (Rsqr x >= 0) by (auto with real).\nfourier.\nQed.\n\nLemma Rpow_2_opp_inf_0 : forall x, (-x^2 > 0 -> False)%R.\nProof.\nintros.\nreplace (x ^ 2)%R with (Rsqr x) in * by (unfold Rsqr ; simpl ; ring).\nassert (Rsqr x >= 0) by (auto with real).\nfourier.\nQed.\n(* end hide*) \n\n(** Equality to 0 of a polynom of degree one *)\n\nLemma Pol_degree_1 : forall a b, (forall x, a * x + b = 0) -> (a = 0 /\\ b = 0).\nProof.\nintros.\nassert (H1 : (a * 0 + b = 0)).\napply H.\nassert (H2 : (a * 1 + b = 0)).\napply H.\nrewrite Cmult_0_r in H1.\nrewrite Cmult_1_r in H2.\nrewrite Cadd_0_l in H1.\nsubst. rewrite Cadd_0_r in H2.\nsubst.\nintuition.\nQed.\n\n(** Unicicty of roots of a polynom of degree two*)\n\nLemma Cpol_2_root_unicity : forall x1 x2 x3 x4,\n(forall x, (x + x1) * (x + x2) = (x + x3) * (x + x4)) ->\n(x1 = x3 /\\ x2 = x4) \\/ (x1 = x4 /\\ x2 = x3).\nProof.\nintros x1 x2 x3 x4 H.\nassert (H1 : (forall x : C, (x + x1) * (x + x2) = (x + x3) * (x + x4)) -> \n(forall x, (x1 + x2 - x3 - x4) * x + x1 * x2 - x3 * x4 = 0)).\nintros H0 x.\nassert (H1 : ((x + x1) * (x + x2) = (x + x3) * (x + x4) -> \n(x1 + x2 - x3 - x4) * x + x1 * x2 - x3 * x4 = 0)).\nintros H1.\napply Cminus_diag_eq in H1. ring_simplify in H1.\nrepeat rewrite <- Cmult_add_distr_l in H1.\nrepeat rewrite <- Cmult_minus_distr_l in H1.\nrewrite Cmult_comm in H1.\nassumption.\napply H1. apply H0.\nassert (H2 : (x1 + x2 - x3 - x4 = 0 /\\ x1 * x2 - x3 * x4 = 0)).\napply Pol_degree_1.\nintros x.\nreplace ((x1 + x2 - x3 - x4) * x + (x1 * x2 - x3 * x4)) with \n((x1 + x2 - x3 - x4) * x + x1 * x2 - x3 * x4) by ring.\napply H1.\nintros x0.\napply H.\ndestruct H2 as [H0 H2].\nassert (H3 : ((-x1 + x1) * (-x1 + x2) = (-x1 + x3) * (-x1 + x4))).\napply H.\nassert (H4 : ((-x2 + x1) * (-x2 + x2) = (-x2 + x3) * (-x2 + x4))).\napply H. rewrite Cadd_opp_l in *.\n(* From this point we do all in parallel *)\ndestruct (Ceq_dec x2 x1) ;\nrewrite Cmult_0_l in *; rewrite Cmult_0_r in * ;\nsymmetry in H3 ; symmetry in H4 ;\napply Cmult_integral in H3 ; apply Cmult_integral in H4 ;\ndestruct H3 as [H3|H3] ; destruct H4 as [H4|H4] ;\nrewrite Cadd_comm in * ; apply Cminus_diag_uniq in H3 ;\napply Cminus_diag_uniq in H4 ; subst ; ring_simpl ; intuition.\nQed.\n\n\n(** Solve a polynom of degree two in the Complex field as a function of delta *)\nLemma Cpol_d_2 : forall a b c delta, (delta = b^2 - 4*a * c) ->\na <> 0 -> Cim a = 0%R -> Cim b = 0%R -> Cim c = 0%R ->\nexists x1, exists x2, forall x, \na * x ^ 2 + b * x + c =  a * (x + x1) * (x + x2)\n/\\ ((Cim delta) = 0%R /\\ Cre delta > 0%R -> Cim x1 = 0%R /\\ Cim x2 = 0%R) \n/\\ ((Cim delta) = 0%R /\\ Cre delta < 0%R -> Cim x1 <> 0%R /\\ Cim x2 <> 0%R)\n/\\ ((Cim delta) = 0%R /\\ Cre delta = 0%R -> x1 = x2 /\\ Cim x1 = 0%R).\nProof.\nintros a b c delta Hdelta Ha Hima Himb Himc.\ndestruct (Croot_pol_2 delta) as [delta1 Hsquare].\nexists (( b / (a + a) - delta1 / (a + a))).\nexists (( b / (a + a) + delta1 / (a + a))).\nintros x.\nrepeat split. unfold Cdiv. ring_simplify.\nrewrite Hsquare. rewrite Hdelta.\nunfold Cminus. repeat rewrite Cadd_assoc.\napply Cadd_eq_compat_l.\nring_simplify. rewrite Rplus_0_l.\nassert (H : (2 * 2 = 4)) by (CusingR_simpl ; ring).\nrewrite <- H. replace (2, 0%R) with (IRC 2) by (reflexivity).\nreplace (a + a) with (2 * a) by (CusingR_simpl ; ring).\nfield. split. assumption. intro H0. rewrite <- Ceq in H0. simpl in H0.\ndestruct H0. assert (2 <> 0)%R by discrR. intuition.\nCusingR2. ring_simpl. \ngeneralize H2. intro H3.\n(apply Rmult_integral in H3 ; destruct H3 as [H3|H3]).\n(apply Rmult_integral in H3 ; destruct H3 as [H3|H3]).\nfourier.\nrewrite H3 in *. rewrite <- H1 in H0. ring_simpl.\napply Rpow_2_opp_inf_0 in H0. destruct H0.\nrewrite H3. ring.\nCusingR2. ring_simpl.\n(apply Rmult_integral in H2 ; destruct H2 as [H2|H2]).\n(apply Rmult_integral in H2 ; destruct H2 as [H2|H2]).\nfourier. rewrite H2 in H1. rewrite <- H1 in H0. ring_simpl.\napply Rpow_2_opp_inf_0 in H0. destruct H0.\nrewrite H2. ring. \nCusingR2. ring_simpl.\napply Rmult_integral in H0 ; destruct H0 as [H0|H0].\napply Rmult_integral in H0 ; destruct H0 as [H0|H0].\napply Rmult_integral in H0 ; destruct H0 as [H0|H0].\nfourier.\napply Rinv_neq_0_compat in H0. destruct H0.\nintro H8. ring_simplify in H8. apply Rmult_integral in H8. destruct H8 as [H8|H8].\nfourier.\nreplace (r9 ^ 2)%R with (Rsqr r9) in H8 by (unfold Rsqr ; simpl ; ring).\nassert (H5 : (r9 = 0)%R). apply Rsqr_0_uniq ; assumption.\nrewrite H5 in *. apply Ha. split ; reflexivity.\nassumption.\nrewrite H0 in *. ring_simpl. rewrite <- H2 in H1.\napply Rpow_2_inf_0 in H1. destruct H1. reflexivity.\nCusingR2. ring_simpl.\napply Rmult_integral in H0 ; destruct H0 as [H0|H0].\napply Rmult_integral in H0 ; destruct H0 as [H0|H0].\napply Rmult_integral in H0 ; destruct H0 as [H0|H0].\nfourier.\napply Rinv_neq_0_compat in H0. destruct H0.\nintro H8. ring_simplify in H8. apply Rmult_integral in H8. destruct H8 as [H8|H8].\nfourier.\nreplace (r9 ^ 2)%R with (Rsqr r9) in H8 by (unfold Rsqr ; simpl ; ring).\nassert (H5 : (r9 = 0)%R). apply Rsqr_0_uniq ; assumption.\nrewrite H5 in *. apply Ha. split ; reflexivity.\nassumption.\nrewrite H0 in *. ring_simpl. rewrite <- H2 in H1.\napply Rpow_2_inf_0 in H1. destruct H1.\nreflexivity. unfold Cminus. apply Cadd_eq_compat_l.\nassert (H0 : (delta = 0)) by (rewrite <- Ceq ; intuition).\nrewrite H0 in *. \nassert (H1 : delta1 = 0). simpl in Hsquare. rewrite Cmult_1_r in Hsquare.\napply Cmult_integral in Hsquare. destruct Hsquare ; assumption.\nrewrite H1. unfold Cdiv. ring.\nCusingR2. ring_simpl.\napply Rmult_integral in H2 ; destruct H2 as [H2|H2].\napply Rmult_integral in H2 ; destruct H2 as [H2|H2].\nfourier.\nrewrite H2 in *. ring_simplify in H1.\nrewrite <- H1 in H0. replace (r2 ^ 2)%R with (Rsqr r2) in H0 by (unfold Rsqr ; simpl ; ring).\nassert (H10 : (r2 = 0)%R). apply Rsqr_0_uniq. apply Ropp_eq_0_compat in H0.\nring_simplify in H0. assumption.\nrewrite H10 in *. ring.\nrewrite H2 in *. ring.\nQed.\n\n(** Real properties that can be deduced from the resolution of a complex polynom*)\nLemma Cpol_2_real_delta_pos : forall a b c delta, ((delta = b^2 - 4*a * c ) ->\ndelta > 0 -> a <> 0 ->\nexists x1, exists x2, forall x,\na * x ^ 2 + b * x + c =  a * (x + x1) * (x + x2))%R.\nProof.\nintros a b c delta deltadef Hdelta Ha.\ndestruct (Cpol_d_2 (a +i 0%R) (b +i 0%R) (c +i 0%R) (delta +i 0%R)) as [x1 [x2 H1]].\nCusingR2.\nring.\nring.\nCusingR2.\nreflexivity.\nCusingR2.\nreflexivity.\nCusingR2.\nreflexivity.\nCusingR2.\nreflexivity.\nexists (Cre x1). exists (Cre x2).\nassert (HRtoC : (forall x, Cre ((a +i 0%R) * (x +i 0%R) ^ 2 + (b +i 0%R) * (x +i 0%R) + (c +i  0%R)) = \nCre ((a +i 0%R) * ((x +i 0%R) + x1) * ((x +i 0%R) + x2)))).\nintros x.\napply Cre_eq_compat. generalize (H1 (x +i 0%R)). intro H0.\ndestruct H0 as [H2 [H3 [H4 H5]]].\n apply H2.\nintros x.\ngeneralize (H1 (x +i 0%R)). intro H0.\ndestruct H0 as [H2 [H3 [H4 H5]]].\nassert (HCroot : (Cim x1 = 0%R /\\ Cim x2 = 0%R)). apply H3. simpl. split. reflexivity. assumption.\nCusingR2. ring_simpl. assumption.\nQed.\n\nLemma Cpol_2_real_delta_eq_0 : forall a b c delta, ((delta = b^2 - 4*a * c) ->\ndelta = 0 -> a <> 0 ->\nexists x1, exists x2, forall x,\na * x ^ 2 + b * x + c =  a * (x + x1) * (x + x2))%R.\nProof.\nintros a b c delta deltadef Hdelta Ha.\ndestruct (Cpol_d_2 (a +i 0%R) (b +i 0%R) (c +i 0%R) (delta +i 0%R)) as [x1 [x2 H1]]. \nCusingR2.\nring.\nring.\nCusingR2.\nreflexivity.\nCusingR2.\nreflexivity.\nCusingR2.\nreflexivity.\nCusingR2.\nreflexivity.\nexists (Cre x1). exists (Cre x2).\nassert (HRtoC : (forall x, Cre ((a +i 0%R) * (x +i 0%R) ^ 2 + (b +i 0%R) * (x +i 0%R) + (c +i  0%R)) = \nCre ((a +i 0%R) * ((x +i 0%R) + x1) * ((x +i 0%R) + x2)))).\nintros x.\napply Cre_eq_compat. generalize (H1 (x +i 0%R)). intro H0.\ndestruct H0 as [H2 [H3 [H4 H5]]].\n apply H2.\nintros x.\ngeneralize (H1 (x +i 0%R)). intro H0.\ndestruct H0 as [H2 [H3 [H4 H5]]].\nassert (HCroot : (x1 = x2 /\\ Cim x1 = 0%R)). apply H5. simpl. split. reflexivity. assumption.\nCusingR2. subst. ring_simpl. assumption.\nQed.\n\nLemma Cpol_2_real_delta_eq_neg : forall a b c delta, ((delta = b^2 - 4*a * c) ->\ndelta < 0 -> a <> 0 ->\n~ (exists x1, exists x2, forall x,  \na * x ^ 2 + b * x + c =  a * (x + x1) * (x + x2)))%R.\nProof.\nintros a b c delta deltadef Hdelta Ha.\ndestruct (Cpol_d_2 (a +i 0%R) (b +i 0%R) (c +i 0%R) (delta +i 0%R)) as [x1 [x2 H1]]. \nCusingR2.\nring.\nring.\nCusingR2.\nreflexivity.\nCusingR2.\nreflexivity.\nCusingR2.\nreflexivity.\nCusingR2.\nreflexivity. \nintro H.\ndestruct H as (x3, H) . destruct H as (x4, H).\nassert (forall x : C, (a +i 0%R) * x ^ 2 + (b +i  0%R) * x + (c +i  0%R) =\n     (a +i 0%R) * (x + x1) * (x + x2)).\nintro x. \ngeneralize (H1 x). intros H0.\ndestruct H0 as [H2 [H3 [H4 H5]]].\napply H2.\nassert (H10 : forall x : C, (a +i 0%R) * x ^ 2 + (b +i  0%R) * x + (c +i  0%R) =\n     (a +i 0%R) * (x + (x3 +i 0%R)) * (x + (x4 +i 0%R))).\nintros x.\ndestruct x as (r, r0).\nrewrite <- Ceq. split.\nsimpl. ring_simplify.\ngeneralize (H r). intro H15. ring_simplify in H15.\nreplace (a * r ^ 2 - a * r0 ^ 2 + r * b + c)%R with ((a * r ^ 2 + r * b + c) - a* r0^2)%R by ring.\nrewrite H15. ring.\nsimpl. ring_simplify.\ngeneralize (H 1%R). intro H15. ring_simplify in H15.\ngeneralize (H 0%R). intro H16. ring_simplify in H16.\nrewrite <- H16 in H15. ring_simplify in H15.\nrewrite <- Rmult_plus_distr_l in H15.\nrewrite Rplus_comm in H15. symmetry in H15. rewrite Rplus_comm in H15.\napply Rplus_eq_reg_l in H15. rewrite Rplus_comm in H15.\napply Rplus_eq_reg_l in H15.\nrewrite <- H15. ring.\nassert (Htra :  (x1 = (x3 +i 0%R) /\\ x2 = (x4 +i 0%R) \\/ x1 = (x4 +i 0%R) /\\ x2 = (x3 +i 0%R))).\nassert (forall x : C, (x + (x3 +i 0%R)) * (x + (x4 +i 0%R))  = (x + x1) * (x + x2)).\nintro x. apply Cmult_eq_reg_l with (a +i 0%R).\nCusingR2. reflexivity. generalize (H0 x). generalize (H10 x).\nintros abs1 abs2.\nring_simplify in abs1 ; ring_simplify in abs2 ; ring_simplify.\nrewrite <- abs1. rewrite abs2. reflexivity.\napply Cpol_2_root_unicity.\nintros x. rewrite H2. reflexivity.\ngeneralize (H1 0). intros Hdeltas.\ndestruct Hdeltas as [H2 [H3 [H4 H5]]].\nclear H3 H5 H2.\nassert (Habss : (Cim x1 <> 0%R /\\ Cim x2 <> 0%R)).\napply H4. intuition. clear H4.\ndestruct Habss as (Habss1, Habss2).\ndestruct Htra as [[Htra1 Htra2]|[Htra1 Htra2]].\nrewrite <- Ceq in Htra1.\ndestruct Htra1 as (Htra1, Htraabs).\nsimpl in Htraabs.\napply Habss1. assumption.\nrewrite <- Ceq in Htra1.\ndestruct Htra1 as (Htra1, Htraabs).\nsimpl in Htraabs.\napply Habss1. assumption.\nQed.\n\nLemma Cfpol_root : forall a b c delta, ((delta = b^2 - 4*a * c) ->\ndelta >= 0 -> a <> 0 -> exists x, a * x ^ 2 + b * x + c = 0)%R.\nProof.\nintros a b c delta Hdelta deltapos Ha.\ndestruct deltapos.\ndestruct (Cpol_2_real_delta_pos a b c delta) as [x H0].\nassumption. assumption. assumption.\ndestruct H0 as (x1, H0).\nexists (-x1)%R. rewrite H0. ring.\ndestruct (Cpol_2_real_delta_eq_0 a b c delta) as [x2 H5].\nassumption. assumption. assumption.\ndestruct H5 as (x1, H0).\nexists (-x1)%R. rewrite H0. ring.\nQed.\n\nLemma Cpol_pos : forall a b c delta, (delta = b^2 - 4*a * c)%R ->\n a <> 0%R ->\n(forall x, 0 <> a*x*x+b*x+c)%R -> delta < 0%R.\nintros a b c delta Hdelta Ha.\nintro Hpoly.\ndestruct (total_order_T delta 0) as [[H|H]|H].\nassumption.\ndestruct (Cfpol_root a b c delta).\nassumption. intuition. assumption. \ndestruct (Hpoly x). ring_simplify. symmetry. \nring_simplify in H0. assumption.\ndestruct (Cfpol_root a b c delta).\nassumption. intuition. assumption. \ndestruct (Hpoly x). ring_simplify. symmetry. \nring_simplify in H0. assumption.\nQed.\n\n\nLemma Pos_poly_del : forall a b c : R,\na <> 0%R -> a > 0%R -> (forall x, 0 <= a*x*x+b*x+c) -> b^2 - 4*a*c <=0.\nProof.\nintros a b c Ha Haa Hpoly.\npose ( b^2 - 4*a*c)%R as delta.\ndestruct (total_order_T delta 0) as [[H|H]|H].\nintuition. intuition.\ndestruct (Cfpol_root a b c delta).\nreflexivity.\nintuition.\nassumption.\nassert (H1 : (exists x1, exists x2, forall x,\na * x ^ 2 + b * x + c =  a * (x + x1) * (x + x2))%R).\napply Cpol_2_real_delta_pos with delta.\nring_simplify.\nreflexivity.\nassumption.\nassumption.\ndestruct H1 as [x1 [x2 H1]].\nassert (H9 : (0 > a * ( -(x1 + x2)/2 + x1) * ( - (x1 + x2)/2 + x2))%R).\nreplace ((- (x1 + x2) / 2 + x1))%R with ((x1 - x2) /2)%R by field.\nreplace ((- (x1 + x2) / 2 + x2))%R with (-(x1 - x2) /2)%R by field.\nreplace (a * ((x1 - x2) / 2) * (- (x1 - x2) / 2))%R with ( ((x1 - x2) / 2)^2 * (-a))%R by field.\nreplace 0%R with (  ((x1 - x2) / 2) ^ 2 * 0 )%R by ring.\napply Rmult_gt_compat_l.\nassert (H10 : (x1 <> x2)).\nintro H11. rewrite H11 in H1.\nassert ((a * 0 ^ 2 + b * 0 + c)%R = (a * (0 + x2) * (0 + x2)))%R.\napply H1.\nassert ((a * 1 ^ 2 + b * 1 + c)%R = (a * (1 + x2) * (1 + x2)))%R.\napply H1.\nring_simpl.\nrewrite <- H2 in H3. unfold delta in H.\nreplace (a + b + c)%R with (c + a + b)%R in H3 by ring.\nreplace (c + 2 * a * x2 +a)%R with (c + a + 2 * a * x2)%R in H3 by ring.\napply Rplus_eq_reg_l in H3. subst.\nreplace ((2 * a * x2) ^ 2 - 4 * a * (a * x2 ^ 2))%R with (0)%R in H by ring .\nfourier.\nreplace (((x1 - x2) / 2) ^ 2)%R with (Rsqr (((x1 - x2) / 2))) by (unfold Rsqr ; simpl ; ring).\napply Rlt_0_sqr.\nintro H30. replace 0%R with (0/2)%R in H30 by field.\nunfold Rdiv in *. rewrite Rmult_comm in H30.\nsymmetry in H30. rewrite Rmult_comm in H30.\napply Rmult_eq_reg_l in H30. \napply H10. symmetry in H30. auto with *.\napply Rinv_neq_0_compat.\ndiscrR.\nintuition.\nassert ( 0 <= a * (- (x1 + x2) / 2 + x1) * (- (x1 + x2) / 2 + x2)).\nrewrite <- H1. replace ( (- (x1 + x2) / 2) ^ 2)%R with ((- (x1 + x2) / 2) * (- (x1 + x2) / 2) )%R by ring.\nrewrite <- Rmult_assoc. apply Hpoly.\nfourier.\nQed.\n\nRequire Import Cpolar.\nRequire Import Cexp.\n\nOpen Scope C_scope.\n\n\nLemma ast_fun_pos : forall n r, (n > 0)%nat -> r > 0 -> (r + 1) ^ n - r > 0.\nProof.\nintros n r Hn Hr.\ninduction Hn.\nsimpl. ring_simplify. fourier.\nsimpl. rewrite Rmult_plus_distr_r. replace 0%R with (0 + 0)%R by intuition.\nunfold Rminus. rewrite Rplus_assoc. apply Rplus_lt_compat.\napply Rmult_gt_0_compat.\nassumption.\napply pow_lt. fourier.\nrewrite Rmult_1_l. apply IHHn.\nQed.\n\n(** ** Every positive real has a n root *)\nLemma exist_root_n_pos : forall r n, r >= 0 -> (n > 0)%nat -> {root | root ^ n = r}%R.\nProof.\nintros r n Hr Hn.\npose (f := (fun x => x ^ n - r)%R).\nassert (Cont_pow : forall x, continuity_pt f x).\nunfold f. intros x. reg.\ndestruct (total_order_T r 0) as [[order|order]|order].\nfourier.\nexists 0. rewrite order.\nrewrite pow_ne_zero. reflexivity.\nintuition.\nassert (Hsup0 : r+1 > 0) by fourier.\nassert (Hpos : forall n, (n > 0)%nat -> (r + 1) ^ n - r > 0).\n intros n1 Hn1. apply ast_fun_pos. assumption. assumption.\nassert (Hneg : 0 ^ n - r < 0). rewrite pow_ne_zero. fourier.\n intuition.\n\ngeneralize (IVT (fun x => x ^ n - r) 0 (r + 1) Cont_pow Hsup0 Hneg)%R.\n\nintros H. destruct H as (x, H).\napply Hpos. assumption.\nexists  x. intuition.\nQed.\n\n(** ** Every complex has a n root *) \n\nLemma exist_root_n : forall n z, (n > 0)%nat -> {root | root ^ n = z}.\nProof.\nintros n z Hn.\ndestruct (polar z) as [r [theta Hrt]].\ndestruct Hrt as [Hrpos [Htheta Hpol]].\nrewrite Cmult_IRC_compat_l in Hpol.\nrewrite <- Cexp_trigo_compat in Hpol.\ndestruct (exist_root_n_pos r n Hrpos) as (root_real, Hreal).\napply Hn.\nexists ( root_real * Cexp ((0 +i theta ) / INC n)).\nrewrite Cpow_mul_distr_l.\nrewrite IRC_pow_compat. rewrite Hreal. rewrite <- Cexp_mult.\nfield_simplify (INC n * ((0 +i  theta) / INC n)).\nunfold Cdiv. rewrite Cinv_1. rewrite Cmult_1_r.\napply Hpol. \napply not_0_INC. intuition.\nQed.\n\n\n", "meta": {"author": "coqtail", "repo": "coqtail", "sha": "96799cc6901b9cdb1c5f47add0f9cd6584fdd389", "save_path": "github-repos/coq/coqtail-coqtail", "path": "github-repos/coq/coqtail-coqtail/coqtail-96799cc6901b9cdb1c5f47add0f9cd6584fdd389/rls/rls1/Complex/Croot_n.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.27597459588847684}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\nRequire Export RegExp.Utility.\nRequire Export RegExp.Definitions.\n\n\n\n\nLemma Empty_false : forall s, Empty ~!= s.\nProof. hammer_hook \"Boolean\" \"Boolean.Empty_false\".\ninduction s.\nreflexivity.\nsimpl.  apply IHs.\nQed.\n\n\n\n\nLemma Eps_true : Eps ~== EmptyString.\nProof. hammer_hook \"Boolean\" \"Boolean.Eps_true\".\nsimpl.  reflexivity.\nQed.\n\nLemma Eps_false : forall s, s <> \"\"%string -> Eps ~!= s.\nProof. hammer_hook \"Boolean\" \"Boolean.Eps_false\".\ninduction s.\nintro Hs. elim Hs. auto.\nintro Has. simpl. eapply Empty_false.\nQed.\n\n\n\n\nAdd Parametric Morphism : Or with\nsignature re_eq ==> re_eq ==> re_eq as Or_morphism.\nProof.\nintros x y H x0 y0 H0.  unfold re_eq in *.  intro s.\ngeneralize dependent x.  generalize dependent y.\ngeneralize dependent x0. generalize dependent y0.\ninduction s.\n\nintros y0 x0 H0 y x H.  specialize (H0 \"\"%string).  specialize (H \"\"%string).\nsimpl in *.  rewrite <- H0.  rewrite <- H.  reflexivity.\n\nsimpl.  intros y0 x0 H0 y x H.  eapply IHs.\nintros.  repeat rewrite <- derivation.  eapply H0.\nintros.  repeat rewrite <- derivation.  eapply H.\nQed.\n\nAdd Parametric Morphism : And with\nsignature re_eq ==> re_eq ==> re_eq as And_morphism.\nProof.\nintros x y H x0 y0 H0.  unfold re_eq in *.  intros s.\ngeneralize dependent x.  generalize dependent y.\ngeneralize dependent x0. generalize dependent y0.\ninduction s.\n\nintros y0 x0 H0 y x H.  specialize (H0 \"\"%string).  specialize (H \"\"%string).\nsimpl in *.  rewrite <- H0.  rewrite <- H.  reflexivity.\n\nsimpl.  intros y0 x0 H0 y x H.  eapply IHs.\nintros s0.  repeat rewrite <- derivation.  eapply H0.\nintros s0.  repeat rewrite <- derivation.  eapply H.\nQed.\n\nAdd Parametric Morphism : Not with\nsignature re_eq ==> re_eq as Not_morphism.\nProof.\nintros x y H.  unfold re_eq in *.  intros s.\ngeneralize dependent x. generalize dependent y.\ninduction s.\n\nintros y x H.  specialize (H \"\"%string).  simpl in *.  rewrite <- H.  reflexivity.\n\nsimpl.  intros y x H.  eapply IHs.\nintros s0.  repeat rewrite <- derivation.  eapply H.\nQed.\n\n\n\nLemma matches_Or : forall s r r',  r || r' ~= s = ((r ~= s) || (r' ~= s))%bool.\nProof. hammer_hook \"Boolean\" \"Boolean.matches_Or\".\ninduction s.\nsimpl.  reflexivity.\nsimpl.  intros r r'.  eapply IHs.\nQed.\n\nLemma matches_And : forall s r r',  matches (And r r') s = ((r ~= s) && (r' ~= s))%bool.\nProof. hammer_hook \"Boolean\" \"Boolean.matches_And\".\ninduction s.\nsimpl.  reflexivity.\nsimpl.  intros.  eapply IHs.\nQed.\n\nLemma matches_Not : forall s r,  (Not r) ~= s = negb (r ~= s).\nProof. hammer_hook \"Boolean\" \"Boolean.matches_Not\".\ninduction s.\nsimpl.  reflexivity.\nsimpl.  intros.  eapply IHs.\nQed.\n\n\n\n\nLemma Or_comm_s : forall s r r', (r || r') ~= s = (r' || r) ~= s.\nProof. hammer_hook \"Boolean\" \"Boolean.Or_comm_s\".\nintros s r r'.  repeat erewrite matches_Or.\ndestruct (r ~= s); destruct (r' ~= s); reflexivity.\nQed.\n\nTheorem Or_comm : forall r r', r || r' =R= r' || r.\nProof. hammer_hook \"Boolean\" \"Boolean.Or_comm\".\nunfold re_eq.  intros r r' s.  eapply Or_comm_s.\nQed.\n\nLemma Or_assoc_s : forall s r r' r'',\n((r || r') || r'') ~= s = (r || (r' || r'')) ~= s.\nProof. hammer_hook \"Boolean\" \"Boolean.Or_assoc_s\".\nintros.   repeat erewrite matches_Or.\ndestruct (r ~= s); destruct (r' ~= s); destruct (r'' ~= s); reflexivity.\nQed.\n\nTheorem Or_assoc : forall r r' r'', (r || r') || r'' =R= r || (r' || r'').\nProof. hammer_hook \"Boolean\" \"Boolean.Or_assoc\".\nunfold re_eq.  intros r r' r'' s.  eapply Or_assoc_s.\nQed.\n\nLemma And_comm : forall r r', And r r' =R= And r' r.\nProof. hammer_hook \"Boolean\" \"Boolean.And_comm\".\nunfold re_eq.  intros r r' s.  repeat erewrite matches_And.\ndestruct (r ~= s); destruct (r' ~= s); reflexivity.\nQed.\n\nLemma And_assoc : forall r r' r'', And (And r r') r'' =R= And r (And r' r'').\nProof. hammer_hook \"Boolean\" \"Boolean.And_assoc\".\nunfold re_eq.  intros r r' r'' s.  repeat erewrite matches_And.\ndestruct (r ~= s); destruct (r' ~= s); destruct (r'' ~= s); reflexivity.\nQed.\n\n\n\nLemma Or_left_id_s : forall s r, (Empty || r) ~= s = r ~= s.\nProof. hammer_hook \"Boolean\" \"Boolean.Or_left_id_s\".\ninduction s.\nsimpl.  reflexivity.\nsimpl.  intros r.  eapply IHs.\nQed.\n\nTheorem Or_left_id : forall r, Empty || r =R= r.\nProof. hammer_hook \"Boolean\" \"Boolean.Or_left_id\".\nunfold re_eq.  intros r s.  eapply Or_left_id_s.\nQed.\n\nTheorem Or_right_id : forall r, r || Empty =R= r.\nintros.  setoid_rewrite Or_comm.\neapply Or_left_id.\nQed.\n\nCorollary Or_right_id_s : forall s r, (r || Empty) ~= s = r ~= s.\nProof. hammer_hook \"Boolean\" \"Boolean.Or_right_id_s\".\nintros s r.  specialize Or_right_id.\nintros H.  unfold re_eq in H.  eapply H.\nQed.\n\n\n\nLemma Or_idem_s : forall s r, (r || r) ~= s = r ~= s.\nProof. hammer_hook \"Boolean\" \"Boolean.Or_idem_s\".\nintros s r.  erewrite matches_Or.  destruct (r ~= s); reflexivity.\nQed.\n\nTheorem Or_idem : forall r, r || r =R= r.\nProof. hammer_hook \"Boolean\" \"Boolean.Or_idem\".\nunfold re_eq.  intros r s.  eapply Or_idem_s.\nQed.\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/regexp/Boolean.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.2759745958884768}}
{"text": "From Coq Require Import\n     Arith Lia (* nia *)\n     Morphisms\n.\n\nFrom ExtLib Require Import\n     Data.String\n.\n\nFrom ITree Require Import\n     Axioms\n     ITree\n     ITreeFacts\n     Events.MapDefault\n     Events.State\n     Events.StateFacts\n     Props.Infinite.\n\nFrom ITree.Extra Require Import\n     Dijkstra.DijkstraMonad\n     Dijkstra.PureITreeBasics\n     Dijkstra.IterRel\n     Dijkstra.DelaySpecMonad\n     Dijkstra.StateSpecT\n     Dijkstra.StateDelaySpec\n.\n\nFrom Paco Require Import paco.\n\nFrom hoare Require Import Imp.\n\nImport Monads.\nImport MonadNotation.\nImport ImpNotations.\n#[local] Open Scope monad_scope.\n#[local] Open Scope itree_scope.\n#[local] Open Scope imp_scope.\n\nDefinition denote_imp (c : com) : stateT env Delay unit :=\n  interp_imp (denote_com c).\n\nDefinition hoare_triple (P Q : env -> Prop) (c : com) : Prop :=\n  forall (s s' :env), P s -> (denote_imp c s ≈ ret (s',tt)) -> Q s'.\n\nDefinition lift_imp_post (P : env -> Prop) : Delay (env * unit) -> Prop :=\n  fun (t : Delay (env * unit) ) => (exists (s : env), ret (s, tt) ≈ t /\\ P s).\n\nNotation \"{{ P }} c {{ Q }}\" := (hoare_triple P Q c) (at level 70).\n\nDefinition is_bool (E : Type -> Type) (bc : bool) (be : bexp) (s : env) : Prop :=\n   @interp_imp E bool (denote_bexp be) s ≈ ret (s, bc).\n\nDefinition is_true (b : bexp) (s : env) : Prop :=\n  is_bool void1 true b s.\n\nDefinition is_false  (b : bexp) (s : env) : Prop :=\n  is_bool void1 false b s.\n\n(*\nLtac unf_intep := unfold interp_imp, interp_map, interp_state, interp, Basics.iter, MonadIter_stateT0, interp, Basics.iter, MonadIter_stateT0.\n*)\n\nLemma aexp_term : forall (E : Type -> Type) (ae : aexp) (s : env),\n    exists (n : nat), @interp_imp void1 _ (denote_aexp ae) s ≈ Ret (s,n).\nProof.\n  intros. induction ae.\n  - exists n. cbn. tau_steps. reflexivity.\n    (*getvar case, extract to a lemma*)\n  - cbn. exists (lookup_default x 0 s).\n    tau_steps. reflexivity.\n  - basic_solve. exists (n0 + n)%nat.\n    cbn. setoid_rewrite interp_imp_bind. rewrite IHae1.\n    setoid_rewrite bind_ret_l. setoid_rewrite interp_imp_bind. rewrite IHae2.\n    tau_steps. reflexivity.\n  - basic_solve. exists (n0 - n)%nat.\n    cbn. setoid_rewrite interp_imp_bind. rewrite IHae1.\n    setoid_rewrite bind_ret_l. setoid_rewrite interp_imp_bind. rewrite IHae2.\n    tau_steps. reflexivity.\n  - basic_solve. exists (n0 * n)%nat.\n    cbn. setoid_rewrite interp_imp_bind. rewrite IHae1.\n    setoid_rewrite bind_ret_l. setoid_rewrite interp_imp_bind. rewrite IHae2.\n    tau_steps. reflexivity.\nQed.\n\nLemma bools_term : forall (be : bexp) (s : env),\n    exists (bc : bool), @interp_imp void1 _ (denote_bexp be) s ≈ Ret (s,bc).\nProof.\n  intros. induction be.\n  - exists true. cbn. unfold interp_imp, interp_map, interp_state. repeat rewrite interp_ret.\n    tau_steps. reflexivity.\n  - exists false. tau_steps. reflexivity.\n  - specialize (aexp_term void1 a1 s) as Ha1. specialize (aexp_term void1 a2 s) as Ha2.\n    basic_solve. exists (n0 =? n)%nat.\n    cbn. setoid_rewrite interp_imp_bind. rewrite Ha1.\n    setoid_rewrite bind_ret_l. setoid_rewrite interp_imp_bind.\n    rewrite Ha2. tau_steps. reflexivity.\n  - specialize (aexp_term void1 a1 s) as Ha1. specialize (aexp_term void1 a2 s) as Ha2.\n    basic_solve. exists (n0 <=? n).\n    cbn. setoid_rewrite interp_imp_bind. rewrite Ha1.\n    setoid_rewrite bind_ret_l. setoid_rewrite interp_imp_bind.\n    rewrite Ha2. tau_steps. reflexivity.\n  - basic_solve. exists (negb bc). cbn.\n    setoid_rewrite interp_imp_bind. rewrite IHbe. tau_steps.\n    reflexivity.\n  - basic_solve. exists (bc0 && bc)%bool.\n    cbn. setoid_rewrite interp_imp_bind. rewrite IHbe1. setoid_rewrite bind_ret_l.\n    cbn. setoid_rewrite interp_imp_bind. rewrite IHbe2. tau_steps.\n    reflexivity.\nQed.\n\nLemma classic_bool : forall (b : bexp) (s : env), is_true b s \\/ is_false b s.\nProof.\n  intros. specialize (bools_term b s) as Hbs.\n  basic_solve. destruct bc; auto.\nQed.\n\n(*   *)\n\nLemma hoare_seq : forall (c1 c2 : com) (P Q R : env -> Prop), {{P}} c1 {{Q}} -> {{Q}} c2 {{R}}  ->\n                                                               {{P}} c1 ;;; c2 {{R}}.\nProof.\n  unfold hoare_triple. intros c1 c2 P Q R Hc1 Hc2 s s' Hs Hs'.\n  unfold denote_imp in Hs'. cbn in Hs'. rewrite interp_imp_bind in Hs'.\n  fold (denote_imp c1) in Hs'. fold (denote_imp c2) in Hs'.\n  destruct (eutt_reta_or_div (denote_imp c1 s) ); basic_solve.\n  - destruct a as [s'' [] ]. rewrite <- H in Hs'. setoid_rewrite bind_ret_l in Hs'. symmetry in H.\n    eapply Hc2; eauto.\n  - apply div_spin_eutt in H. rewrite H in Hs'. rewrite <- spin_bind in Hs'.\n    symmetry in Hs'. exfalso. eapply not_ret_eutt_spin. eauto.\nQed.\n\nLemma hoare_if : forall (c1 c2 : com) (b : bexp) (P Q : env -> Prop),\n    {{fun s => is_true b s /\\ P s}} c1 {{Q}} ->\n    {{fun s => is_false b s /\\ P s}} c2 {{Q}} ->\n    {{ P }} TEST b THEN c1 ELSE c2 FI {{Q}}.\nProof.\n  unfold hoare_triple. intros c1 c2 b P Q Hc1 Hc2 s s' Hs.\n  unfold denote_imp. cbn.\n  destruct (classic_bool b s).\n  - unfold is_true, is_bool in H. rewrite interp_imp_bind.\n    rewrite H. setoid_rewrite bind_ret_l. apply Hc1. auto.\n  - unfold is_false, is_bool in H. rewrite interp_imp_bind.\n    rewrite H. setoid_rewrite bind_ret_l. apply Hc2. auto.\nQed.\n\nDefinition app {A B : Type} (f : A -> B) (a : A) := f a.\n\nDefinition run_state_itree {A S : Type} {E : Type -> Type} (s : S) (m : stateT S (itree E) A )  : itree E (S * A) :=\n  m s.\n\nGlobal Instance EqStateEq {S R: Type} {E : Type -> Type} : Equivalence (@state_eq E R S).\nProof.\n  constructor; repeat intro.\n  - reflexivity.\n  -  unfold state_eq in H. symmetry. auto.\n  - unfold state_eq in *. rewrite H. auto.\nQed.\n\nGlobal Instance run_state_proper_eq_itree {E : Type -> Type} {S R : Type} {s : S} :\n  Proper (@state_eq E S R ==> eq_itree eq) (@run_state_itree R S E s).\nProof.\n  repeat intro. unfold run_state_itree. unfold state_eq in H. rewrite H. reflexivity.\nQed.\n\nGlobal Instance run_state_proper_eutt {E : Type -> Type} {S R : Type} {s : S} :\n  Proper (@state_eq E S R ==> eutt eq) (@run_state_itree R S E s).\nProof.\n  repeat intro. unfold run_state_itree. unfold state_eq in H. rewrite H. reflexivity.\nQed.\n\nGlobal Instance eutt_proper_under_interp_state\n       {E F: Type -> Type} {S R : Type} {h : E ~> stateT S (itree F) } :\n  Proper (eq_itree eq ==> @state_eq F S R) (fun (t : itree E R) =>  interp_state h t).\nProof.\n  repeat intro. unfold interp_state. rewrite H. reflexivity.\nQed.\n\n(*\nCheck (case_ (handle_map (V := value) pure_state ) ).\n\nTimeout 5 Definition run_state_map {value A : Type} (t : itree (mapE var 0 +' void1)  A) s  : itree void1 ( env * A):=\n  interp_state (case_ (handle_map (V := value) ) pure_state) t s.\n*)\n\nSection interp_state_eq_iter.\n  Context {E F: Type -> Type}.\n  Context (S : Type).\n  Context (f : E ~> stateT S (itree F) ).\n  Context (A B : Type).\n  Context (g : A ->itree E (A + B) ).\n  Context (a : A).\n\n\n  Lemma interp_state_eq_iter : state_eq (interp_state f (ITree.iter g a) )\n                              (MonadIter_stateT0 _ _ (fun a0 => interp_state f (g a0)) a).\n  Proof.\n    unfold ITree.iter, Iter_Kleisli, Basics.iter, MonadIter_itree.\n    eapply interp_state_iter; reflexivity.\n  Qed.\n\nEnd interp_state_eq_iter.\nSet Default Timeout 15.\n\nGlobal Instance proper_state_eq_iter {S: Type} :\n  Proper (@state_eq void1 S (unit + unit) ==> @state_eq void1 S (unit) ) (fun body => @MonadIter_stateT0 Delay S _ _ unit unit (fun _ : unit => body) tt ).\nProof.\n  repeat intro.\n  unfold MonadIter_stateT0, Basics.iter, MonadIterDelay. eapply eq_itree_iter.\n  repeat intro. subst. destruct y0 as [s' [] ].\n  simpl. specialize (H s'). rewrite H. reflexivity.\nQed.\n\nLemma interp_state_bind_state : forall (E F : Type -> Type) (A B S : Type)\n                   (h : forall T : Type, E T -> S -> itree F (S * T) ) (t : itree E A)\n                   (k : A -> itree E B),\n    state_eq (interp_state h (ITree.bind t k))\n             (bind (interp_state h t) (fun a => interp_state h (k a) ) ).\n\nProof.\n  unfold state_eq. intros. eapply interp_state_bind.\nQed.\n\nDefinition state_eq2 {E : Type -> Type} {A B S : Type} (k1 k2 : A -> stateT S (itree E) B ) : Prop :=\n  forall a, state_eq (k1 a)  (k2 a).\n\nLemma eq_itree_clo_bind {E : Type -> Type} {R1 R2 : Type} :\n  forall (RR : R1 -> R2 -> Prop) (U1 U2 : Type) (UU : U1 -> U2 -> Prop)\n         (t1 : itree E U1) (t2 : itree E U2)\n         (k1 : U1 -> itree E R1) (k2 : U2 -> itree E R2),\n    eq_itree UU t1 t2 ->\n    (forall (u1 : U1) (u2 : U2), UU u1 u2 -> eq_itree RR (k1 u1) (k2 u2)  ) ->\n    eq_itree RR (ITree.bind t1 k1) (ITree.bind t2 k2).\nProof.\n  intros. unfold eq_itree in *. eapply eqit_bind'; eauto.\nQed.\n\n\nGlobal Instance bind_state_eq2 {E : Type -> Type} {A B S : Type} {m : stateT S (itree E) A} :\n  Proper (@state_eq2 E A B S ==> @state_eq E S B) (bind m).\nProof.\n  repeat intro. unfold state_eq2, state_eq in H. cbn.\n  eapply eq_itree_clo_bind; try reflexivity. intros. subst.\n  destruct u2 as [s' a]. simpl. rewrite H. reflexivity.\nQed.\n\n(*can actually make this nicer*)\nLemma compile_while : forall (b : bexp) (c : com),\n                             ((denote_imp ( WHILE b DO c END )) ≈ MonadIter_stateT0 unit unit\n                                         (fun _ : unit => bind (interp_imp (denote_bexp b))\n                                                               (fun b : bool => if b\n                                                                         then bind (denote_imp c) (fun _ : unit => interp_imp (Ret (inl tt)) )\n                                                                         else interp_imp (Ret (inr tt))) ) tt)%monad.\nProof.\n  intros. simpl. unfold denote_imp. simpl. unfold while. unfold interp_imp at 1, interp_map at 1.\n  cbn. red. red. intros. symmetry.\n  rewrite interp_iter. do 3 red.\n  match goal with | |- _ ≈ ?m _ => set m as while_denote; fold while_denote end.\n  assert (Hwhile_rewrite : state_eq while_denote while_denote); try reflexivity.\n  unfold while_denote in Hwhile_rewrite at 2.\n  setoid_rewrite interp_state_eq_iter in Hwhile_rewrite.\n  fold (run_state_itree s while_denote). rewrite Hwhile_rewrite.\n  clear Hwhile_rewrite. unfold run_state_itree.\n  match goal with |- MonadIter_stateT0 _ _ (fun _ :unit => ?m1) _ _ ≈ MonadIter_stateT0 _ _ (fun _ : unit => ?m2) _ _ =>\n                  enough (state_eq m1 m2) end.\n  - eapply proper_state_eq_iter in H.\n    match goal with |- ?m1 s ≈ ?m2 s => set m1 as while_denote1; fold while_denote1;\n                                        set m2 as while_denote2; fold while_denote2 end.\n    fold (run_state_itree s while_denote1). fold (run_state_itree s while_denote2).\n    unfold while_denote1. unfold while_denote2. rewrite H. reflexivity.\n - rewrite interp_bind. rewrite interp_state_bind_state.\n   clear s. intro s. eapply eq_itree_clo_bind; try reflexivity.\n   intros. subst. destruct u2 as [s' b0 ]. simpl. destruct b0.\n   + rewrite interp_bind. rewrite interp_state_bind.\n     unfold interp_imp, interp_map. reflexivity.\n   + unfold interp_imp, interp_map. reflexivity.\nQed.\n\n\n\n\nLemma hoare_while : forall (c : com) (b : bexp) (P : env -> Prop),\n    {{fun s => is_true b s /\\ P s}} c {{ P  }} ->\n    {{ P }} WHILE b DO c END {{ fun s => is_false b s /\\ P s}}.\nProof.\n  unfold hoare_triple. intros.\n  specialize (compile_while b c) as Hbc. red in Hbc. red in Hbc.\n  rewrite Hbc in H1. clear Hbc.\n  specialize (loop_invar_state env unit unit) as Hloop. unfold State in Hloop.\n  rename H1 into Heutt. rename H0 into Hs.\n  set ((fun _ : unit =>\n             b <-\n             interp_imp\n               (denote_bexp b);;\n             (if b\n              then\n               _ <- denote_imp c;;\n               interp_imp\n                 (Ret (inl tt))\n              else\n               interp_imp\n                 (Ret (inr tt))))) as body.\n  split.\n  - set (fun (t : Delay (env * unit) ) =>\n           (exists s, t ≈ ret (s,tt) /\\ is_false b s) \\/ any_infinite t\n        ) as p.\n    set (fun (t : Delay (env * unit + env * unit)) =>\n           (exists s, (t ≈ ret (inl (s,tt)) ) \\/ ((t ≈ ret (inr (s,tt)) /\\ is_false b s)) )  \\/ any_infinite t\n        ) as q.\n    assert (resp_eutt p) as Hp.\n    {\n      unfold p. unfold is_false, is_bool.\n      intros t1 t2 He. split; intro; basic_solve.\n      - left. exists s0.  split; auto. rewrite <- He. auto.\n      - rewrite He in H0. auto.\n      - left. exists s0. split; auto. rewrite He. auto.\n      - rewrite <- He in H0. auto.\n    }\n    assert (resp_eutt q) as Hq.\n    {\n      unfold q. unfold is_true, is_false, is_bool.\n      intros t1 t2 He. split; intros; basic_solve.\n      - left. exists s0. rewrite He in H0. auto.\n      - left. exists s0. rewrite He in H0. auto.\n      - rewrite He in H0. auto.\n      - left. exists s0. rewrite He. auto.\n      - left. exists s0. rewrite He. auto.\n      - rewrite <- He in H0. auto.\n    }\n   enough (p (Ret (s',tt) ) ).\n    {\n      unfold p in H0. basic_solve; auto. pinversion H0.\n    }\n    enough (p (CategoryOps.iter body tt s) ).\n    {\n      eapply Hp; try apply H0. unfold CategoryOps.iter, Iter_Kleisli, Basics.iter.\n      unfold body. symmetry. auto.\n    }\n    enough ((p \\1/ any_infinite) (CategoryOps.iter body tt s) ).\n    {\n      destruct H0; auto. unfold p. auto.\n    }\n    specialize Hloop with (s := s) (p := p) (q := q).\n    eapply Hloop; eauto.\n    + unfold reassoc. unfold body.\n      destruct (eutt_reta_or_div (interp_imp (denote_com c) s ) );\n      destruct (classic_bool b s); basic_solve.\n      * do 2 red in H1. unfold interp_imp, interp_map in H1.\n        destruct a as [s'' [] ].\n        eapply Hq.\n        -- cbn. setoid_rewrite bind_bind.\n           rewrite H1.\n           setoid_rewrite bind_ret_l. simpl.\n           setoid_rewrite bind_bind. rewrite <- H0.\n           tau_steps. reflexivity.\n        -- unfold q. left. exists s''. left. reflexivity.\n      * do 2 red in H1. unfold interp_imp, interp_map in H1.\n        destruct a as [s'' [] ].\n        eapply Hq.\n        -- cbn. rewrite H1. setoid_rewrite bind_bind. setoid_rewrite bind_ret_l.\n           simpl. tau_steps. reflexivity.\n        -- unfold q. left. exists s. right. split; auto. reflexivity.\n      * do 2 red in H1. unfold interp_imp, interp_map in H1.\n        eapply Hq.\n        -- cbn. rewrite H1. setoid_rewrite bind_bind. setoid_rewrite bind_ret_l.\n           simpl. apply div_spin_eutt in H0. rewrite H0. setoid_rewrite bind_bind.\n           rewrite <- spin_bind. reflexivity.\n        -- red. right. apply spin_infinite.\n      * do 2 red in H1. unfold interp_imp, interp_map in H1.\n        eapply Hq.\n        -- cbn. rewrite H1. setoid_rewrite bind_bind. setoid_rewrite bind_ret_l.\n           simpl. apply div_spin_eutt in H0.\n           tau_steps. reflexivity.\n        -- red. left. exists s. right. split; auto; reflexivity.\n   + unfold q,p. unfold DelaySpecMonad.loop_invar_imp. intros.\n     basic_solve.\n     * cbn in H0. exfalso. destruct (eutt_reta_or_div t); basic_solve.\n       -- rewrite <- H1 in H0. setoid_rewrite bind_ret_l in H0. basic_solve.\n       -- apply div_spin_eutt in H1. rewrite H1 in H0. rewrite <- spin_bind in H0.\n          symmetry in H0. eapply not_ret_eutt_spin; eauto.\n     * cbn in H0. destruct (eutt_reta_or_div t); basic_solve; auto.\n       rewrite <- H2 in H0. setoid_rewrite bind_ret_l in H0. basic_solve. left.\n       exists s0. split; auto. symmetry. auto.\n     * right. destruct (eutt_reta_or_div t); basic_solve; auto.\n       cbn in H0. rewrite <- H1 in H0. setoid_rewrite bind_ret_l in H0.\n       pinversion H0.\n  + unfold q.\n    unfold DelaySpecMonad.iter_lift, iso_destatify_arrow, reassoc.\n    basic_solve; try (destruct (classic_bool b s0) );\n      try (destruct (eutt_reta_or_div (interp_imp (denote_com c) s0 ) )); basic_solve.\n    * eapply Hq.\n      -- cbn. rewrite H0. setoid_rewrite bind_ret_l.\n         setoid_rewrite bind_bind. do 2 red in H1. unfold interp_imp, interp_map in H1.\n         rewrite H1. setoid_rewrite bind_ret_l. simpl.\n         destruct a as [s1 [] ]. rewrite <- H2. setoid_rewrite bind_bind.\n         setoid_rewrite bind_ret_l. simpl. tau_steps. reflexivity.\n      -- red. left. destruct a as [s'' [] ]. exists s''. left. reflexivity.\n    * eapply Hq.\n      -- cbn. rewrite H0. setoid_rewrite bind_ret_l. setoid_rewrite bind_bind.\n         do 2 red in H1. unfold interp_imp, interp_map in H1. rewrite H1.\n         setoid_rewrite bind_ret_l. simpl. apply div_spin_eutt in H2. rewrite H2.\n         setoid_rewrite bind_bind. rewrite <- spin_bind. reflexivity.\n      -- right. apply spin_infinite.\n    * destruct a as [s'' [] ]. eapply Hq.\n      -- cbn.  rewrite H0. setoid_rewrite bind_ret_l.\n         do 2 red in H1. unfold interp_imp, interp_map in H1. rewrite H1.\n         setoid_rewrite bind_bind. setoid_rewrite bind_ret_l. simpl. tau_steps. reflexivity.\n      -- left. exists s0. right. split; auto. reflexivity.\n    * eapply Hq.\n      -- cbn.  rewrite H0. setoid_rewrite bind_ret_l.\n         do 2 red in H1. unfold interp_imp, interp_map in H1. rewrite H1.\n         setoid_rewrite bind_bind. setoid_rewrite bind_ret_l. simpl. tau_steps. reflexivity.\n      -- left. exists s0. right. split; auto. reflexivity.\n    * do 2 red in H1. do 2 red in H2. rewrite H1 in H2.\n      apply eutt_inv_Ret in H2. injection H2. discriminate.\n    * do 2 red in H1. do 2 red in H2. rewrite H1 in H2.\n      apply eutt_inv_Ret in H2. injection H2. discriminate.\n    * eapply Hq.\n      -- cbn.  rewrite H0. setoid_rewrite bind_ret_l.  reflexivity.\n      -- left. exists s0. right. split; auto. reflexivity.\n    * eapply Hq.\n      -- cbn.  rewrite H0. setoid_rewrite bind_ret_l.  reflexivity.\n      -- left. exists s0. right. split; auto. reflexivity.\n    * right. cbn. apply div_spin_eutt in H0. rewrite H0. rewrite <- spin_bind.\n      apply spin_infinite.\n   - set (fun (t : Delay (env * unit)) =>\n           (exists s, t ≈ ret (s,tt) /\\ P s ) \\/ any_infinite t\n        ) as p.\n    set (fun (t : Delay (env * unit + env * unit)) =>\n           (exists s, (t ≈ ret (inl (s,tt) ) \\/ t ≈ ret (inr (s,tt) ) ) /\\ P s )\\/ any_infinite t )  as q.\n    assert (resp_eutt p) as Hp.\n    {\n      unfold p. intros t1 t2 He. split; intros; basic_solve.\n      - left. exists s0. rewrite He in H0. auto.\n      - right. rewrite He in H0. auto.\n      - left.  exists s0. rewrite <- He in H0. split; auto.\n      - right. rewrite He. auto.\n    }\n      assert (resp_eutt q) as Hq.\n      {\n        unfold q. intros t1 t2 He. split; intros; basic_solve.\n        - left. exists s0. rewrite He in H0. auto.\n        - left. exists s0. rewrite He in H0. auto.\n        - right. rewrite He in H0. auto.\n        - left. rewrite <- He in H0. exists s0. auto.\n        - left. rewrite <- He in H0. exists s0. auto.\n        - right. rewrite He. auto.\n      }\n      specialize Hloop with (s := s) (p := p) (q := q).\n\n      enough (p (Ret (s',tt))).\n      {\n        unfold p in H0. basic_solve; auto. pinversion H0.\n      }\n      enough ((p \\1/ any_infinite) (CategoryOps.iter body tt s ) ).\n      {\n        destruct H0.\n        - eapply Hp; try apply H0. rewrite <- Heutt. reflexivity.\n        - unfold CategoryOps.iter, Iter_Kleisli, Basics.iter in H0.\n          unfold body in H0. rewrite Heutt in H0. pinversion H0.\n      }\n      eapply Hloop; eauto.\n      + unfold reassoc. unfold body. destruct (classic_bool b s).\n        * assert (is_true b s /\\ P s); auto.\n          destruct (eutt_reta_or_div (interp_imp (denote_com c) s) ); basic_solve.\n          -- destruct a as [s'' [] ].\n             unfold is_true, is_bool in H0.\n             unfold interp_imp, interp_map in H0.\n             eapply Hq.\n             ++ cbn. setoid_rewrite bind_bind. rewrite H0.\n                setoid_rewrite bind_ret_l. simpl. setoid_rewrite bind_bind.\n                rewrite <- H2. tau_steps.\n                reflexivity.\n             ++ specialize (H s s''). unfold q. left. exists s''. split; try (left; reflexivity).\n                eapply H; eauto. symmetry. auto.\n          -- apply div_spin_eutt in H2.\n             cbn. rewrite bind_bind.\n             unfold is_true, is_bool in H0.\n             unfold interp_imp, interp_map in H0. rewrite H0.\n             setoid_rewrite bind_ret_l. simpl. rewrite H2.\n             setoid_rewrite bind_bind. rewrite <- spin_bind.\n             right. apply spin_infinite.\n        * unfold is_false, is_bool, interp_imp, interp_map in H0. cbn.\n          eapply Hq.\n          -- setoid_rewrite bind_bind. rewrite H0. setoid_rewrite bind_ret_l.\n             simpl. cbn. tau_steps. reflexivity.\n          -- unfold q. left. exists s. split; auto. right. reflexivity.\n      + red. intros. unfold p. unfold q in H0. basic_solve.\n        * cbn in H0.\n          destruct (eutt_reta_or_div t); basic_solve.\n          -- destruct a as [s'' [] ]. rewrite <- H2 in H0.\n             setoid_rewrite bind_ret_l in H0. basic_solve.\n          -- exfalso. apply div_spin_eutt in H2. rewrite H2 in H0. rewrite <- spin_bind in H0.\n             symmetry in H0. apply not_ret_eutt_spin in H0. auto.\n        * cbn in H0.\n        destruct (eutt_reta_or_div t); basic_solve.\n        -- destruct a as [s'' [] ]. rewrite <- H2 in H0.\n           setoid_rewrite bind_ret_l in H0. basic_solve. left. exists s0.\n           symmetry in H2. auto.\n        -- exfalso. apply div_spin_eutt in H2. rewrite H2 in H0.\n           rewrite <- spin_bind in H0. symmetry in H0. apply not_ret_eutt_spin in H0. auto.\n      * cbn in H0. right. destruct (eutt_reta_or_div t); auto.\n        basic_solve. rewrite <- H1 in H0. setoid_rewrite bind_ret_l in H0.\n        pinversion H0.\n    + unfold DelaySpecMonad.iter_lift, iso_destatify_arrow, reassoc.\n      intros t Ht. cbn.\n      destruct (eutt_reta_or_div t);\n         basic_solve.\n      * destruct a as [s'' [] ].\n        destruct (classic_bool b s'');\n          destruct (eutt_reta_or_div (interp_imp (denote_com c) s'' )); basic_solve;\n        eapply Hq.\n        -- rewrite <- H0. setoid_rewrite bind_ret_l.\n           setoid_rewrite bind_bind. do 2 red in H1.\n           unfold interp_imp, interp_map in H1. rewrite H1. setoid_rewrite bind_ret_l.\n           simpl. setoid_rewrite bind_bind.\n           rewrite <- H2. setoid_rewrite bind_ret_l. destruct a as [s3 [] ].\n           simpl. tau_steps. reflexivity.\n        -- destruct a as [s3 [] ]. unfold q in Ht. basic_solve.\n           ++ rewrite  H3 in H0. basic_solve.\n              unfold q. left. exists s3. split; try (left; reflexivity). symmetry in H2.\n              cbn in H0. pinversion H0. subst. injection REL; intros; subst.\n              eapply H; eauto.\n           ++ rewrite H3 in H0. cbn in *; basic_solve; pinversion H0; try discriminate; basic_solve.\n           ++ rewrite <- H0 in H3. pinversion H3.\n        -- rewrite <- H0. setoid_rewrite bind_ret_l. setoid_rewrite bind_bind.\n           do 2 red in H1. unfold interp_imp, interp_map in H1. rewrite H1.\n           setoid_rewrite bind_ret_l. simpl. apply div_spin_eutt in H2.\n           setoid_rewrite bind_bind. rewrite H2.\n           rewrite <- spin_bind. reflexivity.\n        -- unfold q. right. apply spin_infinite.\n        -- rewrite <- H0. setoid_rewrite bind_ret_l.\n           unfold is_false, is_bool in H1. unfold interp_imp, interp_map in H1.\n           rewrite H1. setoid_rewrite bind_bind. setoid_rewrite bind_ret_l. simpl.\n           tau_steps. reflexivity.\n        -- unfold q. left. exists s''. split; try (right; reflexivity). unfold q in Ht.\n           basic_solve.\n           ++ rewrite H3 in H0. basic_solve. auto. pinversion H0. injection REL; intros; subst; auto.\n           ++ rewrite H3 in H0. basic_solve. pinversion H0. discriminate.\n           ++ rewrite <- H0 in H3. pinversion H3.\n        -- rewrite <- H0. setoid_rewrite bind_ret_l.\n           setoid_rewrite bind_bind.\n           do 2 red in H1. unfold interp_imp, interp_map in H1.\n           rewrite H1. setoid_rewrite bind_ret_l. simpl. tau_steps.\n           reflexivity.\n        -- unfold q. left. exists s''.\n           split; try (right; reflexivity). unfold q in Ht.\n           basic_solve.\n           ++ rewrite H3 in H0. basic_solve. pinversion H0; injection REL; intros; subst; auto.\n           ++ rewrite H3 in H0. basic_solve. pinversion H0; discriminate.\n           ++ rewrite <- H0 in H3. pinversion H3.\n     * destruct b0 as [s'' [] ]. eapply Hq.\n       -- rewrite <- H0. setoid_rewrite bind_ret_l.\n          reflexivity.\n       -- unfold q. left. exists s''. split; try (right; reflexivity).\n          unfold q in Ht. basic_solve.\n          ++ rewrite H1 in H0. basic_solve. pinversion H0. discriminate.\n          ++ rewrite H1 in H0. basic_solve. pinversion H0; injection REL; intros; subst; auto.\n          ++ rewrite <- H0 in H1. pinversion H1.\n     * clear Ht. unfold q. right. apply div_spin_eutt in H0.\n       rewrite H0. rewrite <- spin_bind. apply spin_infinite.\n\nQed.\n\nLemma denote_imp_bind : forall (c1 c2 : com), state_eq (denote_imp (c1 ;;; c2)) (denote_imp c1 ;; denote_imp c2).\nProof.\n  intros. intro. cbn. unfold denote_imp. simpl. setoid_rewrite interp_imp_bind.\n  eapply eq_itree_clo_bind; try reflexivity. intros. subst. destruct u2. reflexivity.\nQed.\n\nDefinition state_eq_eutt {R S : Type} {E : Type -> Type} (m0 m1 : stateT S (itree E) R) :Prop :=\n  forall s, m0 s ≈ m1 s.\n\nGlobal Instance equiv_state_eq_eutt {R S} {E} : Equivalence (@state_eq_eutt R S E).\nProof.\n  constructor; red; red; intros.\n  - reflexivity.\n  - red in H. rewrite H. reflexivity.\n  - red in H. red in H0.  rewrite H. rewrite H0. reflexivity.\nQed.\n\nLemma state_eq_sub_state_eutt : forall (E : Type -> Type) (R S: Type) ,\n    subrelation (@state_eq E S R) state_eq_eutt.\nProof.\n  red. intros E R S m0 m1 Heq.\n  red. red in Heq. intros. rewrite Heq. reflexivity.\nQed.\n\nGlobal Instance state_eq_prop_state_eutt {R S} {E} : Proper (@state_eq E S R ==> state_eq ==> impl) state_eq_eutt.\nProof.\n  red. red. intros m0 m1 Heq0. red. intros m2 m3. intros Heq2.\n  red. intros. red. red in H. red in Heq2. red in Heq0. intros.\n  rewrite <- Heq2. rewrite <- H. rewrite Heq0. reflexivity.\nQed.\n\nLemma set_var_val_interp : forall x n E, @state_eq_eutt _ _ E (interp_imp (trigger (SetVar x n))) (fun s => Ret (Maps.add x n s,tt)).\nProof.\n  intros. intro. tau_steps. reflexivity.\nQed.\n\nFixpoint compute_aexp (a : aexp) (s : env) : value :=\n  match a with\n  | ANum n => n\n  | AId x => lookup_default x 0 s\n  | APlus a1 a2 => (compute_aexp a1 s) + (compute_aexp a2 s)\n  | AMinus a1 a2 => (compute_aexp a1 s) - (compute_aexp a2 s)\n  | AMult a1 a2 => (compute_aexp a1 s) * (compute_aexp a2 s)\n  end.\n\n\nFixpoint compute_bexp (b : bexp) (s : env)  : bool :=\n  match b with\n  | BTrue => true\n  | BFalse => false\n  | BEq a1 a2 => (compute_aexp a1 s) =? (compute_aexp a2 s)\n  | BLe a1 a2 => (compute_aexp a1 s) <=? (compute_aexp a2 s)\n  | BNot b0 => negb (compute_bexp b0 s)\n  | BAnd b1 b2 => (compute_bexp b1 s) && (compute_bexp b2 s)\n  end.\n\nLemma compute_aexp_sc : forall (a : aexp),\n    @state_eq_eutt value env void1 (interp_imp (denote_aexp a)) (fun s => Ret (s, compute_aexp a s)).\nProof.\n  intros. red. intros. induction a; simpl;\n  try (tau_steps; reflexivity);\n  try (rewrite interp_imp_bind; rewrite IHa1; rewrite bind_ret_l;\n    rewrite interp_imp_bind; rewrite IHa2; rewrite bind_ret_l; tau_steps; reflexivity).\nQed.\n\nLemma compute_aexp_sc_tree : forall (a : aexp) (s : env),\n    (@interp_imp void1 value (denote_aexp a) s) ≈ (Ret (s, compute_aexp a s) ).\nProof.\n  intros. apply compute_aexp_sc.\nQed.\n\n\nLemma compute_bexp_sc : forall (b : bexp),\n    @state_eq_eutt bool env void1 (interp_imp (denote_bexp b) ) (fun s => Ret (s, compute_bexp b s)).\nProof.\n  intros. red. intros. induction b; simpl;\n  try (tau_steps; reflexivity).\n  - rewrite interp_imp_bind. rewrite compute_aexp_sc_tree.\n    rewrite bind_ret_l. rewrite interp_imp_bind. rewrite compute_aexp_sc_tree.\n    rewrite bind_ret_l. tau_steps. reflexivity.\n  - rewrite interp_imp_bind. rewrite compute_aexp_sc_tree.\n    rewrite bind_ret_l. rewrite interp_imp_bind. rewrite compute_aexp_sc_tree.\n    rewrite bind_ret_l. tau_steps. reflexivity.\n  - rewrite interp_imp_bind. rewrite IHb. rewrite bind_ret_l.\n    tau_steps. reflexivity.\n  - rewrite interp_imp_bind. rewrite IHb1. rewrite bind_ret_l.\n    rewrite interp_imp_bind. rewrite IHb2. rewrite bind_ret_l.\n    tau_steps. reflexivity.\nQed.\n\nLemma compute_bexp_sc_tree : forall (b : bexp) (s : env),\n    (@interp_imp void1 bool (denote_bexp b) s ) ≈ (Ret (s, compute_bexp b s) ).\nProof.\n  intros. apply compute_bexp_sc.\nQed.\n\nDefinition inc_var (x : var) (s : env) : env:=\n  Maps.add x (1 + lookup_default x 0 s)%nat  s.\n\nLemma compute_assign_sc : forall (x : var) (a : aexp),\n    state_eq_eutt (@interp_imp void1 unit (denote_com (x ::= a) ) )\n                  (fun s => Ret (Maps.add x (compute_aexp a s) s, tt) ).\nProof.\n  intros. simpl. intro. rewrite interp_imp_bind.\n  rewrite compute_aexp_sc_tree. rewrite bind_ret_l. tau_steps. reflexivity.\nQed.\n\nLemma compute_assign_sc_tree : forall (x : var) (a : aexp) (s : env),\n    (@interp_imp void1 unit (denote_com (x ::= a)) s ) ≈ Ret (Maps.add x (compute_aexp a s) s, tt ).\nProof.\n  intros. apply compute_assign_sc.\nQed.\n(*state_eq_eutt is proper wrt to verify_cond*)\n\nGlobal Instance proper_verify_cond {S A : Type} {w : StateDelaySpec S A} :\n  Proper (state_eq_eutt ==> iff) (verify_cond S w).\nProof.\n  repeat intro. unfold verify_cond, DijkstraProp. split; intros.\n  - repeat red in H0. repeat red. intros. specialize (H0 s p). destruct p as [p Hp].\n    simpl in *.\n    eapply Hp; [symmetry; apply H | eauto].\n  - repeat red in H0. repeat red. intros. specialize (H0 s p). destruct p as [p Hp].\n    simpl in *.\n    eapply Hp; auto.\nQed.\n\nGlobal Instance proper_verify_cond_strong {S A : Type} {w : StateDelaySpec S A} :\n  Proper (state_eq ==> iff) (verify_cond S w).\nProof.\n  repeat intro. unfold verify_cond, DijkstraProp. split; intros.\n  - repeat red in H0. repeat red. intros. specialize (H0 s p). destruct p as [p Hp].\n    simpl in *. apply state_eq_sub_state_eutt in H.\n    eapply Hp; [symmetry|]; auto.\n  - repeat red in H0. repeat red. intros. specialize (H0 s p). destruct p as [p Hp].\n    simpl in *. apply state_eq_sub_state_eutt in H. eapply Hp; eauto.\nQed.\n\nGlobal Instance state_eutt_iter {A B S: Type} {E : Type -> Type} :\n  Proper (pointwise_relation A (@state_eq_eutt (A + B) S E ) ==>\n                             pointwise_relation A (@state_eq_eutt B S E) ) (MonadIter_stateT0 B A).\nProof.\n  repeat intro. red in H. red. red. unfold MonadIter_stateT0.\n  apply eutt_iter. red. intros. destruct a0 as [s' a']. simpl. red in H.\n  rewrite H. reflexivity.\nQed.\n\nGlobal Instance state_eutt_bind_l {A B S : Type} {E : Type -> Type} :\n  Proper ((@state_eq_eutt A S E) ==> pointwise_relation _ (@state_eq_eutt B S E)  ) bind.\nProof.\n  unfold Proper, respectful, pointwise_relation. intros m0 m1 Heutt k.\n  intro. cbn. red in Heutt. rewrite Heutt. reflexivity.\nQed.\n(*we need a way to generate properness goals, this is fucking ridiculous*)\nGlobal Instance state_eutt_bind_r {A B S : Type} {E : Type -> Type}\n       {m : stateT S (itree E) A } :\n  Proper ((pointwise_relation _ state_eq_eutt) ==>  (@state_eq_eutt B S E )  ) (bind m).\nProof.\n  repeat intro. rename x into k0. rename y into k1. rename H into Heutt.\n  red. red. red in Heutt. red in Heutt. cbn.\n  eapply eutt_clo_bind; try reflexivity. intros. subst. destruct u2 as [s' a]. simpl.\n  rewrite Heutt. reflexivity.\nQed.\n\nGlobal Instance state_eutt_bind_l' {A B S : Type} {E : Type -> Type} :\n  Proper ((@state_eq_eutt A S E) ==> pointwise_relation _ (@state_eq_eutt B S E) ==> state_eq_eutt  ) bind.\nProof.\n  unfold Proper, respectful, pointwise_relation. intros m0 m1 Hmeutt k0 k1 Hkeutt.\n  intro. cbn. red in Hmeutt. rewrite Hmeutt.\n  eapply eutt_clo_bind; try reflexivity. intros. subst. destruct u2 as [s' a].\n  simpl. red in Hkeutt. rewrite Hkeutt. reflexivity.\nQed.\n\nGlobal Instance run_state_eutt_proper_eutt : forall (E : Type -> Type) (S R : Type) (s : S),\n          Proper (@state_eq_eutt R S E  ==> eutt eq) (run_state_itree s).\nProof.\n  repeat intro. red in H. unfold run_state_itree. rewrite H. reflexivity.\nQed.\n\nLemma lookup_nin : forall (x : var) (s : env), (forall v : value, ~ Maps.mapsto x v s) -> Maps.lookup x s = None.\nProof.\n  intros. red in s. red in s. generalize dependent x. induction s; intros; auto.\n  - cbn. destruct a as [y v]. destruct (Strings.String.string_dec x y).\n    + subst. exfalso. apply (H v). red. cbn. red. cbn.\n      rewrite RelDec.rel_dec_eq_true; auto. apply RelDec_Correct_string.\n    + rewrite RelDec.rel_dec_neq_false; auto; try apply RelDec_Correct_string.\n      unfold Maps.lookup in IHs. cbn in *. apply IHs; auto. intros.\n      intro Hcontra. apply (H v0). red. cbn.\n      rewrite RelDec.rel_dec_neq_false; auto; try apply RelDec_Correct_string.\nQed.\n\n\nLemma lookup_neq : forall (s : env) (x y: var) (v d: value), x <> y ->\n                lookup_default x d (Maps.add y v s)  = lookup_default x d s.\nProof.\n\n  intros.\n  destruct (classic (exists v', Maps.mapsto x v' s)).\n  - destruct H0 as [v' Hv'].\n    assert (Maps.mapsto x v' (Maps.add y v s)).\n    {\n      eapply Maps.mapsto_add_neq in Hv'; eauto.\n    }\n    apply Maps.mapsto_lookup in H0. apply Maps.mapsto_lookup in Hv'. unfold lookup_default.\n    rewrite Hv'. rewrite H0. auto.\n  - assert (forall v',~ Maps.mapsto x v' s).\n    { intros v' Hc. apply H0. exists v'. auto. }\n    clear H0. apply lookup_nin in H1 as Hs. unfold lookup_default.\n    rewrite Hs.\n    assert (forall v', ~Maps.mapsto x v' (Maps.add y v s)).\n    {\n      intros v' Hcontra. apply Maps.mapsto_add_neq in Hcontra; auto.\n      eapply H1; eauto.\n    }\n    apply lookup_nin in H0 as Hs'. rewrite Hs'. auto.\nQed.\n\n\nLemma lookup_eq : forall (s : env) (x : var) (v d : value),\n    lookup_default x d (Maps.add x v s) = v.\nProof.\n  intros. assert (Maps.mapsto x v (Maps.add x v s) ).\n  { apply Maps.mapsto_add_eq; try reflexivity. }\n  eapply Maps.mapsto_lookup in H. unfold lookup_default. rewrite H. auto.\nQed.\n\nDefinition assign_aexp (P : env -> Prop) (x : var) (a : aexp) : env -> Prop :=\n  fun s => P (Maps.add x (compute_aexp a s) s).\n\nLemma hoare_assign : forall (P : env -> Prop) (x : var) (a : aexp),\n    {{assign_aexp P x a}} x ::= a {{P}}.\nProof.\n  intros. red. intros s s' Hassign Hret. unfold denote_imp in Hret.\n  rewrite compute_assign_sc_tree in Hret. basic_solve. auto.\nQed.\n\nLemma hoare_consequence : forall (P0 P1 Q0 Q1: env -> Prop) (c : com),\n    (forall s, P0 s -> P1 s) -> (forall s, Q0 s -> Q1 s) ->\n    {{P1}} c {{Q0}} -> {{P0}} c {{Q1}}.\nProof.\n  unfold hoare_triple. intros P0 P1 Q0 Q1 c HP HQ Hc s s' Hs Hcomp.\n  apply HQ. eapply Hc; eauto.\nQed.\n\nSection SQRTEx.\n\n  Context (i n : var).\n  Context ( Hneq : i <> n).\n\n  Definition nat_sqrt : com :=\n    i ::= 0;;;\n    WHILE (~ (i * i = n) ) DO\n       i ::= i + 1\n    END.\n\n  Local Open Scope nat_scope.\n  Local Close Scope imp_scope.\n\n\n  Definition is_square : nat -> Prop := fun (n : nat) => exists (m : nat), (m * m = n).\n\n  Definition pre1 : env -> Prop := fun s => is_square (lookup_default n 0 s).\n  Definition pre2 : env -> Prop := fun s => ~ is_square (lookup_default n 0 s).\n\n  Definition post1 (s0 : env) (t : Delay (env * unit) ) : Prop :=\n    exists s, t ≈ ret (s,tt) /\\ (lookup_default i 0 s * lookup_default i 0 s) = lookup_default n 0 s0.\n\n  Definition post2 : env -> Delay (env * unit) -> Prop := fun _ t => any_infinite t.\n\n  Lemma burn_tree : forall (E : Type -> Type) (R : Type) (n : nat) (t : itree E R),\n      t ≈ burn n t.\n  Proof.\n    intros. symmetry. generalize dependent t. induction n0; intros; try reflexivity.\n    simpl. destruct (observe t) eqn : Heq.\n    - specialize (itree_eta t) as Ht. rewrite Heq in Ht. rewrite Ht. reflexivity.\n    - specialize (itree_eta t) as Ht. rewrite Heq in Ht. rewrite Ht.\n      rewrite tau_eutt. auto.\n    - specialize (itree_eta t) as Ht. rewrite Heq in Ht. rewrite Ht. reflexivity.\n  Qed.\n(*\n  Global Instance proper_state_eq_eutt_iter {S Type: } :\n    Proper (state_eq_eutt ==> pointwise_relation _ (state_eq_eutt) )\n           (fun body)\n*)\n\n\n  Lemma compile_nat_sqrt_body :\n    state_eq_eutt (denote_imp (WHILE (~ i * i  = n) DO i ::= i + 1 END)%imp)\n                              (MonadIter_stateT0 _ _  (fun (_ :unit) (s : env) =>\n                                                         if (compute_bexp (~ i * i = n) s)\n                                                         then Ret (inc_var i s, inl tt)\n                                                         else Ret (s, inr tt) ) tt ) .\n  Proof.\n    rewrite compile_while. apply state_eutt_iter. intro.\n    rewrite compute_bexp_sc. intro. simpl. rewrite bind_ret_l. simpl.\n    destruct (lookup_default i 0 s * lookup_default i 0 s =? lookup_default n 0 s); simpl.\n    - tau_steps. reflexivity.\n    - unfold denote_imp. rewrite compute_assign_sc_tree. rewrite bind_ret_l.\n      cbn. tau_steps. rewrite Nat.add_comm. reflexivity.\n  Qed.\n\n  Let body_arrow (s : env) : Delay (env * (unit + unit) ) :=\n    if (compute_bexp (~ i * i = n) s )\n    then Ret (inc_var i s, inl tt)\n    else Ret (s, inr tt).\n\n  (*this may force me to come up with good wf_from conditions*)\n\n  Ltac eqbdestruct a b := destruct (a =? b) eqn :?Heq;\n                          match type of Heq with\n                            | _ = true => apply Nat.eqb_eq in Heq\n                            | _ = false => apply Nat.eqb_neq in Heq end.\n\n\n  Lemma diverge_if_not_square_nat_sqrt_aux : forall (s : env),\n      ~ is_square (lookup_default n 0 s) ->\n      not_wf_from (fun s0 s1 => Ret (s1, inl tt) ≈ body_arrow s0 ) s.\n  Proof.\n    intros s Hn.\n    set (lookup_default n 0 s) as n0.\n    assert (forall m, m * m <> n0 ).\n    {\n      intros m Hcontra. unfold n0 in Hcontra. apply Hn. exists m. auto.\n    }\n    eapply intro_not_wf with (P := fun s => lookup_default n 0 s = n0) (f := fun s => inc_var i s); auto.\n    - intros s0 s1 Hinv Heval. unfold body_arrow in Heval. simpl in Heval.\n      rewrite Hinv in Heval. eqbdestruct (lookup_default i 0 s0 * lookup_default i 0 s0) n0.\n      + simpl in *. basic_solve. pinversion Heval; discriminate.\n      + simpl in Heval. basic_solve. pinversion Heval. injection REL; intros; subst. unfold inc_var. rewrite lookup_neq; auto.\n    - intros s' Hinv. unfold body_arrow. simpl. rewrite Hinv.\n      eqbdestruct (lookup_default i 0 s' * lookup_default i 0 s') n0; simpl.\n      + exfalso. eapply H; apply Heq.\n      + reflexivity.\n  Qed.\n\n  Lemma converge_if_square_nat_sqrt_aux : forall (s : env),\n      lookup_default i 0 s = 0 ->\n      is_square (lookup_default n 0 s) ->\n      wf_from (fun s0 s1 => Ret (s1, inl tt) ≈ body_arrow s0 ) s.\n  Proof.\n    intros s Hi H. intros. unfold is_square in H. destruct H as [sqrt Hsqrt].\n    set (fun s' : env => lookup_default i 0 s' <= sqrt /\\\n                         lookup_default n 0 s = lookup_default n 0 s') as inv.\n    set (fun s : env => sqrt - lookup_default i 0 s)  as f.\n    apply wf_intro_gt with (f := f) (P := inv); unfold inv; unfold f.\n    - intros s1 s2 Hs1 Heutt.\n      unfold body_arrow in Heutt. simpl in Heutt.\n      destruct Hs1 as [Hsqrt1 Hconst].\n      eqbdestruct (lookup_default i 0 s1 * lookup_default i 0 s1) (lookup_default n 0 s1);\n        simpl in *; basic_solve; pinversion Heutt; try discriminate; injection REL; intros; subst.\n      split.\n      + unfold inc_var. rewrite lookup_eq.\n        nia.\n      + unfold inc_var. rewrite lookup_neq; auto.\n    - intros s1 s2 Hs1 Heutt. unfold body_arrow in Heutt. simpl in *.\n      eqbdestruct (lookup_default i 0 s1 * lookup_default i 0 s1) (lookup_default n 0 s1); simpl in *;\n        pinversion Heutt; try discriminate; injection REL; intros; subst.\n        unfold inc_var. rewrite lookup_eq. nia.\n    - split; nia.\n Qed.\n\n      (*Global Instance state_eq_eutt_eutt : Proper (state_eq_eutt ==> (pointwise_relation _ (eutt eq) ) ) (pointwise_relation _ (eutt eq) ). *)\n\n\n  Lemma diverge_if_not_square_nat_sqrt : forall (s : env),\n      ~ is_square (lookup_default n 0 s) ->\n      any_infinite ( (denote_imp (WHILE (~ i * i  = n) DO i ::= i + 1 END)%imp) s).\n    Proof.\n      intros.\n      enough (denote_imp (WHILE ~ i * i = n DO i ::= i + 1 END)%imp s ≈ ITree.spin).\n      {\n         rewrite H0. apply spin_infinite.\n      }\n      match goal with |- ?m s ≈ ITree.spin => fold (run_state_itree s m) end.\n      rewrite compile_nat_sqrt_body. unfold run_state_itree.\n      apply iter_inl_spin_state.\n      apply ( diverge_if_not_square_nat_sqrt_aux) in H. unfold state_iter_arrow_rel.\n      simpl. unfold body_arrow in H. simpl in *. generalize dependent s. pcofix CIH. intros.\n      pinversion H0; try apply not_wf_F_mono'.\n      pfold. eapply not_wf with (a' := (a',tt)).\n      - symmetry. auto.\n      - right. auto.\n    Qed.\n\n    (*maybe there is a better way to do it, prove that if the body can't prove a a spin,\n      and it is wf then\n      start working on that\n     *)\n\n  Lemma converge_if_square_nat_sqrt : forall (s : env),\n        lookup_default i 0 s = 0 ->\n        is_square (lookup_default n 0 s) ->\n        exists s', (denote_imp (WHILE ~ i * i = n DO i ::= i + 1 END)%imp s ≈ Ret (s',tt) ).\n  Proof.\n    intros s Hi0 Hn. specialize (converge_if_square_nat_sqrt_aux s Hi0 Hn) as Hwf.\n    eenough (exists s', _ ≈ Ret (s',tt) ).\n    {\n      destruct H as [s' H] . exists s'.\n      match goal with |- (?m s ≈ _)%monad => fold (run_state_itree s m) end.\n      rewrite compile_nat_sqrt_body. unfold run_state_itree. apply H.\n    }\n    specialize (iter_wf_converge_state unit unit env (fun _ : unit => body_arrow) ) as Hconv.\n    specialize (Hconv tt s).\n    enough ( exists p : env * unit,\n            MonadIter_stateT0 unit unit (fun _ : unit => body_arrow) tt s\n            ≈ Ret p).\n    { destruct H as [ [s' [] ] H ]. eauto. }\n    apply Hconv.\n    - intros. unfold body_arrow. simpl.\n      eqbdestruct (lookup_default i 0 s0 * lookup_default i 0 s0) (lookup_default n 0 s0); simpl.\n      + exists (s0, inr tt). reflexivity.\n      + exists (inc_var i s0, inl tt). reflexivity.\n    - clear Hconv. clear Hi0. clear Hn. induction Hwf.\n      + apply base. intros [s' [] ] ? . apply (H s').\n        unfold state_iter_arrow_rel in H0. symmetry. auto.\n      + apply step. intros [ s' [] ] ?. eapply H0. unfold state_iter_arrow_rel in H1. symmetry. auto.\n  Qed.\n\n\n  Lemma prepost1_holds_nat_sqrt_loop :\n    verify_cond env (encode_dyn env ((pre1 /1\\ fun s => lookup_default i 0 s = 0), post1) )\n                (denote_imp (WHILE (~ i * i  = n) DO i ::= i + 1 END)%imp ).\n  Proof.\n    rewrite compile_nat_sqrt_body.\n    repeat red. simpl. intros. destruct H. apply H0. clear H0. destruct H as [Hpre Hi0].\n    assert (Hpost1 : forall s, resp_eutt (post1 s)).\n    {\n      unfold post1. repeat intro. split; basic_solve.\n      - exists s1. split; auto. rewrite <- H. auto.\n      - exists s1. rewrite H. split; auto.\n    }\n    unfold pre1 in Hpre.\n\n    clear p.\n    set (lookup_default n 0 s) as n0.\n    set (fun x s => lookup_default x 0 s)  as get.\n    set (fun (t : Delay ((env * unit) + (env * unit)) ) => exists s0,\n    ((t ≈ ret (inl (s0,tt)) /\\ get i s0 * get i s0 <= n0  ) \\/ (t ≈ ret (inr (s0,tt)) /\\ get i s0 * get i s0 = n0)) /\\ get n s0 = n0 ) as q .\n    set (fun (t : Delay (env * unit)) => exists s0, t ≈ ret (s0,tt) /\\ get i s0 * get i s0 = n0 ) as p.\n    match goal with |- post1 s ?t => enough (p t); auto end.\n    assert (Hq : resp_eutt q).\n    {\n      + unfold q. repeat intro. split; intros; basic_solve; auto.\n        * exists s0. split; auto. left. rewrite <- H. auto.\n        * exists s0. split; auto. right. rewrite <- H. auto.\n        * exists s0. split; auto. left. rewrite H. auto.\n        * exists s0. split; auto. right. rewrite H. auto.\n    }\n    match goal with |- p ?t => enough ((p \\1/ any_infinite) t)  end.\n    - destruct H; auto. exfalso.\n      specialize (converge_if_square_nat_sqrt s Hi0 Hpre) as Hconv.\n      basic_solve.\n      match type of Hconv with ?m s ≈ _ => fold (run_state_itree s m) in Hconv end.\n      rewrite compile_nat_sqrt_body in Hconv. unfold run_state_itree in Hconv. rewrite Hconv in H.\n      pinversion H.\n    - eapply loop_invar_state with (q := q); eauto.\n      (*Establishment*)\n      + unfold reassoc. simpl. rewrite Hi0. simpl.\n        destruct (lookup_default n 0 s) eqn : Heq; simpl.\n        * eapply Hq.\n          -- rewrite bind_ret_l. reflexivity.\n          -- red. exists s. split; auto. right. unfold get. split; try reflexivity. unfold n0.\n             (*wierd, so it seems to have something to do with different type aliasing for env*)\n             unfold env in Hi0. rewrite Hi0. auto.\n        * eapply Hq.\n          -- rewrite bind_ret_l. reflexivity.\n          -- red. exists (inc_var i s). split; auto.\n             ++ left. split; try reflexivity. unfold get, inc_var.\n                rewrite lookup_eq. unfold is_square in Hpre. basic_solve. nia.\n             ++ unfold get, inc_var. rewrite lookup_neq; auto.\n      (*Post Condition*)\n      + red. cbn. intros. red. red in H. basic_solve.\n        * exists s0. destruct (eutt_reta_or_div t); basic_solve.\n          -- destruct a as [ s' [] ]. rewrite <- H2 in H. simpl in *. rewrite bind_ret_l in H.\n             basic_solve.\n          -- apply div_spin_eutt in H2. rewrite H2 in H.\n             rewrite <- spin_bind in H. exfalso. symmetry in H. eapply not_ret_eutt_spin; try apply H.\n        * exists s0. destruct (eutt_reta_or_div t); basic_solve.\n          -- destruct a as [ s' []  ]. symmetry in H2. rewrite H2 in H.\n             simpl in *. rewrite H1. rewrite bind_ret_l in H. basic_solve. auto.\n          -- apply div_spin_eutt in H2. rewrite H2 in H. rewrite <- spin_bind in H.\n             exfalso. symmetry in H. eapply not_ret_eutt_spin; try apply H.\n       (*Preservation*)\n      + intros. simpl. red in H. basic_solve.\n        * eapply Hq.\n          -- rewrite H. simpl. rewrite bind_ret_l. unfold DelaySpecMonad.iter_lift, iso_destatify_arrow, reassoc.\n             simpl. reflexivity.\n          -- eqbdestruct (lookup_default i 0 s0 * lookup_default i 0 s0) (lookup_default n 0 s0).\n             ++ simpl. red. exists s0. setoid_rewrite Heq.\n                rewrite Nat.eqb_refl.\n                cbn. rewrite bind_ret_l. split; auto. right. unfold get, n0.\n                split; try reflexivity.\n                unfold env in Heq.  rewrite Heq. auto.\n             ++ simpl. red. exists (inc_var i s0).  apply Nat.eqb_neq in Heq as Heq'. setoid_rewrite Heq'. simpl. rewrite bind_ret_l. split; auto.\n                ** left. split; try reflexivity. unfold get, inc_var. rewrite lookup_eq.\n                   unfold get in H1. red in Hpre. basic_solve. unfold get in H0. unfold n0 in *.\n                   rewrite <- Hpre. rewrite <- H0 in H1. rewrite <- Hpre in H0. unfold env in *.  rewrite H0 in Heq.\n                   assert (lookup_default i 0 s0 < m); nia.\n                ** unfold get, inc_var. rewrite lookup_neq; auto.\n         * eapply Hq.\n           -- rewrite H. simpl. rewrite bind_ret_l. cbn. reflexivity.\n           -- red. exists s0. split; auto. right. split; auto. reflexivity.\n  Qed.\n\n\n  Lemma prepost1_holds_nat_sqrt : verify_cond env (encode_dyn env (pre1,post1) ) (denote_imp nat_sqrt).\n  Proof.\n    unfold nat_sqrt.  rewrite denote_imp_bind.\n    setoid_rewrite compile_nat_sqrt_body.\n    setoid_rewrite compute_assign_sc. repeat red. intros s [p Hp]. intros. simpl in H.\n    destruct H as [Hpre H]. apply H. clear H.\n    assert (Hpost: forall s, resp_eutt (post1 s)).\n    {\n      repeat intro. unfold post1. split; intros; basic_solve.\n      - exists s1. split; auto. rewrite <- H. auto.\n      - exists s1. rewrite H. split; auto.\n    }\n    eapply Hpost.\n    - Opaque Maps.add. simpl. rewrite bind_ret_l. simpl. reflexivity.\n    - match goal with |- post1 s ?m => enough (post1 (Maps.add i 0 s) m) end.\n      { unfold post1. unfold post1 in H. rewrite lookup_neq in H; auto. }\n      specialize prepost1_holds_nat_sqrt_loop as Hloop.\n      rewrite compile_nat_sqrt_body in Hloop. repeat red in Hloop.\n      match goal with |- post1 ?s _ => set s as s1 end.\n      simpl in Hloop. specialize (Hloop s1 (exist _ (post1 s1) (Hpost s1)) ).\n      simpl in *. eapply Hloop. split; try split; intros.\n      + unfold pre1, s1. rewrite lookup_neq; auto.\n      + unfold s1. rewrite lookup_eq. auto.\n      + red. red in H. basic_solve. unfold s1 in H0. exists s0. split; auto.\n   Qed.\n\n  Lemma prepost2_holds_nat_sqrt : verify_cond env (encode_dyn env (pre2,post2) ) (denote_imp nat_sqrt).\n  Proof.\n    unfold nat_sqrt. rewrite denote_imp_bind.\n    setoid_rewrite compile_nat_sqrt_body.\n    setoid_rewrite compute_assign_sc. repeat red. intros s [p Hp]. intros. simpl in H.\n    destruct H as [Hpre H]. apply H. clear H. red in Hpre.\n    simpl. red. rewrite bind_ret_l. simpl.\n    assert (Hs' : ~ is_square (lookup_default n 0 (Maps.add i 0 s)) ).\n    { rewrite lookup_neq; auto. } clear Hpre.\n    apply diverge_if_not_square_nat_sqrt in Hs' as Hdivs.\n    specialize compile_nat_sqrt_body as Hcomp. red in Hcomp. rewrite <- Hcomp.\n    auto.\n  Qed.\n\n  Lemma both_hold_nat_sqrt : verify_cond env\n                      (encode_list_dyn env (  (pre1, post1) :: (pre2,post2) :: nil ) ) (denote_imp nat_sqrt).\n  Proof.\n     repeat red. cbn. intros. inversion H; subst.\n     - apply prepost1_holds_nat_sqrt. auto.\n     - inversion H1; subst; try inversion H2.\n       apply prepost2_holds_nat_sqrt. auto.\n  Qed.\n\nEnd SQRTEx.\n", "meta": {"author": "DeepSpec", "repo": "InteractionTrees", "sha": "8e28e2ee08496c696e03916a22d93c39559a9715", "save_path": "github-repos/coq/DeepSpec-InteractionTrees", "path": "github-repos/coq/DeepSpec-InteractionTrees/InteractionTrees-8e28e2ee08496c696e03916a22d93c39559a9715/hoare_example/ImpHoare.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.27590741431744664}}
{"text": "(* Set Typeclasses Unique Instances *)\n(** This lets typeclass search assume that instance heads are unique,\n    so if one matches no other need to be tried,\n    avoiding backtracking (even in unique solutions mode) \n    This is on a class-by-class basis.\n *)\n\n(* Non unique *)\nClass B.\nClass A.\nSet Typeclasses Unique Instances.\n(* Unique *)\nClass D.\nClass C (A : Type) := c : A.\n\nHint Mode C +.\nFail Definition test := c.\n\nUnset Typeclasses Unique Instances.\nInstance : B -> D -> C nat := fun _ _ => 0.\nInstance : A -> D -> C nat := fun _ _ => 0.\nInstance : B -> C bool := fun _ => true.\n\nInstance : forall A, C A -> C (option A) := fun A _ => None.\n\nSet Typeclasses Debug.\n\nSet Typeclasses Unique Solutions.\n(** This forces typeclass resolution to fail if at least two solutions \n   exist to a given set of constraints. This is a global setting.\n   For constraints involving assumed unique instances, it will not fail\n   if two such instances could apply, however it will fail if two different\n   instances of a unique class could apply.\n *)\nFail Definition foo (d d' : D) (b b' : B) (a' a'' : A) := c : nat.\nDefinition foo (d d' : D) (b b' : B) (a' : A) := c : nat.\n\nFail Definition foo' (b b' : B) := _ : B.\nUnset Typeclasses Unique Solutions.\nDefinition foo' (b b' : B) := _ : B.\n\nSet Typeclasses Unique Solutions.\nDefinition foo'' (d d' : D) := _ : D.\n\n(** Cut backtracking *)\nModule BacktrackGreenCut.\n  Unset Typeclasses Unique Solutions.\n  Class C (A : Type) := c : A.\n\n  Class D (A : Type) : Type := { c_of_d :> C A }.\n  \n  Instance D1 : D unit.\n  Admitted.\n  \n  Instance D2 : D unit.\n  Admitted.\n\n  (** Two instances of D unit, but when searching for [C unit], no \n      backtracking on the second instance should be needed except\n      in dependent cases. Check by adding an unresolvable constraint.\n   *)\n\n  Variable f : D unit -> C bool -> True.\n  Fail Definition foo := f _ _. \n  \n  Fail Definition foo' := let y := _ : D unit in let x := _ : C bool in f _ x. \n  \n  Unset Typeclasses Strict Resolution.\n  Class Transitive (A : Type) := { trans : True }.\n  Class PreOrder (A : Type) := { preorder_trans :> Transitive A }.\n  Class PartialOrder (A : Type) := { partialorder_trans :> Transitive A }.\n  Class PartialOrder' (A : Type) := { partialorder_trans' :> Transitive A }.\n  \n  Instance: PreOrder nat. Admitted.\n  Instance: PartialOrder nat. Admitted.\n  \n  Class NoInst (A : Type) := {}.\n    \n  Variable foo : forall `{ T : Transitive nat } `{ NoInst (let x:=@trans _ T in nat) }, nat.\n  \n  Fail Definition bar := foo.\n\n\nEnd BacktrackGreenCut.\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/typeclasses/backtrack.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984434543457, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.2759074143174466}}
{"text": "(*===========================================================================\n    Some useful instances of Monad\n  ===========================================================================*)\nRequire Import ssreflect seq.\nRequire Import monad.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nRequire Import FunctionalExtensionality.\n\n(*---------------------------------------------------------------------------\n    Option monad\n  ---------------------------------------------------------------------------*)\nInstance optionMonadOps : MonadOps option :=\n{ retn := Some\n; bind := fun X Y (c: option X) f => if c is Some y then f y else None }.\n\nInstance optionMonad : Monad option.\nProof. apply Build_Monad. done. move => X; by case. move => X Y Z; by case. Qed.\n\n(*---------------------------------------------------------------------------\n    Error monad\n  ---------------------------------------------------------------------------*)\nSection Error.\n\n  Variable F: Type.\n\n  Inductive Result X :=\n  | Error (f:F)\n  | Success (x:X).\n\n  Global Instance errorMonadOps : MonadOps Result :=\n  { retn := Success\n  ; bind := fun X Y (c: Result X) f =>\n    match c with Success x => f x | Error e => Error _ e end }.\n\n  Global Instance errorMonad : Monad Result.\n  Proof. apply Build_Monad. done. move => X; by case. move => X Y Z; by case. Qed.\n\n  Definition raiseError {X} e : Result X := Error _ e.\n\nEnd Error.\n\n(*---------------------------------------------------------------------------\n    List monad\n    @todo akenn: fix this so we don't get a universe inconsistency later!\n  ---------------------------------------------------------------------------*)\n(*\nLemma flatten_map_cat {A B} (f:A->seq B) x y :\n  flatten (map f (x ++ y)) = flatten (map f x) ++ flatten (map f y).\nProof. induction x => //. by rewrite /= IHx catA. Qed.\n\nInstance seqMonadOps : MonadOps seq :=\n{ retn := fun X (x:X) => x::nil\n; bind := fun X Y (x: seq X) f => flatten (map f x) }.\n\nInstance seqMonad : Monad seq.\nProof. apply Build_Monad.\n+ move => X Y x f. by rewrite /= cats0.\n+ move => X c. rewrite /=. induction c => //. by rewrite /=IHc.\n+ induction c => //. move => f g. rewrite/=flatten_map_cat. rewrite/= in IHc. by rewrite IHc.\nQed.\n*)\n(*---------------------------------------------------------------------------\n    I/O monad. D is the type of the input/output data\n  ---------------------------------------------------------------------------*)\nSection IO.\n\n  Variable Chan: Type.\n  Variable D: Type.\n\n  Inductive IOM X :=\n  | retnIO (x:X)\n  | Out (ch:Chan) (d:D) (rest:IOM X)\n  | In (ch:Chan) (f:D -> IOM X).\n\n  Fixpoint bindIO X Y (c: IOM X) (f: X -> IOM Y) :=\n   match c with\n   | retnIO y => f y\n   | Out ch d rest => Out ch d (bindIO rest f)\n   | In ch g => In ch (fun d => bindIO (g d) f)\n   end.\n\n  Global Instance IOMonadOps : MonadOps IOM :=\n  { retn := retnIO; bind := bindIO }.\n\n  Global Instance IOMonad : Monad IOM.\n  Proof. apply Build_Monad.\n  (* assoc *) done.\n  (* id_l *) induction c => //.\n  + rewrite /= in IHc. by rewrite /=IHc.\n  + rewrite /=. rewrite /= in H. by rewrite (functional_extensionality _ _ H).\n  (* id_r *) induction c => //.\n  + move => f g. rewrite /= in IHc. by rewrite /=IHc.\n  + move => f0 g. rewrite /= in H.\n    rewrite /=. apply f_equal. apply functional_extensionality. move => d. by rewrite H.\n  Qed.\n\n  Definition IO_write ch d : IOM unit := Out ch d (retn tt).\n  Definition IO_read ch : IOM D := In ch retn.\n\n  Require Import Streams.\n  Fixpoint IO_run X (s:Stream D) (m: IOM X) : seq D * X :=\n  match m with\n  | retnIO x => (nil,x)\n  | In ch g => let: Cons h t := s in IO_run t (g h)\n  | Out ch d m => let: (output, result) := IO_run s m in (cons d output, result)\n  end.\n\n  Definition OutputM X := (seq D * X)%type.\n\n  Global Instance OutputMonadOps : MonadOps OutputM :=\n  { retn := fun {X} (x:X) => (nil, x);\n    bind := fun {X Y} (c: OutputM X) (f: X -> OutputM Y) =>\n            let (s, x) := c in\n            let (s', y) := f x in (s++s', y) }.\n\n  Global Instance OutputMonad : Monad OutputM.\n  Proof. apply Build_Monad.\n  (* assoc *) move => X Y x f. rewrite /bind/retn/=. by case (f x).\n  (* id_l *) move => X c. rewrite /bind/retn/=. case c => s x. by rewrite cats0.\n  (* id_r *) move => X Y Z c f g. case c => s x.\n    rewrite /bind/=. case (f x) => s' y. case (g y) => s'' z. by rewrite catA.\n  Qed.\n\n  Definition Output_write d : OutputM unit := ([::d], tt).\nEnd IO.\n\nExisting Instance IOMonadOps.\nExisting Instance IOMonad.\nExisting Instance OutputMonadOps.\nExisting Instance OutputMonad.\n\n(*---------------------------------------------------------------------------\n    State monad. S is the type of states\n  ---------------------------------------------------------------------------*)\nSection State.\n\n  Context {S: Type}.\n\n  Definition SM X := S -> (S * X)%type.\n\n  (* Of course, this is a monad *)\n  Global Instance SMonadOps : MonadOps SM :=\n  { retn := fun X (x: X) (s:S) => (s, x)\n  ; bind := fun X Y (c: SM X) (f: X -> SM Y) =>\n            fun s => let (st1, a1) := c s in f a1 st1 }.\n\n  Global Instance SMonad : Monad SM.\n  Proof.\n  apply Build_Monad.\n  (* assoc *) move => X Y x f. by apply functional_extensionality => s.\n  (* id_l *) move => X c. apply functional_extensionality => s. simpl. by elim (c s).\n  (* id_r *) move => X Y Z c f g. apply functional_extensionality => s. simpl. by elim (c s).\n  Qed.\n\n  Definition SM_get : SM S := fun s => (s,s).\n  Definition SM_set (s':S) : SM unit := fun s => (s',tt).\n\n  Lemma bindGet {Y} (s: S) (f: S -> SM Y):\n    bind SM_get f s = f s s.\n  Proof. done. Qed.\n\nEnd State.\n\n(*---------------------------------------------------------------------------\n    Stateful I/O. S is the type of states, D the type of input/output data\n  ---------------------------------------------------------------------------*)\n(*\nRequire Import Streams.\nSection StateIO.\n\n  Variable S: Type.\n  Variable D: Type.\n\n  Inductive Act := In (d:D) | Out (d:D).\n\n  Definition SO X := S -> seq Act -> S -> X -> Prop.\n  Inductive SOtrans X : SO X :=\n  | unitSO (x: X) : forall s, SOtrans s nil s x\n  | bindSO Y (c: SO Y) (f: Y -> SO X) :\n    forall s s' s'' t t' x y, c s t s' y -> f y s' t' s'' x -> SOtrans s (t++t') s'' x.\n\n\nCheck unitSO. SOtrans.\nCheck unitSO.\n  (* Of course, this is a monad *)\n  Global Instance SOMonadOps : MonadOps SO :=\n  { retn := unitSO\n  ; bind := bindSO }. fun X Y (c: SO X) (f: X -> SO Y) =>\n            fun str s => let: (st1, xs1, a1) := c str s in\n                     let: (st2, xs2, a2) := f a1 str st1 in\n                     (st2, xs1++xs2, a2) }.\n\n  Global Instance SOMonad : Monad SO.\n  Proof.\n  apply Build_Monad.\n  (* assoc *) move => X Y x f. apply functional_extensionality => s.\n              simpl. by case E: (f x s) => [[st2 xs2] a2].\n  (* id_l *) move => X c. apply functional_extensionality => s.\n             simpl. case E: c => [[st xs] a]. by rewrite cats0.\n  (* id_r *) move => X Y Z c f g. apply functional_extensionality => s.\n             simpl. case E1: (c s) => [[st1 xs1] a1].\n                    case E2: (f a1 st1) => [[st2 xs2] a2].\n                    case E3: (g a2 st2) => [[st3 xs3] a3]. by rewrite catA.\n  Qed.\n\n  Definition SO_get : SO S := fun s => (s,nil,s).\n  Definition SO_set (s':S) : SO unit := fun s => (s',nil,tt).\n  Definition SO_output (d:D) : SO unit := fun s => (s,d::nil,tt).\nEnd StateO.\n*)\n\n(*===========================================================================\n    Monad transformers\n  ===========================================================================*)\n\nSection MonadTransformers.\n\n(* Base monad *)\nVariable M: Type -> Type.\nVariable ops: MonadOps M.\nVariable laws: Monad M.\n\n(*---------------------------------------------------------------------------\n    Option monad transformer\n  ---------------------------------------------------------------------------*)\n(* Base monad *)\nSection OptionMT.\n\n  Definition optionMT X := M (option X).\n\n  Global Instance optionMT_ops : MonadOps optionMT :=\n  { retn := fun X (x:X) => retn (Some x)\n  ; bind := fun X Y (c: optionMT X) (f: X -> optionMT Y) =>\n      bind (MonadOps:=ops) c (fun x:option X => if x is Some x' then f x' else retn None) }.\n\n  Global Instance optionMT_laws : Monad optionMT.\n  Proof. apply Build_Monad.\n  (* assoc *) move => X Y x f. by rewrite /=id_l.\n  (* id_l *)  move => X c. rewrite /= -{2}(id_r (option X) c).\n    apply: f_equal. apply functional_extensionality => x. by elim x.\n  (* id_r *) move => X Y Z c f g. rewrite /=assoc. apply: f_equal.\n    apply functional_extensionality => x. elim x => //. by rewrite id_l.\n  Qed.\n\n  Global Coercion OMT_lift {X} (c: M X) : optionMT X :=\n  let! x = c; retn (Some x).\nEnd OptionMT.\n\n(*---------------------------------------------------------------------------\n    Error monad transformer\n  ---------------------------------------------------------------------------*)\nSection ErrorMT.\n\n  Variable F: Type.\n\n  Definition errorMT X := M (Result F X).\n\n  Global Instance errorMT_ops : MonadOps errorMT :=\n  { retn := fun X (x:X) => retn (Success _ x)\n  ; bind := fun X Y (c: errorMT X) (f: X -> errorMT Y) =>\n            bind (MonadOps:=ops) c (fun x =>\n            match x with Success x => f x | Error e => retn (Error _ e) end) }.\n\n  Global Instance errorMT_laws : Monad errorMT.\n  Proof. apply Build_Monad.\n  (* assoc *) move => X Y x f. by rewrite/= id_l.\n  (* id_l *)  move => X c. simpl. rewrite -{2}(id_r (Result _ _) c).\n  apply f_equal. apply functional_extensionality => x. by elim x.\n  (* id_r *) move => X Y Z c f g. simpl. rewrite assoc.\n  apply f_equal. apply functional_extensionality => x.\n  elim x => //. move => f'. by rewrite id_l.\n  Qed.\n\n  Definition EMT_raise {X} e : errorMT X :=\n    retn (Error _ e).\n\n  Global Coercion EMT_lift {X} (c: M X) : errorMT X :=\n    let! x = c; retn (Success _ x).\n\nEnd ErrorMT.\n\n(*---------------------------------------------------------------------------\n    State monad transformer. S is the type of states, M is underlying monad\n\n    This causes a universe inconsistency with procstatemonad.v!\n  ---------------------------------------------------------------------------*)\nSection StateMT.\n\n  Variable S: Type.\n\n  Definition SMT X := S -> M (S * X)%type.\n\n  (* Of course, this is a monad *)\n  Global Instance SMT_ops : MonadOps SMT :=\n  { retn := fun X (x: X) (s:S) => retn (s, x)\n  ; bind := fun X Y (c: SMT X) (f: X -> SMT Y) =>\n            fun s => let! (st1, a1) = c s; f a1 st1 }.\n\n  Global Instance SMT_laws : Monad SMT.\n  Proof.\n  assert (H1:forall Z, (fun z:S*Z => let (st,x) := z in retn (T:=M)(st, x)) = fun z => retn z).\n  move => Z. apply functional_extensionality. by elim.\n\n  assert(H2: forall Z, (fun z:S*Z => retn z) = retn).\n  move => Z. by apply functional_extensionality.\n\n  apply Build_Monad.\n  (* assoc *) move => X Y x f. apply functional_extensionality => s. by rewrite /=id_l.\n  (* id_l *) move => X c. apply functional_extensionality => s. by rewrite /= H1/= id_r.\n  (* id_r *) move => X Y Z c f g. apply functional_extensionality => s.\n  rewrite /= assoc/=. apply f_equal. apply functional_extensionality. by elim.\n  Qed.\n\n  Definition SMT_get : SMT S := fun s => retn (s,s).\n  Definition SMT_set (s':S) : SMT unit := fun s => retn (s',tt).\n\n  Global Coercion SMT_lift {X} (c: M X) : SMT X :=\n  fun s => let! r = c; retn (s,r).\n\n  Lemma SMT_bindGet {Y} (s: S) (f: S -> SMT Y):\n    bind SMT_get f s = f s s.\n  Proof. by rewrite /bind/SMT_get/= id_l. Qed.\n\n  Lemma SMT_doSet {Y} (s s': S) (c: SMT Y):\n    (do! SMT_set s'; c) s = c s'.\n  Proof. by rewrite /bind/SMT_set/= id_l. Qed.\n\nEnd StateMT.\n\nEnd MonadTransformers.", "meta": {"author": "jbj", "repo": "x86proved", "sha": "d314fa6d23c064a2be4bf686ac7da16a591fda01", "save_path": "github-repos/coq/jbj-x86proved", "path": "github-repos/coq/jbj-x86proved/x86proved-d314fa6d23c064a2be4bf686ac7da16a591fda01/src/monadinst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.27590740667197156}}
{"text": "(** * Testcases for [write_as.v]\nAuthors: \n    - Lulof Pirée (1363638)\nCreation date: 16 June 2021\n\n--------------------------------------------------------------------------------\n\nThis file is part of Waterproof-lib.\n\nWaterproof-lib is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nWaterproof-lib is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with Waterproof-lib.  If not, see <https://www.gnu.org/licenses/>.\n*)\nFrom Ltac2 Require Import Ltac2.\nFrom Ltac2 Require Option.\n\n\nRequire Import Waterproof.message.\nRequire Import Waterproof.load_database.DisableWildcard.\n\n\nLoad write_as.\nRequire Import Waterproof.test_auxiliary.\n\nOpen Scope nat_scope.\nRequire Import Arith.\nRequire Import Bool.\n\n(** * Test 1\n    Base case: perform a valid rewrite.\n*)\nLemma test_write_as_1: forall x, x = 1 + 1 + 1 -> x = 3.\nProof.\n    intros x h.\n    Write h as (x = 3).\n    assert_hyp_has_type @h constr:(x = 3).\n    assumption.\nQed.\n\n(** * Test 1\n    Error case: invalid rewrite.\n*)\nLemma test_write_as_2: forall x, x = 1 + 1 + 1 -> x = 3.\nProof.\n    intros x h.\n    let result () := Write h as (x = 4) in\n    assert_raises_error result.\nAbort.", "meta": {"author": "impermeable", "repo": "coq-waterproof", "sha": "a32bad4e44fedb4038065d2b55660cd967c2d1fd", "save_path": "github-repos/coq/impermeable-coq-waterproof", "path": "github-repos/coq/impermeable-coq-waterproof/coq-waterproof-a32bad4e44fedb4038065d2b55660cd967c2d1fd/waterproof/deprecated/Undesired tactics/write_as_test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.27590740667197156}}
{"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 computation3.\n\n\nLemma oappl_OLL_cons {T} :\n  forall l : list (OList T),\n    oappl (OLL [] :: l) = oappl l.\nProof. sp. Qed.\nHint Rewrite @oappl_OLL_cons : slow.\n\nLemma oeqset_osubset {T} :\n  forall (o1 o2 o3 : OList T),\n    oeqset o1 o2 -> osubset o2 o3 -> osubset o1 o3.\nProof.\n  introv h1 h2.\n  eapply osubset_trans;[|eauto]; eauto 3 with slow.\nQed.\n\nLemma subset_not_in :\n  forall (T : tuniv) (s1 s2 : list T) (x : T),\n    subset s1 s2 -> !LIn x s2 -> !LIn x s1.\nProof.\n  introv ss h i.\n  apply ss in i; sp.\nQed.\n\nDefinition get_utokens_step_seq_arg1 {o}\n           (f : @ntseq o)\n           (t : @NTerm o) :=\n  match t with\n    | oterm (Can (Nint z)) _ =>\n      if Z_le_gt_dec 0 z\n      then get_utokens_step_seq (f (Z.to_nat z))\n      else []\n    | _ => []\n  end.\n\nLemma fold_get_utokens_step_seq_arg1 {o} :\n  forall (f : @ntseq o)\n         (t : @NTerm o),\n    match t with\n      | oterm (Can (Nint z)) _ =>\n        if Z_le_gt_dec 0 z\n        then get_utokens_step_seq (f (Z.to_nat z))\n        else []\n      | _ => []\n    end = get_utokens_step_seq_arg1 f t.\nProof. sp. Qed.\n\nDefinition get_utokens_step_seq_bterm {o}\n           (f : @ntseq o)\n           (b : @BTerm o) :=\n  match b with\n    | bterm [] (oterm (Can (Nint z)) _) =>\n      if Z_le_gt_dec 0 z\n      then get_utokens_step_seq (f (Z.to_nat z))\n      else []\n    | _ => []\n  end.\n\nLemma fold_get_utokens_step_seq_bterm {o} :\n  forall (f : @ntseq o)\n         (b : @BTerm o),\n    match b with\n      | bterm [] (oterm (Can (Nint z)) _) =>\n        if Z_le_gt_dec 0 z\n        then get_utokens_step_seq (f (Z.to_nat z))\n        else []\n      | _ => []\n    end = get_utokens_step_seq_bterm f b.\nProof. sp. Qed.\n\nDefinition get_utokens_step_seq_bterms {o}\n           (f  : @ntseq o)\n           (bs : list (@BTerm o)) :=\n  match bs with\n    | bterm [] (oterm (Can (Nint z)) _) :: _ =>\n      if Z_le_gt_dec 0 z\n      then get_utokens_step_seq (f (Z.to_nat z))\n      else []\n    | _ => []\n  end.\n\nLemma fold_get_utokens_step_seq_bterms {o} :\n  forall f (bs : list (@BTerm o)),\n    match bs with\n      | bterm [] (oterm (Can (Nint z)) _) :: _ =>\n        if Z_le_gt_dec 0 z\n        then get_utokens_step_seq (f (Z.to_nat z))\n        else []\n      | _ => []\n    end = get_utokens_step_seq_bterms f bs.\nProof. sp. Qed.\n\nDefinition get_utokens_step_seq_ncan {o}\n           (f    : @ntseq o)\n           (ncan : NonCanonicalOp)\n           (bs   : list (@BTerm o)) :=\n  match ncan with\n    | NApply  => get_utokens_step_seq_bterms f bs\n    | NEApply => get_utokens_step_seq_bterms f bs\n    | _ => []\n  end.\n\nLemma fold_get_utokens_step_seq_ncan {o} :\n  forall f ncan (bs : list (@BTerm o)),\n    match ncan with\n      | NApply  => get_utokens_step_seq_bterms f bs\n      | NEApply => get_utokens_step_seq_bterms f bs\n      | _ => []\n    end = get_utokens_step_seq_ncan f ncan bs.\nProof. sp. Qed.\n\nLemma lsubst_aux_equal_mk_nat {o} :\n  forall (t : @NTerm o) sub n u,\n    nr_ut_sub u sub\n    -> lsubst_aux t sub = mk_nat n\n    -> t = mk_nat n.\nProof.\n  introv nrut e.\n  destruct t as [v|f|op bs]; allsimpl; ginv.\n  - remember (sub_find sub v) as  sf; symmetry in Heqsf; destruct sf; subst; ginv.\n    eapply nr_ut_some_implies in Heqsf; eauto; exrepnd; ginv.\n  - inversion e as [e1]; subst; clear e.\n    destruct bs; allsimpl; ginv.\nQed.\n\nLemma oappl_OLS_singleton {T} :\n  forall (f : nat -> OList T), oappl [OLS f] = OLS f.\nProof. sp. Qed.\nHint Rewrite @oappl_OLS_singleton : slow.\n\nLemma nt_wf_Exc {o} :\n  forall (bs : list (@BTerm o)),\n    nt_wf (oterm Exc bs)\n    <=> {a : NTerm\n         & {b : NTerm\n         & bs = [nobnd a, nobnd b]\n         # nt_wf a\n         # nt_wf b}}.\nProof.\n  introv; split; intro h.\n  - inversion h as [|?|? ? imp]; subst; allsimpl.\n    repeat (destruct bs; allsimpl; ginv).\n    destruct b as [l1 t1].\n    destruct b0 as [l2 t2].\n    destruct l1; allsimpl; ginv.\n    destruct l2; allsimpl; ginv.\n    pose proof (imp (bterm [] t1)) as h1; autodimp h1 hyp.\n    pose proof (imp (bterm [] t2)) as h2; autodimp h2 hyp.\n    allrw @bt_wf_iff.\n    unfold nobnd.\n    eexists; eexists; dands; eauto.\n  - exrepnd; subst.\n    constructor; simpl; tcsp.\n    introv i; repndors; subst; tcsp; apply bt_wf_iff; auto.\nQed.\n\nLemma nt_wf_NFix {o} :\n  forall (bs : list (@BTerm o)),\n    nt_wf (oterm (NCan NFix) bs)\n    <=> {a : NTerm\n         & bs = [nobnd a]\n         # nt_wf a}.\nProof.\n  introv; split; intro h.\n  - inversion h as [|?|? ? imp]; subst; allsimpl.\n    repeat (destruct bs; allsimpl; ginv).\n    destruct b as [l1 t1].\n    destruct l1; allsimpl; ginv.\n    pose proof (imp (bterm [] t1)) as h1; autodimp h1 hyp.\n    allrw @bt_wf_iff.\n    unfold nobnd.\n    eexists; dands; eauto.\n  - exrepnd; subst.\n    constructor; simpl; tcsp.\n    introv i; repndors; subst; tcsp; apply bt_wf_iff; auto.\nQed.\n\nLemma wf_isexc_implies {o} :\n  forall (t : @NTerm o),\n    nt_wf t\n    -> isexc t\n    -> {a, e : NTerm $ t = mk_exception a e}.\nProof.\n  introv wf ise.\n  unfold isexc in ise.\n  destruct t as [v|f|op bs]; allsimpl; tcsp.\n  destruct op as [can|ncan|exc|abs]; allsimpl; tcsp; GC.\n  apply nt_wf_Exc in wf; exrepnd; subst.\n  eexists; eexists; reflexivity.\nQed.\n\nLemma nt_wf_NCbv {o} :\n  forall (bs : list (@BTerm o)),\n    nt_wf (oterm (NCan NCbv) bs)\n    <=> {v : NVar\n         & {a : NTerm\n         & {b : NTerm\n         & bs = [nobnd a, bterm [v] b]\n         # nt_wf a\n         # nt_wf b }}}.\nProof.\n  introv; split; intro h.\n  - inversion h as [|?|? ? imp]; subst; allsimpl.\n    repeat (destruct bs; allsimpl; ginv).\n    destruct b as [l1 t1].\n    destruct b0 as [l2 t2].\n    destruct l1; allsimpl; ginv.\n    destruct l2 as [|v l2]; allsimpl; ginv.\n    destruct l2; allsimpl; ginv.\n    pose proof (imp (bterm [] t1)) as h1; autodimp h1 hyp.\n    pose proof (imp (bterm [v] t2)) as h2; autodimp h2 hyp.\n    allrw @bt_wf_iff.\n    unfold nobnd.\n    eexists; dands; eauto.\n  - exrepnd; subst.\n    constructor; simpl; tcsp.\n    introv i; repndors; subst; tcsp; apply bt_wf_iff; auto.\nQed.\n\nLemma nt_wf_NTryCatch {o} :\n  forall (bs : list (@BTerm o)),\n    nt_wf (oterm (NCan NTryCatch) bs)\n    <=> {v : NVar\n         & {a : NTerm\n         & {b : NTerm\n         & {c : NTerm\n         & bs = [nobnd a, nobnd b, bterm [v] c]\n         # nt_wf a\n         # nt_wf b\n         # nt_wf c }}}}.\nProof.\n  introv; split; intro h.\n  - inversion h as [|?|? ? imp]; subst; allsimpl.\n    repeat (destruct bs; allsimpl; ginv).\n    destruct b as [l1 t1].\n    destruct b0 as [l2 t2].\n    destruct b1 as [l3 t3].\n    destruct l1; allsimpl; ginv.\n    destruct l2; allsimpl; ginv.\n    destruct l3 as [|v l3]; allsimpl; ginv.\n    destruct l3; allsimpl; ginv.\n    pose proof (imp (bterm [] t1)) as h1; autodimp h1 hyp.\n    pose proof (imp (bterm [] t2)) as h2; autodimp h2 hyp.\n    pose proof (imp (bterm [v] t3)) as h3; autodimp h3 hyp.\n    allrw @bt_wf_iff.\n    unfold nobnd.\n    eexists; eexists; eexists; eexists; dands; eauto.\n  - exrepnd; subst.\n    constructor; simpl; tcsp.\n    introv i; repndors; subst; tcsp; apply bt_wf_iff; auto.\nQed.\n\nLemma get_cutokens_onil_eq {o} :\n  forall (t : @NTerm o),\n    oapp (get_cutokens t) onil = get_cutokens t.\nProof.\n  introv; rw <- @get_cutokens_onil; auto.\nQed.\nHint Rewrite @get_cutokens_onil_eq : slow.\n\nLemma iscan_lsubst_aux_nr_ut_sub_eq_doms {o} :\n  forall (t u : @NTerm o) sub sub',\n    nr_ut_sub u sub\n    -> nr_ut_sub u sub'\n    -> dom_sub sub = dom_sub sub'\n    -> iscan (lsubst_aux t sub)\n    -> iscan (lsubst_aux t sub').\nProof.\n  introv nrut1 nrut2 eqdoms isc.\n  destruct t as [v|f|op bs]; allsimpl; tcsp.\n  remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf; allsimpl; tcsp.\n  pose proof (sub_find_some_eq_doms_nr_ut_sub sub sub' v u) as h.\n  repeat (autodimp h hyp).\n  rw Heqsf in h; exrepnd.\n  rw h0; simpl; tcsp.\nQed.\nHint Resolve iscan_lsubst_aux_nr_ut_sub_eq_doms : slow.\n\nLemma osubset_oapp_left_iff {T} :\n  forall o o1 o2 : OList T,\n    osubset (oapp o1 o2) o <=> (osubset o1 o # osubset o2 o).\nProof.\n  introv; split; intro h; repnd; try (apply osubset_oapp_left; auto).\n  dands; introv i; apply h; apply in_olist_oapp; sp.\nQed.\n\nLemma subset_flat_map_get_utokens_b {o} :\n  forall (l : list (@BTerm o)),\n    subset (flat_map get_utokens_b l)\n           (flat_map get_utokens_step_seq_b l).\nProof.\n  introv.\n  apply subset_flat_map2; introv i.\n  destruct x; simpl; eauto 3 with slow.\nQed.\nHint Resolve subset_flat_map_get_utokens_b : slow.\n\nDefinition get_utokens_step_seq_bterms_seq {o}\n           (bs : list (@BTerm o)) :=\n  match bs with\n    | bterm [] (sterm f) :: bterm [] (oterm (Can (Nint z)) _) :: _ =>\n      if Z_le_gt_dec 0 z\n      then get_utokens_step_seq (f (Z.to_nat z))\n      else []\n    | _ => []\n  end.\n\nLemma fold_get_utokens_step_seq_bterms_seq {o} :\n  forall (bs : list (@BTerm o)),\n    match bs with\n      | bterm [] (sterm f) :: bterm [] (oterm (Can (Nint z)) _) :: _ =>\n        if Z_le_gt_dec 0 z\n        then get_utokens_step_seq (f (Z.to_nat z))\n        else []\n      | _ => []\n    end = get_utokens_step_seq_bterms_seq bs.\nProof. sp. Qed.\n\nDefinition get_utokens_step_seq_ncan_seq {o}\n           (ncan : NonCanonicalOp)\n           (bs   : list (@BTerm o)) :=\n  match ncan with\n    | NApply  => get_utokens_step_seq_bterms_seq bs\n    | NEApply => get_utokens_step_seq_bterms_seq bs\n    | _ => []\n  end.\n\nLemma fold_get_utokens_step_seq_ncan_seq {o} :\n  forall ncan (bs : list (@BTerm o)),\n    match ncan with\n      | NApply  => get_utokens_step_seq_bterms_seq bs\n      | NEApply => get_utokens_step_seq_bterms_seq bs\n      | _ => []\n    end = get_utokens_step_seq_ncan_seq ncan bs.\nProof. sp. Qed.\n\nDefinition ncan_nil {T} (ncan : NonCanonicalOp) : list T :=\n  match ncan with\n    | NApply => []\n    | _ => []\n  end.\n\nLemma fold_ncan_nil {T} :\n  forall ncan,\n    match ncan with\n      | NApply => []\n      | _ => []\n    end = ([] : list T).\nProof.\n  introv; destruct ncan; sp.\nQed.\nHint Rewrite @fold_ncan_nil : slow.\n\nLemma sub_find_sub_filter_singleton_eq {o} :\n  forall (sub : @Sub o) (v : NVar),\n    sub_find (sub_filter sub [v]) v = None.\nProof.\n  introv.\n  rw @sub_find_sub_filter_eq; allrw memvar_singleton; boolvar; auto.\nQed.\nHint Rewrite @sub_find_sub_filter_singleton_eq : slow.\n\nDefinition get_utokens_step_seq_op_seq {o}\n           (op : @Opid o)\n           (bs : list (@BTerm o)) :=\n  match op with\n    | NCan NApply  => get_utokens_step_seq_bterms_seq bs\n    | NCan NEApply => get_utokens_step_seq_bterms_seq bs\n    | _ => []\n  end.\n\nLemma fold_get_utokens_step_seq_op_seq {o} :\n  forall op (bs : list (@BTerm o)),\n    match op with\n      | NCan NApply  => get_utokens_step_seq_bterms_seq bs\n      | NCan NEApply => get_utokens_step_seq_bterms_seq bs\n      | _ => []\n    end = get_utokens_step_seq_op_seq op bs.\nProof. sp. Qed.\n\nLemma subset_get_utokens_step_seq_lsubst_aux {o} :\n  forall (t : @NTerm o) sub,\n    subset (get_utokens_step_seq t) (get_utokens_step_seq (lsubst_aux t sub)).\nProof.\n  nterm_ind1 t as [v|f ind|op bs ind] Case; introv; simpl; auto.\n  Case \"oterm\".\n  allrw @fold_get_utokens_step_seq_bterms_seq.\n  allrw @fold_get_utokens_step_seq_op_seq.\n  allrw subset_app; dands; eauto 3 with slow.\n  - apply subset_app_l.\n    apply subset_app_r.\n    allrw flat_map_map; unfold compose.\n    apply subset_flat_map2; introv i.\n    destruct x as [l t]; allsimpl.\n    eapply ind; eauto.\n  - apply subset_app_l.\n    apply subset_app_l.\n    dopid op as [can|ncan|exc|abs] SCase; simpl; auto;[].\n    SCase \"NCan\".\n    allrw @fold_get_utokens_step_seq_ncan_seq.\n    destruct ncan; simpl; auto;[|].\n    + destruct bs; simpl; auto;[].\n      destruct b as [l t]; simpl;[].\n      destruct l; simpl; auto;[].\n      destruct t as [v|f|op bs1]; simpl; autorewrite with slow in *; auto;[].\n      destruct bs; simpl; auto;[].\n      destruct b as [l t].\n      destruct l; simpl; auto;[].\n      destruct t as [v|f1|op bs1]; simpl; autorewrite with slow in *; auto.\n    + destruct bs; simpl; auto;[].\n      destruct b as [l t]; simpl;[].\n      destruct l; simpl; auto;[].\n      destruct t as [v|f|op bs1]; simpl; autorewrite with slow in *; auto;[].\n      destruct bs; simpl; auto;[].\n      destruct b as [l t].\n      destruct l; simpl; auto;[].\n      destruct t as [v|f1|op bs1]; simpl; autorewrite with slow in *; auto.\nQed.\n\nDefinition is_utok_sub {o} (sub : @Sub o) :=\n  forall v t, LIn (v,t) sub -> is_utok t.\n\nLemma is_utok_sub_cons {o} :\n  forall v (t : @NTerm o) sub,\n    is_utok_sub ((v, t) :: sub) <=> (is_utok t # is_utok_sub sub).\nProof.\n  introv.\n  unfold is_utok_sub; simpl; split; introv h; repnd; dands; introv.\n  - eapply h; eauto.\n  - intro i; eapply h; eauto.\n  - intro i; repndors; ginv; auto.\n    eapply h; eauto.\nQed.\n\nLemma in_is_utok_sub {o} :\n  forall (sub : @Sub o) v t,\n    is_utok_sub sub\n    -> LIn (v, t) sub\n    -> is_utok t.\nProof.\n  introv i j; apply i in j; auto.\nQed.\n\nLemma implies_is_utok_sub {o} :\n  forall (sub : @Sub o) l, is_utok_sub sub -> is_utok_sub (sub_filter sub l).\nProof.\n  introv isu i.\n  allrw @in_sub_filter; repnd.\n  apply isu in i0; sp.\nQed.\nHint Resolve implies_is_utok_sub : slow.\n\nLemma eqset_flat_map_get_utokens_step_seq_b_is_utok_sub {o} :\n  forall (bs : list (@BTerm o)) sub,\n    (forall (nt nt' : NTerm) (lv : list NVar),\n       LIn (bterm lv nt) bs\n       -> (osize nt') <=< (osize nt)\n       -> forall sub : @Sub o,\n            is_utok_sub sub\n            -> eqset (get_utokens_step_seq (lsubst_aux nt' sub))\n                     (get_utokens_step_seq nt' ++ get_utokens_sub (sub_keep_first sub (free_vars nt'))))\n    -> is_utok_sub sub\n    -> eqset\n         (flat_map get_utokens_step_seq_b\n                   (map (fun t => lsubst_bterm_aux t sub) bs))\n         (flat_map get_utokens_step_seq_b bs ++\n                   get_utokens_sub (sub_keep_first sub (flat_map free_vars_bterm bs))).\nProof.\n  introv ind isu.\n  allrw flat_map_map; unfold compose.\n  introv; split; intro i.\n\n  - rw lin_flat_map in i; exrepnd.\n    destruct x0 as [l t]; allsimpl.\n    eapply ind in i0; eauto 3 with slow.\n    allrw in_app_iff; repndors.\n\n    { left.\n      rw lin_flat_map.\n      eexists; dands; eauto. }\n\n    { right.\n      allrw @in_get_utokens_sub; exrepnd.\n      exists v t0; dands; auto.\n      allrw @in_sub_keep_first; repnd.\n      allrw @sub_find_sub_filter_some; repnd; dands; auto.\n      rw lin_flat_map.\n      eexists; dands; eauto; simpl.\n      allrw in_remove_nvars; dands; auto. }\n\n  - allrw in_app_iff; allrw lin_flat_map.\n    repndors; exrepnd.\n\n    { eexists; dands; eauto.\n      destruct x0 as [l t]; allsimpl.\n      eapply ind; eauto 3 with slow.\n      allrw in_app_iff; tcsp. }\n\n    { allrw @in_range_iff; exrepnd.\n      allrw @in_sub_keep_first; repnd.\n      allrw lin_flat_map; exrepnd.\n      eexists; dands; eauto.\n      destruct x1 as [l t]; allsimpl.\n      allrw in_remove_nvars; repnd.\n      eapply ind; eauto 3 with slow.\n      allrw in_app_iff.\n      right.\n      unfold get_utokens_sub.\n      rw lin_flat_map; eexists; dands; eauto.\n      allrw @in_range_iff; exists v.\n      allrw @in_sub_keep_first; dands; auto.\n      rw @sub_find_sub_filter_eq; boolvar; tcsp. }\nQed.\n\nLemma get_utokens_sub_sub_keep_first2 {o} :\n  forall (sub : @Sub o) (l1 l2 : list NVar),\n    subset l1 l2\n    -> subset\n         (get_utokens_sub (sub_keep_first sub l1))\n         (get_utokens_sub (sub_keep_first sub l2)).\nProof.\n  introv i j.\n  allunfold @get_utokens_sub.\n  allrw lin_flat_map; exrepnd.\n  eexists; dands; eauto.\n  allrw @in_range_iff; exrepnd.\n  exists v.\n  allrw @in_sub_keep_first; repnd; dands; auto.\nQed.\n\nLemma get_utokens_step_seq_lsubst_aux_is_utok_sub_aux1 {o} :\n  forall a (sub : @Sub o) v l vs,\n    is_utok_sub sub\n    -> sub_find sub v = Some (mk_utoken a)\n    -> eqset (l ++ get_utokens_sub (sub_keep_first sub (v :: vs)))\n             (a :: l ++ get_utokens_sub (sub_keep_first sub vs)).\nProof.\n  introv isu e; allrw in_app_iff; split; introv h;\n  allsimpl; allrw in_app_iff; repndors; tcsp; allsimpl.\n\n  - allunfold @get_utokens_sub.\n    allrw lin_flat_map; exrepnd.\n    allrw @in_range_iff; exrepnd.\n    allrw @in_sub_keep_first; repnd.\n    allsimpl; repndors; subst; tcsp.\n\n    + rw h1 in e; ginv; allsimpl; repndors; tcsp.\n\n    + right.\n      right.\n      exists x0; dands; auto.\n      rw @in_range_iff.\n      exists v0.\n      rw @in_sub_keep_first; dands; auto.\n\n  - subst.\n    right.\n    allunfold @get_utokens_sub.\n    allrw lin_flat_map.\n    exists (mk_utoken x); simpl; dands; tcsp.\n    allrw @in_range_iff.\n    exists v.\n    allrw @in_sub_keep_first; simpl; dands; tcsp.\n\n  - allunfold @get_utokens_sub.\n    allrw lin_flat_map; exrepnd.\n    allrw @in_range_iff; exrepnd.\n    allrw @in_sub_keep_first; repnd.\n    right.\n    exists x0; dands; auto.\n    rw @in_range_iff.\n    exists v0.\n    rw @in_sub_keep_first; dands; simpl; tcsp.\nQed.\n\nLemma get_utokens_step_seq_lsubst_aux_is_utok_sub_aux2 {o} :\n  forall (sub : @Sub o) v l vs,\n    is_utok_sub sub\n    -> sub_find sub v = None\n    -> eqset (l ++ get_utokens_sub (sub_keep_first sub (v :: vs)))\n             (l ++ get_utokens_sub (sub_keep_first sub vs)).\nProof.\n  introv isu e; allrw in_app_iff; split; introv h;\n  allsimpl; allrw in_app_iff; repndors; tcsp; allsimpl.\n\n  - allunfold @get_utokens_sub.\n    allrw lin_flat_map; exrepnd.\n    allrw @in_range_iff; exrepnd.\n    allrw @in_sub_keep_first; repnd.\n    allsimpl; repndors; subst; tcsp.\n\n    + rw h1 in e; ginv; allsimpl; repndors; tcsp.\n\n    + right.\n      exists x0; dands; auto.\n      rw @in_range_iff.\n      exists v0.\n      rw @in_sub_keep_first; dands; auto.\n\n  - allunfold @get_utokens_sub.\n    allrw lin_flat_map; exrepnd.\n    allrw @in_range_iff; exrepnd.\n    allrw @in_sub_keep_first; repnd.\n    right.\n    exists x0; dands; auto.\n    rw @in_range_iff.\n    exists v0.\n    rw @in_sub_keep_first; dands; simpl; tcsp.\nQed.\n\nLemma implies_eqset_cons {T} :\n  forall (x : T) l1 l2,\n    eqset l1 l2\n    -> eqset (x :: l1) (x :: l2).\nProof.\n  introv e; introv; split; intro h; allsimpl; repndors; tcsp; right; apply e; auto.\nQed.\n\nLemma eqset_app_move2 :\n  forall {T} (a b c : list T),\n    eqset ((a ++ b) ++ c) ((a ++ c) ++ b).\nProof.\n  introv; introv; split; intro i; allrw in_app_iff; sp.\nQed.\n\nLemma nr_ut_sub_is_utok_sub {o} :\n  forall sub (t : @NTerm o),\n    nr_ut_sub t sub\n    -> is_utok_sub sub.\nProof.\n  induction sub; introv h; eauto 3 with slow.\n  - introv i; allsimpl; tcsp.\n  - destruct a as [v u].\n    apply is_utok_sub_cons.\n    apply nr_ut_sub_cons_iff in h; exrepnd; subst.\n    apply IHsub in h0; simpl; dands; auto.\nQed.\nHint Resolve nr_ut_sub_is_utok_sub : slow.\n\nLemma get_utokens_step_seq_lsubst_aux_is_utok_sub {o} :\n  forall (t : @NTerm o) (sub : Substitution),\n    is_utok_sub sub\n    -> eqset\n         (get_utokens_step_seq (lsubst_aux t sub))\n         (get_utokens_step_seq t ++ get_utokens_sub (sub_keep_first sub (free_vars t))).\nProof.\n  nterm_ind1s t as [v|f ind|op bs ind] Case; introv isus; simpl; autorewrite with slow; auto.\n\n  - Case \"vterm\".\n    rw @sub_keep_singleton.\n    remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf;\n    simpl; autorewrite with slow; auto.\n    rw @get_utokens_sub_cons; autorewrite with slow; eauto 3 with slow.\n    apply sub_find_some in Heqsf.\n    apply isus in Heqsf.\n    apply is_utok_implies in Heqsf; exrepnd; subst; simpl; auto.\n\n  - Case \"oterm\".\n    dopid op as [can|ncan|exc|abs] SCase; simpl; autorewrite with slow;\n    try (complete (apply eqset_flat_map_get_utokens_step_seq_b_is_utok_sub; auto));[|].\n\n    + rw <- app_assoc.\n      apply eqset_app_if; auto.\n      apply eqset_flat_map_get_utokens_step_seq_b_is_utok_sub; auto.\n\n    + destruct ncan; allsimpl; autorewrite with slow in *;\n      try (complete (apply eqset_flat_map_get_utokens_step_seq_b_is_utok_sub; auto));\n      allrw @fold_get_utokens_step_seq_bterms_seq;[|].\n\n      * eapply eqset_trans;[|apply eqset_sym;apply eqset_app_move2].\n        apply eqset_app_if.\n\n        { apply eqset_flat_map_get_utokens_step_seq_b_is_utok_sub; auto. }\n\n        { destruct bs as [|b bs]; simpl; auto.\n          destruct b as [l t]; simpl.\n          destruct l as [|v l]; allsimpl; auto; autorewrite with slow.\n          destruct t as [v|f|op bs1]; allsimpl; auto;[|].\n\n          - remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf;\n            allsimpl; autorewrite with slow; auto;[].\n            applydup @sub_find_some in Heqsf as j.\n            apply isus in j.\n            apply is_utok_implies in j; exrepnd; subst; allsimpl; autorewrite with slow in *; auto.\n\n          - destruct bs as [|b bs]; allsimpl; auto;[].\n            destruct b as [l t]; allsimpl.\n            destruct l as [|v l]; allsimpl; autorewrite with slow; auto;[].\n            destruct t as [v|f1|op bs1]; allsimpl; auto;[].\n            remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf;\n            allsimpl; autorewrite with slow; auto;[].\n            applydup @sub_find_some in Heqsf as j.\n            apply isus in j.\n            apply is_utok_implies in j; exrepnd; subst; allsimpl; autorewrite with slow in *; auto.\n        }\n\n      * eapply eqset_trans;[|apply eqset_sym;apply eqset_app_move2].\n        apply eqset_app_if.\n\n        { apply eqset_flat_map_get_utokens_step_seq_b_is_utok_sub; auto. }\n\n        { destruct bs as [|b bs]; simpl; auto.\n          destruct b as [l t]; simpl.\n          destruct l as [|v l]; allsimpl; auto; autorewrite with slow.\n          destruct t as [v|f|op bs1]; allsimpl; auto;[|].\n\n          - remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf;\n            allsimpl; autorewrite with slow; auto;[].\n            applydup @sub_find_some in Heqsf as j.\n            apply isus in j.\n            apply is_utok_implies in j; exrepnd; subst; allsimpl; autorewrite with slow in *; auto.\n\n          - destruct bs as [|b bs]; allsimpl; auto;[].\n            destruct b as [l t]; allsimpl.\n            destruct l as [|v l]; allsimpl; autorewrite with slow; auto;[].\n            destruct t as [v|f1|op bs1]; allsimpl; auto;[].\n            remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf;\n            allsimpl; autorewrite with slow; auto;[].\n            applydup @sub_find_some in Heqsf as j.\n            apply isus in j.\n            apply is_utok_implies in j; exrepnd; subst; allsimpl; autorewrite with slow in *; auto.\n        }\nQed.\n\nLemma get_utokens_so_subset_get_cutokens_so {o} :\n  forall (t : @SOTerm o),\n    subseto (get_utokens_so t) (get_cutokens_so t).\nProof.\n  soterm_ind1s t as [v ts ind | |op bs ind] Case; simpl;\n  try (complete (eauto 3 with slow)).\n\n  - Case \"sovar\".\n    eapply subseto_oeqset;[|apply oeqset_sym;apply oeqset_oappl_OLL].\n    apply subseto_flat_map2; auto.\n\n  - Case \"soterm\".\n    eapply subseto_oeqset;[|apply oeqset_sym;apply oeqset_oappl_OLL].\n    apply subseto_app_l; dands; apply implies_subseto_app_r.\n\n    + left; apply subseto_refl.\n\n    + right.\n      apply subseto_flat_map2; auto.\n      introv i.\n      destruct x as [l t]; allsimpl.\n      eapply ind; eauto.\nQed.\n\nLemma not_in_olist {T} :\n  forall (v : T), !in_olist v onil.\nProof.\n  introv h.\n  inversion h; subst; exrepnd; allsimpl; tcsp.\nQed.\n\nLemma no_utokens_implies_get_utokens_so_nil {o} :\n  forall (t : @SOTerm o),\n    no_utokens t\n    -> get_utokens_so t = [].\nProof.\n  introv h.\n  unfold no_utokens in h; auto.\nQed.\n\nLemma compute_step_subst_utoken {o} :\n  forall lib (t u : @NTerm o) sub,\n    nt_wf t\n    -> compute_step lib (lsubst t sub) = csuccess u\n    -> nr_ut_sub t sub\n    -> disjoint (get_utokens_sub sub) (get_utokens t)\n    -> {w : NTerm\n        & alpha_eq u (lsubst w sub)\n        # disjoint (get_utokens_sub sub) (get_utokens w)\n        # subvars (free_vars w) (free_vars t)\n        # subset (get_utokens w) (get_utokens t)\n        # (forall sub',\n             nr_ut_sub t sub'\n             -> dom_sub sub = dom_sub sub'\n             -> disjoint (get_utokens_sub sub') (get_utokens t)\n             -> {s : NTerm\n                 & compute_step lib (lsubst t sub') = csuccess s\n                 # alpha_eq s (lsubst w sub')})}.\nProof.\n  nterm_ind1s t as [v|f ind|op bs ind] Case; introv wf comp nrut disj; tcsp.\n\n  - Case \"vterm\".\n    unflsubst in comp; eauto with slow.\n    allsimpl.\n    remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf.\n\n    + applydup @sub_find_some in Heqsf.\n      eapply in_nr_ut_sub in Heqsf0; eauto; exrepnd; subst.\n      csunf comp; allsimpl; ginv.\n      exists (@mk_var o v).\n      unflsubst; simpl; rw Heqsf; dands; eauto 3 with slow.\n      introv nrut' eqdoms disj'.\n      pose proof (sub_find_some_eq_doms_nr_ut_sub sub sub' v (vterm v)) as h.\n      repeat (autodimp h hyp).\n      rw Heqsf in h; exrepnd.\n      unflsubst; simpl; rw h0.\n      csunf; simpl.\n      eexists; dands; eauto.\n      unflsubst; simpl; rw h0; auto.\n\n    + csunf comp; allsimpl; ginv.\n\n  - Case \"sterm\".\n    allsimpl.\n    unflsubst in comp; allsimpl.\n    csunf comp; allsimpl; ginv.\n    exists (sterm f); simpl.\n    unflsubst; simpl.\n    dands; eauto 3 with slow.\n    introv nrut' eqdoms' disj'.\n    unflsubst; simpl.\n    csunf; simpl.\n    eexists; dands; eauto.\n\n  - Case \"oterm\".\n    dopid op as [can|ncan|exc|abs] SCase.\n\n    + SCase \"Can\".\n      unflsubst in comp; allsimpl.\n      csunf comp; allsimpl; ginv.\n      exists (oterm (Can can) bs).\n      allrw app_nil_r; allsimpl.\n      unflsubst; allsimpl; dands; eauto 3 with slow.\n\n      introv nrut' eqdoms disj'.\n      repeat unflsubst; simpl; csunf; simpl.\n      eexists; dands; eauto.\n\n    + SCase \"NCan\".\n      destruct bs; try (complete (allsimpl; ginv)).\n      destruct b as [l t]; try (complete (allsimpl; ginv)).\n      destruct l; try (complete (allsimpl; ginv)).\n\n      { destruct t as [x|f|op bts]; try (complete (allsimpl; ginv));\n        [ | | ].\n\n        { unflsubst in comp; allsimpl.\n          allrw @sub_filter_nil_r.\n          remember (sub_find sub x) as sf; symmetry in Heqsf; destruct sf;\n          [|csunf comp; allsimpl; ginv].\n\n          applydup @sub_find_some in Heqsf.\n          eapply in_nr_ut_sub in Heqsf0; eauto; exrepnd; subst.\n          apply compute_step_ncan_vterm_success in comp.\n          repndors; exrepnd; subst.\n\n          - exists (@mk_axiom o); allsimpl.\n            rw @cl_lsubst_trivial; simpl; dands; eauto with slow.\n            introv nrut' eqdoms disj'.\n            exists (@mk_axiom o); allsimpl.\n            rw (@cl_lsubst_trivial o mk_axiom); simpl; dands; eauto 3 with slow.\n            unflsubst; simpl; allrw @sub_filter_nil_r.\n            pose proof (sub_find_some_eq_doms_nr_ut_sub sub sub' x (oterm (NCan NParallel) (bterm [] (vterm x) :: bs))) as h; repeat (autodimp h hyp).\n            rw Heqsf in h; exrepnd; rw h0.\n            csunf; simpl.\n            unfold compute_step_parallel; auto.\n\n          - destruct bs; allsimpl; cpx; GC.\n            exists (@mk_apply o (mk_var x) (mk_fix (mk_var x))).\n            unflsubst; simpl; allrw @sub_filter_nil_r; allrw; dands; eauto 3 with slow.\n            introv nrut' eqdoms disj'.\n            repeat unflsubst; simpl; allrw @sub_filter_nil_r.\n            pose proof (sub_find_some_eq_doms_nr_ut_sub sub sub' x (oterm (NCan NFix) [bterm [] (vterm x)])) as h; repeat (autodimp h hyp).\n            rw Heqsf in h; exrepnd; rw h0.\n            csunf; simpl.\n            eexists; dands; eauto.\n\n          - destruct bs; allsimpl; cpx.\n            destruct bs; allsimpl; cpx.\n            destruct b0 as [l t].\n            destruct l; allsimpl; cpx.\n\n            exists (lsubst t [(x0, mk_var x)]).\n            dands; allrw app_nil_r.\n\n            + eapply alpha_eq_trans;[|apply alpha_eq_sym; apply combine_1var_sub]; eauto 2 with slow.\n              simpl.\n              unflsubst (@mk_var o x); simpl; rw Heqsf.\n              rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow.\n              unfold subst; rw <- @cl_lsubst_app; eauto 3 with slow; simpl.\n              apply alpha_eq_lsubst_if_ext_eq; auto.\n              introv i; simpl.\n              rw @sub_find_app; rw @sub_find_sub_filter_eq; rw memvar_singleton.\n              boolvar; simpl; boolvar; simpl; tcsp.\n              remember (sub_find sub v) as sf; destruct sf; allsimpl; auto.\n\n            + eapply disjoint_eqset_r;[apply eqset_sym; apply get_utokens_lsubst|].\n              eapply subset_disjoint_r; eauto 3 with slow.\n              apply app_subset; dands; eauto 3 with slow.\n              eapply subset_trans;[apply get_utokens_sub_sub_keep_first|].\n              unfold get_utokens_sub; simpl; auto.\n\n            + eapply subvars_eqvars;[|apply eqvars_sym; apply eqvars_free_vars_disjoint]; simpl.\n              unfold dom_sub; simpl; boolvar; simpl; allrw app_nil_r; eauto with slow.\n\n            + autorewrite with slow.\n              eapply subset_eqset_l;[apply eqset_sym;apply get_utokens_lsubst|].\n              unfold get_cutokens_sub; simpl; boolvar; simpl;\n              autorewrite with slow; eauto 3 with slow.\n\n            + introv nrut' eqdoms disj'.\n              unflsubst; simpl; allrw @sub_filter_nil_r.\n              pose proof (sub_find_some_eq_doms_nr_ut_sub\n                            sub sub' x\n                            (oterm (NCan NCbv) [bterm [] (vterm x), bterm [x0] t])) as h; repeat (autodimp h hyp).\n              rw Heqsf in h; exrepnd; rw h0.\n              csunf; simpl.\n              eexists; dands; eauto.\n              unfold apply_bterm; simpl.\n              rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow.\n              eapply alpha_eq_trans;[|apply alpha_eq_sym; apply combine_1var_sub]; eauto 2 with slow; simpl.\n              fold_terms; rw <- @cl_lsubst_app; eauto 3 with slow; simpl.\n              unflsubst (@mk_var o x); simpl; rw h0.\n              apply alpha_eq_lsubst_if_ext_eq; auto.\n              introv i; simpl.\n              rw @sub_find_app; rw @sub_find_sub_filter_eq; rw memvar_singleton.\n              boolvar; simpl; boolvar; simpl; tcsp.\n              remember (sub_find sub' v) as sf; destruct sf; allsimpl; auto.\n\n          - repeat (destruct bs; allsimpl; ginv).\n            destruct b0 as [l1 t1]; allsimpl.\n            destruct b1 as [l2 t2]; allsimpl.\n            allunfold @nobnd.\n            destruct l1, l2; allsimpl; ginv.\n            allrw @sub_filter_nil_r; allrw app_nil_r; allrw remove_nvars_nil_l.\n\n            exists (mk_atom_eq t1 t1 (mk_var x) mk_bot).\n            unflsubst; simpl.\n            allrw @sub_filter_nil_r; allrw app_nil_r; allrw remove_nvars_nil_l;\n            allrw @sub_find_sub_filter_eq;\n            allrw; dands; eauto 3 with slow.\n\n            { allrw disjoint_app_r; repnd; dands; eauto 3 with slow. }\n\n            { allrw subvars_app_l; dands; eauto 3 with slow. }\n\n            introv nrut' eqdoms disj'.\n            unflsubst; simpl; allrw @sub_filter_nil_r.\n            pose proof (sub_find_some_eq_doms_nr_ut_sub\n                          sub sub' x\n                          (oterm (NCan NTryCatch) [bterm [] (vterm x), bterm [] t1, bterm [x0] t2])) as h; repeat (autodimp h hyp).\n            rw Heqsf in h; exrepnd; rw h0.\n            csunf; simpl.\n            eexists; dands; eauto; fold_terms.\n            unflsubst; simpl;\n            allrw @sub_filter_nil_r;\n            allrw @sub_find_sub_filter_eq;\n            allrw memvar_singleton;\n            allrw <- beq_var_refl;\n            allrw; auto.\n\n          - repndors; exrepnd; subst.\n\n            + repeat (destruct bs; allsimpl; ginv).\n              destruct b as [l1 u1].\n              destruct b0 as [l2 u2].\n              destruct b1 as [l3 u3]; allsimpl.\n              destruct l1, l2, l3; allsimpl; boolvar; ginv;[].\n              allrw @sub_filter_nil_r; allrw app_nil_r.\n              allunfold @nobnd.\n              repeat (apply cons_inj in comp1; repnd); GC; ginv.\n              inversion comp0 as [epk]; clear comp0.\n              fold_terms.\n\n              repndors; repnd; subst; allrw @sub_filter_nil_r.\n\n              * exists u2.\n                unflsubst; dands; eauto 4 with slow.\n\n                introv nrut' eqdoms disj'.\n                pose proof (sub_find_some_eq_doms_nr_ut_sub\n                              sub sub' x\n                              (oterm (NCan (NCompOp CompOpEq))\n                                     [nobnd (mk_var x), nobnd u1, nobnd u2, nobnd u3])) as h; repeat (autodimp h hyp).\n                rw Heqsf in h; exrepnd.\n                unflsubst; simpl; allrw @sub_filter_nil_r; allrw.\n                assert (disjoint (get_utokens_sub sub) (get_utokens u1)) as ni2.\n                { allrw disjoint_app_r; sp. }\n                applydup @sub_find_some in Heqsf.\n                unfold get_utokens_sub in ni2.\n                apply in_sub_eta in Heqsf0; repnd.\n                disj_flat_map; allsimpl; allrw disjoint_singleton_l.\n                eapply lsubst_aux_utoken_eq_utoken_implies in Heqsf2; eauto; exrepnd; subst; allsimpl; allrw Heqsf2; GC.\n                pose proof (nr_ut_sub_some_eq\n                              sub v x a (oterm (NCan (NCompOp CompOpEq))\n                                               [nobnd (mk_var x), nobnd (mk_var v), nobnd u2, nobnd u3]))\n                  as k; repeat (autodimp k hyp); subst; simpl; tcsp.\n                allrw; csunf; simpl; boolvar; allsimpl; tcsp; GC.\n                dcwf h; allsimpl.\n                unfold compute_step_comp; simpl; boolvar; tcsp; GC.\n                eexists; dands; eauto.\n                unflsubst; auto.\n\n              * exists u3.\n                unflsubst; dands; eauto 4 with slow.\n\n                introv nrut' eqdoms disj'.\n                pose proof (sub_find_some_eq_doms_nr_ut_sub\n                              sub sub' x\n                              (oterm (NCan (NCompOp CompOpEq))\n                                     [nobnd (mk_var x), nobnd u1, nobnd u2, nobnd u3])) as h; repeat (autodimp h hyp).\n                rw Heqsf in h; exrepnd.\n                unflsubst; simpl; allrw @sub_filter_nil_r; allrw app_nil_r; allrw.\n                allapply @lsubst_aux_pk2term_eq_utoken_implies_or; repndors; exrepnd; subst; allsimpl.\n\n                { dup epk1 as e.\n                  eapply nr_ut_some_implies in e;[|exact nrut].\n                  destruct e as [a' e].\n                  allapply @pk2term_utoken; subst; allsimpl.\n                  assert (a' <> a) as d by (intro e; subst; tcsp).\n\n                  pose proof (nr_ut_sub_some_diff\n                                sub v x a' a\n                                (oterm (NCan (NCompOp CompOpEq))\n                                       [nobnd (mk_var x), nobnd (mk_var v), nobnd u2, nobnd u3])) as h; repeat (autodimp h hyp).\n                  pose proof (sub_find_some_eq_doms_nr_ut_sub\n                                sub sub' v\n                                (oterm (NCan (NCompOp CompOpEq))\n                                       [nobnd (mk_var x), nobnd (mk_var v), nobnd u2, nobnd u3])) as k; repeat (autodimp k hyp).\n                  assert (sub_find sub v = Some (mk_utoken a')) as e by auto; allrw e; GC; exrepnd; rw k0.\n                  pose proof (nr_ut_sub_some_diff2\n                                sub' v x a1 a0\n                                (oterm (NCan (NCompOp CompOpEq))\n                                       [nobnd (mk_var x), nobnd (mk_var v), nobnd u2, nobnd u3])) as hh;\n                    repeat (autodimp hh hyp); allsimpl; tcsp.\n                  csunf; simpl; boolvar; allsimpl; tcsp; GC.\n                  dcwf q; allsimpl.\n                  unfold compute_step_comp; simpl; boolvar; ginv; tcsp.\n                  eexists; dands; eauto; unflsubst.\n                }\n\n                { allrw @lsubst_aux_pk2term.\n                  allrw @pk2term_eq; allsimpl; allrw app_nil_r.\n                  csunf; simpl.\n                  dcwf h.\n                  unfold compute_step_comp; simpl.\n                  allrw @get_param_from_cop_pk2can.\n                  boolvar; subst; eexists; dands; eauto; unflsubst.\n                  allsimpl.\n                  allrw disjoint_cons_r; repnd.\n                  apply sub_find_some in h0.\n                  rw @in_get_utokens_sub in disj'; destruct disj'.\n                  eexists; eexists; dands; eauto; simpl; auto.\n                }\n\n            + destruct bs; allsimpl; cpx.\n              destruct b as [l t].\n              destruct l; allsimpl; cpx; fold_terms; ginv.\n              allrw @sub_filter_nil_r.\n              pose proof (ind t t []) as h; repeat (autodimp h hyp); clear ind; eauto 3 with slow.\n              rw <- @cl_lsubst_lsubst_aux in comp1; eauto with slow.\n\n              allrw @nt_wf_NCompOp; exrepnd; ginv; allsimpl; autorewrite with slow in *.\n              allrw disjoint_app_r; repnd.\n\n              pose proof (h x0 sub) as k; clear h; repeat (autodimp k hyp).\n              { eapply nr_ut_sub_change_term;[|idtac|eauto];\n                allsimpl; allrw remove_nvars_nil_l; eauto with slow. }\n              exrepnd.\n\n              exists (oterm (NCan (NCompOp CompOpEq))\n                            (nobnd (mk_var x) :: nobnd w :: nobnd t3 :: nobnd t4 ::[])).\n              unflsubst; simpl; autorewrite with slow in *; allrw @sub_filter_nil_r; allrw.\n              dands; eauto 4 with slow.\n\n              * prove_alpha_eq4; allrw map_length.\n                introv k; destruct n; cpx.\n                destruct n; cpx.\n                apply alphaeqbt_nilv2.\n                unflsubst in k1.\n\n              * rw disjoint_app_r; dands; auto.\n                allrw disjoint_app_r; dands; eauto 3 with slow.\n\n              * introv nrut' eqdoms disj'.\n                unflsubst; simpl; allrw @sub_filter_nil_r.\n                pose proof (sub_find_some_eq_doms_nr_ut_sub\n                              sub sub' x\n                              (oterm (NCan (NCompOp CompOpEq))\n                                     (nobnd (mk_var x)\n                                            :: nobnd t2\n                                            :: nobnd t3\n                                            :: nobnd t4\n                                            :: []))) as h; repeat (autodimp h hyp).\n                rw Heqsf in h; exrepnd; allrw.\n                pose proof (k0 sub') as h; clear k0; repeat (autodimp h hyp).\n                { eapply nr_ut_sub_change_term;[|idtac|eauto];\n                  allsimpl; allrw remove_nvars_nil_l; eauto with slow. }\n                { allsimpl; introv i j; apply disj' in i.\n                  allrw in_app_iff; sp. }\n                exrepnd.\n                eapply isnoncan_like_lsubst_aux_nr_ut_implies in comp3; eauto.\n                unfold mk_utoken.\n                rw @compute_step_ncompop_ncanlike2; eauto with slow; boolvar; allsimpl; tcsp;[].\n                unflsubst in h2; fold_terms; rw h2.\n                eexists; dands; auto.\n                unflsubst; simpl; allrw @sub_filter_nil_r; allrw.\n\n                prove_alpha_eq4; allrw map_length.\n                introv k; destruct n; cpx.\n                destruct n; cpx.\n                apply alphaeqbt_nilv2.\n                unflsubst in h1.\n\n            + apply isexc_implies2 in comp2; exrepnd; subst.\n              destruct bs; allsimpl; ginv.\n              destruct b as [l1 t1].\n              destruct l1; allsimpl; ginv.\n              fold_terms; cpx.\n              allrw @sub_filter_nil_r.\n              destruct t1; allsimpl; ginv.\n              { remember (sub_find sub n) as sfn; symmetry in Heqsfn; destruct sfn; ginv.\n                apply sub_find_some in Heqsfn.\n                eapply in_nr_ut_sub in Heqsfn; eauto; exrepnd; ginv; auto. }\n              exists (oterm Exc l0).\n              unflsubst; simpl; dands; eauto 4 with slow.\n\n              introv nrut' eqdoms disj'.\n              pose proof (sub_find_some_eq_doms_nr_ut_sub\n                            sub sub' x\n                            (oterm (NCan (NCompOp CompOpEq))\n                                   (nobnd (mk_var x) :: nobnd (oterm Exc l0) :: bs))) as h; repeat (autodimp h hyp).\n              rw Heqsf in h; exrepnd; allrw.\n\n              unflsubst; simpl; allrw @sub_filter_nil_r; allrw.\n              csunf; simpl; boolvar; allsimpl; tcsp; GC.\n              eexists; dands; eauto.\n              unflsubst.\n\n          - repeat (destruct bs; allsimpl; ginv).\n            destruct b as [l1 u1].\n            destruct b0 as [l2 u2]; allsimpl.\n            destruct l1, l2; ginv; boolvar; tcsp; GC; fold_terms; ginv.\n            repndors; repnd; subst; allrw @sub_filter_nil_r.\n\n            + exists u1; unflsubst; dands; eauto 4 with slow.\n\n              introv nrut' eqdoms disj'.\n              unflsubst; simpl; boolvar.\n              allrw @sub_filter_nil_r.\n              pose proof (sub_find_some_eq_doms_nr_ut_sub\n                            sub sub' x\n                            (oterm (NCan (NCanTest CanIsuatom))\n                                   [nobnd (mk_var x), nobnd u1, nobnd u2])) as h; repeat (autodimp h hyp).\n              rw Heqsf in h; exrepnd; allrw.\n              csunf; simpl; eexists; dands; eauto.\n              unflsubst.\n\n            + exists u2; unflsubst; dands; eauto with slow.\n\n              introv nrut' eqdoms disj'.\n              unflsubst; simpl; boolvar.\n              allrw @sub_filter_nil_r.\n              pose proof (sub_find_some_eq_doms_nr_ut_sub\n                            sub sub' x\n                            (oterm (NCan (NCanTest x0))\n                                   [nobnd (mk_var x), nobnd u1, nobnd u2])) as h; repeat (autodimp h hyp).\n              rw Heqsf in h; exrepnd; allrw.\n              csunf; simpl; eexists; dands; eauto.\n              unflsubst.\n              destruct x0; sp.\n        }\n\n        { unflsubst in comp; allsimpl.\n          allrw @fold_get_utokens_step_seq_bterms.\n          allrw @fold_get_utokens_step_seq_ncan.\n          csunf comp; allsimpl.\n          dopid_noncan ncan SSCase; allsimpl; ginv.\n\n          - SSCase \"NApply\".\n            apply compute_step_seq_apply_success in comp; exrepnd; subst; allsimpl.\n            repeat (destruct bs; allsimpl; ginv).\n            allrw @fold_get_utokens_step_seq_bterm.\n            destruct b as [l t]; allsimpl.\n            allrw @fold_get_utokens_step_seq_arg1.\n            allunfold @nobnd.\n            destruct l; allsimpl; ginv.\n            autorewrite with slow in *.\n\n            exists (mk_eapply (mk_ntseq f) t).\n            unflsubst; simpl; autorewrite with slow in *; fold_terms.\n            allrw disjoint_app_r; repnd.\n            dands; eauto 3 with slow.\n\n            introv nrut' eqdoms' disj'.\n            unflsubst; simpl; autorewrite with slow in *.\n            csunf; simpl.\n            eexists; dands; eauto.\n            unflsubst; simpl; autorewrite with slow in *.\n            eauto 3 with slow.\n\n          - SSCase \"NEApply\".\n            apply compute_step_eapply_success in comp; exrepnd; subst.\n            allunfold @nobnd.\n            destruct bs; allsimpl; ginv.\n            allrw @fold_get_utokens_step_seq_bterm.\n            destruct b as [vs t]; allsimpl.\n            allrw @fold_get_utokens_step_seq_arg1.\n            destruct vs; allsimpl; ginv.\n            autorewrite with slow in *.\n            allrw disjoint_app_r; repnd.\n\n            repndors; exrepnd; subst; allsimpl.\n\n            + apply compute_step_eapply2_success in comp1; repnd.\n              destruct bs; allsimpl; ginv; autorewrite with slow in *.\n              repndors; exrepnd; subst; ginv;[]; allsimpl.\n\n              allrw @nt_wf_eapply_iff; exrepnd; ginv; allsimpl.\n              allrw @nt_wf_sterm_iff.\n              pose proof (wf2 n) as seq; repnd; clear wf2.\n\n              exists (f0 n).\n              unflsubst.\n              eapply lsubst_aux_equal_mk_nat in comp4; eauto;[]; subst; allsimpl; GC.\n              boolvar; try omega;[].\n              allrw @Znat.Nat2Z.id.\n              unfold oatoms.\n              autorewrite with slow in *.\n              rw @lsubst_aux_trivial_cl_term2; auto;[].\n              try (rewrite seq).\n              try (rewrite seq1).\n              dands; eauto 3 with slow.\n\n              * introv nrut' eqdoms' disj'.\n                unflsubst; simpl.\n                csunf; simpl.\n                dcwf h;[].\n                unfold compute_step_eapply2; simpl; boolvar; try omega;[]; GC.\n                allrw @Znat.Nat2Z.id.\n                eexists; dands; eauto.\n                unflsubst.\n                rw @lsubst_aux_trivial_cl_term2; auto.\n\n            + eapply isexc_lsubst_aux_nr_ut_sub in comp0; eauto;[].\n              allrw @nt_wf_eapply_iff; exrepnd; ginv; allsimpl.\n              allrw @nt_wf_sterm_iff; autorewrite with slow in *.\n              apply wf_isexc_implies in comp0; auto;[].\n              exrepnd; subst; allsimpl; autorewrite with slow in *.\n              exists (mk_exception a e); simpl; autorewrite with slow in *.\n              unflsubst; simpl; autorewrite with slow in *.\n              allrw disjoint_app_r.\n              allrw subvars_app_l; repnd.\n              allrw @oeqset_oappl_cons.\n              dands; eauto 3 with slow;[].\n\n              introv nrut' eqdoms' diff'.\n              allrw disjoint_app_r; repnd.\n              unflsubst; simpl; autorewrite with slow in *.\n              csunf; simpl.\n              dcwf h;[].\n              eexists; dands; eauto.\n              unflsubst; simpl; autorewrite with slow in *; eauto 3 with slow.\n\n            + allrw @nt_wf_eapply_iff; exrepnd; ginv; allsimpl.\n              allrw @nt_wf_sterm_iff; autorewrite with slow in *.\n              pose proof (ind b b []) as h; clear ind; repeat (autodimp h hyp); eauto 3 with slow.\n              pose proof (h x sub) as ih; clear h; repeat (autodimp ih hyp); eauto 3 with slow.\n              { unflsubst; auto. }\n              { eapply nr_ut_sub_change_term;[| |exact nrut]; simpl; autorewrite with slow; auto. }\n              exrepnd;[].\n\n              exists (mk_eapply (mk_ntseq f) w); simpl; autorewrite with slow.\n              unflsubst; simpl; autorewrite with slow.\n              unfold oatoms.\n              allrw @oeqset_oappl_cons; autorewrite with slow.\n              unflsubst in ih1.\n              dands; repeat (apply osubset_oapp_left); eauto 3 with slow.\n              { prove_alpha_eq3. }\n\n              introv nrut' eqdoms' disj'.\n              unflsubst; simpl; autorewrite with slow in *.\n              eapply isnoncan_like_lsubst_aux_nr_ut_implies in comp3; eauto;[].\n              fold_terms; unfold mk_eapply.\n              rw @compute_step_eapply_iscan_isnoncan_like; simpl; eauto 3 with slow;[].\n              pose proof (ih0 sub') as h'; clear ih0.\n              repeat (autodimp h' hyp); eauto 3 with slow.\n              { eapply nr_ut_sub_change_term;[| |exact nrut']; simpl; autorewrite with slow; auto. }\n              exrepnd.\n              unflsubst in h'1.\n              rw h'1.\n              eexists; dands; eauto.\n              unflsubst; simpl; autorewrite with slow.\n              unflsubst in h'0.\n              prove_alpha_eq3.\n\n          - SSCase \"NFix\".\n            autorewrite with slow in *.\n            apply compute_step_fix_success in comp; repnd; subst.\n            destruct bs; allsimpl; ginv.\n            apply nt_wf_NFix in wf; exrepnd; subst; allunfold @nobnd; ginv.\n\n            exists (mk_apply (mk_ntseq f) (mk_fix (mk_ntseq f))).\n            unflsubst; simpl.\n            autorewrite with slow.\n            allrw @oeqset_oappl_cons; autorewrite with slow.\n            dands; repeat (apply osubset_oapp_left); eauto 3 with slow.\n\n            introv nrut' eqdoms' disj'.\n            unflsubst; simpl.\n            csunf; simpl.\n            eexists; dands; eauto.\n\n          - SSCase \"NCbv\".\n            autorewrite with slow in *.\n            apply nt_wf_NCbv in wf; exrepnd; allunfold @nobnd; ginv.\n            unfold apply_bterm; simpl.\n            repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n\n            exists (subst b v (mk_ntseq f)).\n            allsimpl; autorewrite with slow in *.\n\n            dands; eauto 3 with slow.\n\n            + pose proof (combine_sub_nest b (sub_filter sub [v]) [(v, mk_ntseq f)]) as aeq1.\n              rw @lsubst_sub_shallow_cl_sub in aeq1; eauto 3 with slow.\n              pose proof (combine_sub_nest b [(v,mk_ntseq f)] sub) as aeq2.\n              allrw @fold_subst.\n              eapply alpha_eq_trans;[clear aeq2|apply alpha_eq_sym;exact aeq2].\n              eapply alpha_eq_trans;[exact aeq1|clear aeq1].\n              apply alpha_eq_lsubst_if_ext_eq; auto.\n              unfold ext_alpha_eq_subs; simpl; introv i.\n              rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n              boolvar; simpl; boolvar; simpl; tcsp; GC.\n              remember (sub_find sub v0) as sf; destruct sf; simpl; tcsp.\n\n            + eapply disjoint_eqset_r;[apply eqset_sym; apply get_utokens_subst|].\n              boolvar; allrw disjoint_app_r; dands; eauto 3 with slow.\n\n            + eapply subvars_eqvars;[|apply eqvars_sym;apply eqvars_free_vars_disjoint].\n              allsimpl.\n              apply subvars_app_l; dands; auto.\n              boolvar; simpl; auto.\n\n            + eapply subset_eqset_l;[apply eqset_sym;apply get_utokens_subst|].\n              boolvar; simpl; autorewrite with slow; auto.\n\n            + introv nrut' eqdoms' disj'.\n              unflsubst; simpl.\n              csunf; simpl.\n              unfold apply_bterm; simpl.\n              eexists; dands; eauto.\n              repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n\n              pose proof (combine_sub_nest b (sub_filter sub' [v]) [(v, mk_ntseq f)]) as aeq1.\n              rw @lsubst_sub_shallow_cl_sub in aeq1; eauto 3 with slow;[].\n              pose proof (combine_sub_nest b [(v,mk_ntseq f)] sub') as aeq2.\n              allrw @fold_subst.\n              eapply alpha_eq_trans;[clear aeq2|apply alpha_eq_sym;exact aeq2].\n              eapply alpha_eq_trans;[exact aeq1|clear aeq1].\n              apply alpha_eq_lsubst_if_ext_eq; auto.\n              unfold ext_alpha_eq_subs; simpl; introv i.\n              rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n              boolvar; simpl; boolvar; simpl; tcsp; GC.\n              remember (sub_find sub' v0) as sf; destruct sf; simpl; tcsp.\n\n          - SSCase \"NTryCatch\".\n            allsimpl; autorewrite with slow in *.\n            allrw @nt_wf_NTryCatch; exrepnd; allunfold @nobnd; ginv.\n            allsimpl; autorewrite with slow in *.\n            exists (mk_atom_eq b b (mk_ntseq f) mk_bot).\n            unflsubst; simpl; autorewrite with slow in *.\n            allrw @sub_find_sub_filter_eq.\n            allrw memvar_singleton; boolvar; tcsp;[]; fold_terms.\n            allrw subvars_app_l.\n            allrw disjoint_app_r; repnd.\n            allrw @oeqset_oappl_cons.\n            dands; repeat (apply osubset_oapp_left); dands; eauto 4 with slow.\n\n            introv nrut' eqdoms' disj'.\n            unflsubst; simpl; autorewrite with slow in *.\n            csunf; simpl.\n            unflsubst; simpl; autorewrite with slow in *.\n            allrw @sub_find_sub_filter_eq.\n            allrw memvar_singleton; boolvar; tcsp;[]; fold_terms.\n            eexists; dands; eauto 3 with slow.\n\n          - SSCase \"NCanTest\".\n            apply compute_step_seq_can_test_success in comp; exrepnd; subst.\n            allrw @nt_wf_NCanTest; exrepnd; allunfold @nobnd; ginv; allsimpl.\n            autorewrite with slow in *.\n            allrw disjoint_app_r; repnd.\n\n            exists t3.\n            unflsubst.\n            dands; eauto 3 with slow.\n\n            introv nrut' eqdoms' disj'.\n            allrw disjoint_app_r.\n            unflsubst; simpl; autorewrite with slow in *.\n            csunf; simpl.\n            eexists; dands; eauto.\n            unflsubst; auto.\n        }\n\n        dopid op as [can2|ncan2|exc2|abs2] SSCase.\n\n        * SSCase \"Can\".\n          dopid_noncan ncan SSSCase.\n\n          { SSSCase \"NApply\".\n\n            clear ind; unflsubst in comp; allsimpl; csunf comp; simpl in comp.\n            apply compute_step_apply_success in comp; repndors; exrepnd; subst; fold_terms.\n\n            { repeat (destruct bs; allsimpl; ginv).\n              repeat (destruct bts; allsimpl; ginv).\n              destruct b0 as [l1 u1].\n              destruct b1 as [l2 u2].\n              destruct l1; allsimpl; ginv; fold_terms; cpx.\n              allrw @sub_filter_nil_r.\n\n              - exists (subst u2 v u1).\n                rw <- @cl_lsubst_lsubst_aux; try (complete (boolvar; eauto with slow)).\n                unfold subst.\n                autorewrite with slow in *.\n                dands; eauto 3 with slow.\n\n                + pose proof (combine_sub_nest u2 [(v, u1)] sub) as h.\n                  eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                  pose proof (combine_sub_nest u2 (sub_filter sub [v]) [(v, lsubst_aux u1 sub)]) as h.\n                  eapply alpha_eq_trans;[apply h|]; clear h.\n                  simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                  apply alpha_eq_lsubst_if_ext_eq; auto.\n                  rw <- @cl_lsubst_lsubst_aux; eauto with slow.\n                  unfold ext_alpha_eq_subs; simpl; introv i.\n                  rw @sub_find_app; rw @sub_find_sub_filter_eq; rw memvar_singleton.\n                  boolvar; simpl; boolvar; simpl; tcsp.\n                  remember (sub_find sub v0) as sf; destruct sf; simpl; tcsp.\n\n                + eapply subset_disjoint_r;[exact disj|]; simpl.\n                  eapply subset_eqset_l;[apply eqset_sym; apply get_utokens_lsubst|].\n                  simpl; boolvar; unfold get_utokens_sub; simpl; allrw app_nil_r; eauto with slow.\n\n                + allrw remove_nvars_nil_l; allrw app_nil_r.\n                  eapply subvars_eqvars;[|apply eqvars_sym; apply eqvars_free_vars_disjoint].\n                  simpl; boolvar; simpl; allrw app_nil_r; eauto with slow.\n\n                + autorewrite with slow.\n                  eapply subset_eqset_l;[apply eqset_sym;apply get_utokens_lsubst|].\n                  apply subset_app; dands; eauto 3 with slow.\n                  unfold get_utokens_sub; simpl; boolvar; simpl;\n                  autorewrite with slow; eauto 3 with slow.\n\n                + introv nrut' eqdoms diff'.\n                  unflsubst; simpl; allrw @sub_filter_nil_r.\n                  csunf; simpl.\n                  allrw <- @cl_lsubst_lsubst_aux; eauto with slow.\n                  eexists; dands; eauto.\n                  unfold apply_bterm; simpl.\n\n                  pose proof (combine_sub_nest u2 [(v,u1)] sub') as h.\n                  eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                  pose proof (combine_sub_nest u2 (sub_filter sub' [v]) [(v, lsubst u1 sub')]) as h.\n                  eapply alpha_eq_trans;[apply h|]; clear h.\n                  simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                  apply alpha_eq_lsubst_if_ext_eq; auto.\n                  unfold ext_alpha_eq_subs; simpl; introv i.\n                  rw @sub_find_app; rw @sub_find_sub_filter_eq; rw memvar_singleton.\n                  boolvar; simpl; boolvar; simpl; tcsp.\n                  remember (sub_find sub' v0) as sf; destruct sf; simpl; tcsp.\n            }\n\n            { destruct bts; ginv.\n              repeat (destruct bs; allsimpl; ginv).\n              destruct b as [l t].\n              destruct l; allsimpl; ginv.\n              allrw @sub_filter_nil_r; fold_terms; ginv.\n              allrw app_nil_r; allrw remove_nvars_nil_l.\n\n              exists (mk_eapply (mk_nseq f) t).\n              simpl; autorewrite with slow in *.\n              dands; eauto 3 with slow.\n\n              - unflsubst; simpl.\n                allrw @sub_filter_nil_r; fold_terms; auto.\n\n              - introv nrut' eqdoms diff'.\n                unflsubst; simpl; allrw @sub_filter_nil_r; fold_terms.\n                csunf; simpl.\n                eexists; dands; eauto.\n\n                unflsubst; simpl.\n                allrw @sub_filter_nil_r; fold_terms; auto.\n            }\n          }\n\n          { SSSCase \"NEApply\".\n\n            unflsubst in comp; allsimpl.\n            apply nt_wf_eapply_iff in wf; exrepnd; ginv.\n            csunf comp; allsimpl.\n            eapply compute_step_eapply_success in comp; exrepnd.\n            allunfold @nobnd; allsimpl; ginv; autorewrite with slow in *.\n            allrw disjoint_app_r; repnd.\n\n            repndors; exrepnd; subst.\n\n            - apply compute_step_eapply2_success in comp1; repnd; GC.\n              repndors; exrepnd; allsimpl; subst; ginv.\n\n              + repeat (destruct bts; allsimpl; ginv;[]).\n                destruct b1; allsimpl; ginv.\n                unfold mk_lam in comp3; ginv; autorewrite with slow in *.\n                unfold apply_bterm; simpl.\n                repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n\n                exists (subst n v b).\n                allsimpl; autorewrite with slow in *.\n\n                dands; eauto 3 with slow.\n\n                * eapply alpha_eq_trans;[apply combine_sub_nest|].\n                  eapply alpha_eq_trans;[|apply alpha_eq_sym; apply combine_sub_nest].\n                  simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow;[].\n                  apply alpha_eq_lsubst_if_ext_eq; auto.\n                  unfold ext_alpha_eq_subs; simpl; introv i.\n                  rw @sub_find_app; allrw @sub_find_sub_filter_eq; allrw memvar_cons.\n                  boolvar; simpl; boolvar; simpl; tcsp; GC;[].\n                  remember (sub_find sub v0) as sf; destruct sf; simpl; tcsp.\n\n                * eapply disjoint_eqset_r;[apply eqset_sym;apply get_utokens_subst|].\n                  allrw disjoint_app_r; dands; eauto 3 with slow.\n                  boolvar; eauto 3 with slow.\n\n                * eapply subvars_eqvars;[|apply eqvars_sym; apply eqvars_free_vars_disjoint].\n                  simpl; allrw subvars_app_l; dands; eauto 3 with slow.\n                  boolvar; simpl; autorewrite with slow; eauto 3 with slow.\n\n                * autorewrite with slow.\n                  eapply subset_eqset_l;[apply eqset_sym;apply get_utokens_lsubst|].\n                  apply subset_app; dands; eauto 3 with slow.\n                  unfold get_utokens_sub; simpl; boolvar; simpl;\n                  autorewrite with slow; eauto 3 with slow.\n\n                * introv nrut' eqdoms diff'.\n                  unflsubst; simpl; autorewrite with slow in *.\n                  fold_terms; unfold mk_eapply.\n                  rw @compute_step_eapply_lam_iscan; eauto 3 with slow;[].\n                  eexists; dands; eauto.\n                  repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow;[]).\n\n                  eapply alpha_eq_trans;[|apply alpha_eq_sym; apply combine_sub_nest].\n                  eapply alpha_eq_trans;[apply combine_sub_nest|].\n                  simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow;[].\n                  apply alpha_eq_lsubst_if_ext_eq; auto.\n                  unfold ext_alpha_eq_subs; simpl; introv i.\n                  rw @sub_find_app; rw @sub_find_sub_filter_eq; rw memvar_singleton.\n                  boolvar; simpl; boolvar; simpl; tcsp.\n                  remember (sub_find sub' v0) as sf; destruct sf; simpl; tcsp.\n\n              + allunfold @mk_nseq; destruct bts; allsimpl; ginv; allsimpl; fold_terms.\n                eapply lsubst_aux_equal_mk_nat in comp4;[|eauto]; subst; allsimpl.\n                exists (@mk_nat o (f n)); simpl.\n                unflsubst; simpl; fold_terms.\n                dands; eauto 3 with slow.\n                introv nrut' eqdoms diff'.\n                unflsubst; simpl; fold_terms.\n                csunf; simpl; dcwf h; simpl; boolvar; try omega;[].\n                rw Znat.Nat2Z.id.\n                eexists; dands; eauto.\n\n            - eapply isexc_lsubst_aux_nr_ut_sub in comp0; eauto;[].\n              apply wf_isexc_implies in comp0; exrepnd; subst; allsimpl; autorewrite with slow in *; auto;[].\n              allrw disjoint_app_r; repnd.\n              exists (mk_exception a e); unflsubst; simpl; autorewrite with slow in *.\n              allrw disjoint_app_r.\n              allrw subvars_app_l.\n              allrw @oappl_app_as_oapp.\n              allrw @oeqset_oappl_cons; autorewrite with slow in *.\n              dands; eauto 3 with slow.\n\n              introv nrut' eqdoms' disj'.\n              allrw disjoint_app_r; repnd.\n              unflsubst; simpl; autorewrite with slow in *.\n              fold_terms; unfold mk_eapply.\n              rw @compute_step_eapply_iscan_isexc; simpl; eauto 3 with slow;\n              [|eapply eapply_wf_def_len_implies;[|eauto];\n                allrw map_map; unfold compose;\n                apply eq_maps; introv i; destruct x; simpl; unfold num_bvars; simpl; auto].\n              eexists; dands; eauto.\n              unflsubst; simpl; autorewrite with slow in *; auto.\n\n            - pose proof (ind b b []) as h; clear ind.\n              repeat (autodimp h hyp); eauto 3 with slow;[].\n              pose proof (h x sub) as ih; clear h.\n              rw <- @cl_lsubst_lsubst_aux in comp1; eauto 3 with slow;[].\n              repeat (autodimp ih hyp); eauto 3 with slow.\n              { eapply nr_ut_sub_change_term;[| |exact nrut]; simpl;\n                autorewrite with slow in *; eauto 3 with slow. }\n              exrepnd.\n\n              exists (mk_eapply (oterm (Can can2) bts) w).\n              unflsubst; simpl; autorewrite with slow in *.\n              allrw disjoint_app_r; repnd.\n              allrw subvars_app_l.\n              allrw @oappl_app_as_oapp.\n              allrw @oeqset_oappl_cons; autorewrite with slow in *.\n              rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow;[].\n              dands; eauto 3 with slow.\n\n              + prove_alpha_eq3.\n\n              + introv nrut' eqdoms' disj'.\n                unflsubst; simpl; autorewrite with slow in *.\n                eapply isnoncan_like_lsubst_aux_nr_ut_implies in comp3; eauto;[].\n                fold_terms; unfold mk_eapply.\n                rw @compute_step_eapply_iscan_isnoncan_like; simpl; eauto 3 with slow;\n                [|eapply eapply_wf_def_len_implies;[|eauto];\n                  allrw map_map; unfold compose;\n                  apply eq_maps; introv i; destruct x0; simpl; unfold num_bvars; simpl; auto];\n                [].\n                pose proof (ih0 sub') as h'; clear ih0.\n                repeat (autodimp h' hyp); eauto 3 with slow.\n                { eapply nr_ut_sub_change_term;[| |exact nrut']; simpl;\n                  autorewrite with slow; eauto 3 with slow. }\n                exrepnd.\n                unflsubst in h'1.\n                rw h'1.\n                eexists; dands; eauto.\n                unflsubst; simpl; autorewrite with slow.\n                unflsubst in h'0.\n                prove_alpha_eq3.\n          }\n\n(*          { SSSCase \"NApseq\".\n\n            clear ind.\n            unflsubst in comp; allsimpl.\n            csunf comp; allsimpl.\n            apply compute_step_apseq_success in comp; exrepnd; subst; allsimpl.\n            repeat (destruct bts; allsimpl; ginv).\n            repeat (destruct bs; allsimpl; ginv).\n            fold_terms.\n\n            exists (@mk_nat o (n n0)).\n            unflsubst; simpl; fold_terms.\n            autorewrite with slow.\n            dands; eauto 3 with slow.\n            introv nrut' eqdoms diff'.\n            unflsubst; simpl.\n            csunf; simpl.\n            boolvar; try omega.\n            rw @Znat.Nat2Z.id.\n            eexists; dands; eauto.\n          }*)\n\n          { SSSCase \"NFix\".\n\n            clear ind; unflsubst in comp; allsimpl; csunf comp; simpl in comp.\n            apply compute_step_fix_success in comp; exrepnd; subst; fold_terms.\n            repeat (destruct bs; allsimpl; ginv).\n            allrw @sub_filter_nil_r.\n            exists (mk_apply (oterm (Can can2) bts) (mk_fix (oterm (Can can2) bts))).\n            unflsubst; simpl; autorewrite with slow.\n            allrw @oappl_app_as_oapp.\n            allrw @oeqset_oappl_cons; autorewrite with slow in *.\n            allrw @osubset_oapp_left_iff.\n            allrw disjoint_app_r; repnd.\n            allrw subset_app.\n\n            dands; eauto 3 with slow.\n\n            { introv nrut' eqdoms diff'.\n              unflsubst; simpl; allrw @sub_filter_nil_r.\n              csunf; simpl.\n              eexists; dands; eauto.\n              unflsubst; simpl; allrw @sub_filter_nil_r; auto.\n            }\n          }\n\n          { SSSCase \"NSpread\".\n\n            clear ind; unflsubst in comp; allsimpl; csunf comp; simpl in comp.\n            apply compute_step_spread_success in comp; exrepnd; subst; fold_terms.\n            repeat (destruct bs; allsimpl; ginv).\n            repeat (destruct bts; allsimpl; ginv).\n            destruct b0 as [l1 u1].\n            destruct b1 as [l2 u2].\n            destruct b2 as [l3 u3].\n            destruct l1; allsimpl; ginv; fold_terms; cpx.\n            autorewrite with slow in *.\n            allunfold @nobnd; ginv; allsimpl.\n\n            - exists (lsubst u1 [(va,u2),(vb,u3)]).\n              repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n              dands.\n\n              + pose proof (combine_sub_nest u1 [(va,u2),(vb,u3)] sub) as h.\n                eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                pose proof (combine_sub_nest u1 (sub_filter sub [va,vb]) [(va,lsubst u2 sub),(vb,lsubst u3 sub)]) as h.\n                eapply alpha_eq_trans;[apply h|]; clear h.\n                simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                apply alpha_eq_lsubst_if_ext_eq; auto.\n                unfold ext_alpha_eq_subs; simpl; introv i.\n                rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n                boolvar; simpl; boolvar; simpl; tcsp.\n                remember (sub_find sub v) as sf; destruct sf; simpl; tcsp.\n\n              + eapply subset_disjoint_r;[exact disj|]; simpl.\n                eapply subset_eqset_l;[apply eqset_sym; apply get_utokens_lsubst|].\n                simpl; boolvar; unfold get_utokens_sub; simpl; allrw app_nil_r;\n                allrw subset_app; dands; eauto with slow.\n\n              + allrw remove_nvars_nil_l; allrw app_nil_r.\n                eapply subvars_eqvars;[|apply eqvars_sym; apply eqvars_free_vars_disjoint].\n                simpl; boolvar; simpl; allrw app_nil_r; eauto with slow.\n\n              + eapply subset_eqset_l;[apply eqset_sym;apply get_utokens_lsubst|].\n                apply subset_app; dands; eauto 3 with slow.\n                unfold get_utokens_sub; simpl; boolvar; simpl;\n                autorewrite with slow; eauto 3 with slow.\n\n              + introv nrut' eqdoms diff'.\n                unflsubst; simpl.\n                csunf; simpl; allrw @sub_filter_nil_r.\n                eexists; dands; eauto.\n                unfold apply_bterm; simpl; allrw @lsubst_aux_nil.\n                repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n\n                pose proof (combine_sub_nest u1 [(va,u2),(vb,u3)] sub') as h.\n                eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                pose proof (combine_sub_nest u1 (sub_filter sub' [va,vb]) [(va,lsubst u2 sub'),(vb,lsubst u3 sub')]) as h.\n                eapply alpha_eq_trans;[apply h|]; clear h.\n                simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                apply alpha_eq_lsubst_if_ext_eq; auto.\n                unfold ext_alpha_eq_subs; simpl; introv i.\n                rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n                boolvar; simpl; boolvar; simpl; tcsp.\n                remember (sub_find sub' v) as sf; destruct sf; simpl; tcsp.\n          }\n\n          { SSSCase \"NDsup\".\n\n            clear ind; unflsubst in comp; allsimpl; csunf comp; simpl in comp.\n            apply compute_step_dsup_success in comp; exrepnd; subst; fold_terms.\n            repeat (destruct bs; allsimpl; ginv).\n            repeat (destruct bts; allsimpl; ginv).\n            destruct b0 as [l1 u1].\n            destruct b1 as [l2 u2].\n            destruct b2 as [l3 u3].\n            destruct l1; allsimpl; ginv; fold_terms; cpx.\n            autorewrite with slow in *.\n            allunfold @nobnd; ginv; allsimpl.\n\n            - exists (lsubst u1 [(va,u2),(vb,u3)]).\n              repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n              dands.\n\n              + pose proof (combine_sub_nest u1 [(va,u2),(vb,u3)] sub) as h.\n                eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                pose proof (combine_sub_nest u1 (sub_filter sub [va,vb]) [(va,lsubst u2 sub),(vb,lsubst u3 sub)]) as h.\n                eapply alpha_eq_trans;[apply h|]; clear h.\n                simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                apply alpha_eq_lsubst_if_ext_eq; auto.\n                unfold ext_alpha_eq_subs; simpl; introv i.\n                rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n                boolvar; simpl; boolvar; simpl; tcsp.\n                remember (sub_find sub v) as sf; destruct sf; simpl; tcsp.\n\n              + eapply subset_disjoint_r;[exact disj|]; simpl.\n                eapply subset_eqset_l;[apply eqset_sym; apply get_utokens_lsubst|].\n                simpl; boolvar; unfold get_utokens_sub; simpl; allrw app_nil_r;\n                allrw subset_app; dands; eauto with slow.\n\n              + allrw remove_nvars_nil_l; allrw app_nil_r.\n                eapply subvars_eqvars;[|apply eqvars_sym; apply eqvars_free_vars_disjoint].\n                simpl; boolvar; simpl; allrw app_nil_r; eauto with slow.\n\n              + eapply subset_eqset_l;[apply eqset_sym;apply get_utokens_lsubst|].\n                apply subset_app; dands; eauto 3 with slow.\n                unfold get_utokens_sub; simpl; boolvar; simpl;\n                autorewrite with slow; eauto 3 with slow.\n\n              + introv nrut' eqdoms diff'.\n                unflsubst; simpl.\n                csunf; simpl; allrw @sub_filter_nil_r.\n                eexists; dands; eauto.\n                unfold apply_bterm; simpl; allrw @lsubst_aux_nil.\n                repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n\n                pose proof (combine_sub_nest u1 [(va,u2),(vb,u3)] sub') as h.\n                eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                pose proof (combine_sub_nest u1 (sub_filter sub' [va,vb]) [(va,lsubst u2 sub'),(vb,lsubst u3 sub')]) as h.\n                eapply alpha_eq_trans;[apply h|]; clear h.\n                simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                apply alpha_eq_lsubst_if_ext_eq; auto.\n                unfold ext_alpha_eq_subs; simpl; introv i.\n                rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n                boolvar; simpl; boolvar; simpl; tcsp.\n                remember (sub_find sub' v) as sf; destruct sf; simpl; tcsp.\n          }\n\n          { SSSCase \"NDecide\".\n\n            clear ind; unflsubst in comp; allsimpl; csunf comp; simpl in comp.\n            apply compute_step_decide_success in comp; exrepnd; subst; fold_terms.\n            repeat (destruct bs; allsimpl; ginv).\n            repeat (destruct bts; allsimpl; ginv).\n            destruct b0 as [l1 u1].\n            destruct b1 as [l2 u2].\n            destruct b as [l3 u3].\n            destruct l1; allsimpl; ginv; fold_terms; cpx.\n            autorewrite with slow in *.\n            allunfold @nobnd; ginv; allsimpl.\n\n            repndors; repnd; subst; ginv; cpx; allrw memvar_singleton.\n\n            - exists (subst u3 v1 u2).\n              unfold subst.\n              repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n              dands.\n\n              + pose proof (combine_sub_nest u3 [(v1,u2)] sub) as h.\n                eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                pose proof (combine_sub_nest u3 (sub_filter sub [v1]) [(v1,lsubst u2 sub)]) as h.\n                eapply alpha_eq_trans;[apply h|]; clear h.\n                simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                apply alpha_eq_lsubst_if_ext_eq; auto.\n                unfold ext_alpha_eq_subs; simpl; introv i.\n                rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n                boolvar; simpl; boolvar; simpl; tcsp.\n                remember (sub_find sub v) as sf; destruct sf; simpl; tcsp.\n\n              + eapply subset_disjoint_r;[exact disj|]; simpl.\n                eapply subset_eqset_l;[apply eqset_sym; apply get_utokens_lsubst|].\n                simpl; boolvar; unfold get_utokens_sub; simpl; allrw app_nil_r;\n                allrw subset_app; dands; eauto with slow.\n\n              + allrw remove_nvars_nil_l; allrw app_nil_r.\n                eapply subvars_eqvars;[|apply eqvars_sym; apply eqvars_free_vars_disjoint].\n                simpl; boolvar; simpl; allrw app_nil_r; eauto with slow.\n\n              + eapply subset_eqset_l;[apply eqset_sym;apply get_utokens_lsubst|].\n                apply subset_app; dands; eauto 3 with slow.\n                unfold get_utokens_sub; simpl; boolvar; simpl;\n                autorewrite with slow; eauto 3 with slow.\n\n              + introv nrut' eqdoms diff'.\n                unflsubst; simpl.\n                allrw @sub_filter_nil_r; allsimpl.\n                csunf; simpl.\n                eexists; dands; eauto.\n                unfold apply_bterm; simpl; allrw @lsubst_aux_nil.\n                repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n\n                pose proof (combine_sub_nest u3 [(v1,u2)] sub') as h.\n                eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                pose proof (combine_sub_nest u3 (sub_filter sub' [v1]) [(v1,lsubst u2 sub')]) as h.\n                eapply alpha_eq_trans;[apply h|]; clear h.\n                simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                apply alpha_eq_lsubst_if_ext_eq; auto.\n                unfold ext_alpha_eq_subs; simpl; introv i.\n                rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n                boolvar; simpl; boolvar; simpl; tcsp.\n                remember (sub_find sub' v) as sf; destruct sf; simpl; tcsp.\n\n            - exists (subst u1 v2 u2).\n              unfold subst.\n              repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n              dands.\n\n              + pose proof (combine_sub_nest u1 [(v2,u2)] sub) as h.\n                eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                pose proof (combine_sub_nest u1 (sub_filter sub [v2]) [(v2,lsubst u2 sub)]) as h.\n                eapply alpha_eq_trans;[apply h|]; clear h.\n                simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                apply alpha_eq_lsubst_if_ext_eq; auto.\n                unfold ext_alpha_eq_subs; simpl; introv i.\n                rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n                boolvar; simpl; boolvar; simpl; tcsp.\n                remember (sub_find sub v) as sf; destruct sf; simpl; tcsp.\n\n              + eapply subset_disjoint_r;[exact disj|]; simpl.\n                eapply subset_eqset_l;[apply eqset_sym; apply get_utokens_lsubst|].\n                simpl; boolvar; unfold get_utokens_sub; simpl; allrw app_nil_r;\n                allrw subset_app; dands; eauto with slow.\n\n              + allrw remove_nvars_nil_l; allrw app_nil_r.\n                eapply subvars_eqvars;[|apply eqvars_sym; apply eqvars_free_vars_disjoint].\n                simpl; boolvar; simpl; allrw app_nil_r; eauto with slow.\n\n              + eapply subset_eqset_l;[apply eqset_sym;apply get_utokens_lsubst|].\n                apply subset_app; dands; eauto 3 with slow.\n                unfold get_utokens_sub; simpl; boolvar; simpl;\n                autorewrite with slow; eauto 3 with slow.\n\n              + introv nrut' eqdoms diff'.\n                unflsubst; simpl.\n                allrw @sub_filter_nil_r; allsimpl.\n                csunf; simpl.\n                eexists; dands; eauto.\n                unfold apply_bterm; simpl; allrw @lsubst_aux_nil.\n                repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n\n                pose proof (combine_sub_nest u1 [(v2,u2)] sub') as h.\n                eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                pose proof (combine_sub_nest u1 (sub_filter sub' [v2]) [(v2,lsubst u2 sub')]) as h.\n                eapply alpha_eq_trans;[apply h|]; clear h.\n                simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                apply alpha_eq_lsubst_if_ext_eq; auto.\n                unfold ext_alpha_eq_subs; simpl; introv i.\n                rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n                boolvar; simpl; boolvar; simpl; tcsp.\n                remember (sub_find sub' v) as sf; destruct sf; simpl; tcsp.\n          }\n\n          { SSSCase \"NCbv\".\n\n            clear ind; unflsubst in comp; allsimpl; csunf comp; simpl in comp.\n            apply compute_step_cbv_success in comp; exrepnd; subst; fold_terms.\n            repeat (destruct bs; allsimpl; ginv).\n            destruct b as [l1 u1].\n            destruct l1; allsimpl; ginv; fold_terms; cpx.\n            autorewrite with slow in *.\n\n            - exists (subst u1 v (oterm (Can can2) bts)).\n              repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n              unfold subst.\n              dands.\n\n              + pose proof (combine_sub_nest u1 [(v,oterm (Can can2) bts)] sub) as h.\n                eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                pose proof (combine_sub_nest u1 (sub_filter sub [v]) [(v, lsubst_aux (oterm (Can can2) bts) sub)]) as h.\n                eapply alpha_eq_trans;[apply h|]; clear h.\n                repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n                simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                apply alpha_eq_lsubst_if_ext_eq; auto.\n                unfold ext_alpha_eq_subs; simpl; introv i.\n                rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n                boolvar; simpl; boolvar; simpl; tcsp.\n                remember (sub_find sub v0) as sf; destruct sf; simpl; tcsp.\n\n              + eapply subset_disjoint_r;[exact disj|]; simpl.\n                eapply subset_eqset_l;[apply eqset_sym; apply get_utokens_lsubst|].\n                simpl; boolvar; unfold get_utokens_sub; simpl; allrw app_nil_r;\n                allrw subset_app; dands; eauto 3 with slow.\n\n              + allrw remove_nvars_nil_l; allrw app_nil_r.\n                eapply subvars_eqvars;[|apply eqvars_sym; apply eqvars_free_vars_disjoint].\n                simpl; boolvar; simpl; allrw app_nil_r; eauto with slow.\n\n              + eapply subset_eqset_l;[apply eqset_sym;apply get_utokens_lsubst|].\n                apply subset_app; dands; eauto 3 with slow.\n                unfold get_utokens_sub; simpl; boolvar; simpl;\n                autorewrite with slow; eauto 3 with slow.\n\n              + introv nrut' eqdoms diff'.\n                unflsubst; simpl.\n                allrw @sub_filter_nil_r.\n                csunf; simpl.\n                eexists; dands; eauto.\n                unfold apply_bterm; simpl; allrw @lsubst_aux_nil.\n                repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n\n                pose proof (combine_sub_nest u1 [(v,oterm (Can can2) bts)] sub') as h.\n                eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                pose proof (combine_sub_nest u1 (sub_filter sub' [v]) [(v, lsubst_aux (oterm (Can can2) bts) sub')]) as h.\n                eapply alpha_eq_trans;[apply h|]; clear h.\n                repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n                simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                apply alpha_eq_lsubst_if_ext_eq; auto.\n                unfold ext_alpha_eq_subs; simpl; introv i.\n                rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n                boolvar; simpl; boolvar; simpl; tcsp.\n                remember (sub_find sub' v0) as sf; destruct sf; simpl; tcsp.\n          }\n\n          { SSSCase \"NSleep\".\n\n            clear ind; unflsubst in comp; allsimpl; csunf comp; simpl in comp.\n            apply compute_step_sleep_success in comp; exrepnd; subst; fold_terms.\n            repeat (destruct bs; allsimpl; ginv).\n            repeat (destruct bts; allsimpl; ginv).\n\n            - exists (@mk_axiom o).\n              unflsubst; simpl; dands; eauto 3 with slow.\n\n              introv nrut' eqdoms diff'.\n              repeat (unflsubst; simpl).\n              csunf; simpl.\n              unfold compute_step_sleep; simpl.\n              eexists; dands; eauto.\n          }\n\n          { SSSCase \"NTUni\".\n\n            clear ind; unflsubst in comp; allsimpl; csunf comp; simpl in comp.\n            apply compute_step_tuni_success in comp; exrepnd; subst; fold_terms.\n            repeat (destruct bs; allsimpl; ginv).\n            repeat (destruct bts; allsimpl; ginv).\n\n            - exists (@mk_uni o n).\n              unflsubst; simpl; dands; eauto 3 with slow.\n\n              introv nrut' eqdoms diff'.\n              repeat (unflsubst; simpl).\n              csunf; simpl.\n              unfold compute_step_tuni; simpl.\n              boolvar; try omega.\n              eexists; dands; eauto.\n              rw Znat.Nat2Z.id; auto.\n          }\n\n          { SSSCase \"NMinus\".\n\n            clear ind; unflsubst in comp; allsimpl; csunf comp; simpl in comp.\n            apply compute_step_minus_success in comp; exrepnd; subst; fold_terms.\n            repeat (destruct bs; allsimpl; ginv).\n            repeat (destruct bts; allsimpl; ginv).\n\n            - exists (@mk_integer o (- z)).\n              unflsubst; simpl; dands; eauto 3 with slow.\n\n              introv nrut' eqdoms diff'.\n              repeat (unflsubst; simpl).\n              csunf; simpl.\n              unfold compute_step_minus; simpl.\n              eexists; dands; eauto.\n          }\n\n          { SSSCase \"NFresh\".\n\n            clear ind; unflsubst in comp; allsimpl; csunf comp; simpl in comp; ginv.\n          }\n\n          { SSSCase \"NTryCatch\".\n\n            clear ind; unflsubst in comp; allsimpl; csunf comp; simpl in comp.\n            allrw @sub_filter_nil_r.\n            apply compute_step_try_success in comp; exrepnd; subst; fold_terms.\n            repeat (destruct bs; allsimpl; ginv).\n            destruct b as [l1 u1].\n            destruct b0 as [l2 u2].\n            destruct l1; allsimpl; ginv; fold_terms; cpx.\n\n            - exists (mk_atom_eq u1 u1 (oterm (Can can2) bts) mk_bot).\n              unflsubst; simpl.\n              allrw @sub_filter_nil_r; allrw app_nil_r; allrw @remove_nvars_nil_l.\n              allrw @sub_find_sub_filter_eq; allrw memvar_singleton.\n              allrw <- beq_var_refl; simpl; fold_terms.\n              allrw subvars_app_l.\n              allrw subset_app.\n              allrw disjoint_app_r; repnd.\n              allrw @oappl_app_as_oapp; autorewrite with slow in *.\n              allrw @oeqset_oappl_cons; autorewrite with slow in *.\n              allrw @osubset_oapp_left_iff; autorewrite with slow.\n              dands; eauto 3 with slow.\n\n              introv nrut' eqdoms diff'.\n              unflsubst; simpl; allrw @sub_filter_nil_r.\n              csunf; simpl.\n              eexists; dands; eauto.\n              unflsubst.\n              simpl.\n              allrw @sub_filter_nil_r; allrw app_nil_r; allrw @remove_nvars_nil_l.\n              allrw @sub_find_sub_filter_eq; allrw memvar_singleton.\n              allrw <- beq_var_refl; auto.\n          }\n\n          { SSSCase \"NParallel\".\n            unflsubst in comp; allsimpl.\n            csunf comp; allsimpl.\n            apply compute_step_parallel_success in comp; subst; allsimpl.\n            exists (@mk_axiom o).\n            unflsubst; simpl; fold_terms.\n            dands; autorewrite with slow in *; eauto 3 with slow.\n            introv nrut' eqdoms disj'.\n            exists (@mk_axiom o); allsimpl.\n            rw (@cl_lsubst_trivial o mk_axiom); simpl; dands; eauto 3 with slow.\n            unflsubst.\n          }\n\n          { SSSCase \"NCompOp\".\n\n            unflsubst in comp; allsimpl.\n            allrw @sub_filter_nil_r.\n            apply compute_step_ncompop_can1_success in comp; repnd.\n            repndors; exrepnd; subst.\n\n            - (* Can case *)\n              repeat (destruct bs; allsimpl; ginv).\n              destruct b as [l1 u1].\n              destruct b0 as [l2 u2].\n              destruct b1 as [l3 u3].\n              destruct l1; allsimpl; ginv; fold_terms.\n              allrw @sub_filter_nil_r; allrw app_nil_r.\n              allunfold @nobnd.\n              repeat (apply cons_inj in comp1; repnd); GC; ginv.\n              inversion comp2 as [epk]; clear comp2.\n              fold_terms.\n              apply compute_step_compop_success_can_can in comp1; exrepnd; subst; GC.\n              repeat (destruct bts; allsimpl; ginv).\n              autorewrite with slow in *.\n              repndors; exrepnd; subst;\n              allrw @get_param_from_cop_some; subst; allsimpl; fold_terms.\n\n              + allapply @lsubst_aux_eq_spcan_implies; repndors; exrepnd; allsimpl;\n                subst; allsimpl; fold_terms; boolvar; ginv.\n\n                * assert (sub_find sub v = Some (mk_integer n2)) as e by auto.\n                  apply sub_find_some in e.\n                  eapply in_nr_ut_sub in e; eauto; exrepnd; ginv.\n\n                * assert (sub_find sub v = Some (mk_integer n2)) as e by auto.\n                  apply sub_find_some in e.\n                  eapply in_nr_ut_sub in e; eauto; exrepnd; ginv.\n\n                * exists u2; unflsubst; allsimpl; autorewrite with slow in *.\n                  allrw @oappl_app_as_oapp; autorewrite with slow in *.\n                  allrw @oeqset_oappl_cons; autorewrite with slow in *.\n                  allrw @osubset_oapp_left_iff; autorewrite with slow.\n                  dands; eauto 4 with slow.\n\n                  introv nrut' eqdoms diff'; unflsubst; simpl; fold_terms.\n                  allrw @sub_filter_nil_r.\n                  csunf; simpl; eexists; dands; eauto.\n                  boolvar; allsimpl; tcsp; GC.\n                  dcwf h; allsimpl;[].\n                  unfold compute_step_comp; simpl.\n                  boolvar; tcsp; try omega.\n                  unflsubst.\n\n                * exists u3; unflsubst; allsimpl; autorewrite with slow in *.\n                  allrw @oappl_app_as_oapp; autorewrite with slow in *.\n                  allrw @oeqset_oappl_cons; autorewrite with slow in *.\n                  allrw @osubset_oapp_left_iff; autorewrite with slow.\n                  dands; eauto 4 with slow.\n\n                  introv nrut' eqdoms diff'; unflsubst; simpl; fold_terms.\n                  allrw @sub_filter_nil_r.\n                  csunf; simpl; boolvar; allsimpl; tcsp; GC.\n                  dcwf h; allsimpl;[].\n                  unfold compute_step_comp; simpl.\n                  boolvar; tcsp; try omega.\n                  eexists; dands; eauto.\n                  unflsubst.\n\n              + allapply @lsubst_aux_eq_spcan_implies; repndors; exrepnd; allsimpl; subst; allsimpl.\n\n                * dup epk1 as sf.\n                  eapply nr_ut_some_implies in sf; eauto; exrepnd;[].\n                  rw <- @pk2term_eq in sf0.\n                  apply pk2term_utoken in sf0; subst; allsimpl; fold_terms.\n\n                  exists (if param_kind_deq pk1 (PKa a) then u2 else u3).\n                  allrw disjoint_app_r; repnd.\n                  autorewrite with slow in *.\n                  allrw @oappl_app_as_oapp; autorewrite with slow in *.\n                  allrw @oeqset_oappl_cons; autorewrite with slow in *.\n                  allrw @osubset_oapp_left_iff; autorewrite with slow.\n                  dands; boolvar; subst; eauto 3 with slow; try unflsubst;allsimpl;[|].\n\n                  { allrw disjoint_singleton_r.\n                    apply sub_find_some in epk1.\n                    rw @in_get_utokens_sub in disj0; destruct disj0.\n                    eexists; eexists; dands; eauto; simpl; auto. }\n\n                  { introv nrut' eqdoms diff'; unflsubst; simpl; fold_terms.\n                    allrw @sub_filter_nil_r; allsimpl.\n\n                    pose proof (sub_find_some_eq_doms_nr_ut_sub sub sub' v) as h.\n                    applydup h in nrut'; auto; clear h;[].\n                    rw epk1 in nrut'0; exrepnd.\n                    rw nrut'1; allsimpl.\n\n                    csunf; simpl.\n                    dcwf h; allsimpl;[].\n                    unfold compute_step_comp; simpl.\n                    allrw @get_param_from_cop_pk2can.\n                    unflsubst.\n                    boolvar; eexists; dands; eauto.\n\n                    subst; allsimpl.\n                    allrw disjoint_cons_r; repnd.\n                    apply sub_find_some in nrut'1.\n                    rw @in_get_utokens_sub in diff'; destruct diff'.\n                    eexists; eexists; dands; eauto; simpl; auto. }\n\n                * exists (if param_kind_deq pk1 pk2 then u2 else u3).\n                  allrw disjoint_app_r; repnd.\n                  autorewrite with slow in *.\n                  repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n                  repeat (allrw @oeqset_oappl_cons; autorewrite with slow in *).\n                  allrw @osubset_oapp_left_iff; autorewrite with slow.\n                  dands; boolvar; subst; eauto 4 with slow; try unflsubst;allsimpl.\n\n                  { introv nrut' eqdoms diff'; unflsubst; simpl; fold_terms.\n                    allrw @sub_filter_nil_r; allsimpl.\n                    csunf; simpl.\n                    dcwf h; allsimpl;[].\n                    unfold compute_step_comp; simpl.\n                    allrw @get_param_from_cop_pk2can; boolvar; tcsp.\n                    eexists; dands; eauto.\n                    unflsubst. }\n\n                  { introv nrut' eqdoms diff'; unflsubst; simpl; fold_terms.\n                    allrw @sub_filter_nil_r; allsimpl.\n                    csunf; simpl.\n                    dcwf h; allsimpl;[].\n                    unfold compute_step_comp; simpl.\n                    allrw @get_param_from_cop_pk2can; boolvar; tcsp.\n                    eexists; dands; eauto.\n                    unflsubst. }\n\n            - (* NCan/Abs Case *)\n              destruct bs; allsimpl; ginv.\n              destruct b as [l1 u1].\n              destruct l1; allsimpl; ginv; fold_terms; cpx; allsimpl.\n              allrw @sub_filter_nil_r.\n              pose proof (ind u1 u1 []) as h.\n              repeat (autodimp h hyp); clear ind; eauto 3 with slow.\n              rw <- @cl_lsubst_lsubst_aux in comp4; eauto 3 with slow.\n              allrw @nt_wf_NCompOp; exrepnd; ginv; allsimpl.\n              autorewrite with slow in *.\n              allrw disjoint_app_r; repnd.\n\n              pose proof (h t' sub) as k; clear h.\n              repeat (autodimp k hyp).\n              { eapply nr_ut_sub_change_term;[|idtac|eauto];\n                allsimpl; allrw remove_nvars_nil_l; eauto with slow. }\n              exrepnd.\n              exists (oterm (NCan (NCompOp c))\n                            (nobnd (oterm (Can can2) bts)\n                                   :: nobnd w\n                                   :: nobnd t3\n                                   :: nobnd t4\n                                   :: [])).\n              unflsubst; simpl.\n              repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n              repeat (allrw @oeqset_oappl_cons; autorewrite with slow in *).\n              allrw @osubset_oapp_left_iff; autorewrite with slow.\n              allrw subset_app.\n              dands; autorewrite with slow; eauto 4 with slow.\n\n              + prove_alpha_eq4; introv h; allrw map_length.\n                destruct n; cpx.\n                destruct n; cpx.\n                apply alphaeqbt_nilv2.\n                unflsubst in k1.\n\n              + repeat (rw disjoint_app_r); dands; eauto with slow;\n                eapply subset_disjoint_r; try (exact disj); simpl;\n                eauto with slow.\n\n              + introv nrut' eqdoms diff'.\n                unflsubst; simpl.\n                allrw @sub_filter_nil_r.\n                eapply isnoncan_like_lsubst_aux_nr_ut_implies in comp3; eauto.\n                rw @compute_step_ncompop_ncanlike2; boolvar; allsimpl; tcsp; eauto with slow.\n                dcwf h;[].\n                pose proof (k0 sub') as h; repeat (autodimp h hyp).\n                { eapply nr_ut_sub_change_term;[|idtac|eauto];\n                  allsimpl; allrw remove_nvars_nil_l; eauto with slow. }\n                { allsimpl; allrw disjoint_app_r; sp. }\n                exrepnd.\n                unflsubst in h1; rw h1.\n                eexists; dands; eauto.\n                unflsubst; simpl; allrw @sub_filter_nil_r.\n                prove_alpha_eq4; introv h; allrw map_length.\n                destruct n; cpx.\n                destruct n; cpx.\n                apply alphaeqbt_nilv2.\n                unflsubst in h0.\n\n            - (* Exc Case *)\n              destruct bs; allsimpl; cpx;[].\n              destruct b as [l1 u1].\n              destruct l1; allsimpl; ginv; fold_terms; cpx; allsimpl;[].\n              allrw @sub_filter_nil_r.\n              assert (isexc u1) as ise.\n              { eapply isexc_lsubst_aux_nr_ut_sub in comp1; eauto. }\n              apply isexc_implies2 in ise; exrepnd; subst; allsimpl; GC.\n              exists (oterm Exc l); unflsubst; simpl.\n              repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n              repeat (allrw @oeqset_oappl_cons; autorewrite with slow in *).\n              repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n              allrw @osubset_oapp_left_iff; autorewrite with slow.\n              dands; autorewrite with slow; eauto 4 with slow.\n\n              introv nrut' eqdoms diff'.\n              unflsubst; simpl; csunf; simpl; boolvar; allsimpl; tcsp.\n              dcwf h;[].\n              eexists; dands; eauto.\n              allrw @sub_filter_nil_r.\n              unflsubst.\n          }\n\n          { SSSCase \"NArithOp\".\n\n            unflsubst in comp; allsimpl.\n            apply compute_step_narithop_can1_success in comp; repnd.\n            repndors; exrepnd; subst.\n\n            - (* Can case *)\n              repeat (destruct bs; allsimpl; ginv);[].\n              destruct b as [l1 u1].\n              destruct l1; allsimpl; ginv; fold_terms; cpx; allsimpl;[].\n              allrw @sub_filter_nil_r.\n              apply compute_step_arithop_success_can_can in comp1; exrepnd; subst; GC.\n              repeat (destruct bts; allsimpl; ginv).\n              autorewrite with slow in *.\n              repndors; exrepnd; subst;\n              allapply @get_param_from_cop_pki;\n              allapply @get_param_from_cop_pka;\n              allapply @get_param_from_cop_pks;\n              subst; allsimpl; GC; fold_terms.\n\n              assert (lsubst_aux u1 sub = mk_integer n2) as e by auto.\n              allrw e; GC.\n\n              allapply @lsubst_aux_eq_spcan_implies; repndors; exrepnd; allsimpl;\n              subst; allsimpl; fold_terms; boolvar; ginv.\n\n              * assert (sub_find sub v = Some (mk_integer n2)) as e by auto.\n                apply sub_find_some in e.\n                eapply in_nr_ut_sub in e; eauto; exrepnd; ginv.\n\n              * exists (@mk_integer o (get_arith_op a n1 n2)); unflsubst; dands; simpl; eauto 3 with slow.\n                introv nrut' eqdoms diff'; unflsubst; simpl; fold_terms.\n                csunf; simpl; boolvar; allsimpl; tcsp; GC.\n                dcwf h;allsimpl;[].\n                eexists; dands; eauto.\n\n            - (* NCan/Abs Case *)\n              destruct bs; allsimpl; ginv.\n              destruct b as [l1 u1].\n              destruct l1; allsimpl; ginv; fold_terms; cpx; allsimpl.\n              allrw @sub_filter_nil_r.\n              pose proof (ind u1 u1 []) as h.\n              repeat (autodimp h hyp); clear ind; eauto 3 with slow.\n              rw <- @cl_lsubst_lsubst_aux in comp4; eauto 3 with slow.\n              allrw @nt_wf_NArithOp; exrepnd; ginv; allsimpl.\n              autorewrite with slow in *.\n              allrw disjoint_app_r; repnd.\n\n              pose proof (h t' sub) as k; clear h.\n              repeat (autodimp k hyp).\n              { eapply nr_ut_sub_change_term;[|idtac|eauto];\n                allsimpl; allrw remove_nvars_nil_l; eauto with slow. }\n              exrepnd.\n              exists (oterm (NCan (NArithOp a))\n                            (nobnd (oterm (Can can2) bts)\n                                   :: nobnd w\n                                   :: [])).\n              unflsubst; simpl.\n              repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n              repeat (allrw @oeqset_oappl_cons; autorewrite with slow in *).\n              allrw @osubset_oapp_left_iff; autorewrite with slow.\n              dands; autorewrite with slow; eauto 4 with slow.\n\n              + prove_alpha_eq4; introv h; allrw map_length; destruct n; cpx.\n                destruct n; cpx.\n                apply alphaeqbt_nilv2.\n                unflsubst in k1.\n\n              + repeat (rw disjoint_app_r); dands; eauto with slow;\n                eapply subset_disjoint_r; try (exact disj); simpl;\n                eauto with slow.\n\n              + introv nrut' eqdoms diff'.\n                unflsubst; simpl; allrw @sub_filter_nil_r.\n                eapply isnoncan_like_lsubst_aux_nr_ut_implies in comp3; eauto.\n                rw @compute_step_narithop_ncanlike2; boolvar; allsimpl; tcsp; eauto with slow.\n                pose proof (k0 sub') as h; repeat (autodimp h hyp).\n                { eapply nr_ut_sub_change_term;[|idtac|eauto];\n                  allsimpl; allrw remove_nvars_nil_l; eauto with slow. }\n                { allsimpl; allrw disjoint_app_r; sp. }\n                exrepnd.\n                unflsubst in h1; rw h1.\n                dcwf h; allsimpl; [].\n                eexists; dands; eauto.\n                unflsubst; simpl; allrw @sub_filter_nil_r.\n                prove_alpha_eq4; introv h; allrw map_length.\n                destruct n; cpx.\n                destruct n; cpx.\n                apply alphaeqbt_nilv2.\n                unflsubst in h0.\n\n            - (* Exc Case *)\n              destruct bs; allsimpl; cpx.\n              destruct b as [l1 u1].\n              destruct l1; allsimpl; ginv; fold_terms; cpx; allsimpl.\n              allrw @sub_filter_nil_r.\n              assert (isexc u1) as ise.\n              { eapply isexc_lsubst_aux_nr_ut_sub in comp1; eauto. }\n              apply isexc_implies2 in ise; exrepnd; subst; allsimpl; GC.\n              exists (oterm Exc l); unflsubst; simpl.\n              repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n              repeat (allrw @oeqset_oappl_cons; autorewrite with slow in *).\n              repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n              allrw @osubset_oapp_left_iff; autorewrite with slow.\n              dands; autorewrite with slow; eauto 4 with slow.\n\n              introv nrut' eqdoms diff'.\n              unflsubst; simpl; csunf; simpl; boolvar; allsimpl; tcsp.\n              dcwf h; allsimpl; [].\n              eexists; dands; eauto.\n              allrw @sub_filter_nil_r.\n              unflsubst.\n          }\n\n          { SSSCase \"NCanTest\".\n\n            unflsubst in comp; allsimpl; csunf comp; allsimpl.\n            autorewrite with slow in *.\n            apply compute_step_can_test_success in comp; exrepnd.\n            repeat (destruct bs; allsimpl; ginv).\n            destruct b as [l1 u1].\n            destruct b0 as [l2 u2].\n            destruct l1; allsimpl; ginv; fold_terms; cpx; allsimpl.\n            allrw @sub_filter_nil_r.\n            exists (if canonical_form_test_for c can2 then u1 else u2).\n            repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n            repeat (allrw @oeqset_oappl_cons; autorewrite with slow in *).\n            repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n            allrw @osubset_oapp_left_iff; autorewrite with slow.\n            allrw disjoint_app_r; repnd.\n            unflsubst; simpl; dands; autorewrite with slow; eauto 4 with slow;\n            try (complete (remember (canonical_form_test_for c can2) as cft; destruct cft; eauto 3 with slow));\n            [].\n\n            introv nrut' eqdoms diff'.\n            unflsubst; simpl; csunf; simpl.\n            allrw @sub_filter_nil_r.\n            eexists; dands; eauto.\n            unflsubst.\n            remember (canonical_form_test_for c can2) as cft; destruct cft; auto.\n          }\n\n        * SSCase \"NCan\".\n          unflsubst in comp; allsimpl.\n\n          allrw @fold_get_utokens_step_seq_bterms_seq.\n          allrw @fold_get_utokens_step_seq_ncan_seq.\n          autorewrite with slow in *.\n          allrw disjoint_app_r; repnd.\n\n          rw @compute_step_ncan_ncan in comp.\n\n          remember (compute_step\n                      lib\n                      (oterm (NCan ncan2)\n                             (map (fun t : BTerm => lsubst_bterm_aux t sub)\n                                  bts))) as c; symmetry in Heqc; destruct c; ginv;[].\n\n          pose proof (ind (oterm (NCan ncan2) bts) (oterm (NCan ncan2) bts) []) as h.\n          repeat (autodimp h hyp); clear ind; eauto 3 with slow.\n\n          pose proof (h n sub) as k; clear h.\n          unflsubst in k; allsimpl.\n          allrw @fold_get_utokens_step_seq_bterms_seq.\n          allrw @fold_get_utokens_step_seq_ncan_seq.\n          autorewrite with slow in *.\n          allrw disjoint_app_r.\n          applydup @nt_wf_oterm_fst in wf.\n\n          repeat (autodimp k hyp);[|].\n          { eapply nr_ut_sub_change_term;[|idtac|eauto];\n            allsimpl; allrw remove_nvars_nil_l; eauto with slow. }\n          exrepnd.\n          exists (oterm (NCan ncan) (nobnd w :: bs)).\n          unflsubst; simpl.\n          autorewrite with slow in *.\n          allrw disjoint_app_r.\n          allrw subvars_app_l.\n          repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n          repeat (allrw @oeqset_oappl_cons; autorewrite with slow in *).\n          repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n          allrw @osubset_oapp_left_iff; autorewrite with slow.\n          dands; autorewrite with slow in *; eauto 3 with slow.\n\n          { prove_alpha_eq4; introv k; destruct n0; cpx.\n            apply alphaeqbt_nilv2.\n            unflsubst in k1. }\n\n          { introv nrut' eqdoms diff'.\n            pose proof (k0 sub') as h.\n            repeat (autodimp h hyp).\n            { eapply nr_ut_sub_change_term;[|idtac|eauto];\n              allsimpl; allrw remove_nvars_nil_l; eauto with slow. }\n            { allsimpl; allrw disjoint_app_r; sp. }\n            exrepnd.\n            unflsubst; simpl.\n            rw @compute_step_ncan_ncan.\n            allrw @sub_filter_nil_r.\n            unflsubst in h1; allsimpl; rw h1.\n            eexists; dands; eauto.\n            unflsubst; unflsubst in h0; simpl; allrw @sub_filter_nil_r.\n            prove_alpha_eq4; introv k; destruct n0; cpx.\n            apply alphaeqbt_nilv2; auto.\n          }\n\n        * SSCase \"Exc\".\n          unflsubst in comp; csunf comp; allsimpl.\n\n          autorewrite with slow in *.\n          allrw disjoint_app_r; repnd.\n\n          apply compute_step_catch_success in comp; repnd; repndors; exrepnd; subst.\n\n          { repeat (destruct bs; allsimpl; ginv).\n            repeat (destruct bts; allsimpl; ginv).\n            destruct b0 as [l1 u1].\n            destruct b1 as [l2 u2].\n            destruct b2 as [l3 u3].\n            destruct b3 as [l4 u4].\n            destruct l1; allsimpl; ginv; fold_terms; cpx; allsimpl.\n            autorewrite with slow in *.\n\n            exists (mk_atom_eq u1 u3 (subst u2 v u4) (mk_exception u3 u4)).\n            repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n            unfold subst.\n\n            allsimpl; autorewrite with slow in *.\n            allrw disjoint_app_r; repnd.\n            allrw subvars_app_l.\n            repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n            repeat (allrw @oeqset_oappl_cons; autorewrite with slow in *).\n            repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n            allrw @osubset_oapp_left_iff; autorewrite with slow.\n            allrw subset_app.\n\n            dands; eauto 4 with slow; fold_terms.\n\n            + eapply alpha_eq_trans;\n              [|apply alpha_eq_sym; apply alpha_eq_mk_atom_eq_lsubst].\n              apply implies_alpha_eq_mk_atom_eq; auto.\n\n              * pose proof (combine_sub_nest u2 [(v,u4)] sub) as h.\n                eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                pose proof (combine_sub_nest u2 (sub_filter sub [v]) [(v, lsubst u4 sub)]) as h.\n                eapply alpha_eq_trans;[apply h|]; clear h.\n                simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                apply alpha_eq_lsubst_if_ext_eq; auto.\n                unfold ext_alpha_eq_subs; simpl; introv i.\n                rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n                boolvar; simpl; boolvar; simpl; tcsp.\n                remember (sub_find sub v0) as sf; destruct sf; simpl; tcsp.\n\n              * eapply alpha_eq_trans;\n                [|apply alpha_eq_sym; apply alpha_eq_mk_exception_lsubst].\n                apply implies_alphaeq_exception; auto.\n\n            + eapply disjoint_eqset_r;[apply eqset_sym; apply get_utokens_lsubst|].\n              allrw disjoint_app_r; dands; eauto 3 with slow;[].\n              eapply subset_disjoint_r;[|apply get_utokens_sub_sub_keep_first].\n              unfold get_utokens_sub at 2; simpl; autorewrite with slow; eauto 3 with slow.\n\n            + simpl; allrw remove_nvars_nil_l; allrw app_nil_r.\n              allrw subvars_app_l; dands; eauto 4 with slow.\n              eapply subvars_eqvars;[|apply eqvars_sym; apply eqvars_free_vars_disjoint].\n              allsimpl; boolvar; allsimpl; allrw app_nil_r;\n              allrw subvars_app_l; dands; eauto with slow.\n\n            + eapply subset_eqset_l;[apply eqset_sym;apply get_utokens_lsubst|].\n              apply subset_app; dands; eauto 3 with slow.\n              unfold get_utokens_sub; simpl; boolvar; simpl;\n              autorewrite with slow; eauto 3 with slow.\n\n            + introv nrut' eqdoms diff'.\n              unflsubst; simpl.\n              csunf; simpl.\n              allrw @sub_filter_nil_r.\n              repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n              eexists; dands; eauto.\n\n              eapply alpha_eq_trans;\n                [|apply alpha_eq_sym; apply alpha_eq_mk_atom_eq_lsubst].\n              apply implies_alpha_eq_mk_atom_eq; auto.\n\n              * pose proof (combine_sub_nest u2 [(v,u4)] sub') as h.\n                eapply alpha_eq_trans;[|apply alpha_eq_sym; apply h]; clear h.\n                pose proof (combine_sub_nest u2 (sub_filter sub' [v]) [(v, lsubst u4 sub')]) as h.\n                eapply alpha_eq_trans;[apply h|]; clear h.\n                simpl; rw @lsubst_sub_shallow_cl_sub; eauto 3 with slow.\n                apply alpha_eq_lsubst_if_ext_eq; auto.\n                unfold ext_alpha_eq_subs; simpl; introv i.\n                rw @sub_find_app; rw @sub_find_sub_filter_eq; allrw memvar_cons.\n                boolvar; simpl; boolvar; simpl; tcsp.\n                remember (sub_find sub' v0) as sf; destruct sf; simpl; tcsp.\n\n              * eapply alpha_eq_trans;\n                [|apply alpha_eq_sym; apply alpha_eq_mk_exception_lsubst].\n                apply implies_alphaeq_exception; auto.\n          }\n\n          { exists (oterm Exc bts); unflsubst; simpl.\n            allrw @oappl_app_as_oapp; autorewrite with slow in *.\n            dands; eauto 3 with slow.\n\n            introv nrut' eqdoms diff'.\n            unflsubst; simpl.\n            csunf; simpl.\n            rw @compute_step_catch_if_diff; auto.\n            allrw @sub_filter_nil_r.\n            eexists; dands; eauto.\n            unflsubst.\n          }\n\n        * SSCase \"Abs\".\n          unflsubst in comp; allsimpl.\n\n          autorewrite with slow in *.\n          allrw disjoint_app_r; repnd.\n\n          rw @compute_step_ncan_abs in comp.\n\n          remember (compute_step_lib\n                      lib abs2\n                      (map (fun t : BTerm => lsubst_bterm_aux t sub)\n                           bts)) as c; symmetry in Heqc; destruct c; ginv.\n          pose proof (ind (oterm (Abs abs2) bts) (oterm (Abs abs2) bts) []) as h.\n          repeat (autodimp h hyp); clear ind; eauto 3 with slow.\n\n          pose proof (h n sub) as k; clear h.\n          unflsubst in k; allsimpl.\n          autorewrite with slow in *.\n          allrw disjoint_app_r.\n          applydup @nt_wf_oterm_fst in wf.\n\n          repeat (autodimp k hyp);[|].\n          { eapply nr_ut_sub_change_term;[|idtac|eauto];\n            allsimpl; allrw remove_nvars_nil_l; eauto with slow. }\n          exrepnd.\n          exists (oterm (NCan ncan) (nobnd w :: bs)).\n          unflsubst; simpl.\n          autorewrite with slow in *.\n          allrw disjoint_app_r.\n          allrw subvars_app_l.\n          repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n          repeat (allrw @oeqset_oappl_cons; autorewrite with slow in *).\n          repeat (allrw @oappl_app_as_oapp; autorewrite with slow in *).\n          allrw @osubset_oapp_left_iff; autorewrite with slow.\n          dands; autorewrite with slow in *; eauto 3 with slow.\n\n          { prove_alpha_eq4; introv k; destruct n0; cpx.\n            apply alphaeqbt_nilv2.\n            unflsubst in k1. }\n\n          { introv nrut' eqdoms diff'.\n            pose proof (k0 sub') as h.\n            repeat (autodimp h hyp).\n            { eapply nr_ut_sub_change_term;[|idtac|eauto];\n              allsimpl; allrw remove_nvars_nil_l; eauto with slow. }\n            { allsimpl; allrw disjoint_app_r; sp. }\n            exrepnd.\n            unflsubst; simpl.\n            rw @compute_step_ncan_abs.\n            allrw @sub_filter_nil_r.\n            unflsubst in h1; csunf h1; allsimpl; rw h1.\n            eexists; dands; eauto.\n            unflsubst; unflsubst in h0; simpl.\n            prove_alpha_eq4; introv k; destruct n0; cpx.\n            allrw @sub_filter_nil_r.\n            apply alphaeqbt_nilv2; auto.\n          }\n      }\n\n      { (* Fresh case *)\n        unflsubst in comp; csunf comp; allsimpl.\n        autorewrite with slow in *.\n        apply compute_step_fresh_success in comp; exrepnd; subst; allsimpl.\n        repeat (destruct bs; allsimpl; ginv); autorewrite with slow in *.\n        allrw @nt_wf_fresh.\n\n        repndors; exrepnd; subst.\n\n        - apply lsubst_aux_eq_vterm_implies in comp0; repndors; exrepnd; subst; allsimpl.\n          { apply sub_find_some in comp0.\n            apply in_cl_sub in comp0; eauto with slow.\n            allunfold @closed; allsimpl; sp. }\n\n          exists (@mk_fresh o n (mk_var n)); unflsubst; simpl.\n          autorewrite with slow in *.\n          dands; eauto 3 with slow.\n\n          introv ntuf' eqdoms diff'.\n          unflsubst; csunf.\n          simpl; rw @sub_find_sub_filter_eq; rw memvar_singleton; boolvar; tcsp.\n          exists (@mk_fresh o n (mk_var n)); dands; auto.\n          rw @cl_lsubst_trivial; simpl; eauto 3 with slow.\n          autorewrite with slow in *; simpl; auto.\n\n        - apply isvalue_like_lsubst_aux_implies in comp0;\n          repndors; exrepnd; subst; allsimpl; fold_terms.\n\n          + exists (pushdown_fresh n t).\n            rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow.\n            rw @get_utokens_pushdown_fresh.\n            rw @free_vars_pushdown_fresh.\n            dands; eauto 3 with slow.\n\n            * apply alpha_eq_sym.\n              apply cl_lsubst_pushdown_fresh; eauto 3 with slow.\n\n            * introv nrut' eqdoms' disj'.\n              unflsubst; simpl.\n              rw @compute_step_fresh_if_isvalue_like2; eauto 3 with slow.\n              eexists; dands; eauto.\n              rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow.\n              apply alpha_eq_sym.\n              apply cl_lsubst_pushdown_fresh; eauto with slow.\n\n          + allrw.\n            rw @sub_find_sub_filter_eq in comp1; rw memvar_singleton in comp1.\n            boolvar; ginv.\n            applydup @sub_find_some in comp1 as sf.\n            apply (in_nr_ut_sub _ _ _ (mk_fresh n (mk_var v))) in sf; auto.\n            exrepnd; subst.\n            allsimpl; fold_terms.\n            exists (@mk_var o v).\n            unflsubst; simpl; fold_terms.\n            allrw.\n            dands; eauto 3 with slow.\n\n            { rw subvars_prop; simpl; introv i; repndors; tcsp; subst.\n              rw in_remove_nvars; simpl; sp. }\n\n            { introv nrut' eqdoms' disj'.\n              unflsubst; simpl.\n              rw @sub_find_sub_filter_eq; rw memvar_singleton.\n              boolvar; tcsp.\n              pose proof (sub_find_some_eq_doms_nr_ut_sub sub sub' v (mk_fresh n (mk_var v))) as h.\n              repeat (autodimp h hyp).\n              rw comp1 in h; exrepnd.\n              rw h0.\n              csunf; simpl; fold_terms.\n              eexists; dands; eauto.\n              unflsubst; simpl; allrw; auto.\n            }\n\n        - apply (isnoncan_like_lsubst_aux_nr_ut_implies _ _ (oterm (NCan NFresh) [bterm [n] t])) in comp1;\n          [|apply nr_ut_sub_sub_filter_disj; auto; simpl;\n            rw app_nil_r; rw disjoint_singleton_l; rw in_remove_nvar;\n            complete sp].\n          repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n          repeat (rw <- @cl_lsubst_lsubst_aux in comp2; eauto 3 with slow).\n          remember (get_fresh_atom (lsubst t (sub_filter sub [n]))) as a'.\n          unfold subst in comp2.\n\n          pose proof (cl_lsubst_app t (sub_filter sub [n]) [(n,mk_utoken a')]) as h.\n          repeat (autodimp h hyp); eauto 3 with slow; rw <- h in comp2; clear h.\n\n          pose proof (ind t t [n]) as h.\n          repeat (autodimp h hyp); eauto 3 with slow.\n\n          pose proof (get_fresh_atom_prop (lsubst t (sub_filter sub [n]))) as fap.\n          rw <- Heqa' in fap.\n\n          pose proof (h x (sub_filter sub [n] ++ [(n, mk_utoken a')])) as k; clear h.\n          repeat (autodimp k hyp); eauto 3 with slow.\n\n          { apply implies_nr_ut_sub_app; eauto with slow.\n            - apply (nr_ut_sub_sub_filter_change_term_disj _ _ (mk_fresh n t)); allsimpl; tcsp; allrw app_nil_r; auto.\n              { apply disjoint_singleton_l; rw in_remove_nvars; simpl; sp. }\n              { rw subvars_prop; introv i; rw in_app_iff; rw in_remove_nvars; simpl.\n                destruct (deq_nvar x0 n); tcsp.\n                left; sp. }\n          }\n\n          { rw @get_utokens_sub_app; rw @get_utokens_sub_cons; rw @get_utokens_sub_nil; rw app_nil_r; simpl.\n            rw disjoint_app_l; rw disjoint_singleton_l; dands; eauto 3 with slow.\n            - apply (subset_disjoint _ _ (get_utokens_sub sub)); eauto 3 with slow.\n              apply get_utokens_sub_filter_subset.\n            - intro i; destruct fap.\n              unflsubst.\n              apply get_utokens_lsubst_aux; auto.\n              rw in_app_iff; sp.\n          }\n\n          exrepnd.\n          exists (mk_fresh n w); dands; allsimpl;\n          autorewrite with slow; eauto 3 with slow.\n\n          + pose proof (implies_alpha_eq_mk_fresh_subst_utokens\n                          n a' x\n                          (lsubst w (sub_filter sub [n] ++ [(n, mk_utoken a')]))\n                          k1) as h.\n            eapply alpha_eq_trans;[exact h|clear h].\n            allrw @get_utokens_sub_app; allrw @get_utokens_sub_cons; allrw @get_utokens_sub_nil.\n            allrw app_nil_r; allsimpl.\n            allrw disjoint_app_l; allrw disjoint_singleton_l; repnd.\n\n            pose proof (cl_lsubst_app w (sub_filter sub [n]) [(n,mk_utoken a')]) as h.\n            repeat (autodimp h hyp); eauto 3 with slow.\n            rw h; clear h; allrw @fold_subst.\n            eapply alpha_eq_trans;\n              [apply implies_alpha_eq_mk_fresh; apply simple_alphaeq_subst_utokens_subst|];\n              [|repeat unflsubst];[].\n\n            intro h.\n            allrw @get_utokens_lsubst; allrw in_app_iff; allrw not_over_or; repnd.\n            repndors; tcsp;[].\n\n            destruct fap.\n            allrw @in_get_utokens_sub; exrepnd.\n            exists v t0; dands; auto;[].\n            allrw @in_sub_keep_first; repnd; dands; auto.\n            rw subvars_prop in k3; apply k3 in h0; auto.\n\n          + apply subars_remove_nvars_lr; auto.\n\n          + introv nrut' eqdoms diff'.\n            unflsubst; simpl.\n            rw @compute_step_fresh_if_isnoncan_like; eauto with slow.\n            remember (get_fresh_atom (lsubst_aux t (sub_filter sub' [n]))) as a''.\n            unfold subst; repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow).\n            rw <- @cl_lsubst_app; eauto with slow.\n\n            pose proof (get_fresh_atom_prop (lsubst_aux t (sub_filter sub' [n]))) as fap'.\n            rw <- Heqa'' in fap'; repnd.\n            repeat (rw <- @cl_lsubst_lsubst_aux in fap'; eauto 3 with slow).\n\n            pose proof (k0 (sub_filter sub' [n] ++ [(n, mk_utoken a'')])) as h.\n            repeat (autodimp h hyp).\n\n            { apply implies_nr_ut_sub_app; eauto with slow.\n              - apply (nr_ut_sub_sub_filter_change_term_disj _ _ (mk_fresh n t)); allsimpl; tcsp; allrw app_nil_r; auto.\n                { apply disjoint_singleton_l; rw in_remove_nvars; simpl; sp. }\n                { rw subvars_prop; introv i; rw in_app_iff; rw in_remove_nvars; simpl.\n                  destruct (deq_nvar x0 n); tcsp.\n                  left; sp. }\n            }\n\n            { allrw @dom_sub_app; simpl; allrw <- @dom_sub_sub_filter; allrw; auto. }\n\n            { rw @get_utokens_sub_app; rw @get_utokens_sub_cons; rw @get_utokens_sub_nil; rw app_nil_r; simpl.\n              rw disjoint_app_l; rw disjoint_singleton_l; dands.\n              - apply (subset_disjoint _ _ (get_utokens_sub sub')); eauto with slow.\n                apply get_utokens_sub_filter_subset.\n              - intro i; destruct fap'.\n                unflsubst.\n                apply get_utokens_lsubst_aux; eauto 3 with slow.\n                rw in_app_iff; tcsp.\n            }\n\n            exrepnd.\n            rw h1; simpl.\n            eexists; dands; eauto.\n\n            pose proof (implies_alpha_eq_mk_fresh_subst_utokens\n                          n a'' s\n                          (lsubst w (sub_filter sub' [n] ++ [(n, mk_utoken a'')]))\n                          h0) as h.\n            eapply alpha_eq_trans;[exact h|clear h].\n\n            pose proof (cl_lsubst_app w (sub_filter sub' [n]) [(n,mk_utoken a'')]) as h.\n            repeat (autodimp h hyp); eauto 3 with slow.\n            rw h; clear h; allrw @fold_subst.\n            eapply alpha_eq_trans;[apply implies_alpha_eq_mk_fresh; apply simple_alphaeq_subst_utokens_subst|].\n\n            { intro h; destruct fap'.\n              allrw @get_utokens_lsubst; allrw in_app_iff; allrw not_over_or; repnd.\n              repndors; tcsp.\n              allrw @in_get_utokens_sub; exrepnd.\n              right.\n              exists v t0; dands; auto.\n              allrw @in_sub_keep_first; repnd; dands; auto.\n              rw subvars_prop in k3; apply k3 in h2; auto. }\n\n            repeat unflsubst.\n      }\n\n    + SCase \"Exc\".\n      unflsubst in comp; csunf comp; allsimpl; ginv.\n      exists (oterm Exc bs); unflsubst; simpl; dands; eauto with slow.\n\n      { introv nrut' eqdoms diff'.\n        unflsubst; csunf; simpl; eexists; dands; eauto. }\n\n    + SCase \"Abs\".\n      unflsubst in comp; csunf comp; allsimpl; ginv.\n      apply compute_step_lib_success in comp; exrepnd; subst.\n\n      pose proof (found_entry_change_bs abs oa2 vars rhs lib (lsubst_bterms_aux bs sub) correct bs comp0) as fe.\n      autodimp fe hyp.\n      { unfold lsubst_bterms_aux; rw map_map; unfold compose.\n        apply eq_maps; introv i; destruct x as [l t]; simpl.\n        unfold num_bvars; simpl; auto. }\n      apply found_entry_implies_matching_entry in fe; auto.\n      unfold matching_entry in fe; repnd.\n\n      exists (mk_instance vars bs rhs); unflsubst; simpl; dands;\n      autorewrite with slow; eauto with slow.\n\n      { pose proof (alpha_eq_lsubst_aux_mk_instance rhs vars bs sub) as h.\n        repeat (autodimp h hyp); eauto with slow. }\n\n      { eapply subset_disjoint_r;[|apply get_utokens_mk_instance]; auto.\n        eapply subset_disjoint_r;[exact disj|].\n        autorewrite with slow.\n        unfold correct_abs in correct; repnd.\n        dup correct as c.\n        apply no_utokens_implies_get_utokens_so_nil in c.\n        rw c; simpl.\n        apply subset_flat_map2; introv i; destruct x; simpl; eauto 3 with slow. }\n\n      { eapply subvars_trans;[apply subvars_free_vars_mk_instance|]; auto.\n        unfold correct_abs in correct; sp. }\n\n      { eapply subset_trans;[apply get_utokens_mk_instance|]; auto.\n        unfold correct_abs in correct; repnd.\n        dup correct as c.\n        apply no_utokens_implies_get_utokens_so_nil in c.\n        rw c; simpl.\n        apply subset_flat_map2; introv i; destruct x; simpl; eauto 3 with slow. }\n\n      { introv nrut' eqdoms diff'.\n        unflsubst; csunf; simpl.\n\n        pose proof (found_entry_change_bs abs oa2 vars rhs lib (lsubst_bterms_aux bs sub) correct (lsubst_bterms_aux bs sub') comp0) as fe'.\n        autodimp fe' hyp.\n        { unfold lsubst_bterms_aux; allrw map_map; unfold compose.\n          apply eq_maps; introv i; destruct x as [l t]; simpl.\n          unfold num_bvars; simpl; auto. }\n        apply found_entry_implies_compute_step_lib_success in fe'.\n        unfold lsubst_bterms_aux in fe'; rw fe'.\n        eexists; dands; eauto.\n        unflsubst.\n        fold (lsubst_bterms_aux bs sub').\n        apply alpha_eq_lsubst_aux_mk_instance; eauto with slow.\n      }\nQed.\n\nLemma compute_step_preserves_utokens {o} :\n  forall lib (t u : @NTerm o),\n    nt_wf t\n    -> compute_step lib t = csuccess u\n    -> subset (get_utokens u) (get_utokens t).\nProof.\n  introv wf comp.\n  pose proof (compute_step_subst_utoken lib t u []) as h.\n  autorewrite with slow in *.\n  repeat (autodimp h hyp); exrepnd; autorewrite with slow in *.\n  apply alphaeq_preserves_utokens in h1; rw h1; auto.\nQed.\n\n(*\nLemma compute_step_preserves_utokens {o} :\n  forall lib (t u : @NTerm o),\n    compute_step lib t = csuccess u\n    -> subset (get_utokens u) (get_utokens t).\nProof.\n  introv comp.\n  apply compute_step_preserves in comp; repnd.\n  introv i.\n  apply comp in i; sp.\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_preserve3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.2759074066719715}}
{"text": "(* name update:\n    old kon will now be called xon (eXact contents),\n    old update will be the new kon *)\n\n\n(*  donkey_sentence_4.v- simplifying the type of AND, etc, by only quantifying over one presupposition count,\n    removing a bunch of maxes *)\n\n(* id, comp, flip, eq_ind_dep, eq_trans', tnf, feq, feq2, feq3 *)\n    Definition id : forall {A : Type}, A -> A := fun (A : Type) (x : A) => x.\n    Definition comp : forall {A B C:Type},(B->C)->(A->B)->A->C := fun (A B C : Type) (f : B -> C) (g : A -> B) (x : A) => f (g x).\n    Infix \"∘\" := comp (at level 20).\n    Definition flip : forall {A B C:Type},(A->B->C)->B->A->C := fun (A B C : Type) (f : A -> B -> C) (y : B) (x : A) => f x y.\n    Definition eq_ind_dep : forall {A:Type} (x:A) (P:forall z:A, x = z -> Prop), P x eq_refl -> forall (y:A) (e:x=y), P y e\n        :=  fun (A : Type) (x : A) (P : forall z : A, x = z -> Prop) (p : P x eq_refl) (y : A) (e : x = y) =>\n            match e as d in (_ = z) return (P z d) with eq_refl => p end.\n    Definition eq_trans' : forall {A : Type} {x y z : A}, x = y -> x = z -> y = z\n        :=  fun (A : Type) (x y z : A) (u : x = y) (v : x = z) => eq_ind x (flip eq z) v y u.\n    Definition tnf : true <> false := eq_ind true (fun b : bool => if b then True else False) I false.\n\n    Definition feq  : forall {A B : Type} (f : A -> B) {x y : A}, x = y -> (f x) = (f y)\n        :=  fun (A B : Type) (f : A -> B) (x : A) => eq_ind x (fun z : A => (f x) = (f z)) eq_refl.\n    Definition feq2 : forall {A B C : Type} (f : A -> B -> C) {x a : A} {y b : B}, x = a -> y = b -> (f x y) = (f a b)\n        :=  fun (A B C : Type) (f : A -> B -> C) (x a : A) (y b : B) =>\n            eq_ind x (fun z : A => y = b -> (f x y) = (f z b)) (feq (f x)) a.\n    Definition feq3 : forall {A B C D : Type} (f : A -> B -> C -> D) {x a : A} {y b : B} {z c : C},\n            x = a -> y = b -> z = c -> (f x y z) = (f a b c)\n            :=  fun (A B C D : Type) (f : A -> B -> C -> D) (x a : A) (y b : B) (z c : C) =>\n                eq_ind  x (fun d : A => y = b -> z = c -> (f x y z) = (f d b c)) (feq2 (f x)) a.\n\n(* CDS_prims.v *)\n    Axiom e prop world      : Set.\n    Axiom tv                : prop -> world -> bool.\n    Axiom truth             : prop.\n    Axiom p_not             : prop -> prop.\n    Axiom p_and p_implies   : prop -> prop -> prop.\n\n    Section Statterm.\n        Inductive statterm : Set := ent : statterm | prp : statterm | func : statterm -> statterm -> statterm.\n        Fixpoint Sns (s : statterm) : Set := match s with ent => e | prp => prop | func a b => Sns a -> Sns b end.\n        (* for the record, Ext and ext_at aren't necessary for the dynamic stuff *)\n        Fixpoint Ext (s : statterm) : Set := match s with ent => e | prp => bool | func a b => Sns a -> Ext b end.\n        Fixpoint ext_at (s : statterm) : Sns s -> world -> Ext s\n            :=  match s as t return (Sns t -> world -> Ext t) with\n                    | ent       => fun (x : e) (_ : world) => x\n                    | prp       => tv\n                    | func a b  => fun (f : Sns a -> Sns b) (w : world) (x : Sns a) => ext_at b (f x) w\n                end.\n    End     Statterm.\n\n    Axiom p_exists p_forall : forall s : statterm, (Sns s -> prop) -> prop.\n\n    Module Import   Sem_notations.\n        Infix \"and\"         := p_and            (at level 80)   : sem_scope.\n        Infix \"implies\"     := p_implies        (at level 80)   : sem_scope.\n        Notation \"'not' p\"  := (p_not p)        (at level 80)   : sem_scope.\n        Notation \"p @ w\"    := (tv p w)         (at level 30)   : sem_scope.\n        Open Scope sem_scope.\n        Infix    \"~>\"       := implb            (at level 50)   : bool_scope.\n        Notation \"-~ x\"     := (negb x)         (at level 50)   : bool_scope.\n        Open Scope bool_scope.\n    End             Sem_notations.\n\n    Definition s_that   : (e -> prop) -> (e -> prop) -> e -> prop   := fun (P Q : e -> prop) (x : e) => (P x) and (Q x).\n    Infix \"that\"        := s_that (at level 80) : sem_scope.\n    Definition pex      : (e -> prop) -> prop   := p_exists ent.\n    Definition pfa      : (e -> prop) -> prop   := p_forall ent.\n    Definition some     : (e -> prop) -> (e -> prop) -> prop := fun P Q : e -> prop => pex (P that Q).\n    Definition every    : (e -> prop) -> (e -> prop) -> prop := fun P Q : e -> prop => pfa (fun x : e => (P x) implies (Q x)).\n\n    Definition p_entails : prop -> prop -> Prop := fun p q : prop => forall w : world, p@w = true -> q@w = true.\n    Infix \"entails\" := p_entails (at level 80) : sem_scope.\n    Definition p_equiv : prop -> prop -> Prop := fun p q : prop => (p entails q) /\\ (q entails p).\n    Infix \"≡\" := p_equiv (at level 80) : sem_scope.\n\n(* extensions.v (plus relevant extensional stuff from CDS_prims.v) *)\n    Section prop_axioms.\n        Axiom p_and_ax      : forall (p q : prop) (w : world), (p and q)@w = (p@w && q@w).\n        Axiom p_implies_ax  : forall (p q : prop) (w : world), (p implies q)@w = (p@w ~> q@w).\n        Axiom p_not_ax      : forall (p   : prop) (w : world), (not p)@w = -~(p@w).\n        Axiom truth_ax      : forall w : world, truth@w = true.\n        Axiom p_exists_ax   : forall (s : statterm) (R : Sns s -> prop) (w : world),\n            ((p_exists s R)@w = true) <-> ~(forall x : Sns s, (R x)@w = false).\n        Axiom p_forall_ax   : forall (s : statterm) (R : (Sns s) -> prop) (w : world),\n            ((p_forall s R)@w = true) <-> (forall x : Sns s, (R x)@w = true).\n    End prop_axioms.\n\n    Section prop_Theorems.\n        Definition dne          : forall p : prop, (not (not p)) entails p\n            :=  fun (p : prop) (w : world) (e : (not (not p))@w = true) =>\n                (if p@w as b return (-~(-~b) = true -> b = true) then id else id)\n                (eq_trans' (eq_trans (p_not_ax (not p) w) (feq negb (p_not_ax p w))) e).\n\n        Definition int_eq : forall p q : prop, (forall w : world, p@w = q@w) -> p ≡ q\n            :=  fun (p q : prop) (f : forall w : world, p@w = q@w) =>\n                conj (fun w : world => eq_trans' (f w)) (fun w : world => eq_trans (f w)).\n    End prop_Theorems.\n\n(* Vect.v *)\n    Inductive Vect (A : Type) : nat -> Type := vnil : Vect A 0 | vcons : forall n : nat, A -> Vect A n -> Vect A (S n).\n    Arguments vnil  {A}.\n    Arguments vcons {A} {n} _ _.\n\n    Module Import   VectNotes.\n        Notation \"[]\" := vnil (at level 0) : vect_scope.\n        Infix \"::\" := vcons (at level 60, right associativity) : vect_scope.\n        Open Scope vect_scope.\n        Notation \"[ x ]\" := ((x :: [])) (at level 0) : vect_scope.\n        Notation \"[ x , .. , y ]\" := ((vcons x .. (y :: []) ..)) (at level 0) : vect_scope.\n    End             VectNotes.\n\n    Definition head : forall {A : Type} {n : nat}, Vect A (S n) -> A\n        :=  fun (A : Type) (n : nat) (v : Vect A (S n)) =>\n            match v in (Vect _ m) return (if m then unit else A) with [] => tt | x :: _ => x end.\n\n    Definition tail : forall {A : Type} {n : nat}, Vect A (S n) -> Vect A n\n        :=  fun (A : Type) (n : nat) (v : Vect A (S n)) =>\n            match v in (Vect _ m) return (match m with 0 => unit | S k => Vect A k end) with [] => tt | _ :: xs => xs end.\n\n    Fixpoint append {A : Type} {m n : nat} (u : Vect A m) (v : Vect A n) : Vect A (m+n)\n        := match u in (Vect _ i) return (Vect A (i+n)) with [] => v | x :: l => x::(append l v) end.\n    Infix \"++\" := append (at level 60, right associativity) : vect_scope.\n\n    Fixpoint take (A : Type) (m n : nat) {struct m} : Vect A (m+n) -> Vect A m\n        :=  match m as k return (Vect A (k+n) -> Vect A k) with\n                | 0     => fun _ : Vect A n => []\n                | S i   => fun v : Vect A (S (i+n)) => (head v)::(take A i n (tail v))\n            end.\n    Fixpoint drop (A : Type) (m n : nat) {struct m} : Vect A (m+n) -> Vect A n\n        :=  match m as k return (Vect A (k+n) -> Vect A n) with\n                | 0     => id\n                | S i   => fun v : Vect A (S (i+n)) => drop A i n (tail v)\n            end.\n    Arguments take {A} m {n} v.\n    Arguments drop {A} m {n} v.\n    (* split_at? *)\n\n    Fixpoint nth {A : Type} (m : nat) {n : nat} : Vect A (S (m+n)) -> A\n        := match m as i return (Vect A (S (i+n)) -> A) with 0 => head | S i => fun v : Vect A (S (S (i+n))) => nth i (tail v) end.\n\n    (* h_frnt/k_frnt below the proofs section- need to move them below the proofs section b/c they rely on Zria/Zrix *)\n\n    Definition vcast : forall {A : Type} {m : nat}, Vect A m -> forall {n : nat}, m = n -> Vect A n\n        := fun (A : Type) (m : nat) => eq_rect m (Vect A).\n\n(* max and vmax *)\n    Fixpoint max (m n : nat) {struct m} : nat\n        := match m with 0 => n | S i => S (match n with 0 => i | S j => max i j end) end.\n\n    Fixpoint vmax {n : nat} : Vect nat n -> nat\n        :=  match n as k return (Vect nat k -> nat) with\n                | 0     =>  fun _ : Vect nat    0   => 0\n                | S i   =>  fun v : Vect nat (S i)  => max (S (head v)) (vmax (tail v))\n            end.\n\n(* Vect.v/DyCG.v Proofs *)\n    (* meta-proofs over equality *)\n        Definition refl_l_id_trans : forall {A : Type} {x y : A} (e : x = y), e = (eq_trans eq_refl e)\n            := fun (A : Type) (x : A) => eq_ind_dep x (fun (z : A) (d : x = z) => d = eq_trans eq_refl d) eq_refl.\n        Definition refl_r_id_trans': forall {A : Type} {x y : A} (e : x = y), (eq_sym e) = (eq_trans' e eq_refl)\n            := fun (A : Type) (x : A) => eq_ind_dep x (fun (z : A) (d : x = z) => (eq_sym d) = (eq_trans' d eq_refl)) eq_refl.\n        Definition feq_comp : forall {A B C : Type} (f : B -> C) (g : A -> B) {x y : A} (e : x = y),\n            (feq f (feq g e)) = (feq (f∘g) e)\n            :=  fun (A B C : Type) (f : B -> C) (g : A -> B) (x : A) =>\n                eq_ind_dep x (fun (z : A) (d : x = z) => (feq f (feq g d)) = (feq (f∘g) d)) eq_refl.\n        Definition feqovertrans : forall {A B : Type} (f : A -> B) {x y z : A} (p : x = y) (q : y = z),\n            (eq_trans (feq f p) (feq f q)) = (feq f (eq_trans p q))\n            :=  fun (A B : Type) (f : A -> B) (x y z : A) (p : x = y) =>\n                eq_ind_dep y (fun (k : A) (q : y = k) => (eq_trans (feq f p) (feq f q)) = (feq f (eq_trans p q))) eq_refl z.\n        Definition eq_rect_f1   : forall {A B : Type} (P : A -> Type) {x : A} (f : P x -> B) {y : A} (e : x = y) (p : P y),\n            (eq_rect x (fun z : A => P z -> B) f y e p) = (f (eq_rect y P p x (eq_sym e)))\n            :=  fun (A B : Type) (P : A -> Type) (x : A) (f : P x -> B) =>\n                eq_ind_dep  x (fun (y : A) (d : x = y) =>\n                               forall p : P y, (eq_rect x (fun z : A => P z -> B) f y d p) = (f (eq_rect y P p x (eq_sym d))))\n                            (fun p : P x => eq_refl).\n        Definition eq_rect_f2   : forall {A B : Type} (P : A -> Type) {x : A} (f : B -> P x) (b : B) {y : A} (e : x = y),\n            (eq_rect x (fun z : A => B -> P z) f y e b) = (eq_rect x P (f b) y e)\n            :=  fun (A B : Type) (P : A -> Type) (x : A) (f : B -> P x) (b : B) =>\n                eq_ind_dep  x (fun (y : A) (d : x = y) => (eq_rect x (fun z : A => B -> P z) f y d b) = (eq_rect x P (f b) y d))\n                            eq_refl.\n        Definition eq_rect_f3   : forall {A : Type} (P Q : A -> Type) {x : A} (f : P x -> Q x) {y : A} (e : x = y) (p : P y),\n            (eq_rect x (fun z : A => P z -> Q z) f y e p) = (eq_rect x Q (f (eq_rect y P p x (eq_sym e))) y e)\n            :=  fun (A : Type) (P Q : A -> Type) (x : A) (f : P x -> Q x) =>\n                eq_ind_dep x (fun (y : A) (d : x = y) => forall p : P y,\n                                (eq_rect x (fun z : A => P z -> Q z) f y d p) = (eq_rect x Q (f (eq_rect y P p x (eq_sym d))) y d))\n                    (fun p : P x => eq_refl).\n        Definition eq_rect_feq  : forall {A B : Type} (P : B -> Type) (f : A -> B) {x : A} (p : P (f x)) {y : A} (d : x = y),\n            (eq_rect (f x) P p (f y) (feq f d)) = (eq_rect x (P∘f) p y d)\n            :=  fun (A B : Type) (P : B -> Type) (f : A -> B) (x : A) (p : P (f x)) =>\n                eq_ind_dep x (fun (y : A) (d : x = y) => (eq_rect (f x) P p (f y) (feq f d)) = (eq_rect x (P∘f) p y d)) eq_refl.\n        Definition trans_inv1   : forall {A : Type} {x y : A} (p : x = y), (eq_trans (eq_sym p) p) = eq_refl\n            := fun (A : Type) (x : A) => eq_ind_dep x (fun (y : A) (p : x = y) => (eq_trans (eq_sym p) p) = eq_refl) eq_refl.\n        Definition trans_inv2   : forall {A : Type} {x y : A} (p : x = y), (eq_trans p (eq_sym p)) = eq_refl\n            := fun (A : Type) (x : A) => eq_ind_dep x (fun (y : A) (p : x = y) => (eq_trans p (eq_sym p)) = eq_refl) eq_refl.\n        Definition trans'_inv   : forall {A : Type} {x y : A} (p : x = y), (eq_trans' p p) = eq_refl\n            := fun (A : Type) (x : A) => eq_ind_dep x (fun (y : A) (p : x = y) => (eq_trans' p p) = eq_refl) eq_refl.\n        Definition feqoversym : forall {A B : Type} (f : A -> B) {x y : A} (d : x = y), (feq f (eq_sym d)) = (eq_sym (feq f d))\n            :=  fun (A B : Type) (f : A -> B) (x : A) =>\n                eq_ind_dep x (fun (y : A) (d : x = y) => (feq f (eq_sym d)) = (eq_sym (feq f d))) eq_refl.\n\n    (* Basic nat/addition proofs *)\n        Definition Zria         : forall n : nat, (n+0) = n\n            := nat_ind (fun n : nat => (n+0) = n) eq_refl (fun i : nat => feq S).\n        Definition Sdistr       : forall m j : nat, (S (m+j)) = (m+(S j))\n            := fun m j : nat => nat_ind (fun i : nat => (S (i+j)) = (i+(S j))) eq_refl (fun i : nat => feq S) m.\n        Definition add_comm     : forall m n : nat, (m+n) = (n+m)\n            :=  fun m : nat =>\n                nat_ind (fun n : nat => (m+n) = (n+m)) (Zria m)\n                        (fun (j : nat) (e : (m+j) = (j+m)) => eq_trans' (Sdistr m j) (feq S e)).\n        Definition add_assoc    : forall m n k : nat, (m+(n+k)) = ((m+n)+k)\n            := fun m n k : nat => nat_ind (fun i : nat => (i+(n+k)) = ((i+n)+k)) eq_refl (fun i : nat => feq S) m.\n        Definition assoc_flip   : forall m n k : nat, ((m+n)+k) = ((m+k)+n)\n            := fun m n k : nat => nat_ind (fun i : nat => ((i+n)+k) = ((i+k)+n)) (add_comm n k) (fun i : nat => feq S) m.\n\n    (* Vect proofs *)\n        Definition Vect_form : forall {A : Type} {n : nat} (v : Vect A n),\n                                (match n as m return (Vect A m -> Prop)\n                                 with 0 => eq [] | S i => fun u : Vect A (S i) => ((head u)::(tail u)) = u end) v\n            :=  fun (A : Type) (n : nat) (v : Vect A n) =>\n                match v as u in (Vect _ k)\n                return ((match k as m return (Vect A m -> Prop)\n                         with 0 => eq [] | S i => fun l : Vect A (S i) => ((head l)::(tail l)) = l end) u)\n                with [] => eq_refl | x::xs => eq_refl end.\n\n        (* \"vcast narrowing\" *)\n        Definition vcstnrw      : forall {A : Type} {m : nat} (v : Vect A (S m)) {n : nat} (e : m = n),\n            (vcast v (feq S e)) = ((head v)::(vcast (tail v) e))\n            :=  fun (A : Type) (m : nat) (v : Vect A (S m)) =>\n                eq_ind_dep m    (fun (n : nat) (d : m = n) => (vcast v (feq S d)) = ((head v)::(vcast (tail v) d)))\n                                (eq_sym (Vect_form v)).\n        Definition vcsttrans    : forall {A : Type} {m : nat} (v : Vect A m) {n k : nat} (p : m = n) (q : n = k),\n            (vcast (vcast v p) q) = (vcast v (eq_trans p q))\n            :=  fun (A : Type) (m : nat) (v : Vect A m) (n k : nat) (p : m = n) =>\n                eq_ind_dep n (fun (z : nat) (q : n = z) => (vcast (vcast v p) q) = (vcast v (eq_trans p q))) eq_refl k.\n        Definition vcstinj      : forall {A : Type} {m : nat} (u v : Vect A m) {n : nat} (e : m = n),\n            (vcast u e) = (vcast v e) -> u = v\n            :=  fun (A : Type) (m : nat) (u v : Vect A m) =>\n                eq_ind_dep m (fun (n : nat) (d : m = n) => (vcast u d) = (vcast v d) -> u = v) id.\n\n        Definition take_assoc   : forall {A : Type} (m n k : nat) (v : Vect A (m+(n+k))),\n            (take m v) = (take m (take (m+n) (vcast v (add_assoc m n k))))\n            :=  fun (A : Type) (m n k : nat) =>\n                nat_ind (fun i : nat => forall v : Vect A (i+(n+k)),\n                            (take i v) = (take i (take (i+n) (vcast v (add_assoc i n k)))))\n                        (fun _ : Vect A (n+k) => eq_refl)\n                        (fun (i : nat)\n                             (f : forall r : Vect A (i+(n+k)), (take i r) = (take i (take (i+n) (vcast r (add_assoc i n k)))))\n                             (v : Vect A (S (i+(n+k)))) =>\n                            eq_trans    (feq (vcons (head v)) (f (tail v)))\n                                        (eq_sym (feq    (fun u : Vect A (S ((i+n)+k)) => (head u)::(take i (take (i+n) (tail u))))\n                                                        (vcstnrw v (add_assoc i n k)))))\n                        m.\n        Definition drop_assoc   : forall {A : Type} (m n k : nat) (v : Vect A ((m+n)+k)),\n            (drop (m+n) v) = (drop n (drop m (vcast v (eq_sym (add_assoc m n k)))))\n            :=  fun (A : Type) (m n k : nat) =>\n                nat_ind (fun i : nat => forall v : Vect A ((i+n)+k),\n                            (drop (i+n) v) = (drop n (drop i (vcast v (eq_sym (add_assoc i n k))))))\n                        (fun v : Vect A (n+k) => eq_refl)\n                        (fun (i : nat) (f : forall r : Vect A ((i+n)+k),\n                                                (drop (i+n) r) = (drop n (drop i (vcast r (eq_sym (add_assoc i n k))))))\n                             (v : Vect A (S ((i+n)+k))) =>\n                            eq_trans    (f (tail v))\n                                        (eq_trans'  (feq    (fun u : Vect A (S (i+(n+k))) => drop n (drop i (tail u)))\n                                                            (vcstnrw v (eq_sym (add_assoc i n k))))\n                                                    (feq    (fun d : (S ((i+n)+k)) = (S (i+(n+k))) =>\n                                                                drop n (drop i (tail (vcast v d))))\n                                                            (feqoversym S (add_assoc i n k)))))\n                        m.\n        Definition take_assoc2  : forall {A : Type} (m n k : nat) (v : Vect A (m+(n+k))),\n            ((take m v) ++ (take n (drop m v))) = (take (m+n) (vcast v (add_assoc m n k)))\n            :=  fun (A : Type) (m n k : nat) =>\n                nat_ind (fun i : nat => forall v : Vect A (i+(n+k)),\n                            ((take i v) ++ (take n (drop i v))) = (take (i+n) (vcast v (add_assoc i n k))))\n                        (fun v : Vect A (n+k) => eq_refl)\n                        (fun (i : nat) (f : forall r : Vect A (i+(n+k)),\n                                            ((take i r) ++ (take n (drop i r))) = (take (i+n) (vcast r (add_assoc i n k))))\n                             (v : Vect A (S (i+(n+k)))) =>\n                            eq_trans    (feq    (vcons (head v)) (f (tail v)))\n                                        (eq_sym (feq    (fun u : Vect A (S ((i+n)+k)) => (head u)::(take (i+n) (tail u)))\n                                                        (vcstnrw v (add_assoc i n k)))))\n                        m.\n\n        Definition Nriap        : forall {A : Type} {n : nat} (v : Vect A n), v = (vcast (v ++ []) (Zria n))\n            :=  fun A : Type =>\n                Vect_ind A  (fun (n : nat) (v : Vect A n) => v = (vcast (v ++ []) (Zria n))) eq_refl\n                            (fun (i : nat) (x : A) (r : Vect A i) (e : r = (vcast (r ++ []) (Zria i))) =>\n                                eq_trans    (feq (vcons x) e)\n                                            (eq_ind_dep (i+0)\n                                                (fun (z : nat) (d : (i+0) = z) =>\n                                                    (x::(vcast (r ++ []) d)) = (vcast (x::(r ++ [])) (feq S d)))\n                                                eq_refl i (Zria i))).\n        Definition Nriap2       : forall {A : Type} {n : nat} (v : Vect A (n+0)), ((vcast v (Zria n)) ++ []) = v\n            :=  fun A : Type =>\n                nat_ind (fun n : nat => forall v : Vect A (n+0), ((vcast v (Zria n)) ++ []) = v)\n                        (fun v : Vect A 0 => eq_ind [] (fun u : Vect A 0 => (u ++ []) = u) eq_refl v (Vect_form v))\n                        (fun (j : nat) (f : forall r : Vect A (j+0), ((vcast r (Zria j)) ++ []) = r) (v : Vect A (S (j+0))) =>\n                            eq_trans    (feq (flip append []) (vcstnrw v (Zria j)))\n                                        (eq_trans (feq (vcons (head v)) (f (tail v))) (Vect_form v))).\n\n        Definition tkdr_app_inv : forall {A : Type} (m : nat) {n : nat} (v : Vect A (m+n)), v = ((take m v) ++ (drop m v))\n            :=  fun (A : Type) (m n : nat) =>\n                nat_ind (fun i : nat => forall v : Vect A (i+n), v = ((take i v) ++ (drop i v)))\n                        (@eq_refl (Vect A n))\n                        (fun (i : nat) (f : forall r : Vect A (i+n), r = ((take i r) ++ (drop i r))) (v : Vect A (S (i+n))) =>\n                            eq_trans' (Vect_form v) (feq (vcons (head v)) (f (tail v)))) m.\n\n        (* take/drop of a vector (l++r) is equal to l/r, respectively *)\n        Definition tkdr_app_inv2a : forall {A : Type} (m : nat) {n : nat} (u : Vect A m) (v : Vect A n), u = (take m (u ++ v))\n            :=  fun (A : Type) (m n : nat) (u : Vect A m) (v : Vect A n) =>\n                Vect_ind A  (fun (i : nat) (l : Vect A i) => l = (take i (l ++ v))) eq_refl\n                            (fun (i : nat) (x : A) (l : Vect A i) => feq (vcons x)) m u.\n        Definition tkdr_app_inv2b : forall {A : Type} (m : nat) {n : nat} (u : Vect A m) (v : Vect A n), v = (drop m (u ++ v))\n            :=  fun (A : Type) (m n : nat) (u : Vect A m) (v : Vect A n) =>\n                Vect_ind A  (fun (i : nat) (l : Vect A i) => v = (drop i (l ++ v))) eq_refl\n                            (fun (i : nat) (_ : A) (l : Vect A i) => id) m u.\n\n        (* functional versions! *)\n        Definition tkdr_app_inv3a : forall {A : Type} {n m : nat} (v : Vect A m),\n            (fun u : Vect A n => take m (v ++ u)) = (fun _ : Vect A n => v)\n            :=  fun (A : Type) (n : nat) =>\n                Vect_ind A  (fun (m : nat) (v : Vect A m) => (fun u : Vect A n => take m (v ++ u)) = (fun _ : Vect A n => v))\n                            eq_refl (fun (i : nat) (x : A) (l : Vect A i) => feq (comp (vcons x))).\n        Definition tkdr_app_inv3b : forall {A : Type} {n m : nat} (v : Vect A m), (fun u : Vect A n => drop m (v ++ u)) = id\n            :=  fun (A : Type) (n : nat) =>\n                Vect_ind A  (fun (m : nat) (v : Vect A m) => (fun u : Vect A n => drop m (v ++ u)) = id)\n                            eq_refl (fun (i : nat) (x : A) (l : Vect A i) => id).\n\n        Definition vapp0        : forall {A : Type} {m : nat} (v : Vect A (m+0)), ((take m v) ++ []) = v\n            :=  fun A : Type =>\n                nat_ind (fun m : nat => forall v : Vect A (m+0), ((take m v) ++ []) = v) Vect_form\n                        (fun (i : nat) (f : forall r : Vect A (i+0), ((take i r) ++ []) = r) (v : Vect A (S (i+0))) =>\n                            eq_trans (feq (vcons (head v)) (f (tail v))) (Vect_form v)).\n\n        Definition vcsttke      : forall {A : Type} {m n : nat} (v : Vect A (m+n)) {k : nat} (d : m = k),\n            (vcast (take m v) d) = (take k (vcast v (feq (flip plus n) d)))\n            :=  fun (A : Type) (m n : nat) (v : Vect A (m+n)) =>\n                eq_ind_dep  m (fun (k : nat) (d : m = k) => (vcast (take m v) d) = (take k (vcast v (feq (flip plus n) d))))\n                            eq_refl.\n\n    (* Max Proofs *)\n        Definition Zrix     : forall m : nat, (max m 0) = m\n            := fun m : nat => match m as i return ((max i 0) = i) with 0 => eq_refl | S i => eq_refl end.\n        Definition max_plus : forall m n : nat, (max m (m+n)) = (m+n)\n            := fun m n : nat => nat_ind (fun i : nat => (max i (i+n)) = (i+n)) eq_refl (fun i : nat => feq S) m.\n        Definition max_idem : forall m : nat, (max m m) = m\n            := nat_ind (fun m : nat => (max m m) = m) eq_refl (fun i : nat => feq S).\n        Definition max_assoc: forall m n p : nat, (max (max m n) p) = (max m (max n p))\n            :=  nat_ind (fun m : nat => forall n p : nat, (max (max m n) p) = (max m (max n p)))\n                        (fun n p : nat => eq_refl)\n                        (fun (i : nat) (f : forall j k : nat, (max (max i j) k) = (max i (max j k))) (n p : nat) =>\n                            match n as j,p as k return ((max (max (S i) j) k) = (max (S i) (max j k)))\n                            with S j,S k => feq S (f j k) | _,_ => eq_refl end).\n        Definition max_comm : forall m n : nat, (max m n) = (max n m)\n            :=  nat_ind (fun m : nat => forall n : nat, (max m n) = (max n m)) (fun n : nat => eq_sym (Zrix n))\n                        (fun (i : nat) (f : forall j : nat, (max i j) = (max j i)) (n : nat) =>\n                            match n as j return ((max (S i) j) = (max j (S i))) with 0 => eq_refl | S j => feq S (f j) end).\n\n        Fixpoint max_dist (m n k : nat) {struct k} : (max (max m k) (max n k)) = (max (max m n) k)\n            :=  match m as x,n as y,k as z return ((max (max x z) (max y z)) = (max (max x y) z)) with\n                    | 0,0,0         => eq_refl\n                    | 0,0,S z       => feq S (max_dist 0 0 z)\n                    | 0,S y,0       => eq_refl\n                    | 0,S y,S z     => feq S (max_dist 0 y z)\n                    | S x,0,0       => eq_refl\n                    | S x,0,S z     => feq S (eq_trans (max_dist x 0 z) (feq (flip max z) (Zrix x)))\n                    | S x,S y,0     => eq_refl\n                    | S x,S y,S z   => feq S (max_dist x y z)\n                end.\n        Definition max_plus_2 : forall m n : nat, (S (m+n)) = (max m (S (m+n)))\n            := fun m n : nat => nat_ind (fun i : nat => (S (i+n)) = (max i (S (i+n)))) eq_refl (fun i : nat => feq S) m.\n\n        Definition max_add      : forall m n k : nat, (max (k+m) (k+n)) = (k+(max m n))\n            := fun m n : nat => nat_ind (fun k : nat => (max (k+m) (k+n)) = (k+(max m n))) eq_refl (fun k : nat => feq S).\n        Definition max_k_plus   : forall m n k : nat, (max (m+k) (n+k)) = ((max m n)+k)\n            :=  fun m n k : nat =>\n                eq_trans (feq2 max (add_comm m k) (add_comm n k)) (eq_trans (max_add m n k) (add_comm k (max m n))).\n\n        Definition max_succ     : forall m : nat, (max m (S m)) = (S m)\n            := nat_ind (fun m : nat => (max m (S m)) = (S m)) eq_refl (fun i : nat => feq S).\n\n    (* Other *)\n        Definition andb_assoc : forall b c d : bool, (b && (c && d)) = ((b && c) && d)\n            := fun b c d : bool => if b as s return ((s && (c && d)) = ((s && c) && d)) then eq_refl else eq_refl.\n        Definition feqSZria     : forall (m n : nat) (p : m = n), (feq (flip plus 0) (feq S p)) = (feq S (feq (flip plus 0) p))\n            := fun (m n : nat) (p : m = n) => eq_trans (feq_comp (flip plus 0) S p) (eq_sym (feq_comp S (flip plus 0) p)).\n        Definition dist0isidem  : forall m : nat, (max_dist 0 0 m) = (max_idem m)\n            := nat_ind (fun m : nat => (max_dist 0 0 m) = (max_idem m)) eq_refl (fun i : nat => feq (feq S)).\n        Definition Zrvsadas00   : forall m : nat, (Zria (m+0)) = (eq_sym (add_assoc m 0 0))\n            := nat_ind  (fun m : nat => (Zria (m+0)) = (eq_sym (add_assoc m 0 0))) eq_refl\n                        (fun (i : nat) (d : (Zria (i+0)) = (eq_sym (add_assoc i 0 0))) =>\n                            eq_trans (feq (feq S) d) (feqoversym S (add_assoc i 0 0))).\n\n(* h_frnt/k_frnt *)\n    Fixpoint h_frnt (m n : nat)   {struct m} : {x : nat | (max m n) = (m+x)}\n        :=  match m as i,n as j return {x : nat | (max i j) = (i+x)} with\n                | 0,j       =>  exist (eq j) j eq_refl\n                | i,0       =>  exist (fun x : nat => (max i 0) = (i+x)) 0 (eq_trans (Zrix i) (eq_sym (Zria i)))\n                | S i,S j   =>  let (x,p) := (h_frnt i j) in (exist (fun y : nat => (S (max i j)) = (S (i+y))) x (feq S p))\n            end.\n    Fixpoint k_frnt (m n : nat)   {struct m} : {y : nat | (max m n) = (n+y)}\n        :=  match m as i,n as j return {y : nat | (max i j) = (j+y)} with\n                | 0,j       =>  exist (fun y : nat => j = (j+y)) 0 (eq_sym (Zria j))\n                | i,0       =>  exist (eq (max i 0)) (max i 0) eq_refl\n                | S i,S j   =>  let (y,q) := (k_frnt i j) in (exist (fun x : nat => (S (max i j)) = (S (j+x))) y (feq S q))\n            end.\n\n    (* relevant proofs- uniqueness of results, coincidence of results when applied to same argument twice *)\n        Definition h_frnt_unique    : forall m n k : nat, (max m n) = (m+k) -> k = (proj1_sig (h_frnt m n))\n            :=  nat_ind (fun m : nat => forall n k : nat, (max m n) = (m+k) -> k = (proj1_sig (h_frnt m n)))\n                        (eq_sym (A:=nat))\n                        (fun (i : nat) (IHi : forall j k : nat, (max i j) = (i+k) -> k = (proj1_sig (h_frnt i j))) (n k : nat) =>\n                         match n as j return ((max (S i) j) = (S (i+k)) -> k = (proj1_sig (h_frnt (S i) j))) with\n                            | 0     =>  fun e : (S i) = (S (i+k)) =>\n                                        (match i as x\n                                         return (((max x 0) = (x+k) -> k = (proj1_sig (h_frnt x 0))) -> x = (x+k) -> k = 0)\n                                         with 0 => id | S x => id end) (IHi 0 k) (feq pred e)\n                            | S j   =>  fun e : (S (max i j)) = (S (i+k)) =>\n                                        eq_trans    (IHi j k (feq pred e))\n                                                    (let (x,_) as s\n                                                     return ((proj1_sig s)\n                                                                = (proj1_sig (let (x,p) := s in\n                                                                                exist   (fun y : nat => (S (max i j)) = (S (i+y)))\n                                                                                        x (feq S p))))\n                                                        := (h_frnt i j) in eq_refl)\n                         end).\n        Definition k_frnt_unique    : forall m n k : nat, (max m n) = (n+k) -> k = (proj1_sig (k_frnt m n))\n            :=  nat_ind (fun m : nat => forall n k : nat, (max m n) = (n+k) -> k = (proj1_sig (k_frnt m n)))\n                        (nat_ind    (fun n : nat => forall k : nat, n = (n+k) -> k = 0) (eq_sym (x:=0))\n                                    (fun (j : nat) (f : forall k : nat, j = (j+k) -> k = 0) (k : nat) (e : (S j) = (S (j+k))) =>\n                                     f k (feq pred e)))\n                        (fun (i : nat) (f : forall j k : nat, (max i j) = (j+k) -> k = (proj1_sig (k_frnt i j))) (n k : nat) =>\n                         match n as j return ((max (S i) j) = (j+k) -> k = (proj1_sig (k_frnt (S i) j))) with\n                            | 0     =>  @eq_sym nat (S i) k\n                            | S j   =>  fun e : (S (max i j)) = (S (j+k)) =>\n                                        eq_trans    (f j k (feq pred e))\n                                                    (let (x,_) as s\n                                                     return ((proj1_sig s)\n                                                                = (proj1_sig (let (y,q) := s in\n                                                                                exist   (fun x : nat => (S (max i j)) = (S (j+x)))\n                                                                                        y (feq S q))))\n                                                        := (k_frnt i j) in eq_refl)\n                         end).\n        Definition frnts_idem       : forall m : nat, (h_frnt m m) = (k_frnt m m)\n            :=  nat_ind (fun m : nat => (h_frnt m m) = (k_frnt m m)) eq_refl\n                        (fun i : nat =>\n                         feq (fun s : {x : nat | (max i i) = (i+x)} =>\n                              let (x,p) := s in exist (fun y : nat => (S (max i i)) = (S (i+y))) x (feq S p))).\n\n(* DyCG.v- types *)\n    (* remember: new type names (gotta make changes)\n        kon will now be called xon\n        update will now be called kon *)\n\n    Notation \"'e^' n\" := (Vect e n) (at level 0) : vect_scope.\n    Definition con : nat -> Set := fun n : nat => e^n -> prop.\n    (* kon will now be defined less generally- no quantification over \"other\" DR's; gonna outsource that generalization to kext *)\n    Definition kon : nat -> nat -> Set := fun m i : nat => con m -> con (m+i).\n    (* mostly for reasons of comparing with the older setups, I'm gonna ressurect the type of \"updates\" for the old kon *)\n    Definition update : nat -> nat -> Set := fun m i : nat => forall n : nat, kon (m+n) i.\n\n    Fixpoint p_i (n : nat) {struct n} : Set := match n with 0 => prop | S i => e -> p_i i end.\n\n    Definition udy' : (nat -> nat) -> nat -> nat -> Set\n        := fun (f : nat -> nat) (n i : nat) => forall u : Vect nat n, kon (f (vmax u)) i.\n    Definition udy  : nat -> nat -> nat -> Set := udy'∘max.\n\n    Fixpoint dy' (f : nat -> nat) (n i : nat) {struct n} : Set\n        :=  match n with\n                | 0     => kon (f 0) i\n                | S j   => forall m : nat, dy' (f∘(max (S m))) j i\n            end.\n    Definition dy : nat -> nat -> nat -> Set := dy'∘max.\n\n(* DyCG.v- basics *)\n    (*  casts are basically just eq_rec with equated nat's implicit- see comments below each for converting them\n        into versions where the arguments are the ones that get casted *)\n    Definition ccast : forall {m : nat}, con m -> forall {n : nat}, m = n -> con n\n        := fun m : nat => eq_rec m con.\n        (* := fun (m : nat) (c : con m) (n : nat) (d : m = n) (v : e^n) => c (vcast v (eq_sym d)). *)\n    Definition kcast : forall {m i : nat}, kon m i -> forall {n : nat}, m = n -> kon n i\n        := fun m i : nat => eq_rec m (flip kon i).\n        (* :=  fun (m i : nat) (k : kon m i) (n : nat) (d : m = n) (c : con n) (v : e^(n+i)) =>\n            k (ccast c (eq_sym d)) (vcast v (eq_sym (feq (flip plus i) d))). *)\n\n    (* cext,kext *)\n    (* context extension- defined to add arbitrary # of DR's, but the c⁺ notation will still be for +1 *)\n    Definition cext : forall i : nat, update 0 i := fun (i n : nat) (c : con n) (v : e^(n+i)) => c (take n v).\n    Notation \"c ⁺\" := (cext 1 _ c) (at level 0) : dyn_scope.\n    Open Scope dyn_scope.\n    Definition kext : forall {m i : nat}, kon m i -> update m i\n        :=  fun (m i : nat) (k : kon m i) (n : nat) (c : con (m+n)) (v : e^((m+n)+i)) =>\n            (* v ≈ ((l ++ u) ++ r) *)\n            let l := (take m (take (m+n) v)) in\n            let u := (drop m (take (m+n) v)) in\n            let r := (drop (m+n) v) in\n            k (fun t : e^m => c (t ++ u)) (l ++ r).\n        (* definition is such that the context sees the n \"extra\" DR's, but k itself never interacts with them directly *)\n        (* this may lead to weirdness in the indexing of DR's, but then again so has everything else so far *)\n\n    Definition dy1ext'  : forall (f : nat -> nat) (n i : nat), dy' f 1 i -> dy' ((max n)∘f) 1 i\n        :=  fun (f : nat -> nat) (n i : nat) (D : dy' f 1 i) (m : nat) =>\n            let (y,q) := (k_frnt n (f (S m))) in kcast (kext (D m) y) (eq_sym q).\n\n    Definition dy1ext   : forall {m i : nat}, dy m 1 i -> forall n : nat, dy (max m n) 1 i\n        :=  fun (m i : nat) (D : dy m 1 i) (n j : nat) =>\n            let (y,q) := (k_frnt n (max m (S j))) in\n            kcast (kext (D j) y) (eq_trans' q (eq_trans' (max_assoc n m (S j)) (feq (flip max (S j)) (max_comm n m)))).\n\n    (* Definition d1ext: forall {m i : nat}, dy m 1 i -> forall n : nat, dy (m+n) 1 i. *)\n    (* shouldn't I be able to do this with a variant of dy1ext since (max m (m+n)) = (m+n)? *)\n\n    Fixpoint vexists {n : nat} : con n -> prop\n        :=  match n as k return (con k -> prop) with\n                | 0     =>  fun c : con 0 => c []\n                | S i   =>  fun c : con (S i) => pex (fun x : e => vexists (fun v : e^i => c (x::v)))\n            end.\n\n    Definition cc : forall {m i : nat}, kon m i -> kon m i\n        := fun (m i : nat) (k : kon m i) (c : con m) (v : e^(m+i)) => (c (take m v)) and (k c v).\n\n    (* order or kext-ing and recasting kon's doesn't change anything *)\n    Definition kextkcast    : forall {m n i : nat} (k : kon m i) {j : nat} (d : m = j) (c : con (j+n)) (v : e^((j+n)+i)),\n        (kcast (kext k n) (feq (flip plus n) d) c v) = (kext (kcast k d) n c v)\n        :=  fun (m n i : nat) (k : kon m i) =>\n            eq_ind_dep m\n                (fun (j : nat) (d : m = j) => forall (c : con (j+n)) (v : e^((j+n)+i)),\n                    (kcast (kext k n) (feq (flip plus n) d) c v) = (kext (kcast k d) n c v))\n                (fun (c : con (m+n)) (v : e^((m+n)+i)) => eq_refl).\n    (* don't actually need to quantify over contexts and DR vectors! *)\n    Definition kextkcastfun : forall {m n i : nat} (k : kon m i) {j : nat} (d : m = j),\n        (kcast (kext k n) (feq (flip plus n) d)) = (kext (kcast k d) n)\n        :=  fun (m n i : nat) (k : kon m i) =>\n            eq_ind_dep m (fun (j : nat) (d : m = j) => (kcast (kext k n) (feq (flip plus n) d)) = (kext (kcast k d) n)) eq_refl.\n    (* can avoid quantifying over k as well! *)\n    Definition kextkcastfun2 : forall {m n i j : nat} (d : m = j),\n        (fun k : kon m i => kcast (kext k n) (feq (flip plus n) d)) = (fun k : kon m i => kext (kcast k d) n)\n        :=  fun m n i : nat =>\n            eq_ind_dep m\n                (fun (j : nat) (d : m = j) =>\n                    (fun k : kon m i => kcast (kext k n) (feq (flip plus n) d)) = (fun k : kon m i => kext (kcast k d) n))\n                eq_refl.\n    (* can even avoid quantifying over i and n! *)\n    Definition kextkcastfun3 : forall {m j : nat} (d : m = j),\n        (fun (i : nat) (k : kon m i) (n : nat) => kcast (kext k n) (feq (flip plus n) d))\n            = (fun (i : nat) (k : kon m i) => kext (kcast k d))\n        :=  fun m : nat =>\n            eq_ind_dep m\n                (fun (j : nat) (d : m = j) =>\n                    (fun (i : nat) (k : kon m i) (n : nat) => kcast (kext k n) (feq (flip plus n) d))\n                    = (fun (i : nat) (k : kon m i) => kext (kcast k d)))\n                eq_refl.\n\n    (* order of performing cc/kext on a content doesn't change anything *)\n    Definition kextcc : forall {m n i:nat}(k:kon m i)(c:con (m+n))(v:e^((m+n)+i)), (cc (kext k n) c v) = (kext (cc k) n c v)\n        :=  fun (m n i : nat) (k : kon m i) (c : con (m+n)) (v : e^((m+n)+i)) =>\n            let l := (take (m+n) v) in\n            let r := (drop (m+n) v) in\n            feq (fun u : e^(m+n) => (c u) and (k (fun t : e^m => c (t ++ (drop m l))) ((take m l) ++ r)))\n                (eq_trans (tkdr_app_inv m l) (feq (fun u : e^m => u ++ (drop m l)) (tkdr_app_inv2a m (take m l) r))).\n    (* maybe do a similar proof for kext vs AND,etc? *)\n\n(* DyCG.v- \"propositional\" level *)\n    Definition NOT : forall {m i : nat}, kon m i -> kon m 0\n        :=  fun (m i : nat) (k : kon m i) (c : con m) (v : e^(m+0)) =>\n            not (vexists (fun u : e^i => k c ((take m v) ++ u))).\n\n    Definition dynNOT : forall {m i : nat} (k : kon m i) (c : con m) (v : e^m),\n        (NOT (NOT k) c (v ++ [])) ≡ (vexists (fun u : e^i => k c (v ++ u)))\n        :=  fun (m i : nat) (k : kon m i) (c : con m) (v : e^m) =>\n            let C := (fun l : e^m => vexists (fun u : e^i => k c (l ++ u))) in\n            let V := (fun (n : nat) (l : e^n) => take n ((take n (l ++ [])) ++ [])) in\n            int_eq  (NOT (NOT k) c (v ++ [])) (C v)\n                    (fun w : world =>\n                         eq_trans   (p_not_ax (not (C (V m v))) w)\n                        (eq_trans   (f_equal negb (p_not_ax (C (V m v)) w))\n                        (eq_trans   (if ((C (V m v))@w) as b return (-~(-~b) = b) then eq_refl else eq_refl)\n                                    (f_equal    (fun l : e^m => (C l)@w)\n                                                (Vect_ind e (fun (n : nat) (l : e^n) => (V n l) = l) eq_refl\n                                                            (fun (j : nat) (x : e) (l : e^j) => feq (vcons x)) m v))))).\n\n    Definition kextNOT : forall {m n i:nat}(k:kon m i)(c:con (m+n))(v:e^(m+n)),(NOT(kext k n)c(v++[]))=(kext(NOT k)n c(v++[]))\n        :=  fun (m n i : nat) (k : kon m i) (c : con (m+n)) (v : e^(m+n)) =>\n            feq3    (fun (f : e^i -> e^(m+n)) (g : e^i -> e^m) (h : e^i -> e^i) =>\n                        not (vexists (fun u : e^i => k (fun t : e^m => c (t ++ (drop m (f u)))) ((g u) ++ (h u)))))\n                    (tkdr_app_inv3a (take (m+n) (v ++ [])))\n                    (eq_trans   (feq    (comp (take m)) (tkdr_app_inv3a (take (m+n) (v ++ []))))\n                                (feq    (fun (l : e^m) (_ : e^i) => l)\n                                        (tkdr_app_inv2a m (take m (take (m+n) (v ++ []))) (drop (m+n) (v ++ [])))))\n                    (tkdr_app_inv3b (take (m+n) (v ++ []))).\n\n    Definition d_AND : forall {m i j : nat}, kon m i -> kon (m+i) j -> kon m (i+j)\n        :=  fun (m i j : nat) (h : kon m i) (k : kon (m+i) j) (c : con m) (v : e^(m+(i+j))) =>\n            let u := (vcast v (add_assoc m i j)) in (h c (take (m+i) u)) and (k (cc h c) u).\n    Infix \"AND\" := d_AND (at level 20) : dyn_scope.\n\n    (* 15 lines!!!! *)\n    Definition dynAND : forall (m i j : nat) (h : kon m i) (k : kon (m+i) j) (c : con m) (v : e^(m+(i+j))),\n        (cc (h AND k) c v) ≡ (cc k (cc h c) (vcast v (add_assoc m i j)))\n        :=  fun (m i j : nat) (h : kon m i) (k : kon (m+i) j) (c : con m) (v : e^(m+(i+j))) =>\n            let u := (vcast v (add_assoc m i j)) in\n            let P := (c (take m v)) in\n            let Q := (h c (take (m+i) u)) in\n            let R := (k (cc h c) u) in\n            let T := (c (take m (take (m+i) u))) in\n            int_eq  (cc (h AND k) c v) (cc k (cc h c) u)\n                    (fun w : world =>\n                         eq_trans   (p_and_ax P ((h AND k) c v) w)\n                        (eq_trans   (feq (andb (P@w)) (p_and_ax Q R w))\n                        (eq_trans   (andb_assoc (P@w) (Q@w) (R@w))\n                        (eq_trans   (feq (fun l : e^m => ((c l)@w && Q@w) && R@w) (take_assoc m i j v))\n                        (eq_sym     (eq_trans (p_and_ax (T and Q) R w) (feq (flip andb (R@w)) (p_and_ax T Q w)))))))).\n\n    Definition d_OR : forall {m i j : nat}, kon m i -> kon m j -> kon m 0\n        := fun (m i j : nat) (h : kon m i) (k : kon m j) => NOT ((NOT h) AND (NOT (kext k 0))).\n    Infix \"OR\" := d_OR (at level 0) : dyn_scope.\n\n    Definition d_IMPLIES : forall {m i j : nat}, kon m i -> kon (m+i) j -> kon m 0\n        := fun (m i j : nat) (h : kon m i) (k : kon (m+i) j) => (NOT h) OR (h AND k).\n    Infix \"IMPLIES\" := d_IMPLIES (at level 20) : dyn_scope.\n\n(* DyCG.v- predicate level *)\n    (* the use of kext in here is…interesting, to say the least. Wonder what it'll mean for the indices later? *)\n    Fixpoint udyn (m : nat) {struct m} : p_i m -> udy 0 m 0\n        :=  match m as k return (p_i k -> udy 0 k 0) with\n                | 0     =>  fun (p : prop) (_ : Vect nat 0) (_ : con 0) (_ : e^0) => p\n                | S i   =>  fun (P : e -> p_i i) (u : Vect nat (S i)) (c : con (vmax u)) (v : e^((vmax u)+0)) =>\n                            let (x,p) := (h_frnt (S (head u)) (vmax (tail u))) in\n                            let (y,q) := (k_frnt (S (head u)) (vmax (tail u))) in\n                            kext    (udyn i (P (nth (head u) (vcast v (eq_trans (Zria (vmax u)) p)))) (tail u))\n                                    y (ccast c q) (vcast v (feq (flip plus 0) q))\n            end.\n\n    Fixpoint udytody (f : nat -> nat) (n i : nat) {struct n} : udy' f n i -> dy' f n i\n      :=    match n as j return (udy' f j i -> dy' f j i) with\n                | 0     =>  fun g : Vect nat 0 -> kon (f 0) i => g []\n                | S j   =>  fun (g : forall u : Vect nat (S j), kon (f (vmax u)) i) (m : nat) =>\n                            udytody (f∘(max (S m))) j i (fun r : Vect nat j => g (m::r))\n            end.\n\n    Definition dyn  : forall n : nat, p_i n -> dy  0 n 0 := fun (n : nat) (P : p_i n) => udytody id n 0 (udyn n P).\n\n    (* New! 11/18/2018: converting back from dy' to udy', plus proof that they form an iso (up to functional extensionality of index arg's) *)\n    Fixpoint dytoudy (f : nat -> nat) (k i : nat) {struct k} : dy' f k i -> udy' f k i\n        :=  match k as n return (dy' f n i -> udy' f n i) with\n                | 0     =>  fun (h : dy' f    0  i) (_ : Vect nat    0 ) => h\n                | S j   =>  fun (D : dy' f (S j) i) (u : Vect nat (S j)) =>\n                            eq_rec ((head u)::(tail u)) (fun v : Vect nat (S j) => xon (f (vmax v)) i) (dytoudy (f∘(max (S (head u)))) j i (D (head u)) (tail u)) u (Vect_form u)\n            end.\n\n    Definition udu_inv : forall (i k : nat) (u : Vect nat k) (f : nat -> nat) (D : udy' f k i), (dytoudy f k i (udytody f k i D) u) = (D u)\n        :=  fun i : nat =>\n            Vect_ind nat    (fun (k : nat) (u : Vect nat k) => forall (f : nat -> nat) (D : udy' f k i), (dytoudy f k i (udytody f k i D) u) = (D u))\n                            (fun (f : nat -> nat) (D : udy' f 0 i) => eq_refl)\n                            (fun (k n : nat) (r : Vect nat k) (g : forall (h : nat -> nat) (E : udy' f k i), (dytoudy h k i (udytody h k i E) r) = (E r))\n                                 (f : nat -> nat) (D : udy' f (S k) i) => g (f∘(max (S n))) (fun t : Vect nat k => D (n::t))).\n\n    Definition dud_type : forall (i k : nat) (f : nat -> nat), dy' f k i -> Prop\n        :=  fun i : nat => nat_rect (fun k : nat => forall f : nat -> nat, dy' f k i -> Prop)\n                                    (fun (f : nat -> nat) (h : xon (f 0) i) => (udytody f 0 i (dytoudy f 0 i h)) = h)\n                                    (fun (k : nat) (P : forall g : nat -> nat, dy' g k i -> Prop) (f : nat -> nat) (D : dy' f (S k) i) => forall n : nat, P (f∘(max (S n))) (D n)).\n\n    Definition dud_inv : forall (i k : nat) (f : nat -> nat) (D : dy' f k i), dud_type i k f D\n        :=  fun i : nat =>\n            nat_ind (fun k : nat => forall (f : nat -> nat) (D : dy' f k i), dud_type i k f D)\n                    (fun (f : nat -> nat) (D : xon (f 0) i) => eq_refl)\n                    (fun (k : nat) (h : forall (g : nat -> nat) (E : dy' g k i), dud_type i k g E) (f : nat -> nat) (D : dy' f (S k) i) (n : nat) => h (f∘(max (S n))) (D n)).\n\n\n(* Dynamic Quantifiers *)\n    Definition EXISTS : forall {m i : nat}, dy m 1 i -> kon m (S i)\n        :=  fun (m i : nat) (D : dy m 1 i) (c : con m) (v : e^(m+(S i))) =>\n            kcast (D m) (eq_trans (feq (max m) (add_comm 1 m)) (max_plus m 1)) c⁺ (vcast v (add_assoc m 1 i)).\n    Definition FORALL : forall {m i : nat}, dy m 1 i -> kon m 0\n        := fun (m i : nat) (D : dy m 1 i) => NOT (EXISTS (fun j : nat => NOT (D j))).\n\n    (* type-correct version of THAT which feeds D and E different indices *)\n    Definition bad_THAT : forall {m i j : nat}, dy m 1 i -> dy (m+i) 1 j -> dy m 1 (i+j)\n        :=  fun (m i j : nat) (D : dy m 1 i) (E : dy (m+i) 1 j) (n : nat) =>\n            (D n) AND (kcast (E (n+i)) (max_k_plus m (S n) i)).\n    Infix \"bTHAT\" := bad_THAT (at level 20) : dyn_scope.\n\n    Definition badSOME  : forall {m i j : nat}, dy m 1 i -> dy (m+i) 1 j -> kon m (S (i+j))\n        := fun (m i j : nat) (D : dy m 1 i) (E : dy (m+i) 1 j) => EXISTS (D bTHAT E).\n\n    Definition badEVERY : forall {m i j : nat}, dy m 1 i -> dy (m+i) 1 j -> kon m 0\n        :=  fun (m i j : nat) (D : dy m 1 i) (E : dy (m+i) 1 j) =>\n            FORALL (fun n : nat => (D n) IMPLIES (kcast (E (n+i)) (max_k_plus m (S n) i))).\n\n    Definition IT       : forall (n : nat) {m i : nat}, dy m 1 i -> kon (max m (S n)) i\n        := fun (n m i : nat) (D : dy m 1 i) => D n.\n\n(* attempt at \"working\" version of SOME *)\n    (* Definition SOME'    : forall {m i j : nat}, dy m 1 i -> dy (m+i) 1 j -> kon m (S (i+j))\n        :=  fun (m i j : nat) (D : dy m 1 i) (E : dy (m+i) 1 j) (c : con m) (v : e^(m+(S (i+j)))) =>\n            (kcast (D m) (eq_trans (max_succ m) (add_comm 1 m)))\n            AND\n            (kcast (kext (E m) (if i then 0 else 1)) (kindaspecprf m i))\n            c⁺ (vcast v (add_assoc m 1 (i+j))). *)\n\n    (* Definition pred : nat -> nat := fun m : nat => match m with 0 => 0 | S i => i end.\n    Definition fooproofthingy : forall m i : nat, (max (m+i) (S m)) = (S (m+(pred i)))\n        :=  fun m i : nat =>\n            (fix nxt (x : nat) {struct x} : (max (x+i) (S x)) = (S (x+(pred i))) :=\n             match x as y return ((max (y+i) (S y)) = (S (y+(pred i)))) with\n                | 0     =>  max_comm i 1\n                | S y   =>  feq S (nxt y)\n             end) m.\n\n    Definition kindaspecprf : forall m i : nat, ((max (m+i) (S m))+(if i then 0 else 1)) = ((m+1)+i)\n        :=  fun m i : nat =>\n            eq_trans    (feq (flip plus (if i then 0 else 1)) (eq_trans (feq (max (m+i)) (add_comm 1 m)) (max_add i 1 m)))\n                        (eq_trans'  (add_assoc m (max i 1) (if i then 0 else 1))\n                                    (eq_trans   (feq (plus m)\n                                                    (match i as x\n                                                     return (((max x 1)+(if x then 0 else 1)) = (S x)) with\n                                                        | 0     => eq_refl\n                                                        | S x   => feq S (eq_trans  (add_comm (max x 0) 1)\n                                                                                    (feq S (Zrix x)))\n                                                     end))\n                                                (add_assoc m 1 i))). *)\n\n(* Static term assumptions *)\n    Axioms farmer donkey bray : e -> prop.\n    Axioms own beat : e -> e -> prop.\n    Axioms john bill chiquita : e.\n\n(* Dynamic lexical item definitions *)\n    Definition BRAY     : dy 0 1 0 := dyn 1 bray.\n    Definition FARMER   : dy 0 1 0 := dyn 1 farmer.\n    Definition DONKEY   : dy 0 1 0 := dyn 1 donkey.\n    Definition OWN      : dy 0 2 0 := dyn 2 own.\n    Definition BEAT     : dy 0 2 0 := dyn 2 beat.\n    Definition OutBlue  : forall {n : nat}, con n := fun (n : nat) (_ : e^n) => truth.\n\n(* old Back to testing sentences *)\n    (* The second form of a donkey sentence- \"if a farmer owns a donkey, he beats it\" *)\n        (* Definition IAFOADHBI : kon 0 0 := d_IMPLIES (n:=0) AFOAD (BEAT 0 1). *)\n            (*  (IT 0 (fun m : nat => eq_rec (max m 1) ((flip kon 0)∘S) (IT 1 (BEAT m)) (max 1 m) (max_comm m 1))) : kon 2 0\n                (IT 1 (fun n : nat =>\n                            eq_rec  (max n 0) ((flip kon 0)∘S)\n                                    (IT 0 (fun m : nat => eq_rec (max m n) ((flip kon 0)∘S) (BEAT m n) (max n m) (max_comm m n)))\n                                    n (Zrix n))) : kon 2 0\n                Both reduce to (BEAT 0 1) *)\n            (* ≡ (fun (_ : con 0) (_ : e^0) =>\n                    (some farmer (fun x : e => some donkey (own x)))\n                        implies (some farmer (fun x : e => some (donkey that (own x)) (beat x)))) *)\n\n\n(* newer testings- looking good so far, believe it or not! *)\n    (* \"Some donkey brayed\" vs \"There exists a donkey₀ and it₀ brayed\" *)\n        Definition exdonkandbr  : kon 0 1   := (EXISTS DONKEY) AND (IT 0 BRAY).\n            (* :=: (fun (_ : con 0) (v : e^1) => let x := (nth 0 v) in (donkey x) and (bray x)) *)\n            (* \"There is a donkey₀ and it₀ brayed\" *)\n        Definition smdonkbr     : kon 0 1   := (badSOME DONKEY BRAY).\n            (* :=: (fun (_ : con 0) (v : e^1) => let x := (nth 0 v) in (donkey x) and (bray x)) *)\n            (* \"Some donkey brayed\" *)\n    (* \"A farmer owns a donkey\", with both scopings of farmer vs donkey *)\n        Definition AFOAD1       : kon 0 2   := badSOME FARMER (fun m : nat => badSOME (dy1ext DONKEY (S m)) (OWN (m+0))).\n            (* :=: (fun (_ : con 0) (v : e^2) => let (x,y) := (nth 0 v,nth 1 v) in (farmer x) and ((donkey y) and (own x y))) *)\n            (* \"A farmer₀ owns a donkey₁\", farmer>donkey *)\n        Definition AFOAD2       : kon 0 2\n            :=  badSOME DONKEY\n                        (fun n : nat =>\n                         badSOME    (dy1ext FARMER (S n))\n                                    (fun m : nat => kcast (OWN m (n+0)) (max_comm (S m) (S (n+0))))).\n            (* :=: (fun (_ : con 0) (v : e^2) => let (x,y) := (nth 0 v,nth 1 v) in (donkey x) and ((farmer y) and (own y x))) *)\n            (* \"A farmer₁ owns a donkey₀\", donkey>farmer *)\n    (* \"A farmer owns a donkey. It brays\" with both scopings *)\n        Definition FODDBR1      : kon 0 2   := AFOAD1 AND (IT 1 BRAY).\n            (* :=: (fun (_ : con 0) (v : e^2) => let (x,y) := (nth 0 v,nth 1 v) in\n                        ((farmer x) and ((donkey y) and (own x y))) and (bray y)) *)\n            (* \"A farmer₀ owns a donkey₁. It₁ brays.\" *)\n        Definition FODDBR2      : kon 0 2   := AFOAD2 AND (kext (IT 0 BRAY) 1).\n            (* :=: (fun (_ : con 0) (v : e^2) => let (x,y) := (nth 0 v,nth 1 v) in\n                    ((donkey x) and ((farmer y) and (own y x))) and (bray x)) *)\n            (* \"A farmer₁ owns a donkey₀. It₀ brays.\" *)\n    (* \"A farmer owns a donkey. He brays\" with both scopings *)\n        Definition FODFBR1      : kon 0 2   := AFOAD1 AND (kext (IT 0 BRAY) 1).\n            (* :=: (fun (_ : con 0) (v : e^2) => let (x,y) := (nth 0 v,nth 1 v) in\n                    ((farmer x) and ((donkey y) and (own x y))) and (bray x)) *)\n            (* \"A farmer₀ owns a donkey₁. He₀ brays.\" *)\n        Definition FODFBR2      : kon 0 2   := AFOAD2 AND (IT 1 BRAY).\n            (* :=: (fun (_ : con 0) (v : e^2) => let (x,y) := (nth 0 v,nth 1 v) in\n                    ((donkey x) and ((farmer y) and (own y x))) and (bray y)) *)\n            (* \"A farmer₁ owns a donkey₀. He₁ brays.\" *)\n\n    (* \"A farmer owns a donkey that brays\" *)\n    Definition FODB     : kon 0 2\n        := badSOME FARMER (fun m : nat => badSOME ((dy1ext DONKEY (S m)) bTHAT (OWN (m+0))) (dy1ext BRAY (S (m+0)))).\n        (* :=: (fun (_ : con 0) (v : e^2) => let (x,y) := (nth 0 v,nth 1 v) in\n                    (farmer x) and (((donkey y) and (own x y)) and (bray y))) *)\n\n    (* \"A farmer owns a donkey that brays. He brays (too).\" *)\n    Definition FODBFB   : kon 0 2 := FODB AND (kext (IT 0 BRAY) 1).\n        (* :=: (fun (_ : con 0) (v : e^2) => let (x,y) := (nth 0 v,nth 1 v) in\n                    ((farmer x) and (((donkey y) and (own x y)) and (bray y))) and (bray x)) *)\n\n    (* \"A farmer owns a donkey that brays. It also brays.\" *)\n    Definition FODBDB   : kon 0 2 := FODB AND (IT 1 BRAY).\n        (* :=: (fun (_ : con 0) (v : e^2) => let (x,y) := (nth 0 v,nth 1 v) in\n                    ((farmer x) and (((donkey y) and (own x y)) and (bray y))) and (bray y)) *)\n\n\n(*  some simpler problem cases- anaphoric reference outside of the sentence works correctly,\n    but fails within the scope of the quantifier in the sentence itself (almost as if it was being passed a bad argument…\n    (/sarcasm)) *)\n\n    (* \"A farmer who owns a donkey brays\"- predicts that the donkey is the braying one *)\n        Definition AFOADB   : kon 0 2\n            := badSOME (FARMER bTHAT (fun m : nat => badSOME (dy1ext DONKEY (S m)) (OWN (m+0)))) (dy1ext BRAY 1).\n            (* :=: (fun (_ : con 0) (v : e^2) => let (x,y) := (nth 0 v,nth 1 v) in\n                    ((farmer x) and ((donkey y) and (own x y))) and (bray y)) *)\n        (* \"A farmer who owns a donkey brays. It brays (too).\" *)\n        Definition AFOADRDB : kon 0 2 := AFOADB AND (IT 1 BRAY).\n            (* :=: (fun (_ : con 0) (v : e^2) => let (x,y) := (nth 0 v,nth 1 v) in\n                        (((farmer x) and ((donkey y) and (own x y))) and (bray y)) and (bray y)) *)\n        (* \"A farmer who owns a donkey brays. He also brays.\" *)\n        Definition AFOADBFB : kon 0 2 := AFOADB AND (kext (IT 0 BRAY) 1).\n            (* :=: (fun (_ : con 0) (v : e^2) => let (x,y) := (nth 0 v,nth 1 v) in\n                        (((farmer x) and ((donkey y) and (own x y))) and (bray y)) and (bray x)) *)\n    (* \"A donkey that some farmer owns brays\"- predicts the farmer is the braying one *)\n        Definition ADSFOB   : kon 0 2\n            :=  badSOME (DONKEY bTHAT\n                            (fun n : nat =>\n                                badSOME (dy1ext FARMER (S n)) (fun m : nat => kcast (OWN m (n+0)) (feq S (max_comm m (n+0))))))\n                        (dy1ext BRAY 1).\n            (* :=: (fun (_ : con 0) (v : e^2) => let (x,y) := (nth 0 v,nth 1 v) in\n                        ((donkey x) and ((farmer y) and (own y x))) and (bray y)) *)\n        (* \"A donkey that some farmer owns brays. It also brays.\" *)\n        Definition ADSFOBDB   : kon 0 2 := ADSFOB AND (kext (IT 0 BRAY) 1).\n            (* :=: (fun (_ : con 0) (v : e^2) => let (x,y) := (nth 0 v,nth 1 v) in\n                        (((donkey x) and ((farmer y) and (own y x))) and (bray y)) and (bray x)) *)\n        (* \"A donkey that some farmer owns brays. He brays (too).\" *)\n        Definition ADSFOBFB   : kon 0 2 := ADSFOB AND (IT 1 BRAY).\n            (* :=: (fun (_ : con 0) (v : e^2) => let (x,y) := (nth 0 v,nth 1 v) in\n                        (((donkey x) and ((farmer y) and (own y x))) and (bray y)) and (bray y)) *)\n\n\n(* dare I try…the donkey sentence? *)\n(* still failed… *)\nDefinition the_donkey_sentence : kon 0 0\n    :=  badEVERY    (FARMER bTHAT (fun m : nat => badSOME (dy1ext DONKEY (S m)) (OWN (m+0))))\n                    (fun m : nat => kcast (IT 0 (BEAT m)) (feq S (Zrix m))).\n\n    (* :=: (fun (_ : con 0) (_ : e^0) =>\n         not (pex (fun x : e =>\n                    not (not ((not (not (pex (fun y : e => farmer x and ((donkey y) and (own x y))))))\n                                and (not (pex (fun y : e => ((farmer x) and ((donkey y) and (own x y))) and (beat y x)))))))))\n    :≡: (fun (_ : con 0) (_ : e^0) =>\n         every  (fun x : e => (farmer x) and (some donkey (own x)))\n                (fun x : e => (farmer x) and (some (donkey that (own x)) (flip beat x)))) *)\n\n\n(* maybe the issue is the picking of the new DR as the first of the \"new\" DR's? idk *)\n(*  anyway, problem shows up pretty early- especially worrisome to me (other than the THAT situation)\n    is that IT pretty much needs to select the 0th element, yet this points to the wrong DR, right? *)\n(* the_donkey_sentence : kon 0 0\n    :=: (badEVERY   (FARMER THAT (fun m : nat => badSOME (dy1ext DONKEY (S m)) (OWN (m+0))))\n                    (fun m : nat => kcast (IT 0 (BEAT m)) (feq S (Zrix m))))\n    :=: (@badEVERY 0 1 0\n            (@bad_THAT 0 0 1 FARMER (fun m : nat => @badSOME (S m) 0 0 (dy1ext DONKEY (S m)) (OWN (m+0))))\n            (fun m : nat => kcast (IT 0 (BEAT m)) (feq S (Zrix m))))\n    :=: (FORALL (fun m : nat =>\n                    (@bad_THAT 0 0 1 FARMER (fun m : nat => @badSOME (S m) 0 0 (dy1ext DONKEY (S m)) (OWN (m+0))) m)\n                        IMPLIES (kcast (kcast (IT 0 (BEAT (m+1))) (feq S (Zrix (m+1)))) (max_k_plus 0 (S m) 1))))\n    :=: (@FORALL 0 0\n                (fun m : nat =>\n                    (@bad_THAT 0 0 1 FARMER (fun m : nat => @badSOME (S m) 0 0 (dy1ext DONKEY (S m)) (OWN (m+0))) m)\n                        IMPLIES (kcast (kcast (IT 0 (BEAT (m+1))) (feq S (Zrix (m+1)))) (max_k_plus 0 (S m) 1))))\n    :=: (NOT (EXISTS\n                (fun m : nat =>\n                 NOT ((@bad_THAT 0 0 1 FARMER (fun m : nat => @badSOME (S m) 0 0 (dy1ext DONKEY (S m)) (OWN (m+0))) m)\n                        IMPLIES (kcast (kcast (IT 0 (BEAT (m+1))) (feq S (Zrix (m+1)))) (max_k_plus 0 (S m) 1))))))\n    :=: (@NOT 0 1\n            (EXISTS\n                (fun m : nat =>\n                 NOT ((@bad_THAT 0 0 1 FARMER (fun m : nat => @badSOME (S m) 0 0 (dy1ext DONKEY (S m)) (OWN (m+0))) m)\n                        IMPLIES (kcast (kcast (IT 0 (BEAT (m+1))) (feq S (Zrix (m+1)))) (max_k_plus 0 (S m) 1))))))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                 EXISTS\n                    (fun m : nat =>\n                     NOT ((@bad_THAT 0 0 1 FARMER (fun m : nat => @badSOME (S m) 0 0 (dy1ext DONKEY (S m)) (OWN (m+0))) m)\n                            IMPLIES (kcast (kcast (IT 0 (BEAT (m+1))) (feq S (Zrix (m+1)))) (max_k_plus 0 (S m) 1))))\n                    c [x])))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                 @EXISTS 0 0\n                    (fun m : nat =>\n                     NOT ((@bad_THAT 0 0 1 FARMER (fun m : nat => @badSOME (S m) 0 0 (dy1ext DONKEY (S m)) (OWN (m+0))) m)\n                            IMPLIES (kcast (kcast (IT 0 (BEAT (m+1))) (feq S (Zrix (m+1)))) (max_k_plus 0 (S m) 1))))\n                    c [x])))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                     NOT ((@bad_THAT 0 0 1 FARMER (fun m : nat => @badSOME (S m) 0 0 (dy1ext DONKEY (S m)) (OWN (m+0))) 0)\n                            IMPLIES (IT 0 (BEAT 1))) c⁺ [x])))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                     @NOT 1 0\n                        ((@bad_THAT 0 0 1 FARMER (fun m : nat => @badSOME (S m) 0 0 (dy1ext DONKEY (S m)) (OWN (m+0))) 0)\n                            IMPLIES (IT 0 (BEAT 1)))\n                        c⁺ [x])))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                        not ((@bad_THAT 0 0 1 FARMER (fun m : nat => @badSOME (S m) 0 0 (dy1ext DONKEY (S m)) (OWN (m+0))) 0)\n                                IMPLIES (IT 0 (BEAT 1)) c⁺ [x]))))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                        not (@d_IMPLIES 1 1 0\n                                (@bad_THAT 0 0 1 FARMER (fun m : nat => @badSOME (S m) 0 0 (dy1ext DONKEY (S m)) (OWN (m+0))) 0)\n                                (IT 0 (BEAT 1)) c⁺ [x]))))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                        not (@d_IMPLIES 1 1 0   ((FARMER 0) AND (@badSOME 1 0 0 (dy1ext DONKEY 1) (OWN 0)))\n                                                (IT 0 (BEAT 1)) c⁺ [x]))))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                        not (@d_IMPLIES 1 1 0\n                                (@d_AND 1 0 1 (FARMER 0) (@badSOME 1 0 0 (dy1ext DONKEY 1) (OWN 0)))\n                                (@IT 0 2 0 (BEAT 1)) c⁺ [x]))))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                        not (@d_IMPLIES 1 1 0\n                                (fun (d : con 1) (v : e^2) =>\n                                    (FARMER 0 d [head v]) and (@badSOME 1 0 0 (dy1ext DONKEY 1) (OWN 0) (cc (FARMER 0) d) v))\n                                (BEAT 1 0) c⁺ [x]))))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                        not (@d_IMPLIES 1 1 0\n                                (fun (d : con 1) (v : e^2) =>\n                                    (farmer (head v)) and (EXISTS ((dy1ext DONKEY 1) THAT (OWN 0)) (cc (FARMER 0) d) v))\n                                (BEAT 1 0) c⁺ [x]))))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                        not (@d_IMPLIES 1 1 0\n                                (fun (d : con 1) (v : e^2) =>\n                                    (farmer (head v))\n                                        and (@EXISTS 1 0 (@bad_THAT 1 0 0 (dy1ext DONKEY 1) (OWN 0)) (cc (FARMER 0) d) v))\n                                (BEAT 1 0) c⁺ [x]))))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                        not (@d_IMPLIES 1 1 0\n                                (fun (d : con 1) (v : e^2) =>\n                                    (farmer (head v)) and (@bad_THAT 1 0 0 (dy1ext DONKEY 1) (OWN 0) 1 (cc (FARMER 0) d)⁺ v))\n                                (BEAT 1 0) c⁺ [x]))))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                        not (@d_IMPLIES 1 1 0\n                                (fun (d : con 1) (v : e^2) =>\n                                    (farmer (head v)) and ((dy1ext DONKEY 1 1) AND (OWN 0 1) (cc (FARMER 0) d)⁺ v))\n                                (BEAT 1 0) c⁺ [x]))))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                        not (@d_IMPLIES 1 1 0\n                                (fun (d : con 1) (v : e^2) =>\n                                    (farmer (head v)) and (@d_AND 2 0 0 (dy1ext DONKEY 1 1) (OWN 0 1) (cc (FARMER 0) d)⁺ v))\n                                (BEAT 1 0) c⁺ [x]))))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                        not (@d_IMPLIES 1 1 0\n                                (fun (d : con 1) (v : e^2) =>\n                                    (farmer (head v))\n                                        and ((dy1ext DONKEY 1 1 (cc (FARMER 0) d)⁺ (take 2 v))\n                                                and (OWN 0 1 (cc (dy1ext DONKEY 1 1) (cc (FARMER 0) d)⁺) v)))\n                                (BEAT 1 0) c⁺ [x]))))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                        not (@d_IMPLIES 1 1 0\n                                (fun (d : con 1) (v : e^2) =>\n                                    (farmer (head v))\n                                        and ((@dy1ext 0 0 DONKEY 1 1 (cc (FARMER 0) d)⁺ (take 2 v))\n                                                and (OWN 0 1 (cc (dy1ext DONKEY 1 1) (cc (FARMER 0) d)⁺) v)))\n                                (BEAT 1 0) c⁺ [x]))))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                        not (@d_IMPLIES 1 1 0\n                                (fun (d : con 1) (v : e^2) =>\n                                    (farmer (head v))\n                                        and ((kext (DONKEY 1) 0 (cc (FARMER 0) d)⁺ (take 2 v))\n                                                and (OWN 0 1 (cc (dy1ext DONKEY 1 1) (cc (FARMER 0) d)⁺) v)))\n                                (BEAT 1 0) c⁺ [x]))))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                        not (@d_IMPLIES 1 1 0\n                                (fun (d : con 1) (v : e^2) =>\n                                    (farmer (head v))\n                                        and ((@kext 2 0 (DONKEY 1) 0 (cc (FARMER 0) d)⁺ (take 2 v))\n                                                and (OWN 0 1 (cc (dy1ext DONKEY 1 1) (cc (FARMER 0) d)⁺) v)))\n                                (BEAT 1 0) c⁺ [x]))))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                        not (@d_IMPLIES 1 1 0\n                                (fun (d : con 1) (v : e^2) =>\n                                    (farmer (head v))\n                                        and ((DONKEY 1 (fun t : e^2 => (cc (FARMER 0) d)⁺ (t ++ [])) [head v,head (tail v)])\n                                                and (OWN 0 1 (cc (dy1ext DONKEY 1 1) (cc (FARMER 0) d)⁺) v)))\n                                (BEAT 1 0) c⁺ [x]))))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                        not (@d_IMPLIES 1 1 0\n                                (fun (d : con 1) (v : e^2) =>\n                                    (farmer (head v)) and ((donkey (head (tail v))) and (own (head v) (head (tail v)))))\n                                (BEAT 1 0) c⁺ [x]))))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                        not ((NOT (fun (d : con 1) (v : e^2) =>\n                                    (farmer (head v)) and ((donkey (head (tail v))) and (own (head v) (head (tail v))))))\n                                OR ((fun (d : con 1) (v : e^2) =>\n                                        (farmer (head v)) and ((donkey (head (tail v))) and (own (head v) (head (tail v)))))\n                                        AND (BEAT 1 0))\n                                c⁺ [x]))))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                        not (@d_OR 1 0 1\n                                (NOT (fun (d : con 1) (v : e^2) =>\n                                        (farmer (head v)) and ((donkey (head (tail v))) and (own (head v) (head (tail v))))))\n                                ((fun (d : con 1) (v : e^2) =>\n                                        (farmer (head v)) and ((donkey (head (tail v))) and (own (head v) (head (tail v)))))\n                                        AND (BEAT 1 0))\n                                c⁺ [x]))))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                        not (NOT ((NOT (NOT (fun (d : con 1) (v : e^2) =>\n                                                (farmer (head v))\n                                                    and ((donkey (head (tail v))) and (own (head v) (head (tail v)))))))\n                                    AND (NOT (kext ((fun (d : con 1) (v : e^2) =>\n                                                        (farmer (head v))\n                                                            and ((donkey (head (tail v))) and (own (head v) (head (tail v)))))\n                                         AND (BEAT 1 0)) 0)))\n                                c⁺ [x]))))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                        not (@NOT 1 0\n                                (@d_AND 1 0 0\n                                    (@NOT 1 0 (@NOT 1 1\n                                        (fun (d : con 1) (v : e^2) => (farmer (head v))\n                                            and ((donkey (head (tail v))) and (own (head v) (head (tail v)))))))\n                                    (@NOT 1 1 (kext\n                                        ((fun (d : con 1) (v : e^2) => (farmer (head v))\n                                            and ((donkey (head (tail v))) and (own (head v) (head (tail v)))))\n                                        AND (BEAT 1 0)) 0)))\n                                c⁺ [x]))))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                        not (not ((not (not (pex (fun y : e => (farmer x) and ((donkey y) and (own x y))))))\n                                    and\n                                    (not\n                                     (pex\n                                      (fun y : e =>\n                                       kext ((fun (d : con 1) (v : e^2) => (farmer (head v))\n                                                and ((donkey (head (tail v))) and (own (head v) (head (tail v)))))\n                                                AND (BEAT 1 0))\n                                                0 (cc (fun (d : con 1) (v : e^1) =>\n                                                        not (not (pex\n                                                                (fun y : e =>\n                                                                    (farmer (head v)) and ((donkey y) and (own (head v) y)))))) c⁺)\n                                                [x,y]))))))))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                        not (not ((not (not (pex (fun y : e => (farmer x) and ((donkey y) and (own x y))))))\n                                    and\n                                    (not\n                                     (pex\n                                      (fun y : e =>\n                                       @kext 1 1 (@d_AND 1 1 0 (fun (d : con 1) (v : e^2) => (farmer (head v))\n                                                and ((donkey (head (tail v))) and (own (head v) (head (tail v)))))\n                                                (BEAT 1 0))\n                                                0\n                                                (cc (fun (d : con 1) (v : e^1) =>\n                                                        not (not (pex\n                                                                (fun y : e =>\n                                                                    (farmer (head v)) and ((donkey y) and (own (head v) y)))))) c⁺)\n                                                [x,y]))))))))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                        not (not ((not (not (pex (fun y : e => (farmer x) and ((donkey y) and (own x y))))))\n                                    and (not (pex (fun y : e => ((farmer x) and ((donkey y) and (own x y)))\n                                                        and (BEAT 1 0\n                                                                (cc (fun (d : con 1) (v : e^2) => (farmer (head v)) and\n                                                                        ((donkey (head (tail v)))\n                                                                            and (own (head v) (head (tail v)))))\n                                                                    (fun t : e^1 => cc (fun (d : con 1) (v : e^1) =>\n                                                                                            not (not (pex (fun y : e =>\n                                                                                                 (farmer (head v)) and\n                                                                                                    ((donkey y)\n                                                                                                        and (own (head v) y))))))\n                                                                                        c⁺ (t ++ [])))\n                                                                [x,y])))))))))\n    :=: (fun (c : con 0) (_ : e^0) =>\n            not (pex (fun x : e =>\n                        not (not ((not (not (pex (fun y : e => (farmer x) and ((donkey y) and (own x y))))))\n                                    and (not (pex (fun y : e => ((farmer x) and ((donkey y) and (own x y)))\n                                                                    and (beat y x))))))))) *)\n\n\n(* newer versions of the quantifier stuff, along with a new function- that_proof *)\n    Fixpoint that_proof (m n i : nat) {struct n} : {k : nat | ((max (m+i) n)+k) = ((max m n)+i)}\n        :=  match n as y return {k : nat | ((max (m+i) y)+k) = ((max m y)+i)} with\n                | 0     =>  exist   (fun k : nat => ((max (m+i) 0)+k) = ((max m 0)+i)) 0\n                                    (eq_trans (Zria (max (m+i) 0)) (eq_trans (Zrix (m+i)) (eq_sym (feq (flip plus i) (Zrix m)))))\n                | S y   =>  match i as z return {k : nat | ((max (m+z) (S y))+k) = ((max m (S y))+z)} with\n                                | 0     =>  exist   (fun k : nat => ((max (m+0) (S y))+k) = ((max m (S y))+0)) 0\n                                                    (eq_trans   (Zria (max (m+0) (S y)))\n                                                                (eq_trans   (feq (flip max (S y)) (Zria m))\n                                                                            (eq_sym (Zria (max m (S y))))))\n                                | S z   =>  match m as x return {k : nat | ((max (x+(S z)) (S y))+k) = ((max x (S y))+(S z))} with\n                                                | 0     =>  let (a,p) := (that_proof 0 y z) in\n                                                            exist   (fun k : nat => (S ((max z y)+k)) = (S (y+(S z)))) (S a)\n                                                                    (feq S (eq_trans'   (Sdistr (max z y) a)\n                                                                                        (eq_trans (feq S p) (Sdistr y z))))\n                                                | S x   =>  let (b,q) := (that_proof x y (S z)) in\n                                                            exist   (fun k : nat =>\n                                                                        (S ((max (x+(S z)) y)+k)) = (S ((max x y)+(S z))))\n                                                                    b (feq S q)\n                                            end\n                            end\n            end.\n\n    Definition d_THAT : forall {m i j : nat}, dy m 1 i -> dy (m+i) 1 j -> dy m 1 (i+j)\n        :=  fun (m i j : nat) (D : dy m 1 i) (E : dy (m+i) 1 j) (n : nat) =>\n            let (k,p) := (that_proof m (S n) i) in (D n) AND (kcast (kext (E n) k) p).\n    Infix \"THAT\" := d_THAT (at level 30) : dyn_scope.\n    Definition SOME  : forall {m i j : nat}, dy m 1 i -> dy (m+i) 1 j -> kon m (S (i+j))\n        := fun (m i j : nat) (D : dy m 1 i) (E : dy (m+i) 1 j) => EXISTS (D THAT E).\n    Definition EVERY : forall {m i j : nat}, dy m 1 i -> dy (m+i) 1 j -> kon m 0\n        :=  fun (m i j : nat) (D : dy m 1 i) (E : dy (m+i) 1 j) =>\n            FORALL (fun n : nat => let (k,p) := (that_proof m (S n) i) in (D n) IMPLIES (kcast (kext (E n) k) p)).\n\n(* not using that_proof, but does require additional functions, including subtraction and min *)\n    Fixpoint min (m n : nat) {struct m} : nat := match m with 0 => 0 | S i => match n with 0 => 0 | S j => S (min i j) end end.\n    Definition pred : nat -> nat := fun m : nat => match m with 0 => 0 | S i => i end.\n    Definition Zramn : forall m : nat, (min m 0) = 0\n        := fun m : nat => match m as i return ((min i 0) = 0) with 0 => eq_refl | S i => eq_refl end.\n    Fixpoint minus (m n : nat) {struct m} : nat\n        := match m with 0 => 0 | S i => match n with 0 => S i | S j => minus i j end end.\n    Infix \"-\" := minus : type_scope. (* weirdness concerning the notation evaluations *)\n    Definition Zris : forall m : nat, (m-0) = m\n        := fun m : nat => match m as i return ((i-0) = i) with 0 => eq_refl | S i => eq_refl end.\n    Fixpoint thtprf (m n i : nat) : ((max (m+i) n)+(min (n-m) i)) = ((max m n)+i)\n        :=  match m as x,n as y,i as z return (((max (x+z) y)+(min (y-x) z)) = ((max x y)+z)) with\n                | 0,0,z         =>  eq_trans (Zria (max z 0)) (Zrix z)\n                | 0,S y,0       =>  eq_refl\n                | 0,S y,S z     =>  feq S (eq_trans' (Sdistr (max z y) (min y z))\n                                            (eq_trans   (feq S (eq_trans'\n                                                                    (feq (fun a : nat => (max z y)+(min a z)) (Zris y))\n                                                                    (thtprf 0 y z)))\n                                                        (Sdistr y z)))\n                | S x,0,z       =>  feq S (Zria (x+z))\n                | S x,S y,z     =>  feq S (thtprf x y z)\n            end.\n\n    Definition d_THAT2 : forall {m i j : nat}, dy m 1 i -> dy (m+i) 1 j -> dy m 1 (i+j)\n        :=  fun (m i j : nat) (D : dy m 1 i) (E : dy (m+i) 1 j) (k : nat) =>\n            let n := (min ((S k)-m) i) in\n            (D k) AND (kcast (kext (E k) n) (thtprf m (S k) i)).\n            (* @d_AND (max m (S k)) i j (D k)\n                (@kcast ((max (m+i) (S k))+n) j (@kext (max (m+i) (S k)) j (E k) n) ((max m (S k))+i) (thtprf m (S k) i)). *)\n    Infix \"THAT2\" := d_THAT2 (at level 30) : dyn_scope.\n    Definition SOME2  : forall {m i j : nat}, dy m 1 i -> dy (m+i) 1 j -> kon m (S (i+j))\n        := fun (m i j : nat) (D : dy m 1 i) (E : dy (m+i) 1 j) => EXISTS (D THAT2 E).\n    Definition EVERY2 : forall {m i j : nat}, dy m 1 i -> dy (m+i) 1 j -> kon m 0\n        :=  fun (m i j : nat) (D : dy m 1 i) (E : dy (m+i) 1 j) =>\n            FORALL (fun n : nat => let k := (min ((S n)-m) i) in (D n) IMPLIES (kcast (kext (E n) k) (thtprf m (S n) i))).\n\n(* new version of dynamic one-place predicate extension- makes use of minus *)\n    Fixpoint d1exprf (m n j : nat) : ((max m j)+(n-(j-m))) = (max (m+n) j)\n        :=  match m as x,n as y,j as z return (((max x z)+(y-(z-x))) = (max (x+y) z)) with\n                | 0,0,z         =>  Zria z\n                | 0,S y,0       =>  eq_refl\n                | 0,S y,S z     =>  feq S (eq_trans' (feq (fun a : nat => z+(y-a)) (Zris z)) (d1exprf 0 y z))\n                | S x,0,0       =>  eq_refl\n                | S x,0,S z     =>  feq S (d1exprf x 0 z)\n                | S x,S y,0     =>  eq_refl\n                | S x,S y,S z   =>  feq S (d1exprf x (S y) z)\n            end.\n\n    Definition d1ext : forall {m i : nat}, dy m 1 i -> forall n : nat, dy (m+n) 1 i\n        :=  fun (m i : nat) (D : dy m 1 i) (n k : nat) =>\n            let j := (n-((S k)-m)) in kcast (kext (D k) j) (d1exprf m n (S k)).\n            (* @kcast ((max m (S k))+j) i (@kext (max m (S k)) i (D k) j) (max (m+n) (S k)) (d1exprf m n (S k)). *)\n\n\n\n(* testing newer version of the quantifiers with new THAT, but still dy1ext *)\n    Definition the_donkey_sentence2 : kon 0 0\n        :=  EVERY   (FARMER THAT (fun m : nat => SOME (dy1ext DONKEY (S m)) (OWN (m+0))))\n                    (fun m : nat => kcast (IT 0 (BEAT m)) (feq S (Zrix m))).\n        (* :=: (fun (_ : con 0) (_ : e^0) =>\n             not (pex   (fun x : e =>\n                         not (not ((not (not (pex (fun y : e => (farmer x) and ((donkey y) and (own x y))))))\n                                    and (not (pex (fun y : e => ((farmer x) and ((donkey y) and (own x y)))\n                                                    and (beat x x))))))))) *)\n        (* :≡: (fun (_ : con 0) (_ : e^0) => every (fun x : e => (farmer x) and (some donkey (own x))) (fun x : e => beat x x)) *)\n\n    Definition AFTOADBI : kon 0 2\n        :=  SOME    (FARMER THAT (fun m : nat => SOME (dy1ext DONKEY (S m)) (OWN (m+0))))\n                    (fun m : nat => kcast (IT 0 (BEAT m)) (feq S (Zrix m))).\n        (* :=: (fun (_ : con 0) (v : e^2) => let (x,y) := (nth 0 v,nth 1 v) in\n                ((farmer x) and ((donkey y) and (own x y))) and (beat x x)) *)\n\n\n(* testing quantifiers with new THAT as well as d1ext instead of dy1ext *)\n    Definition the_donkey_sentence3 : kon 0 0\n        :=  @EVERY2 0 1 0\n                    (@d_THAT2 0 0 1 FARMER\n                        (fun m : nat => @SOME2 (S m) 0 0 (@d1ext 0 0 DONKEY (S m)) (OWN (m+0))))\n                    (fun m : nat => @kcast (S (max m 0)) 0 (@IT 0 (S m) 0 (BEAT m)) (S m) (feq S (Zrix m))).\n        (* yields same thing as old version… *)\n\n    (* Definition AFTOADBI2 : kon 0 2 *)\n\n", "meta": {"author": "needle29", "repo": "needle29", "sha": "93aace1fabf65c4bfb45f9e7c65d0759ca20278a", "save_path": "github-repos/coq/needle29-needle29", "path": "github-repos/coq/needle29-needle29/needle29-93aace1fabf65c4bfb45f9e7c65d0759ca20278a/donkey_sentence_4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.2759074066719715}}
{"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(*                                Checker.v                                 *)\n(****************************************************************************)\n(*               The mutilated checkerboard problem                         *)\n(*               Coq V5.10  G. Huet March 20th 1996                         *)\n(* Uses second-order formalisation Constrained Resolution G. Huet July 1973 *)\n(* Cf `A tough nut for proof procedures' J. McCarthy July 1964 SAIL Memo 16 *)\n(****************************************************************************)\n\nRequire Import Functions.\n\nParameter Black White : Set. (* sets of black (resp. white) squares *)\n\nParameter BW : Black -> White. (* |Black|<=|White| in full board *)\nAxiom BW_One_one : Injective _ _ BW.\n\n(* finite board *)\nAxiom Finite_Board : Finite Black.\n\n(* The Domino one_one map covers White *)\nParameter Domino : White -> Black.\nAxiom Domino_one_one : Injective _ _ Domino.\n\nTheorem Domino_covers_Black : Surjective _ _ Domino.\nProof.\napply Surjections_right with (f := BW).\napply (Finite_Board (BW o Domino)).\napply Injections_compose.\nexact BW_One_one.\nexact Domino_one_one.\nQed.\n\n\n\n", "meta": {"author": "coq-contribs", "repo": "checker", "sha": "07c048f263a2d3dd818d0810b01519d827d74993", "save_path": "github-repos/coq/coq-contribs-checker", "path": "github-repos/coq/coq-contribs-checker/checker-07c048f263a2d3dd818d0810b01519d827d74993/Checker.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832354982647, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.27580667126163755}}
{"text": "From Coq Require Import Numbers.Cyclic.ZModulo.ZModulo.\nFrom Coq Require Import ZArith.BinInt.\nFrom Coq Require Import ZArith.Zdiv.\nFrom Coq Require Import Lists.List.\nFrom Coq Require        Numbers.NatInt.NZLog.\nFrom Coq Require Import Strings.String.\nFrom CryptolToCoq Require Export CompM.\n\nDefinition sort (n : nat) := Type.\n\nAxiom error : forall (a : Type), String.string -> a.\n\nDefinition String := String.string.\n\nDefinition equalString (s1 s2: String) : bool :=\n  match String.string_dec s1 s2 with\n  | left _ => true\n  | right _ => false\n  end.\n\nDefinition appendString : String -> String -> String :=\n  String.append.\n\nDefinition Unit        := tt.\nDefinition UnitType    := unit.\nDefinition UnitType__rec := unit_rect.\n\nDefinition Bool   := bool.\nDefinition Eq     := identity.\nDefinition Eq__rec  := identity_rect.\nDefinition Refl   := identity_refl.\nDefinition EqP     := @eq.\nDefinition ReflP  := @eq_refl.\nDefinition true      := true.\nDefinition ite (a : Type) (b : Bool) (t e : a) : a := if b then t else e.\nDefinition and    := andb.\nDefinition false      := false.\nDefinition not      := negb.\nDefinition or     := orb.\nDefinition xor    := xorb.\nDefinition boolEq := Coq.Bool.Bool.eqb.\n\n(* SAW uses an alternate form of eq_rect where the motive function P also\ndepends on the equality proof itself *)\nDefinition EqP__rec (A : Type) (x : A) (P: forall y, x=y -> Type) (p:P x eq_refl) y (e:x=y) :\n  P y e.\n  dependent inversion e; assumption.\nDefined.\n\nTheorem boolEq__eq (b1 b2:Bool) : Eq Bool (boolEq b1 b2) (ite Bool b1 b2 (not b2)).\nProof.\n  destruct b1, b2; reflexivity.\nQed.\n\nDefinition coerce (a b : sort 0) (eq : Eq (sort 0) a b) (x : a) : b :=\n  match eq in identity _ a' return a' with\n  | identity_refl _ => x\n  end\n.\n\n(** Typeclass for `eq` **)\n(* NOTE: SAW core prelude's eq is not being used much by the translation at the\nmoment, so we skip it.  The following type class declaration could be used if\none wanted to translate `eq`.  However, it would require more work in the\ntranslation, because calls to `eq T a b` in SAW must be translated to either `eq\na b` or `@eq T _ a b`, where the underscore stands for the dictionary.  As a\nresult, this would not be an identifier-to-identifier translation, but rather a\nterm-to-term translation, and would require knowing the number of arguments\nexpected before the dicitonary. *)\n(*\nClass eqClass `(a : Type) :=\n  {\n    eq : a -> a -> bool;\n    eq_refl : forall (x : a), Eq Bool (eq x x) True;\n  }.\n\nGlobal Instance eqClassBool : eqClass Bool :=\n  {\n    eq := boolEq;\n  }.\n+ destruct x; reflexivity.\nDefined.\n\nTheorem eq_Bool : Eq (Bool -> Bool -> Bool) eq boolEq.\nProof.\n  reflexivity.\nQed.\n\nGlobal Instance eqClass_sawVec (n : nat) (a : Type) `(A : eqClass a) : eqClass (sawVec n a) :=\n  {\n    eq := Vector.eqb _ eq;\n  }.\n+ induction 0 as [|? ? ? IH].\n  - reflexivity.\n  - simpl.\n    rewrite eq_refl.\n    rewrite IH.\n    reflexivity.\nDefined.\n*)\n\n(* SAW's prelude defines iteDep as a Bool eliminator whose arguments are\nreordered to look more like if-then-else. *)\nDefinition iteDep (P : Bool -> Type) (b : Bool) : P true -> P false -> P b :=\n  fun Ptrue Pfalse => bool_rect P Ptrue Pfalse b.\n\nDefinition ite_eq_iteDep : forall (a : Type) (b : Bool) (x y : a),\n    @identity a (ite a b x y) (iteDep (fun _ => a) b x y).\nProof.\n  reflexivity.\nDefined.\n\nDefinition iteDep_True : forall (p : Bool -> Type), forall (f1 : p true), forall (f2 : p false), (@identity (p true) (iteDep p true f1 f2)) f1.\nProof.\n  reflexivity.\nDefined.\n\nDefinition iteDep_False : forall (p : Bool -> Type), forall (f1 : p true), forall (f2 : p false), (@identity (p false) (iteDep p false f1 f2)) f2.\nProof.\n  reflexivity.\nDefined.\n\nDefinition not__eq (b : Bool) : @identity Bool (not b) (ite Bool b false true).\nProof.\n  reflexivity.\nDefined.\n\nDefinition and__eq (b1 b2 : Bool) : @identity Bool (and b1 b2) (ite Bool b1 b2 false).\nProof.\n  reflexivity.\nDefined.\n\nDefinition or__eq (b1 b2 : Bool) : @identity Bool (or b1 b2) (ite Bool b1 true b2).\nProof.\n  reflexivity.\nDefined.\n\nDefinition xor__eq (b1 b2 : Bool) : @identity Bool (xor b1 b2) (ite Bool b1 (not b2) b2).\nProof.\n  destruct b1; destruct b2; reflexivity.\nDefined.\n\n(*\nDefinition eq__eq (b1 b2 : Bool) : @identity Bool (eq b1 b2) (ite Bool b1 b2 (not b2)).\nProof.\n  destruct b1; destruct b2; reflexivity.\nDefined.\n*)\n\nTheorem ite_bit (b c d : Bool) : Eq Bool (ite Bool b c d) (and (or (not b) c) (or b d)).\nProof.\n  destruct b, c, d; reflexivity.\nQed.\n\n(* TODO: doesn't actually coerce *)\nDefinition sawCoerce {T : Type} (a b : Type) (_ : T) (x : a) := x.\n\n(* TODO: doesn't actually coerce *)\nDefinition sawUnsafeCoerce (a b : Type) (x : a) := x.\n\nDefinition Nat := nat.\nDefinition Nat_rect := nat_rect.\n\n(* Definition minNat := Nat.min. *)\n\nDefinition uncurry (a b c : Type) (f : a -> b -> c) (p : a * (b * unit)) : c  :=\n  f (fst p) (fst (snd p)).\n\nDefinition widthNat (n : Nat) : Nat := 1 + Nat.log2 n.\n\nDefinition divModNat (x y : Nat) : (Nat * Nat) :=\n  match y with\n  | 0 => (y, y)\n  | S y'=>\n    let (p, q) := Nat.divmod x y' 0 y' in\n    (p, y' - q)\n  end.\n\nDefinition id := @id.\nDefinition PairType := prod.\nDefinition PairValue := @pair.\nDefinition Pair__rec := prod_rect.\nDefinition fst {A B} := @fst A B.\nDefinition snd {A B} := @snd A B.\nDefinition Zero := O.\nDefinition Succ := S.\n\n\nDefinition Integer := Z.\nDefinition intAdd : Integer -> Integer -> Integer := Z.add.\nDefinition intSub : Integer -> Integer -> Integer := Z.sub.\nDefinition intMul : Integer -> Integer -> Integer := Z.mul.\nDefinition intDiv : Integer -> Integer -> Integer := Z.div.\nDefinition intMod : Integer -> Integer -> Integer := Z.modulo.\nDefinition intMin : Integer -> Integer -> Integer := Z.min.\nDefinition intMax : Integer -> Integer -> Integer := Z.max.\nDefinition intNeg : Integer -> Integer := Z.opp.\nDefinition intAbs : Integer -> Integer := Z.abs.\nDefinition intEq : Integer -> Integer -> Bool := Z.eqb.\nDefinition intLe : Integer -> Integer -> Bool := Z.leb.\nDefinition intLt : Integer -> Integer -> Bool := Z.ltb.\nDefinition intToNat : Integer -> Nat := Z.to_nat.\nDefinition natToInt : Nat -> Integer := Z.of_nat.\n\n(* NOTE: the following will be nonsense for values of n <= 1 *)\nDefinition IntMod (n : nat) := Z.\nDefinition toIntMod (n : Nat) : Integer -> IntMod n := fun i => Z.modulo i (Z.of_nat n).\nDefinition fromIntMod (n : Nat) : (IntMod n) -> Integer := ZModulo.to_Z (Pos.of_nat n).\nLocal Notation \"[| a |]_ n\" := (to_Z (Pos.of_nat n) a) (at level 0, a at level 99).\nDefinition intModEq (n : Nat) (a : IntMod n) (b : IntMod n) : Bool\n  := Z.eqb [| a |]_n [| b |]_n.\nDefinition intModAdd : forall (n : Nat), (IntMod n) -> (IntMod n) -> IntMod n\n  := fun _ => ZModulo.add.\nDefinition intModSub : forall (n : Nat), (IntMod n) -> (IntMod n) -> IntMod n\n  := fun _ => ZModulo.sub.\nDefinition intModMul : forall (n : Nat), (IntMod n) -> (IntMod n) -> IntMod n\n  := fun _ => ZModulo.mul.\nDefinition intModNeg : forall (n : Nat), (IntMod n) -> IntMod n\n  := fun _ => ZModulo.opp.\n\n\n(***\n *** A simple typeclass-based implementation of SAW record types\n ***\n *** The idea is to support a projection term recordProj e \"field\" on an element\n *** e of a record type without having to find \"field\" in the record type of e,\n *** by using typeclass resolution to find it for us.\n ***)\n\n(* The empty record type *)\nVariant RecordTypeNil : Type :=\n  RecordNil : RecordTypeNil.\n\n(* A non-empty record type *)\nVariant RecordTypeCons (str:String.string) (tp:Type) (rest_tp:Type) : Type :=\n  RecordCons (x:tp) (rest:rest_tp) : RecordTypeCons str tp rest_tp.\n\nArguments RecordTypeCons str%string_scope tp rest_tp.\nArguments RecordCons str%string_scope {tp rest_tp} x rest.\n\n(* Get the head element of a non-empty record type *)\nDefinition recordHead {str tp rest_tp} (r:RecordTypeCons str tp rest_tp) : tp :=\n  match r with\n  | RecordCons _ x _ => x\n  end.\n\n(* Get the tail of a non-empty record type *)\nDefinition recordTail {str tp rest_tp} (r:RecordTypeCons str tp rest_tp) : rest_tp :=\n  match r with\n  | RecordCons _ _ rest => rest\n  end.\n\n(* An inductive description of a string being a field in a record type *)\nInductive IsRecordField (str:String) : Type -> Type :=\n| IsRecordField_Base tp rtp : IsRecordField str (RecordTypeCons str tp rtp)\n| IsRecordField_Step str' tp rtp : IsRecordField str rtp ->\n                                   IsRecordField str (RecordTypeCons str' tp rtp).\n\n(* We want to use this as a typeclass, with its constructors for instances *)\nExisting Class IsRecordField.\nHint Constructors IsRecordField : typeclass_instances.\n\n(* If str is a field in record type rtp, get its associated type *)\nFixpoint getRecordFieldType rtp str `{irf:IsRecordField str rtp} : Type :=\n  match irf with\n  | IsRecordField_Base _ tp rtp => tp\n  | IsRecordField_Step _ _ _ _ irf' => @getRecordFieldType _ _ irf'\n  end.\n\n(* If str is a field in record r of record type rtp, get its associated value *)\nFixpoint getRecordField {rtp} str `{irf:IsRecordField str rtp} :\n  rtp -> getRecordFieldType rtp str :=\n  match irf in IsRecordField _ rtp\n        return rtp -> getRecordFieldType rtp str (irf:=irf) with\n  | IsRecordField_Base _ tp rtp' => fun r => recordHead r\n  | IsRecordField_Step _ _ _ _ irf' =>\n    fun r => @getRecordField _ _ irf' (recordTail r)\n  end.\n\n(* Reorder the arguments of getRecordField *)\nDefinition RecordProj {rtp} (r:rtp) str `{irf:IsRecordField str rtp} :\n  getRecordFieldType rtp str :=\n  getRecordField str r.\n\nArguments RecordProj {_} r str%string {_}.\n\n\n(* Some tests *)\n\nDefinition recordTest1 := RecordCons \"fld1\" 0 (RecordCons \"fld2\" true RecordNil).\n(* Check recordTest1. *)\n\nDefinition recordTest2 := RecordProj recordTest1 \"fld1\".\n(* Check recordTest2. *)\n\n(* Definition recordTestFail := RecordProj recordTest1 \"fld3\". *)\n\nDefinition recordTest4 :=\n RecordCons \"id_fun\" (fun (X:Type) (x:X) => x) RecordNil.\n\nDefinition recordTest5 := RecordProj recordTest4 \"id_fun\" nat 0.\n", "meta": {"author": "GaloisInc", "repo": "saw-core-coq", "sha": "91d7dae3272d93906b1068e15d0312dddfa64d64", "save_path": "github-repos/coq/GaloisInc-saw-core-coq", "path": "github-repos/coq/GaloisInc-saw-core-coq/saw-core-coq-91d7dae3272d93906b1068e15d0312dddfa64d64/coq/handwritten/CryptolToCoq/SAWCoreScaffolding.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2758066712616375}}
{"text": "(** * Non-unital lB0-systems\n\nBy Vladimir Voevodsky, started on Jan. 24, 2015 *)\n\n\nRequire Import UniMath.Foundations.All.\n\nRequire Import TypeTheory.Csystems.hSet_ltowers.\n\nRequire Export TypeTheory.Bsystems.prelB. \nRequire Export TypeTheory.Bsystems.TS_ST.\nRequire Export TypeTheory.Bsystems.STid .\nRequire Export TypeTheory.Bsystems.dlt .\n\n\n\n(** ** Definitions of the main layers *)\n\n(** *** The layer associated with operations T *)\n\nDefinition T_layer ( BB : lBsystem_carrier ) :=\n  ∑ T : T_layer_0 BB, ( T_ax1a_type T ) × ( T_ax1b_type T ).\n\n(** Warning: [T_layer_0] refers to a pre-lB-system, [T_layer] refers to a lB0-system. *)\n\nDefinition T_layer_to_T_layer_0 ( BB : lBsystem_carrier ) : T_layer BB -> T_layer_0 BB :=\n  pr1 . \nCoercion T_layer_to_T_layer_0 : T_layer >-> T_layer_0 . \n \n\n\n(** *** The layer associated with operations Tt *)\n\n\nDefinition Tt_layer { BB : lBsystem_carrier } ( T : T_ops_type BB ) :=\n  ∑ Tt : Tt_ops_type BB, Tt_ax1_type T Tt.\n\nDefinition Tt_layer_to_Tt_ops_type ( BB : lBsystem_carrier ) ( T : T_ops_type BB )\n  ( Tt : Tt_layer T ) : Tt_ops_type BB := pr1 Tt .\nCoercion Tt_layer_to_Tt_ops_type : Tt_layer >-> Tt_ops_type . \n\n\n(** *** The structure formed by operations T and Tt *)\n\nDefinition T_Tt_layer ( BB : lBsystem_carrier ) :=\n  ∑ T : T_layer BB, Tt_layer T.\n\nDefinition T_Tt_layer_to_T_layer { BB : lBsystem_carrier } ( T_Tt : T_Tt_layer BB ) :\n  T_layer BB := pr1 T_Tt .\nCoercion T_Tt_layer_to_T_layer : T_Tt_layer >->  T_layer .\n\nDefinition T_Tt_layer_to_Tt_layer { BB : lBsystem_carrier } ( T_Tt : T_Tt_layer BB ) :\n  Tt_layer T_Tt := pr2 T_Tt .\nCoercion T_Tt_layer_to_Tt_layer : T_Tt_layer >-> Tt_layer .  \n\n\n(** *** The layer associated with operations S *)\n\n\nDefinition S_layer ( BB : lBsystem_carrier ) :=\n  ∑ S : S_layer_0 BB, ( S_ax1a_type S ) × ( S_ax1b_type S ).\n\nDefinition S_layer_to_S_layer_0 ( BB : lBsystem_carrier ) :\n  S_layer BB -> S_layer_0 BB := pr1 .\nCoercion S_layer_to_S_layer_0 : S_layer >-> S_layer_0 . \n\n\n(** *** The layer associated with operations St *)\n\n\nDefinition St_layer { BB : lBsystem_carrier } ( S : S_ops_type BB ) :=\n  ∑ St : St_ops_type BB, St_ax1_type S St.\n\nDefinition St_layer_to_St_ops_type ( BB : lBsystem_carrier ) ( S : S_ops_type BB )\n  ( St : St_layer S ) : St_ops_type BB := pr1 St.\nCoercion St_layer_to_St_ops_type : St_layer >-> St_ops_type .\n\n\n(** *** The structure formed by operations S and St *)\n\nDefinition S_St_layer ( BB : lBsystem_carrier ) :=\n  ∑ S : S_layer BB, St_layer S.\n\nDefinition S_St_layer_to_S_layer { BB : lBsystem_carrier } ( S_St : S_St_layer BB ) :\n  S_layer BB := pr1 S_St .\nCoercion S_St_layer_to_S_layer : S_St_layer >->  S_layer .\n\nDefinition S_St_layer_to_St_layer { BB : lBsystem_carrier } ( S_St : S_St_layer BB ) :\n  St_layer S_St := pr2 S_St .\nCoercion S_St_layer_to_St_layer : S_St_layer >-> St_layer .  \n\n\n(** ** Complete definition of a non-unital lB0-system *)\n\nDefinition T_ax1_type ( BB : prelBsystem_non_unital ) :=\n  ( T_ax1a_type ( @T_op BB ) ) × ( T_ax1b_type ( @T_op BB ) ) .\n\nDefinition Tt_ax1_type' ( BB : prelBsystem_non_unital ) :=\n  Tt_ax1_type ( @T_op BB ) ( @Tt_op BB ) .\n\nDefinition S_ax1_type ( BB : prelBsystem_non_unital ) :=\n  ( S_ax1a_type ( @S_op BB ) ) × ( S_ax1b_type ( @S_op BB ) ) .\n\nDefinition St_ax1_type' ( BB : prelBsystem_non_unital ) :=\n  St_ax1_type ( @S_op BB ) ( @St_op BB ) .\n\nDefinition lB0system_non_unital :=\n  ∑ BB : prelBsystem_non_unital,\n               ( ( T_ax1_type BB ) × ( Tt_ax1_type' BB ) ) ×\n               ( ( S_ax1_type BB ) × ( St_ax1_type' BB ) ).\n\n(** This definition corresponds to Definition 2.5 in arXiv:1410.5389v1 modulo\n    the details on the treatment of the second cases of 2.5.2 and 2.5.4, discussed\n    elsewhere (see the definition of [T_ax1b_type] and [S_ax1b_type] and the lemmas\n    [ft_T] and [ft_S]). *) \n\nDefinition lB0system_non_unital_pr1 : lB0system_non_unital -> prelBsystem_non_unital := pr1 .\nCoercion lB0system_non_unital_pr1 : lB0system_non_unital >-> prelBsystem_non_unital .\n\n\n(** *** Access functions to the axioms *)\n\n \nDefinition T_ax1a { BB : lB0system_non_unital } : T_ax1a_type ( @T_op BB ) :=\n  pr1 ( pr1 ( pr1 ( pr2 BB ) ) ) .\n\nDefinition T_ax1b { BB : lB0system_non_unital } : T_ax1b_type ( @T_op BB ) :=\n  pr2 ( pr1 ( pr1 ( pr2 BB ) ) ) .\n\nDefinition Tt_ax1 { BB : lB0system_non_unital } : Tt_ax1_type ( @T_op BB ) ( @Tt_op BB ) :=\n  pr2 ( pr1 ( pr2 BB ) ) .\n\nDefinition Tt_ax0 { BB : lB0system_non_unital } : Tt_ax0_type ( @Tt_op BB ) :=\n  Tt_ax1_to_Tt_ax0 ( @T_ax0 BB ) ( @Tt_ax1 BB ) .  \n\n\nDefinition S_ax1a { BB : lB0system_non_unital } : S_ax1a_type ( @S_op BB ) :=\n  pr1 ( pr1 ( pr2 ( pr2 BB ) ) ) .\n\nDefinition S_ax1b { BB : lB0system_non_unital } : S_ax1b_type ( @S_op BB ) :=\n  pr2 ( pr1 ( pr2 ( pr2 BB ) ) ) .\n\nDefinition St_ax1 { BB : lB0system_non_unital } : St_ax1_type ( @S_op BB ) ( @St_op BB ) :=\n  pr2 ( pr2 ( pr2 BB ) ) .\n\nDefinition St_ax0 { BB : lB0system_non_unital } : St_ax0_type ( @St_op BB ) :=\n  St_ax1_to_St_ax0 ( @S_ax0 BB ) ( @St_ax1 BB ) .\n\n\n\n(** ** Derived operations re-defined in a more streamlined form *)\n\n\n(** *** Derived operations related to operation T *)\n\n\n\nDefinition T_fun { BB : lB0system_non_unital } ( X : BB ) ( gt0 : ll X > 0 ) :\n  ltower_fun ( ltower_over ( ft X ) ) ( ltower_over X ) :=\n  T_fun.T_fun ( @T_ax0 BB ) ( @T_ax1a BB ) ( @T_ax1b BB ) gt0 . \n  \nDefinition Tj_fun { BB : lB0system_non_unital } { A X1 : BB } ( isov : isover X1 A ) :\n  ltower_fun ( ltower_over A ) ( ltower_over X1 ) :=\n  T_fun.Tj_fun ( @T_ax0 BB ) ( @T_ax1a BB ) ( @T_ax1b BB ) isov .\n\nDefinition Tj_fun_compt { BB : lB0system_non_unital } { X Y : BB } ( isab : isabove X Y ) :\n  Tj_fun isab = ltower_funcomp ( Tj_fun ( isover_ft' isab ) ) ( T_fun X ( isabove_gt0 isab ) ) :=\n  Tj_fun_compt ( @T_ax0 BB ) ( @T_ax1a BB ) ( @T_ax1b BB ) isab . \n\nDefinition Tj { BB : lB0system_non_unital } { X A Y : BB }\n           ( isov1 : isover X A ) ( isov2 : isover Y A ) : BB :=\n  pocto ( Tj_fun isov1 (  obj_over_constr isov2 ) ) .\n\nDefinition isover_Tj { BB : lB0system_non_unital } { X A Y : BB }\n           ( isov1 : isover X A ) ( isov2 : isover Y A ) : isover ( Tj isov1 isov2 ) X :=\n  pr2 ( Tj_fun isov1 (  obj_over_constr isov2 ) ) .\n\nDefinition Tj_compt { BB : lB0system_non_unital } { X A Y : BB }\n           ( isab : isabove X A ) ( isov2 : isover Y A ) :\n  Tj isab isov2 =\n  T_ext X ( Tj ( isover_ft' isab ) isov2 ) ( isabove_gt0 isab ) ( isover_Tj ( isover_ft' isab ) isov2 ) . \nProof.\n  unfold Tj .  \n  rewrite Tj_fun_compt . \n  apply idpath . \nDefined.\n\n\nDefinition Tprod_over { BB : lB0system_non_unital } ( X1 : BB ) :\n  ltower_fun BB ( ltower_over X1 ) :=\n  T_fun.Tprod_fun ( @T_ax0 BB ) ( @T_ax1a BB ) ( @T_ax1b BB ) X1 .  \n           \n\nDefinition Tprod { BB : lB0system_non_unital } ( X Y : BB ) : BB := pocto ( Tprod_over X Y ) .\n\nDefinition isover_Tprod { BB : lB0system_non_unital } ( X Y : BB ) :\n  isover ( Tprod X Y ) X := pr2 ( Tprod_over X Y ) .\n\nLemma ll_Tprod { BB : lB0system_non_unital } ( X Y : BB ) : ll ( Tprod X Y ) = ll X + ll Y .\nProof.\n  unfold Tprod .\n  rewrite ll_pocto .\n  rewrite natpluscomm . \n  rewrite ( @ll_ltower_fun BB _ ( Tprod_over X ) ) . \n  apply idpath . \nDefined.\n\n\n\nDefinition Tprod_compt { BB : lB0system_non_unital } ( X Y : BB ) ( gt0 : ll X > 0 ) :\n  Tprod X Y = T_ext X ( Tprod ( ft X ) Y ) gt0 ( isover_Tprod _ _ ) .\nProof.\n  set ( int :=\n             T_fun.Tprod_compt\n               ( @T_ax0 BB ) ( @T_ax1a BB ) ( @T_ax1b BB ) X Y gt0 ).\n  exact ( maponpaths pocto int ) . \nDefined.\n\n\n(** *** Derived operations related to operation S *)\n\n\n\nLemma ll_S_ext { BB : lB0system_non_unital }\n      ( r : Tilde BB ) ( X : BB ) ( inn : isover X ( dd r )  ) : ll ( S_ext r X inn ) = ll X - 1.\nProof.\n  apply S_fun.ll_S_ext .\n  + apply ( @S_ax0 BB ) .\n  + apply ( @S_ax1b BB ) . \nDefined.\n\n  \n\nDefinition S_fun { BB : lB0system_non_unital } ( r : Tilde BB ) :\n  ltower_fun ( ltower_over ( dd r ) ) ( ltower_over ( ft ( dd r ) ) ) :=\n  ltower_fun_S ( @S_ax0 BB ) ( @S_ax1a BB ) ( @S_ax1b BB ) r . \n\n\n\n\n\n\n\n\n\n\n(* End of the file lB0_non_unital.v *)\n\n", "meta": {"author": "UniMath", "repo": "TypeTheory", "sha": "e7fc5a0c4564afc44b084d134e4110d447b68404", "save_path": "github-repos/coq/UniMath-TypeTheory", "path": "github-repos/coq/UniMath-TypeTheory/TypeTheory-e7fc5a0c4564afc44b084d134e4110d447b68404/TypeTheory/Bsystems/lB0_non_unital.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2758066636828176}}
{"text": "(* -*- company-coq-local-symbols: ((\"|=\" . ?⊨) (\"=|\" . ?⫤) (\"->>\" . ?↠) (\"=~\" . ?≈) (\"<|\" . ?⟨) (\"|>\" . ?⟩) ); -*- *)\nSet Warnings \"-notation-overridden\".\n\nRequire Import Prelude.Prelude.\nRequire Import Defs.Defs.\n\nRequire Import Complete.SameShape.\n\nDefinition subst_name (x__in x__out x : termvar) : termvar := (if eq_var x x__out then x__in else x).\n#[export] Hint Unfold subst_name : core.\n\nFixpoint subst_name_Env (x__in x__out : termvar) (env:Env) : Env :=\n  match env with\n  | Env_Empty            => Env_Empty\n  | (Env_Skol env' skA ) => Env_Skol (subst_name_Env x__in x__out env') skA\n  | (Env_A env' a      ) => Env_A (subst_name_Env x__in x__out env') a\n  | (Env_Var env' x sch) => Env_Var (subst_name_Env x__in x__out env') (subst_name x__in x__out x) sch\n  | (Env_Obj env' obj  ) => Env_Obj (subst_name_Env x__in x__out env') obj\nend.\n#[export] Hint Unfold subst_name_Env : core.\n\nDefinition Inf_rename_binding__def := forall (env__in : Env) (e : e) (a : A) (ty : Ty) (env__out : Env),\n    env__in |= e ▸ ⟨a⟩ ty =| env__out\n  -> forall x__in x__out,\n    (subst_name_Env x__in x__out env__in) |= subst_tm_e (e_Var_f x__in) x__out e ▸ ⟨a⟩ ty =| (subst_name_Env x__in x__out env__out).\n\nDefinition Gen_rename_binding__def := forall (env__in : Env) (e : e) (sch : Sch) (env__out : Env),\n    env__in |= e ▸ sch =| env__out\n  -> forall x__in x__out,\n    (subst_name_Env x__in x__out env__in) |= subst_tm_e (e_Var_f x__in) x__out e ▸ sch =| (subst_name_Env x__in x__out env__out).\n\nTheorem subst_name_Env_lookup: forall (env : Env) (x__in x__out x : termvar) (sch : Sch),\n    SchPSI.In (x, sch) (Env_bindings env)\n  -> SchPSI.In (subst_name x__in x__out x, sch) (Env_bindings (subst_name_Env x__in x__out env)).\nProof.\n  introv IN. induction env.\n  - crush.\n  - simpl. rewr in IN. rewr. eauto.\n  - simpl. rewr in IN. rewr. eauto.\n  - simpl. rewr in IN. rewr. indestr.\n    + eauto.\n    + rewr in H. crush.\n  - simpl. rewr in IN. rewr. eauto.\nQed.\n\nTheorem Inst_Env_sub : forall env1 env2 sch a ty,\n    Inst env1 sch a ty\n  -> env1 [=]e# env2\n  -> Inst env2 sch a ty.\nProof.\n  intros. gen env2. induction H; intros. crush.\n  econstructor. unfold Env_fr_eq in H0. fsetdec. intros.\n  eapply H. eassumption. crush.\nQed.\n\nTheorem subst_name_Env_Env_eq : forall x__in x__out env,\n    subst_name_Env x__in x__out env [=]e env.\nProof.\n  induction env. 1,2,3,5: crush.\n  rewr_erel. unfold Env_eq in IHenv. destr. split.\n  simpl. rewr. assumption.\n  simpl. rewr. assumption.\nQed.\n#[export] Hint Resolve subst_name_Env_Env_eq : core.\n\nTheorem subst_name_Env_Env_fr_eq : forall x__in x__out env,\n    subst_name_Env x__in x__out env [=]e# env.\nProof.\n  induction env. 1,2,3,5: crush.\n  rewr_erel. unfold Env_fr_eq in IHenv. destr. split.\n  simpl. rewr. assumption.\n  simpl. rewr. assumption.\nQed.\n#[export] Hint Resolve subst_name_Env_Env_fr_eq : core.\n\nTheorem subst_name_Env_cons_o : forall env obj x__in x__out,\n    subst_name_Env x__in x__out (env ::o obj) = subst_name_Env x__in x__out env ::o obj.\nProof. reflexivity. Qed.\n#[export] Hint Rewrite subst_name_Env_cons_o : core.\n\nTheorem subst_name_Env_app : forall x__in x__out env1 env2,\n    subst_name_Env x__in x__out (env1 +++ env2)\n  = subst_name_Env x__in x__out env1 +++ subst_name_Env x__in x__out env2.\nProof. induction env2; crush. Qed.\n#[export] Hint Rewrite subst_name_Env_app : core.\n\nTheorem subst_name_Envsubst_exvar_Env : forall x__in x__out ty exA env,\n    subst_name_Env x__in x__out (subst_exvar_Env ty exA env)\n  = subst_exvar_Env ty exA (subst_name_Env x__in x__out env).\nProof. induction env; rewr; crush. Qed.\n\nTheorem subst_name_Env_Sub_app_Env : forall x__in x__out env sub,\n    subst_name_Env x__in x__out (Sub_app_Env env sub)\n  = Sub_app_Env (subst_name_Env x__in x__out env) sub.\nProof.\n  intros. induction sub. crush.\n  destruct a. simpl. rewr.\n  rewrite <- IHsub. rewrite subst_name_Envsubst_exvar_Env. reflexivity.\nQed.\n\nTheorem subst_name_Env_U : forall (x__in x__out : termvar) (env__in env__out : Env) (E : Eqs),\n    U env__in E env__out\n  -> U (subst_name_Env x__in x__out env__in) E (subst_name_Env x__in x__out env__out).\nProof.\n  introv U. destruct U. econstructor.\n  induction Us. crush.\n  forwards: subst_name_Env_Sub_app_Env. rewrite H in IHUs.\n  econstructor. 2:eassumption. clear H. destruct UNI. 1,2,3: auto.\n  - assert (FrA [exA2; exA1] (subst_name_Env x__in x__out (Env1 ::a (A2 ++ exA :: A1) +++ Env2))). eauto.\n    rewr. rewr in H2. simpl. applys_eq UssSplitL. rewr in H3. eassumption. rewr. eassumption.\n  - assert (FrA [exA2; exA1] (subst_name_Env x__in x__out (Env1 ::a (A2 ++ exA :: A1) +++ Env2))). eauto.\n    rewr. rewr in H2. simpl. applys_eq UssSplitR. rewr in H3. eassumption. rewr. eassumption.\n  - rewr. applys_eq UssSubExL. fold subst_name_Env.\n    assert (subst_name_Env x__in x__out (Env1 ::a A1) [=]e Env1 ::a A1). eauto. unfold Env_eq in H1. destr. rewrite H2. assumption.\n  - assert (exA `in` Env_exvars (subst_name_Env x__in x__out Env1 ::a A1)).\n      assert (subst_name_Env x__in x__out (Env1 ::a A1) [=]e Env1 ::a A1). eauto. unfold Env_eq in H1. destr. rewrite H2. assumption.\n    rewr. applys_eq UssSubExR. eassumption.\n  - rewr. applys_eq UssSubUnitAL.\n  - rewr. applys_eq UssSubUnitAR.\nQed.\n\nTheorem Inf_Gen_Wf :\n  Inf_rename_binding__def /\\ Gen_rename_binding__def.\nProof.\n  apply Inf_Gen_mut.\n\n  - introv IN SS. intros x__in x__out.\n    forwards IN': subst_name_Env_lookup x__in x__out. eassumption.\n    unfold subst_name in IN'. destruct (x == x__out).\n    + simpl. if_taut. intros. econstructor. eassumption.\n      eapply Inst_Env_sub. eassumption. auto using subst_name_Env_Env_fr_eq.\n    + simpl. if_taut. intros. econstructor. eassumption.\n      eapply Inst_Env_sub. eassumption. auto using subst_name_Env_Env_fr_eq.\n\n  - intros. simpl. crush.\n\n  - introv NIE INF IH. intros.\n    forwards EQ: subst_name_Env_Env_fr_eq x__in x__out Envin.\n    simpl. applys InfAbs (L \\u singleton x__out). unfold Env_fr_eq in EQ. destr. rewrite e0. eassumption.\n    intros y NI__y.\n    forwards: IH y x__in x__out. fsetdec.\n    assert (y <> x__out). unfold not. intros. apply NI__y. fsetdec.\n    asserts_rewrite ( subst_tm_e (e_Var_f x__in) x__out (open_e_wrt_e e5 (e_Var_f y))\n                    = open_e_wrt_e (subst_tm_e (e_Var_f x__in) x__out e5) (e_Var_f y)) in H.\n      rewrite subst_tm_e_open_e_wrt_e. simpl. ifdec. contradiction. reflexivity. auto.\n    asserts_rewrite (subst_name x__in x__out y = y) in H.\n      unfold subst_name. ifdec. contradiction. reflexivity.\n    assumption.\n\n  - introv NIE INF__e1 IH__e1 INF__e2 IH__e2 U. intros.\n    simpl.\n    forwards IH1: IH__e1 x__in x__out.\n    forwards IH2: IH__e2 x__in x__out.\n    applys InfApp exB.\n    2:apply IH1.\n    2:apply IH2.\n    + forwards EQ: subst_name_Env_Env_fr_eq x__in x__out (Env2 ::a (A2 ++ A1')).\n      unfold Env_fr_eq in EQ. destr. rewrite H0. eassumption.\n    + forwards U': subst_name_Env_U x__in x__out. eassumption.\n      rewr in U'. assumption.\n\n  - introv GEN IH__gen MON IH__mon. intros.\n    forwards: IH__gen.\n    simpl. applys InfLet (L \\u singleton x__out).\n    + eassumption.\n    + intros y NI__y. forwards: IH__mon y x__in x__out. fsetdec.\n      assert (y <> x__out). unfold not. intros. apply NI__y. fsetdec.\n      asserts_rewrite ( subst_tm_e (e_Var_f x__in) x__out (open_e_wrt_e e2 (e_Var_f y))\n                      = open_e_wrt_e (subst_tm_e (e_Var_f x__in) x__out e2) (e_Var_f y)) in H0.\n        rewrite subst_tm_e_open_e_wrt_e. simpl. ifdec. contradiction. reflexivity. auto.\n      asserts_rewrite (subst_name x__in x__out y = y) in H0.\n        unfold subst_name. ifdec. contradiction. reflexivity.\n      eassumption.\n\n  - introv INF IH__inf GEN. intros.\n    forwards: IH__inf.\n    econstructor. eassumption. assumption.\nQed.\n\nTheorem subst_name_Env_notin_involuntive : forall (x__out x__in : termvar) (env : Env),\n    x__out \\notin Env_boundvars env\n  -> subst_name_Env x__in x__out env = env.\nProof.\n  induction env.\n  - crush.\n  - crush.\n  - crush.\n  - intros. simpl. unfold subst_name. ifdec; crush.\n  - crush.\nQed.\n\nTheorem SameShape_boundvars : forall env1 env2,\n    SameShape env1 env2\n  -> Env_boundvars env1 = Env_boundvars env2.\nProof. introv SS. induction SS; crush. Qed.\n\nTheorem Inf_rename_binding' : forall y env__in x sch e a ty env__out sch',\n    (env__in ::x x :- sch) |=                          e ▸ ⟨a⟩ ty =| (env__out ::x x :- sch')\n  -> x \\notin (Env_boundvars env__in)\n  -> (env__in ::x y :- sch) |= subst_tm_e (e_Var_f y) x e ▸ ⟨a⟩ ty =| (env__out ::x y :- sch').\nProof.\n  introv INF NIE. destruct (x == y).\n  - subst.\n    asserts_rewrite (subst_tm_e (e_Var_f y) y e = e). rewrite subst_tm_e_spec. crush.\n    assumption.\n  - forwards: proj1 Inf_Gen_Wf. unfold Inf_rename_binding__def in H. forwards: H y x. eassumption.\n    simpl in H0. unfold subst_name in H0. if_taut.\n    assert (x \\notin Env_boundvars env__out).\n      forwards: Inf_SameShape. apply INF. inverts H1. apply SameShape_boundvars in H4. crush.\n    forwards REWR1: subst_name_Env_notin_involuntive x env__in.  fsetdec. rewrite REWR1 in H0.\n    forwards REWR2: subst_name_Env_notin_involuntive x env__out. fsetdec. rewrite REWR2 in H0.\n    assumption.\nQed.\n", "meta": {"author": "rogerbosman", "repo": "hdm-fully-grounding", "sha": "master", "save_path": "github-repos/coq/rogerbosman-hdm-fully-grounding", "path": "github-repos/coq/rogerbosman-hdm-fully-grounding/hdm-fully-grounding-main/coq/Complete/InfGenRename.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.27580666368281753}}
{"text": "Require Import List Ascii.\nRequire Import Ynot.\nRequire Import IO Net FS.\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) : IO.Trace -> Prop :=\n| NilCorrect : trace local remote nil\n| ConsCorrect : forall data reply past wait, trace local remote past -> \n  (forall msg, ~In (UDP.Recd local remote msg) wait) ->\n  trace local remote \n      (WroteString stdout reply ++\n       UDP.Recd local remote reply :: wait ++ UDP.Sent local remote data :: \n       ReadLine stdin data ++ 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 waitReceive : forall (local remote : Net.SockAddr) (tr : [Trace]),\n  STsep (tr ~~ IO.traced tr)\n        (fun res:(list ascii * [Trace]) => tr ~~ \n          im :~~ (snd res) in IO.traced (UDP.Recd local remote (fst res) :: (im ++ tr))).\n  refine (fun local remote tr =>\n    {{Fix (fun im => im ~~ tr ~~ IO.traced (im ++ tr))\n        (fun _ (res:list ascii * [Trace]) => tr ~~\n           im :~~ (snd res) in IO.traced (UDP.Recd local remote (fst res) :: (im ++ tr)))\n        (fun self im => \n           reply <- UDP.recv local (inhabit_unpack2 im tr (fun im tr => im ++ tr)); \n           if sock_eq remote (fst reply) then \n             {{Return (snd reply, im)}}\n           else\n             {{self (im ~~~ (UDP.Recd local (fst reply) (snd reply)) :: im)}}\n         ) [@nil Action]%inhabited}});\n  solve [ sep fail auto\n        | sep fail auto; apply proj_inv in H; destruct H; sep fail auto ].\nQed.\n\nDefinition iter : forall (local remote : Net.SockAddr) (tr : [Trace]),\n  STsep (tr ~~ IO.traced tr * handle FS.stdin * handle FS.stdout)\n        (fun _:unit => tr ~~ Exists request :@ list ascii, Exists reply :@ list ascii, Exists q :@ Trace,\n          handle FS.stdin * handle FS.stdout *\n          IO.traced (WroteString FS.stdout reply  ++\n            (UDP.Recd local remote reply :: (q ++ UDP.Sent local remote request ::\n              (ReadLine FS.stdin request ++ tr))))).\n  refine (fun local remote tr =>\n    ln <- readline FS.stdin FS.ro_readable tr <@> _ ;\n    UDP.send local remote ln (tr ~~~ ReadLine FS.stdin ln ++ tr) <@> _ ;;\n    reply <- waitReceive local remote (tr ~~~ UDP.Sent local remote ln :: (ReadLine FS.stdin ln ++ tr)) <@> _;\n    writeline FS.stdout (fst reply) FS.wo_writeable (inhabit_unpack2 tr (snd reply) \n      (fun tr q => (UDP.Recd local remote (fst reply)) :: q ++ (UDP.Sent local remote ln ::\n        (ReadLine FS.stdin ln ++ tr)))) <@> _ ;;\n    {{Return tt}});\n  solve [ inhabiter; unpack_conc; rsep fail auto; sep fail auto; rsep 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\nDefinition client : forall (local remote : Net.SockAddr) (tr : [Trace]),\n  STsep (tr ~~ [trace local remote tr] * IO.traced tr * handle FS.stdin * handle FS.stdout)\n        (fun _:unit => tr ~~ Exists v :@ Trace, [v <> tr] * [trace local remote tr] *\n             IO.traced v * handle FS.stdin * handle FS.stdout).\n  intros. refine ({{iter local remote tr <@> (tr ~~ [trace local remote tr])}}).\n  sep fail auto.\n  intros; inhabiter. sep fail auto. assert (WroteString stdout v1 ++\n      (UDP.Recd local remote v1\n       :: v2 ++ UDP.Sent local remote v0 :: ReadLine stdin v0 ++ x) <> x).\n  unfold WroteString, ReadLine. assert ((WroteString stdout v1 ++\n   UDP.Recd local remote v1\n   :: v2 ++\n      UDP.Sent local remote v0\n      :: ReadLine stdin v0) ++ x <> x).\n  eapply list_no_cycle'. firstorder. rewrite app_ass in H3. simpl in *. rewrite app_ass in H3. simpl in *. firstorder.\n  sep fail auto.\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/UdpClient.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2757301283516518}}
{"text": "Require Export CatSem.PROP_untyped.arities.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Transparent Obligations.\nUnset Automatic Introduction.\n\n(** ** Category of representations *)\n(** we define a category of representations of a signature Sig  *)\n(** main work has been done in ./arities.v , remains to do:\n\t- identity representation morphism\n\t- composition of rep morphs\n*)\n\n(**  Morphisms of representations are just monad morphisms which verify \n    some property. It is hence sufficient to check those properties.\n    No new data is defined here. *)\n\nSection cat_of_reps.\n\nNotation \"[ T ]\" := (list T) (at level 5).\n\nVariable S : Signature.\n\n(** ** Identity  \n    identity representation morphism *)\n\nSection id.\n\nVariable P : Representation S.\n\nHint Extern 1 (CONSTR _ _ = CONSTR _ _) => apply CONSTR_eq.\n\nLemma Prod_mor_c_id V i (x : prod_mod_c _ V (sig (s:= S) i)):\n Prod_mor_c (RMonad_id P) (l:=sig (s:=S) i) (V:=V) x = x.\nProof.\n  induction x; simpl; intros; auto.\nQed.\n\nHint Rewrite Prod_mor_c_id : bla.\n\nObligation Tactic := unfold commute, commute_left, commute_right;\n     simpl; intros; autorewrite with bla; auto.\n\nHint Extern 1 (_ = _) => apply f_equal.\n\nProgram Instance Rep_Id_struct : Representation_Hom_struct (RMonad_id P).\n\nDefinition Rep_Id := Build_Representation_Hom Rep_Id_struct.\n\nEnd id.\n\nHint Extern 1 (CONSTR _ _ = CONSTR _ _) => apply CONSTR_eq.\n\n(** ** Composition\n       composition of rep homs, preparation *)\n\nSection comp_prepar.\n\nVariables P Q R : RMonad SM_po.\nVariable f : RMonad_Hom P Q.\nVariable g : RMonad_Hom Q R.\n\nLemma prod_ind_mod_mor_comp l (V : TYPE) (t : prod_mod_c _ V l) :\n    Prod_mor_c (RMonad_comp f g) t = Prod_mor_c g (Prod_mor_c f t).\nProof.\n  induction t; simpl; auto.\nQed.\n\nHint Rewrite prod_ind_mod_mor_comp : bla.\n\nLemma comp_hophop l \n       (MR : modhom_from_arity R (l)) \n       (MP : modhom_from_arity P (l))\n       (MQ : modhom_from_arity Q (l))\n       (HMf : commute f MP MQ)\n       (HMg : commute g MQ MR): \n       commute (RMonad_comp f g) MP MR.\nProof.\n  intros;\n  unfold commute, commute_left in *;\n  simpl in *; intros;\n  rerew_all;\n  autorewrite with bla; auto.\nQed.\n    \nEnd comp_prepar.\n\n(** composition of rep homs *)\n\nSection comp.\n\nVariables P Q R : Representation S.\nVariable f : Representation_Hom P Q.\nVariable g : Representation_Hom Q R.\n\nObligation Tactic := simpl; intros;\n   apply comp_hophop with (repr Q _ );\n   match goal with \n       [H:Representation_Hom _ _ |- _ ] => apply H end.\n\nProgram Instance Rep_comp_struct : \n   Representation_Hom_struct (RMonad_comp f g).\n\nDefinition Rep_Comp := Build_Representation_Hom Rep_comp_struct.\n\nEnd comp.\n\n(** ** Equality of Representation Morphisms\nrep homs are equal if their resp carriers (monad homs) are *)\n\nSection Req_equiv.\n\nVariables P R : Representation S.\n\nLtac equiv := match goal with \n     | [|- Reflexive _ ] => unfold Reflexive; intro;\n                            apply Equivalence_Reflexive\n     | [|- Symmetric _] => unfold Symmetric; do 2 intro;\n                            apply Equivalence_Symmetric\n     | [|- Transitive _ ] => unfold Transitive; do 3 intro;\n                             apply Equivalence_Transitive end.\n\nExisting Instance RMonad_Hom_oid.\n\nLemma eq_Rep_equiv : \n   @Equivalence (Representation_Hom P R) \n     (fun a c => repr_hom_c a == repr_hom_c c).\nProof.\n  constructor; equiv.\nQed.\n\nDefinition eq_Rep_oid := Build_Setoid (eq_Rep_equiv).\n\nEnd Req_equiv.\n\nExisting Instance RMONAD_struct.\n\nObligation Tactic := simpl; intros; try unf_Proper;\n        simpl; intros; \n   repeat match goal with [H:_ |-_]=>rewrite H end;\n   auto.\n\n(** ** Category of Representations *)\n\nProgram Instance REP_struct : \n         Cat_struct (@Representation_Hom S) := {\n  mor_oid a c := eq_Rep_oid a c;\n  id a := Rep_Id a;\n  comp P Q R f g := Rep_Comp f g }.\n\nDefinition REP := Build_Cat REP_struct.\n\nEnd cat_of_reps.\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/PROP_untyped/representations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.27573012226707305}}
{"text": "Require Import Coq.Classes.Morphisms.\nRequire Import Coq.Relations.Relations.\nRequire Import ExtLib.Core.RelDec.\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.Tactics.\nRequire Import MirrorCore.ExprI.\nRequire Import MirrorCore.SubstI.\nRequire Import MirrorCore.RTac.Core.\nRequire Import MirrorCore.RTac.CoreK.\n\nRequire Import MirrorCore.Util.Quant.\nRequire Import MirrorCore.Util.Forwardy.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nSection spec_lemmas.\n  Context {typ : Set}.\n  Context {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 {ExprUVar_expr : ExprUVar expr}.\n  Context {ExprUVarOk_expr : ExprUVarOk ExprUVar_expr}.\n\n  Local Hint Constructors WellFormed_ctx_subst.\n  Lemma WellFormed_ctx_subst_fromAll\n  : forall t (c : Ctx typ expr) (cs : ctx_subst (CAll c t)),\n      WellFormed_ctx_subst cs ->\n      WellFormed_ctx_subst (fromAll cs).\n  Proof.\n    intros.\n    refine match H in @WellFormed_ctx_subst _ _ _ _ C cs\n                 return match C as C return ctx_subst C -> Prop with\n                          | CAll _ _ => fun x => WellFormed_ctx_subst (fromAll x)\n                          | _ => fun _ => True\n                        end cs\n           with\n             | @WF_AllSubst _ _ _ _ _ _ _ pf => pf\n             | _ => I\n           end.\n  Qed.\n\n  Lemma WellFormed_ctx_subst_fromHyp\n  : forall t (c : Ctx typ expr) (cs : ctx_subst (CHyp c t)),\n      WellFormed_ctx_subst cs ->\n      WellFormed_ctx_subst (fromHyp cs).\n  Proof.\n    intros.\n    refine match H in @WellFormed_ctx_subst _ _ _ _ C cs\n                 return match C as C return ctx_subst C -> Prop with\n                          | CHyp _ _ => fun x => WellFormed_ctx_subst (fromHyp x)\n                          | _ => fun _ => True\n                        end cs\n           with\n             | @WF_HypSubst _ _ _ _ _ _ _ pf => pf\n             | _ => I\n           end.\n  Qed.\n  Local Hint Resolve WellFormed_ctx_subst_fromAll WellFormed_ctx_subst_fromHyp.\n\n  Lemma pctxD_remembers {c s l a sD pD}\n  : forall (WFp : WellFormed_bimap (length (getUVars c)) (length l) (length (getVars c)) a),\n      WellFormed_ctx_subst s ->\n    pctxD s = Some sD ->\n    amap_substD (getUVars c ++ l) (getVars c) a = Some pD ->\n    exists sD',\n      pctxD (remembers s l a) = Some sD' /\\\n      forall us vs (P : exprT _ _ Prop),\n        (sD (fun us vs =>\n               forall us', pD (hlist_app us us') vs -> P (hlist_app us us') vs) us vs <->\n         sD' P us vs).\n  Proof.\n    simpl. intros.\n    rewrite H0.\n    destruct (pctxD_substD H H0) as [ ? [ ? ? ] ].\n    eapply amap_instantiates_substD\n      with (f := fun u => ctx_lookup u s)\n           (C := fun (P : exprT (getUVars c ++ l) (getVars c) Prop) =>\n                   forall us vs, sD (fun us vs => x us vs -> forall us', P (hlist_app us us') vs) us vs)\n           in H1; try eassumption.\n    forward_reason.\n    rewrite H1.\n    eexists; split; eauto.\n    simpl. intros.\n    split.\n    { eapply Ap_pctxD; eauto.\n      generalize (H3 us vs); clear H3.\n      eapply Ap_pctxD; eauto.\n      generalize (H4 us vs); clear H4.\n      eapply Ap_pctxD; eauto.\n      eapply Pure_pctxD; eauto.\n      intros.\n      eapply _forall_sem; intros.\n      eapply H5; clear H5.\n      eapply H3; eauto. }\n    { eapply Ap_pctxD; eauto.\n      generalize (H3 us vs); clear H3.\n      eapply Ap_pctxD; eauto.\n      generalize (H4 us vs); clear H4.\n      eapply Ap_pctxD; eauto.\n      eapply Pure_pctxD; eauto.\n      intros.\n      eapply _forall_sem with (x := us') in H5; intros.\n      eapply H5; clear H5.\n      eapply H3; eauto. }\n    { clear - H0. constructor.\n      { intros. eapply Pure_pctxD; eauto. }\n      { intros. generalize (H1 us vs).\n        eapply Ap_pctxD; eauto.\n        generalize (H us vs).\n        eapply Ap_pctxD; eauto.\n        eapply Pure_pctxD; eauto. } }\n    { red. intros.\n      destruct (pctxD_substD H H0) as [ ? [ ? ? ] ].\n      eapply ctx_substD_lookup in H4; eauto.\n      forward_reason.\n      eapply exprD_weakenU with (tus' := l) in H8; eauto.\n      destruct H8 as [ ? [ ? ? ] ].\n      eapply nth_error_get_hlist_nth_weaken in H4.\n      revert H4. instantiate (1 := l).\n      simpl. destruct 1 as [ ? [ ? ? ] ].\n      rewrite H5 in H4. inv_all. subst.\n      eexists; split; eauto.\n      intros us vs.\n      generalize (H7 us vs); clear H7.\n      eapply Ap_pctxD; eauto.\n      eapply Pure_pctxD; eauto. intros.\n      rewrite <- H11; clear H11; eauto.\n      rewrite <- H10; clear H10.\n      eauto. }\n  Qed.\n\n  Lemma _exists_impl : forall l (P Q : hlist typD l -> Prop),\n                         (forall x, P x -> Q x) ->\n                         _exists _ l P -> _exists _ l Q.\n  Proof using.\n    intros.\n    eapply _exists_sem in H0. eapply _exists_sem.\n    destruct H0. exists x. auto.\n  Qed.\n\n  Lemma Ap_impls : forall (Ps : list Prop) (P Q : Prop),\n                     _impls Ps (P -> Q) ->\n                     _impls Ps P -> _impls Ps Q.\n  Proof using.\n    induction Ps; simpl; eauto.\n  Qed.\n\n  Opaque remembers.\n\n  Lemma GoalImplies_GConj_\n  : forall c (cs : ctx_subst c) l r,\n      GoalImplies (cs, GConj l r) (cs, GConj_ l r).\n  Proof.\n    simpl; intros.\n    split; auto.\n    split.\n    { destruct l; destruct r; inversion H; try constructor; eauto;\n      try constructor. }\n    { forward.\n      assert (   (l = GSolved /\\ r = GConj l r)\n                 \\/ (r = GSolved /\\ l = GConj l r)\n                 \\/ (GConj_ l r = GConj l r)).\n      { clear. destruct l; destruct r; simpl;\n               try solve [ left; eauto | right; left; eauto | right; right; congruence ]. }\n      destruct H3 as [ ? | [ ? | ? ] ]; forward_reason.\n      { subst l. destruct H4. simpl.\n        rewrite H2.\n        split; [ reflexivity | ].\n        intros.\n        eapply Pure_pctxD; eauto. intros; tauto. }\n      { destruct H4; subst. simpl.\n        rewrite H2.\n        split; [ reflexivity | ].\n        intros.\n        eapply Pure_pctxD; eauto. intros; tauto. }\n      { destruct H3.\n        simpl in *. forward.\n        split; [ reflexivity | ].\n        inv_all; subst.\n        intros.\n        eapply Pure_pctxD; eauto. } }\n  Qed.\n\n  Lemma GoalImplies_GConj\n  : forall c (cs : ctx_subst c) l r,\n      GoalImplies (cs, GConj_ l r) (cs, GConj l r).\n  Proof.\n    simpl; intros.\n    split; auto.\n    split.\n    { inversion H; subst.\n      destruct l; destruct r; simpl; auto; try constructor; auto. }\n    { forward.\n      assert (   (l = GSolved /\\ r = GConj l r)\n                 \\/ (r = GSolved /\\ l = GConj l r)\n                 \\/ (GConj_ l r = GConj l r)).\n      { clear. destruct l; destruct r; simpl;\n               try solve [ left; eauto | right; left; eauto | right; right; congruence ]. }\n      destruct H5 as [ ? | [ ? | ? ] ]; forward_reason.\n      { subst l. destruct H6. simpl.\n        rewrite H3.\n        split; [ reflexivity | ].\n        intros.\n        eapply Pure_pctxD; eauto. inv_all; subst. intros; tauto. }\n      { destruct H6; subst. simpl.\n        rewrite H2.\n        split; [ reflexivity | ].\n        intros.\n        eapply Pure_pctxD; eauto. inv_all; subst. intros; tauto. }\n      { destruct H5.\n        simpl in *. forward.\n        split; [ reflexivity | ].\n        inv_all; subst.\n        intros.\n        eapply Pure_pctxD; eauto. } }\n  Qed.\n\n  Lemma rtac_spec_All_More\n    : forall ctx s t g c g',\n      rtac_spec (AllSubst (t:=t) s) g (More_ c g') ->\n      rtac_spec (ctx:=ctx) s (GAll t g) (More_ (fromAll c) (GAll t g')).\n  Proof using.\n    unfold rtac_spec; simpl; intros.\n    inv_all. forward_reason.\n    forward_reason.\n    rewrite (ctx_subst_eta c) in *.\n    simpl in *; inv_all; subst.\n    split; auto. split; auto.\n    { constructor. auto. }\n    forward. inv_all; subst.\n    destruct H7. inv_all. subst.\n    split; auto.\n    intros. gather_facts.\n    eapply Pure_pctxD; eauto.\n  Qed.\n\n  Lemma rtac_spec_All_Solved\n    : forall ctx s t g c,\n      rtac_spec (AllSubst (t:=t) s) g (Solved c) ->\n      rtac_spec (ctx:=ctx) s (GAll t g) (Solved (fromAll c)).\n  Proof using RTypeOk_typ.\n    intros.\n    eapply Proper_rtac_spec.\n    3: eapply rtac_spec_All_More.\n    - reflexivity.\n    - change (Solved (fromAll c)) with (More (fromAll c) GSolved).\n      eapply More_More_.\n      instantiate (1 := GSolved).\n      red. split.\n      { split; constructor. constructor. }\n      { simpl.\n        constructor. constructor; auto. }\n    - eapply Proper_rtac_spec.\n      + reflexivity.\n      + symmetry. eapply More_More_. reflexivity.\n      + apply H.\n  Qed.\n\n  Lemma rtac_spec_GConj_Solved\n    : forall ctx c s g1 g2 r,\n      rtac_spec s g1 (Solved (c:=ctx) c) ->\n      rtac_spec c g2 r ->\n      rtac_spec s (GConj_ g1 g2) r.\n  Proof.\n    unfold rtac_spec. intros.\n    destruct r; auto;\n    intros; inv_all; forward_reason.\n    { split; auto.\n      split; auto.\n      simpl.\n      forward.\n      forward_reason.\n      split.\n      { etransitivity; eauto. }\n      intros. gather_facts.\n      eapply pctxD_SubstMorphism; eauto.\n      gather_facts.\n      eapply Pure_pctxD; eauto. }\n    { split; auto.\n      simpl. forward; forward_reason.\n      split.\n      { etransitivity; eauto. }\n      intros. gather_facts.\n      eapply pctxD_SubstMorphism; eauto.\n      gather_facts.\n      eapply Pure_pctxD; eauto. }\n  Qed.\n  Lemma rtac_spec_GConj_More_\n    : forall ctx c s g1 g2 r g,\n      rtac_spec s g1 (More_ (c:=ctx) c g) ->\n      rtac_spec c g2 r ->\n      rtac_spec c (GConj_ g g2) r ->\n      rtac_spec s (GConj_ g1 g2) r.\n  Proof.\n    unfold rtac_spec. intros.\n    destruct r; auto;\n    intros; inv_all; forward_reason.\n    { split; auto.\n      split; auto.\n      simpl.\n      destruct H1; auto.\n      { constructor; eauto. }\n      simpl in H9. destruct H9.\n      forward.\n      forward_reason.\n      split.\n      { etransitivity; eauto. }\n      intros. gather_facts.\n      eapply pctxD_SubstMorphism; eauto.\n      gather_facts.\n      eapply Pure_pctxD; eauto.\n      tauto. }\n    { split; auto.\n      simpl.\n      destruct H1; eauto.\n      { constructor; auto. }\n      simpl in *.\n      forward; forward_reason.\n      split.\n      { etransitivity; eauto. }\n      intros. gather_facts.\n      eapply pctxD_SubstMorphism; eauto.\n      gather_facts.\n      eapply Pure_pctxD; eauto. tauto. }\n  Qed.\n\n  Lemma rtac_spec_Hyp_Solved\n    : forall e (ctx : Ctx typ expr) (s : ctx_subst ctx)\n             (c : ctx_subst (CHyp ctx e)) (g : Goal typ expr),\n      rtac_spec (HypSubst s) g (Solved c) ->\n      rtac_spec s (GHyp e g) (Solved (fromHyp c)).\n  Proof using.\n    simpl. intros.\n    inv_all. destruct H; auto.\n    split; auto.\n    forward.\n    destruct H6. inv_all; subst.\n    simpl in *.\n    forward. inv_all. subst.\n    split; auto.\n  Qed.\n\n  Lemma rtac_spec_Hyp_More\n    : forall (g0 g : Goal typ expr) (e : expr) (ctx : Ctx typ expr)\n             (s : ctx_subst ctx) (c : ctx_subst (CHyp ctx e)),\n      rtac_spec (HypSubst s) g (More_ c g0) ->\n      rtac_spec s (GHyp e g) (More_ (fromHyp c) (GHyp e g0)).\n  Proof using.\n    simpl. intros. inv_all.\n    forward_reason.\n    split; auto.\n    split.\n    { constructor. auto. }\n    forward. forward_reason.\n    inv_all. subst.\n    simpl in *. forward. inv_all; subst.\n    split; auto.\n    intros. gather_facts.\n    eapply Pure_pctxD; eauto.\n  Qed.\n\n  Lemma rtac_spec_Conj_Solved\n    : forall ctx s g1 g2 c r,\n      rtac_spec s g1 (Solved c) ->\n      rtac_spec c g2 r ->\n      rtac_spec (ctx:=ctx) s (GConj_ g1 g2) r.\n  Proof using.\n    simpl.\n    destruct r; simpl; auto; intros; inv_all; forward_reason.\n    { split; auto. split; auto.\n      forward. forward_reason.\n      split.\n      { etransitivity; eauto. }\n      { intros; gather_facts.\n        eapply pctxD_SubstMorphism; eauto.\n        gather_facts.\n        eapply Pure_pctxD; eauto. } }\n    { split; auto.\n      forward. forward_reason.\n      split.\n      { etransitivity; eauto. }\n      { intros; gather_facts.\n        eapply pctxD_SubstMorphism; eauto.\n        gather_facts.\n        eapply Pure_pctxD; eauto. } }\n  Qed.\n\n  Lemma rtac_spec_GConj_More_Solved\n    : forall ctx s s' s'' g1 g2 g1',\n      rtac_spec s g1 (More_ s' g1') ->\n      rtac_spec s' g2 (Solved s'') ->\n      rtac_spec (ctx:=ctx) s (GConj_ g1 g2) (More_ s'' g1').\n  Proof using.\n    simpl.\n    intros; inv_all. forward_reason.\n    split; auto. split; auto.\n    forward. forward_reason.\n    split.\n    { etransitivity; eauto. }\n    intros; gather_facts.\n    eapply pctxD_SubstMorphism; eauto.\n    gather_facts.\n    eapply Pure_pctxD; eauto.\n  Qed.\n\n  Lemma rtac_spec_GConj_More_More\n    : forall ctx s s' s'' g1 g2 g1' g2',\n      rtac_spec s g1 (More_ s' g1') ->\n      rtac_spec s' g2 (More_ s'' g2') ->\n      rtac_spec (ctx:=ctx) s (GConj_ g1 g2) (More_ s'' (GConj_ g1' g2')).\n  Proof using.\n    simpl.\n    intros; inv_all. forward_reason.\n    split; auto.\n    split.\n    { constructor; auto. }\n    forward. forward_reason.\n    split.\n    { etransitivity; eauto. }\n    intros; gather_facts.\n    eapply pctxD_SubstMorphism; eauto.\n    gather_facts.\n    eapply Pure_pctxD; eauto.\n    tauto.\n  Qed.\n\n  Lemma rtac_spec_GSolved_Solved\n    : forall ctx s, rtac_spec (ctx:=ctx) s GSolved (Solved s).\n  Proof using.\n    simpl.\n    intros. split; auto.\n    forward. split. reflexivity.\n    eapply Pure_pctxD; eauto.\n  Qed.\n\n  Lemma ExprTApplicative_with_extra\n    : forall (l : list typ) (ctx : Ctx typ expr) (s : ctx_subst ctx)\n             (e : exprT (getUVars ctx) (getVars ctx) Prop ->\n                  exprT (getAmbientUVars ctx) (getAmbientVars ctx) Prop),\n      pctxD s = Some e ->\n      CtxLogic.ExprTApplicative\n        (fun P : exprT (getUVars ctx ++ l) (getVars ctx) Prop =>\n           forall (us : hlist typD (getAmbientUVars ctx))\n                  (vs : hlist typD (getAmbientVars ctx)),\n             e\n               (fun (us0 : hlist typD (getUVars ctx))\n                    (vs0 : hlist typD (getVars ctx)) =>\n                  forall z : hlist typD l, P (hlist_app us0 z) vs0) us vs).\n  Proof using.\n    constructor.\n    { intros. eapply Pure_pctxD; eauto. }\n    { intros. gather_facts. eapply Pure_pctxD; eauto. }\n  Qed.\n\n  Lemma rtac_spec_remembers_full_Solved\n    : forall (l : list typ)\n             (a : amap expr)\n             (g : Goal typ expr)\n             (ctx : Ctx typ expr)\n             (s : ctx_subst ctx)\n             (c : ctx_subst (CExs ctx l)),\n      amap_is_full (length l) (fst (fromExs c)) = true ->\n      rtac_spec (remembers s l a) g (Solved c) ->\n      rtac_spec s (GExs l a g) (Solved (snd (fromExs c))).\n  Proof using RTypeOk_typ ExprOk_expr.\n    unfold rtac_spec. simpl.\n    intros. inv_all.\n    Transparent remembers. unfold remembers in *. Opaque remembers.\n    forward_reason.\n    assert (WellFormed_ctx_subst\n              (ExsSubst (ts:=l) s (amap_instantiate (fun u : nat => ctx_lookup u s) a))).\n    { edestruct remembers_sound; eauto with typeclass_instances. }\n    forward_reason. clear H1.\n    rewrite (ctx_subst_eta c) in *; simpl in *.\n    generalize dependent (snd (fromExs c)).\n    generalize dependent (fst (fromExs c)).\n    intros. inv_all.\n    split; auto.\n    forward. inv_all. subst.\n    assert (sem_preserves_if_ho\n              (fun P : exprT (getUVars ctx ++ l) (getVars ctx) Prop =>\n                 forall (us : hlist typD (getAmbientUVars ctx))\n                        (vs : hlist typD (getAmbientVars ctx)),\n                   e (fun us vs => forall z, P (hlist_app us z) vs) us vs) (fun u : uvar => subst_lookup u s)).\n    { clear H7. red.\n      intros.\n      generalize H0.\n      eapply pctxD_substD in H0; try eassumption.\n      destruct H0 as [ ? [ ? ? ] ].\n      eapply substD_lookup\n      with (SubstOk := @SubstOk_ctx_subst _ _ _ _ _ _ _) in H7;\n        try eassumption.\n      forward_reason.\n      eapply nth_error_get_hlist_nth_weaken with (ls' := l) in H7.\n      simpl in H7. rewrite H9 in H7.\n      forward_reason. inv_all. subst.\n      eapply exprD_weakenU with (tus' := l) in H11; eauto.\n      destruct H11 as [ ? [ ? ? ] ].\n      eexists; split; eauto.\n      intros. gather_facts. eapply Pure_pctxD; eauto.\n      intros. rewrite <- H13; clear H13; eauto.\n      rewrite <- H11; clear H11.\n      eauto.\n      Unshelve. eassumption. eassumption. }\n    generalize (fun AC => @amap_instantiates_substD _ _ _ _ _ (getUVars ctx ++ l) (getVars ctx) _ AC (fun u : nat => ctx_lookup u s) _ _ _ _ _ H4 H8 H9).\n    clear H9. destruct 1 as [ ? [ ? ? ] ].\n    { clear - H0.\n      revert H0. revert e; revert s; revert ctx; revert l.\n      eapply ExprTApplicative_with_extra. }\n    rewrite H9 in *.\n    forward. inv_all; subst.\n    forward_reason. inv_all; subst.\n    split; eauto.\n    intros. gather_facts.\n    rewrite H0 in *. rewrite H9 in *.\n    rewrite H12 in *. rewrite H7 in *.\n    gather_facts.\n    eapply subst_getInstantiation in H7;\n      eauto using WellFormed_entry_WellFormed_pre_entry.\n    destruct H7.\n    eapply pctxD_SubstMorphism; eauto.\n    gather_facts.\n    eapply Pure_pctxD; eauto.\n    clear - H7.\n    intros. specialize (H7 us vs).\n    eapply _exists_sem.\n    exists (hlist_map\n              (fun (t : typ) (x0 : exprT (getUVars ctx) (getVars ctx) (typD t)) =>\n                 x0 us vs) x2).\n    rewrite _forall_sem in H1.\n    split.\n    { eapply H. eapply H0. eapply H7. }\n    { eapply H1. eapply H7. }\n  Qed.\n\n  Lemma rtac_spec_Exs_More\n    : forall ctx (s : ctx_subst ctx) l a g c g',\n      rtac_spec (remembers s l a) g (More_ c g') ->\n      rtac_spec s (GExs l a g)\n                (More_ (snd (fromExs c)) (GExs l (fst (fromExs c)) g')).\n  Proof using RTypeOk_typ ExprOk_expr.\n    unfold rtac_spec.\n    Transparent remembers. unfold remembers. Opaque remembers.\n    intros. inv_all.\n    forward_reason.\n    destruct H.\n    { edestruct remembers_sound; eauto with typeclass_instances. }\n    simpl in *.\n    rewrite (ctx_subst_eta c) in *. simpl in *.\n    generalize dependent (snd (fromExs c)).\n    generalize dependent (fst (fromExs c)).\n    clear c. intros; inv_all; subst.\n    split; auto.\n    forward_reason.\n    split.\n    { constructor; eauto using WellFormed_entry_WellFormed_pre_entry. }\n    forward. inv_all. subst.\n    assert (sem_preserves_if_ho\n              (fun P : exprT (getUVars ctx ++ l) (getVars ctx) Prop =>\n                 forall (us : hlist typD (getAmbientUVars ctx))\n                        (vs : hlist typD (getAmbientVars ctx)),\n                   e (fun us vs => forall z, P (hlist_app us z) vs) us vs) (fun u : uvar => subst_lookup u s)).\n    { clear H7. red.\n      intros.\n      generalize H0.\n      eapply pctxD_substD in H0; try eassumption.\n      destruct H0 as [ ? [ ? ? ] ].\n      eapply substD_lookup\n      with (SubstOk := @SubstOk_ctx_subst _ _ _ _ _ _ _) in H7;\n        try eassumption.\n      forward_reason.\n      eapply nth_error_get_hlist_nth_weaken with (ls' := l) in H7.\n      simpl in H7. rewrite H9 in H7.\n      forward_reason. inv_all. subst.\n      eapply exprD_weakenU with (tus' := l) in H11; eauto.\n      destruct H11 as [ ? [ ? ? ] ].\n      eexists; split; eauto.\n      intros. gather_facts. eapply Pure_pctxD; eauto.\n      intros. rewrite <- H13; clear H13; eauto.\n      rewrite <- H11; clear H11.\n      eauto.\n      Unshelve. eassumption. eassumption. }\n    generalize (fun AC => @amap_instantiates_substD _ _ _ _ _ (getUVars ctx ++ l) (getVars ctx) _ AC (fun u : nat => ctx_lookup u s) _ _ _ _ _ H3 H8 H9).\n    clear H9. destruct 1 as [ ? [ ? ? ] ].\n    { clear - H0.\n      revert H0. revert e; revert s; revert ctx; revert l.\n      eapply ExprTApplicative_with_extra. }\n    rewrite H9 in *.\n    forward. inv_all; subst.\n    forward_reason. inv_all; subst.\n    split; eauto.\n    intros. gather_facts.\n    rewrite H0 in *. rewrite H9 in *.\n    rewrite H13 in *. rewrite H7 in *.\n    gather_facts.\n    destruct H7.\n    eapply pctxD_SubstMorphism; eauto.\n    gather_facts.\n    eapply Pure_pctxD; eauto.\n    clear.\n    intros.\n    revert H2. eapply _exists_impl.\n    rewrite _forall_sem in H1.\n    intros. specialize (H x0).\n    specialize (H0 x0).\n    specialize (H1 x0).\n    tauto.\n  Qed.\n\nEnd spec_lemmas.\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/SpecLemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.275730122267073}}
{"text": "Require Import Raft.\nRequire Import CommonDefinitions.\nRequire Import TraceUtil.\n\nSection OutputCorrect.\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  Class output_correct_interface : Prop :=\n    {\n      output_correct_invariant :\n        forall client id out failed net tr,\n          step_f_star step_f_init (failed, net) tr ->\n          in_output_trace client id out tr ->\n          output_correct client id out (applied_entries (nwState net))\n    }.\nEnd OutputCorrect.", "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/OutputCorrectInterface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.27568496520172214}}
{"text": "Require Export LL.FOLL.Dyadic.StructuralRules.\n\nExport LLNotations.\nSet Implicit Arguments.\n\nLtac solvell2 :=\n try\n match goal with\n | [ H: LL2N _ ?B ?L |- LL2S ?B ?L] => apply LL2NtoLL2S in H;auto\n end. \n   \nLtac llExact H :=\n  let G:= type of H in\n  match G with\n  | (LL2N ?x ?Gamma ?Delta) =>\n    match goal with\n    | [ |- LL2N ?x ?Gamma' ?Delta'] =>\n      eapply @LL2N_compat with (B1:=Gamma) (L1:=Delta); try perm\n    end \n  end;auto.\n \nLtac llExact' H :=\n  let G:= type of H in\n  match G with\n  | (LL2S ?Gamma ?Delta) =>\n    match goal with\n    | [ |- LL2S ?Gamma' ?Delta'] =>\n      eapply @LL2S_compat with (B1:=Gamma) (L1:=Delta); try perm\n    end \n  end;auto.\n\n\nLtac LLExact H := \n  match (type of H) with\n  | LL2S _ _  =>  llExact' H\n  | LL2N _ _ _ => llExact H\n  end.\n\n  Definition CutW {OL:OLSig} (w: nat) :=  \n    forall i j C A M N B, \n    complexity C  < w ->\n      (LL2 i |-- B; C::M -> LL2 j |-- B; (dual C)::N -> LL2 |-- B; M ++ N) /\\\n      (S (complexity A) = complexity C ->\n       LL2 i |-- A::B ; M -> LL2 j |-- B; (! dual A)::N -> LL2 |-- B; M++N). \n\n  Definition CutH {OL:OLSig} (w m: nat) :=  \n    forall i j C A M N B, \n   i + j < m ->\n    complexity C = w ->\n      (LL2 i |-- B; C::M -> LL2 j |-- B; (dual C)::N -> LL2 |-- B; M ++ N) /\\\n      (S (complexity A) = complexity C ->\n      LL2 i |-- A::B ; M -> LL2 j |-- B; (! dual A)::N -> LL2 |-- B; M++N). \n\n\nLtac dualSimpl :=\n match goal with\n | H: ?F = ?C^ |- _ => \n    apply dualSubst in H;subst\n | H: ?C^ = ?F |- _ => \n   symmetry in H; apply dualSubst in H;subst    \n | H: context [((?C)^)^] |- _ => \n    rewrite <- ng_involutive in H  \nend;auto.    \n\n\nLtac putFirst H TT :=\nmatch type of H with\n| LL2N ?x ?BB (?FF::TT::?XX) => \n    eapply LL2N_compat with \n     (B2:=BB) (L2:= TT::FF::XX) in H;try perm\n | LL2N ?x ?BB (?FF::?GG::TT::?XX) => \n   eapply LL2N_compat with \n     (B2:=BB) (L2:= TT::FF::GG::XX) in H;try perm\nend.\n\n Ltac applyCutH := \n  match goal with\n  | [ H: CutH _ _ |- LL2N ?x (?FF::?BX) _ -> \n         LL2N ?y ?BX _ -> \n         LL2S _ _ ] => eapply H with (m := x + y) (C:=Quest FF);sauto\n  | [ H: CutH _ _ |- LL2N ?x _ _ -> \n         LL2N ?y _ _ -> \n         LL2S _ _ ] => eapply H ;sauto\n  | _ => idtac end.\n\n\nLtac applyCutW := \n  match goal with\n | [ H: CutW _ |- LL2N ?x (?FF::?BX) _ -> \n         LL2N ?y ?BX _ -> \n         LL2S _ _ ] => eapply @H with (m := x + y) (C:=Quest FF);sauto\n \n  | [ H: CutW _ |- LL2N _ _ (?CF::_) -> \n         LL2N _ _ _ -> \n         LL2S _ _ ] => eapply H ;sauto\n  | _ => idtac end.\n  \nTactic Notation \"cutH\" constr(P1) constr(P2) :=\n   let tP1 := type of P1 in\n   let H' := fresh \"HCUT\" in\n   match tP1 with\n   | LL2N ?x ?BX (?CF::?CX) => let tP2 := type of P2 in\n                    match tP2 with \n                    | LL2N ?y ?BX (_::?CY) =>  \n                           assert(H': tP1 -> tP2 -> LL2S BX (CX++CY));\n                           applyCutH; try rewrite app_nil_r in H' \n                    | _ => idtac \"type of \" P2 \" is \" tP2 end\n   | LL2N ?x ?BX (?NF::?CF::?CX2) => let tP2 := type of P2 in\n                    match tP2 with \n                    | LL2N ?y ?BX (_::?CY) =>  \n                           assert(LL2N x BX (CF::(NF++CX2)) -> tP2 -> LL2S BX ((NF::CX2)++CY));\n                           applyCutH; try rewrite app_nil_r in H' \n                    | _ => idtac \"type of \" P2 \" is \" tP2 end\n\n   | _ => idtac \"type of \" P1 \" is \" tP1 end.\n  \nTactic Notation \"cutW\" constr(P1) constr(P2) :=\n   let tP1 := type of P1 in\n   let H' := fresh \"WCUT\" in\n   match tP1 with\n   | LL2N ?x ?BX (?CF::?CX) => let tP2 := type of P2 in\n                    match tP2 with \n                    | LL2N ?y ?BX (_::?CY) =>  \n                           assert(H': tP1 -> tP2 -> LL2S BX (CX++CY));\n                           applyCutW; try rewrite app_nil_r in H'\n                    | _ => idtac \"type of \" P2 \" is \" tP2 end\n   | _ => idtac \"type of \" P1 \" is \" tP1 end.\n\nTactic Notation \"cutH'\" constr(P1) constr(P2) :=\n   let tP1 := type of P1 in\n   let H' := fresh \"HCUT\" in\n   match tP1 with\n   | LL2N ?x (?CF::?BX) (?CX) => let tP2 := type of P2 in\n                    match tP2 with \n                    | LL2N ?y ?BX (_::?CY) =>  \n                           assert(H': tP1 -> tP2 -> LL2S BX (CX++CY));\n                           applyCutH; try rewrite app_nil_r in H'\n                    | _ => idtac \"type of \" P2 \" is \" tP2 end\n   | _ => idtac \"type of \" P1 \" is \" tP1 end.\n  \nTactic Notation \"cutW'\" constr(P1) constr(P2) :=\n   let tP1 := type of P1 in\n   let H' := fresh \"WCUT\" in\n   match tP1 with\n   | LL2N ?x (?CF::?BX) ?CX => let tP2 := type of P2 in\n                    match tP2 with \n                    | LL2N ?y ?BX (_::?CY) =>  \n                           assert(H': tP1 -> tP2 -> LL2S BX (CX++CY));\n                           applyCutW; try rewrite app_nil_r in H'\n                    | _ => idtac \"type of \" P2 \" is \" tP2 end\n   | _ => idtac \"type of \" P1 \" is \" tP1 end.    \n\n\n     \n", "meta": {"author": "brunofx86", "repo": "LLFramework", "sha": "d12e01875912ef52397d8cd899b7fb0e26977ac5", "save_path": "github-repos/coq/brunofx86-LLFramework", "path": "github-repos/coq/brunofx86-LLFramework/LLFramework-d12e01875912ef52397d8cd899b7fb0e26977ac5/FOLL/Dyadic/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.27568496520172214}}
{"text": "From Perennial.program_proof.mvcc Require Import\n     wrbuf_prelude wrbuf_repr wrbuf_sort_ents_by_key\n     index_proof\n     tuple_repr tuple_own tuple_free tuple_write_lock.\n\nSection heap.\nContext `{!heapGS Σ, !mvcc_ghostG Σ}.\n\n(*********************************************************************)\n(* func (wrbuf *WrBuf) OpenTuples(tid uint64, idx *index.Index) bool *)\n(*********************************************************************)\nTheorem wp_wrbuf__OpenTuples wrbuf (tid : u64) (idx : loc) sid mods γ :\n  is_index idx γ -∗\n  {{{ own_wrbuf_xtpls wrbuf mods ∗ active_tid γ tid sid }}}\n    WrBuf__OpenTuples #wrbuf #tid #idx\n  {{{ (ok : bool), RET #ok;\n      active_tid γ tid sid ∗\n      if ok\n      then ∃ (tpls : gmap u64 loc), own_wrbuf wrbuf mods tpls ∗ own_tuples_locked (int.nat tid) tpls γ\n      else own_wrbuf_xtpls wrbuf mods\n  }}}.\nProof.\n  iIntros \"#Hidx !>\" (Φ) \"[Hwrbuf Hactive] HΦ\".\n  wp_call.\n  \n  (***********************************************************)\n  (* wrbuf.sortEntsByKey()                                   *)\n  (***********************************************************)\n  wp_apply (wp_wrbuf__sortEntsByKey with \"Hwrbuf\").\n  iIntros \"Hwrbuf\".\n  wp_pures.\n  \n  (***********************************************************)\n  (* ents := wrbuf.ents                                      *)\n  (* var pos uint64 = 0                                      *)\n  (* for pos < uint64(len(ents)) {                           *)\n  (*     ent := ents[pos]                                    *)\n  (*     tpl := idx.GetTuple(ent.key)                        *)\n  (*     ret := tpl.Own(tid)                                 *)\n  (*     if ret != common.RET_SUCCESS {                      *)\n  (*         break                                           *)\n  (*     }                                                   *)\n  (*     ents[pos] = WrEnt {                                 *)\n  (*         key : ent.key,                                  *)\n  (*         val : ent.val,                                  *)\n  (*         wr  : ent.wr,                                   *)\n  (*         tpl : tpl,                                      *)\n  (*     }                                                   *)\n  (*     pos++                                               *)\n  (* }                                                       *)\n  (***********************************************************)\n  iNamed \"Hwrbuf\".\n  (* Obtain [is_slice_small] and eq about length of [ents]. *)\n  iDestruct (is_slice_sz with \"HentsS\") as \"%HentsLen\".\n  rewrite fmap_length in HentsLen.\n  iDestruct (is_slice_small_acc with \"HentsS\") as \"[HentsS HentsC]\".\n  wp_loadField.\n  wp_pures.\n  wp_apply (wp_ref_to); first by auto.\n  iIntros (pos) \"HposR\".\n  wp_pures.\n  set P := (λ (b : bool), ∃ (n : u64) (tpls : gmap u64 loc) (ents' : list wrent),\n               let m : dbmap := list_to_map (wrent_to_key_dbval <$> ents) in\n               \"Hactive\"  ∷ active_tid γ tid sid ∗\n               \"HentsS\"   ∷ is_slice_small entsS (struct.t WrEnt) 1 (wrent_to_val <$> ents') ∗\n               \"HposR\"    ∷ pos ↦[uint64T] #n ∗\n               \"Htokens\"  ∷ ([∗ map] k ↦ _ ∈ tpls, mods_token γ k (int.nat tid)) ∗\n               \"#HtplsRP\" ∷ ([∗ map] k ↦ t ∈ tpls, is_tuple t k γ) ∗\n               \"%Htpls\"   ∷ ⌜tpls = list_to_map (wrent_to_key_tpl <$> (take (int.nat n) ents'))⌝ ∗\n               \"%Hm\"      ∷ ⌜m = list_to_map (wrent_to_key_dbval <$> ents')⌝ ∗\n               \"%Hlen\"    ∷ ⌜length ents = length ents'⌝ ∗\n               \"%HNoDup\"  ∷ ⌜NoDup ents'.*1.*1.*1⌝\n           )%I.\n  wp_apply (wp_forBreak_cond P with \"[] [Hactive HentsS HposR]\").\n  { (* Loop body. *)\n    clear Φ HNoDup.\n    iIntros (Φ) \"!> HP HΦ\".\n    iNamed \"HP\".\n    wp_load.\n    wp_apply (wp_slice_len).\n    wp_if_destruct; last first.\n    { (* Loop condition. *)\n      iApply \"HΦ\".\n      subst P. simpl.\n      eauto 10 with iFrame.\n    }\n    wp_load.\n    destruct (list_lookup_lt _ (wrent_to_val <$> ents') (int.nat n)) as [ent Hlookup].\n    { rewrite fmap_length. word. }\n    wp_apply (wp_SliceGet with \"[$HentsS]\"); first done.\n    iIntros \"[HentsS %Hty]\".\n    wp_pures.\n    apply val_to_wrent_with_val_ty in Hty as (k & v & w & t & Hent).\n    subst ent.\n    wp_pures.\n    wp_apply (wp_index__GetTuple with \"Hidx\").\n    iIntros (tpl) \"#Htpl\".\n    wp_pures.\n    wp_apply (wp_tuple__Own with \"Htpl Hactive\").\n    iIntros (ret) \"[Hactive HpostOwn]\".\n    wp_pures.\n    unfold post_tuple__Own.\n    wp_if_destruct.\n    { (* Early return due to failed [tuple__Own]. *)\n      iApply \"HΦ\".\n      subst P. simpl.\n      eauto 10 with iFrame.\n    }\n    wp_load.\n    wp_apply (wp_SliceSet with \"[$HentsS]\"); first by auto 10.\n    iIntros \"HentsS\".\n    wp_load.\n    wp_store.\n    iApply \"HΦ\".\n    subst P. simpl.\n    replace (int.Z 0) with 0 by word.\n    set tpls := list_to_map (wrent_to_key_tpl <$> _).\n    iExists _, (<[k := tpl]> tpls), _.\n    rewrite wrent_to_val_unfold -list_fmap_insert.\n    iFrame \"HentsS Hactive HposR\".\n    replace (int.nat (word.add _ _)) with (S (int.nat n)) by word.\n    rewrite take_S_insert; last word.\n    (* Deduce [k ∉ (take (int.nat i) ents).*1.*1.*1]. *)\n    apply wrent_to_val_with_lookup in Hlookup as (k' & v' & w' & t' & Eqx & Hlookup).\n    inversion Eqx. subst k' v' w' t'.\n    apply take_drop_middle in Hlookup as Eqents.\n    rewrite -Eqents in HNoDup.\n    do 3 rewrite fmap_app in HNoDup.\n    do 3 rewrite fmap_cons in HNoDup.\n    simpl in HNoDup.\n    (* Before we swap using [NoDup_app_comm], obtain [Hnotin'] which we'll need for proving [HNoDup]. *)\n    apply NoDup_app in HNoDup as H.\n    destruct H as (_ & Hnotin' & _).\n    apply NoDup_app_comm in HNoDup.\n    apply NoDup_app in HNoDup as (HNoDup1 & Hnotin & HNoDup2).\n    pose proof (elem_of_list_here k (drop (S (int.nat n)) ents').*1.*1.*1) as Helem.\n    specialize (Hnotin k Helem).\n    assert (HNone : tpls !! k = None).\n    { apply not_elem_of_list_to_map_1. clear -Hnotin. set_solver. }\n    rewrite big_sepM_insert; last done.\n    iFrame \"Htokens HpostOwn\".\n    iSplitL.\n    { rewrite big_sepM_insert; last done. by iFrame \"#\". }\n    iPureIntro.\n    split.\n    { rewrite fmap_snoc.\n      unfold wrent_to_key_tpl. simpl. symmetry.\n      apply list_to_map_snoc.\n      clear -Hnotin. set_solver.\n    }\n    split.\n    { rewrite Hm. f_equal.\n      rewrite list_fmap_insert.\n      unfold wrent_to_key_dbval. simpl.\n      rewrite list_insert_id; first done.\n      rewrite list_lookup_fmap Hlookup.\n      done.\n    }\n    split.\n    { rewrite Hlen. by rewrite insert_length. }\n    { rewrite -Eqents.\n      rewrite -insert_take_drop; last first.\n      { rewrite -Hlen. word. }\n      rewrite list_insert_insert.\n      rewrite insert_take_drop; last first.\n      { rewrite -Hlen. word. }\n      do 3 rewrite fmap_app.\n      do 3 rewrite fmap_cons.\n      rewrite NoDup_app.\n      split; done.\n    }\n  }\n  { (* Loop entry. *)\n    subst P. simpl.\n    iExists _, ∅, _.\n    iFrame.\n    replace (int.nat 0) with 0%nat by word.\n    rewrite take_0. simpl.\n    by do 2 rewrite big_sepM_empty.\n  }\n  iIntros \"HP\". subst P. simpl.\n  clear HNoDup.\n  iNamed \"HP\".\n  (**\n   * Here we have [mods_token] and [is_tuple] for each element in [ents].\n   *)\n\n  (***********************************************************)\n  (* if pos < uint64(len(ents)) {                            *)\n  (*     var i uint64 = 0                                    *)\n  (*     for i < pos {                                       *)\n  (*         tpl := ents[i].tpl                              *)\n  (*         tpl.Free()                                      *)\n  (*         i++                                             *)\n  (*     }                                                   *)\n  (*     return false                                        *)\n  (* }                                                       *)\n  (***********************************************************)\n  wp_pures.\n  wp_load.\n  wp_apply wp_slice_len.\n  wp_if_destruct.\n  { (* Early return due to failure of acquiring all locks. *)\n    wp_apply (wp_ref_to); first by auto.\n    iIntros (i) \"HiR\".\n    wp_pures.\n    set P := (λ (b : bool), ∃ (m : u64),\n                 let tpls' := list_to_map (wrent_to_key_tpl <$> drop (int.nat m) (take (int.nat n) ents')) in\n                 \"HentsS\"   ∷ is_slice_small entsS (struct.t WrEnt) 1 (wrent_to_val <$> ents') ∗\n                 \"HposR\"    ∷ pos ↦[uint64T] #n ∗\n                 \"HiR\"      ∷ i ↦[uint64T] #m ∗\n                 \"Htokens\"  ∷ ([∗ map] k ↦ _ ∈ tpls', mods_token γ k (int.nat tid)))%I.\n    wp_apply (wp_forBreak_cond P with \"[] [HentsS HposR HiR Htokens]\").\n    { (* Loop body. *)\n      clear Φ.\n      iIntros (Φ) \"!> HP HΦ\".\n      subst P. simpl.\n      iNamed \"HP\".\n      do 2 wp_load.\n      wp_if_destruct; last first.\n      { (* Loop condition. *)\n        iApply \"HΦ\".\n        eauto 10 with iFrame.\n      }\n      wp_load.\n      destruct (list_lookup_lt _ (wrent_to_val <$> ents') (int.nat m)) as [ent Hlookup].\n      { rewrite fmap_length. word. }\n      wp_apply (wp_SliceGet with \"[$HentsS]\"); first done.\n      iIntros \"[HentsS %Hty]\".\n      apply val_to_wrent_with_val_ty in Hty as (k & v & w & t & Hent).\n      subst ent.\n      wp_pures.\n      (* Obtain [is_tuple] and [mods_token] for [t]. *)\n      set ents'' := (take _ ents').\n      apply wrent_to_val_with_lookup in Hlookup as (k' & v' & w' & t' & Eqx & Hlookup).\n      inversion Eqx. subst k' v' w' t'.\n      iDestruct (big_sepM_lookup _ _ k t with \"HtplsRP\") as \"#HtplRP\".\n      { rewrite Htpls.\n        rewrite -elem_of_list_to_map; last first.\n        { pose proof HNoDup as HNoDup'.\n          rewrite -(take_drop (int.nat m) ents') in HNoDup.\n          do 3 rewrite fmap_app in HNoDup.\n          apply NoDup_app in HNoDup as [HNoDup _].\n          replace _.*1 with ents''.*1.*1.*1; last first.\n          { do 3 rewrite -list_fmap_compose. set_solver. }\n          rewrite -(take_drop (int.nat n) ents') in HNoDup'.\n          do 3 rewrite fmap_app in HNoDup'.\n          by apply NoDup_app in HNoDup' as [HNoDup' _].\n        }\n        apply (elem_of_list_lookup_2 _ (int.nat m)).\n        rewrite fmap_take.\n        rewrite lookup_take; last word.\n        by rewrite list_lookup_fmap Hlookup.\n      }\n      rewrite (drop_S _ (k, v, w, t)); last first.\n      { subst ents''. rewrite lookup_take; [done | word]. }\n      rewrite fmap_cons list_to_map_cons. simpl.\n      rewrite big_sepM_insert; last first.\n      { apply not_elem_of_list_to_map_1.\n        apply take_drop_middle in Hlookup.\n        rewrite -Hlookup in HNoDup.\n        do 3 rewrite fmap_app in HNoDup.\n        apply NoDup_app in HNoDup as (_ & _ & HNoDup).\n        apply NoDup_cons in HNoDup as [Hnotin _]. simpl in Hnotin.\n        rewrite -(take_drop (int.nat n) ents') in Hnotin.\n        rewrite drop_app_le in Hnotin; last first.\n        { rewrite take_length_le; first word. rewrite -Hlen. word. }\n        clear -Hnotin. set_solver.\n      }\n      iDestruct \"Htokens\" as \"[Htoken Htokens]\".\n      wp_apply (wp_tuple__Free with \"HtplRP Htoken\").\n      wp_pures.\n      wp_load.\n      wp_store.\n      iApply \"HΦ\".\n      iExists _.\n      iFrame.\n      replace (int.nat (word.add _ _)) with (S (int.nat m)) by word.\n      by iFrame.\n    }\n    { subst P. simpl.\n      iExists _. iFrame.\n      replace (int.nat 0) with 0%nat by word.\n      rewrite drop_0. by subst tpls.\n    }\n    iIntros \"HP\".\n    iNamed \"HP\".\n    wp_pures.\n    iApply \"HΦ\".\n    iDestruct (\"HentsC\" with \"HentsS\") as \"HentsS\".\n    rewrite Hm in Hmods.\n    eauto 10 with iFrame.\n  }\n\n  (***********************************************************)\n  (* for _, ent := range ents {                              *)\n  (*     ent.tpl.WriteLock()                                 *)\n  (* }                                                       *)\n  (***********************************************************)\n  replace (take (int.nat n) ents') with ents' in Htpls; last first.\n  { apply Znot_lt_ge in Heqb. symmetry. apply take_ge. word. }\n  set P := (λ (i : u64),\n              let tpls_take := (list_to_map (wrent_to_key_tpl <$> (take (int.nat i) ents'))) in\n              let tpls_drop := (list_to_map (wrent_to_key_tpl <$> (drop (int.nat i) ents'))) in\n              \"Htokens\"  ∷ ([∗ map] k ↦ _ ∈ tpls_drop, mods_token γ k (int.nat tid)) ∗\n              \"HtplsOwn\" ∷ own_tuples_locked (int.nat tid) tpls_take γ\n           )%I.\n  wp_apply (wp_forSlice P with \"[] [$HentsS Htokens]\").\n  { (* Loop body. *)\n    clear Φ.\n    iIntros (j e).\n    iIntros (Φ) \"!> (HP & %Hbound & %Hlookup) HΦ\".\n    subst P. simpl.\n    iNamed \"HP\".\n    apply wrent_to_val_with_lookup in Hlookup as (k & v & w & t & Eqx & Hlookup).\n    subst e.\n    wp_pures.\n    (* Retrieve [is_tuple] of key [k]. *)\n    iDestruct (big_sepM_lookup _ _ k t with \"HtplsRP\") as \"HtplRP\".\n    { rewrite Htpls.\n      rewrite -elem_of_list_to_map; last first.\n      { replace _.*1 with ents'.*1.*1.*1; first done.\n        do 3 rewrite -list_fmap_compose. set_solver.\n      }\n      apply elem_of_list_lookup_2, (elem_of_list_fmap_1 wrent_to_key_tpl) in Hlookup.\n      done.\n    }\n    (**\n     * Deduce [k ∉ (drop (S (int.nat i)) ents').*1.*1.*1], which we need in [big_sepM_insert].\n     * Deduce [k ∉ (take (int.nat i) ents').*1.*1.*1], which we need in [list_to_map_snoc] and [big_sepM_insert].\n     *)\n    apply take_drop_middle in Hlookup as Eqents.\n    rewrite -Eqents in HNoDup.\n    do 3 rewrite fmap_app in HNoDup.\n    do 3 rewrite fmap_cons in HNoDup.\n    simpl in HNoDup.\n    apply NoDup_app_comm in HNoDup as HNoDup'.\n    apply NoDup_app in HNoDup as (_ & _ & HNoDup).\n    apply NoDup_cons in HNoDup as [Hnotin _].\n    apply NoDup_app in HNoDup' as (_ & Hnotin' & _).\n    specialize (Hnotin' k).\n    pose proof (elem_of_list_here k (drop (S (int.nat j)) ents').*1.*1.*1) as Helem.\n    specialize (Hnotin' Helem).\n    (* Q: How to rewrite [P -> Q] to [Q] and prove [P]. *)\n    (* specialize (Hnotin' elem_of_list_here). doesn't work. *)\n    (* Retrieve [mods_token] of key [k]. *)\n    rewrite (drop_S _ _ _ Hlookup).\n    rewrite fmap_cons list_to_map_cons. simpl.\n    rewrite big_sepM_insert; last first.\n    { apply not_elem_of_list_to_map_1. set_solver. }\n    iDestruct \"Htokens\" as \"[Htoken Htokens]\".\n\n    wp_apply (wp_tuple__WriteLock with \"HtplRP Htoken\").\n    iIntros (phys) \"Htpl\".\n    iApply \"HΦ\".\n    replace (int.nat (word.add _ _)) with (S (int.nat j)) by word.\n    iFrame \"Htokens\".\n    rewrite (take_S_r _ _ _ Hlookup).\n    rewrite fmap_snoc list_to_map_snoc; last first.\n    { simpl. rewrite -list_fmap_compose. set_solver. }\n    unfold named. rewrite {2} /own_tuples_locked.\n    rewrite big_sepM_insert; last first.\n    { apply not_elem_of_list_to_map_1. set_solver. }\n    iFrame \"HtplsOwn\".\n    by iExists phys.\n  }\n  { (* Loop entry. *)\n    subst P. simpl.\n    replace (int.nat 0) with 0%nat by word.\n    rewrite drop_0 take_0 -Htpls. simpl.\n    iFrame \"Htokens\".\n    by iApply big_sepM_empty.\n  }\n  iIntros \"[HP HentsS]\".\n  subst P. simpl.\n  iNamed \"HP\".\n  iDestruct (\"HentsC\" with \"HentsS\") as \"HentsS\".\n  wp_pures.\n\n  (***********************************************************)\n  (* return true                                             *)\n  (***********************************************************)\n  iApply \"HΦ\".\n  iFrame \"Hactive\".\n  iExists _.\n  rewrite -HentsLen Hlen firstn_all.\n  iFrame \"HtplsOwn\".\n  rewrite Hm in Hmods.\n  eauto 10 with iFrame.\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/mvcc/wrbuf_open_tuples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.27568496520172214}}
{"text": "Require Import SpecCert.x86.Architecture.\n\nDefinition open_smram_pre\n           {Label: Type}\n           (a:     Architecture Label) :=\n  smramc_is_unlocked (memory_controller a).\n\nDefinition open_smram_post\n           {Label: Type}\n           (a a':  Architecture Label) :=\n    exists h, let m' := open_smram (memory_controller a) h\n    in a' = update_memory_controller a m'.\n", "meta": {"author": "lthms", "repo": "speccert", "sha": "8c1edfb173548af0e9ca3c4e24d43726401fdb71", "save_path": "github-repos/coq/lthms-speccert", "path": "github-repos/coq/lthms-speccert/speccert-8c1edfb173548af0e9ca3c4e24d43726401fdb71/src/x86/Transition/Event/OpenSmram.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.2756849589374826}}
{"text": "Require Import Coq.Reals.Reals.\nRequire Import Coq.omega.Omega.\nRequire Import Coq.Arith.Minus.\nRequire Import Coq.micromega.Lra.\nRequire Import RRR.Lang.Syntax.\nRequire Import RRR.Lang.Bindings.\nRequire Import RRR.Lang.BindingsFacts.\nRequire Import RRR.Lang.Entropy.\nRequire Import RRR.Lang.SmallStep.\nRequire Import RRR.Lang.Evaluation.\nRequire Import RRR.Lang.Measure.\nRequire Import RRR.Lebesgue.Lebesgue.\nRequire Import FunctionalExtensionality.\n\nSet Implicit Arguments.\n\nSection section_sss_antitone_S_aux.\nContext (n : nat).\nContext (μNS_antitone : ∀ e, μNS (S n) e ≤ μNS n e).\n\nFact sss_antitone_S_aux_bifurcate e :\n∀ t t' e' w₁, sss (eval (S n)) t e t' e' w₁ → (\n  ∃ w₀, sss (eval n) t e t' e' w₀ ∧ w₀ ≤ w₁\n) ∨ (\n  ∃ K f, e = ktx_plug K (exp_sample (val_query f)) ∧\n  t' = t ∧ e' = ktx_plug K exp_exn ∧\n  w₁ = 1 ∧ 0 = μNS (S n) f ∧ 0 < μNS n f\n).\nProof.\ninduction 1.\n+ left. repeat eexists; [constructor|apply ennr_le_refl].\n+ left. repeat eexists; [constructor|apply ennr_le_refl].\n+ left. repeat eexists; [constructor|apply ennr_le_refl].\n+ left. repeat eexists; [constructor; eauto|apply ennr_le_refl].\n+ left. repeat eexists; [constructor|apply ennr_le_refl].\n+ left. repeat eexists; [constructor|apply ennr_le_refl].\n+ left. repeat eexists; [constructor|apply ennr_le_refl].\n+ left. repeat eexists; [constructor|apply ennr_le_refl].\n+ left. assert (0 < μNS n e) as NS.\n  1:{ eapply ennr_lt_le_trans; [eassumption|apply μNS_antitone]. }\n  repeat eexists.\n  - apply sss_sample_query. apply NS.\n  - apply ennr_mult_inv_le_compat. apply μNS_antitone.\n+ destruct (ennr_0_lt_dec (μNS n e)) as [NS|NS].\n  - right. eexists ktx_hole. repeat eexists; assumption.\n  - left. repeat eexists.\n    1:{ apply sss_sample_query_exn. apply NS. }\n    apply ennr_le_refl.\n+ left. repeat eexists; [unshelve constructor; auto|].\n  apply ennr_le_refl.\n+ destruct IHsss as [[w₀ [IHsss Hw]]|[K [f [? [? [? [? [? ?]]]]]]]].\n  2:{ subst. right. eexists (ktx_app1 K _). repeat eexists; assumption. }\n  left. repeat eexists. 2:{ apply Hw. }\n  bind_ktx_app1. apply ktx_congruence; eassumption.\n+ destruct IHsss as [[w₀ [IHsss Hw]]|[K [f [? [? [? [? [? ?]]]]]]]].\n  2:{ subst. right. eexists (ktx_app2 _ K). repeat eexists; assumption. } left. repeat eexists. 2:{ apply Hw. }\n  bind_ktx_app2. apply ktx_congruence; eassumption.\n+ destruct IHsss as [[w₀ [IHsss Hw]]|[K [f [? [? [? [? [? ?]]]]]]]].\n  2:{ subst. right. eexists (ktx_let K _). repeat eexists; assumption. }\n  left. repeat eexists. 2:{ apply Hw. }\n  bind_ktx_let. apply ktx_congruence; eassumption.\n+ destruct IHsss as [[w₀ [IHsss Hw]]|[K [f [? [? [? [? [? ?]]]]]]]].\n  2:{ subst. right. eexists (ktx_binop1 _ K _). repeat eexists; assumption. }\n  left. repeat eexists. 2:{ apply Hw. }\n  bind_ktx_binop1. apply ktx_congruence; eassumption.\n+ destruct IHsss as [[w₀ [IHsss Hw]]|[K [f [? [? [? [? [? ?]]]]]]]].\n  2:{ subst. right. eexists (ktx_binop2 _ _ K). repeat eexists; assumption. }\n  left. repeat eexists. 2:{ apply Hw. }\n  bind_ktx_binop2. apply ktx_congruence; eassumption.\n+ destruct IHsss as [[w₀ [IHsss Hw]]|[K [f [? [? [? [? [? ?]]]]]]]].\n  2:{ subst. right. eexists (ktx_proj K _). repeat eexists; assumption. }\n  left. repeat eexists. 2:{ apply Hw. }\n  bind_ktx_proj. apply ktx_congruence; eassumption.\n+ destruct IHsss as [[w₀ [IHsss Hw]]|[K [f [? [? [? [? [? ?]]]]]]]].\n  2:{ subst. right. eexists (ktx_if K _ _). repeat eexists; assumption. }\n  left. repeat eexists. 2:{ apply Hw. }\n  bind_ktx_if. apply ktx_congruence; eassumption.\n+ destruct IHsss as [[w₀ [IHsss Hw]]|[K [f [? [? [? [? [? ?]]]]]]]].\n  2:{ subst. right. eexists (ktx_sample K). repeat eexists; assumption. }\n  left. repeat eexists. 2:{ apply Hw. }\n  bind_ktx_sample. apply ktx_congruence; eassumption.\n+ destruct IHsss as [[w₀ [IHsss Hw]]|[K [f [? [? [? [? [? ?]]]]]]]].\n  2:{ subst. right. eexists (ktx_score K). repeat eexists; assumption. }\n  left. repeat eexists. 2:{ apply Hw. }\n  bind_ktx_score. apply ktx_congruence; eassumption.\nQed.\n\nFact sss_antitone_S_aux e :\n∀ t t' e' w₁, sss (eval (S n)) t e t' e' w₁ →\n∃ e₀ w₀, sss (eval n) t e t' e₀ w₀.\nProof.\ndo 4 intro. intro H.\napply sss_antitone_S_aux_bifurcate in H.\ndestruct H as [[? [? ?]] | [? [? [? [? [? [? [? ?]]]]]]]].\n+ repeat eexists. eassumption.\n+ subst. repeat eexists.\n  apply ktx_congruence. apply sss_sample_query. assumption.\nQed.\n\nFact stop_monotone_S_aux e : stop n e → stop (S n) e.\nProof.\nunfold stop. intros [Stop_n NotExn].\nsplit.\n+ do 4 intro. intro Step_Sn.\n  apply sss_antitone_S_aux_bifurcate in Step_Sn as [ [? [Step_n ?]] | Step_Sn ].\n  - eapply Stop_n. apply Step_n.\n  - destruct Step_Sn as [K [f [? [? [? [? [? ?]]]]]]]. subst.\n    eapply Stop_n with (t := t). apply ktx_congruence. apply sss_sample_query. assumption.\n+ apply NotExn.\nQed.\nEnd section_sss_antitone_S_aux.\n\nFixpoint\n(** In general, [ev2v N t e = Some _ → ev2v (S N) t e = Some _] does not hold. *)\nev2v_monotone_S N e {struct N} :\n∫ (λ t, match ev2v N t e with\n  | Some (_, _, _, w) => if ev2v (S N) t e then 0 else w\n  | None => 0\nend) μentropy = 0\nwith\nμNS_antitone_S n e {struct n} : μNS (S n) e ≤ μNS n e\nwith\nμNS_antitone_S_minus_aux n e {struct n} :\n∀ k, (k < n)%nat → μNS (S k) e ≤ μNS k e\nwith\nev2v_S n t e k0 t0 v0 w0 k1 t1 v1 w1\n(Ev2v_e_n: ev2v n t e = Some (k0, t0, v0, w0))\n(Ev2v_e_Sn: ev2v (S n) t e = Some (k1, t1, v1, w1)) {struct n} :\nt0 = t1 ∧ k0 = k1 ∧ v0 = v1 ∧ w0 ≤ w1\nwith\nμTV_monotone_S N e V {struct N} : μTV N e V ≤ μTV (S N) e V.\nProof.\n{\nclear- ev2v_S ev2v_monotone_S. \ndestruct N as [ | N ].\n1:{\n  rewrite <- integration_const_entropy with (f := λ _, 0) by trivial.\n  integrand_extensionality t.\n  simpl ev2v. destruct (exp_val_dec e) as [[v Hv]|Nonval_e] eqn:Dec_val_e; ring.\n}\ndestruct (sss_exp_dec N e) as [Step_e_N | Stop_e_N].\n2:{\n  rewrite <- integration_const_entropy with (f := λ _, 0) by trivial.\n  integrand_extensionality t.\n  destruct (exp_val_dec e) as [[v Hv]|Nonval_e].\n  + subst. simpl. ring.\n  + destruct (exp_ktx_exn_dec e) as [[K ?]|Nonexn_e].\n    1:{ subst. rewrite ev2v_ktx_exn. ring. }\n    rewrite ev2v_stuck.\n    3:{ assumption. }\n    2:{ split; assumption. }\n    1:{ ring. }\n}\nspecialize (Step_e_N entropy0) as [t' [e' [w Step_e_N]]].\napply sss_quadfurcate in Step_e_N.\ndestruct Step_e_N as [Step_e_N|[Step_e_N|[Step_e_N|Step_e_N]]].\n+ destruct Step_e_N as [Step_e_N Hw].\n  match goal with [ |- ∫ ?f _ = _ ] => replace f with (\n    λ t, match ev2v N t e' with\n      | Some (_, _, _, w') => if ev2v (S N) t e' then 0 else w * w'\n      | None => 0\n    end\n  ) end.\n  2:{\n    extensionality t.\n    specialize (Step_e_N (S N) t) as Step_e_SN.\n    specialize (Step_e_N N t) as Step_e_N.\n    apply sss_ev2v in Step_e_SN. apply sss_ev2v in Step_e_N.\n    rewrite Step_e_SN, Step_e_N.\n    destruct (ev2v N t e') as [ [[[? ?] ?] ?] | ],\n             (ev2v (S N) t e') as [ [[[? ?] ?] ?] | ]; reflexivity.\n  }\n  apply eq_sym. eapply ennr_mult_infinity_compat_0_eq.\n  2:{ apply eq_sym. apply ev2v_monotone_S with (e := e') (N := N). }\n  rewrite <- integration_linear_mult_l.\n  apply integrand_extensionality_le. intro t.\n  repeat match goal with\n  | [ |- context[match ?x with _ => _ end] ] => destruct x\n  | [ |- (0 ≤ _)%ennr ] => apply ennr_le_0\n  | [ |- (_ ≤ ∞)%ennr ] => apply ennr_le_infinity\n  | [ |- (_ * ?r ≤ _ * ?r)%ennr ] => apply ennr_mult_le_compat_r\n  end.\n+ destruct Step_e_N as [K [f [? [Pos_N [? [? ?]]]]]]. subst.\n  destruct (ennr_0_lt_dec (μNS (S N) f)) as [Pos_SN|Zero_SN].\n  - match goal with [ |- ∫ ?g _ = _ ] => replace g with (\n      λ t, match ev2v N t (ktx_plug K f) with\n        | Some (_, _, _, w') => if ev2v (S N) t (ktx_plug K f) then 0 else (/ μNS N f) * w'\n        | None => 0\n      end\n    ) end.\n    2:{\n      extensionality t.\n      erewrite sss_ev2v with (N := N) (e := ktx_plug K (exp_sample (val_query f))).\n      2:{ apply ktx_congruence. apply sss_sample_query. assumption. }\n      erewrite sss_ev2v with (N := S N) (e := ktx_plug K (exp_sample (val_query f))).\n      2:{ apply ktx_congruence. apply sss_sample_query. assumption. }\n      destruct (ev2v N t (ktx_plug K f)) as [ [[[? ?] ?] ?] | ],\n      (ev2v (S N) t (ktx_plug K f)) as [ [[[? ?] ?] ?] | ]; reflexivity.\n    }\n    apply eq_sym. eapply ennr_mult_infinity_compat_0_eq.\n    2:{ apply eq_sym. apply ev2v_monotone_S with (e := ktx_plug K f) (N := N). }\n    rewrite <- integration_linear_mult_l.\n    apply integrand_extensionality_le. intro t.\n    repeat match goal with\n    | [ |- context[match ?x with _ => _ end] ] => destruct x\n    | [ |- (0 ≤ _)%ennr ] => apply ennr_le_0\n    | [ |- (_ ≤ ∞)%ennr ] => apply ennr_le_infinity\n    | [ |- (_ * ?r ≤ _ * ?r)%ennr ] => apply ennr_mult_le_compat_r\n    end.\n  - match goal with [ |- ∫ ?g _ = _ ] => replace g with (\n      λ t, match ev2v N t (ktx_plug K f) with\n        | Some (_, _, _, w') => if ev2v (S N) t (ktx_plug K f) then 0 else (/ μNS N f) * w'\n        | None => 0\n      end + match ev2v N t (ktx_plug K f) with\n        | Some (_, _, _, w') => if ev2v (S N) t (ktx_plug K f) then (/ μNS N f) * w' else 0\n        | None => 0\n      end\n    ) end.\n    2:{\n      extensionality t.\n      erewrite sss_ev2v with (N := N) (e := ktx_plug K (exp_sample (val_query f))).\n      2:{ apply ktx_congruence. apply sss_sample_query. assumption. }\n      erewrite sss_ev2v with (e := ktx_plug K (exp_sample (val_query f))).\n\n      2:{ apply ktx_congruence. apply sss_sample_query_exn. assumption. }\n      rewrite ev2v_ktx_exn.\n      destruct (ev2v N t (ktx_plug K f)) as [ [[[? ?] ?] ?] | ]. 2:{ ring. }\n      destruct (ev2v (S N) t (ktx_plug K f)) as [ [[[? ?] ?] ?] | ]; ring.\n    }\n    rewrite <- integration_linear_plus.\n    match goal with [ |- ?x + _ = 0 ] => replace x with 0 end.\n    2:{\n      eapply ennr_mult_infinity_compat_0_eq.\n      2:{ apply eq_sym. apply ev2v_monotone_S with (e := ktx_plug K f) (N := N). }\n      rewrite <- integration_linear_mult_l.\n      apply integrand_extensionality_le. intro t.\n      repeat match goal with\n      | [ |- context[match ?x with _ => _ end] ] => destruct x\n      | [ |- (0 ≤ _)%ennr ] => apply ennr_le_0\n      | [ |- (_ ≤ ∞)%ennr ] => apply ennr_le_infinity\n      | [ |- (_ * ?r ≤ _ * ?r)%ennr ] => apply ennr_mult_le_compat_r\n      end.\n    }\n    match goal with [ |- 0 + ?x = 0 ] => replace x with 0 end; [ring|].\n    assert (0 = μNS (S N) (ktx_plug K f)) as Zero_SN_K.\n    1:{ apply ennr_le_0_is_0. rewrite Zero_SN. apply μNS_ktx_plug_le. }\n    eapply ennr_mult_infinity_compat_0_eq. 2:{ apply Zero_SN_K. }\n    unfold μNS at 2.\n    rewrite <- integration_linear_mult_l.\n    apply integrand_extensionality_le. intro t.\n    destruct (ev2v N t (ktx_plug K f)) as [ [[[? ?] ?] ?] | ] eqn:HN. 2:{ apply ennr_le_0. }\n    destruct (ev2v (S N) t (ktx_plug K f)) as [ [[[? ?] ?] ?] | ] eqn:HSN. 2:{ apply ennr_le_0. }\n    unfold ρNS. erewrite ev2v_Some_eval. 2:{ apply HSN. }\n    apply ennr_mult_le_compat.\n    1:{ apply ennr_le_infinity. }\n    (* apply mutual induction hypothesis *)\n    eapply ev2v_S with (n := N) in HN. 2:{ apply HSN. } apply HN.\n+ destruct Step_e_N as [K [f [? [NS [? [? ?]]]]]]. subst.\n  rewrite integration_const_entropy with (v := 0). 1:{ ring. }\n  intro t. erewrite sss_ev2v with (N := N).\n  2:{ apply ktx_congruence. apply sss_sample_query_exn. assumption. }\n  rewrite ev2v_ktx_exn. ring.\n+ destruct Step_e_N as [K [? [? [? ?]]]]. subst.\n  match goal with [ |- ∫ ?f _ = _ ] => replace f with (\n    λ t, match ev2v N (πR t) (ktx_plug K (val_real (πU t))) with\n      | Some (_, _, _, w) => if ev2v (S N) (πR t) (ktx_plug K (val_real (πU t))) then 0 else w\n      | None => 0\n    end\n  ) end.\n  2:{\n    extensionality t.\n    erewrite sss_ev2v with (N := N) (e := ktx_plug K (exp_sample val_unif)).\n    2:{ apply ktx_congruence. apply sss_sample_unif. }\n    erewrite sss_ev2v with (N := S N) (e := ktx_plug K (exp_sample val_unif)).\n    2:{ apply ktx_congruence. apply sss_sample_unif. }\n    destruct (ev2v N (πR t) (ktx_plug K (val_real (πU t)))) as [ [[[? ?] ?] ?] | ] eqn:P,\n             (ev2v (S N) (πR t) (ktx_plug K (val_real (πU t)))) as [ [[[? ?] ?] ?] | ] eqn:Q; try reflexivity; try ring.\n  }\n  assert (0 = ∫ (λ (t1 : entropy), ∫ (λ t2,\n    match ev2v N t2 (ktx_plug K (val_real (proj1_sig (t1 0%nat)))) with\n    | Some (_, _, _, w) => if ev2v (S N) t2 (ktx_plug K (val_real (proj1_sig (t1 0%nat)))) then 0 else w\n    | None => 0\n    end\n  ) μentropy) μentropy) as H.\n  2:{ rewrite <- integration_πL_πR in H. auto. }\n  assert (0 = ∫ (λ r, ∫ (λ t,\n    match ev2v N t (ktx_plug K (val_real r)) with\n    | Some (_, _, _, w) => if ev2v (S N) t (ktx_plug K (val_real r)) then 0 else w\n    | None => 0\n    end\n  ) μentropy * (if Rinterval_dec 0 1 r then 1 else 0)) lebesgue_measure) as H.\n  2:{ rewrite <- integration_πU_lebesgue in H. auto. }\n  erewrite integration_of_const with (r := 0). 1:{ ring. }\n  intro r. match goal with [ |- ?x * _ = 0 ] => replace x with 0 end. 1:{ ring. }\n  eapply ennr_mult_infinity_compat_0_eq.\n  2:{ apply eq_sym. apply ev2v_monotone_S with (e := ktx_plug K (val_real r)) (N := N). }\n  rewrite <- integration_linear_mult_l.\n  apply integrand_extensionality_le. intro t.\n  repeat match goal with\n  | [ |- context[match ?x with _ => _ end] ] => destruct x\n  | [ |- (0 ≤ _)%ennr ] => apply ennr_le_0\n  | [ |- (_ ≤ ∞)%ennr ] => apply ennr_le_infinity\n  | [ |- (_ * ?r ≤ _ * ?r)%ennr ] => apply ennr_mult_le_compat_r\n  end.\n  repeat match goal with\n  | [ H : ?P |- ?P ] => apply H\n  | [ |- (0 ≤ _)%ennr ] => apply ennr_le_0\n  | [ |- (_ ≤ ∞)%ennr ] => apply ennr_le_infinity\n  | [ _ : 0 < ?r |- context[∞ * ?r] ] => rewrite ennr_mul_infinity_l\n  | [ |- ?r ≤ ∞ * ?r ] => destruct (ennr_0_lt_dec e); subst\n  end.\n}\n    \n{\ndestruct n as [ | n ].\n1:{ rewrite μNS_O. apply μNS_le_1. }\ndestruct (exp_val_dec e) as [ [v Hv] | NotVal_e ].\n1:{ subst. repeat rewrite μNS_val. apply ennr_le_refl. }\ndestruct (exp_ktx_exn_dec e) as [ [K ?] | NotExn_e ].\n1:{ subst. repeat rewrite <-μNS_exn. apply ennr_le_refl. }\ndestruct (sss_exp_dec n e) as [ Step_n | Stop_n ].\n2:{\n  rewrite <- μNS_stuck with (N := S n). 1:{ apply ennr_le_0. }\n  * split.\n    + intros t t' e' w Step_Sn.\n      apply sss_antitone_S_aux in Step_Sn as [? [? Step_Sn]].\n      2:{ apply μNS_antitone_S with (n := n). }\n      eapply Stop_n. apply Step_Sn.\n    + assumption.\n  * assumption.\n}\nspecialize Step_n as Step_n0.\nspecialize (Step_n0 entropy0) as [t' [e' [w Step_n0]]].\napply sss_quadfurcate in Step_n0.\ndestruct Step_n0 as [Q | [Q | [Q | Q]]].\n+ clear t'. destruct Q as [Q ?].\n  pose (Q (S n)) as Q_Sn. pose (Q n) as Q_n.\n  assert (∀ K N t, sss (eval N) t (ktx_plug K e) t (ktx_plug K e') w) as QK.\n  1:{ intros. apply ktx_congruence. eapply Q. }\n  apply sss_preserves_μNS in Q_Sn. repeat rewrite Q_Sn.\n  apply sss_preserves_μNS in Q_n. repeat rewrite Q_n.\n  apply ennr_mult_le_compat_r. apply μNS_antitone_S with (n := n).\n+ destruct Q as [K [f [? [NS_n [? [? ?]]]]]]. subst.\n  assert (∀ K t,\n  sss (eval n) t (ktx_plug K (exp_sample (val_query f)))\n  t (ktx_plug K f) (/ μNS (n) f)\n  ) as Step_Kf_n.\n  1:{\n  clear- NS_n. intros K t.\n  apply ktx_congruence. constructor. assumption.\n  }\n  destruct (ennr_0_lt_dec (μNS (S n) f)) as [NS_Sn|NS_Sn].\n  - assert (∀ K t,\n      sss (eval (S n)) t (ktx_plug K (exp_sample (val_query f)))\n      t (ktx_plug K f) (/ μNS (S n) f)\n    ) as Step_Kf_Sn.\n    1:{\n      clear- NS_Sn. intros K t.\n      apply ktx_congruence. constructor. assumption.\n    }\n    rename f into e.\n    erewrite sss_preserves_μNS with (N := n); try apply Step_Kf_n.\n    erewrite sss_preserves_μNS with (N := S n); try apply Step_Kf_Sn.\n    replace (μNS (S n) e) with (μNS (S n) (ktx_plug ktx_hole e)) by trivial.\n    replace (μNS n e) with (μNS n (ktx_plug ktx_hole e)) by trivial.\n    repeat rewrite μNS_ktx_rewrite_S.\n    repeat rewrite μNS_ktx_rewrite with (N := n).\n    apply ennr_inv_useful_fact.\n    5:{ rewrite <- μNS_ktx_rewrite. apply μNS_finite. }\n    4:{ rewrite <- μNS_ktx_rewrite, <- μNS_ktx_rewrite_S. apply μNS_antitone_S with (n := n). }\n    3:{\n      simpl ktx_plug.\n      repeat rewrite integration_linear_minus.\n      2:{\n        intro t. repeat match goal with\n        | [ |- context[match ?x with _ => _ end] ] => destruct x\n        | [ |- (0 ≤ _)%ennr ] => apply ennr_le_0\n        | [ |- (?r * _ ≤ ?r * _)%ennr ] => apply ennr_mult_le_compat_l\n        end. rewrite μNS_val. apply μNS_le_1.\n      }\n      2:{\n        intro t. repeat match goal with\n        | [ |- context[match ?x with _ => _ end] ] => destruct x\n        | [ |- (0 ≤ _)%ennr ] => apply ennr_le_0\n        | [ |- (?r * _ ≤ ?r * _)%ennr ] => apply ennr_mult_le_compat_l\n        end. rewrite μNS_val. apply μNS_le_1.\n      }\n\n      match goal with [ |- ?x ≤ _ ] => replace x with (\n        ∫ (λ t, match ev2v n t e with\n          | Some (k, _, v, w) =>\n            (if ev2v (S n) t e then w else 0) *\n            (μNS (n - k) v - μNS (n - k) (ktx_plug K v))\n          | None => 0\n        end) μentropy +\n        ∫ (λ t, match ev2v n t e with\n          | Some (k, _, v, w) =>\n            (if ev2v (S n) t e then 0 else w) *\n            (μNS (n - k) v - μNS (n - k) (ktx_plug K v))\n          | None => 0\n        end) μentropy\n      ) end.\n      2:{\n        rewrite integration_linear_plus. integrand_extensionality t.\n        repeat match goal with\n        | [ |- context[match ?x with _ => _ end] ] => destruct x\n        | [ |- context[(0 * _)%ennr]] => rewrite ennr_mul_0_l\n        | [ |- context[(0 + _)%ennr]] => rewrite ennr_add_0_l\n        | [ |- context[(_ + 0)%ennr]] => rewrite ennr_add_0_r\n        | [ |- context[(_ - 0)%ennr]] => rewrite ennr_minus_0\n        end.\n        3:{ ring. }\n        2:{ apply ennr_minus_distr_r. apply μNS_ktx_plug_le. }\n        1:{ apply ennr_minus_distr_r. apply μNS_ktx_plug_le. }\n      }\n      match goal with [ |- _ + ?x ≤ _ ] => replace x with 0 end.\n      2:{\n        eapply ennr_mult_infinity_compat_0_eq.\n        2:{ apply eq_sym. apply ev2v_monotone_S with (N := n) (e := e). }\n        rewrite <- integration_linear_mult_l.\n        apply integrand_extensionality_le. intro t.\n        destruct (ev2v n t e) as [ [[[? ?] ?] ?] | ]. 2:{ apply ennr_le_0. }\n        repeat match goal with\n        | [ |- context[match ?x with _ => _ end] ] => destruct x\n        | [ |- context[(0 * _)%ennr]] => rewrite ennr_mul_0_l\n        | [ |- (0 ≤ _)%ennr ] => apply ennr_le_0\n        | [ |- (_ ≤ ∞)%ennr ] => apply ennr_le_infinity\n        | [ |- ?r * _ ≤ _ * ?r ] => rewrite ennr_mul_comm with (n := r)\n        | [ |- _ * ?r ≤ _ * ?r ] => apply ennr_mult_le_compat_r\n        end.\n      }\n      rewrite ennr_add_0_r.\n\n      apply integrand_extensionality_le. intro t.\n      destruct (ev2v n t e) as [[[[k0 t0] v0] w0]|] eqn:Ev2v_e_n,\n          (ev2v (S n) t e) as [[[[k1 t1] v1] w1]|] eqn:Ev2v_e_Sn;\n      repeat match goal with\n      | [ |- context[match ?x with _ => _ end] ] => destruct x\n      | [ |- (0 ≤ _)%ennr ] => apply ennr_le_0\n      | [ |- context[(_ - 0)%ennr] ] => rewrite ennr_minus_0\n      | [ |- context[(_ * 1)%ennr] ] => rewrite ennr_mul_1_r\n      | [ |- context[(0 * _)%ennr] ] => rewrite ennr_mul_0_l\n      | [ |- context[μNS _ (exp_val _)] ] => rewrite μNS_val\n      end.\n      2:{\n        (* apply mutual induction hypothesis *)\n        eapply ev2v_S with (n := n) in Ev2v_e_Sn as [? [? ?]]; try exact Ev2v_e_n.\n        subst. assert ((n - k1 = 0)%nat) as P by omega. rewrite P.\n        rewrite μNS_O, ennr_minus_self, ennr_mul_0_r. apply ennr_le_0.\n      }\n      rewrite ennr_minus_distr_r. 2:{ apply μNS_le_1. }\n      rewrite <- ennr_mul_1_r with (r := w1) at 1.\n      repeat rewrite ennr_mul_comm with (n := w0).\n      repeat rewrite ennr_mul_comm with (n := w1).\n      repeat rewrite <- ennr_minus_distr_l; try apply μNS_le_1.\n      (* apply mutual induction hypothesis *)\n      eapply ev2v_S with (n := n) in Ev2v_e_Sn as [? [? [? ?]]]; try exact\n      Ev2v_e_n. subst.\n      apply ennr_mult_le_compat. 2:{ assumption. }\n      apply ennr_minus_le_compat_r; try apply μNS_le_1.\n      rewrite <- minus_Sn_m. 2:{ omega. }\n      destruct k1.\n      - rewrite <- minus_n_O. apply μNS_antitone_S with (n := n).\n      - (* apply mutual induction hypothesis *)\n        apply μNS_antitone_S_minus_aux with (n := n). omega.\n    }\n    2:{\n      simpl ktx_plug. apply integrand_extensionality_le; intro t.\n      repeat match goal with\n      | [ |- context[match ?x with _ => _ end] ] => destruct x\n      | [ |- (0 ≤ _)%ennr ] => apply ennr_le_0\n      end. apply ennr_mult_le_compat_l. rewrite μNS_val. apply μNS_le_1.\n    }\n    1:{\n      simpl ktx_plug. apply integrand_extensionality_le; intro t.\n      repeat match goal with\n      | [ |- context[match ?x with _ => _ end] ] => destruct x\n      | [ |- (0 ≤ _)%ennr ] => apply ennr_le_0\n      end. apply ennr_mult_le_compat_l. rewrite μNS_val. apply μNS_le_1.\n    }\n  - erewrite sss_preserves_μNS with (N := n).\n    2:{ intro. apply ktx_congruence. apply sss_sample_query. apply NS_n. }\n    assert (0 = μTV n f full_event) as TV_n.\n    1:{\n      apply ennr_le_0_is_0. rewrite NS_Sn.\n      eapply ennr_le_trans. 2:{ apply μTV_le_μNS. }\n      apply μTV_monotone_S with (N := n). (* apply mutual induction hypothesis *)\n    }\n    replace (μNS n (ktx_plug K f)) with (μNS n f).\n    1:{\n      rewrite ennr_mult_inv_r_finite.\n      + apply μNS_le_1.\n      + apply NS_n.\n      + apply μNS_finite.\n    }\n    rewrite μNS_decompose with (e := f). rewrite <- TV_n, ennr_add_0_l.\n    rewrite μNS_ktx_rewrite. match goal with\n      [ |- ?x = ?y + ?x ] => replace y with 0\n    end. 1:{ ring. }\n    apply ennr_mult_infinity_compat_0_eq with (r2 := μTV n f full_event).\n    2:{ apply TV_n. }\n    unfold μTV. rewrite <- integration_linear_mult_l.\n    apply integrand_extensionality_le. intro t.\n    rewrite <- ev2v_ρTV_same_weight. destruct (ev2v n t f) as [[[[? ?] ?] ?]|].\n    2:{ apply ennr_le_0. }\n    1:{ rewrite ennr_mul_comm. apply ennr_mult_le_compat_r. apply ennr_le_infinity. }\n+ destruct Q as [K [f [? [NS_n [? [? ?]]]]]]. subst.\n  assert (0 = μNS (S n) f) as NS_Sn.\n  1:{ apply ennr_le_0_is_0. rewrite NS_n. apply μNS_antitone_S with (n := n). }\n  erewrite sss_preserves_μNS with (N := n).\n  2:{ intro t. apply ktx_congruence. apply sss_sample_query_exn. apply NS_n. }\n  erewrite sss_preserves_μNS with (N := S n).\n  2:{ intro t. apply ktx_congruence. apply sss_sample_query_exn. apply NS_Sn. }\n  repeat erewrite <-μNS_exn. rewrite ennr_mul_1_r. apply ennr_le_refl.\n+ destruct Q as [K [? [? [? ?]]]]. subst.\n  repeat rewrite ktx_sample_unif_preserves_μNS.\n  apply integrand_extensionality_le. intro r.\n  apply ennr_mult_le_compat_r.\n  apply μNS_antitone_S with (n := n).\n}\n\n{\ndestruct n as [|n].\n1:{ intros. exfalso. omega. }\ninduction k as [|k IHk].\n1:{ intro. rewrite μNS_O. apply μNS_le_1. }\nintro H.\ndestruct (lt_eq_lt_dec k (n - 1)) as [ [|] | ].\n+ (* apply mutual induction hypothesis *)\n  apply μNS_antitone_S_minus_aux with (n := n). omega.\n+ assert (S k = n) as Q. 1:{ omega. } rewrite Q.\n  (* apply mutual induction hypothesis *)\n  apply μNS_antitone_S with (n := n).\n+ exfalso. omega.\n}\n\n{\ndestruct n as [|n].\n1:{\n  cbn in *.\n  destruct (exp_val_dec e) as [[v Hv] | Nonval_e ].\n  + inversion Ev2v_e_n. inversion Ev2v_e_Sn. subst.\n    repeat split. apply ennr_le_refl.\n  + inversion Ev2v_e_n.\n}\napply unfold_ev2v_S_to_Some in Ev2v_e_n.\napply unfold_ev2v_S_to_Some in Ev2v_e_Sn.\ndestruct Ev2v_e_n as [Ev2v_e_n|Ev2v_e_n], Ev2v_e_Sn as [Ev2v_e_Sn|Ev2v_e_Sn].\n+ destruct Ev2v_e_n as [? [? [? ?]]], Ev2v_e_Sn as [? [? [? ?]]]. subst.\n  match goal with [H : exp_val _ = exp_val _ |- _] => inversion H; clear H end. subst.\n  repeat split. apply ennr_le_refl.\n+ destruct Ev2v_e_n as [? [? [? ?]]], Ev2v_e_Sn as [? [? [? [? [? [? [? [?\n?]]]]]]]].\n  subst. match goal with [H : sss _ ?t (exp_val _) _ _ _ |- _ ] => inversion H end.\n+ destruct Ev2v_e_Sn as [? [? [? ?]]], Ev2v_e_n as [? [? [? [? [? [? [? [?\n?]]]]]]]].\n  subst. match goal with [H : sss _ ?t (exp_val _) _ _ _ |- _ ] => inversion H end.\n+ destruct Ev2v_e_n as [? [? [? [? [Step_n [? [? [? Ev2v_n]]]]]]]], Ev2v_e_Sn as [? [t' [e' [? [Step_Sn [? [? [? Ev2v_Sn]]]]]]]].\n  subst.\n  apply sss_quadfurcate in Step_n as Q. destruct Q as [Q | [Q | [Q | Q]]].\n  - destruct Q as [Q Hw].\n    specialize (Q (S n) t) as Step_Sn'.\n    specialize (Q n t) as Step_n'.\n    destruct (sss_unique Step_Sn' Step_Sn) as [? [? ?]]. subst.\n    destruct (sss_unique Step_n Step_n') as [? [? ?]]. subst.\n    eapply ev2v_S with (n := n) in Ev2v_Sn as [? [? [? ?]]]; try exact Ev2v_n. subst.\n    repeat split. apply ennr_mult_le_compat_l. assumption.\n  - destruct Q as [K [f [? [? [? [? ?]]]]]]. subst.\n    eapply sss_ktx_inv in Step_n; try reflexivity.\n    2:{ inversion 1. }\n    eapply sss_ktx_inv in Step_Sn; try reflexivity.\n    2:{ inversion 1. }\n    destruct Step_n as [? [Step_n ?]]. inversion Step_n; subst.\n    3:{ subst. match goal with [H : sss _ ?t (exp_val _) _ _ _ |- _ ] => inversion H end. }\n    2:{ match goal with [H1: 0 = ?x, H2: 1 = / ?x |- _ ] => rewrite <-H1 in H2; rewrite ennr_inv_0 in H2; inversion H2 end. }\n    destruct Step_Sn as [? [Step_Sn ?]]. inversion Step_Sn; subst.\n    3:{ subst. match goal with [H : sss _ ?t (exp_val _) _ _ _ |- _ ] => inversion H end. }\n    2:{ rewrite ev2v_ktx_exn in Ev2v_Sn. inversion Ev2v_Sn. }\n    eapply ev2v_S with (n := n) in Ev2v_Sn as [? [? [? ?]]]; try exact Ev2v_n. subst.\n    repeat split. apply ennr_mult_le_compat; try assumption.\n    apply ennr_mult_inv_le_compat.\n    apply μNS_antitone_S with (n := n). (* apply mutual induction hypothesis *)\n  - destruct Q as [K [? [? [? [? [? ?]]]]]]. subst.\n    rewrite ev2v_ktx_exn in Ev2v_n. inversion Ev2v_n.\n  - destruct Q as [K [? [? [? ?]]]]. subst.\n    eapply sss_ktx_inv in Step_Sn; try reflexivity.\n    2:{ inversion 1. }\n    destruct Step_Sn as [? [Step_Sn ?]]. inversion Step_Sn; subst.\n    2:{ subst. match goal with [H : sss _ ?t (exp_val _) _ _ _ |- _ ] => inversion H end. }\n    eapply ev2v_S with (n := n) in Ev2v_Sn as [? [? [? ?]]]; try apply Ev2v_n. subst.\n    repeat rewrite ennr_mul_1_l. repeat split. assumption.\n}\n{\ndestruct N as [|N].\n1:{\n  destruct (exp_val_dec e) as [[v ?]|].\n  + subst. repeat rewrite μTV_val. apply ennr_le_refl.\n  + rewrite μTV_O_nonval by assumption. apply ennr_le_0.\n}\ndestruct (exp_val_dec e) as [[v ?]|Notval_e].\n1:{ subst. repeat rewrite μTV_val. apply ennr_le_refl. }\ndestruct (exp_ktx_exn_dec e) as [[K ?]|Notexn_e].\n1:{ subst. repeat rewrite <-μTV_exn. apply ennr_le_refl. }\ndestruct (sss_exp_dec N e) as [ Step_e_N | Stop_e_N ].\n2:{\n  rewrite <- μTV_stuck_S with (N := N). 1:{apply ennr_le_0. }\n  + split; assumption.\n  + assumption.\n}\nspecialize (Step_e_N entropy0) as [t' [e' [w Step_e_N]]].\napply sss_quadfurcate in Step_e_N.\ndestruct Step_e_N as [ [Step_e_N Hw] | [ Step_e_N | [ Step_e_N | Step_e_N ]] ].\n+ erewrite sss_preserves_μTV with (N := N) by apply Step_e_N.\n  erewrite sss_preserves_μTV with (N := S N) by apply Step_e_N.\n  cbn. apply ennr_mult_le_compat_r. apply μTV_monotone_S with (N := N).\n+ destruct Step_e_N as [K [f [? [? [? [? ?]]]]]]. subst.\n  erewrite sss_preserves_μTV with (N := N). \n  2:{ intro. apply ktx_congruence. apply sss_sample_query. assumption. }\n  destruct (ennr_0_lt_dec (μNS (S N) f)) as [NS_SN|NS_SN].\n  1:{\n    erewrite sss_preserves_μTV with (N := S N). \n    2:{ intro. apply ktx_congruence. apply sss_sample_query. assumption. }\n    unfold unif_score_meas. apply ennr_mult_le_compat.\n    + apply μTV_monotone_S with (N := N).\n    + apply ennr_mult_inv_le_compat.\n      apply μNS_antitone_S with (n := N). (* apply mutual induction hypothesis *)\n  }\n  unfold unif_score_meas.\n  replace (μTV N (ktx_plug K f) V) with 0.\n  1:{ rewrite ennr_mul_0_l. apply ennr_le_0. }\n  apply ennr_le_0_is_0.\n  rewrite NS_SN. eapply ennr_le_trans. 1:{ apply μTV_monotone_S with (N := N). }\n  eapply ennr_le_trans. 1:{ apply μTV_le_μNS. }\n  apply μNS_ktx_plug_le.\n+ destruct Step_e_N as [K [f [? [NS_N [? [? ?]]]]]]. subst.\n  assert (0 = μNS (S N) f) as NS_SN.\n  1:{ apply ennr_le_0_is_0. rewrite NS_N.\n      apply μNS_antitone_S with (n := N). (* apply mutual induction hypothesis *) }\n  erewrite sss_preserves_μTV with (N := N).\n  2:{ intro t. apply ktx_congruence. apply sss_sample_query_exn. apply NS_N. }\n  erewrite sss_preserves_μTV with (N := S N).\n  2:{ intro t. apply ktx_congruence. apply sss_sample_query_exn. apply NS_SN. }\n  cbn. repeat rewrite ennr_mul_1_r. apply μTV_monotone_S with (N := N).\n+ destruct Step_e_N as [K [? [? [? ?]]]]. subst.\n  rewrite ktx_sample_unif_preserves_μTV with (N := N).\n  rewrite ktx_sample_unif_preserves_μTV with (N := S N).\n  apply integrand_extensionality_le. intro t.\n  apply ennr_mult_le_compat_r. apply μTV_monotone_S with (N := N).\n}\nQed.\n\nLemma μTV_monotone e A N' N :\nN' <= N → μTV N' e A ≤ μTV N e A.\nProof.\ninduction 1 as [ | ? ? IH ] ; intros.\n+ apply ennr_le_refl.\n+ eapply ennr_le_trans; [ apply IH | ].\n  apply μTV_monotone_S.\nQed.\n\nLemma μNS_antitone e N' N :\nN' <= N → μNS N e ≤ μNS N' e.\nProof.\ninduction 1 as [ | ? ? IH ] ; intros.\n+ apply ennr_le_refl.\n+ eapply ennr_le_trans ; [ | apply IH ].\n  apply μNS_antitone_S.\nQed.\n\nLemma μNT_antitone e : antitone (λ n, μNT n e full_event).\nProof.\nunfold antitone. intros N' N HN.\nrepeat rewrite μNT_as_diff.\napply ennr_minus_le_compat.\n4:{ apply μNS_antitone. omega. }\n3:{ apply μTV_monotone. omega. }\n2:{ apply μTV_le_μNS. }\n1:{ apply μTV_le_μNS. }\nQed.\n\nLemma sss_preserves_μTV_sup e e' w:\n(∀ N t, sss (eval N) t e t e' w) →\n∀ V, μTV_sup e V = unif_score_meas w (μTV_sup e') V.\nProof.\nintros Hsss V. simpl unif_score_meas. unfold μTV_sup.\nrewrite <- sup_linear_mult_r.\n2:{\n  intro H. exfalso. specialize (Hsss O entropy0).\n  apply sss_weight_finite in Hsss. rewrite H in Hsss. \n  apply ennr_lt_irrefl in Hsss. auto.\n}\nrewrite sup_S. 2:{ apply μTV_monotone_S. }\napply sup_extensionality. intro n.\nerewrite sss_preserves_μTV by eapply Hsss.\nreflexivity.\nQed.\n\nLemma sss_preserves_μNS_inf e e' w:\n(∀ N t, sss (eval N) t e t e' w) →\nμNS_inf e = μNS_inf e' * w.\nProof.\nintros Hsss. unfold μNS_inf.\nrewrite <- inf_linear_mult_r.\n2:{\n  intro.\n  pose (inf_is_glb (λ N, μNS N e')) as Q.\n  destruct Q as [Q _]. unfold is_lower_bound in Q.\n  eapply ennr_le_lt_trans.\n  1:{ apply Q. exists O. rewrite μNS_O. reflexivity. }\n  simpl. trivial.\n}\nrewrite inf_S. 2:{ apply μNS_antitone_S. }\napply inf_extensionality. intro n.\nerewrite sss_preserves_μNS by eapply Hsss.\nreflexivity.\nQed.\n\nLemma ktx_sample_unif_preserves_μTV_sup K V :\nμTV_sup (ktx_plug K (exp_sample val_unif)) V =\n∫ (λ r, μTV_sup (ktx_plug K (val_real r)) V * if (Rinterval_dec 0 1 r) then 1 else 0) lebesgue_measure.\nProof.\nunfold μTV_sup.\nrewrite sup_S by apply μTV_monotone_S.\nsetoid_rewrite ktx_sample_unif_preserves_μTV.\nrewrite interchange_sup_integration.\n2:{\n  intro r. intros n n' Nle.\n  apply ennr_mult_le_compat_r. apply μTV_monotone. omega.\n}\nintegrand_extensionality r.\nrewrite sup_linear_mult_r.\n2:{ intro H. exfalso. destruct (Rinterval_dec 0 1 r); inversion H. }\nreflexivity.\nQed.\n\nLemma ktx_sample_unif_preserves_μNS_inf K :\nμNS_inf (ktx_plug K (exp_sample val_unif)) =\n∫ (λ r, μNS_inf (ktx_plug K (val_real r)) * if (Rinterval_dec 0 1 r) then 1 else 0) lebesgue_measure.\nProof.\nunfold μNS_inf.\nrewrite inf_S by apply μNS_antitone_S.\nsetoid_rewrite ktx_sample_unif_preserves_μNS.\nrewrite interchange_inf_integration.\n2:{\n  intro r. intros n n' Nle.\n  apply ennr_mult_le_compat_r. apply μNS_antitone. omega.\n}\nintegrand_extensionality r.\nrewrite inf_linear_mult_r.\n2:{\n  intro H. eapply ennr_le_lt_trans; [apply μNS_inf_le_1|]. simpl. trivial.\n}\nreflexivity.\nQed.\n\nLemma μTV_has_lim e V : has_lim (λ n, μTV n e V).\nProof.\napply monotone_has_lim. unfold monotone. apply μTV_monotone.\nQed.\n\nLemma μNS_has_lim e : has_lim (λ n, μNS n e).\nProof.\napply antitone_has_lim. unfold antitone. apply μNS_antitone.\nQed.\n\nLemma μNT_has_lim e : has_lim (λ n, μNT n e full_event).\nProof.\napply antitone_has_lim. unfold antitone. apply μNT_antitone.\nQed.\n\nLtac generalize_has_lim := repeat let HL := fresh \"HasLim\" in\nmatch goal with\n| [ |- context[monotone_has_lim ?f ?H] ] =>\n  generalize (monotone_has_lim f H) as HL; intro HL\n| [ |- context[antitone_has_lim ?f ?H] ] =>\n  generalize (antitone_has_lim f H) as HL; intro HL\n| [ |- context[prod_has_lim ?f ?g ?Hf ?Hg] ] =>\n  generalize (prod_has_lim f g Hf Hg) as HL; intro HL\n| [ |- context[inv_has_lim ?f ?H] ] =>\n  generalize (inv_has_lim f H) as HL; intro HL\n| [ |- context[μNS_has_lim ?e] ] =>\n  generalize (μNS_has_lim e) as HL; intro HL\n| [ |- context[μTV_has_lim ?e ?V] ] =>\n  generalize (μTV_has_lim e V) as HL; intro HL\n| [ |- context[μNT_has_lim ?e] ] =>\n  generalize (μNT_has_lim e) as HL; intro HL\nend.\n\nLemma ktx_sample_query_preserves_μTV_sup e :\n0 < μNS_inf e →\n∀ K V,\nμTV_sup (ktx_plug K (exp_sample (val_query e))) V =\nμTV_sup (ktx_plug K e) V * / μNS_inf e.\nProof.\nintro NS_e. intro K. intro V.\nunfold μTV_sup, μNS_inf.\nrewrite sup_S. 2:{ apply μTV_monotone_S. }\nunshelve erewrite sup_is_lim with (f := λ n, μTV (S n) _ _).\n1:{ unfold monotone. intros. apply μTV_monotone. omega. }\ngeneralize_has_lim.\nunshelve erewrite sup_is_lim with (f := λ n, μTV n (ktx_plug K e) V).\n1:{ unfold monotone. apply μTV_monotone. }\ngeneralize_has_lim.\nunshelve erewrite inf_is_lim with (f := λ n, μNS n e).\n1:{ unfold antitone. apply μNS_antitone. }\ngeneralize_has_lim.\nunshelve erewrite <-lim_of_inv.\ngeneralize_has_lim.\nunshelve erewrite <-lim_of_product.\n1:{\n  apply prod_has_lim.\n  + apply μTV_has_lim.\n  + apply inv_has_lim. apply μNS_has_lim.\n}\n3:{\n  intro H. exfalso. unshelve erewrite lim_of_inv' in H.\n  1:{ apply μNS_has_lim. }\n  apply ennr_inv_is_zero in H.\n  rewrite <-inf_is_lim' in H. 2:{ unfold antitone. apply μNS_antitone. }\n  specialize (μNS_inf_le_1 e) as H'. unfold μNS_inf in H'.\n  rewrite H in H'. repeat match goal with\n  | [ H: ∞ ≤ 1 |- _ ] => inversion H; clear H\n  | [ H: ∞ < 1 |- _ ] => inversion H; clear H\n  | [ H: ∞ = 1 |- _ ] => inversion H; clear H\n  end.\n}\n2:{\n  intro. unshelve erewrite lim_of_inv'. \n  1:{ apply μNS_has_lim. }\n  apply ennr_inv_lt_infinity.\n  rewrite <-inf_is_lim'. 2:{ unfold antitone. apply μNS_antitone. }\n  apply NS_e.\n}\ngeneralize_has_lim.\napply lim_extensionality. intro n. assert (0 < μNS n e).\n1:{\n  unfold μNS_inf in NS_e.\n  specialize (inf_is_glb (λ n, μNS n e)) as Q. destruct Q as [Q _].\n  unfold is_lower_bound in Q. eapply ennr_lt_le_trans; [apply NS_e|].\n  apply Q. repeat eexists.\n}\nerewrite sss_preserves_μTV.\n2:{ intro. apply ktx_congruence. apply sss_sample_query. assumption. }\ncbn. reflexivity.\nQed.\n\nLemma ktx_sample_query_preserves_μNS_inf e :\n0 < μNS_inf e →\n∀ K,\nμNS_inf (ktx_plug K (exp_sample (val_query e))) =\nμNS_inf (ktx_plug K e) * / μNS_inf e.\nProof.\nintro NS_e. intro K.\nunfold μNS_inf.\nrewrite inf_S. 2:{ apply μNS_antitone_S. }\nunshelve erewrite inf_is_lim with (f := λ n, μNS (S n) _).\n1:{ unfold antitone. intros. apply μNS_antitone. omega. }\ngeneralize_has_lim.\nunshelve erewrite inf_is_lim with (f := λ n, μNS n (ktx_plug K e)).\n1:{ unfold antitone. apply μNS_antitone. }\ngeneralize_has_lim.\nunshelve erewrite inf_is_lim with (f := λ n, μNS n e).\n1:{ unfold antitone. apply μNS_antitone. }\ngeneralize_has_lim.\nrewrite <-lim_of_inv.\nunshelve erewrite <-lim_of_product.\n1:{\n  apply prod_has_lim.\n  + apply μNS_has_lim.\n  + apply inv_has_lim. apply μNS_has_lim.\n}\n3:{\n  intro H. exfalso. rewrite lim_of_inv in H. apply ennr_inv_is_zero in H.\n  rewrite <-inf_is_lim' in H. 2:{ unfold antitone. apply μNS_antitone. }\n  specialize (μNS_inf_le_1 e) as H'. unfold μNS_inf in H'.\n  rewrite H in H'. repeat match goal with\n  | [ H: ∞ ≤ 1 |- _ ] => inversion H; clear H\n  | [ H: ∞ < 1 |- _ ] => inversion H; clear H\n  | [ H: ∞ = 1 |- _ ] => inversion H; clear H\n  end.\n}\n2:{\n  intro. rewrite lim_of_inv. apply ennr_inv_lt_infinity.\n  rewrite <-inf_is_lim'. 2:{ unfold antitone. apply μNS_antitone. }\n  apply NS_e.\n}\ngeneralize_has_lim. apply lim_extensionality. intro n.\nassert (0 < μNS n e).\n1:{\n  unfold μNS_inf in NS_e.\n  specialize (inf_is_glb (λ n, μNS n e)) as Q. destruct Q as [Q _].\n  unfold is_lower_bound in Q. eapply ennr_lt_le_trans; [apply NS_e|].\n  apply Q. repeat eexists.\n}\nerewrite sss_preserves_μNS.\n2:{ intro. apply ktx_congruence. apply sss_sample_query. assumption. }\ncbn. reflexivity.\nQed.\n\nFact sss_antitone_S N e :\n∀ t t' e' w₁, sss (eval (S N)) t e t' e' w₁ →\n∃ e₀ w₀, sss (eval N) t e t' e₀ w₀.\nProof.\napply sss_antitone_S_aux.\napply μNS_antitone_S.\nQed.\n\nFact stop_monotone_S N e : stop N e → stop (S N) e.\nProof.\napply stop_monotone_S_aux.\napply μNS_antitone_S.\nQed.\n\nFact stop_monotone N e : stop N e → ∀ N', N <= N' → stop N' e.\nProof.\nintros Stop N'. induction 1.\n+ apply Stop.\n+ apply stop_monotone_S. assumption.\nQed.\n\nLemma μTV_stuck N e V :\nstop N e →\n(∀ v, e = exp_val v → False) →\n∀ N', 0 = μTV N' e V.\nProof.\nintros.\ndestruct (le_dec N' (S N)).\n+ apply ennr_le_antisym. 1:{ apply ennr_le_0. }\n  erewrite μTV_stuck_S by eassumption.\n  apply μTV_monotone. omega.\n+ destruct N'. 1:{ exfalso. omega. }\n  apply stop_monotone with (N' := N') in H. 2:{ omega. }\n  erewrite <- μTV_stuck_S by assumption.\n  ring.\nQed.\n\nLemma μTV_sup_stuck N e V :\nstop N e →\n(∀ v, e = exp_val v → False) →\n0 = μTV_sup e V.\nProof.\nintros.\nunfold μTV_sup. erewrite sup_of_constant. 1:{ reflexivity. }\nintro. apply eq_sym.\neapply μTV_stuck; eassumption.\nQed.\n\nLemma μTV_sup_le_μNS_inf e V :\nμTV_sup e V ≤ μNS_inf e.\nProof.\nunfold μTV_sup, μNS_inf. apply sup_le_inf.\n3:{ intro. apply μTV_le_μNS. }\n2:{ repeat intro. apply μNS_antitone. omega. }\n1:{ repeat intro. apply μTV_monotone. omega. }\nQed.\n", "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/Lang/Monotonicity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2756849589374826}}
{"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_Ф_sendAcceptAndReturnChange128 (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 sendAcceptAndReturnChange128(uint64 fee) private { \n    tvm.rawReserve(address(this).balance - fee, 0); \n    IParticipant(msg.sender).receiveAnswer{value: 0, bounce: false, flag: 128}(STATUS_SUCCESS, 0); \n  } *) \n\nLemma DePoolContract_Ф_sendAcceptAndReturnChange128_exec : forall (Л_fee: XInteger64) (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 , 128) $} |}  in \nexec_state ( ↓ DePoolContract_Ф_sendAcceptAndReturnChange128 Л_fee ) l =  \n{$ l With (VMState_ι_messages ,  newMessage :: oldMessages) ;\n                 (VMState_ι_reserved ,  ( eval_state tvm_balance l ) - Л_fee)$} .  \nProof.\n  intros. destruct l. auto. \nQed. \n\nLemma DePoolContract_Ф_sendAcceptAndReturnChange128_eval : forall (Л_fee: XInteger64)\n                                                  ( l: Ledger ) ,\neval_state ( ↓ DePoolContract_Ф_sendAcceptAndReturnChange128 Л_fee ) l = I .\nProof.\n  intros. destruct l. auto. \nQed. \n\n\n\nEnd DePoolContract_Ф_sendAcceptAndReturnChange128.", "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_sendAcceptAndReturnChange128.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.27567737816363747}}
{"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_granule_delegate_spec (addr: Z64) (adt: RData) : option (RData * Z64) :=\n    match addr with\n    | VZ64 addr =>\n      rely Z.land (r_scr_el3 (cpu_regs (priv adt))) SCR_WORLD_MASK =? SCR_REALM_WORLD;\n      rely prop_dec ((buffer (priv adt)) @ SLOT_DELEGATED = None);\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        rely prop_dec ((gpt_lk (share adt)) @ gidx = None);\n        rely prop_dec ((gpt (share adt)) @ gidx = false);\n        if g_tag (ginfo gn) =? GRANULE_STATE_NS then\n          rely prop_dec (gtype gn = GRANULE_STATE_NS);\n          let e := EVT CPU_ID (ACQ gidx) in\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}\n          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' {glock: Some CPU_ID})) in\n          Some (adt {log: e' :: e2 :: e1 :: e :: (log adt)}\n                    {share: (share adt) {gs: (gs (share adt)) # gidx == (g' {gtype: GRANULE_STATE_DELEGATED})}\n                                        {gpt: (gpt (share adt)) # gidx == true}}\n                    {priv: (priv adt) {cpu_regs: regs'}},\n                VZ64 0)\n        else\n          let e := EVT CPU_ID (ACQ gidx) in\n          let e' := EVT CPU_ID (REL gidx (gn {glock: Some CPU_ID})) in\n          Some (adt {log: e' :: e :: (log adt)}, VZ64 1)\n      else Some (adt, VZ64 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/RmiSMC/Specs/smc_granule_delegate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2756773725508728}}
{"text": "Require Import Lia.\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 DenseOrder.\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 Local.\nRequire Import Thread.\n\nRequire Import PromiseConsistent.\n\nSet Implicit Arguments.\n\n\nModule PFCommon.\n  Inductive sim_local (lc_src lc_tgt: Local.t): Prop :=\n  | sim_local_intro\n      (TVIEW: (Local.tview lc_src) = (Local.tview lc_tgt))\n      (PROMISES: (Local.promises lc_src) = Memory.bot)\n  .\n  #[global]\n  Hint Constructors sim_local: core.\n\n  Definition vals_incl (mem1 mem2: Memory.t): Prop :=\n    forall loc from to val released\n      (GET1: Memory.get loc to mem1 = Some (from, Message.full val released)),\n    exists f t r,\n      <<GET2: Memory.get loc t mem2 = Some (f, Message.full val r)>>.\n\n  #[global]\n  Program Instance vals_incl_PreOrder: PreOrder vals_incl.\n  Next Obligation.\n    ii. eauto.\n  Qed.\n  Next Obligation.\n    ii. exploit H; eauto. i. des. eauto.\n  Qed.\n\n\n  (* lemmas on step *)\n\n  Lemma fence_step\n        lc1_src\n        lc1_tgt sc1 ordr ordw lc2_tgt sc2\n        (LOCAL1: sim_local lc1_src lc1_tgt)\n        (STEP_TGT: Local.fence_step lc1_tgt sc1 ordr ordw lc2_tgt sc2):\n    exists lc2_src,\n      <<STEP_SRC: Local.fence_step lc1_src sc1 ordr ordw lc2_src sc2>> /\\\n      <<LOCAL2: sim_local lc2_src lc2_tgt>>.\n  Proof.\n    destruct lc1_src, lc1_tgt. inv LOCAL1. inv STEP_TGT. ss.\n    subst. esplits.\n    - econs; eauto. ii. ss.\n      rewrite Memory.bot_get in *. ss.\n    - econs; eauto.\n  Qed.\n\n  Lemma failure_step\n        lc1_src lc1_tgt\n        (LOCAL1: sim_local lc1_src lc1_tgt)\n        (STEP_TGT: Local.failure_step lc1_tgt):\n    <<STEP_SRC: Local.failure_step lc1_src>>.\n  Proof.\n    destruct lc1_src, lc1_tgt. inv LOCAL1. inv STEP_TGT. ss.\n    subst. econs; eauto.\n    eapply Local.bot_promise_consistent; ss.\n  Qed.\nEnd PFCommon.\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/invariant/PFCommon.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.27567736693810796}}
{"text": "(** This file is a tutorial to learn how to use the Cerise Program Logic within Coq.\n    We will use the modularity of the program logic to use the specification of\n    a macro in a program, and show how the macro can be linked via a linking table.\n\n    Prerequisites:\n    We assume the user has already followed the first part of the tutorial\n    \"cerise_tutorial.v\" and is able to prove the specification of a program\n    with known code using the Cerise Proof Mode. *)\n\nFrom iris.proofmode Require Import tactics.\nFrom cap_machine Require Import rules proofmode macros_new macros_helpers.\nOpen Scope Z_scope.\n\nSection increment_macro.\n  Context {Σ:gFunctors} {memg:memG Σ} {regg:regG Σ}\n          `{MP: MachineParameters}.\n\n  (** The increment macro is a macro that takes a register r (r ≠ r_env), which\n      contains a capability C with a permission p ≤ RW, that points to\n      an integer n. The macro increments the value of the integer.\n      The macro uses the register r_env to perform the arithmetic, and clear\n      the result of the register.\n   *)\n  Definition incr_instrs r r_env : list Word :=\n    encodeInstrsW [\n      Load r_env r ;\n      Add r_env r_env 1;\n      Store r r_env;\n      Mov r_env 0 ].\n\n  (** Specification of the macro. The proof is an optional exercise. *)\n  Lemma incr_macro_spec\n    p_pc b_pc e_pc a_prog (* pc *)\n    r r_env (* registers of the macro *)\n    p (e b a : Addr) n (* capability *)\n    w_env\n    φ :\n\n    let e_prog := (a_prog ^+ length (incr_instrs r r_env))%a in\n    r <> r_env ->\n\n    ExecPCPerm p_pc ->\n    SubBounds b_pc e_pc a_prog e_prog ->\n\n    b <= a < e -> (* a is in the bounds of the capability *)\n    writeAllowed p = true -> (* p can Read/Write *)\n\n    ⊢ ( PC ↦ᵣ WCap p_pc b_pc e_pc a_prog (* PC points to the prog*)\n        ∗ codefrag a_prog (incr_instrs r r_env) (* the prog instruction start at a_prog *)\n        ∗ r ↦ᵣ WCap p b e a (* r contains the capability *)\n        ∗ r_env ↦ᵣ w_env (* ownership of r_env *)\n        ∗ a ↦ₐ WInt n (* content of a, which is an integer *)\n         ∗ ▷ ( PC ↦ᵣ WCap p_pc b_pc e_pc e_prog\n               ∗ r ↦ᵣ WCap p b e a\n               ∗ r_env ↦ᵣ WInt 0 (* cleared register *)\n               ∗ a ↦ₐ WInt (n+1) (* incremented value *)\n                ∗ codefrag a_prog (incr_instrs r r_env)\n               -∗ WP Seq (Instr Executable) {{ φ }}))\n       -∗ WP Seq (Instr Executable) {{ φ }}%I.\n  Proof.\n  (* FILL IN HERE *)\n  Admitted.\n\n  (** The increment macro is just a list of instructions. In particular,\n      it can be used as a part of a bigger list of instructions.\n      The specification assumes that the PCC points to the first address of the\n      macro, and the list of instructions is _included_ into the bounds of the\n      PCC: thus, the specification can be used in the proof of the specification\n      of a bigger program.\n\n      The macros are a way to define the program modularly.\n      For such short macro, the modularity is a bit \"too much\", but dealing\n      with larger and complex macros (e.g. involving a loop), this modularity\n      is necessary. *)\n\n  (** The following is a very simple example of program that uses the macro. The\n      program assumes that R0 contains a writing capability pointing to the\n      memory. It initializes the value of this memory address at 0, calls the\n      increment macro to increment the value, and finally loads the\n      incremented value in the register R1.\n\n      The reader may notice 3 blocks of instructions, separated by the `++`\n      operator. The proof will leverage this block separation using new\n      `focus_block` tactics, detailled in `proofmode.md`, section `Focusing a\n      sub-block`. They allow us to focus on a block, prove its specification\n      locally, and then continue the proof of the global program.\n      *)\n  Definition prog_instrs: list Word :=\n    encodeInstrsW [Store r_t0 0 ] ++\n            incr_instrs r_t0 r_t1 ++\n            encodeInstrsW [Load r_t1 r_t0 ].\n\n\n  Lemma prog_spec\n    p_pc b_pc e_pc a_prog (* pc *)\n    p (e b a : Addr) w (* capability *)\n    w_env\n    φ :\n\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\n    b <= a < e -> (* a is in the bounds of the capability *)\n    writeAllowed p = true -> (* p can Read/Write *)\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_t0 ↦ᵣ WCap p b e a (* r_t0 contains the capability *)\n        ∗ r_t1 ↦ᵣ w_env (* ownership of r_t1 *)\n        ∗ a ↦ₐ w (* content of a *)\n         ∗ ▷ ( PC ↦ᵣ WCap p_pc b_pc e_pc e_prog\n               ∗ r_t0 ↦ᵣ WCap p b e a (* r_t0 contains the capability *)\n               ∗ r_t1 ↦ᵣ WInt 1 (* ownership of r_t1 *)\n               ∗ a ↦ₐ WInt 1 (* incremented value *)\n               ∗ codefrag a_prog prog_instrs\n               -∗ WP Seq (Instr Executable) {{ φ }}))\n       -∗ WP Seq (Instr Executable) {{ φ }}%I.\n  Proof.\n  intros * Hpc_perm Hpc_bounds Ha_bounds Hperm.\n  iIntros \"(HPC& Hprog& Hr& Hrenv& Ha& Hcont)\".\n\n  (* 1 - prepare the assertions for the proof *)\n  subst e_prog; simpl.\n  (* Derives the facts from the codefrag *)\n  simpl in *.\n  (* We use the new tactic to focus on the first block. *)\n  (* Initialisation block *)\n  focus_block_0 \"Hprog\" as \"Hintro\" \"Hnext\".\n  iInstr \"Hintro\";[by rewrite withinBounds_true_iff|].\n  unfocus_block \"Hintro\" \"Hnext\" as \"Hprog\".\n\n  (* Increment macro *)\n  focus_block 1%nat \"Hprog\" as a_incr Ha_incr \"Hincr\" \"Hnext\".\n  (* We use the specification of the macro. *)\n  iApply (incr_macro_spec with \"[- $HPC $Hincr $Hr $Hrenv $Ha]\");eauto.\n  iNext; iIntros \"(HPC &Hr &Hrenv &Ha &Hincr)\".\n  unfocus_block \"Hincr\" \"Hnext\" as \"Hprog\".\n\n  focus_block 2%nat \"Hprog\" as a_end Ha_end \"Hend\" \"Hnext\".\n  iGo \"Hend\".\n  { split. apply writeA_implies_readA; done. by rewrite withinBounds_true_iff.  }\n  unfocus_block \"Hend\" \"Hnext\" as \"Hprog\".\n\n  (* 3 - continuation *)\n  iApply \"Hcont\".\n  simpl in *.\n  replace (a_end ^+1)%a with (a_prog ^+ 6%nat)%a by solve_addr.\n  iFrame.\n  Qed.\nEnd increment_macro.\n\nSection rclear_macro.\n  Context {Σ:gFunctors} {memg:memG Σ} {regg:regG Σ}\n          `{MP: MachineParameters}.\n\n  (** In this section, we will use a pre-defined macro in Cerise, `rclear`.\n      `rclear` is a macro that clears (puts 0) the list of registers given as\n      argument. *)\n\n  (** The following program assumes that the register r0 contains a capability\n      that points to a buffer with at least 2 integers.\n      It performs the addition of the 2 integers of the buffer and stores the\n      result at the address of the second integer.\n      Then, it clears all the used registers (to remove every trace of\n      the computations) and halts the machine. *)\n  Definition secret_add_instrs: list Word :=\n    encodeInstrsW\n            [Load r_t1 r_t0;\n             Lea r_t0 1;\n             Load r_t2 r_t0;\n             Add r_t1 r_t1 r_t2;\n             Store r_t0 r_t1\n            ] ++\n            rclear_instrs [r_t0;r_t1;r_t2] ++\n            encodeInstrsW [Halt].\n\n  (** **** Exercise 3 --- Secret addition\n        Define the lemma `secret_add_spec` that specifies the program\n        `secret_add_instrs` and prove it.\n\n        Use the tactics to focus and unfocus the block.\n        The specification of the `rclear` macro is `rclear_spec`,\n        defined in the file `theories/examples/macros_new.v`.\n\n        Hint (specification): TODO ???\n        Hint (proof): The specification of `rclear` requires the use of\n        the `big_sepM` resource. The `big_sepM` resource [...] use a map.\n        We urge the reader to search lemmas about `big_sepM` and\n        `gmap`.\n\n        Hint (proof): useful lemmas\n        - big_sepM_insert\n        - big_sepM_insert_delete\n        - delete_insert_ne\n        - delete_empty\n   *)\n\nEnd rclear_macro.\n\nSection linking_table.\n  Context {Σ:gFunctors} {memg:memG Σ} {regg:regG Σ}\n          `{MP: MachineParameters}.\n\n  (* Demo with incr_macro for the setup *)\n\n  (* Exercices using malloc and assert *)\n\nEnd linking_table.\n\n\n  (** Outline\n    2 steps:\n    1. use the macro in the middle of the code (as a real macro)\n    2. capture the macro into a sentry-capability (as a function), and use a linking table\n\n    1.1) Demo\n    Define a program that use this specification that do the following:\n    - takes a capability input\n    - store 0 into it\n    - use the increment macro\n\n    1.2) Exercise\n    Exercise with the rclear macro: specify and prove\n\n    2.1) Demo\n    Same program as 1.1, but the increment macro is reachable via\n    the linking table (instead of inlined).\n    It requires some boilerplate about the linking table and shows\n    how to set it up.\n\n    2.2) Exercise\n    At last exercise, the reader should be able to use the Cerise macros,\n    so why not a program that does the following:\n    - dyn alloc a region of memory with malloc\n    - stores 42 in the last adresse\n    - assert it is 42\n\n    Finally, list the macros available in Cerise *)\n\n\n  (** Now that you are familiar with the Cerise Proofmode,\n      we recommand to try defining a program by yourself, as\n      well as its specification.\n      We also recommand to continue the tutorial with\n      TODO (next file) to learn how to define the specification,\n      how to use the logical relation to reason with unknown code,\n      and how to deal with local encapsulation, using the call macro.\n   *)\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_modularity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.27567241587655955}}
{"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(** %\\subsection*{ extras :  finite\\_misc.v }%*)\nSet Implicit Arguments.\nUnset Strict Implicit.\nRequire Export empty.\nRequire Export conshdtl.\n\n(** - Like before_after, a file with stuff I thought I could use some day but didn't: *)\n\n(* The relation with lists *)\n\nSection list_seq.\n(* We define a list with entries in a setoid *)\nInductive SList (A : Setoid) : Type :=\n  | Snil : SList A\n  | Scons : A -> SList A -> SList A.\n\nFixpoint Length (A : Setoid) (L : SList A) {struct L} : nat :=\n  match L with\n  | Snil => 0\n  | Scons _ L' => S (Length L')\n  end.\n\nFixpoint SList2fun (A : Setoid) (L : SList A) {struct L} :\n seq (Length L) A :=\n  match L return (seq (Length L) A:Type) with\n  | Snil => empty_seq A\n  | Scons a L' => a;; SList2fun L'\n  end.\n\nDefinition SList2seq : forall (A : Setoid) (L : SList A), seq (Length L) A.\nintros.\nred in |- *.\napply (Build_Map (Ap:=SList2fun L)).\nred in |- *.\nintros k k'.\nelim k.\nsimple induction index.\nelim k'.\nsimple induction index0.\nintros.\napply Ap_comp; auto with algebra.\nintros.\ninversion H0.\nelim k'.\nsimple induction index0.\nsimpl in |- *.\nintros.\ninversion H0.\nintros.\napply Ap_comp; auto with algebra.\nDefined.\n\nFixpoint Seq2SList (A : Setoid) (n : nat) {struct n} : \n seq n A -> SList A :=\n  match n return (seq n A -> SList A) with\n  | O => fun b : seq 0 A => Snil A\n  | S m =>\n      fun b : seq (S m) A =>\n      Scons (b (Build_finiteT (le_lt_n_Sm _ _ (le_O_n m))))\n        (Seq2SList (Seqtl b))\n  end.\nEnd list_seq.\n\nSection other.\n(* The next reverses a sequence: 0...n-1 -> n-1...0 *)\nDefinition reverse_seq : forall n : nat, seq n (fin n).\nsimple induction n.\n(* First the case n=0, ie. the empty map *)\napply (Build_Map (Ap:=fun nonexistent_thingy : fin 0 => nonexistent_thingy)).\nred in |- *.\nauto with algebra.\n(* The nonempty case. *)\nintros.\n(* If we have the reversing map X on 0...n0-1 (=(fin n)), the reversing map on 0...n0 *)\n(* can be made thus: we map 0 to n0, and we map m+1 to X(m) *)\napply\n (Build_Map\n    (Ap:=fun finelt : fin (S n0) =>\n         match finelt return (fin (S n0)) with\n         | Build_finiteT x x0 =>\n             match x as x1 return (x1 < S n0 -> fin (S n0)) with\n             | O => fun _ : 0 < S n0 => Build_finiteT (lt_n_Sn n0)\n             | S m =>\n                 fun HSm : S m < S n0 =>\n                 Build_finiteT\n                   (lt_S (index (X (Build_finiteT (lt_S_n m n0 HSm)))) n0\n                      (in_range_prf (X (Build_finiteT (lt_S_n m n0 HSm)))))\n             end x0\n         end)).\nred in |- *.\n(* To prove the fun_compatibility of the newly devised function: *)\nintro x.\ncase x.\nintro x0.\ncase x0.\nintros l y.\ncase y.\nintro x1.\ncase x1. \n(* first the cases where x=0 or y=0 *)\nsimpl in |- *.\ntauto.\nsimpl in |- *.\nintros.\ninversion H.\nsimpl in |- *.\nintros n1 l y.\ncase y.\nintro x1.\ncase x1.\nintros.\ninversion H.\n(* Now the interesting case. Here we make use of the fun_compatibility of X *)\nintros.\ninversion H.\nelim X.\nintros.\nsimpl in |- *.\nred in Map_compatible_prf.\nsimpl in Map_compatible_prf.\napply Map_compatible_prf; auto with algebra.\nDefined.\n\n(* Reverting finite sequences *)\nDefinition reverse (n : nat) (X : Setoid) (f : seq n X) :=\n  comp_map_map f (reverse_seq n):seq n X.\n\n(* Now we can easily cons elements at the right part of a seq: *)\n\nDefinition consr :\n  forall (X : Setoid) (n : nat) (x : X) (f : seq n X), seq (S n) X.\nintros.\nexact (reverse (x;; reverse f)).\nDefined.\nEnd other.", "meta": {"author": "coq-contribs", "repo": "lin-alg", "sha": "74833da8a93b1c4c921d4aaebbc9f7c2a096a5eb", "save_path": "github-repos/coq/coq-contribs-lin-alg", "path": "github-repos/coq/coq-contribs-lin-alg/lin-alg-74833da8a93b1c4c921d4aaebbc9f7c2a096a5eb/extras/finite_misc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.27567241587655955}}
{"text": "Require Import String List.\nImport ListNotations.\n#[ local ]\n Open Scope string.\n\nFrom MetaCoq.Template Require Import All.\n\n(* TODO add another node for embedded terms. This should be a bit more performant when we use predefined terms like \"eq\" since we don't really need to look them up in the environment. *)\nInductive nterm : Type :=\n| nRef : string -> nterm (* turns into tRel, tInd, tConstruct from the normal term type. This needs to looked up in the environment during translation *)\n| nConst : string -> nterm (* turns into tConst from the normal term type. We use the modpath from GenM to build the correct kername *)\n| nHole : nterm\n| nTerm : term -> nterm\n| nProd : string -> nterm -> nterm -> nterm\n| nArr : nterm -> nterm -> nterm\n| nLambda : string -> nterm -> nterm -> nterm\n| nApp : nterm -> list nterm -> nterm\n| nFix : mfixpoint nterm -> nat -> nterm\n| nCase : string -> nat -> nterm -> nterm -> list (nat * nterm) -> nterm.\n\nDefinition nlemma : Type := string * nterm * nterm.\nDefinition lemma : Type := string * term * term.\n\nFixpoint mknArr (nt0: nterm) (nts: list nterm) :=\n  match nts with\n  | [] => nt0\n  | nt :: nts =>\n    nArr nt0 (mknArr nt nts)\n  end.\n\nFixpoint mknArrRev (nts: list nterm) (nt0: nterm) :=\n  match nts with\n  | [] => nt0\n  | nt :: nts => nArr nt (mknArrRev nts nt0)\n  end.\n", "meta": {"author": "uds-psl", "repo": "autosubst-metacoq", "sha": "58249921285be2a13792ead89feb1d95ffdc0ece", "save_path": "github-repos/coq/uds-psl-autosubst-metacoq", "path": "github-repos/coq/uds-psl-autosubst-metacoq/autosubst-metacoq-58249921285be2a13792ead89feb1d95ffdc0ece/src/Nterm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.27564024283741045}}
{"text": "Set Implicit Arguments.\nRequire Import Shared.\nRequire Import LibFix.\nRequire Import JsSemanticsAux JsWf JsWfAux JsSafety JsScopes JsInterpreter.\n\n\n(**************************************************************)\n(** ** Correctness of proto_comp. *)\n\nSection Proto.\n\n(** Termination of [proto_comp] *)\n\nInductive proto_closer : binary (heap * field * loc) :=\n  | proto_closer_next : forall h f (l l':loc),\n      ok_heap h ->\n      ~ indom h l f ->\n      binds h l field_proto l' ->\n      proto_closer (h, f, l') (h, f, l).\n\nLemma proto_closer_wf : wf proto_closer.\nProof.\n  intros [[h f] l]. constructor.\n  intros [[h' f'] l'] H. inverts H as O D B1.\n  lets~ N: ok_heap_protochain B1. inverts N as B2 P.\n    false. forwards*: ok_heap_null B1.\n  forwards E: binds_func_loc B2 B1. subst.\n  clears O B1 B2 D.\n  induction P; constructor; intros [[h2 f2] l2] M; inverts M.\n    false. forwards*: ok_heap_null.\n    forwards E: binds_func_loc H H8. subst*.\nQed.\n\nLemma proto_comp_fix : forall h f l, \n  ok_heap h -> proto_comp h f l = proto_comp_body proto_comp h f l.  \nProof.\n  applys~ (FixFun3_fix_partial proto_closer). apply proto_closer_wf.\n  intros h1 f1 l1 proto_comp1 proto_comp2 O Cont. unfolds.\n  repeat case_if*.\n    sets_eq v: (read h1 l1 field_proto). destruct~ v.\n    applys~ Cont. constructor~. rewrite* binds_equiv_read.\nQed.\n\n(** Correctness and completeness of [proto_comp] *)\n\nHint Constructors proto.\n\nLemma proto_comp_correct : forall h f l l',\n  ok_heap h ->\n  bound h l ->\n  proto_comp h f l = l' -> \n  proto h f l l'.\nProof.\n  introv OK B E. forwards~ PC: ok_heap_protochain_bound B.\n  induction PC.\n   lets (f'&B1): B. rewrite indom_equiv_binds in B1.\n    lets (v&B2): B1. forwards*: ok_heap_null B2.\n   rewrite~ proto_comp_fix in E.\n    unfold proto_comp_body in E.\n    case_if*. subst~.\n    case_if*. subst~.\n    case_if* in E.\n     rewrite~ binds_equiv_read in H.\n      rewrite H in E. rewrite* <- binds_equiv_read in H.\n      apply* proto_next.\n      tests: (l'0 = loc_null).\n        rewrite~ proto_comp_fix in E.\n         unfolds in E. case_if. subst~.\n        apply* IHPC. inverts* PC. apply* binds_bound.\n   false n1.\n    lets (v&B1): B. rewrite indom_equiv_binds in B1.\n    lets (v'&B2): B1. forwards~ B3: ok_heap_protochain B2.\n    inverts* B3. rewrite* indom_equiv_binds.\nQed.\n\nLemma proto_comp_complete : forall h f l l',\n  ok_heap h ->\n  bound h l ->\n  proto h f l l' ->\n  proto_comp h f l = l'.\nProof.\n  introv OK B P. induction P; \n   rewrite* proto_comp_fix; unfold proto_comp_body; case_if*.\n  case_if*.\n  subst. lets (f'&B'): B. rewrite~ indom_equiv_binds in B'.\n   lets (v&B''): B'. forwards*: ok_heap_null B''.\n  case_if*. case_if*. \n    rewrite (binds_read H0).\n     tests: (l' = loc_null).\n       asserts: (l'' = loc_null).\n         apply* proto_func.\n       subst. rewrite* proto_comp_fix. unfold proto_comp_body. case_if*.\n      apply* IHP.\n       forwards*: ok_heap_ok_value H0.\n       inverts* H1. inverts* H2. apply* indom_bound.\n    false n1. rewrite* indom_equiv_binds.\nQed.\n\nEnd Proto.\n\n\n(**************************************************************)\n(** ** Correctness of scope_comp. *)\n\nSection Scopes.\n\n(** Correctness and completeness of [scope_comp] *)\n\nLemma scope_comp_correct : forall h f L l',\n  scope_comp h f L = l' ->\n  ok_heap h ->\n  ok_scope h L ->\n  scopes h f L l'.\nProof.\n  introv E OK OKL.\n  lets~ FOK: ok_scope_all_bound (rm OKL) OK.\n  gen h f L l'. induction L; introv OKL E.\n  inverts E. constructor*. \n  simpls. inverts OKL as (Ba & BL).\n  lets* (l&Hl): proto_defined h f a. apply* indom_bound.\n  assert (forall l', proto_comp h f a = l' -> l = l').\n    introv E'. lets*: proto_comp_correct E'.\n      apply* indom_bound.\n      apply* proto_func.\n  forwards: (rm H); [ reflexivity | ]. subst. case_if*.\n    constructor*.\n     apply* proto_comp_correct.\n     apply* indom_bound.\n    apply* scopes_here.\nQed.\n\nLemma scope_comp_complete : forall h f L l',\n  scopes h f L l' ->\n  ok_heap h ->\n  ok_scope h L ->\n  scope_comp h f L = l'.\nProof.\n  introv Sc OK OKL. forwards~ FOK: ok_scope_all_bound (rm OKL).\n  induction Sc; simpls*.\n  asserts Eq: (proto_comp h f l = l').\n    forwards*: proto_comp_complete H. inverts* H.\n      apply* indom_bound.\n      apply* binds_bound.\n   inverts FOK. rewrite Eq. forwards*: proto_comp_correct Eq. case_if*.\n  inverts FOK. case_if*. false. lets*: proto_comp_complete H.\n  (* LATER: use [case_if* as C] *)\nQed.\n\nEnd Scopes.\n\n\n(**************************************************************)\n(** ** Correctness of getvalue_comp. *)\n\nSection Getvalue.\n\n(** Correctness and completness of [getvalue_comp] *)\n\nLemma getvalue_comp_correct_ref : forall h l f v,\n  getvalue_comp h (Ref l (field_normal f)) = Some v ->\n  ok_heap h ->\n  bound h l ->\n  getvalue h (Ref l (field_normal f)) v.\nProof.\n  introv E OK B. unfolds in E. case_if*.\n  asserts [l' Hl']: (exists l', proto_comp h (field_normal f) l = l').\n    destruct* proto_comp. \n  rewrite Hl' in E. case_if*; inverts~ E.\n    apply* getvalue_ref_null. subst. apply* proto_comp_correct.\n    lets~ M: proto_comp_correct Hl'. applys* getvalue_ref_not_null.\n      applys~ read_binds. apply* proto_indom.\nQed.\n\nLemma getvalue_comp_correct : forall h r v,\n  getvalue_comp h r = Some v ->\n  ok_result h r ->\n  ok_heap h ->\n  getvalue h r v.\nProof.\n  introv E R OK. unfolds getvalue_comp.\n  destruct r as [|[l f]].\n    inverts E. constructor.\n    asserts [f' Hf]: (exists f', f = field_normal f').\n      destruct* f; false.\n     subst. apply* getvalue_comp_correct_ref. case_if*.\n      inverts R as R. inverts* R.\n      apply* indom_bound.\nQed.\n\nLemma getvalue_comp_complete : forall h r v,\n  getvalue h r v ->\n  ok_heap h ->\n  getvalue_comp h r = Some v.\nProof.\n  introv Gv OK. unfold getvalue_comp. induction Gv.\n  fequals.\n  case_if*. forwards* M: proto_comp_complete H.\n    inverts H; tryfalse. apply* binds_bound. applys* binds_bound.\n   rewrite M. case_if*. fequals. applys* binds_read.\n  case_if*. forwards*: proto_comp_complete H. (* ARTHUR: can you factorize the pattern with the other case? *)\n    inverts H; tryfalse. apply* binds_bound.\n   case_if*.\nQed.\n\nEnd Getvalue.\n\n\n(**************************************************************)\n(** ** Lemmas for the correctness of the interpreter *)\n\nSection Correctness.\n\nGlobal Instance out_comparable : Comparable out.\nProof.\n  (* Warning: This proof is classical, and is only there for the proofs.\n      It shouldn't be extracted. *)\n  (* TODO: do we want/need a version that can be extracted? *)\n      (* Martin: I don't thing so for this case: I'm just using it to apply the lemmas `elim_*'. *)\n  applys (@comparable_beq out) (fun (o1 o2 : out) =>\n    If o1 = o2 then true else false). (* todo: remove type annot *)\n  split; introv E.\n   case_if*.\n   subst; case_if*.\nQed.\n\nLemma wrong_not_ret : forall h h' r,\n  wrong h <> out_return h' (ret_result r).\nProof.\n  introv. unfold wrong.\n  destruct Mnostuck; discriminate.\nQed.\n\nLemma ret_not_wrong : forall h h' r,\n  out_return h' (ret_result r) <> wrong h.\nProof. introv E. symmetry in E. forwards*: wrong_not_ret E. Qed.\n\nLemma elim_if_success : forall r0 k h r,\n  if_success r0 k = out_return h r ->\n  (r0 = out_return h r /\\ forall v, r <> ret_result v) \\/\n    exists r1 h0, r0 = out_return h0 (ret_result r1).\nProof.\n  introv E. destruct r0.\n   destruct* r0. inverts E. left. split*. introv. discriminate.\n   simpls. inverts* E.\n   simpls. inverts* E.\nQed.\n\nLemma elim_if_defined : forall A h f r (a : option A),\n  if_defined h a f = r ->\n  a = None \\/ exists b, a = Some b.\nProof. introv E. destruct* a. Qed.\n\nLemma elim_if_success_value : forall r0 k h r,\n  if_success_value r0 k = out_return h r ->\n  (r0 = out_return h r /\\ forall v, r <> ret_result v) \\/\n  (exists v h, r0 = out_return h (ret_result v) /\\ getvalue_comp h v = None) \\/\n  exists v h b, r0 = out_return h (ret_result v) /\\ getvalue_comp h v = Some b.\nProof.\n  introv E.\n  unfolds in E.\n  forwards~ [OK | (v&h'&E')]: elim_if_success E.\n  right. subst. simpls.\n  forwards~ [? | ?]: elim_if_defined E.\n  rewrite H in E. simpls.\n   left*.\n  lets (b&E'): H. right*.\nQed.\n\nLemma elim_if_is_ref : forall h o k r,\n  if_is_ref h o k = r ->\n  ((exists h', wrong h' = r) /\\ exists v, o = result_value v)\n    \\/ exists l f, o = result_ref (Ref l f).\nProof.\n  introv E. destruct* o.\n  inverts E. right. destruct* r0.\nQed.\n\nLemma elim_if_is_null_ref : forall r k1 k2 rf,\n  if_is_null_ref r k1 k2 = rf ->\n  (exists v, r = result_value v) \\/\n  (exists l f, l <> loc_null /\\ r = Ref l f /\\ rf = k2 r) \\/\n  exists f, r = Ref loc_null f /\\ rf = k1 f.\nProof.\n  introv E. destruct r.\n   left*.\n   right. destruct r. simpl in E.\n    case_if.\n     subst*.\n     left*.\nQed.\n\nLemma elim_if_is_field_normal : forall h f k r,\n  if_is_field_normal h f k = r ->\n  (r = wrong h) \\/ exists f', f = field_normal f'.\nProof. introv E. destruct f; simpls*. Qed.\n\nLemma elim_if_eq : forall l0 h o k1 k2 r,\n  if_eq l0 h o k1 k2 = r ->\n  o = None \\/\n  (exists v, o = Some v /\\ r = wrong h) \\/\n  (o = Some (value_loc l0) /\\ r = k1 I) \\/\n  exists l, o = Some (value_loc l) /\\ l <> l0 /\\ r = k2 l.\nProof.\n  introv E. destruct* o.\n  right. destruct v; inverts* E.\n  right. tests: (l0 = l).\n   left. split~. simpl. case_if*.\n   right. exists l. splits~. simpl. case_if*.\nQed.\n\nLemma elim_if_not_eq : forall l0 h o k r,\n  if_not_eq l0 h o k = r ->\n  o = None \\/\n    ((exists h', wrong h' = r) /\\ exists v, o = Some v) \\/\n    exists l, o = Some (value_loc l) /\\ l <> l0.\nProof.\n  introv E.\n  forwards* [eqr | [(v&eqo&eqr) | [(eqo&eqr) | (l&eqo&_&eqr)]]]: elim_if_eq E.\n  substs. simpls.\n  case_if.\n   branch 2. splits*.\n   branch 3. exists l. split~.\nQed.\n\nLemma elim_if_is_string : forall h o k r,\n  if_is_string h o k = r ->\n  o = None \\/\n    ((exists h', wrong h' = r) /\\ exists v, o = Some v) \\/\n    exists s, o = Some (value_string s).\nProof. introv E. destruct* o. right. destruct v; inverts* E. Qed.\n\nLemma elim_if_binds_field : forall f h l k r,\n  if_binds_field f h l k = r ->\n  (r = wrong h /\\ ~indom h l f) \\/\n  (exists v, r = k v /\\ binds h l f v).\nProof.\n  introv E.\n  unfolds in E. case_if* in E.\n  right. eexists. split*.\n  rewrite* binds_equiv_read.\nQed.\n\nLemma elim_if_binds_field_loc : forall f h l k r,\n  if_binds_field_loc f h l k = r ->\n  (r = wrong h /\\ forall l', ~binds h l f (value_loc l')) \\/\n  (exists l', r = k l' /\\ binds h l f (value_loc l')).\nProof.\n  introv E. unfolds in E.\n  lets* [C1 | C2]: elim_if_binds_field E.\n  lets (H&H0): C1. left. split~. introv B.\n    false H0. rewrite* indom_equiv_binds.\n  lets (v&R&B): C2.\n   destruct v; try (\n     left; split~; introv B';\n     forwards~ H: binds_func B B'; discriminate H).\n   right. exists l0. split~.\nQed.\n\nLemma elim_if_boolean : forall h v k1 k2 r,\n  if_boolean h v k1 k2 = r ->\n  (r = wrong h /\\ forall b, v <> value_bool b) \\/\n  (r = k1 I /\\ v = value_bool true) \\/\n  (r = k2 I /\\ v = value_bool false).\nProof.\n  introv E. destruct v; simpls;\n    try (left; subst; split; [reflexivity | discriminate]).\n  right. destruct b; [left* | right*].\nQed.\n\nLemma elim_if_binds_scope_body : forall h l k r,\n  if_binds_scope_body h l k = r ->\n  r = wrong h \\/\n  (indom h l field_body /\\\n    indom h l field_scope /\\\n    exists s f e, read h l field_scope = value_scope s /\\\n    read h l field_body = value_body f e /\\ k s f e = r).\nProof.\n  introv E. unfold if_binds_scope_body in E.\n  lets* [C1 | C2]: elim_if_binds_field E.\n  lets (v&R&B): C2. clear C2.\n  destruct v; try (left~; fail).\n  symmetry in R. lets* [C1 | C2]: elim_if_binds_field R.\n  lets (v&R'&B'): C2. clear C2.\n  destruct v; try (left~; fail).\n  right. splits; try rewrite* indom_equiv_binds.\n  repeat eexists; eauto; rewrite* <- binds_equiv_read; rewrite* indom_equiv_binds.\nQed.\n\nLemma sub_safety : forall h h' s e r,\n    red h s e h' r -> ok_heap h -> ok_scope h s ->\n    ok_heap h' /\\ ok_scope h' s /\\ ok_result h' r.\nProof. intros. splits; apply* safety. Qed.\n\nLemma arguments_comp_correct : forall xs vs lfv,\n  arguments_comp xs vs = lfv ->\n  arguments xs vs lfv.\nProof.\n  induction xs; introv E.\n   simpls. subst. constructors.\n   destruct vs.\n     simpls. rewrite <- E. apply* arguments_nil_values.\n     simpls. rewrite <- E. apply* arguments_cons.\nQed.\n\n\n(**************************************************************)\n(** ** Tactics for the correctness of the interpreter *)\n\nLtac name_heap_write h' :=\n  match goal with  |- context [ write ?h ?l ?f ?v ] =>\n    sets_eq h': (write h l f v) end.\nLtac name_heap_sub_write h' :=\n  match goal with  |- context [ write (write ?h ?l ?f ?v) _ _ _ ] =>\n    sets_eq h': (write h l f v) end.\nLtac name_heap_write_fields h' :=\n  match goal with  |- context [ write_fields ?h ?l ?li ] =>\n    sets_eq h': (write_fields h l li) end.\nLtac name_heap_reserve_local_vars h' :=\n  match goal with  |- context [ reserve_local_vars ?h ?l ?li ] =>\n    sets_eq h': (reserve_local_vars h l li) end.\nLtac name_heap_alloc_obj H h' :=\n  match goal with |- context [ alloc_obj ?h ?l ?l' ] =>\n    sets_eq h': (alloc_obj h l l') end.\nLtac name_heap_write_in H h' :=\n  match goal with  H: context [ write ?h ?l ?f ?v ] |- _ =>\n    sets_eq h': (write h l f v) end.\nLtac name_heap_sub_write_in H h' :=\n  match goal with  H: context [ write (write ?h ?l ?f ?v) _ _ _ ] |- _ =>\n    sets_eq h': (write h l f v) end.\nLtac name_heap_write_fields_in H h' :=\n  match goal with  H: context [ write_fields ?h ?l ?li ] |- _ =>\n    sets_eq h': (write_fields h l li) end.\nLtac name_heap_sub_write_fields_in H h' :=\n  match goal with  H: context [ write_fields (write_fields ?h ?l ?li) _ _ ] |- _ =>\n    sets_eq h': (write_fields h l li) end.\nLtac name_heap_reserve_local_vars_in H h' :=\n  match goal with  H: context [ reserve_local_vars ?h ?l ?li ] |- _ =>\n    sets_eq h': (reserve_local_vars h l li) end.\nLtac name_heap_alloc_obj_in H h' :=\n  match goal with  H: context [ alloc_obj ?h ?l ?l' ] |- _ =>\n    sets_eq h': (alloc_obj h l l') end.\n\n\n(**************************************************************)\n(** ** Correctness of the implementation of operators *)\n\nLemma typeof_comp_correct : forall h v str,\n  typeof_comp h v = Some str ->\n  ok_heap h ->\n  typeof_red h v str.\nProof.\n  introv E OK.\n  destruct v; try (inverts E; constructor).\n  simpl in E. case_if; inverts E.\n   rewrite indom_equiv_binds in i. lets (v&B): i.\n    apply* typeof_red_function. exists* v.\n   lets OKf: ok_heap_function OK. unfolds in OKf.\n   apply* typeof_red_object. introv (v&B). false n.\n    forwards (?&?&?&?&F&?&?): OKf B.\n    rewrite* indom_equiv_binds.\nQed.\n\nInductive proto_closer_for_binary_op_comp : binary (binary_op * heap * value * value) :=\n  | proto_closer_for_binary_op_comp_instanceof : forall h (l1 l2 l3 l4:loc),\n      ok_heap h ->\n      binds h l1 field_normal_prototype (value_loc l3) ->\n      binds h l2 field_proto (value_loc l4) ->\n      l3 <> l4 ->\n      proto_closer_for_binary_op_comp (binary_op_instanceof, h, value_loc l1, value_loc l4) (binary_op_instanceof, h, value_loc l1, value_loc l2).\n\nLemma proto_closer_for_binary_op_comp_wf : wf proto_closer_for_binary_op_comp.\nProof.\n  intros [[[b h] v1] v2]. constructor.\n  intros [[[b' h'] v1'] v2'] H. inverts H as O B1 B2 D.\n  lets~ N: ok_heap_protochain B2. inverts N as B3 P.\n    false. forwards*: ok_heap_null B2.\n  forwards*: binds_func_loc B3 B2. subst.\n  clears O B1 B2 B3 D.\n  induction P; constructor; intros [[[b'' h''] v1''] v2''] M; inverts M.\n    false. forwards*: ok_heap_null.\n    forwards E: binds_func_loc H H9. subst*.\nQed.\n\nLemma binary_op_comp_fix : forall h op v1 v2,\n  ok_heap h -> binary_op_comp op h v1 v2 = binary_op_comp_body binary_op_comp op h v1 v2.\nProof.\n  introv O. applys~ (FixFun4_fix_partial proto_closer_for_binary_op_comp (fun _ h _ _ => ok_heap h)).\n    apply proto_closer_for_binary_op_comp_wf.\n  introv O1 Cont. unfolds. destruct~ x1.\n    repeat case_if~. destruct~ x3. simpl. destruct~ x4.\n    case_if~; symmetry; case_if~.\n    sets_eq v: (read x2 l field_normal_prototype). destruct~ v.\n    sets_eq v: (read x2 l0 field_proto). destruct~ v.\n    simpls. repeat case_if~.\n    rewrite~ Cont.\n    apply~ proto_closer_for_binary_op_comp_instanceof.\n      rewrite* binds_equiv_read.\n      rewrite* binds_equiv_read.\n      auto*.\nQed.\n\nLemma binary_op_comp_correct : forall b h v1 v2 r,\n  binary_op_comp b h v1 v2 = Some r ->\n  ok_heap h -> ok_value h v1 -> ok_value h v2 ->\n  binary_op_red b h v1 v2 r.\nProof.\n  introv E OK O1 O2. rewrite~ binary_op_comp_fix in E.\n  destruct b; simpls.\n  (* add *)\n  destruct v1; destruct v2; simpls; tryfalse.\n    inverts E. constructor*.\n    inverts E. constructor*.\n  (* mult *)\n  destruct v1; destruct v2; simpls; tryfalse.\n   inverts E. constructor*.\n  (* div *)\n  destruct v1; destruct v2; simpls; tryfalse.\n   inverts E. constructor*.\n  (* equal *)\n  case_if in E as B; tryfalse. lets (B1&B2): a. inverts~ E.\n  rewrite~ value_compare_correct. constructor~.\n  \n  (* instanceof *)\n  destruct v1; simpls; tryfalse.\n  apply* binary_op_red_instanceof.\n  case_if in E.\n   inverts E. apply* instanceof_red_value.\n   inverts* O2.\n    unfolds in H. rewrite~ indom_equiv_binds in H.\n    lets (v0 & B): (rm H).\n    lets~ N: ok_heap_protochain B.\n    clear n v0 B. induction N.\n     false. case_if in E.\n      set_eq v: (read h l field_normal_prototype) in E.\n      destruct v; tryfalse. simpl in E. case_if in E.\n      rewrite~ indom_equiv_binds in i0. lets (v & B): i0.\n      forwards*: ok_heap_null B.\n     gen E; intro E. case_if in E. (* FIXME: It seems there is a bug in `case_if' that make it ignore what stands after a `in' argument. *)\n      set_eq v: (read h l field_normal_prototype) in E.\n      destruct v; simpls; tryfalse. case_if in E.\n      set_eq v: (read h l0 field_proto) in E.\n      destruct v; simpls; tryfalse.\n      asserts: (l2 = l').\n        applys~ binds_func_loc H.\n        rewrite* binds_equiv_read.       \n      subst l'. case_if in E.\n       inverts E. subst. apply* instanceof_red_true.\n         rewrite* binds_equiv_read.\n       apply* instanceof_red_trans.\n         rewrite* binds_equiv_read.\n        tests: (l2 = loc_null).\n          clear IHN. rewrite~ binary_op_comp_fix in E.\n           simpl in E. case_if in E.\n            inverts E. constructor~.\n            false n0. constructor.\n          apply* IHN; clear IHN.\n           rewrite~ binary_op_comp_fix in E.\n           simpl in E. case_if in E.\n            false. inverts~ b.\n            apply* E.\n\n  (* in *)\n  destruct v1; destruct v2; simpls; tryfalse. inverts E.\n  inverts O2.\n   inverts H.\n    apply* binary_op_red_in.\n      constructor.\n    case_if.\n     rewrite~ proto_comp_fix. unfold proto_comp_body.\n     case_if. rewrite decide_spec. fold_bool. apply* eqb_eq.\n   apply* binary_op_red_in.\n     apply* proto_comp_correct.\n      apply* indom_bound.\n     rewrite decide_spec. case_if*.\n      rewrite* eqb_eq.\n      rewrite* eqb_neq.\nQed.\n\nLemma unary_op_comp_correct : forall b h v r,\n  unary_op_comp b h v = Some r ->\n  unary_op_red b h v r.\nProof.\n  introv E.\n  destruct b; simpls; tryfalse.\n\n  (* not *)\n  destruct v; tryfalse.\n  inverts~ E. apply* unary_op_red_not.\n\n  (* void *)\n  inverts~ E. apply* unary_op_red_void.\nQed.\n\n\n(**************************************************************)\n(** ** Correctness of the interpreter *)\n\nLemma run_list_value_add_value : forall m s h0 es vs vs0 k k' r,\n  run_list_value m h0 s (vs ++ vs0) es k = r ->\n  (forall h vs', k' h vs' = k h (LibList.rev vs0 ++ vs')) ->\n  run_list_value m h0 s vs es k' = r.\nProof.\n  induction m.\n    simpl. intros; subst~.\n    introv E T. destruct es; simpls.\n     rewrite <- E. rewrite rev_app. apply* T.\n    destruct~ run. destruct~ r0. simpls.\n     destruct~ getvalue_comp. simpls. apply* IHm.\nQed.\n\nTheorem run_correct : forall m h s e h' v,\n  run m h s e = out_return h' (ret_result v) ->\n  ok_heap h ->\n  ok_scope h s ->\n  red h s e h' v\nwith run_list_value_correct : forall m h1 s es k h3 v,\n  run_list_value m h1 s nil es k = out_return h3 (ret_result v) ->\n  ok_heap h1 ->\n  ok_scope h1 s ->\n  exists h2 vs,\n  k h2 vs = out_return h3 (ret_result v) /\\\n  red_list_value h1 s es h2 vs.\nProof.\n  intro m. destruct m.\n    introv R OK OKL; false.\n  destruct e; introv R OK OKL; simpl in R;\n    try (inverts* R; fail).\n\n  (* this *)\n  forwards [(?&_) | (l'&eq&B)]: elim_if_binds_field_loc R.\n    forwards*: ret_not_wrong H.\n  inverts* eq.\n  apply* red_this.\n    apply* scope_comp_correct.\n  apply* proto_comp_correct.\n  sets_eq ls: (scope_comp h field_this s).\n  symmetry in EQls. forwards* Pro: scope_comp_correct EQls.\n  inverts Pro.\n    rewrite <- H in B.\n    rewrite* proto_comp_fix in B.\n    unfold proto_comp_body in B. case_if~ in B.\n    forwards*: ok_heap_null B.\n  inverts keep H; tryfalse.\n    exists~ field_this.\n    apply* binds_bound.\n  asserts (lp&Dlp&Plp): (exists l', l' <> loc_null /\\ proto h field_this ls l').\n    apply* scopes_proto_not_null.\n    intro_subst.\n    rewrite* proto_comp_fix in B.\n    unfold proto_comp_body in B. case_if~ in B.\n    forwards*: ok_heap_null B.\n  inverts* Plp.\n    exists~ field_this.\n  apply* binds_bound.\n\n  (* variable *)\n  inverts* R.\n  apply red_variable.\n  apply* scope_comp_correct.\n\n  (* literal *)\n  inverts* R. constructor*.\n\n  (* obj *)\n  name_heap_alloc_obj_in R h3.\n  sets_eq sl: (split l). destruct sl as [lx lx0].\n  asserts OK3: (ok_heap h3).\n    subst h3. apply* ok_heap_alloc_obj.\n      apply* ok_heap_protochain_indom. applys* ok_heap_special_obj_proto OK.\n      right. applys* ok_heap_special_obj_proto OK.\n      apply fresh_for_spec.\n  asserts OKL3: (ok_scope h3 s).\n    applys* ok_scope_extends h.\n    subst h3. apply* extends_proto_write.\n  forwards~ (h2&vs&R'&IHR): run_list_value_correct R.\n  inverts R'.\n  apply* red_object.\n    apply* fresh_for_spec.\n    rewrite <- EQh3. apply IHR.\n    apply* arguments_comp_correct.\n\n  (* functions *)\n  destruct o.\n    (* --named *)\n    inverts R.\n    apply* red_function_named; apply* fresh_for_spec.\n    (* --unnamed *)\n    inverts R.\n    apply* red_function_unnamed; apply* fresh_for_spec.\n\n  (* access *)\n  forwards [(?&?) | (r1&h1&eq1)]: elim_if_success R; tryfalse.\n  rewrite eq1 in R. simpl in R.\n  forwards  [eqr | [(eqr&v'&eqo) | (l&eqo&diffno)]]: elim_if_not_eq R.\n    rewrite eqr in R. simpl in R. forwards*: wrong_not_ret R.\n    lets (h'0&eqr'): eqr. forwards*: wrong_not_ret eqr'.\n  rewrite eqo in R. simpl in R.\n  case_if* in R; tryfalse.\n  forwards [(?&?) | (r2&h2&eq2)]: elim_if_success R; tryfalse.\n  rewrite eq2 in R. simpl in R.\n  forwards [eqr2 | [(eqr2&v''&eqr2') | (str&eqstr)]]: elim_if_is_string R.\n    rewrite eqr2 in R. simpl in R. forwards*: wrong_not_ret R.\n    lets (h'0&eqr2''): eqr2. forwards*: wrong_not_ret eqr2''.\n  rewrite eqstr in R; simpl in R.\n  inverts* R.\n  forwards* R1: run_correct eq1.\n  forwards* (OK1&OKL1&OKr1): sub_safety R1.\n  forwards* R2: run_correct eq2.\n  apply* red_access; try apply* getvalue_comp_correct; apply* safety.\n\n  (* member *)\n  forwards [(?&?) | (r1&h1&eq1)]: elim_if_success R; tryfalse.\n  rewrite eq1 in R; simpl in R.\n  forwards [((?&?)&(?&?)) | (l&f&eq2)]: elim_if_is_ref R.\n    rewrite H0 in R. simpl in R. forwards*: wrong_not_ret R.\n  rewrite eq2 in R. simpl in R.\n  forwards [? | (f'&eq3)]: elim_if_is_field_normal R.\n    false* wrong_not_ret.\n  rewrite eq3 in R. simpl in R.\n  subst. inverts* R.\n  forwards~ R1: run_correct eq1.\n  assert (f' = s0); subst.\n    inverts R1. inverts H9. inverts* H10.\n  apply* red_member.\n\n  (* new *)\n  forwards [(?&?) | (r1&h1&eq1)]: elim_if_success R; tryfalse.\n  rewrite eq1 in R. simpl in R.\n  forwards [eqr | [((h2&eqr)&(v'&eqo)) | (l1&eqo&diffno)]]: elim_if_not_eq R.\n    rewrite eqr in R. simpl in R. forwards*: wrong_not_ret R.\n    forwards*: wrong_not_ret eqr.\n  rewrite eqo in R; simpl in R.\n  case_if* in R.\n  forwards* [? | (Ib&Is&sc&f&e2&Escope&Ebody&R')]: elim_if_binds_scope_body R.\n    subst. forwards*: ret_not_wrong H.\n  clear R. rename R' into R.\n  forwards [(?&?) | (v'&R'&Bv')]: elim_if_binds_field R.\n    forwards*: ret_not_wrong H.\n  clear R. symmetry in R'. rename R' into R.\n  forwards* R1: run_correct eq1.\n  forwards* (OK1&OKL1&OKr1&Ext1): safety R1.\n  forwards~ (h2&vs&R'&IHR): run_list_value_correct R.\n  clear R. rename R' into R.\n  forwards [(?&?) | [(?&h0&eq3&eqv1) | (?&h0&v1&eq3&eqv1)]]: elim_if_success_value R; tryfalse.\n    rewrite eq3 in R. simpls. rewrite eqv1 in R. simpls. forwards*: wrong_not_ret R.\n  name_heap_reserve_local_vars_in eq3 h7.\n  name_heap_write_fields_in EQh7 h6.\n  name_heap_write_in EQh6 h5.\n  name_heap_sub_write_in EQh5 h4.\n  name_heap_alloc_obj_in EQh4 h3.\n  rewrite eq3 in R. simpls. rewrite eqv1 in R. simpls.\n  inverts R.\n  forwards* (OK2&OKL2&OKlv2&Ext2): safety_list IHR.\n  (* What follows is nearly a copy/paste of the corresponding proof in JsSafety. *)\n  asserts O3: (ok_heap h3). subst h3. apply* ok_heap_alloc_obj. \n    applys* obj_or_glob_of_value_protochain h1 l1 field_normal_prototype v'.\n    right. forwards~: ok_heap_special_obj_proto h1. apply* OK1.\n     forwards [(l3&El3)|?]: (value_loc_or_not v'). \n       subst v'. simpl. forwards OV: ok_heap_ok_value OK1.\n        unfolds in OV. forwards~: OV Bv'. case_if*.\n       rewrite~ obj_or_glob_of_value_not_loc.\n       apply* fresh_for_spec.\n  asserts S3: (ok_scope h3 s). subst h3. apply* ok_scope_write.\n  asserts O4: (ok_heap h4). subst h4. apply* ok_heap_alloc_obj.\n    constructor. apply* fresh_for_spec.\n  asserts S4: (ok_scope h4 s). subst h4. apply* ok_scope_write.\n  asserts O5: (ok_heap h5). subst h5. forwards*: ok_heap_write_this h4 (fresh_for h3) (fresh_for h2).\n    subst h4. apply* binds_write_neq. apply* binds_write_eq.\n    apply* fresh_for_spec.\n    applys neq_sym. applys~ fresh_binds_neq h3. apply* fresh_for_spec.\n     applys~ ok_heap_special_global_this. apply* O3.\n    subst h4 h3. do 2 apply* indom_write. apply* indom_write_eq.\n  asserts S5: (ok_scope h5 s). subst h5. apply* ok_scope_write.\n  asserts O6: (ok_heap h6). subst h6. apply* ok_heap_write_fields_user.\n    subst h5 h4 h3. apply* indom_write. indom_simpl.\n    apply* fresh_for_spec.\n    apply* arguments_ok_value.\n     apply* arguments_comp_correct.\n     applys~ Forall_trans value (ok_value h2).\n     introv Oa. applys~ ok_value_extends h2.\n     subst h5 h4 h3. repeat apply* extends_proto_write_trans.\n  asserts S6: (ok_scope h6 s). subst h6. apply* ok_scope_write_fields.\n  asserts O7: (ok_heap h7). subst h7. apply* ok_heap_write_fields_user_undef.\n    subst h6 h5 h4. apply* indom_write_fields. apply* indom_write. apply* indom_write_eq.\n    apply* fresh_for_spec.\n  asserts S7: (ok_scope h7 s). applys* ok_scope_extends.\n    subst h7. apply* extends_proto_write_fields_trans.\n  assert (ok_scope h7 (fresh_for h3 :: sc)).\n    subst h7. apply* ok_scope_write_fields.\n    subst h6. apply* ok_scope_write_fields.\n    subst h5. apply* ok_scope_write.\n    subst h4. apply* ok_scope_cons.\n    subst h3. repeat apply* ok_scope_write.\n    forwards~ Of: ok_heap_function OK1.\n    unfolds in Of.\n    rewrite* <- binds_equiv_read in Escope.\n    forwards: Of l1.\n      left. apply Escope.\n    applys* ok_scope_extends h1.\n    apply* ok_heap_binds_ok_scope.\n    apply* indom_write_eq.\n  forwards~ R2: run_correct eq3.\n  forwards* (O'&S'&OKr2&E'): safety R2.\n  apply* red_new.\n    apply* getvalue_comp_correct.\n    rewrite* binds_equiv_read.\n    rewrite* binds_equiv_read.\n    apply* fresh_for_spec.\n    apply* fresh_for_spec.\n    apply* arguments_comp_correct.\n    subst*.\n    apply* getvalue_comp_correct.\n\n  (* call *)\n  forwards [(?&?) | (r1&h1&eq1)]: elim_if_success R; tryfalse.\n  rewrite eq1 in R. simpl in R.\n  forwards* [eqr | [(v1&eqo&eqr) | [(eqo&eqr) | (l1&eqo&notEval&eqr)]]]: elim_if_eq R.\n    rewrite eqr in R. simpl in R. forwards*: wrong_not_ret R.\n    forwards*: ret_not_wrong eqr.\n  (* --call to eval *)\n  unfold make_error in eqr. inverts* eqr.\n  (* -- call to function *)\n  clears R. symmetry in eqr. rename eqr into R.\n  forwards* [? | (Ib&Is&sc&f&e2&Escope&Ebody&R')]: elim_if_binds_scope_body R.\n    subst. forwards*: ret_not_wrong H.\n  clear R. rename R' into R.\n  forwards* R1: run_correct eq1.\n  forwards* (OK1&OKL1&OKr1&Ext1): safety R1.\n  forwards~ (h2&vs&R'&IHR): run_list_value_correct R.\n  clears R. rename R' into R.\n  forwards [(?&?) | [(r2&h3&eq2&eqv0) | (r2&h3&v2&eq2&eqv0)]]: elim_if_success_value R; tryfalse.\n    rewrite eq2 in R. simpls. rewrite eqv0 in R. simpls. forwards*: wrong_not_ret R.\n  rewrite eq2 in R. simpls. rewrite eqv0 in R. simpls.\n  inverts* R.\n  forwards* (OK2&OKL2&OKlv2&Ext2): safety_list IHR.\n  name_heap_write_fields_in eq2 h6.\n  asserts OK2sc: (ok_scope h2 sc).\n    lets Of: ok_heap_function OK1. unfolds in Of.\n    rewrite* <- binds_equiv_read in Escope.\n    forwards: Of l1.\n      left. apply Escope.\n    applys* ok_scope_extends h1.\n    apply* ok_heap_binds_ok_scope.\n  name_heap_sub_write_fields_in EQh6 h5.\n  name_heap_write_in EQh5 h4.\n  name_heap_alloc_obj_in EQh4 h3.\n  asserts OK6: (ok_heap h6).\n    (* This part is very closed to the corresponding one in JsSafety:\n       maybe it can be factorized?*)\n    asserts: (has_some_proto h3 (fresh_for h2)). subst h3. indom_simpl.\n     subst h6. apply* ok_heap_write_fields_user_undef.\n       subst h5 h4 h3. apply~ indom_write_fields. indom_simpl.\n       apply* fresh_for_spec.\n     subst h5. apply* ok_heap_write_fields_user.\n       subst h4 h3. indom_simpl.\n       apply* fresh_for_spec.\n     subst h4. applys ok_heap_write_this h3 (fresh_for h2) (get_this h1 r1) (@eq_refl). \n       subst h3. apply* ok_heap_alloc_obj. constructor.\n       apply* fresh_for_spec.\n       subst h3. apply* binds_write_neq. apply* binds_write_eq.\n       apply* fresh_for_spec.\n       applys neq_sym. applys~ fresh_binds_neq h2. apply* fresh_for_spec.\n       applys~ ok_heap_special_global_this. apply* OK2.\n       auto.\n     destruct r1 as [v1|[l0 f0]].\n       subst h3. do 2 apply* indom_write. \n        apply* ok_heap_special_global_proto. apply* OK2.\n       unfold get_this. case_if.\n         subst h3. do 2 apply* indom_write. \n          apply* ok_heap_special_global_proto. apply* OK2.\n         subst h3.\n          do 2 apply* has_some_proto_write. inverts OKr1 as [N|P].\n            subst l0. simpl in eqo. case_if in eqo.\n            forwards~: extends_proto_elim Ext2 P.\n     apply* arguments_ok_value. apply* arguments_comp_correct.\n     applys~ Forall_trans value (ok_value h2).\n       introv Oa. applys~ ok_value_extends h2.\n        subst h4 h3. repeat apply* extends_proto_write_trans.\n  asserts OKL6: (ok_scope h6 (fresh_for h2 :: sc)).\n    subst h6. apply* ok_scope_write_fields.\n    subst h5. apply* ok_scope_write_fields.\n    subst h4. apply* ok_scope_write.\n    subst h3. apply* ok_scope_cons.\n    apply* ok_scope_write.\n    apply* indom_write_eq.\n  forwards* R2: run_correct eq2.\n  forwards* (_&OKL'&OKr2&Ext6): safety R2.\n  apply* red_call.\n    apply* getvalue_comp_correct.\n    rewrite* binds_equiv_read.\n    rewrite* binds_equiv_read.\n    apply* fresh_for_spec.\n    apply* arguments_comp_correct.\n    rewrite <- EQh3. rewrite <- EQh4. rewrite <- EQh5.\n    unfold reserve_local_vars. rewrite <- EQh6.\n      apply* R2.\n    apply* getvalue_comp_correct.\n      apply* safety.\n\n  (* unary_op *)\n  destruct u.\n  (* not *)\n  forwards [(?&?) | [(v0&h1&eq1&eqv0) | (v0&h1&b'&eq1&eqv0)]]: elim_if_success_value R; tryfalse.\n    rewrite eq1 in R. simpls. rewrite eqv0 in R. simpls. forwards*: wrong_not_ret R.\n  rewrite eq1 in R. simpls. rewrite eqv0 in R. simpls.\n  forwards [? | (v2&eqv2)]: elim_if_defined R.\n    rewrite H in R; simpl in R; forwards*: wrong_not_ret R.\n  rewrite eqv2 in R; simpl in R.\n  destruct b'; tryfalse. inverts eqv2.\n  inverts~ R.\n  forwards~ R': run_correct eq1.\n  forwards* (OK1&OKL1&OKr1): sub_safety R'.\n  apply* red_unary_op.\n    apply* getvalue_comp_correct.\n    apply* unary_op_comp_correct.\n\n  (* delete *)\n  forwards [(?&?) | (r1&h1&eq1)]: elim_if_success R; tryfalse.\n  rewrite eq1 in R. simpl in R.\n  case_if in R; inverts R.\n   apply* red_delete_false.\n   apply* red_delete_true.\n\n  (* typeof *)\n  forwards [(?&?) | (r1&h1&eq1)]: elim_if_success R; tryfalse.\n  rewrite eq1 in R. simpl in R.\n  forwards [(v1&eqr) | [(l&f&diffno&eqr&eqres) | (f&eqr&eqres)]]: elim_if_is_null_ref R.\n    rewrite eqr in R. simpl in R.\n     forwards [? | (v2&eqv2)]: elim_if_defined R.\n       rewrite H in R. simpl in R. forwards*: wrong_not_ret R.\n     rewrite eqv2 in R. simpl in R. inverts R.\n     forwards~ R1: run_correct eq1.\n     forwards* (OK'&OKL'&OKr1): sub_safety R1.\n     apply* red_typeof_value.\n       subst r1. constructor.\n     apply* typeof_comp_correct.\n    clear R. symmetry in eqres.\n     forwards [? | (v2&eqv2)]: elim_if_defined eqres.\n       rewrite H in eqres. simpl in eqres. forwards*: wrong_not_ret eqres.\n     rewrite eqv2 in eqres. simpl in eqres.\n     forwards [? | (v3&eqv3)]: elim_if_defined eqres.\n       rewrite H in eqres. simpl in eqres. forwards*: wrong_not_ret eqres.\n     rewrite eqv3 in eqres. simpl in eqres. inverts eqres.\n     forwards~ R1: run_correct eq1.\n     forwards* (OK'&OKL'&OKr1): sub_safety R1.\n     apply* red_typeof_value.\n       apply* getvalue_comp_correct.\n     apply* typeof_comp_correct.\n    clear R. inverts eqres.\n     forwards~ R1: run_correct eq1. subst r1.\n     apply* red_typeof_undefined.\n\n  (* The four next cases are copy/pasted. *)\n  (* pre_incr *)\n  forwards [(?&?) | (r1&h1&eq1)]: elim_if_success R; tryfalse.\n  rewrite eq1 in R. simpl in R.\n  forwards [(eqw&v'&eqv') | (l&f&eq')]: elim_if_is_ref R.\n    lets (h'0&eqw'): eqw. forwards*: wrong_not_ret eqw'.\n  rewrite eq' in R. simpl in R.\n  forwards [? | (v1&eqv1)]: elim_if_defined R.\n    rewrite H in R. simpl in R. forwards*: wrong_not_ret R.\n  destruct f; tryfalse.\n  rewrite eqv1 in R. simpl in R.\n  forwards [? | (v2&eqv2)]: elim_if_defined R.\n    rewrite H in R. simpl in R. forwards*: wrong_not_ret R.\n  rewrite eqv2 in R. simpl in R.\n  inverts R. substs.\n  forwards~ R1: run_correct eq1.\n  forwards* (OK1&OKL1&OKr1): sub_safety R1.\n  asserts OV1: (ok_value h1 v1).\n    repeat case_if in eqv1; inverts eqv1. constructor*.\n    lets OKV: ok_heap_ok_value OK1. unfolds in OKV.\n    apply* OKV. rewrite* binds_equiv_read.\n      apply* proto_indom. apply* proto_comp_correct.\n        inverts~ OKr1. inverts* H0.\n        apply* indom_bound.\n      auto*.\n  asserts OKV1': (ok_value h v1).\n    inverts* OV1. false.\n    rewrite~ binary_op_comp_fix in eqv2. simpl in eqv2.\n    false eqv2.\n    apply* red_pre_incr.\n      apply* getvalue_comp_correct.\n      apply* binary_op_comp_correct.\n \n  (* post_incr *)\n  forwards [(?&?) | (r1&h1&eq1)]: elim_if_success R; tryfalse.\n  rewrite eq1 in R. simpl in R.\n  forwards [(eqw&v'&eqv') | (l&f&eq')]: elim_if_is_ref R.\n    lets (h'0&eqw'): eqw. forwards*: wrong_not_ret eqw'.\n  rewrite eq' in R. simpl in R.\n  forwards [? | (v1&eqv1)]: elim_if_defined R.\n    rewrite H in R. simpl in R. forwards*: wrong_not_ret R.\n  destruct f; tryfalse.\n  rewrite eqv1 in R. simpl in R.\n  forwards [? | (v2&eqv2)]: elim_if_defined R.\n    rewrite H in R. simpl in R. forwards*: wrong_not_ret R.\n  rewrite eqv2 in R. simpl in R.\n  inverts R. substs.\n  forwards~ R1: run_correct eq1.\n  forwards* (OK1&OKL1&OKr1): sub_safety R1.\n  asserts OV1: (ok_value h1 v1).\n    repeat case_if in eqv1; inverts eqv1. constructor*.\n    lets OKV: ok_heap_ok_value OK1. unfolds in OKV.\n    apply* OKV. rewrite* binds_equiv_read.\n      apply* proto_indom. apply* proto_comp_correct.\n        inverts~ OKr1. inverts* H0.\n        apply* indom_bound.\n      auto*.\n  asserts OKV1': (ok_value h v1).\n    inverts* OV1. false.\n    rewrite~ binary_op_comp_fix in eqv2. simpl in eqv2.\n    false eqv2.\n    apply* red_post_incr.\n      apply* getvalue_comp_correct.\n      apply* binary_op_comp_correct.\n\n  (* pre_decr *)\n  forwards [(?&?) | (r1&h1&eq1)]: elim_if_success R; tryfalse.\n  rewrite eq1 in R. simpl in R.\n  forwards [(eqw&v'&eqv') | (l&f&eq')]: elim_if_is_ref R.\n    lets (h'0&eqw'): eqw. forwards*: wrong_not_ret eqw'.\n  rewrite eq' in R. simpl in R.\n  forwards [? | (v1&eqv1)]: elim_if_defined R.\n    rewrite H in R. simpl in R. forwards*: wrong_not_ret R.\n  destruct f; tryfalse.\n  rewrite eqv1 in R. simpl in R.\n  forwards [? | (v2&eqv2)]: elim_if_defined R.\n    rewrite H in R. simpl in R. forwards*: wrong_not_ret R.\n  rewrite eqv2 in R. simpl in R.\n  inverts R. substs.\n  forwards~ R1: run_correct eq1.\n  forwards* (OK1&OKL1&OKr1): sub_safety R1.\n  asserts OV1: (ok_value h1 v1).\n    repeat case_if in eqv1; inverts eqv1. constructor*.\n    lets OKV: ok_heap_ok_value OK1. unfolds in OKV.\n    apply* OKV. rewrite* binds_equiv_read.\n      apply* proto_indom. apply* proto_comp_correct.\n        inverts~ OKr1. inverts* H0.\n        apply* indom_bound.\n      auto*.\n  asserts OKV1': (ok_value h v1).\n    inverts* OV1. false.\n    rewrite~ binary_op_comp_fix in eqv2. simpl in eqv2.\n    false eqv2.\n    apply* red_pre_decr.\n      apply* getvalue_comp_correct.\n      apply* binary_op_comp_correct.\n\n  (* post_decr *)\n  forwards [(?&?) | (r1&h1&eq1)]: elim_if_success R; tryfalse.\n  rewrite eq1 in R. simpl in R.\n  forwards [(eqw&v'&eqv') | (l&f&eq')]: elim_if_is_ref R.\n    lets (h'0&eqw'): eqw. forwards*: wrong_not_ret eqw'.\n  rewrite eq' in R. simpl in R.\n  forwards [? | (v1&eqv1)]: elim_if_defined R.\n    rewrite H in R. simpl in R. forwards*: wrong_not_ret R.\n  destruct f; tryfalse.\n  rewrite eqv1 in R. simpl in R.\n  forwards [? | (v2&eqv2)]: elim_if_defined R.\n    rewrite H in R. simpl in R. forwards*: wrong_not_ret R.\n  rewrite eqv2 in R. simpl in R.\n  inverts R. substs.\n  forwards~ R1: run_correct eq1.\n  forwards* (OK1&OKL1&OKr1): sub_safety R1.\n  asserts OV1: (ok_value h1 v1).\n    repeat case_if in eqv1; inverts eqv1. constructor*.\n    lets OKV: ok_heap_ok_value OK1. unfolds in OKV.\n    apply* OKV. rewrite* binds_equiv_read.\n      apply* proto_indom. apply* proto_comp_correct.\n        inverts~ OKr1. inverts* H0.\n        apply* indom_bound.\n      auto*.\n  asserts OKV1': (ok_value h v1).\n    inverts* OV1. false.\n    rewrite~ binary_op_comp_fix in eqv2. simpl in eqv2.\n    false eqv2.\n    apply* red_post_decr.\n      apply* getvalue_comp_correct.\n      apply* binary_op_comp_correct.\n\n  (* void *) (* Note:  this is more or less a copy/paste of the proof of `not' above. *)\n  forwards [(?&?) | [(v0&h1&eq1&eqv0) | (v0&h1&b'&eq1&eqv0)]]: elim_if_success_value R; tryfalse.\n    rewrite eq1 in R. simpls. rewrite eqv0 in R. simpls. forwards*: wrong_not_ret R.\n  rewrite eq1 in R. simpls. rewrite eqv0 in R. simpls.\n  inverts~ R.\n  forwards~ R': run_correct eq1.\n  forwards* (OK1&OKL1&OKr1): sub_safety R'.\n  apply* red_unary_op.\n    apply* getvalue_comp_correct.\n    apply* unary_op_comp_correct.\n\n  (* binary_op *)\n  forwards [(?&?) | [(v0&h1&eq1&eqv0) | (v0&h1&b'&eq1&eqv0)]]: elim_if_success_value R; tryfalse.\n    rewrite eq1 in R. simpls. rewrite eqv0 in R. simpls. forwards*: wrong_not_ret R.\n  rewrite eq1 in R. simpls. rewrite eqv0 in R. simpls.\n  forwards [(?&?) | [(v1&h2&eq2&eqv1) | (v1&h2&b''&eq2&eqv1)]]: elim_if_success_value R; tryfalse.\n    rewrite eq2 in R. simpls. rewrite eqv1 in R. simpls. forwards*: wrong_not_ret R.\n  rewrite eq2 in R. simpls. rewrite eqv1 in R. simpls.\n  forwards [? | (v3&eqv3)]: elim_if_defined R.\n    rewrite H in R. simpl in R. forwards*: wrong_not_ret R.\n  rewrite eqv3 in R. simpl in R.\n  inverts* R.\n  forwards* He1: run_correct eq1.\n  forwards* (OK1&OKL1&OKr1): sub_safety He1.\n  forwards* R2: run_correct eq2.\n  forwards* (OK2&OKL2&OKr2&Ext'): safety R2.\n  forwards* G0: getvalue_comp_correct eqv0.\n  forwards* G1: getvalue_comp_correct eqv1.\n  apply* red_binary_op.\n  apply* binary_op_comp_correct.\n    applys* ok_value_extends h1. forwards* O0: ok_result_prove G0.\n     inverts~ O0.\n    forwards* O1: ok_result_prove G1. inverts~ O1.\n\n  (* and *)\n  forwards [(?&?) | [(v0&h1&eq1&eqv0) | (v0&h1&b'&eq1&eqv0)]]: elim_if_success_value R; tryfalse.\n    rewrite eq1 in R. simpls. rewrite eqv0 in R. simpls. forwards*: wrong_not_ret R.\n  rewrite eq1 in R. simpls. rewrite eqv0 in R. simpls.\n  forwards~ R1: run_correct eq1.\n  forwards* (OK1&OKL1&OKr1): sub_safety R1.\n  forwards [(?&?) | [(eq2&eqv) | (eq2&eqv)]]: elim_if_boolean R.\n    forwards*: ret_not_wrong H.\n    subst b'. simpls.\n    forwards [(?&?) | [(v1&h2&eq3&eqv1) | (v1&h2&b''&eq3&eqv1)]]: elim_if_success_value R; tryfalse.\n      rewrite eq3 in R. simpls. rewrite eqv1 in R. simpls. forwards*: wrong_not_ret R.\n    rewrite eq3 in R; simpls. rewrite eqv1 in R. simpls.\n     forwards~ R2: run_correct eq3.\n     forwards* (OK2&OKL2&OKr2): sub_safety R2.\n     inverts~ R.\n     apply* red_and_true.\n       apply* getvalue_comp_correct.\n       apply* getvalue_comp_correct.\n    inverts~ eq2.\n     subst b'. simpls.\n     apply* red_and_false.\n       apply* getvalue_comp_correct.\n\n  (* or *)\n  forwards [(?&?) | [(v0&h1&eq1&eqv0) | (v0&h1&b'&eq1&eqv0)]]: elim_if_success_value R; tryfalse.\n    rewrite eq1 in R. simpls. rewrite eqv0 in R. simpls. forwards*: wrong_not_ret R.\n  rewrite eq1 in R. simpls. rewrite eqv0 in R. simpls.\n  forwards~ R1: run_correct eq1.\n  forwards* (OK1&OKL1&OKr1): sub_safety R1.\n  forwards [(?&?) | [(eq2&eqv) | (eq2&eqv)]]: elim_if_boolean R.\n    forwards*: ret_not_wrong H.\n    subst b'. simpls.\n     inverts~ R.\n     apply* red_or_true.\n       apply* getvalue_comp_correct.\n    subst b'. simpls.\n    forwards [(?&?) | [(v1&h2&eq3&eqv1) | (v1&h2&b''&eq3&eqv1)]]: elim_if_success_value R; tryfalse.\n      rewrite eq3 in R. simpls. rewrite eqv1 in R. simpls. forwards*: wrong_not_ret R.\n    rewrite eq3 in R. simpls. rewrite eqv1 in R. simpls.\n     forwards~ R2: run_correct eq3.\n     forwards* (OK2&OKL2&OKr2): sub_safety R2.\n     inverts~ R.\n     apply* red_or_false.\n       apply* getvalue_comp_correct.\n       apply* getvalue_comp_correct.\n\n  (* assign *)\n  destruct o.\n  (* with an operator *)\n  forwards [(?&?) | (r1&h1&eq1)]: elim_if_success R; tryfalse.\n  rewrite eq1 in R. simpl in R.\n  forwards [(eqw&v'&eqv') | (l&f&eq')]: elim_if_is_ref R.\n    lets (h'0&eqw'): eqw. forwards*: wrong_not_ret eqw'.\n  rewrite eq' in R. simpl in R.\n  forwards [? | (v1&eqv1)]: elim_if_defined R.\n    rewrite H in R. simpl in R. forwards*: wrong_not_ret R.\n  rewrite eqv1 in R. simpl in R.\n  forwards [(?&?) | [(r2&h2&eq2&eqv2) | (r2&h2&v2&eq2&eqv2)]]: elim_if_success_value R; tryfalse.\n    rewrite eq2 in R. simpls. rewrite eqv2 in R. simpls. forwards*: wrong_not_ret R.\n  rewrite eq2 in R. simpls. rewrite eqv2 in R. simpls.\n  destruct f; tryfalse.\n  subst r1.\n  forwards [? | (v3&eqv3)]: elim_if_defined R.\n    rewrite H in R. simpl in R. forwards*: wrong_not_ret R.\n  rewrite eqv3 in R. simpl in R.\n  inverts R.\n  forwards* R1: run_correct eq1.\n  forwards* (OK1&OKL1&OKr1&Ext1): safety R1.\n  forwards* R2: run_correct eq2.\n  forwards* (OK2&OKL2&OKr2&Ext2): safety R2.\n  apply* red_assign_op.\n    apply* getvalue_comp_correct.\n    apply* getvalue_comp_correct.\n    apply* binary_op_comp_correct.\n      applys ok_value_extends Ext2.\n      case_if in eqv1. case_if in eqv1.\n       inverts* eqv1.\n       inverts* eqv1. apply* ok_heap_ok_value.\n       rewrite* binds_equiv_read.\n       apply* proto_indom.\n         apply* proto_comp_correct.\n         apply* indom_bound.\n         inverts OKr1.\n         inverts* H0.\n         auto*.\n      inverts* OKr2.\n       simpls. inverts~ eqv2.\n       simpls. inverts~ eqv2.\n       case_if in H1. case_if in H1.\n        inverts* H1.\n        inverts* H1. apply* ok_heap_ok_value.\n        rewrite* binds_equiv_read.\n        apply* proto_indom.\n          apply* proto_comp_correct.\n          apply* indom_bound.\n          auto*.\n\n  (* without *)\n  forwards [(?&?) | (r1&h1&eq1)]: elim_if_success R; tryfalse.\n  rewrite eq1 in R. simpl in R.\n  forwards [(eqw&v'&eqv') | (l&f&eq')]: elim_if_is_ref R.\n    lets (h'0&eqw'): eqw. forwards*: wrong_not_ret eqw'.\n  rewrite eq' in R. simpl in R.\n  forwards [(?&?) | [(v0&h2&eq2&eqv0) | (v0&h2&b&eq2&eqv0)]]: elim_if_success_value R; tryfalse.\n    rewrite eq2 in R. simpls. rewrite eqv0 in R. simpls. forwards*: wrong_not_ret R.\n  rewrite eq2 in R. simpls. rewrite eqv0 in R. simpls.\n  inverts* R.\n  forwards* R1: run_correct eq1.\n  forwards* (OK1&OKL1&OKr1): sub_safety R1.\n  inverts* OKr1; tryfalse.\n  inverts H0.\n  forwards* R2: run_correct eq2.\n  forwards* (OK2&OKL2&OKr2): sub_safety R2.\n  apply* red_assign.\n  apply* getvalue_comp_correct.\n\n  (* seq *)\n  forwards [(?&?) | (r1&h1&eq1)]: elim_if_success R; tryfalse.\n  rewrite eq1 in R. simpl in R.\n  forwards [(?&?) | (r2&h2&eq2)]: elim_if_success R; tryfalse.\n  rewrite eq2 in R. simpl in R.\n  inverts* R.\n  forwards~ R1: run_correct eq1.\n  forwards* (OK1&OKL1&OKr1): sub_safety R1.\n  forwards~ R2: run_correct eq2.\n  forwards* (OK2&OKL2&OKr2): sub_safety R2.\n  apply* red_seq.\n\ndestruct o. (* NEWSYNTAX -- reorganize the two cases *)\n  (* var_decl_expr *)\n  forwards [(?&?) | (v0&h0&eq)]: elim_if_success R; tryfalse.\n  rewrite eq in R. simpl in R.\n  forwards* R1: run_correct eq.\n  inverts R.\n  apply* red_var_decl_expr.\n  (* var_decl *)\n  inverts R.\n  apply* red_var_decl.\n\ndestruct o. (* NEWSYTNAX --reorganized *) \n  (* if *)\n  forwards [(?&?) | [(v0&h1&eq1&eqv0) | (v0&h1&b'&eq1&eqv0)]]: elim_if_success_value R; tryfalse.\n    rewrite eq1 in R. simpls. rewrite eqv0 in R. simpls. forwards*: wrong_not_ret R.\n  rewrite eq1 in R. simpls. rewrite eqv0 in R. simpls.\n  forwards~ R1: run_correct eq1.\n  forwards* (OK1&OKL1&OKr1): sub_safety R1.\n  forwards [(?&?) | [(eq2&eqv) | (eq2&eqv)]]: elim_if_boolean R.\n    forwards*: ret_not_wrong H.\n    eapply red_if_true.\n      apply* run_correct.\n      subst b'. apply* getvalue_comp_correct.\n      apply* run_correct.\n  eapply red_if_false.\n    apply* run_correct.\n    subst b'. apply* getvalue_comp_correct.\n    apply* run_correct.\n\n  (* if *)\n  forwards [(?&?) | [(v0&h1&eq1&eqv0) | (v0&h1&b'&eq1&eqv0)]]: elim_if_success_value R; tryfalse.\n    rewrite eq1 in R. simpls. rewrite eqv0 in R. simpls. forwards*: wrong_not_ret R.\n  rewrite eq1 in R. simpls. rewrite eqv0 in R. simpls.\n  forwards~ R1: run_correct eq1.\n  forwards* (OK1&OKL1&OKr1): sub_safety R1.\n  forwards [(?&?) | [(eq2&eqv) | (eq2&eqv)]]: elim_if_boolean R.\n    forwards*: ret_not_wrong H.\n    eapply red_if_true.\n      apply* run_correct.\n      subst b'. apply* getvalue_comp_correct.\n      apply* run_correct.\n  inverts eq2.\n  eapply red_if_false_implicit.\n    apply* run_correct.\n    subst b'. apply* getvalue_comp_correct.\n\n  (* while *)\n  forwards [(?&?) | [(v0&h1&eq1&eqv0) | (v0&h1&b'&eq1&eqv0)]]: elim_if_success_value R; tryfalse.\n    rewrite eq1 in R. simpls. rewrite eqv0 in R. simpls. forwards*: wrong_not_ret R.\n  rewrite eq1 in R. simpls. rewrite eqv0 in R. simpls.\n  forwards~ R1: run_correct eq1.\n  forwards* (OK1&OKL1&OKr1): sub_safety R1.\n  forwards [(?&?) | [(_&eqv) | (_&eqv)]]: elim_if_boolean R.\n    forwards*: ret_not_wrong H.\n   subst b'. simpls.\n    forwards [(?&?) | (r2&h2&eq2)]: elim_if_success R; tryfalse.\n    rewrite eq2 in R. simpl in R.\n    inverts R. apply* red_while_true. apply* getvalue_comp_correct.\n   subst b'. simpls.\n    inverts R. apply* red_while_false. apply* getvalue_comp_correct.\n\n  (* with *)\n  forwards [(?&?) | (r1&h1&eq1)]: elim_if_success R; tryfalse.\n  rewrite eq1 in R. simpl in R.\n  forwards [eqr | [(eqr&v'&eqo) | (l&eqo&diffno)]]: elim_if_not_eq R.\n    rewrite eqr in R. simpl in R. forwards*: wrong_not_ret R.\n    lets (h'0&eqr'): eqr. false (>> wrong_not_ret eqr').\n  rewrite eqo in R. simpl in R.\n  case_if in R. \n  forwards [(?&?) | (r2&h2&eq2)]: elim_if_success R; tryfalse.\n  rewrite eq2 in R. simpl in R.\n  inverts* R.\n  forwards* R1: run_correct eq1.\n  forwards* (OK1&OKL1&OKr1): sub_safety R1.\n  forwards* R2: run_correct eq2.\n    apply* ok_scope_cons.\n    assert (ok_value h1 l).\n      inverts OKr1; simpls.\n      inverts* eqo.\n      inverts H;\n        case_if* in eqo; tryfalse.\n      case_if* in eqo;\n        tryfalse.\n      inverts eqo.\n      lets OKV1: ok_heap_ok_value OK1.\n      unfold ok_heap_ok_value_def in OKV1.\n      apply~ OKV1.\n        rewrite* binds_equiv_read.\n         apply* proto_indom.\n         apply* proto_comp_correct.\n         apply* indom_bound.\n        split; discriminate.\n    inverts* H.\n  apply* red_with.\n    apply* getvalue_comp_correct.\n\n  (* skip *)\n  inverts R.\n  apply* red_skip.\n\n  (* red_list_value *)\n  intro m. destruct m.\n    introv R OK OKL. false.\n  introv R OK OKL. destruct es; simpl in R.\n    do 2 eexists. splits*. constructor.\n    forwards [(?&?) | [(v0&h2&eq2&eqv0) | (v0&h2&b&eq2&eqv0)]]: elim_if_success_value R; tryfalse.\n      rewrite eq2 in R. simpls. rewrite eqv0 in R. simpls. forwards*: wrong_not_ret R.\n    rewrite eq2 in R. simpls. rewrite eqv0 in R. simpls.\n    rewrite <- (app_nil_l (b :: nil)) in R.\n    forwards R': run_list_value_add_value R.\n      introv. reflexivity.\n    forwards~ Rc: run_correct eq2.\n    forwards~ (O2&S2&Or2&E2): safety Rc.\n    forwards~ (h4&vs'&E&Rl): run_list_value_correct R'.\n    do 2 eexists. splits*.\n    apply* red_list_cons.\n    apply* getvalue_comp_correct.\nAdmitted. (* Admitted for the same reasons than the one of JsSafety:\n             This proof requires a lot of memory and time! *)\n\n\n(* Require a deterministic semantic:\nTheorem run_complete : forall h h' L e v,\n  red h L e h' v ->\n  ok_heap h -> ok_scope h L ->\n  exists m, run m h L e = out_return h' (ret_result v).\n*)\n\nEnd Correctness.\n\n", "meta": {"author": "jeremyjohnston", "repo": "javascript-vm", "sha": "eb4b20f46d36c8342f0f012cd38500ca6dab3e1a", "save_path": "github-repos/coq/jeremyjohnston-javascript-vm", "path": "github-repos/coq/jeremyjohnston-javascript-vm/javascript-vm-eb4b20f46d36c8342f0f012cd38500ca6dab3e1a/jscert/core_js_src/JsInterpreterProofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4804786780479071, "lm_q1q2_score": 0.27564024283741045}}
{"text": "Require Export DEX_BigStepWithTypes.\n\nImport DEX_BigStep.DEX_BigStep DEX_Dom DEX_Prog.\n\nSection p.\n  Variable p : DEX_ExtendedProgram.\n\n    Inductive compat_value (*h:Heap.t*) : DEX_value -> L.t -> Prop :=\n(*       compat_value_array : forall loc k mpc length tp,\n        Heap.typeof h loc = Some (Heap.LocationArray length tp mpc) ->\n        compat_value h (Ref loc) (L.Array k (newArT p mpc))\n    | compat_value_object : forall loc k c,\n      Heap.typeof h loc = Some (Heap.LocationObject c) ->\n      compat_value h (Ref loc) k *)\n    | compat_value_num : forall n k,\n      compat_value (* h *) (Num n) k\n(*     | compat_value_null : forall k,\n      compat_value h Null k *).\n\n     Definition compat_registers (*h:Heap.t*) (regs:DEX_Registers.t) (rt:TypeRegisters) : Prop :=\n      forall x v k, DEX_Registers.get regs x = Some v -> \n        VarMap.get _ rt x = Some k ->\n        compat_value (* h *) v k. \n\n(*     Definition compat_localvar (*h:Heap.t*) (l:LocalVar.t) (lvt:Var->L.t') : Prop :=\n      forall x v, LocalVar.get l x = Some v -> compat_value h v (lvt x). *)\n\n(*     Definition compat_heap (h:Heap.t) (ft:FieldSignature -> L.t') : Prop :=\n      (forall loc cn f v,\n        Heap.typeof h loc = Some (Heap.LocationObject cn) ->\n        Heap.get h (Heap.DynamicField loc f) = Some v -> compat_value h v (ft f))\n      /\\\n      (forall loc v length tp mpc i,\n        Heap.typeof h loc = Some (Heap.LocationArray length tp mpc) ->\n        Heap.get h (Heap.ArrayElement loc i) = Some v -> compat_value h v (newArT p mpc)). *)\n\n(*     Definition typeof_stable (h1 h2:Heap.t) : Prop :=\n      forall loc,\n        Heap.typeof h1 loc <> None ->\n        Heap.typeof h1 loc = Heap.typeof h2 loc.\n\n    Definition exec_typeof_rel (s:IntraNormalState) (r:ReturnState) : Prop :=\n      match s with (pc,(h,os,l)) =>\n        typeof_stable h (fst r)\n      end.     *)\n\n    Definition compat_state (sgn:DEX_sign) (s:DEX_IntraNormalState) (rt:TypeRegisters) : Prop :=\n      match s with (pc, regs) =>\n(*         compat_heap h (ft p) /\\ *)\n(*         compat_localvar h l sgn.(lvt) /\\ *)\n        compat_registers regs rt \n      end.\n    \n    Inductive compat_res (sgn:DEX_sign) : DEX_ReturnState -> Prop :=\n    | compat_res_val : forall (* h *) v k,\n      sgn.(DEX_resType) = Some k ->\n      compat_value (* h *) v k ->\n(*       compat_heap h (ft p) -> *)\n      compat_res sgn ((* h, *)Normal (Some v))\n    | compat_res_void : (* forall h, *)\n      sgn.(DEX_resType) = None ->\n(*       compat_heap h (ft p) -> *)\n      compat_res sgn ((* h, *)Normal None)\n(*    | compat_res_exception : forall h loc,\n      compat_heap h (ft p) ->\n      compat_res sgn (h,Exception loc) *).\n\n\n(* Ltac inv_compat H :=\ndestruct H as [(* Hcompat_h [Hcompat_l *) Hcompat_regs(* ] *)]; simpl in Hcompat_regs;\n(* elim Hcompat_h; intros Hcompat_h1 Hcompat_h2; *)\nrepeat match goal with\n(*          [ id : compat_value _ (Ref _) _ /\\ _  |-_ ] => \n         let h := fresh in (\n           destruct id as [h id];\n           inversion_mine h; DiscrimateEq) \n       |*) [ id : compat_value _ _ _ /\\ _  |-_ ] => \n         let h := fresh in destruct id as [h id]\n       end.\nHint Constructors compat_value. *)\n\nLemma compat_value_join(* ' *) : forall (* h *) a t k,\n  compat_value (* h *) a t ->\n  compat_value (* h *) a (L.join(* ' *) k t).\nProof.\n  intros.\n  inversion_clear H. constructor.\nQed.\nHint Resolve compat_value_join(* ' *).\n\n(* Lemma compat_operandstack_lift : forall h s k st,\n  compat_operandstack h s st ->\n  compat_operandstack h s (lift k st).\nProof.\n  induction s; destruct st; simpl; intros; auto.\n  split; intuition.\nQed.\nHint Resolve compat_operandstack_lift.\nHint Unfold compat_localvar. *)\n\n(* Lemma compat_operandstack_elift : forall m pc h s k st,\n  compat_operandstack h s st ->\n  compat_operandstack h s (elift m pc k st).\nProof.\n  unfold elift; intros.\n  destruct (throwableAt m pc); simpl; auto.\nQed.\nHint Resolve compat_operandstack_elift. *)\n\n(* Lemma compat_value_new_allocation : forall p lt loc h h' ke v,\n  Heap.new h p lt = Some (loc, h') ->\n  compat_value h v ke ->\n  compat_value h' v ke.\nProof.\n  intros.\n  inversion_mine H0; auto.\n  destruct (eq_excluded_middle _ loc loc0); subst.\n  rewrite (@Heap.new_fresh_location _ _ _ _ _ H) in H1; discriminate.\n  rewrite <- (@Heap.new_typeof_old _ _ _ _ _ _ H H0) in H1.\n  eauto.\n  destruct (eq_excluded_middle _ loc loc0); subst.\n  rewrite (@Heap.new_fresh_location _ _ _ _ _ H) in H1; discriminate.\n  rewrite <- (@Heap.new_typeof_old _ _ _ _ _ _ H H0) in H1.\n  eauto.\nQed.\nHint Resolve compat_value_new_allocation. *)\n\n(* Lemma compat_heap_new_object : forall ft lt loc h h',\n  Heap.new h p.(prog) lt = Some (loc, h') ->\n  compat_heap h ft ->\n  compat_heap h' ft.\nProof.\n  intros.\n  destruct lt.\n  destruct H0.\n  split; intros.\n  destruct (eq_excluded_middle _ loc loc0); subst.\n  destruct (excluded_middle (defined_field p.(prog) c f)).\n  destruct H4.\n  rewrite (@Heap.new_defined_object_field _ _ _ _ _ _ _ H H4) in H3; inversion_mine H3.\n  unfold init_field_value.\n  destruct (FIELD.initValue x); auto.\n  destruct (FIELDSIGNATURE.type (FIELD.signature x)); simpl; auto.\n  rewrite (@Heap.new_undefined_object_field _ _ _ _ _ _ H H4) in H3; inversion_mine H3.\n  rewrite (@Heap.new_typeof_old _ _ _ _ _ _ H H4) in H2.\n  rewrite (@Heap.new_object_no_change _ _ _ _ _ (Heap.DynamicField loc0 f) H) in H3.\n  eauto.\n  red; intros; elim H4.\n  inversion_mine H5; auto.\n  destruct (eq_excluded_middle _ loc loc0); subst.\n  rewrite (@Heap.new_typeof _ _ _ _ _ H) in H2; discriminate.\n  rewrite (@Heap.new_typeof_old _ _ _ _ _ _ H H4) in H2.\n  rewrite (@Heap.new_object_no_change _ _ _ _ _ (Heap.ArrayElement loc0 i) H) in H3.\n  eauto.\n  red; intros; elim H4.\n  inversion_mine H5; auto.\n  destruct H0 as [H0 H00].\n  split; intros.\n  destruct (eq_excluded_middle _ loc loc0); subst.\n  rewrite (@Heap.new_typeof _ _ _ _ _ H) in H1; discriminate.\n  rewrite (@Heap.new_typeof_old _ _ _ _ _ _ H H3) in H1.\n  rewrite (@Heap.new_array_no_change _ _ _ _ _ _ _ (Heap.DynamicField loc0 f) H) in H2.\n  eauto.\n  red; intros; elim H3.\n  inversion_mine H4; auto.\n  destruct (eq_excluded_middle _ loc loc0); subst.\n  destruct (excluded_middle (0 <= i < Int.toZ t)%Z).\n  rewrite (@Heap.new_valid_array_index _ _ _ _ _ _ _ _ H H3) in H2; inversion_mine H2.\n  unfold init_value.\n  destruct t0; auto.\n  rewrite (@Heap.new_unvalid_array_index _ _ _ _ _ _ _ _ H H3) in H2; discriminate.\n  rewrite (@Heap.new_typeof_old _ _ _ _ _ _ H H3) in H1.\n  rewrite (@Heap.new_array_no_change _ _ _ _ _ _ _ (Heap.ArrayElement loc0 i) H) in H2.\n  eauto.\n  red; intros; elim H3.\n  inversion_mine H4; auto.\nQed.\nHint Resolve compat_heap_new_object.\n\nOpaque Heap.update. *)\n\n(* Lemma compat_operandstack_new_allocation : forall p lt h h' os st loc,\n  Heap.new h p lt = Some (loc, h') ->\n  compat_operandstack h os st ->\n  compat_operandstack h' os st.\nProof.\n  induction os; destruct st; simpl; intuition eauto.\nQed. *)\n\n(* Lemma compat_localvar_new_allocation : forall p lt h h' l lvt loc,\n  Heap.new h p lt = Some (loc, h') ->\n  compat_localvar h l lvt ->\n  compat_localvar h' l lvt.\nProof.\n  eauto.\nQed. *)\n\n(* Hint Resolve compat_localvar_new_allocation compat_operandstack_new_allocation. *)\n\n(* Lemma compat_value_heap_update : forall h am v k v0,\n  compat_value h v k ->\n  compat_value (Heap.update h am v0) v k.\nProof.\n  intros.\n  inversion_mine H; auto.\n  constructor 1 with length tp.\n  rewrite Heap.typeof_update_same; auto.\n  constructor 2 with c.\n  rewrite Heap.typeof_update_same; auto.\nQed.\nHint Resolve compat_value_heap_update.\n\nLemma compat_localvar_heap_update : forall h am l lvt v,\n  compat_localvar h l lvt ->\n  compat_localvar (Heap.update h am v) l lvt.\nProof.\n  eauto.\nQed.\n\nLemma compat_operandstack_heap_update : forall h am os st v,\n  compat_operandstack h os st ->\n  compat_operandstack (Heap.update h am v) os st.\nProof.\n  induction os; destruct st; simpl; intuition eauto.\nQed.\nHint Resolve compat_operandstack_heap_update compat_localvar_heap_update. *)\n\nLemma compat_value_leql(* ' *) : forall (* h *) v k1 k2,\n  compat_value (* h *) v k1 -> L.leql(* ' *) k1 k2 ->\n  compat_value (* h *) v k2.\nProof.\n  intros.\n  inversion_mine H0; inversion_mine H; econstructor.\nQed.\n\n\n(* Lemma compat_heap_update_object : forall h ft loc f v k,\n  compat_heap h ft ->\n  compat_value h v k -> L.leql' k (ft f) ->\n  compat_heap (Heap.update h (Heap.DynamicField loc f) v) ft.\nProof.\n  intros.\n  destruct H; split; intros.\n  apply compat_value_heap_update.\n  rewrite Heap.typeof_update_same in H3.\n  destruct (eq_excluded_middle _ loc loc0); subst.\n  destruct (eq_excluded_middle _ f f0); subst.\n  rewrite Heap.get_update_same in H4.\n  inversion_mine H4.\n  eapply compat_value_leql'; eauto.\n  eapply Heap.CompatObject; eauto.\n  rewrite Heap.get_update_old in H4.\n  eauto.\n  intros T; elim H5; inversion_mine T; auto.\n  rewrite Heap.get_update_old in H4.\n  eauto.\n  intros T; elim H5; inversion_mine T; auto.\n  rewrite Heap.typeof_update_same in H3.\n  rewrite Heap.get_update_old in H4.\n  apply compat_value_heap_update; eauto.\n  discriminate.\nQed.\n\nHint Resolve compat_heap_update_object.\n\nLemma compat_heap_update_array : forall h ft loc i v kv mpc length tp,\n  compat_heap h ft ->\n  Heap.typeof h loc = Some (Heap.LocationArray length tp mpc) ->\n  compat_value h v kv -> \n  L.leql' kv (newArT p mpc) ->\n  (0 <= i < Int.toZ length)%Z ->\n  compat_heap (Heap.update h (Heap.ArrayElement loc i) v) ft.\nProof.\n  intros.\n  destruct H; split; intros.\n  apply compat_value_heap_update.\n  rewrite Heap.typeof_update_same in H5.\n  rewrite Heap.get_update_old in H6.\n  eauto.\n  discriminate.\n  rewrite Heap.typeof_update_same in H5.\n  destruct (eq_excluded_middle _ loc loc0); subst.\n  destruct (eq_excluded_middle _ i i0); subst.\n  rewrite Heap.get_update_same in H6.\n  inversion_mine H6.\n  apply compat_value_heap_update.\n  DiscrimateEq.\n  eapply compat_value_leql'; eauto.\n  eapply Heap.CompatArray; eauto.\n  rewrite Heap.get_update_old in H6.\n  eauto.\n  intros T; elim H7; inversion_mine T; auto.\n  rewrite Heap.get_update_old in H6.\n  eauto.\n  intros T; elim H7; inversion_mine T; auto.\nQed.\n\nHint Resolve compat_heap_update_array. *)\n\n(* Lemma compat_localvar_update : forall l lvt x v h k,\n  compat_value h v k ->\n  L.leql' k (lvt x) ->\n  compat_localvar h l lvt ->\n  compat_localvar h (LocalVar.update l x v) lvt.\nProof.\n  intros.\n  intros y vy Hy.\n  elim (eq_excluded_middle _ x y); intro; subst.\n  rewrite LocalVar.get_update_new in Hy; inversion_mine Hy; auto.\n  eapply compat_value_leql'; eauto.\n  rewrite LocalVar.get_update_old in Hy; auto.\nQed. *)\n\nLemma compat_registers_n : forall regs rt i k v,\n  compat_registers regs rt ->\n  VarMap.get _ rt i = Some k ->\n  DEX_Registers.get regs i = Some v ->\n  compat_value v k.\nProof.\n  intros. destruct v; econstructor 1.\nQed.\n\nLemma compat_intra : forall (* kobs *) sgn m region se (* tau *) s1 s2 rt1 rt2 (* h *) i,\n  DEX_BigStepWithTypes.exec_intra (* kobs *) (* p *) se region m sgn i (* tau *) s1 rt1 (* b1 *) s2 rt2 (* b2 *) ->\n  compat_state sgn s1 rt1 -> \n  compat_state sgn s2 rt2.\nProof.\n  intros.\n  inversion_mine H.\n  destruct i; inversion_mine H1; simpl in H0; simpl; auto; unfold compat_registers;\n    intros x' v' k'; try (destruct v'; constructor).\nQed.  \n\nHint Constructors compat_res.\nHint Resolve compat_value_leql(* ' *).  \n\nLemma compat_return : forall (* kobs *) sgn m region se (* tau *) s1 r2 rt1 (* b1 b2  *)i,\n  DEX_BigStepWithTypes.exec_return (* kobs p *) se region m sgn i (* tau *) s1 rt1 (* b1  *) r2 (* b2 *) ->\n  compat_state sgn s1 rt1 -> \n  compat_res sgn r2.\nProof.\n  intros.\n  inversion_mine H.\n  destruct i; inversion_mine H1.\n  constructor 2; auto.\n  constructor 1 with (k:=kr). symmetry; auto.\n  destruct val; constructor.\nQed.  \n\n(* Lemma compat_nth_error : forall h os1 st1 i k1 v1,\n  compat_operandstack h os1 st1 ->\n  nth_error st1 i = Some k1 ->\n  nth_error os1 i = Some v1 ->\n  compat_value h v1 k1.\nProof.\n  induction os1; destruct st1; simpl in *; intros; intuition.\n  destruct i; simpl in H1; try discriminate.\n  destruct i; simpl in H0, H1.\n  inversion_mine H0; inversion_mine H1; auto.\n  eauto.\nQed. *)\n\n(* Lemma compat_stack2localvar : forall sgn h os1 os2 st1 st2,\n  length st1 = length os1 ->\n  compat_type_st_lvt sgn (st1++st2) (length st1) ->\n  compat_operandstack h (os1++os2) (st1++st2) ->\n  compat_localvar h (stack2localvar (os1 ++ os2) (length os1)) (lvt sgn).\nProof.\n  repeat intro.\n  destruct (le_lt_dec (length os1) (Var_toN x)).\n  rewrite stack2locvar_prop1 in H2; auto.\n  discriminate.\n  rewrite stack2locvar_prop2 in H2; auto.\n  destruct (H0 x) as [k [T1 T2]].\n  rewrite H; auto.\n  apply compat_value_leql' with k; auto.\n  apply compat_nth_error with (os1++os2) (st1++st2) (length os1 - Var_toN x - 1)%nat; auto.\n  rewrite <- H; auto.\nQed. *)\n\n(* Lemma length_app : forall (A:Set) (l1 l2:list A),\n  length (l1++l2) = (length l1 + length l2)%nat.\nProof.\n  induction l1; simpl; intros; auto.\nQed.\n\nLemma length_app_cons : forall (A:Set) (l:list A) (a:A),\n  length (l++a::nil) = S (length l).\nProof.\n  induction l; simpl; auto.\nQed. *)\n\n(* Lemma compat_call_init : forall kobs se reg prog m sgn i s1 st1 b1 r br m2 sgn2 s0 st0 b0  b2 tau ret,\n  BigStepWithTypes.exec_call kobs se reg prog m sgn i s1 st1 b1 r br m2 sgn2 s0 st0 b0 ret b2 tau ->\n  compat_state sgn s1 st1 ->\n  compat_state sgn2 s0 st0.\nProof.\n  intros.\n  inversion_mine H; inversion_mine H1; simpl in H0; inv_compat H0;\n    (split; [idtac|split]); simpl; auto.\n  eapply compat_stack2localvar; eauto.\n  congruence.\n  replace (args++Ref loc::os) with ((args++(Ref loc::nil))++os).\n  replace (S (length args)) with (length (args++(Ref loc::nil))).\n  apply compat_stack2localvar with (st0++(L.Simple k::nil)) st'; auto.\n  repeat rewrite length_app_cons; simpl; congruence.\n  rewrite length_app_cons.\n  rewrite app_ass; simpl.\n  auto.\n  repeat rewrite app_ass; simpl; auto.\n  rewrite length_app_cons; congruence.\n  repeat rewrite app_ass; simpl; auto.\n  eapply compat_stack2localvar; eauto.\n  congruence.\n  replace (args++Ref loc0::os) with ((args++(Ref loc0::nil))++os).\n  replace (S (length args)) with (length (args++(Ref loc0::nil))).\n  apply compat_stack2localvar with (st0++(L.Simple k::nil)) st'; auto.\n  repeat rewrite length_app_cons; simpl; congruence.\n  rewrite length_app_cons.\n  rewrite app_ass; simpl.\n  auto.\n  repeat rewrite app_ass; simpl; auto.\n  rewrite length_app_cons; congruence.\n  repeat rewrite app_ass; simpl; auto.\n  eapply compat_stack2localvar; eauto.\n  congruence.\n  replace (args++Ref loc0::os) with ((args++(Ref loc0::nil))++os).\n  replace (S (length args)) with (length (args++(Ref loc0::nil))).\n  apply compat_stack2localvar with (st0++(L.Simple k::nil)) st'; auto.\n  repeat rewrite length_app_cons; simpl; congruence.\n  rewrite length_app_cons.\n  rewrite app_ass; simpl.\n  auto.\n  repeat rewrite app_ass; simpl; auto.\n  rewrite length_app_cons; congruence.\n  repeat rewrite app_ass; simpl; auto.\nQed.\n\nLemma typeof_stable_value : forall h1 h2 v k,\n  typeof_stable h1 h2 ->\n  compat_value h1 v k ->\n  compat_value h2 v k.\nProof.\n  intros.\n  inversion_mine H0; auto;\n  rewrite (H loc) in H1; eauto;\n    congruence.\nQed.\n\nLemma typeof_stable_localvar : forall h1 h2 l lvt,\n  typeof_stable h1 h2 ->\n  compat_localvar h1 l lvt ->\n  compat_localvar h2 l lvt.\nProof.\n  intros.\n  intros x v H1.\n  apply typeof_stable_value with h1; auto.\nQed.\n\nHint Resolve typeof_stable_localvar.\n\nLemma typeof_stable_operandstack : forall h1 h2 os st,\n  typeof_stable h1 h2 ->\n  compat_operandstack h1 os st ->\n  compat_operandstack h2 os st.\nProof.\n  induction os; destruct st; simpl; intuition.\n  apply typeof_stable_value with h1; auto.\nQed.\n\nHint Resolve typeof_stable_operandstack. *)\n\n(* Lemma compat_operandstack_app : forall h os1 os2 st1 st2,\n  compat_operandstack h (os1++os2) (st1++st2) ->\n  length os1 = length st1 ->\n  compat_operandstack h os2 st2.\nProof.\n  induction os1; destruct st1; simpl; intuition eauto.\n  discriminate.\n  discriminate.  \nQed.\n\nLemma compat_call : forall kobs se reg prog m sgn i s1 st1 b1 r br m2 sgn2 s0 st0 b0 s2 st2 b2 tau,\n  BigStepWithTypes.exec_call kobs se reg prog m sgn i s1 st1 b1 r br m2 sgn2 s0 st0 b0 (inl _ (s2,st2)) b2 tau ->\n  compat_state sgn s1 st1 ->\n  compat_res sgn2 r ->\n  exec_typeof_rel s0 r ->\n  compat_state sgn s2 st2.\nProof.\n  intros.\n  inversion_mine H; inversion_mine H5; simpl in H0; inv_compat H0; inversion_mine H1;\n    simpl in H2;\n    (split; [idtac|split]); simpl; eauto.\n  rewrite H3; apply compat_operandstack_lift; simpl; split; auto.\n  apply typeof_stable_operandstack with h1; auto.\n  apply compat_operandstack_app with (1:=Hcompat_os).\n  congruence.\n  rewrite H3; apply compat_operandstack_lift; simpl.\n  apply typeof_stable_operandstack with h1; auto.\n  apply compat_operandstack_app with (1:=Hcompat_os).\n  congruence.\n  rewrite H3; repeat apply compat_operandstack_lift; simpl; split; auto.\n  apply typeof_stable_operandstack with h1; auto.\n  destruct (compat_operandstack_app _ _ _ _ _ Hcompat_os); auto.\n  congruence.\n  rewrite H3; repeat apply compat_operandstack_lift; simpl; auto.\n  apply typeof_stable_operandstack with h1; auto.\n  destruct (compat_operandstack_app _ _ _ _ _ Hcompat_os); auto.\n  congruence.\nQed.\n\n\nLemma compat_call_ret : forall kobs se reg prog m sgn i s1 st1 b1 r br m2 sgn2 s0 st0 b0 r2 b2 tau,\n  BigStepWithTypes.exec_call kobs se reg prog m sgn i s1 st1 b1 r br m2 sgn2 s0 st0 b0 (inr _ r2) b2 tau ->\n  compat_state sgn s1 st1 ->\n  compat_res sgn2 r ->\n  exec_typeof_rel s0 r ->\n  compat_res sgn r2.\nProof.\n  intros.\n  inversion_mine H; inversion_mine H5; simpl in H0; inv_compat H0; inversion_mine H1;\n    simpl in H2.\n  constructor.\n  auto.\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_compat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2756402428374104}}
{"text": "(* En este archivo se formalizan las pre y post condiciones de las\n * acciones capaces de mutar el sistema *)\nRequire Import Estado.\nRequire Import EqTheorems.\nRequire Import Operaciones.\nRequire Import RuntimePermissions.\nRequire Import Maps.\n\nSection SemInstall.\n\n(* Indica si un elemento pertenece a una lista *)\nDefinition InBool (A:Set) (aeq : forall x y:A, {x=y} + {x<>y}) (a:A) (list:list A) : bool :=\n    existsb (fun a' => If aeq a a' then true else false) list.\n\n(* Indica si una lista tiene duplicados *)\nFunction has_duplicates (A:Set) (aeq : forall x y:A, {x=y} + {x<>y}) (list:list A) {struct list} : bool :=\n    match list with\n    | nil => false\n    | a::rest => orb (InBool A aeq a rest) (has_duplicates A aeq rest)\n    end.\n\n(* Predicado que se cumple cuando no existe en el sistema un componente con igual identificador que c *)\nDefinition cmpNotInState (c:Cmp) (s:System) : Prop := \nforall (c':Cmp) (a:idApp),\ninApp c' a s ->\ngetCmpId c <> getCmpId c'.\n\n(* Certificado del fabricante del dispositivo *)\nParameter manufactCert : Cert.\n\n(* Indica si el permiso p tiene igual identificador que uno de sistema *)\nDefinition isSystemPermId (p:Perm) : Prop :=\n    (exists p':Perm, isSystemPerm p' /\\ idP p' = idP p).\n\n(* Predicado que se cumple cuando los permisos que define el manifiesto no fueron definidos por otra aplicación en el sistema *)\nDefinition authPerms (m:Manifest)(s:System) : Prop := \nforall (p :Perm),\nIn p (usrP m) -> (* todos los permisos que define la aplicacion *)\n~(isSystemPermId p) -> (* y no sean de sistema (en tal caso se permite pero se ignora!), *)\n~(exists p':Perm, usrDefPerm p' s /\\ idP p' = idP p). (* no estan ya definidos *)\n\n(* Predicado que se cumple si un componente define correctamente sus intentFilters *)\nDefinition cmpDeclareIntentFilterCorrectly (c:Cmp): Prop :=\n(* Si hay filtros de datos o de categorías, debe haber filtros de actividad *)\nmatch c with\n   | cmpAct a => forall (iFil: intentFilter),\n                       (In iFil (intFilterA a)) -> ((dataFilter iFil) <> nil \\/ (catFilter iFil)<> nil) -> \n                        (actFilter iFil) <> nil\n   | cmpSrv s => forall (iFil: intentFilter),\n                       (In iFil (intFilterS s)) -> ((dataFilter iFil) <> nil \\/ (catFilter iFil)<> nil) -> \n                        (actFilter iFil) <> nil\n   | cmpCP _ => True\n   | cmpBR br => forall (iFil: intentFilter),\n                       (In iFil (intFilterB br)) -> ((dataFilter iFil) <> nil \\/ (catFilter iFil)<> nil) -> \n                        (actFilter iFil) <> nil\nend.                                      \n\n(* Precondición de install *)\nDefinition pre_install (a:idApp)(m:Manifest)(c:Cert)(lRes: (list res))(s:System) : Prop := \n(* la aplicación no estaba instalada en el sistema *)\n(~isAppInstalled a s) /\\\n(* no hay dos componentes iguales en la aplicación a instalar *)\n(has_duplicates idCmp idCmp_eq (map getCmpId (cmp m)) = false ) /\\\n(* no hay dos permisos iguales en la aplicación a instalar *)\n(has_duplicates idPerm idPerm_eq (map idP (usrP m)) = false ) /\\\n(* no existe en el sistema ningún componente con igual identificador que los definidos en la aplicación *)\n(forall c:Cmp, In c (cmp m) -> cmpNotInState c s) /\\\n(* no intenta redefinir ningún permiso *)\nauthPerms m s /\\\n(* no hay componentes que definan mal los intent filters *)\n(forall (c:Cmp), In c (cmp m) -> cmpDeclareIntentFilterCorrectly c).\n\n(* Valor incial para los recursos de las aplicaciones *)\nParameter initVal : Val.\n\n(* Agrega el Manifesto al estado estático del sistema *)\nDefinition addManifest (m:Manifest)(a:idApp)(s s':System): Prop :=\n(forall (a':idApp)(m':Manifest), \nmap_apply idApp_eq (manifest (environment s)) a' = Value idApp m' ->\nmap_apply idApp_eq (manifest (environment s')) a' = Value idApp m') /\\\n(forall (a':idApp)(m':Manifest),\nmap_apply idApp_eq (manifest (environment s')) a' = Value idApp m' ->\nmap_apply idApp_eq (manifest (environment s)) a' = Value idApp m' \\/ a = a')/\\\nmap_apply idApp_eq (manifest (environment s')) a = Value idApp m /\\\nmap_correct (manifest (environment s')).\n\n(* Agrega el Certificado al estado estático del sistema *)\nDefinition addCert (c:Cert)(a:idApp)(s s':System): Prop :=\n(forall (a':idApp)(c':Cert), \nmap_apply idApp_eq (cert (environment s)) a' = Value idApp c' ->\nmap_apply idApp_eq (cert (environment s')) a' = Value idApp c') /\\\n(forall (a':idApp)(c':Cert),\nmap_apply idApp_eq (cert (environment s')) a' = Value idApp c' ->\nmap_apply idApp_eq (cert (environment s)) a' = Value idApp c' \\/ a = a')/\\\nmap_apply idApp_eq (cert (environment s')) a = Value idApp c /\\\nmap_correct (cert (environment s')).\n\n(* Agrega la aplicación al estado dinámico del sistema *)\nDefinition addApp (a:idApp)(s s':System) : Prop :=\n(forall a':idApp,\nIn a' (apps (state s)) -> \nIn a' (apps (state s')) ) /\\\n(forall a':idApp,\nIn a' (apps (state s')) -> \nIn a' (apps (state s)) \\/ (a' = a)) /\\\nIn a (apps (state s')).\n\n(* Agrega recursos al estado dinámico del sistema *)\nDefinition addRes (a:idApp)(lRes: list res)(s s':System) : Prop :=\n(forall (a':idApp)(r:res)(v:Val),\nmap_apply rescontdomeq (resCont (state s)) (a', r) = Value (idApp*res) v -> \nmap_apply rescontdomeq (resCont (state s')) (a', r) = Value (idApp*res) v) /\\\n(forall (a':idApp)(r:res)(v:Val),\nmap_apply rescontdomeq (resCont (state s')) (a', r) = Value (idApp*res) v -> \nmap_apply rescontdomeq (resCont (state s)) (a', r) = Value (idApp*res) v \\/ \n(a' = a /\\ In r lRes /\\ v = initVal)) /\\\n(forall r:res, In r lRes -> map_apply rescontdomeq (resCont (state s')) (a, r) = Value (idApp*res) initVal) /\\\nmap_correct (resCont (state s')).\n\n(* Agrega los permisos definidos por el usuario *)\nDefinition addDefPerms (a:idApp)(m:Manifest)(s s':System) : Prop :=\n(forall (a':idApp)(lPerm:list Perm), \nmap_apply idApp_eq (defPerms (environment s)) a' = Value idApp lPerm ->\nmap_apply idApp_eq (defPerms (environment s')) a' = Value idApp lPerm)  /\\\n(forall (a':idApp)(lPerm:list Perm), \nmap_apply idApp_eq (defPerms (environment s')) a' = Value idApp lPerm ->\nmap_apply idApp_eq (defPerms (environment s)) a' = Value idApp lPerm \\/ (a=a')) /\\\n(exists (lPerm: (list Perm)),\nmap_apply idApp_eq (defPerms (environment s')) a = Value idApp lPerm /\\\n(forall (p:Perm), \nIn p (usrP m) /\\ ~ isSystemPermId p <->\nIn p lPerm)) /\\\nmap_correct (defPerms (environment s')).\n\nDefinition initializePermLists (a:idApp) (s s':System) : Prop :=\n(* Se inicializan permisos otorgados a la aplicación como vacíos *)\n(forall (a':idApp)(lPerm: list Perm),\nmap_apply idApp_eq (perms (state s)) a' = Value idApp lPerm -> \nmap_apply idApp_eq (perms (state s')) a' = Value idApp lPerm) /\\\n(forall (a':idApp)(lPerm:list Perm),\nmap_apply idApp_eq (perms (state s')) a' = Value idApp lPerm -> \nmap_apply idApp_eq (perms (state s)) a' = Value idApp lPerm \\/\n(a=a' /\\ lPerm=nil)) /\\\n(map_apply idApp_eq (perms (state s')) a = Value idApp nil) /\\\nmap_correct (perms (state s')).\n\nDefinition initializeGroups (a:idApp) (m: Manifest) (s s': System) : Prop :=\n(* Inicializamos los grupos autorizados. Si hay algún permiso normal que esté agrupado, el grupo se autoriza. *)\n(forall (a':idApp)(lGrp: list idGrp),\nmap_apply idApp_eq (grantedPermGroups (state s)) a' = Value idApp lGrp -> \nmap_apply idApp_eq (grantedPermGroups (state s')) a' = Value idApp lGrp) /\\\n(forall (a':idApp)(lGrp:list idGrp),\nmap_apply idApp_eq (grantedPermGroups (state s')) a' = Value idApp lGrp -> \nmap_apply idApp_eq (grantedPermGroups (state s)) a' = Value idApp lGrp \\/\na=a') /\\\n\n(exists (lGrp: list idGrp),\n  map_apply idApp_eq (grantedPermGroups (state s')) a = Value idApp lGrp /\\\n  (forall (p: Perm) (g: idGrp), In p (use m) /\\ pl p = normal /\\ maybeGrp p = Some g\n    -> In g lGrp)) /\\\n\nmap_correct (grantedPermGroups (state s')).\n\n\n\n(* Postcondición de install *)\nDefinition post_install (a:idApp) (m:Manifest) (c:Cert) (lRes: (list res)) (s s':System) : Prop := \n(* Already runned apps remain the same *)\nalreadyVerified (state s) = alreadyVerified (state s') /\\\n(* Inicializo los grupos, lo hago acá arriba para no tener que modificar tanto en la prueba*)\ninitializeGroups a m s s' /\\\n(* Agregar manifesto, certificado, lista de recursos y permisos definidos al estado estático del sistema *)\naddManifest m a s s' /\\\naddCert c a s s' /\\\naddDefPerms a m s s' /\\\n(* Agregar la aplicación, recursos y permisos al estado dinámico del sistema *)\naddApp a s s' /\\\naddRes a lRes s s' /\\\ninitializePermLists a s s' /\\\n(* el resto de los campos no cambian *)\nrunning (state s) = running (state s') /\\ \ndelPPerms (state s) = delPPerms (state s') /\\ \ndelTPerms (state s) = delTPerms (state s') /\\\nsystemImage (environment s) = systemImage (environment s') /\\\nsentIntents (state s) = sentIntents (state s').\n\nEnd SemInstall.\n\n\nSection SemUninstall.\n\n(* Precondición de uninstall *)\nDefinition pre_uninstall (a:idApp)(s:System) : Prop :=\n(* La aplicación está instalada *)\nIn a (apps (state s))  /\\\n(* y ninguno de sus componentes está en ejecución *)\n(forall (ic:iCmp)(c:Cmp), \nmap_apply iCmp_eq (running (state s)) ic = Value iCmp c -> \n~inApp c a s).\n\n(* Quitar el Manifesto del sistema *)\nDefinition removeManifest (a:idApp) (s s':System) : Prop :=\n(forall (a':idApp)(m':Manifest), \nmap_apply idApp_eq (manifest (environment s')) a' = Value idApp m' ->\nmap_apply idApp_eq (manifest (environment s)) a' = Value idApp m') /\\\n(forall (a':idApp)(m':Manifest),\nmap_apply idApp_eq (manifest (environment s)) a' = Value idApp m' ->\nmap_apply idApp_eq (manifest (environment s')) a' = Value idApp m' \\/ a = a')/\\\n~is_Value (map_apply idApp_eq (manifest (environment s')) a) /\\\nmap_correct (manifest (environment s')).\n\n(* Quitar el Certificado al estado estático del sistema *)\nDefinition removeCert (a:idApp)(s s':System): Prop :=\n(forall (a':idApp)(c':Cert), \nmap_apply idApp_eq (cert (environment s')) a' = Value idApp c' ->\nmap_apply idApp_eq (cert (environment s)) a' = Value idApp c') /\\\n(forall (a':idApp)(c':Cert),\nmap_apply idApp_eq (cert (environment s)) a' = Value idApp c' ->\nmap_apply idApp_eq (cert (environment s')) a' = Value idApp c' \\/ a = a')/\\\n~is_Value (map_apply idApp_eq (cert (environment s')) a) /\\\nmap_correct (cert (environment s')).\n\n(* Quitar la aplicación del sistema *)\nDefinition removeApp (a:idApp)(s s':System) : Prop :=\n(forall a':idApp, In a' (apps (state s')) -> In a' (apps (state s))) /\\\n(forall a':idApp, In a' (apps (state s)) -> In a' (apps (state s')) \\/ a' = a) /\\\n~ In a (apps (state s'))/\\\nremoveManifest a s s' /\\\nremoveCert a s s'.\n\nDefinition removeFromVerified (a:idApp)(s s':System) : Prop :=\n(forall a':idApp, In a' (alreadyVerified (state s')) -> In a' (alreadyVerified (state s))) /\\\n(forall a':idApp, In a' (alreadyVerified (state s)) -> In a' (alreadyVerified (state s')) \\/ a' = a) /\\\n~ In a (alreadyVerified (state s')).\n\n(* Revocar los permisos otorgados a la aplicación *)\nDefinition revokePerms (a:idApp) (s s': System) : Prop := \n(forall (a':idApp) (lPerm': list Perm),\nmap_apply idApp_eq (perms (state s')) a' = Value idApp lPerm' ->\nexists lPerm:list Perm,\nmap_apply idApp_eq (perms (state s)) a' = Value idApp lPerm) /\\\n(forall (a':idApp)(lPerm: list Perm),\nmap_apply idApp_eq (perms (state s)) a' = Value idApp lPerm ->\n(exists lPerm',\nmap_apply idApp_eq (perms (state s')) a' = Value idApp lPerm' /\\\nforall (defPermsA : list Perm) (p:Perm),\nmap_apply idApp_eq (defPerms (environment s)) a = Value idApp defPermsA ->\n((In p lPerm /\\ ~In p defPermsA) <-> In p lPerm')) \\/\na = a')/\\\n~is_Value (map_apply idApp_eq (perms (state s')) a) /\\\nmap_correct (perms (state s')).\n\n(* Revocar los permisos otorgados a la aplicación *)\nDefinition revokePermGroups (a:idApp) (s s': System) : Prop := \n(forall (a':idApp)(lGrps: list idGrp),\nmap_apply idApp_eq (grantedPermGroups (state s')) a' = Value idApp lGrps ->\nmap_apply idApp_eq (grantedPermGroups (state s)) a' = Value idApp lGrps) /\\\n(forall (a':idApp)(lGrps: list idGrp),\nmap_apply idApp_eq (grantedPermGroups (state s)) a' = Value idApp lGrps ->\nmap_apply idApp_eq (grantedPermGroups (state s')) a' = Value idApp lGrps \\/\na = a')/\\\n~is_Value (map_apply idApp_eq (grantedPermGroups (state s')) a) /\\\nmap_correct (grantedPermGroups (state s')).\n\n(* Borrar los permisos definidos por la aplicación *)\nDefinition removeDefPerms (a:idApp) (s s':System) : Prop :=\n(forall (a':idApp)(lPerm: list Perm),\nmap_apply idApp_eq (defPerms (environment s')) a' = Value idApp lPerm ->\nmap_apply idApp_eq (defPerms (environment s)) a' = Value idApp lPerm) /\\\n(forall (a':idApp)(lPerm: list Perm),\nmap_apply idApp_eq (defPerms (environment s)) a' = Value idApp lPerm ->\nmap_apply idApp_eq (defPerms (environment s')) a' = Value idApp lPerm \\/\na = a')/\\\n~is_Value(map_apply idApp_eq (defPerms (environment s')) a) /\\\nmap_correct (defPerms (environment s')).\n\n(* Quitar los recursos de la aplicación *)\nDefinition removeRes (a:idApp) (s s':System) : Prop :=\n(forall (a':idApp)(r:res)(v:Val), map_apply rescontdomeq (resCont (state s')) (a', r) = Value (idApp*res) v -> map_apply rescontdomeq (resCont (state s)) (a', r) = Value (idApp*res) v) /\\\n(forall (a':idApp)(r:res)(v:Val), map_apply rescontdomeq (resCont (state s)) (a', r) = Value (idApp*res) v -> map_apply rescontdomeq (resCont (state s')) (a', r) = Value (idApp*res) v \\/ a = a') /\\\n(forall (r:res), ~is_Value (map_apply rescontdomeq (resCont (state s')) (a, r))) /\\\nmap_correct (resCont (state s')).\n\n(* Borrar los permisos delegados de forma temporal a otras instancias \nen ejecución sobre recursos de algún CProvider de la aplicación *)\nDefinition revokeOtherTPerm (a:idApp)(s s': System) : Prop :=\n(forall (ic:iCmp)(cp:CProvider)(u:uri)(pt:PType),\nmap_apply deltpermsdomeq (delTPerms (state s')) (ic, cp, u) = Value (iCmp*CProvider*uri) pt -> map_apply deltpermsdomeq (delTPerms (state s)) (ic, cp, u) = Value (iCmp*CProvider*uri) pt) /\\\n(forall (ic:iCmp)(cp:CProvider)(u:uri)(pt:PType),\nmap_apply deltpermsdomeq (delTPerms (state s)) (ic, cp, u) = Value (iCmp*CProvider*uri) pt -> map_apply deltpermsdomeq (delTPerms (state s')) (ic, cp, u) = Value (iCmp*CProvider*uri) pt \\/ \ninApp (cmpCP cp) a s) /\\\n(forall (ic:iCmp)(cp:CProvider)(u:uri)(pt:PType),\ninApp (cmpCP cp) a s -> \n~ is_Value (map_apply deltpermsdomeq (delTPerms (state s')) (ic, cp, u))) /\\\nmap_correct (delTPerms (state s')).\n\n(* Borrar los permisos delegados de forma permanente a la aplicación y los permisos delegados de forma permanente \na otras aplicaciones sobre recursos de algún CProvider de la aplicación *)\nDefinition revokePPerm (a:idApp) (s s':System) : Prop :=\n(forall (a':idApp)(cp:CProvider)(u:uri)(pt:PType),\nmap_apply delppermsdomeq (delPPerms (state s')) (a', cp, u) = Value (idApp*CProvider*uri) pt -> map_apply delppermsdomeq (delPPerms (state s)) (a', cp, u) = Value (idApp*CProvider*uri) pt) /\\\n(forall (a':idApp)(cp:CProvider)(u:uri)(pt:PType),\nmap_apply delppermsdomeq (delPPerms (state s)) (a', cp, u) = Value (idApp*CProvider*uri) pt -> map_apply delppermsdomeq (delPPerms (state s')) (a', cp, u) = Value (idApp*CProvider*uri) pt \\/ a = a' \\/ \ninApp (cmpCP cp) a s) /\\\n(forall (cp:CProvider)(u:uri)(pt:PType), ~ is_Value (map_apply delppermsdomeq (delPPerms (state s')) (a, cp, u))) /\\\n(forall (a':idApp)(cp:CProvider)(u:uri)(pt:PType),\ninApp (cmpCP cp) a s->\n~ is_Value (map_apply delppermsdomeq (delPPerms (state s')) (a', cp, u))) /\\\nmap_correct (delPPerms (state s')).\n\n(* Postcondición de uninstall *)\nDefinition post_uninstall (a:idApp)(s s':System) : Prop :=\n(* Se quita la aplciación de la lista de apps verificadas *)\nremoveFromVerified a s s' /\\\n(* Se quita la aplicación de la lista de apps instaladas, *)\nremoveApp a  s s' /\\\n(* Se quitan los permisos otorgados a ella *)\nrevokePerms a s s' /\\\nrevokePermGroups a s s' /\\\n(* Se quitan los permisos que define *)\nremoveDefPerms a s s' /\\\n(* Se quitan sus recursos *)\nremoveRes a s s' /\\\n(* Se revocan permisos delegados a cproviders de ella *)\nrevokeOtherTPerm a s s' /\\\nrevokePPerm a s s'/\\\n(* nada más cambia *)\nrunning (state s) = running (state s') /\\\nsystemImage (environment s) = systemImage (environment s') /\\\nsentIntents (state s) = sentIntents (state s').\n\nEnd SemUninstall.\n\nSection SemGrant.\n\n(* Predicado que se cumple cuando el usuario autoriza el otorgamiento de un permiso *)\nParameter usrAuth : Perm -> Prop. (* no entiendo que significa *)\n\n(* Precondición grant *)\nDefinition pre_grant (p:Perm)(a:idApp)(s:System) : Prop :=\n(exists m:Manifest, isManifestOfApp a m s /\\\nIn p (use m)) /\\ (* Solo permito grantear independientemente permisos declarados en el Manifest *)\n(isSystemPerm p \\/ usrDefPerm p s) /\\ (* , que existan *)\n~(exists lPerm:list Perm, map_apply idApp_eq (perms (state s)) a = Value idApp lPerm /\\ In p lPerm) /\\ (* No hayan sido ya granteados *)\npl p = dangerous /\\ (* , sean peligrosos *)\n(*, el permiso no está agrupado *)\n(maybeGrp p = None \\/\n  (exists (g: idGrp) (lGroup: list idGrp), maybeGrp p = Some g /\\ (* o si el permiso está agrupado, ese grupo no debe haber sido 'otorgado' previamente *)\n    map_apply idApp_eq (grantedPermGroups (state s)) a = Value idApp lGroup /\\ ~(In g lGroup))).\n\n(* Agrega los permisos otorgados a la aplicación *)\nDefinition grantPerm (a:idApp)(p:Perm)(s s':System) : Prop :=\n(forall (a':idApp)(lPerm:list Perm),\nmap_apply idApp_eq (perms (state s)) a' = Value idApp lPerm ->\nexists lPerm':list Perm, map_apply idApp_eq (perms (state s')) a' = Value idApp lPerm' /\\\nforall p':Perm, In p' lPerm -> In p' lPerm') /\\\n\n(forall (a':idApp)(lPerm':list Perm),\nmap_apply idApp_eq (perms (state s')) a' = Value idApp lPerm' ->\nexists lPerm:list Perm, map_apply idApp_eq (perms (state s)) a' = Value idApp lPerm /\\\nforall p':Perm, In p' lPerm' -> ~In p' lPerm -> (a=a' /\\ p=p')) /\\\n\n(exists (lPerm':(list Perm)), map_apply idApp_eq (perms (state s')) a = Value idApp lPerm' /\\ In p lPerm') /\\\nmap_correct (perms (state s')).\n\n(* Marca que un permiso del grupo de permisos g ya fue otorgado a la aplicación *)\nDefinition grantPermGroup (a:idApp)(g:idGrp)(s s':System) : Prop :=\n(forall (a':idApp)(lGrp:list idGrp),\nmap_apply idApp_eq (grantedPermGroups (state s)) a' = Value idApp lGrp ->\nexists lGrp':list idGrp, map_apply idApp_eq (grantedPermGroups (state s')) a' = Value idApp lGrp' /\\\nforall g':idGrp, In g' lGrp -> In g' lGrp') /\\\n(forall (a':idApp)(lGrp':list idGrp),\nmap_apply idApp_eq (grantedPermGroups (state s')) a' = Value idApp lGrp' ->\nexists lGrp:list idGrp, map_apply idApp_eq (grantedPermGroups (state s)) a' = Value idApp lGrp /\\\nforall g':idGrp, In g' lGrp' -> ~In g' lGrp -> (a=a' /\\ g=g')) /\\\n(exists (lGrp':(list idGrp)), map_apply idApp_eq (grantedPermGroups (state s')) a = Value idApp lGrp' /\\ In g lGrp') /\\\nmap_correct (grantedPermGroups (state s')).\n\n(* Postcondición grant *)\nDefinition post_grant (p:Perm)(a:idApp)(s s':System) : Prop :=\n(* Already runned apps remain the same *)\nalreadyVerified (state s) = alreadyVerified (state s') /\\\n(* Se otorga el permiso p a a *)\ngrantPerm a p s s' /\\\n(* y si el permiso está agrupado, marcamos al grupo como otorgado *)\n(forall (g: idGrp), maybeGrp p = Some g -> grantPermGroup a g s s') /\\\n(* pero si no lo está, los grupos permanecen iguales *)\n(maybeGrp p = None -> (grantedPermGroups (state s)) = (grantedPermGroups (state s'))) /\\\n(* nada más cambia *)\n(environment s) = (environment s') /\\\n(apps (state s)) = (apps (state s')) /\\\n(running (state s)) = (running (state s')) /\\\n(delPPerms (state s)) = (delPPerms (state s')) /\\\n(delTPerms (state s)) = (delTPerms (state s')) /\\\n(resCont (state s)) = (resCont (state s')) /\\\n(sentIntents (state s)) = (sentIntents (state s')).\n\nEnd SemGrant.\n\nSection SemGrantAuto.\n\nDefinition pre_grantAuto (p: Perm) (a: idApp) (s: System) : Prop :=\n(* La precondición es casi la misma que la de grant *)\n(exists m:Manifest, isManifestOfApp a m s /\\\nIn p (use m)) /\\\n(isSystemPerm p \\/ usrDefPerm p s) /\\\n~(exists lPerm:list Perm, map_apply idApp_eq (perms (state s)) a = Value idApp lPerm /\\ In p lPerm) /\\\npl p = dangerous /\\\n(* con la diferencia de que el permiso tiene que estar agrupado, y ese grupo ya debe haber sido 'otorgado' antes *)\n(exists (g: idGrp) (lGroup: list idGrp), maybeGrp p = Some g /\\\n    map_apply idApp_eq (grantedPermGroups (state s)) a = Value idApp lGroup /\\\n    In g lGroup).\n\nDefinition post_grantAuto (p:Perm) (a:idApp) (s s':System) : Prop :=\n(* Already runned apps remain the same *)\nalreadyVerified (state s) = alreadyVerified (state s') /\\\n(* Se otorga el permiso p a a *)\ngrantPerm a p s s' /\\\n(* nada más cambia *)\n(environment s) = (environment s') /\\\n(apps (state s)) = (apps (state s')) /\\\n(grantedPermGroups (state s)) = (grantedPermGroups (state s')) /\\\n(running (state s)) = (running (state s')) /\\\n(delPPerms (state s)) = (delPPerms (state s')) /\\\n(delTPerms (state s)) = (delTPerms (state s')) /\\\n(resCont (state s)) = (resCont (state s')) /\\\n(sentIntents (state s)) = (sentIntents (state s')).\nEnd SemGrantAuto.\n\n\nSection SemRevoke.\n\n(* Precondición revoke *)\nDefinition pre_revoke (p:Perm)(a:idApp)(s:System) : Prop :=\n(* El permiso debe estar otorgado *)\n(exists (lPerm : list Perm), map_apply idApp_eq (perms (state s)) a = Value idApp lPerm /\\ In p lPerm) /\\\n(* y no debe esar agrupado*)\nmaybeGrp p = None.\n\n(* Quita el permiso otorgado a la aplicación *)\nDefinition revokePerm (a:idApp)(p:Perm)(s s':System) : Prop :=\n(forall (a':idApp)(lPerm':list Perm),\nmap_apply idApp_eq (perms (state s')) a' = Value idApp lPerm' ->\nexists lPerm:list Perm, map_apply idApp_eq (perms (state s)) a' = Value idApp lPerm /\\\nforall p':Perm, In p' lPerm' -> In p' lPerm) /\\\n\n(forall (a':idApp)(lPerm:list Perm),\nmap_apply idApp_eq (perms (state s)) a' = Value idApp lPerm ->\nexists lPerm':list Perm, map_apply idApp_eq (perms (state s')) a' = Value idApp lPerm' /\\\nforall p':Perm, In p' lPerm -> ~In p' lPerm' -> (a=a' /\\ p=p')) /\\\n\n(exists (lPerm':(list Perm)), map_apply idApp_eq (perms (state s')) a = Value idApp lPerm' /\\ ~In p lPerm') /\\\nmap_correct (perms (state s')).\n\n\n(* Postcondición revoke *)\nDefinition post_revoke (p:Perm)(a:idApp)(s s':System) : Prop :=\n(* Already runned apps remain the same *)\nalreadyVerified (state s) = alreadyVerified (state s') /\\\n(* Se revoca el permiso p a a *)\nrevokePerm a p s s' /\\\n\n(* nada más cambia *)\n(environment s) = (environment s') /\\\napps (state s) = apps (state s') /\\\ngrantedPermGroups (state s) = grantedPermGroups (state s') /\\\nrunning (state s) = running (state s') /\\\ndelPPerms (state s) = delPPerms (state s') /\\\ndelTPerms (state s) = delTPerms (state s') /\\\nresCont (state s) = resCont (state s') /\\\nsentIntents (state s) = sentIntents (state s').\n\nEnd SemRevoke.\n\nSection SemRevokeGroup.\n\n(* Precondición revoke *)\nDefinition pre_revokeGroup (g:idGrp)(a:idApp)(s:System) : Prop :=\n(* El permiso debe estar otorgado *)\nexists (lGrp : list idGrp), map_apply idApp_eq (grantedPermGroups (state s)) a = Value idApp lGrp /\\ In g lGrp.\n\nDefinition revokePermGroup (a:idApp)(g:idGrp)(s s':System) : Prop :=\n(forall (a':idApp)(lGrp':list idGrp),\nmap_apply idApp_eq (grantedPermGroups (state s')) a' = Value idApp lGrp' ->\nexists lGrp:list idGrp, map_apply idApp_eq (grantedPermGroups (state s)) a' = Value idApp lGrp /\\\nforall g':idGrp, In g' lGrp' -> In g' lGrp) /\\\n\n(forall (a':idApp)(lGrp:list idGrp),\nmap_apply idApp_eq (grantedPermGroups (state s)) a' = Value idApp lGrp ->\nexists lGrp':list idGrp, map_apply idApp_eq (grantedPermGroups (state s')) a' = Value idApp lGrp' /\\\nforall g':idGrp, In g' lGrp -> ~In g' lGrp' -> (a=a' /\\ g=g')) /\\\n\n(exists (lGrp':(list idGrp)), map_apply idApp_eq (grantedPermGroups (state s')) a = Value idApp lGrp' /\\ ~In g lGrp') /\\\nmap_correct (grantedPermGroups (state s')).\n\nDefinition revokeGroupedPerms (a: idApp) (g:idGrp) (s s': System) : Prop :=\n(forall (a':idApp)(lPerm':list Perm),\nmap_apply idApp_eq (perms (state s')) a' = Value idApp lPerm' ->\nexists lPerm:list Perm, map_apply idApp_eq (perms (state s)) a' = Value idApp lPerm /\\\nforall p':Perm, In p' lPerm' -> In p' lPerm) /\\\n\n(forall (a':idApp)(lPerm:list Perm),\nmap_apply idApp_eq (perms (state s)) a' = Value idApp lPerm ->\nexists lPerm':list Perm, map_apply idApp_eq (perms (state s')) a' = Value idApp lPerm' /\\\nforall p':Perm, In p' lPerm -> ~In p' lPerm' -> (a=a' /\\ maybeGrp p' = Some g)) /\\\n\n(exists (lPerm':(list Perm)), map_apply idApp_eq (perms (state s')) a = Value idApp lPerm' /\\\n  (forall p:Perm, maybeGrp p = Some g -> ~In p lPerm')) /\\\n\nmap_correct (perms (state s')).\n\n(* Postcondición revoke *)\nDefinition post_revokeGroup (g:idGrp)(a:idApp)(s s':System) : Prop :=\n(* Already runned apps remain the same *)\nalreadyVerified (state s) = alreadyVerified (state s') /\\\n(* Quitamos el grupo g*)\nrevokePermGroup a g s s' /\\\n\n(* Revoco todos los permisos pertenecientes a ese grupo*)\nrevokeGroupedPerms a g s s' /\\\n\n(* nada más cambia *)\n(environment s) = (environment s') /\\\napps (state s) = apps (state s') /\\\nrunning (state s) = running (state s') /\\\ndelPPerms (state s) = delPPerms (state s') /\\\ndelTPerms (state s) = delTPerms (state s') /\\\nresCont (state s) = resCont (state s') /\\\nsentIntents (state s) = sentIntents (state s').\n\nEnd SemRevokeGroup.\n\nSection SemHasPermission.\n\n(* Precondición haspermission *)\nDefinition pre_hasPermission (p:Perm)(c:Cmp)(s:System) : Prop :=\n(* Nada es necesario para preguntar si un componente tiene permisos *)\nTrue.\n\n(* Postcondición haspermission *)\nDefinition post_hasPermission (p:Perm)(c:Cmp)(s s':System) : Prop :=\n(* Su ejecución no muta el sistema *)\ns = s'. \n\nEnd SemHasPermission.\n\nSection SemRead.\n\n(* Proposición que se cumple si el mínimo sdk para correr la aplicación es n *)\nDefinition getCmpMinSdk (c : Cmp) (s:System) (n:nat) : Prop :=\n    (exists (idap:idApp) (mfst:Manifest), isManifestOfApp idap mfst s\n        /\\ inApp c idap s /\\ minSdk mfst = Some n).\n\n(* Proposición que se cumple si el sdk objetiv de la aplicación es n *)\nDefinition getCmpTargetSdk (c : Cmp) (s:System) (n:nat) : Prop :=\n    (exists (idap:idApp) (mfst:Manifest), isManifestOfApp idap mfst s\n        /\\ inApp c idap s /\\ targetSdk mfst = Some n).\n\n(* Proposición que se cumple si el mínimo sdk o la versión objetivo para correr la aplicación es menor que 16 *)\nDefinition getDefaultExp (cp: CProvider) (s:System): Prop :=\nexists (m n : nat), getCmpMinSdk (cmpCP cp) s n /\\ getCmpTargetSdk (cmpCP cp) s m /\\\n(n <= 16 \\/ m <= 16).\n\n(* Predicado que se cumple si el componente c tiene los permisos necesarios para efectuar la operación thisE sobre el content provider cp *)\nDefinition canDoThis (c:Cmp)(cp:CProvider)(s:System) (thisE : CProvider -> option Perm) : Prop :=\nexists (a1 a2:idApp),\n(* c pertenece a a1 *)\ninApp c a1 s /\\\nexists m:Manifest, \nisManifestOfApp a2 m s /\\\n(* cp pertenece a a2, cuyo manifiesto es m *)\nIn (cmpCP cp) (cmp m) /\\\n((((expC cp)= Some true \\/\n(expC cp = None /\\ getDefaultExp cp s))/\\ \nforall p:Perm, (thisE cp) = (Some p) \\/\n(thisE cp = None /\\ cmpEC cp = (Some p)) \\/ \n(thisE cp = None /\\ cmpEC cp = None /\\\nappE m = Some p) ->\nappHasPermission a1 p s (* a1 tiene el permiso necesario para iniciar cp *)\n)\n\\/ a1 = a2). (* o son la misma aplicación *)\n\n(* Proposición que se cumple si el componente c tiene los permisos necesarios para leer el content provider cp *)\nDefinition canRead (c:Cmp)(cp:CProvider)(s:System) : Prop := canDoThis c cp s readE.\n\n(* El componente c tiene permisos delegados para realizar la operación pt sobre el\n  recurso identificado por u del content provider cp *)\nDefinition delPerms (c:Cmp)(cp:CProvider)(u:uri)(pt:PType)(s:System) :=\nexists (a:idApp), \ninApp c a s /\\\n((exists (ic':iCmp) (c':Cmp), \nmap_apply iCmp_eq (running (state s)) ic' = Value iCmp c' /\\ \ninApp c' a s /\\ (map_apply deltpermsdomeq (delTPerms (state s)) (ic', cp, u) = Value (iCmp*CProvider*uri) Both \\/ map_apply deltpermsdomeq (delTPerms (state s)) (ic', cp, u) = Value (iCmp*CProvider*uri) pt)) \\/\nmap_apply delppermsdomeq (delPPerms (state s)) (a, cp, u) = Value (idApp*CProvider*uri) Both \\/\nmap_apply delppermsdomeq (delPPerms (state s)) (a, cp, u) = Value (idApp*CProvider*uri) pt).\n\n(* Precondición de read *)\nDefinition pre_read (ic:iCmp)(cp:CProvider)(u:uri)(s:System) : Prop :=\n(* existe el recurso en el CProvider *)\nexistsRes cp u s /\\\n(* existe un componente en una aplicación instalada, que tiene una instancia en ejecución y\n  tiene permisos de lectura sobre el recurso *)\n(exists (c:Cmp), \nmap_apply iCmp_eq (running (state s)) ic = Value iCmp c /\\\n(canRead c cp s \\/ delPerms c cp u Read s)).\n\n(* Postcondición de read *)\nDefinition post_read (ic:iCmp)(cp:CProvider)(u:uri)(s s':System) : Prop :=\n(* El sistema no varía *)\ns = s'.\n\nEnd SemRead.\n\n\nSection SemWrite.\n\n(* Un componente tiene los permisos necesarios para sobreescribir un recurso de un content provider *)\nDefinition canWrite (c:Cmp)(cp:CProvider)(s:System) : Prop := canDoThis c cp s writeE.\n\n(* Precondición de write *)\nDefinition pre_write (ic:iCmp)(cp:CProvider)(u:uri)(newV:Val)(s:System) : Prop :=\n(* Existe el recurso u en cp *)\nexistsRes cp u s /\\\n(exists (c:Cmp),\n(* ic es una instancia en ejecución de un componente que puede escribir en u de cp *)\nmap_apply iCmp_eq (running (state s)) ic = Value iCmp c /\\\n ~isCProvider c /\\ \n(canWrite c cp s \\/ delPerms c cp u Write s)).\n\n(* Postcondición de write *)\nDefinition post_write (ic:iCmp)(cp:CProvider)(u:uri)(val:Val)(s s':System) : Prop :=\n(* Already runned apps remain the same *)\nalreadyVerified (state s) = alreadyVerified (state s') /\\\n(* Actualizamos el contendo del recurso que se escribió *)\n(forall (a':idApp)(r:res)(v:Val),\nmap_apply rescontdomeq (resCont (state s)) (a', r) = Value (idApp*res) v -> map_apply rescontdomeq (resCont (state s')) (a', r) = Value (idApp*res) v \\/ \n(inApp (cmpCP cp) a' s /\\ \nmap_apply uri_eq (map_res cp) u = Value uri r)) /\\\n(forall (a':idApp)(r:res)(v:Val),\nmap_apply rescontdomeq (resCont (state s')) (a', r) = Value (idApp*res) v -> map_apply rescontdomeq (resCont (state s)) (a', r) = Value (idApp*res) v \\/ \n((inApp (cmpCP cp) a' s)  /\\\nmap_apply uri_eq (map_res cp) u = Value uri r /\\ v = val)) /\\\n(forall (a':idApp)(r:res), inApp (cmpCP cp) a' s ->\nmap_apply uri_eq (map_res cp) u = Value uri r -> \nmap_apply rescontdomeq (resCont (state s')) (a', r) = Value (idApp*res) val) /\\\nmap_correct (resCont (state s')) /\\\n(* El resto del sistema no varía *)\n(environment s) = (environment s') /\\\napps (state s) = apps (state s') /\\ \ngrantedPermGroups (state s) = grantedPermGroups (state s') /\\\nperms (state s) = perms (state s') /\\\nrunning (state s) = running (state s') /\\ \ndelPPerms (state s) = delPPerms (state s') /\\\ndelTPerms (state s) = delTPerms (state s') /\\ \nsentIntents (state s) = sentIntents (state s').\n\nEnd SemWrite.\n\n\nSection SemSendIntent.\n\nDefinition cmpRunning (ic:iCmp) (s:System): Prop :=\n(* existe un componente instalado en una aplicación que está ejecutándose *)\nexists (a:idApp) (c:Cmp),\ninApp c a s /\\\nmap_apply iCmp_eq (running (state s)) ic = Value iCmp c /\\ ~ isCProvider c.\n\n(* Precondición de start activity *)\nDefinition pre_startActivity (i:Intent)(ic:iCmp)(s:System) : Prop := \n(* el intent va dirigido a una actividad *)\n(intType i) = intActivity /\\\n(* No especifica ningún permiso (esto se resuelve luego) *)\n(brperm i) = None /\\\n(* ic es una instancia en ejecución *)\ncmpRunning ic s /\\\n(* No existe un intent con igual identificador ya enviado *)\n~(exists (i':Intent) (ic':iCmp), In (ic',i') (sentIntents (state s)) /\\ idI i' = idI i).\n\n(* Precondición de start activity for result *)\nDefinition pre_startActivityForResult (i:Intent)(int:nat)(ic:iCmp)(s:System) : Prop := \n(* Es la misma que la de startActivity*)\n    pre_startActivity i ic s.\n\n(* Precondición de start service *)\nDefinition pre_startService (i:Intent)(ic:iCmp)(s:System) : Prop := \n(* el intent va dirigido a un servicio *)\n(intType i) = intService /\\\n(* No especifica ningún permiso (esto se resuelve luego) *)\n(brperm i) = None /\\\n(* ic es una instancia en ejecución *)\ncmpRunning ic s /\\\n(* No existe un intent con igual identificador ya enviado *)\n~(exists (i':Intent) (ic':iCmp), In (ic',i') (sentIntents (state s)) /\\ idI i' = idI i).\n\n(* Precondición de send broadcast *)\nDefinition pre_sendBroadcast (i:Intent)(ic:iCmp)(p:option Perm)(s:System) : Prop := \n(* el intent va dirigido a un broadcast receiver *)\n(intType i) = intBroadcast /\\\n(* No especifica ningún permiso (esto se resuelve luego) *)\n(brperm i) = None /\\\n(* ic es una instancia en ejecución *)\ncmpRunning ic s /\\\n(* No existe un intent con igual identificador ya enviado *)\n~(exists (i':Intent) (ic':iCmp), In (ic',i') (sentIntents (state s)) /\\ idI i' = idI i).\n\n(* Precondición de send ordered broadcast *)\nDefinition pre_sendOrderedBroadcast (i:Intent)(ic:iCmp)(p:option Perm)(s:System) : Prop := \n(* Es la misma que la de sendBroadcast *)\n    pre_sendBroadcast i ic p s.\n\n(* Precondición de send sticky broadcast *)\nDefinition pre_sendStickyBroadcast (i:Intent)(ic:iCmp)(s:System) : Prop := \n(* Es la misma que la de sendBroadcast *)\n    pre_sendBroadcast i ic None s.\n\n(* Función que retorna un intent idéntico al especificado pero asignándole un permiso *)\nDefinition createIntent (oldIntent:Intent) (p:option Perm) : Intent :=\n     intent (idI oldIntent)\n            (cmpName oldIntent)\n            (intType oldIntent)\n            (action oldIntent)\n            (data oldIntent)\n            (category oldIntent)\n            (extra oldIntent)\n            (flags oldIntent)\n            p.\n\n(* Agrega el Intent enviado a la lista de Intents enviados del sistema *)\nDefinition addIntent (i:Intent)(ic:iCmp) (p:option Perm) (s s':System) : Prop :=\n(forall (i':Intent)(ic':iCmp), In (ic', i') (sentIntents (state s)) -> In (ic', i') (sentIntents (state s'))) /\\\n(forall (i':Intent)(ic':iCmp), In (ic', i') (sentIntents (state s')) -> In (ic', i') (sentIntents (state s)) \\/\n(ic=ic' /\\\ni'=createIntent i p))/\\\nIn (ic, createIntent i p) (sentIntents (state s')).\n\n(* Solo la lista de intents enviados cambió *)\nDefinition onlyIntentsChanged (s s':System) : Prop :=\n(environment s) = (environment s') /\\\n(apps (state s)) = (apps (state s')) /\\\n(grantedPermGroups (state s)) = (grantedPermGroups (state s')) /\\\n(perms (state s)) = (perms (state s')) /\\\n(running (state s)) = (running (state s')) /\\\n(delPPerms (state s)) = (delPPerms (state s')) /\\\n(delTPerms (state s)) = (delTPerms (state s')) /\\\n(resCont (state s)) = (resCont (state s')) /\\\n(alreadyVerified (state s)) = (alreadyVerified (state s')).\n\n(* Postcondición de start activity *)\nDefinition post_startActivity (i:Intent)(ic:iCmp)(s s':System) : Prop := \n(* Se crea y agrega el intent a la lista de enviados *)\naddIntent i ic None s s' /\\\n(* El resto del sistema no varía *)\nonlyIntentsChanged s s'.\n\n(* Postcondición de start activity for result *)\nDefinition post_startActivityForResult (i:Intent)(int:nat)(ic:iCmp)(s s':System) : Prop := \n(* Es la misma que la de startActivity*)\n    post_startActivity i ic s s'.\n\n(* Postcondición de start service *)\nDefinition post_startService (i:Intent)(ic:iCmp)(s s':System) : Prop := \n(* Es la misma que la de startActivity*)\n    post_startActivity i ic s s'.\n\n(* Postcondición de send broadcast *)\nDefinition post_sendBroadcast (i:Intent)(ic:iCmp)(p:option Perm)(s s':System) : Prop := \n(* Se crea y agrega el intent a la lista de enviados *)\naddIntent i ic p s s' /\\\n(* El resto del sistema no varía *)\nonlyIntentsChanged s s'.\n\n(* Postcondición de send ordered broadcast *)\nDefinition post_sendOrderedBroadcast (i:Intent)(ic:iCmp)(p:option Perm)(s s':System) : Prop := \n(* Es la misma que la de sendBroadcast *)\n    post_sendBroadcast i ic p s s'.\n\n(* Postcondición de send sticky broadcast *)\nDefinition post_sendStickyBroadcast (i:Intent)(ic:iCmp)(s s':System) : Prop := \n    post_startActivity i ic s s'.\n\nEnd SemSendIntent.\n\n\nSection SemResolveIntent.\n\n(* El predicado se cumple si la aplicación puede recibir intents con\n  la acción especificada *)\nDefinition actionTest (i:Intent)(iFil:intentFilter): Prop :=\n((action i) = None /\\ (actFilter iFil) <> nil) \\/ \n(exists (iAct:intentAction), (action i) = Some iAct /\\ In iAct (actFilter iFil)).\n\n\n(* El predicado se cumple si la aplicación puede recibir intents con la \n  categoría especificada *)\nDefinition categoryTest (i:Intent)(iFil:intentFilter): Prop :=\ncategory i = nil \\/ \n(exists (lIntent:list Category), (category i) = lIntent /\\\n(forall cat:Category, In cat lIntent -> In cat (catFilter iFil))).\n\n(* El predicado se cumple si la URI del intent es de tipo 'content' o 'file' *)\nDefinition isContentOrFile (i:Intent) : Prop :=\n(type (data i)) = content \\/ (type (data i)) = file.\n\n(* Si el intent no especifica URI ni tipo MIME, pasa el test si el filtro \n  tampoco lo hace *)\nDefinition notUriAndNotMime (i:Intent)(iFil:intentFilter): Prop :=\npath (data i) = None /\\ \nmime (data i) =None /\\\ndataFilter iFil = nil.\n\n(* Si el intent especifica URI pero no tipo MIME, pasa el test\n  si el filtro especifica la misma URI y no especifica ningún tipo MIME *)\nDefinition uriAndNotMime (i:Intent)(iFil:intentFilter) : Prop :=\npath (data i) <> None /\\\nmime (data i) = None /\\\nexists (d:Data), (data i) = d /\\ In d (dataFilter iFil).\n\n(* Si el intent especifica tipo MIME pero no URI, pasa el test\n  si el filtro lista el mismo tipo MIME y no especifica ninguna URI *)\nDefinition notUriAndMime (i:Intent)(iFil:intentFilter) : Prop :=\npath (data i) = None /\\\nmime (data i) <> None /\\\nexists (d:Data), (data i) = d /\\ In d (dataFilter iFil).\n\n\n(* Si el intent especifica tipo MIME y URI, pasa el test\n  si el filtro lista el mismo tipo MIME y \n  el filtro lista la misma URI o \n  la URI contiene un content: o file: y el filtro no lista ninguna URI *)\nDefinition uriAndMime (i:Intent)(iFil:intentFilter) : Prop :=\npath (data i) <> None /\\\nmime (data i) <> None /\\\n(exists (dCmp1:Data)(dCmp2:Data),\n(mime (data i) = mime dCmp1 /\\ In dCmp1 (dataFilter iFil) /\\\n(path (data i) = path dCmp2 \\/ (isContentOrFile i /\\ path dCmp2 = None)) /\\ In dCmp2 (dataFilter iFil))).\n\n(* El predicado se cumple si se cumplen alguno de los cuatro tests especificados\n  anteriormente *)\nDefinition dataTest (i:Intent)(iFil:intentFilter): Prop :=\nnotUriAndNotMime i iFil \\/\nuriAndNotMime i iFil \\/\nnotUriAndMime i iFil \\/\nuriAndMime i iFil.\n\n(* El componente c tiene definido algún intent filter *)\nDefinition canBeStarted (c:Cmp) (s:System): Prop :=\n match c with\n    | cmpAct a => (expA a = Some true) \\/ (expA a = None /\\ (intFilterA a) = nil)\n    | cmpSrv sr => (expS sr = Some true) \\/ (expS sr = None /\\ (intFilterS sr) = nil)\n    | cmpCP cp => (expC cp = Some true) \\/ (expC cp = None /\\ getDefaultExp cp s)\n    | cmpBR br => (expB br = Some true) \\/ (expB br = None /\\ (intFilterB br) = nil)\n end.\n\n(* El componente c1 tiene los permisos para iniciar al componente c2 mandando un intent explícito *)\nDefinition canStart (c1 c2: Cmp)(s:System) : Prop :=\nexists (a1 a2:idApp),\ninApp c1 a1 s /\\ inApp c2 a2 s /\\\n(* Ambos componentes pertenecen a la misma aplicación o *)\n(a1 = a2 \\/\n(* c2 puede ser iniciado por otro componente y *)\n(canBeStarted c2 s /\\\n(* a1 tiene los permisos de acceso *)\n(forall (p:Perm)(m:Manifest),\nisManifestOfApp a1 m s /\\\nmatch c2 with \n    | cmpAct a => (cmpEA a = Some p \\/ (cmpEA a = None /\\ (appE m) = Some p))\n    | cmpSrv s => (cmpES s = Some p \\/ (cmpES s = None /\\ (appE m) = Some p))\n    | cmpCP cp => (cmpEC cp = Some p \\/ (cmpEC cp = None /\\ (appE m) = Some p))\n    | cmpBR br => (cmpEB br = Some p \\/ (cmpEB br = None /\\ (appE m) = Some p))\nend ->\nappHasPermission a1 p s))).\n\n(* Precondición de resolve intent *)\nDefinition pre_resolveIntent (idi:Intent)(a:idApp)(s:System) : Prop := \nexists (i:Intent),\n(* El id del intent que se desea resolver debe existir *)\nidI idi = idI i /\\\n(* , debe ser implícito *)\n(cmpName i) = None /\\\nexists ic:iCmp,\nIn (ic ,i) (sentIntents (state s)) /\\\nexists c1:Cmp,\n(* fue enviado por una instancia en ejecución de c1 *)\nmap_apply iCmp_eq (running (state s)) ic = Value iCmp c1 /\\\nexists c2:Cmp,\n(* existe algún componente *)\ninApp c2 a s /\\\n(exists (iFil: intentFilter),\n(* uno de cuyos filtros es satisfecho por el intent *)\nmatch (intType i) with\n    | intActivity => exists act:Activity, (cmpAct act) = c2 /\\ In iFil (intFilterA act)\n    | intService => exists sr:Service, (cmpSrv sr) = c2 /\\ In iFil (intFilterS sr)\n    | intBroadcast => exists br:BroadReceiver, (cmpBR br) = c2 /\\ In iFil (intFilterB br)\nend /\\\nactionTest i iFil /\\\ncategoryTest i iFil /\\\ndataTest i iFil) /\\\n(* y efectivamente es iniciable por c1 *)\ncanStart c1 c2 s.\n\n(* El Intent que se resuelve pasa a ser explícito *)\nDefinition implicitToExplicitIntent (idi:idInt)(a:idApp)(s s':System) : Prop :=\n(exists (c c1:Cmp), inApp c a s /\\\n(* c será el componente receptor del intent, cuya existencia aseguró la precondición *)\n(exists (ic:iCmp) (i:Intent),\n(cmpName i) = None /\\\nidi = idI i /\\\nIn (ic ,i) (sentIntents (state s)) /\\\nmap_apply iCmp_eq (running (state s)) ic = Value iCmp c1 /\\\n(exists (iFil: intentFilter),\nmatch (intType i) with\n    | intActivity => exists act:Activity, (cmpAct act) = c /\\ In iFil (intFilterA act)\n    | intService => exists sr:Service, (cmpSrv sr) = c /\\ In iFil (intFilterS sr)\n    | intBroadcast => exists br:BroadReceiver, (cmpBR br) = c /\\ In iFil (intFilterB br)\nend /\\\nactionTest i iFil /\\\ncategoryTest i iFil /\\\ndataTest i iFil)) /\\\ncanStart c1 c s /\\\n(* Todo intent anterior que no es quien se está resolvieno, se mantiene *)\n(forall (i:Intent)(ic:iCmp), In (ic,i) (sentIntents (state s)) ->\nIn (ic,i) (sentIntents (state s')) \\/ idi = idI i ) /\\\n(* Todos los nuevos intents o existían antes (y no son el que se está resolviendo)\n*  o son el que se está resolviendo, actualizado *)\n(forall (i:Intent)(ic:iCmp), In (ic,i) (sentIntents (state s')) -> \n(In (ic,i) (sentIntents (state s)) /\\ idI i <> idi) \\/ \nexists (i':Intent), \nIn (ic,i') (sentIntents (state s)) /\\\nidI i' = idi /\\\nidI i' = idI i /\\\ncmpName i = Some (getCmpId c) /\\\nintType i' = intType i /\\\naction i' = action i /\\\ndata i' = data i /\\\ncategory i' = category i /\\\nextra i' = extra i /\\\nflags i' = flags i /\\\nbrperm i' = brperm i) /\\\n(* El intent actualizado forma parte del nuevo estado *)\n(forall (ic:iCmp) (i:Intent),\nIn (ic, i) (sentIntents (state s)) -> \nidI i = idi ->\n(exists (i':Intent),\nIn (ic,i') (sentIntents (state s')) /\\\n(idI i' = idI i /\\\ncmpName i' = Some (getCmpId c) /\\\nintType i' = intType i /\\\naction i' = action i /\\\ndata i' = data i /\\\ncategory i' = category i /\\\nextra i' = extra i /\\\nflags i' = flags i /\\\nbrperm i' = brperm i)\n))).\n\n(* Postcondición de resolve intent *)\nDefinition post_resolveIntent (i:Intent)(a:idApp)(s s':System) : Prop :=\n(* Already runned apps remain the same *)\nalreadyVerified (state s) = alreadyVerified (state s') /\\\n(* Se explicita el intent *)\nimplicitToExplicitIntent (idI i) a s s' /\\\n(* el resto de los componentes del estado se mantienen iguales *)\n(environment s) = (environment s') /\\\n(apps (state s)) = (apps (state s')) /\\\n(grantedPermGroups (state s)) = (grantedPermGroups (state s')) /\\\n(perms (state s)) = (perms (state s')) /\\\n(running (state s)) = (running (state s')) /\\\n(delPPerms (state s)) = (delPPerms (state s')) /\\\n(delTPerms (state s)) = (delTPerms (state s')) /\\\n(resCont (state s)) = (resCont (state s')).\n\nEnd SemResolveIntent.\n\n\nSection SemReceiveIntent.\n\n(* El intent está dirigido a un componente de la aplicación *)\nDefinition intentForApp (i:Intent)(a:idApp)(c:Cmp)(ic:iCmp)(s:System) : Prop :=\n(cmpName i) = Some (getCmpId c) /\\ \nIn (ic,i) (sentIntents (state s)) /\\\ninApp c a s.\n\n(* El content provider permite delegar permisos sobre el recurso referido por el id *)\nDefinition canGrant (cp:CProvider)(u:uri)(s:System) : Prop :=\nexists (a:idApp),\n(* Si es un componente presente en el sistema y *)\ninApp (cmpCP cp) a s /\\\n(* el cprovider define u como otorgable o *)\n(In u (uriP cp)  \\/\n(* el cprovider no especifica que uris son otorgables y\n* dice que todas ellas son otorgables *)\n(~(exists u':uri, In u' (uriP cp)) /\\ (grantU cp) = true)).\n\n(* Dado un Intent, se necesita conocer el tipo de acceso que efectuará *)\nParameter intentActionType: Intent -> PType. \n\n(* Defino un predicado que establece las condiciones en las que una aplicación puede correr *)\nDefinition canRun (a: idApp) (s: System) : Prop :=\n(* Puede ejecutarse si ya fue ejecutada previamente*)\nIn a (alreadyVerified (state s)) \\/\n(* o si el targetSdk de la aplicación existe y es lo suficientemente alto *)\n(exists (m: Manifest) (n: nat),\n    isManifestOfApp a m s /\\ targetSdk m = Some n /\\ n > vulnerableSdk).\n\n(* Precondición de receive intent *)\nDefinition pre_receiveIntent (i:Intent)(ic:iCmp)(a:idApp)(s:System): Prop :=\n(* a puede recibir el intent si está en condiciones de ser ejecutada *)\ncanRun a s /\\\n(* a puede recibir el intent si está destinado a uno de sus componentes *)\nexists (c:Cmp), intentForApp i a c ic s /\\\n(* que no es un cprovider *)\n~isCProvider c /\\\nexists (c':Cmp),\n(* fue enviado por una instancia en ejecución de c' *)\nmap_apply iCmp_eq (running (state s)) ic = Value iCmp c' /\\\n~isCProvider c' /\\\n(* quien puede iniciarlo *)\ncanStart c' c s /\\\n((intType i) = intActivity ->\nforall (u:uri), path (data i)= Some u ->\n(* si el intent es de actividad y accede a u *)\n(exists (cp:CProvider), \n(*, u debe existir en algún cprovider cp *)\nexistsRes cp u s /\\\n(* u debe soportar otorgamiento de permisos *)\ncanGrant cp u s /\\\n(* quien lo envio'debe tener tales permisos *)\nmatch (intentActionType i) with\n   | Read => canRead c' cp s \\/ delPerms c' cp u Read s (* Se permite la redelegación *)\n   | Write => canWrite c' cp s \\/ delPerms c' cp u Write s\n   | Both => (canRead c' cp s \\/ delPerms c' cp u Read s) /\\ (canWrite c' cp s \\/ delPerms c' cp u Write s)\nend)) /\\\n((intType i) = intBroadcast /\\ (brperm i) <> None ->\n(* si el intent es de broadcast y define un permiso necesario, *)\n(exists (p:Perm),\n(brperm i) = Some p /\\\n(* la aplicación debe contar con él *)\nappHasPermission a p s)).\n\n\n(* El componente ic no se está ejecutando en el sistema *)\nDefinition insNotInState (ic:iCmp) (s:System) : Prop :=\n~is_Value (map_apply iCmp_eq (running (state s)) ic).\n\n(* Ejecución de ic en s' *)\nDefinition runCmp (i:Intent)(ic:iCmp)(c:Cmp)(s s':System): Prop :=\n(* Todo lo que estaba ejecutándose se mantiene *)\n(forall (ic':iCmp)(c':Cmp), \nmap_apply iCmp_eq (running (state s)) ic' = Value iCmp c' -> \nmap_apply iCmp_eq (running (state s')) ic' = Value iCmp c')/\\ \n(* Todo lo nuevo en ejecución o existía o es la instancia que estamos iniciando *)\n(forall (ic':iCmp)(c':Cmp), \nmap_apply iCmp_eq (running (state s')) ic' = Value iCmp c' -> \nmap_apply iCmp_eq (running (state s)) ic' = Value iCmp c' \\/ (ic=ic'/\\ c=c')) /\\\n(* La instancia que estamos iniciando forma parte del nuevo estado*)\nmap_apply iCmp_eq (running (state s')) ic = Value iCmp c /\\\n(* running sigue siendo una func parcial *)\nmap_correct (running (state s')).\n\n(* Se quitó el Intent de la lista de enviados *)\nDefinition removeIntent (i:Intent)(ic:iCmp)(s s':System) : Prop :=\n(forall (i':Intent)(ic':iCmp), In (ic',i') (sentIntents (state s')) -> In (ic',i') (sentIntents (state s))) /\\\n(forall (i':Intent)(ic':iCmp), In (ic',i') (sentIntents (state s)) -> In (ic',i') (sentIntents (state s')) \\/ \n(i = i' /\\ ic = ic')) /\\\n~(In (ic,i) (sentIntents (state s'))).\n\n(* Se otorga permiso temporal a ic de acceso pt sobre el uri u del cprovider cp *)\nDefinition grantTempPerm (pt:PType)(u:uri)(cp:CProvider)(ic:iCmp)(s s':System) : Prop :=\n((forall (ic':iCmp)(cp':CProvider)(u':uri)(pt':PType),\nmap_apply deltpermsdomeq (delTPerms (state s)) (ic', cp', u') = Value (iCmp*CProvider*uri) pt' -> map_apply deltpermsdomeq (delTPerms (state s')) (ic', cp', u') = Value (iCmp*CProvider*uri) pt') /\\\n(forall (ic':iCmp)(cp':CProvider)(u':uri)(pt':PType),\nmap_apply deltpermsdomeq (delTPerms (state s')) (ic', cp', u') = Value (iCmp*CProvider*uri) pt' -> \nmap_apply deltpermsdomeq (delTPerms (state s)) (ic', cp', u') = Value (iCmp*CProvider*uri) pt' \\/ (ic=ic'/\\cp=cp'/\\u=u'/\\pt=pt')) /\\\nmap_apply deltpermsdomeq (delTPerms (state s')) (ic, cp, u) = Value (iCmp*CProvider*uri) pt ) /\\\nmap_correct (delTPerms (state s')).\n\n(* Postcondición de receive intent *)\nDefinition post_receiveIntent (i:Intent)(ic:iCmp)(a:idApp)(s s':System):Prop :=\n(exists (ic':iCmp)(c:Cmp), intentForApp i a c ic s /\\\n~isCProvider c /\\\n(* ic' no debe ser el id de una instancia ya en ejecución *)\ninsNotInState ic' s /\\ \n(* se inicia una instancia de c con identificador ic' *)\nrunCmp i ic' c s s' /\\\n(* si es una actividad *)\n((intType i) = intActivity ->\n(exists (u:uri)(cp:CProvider), \n(* y accede a una uri u *)\npath (data i)=Some u /\\\nexistsRes cp u s /\\\n(* se grantea el permiso temporal correspondiente *)\ngrantTempPerm (intentActionType i) u cp ic' s s')  \\/ \n(* si no, los permisos temporales no cambian *)\npath (data i) = None /\\ (delTPerms (state s)) = (delTPerms (state s'))) /\\\n(* si es un servicio o un broadcast receiver los permisos temporales no cambian *)\n((intType i) = intService ->\n(delTPerms (state s)) = (delTPerms (state s'))) /\\\n((intType i) = intBroadcast ->\n(delTPerms (state s)) = (delTPerms (state s')))) /\\\n(* se quita el intent recibido de la lista de intents enviados *)\nremoveIntent i ic s s' /\\\n(* s y s' difieren a lo sumo solo en running y sentIntents y delTPerms *)\n(environment s) = (environment s') /\\\n(apps (state s)) = (apps (state s')) /\\\n(grantedPermGroups (state s)) = (grantedPermGroups (state s')) /\\\n(perms (state s)) = (perms (state s')) /\\\n(delPPerms (state s)) = (delPPerms (state s')) /\\\n(resCont (state s)) = (resCont (state s')) /\\\nalreadyVerified (state s) = alreadyVerified (state s').\n\nEnd SemReceiveIntent.\n\n\nSection SemStop.\n\n(* Precondición de stop *)\nDefinition pre_stop (ic: iCmp)(s: System) : Prop :=\n(* ic debe existir entre los ids de instancia en ejecución *)\nexists (c:Cmp), map_apply iCmp_eq (running (state s)) ic = Value iCmp c.\n\n(* Postcondición de stop *)\nDefinition post_stop (ic:iCmp)(s s':System) : Prop :=\n(* Already runned apps remain the same *)\nalreadyVerified (state s) = alreadyVerified (state s') /\\\n(* stopIns: Borrar la instancia en ejecución *)\n(forall (ic':iCmp)(c':Cmp), \nmap_apply iCmp_eq (running (state s')) ic' = Value iCmp c' ->\nmap_apply iCmp_eq (running (state s)) ic' = Value iCmp c')/\\\n(forall (ic':iCmp)(c':Cmp), \nmap_apply iCmp_eq (running (state s)) ic' = Value iCmp c' ->\nmap_apply iCmp_eq (running (state s')) ic' = Value iCmp c' \\/ ic=ic')/\\\nmap_correct (running (state s')) /\\\ninsNotInState ic s' /\\\n(* revokeTPermsIns: Si se delegó algún permiso temporal a la instancia, revocarlo *)\n(forall (ic':iCmp)(cp:CProvider)(u:uri)(pt:PType), map_apply deltpermsdomeq (delTPerms (state s')) (ic', cp, u) = Value (iCmp*CProvider*uri) pt -> \nmap_apply deltpermsdomeq (delTPerms (state s)) (ic', cp, u) = Value (iCmp*CProvider*uri) pt) /\\\n(forall (ic':iCmp)(cp:CProvider)(u:uri)(pt:PType), map_apply deltpermsdomeq (delTPerms (state s)) (ic', cp, u) = Value (iCmp*CProvider*uri) pt -> \n(map_apply deltpermsdomeq (delTPerms (state s')) (ic', cp, u) = Value (iCmp*CProvider*uri) pt \\/ ic' = ic)) /\\\n(forall (cp:CProvider)(u:uri), ~is_Value (map_apply deltpermsdomeq (delTPerms (state s')) (ic, cp, u))) /\\\n(* asegurar la corrección de la función delTPerms *)\nmap_correct (delTPerms (state s')) /\\\n(* el resto de los componentes no cambian *)\n(environment s) = (environment s') /\\\napps (state s) = apps (state s') /\\ \ngrantedPermGroups (state s) = grantedPermGroups (state s') /\\ \nperms (state s) = perms (state s') /\\ \ndelPPerms (state s) = delPPerms (state s') /\\ \nresCont (state s) = resCont (state s') /\\ \nsentIntents (state s) = sentIntents (state s').\n\nEnd SemStop.\n\n\nSection SemGrantP.\n\n(* Precondición de grantp *)\nDefinition pre_grantP (ic:iCmp)(cp:CProvider)(a:idApp)(u:uri)(pt:PType)(s:System) : Prop :=\n(* el uri u debe ser otorgable *)\ncanGrant cp u s /\\\n(* debe existir en cp *)\nexistsRes cp u s /\\ \n(* a debe ser una aplicación instalada en el sistema *)\nisAppInstalled a s /\\\nexists (c:Cmp),\n(* ic es una instancia en ejecución de c *)\nmap_apply iCmp_eq (running (state s)) ic = Value iCmp c /\\\n(* quien cuenta con el permiso que quiere otorgar *)\nmatch pt with\n   | Read => canRead c cp s \\/ delPerms c cp u Read s\n   | Write => canWrite c cp s \\/ delPerms c cp u Write s\n   | Both => (canRead c cp s \\/ delPerms c cp u Read s) /\\ (canWrite c cp s \\/ delPerms c cp u Write s)\nend.\n\n(* Función que suma dos permisos *)\nDefinition ptplus (pt pt':PType) : PType :=\nmatch pt with\n    | Both => Both\n    | Read => match pt' with\n        | Read => Read\n        | _ => Both\n        end\n    | Write=> match pt' with\n        | Write => Write\n        | _ => Both\n        end\nend.\n\n(* Postcondición de grantp *)\nDefinition post_grantP (ic:iCmp)(cp:CProvider)(a:idApp)(u:uri)(pt:PType)(s s':System) : Prop :=\n(* Already runned apps remain the same *)\nalreadyVerified (state s) = alreadyVerified (state s') /\\\n(* Todo otorgamiento que no sea el que estamos pisando, permanece igual *)\n(forall (a':idApp)(cp':CProvider)(u':uri)(pt':PType),\nmap_apply delppermsdomeq (delPPerms (state s)) (a', cp', u') = Value (idApp*CProvider*uri) pt' -> \n((a=a'/\\cp=cp'/\\u=u') ->\nmap_apply delppermsdomeq (delPPerms (state s')) (a', cp', u') = Value (idApp*CProvider*uri) (ptplus pt pt')) /\\\n(~(a=a'/\\cp=cp'/\\u=u') ->\nmap_apply delppermsdomeq (delPPerms (state s')) (a', cp', u') = Value (idApp*CProvider*uri) pt')\n) /\\\n(* se suma el pt actual al que ya tenía previamente *)\n(forall (a':idApp)(cp':CProvider)(u':uri)(pt':PType),\nmap_apply delppermsdomeq (delPPerms (state s')) (a', cp', u') = Value (idApp*CProvider*uri) pt' -> \n((a=a'/\\cp=cp'/\\u=u') ->\nmatch map_apply delppermsdomeq (delPPerms (state s)) (a', cp', u') with\n    | Value _ pt'' => ptplus pt pt'' = pt'\n    | _ => pt = pt'\nend\n) /\\\n(~(a=a'/\\cp=cp'/\\u=u') ->\nmap_apply delppermsdomeq (delPPerms (state s)) (a', cp', u') = Value (idApp*CProvider*uri) pt')) /\\\nmap_apply delppermsdomeq (delPPerms (state s')) (a, cp, u) =\nmatch map_apply delppermsdomeq (delPPerms (state s)) (a, cp, u) with\n    | Value _ pt' => Value (idApp*CProvider*uri) (ptplus pt' pt)\n    | _ => Value (idApp*CProvider*uri) pt\nend /\\\n(* se debe asegurar la corrección de delPPerms *)\nmap_correct (delPPerms (state s')) /\\\n(* El resto de los campos del estado no cambian *)\n(environment s) = (environment s') /\\\napps (state s) = apps (state s') /\\\ngrantedPermGroups (state s) = grantedPermGroups (state s') /\\\nperms (state s) = perms (state s') /\\\nrunning (state s) = running (state s') /\\\ndelTPerms (state s) = delTPerms (state s') /\\\nresCont (state s) = resCont (state s') /\\\nsentIntents (state s) = sentIntents (state s').\n\nEnd SemGrantP.\n\n\nSection SemRevokeDel.\n\n(* Precondición de revokedel *)\nDefinition pre_revokeDel (ic:iCmp)(cp:CProvider)(u:uri)(pt:PType)(s:System) : Prop :=\n(* el recurso apuntado por u debe existir en cp *)\nexistsRes cp u s /\\\nexists (c:Cmp),\nmap_apply iCmp_eq (running (state s)) ic = Value iCmp c /\\\n(* el componente del cual ic es una instancia en ejecución debe tener el permiso que desea revocar *)\nmatch pt with\n   | Read => canRead c cp s \\/ delPerms c cp u Read s\n   | Write => canWrite c cp s \\/ delPerms c cp u Write s\n   | Both => (canRead c cp s \\/ delPerms c cp u Read s) /\\ (canWrite c cp s \\/ delPerms c cp u Write s)\nend.\n\n(* Función de resta de tipos de acceso *)\nDefinition ptminus (pt pt':PType) : option PType :=\nmatch pt' with\n    | Both => None\n    | Read => match pt with\n        | Read => None\n        | _ => Some Write\n        end\n    | Write=> match pt with\n        | Write => None\n        | _ => Some Read\n        end\nend.\n\n\n(* Postcondición de revokedel *)\nDefinition post_revokeDel (ic:iCmp)(cp:CProvider)(u:uri)(pt:PType)(s s':System) : Prop :=\n(* Already runned apps remain the same *)\nalreadyVerified (state s) = alreadyVerified (state s') /\\\n(* Todo otorgamiento que no sea el que estamos pisando, permanece igual *)\n(forall (ic':iCmp)(cp':CProvider)(u':uri)(pt':PType),\nmap_apply deltpermsdomeq (delTPerms (state s')) (ic', cp', u') = Value (iCmp*CProvider*uri) pt' -> \nexists pt'':PType, map_apply deltpermsdomeq (delTPerms (state s)) (ic', cp', u') = Value (iCmp*CProvider*uri) pt'' /\\\n(pt'' = pt' \\/\n(cp' = cp /\\ u' = u /\\ ptminus pt'' pt = Some pt'))\n) /\\\n(forall (ic':iCmp)(cp':CProvider)(u':uri)(pt':PType),\nmap_apply deltpermsdomeq (delTPerms (state s)) (ic', cp', u') = Value (iCmp*CProvider*uri) pt' -> \n(ptminus pt' pt = None /\\ cp'=cp /\\ u'=u) \\/\n(exists pt'':PType, map_apply deltpermsdomeq (delTPerms (state s')) (ic', cp', u') = Value (iCmp*CProvider*uri) pt'' /\\ \n(pt'' = pt' \\/\n(cp' = cp /\\ u' = u /\\ ptminus pt' pt = Some pt'')))) /\\\n(* se pisa el permiso temporal con la resta entre él y el que se desea quitar *)\n(forall ic':iCmp,\nmatch map_apply deltpermsdomeq (delTPerms (state s)) (ic', cp, u) with\n    | Error _ _ => ~(is_Value (map_apply deltpermsdomeq (delTPerms (state s')) (ic', cp, u)))\n    | Value _ pt' => match ptminus pt' pt with\n        | None => ~(is_Value (map_apply deltpermsdomeq (delTPerms (state s')) (ic', cp, u)))\n        | Some pt'' => map_apply deltpermsdomeq (delTPerms (state s')) (ic', cp, u) = Value (iCmp*CProvider*uri) pt''\n        end\n    end) /\\\n(* se debe asegurar la corrección de delTPerms *)\nmap_correct (delTPerms (state s')) /\\\n(* Todo otorgamiento que no sea el que estamos pisando, permanece igual *)\n(forall (a':idApp)(cp':CProvider)(u':uri)(pt':PType),\nmap_apply delppermsdomeq (delPPerms (state s')) (a', cp', u') = Value (idApp*CProvider*uri) pt' -> \nexists pt'':PType, map_apply delppermsdomeq (delPPerms (state s)) (a', cp', u') = Value (idApp*CProvider*uri) pt'' /\\\n(pt'' = pt' \\/\n(cp' = cp /\\ u' = u /\\ ptminus pt'' pt = Some pt'))\n) /\\\n(* se pisa el permiso temporal con la resta entre él y el que se desea quitar *)\n(forall (a':idApp)(cp':CProvider)(u':uri)(pt':PType),\nmap_apply delppermsdomeq (delPPerms (state s)) (a', cp', u') = Value (idApp*CProvider*uri) pt' -> \n(ptminus pt' pt = None /\\ cp'=cp /\\ u'=u) \\/\n(exists pt'':PType, map_apply delppermsdomeq (delPPerms (state s')) (a', cp', u') = Value (idApp*CProvider*uri) pt'' /\\ \n(pt'' = pt' \\/\n(cp' = cp /\\ u' = u /\\ ptminus pt' pt = Some pt'')))) /\\\n(forall a':idApp,\nmatch map_apply delppermsdomeq (delPPerms (state s)) (a', cp, u) with\n    | Error _ _ => ~(is_Value (map_apply delppermsdomeq (delPPerms (state s')) (a', cp, u)))\n    | Value _ pt' => match ptminus pt' pt with\n        | None => ~(is_Value (map_apply delppermsdomeq (delPPerms (state s')) (a', cp, u)))\n        | Some pt'' => map_apply delppermsdomeq (delPPerms (state s')) (a', cp, u) = Value (idApp*CProvider*uri) pt''\n    end\nend) /\\\n(* se debe asegurar la corrección de delTPerms *)\nmap_correct (delPPerms (state s')) /\\\n(* El resto de los campos no cambian *)\n(environment s) = (environment s') /\\\napps (state s) = apps (state s') /\\ \ngrantedPermGroups (state s) = grantedPermGroups (state s') /\\ \nperms (state s) = perms (state s') /\\ \nrunning (state s) = running (state s') /\\ \nresCont (state s) = resCont (state s') /\\ \nsentIntents (state s) = sentIntents (state s').\n\nEnd SemRevokeDel.\n\n\nSection SemCall.\n\n(* Predicado para determinar qué permisos requiere determinada llamada a una API del sistema *)\nParameter permSAC : forall p:Perm, isSystemPerm p -> SACall -> Prop.\n\n(* Precondición de call *)\nDefinition pre_call (ic:iCmp)(sac:SACall)(s:System) : Prop :=\n(* El componente del cual ic es una instancia en ejecución debe tener todos los permisos requeridos para efectuar sac *)\nexists c:Cmp, \nmap_apply iCmp_eq (running (state s)) ic = Value iCmp c /\\\nforall (a:idApp)(p:Perm)(H:isSystemPerm p), \ninApp c a s -> \npermSAC p H sac -> \nappHasPermission a p s.\n\n(* Postcondición de call *)\nDefinition post_call (ic:iCmp)(sac:SACall)(s s':System) : Prop :=\n(* El sistema permanece invariante *)\ns = s'.\n\nEnd SemCall.\n\nSection SemVerifyOldApp.\n\nDefinition isOldApp (a: idApp) (s: System) : Prop :=\n(exists (m:Manifest) (n: nat),\n    isManifestOfApp a m s /\\ targetSdk m = Some n /\\ n < vulnerableSdk).\n\nDefinition pre_verifyOldApp (a: idApp) (s: System) : Prop :=\n(* Chequeamos que la aplicación esté instalada ... *)\nisAppInstalled a s /\\\n(* ... que no haya sido ejecutada nunca ... *)\n~ (In a (alreadyVerified (state s))) /\\\n(* ... y que el targetSdk sea lo suficientemente viejo *)\nisOldApp a s.\n\nDefinition revokeGrantedPerms (a:idApp) (s s': System) : Prop :=\n(* (forall (a':idApp) (lPerm': list Perm),\nmap_apply idApp_eq (perms (state s')) a' = Value idApp lPerm' ->\nmap_apply idApp_eq (perms (state s)) a' = Value idApp lPerm' \\/\na = a') /\\ *)\n\n(forall (a':idApp)(lPerm':list Perm),\nmap_apply idApp_eq (perms (state s')) a' = Value idApp lPerm' ->\nexists lPerm:list Perm, map_apply idApp_eq (perms (state s)) a' = Value idApp lPerm /\\\nforall p':Perm, In p' lPerm' -> In p' lPerm) /\\\n\n(* (forall (a':idApp)(lPerm: list Perm),\nmap_apply idApp_eq (perms (state s)) a' = Value idApp lPerm ->\nmap_apply idApp_eq (perms (state s')) a' = Value idApp lPerm \\/\na = a')/\\ *)\n\n(forall (a':idApp)(lPerm:list Perm),\nmap_apply idApp_eq (perms (state s)) a' = Value idApp lPerm ->\nexists lPerm':list Perm, map_apply idApp_eq (perms (state s')) a' = Value idApp lPerm' /\\\nforall p':Perm, In p' lPerm -> ~In p' lPerm' -> a=a') /\\\n\nmap_apply idApp_eq (perms (state s')) a = Value idApp nil /\\\nmap_correct (perms (state s')).\n\n(* Revocar los permisos otorgados a la aplicación *)\nDefinition revokeGrantedPermGroups (a:idApp) (s s': System) : Prop :=\n\n(forall (a':idApp)(lGrp':list idGrp),\nmap_apply idApp_eq (grantedPermGroups (state s')) a' = Value idApp lGrp' ->\nexists lGrp:list idGrp, map_apply idApp_eq (grantedPermGroups (state s)) a' = Value idApp lGrp /\\\nforall g':idGrp, In g' lGrp' -> In g' lGrp) /\\\n\n(forall (a':idApp)(lGrp:list idGrp),\nmap_apply idApp_eq (grantedPermGroups (state s)) a' = Value idApp lGrp ->\nexists lGrp':list idGrp, map_apply idApp_eq (grantedPermGroups (state s')) a' = Value idApp lGrp' /\\\nforall g':idGrp, In g' lGrp -> ~In g' lGrp' -> a=a') /\\\n\nmap_apply idApp_eq (grantedPermGroups (state s')) a = Value idApp nil /\\\nmap_correct (grantedPermGroups (state s')).\n\nDefinition markAsVerified (a: idApp) (s s': System): Prop :=\n(* Mantenemos la información sobre las aplicaciones que no son a *)\n(forall a':idApp,\n    In a' (alreadyVerified (state s)) ->\n        In a' (alreadyVerified (state s'))) /\\\n(* Todas las aplicaciones que ahora están marcadas como ejecutadas lo estaban desde antes \n   o es la aplicación en cuestión*)\n(forall a':idApp,\n    In a' (alreadyVerified (state s')) ->\n        In a' (alreadyVerified (state s)) \\/ (a' = a)) /\\\n(* La aplicación 'a' ahora quedó marcada como ya ejecutada *)\nIn a (alreadyVerified (state s')).\n\n\nDefinition post_verifyOldApp (a: idApp) (s s': System) :=\n(**\n * Removemos todos los permisos que hayan sido otorgados a esta aplicación,\n * porque fueron otorgados en tiempo de instalación. Representamos la idea\n * del popup que le sale al usuario para verificar los permisos con una\n * traza de 'grant's sucesivos.\n *)\n revokeGrantedPerms a s s' /\\\n revokeGrantedPermGroups a s s' /\\\n(**\n * Marcamos a la aplicación como que ya fue ejecutada alguna vez\n *)\nmarkAsVerified a s s' /\\\n(* Nada más cambia  *)\n(environment s = environment s') /\\\n(apps (state s) = apps (state s')) /\\\n(running (state s) = running (state s')) /\\\n(delPPerms (state s) = delPPerms (state s')) /\\\n(delTPerms (state s) = delTPerms (state s')) /\\\n(resCont (state s) = resCont (state s')) /\\\n(sentIntents (state s) = sentIntents (state s')).\n\nEnd SemVerifyOldApp.\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/Semantica.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.27560562485124773}}
{"text": "Require Import Verse.\nRequire Import Syntax.\nRequire Import Language.\nRequire Import Types.\nRequire Import Types.Internal.\nRequire Import Arch.\nRequire Import Compile.\nRequire Import Word.\nRequire Import Error.\nRequire Import PrettyPrint.\nRequire Import DecFacts.\nRequire Import Language.Ast.\n\n(* Require Import SeqFunction. *)\n\nRequire Basics.\nRequire Import Equality.\nRequire Import ListDec.\nRequire Import Omega.\nRequire Import List.\nRequire Import String.\nRequire Import Ensembles.\nRequire Vector.\nRequire Import Bool.\nSet Implicit Arguments.\n\nImport VectorNotations.\nImport ListNotations.\n\nInductive xRegName := reg_a | reg_b | reg_c | reg_d | reg_di | reg_si\n                      | reg_r8 | reg_r9 | reg_r10 | reg_r11 | reg_r12 | reg_r13 | reg_r14 | reg_r15.\n(*                      | reg_r (n : Fin.t 8) : xRegName.*)\n\nHint Resolve Fin.eq_dec : decidable_prop.\nLemma xRegName_eq_dec : DecFacts.eq_dec xRegName.\n  destruct A1; destruct A2; crush_eq_dec.\nDefined.\n\nHint Resolve xRegName_eq_dec : decidable_prop.\n\nInductive xreg : VariableT :=\n| xr (_ : xRegName) (k : kind) (ty : type k)  : xreg ty\n(*| xrH (_ : xRegName) : xreg Word8*)\n.\n\n(**** Consider moving xrL out too *)\n\nDefinition xreg_eqb {k} (ty : type k) (x1 x2 : xreg ty) : bool :=\n  match x1, x2 with\n  | xr n1 _, xr n2 _ => if xRegName_eq_dec n1 n2 then true else false\n(*  | xrH r1, xrH r2     => if xRegName_eq_dec r1 r2 then true else false\n  | _, _               => false*)\n  end.\n\nLemma xreg_eqb_eq{k} (ty : type k) (x1 x2 : xreg ty) : xreg_eqb x1 x2 = true <-> x1 = x2.\n  Hint Unfold xreg_eqb.\n  dependent destruction x1; dependent destruction x2.\n  crush_eq_dec;\n  crush_eqb_eq.\nQed.\n\nTactic Notation \"fill_ineq\" uconstr(B) := (refine B; omega).\n\nNotation al := (xr reg_a Word8).\nNotation ax := (xr reg_a Word16).\nNotation eax := (xr reg_a Word32).\nNotation rax := (xr reg_a Word64).\n\nNotation dl := (xr reg_d Word8).\nNotation dx := (xr reg_d Word16).\nNotation edx := (xr reg_d Word32).\nNotation rdx := (xr reg_d Word64).\n\nInductive xvar : VariableT :=\n| inRegister     : forall k (ty : type k), xreg ty -> xvar ty\n| paramStack     : forall k (ty : type k), nat -> xvar ty\n| localStack     : forall k (ty : type k), nat -> xvar ty\n.\n\nRecord xFrame := { xFunctionName : string;\n                   numParams      : nat;\n                   usedReg       : list xRegName;\n                   stackOffset   : nat }.\n\nModule X86 <: ARCH.\n\n  (** Name of the architecture family *)\n\n  Definition name : string := \"X86-64\".\n\n  Definition machineType := MachineType.\n\n  Instance machineTypeDenote : typeC (fun k : kind => machineType k + {Internal.UnsupportedType}) :=\n    {| mkWord      := wordToMachineWord 3;\n       mkMultiword := fun m n  => error (unsupported (multiword m n));\n       mkArray     := fun n _ t => {- byteAddress -}\n    |}.\n\n  (** The registers for this architecture *)\n\n  Definition register := xreg.\n\n  Definition machineVar := xvar.\n\n  Definition HostEndian := littleE.\n\n  Definition Word := Word64.\n\n  Definition embedRegister := inRegister.\n\n  Inductive typesSupported : forall k, Ensemble (type k) :=\n  | uint8             : typesSupported Word8\n  | uint16            : typesSupported Word16\n  | uint32            : typesSupported Word32\n  | uint64            : typesSupported Word64\n  | xarray {n e ty} : typesSupported ty -> typesSupported (array n e ty)\n  .\n\n  Fixpoint typeCheck {k}(ty : type k) : {typesSupported ty} + {~ typesSupported ty}.\n    refine (match ty with\n            | word 0 | word 1 | word 2 | word 3  => left _\n            | array n e typ => match @typeCheck direct typ with\n                               | left proof      => left (xarray proof)\n                               | right disproof  => right _\n                               end\n            | _ => right _\n            end\n           ); repeat constructor; inversion 1; apply disproof; trivial.\n  Defined.\n\n  Definition supportedType := typesSupported.\n\n  Definition isConst {k} {ty : type k} {aK} (a : arg machineVar aK ty) :=\n    match a with\n    | Ast.const _ => true\n    | _       => false\n    end.\n\n  Definition isMem {ty : type direct} {aK} (a : arg machineVar aK ty) :=\n    match a with\n    | Ast.index _ _ => true\n    | _           => false\n    end.\n\n  Let simple_binop  : list (simop binary) :=\n    [plus; minus; bitOr; bitAnd; bitXor].\n\n  Definition isRegister {k} {ty : type k} (r : xreg ty) :\n    forall {k'} {ty' : type k'} {aK} (a : arg xvar aK ty'), bool.\n    intros.\n    destruct (kind_eq_dec k k'); [subst; destruct (ty_eq_dec ty ty'); [subst | ..] | ..].\n    destruct a. destruct x. exact (xreg_eqb x r).\n    all: exact false.\n  Defined.\n\n  Inductive isRegName (r : xRegName) :\n    forall {k} {ty : type k} {aK}, arg xvar aK ty -> Prop :=\n  | isRName : forall {k} (ty : type k) {aK}, isRegName r (@var _ aK _ _ (inRegister (xr r ty))).\n\n  Lemma isRegName_dec rn {k} {ty : type k} {aK} (a : arg xvar aK ty) : decidable (isRegName rn a).\n    destruct a as [ ? ? ? v | | ]; [ destruct v as [ ? ? r | | ] | .. ]; [ destruct r | ..];\n    crush_eq_dec.\n  Qed.\n\n  Hint Resolve isRegName_dec : decidable_prop.\n\n  Notation IsRegister reg arg := (isRegister reg arg = true).\n\n  Definition onStack {k} {ty : type k} {aK} (a : arg machineVar aK ty) :=\n    match a with\n    | var (localStack _ _) | var (paramStack _ _) => true\n    | _                  => false\n    end.\n\n  Definition supportedInst (i : instruction machineVar) :=\n    match i with\n    | assign (@update2 _ ty o a1 a2) =>  (List.In o simple_binop)\n                                         /\\ (ty = Word64 -> isConst a2 = false)       (* immediates not 64-bit *)\n                                         /\\ (isMem a1 = true -> isMem a2 = false)     (* both arguments cannot be memory *)\n    | assign (@update1 _ ty o a)     => True\n    | assign (@extassign3 _ ty exmul a1 a2 a3 a4) => (ty = Word64 -> isConst a4 = false)             (* immediates not 64-bit *)\n(*                                                     /\\ (ty = Word8 -> IsRegister ah a1 ->\n                                                         IsRegister al a2 -> IsRegister al a3)       (* AH:AL <- AL * r/m 8 *)*)\n                                                     /\\ (ty <> Word8 -> isRegName reg_d a1 ->\n                                                         isRegName reg_a a2 -> isRegName reg_a a3)   (* D:A   <- A  * r/m 16/32/64 *)\n    | assign (@extassign4 _ ty eucl a1 a2 a3 a4 a5) => (ty = Word64 -> isConst a5 = false)           (* immediates not 64-bit *)\n(*                                                       /\\ (ty = Word8 -> IsRegister ah a1  -> IsRegister al a2\n                                                           -> IsRegister ah a3 -> IsRegister al a4)  (* (AH,AL) <- AH:AL / r/m 8 *) *)\n                                                       /\\ (ty <> Word8 -> isRegName reg_d a1 -> isRegName reg_a a2 ->\n                                                           isRegName reg_d a3 -> isRegName reg_a a4) (* (D,A)   <- D:A   / r/m 16/32/64 *)\n    | assign (@assign2 _ ty nop a1 a2) => (ty = Word64 -> isConst a2 = true -> isMem a1 = false)\n                                          /\\ (isConst a2 = true -> isMem a1 = true -> isEndian bigE a1 = false)\n                                          /\\ (isEndian bigE a1 = true -> isMem a2 = false -> (ty = Word32 \\/ ty = Word64) /\\ onStack a2 = false)\n                                          /\\ (isEndian bigE a1 = true -> isMem a2 = true -> isEndian bigE a2 = true)\n                                          /\\ (isEndian bigE a2 = true -> isMem a1 = true -> isEndian bigE a1 = true)\n    | @moveTo _  _ _ ty a i v => (@isEndian xvar lval _ _ bigE (Ast.index a i) = true ->\n                                   (ty = Word32 \\/ ty = Word64) -> @onStack _ _ rval (var v) = false)\n    | CLOBBER v => @onStack _ _ rval (var v) = false\n    | _ => False\n    end.\n\n  Definition instCheck i : decidable (supportedInst i).\n    destruct i as [ a | x i | v ]; [ destruct a | .. ];\n      simpl; (try destruct o); try solve_decidable.\n  Defined.\n\n  Definition functionDescription := xFrame.\n\nEnd X86.\n\nModule XFrame <: FRAME X86.\n\n  Definition frameState := xFrame.\n\n  Definition emptyFrame s :=\n    {| xFunctionName := s;\n       numParams     := 0;\n       usedReg       := List.nil;\n       stackOffset   := 0\n    |}.\n\n  Definition iterateFrame (s : string) (ty : type memory) :=\n    let state := {| xFunctionName := s;\n                    numParams     := 2;\n                    usedReg       := [reg_di; reg_si];\n                    stackOffset   := 0\n                 |} in\n    _ <- when X86.typeCheck ty; {- (inRegister (xr reg_di ty), inRegister (xr reg_si X86.Word), state) -}.\n\n  Definition CCregs : Vector.t xRegName 6 := [reg_di; reg_si; reg_d; reg_c; reg_r8; reg_r9].\n\n  Let newParam state k (ty : type k) :=\n    match lt_dec (numParams state) 6 with\n    | left plt => let r := nth_order CCregs plt in\n                  (inRegister (xr r ty),\n                   {| xFunctionName := xFunctionName state;\n                      numParams     := numParams state + 1;\n                      usedReg       := r :: usedReg state;\n                      stackOffset   := stackOffset state\n                   |})\n    | right _  => let ofst := 8 * (numParams state + 1 - 6 + 1) in\n                  (paramStack ty ofst,\n                   {| xFunctionName := xFunctionName state;\n                      numParams     := numParams state + 1;\n                      usedReg       := usedReg state;\n                      stackOffset   := stackOffset state\n                   |})\n    end.\n\n  Let newLocal state ty :=\n    let ofst := stackOffset state + @sizeOf direct ty in\n    (localStack ty ofst,\n    {| xFunctionName := xFunctionName state;\n       numParams     := numParams state;\n       usedReg       := usedReg state;\n       stackOffset   := ofst\n    |}).\n\n\n  Definition addParam state k ty :=\n    _ <- when X86.typeCheck ty; {- @newParam state k ty -}.\n\n  Definition stackAlloc state ty :=\n    _ <- when X86.typeCheck ty; {- @newLocal state ty -}.\n\n  Definition useRegister state (ty : type direct) (reg : xreg ty ):=\n    match reg with\n    | xr r ty =>\n      if X86.typeCheck ty then\n        if in_dec xRegName_eq_dec r (usedReg state)\n        then None\n        else Some\n               {| xFunctionName := xFunctionName state;\n                  numParams     := numParams state;\n                  usedReg       := r :: usedReg state;\n                  stackOffset   := stackOffset state\n               |}\n      else\n        None\n    end.\n\n  Definition description := @id xFrame.\n\nEnd XFrame.\n\nDefinition orig_reg := [reg_a; reg_b; reg_c; reg_d]%list.\nDefinition index_reg := [reg_di; reg_si]%list.\nDefinition new_reg := [reg_r8; reg_r9; reg_r10; reg_r11; reg_r12; reg_r13; reg_r14; reg_r15]%list.\n\nLocal Definition regName (r : xRegName) :=\n  match r with\n  | reg_a => text \"a\"\n  | reg_b => text \"b\"\n  | reg_c => text \"c\"\n  | reg_d => text \"d\"\n  | reg_di => text \"di\"\n  | reg_si => text \"si\"\n  | reg_r8 => text \"r8\"\n  | reg_r9 => text \"r9\"\n  | reg_r10 => text \"r10\"\n  | reg_r11 => text \"r11\"\n  | reg_r12 => text \"r12\"\n  | reg_r13 => text \"r13\"\n  | reg_r14 => text \"r14\"\n  | reg_r15 => text \"r15\"\n  end.\n\nLocal Definition origRegWrite k (ty : type k) d := match ty with\n                                                   | Word8 => d <> text \"l\"\n                                                   | Word16 => d <> text \"x\"\n                                                   | Word32 => text \"e\" <> d <> text \"x\"\n                                                   | Word64\n                                                   | _      => text \"r\" <> d <> text \"x\"\n                                                   end.\n\nLocal Definition indexRegWrite k (ty : type k) d := match ty with\n                                                    | Word8 => d <> text \"l\"\n                                                    | Word16 => d\n                                                    | Word32 => text \"e\" <> d\n                                                    | Word64\n                                                    | _      => text \"r\" <> d\n                                                    end.\n\nLocal Definition newRegWrite k (ty : type k) d := match ty with\n                                                  | Word8 => d <> text \"b\"\n                                                  | Word16 => d <> text \"w\"\n                                                  | Word32 => d <> text \"d\"\n                                                  | Word64\n                                                  | _      => d\n                                                  end.\n\n\nInstance xRegPretty : forall k (ty : type k), PrettyPrint (xreg ty)\n  := { doc := fun x => text \"%\" <> let 'xr r ty := x in\n                                   let rd := regName r in\n                                   if in_dec xRegName_eq_dec r orig_reg\n                                   then origRegWrite ty rd\n                                   else if in_dec xRegName_eq_dec r index_reg\n                                        then indexRegWrite ty rd\n                                        else newRegWrite ty rd\n     }.\n\nInstance xMachineVar : forall k (ty : type k), PrettyPrint (xvar ty)\n  := { doc := fun x => match x with\n                       | inRegister r           => doc r\n                       | paramStack ty n        => decimal n <> paren (text \"%ebp\")\n                       | localStack ty n        => text \"-\" <> decimal n <> paren (text \"%ebp\")\n                       end\n     }.\n\nLocal Definition xImm d := text \"$\" <> d.\n\nLocal Fixpoint xArgdoc {aK}{k}(ty : type k ) (av : arg xvar aK ty) :=\n  match av with\n  | var v       => doc v\n  | Ast.const c     => xImm (doc c)\n  | Ast.index v (exist _ n _) => decimal (sizeOf ty * n) <> paren (doc v)\n  end.\n\nInstance arg_pretty_print : forall aK k (ty : type k), PrettyPrint (arg xvar aK ty)\n  := { doc := @xArgdoc _ _ ty }.\n\n\nLocal Definition iSuffix {k} (ty : type k) := match ty with\n                                               | Word8 => text \"b\"\n                                               | Word16 => text \"w\"\n                                               | Word32 => text \"l\"\n                                               | Word64 => text \"q\"\n                                               | array _ _ _ => text \"q\"\n                                               | _      => text \"badType\"\n                                               end.\n\nLocal Definition xOp {la ra} (o : op la ra) {k} (ty : type k) := match o with\n                                               | plus    => text \"add\"\n                                               | minus   => text \"sub\"\n                                               | mul     => text \"imul\"\n                                               | exmul   => text \"mul\"\n                                               | quot    => text \"BadOp\"\n                                               | rem     => text \"BadOp\"\n                                               | eucl    => text \"div\"\n                                               | bitOr   => text \"or\"\n                                               | bitAnd  => text \"and\"\n                                               | bitXor  => text \"xor\"\n                                               | bitComp => text \"not\"\n                                               | rotL n  => text \"rol\"\n                                               | rotR n  => text \"ror\"\n                                               | shiftL n => text \"shl\"\n                                               | shiftR n => text \"shr\"\n                                               | nop     => text \"mov\"\n                                                  end <> iSuffix ty.\n\nLocal Definition biargs d1 d2 := commaSep [d1; d2].\n\nLocal Definition mkInst i a := i <_> a.\n\nLocal Definition bswap {k} (ty : type k) (x : xreg ty) :=\n  mkInst (text \"bswap\" <> iSuffix ty) (doc x).\n\nLocal Definition move {ty : type direct} (la : larg _ ty) (ra : rarg _ ty) :=\n  let NOP := xOp nop ty in\n  match la with\n  | @Ast.index _  _ _ bigE _ _ _ => match ra, ty with\n                                      | var (inRegister x), Word32\n                                      | var (inRegister x), Word64 => vcat [ bswap x;\n                                                                               mkInst NOP (biargs (doc ra) (doc la)) ]\n                                      | @Ast.index _  _ _ bigE _ _ _, _ => mkInst NOP (biargs (doc ra) (doc la))\n                                      | _, _ => text \"badInst\"\n                                      end\n  | var (inRegister x) => match ra, ty with\n                          | @Ast.index _  _ _ bigE _ _ _, Word32\n                          | @Ast.index _  _ _ bigE _ _ _, Word64 => vcat [ mkInst NOP (biargs (doc ra) (doc la));\n                                                                             bswap x ]\n                          | _, _ => mkInst NOP (biargs (doc ra) (doc la))\n                          end\n  | _                  => mkInst NOP (biargs (doc ra) (doc la))\n  end.\n\nLocal Definition store {ty : type direct} (la : larg _ ty) (ra : rarg _ ty) :=\n  vcat ([ move la ra ] ++\n                       match ra with\n                       | var (inRegister x) => match la with\n                                               | @Ast.index _  _ _ bigE _ _ _ => [bswap x]\n                                               | _ => List.nil\n                                               end\n                       | _ => List.nil\n                       end).\n\nInstance xAssignmentPrint : PrettyPrint (assignment xvar)\n  := { doc := fun assgn => match assgn with\n                           | @update2 _ ty op la ra => xOp op ty <_> biargs (doc ra) (doc la)\n                           | @update1 _ ty op la    => xOp op ty <_> match op with\n                                                                  | bitComp => doc la\n                                                                  | rotL n\n                                                                  | rotR n\n                                                                  | shiftL n\n                                                                  | shiftR n => biargs (xImm (decimal n)) (doc la)\n                                                                  | nop => biargs (doc la) (doc la)\n                                                                     end\n                           | @assign2 _ ty nop la ra => move la ra\n                           | _ => text \"badInst\"\n                           end\n     }.\n\n\nGlobal Instance instruction_C_print : PrettyPrint (instruction xvar)\n  := { doc := fun i => match i with\n                       | assign a => doc a\n                       | moveTo x i y => move (Ast.index x i) (var y)\n                       | CLOBBER a     => empty\n                       end\n     }.\n\nModule xCodeGen <: CODEGEN X86.\n\n  Import X86.\n\n  Definition emit (i : instruction xvar) : Doc + { not (supportedInst i) } :=\n    _ <- when instCheck i; {- doc i -}.\n\n  Definition sequenceInstructions ds := line <> vcat ds <> line.\n\n  Let preamble n := [  text \".text\";\n                       text \".globl\" <_> n;\n                       text \".type\" <_> n <> text \", @function\";\n                       empty;\n                       n <> text \":\" ]%list.\n\n  Let BP := text \"%rbp\".\n  Let SP := text \"%rsp\".\n  Let push r := mkInst (text \"push\" <> iSuffix Word) r.\n  Let pop r  := mkInst (text \"pop\" <> iSuffix Word) r.\n\n  Let setupBP := [ push BP;\n                   mkInst (xOp nop Word) (biargs SP BP) ]%list.\n\n  Let allocStack n := if nat_eq_dec n 0 then List.nil else [mkInst (xOp minus Word) (biargs (xImm (decimal n)) SP)]%list.\n  Let preserveRegs l := map (fun n => push (doc (xr n Word))) l.\n  Let restoreRegs l := map (fun n => pop (doc (xr n Word))) l.\n  Let clearStack n := if nat_eq_dec n 0 then List.nil else [mkInst (xOp plus Word) (biargs (xImm (decimal n)) SP)]%list.\n\n  Let restoreBP := [mkInst (text \"popq\") BP]%list.\n\n  Let ret := [text \"ret\"]%list.\n\n  Let calleeSave := [reg_b; reg_r12; reg_r13; reg_r14; reg_r15]%list.\n  Let toSave l := filter (fun r => if in_dec xRegName_eq_dec r calleeSave then true else false) l.\n  Let xComment s := text \"#\" <_> text s.\n\n  Definition makeFunction state body := let ofst := stackOffset state in\n                                        let name := text (xFunctionName state) in\n                                        let regs :=  toSave (usedReg state) in\n                                        vcat ((preamble name) ++\n                                                              [nest 4 (vcat ([empty; xComment \"Stack setup\"] ++\n                                                                             setupBP ++ allocStack ofst ++\n                                                                             [xComment \"Callee saved registers\"] ++\n                                                                             preserveRegs regs ++\n                                                                             [body;\n                                                                              xComment \"Stack cleanup\"] ++\n                                                                             clearStack ofst ++\n                                                                             [xComment \"Restore registers\"] ++\n                                                                             restoreRegs regs ++ restoreBP ++\n                                                                             ret))]).\n\n  Definition loopWrapper (msgTy : type memory) (v : machineVar msgTy) (n : machineVar Word) (d : Doc) : Doc :=\n    let label := text \".loopstart\" in\n    let iterate := [ doc (mkInst (xOp plus Word) (biargs (xImm (decimal (sizeOf msgTy))) (doc v)));\n                     mkInst (text \"dec\" <> iSuffix Word) (doc n);\n                     mkInst (text \"jnz\") label ]%list in\n    vcat ([label <> text \":\"] ++ [nest 4 d] ++ iterate).\n\nEnd xCodeGen.\n\nModule Compile := Compiler X86 XFrame xCodeGen.", "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/src/Verse/Arch/X86_64.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.27556781436840705}}
{"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\nRequire Export DistributedReferenceCounting.machine2.machine.\nRequire Export DistributedReferenceCounting.machine2.cardinal.\nRequire Export DistributedReferenceCounting.machine2.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\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.\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/machine2/invariant1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2755678084658072}}
{"text": "Require Import HoareDef STB CannonRA Cannon0 Cannon1 SimModSem.\nRequire Import Coqlib.\nRequire Import ImpPrelude.\nRequire Import Skeleton.\nRequire Import PCM.\nRequire Import ModSem Behavior.\nRequire Import HTactics ProofMode.\nRequire Import HSim IProofMode.\n\nSet Implicit Arguments.\n\n\n\nSection SIMMODSEM.\n  Context `{Σ: GRA.t}.\n  Context `{@GRA.inG CannonRA Σ}.\n\n  Variable GlobalStb: Sk.t -> gname -> option fspec.\n\n  (* Kripke world *)\n  Let W: Type := unit.\n\n  (* world future relation *)\n  Let le: W -> W -> Prop := top2.\n\n  Let le_PreOrder: @PreOrder unit le.\n  Proof. unfold le. econs; eauto. Qed.\n  Local Existing Instance le_PreOrder.\n\n  (* state relation *)\n  Let wf: W -> Any.t -> Any.t -> iProp :=\n        fun _ st_src st_tgt => ((⌜st_src = (1: Z)↑ /\\ st_tgt = (1: Z)↑⌝ ** OwnM (Ready))\n                                ∨ OwnM (Fired))%I\n  .\n\n  Theorem correct: refines2 [Cannon0.Cannon] [Cannon1.Cannon GlobalStb].\n  Proof.\n    (* proof using local simulation *)\n    eapply adequacy_local2. econs; ss. i. red.\n    econstructor 1 with (le:=le) (wf:=mk_wf wf); et; ss; cycle 1.\n\n    (* initial state *)\n    { exists tt. econs. eapply to_semantic.\n      iIntros \"H\". iLeft. iSplitR; ss. }\n\n    (* function \"fire\" *)\n    econs; ss. econs; ss. red.\n    (* use IPM *)\n    apply isim_fun_to_tgt; auto. i; ss.\n    (* state relation * precondition ⊢ isim (state relation* postcondition) p_src p_tgt *)\n    unfold Cannon0.fire_body, Cannon1.fire_body.\n    iIntros \"[INV PRE]\".\n    iDestruct \"PRE\" as \"[[% BALL] %]\". subst.\n    iEval (unfold inv_with, wf) in \"INV\".\n    iDestruct \"INV\" as (w1) \"[[[% READY] | FIRED] _]\".\n    { des; subst. hred_l. hred_r.\n      iApply isim_pget_tgt. hred_r.\n      iApply isim_syscall. iIntros (_).\n      hred_l. hred_r.\n      iApply isim_pput_tgt. hred_r.\n      iApply isim_ret. iSplit.\n      { iApply inv_with_current. iEval (unfold wf).\n        iRight. iCombine \"READY\" \"BALL\" as \"FIRED\".\n        iEval (rewrite <- ReadyBall). iApply \"FIRED\".\n      }\n      { iPureIntro. auto. }\n    }\n    { iCombine \"FIRED\" \"BALL\" as \"FALSE\".\n      iPoseProof (OwnM_valid with \"FALSE\") as \"%\".\n      exfalso. eapply FiredBall; auto.\n    }\n  Qed.\n\n  (* isim *)\n  (*   (* state relation *) *)\n  (*   le (* world future *) wf (* state relation *) w (* current world *) *)\n  (*   (* conditions for functions *) *)\n  (*   mn (* current module name *) conds (* conditions *) o (* maximal call depth (for termination) *) *)\n  (*   (* for coinduction *) *)\n  (*   (r, g, f_src, f_tgt) *)\n  (*   (* post condition : state_src -> state_tgt -> R_src -> R_tgt -> iProp *) *)\n  (*   Q *)\n  (*   (* source program : state_src * itree E R_src *) *)\n  (*   (st_src, prog_src) *)\n  (*   (* target program : state_tgt * itree E R_tgt*) *)\n  (*   (st_tgt, prog_tgt) *)\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/cannon/Cannon01proofH.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.709019146082187, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.2755376214471255}}
{"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.3                                 *)\n(*                               January 1998                               *)\n(*                                                                          *)\n(****************************************************************************)\n(*                                 Logics.v                                 *)\n(****************************************************************************)\n\n(* Some properties about relations on objects in Type *)\n\n  Inductive ACC (A : Type) (R : A -> A -> Prop) : A -> Prop :=\n      ACC_intro :\n        forall x : A, (forall y : A, R y x -> ACC A R y) -> ACC A R x.\n\n  Lemma ACC_nonreflexive :\n   forall (A : Type) (R : A -> A -> Prop) (x : A),\n   ACC A R x -> R x x -> False.\nsimple induction 1; intros.\nexact (H1 x0 H2 H2).\nQed.\n\n  Definition WF (A : Type) (R : A -> A -> Prop) := forall x : A, ACC A R x.\n\n\nSection Inverse_Image.\n\n  Variables (A B : Type) (R : B -> B -> Prop) (f : A -> B).\n\n  Definition Rof (x y : A) : Prop := R (f x) (f y).\n\n  Remark ACC_lemma :\n   forall y : B, ACC B R y -> forall x : A, y = f x -> ACC A Rof x.\n    simple induction 1; intros.\n    constructor; intros.\n    apply (H1 (f y0)); trivial.\n    elim H2 using eq_ind_r; trivial.\n    Qed.\n\n  Lemma ACC_inverse_image : forall x : A, ACC B R (f x) -> ACC A Rof x.\n    intros; apply (ACC_lemma (f x)); trivial.\n    Qed.\n\n  Lemma WF_inverse_image : WF B R -> WF A Rof.\n    red in |- *; intros; apply ACC_inverse_image; auto.\n    Qed.\n\nEnd Inverse_Image.", "meta": {"author": "coq-contribs", "repo": "paradoxes", "sha": "69909bc36842fb228c4ce1206be179ccfeab1e78", "save_path": "github-repos/coq/coq-contribs-paradoxes", "path": "github-repos/coq/coq-contribs-paradoxes/paradoxes-69909bc36842fb228c4ce1206be179ccfeab1e78/Logics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.27553163361917044}}
{"text": "From Vellvm Require Import LLVMAst CFG DynamicTypes.\nRequire Import List ZArith.\nImport ListNotations.\n\nFrom Coq Require Import List String Ascii ZArith.\nOpen Scope string_scope.\n\n\n\n(* InstSimplify's undef.ll tests *)\nDefinition undef_test0_block : block dtyp :=\n  {|\n    blk_id := (Anon 0%Z);\n    blk_phis := [];\n    blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (Mul false false) (DTYPE_I 64%Z) EXP_Undef EXP_Undef)))];\n    blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n    blk_comments := None\n  |}.\n\nDefinition undef_test0_block_refine : block dtyp :=\n  {|\n    blk_id := (Anon 0%Z);\n    blk_phis := [];\n    blk_code := [];\n    blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 64%Z), (EXP_Undef)));\n    blk_comments := None\n  |}.\n\nDefinition undef_test1_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (Mul false false) (DTYPE_I 64%Z) (EXP_Integer 3%Z) EXP_Undef)))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test1_block_refine := undef_test0_block_refine.\n\nDefinition undef_test2_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (Mul false false) (DTYPE_I 64%Z) EXP_Undef (EXP_Integer 3%Z))))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test2_block_refine := undef_test0_block_refine.\n\nDefinition undef_test3_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (Mul false false) (DTYPE_I 64%Z) EXP_Undef (EXP_Integer 6%Z))))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test3_block_refine : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 64%Z), (EXP_Integer 0%Z)));\n      blk_comments := None\n    |}.\n\n\nDefinition undef_test4_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (Mul false false) (DTYPE_I 64%Z) (EXP_Integer 6%Z) EXP_Undef)))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test4_block_refine := undef_test3_block_refine.\n\nDefinition undef_test5_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop And (DTYPE_I 64%Z) EXP_Undef EXP_Undef)))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test5_block_refine := undef_test0_block_refine.\n\nDefinition undef_test6_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop Or (DTYPE_I 64%Z) EXP_Undef EXP_Undef)))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test6_block_refine := undef_test0_block_refine.\n\nDefinition undef_test7_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (UDiv false) (DTYPE_I 64%Z) EXP_Undef (EXP_Integer 1%Z))))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test7_block_refine := undef_test0_block_refine.\n\nDefinition undef_test8_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (SDiv false) (DTYPE_I 64%Z) EXP_Undef (EXP_Integer 1%Z))))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test8_block_refine := undef_test0_block_refine.\n\nDefinition undef_test9_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop URem (DTYPE_I 64%Z) EXP_Undef (EXP_Integer 1%Z))))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test9_block_refine := undef_test3_block_refine.\n\nDefinition undef_test10_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop SRem (DTYPE_I 64%Z) EXP_Undef (EXP_Integer 1%Z))))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test10_block_refine := undef_test3_block_refine.\n\nDefinition undef_test11_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (Shl false false) (DTYPE_I 64%Z) EXP_Undef EXP_Undef)))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test11b_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (Shl false false) (DTYPE_I 64%Z) (EXP_Ident (ID_Local (Name \"a\"))) EXP_Undef)))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test12_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (AShr false) (DTYPE_I 64%Z) EXP_Undef EXP_Undef)))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test12b_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (AShr false) (DTYPE_I 64%Z) (EXP_Ident (ID_Local (Name \"a\"))) EXP_Undef)))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test13_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (LShr false) (DTYPE_I 64%Z) EXP_Undef EXP_Undef)))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test13b_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (LShr false) (DTYPE_I 64%Z) (EXP_Ident (ID_Local (Name \"a\"))) EXP_Undef)))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test14_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_ICmp Slt (DTYPE_I 64%Z) EXP_Undef EXP_Undef)))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 1%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test15_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_ICmp Ult (DTYPE_I 64%Z) EXP_Undef EXP_Undef)))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 1%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test16_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_Select ((DTYPE_I 1%Z),EXP_Undef) ((DTYPE_I 64%Z),(EXP_Ident (ID_Local (Name \"a\")))) ((DTYPE_I 64%Z),EXP_Undef))))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test17_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_Select ((DTYPE_I 1%Z),EXP_Undef) ((DTYPE_I 64%Z),EXP_Undef) ((DTYPE_I 64%Z),(EXP_Ident (ID_Local (Name \"a\")))))))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test18_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"r\"), (INSTR_Call ((DTYPE_Pointer), @EXP_Undef dtyp) [((DTYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"a\"))))]))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test19_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (Shl false false) (DTYPE_Vector 4%Z (DTYPE_I 8%Z)) (EXP_Ident (ID_Local (Name \"a\"))) (EXP_Vector [((DTYPE_I 8%Z),(EXP_Integer 8%Z)); ((DTYPE_I 8%Z),(EXP_Integer 9%Z)); ((DTYPE_I 8%Z),EXP_Undef); ((DTYPE_I 8%Z), (EXP_Integer (-1)%Z))]))))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_Vector 4%Z (DTYPE_I 8%Z)), (EXP_Ident (ID_Local (Name \"b\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test20_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (UDiv false) (DTYPE_I 32%Z) (EXP_Ident (ID_Local (Name \"a\"))) (EXP_Integer 0%Z))))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test20vec_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (UDiv false) (DTYPE_Vector 2%Z (DTYPE_I 32%Z)) (EXP_Ident (ID_Local (Name \"a\"))) EXP_Zero_initializer)))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_Vector 2%Z (DTYPE_I 32%Z)), (EXP_Ident (ID_Local (Name \"b\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test21_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (SDiv false) (DTYPE_I 32%Z) (EXP_Ident (ID_Local (Name \"a\"))) (EXP_Integer 0%Z))))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test21vec_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (SDiv false) (DTYPE_Vector 2%Z (DTYPE_I 32%Z)) (EXP_Ident (ID_Local (Name \"a\"))) EXP_Zero_initializer)))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_Vector 2%Z (DTYPE_I 32%Z)), (EXP_Ident (ID_Local (Name \"b\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test22_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (AShr true) (DTYPE_I 32%Z) EXP_Undef (EXP_Ident (ID_Local (Name \"a\"))))))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test23_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (LShr true) (DTYPE_I 32%Z) EXP_Undef (EXP_Ident (ID_Local (Name \"a\"))))))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test24_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (UDiv false) (DTYPE_I 32%Z) EXP_Undef (EXP_Integer 0%Z))))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test25_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (LShr false) (DTYPE_I 32%Z) (EXP_Integer 0%Z) EXP_Undef)))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test26_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (AShr false) (DTYPE_I 32%Z) (EXP_Integer 0%Z) EXP_Undef)))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test27_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (Shl false false) (DTYPE_I 32%Z) (EXP_Integer 0%Z) EXP_Undef)))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test28_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (Shl false true) (DTYPE_I 32%Z) EXP_Undef (EXP_Ident (ID_Local (Name \"a\"))))))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test29_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (Shl true false) (DTYPE_I 32%Z) EXP_Undef (EXP_Ident (ID_Local (Name \"a\"))))))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test30_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (Shl true true) (DTYPE_I 32%Z) EXP_Undef (EXP_Ident (ID_Local (Name \"a\"))))))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test31_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (Shl false false) (DTYPE_I 32%Z) EXP_Undef (EXP_Ident (ID_Local (Name \"a\"))))))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test32_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (Shl false false) (DTYPE_I 32%Z) EXP_Undef (EXP_Integer 0%Z))))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test33_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (AShr false) (DTYPE_I 32%Z) EXP_Undef (EXP_Integer 0%Z))))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test34_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (LShr false) (DTYPE_I 32%Z) EXP_Undef (EXP_Integer 0%Z))))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test35_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_ExtractElement ((DTYPE_Vector 4%Z (DTYPE_I 32%Z)),(EXP_Ident (ID_Local (Name \"V\")))) ((DTYPE_I 32%Z),(EXP_Integer 4%Z)))))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test36_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_ExtractElement ((DTYPE_Vector 4%Z (DTYPE_I 32%Z)),EXP_Undef) ((DTYPE_I 32%Z),(EXP_Ident (ID_Local (Name \"V\")))))))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test37_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (UDiv false) (DTYPE_I 32%Z) EXP_Undef EXP_Undef)))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test38_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (UDiv false) (DTYPE_I 32%Z) (EXP_Ident (ID_Local (Name \"a\"))) EXP_Undef)))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n      blk_comments := None\n    |}.\n\nDefinition undef_test39_block : block dtyp\n  := {|\n      blk_id := (Anon 0%Z);\n      blk_phis := [];\n      blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (UDiv false) (DTYPE_I 32%Z) (EXP_Integer 0%Z) EXP_Undef)))];\n      blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n      blk_comments := None\n    |}.\n\n\n(* InstSimplify's undef.ll tests *)\nDefinition undef_test0_cfg : cfg dtyp :=\n  {| init := (Anon 0%Z);\n     blks := [{|\n                 blk_id := (Anon 0%Z);\n                 blk_phis := [];\n                 blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (Mul false false) (DTYPE_I 64%Z) EXP_Undef EXP_Undef)))];\n                 blk_term := (IVoid 0%Z, TERM_Ret ((DTYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                 blk_comments := None\n               |}];\n     args := [];\n  |}.\n\nDefinition undef_test0 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"main\");\n                            dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                            dc_param_attrs := ([], []);\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          df_args := [];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (Mul false false) (TYPE_I 64%Z) EXP_Undef EXP_Undef)))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test0_refine : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"main\");\n                            dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                            dc_param_attrs := ([], []);\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          df_args := [];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Undef)));\n                          blk_comments := None\n                        |}]\n        |}].\n\n\nDefinition undef_test1 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test1\");\n                            dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                            dc_param_attrs := ([], []);\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          df_args := [];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (Mul false false) (TYPE_I 64%Z) (EXP_Integer 3%Z) EXP_Undef)))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test2 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test2\");\n                            dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                            dc_param_attrs := ([], []);\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          df_args := [];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (Mul false false) (TYPE_I 64%Z) EXP_Undef (EXP_Integer 3%Z))))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test3 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test3\");\n                            dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                            dc_param_attrs := ([], []);\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          df_args := [];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (Mul false false) (TYPE_I 64%Z) EXP_Undef (EXP_Integer 6%Z))))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test4 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test4\");\n                            dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                            dc_param_attrs := ([], []);\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          df_args := [];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (Mul false false) (TYPE_I 64%Z) (EXP_Integer 6%Z) EXP_Undef)))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test5 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test5\");\n                            dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                            dc_param_attrs := ([], []);\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          df_args := [];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop And (TYPE_I 64%Z) EXP_Undef EXP_Undef)))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test6 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test6\");\n                            dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                            dc_param_attrs := ([], []);\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          df_args := [];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop Or (TYPE_I 64%Z) EXP_Undef EXP_Undef)))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test7 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test7\");\n                            dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                            dc_param_attrs := ([], []);\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          df_args := [];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (UDiv false) (TYPE_I 64%Z) EXP_Undef (EXP_Integer 1%Z))))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test8 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test8\");\n                            dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                            dc_param_attrs := ([], []);\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          df_args := [];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (SDiv false) (TYPE_I 64%Z) EXP_Undef (EXP_Integer 1%Z))))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test9 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test9\");\n                            dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                            dc_param_attrs := ([], []);\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          df_args := [];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop URem (TYPE_I 64%Z) EXP_Undef (EXP_Integer 1%Z))))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test10 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test10\");\n                            dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                            dc_param_attrs := ([], []);\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          df_args := [];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop SRem (TYPE_I 64%Z) EXP_Undef (EXP_Integer 1%Z))))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test11 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test11\");\n                            dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                            dc_param_attrs := ([], []);\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          df_args := [];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (Shl false false) (TYPE_I 64%Z) EXP_Undef EXP_Undef)))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test11b : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test11b\");\n                            dc_type := (TYPE_Function (TYPE_I 64%Z) [(TYPE_I 64%Z)]);\n                            dc_param_attrs := ([], []);\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          df_args := [(Name \"a\")];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (Shl false false) (TYPE_I 64%Z) (EXP_Ident (ID_Local (Name \"a\"))) EXP_Undef)))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test12 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test12\");\n                            dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                            dc_param_attrs := ([], []);\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          df_args := [];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (AShr false) (TYPE_I 64%Z) EXP_Undef EXP_Undef)))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test12b : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test12b\");\n                            dc_type := (TYPE_Function (TYPE_I 64%Z) [(TYPE_I 64%Z)]);\n                            dc_param_attrs := ([], []);\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          df_args := [(Name \"a\")];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (AShr false) (TYPE_I 64%Z) (EXP_Ident (ID_Local (Name \"a\"))) EXP_Undef)))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test13 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test13\");\n                            dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                            dc_param_attrs := ([], []);\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          df_args := [];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (LShr false) (TYPE_I 64%Z) EXP_Undef EXP_Undef)))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test13b : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test13b\");\n                            dc_type := (TYPE_Function (TYPE_I 64%Z) [(TYPE_I 64%Z)]);\n                            dc_param_attrs := ([], []);\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          df_args := [(Name \"a\")];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (LShr false) (TYPE_I 64%Z) (EXP_Ident (ID_Local (Name \"a\"))) EXP_Undef)))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test14 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test14\");\n                            dc_type := (TYPE_Function (TYPE_I 1%Z) []);\n                            dc_param_attrs := ([], []);\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          df_args := [];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_ICmp Slt (TYPE_I 64%Z) EXP_Undef EXP_Undef)))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 1%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test15 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test15\");\n                            dc_type := (TYPE_Function (TYPE_I 1%Z) []);\n                            dc_param_attrs := ([], []);\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          df_args := [];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_ICmp Ult (TYPE_I 64%Z) EXP_Undef EXP_Undef)))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 1%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test16 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test16\");\n                            dc_type := (TYPE_Function (TYPE_I 64%Z) [(TYPE_I 64%Z)]);\n                            dc_param_attrs := ([], []);\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          df_args := [(Name \"a\")];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_Select ((TYPE_I 1%Z),EXP_Undef) ((TYPE_I 64%Z),(EXP_Ident (ID_Local (Name \"a\")))) ((TYPE_I 64%Z),EXP_Undef))))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test17 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test17\");\n                            dc_type := (TYPE_Function (TYPE_I 64%Z) [(TYPE_I 64%Z)]);\n                            dc_param_attrs := ([], []);\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          df_args := [(Name \"a\")];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_Select ((TYPE_I 1%Z),EXP_Undef) ((TYPE_I 64%Z),EXP_Undef) ((TYPE_I 64%Z),(EXP_Ident (ID_Local (Name \"a\")))))))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test18 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test18\");\n                            dc_type := (TYPE_Function (TYPE_I 64%Z) [(TYPE_I 64%Z)]);\n                            dc_param_attrs := ([], []);\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          df_args := [(Name \"a\")];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"r\"), (INSTR_Call ((TYPE_Function (TYPE_I 64%Z) [(TYPE_I 64%Z)]), EXP_Undef) [((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"a\"))))]))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test19 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test19\");\n                            dc_type := (TYPE_Function (TYPE_Vector 4%Z (TYPE_I 8%Z)) [(TYPE_Vector 4%Z (TYPE_I 8%Z))]);\n                            dc_param_attrs := ([], []);\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          df_args := [(Name \"a\")];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (Shl false false) (TYPE_Vector 4%Z (TYPE_I 8%Z)) (EXP_Ident (ID_Local (Name \"a\"))) (EXP_Vector [((TYPE_I 8%Z),(EXP_Integer 8%Z)); ((TYPE_I 8%Z),(EXP_Integer 9%Z)); ((TYPE_I 8%Z),EXP_Undef); ((TYPE_I 8%Z), (EXP_Integer (-1)%Z))]))))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_Vector 4%Z (TYPE_I 8%Z)), (EXP_Ident (ID_Local (Name \"b\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test20 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test20\");\n                            dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_I 32%Z)]);\n                            dc_param_attrs := ([], []);\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          df_args := [(Name \"a\")];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (UDiv false) (TYPE_I 32%Z) (EXP_Ident (ID_Local (Name \"a\"))) (EXP_Integer 0%Z))))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test20vec : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test20vec\");\n                            dc_type := (TYPE_Function (TYPE_Vector 2%Z (TYPE_I 32%Z)) [(TYPE_Vector 2%Z (TYPE_I 32%Z))]);\n                            dc_param_attrs := ([], []);\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          df_args := [(Name \"a\")];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (UDiv false) (TYPE_Vector 2%Z (TYPE_I 32%Z)) (EXP_Ident (ID_Local (Name \"a\"))) EXP_Zero_initializer)))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_Vector 2%Z (TYPE_I 32%Z)), (EXP_Ident (ID_Local (Name \"b\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test21 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test21\");\n                            dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_I 32%Z)]);\n                            dc_param_attrs := ([], []);\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          df_args := [(Name \"a\")];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (SDiv false) (TYPE_I 32%Z) (EXP_Ident (ID_Local (Name \"a\"))) (EXP_Integer 0%Z))))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test21vec : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test21vec\");\n                            dc_type := (TYPE_Function (TYPE_Vector 2%Z (TYPE_I 32%Z)) [(TYPE_Vector 2%Z (TYPE_I 32%Z))]);\n                            dc_param_attrs := ([], []);\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          df_args := [(Name \"a\")];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (SDiv false) (TYPE_Vector 2%Z (TYPE_I 32%Z)) (EXP_Ident (ID_Local (Name \"a\"))) EXP_Zero_initializer)))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_Vector 2%Z (TYPE_I 32%Z)), (EXP_Ident (ID_Local (Name \"b\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test22 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test22\");\n                            dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_I 32%Z)]);\n                            dc_param_attrs := ([], []);\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          df_args := [(Name \"a\")];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (AShr true) (TYPE_I 32%Z) EXP_Undef (EXP_Ident (ID_Local (Name \"a\"))))))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test23 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test23\");\n                            dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_I 32%Z)]);\n                            dc_param_attrs := ([], []);\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          df_args := [(Name \"a\")];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (LShr true) (TYPE_I 32%Z) EXP_Undef (EXP_Ident (ID_Local (Name \"a\"))))))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test24 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test24\");\n                            dc_type := (TYPE_Function (TYPE_I 32%Z) []);\n                            dc_param_attrs := ([], []);\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          df_args := [];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (UDiv false) (TYPE_I 32%Z) EXP_Undef (EXP_Integer 0%Z))))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test25 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test25\");\n                            dc_type := (TYPE_Function (TYPE_I 32%Z) []);\n                            dc_param_attrs := ([], []);\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          df_args := [];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (LShr false) (TYPE_I 32%Z) (EXP_Integer 0%Z) EXP_Undef)))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test26 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test26\");\n                            dc_type := (TYPE_Function (TYPE_I 32%Z) []);\n                            dc_param_attrs := ([], []);\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          df_args := [];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (AShr false) (TYPE_I 32%Z) (EXP_Integer 0%Z) EXP_Undef)))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test27 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test27\");\n                            dc_type := (TYPE_Function (TYPE_I 32%Z) []);\n                            dc_param_attrs := ([], []);\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          df_args := [];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (Shl false false) (TYPE_I 32%Z) (EXP_Integer 0%Z) EXP_Undef)))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test28 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test28\");\n                            dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_I 32%Z)]);\n                            dc_param_attrs := ([], []);\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          df_args := [(Name \"a\")];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (Shl false true) (TYPE_I 32%Z) EXP_Undef (EXP_Ident (ID_Local (Name \"a\"))))))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test29 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test29\");\n                            dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_I 32%Z)]);\n                            dc_param_attrs := ([], []);\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          df_args := [(Name \"a\")];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (Shl true false) (TYPE_I 32%Z) EXP_Undef (EXP_Ident (ID_Local (Name \"a\"))))))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test30 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test30\");\n                            dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_I 32%Z)]);\n                            dc_param_attrs := ([], []);\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          df_args := [(Name \"a\")];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (Shl true true) (TYPE_I 32%Z) EXP_Undef (EXP_Ident (ID_Local (Name \"a\"))))))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test31 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test31\");\n                            dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_I 32%Z)]);\n                            dc_param_attrs := ([], []);\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          df_args := [(Name \"a\")];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (Shl false false) (TYPE_I 32%Z) EXP_Undef (EXP_Ident (ID_Local (Name \"a\"))))))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test32 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test32\");\n                            dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_I 32%Z)]);\n                            dc_param_attrs := ([], []);\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          df_args := [(Name \"a\")];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (Shl false false) (TYPE_I 32%Z) EXP_Undef (EXP_Integer 0%Z))))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test33 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test33\");\n                            dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_I 32%Z)]);\n                            dc_param_attrs := ([], []);\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          df_args := [(Name \"a\")];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (AShr false) (TYPE_I 32%Z) EXP_Undef (EXP_Integer 0%Z))))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test34 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test34\");\n                            dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_I 32%Z)]);\n                            dc_param_attrs := ([], []);\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          df_args := [(Name \"a\")];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (LShr false) (TYPE_I 32%Z) EXP_Undef (EXP_Integer 0%Z))))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test35 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test35\");\n                            dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_Vector 4%Z (TYPE_I 32%Z))]);\n                            dc_param_attrs := ([], []);\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          df_args := [(Name \"V\")];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_ExtractElement ((TYPE_Vector 4%Z (TYPE_I 32%Z)),(EXP_Ident (ID_Local (Name \"V\")))) ((TYPE_I 32%Z),(EXP_Integer 4%Z)))))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test36 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test36\");\n                            dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_I 32%Z)]);\n                            dc_param_attrs := ([], []);\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          df_args := [(Name \"V\")];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_ExtractElement ((TYPE_Vector 4%Z (TYPE_I 32%Z)),EXP_Undef) ((TYPE_I 32%Z),(EXP_Ident (ID_Local (Name \"V\")))))))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test37 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test37\");\n                            dc_type := (TYPE_Function (TYPE_I 32%Z) []);\n                            dc_param_attrs := ([], []);\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          df_args := [];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (UDiv false) (TYPE_I 32%Z) EXP_Undef EXP_Undef)))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test38 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test38\");\n                            dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_I 32%Z)]);\n                            dc_param_attrs := ([], []);\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          df_args := [(Name \"a\")];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (UDiv false) (TYPE_I 32%Z) (EXP_Ident (ID_Local (Name \"a\"))) EXP_Undef)))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\nDefinition undef_test39 : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n          df_prototype := {|dc_name := (Name \"test39\");\n                            dc_type := (TYPE_Function (TYPE_I 32%Z) []);\n                            dc_param_attrs := ([], []);\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          df_args := [];\n          df_instrs := [\n                        {|\n                          blk_id := (Anon 0%Z);\n                          blk_phis := [];\n                          blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (UDiv false) (TYPE_I 32%Z) (EXP_Integer 0%Z) EXP_Undef)))];\n                          blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                          blk_comments := None\n                        |}]\n        |}].\n\n(* InstSimplify's undef.ll tests *)\nDefinition undef_tests : list (toplevel_entity typ (list (block typ)))\n  := [TLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test0\");\n                    dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                    dc_param_attrs := ([], []);\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  df_args := [];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (Mul false false) (TYPE_I 64%Z) EXP_Undef EXP_Undef)))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test1\");\n                    dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                    dc_param_attrs := ([], []);\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  df_args := [];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (Mul false false) (TYPE_I 64%Z) (EXP_Integer 3%Z) EXP_Undef)))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test2\");\n                    dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                    dc_param_attrs := ([], []);\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  df_args := [];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (Mul false false) (TYPE_I 64%Z) EXP_Undef (EXP_Integer 3%Z))))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test3\");\n                    dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                    dc_param_attrs := ([], []);\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  df_args := [];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (Mul false false) (TYPE_I 64%Z) EXP_Undef (EXP_Integer 6%Z))))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test4\");\n                    dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                    dc_param_attrs := ([], []);\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  df_args := [];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (Mul false false) (TYPE_I 64%Z) (EXP_Integer 6%Z) EXP_Undef)))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test5\");\n                    dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                    dc_param_attrs := ([], []);\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  df_args := [];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop And (TYPE_I 64%Z) EXP_Undef EXP_Undef)))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test6\");\n                    dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                    dc_param_attrs := ([], []);\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  df_args := [];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop Or (TYPE_I 64%Z) EXP_Undef EXP_Undef)))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test7\");\n                    dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                    dc_param_attrs := ([], []);\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  df_args := [];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (UDiv false) (TYPE_I 64%Z) EXP_Undef (EXP_Integer 1%Z))))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test8\");\n                    dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                    dc_param_attrs := ([], []);\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  df_args := [];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (SDiv false) (TYPE_I 64%Z) EXP_Undef (EXP_Integer 1%Z))))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test9\");\n                    dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                    dc_param_attrs := ([], []);\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  df_args := [];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop URem (TYPE_I 64%Z) EXP_Undef (EXP_Integer 1%Z))))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test10\");\n                    dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                    dc_param_attrs := ([], []);\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  df_args := [];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop SRem (TYPE_I 64%Z) EXP_Undef (EXP_Integer 1%Z))))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test11\");\n                    dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                    dc_param_attrs := ([], []);\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  df_args := [];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (Shl false false) (TYPE_I 64%Z) EXP_Undef EXP_Undef)))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test11b\");\n                    dc_type := (TYPE_Function (TYPE_I 64%Z) [(TYPE_I 64%Z)]);\n                    dc_param_attrs := ([], []);\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  df_args := [(Name \"a\")];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (Shl false false) (TYPE_I 64%Z) (EXP_Ident (ID_Local (Name \"a\"))) EXP_Undef)))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test12\");\n                    dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                    dc_param_attrs := ([], []);\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  df_args := [];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (AShr false) (TYPE_I 64%Z) EXP_Undef EXP_Undef)))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test12b\");\n                    dc_type := (TYPE_Function (TYPE_I 64%Z) [(TYPE_I 64%Z)]);\n                    dc_param_attrs := ([], []);\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  df_args := [(Name \"a\")];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (AShr false) (TYPE_I 64%Z) (EXP_Ident (ID_Local (Name \"a\"))) EXP_Undef)))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test13\");\n                    dc_type := (TYPE_Function (TYPE_I 64%Z) []);\n                    dc_param_attrs := ([], []);\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  df_args := [];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (LShr false) (TYPE_I 64%Z) EXP_Undef EXP_Undef)))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test13b\");\n                    dc_type := (TYPE_Function (TYPE_I 64%Z) [(TYPE_I 64%Z)]);\n                    dc_param_attrs := ([], []);\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  df_args := [(Name \"a\")];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_IBinop (LShr false) (TYPE_I 64%Z) (EXP_Ident (ID_Local (Name \"a\"))) EXP_Undef)))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test14\");\n                    dc_type := (TYPE_Function (TYPE_I 1%Z) []);\n                    dc_param_attrs := ([], []);\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  df_args := [];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_ICmp Slt (TYPE_I 64%Z) EXP_Undef EXP_Undef)))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 1%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test15\");\n                    dc_type := (TYPE_Function (TYPE_I 1%Z) []);\n                    dc_param_attrs := ([], []);\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  df_args := [];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_ICmp Ult (TYPE_I 64%Z) EXP_Undef EXP_Undef)))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 1%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test16\");\n                    dc_type := (TYPE_Function (TYPE_I 64%Z) [(TYPE_I 64%Z)]);\n                    dc_param_attrs := ([], []);\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  df_args := [(Name \"a\")];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_Select ((TYPE_I 1%Z),EXP_Undef) ((TYPE_I 64%Z),(EXP_Ident (ID_Local (Name \"a\")))) ((TYPE_I 64%Z),EXP_Undef))))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test17\");\n                    dc_type := (TYPE_Function (TYPE_I 64%Z) [(TYPE_I 64%Z)]);\n                    dc_param_attrs := ([], []);\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  df_args := [(Name \"a\")];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"r\"), (INSTR_Op (OP_Select ((TYPE_I 1%Z),EXP_Undef) ((TYPE_I 64%Z),EXP_Undef) ((TYPE_I 64%Z),(EXP_Ident (ID_Local (Name \"a\")))))))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test18\");\n                    dc_type := (TYPE_Function (TYPE_I 64%Z) [(TYPE_I 64%Z)]);\n                    dc_param_attrs := ([], []);\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  df_args := [(Name \"a\")];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"r\"), (INSTR_Call ((TYPE_Function (TYPE_I 64%Z) [(TYPE_I 64%Z)]), EXP_Undef) [((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"a\"))))]))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 64%Z), (EXP_Ident (ID_Local (Name \"r\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test19\");\n                    dc_type := (TYPE_Function (TYPE_Vector 4%Z (TYPE_I 8%Z)) [(TYPE_Vector 4%Z (TYPE_I 8%Z))]);\n                    dc_param_attrs := ([], []);\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  df_args := [(Name \"a\")];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (Shl false false) (TYPE_Vector 4%Z (TYPE_I 8%Z)) (EXP_Ident (ID_Local (Name \"a\"))) (EXP_Vector [((TYPE_I 8%Z),(EXP_Integer 8%Z)); ((TYPE_I 8%Z),(EXP_Integer 9%Z)); ((TYPE_I 8%Z),EXP_Undef); ((TYPE_I 8%Z), (EXP_Integer (-1)%Z))]))))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_Vector 4%Z (TYPE_I 8%Z)), (EXP_Ident (ID_Local (Name \"b\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test20\");\n                    dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_I 32%Z)]);\n                    dc_param_attrs := ([], []);\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  df_args := [(Name \"a\")];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (UDiv false) (TYPE_I 32%Z) (EXP_Ident (ID_Local (Name \"a\"))) (EXP_Integer 0%Z))))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test20vec\");\n                    dc_type := (TYPE_Function (TYPE_Vector 2%Z (TYPE_I 32%Z)) [(TYPE_Vector 2%Z (TYPE_I 32%Z))]);\n                    dc_param_attrs := ([], []);\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  df_args := [(Name \"a\")];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (UDiv false) (TYPE_Vector 2%Z (TYPE_I 32%Z)) (EXP_Ident (ID_Local (Name \"a\"))) EXP_Zero_initializer)))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_Vector 2%Z (TYPE_I 32%Z)), (EXP_Ident (ID_Local (Name \"b\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test21\");\n                    dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_I 32%Z)]);\n                    dc_param_attrs := ([], []);\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  df_args := [(Name \"a\")];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (SDiv false) (TYPE_I 32%Z) (EXP_Ident (ID_Local (Name \"a\"))) (EXP_Integer 0%Z))))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test21vec\");\n                    dc_type := (TYPE_Function (TYPE_Vector 2%Z (TYPE_I 32%Z)) [(TYPE_Vector 2%Z (TYPE_I 32%Z))]);\n                    dc_param_attrs := ([], []);\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  df_args := [(Name \"a\")];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (SDiv false) (TYPE_Vector 2%Z (TYPE_I 32%Z)) (EXP_Ident (ID_Local (Name \"a\"))) EXP_Zero_initializer)))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_Vector 2%Z (TYPE_I 32%Z)), (EXP_Ident (ID_Local (Name \"b\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test22\");\n                    dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_I 32%Z)]);\n                    dc_param_attrs := ([], []);\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  df_args := [(Name \"a\")];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (AShr true) (TYPE_I 32%Z) EXP_Undef (EXP_Ident (ID_Local (Name \"a\"))))))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test23\");\n                    dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_I 32%Z)]);\n                    dc_param_attrs := ([], []);\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  df_args := [(Name \"a\")];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (LShr true) (TYPE_I 32%Z) EXP_Undef (EXP_Ident (ID_Local (Name \"a\"))))))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test24\");\n                    dc_type := (TYPE_Function (TYPE_I 32%Z) []);\n                    dc_param_attrs := ([], []);\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  df_args := [];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (UDiv false) (TYPE_I 32%Z) EXP_Undef (EXP_Integer 0%Z))))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test25\");\n                    dc_type := (TYPE_Function (TYPE_I 32%Z) []);\n                    dc_param_attrs := ([], []);\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  df_args := [];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (LShr false) (TYPE_I 32%Z) (EXP_Integer 0%Z) EXP_Undef)))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test26\");\n                    dc_type := (TYPE_Function (TYPE_I 32%Z) []);\n                    dc_param_attrs := ([], []);\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  df_args := [];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (AShr false) (TYPE_I 32%Z) (EXP_Integer 0%Z) EXP_Undef)))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test27\");\n                    dc_type := (TYPE_Function (TYPE_I 32%Z) []);\n                    dc_param_attrs := ([], []);\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  df_args := [];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (Shl false false) (TYPE_I 32%Z) (EXP_Integer 0%Z) EXP_Undef)))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test28\");\n                    dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_I 32%Z)]);\n                    dc_param_attrs := ([], []);\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  df_args := [(Name \"a\")];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (Shl false true) (TYPE_I 32%Z) EXP_Undef (EXP_Ident (ID_Local (Name \"a\"))))))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test29\");\n                    dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_I 32%Z)]);\n                    dc_param_attrs := ([], []);\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  df_args := [(Name \"a\")];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (Shl true false) (TYPE_I 32%Z) EXP_Undef (EXP_Ident (ID_Local (Name \"a\"))))))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test30\");\n                    dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_I 32%Z)]);\n                    dc_param_attrs := ([], []);\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  df_args := [(Name \"a\")];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (Shl true true) (TYPE_I 32%Z) EXP_Undef (EXP_Ident (ID_Local (Name \"a\"))))))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test31\");\n                    dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_I 32%Z)]);\n                    dc_param_attrs := ([], []);\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  df_args := [(Name \"a\")];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (Shl false false) (TYPE_I 32%Z) EXP_Undef (EXP_Ident (ID_Local (Name \"a\"))))))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test32\");\n                    dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_I 32%Z)]);\n                    dc_param_attrs := ([], []);\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  df_args := [(Name \"a\")];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (Shl false false) (TYPE_I 32%Z) EXP_Undef (EXP_Integer 0%Z))))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test33\");\n                    dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_I 32%Z)]);\n                    dc_param_attrs := ([], []);\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  df_args := [(Name \"a\")];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (AShr false) (TYPE_I 32%Z) EXP_Undef (EXP_Integer 0%Z))))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test34\");\n                    dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_I 32%Z)]);\n                    dc_param_attrs := ([], []);\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  df_args := [(Name \"a\")];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (LShr false) (TYPE_I 32%Z) EXP_Undef (EXP_Integer 0%Z))))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test35\");\n                    dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_Vector 4%Z (TYPE_I 32%Z))]);\n                    dc_param_attrs := ([], []);\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  df_args := [(Name \"V\")];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_ExtractElement ((TYPE_Vector 4%Z (TYPE_I 32%Z)),(EXP_Ident (ID_Local (Name \"V\")))) ((TYPE_I 32%Z),(EXP_Integer 4%Z)))))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test36\");\n                    dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_I 32%Z)]);\n                    dc_param_attrs := ([], []);\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  df_args := [(Name \"V\")];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_ExtractElement ((TYPE_Vector 4%Z (TYPE_I 32%Z)),EXP_Undef) ((TYPE_I 32%Z),(EXP_Ident (ID_Local (Name \"V\")))))))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test37\");\n                    dc_type := (TYPE_Function (TYPE_I 32%Z) []);\n                    dc_param_attrs := ([], []);\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  df_args := [];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (UDiv false) (TYPE_I 32%Z) EXP_Undef EXP_Undef)))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test38\");\n                    dc_type := (TYPE_Function (TYPE_I 32%Z) [(TYPE_I 32%Z)]);\n                    dc_param_attrs := ([], []);\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  df_args := [(Name \"a\")];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (UDiv false) (TYPE_I 32%Z) (EXP_Ident (ID_Local (Name \"a\"))) EXP_Undef)))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                  blk_comments := None\n                |}]\n                |}; \nTLE_Definition {|\n  df_prototype := {|dc_name := (Name \"test39\");\n                    dc_type := (TYPE_Function (TYPE_I 32%Z) []);\n                    dc_param_attrs := ([], []);\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  df_args := [];\n  df_instrs := [\n                {|\n                  blk_id := (Anon 0%Z);\n                  blk_phis := [];\n                  blk_code := [(IId (Name \"b\"), (INSTR_Op (OP_IBinop (UDiv false) (TYPE_I 32%Z) (EXP_Integer 0%Z) EXP_Undef)))];\n                  blk_term := (IVoid 0%Z, TERM_Ret ((TYPE_I 32%Z), (EXP_Ident (ID_Local (Name \"b\")))));\n                  blk_comments := None\n                |}]\n                |}].\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/Transformations/UndefTests.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.27553163361917044}}
{"text": "(* -*- mode: coq -*- *)\n(* Time-stamp: <2014/8/15 20:57:12> *)\n(*\n  monad.v \n  - mathink : Author\n *)\n\n(* SSReflect libraries *)\nRequire Import\n  Ssreflect.ssreflect\n  Ssreflect.ssrbool\n  Ssreflect.ssrfun\n  Ssreflect.eqtype\n  Ssreflect.ssrnat\n  Ssreflect.seq\n  Ssreflect.fintype.\n\n(* Mathematical Components libraries *)\n\n(* Implicity *)\nSet Implicit Arguments.\nUnset Strict Implicit.\nGeneralizable All Variables.\n\nReserved Notation \"m >>= f\" (at level 57, left associativity).\nClass eqMonad (m: eqType -> eqType) :=\n  { emb {X: eqType}: X -> m X;\n    bind {X Y: eqType}(f: X -> m Y): m X -> m Y\n    where \"m >>= f\" := (bind f m);\n\n    emb_bind {X Y: eqType}(f: X -> m Y)(x: X):\n      (emb x >>= f) == f x;\n    bind_emb {X: eqType} (mx: m X):\n      (mx >>= emb) == mx;\n    bind_assoc {X Y Z: eqType}(f: X -> m Y)(g: Y -> m Z)(mx: m X):\n      mx >>= f >>= g == mx >>= (bind g \\o f) }.\nNotation \"m >>= f\" := (bind f m) (at level 57, left associativity).\nNotation \"x <- m ; p\" := (m >>= fun x => p) (at level 65, right associativity).  \n\nProgram Instance eqMaybe: eqMonad option_eqType :=\n  { emb X x := Some x;\n    bind X Y f mx := if mx is Some x then f x else None }.\nNext Obligation.\n  case: mx => //=.\nQed.\nNext Obligation.\n  case: mx => //=.\nQed.\n\nClass eqMonad_F `(monad: eqMonad m) :=\n  { failure {X: eqType}: m X;\n    handle {X: eqType}: m X -> m X -> m X;\n\n    failure_end {X Y: eqType}(f: X -> m Y):\n      failure >>= f == failure;\n    handle_failure {X: eqType}(mx: m X):\n      handle failure mx == mx }.\n\nProgram Instance eqMaybe_F: eqMonad_F eqMaybe :=\n  { failure X := None (A:=X);\n    handle X mx1 mx2 := if mx1 is None then mx2 else mx1 }.\n\n\n", "meta": {"author": "mathink", "repo": "adlib-ssr", "sha": "1c84b7c7e17f25d1b50c6067cc7149c6fd4566d5", "save_path": "github-repos/coq/mathink-adlib-ssr", "path": "github-repos/coq/mathink-adlib-ssr/adlib-ssr-1c84b7c7e17f25d1b50c6067cc7149c6fd4566d5/monad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2755047358918898}}
{"text": "(** This file proves the basic laws of the HeapLang program logic by applying\nthe Iris lifting lemmas. *)\n\nFrom iris.proofmode Require Import tactics.\nFrom iris.bi.lib Require Import fractional.\nFrom iris.base_logic.lib Require Export gen_heap proph_map gen_inv_heap.\nFrom iris.program_logic Require Export weakestpre total_weakestpre.\nFrom iris.program_logic Require Import ectx_lifting total_ectx_lifting.\nFrom iris.heap_lang Require Export class_instances.\nFrom iris.heap_lang Require Import tactics notation.\nFrom iris.prelude Require Import options.\n\nClass heapG Σ := HeapG {\n  heapG_invG : invG Σ;\n  heapG_gen_heapG :> gen_heapG loc (option val) Σ;\n  heapG_inv_heapG :> inv_heapG loc (option val) Σ;\n  heapG_proph_mapG :> proph_mapG proph_id (val * val) Σ;\n}.\n\nGlobal Instance heapG_irisG `{!heapG Σ} : irisG heap_lang Σ := {\n  iris_invG := heapG_invG;\n  state_interp σ κs _ :=\n    (gen_heap_interp σ.(heap) ∗ proph_map_interp κs σ.(used_proph_id))%I;\n  fork_post _ := True%I;\n}.\n\n(** Since we use an [option val] instance of [gen_heap], we need to overwrite\nthe notations.  That also helps for scopes and coercions. *)\n(** FIXME: Refactor these notations using custom entries once Coq bug #13654\nhas been fixed. *)\nNotation \"l ↦{ dq } v\" := (mapsto (L:=loc) (V:=option val) l dq (Some v%V))\n  (at level 20, format \"l  ↦{ dq }  v\") : bi_scope.\nNotation \"l ↦□ v\" := (mapsto (L:=loc) (V:=option val) l DfracDiscarded (Some v%V))\n  (at level 20, format \"l  ↦□  v\") : bi_scope.\nNotation \"l ↦{# q } v\" := (mapsto (L:=loc) (V:=option val) l (DfracOwn q) (Some v%V))\n  (at level 20, format \"l  ↦{# q }  v\") : bi_scope.\nNotation \"l ↦ v\" := (mapsto (L:=loc) (V:=option val) l (DfracOwn 1) (Some v%V))\n  (at level 20, format \"l  ↦  v\") : bi_scope.\n\n(** Same for [gen_inv_heap], except that these are higher-order notations so to\nmake setoid rewriting in the predicate [I] work we need actual definitions\nhere. *)\nSection definitions.\n  Context `{!heapG Σ}.\n  Definition inv_mapsto_own (l : loc) (v : val) (I : val → Prop) : iProp Σ :=\n    inv_mapsto_own l (Some v) (from_option I False).\n  Definition inv_mapsto (l : loc) (I : val → Prop) : iProp Σ :=\n    inv_mapsto l (from_option I False).\nEnd definitions.\n\nGlobal Instance: Params (@inv_mapsto_own) 4 := {}.\nGlobal Instance: Params (@inv_mapsto) 3 := {}.\n\nNotation inv_heap_inv := (inv_heap_inv loc (option val)).\nNotation \"l '↦_' I □\" := (inv_mapsto l I%stdpp%type)\n  (at level 20, I at level 9, format \"l  '↦_' I  '□'\") : bi_scope.\nNotation \"l ↦_ I v\" := (inv_mapsto_own l v I%stdpp%type)\n  (at level 20, I at level 9, format \"l  ↦_ I  v\") : bi_scope.\n\nSection lifting.\nContext `{!heapG Σ}.\nImplicit Types P Q : iProp Σ.\nImplicit Types Φ Ψ : val → iProp Σ.\nImplicit Types efs : list expr.\nImplicit Types σ : state.\nImplicit Types v : val.\nImplicit Types l : loc.\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 x e Φ Ψ :\n  □ ( □ (∀ v, Ψ v -∗ WP (rec: f x := e)%V v @ s; E {{ Φ }}) -∗\n     ∀ v, Ψ v -∗ WP (subst' x v (subst' f (rec: f x := e) e)) @ s; E {{ Φ }}) -∗\n  ∀ v, Ψ v -∗ WP (rec: f x := e)%V v @ s; E {{ Φ }}.\nProof.\n  iIntros \"#Hrec\". iLöb as \"IH\". iIntros (v) \"HΨ\".\n  iApply lifting.wp_pure_step_later; first done.\n  iNext. iApply (\"Hrec\" with \"[] HΨ\"). iIntros \"!>\" (w) \"HΨ\".\n  iApply (\"IH\" with \"HΨ\").\nQed.\n\n(** Fork: Not using Texan triples to avoid some unnecessary [True] *)\nLemma wp_fork s E e Φ :\n  ▷ WP e @ s; ⊤ {{ _, True }} -∗ ▷ Φ (LitV LitUnit) -∗ WP Fork e @ s; E {{ Φ }}.\nProof.\n  iIntros \"He HΦ\". iApply wp_lift_atomic_head_step; [done|].\n  iIntros (σ1 κ κs n) \"Hσ !>\"; iSplit; first by eauto with head_step.\n  iIntros \"!>\" (v2 σ2 efs Hstep); inv_head_step. by iFrame.\nQed.\n\nLemma twp_fork s E e Φ :\n  WP e @ s; ⊤ [{ _, True }] -∗ Φ (LitV LitUnit) -∗ WP Fork e @ s; E [{ Φ }].\nProof.\n  iIntros \"He HΦ\". iApply twp_lift_atomic_head_step; [done|].\n  iIntros (σ1 κs n) \"Hσ !>\"; iSplit; first by eauto with head_step.\n  iIntros (κ v2 σ2 efs Hstep); inv_head_step. by iFrame.\nQed.\n\n(** Heap *)\n\n(** We need to adjust the [gen_heap] and [gen_inv_heap] lemmas because of our\nvalue type being [option val]. *)\n\nLemma mapsto_valid l dq v : l ↦{dq} v -∗ ⌜✓ dq⌝.\nProof. apply mapsto_valid. Qed.\nLemma mapsto_valid_2 l dq1 dq2 v1 v2 :\n  l ↦{dq1} v1 -∗ l ↦{dq2} v2 -∗ ⌜✓ (dq1 ⋅ dq2) ∧ v1 = v2⌝.\nProof.\n  iIntros \"H1 H2\". iDestruct (mapsto_valid_2 with \"H1 H2\") as %[? [=?]]. done.\nQed.\nLemma mapsto_agree l dq1 dq2 v1 v2 : l ↦{dq1} v1 -∗ l ↦{dq2} v2 -∗ ⌜v1 = v2⌝.\nProof. iIntros \"H1 H2\". iDestruct (mapsto_agree with \"H1 H2\") as %[=?]. done. Qed.\n\nLemma mapsto_combine l dq1 dq2 v1 v2 :\n  l ↦{dq1} v1 -∗ l ↦{dq2} v2 -∗ l ↦{dq1 ⋅ dq2} v1 ∗ ⌜v1 = v2⌝.\nProof.\n  iIntros \"Hl1 Hl2\". iDestruct (mapsto_combine with \"Hl1 Hl2\") as \"[$ Heq]\".\n  by iDestruct \"Heq\" as %[= ->].\nQed.\n\nLemma mapsto_frac_ne l1 l2 dq1 dq2 v1 v2 :\n  ¬ ✓(dq1 ⋅ dq2) → l1 ↦{dq1} v1 -∗ l2 ↦{dq2} v2 -∗ ⌜l1 ≠ l2⌝.\nProof. apply mapsto_frac_ne. Qed.\nLemma mapsto_ne l1 l2 dq2 v1 v2 : l1 ↦ v1 -∗ l2 ↦{dq2} v2 -∗ ⌜l1 ≠ l2⌝.\nProof. apply mapsto_ne. Qed.\n\nLemma mapsto_persist l dq v : l ↦{dq} v ==∗ l ↦□ v.\nProof. apply mapsto_persist. Qed.\n\nGlobal Instance inv_mapsto_own_proper l v :\n  Proper (pointwise_relation _ iff ==> (≡)) (inv_mapsto_own l v).\nProof.\n  intros I1 I2 HI. rewrite /inv_mapsto_own. f_equiv=>-[w|]; last done.\n  simpl. apply HI.\nQed.\nGlobal Instance inv_mapsto_proper l :\n  Proper (pointwise_relation _ iff ==> (≡)) (inv_mapsto l).\nProof.\n  intros I1 I2 HI. rewrite /inv_mapsto. f_equiv=>-[w|]; last done.\n  simpl. apply HI.\nQed.\n\nLemma make_inv_mapsto l v (I : val → Prop) E :\n  ↑inv_heapN ⊆ E →\n  I v →\n  inv_heap_inv -∗ l ↦ v ={E}=∗ l ↦_I v.\nProof. iIntros (??) \"#HI Hl\". iApply make_inv_mapsto; done. Qed.\nLemma inv_mapsto_own_inv l v I : l ↦_I v -∗ l ↦_I □.\nProof. apply inv_mapsto_own_inv. Qed.\n\nLemma inv_mapsto_own_acc_strong E :\n  ↑inv_heapN ⊆ E →\n  inv_heap_inv ={E, E ∖ ↑inv_heapN}=∗ ∀ l v I, l ↦_I v -∗\n    (⌜I v⌝ ∗ l ↦ v ∗ (∀ w, ⌜I w ⌝ -∗ l ↦ w ==∗\n      inv_mapsto_own l w I ∗ |={E ∖ ↑inv_heapN, E}=> True)).\nProof.\n  iIntros (?) \"#Hinv\".\n  iMod (inv_mapsto_own_acc_strong with \"Hinv\") as \"Hacc\"; first done.\n  iIntros \"!>\" (l v I) \"Hl\". iDestruct (\"Hacc\" with \"Hl\") as \"(% & Hl & Hclose)\".\n  iFrame \"%∗\". iIntros (w) \"% Hl\". iApply \"Hclose\"; done.\nQed.\n\nLemma inv_mapsto_own_acc E l v I:\n  ↑inv_heapN ⊆ E →\n  inv_heap_inv -∗ l ↦_I v ={E, E ∖ ↑inv_heapN}=∗\n    (⌜I v⌝ ∗ l ↦ v ∗ (∀ w, ⌜I w ⌝ -∗ l ↦ w ={E ∖ ↑inv_heapN, E}=∗ l ↦_I w)).\nProof.\n  iIntros (?) \"#Hinv Hl\".\n  iMod (inv_mapsto_own_acc with \"Hinv Hl\") as \"(% & Hl & Hclose)\"; first done.\n  iFrame \"%∗\". iIntros \"!>\" (w) \"% Hl\". iApply \"Hclose\"; done.\nQed.\n\nLemma inv_mapsto_acc l I E :\n  ↑inv_heapN ⊆ E →\n  inv_heap_inv -∗ l ↦_I □ ={E, E ∖ ↑inv_heapN}=∗\n    ∃ v, ⌜I v⌝ ∗ l ↦ v ∗ (l ↦ v ={E ∖ ↑inv_heapN, E}=∗ ⌜True⌝).\nProof.\n  iIntros (?) \"#Hinv Hl\".\n  iMod (inv_mapsto_acc with \"Hinv Hl\") as ([v|]) \"(% & Hl & Hclose)\"; [done| |done].\n  iIntros \"!>\". iExists (v). iFrame \"%∗\".\nQed.\n\n(** The usable rules for [allocN] stated in terms of the [array] proposition\nare derived in te file [array]. *)\nLemma heap_array_to_seq_meta l vs (n : nat) :\n  length vs = n →\n  ([∗ map] l' ↦ _ ∈ heap_array l vs, meta_token l' ⊤) -∗\n  [∗ list] i ∈ seq 0 n, meta_token (l +ₗ (i : nat)) ⊤.\nProof.\n  iIntros (<-) \"Hvs\". iInduction vs as [|v vs] \"IH\" forall (l)=> //=.\n  rewrite big_opM_union; last first.\n  { apply map_disjoint_spec=> l' v1 v2 /lookup_singleton_Some [-> _].\n    intros (j&w&?&Hjl&?&?)%heap_array_lookup.\n    rewrite loc_add_assoc -{1}[l']loc_add_0 in Hjl. simplify_eq; lia. }\n  rewrite loc_add_0 -fmap_S_seq big_sepL_fmap.\n  setoid_rewrite Nat2Z.inj_succ. setoid_rewrite <-Z.add_1_l.\n  setoid_rewrite <-loc_add_assoc.\n  rewrite big_opM_singleton; iDestruct \"Hvs\" as \"[$ Hvs]\". by iApply \"IH\".\nQed.\n\nLemma heap_array_to_seq_mapsto l v (n : nat) :\n  ([∗ map] l' ↦ ov ∈ heap_array l (replicate n v), gen_heap.mapsto l' (DfracOwn 1) ov) -∗\n  [∗ list] i ∈ seq 0 n, (l +ₗ (i : nat)) ↦ v.\nProof.\n  iIntros \"Hvs\". iInduction n as [|n] \"IH\" forall (l); simpl.\n  { done. }\n  rewrite big_opM_union; last first.\n  { apply map_disjoint_spec=> l' v1 v2 /lookup_singleton_Some [-> _].\n    intros (j&w&?&Hjl&_)%heap_array_lookup.\n    rewrite loc_add_assoc -{1}[l']loc_add_0 in Hjl. simplify_eq; lia. }\n  rewrite loc_add_0 -fmap_S_seq big_sepL_fmap.\n  setoid_rewrite Nat2Z.inj_succ. setoid_rewrite <-Z.add_1_l.\n  setoid_rewrite <-loc_add_assoc.\n  rewrite big_opM_singleton; iDestruct \"Hvs\" as \"[$ Hvs]\". by iApply \"IH\".\nQed.\n\nLemma twp_allocN_seq s E v n :\n  (0 < n)%Z →\n  [[{ True }]] AllocN (Val $ LitV $ LitInt $ n) (Val v) @ s; E\n  [[{ l, RET LitV (LitLoc l); [∗ list] i ∈ seq 0 (Z.to_nat n),\n      (l +ₗ (i : nat)) ↦ v ∗ meta_token (l +ₗ (i : nat)) ⊤ }]].\nProof.\n  iIntros (Hn Φ) \"_ HΦ\". iApply twp_lift_atomic_head_step_no_fork; first done.\n  iIntros (σ1 κs k) \"[Hσ Hκs] !>\"; iSplit; first by destruct n; auto with lia head_step.\n  iIntros (κ v2 σ2 efs Hstep); inv_head_step.\n  iMod (gen_heap_alloc_big _ (heap_array _ (replicate (Z.to_nat n) v)) with \"Hσ\")\n    as \"(Hσ & Hl & Hm)\".\n  { apply heap_array_map_disjoint.\n    rewrite replicate_length Z2Nat.id; auto with lia. }\n  iModIntro; do 2 (iSplit; first done). iFrame \"Hσ Hκs\". 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.\nLemma wp_allocN_seq s E v n :\n  (0 < n)%Z →\n  {{{ True }}} AllocN (Val $ LitV $ LitInt $ n) (Val v) @ s; E\n  {{{ l, RET LitV (LitLoc l); [∗ list] i ∈ seq 0 (Z.to_nat n),\n      (l +ₗ (i : nat)) ↦ v ∗ meta_token (l +ₗ (i : nat)) ⊤ }}}.\nProof.\n  iIntros (Hn Φ) \"_ HΦ\". iApply (twp_wp_step with \"HΦ\").\n  iApply twp_allocN_seq; [by auto..|]; iIntros (l) \"H HΦ\". by iApply \"HΦ\".\nQed.\n\nLemma twp_alloc s E v :\n  [[{ True }]] Alloc (Val v) @ s; E [[{ l, RET LitV (LitLoc l); l ↦ v ∗ meta_token l ⊤ }]].\nProof.\n  iIntros (Φ) \"_ HΦ\". iApply twp_allocN_seq; [auto with lia..|].\n  iIntros (l) \"/= (? & _)\". rewrite loc_add_0. iApply \"HΦ\"; iFrame.\nQed.\nLemma wp_alloc s E v :\n  {{{ True }}} Alloc (Val v) @ s; E {{{ l, RET LitV (LitLoc l); l ↦ v ∗ meta_token l ⊤ }}}.\nProof.\n  iIntros (Φ) \"_ HΦ\". iApply (twp_wp_step with \"HΦ\").\n  iApply twp_alloc; [by auto..|]; iIntros (l) \"H HΦ\". by iApply \"HΦ\".\nQed.\n\nLemma twp_free s E l v :\n  [[{ l ↦ v }]] Free (Val $ LitV $ LitLoc l) @ s; E\n  [[{ RET LitV LitUnit; True }]].\nProof.\n  iIntros (Φ) \"Hl HΦ\". iApply twp_lift_atomic_head_step_no_fork; first done.\n  iIntros (σ1 κs n) \"[Hσ Hκs] !>\". iDestruct (gen_heap_valid with \"Hσ Hl\") as %?.\n  iSplit; first by eauto with head_step.\n  iIntros (κ v2 σ2 efs Hstep); inv_head_step.\n  iMod (gen_heap_update with \"Hσ Hl\") as \"[$ Hl]\".\n  iModIntro. iSplit; first done. iSplit; first done. iFrame. by iApply \"HΦ\".\nQed.\nLemma wp_free s E l v :\n  {{{ ▷ l ↦ v }}} Free (Val $ LitV (LitLoc l)) @ s; E\n  {{{ RET LitV LitUnit; True }}}.\nProof.\n  iIntros (Φ) \">H HΦ\". iApply (twp_wp_step with \"HΦ\").\n  iApply (twp_free with \"H\"); [by auto..|]; iIntros \"H HΦ\". by iApply \"HΦ\".\nQed.\n\nLemma twp_load s E l dq v :\n  [[{ l ↦{dq} v }]] Load (Val $ LitV $ LitLoc l) @ s; E [[{ RET v; l ↦{dq} v }]].\nProof.\n  iIntros (Φ) \"Hl HΦ\". iApply twp_lift_atomic_head_step_no_fork; first done.\n  iIntros (σ1 κs n) \"[Hσ Hκs] !>\". iDestruct (gen_heap_valid with \"Hσ Hl\") as %?.\n  iSplit; first by eauto with head_step.\n  iIntros (κ v2 σ2 efs Hstep); inv_head_step.\n  iModIntro; iSplit=> //. iSplit; first done. iFrame. by iApply \"HΦ\".\nQed.\nLemma wp_load s E l dq v :\n  {{{ ▷ l ↦{dq} v }}} Load (Val $ LitV $ LitLoc l) @ s; E {{{ RET v; l ↦{dq} v }}}.\nProof.\n  iIntros (Φ) \">H HΦ\". iApply (twp_wp_step with \"HΦ\").\n  iApply (twp_load with \"H\"). iIntros \"H HΦ\". by iApply \"HΦ\".\nQed.\n\nLemma twp_store s E l v' v :\n  [[{ l ↦ v' }]] Store (Val $ LitV $ LitLoc l) (Val v) @ s; E\n  [[{ RET LitV LitUnit; l ↦ v }]].\nProof.\n  iIntros (Φ) \"Hl HΦ\". iApply twp_lift_atomic_head_step_no_fork; first done.\n  iIntros (σ1 κs n) \"[Hσ Hκs] !>\". iDestruct (gen_heap_valid with \"Hσ Hl\") as %?.\n  iSplit; first by eauto with head_step.\n  iIntros (κ v2 σ2 efs Hstep); inv_head_step.\n  iMod (gen_heap_update with \"Hσ Hl\") as \"[$ Hl]\".\n  iModIntro. iSplit; first done. iSplit; first done. iFrame. by iApply \"HΦ\".\nQed.\nLemma wp_store s E l v' v :\n  {{{ ▷ l ↦ v' }}} Store (Val $ LitV (LitLoc l)) (Val v) @ s; E\n  {{{ RET LitV LitUnit; l ↦ v }}}.\nProof.\n  iIntros (Φ) \">H HΦ\". iApply (twp_wp_step with \"HΦ\").\n  iApply (twp_store with \"H\"); [by auto..|]; iIntros \"H HΦ\". by iApply \"HΦ\".\nQed.\n\nLemma twp_cmpxchg_fail s E l dq v' v1 v2 :\n  v' ≠ v1 → vals_compare_safe v' v1 →\n  [[{ l ↦{dq} v' }]] CmpXchg (Val $ LitV $ LitLoc l) (Val v1) (Val v2) @ s; E\n  [[{ RET PairV v' (LitV $ LitBool false); l ↦{dq} v' }]].\nProof.\n  iIntros (?? Φ) \"Hl HΦ\". iApply twp_lift_atomic_head_step_no_fork; first done.\n  iIntros (σ1 κs n) \"[Hσ Hκs] !>\". iDestruct (gen_heap_valid with \"Hσ Hl\") as %?.\n  iSplit; first by eauto with head_step.\n  iIntros (κ v2' σ2 efs Hstep); inv_head_step.\n  rewrite bool_decide_false //.\n  iModIntro; iSplit; first done. iSplit; first done. iFrame. by iApply \"HΦ\".\nQed.\nLemma wp_cmpxchg_fail s E l dq v' v1 v2 :\n  v' ≠ v1 → vals_compare_safe v' v1 →\n  {{{ ▷ l ↦{dq} v' }}} CmpXchg (Val $ LitV $ LitLoc l) (Val v1) (Val v2) @ s; E\n  {{{ RET PairV v' (LitV $ LitBool false); l ↦{dq} v' }}}.\nProof.\n  iIntros (?? Φ) \">H HΦ\". iApply (twp_wp_step with \"HΦ\").\n  iApply (twp_cmpxchg_fail with \"H\"); [by auto..|]; iIntros \"H HΦ\". by iApply \"HΦ\".\nQed.\n\nLemma twp_cmpxchg_suc s E l v1 v2 v' :\n  v' = v1 → vals_compare_safe v' v1 →\n  [[{ l ↦ v' }]] CmpXchg (Val $ LitV $ LitLoc l) (Val v1) (Val v2) @ s; E\n  [[{ RET PairV v' (LitV $ LitBool true); l ↦ v2 }]].\nProof.\n  iIntros (?? Φ) \"Hl HΦ\". iApply twp_lift_atomic_head_step_no_fork; first done.\n  iIntros (σ1 κs n) \"[Hσ Hκs] !>\". iDestruct (gen_heap_valid with \"Hσ Hl\") as %?.\n  iSplit; first by eauto with head_step.\n  iIntros (κ v2' σ2 efs Hstep); inv_head_step.\n  rewrite bool_decide_true //.\n  iMod (gen_heap_update with \"Hσ Hl\") as \"[$ Hl]\".\n  iModIntro. iSplit; first done. iSplit; first done. iFrame. by iApply \"HΦ\".\nQed.\nLemma wp_cmpxchg_suc s E l v1 v2 v' :\n  v' = v1 → vals_compare_safe v' v1 →\n  {{{ ▷ l ↦ v' }}} CmpXchg (Val $ LitV $ LitLoc l) (Val v1) (Val v2) @ s; E\n  {{{ RET PairV v' (LitV $ LitBool true); l ↦ v2 }}}.\nProof.\n  iIntros (?? Φ) \">H HΦ\". iApply (twp_wp_step with \"HΦ\").\n  iApply (twp_cmpxchg_suc with \"H\"); [by auto..|]; iIntros \"H HΦ\". by iApply \"HΦ\".\nQed.\n\nLemma twp_faa s E l i1 i2 :\n  [[{ l ↦ LitV (LitInt i1) }]] FAA (Val $ LitV $ LitLoc l) (Val $ LitV $ LitInt i2) @ s; E\n  [[{ RET LitV (LitInt i1); l ↦ LitV (LitInt (i1 + i2)) }]].\nProof.\n  iIntros (Φ) \"Hl HΦ\". iApply twp_lift_atomic_head_step_no_fork; first done.\n  iIntros (σ1 κs n) \"[Hσ Hκs] !>\". iDestruct (gen_heap_valid with \"Hσ Hl\") as %?.\n  iSplit; first by eauto with head_step.\n  iIntros (κ e2 σ2 efs Hstep); inv_head_step.\n  iMod (gen_heap_update with \"Hσ Hl\") as \"[$ Hl]\".\n  iModIntro. do 2 (iSplit; first done). iFrame. by iApply \"HΦ\".\nQed.\nLemma wp_faa s E l i1 i2 :\n  {{{ ▷ l ↦ LitV (LitInt i1) }}} FAA (Val $ LitV $ LitLoc l) (Val $ LitV $ LitInt i2) @ s; E\n  {{{ RET LitV (LitInt i1); l ↦ LitV (LitInt (i1 + i2)) }}}.\nProof.\n  iIntros (Φ) \">H HΦ\". iApply (twp_wp_step with \"HΦ\").\n  iApply (twp_faa with \"H\"); [by auto..|]; iIntros \"H HΦ\". by iApply \"HΦ\".\nQed.\n\nLemma wp_new_proph s E :\n  {{{ True }}}\n    NewProph @ s; E\n  {{{ pvs p, RET (LitV (LitProphecy p)); proph p pvs }}}.\nProof.\n  iIntros (Φ) \"_ HΦ\". iApply wp_lift_atomic_head_step_no_fork; first done.\n  iIntros (σ1 κ κs n) \"[Hσ HR] !>\". iSplit; first by eauto with head_step.\n  iIntros \"!>\" (v2 σ2 efs Hstep). inv_head_step.\n  rename select proph_id into p.\n  iMod (proph_map_new_proph p with \"HR\") as \"[HR Hp]\"; first done.\n  iModIntro; iSplit; first done. iFrame. by iApply \"HΦ\".\nQed.\n\n(* In the following, strong atomicity is required due to the fact that [e] must\nbe able to make a head step for [Resolve e _ _] not to be (head) stuck. *)\n\nLemma resolve_reducible e σ (p : proph_id) v :\n  Atomic StronglyAtomic e → reducible e σ →\n  reducible (Resolve e (Val (LitV (LitProphecy p))) (Val v)) σ.\nProof.\n  intros A (κ & e' & σ' & efs & H).\n  exists (κ ++ [(p, (default v (to_val e'), v))]), e', σ', efs.\n  eapply (Ectx_step []); try done.\n  assert (∃w, Val w = e') as [w <-].\n  { unfold Atomic in A. apply (A σ e' κ σ' efs) in H. unfold is_Some in H.\n    destruct H as [w H]. exists w. simpl in H. by apply (of_to_val _ _ H). }\n  simpl. constructor. by apply prim_step_to_val_is_head_step.\nQed.\n\nLemma step_resolve e vp vt σ1 κ e2 σ2 efs :\n  Atomic StronglyAtomic e →\n  prim_step (Resolve e (Val vp) (Val vt)) σ1 κ e2 σ2 efs →\n  head_step (Resolve e (Val vp) (Val vt)) σ1 κ e2 σ2 efs.\nProof.\n  intros A [Ks e1' e2' Hfill -> step]. simpl in *.\n  induction Ks as [|K Ks _] using rev_ind.\n  + simpl in *. subst. inv_head_step. by constructor.\n  + rewrite fill_app /= in Hfill. destruct K; inversion Hfill; subst; clear Hfill.\n    - rename select ectx_item into Ki.\n      assert (fill_item Ki (fill Ks e1') = fill (Ks ++ [Ki]) e1') as Eq1;\n        first by rewrite fill_app.\n      assert (fill_item Ki (fill Ks e2') = fill (Ks ++ [Ki]) e2') as Eq2;\n        first by rewrite fill_app.\n      rewrite fill_app /=. rewrite Eq1 in A.\n      assert (is_Some (to_val (fill (Ks ++ [Ki]) e2'))) as H.\n      { apply (A σ1 _ κ σ2 efs). eapply (Ectx_step (Ks ++ [Ki])); done. }\n      destruct H as [v H]. apply to_val_fill_some in H. by destruct H, Ks.\n    - rename select (of_val vp = _) into Hvp.\n      assert (to_val (fill Ks e1') = Some vp) as Hfillvp by rewrite -Hvp //.\n      apply to_val_fill_some in Hfillvp as [-> ->]. inv_head_step.\n    - rename select (of_val vt = _) into Hvt.\n      assert (to_val (fill Ks e1') = Some vt) as Hfillvt by rewrite -Hvt //.\n      apply to_val_fill_some in Hfillvt as [-> ->]. inv_head_step.\nQed.\n\nLemma wp_resolve s E e Φ (p : proph_id) v (pvs : list (val * val)) :\n  Atomic StronglyAtomic e →\n  to_val e = None →\n  proph p pvs -∗\n  WP e @ s; E {{ r, ∀ pvs', ⌜pvs = (r, v)::pvs'⌝ -∗ proph p pvs' -∗ Φ r }} -∗\n  WP Resolve e (Val $ LitV $ LitProphecy p) (Val v) @ s; E {{ Φ }}.\nProof.\n  (* TODO we should try to use a generic lifting lemma (and avoid [wp_unfold])\n     here, since this breaks the WP abstraction. *)\n  iIntros (A He) \"Hp WPe\". rewrite !wp_unfold /wp_pre /= He. simpl in *.\n  iIntros (σ1 κ κs n) \"[Hσ Hκ]\". destruct κ as [|[p' [w' v']] κ' _] using rev_ind.\n  - iMod (\"WPe\" $! σ1 [] κs n with \"[$Hσ $Hκ]\") as \"[Hs WPe]\". iModIntro. iSplit.\n    { iDestruct \"Hs\" as \"%\". iPureIntro. destruct s; [ by apply resolve_reducible | done]. }\n    iIntros (e2 σ2 efs step). exfalso. apply step_resolve in step; last done.\n    inv_head_step. match goal with H: ?κs ++ [_] = [] |- _ => by destruct κs end.\n  - rewrite -assoc.\n    iMod (\"WPe\" $! σ1 _ _ n with \"[$Hσ $Hκ]\") as \"[Hs WPe]\". iModIntro. iSplit.\n    { iDestruct \"Hs\" as %?. iPureIntro. destruct s; [ by apply resolve_reducible | done]. }\n    iIntros (e2 σ2 efs step). apply step_resolve in step; last done.\n    inv_head_step; simplify_list_eq.\n    iMod (\"WPe\" $! (Val w') σ2 efs with \"[%]\") as \"WPe\".\n    { by eexists [] _ _. }\n    iModIntro. iNext. iMod \"WPe\" as \"[[$ Hκ] WPe]\".\n    iMod (proph_map_resolve_proph p' (w',v') κs with \"[$Hκ $Hp]\") as (vs' ->) \"[$ HPost]\".\n    iModIntro. rewrite !wp_unfold /wp_pre /=. iDestruct \"WPe\" as \"[HΦ $]\".\n    iMod \"HΦ\". iModIntro. by iApply \"HΦ\".\nQed.\n\nEnd lifting.\n", "meta": {"author": "gares", "repo": "iris", "sha": "7b4a04ce0d396cb27eeef22e883a9f3b738e83f4", "save_path": "github-repos/coq/gares-iris", "path": "github-repos/coq/gares-iris/iris-7b4a04ce0d396cb27eeef22e883a9f3b738e83f4/iris_heap_lang/primitive_laws.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.27550472844871315}}
{"text": "From Undecidability.L.Tactics Require Import LTactics.\nFrom Undecidability.L Require Import UpToC.\nFrom Undecidability.L.Datatypes Require Export List_enc List_in List_basics LBool LNat.\n\nSet Default Proof Using \"Type\".\n\nDefinition lengthEq A :=\n  fix f (t:list A) n :=\n    match n,t with\n      0,nil => true\n    | (S n), _::t => f t n\n    | _,_ => false\n    end.\nLemma lengthEq_spec A (t:list A) n:\n| t | =? n = lengthEq t n.\nProof.\n  induction n in t|-*;destruct t;now cbn.\nQed.\nDefinition lengthEq_time k := k * 15 + 9.\nInstance term_lengthEq A `{registered A} : computableTime' (lengthEq (A:=A)) (fun l _ => (5, fun n _ => (lengthEq_time (min (length l) n),tt))).\nProof.\n  extract. unfold lengthEq_time. solverec.\nQed.\n\n\n(* seq *)\nDefinition c__seq := 20.\nDefinition seq_time (len : nat) := (len + 1) * c__seq.\nInstance term_seq : computableTime' seq (fun start _ => (5, fun len _ => (seq_time len, tt))). \nProof. \n  extract. solverec. \n  all: unfold seq_time, c__seq; solverec. \nQed. \n\n(* prodLists *)\nSection fixprodLists. \n  Variable (X Y : Type).\n  Context `{Xint : registered X} `{Yint : registered Y}.\n\n  Definition c__prodLists1 := 22 + c__map + c__app. \n  Definition c__prodLists2 := 2 * c__map + 39 + c__app.\n  Definition prodLists_time (l1 : list X) (l2 : list Y) := (|l1|) * (|l2| + 1) * c__prodLists2 + c__prodLists1. \n  Global Instance term_prodLists : computableTime' (@list_prod X Y) (fun l1 _ => (5, fun l2 _ => (prodLists_time l1 l2, tt))). \n  Proof. \n    apply computableTimeExt with (x := fix rec (A : list X) (B : list Y) : list (X * Y) := \n      match A with \n      | [] => []\n      | x :: A' => map (@pair X Y x) B ++ rec A' B \n      end). \n    1: { unfold list_prod. change (fun x => ?h x) with h. intros l1 l2. induction l1; easy. }\n    extract. solverec. \n    all: unfold prodLists_time, c__prodLists1, c__prodLists2; solverec. \n    rewrite map_length, map_time_const. leq_crossout. \n  Qed. \nEnd fixprodLists. \n\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_extra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.27550472844871315}}
{"text": "Require Import VST.floyd.proofauto.\nLocal Open Scope logic.\nRequire Import List. Import ListNotations.\nRequire Import tweetnacl20140427.Snuffle.\nRequire Import tweetnacl20140427.Salsa20.\nRequire Import ZArith.\n\nRequire Import tweetnacl20140427.tweetnaclVerifiableC.\nRequire Import tweetnacl20140427.spec_salsa.\nRequire Import tweetnacl20140427.verif_salsa_base.\nOpaque Snuffle20. Opaque prepare_data. Opaque Snuffle.Snuffle.\n\nLemma crypto_core_salsa20_ok: semax_body SalsaVarSpecs SalsaFunSpecs\n      f_crypto_core_salsa20_tweet crypto_core_salsa20_spec.\nProof. unfold crypto_core_salsa20_spec.\nstart_function.\nabbreviate_semax.\nassert_PROP (field_compatible (tarray tuchar 64) [] out /\\ isptr out) as HH by entailer!.\ndestruct HH as [FCout isptrout].\nTime forward_call (c, k, Z0, nonce, out, default_val (tarray tuchar 64), data). (*1.8*)\n  unfold data_at_, field_at_. rewrite field_at_data_at.\n  rewrite field_address_offset by auto with field_compatible.\n  rewrite isptr_offset_val_zero; trivial. cancel.\nIntros ret.\nTime forward. (*1.7*)\nunfold fcore_result in H.\n  remember (Snuffle20 (prepare_data data)) as d; symmetry in Heqd.\n  destruct d. 2: inv H. rewrite Int.eq_true in H.\nExists l.\nTime entailer!. apply derives_refl.\nTime Qed. (*4.3*)\n\nLemma Snuffle_sub_simpl data x:\n    Snuffle20 (prepare_data data) = Some x ->\n    exists s, Snuffle 20 (prepare_data data) = Some s /\\\n    forall i (I:0 <= i < 16) v,\n      Znth i (prepare_data data) = v ->\n      littleendian_invert (Int.sub (Znth i x) v) =\n      littleendian_invert (Znth i s).\nProof. intros.\nTransparent Snuffle20. unfold Snuffle20 in H. Opaque Snuffle20.\nremember (Snuffle 20 (prepare_data data)) as sn.\ndestruct sn; simpl in H. 2: inv H. clear Heqsn.\nexists l; split; trivial.\nintros. rewrite (sumlist_char_Znth _ _ _ H).\n  rewrite Int.add_commut, Int.sub_add_l, H0, Int.sub_idem, Int.add_zero_l. trivial.\nsymmetry in H; apply sumlist_length in H.\nrewrite Zlength_correct, H, prepare_data_length; trivial.\nQed.\n\nLemma crypto_core_hsalsa20_ok: semax_body SalsaVarSpecs SalsaFunSpecs\n      f_crypto_core_hsalsa20_tweet crypto_core_hsalsa20_spec.\nProof. unfold crypto_core_hsalsa20_spec.\nstart_function.\nTime forward_call (c, k, 1, nonce, out, OUT, data). (*1.4*)\nIntros res.\nTime forward. (*1.6*)\nunfold fcore_result in H.\n  remember (Snuffle20 (prepare_data data)) as d; symmetry in Heqd.\n  destruct d. 2: inv H. rewrite Int.eq_false in H.\ndestruct (Snuffle_sub_simpl _ _ Heqd) as [x [X1 X2]].\nExists x.\nTime entailer!. (*0.6*)\n2: apply Int.one_not_zero.\nunfold fcorePOST_SEP; cancel.\n  destruct data as[[Nonce C] [K L]].\n  destruct C as [[[C1 C2] C3] C4].\n  destruct Nonce as [[[N1 N2] N3] N4].\n  destruct K as [[[K1 K2] K3] K4].\n  destruct L as [[[L1 L2] L3] L4].\napply derives_refl'. f_equal.\n  do 8 rewrite X2 in H by (try omega; reflexivity).\n  apply H.\nTime Qed. (*2.8*)", "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_crypto_core.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.2754641344391868}}
{"text": "Require Import Coq.ZArith.ZArith. Local Open Scope Z_scope.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List. Import ListNotations.\nRequire Import coqutil.Tactics.Tactics.\nRequire Import riscv.Spec.Machine.\nRequire Import riscv.Platform.Memory.\nRequire Import riscv.Spec.CSRFile.\nRequire Import riscv.Utility.Utility.\nRequire Import riscv.Utility.RecordSetters.\nRequire Import coqutil.Z.Lia.\nRequire Import coqutil.Map.Interface.\nRequire Import riscv.Platform.MaterializeRiscvProgram.\n\nModule map.\n  (* Swap argument order to enable usage of partially applied `map.set k v` as an updater *)\n  Definition set{key value}{map: map.map key value}(k: key)(v: value)(m: map): map :=\n    map.put m k v.\nEnd map.\n\nSection Riscv.\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 Z word}.\n\n  (* (memory before call, call name, arg values) and (memory after call, return values) *)\n  Definition LogItem: Type := (Mem * string * list word) * (Mem * list word).\n\n  Record State := mkState {\n    regs: Registers;\n    pc: word;\n    nextPc: word;\n    mem: Mem;\n    log: list LogItem;\n    csrs: CSRFile\n  }.\n\n  (* TODO: add XAddrs tracking so that executing an instruction written in a previous cycle\n     (which potentially is already in the pipeline) is not allowed *)\n\n  Definition store(n: nat)(ctxid: SourceType)(a: word) v (mach: State)(post: State -> Prop) :=\n    match Memory.store_bytes n mach.(mem) a v with\n    | Some m => post { mach with mem := m }\n    | None => False\n    end.\n\n  Definition load(n: nat)(ctxid: SourceType)(a: word)(mach: State)(post: _ -> _ -> Prop) :=\n    match Memory.load_bytes n mach.(mem) a with\n    | Some v => post v mach\n    | None => False\n    end.\n\n  Definition updatePc(mach: State): State :=\n    { mach with pc := mach.(nextPc); nextPc ::= word.add (word.of_Z 4) }.\n\n  Definition getReg(regs: Registers)(reg: Z): word :=\n    if ((0 <? reg) && (reg <? 32))%bool 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))%bool then map.put regs reg v else regs.\n\n  Definition run_primitive(a: riscv_primitive)(mach: State):\n             (primitive_result a -> State -> Prop) -> (State -> Prop) -> Prop :=\n    match a with\n    | GetRegister reg => fun postF postA => postF (getReg mach.(regs) reg) mach\n    | SetRegister reg v => fun postF postA => postF tt { mach with regs ::= setReg reg v }\n    | GetPC => fun postF postA => postF mach.(pc) mach\n    | SetPC newPC => fun postF postA => postF tt { mach with nextPc := newPC }\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 { mach with nextPc := word.add mach.(pc) (word.of_Z 4) }\n    | EndCycleNormal => fun postF postA => postF tt (updatePc mach)\n    | EndCycleEarly _ => fun postF postA => postA (updatePc mach) (* ignores postF containing the continuation *)\n    | GetCSRField f => fun postF postA =>\n                         match map.get mach.(csrs) f with\n                         | Some v => postF v mach\n                         | None => False\n                         end\n    | SetCSRField f v => fun postF postA =>\n                           (* only allow setting CSR fields that are supported (not None) on this machine *)\n                           match map.get mach.(csrs) f with\n                           | Some _ => postF tt { mach with csrs ::= map.set f v }\n                           | None => False\n                           end\n    | GetPrivMode => fun postF postA => postF Machine mach\n    | SetPrivMode mode => fun postF postA =>\n                            match mode with\n                            | Machine => postF tt mach\n                            | User | Supervisor => False\n                            end\n    | MakeReservation _\n    | ClearReservation _\n    | CheckReservation _\n    | Fence _ _\n        => fun postF postA => False\n    end.\n\n  Lemma weaken_load: forall n c a m (post1 post2:_->_->Prop),\n      (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    unfold load. intros. destruct (load_bytes n m.(mem) a); intuition eauto.\n  Qed.\n\n  Lemma weaken_store: forall n c a v m (post1 post2:_->Prop),\n      (forall s, post1 s -> post2 s) ->\n      store n c a v m post1 -> store n c a v m post2.\n  Proof.\n    unfold store. intros. destruct (store_bytes n m.(mem) a v); intuition eauto.\n  Qed.\n\n  Lemma weaken_run_primitive: forall 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, run_primitive a s postF1 postA1 -> run_primitive a s postF2 postA2.\n  Proof.\n    destruct a; cbn; intros; try solve [intuition eauto using weaken_load, weaken_store];\n      destruct_one_match; eauto.\n  Qed.\n\nEnd Riscv.\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/deps/riscv-coq/src/riscv/Platform/MinimalCSRs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.2753753891032127}}
{"text": "Require Import Bmc.Forward.\nRequire Import Bmc.Example.\n\nRequire Import SMTC.Tactic.\nRequire Import SMTC.Integers.\n\nSet SMT Solver \"z3\".\nSet SMT Debug.\n\nAxiom by_smt : forall P : Prop, P.\n\n\nGoal forward_post_conj ex1_I ex1_T ex1_P 4.\nProof.\n  unfold ex1_I, ex1_T, ex1_P.\n  unfold forward_post_conj.\n  unfold lasso_fwd_conj.\n  unfold safety_nth_conj.\n  unfold prop_nth_init_conj.\n  unfold loop_free.\n  unfold path.\n  unfold no_loop.\n  unfold no_loop'.\n  unfold sseq.\n  unfold nth.\n  unfold state.\n  repeat rewrite -> Nat.add_0_l.\n  repeat rewrite -> Nat.add_0_r.\n\n  split.\n  - intros.\n    smt solve; apply by_smt.\n\n  - repeat split.\n    + intros.\n      smt solve; apply by_smt.\n    + intros.\n      smt solve; apply by_smt.\n    + intros.\n      smt solve; apply by_smt.\n    + intros.\n      smt solve; apply by_smt.\n    + intros.\n      smt solve; apply by_smt.\nQed.\n\nGoal forward_post_conj ex2_I ex2_T ex2_P 2.\nProof.\n  unfold ex2_I, ex2_T, ex2_P.\n  unfold forward_post_conj, lasso_fwd_conj, safety_nth_conj, prop_nth_init_conj, loop_free, path, no_loop, no_loop', sseq, nth, state.\n  repeat rewrite -> Nat.add_0_l;\n  repeat rewrite -> Nat.add_0_r.\n  split.\n  intros; smt solve; apply by_smt.\n  repeat split; intros; smt solve; apply by_smt.\nQed.\n\nGoal forward_post_conj ex3_I ex3_T ex3_P 6.\nProof.\n  unfold ex3_I, ex3_T, ex3_P.\n  unfold forward_post_conj, lasso_fwd_conj, safety_nth_conj, prop_nth_init_conj, loop_free, path, no_loop, no_loop', sseq, nth, state.\n  repeat rewrite -> Nat.add_0_l;\n  repeat rewrite -> Nat.add_0_r.\n  split.\n  intros; smt solve; apply by_smt.\n  repeat split; intros; smt solve; apply by_smt.\nQed.\n\n(* eof *)\n", "meta": {"author": "dsksh", "repo": "coq-smc", "sha": "60e63dc612eeffe7ed5ad4a658fdacf30709b19a", "save_path": "github-repos/coq/dsksh-coq-smc", "path": "github-repos/coq/dsksh-coq-smc/coq-smc-60e63dc612eeffe7ed5ad4a658fdacf30709b19a/src/Forward_example.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2753036827676202}}
{"text": "Require Import NArith.\nRequire Import Arith.\nRequire Import Bool.\nRequire Import List.\nRequire Import Bag.\nRequire Import Dict.\nRequire Import Misc.\nRequire Import SpaceSearch.CpdtTactics.\nRequire Import JamesTactics.\nRequire Import Coq.Program.Basics.\nRequire Import SpaceSearch.EqDec.\nRequire Import Enumerable.\nRequire Import BGPSpec.\nRequire Import Reachable.\nRequire Import Tracking.\nRequire Import KonneTactics.\nRequire Import Equality.\nRequire Import BGPSpecFacts.\nRequire Import Policy.\nImport EqNotations.\nImport ListNotations.\n\nSection FastPolicy.\n  Variable plainPrefix : PrefixClass.\n  Variable plainTopology : TopologyClass.\n  Variable plainAttributes : PathAttributesClass.\n  Variable plainConfiguration : forall r, ConfigurationClass r.\n\n  Definition trackingAttributes' := @trackingAttributes _ plainAttributes.\n  Definition trackingConfiguration' := @trackingConfiguration _ _ plainAttributes plainConfiguration.\n  Existing Instance trackingAttributes' | 0.\n  Existing Instance trackingConfiguration' | 0.\n  Typeclasses Transparent trackingAttributes'.\n  Typeclasses Transparent trackingConfiguration'.\n  Existing Instance enumerableIncoming.\n  Existing Instance eqDecIncoming.\n\n  Definition fastPolicy (P:forall r, incoming r -> outgoing r -> Prefix ->\n                       RoutingInformation -> RoutingInformation -> \n                       RoutingInformation -> RoutingInformation -> bool) : Prop :=\n    forall r s d p s' ai ai',\n      trackingOk r s p ai ->\n      trackingOk r s' p ai' ->\n      let al' := @import' _ trackingAttributes' _ r _ s  p ai in\n      let al  := @import' _ trackingAttributes' _ r _ s' p ai' in\n      let ao  := @export' _ trackingAttributes' _ r _ s' d p al in\n        leDecRoutingInformation al' al = true -> P r s d p ai al' al ao = true.\n\n  Theorem fastPolicyImpliesPolicy : forall P, fastPolicy P -> (@policy _ _ trackingAttributes' trackingConfiguration' P).\n    intros P Q. unfold policy, fastPolicy in *. \n    intros r s d p ns R.\n    specialize (routerStateOk r s d p ns R); intro S.\n    destruct S as [s' S].\n    destruct S as [S S']. destruct S' as [S' S'']. \n    unfold build, lookup in *.\n    unfold trackingAttributes' in *.\n    rewrite S'. rewrite S''.\n    pose (in_ := adjRIBsIn (lookup (routerState ns) r)).\n    pose (ai  := lookup in_ (s, p)).\n    pose (ai' := lookup in_ (s', p)).\n    specialize (reachableImpliesTrackingOk ns R); intros F. destruct F as [F _].\n    refine ((fun F' => _) F).\n    specialize (F r s p).\n    specialize (F' r s' p).\n    specialize (Q r s d p s' ai ai' F F' S).\n    inline_all.\n    unfold build, lookup in *.\n    trivial.\n  Qed.\nEnd FastPolicy.\n", "meta": {"author": "uwplse", "repo": "bagpipe", "sha": "67a38c4c6def7fb270a045b4afa668d22e293be7", "save_path": "github-repos/coq/uwplse-bagpipe", "path": "github-repos/coq/uwplse-bagpipe/bagpipe-67a38c4c6def7fb270a045b4afa668d22e293be7/src/bagpipe/coq/Main/FastPolicy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.27526149788345605}}
{"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 ListSet.\nRequire Import String.\nRequire Import ZArith.\nRequire Import Permutation.\nRequire Import Equivalence.\nRequire Import Morphisms.\nRequire Import Program.\nRequire Import EquivDec.\nRequire Import Bool.\nRequire Import Utils.\nRequire Import ForeignData.\nRequire Import Data.\nRequire Import DataLift.\n\nSection RecOperators.\n  Context {fdata:foreign_data}.\n\n  Section RecConcat.\n    (** Semantics of the [rec_concat] operator. *)\n    Definition recconcat (r1 r2:list (string*data)) :=\n      rec_concat_sort r1 r2.\n\n    Inductive rec_concat_sem: data -> data -> data -> Prop :=\n    | sem_rec_concat:\n        forall r1 r2,\n          rec_concat_sem (drec r1) (drec r2)\n                         (drec (recconcat r1 r2)).\n\n    (* [orecconcat] is correct and complete wrt. the [rec_concat_sem]\n       semantics. *)\n    \n    Definition orecconcat (a:data) (x:data) :=\n      match a with\n      | drec r2 =>\n        match x with\n        | drec r1 => Some (drec (rec_concat_sort r2 r1))\n        | _ => None\n        end\n      | _ => None\n      end.\n\n    Lemma orecconcat_correct : forall d d1 d2,\n        orecconcat d d1 = Some d2 ->\n        rec_concat_sem d d1 d2.\n    Proof.\n      intros.\n      destruct d; destruct d1; simpl in *; try congruence.\n      inversion H; econstructor; reflexivity.\n    Qed.\n\n    Lemma orecconcat_complete : forall d d1 d2,\n        rec_concat_sem d d1 d2 ->\n        orecconcat d d1 = Some d2.\n    Proof.\n      intros.\n      inversion H; subst.\n      reflexivity.\n    Qed.\n\n    Lemma orecconcat_correct_and_complete : forall d d1 d2,\n        orecconcat d d1 = Some d2 <->\n        rec_concat_sem d d1 d2.\n    Proof.\n      split.\n      apply orecconcat_correct.\n      apply orecconcat_complete.\n    Qed.\n  End RecConcat.\n\n  Section SRProject.\n    Definition sorted_vector (s:list string) : list string :=\n      insertion_sort ODT_lt_dec s.\n    \n    Lemma sorted_vector_sorted (s:list string) :\n      is_list_sorted ODT_lt_dec (sorted_vector s) = true.\n    Proof.\n      rewrite is_list_sorted_Sorted_iff.\n      apply insertion_sort_Sorted.\n    Qed.\n\n    Definition projected_subset (s1 s2:list string) : list string :=\n      filter (fun x => if in_dec string_dec x s2 then true else false) s1.\n    \n    Lemma projected_subst_sorted (s1 s2:list string) :\n      is_list_sorted ODT_lt_dec s1 = true ->\n      is_list_sorted ODT_lt_dec (projected_subset s1 s2) = true.\n    Proof.\n      intros.\n      rewrite sorted_StronglySorted.\n      apply StronglySorted_filter.\n      rewrite <- sorted_StronglySorted.\n      eauto.\n      apply StrictOrder_Transitive.\n      apply StrictOrder_Transitive.\n    Qed.\n    \n    Lemma sorted_projected_subset_is_sublist (s1 s2:list string):\n      is_list_sorted ODT_lt_dec s1 = true ->\n      is_list_sorted ODT_lt_dec s2 = true ->\n      sublist (projected_subset s1 s2) s2.\n    Proof.\n      intros.\n      apply StronglySorted_incl_sublist.\n      rewrite <- sorted_StronglySorted.\n      eapply projected_subst_sorted; assumption.\n      apply StrictOrder_Transitive.\n      rewrite <- sorted_StronglySorted.\n      eauto.\n      apply StrictOrder_Transitive.\n      intros.\n      unfold projected_subset in *.\n      induction s1; simpl in H1.\n      contradiction.\n      assert (is_list_sorted ODT_lt_dec s1 = true).\n      apply (@is_list_sorted_cons_inv string _ _ a s1); assumption.\n      specialize (IHs1 H2); clear H.\n      destruct (in_dec string_dec a s2); simpl in *.\n      - elim H1; clear H1; intros.\n        subst.\n        assumption.\n        apply (IHs1 H).\n      - apply (IHs1 H1).\n    Qed.\n    \n    (* This is a form of projection that guarantees that the projection\n       list is first sorted then pruned to the domain of its input. *)\n    \n    Definition srproject {A} (l:list (string*A)) (s:list string) : list (string*A) :=\n      let ps := (projected_subset (sorted_vector s) (domain l)) in\n      rproject l ps.\n    \n    Lemma insertion_sort_insert_equiv_vec (x a:string) (l:list string) :\n      In x\n         (SortingAdd.insertion_sort_insert ODT_lt_dec a l) <->\n      a = x \\/ In x l.\n    Proof.\n      induction l; simpl; [intuition|].\n      destruct a; destruct a0; simpl in *.\n      split; intros.\n      intuition.\n      intuition.\n      split; intros.\n      intuition.\n      intuition.\n      split; intros.\n      intuition.\n      intuition.\n      destruct (StringOrder.lt_dec (String a a1) (String a0 a2)); simpl; [intuition|].\n      destruct (StringOrder.lt_dec (String a0 a2) (String a a1)); simpl; [intuition|].\n      split; intros.\n      intuition.\n      intuition.\n      subst; clear H0.\n      revert n n0 H1 H3.\n      generalize (String a a1), (String a0 a2); intros.\n      left.\n      destruct (trichotemy s s0); intuition.\n    Qed.\n\n    Lemma sorted_vector_equivlist l : \n      equivlist (sorted_vector l) l.\n    Proof.\n      unfold equivlist.\n      induction l; simpl; [intuition|]; intros x.\n      rewrite <- IHl. apply insertion_sort_insert_equiv_vec.\n    Qed.\n\n    Lemma equivlist_in_dec (x:string) (s1 s2:list string) :\n      (equivlist s1 s2) ->\n      (if (in_dec string_dec x s1) then true else false) =\n      (if (in_dec string_dec x s2) then true else false).\n    Proof.\n      intros.\n      destruct (in_dec string_dec x s1); destruct (in_dec string_dec x s2); try reflexivity.\n      assert (In x s2). rewrite <- H; assumption. congruence.\n      assert (In x s1). rewrite H; assumption. congruence.\n    Qed.\n\n    Lemma sorted_vector_in_dec (x:string) (s1:list string):\n      (if (in_dec string_dec x s1) then true else false) =\n      (if (in_dec string_dec x (sorted_vector s1)) then true else false).\n    Proof.\n      rewrite (equivlist_in_dec x s1 (sorted_vector s1)).\n      reflexivity.\n      rewrite sorted_vector_equivlist.\n      reflexivity.\n    Qed.\n\n    Lemma in_intersection_projected (x:string) (s1 s2:list string) :\n      In x s1 /\\ In x s2 -> In x (projected_subset s1 s2).\n    Proof.\n      intros.\n      elim H; clear H; intros.\n      induction s1.\n      simpl in *. contradiction.\n      simpl in *.\n      elim H; clear H; intros.\n      subst.\n      destruct (in_dec string_dec x s2); try congruence.\n      simpl; left; reflexivity.\n      specialize (IHs1 H); clear H0 H.\n      destruct (in_dec string_dec a s2); auto.\n      simpl; right; assumption.\n    Qed.\n\n    Lemma in_projected (x:string) (s1 s2:list string) :\n      In x (projected_subset s1 s2) -> In x s1.\n    Proof.\n      intros.\n      induction s1; simpl in *; [contradiction|].\n      destruct (in_dec string_dec a s2); simpl in *.\n      elim H; clear H; intros.\n      left; assumption.\n      right; apply (IHs1 H).\n      right; apply (IHs1 H).\n    Qed.\n    \n    Lemma sproject_in_dec {A} (x:string) (s1:list string) (l:list (string*A)) :\n      In x (domain l) ->\n      (if (in_dec string_dec x s1) then true else false) =\n      (if (in_dec string_dec x (projected_subset s1 (domain l))) then true else false).\n    Proof.\n      intros.\n      destruct (in_dec string_dec x s1); destruct (in_dec string_dec x (projected_subset s1 (domain l))); try reflexivity.\n      - assert (In x (projected_subset s1 (domain l))) by\n            (apply in_intersection_projected; auto).\n        congruence.\n      - assert (In x s1) by (apply (in_projected x s1 (domain l)); assumption).\n        congruence.\n    Qed.\n    \n    Lemma rproject_sproject {A} (l:list (string*A)) (s:list string) :\n      is_list_sorted ODT_lt_dec (domain l) = true ->\n      rproject l s = srproject l s.\n    Proof.\n      intros.\n      unfold srproject.\n      unfold rproject.\n      assert (filter\n                (fun x : string * A =>\n                   if in_dec string_dec (fst x) s then true else false) l =\n              filter\n                (fun x : string * A =>\n                   if in_dec string_dec (fst x) (sorted_vector s) then true else false) l).\n      apply filter_eq; intros.\n      rewrite sorted_vector_in_dec; reflexivity.\n      rewrite H0; clear H0;\n        generalize (sorted_vector s) as ss; intros.\n      apply filter_ext; intros.\n      apply sproject_in_dec.\n      destruct x; simpl in *.\n      induction l; try auto.\n      assert (is_list_sorted StringOrder.lt_dec (domain l) = true).\n      apply (@is_list_sorted_cons_inv string _ _ (fst a0) (domain l)); assumption.\n      specialize (IHl H1); clear H1 H.\n      simpl in *.\n      elim H0; clear H0; intros.\n      subst; simpl; left; reflexivity.\n      right; apply (IHl H).\n    Qed.\n\n  End SRProject.\nEnd RecOperators.\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/Operators/RecOperators.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2752225396311443}}
{"text": "From stdpp Require Export list gmap.\nFrom iris.algebra Require Export cmra.\nFrom iris.algebra Require Import updates local_updates proofmode_classes.\nFrom iris.base_logic Require Import base_logic.\nFrom iris Require Import options.\n\nSection cofe.\nContext `{Countable K} {A : ofeT}.\nImplicit Types m : gmap K A.\nImplicit Types i : K.\n\nInstance gmap_dist : Dist (gmap K A) := λ n m1 m2,\n  ∀ i, m1 !! i ≡{n}≡ m2 !! i.\nDefinition gmap_ofe_mixin : OfeMixin (gmap K A).\nProof.\n  split.\n  - intros m1 m2; split.\n    + by intros Hm n k; apply equiv_dist.\n    + intros Hm k; apply equiv_dist; intros n; apply Hm.\n  - intros n; split.\n    + by intros m k.\n    + by intros m1 m2 ? k.\n    + by intros m1 m2 m3 ?? k; trans (m2 !! k).\n  - by intros n m1 m2 ? k; apply dist_S.\nQed.\nCanonical Structure gmapO : ofeT := OfeT (gmap K A) gmap_ofe_mixin.\n\nProgram Definition gmap_chain (c : chain gmapO)\n  (k : K) : chain (optionO A) := {| chain_car n := c n !! k |}.\nNext Obligation. by intros c k n i ?; apply (chain_cauchy c). Qed.\nDefinition gmap_compl `{Cofe A} : Compl gmapO := λ c,\n  map_imap (λ i _, compl (gmap_chain c i)) (c 0).\nGlobal Program Instance gmap_cofe `{Cofe A} : Cofe gmapO :=\n  {| compl := gmap_compl |}.\nNext Obligation.\n  intros ? n c k. rewrite /compl /gmap_compl map_lookup_imap.\n  feed inversion (λ H, chain_cauchy c 0 n H k);simplify_option_eq;auto with lia.\n  by rewrite conv_compl /=; apply reflexive_eq.\nQed.\n\nGlobal Instance gmap_ofe_discrete : OfeDiscrete A → OfeDiscrete gmapO.\nProof. intros ? m m' ? i. by apply (discrete _). Qed.\n(* why doesn't this go automatic? *)\nGlobal Instance gmapO_leibniz: LeibnizEquiv A → LeibnizEquiv gmapO.\nProof. intros; change (LeibnizEquiv (gmap K A)); apply _. Qed.\n\nGlobal Instance lookup_ne k : NonExpansive (lookup k : gmap K A → option A).\nProof. by intros n m1 m2. Qed.\nGlobal Instance lookup_total_ne `{!Inhabited A} k :\n  NonExpansive (lookup_total k : gmap K A → A).\nProof. intros n m1 m2. rewrite !lookup_total_alt. by intros ->. Qed.\nGlobal Instance partial_alter_ne n :\n  Proper ((dist n ==> dist n) ==> (=) ==> dist n ==> dist n)\n         (partial_alter (M:=gmap K A)).\nProof.\n  by intros f1 f2 Hf i ? <- m1 m2 Hm j; destruct (decide (i = j)) as [->|];\n    rewrite ?lookup_partial_alter ?lookup_partial_alter_ne //;\n    try apply Hf; apply lookup_ne.\nQed.\nGlobal Instance insert_ne i : NonExpansive2 (insert (M:=gmap K A) i).\nProof. intros n x y ? m m' ? j; apply partial_alter_ne; by try constructor. Qed.\nGlobal Instance singleton_ne i : NonExpansive (singletonM i : A → gmap K A).\nProof. by intros ????; apply insert_ne. Qed.\nGlobal Instance delete_ne i : NonExpansive (delete (M:=gmap K A) i).\nProof.\n  intros n m m' ? j; destruct (decide (i = j)); simplify_map_eq;\n    [by constructor|by apply lookup_ne].\nQed.\nGlobal Instance alter_ne (f : A → A) (k : K) n :\n  Proper (dist n ==> dist n) f → Proper (dist n ==> dist n) (alter f k).\nProof. intros ? m m' Hm k'. by apply partial_alter_ne; [solve_proper|..]. Qed.\n\nGlobal Instance gmap_empty_discrete : Discrete (∅ : gmap K A).\nProof.\n  intros m Hm i; specialize (Hm i); rewrite lookup_empty in Hm |- *.\n  inversion_clear Hm; constructor.\nQed.\nGlobal Instance gmap_lookup_discrete m i : Discrete m → Discrete (m !! i).\nProof.\n  intros ? [x|] Hx; [|by symmetry; apply: discrete].\n  assert (m ≡{0}≡ <[i:=x]> m)\n    by (by symmetry in Hx; inversion Hx; ofe_subst; rewrite insert_id).\n  by rewrite (discrete m (<[i:=x]>m)) // lookup_insert.\nQed.\nGlobal Instance gmap_insert_discrete m i x :\n  Discrete x → Discrete m → Discrete (<[i:=x]>m).\nProof.\n  intros ?? m' Hm j; destruct (decide (i = j)); simplify_map_eq.\n  { by apply: discrete; rewrite -Hm lookup_insert. }\n  by apply: discrete; rewrite -Hm lookup_insert_ne.\nQed.\nGlobal Instance gmap_singleton_discrete i x :\n  Discrete x → Discrete ({[ i := x ]} : gmap K A) := _.\nLemma insert_idN n m i x :\n  m !! i ≡{n}≡ Some x → <[i:=x]>m ≡{n}≡ m.\nProof. intros (y'&?&->)%dist_Some_inv_r'. by rewrite insert_id. Qed.\n\n(** Internalized properties *)\nLemma gmap_equivI {M} m1 m2 : m1 ≡ m2 ⊣⊢@{uPredI M} ∀ i, m1 !! i ≡ m2 !! i.\nProof. by uPred.unseal. Qed.\nEnd cofe.\n\nArguments gmapO _ {_ _} _.\n\n(** Non-expansiveness of higher-order map functions and big-ops *)\nLemma merge_ne `{Countable K} {A B C : ofeT} (f g : option A → option B → option C)\n    `{!DiagNone f, !DiagNone g} n :\n  ((dist n) ==> (dist n) ==> (dist n))%signature f g →\n  ((dist n) ==> (dist n) ==> (dist n))%signature (merge (M:=gmap K) f) (merge g).\nProof. by intros Hf ?? Hm1 ?? Hm2 i; rewrite !lookup_merge //; apply Hf. Qed.\nInstance union_with_proper `{Countable K} {A : ofeT} n :\n  Proper (((dist n) ==> (dist n) ==> (dist n)) ==>\n          (dist n) ==> (dist n) ==>(dist n)) (union_with (M:=gmap K A)).\nProof.\n  intros ?? Hf ?? Hm1 ?? Hm2 i; apply (merge_ne _ _); auto.\n  by do 2 destruct 1; first [apply Hf | constructor].\nQed.\nInstance map_fmap_proper `{Countable K} {A B : ofeT} (f : A → B) n :\n  Proper (dist n ==> dist n) f → Proper (dist n ==> dist n) (fmap (M:=gmap K) f).\nProof. intros ? m m' ? k; rewrite !lookup_fmap. by repeat f_equiv. Qed.\nInstance map_zip_with_proper `{Countable K} {A B C : ofeT} (f : A → B → C) n :\n  Proper (dist n ==> dist n ==> dist n) f →\n  Proper (dist n ==> dist n ==> dist n) (map_zip_with (M:=gmap K) f).\nProof.\n  intros Hf m1 m1' Hm1 m2 m2' Hm2. apply merge_ne; try done.\n  destruct 1; destruct 1; repeat f_equiv; constructor || done.\nQed.\n\nLemma big_opM_ne_2 `{Monoid M o} `{Countable K} {A : ofeT} (f g : K → A → M) m1 m2 n :\n  m1 ≡{n}≡ m2 →\n  (∀ k y1 y2,\n    m1 !! k = Some y1 → m2 !! k = Some y2 → y1 ≡{n}≡ y2 → f k y1 ≡{n}≡ g k y2) →\n  ([^o map] k ↦ y ∈ m1, f k y) ≡{n}≡ ([^o map] k ↦ y ∈ m2, g k y).\nProof.\n  intros Hl Hf. apply big_opM_gen_proper_2; try (apply _ || done).\n  { by intros ?? ->. }\n  { apply monoid_ne. }\n  intros k. assert (m1 !! k ≡{n}≡ m2 !! k) as Hlk by (by f_equiv).\n  destruct (m1 !! k) eqn:?, (m2 !! k) eqn:?; inversion Hlk; naive_solver.\nQed.\n\nLemma big_sepM2_ne_2 {PROP : bi} `{Countable K} (A B : ofeT)\n    (Φ Ψ : K → A → B → PROP) m1 m2 m1' m2' n :\n  m1 ≡{n}≡ m1' → m2 ≡{n}≡ m2' →\n  (∀ k y1 y1' y2 y2',\n    m1 !! k = Some y1 → m1' !! k = Some y1' → y1 ≡{n}≡ y1' →\n    m2 !! k = Some y2 → m2' !! k = Some y2' → y2 ≡{n}≡ y2' →\n    Φ k y1 y2 ≡{n}≡ Ψ k y1' y2') →\n  ([∗ map] k ↦ y1;y2 ∈ m1;m2, Φ k y1 y2)%I ≡{n}≡ ([∗ map] k ↦ y1;y2 ∈ m1';m2', Ψ k y1 y2)%I.\nProof.\n  intros Hm1 Hm2 Hf. rewrite big_sepM2_eq /big_sepM2_def. f_equiv.\n  { f_equiv; split; intros Hm k.\n    - trans (is_Some (m1 !! k)); [symmetry; apply: is_Some_ne; by f_equiv|].\n      rewrite Hm. apply: is_Some_ne; by f_equiv.\n    - trans (is_Some (m1' !! k)); [apply: is_Some_ne; by f_equiv|].\n      rewrite Hm. symmetry. apply: is_Some_ne; by f_equiv. }\n  apply big_opM_ne_2; [by f_equiv|].\n  intros k [x1 y1] [x2 y2] (?&?&[=<- <-]&?&?)%map_lookup_zip_with_Some\n    (?&?&[=<- <-]&?&?)%map_lookup_zip_with_Some [??]; naive_solver.\nQed.\n\n(* CMRA *)\nSection cmra.\nContext `{Countable K} {A : cmraT}.\nImplicit Types m : gmap K A.\n\nInstance gmap_unit : Unit (gmap K A) := (∅ : gmap K A).\nInstance gmap_op : Op (gmap K A) := merge op.\nInstance gmap_pcore : PCore (gmap K A) := λ m, Some (omap pcore m).\nInstance gmap_valid : Valid (gmap K A) := λ m, ∀ i, ✓ (m !! i).\nInstance gmap_validN : ValidN (gmap K A) := λ n m, ∀ i, ✓{n} (m !! i).\n\nLemma lookup_op m1 m2 i : (m1 ⋅ m2) !! i = m1 !! i ⋅ m2 !! i.\nProof. by apply lookup_merge. Qed.\nLemma lookup_core m i : core m !! i = core (m !! i).\nProof. by apply lookup_omap. Qed.\n\nLemma lookup_includedN n (m1 m2 : gmap K A) : m1 ≼{n} m2 ↔ ∀ i, m1 !! i ≼{n} m2 !! i.\nProof.\n  split; [by intros [m Hm] i; exists (m !! i); rewrite -lookup_op Hm|].\n  revert m2. induction m1 as [|i x m Hi IH] using map_ind=> m2 Hm.\n  { exists m2. by rewrite left_id. }\n  destruct (IH (delete i m2)) as [m2' Hm2'].\n  { intros j. move: (Hm j); destruct (decide (i = j)) as [->|].\n    - intros _. rewrite Hi. apply: ucmra_unit_leastN.\n    - rewrite lookup_insert_ne // lookup_delete_ne //. }\n  destruct (Hm i) as [my Hi']; simplify_map_eq.\n  exists (partial_alter (λ _, my) i m2')=>j; destruct (decide (i = j)) as [->|].\n  - by rewrite Hi' lookup_op lookup_insert lookup_partial_alter.\n  - move: (Hm2' j). by rewrite !lookup_op lookup_delete_ne //\n      lookup_insert_ne // lookup_partial_alter_ne.\nQed.\n\n(* [m1 ≼ m2] is not equivalent to [∀ n, m1 ≼{n} m2],\nso there is no good way to reuse the above proof. *)\nLemma lookup_included (m1 m2 : gmap K A) : m1 ≼ m2 ↔ ∀ i, m1 !! i ≼ m2 !! i.\nProof.\n  split; [by intros [m Hm] i; exists (m !! i); rewrite -lookup_op Hm|].\n  revert m2. induction m1 as [|i x m Hi IH] using map_ind=> m2 Hm.\n  { exists m2. by rewrite left_id. }\n  destruct (IH (delete i m2)) as [m2' Hm2'].\n  { intros j. move: (Hm j); destruct (decide (i = j)) as [->|].\n    - intros _. rewrite Hi. apply: ucmra_unit_least.\n    - rewrite lookup_insert_ne // lookup_delete_ne //. }\n  destruct (Hm i) as [my Hi']; simplify_map_eq.\n  exists (partial_alter (λ _, my) i m2')=>j; destruct (decide (i = j)) as [->|].\n  - by rewrite Hi' lookup_op lookup_insert lookup_partial_alter.\n  - move: (Hm2' j). by rewrite !lookup_op lookup_delete_ne //\n      lookup_insert_ne // lookup_partial_alter_ne.\nQed.\n\nLemma gmap_cmra_mixin : CmraMixin (gmap K A).\nProof.\n  apply cmra_total_mixin.\n  - eauto.\n  - intros n m1 m2 m3 Hm i; by rewrite !lookup_op (Hm i).\n  - intros n m1 m2 Hm i; by rewrite !lookup_core (Hm i).\n  - intros n m1 m2 Hm ? i; by rewrite -(Hm i).\n  - intros m; split.\n    + by intros ? n i; apply cmra_valid_validN.\n    + intros Hm i; apply cmra_valid_validN=> n; apply Hm.\n  - intros n m Hm i; apply cmra_validN_S, Hm.\n  - by intros m1 m2 m3 i; rewrite !lookup_op assoc.\n  - by intros m1 m2 i; rewrite !lookup_op comm.\n  - intros m i. by rewrite lookup_op lookup_core cmra_core_l.\n  - intros m i. by rewrite !lookup_core cmra_core_idemp.\n  - intros m1 m2; rewrite !lookup_included=> Hm i.\n    rewrite !lookup_core. by apply cmra_core_mono.\n  - intros n m1 m2 Hm i; apply cmra_validN_op_l with (m2 !! i).\n    by rewrite -lookup_op.\n  - intros n m y1 y2 Hm Heq.\n    refine ((λ FUN, _) (λ i, cmra_extend n (m !! i) (y1 !! i) (y2 !! i) (Hm i) _));\n      last by rewrite -lookup_op.\n    exists (map_imap (λ i _, projT1 (FUN i)) y1).\n    exists (map_imap (λ i _, proj1_sig (projT2 (FUN i))) y2).\n    split; [|split]=>i; rewrite ?lookup_op !map_lookup_imap;\n    destruct (FUN i) as (z1i&z2i&Hmi&Hz1i&Hz2i)=>/=.\n    + destruct (y1 !! i), (y2 !! i); inversion Hz1i; inversion Hz2i; subst=>//.\n    + revert Hz1i. case: (y1!!i)=>[?|] //.\n    + revert Hz2i. case: (y2!!i)=>[?|] //.\nQed.\nCanonical Structure gmapR := CmraT (gmap K A) gmap_cmra_mixin.\n\nGlobal Instance gmap_cmra_discrete : CmraDiscrete A → CmraDiscrete gmapR.\nProof. split; [apply _|]. intros m ? i. by apply: cmra_discrete_valid. Qed.\n\nLemma gmap_ucmra_mixin : UcmraMixin (gmap K A).\nProof.\n  split.\n  - by intros i; rewrite lookup_empty.\n  - by intros m i; rewrite /= lookup_op lookup_empty (left_id_L None _).\n  - constructor=> i. by rewrite lookup_omap lookup_empty.\nQed.\nCanonical Structure gmapUR := UcmraT (gmap K A) gmap_ucmra_mixin.\n\n(** Internalized properties *)\nLemma gmap_validI {M} m : ✓ m ⊣⊢@{uPredI M} ∀ i, ✓ (m !! i).\nProof. by uPred.unseal. Qed.\nLemma singleton_validI {M} i x : ✓ {[ i := x ]} ⊣⊢@{uPredI M} ✓ x.\nProof.\n  rewrite gmap_validI. apply: anti_symm.\n  - rewrite (bi.forall_elim i) lookup_singleton uPred.option_validI. done.\n  - apply bi.forall_intro=>j. destruct (decide (i = j)) as [<-|Hne].\n    + rewrite lookup_singleton uPred.option_validI. done.\n    + rewrite lookup_singleton_ne // uPred.option_validI.\n      apply bi.True_intro.\nQed.\nEnd cmra.\n\nArguments gmapR _ {_ _} _.\nArguments gmapUR _ {_ _} _.\n\nSection properties.\nContext `{Countable K} {A : cmraT}.\nImplicit Types m : gmap K A.\nImplicit Types i : K.\nImplicit Types x y : A.\n\nGlobal Instance lookup_op_homomorphism {i} :\n  MonoidHomomorphism op op (≡) (lookup i : gmap K A → option A).\nProof. split; [split|]; try apply _. intros m1 m2; by rewrite lookup_op. done. Qed.\n\nLemma lookup_opM m1 mm2 i : (m1 ⋅? mm2) !! i = m1 !! i ⋅ (mm2 ≫= (.!! i)).\nProof. destruct mm2; by rewrite /= ?lookup_op ?right_id_L. Qed.\n\nLemma lookup_validN_Some n m i x : ✓{n} m → m !! i ≡{n}≡ Some x → ✓{n} x.\nProof. by move=> /(_ i) Hm Hi; move:Hm; rewrite Hi. Qed.\nLemma lookup_valid_Some m i x : ✓ m → m !! i ≡ Some x → ✓ x.\nProof. move=> Hm Hi. move:(Hm i). by rewrite Hi. Qed.\n\nLemma insert_validN n m i x : ✓{n} x → ✓{n} m → ✓{n} <[i:=x]>m.\nProof. by intros ?? j; destruct (decide (i = j)); simplify_map_eq. Qed.\nLemma insert_valid m i x : ✓ x → ✓ m → ✓ <[i:=x]>m.\nProof. by intros ?? j; destruct (decide (i = j)); simplify_map_eq. Qed.\nLemma singleton_validN n i x : ✓{n} ({[ i := x ]} : gmap K A) ↔ ✓{n} x.\nProof.\n  split.\n  - move=>/(_ i); by simplify_map_eq.\n  - intros. apply insert_validN. done. apply: ucmra_unit_validN.\nQed.\nLemma singleton_valid i x : ✓ ({[ i := x ]} : gmap K A) ↔ ✓ x.\nProof. rewrite !cmra_valid_validN. by setoid_rewrite singleton_validN. Qed.\n\nLemma delete_validN n m i : ✓{n} m → ✓{n} (delete i m).\nProof. intros Hm j; destruct (decide (i = j)); by simplify_map_eq. Qed.\nLemma delete_valid m i : ✓ m → ✓ (delete i m).\nProof. intros Hm j; destruct (decide (i = j)); by simplify_map_eq. Qed.\n\nLemma insert_singleton_op m i x : m !! i = None → <[i:=x]> m = {[ i := x ]} ⋅ m.\nProof.\n  intros Hi; apply map_eq=> j; destruct (decide (i = j)) as [->|].\n  - by rewrite lookup_op lookup_insert lookup_singleton Hi right_id_L.\n  - by rewrite lookup_op lookup_insert_ne // lookup_singleton_ne // left_id_L.\nQed.\n\nLemma singleton_core (i : K) (x : A) cx :\n  pcore x = Some cx → core {[ i := x ]} =@{gmap K A} {[ i := cx ]}.\nProof. apply omap_singleton. Qed.\nLemma singleton_core' (i : K) (x : A) cx :\n  pcore x ≡ Some cx → core {[ i := x ]} ≡@{gmap K A} {[ i := cx ]}.\nProof.\n  intros (cx'&?&->)%equiv_Some_inv_r'. by rewrite (singleton_core _ _ cx').\nQed.\nLemma singleton_core_total `{!CmraTotal A} (i : K) (x : A) :\n  core {[ i := x ]} =@{gmap K A} {[ i := core x ]}.\nProof. apply singleton_core. rewrite cmra_pcore_core //. Qed.\nLemma singleton_op (i : K) (x y : A) :\n  {[ i := x ]} ⋅ {[ i := y ]} =@{gmap K A} {[ i := x ⋅ y ]}.\nProof. by apply (merge_singleton _ _ _ x y). Qed.\nGlobal Instance singleton_is_op i a a1 a2 :\n  IsOp a a1 a2 → IsOp' ({[ i := a ]} : gmap K A) {[ i := a1 ]} {[ i := a2 ]}.\nProof. rewrite /IsOp' /IsOp=> ->. by rewrite -singleton_op. Qed.\n\nGlobal Instance gmap_core_id m : (∀ x : A, CoreId x) → CoreId m.\nProof.\n  intros; apply core_id_total=> i.\n  rewrite lookup_core. apply (core_id_core _).\nQed.\nGlobal Instance gmap_singleton_core_id i (x : A) :\n  CoreId x → CoreId {[ i := x ]}.\nProof. intros. by apply core_id_total, singleton_core'. Qed.\n\nLemma singleton_includedN_l n m i x :\n  {[ i := x ]} ≼{n} m ↔ ∃ y, m !! i ≡{n}≡ Some y ∧ Some x ≼{n} Some y.\nProof.\n  split.\n  - move=> [m' /(_ i)]; rewrite lookup_op lookup_singleton=> Hi.\n    exists (x ⋅? m' !! i). rewrite -Some_op_opM.\n    split. done. apply cmra_includedN_l.\n  - intros (y&Hi&[mz Hy]). exists (partial_alter (λ _, mz) i m).\n    intros j; destruct (decide (i = j)) as [->|].\n    + by rewrite lookup_op lookup_singleton lookup_partial_alter Hi.\n    + by rewrite lookup_op lookup_singleton_ne// lookup_partial_alter_ne// left_id.\nQed.\n(* We do not have [x ≼ y ↔ ∀ n, x ≼{n} y], so we cannot use the previous lemma *)\nLemma singleton_included_l m i x :\n  {[ i := x ]} ≼ m ↔ ∃ y, m !! i ≡ Some y ∧ Some x ≼ Some y.\nProof.\n  split.\n  - move=> [m' /(_ i)]; rewrite lookup_op lookup_singleton.\n    exists (x ⋅? m' !! i). rewrite -Some_op_opM.\n    split. done. apply cmra_included_l.\n  - intros (y&Hi&[mz Hy]). exists (partial_alter (λ _, mz) i m).\n    intros j; destruct (decide (i = j)) as [->|].\n    + by rewrite lookup_op lookup_singleton lookup_partial_alter Hi.\n    + by rewrite lookup_op lookup_singleton_ne// lookup_partial_alter_ne// left_id.\nQed.\nLemma singleton_included_exclusive_l m i x :\n  Exclusive x → ✓ m →\n  {[ i := x ]} ≼ m ↔ m !! i ≡ Some x.\nProof.\n  intros ? Hm. rewrite singleton_included_l. split; last by eauto.\n  intros (y&?&->%(Some_included_exclusive _)); eauto using lookup_valid_Some.\nQed.\nLemma singleton_included i x y :\n  {[ i := x ]} ≼ ({[ i := y ]} : gmap K A) ↔ x ≡ y ∨ x ≼ y.\nProof.\n  rewrite singleton_included_l. split.\n  - intros (y'&Hi&?). rewrite lookup_insert in Hi.\n    apply Some_included. by rewrite Hi.\n  - intros ?. exists y. by rewrite lookup_insert Some_included.\nQed.\n\nGlobal Instance singleton_cancelable i x :\n  Cancelable (Some x) → Cancelable {[ i := x ]}.\nProof.\n  intros ? n m1 m2 Hv EQ j. move: (Hv j) (EQ j). rewrite !lookup_op.\n  destruct (decide (i = j)) as [->|].\n  - rewrite lookup_singleton. by apply cancelableN.\n  - by rewrite lookup_singleton_ne // !(left_id None _).\nQed.\n\nGlobal Instance gmap_cancelable (m : gmap K A) :\n  (∀ x : A, IdFree x) → (∀ x : A, Cancelable x) → Cancelable m.\nProof.\n  intros ?? n m1 m2 ?? i. apply (cancelableN (m !! i)); by rewrite -!lookup_op.\nQed.\n\nLemma insert_op m1 m2 i x y :\n  <[i:=x ⋅ y]>(m1 ⋅ m2) =  <[i:=x]>m1 ⋅ <[i:=y]>m2.\nProof. by rewrite (insert_merge (⋅) m1 m2 i (x ⋅ y) x y). Qed.\n\nLemma insert_updateP (P : A → Prop) (Q : gmap K A → Prop) m i x :\n  x ~~>: P →\n  (∀ y, P y → Q (<[i:=y]>m)) →\n  <[i:=x]>m ~~>: Q.\nProof.\n  intros Hx%option_updateP' HP; apply cmra_total_updateP=> n mf Hm.\n  destruct (Hx n (Some (mf !! i))) as ([y|]&?&?); try done.\n  { by generalize (Hm i); rewrite lookup_op; simplify_map_eq. }\n  exists (<[i:=y]> m); split; first by auto.\n  intros j; move: (Hm j)=>{Hm}; rewrite !lookup_op=>Hm.\n  destruct (decide (i = j)); simplify_map_eq/=; auto.\nQed.\nLemma insert_updateP' (P : A → Prop) m i x :\n  x ~~>: P → <[i:=x]>m ~~>: λ m', ∃ y, m' = <[i:=y]>m ∧ P y.\nProof. eauto using insert_updateP. Qed.\nLemma insert_update m i x y : x ~~> y → <[i:=x]>m ~~> <[i:=y]>m.\nProof. rewrite !cmra_update_updateP; eauto using insert_updateP with subst. Qed.\n\nLemma singleton_updateP (P : A → Prop) (Q : gmap K A → Prop) i x :\n  x ~~>: P → (∀ y, P y → Q {[ i := y ]}) → {[ i := x ]} ~~>: Q.\nProof. apply insert_updateP. Qed.\nLemma singleton_updateP' (P : A → Prop) i x :\n  x ~~>: P → {[ i := x ]} ~~>: λ m, ∃ y, m = {[ i := y ]} ∧ P y.\nProof. apply insert_updateP'. Qed.\nLemma singleton_update i (x y : A) : x ~~> y → {[ i := x ]} ~~> {[ i := y ]}.\nProof. apply insert_update. Qed.\n\nLemma delete_update m i : m ~~> delete i m.\nProof.\n  apply cmra_total_update=> n mf Hm j; destruct (decide (i = j)); subst.\n  - move: (Hm j). rewrite !lookup_op lookup_delete left_id.\n    apply cmra_validN_op_r.\n  - move: (Hm j). by rewrite !lookup_op lookup_delete_ne.\nQed.\n\nLemma dom_op m1 m2 : dom (gset K) (m1 ⋅ m2) = dom _ m1 ∪ dom _ m2.\nProof.\n  apply elem_of_equiv_L=> i; rewrite elem_of_union !elem_of_dom.\n  unfold is_Some; setoid_rewrite lookup_op.\n  destruct (m1 !! i), (m2 !! i); naive_solver.\nQed.\nLemma dom_included m1 m2 : m1 ≼ m2 → dom (gset K) m1 ⊆ dom _ m2.\nProof.\n  rewrite lookup_included=>? i; rewrite !elem_of_dom. by apply is_Some_included.\nQed.\n\nSection freshness.\n  Local Set Default Proof Using \"Type*\".\n  Context `{!Infinite K}.\n  Lemma alloc_updateP_strong_dep (Q : gmap K A → Prop) (I : K → Prop) m (f : K → A) :\n    pred_infinite I →\n    (∀ i, m !! i = None → I i → ✓ (f i)) →\n    (∀ i, m !! i = None → I i → Q (<[i:=f i]>m)) → m ~~>: Q.\n  Proof.\n    move=> /(pred_infinite_set I (C:=gset K)) HP ? HQ.\n    apply cmra_total_updateP. intros n mf Hm.\n    destruct (HP (dom (gset K) (m ⋅ mf))) as [i [Hi1 Hi2]].\n    assert (m !! i = None).\n    { eapply (not_elem_of_dom (D:=gset K)). revert Hi2.\n      rewrite dom_op not_elem_of_union. naive_solver. }\n    exists (<[i:=f i]>m); split.\n    - by apply HQ.\n    - rewrite insert_singleton_op //.\n      rewrite -assoc -insert_singleton_op;\n        last by eapply (not_elem_of_dom (D:=gset K)).\n    apply insert_validN; [apply cmra_valid_validN|]; auto.\n  Qed.\n  Lemma alloc_updateP_strong (Q : gmap K A → Prop) (I : K → Prop) m x :\n    pred_infinite I →\n    ✓ x → (∀ i, m !! i = None → I i → Q (<[i:=x]>m)) → m ~~>: Q.\n  Proof.\n    move=> HP ? HQ. eapply alloc_updateP_strong_dep with (f := λ _, x); eauto.\n  Qed.\n  Lemma alloc_updateP (Q : gmap K A → Prop) m x :\n    ✓ x → (∀ i, m !! i = None → Q (<[i:=x]>m)) → m ~~>: Q.\n  Proof.\n    move=>??.\n    eapply alloc_updateP_strong with (I:=λ _, True);\n    eauto using pred_infinite_True.\n  Qed.\n  Lemma alloc_updateP_cofinite (Q : gmap K A → Prop) (J : gset K) m x :\n    ✓ x → (∀ i, m !! i = None → i ∉ J → Q (<[i:=x]>m)) → m ~~>: Q.\n  Proof.\n    eapply alloc_updateP_strong.\n    apply (pred_infinite_set (C:=gset K)).\n    intros E. exists (fresh (J ∪ E)).\n    apply not_elem_of_union, is_fresh.\n  Qed.\n\n  (* Variants without the universally quantified Q, for use in case that is an evar. *)\n  Lemma alloc_updateP_strong_dep' m (f : K → A) (I : K → Prop) :\n    pred_infinite I →\n    (∀ i, m !! i = None → I i → ✓ (f i)) →\n    m ~~>: λ m', ∃ i, I i ∧ m' = <[i:=f i]>m ∧ m !! i = None.\n  Proof. eauto using alloc_updateP_strong_dep. Qed.\n  Lemma alloc_updateP_strong' m x (I : K → Prop) :\n    pred_infinite I →\n    ✓ x → m ~~>: λ m', ∃ i, I i ∧ m' = <[i:=x]>m ∧ m !! i = None.\n  Proof. eauto using alloc_updateP_strong. Qed.\n  Lemma alloc_updateP' m x :\n    ✓ x → m ~~>: λ m', ∃ i, m' = <[i:=x]>m ∧ m !! i = None.\n  Proof. eauto using alloc_updateP. Qed.\n  Lemma alloc_updateP_cofinite' m x (J : gset K) :\n    ✓ x → m ~~>: λ m', ∃ i, i ∉ J ∧ m' = <[i:=x]>m ∧ m !! i = None.\n  Proof. eauto using alloc_updateP_cofinite. Qed.\nEnd freshness.\n\nLemma alloc_unit_singleton_updateP (P : A → Prop) (Q : gmap K A → Prop) u i :\n  ✓ u → LeftId (≡) u (⋅) →\n  u ~~>: P → (∀ y, P y → Q {[ i := y ]}) → ∅ ~~>: Q.\nProof.\n  intros ?? Hx HQ. apply cmra_total_updateP=> n gf Hg.\n  destruct (Hx n (gf !! i)) as (y&?&Hy).\n  { move:(Hg i). rewrite !left_id.\n    case: (gf !! i)=>[x|]; rewrite /= ?left_id //.\n    intros; by apply cmra_valid_validN. }\n  exists {[ i := y ]}; split; first by auto.\n  intros i'; destruct (decide (i' = i)) as [->|].\n  - rewrite lookup_op lookup_singleton.\n    move:Hy; case: (gf !! i)=>[x|]; rewrite /= ?right_id //.\n  - move:(Hg i'). by rewrite !lookup_op lookup_singleton_ne // !left_id.\nQed.\nLemma alloc_unit_singleton_updateP' (P: A → Prop) u i :\n  ✓ u → LeftId (≡) u (⋅) →\n  u ~~>: P → ∅ ~~>: λ m, ∃ y, m = {[ i := y ]} ∧ P y.\nProof. eauto using alloc_unit_singleton_updateP. Qed.\nLemma alloc_unit_singleton_update (u : A) i (y : A) :\n  ✓ u → LeftId (≡) u (⋅) → u ~~> y → (∅:gmap K A) ~~> {[ i := y ]}.\nProof.\n  rewrite !cmra_update_updateP;\n    eauto using alloc_unit_singleton_updateP with subst.\nQed.\n\nLemma alloc_local_update m1 m2 i x :\n  m1 !! i = None → ✓ x → (m1,m2) ~l~> (<[i:=x]>m1, <[i:=x]>m2).\nProof.\n  rewrite cmra_valid_validN=> Hi ?.\n  apply local_update_unital=> n mf Hmv Hm; simpl in *.\n  split; auto using insert_validN.\n  intros j; destruct (decide (i = j)) as [->|].\n  - move: (Hm j); rewrite Hi symmetry_iff dist_None lookup_op op_None=>-[_ Hj].\n    by rewrite lookup_op !lookup_insert Hj.\n  - rewrite Hm lookup_insert_ne // !lookup_op lookup_insert_ne //.\nQed.\n\nLemma alloc_singleton_local_update m i x :\n  m !! i = None → ✓ x → (m,∅) ~l~> (<[i:=x]>m, {[ i:=x ]}).\nProof. apply alloc_local_update. Qed.\n\nLemma insert_local_update m1 m2 i x y x' y' :\n  m1 !! i = Some x → m2 !! i = Some y →\n  (x, y) ~l~> (x', y') →\n  (m1, m2) ~l~> (<[i:=x']>m1, <[i:=y']>m2).\nProof.\n  intros Hi1 Hi2 Hup; apply local_update_unital=> n mf Hmv Hm; simpl in *.\n  destruct (Hup n (mf !! i)) as [? Hx']; simpl in *.\n  { move: (Hmv i). by rewrite Hi1. }\n  { move: (Hm i). by rewrite lookup_op Hi1 Hi2 Some_op_opM (inj_iff Some). }\n  split; auto using insert_validN.\n  rewrite Hm Hx'=> j; destruct (decide (i = j)) as [->|].\n  - by rewrite lookup_insert lookup_op lookup_insert Some_op_opM.\n  - by rewrite lookup_insert_ne // !lookup_op lookup_insert_ne.\nQed.\n\nLemma singleton_local_update_any m i y x' y' :\n  (∀ x, m !! i = Some x → (x, y) ~l~> (x', y')) →\n  (m, {[ i := y ]}) ~l~> (<[i:=x']>m, {[ i := y' ]}).\nProof.\n  intros. rewrite /singletonM /map_singleton -(insert_insert ∅ i y' y).\n  apply local_update_total_valid0=>_ _ /singleton_includedN_l [x0 [/dist_Some_inv_r Hlk0 _]].\n  edestruct Hlk0 as [x [Hlk _]]; [done..|].\n  eapply insert_local_update; [|eapply lookup_insert|]; eauto.\nQed.\n\nLemma singleton_local_update m i x y x' y' :\n  m !! i = Some x →\n  (x, y) ~l~> (x', y') →\n  (m, {[ i := y ]}) ~l~> (<[i:=x']>m, {[ i := y' ]}).\nProof.\n  intros Hmi ?. apply singleton_local_update_any.\n  intros x2. rewrite Hmi=>[=<-]. done.\nQed.\n\nLemma delete_local_update m1 m2 i x `{!Exclusive x} :\n  m2 !! i = Some x → (m1, m2) ~l~> (delete i m1, delete i m2).\nProof.\n  intros Hi. apply local_update_unital=> n mf Hmv Hm; simpl in *.\n  split; auto using delete_validN.\n  rewrite Hm=> j; destruct (decide (i = j)) as [<-|].\n  - rewrite lookup_op !lookup_delete left_id symmetry_iff dist_None.\n    apply eq_None_not_Some=> -[y Hi'].\n    move: (Hmv i). rewrite Hm lookup_op Hi Hi' -Some_op. by apply exclusiveN_l.\n  - by rewrite lookup_op !lookup_delete_ne // lookup_op.\nQed.\n\nLemma delete_singleton_local_update m i x `{!Exclusive x} :\n  (m, {[ i := x ]}) ~l~> (delete i m, ∅).\nProof.\n  rewrite -(delete_singleton i x).\n  by eapply delete_local_update, lookup_singleton.\nQed.\n\nLemma delete_local_update_cancelable m1 m2 i mx `{!Cancelable mx} :\n  m1 !! i ≡ mx → m2 !! i ≡ mx →\n  (m1, m2) ~l~> (delete i m1, delete i m2).\nProof.\n  intros Hm1i Hm2i. apply local_update_unital=> n mf Hmv Hm; simpl in *.\n  split; [eauto using delete_validN|].\n  intros j. destruct (decide (i = j)) as [->|].\n  - move: (Hm j). rewrite !lookup_op Hm1i Hm2i !lookup_delete. intros Hmx.\n    rewrite (cancelableN mx n (mf !! j) None) ?right_id // -Hmx -Hm1i. apply Hmv.\n  - by rewrite lookup_op !lookup_delete_ne // Hm lookup_op.\nQed.\n\nLemma delete_singleton_local_update_cancelable m i x `{!Cancelable (Some x)} :\n  m !! i ≡ Some x → (m, {[ i := x ]}) ~l~> (delete i m, ∅).\nProof.\n  intros. rewrite -(delete_singleton i x).\n  apply (delete_local_update_cancelable m _ i (Some x));\n    [done|by rewrite lookup_singleton].\nQed.\n\nLemma gmap_fmap_mono {B : cmraT} (f : A → B) m1 m2 :\n  Proper ((≡) ==> (≡)) f →\n  (∀ x y, x ≼ y → f x ≼ f y) → m1 ≼ m2 → fmap f m1 ≼ fmap f m2.\nProof.\n  intros ??. rewrite !lookup_included=> Hm i.\n  rewrite !lookup_fmap. by apply option_fmap_mono.\nQed.\nEnd properties.\n\nSection unital_properties.\nContext `{Countable K} {A : ucmraT}.\nImplicit Types m : gmap K A.\nImplicit Types i : K.\nImplicit Types x y : A.\n\nLemma insert_alloc_local_update m1 m2 i x x' y' :\n  m1 !! i = Some x → m2 !! i = None →\n  (x, ε) ~l~> (x', y') →\n  (m1, m2) ~l~> (<[i:=x']>m1, <[i:=y']>m2).\nProof.\n  intros Hi1 Hi2 Hup. apply local_update_unital=> n mf Hm1v Hm.\n  assert (mf !! i ≡{n}≡ Some x) as Hif.\n  { move: (Hm i). by rewrite lookup_op Hi1 Hi2 left_id. }\n  destruct (Hup n (mf !! i)) as [Hx'v Hx'eq].\n  { move: (Hm1v i). by rewrite Hi1. }\n  { by rewrite Hif -(inj_iff Some) -Some_op_opM -Some_op left_id. }\n  split.\n  - by apply insert_validN.\n  - simpl in Hx'eq. by rewrite -(insert_idN n mf i x) // -insert_op -Hm Hx'eq Hif.\nQed.\nEnd unital_properties.\n\n(** Functor *)\nInstance gmap_fmap_ne `{Countable K} {A B : ofeT} (f : A → B) n :\n  Proper (dist n ==> dist n) f → Proper (dist n ==>dist n) (fmap (M:=gmap K) f).\nProof. by intros ? m m' Hm k; rewrite !lookup_fmap; apply option_fmap_ne. Qed.\nInstance gmap_fmap_cmra_morphism `{Countable K} {A B : cmraT} (f : A → B)\n  `{!CmraMorphism f} : CmraMorphism (fmap f : gmap K A → gmap K B).\nProof.\n  split; try apply _.\n  - by intros n m ? i; rewrite lookup_fmap; apply (cmra_morphism_validN _).\n  - intros m. apply Some_proper=>i. rewrite lookup_fmap !lookup_omap lookup_fmap.\n    case: (m!!i)=>//= ?. apply cmra_morphism_pcore, _.\n  - intros m1 m2 i. by rewrite lookup_op !lookup_fmap lookup_op cmra_morphism_op.\nQed.\nDefinition gmapO_map `{Countable K} {A B} (f: A -n> B) :\n  gmapO K A -n> gmapO K B := OfeMor (fmap f : gmapO K A → gmapO K B).\nInstance gmapO_map_ne `{Countable K} {A B} :\n  NonExpansive (@gmapO_map K _ _ A B).\nProof.\n  intros n f g Hf m k; rewrite /= !lookup_fmap.\n  destruct (_ !! k) eqn:?; simpl; constructor; apply Hf.\nQed.\n\nProgram Definition gmapOF K `{Countable K} (F : oFunctor) : oFunctor := {|\n  oFunctor_car A _ B _ := gmapO K (oFunctor_car F A B);\n  oFunctor_map A1 _ A2 _ B1 _ B2 _ fg := gmapO_map (oFunctor_map F fg)\n|}.\nNext Obligation.\n  by intros K ?? F A1 ? A2 ? B1 ? B2 ? n f g Hfg; apply gmapO_map_ne, oFunctor_map_ne.\nQed.\nNext Obligation.\n  intros K ?? F A ? B ? x. rewrite /= -{2}(map_fmap_id x).\n  apply map_fmap_equiv_ext=>y ??; apply oFunctor_map_id.\nQed.\nNext Obligation.\n  intros K ?? F A1 ? A2 ? A3 ? B1 ? B2 ? B3 ? f g f' g' x. rewrite /= -map_fmap_compose.\n  apply map_fmap_equiv_ext=>y ??; apply oFunctor_map_compose.\nQed.\nInstance gmapOF_contractive K `{Countable K} F :\n  oFunctorContractive F → oFunctorContractive (gmapOF K F).\nProof.\n  by intros ? A1 ? A2 ? B1 ? B2 ? n f g Hfg; apply gmapO_map_ne, oFunctor_map_contractive.\nQed.\n\nProgram Definition gmapURF K `{Countable K} (F : rFunctor) : urFunctor := {|\n  urFunctor_car A _ B _ := gmapUR K (rFunctor_car F A B);\n  urFunctor_map A1 _ A2 _ B1 _ B2 _ fg := gmapO_map (rFunctor_map F fg)\n|}.\nNext Obligation.\n  by intros K ?? F A1 ? A2 ? B1 ? B2 ? n f g Hfg; apply gmapO_map_ne, rFunctor_map_ne.\nQed.\nNext Obligation.\n  intros K ?? F A ? B ? x. rewrite /= -{2}(map_fmap_id x).\n  apply map_fmap_equiv_ext=>y ??; apply rFunctor_map_id.\nQed.\nNext Obligation.\n  intros K ?? F A1 ? A2 ? A3 ? B1 ? B2 ? B3 ? f g f' g' x. rewrite /= -map_fmap_compose.\n  apply map_fmap_equiv_ext=>y ??; apply rFunctor_map_compose.\nQed.\nInstance gmapURF_contractive K `{Countable K} F :\n  rFunctorContractive F → urFunctorContractive (gmapURF K F).\nProof.\n  by intros ? A1 ? A2 ? B1 ? B2 ? n f g Hfg; apply gmapO_map_ne, rFunctor_map_contractive.\nQed.\n\nProgram Definition gmapRF K `{Countable K} (F : rFunctor) : rFunctor := {|\n  rFunctor_car A _ B _ := gmapR K (rFunctor_car F A B);\n  rFunctor_map A1 _ A2 _ B1 _ B2 _ fg := gmapO_map (rFunctor_map F fg)\n|}.\nSolve Obligations with apply gmapURF.\n\nInstance gmapRF_contractive K `{Countable K} F :\n  rFunctorContractive F → rFunctorContractive (gmapRF K F).\nProof. apply gmapURF_contractive. Qed.\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/gmap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2752225396311443}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\nRequire Import Program.\nRequire Import Arith.\nRequire Import Permutation.\nRequire Import SetoidList.\nRequire Import SetoidPermutation.\nRequire Import Lists.List.\nRequire Import Lia.\nFrom Fairness Require Import\n  Mod\n  FairSim\n  Concurrency\n  FIFOSched\n  SchedSim.\nFrom ExtLib Require Import FMapAList.\n\nSection SIM.\n\n  Context {_Ident : ID}.\n  Variable E : Type -> Type.\n\n  Let eventE1 := @eventE _Ident.\n  Let eventE2 := @eventE (sum_tid _Ident).\n\n  Variable wf : WF.\n  Variable State : Type.\n  Variable R : Type.\n\n  Let thread R := thread _Ident (sE State) R.\n  Import Th.\n\n  Theorem ssim_nondet_fifo\n    p_src p_tgt tid ths_src ths_tgt\n    (THREADS : Permutation (TIdSet.elements ths_src) ths_tgt)\n    (TID : ~ NatMap.In tid ths_src)\n    : forall m_tgt, exists m_src, @ssim nat_wf nat_wf R R R eq p_src m_src p_tgt m_tgt\n                          (sched_nondet R (tid, ths_src))\n                          (sched_fifo R (tid, ths_tgt)).\n  Proof.\n    i.\n\n    remember (fun (i : thread_id) => List.length ths_tgt + 1) as m_src.\n    assert (M_SRC0 : m_src tid > List.length ths_tgt) by (subst; lia).\n    assert (M_SRC1 : forall i tid, nth_error ths_tgt i = Some tid -> m_src tid > i).\n    { subst. i. eapply nth_error_Some' in H. lia. }\n    clear Heqm_src.\n    exists m_src.\n\n    revert p_src p_tgt m_src m_tgt tid ths_src ths_tgt THREADS TID M_SRC0 M_SRC1.\n    pcofix CIH. i.\n\n    rewrite unfold_sched_nondet.\n    rewrite unfold_sched_fifo.\n    rewrite ! bind_trigger.\n    pfold. econs. intros [].\n    - left.\n      destruct (NatMap.is_empty ths_src) eqn: H.\n      + eapply NatMap.is_empty_2 in H.\n        eapply Empty_nil in H.\n        rewrite H in THREADS.\n        eapply Permutation_nil in THREADS.\n        subst ths_tgt.\n        pfold. econs; ss.\n      + assert (~ TIdSet.Empty ths_src).\n        { ii. eapply NatMap.is_empty_1 in H0. rewrite H in H0; ss. }\n        clear H. eapply Empty_nil_neg in H0.\n        destruct ths_tgt as [| tid' ths_tgt' ].\n        { symmetry in THREADS. eapply Permutation_nil in THREADS. ss. }\n        pfold. eapply ssim_chooseL. exists tid'. unfold nm_pop.\n        replace (NatMap.find tid' ths_src) with (Some tt); cycle 1.\n        { symmetry. eapply find_1. eapply NatSet_In_MapsTo. eapply In_NatSetIn.\n          rewrite THREADS. econs; ss.\n        }\n        rewrite bind_trigger.\n        eapply ssim_fairL.\n        remember (fun i => if Nat.eq_dec i tid'\n                        then List.length ths_tgt' + 1\n                        else if NatMapP.F.In_dec (NatMap.remove tid' ths_src) i\n                             then m_src i - 1\n                             else m_src i) as m_src'.\n        exists m_src'. splits.\n        { ii. unfold tids_fmap; ss. des_ifs.\n          assert (List.In i (TIdSet.elements ths_src)).\n          { eapply NatSetIn_In. eapply NatMapP.F.remove_neq_in_iff with (x := tid'). eauto. ss. }\n          rewrite THREADS in H. eapply In_nth_error in H. destruct H as [i' H].\n          enough (m_src i > i') by lia. eapply M_SRC1; eauto.\n        }\n        do 3 econs; eauto. right. eapply CIH.\n        * eapply NatSet_Permutation_remove. eapply THREADS.\n        * eapply NatMap.remove_1; ss.\n        * subst. des_if; ss. lia.\n        * subst. i. des_if.\n          -- eapply nth_error_Some' in H. lia.\n          -- enough (m_src tid0 > 1 + i) by (des_if; lia). eapply M_SRC1. eauto.\n    - left.\n      match goal with\n      | [ |- paco10 _ _ _ _ _ _ _ _ _ _ _ (match ?x with\n                                          | [] => _\n                                          | t' :: ts' => _\n                                          end)] => destruct x as [| tid' ths_tgt'] eqn: E_ths_tgt\n      end.\n      { eapply app_eq_nil in E_ths_tgt. des. ss. }\n      pfold. eapply ssim_chooseL. exists tid'. unfold nm_pop.\n      replace (NatMap.find tid' (TIdSet.add tid ths_src)) with (Some tt); cycle 1.\n      { symmetry. eapply find_1.\n        destruct ths_tgt; ss; inversion E_ths_tgt; subst.\n        - eapply NatMap.add_1; ss.\n        - eapply NatMap.add_2.\n          + intro. subst. eapply TID. eapply In_NatSetIn. rewrite THREADS. econs; ss.\n          + eapply NatSet_In_MapsTo. eapply In_NatSetIn. rewrite THREADS. econs; ss.\n      }\n      rewrite bind_trigger. eapply ssim_fairL.\n      remember (fun i => if Nat.eq_dec i tid'\n                      then List.length ths_tgt' + 1\n                      else if NatMapP.F.In_dec (NatMap.remove tid' (NatSet.add tid ths_src)) i\n                           then m_src i - 1\n                           else m_src i) as m_src'.\n      exists m_src'. splits.\n      { ii. unfold tids_fmap; ss. des_ifs.\n        assert (i = tid \\/ i <> tid) by lia. destruct H; try (subst; lia).\n        assert (List.In i (TIdSet.elements ths_src)).\n        { eapply NatSetIn_In. exists tt. eapply NatSet_In_MapsTo, NatMap.remove_3, NatMap.add_3 in i0; eauto. }\n        rewrite THREADS in H0. eapply In_nth_error in H0. destruct H0 as [i' H0].\n        enough (m_src i > i') by lia. eapply M_SRC1; eauto.\n      }\n      do 3 econs; ss. right. unfold NatMap.key in *. eapply CIH.\n      + eapply NatSet_Permutation_remove.\n        rewrite NatSet_Permutation_add.\n        * eapply Permutation_refl' in E_ths_tgt. rewrite Permutation_app_comm in E_ths_tgt. eapply E_ths_tgt.\n        * intro H. eapply TID. eapply H.\n        * ss.\n      + eapply NatMap.remove_1; ss.\n      + subst. des_if; ss. lia.\n      + subst. i. des_if.\n        * eapply nth_error_Some' in H. lia.\n        * enough (m_src tid0 > 1 + i) by (des_if; lia).\n          assert (nth_error (ths_tgt ++ [tid]) (1 + i) = Some tid0) by (rewrite E_ths_tgt; ss).\n          assert (1 + i < List.length ths_tgt \\/ 1 + i >= List.length ths_tgt) by lia.\n          destruct H1.\n          -- rewrite nth_error_app1 in H0 by ss. eapply M_SRC1; eauto.\n          -- rewrite nth_error_app2 in H0 by ss.\n             assert (1 + i - List.length ths_tgt = 0)\n               by (destruct (1 + i - List.length ths_tgt) as [|[]] in *; ss).\n             rewrite H2 in H0. inversion H0. subst. lia.\n  Qed.\n\n  Theorem gsim_nondet_fifo tid st (ths : @threads _Ident (sE State) R)\n    : gsim nat_wf nat_wf eq\n           (interp_all st ths tid)\n           (interp_all_fifo st ths tid).\n  Proof. \n    eapply ssim_implies_gsim.\n    { instantiate (1 := fun x => x). ss. }\n    eapply ssim_nondet_fifo; ss.\n    eapply NatMap.remove_1; ss.\n    Unshelve. all: exact true.\n  Qed.\n\nEnd SIM.\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/FIFOSchedSim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2752004492301763}}
{"text": "\n(******************************)\n(*                            *)\n(*          CONTENTS          *)\n(*                            *)\n(* is_from          line  20  *)\n(* int_or_ptr       line 280  *)\n(*                            *)\n(******************************)\n\nRequire Import compcert.common.Events compcert.common.Memory.\nRequire Import compcert.common.Values compcert.common.AST.\nRequire Import compcert.x86_32.Archi compcert.lib.Integers.\nRequire Import Coq.ZArith.BinInt Coq.Lists.List Coq.micromega.Lia.\nImport ListNotations.\nLocal Open Scope Z_scope. Local Open Scope list_scope.\n\n\n\n(* Verification of the function Is_from *)\n\nDefinition valid_block (m : mem) (b : block) (o : ptrofs) (n : Z) : Prop :=\n  0 < n /\\\n  Ptrofs.unsigned o + n <= Int.modulus /\\\n  forall i : Z, 0 <= i < n ->\n                common.Memory.Mem.valid_pointer m b (Ptrofs.unsigned o + i) = true.\n\nDefinition Is_from_sem : extcall_sem :=\n  fun _ args m1 trc ret m2 =>\n    m1 = m2 /\\ trc = nil /\\\n    match args with\n    | (Vptr b1 o1) :: (Vptr b2 o2) :: (Vptr b3 o3) :: nil =>\n      exists n : Z, 0 < n /\\\n                    Ptrofs.unsigned o1 + n < Int.modulus /\\\n                    b1 = b2 /\\\n                    Ptrofs.unsigned o1 + n = Ptrofs.unsigned o2 /\\\n                    valid_block m1 b1 o1 n /\\\n                    common.Memory.Mem.valid_pointer m1 b3 (Ptrofs.unsigned o3) = true /\\\n                    ((b1 = b3 /\\\n                      Ptrofs.unsigned o1 <= Ptrofs.unsigned o3 < Ptrofs.unsigned o2 /\\\n                      ret = Vone) \\/\n                     ((b1 <> b3 \\/\n                       (b1 = b3 /\\\n                        (Ptrofs.unsigned o3 < Ptrofs.unsigned o1 \\/\n                         Ptrofs.unsigned o3 >= Ptrofs.unsigned o2)))\n                      /\\ ret = Vzero))\n    | _ => False\n    end.\n\nDefinition Is_from_sig : signature :=\n  mksignature (AST.Tint :: AST.Tint :: AST.Tint :: nil) (Tret AST.Tint) cc_default.\n\nLtac split3 := split; [|split ].\n\nLemma lt_ptr_mod: forall n1 n2,\n    n1 <= n2 <= Ptrofs.max_unsigned -> n1 <= n2 < Ptrofs.modulus.\nProof.\n  intros.\n  replace Ptrofs.max_unsigned with (Z.pred Ptrofs.modulus) in * by\n      (unfold Ptrofs.max_unsigned; lia).\n  now rewrite <- Z.lt_le_pred in *.\nQed.\n\nLemma Is_from_extcall: extcall_properties Is_from_sem Is_from_sig.\nProof.\n  constructor; intros.\n  - destruct H as [_ [_ ?]].\n    do 4 (destruct vargs; try destruct v; try contradiction).\n    destruct H as [_ [_ [_ [_ [_ [_ [_ ?]]]]]]].\n    destruct H as [[_ [_ ?]] | [_ ?]]; subst; apply I.\n  - apply H0.\n  - destruct H as [? _]. subst m1. trivial.\n  - destruct H as [? _]. subst m1. trivial.\n  - destruct H as [? _]. subst m1. trivial.\n  - exists vres, m1'.\n    destruct H as [? [? ?]]; subst m2 t.\n    split.\n    2: split3; [apply Val.lessdef_refl | trivial | apply Mem.unchanged_on_refl].\n    split3; trivial.\n    do 4 (destruct vargs; try destruct v; try contradiction).\n    inversion H1; inversion H4; inversion H6; inversion H11;\n      inversion H13; inversion H18; inversion H20; subst.\n    clear H4 H11 H18 H20 H13 H6 H1.\n    destruct H3 as [n [? [? [? [? ?]]]]].\n    exists n. do 4 (split; trivial).\n    clear -H0 H4. destruct H4 as [? [? ?]].\n    split3; [|eapply Mem.valid_pointer_extends; eauto | tauto].\n    destruct H as [? [? ?]].\n    do 2 (split; trivial).\n    intros. specialize (H4 i2 H5).\n    eapply Mem.valid_pointer_extends; eauto.\n  - intros. exists f, vres, m1'. destruct H0 as [? [? ?]]. split.\n    2: {\n      split. 2: repeat (split; [now subst|]); congruence.\n      clear -H4.\n      do 4 (destruct vargs; try destruct v; try contradiction).\n      destruct H4 as [_ [_ [_ [_ [_ [_ [_ H]]]]]]].\n      destruct vres; auto. now destruct H.\n    }\n    split3; trivial.\n    do 4 (destruct vargs; try destruct v; try contradiction).\n    inversion H2; inversion H7; inversion H9;\n      inversion H17; inversion H19; inversion H27; inversion H29; subst.\n    clear H2 H7 H9 H17 H19 H27 H29.\n    destruct H4 as [n [? [? [? [? [? [? ?]]]]]]].\n    exists n. rewrite H3 in  H12; rewrite H22 in H12; inversion H12.\n    subst; clear H12.\n    assert (Hf: 0 <= Ptrofs.unsigned i + n < Ptrofs.modulus) by\n        (rewrite H4; apply Ptrofs.unsigned_range).\n    assert (Ha: Ptrofs.unsigned (Ptrofs.add i (Ptrofs.repr delta)) + n < Int.modulus). {\n      replace Int.modulus with Ptrofs.modulus by\n          (unfold Int.modulus, Ptrofs.modulus; f_equal).\n      destruct H1 as [_ _ _ _ rep _].\n      destruct (rep b0 b3 delta\n                      (Ptrofs.add i (Ptrofs.repr n)) H22) as [Hx Hy].\n      { right. apply Mem.perm_cur_max, Mem.valid_pointer_nonempty_perm.\n        destruct H5 as [_ [_ H5]].\n        assert (Hm: 0 <= n - 1 < n) by lia; rewrite <- (H5 _ Hm).\n        f_equal; unfold Ptrofs.add; repeat rewrite Ptrofs.unsigned_repr_eq.\n        rewrite Z.add_mod_idemp_r, Z.mod_small by easy. lia.\n      }\n      clear -Hx Hy Hf H0.\n      apply lt_ptr_mod in Hy. unfold Ptrofs.add in *.\n      repeat rewrite Ptrofs.unsigned_repr_eq in *.\n      rewrite Z.add_mod_idemp_r, Z.mod_small in * by easy.\n      rewrite Z.mod_small; [lia|].\n      destruct i. unfold Ptrofs.unsigned in *; simpl in *. lia.\n    }\n    split3; [| |split3; [| |split3]]; trivial.\n    + destruct H1 as [_ _ _ _ rep _].\n      destruct (rep _ _ delta\n                   (Ptrofs.add i (Ptrofs.repr n)) H22) as [Hd' Hd]. {\n        right. apply Mem.perm_cur_max, Mem.valid_pointer_nonempty_perm.\n        destruct H5 as [_ [_ H5]]. assert (0 <= n - 1 < n) by lia.\n        rewrite <- (H5 _ H1). f_equal.\n        unfold Ptrofs.add; repeat rewrite Ptrofs.unsigned_repr_eq.\n        rewrite Z.add_mod_idemp_r, Z.mod_small by easy. lia.\n      }\n      unfold Ptrofs.add. rewrite <- H4.\n      destruct (Ptrofs.unsigned_range i) as [? _].\n      repeat rewrite Ptrofs.unsigned_repr_eq.\n      repeat rewrite Z.add_mod_idemp_r by easy.\n      replace Int.modulus with Ptrofs.modulus in Ha by\n          (unfold Int.modulus, Ptrofs.modulus; f_equal).\n      unfold Ptrofs.add in Hd.\n      repeat rewrite Ptrofs.unsigned_repr_eq in Hd.\n      rewrite Z.add_mod_idemp_r, Z.mod_small in Hd by easy.\n      apply lt_ptr_mod in Hd.\n      repeat rewrite Z.mod_small; [lia | trivial | lia].\n    + split3; [easy | lia|]. intros.\n      destruct H5 as [_ [_ H5]].\n      rewrite <- (Mem.valid_pointer_inject _ _ _ _ _ _ _ H22 H1 (H5 i2 H3)).\n      f_equal. unfold Ptrofs.add; repeat rewrite Ptrofs.unsigned_repr_eq.\n      destruct H1 as [_ _ _ _ rep _].\n      destruct (rep _ _ delta i H22) as [_ Hd]. {\n        left. apply Mem.perm_cur_max, Mem.valid_pointer_nonempty_perm.\n        assert (0 <= 0 < n) by lia; rewrite <- (H5 0 H1); f_equal; lia.\n      }\n      apply lt_ptr_mod in Hd.\n      rewrite Z.add_mod_idemp_r, Z.mod_small by easy. lia.\n    + rewrite <- (Mem.valid_pointer_inject _ _ _ _ _ _ _ H32 H1 H6).\n      f_equal. unfold Ptrofs.add. repeat rewrite Ptrofs.unsigned_repr_eq.\n      destruct H1 as [_ _ _ _ rep _].\n      destruct (rep _ _ delta1 i1 H32) as [_ Hd]. {\n        left; now apply Mem.perm_cur_max,\n              Mem.valid_pointer_nonempty_perm.\n      }\n      apply lt_ptr_mod in Hd.\n      rewrite Z.add_mod_idemp_r, Z.mod_small by easy. lia.\n    + destruct H7.\n      * destruct H3 as [? [? ?]]; subst b1 vres.\n        destruct H1 as [_ _ _ _ rep _].\n        destruct (rep b0 b3 delta i H22) as [_ Hp]. {\n          left; apply Mem.perm_cur_max, Mem.valid_pointer_nonempty_perm.\n          destruct H5 as [_ [_ H5]]; assert (0 <= 0 < n) by lia.\n          specialize (H5 0 H1).\n          now replace (Ptrofs.unsigned i + 0) with (Ptrofs.unsigned i) in H5 by lia.\n        }\n        destruct (rep b0 b3 delta i1 H22) as [_ Hq]. {\n          left; apply Mem.perm_cur_max, Mem.valid_pointer_nonempty_perm;\n            destruct H5 as [_ [_ ?]]; assert (0 <= 0 < n) by lia.\n          specialize (H1 0 H3); now rewrite H6.\n        }\n        destruct (rep b0 b3 delta i0 H22) as [_ Hr]. {\n          destruct H5 as [_ [_ H5]]. rewrite <- H4.\n          assert (Hm: 0 <= n - 1 < n) by lia.\n          right. apply Mem.perm_cur_max, Mem.valid_pointer_nonempty_perm.\n          rewrite <- (H5 _ Hm); f_equal; lia.\n        }\n        rewrite H22 in H32; inversion H32.\n        left. split3; trivial.\n        subst delta1. clear -H7 Hp Hq Hr.\n        unfold Ptrofs.add; repeat rewrite Ptrofs.unsigned_repr_eq.\n        apply lt_ptr_mod in Hp; apply lt_ptr_mod in Hq; apply lt_ptr_mod in Hr.\n        repeat rewrite Z.add_mod_idemp_r, Z.mod_small by easy.\n        lia.\n      * destruct H3. right. split; trivial.\n        rename m2 into m; rename m1' into m'.\n        destruct H1 as [_ _ _ lap rep _].\n        destruct H3.\n        -- destruct (eq_block b3 b7); [|now left].\n           subst b3. right. split; trivial.\n           unfold Ptrofs.add; repeat rewrite Ptrofs.unsigned_repr_eq.\n           repeat rewrite Z.add_mod_idemp_r by easy.\n           destruct H5 as [_ [_ H5]].\n           assert (0 <= 0 < n) by lia.\n           pose proof (H5 _ H3).\n           apply Mem.valid_pointer_nonempty_perm, Mem.perm_cur_max in H6.\n           apply Mem.valid_pointer_nonempty_perm, Mem.perm_cur_max in H8.\n           replace (Ptrofs.unsigned i + 0) with (Ptrofs.unsigned i) in H8 by lia.\n           destruct (rep _ _ delta1 i1 H32) as [_ Hp]; [left; easy|].\n           destruct (rep _ _ delta i H22) as [_ Hq]; [left; easy|].\n           destruct (rep _ _ delta i0 H22) as [_ Hr]. {\n             rewrite <- H4.\n             assert (Hm: 0 <= n - 1 < n) by lia.\n             specialize (H5 _ Hm).\n             replace (Ptrofs.unsigned i + (n - 1)) with (Ptrofs.unsigned i + n - 1) in H5 by lia.\n             apply Mem.valid_pointer_nonempty_perm, Mem.perm_cur_max in H5. now right.\n           }\n           replace Ptrofs.max_unsigned with (Z.pred Ptrofs.modulus) in * by\n               (unfold Ptrofs.max_unsigned; lia).\n           rewrite <- Z.lt_le_pred in *.\n           repeat rewrite Z.mod_small by easy.\n           destruct (lap _ _ _ _ _ _ _ _ H1 H22 H32 H8 H6); [contradiction|].\n           clear rep Hp Hq Hr.\n           replace (Ptrofs.unsigned i) with ((Ptrofs.unsigned i - delta) + delta) in H5 by lia.\n           assert ((Ptrofs.unsigned i1 + delta1 < Ptrofs.unsigned i + delta) \\/\n                   (Ptrofs.unsigned i1 + delta1 >= Ptrofs.unsigned i0 + delta) \\/\n                   ((Ptrofs.unsigned i1 + delta1 >= Ptrofs.unsigned i + delta) /\\\n                    Ptrofs.unsigned i1 + delta1 < Ptrofs.unsigned i0 + delta)) by lia.\n           destruct H10; [auto | destruct H10; [auto|]].\n           exfalso.\n           destruct H10. rewrite <- H4 in H11.\n           assert (0 <= Ptrofs.unsigned i1 + delta1 - Ptrofs.unsigned i - delta < n) by lia.\n           specialize (H5 (Ptrofs.unsigned i1 + delta1 - Ptrofs.unsigned i - delta) H12).\n           apply Mem.valid_pointer_nonempty_perm, Mem.perm_cur_max in H5.\n           destruct (lap b0 b7 delta b1 b7 delta1 _ (Ptrofs.unsigned i1) H1 H22 H32 H5 H6); [auto | apply H13; lia].\n        -- destruct H1. subst b0 vres.\n           right. rewrite H22 in H32; inversion H32.\n           clear H32.\n           split; trivial.\n           unfold Ptrofs.add; repeat rewrite Ptrofs.unsigned_repr_eq.\n           repeat rewrite Z.add_mod_idemp_r by easy.\n           subst delta1.\n           destruct (rep b1 b3 delta i H22) as [_ Hp]. {\n             left; apply Mem.perm_cur_max, Mem.valid_pointer_nonempty_perm.\n             destruct H5 as [_ [_ H5]]; assert (H1: 0 <= 0 < n) by lia.\n             specialize (H5 0 H1).\n             now replace (Ptrofs.unsigned i + 0) with (Ptrofs.unsigned i) in H5 by lia.\n           }\n           destruct (rep b1 b3 delta i1 H22) as [_ Hq].\n           1:  now left; apply Mem.perm_cur_max, Mem.valid_pointer_nonempty_perm.\n           destruct (rep b1 b3 delta i0 H22) as [_ Hr]. {\n             destruct H5 as [_ [_ H5]]. rewrite <- H4.\n             assert (Hm: 0 <= n - 1 < n) by lia.\n             right. apply Mem.perm_cur_max, Mem.valid_pointer_nonempty_perm.\n             rewrite <- (H5 _ Hm); f_equal; lia.\n           }\n           clear - H3 Hp Hq Hr.\n           apply lt_ptr_mod in Hp; apply lt_ptr_mod in Hq; apply lt_ptr_mod in Hr.\n           repeat rewrite Z.mod_small by easy.\n           destruct H3; [left | right]; lia.\n  - intros. destruct H as [_ [? _]]. subst t. simpl. lia.\n  - intros. generalize H. destruct H as [_ [? _]]. subst t1.\n    inversion H0. subst t2. clear H0. intro H.\n    exists vres1, m1. apply H.\n  - intros. destruct H as [? [? ?]]. destruct H0 as [? [? ?]].\n    subst m1 m2 t1 t2. split; [constructor|].\n    intros _. split; trivial.\n    do 4 (destruct vargs; try destruct v; try contradiction).\n    destruct H2 as [_ [_ [_ [_ [_ [_ [_ ?]]]]]]].\n    destruct H4 as [_ [_ [_ [_ [_ [_ [_ ?]]]]]]].\n    intuition; congruence.\nQed.\n\n\n\n(* Verification of int_or_ptr *)\n\nDefinition valid_b_o_So (m : mem) (b : block) (o : ptrofs) : Prop :=\n  Mem.range_perm m b (Ptrofs.unsigned o) (Ptrofs.unsigned o + 2) Cur Nonempty.\n\nLemma valid_b_o_So_dec: forall m b o, {valid_b_o_So m b o} + {~ valid_b_o_So m b o}.\nProof. intros. unfold valid_b_o_So. apply Mem.range_perm_dec. Qed.\n\nDefinition test_iop_sem : extcall_sem :=\n  fun _ args m1 trc ret m2 =>\n    m1 = m2 /\\ trc = nil /\\\n    match args with\n    | [Vint i] =>\n      if (Int.eq Int.one (Int.modu i (Int.repr 2)))\n      then ret = Vone\n      else False\n    | [Vptr b ofs] =>\n      if (Ptrofs.eq Ptrofs.one (Ptrofs.modu ofs (Ptrofs.repr 2)))\n      then False\n      else if valid_b_o_So_dec m1 b ofs\n           then ret = Vzero\n           else False\n    | _ => False\n    end.\n\nDefinition test_iop_sig : signature :=\n  mksignature (AST.Tint :: nil) (Tret AST.Tint) cc_default.\n\nLemma test_iop__extcall: extcall_properties test_iop_sem test_iop_sig.\nProof.\n  constructor; intros.\n  - destruct H as [_ [_ ?]].\n    destruct vargs; try destruct v; try contradiction; destruct vargs; try contradiction.\n    1: destruct (Int.eq Int.one (Int.modu i (Int.repr 2))); subst; easy.\n    destruct (Ptrofs.eq Ptrofs.one (Ptrofs.modu i (Ptrofs.repr 2))).\n    1: contradiction.\n    destruct (valid_b_o_So_dec m1 b i); subst; easy.\n  - trivial.\n  - destruct H as [? _]. subst m1. trivial.\n  - destruct H as [? _]. subst m1. trivial.\n  - destruct H as [? _]. subst m1. trivial.\n  - destruct H as [? [? ?]]; subst m2 t.\n    exists vres, m1'. split.\n    2: split3; [apply Val.lessdef_refl | trivial | apply Mem.unchanged_on_refl].\n    split3; trivial.\n    do 2 (try destruct vargs; try destruct v); try contradiction;\n      inversion H1; inversion H4; inversion H6; auto.\n    clear -H0 H3.\n    destruct (Ptrofs.eq Ptrofs.one (Ptrofs.modu i (Ptrofs.repr 2))); auto.\n    destruct (valid_b_o_So_dec m1 b i);\n      destruct (valid_b_o_So_dec m1' b i); [trivial| | contradiction..].\n    clear H3; destruct n.\n    destruct H0 as [_ [? _ _] _].\n    unfold valid_b_o_So in *.\n    unfold Mem.range_perm in *. intros.\n    specialize (v ofs H).\n    assert (inject_id b = Some (b, 0)) by now unfold inject_id.\n    specialize (mi_perm _ _ _ ofs Cur Nonempty H0).\n    replace (ofs + 0) with ofs in mi_perm by lia.\n    apply (mi_perm v).\n  - intros. exists f, vres, m1'.\n    destruct H0 as [? [? ?]]. subst.\n    split.\n    2: {\n      split.\n      - destruct vres; auto.\n        do 2 (destruct vargs; try destruct v; try contradiction).\n        + destruct (Int.eq Int.one (Int.modu i0 (Int.repr 2))); [inversion H4 | easy].\n        + destruct (Ptrofs.eq Ptrofs.one (Ptrofs.modu i0 (Ptrofs.repr 2))); try contradiction.\n          destruct (valid_b_o_So_dec m2 b0 i0); [inversion H4 | easy].\n      - split; [trivial|].\n        split; [apply Mem.unchanged_on_refl|].\n        split; [apply Mem.unchanged_on_refl|].\n        split; [apply inject_incr_refl | congruence].\n    }\n    split3; trivial.\n    do 2 (destruct vargs; try destruct v; try contradiction).\n    + inversion H2. inversion H5. inversion H7. auto.\n    + inversion H2. inversion H5. inversion H7.\n      subst. clear H7 H2.\n      destruct (Ptrofs.eq Ptrofs.one (Ptrofs.modu i (Ptrofs.repr 2))) eqn:parity1; [contradiction|].\n      destruct (valid_b_o_So_dec m2 b i); [|contradiction].\n      assert (OF: Ptrofs.unsigned (Ptrofs.add i (Ptrofs.repr delta)) = Ptrofs.unsigned i + delta).\n        { eapply Mem.address_inject; eauto. apply v. lia. }\n        assert (AL: (2 | delta)).\n        { change 2 with (align_chunk Mint16unsigned).\n          clear - H10 v H1.\n          eauto using Mem.mi_align, Mem.mi_inj, Mem.range_perm_max. }\n        destruct (Ptrofs.eq Ptrofs.one\n                          (Ptrofs.modu (Ptrofs.add i (Ptrofs.repr delta)) (Ptrofs.repr 2))) eqn:parity2.\n      * assert (0 <= Ptrofs.unsigned i + delta < Ptrofs.modulus). {\n          destruct H1 as [_ _ _ _ rep _].\n          specialize (rep _ _ _ i H10) as [_ rep].\n          left. unfold valid_b_o_So in v.\n          unfold Mem.range_perm in v.\n          specialize (v (Ptrofs.unsigned i)).\n          apply Mem.perm_cur_max in v. auto.\n          lia. apply lt_ptr_mod in rep. assumption.\n        }\n        clear - parity1 parity2 AL H0.\n        rewrite <- Bool.not_false_iff_true in parity2.\n        unfold not in *.\n        destruct parity2.\n        unfold Ptrofs.modu in *.\n        rewrite Ptrofs.unsigned_repr_eq in *.\n        rewrite (Z.mod_small 2 _) in * by easy.\n        unfold Ptrofs.add; repeat rewrite Ptrofs.unsigned_repr_eq.\n        rewrite Z.add_mod_idemp_r, (Z.mod_small (Ptrofs.unsigned i + delta) _) by easy.\n        rewrite <- parity1. do 2 f_equal.\n        rewrite <- Z.add_mod_idemp_r, (Znumtheory.Zdivide_mod delta 2) by easy.\n        now replace (Ptrofs.unsigned i + 0) with (Ptrofs.unsigned i) by lia.\n      * destruct (valid_b_o_So_dec m1' b2 (Ptrofs.add i (Ptrofs.repr delta))); auto.\n        destruct n.\n        assert (inj := H1).\n        destruct H1 as [[? _ _] _ _ _ rep _].\n        unfold valid_b_o_So in *.\n        rewrite OF. replace (Ptrofs.unsigned i + delta + 2) with ((Ptrofs.unsigned i + 2) + delta) by lia.\n  eapply Mem.range_perm_inject; eauto.\n  - destruct H as [_ [? _]]. subst t. simpl; lia.\n  - generalize H. destruct H as [_ [? _]].\n    subst t1; inversion H0; subst t2.\n    intro H; exists vres1, m1; apply H.\n  - destruct H as [? [? ?]]. destruct H0 as [? [? ?]].\n    subst m1 m2 t1 t2.\n    split; [constructor|]. intros _. split; trivial.\n    do 2 (try destruct vargs; try destruct v; try contradiction).\n    + destruct (Int.eq Int.one (Int.modu i (Int.repr 2))); subst; [trivial | contradiction].\n    + destruct (Ptrofs.eq Ptrofs.one (Ptrofs.modu i (Ptrofs.repr 2))); [contradiction|].\n      destruct (valid_b_o_So_dec m b i); [|contradiction].\n      subst; trivial.\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_Is_from.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.2751426320530932}}
{"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 A B C G Gprime Aprime Bprime Cprime Gprimeprime I : Universe, ((wd_ A B /\\ (wd_ B C /\\ (wd_ A C /\\ (wd_ Bprime A /\\ (wd_ Bprime C /\\ (wd_ Aprime B /\\ (wd_ Aprime C /\\ (wd_ Cprime A /\\ (wd_ Cprime B /\\ (wd_ G A /\\ (wd_ Cprime Gprimeprime /\\ (wd_ Aprime Gprime /\\ (wd_ G C /\\ (wd_ I Aprime /\\ (wd_ I Gprime /\\ (wd_ I Cprime /\\ (wd_ I Gprimeprime /\\ (wd_ Gprimeprime C /\\ (wd_ Gprimeprime G /\\ (wd_ Gprime A /\\ (wd_ Gprime G /\\ (col_ G A Aprime /\\ (col_ G B Bprime /\\ (col_ G Cprime C /\\ (col_ I Aprime Gprime /\\ (col_ I Cprime Gprimeprime /\\ (col_ Gprimeprime C G /\\ (col_ Cprime A B /\\ (col_ Gprime A G /\\ (col_ Bprime A C /\\ col_ Aprime B C)))))))))))))))))))))))))))))) -> col_ C G I)).\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_1096.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.2751396677530361}}
{"text": "(** * Coequalizers defined in terms of colimits *)\n(** ** Contents\n- Definition of coequalizers\n- Coincides with the direct definition\n*)\nRequire Import UniMath.Foundations.PartD.\nRequire Import UniMath.Foundations.Propositions.\nRequire Import UniMath.Foundations.Sets.\n\nRequire Import UniMath.MoreFoundations.Tactics.\n\nRequire Import UniMath.Combinatorics.StandardFiniteSets.\n\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.Core.Isos.\nRequire Import UniMath.CategoryTheory.limits.graphs.limits.\nRequire Import UniMath.CategoryTheory.limits.graphs.colimits.\nRequire Import UniMath.CategoryTheory.limits.graphs.eqdiag.\nRequire Import UniMath.CategoryTheory.limits.coequalizers.\n\nLocal Open Scope cat.\n\n(** * Definition of coequalizers in terms of colimits *)\nSection def_coequalizers.\n\n  Variable C : category.\n\n  Local Open Scope stn.\n  Definition One : two := ● 0.\n  Definition Two : two := ● 1.\n\n  Definition Coequalizer_graph : graph.\n  Proof.\n    exists two.\n    use (@two_rec (two -> UU)).\n    - apply two_rec.\n      + apply empty.\n      + apply (unit ⨿ unit).\n    - apply (λ _, empty).\n  Defined.\n\n  Definition Coequalizer_diagram {a b : C} (f g : C⟦a, b⟧) : diagram Coequalizer_graph C.\n  Proof.\n    exists (two_rec a b).\n    use two_rec_dep.\n    - use two_rec_dep; simpl.\n      + apply fromempty.\n      + intro x. induction x.\n        exact f. exact g.\n    - intro. apply fromempty.\n  Defined.\n\n  Definition Coequalizer_cocone {a b : C} (f g : C⟦a, b⟧) (d : C) (h : C⟦b, d⟧)\n             (H : f · h = g · h) : cocone (Coequalizer_diagram f g) d.\n  Proof.\n    use make_cocone.\n    - use two_rec_dep.\n      + exact (f · h).\n      + exact h.\n    - use two_rec_dep; use two_rec_dep.\n      + exact (empty_rect _).\n      + intro e. induction e.\n        * apply idpath.\n        * apply (! H).\n      + exact (empty_rect _).\n      + exact (empty_rect _).\n  Defined.\n\n  Definition isCoequalizer {a b : C} (f g : C⟦a, b⟧) (d : C) (h : C⟦b, d⟧)\n             (H : f · h = g · h) : UU := isColimCocone (Coequalizer_diagram f g) d\n                                                         (Coequalizer_cocone f g d h H).\n\n  Definition make_isCoequalizer {a b : C} (f g : C⟦a, b⟧) (d : C) (h : C⟦b, d⟧)\n             (H : f · h = g · h) :\n    (∏ e (h' : C⟦b, e⟧) (H' : f · h' = g · h'),\n     iscontr (total2 (fun hk : C⟦d, e⟧ => h · hk = h'))) ->\n    isCoequalizer f g d h H.\n  Proof.\n    intros H' x cx.\n    assert (H1 : f · coconeIn cx Two = g · coconeIn cx Two).\n    {\n      use (pathscomp0 (coconeInCommutes cx One Two (ii1 tt))).\n      use (pathscomp0 _ (!(coconeInCommutes cx One Two (ii2 tt)))).\n      apply idpath.\n    }\n    set (H2 := (H' x (coconeIn cx Two) H1)).\n    use tpair.\n    - use (tpair _ (pr1 (pr1 H2)) _).\n      use two_rec_dep.\n      + use (pathscomp0 _ (coconeInCommutes cx One Two (ii1 tt))).\n        change (coconeIn (Coequalizer_cocone f g d h H) _) with (f · h).\n        change (dmor _ _) with f.\n        rewrite <- assoc.\n        apply cancel_precomposition, (pr2 (pr1 H2)).\n      + apply (pr2 (pr1 H2)).\n    - abstract (intro t; apply subtypePath;\n               [intros y; apply impred; intros t0; apply C\n               |induction t as [t p]; apply path_to_ctr, (p Two)]).\n  Defined.\n\n  Definition Coequalizer {a b : C} (f g : C⟦a, b⟧) : UU := ColimCocone (Coequalizer_diagram f g).\n\n  Definition make_Coequalizer {a b : C} (f g : C⟦a, b⟧) (d : C) (h : C⟦b, d⟧) (H : f · h = g · h)\n             (isCEq : isCoequalizer f g d h H) : Coequalizer f g.\n  Proof.\n    use tpair.\n    - use tpair.\n      + exact d.\n      + use Coequalizer_cocone.\n        * exact h.\n        * exact H.\n    - exact isCEq.\n  Defined.\n\n  Definition Coequalizers : UU := ∏ (a b : C) (f g : C⟦a, b⟧), Coequalizer f g.\n\n  Definition hasCoequalizers : UU := ∏ (a b : C) (f g : C⟦a, b⟧), ishinh (Coequalizer f g).\n\n  Definition CoequalizerObject {a b : C} {f g : C⟦a, b⟧} :\n    Coequalizer f g -> C := λ H, colim H.\n\n  Definition CoequalizerArrow {a b : C} {f g : C⟦a, b⟧} (E : Coequalizer f g) :\n    C⟦b, colim E⟧ := colimIn E Two.\n\n  Definition CoequalizerArrowEq {a b : C} {f g : C⟦a, b⟧} (E : Coequalizer f g) :\n    f · CoequalizerArrow E = g · CoequalizerArrow E.\n  Proof.\n    use (pathscomp0 (colimInCommutes E One Two (ii1 tt))).\n    use (pathscomp0 _ (!(colimInCommutes E One Two (ii2 tt)))).\n    apply idpath.\n  Qed.\n\n  Definition CoequalizerOut {a b : C} {f g : C⟦a, b⟧} (E : Coequalizer f g) e (h : C⟦b, e⟧)\n             (H : f · h = g · h) : C⟦colim E, e⟧.\n  Proof.\n    now use colimArrow; use Coequalizer_cocone.\n  Defined.\n\n  Lemma CoequalizerArrowComm {a b : C} {f g : C⟦a, b⟧} (E : Coequalizer f g) (e : C) (h : C⟦b, e⟧)\n        (H : f · h = g · h) : CoequalizerArrow E · CoequalizerOut E e h H = h.\n  Proof.\n    exact (colimArrowCommutes E e _ Two).\n  Qed.\n\n  Lemma CoequalizerOutUnique {a b : C} {f g : C⟦a, b⟧} (E : Coequalizer f g) (e : C) (h : C⟦b, e⟧)\n        (H : f · h = g · h) (w : C⟦colim E, e⟧) (H' : CoequalizerArrow E · w = h) :\n    w = CoequalizerOut E e h H.\n  Proof.\n    apply path_to_ctr.\n    use two_rec_dep.\n    - set (X := colimInCommutes E One Two (ii1 tt)).\n      apply (maponpaths (λ h : _, h · w)) in X.\n      use (pathscomp0 (!X)); rewrite <- assoc.\n      change (dmor _ _) with f.\n      change (coconeIn _ _) with (f · h).\n      apply cancel_precomposition, H'.\n    - apply H'.\n  Qed.\n\n  Definition isCoequalizer_Coequalizer {a b : C} {f g : C⟦a, b⟧} (E : Coequalizer f g) :\n    isCoequalizer f g (CoequalizerObject E) (CoequalizerArrow E)\n                  (CoequalizerArrowEq E).\n  Proof.\n    apply make_isCoequalizer.\n    intros e h H.\n    use (unique_exists (CoequalizerOut E e h H)).\n    (* Commutativity *)\n    - exact (CoequalizerArrowComm E e h H).\n    (* Equality on equalities of morphisms *)\n    - intros y. apply C.\n    (* Uniqueness *)\n    - intros y t. cbn in t.\n      use CoequalizerOutUnique.\n      exact t.\n  Qed.\n\n  Definition CoequalizerOfArrows\n             {a a' b b' : C} {f g : a --> b}\n             {f' g' : a' --> b'}\n             (cfg : Coequalizer f g)\n             (cfg' : Coequalizer f' g')\n             (u : a --> a')\n             (v : b --> b')\n             (eqf : f · v = u · f')\n             (eqg : g · v = u · g')\n    :\n      CoequalizerObject cfg --> CoequalizerObject cfg'.\n  Proof.\n    unshelve eapply CoequalizerOut.\n    - refine (v · _).\n      apply CoequalizerArrow.\n    - abstract (rewrite ! assoc, eqf , eqg, ! assoc' ;\n                 apply cancel_precomposition, CoequalizerArrowEq).\n  Defined.\n  Lemma CoequalizerOfArrowsEq\n        {a a' b b' : C} {f g : a --> b}\n        {f' g' : a' --> b'}\n        (cfg : Coequalizer f g)\n        (cfg' : Coequalizer f' g')\n        (u : a --> a')\n        (v : b --> b')\n        (eqf : f · v = u · f')\n        (eqg : g · v = u · g')\n    :\n      CoequalizerArrow cfg · CoequalizerOfArrows cfg cfg' u v eqf eqg  =\n      v · CoequalizerArrow cfg'.\n  Proof.\n    apply  CoequalizerArrowComm.\n  Qed.\n\n  (** ** Coequalizers to coequalizers *)\n\n  Definition identity_is_Coequalizer_input {a b : C} {f g : C⟦a, b⟧} (E : Coequalizer f g) :\n    total2 (fun hk : C⟦colim E, colim E⟧ => CoequalizerArrow E · hk = CoequalizerArrow E).\n  Proof.\n    use tpair.\n    exact (identity _).\n    apply id_right.\n  Defined.\n\n  Lemma CoequalizerEndo_is_identity  {a b : C} {f g : C⟦a, b⟧} (E : Coequalizer f g)\n        (k : C⟦colim E, colim E⟧) (kH :CoequalizerArrow E · k = CoequalizerArrow E) :\n    identity (colim E) = k.\n  Proof.\n    apply colim_endo_is_identity.\n    unfold colimIn.\n    use two_rec_dep; cbn.\n    + set (X := (coconeInCommutes (colimCocone E) One Two (ii1 tt))).\n      use (pathscomp0 (! (maponpaths (λ h' : _, h' · k) X))).\n      use (pathscomp0 _ X).\n      rewrite <- assoc. apply cancel_precomposition.\n      apply kH.\n    + apply kH.\n  Qed.\n\n  Definition from_Coequalizer_to_Coequalizer {a b : C} {f g : C⟦a, b⟧} (E1 E2 : Coequalizer f g) :\n    C⟦colim E1, colim E2⟧.\n  Proof.\n    apply (CoequalizerOut E1 (colim E2) (CoequalizerArrow E2)).\n    exact (CoequalizerArrowEq E2).\n  Defined.\n\n  Lemma are_inverses_from_Coequalizer_to_Coequalizer {a b : C} {f g : C⟦a, b⟧}\n        (E1 E2 : Coequalizer f g) :\n    is_inverse_in_precat (from_Coequalizer_to_Coequalizer E2 E1)\n                         (from_Coequalizer_to_Coequalizer E1 E2).\n  Proof.\n    split; apply pathsinv0.\n    - apply CoequalizerEndo_is_identity.\n      rewrite assoc.\n      unfold from_Coequalizer_to_Coequalizer.\n      repeat rewrite CoequalizerArrowComm.\n      apply idpath.\n    - apply CoequalizerEndo_is_identity.\n      rewrite assoc.\n      unfold from_Coequalizer_to_Coequalizer.\n      repeat rewrite CoequalizerArrowComm.\n      apply idpath.\n  Qed.\n\n  Lemma isiso_from_Coequalizer_to_Coequalizer {a b : C} {f g : C⟦a, b⟧} (E1 E2 : Coequalizer f g) :\n    is_iso (from_Coequalizer_to_Coequalizer E1 E2).\n  Proof.\n    apply (is_iso_qinv _ (from_Coequalizer_to_Coequalizer E2 E1)).\n    apply are_inverses_from_Coequalizer_to_Coequalizer.\n  Qed.\n\n  Definition iso_from_Coequalizer_to_Coequalizer {a b : C} {f g : C⟦a, b⟧}\n             (E1 E2 : Coequalizer f g) : iso (colim E1) (colim E2) :=\n    tpair _ _ (isiso_from_Coequalizer_to_Coequalizer E1 E2).\n\n  Lemma inv_from_iso_iso_from_Pullback {a b : C} {f g : C⟦a , b⟧} (E1 E2 : Coequalizer f g):\n    inv_from_iso (iso_from_Coequalizer_to_Coequalizer E1 E2) =\n    from_Coequalizer_to_Coequalizer E2 E1.\n  Proof.\n    apply pathsinv0.\n    apply inv_iso_unique'.\n    apply (pr1 (are_inverses_from_Coequalizer_to_Coequalizer E2 E1)).\n  Qed.\n\n\n  (** ** Connections to other colimits *)\n\n  Lemma Coequalizers_from_Colims : Colims C -> Coequalizers.\n  Proof.\n    intros H a b f g. apply H.\n  Defined.\n\nEnd def_coequalizers.\n\n\n(** * Definitions coincide\n    In this section we show that the definition of coequalizer as a colimit coincides with the\n    direct definition. *)\nSection coequalizers_coincide.\n\n  Variable C : category.\n\n\n  (** ** isCoequalizers *)\n\n  Lemma equiv_isCoequalizer1 {a b : C} {f g : C⟦a, b⟧} (e : C) (h : C⟦b, e⟧) (H : f · h = g · h) :\n    limits.coequalizers.isCoequalizer f g h H -> isCoequalizer C f g e h H.\n  Proof.\n    intros X.\n    set (E := limits.coequalizers.make_Coequalizer f g h H X).\n    use (make_isCoequalizer C).\n    intros e' h' H'.\n    use (unique_exists (limits.coequalizers.CoequalizerOut E e' h' H')).\n    (* Commutativity *)\n    - exact (limits.coequalizers.CoequalizerCommutes E e' h' H').\n    (* Equality on equalities of morphisms *)\n    - intros y. apply C.\n    (* Uniqueness *)\n    - intros y T. cbn in T.\n      use (limits.coequalizers.CoequalizerOutsEq E).\n      use (pathscomp0 T).\n      exact (!(limits.coequalizers.CoequalizerCommutes E e' h' H')).\n  Qed.\n\n  Lemma equiv_isCoequalizer2 {a b : C} (f g : C⟦a, b⟧) (e : C) (h : C⟦b, e⟧) (H : f · h = g · h) :\n    limits.coequalizers.isCoequalizer f g h H <- isCoequalizer C f g e h H.\n  Proof.\n    intros X.\n    set (E := make_Coequalizer C f g e h H X).\n    intros e' h' H'.\n    use (unique_exists (CoequalizerOut C E e' h' H')).\n    (* Commutativity *)\n    - exact (CoequalizerArrowComm C E e' h' H').\n    (* Equality on equalities of morphisms *)\n    - intros y. apply C.\n    (* Uniqueness *)\n    - intros y T. cbn in T.\n      use (CoequalizerOutUnique C E).\n      exact T.\n  Qed.\n\n  (** ** Coequalizers *)\n\n  Definition equiv_Coequalizer1 {a b : C} (f g : C⟦a, b⟧) :\n    limits.coequalizers.Coequalizer f g -> Coequalizer C f g.\n  Proof.\n    intros E.\n    exact (make_Coequalizer\n             C f g _ _ _\n             (equiv_isCoequalizer1\n                (limits.coequalizers.CoequalizerObject E)\n                (limits.coequalizers.CoequalizerArrow E)\n                (limits.coequalizers.CoequalizerEqAr E)\n                (limits.coequalizers.isCoequalizer_Coequalizer E))).\n  Defined.\n\n  Definition equiv_Coequalizer2 {a b : C} (f g : C⟦a, b⟧) :\n    limits.coequalizers.Coequalizer f g <- Coequalizer C f g.\n  Proof.\n    intros E.\n    exact (@limits.coequalizers.make_Coequalizer\n             C a b (CoequalizerObject C E) f g\n             (CoequalizerArrow C E)\n             (CoequalizerArrowEq C E)\n             (@equiv_isCoequalizer2\n                a b f g (CoequalizerObject C E)\n                (CoequalizerArrow C E)\n                (CoequalizerArrowEq C E)\n                (isCoequalizer_Coequalizer C E))).\n  Defined.\n\nEnd coequalizers_coincide.\n\n(** Post-composing a coequalizer diagram with a functor yields a\n     coequalizer diagram. *)\nLemma mapdiagram_coequalizer_eq_diag {C : category}{D : category}\n      (F : functor C D){a b : C}(f g : a --> b)  :\n  eq_diag (C := D)\n          (mapdiagram F (Coequalizer_diagram _ f g))\n          (Coequalizer_diagram _ (# F f) (# F g)).\nProof.\n  use tpair.\n  -  use StandardFiniteSets.two_rec_dep; cbn; apply idpath.\n  -  use StandardFiniteSets.two_rec_dep;  use StandardFiniteSets.two_rec_dep;\n       try exact (empty_rect _ ).\n     intro e.\n     induction e; apply idpath.\nDefined.\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/limits/graphs/coequalizers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2750693762907397}}
{"text": "From iris_examples.logrel.F_mu_ref Require Export logrel_binary.\nFrom iris.algebra Require Import list.\nFrom iris.proofmode Require Import tactics.\nFrom iris.program_logic Require Import lifting.\nFrom iris_examples.logrel.F_mu_ref Require Import rules_binary.\n\nSection bin_log_def.\n  Context `{heapG Σ,cfgSG Σ}.\n  Notation D := (prodO valO valO -n> iProp Σ).\n\n  Definition bin_log_related (Γ : list type) (e e' : expr) (τ : type) :=\n    ∀ Δ vvs (ρ : cfg F_mu_ref_lang), env_Persistent Δ →\n    spec_inv ρ ∗ ⟦ Γ ⟧* Δ vvs ⊢\n    ⟦ τ ⟧ₑ Δ (e.[env_subst (vvs.*1)], e'.[env_subst (vvs.*2)]).\nEnd bin_log_def.\n\nNotation \"Γ ⊨ e '≤log≤' e' : τ\" :=\n  (bin_log_related Γ e e' τ) (at level 74, e, e', τ at next level).\n\nSection fundamental.\n  Context `{heapG Σ,cfgSG Σ}.\n  Notation D := (prodO valO valO -n> iPropO Σ).\n  Implicit Types e : expr.\n  Implicit Types Δ : listO D.\n  Local Hint Resolve to_of_val : core.\n\n  Local Tactic Notation \"smart_wp_bind\" uconstr(ctx) ident(v) ident(w)\n        constr(Hv) uconstr(Hp) :=\n    iApply (wp_bind (fill [ctx]));\n    iApply (wp_wand with \"[-]\");\n      [iApply Hp; iFrame \"#\"; trivial|];\n    iIntros (v); iDestruct 1 as (w) Hv.\n\n  (* Put all quantifiers at the outer level *)\n  Lemma bin_log_related_alt {Γ e e' τ} : Γ ⊨ e ≤log≤ e' : τ → ∀ Δ vvs ρ K,\n    env_Persistent Δ →\n    spec_inv ρ ∗ ⟦ Γ ⟧* Δ vvs ∗ ⤇ fill K (e'.[env_subst (vvs.*2)])\n    ⊢ WP e.[env_subst (vvs.*1)] {{ v, ∃ v',\n        ⤇ fill K (of_val v') ∗ interp τ Δ (v, v') }}.\n  Proof.\n    iIntros (Hlog Δ vvs K ρ ?) \"[#Hρ [HΓ Hj]]\". asimpl.\n    iApply (Hlog with \"[HΓ]\"); iFrame. eauto.\n  Qed.\n\n  Notation \"'` H\" := (bin_log_related_alt H) (at level 8).\n\n  Lemma bin_log_related_var Γ x τ :\n    Γ !! x = Some τ → Γ ⊨ Var x ≤log≤ Var x : τ.\n  Proof.\n    iIntros (? Δ vvs ρ ?) \"[#Hρ #HΓ]\". iIntros (K) \"Hj /=\".\n    iDestruct (interp_env_Some_l with \"HΓ\") as ([v v']) \"[Heq Hv]\"; first done.\n    iDestruct \"Heq\" as %Heq.\n    erewrite !env_subst_lookup; rewrite ?list_lookup_fmap ?Heq; eauto.\n    iApply wp_value; auto.\n  Qed.\n\n  Lemma bin_log_related_unit Γ : Γ ⊨ Unit ≤log≤ Unit : TUnit.\n  Proof.\n    iIntros (Δ vvs ρ ?) \"#[Hρ HΓ]\". iIntros (K) \"Hj /=\".\n    iApply wp_value. iExists UnitV; eauto.\n  Qed.\n\n  Lemma bin_log_related_pair Γ e1 e2 e1' e2' τ1 τ2\n      (IHHtyped1 : Γ ⊨ e1 ≤log≤ e1' : τ1)\n      (IHHtyped2 : Γ ⊨ e2 ≤log≤ e2' : τ2) :\n    Γ ⊨ Pair e1 e2 ≤log≤ Pair e1' e2' : TProd τ1 τ2.\n  Proof.\n    iIntros (Δ vvs ρ ?) \"#[Hρ HΓ]\"; iIntros (K) \"Hj /=\".\n    smart_wp_bind (PairLCtx e2.[env_subst _]) v v' \"[Hv #Hiv]\"\n      ('`IHHtyped1 _ _ _ ((PairLCtx e2'.[env_subst _]) :: K)).\n    smart_wp_bind (PairRCtx v) w w' \"[Hw #Hiw]\"\n      ('`IHHtyped2 _ _ _ ((PairRCtx v') :: K)).\n    iApply wp_value.\n    iExists (PairV v' w'); iFrame \"Hw\".\n    iExists (v, v'), (w, w'); simpl; repeat iSplit; trivial.\n  Qed.\n\n  Lemma bin_log_related_fst Γ e e' τ1 τ2\n      (IHHtyped : Γ ⊨ e ≤log≤ e' : TProd τ1 τ2) :\n    Γ ⊨ Fst e ≤log≤ Fst e' : τ1.\n  Proof.\n    iIntros (Δ vvs ρ ?) \"[#Hρ #HΓ]\"; iIntros (K) \"Hj /=\".\n    smart_wp_bind (FstCtx) v v' \"[Hv #Hiv]\" ('`IHHtyped _ _ _ (FstCtx :: K)); cbn.\n    iDestruct \"Hiv\" as ([w1 w1'] [w2 w2']) \"#[% [Hw1 Hw2]]\"; simplify_eq.\n    iMod (step_fst _ _ K (of_val w1') (of_val w2') with \"[-]\") as \"Hw\"; eauto.\n    iApply wp_pure_step_later; auto. iApply wp_value; auto.\n  Qed.\n\n  Lemma bin_log_related_snd Γ e e' τ1 τ2\n      (IHHtyped : Γ ⊨ e ≤log≤ e' : TProd τ1 τ2) :\n    Γ ⊨ Snd e ≤log≤ Snd e' : τ2.\n  Proof.\n    iIntros (Δ vvs ρ ?) \"#[Hρ HΓ]\"; iIntros (K) \"Hj /=\".\n    smart_wp_bind (SndCtx) v v' \"[Hv #Hiv]\" ('`IHHtyped _ _ _ (SndCtx :: K)); cbn.\n    iDestruct \"Hiv\" as ([w1 w1'] [w2 w2']) \"#[% [Hw1 Hw2]]\"; simplify_eq.\n    iMod (step_snd _ _ K (of_val w1') (of_val w2') with \"[-]\") as \"Hw\"; eauto.\n    iApply wp_pure_step_later; auto. iApply wp_value; auto.\n  Qed.\n\n  Lemma bin_log_related_injl Γ e e' τ1 τ2\n      (IHHtyped : Γ ⊨ e ≤log≤ e' : τ1) :\n    Γ ⊨ InjL e ≤log≤ InjL e' : (TSum τ1 τ2).\n  Proof.\n    iIntros (Δ vvs ρ ?) \"#[Hρ HΓ]\"; iIntros (K) \"Hj /=\".\n    smart_wp_bind (InjLCtx) v v' \"[Hv #Hiv]\"\n      ('`IHHtyped _ _ _ (InjLCtx :: K)); cbn.\n    iApply wp_value. repeat rewrite /= to_of_val. eauto.\n    iExists (InjLV v'); iFrame \"Hv\".\n    iLeft; iExists (_,_); eauto 10.\n  Qed.\n\n  Lemma bin_log_related_injr Γ e e' τ1 τ2\n      (IHHtyped : Γ ⊨ e ≤log≤ e' : τ2) :\n    Γ ⊨ InjR e ≤log≤ InjR e' : TSum τ1 τ2.\n  Proof.\n    iIntros (Δ vvs ρ ?) \"#[Hρ HΓ]\"; iIntros (K) \"Hj /=\".\n    smart_wp_bind (InjRCtx) v v' \"[Hv #Hiv]\"\n      ('`IHHtyped _ _ _ (InjRCtx :: K)); cbn.\n    iApply wp_value. repeat rewrite /= to_of_val. eauto.\n    iExists (InjRV v'); iFrame \"Hv\".\n    iRight; iExists (_,_); eauto 10.\n  Qed.\n\n  Lemma bin_log_related_case Γ e0 e1 e2 e0' e1' e2' τ1 τ2 τ3\n      (Hclosed2 : ∀ f, e1.[upn (S (length Γ)) f] = e1)\n      (Hclosed3 : ∀ f, e2.[upn (S (length Γ)) f] = e2)\n      (Hclosed2' : ∀ f, e1'.[upn (S (length Γ)) f] = e1')\n      (Hclosed3' : ∀ f, e2'.[upn (S (length Γ)) f] = e2')\n      (IHHtyped1 : Γ ⊨ e0 ≤log≤ e0' : TSum τ1 τ2)\n      (IHHtyped2 : τ1 :: Γ ⊨ e1 ≤log≤ e1' : τ3)\n      (IHHtyped3 : τ2 :: Γ ⊨ e2 ≤log≤ e2' : τ3) :\n    Γ ⊨ Case e0 e1 e2 ≤log≤ Case e0' e1' e2' : τ3.\n  Proof.\n    iIntros (Δ vvs ρ ?) \"#[Hρ HΓ]\"; iIntros (K) \"Hj /=\".\n    iDestruct (interp_env_length with \"HΓ\") as %?.\n    smart_wp_bind (CaseCtx _ _) v v' \"[Hv #Hiv]\"\n      ('`IHHtyped1 _ _ _ ((CaseCtx _ _) :: K)); cbn.\n    iDestruct \"Hiv\" as \"[Hiv|Hiv]\".\n    - iDestruct \"Hiv\" as ([w w']) \"[% Hw]\"; simplify_eq.\n      iMod (step_case_inl _ _ K (of_val w') with \"[-]\") as \"Hz\"; eauto.\n      simpl.\n      iApply wp_pure_step_later; auto 1 using to_of_val. iNext.\n      asimpl. iApply ('`IHHtyped2 _ ((w,w') :: vvs)); repeat iSplit; eauto.\n      iApply interp_env_cons; auto.\n    - iDestruct \"Hiv\" as ([w w']) \"[% Hw]\"; simplify_eq.\n      iMod (step_case_inr _ _ K (of_val w') with \"[-]\") as \"Hz\"; eauto.\n      simpl.\n      iApply wp_pure_step_later; auto 1 using to_of_val. iNext.\n      asimpl. iApply ('`IHHtyped3 _ ((w,w') :: vvs)); repeat iSplit; eauto.\n      iApply interp_env_cons; auto.\n  Qed.\n\n  Lemma bin_log_related_lam Γ (e e' : expr) τ1 τ2\n      (Hclosed : ∀ f, e.[upn (S (length Γ)) f] = e)\n      (Hclosed' : ∀ f, e'.[upn (S (length Γ)) f] = e')\n      (IHHtyped : τ1 :: Γ ⊨ e ≤log≤ e' : τ2) :\n    Γ ⊨ Lam e ≤log≤ Lam e' : TArrow τ1 τ2.\n  Proof.\n    iIntros (Δ vvs ρ ?) \"#[Hρ HΓ]\"; iIntros (K) \"Hj /=\".\n    iApply wp_value. iExists (LamV _). iIntros \"{$Hj} !#\".\n    iIntros ([v v']) \"#Hiv\". iIntros (K') \"Hj\".\n    iDestruct (interp_env_length with \"HΓ\") as %?.\n    iApply wp_pure_step_later; auto 1 using to_of_val. iNext.\n    iMod (step_lam _ _ K' _ (of_val v') with \"[-]\") as \"Hz\"; eauto.\n    asimpl. iApply ('`IHHtyped _ ((v,v') :: vvs)); repeat iSplit; eauto.\n    iApply interp_env_cons; iSplit; auto.\n  Qed.\n\n  Lemma bin_log_related_app Γ e1 e2 e1' e2' τ1 τ2\n      (IHHtyped1 : Γ ⊨ e1 ≤log≤ e1' : TArrow τ1 τ2)\n      (IHHtyped2 : Γ ⊨ e2 ≤log≤ e2' : τ1) :\n    Γ ⊨ App e1 e2 ≤log≤ App e1' e2' :  τ2.\n  Proof.\n    iIntros (Δ vvs ρ ?) \"#[Hρ HΓ]\"; iIntros (K) \"Hj /=\".\n    smart_wp_bind (AppLCtx (e2.[env_subst (vvs.*1)])) v v' \"[Hv #Hiv]\"\n      ('`IHHtyped1 _ _ _ (((AppLCtx (e2'.[env_subst (vvs.*2)]))) :: K)); cbn.\n    smart_wp_bind (AppRCtx v) w w' \"[Hw #Hiw]\"\n                  ('`IHHtyped2 _ _ _ ((AppRCtx v') :: K)); cbn.\n    iApply (\"Hiv\" $! (w, w') with \"Hiw\"); simpl; eauto.\n  Qed.\n\n  Lemma bin_log_related_tlam Γ e e' τ\n      (IHHtyped : (subst (ren (+1)) <$> Γ) ⊨ e ≤log≤ e' : τ) :\n    Γ ⊨ TLam e ≤log≤ TLam e' : TForall τ.\n  Proof.\n    iIntros (Δ vvs ρ ?) \"#[Hρ HΓ]\"; iIntros (K) \"Hj /=\".\n    iApply wp_value. iExists (TLamV _).\n    iIntros \"{$Hj} /= !#\"; iIntros (τi ? K') \"Hv /=\".\n    iApply wp_pure_step_later; auto; iNext.\n    iMod (step_tlam _ _ K' (e'.[env_subst (vvs.*2)]) with \"[-]\") as \"Hz\"; eauto.\n    iApply '`IHHtyped; repeat iSplit; eauto. by iApply interp_env_ren.\n  Qed.\n\n  Lemma bin_log_related_tapp Γ e e' τ τ'\n      (IHHtyped : Γ ⊨ e ≤log≤ e' : TForall τ) :\n    Γ ⊨ TApp e ≤log≤ TApp e' : τ.[τ'/].\n  Proof.\n    iIntros (Δ vvs ρ ?) \"#[Hρ HΓ]\"; iIntros (K) \"Hj /=\".\n    smart_wp_bind (TAppCtx) v v' \"[Hj #Hv]\"\n      ('`IHHtyped _ _ _ (TAppCtx :: K)).\n    iApply wp_wand_r; iSplitL.\n    { iSpecialize (\"Hv\" $! (interp τ' Δ) with \"[#]\"); [iPureIntro; apply _|].\n      iApply \"Hv\"; eauto. }\n    iIntros (w). iDestruct 1 as (w') \"Hw\".\n    iExists _; rewrite -interp_subst; eauto.\n  Qed.\n\n  Lemma bin_log_related_fold Γ e e' τ\n      (IHHtyped : Γ ⊨ e ≤log≤ e' : τ.[(TRec τ)/]) :\n    Γ ⊨ Fold e ≤log≤ Fold e' : TRec τ.\n  Proof.\n    iIntros (Δ vvs ρ ?) \"#[Hρ HΓ]\"; iIntros (K) \"Hj /=\".\n    iApply (wp_bind (fill [FoldCtx])); iApply wp_wand_l; iSplitR;\n        [|iApply ('`IHHtyped _ _ _ (FoldCtx :: K));\n          rewrite ?fill_app; simpl; repeat iSplitR; trivial].\n    iIntros (v); iDestruct 1 as (w) \"[Hv #Hiv]\".\n    iApply wp_value. repeat rewrite /= to_of_val; eauto.\n    iExists (FoldV w); iFrame \"Hv\".\n    rewrite fixpoint_interp_rec1_eq /= -interp_subst.\n    iAlways; iExists (_, _); eauto.\n  Qed.\n\n  Lemma bin_log_related_unfold Γ e e' τ\n      (IHHtyped : Γ ⊨ e ≤log≤ e' : TRec τ) :\n    Γ ⊨ Unfold e ≤log≤ Unfold e' : τ.[(TRec τ)/].\n  Proof.\n    iIntros (Δ vvs ρ ?) \"#[Hρ HΓ]\"; iIntros (K) \"Hj /=\".\n    iApply (wp_bind (fill [UnfoldCtx])); iApply wp_wand_l; iSplitR;\n        [|iApply ('`IHHtyped _ _ _ (UnfoldCtx :: K));\n          rewrite ?fill_app; simpl; repeat iSplitR; trivial].\n    iIntros (v). iDestruct 1 as (v') \"[Hw #Hiw]\".\n    rewrite /= fixpoint_interp_rec1_eq /=.\n    change (fixpoint _) with (interp (TRec τ) Δ).\n    iDestruct \"Hiw\" as ([w w']) \"#[% Hiz]\"; simplify_eq/=.\n    iMod (step_Fold _ _ K (of_val w') with \"[-]\") as \"Hz\"; eauto.\n    iApply wp_pure_step_later; cbn; auto.\n    iNext. iApply wp_value; auto. iExists _; iFrame \"Hz\".\n      by rewrite -interp_subst.\n  Qed.\n\n  Lemma bin_log_related_alloc Γ e e' τ\n      (IHHtyped : Γ ⊨ e ≤log≤ e' : τ) :\n    Γ ⊨ Alloc e ≤log≤ Alloc e' : Tref τ.\n  Proof.\n    iIntros (Δ vvs ρ ?) \"#[Hρ HΓ]\". iIntros (K) \"Hj /=\".\n    smart_wp_bind (AllocCtx) v v' \"[Hv #Hiv]\" ('`IHHtyped _ _ _ (AllocCtx :: K)).\n    iMod (step_alloc _ _ K (of_val v') v' with \"[Hv]\") as (l') \"[Hj Hl']\"; eauto.\n    iApply wp_fupd. iApply wp_alloc; auto.\n    iIntros \"!>\"; iIntros (l) \"Hl\".\n    iMod (inv_alloc (logN .@ (l,l')) _ (∃ w : val * val,\n      l ↦ w.1 ∗ l' ↦ₛ w.2 ∗ interp τ Δ w)%I with \"[Hl Hl']\") as \"HN\"; eauto.\n    { iNext; iExists (v, v'); by iFrame. }\n    iModIntro; iExists (LocV l'). iFrame \"Hj\". iExists (l, l'). eauto.\n  Qed.\n\n  Lemma bin_log_related_load Γ e e' τ\n      (IHHtyped : Γ ⊨ e ≤log≤ e' : (Tref τ)) :\n    Γ ⊨ Load e ≤log≤ Load e' : τ.\n  Proof.\n    iIntros (Δ vvs ρ ?) \"#[? HΓ]\"; iIntros (K) \"Hj /=\".\n    smart_wp_bind (LoadCtx) v v' \"[Hv #Hiv]\" ('`IHHtyped _ _ _ (LoadCtx :: K)).\n    simpl. iDestruct \"Hiv\" as ([l l']) \"[% Hinv]\"; simplify_eq.\n    iInv (logN .@ (l,l')) as  ([w w']) \"[Hw1 [Hw2 #Hw]]\" \"Hclose\"; simpl.\n    iMod \"Hw2\".\n    iMod (step_load _ _ K l' 1 w' with \"[Hv Hw2]\") as \"[Hv Hw2]\";\n      [solve_ndisj|by iFrame|].\n    iApply (wp_load _ _ 1 with \"[Hw1]\"); eauto.\n    iNext. iIntros \"Hw1\". iMod (\"Hclose\" with \"[Hw1 Hw2]\").\n    { iNext. iExists (w,w'); by iFrame. }\n    iModIntro. iExists w'; by iFrame.\n  Qed.\n\n  Lemma bin_log_related_store Γ e1 e2 e1' e2' τ\n      (IHHtyped1 : Γ ⊨ e1 ≤log≤ e1' : (Tref τ))\n      (IHHtyped2 : Γ ⊨ e2 ≤log≤ e2' : τ) :\n    Γ ⊨ Store e1 e2 ≤log≤ Store e1' e2' : TUnit.\n  Proof.\n    iIntros (Δ vvs ρ ?) \"#[? HΓ]\"; iIntros (K) \"Hj /=\".\n    smart_wp_bind (StoreLCtx _) v v' \"[Hv #Hiv]\"\n      ('`IHHtyped1 _ _ _ ((StoreLCtx _) :: K)).\n    smart_wp_bind (StoreRCtx _) w w' \"[Hw #Hiw]\"\n      ('`IHHtyped2 _ _ _ ((StoreRCtx _) :: K)).\n    simpl. iDestruct \"Hiv\" as ([l l']) \"[% Hinv]\"; simplify_eq/=.\n    iInv (logN .@ (l,l')) as ([v v']) \"[>Hv1 [>Hv2 #Hv]]\" \"Hclose\".\n    iMod (step_store _ _ K l' v' (of_val w') w' with \"[Hw Hv2]\")\n      as \"[Hw Hv2]\"; [solve_ndisj|by iFrame|].\n    iApply (wp_store with \"[Hv1]\"); eauto using to_of_val.\n    iNext. iIntros \"Hv1\". iMod (\"Hclose\" with \"[Hv1 Hv2]\").\n    { iNext; iExists (w, w'); by iFrame. }\n    iExists UnitV; iFrame; auto.\n  Qed.\n\n  Theorem binary_fundamental Γ e τ :\n    Γ ⊢ₜ e : τ → Γ ⊨ e ≤log≤ e : τ.\n  Proof.\n    induction 1.\n    - by apply bin_log_related_var.\n    - by apply bin_log_related_unit.\n    - apply bin_log_related_pair; eauto.\n    - eapply bin_log_related_fst; eauto.\n    - eapply bin_log_related_snd; eauto.\n    - eapply bin_log_related_injl; eauto.\n    - eapply bin_log_related_injr; eauto.\n    - eapply bin_log_related_case; eauto;\n        match goal with H : _ |- _ => eapply (typed_n_closed _ _ _ H) end.\n    - eapply bin_log_related_lam; eauto;\n        match goal with H : _ |- _ => eapply (typed_n_closed _ _ _ H) end.\n    - eapply bin_log_related_app; eauto.\n    - eapply bin_log_related_tlam; eauto with typeclass_instances.\n    - eapply bin_log_related_tapp; eauto.\n    - eapply bin_log_related_fold; eauto.\n    - eapply bin_log_related_unfold; eauto.\n    - eapply bin_log_related_alloc; eauto.\n    - eapply bin_log_related_load; eauto.\n    - eapply bin_log_related_store; eauto.\n  Qed.\nEnd fundamental.\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/logrel/F_mu_ref/fundamental_binary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2750693762907397}}
{"text": "Set Implicit Arguments.\nRequire Import GMuAnnot.Prelude.\nRequire Import GMuAnnot.Infrastructure.\nRequire Import GMuAnnot.Regularity.\nRequire Import GMuAnnot.Regularity2.\nRequire Import GMuAnnot.SubstMatch.\nRequire Import GMuAnnot.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.\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.\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.\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.\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.\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.\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.\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.\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.\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.\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.\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)).\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.\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\n    apply teq_symmetry in EQ.\n    lets: inversion_eq_typ_all EQ; subst.\n\n    apply typing_eq with (open_tt T0 T1) 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.\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 H\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    subst.\n    (* clear H14 H15 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 H19 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 H14. auto.\n    }\n    2: {\n      intros A U Ain Uin.\n      lets WFT: H28 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~ H15.\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~ H15.\n          -- introv Ain Uin. lets HF2: Afresh Ain.\n             apply* fv_typs_notin.\n        }\n        -- rewrite~ List.map_length.\n        -- apply EQ2.\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/Preservation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.27496569478017985}}
{"text": "Require Import Blech.Defaults.\n\nRequire Import Coq.Setoids.Setoid.\nRequire Import Coq.Classes.SetoidClass.\n\nRequire Import Blech.Bishop.\nRequire Import Blech.Bishop.Trv.\nRequire Import Blech.Category.\nRequire Blech.Reflect.\n\nImport CategoryNotations.\nImport BishopNotations.\n\nOpen Scope category_scope.\n\n#[local]\nObligation Tactic := Reflect.category_simpl.\n\n#[program]\nDefinition Trv: Category := {|\n  Obj := True ;\n  Mor _ _ := True  ;\n  Mor_Setoid _ _ := {| equiv _ _ := True |} ;\n\n  id _ := I ;\n  compose _ _ _ _ _ := I ;\n|}.\n\nNext Obligation.\nProof.\n  exists.\n  all: exists.\nQed.\n\nModule TrvNotations.\n  Notation \"·\" := Trv : category_scope.\nEnd TrvNotations.\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/Category/Trv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.27496568816602907}}
{"text": "From Coq Require Import String List ZArith.\nFrom compcert Require Import Coqlib Integers Floats AST Ctypes Cop Clight Clightdefs.\nRequire Import CSplit.semantics.\nRequire Import utils.AClightNotations.\nRequire Import FloydSeq.proofauto.\nRequire VST.floyd.proofauto.\nRequire Import FloydSeq.proofauto.\nRequire Import CSplit.strong.\nRequire Import FloydSeq.client_lemmas.\nRequire Import CSplit.strongSoundness.\nRequire Import CSplit.AClightFunc.\n\n\nLocal Open Scope Z_scope.\nImport AClightNotations.\n\nModule Info.\n  Definition version := \"3.6\"%string.\n  Definition build_number := \"\"%string.\n  Definition build_tag := \"\"%string.\n  Definition arch := \"x86\"%string.\n  Definition model := \"32sse2\"%string.\n  Definition abi := \"macosx\"%string.\n  Definition bitsize := 32.\n  Definition big_endian := false.\n  Definition source_file := \"testprogs/reverse_noinv.c\"%string.\n  Definition normalized := true.\nEnd Info.\n\nRequire Import cprogs.reverse_prog.\nRequire Import cprogs.reverse_def.\n\nDefinition f_reverse_spec_annotation :=\n  ANNOTATION_WITH  sh p l, ((\n            PROP  (writable_share sh)\n\t    LOCAL (temp _p p)\n\t    SEP   (listrep sh l p)),\n  (\n          EX q: val,\n\t    PROP  ()\n\t    LOCAL (temp ret_temp q)\n\t    SEP   (listrep sh (rev l) q))).\n\nDefinition f_reverse_spec_complex :=\n  ltac:(uncurry_funcspec f_reverse_spec_annotation).\n\nDefinition f_reverse_funsig: funsig :=\n  (((_p, (tptr (Tstruct _list noattr))) :: nil),\n   (tptr (Tstruct _list noattr))).\n\nDefinition reverse_spec :=\n  ltac:(make_funcspec _reverse f_reverse_funsig f_reverse_spec_complex).\n\nLtac get_para_type_rec_tac A B :=\n  match B with\n  | ?B1 -> ?B2 => get_para_type_rec_tac (prod A B1) B2\n  | prod _ _ => exact A\n  end.\n\nLtac get_para_type_tac spec_annot :=\n  match type of spec_annot with\n  | ?A -> prod _ _ => exact A\n  | ?A -> ?B => get_para_type_rec_tac A B\n  end.\n\nNotation \"'GET_PARA_TYPE' x\" := ltac:(get_para_type_tac x) (at level 99).\n\nDefinition f_reverse_hint (para: GET_PARA_TYPE f_reverse_spec_annotation) :=\n  match para with\n  | (sh, p, l) =>\n        (Csequence\n(*          (Cset _w (Econst_int (Int.repr 0) tint)) *)\n          (Cset _w  (Ecast (Econst_int (Int.repr 0) tint) (tptr tvoid)))\n          (Csequence\n            (Cset _v (Etempvar _p (tptr (Tstruct _list noattr))))\n            (Csequence\n              (Cloop\n                (Csequence\n                  (Cassert (\n       (EX w v l1 l2,\n          PROP  (writable_share sh; l = rev l1 ++ l2)\n\t  LOCAL (temp _w w; temp _v v)\n\t  SEP   (listrep sh l1 w; listrep sh l2 v))%assert))\n                  (EXGIVEN w\n                    [[((EX v l1 l2,\n          PROP  (writable_share sh; l = rev l1 ++ l2)\n\t  LOCAL (temp _w w; temp _v v)\n\t  SEP   (listrep sh l1 w; listrep sh l2 v))%assert)]] \n                    (EXGIVEN v\n                      [[((EX l1 l2,\n          PROP  (writable_share sh; l = rev l1 ++ l2)\n\t  LOCAL (temp _w w; temp _v v)\n\t  SEP   (listrep sh l1 w; listrep sh l2 v))%assert)]] \n                      (EXGIVEN l1\n                        [[((EX l2,\n          PROP  (writable_share sh; l = rev l1 ++ l2)\n\t  LOCAL (temp _w w; temp _v v)\n\t  SEP   (listrep sh l1 w; listrep sh l2 v))%assert)]] \n                        (EXGIVEN l2\n                          [[((PROP  (writable_share sh; l = rev l1 ++ l2)\n\t  LOCAL (temp _w w; temp _v v)\n\t  SEP   (listrep sh l1 w; listrep sh l2 v))%assert)]] \n                          (Csequence\n                            (Cifthenelse (Etempvar _v (tptr (Tstruct _list noattr)))\n                              Cskip\n                              (Csequence Cbreak Cskip))\n                            (Csequence\n                              (Cassert (\n         (EX t x l2',\n\t    PROP  (writable_share sh; l = rev l1 ++ l2; l2 = x :: l2'; writable_share sh)\n\t    LOCAL (temp _w w; temp _v v)\n\t    SEP   (data_at sh t_struct_list (x, t) v;\n\t           listrep sh l1 w; listrep sh l2' t))%assert))\n                              (EXGIVEN t\n                                [[((EX x l2',\n\t    PROP  (writable_share sh; l = rev l1 ++ l2; l2 = x :: l2'; writable_share sh)\n\t    LOCAL (temp _w w; temp _v v)\n\t    SEP   (data_at sh t_struct_list (x, t) v;\n\t           listrep sh l1 w; listrep sh l2' t))%assert)]] \n                                (EXGIVEN x\n                                  [[((EX l2',\n\t    PROP  (writable_share sh; l = rev l1 ++ l2; l2 = x :: l2'; writable_share sh)\n\t    LOCAL (temp _w w; temp _v v)\n\t    SEP   (data_at sh t_struct_list (x, t) v;\n\t           listrep sh l1 w; listrep sh l2' t))%assert)]] \n                                  (EXGIVEN l2'\n                                    [[((PROP  (writable_share sh; l = rev l1 ++ l2; l2 = x :: l2'; writable_share sh)\n\t    LOCAL (temp _w w; temp _v v)\n\t    SEP   (data_at sh t_struct_list (x, t) v;\n\t           listrep sh l1 w; listrep sh l2' t))%assert)]] \n                                    (Csequence\n                                      (Cset _t\n                                        (Efield\n                                          (Ederef\n                                            (Etempvar _v (tptr (Tstruct _list noattr)))\n                                            (Tstruct _list noattr)) _tail\n                                          (tptr (Tstruct _list noattr))))\n                                      (Csequence\n                                        (Cassign\n                                          (Efield\n                                            (Ederef\n                                              (Etempvar _v (tptr (Tstruct _list noattr)))\n                                              (Tstruct _list noattr)) _tail\n                                            (tptr (Tstruct _list noattr)))\n                                          (Etempvar _w (tptr (Tstruct _list noattr))))\n                                        (Csequence\n                                          (Cset _w\n                                            (Etempvar _v (tptr (Tstruct _list noattr))))\n                                          (Csequence\n                                            (Cset _v\n                                              (Etempvar _t (tptr (Tstruct _list noattr))))\n                                            Cskip))))))))))))))\n                Cskip)\n              (Csequence\n                (Creturn (Some (Etempvar _w (tptr (Tstruct _list noattr)))))\n                Cskip))))\n  end.\n\nDefinition Gprog : funspecs :=\n  ltac:(with_library prog [reverse_spec]).\n\n(*\nTime Definition f_reverse_hint_split para :=\n  match para with\n  | (sh, p, l) =>\n    ltac:(compute_split (f_reverse_hint (sh, p, l)))\n  end.\nGoal forall para,\n  match para with\n  | (sh, p, l) =>\n    ltac:(compute_split (f_reverse_hint (sh, p, l))) = C_split (f_reverse_hint (sh, p, l))\n  end.\n  intros [ [sh p] l].\n  unfold C_split, f_reverse_hint.\n  Print C_split_exgiven.\n\n*)\nTheorem f_reverse_functionally_correct:\n  semax_body Vprog Gprog f_reverse reverse_spec.\nProof.\n  Time VST_A_start_function f_reverse_hint.\n  + Intros.\n    forward.\n    forward.\n    unfold RA_normal, normal_split_assert.\n    Exists nullval p (@nil val) l.\n    entailer!.\n    unfold listrep.\n    entailer!.\n  + intros w v l1 l2.\n    forward_if; [| forward; apply TT_right].\n    forward.\n    unfold RA_normal, normal_split_assert.\n    sep_apply (listrep_isptr sh l2 v).\n    Intros a l2b t.\n    Exists t a l2b.\n    entailer!.\n  + Intros w v l1 l2 t a l2b.\n    forward.\n    forward.\n    forward.\n    forward.\n    unfold RA_normal, normal_split_assert.\n    entailer!.\n    Exists v t (a :: l1) l2b.\n    entailer!.\n    - simpl.\n      rewrite <- app_assoc.\n      reflexivity.\n    - unfold listrep at 2; fold listrep.\n      Exists w.\n      entailer!.\n  + Intros w v l1 l2.\n    forward_if; [forward; apply TT_right |].\n    unfold POSTCONDITION, abbreviate.\n    apply semax_return_return_split_assert.\n    forward.\n    Exists w; entailer!.\n    sep_apply (listrep_null sh l2).\n    entailer!.\n    rewrite app_nil_r, rev_involutive.\n    entailer!.\nQed.\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/testprogs/reverse_annot_noinv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.27496568816602907}}
{"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\nRequire Export cvterm.\nRequire Export substitution3.\n\nRequire Export continuity_axiom2.\nRequire Export continuity_type_aux.\n\nRequire Export cequiv_tacs.\nRequire Export subst_tacs.\n\nRequire Export continuity_per.\n\nRequire Export lift_lsubst_tacs.\n\nRequire Export list. (* why? *)\n\n\n\n(*\nDefinition of_type_int {o} lib (t : @NTerm o) :=\n  {z : Z & reduces_to lib t (mk_integer z)}.\n\nDefinition of_type_int_to_val {o} lib (f : @NTerm o) :=\n  forall a,\n    of_type_int lib a\n    -> {v : NTerm\n        & reduces_to lib (mk_apply f a) v\n        # isvalue_like v}.\n\nDefinition of_type_int_to_val_TO_int {o} lib (F : @NTerm o) :=\n  forall f,\n    of_type_int_to_val lib f\n    -> {z : Z & reduces_to lib (mk_apply F f) (mk_integer z)}.\n*)\n\n\nDefinition value_like_type {o} lib (T : @CTerm o) :=\n  forall t, member lib t T -> isvaluec_like t.\n\nDefinition agree_upto_b_c {o} lib (b f g : @CTerm o) :=\n  forall (t : CTerm),\n    member lib (absolute_value_c t) (mkc_natk b) (* take t's absolute value *)\n    -> equality lib (mkc_apply f t) (mkc_apply g t) mkc_int.\n\nDefinition continuous2 {o} lib (F : @CTerm o) :=\n  forall f,\n    member lib f (mkc_fun mkc_int mkc_int)\n    -> {b : CTerm\n        & member lib b mkc_tnat\n        # forall g : CTerm,\n            member lib g (mkc_fun mkc_int mkc_int)\n            -> agree_upto_b_c lib b f g\n            -> equality lib (mkc_apply F f) (mkc_apply F g) mkc_int}.\n\nDefinition agree_upto_b_type_c {o} (b f g : @CTerm o) : CTerm :=\n  mkc_isect\n    (mkc_set\n       mkc_int\n       nvarx\n       (mkcv_member\n          [nvarx]\n          (absolute_value_cv [nvarx] (mkc_var nvarx))\n          (mkcv_natk [nvarx] (mk_cv [nvarx] b))))\n    nvarx\n    (mkcv_equality\n       [nvarx]\n       (mkcv_apply [nvarx] (mk_cv [nvarx] f) (mkc_var nvarx))\n       (mkcv_apply [nvarx] (mk_cv [nvarx] f) (mkc_var nvarx))\n       (mkcv_int [nvarx])).\n\nDefinition agree_upto_b_type_cv {o} vs (b f g : @CVTerm o vs) : CVTerm vs :=\n  mkcv_isect\n    vs\n    (mkcv_set\n       vs\n       (mkcv_int vs)\n       nvarx\n       (mkcv_member\n          (nvarx :: vs)\n          (absolute_value_cv (nvarx :: vs) (mk_cv_app_r vs [nvarx] (mkc_var nvarx)))\n          (mkcv_natk (nvarx :: vs) (mk_cv_app_l [nvarx] vs b))))\n    nvarx\n    (mkcv_equality\n       (nvarx :: vs)\n       (mkcv_apply (nvarx :: vs) (mk_cv_app_l [nvarx] vs f) (mk_cv_app_r vs [nvarx] (mkc_var nvarx)))\n       (mkcv_apply (nvarx :: vs) (mk_cv_app_l [nvarx] vs g) (mk_cv_app_r vs [nvarx] (mkc_var nvarx)))\n       (mkcv_int (nvarx :: vs))).\n\nDefinition continuous_type_c {o} (F f : @CTerm o) :=\n  mkc_product\n    mkc_tnat\n    nvarb\n    (mkcv_isect\n       [nvarb]\n       (mkcv_fun [nvarb] (mkcv_int [nvarb]) (mkcv_int [nvarb]))\n       nvarg\n       (mkcv_ufun\n          [nvarg, nvarb]\n          (agree_upto_b_type_cv\n             [nvarg,nvarb]\n             (mk_cv_app_l [nvarg] [nvarb] (mkc_var nvarb))\n             (mk_cv [nvarg,nvarb] f)\n             (mk_cv_app_r [nvarb] [nvarg] (mkc_var nvarg)))\n          (mkcv_equality\n             [nvarg,nvarb]\n             (mkcv_apply [nvarg,nvarb] (mk_cv [nvarg,nvarb] F) (mk_cv [nvarg,nvarb] f))\n             (mkcv_apply [nvarg,nvarb] (mk_cv [nvarg,nvarb] F) (mk_cv_app_r [nvarb] [nvarg] (mkc_var nvarg)))\n             (mkcv_int [nvarg,nvarb])))).\n\nDefinition continuous_type_aux {o} vb vg vi (F f : @NTerm o) :=\n  mk_product\n    mk_tnat\n    vb\n    (mk_isect\n       int2int\n       vg\n       (mk_ufun\n          (agree_upto_b_type\n             vi\n             (mk_var vb)\n             f\n             (mk_var vg))\n          (mk_equality\n             (mk_apply F f)\n             (mk_apply F (mk_var vg))\n             mk_int))).\n\nDefinition continuous_type {o} (F f : @NTerm o) :=\n  match newvars3 [F,f] with\n    | (vb,vg,vi) => continuous_type_aux vb vg vi F f\n  end.\n\nLemma lsubstc_continuous_type {o} :\n  forall (F f : @NTerm o)\n         (w : wf_term (continuous_type F f))\n         (s : CSub)\n         (c : cover_vars (continuous_type F f) s),\n    {wF : wf_term F\n     & {wf : wf_term f\n     & {cF : cover_vars F s\n     & {cf : cover_vars f s\n     & alphaeqc\n         (lsubstc (continuous_type F f) w s c)\n         (continuous_type_c (lsubstc F wF s cF) (lsubstc f wf s cf))}}}}.\nProof.\n  introv.\n\n  assert (wf_term F # wf_term f) as wf.\n  { unfold continuous_type in w.\n    remember (newvars3 [F,f]) as p.\n    destruct p as [p vi].\n    destruct p as [vb vg].\n    apply newvars3_prop in Heqp.\n    allsimpl; allrw app_nil_r; allrw in_app_iff; allrw not_over_or; repnd.\n    apply wf_product_iff in w; repnd.\n    apply wf_isect_iff in w; repnd.\n    apply wf_ufun in w; repnd.\n    apply wf_equality_iff in w; repnd.\n    apply wf_apply_iff in w3; repnd; auto. }\n\n  destruct wf as [wF wf].\n  exists wF wf.\n\n  assert (cover_vars F s # cover_vars f s) as cov.\n  { unfold continuous_type in c.\n    remember (newvars3 [F,f]) as p.\n    destruct p as [p vi].\n    destruct p as [vb vg].\n    apply newvars3_prop in Heqp.\n    allsimpl; allrw app_nil_r; allrw in_app_iff; allrw not_over_or; repnd.\n    apply cover_vars_product in c; repnd.\n    apply cover_vars_upto_isect in c; repnd.\n    apply cover_vars_upto_ufun in c; repnd.\n    apply cover_vars_upto_equality in c; repnd.\n    apply cover_vars_upto_apply in c3; repnd.\n    allrw <- @csub_filter_app_r; allsimpl.\n    apply cover_vars_upto_csub_filter_disjoint in c5;\n      [|rw eqvars_prop; simpl; sp; split; sp\n       |allrw disjoint_cons_r; sp].\n    apply cover_vars_upto_csub_filter_disjoint in c3;\n      [|rw eqvars_prop; simpl; sp; split; sp\n       |allrw disjoint_cons_r; sp].\n    sp. }\n\n  destruct cov as [cF cf].\n  exists cF cf.\n\n  unfold alphaeqc; simpl.\n  unfold csubst, lsubst.\n  allrw <- @sub_free_vars_is_flat_map_free_vars_range.\n  allrw @sub_free_vars_csub2sub; boolvar; tcsp;\n  try (complete (destruct n; tcsp)).\n\n  simpl.\n  allrw @sub_filter_nil_r.\n  allrw <- @sub_filter_app_r; simpl.\n  allrw @sub_find_sub_filter; simpl; tcsp.\n  repeat gen_newvar.\n  fold_terms.\n\n  allrw @lsubst_aux_sub_filter;\n    try (complete (repeat get_newvar_prop; allsimpl;\n                   allrw remove_nvars_nil_l; allrw app_nil_r;\n                   allrw in_app_iff; allrw not_over_or; repnd;\n                   allrw disjoint_cons_r; sp)).\n\n  fold_terms.\n  unfold mk_natk.\n  fold (@mk_natk_aux o n1 (mk_var n)).\n  allfold (@mk_tnat o).\n  allfold (@int2int o).\n  pose proof (newvar_not_in_free_vars (@mk_var o nvarb)) as nve; simpl in nve.\n  autodimp nve hyp;[intro k; repndors; tcsp; ginv|rw nve; clear nve].\n  fold (agree_upto_b_type n1 (mk_var n) (lsubst_aux f (csub2sub s)) (mk_var n0)).\n  fold (agree_upto_b_type nvarx (mk_var nvarb) (lsubst_aux f (csub2sub s)) (mk_var nvarg)).\n  fold (continuous_type_aux_aux n n0 n1 n5 (lsubst_aux F (csub2sub s)) (lsubst_aux f (csub2sub s))).\n  unfold mk_ufun.\n  gen_newvar.\n  fold (continuous_type_aux_aux nvarb nvarg nvarx n6 (lsubst_aux F (csub2sub s)) (lsubst_aux f (csub2sub s))).\n  clear dependent n2.\n  clear dependent n3.\n  clear dependent n4.\n\n  apply alphaeq_eq.\n  repeat get_newvar_prop.\n  allsimpl; allrw remove_nvars_nil_l; allrw app_nil_r.\n  allrw in_app_iff; allsimpl; allrw not_over_or; repnd; GC.\n  apply alphaeq_continuous_type_aux_aux; tcsp;\n  try (complete (apply cover_vars_iff_closed_lsubst_aux; auto));\n  try (complete (intro k; inversion k)).\nQed.\n\nTactic Notation \"one_lift_lsubst_cont\" constr(T) ident(name) tactic(tac) :=\n  match T with\n    | context [lsubstc (continuous_type ?a ?b) ?w ?s ?c] =>\n      let w1 := fresh \"w1\" in\n      let w2 := fresh \"w2\" in\n      let c1 := fresh \"c1\" in\n      let c2 := fresh \"c2\" in\n      pose proof (lsubstc_continuous_type a b w s c) as name;\n        destruct name as [w1 name];\n        destruct name as [w2 name];\n        destruct name as [c1 name];\n        destruct name as [c2 name];\n        clear_irr; tac\n  end.\n\nLtac one_lift_lsubst_cont_concl :=\n  match goal with\n    | [ |- ?T ] =>\n      let name := fresh \"eq\" in\n      one_lift_lsubst_cont\n        T\n        name\n        (first [ rewrite name\n               | progress (apply alphaeqc_sym in name; rwal_c name)\n               ]);\n        clear name\n  end.\n\nLtac one_lift_lsubst_cont_hyp H :=\n  let T := type of H in\n  let name := fresh \"eq\" in\n  one_lift_lsubst_cont\n    T name\n    (first [ rewrite name in H\n           | progress (rwal_h name H)\n           ]); clear name.\n\nLtac lift_lsubsts_cont :=\n  repeat (match goal with\n            | [ H : context [lsubstc _ _ _ _ ] |- _ ] => one_lift_lsubst_cont_hyp H\n            | [ |- context [lsubstc _ _ _ _ ] ] => one_lift_lsubst_cont_concl\n          end).\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/continuity/continuity_type.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.274965688166029}}
{"text": "(* Disable notation conflict warnings *)\nSet Warnings \"-notation-overridden\".\n\nFrom Coq Require Import ssreflect ssrfun ssrbool.\nRequire Import Psatz.\nRequire Import Coq.Lists.List.\nRequire Import Coq.NArith.BinNat.\nImport ListNotations.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Coq.Classes.Morphisms.\nRequire Import SetoidList.\nRequire Import Coq.Logic.ProofIrrelevance.\n\nRequire Import GHC.Base.\n\nRequire Import Proofs.Prelude.\n\nRequire Import CoreFVs.\nRequire Import Id.\nRequire Import Core.\nRequire UniqFM.\n\nRequire Import Proofs.Base.\nRequire Import Proofs.Axioms.\nRequire Import Proofs.ContainerProofs.\nRequire Import Proofs.GhcTactics.\nRequire Import Proofs.Unique.\nRequire Import Proofs.Var.\nRequire Import Proofs.VarSetFSet.\n\n\nOpen Scope Z_scope.\n\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nSet Bullet Behavior \"Strict Subproofs\".\n\n\nLemma IntMapEq_VarSetEq : forall x y,\n    x == y ->\n    UniqSet.Mk_UniqSet (UniqFM.UFM x) [=] UniqSet.Mk_UniqSet (UniqFM.UFM y).\nProof.\n  intros. constructor.\n  - unfold In. simpl. intros.\n    eapply IntMap.Eq_membership in H.\n    erewrite H0 in H. symmetry. move /Eq_eq in H. assumption.\n  - unfold In. simpl. intros.\n    eapply IntMap.Eq_membership in H.\n    erewrite H0 in H. move /Eq_eq in H. assumption.\nQed.\n\n(* Stephanie's hack. *)\nLemma fold_is_true : forall b, b = true <-> b.\nProof. intros. unfold is_true. reflexivity. Qed.\n\nLemma false_is_not_true :\n  forall b, b = false <-> b <> true.\nProof.\n  destruct b; intuition.\nQed.\n\n(* Why is this not part of ssr? *)\nLemma eqE : forall (a b:bool), a = b <-> (a <-> b).\nProof.  \n  move=> a b.\n  elim Ea: a;\n  elim Eb: b;\n  try tauto.\n  intuition.\n  symmetry.\n  rewrite fold_is_true.\n  apply H0. auto.\n  intuition.\nQed.\n\nLemma andE a b : a && b <-> a /\\ b.\nProof. \n  elim: a; elim: b; try tauto.\n  split; move=> /andP; try done. \n  split; move=> /andP; try done. \nQed.\n\nLemma orE : forall a b, (a || b) <-> a \\/ b.\nProof. intros a b. unfold is_true. rewrite orb_true_iff. tauto. Qed.\n\nLemma notE : forall a, ~~a <-> ~ a.\nProof. move=>a. unfold is_true. rewrite negb_true_iff. \nsplit. move=>h. rewrite h. auto.\napply not_true_is_false.\nQed.\n\n\n\n(** ** NOTE: VarSets and equality *)\n\n(* VarSets have several different notions of equality. \n   In all three definitions, equal varsets must have the same domain. \n   Now suppose:\n       lookupVarSet m1 x = Some v1 and\n       lookupVarSet m2 x = Some v2\n   The sets are equal when:\n    - v1 = v2                (i.e. coq equality) \n    - almostEqual v1 v2      \n    - v1 == v2               (i.e. same uniques ONLY)\n\n   The last (coarsest) equality is the one used in the FSet signature, \n   and denoted by the [=] notation. \n\n   The almostEqual equality is denoted by {=}.\n\n   Because of this distinction, we have to do some lemmas twice: once \n   for [=] equality, and once for {=} equality.\n  \n*)\n\n\n(** ** VarSet operations respect GHC.Base.==  *)\n\nLemma elemVarSet_eq : forall v1 v2 vs,\n  (v1 == v2) -> \n  elemVarSet v1 vs = elemVarSet v2 vs.\nProof.\n  intros v1 v2 vs h.\n  unfold elemVarSet, UniqSet.elementOfUniqSet.\n  destruct vs.\n  unfold UniqFM.elemUFM.\n  destruct getUniqSet'.\n  move: h.\n  rewrite eq_unique.\n  move=> h.\n  f_equal.\n  auto.\nQed.\n\nLemma lookupVarSet_eq :\n  forall v1 v2 vs,\n    (v1 == v2) ->\n    lookupVarSet vs v1 = lookupVarSet vs v2.\nProof. \n  intros v1 v2 vs.\n  unfold lookupVarSet.\n  unfold UniqSet.lookupUniqSet.\n  destruct vs.\n  unfold UniqFM.lookupUFM.\n  destruct getUniqSet'.\n  intro h.\n  rewrite -> eq_unique in h.\n  rewrite h.\n  reflexivity.\nQed.\n\nLemma extendVarSet_eq : \n  forall x y vs, x == y -> extendVarSet vs x [=] extendVarSet vs y.\nProof.\n  move => x y vs Eq.\n  set_b_iff.\n  move: (add_m) => h.\n  unfold Proper,respectful in h.\n  apply h.\n  assumption.\n  reflexivity.\nQed.\n\n\nLemma delVarSet_eq : \n  forall x y vs, x == y -> delVarSet vs x = delVarSet vs y.\nProof.\n  move => x y vs Eq.\n  unfold delVarSet.\n  move: vs => [i].\n  move: i => [m].\n  rewrite -> eq_unique in Eq.\n  unfold UniqSet.delOneFromUniqSet.\n  unfold UniqFM.delFromUFM.\n  rewrite Eq.\n  reflexivity.\nQed.\n\n\n\n\n\n\n(** ** List based operations in terms of folds *)\n\nLemma extendVarSetList_foldl' : forall x xs, \n    extendVarSetList x xs = Foldable.foldl' (fun x y => add y x) x xs.\nProof.\n  intros.\n  unfold extendVarSetList, UniqSet.addListToUniqSet;\n  replace UniqSet.addOneToUniqSet with \n      (fun x y => add y x).\n  auto.\n  auto.\nQed.\n\nLemma delVarSetList_foldl : forall vl vs,\n    delVarSetList vs vl = Foldable.foldl delVarSet vs vl.\nProof. \n  induction vl.\n  - intro vs. \n    destruct vs. destruct getUniqSet'.\n    unfold_Foldable_foldl.\n    simpl.\n    auto.\n  - intro vs. \n    unfold delVarSetList in *.\n    unfold UniqSet.delListFromUniqSet in *.\n    destruct vs.\n    unfold UniqFM.delListFromUFM in *.\n    revert IHvl.\n    unfold_Foldable_foldl.\n    simpl.\n    intro IHvl.\n    rewrite (IHvl (UniqSet.Mk_UniqSet (UniqFM.delFromUFM getUniqSet' a))).\n    auto.\nQed.\n\n\nLemma mkVarSet_extendVarSetList : forall xs,\n    mkVarSet xs = extendVarSetList emptyVarSet xs.\nProof.\n  reflexivity.\nQed.\n\n\nHint Rewrite mkVarSet_extendVarSetList : hs_simpl.\n\n\n(** ** [lookupVarSet] and [elemVarSet] correspondence *)\n\nLemma lookupVarSet_In:\n  forall vs v, (exists v', lookupVarSet vs v = Some v') <-> In v vs.\nProof.\n  unfold lookupVarSet, UniqSet.lookupUniqSet,\n    UniqFM.lookupUFM, Unique.getWordKey, Unique.getKey.\n  intros.\n  destruct vs.\n  destruct getUniqSet'.\n  destruct (Unique.getUnique v) as [n] eqn:Hv.\n  unfold In, elemVarSet, UniqSet.elementOfUniqSet,\n  UniqFM.elemUFM, Unique.getKey, Unique.getWordKey,\n  Unique.getKey.\n  rewrite Hv.\n  rewrite <- member_lookup.\n  reflexivity.\nQed.\n\nLemma lookupVarSet_elemVarSet : \n  forall v1 v2 vs, lookupVarSet vs v1 = Some v2 -> elemVarSet v1 vs.\nProof.\n  intros.\n  unfold lookupVarSet, elemVarSet in *.\n  unfold UniqSet.lookupUniqSet, UniqSet.elementOfUniqSet in *.\n  destruct vs.\n  unfold UniqFM.lookupUFM, UniqFM.elemUFM in *.\n  destruct getUniqSet'. \n  set (key := Unique.getWordKey (Unique.getUnique v1)) in *.\n  rewrite member_lookup.\n  exists v2. auto.\nQed.\n\nLemma lookupVarSet_None_elemVarSet: \n  forall v1 vs, lookupVarSet vs v1 = None <-> elemVarSet v1 vs = false.\nProof.\n  intros.\n  unfold lookupVarSet, elemVarSet in *.\n  unfold UniqSet.lookupUniqSet, UniqSet.elementOfUniqSet in *.\n  destruct vs.\n  unfold UniqFM.lookupUFM, UniqFM.elemUFM in *.\n  destruct getUniqSet'.\n  set (key := Unique.getWordKey (Unique.getUnique v1)) in *.\n  rewrite non_member_lookup.\n  intuition.\nQed.\n\nLemma elemVarSet_lookupVarSet :\n  forall v1 vs, elemVarSet v1 vs -> exists v2, lookupVarSet vs v1 = Some v2.\nProof.\n  intros.\n  unfold lookupVarSet, elemVarSet in *.\n  unfold UniqSet.lookupUniqSet, UniqSet.elementOfUniqSet in *.\n  destruct vs.\n  unfold UniqFM.lookupUFM, UniqFM.elemUFM in *.\n  destruct getUniqSet'.\n  set (key := Unique.getWordKey (Unique.getUnique v1)) in *.\n  rewrite <- member_lookup.\n  auto.\nQed.\n\n(** ** [lookupVarSet] is Proper  *)\n\nInstance lookupVarSet_m : \n  Proper (Equal ==> (fun x y => x == y) ==> (fun x y => x == y)) lookupVarSet.\nProof.\n  unfold Equal.\n  intros x y H v1 v2 EV.\n  erewrite lookupVarSet_eq; eauto.\n  pose (h1 := H v1).\n  pose (h2 := H v2).\n  repeat rewrite -> mem_iff in h1.\n  repeat rewrite -> mem_iff in h2.\n  destruct (lookupVarSet x v2) eqn:LX;\n  destruct (lookupVarSet y v2) eqn:LY;\n  hs_simpl.\n  - apply ValidVarSet_Axiom in LX.\n    apply ValidVarSet_Axiom in LY.\n    eapply Eq_trans.\n    rewrite Eq_sym.\n    eapply LX.\n    eapply LY.\n  - apply lookupVarSet_elemVarSet in LX.\n    rewrite -> lookupVarSet_None_elemVarSet in LY.\n    set_b_iff.\n    intuition.\n  - apply lookupVarSet_elemVarSet in LY.\n    rewrite -> lookupVarSet_None_elemVarSet in LX.\n    set_b_iff.\n    intuition.\n  - auto.\nQed.\n\n\n(** ** [lookupVarSet . extendVarSet ] simplification *)\n\nLemma lookupVarSet_extendVarSet_self:\n  forall v vs,\n  lookupVarSet (extendVarSet vs v) v = Some v.\nProof.\n  intros.\n  unfold lookupVarSet, extendVarSet in *.\n  unfold UniqSet.lookupUniqSet, UniqSet.addOneToUniqSet in *.\n  destruct vs.\n  unfold UniqFM.lookupUFM, UniqFM.addToUFM in *.\n  destruct getUniqSet'.\n  set (key := Unique.getWordKey (Unique.getUnique v)) in *.\n  apply lookup_insert.\nQed.\n\nHint Rewrite lookupVarSet_extendVarSet_self : hs_simpl.\n\nLemma lookupVarSet_extendVarSet_eq :\n      forall v1 v2 vs,\n      v1 == v2  ->\n      lookupVarSet (extendVarSet vs v1) v2 = Some v1.\nProof.\n  intros v1 v2 vs H.\n  rewrite Eq_sym in H.\n  rewrite (lookupVarSet_eq _ H).\n  unfold lookupVarSet, extendVarSet.\n  unfold UniqSet.lookupUniqSet, UniqSet.addOneToUniqSet.\n  destruct vs.\n  unfold UniqFM.lookupUFM, UniqFM.addToUFM.\n  destruct getUniqSet'.\n  set (k1 := Unique.getWordKey (Unique.getUnique v1)).\n  rewrite lookup_insert.\n  reflexivity.\nQed.\n\nLemma lookupVarSet_extendVarSet_neq :\n      forall v1 v2 vs,\n      not (v1 == v2) ->\n      lookupVarSet (extendVarSet vs v1) v2 = lookupVarSet vs v2.\nProof.\n  intros v1 v2 vs H.\n  assert (Unique.getWordKey (Unique.getUnique v1) <> \n          Unique.getWordKey (Unique.getUnique v2)).\n  { intro h.\n    eapply H.\n    rewrite eq_unique.\n    auto.\n  }\n  unfold lookupVarSet, extendVarSet.\n  unfold UniqSet.lookupUniqSet, UniqSet.addOneToUniqSet.\n  destruct vs.\n  unfold UniqFM.lookupUFM, UniqFM.addToUFM.\n  destruct getUniqSet'.\n  eapply lookup_insert_neq.\n  auto.\nQed.\n\n\n(* --------------------------------- *)\n\n(* Tactics that don't really work. *)\n                                   \nLocal Ltac unfold_VarSet_to_IntMap :=\n  repeat match goal with\n         | [vs : VarSet |- _ ] =>\n           let u := fresh \"u\" in\n           destruct vs as [u]; destruct u; simpl\n         | [ |- UniqSet.Mk_UniqSet _ = UniqSet.Mk_UniqSet _ ] =>\n           f_equal\n         | [ |- UniqFM.UFM _ = UniqFM.UFM _ ] =>\n           f_equal\n         end.\n\n(*\n(* Q: is there a way to do the automatic destructs safely? Sometimes \n   loses too much information. *)\n\nLtac unfold_VarSet :=\n  unfold subVarSet,elemVarSet, isEmptyVarSet, \n         minusVarSet, extendVarSet, extendVarSetList in *;\n  unfold UniqSet.elementOfUniqSet, \n         UniqSet.isEmptyUniqSet, \n         UniqSet.addOneToUniqSet,\n         UniqSet.minusUniqSet,\n         UniqSet.addListToUniqSet in *;\n  try repeat match goal with\n  | vs: VarSet, H : context[match ?vs with _ => _ end]  |- _ => destruct vs\n  end;\n  try repeat match goal with\n  | vs: VarSet |- context[match ?vs with _ => _ end ] => destruct vs\n  end;\n\n  unfold UniqFM.addToUFM, \n         UniqFM.minusUFM, UniqFM.isNullUFM, \n         UniqFM.elemUFM in *;\n  try repeat match goal with\n  | u: UniqFM.UniqFM ?a, H : context[match ?u with _ => _ end]  |- _ => destruct u\n  end;\n  try repeat match goal with\n  | u: UniqFM.UniqFM ?a |- context[match ?u with _ => _ end] => destruct u\n  end. \n\nLtac safe_unfold_VarSet :=\n  unfold subVarSet,elemVarSet, isEmptyVarSet, \n         minusVarSet, extendVarSet, extendVarSetList in *;\n  unfold UniqSet.elementOfUniqSet, \n         UniqSet.isEmptyUniqSet, \n         UniqSet.addOneToUniqSet,\n         UniqSet.minusUniqSet,\n         UniqSet.addListToUniqSet in *;\n  unfold UniqFM.addToUFM, \n         UniqFM.minusUFM, UniqFM.isNullUFM, \n         UniqFM.elemUFM in *. *)\n\n(**************************************)\n\n(** ** [extendVarSetList] simplifications *)\n\nLemma extendVarSetList_nil:\n  forall s,\n  extendVarSetList s [] = s.\nProof.\n  intro s.\n  reflexivity.\nQed.\n\nLemma extendVarSetList_cons:\n  forall s v vs,\n  extendVarSetList s (v :: vs) = extendVarSetList (extendVarSet s v) vs.\nProof.\n  intros.\n  rewrite extendVarSetList_foldl'.\n  autorewrite with hs_simpl.\n  reflexivity.\nQed.\n\nLemma extendVarSetList_singleton:\n  forall vs v, extendVarSetList vs [v] = extendVarSet vs v.\nProof. intros. reflexivity. Qed.\n\n\nLemma extendVarSetList_append:\n  forall s vs1 vs2,\n  extendVarSetList s (vs1 ++ vs2) = extendVarSetList (extendVarSetList s vs1) vs2.\nProof.\n  intros.\n  rewrite extendVarSetList_foldl'.\n  autorewrite with hs_simpl.\n  reflexivity.\nQed.\n\nHint Rewrite extendVarSetList_nil \n             extendVarSetList_cons\n             extendVarSetList_singleton\n             extendVarSetList_append : hs_simpl.\n\n\n\n(** ** [delVarSetList] simplification  *)\n\nLemma delVarSetList_nil:\n  forall e, delVarSetList e [] = e.\nProof.\n  intros.\n  rewrite delVarSetList_foldl.\n  reflexivity.\nQed.\n\nLemma delVarSetList_single:\n  forall e a, delVarSetList e [a] = delVarSet e a.\nProof.\n  intros.\n  rewrite delVarSetList_foldl.\n  autorewrite with hs_simpl.\n  reflexivity.\nQed.\n\nLemma delVarSetList_cons:\n  forall e a vs, delVarSetList e (a :: vs) = delVarSetList (delVarSet e a) vs.\nProof.\n  intros.\n  repeat rewrite delVarSetList_foldl.\n  autorewrite with hs_simpl.\n  reflexivity.\nQed.\n\nLemma delVarSetList_app:\n  forall e vs vs', delVarSetList e (vs ++ vs') = delVarSetList (delVarSetList e vs) vs'.\nProof.\n  intros.\n  repeat rewrite delVarSetList_foldl.\n  autorewrite with hs_simpl.\n  reflexivity.\nQed.\n\nHint Rewrite delVarSetList_nil \n             delVarSetList_cons\n             delVarSetList_single\n             delVarSetList_app : hs_simpl.\n\n\n(** ** [elemVarSet] simplification *)\n\nLemma elemVarSet_emptyVarSet : forall v, (elemVarSet v emptyVarSet) = false.\n  intro v.\n  set_b_iff.\n  fsetdec.\nQed.\n\nLemma elemVarSet_unionVarSet:\n  forall v vs1 vs2,\n    elemVarSet v (unionVarSet vs1 vs2) = elemVarSet v vs1 || elemVarSet v vs2.\nProof.\n  move => v [[i]] [[i0]] /=.\n  rewrite member_union.\n  auto.\nQed.\n\nHint Rewrite elemVarSet_emptyVarSet elemVarSet_unionVarSet : hs_simpl.\n\n\n(** ** [extendVarSet]  *)\n\nLemma extendVarSet_elemVarSet_true : forall set v, \n    elemVarSet v set -> extendVarSet set v [=] set.\nProof. \n  intros.\n  apply add_equal.\n  auto.\nQed.\n\n\nLemma elemVarSet_extendVarSet:\n  forall v vs v',\n  elemVarSet v (extendVarSet vs v') = (v' == v) || elemVarSet v vs.\nProof.\n  intros.\n  rewrite var_eq_realUnique.\n  replace (realUnique v' == realUnique v)%N with \n      (F.eqb v' v). \n\n  eapply F.add_b.\n  unfold F.eqb.\n  cbn.\n  destruct F.eq_dec.\n  - unfold Var_as_DT.eq in e.\n    rewrite <- realUnique_eq in e; auto.\n  - unfold Var_as_DT.eq in n.\n    rewrite <- realUnique_eq in n; apply not_true_is_false in n; auto.\nQed.\n\nHint Rewrite elemVarSet_extendVarSet : hs_simpl.\n\nLemma elemVarSet_extendVarSetList:\n  forall v vs vs',\n  elemVarSet v (extendVarSetList vs vs') = Foldable.elem v vs' || elemVarSet v vs.\nProof.\n  intros.\n  generalize vs.\n  induction vs'.\n  + intros vs0. hs_simpl.\n    simpl.\n    auto.\n  + intros vs0. hs_simpl.\n    rewrite IHvs'.\n    hs_simpl.\n    rewrite Eq_sym.\n    ssrbool.bool_congr.\n    reflexivity.\nQed.\n\nHint Rewrite elemVarSet_extendVarSetList : hs_simpl.\n\nLemma extendVarSet_commute : forall x y vs, \n    extendVarSet (extendVarSet vs y) x  [=] extendVarSet (extendVarSet vs x) y.\nProof.\n  intros.\n  set_b_iff.\n  fsetdec.\nQed.\n\n\n\n(** ** [extendVarSetList] and [delVarSetList] are Proper **)\n\n(* These lemmas show that extendVarSetList respects [=] *)\n\nLemma extendVarSetList_iff : forall l x vs,\n  In x (extendVarSetList vs l) <->\n  In x vs \\/ Foldable.elem x l.\nProof.\n  induction l.\n  - intros x vs.\n    hs_simpl.\n    intuition.\n    inversion H0.\n  - intros x vs.\n    hs_simpl.\n    rewrite IHl.\n    set_b_iff.\n    rewrite add_iff.\n    unfold Var_as_DT.eqb.\n    rewrite Eq_sym.\n    rewrite orE.\n    intuition.\nQed.\n\nLemma delVarSetList_iff : forall l x vs,\n  In x (delVarSetList vs l) <->\n  In x vs /\\ ~ (Foldable.elem x l).\nProof.\n  induction l.\n  - intros x vs. \n    hs_simpl.\n    intuition.\n  - intros x vs.\n    hs_simpl.\n    rewrite IHl.\n    rewrite delVarSet_remove. rewrite remove_iff.\n    unfold Var_as_DT.eqb.\n    rewrite Eq_sym.\n    rewrite orE.\n    intuition.\nQed.\n\nInstance extendVarSetList_m : \n  Proper (Equal ==> (eqlistA (fun x y => x == y)) ==> Equal) extendVarSetList.\nProof.\n  unfold Equal.\n  intros x y H s s' H0 a.\n  do 2 rewrite extendVarSetList_iff.\n  rewrite H.\n  intuition; right.\n  erewrite <- eqlist_Foldable_elem; eauto.\n  eapply EqLaws_Var.\n  erewrite eqlist_Foldable_elem; eauto.\n  eapply EqLaws_Var.\nQed.\n\nInstance delVarSetList_m : \n  Proper (Equal ==> (eqlistA (fun x y => x == y)) ==> Equal) delVarSetList.\nProof.\n  unfold Equal.\n  intros x y H s s' H0 a.\n  do 2 rewrite delVarSetList_iff.\n  rewrite H.\n  intuition.\n  apply H3.\n  erewrite eqlist_Foldable_elem; eauto using EqLaws_Var.\n  apply H3.\n  erewrite <- eqlist_Foldable_elem; eauto using EqLaws_Var.\nQed.\n\nInstance delVarSet_m : \n  Proper (Equal ==> (fun x y => x == y) ==> Equal) delVarSet.\nProof.\n  intros x y H s s' H0 a.\n  replace (delVarSet x s) with (delVarSetList x [s]).\n  replace (delVarSet y s') with (delVarSetList y [s']).\n  assert (eqlistA (_==_) [s] [s']).\n  { constructor; [assumption|constructor]. }\n  rewrite H. rewrite H1. reflexivity.\n  rewrite delVarSetList_cons delVarSetList_nil //=. \n  rewrite delVarSetList_cons delVarSetList_nil //=.\nQed.\n\n(* We can commute the order of addition to varsets. \n   This is only true for [=] *)\nLemma extendVarSetList_extendVarSet_iff: forall l x vs,\n  extendVarSetList (extendVarSet vs x) l [=]\n  extendVarSet (extendVarSetList vs l) x.\nProof.\n  induction l.\n  - intros.\n    hs_simpl.\n    reflexivity.\n  - intros.\n    hs_simpl.\n    rewrite extendVarSet_commute.\n    rewrite IHl.\n    reflexivity.\nQed.\n\n\nLemma elemVarSet_extend_add : forall v s vs a,\n  elemVarSet v (extendVarSetList s vs) ->\n  elemVarSet v (extendVarSetList (add a s) vs).\nProof. \n  intros v s vs a.\n  rewrite InE.\n  rewrite InE.\n  rewrite extendVarSetList_iff.\n  rewrite extendVarSetList_iff.\n  intuition.\n  left.\n  fsetdec.\nQed.\n\nLemma elemVarSet_extendVarSetList_r:\n  forall v s vs,\n  elemVarSet v (mkVarSet vs)  ->\n  elemVarSet v (extendVarSetList s vs) .\nProof.\n  intros v s vs.\n  rewrite mkVarSet_extendVarSetList.\n  rewrite InE.\n  rewrite InE.\n  rewrite extendVarSetList_iff.\n  rewrite extendVarSetList_iff.\n  intuition.\nQed.\n\n\nLemma elemVarSet_mkVarSet_cons:\n  forall v v' vs,\n  elemVarSet v (mkVarSet (v' :: vs)) = false\n  <-> (v' == v) = false /\\ elemVarSet v (mkVarSet vs) = false.\nProof.\n  intros v v' vs.\n  rewrite mkVarSet_extendVarSetList.\n  rewrite extendVarSetList_cons.\n  rewrite mkVarSet_extendVarSetList.\n  rewrite <- not_mem_iff.\n  rewrite <- not_mem_iff.\n  rewrite extendVarSetList_iff.\n  rewrite extendVarSetList_iff.\n  set_b_iff.\n  rewrite add_iff.\n  unfold Var_as_DT.eqb.\n  intuition.\n  apply not_true_is_false.\n  unfold not. auto.\n  destruct H.\n  rewrite H1 in H0.\n  done.\nQed.\n\n\n(* ** Properties about [lookupVarSet (extendVarSetList vs vars) v]\n\n   Note, we can specify what happens when v is an Foldable.elem of vars with\n   varying degrees of precision. When we lookup v, we won't get [Some v]\n   exactly, but we will get something == to v, and that was the most recently\n   added var in vars.\n   \n*)\n\n\nLemma lookupVarSet_extendVarSetList_false:\n  forall (vars:list Var) v vs,\n    ~~ (Foldable.elem v vars ) -> \n    lookupVarSet (extendVarSetList vs vars) v = lookupVarSet vs v.\nProof.\n  elim=> [|x xs IH] //.   (* // is try done. *)\n  - move => v vs.\n    hs_simpl.\n    rewrite negb_or.     (* de morgan law to push ~~ in *)\n    move => /andP [h1 h2]. (* split && into two hypotheses *)\n    rewrite IH //.\n    rewrite lookupVarSet_extendVarSet_neq //.\n    rewrite Eq_sym. by apply /negP.\nQed.\n\n\nLemma lookupVarSet_extendVarSetList_l\n  v vs vars :\n  ~~ elemVarSet v (mkVarSet vars) ->\n  lookupVarSet (extendVarSetList vs vars) v = lookupVarSet vs v.\nProof.\n  hs_simpl.\n  elim: vars vs => [|a vars IH] vs //.\n  hs_simpl.\n\n  rewrite negb_orb => /andP [? ?].\n\n  rewrite lookupVarSet_extendVarSetList_false //.\n  rewrite lookupVarSet_extendVarSet_neq //.\n\n  apply /negP.\n  rewrite Eq_sym //. \nQed.\n\n\nLemma lookupVarSet_extendVarSetList_self_in:\n  forall (vars:list Var) v vs,\n    List.In v vars -> \n    NoDup (map varUnique vars) -> \n    lookupVarSet (extendVarSetList vs vars) v = Some v.\nProof.\n  induction vars.\n  - intros v vs H.\n    inversion H.\n  - intros v vs H ND.\n    hs_simpl.\n    simpl in ND.\n    inversion ND. subst.\n    inversion H; subst.\n    + rewrite lookupVarSet_extendVarSetList_false.\n      by hs_simpl.\n      apply /negP.\n      by rewrite -In_varUnique_elem.\n    + eauto. \nQed.      \n\n\nLemma lookupVarSet_extendVarSetList_self:\n  forall (vars:list Var) v vs,\n    (Foldable.elem v vars) -> \n    lookupVarSet (extendVarSetList vs vars) v == Some v.\nProof.\n  induction vars.\n  - intros v vs H.\n    rewrite elem_nil in H.\n    done.\n  - intros v vs H.\n    rewrite elem_cons in H.\n    hs_simpl.\n    rewrite -> orE in H.\n    elim: H.\n    move => H.\n    destruct (Foldable.elem v vars) eqn:Hv.\n    + specialize (IHvars v (extendVarSet vs a)).\n      unfold is_true in *.\n      apply IHvars. \n      done.\n    + rewrite (lookupVarSet_eq _ H).\n      rewrite lookupVarSet_extendVarSetList_false.\n      rewrite lookupVarSet_extendVarSet_self.\n      hs_simpl.\n      symmetry. done.\n      setoid_rewrite H in Hv.\n      rewrite Hv. done.\n    + move=> h.\n      apply IHvars.\n      auto.\nQed.\n\nInductive LastIn : Var -> list Var -> Prop :=\n  | LastIn_head: forall v1 vs, \n      Foldable.elem v1 vs = false ->\n      LastIn v1 (v1 :: vs)\n  | LastIn_tail: forall v1 v2 vs,\n      LastIn v1 vs ->\n      LastIn v1 (v2 :: vs).\n\nLemma LastIn_elem : forall v vs, \n    LastIn v vs -> Foldable.elem v vs.\nProof.\n  move => v vs h. \n  induction h; hs_simpl; apply /orP. \n  left. reflexivity.\n  right. assumption.\nQed.  \n  \nLemma LastIn_inj : forall v1 v2 vs, \n    LastIn v1 vs -> v1 == v2 -> LastIn v2 vs -> v1 = v2.\nProof.    \n  move=> v1 v2 vs h. induction h.\n  - move=> eq FI.\n    inversion FI. auto. \n    subst. \n    move: (LastIn_elem H2) => h.\n    rewrite -> HSUtil.elem_resp_eq with (a:= v2) in H; try done.\n    rewrite Eq_sym. done.\n  - move=> eq FI. inversion FI.\n    subst. \n    move: (LastIn_elem h) => h0.\n    rewrite -> HSUtil.elem_resp_eq with (a:= v1) in H1; try done.\n    subst. eauto.\nQed.\n\n\n\nLemma lookupVarSet_extendVarSetList_self_exists_LastIn:\n  forall (vars:list Var) v vs,\n    (Foldable.elem v vars) -> \n    exists v', and3 (lookupVarSet (extendVarSetList vs vars) v = Some v')\n               (v == v')\n               (LastIn v' vars).\nProof.\n  elim => // a vars IH.       (* Do induction on first var, \n                                then trivially discharge goal. *)\n                          (* Then introduce names for list components *)\n  move=> v vs.\n  hs_simpl.\n\n  move => /orP [h1 | h1].  (* case analysis on boolean || *)\n\n  destruct (Foldable.elem v vars) eqn:IN. \n\n  + unfold is_true in *.\n    move: (IH v (extendVarSet vs a) IN) => [v' [p q r]].\n    exists v'; split; eauto.\n    eapply LastIn_tail. auto.\n  + rewrite lookupVarSet_extendVarSetList_false ; try by rewrite IN.\n    exists a. split; eauto.\n    rewrite lookupVarSet_extendVarSet_eq //. \n    symmetry => //.\n    eapply LastIn_head.\n    rewrite <- (elem_eq vars _ _ h1).\n    done.\n  + unfold is_true in *.\n    move: (IH v (extendVarSet vs a) h1) => [v' [p q r]].\n    exists v'; split; eauto.\n    eapply LastIn_tail. auto.\nQed.\n\n\n(*\nLemma lookupVarSet_extendVarSetList_self_exists_in:\n  forall (vars:list Var) v vs,\n    (Foldable.elem v vars) -> \n    exists v', and3 (lookupVarSet (extendVarSetList vs vars) v = Some v')\n               (v == v')\n               (List.In v' vars).\nProof.\n  elim => // a vars IH.       (* Do induction on first var, \n                                then trivially discharge goal. *)\n                          (* Then introduce names for list components *)\n  move=> v vs.\n  hs_simpl.\n\n  move => /orP [h1 | h1].  (* case analysis on boolean || *)\n\n  case IN: (Foldable.elem v vars). \n\n  all: try ( unfold is_true in * ; match goal with \n      [ H : Foldable.elem ?v ?vars = true |- _ ] =>\n        move: (IH v (extendVarSet vs a) H) => [v'[]]* ;\n        exists v'; split; eauto using in_cons\n     end ).\n\n   + rewrite lookupVarSet_extendVarSetList_false ; try by rewrite IN.\n     exists a. split; eauto.\n       rewrite lookupVarSet_extendVarSet_eq //. \n       symmetry => //.\n       eapply in_eq.\nQed.\n*)\n\n\nLemma extendVarSetList_same v vars : forall vs1 vs2 ,\n  Foldable.elem v vars ->\n  lookupVarSet (extendVarSetList  vs1 vars) v = \n  lookupVarSet (extendVarSetList vs2 vars)  v.\nProof.\n  elim: vars => // a vars IHvars. \n  - move => vs1 vs2.\n    hs_simpl.  \n    move=> /orP [h1|h2].\n    + destruct (Foldable.elem v vars) eqn:h; eauto.\n      (* ! rewrites one or more times. *)\n      rewrite !lookupVarSet_extendVarSetList_false; try (rewrite h; done).\n      rewrite !lookupVarSet_extendVarSet_eq // ; symmetry ; done.\n    + auto.\nQed.\n\n\n\n(** ** [mkVarSet]  *)\n\n\nLemma elemVarSet_mkVarset_iff_In:\n  forall v vs,\n  elemVarSet v (mkVarSet vs)  <->  List.In (varUnique v) (map varUnique vs).\nProof.\n  intros.\n  rewrite mkVarSet_extendVarSetList.\n  induction vs.\n  - hs_simpl.\n    simpl.\n    done.\n  - hs_simpl.\n    simpl map.\n    split.\n    + move /orP.        \n      rewrite -> varUnique_iff.\n      rewrite -In_varUnique_elem //. \n      move => [h1|h2] //.\n      rewrite h1.\n      apply in_eq.\n      apply in_cons => //.\n    + move => h.\n      apply /orP.\n      inversion h.\n      ++ left.\n         rewrite varUnique_iff //.\n      ++ right.\n         apply In_varUnique_elem => //.\nQed.\n\n(** ** [delVarSet]  *)\n\nLemma delVarSet_elemVarSet_false : forall v set, \n    elemVarSet v set = false -> delVarSet set v [=] set.\nintros.\nset_b_iff.\napply remove_equal.\nauto.\nQed.\n\n\nLemma delVarSet_emptyVarSet x :\n  delVarSet emptyVarSet x = emptyVarSet.\nProof.\n  unfold delVarSet, emptyVarSet.\n  unfold  UniqSet.delOneFromUniqSet , UniqSet.emptyUniqSet.\n  unfold UniqFM.delFromUFM, UniqFM.emptyUFM.\n  repeat f_equal. unfold IntMap.delete, IntMap.empty.\n  f_equal. apply proof_irrelevance.\nQed.\nHint Rewrite delVarSet_emptyVarSet : hs_simpl. \n\n\nLemma delVarSet_extendVarSet : \n  forall set v, \n    elemVarSet v set = false -> (delVarSet (extendVarSet set v) v) [=] set.\nProof.\n  intros.\n  set_b_iff.\n  apply remove_add.\n  auto.\nQed.\n\nLemma elemVarSet_delVarSet: forall v1 fvs v2,\n  elemVarSet v1 (delVarSet fvs v2) = negb (v2 == v1) && elemVarSet v1 fvs.\nProof.\n  intros.\n  destruct elemVarSet eqn:EL.\n  + symmetry.\n    apply andb_true_intro.\n    set_b_iff.\n    rewrite -> remove_iff in EL.\n    unfold Var_as_DT.eqb in EL. unfold not in EL.\n    rewrite negb_true_iff.\n    intuition.\n    apply not_true_is_false.\n    auto.\n  + symmetry.\n    apply not_true_is_false.\n    intro H.\n    apply andb_prop in H.\n    set_b_iff.\n    rewrite -> remove_iff in EL.\n    unfold Var_as_DT.eqb in *.\n    intuition.\n    rewrite -> negb_true_iff in H0.\n    apply H2.\n    intro h.\n    unfold Var_as_DT.t in *.\n    rewrite h in H0.\n    inversion H0.\nQed.\n\nHint Rewrite elemVarSet_delVarSet : hs_simpl.\n\nLemma lookupVarSet_delVarSet_neq :\n      forall v1 v2 vs,\n      not (v1 == v2) ->\n      lookupVarSet (delVarSet vs v1) v2 = lookupVarSet vs v2.\nProof.\n  intros v1 v2 vs H.\n  unfold lookupVarSet,delVarSet.\n  unfold UniqSet.lookupUniqSet, UniqSet.delOneFromUniqSet.\n  destruct vs.\n  unfold UniqFM.lookupUFM, UniqFM.delFromUFM.\n  destruct getUniqSet'.\n  assert (Unique.getWordKey (Unique.getUnique v1) <>\n          Unique.getWordKey (Unique.getUnique v2)).\n  { intro h. apply H. rewrite eq_unique. done. }\n  rewrite delete_neq.\n  auto.\n  auto.\nQed.\n\n\n\nLemma elemVarSet_delVarSet_eq x y vs :\n  (x == y) -> elemVarSet x (delVarSet vs y) = false.\nProof.\n  rewrite -> eq_unique.\n  move => Eq.\n  unfold elemVarSet, delVarSet.\n  unfold UniqSet.elementOfUniqSet, UniqSet.delOneFromUniqSet.\n  move: vs => [i].\n  move: i => [m].\n  unfold UniqFM.elemUFM, UniqFM.delFromUFM.\n  rewrite Eq.\n  set key :=  Unique.getWordKey (Unique.getUnique y).\n  move: (@delete_eq key Var m).\n  rewrite <- non_member_lookup.\n  move => h. rewrite h.\n  done.\nQed.\n\n\n(** ** [delVarSetList]  *)\n\n(* These next two rely on this strong property about the unique \n   representations of IntMaps. *)\nLemma delVarSet_commute : forall x y vs, \n    delVarSet (delVarSet vs x) y [=] delVarSet (delVarSet vs y) x.\nProof.\n  intros.\n  unfold delVarSet.\n  unfold UniqSet.delOneFromUniqSet.\n  destruct vs.\n  unfold UniqFM.delFromUFM. destruct getUniqSet'.\n  apply IntMapEq_VarSetEq.\n  eapply delete_commute; eauto.\n  apply EqLaws_Var.\nQed.\n\nLemma delVarSetList_cons2:\n  forall vs e a, delVarSetList e (a :: vs) [=] delVarSet (delVarSetList e vs) a.\nProof.\n  induction vs; intros e a1;\n  rewrite -> delVarSetList_cons in *.\n  - set_b_iff.\n    hs_simpl.\n    reflexivity.\n  - rewrite delVarSetList_cons.\n    rewrite delVarSetList_cons.\n    rewrite delVarSet_commute.\n    rewrite <- IHvs.\n    rewrite delVarSetList_cons.\n    reflexivity.\nQed.\n\nLemma delVarSetList_rev:\n  forall vs1 vs2,\n  delVarSetList vs1 (rev vs2) [=] delVarSetList vs1 vs2.\nProof.\n  induction vs2.\n  - simpl. reflexivity.\n  - simpl rev.\n    rewrite delVarSetList_cons.\n    rewrite delVarSetList_app.\n    rewrite IHvs2.\n    rewrite delVarSetList_cons.\n    rewrite delVarSetList_nil.\n    rewrite <- delVarSetList_cons2.\n    rewrite delVarSetList_cons.\n    reflexivity.\nQed.\n\n\nLemma elemVarSet_delVarSetList_false_l:\n  forall v vs vs2,\n  elemVarSet v vs = false ->\n  elemVarSet v (delVarSetList vs vs2) = false.\nProof.\n  intros.\n  revert vs H; induction vs2; intros.\n  * rewrite delVarSetList_nil.\n    assumption.\n  * rewrite delVarSetList_cons.\n    apply IHvs2.\n    set_b_iff; fsetdec.\nQed.\n\nLemma delVarSet_unionVarSet:\n  forall vs1 vs2 x,\n  delVarSet (unionVarSet vs1 vs2) x [=] \n  unionVarSet (delVarSet vs1 x) (delVarSet vs2 x).\nProof.\n  intros.\n  set_b_iff.\n  fsetdec.\nQed.\n\nLemma delVarSetList_unionVarSet:\n  forall vs3 vs1 vs2,\n  delVarSetList (unionVarSet vs1 vs2) vs3 [=] \n  unionVarSet (delVarSetList vs1 vs3) (delVarSetList vs2 vs3).\nProof.\n  induction vs3; intros.\n  - repeat rewrite delVarSetList_nil.\n    reflexivity.\n  - repeat rewrite delVarSetList_cons.\n    rewrite delVarSet_unionVarSet.\n    rewrite IHvs3.\n    reflexivity.\nQed.\n\n\n(**************************************)\n\n\n(** ** [subVarSet]  *)\n  \nLemma subVarSet_refl:\n  forall vs1,\n  subVarSet vs1 vs1 .\nProof.\n  intros.\n  set_b_iff.\n  fsetdec.\nQed.\n\nLemma subVarSet_trans:\n  forall vs1 vs2 vs3,\n  subVarSet vs1 vs2  ->\n  subVarSet vs2 vs3  ->\n  subVarSet vs1 vs3 .\nProof.\n  intros.\n  set_b_iff.\n  fsetdec.\nQed.\n\n\nLemma subVarSet_emptyVarSet:\n  forall vs,\n  subVarSet emptyVarSet vs .\nProof.\n  intros.\n  set_b_iff.\n  fsetdec.\nQed.\n\nLemma subVarSet_unitVarSet:\n  forall v vs,\n  subVarSet (unitVarSet v) vs = elemVarSet v vs.\nProof.\n  intros.\n  destruct subVarSet eqn:SV; symmetry.\n  + set_b_iff.\n    fsetdec.\n  + rewrite -> false_is_not_true in *.\n    set_b_iff.\n    intro h.\n    unfold Subset in SV.\n    apply SV.\n    intros.\n    rewrite In_eq_iff; eauto.\n    apply singleton_1 in H; symmetry; auto.\nQed.\n\nLemma elemVarSet_false_true:\n  forall v1 fvs v2,\n  elemVarSet v1 fvs = false ->\n  elemVarSet v2 fvs  ->\n  varUnique v1 <> varUnique v2.\nProof.\n  intros v1 fvs v2.\n  intros.\n  assert (not (v2 == v1 )).\n  intro h. \n  set_b_iff.\n  rewrite -> In_eq_iff in H0; eauto.\n  intro h.\n  rewrite <- varUnique_iff in h.\n  apply H1.\n  rewrite Eq_sym.\n  auto.\nQed.\n\nLemma subVarSet_elemVarSet_true:\n  forall v vs vs',\n  subVarSet vs vs'  ->\n  elemVarSet v vs  ->\n  elemVarSet v vs' .\nProof.\n  intros v vs vs'.\n  set_b_iff.\n  fsetdec.\nQed.\n\nLemma subVarSet_elemVarSet_false:\n  forall v vs vs',\n  subVarSet vs vs'  ->\n  elemVarSet v vs' = false ->\n  elemVarSet v vs = false.\nProof.\n  intros v vs vs'.\n  set_b_iff.\n  fsetdec.\nQed.\n\nLemma subVarSet_extendVarSetList_l:\n  forall vs1 vs2 vs,\n  subVarSet vs1 vs2  ->\n  subVarSet vs1 (extendVarSetList vs2 vs) .\nProof.\n  intros vs1 vs2 vs.\n  generalize dependent vs2.\n  induction vs.\n  - intro vs2. rewrite extendVarSetList_nil. auto.\n  - intro vs2. intro h. \n    rewrite extendVarSetList_cons. \n    rewrite IHvs. auto. \n    set_b_iff. fsetdec.\nQed.\n\n\n    \n\nLemma subVarSet_extendVarSet_both:\n  forall vs1 vs2 v,\n  subVarSet vs1 vs2  ->\n  subVarSet (extendVarSet vs1 v) (extendVarSet vs2 v) .\nProof.\n  intros.\n  set_b_iff.\n  fsetdec.\nQed.\n\n\nLemma subVarSet_extendVarSet:\n  forall vs1 vs2 v,\n  subVarSet vs1 vs2  ->\n  subVarSet vs1 (extendVarSet vs2 v) .\nProof.\n  intros.\n  set_b_iff.\n  fsetdec.\nQed.\n\n\nLemma subVarSet_extendVarSetList:\n  forall vs1 vs2 vs3,\n  subVarSet vs1 vs2  ->\n  subVarSet vs1 (extendVarSetList vs2 vs3) .\nProof.\n\n  induction vs3; autorewrite with hs_simpl.\n  - auto.\n  - intro h. \n    rewrite extendVarSetList_extendVarSet_iff.\n    rewrite subVarSet_extendVarSet; auto.\nQed.\n\nLemma subVarSet_extendVarSet_l:\n  forall vs1 vs2 v v',\n  subVarSet vs1 vs2  ->\n  lookupVarSet vs2 v = Some v' ->\n  subVarSet (extendVarSet vs1 v) vs2 .\nProof.\n  intros.\n  set_b_iff.\n  apply MP.subset_add_3; try assumption.\n  apply lookupVarSet_In.\n  eauto.\nQed.\n\nLemma extendVarSet_subset: forall v1 v2 x,\n  v1 [<=] v2 ->\n  extendVarSet v1 x [<=] extendVarSet v2 x.\nProof.\n  intros.\n  set_b_iff.\n  fsetdec.\nQed.\n  \nLemma extendVarSetList_subset: forall x y vs,\n  x [<=] y ->\n  extendVarSetList x vs [<=] extendVarSetList y vs.\nProof.\n  intros.\n  induction vs; hs_simpl; [assumption|].\n  do 2 rewrite extendVarSetList_extendVarSet_iff.\n  apply extendVarSet_subset.\n  assumption.\nQed.\n\nLemma subVarSet_extendVarSetList_r:\n  forall vs vs1 vs2,\n  subVarSet vs1 (mkVarSet vs)  ->\n  subVarSet vs1 (extendVarSetList vs2 vs) .\nProof.\n  intros vs. \n  rewrite mkVarSet_extendVarSetList.\n  induction vs; intros vs1 vs2.\n  - autorewrite with hs_simpl.\n    set_b_iff.\n    fsetdec.\n  - intro h.     \n    autorewrite with hs_simpl in *.\n    rewrite -> extendVarSetList_extendVarSet_iff in *.\n    destruct (mem a (extendVarSetList empty vs)) eqn:Hd;\n    [|destruct (mem a vs1) eqn:Hd'].\n    + specialize (IHvs vs1 vs2). \n      set_b_iff.\n      assert (Hvs2: In a (extendVarSetList vs2 vs)).\n      * clear -Hd.\n        eapply MP.in_subset.\n        apply Hd. clear Hd a.\n        apply extendVarSetList_subset.\n        fsetdec.\n      * pose proof (subset_equal\n                     (equal_sym (add_equal Hvs2))).\n        eapply (Subset_trans); [apply IHvs| apply H].\n        pose proof (subset_equal (add_equal Hd)).\n        fsetdec.\n    + specialize (IHvs (remove a vs1) vs2). \n      set_b_iff.\n      apply remove_s_m with (x:= a) (y:=a) in h;\n        [|fsetdec].\n      assert (Hs: remove a (add a\n                                (extendVarSetList empty vs))\n                         [<=] (extendVarSetList empty vs)).\n      { apply subset_equal.\n        apply remove_add.\n        assumption. }\n        specialize (IHvs (Subset_trans h Hs)).\n      apply add_s_m with (x:= a) (y:=a) in IHvs;\n        [|fsetdec].\n      assert (Hs': vs1 [<=] add a (remove a vs1)).\n      { apply subset_equal.\n        apply equal_sym.\n        apply add_remove.\n        assumption. }\n      eapply Subset_trans.\n      apply Hs'.\n      assumption.\n    + specialize (IHvs vs1 vs2). \n      set_b_iff.\n      apply subset_add_2.\n      apply IHvs.\n      eapply remove_s_m with (x:= a) (y:=a) in h;\n        [|fsetdec].\n      apply remove_equal in Hd'.\n      fsetdec.\nQed.\n\n    \n\nLemma subVarSet_delVarSet:\n  forall vs1 v,\n  subVarSet (delVarSet vs1 v) vs1 .\nProof.\n  intros.\n  set_b_iff.\n  fsetdec.\nQed.\n\n\nLemma subVarSet_delVarSetList:\n  forall vs1 vl,\n  subVarSet (delVarSetList vs1 vl) vs1 .\nProof.\n  intros.\n  set_b_iff.\n  generalize vs1. clear vs1. induction vl.\n  - intros vs1. hs_simpl. \n    fsetdec.\n  - intros vs1. revert IHvl.\n    hs_simpl.\n    simpl.\n    intro IH. \n    rewrite -> IH with (vs1 := delVarSet vs1 a).\n    set_b_iff.\n    fsetdec.\nQed.\n\n\nLemma subVarSet_delVarSetList_both:\n  forall vs1 vs2 vl,\n  subVarSet vs1 vs2  ->\n  subVarSet (delVarSetList vs1 vl) (delVarSetList vs2 vl) .\nProof.\n  intros.\n  revert vs1 vs2 H. induction vl; intros.\n  - rewrite !delVarSetList_nil.\n    assumption.\n  - rewrite !delVarSetList_cons.\n    apply IHvl.\n    set_b_iff.\n    fsetdec.\nQed.\n\nLemma subVarSet_delVarSet_extendVarSet:\n  forall jps isvs v,\n  subVarSet jps isvs  ->\n  subVarSet (delVarSet jps v) (extendVarSet isvs v) .\nProof.\n  intros.\n  eapply subVarSet_trans.\n  apply subVarSet_delVarSet.\n  apply subVarSet_extendVarSet.\n  assumption.\nQed.\n\nLemma subVarSet_delVarSetList_extendVarSetList:\n  forall jps isvs vs,\n  subVarSet jps isvs  ->\n  subVarSet (delVarSetList jps vs) (extendVarSetList isvs vs) .\nProof.\n  intros.\n  eapply subVarSet_trans.\n  apply subVarSet_delVarSetList.\n  apply subVarSet_extendVarSetList.\n  assumption.\nQed.\n\n\nLemma subVarSet_delVarSetList_extendVarSetList_dual:\n  forall jps isvs vs,\n  subVarSet jps (extendVarSetList isvs vs)  ->\n  subVarSet (delVarSetList jps vs) isvs .\nProof.\n  intros.\n  revert jps isvs H.\n  induction vs; intros.\n  - rewrite !delVarSetList_nil.\n    rewrite !extendVarSetList_nil in H.\n    assumption.\n  - rewrite delVarSetList_cons2.\n    revert H.\n    hs_simpl.\n    intro H.\n    apply IHvs in H.\n    set_b_iff.\n    fsetdec.\nQed.\n\n\nLemma mapUnionVarSet_In_subVarSet:\n  forall a (x : a) xs f,\n  List.In x xs ->\n  subVarSet (f x) (mapUnionVarSet f xs).\nProof.\n  intros a x xs f H.\n  generalize dependent x.\n  induction xs; intros x H.\n  - inversion H.\n  - \n    inversion H as [H'|H'].\n    + unfold mapUnionVarSet.\n      unfold_Foldable_foldr.\n      subst.\n      simpl.\n      set_b_iff.\n      fsetdec.\n    + apply IHxs in H'.\n      clear H IHxs.\n      revert H'.\n      unfold mapUnionVarSet.\n      unfold_Foldable_foldr.\n      intros H'.\n      eapply subVarSet_trans.\n      apply H'.\n      clear H'.\n      set_b_iff.\n      simpl.\n      fsetdec.\nQed.\n\n\nLemma subVarSet_mapUnionVarSet:\n  forall a (xs : list a) f vs,\n  Forall (fun x => subVarSet (f x) vs ) xs ->\n  subVarSet (mapUnionVarSet f xs) vs.\nProof.\n  intros a xs f vs H.\n  induction xs.\n  - unfold mapUnionVarSet.\n    unfold_Foldable_foldr.\n    simpl.\n    apply subVarSet_emptyVarSet.\n  - inversion H.\n    subst.\n    apply IHxs in H3.\n    clear IHxs.\n    revert H3.\n    unfold mapUnionVarSet.\n    unfold_Foldable_foldr.\n    intros H3.\n    set_b_iff.\n    simpl.\n    fsetdec.\nQed.\n\n\nLemma subVarSet_unionVarSet:\n  forall vs1 vs2 vs3,\n  subVarSet (unionVarSet vs1 vs2) vs3 = subVarSet vs1 vs3 && subVarSet vs2 vs3.\nProof.\n  intros.\n  apply eq_iff_eq_true.\n  rewrite andb_true_iff.\n  set_b_iff.\n  split; intro H.\n  - split; fsetdec.\n  - destruct H; fsetdec.\nQed.\n\n\n(** ** [disjointVarSet]  *)\n\nInstance disjointVarSet_m : Proper (Equal ==> Equal ==> Logic.eq) disjointVarSet.\nProof.\n \n  move => x1 y1.  \n  move: (@ValidVarSet_Axiom x1).\n  move: (@ValidVarSet_Axiom y1).\n  move: x1 => [x1]. move: y1=> [y1].\n  move: x1 => [x1]. move: y1=> [y1].\n  move=> vx1 vy1 Eq1.\n  move=> x2 y2. \n  move: (@ValidVarSet_Axiom x2).   move: (@ValidVarSet_Axiom y2).\n  move: x2 => [x2]. move: y2=> [y2].\n  move: x2 => [x2]. move: y2=> [y2].\n  move=> vx2 vy2 Eq2.  \n\n  unfold ValidVarSet, disjointVarSet,\n         UniqFM.disjointUFM,\n         UniqSet.getUniqSet, \n         UniqSet.getUniqSet' in *.\n  unfold lookupVarSet, UniqSet.lookupUniqSet,UniqFM.lookupUFM in *.\n  unfold Equal, In, elemVarSet, UniqSet.elementOfUniqSet, UniqFM.elemUFM in Eq1.\n  unfold Equal, In, elemVarSet, UniqSet.elementOfUniqSet, UniqFM.elemUFM in Eq2.\n  apply null_intersection_eq; eauto.\n  move=> k1.  \n  specialize (Eq1 (Mk_Id GHC.Err.default k1 GHC.Err.default GHC.Err.default GHC.Err.default GHC.Err.default)).\n  simpl in Eq1.\n  auto.\n  move=> k1.\n  specialize (Eq2 (Mk_Id GHC.Err.default k1 GHC.Err.default GHC.Err.default GHC.Err.default GHC.Err.default)).\n  simpl in Eq2.\n  auto.\nQed.\n\n(*\nLemma foldl'_simplify (a b c :Type) (f:c -> b) (g:b->c) (h:b -> a -> b)\n      (xb:b) (xs : list a):\n  (forall x, f (g x) = x) ->\n  Foldable.foldl' (fun x y => g (h (f x) y)) (g xb) xs = \n  g (Foldable.foldl' h xb xs).\nProof.  \n  move => eq.\n  induction xs.\n  hs_simpl. auto.\n  hs_simpl.\n  rewrite eq.\n*)\n\nLemma UniqSet_Mk_UniqSet_eta :\n  forall a b (x : UniqSet.UniqSet a) (f : UniqSet.UniqSet a -> b), \n    match x with\n    | UniqSet.Mk_UniqSet set => f (UniqSet.Mk_UniqSet set)\n    end = f x.\nProof.            \n  move => a b [set] //.\nQed.\n\n\nLemma disjointVarSet_empytVarSet:\n  forall vs,\n  disjointVarSet vs emptyVarSet.\nProof.\n  move => vs1.\n  elim: vs1 => [i].\n  unfold disjointVarSet, emptyVarSet, elemVarSet.\n  simpl.\n  elim: i => [j].\n  simpl.\n  apply intersection_empty.\n  done.\nQed.\nHint Rewrite disjointVarSet_empytVarSet:hs_simpl.\n\nLemma disjointVarSet_mkVarSet_nil:\n  forall vs,\n  disjointVarSet vs (mkVarSet []).\nProof.\n  rewrite mkVarSet_extendVarSetList.\n  hs_simpl.\n  apply disjointVarSet_empytVarSet.\nQed.\n\nLemma disjointVarSet_extendVarSet vs1 var vs2 : \n  disjointVarSet vs1 (extendVarSet vs2 var) <->\n  elemVarSet var vs1 = false /\\ disjointVarSet vs1 vs2.\nProof.\n  move: vs1 vs2 => [[i1]] [[i2]].\n  unfold disjointVarSet, elemVarSet, extendVarSet.\n  unfold UniqSet.getUniqSet,UniqSet.getUniqSet',\n         UniqSet.elementOfUniqSet, UniqSet.addOneToUniqSet.\n  unfold UniqFM.disjointUFM, UniqFM.elemUFM, UniqFM.addToUFM.\n  set k:=  (Unique.getWordKey (Unique.getUnique var)).\n  apply null_intersection_non_member.\nQed.\n\nLemma disjointVarSet_mkVarSet_cons:\n  forall v vs1 vs2,\n  disjointVarSet vs1 (mkVarSet (v :: vs2))  <->\n  elemVarSet v vs1 = false /\\ disjointVarSet vs1 (mkVarSet vs2) .\nProof.\n  move=> v vs1 vs2.\n  rewrite mkVarSet_extendVarSetList.\n  hs_simpl.\n  rewrite extendVarSetList_extendVarSet_iff.\n  rewrite disjointVarSet_extendVarSet.\n  tauto.\nQed.\n\n      \nLemma disjointVarSet_mkVarSet_append:\n  forall vs1 vs2 vs3,\n  disjointVarSet vs1 (mkVarSet (vs2 ++ vs3))  <->\n  disjointVarSet vs1 (mkVarSet vs2)  /\\ disjointVarSet vs1 (mkVarSet vs3).\nProof.  \n  move=> vs1 vs2 vs3.\n  rewrite mkVarSet_extendVarSetList.\n  hs_simpl.\n  elim: vs3 => [|var vars IH]; hs_simpl.\n  + rewrite mkVarSet_extendVarSetList.\n    intuition.\n  + rewrite disjointVarSet_mkVarSet_cons.\n    rewrite and_comm.\n    rewrite and_assoc.\n    rewrite -> and_comm in IH.\n    rewrite <- IH.\n    rewrite extendVarSetList_extendVarSet_iff.\n    rewrite disjointVarSet_extendVarSet.\n    tauto.\nQed. \n\n\nLemma disjointVarSet_mkVarSet:\n  forall vs1 vs2,\n  disjointVarSet vs1 (mkVarSet vs2)  <->\n  Forall (fun v => elemVarSet v vs1 = false) vs2.\nProof.\n  move => vs1 vs2.\n  elim: vs2 => [|v vars IH].\n  rewrite disjointVarSet_mkVarSet_nil. intuition.\n  rewrite disjointVarSet_mkVarSet_cons. rewrite IH.\n  intuition.\n  - inversion H1. auto.\n  - inversion H1. auto.\nQed.\n\n\nLemma disjointVarSet_subVarSet_l:\n  forall vs1 vs2 vs3,\n  disjointVarSet vs2 vs3  ->\n  subVarSet vs1 vs2  ->\n  disjointVarSet vs1 vs3 .\nProof.\n  move=> [[i1]][[i2]][[i3]].\n  unfold disjointVarSet, subVarSet, isEmptyVarSet,minusVarSet.\n  unfold UniqSet.getUniqSet,UniqSet.getUniqSet',\n  UniqSet.isEmptyUniqSet, UniqSet.minusUniqSet.\n  unfold UniqFM.disjointUFM, UniqFM.isNullUFM, UniqFM.minusUFM.\n  apply disjoint_difference.\nQed.\n\n\n(** ** [filterVarSet] *)\n\nLemma filterVarSet_comp : forall f f' vs,\n    filterVarSet f (filterVarSet f' vs) [=] filterVarSet (fun v => f v && f' v) vs.\nProof.\n  intros. destruct vs, getUniqSet'. simpl.\n  apply IntMapEq_VarSetEq, filter_comp, EqLaws_Var.\nQed.\n\nLemma filterSingletonTrue : forall f x,\n  RespectsVar f ->\n  f x = true -> \n  filterVarSet f (unitVarSet x) [=] unitVarSet x.\nProof. \n  move=> f x RR TR.\n  set_b_iff.\n  replace (singleton x) with (add x empty).\n  - rewrite -> filter_add_1; auto.\n    fsetdec.\n  - simpl. unfold singleton, unitVarSet, UniqSet.unitUniqSet.\n    f_equal. unfold UniqFM.unitUFM; f_equal.\n    unfold IntMap.insert, IntMap.singleton; f_equal.\n    apply proof_irrelevance.\nQed.\n\nLemma filterSingletonFalse : forall f x,\n  RespectsVar f ->\n  f x = false -> \n  filterVarSet f (unitVarSet x) [=] emptyVarSet.\nProof. \n  move=> f x RR TR.\n  set_b_iff.\n  replace (singleton x) with (add x empty).\n  - rewrite -> filter_add_2; auto.\n    fsetdec.\n  - simpl. unfold singleton, unitVarSet, UniqSet.unitUniqSet.\n    f_equal. unfold UniqFM.unitUFM; f_equal.\n    unfold IntMap.insert, IntMap.singleton; f_equal.\n    apply proof_irrelevance.\nQed.\n\nLemma filterVarSet_emptyVarSet f :\n  filterVarSet f emptyVarSet = emptyVarSet.\nProof.\n  set_b_iff.\n  simpl. unfold empty, emptyVarSet, UniqSet.emptyUniqSet.\n  f_equal. unfold UniqFM.emptyUFM. f_equal.\n  unfold IntMap.filter, IntMap.empty. simpl.\n  f_equal. apply proof_irrelevance.\nQed.\nHint Rewrite filterVarSet_emptyVarSet : hs_simpl.\n\n\nLemma filterVarSet_constTrue vs : \n  filterVarSet (const true) vs [=] vs.\nProof. \n  unfold filterVarSet.\n  elim: vs => [i].\n  elim: i => [m].\n  simpl. apply IntMapEq_VarSetEq.\n  apply filter_true, EqLaws_Var.\nQed.\nHint Rewrite filterVarSet_constTrue : hs_simpl.\n\nLemma elemVarSet_filterVarSet x f vs :\n  RespectsVar f ->\n  elemVarSet x (filterVarSet f vs) = f x && elemVarSet x vs.\nProof.\n  move => h.\n  rewrite eqE.\n  set_b_iff.\n  rewrite andE.\n  unfold is_true.\n  set_b_iff.\n  rewrite and_comm.\n  apply F.filter_iff.\n  auto.\nQed.\n\nLemma filterVarSet_iff (f1 f2 : Var -> bool) vs : \n  (forall x, (f1 x) <-> (f2 x)) -> \n  filterVarSet f1 vs [=] filterVarSet f2 vs.\nProof.\n  intros. destruct vs, getUniqSet'. simpl.\n  apply IntMapEq_VarSetEq.\nAbort.\n\nLemma filterVarSet_equal f vs1 vs2 :\n  RespectsVar f -> \n  vs1 [=] vs2 ->\n  filterVarSet f vs1 [=] filterVarSet f vs2.\nProof.\n  move => RF EQ.\n  set_b_iff.\n  eapply filter_equal; eauto.\nQed.\n\nLemma filterVarSet_extendVarSet : \n  forall f v vs,\n    RespectsVar f ->\n    filterVarSet f (extendVarSet vs v) [=] \n    if (f v) then extendVarSet (filterVarSet f vs) v \n    else (filterVarSet f vs).\nProof.\n  intros.\n  set_b_iff.\n  destruct (f v) eqn:Hfv; auto.\n  rewrite -> filter_add_1; try done.\n  rewrite -> filter_add_2; try done.\nQed.\n\n\nLemma lookupVarSet_filterVarSet_true : forall f v vs,\n  RespectsVar f ->\n  f v = true ->\n  lookupVarSet (filterVarSet f vs) v = lookupVarSet vs v.\nProof.\n  intros.\n  destruct (lookupVarSet (filterVarSet f vs) v) eqn:Hl.\n  - revert Hl.\n    unfold_VarSet_to_IntMap.\n    unfold IntMap.filter.\n    symmetry.\n    erewrite lookup_filterWithKey.\n    + reflexivity.\n    + apply Hl.\n  - apply lookupVarSet_None_elemVarSet in Hl.\n    symmetry.\n    apply lookupVarSet_None_elemVarSet.\n    set_b_iff.\n    intros Hin.\n    eapply filter_3 in Hin; eauto.\nQed.\n\nLemma lookupVarSet_filterVarSet_false : forall f v vs,\n  RespectsVar f ->\n  f v = false ->\n  lookupVarSet (filterVarSet f vs) v = None.\nProof.\n  intros.\n  apply lookupVarSet_None_elemVarSet.\n  set_b_iff.\n  rewrite filter_iff; [|auto].\n  intros [H1 H2].\n  rewrite H0 in H2.\n  inversion H2.\nQed.\n\nLemma unionVarSet_filterVarSet f vs1 vs2 :\n  RespectsVar f ->\n  unionVarSet (filterVarSet f vs1) (filterVarSet f vs2) [=] filterVarSet f (unionVarSet vs1 vs2).\nProof.\n  move=> g.\n  set_b_iff.\n  rewrite <- filter_union.\n  reflexivity.\n  eauto.\nQed.\n\nLemma filterVarSet_delVarSet f vs v :\n  RespectsVar f ->\n  filterVarSet f (delVarSet vs v) [=]\n  delVarSet (filterVarSet f vs) v.\nProof.\n  move=> Ff. unfold RespectsVar in Ff.\n  set_b_iff. \n  unfold Equal.\n  move=> x.\n  rewrite filter_iff; auto.\n  rewrite remove_iff; auto.\n  rewrite remove_iff; auto.\n  rewrite filter_iff; auto.\n  fsetdec.\nQed.\n\n\nLemma filterVarSet_delVarSetList:\n  forall (f : Var -> bool)  (vars : list Var) (vs : VarSet),\n  RespectsVar f ->\n  filterVarSet f (delVarSetList  vs vars) [=] delVarSetList (filterVarSet f vs) vars.\nProof.\n  induction vars.\n  - move=> vs h. hs_simpl. reflexivity.\n  - move=> vs h.  hs_simpl. \n    rewrite IHvars; try done.\n    rewrite <- filterVarSet_delVarSet; try done.\nQed.\n\n\n(** ** [unionVarSet] *)\n\nLemma unionVarSet_sym vs1 vs2 : unionVarSet vs1 vs2 [=] unionVarSet vs2 vs1.\nProof. set_b_iff. fsetdec. Qed.\n\n\nLemma unionEmpty_l : forall vs,\n    unionVarSet emptyVarSet vs [=] vs.\nProof. set_b_iff. fsetdec. Qed.\nLemma unionEmpty_r : forall vs,\n    unionVarSet vs emptyVarSet [=] vs.\nProof. set_b_iff. fsetdec. Qed.\nLemma unionSingle_l : forall x s,\n    unionVarSet (unitVarSet x) s [=] extendVarSet s x.\nProof. intros. set_b_iff. fsetdec. Qed.\nLemma unionSingle_r : forall x s,\n    unionVarSet s (unitVarSet x) [=] extendVarSet s x.\nProof. intros. set_b_iff. fsetdec. Qed.\n\nHint Rewrite unionEmpty_l unionEmpty_r \n     unionSingle_l unionSingle_r :\n  hs_simpl.\n\n\n(** ** [unionVarSets] *)\n\nLemma unionVarSet_commute (ss : list VarSet) : forall v a,\n      unionVarSet v (Foldable.foldr unionVarSet a ss)\n  [=] unionVarSet a (Foldable.foldr unionVarSet v ss).\nProof.   \n  induction ss.\n  + intros v a. hs_simpl. eapply unionVarSet_sym.\n  + intros v b. hs_simpl.\n    rewrite (IHss a b).\n    rewrite (IHss a v).\n    fsetdec.\nQed.\n\nLemma unionVarSets_cons a ss : unionVarSets (a :: ss) [=] unionVarSet a (unionVarSets ss).\nProof.\n  unfold unionVarSets.\n  unfold UniqSet.unionManyUniqSets.\n  destruct ss.\n  + hs_simpl. reflexivity.\n  + hs_simpl. rewrite unionVarSet_commute.\n    reflexivity.\nQed.\nHint Rewrite unionVarSets_cons : hs_simpl.\n\n\nLemma unionVarSets_def ss : \n  unionVarSets ss [=] Foldable.foldr unionVarSet emptyVarSet ss.\nProof.\n  induction ss. cbv. done.\n  hs_simpl. \n  rewrite IHss. reflexivity.\nQed.\n\n\nLemma unionsVarSet_equal : forall vss1 vss2, Forall2 Equal vss1 vss2 ->\n  (Foldable.foldr unionVarSet emptyVarSet) vss1 [=]\n  (Foldable.foldr unionVarSet emptyVarSet) vss2.\nProof.\n  move=>vss1 vss2.\n  elim.\n  hs_simpl. reflexivity.\n  move=> x y l l' Eq1 Eq2 IH.\n  hs_simpl.\n  f_equiv; auto.\nQed.\n\nInstance unionsVarSet_m : \n   Proper (Forall2 Equal ==> Equal) unionVarSets.\nProof.\n  move=> vss1 vss2 Eq. \n  rewrite unionVarSets_def. rewrite unionVarSets_def.\n  eapply unionsVarSet_equal. auto.\nDefined.\n\n\nLemma delVarSet_unionVarSets ss x :\n  delVarSet (unionVarSets ss) x [=] unionVarSets (List.map (fun s => delVarSet s x) ss).\nProof.\n  induction ss.\n  + cbv. done.\n  + hs_simpl.\n    rewrite delVarSet_unionVarSet. rewrite IHss.\n    rewrite unionVarSets_cons.\n    unfold map. reflexivity.\nQed.\n    \nLemma mapUnionVarSet_cons {A} f (x:A) xs : \n  mapUnionVarSet f (x :: xs) [=] unionVarSet (f x) (mapUnionVarSet f xs).\nProof.                                           \n  unfold mapUnionVarSet.\n  hs_simpl. unfold Base.op_z2218U__.\n  reflexivity.\nQed.\n\nLemma mapUnionVarSets_unionVarSets {A} (f : A -> VarSet) ss :\n  mapUnionVarSet f ss [=] unionVarSets (List.map f ss).\nProof. \n  induction ss. cbv. done.\n  rewrite mapUnionVarSet_cons.\n  rewrite unionVarSets_cons.\n  rewrite IHss.\n  reflexivity.\nQed.\n\n\n(** ** [minusVarSet] *)\n\nLemma minusVarSet_emptyVarSet vs : \n  minusVarSet vs emptyVarSet = vs.\nProof.\n  unfold minusVarSet, emptyVarSet.\n  unfold UniqSet.minusUniqSet, UniqSet.emptyUniqSet.\n  elim: vs => [i].\n  elim: i => [m].\n  unfold UniqFM.minusUFM, UniqFM.emptyUFM.\n  f_equal.\n  f_equal.\n  unfold IntMap.empty.\n  rewrite difference_nil_r.\n  reflexivity.\nQed.\n\nHint Rewrite minusVarSet_emptyVarSet : hs_simpl.\n\nLemma minusVarSet_emptyVarSet_l vs : \n  minusVarSet emptyVarSet vs = emptyVarSet.\nProof.\n  unfold minusVarSet, emptyVarSet.\n  unfold UniqSet.minusUniqSet, UniqSet.emptyUniqSet.\n  elim: vs => [i].\n  elim: i => [m].\n  unfold UniqFM.minusUFM, UniqFM.emptyUFM.\n  f_equal.\n  f_equal.\n  unfold IntMap.empty.\n  rewrite difference_nil_l.\n  reflexivity.\nQed.\n\nHint Rewrite minusVarSet_emptyVarSet_l : hs_simpl.\n\n\n\nLemma elemVarSet_minusVarSetTrue : forall x s,\n  elemVarSet x s = true -> \n  minusVarSet (unitVarSet x) s [=] emptyVarSet.\nProof. intros. set_b_iff.\n       split; try fsetdec.\n       move=> h.\n       move: (diff_1 _ _ _ h) => h1.\n       move: (diff_2 _ _ _ h) => h2.\n       inversion h1. clear h1.\n       unfold IntMap.member, Internal.member in H1; simpl in H1.\n       destruct (compare _ _) eqn:H2 in H1;\n         try solve [inversion H1].\n       apply Bounds.compare_Eq in H2.\n       rewrite <- var_eq_realUnique in H2.\n       rewrite -> fold_is_true in H2.\n       unfold In in H, h2.\n       rewrite (@elemVarSet_eq a x) in h2; done.\nQed.\n\n\nLemma elemVarSet_minusVarSetFalse : forall x s,\n  elemVarSet x s = false -> \n  minusVarSet (unitVarSet x) s [=] unitVarSet x.\nProof.\n  intros. \n  set_b_iff.\n  split; try fsetdec.\n  move=> h.\n  apply diff_3; try done.\n  inversion h.\n  unfold In, singleton in *.\n  rewrite  (@elemVarSet_eq x a) in H; try done.\n  rewrite var_eq_realUnique.\n  unfold IntMap.member, Internal.member in H1; simpl in H1.\n  destruct (compare _ _) eqn:H2 in H1; try solve [inversion H1].\n  apply Bounds.compare_Eq in H2.\n  rewrite Eq_sym; done.\nQed.\n\n\n\nLemma elemVarSet_minusVarSet x vs1 vs2 :\n  elemVarSet x (minusVarSet vs1 vs2) = elemVarSet x vs1 && ~~ elemVarSet x vs2.\nProof.\n  rewrite eqE.\n  set_b_iff.\n  rewrite F.diff_iff.\n  split.\n  move => [h1 h2]. apply /andP. split. auto.\n  apply /negPf.\n  set_b_iff. auto.\n  move => /andP [h1 h2].\n  move: h2 => /negPf => h2.\n  set_b_iff. auto.\nQed.\n\n\nLemma unionVarSet_minusVarSet vs1 vs2 vs :\n  unionVarSet (minusVarSet vs1 vs) (minusVarSet vs2 vs) [=]\n  minusVarSet (unionVarSet vs1 vs2) vs.\nProof.\n  unfold Equal.\n  move=> x.\n  unfold In.\n  rewrite! elemVarSet_minusVarSet.\n  rewrite! elemVarSet_unionVarSet.\n  rewrite! elemVarSet_minusVarSet.\n  rewrite! andb_orb_distrib_l.\n  reflexivity.\nQed.\n\n\n(** ** Compatibility with [almostEqual] *)\n\nLemma lookupVarSet_ae : \n  forall vs v1 v2, \n    almostEqual v1 v2 -> \n    lookupVarSet vs v1 = lookupVarSet vs v2.\nProof. \n  induction 1; simpl; unfold UniqFM.lookupUFM; simpl; auto.\nQed.\n\nLemma delVarSet_ae:\n  forall vs v1 v2,\n  almostEqual v1 v2 ->\n  delVarSet vs v1 = delVarSet vs v2.\nProof.\n  induction 1; simpl;\n  unfold UniqFM.delFromUFM; simpl; auto.\nQed.\n\nLemma elemVarSet_ae:\n  forall vs v1 v2,\n  almostEqual v1 v2 ->\n  elemVarSet v1 vs = elemVarSet v2 vs.\nProof.\n  induction 1; simpl;\n  unfold UniqFM.delFromUFM; simpl; auto.\nQed.\n\n\nLemma elemNegbDisjoint : forall vs vs2, \n    disjointVarSet vs (mkVarSet vs2) ->\n    forall v, Foldable.elem v vs2 -> negb (elemVarSet v vs).\nProof.\n  move=> vs.\n  elim => [|x xs IHxs].\n  - move => ? v. hs_simpl. done.\n  - rewrite disjointVarSet_mkVarSet_cons.\n    move => [h1 h2] v.\n    hs_simpl.\n    move => /orP [h3|h3].\n    erewrite (@elemVarSet_eq x v) in h1.\n    rewrite h1. done.\n    symmetry. done.\n    apply IHxs; try done.\nQed.\n\n\n\nLemma Forall2_diag:\n  forall a P (xs: list a),\n  Forall2 P xs xs <-> Forall (fun x => P x x) xs.\nProof.\n  intros.\n  induction xs.\n  * split; intro; constructor.\n  * split; intro H; constructor; inversion H; intuition.\nQed.\n\n\nLemma lookupVarSet_delVarSet_None:\n  forall v vs, lookupVarSet (delVarSet vs v) v = None.\nProof.\n  intros.\n  unfold lookupVarSet,\n  UniqSet.lookupUniqSet,\n  UniqFM.lookupUFM.\n  unfold delVarSet,\n  UniqSet.delOneFromUniqSet,\n  UniqFM.delFromUFM.\n  destruct vs.\n  destruct getUniqSet'.\n  simpl.\n  apply delete_eq.\nQed.\n\n\n\n\n\n(* A list of variables is fresh for a given varset when \n   any variable with a unique found in the list is not found \n   in the set. i.e. this is list membership using GHC.Base.==\n   for vars. \n*)\n\nDefinition freshList (vars: list Var) (vs :VarSet) :=\n  (forall (v:Var), Foldable.elem v vars  -> \n              lookupVarSet vs v = None).\n\nLemma freshList_nil : forall v,  freshList nil v.\nProof.\n  unfold freshList. intros v v0 H. inversion H.\nQed.\n\nLemma freshList_cons : forall (x:Var) l (v:VarSet),  \n    lookupVarSet v x = None /\\ freshList l v <-> freshList (x :: l) v.\nProof.\n  unfold freshList. intros. \n  split. \n  + intros [? ?] ? ?.\n    rewrite elem_cons in H1.\n    destruct (orb_prop _ _ H1) as [EQ|IN].\n    rewrite -> lookupVarSet_eq with (v2 := x); auto.\n    eauto.\n  + intros. split.\n    eapply H. \n    rewrite elem_cons.\n    eapply orb_true_intro.\n    left. eapply Base.Eq_refl.\n    intros.\n    eapply H.\n    rewrite elem_cons.\n    eapply orb_true_intro.\n    right. auto.\nQed.\n\n\nLemma freshList_app :\n  forall v l1 l2, freshList (l1 ++ l2) v <-> freshList l1 v /\\ freshList l2 v.\nProof.\n  intros.\n  induction l1; simpl.\n  split.\n  intros. split. apply freshList_nil. auto.\n  tauto.\n  split.\n  + intros.\n    rewrite <- freshList_cons in *. tauto. \n  + intros.\n    rewrite <- freshList_cons in *. tauto.\nQed.\n    \n\n\nLemma elemVarSet_unitVarSet_is_eq :\n  forall x v, elemVarSet x (unitVarSet v) = GHC.Base.op_zeze__ x v.\nProof.\n  intros.\n  destruct (GHC.Base.op_zeze__ x v) eqn:Hcomp.\n  - apply varUnique_iff in Hcomp; inversion Hcomp.\n    cbn. rewrite H0 N.compare_refl =>//.\n  - apply ssrbool.negbT, notE in Hcomp.\n    cbn. apply not_true_iff_false.\n    destruct (N.compare _ _) eqn:Hcomp'; auto.\n    contradiction Hcomp.\n    apply varUnique_iff. rewrite /varUnique.\n    f_equal. apply N.compare_eq_iff =>//.\nQed.\n\n\n(** A very specialized [Proper] instance, written for the sole purpose\n    of proving [delVarSetList_commute]. *)\nInstance foldl_m :\n  Proper (Equal ==> (fun (a b : list Var) => a = b) ==> Equal)\n         (Foldable.foldl delVarSet).\nProof.\n  intros s1 s2 Heqs l1 l2 Heql; subst.\n  generalize dependent s2.\n  generalize dependent s1.\n  induction l2.\n  - rewrite /Foldable.foldl //=.\n  - intros s1 s2 Heqs. rewrite !Foldable_foldl_cons.\n    apply IHl2. rewrite Heqs. reflexivity.\nQed.\n\n\nLemma delVarSetList_commute :forall (bndrs:list Var) vs bndr,\n  Foldable.foldl delVarSet (delVarSet vs bndr) bndrs [=]\n  delVarSet (Foldable.foldl delVarSet vs bndrs) bndr.\nProof.\n  elim => [|bndr' bndrs].\n  - move=> vs bndr. hs_simpl. reflexivity.\n  - move=> IH vs bndr.\n    hs_simpl.\n    rewrite delVarSet_commute.\n    eapply IH.\nQed.\n\n\n\n(** A [Proper] instance, written for the sole purpose\n    of proving [delVarSetList_commute]. *)\nInstance foldr_m :\n  Proper (((fun x y => (x == y)) ==> Equal ==> Equal) ==> Equal ==> (fun (a b : list Var) => a = b) ==> Equal)\n         Foldable.foldr.\nProof.\n  intros f1 f2 Hf s1 s2 Heqs l1 l2 Heql; subst.\n  generalize dependent s2.\n  generalize dependent s1.\n  induction l2.\n  - rewrite /Foldable.foldr //=.\n  - intros s1 s2 Heqs. rewrite !Foldable_foldr_cons.\n    specialize (IHl2 s1 s2 Heqs).\n    eapply Hf. reflexivity.\n    eapply IHl2.  \nQed.\n\n\n\n(** A [Proper] instance, written for showing that folding a unionVarSet like term  *)\nInstance foldr_mE :\n  Proper ((Equal ==> Equal ==> Equal) ==> Equal ==> (Forall2 Equal) ==> Equal)\n         Foldable.foldr.\nProof.\n  intros f1 f2 Hf s1 s2 Heqs l1 l2 Heql; subst.\n  generalize dependent s2.\n  generalize dependent s1.\n  generalize dependent l1. \n  induction l2.\n  - move=> l1 Heql. inversion Heql. rewrite /Foldable.foldr //=.\n  - move=> l1 Heql. inversion Heql. subst. \n    intros s1 s2 Heqs. rewrite !Foldable_foldr_cons.   \n    specialize (IHl2 _ H3 s1 s2 Heqs).\n    eapply Hf. auto.\n    eapply IHl2.  \nQed.\n\nLemma delVarSetList_commute_foldr : forall (bndrs:list Var) vs bndr,\n  Foldable.foldr (fun x y => delVarSet y x) (delVarSet vs bndr) bndrs [=]\n  delVarSet (Foldable.foldr (fun x y => delVarSet y x) vs bndrs) bndr.\nProof.\n  elim => [|bndr' bndrs].\n  - move=> vs bndr. hs_simpl. reflexivity.\n  - move=> IH vs bndr.\n    hs_simpl.\n    rewrite delVarSet_commute.\n    rewrite IH. reflexivity.\nQed.\n\nLemma delVarSetList_foldr ss xs : \n  delVarSetList ss xs [=] Foldable.foldr (fun x ss => delVarSet ss x) ss xs.\nProof.\n  generalize dependent ss.\n  induction xs.\n  cbv. destruct ss. auto.\n  - move=> ss. hs_simpl.\n    rewrite <- delVarSetList_commute_foldr.\n    rewrite <- IHxs.\n    reflexivity.\nQed.\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/VarSet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.27496568155187817}}
{"text": "(*******************************************************************\n * Este archivo especifica el estado.\n * \n ******************************************************************)\n\nRequire Export Maps.\n\nSection State.\n\n(** Identificadores de OSs e Hypercalls *)\n\nParameter os_ident : Set.\nParameter os_ident_eq : forall oi1 oi2 : os_ident, {oi1 = oi2} + {oi1 <> oi2}.\n\nParameter Hyperv_call: Set.\n\n\n(* Memoria y direcciones *)\n\n(* Direcciones Virtuales. *)\nParameter vadd: Set.\nParameter vadd_eq : forall va1 va2 : vadd, {va1 = va2} + {va1 <> va2}.\n\n(** Direcciones de Máquina. *)\nParameter madd :  Set.\nParameter madd_eq : forall ma1 ma2 : madd, {ma1 = ma2} + {ma1 <> ma2}.\n\n(** Direcciones Físicas : \nLos sitemas operativos utilizan este tipo de direcciones para ver regiones de memoriea\ncontigua. Estos no ven direcciones de máquina. *)\nParameter padd: Set.\nParameter padd_eq : forall pa1 pa2 : padd, {pa1 = pa2} + {pa1 <> pa2}.\n\n(** Memory values. *)\nParameter value: Set.\nParameter value_eq:forall val1 val2 : value, {val1 = val2} + {val1 <> val2}.\n\n\n(* Environment *)\nRecord context : Set :=\n  Context\n    {(** una dirección virtual es accesible, i.e. no está reserveda \n         por el Hypervisor *)\n       ctxt_vadd_accessible: vadd -> bool;\n     (** guest Oss (Confiable/No Confiable) **)\n       ctxt_oss : os_ident -> bool\n    }.\n\n(* Ejercicio 1 *)\nInductive exec_mode : Set :=\n  | usr : exec_mode\n  | svc : exec_mode.\n\nRecord os : Set :=\n  Os\n    {\n      curr_page : padd;\n      hcall : option Hyperv_call\n    }.\n\nDefinition oss_map := mapping os_ident os.\n\nInductive os_activity : Set :=\n  | running : os_activity\n  | waiting : os_activity.\n\nDefinition hypervisor_map := mapping os_ident (mapping padd madd).\n\nInductive content : Set :=\n  | RW : option value -> content\n  | PT : mapping vadd madd -> content\n  | Other : content.\n\nInductive page_owner : Set :=\n  | Hyp : page_owner\n  | OS : os_ident -> page_owner\n  | No_Owner : page_owner.\n\nRecord page : Set :=\n  Page\n    {\n      page_content : content;\n      page_owned_by : page_owner\n    }.\n\nDefinition system_memory := mapping madd page.\n\nRecord state : Set :=\n  State\n    {\n      active_os : os_ident;\n      aos_exec_mode : exec_mode;\n      aos_activity : os_activity;\n      oss : oss_map;\n      hypervisor : hypervisor_map;\n      memory : system_memory\n    }.\n\nEnd State.", "meta": {"author": "JoelCa", "repo": "CFPTT", "sha": "55f6aca270d7ffba9069ed1033aca474f1d3df9b", "save_path": "github-repos/coq/JoelCa-CFPTT", "path": "github-repos/coq/JoelCa-CFPTT/CFPTT-55f6aca270d7ffba9069ed1033aca474f1d3df9b/VirtualCert/State.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091673, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.27492348990256765}}
{"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 seq ssrnat.\nRequire Import ssrZ ZArith_ext seq_ext ssrnat_ext machine_int multi_int.\nImport MachineInt.\nRequire Import uniq_tac.\nRequire Import mips_seplog mips_tactics mips_contrib mapstos.\nRequire Import multi_sub_u_u_prg.\nImport expr_m.\nImport assert_m.\n\nLocal Open Scope machine_int_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 multi_sub.\n\nVariables k a b t j u bor atmp btmp : reg.\n\nLemma multi_sub_u_u_L_triple : uniq(k, a, b, t, j, u, bor, atmp, btmp, r0) ->\nforall nk va vb, u2Z va + 4 * Z_of_nat nk < \\B^1 ->\nforall A B, size A = nk -> size B = nk ->\n{{ fun s h => [a]_s = va /\\ [b]_s = vb /\\ u2Z [k]_s = Z_of_nat nk /\\\n  (var_e a |--> A ** var_e b |--> B) s h }}\n multi_sub_u_u k a b a t j u bor atmp btmp\n{{ fun s h => exists A', size A' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\\n  u2Z [k]_s = Z_of_nat nk /\\\n  (var_e a |--> A' ** var_e b |--> B) s h /\\\n  u2Z [bor]_s <= 1 /\\\n  \\S_{ nk } A' = \\S_{ nk } A - \\S_{ nk } B + u2Z [bor]_s * \\B^nk }}.\nProof.\nmove=> Hset nk va vb Hna A B Ha Hb; rewrite /multi_sub_u_u.\n\n(** addiu j zero zero16; *)\n\nNextAddiu.\nmove=> s h [Hra [Hrb [Hrk H]]].\nrewrite /wp_addiu; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\n\n(** addi t c zero16 *)\n\nNextAddiu.\nmove=> s h [[Hra [Hrb [Hrk H]]] Hj].\nrewrite /wp_addiu; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\n\n(** addi bor zero zero16; *)\n\nNextAddiu.\nmove=> s h [[[Hra [Hrb [Hrk H]]] Hj] Ht].\nrewrite /wp_addiu; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\n\n(** while (bne j k) ( *)\n\napply hoare_prop_m.hoare_while_invariant with (fun s h => exists A' nj nbor,\n  size A' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\ u2Z [k]_s = Z_of_nat nk /\\\n  (var_e a |--> A' ** var_e b |--> B) s h /\\\n  u2Z [j]_s = Z_of_nat nj /\\ (nj <= nk)%nat /\\\n  u2Z [t]_s = u2Z va + 4 * Z_of_nat nj /\\ u2Z [bor]_s = nbor /\\\n  nbor <= 1 /\\ \\S_{ nj } A' = \\S_{ nj } A - \\S_{ nj } B + nbor * \\B^nj /\\\n  drop nj A = drop nj A').\n\nmove=> s h [[[[Hra [Hrb [Hrk H]]] Hj] Ht Hbor]].\nexists A, O, 0; repeat (split => //).\nby rewrite store.get_r0 add0i sext_Z2u // Z2uK in Hj.\nrewrite Ht sext_0 addi0 Hra //; ring.\nby rewrite Hbor sext_0 addi0 // store.get_r0 Z2uK.\n\nmove=> s h [[A' [nj [nbor [HlenC [Hra [Hrb [Hrk [Hmem [Hrj [Hjk2 [Hrt [Hrbor [Hnbor [HInv Hnth]]]]]]]]]]]]] Hjk]].\nrewrite /= Hrj Hrk in Hjk. move/negPn/eqP/Z_of_nat_inj in Hjk; subst nj.\nexists A'; repeat (split; trivial).\nby rewrite Hrbor.\nby rewrite Hrbor -HInv.\n\n(** lwxs atmp j b; *)\n\napply hoare_lwxs_back_alt'' with (fun s h => exists A' nj nbor,\n  size A' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\ u2Z [k]_s = Z_of_nat nk /\\\n  (var_e a |--> A' ** var_e b |--> B) s h /\\\n  u2Z [j]_s = Z_of_nat nj /\\ (nj < nk)%nat /\\\n  u2Z [t]_s = u2Z va + 4 * Z_of_nat nj /\\ u2Z [bor]_s = nbor /\\ nbor <= 1 /\\\n  \\S_{ nj } A' = \\S_{ nj } A - \\S_{ nj } B + nbor * \\B^nj /\\\n  drop nj A = drop nj A' /\\ [atmp]_s = B `32_ nj).\n\nmove=> s h [ [A' [nj [nbor [HlenA' [Hra [Hrb [Hrk [Hmem [Hrj [Hjk2 [Hrt [Hrbor [Hnbor [HInv Hnth]]]]]]]]]]]]] Hjk]].\nrewrite /= in Hjk; move/eqP in Hjk.\n\nexists (B `32_ nj); split.\n- Decompose_32 B nj B1 B2 HlenB' HB'; last by ssromega.\n  rewrite HB' (decompose_equiv _ _ _ _ _ HlenB') in Hmem.\n  rewrite assert_m.conCE !assert_m.conAE in Hmem.\n  rewrite assert_m.conCE !assert_m.conAE in Hmem.\n  move: Hmem; apply monotony => // h'.\n  apply mapsto_ext => //.\n  by rewrite /= shl_Z2u Hrj inj_mult mulZC.\n- rewrite /update_store_lwxs.\n  exists A', nj, nbor; repeat Reg_upd; repeat (split; trivial).\n  by Assert_upd.\n\nssromega.\n\n(** addu btmp atmp bor; *)\n\napply hoare_addu with (fun s h => exists A' nj nbor,\n  size A' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\ u2Z [k]_s = Z_of_nat nk /\\\n  (var_e a |--> A' ** var_e b |--> B) s h /\\\n  u2Z [j]_s = Z_of_nat nj /\\ (nj < nk)%nat /\\\n  u2Z [t]_s = u2Z va + 4 * Z_of_nat nj /\\ u2Z [bor]_s = nbor /\\\n  nbor <= 1 /\\ \\S_{ nj } A' = \\S_{ nj } A - \\S_{ nj } B + nbor * \\B^nj /\\\n  drop nj A = drop nj A' /\\ [atmp]_s = B `32_ nj /\\\n  [btmp]_s = B `32_ nj `+ [bor]_s).\n\nmove=> s h [A' [nj [nbor [HlenC [Hra [Hrb [Hrk [Hmem [Hrj [Hjk2 [Hrt [Hrbor [Hnbor [HInv [Hnth Hratmp]]]]]]]]]]]]]]].\n\nexists A', nj, nbor; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nby rewrite -Hratmp.\n\n(** sltu btmp atmp; *)\n\napply hoare_sltu with (fun s h => exists A' nj nbor,\n  size A' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\ u2Z [k]_s = Z_of_nat nk /\\\n  (var_e a |--> A' ** var_e b |--> B) s h /\\\n  u2Z [j]_s = Z_of_nat nj /\\ (nj < nk)%nat /\\\n  u2Z [t]_s = u2Z va + 4 * Z_of_nat nj /\\ u2Z [bor]_s = nbor /\\\n  nbor <= 1 /\\ \\S_{ nj } A' = \\S_{ nj } A - \\S_{ nj } B + nbor * \\B^nj /\\\n  drop nj A = drop nj A' /\\\n  [btmp]_s = B `32_ nj `+ [bor]_s /\\\n  [u]_s = if Zlt_bool (u2Z [btmp]_s) (u2Z (B `32_ nj)) then one32 else zero32).\n\nmove=> s h [A' [nj [nbor [HlenC [Hra [Hrb [Hrk [Hmem [Hrj [Hjk2 [Hrt [Hrbor [Hnbor [HInv [Hnth [Hratmp Hrbtmp]]]]]]]]]]]]]]]].\n\nexists A', nj, nbor; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nby rewrite -Hratmp.\n\n(** lwxs atmp j a; *)\n\napply hoare_lwxs_back_alt'' with (fun s h => exists A' nj nbor,\n  size A' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\ u2Z [k]_s = Z_of_nat nk /\\\n  (var_e a |--> A' ** var_e b |--> B) s h /\\\n  u2Z [j]_s = Z_of_nat nj /\\ (nj < nk)%nat /\\ u2Z [t]_s = u2Z va + 4 * Z_of_nat nj /\\\n  u2Z [bor]_s = nbor /\\ nbor <= 1 /\\ \\S_{ nj } A' = \\S_{ nj } A - \\S_{ nj } B + nbor * \\B^nj  /\\\n  drop nj A = drop nj A' /\\ [atmp]_s = A `32_ nj /\\\n  [btmp]_s = B `32_ nj `+ [bor]_s /\\\n  [u]_s = if Zlt_bool (u2Z [btmp]_s) (u2Z (B `32_ nj)) then one32 else zero32).\n\nmove=> s h [A' [nj [nbor [HlenA' [Hra [Hrb [Hrk [Hmem [Hrj [Hjk2 [Hrt [Hrbor [Hnbor [HInv [Hnth [Hrbtmp Hru]]]]]]]]]]]]]]]].\nexists (A' `32_ nj); split.\n- Decompose_32 A' nj A'1 A'2 HlenA'1 HA''; last by ssromega.\n  rewrite HA'' (decompose_equiv _ _ _ _ _ HlenA'1) !assert_m.conAE assert_m.conCE\n    !assert_m.conAE in Hmem.\n  move: Hmem; apply monotony => // h'.\n  apply mapsto_ext => //.\n  by rewrite /= shl_Z2u Hrj inj_mult mulZC.\n- rewrite /update_store_lwxs.\n  exists A', nj, nbor; repeat Reg_upd; repeat (split; trivial).\n  by Assert_upd.\n  rewrite (drop_nth zero32) in Hnth; last by ssromega.\n  symmetry in Hnth.\n  rewrite (drop_nth zero32) in Hnth; last by ssromega.\n  by case: Hnth.\n\n(** ifte_beq u, zero thendo *)\n\napply while.hoare_seq with (fun s h => exists A' nj nbor,\n  size A' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\ u2Z [k]_s = Z_of_nat nk /\\\n  (var_e a |--> A' ** var_e b |--> B) s h /\\\n  u2Z [j]_s = Z_of_nat nj /\\ (nj < nk)%nat /\\\n  u2Z [t]_s = u2Z va + 4 * Z_of_nat nj /\\ drop nj A = drop nj A' /\\\n  u2Z [bor]_s = nbor /\\ nbor <= 1 /\\\n  \\S_{ nj } A' + u2Z [atmp]_s * \\B^nj =\n  \\S_{ nj } A - \\S_{ nj } B + u2Z (A `32_ nj) * \\B^nj - u2Z (B `32_ nj) * \\B^nj + nbor * \\B^nj.+1).\n\napply while.hoare_ifte.\n\n(** addiu u r0 one16; *)\n\napply hoare_addiu with (fun s h => exists A' nj nbor,\n  size A' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\ u2Z [k]_s = Z_of_nat nk /\\\n  (var_e a |--> A' ** var_e b |--> B) s h /\\\n  [u]_s = one32 /\\ u2Z [j]_s = Z_of_nat nj /\\ (nj < nk)%nat /\\\n  u2Z [t]_s = u2Z va + 4 * Z_of_nat nj /\\ u2Z [bor]_s = nbor /\\\n  nbor <= 1 /\\ \\S_{ nj } A' = \\S_{ nj } A - \\S_{ nj } B + nbor * \\B^nj /\\\n  [atmp]_s = A `32_ nj /\\ drop nj A = drop nj A' /\\ [btmp]_s = B `32_ nj `+ [bor]_s /\\\n  u2Z [btmp]_s = u2Z (B `32_ nj) + nbor).\n\nmove=> s h [ [A' [nj [nbor [HlenC [Hra [Hrb [Hrk [Hmem [Hrj [Hjk2 [Hrt [Hrbor [Hnbor [HInv [Hnth [Hratmp [Hrbtmp Hru]]]]]]]]]]]]]]]]] Huzero]; rewrite /= in Huzero.\nexists A', nj, nbor; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nby rewrite add0i sext_Z2u.\nrewrite Hrbtmp -Hrbor u2Z_add //.\napply u2Z_add_no_overflow.\nrewrite -Hrbtmp.\napply Znot_gt_le; move/Z.gt_lt/ltZP => X.\nby rewrite Hru X Z2uK // Z2uK in Huzero.\n\n(** multu atmp one; *)\n\napply hoare_multu with (fun s h => exists A' nj nbor,\n  size A' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\ u2Z [k]_s = Z_of_nat nk /\\\n  (var_e a |--> A' ** var_e b |--> B) s h /\\\n  [u]_s = one32 /\\ u2Z [j]_s = Z_of_nat nj /\\ (nj < nk)%nat /\\\n  u2Z [t]_s = u2Z va + 4 * Z_of_nat nj /\\ u2Z [bor]_s = nbor /\\\n  nbor <= 1 /\\ \\S_{ nj } A' = \\S_{ nj } A - \\S_{ nj } B + nbor * \\B^nj /\\\n  [atmp]_s = A `32_ nj /\\ drop nj A = drop nj A' /\\ [btmp]_s = B `32_ nj `+ [bor]_s /\\\n  u2Z [btmp]_s = u2Z (B `32_ nj) + nbor /\\ store.utoZ s = u2Z (A `32_ nj)).\n\nmove=> s h [A' [nj [nbor [HlenC [Hra [Hrb [Hrk [Hmem [Hrone [Hrj [Hjk2 [Hrt [Hrbor [Hnbor [HInv [Hnth [Hratmp [Hrbtmp Hru]]]]]]]]]]]]]]]]]].\nexists A', nj, nbor; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nby rewrite store.utoZ_multu Hnth Hrone umul_1 (@u2Z_zext 32).\n\n(** msubu btmp one; *)\n\napply hoare_msubu with (fun s h => exists A' nj nbor,\n  size A' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\ u2Z [k]_s = Z_of_nat nk /\\\n  (var_e a |--> A' ** var_e b |--> B) s h /\\\n  [u]_s = one32 /\\ u2Z [j]_s = Z_of_nat nj /\\ (nj < nk)%nat /\\\n  u2Z [t]_s = u2Z va + 4 * Z_of_nat nj /\\ u2Z [bor]_s = nbor /\\ nbor <= 1 /\\\n  \\S_{ nj } A' = \\S_{ nj } A - \\S_{ nj } B + nbor * \\B^nj /\\ [atmp]_s = A `32_ nj /\\\n  drop nj A = drop nj A' /\\\n  [btmp]_s = B `32_ nj `+ [bor]_s /\\ u2Z [btmp]_s = u2Z (B `32_ nj) + nbor /\\\n  ((u2Z [btmp]_s <= u2Z (A `32_ nj) -> store.utoZ s = u2Z (A `32_ nj) - u2Z [btmp]_s) /\\\n   (u2Z (A `32_ nj) < u2Z [btmp]_s -> store.utoZ s = \\B^ 2 + u2Z (A `32_ nj) - u2Z [btmp]_s))).\n\nmove=> s h [A' [nj [nbor [HlenC [Hra [Hrb [Hrk [Hmem [Hone [Hrj [Hjk [Hrt [Hrbor [Hnbor [Hinv [Hratmp [Hnth [Hrbtmp [Hrbtmp2 Hm]]]]]]]]]]]]]]]]]]].\nexists A', nj, nbor.\nrewrite Hone umul_1.\nrepeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nmove=> H; rewrite store.msubu_utoZ Hm ?(@u2Z_zext 32) //.\napply (@ltZ_trans (\\B^1)); by [apply max_u2Z | ].\nexact/Z.le_ge.\nmove=> H; rewrite store.msubu_utoZ_overflow Hm ?(@u2Z_zext 32) //.\napply (@ltZ_trans (\\B^1)); by [exact: max_u2Z | ].\n\n(** sltu bor atmp btmp; *)\n\napply hoare_sltu with (fun s h => exists A' nj nbor,\n  size A' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\ u2Z [k]_s = Z_of_nat nk /\\\n  (var_e a |--> A' ** var_e b |--> B) s h /\\\n  u2Z [j]_s = Z_of_nat nj /\\ (nj < nk)%nat /\\\n  u2Z [t]_s = u2Z va + 4 * Z_of_nat nj /\\ nbor <= 1 /\\\n  \\S_{ nj } A' = \\S_{ nj } A - \\S_{ nj } B + nbor * \\B^nj /\\\n  [atmp]_s = A `32_ nj /\\\n  drop nj A = drop nj A' /\\\n  [btmp]_s = B `32_ nj `+ Z2u 32 nbor /\\\n  u2Z [btmp]_s = u2Z (B `32_ nj) + nbor /\\\n  (u2Z [btmp]_s <= u2Z (A `32_ nj) -> store.utoZ s = u2Z (A `32_ nj) - u2Z [btmp]_s) /\\\n  (u2Z (A `32_ nj) < u2Z [btmp]_s -> store.utoZ s = \\B^2 + u2Z (A `32_ nj) - u2Z [btmp]_s) /\\\n  [bor]_s = if Zlt_bool (u2Z (A `32_ nj)) (u2Z [btmp]_s) then one32 else zero32).\n\nmove=> s h [A' [nj [nbor [HlenC [Hra [Hrb [Hrk [Hmem [Hone [Hrj [Hjk [Hrt [Hrbor [Hnbor [Hinv [Hratmp [Hnth [Hrbtmp [Hrbtmp2 [Hinv1 Hinv2]]]]]]]]]]]]]]]]]]]].\n\nexists A', nj, nbor; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nby rewrite -Hrbor Z2u_u2Z.\nby rewrite -Hratmp.\n\n(** mflhxu atmp *)\n\napply hoare_mflhxu'.\nmove=> s h [A' [nj [nbor [HlenC [Hra [Hrb [Hrk [Hmem  [Hrj [Hjk [Hrt [Hnbor [Hinv [Hratmp [Hrbtmp [Hnth [Hrbtmp2 [Hm1 [Hm2 Hrbor]]]]]]]]]]]]]]]]]]].\n\ncase: (Z_lt_le_dec (u2Z (A `32_ nj)) (u2Z [btmp]_s)).\n- move/ltZP => X.\n  rewrite X in Hrbor.\n  move/ltZP in X.\n  exists A', nj, (u2Z one32); repeat Reg_upd; repeat (split; trivial).\n  by Assert_upd.\n  by rewrite Hrbor.\n  by rewrite Z2uK.\n  move: {Hm1 Hm2}(Hm2 X) => Hm.\n  have Hacx0 : store.acx s = Z2u store.acx_size 0 by apply store.utoZ_acx_beta2; rewrite Hm; lia.\n  rewrite store.utoZ_def Hacx0{Hacx0} Z2uK // in Hm.\n  rewrite mul0Z addZ0 in Hm.\n  rewrite (_ : \\B^2 = \\B^1 * (\\B^1 - 1) + \\B^1) // addZC (mulZC (\\B^1)) in Hm.\n  rewrite (_ : forall a b c d, a + b + c - d = a + (b + c - d)) in Hm; last by (move=> *; ring).\n  apply poly_eq_inv in Hm; last first.\n    rewrite Zbeta1E.\n    split; first exact: min_u2Z.\n    split; first by split; [apply min_u2Z | apply max_u2Z].\n    split; first by [].\n    move: (min_u2Z (A `32_ nj)) (max_u2Z [btmp]_s) => ? ?; lia.\n  case: Hm => _ ->.\n  rewrite Hinv (Zbeta_S nj) Hrbtmp2 Z2uK //; ring.\n- move/leZNgt/ltZP/negbTE => X.\n  rewrite X in Hrbor.\n  move/ltZP/leZNgt in X.\n  exists A', nj, (u2Z zero32); repeat Reg_upd; repeat (split; trivial).\n  by Assert_upd.\n  by rewrite Hrbor.\n  by rewrite Z2uK.\n  move: {Hm1 Hm2}(Hm1 X) => Hm.\n  have Hm_Zbeta1 : store.utoZ s < \\B^1.\n    move: (max_u2Z (A `32_ nj)) (min_u2Z [btmp]_s).\n    rewrite Hm -Zbeta1E => ? ?; lia.\n  case/store.utoZ_lo_beta1 : Hm_Zbeta1 => _ [_ <-].\n  rewrite Hinv Hm Hrbtmp2 Z2uK //; ring.\n\n(** nop; *)\n\napply hoare_nop'.\n\n(** we are in the branch where btmp = atmp + bor has overflowed *)\n\nmove=> s h [[A' [nj [nbor [HlenC [Hra [Hrb [Hrk [Hmem [Hrj [Hjk [Hrt [Hrbor [Hnbor [Hinv [Hnth [Hratmp [Hrbtmp Hru]]]]]]]]]]]]]]]]] Huzero].\nrewrite /= in Huzero. move/negbTE/eqP in Huzero.\nexists A', nj, nbor; repeat Reg_upd; repeat (split; trivial).\nhave [X1 X2] : nbor = 1 /\\ u2Z (B `32_ nj) = \\B^1 - 1.\n  have H : u2Z [btmp]_s < u2Z (B `32_ nj).\n    apply/ltZP.\n    apply: Bool.not_false_is_true => X; by rewrite Hru X in Huzero.\n  rewrite Hrbtmp in H.\n  apply u2Z_add_overflow' in H; rewrite -Zbeta1E in H.\n  move: (max_u2Z (B `32_ nj)) => H'; rewrite -Zbeta1E in H'; lia.\nrewrite Hratmp Hinv X1 X2 !mul1Z (Zbeta_S nj); ring.\n\n(** sw atmp zero16 t; *)\n\napply hoare_sw_back'' with (fun s h => exists A' nj nbor,\n size A' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\\n u2Z [k]_s = Z_of_nat nk /\\ (var_e a |--> A' ** var_e b |--> B) s h /\\\n u2Z [j]_s = Z_of_nat nj /\\ (nj < nk)%nat /\\\n u2Z [t]_s = u2Z va + 4 * Z_of_nat nj /\\ u2Z [bor]_s = nbor /\\\n nbor <= 1 /\\ \\S_{ S nj } A' = \\S_{ S nj } A - \\S_{ S nj } B + nbor * \\B^nj.+1 /\\\n drop (S nj) A = drop (S nj) A').\n\nmove=> s h [A' [nj [nbor [HlenA' [Hra [Hrb [Hrk [Hmem [Hrj [Hjk [Hrt [Hnth [Hrbor [Hnbor Hinv]]]]]]]]]]]]]].\n\nhave Htmp : [ var_e t \\+ int_e (sext 16 zero16) ]e_ s = [ var_e a \\+ int_e (Z2u 32 (Z_of_nat (4 * nj))) ]e_ s.\n  rewrite /= sext_Z2u // addi0.\n  apply u2Z_inj.\n  rewrite u2Z_add_Z_of_nat.\n  rewrite inj_mult Hrt Hra; ring.\n  rewrite inj_mult -Zbeta1E Hra; simpl Z_of_nat; ssromega.\n\nexists (int_e (A' `32_ nj)).\nDecompose_32 A' nj A'1 A'2 HlenA'1 HA''; last by ssromega.\n\nrewrite HA'' (decompose_equiv _ _ _ _ _ HlenA'1) !assert_m.conAE assert_m.conCE\n  !assert_m.conAE in Hmem.\nmove: Hmem; apply monotony => // ht.\nexact/mapsto_ext.\napply currying => h' H'; simpl app in H'.\nexists (upd_nth A' nj [atmp]_s), nj, nbor; repeat (split; trivial).\nexact: size_upd_nth.\nrewrite HA'' upd_nth_cat HlenA'1 // subnn /= (decompose_equiv _ _ _ _ _ HlenA'1).\nrewrite cat0s in H'.\nassoc_comm H'.\nexact: mapsto_ext H'.\n\nrewrite HA'' -cat1s.\nrewrite catA upd_nth_cat'; last by rewrite size_cat /= HlenA'1; ssromega.\nrewrite upd_nth_cat; last by rewrite HlenA'1; ssromega.\nrewrite HlenA'1 subnn; simpl upd_nth; rewrite -lSum_beyond; last by rewrite size_cat /= HlenA'1 addnC.\nrewrite (lSum_cut_last _ A'1) //; last by rewrite size_cat /= HlenA'1 addnC.\nrewrite HA'' -lSum_beyond // in Hinv.\nrewrite subn1 [_.+1.-1]/= -/(\\B^nj) mulZC Hinv.\n\nDecompose_32 A nj A1 A2 HlenA1 HA'; last by ssromega.\nrewrite {3}HA' -cat1s.\nrewrite -> catA. rewrite -lSum_beyond; last by rewrite size_cat /= HlenA1 addnC.\nrewrite (lSum_cut_last _ A1) //; last by rewrite size_cat /= HlenA1 addnC.\nrewrite -/(_ `32_ nj) subn1 [_.+1.-1]/=.\n\nDecompose_32 B nj B1 B2 HlenB1 HB'; last by ssromega.\nrewrite {3}HB' -[in X in _ = _ + _ - X + _]cat1s.\nrewrite -> catA. rewrite -lSum_beyond; last by rewrite size_cat /= HlenB1 addnC.\nrewrite (lSum_cut_last _ B1) //; last by rewrite size_cat /= HlenB1 addnC.\nrewrite -/(_ `32_ nj) subn1 [_.+1.-1]/=.\n\nrewrite HB' -lSum_beyond //.\nhave -> : (B1 ++ (B `32_ nj :: B2)) `32_ nj = B `32_ nj.\n  by rewrite /nth' nth_cat HlenB1 ltnn subnn.\nrewrite HA' -lSum_beyond //.\nhave -> : (A1 ++ (A `32_ nj :: A2)) `32_ nj = A `32_ nj.\n  by rewrite /nth' nth_cat HlenA1 ltnn subnn.\nrewrite -ZbetaE /=; ring.\n\nrewrite drop_upd_nth //.\nrewrite (drop_nth zero32) in Hnth; last by rewrite Ha.\nsymmetry in Hnth.\nrewrite (drop_nth zero32) in Hnth; last by rewrite HlenA'.\nby case: Hnth.\n\n(** addiu t t four16; *)\n\napply hoare_addiu with (fun s h => exists A' nj nbor,\n size A' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\\n u2Z [k]_s = Z_of_nat nk /\\ (var_e a |--> A' ** var_e b |--> B) s h /\\\n u2Z [j]_s = Z_of_nat nj /\\ (nj < nk)%nat /\\\n u2Z [t]_s = u2Z va + 4 * ((Z_of_nat nj) + 1) /\\ u2Z [bor]_s = nbor /\\\n nbor <= 1 /\\ \\S_{ S nj } A' = \\S_{ S nj } A - \\S_{ S nj } B + nbor * \\B^nj.+1 /\\ drop (S nj) A = drop (S nj) A').\n\nmove=> s h [A' [nj [nbor [HlenA' [Hra [Hrb [Hrk [Hmem [Hrj [Hjk [Hrt [Hbor [Hnbor [Hinv Hnth]]]]]]]]]]]]]].\n\nexists A', nj, nbor; repeat Reg_upd; repeat (split; trivial).\n- by Assert_upd.\n- rewrite u2Z_add sext_Z2u // Z2uK //.\n  lia.\n  rewrite -Zbeta1E; ssromega.\n\n(** addiu j j one16 *)\n\napply hoare_addiu'.\nmove=> s h [A' [nj [nbor [HlenC [Hra [Hrb [Hrk [Hmem [Hrj [Hjk [Hrt [Hbor [Hnbor [Hinv Hnth]]]]]]]]]]]]]].\n\nexists A', (S nj), nbor.\nrewrite Z_S.\nrepeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nrewrite u2Z_add sext_Z2u // Z2uK //.\n- lia.\n- move: (min_u2Z va) => ?; rewrite -Zbeta1E; ssromega.\nQed.\n\nLemma multi_sub_u_u_L_triple_B_le_A : uniq(k, a, b, t, j, u, bor, atmp, btmp, r0) ->\nforall nk va vb, u2Z va + 4 * Z_of_nat nk < \\B^1 ->\nforall A B, size A = nk -> size B = nk -> \\S_{ nk } B <= \\S_{ nk } A ->\n{{ fun s h => [a]_s = va /\\ [b]_s = vb /\\\n  u2Z [k]_s = Z_of_nat nk /\\\n  (var_e a |--> A ** var_e b |--> B) s h }}\n multi_sub_u_u k a b a t j u bor atmp btmp\n{{ fun s h => exists A', size A' = nk /\\ [a]_s = va /\\\n   [b]_s = vb /\\ u2Z [k]_s = Z_of_nat nk /\\\n   [bor]_s = zero32 /\\\n   (var_e a |--> A' ** var_e b |--> B) s h /\\\n   \\S_{ nk } A' = \\S_{ nk } A - \\S_{ nk } B }}.\nProof.\nmove=> Hset nk va vb Hna A B Ha Hb HAB.\neapply hoare_prop_m.hoare_weak; last by eapply multi_sub_u_u_L_triple; eauto.\nmove=> s h [A' [HlenA [Hra [Hrb [Hrk [Hmem [Hbor Hsum]]]]]]].\nhave X : u2Z [bor]_s = 0.\n  have {}Hsum : u2Z [bor ]_ s * \\B^nk + (\\S_{ nk } A - \\S_{ nk } B - \\S_{ nk } A') = 0 * \\B^nk + 0.\n    rewrite Hsum; ring.\n  apply poly_eq0_inv in Hsum.\n  tauto.\n  exact: expZ_ge0.\n  move: (min_lSum nk B) (min_lSum nk A') (max_lSum nk A) (max_lSum nk A') => ????.\n  rewrite ZbetaE; ssromega.\nexists A'; repeat (split => //).\nrewrite (_ : 0 = u2Z zero32) in X; last by rewrite Z2uK.\nby move/u2Z_inj : X.\nrewrite Hsum X mul0Z addZ0; reflexivity.\nQed.\n\nEnd multi_sub.\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_sub_u_u_L_triple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593171945416, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.27492347752926377}}
{"text": "Require Export Coq.NArith.NArith.\n\nRequire Export Bedrock.Memory Bedrock.Word.\nRequire Export\n        Fiat.BinEncoders.Env.Automation.SolverOpt\n        Fiat.BinEncoders.Env.BinLib.Bool\n        Fiat.BinEncoders.Env.BinLib.Core\n        Fiat.BinEncoders.Env.BinLib.Enum\n        Fiat.BinEncoders.Env.BinLib.FixInt\n        Fiat.BinEncoders.Env.Common.Compose\n        Fiat.BinEncoders.Env.Common.ComposeCheckSum\n        Fiat.BinEncoders.Env.Common.ComposeIf\n        Fiat.BinEncoders.Env.Common.Specs\n        Fiat.BinEncoders.Env.Common.WordFacts\n        Fiat.BinEncoders.Env.Lib.FixList\n        Fiat.BinEncoders.Env.Lib.IList\n        Fiat.BinEncoders.Env.Lib2.Bool\n        Fiat.BinEncoders.Env.Lib2.EnumOpt\n        Fiat.BinEncoders.Env.Lib2.FixListOpt\n        Fiat.BinEncoders.Env.Lib2.NatOpt\n        Fiat.BinEncoders.Env.Lib2.NoCache\n        Fiat.BinEncoders.Env.Lib2.SumTypeOpt\n        Fiat.BinEncoders.Env.Lib2.Vector\n        Fiat.BinEncoders.Env.Lib2.WordOpt\n        Fiat.BinEncoders.Env.Lib2.IPChecksum.\n\nUnset Implicit Arguments.\n\nOpen Scope nat_scope.\n\nNotation BoundedList A size := { ls: list A | List.length ls < size }.\nNotation BoundedNat size := { n: nat | (n < pow2 size)%nat }.\nNotation BoundedN size := { n: N | (n < FixInt.exp2 size)%N }.\n\nDefinition BoundedListLength {A size} (ls : BoundedList A (pow2 size)) : BoundedNat size :=\n  exist _ (length (` ls)) (proj2_sig ls).\n\nSection Nat.\n  Context {B : Type}.\n  Context {cache : Cache}.\n  Context {cacheAddNat : CacheAdd cache nat}.\n  Context {transformer : Transformer B}.\n  Context {transformerUnit : TransformerUnitOpt transformer bool}.\n\n  (* TODO move *)\n  Definition EncodeBoundedNat {k} (n : BoundedNat k) (ce : CacheEncode) : B * CacheEncode :=\n    (* NToWord + N.of_nat needed for performance (otherwise [apply] doesn't terminate) *)\n    encode_word_Impl (@NToWord k (N.of_nat (`n))) ce.\nEnd Nat.\n\n(* TODO move *)\nDefinition BtoW (b: B) : W :=\n  (zext b 24).\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/CertifiedExtraction/Extraction/BinEncoders/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.27488832005916625}}
{"text": "Require Import Fiat.QueryStructure.Automation.MasterPlan.\nRequire Import Fiat.QueryStructure.Specification.Constraints.DuplicateFree.\n\nDefinition int := nat.\nDefinition ERROR := 2. (* should have been defined as -1 *)\nDefinition FAILURE := 0.\nDefinition SUCCESS := 1.\n\nDefinition any := string.\n\nDefinition sSUBSCRIPTIONS := \"Subscriptions\".\nDefinition sPUBLICATIONS := \"Publications\".\nDefinition sSERVICES := \"Services\".\nDefinition sTOPICS := \"Topics\".\nDefinition sTOPIC := \"topic\".\nDefinition sNODE_ID := \"node_id\".\nDefinition sNODE_API := \"node_api\".\nDefinition sSERVICE_API := \"service_api\".\nDefinition sSERVICE := \"service\".\nDefinition sTOPIC_TYPE := \"topic_type\".\nDefinition sNODES := \"Nodes\".\nDefinition sPARAMS := \"Parameters\".\nDefinition sKEY := \"key\".\nDefinition sVALUE := \"value\".\nDefinition sPARAMSUBSCRIPTIONS := \"ParamSubscriptions\".\n\n(* what happen if the same tuple is repeatedly inserted in sNODES? *)\n(* want drop it when the same thing comes in *)\n\nDefinition stringPrefix str str' : Prop :=\n  prefix str str' = true.\n\nInstance prefixDecideable {B} (f : B -> _) str'\n    : DecideableEnsemble (fun str => stringPrefix (f str) str')\n    := { dec str := prefix (f str) str'}.\n  intros.\n  unfold stringPrefix. destruct (prefix (f a) str'); simpl; split; eauto.\nDefined.\n\nInstance prefixDecideable' {B} (f : B -> _) str'\n  : DecideableEnsemble (fun str => stringPrefix str' (f str))\n    := { dec str := prefix str' (f str)}.\n  intros.\n  unfold stringPrefix. destruct (prefix str' (f a)); simpl; split; eauto.\nDefined.\n\nDefinition RosMasterSchema :=\n  Query Structure Schema\n        [\n          relation sNODES has\n                   schema <sNODE_ID :: string, sNODE_API :: string>\n          where attributes [sNODE_API] depend on [sNODE_ID];\n\n            relation sTOPICS has\n                     schema <sTOPIC :: string, sTOPIC_TYPE :: string>\n          where attributes [sTOPIC_TYPE] depend on [sTOPIC];\n\n            relation sPARAMS has\n                     schema <sKEY :: string, sVALUE :: any>\n          where attributes [sVALUE] depend on [sKEY];\n\n            relation sSUBSCRIPTIONS has\n                     schema <sNODE_ID :: string, sTOPIC :: string>\n          where DuplicateFree;\n\n            relation sPARAMSUBSCRIPTIONS has\n                     schema <sNODE_ID :: string, sKEY :: string>\n          where DuplicateFree;\n\n            relation sPUBLICATIONS has\n                     schema <sNODE_ID :: string, sTOPIC :: string>\n          where DuplicateFree;\n\n            relation sSERVICES has\n                     schema <sNODE_ID :: string, sSERVICE :: string, sSERVICE_API :: string>\n          where attributes [sNODE_ID; sSERVICE_API] depend on [sSERVICE]\n        ]\n        enforcing [ attribute sNODE_ID for sSUBSCRIPTIONS references sNODES;\n                    attribute sTOPIC for sSUBSCRIPTIONS references sTOPICS;\n                    attribute sNODE_ID for sPUBLICATIONS references sNODES;\n                    attribute sTOPIC for sPUBLICATIONS references sTOPICS;\n                    attribute sNODE_ID for sPARAMSUBSCRIPTIONS references sNODES;\n                    attribute sKEY for sPARAMSUBSCRIPTIONS references sPARAMS ].\n\nDefinition RosMasterSig : ADTSig :=\n  ADTsignature {\n      Constructor \"Init\" : rep,\n\n      (* register/unregister methods *)\n\n      Method \"registerService\" : rep * string * string * string * string\n                                    -> rep * (int * string * int),\n\n      Method \"unregisterService\" : rep * string * string * string\n                                    -> rep * (int * string * int),\n\n      Method \"registerSubscriber\" : rep * string * string * string * string\n                                    -> rep * (int * string * list string),\n\n      Method \"unregisterSubscriber\" : rep * string * string * string\n                                      -> rep * (int * string * int),\n\n      Method \"registerPublisher\" : rep * string * string * string * string\n                                    -> rep * (int * string * list string),\n\n      Method \"unregisterPublisher\" : rep * string * string * string\n                                      -> rep * (int * string * int),\n\n      (* name service and system state *)\n\n      Method \"lookupNode\" : rep * string * string\n                          -> rep * (int * string * string),\n\n      Method \"getPublishedTopics\" : rep * string * string\n                          -> rep * (int * string * list (string * string)),\n\n      Method \"getTopicTypes\" : rep * string\n                               -> rep * (int * string * list (string * string)),\n\n      Method \"getSystemState\" : rep * string\n                          -> rep * (int * string * list ( list (string * list string) ) ),\n\n      Method \"getUri\" : rep * string\n                          -> rep * (int * string * string),\n\n      Method \"lookupService\" : rep * string * string\n                          -> rep * (int * string * string),\n\n      (* parameter server API *)\n\n      Method \"deleteParam\" : rep * string * string\n                             -> rep * (int * string * int),\n\n      Method \"setParam\" : rep * string * string * any\n                          -> rep * (int * string * int),\n\n      Method \"getParam\" : rep * string * string\n                          -> rep * (int * string * any),\n\n      Method \"searchParam\" : rep * string * string\n                             -> rep * (int * string * string),\n\n      Method \"subscribeParam\" : rep * string * string * string\n                              -> rep * (int * string * any),\n\n      Method \"unsubscribeParam\" : rep * string * string * string\n                                  -> rep * (int * string * int),\n\n      Method \"hasParam\" : rep * string * string\n                          -> rep * (int * string * bool),\n\n      Method \"getParamNames\" : rep * string\n                               -> rep * (int * string * list string)\n  }.\n\nDefinition RosMasterSpec : ADT RosMasterSig :=\n  Eval simpl in\n    Def ADT {\n      rep := QueryStructure RosMasterSchema,\n\n    Def Constructor0 \"Init\" : rep := empty,,\n\n    Def Method4 \"registerService\"\n      (r : rep) (caller_id : string) (service : string) (service_api : string) (caller_api : string)\n      : rep * (int * string * int)%type\n      :=\n\n        res1 <- Insert <sNODE_ID::caller_id, sSERVICE::service_api, sNODE_API::caller_api> into r ! sSERVICES;\n        If snd res1 Then\n          res2 <- Insert <sNODE_ID :: caller_id, sNODE_API :: caller_api> into (fst res1) ! sNODES;\n          If snd res2 Then\n            ret(fst res2, (SUCCESS, \"Service registered.\", 0))\n          Else\n            ret(r, (FAILURE, \"That node exists but with a different api.\", 0))\n        Else\n          ret(r, (FAILURE, \"That service is already being provided\", 0))\n    ,\n\n    Def Method3 \"unregisterService\"\n      (r : rep) (caller_id : string) (service : string) (service_api : string)\n      : rep * (int * string * int)%type\n      :=\n        res1 <- Delete serv from r ! sSERVICES\n                where (serv ! sNODE_ID = caller_id /\\ serv ! sSERVICE = service /\\ serv ! sSERVICE_API = service_api );\n\n        c1 <- ret (List.length (snd res1));\n\n        (* c1 should be either 0 or 1. How can it be guaranteed?*)\n\n        if beq_nat c1 0 then\n          ret (fst res1, (SUCCESS, \"Service was not registered in the first place.\", c1))\n        else\n          ret (fst res1, (SUCCESS, \"Service unsubscribed.\", c1))\n    ,\n\n\n    Def Method4 \"registerSubscriber\"\n      (r : rep) (caller_id : string) (topic : string) (topic_type : string) (caller_api : string)\n      : rep * (int * string * list string)%type\n      :=\n        res1 <- Insert <sNODE_ID :: caller_id, sTOPIC :: topic> into r ! sSUBSCRIPTIONS;\n\n        if (snd res1) then\n          (res2 <- Insert <sNODE_ID :: caller_id, sNODE_API :: caller_api> into (fst res1) ! sNODES;\n           if (snd res2) then\n             (res3 <- Insert <sTOPIC :: topic, sTOPIC_TYPE :: topic_type> into (fst res2) ! sTOPICS;\n              if snd res3 then\n                (publishers <- For (pub in r ! sPUBLICATIONS) (node in r ! sNODES)\n                            Where ( pub ! sTOPIC = topic  /\\  pub ! sNODE_ID = node ! sNODE_ID )\n                            Return ( node ! sNODE_API );\n                 ret(fst res3, (SUCCESS, \"You are now subscribed.  Publishers are:\", publishers)))\n              else\n                ret(r, (FAILURE, \"That topic exists but with a different type.\", [])))\n           else\n             ret(r, (FAILURE, \"That node exists but with a different api.\", [])))\n        else\n          ret(r, (FAILURE, \"You are already subscribed to that topic.\", []))\n    ,\n\n    Def Method3 \"unregisterSubscriber\"\n      (r : rep) (caller_id : string) (topic : string) (caller_api : string)\n      : rep * (int * string * int)%type\n      :=\n        res1 <- Delete sub from r ! sSUBSCRIPTIONS\n                where (sub ! sNODE_ID = caller_id /\\ sub ! sTOPIC = topic );\n\n        c1 <- ret (List.length (snd res1)); (* or, c1 <- Count (ret (snd res1)); *)\n\n        if beq_nat c1 0 then\n          ret (fst res1, (SUCCESS, \"You weren't subscribed to begin with.\", c1))\n        else\n          ret (fst res1, (SUCCESS, \"You are now unsubscribed.\", c1))\n    ,\n\n    Def Method4 \"registerPublisher\"\n      (r : rep) (caller_id : string) (topic : string) (topic_type : string) (caller_api : string)\n      : rep * (int * string * list string)%type\n      :=\n        res1 <- Insert <sNODE_ID :: caller_id, sTOPIC :: topic> into r ! sPUBLICATIONS;\n        If snd res1 Then\n           (res2 <- Insert <sNODE_ID :: caller_id, sNODE_API :: caller_api> into (fst res1) ! sNODES;\n            If snd res2 Then\n               (res3 <- Insert <sTOPIC :: topic, sTOPIC_TYPE :: topic_type> into (fst res2) ! sTOPICS;\n                If snd res3 Then\n                   subscribers <- For (sub in r ! sSUBSCRIPTIONS) (node in r ! sNODES)\n                   Where ( sub ! sTOPIC = topic  /\\  sub ! sNODE_ID = node ! sNODE_ID )\n                   Return ( node ! sNODE_API );\n\n                   ret(fst res3, (SUCCESS, \"You are now publishing.  Subscribers are:\", subscribers))\n               Else\n               ret(r, (FAILURE, \"That topic exists but with a different type.\", [])))\n           Else\n           ret(r, (FAILURE, \"That node exists but with a different api.\", [])))\n           Else\n           ret(r, (FAILURE, \"You are already publishing to that topic.\", [])),\n\n    Def Method3 \"unregisterPublisher\"\n      (r : rep) (caller_id : string) (topic : string) (caller_api : string)\n      : rep * (int * string * int)%type\n      :=\n        res1 <- Delete pub from r ! sPUBLICATIONS\n                where (pub ! sNODE_ID = caller_id /\\ pub ! sTOPIC = topic );\n\n        c1 <- ret (List.length (snd res1));\n\n        if beq_nat c1 0 then\n          ret (fst res1, (SUCCESS, \"You weren't publishing to begin with.\", c1))\n        else\n          ret (fst res1, (SUCCESS, \"You are now unregistered.\", c1))\n    ,\n\n    Def Method2 \"lookupNode\"\n      (r : rep) (caller_id : string) (node_name : string)\n      : rep * (int * string * string)%type\n      (* Returns (code, statusMessage, URI) *)\n      :=\n        apis <- For (node in r ! sNODES)\n              Where ( node ! sNODE_ID = node_name )\n              Return ( node ! sNODE_API );\n\n        api <- ret (List.hd \"\" apis);\n        c <- ret (List.length apis); (* should be either 0 or 1 *)\n\n        if beq_nat c 0 then\n          ret (r, (FAILURE, \"Node not found.\", api))\n        else\n          ret (r, (SUCCESS, \"Node URI is :\", api))\n    ,\n\n    Def Method2 \"getPublishedTopics\"\n      (r : rep) (caller_id : string) (subgraph : string)\n      : rep * (int * string * list (string * string))%type\n      (* Returns (code, statusMessage, [(topic,type)]) *)\n                                                           :=\n        res <- For (topic in r ! sTOPICS) (pub in r ! sPUBLICATIONS)\n            Where ( topic ! sTOPIC = pub ! sTOPIC)\n            Where (stringPrefix topic!sTOPIC subgraph )\n              Return ( (topic ! sTOPIC, topic ! sTOPIC_TYPE) );\n        ret (r, (SUCCESS, \"Topics with publishers are :\", res))  (* should remove duplicates *)\n    ,\n\n    Def Method1 \"getTopicTypes\"\n      (r : rep) (caller_id : string)\n      : rep * (int * string * list (string * string))%type\n      :=\n        res <- For (topic in r ! sTOPICS)\n              Return ( (topic ! sTOPIC, topic ! sTOPIC_TYPE) );\n        ret (r, (SUCCESS, \"Topics are :\", res))\n    ,\n\n    Def Method1 \"getSystemState\"\n      (r : rep) (caller_id : string)\n      : rep * (int * string * list (list (string * list string)) )%type\n        :=\n        publishers <- For (topic in r ! sTOPICS)\n                 (\n                   pubs <- For (pub in r ! sPUBLICATIONS)\n                             Where (topic ! sTOPIC = pub ! sTOPIC)\n                             Return (pub ! sNODE_ID);\n                   Return ( (topic ! sTOPIC, pubs) )\n                 );\n\n        subscribers <- For (topic in r ! sTOPICS)\n                 (\n                   subs <- For (sub in r ! sSUBSCRIPTIONS)\n                             Where (topic ! sTOPIC = sub ! sTOPIC)\n                             Return (sub ! sNODE_ID);\n                   Return ( (topic ! sTOPIC, subs) )\n                 );\n\n        services <- For (serv in r ! sSERVICES)\n                      Return (serv ! sSERVICE, [serv ! sNODE_ID]);\n\n        ret (r, (SUCCESS, \"System state is :\", [publishers; subscribers; services]))\n    ,\n\n    Def Method1 \"getUri\"\n      (r : rep) (caller_id : string)\n      : rep * (int * string * string)%type\n      :=\n        ret (r, (SUCCESS, \"My URI is :\", \"http://localhost:11311\"))\n    ,\n\n    Def Method2 \"lookupService\"\n      (r : rep) (caller_id : string) (service : string)\n      : rep * (int * string * string)%type\n      :=\n        ids <- For (serv in r ! sSERVICES)\n              Where ( serv ! sSERVICE = service )\n              Return ( serv ! sNODE_ID );\n\n        id <- ret (List.hd \"\" ids);\n        c <- ret (List.length ids); (* should be either 0 or 1 *)\n\n        if beq_nat c 0 then (* could use 'match ... with' instead of if *)\n          ret (r, (FAILURE, \"No one is provind that service.\", id))\n        else\n          ret (r, (SUCCESS, \"Service provider is :\", id)),\n\n            Def Method2 \"deleteParam\"\n      (r : rep) (caller_id : string) (key : string)\n      : rep * (int * string * int)%type\n      :=\n        res <- Delete param from r ! sPARAMS\n                where (param ! sKEY = key);\n        ret (fst res, (SUCCESS, \"Parameter deleted\", 0))\n    ,\n\n    Def Method3 \"setParam\"\n      (r : rep) (caller_id : string) (key : string) (value : any)\n      : rep * (int * string * int)%type\n      :=\n        res1 <- Delete param from r ! sPARAMS\n                where (param ! sKEY = key);\n\n        res2 <- Insert <sKEY :: key, sVALUE :: value> into (fst res1) ! sPARAMS;\n\n        ret (fst res2, (SUCCESS, \"Parameter set\", 0))\n    ,\n\n    Def Method2 \"getParam\" (* not supported for key being a namespace *)\n      (r : rep) (caller_id : string) (key : string)\n      : rep * (int * string * any)%type\n      := values <- For (param in r ! sPARAMS)\n                    Where ( param ! sKEY = key )\n                    Return ( param ! sVALUE  );\n        Ifopt hd_error values as v\n        Then\n        ret (r, (SUCCESS, \"Parameter value is :\", v))\n        Else\n        ret (r, (FAILURE, \"Parameter not set yet\", \"\"))\n    ,\n\n    Def Method2 \"searchParam\" (* unimplemented *)\n      (r : rep) (caller_id : string) (key : string)\n      : rep * (int * string * string)%type\n      := ret (r, (ERROR, \"This API is not implemented.\", \"\"))\n    ,\n\n    Def Method3 \"subscribeParam\"\n      (r : rep) (caller_id : string) (caller_api : string) (key : string)\n      : rep * (int * string * any)%type\n      :=\n\n        res1 <- Insert <sNODE_ID :: caller_id, sKEY :: key> into r ! sPARAMSUBSCRIPTIONS;\n        If snd res1 Then\n           res2 <- Insert <sNODE_ID :: caller_id, sNODE_API :: caller_api> into (fst res1) ! sNODES;\n        If snd res2 Then\n            values <- For (param in r ! sPARAMS)\n                    Where ( param ! sKEY = key )\n                    Return ( param ! sVALUE  );\n        Ifopt hd_error values as v Then\n           ret (fst res2, (SUCCESS, \"Parameter is not set yet.\", v))\n           Else ret (fst res2, (SUCCESS, \"Parameter value is :\", \"\"))\n          Else\n            ret(r, (FAILURE, \"That node exists but with a different api.\", \"\"))\n        Else\n          ret(r, (FAILURE, \"You are already subscribing to that parameter.\", \"\"))\n    ,\n\n    Def Method3 \"unsubscribeParam\"\n      (r : rep) (caller_id : string) (caller_api : string) (key : string)\n      : rep * (int * string * int)%type\n      :=\n        res1 <- Delete paramsub from r ! sPARAMSUBSCRIPTIONS\n                where (paramsub ! sNODE_ID = caller_id /\\ paramsub ! sKEY = key);\n\n        c1 <- ret (List.length (snd res1));\n\n        if beq_nat c1 0 then\n          ret (fst res1, (SUCCESS, \"You weren't subscribed to begin with.\", c1))\n        else\n          ret (fst res1, (SUCCESS, \"You are now unsubscribed.\", c1))\n    ,\n\n    Def Method2 \"hasParam\"\n      (r : rep) (caller_id : string) (key : string)\n      : rep * (int * string * bool)%type\n      := values <- For (param in r ! sPARAMS)\n                    Where ( param ! sKEY = key )\n                    Return ();\n        Ifopt hd_error values as _ Then\n          ret (r, (SUCCESS, \"Parameter is set.\", true))\n          Else ret (r, (FAILURE, \"Parameter is not set.\", false))\n                             ,\n\n    Def Method1 \"getParamNames\"\n      (r : rep) (caller_id : string)\n      : rep * (int * string * list string)%type\n      :=\n        keys <- For (param in r ! sPARAMS)\n                  Return (param ! sKEY);\n        ret (r, (SUCCESS, \"Parameter names are :\", keys))\n\n        }%methDefParsing.\n\nTheorem SharpenedRosMaster :\n  FullySharpened RosMasterSpec.\nProof.\n  start sharpening ADT.\n  start_honing_QueryStructure''.\n  - simpl.\n    GenerateIndexesForAll\n      EqExpressionAttributeCounter\n      ltac:(fun attrlist =>\n              let attrlist' := eval compute in (PickIndexes _ (CountAttributes' attrlist)) in 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    + doAny'\n        ltac:(implement_insert'\n                EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n                EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep)\n        ltac:(master_implement_drill EqIndexUse createEarlyEqualityTerm createLastEqualityTerm)\n               ltac:(repeat subst_refine_evar; try finish honing).\n    + doAny'\n        ltac:(implement_insert'\n                EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n                EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep)\n        ltac:(master_implement_drill EqIndexUse createEarlyEqualityTerm createLastEqualityTerm)\n               ltac:(repeat subst_refine_evar; try finish honing).\n    + doAny'\n        ltac:(implement_insert'\n                EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n                EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep)\n        ltac:(master_implement_drill EqIndexUse createEarlyEqualityTerm createLastEqualityTerm)\n               ltac:(repeat subst_refine_evar; try finish honing).\n    + doAny'\n        ltac:(implement_insert'\n                EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n                EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep)\n        ltac:(master_implement_drill EqIndexUse createEarlyEqualityTerm createLastEqualityTerm)\n               ltac:(repeat subst_refine_evar; try finish honing).\n    + doAny'\n        ltac:(implement_insert'\n                EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n                EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep)\n        ltac:(master_implement_drill EqIndexUse createEarlyEqualityTerm createLastEqualityTerm)\n               ltac:(repeat subst_refine_evar; try finish honing).\n    + doAny'\n        ltac:(implement_insert'\n                EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n                EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep)\n        ltac:(master_implement_drill EqIndexUse createEarlyEqualityTerm createLastEqualityTerm)\n               ltac:(repeat subst_refine_evar; try finish honing).\n    + doAny'\n        ltac:(implement_insert'\n                EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n                EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep)\n        ltac:(master_implement_drill EqIndexUse createEarlyEqualityTerm createLastEqualityTerm)\n               ltac:(repeat subst_refine_evar; try finish honing).\n    + doAny'\n        ltac:(implement_insert'\n                EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n                EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep)\n        ltac:(master_implement_drill EqIndexUse createEarlyEqualityTerm createLastEqualityTerm)\n               ltac:(repeat subst_refine_evar; try finish honing).\n    + doAny'\n        ltac:(implement_insert'\n                EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n                EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep)\n        ltac:(master_implement_drill EqIndexUse createEarlyEqualityTerm createLastEqualityTerm)\n               ltac:(repeat subst_refine_evar; try finish honing).\n    + doAny'\n        ltac:(implement_insert'\n                EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n                EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep)\n        ltac:(master_implement_drill EqIndexUse createEarlyEqualityTerm createLastEqualityTerm)\n               ltac:(repeat subst_refine_evar; try finish honing).\n      implement_nested_Query EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n                             EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep.\n      doAny'\n        ltac:(implement_insert'\n                EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n                EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep)\n        ltac:(master_implement_drill EqIndexUse createEarlyEqualityTerm createLastEqualityTerm)\n               ltac:(repeat subst_refine_evar; try finish honing).\n      implement_nested_Query EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n                             EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep.\n      doAny'\n        ltac:(implement_insert'\n                EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n                EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep)\n        ltac:(master_implement_drill EqIndexUse createEarlyEqualityTerm createLastEqualityTerm)\n               ltac:(repeat subst_refine_evar; try finish honing).\n    + doAny'\n        ltac:(implement_insert'\n                EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n                EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep)\n        ltac:(master_implement_drill EqIndexUse createEarlyEqualityTerm createLastEqualityTerm)\n               ltac:(repeat subst_refine_evar; try finish honing).\n    + doAny'\n        ltac:(implement_insert'\n                EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n                EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep)\n        ltac:(master_implement_drill EqIndexUse createEarlyEqualityTerm createLastEqualityTerm)\n               ltac:(repeat subst_refine_evar; try finish honing).\n    + doAny'\n        ltac:(implement_insert'\n                EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n                EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep)\n        ltac:(master_implement_drill EqIndexUse createEarlyEqualityTerm createLastEqualityTerm)\n               ltac:(repeat subst_refine_evar; try finish honing).\n    + doAny'\n        ltac:(implement_insert'\n                EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n                EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep)\n        ltac:(master_implement_drill EqIndexUse createEarlyEqualityTerm createLastEqualityTerm)\n               ltac:(repeat subst_refine_evar; try finish honing).\n    + doAny'\n        ltac:(implement_insert'\n                EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n                EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep)\n        ltac:(master_implement_drill EqIndexUse createEarlyEqualityTerm createLastEqualityTerm)\n               ltac:(repeat subst_refine_evar; try finish honing).\n    + doAny'\n        ltac:(implement_insert'\n                EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n                EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep)\n        ltac:(master_implement_drill EqIndexUse createEarlyEqualityTerm createLastEqualityTerm)\n               ltac:(repeat subst_refine_evar; try finish honing).\n    + doAny'\n        ltac:(implement_insert'\n                EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n                EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep)\n        ltac:(master_implement_drill EqIndexUse createEarlyEqualityTerm createLastEqualityTerm)\n               ltac:(repeat subst_refine_evar; try finish honing).\n    + doAny'\n        ltac:(implement_insert'\n                EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n                EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep)\n               ltac:(master_implement_drill EqIndexUse createEarlyEqualityTerm createLastEqualityTerm)\n                      ltac:(repeat subst_refine_evar; try finish honing).\n    + doAny'\n        ltac:(implement_insert'\n                EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n                EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep)\n        ltac:(master_implement_drill EqIndexUse createEarlyEqualityTerm createLastEqualityTerm)\n               ltac:(repeat subst_refine_evar; try finish honing).\n    + doAny'\n        ltac:(implement_insert'\n                EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n                EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep)\n               ltac:(master_implement_drill EqIndexUse createEarlyEqualityTerm createLastEqualityTerm)\n               ltac:(repeat subst_refine_evar; try finish honing).\n    + Finish_Master BuildEarlyBag BuildLastBag.\nTime Defined.\n\nTime Definition ROSMasterImpl : ComputationalADT.cADT _ :=\n  Eval simpl in projT1 SharpenedRosMaster.\n\nPrint ROSMasterImpl.\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/RosMaster.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778403, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.27488831405273273}}
{"text": "(* begin hide *)\nRequire Import Psatz.\n\nFrom Coq Require Import\n     Lists.List\n     Strings.String\n     Morphisms\n     ZArith\n     Setoid\n     RelationClasses.\n\nFrom ITree Require Import\n     Basics.Category\n     Basics.HeterogeneousRelations\n     ITree\n     ITreeFacts\n     Events.MapDefault\n     Events.MapDefaultFacts\n     Events.State.\n\nImport ITreeNotations.\n\nFrom ExtLib Require Import\n     Core.RelDec\n     Structures.Monad\n     Structures.Maps\n     Programming.Show\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\nFrom ITreeTutorial Require Import Fin Asm AsmCombinators Utils_tutorial.\n\n(* end hide *)\n\n(* optimizations ------------------------------------------------------------ *)\n\n(** A (simple) optimization is just a function from asm units to asm units. *)\n\nDefinition optimization {A B} := asm A B -> asm A B.\n\n(** An optimization is correct if it yields an equivalent computation.\n\n    - Note that eq_asm requires that resulting register environment and\n      the resulting heap must be equivalent, so this formulation of\n      correctness does not permit the elimination of local variables or\n      differences in the state.  Those optimizations would require\n      more contextual information.\n*)\n\n(** We define an appropriate notion of equivalence on these state components.\n    This will be useful for defining optimizations at the [Asm] level. *)\n\nDefinition EQ_registers (d:value) (regs1 regs2 : registers) : Prop :=\n  @eq_map _ _ _ _ d regs1 regs2.\n\nGlobal Instance EQ_registers_refl {d} : Reflexive (EQ_registers d).\nunfold EQ_registers. typeclasses eauto.\nQed.\n\nGlobal Instance EQ_registers_sym {d} : Symmetric (EQ_registers d).\nunfold EQ_registers. typeclasses eauto.\nQed.\n\nGlobal Instance EQ_registers_trans {d} : Transitive (EQ_registers d).\nunfold EQ_registers. typeclasses eauto.\nQed.\n\nGlobal Instance EQ_registers_eqv {d} : Equivalence (EQ_registers d).\nconstructor; typeclasses eauto.\nQed.\n\n\n\nDefinition EQ_memory (mem1 mem2 : memory) : Prop :=\n  @eq_map _ _ _ _ 0 mem1 mem2.\n\nGlobal Instance EQ_memory_refl : Reflexive (EQ_memory).\nunfold EQ_memory. typeclasses eauto.\nQed.\n\nGlobal Instance EQ_memory_sym : Symmetric (EQ_memory).\nunfold EQ_memory. typeclasses eauto.\nQed.\n\nGlobal Instance EQ_memory_trans : Transitive (EQ_memory).\nunfold EQ_memory. typeclasses eauto.\nQed.\n\nGlobal Instance EQ_memory_eqv : Equivalence (EQ_memory).\nconstructor; typeclasses eauto.\nQed.\n\nDefinition rel_asm {B} : memory * (registers * B) -> memory * (registers * B) -> Prop :=\n  prod_rel EQ_memory (prod_rel (EQ_registers 0) eq).\n\nGlobal Hint Unfold rel_asm: core.\n\n(** The definition [interp_asm] also induces a notion of equivalence (open)\n    _asm_ programs, which is just the equivalence of the ktree category *)\nDefinition eq_asm_denotations_EQ {E A B} (t1 t2 : Kleisli (itree (Reg +' Memory +' E)) A B) : Prop :=\n  forall a mem1 mem2 regs1 regs2,\n    EQ_memory mem1 mem2 ->\n    EQ_registers 0 regs1 regs2 ->\n    (eutt rel_asm)\n      (interp_asm (t1 a) mem1 regs1)\n      (interp_asm (t2 a) mem2 regs2).\n\nDefinition eq_asm_EQ {A B} (p1 p2 : asm A B) : Prop :=\n  eq_asm_denotations_EQ (denote_asm p1) (denote_asm p2).\n\nDefinition optimization_correct A B (opt:optimization) :=\n  forall (p : asm A B),\n    eq_asm_EQ p (opt p).\n\nDefinition EQ_asm {E A} (f g : memory -> registers -> itree E (memory * (registers * A))) : Prop :=\n  forall mem1 mem2 regs1 regs2,\n    EQ_memory mem1 mem2 ->\n    EQ_registers 0 regs1 regs2 ->\n    eutt (@rel_asm A) (f mem1 regs1) (g mem2 regs2).\n\nInfix \"≡\" := EQ_asm (at level 70).\n\nLemma interp_asm_ret_tt : forall (t : itree (Reg +' Memory +' Exit) unit),\n    (interp_asm t) ≡ (interp_asm (t ;; Ret tt)).\nProof.\n  intros t mem1 mem2 regs1 regs2 H1 H2.\n  rewrite interp_asm_bind.\n  rewrite <- bind_ret_r at 1.\n  apply (@eutt_clo_bind _ _ _ _ _ _ rel_asm).\n  { unfold interp_asm.\n    unfold rel_asm.\n    eapply interp_map_proper; try typeclasses eauto; auto.\n    eapply interp_map_proper; try typeclasses eauto; auto.\n    reflexivity.\n  }\n  intros.\n  inversion H; subst.\n  inversion H3. subst.\n  unfold interp_asm.\n  unfold interp_map.\n  rewrite interp_ret.\n  do 2 rewrite interp_state_ret.\n  apply eqit_Ret. constructor. auto. destruct b3.\n  assumption.\nQed.\n\nLemma interp_asm_ret {E A} (x:A) mem reg :\n  interp_asm (Ret x) mem reg ≈ (Ret (mem, (reg, x)) : itree E _).\nProof.\n  unfold interp_asm, interp_map.\n  rewrite interp_ret.\n  repeat rewrite interp_state_ret.\n  reflexivity.\nQed.\n\nGlobal Instance rel_asm_eqv :\n  forall A, Equivalence (@rel_asm A).\nProof.\n  intros.\n  unfold rel_asm. eapply prod_rel_eqv; try typeclasses eauto.\nQed.\n\nLemma interp_asm_GetReg {E A} f r mem reg :\n  @eutt E _ _ (@rel_asm A)\n       (interp_asm (val <- trigger (GetReg r) ;; f val) mem reg)\n       ((interp_asm (f (lookup_default r 0 reg))) mem reg).\nProof.\n  unfold interp_asm, interp_map.\n  rewrite interp_bind.\n  setoid_rewrite interp_trigger.\n  repeat rewrite interp_state_bind. cbn.\n  unfold subevent, resum, ReSum_inl, resum, ReSum_id, id_.\n  unfold Id_IFun.\n  unfold CategoryOps.cat, Cat_Handler, Handler.cat. cbn.\n  unfold lookup_def.\n  unfold embed, Embeddable_forall, embed, Embeddable_itree.\n  unfold trigger. rewrite interp_vis. setoid_rewrite interp_ret.\n  unfold subevent, resum.\n  repeat rewrite interp_state_bind.\n  repeat setoid_rewrite interp_state_ret.\n  unfold inl_, Inl_sum1_Handler, Handler.inl_, Handler.htrigger.\n  rewrite interp_state_trigger_eqit. cbn.\n  rewrite !bind_ret_l, !tau_eutt.\n  rewrite interp_state_ret.\n  rewrite !bind_ret_l, !tau_eutt.\n  rewrite !interp_state_ret; cbn.\n  rewrite bind_ret_l; cbn.\n  reflexivity.\nQed.\n\nLemma interp_asm_SetReg {E A} f r v mem reg :\n  @eutt E _ _ (@rel_asm A)\n       (interp_asm (trigger (SetReg r v) ;; f) mem reg)\n       ((interp_asm f) mem (Maps.add r v reg)).\nProof.\n  unfold interp_asm, interp_map.\n  rewrite interp_bind.\n  unfold trigger.\n  rewrite interp_vis.\n  unfold subevent, resum, ReSum_inl, resum, ReSum_id, id_. cbn.\n  setoid_rewrite interp_ret.\n  rewrite bind_bind.\n  setoid_rewrite tau_eutt.\n  setoid_rewrite bind_ret_l.\n  repeat rewrite interp_state_bind.\n  unfold Id_IFun.\n  unfold CategoryOps.cat, Cat_Handler, Handler.cat. cbn.\n  unfold inl_, Inl_sum1_Handler, Handler.inl_, Handler.htrigger.\n  unfold insert.\n  setoid_rewrite interp_trigger.\n  repeat rewrite interp_state_trigger_eqit.  cbn.\n  rewrite bind_ret_l, tau_eutt.\n  setoid_rewrite interp_state_ret.\n  rewrite bind_ret_l. cbn.\n  reflexivity.\nQed.\n\nLemma interp_asm_Load {E A} f a mem reg :\n  @eutt E _ _ (@rel_asm A)\n       (interp_asm (val <- trigger (Load a) ;; f val) mem reg)\n       ((interp_asm (f (lookup_default a 0 mem))) mem reg).\nProof.\n  unfold interp_asm, interp_map.\n  rewrite interp_bind.\n  rewrite interp_trigger.\n  unfold subevent, resum, ReSum_inr, resum, ReSum_inl, resum, ReSum_id, id_. cbn.\n  repeat rewrite interp_state_bind.\n  unfold Id_IFun.\n  unfold CategoryOps.cat, Cat_Handler, Handler.cat. cbn.\n  unfold CategoryOps.cat, Cat_Handler, Handler.cat. cbn.\n  unfold inl_, Inl_sum1_Handler, Handler.inl_, Handler.htrigger.\n  unfold inr_, Inr_sum1_Handler, Handler.inr_, Handler.htrigger.\n  unfold lookup_def.\n  repeat (setoid_rewrite interp_trigger; rewrite tau_eutt).\n  repeat rewrite interp_state_trigger_eqit.\n  cbn. unfold pure_state, embed, Embeddable_forall, embed, Embeddable_itree, trigger.\n  do 2 rewrite interp_vis, bind_vis.\n  rewrite interp_state_vis. cbn. rewrite bind_vis, interp_state_vis. cbn.\n  rewrite !bind_ret_l, !tau_eutt. rewrite !interp_ret, !interp_state_ret.\n  rewrite bind_ret_l; cbn.\n  reflexivity.\nQed.\n\nLemma interp_asm_Store {E A} f a v mem reg :\n  @eutt E _ _ (@rel_asm A)\n       (interp_asm (trigger (Store a v) ;; f) mem reg)\n       ((interp_asm f) (Maps.add a v mem) reg).\nProof.\n  unfold interp_asm, interp_map.\n  rewrite interp_bind.\n  rewrite interp_trigger.\n  unfold subevent, resum, ReSum_inr, resum, ReSum_inl, resum, ReSum_id, id_. cbn.\n  repeat rewrite interp_state_bind.\n  unfold Id_IFun.\n  unfold CategoryOps.cat, Cat_Handler, Handler.cat. cbn.\n  unfold CategoryOps.cat, Cat_Handler, Handler.cat. cbn.\n  unfold inl_, Inl_sum1_Handler, Handler.inl_, Handler.htrigger.\n  unfold inr_, Inr_sum1_Handler, Handler.inr_, Handler.htrigger.\n  unfold insert, embed, Embeddable_forall, embed, Embeddable_itree.\n  rewrite interp_trigger.\n  setoid_rewrite interp_trigger.\n  rewrite interp_state_trigger_eqit. cbn.\n  cbn. unfold pure_state, embed, Embeddable_forall, embed, Embeddable_itree, trigger.\n  rewrite bind_vis, interp_state_vis. cbn. rewrite !bind_ret_l, !tau_eutt.\n  rewrite interp_state_ret, bind_ret_l; cbn.\n  reflexivity.\nQed.\n\n(* peephole optimizations --------------------------------------------------- *)\n\n(** A (simple) peephole optmization transforms one instruction into a\n   (possibly empty) list of equivalent instructions. *)\nDefinition peephole_optimization := instr -> list instr.\n\n(** We lift peephole optimizations to _asm_ pointwise through the structures. *)\nFixpoint peephole_optimize_block {lbl} (ph : peephole_optimization) (b:block lbl) : block lbl :=\n  match b with\n  | bbi i k => blk_append (ph i) (peephole_optimize_block ph k)\n  | bbb l => bbb l\n  end.\n\nDefinition peephole_optimize_bks {A B} (ph : peephole_optimization) (bs : A -> block B) :=\n  fun (a:A) => peephole_optimize_block ph (bs a).\n\nDefinition peephole_optimize_asm {A B} (ph : peephole_optimization) (p : asm A B) : asm A B :=\n  Build_asm A B (p.(internal)) (peephole_optimize_bks ph (p.(code))).\n\n\n(* peephole correctness ----------------------------------------------------- *)\n\nSection Correctness.\n\n  (** A peephole optimizer is correct if it replaces an instruction with\n    a semantically equivalent sequence of instructions. *)\n  Definition ph_correct (ph : peephole_optimization) :=\n  forall (i:instr),\n    @eq_asm_denotations_EQ Exit unit _ (fun _ => denote_instr i) (fun _ => denote_list (ph i)).\n\n  Lemma ph_blk_append_correct : forall (ph : peephole_optimization) (H : ph_correct ph)\n    lbl1 lbl2 b1 b2 i,\n    (@eq_asm_denotations_EQ Exit (fin lbl1) (fin lbl2) (fun _ => denote_bk b1) (fun _ => denote_bk b2)) ->\n    (@eq_asm_denotations_EQ Exit (fin lbl1) (fin lbl2)\n                         (fun _ => denote_instr i ;; denote_bk b1)\n                         (fun _ => denote_bk (blk_append (ph i) b2))).\n  Proof.\n    intros ph H lbl1 lbl2 b1 b2 i HP.\n    unfold eq_asm_denotations_EQ.\n    intros a mem1 mem2 regs1 regs2 EQ_mem EQ_reg.\n    rewrite denote_blk_append.\n    unfold ph_correct in H.\n    unfold eq_asm_denotations_EQ in H.\n    specialize H with (i:=i).\n    pose proof (H tt) as H2.\n    do 2 rewrite interp_asm_bind.\n    eapply eutt_clo_bind.\n    apply H2; auto.\n    intros.\n    inversion H0; subst. inversion H3; subst.\n    apply HP; auto.\n  Qed.\n\n\nLemma peephole_block_correct :\n  forall (ph : peephole_optimization)\n    (H : ph_correct ph)\n    (lbl1 lbl2 : nat)\n    (b : block (fin lbl2)),\n    @eq_asm_denotations_EQ Exit (fin lbl1) (fin lbl2)\n                        (fun _ => denote_bk b)\n                        (fun _ => denote_bk (peephole_optimize_block ph b)).\nProof.\n  intros ph H lbl1 lbl2 b.\n  induction b.\n  - simpl.\n    unfold eq_asm_denotations_EQ.\n    intros.\n    eapply ph_blk_append_correct; try assumption. exact IHb. assumption.\n  - unfold eq_asm_denotations_EQ.\n    intros.\n    destruct b; simpl.\n    + unfold interp_asm.\n      rewrite interp_ret.\n      unfold interp_map.\n      repeat rewrite interp_state_ret.\n      apply eqit_Ret. constructor; auto; constructor; auto.\n    + setoid_rewrite interp_asm_GetReg.\n      rewrite H1.\n      unfold value in *.\n      remember (lookup_default r 0 regs2) as x.\n      destruct x.\n      repeat rewrite interp_asm_ret.\n      apply eqit_Ret. constructor; auto.\n      repeat rewrite interp_asm_ret.\n      apply eqit_Ret. constructor; auto. \n    + unfold interp_asm, interp_map.\n      unfold id_, Id_Handler, Handler.id_.\n      unfold exit.\n      rewrite interp_vis.\n      cbn. rewrite interp_state_bind.\n      unfold CategoryOps.cat, Cat_Handler, Handler.cat, inr_, Inr_sum1_Handler, Handler.inr_, Handler.htrigger.\n      setoid_rewrite interp_trigger.\n      unfold inr_.\n      rewrite interp_trigger.\n      rewrite interp_state_trigger_eqit.\n      rewrite interp_state_bind.\n      cbn. unfold pure_state.\n      rewrite bind_vis, interp_state_vis. cbn.\n      repeat rewrite bind_vis.\n      rewrite interp_state_bind.\n      rewrite interp_state_trigger_eqit. cbn.\n      rewrite !bind_vis, interp_state_vis. cbn.\n      rewrite bind_vis.\n      apply eqit_Vis; intros [].\nQed.\n\n\nLemma peephole_optimization_correct : forall A B (ph : peephole_optimization) (H : ph_correct ph),\n    optimization_correct A B (peephole_optimize_asm ph).\nProof.\n  intros A B ph H.\n  unfold optimization_correct.\n  intros p.\n  unfold eq_asm, eq_asm_denotations, denote_asm.\n  intros a mem1 mem2 regs1 regs2 H1 H2.\n  unfold interp_asm, interp_map.\n  repeat setoid_rewrite interp_bind.\n  repeat rewrite interp_state_bind.\n  apply (@eutt_clo_bind _ _ _ _ _ _ rel_asm).\n\n  { apply (@eutt_clo_bind _ _ _ _ _ _ rel_asm).\n    -  unfold inr_, Inr_Kleisli, lift_ktree_.\n       unfold ret, Monad_itree.\n       repeat rewrite interp_ret.\n       repeat rewrite interp_state_ret.\n       apply eqit_Ret. constructor; auto. \n    -  intros. inversion H0.\n       subst. cbn.\n       unfold CategorySub.from_bif, FromBifunctor_ktree_fin.\n       repeat rewrite interp_ret.\n       repeat rewrite interp_state_ret.\n       apply eqit_Ret.\n       inversion H4; subst.\n       constructor; auto. }\n\n  intros.\n  inversion H0; subst.\n  simpl in *.\n  unfold denote_bks.\n  unfold iter, CategorySub.Iter_sub.\n  repeat rewrite interp_iter.\n  unfold iter, Iter_Kleisli.\n  cbn.\n  pose proof @interp_state_iter'.\n  red in H5.\n  unfold Basics.iter, MonadIter_stateT0, Basics.iter, MonadIter_itree in *.\n  cbn in *.\n  repeat rewrite H5.\n\n  eapply eutt_iter' with (RI := rel_asm); cbn.\n  2: destruct H4; auto.\n  intros j1 j2 [ ? ? ? ? ? [? ? ? ? ? []]]; cbn.\n  rewrite !interp_bind, !interp_state_bind, !bind_bind. (* Slow! *)\n\n  apply (@eutt_clo_bind _ _ _ _ _ _ rel_asm);\n    [|intros ? ? [? ? ? ? ? [? ? ? ? ? []]]]; cbn.\n  { eapply @peephole_block_correct; eauto. }\n\n  unfold CategorySub.to_bif, ToBifunctor_ktree_fin.\n  apply (@eutt_clo_bind _ _ _ _ _ _ rel_asm);\n    [|intros ? ? [? ? ? ? ? [? ? ? ? ? []]]]; cbn.\n  {\n    rewrite bind_ret_l.\n    unfold case_, Case_sum1, Case_Kleisli, case_sum.\n    unfold CategoryOps.cat, CategorySub.Cat_sub, CategoryOps.cat, Cat_Kleisli.\n    unfold inl_, CategorySub.Inl_sub, inl_, Inl_Kleisli, lift_ktree_.\n    unfold inr_, CategorySub.Inr_sub, inr_, Inr_Kleisli, lift_ktree_.\n    unfold id_, CategorySub.Id_sub, id_, Id_Kleisli, lift_ktree_.\n    cbn.\n    unfold CategorySub.from_bif, FromBifunctor_ktree_fin.\n    destruct split_fin_sum.\n    all: rewrite !bind_ret_l, interp_ret, !interp_state_ret.\n    all: apply eqit_Ret; auto; constructor; auto.\n    all : constructor; auto.\n  }\n\n  rewrite interp_ret, !interp_state_ret, !bind_ret_l.\n  rewrite !interp_state_ret, !bind_ret_l; cbn.\n  apply eqit_Ret.\n  destruct split_fin_sum; auto; constructor; auto.\n  all : econstructor; auto.\n  all : constructor; auto.\nQed.\n\n\n(* concrete optimizations --------------------------------------------------- *)\n\nDefinition simple (i:instr) : list instr :=\n  match i with\n  | Imov dest (Oreg src) =>\n    if Nat.eqb dest src then [] else [i]\n  | _ => [i]\n  end.\n\n(* SAZ: Belongs in the utilities? (but depends on EQ_registers)\n   EQ_Registers is now just an alias for eq_map, so this can be moved to MapDefaultFacts.\n*)\nLemma EQ_registers_add:\n  forall (r : reg) (d:value) (regs1 regs2 : registers),\n    EQ_registers d regs1 regs2 ->\n    EQ_registers d (alist_add r (lookup_default r d regs1) regs1) regs2.\nProof.\n  intros r d regs1 regs2 H.\n  unfold EQ_registers.\n  unfold eq_map.\n  intros.\n  unfold lookup_default at 1, lookup, Map_alist.\n  destruct (Nat.eq_dec k r).\n  - subst. rewrite In_add_eq.\n    apply H.\n  - unfold lookup_default, lookup, Map_alist.\n    rewrite alist_find_neq; auto.\n    apply H.\nQed.\n\nLemma simple_correct : ph_correct simple.\nProof.\n  unfold ph_correct.\n  intros i.\n  unfold eq_asm_denotations_EQ.\n  intros.\n  destruct i; simpl; try apply interp_asm_ret_tt; auto; try reflexivity.\n\n  destruct src.\n  + simpl. rewrite !bind_ret_l.\n    apply interp_asm_ret_tt; auto; try reflexivity.\n\n  + simpl.\n    destruct (Nat.eq_dec dest r).\n    * subst.\n      rewrite Nat.eqb_refl.\n      simpl.\n      rewrite interp_asm_ret.\n      rewrite interp_asm_GetReg.\n\n      unfold trigger.\n      unfold interp_asm, interp_map.\n      rewrite interp_vis.\n      cbn.\n      repeat rewrite interp_state_bind.\n      unfold CategoryOps.cat, Cat_Handler, Handler.cat. simpl.\n      unfold inl_, Inl_sum1_Handler, Handler.inl_, Handler.htrigger.\n      unfold insert.\n      unfold embed, Embeddable_itree, Embeddable_forall, inl_, 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, bind_ret_l, interp_ret. cbn.\n      rewrite tau_eutt, 2 interp_state_ret.\n      apply eqit_Ret.\n      constructor; auto; constructor; auto.\n      auto using EQ_registers_add.\n    * apply Nat.eqb_neq in n.\n      rewrite n.\n      apply interp_asm_ret_tt; auto.\nQed.\n\nEnd Correctness.\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/tutorial/AsmOptimization.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.274888308046299}}
{"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\nRequire Import\n        Fiat.Narcissus.Common.Specs\n        Fiat.Narcissus.Formats.AsciiOpt.\nRequire Import\n        Bedrock.Word\n        Coq.ZArith.ZArith\n        Coq.Strings.Ascii\n        Coq.Strings.String.\n\nSection String.\n  (* this has an exact idential structure to _FixList_ *)\n  Context {B : Type}.\n  Context {cache : Cache}.\n  Context {cacheAddNat : CacheAdd cache nat}.\n  Context {monoid : Monoid B}.\n  Context {monoidUnit : QueueMonoidOpt monoid bool}.\n\n  Fixpoint format_string (xs : string) (ce : CacheFormat)\n    : Comp (B * CacheFormat) :=\n    match xs with\n    | EmptyString => ret (mempty, addE ce 0)\n    | String x xs' => `(b1, env1) <- format_ascii x ce;\n                      `(b2, env2) <- format_string xs' env1;\n                      ret (mappend b1 b2, env2)\n    end%comp.\n\n    Fixpoint encode_string (xs : string) (ce : CacheFormat) : B * CacheFormat :=\n    match xs with\n    | EmptyString => (mempty, addE ce 0)\n    | String x xs' => let (b1, env1) := encode_ascii x ce in\n                      let (b2, env2) := encode_string xs' env1 in\n                          (mappend b1 b2, env2)\n    end.\n\n  Fixpoint decode_string (s : nat) (b : B) (cd : CacheDecode) : option (string * B * CacheDecode) :=\n    match s with\n    | O => Some (EmptyString, b, addD cd 0)\n    | S s' => `(x, b1, e1) <- decode_ascii b cd;\n              `(xs, b2, e2) <- decode_string s' b1 e1;\n              Some (String x xs, b2, e2)\n    end.\n\n  Local Opaque format_ascii.\n  Local Opaque encode_ascii.\n\n  Theorem String_decode_correct\n          {P : CacheDecode -> Prop}\n          (P_OK : forall b cd, P cd -> P (addD cd b))\n    : forall sz,\n      CorrectDecoder\n        monoid\n        (fun ls => length ls = sz)\n        (fun ls => length ls = sz)\n        eq\n        format_string (decode_string sz) P\n        format_string.\n  Proof.\n    split.\n    { intros env env' xenv l l' ext ? Eeq Ppred Penc.\n      subst.\n      generalize dependent env.\n      revert env' xenv l' env_OK.\n      induction l.\n      { intros.\n        inversion Penc; subst; clear Penc.\n        rewrite mempty_left; eexists _, _; intuition eauto.\n        simpl; eauto.\n        apply add_correct; eauto.\n      }\n      { intros.\n        simpl in *.\n        unfold Bind2 in *; computes_to_inv; subst.\n        injection Penc''; intros; subst.\n        destruct v; destruct v0.\n        destruct (proj1 (Ascii_decode_correct P_OK) _ _ _ _ _ (mappend b0 ext) env_OK Eeq I Penc) as [? [? [? xenv_OK] ] ].\n      simpl. rewrite <- mappend_assoc, H; simpl; split_and; subst.\n      destruct (IHl _ _ _ H4 _ H1 Penc') as [? [? ?] ].\n      split_and; subst.\n      setoid_rewrite H3; simpl; eexists _, _;\n        intuition eauto.\n      simpl; unfold Bind2; eauto.\n      }\n    }\n    { induction sz; simpl; intros.\n      { split; eauto;\n          injections; repeat eexists; simpl; eauto using mempty_left.\n        apply add_correct; eauto.\n      }\n      { destruct (decode_ascii t env') as [ [ [? ?] ?] | ] eqn: ? ;\n          simpl in *; try discriminate.\n        destruct (decode_string sz b c) as [ [ [? ?] ?] | ] eqn: ? ;\n          simpl in *; try discriminate; injections.\n        eapply (proj2 (Ascii_decode_correct P_OK)) in Heqo; eauto;\n          destruct Heqo; destruct_ex; intuition; subst;\n            eapply IHsz in Heqo0; eauto; destruct Heqo0;\n              destruct_ex; intuition; subst.\n        simpl.\n        eexists _, _; intuition eauto.\n        computes_to_econstructor; eauto.\n        computes_to_econstructor; eauto.\n        rewrite mappend_assoc; reflexivity.\n      }\n    }\n  Qed.\n\n  Theorem decode_string_lt\n    : forall len (lt_len : lt 0 len)\n             (b3 : B)\n             (cd0 : CacheDecode)\n             (a : string) (b' : B)\n             (cd' : CacheDecode),\n      decode_string len b3 cd0 = Some (a, b', cd') -> lt_B b' b3.\n  Proof.\n    induction len; simpl; intros; try omega.\n    destruct (decode_ascii b3 cd0) as [ [ [? ?] ?] | ] eqn: ? ;\n      simpl in *; try discriminate.\n    eapply ascii_decode_lt in Heqo.\n    destruct (decode_string len b c) as [ [ [? ?] ?] | ] eqn: ? ;\n      simpl in *; try discriminate.\n    injections.\n    inversion lt_len; subst; simpl in *.\n    - injections; eauto.\n    - eapply IHlen in Heqo0; eauto; unfold lt_B in *; omega.\n  Qed.\n\nEnd String.\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/FixStringOpt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.274888308046299}}
{"text": "From iris_io Require Export lang.\n\nModule Ghostlang.\n  Inductive expr :=\n  | Var (x : var)\n  | Rec (e : {bind 2 of expr})\n  | Lam (e : {bind expr})\n  | LetIn (e : expr) (e : {bind expr})\n  | GRLetIn (e : expr) (e : {bind expr})\n  | Seq (e1 e2 : expr)\n  | GRSeq (e1 e2 : expr)\n  | App (e1 e2 : expr)\n  (* Base Types *)\n  | Unit\n  | Nat (n : nat)\n  | Bool (b : bool)\n  | BinOp (op : binop) (e1 e2 : expr)\n  (* If then else *)\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 : {bind expr}) (e2 : {bind expr})\n  (* Recursive Types *)\n  | Fold (e : expr)\n  | Unfold (e : expr)\n  (* Polymorphic Types *)\n  | TLam (e : expr)\n  | TApp (e : expr)\n  (* Concurrency *)\n  | Fork (e : expr)\n  (* Reference Types *)\n  | Loc (l : loc)\n  | IOtag (t : ioTag)\n  | Alloc (e : expr)\n  | Load (e : expr)\n  | Store (e1 : expr) (e2 : expr)\n  (* Compare and swap used for fine-grained concurrency *)\n  | CAS (e0 : expr) (e1 : expr) (e2 : expr)\n  (* Instrumenting Prophecies *)\n  | Pr (l : loc)\n  | Create_Pr\n  | Assign_Pr (e1 e2 : expr)\n  (* Random bit *)\n  | Rand\n  (* I/O *)\n  | IO (e1 e2 : expr).\n\n  Fixpoint instr(e: expr): Plang.expr :=\n    match e with\n      Var x => Plang.Var x\n    | Rec e => Plang.Rec (instr e)\n    | Lam e => Plang.Lam (instr e)\n    | LetIn e1 e2 => Plang.LetIn (instr e1) (instr e2)\n    | GRLetIn e1 e2 => Plang.LetIn (instr e1) (instr e2)\n    | Seq e1 e2 => Plang.Seq (instr e1) (instr e2)\n    | GRSeq e1 e2 => Plang.Seq (instr e1) (instr e2)\n    | App e1 e2 => Plang.App (instr e1) (instr e2)\n    | Unit => Plang.Unit\n    | Nat n => Plang.Nat n\n    | Bool b => Plang.Bool b\n    | BinOp op e1 e2 => Plang.BinOp op (instr e1) (instr e2)\n    | If e0 e1 e2 => Plang.If (instr e0) (instr e1) (instr e2)\n    | Pair e1 e2 => Plang.Pair (instr e1) (instr e2)\n    | Fst e => Plang.Fst (instr e)\n    | Snd e => Plang.Snd (instr e)\n    | InjL e => Plang.InjL (instr e)\n    | InjR e => Plang.InjR (instr e)\n    | Case e0 e1 e2 => Plang.Case (instr e0) (instr e1) (instr e2)\n    | Fold e => Plang.Fold (instr e)\n    | Unfold e => Plang.Unfold (instr e)\n    | TLam e => Plang.TLam (instr e)\n    | TApp e => Plang.TApp (instr e)\n    | Fork e => Plang.Fork (instr e)\n    | Loc l => Plang.Loc l\n    | IOtag t => Plang.IOtag t\n    | Alloc e => Plang.Alloc (instr e)\n    | Load e => Plang.Load (instr e)\n    | Store e1 e2 => Plang.Store (instr e1) (instr e2)\n    | CAS e0 e1 e2 => Plang.CAS (instr e0) (instr e1) (instr e2)\n    | Pr l => Plang.Pr l\n    | Create_Pr => Plang.Create_Pr\n    | Assign_Pr e1 e2 => Plang.Assign_Pr (instr e1) (instr e2)\n    | Rand => Plang.Rand\n    | IO e1 e2 => Plang.IO (instr e1) (instr e2)\n    end.\n\n  Fixpoint ghost_ok(e: expr): Prop :=\n    match e with\n    | Var x => True\n    | Create_Pr => True\n    | Assign_Pr e1 e2 => ghost_ok e1 /\\ ghost_ok e2\n    | _ => False\n    end.\n\n  Inductive var_erases_to: list bool -> var -> var -> Prop :=\n  | var_erases_to_real_O gs:\n    var_erases_to (false :: gs) O O\n  | var_erases_to_real_S gs x x':\n    var_erases_to gs x x' ->\n    var_erases_to (false :: gs) (S x) (S x')\n  | var_erases_to_ghost_S gs x x':\n    var_erases_to gs x x' ->\n    var_erases_to (true :: gs) (S x) x'\n  .\n\n  Inductive erases_to: list bool -> expr -> Plang.expr -> Prop :=\n  | Var_erases_to gs x x':\n    var_erases_to gs x x' ->\n    erases_to gs (Var x) (Plang.Var x')\n  | Rec_erases_to gs e e':\n    erases_to (false :: false :: gs) e e' ->\n    erases_to gs (Rec e) (Plang.Rec e')\n  | Lam_erases_to gs e e':\n    erases_to (false :: gs) e e' ->\n    erases_to gs (Lam e) (Plang.Lam e')\n  | LetIn_erases_to gs e1 e2 e1' e2':\n    erases_to gs e1 e1' ->\n    erases_to (false :: gs) e2 e2' ->\n    erases_to gs (LetIn e1 e2) (Plang.LetIn e1' e2')\n  | GRLetIn_erases_to gs e1 e2 e2':\n    ghost_ok e1 ->\n    erases_to (true :: gs) e2 e2' ->\n    erases_to gs (GRLetIn e1 e2) e2'\n  | Seq_erases_to gs e1 e2 e1' e2':\n    erases_to gs e1 e1' ->\n    erases_to gs e2 e2' ->\n    erases_to gs (Seq e1 e2) (Plang.Seq e1' e2')\n  | GRSeq_erases_to gs e1 e2 e2':\n    ghost_ok e1 ->\n    erases_to gs e2 e2' ->\n    erases_to gs (GRSeq e1 e2) e2'\n  | App_erases_to gs e1 e2 e1' e2':\n    erases_to gs e1 e1' ->\n    erases_to gs e2 e2' ->\n    erases_to gs (App e1 e2) (Plang.App e1' e2')\n  | Unit_erases_to gs:\n    erases_to gs Unit Plang.Unit\n  | Nat_erases_to gs n:\n    erases_to gs (Nat n) (Plang.Nat n)\n  | Bool_erases_to gs b:\n    erases_to gs (Bool b) (Plang.Bool b)\n  | BinOp_erases_to gs op e1 e2 e1' e2':\n    erases_to gs e1 e1' ->\n    erases_to gs e2 e2' ->\n    erases_to gs (BinOp op e1 e2) (Plang.BinOp op e1' e2')\n  | If_erases_to gs e0 e1 e2 e0' e1' e2':\n    erases_to gs e0 e0' ->\n    erases_to gs e1 e1' ->\n    erases_to gs e2 e2' ->\n    erases_to gs (If e0 e1 e2) (Plang.If e0' e1' e2')\n  | Pair_erases_to gs e1 e2 e1' e2':\n    erases_to gs e1 e1' ->\n    erases_to gs e2 e2' ->\n    erases_to gs (Pair e1 e2) (Plang.Pair e1' e2')\n  | Fst_erases_to gs e e':\n    erases_to gs e e' ->\n    erases_to gs (Fst e) (Plang.Fst e')\n  | Snd_erases_to gs e e':\n    erases_to gs e e' ->\n    erases_to gs (Snd e) (Plang.Snd e')\n  | InjL_erases_to gs e e':\n    erases_to gs e e' ->\n    erases_to gs (InjL e) (Plang.InjL e')\n  | InjR_erases_to gs e e':\n    erases_to gs e e' ->\n    erases_to gs (InjR e) (Plang.InjR e')\n  | Case_erases_to gs e0 e1 e2 e0' e1' e2':\n    erases_to gs e0 e0' ->\n    erases_to (false :: gs) e1 e1' ->\n    erases_to (false :: gs) e2 e2' ->\n    erases_to gs (Case e0 e1 e2) (Plang.Case e0' e1' e2')\n  | Fold_erases_to gs e e':\n    erases_to gs e e' ->\n    erases_to gs (Fold e) (Plang.Fold e')\n  | Unfold_erases_to gs e e':\n    erases_to gs e e' ->\n    erases_to gs (Unfold e) (Plang.Unfold e')\n  | TLam_erases_to gs e e':\n    erases_to gs e e' ->\n    erases_to gs (TLam e) (Plang.TLam e')\n  | TApp_erases_to gs e e':\n    erases_to gs e e' ->\n    erases_to gs (TApp e) (Plang.TApp e')\n  | Fork_erases_to gs e e':\n    erases_to gs e e' ->\n    erases_to gs (Fork e) (Plang.Fork e')\n  | Loc_erases_to gs l:\n    erases_to gs (Loc l) (Plang.Loc l)\n  | IOtag_erases_to gs t:\n    erases_to gs (IOtag t) (Plang.IOtag t)\n  | Alloc_erases_to gs e e':\n    erases_to gs e e' ->\n    erases_to gs (Alloc e) (Plang.Alloc e')\n  | Load_erases_to gs e e':\n    erases_to gs e e' ->\n    erases_to gs (Load e) (Plang.Load e')\n  | Store_erases_to gs e1 e2 e1' e2':\n    erases_to gs e1 e1' ->\n    erases_to gs e2 e2' ->\n    erases_to gs (Store e1 e2) (Plang.Store e1' e2')\n  | CAS_erases_to gs e0 e1 e2 e0' e1' e2':\n    erases_to gs e0 e0' ->\n    erases_to gs e1 e1' ->\n    erases_to gs e2 e2' ->\n    erases_to gs (CAS e0 e1 e2) (Plang.CAS e0' e1' e2')\n  | Rand_erases_to gs:\n    erases_to gs Rand Plang.Rand\n  | IO_erases_to gs e1 e2 e1' e2':\n    erases_to gs e1 e1' ->\n    erases_to gs e2 e2' ->\n    erases_to gs (IO e1 e2) (Plang.IO e1' e2')\n  .\n\nEnd Ghostlang.", "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_ghost.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2748019224645231}}
{"text": "Require Import String.\nRequire Import Ascii.\nRequire Import ListSet.\n\n(* Symbolic models in cryptography *)\n(*\n        - Literal : atomic messages\n        - Pair : injective pairing operation\n\n    Primitive keyed cryptographic operators :\n        - HMac (symmetric cryptographic primitive) : use to prove the origin of a message by providing evidence of knowledge \n            of a shared secret used as key. Its validity is checked by comparing the received MAC to a freshly computed one.\n        - Symmetric encryption (SEnc) : protect the secrecy of a message whilst allowing principals who know the encryption\n            key to retrieve the message by decrypting its encryption.\n\n        - Sign and Enc (assymetric cryptographic primitive) : same functionalities, but use key pairs, one public and one private.\n*)\n\nInductive term: Type :=\n    | Literal (b: string)\n    | Pair (a: term) (b: term)\n    | HMac (k: term) (p: term)\n    | SEnc (k: term) (p: term)\n    | Sign (k: term) (p: term)\n    | Enc (k: term) (p: term).\n\n(* Signature: Protocol Usages and Events *)\n\nModule Type ProtocolDefs.\n    Parameter nonce_usage: Type.\n    Parameters hmac_usage senc_usage: Type.\n    Parameters sign_usage enc_usage: Type.\n    Parameter pEvent: Type.\nEnd ProtocolDefs.\n\n(* Protocol Example: an Authenticated RPC Protocol\n    a       : Log(Request(a, b, req))\n    a -> b  : req | hmac(kab, Literal([TagRequest]) | req)\n    b       : assert(Request(a, b, req))\n    b       : Log(Response(a, b, req, resp))\n    b -> a  : resp | hmac(kab, Literal([TagResponse]) | req | resp)\n    a       : assert(Response(a, b, req, resp))\n*)\n\nModule RPCDefs <: ProtocolDefs.\n    Parameter TagRequest: ascii.\n    Parameter TagResponse: ascii.\n    Parameter TagsDistinct: TagRequest <> TagResponse.\n\n    Definition nonce_usage := False.\n    Definition senc_usage := False.\n    Definition sign_usage := False.\n    Definition enc_usage := False.\n\n    Inductive hmac_usage' :=\n        | U_KeyAB (a b: term).\n    Definition hmac_usage := hmac_usage'.\n\n    Inductive pEvent' :=\n        | Request (a b req: term)\n        | Response (a b req resp: term)\n        | Bad (p: term).\n    Definition pEvent := pEvent'.\nEnd RPCDefs.\n\n(* Protocol Example: Encrypted RPC Protocol\n    a       : Log(Request(a, b, req))\n    a       : k = keygen()\n    a -> b  : senc(kab, req | k)\n    b       : assert(Request(a, b, req))\n    b       : Log(Response(a, b, req, resp))\n    b -> a  : senc(k, resp)\n    a       : assert(Response(a, b, req, resp))\n*)\n\nModule ERPCDefs <: ProtocolDefs.\n    Parameter TagRequest: ascii.\n    Parameter TagResponse: ascii.\n    Parameter TagsDistinct: TagRequest <> TagResponse.\n\n    Inductive nonce_usage' :=\n        | U_RequestN (a b: term)\n        | U_ResponseN (a b: term).\n    Definition nonce_usage := nonce_usage'.\n\n    Inductive senc_usage' :=\n        | U_SKeyAB (a b req: term)\n        | U_KeyAB (a b: term).\n    Definition senc_usage := senc_usage'.\n\n    Definition hmac_usage := False.\n    Definition sign_usage := False.\n    Definition enc_usage := False.\n\n    Inductive pEvent' :=\n        | Request (a b req: term)\n        | Response (a b req resp: term)\n        | Bad (p: term).\n    Definition pEvent := pEvent'.\nEnd ERPCDefs.\n\n(* Protocol Example: Otway-Rees Protocol \n    i       : ni = fresh()\n    i -> r  : i | ni\n    r       : nr = fresh()\n    r -> s  : i | r | ni | nr\n    s       : kir = keygen()\n    s       : Log(Initiator(i, ni, kir, r))\n    s       : Log(Responder(r, nr, kir, i))\n    s -> r  : senc(ki, i | r | kir | ni) | senc(kr, i | r | kir | nr)\n    r       : Log(Responder(i, nr, kir, r))\n    r -> i  : senc(ki, i | r | kir | ni)\n    i       : assert(Initiator(i, ni, kir, r))\n*)\n\nModule OtwayReesDefs <: ProtocolDefs.\n    Parameter TagRequest: ascii.\n    Parameter TagResponse: ascii.\n    Parameter TagsDistinct: TagRequest <> TagResponse.\n    \n    Definition nonce_usage := False.\n    Definition sign_usage := False.\n    Definition enc_usage := False.\n\n    Inductive hmac_usage' :=\n        | U_KeyAB (a b: term).\n    Definition hmac_usage := hmac_usage'.\n\n    Inductive senc_usage' :=\n        | U_SKeyAB (p: term).\n    Definition senc_usage := senc_usage'.\n\n    Inductive pEvent' :=\n        | Request (a b req: term)\n        | Response (a b req resp: term)\n        | Initiator (p np kpb b: term)\n        | Responder (p np kap a: term)\n        | Bad (p: term).\n    Definition pEvent := pEvent'.    \nEnd OtwayReesDefs.\n\n(* General Usages and Events *)\n\nModule Defs (PD : ProtocolDefs).\n    Include PD.\n\n    Inductive usage: Type :=\n        | AdversaryGuess\n        | Nonce (nu: nonce_usage)\n        | HMacKey (hu: hmac_usage)\n        | SEncKey (eu: senc_usage)\n        | SignKey (su: sign_usage)\n        | VerfKey (su: sign_usage)\n        | EncKey (eu: enc_usage)\n        | DecKey (eu: enc_usage).\n\n    Inductive event: Type :=\n        | New (t: term) (u: usage)\n        | AsymPair (pk: term) (sk: term)\n        | ProtEvent (pe: pEvent).\n\n    (* Definition of logs, here as simple sets of events. Also, some definitions of membership and inclusion order. *)\n    Definition log: Type := set event.\n    Definition Logged (e: event) (L: log): Prop := set_In e L.\n    Definition LoggedP (e: pEvent) (L: log): Prop := Logged (ProtEvent e) L.\n    Definition leq_log (L L': log): Prop := forall e, Logged e L -> Logged e L'.\n\n    (* Notion of stability of log-dependant predicates under addition of events to the log *)\n    Definition Stable (P: log -> Prop) := forall L L', \n        leq_log L L' -> P L -> \n        P L'.\n    (* General well-formedness condition stating that any given term can have at most one usage, and that the components of asymmetric\n        keypairs must have the same primitive usage, and use the appropriate usage constructor. *)\n    Definition WF_Log (L: log): Prop :=\n        (forall t u u',\n            Logged (New t u) L ->\n            Logged (New t u') L -> u = u') /\\\n        (forall pk sk,\n            Logged (AsymPair pk sk) L ->\n            ((exists su,\n                Logged (New pk (VerfKey su)) L /\\\n                Logged (New sk (SignKey su)) L) \\/\n            (exists eu,\n                Logged (New pk (EncKey eu)) L /\\\n                Logged (New sk (DecKey eu)) L))).\nEnd Defs.\n\n(* Signature: Protocol Invariants *)\nModule Type ProtocolInvariants (PD: ProtocolDefs).\n    Include Defs PD.\n    (* Additional well-formedness invariant on the log, meant to represent conditions enforced by the key management infrastructure\n        (for example, unidirectionality of keys) *)\n    Parameter LogInvariant: log -> Prop.\n\n    (* As follow : \n        - a release primComp for each kind of primitive usage, and proofs that the release conditions are stable\n        - a payload condition canPrim for each kind of primitive key usage (excluding nonces), also equipped with proofs of stability.\n        Note : Assymetric cryptography is treated in the same way\n    *)\n\n    (* Nonce Predicate *)\n    Parameter nonceComp: term -> log -> Prop.\n    Parameter nonceComp_Stable: forall t, Stable (nonceComp t).\n\n    (* HMAC Predicates *)\n    Parameter hmacComp: term -> log -> Prop.\n    Parameter hmacComp_Stable: forall t, Stable (hmacComp t).\n\n    Parameter canHmac: term -> term -> log -> Prop.\n    Parameter canHmac_Stable: forall k p, Stable (canHmac k p).\n\n    (* SEnc Predicates *)\n    Parameter sencComp: term -> log -> Prop.\n    Parameter sencComp_Stable: forall t, Stable (sencComp t).\n\n    Parameter canSEnc: term -> term -> log -> Prop.\n    Parameter canSEnc_Stable: forall k p, Stable (canSEnc k p).\n\n    (* Sign Predicates *)\n    Parameter sigComp: term -> log -> Prop.\n    Parameter sigComp_Stable: forall t, Stable (sigComp t).\n\n    Parameter canSign: term -> term -> log -> Prop.\n    Parameter canSign_Stable: forall k p, Stable (canSign k p).\n\n    (* Enc Predicates *)\n    Parameter encComp: term -> log -> Prop.\n    Parameter encComp_Stable: forall t, Stable (encComp t).\n\n    Parameter canEnc: term -> term -> log -> Prop.\n    Parameter canEnc_Stable: forall k p, Stable (canEnc k p).\nEnd ProtocolInvariants.\n\nModule RPCInvariants <: ProtocolInvariants RPCDefs.\n    Import RPCDefs.\n    Include Defs RPCDefs.\n    \n    (* A-RPC: Log Invariant *)\n    Definition LogInvariant L :=\n        forall t u, Logged (New t u) L -> (exists bs, t = Literal bs).\n\n    (* A-RPC: Key usage test *)\n    Definition KeyAB a b k L :=\n        Logged (New k (HMacKey (U_KeyAB a b))) L.\n\n    (* A-RPC: Release Condition *)\n    Definition KeyABComp a b L :=\n        LoggedP (Bad a) L \\/ LoggedP (Bad b) L.\n\n    Definition hmacComp k L :=\n        exists a, exists b, KeyAB a b k L /\\ KeyABComp a b L.\n\n    Theorem hmacComp_Stable:\n        forall t, Stable (hmacComp t).\n    Proof.\n        intro t. unfold Stable. intros L L'. \n        unfold leq_log. unfold hmacComp. unfold KeyAB. unfold KeyABComp. unfold LoggedP.\n        firstorder.\n    Qed.\n\n    (* A-RPC: Payload Condition *)\n    Definition KeyABPayload a b p L :=\n        (exists req,\n            p = Pair (Literal (String TagRequest EmptyString)) req /\\\n            LoggedP (Request a b req) L) \n        \\/\n        (exists req, exists resp,\n            p = Pair (Literal (String TagResponse EmptyString)) (Pair req resp) /\\\n            LoggedP (Response a b req resp) L).\n\n    Definition canHmac k p L :=\n        exists a, exists b, KeyAB a b k L /\\ KeyABPayload a b p L.\n\n    Theorem canHmac_Stable:\n        forall k p, Stable (canHmac k p).\n    Proof.\n        intros k p. unfold Stable. intros L L'.\n        unfold leq_log. unfold canHmac. unfold KeyAB. unfold KeyABPayload. unfold LoggedP.\n        intros Hleq_log HcanHmacL.\n        destruct HcanHmacL as (a, HcanHmacL_a). destruct HcanHmacL_a as (b, HcanHmacL_ab).\n        exists a. exists b. firstorder.\n    Qed.\n\n    (* For the authenticated RPC protocol, all other usage conditions are trivially False. *)\n    Definition nonceComp (_: term) (_: log) := False.\n    Definition sencComp (_: term) (_: log) := False.\n    Definition canSEnc (_ _: term) (_: log) := False.\n    Definition sigComp (_: term) (_: log) := False.\n    Definition canSign (_ _: term) (_: log) := False.\n    Definition encComp (_: term) (_: log) := False.\n    Definition canEnc (_ _: term) (_: log) := False.\n\n    Theorem nonceComp_Stable: \n        forall t, Stable (nonceComp t).\n    Proof. \n        firstorder.\n    Qed.\n\n    Theorem sencComp_Stable: \n        forall t, Stable (sencComp t).\n    Proof. \n        firstorder. \n    Qed.\n\n    Theorem canSEnc_Stable:\n        forall k p, Stable (canSEnc k p).\n    Proof.\n        firstorder.\n    Qed.\n\n    Theorem sigComp_Stable:\n        forall t, Stable (sigComp t).\n    Proof.\n        firstorder.\n    Qed. \n\n    Theorem canSign_Stable:\n        forall k p, Stable (canSign k p).\n    Proof.\n        firstorder.\n    Qed.\n\n    Theorem encComp_Stable:\n        forall t, Stable (encComp t).\n    Proof.\n        firstorder.\n    Qed. \n\n    Theorem canEnc_Stable:\n        forall k p, Stable (canEnc k p).\n    Proof.\n        firstorder.\n    Qed.\nEnd RPCInvariants.\n\nModule ERPCInvariants <: ProtocolInvariants ERPCDefs.\n    Import ERPCDefs.\n    Include Defs ERPCDefs.\n\n    (* E-RPC: Log Invariant *)\n    Definition LogInvariant L :=\n        forall t u, Logged (New t u) L -> (exists bs, t = Literal bs).\n\n    (* E-RPC: Release Condition for Nonce *)\n    Definition RequestNComp a b L :=\n        LoggedP (Bad a) L \\/ LoggedP (Bad b) L.\n    \n    Definition RequestN a b n L :=\n        Logged (New n (Nonce (U_RequestN a b))) L.\n\n    Definition ResponseNComp a b L :=\n        LoggedP (Bad a) L \\/ LoggedP (Bad b) L.\n\n    Definition ResponseN a b n L := \n        Logged (New n (Nonce (U_ResponseN a b))) L.\n\n    Definition RequestAB a b req L :=\n        Logged (New req (Nonce (U_RequestN a b))) L.\n\n    Definition nonceComp n L :=\n        exists a, exists b, (RequestN a b n L /\\ RequestNComp a b L) \n            \\/ (ResponseN a b n L /\\ ResponseNComp a b L).\n\n    Theorem nonceComp_Stable:\n        forall t, Stable (nonceComp t).\n    Proof.\n        intro t. unfold Stable. intros L L'.\n        unfold leq_log. unfold nonceComp. unfold RequestN. unfold RequestNComp.\n        unfold ResponseN. unfold ResponseNComp. unfold LoggedP.\n        firstorder.\n    Qed.\n\n    Definition SessionKeyAB a b k req L :=\n        Logged (New k (SEncKey (U_SKeyAB a b req))) L.\n\n    Definition SessionKeyComp a b (req: term) L :=\n        LoggedP (Bad a) L \\/ LoggedP (Bad b) L.\n\n    Definition KeyAB a b k L :=\n        Logged (New k (SEncKey (U_KeyAB a b))) L.\n\n    Definition KeyABComp a b L :=\n        LoggedP (Bad a) L \\/ LoggedP (Bad b) L.\n\n    Definition sencComp k L :=\n        (exists a, exists b, exists req, SessionKeyAB a b k req L /\\ SessionKeyComp a b req L)\n            \\/ (exists a, exists b, KeyAB a b k L /\\ KeyABComp a b L).\n\n    Theorem sencComp_Stable:\n        forall t, Stable (sencComp t).\n    Proof.\n        intro t. unfold Stable. intros L L'.\n        unfold leq_log. unfold sencComp. \n        unfold SessionKeyAB. unfold SessionKeyComp. \n        unfold KeyAB. unfold KeyABComp. unfold LoggedP.\n        intros Hleq_log HsencCompL.\n        destruct HsencCompL as [HsencCompL_sess | HsencCompL_key].\n        - left. destruct HsencCompL_sess as (a, HsencCompL_sess_a). destruct HsencCompL_sess_a as (b, HsencCompL_sess_ab).\n            destruct HsencCompL_sess_ab as (req, HsencCompL_sess_abreq). exists a. exists b. exists req. firstorder.\n        - right. destruct HsencCompL_key as (a, HsencCompL_key_a). destruct HsencCompL_key_a as (b, HsencCompL_key_ab).\n            exists a. exists b. firstorder.\n    Qed.\n        \n    Definition SessionKeyPayload a b req m L :=\n        LoggedP (Response a b req m) L.\n    \n    Definition KeyABPayload a b p L :=\n        exists req, exists k,\n            p = Pair req k /\\\n            SessionKeyAB a b k req L /\\\n            LoggedP (Request a b req) L.\n\n    Definition canSEnc k m L :=\n        (exists a, exists b, exists req, SessionKeyAB a b k req L /\\ SessionKeyPayload a b req m L)\n        \\/ (exists a, exists b, KeyAB a b k L /\\ KeyABPayload a b m L).\n\n    Theorem canSEnc_Stable:\n        forall k m, Stable (canSEnc k m).\n    Proof.\n        intros k m. unfold Stable. intros L L'.\n        unfold leq_log. unfold canSEnc. \n        unfold SessionKeyAB. unfold SessionKeyPayload. \n        unfold KeyAB. unfold KeyABPayload. unfold LoggedP.\n        intros Hleq_log HcanSEncL.\n        destruct HcanSEncL as [HcanSEncL_sess | HcanSEncL_key].\n        - left. destruct HcanSEncL_sess as (a, HcanSEncL_sess_a). destruct HcanSEncL_sess_a as (b, HcanSEncL_sess_ab).\n            destruct HcanSEncL_sess_ab as (req, HcanSEncL_sess_abreq). exists a. exists b. exists req. firstorder.\n        - right. destruct HcanSEncL_key as (a, HcanSEncL_key_a). destruct HcanSEncL_key_a as (b, HcanSEncL_key_ab).\n            exists a. exists b. firstorder.\n    Qed.\n    \n    Definition sigComp (_: term) (_: log) := False.\n    Definition canSign (_ _: term) (_: log) := False.\n    Definition hmacComp (_: term) (_: log) := False.\n    Definition canHmac (_ _: term) (_: log) := False.\n    Definition encComp (_: term) (_: log) := False.\n    Definition canEnc (_ _: term) (_: log) := False.\n\n    Theorem sigComp_Stable:\n        forall t, Stable (sigComp t).\n    Proof.\n        firstorder.\n    Qed. \n\n    Theorem canSign_Stable:\n        forall k p, Stable (canSign k p).\n    Proof.\n        firstorder.\n    Qed.\n\n    Theorem hmacComp_Stable:\n        forall t, Stable (hmacComp t).\n    Proof.\n        firstorder.\n    Qed. \n\n    Theorem canHmac_Stable:\n        forall k p, Stable (canHmac k p).\n    Proof.\n        firstorder.\n    Qed.\n\n    Theorem encComp_Stable:\n        forall t, Stable (encComp t).\n    Proof.\n        firstorder.\n    Qed. \n\n    Theorem canEnc_Stable:\n        forall k p, Stable (canEnc k p).\n    Proof.\n        firstorder.\n    Qed.\nEnd ERPCInvariants.\n\nModule OtwayReesInvariants <: ProtocolInvariants OtwayReesDefs.\n    Import OtwayReesDefs.\n    Include Defs OtwayReesDefs.\n\n    Definition LogInvariant L :=\n        forall t u, Logged (New t u) L -> (exists bs, t = Literal bs).\n\n    Definition KeyAB a b k L := \n        Logged (New k (HMacKey (U_KeyAB a b))) L.\n\n    Definition KeyABComp a b L :=\n        LoggedP (Bad a) L \\/ LoggedP (Bad b) L.\n\n    Definition hmacComp k L := \n        exists a, exists b, KeyAB a b k L /\\ KeyABComp a b L.\n    \n    Theorem hmacComp_Stable: \n        forall t, Stable (hmacComp t).\n    Proof.\n        intro t. unfold Stable. intros L L'.\n        unfold leq_log. unfold hmacComp. unfold KeyAB. unfold KeyABComp. unfold LoggedP.\n        firstorder.\n    Qed.\n\n    Definition KeyABPayload a b p L := \n        (exists req,\n            p = Pair (Literal (String TagRequest EmptyString)) req /\\\n            LoggedP (Request a b req) L) \\/\n        (exists req, exists resp,\n            p = Pair (Literal (String TagResponse EmptyString)) (Pair req resp) /\\\n            LoggedP (Response a b req resp) L).\n    \n    Definition canHmac k p L := \n        exists a, exists b, KeyAB a b k L /\\ KeyABPayload a b p L.\n    \n    Theorem canHmac_Stable:\n        forall k p, Stable (canHmac k p).\n    Proof.\n        intros k p. unfold Stable. intros L L'.\n        unfold leq_log. unfold canHmac. unfold KeyAB. unfold KeyABPayload. unfold LoggedP.\n        intros Hleq_log HcanHmacL.\n        destruct HcanHmacL as (a, HcanHmacL_a). destruct HcanHmacL_a as (b, HcanHmacL_ab).\n        exists a. exists b. firstorder.\n    Qed.\n\n    Definition PrinKeyAB p k L := \n        Logged (New k (SEncKey (U_SKeyAB p))) L.\n\n    Definition PrinKeyComp p (k: term) L :=\n        LoggedP (Bad p) L.\n\n    Definition sencComp k L :=\n        exists p, PrinKeyAB p k L /\\ PrinKeyComp p k L.\n\n    Theorem sencComp_Stable: \n        forall t, Stable (sencComp t).\n    Proof.\n        intro t. unfold Stable. intros L L'.\n        unfold leq_log. unfold sencComp. unfold PrinKeyAB. unfold PrinKeyComp. unfold LoggedP.\n        firstorder.\n    Qed.\n\n    Definition PrinKeyPayload p m L:= \n        (exists b, exists np, exists kpb,\n            p <> b /\\\n            m = Pair p (Pair b (Pair kpb np)) /\\\n            KeyAB p b kpb L /\\\n            LoggedP (Initiator p np kpb b) L) \\/\n        (exists a, exists np, exists kap,\n            p <> a /\\\n            m = Pair a (Pair p (Pair kap np)) /\\\n            KeyAB a p kap L /\\\n            LoggedP (Responder p np kap a) L).\n\n    Definition canSEnc k m L := \n        exists p, PrinKeyAB p k L /\\ PrinKeyPayload p m L.\n    \n    Theorem canSEnc_Stable:\n        forall k m, Stable (canSEnc k m).\n    Proof.\n        intros k m. unfold Stable. intros L L'.\n        unfold leq_log. unfold canSEnc. unfold PrinKeyAB. unfold PrinKeyPayload. unfold LoggedP.\n        intros Hleq_log HcanSEncL. destruct HcanSEncL as (p, HcanSEncL_p).\n        destruct HcanSEncL_p as (HcanSEncL_log & HcanSEncL_keys).\n        exists p. split.\n        - firstorder.\n        - destruct HcanSEncL_keys as [HcanSEncL_keys_init | HcanSEncL_keys_resp].\n            * left. destruct HcanSEncL_keys_init as (b, HcanSEncL_keys_init_b). \n                destruct HcanSEncL_keys_init_b as (np, HcanSEncL_keys_init_bnp).\n                destruct HcanSEncL_keys_init_bnp as (kpb, HcanSEncL_keys_init_bnpkpb).\n                exists b. exists np. exists kpb. firstorder.\n            * right. destruct HcanSEncL_keys_resp as (a, HcanSEncL_keys_resp_a).\n                destruct HcanSEncL_keys_resp_a as (np, HcanSEncL_keys_resp_anp).\n                destruct HcanSEncL_keys_resp_anp as (kap, HcanSEncL_keys_resp_anpkap).\n                exists a. exists np. exists kap. firstorder. \n    Qed.\n    \n    Definition nonceComp (_: term) (_: log) := False.\n    Definition sigComp (_: term) (_: log) := False.\n    Definition canSign (_ _: term) (_: log) := False.\n    Definition encComp (_: term) (_: log) := False.\n    Definition canEnc (_ _: term) (_: log) := False.\n\n    Theorem nonceComp_Stable: \n        forall t, Stable (nonceComp t).\n    Proof. \n        firstorder.\n    Qed.\n\n    Theorem sigComp_Stable:\n        forall t, Stable (sigComp t).\n    Proof.\n        firstorder.\n    Qed. \n\n    Theorem canSign_Stable:\n        forall k p, Stable (canSign k p).\n    Proof.\n        firstorder.\n    Qed.\n\n    Theorem encComp_Stable:\n        forall t, Stable (encComp t).\n    Proof.\n        firstorder.\n    Qed. \n\n    Theorem canEnc_Stable:\n        forall k p, Stable (canEnc k p).\n    Proof.\n        firstorder.\n    Qed.\nEnd OtwayReesInvariants.\n\nModule CryptographicInvariants (PD: ProtocolDefs) (PI: ProtocolInvariants PD).\n    Include PI.\n\n    Definition GoodLog (L: log): Prop :=\n        WF_Log L /\\ LogInvariant L.\n\n    (*\n        Level predicates indicate how cryptography can be used by honest or dishonest protocol participants.\n        We say that a term t is Low in log L (denotate Level Low t L) whenever it may be made known to the adversary \n            without compromising the protocol's security objectives.\n        We say that a term t is High in log L whenever it can be derivated by any honest or dishonest protocol participant \n            (including the adversary).\n        Intuitively, a term is truly secret if it is not Low in the current Log\n    *)\n    Inductive level := Low | High.\n    Inductive Level: level -> term -> log -> Prop :=\n        (* AdversaryGuesses are always Low *)\n        | Level_AdversaryGuess: forall l bs L,\n            Logged (New (Literal bs) AdversaryGuess) L ->\n            Level l (Literal bs) L\n\n        (* Nonces are Low when nonceComp holds *)\n        | Level_Nonce: forall l bs L nu,\n            Logged (New (Literal bs) (Nonce nu)) L ->\n            (l = Low -> nonceComp (Literal bs) L) ->\n            Level l (Literal bs) L \n        (* HMacKeys are Low when hmacComp holds *)\n        | Level_HMacKey: forall l bs L hu,\n            Logged (New (Literal bs) (HMacKey hu)) L ->\n            (l = Low -> hmacComp (Literal bs) L) ->\n            Level l (Literal bs) L \n        (* SEncKeys are Low when sencComp holds *)\n        | Level_SEncKey: forall l bs L su,\n            Logged (New (Literal bs) (SEncKey su)) L ->\n            (l = Low -> sencComp (Literal bs) L) ->\n            Level l (Literal bs) L \n        (* SigKeys are Low when sigComp holds *)\n        | Level_SigKey: forall l bs L su,\n            Logged (New (Literal bs) (SignKey su)) L ->\n            (l = Low -> sigComp (Literal bs) L) ->\n            Level l (Literal bs) L \n        (* VerfKeys are always Low *)\n        | Level_VerKey: forall l bs L su,\n            Logged (New (Literal bs) (VerfKey su)) L ->\n            Level l (Literal bs) L \n        (* EncKeys are always Low *)\n        | Level_EncKey: forall l bs L eu,\n            Logged (New (Literal bs) (EncKey eu)) L ->\n            Level l (Literal bs) L \n        (* DecKeys are Low when encComp holds *)\n        | Level_DecKey: forall l bs L eu,\n            Logged (New (Literal bs) (DecKey eu)) L ->\n            (l = Low -> encComp (Literal bs) L) ->\n            Level l (Literal bs) L \n\n        (* Paris are as Low as their components *)\n        | Level_Pair: forall l t1 t2 L,\n            Level l t1 L ->\n            Level l t2 L ->\n            Level l (Pair t1 t2) L\n\n        (* Honest Hmacs are as Low as their payload *)\n        | Level_HMac: forall l k m L,\n            canHmac k m L ->\n            Level l m L ->\n            Level l (HMac k m) L\n        (* Dishonest Hmacs are Low *)\n        | Level_HMac_Low: forall l k m L,\n            Level Low k L ->\n            Level Low m L ->\n            Level l (HMac k m) L \n\n        (* Honest SEncs are Low *)\n        | Level_SEnc: forall l l' k p L,\n            canSEnc k p L ->\n            Level l' k L ->\n            Level l (SEnc k p) L \n        (* Dishonest SEncs are Low *)\n        | Level_SEnc_Low: forall l k p L,\n            Level Low k L ->\n            Level Low p L ->\n            Level l (SEnc k p) L\n            \n        (* Honests Sigs are as Low as their payload *)\n        | Level_Sig : forall l k m L,\n            canSign k m L ->\n            Level l m L ->\n            Level l (Sign k m) L \n        (* Dishonest Sigs are Low *)\n        | Level_Sig_Low : forall l k m L,\n            Level Low k L ->\n            Level Low m L ->\n            Level l (Sign k m) L\n\n        (* Honest Encryptions are Low *)\n        | Level_Enc : forall l k p L,\n            canEnc k p L ->\n            Level High p L ->\n            Level l (Enc k p) L \n        (* Dishonest Encryptions are Low *)\n        | Level_Enc_Low : forall l k p L,\n            Level Low k L ->\n            Level Low p L ->\n            Level l (Enc k p) L.\n    \n    (* Generic Invariants: Low is included in High. *)\n    Theorem Low_High: forall t L,\n        Level Low t L -> Level High t L.\n    Proof.\n        intros t L. intro Hlow.\n        induction Hlow.\n        - apply Level_AdversaryGuess. assumption.\n        - apply Level_Nonce with (nu:=nu) ; try assumption. easy. \n        - apply Level_HMacKey with (hu:=hu) ; try assumption. easy.\n        - apply Level_SEncKey with (su:=su) ; try assumption. easy.\n        - apply Level_SigKey with (su:=su) ; try assumption. easy.\n        - apply Level_VerKey with (su:=su). assumption.\n        - apply Level_EncKey with (eu:=eu). assumption.\n        - apply Level_DecKey with (eu:=eu) ; try assumption. easy.\n        - apply Level_Pair ; assumption.\n        - apply Level_HMac ; assumption.\n        - apply Level_HMac_Low ; assumption.\n        - apply Level_SEnc with (l':=l') ; assumption.\n        - apply Level_SEnc_Low ; assumption. \n        - apply Level_Sig ; assumption.\n        - apply Level_Sig_Low ; assumption.\n        - apply Level_Enc ; assumption.\n        - apply Level_Enc_Low ; assumption.  \n    Qed.\n\n    (* Generic Invariants: Level is stable. *)\n    Theorem Level_Stable: forall l t L L',\n        leq_log L L' -> Level l t L ->\n        Level l t L'.\n    Proof.\n        intros l t L L'. intros Hleq_log HlevelL.\n        induction HlevelL.\n        - apply Level_AdversaryGuess. unfold leq_log in Hleq_log.\n            specialize Hleq_log with (e:=(New (Literal bs) AdversaryGuess)). auto.\n        - apply Level_Nonce with (nu:=nu). \n            * unfold leq_log in Hleq_log.\n                specialize Hleq_log with (e:=(New (Literal bs) (Nonce nu))). auto.\n            * intro Hllow. apply H0 in Hllow. \n                assert ( Hstable : Stable (nonceComp (Literal bs)) ). apply nonceComp_Stable. firstorder.\n        - apply Level_HMacKey with (hu:=hu).\n            * unfold leq_log in Hleq_log.\n                specialize Hleq_log with (e:=(New (Literal bs) (HMacKey hu))). auto.\n            * intro Hllow. apply H0 in Hllow.\n                assert ( Hstable : Stable (hmacComp (Literal bs)) ). apply hmacComp_Stable. firstorder.\n        - apply Level_SEncKey with (su:=su). \n            * unfold leq_log in Hleq_log.\n                specialize Hleq_log with (e:=(New (Literal bs) (SEncKey su))). auto.\n            * intro Hllow. apply H0 in Hllow.\n                assert ( Hstable : Stable (sencComp (Literal bs)) ). apply sencComp_Stable. firstorder.\n        - apply Level_SigKey with (su:=su).\n            * unfold leq_log in Hleq_log.\n                specialize Hleq_log with (e:=(New (Literal bs) (SignKey su))). auto.\n            * intro Hllow. apply H0 in Hllow.\n                assert ( Hstable : Stable (sigComp (Literal bs)) ). apply sigComp_Stable. firstorder.\n        - apply Level_VerKey with (su:=su). unfold leq_log in Hleq_log.\n            specialize Hleq_log with (e:=(New (Literal bs) (VerfKey su))). auto.\n        - apply Level_EncKey with (eu:=eu). unfold leq_log in Hleq_log.\n            specialize Hleq_log with (e:=(New (Literal bs) (EncKey eu))). auto.\n        - apply Level_DecKey with (eu:=eu).\n            * unfold leq_log in Hleq_log.\n                specialize Hleq_log with (e:=(New (Literal bs) (DecKey eu))). auto.\n            * intro Hllow. apply H0 in Hllow.\n                assert ( Hstable : Stable (encComp (Literal bs)) ). apply encComp_Stable. firstorder.\n        - apply Level_Pair ; firstorder.\n        - apply Level_HMac ; try auto.\n            assert ( Hstable : Stable (canHmac k m) ). apply canHmac_Stable. firstorder.\n        - apply Level_HMac_Low ; firstorder.\n        - apply Level_SEnc with (l':=l') ; try auto.\n            assert ( Hstable : Stable (canSEnc k p) ). apply canSEnc_Stable. firstorder.\n        - apply Level_SEnc_Low ; firstorder.\n        - apply Level_Sig ; try auto.\n            * assert ( Hstable : Stable (canSign k m) ). apply canSign_Stable. firstorder. \n        - apply Level_Sig_Low ; firstorder.\n        - apply Level_Enc ; try auto.\n            assert ( Hstable : Stable (canEnc k p) ). apply canEnc_Stable. firstorder.\n        - apply Level_Enc_Low ; firstorder.\n    Qed.\n\n    (* Generic Invariants: Distinct usages are absurd *)\n    Theorem AbsurdDistinctUsages : forall P L t u u',\n        GoodLog L ->\n        u <> u' ->\n        Logged (New t u) L ->\n        Logged (New t u') L ->\n        P.\n    Proof.\n        intros P L t u u'. intros HGoodLog Hu_not_u' HlogU HlogU'.\n        unfold GoodLog in HGoodLog. destruct HGoodLog as (HGL_WfLog & _).\n        unfold WF_Log in HGL_WfLog. destruct HGL_WfLog as (HGL_WL_Usage & _).\n        specialize HGL_WL_Usage with (t:=t) (u:=u) (u':=u').\n        apply HGL_WL_Usage in HlogU ; try assumption.\n        exfalso. tauto.\n    Qed.\n\n    (* Generic Invariants: Level inversion. *)\n    Theorem LowNonce_Inversion : forall L n nu,\n        GoodLog L ->\n        Logged (New (Literal n) (Nonce nu)) L ->\n        forall l t, l = Low -> t = Literal n -> Level l t L ->\n        nonceComp (Literal n) L.\n    Proof.\n        intros L n nu. intros HGoodLog Hlog. intros l t. intros Hlow HLit Hlevel. symmetry in HLit.\n        unfold GoodLog in HGoodLog. destruct HGoodLog as (HGL_WfLog & _).\n        unfold WF_Log in HGL_WfLog. destruct HGL_WfLog as (HGL_WL_Usage & _).\n        induction Hlevel ; try discriminate. \n        - exfalso. specialize HGL_WL_Usage with (t:=Literal n) (u:=Nonce nu) (u':=AdversaryGuess).\n            apply HGL_WL_Usage in Hlog ; try assumption. \n            + discriminate. \n            + rewrite HLit. assumption. \n        - firstorder. rewrite HLit. assumption.\n        - exfalso. specialize HGL_WL_Usage with (t:=Literal n) (u:=Nonce nu) (u':=HMacKey hu).\n            apply HGL_WL_Usage in Hlog ; try assumption. \n            + discriminate.\n            + rewrite HLit. assumption.\n        - exfalso. specialize HGL_WL_Usage with (t:=Literal n) (u:=Nonce nu) (u':=SEncKey su).\n            apply HGL_WL_Usage in Hlog ; try assumption. \n            + discriminate.\n            + rewrite HLit. assumption.\n        - exfalso. specialize HGL_WL_Usage with (t:=Literal n) (u:=Nonce nu) (u':=SignKey su).\n            apply HGL_WL_Usage in Hlog ; try assumption. \n            + discriminate.\n            + rewrite HLit. assumption.\n        - exfalso. specialize HGL_WL_Usage with (t:=Literal n) (u:=Nonce nu) (u':=VerfKey su).\n            apply HGL_WL_Usage in Hlog ; try assumption. \n            + discriminate.\n            + rewrite HLit. assumption.\n        - exfalso. specialize HGL_WL_Usage with (t:=Literal n) (u:=Nonce nu) (u':=EncKey eu).\n            apply HGL_WL_Usage in Hlog ; try assumption. \n            + discriminate.\n            + rewrite HLit. assumption.\n        - exfalso. specialize HGL_WL_Usage with (t:=Literal n) (u:=Nonce nu) (u':=DecKey eu).\n            apply HGL_WL_Usage in Hlog ; try assumption. \n            + discriminate.\n            + rewrite HLit. assumption.  \n    Qed.\n\n    Theorem LowHmacKeyLiteral_Inversion : forall L k hu,\n        GoodLog L ->\n        Logged (New (Literal k) (HMacKey hu)) L ->\n        forall l t, l = Low -> t = Literal k -> Level l t L ->\n        hmacComp (Literal k) L.\n    Proof. \n        intros L k hu. intros HGoodLog Hlog. intros l t. intros Hlow HLit Hlevel. symmetry in HLit.\n        unfold GoodLog in HGoodLog. destruct HGoodLog as (HGL_WfLog & _).\n        unfold WF_Log in HGL_WfLog. destruct HGL_WfLog as (HGL_WL_Usage & _).\n        induction Hlevel ; try discriminate.\n        - exfalso. specialize HGL_WL_Usage with (t:=Literal bs) (u:=HMacKey hu) (u':=AdversaryGuess).\n            rewrite HLit in Hlog. apply HGL_WL_Usage in Hlog ; try assumption. discriminate.\n        - exfalso. specialize HGL_WL_Usage with (t:=Literal bs) (u:=HMacKey hu) (u':=Nonce nu).\n            rewrite HLit in Hlog. apply HGL_WL_Usage in Hlog ; try assumption. discriminate.\n        - apply H0 in Hlow. rewrite HLit. assumption.\n        - exfalso. specialize HGL_WL_Usage with (t:=Literal bs) (u:=HMacKey hu) (u':=SEncKey su).\n            rewrite HLit in Hlog. apply HGL_WL_Usage in Hlog ; try assumption. discriminate.\n        - exfalso. specialize HGL_WL_Usage with (t:=Literal bs) (u:=HMacKey hu) (u':=SignKey su).\n            rewrite HLit in Hlog. apply HGL_WL_Usage in Hlog ; try assumption. discriminate.\n        - exfalso. specialize HGL_WL_Usage with (t:=Literal bs) (u:=HMacKey hu) (u':=VerfKey su).\n            rewrite HLit in Hlog. apply HGL_WL_Usage in Hlog ; try assumption. discriminate.\n        - exfalso. specialize HGL_WL_Usage with (t:=Literal bs) (u:=HMacKey hu) (u':=EncKey eu).\n            rewrite HLit in Hlog. apply HGL_WL_Usage in Hlog ; try assumption. discriminate.\n        - exfalso. specialize HGL_WL_Usage with (t:=Literal bs) (u:=HMacKey hu) (u':=DecKey eu).\n            rewrite HLit in Hlog. apply HGL_WL_Usage in Hlog ; try assumption. discriminate.\n    Qed.\n\n    Theorem HMac_Inversion : forall L l k p,\n        forall t, t = HMac k p -> Level l t L ->\n        canHmac k p L \\/ Level Low k L.\n    Proof.\n        intros L l k p. intro t. intros Hhmac Hlevel.\n        induction Hlevel ; try discriminate.\n        - injection Hhmac. intros Hm Hk0. rewrite Hm in H. rewrite Hk0 in H. auto.\n        - injection Hhmac. intros _ Hk0. rewrite Hk0 in Hlevel1. auto.\n    Qed.\n\n    Theorem LowSencKeyLiteral_Inversion: forall L k su,\n        GoodLog L ->\n        Logged (New (Literal k) (SEncKey su)) L ->\n        forall l t, l = Low -> t = Literal k -> Level l t L ->\n        sencComp (Literal k) L.\n    Proof.\n        intros L k su. intros HGoodLog Hlog. intros l t. intros Hlow Hlit Hlevel.\n        unfold GoodLog in HGoodLog. destruct HGoodLog as (HGL_WfLog & _).\n        unfold WF_Log in HGL_WfLog. destruct HGL_WfLog as (HGL_WL_Usage & _).\n        induction Hlevel ; try discriminate.\n        - exfalso. specialize HGL_WL_Usage with (t:=Literal k) (u:=SEncKey su) (u':=AdversaryGuess).\n            rewrite Hlit in H. apply HGL_WL_Usage in Hlog ; try assumption. discriminate.\n        - exfalso. specialize HGL_WL_Usage with (t:=Literal k) (u:=SEncKey su) (u':=Nonce nu).\n            rewrite Hlit in H. apply HGL_WL_Usage in Hlog ; try assumption. discriminate.\n        - exfalso. specialize HGL_WL_Usage with (t:=Literal k) (u:=SEncKey su) (u':=HMacKey hu). \n            rewrite Hlit in H. apply HGL_WL_Usage in Hlog ; try assumption. discriminate.\n        - apply H0 in Hlow. rewrite Hlit in Hlow. assumption.\n        - exfalso. specialize HGL_WL_Usage with (t:=Literal k) (u:=SEncKey su) (u':=SignKey su0).\n            rewrite Hlit in H. apply HGL_WL_Usage in Hlog ; try assumption. discriminate.\n        - exfalso. specialize HGL_WL_Usage with (t:=Literal k) (u:=SEncKey su) (u':=VerfKey su0).\n            rewrite Hlit in H. apply HGL_WL_Usage in Hlog ; try assumption. discriminate.\n        - exfalso. specialize HGL_WL_Usage with (t:=Literal k) (u:=SEncKey su) (u':=EncKey eu).\n            rewrite Hlit in H. apply HGL_WL_Usage in Hlog ; try assumption. discriminate.\n        - exfalso. specialize HGL_WL_Usage with (t:=Literal k) (u:=SEncKey su) (u':=DecKey eu).\n            rewrite Hlit in H. apply HGL_WL_Usage in Hlog ; try assumption. discriminate.\n    Qed.\n\n    Theorem SEnc_Inversion : forall L l k p,\n        forall t, t = SEnc k p -> Level l t L ->\n        canSEnc k p L \\/ Level Low k L.\n    Proof.\n        intros L l k p. intro t. intros Hsenc Hlevel.\n        induction Hlevel ; try discriminate.\n        - injection Hsenc. intros Hp0 Hk0. rewrite Hp0 in H. rewrite Hk0 in H. auto.\n        - injection Hsenc. intros _ Hk0. rewrite Hk0 in Hlevel1. auto.\n    Qed.\n\n    Theorem Sign_Inversion : forall L l k p,\n        forall t, t = Sign k p -> Level l t L ->\n        canSign k p L \\/ Level Low k L.\n    Proof.\n        intros L l k p. intro t. intros Hsign Hlevel.\n        induction Hlevel ; try discriminate.\n        - injection Hsign. intros Hm Hk0. rewrite Hm in H. rewrite Hk0 in H. auto.\n        - injection Hsign. intros _ Hk0. rewrite Hk0 in Hlevel1. auto.\n    Qed.\n\n    Theorem Enc_Inversion : forall L l k p,\n        forall t, t = Enc k p -> Level l t L ->\n        (canEnc k p L /\\ Level High p L) \\/ Level Low k L.\n    Proof.\n        intros L l k p. intro t. intros Henc Hlevel.\n        induction Hlevel ; try discriminate.\n        - injection Henc. intros Hp0 Hk0. \n            rewrite Hp0 in H. rewrite Hk0 in H. rewrite Hp0 in Hlevel. auto.\n        - injection Henc. intros _ Hk0. rewrite Hk0 in Hlevel1. auto.\n    Qed.\nEnd CryptographicInvariants.\n\nModule RPCTheorems.\n    Import RPCDefs.\n    Include CryptographicInvariants RPCDefs RPCInvariants.\n    Import RPCInvariants.\n\n    (* A-RPC: Request Correspondence Theorem *)\n    Theorem RequestCorrespondence: forall a b k req L,\n        GoodLog L -> KeyAB a b k L ->\n        forall l t, l = Low -> t = (HMac k (Pair (Literal (String TagRequest EmptyString)) req)) -> \n        Level l t L ->\n        LoggedP (Request a b req) L \\/\n        LoggedP (Bad a) L \\/ LoggedP (Bad b) L.\n    Proof.\n        intros a b k req L. unfold KeyAB. \n        intros HGoodLog HKeyAB. intros l t. intros Hlow Hhmac Hlevel. \n        assert ( HGoodLog_bis : GoodLog L ). assumption.\n        unfold GoodLog in HGoodLog. destruct HGoodLog as (HGL_WfLog & HGL_LogInv).\n        unfold WF_Log in HGL_WfLog. destruct HGL_WfLog as (HGL_WL_Usage & _).\n        unfold LogInvariant in HGL_LogInv. induction Hlevel ; try discriminate.\n        - left. injection Hhmac. intros Hm Hk0. rewrite Hk0 in H. unfold canHmac in H.\n            destruct H as (a0, Ha). destruct Ha as (b0, Hab). destruct Hab as (Hab_key & Hab_keyPayload).\n            unfold KeyAB in Hab_key. specialize HGL_WL_Usage with (t:=k) (u:=HMacKey (U_KeyAB a b)) (u':=HMacKey (U_KeyAB a0 b0)).\n            apply HGL_WL_Usage in HKeyAB ; try assumption. injection HKeyAB. intros Hb Ha.\n            unfold KeyABPayload in Hab_keyPayload. destruct Hab_keyPayload as [Hab_KP_req | Hab_KP_reqresp].\n            + destruct Hab_KP_req as (req0, Hab_KP_req). destruct Hab_KP_req as (Hab_KP_req_m & Hab_KP_req_log).\n                symmetry in Hm. rewrite Hab_KP_req_m in Hm. injection Hm. intro Hreq.\n                rewrite Ha. rewrite Hb. rewrite Hreq. assumption.\n            +  exfalso. destruct Hab_KP_reqresp as (req0, Hab_KP_req). destruct Hab_KP_req as (resp0, Hab_KP_reqresp).\n                destruct Hab_KP_reqresp as (Hab_KP_reqresp_m & _). symmetry in Hm. rewrite Hab_KP_reqresp_m in Hm. \n                injection Hm. intros _ Htag.\n                assert ( HtagDistinct : TagRequest <> TagResponse ). apply TagsDistinct. \n                tauto.\n        - right. injection Hhmac. intros Hm Hk0.\n            specialize HGL_LogInv with (t:=k) (u:=HMacKey (U_KeyAB a b)). \n            assert ( Hlog : Logged (New k (HMacKey (U_KeyAB a b))) L ). assumption.\n            apply HGL_LogInv in HKeyAB. destruct HKeyAB as (bs, HLitk).\n            assert ( HhmacComp : hmacComp (Literal bs) L ).\n            + apply LowHmacKeyLiteral_Inversion with (hu:=U_KeyAB a b) (l:=Low) (t:=Literal bs) ; try easy.\n                * rewrite HLitk in Hlog. assumption.\n                * rewrite Hk0 in Hlevel1. rewrite HLitk in Hlevel1. assumption.\n            + unfold hmacComp in HhmacComp. destruct HhmacComp as (a0, HhmacComp_a). destruct HhmacComp_a as (b0, HhmacComp_ab).\n                destruct HhmacComp_ab as (HHC_ab_key & HHC_ab_keyComp). unfold KeyAB in HHC_ab_key.\n                rewrite HLitk in Hlog. specialize HGL_WL_Usage with (t:=Literal bs) (u:=HMacKey (U_KeyAB a b)) (u':=HMacKey (U_KeyAB a0 b0)).\n                apply HGL_WL_Usage in HHC_ab_key ; try assumption. injection HHC_ab_key.\n                intros Hb Ha. rewrite Hb. rewrite Ha. unfold KeyABComp in HHC_ab_keyComp. assumption.\n    Qed.\n\n    (* A-RPC: Response Correspondence Theorem *)\n    Theorem ResponseCorrespondence: forall a b k req resp L,\n        GoodLog L -> KeyAB a b k L ->\n        forall l t, l = Low -> t = (HMac k (Pair (Literal (String TagResponse EmptyString)) (Pair req resp))) ->\n        Level l t L ->\n        LoggedP (Response a b req resp) L \\/\n        LoggedP (Bad a) L \\/ LoggedP (Bad b) L.\n    Proof.\n        intros a b k req resp L. unfold KeyAB.\n        intros HGoodLog HKeyAB. intros l t. intros Hlow Hhmac Hlevel. \n        assert ( HGoodLog_bis : GoodLog L ). assumption.\n        unfold GoodLog in HGoodLog. destruct HGoodLog as (HGL_WfLog & HGL_LogInv).\n        unfold WF_Log in HGL_WfLog. destruct HGL_WfLog as (HGL_WL_Usage & _).\n        unfold LogInvariant in HGL_LogInv. induction Hlevel ; try discriminate.\n        - left. injection Hhmac. intros Hm Hk0. rewrite Hk0 in H. unfold canHmac in H.\n            destruct H as (a0, Ha). destruct Ha as (b0, Hab). destruct Hab as (Hab_key & Hab_keyPayload).\n            unfold KeyAB in Hab_key. specialize HGL_WL_Usage with (t:=k) (u:=HMacKey (U_KeyAB a b)) (u':=HMacKey (U_KeyAB a0 b0)).\n            apply HGL_WL_Usage in HKeyAB ; try assumption. injection HKeyAB. intros Hb Ha.\n            unfold KeyABPayload in Hab_keyPayload. destruct Hab_keyPayload as [Hab_KP_req | Hab_KP_reqresp].\n            + exfalso. destruct Hab_KP_req as (req0, hab_KP_req). destruct hab_KP_req as (Hab_KP_req_m & _).\n                symmetry in Hm. rewrite Hab_KP_req_m in Hm. injection Hm. intros _ Htag.\n                assert ( HtagDistinct : TagRequest <> TagResponse ). apply TagsDistinct. firstorder.\n            + destruct Hab_KP_reqresp as (req0, hab_KP_req). destruct hab_KP_req as (resp0, Hab_KP_reqresp).\n                destruct Hab_KP_reqresp as (Hab_KP_reqresp_m & Hab_KP_reqresp_log). symmetry in Hm. rewrite Hab_KP_reqresp_m in Hm. \n                injection Hm. intros Hresp Hreq. rewrite Ha. rewrite Hb. rewrite Hreq. rewrite Hresp. assumption.\n        - right. injection Hhmac. intros Hm Hk0.\n            specialize HGL_LogInv with (t:=k) (u:=HMacKey (U_KeyAB a b)).\n            assert ( Hlog : Logged (New k (HMacKey (U_KeyAB a b))) L ). assumption.\n            apply HGL_LogInv in HKeyAB. destruct HKeyAB as (bs, HLitk).\n            assert ( HhmacComp : hmacComp (Literal bs) L).\n            + apply LowHmacKeyLiteral_Inversion with (hu:=U_KeyAB a b) (l:=Low) (t:=Literal bs) ; try easy.\n                * rewrite HLitk in Hlog. assumption.\n                * rewrite Hk0 in Hlevel1. rewrite HLitk in Hlevel1. assumption.\n            + unfold hmacComp in HhmacComp. destruct HhmacComp as (a0, HhmacComp_a). destruct HhmacComp_a as (b0, HhmacComp_ab).\n                destruct HhmacComp_ab as (HHC_ab_key & HHC_ab_keyComp). unfold KeyAB in HHC_ab_key.\n                rewrite HLitk in Hlog. specialize HGL_WL_Usage with (t:=Literal bs) (u:=HMacKey (U_KeyAB a b)) (u':=HMacKey (U_KeyAB a0 b0)).\n                apply HGL_WL_Usage in HHC_ab_key ; try assumption. injection HHC_ab_key.\n                intros Hb Ha. rewrite Hb. rewrite Ha. unfold KeyABComp in HHC_ab_keyComp. assumption. \n    Qed.\n\n    (* A-RPC: Key Secrecy Theorem *)\n    Theorem KeySecrecy: forall a b k L,\n        GoodLog L -> KeyAB a b k L -> \n        forall l, l = Low -> Level l k L ->\n        LoggedP (Bad a) L \\/ LoggedP (Bad b) L.\n    Proof.\n        intros a b k L. unfold KeyAB.\n        intros HGoodLog HKeyAB. intro l. intros Hlow Hlevel. \n        unfold GoodLog in HGoodLog. destruct HGoodLog as (HGL_WfLog & HGL_LogInv).\n        unfold WF_Log in HGL_WfLog. destruct HGL_WfLog as (HGL_WL_Usage & _).\n        unfold LogInvariant in HGL_LogInv. specialize HGL_LogInv with (t:=k) (u:=HMacKey (U_KeyAB a b)).\n        assert ( HKeyAB_bis : Logged (New k (HMacKey (U_KeyAB a b))) L ). assumption.\n        apply HGL_LogInv in HKeyAB_bis. destruct HKeyAB_bis as (bs, HLitk).\n        induction k ; try discriminate. induction Hlevel ; try discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=AdversaryGuess) (u':=HMacKey (U_KeyAB a b)).\n            apply HGL_WL_Usage in HKeyAB ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=Nonce nu) (u':=HMacKey (U_KeyAB a b)).\n            apply HGL_WL_Usage in HKeyAB ; try assumption. discriminate.\n        - apply H0 in Hlow. unfold hmacComp in Hlow. destruct Hlow as (a', Hlow_a). destruct Hlow_a as (b', Hlow_ab).\n            destruct Hlow_ab as (Hab_key & Hab_keyComp). unfold KeyAB in Hab_key.\n            specialize HGL_WL_Usage with (t:=Literal bs0) (u:=HMacKey (U_KeyAB a b)) (u':=HMacKey (U_KeyAB a' b')).\n            apply HGL_WL_Usage in Hab_key ; try assumption. injection Hab_key.\n            intros Hb Ha. rewrite Ha. rewrite Hb. unfold KeyABComp in Hab_keyComp. assumption.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=SEncKey su) (u':=HMacKey (U_KeyAB a b)).\n            apply HGL_WL_Usage in HKeyAB ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=SignKey su) (u':=HMacKey (U_KeyAB a b)).\n            apply HGL_WL_Usage in HKeyAB ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=VerfKey su) (u':=HMacKey (U_KeyAB a b)).\n            apply HGL_WL_Usage in HKeyAB ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=EncKey eu) (u':=HMacKey (U_KeyAB a b)).\n            apply HGL_WL_Usage in HKeyAB ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=DecKey eu) (u':=HMacKey (U_KeyAB a b)).\n            apply HGL_WL_Usage in HKeyAB ; try assumption. discriminate.\n    Qed.\n\n    (* Keyed HMAC Inversion Theorem *)\n    Theorem KeyedHMac_Inversion: forall hu k p L,\n        GoodLog L -> Logged (New k (HMacKey hu)) L ->\n        forall l t, l = High -> t = HMac k p -> Level l t L ->\n        canHmac k p L \\/ hmacComp k L.\n    Proof.\n        intros hu k p L. intros HGoodLog Hlog. intros l t. intros Hhigh Hhmac Hlevel.\n        assert ( HGoodLog_bis : GoodLog L ). assumption.\n        unfold GoodLog in HGoodLog. destruct HGoodLog as (HGL_WfLog & HGL_LogInv).\n        unfold WF_Log in HGL_WfLog. destruct HGL_WfLog as (HGL_WL_Usage & _).\n        unfold LogInvariant in HGL_LogInv. induction Hlevel ; try discriminate.\n        - left. injection Hhmac. intros Hm Hk0. rewrite Hm in H. rewrite Hk0 in H. assumption.\n        - right. injection Hhmac. intros _ Hk0. rewrite Hk0 in Hlevel1.\n            specialize HGL_LogInv with (t:=k) (u:=HMacKey hu).\n            assert ( Hlog_bis : Logged (New k (HMacKey hu)) L ). assumption.\n            apply HGL_LogInv in Hlog_bis. destruct Hlog_bis as (bs, HLitk).\n            rewrite HLitk. apply LowHmacKeyLiteral_Inversion with (hu:=hu) (l:=Low) (t:=Literal bs) ; try easy.\n            + rewrite HLitk in Hlog. assumption.\n            + rewrite HLitk in Hlevel1. assumption.\n    Qed.\nEnd RPCTheorems.\n\nModule ERPCTheorems.\n    Import ERPCDefs.\n    Include CryptographicInvariants ERPCDefs ERPCInvariants.\n    Import ERPCInvariants.\n\n    (*Theorem KeyedHMac_Inversion: forall a b p k L,\n        GoodLog L -> KeyAB a b k L ->\n        forall l t, l = High -> t = SEnc k p -> Level l t L ->\n        canEnc k p L \\/ encComp k L.\n    Proof.\n        intros a b p k L. intros HGoodLog HKeyAB. intros l t. intros Hhigh Hsenc Hlevel.\n        assert ( HGoodLog_bis : GoodLog L ). assumption.\n        unfold GoodLog in HGoodLog. destruct HGoodLog as (HGL_WfLog & HGL_LogInv).\n        unfold WF_Log in HGL_WfLog. destruct HGL_WfLog as (HGL_WL_Usage & _).\n        unfold LogInvariant in HGL_LogInv. induction Hlevel ; try discriminate.\n        - left. injection Hsenc. intros Hm Hk0. rewrite Hk0 in H. rewrite Hm in H. assumption.\n        - right. injection Hsenc. intros Hm Hk0. rewrite Hk0 in Hlevel1.\n            unfold KeyAB in HKeyAB. assert ( Hlog : Logged (New k (SEncKey (U_KeyAB a b))) L ). assumption.\n            specialize HGL_LogInv with (t:=k) (u:=SEncKey (U_KeyAB a b)).\n            apply HGL_LogInv in HKeyAB. destruct HKeyAB as (bs, HLitk). rewrite HLitk. \n            eapply LowSencKeyLiteral_Inversion. with (su:=U_KeyAB a b) (l:=Low) (t:=Literal bs) ; try easy.\n            + rewrite HLitk in Hlog. assumption.\n            + rewrite HLitk in Hlevel1. assumption.\n    Qed.*)\n\n    Theorem RequestCorrespondence: forall a b kab req k L,\n        GoodLog L -> KeyAB a b kab L ->\n        forall l t, l = Low -> t = SEnc kab (Pair req k) -> Level l t L ->\n        (LoggedP (Request a b req) L /\\ SessionKeyAB a b k req L) \\/\n        (LoggedP (Bad a) L \\/ LoggedP (Bad b) L).\n    Proof.\n        intros a b kab req k L. unfold KeyAB. intros HGoodLog HKeyAB. intros l t. intros Hlow Hsenc Hlevel.\n        assert ( HGoodLog_bis : GoodLog L ). assumption.\n        unfold GoodLog in HGoodLog. destruct HGoodLog as (HGL_WfLog & HGL_LogInv).\n        unfold WF_Log in HGL_WfLog. destruct HGL_WfLog as (HGL_WL_Usage & _).\n        unfold LogInvariant in HGL_LogInv. induction Hlevel ; try discriminate.\n        - left. injection Hsenc. intros Hp Hk0. rewrite Hk0 in H.\n            unfold canSEnc in H. unfold KeyAB in HKeyAB.\n            destruct H as [Hsess | Hkey].\n            + destruct Hsess as (a0, Hsess_a). destruct Hsess_a as (b0, Hsess_ab). \n                destruct Hsess_ab as (req0, Hsess_abreq). destruct Hsess_abreq as (Hsess_sessKey & _). \n                unfold SessionKeyAB in Hsess_sessKey.\n                specialize HGL_WL_Usage with (t:=kab) (u:=SEncKey (U_KeyAB a b)) (u':=SEncKey (U_SKeyAB a0 b0 req0)).\n                apply HGL_WL_Usage in HKeyAB ; try assumption. discriminate.\n            + destruct Hkey as (a0, Hkey_a). destruct Hkey_a as (b0, Hkey_ab).\n                destruct Hkey_ab as (Hkey_key & Hkey_keyPayload). unfold KeyAB in Hkey_key.\n                specialize HGL_WL_Usage with (t:=kab) (u:=SEncKey (U_KeyAB a b)) (u':=SEncKey (U_KeyAB a0 b0)).\n                apply HGL_WL_Usage in HKeyAB ; try assumption. injection HKeyAB. intros Hb Ha.\n                unfold KeyABPayload in Hkey_keyPayload. \n                destruct Hkey_keyPayload as (req0, Hkey_keyPayload_req). \n                destruct Hkey_keyPayload_req as (k', Hkey_keyPayload_reqk).\n                destruct Hkey_keyPayload_reqk as (Hp_bis & Hkey_keyPayload).\n                symmetry in Hp. rewrite Hp_bis in Hp. injection Hp. intros Hk Hreq.\n                rewrite <- Hb in Hkey_keyPayload. rewrite <- Ha in Hkey_keyPayload.\n                rewrite <- Hk in Hkey_keyPayload. rewrite <- Hreq in Hkey_keyPayload. easy.\n        - right. injection Hsenc. intros Hp Hk0. \n            specialize HGL_LogInv with (t:=kab) (u:=SEncKey (U_KeyAB a b)).\n            assert ( Hlog : Logged (New kab (SEncKey (U_KeyAB a b))) L ). assumption.\n            apply HGL_LogInv in HKeyAB. destruct HKeyAB as (bs, HLitKab).\n            assert ( HsencComp : sencComp (Literal bs) L ).\n            + apply LowSencKeyLiteral_Inversion with (su:=U_KeyAB a b) (l:=Low) (t:=Literal bs) ; try easy.\n                * rewrite HLitKab in Hlog. assumption.\n                * rewrite Hk0 in Hlevel1. rewrite HLitKab in Hlevel1. assumption.\n            + unfold sencComp in HsencComp. destruct HsencComp as [HsencComp_sess | HsencComp_key].\n                * destruct HsencComp_sess as (a0, HsencComp_sess_a). destruct HsencComp_sess_a as (b0, HsencComp_sess_ab).\n                    destruct HsencComp_sess_ab as (req0, HsencComp_sess_abreq).\n                    destruct HsencComp_sess_abreq as (HSC_sess_key & _). unfold SessionKeyAB in HSC_sess_key.\n                    specialize HGL_WL_Usage with (t:=kab) (u:=SEncKey (U_KeyAB a b)) (u':=SEncKey (U_SKeyAB a0 b0 req0)).\n                    rewrite <- HLitKab in HSC_sess_key. apply HGL_WL_Usage in Hlog ; try assumption. discriminate.\n                * destruct HsencComp_key as (a0, HsencComp_key_a). destruct HsencComp_key_a as (b0, HsencComp_key_ab).\n                    destruct HsencComp_key_ab as (HSC_key_key & HSC_key_keyComp). unfold KeyAB in HSC_key_key.\n                    specialize HGL_WL_Usage with (t:=Literal bs) (u:=SEncKey (U_KeyAB a b)) (u':=SEncKey (U_KeyAB a0 b0)).\n                    rewrite HLitKab in Hlog. apply HGL_WL_Usage in Hlog ; try assumption. injection Hlog. intros Hb Ha.\n                    unfold KeyABComp in HSC_key_keyComp. rewrite Hb. rewrite Ha. assumption.\n    Qed.\n\n    Theorem ResponseCorrespondence: forall a b k req resp L,\n        GoodLog L -> SessionKeyAB a b k req L ->\n        forall l t, l = Low -> t = SEnc k resp -> Level l t L ->\n        LoggedP (Response a b req resp) L \\/ (LoggedP (Bad a) L \\/ LoggedP (Bad b) L).\n    Proof.\n        intros a b k req resp L. intros HGoodLog HSessionKey. intros l t. intros Hlow Hsenc Hlevel.\n        assert ( HGoodLog_bis : GoodLog L ). assumption. unfold SessionKeyAB in HSessionKey.\n        unfold GoodLog in HGoodLog. destruct HGoodLog as (HGL_WfLog & HGL_LogInv).\n        unfold WF_Log in HGL_WfLog. destruct HGL_WfLog as (HGL_WL_Usage & _).\n        unfold LogInvariant in HGL_LogInv. induction Hlevel ; try discriminate.\n        - left. injection Hsenc. intros Hp Hk0. rewrite Hk0 in H.\n            unfold canSEnc in H. destruct H as [Hsess | Hkey].\n            + destruct Hsess as (a0, Hsess_a). destruct Hsess_a as (b0, Hsess_ab). \n                destruct Hsess_ab as (req0, Hsess_abreq).\n                destruct Hsess_abreq as (Hsess_sessKey & Hsess_sessKeyPayload). unfold SessionKeyAB in Hsess_sessKey.\n                specialize HGL_WL_Usage with (t:=k) (u:=SEncKey (U_SKeyAB a b req)) (u':=SEncKey (U_SKeyAB a0 b0 req0)).\n                assert ( Hlog : Logged (New k (SEncKey (U_SKeyAB a b req))) L ). assumption.\n                apply HGL_WL_Usage in HSessionKey ; try assumption. injection HSessionKey. intros Hreq Hb Ha.\n                unfold SessionKeyPayload in Hsess_sessKeyPayload. rewrite Ha. rewrite Hb. rewrite Hreq.\n                rewrite Hp in Hsess_sessKeyPayload. assumption.\n            + destruct Hkey as (a0, Hkey_a). destruct Hkey_a as (b0, Hkey_ab).\n                destruct Hkey_ab as (Hkey_key & _). unfold KeyAB in Hkey_key.\n                specialize HGL_WL_Usage with (t:=k) (u:=SEncKey (U_SKeyAB a b req)) (u':=SEncKey (U_KeyAB a0 b0)).\n                apply HGL_WL_Usage in HSessionKey ; try assumption. discriminate.\n        - right. injection Hsenc. intros Hp Hk0. \n            specialize HGL_LogInv with (t:=k) (u:=SEncKey (U_SKeyAB a b req)).\n            assert ( Hlog : Logged (New k (SEncKey (U_SKeyAB a b req))) L ). assumption.\n            apply HGL_LogInv in HSessionKey. destruct HSessionKey as (bs, HLitk).\n            assert ( HsencComp : sencComp (Literal bs) L ).\n            + apply LowSencKeyLiteral_Inversion with (su:=U_SKeyAB a b req) (l:=Low) (t:=Literal bs) ; try easy.\n                * rewrite HLitk in Hlog. assumption.\n                * rewrite Hk0 in Hlevel1. rewrite HLitk in Hlevel1. assumption.\n            + unfold sencComp in HsencComp. destruct HsencComp as [HsencComp_sess | HsencComp_key].\n                * destruct HsencComp_sess as (a0, HsencComp_sess_a). destruct HsencComp_sess_a as (b0, HsencComp_sess_ab).\n                    destruct HsencComp_sess_ab as (req0, HsencComp_sess_abreq). \n                    destruct HsencComp_sess_abreq as (HSC_sess_sessKey & HSC_sess_sessKeyComp).\n                    unfold SessionKeyAB in HSC_sess_sessKey. rewrite HLitk in Hlog.\n                    specialize HGL_WL_Usage with (t:=Literal bs) (u:=SEncKey (U_SKeyAB a b req)) (u':=SEncKey (U_SKeyAB a0 b0 req0)).\n                    apply HGL_WL_Usage in HSC_sess_sessKey ; try assumption. injection HSC_sess_sessKey.\n                    intros Hreq Hb Ha. unfold SessionKeyComp in HSC_sess_sessKeyComp. rewrite Ha. rewrite Hb. assumption.\n                * destruct HsencComp_key as (a0, HsencComp_key_a). destruct HsencComp_key_a as (b0, HsencComp_key_ab).\n                    destruct HsencComp_key_ab as (HSC_key_key & _). unfold KeyAB in HSC_key_key.\n                    specialize HGL_WL_Usage with (t:=Literal bs) (u:=SEncKey (U_SKeyAB a b req)) (u':=SEncKey (U_KeyAB a0 b0)).\n                    rewrite HLitk in Hlog. apply HGL_WL_Usage in Hlog ; try assumption. discriminate.\n    Qed.\n\n    Theorem KeyABSecrecy: forall a b k L,\n        GoodLog L -> KeyAB a b k L -> \n        forall l, l = Low -> Level l k L ->\n        LoggedP (Bad a) L \\/ LoggedP (Bad b) L.\n    Proof.\n        intros a b k L. unfold KeyAB.\n        intros HGoodLog HKeyAB. intro l. intros Hlow Hlevel.\n        unfold GoodLog in HGoodLog. destruct HGoodLog as (HGL_WfLog & HGL_LogInv).\n        unfold WF_Log in HGL_WfLog. destruct HGL_WfLog as (HGL_WL_Usage & _).\n        unfold LogInvariant in HGL_LogInv. specialize HGL_LogInv with (t:=k) (u:=SEncKey (U_KeyAB a b)).\n        assert ( HKeyAB_bis : Logged (New k (SEncKey (U_KeyAB a b))) L ). assumption.\n        apply HGL_LogInv in HKeyAB_bis. destruct HKeyAB_bis as (bs, HLitk).\n        induction k ; try discriminate. induction Hlevel ; try discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=SEncKey (U_KeyAB a b)) (u':=AdversaryGuess).\n            apply HGL_WL_Usage in HKeyAB ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=SEncKey (U_KeyAB a b)) (u':=Nonce nu).\n            apply HGL_WL_Usage in HKeyAB ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=SEncKey (U_KeyAB a b)) (u':=HMacKey hu).\n            apply HGL_WL_Usage in HKeyAB ; try assumption. discriminate.\n        - apply H0 in Hlow. unfold sencComp in Hlow. destruct Hlow as [Hlow_sess | Hlow_key].\n            + destruct Hlow_sess as (a', Hlow_sess_a). destruct Hlow_sess_a as (b', Hlow_sess_ab).\n                destruct Hlow_sess_ab as (req', Hlow_sess_abreq).\n                destruct Hlow_sess_abreq as (Hlow_sess_key & _). unfold KeyAB in Hlow_sess_key. \n                specialize HGL_WL_Usage with (t:=Literal bs0) (u:=SEncKey (U_KeyAB a b)) (u':=SEncKey (U_SKeyAB a' b' req')).\n                apply HGL_WL_Usage in Hlow_sess_key ; try assumption. discriminate. \n            + destruct Hlow_key as (a', Hlow_key_a). destruct Hlow_key_a as (b', Hlow_key_ab).\n                destruct Hlow_key_ab as (Hlow_key_key & Hlow_key_keyComp). unfold KeyAB in Hlow_key_key.\n                specialize HGL_WL_Usage with (t:=Literal bs0) (u:=SEncKey (U_KeyAB a b)) (u':=SEncKey (U_KeyAB a' b')).\n                apply HGL_WL_Usage in HKeyAB ; try assumption. injection HKeyAB. intros Hb Ha.\n                rewrite Hb. rewrite Ha. unfold KeyABComp in Hlow_key_keyComp. assumption.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=SEncKey (U_KeyAB a b)) (u':=SignKey su).\n            apply HGL_WL_Usage in HKeyAB ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=SEncKey (U_KeyAB a b)) (u':=VerfKey su).\n            apply HGL_WL_Usage in HKeyAB ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=SEncKey (U_KeyAB a b)) (u':=EncKey eu).\n            apply HGL_WL_Usage in HKeyAB ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=SEncKey (U_KeyAB a b)) (u':=DecKey eu).\n            apply HGL_WL_Usage in HKeyAB ; try assumption. discriminate.\n    Qed.\n\n    Theorem SessionKeySecrecy: forall a b req k L,\n        GoodLog L -> SessionKeyAB a b k req L ->\n        forall l, l = Low -> Level l k L ->\n        LoggedP (Bad a) L \\/ LoggedP (Bad b) L.\n    Proof.\n        intros a b req k L. unfold SessionKeyAB.\n        intros HGoodLog HSessionKey. intro l. intros Hlow Hlevel.\n        unfold GoodLog in HGoodLog. destruct HGoodLog as (HGL_WfLog & HGL_LogInv).\n        unfold WF_Log in HGL_WfLog. destruct HGL_WfLog as (HGL_WL_Usage & _).\n        unfold LogInvariant in HGL_LogInv. specialize HGL_LogInv with (t:=k) (u:=SEncKey (U_SKeyAB a b req)).\n        assert ( HSessionKey_bis : Logged (New k (SEncKey (U_SKeyAB a b req))) L ). assumption.\n        apply HGL_LogInv in HSessionKey_bis. destruct HSessionKey_bis as (bs, HLitk).\n        induction k ; try discriminate. induction Hlevel ; try discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=SEncKey (U_SKeyAB a b req)) (u':=AdversaryGuess).\n            apply HGL_WL_Usage in HSessionKey ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=SEncKey (U_SKeyAB a b req)) (u':=Nonce nu).\n            apply HGL_WL_Usage in HSessionKey ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=SEncKey (U_SKeyAB a b req)) (u':=HMacKey hu).\n            apply HGL_WL_Usage in HSessionKey ; try assumption. discriminate.\n        - apply H0 in Hlow. unfold sencComp in Hlow. destruct Hlow as [Hlow_sess | Hlow_key].\n            + destruct Hlow_sess as (a', Hlow_sess_a). destruct Hlow_sess_a as (b', Hlow_sess_ab).\n                destruct Hlow_sess_ab as (req', Hlow_sess_abreq). destruct Hlow_sess_abreq as (Hsess_sessKey & Hsess_sessKeyComp).\n                unfold SessionKeyAB in Hsess_sessKey. \n                specialize HGL_WL_Usage with (t:=Literal bs0) (u:=SEncKey (U_SKeyAB a b req)) (u':=SEncKey (U_SKeyAB a' b' req')).\n                apply HGL_WL_Usage in Hsess_sessKey ; try assumption. injection Hsess_sessKey. intros Hreq Hb Ha.\n                rewrite Ha. rewrite Hb. unfold SessionKeyComp in Hsess_sessKeyComp. assumption.\n            + destruct Hlow_key as (a', Hlow_key_a). destruct Hlow_key_a as (b', Hlow_key_ab).\n                destruct Hlow_key_ab as (Hlow_key_key & _). unfold KeyAB in Hlow_key_key.\n                specialize HGL_WL_Usage with (t:=Literal bs0) (u:=SEncKey (U_SKeyAB a b req)) (u':=SEncKey (U_KeyAB a' b')).\n                apply HGL_WL_Usage in Hlow_key_key ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=SEncKey (U_SKeyAB a b req)) (u':=SignKey su).\n            apply HGL_WL_Usage in HSessionKey ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=SEncKey (U_SKeyAB a b req)) (u':=VerfKey su).\n            apply HGL_WL_Usage in HSessionKey ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=SEncKey (U_SKeyAB a b req)) (u':=EncKey eu).\n            apply HGL_WL_Usage in HSessionKey ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=SEncKey (U_SKeyAB a b req)) (u':=DecKey eu).\n            apply HGL_WL_Usage in HSessionKey ; try assumption. discriminate.\n    Qed.\n\n    Theorem RequestSecrecy: forall a b req L,\n        GoodLog L -> RequestAB a b req L ->\n        forall l, l = Low -> Level l req L ->\n        LoggedP (Bad a) L \\/ LoggedP (Bad b) L.\n    Proof.\n        intros a b req L. unfold RequestAB. intros HGoodLog Hrequest. intro l. intros Hlow Hlevel.\n        unfold GoodLog in HGoodLog. destruct HGoodLog as (HGL_WfLog & HGL_LogInv).\n        unfold WF_Log in HGL_WfLog. destruct HGL_WfLog as (HGL_WL_Usage & _).\n        unfold LogInvariant in HGL_LogInv. specialize HGL_LogInv with (t:=req) (u:=Nonce (U_RequestN a b)).\n        assert ( Hlog : Logged (New req (Nonce (U_RequestN a b))) L ). assumption.\n        apply HGL_LogInv in Hlog. destruct Hlog as (bs, HLitreq).\n        induction req ; try discriminate. induction Hlevel ; try discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=Nonce (U_RequestN a b)) (u':=AdversaryGuess).\n            apply HGL_WL_Usage in Hrequest ; try assumption. discriminate.\n        - apply H0 in Hlow. unfold nonceComp in Hlow.\n            destruct Hlow as (a', Hlow_a). destruct Hlow_a as (b', Hlow_ab).\n            destruct Hlow_ab as [Hlow_req | Hlow_resp].\n            + destruct Hlow_req as (Hlow_req & Hlow_reqComp). unfold RequestN in Hlow_req.\n                specialize HGL_WL_Usage with (t:=Literal bs0) (u:=Nonce (U_RequestN a b)) (u':=Nonce (U_RequestN a' b')).\n                apply HGL_WL_Usage in Hrequest ; try assumption. injection Hrequest. intros Hb Ha.\n                unfold RequestNComp in Hlow_reqComp. rewrite <- Ha in Hlow_reqComp. rewrite <- Hb in Hlow_reqComp.\n                assumption.\n            + destruct Hlow_resp as (Hlow_resp & _). unfold ResponseN in Hlow_resp.\n                specialize HGL_WL_Usage with (t:=Literal bs0) (u:=Nonce (U_RequestN a b)) (u':=Nonce (U_ResponseN a' b')).\n                apply HGL_WL_Usage in Hrequest ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=Nonce (U_RequestN a b)) (u':=HMacKey hu).\n            apply HGL_WL_Usage in Hrequest ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=Nonce (U_RequestN a b)) (u':=SEncKey su).\n            apply HGL_WL_Usage in Hrequest ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=Nonce (U_RequestN a b)) (u':=SignKey su).\n            apply HGL_WL_Usage in Hrequest ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=Nonce (U_RequestN a b)) (u':=VerfKey su).\n            apply HGL_WL_Usage in Hrequest ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=Nonce (U_RequestN a b)) (u':=EncKey eu).\n            apply HGL_WL_Usage in Hrequest ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=Nonce (U_RequestN a b)) (u':=DecKey eu).\n            apply HGL_WL_Usage in Hrequest ; try assumption. discriminate.\n    Qed.\nEnd ERPCTheorems.\n\nModule OtwayReesTheorems.\n    Import OtwayReesDefs.\n    Include CryptographicInvariants OtwayReesDefs OtwayReesInvariants.\n    Import OtwayReesInvariants.\n\n    Theorem RequestCorrespondence: forall a b k req L,\n        GoodLog L -> KeyAB a b k L ->\n        forall l t, l = Low -> t = (HMac k (Pair (Literal (String TagRequest EmptyString)) req)) -> \n        Level l t L ->\n        LoggedP (Request a b req) L \\/\n        LoggedP (Bad a) L \\/ LoggedP (Bad b) L.\n    Proof.\n        intros a b k req L. unfold KeyAB. \n        intros HGoodLog HKeyAB. intros l t. intros Hlow Hhmac Hlevel. \n        assert ( HGoodLog_bis : GoodLog L ). assumption.\n        unfold GoodLog in HGoodLog. destruct HGoodLog as (HGL_WfLog & HGL_LogInv).\n        unfold WF_Log in HGL_WfLog. destruct HGL_WfLog as (HGL_WL_Usage & _).\n        unfold LogInvariant in HGL_LogInv. induction Hlevel ; try discriminate.\n        - left. injection Hhmac. intros Hm Hk0. rewrite Hk0 in H. unfold canHmac in H.\n            destruct H as (a0, Ha). destruct Ha as (b0, Hab). destruct Hab as (Hab_key & Hab_keyPayload).\n            unfold KeyAB in Hab_key. specialize HGL_WL_Usage with (t:=k) (u:=HMacKey (U_KeyAB a b)) (u':=HMacKey (U_KeyAB a0 b0)).\n            apply HGL_WL_Usage in HKeyAB ; try assumption. injection HKeyAB. intros Hb Ha.\n            unfold KeyABPayload in Hab_keyPayload. destruct Hab_keyPayload as [Hab_KP_req | Hab_KP_reqresp].\n            + destruct Hab_KP_req as (req0, Hab_KP_req). destruct Hab_KP_req as (Hab_KP_req_m & Hab_KP_req_log).\n                symmetry in Hm. rewrite Hab_KP_req_m in Hm. injection Hm. intro Hreq.\n                rewrite Ha. rewrite Hb. rewrite Hreq. assumption.\n            +  exfalso. destruct Hab_KP_reqresp as (req0, Hab_KP_req). destruct Hab_KP_req as (resp0, Hab_KP_reqresp).\n                destruct Hab_KP_reqresp as (Hab_KP_reqresp_m & _). symmetry in Hm. rewrite Hab_KP_reqresp_m in Hm. \n                injection Hm. intros _ Htag.\n                assert ( HtagDistinct : TagRequest <> TagResponse ). apply TagsDistinct. \n                tauto.\n        - right. injection Hhmac. intros Hm Hk0.\n            specialize HGL_LogInv with (t:=k) (u:=HMacKey (U_KeyAB a b)). \n            assert ( Hlog : Logged (New k (HMacKey (U_KeyAB a b))) L ). assumption.\n            apply HGL_LogInv in HKeyAB. destruct HKeyAB as (bs, HLitk).\n            assert ( HhmacComp : hmacComp (Literal bs) L ).\n            + apply LowHmacKeyLiteral_Inversion with (hu:=U_KeyAB a b) (l:=Low) (t:=Literal bs) ; try easy.\n                * rewrite HLitk in Hlog. assumption.\n                * rewrite Hk0 in Hlevel1. rewrite HLitk in Hlevel1. assumption.\n            + unfold hmacComp in HhmacComp. destruct HhmacComp as (a0, HhmacComp_a). destruct HhmacComp_a as (b0, HhmacComp_ab).\n                destruct HhmacComp_ab as (HHC_ab_key & HHC_ab_keyComp). unfold KeyAB in HHC_ab_key.\n                rewrite HLitk in Hlog. specialize HGL_WL_Usage with (t:=Literal bs) (u:=HMacKey (U_KeyAB a b)) (u':=HMacKey (U_KeyAB a0 b0)).\n                apply HGL_WL_Usage in HHC_ab_key ; try assumption. injection HHC_ab_key.\n                intros Hb Ha. rewrite Hb. rewrite Ha. unfold KeyABComp in HHC_ab_keyComp. assumption.\n    Qed.\n\n    Theorem ResponseCorrespondence: forall a b k req resp L,\n        GoodLog L -> KeyAB a b k L ->\n        forall l t, l = Low -> t = (HMac k (Pair (Literal (String TagResponse EmptyString)) (Pair req resp))) ->\n        Level l t L ->\n        LoggedP (Response a b req resp) L \\/\n        LoggedP (Bad a) L \\/ LoggedP (Bad b) L.\n    Proof.\n        intros a b k req resp L. unfold KeyAB.\n        intros HGoodLog HKeyAB. intros l t. intros Hlow Hhmac Hlevel. \n        assert ( HGoodLog_bis : GoodLog L ). assumption.\n        unfold GoodLog in HGoodLog. destruct HGoodLog as (HGL_WfLog & HGL_LogInv).\n        unfold WF_Log in HGL_WfLog. destruct HGL_WfLog as (HGL_WL_Usage & _).\n        unfold LogInvariant in HGL_LogInv. induction Hlevel ; try discriminate.\n        - left. injection Hhmac. intros Hm Hk0. rewrite Hk0 in H. unfold canHmac in H.\n            destruct H as (a0, Ha). destruct Ha as (b0, Hab). destruct Hab as (Hab_key & Hab_keyPayload).\n            unfold KeyAB in Hab_key. specialize HGL_WL_Usage with (t:=k) (u:=HMacKey (U_KeyAB a b)) (u':=HMacKey (U_KeyAB a0 b0)).\n            apply HGL_WL_Usage in HKeyAB ; try assumption. injection HKeyAB. intros Hb Ha.\n            unfold KeyABPayload in Hab_keyPayload. destruct Hab_keyPayload as [Hab_KP_req | Hab_KP_reqresp].\n            + exfalso. destruct Hab_KP_req as (req0, hab_KP_req). destruct hab_KP_req as (Hab_KP_req_m & _).\n                symmetry in Hm. rewrite Hab_KP_req_m in Hm. injection Hm. intros _ Htag.\n                assert ( HtagDistinct : TagRequest <> TagResponse ). apply TagsDistinct. firstorder.\n            + destruct Hab_KP_reqresp as (req0, hab_KP_req). destruct hab_KP_req as (resp0, Hab_KP_reqresp).\n                destruct Hab_KP_reqresp as (Hab_KP_reqresp_m & Hab_KP_reqresp_log). symmetry in Hm. rewrite Hab_KP_reqresp_m in Hm. \n                injection Hm. intros Hresp Hreq. rewrite Ha. rewrite Hb. rewrite Hreq. rewrite Hresp. assumption.\n        - right. injection Hhmac. intros Hm Hk0.\n            specialize HGL_LogInv with (t:=k) (u:=HMacKey (U_KeyAB a b)).\n            assert ( Hlog : Logged (New k (HMacKey (U_KeyAB a b))) L ). assumption.\n            apply HGL_LogInv in HKeyAB. destruct HKeyAB as (bs, HLitk).\n            assert ( HhmacComp : hmacComp (Literal bs) L).\n            + apply LowHmacKeyLiteral_Inversion with (hu:=U_KeyAB a b) (l:=Low) (t:=Literal bs) ; try easy.\n                * rewrite HLitk in Hlog. assumption.\n                * rewrite Hk0 in Hlevel1. rewrite HLitk in Hlevel1. assumption.\n            + unfold hmacComp in HhmacComp. destruct HhmacComp as (a0, HhmacComp_a). destruct HhmacComp_a as (b0, HhmacComp_ab).\n                destruct HhmacComp_ab as (HHC_ab_key & HHC_ab_keyComp). unfold KeyAB in HHC_ab_key.\n                rewrite HLitk in Hlog. specialize HGL_WL_Usage with (t:=Literal bs) (u:=HMacKey (U_KeyAB a b)) (u':=HMacKey (U_KeyAB a0 b0)).\n                apply HGL_WL_Usage in HHC_ab_key ; try assumption. injection HHC_ab_key.\n                intros Hb Ha. rewrite Hb. rewrite Ha. unfold KeyABComp in HHC_ab_keyComp. assumption. \n    Qed.\n\n    Theorem KeySecrecy: forall a b k L,\n        GoodLog L -> KeyAB a b k L -> \n        forall l, l = Low -> Level l k L ->\n        LoggedP (Bad a) L \\/ LoggedP (Bad b) L.\n    Proof.\n        intros a b k L. unfold KeyAB.\n        intros HGoodLog HKeyAB. intro l. intros Hlow Hlevel. \n        unfold GoodLog in HGoodLog. destruct HGoodLog as (HGL_WfLog & HGL_LogInv).\n        unfold WF_Log in HGL_WfLog. destruct HGL_WfLog as (HGL_WL_Usage & _).\n        unfold LogInvariant in HGL_LogInv. specialize HGL_LogInv with (t:=k) (u:=HMacKey (U_KeyAB a b)).\n        assert ( HKeyAB_bis : Logged (New k (HMacKey (U_KeyAB a b))) L ). assumption.\n        apply HGL_LogInv in HKeyAB_bis. destruct HKeyAB_bis as (bs, HLitk).\n        induction k ; try discriminate. induction Hlevel ; try discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=AdversaryGuess) (u':=HMacKey (U_KeyAB a b)).\n            apply HGL_WL_Usage in HKeyAB ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=Nonce nu) (u':=HMacKey (U_KeyAB a b)).\n            apply HGL_WL_Usage in HKeyAB ; try assumption. discriminate.\n        - apply H0 in Hlow. unfold hmacComp in Hlow. destruct Hlow as (a', Hlow_a). destruct Hlow_a as (b', Hlow_ab).\n            destruct Hlow_ab as (Hab_key & Hab_keyComp). unfold KeyAB in Hab_key.\n            specialize HGL_WL_Usage with (t:=Literal bs0) (u:=HMacKey (U_KeyAB a b)) (u':=HMacKey (U_KeyAB a' b')).\n            apply HGL_WL_Usage in Hab_key ; try assumption. injection Hab_key.\n            intros Hb Ha. rewrite Ha. rewrite Hb. unfold KeyABComp in Hab_keyComp. assumption.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=SEncKey su) (u':=HMacKey (U_KeyAB a b)).\n            apply HGL_WL_Usage in HKeyAB ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=SignKey su) (u':=HMacKey (U_KeyAB a b)).\n            apply HGL_WL_Usage in HKeyAB ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=VerfKey su) (u':=HMacKey (U_KeyAB a b)).\n            apply HGL_WL_Usage in HKeyAB ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=EncKey eu) (u':=HMacKey (U_KeyAB a b)).\n            apply HGL_WL_Usage in HKeyAB ; try assumption. discriminate.\n        - specialize HGL_WL_Usage with (t:=Literal bs0) (u:=DecKey eu) (u':=HMacKey (U_KeyAB a b)).\n            apply HGL_WL_Usage in HKeyAB ; try assumption. discriminate.\n    Qed.\n\n    Theorem KeyedHMac_Inversion: forall hu k p L,\n        GoodLog L -> Logged (New k (HMacKey hu)) L ->\n        forall l t, l = High -> t = HMac k p -> Level l t L ->\n        canHmac k p L \\/ hmacComp k L.\n    Proof.\n        intros hu k p L. intros HGoodLog Hlog. intros l t. intros Hhigh Hhmac Hlevel.\n        assert ( HGoodLog_bis : GoodLog L ). assumption.\n        unfold GoodLog in HGoodLog. destruct HGoodLog as (HGL_WfLog & HGL_LogInv).\n        unfold WF_Log in HGL_WfLog. destruct HGL_WfLog as (HGL_WL_Usage & _).\n        unfold LogInvariant in HGL_LogInv. induction Hlevel ; try discriminate.\n        - left. injection Hhmac. intros Hm Hk0. rewrite Hm in H. rewrite Hk0 in H. assumption.\n        - right. injection Hhmac. intros _ Hk0. rewrite Hk0 in Hlevel1.\n            specialize HGL_LogInv with (t:=k) (u:=HMacKey hu).\n            assert ( Hlog_bis : Logged (New k (HMacKey hu)) L ). assumption.\n            apply HGL_LogInv in Hlog_bis. destruct Hlog_bis as (bs, HLitk).\n            rewrite HLitk. apply LowHmacKeyLiteral_Inversion with (hu:=hu) (l:=Low) (t:=Literal bs) ; try easy.\n            + rewrite HLitk in Hlog. assumption.\n            + rewrite HLitk in Hlevel1. assumption.\n    Qed.\n\n    Theorem InitiatorCorrespondence: forall a b ka na kab L,\n        GoodLog L -> (a <> b) -> PrinKeyAB a ka L ->\n        forall l t, l = Low -> t = SEnc ka (Pair a (Pair b (Pair kab na))) -> Level l t L ->\n        KeyAB a b kab L \\/ LoggedP (Bad a) L.\n    Proof.\n        intros a b ka na kab L. intros HGoodLog Hanotb HprinKeyAB.\n        intros l t. intros Hlow Hsenc Hlevel. assert ( HGoodLog_bis : GoodLog L ). assumption.\n        unfold GoodLog in HGoodLog. destruct HGoodLog as (HGL_WfLog & HGL_LogInv).\n        unfold WF_Log in HGL_WfLog. destruct HGL_WfLog as (HGL_WL_Usage & _).\n        unfold LogInvariant in HGL_LogInv. unfold PrinKeyAB in HprinKeyAB.\n        induction Hlevel ; try discriminate.\n        - left. injection Hsenc. intros Hp Hk. unfold canSEnc in H.\n            destruct H as (p0, Hp0). destruct Hp0 as (HprinKey & HprinKeyPayload).\n            rewrite Hk in HprinKey. unfold PrinKeyAB in HprinKey.\n            specialize HGL_WL_Usage with (t:=ka) (u:=SEncKey (U_SKeyAB a)) (u':=SEncKey (U_SKeyAB p0)).\n            apply HGL_WL_Usage in HprinKeyAB ; try assumption. injection HprinKeyAB. intro Ha.\n            unfold PrinKeyPayload in HprinKeyPayload. destruct HprinKeyPayload as [HpKP_init | HpKP_resp].\n            * destruct HpKP_init as (b0, HpKP_init_b). destruct HpKP_init_b as (np0, HpKP_init_bnp).\n                destruct HpKP_init_bnp as (kpb0, HpKP_init_bnpkpb). destruct HpKP_init_bnpkpb as (_ & HpKP_init_bnpkpb).\n                destruct HpKP_init_bnpkpb as (Hp_bis & HpKP_init_bnpkpb).\n                symmetry in Hp_bis. rewrite Hp in Hp_bis. injection Hp_bis.\n                intros _ Hkpb0 Hb0 _. destruct HpKP_init_bnpkpb as (HpKP_init_key & _).\n                rewrite Ha. rewrite <- Hb0. rewrite <- Hkpb0. assumption.\n            * exfalso. destruct HpKP_resp as (a0, HpKP_resp_a). destruct HpKP_resp_a as (np0, HpKP_resp_anp).\n                destruct HpKP_resp_anp as (kap0, HpKP_resp_anpkap). destruct HpKP_resp_anpkap as (Hpnota & HpKP_resp_anpkap).\n                destruct HpKP_resp_anpkap as (Hp_bis & _). symmetry in Hp_bis. rewrite Hp in Hp_bis.\n                injection Hp_bis. intros _ _ _ Ha0. rewrite Ha0 in Hpnota. firstorder.\n        - right. injection Hsenc. intros Hp Hk. rewrite Hk in Hlevel1.\n            specialize HGL_LogInv with (t:=ka) (u:=SEncKey (U_SKeyAB a)).\n            assert ( Hlog : Logged (New ka (SEncKey (U_SKeyAB a))) L ). assumption.\n            apply HGL_LogInv in Hlog. destruct Hlog as (bs, HLitka).\n            assert ( HsencComp : sencComp (Literal bs) L ).  \n            * rewrite HLitka in Hlevel1. apply LowSencKeyLiteral_Inversion with (su:=U_SKeyAB a) (l:=Low) (t:=Literal bs) ; try easy.\n                rewrite HLitka in HprinKeyAB. assumption.\n            * unfold sencComp in HsencComp. destruct HsencComp as (p0, HsencComp_p).\n                destruct HsencComp_p as (HSC_prinKey & HSC_prinKeyComp).\n                unfold PrinKeyAB in HSC_prinKey. unfold PrinKeyComp in HSC_prinKeyComp.\n                rewrite HLitka in HprinKeyAB. specialize HGL_WL_Usage with (t:=Literal bs) (u:=SEncKey (U_SKeyAB a)) (u':=SEncKey (U_SKeyAB p0)).\n                apply HGL_WL_Usage in HprinKeyAB ; try assumption. injection HprinKeyAB. intro Ha. rewrite Ha. assumption.\n    Qed.\n\n    Theorem ResponderCorrespondence: forall a b kb nb kab L,\n        GoodLog L -> (a <> b) -> PrinKeyAB b kb L ->\n        forall l t, l = Low -> t = SEnc kb (Pair a (Pair b (Pair kab nb))) -> Level l t L ->\n        KeyAB a b kab L \\/ LoggedP (Bad b) L.\n    Proof.\n        intros a b kb nb kab L. intros HGoodLog Hanotb HprinKeyAB.\n        assert ( HGoodLog_bis : GoodLog L ). assumption.\n        unfold PrinKeyAB in HprinKeyAB. intros l t. intros Hlow Hsenc Hlevel.\n        unfold GoodLog in HGoodLog. destruct HGoodLog as (HGL_WfLog & HGL_LogInv).\n        unfold WF_Log in HGL_WfLog. destruct HGL_WfLog as (HGL_WL_Usage & _).\n        unfold LogInvariant in HGL_LogInv. induction Hlevel ; try discriminate.\n        - left. injection Hsenc. intros Hp Hk. rewrite Hk in H. unfold canSEnc in H.\n            destruct H as (p0, Hp0). destruct Hp0 as (HprinKey & HprinKeyPayload).\n            unfold PrinKeyAB in HprinKey. unfold PrinKeyPayload in HprinKeyPayload.\n            specialize HGL_WL_Usage with (t:=kb) (u:=SEncKey (U_SKeyAB b)) (u':=SEncKey (U_SKeyAB p0)).\n            apply HGL_WL_Usage in HprinKeyAB ; try assumption. injection HprinKeyAB. intro Hb.\n            destruct HprinKeyPayload as [HpKP_init | HpKP_resp].\n            * exfalso. destruct HpKP_init as (b0, HpKP_init_b). destruct HpKP_init_b as (np0, HpKP_init_bnp).\n                destruct HpKP_init_bnp as (kpb0, HpKP_init_bnpkpb). destruct HpKP_init_bnpkpb as (Hpnotb & HpKP_init_bnpkpb).\n                destruct HpKP_init_bnpkpb as (Hp_bis & _). symmetry in Hp_bis. rewrite Hp in Hp_bis. injection Hp_bis.\n                intros _ _ Hb0 Hp0. rewrite Hb in Hb0. firstorder.\n            * destruct HpKP_resp as (a0, HpKP_resp_a). destruct HpKP_resp_a as (np0, HpKP_resp_anp).\n                destruct HpKP_resp_anp as (kap0, HpKP_resp_anpkap). destruct HpKP_resp_anpkap as (_ & HpKP_resp_anpkap).\n                destruct HpKP_resp_anpkap as (Hp_bis & HpKP_resp_anpkap). destruct HpKP_resp_anpkap as (HKeyAB & _).\n                symmetry in Hp_bis. rewrite Hp in Hp_bis. injection Hp_bis. intros _ Hkap Hp0 Ha0.\n                rewrite <- Ha0. rewrite <- Hp0. rewrite <- Hkap. assumption.\n        - right. injection Hsenc. intros Hp Hk. rewrite Hk in Hlevel1.\n            specialize HGL_LogInv with (t:=kb) (u:=SEncKey (U_SKeyAB b)).\n            assert ( Hlog : Logged (New kb (SEncKey (U_SKeyAB b))) L ). assumption.\n            apply HGL_LogInv in Hlog. destruct Hlog as (bs, HLitka).\n            assert ( HsencComp : sencComp (Literal bs) L ).  \n            * rewrite HLitka in Hlevel1. apply LowSencKeyLiteral_Inversion with (su:=U_SKeyAB b) (l:=Low) (t:=Literal bs) ; try easy.\n                rewrite HLitka in HprinKeyAB. assumption.\n            * unfold sencComp in HsencComp. destruct HsencComp as (p0, HsencComp_p).\n                destruct HsencComp_p as (HSC_prinKey & HSC_prinKeyComp).\n                unfold PrinKeyAB in HSC_prinKey. unfold PrinKeyComp in HSC_prinKeyComp.\n                rewrite HLitka in HprinKeyAB. specialize HGL_WL_Usage with (t:=Literal bs) (u:=SEncKey (U_SKeyAB b)) (u':=SEncKey (U_SKeyAB p0)).\n                apply HGL_WL_Usage in HprinKeyAB ; try assumption. injection HprinKeyAB. intro Hb. rewrite Hb. assumption.\n    Qed.\nEnd OtwayReesTheorems.\n", "meta": {"author": "BtheCat", "repo": "babel-MAC", "sha": "295ffd0adcb1338ce49f1e25da54a3c47543a055", "save_path": "github-repos/coq/BtheCat-babel-MAC", "path": "github-repos/coq/BtheCat-babel-MAC/babel-MAC-295ffd0adcb1338ce49f1e25da54a3c47543a055/symbolic_security.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2748019224645231}}
{"text": "(** This code was automatically generated by Autosubst 2.0 Beta.\n\nThe following inductive types were generated:\nty : Type\ntm : Type\nvl : Type\n\nThe following variable constructors were generated:\nvar_ty : Type\nvar_vl : Type\n\nAutosubst 2 uses vectors of substitutions. The types of the generated substiutions are listed below:\nsubst_of subst_of_ty := index -> ty\nsubst_of subst_of_tm := (index -> ty, index -> vl)\nsubst_of subst_of_vl := (index -> ty, index -> vl)\n\nAutosubst 2 furthermore generated the following instantiation operations:\nsubst_ty : subst_of subst_of_ty -> ty -> ty,\nalso accessible as s.[sigma]\nsubst_tm : subst_of subst_of_tm -> tm -> tm,\nalso accessible as s.[sigma]\nsubst_vl : subst_of subst_of_vl -> vl -> vl,\nalso accessible as s.[sigma]\n\nSee the generated dot-graph for further details.\n\nAutomation has been extended to include the generated definitions. The tactic asimpl simplifies goals containing substiution expressions, autosubst corresponds to now asimpl.\n\nIf Autosubst 2 does not behave as expected, we are grateful for a short mail to autosubst@ps.uni-saarland.de.\nThank you!\n\nNote: As work-in-progress, some proofs were added by hand. These are marked accordingly.\n*)\n\nRequire Export Autosubst2.\nSet Implicit Arguments.\nRequire Import Lists.List.\nImport ListNotations.\nSet Typeclasses Filtered Unification.\n\nInductive ty  : Type :=\n  | var_ty : index -> ty\n  | arr : ty -> ty -> ty\n  | all : ty -> ty.\n\nDefinition congr_arr {s0 s1 t0 t1: ty} (E0: s0 = t0) (E1: s1 = t1) : arr s0 s1 = arr t0 t1 :=\n  apc (ap arr E0) (E1).\n\nDefinition congr_all {s0 t0: ty} (E0: s0 = t0) : all s0 = all t0 :=\n  ap all E0.\n\nDefinition subst_of_ty  : list Type :=\n  [ty: Type].\n\nDefinition toVarRen_ty (xi: ren_of subst_of_ty) : _ :=\n  let xi := xi in xi.\n\n\n\nDefinition upren_ty_ty (xi: ren_of subst_of_ty) : ren_of subst_of_ty :=\n  let xi_ty := xi in up_ren xi_ty.\n\nFixpoint ren_ty (xi: ren_of subst_of_ty) (s: ty) : ty :=\n  match s with\n  | var_ty x => var_ty ((toVarRen_ty xi) x)\n  | arr s0 s1 => arr ((ren_ty xi s0)) ((ren_ty xi s1))\n  | all s0 => all ((ren_ty (upren_ty_ty xi) s0))\n  end.\n\nDefinition toVar_ty (sigma: subst_of subst_of_ty) : _ :=\n  let sigma := sigma in sigma.\n\nDefinition eq_toVar_ty {sigma tau: subst_of subst_of_ty} (E: eq_of_subst sigma tau) (n: index) : toVar_ty sigma n = toVar_ty tau n.\n  rename sigma into sigma_ty. rename tau into tau_ty. rename E into E_ty.\n  exact (E_ty n).\nDefined.\n\nDefinition compren_ty (sigma: subst_of subst_of_ty) (xi: ren_of subst_of_ty) : subst_of subst_of_ty :=\n  match sigma with\n  | sigma_ty => fun x => ren_ty xi (sigma_ty x)\n  end.\n\nDefinition up_ty_ty (sigma: subst_of subst_of_ty) : subst_of subst_of_ty :=\n  match compren_ty sigma S with\n  | sigma_ty => scons (var_ty 0) sigma_ty\n  end.\n\n\n\n\n\nFixpoint subst_ty (sigma: subst_of subst_of_ty) (s: ty) : ty :=\n  match s with\n  | var_ty x =>  ((toVar_ty sigma) x)\n  | arr s0 s1 => arr ((subst_ty sigma s0)) ((subst_ty sigma s1))\n  | all s0 => all ((subst_ty (up_ty_ty sigma) s0))\n  end.\n\nDefinition comp_ty (sigma tau: subst_of subst_of_ty) : subst_of subst_of_ty :=\n  match sigma with\n  | sigma_ty => fun x => subst_ty tau (sigma_ty x)\n  end.\n\nDefinition substMixin_ty  : substMixin ty :=\n  {|subst_of_substType := subst_of_ty;inst_of_substType := subst_ty|}.\n\nCanonical Structure substType_ty  : substType :=\n  Eval hnf in @Pack ty substMixin_ty ty.\n\nDefinition upId_ty_ty (sigma_ty: index -> ty) (E_ty: sigma_ty == var_ty) : @eq_of_subst subst_of_ty (up_ty_ty sigma_ty) var_ty :=\n  fun n => match n return (match up_ty_ty sigma_ty with\n  | tau_ty => tau_ty n = var_ty  n\n  end) with\n  | 0 => eq_refl\n  | S n => ap (ren_ty S) (E_ty n)\n  end.\n\nFixpoint id_ty (sigma_ty: index -> ty) (E_ty: sigma_ty == var_ty) (s: ty) : subst_ty sigma_ty s = s :=\n  match s with\n  | var_ty n => E_ty n\n  | arr s0 s1 => apc (ap arr (id_ty _ E_ty s0)) ((id_ty _ E_ty s1))\n  | all s0 => ap all (match upId_ty_ty _ E_ty with\n      | E_ty => id_ty _ E_ty s0\n      end)\n  end.\n\nDefinition toSubst_ty (xi: ren_of subst_of_ty) : subst_of subst_of_ty :=\n  match xi with\n  | xi_ty => fun x => var_ty (xi_ty x)\n  end.\n\nFixpoint compTrans_ren_ren_ty (xi_ty zeta_ty theta_ty: ren) (E_ty: funcomp (xi_ty) (zeta_ty) == theta_ty) (s: ty)\n           : ren_ty zeta_ty (ren_ty xi_ty s) = ren_ty theta_ty s :=\n  match s with\n  | var_ty n => ap var_ty (E_ty n)\n  | arr s0 s1 => apc (ap arr (compTrans_ren_ren_ty xi_ty zeta_ty theta_ty E_ty s0)) ((compTrans_ren_ren_ty xi_ty zeta_ty theta_ty E_ty s1))\n  | all s0 => ap all (compTrans_ren_ren_ty (up_ren xi_ty) (up_ren zeta_ty) (up_ren theta_ty) (up_ren_ren xi_ty zeta_ty theta_ty E_ty) s0)\n  end.\n\nDefinition compE_ren_ren_ty (xi_ty zeta_ty: ren) (s: ty) : ren_ty zeta_ty (ren_ty xi_ty s) = ren_ty (funcomp xi_ty zeta_ty) s :=\n  compTrans_ren_ren_ty xi_ty zeta_ty (funcomp xi_ty zeta_ty) (fun _ => eq_refl) s.\n\nDefinition up_ren_subst_ty_ty (xi_ty: ren) (theta_ty tau_ty: index -> ty) (E_ty: (fun x =>  theta_ty (xi_ty x)) == tau_ty)\n  : @eq_of_subst subst_of_ty (comp_ty (toSubst_ty (upren_ty_ty xi_ty)) (up_ty_ty theta_ty)) (up_ty_ty tau_ty) :=\n  fun n => match n return match comp_ty (toSubst_ty (upren_ty_ty xi_ty)) (up_ty_ty theta_ty), up_ty_ty tau_ty with\n  | xi_ty, tau_ty => xi_ty n = tau_ty n\n  end with\n  | 0 => eq_refl\n  | S n => ap (ren_ty S) (E_ty n)\n  end.\n\nFixpoint compTrans_ren_subst_ty (xi_ty: ren) (tau_ty theta_ty: index -> ty) (E_ty: (fun x =>  tau_ty (xi_ty x)) == theta_ty) (s: ty)\n           : subst_ty tau_ty (ren_ty xi_ty s) = subst_ty theta_ty s :=\n  match s with\n  | var_ty n =>  (E_ty n)\n  | arr s0 s1 => apc (ap arr (compTrans_ren_subst_ty xi_ty _ _ E_ty s0)) ((compTrans_ren_subst_ty xi_ty _ _ E_ty s1))\n  | all s0 => ap all (match up_ren_subst_ty_ty xi_ty tau_ty theta_ty E_ty with\n      | E_ty => compTrans_ren_subst_ty (up_ren xi_ty) _ _ E_ty s0\n      end)\n  end.\n\nDefinition compE_ren_subst_ty (xi_ty: ren) (tau_ty: index -> ty) (s: ty)\n  : subst_ty tau_ty (ren_ty xi_ty s) = subst_ty (funcomp xi_ty tau_ty) s :=\n  compTrans_ren_subst_ty xi_ty tau_ty (funcomp xi_ty tau_ty) (fun _ => eq_refl) s.\n\nDefinition up_subst_ren_ty_ty (sigma_ty: index -> ty)\n  (rho_ty: ren)\n  (tau_ty: index -> ty)\n  (E_ty: (fun x =>  ren_ty rho_ty (sigma_ty x)) == tau_ty)\n  : @eq_of_subst subst_of_ty (compren_ty (up_ty_ty sigma_ty) (upren_ty_ty rho_ty)) (up_ty_ty tau_ty) :=\n  fun n => match n return match compren_ty (up_ty_ty sigma_ty) (upren_ty_ty rho_ty), up_ty_ty tau_ty with\n  | sigma_ty, tau_ty => sigma_ty n = tau_ty n\n  end with\n  | 0 => eq_refl\n  | S n =>\n      eq_trans (compE_ren_ren_ty S (up_ren rho_ty) (sigma_ty n)) (eq_trans (eq_sym (compE_ren_ren_ty rho_ty S (sigma_ty n))) (ap (ren_ty S) (E_ty n)))\n  end.\n\nFixpoint compTrans_subst_ren_ty (sigma_ty: index -> ty)\n           (zeta_ty: ren)\n           (theta_ty: index -> ty)\n           (E_ty: (fun x =>  ren_ty zeta_ty (sigma_ty x)) == theta_ty)\n           (s: ty) : ren_ty zeta_ty (subst_ty sigma_ty s) = subst_ty theta_ty s :=\n  match s with\n  | var_ty n =>  (E_ty n)\n  | arr s0 s1 => apc (ap arr (compTrans_subst_ren_ty _ zeta_ty _ E_ty s0)) ((compTrans_subst_ren_ty _ zeta_ty _ E_ty s1))\n  | all s0 => ap all (match up_subst_ren_ty_ty sigma_ty zeta_ty theta_ty E_ty with\n      | E_ty => compTrans_subst_ren_ty _ (up_ren zeta_ty) _ E_ty s0\n      end)\n  end.\n\nDefinition compE_subst_ren_ty (sigma_ty: index -> ty) (zeta_ty: ren) (s: ty)\n  : ren_ty zeta_ty (subst_ty sigma_ty s) = subst_ty (fun n => ren_ty (zeta_ty) (sigma_ty n)) s :=\n  compTrans_subst_ren_ty sigma_ty zeta_ty (fun n => ren_ty (zeta_ty) (sigma_ty n)) (fun _ => eq_refl) s.\n\nDefinition up_subst_subst_ty_ty (sigma_ty theta_ty tau_ty: index -> ty) (E_ty: (fun x =>  subst_ty theta_ty (sigma_ty x)) == tau_ty)\n  : @eq_of_subst subst_of_ty (comp_ty (up_ty_ty sigma_ty) (up_ty_ty theta_ty)) (up_ty_ty tau_ty) :=\n  fun n => match n return match comp_ty (up_ty_ty sigma_ty) (up_ty_ty theta_ty), up_ty_ty tau_ty with\n  | sigma_ty, tau_ty => sigma_ty n = tau_ty n\n  end with\n  | 0 => eq_refl\n  | S n =>\n      eq_trans (compE_ren_subst_ty S _ (sigma_ty n)) (eq_trans (eq_sym (compE_subst_ren_ty theta_ty S (sigma_ty n))) (ap (ren_ty S) (E_ty n)))\n  end.\n\nFixpoint compTrans_subst_subst_ty (sigma_ty tau_ty theta_ty: index -> ty)\n           (E_ty: (fun x =>  subst_ty tau_ty (sigma_ty x)) == theta_ty)\n           (s: ty) : subst_ty tau_ty (subst_ty sigma_ty s) = subst_ty theta_ty s :=\n  match s with\n  | var_ty n =>  (E_ty n)\n  | arr s0 s1 => apc (ap arr (compTrans_subst_subst_ty _ _ _ E_ty s0)) ((compTrans_subst_subst_ty _ _ _ E_ty s1))\n  | all s0 => ap all (match up_subst_subst_ty_ty sigma_ty tau_ty theta_ty E_ty with\n      | E_ty => compTrans_subst_subst_ty _ _ _ E_ty s0\n      end)\n  end.\n\nDefinition compE_subst_subst_ty (sigma_ty tau_ty: index -> ty) (s: ty)\n  : subst_ty tau_ty (subst_ty sigma_ty s) = subst_ty (fun n => subst_ty (tau_ty) (sigma_ty n)) s :=\n  compTrans_subst_subst_ty sigma_ty tau_ty (fun n => subst_ty (tau_ty) (sigma_ty n)) (fun _ => eq_refl) s.\n\nDefinition eq_up_ty_ty {sigma tau: subst_of subst_of_ty} (E: eq_of_subst sigma tau) : eq_of_subst (up_ty_ty sigma) (up_ty_ty tau).\n  rename sigma into sigma_ty. rename tau into tau_ty. rename E into E_ty.\n  exact (fun i: index => match i return (var_ty 0 .: sigma_ty >>> ren_ty S) i = (var_ty 0 .: tau_ty >>> ren_ty S) i with 0 => eq_refl\n                                                                                                                     | S j => ap _ (E_ty j) end).\nDefined.\n\nFixpoint subst_eq_ty {sigma tau: subst_of subst_of_ty} (E: eq_of_subst sigma tau) (s: ty) : subst_ty sigma s = subst_ty tau s :=\n  match s with\n  | var_ty n => eq_toVar_ty E n\n  | arr s0 s1 => congr_arr (subst_eq_ty E s0) (subst_eq_ty E s1)\n  | all s0 => congr_all (subst_eq_ty (eq_up_ty_ty E) s0)\n  end.\n\nClass AsimplInst_ty (s: ty) (sigma: subst_of subst_of_ty) (t: ty) := asimplInstEqn_ty : (subst_ty sigma) s = t .\nHint Mode AsimplInst_ty + + - : typeclass_instance.\n\nClass AsimplSubst_ty (sigma tau: subst_of subst_of_ty) := asimplSubstEqn_ty : match sigma, tau with\n| sigma_ty, tau_ty => (forall x, sigma_ty x = tau_ty x)\nend .\nHint Mode AsimplSubst_ty + - : typeclass_instance.\n\nClass AsimplComp_ty (sigma tau theta: subst_of subst_of_ty) := asimplCompEqn_ty : match comp_ty sigma tau, theta with\n| sigma_tau_ty, theta_ty => (forall x, sigma_tau_ty x = theta_ty x)\nend .\nHint Mode AsimplComp_ty + + - : typeclass_instance.\n\n\n\nInstance AsimplToVar_ty (sigma_ty: index -> ty) : AsimplGen (toVar_ty sigma_ty) sigma_ty.\nProof. intros x. reflexivity. Qed.\n\nInstance AsimplAsimplInst_ty (s t: ty)\n(sigma sigma': subst_of subst_of_ty)\n(E_sigma: AsimplSubst_ty sigma sigma')\n(E: AsimplInst_ty s sigma' t) : Asimpl (subst_ty sigma s) t.\nProof. rewrite <- E. apply subst_eq_ty. assumption. Qed.\n\nInstance AsimplInstRefl_ty (s: ty) (sigma: subst_of subst_of_ty) : AsimplInst_ty s sigma (s.[ sigma ]) |100.\nProof. reflexivity. Qed.\n\nInstance AsimplInstVar_ty (x y: index)\n(sigma: subst_of subst_of_ty)\n(sigma': index -> ty)\n(s: ty)\n(E: AsimplIndex x y)\n(E': AsimplGen (toVar_ty sigma) sigma')\n(E'': AsimplVarInst y sigma' s) : AsimplInst_ty (var_ty x) sigma s.\nProof. rewrite E. rewrite <- E''. apply E'.  Qed.\n\n(* Proof written by hand. *)\nInstance asimplInst_arr (s0 s1 s0' s1': _)\n(sigma theta_0 theta_1: subst_of subst_of_ty)\n(E_0': AsimplSubst_ty (sigma) theta_0)\n(E_1': AsimplSubst_ty (sigma) theta_1)\n(E_0: AsimplInst_ty s0 theta_0 s0')\n(E_1: AsimplInst_ty s1 theta_1 s1') : AsimplInst_ty (arr s0 s1) sigma (arr s0' s1').\nProof.\n  unfold AsimplInst_ty.\n  simpl. f_equal.\n  - rewrite <- E_0. apply subst_eq_ty. assumption.\n  - rewrite <- E_1. apply subst_eq_ty. assumption.\nQed. \n\n(* Proof written by hand. *)\nInstance asimplInst_all (s0 s0': _)\n(sigma theta_0: subst_of subst_of_ty)\n(E_0': AsimplSubst_ty ((up_ty_ty sigma)) theta_0)\n(E_0: AsimplInst_ty s0 theta_0 s0') : AsimplInst_ty (all s0) sigma (all s0').\nProof.\n  unfold AsimplInst_ty. simpl.\n  f_equal.\n  - rewrite <- E_0. apply subst_eq_ty. assumption. \nQed. \n\nInstance AsimplId_ty (s: ty) : AsimplInst_ty s var_ty s.\nProof. apply id_ty; reflexivity. Qed.\n\n(* Proof written by hand. *)\nInstance AsimplInstInst_ty (s t: ty)\n(sigma sigma' tau sigma_tau: subst_of subst_of_ty)\n(E1: AsimplSubst_ty sigma sigma')\n(E2: AsimplComp_ty sigma' tau sigma_tau)\n(E3: AsimplInst_ty s sigma_tau t) : AsimplInst_ty (subst_ty sigma s) tau t. \nProof.\n  rewrite <- E3. apply compTrans_subst_subst_ty.\n  intros x. rewrite E1. apply E2. \nQed. \n\n(* Proof written by hand. *)\nInstance AsimplSubstRefl_ty (sigma: subst_of subst_of_ty) : AsimplSubst_ty sigma sigma | 100.\nProof. intros x. reflexivity. Qed.\n\n(* Proof written by hand. *)\nInstance AsimplSubstComp_ty (sigma sigma' tau tau' theta: subst_of subst_of_ty)\n(E_sigma: AsimplSubst_ty sigma sigma')\n(E_tau: AsimplSubst_ty tau tau')\n(E: AsimplComp_ty sigma' tau' theta) : AsimplSubst_ty (comp_ty sigma tau) theta |90.\nProof.\n  intros x. rewrite <- E. unfold comp_ty.\n  rewrite E_sigma. apply subst_eq_ty. assumption. \nQed. \n\nInstance AsimplSubstCongr_ty (sigma_ty tau_ty: index -> ty) (E_ty: AsimplGen sigma_ty tau_ty) : AsimplSubst_ty sigma_ty tau_ty |95.\nProof. repeat split; assumption. Qed.\n\n(* Proof written by hand. *)\nInstance AsimplCompRefl_ty (sigma tau: subst_of subst_of_ty) : AsimplComp_ty sigma tau (comp_ty sigma tau) | 100.\nProof. intros x. reflexivity. Qed. \n\n(* Proof written by hand. *)\nInstance AsimplCompIdL_ty (sigma: subst_of subst_of_ty)\n(tau: index -> ty)\n(E: AsimplGen (toVar_ty sigma) tau) : AsimplComp var_ty (subst_ty sigma) tau.\nProof.\n  intros x. simpl. apply E. \nQed. \n\nInstance AsimplCompIdR_ty (sigma: index -> ty) : AsimplComp sigma (subst_ty var_ty) sigma.\nProof. intros x. apply id_ty; reflexivity. Qed.\n\n(* Proof written by hand. *)\nInstance AsimplCompAsso_ty (sigma tau theta tau_theta sigma_tau_theta: subst_of subst_of_ty)\n(E: AsimplComp_ty tau theta tau_theta)\n(E': AsimplComp_ty sigma tau_theta sigma_tau_theta) : AsimplComp_ty (comp_ty sigma tau) theta sigma_tau_theta.\nProof. intros x. rewrite <- E'. unfold comp_ty. erewrite compTrans_subst_subst_ty. reflexivity.\n       assumption. Qed.\n\n(* Proof written by hand. *)\nInstance AsimplCompCongr_ty (sigma_ty theta_ty: index -> ty)\n(tau_ty tau: subst_of subst_of_ty)\n(E_ty: AsimplSubst_ty (tau) tau_ty)\n(E_ty': AsimplComp sigma_ty (subst_ty tau_ty) theta_ty) : AsimplComp_ty sigma_ty tau theta_ty.\nProof.\n  intros x. rewrite <- E_ty'. simpl. apply subst_eq_ty. assumption. \nQed. \n\n(* Proof written by hand. *)\nInstance AsimplCompCongr'_ty (sigma_ty theta_ty: index -> ty)\n(tau_ty tau: subst_of subst_of_ty)\n(E_ty: AsimplSubst_ty (tau) tau_ty)\n(E_ty': AsimplComp sigma_ty (subst_ty tau_ty) theta_ty) : AsimplComp (subst_ty sigma_ty) (subst_ty tau) (subst_ty theta_ty).\nProof.\n  intros s. simpl.\n  erewrite AsimplInstInst_ty.\n  - reflexivity.\n  - intros x. reflexivity.\n  - intros t. rewrite <- E_ty'. apply subst_eq_ty. assumption.  \n  - reflexivity. \nQed. \n    \nInstance AsimplRefl_ty (s: ty) : Asimpl s s | 100.\nProof. reflexivity. Qed.\n\nInstance AsimplGenComp_ty (sigma sigma': index -> ty)\n(tau tau': subst_of subst_of_ty)\n(theta: index -> ty)\n(E: AsimplGen sigma sigma')\n(E': AsimplSubst_ty tau tau')\n(E'': AsimplComp sigma' (subst_ty tau') theta) : AsimplGen (sigma >>> (subst_ty tau) ) theta.\nProof. intros x. rewrite <- E''. simpl. rewrite E. now apply subst_eq_ty. Qed.\n\n(* Proof *and statement* written by hand. *)\nLemma up_ren_up (xi : ren) (sigma : index -> ty) (E : (xi >>> var_ty) == sigma) :\n  (upren_ty_ty xi >>> var_ty) == up_ty_ty sigma. \nProof.\n  intros [|x].\n  - reflexivity.\n  - simpl. unfold compren_ty. rewrite <- E. reflexivity.\nQed.\n  \n(* Proof *and statement* written by hand. *)\nLemma ren_inst_ty (xi : ren) (sigma : index -> ty) (s : ty) (E : (xi >>> var_ty) == sigma) :\n  ren_ty xi s = s.[sigma].\nProof.\n  revert xi sigma E. induction s; intros xi sigma E.\n  - apply E.\n  - simpl. rewrite (IHs1 _ _ E). rewrite (IHs2 _ _ E). reflexivity.\n  - simpl. rewrite IHs with (sigma := up_ty_ty sigma).\n    + reflexivity. \n    + apply up_ren_up. assumption. \nQed.\n\n(* Proof written by hand. *)\nInstance AsimplSubstUp_ty_ty (sigma_ty tau_ty: index -> ty)\n         (E_ty: AsimplGen (var_ty 0 .: sigma_ty >>> (subst_ty ((S >>> var_ty)))) tau_ty) : AsimplSubst_ty (up_ty_ty sigma_ty) tau_ty.\nProof.\n  unfold up_ty_ty. intros x. rewrite <- E_ty.\n  simpl. destruct x.\n  - reflexivity.\n  - simpl. unfold compren_ty. erewrite ren_inst_ty. reflexivity. reflexivity. \nQed. \n\nTypeclasses Opaque toVar_ty.\n\nInductive tm  : Type :=\n  \n  | app : tm -> tm -> tm\n  | tapp : tm -> ty -> tm\n  | vt : vl -> tm\n with vl  : Type :=\n  | var_vl : index -> vl\n  | lam : ty -> tm -> vl\n  | tlam : tm -> vl.\n\nDefinition congr_app {s0 s1 t0 t1: tm} (E0: s0 = t0) (E1: s1 = t1) : app s0 s1 = app t0 t1 :=\n  apc (ap app E0) (E1).\n\nDefinition congr_tapp {s0: tm} {s1: ty} {t0: tm} {t1: ty} (E0: s0 = t0) (E1: s1 = t1) : tapp s0 s1 = tapp t0 t1 :=\n  apc (ap tapp E0) (E1).\n\nDefinition congr_vt {s0 t0: vl} (E0: s0 = t0) : vt s0 = vt t0 :=\n  ap vt E0.\n\nDefinition congr_lam {s0: ty} {s1: tm} {t0: ty} {t1: tm} (E0: s0 = t0) (E1: s1 = t1) : lam s0 s1 = lam t0 t1 :=\n  apc (ap lam E0) (E1).\n\nDefinition congr_tlam {s0 t0: tm} (E0: s0 = t0) : tlam s0 = tlam t0 :=\n  ap tlam E0.\n\nDefinition subst_of_tm  : list Type :=\n  [ty: Type;vl: Type].\n\nDefinition subst_of_vl  : list Type :=\n  [ty: Type;vl: Type].\n\nDefinition toVarRen_tm (xi: ren_of subst_of_tm) : _ :=\n  let (_, _) := xi in xi.\n\nDefinition toVarRen_vl (xi: ren_of subst_of_vl) : _ :=\n  let (_, xi) := xi in xi.\n\nDefinition castren_tm_ty (xi: ren_of subst_of_tm) : ren_of subst_of_ty :=\n  let (xi_ty, _) := xi in xi_ty.\n\nDefinition castren_tm_vl (xi: ren_of subst_of_tm) : ren_of subst_of_vl :=\n  let (xi_ty, xi_vl) := xi in (xi_ty, xi_vl).\n\nDefinition castren_vl_ty (xi: ren_of subst_of_vl) : ren_of subst_of_ty :=\n  let (xi_ty, _) := xi in xi_ty.\n\nDefinition castren_vl_tm (xi: ren_of subst_of_vl) : ren_of subst_of_tm :=\n  let (xi_ty, xi_vl) := xi in (xi_ty, xi_vl).\n\nDefinition upren_tm_ty (xi: ren_of subst_of_tm) : ren_of subst_of_tm :=\n  let (xi_ty, xi_vl) := xi in (up_ren xi_ty, xi_vl).\n\nDefinition upren_tm_vl (xi: ren_of subst_of_tm) : ren_of subst_of_tm :=\n  let (xi_ty, xi_vl) := xi in (xi_ty, up_ren xi_vl).\n\nDefinition upren_vl_ty (xi: ren_of subst_of_vl) : ren_of subst_of_vl :=\n  let (xi_ty, xi_vl) := xi in (up_ren xi_ty, xi_vl).\n\nDefinition upren_vl_vl (xi: ren_of subst_of_vl) : ren_of subst_of_vl :=\n  let (xi_ty, xi_vl) := xi in (xi_ty, up_ren xi_vl).\n\nFixpoint ren_tm (xi: ren_of subst_of_tm) (s: tm) : tm :=\n  match s with\n  \n  | app s0 s1 => app ((ren_tm xi s0)) ((ren_tm xi s1))\n  | tapp s0 s1 => tapp ((ren_tm xi s0)) ((ren_ty (castren_tm_ty xi) s1))\n  | vt s0 => vt ((ren_vl (castren_tm_vl xi) s0))\n  end\n with ren_vl (xi: ren_of subst_of_vl) (s: vl) : vl :=\n  match s with\n  | var_vl x => var_vl ((toVarRen_vl xi) x)\n  | lam s0 s1 => lam ((ren_ty (castren_vl_ty xi) s0)) ((ren_tm (upren_vl_vl (castren_vl_tm xi)) s1))\n  | tlam s0 => tlam ((ren_tm (upren_vl_ty (castren_vl_tm xi)) s0))\n  end.\n\nDefinition toVar_tm (sigma: subst_of subst_of_tm) : _ :=\n  let (_, _) := sigma in sigma.\n\nDefinition toVar_vl (sigma: subst_of subst_of_vl) : _ :=\n  let (_, sigma) := sigma in sigma.\n\n\n\nDefinition eq_toVar_vl {sigma tau: subst_of subst_of_vl} (E: eq_of_subst sigma tau) (n: index) : toVar_vl sigma n = toVar_vl tau n.\n  destruct sigma as (sigma_ty & sigma_vl). destruct tau as (tau_ty & tau_vl). destruct E as (E_ty & E_vl).\n  exact (E_vl n).\nDefined.\n\nDefinition compren_tm (sigma: subst_of subst_of_tm) (xi: ren_of subst_of_tm) : subst_of subst_of_tm :=\n  match sigma with\n  | (sigma_ty, sigma_vl) => (fun x => ren_ty (castren_tm_ty xi) (sigma_ty x), fun x => ren_vl (castren_tm_vl xi) (sigma_vl x))\n  end.\n\nDefinition compren_vl (sigma: subst_of subst_of_vl) (xi: ren_of subst_of_vl) : subst_of subst_of_vl :=\n  match sigma with\n  | (sigma_ty, sigma_vl) => (fun x => ren_ty (castren_vl_ty xi) (sigma_ty x), fun x => ren_vl xi (sigma_vl x))\n  end.\n\nDefinition up_tm_ty (sigma: subst_of subst_of_tm) : subst_of subst_of_tm :=\n  match compren_tm sigma (S, idren) with\n  | (sigma_ty, sigma_vl) => (scons (var_ty 0) sigma_ty, sigma_vl)\n  end.\n\nDefinition up_tm_vl (sigma: subst_of subst_of_tm) : subst_of subst_of_tm :=\n  match compren_tm sigma (idren, S) with\n  | (sigma_ty, sigma_vl) => (sigma_ty, scons (var_vl 0) sigma_vl)\n  end.\n\nDefinition up_vl_ty (sigma: subst_of subst_of_vl) : subst_of subst_of_vl :=\n  match compren_vl sigma (S, idren) with\n  | (sigma_ty, sigma_vl) => (scons (var_ty 0) sigma_ty, sigma_vl)\n  end.\n\nDefinition up_vl_vl (sigma: subst_of subst_of_vl) : subst_of subst_of_vl :=\n  match compren_vl sigma (idren, S) with\n  | (sigma_ty, sigma_vl) => (sigma_ty, scons (var_vl 0) sigma_vl)\n  end.\n\nDefinition cast_tm_ty (sigma: subst_of subst_of_tm) : subst_of subst_of_ty :=\n  let (sigma_ty, _) := sigma in sigma_ty.\n\nDefinition cast_tm_vl (sigma: subst_of subst_of_tm) : subst_of subst_of_vl :=\n  let (sigma_ty, sigma_vl) := sigma in (sigma_ty, sigma_vl).\n\nDefinition cast_vl_ty (sigma: subst_of subst_of_vl) : subst_of subst_of_ty :=\n  let (sigma_ty, _) := sigma in sigma_ty.\n\nDefinition cast_vl_tm (sigma: subst_of subst_of_vl) : subst_of subst_of_tm :=\n  let (sigma_ty, sigma_vl) := sigma in (sigma_ty, sigma_vl).\n\nDefinition eq_cast_tm_ty {sigma tau: subst_of subst_of_tm} (E: eq_of_subst sigma tau) : eq_of_subst (cast_tm_ty sigma) (cast_tm_ty tau).\n  destruct sigma as (sigma_ty & sigma_vl). destruct tau as (tau_ty & tau_vl). destruct E as (E_ty & E_vl).\n  exact (E_ty).\nDefined.\n\nDefinition eq_cast_tm_vl {sigma tau: subst_of subst_of_tm} (E: eq_of_subst sigma tau) : eq_of_subst (cast_tm_vl sigma) (cast_tm_vl tau).\n  destruct sigma as (sigma_ty & sigma_vl). destruct tau as (tau_ty & tau_vl). destruct E as (E_ty & E_vl).\n  exact (conj (E_ty) (E_vl)).\nDefined.\n\nDefinition eq_cast_vl_ty {sigma tau: subst_of subst_of_vl} (E: eq_of_subst sigma tau) : eq_of_subst (cast_vl_ty sigma) (cast_vl_ty tau).\n  destruct sigma as (sigma_ty & sigma_vl). destruct tau as (tau_ty & tau_vl). destruct E as (E_ty & E_vl).\n  exact (E_ty).\nDefined.\n\nDefinition eq_cast_vl_tm {sigma tau: subst_of subst_of_vl} (E: eq_of_subst sigma tau) : eq_of_subst (cast_vl_tm sigma) (cast_vl_tm tau).\n  destruct sigma as (sigma_ty & sigma_vl). destruct tau as (tau_ty & tau_vl). destruct E as (E_ty & E_vl).\n  exact (conj (E_ty) (E_vl)).\nDefined.\n\nFixpoint subst_tm (sigma: subst_of subst_of_tm) (s: tm) : tm :=\n  match s with\n  \n  | app s0 s1 => app ((subst_tm sigma s0)) ((subst_tm sigma s1))\n  | tapp s0 s1 => tapp ((subst_tm sigma s0)) ((subst_ty (cast_tm_ty sigma) s1))\n  | vt s0 => vt ((subst_vl (cast_tm_vl sigma) s0))\n  end\n with subst_vl (sigma: subst_of subst_of_vl) (s: vl) : vl :=\n  match s with\n  | var_vl x =>  ((toVar_vl sigma) x)\n  | lam s0 s1 => lam ((subst_ty (cast_vl_ty sigma) s0)) ((subst_tm (up_vl_vl (cast_vl_tm sigma)) s1))\n  | tlam s0 => tlam ((subst_tm (up_vl_ty (cast_vl_tm sigma)) s0))\n  end.\n\nDefinition comp_tm (sigma tau: subst_of subst_of_tm) : subst_of subst_of_tm :=\n  match sigma with\n  | (sigma_ty, sigma_vl) => (fun x => subst_ty (cast_tm_ty tau) (sigma_ty x), fun x => subst_vl (cast_tm_vl tau) (sigma_vl x))\n  end.\n\nDefinition comp_vl (sigma tau: subst_of subst_of_vl) : subst_of subst_of_vl :=\n  match sigma with\n  | (sigma_ty, sigma_vl) => (fun x => subst_ty (cast_vl_ty tau) (sigma_ty x), fun x => subst_vl tau (sigma_vl x))\n  end.\n\nDefinition substMixin_tm  : substMixin tm :=\n  {|subst_of_substType := subst_of_tm;inst_of_substType := subst_tm|}.\n\nDefinition substMixin_vl  : substMixin vl :=\n  {|subst_of_substType := subst_of_vl;inst_of_substType := subst_vl|}.\n\nCanonical Structure substType_tm  : substType :=\n  Eval hnf in @Pack tm substMixin_tm tm.\n\nCanonical Structure substType_vl  : substType :=\n  Eval hnf in @Pack vl substMixin_vl vl.\n\nDefinition upId_tm_ty (sigma_ty: index -> ty) (sigma_vl: index -> vl) (E_ty: sigma_ty == var_ty) (E_vl: sigma_vl == var_vl)\n  : @eq_of_subst subst_of_tm (up_tm_ty (sigma_ty, sigma_vl)) (var_ty, var_vl) :=\n  conj (fun n => match n return (match up_tm_ty (sigma_ty, sigma_vl) with\n  | (tau_ty, tau_vl) => tau_ty n = var_ty  n\n  end) with\n  | 0 => eq_refl\n  | S n => ap (ren_ty (castren_tm_ty (S, idren))) (E_ty n)\n  end) (fun n => ap (ren_vl (castren_tm_vl (S, idren))) (E_vl n)).\n\nDefinition upId_tm_vl (sigma_ty: index -> ty) (sigma_vl: index -> vl) (E_ty: sigma_ty == var_ty) (E_vl: sigma_vl == var_vl)\n  : @eq_of_subst subst_of_tm (up_tm_vl (sigma_ty, sigma_vl)) (var_ty, var_vl) :=\n  conj (fun n => ap (ren_ty (castren_tm_ty (idren, S))) (E_ty n)) (fun n => match n return (match up_tm_vl (sigma_ty, sigma_vl) with\n  | (tau_ty, tau_vl) => tau_vl n = var_vl  n\n  end) with\n  | 0 => eq_refl\n  | S n => ap (ren_vl (castren_tm_vl (idren, S))) (E_vl n)\n  end).\n\nDefinition upId_vl_ty (sigma_ty: index -> ty) (sigma_vl: index -> vl) (E_ty: sigma_ty == var_ty) (E_vl: sigma_vl == var_vl)\n  : @eq_of_subst subst_of_vl (up_vl_ty (sigma_ty, sigma_vl)) (var_ty, var_vl) :=\n  conj (fun n => match n return (match up_vl_ty (sigma_ty, sigma_vl) with\n  | (tau_ty, tau_vl) => tau_ty n = var_ty  n\n  end) with\n  | 0 => eq_refl\n  | S n => ap (ren_ty (castren_vl_ty (S, idren))) (E_ty n)\n  end) (fun n => ap (ren_vl (S, idren)) (E_vl n)).\n\nDefinition upId_vl_vl (sigma_ty: index -> ty) (sigma_vl: index -> vl) (E_ty: sigma_ty == var_ty) (E_vl: sigma_vl == var_vl)\n  : @eq_of_subst subst_of_vl (up_vl_vl (sigma_ty, sigma_vl)) (var_ty, var_vl) :=\n  conj (fun n => ap (ren_ty (castren_vl_ty (idren, S))) (E_ty n)) (fun n => match n return (match up_vl_vl (sigma_ty, sigma_vl) with\n  | (tau_ty, tau_vl) => tau_vl n = var_vl  n\n  end) with\n  | 0 => eq_refl\n  | S n => ap (ren_vl (idren, S)) (E_vl n)\n  end).\n\nFixpoint id_tm (sigma_ty: index -> ty) (sigma_vl: index -> vl) (E_ty: sigma_ty == var_ty) (E_vl: sigma_vl == var_vl) (s: tm)\n           : subst_tm (sigma_ty, sigma_vl) s = s :=\n  match s with\n  \n  | app s0 s1 => apc (ap app (id_tm _ _ E_ty E_vl s0)) ((id_tm _ _ E_ty E_vl s1))\n  | tapp s0 s1 => apc (ap tapp (id_tm _ _ E_ty E_vl s0)) ((id_ty _ E_ty s1))\n  | vt s0 => ap vt (id_vl _ _ E_ty E_vl s0)\n  end\n with id_vl (sigma_ty: index -> ty) (sigma_vl: index -> vl) (E_ty: sigma_ty == var_ty) (E_vl: sigma_vl == var_vl) (s: vl)\n        : subst_vl (sigma_ty, sigma_vl) s = s :=\n  match s with\n  | var_vl n => E_vl n\n  | lam s0 s1 => apc (ap lam (id_ty _ E_ty s0)) ((match upId_tm_vl _ _ E_ty E_vl with\n      | conj (E_ty) (E_vl) => id_tm _ _ E_ty E_vl s1\n      end))\n  | tlam s0 => ap tlam (match upId_tm_ty _ _ E_ty E_vl with\n      | conj (E_ty) (E_vl) => id_tm _ _ E_ty E_vl s0\n      end)\n  end.\n\nDefinition toSubst_tm (xi: ren_of subst_of_tm) : subst_of subst_of_tm :=\n  match xi with\n  | (xi_ty, xi_vl) => (fun x => var_ty (xi_ty x), fun x => var_vl (xi_vl x))\n  end.\n\nDefinition toSubst_vl (xi: ren_of subst_of_vl) : subst_of subst_of_vl :=\n  match xi with\n  | (xi_ty, xi_vl) => (fun x => var_ty (xi_ty x), fun x => var_vl (xi_vl x))\n  end.\n\nFixpoint compTrans_ren_ren_tm (xi_ty xi_vl zeta_ty zeta_vl theta_ty theta_vl: ren)\n           (E_ty: funcomp (xi_ty) (zeta_ty) == theta_ty)\n           (E_vl: funcomp (xi_vl) (zeta_vl) == theta_vl)\n           (s: tm) : ren_tm (zeta_ty, zeta_vl) (ren_tm (xi_ty, xi_vl) s) = ren_tm (theta_ty, theta_vl) s :=\n  match s with\n  \n  | app s0 s1 =>\n      apc (ap app (compTrans_ren_ren_tm xi_ty xi_vl zeta_ty zeta_vl theta_ty theta_vl E_ty E_vl s0)) ((compTrans_ren_ren_tm xi_ty xi_vl zeta_ty zeta_vl theta_ty theta_vl E_ty E_vl s1))\n  | tapp s0 s1 =>\n      apc (ap tapp (compTrans_ren_ren_tm xi_ty xi_vl zeta_ty zeta_vl theta_ty theta_vl E_ty E_vl s0)) ((compTrans_ren_ren_ty xi_ty zeta_ty theta_ty E_ty s1))\n  | vt s0 => ap vt (compTrans_ren_ren_vl xi_ty xi_vl zeta_ty zeta_vl theta_ty theta_vl E_ty E_vl s0)\n  end\n with compTrans_ren_ren_vl (xi_ty xi_vl zeta_ty zeta_vl theta_ty theta_vl: ren)\n        (E_ty: funcomp (xi_ty) (zeta_ty) == theta_ty)\n        (E_vl: funcomp (xi_vl) (zeta_vl) == theta_vl)\n        (s: vl) : ren_vl (zeta_ty, zeta_vl) (ren_vl (xi_ty, xi_vl) s) = ren_vl (theta_ty, theta_vl) s :=\n  match s with\n  | var_vl n => ap var_vl (E_vl n)\n  | lam s0 s1 =>\n      apc (ap lam (compTrans_ren_ren_ty xi_ty zeta_ty theta_ty E_ty s0)) ((compTrans_ren_ren_tm xi_ty (up_ren xi_vl) zeta_ty (up_ren zeta_vl) theta_ty (up_ren theta_vl) E_ty (up_ren_ren xi_vl zeta_vl theta_vl E_vl) s1))\n  | tlam s0 =>\n      ap tlam (compTrans_ren_ren_tm (up_ren xi_ty) xi_vl (up_ren zeta_ty) zeta_vl (up_ren theta_ty) theta_vl (up_ren_ren xi_ty zeta_ty theta_ty E_ty) E_vl s0)\n  end.\n\nDefinition compE_ren_ren_tm (xi_ty xi_vl zeta_ty zeta_vl: ren) (s: tm) : ren_tm (zeta_ty, zeta_vl) (ren_tm (xi_ty\n                                                                                                           , xi_vl) s) = ren_tm ((funcomp xi_ty zeta_ty)\n                                                                                                                                , (funcomp xi_vl zeta_vl)) s :=\n  compTrans_ren_ren_tm xi_ty xi_vl zeta_ty zeta_vl (funcomp xi_ty zeta_ty) (funcomp xi_vl zeta_vl) (fun _ => eq_refl) (fun _ => eq_refl) s.\n\nDefinition compE_ren_ren_vl (xi_ty xi_vl zeta_ty zeta_vl: ren) (s: vl) : ren_vl (zeta_ty, zeta_vl) (ren_vl (xi_ty\n                                                                                                           , xi_vl) s) = ren_vl ((funcomp xi_ty zeta_ty)\n                                                                                                                                , (funcomp xi_vl zeta_vl)) s :=\n  compTrans_ren_ren_vl xi_ty xi_vl zeta_ty zeta_vl (funcomp xi_ty zeta_ty) (funcomp xi_vl zeta_vl) (fun _ => eq_refl) (fun _ => eq_refl) s.\n\nDefinition up_ren_subst_tm_ty (xi_ty xi_vl: ren)\n  (theta_ty: index -> ty)\n  (theta_vl: index -> vl)\n  (tau_ty: index -> ty)\n  (tau_vl: index -> vl)\n  (E_ty: (fun x =>  theta_ty (xi_ty x)) == tau_ty)\n  (E_vl: (fun x =>  theta_vl (xi_vl x)) == tau_vl) : @eq_of_subst subst_of_tm (comp_tm (toSubst_tm (upren_tm_ty (xi_ty\n                                                                                                                , xi_vl))) (up_tm_ty (theta_ty\n                                                                                                                                     , theta_vl))) (up_tm_ty (tau_ty\n                                                                                                                                                             , tau_vl)) :=\n  conj (fun n => match n return match comp_tm (toSubst_tm (upren_tm_ty (xi_ty, xi_vl))) (up_tm_ty (theta_ty, theta_vl)), up_tm_ty (tau_ty\n                                                                                                                                  , tau_vl) with\n  | (xi_ty, xi_vl), (tau_ty, tau_vl) => xi_ty n = tau_ty n\n  end with\n  | 0 => eq_refl\n  | S n => ap (ren_ty (castren_tm_ty (S, idren))) (E_ty n)\n  end) (fun n => ap (ren_vl (castren_tm_vl (S, idren))) (E_vl n)).\n\nDefinition up_ren_subst_tm_vl (xi_ty xi_vl: ren)\n  (theta_ty: index -> ty)\n  (theta_vl: index -> vl)\n  (tau_ty: index -> ty)\n  (tau_vl: index -> vl)\n  (E_ty: (fun x =>  theta_ty (xi_ty x)) == tau_ty)\n  (E_vl: (fun x =>  theta_vl (xi_vl x)) == tau_vl) : @eq_of_subst subst_of_tm (comp_tm (toSubst_tm (upren_tm_vl (xi_ty\n                                                                                                                , xi_vl))) (up_tm_vl (theta_ty\n                                                                                                                                     , theta_vl))) (up_tm_vl (tau_ty\n                                                                                                                                                             , tau_vl)) :=\n  conj (fun n => ap (ren_ty (castren_tm_ty (idren, S))) (E_ty n)) (fun n => match n return match comp_tm (toSubst_tm (upren_tm_vl (xi_ty\n                                                                                                                                  , xi_vl))) (up_tm_vl (theta_ty\n                                                                                                                                                       , theta_vl)), up_tm_vl (tau_ty\n                                                                                                                                                                              , tau_vl) with\n  | (xi_ty, xi_vl), (tau_ty, tau_vl) => xi_vl n = tau_vl n\n  end with\n  | 0 => eq_refl\n  | S n => ap (ren_vl (castren_tm_vl (idren, S))) (E_vl n)\n  end).\n\nDefinition up_ren_subst_vl_ty (xi_ty xi_vl: ren)\n  (theta_ty: index -> ty)\n  (theta_vl: index -> vl)\n  (tau_ty: index -> ty)\n  (tau_vl: index -> vl)\n  (E_ty: (fun x =>  theta_ty (xi_ty x)) == tau_ty)\n  (E_vl: (fun x =>  theta_vl (xi_vl x)) == tau_vl) : @eq_of_subst subst_of_vl (comp_vl (toSubst_vl (upren_vl_ty (xi_ty\n                                                                                                                , xi_vl))) (up_vl_ty (theta_ty\n                                                                                                                                     , theta_vl))) (up_vl_ty (tau_ty\n                                                                                                                                                             , tau_vl)) :=\n  conj (fun n => match n return match comp_vl (toSubst_vl (upren_vl_ty (xi_ty, xi_vl))) (up_vl_ty (theta_ty, theta_vl)), up_vl_ty (tau_ty\n                                                                                                                                  , tau_vl) with\n  | (xi_ty, xi_vl), (tau_ty, tau_vl) => xi_ty n = tau_ty n\n  end with\n  | 0 => eq_refl\n  | S n => ap (ren_ty (castren_vl_ty (S, idren))) (E_ty n)\n  end) (fun n => ap (ren_vl (S, idren)) (E_vl n)).\n\nDefinition up_ren_subst_vl_vl (xi_ty xi_vl: ren)\n  (theta_ty: index -> ty)\n  (theta_vl: index -> vl)\n  (tau_ty: index -> ty)\n  (tau_vl: index -> vl)\n  (E_ty: (fun x =>  theta_ty (xi_ty x)) == tau_ty)\n  (E_vl: (fun x =>  theta_vl (xi_vl x)) == tau_vl) : @eq_of_subst subst_of_vl (comp_vl (toSubst_vl (upren_vl_vl (xi_ty\n                                                                                                                , xi_vl))) (up_vl_vl (theta_ty\n                                                                                                                                     , theta_vl))) (up_vl_vl (tau_ty\n                                                                                                                                                             , tau_vl)) :=\n  conj (fun n => ap (ren_ty (castren_vl_ty (idren, S))) (E_ty n)) (fun n => match n return match comp_vl (toSubst_vl (upren_vl_vl (xi_ty\n                                                                                                                                  , xi_vl))) (up_vl_vl (theta_ty\n                                                                                                                                                       , theta_vl)), up_vl_vl (tau_ty\n                                                                                                                                                                              , tau_vl) with\n  | (xi_ty, xi_vl), (tau_ty, tau_vl) => xi_vl n = tau_vl n\n  end with\n  | 0 => eq_refl\n  | S n => ap (ren_vl (idren, S)) (E_vl n)\n  end).\n\nFixpoint compTrans_ren_subst_tm (xi_ty xi_vl: ren)\n           (tau_ty: index -> ty)\n           (tau_vl: index -> vl)\n           (theta_ty: index -> ty)\n           (theta_vl: index -> vl)\n           (E_ty: (fun x =>  tau_ty (xi_ty x)) == theta_ty)\n           (E_vl: (fun x =>  tau_vl (xi_vl x)) == theta_vl)\n           (s: tm) : subst_tm (tau_ty, tau_vl) (ren_tm (xi_ty, xi_vl) s) = subst_tm (theta_ty, theta_vl) s :=\n  match s with\n  \n  | app s0 s1 =>\n      apc (ap app (compTrans_ren_subst_tm xi_ty xi_vl _ _ _ _ E_ty E_vl s0)) ((compTrans_ren_subst_tm xi_ty xi_vl _ _ _ _ E_ty E_vl s1))\n  | tapp s0 s1 => apc (ap tapp (compTrans_ren_subst_tm xi_ty xi_vl _ _ _ _ E_ty E_vl s0)) ((compTrans_ren_subst_ty xi_ty _ _ E_ty s1))\n  | vt s0 => ap vt (compTrans_ren_subst_vl xi_ty xi_vl _ _ _ _ E_ty E_vl s0)\n  end\n with compTrans_ren_subst_vl (xi_ty xi_vl: ren)\n        (tau_ty: index -> ty)\n        (tau_vl: index -> vl)\n        (theta_ty: index -> ty)\n        (theta_vl: index -> vl)\n        (E_ty: (fun x =>  tau_ty (xi_ty x)) == theta_ty)\n        (E_vl: (fun x =>  tau_vl (xi_vl x)) == theta_vl)\n        (s: vl) : subst_vl (tau_ty, tau_vl) (ren_vl (xi_ty, xi_vl) s) = subst_vl (theta_ty, theta_vl) s :=\n  match s with\n  | var_vl n =>  (E_vl n)\n  | lam s0 s1 =>\n      apc (ap lam (compTrans_ren_subst_ty xi_ty _ _ E_ty s0)) ((match up_ren_subst_vl_vl xi_ty xi_vl tau_ty tau_vl theta_ty theta_vl E_ty E_vl with\n      | conj (E_ty) (E_vl) => compTrans_ren_subst_tm xi_ty (up_ren xi_vl) _ _ _ _ E_ty E_vl s1\n      end))\n  | tlam s0 => ap tlam (match up_ren_subst_vl_ty xi_ty xi_vl tau_ty tau_vl theta_ty theta_vl E_ty E_vl with\n      | conj (E_ty) (E_vl) => compTrans_ren_subst_tm (up_ren xi_ty) xi_vl _ _ _ _ E_ty E_vl s0\n      end)\n  end.\n\nDefinition compE_ren_subst_tm (xi_ty xi_vl: ren) (tau_ty: index -> ty) (tau_vl: index -> vl) (s: tm) : subst_tm (tau_ty\n                                                                                                                , tau_vl) (ren_tm (xi_ty\n                                                                                                                                  , xi_vl) s) = subst_tm ((funcomp xi_ty tau_ty)\n                                                                                                                                                         , (funcomp xi_vl tau_vl)) s :=\n  compTrans_ren_subst_tm xi_ty xi_vl tau_ty tau_vl (funcomp xi_ty tau_ty) (funcomp xi_vl tau_vl) (fun _ => eq_refl) (fun _ => eq_refl) s.\n\nDefinition compE_ren_subst_vl (xi_ty xi_vl: ren) (tau_ty: index -> ty) (tau_vl: index -> vl) (s: vl) : subst_vl (tau_ty\n                                                                                                                , tau_vl) (ren_vl (xi_ty\n                                                                                                                                  , xi_vl) s) = subst_vl ((funcomp xi_ty tau_ty)\n                                                                                                                                                         , (funcomp xi_vl tau_vl)) s :=\n  compTrans_ren_subst_vl xi_ty xi_vl tau_ty tau_vl (funcomp xi_ty tau_ty) (funcomp xi_vl tau_vl) (fun _ => eq_refl) (fun _ => eq_refl) s.\n\nDefinition up_subst_ren_tm_ty (sigma_ty: index -> ty)\n  (sigma_vl: index -> vl)\n  (rho_ty rho_vl: ren)\n  (tau_ty: index -> ty)\n  (tau_vl: index -> vl)\n  (E_ty: (fun x =>  ren_ty rho_ty (sigma_ty x)) == tau_ty)\n  (E_vl: (fun x =>  ren_vl (rho_ty, rho_vl) (sigma_vl x)) == tau_vl) : @eq_of_subst subst_of_tm (compren_tm (up_tm_ty (sigma_ty\n                                                                                                                      , sigma_vl)) (upren_tm_ty (rho_ty\n                                                                                                                                                , rho_vl))) (up_tm_ty (tau_ty\n                                                                                                                                                                      , tau_vl)) :=\n  conj (fun n => match n return match compren_tm (up_tm_ty (sigma_ty, sigma_vl)) (upren_tm_ty (rho_ty, rho_vl)), up_tm_ty (tau_ty\n                                                                                                                          , tau_vl) with\n  | (sigma_ty, sigma_vl), (tau_ty, tau_vl) => sigma_ty n = tau_ty n\n  end with\n  | 0 => eq_refl\n  | S n =>\n      eq_trans (compE_ren_ren_ty S (up_ren rho_ty) (sigma_ty n)) (eq_trans (eq_sym (compE_ren_ren_ty rho_ty S (sigma_ty n))) (ap (ren_ty S) (E_ty n)))\n  end) (fun n => eq_trans (compE_ren_ren_vl S idren (up_ren rho_ty) rho_vl (sigma_vl n)) (eq_trans (eq_sym (compE_ren_ren_vl rho_ty rho_vl S idren (sigma_vl n))) (ap (ren_vl (S\n                                                                                                                                                                              , idren)) (E_vl n)))).\n\nDefinition up_subst_ren_tm_vl (sigma_ty: index -> ty)\n  (sigma_vl: index -> vl)\n  (rho_ty rho_vl: ren)\n  (tau_ty: index -> ty)\n  (tau_vl: index -> vl)\n  (E_ty: (fun x =>  ren_ty rho_ty (sigma_ty x)) == tau_ty)\n  (E_vl: (fun x =>  ren_vl (rho_ty, rho_vl) (sigma_vl x)) == tau_vl) : @eq_of_subst subst_of_tm (compren_tm (up_tm_vl (sigma_ty\n                                                                                                                      , sigma_vl)) (upren_tm_vl (rho_ty\n                                                                                                                                                , rho_vl))) (up_tm_vl (tau_ty\n                                                                                                                                                                      , tau_vl)) :=\n  conj (fun n => eq_trans (compE_ren_ren_ty idren rho_ty (sigma_ty n)) (eq_trans (eq_sym (compE_ren_ren_ty rho_ty idren (sigma_ty n))) (ap (ren_ty idren) (E_ty n)))) (fun n => match n return match compren_tm (up_tm_vl (sigma_ty\n                                                                                                                                                                                                                          , sigma_vl)) (upren_tm_vl (rho_ty\n                                                                                                                                                                                                                                                    , rho_vl)), up_tm_vl (tau_ty\n                                                                                                                                                                                                                                                                         , tau_vl) with\n  | (sigma_ty, sigma_vl), (tau_ty, tau_vl) => sigma_vl n = tau_vl n\n  end with\n  | 0 => eq_refl\n  | S n =>\n      eq_trans (compE_ren_ren_vl idren S rho_ty (up_ren rho_vl) (sigma_vl n)) (eq_trans (eq_sym (compE_ren_ren_vl rho_ty rho_vl idren S (sigma_vl n))) (ap (ren_vl (idren\n                                                                                                                                                                   , S)) (E_vl n)))\n  end).\n\nDefinition up_subst_ren_vl_ty (sigma_ty: index -> ty)\n  (sigma_vl: index -> vl)\n  (rho_ty rho_vl: ren)\n  (tau_ty: index -> ty)\n  (tau_vl: index -> vl)\n  (E_ty: (fun x =>  ren_ty rho_ty (sigma_ty x)) == tau_ty)\n  (E_vl: (fun x =>  ren_vl (rho_ty, rho_vl) (sigma_vl x)) == tau_vl) : @eq_of_subst subst_of_vl (compren_vl (up_vl_ty (sigma_ty\n                                                                                                                      , sigma_vl)) (upren_vl_ty (rho_ty\n                                                                                                                                                , rho_vl))) (up_vl_ty (tau_ty\n                                                                                                                                                                      , tau_vl)) :=\n  conj (fun n => match n return match compren_vl (up_vl_ty (sigma_ty, sigma_vl)) (upren_vl_ty (rho_ty, rho_vl)), up_vl_ty (tau_ty\n                                                                                                                          , tau_vl) with\n  | (sigma_ty, sigma_vl), (tau_ty, tau_vl) => sigma_ty n = tau_ty n\n  end with\n  | 0 => eq_refl\n  | S n =>\n      eq_trans (compE_ren_ren_ty S (up_ren rho_ty) (sigma_ty n)) (eq_trans (eq_sym (compE_ren_ren_ty rho_ty S (sigma_ty n))) (ap (ren_ty S) (E_ty n)))\n  end) (fun n => eq_trans (compE_ren_ren_vl S idren (up_ren rho_ty) rho_vl (sigma_vl n)) (eq_trans (eq_sym (compE_ren_ren_vl rho_ty rho_vl S idren (sigma_vl n))) (ap (ren_vl (S\n                                                                                                                                                                              , idren)) (E_vl n)))).\n\nDefinition up_subst_ren_vl_vl (sigma_ty: index -> ty)\n  (sigma_vl: index -> vl)\n  (rho_ty rho_vl: ren)\n  (tau_ty: index -> ty)\n  (tau_vl: index -> vl)\n  (E_ty: (fun x =>  ren_ty rho_ty (sigma_ty x)) == tau_ty)\n  (E_vl: (fun x =>  ren_vl (rho_ty, rho_vl) (sigma_vl x)) == tau_vl) : @eq_of_subst subst_of_vl (compren_vl (up_vl_vl (sigma_ty\n                                                                                                                      , sigma_vl)) (upren_vl_vl (rho_ty\n                                                                                                                                                , rho_vl))) (up_vl_vl (tau_ty\n                                                                                                                                                                      , tau_vl)) :=\n  conj (fun n => eq_trans (compE_ren_ren_ty idren rho_ty (sigma_ty n)) (eq_trans (eq_sym (compE_ren_ren_ty rho_ty idren (sigma_ty n))) (ap (ren_ty idren) (E_ty n)))) (fun n => match n return match compren_vl (up_vl_vl (sigma_ty\n                                                                                                                                                                                                                          , sigma_vl)) (upren_vl_vl (rho_ty\n                                                                                                                                                                                                                                                    , rho_vl)), up_vl_vl (tau_ty\n                                                                                                                                                                                                                                                                         , tau_vl) with\n  | (sigma_ty, sigma_vl), (tau_ty, tau_vl) => sigma_vl n = tau_vl n\n  end with\n  | 0 => eq_refl\n  | S n =>\n      eq_trans (compE_ren_ren_vl idren S rho_ty (up_ren rho_vl) (sigma_vl n)) (eq_trans (eq_sym (compE_ren_ren_vl rho_ty rho_vl idren S (sigma_vl n))) (ap (ren_vl (idren\n                                                                                                                                                                   , S)) (E_vl n)))\n  end).\n\nFixpoint compTrans_subst_ren_tm (sigma_ty: index -> ty)\n           (sigma_vl: index -> vl)\n           (zeta_ty zeta_vl: ren)\n           (theta_ty: index -> ty)\n           (theta_vl: index -> vl)\n           (E_ty: (fun x =>  ren_ty zeta_ty (sigma_ty x)) == theta_ty)\n           (E_vl: (fun x =>  ren_vl (zeta_ty, zeta_vl) (sigma_vl x)) == theta_vl)\n           (s: tm) : ren_tm (zeta_ty, zeta_vl) (subst_tm (sigma_ty, sigma_vl) s) = subst_tm (theta_ty, theta_vl) s :=\n  match s with\n  \n  | app s0 s1 =>\n      apc (ap app (compTrans_subst_ren_tm _ _ zeta_ty zeta_vl _ _ E_ty E_vl s0)) ((compTrans_subst_ren_tm _ _ zeta_ty zeta_vl _ _ E_ty E_vl s1))\n  | tapp s0 s1 => apc (ap tapp (compTrans_subst_ren_tm _ _ zeta_ty zeta_vl _ _ E_ty E_vl s0)) ((compTrans_subst_ren_ty _ zeta_ty _ E_ty s1))\n  | vt s0 => ap vt (compTrans_subst_ren_vl _ _ zeta_ty zeta_vl _ _ E_ty E_vl s0)\n  end\n with compTrans_subst_ren_vl (sigma_ty: index -> ty)\n        (sigma_vl: index -> vl)\n        (zeta_ty zeta_vl: ren)\n        (theta_ty: index -> ty)\n        (theta_vl: index -> vl)\n        (E_ty: (fun x =>  ren_ty zeta_ty (sigma_ty x)) == theta_ty)\n        (E_vl: (fun x =>  ren_vl (zeta_ty, zeta_vl) (sigma_vl x)) == theta_vl)\n        (s: vl) : ren_vl (zeta_ty, zeta_vl) (subst_vl (sigma_ty, sigma_vl) s) = subst_vl (theta_ty, theta_vl) s :=\n  match s with\n  | var_vl n =>  (E_vl n)\n  | lam s0 s1 =>\n      apc (ap lam (compTrans_subst_ren_ty _ zeta_ty _ E_ty s0)) ((match up_subst_ren_vl_vl sigma_ty sigma_vl zeta_ty zeta_vl theta_ty theta_vl E_ty E_vl with\n      | conj (E_ty) (E_vl) => compTrans_subst_ren_tm _ _ zeta_ty (up_ren zeta_vl) _ _ E_ty E_vl s1\n      end))\n  | tlam s0 => ap tlam (match up_subst_ren_vl_ty sigma_ty sigma_vl zeta_ty zeta_vl theta_ty theta_vl E_ty E_vl with\n      | conj (E_ty) (E_vl) => compTrans_subst_ren_tm _ _ (up_ren zeta_ty) zeta_vl _ _ E_ty E_vl s0\n      end)\n  end.\n\nDefinition compE_subst_ren_tm (sigma_ty: index -> ty) (sigma_vl: index -> vl) (zeta_ty zeta_vl: ren) (s: tm) : ren_tm (zeta_ty\n                                                                                                                      , zeta_vl) (subst_tm (sigma_ty\n                                                                                                                                           , sigma_vl) s) = subst_tm ((fun n => ren_ty (zeta_ty) (sigma_ty n))\n                                                                                                                                                                     , (fun n => ren_vl ((zeta_ty\n                                                                                                                                                                                         , zeta_vl)) (sigma_vl n))) s :=\n  compTrans_subst_ren_tm sigma_ty sigma_vl zeta_ty zeta_vl (fun n => ren_ty (zeta_ty) (sigma_ty n)) (fun n => ren_vl ((zeta_ty\n                                                                                                                      , zeta_vl)) (sigma_vl n)) (fun _ => eq_refl) (fun _ => eq_refl) s.\n\nDefinition compE_subst_ren_vl (sigma_ty: index -> ty) (sigma_vl: index -> vl) (zeta_ty zeta_vl: ren) (s: vl) : ren_vl (zeta_ty\n                                                                                                                      , zeta_vl) (subst_vl (sigma_ty\n                                                                                                                                           , sigma_vl) s) = subst_vl ((fun n => ren_ty (zeta_ty) (sigma_ty n))\n                                                                                                                                                                     , (fun n => ren_vl ((zeta_ty\n                                                                                                                                                                                         , zeta_vl)) (sigma_vl n))) s :=\n  compTrans_subst_ren_vl sigma_ty sigma_vl zeta_ty zeta_vl (fun n => ren_ty (zeta_ty) (sigma_ty n)) (fun n => ren_vl ((zeta_ty\n                                                                                                                      , zeta_vl)) (sigma_vl n)) (fun _ => eq_refl) (fun _ => eq_refl) s.\n\nDefinition up_subst_subst_tm_ty (sigma_ty: index -> ty)\n  (sigma_vl: index -> vl)\n  (theta_ty: index -> ty)\n  (theta_vl: index -> vl)\n  (tau_ty: index -> ty)\n  (tau_vl: index -> vl)\n  (E_ty: (fun x =>  subst_ty theta_ty (sigma_ty x)) == tau_ty)\n  (E_vl: (fun x =>  subst_vl (theta_ty, theta_vl) (sigma_vl x)) == tau_vl) : @eq_of_subst subst_of_tm (comp_tm (up_tm_ty (sigma_ty\n                                                                                                                         , sigma_vl)) (up_tm_ty (theta_ty\n                                                                                                                                                , theta_vl))) (up_tm_ty (tau_ty\n                                                                                                                                                                        , tau_vl)) :=\n  conj (fun n => match n return match comp_tm (up_tm_ty (sigma_ty, sigma_vl)) (up_tm_ty (theta_ty, theta_vl)), up_tm_ty (tau_ty\n                                                                                                                        , tau_vl) with\n  | (sigma_ty, sigma_vl), (tau_ty, tau_vl) => sigma_ty n = tau_ty n\n  end with\n  | 0 => eq_refl\n  | S n =>\n      eq_trans (compE_ren_subst_ty S _ (sigma_ty n)) (eq_trans (eq_sym (compE_subst_ren_ty theta_ty S (sigma_ty n))) (ap (ren_ty S) (E_ty n)))\n  end) (fun n => eq_trans (compE_ren_subst_vl S idren _ _ (sigma_vl n)) (eq_trans (eq_sym (compE_subst_ren_vl theta_ty theta_vl S idren (sigma_vl n))) (ap (ren_vl (S\n                                                                                                                                                                   , idren)) (E_vl n)))).\n\nDefinition up_subst_subst_tm_vl (sigma_ty: index -> ty)\n  (sigma_vl: index -> vl)\n  (theta_ty: index -> ty)\n  (theta_vl: index -> vl)\n  (tau_ty: index -> ty)\n  (tau_vl: index -> vl)\n  (E_ty: (fun x =>  subst_ty theta_ty (sigma_ty x)) == tau_ty)\n  (E_vl: (fun x =>  subst_vl (theta_ty, theta_vl) (sigma_vl x)) == tau_vl) : @eq_of_subst subst_of_tm (comp_tm (up_tm_vl (sigma_ty\n                                                                                                                         , sigma_vl)) (up_tm_vl (theta_ty\n                                                                                                                                                , theta_vl))) (up_tm_vl (tau_ty\n                                                                                                                                                                        , tau_vl)) :=\n  conj (fun n => eq_trans (compE_ren_subst_ty idren _ (sigma_ty n)) (eq_trans (eq_sym (compE_subst_ren_ty theta_ty idren (sigma_ty n))) (ap (ren_ty idren) (E_ty n)))) (fun n => match n return match comp_tm (up_tm_vl (sigma_ty\n                                                                                                                                                                                                                        , sigma_vl)) (up_tm_vl (theta_ty\n                                                                                                                                                                                                                                               , theta_vl)), up_tm_vl (tau_ty\n                                                                                                                                                                                                                                                                      , tau_vl) with\n  | (sigma_ty, sigma_vl), (tau_ty, tau_vl) => sigma_vl n = tau_vl n\n  end with\n  | 0 => eq_refl\n  | S n =>\n      eq_trans (compE_ren_subst_vl idren S _ _ (sigma_vl n)) (eq_trans (eq_sym (compE_subst_ren_vl theta_ty theta_vl idren S (sigma_vl n))) (ap (ren_vl (idren\n                                                                                                                                                        , S)) (E_vl n)))\n  end).\n\nDefinition up_subst_subst_vl_ty (sigma_ty: index -> ty)\n  (sigma_vl: index -> vl)\n  (theta_ty: index -> ty)\n  (theta_vl: index -> vl)\n  (tau_ty: index -> ty)\n  (tau_vl: index -> vl)\n  (E_ty: (fun x =>  subst_ty theta_ty (sigma_ty x)) == tau_ty)\n  (E_vl: (fun x =>  subst_vl (theta_ty, theta_vl) (sigma_vl x)) == tau_vl) : @eq_of_subst subst_of_vl (comp_vl (up_vl_ty (sigma_ty\n                                                                                                                         , sigma_vl)) (up_vl_ty (theta_ty\n                                                                                                                                                , theta_vl))) (up_vl_ty (tau_ty\n                                                                                                                                                                        , tau_vl)) :=\n  conj (fun n => match n return match comp_vl (up_vl_ty (sigma_ty, sigma_vl)) (up_vl_ty (theta_ty, theta_vl)), up_vl_ty (tau_ty\n                                                                                                                        , tau_vl) with\n  | (sigma_ty, sigma_vl), (tau_ty, tau_vl) => sigma_ty n = tau_ty n\n  end with\n  | 0 => eq_refl\n  | S n =>\n      eq_trans (compE_ren_subst_ty S _ (sigma_ty n)) (eq_trans (eq_sym (compE_subst_ren_ty theta_ty S (sigma_ty n))) (ap (ren_ty S) (E_ty n)))\n  end) (fun n => eq_trans (compE_ren_subst_vl S idren _ _ (sigma_vl n)) (eq_trans (eq_sym (compE_subst_ren_vl theta_ty theta_vl S idren (sigma_vl n))) (ap (ren_vl (S\n                                                                                                                                                                   , idren)) (E_vl n)))).\n\nDefinition up_subst_subst_vl_vl (sigma_ty: index -> ty)\n  (sigma_vl: index -> vl)\n  (theta_ty: index -> ty)\n  (theta_vl: index -> vl)\n  (tau_ty: index -> ty)\n  (tau_vl: index -> vl)\n  (E_ty: (fun x =>  subst_ty theta_ty (sigma_ty x)) == tau_ty)\n  (E_vl: (fun x =>  subst_vl (theta_ty, theta_vl) (sigma_vl x)) == tau_vl) : @eq_of_subst subst_of_vl (comp_vl (up_vl_vl (sigma_ty\n                                                                                                                         , sigma_vl)) (up_vl_vl (theta_ty\n                                                                                                                                                , theta_vl))) (up_vl_vl (tau_ty\n                                                                                                                                                                        , tau_vl)) :=\n  conj (fun n => eq_trans (compE_ren_subst_ty idren _ (sigma_ty n)) (eq_trans (eq_sym (compE_subst_ren_ty theta_ty idren (sigma_ty n))) (ap (ren_ty idren) (E_ty n)))) (fun n => match n return match comp_vl (up_vl_vl (sigma_ty\n                                                                                                                                                                                                                        , sigma_vl)) (up_vl_vl (theta_ty\n                                                                                                                                                                                                                                               , theta_vl)), up_vl_vl (tau_ty\n                                                                                                                                                                                                                                                                      , tau_vl) with\n  | (sigma_ty, sigma_vl), (tau_ty, tau_vl) => sigma_vl n = tau_vl n\n  end with\n  | 0 => eq_refl\n  | S n =>\n      eq_trans (compE_ren_subst_vl idren S _ _ (sigma_vl n)) (eq_trans (eq_sym (compE_subst_ren_vl theta_ty theta_vl idren S (sigma_vl n))) (ap (ren_vl (idren\n                                                                                                                                                        , S)) (E_vl n)))\n  end).\n\nFixpoint compTrans_subst_subst_tm (sigma_ty: index -> ty)\n           (sigma_vl: index -> vl)\n           (tau_ty: index -> ty)\n           (tau_vl: index -> vl)\n           (theta_ty: index -> ty)\n           (theta_vl: index -> vl)\n           (E_ty: (fun x =>  subst_ty tau_ty (sigma_ty x)) == theta_ty)\n           (E_vl: (fun x =>  subst_vl (tau_ty, tau_vl) (sigma_vl x)) == theta_vl)\n           (s: tm) : subst_tm (tau_ty, tau_vl) (subst_tm (sigma_ty, sigma_vl) s) = subst_tm (theta_ty, theta_vl) s :=\n  match s with\n  \n  | app s0 s1 => apc (ap app (compTrans_subst_subst_tm _ _ _ _ _ _ E_ty E_vl s0)) ((compTrans_subst_subst_tm _ _ _ _ _ _ E_ty E_vl s1))\n  | tapp s0 s1 => apc (ap tapp (compTrans_subst_subst_tm _ _ _ _ _ _ E_ty E_vl s0)) ((compTrans_subst_subst_ty _ _ _ E_ty s1))\n  | vt s0 => ap vt (compTrans_subst_subst_vl _ _ _ _ _ _ E_ty E_vl s0)\n  end\n with compTrans_subst_subst_vl (sigma_ty: index -> ty)\n        (sigma_vl: index -> vl)\n        (tau_ty: index -> ty)\n        (tau_vl: index -> vl)\n        (theta_ty: index -> ty)\n        (theta_vl: index -> vl)\n        (E_ty: (fun x =>  subst_ty tau_ty (sigma_ty x)) == theta_ty)\n        (E_vl: (fun x =>  subst_vl (tau_ty, tau_vl) (sigma_vl x)) == theta_vl)\n        (s: vl) : subst_vl (tau_ty, tau_vl) (subst_vl (sigma_ty, sigma_vl) s) = subst_vl (theta_ty, theta_vl) s :=\n  match s with\n  | var_vl n =>  (E_vl n)\n  | lam s0 s1 =>\n      apc (ap lam (compTrans_subst_subst_ty _ _ _ E_ty s0)) ((match up_subst_subst_vl_vl sigma_ty sigma_vl tau_ty tau_vl theta_ty theta_vl E_ty E_vl with\n      | conj (E_ty) (E_vl) => compTrans_subst_subst_tm _ _ _ _ _ _ E_ty E_vl s1\n      end))\n  | tlam s0 => ap tlam (match up_subst_subst_vl_ty sigma_ty sigma_vl tau_ty tau_vl theta_ty theta_vl E_ty E_vl with\n      | conj (E_ty) (E_vl) => compTrans_subst_subst_tm _ _ _ _ _ _ E_ty E_vl s0\n      end)\n  end.\n\nDefinition compE_subst_subst_tm (sigma_ty: index -> ty) (sigma_vl: index -> vl) (tau_ty: index -> ty) (tau_vl: index -> vl) (s: tm)\n  : subst_tm (tau_ty, tau_vl) (subst_tm (sigma_ty, sigma_vl) s) = subst_tm ((fun n => subst_ty (tau_ty) (sigma_ty n))\n                                                                           , (fun n => subst_vl ((tau_ty, tau_vl)) (sigma_vl n))) s :=\n  compTrans_subst_subst_tm sigma_ty sigma_vl tau_ty tau_vl (fun n => subst_ty (tau_ty) (sigma_ty n)) (fun n => subst_vl ((tau_ty\n                                                                                                                         , tau_vl)) (sigma_vl n)) (fun _ => eq_refl) (fun _ => eq_refl) s.\n\nDefinition compE_subst_subst_vl (sigma_ty: index -> ty) (sigma_vl: index -> vl) (tau_ty: index -> ty) (tau_vl: index -> vl) (s: vl)\n  : subst_vl (tau_ty, tau_vl) (subst_vl (sigma_ty, sigma_vl) s) = subst_vl ((fun n => subst_ty (tau_ty) (sigma_ty n))\n                                                                           , (fun n => subst_vl ((tau_ty, tau_vl)) (sigma_vl n))) s :=\n  compTrans_subst_subst_vl sigma_ty sigma_vl tau_ty tau_vl (fun n => subst_ty (tau_ty) (sigma_ty n)) (fun n => subst_vl ((tau_ty\n                                                                                                                         , tau_vl)) (sigma_vl n)) (fun _ => eq_refl) (fun _ => eq_refl) s.\n\nDefinition eq_up_tm_ty {sigma tau: subst_of subst_of_tm} (E: eq_of_subst sigma tau) : eq_of_subst (up_tm_ty sigma) (up_tm_ty tau).\n  destruct sigma as (sigma_ty & sigma_vl). destruct tau as (tau_ty & tau_vl). destruct E as (E_ty & E_vl).\n  exact (conj (fun i: index => match i return (var_ty 0 .: sigma_ty >>> ren_ty (castren_tm_ty (S\n                                                                                              , idren))) i = (var_ty 0 .: tau_ty >>> ren_ty (castren_tm_ty (S\n                                                                                                                                                           , idren))) i\n  with 0 => eq_refl | S j => ap _ (E_ty j) end) (fun i: index => ap _ (E_vl i))).\nDefined.\n\nDefinition eq_up_tm_vl {sigma tau: subst_of subst_of_tm} (E: eq_of_subst sigma tau) : eq_of_subst (up_tm_vl sigma) (up_tm_vl tau).\n  destruct sigma as (sigma_ty & sigma_vl). destruct tau as (tau_ty & tau_vl). destruct E as (E_ty & E_vl).\n  exact (conj (fun i: index => ap _ (E_ty i)) (fun i: index => match i return (var_vl 0 .: sigma_vl >>> ren_vl (castren_tm_vl (idren\n                                                                                                                              , S))) i = (var_vl 0 .: tau_vl >>> ren_vl (castren_tm_vl (idren\n                                                                                                                                                                                       , S))) i\n  with 0 => eq_refl | S j => ap _ (E_vl j) end)).\nDefined.\n\nDefinition eq_up_vl_ty {sigma tau: subst_of subst_of_vl} (E: eq_of_subst sigma tau) : eq_of_subst (up_vl_ty sigma) (up_vl_ty tau).\n  destruct sigma as (sigma_ty & sigma_vl). destruct tau as (tau_ty & tau_vl). destruct E as (E_ty & E_vl).\n  exact (conj (fun i: index => match i return (var_ty 0 .: sigma_ty >>> ren_ty (castren_vl_ty (S\n                                                                                              , idren))) i = (var_ty 0 .: tau_ty >>> ren_ty (castren_vl_ty (S\n                                                                                                                                                           , idren))) i\n  with 0 => eq_refl | S j => ap _ (E_ty j) end) (fun i: index => ap _ (E_vl i))).\nDefined.\n\nDefinition eq_up_vl_vl {sigma tau: subst_of subst_of_vl} (E: eq_of_subst sigma tau) : eq_of_subst (up_vl_vl sigma) (up_vl_vl tau).\n  destruct sigma as (sigma_ty & sigma_vl). destruct tau as (tau_ty & tau_vl). destruct E as (E_ty & E_vl).\n  exact (conj (fun i: index => ap _ (E_ty i)) (fun i: index => match i return (var_vl 0 .: sigma_vl >>> ren_vl (idren\n                                                                                                               , S)) i = (var_vl 0 .: tau_vl >>> ren_vl (idren\n                                                                                                                                                        , S)) i\n  with 0 => eq_refl | S j => ap _ (E_vl j) end)).\nDefined.\n\nFixpoint subst_eq_tm {sigma tau: subst_of subst_of_tm} (E: eq_of_subst sigma tau) (s: tm) : subst_tm sigma s = subst_tm tau s :=\n  match s with\n  \n  | app s0 s1 => congr_app (subst_eq_tm E s0) (subst_eq_tm E s1)\n  | tapp s0 s1 => congr_tapp (subst_eq_tm E s0) (subst_eq_ty (eq_cast_tm_ty E) s1)\n  | vt s0 => congr_vt (subst_eq_vl (eq_cast_tm_vl E) s0)\n  end\n with subst_eq_vl {sigma tau: subst_of subst_of_vl} (E: eq_of_subst sigma tau) (s: vl) : subst_vl sigma s = subst_vl tau s :=\n  match s with\n  | var_vl n => eq_toVar_vl E n\n  | lam s0 s1 => congr_lam (subst_eq_ty (eq_cast_vl_ty E) s0) (subst_eq_tm (eq_up_tm_vl (eq_cast_vl_tm E)) s1)\n  | tlam s0 => congr_tlam (subst_eq_tm (eq_up_tm_ty (eq_cast_vl_tm E)) s0)\n  end.\n\nClass AsimplInst_tm (s: tm) (sigma: subst_of subst_of_tm) (t: tm) := asimplInstEqn_tm : (subst_tm sigma) s = t .\nHint Mode AsimplInst_tm + + - : typeclass_instance.\n\nClass AsimplSubst_tm (sigma tau: subst_of subst_of_tm) := asimplSubstEqn_tm : match sigma, tau with\n| (sigma_ty, sigma_vl), (tau_ty, tau_vl) => (forall x, sigma_ty x = tau_ty x) /\\ ((forall x, sigma_vl x = tau_vl x))\nend .\nHint Mode AsimplSubst_tm + - : typeclass_instance.\n\nClass AsimplComp_tm (sigma tau theta: subst_of subst_of_tm) := asimplCompEqn_tm : match comp_tm sigma tau, theta with\n| (sigma_tau_ty, sigma_tau_vl), (theta_ty, theta_vl) => (forall x, sigma_tau_ty x = theta_ty x) /\\ ((forall x, sigma_tau_vl x = theta_vl x))\nend .\nHint Mode AsimplComp_tm + + - : typeclass_instance.\n\nClass AsimplInst_vl (s: vl) (sigma: subst_of subst_of_vl) (t: vl) := asimplInstEqn_vl : (subst_vl sigma) s = t .\nHint Mode AsimplInst_vl + + - : typeclass_instance.\n\nClass AsimplSubst_vl (sigma tau: subst_of subst_of_vl) := asimplSubstEqn_vl : match sigma, tau with\n| (sigma_ty, sigma_vl), (tau_ty, tau_vl) => (forall x, sigma_ty x = tau_ty x) /\\ ((forall x, sigma_vl x = tau_vl x))\nend .\nHint Mode AsimplSubst_vl + - : typeclass_instance.\n\nClass AsimplComp_vl (sigma tau theta: subst_of subst_of_vl) := asimplCompEqn_vl : match comp_vl sigma tau, theta with\n| (sigma_tau_ty, sigma_tau_vl), (theta_ty, theta_vl) => (forall x, sigma_tau_ty x = theta_ty x) /\\ ((forall x, sigma_tau_vl x = theta_vl x))\nend .\nHint Mode AsimplComp_vl + + - : typeclass_instance.\n\nInstance AsimplCast_tm_ty (sigma_ty: index -> ty)\n(sigma_vl: index -> vl)\n(tau: subst_of subst_of_ty)\n(E: AsimplSubst_ty sigma_ty tau) : AsimplSubst_ty ((cast_tm_ty (sigma_ty, sigma_vl))) tau.\nProof. apply E. Qed.\nTypeclasses Opaque cast_tm_ty.\nInstance AsimplCast_tm_vl (sigma_ty: index -> ty)\n(sigma_vl: index -> vl)\n(tau: subst_of subst_of_vl)\n(E: AsimplSubst_vl (sigma_ty, sigma_vl) tau) : AsimplSubst_vl ((cast_tm_vl (sigma_ty, sigma_vl))) tau.\nProof. apply E. Qed.\nTypeclasses Opaque cast_tm_vl.\n\n\n\nInstance AsimplAsimplInst_tm (s t: tm)\n(sigma sigma': subst_of subst_of_tm)\n(E_sigma: AsimplSubst_tm sigma sigma')\n(E: AsimplInst_tm s sigma' t) : Asimpl (subst_tm sigma s) t.\nProof. rewrite <- E. apply subst_eq_tm. assumption. Qed.\n\nInstance AsimplInstRefl_tm (s: tm) (sigma: subst_of subst_of_tm) : AsimplInst_tm s sigma (s.[ sigma ]) |100.\nProof. reflexivity. Qed.\n\n\n(* Proof written by hand *)\nInstance asimplInst_app (s0 s1 s0' s1': _)\n(sigma theta_0 theta_1: subst_of subst_of_tm)\n(E_0': AsimplSubst_tm (sigma) theta_0)\n(E_1': AsimplSubst_tm (sigma) theta_1)\n(E_0: AsimplInst_tm s0 theta_0 s0')\n(E_1: AsimplInst_tm s1 theta_1 s1') : AsimplInst_tm (app s0 s1) sigma (app s0' s1').\nProof.\n  unfold AsimplInst_tm. simpl. f_equal. \n  - rewrite <- E_0. apply subst_eq_tm. assumption.\n  - rewrite <- E_1. apply subst_eq_tm. assumption.\nQed.\n\n(* Proof written by hand *)\nInstance asimplInst_tapp (s0 s1 s0' s1': _)\n(sigma theta_0: subst_of subst_of_tm)\n(theta_1: subst_of subst_of_ty)\n(E_0': AsimplSubst_tm (sigma) theta_0)\n(E_1': AsimplSubst_ty (((cast_tm_ty sigma))) theta_1)\n(E_0: AsimplInst_tm s0 theta_0 s0')\n(E_1: AsimplInst_ty s1 theta_1 s1') : AsimplInst_tm (tapp s0 s1) sigma (tapp s0' s1').\nProof.\n  unfold AsimplInst_tm. simpl. f_equal.\n  - rewrite <- E_0. apply subst_eq_tm. assumption.\n  - rewrite <- E_1. apply subst_eq_ty. assumption.\nQed.\n  \n\n(* Proof written by hand *)\nInstance asimplInst_vt (s0 s0': _)\n(sigma: subst_of subst_of_tm)\n(theta_0: subst_of subst_of_vl)\n(E_0': AsimplSubst_vl (((cast_tm_vl sigma))) theta_0)\n(E_0: AsimplInst_vl s0 theta_0 s0') : AsimplInst_tm (vt s0) sigma (vt s0').\nProof.\n  unfold AsimplInst_tm. simpl. f_equal.\n  - rewrite <- E_0. apply subst_eq_vl. assumption.\nQed.\n\nInstance AsimplId_tm (s: tm) : AsimplInst_tm s (var_ty, var_vl) s.\nProof. apply id_tm; reflexivity. Qed.\n\n(* Proof written by hand *)\nInstance AsimplInstInst_tm (s t: tm)\n(sigma sigma' tau sigma_tau: subst_of subst_of_tm)\n(E1: AsimplSubst_tm sigma sigma')\n(E2: AsimplComp_tm sigma' tau sigma_tau)\n(E3: AsimplInst_tm s sigma_tau t) : AsimplInst_tm (subst_tm sigma s) tau t. \nProof.\n  rewrite <- E3. destruct sigma, sigma_tau, tau, sigma'.\n  destruct E1 as [E1_ty E1_vl]. destruct E2 as [E2_ty E2_vl]. \n  apply compTrans_subst_subst_tm.\n  - intros x.  rewrite E1_ty. apply E2_ty.\n  - intros x. rewrite E1_vl. apply E2_vl. \nQed. \n\n\n(* Proof written by hand. *)\nInstance AsimplSubstRefl_tm (sigma: subst_of subst_of_tm) : AsimplSubst_tm sigma sigma | 100.\nProof. destruct sigma; repeat split; intros x; reflexivity. Qed.\n\n(* Proof written by hand *)\nInstance AsimplSubstComp_tm (sigma sigma' tau tau' theta: subst_of subst_of_tm)\n(E_sigma: AsimplSubst_tm sigma sigma')\n(E_tau: AsimplSubst_tm tau tau')\n(E: AsimplComp_tm sigma' tau' theta) : AsimplSubst_tm (comp_tm sigma tau) theta |90. \nProof.\n  destruct sigma', tau', tau, theta, sigma.\n  destruct E as [E_ty E_vl]. destruct E_sigma as [E'_ty E'_vl]. destruct E_tau as [E''_ty E''_vl]. \n  repeat split.\n  - intros x. simpl. rewrite <- E_ty. rewrite E'_ty. apply subst_eq_ty. assumption. \n  - intros x. simpl. rewrite <- E_vl. rewrite E'_vl. apply subst_eq_vl. split; assumption.\nQed.\n\nInstance AsimplSubstCongr_tm (sigma_ty: index -> ty)\n(sigma_vl: index -> vl)\n(tau_ty: index -> ty)\n(tau_vl: index -> vl)\n(E_ty: AsimplGen sigma_ty tau_ty)\n(E_vl: AsimplGen sigma_vl tau_vl) : AsimplSubst_tm (sigma_ty, sigma_vl) (tau_ty, tau_vl) |95.\nProof. repeat split; assumption. Qed.\n\n(* Proof written by hand. *)\nInstance AsimplCompRefl_tm (sigma tau: subst_of subst_of_tm) : AsimplComp_tm sigma tau (comp_tm sigma tau) | 100.\nProof. destruct sigma; destruct tau; repeat split; intros x; reflexivity. Qed.\n\nInstance AsimplCompIdR_tm (sigma: index -> tm) : AsimplComp sigma (subst_tm (var_ty, var_vl)) sigma.\nProof. intros x. apply id_tm; reflexivity. Qed.\n\n(* Proof written by hand *)\nInstance AsimplCompAsso_tm (sigma tau theta tau_theta sigma_tau_theta: subst_of subst_of_tm)\n(E: AsimplComp_tm tau theta tau_theta)\n(E': AsimplComp_tm sigma tau_theta sigma_tau_theta) : AsimplComp_tm (comp_tm sigma tau) theta sigma_tau_theta.\nProof.\n  destruct tau, theta, tau_theta, sigma, sigma_tau_theta.\n  destruct E as [E_ty E_vl]. destruct E' as [E'_ty E'_vl]. \n  unfold AsimplComp_tm. simpl. split; intros x.\n  - rewrite <- E'_ty. simpl. erewrite compTrans_subst_subst_ty.\n    + reflexivity.\n    + assumption.\n  - rewrite <- E'_vl. simpl. erewrite compTrans_subst_subst_vl.\n    + reflexivity.\n    + assumption.\n    + assumption.      \nQed. \n \n(* Proof written by hand *)\nInstance AsimplCompCongr_tm (sigma_ty: index -> ty)\n(sigma_vl: index -> vl)\n(theta_ty: index -> ty)\n(theta_vl: index -> vl)\n(tau_ty: subst_of subst_of_ty)\n(tau_vl: subst_of subst_of_vl)\n(tau: subst_of subst_of_tm)\n(E_ty: AsimplSubst_ty ((cast_tm_ty tau)) tau_ty)\n(E_vl: AsimplSubst_vl ((cast_tm_vl tau)) tau_vl)\n(E_ty': AsimplComp sigma_ty (subst_ty tau_ty) theta_ty)\n(E_vl': AsimplComp sigma_vl (subst_vl tau_vl) theta_vl) : AsimplComp_tm (sigma_ty, sigma_vl) tau (theta_ty, theta_vl).\nProof.\n  unfold AsimplComp_tm. split.\n  - intros x. rewrite <- E_ty'. simpl. apply subst_eq_ty. assumption.\n  - intros x. rewrite <- E_vl'. simpl. apply subst_eq_vl. assumption. \nQed. \n\n(* Proof written by hand *)\nInstance AsimplCompCongr'_tm (sigma_ty: index -> ty)\n(sigma_vl: index -> vl)\n(theta_ty: index -> ty)\n(theta_vl: index -> vl)\n(tau_ty: subst_of subst_of_ty)\n(tau_vl: subst_of subst_of_vl)\n(tau: subst_of subst_of_tm)\n(E_ty: AsimplSubst_ty ((cast_tm_ty tau)) tau_ty)\n(E_vl: AsimplSubst_vl ((cast_tm_vl tau)) tau_vl)\n(E_ty': AsimplComp sigma_ty (subst_ty tau_ty) theta_ty)\n(E_vl': AsimplComp sigma_vl (subst_vl tau_vl) theta_vl) : AsimplComp (subst_tm (sigma_ty, sigma_vl)) (subst_tm tau) (subst_tm (theta_ty\n                                                                                                                             , theta_vl)). \nProof.\n  intros s. simpl. erewrite AsimplInstInst_tm. \n  - reflexivity.\n  - instantiate (1 := (sigma_ty, sigma_vl)). split; reflexivity. \n  - instantiate (1 := (theta_ty, theta_vl)). \n    unfold AsimplComp_tm. simpl. split.\n    + intros x. rewrite <- E_ty'. simpl. apply subst_eq_ty. assumption.\n    + intros x. rewrite <- E_vl'. simpl. apply subst_eq_vl. assumption. \n  - reflexivity. \nQed. \n\nInstance AsimplRefl_tm (s: tm) : Asimpl s s | 100.\nProof. reflexivity. Qed.\n\nInstance AsimplGenComp_tm (sigma sigma': index -> tm)\n(tau tau': subst_of subst_of_tm)\n(theta: index -> tm)\n(E: AsimplGen sigma sigma')\n(E': AsimplSubst_tm tau tau')\n(E'': AsimplComp sigma' (subst_tm tau') theta) : AsimplGen (sigma >>> (subst_tm tau) ) theta.\nProof. intros x. rewrite <- E''. simpl. rewrite E. now apply subst_eq_tm. Qed.\n\n(* Lemma up_ren_up (xi : ren) (sigma : index -> ty) (E : (xi >>> var_ty) == sigma) :\n  (upren_ty_ty xi >>> var_ty) == up_ty_ty sigma. \nProof.\n  intros [|x].\n  - reflexivity.\n  - simpl. unfold compren_ty. rewrite <- E. reflexivity.\nQed. *)\n\n\n(* Proof written by hand. *) \nDefinition up_ren_up_vl_vl (xi zeta : ren) (sigma : index -> ty) (tau: index -> vl)  (E_ty : (xi >>> var_ty) == sigma) (E_vl: (zeta >>> var_vl) == tau) :\n  @eq_of_subst subst_of_tm  (xi >>> var_ty, up_ren zeta >>> var_vl) (up_vl_vl (sigma, tau)).\nProof.\n  split.\n  - intros x. simpl. rewrite <- E_ty.\n    reflexivity.\n  - intros x. simpl. destruct x.\n    + reflexivity.\n    + simpl. rewrite <- E_vl. reflexivity. \nQed. \n\nDefinition up_ren_up_vl_ty (xi zeta : ren) (sigma : index -> ty) (tau: index -> vl)  (E_ty : (xi >>> var_ty) == sigma) (E_vl: (zeta >>> var_vl) == tau) :\n  @eq_of_subst subst_of_tm  (up_ren xi >>> var_ty,  zeta >>> var_vl) (up_vl_ty (sigma, tau)).\nProof.\n  split.\n  - intros x. simpl. destruct x; [reflexivity|].\n    simpl.  rewrite <- E_ty. reflexivity. \n  - intros x. simpl. rewrite <- E_vl. simpl. reflexivity.\nQed. \n\nPrint subst_tm. \n\n(* Proof written by hand. *)\nFixpoint ren_inst_tm (xi zeta : ren) (sigma : index -> ty) (tau: index -> vl)  (E_ty : (xi >>> var_ty) == sigma) (E_vl: (zeta >>> var_vl) == tau) (s : tm):\n  ren_tm (xi, zeta) s = s.[(sigma, tau)]\nwith ren_inst_vl (xi zeta : ren) (sigma : index -> ty) (tau: index -> vl)  (E_ty : (xi >>> var_ty) == sigma) (E_vl: (zeta >>> var_vl) == tau) (s : vl):\n       ren_vl (xi, zeta) s = s.[(sigma, tau)].\nProof.\n  - induction s.\n    + simpl. rewrite IHs1. rewrite IHs2. reflexivity.\n    + simpl. rewrite IHs.\n      erewrite ren_inst_ty. reflexivity. assumption.\n    + simpl. erewrite ren_inst_vl.\n      reflexivity. assumption. assumption.\n  - induction s.\n    + simpl. apply E_vl.\n    + simpl. erewrite ren_inst_ty; try eassumption. \n      destruct (@up_ren_up_vl_vl xi zeta sigma tau E_ty E_vl) as (H1&H2). \n      rewrite ren_inst_tm with (sigma := fun x : index => ren_ty idren (sigma x)) (tau := var_vl 0 .: (fun x : index => ren_vl (idren, S) (tau x))).\n      * reflexivity.\n      * apply H1.\n      * apply H2.\n    + simpl.\n      destruct (@up_ren_up_vl_ty xi zeta sigma tau E_ty E_vl) as (H1&H2).\n      rewrite ren_inst_tm with (sigma := var_ty 0 .: (fun x : index => ren_ty S (sigma x))) (tau :=  fun x : index => ren_vl (S, idren) (tau x)).\n      * reflexivity.\n      * apply H1.\n      * apply H2.\nQed. \n\n\n(* Proof written by hand *)\nInstance AsimplSubstUp_tm_ty (sigma_ty: index -> ty)\n(sigma_vl: index -> vl)\n(tau_ty: index -> ty)\n(tau_vl: index -> vl)\n(E_ty: AsimplGen (var_ty 0 .: sigma_ty >>> (subst_ty ((cast_tm_ty ((S >>> var_ty, id >>> var_vl)))))) tau_ty)\n(E_vl: AsimplGen ( sigma_vl >>> (subst_vl ((cast_tm_vl ((S >>> var_ty, id >>> var_vl)))))) tau_vl) : AsimplSubst_tm (up_tm_ty (sigma_ty\n                                                                                                                              , sigma_vl)) (tau_ty\n                                                                                                                                            , tau_vl).\nProof.\n  split.\n  - intros x. rewrite <- E_ty. destruct x; [reflexivity|]. \n    simpl. erewrite ren_inst_ty; reflexivity. \n  - intros x. rewrite <- E_vl.\n    simpl. erewrite ren_inst_vl; reflexivity. \nQed. \n\n(* Proof written by hand *)\nInstance AsimplSubstUp_tm_vl (sigma_ty: index -> ty)\n(sigma_vl: index -> vl)\n(tau_ty: index -> ty)\n(tau_vl: index -> vl)\n(E_ty: AsimplGen ( sigma_ty >>> (subst_ty ((cast_tm_ty ((id >>> var_ty, S >>> var_vl)))))) tau_ty)\n(E_vl: AsimplGen (var_vl 0 .: sigma_vl >>> (subst_vl ((cast_tm_vl ((id >>> var_ty\n                                                                   , S >>> var_vl)))))) tau_vl) : AsimplSubst_tm (up_tm_vl (sigma_ty\n                                                                                                                           , sigma_vl)) (tau_ty\n                                                                                                                                         , tau_vl).\nProof.\n  split.\n  - intros x. rewrite <- E_ty. erewrite ren_inst_ty; reflexivity. \n  - intros x. rewrite <- E_vl. destruct x; [reflexivity|].\n    simpl. erewrite ren_inst_vl; reflexivity. \nQed. \n\nInstance AsimplCast_vl_ty (sigma_ty: index -> ty)\n(sigma_vl: index -> vl)\n(tau: subst_of subst_of_ty)\n(E: AsimplSubst_ty sigma_ty tau) : AsimplSubst_ty ((cast_vl_ty (sigma_ty, sigma_vl))) tau.\nProof. apply E. Qed.\nTypeclasses Opaque cast_vl_ty.\n\nInstance AsimplToVar_vl (sigma_ty: index -> ty) (sigma_vl: index -> vl) : AsimplGen (toVar_vl (sigma_ty, sigma_vl)) sigma_vl.\nProof. intros x. reflexivity. Qed.\n\nInstance AsimplAsimplInst_vl (s t: vl)\n(sigma sigma': subst_of subst_of_vl)\n(E_sigma: AsimplSubst_vl sigma sigma')\n(E: AsimplInst_vl s sigma' t) : Asimpl (subst_vl sigma s) t.\nProof. rewrite <- E. apply subst_eq_vl. assumption. Qed.\n\nInstance AsimplInstRefl_vl (s: vl) (sigma: subst_of subst_of_vl) : AsimplInst_vl s sigma (s.[ sigma ]) |100.\nProof. reflexivity. Qed.\n\nInstance AsimplInstVar_vl (x y: index)\n(sigma: subst_of subst_of_vl)\n(sigma': index -> vl)\n(s: vl)\n(E: AsimplIndex x y)\n(E': AsimplGen (toVar_vl sigma) sigma')\n(E'': AsimplVarInst y sigma' s) : AsimplInst_vl (var_vl x) sigma s.\nProof. rewrite E. rewrite <- E''. apply E'.  Qed.\n\n(* Proof written by hand *)\nInstance asimplInst_lam (s0 s1 s0' s1': _)\n(sigma: subst_of subst_of_vl)\n(theta_0: subst_of subst_of_ty)\n(theta_1: subst_of subst_of_tm)\n(E_0': AsimplSubst_ty (((cast_vl_ty sigma))) theta_0)\n(E_1': AsimplSubst_tm ((up_vl_vl ((cast_vl_tm sigma)))) theta_1)\n(E_0: AsimplInst_ty s0 theta_0 s0')\n(E_1: AsimplInst_tm s1 theta_1 s1') : AsimplInst_vl (lam s0 s1) sigma (lam s0' s1'). \nProof.\n  unfold AsimplInst_vl. simpl. f_equal.\n  - rewrite <- E_0. apply subst_eq_ty. assumption.\n  - rewrite <- E_1. apply subst_eq_tm. assumption.\nQed.\n\n\n(* Proof written by hand *)\nInstance asimplInst_tlam (s0 s0': _)\n(sigma: subst_of subst_of_vl)\n(theta_0: subst_of subst_of_tm)\n(E_0': AsimplSubst_tm ((up_vl_ty ((cast_vl_tm sigma)))) theta_0)\n(E_0: AsimplInst_tm s0 theta_0 s0') : AsimplInst_vl (tlam s0) sigma (tlam s0').\nProof.\n  unfold AsimplInst_vl. simpl. f_equal.\n  - rewrite <- E_0. apply subst_eq_tm. assumption.\nQed.\n\nInstance AsimplId_vl (s: vl) : AsimplInst_vl s (var_ty, var_vl) s.\nProof. apply id_vl; reflexivity. Qed.\n\n(* Proof written by hand *)\nInstance AsimplInstInst_vl (s t: vl)\n(sigma sigma' tau sigma_tau: subst_of subst_of_vl)\n(E1: AsimplSubst_vl sigma sigma')\n(E2: AsimplComp_vl sigma' tau sigma_tau)\n(E3: AsimplInst_vl s sigma_tau t) : AsimplInst_vl (subst_vl sigma s) tau t.\nProof.\n  rewrite <- E3. destruct sigma, sigma_tau, tau, sigma'.\n  destruct E1 as [E1_ty E1_vl]. destruct E2 as [E2_ty E2_vl]. \n  apply compTrans_subst_subst_vl.\n  - intros x.  rewrite E1_ty. apply E2_ty.\n  - intros x. rewrite E1_vl. apply E2_vl. \nQed. \n\n(* Proof written by hand. *)\nInstance AsimplSubstRefl_vl (sigma: subst_of subst_of_vl) : AsimplSubst_vl sigma sigma | 100.\nProof. destruct sigma; repeat split; intros x; reflexivity. Qed.\n\n(* Proof written by hand *)\nInstance AsimplSubstComp_vl (sigma sigma' tau tau' theta: subst_of subst_of_vl)\n(E_sigma: AsimplSubst_vl sigma sigma')\n(E_tau: AsimplSubst_vl tau tau')\n(E: AsimplComp_vl sigma' tau' theta) : AsimplSubst_vl (comp_vl sigma tau) theta |90.\nProof.\n  destruct sigma', tau', tau, theta, sigma.\n  destruct E as [E_ty E_vl]. destruct E_sigma as [E'_ty E'_vl]. destruct E_tau as [E''_ty E''_vl]. \n  repeat split.\n  - intros x. simpl. rewrite <- E_ty. rewrite E'_ty. apply subst_eq_ty. assumption. \n  - intros x. simpl. rewrite <- E_vl. rewrite E'_vl. apply subst_eq_vl. split; assumption.\nQed.\n\nInstance AsimplSubstCongr_vl (sigma_ty: index -> ty)\n(sigma_vl: index -> vl)\n(tau_ty: index -> ty)\n(tau_vl: index -> vl)\n(E_ty: AsimplGen sigma_ty tau_ty)\n(E_vl: AsimplGen sigma_vl tau_vl) : AsimplSubst_vl (sigma_ty, sigma_vl) (tau_ty, tau_vl) |95.\nProof. repeat split; assumption. Qed.\n\nInstance AsimplCompRefl_vl (sigma tau: subst_of subst_of_vl) : AsimplComp_vl sigma tau (comp_vl sigma tau) | 100.\nProof. destruct sigma; destruct tau; repeat split; intros x; reflexivity. Qed.\n\n\nInstance AsimplCompIdL_vl (sigma: subst_of subst_of_vl)\n(tau: index -> vl)\n(E: AsimplGen (toVar_vl sigma) tau) : AsimplComp var_vl (subst_vl sigma) tau.\nProof.\n  intros x. rewrite <- E. reflexivity. \nQed. \n\nInstance AsimplCompIdR_vl (sigma: index -> vl) : AsimplComp sigma (subst_vl (var_ty, var_vl)) sigma.\nProof. intros x. apply id_vl; reflexivity. Qed.\n\n\n(* Proof written by hand *)\nInstance AsimplCompAsso_vl (sigma tau theta tau_theta sigma_tau_theta: subst_of subst_of_vl)\n(E: AsimplComp_vl tau theta tau_theta)\n(E': AsimplComp_vl sigma tau_theta sigma_tau_theta) : AsimplComp_vl (comp_vl sigma tau) theta sigma_tau_theta.\nProof.\n  destruct tau, theta, tau_theta, sigma, sigma_tau_theta.\n  destruct E as [E_ty E_vl]. destruct E' as [E'_ty E'_vl]. \n  unfold AsimplComp_tm. simpl. split; intros x.\n  - rewrite <- E'_ty. simpl. erewrite compTrans_subst_subst_ty.\n    + reflexivity.\n    + assumption.\n  - rewrite <- E'_vl. simpl. erewrite compTrans_subst_subst_vl.\n    + reflexivity.\n    + assumption.\n    + assumption.      \nQed. \n\n(* Proof written by hand *)\nInstance AsimplCompCongr_vl (sigma_ty: index -> ty)\n(sigma_vl: index -> vl)\n(theta_ty: index -> ty)\n(theta_vl: index -> vl)\n(tau_ty: subst_of subst_of_ty)\n(tau_vl tau: subst_of subst_of_vl)\n(E_ty: AsimplSubst_ty ((cast_vl_ty tau)) tau_ty)\n(E_vl: AsimplSubst_vl (tau) tau_vl)\n(E_ty': AsimplComp sigma_ty (subst_ty tau_ty) theta_ty)\n(E_vl': AsimplComp sigma_vl (subst_vl tau_vl) theta_vl) : AsimplComp_vl (sigma_ty, sigma_vl) tau (theta_ty, theta_vl).\nProof.\n  unfold AsimplComp_tm. split.\n  - intros x. rewrite <- E_ty'. simpl. apply subst_eq_ty. assumption.\n  - intros x. rewrite <- E_vl'. simpl. apply subst_eq_vl. assumption. \nQed. \n\n(* Proof written by hand *)\nInstance AsimplCompCongr'_vl (sigma_ty: index -> ty)\n(sigma_vl: index -> vl)\n(theta_ty: index -> ty)\n(theta_vl: index -> vl)\n(tau_ty: subst_of subst_of_ty)\n(tau_vl tau: subst_of subst_of_vl)\n(E_ty: AsimplSubst_ty ((cast_vl_ty tau)) tau_ty)\n(E_vl: AsimplSubst_vl (tau) tau_vl)\n(E_ty': AsimplComp sigma_ty (subst_ty tau_ty) theta_ty)\n(E_vl': AsimplComp sigma_vl (subst_vl tau_vl) theta_vl) : AsimplComp (subst_vl (sigma_ty, sigma_vl)) (subst_vl tau) (subst_vl (theta_ty\n                                                                                                                             , theta_vl)).\nProof.\n  intros s. simpl. erewrite AsimplInstInst_vl. \n  - reflexivity.\n  - instantiate (1 := (sigma_ty, sigma_vl)). split; reflexivity. \n  - instantiate (1 := (theta_ty, theta_vl)). \n    unfold AsimplComp_tm. simpl. split.\n    + intros x. rewrite <- E_ty'. simpl. apply subst_eq_ty. assumption.\n    + intros x. rewrite <- E_vl'. simpl. apply subst_eq_vl. assumption. \n  - reflexivity. \nQed. \n\nInstance AsimplRefl_vl (s: vl) : Asimpl s s | 100.\nProof. reflexivity. Qed.\n\nInstance AsimplGenComp_vl (sigma sigma': index -> vl)\n(tau tau': subst_of subst_of_vl)\n(theta: index -> vl)\n(E: AsimplGen sigma sigma')\n(E': AsimplSubst_vl tau tau')\n(E'': AsimplComp sigma' (subst_vl tau') theta) : AsimplGen (sigma >>> (subst_vl tau) ) theta.\nProof. intros x. rewrite <- E''. simpl. rewrite E. now apply subst_eq_vl. Qed.\n\n(* Proof written by hand *)\nInstance AsimplSubstUp_vl_ty (sigma_ty: index -> ty)\n(sigma_vl: index -> vl)\n(tau_ty: index -> ty)\n(tau_vl: index -> vl)\n(E_ty: AsimplGen (var_ty 0 .: sigma_ty >>> (subst_ty ((cast_vl_ty ((S >>> var_ty, id >>> var_vl)))))) tau_ty)\n(E_vl: AsimplGen ( sigma_vl >>> (subst_vl (((S >>> var_ty, id >>> var_vl))))) tau_vl) : AsimplSubst_vl (up_vl_ty (sigma_ty\n                                                                                                                 , sigma_vl)) (tau_ty\n                                                                                                                               , tau_vl).\nProof.\n  split. \n  - intros x. rewrite <- E_ty. destruct x; [reflexivity|]. simpl.\n    erewrite ren_inst_ty; reflexivity.\n  - intros x. rewrite <- E_vl.\n    erewrite ren_inst_vl; reflexivity.\nQed.\n\n(* Proof written by hand *)\nInstance AsimplSubstUp_vl_vl (sigma_ty: index -> ty)\n(sigma_vl: index -> vl)\n(tau_ty: index -> ty)\n(tau_vl: index -> vl)\n(E_ty: AsimplGen ( sigma_ty >>> (subst_ty ((cast_vl_ty ((id >>> var_ty, S >>> var_vl)))))) tau_ty)\n(E_vl: AsimplGen (var_vl 0 .: sigma_vl >>> (subst_vl (((id >>> var_ty, S >>> var_vl))))) tau_vl) : AsimplSubst_vl (up_vl_vl (sigma_ty\n                                                                                                                            , sigma_vl)) (tau_ty\n                                                                                                                                          , tau_vl).\nProof.\n  split.\n  - intros x. rewrite <- E_ty. simpl.\n    erewrite ren_inst_ty; reflexivity.\n  - intros x. rewrite <- E_vl. destruct x; [reflexivity|]. simpl.\n    erewrite ren_inst_vl; reflexivity. \nQed. \n\nTypeclasses Opaque toVar_vl.\n\n", "meta": {"author": "Blaisorblade", "repo": "autosubst2-proto", "sha": "25b9d35abe99ca5c33841fca5855c6156f3950bf", "save_path": "github-repos/coq/Blaisorblade-autosubst2-proto", "path": "github-repos/coq/Blaisorblade-autosubst2-proto/autosubst2-proto-25b9d35abe99ca5c33841fca5855c6156f3950bf/lfmtp17-coq/SystemF_cbv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.27477236585595666}}
{"text": "(* Sequent calculus with upper bounds on proof size.\n   Useful for doing induction on.\n\n   The main purpose this file is to provide the inversion lemmas (at the very bottom of the file).\n *)\nFrom Coq Require Import ssreflect.\nFrom stdpp Require Import prelude.\nFrom bunched.algebra Require Import bi.\nFrom bunched Require Import seqcalc_s4.\n\nReserved Notation \"P ⊢ᴮ{ n } Q\" (at level 99, n, Q at level 200, right associativity).\nReserved Notation \"Δ =?{ n } Δ'\" (at level 99, n at level 200).\n\nSection SeqcalcHeight.\n\n  Implicit Type Δ : bunch.\n  Implicit Type ψ ϕ : formula.\n\n  (** ** Alternative formulation of bunch equivalences *)\n  Inductive bunch_equiv : bunch → bunch → Prop :=\n  | BE_cong Π Δ1 Δ2 :\n      Δ1 =? Δ2 →\n      fill Π Δ1 =? fill Π Δ2\n  | BE_comma_unit_l Δ :\n      (empty ,, Δ)%B =? Δ\n  | BE_comma_comm Δ1 Δ2 :\n      (Δ1 ,, Δ2)%B =? (Δ2 ,, Δ1)%B\n  | BE_comma_assoc Δ1 Δ2 Δ3 : (Δ1 ,, (Δ2 ,, Δ3))%B =? ((Δ1 ,, Δ2) ,, Δ3)%B\n  | BE_semic_unit_l Δ : (top ;, Δ)%B =? Δ\n  | BE_semic_comm Δ1 Δ2  : (Δ1 ;, Δ2)%B =? (Δ2 ;, Δ1)%B\n  | BE_semic_assoc Δ1 Δ2 Δ3  : (Δ1 ;, (Δ2 ;, Δ3))%B =? ((Δ1 ;, Δ2) ;, Δ3)%B\n  where \"Δ =? Γ\" := (bunch_equiv Δ%B Γ%B).\n\n  Definition bunch_equiv_h := rtsc (bunch_equiv).\n\n  Lemma bunch_equiv_1 Δ Δ' :\n    (Δ =? Δ') → (Δ ≡ Δ').\n  Proof. induction 1; by econstructor; eauto. Qed.\n\n  Lemma bunch_equiv_2 Δ Δ' :\n    (Δ ≡ Δ') → (bunch_equiv_h Δ Δ').\n  Proof.\n    induction 1.\n    all: try by (eapply rtsc_lr; econstructor).\n    - unfold bunch_equiv_h. reflexivity.\n    - by symmetry.\n    - etrans; eauto.\n    - eapply rtc_congruence; eauto.\n      intros X Y. apply sc_congruence. clear X Y.\n      intros X Y ?. by econstructor.\n  Qed.\n\n  Local Lemma bunch_equiv_fill_1 Δ Π ϕ :\n    fill Π (frml ϕ) =? Δ →\n    ∃ C', Δ = fill C' (frml ϕ) ∧ (∀ Δ, fill C' Δ ≡ fill Π Δ).\n  Proof.\n    intros Heq.\n    remember (fill Π (frml ϕ)) as Y.\n    revert Π HeqY.\n    induction Heq=>C' heqY; symmetry in heqY.\n    + apply bunch_decomp_complete in heqY.\n      apply bunch_decomp_ctx in heqY.\n      destruct heqY as [H1 | H2].\n      * destruct H1 as [C1 [HC0%bunch_decomp_correct HC]].\n        destruct (IHHeq C1 HC0) as [C2 [HΔ1 HC2]].\n        simplify_eq/=.\n        exists (C2 ++ Π). rewrite fill_app. split; first done.\n        intros Δ. rewrite !fill_app HC2 //.\n      * destruct H2 as (C1 & C2 & HC1 & HC2 & Hdec0).\n        specialize (Hdec0 Δ2). apply bunch_decomp_correct in Hdec0.\n        exists (C1 Δ2). split ; eauto.\n        intros Δ. rewrite HC1.\n        assert (Δ1 ≡ Δ2) as <-.\n        { by apply bunch_equiv_1. }\n        by rewrite HC2.\n    + apply bunch_decomp_complete in heqY.\n      inversion heqY; simplify_eq/=.\n      { inversion H3. }\n      apply bunch_decomp_correct in H3.\n      exists Π. split; eauto.\n      intros X. rewrite fill_app /= left_id //.\n    + apply bunch_decomp_complete in heqY.\n      inversion heqY; simplify_eq/=.\n      * exists (Π ++ [CtxCommaR Δ2]). split.\n        { rewrite fill_app/=.\n          apply bunch_decomp_correct in H3.\n          by rewrite H3. }\n        intros Δ. rewrite !fill_app/=.\n        by rewrite comm.\n      * exists (Π ++ [CtxCommaL Δ1]). split.\n        { rewrite fill_app/=.\n          apply bunch_decomp_correct in H3.\n          by rewrite H3. }\n        intros Δ. rewrite !fill_app/=.\n        by rewrite comm.\n    + apply bunch_decomp_complete in heqY.\n      inversion heqY; simplify_eq/=.\n      * exists (Π ++ [CtxCommaL Δ2;CtxCommaL Δ3])%B. split.\n        { rewrite fill_app/=.\n          apply bunch_decomp_correct in H3.\n          by rewrite H3. }\n        intros Δ. rewrite !fill_app/=.\n        by rewrite assoc.\n      * inversion H3; simplify_eq/=.\n        ** exists (Π0 ++ [CtxCommaR Δ1;CtxCommaL Δ3])%B. split.\n           { rewrite fill_app/=.\n             apply bunch_decomp_correct in H4.\n               by rewrite H4. }\n           intros Δ. rewrite !fill_app/=.\n           by rewrite assoc.\n        ** exists (Π0 ++ [CtxCommaR (Δ1,,Δ2)])%B. split.\n           { simpl. rewrite fill_app/=.\n             apply bunch_decomp_correct in H4.\n             by rewrite H4. }\n           intros Δ. rewrite !fill_app/=.\n           by rewrite assoc.\n    + apply bunch_decomp_complete in heqY.\n      inversion heqY; simplify_eq/=.\n      { inversion H3. }\n      apply bunch_decomp_correct in H3.\n      exists Π. split; eauto.\n      intros X. rewrite fill_app /= left_id //.\n    + apply bunch_decomp_complete in heqY.\n      inversion heqY; simplify_eq/=.\n      * exists (Π ++ [CtxSemicR Δ2]). split.\n        { rewrite fill_app/=.\n          apply bunch_decomp_correct in H3.\n          by rewrite H3. }\n        intros Δ. rewrite !fill_app/=.\n        by rewrite comm.\n      * exists (Π ++ [CtxSemicL Δ1]). split.\n        { rewrite fill_app/=.\n          apply bunch_decomp_correct in H3.\n          by rewrite H3. }\n        intros Δ. rewrite !fill_app/=.\n        by rewrite comm.\n    + apply bunch_decomp_complete in heqY.\n      inversion heqY; simplify_eq/=.\n      * exists (Π ++ [CtxSemicL Δ2;CtxSemicL Δ3])%B. split.\n        { rewrite fill_app/=.\n          apply bunch_decomp_correct in H3.\n          by rewrite H3. }\n        intros Δ. rewrite !fill_app/=.\n        by rewrite assoc.\n      * inversion H3; simplify_eq/=.\n        ** exists (Π0 ++ [CtxSemicR Δ1;CtxSemicL Δ3])%B. split.\n           { rewrite fill_app/=.\n             apply bunch_decomp_correct in H4.\n               by rewrite H4. }\n           intros Δ. rewrite !fill_app/=.\n           by rewrite assoc.\n        ** exists (Π0 ++ [CtxSemicR (Δ1;,Δ2)])%B. split.\n           { simpl. rewrite fill_app/=.\n             apply bunch_decomp_correct in H4.\n             by rewrite H4. }\n           intros Δ. rewrite !fill_app/=.\n           by rewrite assoc.\n  Qed.\n\n  Local Lemma bunch_equiv_fill_2 Δ Π ϕ :\n    Δ =? fill Π (frml ϕ) →\n    ∃ C', Δ = fill C' (frml ϕ) ∧ (∀ Δ, fill C' Δ ≡ fill Π Δ).\n  Proof.\n    intros Heq.\n    remember (fill Π (frml ϕ)) as Y.\n    revert Π HeqY.\n    induction Heq=>C' heqY; symmetry in heqY.\n    + apply bunch_decomp_complete in heqY.\n      apply bunch_decomp_ctx in heqY.\n      destruct heqY as [H1 | H2].\n      * destruct H1 as [C1 [HC0%bunch_decomp_correct HC]].\n        destruct (IHHeq C1 HC0) as [C2 [HΔ1 HC2]].\n        simplify_eq/=.\n        exists (C2 ++ Π). rewrite fill_app. split; first done.\n        intros Δ. rewrite !fill_app HC2 //.\n      * destruct H2 as (C1 & C2 & HC1 & HC2 & Hdec0).\n        specialize (Hdec0 Δ1). apply bunch_decomp_correct in Hdec0.\n        exists (C1 Δ1). split ; eauto.\n        intros Δ. rewrite HC1.\n        assert (Δ1 ≡ Δ2) as ->.\n        { by apply bunch_equiv_1. }\n        by rewrite HC2.\n    + exists (C' ++ [CtxCommaR empty]). simpl; split.\n      { rewrite fill_app /=. by rewrite heqY. }\n      intros X; rewrite fill_app/=.\n      by rewrite left_id.\n    + apply bunch_decomp_complete in heqY.\n      inversion heqY; simplify_eq/=.\n      * exists (Π ++ [CtxCommaR Δ1]). split.\n        { rewrite fill_app/=.\n          apply bunch_decomp_correct in H3.\n          by rewrite H3. }\n        intros Δ. rewrite !fill_app/=.\n        by rewrite comm.\n      * exists (Π ++ [CtxCommaL Δ2]). split.\n        { rewrite fill_app/=.\n          apply bunch_decomp_correct in H3.\n          by rewrite H3. }\n        intros Δ. rewrite !fill_app/=.\n        by rewrite comm.\n    + apply bunch_decomp_complete in heqY.\n      inversion heqY; simplify_eq/=.\n      * inversion H3; simplify_eq/=.\n        ** exists (Π0 ++ [CtxCommaL (Δ2 ,, Δ3)])%B. split.\n           { rewrite fill_app/=.\n             apply bunch_decomp_correct in H4.\n               by rewrite H4. }\n           intros Δ. rewrite !fill_app/=.\n           by rewrite assoc.\n        ** exists (Π0 ++ [CtxCommaL Δ3;CtxCommaR Δ1])%B. split.\n           { simpl. rewrite fill_app/=.\n             apply bunch_decomp_correct in H4.\n             by rewrite H4. }\n           intros Δ. rewrite !fill_app/=.\n           by rewrite assoc.\n      * exists (Π ++ [CtxCommaR Δ2;CtxCommaR Δ1])%B. split.\n        { rewrite fill_app/=.\n          apply bunch_decomp_correct in H3.\n            by rewrite H3. }\n           intros Δ. rewrite !fill_app/=.\n           by rewrite assoc.\n    + exists (C' ++ [CtxSemicR top]). simpl; split.\n      { rewrite fill_app /=. by rewrite heqY. }\n      intros X; rewrite fill_app/=.\n      by rewrite left_id.\n    + apply bunch_decomp_complete in heqY.\n      inversion heqY; simplify_eq/=.\n      * exists (Π ++ [CtxSemicR Δ1]). split.\n        { rewrite fill_app/=.\n          apply bunch_decomp_correct in H3.\n          by rewrite H3. }\n        intros Δ. rewrite !fill_app/=.\n        by rewrite comm.\n      * exists (Π ++ [CtxSemicL Δ2]). split.\n        { rewrite fill_app/=.\n          apply bunch_decomp_correct in H3.\n          by rewrite H3. }\n        intros Δ. rewrite !fill_app/=.\n        by rewrite comm.\n    + apply bunch_decomp_complete in heqY.\n      inversion heqY; simplify_eq/=.\n      * inversion H3; simplify_eq/=.\n        ** exists (Π0 ++ [CtxSemicL (Δ2 ;, Δ3)])%B. split.\n           { rewrite fill_app/=.\n             apply bunch_decomp_correct in H4.\n             by rewrite H4. }\n           intros Δ. rewrite !fill_app/=.\n           by rewrite assoc.\n        ** exists (Π0 ++ [CtxSemicL Δ3;CtxSemicR Δ1])%B. split.\n           { simpl. rewrite fill_app/=.\n             apply bunch_decomp_correct in H4.\n             by rewrite H4. }\n           intros Δ. rewrite !fill_app/=.\n           by rewrite assoc.\n      * exists (Π ++ [CtxSemicR Δ2;CtxSemicR Δ1])%B. split.\n        { rewrite fill_app/=.\n          apply bunch_decomp_correct in H3.\n            by rewrite H3. }\n           intros Δ. rewrite !fill_app/=.\n           by rewrite assoc.\n  Qed.\n\n  Lemma bunch_equiv_fill Δ Π ϕ :\n    Δ ≡ (fill Π (frml ϕ)) →\n    ∃ C', Δ = fill C' (frml ϕ) ∧ (∀ Δ, fill C' Δ ≡ fill Π Δ).\n  Proof.\n    intros H%bunch_equiv_2.\n    revert Δ H. eapply rtc_ind_l.\n    { exists Π. eauto. }\n    intros X Y HXY HY. clear HY.\n    intros (C0 & -> & HC0).\n    destruct HXY as [HXY|HXY].\n    - apply bunch_equiv_fill_2 in HXY.\n      destruct HXY as (C' & -> & HC').\n      eexists; split; eauto.\n      intros ?. by rewrite HC' HC0.\n    - apply bunch_equiv_fill_1 in HXY.\n      destruct HXY as (C' & -> & HC').\n      eexists; split; eauto.\n      intros ?. by rewrite HC' HC0.\n  Qed.\n\n  (** * SEQUENT CALCULUS *)\n  Polymorphic Inductive proves : bunch → formula → nat → Prop :=\n    (* structural *)\n  | BI_Higher Δ ϕ n : (Δ ⊢ᴮ{n} ϕ) → (Δ ⊢ᴮ{S n} ϕ)\n  | BI_Axiom (a : atom) : frml (ATOM a) ⊢ᴮ{0} ATOM a\n  | BI_Equiv Δ Δ' ϕ n :\n      (Δ ≡ Δ') → (Δ ⊢ᴮ{n} ϕ) →\n      Δ' ⊢ᴮ{S n} ϕ\n  | BI_Weaken Π Δ Δ' ϕ n : (fill Π Δ ⊢ᴮ{n} ϕ) →\n                         fill Π (Δ ;, Δ') ⊢ᴮ{S n} ϕ\n  | BI_Contr Π Δ ϕ n : (fill Π (Δ ;, Δ) ⊢ᴮ{n} ϕ) →\n                     fill Π Δ ⊢ᴮ{S n} ϕ\n  (* | BI_Cut Π Δ ϕ ψ : (Δ ⊢ᴮ ψ) → *)\n  (*                    (fill Π (frml ψ) ⊢ᴮ ϕ) → *)\n  (*                    fill Π Δ ⊢ᴮ ϕ *)\n  (* modal *)\n  | BI_Box_L Π ϕ ψ n :\n      (fill Π (frml ϕ) ⊢ᴮ{n} ψ) →\n      fill Π (frml (BOX ϕ)) ⊢ᴮ{S n} ψ\n  | BI_Box_R Δ ϕ n :\n      (BOX <·> Δ ⊢ᴮ{n} ϕ) →\n      BOX <·> Δ ⊢ᴮ{S n} BOX ϕ\n    (* multiplicatives *)\n  | BI_Emp_R :\n      empty ⊢ᴮ{0} EMP\n  | BI_Emp_L Π ϕ n :\n      (fill Π empty ⊢ᴮ{n} ϕ) →\n      fill Π (frml EMP) ⊢ᴮ{S n} ϕ\n  | BI_Sep_R Δ Δ' ϕ ψ n m :\n      (Δ ⊢ᴮ{n} ϕ) →\n      (Δ' ⊢ᴮ{m} ψ) →\n      Δ ,, Δ' ⊢ᴮ{S (n `max` m)} SEP ϕ ψ\n  | BI_Sep_L Π ϕ ψ χ n :\n      (fill Π (frml ϕ ,, frml ψ) ⊢ᴮ{n} χ) →\n      fill Π (frml (SEP ϕ ψ)) ⊢ᴮ{S n} χ\n  | BI_Wand_R Δ ϕ ψ n :\n      (Δ ,, frml ϕ ⊢ᴮ{n} ψ) →\n      Δ  ⊢ᴮ{S n} WAND ϕ ψ\n  | BI_Wand_L Π Δ ϕ ψ χ n m :\n      (Δ ⊢ᴮ{n} ϕ) →\n      (fill Π (frml ψ) ⊢ᴮ{m} χ) →\n      fill Π (Δ ,, frml (WAND ϕ ψ)) ⊢ᴮ{S (n `max` m)} χ\n    (* additives *)\n  | BI_False_L Π ϕ :\n      fill Π (frml BOT) ⊢ᴮ{0} ϕ\n  | BI_True_R Δ :\n      Δ ⊢ᴮ{0} TOP\n  | BI_True_L Π ϕ n :\n      (fill Π top ⊢ᴮ{n} ϕ) →\n      fill Π (frml TOP) ⊢ᴮ{S n} ϕ\n  | BI_Conj_R Δ Δ' ϕ ψ n m :\n      (Δ ⊢ᴮ{n} ϕ) →\n      (Δ' ⊢ᴮ{m} ψ) →\n      Δ ;, Δ' ⊢ᴮ{S (n `max` m)} CONJ ϕ ψ\n  | BI_Conj_L Π ϕ ψ χ n :\n      (fill Π (frml ϕ ;, frml ψ) ⊢ᴮ{n} χ) →\n      fill Π (frml (CONJ ϕ ψ)) ⊢ᴮ{S n} χ\n  | BI_Disj_R1 Δ ϕ ψ n :\n      (Δ ⊢ᴮ{n} ϕ) →\n      Δ ⊢ᴮ{S n} DISJ ϕ ψ\n  | BI_Disj_R2 Δ ϕ ψ n :\n      (Δ ⊢ᴮ{n} ψ) →\n      Δ ⊢ᴮ{S n} DISJ ϕ ψ\n  | BI_Disj_L Π ϕ ψ χ n m :\n      (fill Π (frml ϕ) ⊢ᴮ{n} χ) →\n      (fill Π (frml ψ) ⊢ᴮ{m} χ) →\n      fill Π (frml (DISJ ϕ ψ)) ⊢ᴮ{S (n `max` m)} χ\n  | BI_Impl_R Δ ϕ ψ n :\n      (Δ ;, frml ϕ ⊢ᴮ{n} ψ) →\n      Δ  ⊢ᴮ{S n} IMPL ϕ ψ\n  | BI_Impl_L Π Δ ϕ ψ χ n m:\n      (Δ ⊢ᴮ{n} ϕ) →\n      (fill Π (frml ψ) ⊢ᴮ{m} χ) →\n      fill Π (Δ ;, frml (IMPL ϕ ψ)) ⊢ᴮ{S (n `max` m)} χ\n  where \"Δ ⊢ᴮ{ n } ϕ\" := (proves Δ%B ϕ%B n).\n\n  Lemma provesN_proves n Δ ϕ :\n    (Δ ⊢ᴮ{ n } ϕ) → Δ ⊢ᴮ ϕ.\n  Proof.\n    induction 1; eauto.\n    by econstructor; eauto.\n    by econstructor; eauto.\n    by econstructor; eauto.\n    by econstructor; eauto.\n    by econstructor; eauto.\n    by econstructor; eauto.\n    by econstructor; eauto.\n    by econstructor; eauto.\n    by econstructor; eauto.\n    by econstructor; eauto.\n    by econstructor; eauto.\n    by econstructor; eauto.\n    by econstructor; eauto.\n    by econstructor; eauto.\n    by econstructor; eauto.\n    by econstructor; eauto.\n    by econstructor; eauto.\n    by econstructor; eauto.\n    by econstructor; eauto.\n    by econstructor; eauto.\n    by econstructor; eauto.\n    by econstructor; eauto.\n  Qed.\n\n  Lemma proves_provesN Δ ϕ :\n    (Δ ⊢ᴮ ϕ) → ∃ n, Δ ⊢ᴮ{n} ϕ.\n  Proof.\n    induction 1.\n    all: try destruct IHproves as [n IH].\n    all: try (destruct IHproves1 as [n1 IH1];\n              destruct IHproves2 as [n2 IH2]).\n    all: try by eexists; econstructor; eauto.\n  Qed.\n\n  (** * Inversion lemmas *)\n  Local Ltac bind_ctx :=\n    match goal with\n    | [ |- fill ?Π ?Δ,, ?Δ' ⊢ᴮ{_} _ ] =>\n      replace (fill Π Δ,, Δ')%B\n      with (fill (Π ++ [CtxCommaL Δ']) Δ)%B\n      by rewrite fill_app//\n    | [ |- fill ?Π ?Δ;, ?Δ' ⊢ᴮ{_} _ ] =>\n      replace (fill Π Δ;, Δ')%B\n      with (fill (Π ++ [CtxSemicL Δ']) Δ)%B\n      by rewrite fill_app//\n    end.\n\n  Local Ltac commute_left_rule IH :=\n    intros ->; bind_ctx;\n    econstructor; eauto; rewrite fill_app; by eapply IH.\n\n  Lemma wand_r_inv' Δ ϕ ψ n :\n    (Δ ⊢ᴮ{n} WAND ϕ ψ) →\n    (Δ ,, frml ϕ ⊢ᴮ{n} ψ)%B.\n  Proof.\n    remember (WAND ϕ ψ) as A.\n    intros H. revert ϕ ψ HeqA.\n    induction H; intros A B; try by inversion 1.\n    all: try by (commute_left_rule IHproves).\n    - intros ->. by constructor; apply IHproves.\n    - intros ->. eapply BI_Equiv.\n      { rewrite -H. reflexivity. }\n      by apply IHproves.\n    - intros ?; simplify_eq/=. by apply BI_Higher.\n    - commute_left_rule IHproves2.\n    - intros ?; simplify_eq/=.\n      bind_ctx. eapply BI_Disj_L.\n      + rewrite fill_app/=. by eapply IHproves1.\n      + rewrite fill_app/=. by eapply IHproves2.\n    - commute_left_rule IHproves2.\n  Qed.\n\n  Lemma impl_r_inv' Δ ϕ ψ n :\n    (Δ ⊢ᴮ{n} IMPL ϕ ψ) →\n    (Δ ;, frml ϕ ⊢ᴮ{n} ψ)%B.\n  Proof.\n    remember (IMPL ϕ ψ) as A.\n    intros H. revert ϕ ψ HeqA.\n    induction H; intros A B; try by inversion 1.\n    all: try by (commute_left_rule IHproves).\n    - intros ->. by constructor; apply IHproves.\n    - intros ->. eapply BI_Equiv.\n      { rewrite -H. reflexivity. }\n      by apply IHproves.\n    - commute_left_rule IHproves2.\n    - intros ?; simplify_eq/=.\n      bind_ctx. eapply BI_Disj_L.\n      + rewrite fill_app/=. by eapply IHproves1.\n      + rewrite fill_app/=. by eapply IHproves2.\n    - intros ?; simplify_eq/=. by apply BI_Higher.\n    - commute_left_rule IHproves2.\n  Qed.\n\n  Lemma box_l_inv' Δ Π ϕ χ n :\n    (Δ ⊢ᴮ{n} χ) →\n    Δ = fill Π (frml (BOX (BOX ϕ))) →\n    (fill Π (frml (BOX ϕ)) ⊢ᴮ{n} χ).\n  Proof.\n    revert Π Δ χ.\n    induction n using lt_wf_ind. rename H into IHproves.\n    intros Π Δ χ PROOF Heq. symmetry in Heq. revert Heq.\n    inversion PROOF; simplify_eq/= => Heq.\n    - (* raising the pf height *)\n      apply BI_Higher.\n      eapply IHproves; eauto.\n    - (* axiom *)\n      apply fill_is_frml in Heq. destruct_and!; simplify_eq/=.\n    - (* equivalence of bunches *)\n      simplify_eq/=.\n      destruct (bunch_equiv_fill _ _ _ H) as [Π2 [-> HΠ2]].\n      eapply BI_Equiv.\n      { apply HΠ2. }\n      eapply IHproves; eauto.\n    - (* weakening *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [Π1 [HΠ0 HΠ]].\n        inversion HΠ0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          apply BI_Weaken.\n          rewrite -fill_app.\n          eapply IHproves; eauto.\n          by apply bunch_decomp_correct, bunch_decomp_app.\n        * rewrite !fill_app/=.\n          by apply BI_Weaken.\n      + rename Π into Π'.\n        rename Π0 into Π0'.\n        destruct H2 as (Π0 & Π1 & HΠ0 & HΠ1 & Hdec0).\n        rewrite -HΠ1.\n        apply BI_Weaken.\n        rewrite -HΠ0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* contraction *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2]; last first.\n      + rename Π0 into Π0'.\n        destruct H2 as (Π0 & Π1 & HΠ0 & HΠ1 & Hdec0).\n        rewrite -HΠ1.\n        apply BI_Contr.\n        rewrite -HΠ0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n      + destruct H1 as [C0 [HC0 ->]].\n        apply bunch_decomp_correct in HC0.\n        simplify_eq/=.\n        rename Π0 into Π.\n        assert (fill Π (fill C0 (frml (BOX ϕ));, fill C0 (frml (BOX (BOX ϕ)))) ⊢ᴮ{ n0} χ) as IH1.\n        { specialize (IHproves n0 (lt_n_Sn _)).\n          set (C2 := (C0 ++ [CtxSemicL (fill C0 (frml (BOX (BOX ϕ))))] ++ Π)%B).\n          specialize (IHproves C2 _ _ H).\n          revert IHproves. rewrite /C2 !fill_app /=.\n          eauto. }\n        rewrite fill_app.\n        apply BI_Contr.\n        set (C2 := (C0 ++ [CtxSemicR (fill C0 (frml (BOX ϕ)))] ++ Π)%B).\n        replace (fill Π (fill C0 (frml (BOX ϕ));, fill C0 (frml (BOX ϕ))))%B\n                   with (fill C2 (frml (BOX ϕ)))%B by rewrite fill_app//.\n        eapply IHproves; eauto.\n        rewrite /C2 fill_app/=//.\n    - (* box L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        by apply BI_Higher.\n      + destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Box_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* box R *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_box in Heq.\n      destruct Heq as (Π' & -> & ->%bunch_decomp_correct).\n      change (frml (BOX ϕ)) with (BOX <·> (frml ϕ)).\n      rewrite -(bunch_map_fill BOX). apply BI_Box_R.\n      rewrite bunch_map_fill /=. eapply IHproves; eauto.\n      rewrite bunch_map_fill //.\n    - (* emp R *)\n      exfalso.\n      apply bunch_decomp_complete in Heq.\n      inversion Heq.\n    - (* emp L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Emp_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* sep R *)\n      apply bunch_decomp_complete in Heq.\n      inversion Heq; simplify_eq/=.\n      + rewrite fill_app /=.\n        eapply BI_Sep_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n      + rewrite fill_app /=.\n        eapply BI_Sep_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n    - (* sep L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Sep_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* wand R *)\n      apply BI_Wand_R.\n      assert ((fill Π (frml (BOX ϕ)),, frml ϕ0) =\n                   fill (Π ++ [CtxCommaL (frml ϕ0)]) (frml (BOX ϕ)))%B as ->.\n      { rewrite fill_app//. }\n      eapply IHproves; eauto. rewrite -Heq fill_app /= //.\n    - (* wand L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          eapply BI_Wand_L; eauto.\n          eapply IHproves; eauto; first lia.\n          by apply bunch_decomp_correct.\n        * exfalso. inversion H5.\n      + destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Wand_L; eauto.\n        rewrite -HC0.\n        eapply IHproves; eauto; first lia.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* bot L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_False_L.\n    - (* top R *) apply BI_True_R.\n    - (* top L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_True_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* conjR *)\n      apply bunch_decomp_complete in Heq.\n      inversion Heq; simplify_eq/=.\n      + rewrite fill_app /=.\n        eapply BI_Conj_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n      + rewrite fill_app /=.\n        eapply BI_Conj_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n    - (* conjL *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Conj_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* disj R 1 *)\n      eapply BI_Disj_R1.\n      eapply IHproves; eauto.\n    - (* disj R 2 *)\n      eapply BI_Disj_R2.\n      eapply IHproves; eauto.\n    - (* disj L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Disj_L.\n        * rewrite -HC0.\n          eapply IHproves; eauto; first lia.\n          apply bunch_decomp_correct. apply Hdec0.\n        * rewrite -HC0.\n          eapply IHproves; eauto; first lia.\n          apply bunch_decomp_correct. apply Hdec0.\n    - (* impl R *)\n      apply BI_Impl_R.\n      assert ((fill Π (frml (BOX ϕ));, frml ϕ0) =\n                   fill (Π ++ [CtxSemicL (frml ϕ0)]) (frml (BOX ϕ)))%B as ->.\n      { rewrite fill_app//. }\n      eapply IHproves; eauto. rewrite -Heq fill_app /= //.\n    - (* impl L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          eapply BI_Impl_L; eauto.\n          eapply IHproves; eauto; first lia.\n          by apply bunch_decomp_correct.\n        * exfalso. inversion H5.\n      + destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Impl_L; eauto.\n        rewrite -HC0.\n        eapply IHproves; eauto; first lia.\n        apply bunch_decomp_correct. apply Hdec0.\n  Qed.\n\n  Lemma sep_l_inv' Δ Π ϕ ψ χ n :\n    (Δ ⊢ᴮ{n} χ) →\n    Δ = fill Π (frml (SEP ϕ ψ)) →\n    (fill Π (frml ϕ,, frml ψ) ⊢ᴮ{n} χ).\n  Proof.\n    revert Π Δ χ.\n    induction n using lt_wf_ind. rename H into IHproves.\n    intros Π Δ χ PROOF Heq. symmetry in Heq. revert Heq.\n    inversion PROOF; simplify_eq/= => Heq.\n    (* induction H => C' Heq; symmetry in Heq. *)\n    - (* raising the pf height *)\n      apply BI_Higher.\n      eapply IHproves; eauto.\n    - (* axiom *)\n      apply fill_is_frml in Heq. destruct_and!; simplify_eq/=.\n      (* eapply BI_Sep_R; by econstructor. *)\n    - (* equivalence of bunches *)\n      simplify_eq/=.\n      destruct (bunch_equiv_fill _ _ _ H) as [C2 [-> HC2]].\n      eapply BI_Equiv.\n      { apply HC2. }\n      eapply IHproves; eauto.\n    - (* weakening *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          apply BI_Weaken.\n          rewrite -fill_app.\n          eapply IHproves; eauto.\n          by apply bunch_decomp_correct, bunch_decomp_app.\n        * rewrite !fill_app/=.\n          by apply BI_Weaken.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Weaken.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* contraction *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2]; last first.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Contr.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n      + rename Π0 into C'.\n        destruct H1 as [C0 [HC0 ->]].\n        apply bunch_decomp_correct in HC0.\n        simplify_eq/=.\n        assert (fill C' (fill C0 (frml ϕ,, frml ψ);, fill C0 (frml (SEP ϕ ψ))) ⊢ᴮ{ n0} χ) as IH1.\n        { specialize (IHproves n0 (lt_n_Sn _)).\n          set (C2 := (C0 ++ [CtxSemicL (fill C0 (frml (SEP ϕ ψ)))] ++ C')%B).\n          specialize (IHproves C2 _ _ H).\n          revert IHproves. rewrite /C2 !fill_app /=.\n          eauto. }\n        rewrite fill_app.\n        apply BI_Contr.\n        set (C2 := (C0 ++ [CtxSemicR (fill C0 (frml ϕ,, frml ψ))] ++ C')%B).\n        replace (fill C' (fill C0 (frml ϕ,, frml ψ);, fill C0 (frml ϕ,, frml ψ)))%B\n                   with (fill C2 (frml ϕ,, frml ψ))%B by rewrite fill_app//.\n        eapply IHproves; eauto.\n        rewrite /C2 fill_app//.\n    - (* box L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Box_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* box R *)\n      exfalso.\n      apply bunch_decomp_complete in Heq.\n      simplify_eq/=.\n      rename Δ0 into Δ. revert Π Heq. clear.\n      induction Δ as [ | | | Δ1 IH1 Δ2 IH2 | Δ1 IH1 Δ2 IH2] => Π /=;\n         inversion 1; simplify_eq/=;\n         solve [ by eapply IH1 | by eapply IH2 ].\n    - (* emp R *)\n      exfalso.\n      apply bunch_decomp_complete in Heq.\n      inversion Heq.\n    - (* emp L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Emp_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* sep R *)\n      apply bunch_decomp_complete in Heq.\n      inversion Heq; simplify_eq/=.\n      + rewrite fill_app /=.\n        eapply BI_Sep_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n      + rewrite fill_app /=.\n        eapply BI_Sep_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n    - (* sep L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        by apply BI_Higher.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Sep_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* wand R *)\n      apply BI_Wand_R.\n      assert ((fill Π (frml ϕ,, frml ψ),, frml ϕ0) =\n                   fill (Π ++ [CtxCommaL (frml ϕ0)]) (frml ϕ,, frml ψ))%B as ->.\n      { rewrite fill_app//. }\n      eapply IHproves; eauto. rewrite -Heq fill_app /= //.\n    - (* wand L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          eapply BI_Wand_L; eauto.\n          eapply IHproves; eauto; first lia.\n          by apply bunch_decomp_correct.\n        * exfalso. inversion H5.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Wand_L; eauto.\n        rewrite -HC0.\n        eapply IHproves; eauto; first lia.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* bot L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_False_L.\n    - (* top R *) apply BI_True_R.\n    - (* top L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_True_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* conjR *)\n      apply bunch_decomp_complete in Heq.\n      inversion Heq; simplify_eq/=.\n      + rewrite fill_app /=.\n        eapply BI_Conj_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n      + rewrite fill_app /=.\n        eapply BI_Conj_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n    - (* conjL *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Conj_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* disj R 1 *)\n      eapply BI_Disj_R1.\n      eapply IHproves; eauto.\n    - (* disj R 2 *)\n      eapply BI_Disj_R2.\n      eapply IHproves; eauto.\n    - (* disj L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Disj_L.\n        * rewrite -HC0.\n          eapply IHproves; eauto; first lia.\n          apply bunch_decomp_correct. apply Hdec0.\n        * rewrite -HC0.\n          eapply IHproves; eauto; first lia.\n          apply bunch_decomp_correct. apply Hdec0.\n    - (* impl R *)\n      apply BI_Impl_R.\n      assert ((fill Π (frml ϕ,, frml ψ);, frml ϕ0) =\n                   fill (Π ++ [CtxSemicL (frml ϕ0)]) (frml ϕ,, frml ψ))%B as ->.\n      { rewrite fill_app//. }\n      eapply IHproves; eauto. rewrite -Heq fill_app /= //.\n    -       apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          eapply BI_Impl_L; eauto.\n          eapply IHproves; eauto; first lia.\n          by apply bunch_decomp_correct.\n        * exfalso. inversion H5.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Impl_L; eauto.\n        rewrite -HC0.\n        eapply IHproves; eauto; first lia.\n        apply bunch_decomp_correct. apply Hdec0.\n  Qed.\n\n  Lemma conj_l_inv' Δ Π ϕ ψ χ n :\n    (Δ ⊢ᴮ{n} χ) →\n    Δ = fill Π (frml (CONJ ϕ ψ)) →\n    (fill Π (frml ϕ;, frml ψ) ⊢ᴮ{n} χ).\n  Proof.\n    revert Π Δ χ.\n    induction n using lt_wf_ind. rename H into IHproves.\n    intros Π Δ χ PROOF Heq. symmetry in Heq. revert Heq.\n    inversion PROOF; simplify_eq/= => Heq.\n    (* induction H => C' Heq; symmetry in Heq. *)\n    - (* raising the pf height *)\n      apply BI_Higher.\n      eapply IHproves; eauto.\n    - (* axiom *)\n      apply fill_is_frml in Heq. destruct_and!; simplify_eq/=.\n      (* eapply BI_Sep_R; by econstructor. *)\n    - (* equivalence of bunches *)\n      simplify_eq/=.\n      destruct (bunch_equiv_fill _ _ _ H) as [C2 [-> HC2]].\n      eapply BI_Equiv.\n      { apply HC2. }\n      eapply IHproves; eauto.\n    - (* weakening *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          apply BI_Weaken.\n          rewrite -fill_app.\n          eapply IHproves; eauto.\n          by apply bunch_decomp_correct, bunch_decomp_app.\n        * rewrite !fill_app/=.\n          by apply BI_Weaken.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Weaken.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* contraction *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2]; last first.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Contr.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n      + rename Π0 into C'.\n        destruct H1 as [C0 [HC0 ->]].\n        apply bunch_decomp_correct in HC0.\n        simplify_eq/=.\n        assert (fill C' (fill C0 (frml ϕ;, frml ψ);, fill C0 (frml (CONJ ϕ ψ))) ⊢ᴮ{ n0} χ) as IH1.\n        { specialize (IHproves n0 (lt_n_Sn _)).\n          set (C2 := (C0 ++ [CtxSemicL (fill C0 (frml (CONJ ϕ ψ)))] ++ C')%B).\n          specialize (IHproves C2 _ _ H).\n          revert IHproves. rewrite /C2 !fill_app /=.\n          eauto. }\n        rewrite fill_app.\n        apply BI_Contr.\n        set (C2 := (C0 ++ [CtxSemicR (fill C0 (frml ϕ;, frml ψ))] ++ C')%B).\n        replace (fill C' (fill C0 (frml ϕ;, frml ψ);, fill C0 (frml ϕ;, frml ψ)))%B\n                   with (fill C2 (frml ϕ;, frml ψ))%B by rewrite fill_app//.\n        eapply IHproves; eauto.\n        rewrite /C2 fill_app//.\n    - (* box L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Box_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* box R *)\n      exfalso.\n      apply bunch_decomp_complete in Heq.\n      simplify_eq/=.\n      rename Δ0 into Δ. revert Π Heq. clear.\n      induction Δ as [ | | | Δ1 IH1 Δ2 IH2 | Δ1 IH1 Δ2 IH2] => Π /=;\n         inversion 1; simplify_eq/=;\n         solve [ by eapply IH1 | by eapply IH2 ].\n    - (* emp R *)\n      exfalso.\n      apply bunch_decomp_complete in Heq.\n      inversion Heq.\n    - (* emp L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Emp_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* sep R *)\n      apply bunch_decomp_complete in Heq.\n      inversion Heq; simplify_eq/=.\n      + rewrite fill_app /=.\n        eapply BI_Sep_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n      + rewrite fill_app /=.\n        eapply BI_Sep_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n    - (* sep L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Sep_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* wand R *)\n      apply BI_Wand_R.\n      assert ((fill Π (frml ϕ;, frml ψ),, frml ϕ0) =\n                   fill (Π ++ [CtxCommaL (frml ϕ0)]) (frml ϕ;, frml ψ))%B as ->.\n      { rewrite fill_app//. }\n      eapply IHproves; eauto. rewrite -Heq fill_app /= //.\n    - (* wand L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          eapply BI_Wand_L; eauto.\n          eapply IHproves; eauto; first lia.\n          by apply bunch_decomp_correct.\n        * exfalso. inversion H5.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Wand_L; eauto.\n        rewrite -HC0.\n        eapply IHproves; eauto; first lia.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* bot L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_False_L.\n    - (* top R *) apply BI_True_R.\n    - (* top L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_True_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* conjR *)\n      apply bunch_decomp_complete in Heq.\n      inversion Heq; simplify_eq/=.\n      + rewrite fill_app /=.\n        eapply BI_Conj_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n      + rewrite fill_app /=.\n        eapply BI_Conj_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n    - (* conjL *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        by apply BI_Higher.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Conj_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* disj R 1 *)\n      eapply BI_Disj_R1.\n      eapply IHproves; eauto.\n    - (* disj R 2 *)\n      eapply BI_Disj_R2.\n      eapply IHproves; eauto.\n    - (* disj L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Disj_L.\n        * rewrite -HC0.\n          eapply IHproves; eauto; first lia.\n          apply bunch_decomp_correct. apply Hdec0.\n        * rewrite -HC0.\n          eapply IHproves; eauto; first lia.\n          apply bunch_decomp_correct. apply Hdec0.\n    - (* impl R *)\n      apply BI_Impl_R.\n      assert ((fill Π (frml ϕ;, frml ψ);, frml ϕ0) =\n                   fill (Π ++ [CtxSemicL (frml ϕ0)]) (frml ϕ;, frml ψ))%B as ->.\n      { rewrite fill_app//. }\n      eapply IHproves; eauto. rewrite -Heq fill_app /= //.\n    -       apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          eapply BI_Impl_L; eauto.\n          eapply IHproves; eauto; first lia.\n          by apply bunch_decomp_correct.\n        * exfalso. inversion H5.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Impl_L; eauto.\n        rewrite -HC0.\n        eapply IHproves; eauto; first lia.\n        apply bunch_decomp_correct. apply Hdec0.\n  Qed.\n\n  Lemma top_l_inv' Δ Π ϕ ψ χ n :\n    (Δ ⊢ᴮ{n} χ) →\n    Δ = fill Π (frml TOP) →\n    (fill Π top ⊢ᴮ{n} χ).\n  Proof.\n    revert Π Δ χ.\n    induction n using lt_wf_ind. rename H into IHproves.\n    intros Π Δ χ PROOF Heq. symmetry in Heq. revert Heq.\n    inversion PROOF; simplify_eq/= => Heq.\n    (* induction H => C' Heq; symmetry in Heq. *)\n    - (* raising the pf height *)\n      apply BI_Higher.\n      eapply IHproves; eauto.\n    - (* axiom *)\n      apply fill_is_frml in Heq. destruct_and!; simplify_eq/=.\n    - (* equivalence of bunches *)\n      simplify_eq/=.\n      destruct (bunch_equiv_fill _ _ _ H) as [C2 [-> HC2]].\n      eapply BI_Equiv.\n      { apply HC2. }\n      eapply IHproves; eauto.\n    - (* weakening *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          apply BI_Weaken.\n          rewrite -fill_app.\n          eapply IHproves; eauto.\n          by apply bunch_decomp_correct, bunch_decomp_app.\n        * rewrite !fill_app/=.\n          by apply BI_Weaken.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Weaken.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* contraction *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2]; last first.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Contr.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n      + rename Π0 into C'.\n        destruct H1 as [C0 [HC0 ->]].\n        apply bunch_decomp_correct in HC0.\n        simplify_eq/=.\n        assert (fill C' (fill C0 top;, fill C0 (frml TOP)) ⊢ᴮ{ n0} χ) as IH1.\n        { specialize (IHproves n0 (lt_n_Sn _)).\n          set (C2 := (C0 ++ [CtxSemicL (fill C0 (frml TOP))] ++ C')%B).\n          specialize (IHproves C2 _ _ H).\n          revert IHproves. rewrite /C2 !fill_app /=.\n          eauto. }\n        rewrite fill_app.\n        apply BI_Contr.\n        set (C2 := (C0 ++ [CtxSemicR (fill C0 top)] ++ C')%B).\n        replace (fill C' (fill C0 top;, fill C0 top))%B\n                   with (fill C2 top)%B by rewrite fill_app//.\n        eapply IHproves; eauto.\n        rewrite /C2 fill_app//.\n    - (* box L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Box_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* box R *)\n      exfalso.\n      apply bunch_decomp_complete in Heq.\n      simplify_eq/=.\n      rename Δ0 into Δ. revert Π Heq. clear.\n      induction Δ as [ | | | Δ1 IH1 Δ2 IH2 | Δ1 IH1 Δ2 IH2] => Π /=;\n         inversion 1; simplify_eq/=;\n         solve [ by eapply IH1 | by eapply IH2 ].\n    - (* emp R *)\n      exfalso.\n      apply bunch_decomp_complete in Heq.\n      inversion Heq.\n    - (* emp L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Emp_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* sep R *)\n      apply bunch_decomp_complete in Heq.\n      inversion Heq; simplify_eq/=.\n      + rewrite fill_app /=.\n        eapply BI_Sep_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n      + rewrite fill_app /=.\n        eapply BI_Sep_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n    - (* sep L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Sep_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* wand R *)\n      apply BI_Wand_R.\n      assert ((fill Π top,, frml ϕ0) =\n                   fill (Π ++ [CtxCommaL (frml ϕ0)]) top)%B as ->.\n      { rewrite fill_app//. }\n      eapply IHproves; eauto. rewrite -Heq fill_app /= //.\n    - (* wand L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          eapply BI_Wand_L; eauto.\n          eapply IHproves; eauto; first lia.\n          by apply bunch_decomp_correct.\n        * exfalso. inversion H5.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Wand_L; eauto.\n        rewrite -HC0.\n        eapply IHproves; eauto; first lia.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* bot L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_False_L.\n    - (* top R *) apply BI_True_R.\n    - (* top L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        by eapply BI_Higher.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_True_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* conjR *)\n      apply bunch_decomp_complete in Heq.\n      inversion Heq; simplify_eq/=.\n      + rewrite fill_app /=.\n        eapply BI_Conj_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n      + rewrite fill_app /=.\n        eapply BI_Conj_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n    - (* conjL *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Conj_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* disj R 1 *)\n      eapply BI_Disj_R1.\n      eapply IHproves; eauto.\n    - (* disj R 2 *)\n      eapply BI_Disj_R2.\n      eapply IHproves; eauto.\n    - (* disj L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Disj_L.\n        * rewrite -HC0.\n          eapply IHproves; eauto; first lia.\n          apply bunch_decomp_correct. apply Hdec0.\n        * rewrite -HC0.\n          eapply IHproves; eauto; first lia.\n          apply bunch_decomp_correct. apply Hdec0.\n    - (* impl R *)\n      apply BI_Impl_R.\n      assert ((fill Π top;, frml ϕ0) =\n                   fill (Π ++ [CtxSemicL (frml ϕ0)]) top)%B as ->.\n      { rewrite fill_app//. }\n      eapply IHproves; eauto. rewrite -Heq fill_app /= //.\n    -       apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          eapply BI_Impl_L; eauto.\n          eapply IHproves; eauto; first lia.\n          by apply bunch_decomp_correct.\n        * exfalso. inversion H5.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Impl_L; eauto.\n        rewrite -HC0.\n        eapply IHproves; eauto; first lia.\n        apply bunch_decomp_correct. apply Hdec0.\n  Qed.\n\n  Lemma emp_l_inv' Δ Π ϕ ψ χ n :\n    (Δ ⊢ᴮ{n} χ) →\n    Δ = fill Π (frml EMP) →\n    (fill Π empty ⊢ᴮ{n} χ).\n  Proof.\n    revert Π Δ χ.\n    induction n using lt_wf_ind. rename H into IHproves.\n    intros Π Δ χ PROOF Heq. symmetry in Heq. revert Heq.\n    inversion PROOF; simplify_eq/= => Heq.\n    (* induction H => C' Heq; symmetry in Heq. *)\n    - (* raising the pf height *)\n      apply BI_Higher.\n      eapply IHproves; eauto.\n    - (* axiom *)\n      apply fill_is_frml in Heq. destruct_and!; simplify_eq/=.\n    - (* equivalence of bunches *)\n      simplify_eq/=.\n      destruct (bunch_equiv_fill _ _ _ H) as [C2 [-> HC2]].\n      eapply BI_Equiv.\n      { apply HC2. }\n      eapply IHproves; eauto.\n    - (* weakening *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          apply BI_Weaken.\n          rewrite -fill_app.\n          eapply IHproves; eauto.\n          by apply bunch_decomp_correct, bunch_decomp_app.\n        * rewrite !fill_app/=.\n          by apply BI_Weaken.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Weaken.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* contraction *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2]; last first.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Contr.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n      + rename Π0 into C'.\n        destruct H1 as [C0 [HC0 ->]].\n        apply bunch_decomp_correct in HC0.\n        simplify_eq/=.\n        assert (fill C' (fill C0 empty;, fill C0 (frml EMP)) ⊢ᴮ{ n0} χ) as IH1.\n        { specialize (IHproves n0 (lt_n_Sn _)).\n          set (C2 := (C0 ++ [CtxSemicL (fill C0 (frml EMP))] ++ C')%B).\n          specialize (IHproves C2 _ _ H).\n          revert IHproves. rewrite /C2 !fill_app /=.\n          eauto. }\n        rewrite fill_app.\n        apply BI_Contr.\n        set (C2 := (C0 ++ [CtxSemicR (fill C0 empty)] ++ C')%B).\n        replace (fill C' (fill C0 empty;, fill C0 empty))%B\n                   with (fill C2 empty)%B by rewrite fill_app//.\n        eapply IHproves; eauto.\n        rewrite /C2 fill_app//.\n    - (* box L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Box_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* box R *)\n      exfalso.\n      apply bunch_decomp_complete in Heq.\n      simplify_eq/=.\n      rename Δ0 into Δ. revert Π Heq. clear.\n      induction Δ as [ | | | Δ1 IH1 Δ2 IH2 | Δ1 IH1 Δ2 IH2] => Π /=;\n         inversion 1; simplify_eq/=;\n         solve [ by eapply IH1 | by eapply IH2 ].\n    - (* emp R *)\n      exfalso.\n      apply bunch_decomp_complete in Heq.\n      inversion Heq.\n    - (* emp L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        by eapply BI_Higher.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Emp_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* sep R *)\n      apply bunch_decomp_complete in Heq.\n      inversion Heq; simplify_eq/=.\n      + rewrite fill_app /=.\n        eapply BI_Sep_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n      + rewrite fill_app /=.\n        eapply BI_Sep_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n    - (* sep L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Sep_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* wand R *)\n      apply BI_Wand_R.\n      assert ((fill Π empty,, frml ϕ0) =\n                   fill (Π ++ [CtxCommaL (frml ϕ0)]) empty)%B as ->.\n      { rewrite fill_app//. }\n      eapply IHproves; eauto. rewrite -Heq fill_app /= //.\n    - (* wand L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          eapply BI_Wand_L; eauto.\n          eapply IHproves; eauto; first lia.\n          by apply bunch_decomp_correct.\n        * exfalso. inversion H5.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Wand_L; eauto.\n        rewrite -HC0.\n        eapply IHproves; eauto; first lia.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* bot L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_False_L.\n    - (* true R *) apply BI_True_R.\n    - (* true L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_True_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* conjR *)\n      apply bunch_decomp_complete in Heq.\n      inversion Heq; simplify_eq/=.\n      + rewrite fill_app /=.\n        eapply BI_Conj_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n      + rewrite fill_app /=.\n        eapply BI_Conj_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n    - (* conjL *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Conj_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* disj R 1 *)\n      eapply BI_Disj_R1.\n      eapply IHproves; eauto.\n    - (* disj R 2 *)\n      eapply BI_Disj_R2.\n      eapply IHproves; eauto.\n    - (* disj L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Disj_L.\n        * rewrite -HC0.\n          eapply IHproves; eauto; first lia.\n          apply bunch_decomp_correct. apply Hdec0.\n        * rewrite -HC0.\n          eapply IHproves; eauto; first lia.\n          apply bunch_decomp_correct. apply Hdec0.\n    - (* impl R *)\n      apply BI_Impl_R.\n      assert ((fill Π empty;, frml ϕ0) =\n                   fill (Π ++ [CtxSemicL (frml ϕ0)]) empty)%B as ->.\n      { rewrite fill_app//. }\n      eapply IHproves; eauto. rewrite -Heq fill_app /= //.\n    -       apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          eapply BI_Impl_L; eauto.\n          eapply IHproves; eauto; first lia.\n          by apply bunch_decomp_correct.\n        * exfalso. inversion H5.\n      + rename Π0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Impl_L; eauto.\n        rewrite -HC0.\n        eapply IHproves; eauto; first lia.\n        apply bunch_decomp_correct. apply Hdec0.\n  Qed.\n\n(** Derivable rules / inversion lemmas *)\n\nLemma impl_r_inv Δ ϕ ψ :\n  (Δ ⊢ᴮ IMPL ϕ ψ) →\n  (Δ ;, frml ϕ ⊢ᴮ ψ)%B.\nProof.\n  intros [n H]%proves_provesN.\n  eapply provesN_proves.\n  by apply impl_r_inv'.\nQed.\nLemma wand_r_inv Δ ϕ ψ :\n  (Δ ⊢ᴮ WAND ϕ ψ) →\n  (Δ ,, frml ϕ ⊢ᴮ ψ)%B.\nProof.\n  intros [n H]%proves_provesN.\n  eapply provesN_proves.\n  by apply wand_r_inv'.\nQed.\nLemma sep_l_inv Π ϕ ψ χ :\n  (fill Π (frml (SEP ϕ ψ)) ⊢ᴮ χ) →\n  (fill Π (frml ϕ,, frml ψ) ⊢ᴮ χ).\nProof.\n  intros [n H]%proves_provesN.\n  eapply provesN_proves.\n  eapply sep_l_inv'; eauto.\nQed.\nLemma conj_l_inv Π ϕ ψ χ :\n  (fill Π (frml (CONJ ϕ ψ)) ⊢ᴮ χ) →\n  (fill Π (frml ϕ;, frml ψ) ⊢ᴮ χ).\nProof.\n  intros [n H]%proves_provesN.\n  eapply provesN_proves.\n  eapply conj_l_inv'; eauto.\nQed.\n\nLemma box_l_inv Π Δ ϕ :\n  (fill Π (BOX <·> (BOX <·> Δ)) ⊢ᴮ ϕ) →\n  (fill Π (BOX <·> Δ) ⊢ᴮ ϕ).\nProof.\n  revert Π. induction Δ; simpl; eauto.\n  - intros Π [n H]%proves_provesN.\n    eapply provesN_proves.\n    eapply box_l_inv'; eauto.\n  - intros Π H1.\n    replace (fill Π (BOX <·> Δ1,, (BOX <·> Δ2)))%B\n      with (fill (CtxCommaR (BOX <·> Δ1)::Π) (BOX <·> Δ2)) by reflexivity.\n    apply IHΔ2. simpl.\n    replace (fill Π (BOX <·> Δ1,, BOX <·> (BOX <·> Δ2)))%B\n      with (fill (CtxCommaL (BOX <·> (BOX <·> Δ2))::Π) (BOX <·> Δ1)) by reflexivity.\n    apply IHΔ1. simpl. done.\n  - intros Π H1.\n    replace (fill Π (BOX <·> Δ1;, (BOX <·> Δ2)))%B\n      with (fill (CtxSemicR (BOX <·> Δ1)::Π) (BOX <·> Δ2)) by reflexivity.\n    apply IHΔ2. simpl.\n    replace (fill Π (BOX <·> Δ1;, BOX <·> (BOX <·> Δ2)))%B\n      with (fill (CtxSemicL (BOX <·> (BOX <·> Δ2))::Π) (BOX <·> Δ1)) by reflexivity.\n    apply IHΔ1. simpl. done.\nQed.\n\nLemma collapse_l_inv Π Δ ϕ :\n  (fill Π (frml (collapse Δ)) ⊢ᴮ ϕ) →\n  (fill Π Δ ⊢ᴮ ϕ).\nProof.\n  revert Π. induction Δ; simpl; first done.\n  - intros Π [n H]%proves_provesN.\n    eapply provesN_proves.\n    eapply top_l_inv'; eauto.\n  - intros Π [n H]%proves_provesN.\n    eapply provesN_proves.\n    eapply emp_l_inv'; eauto.\n  - intros Π H1.\n    replace (fill Π (Δ1,, Δ2))%B\n      with (fill (CtxCommaR Δ1::Π) Δ2) by reflexivity.\n    apply IHΔ2. simpl.\n    replace (fill Π (Δ1,, frml (collapse Δ2)))%B\n      with (fill (CtxCommaL (frml (collapse Δ2))::Π) Δ1) by reflexivity.\n    apply IHΔ1. simpl.\n    by apply sep_l_inv.\n  - intros Π H1.\n    replace (fill Π (Δ1;, Δ2))%B\n      with (fill (CtxSemicR Δ1::Π) Δ2) by reflexivity.\n    apply IHΔ2. simpl.\n    replace (fill Π (Δ1;, frml (collapse Δ2)))%B\n      with (fill (CtxSemicL (frml (collapse Δ2))::Π) Δ1) by reflexivity.\n    apply IHΔ1. simpl.\n    by apply conj_l_inv.\nQed.\n\nEnd SeqcalcHeight.\n", "meta": {"author": "co-dan", "repo": "BI-cutelim", "sha": "cfbabc61a7a4b4c7e5bc7bb873fea4257949a76f", "save_path": "github-repos/coq/co-dan-BI-cutelim", "path": "github-repos/coq/co-dan-BI-cutelim/BI-cutelim-cfbabc61a7a4b4c7e5bc7bb873fea4257949a76f/theories/seqcalc_height_s4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.27477235899866037}}
{"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 Maps Integers Floats Lattice Kildall.\nRequire Import AST Linking Builtins.\nRequire Compopts Machregs.\nRequire Import Op Registers RTL RTLmach.\nRequire Import Liveness ValueDomain ValueAOp ValueAnalysis.\nRequire Import ConstpropOp.\n\n(** The code transformation builds on the results of the static analysis\n  of values from module [ValueAnalysis].  It proceeds instruction by\n  instruction.\n- Operators whose arguments are all statically known are turned into\n  ``load integer constant'', ``load float constant'' or ``load\n  symbol address'' operations.  Likewise for loads whose result can\n  be statically predicted.\n- Operators for which some but not all arguments are known are subject\n  to strength reduction (replacement by cheaper operators) and\n  similarly for the addressing modes of load and store instructions.\n- Cast operators that have no effect (because their arguments are\n  already normalized to the destination type) are removed.\n- Conditional branches and multi-way branches are statically resolved\n  into [Inop] instructions when possible.\n- Other instructions are unchanged.\n\n  In addition, we try to jump over conditionals whose condition can\n  be statically resolved based on the abstract state \"after\" the\n  instruction that branches to the conditional.  A typical example is:\n<<\n          1: x := 0 and goto 2\n          2: if (x == 0) goto 3 else goto 4\n>>\n    where other instructions branch into 2 with different abstract values\n    for [x].  We transform this code into:\n<<\n          1: x := 0 and goto 3\n          2: if (x == 0) goto 3 else goto 4\n>>\n*)\n\nDefinition transf_ros (ae: AE.t) (ros: reg + ident) : reg + ident :=\n  match ros with\n  | inl r =>\n      match areg ae r with\n      | Ptr(Gl symb ofs) => if Ptrofs.eq ofs Ptrofs.zero then inr _ symb else ros\n      | _ => ros\n      end\n  | inr s => ros\n  end.\n\nFixpoint successor_rec (n: nat) (f: function) (ae: AE.t) (pc: node) : node :=\n  match n with\n  | O => pc\n  | S n' =>\n      match f.(fn_code)!pc with\n      | Some (Inop s) =>\n          successor_rec n' f ae s\n      | Some (Icond cond args s1 s2) =>\n          match resolve_branch (eval_static_condition cond (aregs ae args)) with\n          | Some b => successor_rec n' f ae (if b then s1 else s2)\n          | None => pc\n          end\n      | _ => pc\n      end\n  end.\n\nDefinition num_iter := 10%nat.\n\nDefinition successor (f: function) (ae: AE.t) (pc: node) : node :=\n  successor_rec num_iter f ae pc.\n\nFixpoint builtin_arg_reduction (ae: AE.t) (a: builtin_arg reg) :=\n  match a with\n  | BA r =>\n      match areg ae r with\n      | I n => BA_int n\n      | L n => BA_long n\n      | F n => if Compopts.generate_float_constants tt then BA_float n else a\n      | FS n => if Compopts.generate_float_constants tt then BA_single n else a\n      | _ => a\n      end\n  | BA_splitlong hi lo =>\n      match builtin_arg_reduction ae hi, builtin_arg_reduction ae lo with\n      | BA_int nhi, BA_int nlo => BA_long (Int64.ofwords nhi nlo)\n      | hi', lo' => BA_splitlong hi' lo'\n      end\n  | BA_addptr a1 a2 =>\n      BA_addptr (builtin_arg_reduction ae a1) (builtin_arg_reduction ae a2)\n  | _ => a\n  end.\n\nDefinition builtin_arg_strength_reduction\n      (ae: AE.t) (a: builtin_arg reg) (c: builtin_arg_constraint) :=\n  let a' := builtin_arg_reduction ae a in\n  if builtin_arg_ok a' c then a' else a.\n\nFixpoint builtin_args_strength_reduction\n      (ae: AE.t) (al: list (builtin_arg reg)) (cl: list builtin_arg_constraint) :=\n  match al with\n  | nil => nil\n  | a :: al =>\n      builtin_arg_strength_reduction ae a (List.hd OK_default cl)\n      :: builtin_args_strength_reduction ae al (List.tl cl)\n  end.\n\n(** For debug annotations, add constant values to the original info\n    instead of replacing it. *)\n\nFixpoint debug_strength_reduction (ae: AE.t) (al: list (builtin_arg reg)) :=\n  match al with\n  | nil => nil\n  | a :: al =>\n      let a' := builtin_arg_reduction ae a in\n      let al' := a :: debug_strength_reduction ae al in\n      match a, a' with\n      | BA _, (BA_int _ | BA_long _ | BA_float _ | BA_single _) => a' :: al'\n      | _, _ => al'\n      end\n  end.\n\nDefinition builtin_strength_reduction\n             (ae: AE.t) (ef: external_function) (al: list (builtin_arg reg)) :=\n  match ef with\n  | EF_debug _ _ _ => debug_strength_reduction ae al\n  | _ => builtin_args_strength_reduction ae al (Machregs.builtin_constraints ef)\n  end.\n\n(*\nDefinition transf_builtin\n             (ae: AE.t) (am: amem) (rm: romem)\n             (ef: external_function)\n             (args: list (builtin_arg reg)) (res: builtin_res reg) (s: node) :=\n  let dfl := Ibuiltin ef (builtin_strength_reduction ae ef args) res s in\n  match ef, res with\n  | EF_builtin name sg, BR rd =>\n      match lookup_builtin_function name sg with\n      | Some bf => \n          match eval_static_builtin_function ae am rm bf args with\n          | Some a =>\n              match const_for_result a with\n              | Some cop => Iop cop nil rd s\n              | None => dfl\n              end\n          | None => dfl\n          end\n      | None => dfl\n      end\n  | _, _ => dfl\n  end.\n*)\n\nDefinition transf_instr (f: function) (an: PMap.t VA.t) (rm: romem)\n                        (pc: node) (instr: instruction) :=\n  match an!!pc with\n  | VA.Bot =>\n      instr\n  | VA.State ae am =>\n      match instr with\n      | Iop op args res s =>\n          let aargs := aregs ae args in\n          let a := eval_static_operation op aargs in\n          let s' := successor f (AE.set res a ae) s 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 aargs in\n              Iop op' args' res s'\n          end\n      | Iload chunk addr args dst s =>\n          let aargs := aregs ae args in\n          let a := ValueDomain.loadv chunk rm am (eval_static_addressing addr aargs) 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 aargs in\n              Iload chunk addr' args' dst s\n          end\n      | Istore chunk addr args src s =>\n          let aargs := aregs ae args in\n          let (addr', args') := addr_strength_reduction addr args aargs in\n          Istore chunk addr' args' src s\n      | Icall sig ros args res s =>\n          Icall sig (transf_ros ae ros) args res s\n      | Itailcall sig ros args =>\n          Itailcall sig (transf_ros ae ros) args\n      | Ibuiltin ef args res s =>\n          let dfl := Ibuiltin ef (builtin_strength_reduction ae ef args) res s in\n          match ef, res with\n          | EF_builtin name sg, BR rd =>\n              match lookup_builtin_function name sg with\n              | Some bf => \n                  match eval_static_builtin_function ae am rm bf args with\n                  | Some a =>\n                      match const_for_result a with\n                      | Some cop => Iop cop nil rd s\n                      | None => dfl\n                      end\n                 | None => dfl\n                 end\n             | None => dfl\n             end\n          | _, _ => dfl\n          end\n      | Icond cond args s1 s2 =>\n          let aargs := aregs ae args in\n          match resolve_branch (eval_static_condition cond aargs) with\n          | Some b =>\n              if b then Inop s1 else Inop s2\n          | None =>\n              let (cond', args') := cond_strength_reduction cond args aargs in\n              Icond cond' args' s1 s2\n          end\n      | Ijumptable arg tbl =>\n          match areg ae 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  end.\n\nDefinition transf_function (rm: romem) (f: function) : function :=\n  let an := ValueAnalysis.analyze rm f in\n  mkfunction\n    f.(fn_sig)\n    f.(fn_params)\n    f.(fn_stacksize)\n    (PTree.map (transf_instr f an rm) f.(fn_code))\n    f.(fn_entrypoint).\n\nDefinition transf_fundef (rm: romem) (fd: fundef) : fundef :=\n  AST.transf_fundef (transf_function rm) fd.\n\nDefinition transf_program (p: program) : program :=\n  let rm := romem_for p in\n  transform_program (transf_fundef rm) p.\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/Constprop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.27475055564292195}}
{"text": "Require Import GL4ip_PSGL4ip_calcs.\nRequire Import List.\nExport ListNotations.\n\nRequire Import genT gen.\nRequire Import ddT.\nRequire Import gen_tacs.\nRequire Import gen_seq.\nRequire Import List_lemmasT.\nRequire Import existsT.\nRequire Import univ_gen_ext.\nRequire Import GL4ip_PSGL4ip_list_lems.\nRequire Import dd_fc.\nRequire Import PeanoNat.\nRequire Import Coq.Init.Nat.\nRequire Import strong_inductionT.\nRequire Import PSGL4ip_termination_measure.\nRequire Import GL4ip_PSGL4ip_remove_list.\nRequire Import GL4ip_PSGL4ip_dec.\nRequire Import Lia.\n\nDelimit Scope My_scope with M.\nOpen Scope My_scope.\nSet Implicit Arguments.\n\nDefinition proj1_sigT2 {A : Type} (P : A -> Type) (e:sigT P) := match e with\n                                    | existT _ a b => a\n                                    end.\n\nDefinition proj2_sigT2 {A : Type} (P : A -> Type) (e : sigT P) :=\n  match e return (P (proj1_sigT2 e)) with\n  | existT _ a b => b\n  end.\n\nLemma In_InT : forall (A : MPropF V) l, In A l -> InT A l.\nProof.\nintros. apply in_splitT in H. destruct H. destruct s. subst. apply InT_or_app. right.\napply InT_eq.\nQed.\n\nLemma In_InT_pair : forall (A : MPropF V) (n : nat) l, In (A, n) l -> InT (A, n) l.\nProof.\ninduction l.\n- intro. inversion H.\n- intro. assert ({(A, n) = a} + {(A, n) <> a}). destruct a.\n  destruct (eq_dec_form A m). subst. destruct (eq_dec_nat n n0). subst. auto.\n  right. intro. apply n1. inversion H0. auto. right. intro. inversion H0.\n  auto. destruct H0. subst. apply InT_eq. apply InT_cons. apply IHl.\n  inversion H. exfalso. auto. assumption.\nQed.\n\nLemma dec_le : forall n m, (n <= m) + ((n <= m) -> False).\nProof.\ninduction n.\n- intro m. left. apply le_0_n.\n- intro m. pose (IHn m). destruct s.\n  * destruct (eq_dec_nat n m). subst. right. intro. lia. left. lia.\n  * right. intro. apply f. lia.\nQed.\n\nLemma InT_map_iff : forall {A B : Type} (f : A -> B) (l : list A) (y : B),\n       (InT y (map f l) -> (existsT2 x : A, (f x = y) * InT x l)) *\n       ((existsT2 x : A, (f x = y) * InT x l) -> InT y (map f l)).\nProof.\ninduction l.\n- intros. simpl. split. intro. inversion X. intro. destruct X. destruct p. inversion i.\n- simpl. intros. split.\n  * intro. inversion X.\n    + subst. exists a. split ; [ reflexivity | apply InT_eq].\n    + subst. pose (IHl y). destruct p. apply s in X0. destruct X0. destruct p. exists x.\n      split. assumption. apply InT_cons. assumption.\n  * intro. pose (IHl y). destruct p. clear s. pose (proj2_sigT2 X).\n    destruct p. inversion i0. subst. rewrite <- e. rewrite <- H0. apply InT_eq.\n    subst. assert (existsT2 x : A, (f x = y) * InT x l). exists (proj1_sigT2 X).\n    split ; assumption. apply i in X1. apply InT_cons. assumption.\nQed.\n\nLemma le_False_lt : forall n m, ((n <= m) -> False) -> (m < n).\nProof.\ninduction n.\n- intros. exfalso. apply H. apply le_0_n.\n- induction m.\n  * intros. lia.\n  * intros. apply Lt.lt_n_S. apply IHn. intro. apply H. apply Le.le_n_S. assumption.\nQed.\n\nLemma top_boxes_nobox_gen_ext : forall l, nobox_gen_ext (top_boxes l) l.\nProof.\ninduction l.\n- simpl. apply univ_gen_ext_nil.\n- destruct a ; simpl.\n  * apply univ_gen_ext_extra. intro. inversion X. inversion H. assumption.\n  * apply univ_gen_ext_extra. intro. inversion X. inversion H. assumption.\n  * apply univ_gen_ext_extra. intro. inversion X. inversion H. assumption.\n  * apply univ_gen_ext_extra. intro. inversion X. inversion H. assumption.\n  * apply univ_gen_ext_extra. intro. inversion X. inversion H. assumption.\n  * apply univ_gen_ext_cons. assumption.\nQed.\n\nLemma nobox_gen_ext_top_boxes_identity : forall l0 l1, nobox_gen_ext l0 l1 ->\n                                                       is_Boxed_list l0 ->\n                                                       (l0 = top_boxes l1).\nProof.\nintros l0 l1 X. induction X.\n- intros. reflexivity.\n- intro. simpl. destruct x.\n  * exfalso. pose (H (# v)). assert (In # v (# v :: l)). apply in_eq. apply e in H0.\n    destruct H0. inversion H0.\n  * exfalso. pose (H (⊥ V)). assert (In (⊥ V) (⊥ V :: l)). apply in_eq. apply e in H0.\n    destruct H0. inversion H0.\n  * exfalso. pose (H (x1 ∧ x2)). assert (In (x1 ∧ x2) (x1 ∧ x2 :: l)). apply in_eq. apply e in H0.\n    destruct H0. inversion H0.\n  * exfalso. pose (H (x1 ∨ x2)). assert (In (x1 ∨ x2) (x1 ∨ x2 :: l)). apply in_eq. apply e in H0.\n    destruct H0. inversion H0.\n  * exfalso. pose (H (x1 → x2)). assert (In (x1 → x2) (x1 → x2 :: l)). apply in_eq. apply e in H0.\n    destruct H0. inversion H0.\n  * assert (l = top_boxes le). apply IHX. intro. intros. apply H. apply in_cons. assumption.\n    rewrite H0. reflexivity.\n- simpl. destruct x.\n  * apply IHX.\n  * apply IHX.\n  * apply IHX.\n  * apply IHX.\n  * apply IHX.\n  * exfalso. apply p. exists x. reflexivity.\nQed.\n\nFixpoint flatten_list {A : Type} (l : list (list A)) : list A :=\n  match l with\n  | [ ] => [ ]\n  | h :: t => h ++ (flatten_list t)\n  end\n.\n\nLemma InT_flatten_list_InT_elem {A : Type} : forall (l : list (list A)) b,\n        InT b (flatten_list l) -> (existsT2 bs, (InT b bs) * (InT bs l)).\nProof.\ninduction l.\n- intros. simpl in X. inversion X.\n- intros. simpl in X. apply InT_app_or in X. destruct X.\n  * exists a. split ; [assumption | apply InT_eq].\n  * pose (IHl b). apply s in i. destruct i. destruct p. exists x. split ; [assumption | apply InT_cons ; assumption].\nQed.\n\nLemma redundant_flatten_list : forall ls (s : (list (MPropF V)) * (MPropF V)), map (fun z : list (MPropF V) * (MPropF V) => [z;s]) ls =\nflatten_list (map (fun y : list (MPropF V) * (MPropF V) => [[y;s]]) ls).\nProof.\ninduction ls.\n- intros. simpl. reflexivity.\n- simpl. intros. rewrite IHls. reflexivity.\nQed.\n\nLemma InT_trans_flatten_list {A : Type} : forall (l : list (list A)) bs b,\n        (InT b bs) -> (InT bs l) -> (InT b (flatten_list l)).\nProof.\ninduction l.\n- intros. inversion X0.\n- intros. inversion X0.\n  * subst. simpl. apply InT_or_app. auto.\n  * subst. simpl. apply InT_or_app. right. pose (IHl bs b X X1) ; assumption.\nQed.\n\n(* In this file we prove that each sequent Γ |- Δ has a derivation (not proof) D in\n   PSGL4ip of maximal height: all derivations in PSGL4ip of this sequent must have an\n   inferior or equal height to that of D.\n\n   This result can be understood as claiming that the proof search defined by PSGL4ip\n   terminates. *)\n\n(* The next lemma claims that for each sequent s there is a derivation of that sequent. *)\n\nLemma der_s_inhabited : forall s, inhabited (derrec PSGL4ip_rules (fun _ => True) s).\nProof.\nintros s.\npose (@dpI ((list (MPropF V)) *(MPropF V) ) PSGL4ip_rules (fun _ : ((list (MPropF V)) *(MPropF V)) => True) s).\nassert (H: (fun _ : ((list (MPropF V)) *(MPropF V) ) => True) s). apply I. apply d in H. apply inhabits. assumption.\nQed.\n\n(* The next definition deals with the property of being a derivation D0 of maximal height\n   for the sequent s. *)\n\nDefinition is_mhd (s: (list (MPropF V)) * (MPropF V)) (D0 : derrec (PSGL4ip_rules) (fun _ => True) s): Prop :=\n      forall (D1 : derrec (PSGL4ip_rules) (fun _ => True) s), derrec_height D1 <= derrec_height D0.\n\n\n(* The next lemma says that given a list and an element, there are only finitely many\n   ways to insert this element in a list. *)\n\nLemma list_of_splits : forall (l : list (MPropF V)), existsT2 listSplits,\n                            forall l1 l2, ((l1 ++ l2 = l) <-> In (l1, l2) listSplits).\nProof.\ninduction l.\n- exists [([],[])]. intros. destruct l1. split ; intro. simpl in H. rewrite H. apply in_eq.\n  simpl in H. destruct H. inversion H. reflexivity. inversion H. split ; intro.\n  simpl in H. inversion H. simpl. inversion H. inversion H0. inversion H0.\n- destruct IHl. exists ([([], a :: l)] ++ (map (fun y => (a :: (fst y), snd y)) x)).\n  intros. split ; intro.\n  * apply in_or_app. destruct l1. simpl. left. left. simpl in H. rewrite H.\n    reflexivity. simpl in H. inversion H. subst. right. pose (i l1 l2). destruct i0.\n    assert (l1 ++ l2 = l1 ++ l2). reflexivity. apply H0 in H2.\n    pose (in_map (fun y : list (MPropF V) * list (MPropF V) => (a :: fst y, snd y)) x (l1, l2) H2).\n    simpl in i. assumption.\n  * simpl in H. destruct H. inversion H. simpl. reflexivity. rewrite in_map_iff in H.\n    destruct H. destruct H. inversion H. subst. simpl. pose (i (fst x0) (snd x0)).\n    destruct i0. assert ((fst x0, snd x0) = x0). destruct x0. simpl. reflexivity.\n    rewrite H3 in H2. apply H2 in H0. rewrite H0. reflexivity.\nQed.\n\nDefinition listInserts l (A : MPropF V) := map (fun y => (fst y) ++ A :: (snd y)) (proj1_sigT2 (list_of_splits l)).\n\n(* The next two lemmas make sure that the definition listInserts indeed captures the intended\n   list. *)\n\nLemma listInserts_In : forall l (A: MPropF V) l1 l2, ((l1 ++ l2 = l) -> In (l1 ++ A :: l2) (listInserts l A)).\nProof.\nintros. unfold listInserts. assert (In (l1, l2) (proj1_sigT2 (list_of_splits l))). destruct (list_of_splits l).\nsimpl. pose (i l1 l2). apply i0. assumption.\npose (in_map (fun y : list (MPropF V) * list (MPropF V) => fst y ++ A :: snd y) (proj1_sigT2 (list_of_splits l)) (l1, l2) H0).\nsimpl in i. assumption.\nQed.\n\nLemma listInserts_InT : forall l (A: MPropF V) l1 l2, ((l1 ++ l2 = l) -> InT (l1 ++ A :: l2) (listInserts l A)).\nProof.\nintros. unfold listInserts. assert (InT (l1, l2) (proj1_sigT2 (list_of_splits l))). destruct (list_of_splits l). apply In_InT_seqs.\nsimpl. pose (i l1 l2). apply i0. assumption.\npose (InT_map (fun y : list (MPropF V) * list (MPropF V) => fst y ++ A :: snd y) H0).\nsimpl in i. assumption.\nQed.\n\nLemma In_listInserts : forall l (A: MPropF V) l0, In l0 (listInserts l A) ->\n                            (exists l1 l2, prod (l1 ++ l2 = l) (l1 ++ A :: l2 = l0)).\nProof.\nintros. unfold listInserts in H. destruct (list_of_splits l). simpl in H. rewrite in_map_iff in H.\ndestruct H. destruct H. subst. exists (fst x0). exists (snd x0). split. apply i.\ndestruct x0. simpl. assumption. reflexivity.\nQed.\n\nLemma InT_listInserts : forall l (A: MPropF V) l0, InT l0 (listInserts l A) ->\n                            (existsT2 l1 l2, prod (l1 ++ l2 = l) (l1 ++ A :: l2 = l0)).\nProof.\nintros. unfold listInserts in H. destruct (list_of_splits l). simpl in H. apply InT_map_iff in H.\ndestruct H. subst. exists (fst x0). exists (snd x0). split. apply i.\ndestruct x0. destruct p. simpl. apply InT_In ; auto. destruct p. subst. reflexivity.\nQed.\n\n(* The definitions below allow you to create the list of all sequents given two lists and a\n   formula to insert in one of them. *)\n\nDefinition listInsertsL_Seqs (Γ : list (MPropF V)) (A C : MPropF V) := map (fun y => (y, C)) (listInserts Γ A).\n\nFixpoint remove_nth (n: nat) (A : MPropF V) l:=\n    match n with\n      | 0 => l\n      | 1 => match l with\n               | [] => []\n               | B::tl => if (eq_dec_form A B) then tl else B:: tl\n             end\n      | S m => match l with\n                 | [] => []\n                 | B::tl => B::(remove_nth m A tl)\n               end\n      end.\n\nFixpoint nth_split (n : nat) (l : list (MPropF V)) : (list (MPropF V) * list (MPropF V)) :=\n    match n with\n      | 0 => ([], l)\n      | 1 => match l with\n               | [] => ([], [])\n               | B::tl => ([B] , tl)\n             end\n      | S m => match l with\n                 | [] => ([], [])\n                 | B::tl => (B :: (fst (nth_split m tl)), snd (nth_split m tl))\n               end\n      end.\n\nLemma nth_split_length : forall (l0 l1 : list (MPropF V)), (nth_split (length l0) (l0 ++ l1)) = (l0, l1).\nProof.\ninduction l0.\n- intros. simpl. reflexivity.\n- intros. pose (IHl0 l1). simpl (length (a :: l0)). simpl ((a :: l0) ++ l1).\n  simpl. destruct l0.\n  * simpl. reflexivity.\n  * assert (match length (m :: l0) with\n| 0 => ([a], (m :: l0) ++ l1)\n| S _ =>\n    (a :: fst (nth_split (length (m :: l0)) ((m :: l0) ++ l1)),\n    snd (nth_split (length (m :: l0)) ((m :: l0) ++ l1)))\nend = (a :: fst (nth_split (length (m :: l0)) ((m :: l0) ++ l1)),\n    snd (nth_split (length (m :: l0)) ((m :: l0) ++ l1)))). reflexivity. rewrite H.\nclear H. rewrite e. simpl. reflexivity.\nQed.\n\nLemma effective_remove_nth : forall A l0 l1, ((remove_nth (S (length l0)) A (l0 ++ A :: l1)) = l0 ++ l1).\nProof.\ninduction l0.\n- intros. simpl. destruct (eq_dec_form A A). reflexivity. exfalso. auto.\n- intros. simpl (S (length (a :: l0))). repeat rewrite <- app_assoc. simpl ((a :: l0) ++ A :: l1).\n  pose (IHl0 l1). simpl ((a :: l0) ++ l1). rewrite <- e. simpl. reflexivity.\nQed.\n\nLemma nth_split_idL : forall (l0 l1 : list (MPropF V)), l0 = fst (nth_split (length l0) (l0 ++ l1)).\nProof.\ninduction l0.\n- intros. simpl. reflexivity.\n- intros. simpl (length (a :: l0)). pose (IHl0 l1). assert (fst (nth_split (S (length l0)) ((a :: l0) ++ l1)) =\n  a :: fst (nth_split (length l0) (l0 ++ l1))). simpl. destruct l0. simpl. reflexivity.\n  simpl. reflexivity. rewrite H. rewrite <- e. reflexivity.\nQed.\n\nLemma nth_split_idR : forall (l0 l1 : list (MPropF V)), l1 = snd (nth_split (length l0) (l0 ++ l1)).\nProof.\ninduction l0.\n- intros. simpl. reflexivity.\n- intros. simpl (length (a :: l0)). pose (IHl0 l1). rewrite e. destruct l0.\n  * simpl. reflexivity.\n  * simpl (length (m :: l0)). simpl (S (S (length l0))).\n    simpl (length (m :: l0)) in e. rewrite <- e.\n    assert ((S (S (length l0))) = (length (a :: m :: l0))). simpl. reflexivity.\n    rewrite H. rewrite nth_split_length. simpl. reflexivity.\nQed.\n\nLemma nth_split_length_id : forall (l0 l1 : list (MPropF V)) n, (length l0 = n) ->\n                                (fst (nth_split n (l0 ++ l1)) = l0 /\\\n                                snd (nth_split n (l0 ++ l1)) = l1).\nProof.\ninduction l0.\n- intros. simpl. split. simpl in H. subst. simpl. reflexivity. simpl in H. subst. simpl. reflexivity.\n- intros. simpl in H. subst. split.\n  * assert (J1:length l0 = length l0). reflexivity. pose (@IHl0 l1 (length l0) J1).\n    destruct a0. simpl. destruct l0. simpl. reflexivity. simpl. rewrite <- H.\n    simpl. reflexivity.\n  * assert (J1:length l0 = length l0). reflexivity. pose (@IHl0 l1 (length l0) J1).\n    destruct a0. rewrite <- H0. simpl ((a :: l0) ++ snd (nth_split (length l0) (l0 ++ l1))).\n    assert ((nth_split (S (length l0)) (a :: l0 ++ snd (nth_split (length l0) (l0 ++ l1))) =\n    (a :: l0 ,snd (nth_split (length l0) (l0 ++ l1))))).\n    pose (nth_split_length (a :: l0) (snd (nth_split (length l0) (l0 ++ l1)))). apply e.\n    rewrite H1. simpl. reflexivity.\nQed.\n\n\n\n\n\n(*------------------------------------------------------------------------------------------------------------------------------------------------------------------- *)\n\n\n\n\n\n(* And rules *)\n\n(* Let's start with AndR *)\n\nDefinition prems_And_R (s : (list (MPropF V)) * (MPropF V)) : list (list ((list (MPropF V)) * (MPropF V))) :=\nmatch (snd s) with\n  | And A B => [[(fst s, A);(fst s, B)]]\n  | _ => nil\nend.\n\nLemma finite_AndR_premises_of_S : forall (s : (list (MPropF V)) * (MPropF V)), existsT2 listAndRprems,\n              (forall prems, ((AndRRule prems s) -> (InT prems listAndRprems)) *\n                             ((InT prems listAndRprems) -> (AndRRule prems s))).\nProof.\nintro s.\nexists (prems_And_R s). intros. split ; intros. inversion H. subst. unfold prems_And_R.\nsimpl. apply InT_eq. unfold prems_And_R in H. destruct s. simpl in H.\ndestruct m. 1-2: inversion H. 2-4: inversion H. inversion H. subst. apply AndRRule_I.\ninversion H1.\nQed.\n\n\n\n(* And now AndL *)\n\nFixpoint top_ands (l : list (MPropF V)) : list (MPropF V) :=\nmatch l with\n  | nil => nil\n  | h :: t => match h with\n                | And A B => (And A B) :: top_ands t\n                | _ => top_ands t\n              end\nend.\n\nFixpoint pos_top_ands (l : list (MPropF V)) : (list ((MPropF V) * nat)) :=\nmatch l with\n  | nil => nil\n  | h :: t => match h with\n                | And A B => (And A B, 1) :: (map (fun y => (fst y, S (snd y))) (pos_top_ands t))\n                | _ => (map (fun y => (fst y, S  (snd y))) (pos_top_ands t))\n              end\nend.\n\nFixpoint prems_And_L (l : list ((MPropF V) * nat)) (s : (list (MPropF V)) * (MPropF V)) : list ((list (MPropF V)) * (MPropF V)) :=\nmatch l with\n  | nil => nil\n  | (C, n) :: t => match n with\n      | 0 => prems_And_L t s\n      | S m => match C with\n           | And A B => ((fst (nth_split m (remove_nth (S m) C (fst s)))) ++ A :: B :: (snd (nth_split m (remove_nth (S m) C (fst s)))) , snd s)\n                                :: (prems_And_L t s)\n           | _ => prems_And_L t s\n           end\n      end\nend.\n\nLemma In_pos_top_ands_0_False : forall l (A : MPropF V), In (A, 0) (pos_top_ands l) -> False.\nProof.\n- induction l.\n  * intros. inversion H.\n  * intros. simpl in H. destruct a.\n    1-2: simpl in H ; apply In_InT_pair in H ; apply InT_map_iff in H ; destruct H ;\n    destruct p ; destruct x ; inversion e.\n    2-4: simpl in H ; apply In_InT_pair in H ; apply InT_map_iff in H ; destruct H ;\n    destruct p ; destruct x ; inversion e.\n    simpl in H. destruct H. inversion H. apply In_InT_pair in H. apply InT_map_iff in H. destruct H.\n    destruct p. destruct x. inversion e.\nQed.\n\nLemma In_pos_top_ands_split_l : forall l (A : MPropF V) n, In (A, S n) (pos_top_ands l) -> \n          existsT2 l0 l1, (l = l0 ++ A :: l1) *\n                          (length l0 = n) *\n                          (l0 = fst (nth_split n (remove_nth (S n) A l))) *\n                          (l1 = snd (nth_split n (remove_nth (S n) A l))).\nProof.\ninduction l.\n- intros. simpl. exfalso. simpl in H. destruct H.\n- intros. simpl in H. destruct a.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_ands_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (# v :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (# v :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n    # v :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (# v :: x))). simpl. reflexivity.\n    rewrite H0. assert ((# v :: x ++ A :: x0) = ((# v :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (# v :: x) x0). simpl (length (# v :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (# v :: x))). simpl. reflexivity.\n    rewrite H. assert ((# v :: x ++ A :: x0) = ((# v :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (# v :: x) x0). simpl (length (# v :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_ands_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (⊥ V :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (⊥ V :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      ⊥ V :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (⊥ V :: x))). simpl. reflexivity.\n    rewrite H0. assert ((⊥ V :: x ++ A :: x0) = ((⊥ V :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (⊥ V :: x) x0). simpl (length (⊥ V :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (⊥ V :: x))). simpl. reflexivity.\n    rewrite H. assert ((⊥ V :: x ++ A :: x0) = ((⊥ V :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (⊥ V :: x) x0). simpl (length (⊥ V :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. inversion H.\n    + inversion H1. subst. exists []. exists l. repeat split. simpl.\n      destruct (eq_dec_form (a1 ∧ a2) (a1 ∧ a2)). reflexivity. exfalso. auto.\n    + subst. apply InT_map_iff in H1. destruct H1. destruct p.\n      destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n      apply InT_In in i. apply In_pos_top_ands_0_False in i. assumption.\n      apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n      subst. exists (a1 ∧ a2 :: x). exists x0. repeat split.\n      rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n      assert (fst (a1 ∧ a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      a1 ∧ a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n      assert (S (S (length x)) = S (length (a1 ∧ a2 :: x))). simpl. reflexivity.\n      rewrite H1. assert ((a1 ∧ a2 :: x ++ A :: x0) = ((a1 ∧ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n      rewrite H2. clear H2. clear H1. rewrite effective_remove_nth.\n      pose (nth_split_idL (a1 ∧ a2 :: x) x0). simpl (length (a1 ∧ a2 :: x)) in e2.\n      rewrite <- e2. reflexivity.\n      rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n      assert (S (S (length x)) = S (length (a1 ∧ a2 :: x))). simpl. reflexivity.\n      rewrite H0. assert ((a1 ∧ a2 :: x ++ A :: x0) = ((a1 ∧ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n      rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n      pose (nth_split_idR (a1 ∧ a2 :: x) x0). simpl (length (a1 ∧ a2 :: x)) in e2.\n      rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_ands_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (a1 ∨ a2 :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (a1 ∨ a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      a1 ∨ a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (a1 ∨ a2 :: x))). simpl. reflexivity.\n    rewrite H0. assert ((a1 ∨ a2 :: x ++ A :: x0) = ((a1 ∨ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (a1 ∨ a2 :: x) x0). simpl (length (a1 ∨ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (a1 ∨ a2 :: x))). simpl. reflexivity.\n    rewrite H. assert ((a1 ∨ a2 :: x ++ A :: x0) = ((a1 ∨ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (a1 ∨ a2 :: x) x0). simpl (length (a1 ∨ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_ands_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (a1 → a2 :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (a1 → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      a1 → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (a1 → a2 :: x))). simpl. reflexivity.\n    rewrite H0. assert ((a1 → a2 :: x ++ A :: x0) = ((a1 → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (a1 → a2 :: x) x0). simpl (length (a1 → a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (a1 → a2 :: x))). simpl. reflexivity.\n    rewrite H. assert ((a1 → a2 :: x ++ A :: x0) = ((a1 → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (a1 → a2 :: x) x0). simpl (length (a1 → a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_ands_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (Box a :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (Box a :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n    Box a :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (Box a :: x))). simpl. reflexivity.\n    rewrite H0. assert ((Box a :: x ++ A :: x0) = ((Box a :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (Box a :: x) x0). simpl (length (Box a :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (Box a :: x))). simpl. reflexivity.\n    rewrite H. assert ((Box a :: x ++ A :: x0) = ((Box a :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (Box a :: x) x0). simpl (length (Box a :: x)) in e2.\n    rewrite <- e2. reflexivity.\nQed.\n\nLemma Good_pos_in_pos_top_ands : forall A B Γ0 Γ1,\n              In (And A B, S (length Γ0)) (pos_top_ands (Γ0 ++ And A B :: Γ1)).\nProof.\ninduction Γ0.\n- intros. simpl. auto.\n- intros. destruct a.\n  1-2: simpl ; apply InT_In ; apply InT_map_iff ; exists (And A B, S (length Γ0)) ;\n  split ; simpl ; try reflexivity ; apply In_InT_pair ; apply IHΓ0.\n  2-4: simpl ; apply InT_In ; apply InT_map_iff ; exists (And A B, S (length Γ0)) ;\n  split ; simpl ; try reflexivity ; apply In_InT_pair ; apply IHΓ0.\n  simpl. right. apply InT_In. apply InT_map_iff. exists (And A B, S (length Γ0)).\n  split. simpl. reflexivity. apply In_InT_pair. apply IHΓ0.\nQed.\n\nLemma AndL_help01 : forall prem s l, InT prem (prems_And_L l s) ->\n                  (existsT2 n A B Γ0 Γ1 C,\n                        (In (And A B, S n) l) *\n                        (prem = (Γ0 ++ A :: B :: Γ1, C)) *\n                        (C = snd s) *\n                        (Γ0 = (fst (nth_split n (remove_nth (S n) (And A B) (fst s))))) *\n                        (Γ1 = (snd (nth_split n (remove_nth (S n) (And A B) (fst s)))))).\nProof.\nintros prem s. destruct s. induction l0 ; intros.\n- simpl in H. inversion H.\n- simpl (fst (l, m)). destruct a. destruct m0.\n  1-2: simpl in H ; destruct n ; pose (IHl0 H) ; repeat destruct s ; repeat destruct p ; exists x ; exists x0 ; exists x1 ;\n  exists x2 ; exists x3 ; exists x4 ; repeat split ; try auto ; apply in_cons ; assumption.\n  2-4: simpl in H ; destruct n ; pose (IHl0 H) ; repeat destruct s ; repeat destruct p ; exists x ; exists x0 ; exists x1 ;\n  exists x2 ; exists x3 ; exists x4 ; repeat split ; try auto ; apply in_cons ; assumption.\n  destruct n.\n  + pose (IHl0 H). repeat destruct s. repeat destruct p. exists x. exists x0. exists x1.\n     exists x2. exists x3. exists x4. repeat split ; try auto. apply in_cons. assumption.\n  + inversion H.\n    { simpl in H1. simpl in H0. simpl (fst (l, m)) in IHl0. simpl (snd (l, m)) in IHl0.\n      exists n. exists m0_1. exists m0_2.\n      exists (fst (nth_split n match n with\n           | 0 => match l with\n                  | [] => []\n                  | B :: tl => if eq_dec_form (m0_1 ∧ m0_2) B then tl else B :: tl\n                  end\n           | S _ => match l with\n                    | [] => []\n                    | B :: tl => B :: remove_nth n (m0_1 ∧ m0_2) tl\n                    end\n           end)).\n      exists (snd (nth_split n match n with\n           | 0 => match l with\n                  | [] => []\n                  | B :: tl => if eq_dec_form (m0_1 ∧ m0_2) B then tl else B :: tl\n                  end\n           | S _ => match l with\n                    | [] => []\n                    | B :: tl => B :: remove_nth n (m0_1 ∧ m0_2) tl\n                    end\n           end)). exists m. repeat split ; auto. apply in_eq. }\n    { pose (IHl0 H1). repeat destruct s. repeat destruct p. exists x. exists x0. exists x1.\n      exists x2. exists x3. exists x4. repeat split ; try auto. apply in_cons. assumption. }\nQed.\n\nLemma AndL_help1 : forall prem s, InT prem (prems_And_L (pos_top_ands (fst s)) s) -> AndLRule [prem] s.\nProof.\nintros. pose (@AndL_help01 _ _ _ H). repeat destruct s0. destruct s.\nrepeat destruct p. subst. simpl in i. simpl (fst (l, m)).\nsimpl (fst (l, m)) in H. simpl (snd (l, m)). simpl (snd (l, m)) in H.\napply In_pos_top_ands_split_l in i.\ndestruct i. destruct s. repeat destruct p.\nsubst. rewrite <- e. rewrite <- e0. apply AndLRule_I.\nQed.\n\nLemma AndL_help002 : forall Γ0 Γ1 l C A B,\n           InT (Γ0 ++ A :: B :: Γ1, C) (prems_And_L ((A ∧ B, S (length Γ0)) :: l) (Γ0 ++ A ∧ B :: Γ1, C)).\nProof.\nintros. unfold prems_And_L.\nsimpl (fst (Γ0 ++ A ∧ B :: Γ1, C)). simpl (snd (Γ0 ++ A ∧ B :: Γ1, C)).\nrepeat rewrite effective_remove_nth. pose (nth_split_idL Γ0 Γ1).\nrewrite <- e. pose (nth_split_idR Γ0 Γ1). rewrite <- e0. apply InT_eq.\nQed.\n\nLemma AndL_help02 : forall Γ0 Γ1 C A B l n,\n            AndLRule [(Γ0 ++ A :: B :: Γ1, C)] (Γ0 ++ (And A B) :: Γ1, C) ->\n            (length Γ0 = n) ->\n            (In ((And A B), S n) l) ->\n            InT (Γ0 ++ A :: B :: Γ1, C) (prems_And_L l (Γ0 ++ (And A B) :: Γ1, C)).\nProof.\ninduction l ; intros.\n- inversion H1.\n- destruct a. destruct m.\n  1-2: subst ; apply In_InT_pair in H1 ; inversion H1 ; subst ; inversion H2 ; subst ; apply InT_In in H2 ;\n    assert (J1: length Γ0 = length Γ0) ; try reflexivity ; pose (IHl _ H J1 H2) ; simpl ; destruct n0 ; assumption ; assumption.\n  2-4: subst ; apply In_InT_pair in H1 ; inversion H1 ; subst ; inversion H2 ; subst ; apply InT_In in H2 ;\n    assert (J1: length Γ0 = length Γ0) ; try reflexivity ; pose (IHl _ H J1 H2) ; simpl ; destruct n0 ; assumption ; assumption.\n  * apply In_InT_pair in H1. inversion H1.\n    + subst. inversion H3. subst. apply AndL_help002.\n    + subst. assert (J1: (length Γ0) = (length Γ0)). reflexivity. apply InT_In in H3.\n       pose (IHl (length Γ0) H J1 H3). simpl. destruct n0 ; auto. apply InT_cons ; auto.\nQed.\n\nLemma AndL_help2 : forall prem s, AndLRule [prem] s -> InT prem (prems_And_L (pos_top_ands (fst s)) s).\nProof.\nintros. inversion H. subst. simpl.\npose (@AndL_help02 Γ0 Γ1 C A B (pos_top_ands (Γ0 ++ (And A B) :: Γ1)) (length Γ0)). apply i ; try assumption ; auto.\napply Good_pos_in_pos_top_ands.\nQed.\n\nLemma finite_AndL_premises_of_S : forall (s : (list (MPropF V)) * (MPropF V)), existsT2 listAndLprems,\n              (forall prems, ((AndLRule prems s) -> (InT prems listAndLprems)) *\n                             ((InT prems listAndLprems) -> (AndLRule prems s))).\nProof.\nintros. destruct s.\nexists (map (fun y => [y]) (prems_And_L (pos_top_ands l) (l,m))).\nintros. split ; intro.\n- inversion H. subst.\n  pose (AndL_help2 H). apply InT_map_iff. exists (Γ0 ++ A :: B :: Γ1, m) ; split ; auto.\n- apply InT_map_iff in H. destruct H. destruct p. subst. apply AndL_help1. simpl. assumption.\nQed.\n\n\n(*------------------------------------------------------------------------------------------------------------------------------------------------------------------- *)\n\n\n\n\n\n(* Or rules *)\n\n(* Let's start with OrR1 *)\n\nDefinition prems_Or_R1 (s : (list (MPropF V)) * (MPropF V)) : list (list ((list (MPropF V)) * (MPropF V))) :=\nmatch (snd s) with\n  | Or A B => [[(fst s, A)]]\n  | _ => nil\nend.\n\nLemma finite_OrR1_premises_of_S : forall (s : (list (MPropF V)) * (MPropF V)), existsT2 listOrR1prems,\n              (forall prems, ((OrR1Rule prems s) -> (InT prems listOrR1prems)) *\n                             ((InT prems listOrR1prems) -> (OrR1Rule prems s))).\nProof.\nintros. exists (prems_Or_R1 s). intros. split ; intro.\ninversion H. subst. unfold prems_Or_R1. simpl. apply InT_eq.\nunfold prems_Or_R1 in H. destruct s. destruct m ; inversion H. 2: inversion H1.\nsubst. apply OrR1Rule_I.\nQed.\n\n(* And OrR2 *)\n\nDefinition prems_Or_R2 (s : (list (MPropF V)) * (MPropF V)) : list (list ((list (MPropF V)) * (MPropF V))) :=\nmatch (snd s) with\n  | Or A B => [[(fst s, B)]]\n  | _ => nil\nend.\n\nLemma finite_OrR2_premises_of_S : forall (s : (list (MPropF V)) * (MPropF V)), existsT2 listOrR2prems,\n              (forall prems, ((OrR2Rule prems s) -> (InT prems listOrR2prems)) *\n                             ((InT prems listOrR2prems) -> (OrR2Rule prems s))).\nProof.\nintros. exists (prems_Or_R2 s). intros. split ; intro.\ninversion H. subst. unfold prems_Or_R2. simpl. apply InT_eq.\nunfold prems_Or_R2 in H. destruct s. destruct m ; inversion H. 2: inversion H1.\nsubst. apply OrR2Rule_I.\nQed.\n\n\n\n(* And now OrL *)\n\nFixpoint top_ors (l : list (MPropF V)) : list (MPropF V) :=\nmatch l with\n  | nil => nil\n  | h :: t => match h with\n                | Or A B => (Or A B) :: top_ors t\n                | _ => top_ors t\n              end\nend.\n\nFixpoint pos_top_ors (l : list (MPropF V)) : (list ((MPropF V) * nat)) :=\nmatch l with\n  | nil => nil\n  | h :: t => match h with\n                | Or A B => (Or A B, 1) :: (map (fun y => (fst y, S (snd y))) (pos_top_ors t))\n                | _ => (map (fun y => (fst y, S  (snd y))) (pos_top_ors t))\n              end\nend.\n\nFixpoint prems_Or_L (l : list ((MPropF V) * nat)) (s : (list (MPropF V)) * (MPropF V)) : list (list ((list (MPropF V)) * (MPropF V))) :=\nmatch l with\n  | nil => nil\n  | (C, n) :: t => match n with\n      | 0 => prems_Or_L t s\n      | S m => match C with\n           | Or A B => [((fst (nth_split m (remove_nth (S m) C (fst s)))) ++ A :: (snd (nth_split m (remove_nth (S m) C (fst s)))) , snd s);\n                               ((fst (nth_split m (remove_nth (S m) C (fst s)))) ++ B :: (snd (nth_split m (remove_nth (S m) C (fst s)))) , snd s)]\n                                :: (prems_Or_L t s)\n           | _ => prems_Or_L t s\n           end\n      end\nend.\n\nLemma In_pos_top_ors_0_False : forall l (A : MPropF V), In (A, 0) (pos_top_ors l) -> False.\nProof.\n- induction l.\n  * intros. inversion H.\n  * intros. simpl in H. destruct a.\n    1-3: simpl in H ; apply In_InT_pair in H ; apply InT_map_iff in H ; destruct H ;\n    destruct p ; destruct x ; inversion e.\n    2-3: simpl in H ; apply In_InT_pair in H ; apply InT_map_iff in H ; destruct H ;\n    destruct p ; destruct x ; inversion e.\n    simpl in H. destruct H. inversion H. apply In_InT_pair in H. apply InT_map_iff in H. destruct H.\n    destruct p. destruct x. inversion e.\nQed.\n\nLemma In_pos_top_ors_split_l : forall l (A : MPropF V) n, In (A, S n) (pos_top_ors l) -> \n          existsT2 l0 l1, (l = l0 ++ A :: l1) *\n                          (length l0 = n) *\n                          (l0 = fst (nth_split n (remove_nth (S n) A l))) *\n                          (l1 = snd (nth_split n (remove_nth (S n) A l))).\nProof.\ninduction l.\n- intros. simpl. exfalso. simpl in H. destruct H.\n- intros. simpl in H. destruct a.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_ors_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (# v :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (# v :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n    # v :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (# v :: x))). simpl. reflexivity.\n    rewrite H0. assert ((# v :: x ++ A :: x0) = ((# v :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (# v :: x) x0). simpl (length (# v :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (# v :: x))). simpl. reflexivity.\n    rewrite H. assert ((# v :: x ++ A :: x0) = ((# v :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (# v :: x) x0). simpl (length (# v :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_ors_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (⊥ V :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (⊥ V :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      ⊥ V :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (⊥ V :: x))). simpl. reflexivity.\n    rewrite H0. assert ((⊥ V :: x ++ A :: x0) = ((⊥ V :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (⊥ V :: x) x0). simpl (length (⊥ V :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (⊥ V :: x))). simpl. reflexivity.\n    rewrite H. assert ((⊥ V :: x ++ A :: x0) = ((⊥ V :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (⊥ V :: x) x0). simpl (length (⊥ V :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_ors_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (a1 ∧ a2 :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (a1 ∧ a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      a1 ∧ a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (a1 ∧ a2 :: x))). simpl. reflexivity.\n    rewrite H0. assert ((a1 ∧ a2 :: x ++ A :: x0) = ((a1 ∧ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (a1 ∧ a2 :: x) x0). simpl (length (a1 ∧ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (a1 ∧ a2 :: x))). simpl. reflexivity.\n    rewrite H. assert ((a1 ∧ a2 :: x ++ A :: x0) = ((a1 ∧ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (a1 ∧ a2 :: x) x0). simpl (length (a1 ∧ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. inversion H.\n    + inversion H1. subst. exists []. exists l. repeat split. simpl.\n      destruct (eq_dec_form (a1 ∨ a2) (a1 ∨ a2)). reflexivity. exfalso. auto.\n    + subst. apply InT_map_iff in H1. destruct H1. destruct p.\n      destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n      apply InT_In in i. apply In_pos_top_ors_0_False in i. assumption.\n      apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n      subst. exists (a1 ∨ a2 :: x). exists x0. repeat split.\n      rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n      assert (fst (a1 ∨ a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      a1 ∨ a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n      assert (S (S (length x)) = S (length (a1 ∨ a2 :: x))). simpl. reflexivity.\n      rewrite H1. assert ((a1 ∨ a2 :: x ++ A :: x0) = ((a1 ∨ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n      rewrite H2. clear H2. clear H1. rewrite effective_remove_nth.\n      pose (nth_split_idL (a1 ∨ a2 :: x) x0). simpl (length (a1 ∨ a2 :: x)) in e2.\n      rewrite <- e2. reflexivity.\n      rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n      assert (S (S (length x)) = S (length (a1 ∨ a2 :: x))). simpl. reflexivity.\n      rewrite H0. assert ((a1 ∨ a2 :: x ++ A :: x0) = ((a1 ∨ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n      rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n      pose (nth_split_idR (a1 ∨ a2 :: x) x0). simpl (length (a1 ∨ a2 :: x)) in e2.\n      rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_ors_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (a1 → a2 :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (a1 → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      a1 → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (a1 → a2 :: x))). simpl. reflexivity.\n    rewrite H0. assert ((a1 → a2 :: x ++ A :: x0) = ((a1 → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (a1 → a2 :: x) x0). simpl (length (a1 → a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (a1 → a2 :: x))). simpl. reflexivity.\n    rewrite H. assert ((a1 → a2 :: x ++ A :: x0) = ((a1 → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (a1 → a2 :: x) x0). simpl (length (a1 → a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_ors_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (Box a :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (Box a :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n    Box a :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (Box a :: x))). simpl. reflexivity.\n    rewrite H0. assert ((Box a :: x ++ A :: x0) = ((Box a :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (Box a :: x) x0). simpl (length (Box a :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (Box a :: x))). simpl. reflexivity.\n    rewrite H. assert ((Box a :: x ++ A :: x0) = ((Box a :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (Box a :: x) x0). simpl (length (Box a :: x)) in e2.\n    rewrite <- e2. reflexivity.\nQed.\n\nLemma Good_pos_in_pos_top_ors : forall A B Γ0 Γ1,\n              In (Or A B, S (length Γ0)) (pos_top_ors (Γ0 ++ Or A B :: Γ1)).\nProof.\ninduction Γ0.\n- intros. simpl. auto.\n- intros. destruct a.\n  1-3: simpl ; apply InT_In ; apply InT_map_iff ; exists (Or A B, S (length Γ0)) ;\n  split ; simpl ; try reflexivity ; apply In_InT_pair ; apply IHΓ0.\n  2-3: simpl ; apply InT_In ; apply InT_map_iff ; exists (Or A B, S (length Γ0)) ;\n  split ; simpl ; try reflexivity ; apply In_InT_pair ; apply IHΓ0.\n  simpl. right. apply InT_In. apply InT_map_iff. exists (Or A B, S (length Γ0)).\n  split. simpl. reflexivity. apply In_InT_pair. apply IHΓ0.\nQed.\n\nLemma OrL_help01 : forall prems s l, InT prems (prems_Or_L l s) ->\n                  (existsT2 n prem1 prem2 A B Γ0 Γ1 C,\n                        (prems = [prem1; prem2]) *\n                        (In ((Or A B), S n) l) *\n                        (prem1 = (Γ0 ++ A :: Γ1, C)) *\n                        (prem2 = (Γ0 ++ B :: Γ1, C)) *\n                        (C = snd s) *\n                        (Γ0 = (fst (nth_split n (remove_nth (S n) (Or A B) (fst s))))) *\n                        (Γ1 = (snd (nth_split n (remove_nth (S n) (Or A B) (fst s)))))).\nProof.\nintros prems s. destruct s. induction l0 ; intros.\n- simpl in H. inversion H.\n- simpl (fst (l, m)). simpl (snd (l, m)). destruct a. destruct m0.\n  1-3: simpl in H ; destruct n ; pose (IHl0 H) ; repeat destruct s ; repeat destruct p ; exists x ; exists x0 ; exists x1 ;\n      exists x2 ; exists x3 ; exists x4 ; exists x5 ; exists x6 ; repeat split ; try auto ; apply in_cons ; assumption.\n  2-3: simpl in H ; destruct n ; pose (IHl0 H) ; repeat destruct s ; repeat destruct p ; exists x ; exists x0 ; exists x1 ;\n      exists x2 ; exists x3 ; exists x4 ; exists x5 ; exists x6 ; repeat split ; try auto ; apply in_cons ; assumption.\n  destruct n.\n  + pose (IHl0 H). repeat destruct s. repeat destruct p. exists x. exists x0. exists x1.\n    exists x2. exists x3. exists x4. exists x5. exists x6. repeat split ; try auto. apply in_cons. assumption.\n  + inversion H.\n\n    { simpl in H1. simpl in H0. simpl (fst (l, m)) in IHl0. simpl (snd (l, m)) in IHl0.\n      exists n.\n      exists (fst\n         (nth_split n\n            match n with\n            | 0 => match l with\n                   | [] => []\n                   | B :: tl => if eq_dec_form (m0_1 ∨ m0_2) B then tl else B :: tl\n                   end\n            | S _ => match l with\n                     | [] => []\n                     | B :: tl => B :: remove_nth n (m0_1 ∨ m0_2) tl\n                     end\n            end) ++\n       m0_1\n       :: snd\n            (nth_split n\n               match n with\n               | 0 => match l with\n                      | [] => []\n                      | B :: tl => if eq_dec_form (m0_1 ∨ m0_2) B then tl else B :: tl\n                      end\n               | S _ => match l with\n                        | [] => []\n                        | B :: tl => B :: remove_nth n (m0_1 ∨ m0_2) tl\n                        end\n               end), m).\n      exists (fst\n        (nth_split n\n           match n with\n           | 0 => match l with\n                  | [] => []\n                  | B :: tl => if eq_dec_form (m0_1 ∨ m0_2) B then tl else B :: tl\n                  end\n           | S _ => match l with\n                    | [] => []\n                    | B :: tl => B :: remove_nth n (m0_1 ∨ m0_2) tl\n                    end\n           end) ++\n      m0_2\n      :: snd\n           (nth_split n\n              match n with\n              | 0 => match l with\n                     | [] => []\n                     | B :: tl => if eq_dec_form (m0_1 ∨ m0_2) B then tl else B :: tl\n                     end\n              | S _ => match l with\n                       | [] => []\n                       | B :: tl => B :: remove_nth n (m0_1 ∨ m0_2) tl\n                       end\n              end), m).  exists m0_1. exists m0_2. exists (fst (nth_split n (remove_nth (S n) (m0_1 ∨ m0_2) l))).\n           exists (snd (nth_split n (remove_nth (S n) (m0_1 ∨ m0_2) l))). exists m. repeat split ; auto. apply in_eq. }\n    { pose (IHl0 H1). repeat destruct s. repeat destruct p. exists x. exists x0. exists x1.\n      exists x2. exists x3. exists x4. exists x5. exists x6. repeat split ; try auto. apply in_cons. assumption. }\nQed.\n\nLemma OrL_help1 : forall prems s, InT prems (prems_Or_L (pos_top_ors (fst s)) s) ->\n                                         OrLRule prems s.\nProof.\nintros. pose (@OrL_help01 _ _ _ H). repeat destruct s0. destruct s. simpl in H.\nrepeat destruct p. subst. simpl in i. simpl (fst (l, m)). simpl (snd (l, m)). simpl (snd (l, m)) in H.\nsimpl (fst (l, m)) in H. apply In_pos_top_ors_split_l in i.\ndestruct i. destruct s. repeat destruct p.\nsubst. rewrite <- e. rewrite <- e0. apply OrLRule_I.\nQed.\n\nLemma OrL_help002 : forall Γ0 Γ1 l C A B,\n           InT [(Γ0 ++ A :: Γ1, C); (Γ0 ++ B :: Γ1, C)] (prems_Or_L ((A ∨ B, S (length Γ0)) :: l) (Γ0 ++ A ∨ B :: Γ1, C)).\nProof.\nintros. unfold prems_Or_L.\nsimpl (fst (Γ0 ++ A ∨ B :: Γ1, C)). simpl (snd (Γ0 ++ A ∨ B :: Γ1, C)).\nrepeat rewrite effective_remove_nth. pose (nth_split_idL Γ0 Γ1).\nrewrite <- e. pose (nth_split_idR Γ0 Γ1). rewrite <- e0. apply InT_eq.\nQed.\n\nLemma OrL_help02 : forall Γ0 Γ1 C A B l n,\n            OrLRule [(Γ0 ++ A :: Γ1, C); (Γ0 ++ B :: Γ1, C)] (Γ0 ++ A ∨ B :: Γ1, C) ->\n            (length Γ0 = n) ->\n            (In ((A ∨ B), S n) l) ->\n            InT [(Γ0 ++ A :: Γ1, C); (Γ0 ++ B :: Γ1, C)] (prems_Or_L l (Γ0 ++ A ∨ B :: Γ1, C)).\nProof.\ninduction l ; intros.\n- inversion H1.\n- destruct a. destruct m.\n  1-3: subst ; apply In_InT_pair in H1 ; inversion H1 ; subst ; inversion H2 ; subst ; apply InT_In in H2 ;\n    assert (J1: length Γ0 = length Γ0) ; try reflexivity ; pose (IHl _ H J1 H2) ; try simpl ; destruct n0 ; assumption ; assumption.\n  2-3: subst ; apply In_InT_pair in H1 ; inversion H1 ; subst ; inversion H2 ; subst ; apply InT_In in H2 ;\n    assert (J1: length Γ0 = length Γ0) ; try reflexivity ; pose (IHl _ H J1 H2) ; try simpl ; destruct n0 ; assumption ; assumption.\n  apply In_InT_pair in H1. inversion H1.\n    + subst. inversion H3. subst. pose (OrL_help002 Γ0 Γ1 l C A B) ; auto.\n    + subst. assert (J1: (length Γ0) = (length Γ0)). reflexivity. apply InT_In in H3.\n      pose (IHl (length Γ0) H J1 H3). simpl. destruct n0. assumption. apply InT_cons. auto.\nQed.\n\nLemma OrL_help2 : forall prems s, OrLRule prems s -> InT prems (prems_Or_L (pos_top_ors (fst s)) s).\nProof.\nintros. inversion H. subst. simpl.\npose (@OrL_help02 Γ0 Γ1 C A B (pos_top_ors (Γ0 ++ (Or A B) :: Γ1)) (length Γ0)). apply i ; try assumption.\nreflexivity. apply Good_pos_in_pos_top_ors.\nQed.\n\nLemma finite_OrL_premises_of_S : forall (s : (list (MPropF V)) * (MPropF V)), existsT2 listOrLprems,\n              (forall prems, ((OrLRule prems s) -> (InT prems listOrLprems)) *\n                             ((InT prems listOrLprems) -> (OrLRule prems s))).\nProof.\nintros. destruct s.\nexists (prems_Or_L (pos_top_ors l) (l,m)).\nintros. split ; intro.\n- inversion H. subst. pose (OrL_help2 H) ; auto.\n- apply OrL_help1. simpl. assumption.\nQed.\n\n\n\n\n\n(*------------------------------------------------------------------------------------------------------------------------------------------------------------------- *)\n\n\n\n\n\n(* ImpR rule *)\n\nFixpoint top_imps (l : list (MPropF V)) : list (MPropF V) :=\nmatch l with\n  | nil => nil\n  | h :: t => match h with\n                | Imp A B => (Imp A B) :: top_imps t\n                | _ => top_imps t\n              end\nend.\n\nFixpoint pos_top_imps (l : list (MPropF V)) : (list ((MPropF V) * nat)) :=\nmatch l with\n  | nil => nil\n  | h :: t => match h with\n                | Imp A B => (Imp A B, 1) :: (map (fun y => (fst y, S (snd y))) (pos_top_imps t))\n                | _ => (map (fun y => (fst y, S  (snd y))) (pos_top_imps t))\n              end\nend.\n\nDefinition prems_Imp_R (s : (list (MPropF V)) * (MPropF V)) :=\nmatch (snd s) with\n  | Imp A B => listInsertsL_Seqs (fst s) A B\n  | _ => nil\nend.\n\nLemma ImpR_help1 : forall prem s, InT prem (prems_Imp_R s) -> ImpRRule [prem] s.\nProof.\nintros. destruct s. destruct m ; simpl in H. 1-4: inversion H. 2: inversion H.\nsubst. unfold prems_Imp_R in H. simpl in H. unfold listInsertsL_Seqs in H.\napply InT_map_iff in H. destruct H. destruct p. subst. unfold listInserts in i.\napply InT_map_iff in i. destruct i. destruct p ; subst.\ndestruct (list_of_splits l). pose (i0 (fst x0) (snd x0)). simpl in i.\nassert (In (fst x0, snd x0) x). destruct x0. simpl. apply InT_In ; auto.\napply i1 in H. rewrite <- H. apply ImpRRule_I.\nQed.\n\nLemma ImpR_help2 : forall prem s, ImpRRule [prem] s -> InT prem (prems_Imp_R s).\nProof.\nintros. inversion H. subst. unfold prems_Imp_R. simpl. unfold listInsertsL_Seqs.\napply InT_map_iff. exists (Γ0 ++ A :: Γ1). split ; auto. unfold listInserts.\napply InT_map_iff. exists (Γ0,Γ1). simpl ; split ; auto.  destruct (list_of_splits (Γ0 ++ Γ1)).\nsimpl. pose (i Γ0 Γ1). apply In_InT_seqs. apply i0. reflexivity.\nQed.\n\nLemma finite_ImpR_premises_of_S : forall (s : (list (MPropF V)) * (MPropF V)), existsT2 listImpRprems,\n              (forall prems, ((ImpRRule prems s) -> (InT prems listImpRprems)) *\n                             ((InT prems listImpRprems) -> (ImpRRule prems s))).\nProof.\nintro s. destruct s.\nexists (map (fun y => [y]) (prems_Imp_R (l,m))).\nintros. split ; intro.\n- inversion H. subst. apply InT_map_iff.\n  exists (Γ0 ++ A :: Γ1, B). split. reflexivity.\n  pose (@ImpR_help2 (Γ0 ++ A :: Γ1, B) (Γ0 ++ Γ1, A → B)). simpl in i. apply i.\n  assumption.\n- apply InT_map_iff in H. destruct H. destruct p. subst. apply ImpR_help1. simpl. assumption.\nQed.\n\n\n\n\n\n(*------------------------------------------------------------------------------------------------------------------------------------------------------------------- *)\n\n\n\n\n\n(* AtomImpL1 rule. *)\n\nFixpoint top_atomimps (l : list (MPropF V)) : list (MPropF V) :=\nmatch l with\n  | nil => nil\n  | h :: t => match h with\n                | Imp A B => match A with\n                                   | # P => (Imp # P B) :: top_atomimps t\n                                   | _ => top_atomimps t\n                                   end\n                | _ => top_atomimps t\n              end\nend.\n\nFixpoint pos_top_atomimps (l : list (MPropF V)) : (list ((MPropF V) * nat)) :=\nmatch l with\n  | nil => nil\n  | h :: t => match h with\n                | Imp A B => match A with\n                                   | # P => (Imp # P B, 1) :: (map (fun y => (fst y, S (snd y))) (pos_top_atomimps t))\n                                   | _ => (map (fun y => (fst y, S (snd y))) (pos_top_atomimps t))\n                                   end\n                | _ => (map (fun y => (fst y, S (snd y))) (pos_top_atomimps t))\n              end\nend.\n\nFixpoint top_atoms (l : list (MPropF V)) : list (MPropF V) :=\nmatch l with\n  | nil => nil\n  | h :: t => match h with\n                 | # P => # P :: top_atoms t\n                 | _ => top_atoms t\n                 end\nend.\n\nFixpoint pos_top_atoms (l : list (MPropF V)) : (list ((MPropF V) * nat)) :=\nmatch l with\n  | nil => nil\n  | h :: t => match h with\n                 | # P => (# P, 1) :: (map (fun y => (fst y, S (snd y))) (pos_top_atoms t))\n                 | _ => (map (fun y => (fst y, S (snd y))) (pos_top_atoms t))\n                 end\nend.\n\nInductive eqb_ind (P Q : V) (b : bool): Type :=\n | equalb : P = Q -> b = true -> (eqb_ind P Q b)\n | diffb : P <> Q -> b = false -> (eqb_ind P Q b).\n\nLemma dec_eqb_ind : forall P Q,\n  existsT2 b, (eqb_ind P Q b).\nProof.\nintros. destruct (eq_dec_propvar P Q).\n- exists true. apply equalb ; auto.\n- exists false. apply diffb ; auto.\nQed.\n\nDefinition eqb_prop (P Q : V) : bool := proj1_sigT2 (dec_eqb_ind P Q).\n\nLemma eqb_prop_eq : forall P0 P1, ((P0 = P1) -> (eqb_prop P0 P1 = true)) * ((eqb_prop P0 P1 = true) -> (P0 = P1)).\nProof.\nunfold eqb_prop.\nintros. destruct dec_eqb_ind. inversion e. subst. split. intros. auto. auto. subst.\nsplit ; intro ; auto. simpl in H0. inversion H0.\nQed.\n\nDefinition all_pos_top_atoms_atomimps (l : list (MPropF V)) : list (list ((MPropF V * nat) * (MPropF V * nat))) :=\n                        map (fun x => (map (fun y => (x,y)) (pos_top_atomimps l))) (pos_top_atoms l).\n\n\nDefinition pair_atom_same_antec (p : ((MPropF V * nat) * (MPropF V * nat))) : bool :=\nmatch (fst (fst p)) with\n  | # P0 => match (fst (snd p)) with\n      | Imp A B => match A with\n                           | # P1 => eqb_prop P0 P1\n                           | _ => false\n                           end\n      | _ => false\n      end\n  | _ => false\nend.\n\nDefinition pos_atomimps_is_left_atoms (l : list (MPropF V)) :=\n          filter (fun (x : ((MPropF V * nat) * (MPropF V * nat))) => andb (ltb (snd (fst x)) (snd (snd x))) (pair_atom_same_antec x))\n          (concat (all_pos_top_atoms_atomimps l)).\n\nDefinition pos_top_atomimps_L1 l := map (fun x => snd x) (pos_atomimps_is_left_atoms l).\n\nFixpoint prems_AtomImp_L1 (l : list ((MPropF V) * nat)) (s : (list (MPropF V)) * (MPropF V)) : list ((list (MPropF V)) * (MPropF V)) :=\nmatch l with\n  | nil => nil\n  | (C, n) :: t => match n with\n      | 0 => prems_AtomImp_L1 t s\n      | S m => match C with\n           | Imp A B => match A with\n                               | # P => ((fst (nth_split m (remove_nth (S m) C (fst s)))) ++ B :: (snd (nth_split m (remove_nth (S m) C (fst s)))), snd s)\n                                             :: (prems_AtomImp_L1 t s)\n                               | _ => prems_AtomImp_L1 t s\n                               end\n           | _ => prems_AtomImp_L1 t s\n           end\n      end\nend.\n\nLemma In_pos_top_atoms_0_False : forall l (A : MPropF V), In (A, 0) (pos_top_atoms l) -> False.\nProof.\n- induction l.\n  * intros. inversion H.\n  * intros. simpl in H. destruct a.\n    1: simpl in H ;  destruct H ; [ inversion H | simpl ; apply in_map_iff in H ; destruct H ; \n    destruct H ; destruct x ; simpl in H ; inversion H].\n    1-5: apply in_map_iff in H ; destruct H ; destruct H ; destruct x ; simpl in H ; inversion H.\nQed.\n\nLemma In_pos_top_atomimps_0_False : forall l (A : MPropF V), In (A, 0) (pos_top_atomimps l) -> False.\nProof.\n- induction l.\n  * intros. inversion H.\n  * intros. simpl in H. destruct a.\n    1-4: apply in_map_iff in H ; destruct H ; destruct H ; destruct x ; simpl in H ; inversion H.\n    2: apply in_map_iff in H ; destruct H ; destruct H ; destruct x ; simpl in H ; inversion H.\n    destruct a1.\n    2-6: apply in_map_iff in H ; destruct H ; destruct H ; destruct x ; simpl in H ; inversion H.\n    simpl in H. destruct H. inversion H. apply in_map_iff in H. destruct H. destruct x. simpl in H. destruct H.\n    inversion H.\nQed.\n\nLemma In_pos_top_atomimps_L1_0_False : forall l (A : MPropF V), In (A, 0) (pos_top_atomimps_L1 l) -> False.\nProof.\n- induction l.\n  * intros. inversion H.\n  * intros. simpl in H. destruct a.\n    1-4: simpl in H ;  apply In_InT_pair in H ; apply InT_map_iff in H ; destruct H ;\n    destruct p ; destruct x ; simpl in e ; subst ; unfold pos_atomimps_is_left_atoms in i ;\n    apply InT_In in i ; apply filter_In in i ; destruct i ; simpl in H0 ; apply in_concat in H ;\n    destruct H ; destruct H ; unfold all_pos_top_atoms_atomimps in H ;\n    apply in_map_iff in H ; destruct H ; destruct H ; subst ;\n    apply in_map_iff in H1 ; destruct H1 ; destruct H ; inversion H ; subst ; clear H ;\n    apply in_map_iff in H1 ; destruct H1 ; destruct H ; destruct x ; simpl in H ; inversion H.\n    2: simpl in H ;  apply In_InT_pair in H ; apply InT_map_iff in H ; destruct H ;\n    destruct p ; destruct x ; simpl in e ; subst ; unfold pos_atomimps_is_left_atoms in i ;\n    apply InT_In in i ; apply filter_In in i ; destruct i ; simpl in H0 ; apply in_concat in H ;\n    destruct H ; destruct H ; unfold all_pos_top_atoms_atomimps in H ;\n    apply in_map_iff in H ; destruct H ; destruct H ; subst ;\n    apply in_map_iff in H1 ; destruct H1 ; destruct H ; inversion H ; subst ; clear H ;\n    apply in_map_iff in H1 ; destruct H1 ; destruct H ; destruct x ; simpl in H ; inversion H.\n    destruct a1.\n    2-6: simpl in H ;  apply In_InT_pair in H ; apply InT_map_iff in H ; destruct H ;\n    destruct p ; destruct x ; simpl in e ; subst ; unfold pos_atomimps_is_left_atoms in i ;\n    apply InT_In in i ; apply filter_In in i ; destruct i ; simpl in H0 ; apply in_concat in H ;\n    destruct H ; destruct H ; unfold all_pos_top_atoms_atomimps in H ;\n    apply in_map_iff in H ; destruct H ; destruct H ; subst ;\n    apply in_map_iff in H1 ; destruct H1 ; destruct H ; inversion H ; subst ; clear H ;\n    apply in_map_iff in H1 ; destruct H1 ; destruct H ; destruct x ; simpl in H ; inversion H.\n    apply In_InT_pair in H ; apply InT_map_iff in H. destruct H. destruct x. destruct p0.\n    destruct p1. simpl in p. destruct p. inversion e. subst. unfold pos_atomimps_is_left_atoms in i.\n     apply InT_In in i ; apply filter_In in i ; destruct i. simpl in H0. apply in_concat in H ;\n    destruct H ; destruct H ; unfold all_pos_top_atoms_atomimps in H ;\n    apply in_map_iff in H ; destruct H. destruct H. subst. destruct x0.\n    apply in_map_iff in H1. destruct H1. destruct H. inversion H. subst. inversion H1.\n    inversion H3. apply in_map_iff in H3. destruct H3. destruct H3. inversion H3.\nQed.\n\nLemma filter_InT : forall [A : Type] (f : A -> bool) (x : A) (l : list A), (InT x (filter f l) -> ((InT x l) * (f x = true))) *\n                                                                                                       ( ((InT x l) * (f x = true)) -> InT x (filter f l)).\nProof.\nintros A f x. induction l.\n- simpl. split ; intro. inversion X. destruct X. auto.\n- split. destruct IHl. intros. simpl in X. remember (f a) as c. destruct c. inversion X. subst. split ; auto. apply InT_eq.\n  subst. apply p in X0. destruct X0. split ; auto. apply InT_cons ; auto. apply p in X. destruct X.\n  split ; auto. apply InT_cons ; auto.\n  intros. destruct X. destruct IHl. inversion i. subst. simpl. destruct (f x). apply InT_eq.\n  inversion e. subst. simpl. destruct (f a). apply InT_cons. apply i0. split ; auto.\n  apply i0 ; split ; auto.\nQed.\n\nLemma InT_concat: forall [A : Type] (l : list (list A)) (y : A), (InT y (concat l) -> (existsT2 x : list A, (InT x l) * (InT y x))) *\n                                                                                            ((existsT2 x : list A, (InT x l) * (InT y x)) -> InT y (concat l) ).\nProof.\nintro A. induction l.\n- intros. simpl. split ; intro. inversion X. destruct X. destruct p. inversion i.\n- intros. simpl. split ; intro. apply InT_app_or in X. destruct X. exists a. split ; auto. apply InT_eq.\n  pose (IHl y). destruct p. apply s in i. destruct i. destruct p. exists x. split ; auto. apply InT_cons ; auto.\n  destruct X. destruct p. inversion i. subst. apply InT_or_app. auto. subst. apply InT_or_app.\n  right. apply IHl. exists x. split ; auto.\nQed.\n\nLemma In_pos_top_atomimps_split_l :forall l (A : MPropF V) n, In (A, S n) (pos_top_atomimps l) ->\n          existsT2 l0 l1, (l = l0 ++ A :: l1) *\n                          (length l0 = n) *\n                          (l0 = fst (nth_split n (remove_nth (S n) A l))) *\n                          (l1 = snd (nth_split n (remove_nth (S n) A l))).\nProof.\ninduction l.\n- intros. simpl. exfalso. simpl in H. destruct H.\n- intros. simpl in H. destruct a.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_atomimps_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (# v :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (# v :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n    # v :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (# v :: x))). simpl. reflexivity.\n    rewrite H0. assert ((# v :: x ++ A :: x0) = ((# v :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (# v :: x) x0). simpl (length (# v :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (# v :: x))). simpl. reflexivity.\n    rewrite H. assert ((# v :: x ++ A :: x0) = ((# v :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (# v :: x) x0). simpl (length (# v :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_atomimps_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (⊥ V :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (⊥ V :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      ⊥ V :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (⊥ V :: x))). simpl. reflexivity.\n    rewrite H0. assert ((⊥ V :: x ++ A :: x0) = ((⊥ V :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (⊥ V :: x) x0). simpl (length (⊥ V :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (⊥ V :: x))). simpl. reflexivity.\n    rewrite H. assert ((⊥ V :: x ++ A :: x0) = ((⊥ V :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (⊥ V :: x) x0). simpl (length (⊥ V :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_atomimps_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (a1 ∧ a2 :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (a1 ∧ a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      a1 ∧ a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (a1 ∧ a2 :: x))). simpl. reflexivity.\n    rewrite H0. assert ((a1 ∧ a2 :: x ++ A :: x0) = ((a1 ∧ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (a1 ∧ a2 :: x) x0). simpl (length (a1 ∧ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (a1 ∧ a2 :: x))). simpl. reflexivity.\n    rewrite H. assert ((a1 ∧ a2 :: x ++ A :: x0) = ((a1 ∧ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (a1 ∧ a2 :: x) x0). simpl (length (a1 ∧ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_atomimps_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (a1 ∨ a2 :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (a1 ∨ a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      a1 ∨ a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (a1 ∨ a2 :: x))). simpl. reflexivity.\n    rewrite H0. assert ((a1 ∨ a2 :: x ++ A :: x0) = ((a1 ∨ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (a1 ∨ a2 :: x) x0). simpl (length (a1 ∨ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (a1 ∨ a2 :: x))). simpl. reflexivity.\n    rewrite H. assert ((a1 ∨ a2 :: x ++ A :: x0) = ((a1 ∨ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (a1 ∨ a2 :: x) x0). simpl (length (a1 ∨ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. destruct a1.\n    + inversion H. inversion H1 ; subst. exists []. exists l. repeat split ; auto. simpl.\n       destruct (eq_dec_form (# v → a2) (# v → a2)) ; auto. exfalso. apply n ; auto.\n       subst. apply InT_map_iff in H1. destruct H1. destruct p.\n      destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n      apply InT_In in i. apply In_pos_top_atomimps_0_False in i. assumption.\n      apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n      subst. exists (# v → a2 :: x). exists x0. repeat split.\n      rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n      assert (fst (# v → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      # v → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n      assert (S (S (length x)) = S (length (# v → a2 :: x))). simpl. reflexivity.\n      rewrite H1. assert ((# v → a2 :: x ++ A :: x0) = ((# v → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n      rewrite H2. clear H2. clear H1. rewrite effective_remove_nth.\n      pose (nth_split_idL (# v → a2 :: x) x0). simpl (length (# v → a2 :: x)) in e2.\n      rewrite <- e2. reflexivity.\n      rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n      assert (S (S (length x)) = S (length (# v → a2 :: x))). simpl. reflexivity.\n      rewrite H0. assert ((# v → a2 :: x ++ A :: x0) = ((# v → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n      rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n      pose (nth_split_idR (# v → a2 :: x) x0). simpl (length (# v → a2 :: x)) in e2.\n      rewrite <- e2. reflexivity.\n    + apply InT_map_iff in H. destruct H. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_atomimps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists (⊥ V → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst (⊥ V → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        ⊥ V → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length (⊥ V → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert ((⊥ V → a2 :: x ++ A :: x0) = ((⊥ V → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL (⊥ V → a2 :: x) x0). simpl (length (⊥ V → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length (⊥ V → a2 :: x))). simpl. reflexivity.\n        rewrite H. assert ((⊥ V → a2 :: x ++ A :: x0) = ((⊥ V → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n        pose (nth_split_idR (⊥ V → a2 :: x) x0). simpl (length (⊥ V → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n    + apply InT_map_iff in H. destruct H. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_atomimps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists ((a1_1 ∧ a1_2) → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst ((a1_1 ∧ a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        (a1_1 ∧ a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length ((a1_1 ∧ a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert (((a1_1 ∧ a1_2) → a2 :: x ++ A :: x0) = (((a1_1 ∧ a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL ((a1_1 ∧ a1_2) → a2 :: x) x0). simpl (length ((a1_1 ∧ a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length ((a1_1 ∧ a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H. assert (((a1_1 ∧ a1_2) → a2 :: x ++ A :: x0) = (((a1_1 ∧ a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n        pose (nth_split_idR ((a1_1 ∧ a1_2) → a2 :: x) x0). simpl (length ((a1_1 ∧ a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n    + apply InT_map_iff in H. destruct H. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_atomimps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists ((a1_1 ∨ a1_2) → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst ((a1_1 ∨ a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        (a1_1 ∨ a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length ((a1_1 ∨ a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert (((a1_1 ∨ a1_2) → a2 :: x ++ A :: x0) = (((a1_1 ∨ a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL ((a1_1 ∨ a1_2) → a2 :: x) x0). simpl (length ((a1_1 ∨ a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length ((a1_1 ∨ a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H. assert (((a1_1 ∨ a1_2) → a2 :: x ++ A :: x0) = (((a1_1 ∨ a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n        pose (nth_split_idR ((a1_1 ∨ a1_2) → a2 :: x) x0). simpl (length ((a1_1 ∨ a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n    + apply InT_map_iff in H. destruct H. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_atomimps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists ((a1_1 → a1_2) → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst ((a1_1 → a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        (a1_1 → a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length ((a1_1 → a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert (((a1_1 → a1_2) → a2 :: x ++ A :: x0) = (((a1_1 → a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL ((a1_1 → a1_2) → a2 :: x) x0). simpl (length ((a1_1 → a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length ((a1_1 → a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H. assert (((a1_1 → a1_2) → a2 :: x ++ A :: x0) = (((a1_1 → a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n        pose (nth_split_idR ((a1_1 → a1_2) → a2 :: x) x0). simpl (length ((a1_1 → a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n    + apply InT_map_iff in H. destruct H. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_atomimps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists (Box a1 → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst (Box a1 → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        Box a1 → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length (Box a1 → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert ((Box a1 → a2 :: x ++ A :: x0) = ((Box a1 → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL (Box a1 → a2 :: x) x0). simpl (length (Box a1 → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length (Box a1 → a2 :: x))). simpl. reflexivity.\n        rewrite H. assert ((Box a1 → a2 :: x ++ A :: x0) = ((Box a1 → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n        pose (nth_split_idR (Box a1 → a2 :: x) x0). simpl (length (Box a1 → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_atomimps_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (Box a :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (Box a :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n    Box a :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (Box a :: x))). simpl. reflexivity.\n    rewrite H0. assert ((Box a :: x ++ A :: x0) = ((Box a :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (Box a :: x) x0). simpl (length (Box a :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (Box a :: x))). simpl. reflexivity.\n    rewrite H. assert ((Box a :: x ++ A :: x0) = ((Box a :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (Box a :: x) x0). simpl (length (Box a :: x)) in e2.\n    rewrite <- e2. reflexivity.\nQed.\n\nLemma In_pos_top_atomimps_L1_split_l : forall l (A : MPropF V) n, In (A, S n) (pos_top_atomimps_L1 l) ->\n          existsT2 l0 l1 l2 P, (l = l0 ++ # P :: l1 ++ A :: l2) *\n                          (length (l0 ++ # P :: l1) = n) *\n                          ( l0 ++ # P :: l1 = fst (nth_split n (remove_nth (S n) A l))) *\n                          (l2 = snd (nth_split n (remove_nth (S n) A l))).\nProof.\ninduction l.\n- intros. simpl. exfalso. simpl in H. destruct H.\n- intros. simpl in H. unfold pos_top_atomimps_L1 in H. apply In_InT_pair in H.\n  apply InT_map_iff in H. destruct H. destruct p. destruct x. destruct p. destruct p0. simpl in e.\n  inversion e. subst. unfold pos_atomimps_is_left_atoms in i. apply filter_InT in i. clear e.\n  destruct i. simpl in e. assert (n0 <? S n = true). apply andb_prop in e. destruct e.\n  auto. apply Nat.ltb_lt in H. apply InT_concat in i. destruct i. destruct p.\n  unfold all_pos_top_atoms_atomimps in i. apply InT_map_iff in i. destruct i.\n  destruct x0. destruct p. subst. apply InT_map_iff in i0. destruct i0.\n  destruct x. destruct p. inversion e0. subst. destruct a.\n  { simpl in i0. apply InT_map_iff in i0. destruct i0. destruct p. destruct x. simpl in e1.\n     inversion e1. subst. destruct n. exfalso. inversion H. subst. apply InT_In in i.\n     apply In_pos_top_atoms_0_False in i. auto. lia. inversion i.\n     - { inversion H1. subst. destruct A.\n       1-4: exfalso ; apply andb_prop in e ; destruct e ; unfold pair_atom_same_antec in H2 ; simpl in H2 ; inversion H2.\n       2: exfalso ; apply andb_prop in e ; destruct e ; unfold pair_atom_same_antec in H2 ; simpl in H2 ; inversion H2.\n       assert (A1 = # v). apply andb_prop in e. destruct e. unfold pair_atom_same_antec in H2. simpl in H2.\n       destruct A1. 2-6: exfalso ; inversion H2. apply eqb_prop_eq in H2. subst. auto. subst.\n       pose (InT_In i0). exists []. apply In_pos_top_atomimps_split_l in i1. destruct i1.\n       repeat destruct s. repeat destruct p ; subst. exists x. exists x0. exists v.\n       repeat split ; auto. assert (S (length x) = length (# v :: x)). auto. rewrite H0.\n       assert (# v :: x ++ # v → A2 :: x0 = (# v :: x) ++ # v → A2 :: x0). auto.\n       rewrite H2. rewrite effective_remove_nth. rewrite <- nth_split_idL. auto.\n       assert (S (length x) = length (# v :: x)). auto. rewrite H0.\n       assert (# v :: x ++ # v → A2 :: x0 = (# v :: x) ++ # v → A2 :: x0). auto.\n       rewrite H2. rewrite effective_remove_nth. rewrite <- nth_split_idR. auto. }\n     - subst. apply InT_map_iff in H1. destruct H1. destruct p. destruct x. simpl in e2. inversion e2. subst.\n       assert (In (A, S n) (pos_top_atomimps_L1 l)).\n       { unfold pos_top_atomimps_L1. apply in_map_iff. exists (m, n1, (A, S n)). simpl ; split ; auto.\n         unfold pos_atomimps_is_left_atoms. apply filter_In. split. 2: simpl.\n         2: apply andb_true_intro ; split ; auto. 2: apply Nat.ltb_lt ; lia. apply in_concat.\n         exists (map (fun y : MPropF V * nat => ((m, n1), y)) (pos_top_atomimps l)). split ; auto.\n         apply in_map_iff. exists (m, n1). split ; auto. apply InT_In ; auto. apply in_map_iff. exists (A, S n).\n         split ; auto. apply InT_In ; auto. unfold pair_atom_same_antec. simpl.\n         apply andb_prop in e. destruct e. unfold pair_atom_same_antec in H1. simpl in H1.\n         destruct m. 2-6: exfalso ; inversion H1. destruct A. 1-4: inversion H1. 2: inversion H1.\n         destruct A1. 2-6: inversion H1. auto. }\n       apply IHl in H0. destruct H0. repeat destruct s. repeat destruct p. subst.\n       exists (# v :: x). exists x0. exists x1. exists x2. repeat split ; auto.\n       assert (length (# v :: x ++ # x2 :: x0) = S (length (x ++ # x2 :: x0))).\n       simpl. auto. rewrite <- H0.\n       assert (# v :: x ++ # x2 :: x0 ++ A :: x1 = (# v :: x ++ # x2 :: x0) ++ A :: x1).\n       simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n       rewrite effective_remove_nth. rewrite <- nth_split_idL. auto.\n       assert (length (# v :: x ++ # x2 :: x0) = S (length (x ++ # x2 :: x0))).\n       simpl. auto. rewrite <- H0.\n       assert (# v :: x ++ # x2 :: x0 ++ A :: x1 = (# v :: x ++ # x2 :: x0) ++ A :: x1).\n       simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n       rewrite effective_remove_nth. rewrite <- nth_split_idR. auto. }\n  { simpl in i0. apply InT_map_iff in i0. destruct i0. destruct p. destruct x. simpl in e1.\n     inversion e1. subst. simpl in i. apply InT_map_iff in i. destruct i. destruct x. simpl in p.\n     destruct p. inversion e2. subst. clear e0. clear e2. clear e1.\n     assert (In (A, n) (pos_top_atomimps_L1 l)).\n     { unfold pos_top_atomimps_L1. apply in_map_iff. exists (m, n1, (A, n)). simpl ; split ; auto.\n       unfold pos_atomimps_is_left_atoms. apply filter_In. split. 2: simpl.\n       2: apply andb_true_intro ; split ; auto. 2: apply Nat.ltb_lt ; lia. apply in_concat.\n       exists (map (fun y : MPropF V * nat => ((m, n1), y)) (pos_top_atomimps l)). split ; auto.\n       apply in_map_iff. exists (m, n1). split ; auto. apply InT_In ; auto. apply in_map_iff. exists (A, n).\n       split ; auto. apply InT_In ; auto. unfold pair_atom_same_antec. simpl.\n       apply andb_prop in e. destruct e. unfold pair_atom_same_antec in H1. simpl in H1.\n       destruct m. 2-6: exfalso ; inversion H1. destruct A. 1-4: inversion H1. 2: inversion H1.\n       destruct A1. 2-6: inversion H1. auto. }\n     destruct n. exfalso. apply In_pos_top_atomimps_L1_0_False in H0. auto.\n     apply IHl in H0. destruct H0. repeat destruct s. repeat destruct p. subst.\n     exists (⊥ V :: x). exists x0. exists x1. exists x2. repeat split ; auto.\n     assert (length (⊥ V :: x ++ # x2 :: x0) = S (length (x ++ # x2 :: x0))).\n     simpl. auto. rewrite <- H0.\n     assert (⊥ V :: x ++ # x2 :: x0 ++ A :: x1 = (⊥ V :: x ++ # x2 :: x0) ++ A :: x1).\n     simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n     rewrite effective_remove_nth. rewrite <- nth_split_idL. auto.\n     assert (length (⊥ V :: x ++ # x2 :: x0) = S (length (x ++ # x2 :: x0))).\n     simpl. auto. rewrite <- H0.\n     assert (⊥ V :: x ++ # x2 :: x0 ++ A :: x1 = (⊥ V:: x ++ # x2 :: x0) ++ A :: x1).\n     simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n     rewrite effective_remove_nth. rewrite <- nth_split_idR. auto. }\n  { simpl in i0. apply InT_map_iff in i0. destruct i0. destruct p. destruct x. simpl in e1.\n     inversion e1. subst. simpl in i. apply InT_map_iff in i. destruct i. destruct x. simpl in p.\n     destruct p. inversion e2. subst. clear e0. clear e2. clear e1.\n     assert (In (A, n) (pos_top_atomimps_L1 l)).\n     { unfold pos_top_atomimps_L1. apply in_map_iff. exists (m, n1, (A, n)). simpl ; split ; auto.\n       unfold pos_atomimps_is_left_atoms. apply filter_In. split. 2: simpl.\n       2: apply andb_true_intro ; split ; auto. 2: apply Nat.ltb_lt ; lia. apply in_concat.\n       exists (map (fun y : MPropF V * nat => ((m, n1), y)) (pos_top_atomimps l)). split ; auto.\n       apply in_map_iff. exists (m, n1). split ; auto. apply InT_In ; auto. apply in_map_iff. exists (A, n).\n       split ; auto. apply InT_In ; auto. unfold pair_atom_same_antec. simpl.\n       apply andb_prop in e. destruct e. unfold pair_atom_same_antec in H1. simpl in H1.\n       destruct m. 2-6: exfalso ; inversion H1. destruct A. 1-4: inversion H1. 2: inversion H1.\n       destruct A1. 2-6: inversion H1. auto. }\n     destruct n. exfalso. apply In_pos_top_atomimps_L1_0_False in H0. auto.\n     apply IHl in H0. destruct H0. repeat destruct s. repeat destruct p. subst.\n     exists (a1 ∧ a2 :: x). exists x0. exists x1. exists x2. repeat split ; auto.\n     assert (length (a1 ∧ a2 :: x ++ # x2 :: x0) = S (length (x ++ # x2 :: x0))).\n     simpl. auto. rewrite <- H0.\n     assert (a1 ∧ a2 :: x ++ # x2 :: x0 ++ A :: x1 = (a1 ∧ a2 :: x ++ # x2 :: x0) ++ A :: x1).\n     simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n     rewrite effective_remove_nth. rewrite <- nth_split_idL. auto.\n     assert (length (a1 ∧ a2 :: x ++ # x2 :: x0) = S (length (x ++ # x2 :: x0))).\n     simpl. auto. rewrite <- H0.\n     assert (a1 ∧ a2 :: x ++ # x2 :: x0 ++ A :: x1 = (a1 ∧ a2 :: x ++ # x2 :: x0) ++ A :: x1).\n     simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n     rewrite effective_remove_nth. rewrite <- nth_split_idR. auto. }\n  { simpl in i0. apply InT_map_iff in i0. destruct i0. destruct p. destruct x. simpl in e1.\n     inversion e1. subst. simpl in i. apply InT_map_iff in i. destruct i. destruct x. simpl in p.\n     destruct p. inversion e2. subst. clear e0. clear e2. clear e1.\n     assert (In (A, n) (pos_top_atomimps_L1 l)).\n     { unfold pos_top_atomimps_L1. apply in_map_iff. exists (m, n1, (A, n)). simpl ; split ; auto.\n       unfold pos_atomimps_is_left_atoms. apply filter_In. split. 2: simpl.\n       2: apply andb_true_intro ; split ; auto. 2: apply Nat.ltb_lt ; lia. apply in_concat.\n       exists (map (fun y : MPropF V * nat => ((m, n1), y)) (pos_top_atomimps l)). split ; auto.\n       apply in_map_iff. exists (m, n1). split ; auto. apply InT_In ; auto. apply in_map_iff. exists (A, n).\n       split ; auto. apply InT_In ; auto. unfold pair_atom_same_antec. simpl.\n       apply andb_prop in e. destruct e. unfold pair_atom_same_antec in H1. simpl in H1.\n       destruct m. 2-6: exfalso ; inversion H1. destruct A. 1-4: inversion H1. 2: inversion H1.\n       destruct A1. 2-6: inversion H1. auto. }\n     destruct n. exfalso. apply In_pos_top_atomimps_L1_0_False in H0. auto.\n     apply IHl in H0. destruct H0. repeat destruct s. repeat destruct p. subst.\n     exists (a1 ∨ a2 :: x). exists x0. exists x1. exists x2. repeat split ; auto.\n     assert (length (a1 ∨ a2 :: x ++ # x2 :: x0) = S (length (x ++ # x2 :: x0))).\n     simpl. auto. rewrite <- H0.\n     assert (a1 ∨ a2 :: x ++ # x2 :: x0 ++ A :: x1 = (a1 ∨ a2 :: x ++ # x2 :: x0) ++ A :: x1).\n     simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n     rewrite effective_remove_nth. rewrite <- nth_split_idL. auto.\n     assert (length (a1 ∨ a2 :: x ++ # x2 :: x0) = S (length (x ++ # x2 :: x0))).\n     simpl. auto. rewrite <- H0.\n     assert (a1 ∨ a2 :: x ++ # x2 :: x0 ++ A :: x1 = (a1 ∨ a2 :: x ++ # x2 :: x0) ++ A :: x1).\n     simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n     rewrite effective_remove_nth. rewrite <- nth_split_idR. auto. }\n  { simpl in i0. destruct n. exfalso. inversion H. subst. apply InT_In in i. apply In_pos_top_atoms_0_False in i. auto.\n     subst. lia.\n     assert (InT (A, S (S n)) (map (fun y : MPropF V * nat => (fst y, S (snd y))) (pos_top_atomimps l))).\n     { destruct a1. 2-6: auto. inversion i0. subst. inversion H1. auto. }\n     apply InT_map_iff in H0. destruct H0. destruct p. destruct x. simpl in e1.\n     inversion e1. subst. simpl in i. apply InT_map_iff in i. destruct i. destruct x. simpl in p.\n     destruct p. inversion e2. subst. clear e0. clear e2. clear e1.\n     assert (In (A, S n) (pos_top_atomimps_L1 l)).\n     { unfold pos_top_atomimps_L1. apply in_map_iff. exists (m, n1, (A, S n)). simpl ; split ; auto.\n       unfold pos_atomimps_is_left_atoms. apply filter_In. split. 2: simpl.\n       2: apply andb_true_intro ; split ; auto. 2: apply Nat.ltb_lt ; lia. apply in_concat.\n       exists (map (fun y : MPropF V * nat => ((m, n1), y)) (pos_top_atomimps l)). split ; auto.\n       apply in_map_iff. exists (m, n1). split ; auto. apply InT_In ; auto. apply in_map_iff. exists (A, S n).\n       split ; auto. apply InT_In ; auto. unfold pair_atom_same_antec. simpl.\n       apply andb_prop in e. destruct e. unfold pair_atom_same_antec in H1. simpl in H1.\n       destruct m. 2-6: exfalso ; inversion H1. destruct A. 1-4: inversion H1. 2: inversion H1.\n       destruct A1. 2-6: inversion H1. auto. }\n     apply IHl in H0. destruct H0. repeat destruct s. repeat destruct p. subst.\n     exists (a1 → a2 :: x). exists x0. exists x1. exists x2. repeat split ; auto.\n     assert (length (a1 → a2 :: x ++ # x2 :: x0) = S (length (x ++ # x2 :: x0))).\n     simpl. auto. rewrite <- H0.\n     assert (a1 → a2 :: x ++ # x2 :: x0 ++ A :: x1 = (a1 → a2 :: x ++ # x2 :: x0) ++ A :: x1).\n     simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n     rewrite effective_remove_nth. rewrite <- nth_split_idL. auto.\n     assert (length (a1 → a2 :: x ++ # x2 :: x0) = S (length (x ++ # x2 :: x0))).\n     simpl. auto. rewrite <- H0.\n     assert (a1 → a2 :: x ++ # x2 :: x0 ++ A :: x1 = (a1 → a2 :: x ++ # x2 :: x0) ++ A :: x1).\n     simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n     rewrite effective_remove_nth. rewrite <- nth_split_idR. auto. }\n  { simpl in i0. apply InT_map_iff in i0. destruct i0. destruct p. destruct x. simpl in e1.\n     inversion e1. subst. simpl in i. apply InT_map_iff in i. destruct i. destruct x. simpl in p.\n     destruct p. inversion e2. subst. clear e0. clear e2. clear e1.\n     assert (In (A, n) (pos_top_atomimps_L1 l)).\n     { unfold pos_top_atomimps_L1. apply in_map_iff. exists (m, n1, (A, n)). simpl ; split ; auto.\n       unfold pos_atomimps_is_left_atoms. apply filter_In. split. 2: simpl.\n       2: apply andb_true_intro ; split ; auto. 2: apply Nat.ltb_lt ; lia. apply in_concat.\n       exists (map (fun y : MPropF V * nat => ((m, n1), y)) (pos_top_atomimps l)). split ; auto.\n       apply in_map_iff. exists (m, n1). split ; auto. apply InT_In ; auto. apply in_map_iff. exists (A, n).\n       split ; auto. apply InT_In ; auto. unfold pair_atom_same_antec. simpl.\n       apply andb_prop in e. destruct e. unfold pair_atom_same_antec in H1. simpl in H1.\n       destruct m. 2-6: exfalso ; inversion H1. destruct A. 1-4: inversion H1. 2: inversion H1.\n       destruct A1. 2-6: inversion H1. auto. }\n     destruct n. exfalso. apply In_pos_top_atomimps_L1_0_False in H0. auto.\n     apply IHl in H0. destruct H0. repeat destruct s. repeat destruct p. subst.\n     exists (Box a :: x). exists x0. exists x1. exists x2. repeat split ; auto.\n     assert (length (Box a :: x ++ # x2 :: x0) = S (length (x ++ # x2 :: x0))).\n     simpl. auto. rewrite <- H0.\n     assert (Box a :: x ++ # x2 :: x0 ++ A :: x1 = (Box a :: x ++ # x2 :: x0) ++ A :: x1).\n     simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n     rewrite effective_remove_nth. rewrite <- nth_split_idL. auto.\n     assert (length (Box a :: x ++ # x2 :: x0) = S (length (x ++ # x2 :: x0))).\n     simpl. auto. rewrite <- H0.\n     assert (Box a :: x ++ # x2 :: x0 ++ A :: x1 = (Box a :: x ++ # x2 :: x0) ++ A :: x1).\n     simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n     rewrite effective_remove_nth. rewrite <- nth_split_idR. auto. }\nQed.\n\nLemma Good_pos_in_pos_top_atomimps : forall A P Γ0 Γ1,\n              In (Imp # P A, S (length Γ0)) (pos_top_atomimps (Γ0 ++ Imp # P A :: Γ1)).\nProof.\ninduction Γ0.\n- intros. simpl. auto.\n- intros. destruct a.\n  1-4: simpl ; apply InT_In ; apply InT_map_iff ; exists (Imp # P A, S (length Γ0)) ;\n  split ; simpl ; try reflexivity ; apply In_InT_pair ; apply IHΓ0.\n  2: simpl ; apply InT_In ; apply InT_map_iff ; exists (Imp # P A, S (length Γ0)) ;\n  split ; simpl ; try reflexivity ; apply In_InT_pair ; apply IHΓ0.\n  simpl. destruct a1.\n  simpl ; right ; apply InT_In ; apply InT_map_iff ; exists (Imp # P A, S (length Γ0)) ;\n  split ; simpl ; try reflexivity ; apply In_InT_pair ; apply IHΓ0.\n  1-5: simpl ; apply InT_In ; apply InT_map_iff ; exists (Imp # P A, S (length Γ0)) ;\n  split ; simpl ; try reflexivity ; apply In_InT_pair ; apply IHΓ0.\nQed.\n\nLemma Good_pos_in_pos_top_atoms : forall P Γ0 Γ1,\n              In (# P, S (length Γ0)) (pos_top_atoms (Γ0 ++ # P :: Γ1)).\nProof.\ninduction Γ0.\n- intros. simpl. auto.\n- intros. destruct a.\n  2-6: simpl ; apply InT_In ; apply InT_map_iff ; exists (# P, S (length Γ0)) ;\n  split ; simpl ; try reflexivity ; apply In_InT_pair ; apply IHΓ0.\n  simpl. right. apply in_map_iff. exists (# P, S (length Γ0)). split ; auto.\nQed.\n\nLemma Good_pos_in_pos_top_atom_atomimps_L1 : forall A P Γ0 Γ1 Γ2,\n              In (# P → A, S (length (Γ0 ++ # P :: Γ1))) (pos_top_atomimps_L1 (Γ0 ++ # P :: Γ1 ++ # P → A :: Γ2)).\nProof.\ninduction Γ0.\n- intros. simpl. unfold pos_top_atomimps_L1. unfold pos_atomimps_is_left_atoms. apply in_map_iff.\n  exists ((# P, 1),(# P → A, S (S (length Γ1)))). split. auto. apply filter_In. split. apply in_concat.\n  exists (map (fun y : MPropF V * nat => ((# P,1), y)) (pos_top_atomimps (# P :: Γ1 ++ # P → A :: Γ2))).\n  split. unfold all_pos_top_atoms_atomimps. apply in_map_iff. exists (# P, 1) ; split ; auto.\n  simpl. auto. apply in_map_iff. exists (# P → A, S (S (length Γ1))). split ; auto. simpl.\n  apply in_map_iff. exists ((# P → A, S (length Γ1))). split ; simpl ; auto.\n  apply Good_pos_in_pos_top_atomimps. simpl. unfold pair_atom_same_antec.\n  simpl. apply eqb_prop_eq. auto.\n- intros. simpl. pose (IHΓ0 Γ1 Γ2). unfold pos_top_atomimps_L1 in i. unfold pos_atomimps_is_left_atoms in i.\n  apply in_map_iff in i. destruct i. destruct x. destruct p. destruct p0. simpl in H. destruct H. inversion H. subst.\n  clear H. apply filter_In in H0. destruct H0. simpl in H0. apply in_concat in H. destruct H. destruct H.\n  apply andb_prop in H0. destruct H0. apply Nat.ltb_lt in H0. unfold pair_atom_same_antec in H2. simpl in H2.\n  destruct m. 2-6: exfalso ; inversion H2. apply eqb_prop_eq in H2. subst. unfold all_pos_top_atoms_atomimps in H.\n  apply in_map_iff in H. destruct H. destruct H. subst. apply in_map_iff in H1. destruct H1. destruct x0. destruct x.\n  destruct H. inversion H. subst. clear H. unfold pos_top_atomimps_L1.\n  apply in_map_iff. exists ((#P, S n),(# P → A, S (S (length (Γ0 ++ # P :: Γ1))))). simpl. split ; auto.\n  unfold pos_atomimps_is_left_atoms. apply filter_In. repeat split. 2: simpl ; auto.\n  2: apply andb_true_intro. 2: split. 2: apply Nat.ltb_lt. 2: lia. 2: unfold pair_atom_same_antec.\n  2: simpl ; apply eqb_prop_eq ; auto. apply in_concat.\n  exists (map (fun y : MPropF V * nat => ((# P, S n), y)) (pos_top_atomimps (a :: Γ0 ++ # P :: Γ1 ++ # P → A :: Γ2))). split ; auto.\n  unfold all_pos_top_atoms_atomimps. apply in_map_iff. exists (# P, S n). split ; auto.\n  unfold pos_top_atoms. destruct a. 2-6:apply in_map_iff ; exists (# P, n) ; simpl ; split ; auto.\n  apply in_cons. apply in_map_iff ; exists (# P, n) ; simpl ; split ; auto.\n  apply in_map_iff. exists (# P → A, S (S (length (Γ0 ++ # P :: Γ1)))). split ; auto.\n  simpl. destruct a.\n  1-4: apply in_map_iff ; exists ((# P → A, S (length (Γ0 ++ # P :: Γ1)))) ; simpl ; split ; auto.\n  2: apply in_map_iff ; exists ((# P → A, S (length (Γ0 ++ # P :: Γ1)))) ; simpl ; split ; auto.\n  destruct a1. 2-6: apply in_map_iff ; exists ((# P → A, S (length (Γ0 ++ # P :: Γ1)))) ; simpl ; split ; auto.\n  apply in_cons.  apply in_map_iff ; exists ((# P → A, S (length (Γ0 ++ # P :: Γ1)))) ; simpl ; split ; auto.\nQed.\n\nLemma AtomImpL1_help01 : forall prem s l, InT prem (prems_AtomImp_L1 l s) ->\n                  (existsT2 n A P Γ0 Γ1 C,\n                        (In (Imp # P A, S n) l) *\n                        (prem = (Γ0 ++ A :: Γ1, C)) *\n                        (C = snd s) *\n                        (Γ0 = (fst (nth_split n (remove_nth (S n) (Imp # P A) (fst s))))) *\n                        (Γ1 = (snd (nth_split n (remove_nth (S n) (Imp # P A) (fst s)))))).\nProof.\nintros prem s. destruct s. induction l0 ; intros.\n- simpl in H. inversion H.\n- simpl (fst (l, m)). destruct a. destruct m0.\n  1-4: simpl in H ; destruct n ; pose (IHl0 H) ; repeat destruct s ; repeat destruct p ; exists x ; exists x0 ; exists x1 ;\n  exists x2 ; exists x3 ; exists x4 ; repeat split ; try auto ; apply in_cons ; assumption.\n  2: simpl in H ; destruct n ; pose (IHl0 H) ; repeat destruct s ; repeat destruct p ; exists x ; exists x0 ; exists x1 ;\n  exists x2 ; exists x3 ; exists x4 ; repeat split ; try auto ; apply in_cons ; assumption.\n  destruct m0_1.\n  2-6: simpl in H ; destruct n ; pose (IHl0 H) ; repeat destruct s ; repeat destruct p ; exists x ; exists x0 ; exists x1 ;\n  exists x2 ; exists x3 ; exists x4 ; repeat split ; try auto ; apply in_cons ; assumption.\n  destruct n.\n  + pose (IHl0 H). repeat destruct s. repeat destruct p. exists x. exists x0. exists x1.\n     exists x2. exists x3. exists x4. repeat split ; try auto. apply in_cons. assumption.\n  + unfold prems_AtomImp_L1 in H. simpl (snd (l, m)). simpl (fst (l, m)).\n     assert ((prem = ((fst (nth_split n (remove_nth (S n) (# v → m0_2) l)) ++\n        m0_2 :: snd (nth_split n (remove_nth (S n) (# v → m0_2) (fst (l, m)))), m))) +\n     InT prem ((fix prems_AtomImp_L1 (l : list (MPropF V * nat)) (s : list (MPropF V) * MPropF V) {struct l} :\n               list (list (MPropF V) * MPropF V) :=\n             match l with\n             | [] => []\n             | (C, 0) :: t => prems_AtomImp_L1 t s\n             | (C, S m) :: t =>\n                 match C with\n                 | # _ → B =>\n                     (fst (nth_split m (remove_nth (S m) C (fst s))) ++ B :: snd (nth_split m (remove_nth (S m) C (fst s))), snd s)\n                     :: prems_AtomImp_L1 t s\n                 | _ => prems_AtomImp_L1 t s\n                 end\n             end) l0 (l, m))).\n      inversion H ; auto. destruct H0.\n    * subst. clear H. clear IHl0. exists n. exists m0_2. exists v. simpl (fst (l, m)).\n      exists (fst (nth_split n (remove_nth (S n) (# v → m0_2) l))).\n      exists (snd (nth_split n (remove_nth (S n) (# v → m0_2) l))). exists m. repeat split ; auto. apply in_eq.\n    * apply IHl0 in i. destruct i. repeat destruct s. repeat destruct p. exists x. exists x0. exists x1.\n      exists x2. exists x3. exists x4. repeat split ; try auto. apply in_cons. assumption.\nQed.\n\nLemma pos_top_atoms_insert : forall n Γ0 Γ1 m, InT (m, n) (pos_top_atoms (Γ0 ++ Γ1)) ->\n                                                    n < S (length Γ0) ->\n                                                    existsT2 Γ2 Γ3 : list (MPropF V), Γ2 ++ m :: Γ3 = Γ0.\nProof.\ninduction n.\n- intros. apply InT_In in H. apply In_pos_top_atoms_0_False in H. inversion H.\n- intros. destruct Γ0.\n  + simpl in H0. exfalso. lia.\n  + simpl in H0. assert (n < S (length Γ0)). lia.\n     destruct m0.\n     * simpl in H. inversion H. subst. inversion H3. subst. exists []. exists Γ0. auto.\n        subst. apply InT_map_iff in H3. destruct H3. destruct x. destruct p. simpl in e.\n        inversion e. subst. pose (@IHn Γ0 Γ1 m i H1). repeat destruct s. rewrite <- e0.\n        exists (# v :: x). exists x0. simpl ; auto.\n     * simpl in H. apply InT_map_iff in H. destruct H. destruct x. destruct p. simpl in e.\n        inversion e. subst. pose (@IHn Γ0 Γ1 m i H1). repeat destruct s. rewrite <- e0.\n        exists (⊥ V :: x). exists x0. simpl ; auto.\n     * simpl in H. apply InT_map_iff in H. destruct H. destruct x. destruct p. simpl in e.\n        inversion e. subst. pose (@IHn Γ0 Γ1 m i H1). repeat destruct s. rewrite <- e0.\n        exists (m0_1 ∧ m0_2 :: x). exists x0. simpl ; auto.\n     * simpl in H. apply InT_map_iff in H. destruct H. destruct x. destruct p. simpl in e.\n        inversion e. subst. pose (@IHn Γ0 Γ1 m i H1). repeat destruct s. rewrite <- e0.\n        exists (m0_1 ∨ m0_2 :: x). exists x0. simpl ; auto.\n     * simpl in H. apply InT_map_iff in H. destruct H. destruct x. destruct p. simpl in e.\n        inversion e. subst. pose (@IHn Γ0 Γ1 m i H1). repeat destruct s. rewrite <- e0.\n        exists (m0_1 → m0_2 :: x). exists x0. simpl ; auto.\n     * simpl in H. apply InT_map_iff in H. destruct H. destruct x. destruct p. simpl in e.\n        inversion e. subst. pose (@IHn Γ0 Γ1 m i H1). repeat destruct s. rewrite <- e0.\n        exists (Box m0 :: x). exists x0. simpl ; auto.\nQed.\n\nLemma exfalso_list_0 : forall l (A : MPropF V), (A :: l = l) -> False.\nProof.\ninduction l.\n- intros. inversion H.\n- intros. inversion H. apply IHl in H2. auto.\nQed.\n\nLemma exfalso_list_1 : forall (l1 l0 : list (MPropF V)), (l0 <> nil) -> (l0 ++ l1 = l1) -> False.\nProof.\ninduction l1.\n- intros. rewrite app_nil_r in H0. subst. apply H ; auto.\n- intros. destruct l0.\n  * simpl in H0. apply H ; auto.\n  * inversion H0. assert (l0 ++ [a] <> []). intro. destruct l0. simpl in H1. inversion H1. inversion H1.\n    assert ((l0 ++ [a]) ++ l1 = l1). rewrite <- app_assoc ; auto.\n    pose (IHl1 (l0 ++ [a]) H1 H4). auto.\nQed.\n\nLemma one_less_remove_split : forall n l0 l1 P B C,\n    (fst (nth_split (S n) (remove_nth (S (S n)) (Imp (# P) C) (B :: l0))) ++ C :: (snd (nth_split (S n) (remove_nth (S (S n)) (Imp (# P) C) (B :: l0)))) = B :: l1) ->\n    (fst (nth_split n (remove_nth (S n) (# P → C) l0)) ++ C :: snd (nth_split n (remove_nth (S n) (# P → C) l0)) = l1).\nProof.\ninduction n.\n- intros. simpl. simpl in H. inversion H. destruct l0 ; auto.\n- intros. simpl in H. inversion H. subst. simpl. auto.\nQed.\n\n\nLemma one_less_remove_split1 : forall n P0 P1 C A Γ0 Γ1 m,\n    (fst (nth_split (S n) (remove_nth (S (S n)) (# P1 → C) ((m :: Γ0) ++ # P0 → A :: Γ1))) ++\n    C :: snd (nth_split (S n) (remove_nth (S (S n)) (# P1 → C) ((m :: Γ0) ++ # P0 → A :: Γ1))) = (m :: Γ0) ++ A :: Γ1) ->\n    (fst (nth_split n (remove_nth (S n) (# P1 → C) (Γ0 ++ # P0 → A :: Γ1))) ++\n    C :: snd (nth_split n (remove_nth (S n) (# P1 → C) (Γ0 ++ # P0 → A :: Γ1))) = Γ0 ++ A :: Γ1).\nProof.\nintros. apply one_less_remove_split with (B:=m). auto.\nQed.\n\n\nLemma remove_split_eq : forall P0 P1 A C n Γ0 Γ1,\n((fst (nth_split n (remove_nth (S n) (# P1 → C) (Γ0 ++ # P0 → A :: Γ1)))) ++ C :: (snd (nth_split n (remove_nth (S n) (# P1 → C) (Γ0 ++ # P0 → A :: Γ1)))) =\nΓ0 ++ A :: Γ1) ->\n(A = C) * (P0 = P1) * (Γ0 = fst (nth_split n (remove_nth (S n) (# P1 → C) (Γ0 ++ # P0 → A :: Γ1)))) *\n(Γ1 = snd (nth_split n (remove_nth (S n) (# P1 → C) (Γ0 ++ # P0 → A :: Γ1)))) * (length Γ0 = n).\nProof.\ninduction n.\n- intros. simpl. destruct Γ0.\n  * simpl. simpl in H. destruct (eq_dec_form (# P1 → C) (# P0 → A)).\n    + inversion H ; inversion e ; auto ; repeat split ; auto.\n    + inversion H ; subst. exfalso. apply exfalso_list_0 in H2 ; auto.\n  * simpl. exfalso. simpl in H. inversion H. subst.\n    destruct (eq_dec_form (# P1 → m) m). assert (weight_form (# P1 → m) = weight_form m).\n    rewrite e. auto. simpl in H0. lia.\n    assert (length (m :: Γ0 ++ # P0 → A :: Γ1) = length (Γ0 ++ A :: Γ1)). rewrite H2. auto.\n    simpl in H0. repeat rewrite app_length in H0. simpl in H0. lia.\n- intros. destruct Γ0.\n  * simpl in H. destruct n. simpl in H. exfalso. inversion H. assert (weight_form (# P0 → A) = weight_form A).\n    rewrite H1. auto. simpl in H0. lia. simpl in H. inversion H. subst. exfalso. assert (weight_form (# P0 → A) = weight_form A).\n    rewrite H1. auto. simpl in H0. lia.\n  * pose (IHn Γ0 Γ1). assert (fst (nth_split n (remove_nth (S n) (# P1 → C) (Γ0 ++ # P0 → A :: Γ1))) ++\n    C :: snd (nth_split n (remove_nth (S n) (# P1 → C) (Γ0 ++ # P0 → A :: Γ1))) = Γ0 ++ A :: Γ1).\n    apply one_less_remove_split1 in H. auto.\n    apply p in H0. repeat destruct H0. repeat destruct p0. clear p. subst. repeat split ; auto.\n    1-2 : assert (S (length Γ0) = length (m :: Γ0)) ; auto ; rewrite H0 ; rewrite effective_remove_nth.\n    rewrite <- nth_split_idL ; auto. rewrite <- nth_split_idR ; auto.\nQed.\n\n\nLemma AtomImpL1_help0111 : forall A P l Γ0 Γ1 C,\n      InT (Γ0 ++ A :: Γ1, C) (prems_AtomImp_L1 l (Γ0 ++ # P → A :: Γ1, C)) ->\n      InT (# P → A, S (length Γ0)) l.\nProof.\ninduction l.\n- intros. simpl in H. inversion H.\n- intros. destruct a. destruct m.\n  * apply InT_cons. apply IHl with (Γ1:=Γ1) (C:=C).\n     unfold prems_AtomImp_L1 in H. destruct n ; auto.\n  * apply InT_cons. apply IHl with (Γ1:=Γ1) (C:=C).\n     unfold prems_AtomImp_L1 in H. destruct n ; auto.\n  * apply InT_cons. apply IHl with (Γ1:=Γ1) (C:=C).\n     unfold prems_AtomImp_L1 in H. destruct n ; auto.\n  * apply InT_cons. apply IHl with (Γ1:=Γ1) (C:=C).\n     unfold prems_AtomImp_L1 in H. destruct n ; auto.\n  * simpl in H. destruct n ; auto. apply IHl in H. apply InT_cons ; auto.\n    simpl in H. destruct m1 ; simpl in H. 2-6: apply IHl in H ; apply InT_cons ; auto.\n    inversion H. 2: subst ; apply IHl in H1 ; apply InT_cons ; auto.\n    subst. inversion H1. clear H1. clear H. apply remove_split_eq in H2.\n    destruct H2. repeat destruct p. subst. apply InT_eq.\n  * apply InT_cons. apply IHl with (Γ1:=Γ1) (C:=C).\n     unfold prems_AtomImp_L1 in H. destruct n ; auto.\nQed.\n\nLemma AtomImpL1_help011 : forall A P Γ0 Γ1 C,\n      InT (Γ0 ++ A :: Γ1, C) (prems_AtomImp_L1 (pos_top_atomimps_L1 (Γ0 ++ # P → A :: Γ1)) (Γ0 ++ # P → A :: Γ1, C)) ->\n      (existsT2 Γ2 Γ3, Γ2 ++ # P :: Γ3 = Γ0).\nProof.\nintros.\nassert (InT (# P → A, S (length Γ0)) (pos_top_atomimps_L1 (Γ0 ++ # P → A :: Γ1))).\napply AtomImpL1_help0111 with (Γ1:=Γ1) (C:=C) ; auto.\nunfold pos_top_atomimps_L1 in H0. unfold pos_atomimps_is_left_atoms in H0.\nunfold all_pos_top_atoms_atomimps in H0. apply InT_map_iff in H0.\ndestruct H0. destruct x. simpl in p. destruct p. subst. destruct p0. apply filter_InT in i.\ndestruct i. simpl in e. assert (m = # P). symmetry in e ; apply Bool.andb_true_eq in e.\ndestruct e. unfold pair_atom_same_antec in H1. simpl in H1. destruct m ; simpl in H1 ; inversion H1.\nsymmetry in H3. apply eqb_prop_eq in H3. subst. auto. subst.\napply InT_concat in i. destruct i. destruct p.\napply InT_map_iff in i. destruct i. destruct p. subst. apply Bool.andb_true_iff in e.\ndestruct e. apply Nat.ltb_lt in H0. unfold pair_atom_same_antec in H1.\nsimpl in H1. apply InT_map_iff in i0. destruct i0. destruct p. inversion e.\nsubst. clear e. pose (@pos_top_atoms_insert n Γ0 (# P → A :: Γ1) (# P) i H0). assumption.\nQed.\n\nLemma AtomImpL1_help1 : forall prem s, InT prem (prems_AtomImp_L1 (pos_top_atomimps_L1 (fst s)) s) -> AtomImpL1Rule [prem] s.\nProof.\nintros. destruct s. simpl in H. pose (@AtomImpL1_help01 _ _ _ H). repeat destruct s.\nrepeat destruct p. subst. simpl in i. simpl (fst (l, m)).\nsimpl (fst (l, m)) in H. simpl (snd (l, m)). simpl (snd (l, m)) in H.\napply In_pos_top_atomimps_L1_split_l in i.\ndestruct i. repeat destruct s. repeat destruct p. rewrite <- e. simpl (fst (l, m)) in e0. rewrite <- e0.\nsubst. repeat rewrite <- app_assoc. simpl.\nassert (x2 ++ # x5 :: x3 ++ # x1 → x0 :: x4 = (x2 ++ # x5 :: x3) ++ # x1 → x0 :: x4). repeat rewrite <- app_assoc ; auto.\nrewrite H0 in H.\nrepeat rewrite effective_remove_nth in H. rewrite <- nth_split_idL in H. rewrite <- nth_split_idR in H.\napply AtomImpL1_help011 in H. destruct H. destruct s. rewrite <- e1 in H0. rewrite H0.\nassert (x2 ++ # x5 :: x3 ++ x0 :: x4 = (x2 ++ # x5 :: x3) ++ x0 :: x4). repeat rewrite <- app_assoc ; auto.\nrewrite <- e1 in H. rewrite H. repeat rewrite <- app_assoc. simpl. apply AtomImpL1Rule_I.\nQed.\n\nLemma AtomImpL1_help002 : forall Γ0 Γ1 Γ2 l C A P,\n           InT (Γ0 ++ # P :: Γ1 ++ A :: Γ2, C) (prems_AtomImp_L1 ((Imp # P A, S (length (Γ0 ++ # P :: Γ1))) :: l) (Γ0 ++ # P :: Γ1 ++ # P → A :: Γ2, C)).\nProof.\nintros. unfold prems_AtomImp_L1.\nsimpl (fst (Γ0 ++ # P :: Γ1 ++ # P → A :: Γ2, C)). simpl (fst (Γ0 ++ # P :: Γ1 ++ # P → A :: Γ2, C)).\nsimpl (snd (Γ0 ++ # P :: Γ1 ++ # P → A :: Γ2, C)).\nassert (Γ0 ++ # P :: Γ1 ++ # P → A :: Γ2 = (Γ0 ++ # P :: Γ1) ++ # P → A :: Γ2). repeat rewrite <- app_assoc ; auto.\nrewrite H.\nrepeat rewrite effective_remove_nth. pose (nth_split_idL (Γ0 ++ # P :: Γ1) Γ2).\nrewrite <- e. pose (nth_split_idR (Γ0 ++ # P :: Γ1) Γ2). rewrite <- e0. repeat rewrite <- app_assoc. simpl. apply InT_eq.\nQed.\n\nLemma AtomImpL1_help02 : forall Γ0 Γ1 Γ2 A P C l n,\n            AtomImpL1Rule [(Γ0 ++ # P :: Γ1 ++ A :: Γ2, C)] (Γ0 ++ # P :: Γ1 ++ # P → A :: Γ2, C) ->\n            (length (Γ0 ++ # P :: Γ1) = n) ->\n            (In (# P → A, S n) l) ->\n            InT (Γ0 ++ # P :: Γ1 ++ A :: Γ2, C) (prems_AtomImp_L1 l (Γ0 ++ # P :: Γ1 ++ # P → A :: Γ2, C)).\nProof.\ninduction l ; intros.\n- inversion H1.\n- destruct a. destruct m.\n  1-4: subst ; apply In_InT_pair in H1 ; inversion H1 ; subst ; inversion H2 ; subst ; apply InT_In in H2 ;\n    assert (J1: length (Γ0 ++ # P :: Γ1) = length (Γ0 ++ # P :: Γ1)) ; try reflexivity ; pose (IHl _ H J1 H2) ; simpl ; destruct n0 ; assumption ; assumption.\n  2: subst ; apply In_InT_pair in H1 ; inversion H1 ; subst ; inversion H2 ; subst ; apply InT_In in H2 ;\n    assert (J1: length (Γ0 ++ # P :: Γ1) = length (Γ0 ++ # P :: Γ1)) ; try reflexivity ; pose (IHl _ H J1 H2) ; simpl ; destruct n0 ; assumption ; assumption.\n  destruct m1.\n  2-6: subst ; apply In_InT_pair in H1 ; inversion H1 ; subst ; inversion H2 ; subst ; apply InT_In in H2 ;\n    assert (J1: length (Γ0 ++ # P :: Γ1) = length (Γ0 ++ # P :: Γ1)) ; try reflexivity ; pose (IHl _ H J1 H2) ; simpl ; destruct n0 ; assumption ; assumption.\n  apply In_InT_pair in H1. inversion H1.\n    + subst. inversion H3. subst. apply AtomImpL1_help002.\n    + subst. assert (J1: (length (Γ0 ++ # P :: Γ1)) = (length (Γ0 ++ # P :: Γ1))). reflexivity. apply InT_In in H3.\n       pose (IHl (length (Γ0 ++ # P :: Γ1)) H J1 H3). simpl. destruct n0 ; auto. apply InT_cons. auto.\nQed.\n\nLemma AtomImpL1_help2 : forall prem s, AtomImpL1Rule [prem] s -> InT prem (prems_AtomImp_L1 (pos_top_atomimps_L1 (fst s)) s).\nProof.\nintros. inversion H. subst. simpl.\npose (@AtomImpL1_help02 Γ0 Γ1 Γ2 A P C (pos_top_atomimps_L1 (Γ0 ++ # P :: Γ1 ++ # P → A :: Γ2)) (length (Γ0 ++ # P :: Γ1))).\napply i ; try assumption ; auto. apply Good_pos_in_pos_top_atom_atomimps_L1.\nQed.\n\nLemma finite_AtomImpL1_premises_of_S : forall (s : (list (MPropF V)) * (MPropF V)), existsT2 listAtomImpL1prems,\n              (forall prems, ((AtomImpL1Rule prems s) -> (InT prems listAtomImpL1prems)) *\n                             ((InT prems listAtomImpL1prems) -> (AtomImpL1Rule prems s))).\nProof.\nintros. destruct s.\nexists (map (fun y => [y]) (prems_AtomImp_L1 (pos_top_atomimps_L1 l) (l,m))).\nintros. split ; intro.\n- inversion H. subst.\n  pose (AtomImpL1_help2 H). apply InT_map_iff. exists (Γ0 ++ # P :: Γ1 ++ A :: Γ2, m) ; split ; auto.\n- apply InT_map_iff in H. destruct H. destruct p. subst. apply AtomImpL1_help1. simpl. assumption.\nQed.\n\n\n\n\n(*------------------------------------------------------------------------------------------------------------------------------------------------------------------- *)\n\n\n\n\n\n(* AtomImpL2 rule. *)\n\nDefinition pos_atomimps_is_right_atoms (l : list (MPropF V)) :=\n          filter (fun (x : ((MPropF V * nat) * (MPropF V * nat))) => andb (ltb (snd (snd x)) (snd (fst x))) (pair_atom_same_antec x))\n          (concat (all_pos_top_atoms_atomimps l)).\n\nDefinition pos_top_atomimps_L2 l := map (fun x => snd x) (pos_atomimps_is_right_atoms l).\n\nFixpoint prems_AtomImp_L2 (l : list ((MPropF V) * nat)) (s : (list (MPropF V)) * (MPropF V)) : list ((list (MPropF V)) * (MPropF V)) :=\nmatch l with\n  | nil => nil\n  | (C, n) :: t => match n with\n      | 0 => prems_AtomImp_L2 t s\n      | S m => match C with\n           | Imp A B => match A with\n                               | # P => ((fst (nth_split m (remove_nth (S m) C (fst s)))) ++ B :: (snd (nth_split m (remove_nth (S m) C (fst s)))), snd s)\n                                             :: (prems_AtomImp_L2 t s)\n                               | _ => prems_AtomImp_L2 t s\n                               end\n           | _ => prems_AtomImp_L2 t s\n           end\n      end\nend.\n\nLemma In_pos_top_atomimps_L2_0_False : forall l (A : MPropF V), In (A, 0) (pos_top_atomimps_L2 l) -> False.\nProof.\n- induction l.\n  * intros. inversion H.\n  * intros. simpl in H. destruct a.\n    1-4: simpl in H ;  apply In_InT_pair in H ; apply InT_map_iff in H ; destruct H ;\n    destruct p ; destruct x ; simpl in e ; subst ; unfold pos_atomimps_is_left_atoms in i ;\n    apply InT_In in i ; apply filter_In in i ; destruct i ; simpl in H0 ; apply in_concat in H ;\n    destruct H ; destruct H ; unfold all_pos_top_atoms_atomimps in H ;\n    apply in_map_iff in H ; destruct H ; destruct H ; subst ;\n    apply in_map_iff in H1 ; destruct H1 ; destruct H ; inversion H ; subst ; clear H ;\n    apply in_map_iff in H1 ; destruct H1 ; destruct H ; destruct x ; simpl in H ; inversion H.\n    2: simpl in H ;  apply In_InT_pair in H ; apply InT_map_iff in H ; destruct H ;\n    destruct p ; destruct x ; simpl in e ; subst ; unfold pos_atomimps_is_left_atoms in i ;\n    apply InT_In in i ; apply filter_In in i ; destruct i ; simpl in H0 ; apply in_concat in H ;\n    destruct H ; destruct H ; unfold all_pos_top_atoms_atomimps in H ;\n    apply in_map_iff in H ; destruct H ; destruct H ; subst ;\n    apply in_map_iff in H1 ; destruct H1 ; destruct H ; inversion H ; subst ; clear H ;\n    apply in_map_iff in H1 ; destruct H1 ; destruct H ; destruct x ; simpl in H ; inversion H.\n    destruct a1.\n    2-6: simpl in H ;  apply In_InT_pair in H ; apply InT_map_iff in H ; destruct H ;\n    destruct p ; destruct x ; simpl in e ; subst ; unfold pos_atomimps_is_left_atoms in i ;\n    apply InT_In in i ; apply filter_In in i ; destruct i ; simpl in H0 ; apply in_concat in H ;\n    destruct H ; destruct H ; unfold all_pos_top_atoms_atomimps in H ;\n    apply in_map_iff in H ; destruct H ; destruct H ; subst ;\n    apply in_map_iff in H1 ; destruct H1 ; destruct H ; inversion H ; subst ; clear H ;\n    apply in_map_iff in H1 ; destruct H1 ; destruct H ; destruct x ; simpl in H ; inversion H.\n    apply In_InT_pair in H ; apply InT_map_iff in H. destruct H. destruct x. destruct p0.\n    destruct p1. simpl in p. destruct p. inversion e. subst. unfold pos_atomimps_is_left_atoms in i.\n     apply InT_In in i ; apply filter_In in i ; destruct i. simpl in H0. apply in_concat in H ;\n    destruct H ; destruct H ; unfold all_pos_top_atoms_atomimps in H ;\n    apply in_map_iff in H ; destruct H. destruct H. subst. destruct x0.\n    apply in_map_iff in H1. destruct H1. destruct H. inversion H. subst. inversion H1.\n    inversion H3. apply in_map_iff in H3. destruct H3. destruct H3. inversion H3.\nQed.\n\nLemma In_pos_top_atoms_split_l :forall l (A : MPropF V) n, In (A, S n) (pos_top_atoms l) ->\n          existsT2 l0 l1, (l = l0 ++ A :: l1) *\n                          (length l0 = n) *\n                          (l0 = fst (nth_split n (remove_nth (S n) A l))) *\n                          (l1 = snd (nth_split n (remove_nth (S n) A l))).\nProof.\ninduction l.\n- intros. simpl. exfalso. simpl in H. destruct H.\n- intros. simpl in H. destruct a.\n  * apply In_InT_pair in H. inversion H.\n    + inversion H1 ; subst. exists []. exists l. repeat split ; auto. simpl.\n       destruct (eq_dec_form (# v) (# v)) ; auto. exfalso. apply n ; auto.\n    + subst. apply InT_map_iff in H1. destruct H1. destruct p.\n      destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n      apply InT_In in i. apply In_pos_top_atoms_0_False in i. assumption.\n      apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n      subst. exists (# v :: x). exists x0. repeat split.\n      rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n      assert (fst (# v :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      # v :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n      assert (S (S (length x)) = S (length (# v :: x))). simpl. reflexivity.\n      rewrite H1. assert ((# v :: x ++ A :: x0) = ((# v :: x) ++ A :: x0)). simpl. reflexivity.\n      rewrite H2. clear H2. clear H1. rewrite effective_remove_nth.\n      pose (nth_split_idL (# v :: x) x0). simpl (length (# v :: x)) in e2.\n      rewrite <- e2. reflexivity.\n      rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n      assert (S (S (length x)) = S (length (# v:: x))). simpl. reflexivity.\n      rewrite H0. assert ((# v :: x ++ A :: x0) = ((# v :: x) ++ A :: x0)). simpl. reflexivity.\n      rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n      pose (nth_split_idR (# v :: x) x0). simpl (length (# v :: x)) in e2.\n      rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_atoms_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (⊥ V :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (⊥ V :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      ⊥ V :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (⊥ V :: x))). simpl. reflexivity.\n    rewrite H0. assert ((⊥ V :: x ++ A :: x0) = ((⊥ V :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (⊥ V :: x) x0). simpl (length (⊥ V :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (⊥ V :: x))). simpl. reflexivity.\n    rewrite H. assert ((⊥ V :: x ++ A :: x0) = ((⊥ V :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (⊥ V :: x) x0). simpl (length (⊥ V :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_atoms_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (a1 ∧ a2 :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (a1 ∧ a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      a1 ∧ a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (a1 ∧ a2 :: x))). simpl. reflexivity.\n    rewrite H0. assert ((a1 ∧ a2 :: x ++ A :: x0) = ((a1 ∧ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (a1 ∧ a2 :: x) x0). simpl (length (a1 ∧ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (a1 ∧ a2 :: x))). simpl. reflexivity.\n    rewrite H. assert ((a1 ∧ a2 :: x ++ A :: x0) = ((a1 ∧ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (a1 ∧ a2 :: x) x0). simpl (length (a1 ∧ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_atoms_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (a1 ∨ a2 :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (a1 ∨ a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      a1 ∨ a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (a1 ∨ a2 :: x))). simpl. reflexivity.\n    rewrite H0. assert ((a1 ∨ a2 :: x ++ A :: x0) = ((a1 ∨ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (a1 ∨ a2 :: x) x0). simpl (length (a1 ∨ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (a1 ∨ a2 :: x))). simpl. reflexivity.\n    rewrite H. assert ((a1 ∨ a2 :: x ++ A :: x0) = ((a1 ∨ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (a1 ∨ a2 :: x) x0). simpl (length (a1 ∨ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_atoms_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (a1 → a2 :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (a1 → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      a1 → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (a1 → a2 :: x))). simpl. reflexivity.\n    rewrite H0. assert ((a1 → a2 :: x ++ A :: x0) = ((a1 → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (a1 → a2 :: x) x0). simpl (length (a1 → a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (a1 → a2 :: x))). simpl. reflexivity.\n    rewrite H. assert ((a1 → a2 :: x ++ A :: x0) = ((a1 → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (a1 → a2 :: x) x0). simpl (length (a1 → a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_atoms_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (Box a :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (Box a :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n    Box a :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (Box a :: x))). simpl. reflexivity.\n    rewrite H0. assert ((Box a :: x ++ A :: x0) = ((Box a :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (Box a :: x) x0). simpl (length (Box a :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (Box a :: x))). simpl. reflexivity.\n    rewrite H. assert ((Box a :: x ++ A :: x0) = ((Box a :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (Box a :: x) x0). simpl (length (Box a :: x)) in e2.\n    rewrite <- e2. reflexivity.\nQed.\n\nLemma In_pos_top_atomimps_L2_split_l : forall l (A : MPropF V) n, In (A, S n) (pos_top_atomimps_L2 l) ->\n          existsT2 l0 l1 l2 P, (l = l0 ++ A :: l1 ++ # P :: l2) *\n                          (length l0 = n) *\n                          ( l0 = fst (nth_split n (remove_nth (S n) A l))) *\n                          (l1 ++ # P :: l2 = snd (nth_split n (remove_nth (S n) A l))).\nProof.\ninduction l.\n- intros. simpl. exfalso. simpl in H. destruct H.\n- intros. simpl in H. unfold pos_top_atomimps_L2 in H. apply In_InT_pair in H.\n  apply InT_map_iff in H. destruct H. destruct p. destruct x. destruct p. destruct p0. simpl in e.\n  inversion e. subst. unfold pos_atomimps_is_left_atoms in i. apply filter_InT in i. clear e.\n  destruct i. simpl in e. assert (S n <? n0 = true). apply andb_prop in e. destruct e.\n  auto. apply Nat.ltb_lt in H. apply InT_concat in i. destruct i. destruct p.\n  unfold all_pos_top_atoms_atomimps in i. apply InT_map_iff in i. destruct i.\n  destruct x0. destruct p. subst. apply InT_map_iff in i0. destruct i0.\n  destruct x. destruct p. inversion e0. subst. destruct a.\n  { simpl in i0. apply InT_map_iff in i0. destruct i0. destruct p. destruct x. simpl in e1.\n     inversion e1. subst. inversion i.\n     - inversion H1. subst. exfalso. lia.\n     - subst. apply InT_map_iff in H1. destruct H1. destruct p. destruct x. simpl in e2. inversion e2. subst.\n       destruct n. exfalso. apply InT_In in i0. apply In_pos_top_atomimps_0_False in i0. auto.\n       assert (In (A, S n) (pos_top_atomimps_L2 l)).\n       { unfold pos_top_atomimps_L2. apply in_map_iff. exists (m, n1, (A, S n)). simpl ; split ; auto.\n         unfold pos_atomimps_is_right_atoms. apply filter_In. split. 2: simpl.\n         2: apply andb_true_intro ; split ; auto. 2: apply Nat.ltb_lt ; lia. apply in_concat.\n         exists (map (fun y : MPropF V * nat => ((m, n1), y)) (pos_top_atomimps l)). split ; auto.\n         apply in_map_iff. exists (m, n1). split ; auto. apply InT_In ; auto. apply in_map_iff. exists (A, S n).\n         split ; auto. apply InT_In ; auto. unfold pair_atom_same_antec. simpl.\n         apply andb_prop in e. destruct e. unfold pair_atom_same_antec in H1. simpl in H1.\n         destruct m. 2-6: exfalso ; inversion H1. destruct A. 1-4: inversion H1. 2: inversion H1.\n         destruct A1. 2-6: inversion H1. auto. }\n       apply IHl in H0. destruct H0. repeat destruct s. repeat destruct p. subst.\n       exists (# v :: x). exists x0. exists x1. exists x2. repeat split ; auto.\n       assert (length (# v :: x) = S (length x)).\n       simpl. auto. rewrite <- H0.\n       assert (# v :: x ++ A :: x0 ++ # x2 :: x1 = (# v :: x) ++ A :: x0 ++ # x2 :: x1).\n       simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n       rewrite effective_remove_nth. rewrite <- nth_split_idL. auto.\n       assert (length (# v :: x) = S (length x)).\n       simpl. auto. rewrite <- H0.\n       assert (# v :: x ++ A :: x0 ++ # x2 :: x1 = (# v :: x) ++ A :: x0 ++ # x2 :: x1).\n       simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n       rewrite effective_remove_nth. rewrite <- nth_split_idR. auto. }\n  { simpl in i0. apply InT_map_iff in i0. destruct i0. destruct p. destruct x. simpl in e1.\n     inversion e1. subst. simpl in i. apply InT_map_iff in i. destruct i. destruct x. simpl in p.\n     destruct p. inversion e2. subst. clear e0. clear e2. clear e1.\n     assert (In (A, n) (pos_top_atomimps_L2 l)).\n     { unfold pos_top_atomimps_L2. apply in_map_iff. exists (m, n1, (A, n)). simpl ; split ; auto.\n       unfold pos_atomimps_is_left_atoms. apply filter_In. split. 2: simpl.\n       2: apply andb_true_intro ; split ; auto. 2: apply Nat.ltb_lt ; lia. apply in_concat.\n       exists (map (fun y : MPropF V * nat => ((m, n1), y)) (pos_top_atomimps l)). split ; auto.\n       apply in_map_iff. exists (m, n1). split ; auto. apply InT_In ; auto. apply in_map_iff. exists (A, n).\n       split ; auto. apply InT_In ; auto. unfold pair_atom_same_antec. simpl.\n       apply andb_prop in e. destruct e. unfold pair_atom_same_antec in H1. simpl in H1.\n       destruct m. 2-6: exfalso ; inversion H1. destruct A. 1-4: inversion H1. 2: inversion H1.\n       destruct A1. 2-6: inversion H1. auto. }\n     destruct n. exfalso. apply In_pos_top_atomimps_L2_0_False in H0. auto.\n     apply IHl in H0. destruct H0. repeat destruct s. repeat destruct p. subst.\n     exists (⊥ V :: x). exists x0. exists x1. exists x2. repeat split ; auto.\n     assert (length (⊥ V :: x) = S (length x)).\n     simpl. auto. rewrite <- H0.\n     assert (⊥ V :: x ++ A :: x0 ++ # x2 :: x1 = (⊥ V :: x) ++ A :: x0 ++ # x2 :: x1).\n     simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n     rewrite effective_remove_nth. rewrite <- nth_split_idL. auto.\n     assert (length (⊥ V :: x) = S (length x)).\n     simpl. auto. rewrite <- H0.\n     assert (⊥ V :: x ++ A :: x0 ++ # x2 :: x1 = (⊥ V :: x) ++ A :: x0 ++ # x2 :: x1).\n     simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n     rewrite effective_remove_nth. rewrite <- nth_split_idR. auto. }\n  { simpl in i0. apply InT_map_iff in i0. destruct i0. destruct p. destruct x. simpl in e1.\n     inversion e1. subst. simpl in i. apply InT_map_iff in i. destruct i. destruct x. simpl in p.\n     destruct p. inversion e2. subst. clear e0. clear e2. clear e1.\n     assert (In (A, n) (pos_top_atomimps_L2 l)).\n     { unfold pos_top_atomimps_L2. apply in_map_iff. exists (m, n1, (A, n)). simpl ; split ; auto.\n       unfold pos_atomimps_is_left_atoms. apply filter_In. split. 2: simpl.\n       2: apply andb_true_intro ; split ; auto. 2: apply Nat.ltb_lt ; lia. apply in_concat.\n       exists (map (fun y : MPropF V * nat => ((m, n1), y)) (pos_top_atomimps l)). split ; auto.\n       apply in_map_iff. exists (m, n1). split ; auto. apply InT_In ; auto. apply in_map_iff. exists (A, n).\n       split ; auto. apply InT_In ; auto. unfold pair_atom_same_antec. simpl.\n       apply andb_prop in e. destruct e. unfold pair_atom_same_antec in H1. simpl in H1.\n       destruct m. 2-6: exfalso ; inversion H1. destruct A. 1-4: inversion H1. 2: inversion H1.\n       destruct A1. 2-6: inversion H1. auto. }\n     destruct n. exfalso. apply In_pos_top_atomimps_L2_0_False in H0. auto.\n     apply IHl in H0. destruct H0. repeat destruct s. repeat destruct p. subst.\n     exists (a1 ∧ a2 :: x). exists x0. exists x1. exists x2. repeat split ; auto.\n     assert (length (a1 ∧ a2 :: x) = S (length x)).\n     simpl. auto. rewrite <- H0.\n     assert (a1 ∧ a2 :: x ++ A :: x0 ++ # x2 :: x1 = (a1 ∧ a2 :: x) ++ A :: x0 ++ # x2 :: x1).\n     simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n     rewrite effective_remove_nth. rewrite <- nth_split_idL. auto.\n     assert (length (a1 ∧ a2 :: x) = S (length x)).\n     simpl. auto. rewrite <- H0.\n     assert (a1 ∧ a2 :: x ++ A :: x0 ++ # x2 :: x1 = (a1 ∧ a2 :: x) ++ A :: x0 ++ # x2 :: x1).\n     simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n     rewrite effective_remove_nth. rewrite <- nth_split_idR. auto. }\n  { simpl in i0. apply InT_map_iff in i0. destruct i0. destruct p. destruct x. simpl in e1.\n     inversion e1. subst. simpl in i. apply InT_map_iff in i. destruct i. destruct x. simpl in p.\n     destruct p. inversion e2. subst. clear e0. clear e2. clear e1.\n     assert (In (A, n) (pos_top_atomimps_L2 l)).\n     { unfold pos_top_atomimps_L2. apply in_map_iff. exists (m, n1, (A, n)). simpl ; split ; auto.\n       unfold pos_atomimps_is_left_atoms. apply filter_In. split. 2: simpl.\n       2: apply andb_true_intro ; split ; auto. 2: apply Nat.ltb_lt ; lia. apply in_concat.\n       exists (map (fun y : MPropF V * nat => ((m, n1), y)) (pos_top_atomimps l)). split ; auto.\n       apply in_map_iff. exists (m, n1). split ; auto. apply InT_In ; auto. apply in_map_iff. exists (A, n).\n       split ; auto. apply InT_In ; auto. unfold pair_atom_same_antec. simpl.\n       apply andb_prop in e. destruct e. unfold pair_atom_same_antec in H1. simpl in H1.\n       destruct m. 2-6: exfalso ; inversion H1. destruct A. 1-4: inversion H1. 2: inversion H1.\n       destruct A1. 2-6: inversion H1. auto. }\n     destruct n. exfalso. apply In_pos_top_atomimps_L2_0_False in H0. auto.\n     apply IHl in H0. destruct H0. repeat destruct s. repeat destruct p. subst.\n     exists (a1 ∨ a2 :: x). exists x0. exists x1. exists x2. repeat split ; auto.\n     assert (length (a1 ∨ a2 :: x) = S (length x)).\n     simpl. auto. rewrite <- H0.\n     assert (a1 ∨ a2 :: x ++ A :: x0 ++ # x2 :: x1 = (a1 ∨ a2 :: x) ++ A :: x0 ++ # x2 :: x1).\n     simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n     rewrite effective_remove_nth. rewrite <- nth_split_idL. auto.\n     assert (length (a1 ∨ a2 :: x) = S (length x)).\n     simpl. auto. rewrite <- H0.\n     assert (a1 ∨ a2 :: x ++ A :: x0 ++ # x2 :: x1 = (a1 ∨ a2 :: x) ++ A :: x0 ++ # x2 :: x1).\n     simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n     rewrite effective_remove_nth. rewrite <- nth_split_idR. auto. }\n  { simpl in i0. destruct a1.\n     { inversion i0. inversion H1.\n        - subst. exists []. simpl in i. apply InT_map_iff in i. destruct i. destruct x.\n          simpl in p. destruct p. inversion e1 ; subst. destruct n. exfalso. apply InT_In in i. apply In_pos_top_atoms_0_False in i.\n          auto. apply InT_In in i. apply In_pos_top_atoms_split_l in i. destruct i. repeat destruct s.\n          repeat destruct p. subst. exists x. exists x0.\n          assert (m = # v). apply andb_prop in e. destruct e. unfold pair_atom_same_antec in H2. simpl in H2.\n          destruct m. 2-6: exfalso ; inversion H2. apply eqb_prop_eq in H2. subst. auto. subst.\n          exists v. repeat split ; auto. simpl. destruct (eq_dec_form (# v → a2) (# v → a2)).\n          auto. exfalso. apply n. auto.\n        - subst. simpl in i. simpl in i. apply InT_map_iff in i. destruct i. destruct x. simpl in p. destruct p.\n           inversion e1 ; subst.  apply InT_map_iff in H1. destruct H1. destruct p. destruct x. simpl in e2.\n           inversion e2. subst.\n            assert (In (A, n) (pos_top_atomimps_L2 l)).\n             { unfold pos_top_atomimps_L2. apply in_map_iff. exists (m, n1, (A, n)). simpl ; split ; auto.\n               unfold pos_atomimps_is_left_atoms. apply filter_In. split. 2: simpl.\n               2: apply andb_true_intro ; split ; auto. 2: apply Nat.ltb_lt ; lia. apply in_concat.\n               exists (map (fun y : MPropF V * nat => ((m, n1), y)) (pos_top_atomimps l)). split ; auto.\n               apply in_map_iff. exists (m, n1). split ; auto. apply InT_In ; auto. apply in_map_iff. exists (A, n).\n               split ; auto. apply InT_In ; auto. unfold pair_atom_same_antec. simpl.\n               apply andb_prop in e. destruct e. unfold pair_atom_same_antec in H1. simpl in H1.\n               destruct m. 2-6: exfalso ; inversion H1. destruct A. 1-4: inversion H1. 2: inversion H1.\n               destruct A1. 2-6: inversion H1. auto. }\n             destruct n. exfalso. apply In_pos_top_atomimps_L2_0_False in H0. auto.\n             apply IHl in H0. destruct H0. repeat destruct s. repeat destruct p. subst.\n             exists (# v → a2 :: x). exists x0. exists x1. exists x2. repeat split ; auto.\n             assert (length (# v → a2 :: x) = S (length x)).\n             simpl. auto. rewrite <- H0.\n             assert (# v → a2 :: x ++ A :: x0 ++ # x2 :: x1 = (# v → a2 :: x) ++ A :: x0 ++ # x2 :: x1).\n             simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n             rewrite effective_remove_nth. rewrite <- nth_split_idL. auto.\n             assert (length (# v → a2 :: x) = S (length x)).\n             simpl. auto. rewrite <- H0.\n             assert (# v → a2 :: x ++ A :: x0 ++ # x2 :: x1 = (# v → a2 :: x) ++ A :: x0 ++ # x2 :: x1).\n             simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n             rewrite effective_remove_nth. rewrite <- nth_split_idR. auto. }\n     { subst. simpl in i. simpl in i. apply InT_map_iff in i. destruct i. destruct x. simpl in p. destruct p.\n       inversion e1 ; subst. apply InT_map_iff in i0. destruct i0. destruct p. destruct x. simpl in e2.\n       inversion e2. subst.\n        assert (In (A, n) (pos_top_atomimps_L2 l)).\n         { unfold pos_top_atomimps_L2. apply in_map_iff. exists (m, n1, (A, n)). simpl ; split ; auto.\n           unfold pos_atomimps_is_left_atoms. apply filter_In. split. 2: simpl.\n           2: apply andb_true_intro ; split ; auto. 2: apply Nat.ltb_lt ; lia. apply in_concat.\n           exists (map (fun y : MPropF V * nat => ((m, n1), y)) (pos_top_atomimps l)). split ; auto.\n           apply in_map_iff. exists (m, n1). split ; auto. apply InT_In ; auto. apply in_map_iff. exists (A, n).\n           split ; auto. apply InT_In ; auto. unfold pair_atom_same_antec. simpl.\n           apply andb_prop in e. destruct e. unfold pair_atom_same_antec in H1. simpl in H1.\n           destruct m. 2-6: exfalso ; inversion H1. destruct A. 1-4: inversion H1. 2: inversion H1.\n           destruct A1. 2-6: inversion H1. auto. }\n         destruct n. exfalso. apply In_pos_top_atomimps_L2_0_False in H0. auto.\n         apply IHl in H0. destruct H0. repeat destruct s. repeat destruct p. subst.\n         exists (⊥ V → a2 :: x). exists x0. exists x1. exists x2. repeat split ; auto.\n         assert (length (⊥ V → a2 :: x) = S (length x)).\n         simpl. auto. rewrite <- H0.\n         assert (⊥ V → a2 :: x ++ A :: x0 ++ # x2 :: x1 = (⊥ V → a2 :: x) ++ A :: x0 ++ # x2 :: x1).\n         simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n         rewrite effective_remove_nth. rewrite <- nth_split_idL. auto.\n         assert (length (⊥ V → a2 :: x) = S (length x)).\n         simpl. auto. rewrite <- H0.\n         assert (⊥ V → a2 :: x ++ A :: x0 ++ # x2 :: x1 = (⊥ V → a2 :: x) ++ A :: x0 ++ # x2 :: x1).\n         simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n         rewrite effective_remove_nth. rewrite <- nth_split_idR. auto. }\n     { subst. simpl in i. simpl in i. apply InT_map_iff in i. destruct i. destruct x. simpl in p. destruct p.\n       inversion e1 ; subst. apply InT_map_iff in i0. destruct i0. destruct p. destruct x. simpl in e2.\n       inversion e2. subst.\n        assert (In (A, n) (pos_top_atomimps_L2 l)).\n         { unfold pos_top_atomimps_L2. apply in_map_iff. exists (m, n1, (A, n)). simpl ; split ; auto.\n           unfold pos_atomimps_is_left_atoms. apply filter_In. split. 2: simpl.\n           2: apply andb_true_intro ; split ; auto. 2: apply Nat.ltb_lt ; lia. apply in_concat.\n           exists (map (fun y : MPropF V * nat => ((m, n1), y)) (pos_top_atomimps l)). split ; auto.\n           apply in_map_iff. exists (m, n1). split ; auto. apply InT_In ; auto. apply in_map_iff. exists (A, n).\n           split ; auto. apply InT_In ; auto. unfold pair_atom_same_antec. simpl.\n           apply andb_prop in e. destruct e. unfold pair_atom_same_antec in H1. simpl in H1.\n           destruct m. 2-6: exfalso ; inversion H1. destruct A. 1-4: inversion H1. 2: inversion H1.\n           destruct A1. 2-6: inversion H1. auto. }\n         destruct n. exfalso. apply In_pos_top_atomimps_L2_0_False in H0. auto.\n         apply IHl in H0. destruct H0. repeat destruct s. repeat destruct p. subst.\n         exists ((a1_1 ∧ a1_2) → a2 :: x). exists x0. exists x1. exists x2. repeat split ; auto.\n         assert (length ((a1_1 ∧ a1_2) → a2 :: x) = S (length x)).\n         simpl. auto. rewrite <- H0.\n         assert ((a1_1 ∧ a1_2) → a2 :: x ++ A :: x0 ++ # x2 :: x1 = ((a1_1 ∧ a1_2) → a2 :: x) ++ A :: x0 ++ # x2 :: x1).\n         simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n         rewrite effective_remove_nth. rewrite <- nth_split_idL. auto.\n         assert (length ((a1_1 ∧ a1_2) → a2 :: x) = S (length x)).\n         simpl. auto. rewrite <- H0.\n         assert ((a1_1 ∧ a1_2) → a2 :: x ++ A :: x0 ++ # x2 :: x1 = ((a1_1 ∧ a1_2) → a2 :: x) ++ A :: x0 ++ # x2 :: x1).\n         simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n         rewrite effective_remove_nth. rewrite <- nth_split_idR. auto. }\n     { subst. simpl in i. simpl in i. apply InT_map_iff in i. destruct i. destruct x. simpl in p. destruct p.\n       inversion e1 ; subst. apply InT_map_iff in i0. destruct i0. destruct p. destruct x. simpl in e2.\n       inversion e2. subst.\n        assert (In (A, n) (pos_top_atomimps_L2 l)).\n         { unfold pos_top_atomimps_L2. apply in_map_iff. exists (m, n1, (A, n)). simpl ; split ; auto.\n           unfold pos_atomimps_is_left_atoms. apply filter_In. split. 2: simpl.\n           2: apply andb_true_intro ; split ; auto. 2: apply Nat.ltb_lt ; lia. apply in_concat.\n           exists (map (fun y : MPropF V * nat => ((m, n1), y)) (pos_top_atomimps l)). split ; auto.\n           apply in_map_iff. exists (m, n1). split ; auto. apply InT_In ; auto. apply in_map_iff. exists (A, n).\n           split ; auto. apply InT_In ; auto. unfold pair_atom_same_antec. simpl.\n           apply andb_prop in e. destruct e. unfold pair_atom_same_antec in H1. simpl in H1.\n           destruct m. 2-6: exfalso ; inversion H1. destruct A. 1-4: inversion H1. 2: inversion H1.\n           destruct A1. 2-6: inversion H1. auto. }\n         destruct n. exfalso. apply In_pos_top_atomimps_L2_0_False in H0. auto.\n         apply IHl in H0. destruct H0. repeat destruct s. repeat destruct p. subst.\n         exists ((a1_1 ∨ a1_2) → a2 :: x). exists x0. exists x1. exists x2. repeat split ; auto.\n         assert (length ((a1_1 ∨ a1_2) → a2 :: x) = S (length x)).\n         simpl. auto. rewrite <- H0.\n         assert ((a1_1 ∨ a1_2) → a2 :: x ++ A :: x0 ++ # x2 :: x1 = ((a1_1 ∨ a1_2) → a2 :: x) ++ A :: x0 ++ # x2 :: x1).\n         simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n         rewrite effective_remove_nth. rewrite <- nth_split_idL. auto.\n         assert (length ((a1_1 ∨ a1_2) → a2 :: x) = S (length x)).\n         simpl. auto. rewrite <- H0.\n         assert ((a1_1 ∨ a1_2) → a2 :: x ++ A :: x0 ++ # x2 :: x1 = ((a1_1 ∨ a1_2) → a2 :: x) ++ A :: x0 ++ # x2 :: x1).\n         simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n         rewrite effective_remove_nth. rewrite <- nth_split_idR. auto. }\n     { subst. simpl in i. simpl in i. apply InT_map_iff in i. destruct i. destruct x. simpl in p. destruct p.\n       inversion e1 ; subst. apply InT_map_iff in i0. destruct i0. destruct p. destruct x. simpl in e2.\n       inversion e2. subst.\n        assert (In (A, n) (pos_top_atomimps_L2 l)).\n         { unfold pos_top_atomimps_L2. apply in_map_iff. exists (m, n1, (A, n)). simpl ; split ; auto.\n           unfold pos_atomimps_is_left_atoms. apply filter_In. split. 2: simpl.\n           2: apply andb_true_intro ; split ; auto. 2: apply Nat.ltb_lt ; lia. apply in_concat.\n           exists (map (fun y : MPropF V * nat => ((m, n1), y)) (pos_top_atomimps l)). split ; auto.\n           apply in_map_iff. exists (m, n1). split ; auto. apply InT_In ; auto. apply in_map_iff. exists (A, n).\n           split ; auto. apply InT_In ; auto. unfold pair_atom_same_antec. simpl.\n           apply andb_prop in e. destruct e. unfold pair_atom_same_antec in H1. simpl in H1.\n           destruct m. 2-6: exfalso ; inversion H1. destruct A. 1-4: inversion H1. 2: inversion H1.\n           destruct A1. 2-6: inversion H1. auto. }\n         destruct n. exfalso. apply In_pos_top_atomimps_L2_0_False in H0. auto.\n         apply IHl in H0. destruct H0. repeat destruct s. repeat destruct p. subst.\n         exists ((a1_1 → a1_2) → a2 :: x). exists x0. exists x1. exists x2. repeat split ; auto.\n         assert (length ((a1_1 → a1_2) → a2 :: x) = S (length x)).\n         simpl. auto. rewrite <- H0.\n         assert ((a1_1 → a1_2) → a2 :: x ++ A :: x0 ++ # x2 :: x1 = ((a1_1 → a1_2) → a2 :: x) ++ A :: x0 ++ # x2 :: x1).\n         simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n         rewrite effective_remove_nth. rewrite <- nth_split_idL. auto.\n         assert (length ((a1_1 → a1_2) → a2 :: x) = S (length x)).\n         simpl. auto. rewrite <- H0.\n         assert ((a1_1 → a1_2) → a2 :: x ++ A :: x0 ++ # x2 :: x1 = ((a1_1 → a1_2) → a2 :: x) ++ A :: x0 ++ # x2 :: x1).\n         simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n         rewrite effective_remove_nth. rewrite <- nth_split_idR. auto. }\n     { subst. simpl in i. simpl in i. apply InT_map_iff in i. destruct i. destruct x. simpl in p. destruct p.\n       inversion e1 ; subst. apply InT_map_iff in i0. destruct i0. destruct p. destruct x. simpl in e2.\n       inversion e2. subst.\n        assert (In (A, n) (pos_top_atomimps_L2 l)).\n         { unfold pos_top_atomimps_L2. apply in_map_iff. exists (m, n1, (A, n)). simpl ; split ; auto.\n           unfold pos_atomimps_is_left_atoms. apply filter_In. split. 2: simpl.\n           2: apply andb_true_intro ; split ; auto. 2: apply Nat.ltb_lt ; lia. apply in_concat.\n           exists (map (fun y : MPropF V * nat => ((m, n1), y)) (pos_top_atomimps l)). split ; auto.\n           apply in_map_iff. exists (m, n1). split ; auto. apply InT_In ; auto. apply in_map_iff. exists (A, n).\n           split ; auto. apply InT_In ; auto. unfold pair_atom_same_antec. simpl.\n           apply andb_prop in e. destruct e. unfold pair_atom_same_antec in H1. simpl in H1.\n           destruct m. 2-6: exfalso ; inversion H1. destruct A. 1-4: inversion H1. 2: inversion H1.\n           destruct A1. 2-6: inversion H1. auto. }\n         destruct n. exfalso. apply In_pos_top_atomimps_L2_0_False in H0. auto.\n         apply IHl in H0. destruct H0. repeat destruct s. repeat destruct p. subst.\n         exists ((Box a1) → a2 :: x). exists x0. exists x1. exists x2. repeat split ; auto.\n         assert (length ((Box a1) → a2 :: x) = S (length x)).\n         simpl. auto. rewrite <- H0.\n         assert ((Box a1) → a2 :: x ++ A :: x0 ++ # x2 :: x1 = ((Box a1) → a2 :: x) ++ A :: x0 ++ # x2 :: x1).\n         simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n         rewrite effective_remove_nth. rewrite <- nth_split_idL. auto.\n         assert (length ((Box a1) → a2 :: x) = S (length x)).\n         simpl. auto. rewrite <- H0.\n         assert ((Box a1) → a2 :: x ++ A :: x0 ++ # x2 :: x1 = ((Box a1) → a2 :: x) ++ A :: x0 ++ # x2 :: x1).\n         simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n         rewrite effective_remove_nth. rewrite <- nth_split_idR. auto. } }\n  { simpl in i0. apply InT_map_iff in i0. destruct i0. destruct p. destruct x. simpl in e1.\n     inversion e1. subst. simpl in i. apply InT_map_iff in i. destruct i. destruct x. simpl in p.\n     destruct p. inversion e2. subst. clear e0. clear e2. clear e1.\n     assert (In (A, n) (pos_top_atomimps_L2 l)).\n     { unfold pos_top_atomimps_L2. apply in_map_iff. exists (m, n1, (A, n)). simpl ; split ; auto.\n       unfold pos_atomimps_is_left_atoms. apply filter_In. split. 2: simpl.\n       2: apply andb_true_intro ; split ; auto. 2: apply Nat.ltb_lt ; lia. apply in_concat.\n       exists (map (fun y : MPropF V * nat => ((m, n1), y)) (pos_top_atomimps l)). split ; auto.\n       apply in_map_iff. exists (m, n1). split ; auto. apply InT_In ; auto. apply in_map_iff. exists (A, n).\n       split ; auto. apply InT_In ; auto. unfold pair_atom_same_antec. simpl.\n       apply andb_prop in e. destruct e. unfold pair_atom_same_antec in H1. simpl in H1.\n       destruct m. 2-6: exfalso ; inversion H1. destruct A. 1-4: inversion H1. 2: inversion H1.\n       destruct A1. 2-6: inversion H1. auto. }\n     destruct n. exfalso. apply In_pos_top_atomimps_L2_0_False in H0. auto.\n     apply IHl in H0. destruct H0. repeat destruct s. repeat destruct p. subst.\n     exists (Box a :: x). exists x0. exists x1. exists x2. repeat split ; auto.\n     assert (length (Box a :: x) = S (length x)).\n     simpl. auto. rewrite <- H0.\n     assert (Box a :: x ++ A :: x0 ++ # x2 :: x1 = (Box a :: x) ++ A :: x0 ++ # x2 :: x1).\n     simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n     rewrite effective_remove_nth. rewrite <- nth_split_idL. auto.\n     assert (length (Box a :: x) = S (length x)).\n     simpl. auto. rewrite <- H0.\n     assert (Box a :: x ++ A :: x0 ++ # x2 :: x1 = (Box a :: x) ++ A :: x0 ++ # x2 :: x1).\n     simpl. repeat rewrite <- app_assoc ; auto. rewrite H1.\n     rewrite effective_remove_nth. rewrite <- nth_split_idR. auto. }\nQed.\n\nLemma Good_pos_in_pos_top_atom_atomimps_L2 : forall A P Γ0 Γ1 Γ2,\n              In (# P → A, S (length Γ0)) (pos_top_atomimps_L2 (Γ0 ++ # P → A :: Γ1 ++ # P :: Γ2)).\nProof.\ninduction Γ0.\n- intros. simpl. unfold pos_top_atomimps_L2. unfold pos_atomimps_is_right_atoms. apply in_map_iff.\n  exists ((# P, S (S (length Γ1))),(# P → A, 1)). split. auto. apply filter_In. split. apply in_concat.\n  exists (map (fun y : MPropF V * nat => ((# P, S (S (length Γ1))), y)) (pos_top_atomimps (# P → A :: Γ1 ++ # P :: Γ2))).\n  split. unfold all_pos_top_atoms_atomimps. apply in_map_iff. exists (# P, S (S (length Γ1))) ; split ; auto.\n  simpl. auto. apply in_map_iff. exists (# P, S (length Γ1)). split ; auto. apply Good_pos_in_pos_top_atoms.\n  apply in_map_iff. exists (# P → A, 1). split ; simpl ; auto. unfold pair_atom_same_antec.\n  simpl. apply eqb_prop_eq. auto.\n- intros. simpl. pose (IHΓ0 Γ1 Γ2). unfold pos_top_atomimps_L2 in i. unfold pos_atomimps_is_right_atoms in i.\n  apply in_map_iff in i. destruct i. destruct x. destruct p. destruct p0. simpl in H. destruct H. inversion H. subst.\n  clear H. apply filter_In in H0. destruct H0. simpl in H0. apply in_concat in H. destruct H. destruct H.\n  apply andb_prop in H0. destruct H0. apply Nat.ltb_lt in H0. unfold pair_atom_same_antec in H2. simpl in H2.\n  destruct m. 2-6: exfalso ; inversion H2. apply eqb_prop_eq in H2. subst. unfold all_pos_top_atoms_atomimps in H.\n  apply in_map_iff in H. destruct H. destruct H. subst. apply in_map_iff in H1. destruct H1. destruct x0. destruct x.\n  destruct H. inversion H. subst. clear H. unfold pos_top_atomimps_L2.\n  apply in_map_iff. exists ((#P, S n),(# P → A, S (S (length Γ0)))). simpl. split ; auto.\n  unfold pos_atomimps_is_left_atoms. apply filter_In. repeat split. 2: simpl ; auto.\n  2: apply andb_true_intro. 2: split. 2: apply Nat.ltb_lt. 2: lia. 2: unfold pair_atom_same_antec.\n  2: simpl ; apply eqb_prop_eq ; auto. apply in_concat.\n  exists (map (fun y : MPropF V * nat => ((# P, S n), y)) (pos_top_atomimps (a :: Γ0 ++ # P → A:: Γ1 ++ # P :: Γ2))). split ; auto.\n  unfold all_pos_top_atoms_atomimps. apply in_map_iff. exists (# P, S n). split ; auto.\n  unfold pos_top_atoms. destruct a. 2-6:apply in_map_iff ; exists (# P, n) ; simpl ; split ; auto.\n  apply in_cons. apply in_map_iff ; exists (# P, n) ; simpl ; split ; auto.\n  apply in_map_iff. exists (# P → A, S (S (length Γ0))). split ; auto.\n  simpl. destruct a.\n  1-4: apply in_map_iff ; exists ((# P → A, S (length Γ0))) ; simpl ; split ; auto.\n  2: apply in_map_iff ; exists ((# P → A, S (length Γ0))) ; simpl ; split ; auto.\n  destruct a1. 2-6: apply in_map_iff ; exists ((# P → A, S (length Γ0))) ; simpl ; split ; auto.\n  apply in_cons.  apply in_map_iff ; exists ((# P → A, S (length Γ0))) ; simpl ; split ; auto.\nQed.\n\nLemma AtomImpL2_help01 : forall prem s l, InT prem (prems_AtomImp_L2 l s) ->\n                  (existsT2 n A P Γ0 Γ1 C,\n                        (In (Imp # P A, S n) l) *\n                        (prem = (Γ0 ++ A :: Γ1, C)) *\n                        (C = snd s) *\n                        (Γ0 = (fst (nth_split n (remove_nth (S n) (Imp # P A) (fst s))))) *\n                        (Γ1 = (snd (nth_split n (remove_nth (S n) (Imp # P A) (fst s)))))).\nProof.\nintros prem s. destruct s. induction l0 ; intros.\n- simpl in H. inversion H.\n- simpl (fst (l, m)). destruct a. destruct m0.\n  1-4: simpl in H ; destruct n ; pose (IHl0 H) ; repeat destruct s ; repeat destruct p ; exists x ; exists x0 ; exists x1 ;\n  exists x2 ; exists x3 ; exists x4 ; repeat split ; try auto ; apply in_cons ; assumption.\n  2: simpl in H ; destruct n ; pose (IHl0 H) ; repeat destruct s ; repeat destruct p ; exists x ; exists x0 ; exists x1 ;\n  exists x2 ; exists x3 ; exists x4 ; repeat split ; try auto ; apply in_cons ; assumption.\n  destruct m0_1.\n  2-6: simpl in H ; destruct n ; pose (IHl0 H) ; repeat destruct s ; repeat destruct p ; exists x ; exists x0 ; exists x1 ;\n  exists x2 ; exists x3 ; exists x4 ; repeat split ; try auto ; apply in_cons ; assumption.\n  destruct n.\n  + pose (IHl0 H). repeat destruct s. repeat destruct p. exists x. exists x0. exists x1.\n     exists x2. exists x3. exists x4. repeat split ; try auto. apply in_cons. assumption.\n  + unfold prems_AtomImp_L2 in H. simpl (snd (l, m)). simpl (fst (l, m)).\n     assert ((prem = ((fst (nth_split n (remove_nth (S n) (# v → m0_2) l)) ++\n        m0_2 :: snd (nth_split n (remove_nth (S n) (# v → m0_2) (fst (l, m)))), m))) +\n     InT prem ((fix prems_AtomImp_L2 (l : list (MPropF V * nat)) (s : list (MPropF V) * MPropF V) {struct l} :\n               list (list (MPropF V) * MPropF V) :=\n             match l with\n             | [] => []\n             | (C, 0) :: t => prems_AtomImp_L2 t s\n             | (C, S m) :: t =>\n                 match C with\n                 | # _ → B =>\n                     (fst (nth_split m (remove_nth (S m) C (fst s))) ++ B :: snd (nth_split m (remove_nth (S m) C (fst s))), snd s)\n                     :: prems_AtomImp_L2 t s\n                 | _ => prems_AtomImp_L2 t s\n                 end\n             end) l0 (l, m))).\n      inversion H ; auto. destruct H0.\n    * subst. clear H. clear IHl0. exists n. exists m0_2. exists v. simpl (fst (l, m)).\n      exists (fst (nth_split n (remove_nth (S n) (# v → m0_2) l))).\n      exists (snd (nth_split n (remove_nth (S n) (# v → m0_2) l))). exists m. repeat split ; auto. apply in_eq.\n    * apply IHl0 in i. destruct i. repeat destruct s. repeat destruct p. exists x. exists x0. exists x1.\n      exists x2. exists x3. exists x4. repeat split ; try auto. apply in_cons. assumption.\nQed.\n\nLemma AtomImpL2_help0111 : forall A P l Γ0 Γ1 C,\n      InT (Γ0 ++ A :: Γ1, C) (prems_AtomImp_L2 l (Γ0 ++ # P → A :: Γ1, C)) ->\n      InT (# P → A, S (length Γ0)) l.\nProof.\ninduction l.\n- intros. simpl in H. inversion H.\n- intros. destruct a. destruct m.\n  1-4: apply InT_cons ; apply IHl with (Γ1:=Γ1) (C:=C) ; unfold prems_AtomImp_L2 in H ; destruct n ; auto.\n  2: apply InT_cons ; apply IHl with (Γ1:=Γ1) (C:=C) ; unfold prems_AtomImp_L2 in H ; destruct n ; auto.\n  simpl in H. destruct n ; auto. apply IHl in H. apply InT_cons ; auto.\n  simpl in H. destruct m1 ; simpl in H. 2-6: apply IHl in H ; apply InT_cons ; auto.\n  inversion H. 2: subst ; apply IHl in H1 ; apply InT_cons ; auto.\n  subst. inversion H1. clear H1. clear H. apply remove_split_eq in H2.\n  destruct H2. repeat destruct p. subst. apply InT_eq.\nQed.\n\nLemma shift_pos_top_atoms : forall A n Γ0 Γ1, InT (A, n) (pos_top_atoms (Γ0 ++ Γ1)) -> (length Γ0 < n) ->\n                                InT (A, (n - length Γ0)) (pos_top_atoms (Γ1)).\nProof.\ninduction n.\n- intros. simpl. exfalso. lia.\n- intros. destruct Γ0.\n  * simpl. auto.\n  * simpl in H0. simpl. simpl in H. destruct m.\n    inversion H. inversion H2 ; subst. simpl. exfalso. lia. subst. apply InT_map_iff in H2.\n    destruct H2. destruct p. destruct x. simpl in e. inversion e ; subst. apply IHn in i ; auto ; lia.\n    1-5: apply InT_map_iff in H ; destruct H ; destruct p ; destruct x ; simpl in e ; inversion e ; subst ; apply IHn in i ; auto ; lia.\nQed.\n\nLemma AtomImpL2_help011 : forall A P Γ0 Γ1 C,\n      InT (Γ0 ++ A :: Γ1, C) (prems_AtomImp_L2 (pos_top_atomimps_L2 (Γ0 ++ # P → A :: Γ1)) (Γ0 ++ # P → A :: Γ1, C)) ->\n      (existsT2 Γ2 Γ3, Γ2 ++ # P :: Γ3 = Γ1).\nProof.\nintros.\nassert (InT (# P → A, S (length Γ0)) (pos_top_atomimps_L2 (Γ0 ++ # P → A :: Γ1))).\napply AtomImpL2_help0111 with (Γ1:=Γ1) (C:=C) ; auto.\nunfold pos_top_atomimps_L2 in H0. unfold pos_atomimps_is_right_atoms in H0.\nunfold all_pos_top_atoms_atomimps in H0. apply InT_map_iff in H0.\ndestruct H0. destruct x. simpl in p. destruct p. subst. destruct p0. apply filter_InT in i.\ndestruct i. simpl in e. assert (m = # P). symmetry in e ; apply Bool.andb_true_eq in e.\ndestruct e. unfold pair_atom_same_antec in H1. simpl in H1. destruct m ; simpl in H1 ; inversion H1.\nsymmetry in H3. apply eqb_prop_eq in H3. subst. auto. subst.\napply InT_concat in i. destruct i. destruct p.\napply InT_map_iff in i. destruct i. destruct p. subst. apply Bool.andb_true_iff in e.\ndestruct e. apply Nat.ltb_lt in H0. unfold pair_atom_same_antec in H1.\nsimpl in H1. apply InT_map_iff in i0. destruct i0. destruct p. inversion e.\nsubst. clear e. pose (@shift_pos_top_atoms (# P) n (Γ0 ++ [# P → A]) Γ1).\nrepeat rewrite <- app_assoc in i1. simpl in i1. pose (i1 i). rewrite app_length in i2. simpl in i2.\nassert ((Nat.add (length Γ0) 1) = S (length Γ0)). lia. rewrite H2 in i2.\npose (i2 H0). Search pos_top_atoms.\nassert (existsT2 m, S m = n - S (length Γ0)).\ndestruct (n - S (length Γ0)). exfalso. apply InT_In in i3. apply In_pos_top_atoms_0_False in i3. auto.\nexists n0 ; auto. destruct H3. rewrite <- e in i3. apply InT_In in i3.\napply In_pos_top_atoms_split_l in i3. destruct i3. repeat destruct s.\nrepeat destruct p. subst. exists x0. exists x1. auto.\nQed.\n\nLemma AtomImpL2_help1 : forall prem s, InT prem (prems_AtomImp_L2 (pos_top_atomimps_L2 (fst s)) s) -> AtomImpL2Rule [prem] s.\nProof.\nintros. destruct s. simpl in H. pose (@AtomImpL2_help01 _ _ _ H). repeat destruct s.\nrepeat destruct p. subst. simpl in i. simpl (fst (l, m)).\nsimpl (fst (l, m)) in H. simpl (snd (l, m)). simpl (snd (l, m)) in H.\napply In_pos_top_atomimps_L2_split_l in i.\ndestruct i. repeat destruct s. repeat destruct p. rewrite <- e. simpl (fst (l, m)) in e0. rewrite <- e0.\nsubst. repeat rewrite <- app_assoc. simpl.\nrepeat rewrite effective_remove_nth in H. rewrite <- nth_split_idL in H. rewrite <- nth_split_idR in H.\napply AtomImpL2_help011 in H. destruct H. destruct s. rewrite <- e1. apply AtomImpL2Rule_I.\nQed.\n\nLemma AtomImpL2_help002 : forall Γ0 Γ1 Γ2 l C A P,\n           InT (Γ0 ++ A :: Γ1 ++ # P :: Γ2, C) (prems_AtomImp_L2 ((Imp # P A, S (length Γ0)) :: l) (Γ0 ++ # P → A :: Γ1 ++ # P :: Γ2, C)).\nProof.\nintros. unfold prems_AtomImp_L2.\nsimpl (fst (Γ0 ++ # P → A :: Γ1 ++ # P :: Γ2, C)). simpl (snd (Γ0 ++ # P → A :: Γ1 ++ # P :: Γ2, C)).\nrepeat rewrite effective_remove_nth. rewrite <- nth_split_idL. rewrite <- nth_split_idR. apply InT_eq.\nQed.\n\nLemma AtomImpL2_help02 : forall Γ0 Γ1 Γ2 A P C l n,\n            AtomImpL2Rule [(Γ0 ++ A :: Γ1 ++ # P :: Γ2, C)] (Γ0 ++ # P → A :: Γ1 ++ # P :: Γ2, C) ->\n            (length Γ0 = n) ->\n            (In (# P → A, S n) l) ->\n            InT (Γ0 ++ A :: Γ1 ++ # P :: Γ2, C) (prems_AtomImp_L2 l (Γ0 ++ # P → A :: Γ1 ++ # P :: Γ2, C)).\nProof.\ninduction l ; intros.\n- inversion H1.\n- destruct a. destruct m.\n  1-4: subst ; apply In_InT_pair in H1 ; inversion H1 ; subst ; inversion H2 ; subst ; apply InT_In in H2 ;\n    assert (J1: length Γ0 = length Γ0) ; try reflexivity ; pose (IHl _ H J1 H2) ; simpl ; destruct n0 ; assumption ; assumption.\n  2: subst ; apply In_InT_pair in H1 ; inversion H1 ; subst ; inversion H2 ; subst ; apply InT_In in H2 ;\n    assert (J1: length Γ0 = length Γ0) ; try reflexivity ; pose (IHl _ H J1 H2) ; simpl ; destruct n0 ; assumption ; assumption.\n  destruct m1.\n  2-6: subst ; apply In_InT_pair in H1 ; inversion H1 ; subst ; inversion H2 ; subst ; apply InT_In in H2 ;\n    assert (J1: length Γ0 = length Γ0) ; try reflexivity ; pose (IHl _ H J1 H2) ; simpl ; destruct n0 ; assumption ; assumption.\n  apply In_InT_pair in H1. inversion H1.\n    + subst. inversion H3. subst. apply AtomImpL2_help002.\n    + subst. assert (J1: (length Γ0) = (length Γ0)). reflexivity. apply InT_In in H3.\n       pose (IHl (length Γ0) H J1 H3). simpl. destruct n0 ; auto. apply InT_cons. auto.\nQed.\n\nLemma AtomImpL2_help2 : forall prem s, AtomImpL2Rule [prem] s -> InT prem (prems_AtomImp_L2 (pos_top_atomimps_L2 (fst s)) s).\nProof.\nintros. inversion H. subst. simpl.\npose (@AtomImpL2_help02 Γ0 Γ1 Γ2 A P C (pos_top_atomimps_L2 (Γ0 ++ # P → A :: Γ1 ++ # P :: Γ2)) (length Γ0)).\napply i ; try assumption ; auto. apply Good_pos_in_pos_top_atom_atomimps_L2.\nQed.\n\nLemma finite_AtomImpL2_premises_of_S : forall (s : (list (MPropF V)) * (MPropF V)), existsT2 listAtomImpL2prems,\n              (forall prems, ((AtomImpL2Rule prems s) -> (InT prems listAtomImpL2prems)) *\n                             ((InT prems listAtomImpL2prems) -> (AtomImpL2Rule prems s))).\nProof.\nintros. destruct s.\nexists (map (fun y => [y]) (prems_AtomImp_L2 (pos_top_atomimps_L2 l) (l,m))).\nintros. split ; intro.\n- inversion H. subst.\n  pose (AtomImpL2_help2 H). apply InT_map_iff. exists (Γ0 ++ A :: Γ1 ++ # P :: Γ2, m) ; split ; auto.\n- apply InT_map_iff in H. destruct H. destruct p. subst. apply AtomImpL2_help1. simpl. assumption.\nQed.\n\n\n\n(*------------------------------------------------------------------------------------------------------------------------------------------------------------------- *)\n\n\n\n\n\n(* AndImpL rule. *)\n\nFixpoint top_andimps (l : list (MPropF V)) : list (MPropF V) :=\nmatch l with\n  | nil => nil\n  | h :: t => match h with\n                | Imp A B => match A with\n                                   | And C D => (Imp (And C D) B) :: top_andimps t\n                                   | _ => top_andimps t\n                                   end\n                | _ => top_andimps t\n              end\nend.\n\nFixpoint pos_top_andimps (l : list (MPropF V)) : (list ((MPropF V) * nat)) :=\nmatch l with\n  | nil => nil\n  | h :: t => match h with\n                | Imp A B => match A with\n                                   | And C D => (Imp (And C D) B, 1) :: (map (fun y => (fst y, S (snd y))) (pos_top_andimps t))\n                                   | _ => (map (fun y => (fst y, S (snd y))) (pos_top_andimps t))\n                                   end\n                | _ => (map (fun y => (fst y, S (snd y))) (pos_top_andimps t))\n              end\nend.\n\nFixpoint prems_AndImp_L (l : list ((MPropF V) * nat)) (s : (list (MPropF V)) * (MPropF V)) : list ((list (MPropF V)) * (MPropF V)) :=\nmatch l with\n  | nil => nil\n  | (C, n) :: t => match n with\n      | 0 => prems_AndImp_L t s\n      | S m => match C with\n           | Imp A B => match A with\n                               | And D E => ((fst (nth_split m (remove_nth (S m) C (fst s)))) ++ (Imp D (Imp E B)) :: (snd (nth_split m (remove_nth (S m) C (fst s)))) , snd s)\n                                                      :: (prems_AndImp_L t s)\n                               | _ => prems_AndImp_L t s\n                               end\n           | _ => prems_AndImp_L t s\n           end\n      end\nend. \n\nLemma In_pos_top_andimps_0_False : forall l (A : MPropF V), In (A, 0) (pos_top_andimps l) -> False.\nProof.\n- induction l.\n  * intros. inversion H.\n  * intros. simpl in H. destruct a.\n    1-4: simpl in H ; apply In_InT_pair in H ; apply InT_map_iff in H ; destruct H ;\n    destruct p ; destruct x ; inversion e.\n    2: simpl in H ; apply In_InT_pair in H ; apply InT_map_iff in H ; destruct H ;\n    destruct p ; destruct x ; inversion e.\n    destruct a1.\n    1-2: simpl in H ; apply In_InT_pair in H ; apply InT_map_iff in H ; destruct H ;\n    destruct p ; destruct x ; inversion e.\n    2-4: simpl in H ; apply In_InT_pair in H ; apply InT_map_iff in H ; destruct H ;\n    destruct p ; destruct x ; inversion e.\n    simpl in H. destruct H. inversion H. apply In_InT_pair in H. apply InT_map_iff in H. destruct H.\n    destruct p. destruct x. inversion e.\nQed.\n\nLemma In_pos_top_andimps_split_l : forall l (A : MPropF V) n, In (A, S n) (pos_top_andimps l) ->\n          existsT2 l0 l1, (l = l0 ++ A :: l1) *\n                          (length l0 = n) *\n                          (l0 = fst (nth_split n (remove_nth (S n) A l))) *\n                          (l1 = snd (nth_split n (remove_nth (S n) A l))).\nProof.\ninduction l.\n- intros. simpl. exfalso. simpl in H. destruct H.\n- intros. simpl in H. destruct a.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_andimps_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (# v :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (# v :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n    # v :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (# v :: x))). simpl. reflexivity.\n    rewrite H0. assert ((# v :: x ++ A :: x0) = ((# v :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (# v :: x) x0). simpl (length (# v :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (# v :: x))). simpl. reflexivity.\n    rewrite H. assert ((# v :: x ++ A :: x0) = ((# v :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (# v :: x) x0). simpl (length (# v :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_andimps_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (⊥ V :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (⊥ V :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      ⊥ V :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (⊥ V :: x))). simpl. reflexivity.\n    rewrite H0. assert ((⊥ V :: x ++ A :: x0) = ((⊥ V :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (⊥ V :: x) x0). simpl (length (⊥ V :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (⊥ V :: x))). simpl. reflexivity.\n    rewrite H. assert ((⊥ V :: x ++ A :: x0) = ((⊥ V :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (⊥ V :: x) x0). simpl (length (⊥ V :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_andimps_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (a1 ∧ a2 :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (a1 ∧ a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      a1 ∧ a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (a1 ∧ a2 :: x))). simpl. reflexivity.\n    rewrite H0. assert ((a1 ∧ a2 :: x ++ A :: x0) = ((a1 ∧ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (a1 ∧ a2 :: x) x0). simpl (length (a1 ∧ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (a1 ∧ a2 :: x))). simpl. reflexivity.\n    rewrite H. assert ((a1 ∧ a2 :: x ++ A :: x0) = ((a1 ∧ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (a1 ∧ a2 :: x) x0). simpl (length (a1 ∧ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_andimps_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (a1 ∨ a2 :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (a1 ∨ a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      a1 ∨ a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (a1 ∨ a2 :: x))). simpl. reflexivity.\n    rewrite H0. assert ((a1 ∨ a2 :: x ++ A :: x0) = ((a1 ∨ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (a1 ∨ a2 :: x) x0). simpl (length (a1 ∨ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (a1 ∨ a2 :: x))). simpl. reflexivity.\n    rewrite H. assert ((a1 ∨ a2 :: x ++ A :: x0) = ((a1 ∨ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (a1 ∨ a2 :: x) x0). simpl (length (a1 ∨ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * destruct a1.\n    + apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_andimps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists (# v → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst (# v → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        # v → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length (# v → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert ((# v → a2 :: x ++ A :: x0) = ((# v → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL (# v → a2 :: x) x0). simpl (length (# v → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length (# v → a2 :: x))). simpl. reflexivity.\n        rewrite H. assert ((# v → a2 :: x ++ A :: x0) = ((# v → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n        pose (nth_split_idR (# v → a2 :: x) x0). simpl (length (# v → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n    + apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_andimps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists (⊥ V → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst (⊥ V → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        ⊥ V → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length (⊥ V → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert ((⊥ V → a2 :: x ++ A :: x0) = ((⊥ V → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL (⊥ V → a2 :: x) x0). simpl (length (⊥ V → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length (⊥ V → a2 :: x))). simpl. reflexivity.\n        rewrite H. assert ((⊥ V → a2 :: x ++ A :: x0) = ((⊥ V → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n        pose (nth_split_idR (⊥ V → a2 :: x) x0). simpl (length (⊥ V → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n    + apply In_InT_pair in H. inversion H.\n      { inversion H1. subst. exists []. exists l. repeat split. simpl.\n        destruct (eq_dec_form ((a1_1 ∧ a1_2) → a2) ((a1_1 ∧ a1_2) → a2)). reflexivity. exfalso. auto. }\n      { subst. apply InT_map_iff in H1. destruct H1. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_andimps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists ((a1_1 ∧ a1_2) → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst ((a1_1 ∧ a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        (a1_1 ∧ a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length ((a1_1 ∧ a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H1. assert (((a1_1 ∧ a1_2) → a2 :: x ++ A :: x0) = (((a1_1 ∧ a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H2. clear H2. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL ((a1_1 ∧ a1_2) → a2 :: x) x0). simpl (length ((a1_1 ∧ a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length ((a1_1 ∧ a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert (((a1_1 ∧ a1_2) → a2 :: x ++ A :: x0) = (((a1_1 ∧ a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idR ((a1_1 ∧ a1_2) → a2 :: x) x0). simpl (length ((a1_1 ∧ a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity. }\n    + apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_andimps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists ((a1_1 ∨ a1_2) → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst ((a1_1 ∨ a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        (a1_1 ∨ a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length ((a1_1 ∨ a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert (((a1_1 ∨ a1_2) → a2 :: x ++ A :: x0) = (((a1_1 ∨ a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL ((a1_1 ∨ a1_2) → a2 :: x) x0). simpl (length ((a1_1 ∨ a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length ((a1_1 ∨ a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H. assert (((a1_1 ∨ a1_2) → a2 :: x ++ A :: x0) = (((a1_1 ∨ a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n        pose (nth_split_idR ((a1_1 ∨ a1_2) → a2 :: x) x0). simpl (length ((a1_1 ∨ a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n    + apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_andimps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists ((a1_1 → a1_2) → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst ((a1_1 → a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        (a1_1 → a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length ((a1_1 → a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert (((a1_1 → a1_2) → a2 :: x ++ A :: x0) = (((a1_1 → a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL ((a1_1 → a1_2) → a2 :: x) x0). simpl (length ((a1_1 → a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length ((a1_1 → a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H. assert (((a1_1 → a1_2) → a2 :: x ++ A :: x0) = (((a1_1 → a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n        pose (nth_split_idR ((a1_1 → a1_2) → a2 :: x) x0). simpl (length ((a1_1 → a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n    + apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_andimps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists (Box a1 → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst (Box a1 → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        Box a1 → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length (Box a1 → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert ((Box a1 → a2 :: x ++ A :: x0) = ((Box a1 → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL (Box a1 → a2 :: x) x0). simpl (length (Box a1 → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length (Box a1 → a2 :: x))). simpl. reflexivity.\n        rewrite H. assert ((Box a1 → a2 :: x ++ A :: x0) = ((Box a1 → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n        pose (nth_split_idR (Box a1 → a2 :: x) x0). simpl (length (Box a1 → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_andimps_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (Box a :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (Box a :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n    Box a :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (Box a :: x))). simpl. reflexivity.\n    rewrite H0. assert ((Box a :: x ++ A :: x0) = ((Box a :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (Box a :: x) x0). simpl (length (Box a :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (Box a :: x))). simpl. reflexivity.\n    rewrite H. assert ((Box a :: x ++ A :: x0) = ((Box a :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (Box a :: x) x0). simpl (length (Box a :: x)) in e2.\n    rewrite <- e2. reflexivity.\nQed.\n\nLemma Good_pos_in_pos_top_andimps : forall A B C Γ0 Γ1,\n              In (Imp (And A B) C, S (length Γ0)) (pos_top_andimps (Γ0 ++ Imp (And A B) C :: Γ1)).\nProof.\ninduction Γ0.\n- intros. simpl. auto.\n- intros. destruct a.\n  1-4: simpl ; apply InT_In ; apply InT_map_iff ; exists (Imp (And A B)C, S (length Γ0)) ;\n  split ; simpl ; try reflexivity ; apply In_InT_pair ; apply IHΓ0.\n  2: simpl ; apply InT_In ; apply InT_map_iff ; exists (Imp (And A B) C, S (length Γ0)) ;\n  split ; simpl ; try reflexivity ; apply In_InT_pair ; apply IHΓ0.\n  destruct a1.\n  1-2: simpl ; apply InT_In ; apply InT_map_iff ; exists (Imp (And A B)C, S (length Γ0)) ;\n  split ; simpl ; try reflexivity ; apply In_InT_pair ; apply IHΓ0.\n  2-4: simpl ; apply InT_In ; apply InT_map_iff ; exists (Imp (And A B)C, S (length Γ0)) ;\n  split ; simpl ; try reflexivity ; apply In_InT_pair ; apply IHΓ0.\n  simpl. right. apply InT_In. apply InT_map_iff. exists (Imp (And A B) C, S (length Γ0)).\n  split. simpl. reflexivity. apply In_InT_pair. apply IHΓ0.\nQed.\n\nLemma AndImpL_help01 : forall prem s l, InT prem (prems_AndImp_L l s) ->\n                  (existsT2 n A B D Γ0 Γ1 C,\n                        (In (Imp (And A B) D, S n) l) *\n                        (prem = (Γ0 ++ Imp A (Imp B D) :: Γ1, C)) *\n                        (C = snd s) *\n                        (Γ0 = (fst (nth_split n (remove_nth (S n) (Imp (And A B) D) (fst s))))) *\n                        (Γ1 = (snd (nth_split n (remove_nth (S n) (Imp (And A B) D) (fst s)))))).\nProof.\nintros prem s. destruct s. induction l0 ; intros.\n- simpl in H. inversion H.\n- simpl (fst (l, m)). destruct a. destruct m0.\n  1-4: simpl in H ; destruct n ; pose (IHl0 H) ; repeat destruct s ; repeat destruct p ; exists x ; exists x0 ; exists x1 ;\n  exists x2 ; exists x3 ; exists x4 ; exists x5 ; repeat split ; try auto ; apply in_cons ; assumption.\n  2: simpl in H ; destruct n ; pose (IHl0 H) ; repeat destruct s ; repeat destruct p ; exists x ; exists x0 ; exists x1 ;\n  exists x2 ; exists x3 ; exists x4 ; exists x5 ; repeat split ; try auto ; apply in_cons ; assumption.\n  destruct m0_1.\n  1-2: simpl in H ; destruct n ; pose (IHl0 H) ; repeat destruct s ; repeat destruct p ; exists x ; exists x0 ; exists x1 ;\n  exists x2 ; exists x3 ; exists x4 ; exists x5 ; repeat split ; try auto ; apply in_cons ; assumption.\n  2-4: simpl in H ; destruct n ; pose (IHl0 H) ; repeat destruct s ; repeat destruct p ; exists x ; exists x0 ; exists x1 ;\n  exists x2 ; exists x3 ; exists x4 ; exists x5 ; repeat split ; try auto ; apply in_cons ; assumption.\n  destruct n.\n  + pose (IHl0 H). repeat destruct s. repeat destruct p. exists x. exists x0. exists x1.\n     exists x2. exists x3. exists x4. exists x5. repeat split ; try auto. apply in_cons. assumption.\n  + inversion H.\n    { simpl in H1. simpl in H0. simpl (fst (l, m)) in IHl0. simpl (snd (l, m)) in IHl0.\n      exists n. exists m0_1_1. exists m0_1_2. exists m0_2.\n      exists (fst (nth_split n match n with\n           | 0 => match l with\n                  | [] => []\n                  | B :: tl => if eq_dec_form ((m0_1_1 ∧ m0_1_2) → m0_2) B then tl else B :: tl\n                  end\n           | S _ => match l with\n                    | [] => []\n                    | B :: tl => B :: remove_nth n ((m0_1_1 ∧ m0_1_2) → m0_2) tl\n                    end\n           end)).\n      exists (snd (nth_split n match n with\n           | 0 => match l with\n                  | [] => []\n                  | B :: tl => if eq_dec_form ((m0_1_1 ∧ m0_1_2) → m0_2) B then tl else B :: tl\n                  end\n           | S _ => match l with\n                    | [] => []\n                    | B :: tl => B :: remove_nth n ((m0_1_1 ∧ m0_1_2) → m0_2) tl\n                    end\n           end)). exists m. repeat split ; auto. apply in_eq. }\n    { pose (IHl0 H1). repeat destruct s. repeat destruct p. exists x. exists x0. exists x1.\n      exists x2. exists x3. exists x4. exists x5. repeat split ; try auto. apply in_cons. assumption. }\nQed.\n\nLemma AndImpL_help1 : forall prem s, InT prem (prems_AndImp_L (pos_top_andimps (fst s)) s) -> AndImpLRule [prem] s.\nProof.\nintros. pose (@AndImpL_help01 _ _ _ H). repeat destruct s0. destruct s.\nrepeat destruct p. subst. simpl in i. simpl (fst (l, m)).\nsimpl (fst (l, m)) in H. simpl (snd (l, m)). simpl (snd (l, m)) in H.\napply In_pos_top_andimps_split_l in i.\ndestruct i. destruct s. repeat destruct p.\nsubst. rewrite <- e. rewrite <- e0. apply AndImpLRule_I.\nQed.\n\nLemma AndImpL_help002 : forall Γ0 Γ1 l C A B D,\n           InT (Γ0 ++ A → B → D :: Γ1, C) (prems_AndImp_L (((A ∧ B) → D, S (length Γ0)) :: l) (Γ0 ++ (A ∧ B) → D :: Γ1, C)).\nProof.\nintros. unfold prems_AndImp_L.\nsimpl (fst (Γ0 ++ (A ∧ B) → D :: Γ1, C)). simpl (snd (Γ0 ++ (A ∧ B) → D :: Γ1, C)).\nrepeat rewrite effective_remove_nth. pose (nth_split_idL Γ0 Γ1).\nrewrite <- e. pose (nth_split_idR Γ0 Γ1). rewrite <- e0. apply InT_eq.\nQed.\n\nLemma AndImpL_help02 : forall Γ0 Γ1 C A B D l n,\n            AndImpLRule [(Γ0 ++ A → B → D :: Γ1, C)] (Γ0 ++ (And A B) → D :: Γ1, C) ->\n            (length Γ0 = n) ->\n            (In ((And A B) → D, S n) l) ->\n            InT (Γ0 ++ A → B → D :: Γ1, C) (prems_AndImp_L l (Γ0 ++ (And A B) → D :: Γ1, C)).\nProof.\ninduction l ; intros.\n- inversion H1.\n- destruct a. destruct m.\n  1-4: subst ; apply In_InT_pair in H1 ; inversion H1 ; subst ; inversion H2 ; subst ; apply InT_In in H2 ;\n    assert (J1: length Γ0 = length Γ0) ; try reflexivity ; pose (IHl _ H J1 H2) ; simpl ; destruct n0 ; assumption ; assumption.\n  2: subst ; apply In_InT_pair in H1 ; inversion H1 ; subst ; inversion H2 ; subst ; apply InT_In in H2 ;\n    assert (J1: length Γ0 = length Γ0) ; try reflexivity ; pose (IHl _ H J1 H2) ; simpl ; destruct n0 ; assumption ; assumption.\n  destruct m1.\n  1-2: subst ; apply In_InT_pair in H1 ; inversion H1 ; subst ; inversion H2 ; subst ; apply InT_In in H2 ;\n    assert (J1: length Γ0 = length Γ0) ; try reflexivity ; pose (IHl _ H J1 H2) ; simpl ; destruct n0 ; assumption ; assumption.\n  2-4: subst ; apply In_InT_pair in H1 ; inversion H1 ; subst ; inversion H2 ; subst ; apply InT_In in H2 ;\n    assert (J1: length Γ0 = length Γ0) ; try reflexivity ; pose (IHl _ H J1 H2) ; simpl ; destruct n0 ; assumption ; assumption.\n  apply In_InT_pair in H1. inversion H1.\n    + subst. inversion H3. subst. apply AndImpL_help002.\n    + subst. assert (J1: (length Γ0) = (length Γ0)). reflexivity. apply InT_In in H3.\n       pose (IHl (length Γ0) H J1 H3). simpl. destruct n0 ; auto. apply InT_cons ; auto.\nQed.\n\nLemma AndImpL_help2 : forall prem s, AndImpLRule [prem] s -> InT prem (prems_AndImp_L (pos_top_andimps (fst s)) s).\nProof.\nintros. inversion H. subst. simpl.\npose (@AndImpL_help02 Γ0 Γ1 D A B C (pos_top_andimps (Γ0 ++ (And A B) → C :: Γ1)) (length Γ0)). apply i ; try assumption ; auto.\napply Good_pos_in_pos_top_andimps.\nQed.\n\nLemma finite_AndImpL_premises_of_S : forall (s : (list (MPropF V)) * (MPropF V)), existsT2 listAndImpLprems,\n              (forall prems, ((AndImpLRule prems s) -> (InT prems listAndImpLprems)) *\n                             ((InT prems listAndImpLprems) -> (AndImpLRule prems s))).\nProof.\nintros. destruct s.\nexists (map (fun y => [y]) (prems_AndImp_L (pos_top_andimps l) (l,m))).\nintros. split ; intro.\n- inversion H. subst.\n  pose (AndImpL_help2 H). apply InT_map_iff. exists (Γ0 ++ A → B → C :: Γ1, m) ; split ; auto.\n- apply InT_map_iff in H. destruct H. destruct p. subst. apply AndImpL_help1. simpl. assumption.\nQed.\n\n\n\n\n\n(*------------------------------------------------------------------------------------------------------------------------------------------------------------------- *)\n\n\n\n\n\n(* OrImpL rule. *)\n\nFixpoint top_orimps (l : list (MPropF V)) : list (MPropF V) :=\nmatch l with\n  | nil => nil\n  | h :: t => match h with\n                | Imp A B => match A with\n                                   | Or C D => (Imp (Or C D) B) :: top_orimps t\n                                   | _ => top_orimps t\n                                   end\n                | _ => top_orimps t\n              end\nend.\n\nFixpoint pos_top_orimps (l : list (MPropF V)) : (list ((MPropF V) * nat)) :=\nmatch l with\n  | nil => nil\n  | h :: t => match h with\n                | Imp A B => match A with\n                                   | Or C D => (Imp (Or C D) B, 1) :: (map (fun y => (fst y, S (snd y))) (pos_top_orimps t))\n                                   | _ => (map (fun y => (fst y, S (snd y))) (pos_top_orimps t))\n                                   end\n                | _ => (map (fun y => (fst y, S (snd y))) (pos_top_orimps t))\n              end\nend.\n\nFixpoint prems_OrImp_L (l : list ((MPropF V) * nat)) (s : (list (MPropF V)) * (MPropF V)) : list ((list (MPropF V)) * (MPropF V)) :=\nmatch l with\n  | nil => nil\n  | (C, n) :: t => match n with\n      | 0 => prems_OrImp_L t s\n      | S m => match C with\n           | Imp A B => match A with\n                               | Or D E => (map (fun x => (((fst (nth_split m (remove_nth (S m) C (fst s)))) ++ Imp D B :: x) , snd s))\n                                                            (listInserts (snd (nth_split m (remove_nth (S m) C (fst s)))) (Imp E B)))\n                                                   ++ (prems_OrImp_L t s)\n                               | _ => prems_OrImp_L t s\n                               end\n           | _ => prems_OrImp_L t s\n           end\n      end\nend.\n\nLemma In_pos_top_orimps_0_False : forall l (A : MPropF V), In (A, 0) (pos_top_orimps l) -> False.\nProof.\n- induction l.\n  * intros. inversion H.\n  * intros. simpl in H. destruct a.\n    1-4: simpl in H ; apply In_InT_pair in H ; apply InT_map_iff in H ; destruct H ;\n    destruct p ; destruct x ; inversion e.\n    2: simpl in H ; apply In_InT_pair in H ; apply InT_map_iff in H ; destruct H ;\n    destruct p ; destruct x ; inversion e.\n    destruct a1.\n    1-3: simpl in H ; apply In_InT_pair in H ; apply InT_map_iff in H ; destruct H ;\n    destruct p ; destruct x ; inversion e.\n    2-3: simpl in H ; apply In_InT_pair in H ; apply InT_map_iff in H ; destruct H ;\n    destruct p ; destruct x ; inversion e.\n    simpl in H. destruct H. inversion H. apply In_InT_pair in H. apply InT_map_iff in H. destruct H.\n    destruct p. destruct x. inversion e.\nQed.\n\nLemma In_pos_top_orimps_split_l : forall l (A : MPropF V) n, In (A, S n) (pos_top_orimps l) ->\n          existsT2 l0 l1, (l = l0 ++ A :: l1) *\n                          (length l0 = n) *\n                          (l0 = fst (nth_split n (remove_nth (S n) A l))) *\n                          (l1 = snd (nth_split n (remove_nth (S n) A l))).\nProof.\ninduction l.\n- intros. simpl. exfalso. simpl in H. destruct H.\n- intros. simpl in H. destruct a.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_orimps_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (# v :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (# v :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n    # v :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (# v :: x))). simpl. reflexivity.\n    rewrite H0. assert ((# v :: x ++ A :: x0) = ((# v :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (# v :: x) x0). simpl (length (# v :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (# v :: x))). simpl. reflexivity.\n    rewrite H. assert ((# v :: x ++ A :: x0) = ((# v :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (# v :: x) x0). simpl (length (# v :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_orimps_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (⊥ V :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (⊥ V :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      ⊥ V :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (⊥ V :: x))). simpl. reflexivity.\n    rewrite H0. assert ((⊥ V :: x ++ A :: x0) = ((⊥ V :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (⊥ V :: x) x0). simpl (length (⊥ V :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (⊥ V :: x))). simpl. reflexivity.\n    rewrite H. assert ((⊥ V :: x ++ A :: x0) = ((⊥ V :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (⊥ V :: x) x0). simpl (length (⊥ V :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_orimps_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (a1 ∧ a2 :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (a1 ∧ a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      a1 ∧ a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (a1 ∧ a2 :: x))). simpl. reflexivity.\n    rewrite H0. assert ((a1 ∧ a2 :: x ++ A :: x0) = ((a1 ∧ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (a1 ∧ a2 :: x) x0). simpl (length (a1 ∧ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (a1 ∧ a2 :: x))). simpl. reflexivity.\n    rewrite H. assert ((a1 ∧ a2 :: x ++ A :: x0) = ((a1 ∧ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (a1 ∧ a2 :: x) x0). simpl (length (a1 ∧ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_orimps_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (a1 ∨ a2 :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (a1 ∨ a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      a1 ∨ a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (a1 ∨ a2 :: x))). simpl. reflexivity.\n    rewrite H0. assert ((a1 ∨ a2 :: x ++ A :: x0) = ((a1 ∨ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (a1 ∨ a2 :: x) x0). simpl (length (a1 ∨ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (a1 ∨ a2 :: x))). simpl. reflexivity.\n    rewrite H. assert ((a1 ∨ a2 :: x ++ A :: x0) = ((a1 ∨ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (a1 ∨ a2 :: x) x0). simpl (length (a1 ∨ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * destruct a1.\n    + apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_orimps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists (# v → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst (# v → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        # v → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length (# v → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert ((# v → a2 :: x ++ A :: x0) = ((# v → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL (# v → a2 :: x) x0). simpl (length (# v → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length (# v → a2 :: x))). simpl. reflexivity.\n        rewrite H. assert ((# v → a2 :: x ++ A :: x0) = ((# v → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n        pose (nth_split_idR (# v → a2 :: x) x0). simpl (length (# v → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n    + apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_orimps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists (⊥ V → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst (⊥ V → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        ⊥ V → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length (⊥ V → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert ((⊥ V → a2 :: x ++ A :: x0) = ((⊥ V → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL (⊥ V → a2 :: x) x0). simpl (length (⊥ V → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length (⊥ V → a2 :: x))). simpl. reflexivity.\n        rewrite H. assert ((⊥ V → a2 :: x ++ A :: x0) = ((⊥ V → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n        pose (nth_split_idR (⊥ V → a2 :: x) x0). simpl (length (⊥ V → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n    + apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_orimps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists ((a1_1 ∧ a1_2) → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst ((a1_1 ∧ a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        (a1_1 ∧ a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length ((a1_1 ∧ a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert (((a1_1 ∧ a1_2) → a2 :: x ++ A :: x0) = (((a1_1 ∧ a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL ((a1_1 ∧ a1_2) → a2 :: x) x0). simpl (length ((a1_1 ∧ a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length ((a1_1 ∧ a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H. assert (((a1_1 ∧ a1_2) → a2 :: x ++ A :: x0) = (((a1_1 ∧ a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n        pose (nth_split_idR ((a1_1 ∧ a1_2) → a2 :: x) x0). simpl (length ((a1_1 ∧ a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n    + apply In_InT_pair in H. inversion H.\n      { inversion H1. subst. exists []. exists l. repeat split. simpl.\n        destruct (eq_dec_form ((a1_1 ∨ a1_2) → a2) ((a1_1 ∨ a1_2) → a2)). reflexivity. exfalso. auto. }\n      { subst. apply InT_map_iff in H1. destruct H1. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_orimps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists ((a1_1 ∨ a1_2) → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst ((a1_1 ∨ a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        (a1_1 ∨ a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length ((a1_1 ∨ a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H1. assert (((a1_1 ∨ a1_2) → a2 :: x ++ A :: x0) = (((a1_1 ∨ a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H2. clear H2. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL ((a1_1 ∨ a1_2) → a2 :: x) x0). simpl (length ((a1_1 ∨ a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length ((a1_1 ∨ a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert (((a1_1 ∨ a1_2) → a2 :: x ++ A :: x0) = (((a1_1 ∨ a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idR ((a1_1 ∨ a1_2) → a2 :: x) x0). simpl (length ((a1_1 ∨ a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity. }\n    + apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_orimps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists ((a1_1 → a1_2) → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst ((a1_1 → a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        (a1_1 → a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length ((a1_1 → a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert (((a1_1 → a1_2) → a2 :: x ++ A :: x0) = (((a1_1 → a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL ((a1_1 → a1_2) → a2 :: x) x0). simpl (length ((a1_1 → a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length ((a1_1 → a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H. assert (((a1_1 → a1_2) → a2 :: x ++ A :: x0) = (((a1_1 → a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n        pose (nth_split_idR ((a1_1 → a1_2) → a2 :: x) x0). simpl (length ((a1_1 → a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n    + apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_orimps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists (Box a1 → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst (Box a1 → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        Box a1 → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length (Box a1 → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert ((Box a1 → a2 :: x ++ A :: x0) = ((Box a1 → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL (Box a1 → a2 :: x) x0). simpl (length (Box a1 → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length (Box a1 → a2 :: x))). simpl. reflexivity.\n        rewrite H. assert ((Box a1 → a2 :: x ++ A :: x0) = ((Box a1 → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n        pose (nth_split_idR (Box a1 → a2 :: x) x0). simpl (length (Box a1 → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_orimps_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (Box a :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (Box a :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n    Box a :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (Box a :: x))). simpl. reflexivity.\n    rewrite H0. assert ((Box a :: x ++ A :: x0) = ((Box a :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (Box a :: x) x0). simpl (length (Box a :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (Box a :: x))). simpl. reflexivity.\n    rewrite H. assert ((Box a :: x ++ A :: x0) = ((Box a :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (Box a :: x) x0). simpl (length (Box a :: x)) in e2.\n    rewrite <- e2. reflexivity.\nQed.\n\nLemma Good_pos_in_pos_top_orimps : forall A B C Γ0 Γ1,\n              In (Imp (Or A B) C, S (length Γ0)) (pos_top_orimps (Γ0 ++ Imp (Or A B) C :: Γ1)).\nProof.\ninduction Γ0.\n- intros. simpl. auto.\n- intros. destruct a.\n  1-4: simpl ; apply InT_In ; apply InT_map_iff ; exists (Imp (Or A B)C, S (length Γ0)) ;\n  split ; simpl ; try reflexivity ; apply In_InT_pair ; apply IHΓ0.\n  2: simpl ; apply InT_In ; apply InT_map_iff ; exists (Imp (Or A B) C, S (length Γ0)) ;\n  split ; simpl ; try reflexivity ; apply In_InT_pair ; apply IHΓ0.\n  destruct a1.\n  1-3: simpl ; apply InT_In ; apply InT_map_iff ; exists (Imp (Or A B)C, S (length Γ0)) ;\n  split ; simpl ; try reflexivity ; apply In_InT_pair ; apply IHΓ0.\n  2-3: simpl ; apply InT_In ; apply InT_map_iff ; exists (Imp (Or A B)C, S (length Γ0)) ;\n  split ; simpl ; try reflexivity ; apply In_InT_pair ; apply IHΓ0.\n  simpl. right. apply InT_In. apply InT_map_iff. exists (Imp (Or A B) C, S (length Γ0)).\n  split. simpl. reflexivity. apply In_InT_pair. apply IHΓ0.\nQed.\n\nLemma OrImpL_help01 : forall prem s l, InT prem (prems_OrImp_L l s) ->\n                  (existsT2 n A B D Γ0 Γ1 Γ2 C,\n                        (In (Imp (Or A B) D, S n) l) *\n                        (prem = (Γ0 ++ Imp A D :: Γ1 ++ Imp B D :: Γ2, C)) *\n                        (C = snd s) *\n                        (Γ0 = (fst (nth_split n (remove_nth (S n) (Imp (Or A B) D) (fst s))))) *\n                        (Γ1 ++ Γ2 = (snd (nth_split n (remove_nth (S n) (Imp (Or A B) D) (fst s)))))).\nProof.\nintros prem s. destruct s. induction l0 ; intros.\n- simpl in H. inversion H.\n- simpl (fst (l, m)). destruct a. destruct m0.\n  1-4: simpl in H ; destruct n ; pose (IHl0 H) ; repeat destruct s ; repeat destruct p ; exists x ; exists x0 ; exists x1 ;\n  exists x2 ; exists x3 ; exists x4 ; exists x5 ; exists x6 ; repeat split ; try auto ; apply in_cons ; assumption.\n  2: simpl in H ; destruct n ; pose (IHl0 H) ; repeat destruct s ; repeat destruct p ; exists x ; exists x0 ; exists x1 ;\n  exists x2 ; exists x3 ; exists x4 ; exists x5 ; exists x6 ; repeat split ; try auto ; apply in_cons ; assumption.\n  destruct m0_1.\n  1-3: simpl in H ; destruct n ; pose (IHl0 H) ; repeat destruct s ; repeat destruct p ; exists x ; exists x0 ; exists x1 ;\n  exists x2 ; exists x3 ; exists x4 ; exists x5 ; exists x6 ; repeat split ; try auto ; apply in_cons ; assumption.\n  2-3: simpl in H ; destruct n ; pose (IHl0 H) ; repeat destruct s ; repeat destruct p ; exists x ; exists x0 ; exists x1 ;\n  exists x2 ; exists x3 ; exists x4 ; exists x5 ; exists x6 ; repeat split ; try auto ; apply in_cons ; assumption.\n  destruct n.\n  + pose (IHl0 H). repeat destruct s. repeat destruct p. exists x. exists x0. exists x1.\n     exists x2. exists x3. exists x4. exists x5. exists x6. repeat split ; try auto. apply in_cons. assumption.\n  + unfold prems_OrImp_L in H. apply InT_app_or in H. destruct H.\n     * apply InT_map_iff in i. destruct i. destruct p. subst. apply InT_listInserts in i. destruct i. destruct s.\n       destruct p. subst. exists n. exists m0_1_1. exists m0_1_2. exists m0_2.\n       exists (fst (nth_split n\n          match n with\n          | 0 => match l with\n                 | [] => []\n                 | B :: tl => if eq_dec_form ((m0_1_1 ∨ m0_1_2) → m0_2) B then tl else B :: tl\n                 end\n          | S _ => match l with\n                   | [] => []\n                   | B :: tl => B :: remove_nth n ((m0_1_1 ∨ m0_1_2) → m0_2) tl\n                   end\n          end)).\n         exists x0. exists x1. exists m. repeat split ; auto. apply in_eq.\n      * apply IHl0 in i. destruct i. repeat destruct s. repeat destruct p. exists x. exists x0. exists x1.\n        exists x2. exists x3. exists x4. exists x5. exists x6. repeat split ; try auto. apply in_cons. assumption.\nQed.\n\nLemma OrImpL_help1 : forall prem s, InT prem (prems_OrImp_L (pos_top_orimps (fst s)) s) -> OrImpLRule [prem] s.\nProof.\nintros. pose (@OrImpL_help01 _ _ _ H). repeat destruct s0. destruct s.\nrepeat destruct p. subst. simpl in i. simpl (fst (l, m)).\nsimpl (fst (l, m)) in H. simpl (snd (l, m)). simpl (snd (l, m)) in H.\napply In_pos_top_orimps_split_l in i.\ndestruct i. destruct s. repeat destruct p. rewrite <- e1. rewrite e2. simpl (fst (l, m)) in e. rewrite <- e in e0.\nrewrite e0. apply OrImpLRule_I.\nQed.\n\nLemma OrImpL_help002 : forall Γ0 Γ1 Γ2 l C A B D,\n           InT (Γ0 ++ A → D :: Γ1 ++ B → D :: Γ2, C) (prems_OrImp_L (((A ∨ B) → D, S (length Γ0)) :: l) (Γ0 ++ (A ∨ B) → D :: Γ1 ++ Γ2, C)).\nProof.\nintros. unfold prems_OrImp_L.\nsimpl (fst (Γ0 ++ (A ∨ B) → D :: Γ1 ++ Γ2, C)). simpl (snd (Γ0 ++ (A ∨ B) → D :: Γ1 ++ Γ2, C)).\nrepeat rewrite effective_remove_nth. pose (nth_split_idL Γ0 (Γ1 ++ Γ2)).\nrewrite <- e. pose (nth_split_idR Γ0 (Γ1 ++ Γ2)). rewrite <- e0. apply InT_or_app. left.\napply InT_map_iff. exists (Γ1 ++ B → D :: Γ2). split. auto. apply listInserts_InT ; auto.\nQed.\n\nLemma OrImpL_help02 : forall Γ0 Γ1 Γ2 C A B D l n,\n            OrImpLRule [(Γ0 ++ A → D :: Γ1 ++ B → D :: Γ2, C)] (Γ0 ++ (Or A B) → D :: Γ1 ++ Γ2, C) ->\n            (length Γ0 = n) ->\n            (In ((Or A B) → D, S n) l) ->\n            InT (Γ0 ++ A → D :: Γ1 ++ B → D :: Γ2, C) (prems_OrImp_L l (Γ0 ++ (Or A B) → D :: Γ1 ++ Γ2, C)).\nProof.\ninduction l ; intros.\n- inversion H1.\n- destruct a. destruct m.\n  1-4: subst ; apply In_InT_pair in H1 ; inversion H1 ; subst ; inversion H2 ; subst ; apply InT_In in H2 ;\n    assert (J1: length Γ0 = length Γ0) ; try reflexivity ; pose (IHl _ H J1 H2) ; simpl ; destruct n0 ; assumption ; assumption.\n  2: subst ; apply In_InT_pair in H1 ; inversion H1 ; subst ; inversion H2 ; subst ; apply InT_In in H2 ;\n    assert (J1: length Γ0 = length Γ0) ; try reflexivity ; pose (IHl _ H J1 H2) ; simpl ; destruct n0 ; assumption ; assumption.\n  destruct m1.\n  1-3: subst ; apply In_InT_pair in H1 ; inversion H1 ; subst ; inversion H2 ; subst ; apply InT_In in H2 ;\n    assert (J1: length Γ0 = length Γ0) ; try reflexivity ; pose (IHl _ H J1 H2) ; simpl ; destruct n0 ; assumption ; assumption.\n  2-3: subst ; apply In_InT_pair in H1 ; inversion H1 ; subst ; inversion H2 ; subst ; apply InT_In in H2 ;\n    assert (J1: length Γ0 = length Γ0) ; try reflexivity ; pose (IHl _ H J1 H2) ; simpl ; destruct n0 ; assumption ; assumption.\n  apply In_InT_pair in H1. inversion H1.\n    + subst. inversion H3. subst. apply OrImpL_help002.\n    + subst. assert (J1: (length Γ0) = (length Γ0)). reflexivity. apply InT_In in H3.\n       pose (IHl (length Γ0) H J1 H3). simpl. destruct n0 ; auto. apply InT_or_app. auto.\nQed.\n\nLemma OrImpL_help2 : forall prem s, OrImpLRule [prem] s -> InT prem (prems_OrImp_L (pos_top_orimps (fst s)) s).\nProof.\nintros. inversion H. subst. simpl.\npose (@OrImpL_help02 Γ0 Γ1 Γ2 D A B C (pos_top_orimps (Γ0 ++ (Or A B) → C :: Γ1 ++ Γ2)) (length Γ0)). apply i ; try assumption ; auto.\napply Good_pos_in_pos_top_orimps.\nQed.\n\nLemma finite_OrImpL_premises_of_S : forall (s : (list (MPropF V)) * (MPropF V)), existsT2 listOrImpLprems,\n              (forall prems, ((OrImpLRule prems s) -> (InT prems listOrImpLprems)) *\n                             ((InT prems listOrImpLprems) -> (OrImpLRule prems s))).\nProof.\nintros. destruct s.\nexists (map (fun y => [y]) (prems_OrImp_L (pos_top_orimps l) (l,m))).\nintros. split ; intro.\n- inversion H. subst.\n  pose (OrImpL_help2 H). apply InT_map_iff. exists (Γ0 ++ A → C :: Γ1 ++ B → C :: Γ2, m) ; split ; auto.\n- apply InT_map_iff in H. destruct H. destruct p. subst. apply OrImpL_help1. simpl. assumption.\nQed.\n\n\n\n\n(*------------------------------------------------------------------------------------------------------------------------------------------------------------------- *)\n\n\n\n\n\n(* ImpImpL rule. *)\n\nFixpoint top_impimps (l : list (MPropF V)) : list (MPropF V) :=\nmatch l with\n  | nil => nil\n  | h :: t => match h with\n                | Imp A B => match A with\n                                   | Imp D E => (Imp (Imp D E) B) :: top_impimps t\n                                   | _ => top_impimps t\n                                   end\n                | _ => top_impimps t\n              end\nend.\n\nFixpoint pos_top_impimps (l : list (MPropF V)) : (list ((MPropF V) * nat)) :=\nmatch l with\n  | nil => nil\n  | h :: t => match h with\n                | Imp A B => match A with\n                                   | Imp C D => (Imp (Imp C D) B, 1) :: (map (fun y => (fst y, S (snd y))) (pos_top_impimps t))\n                                   | _ => (map (fun y => (fst y, S (snd y))) (pos_top_impimps t))\n                                   end\n                | _ => (map (fun y => (fst y, S (snd y))) (pos_top_impimps t))\n              end\nend.\n\nFixpoint prems_ImpImp_L (l : list ((MPropF V) * nat)) (s : (list (MPropF V)) * (MPropF V)) : list (list ((list (MPropF V)) * (MPropF V))) :=\nmatch l with\n  | nil => nil\n  | (C, n) :: t => match n with\n      | 0 => prems_ImpImp_L t s\n      | S m => match C with\n           | Imp A B => match A with\n                               | Imp D E => [(((fst (nth_split m (remove_nth (S m) C (fst s)))) ++ (Imp E B) :: (snd (nth_split m (remove_nth (S m) C (fst s))))), Imp D E);\n                                                     (((fst (nth_split m (remove_nth (S m) C (fst s)))) ++ B :: (snd (nth_split m (remove_nth (S m) C (fst s))))), (snd s))]\n                                                 :: (prems_ImpImp_L t s)\n                               | _ => prems_ImpImp_L t s\n                               end\n           | _ => prems_ImpImp_L t s\n           end\n      end\nend.\n\nLemma In_pos_top_impimps_0_False : forall l (A : MPropF V), In (A, 0) (pos_top_impimps l) -> False.\nProof.\n- induction l.\n  * intros. inversion H.\n  * intros. simpl in H. destruct a.\n    1-4: simpl in H ; apply In_InT_pair in H ; apply InT_map_iff in H ; destruct H ;\n    destruct p ; destruct x ; inversion e.\n    2: simpl in H ; apply In_InT_pair in H ; apply InT_map_iff in H ; destruct H ;\n    destruct p ; destruct x ; inversion e.\n    destruct a1.\n    1-4: simpl in H ; apply In_InT_pair in H ; apply InT_map_iff in H ; destruct H ;\n    destruct p ; destruct x ; inversion e.\n    2: simpl in H ; apply In_InT_pair in H ; apply InT_map_iff in H ; destruct H ;\n    destruct p ; destruct x ; inversion e.\n    simpl in H. destruct H. inversion H. apply In_InT_pair in H. apply InT_map_iff in H. destruct H.\n    destruct p. destruct x. inversion e.\nQed.\n\nLemma In_pos_top_impimps_split_l : forall l (A : MPropF V) n, In (A, S n) (pos_top_impimps l) ->\n          existsT2 l0 l1, (l = l0 ++ A :: l1) *\n                          (length l0 = n) *\n                          (l0 = fst (nth_split n (remove_nth (S n) A l))) *\n                          (l1 = snd (nth_split n (remove_nth (S n) A l))).\nProof.\ninduction l.\n- intros. simpl. exfalso. simpl in H. destruct H.\n- intros. simpl in H. destruct a.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_impimps_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (# v :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (# v :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n    # v :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (# v :: x))). simpl. reflexivity.\n    rewrite H0. assert ((# v :: x ++ A :: x0) = ((# v :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (# v :: x) x0). simpl (length (# v :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (# v :: x))). simpl. reflexivity.\n    rewrite H. assert ((# v :: x ++ A :: x0) = ((# v :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (# v :: x) x0). simpl (length (# v :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_impimps_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (⊥ V :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (⊥ V :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      ⊥ V :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (⊥ V :: x))). simpl. reflexivity.\n    rewrite H0. assert ((⊥ V :: x ++ A :: x0) = ((⊥ V :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (⊥ V :: x) x0). simpl (length (⊥ V :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (⊥ V :: x))). simpl. reflexivity.\n    rewrite H. assert ((⊥ V :: x ++ A :: x0) = ((⊥ V :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (⊥ V :: x) x0). simpl (length (⊥ V :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_impimps_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (a1 ∧ a2 :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (a1 ∧ a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      a1 ∧ a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (a1 ∧ a2 :: x))). simpl. reflexivity.\n    rewrite H0. assert ((a1 ∧ a2 :: x ++ A :: x0) = ((a1 ∧ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (a1 ∧ a2 :: x) x0). simpl (length (a1 ∧ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (a1 ∧ a2 :: x))). simpl. reflexivity.\n    rewrite H. assert ((a1 ∧ a2 :: x ++ A :: x0) = ((a1 ∧ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (a1 ∧ a2 :: x) x0). simpl (length (a1 ∧ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_impimps_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (a1 ∨ a2 :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (a1 ∨ a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      a1 ∨ a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (a1 ∨ a2 :: x))). simpl. reflexivity.\n    rewrite H0. assert ((a1 ∨ a2 :: x ++ A :: x0) = ((a1 ∨ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (a1 ∨ a2 :: x) x0). simpl (length (a1 ∨ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (a1 ∨ a2 :: x))). simpl. reflexivity.\n    rewrite H. assert ((a1 ∨ a2 :: x ++ A :: x0) = ((a1 ∨ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (a1 ∨ a2 :: x) x0). simpl (length (a1 ∨ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * destruct a1.\n    + apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_impimps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists (# v → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst (# v → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        # v → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length (# v → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert ((# v → a2 :: x ++ A :: x0) = ((# v → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL (# v → a2 :: x) x0). simpl (length (# v → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length (# v → a2 :: x))). simpl. reflexivity.\n        rewrite H. assert ((# v → a2 :: x ++ A :: x0) = ((# v → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n        pose (nth_split_idR (# v → a2 :: x) x0). simpl (length (# v → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n    + apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_impimps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists (⊥ V → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst (⊥ V → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        ⊥ V → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length (⊥ V → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert ((⊥ V → a2 :: x ++ A :: x0) = ((⊥ V → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL (⊥ V → a2 :: x) x0). simpl (length (⊥ V → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length (⊥ V → a2 :: x))). simpl. reflexivity.\n        rewrite H. assert ((⊥ V → a2 :: x ++ A :: x0) = ((⊥ V → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n        pose (nth_split_idR (⊥ V → a2 :: x) x0). simpl (length (⊥ V → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n    + apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_impimps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists ((a1_1 ∧ a1_2) → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst ((a1_1 ∧ a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        (a1_1 ∧ a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length ((a1_1 ∧ a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert (((a1_1 ∧ a1_2) → a2 :: x ++ A :: x0) = (((a1_1 ∧ a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL ((a1_1 ∧ a1_2) → a2 :: x) x0). simpl (length ((a1_1 ∧ a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length ((a1_1 ∧ a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H. assert (((a1_1 ∧ a1_2) → a2 :: x ++ A :: x0) = (((a1_1 ∧ a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n        pose (nth_split_idR ((a1_1 ∧ a1_2) → a2 :: x) x0). simpl (length ((a1_1 ∧ a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n    + apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_impimps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists ((a1_1 ∨ a1_2) → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst ((a1_1 ∨ a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        (a1_1 ∨ a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length ((a1_1 ∨ a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert (((a1_1 ∨ a1_2) → a2 :: x ++ A :: x0) = (((a1_1 ∨ a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL ((a1_1 ∨ a1_2) → a2 :: x) x0). simpl (length ((a1_1 ∨ a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length ((a1_1 ∨ a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H. assert (((a1_1 ∨ a1_2) → a2 :: x ++ A :: x0) = (((a1_1 ∨ a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n        pose (nth_split_idR ((a1_1 ∨ a1_2) → a2 :: x) x0). simpl (length ((a1_1 ∨ a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n    + apply In_InT_pair in H. inversion H.\n      { inversion H1. subst. exists []. exists l. repeat split. simpl.\n        destruct (eq_dec_form ((a1_1 → a1_2) → a2) ((a1_1 → a1_2) → a2)). reflexivity. exfalso. auto. }\n      { subst. apply InT_map_iff in H1. destruct H1. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_impimps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists ((a1_1 → a1_2) → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst ((a1_1 → a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        (a1_1 → a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length ((a1_1 → a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H1. assert (((a1_1 → a1_2) → a2 :: x ++ A :: x0) = (((a1_1 → a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H2. clear H2. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL ((a1_1 → a1_2) → a2 :: x) x0). simpl (length ((a1_1 → a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length ((a1_1 → a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert (((a1_1 → a1_2) → a2 :: x ++ A :: x0) = (((a1_1 → a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idR ((a1_1 → a1_2) → a2 :: x) x0). simpl (length ((a1_1 → a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity. }\n    + apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_impimps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists ((Box a1) → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst ((Box a1) → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        (Box a1) → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length ((Box a1) → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert (((Box a1) → a2 :: x ++ A :: x0) = (((Box a1) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL ((Box a1) → a2 :: x) x0). simpl (length ((Box a1) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length ((Box a1) → a2 :: x))). simpl. reflexivity.\n        rewrite H. assert (((Box a1) → a2 :: x ++ A :: x0) = (((Box a1) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n        pose (nth_split_idR ((Box a1) → a2 :: x) x0). simpl (length ((Box a1) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_impimps_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (Box a :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (Box a :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n    Box a :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (Box a :: x))). simpl. reflexivity.\n    rewrite H0. assert ((Box a :: x ++ A :: x0) = ((Box a :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (Box a :: x) x0). simpl (length (Box a :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (Box a :: x))). simpl. reflexivity.\n    rewrite H. assert ((Box a :: x ++ A :: x0) = ((Box a :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (Box a :: x) x0). simpl (length (Box a :: x)) in e2.\n    rewrite <- e2. reflexivity.\nQed.\n\nLemma Good_pos_in_pos_top_impimps : forall A B C Γ0 Γ1,\n              In (Imp (Imp A B) C, S (length Γ0)) (pos_top_impimps (Γ0 ++ Imp (Imp A B) C :: Γ1)).\nProof.\ninduction Γ0.\n- intros. simpl. auto.\n- intros. destruct a.\n  1-4: simpl ; apply InT_In ; apply InT_map_iff ; exists (Imp (Imp A B) C, S (length Γ0)) ;\n  split ; simpl ; try reflexivity ; apply In_InT_pair ; apply IHΓ0.\n  2: simpl ; apply InT_In ; apply InT_map_iff ; exists (Imp (Imp A B) C, S (length Γ0)) ;\n  split ; simpl ; try reflexivity ; apply In_InT_pair ; apply IHΓ0.\n  destruct a1.\n  1-4: simpl ; apply InT_In ; apply InT_map_iff ; exists (Imp (Imp A B) C, S (length Γ0)) ;\n  split ; simpl ; try reflexivity ; apply In_InT_pair ; apply IHΓ0.\n  2: simpl ; apply InT_In ; apply InT_map_iff ; exists (Imp (Imp A B) C, S (length Γ0)) ;\n  split ; simpl ; try reflexivity ; apply In_InT_pair ; apply IHΓ0.\n  simpl. right. apply InT_In. apply InT_map_iff. exists (Imp (Imp A B) C, S (length Γ0)).\n  split. simpl. reflexivity. apply In_InT_pair. apply IHΓ0.\nQed.\n\nLemma ImpImpL_help01 : forall prems s l, InT prems (prems_ImpImp_L l s) ->\n                  (existsT2 n prem1 prem2 A B C Γ0 Γ1 D,\n                        (prems = [prem1; prem2]) *\n                        (In ((Imp (Imp A B) C), S n) l) *\n                        (prem1 = (Γ0 ++ Imp B C :: Γ1, Imp A B)) *\n                        (prem2 = (Γ0 ++ C :: Γ1, D)) *\n                        (D = snd s) *\n                        (Γ0 = (fst (nth_split n (remove_nth (S n) (Imp (Imp A B) C) (fst s))))) *\n                        (Γ1 = (snd (nth_split n (remove_nth (S n) (Imp (Imp A B) C) (fst s)))))).\nProof.\nintros prems s. destruct s. induction l0 ; intros.\n- simpl in H. inversion H.\n- simpl (fst (l, m)). destruct a. destruct m0.\n  1-4: simpl in H ; destruct n ; pose (IHl0 H) ; repeat destruct s ; repeat destruct p ; exists x ; exists x0 ; exists x1 ;\n  exists x2 ; exists x3 ; exists x4 ; exists x5 ; exists x6 ; exists x7 ; repeat split ; try auto ; apply in_cons ; assumption.\n  2: simpl in H ; destruct n ; pose (IHl0 H) ; repeat destruct s ; repeat destruct p ; exists x ; exists x0 ; exists x1 ;\n  exists x2 ; exists x3 ; exists x4 ; exists x5 ; exists x6 ; exists x7 ; repeat split ; try auto ; apply in_cons ; assumption.\n  destruct m0_1.\n  1-4: simpl in H ; destruct n ; pose (IHl0 H) ; repeat destruct s ; repeat destruct p ; exists x ; exists x0 ; exists x1 ;\n  exists x2 ; exists x3 ; exists x4 ; exists x5 ; exists x6 ; exists x7 ; repeat split ; try auto ; apply in_cons ; assumption.\n  2: simpl in H ; destruct n ; pose (IHl0 H) ; repeat destruct s ; repeat destruct p ; exists x ; exists x0 ; exists x1 ;\n  exists x2 ; exists x3 ; exists x4 ; exists x5 ; exists x6 ; exists x7 ; repeat split ; try auto ; apply in_cons ; assumption.\n  destruct n.\n  + pose (IHl0 H). repeat destruct s. repeat destruct p. exists x. exists x0. exists x1.\n     exists x2. exists x3. exists x4. exists x5. exists x6. exists x7. repeat split ; try auto. apply in_cons. assumption.\n  + inversion H.\n    { simpl in H1. simpl in H0. simpl (fst (l, m)) in IHl0. simpl (snd (l, m)) in IHl0.\n      exists n. exists (fst\n         (nth_split n\n            match n with\n            | 0 => match l with\n                   | [] => []\n                   | B :: tl => if eq_dec_form ((m0_1_1 → m0_1_2) → m0_2) B then tl else B :: tl\n                   end\n            | S _ => match l with\n                     | [] => []\n                     | B :: tl => B :: remove_nth n ((m0_1_1 → m0_1_2) → m0_2) tl\n                     end\n            end) ++\n       m0_1_2 → m0_2\n       :: snd\n            (nth_split n\n               match n with\n               | 0 => match l with\n                      | [] => []\n                      | B :: tl => if eq_dec_form ((m0_1_1 → m0_1_2) → m0_2) B then tl else B :: tl\n                      end\n               | S _ => match l with\n                        | [] => []\n                        | B :: tl => B :: remove_nth n ((m0_1_1 → m0_1_2) → m0_2) tl\n                        end\n               end), m0_1_1 → m0_1_2).\n      exists (fst\n        (nth_split n\n           match n with\n           | 0 => match l with\n                  | [] => []\n                  | B :: tl => if eq_dec_form ((m0_1_1 → m0_1_2) → m0_2) B then tl else B :: tl\n                  end\n           | S _ => match l with\n                    | [] => []\n                    | B :: tl => B :: remove_nth n ((m0_1_1 → m0_1_2) → m0_2) tl\n                    end\n           end) ++\n      m0_2\n      :: snd\n           (nth_split n\n              match n with\n              | 0 => match l with\n                     | [] => []\n                     | B :: tl => if eq_dec_form ((m0_1_1 → m0_1_2) → m0_2) B then tl else B :: tl\n                     end\n              | S _ => match l with\n                       | [] => []\n                       | B :: tl => B :: remove_nth n ((m0_1_1 → m0_1_2) → m0_2) tl\n                       end\n              end), m).\n      exists m0_1_1. exists m0_1_2. exists m0_2.\n      exists (fst\n         (nth_split n\n            match n with\n            | 0 => match l with\n                   | [] => []\n                   | B :: tl => if eq_dec_form ((m0_1_1 → m0_1_2) → m0_2) B then tl else B :: tl\n                   end\n            | S _ => match l with\n                     | [] => []\n                     | B :: tl => B :: remove_nth n ((m0_1_1 → m0_1_2) → m0_2) tl\n                     end\n            end)).\n      exists (snd\n            (nth_split n\n               match n with\n               | 0 => match l with\n                      | [] => []\n                      | B :: tl => if eq_dec_form ((m0_1_1 → m0_1_2) → m0_2) B then tl else B :: tl\n                      end\n               | S _ => match l with\n                        | [] => []\n                        | B :: tl => B :: remove_nth n ((m0_1_1 → m0_1_2) → m0_2) tl\n                        end\n               end)). exists m. repeat split ; auto. apply in_eq. }\n    { pose (IHl0 H1). repeat destruct s. repeat destruct p. exists x. exists x0. exists x1.\n      exists x2. exists x3. exists x4. exists x5. exists x6. exists x7. repeat split ; try auto. apply in_cons. assumption. }\nQed.\n\nLemma ImpImpL_help1 : forall prems s, InT prems (prems_ImpImp_L (pos_top_impimps (fst s)) s) -> ImpImpLRule prems s.\nProof.\nintros. pose (@ImpImpL_help01 _ _ _ H). repeat destruct s0. destruct s.\nrepeat destruct p. subst. simpl in i. simpl (fst (l, m)).\nsimpl (fst (l, m)) in H. simpl (snd (l, m)). simpl (snd (l, m)) in H.\napply In_pos_top_impimps_split_l in i.\ndestruct i. destruct s. repeat destruct p.\nsubst. rewrite <- e. rewrite <- e0. apply ImpImpLRule_I.\nQed.\n\nLemma ImpImpL_help002 : forall Γ0 Γ1 l D A B C,\n           InT [(Γ0 ++ B → C :: Γ1, A → B);(Γ0 ++ C :: Γ1, D)] (prems_ImpImp_L (((A →  B) → C, S (length Γ0)) :: l) (Γ0 ++ (A → B) → C :: Γ1, D)).\nProof.\nintros. unfold prems_ImpImp_L.\nsimpl (fst (Γ0 ++ (A → B) → C :: Γ1, D)). simpl (snd (Γ0 ++ (A → B) → C :: Γ1, D)).\nrepeat rewrite effective_remove_nth. pose (nth_split_idL Γ0 Γ1).\nrewrite <- e. pose (nth_split_idR Γ0 Γ1). rewrite <- e0. apply InT_eq.\nQed.\n\nLemma ImpImpL_help02 : forall Γ0 Γ1 D A B C l n,\n            ImpImpLRule [(Γ0 ++ B → C :: Γ1, A → B);(Γ0 ++ C :: Γ1, D)] (Γ0 ++ (A → B) → C :: Γ1, D) ->\n            (length Γ0 = n) ->\n            (In ((A → B) → C, S n) l) ->\n            InT [(Γ0 ++ B → C :: Γ1, A → B);(Γ0 ++ C :: Γ1, D)] (prems_ImpImp_L l (Γ0 ++ (A → B) → C :: Γ1, D)).\nProof.\ninduction l ; intros.\n- inversion H1.\n- destruct a. destruct m.\n  1-4: subst ; apply In_InT_pair in H1 ; inversion H1 ; subst ; inversion H2 ; subst ; apply InT_In in H2 ;\n    assert (J1: length Γ0 = length Γ0) ; try reflexivity ; pose (IHl _ H J1 H2) ; simpl ; destruct n0 ; assumption ; assumption.\n  2: subst ; apply In_InT_pair in H1 ; inversion H1 ; subst ; inversion H2 ; subst ; apply InT_In in H2 ;\n    assert (J1: length Γ0 = length Γ0) ; try reflexivity ; pose (IHl _ H J1 H2) ; simpl ; destruct n0 ; assumption ; assumption.\n  destruct m1.\n  1-4: subst ; apply In_InT_pair in H1 ; inversion H1 ; subst ; inversion H2 ; subst ; apply InT_In in H2 ;\n    assert (J1: length Γ0 = length Γ0) ; try reflexivity ; pose (IHl _ H J1 H2) ; simpl ; destruct n0 ; assumption ; assumption.\n  2: subst ; apply In_InT_pair in H1 ; inversion H1 ; subst ; inversion H2 ; subst ; apply InT_In in H2 ;\n    assert (J1: length Γ0 = length Γ0) ; try reflexivity ; pose (IHl _ H J1 H2) ; simpl ; destruct n0 ; assumption ; assumption.\n  apply In_InT_pair in H1. inversion H1.\n    + subst. inversion H3. subst. apply ImpImpL_help002.\n    + subst. assert (J1: (length Γ0) = (length Γ0)). reflexivity. apply InT_In in H3.\n       pose (IHl (length Γ0) H J1 H3). simpl. destruct n0 ; auto. apply InT_cons ; auto.\nQed.\n\nLemma ImpImpL_help2 : forall prems s, ImpImpLRule prems s -> InT prems (prems_ImpImp_L (pos_top_impimps (fst s)) s).\nProof.\nintros. inversion H. subst. simpl.\npose (@ImpImpL_help02 Γ0 Γ1 D A B C (pos_top_impimps (Γ0 ++ (A → B) → C :: Γ1)) (length Γ0)).\napply i ; try assumption ; auto.\napply Good_pos_in_pos_top_impimps.\nQed.\n\nLemma finite_ImpImpL_premises_of_S : forall (s : (list (MPropF V)) * (MPropF V)), existsT2 listImpImpLprems,\n              (forall prems, ((ImpImpLRule prems s) -> (InT prems listImpImpLprems)) *\n                             ((InT prems listImpImpLprems) -> (ImpImpLRule prems s))).\nProof.\nintros. destruct s.\nexists (prems_ImpImp_L (pos_top_impimps l) (l,m)).\nintros. split ; intro.\n- inversion H. subst.\n  pose (ImpImpL_help2 H). auto.\n- apply ImpImpL_help1. simpl. assumption.\nQed.\n\n\n\n(*------------------------------------------------------------------------------------------------------------------------------------------------------------------- *)\n\n\n\n\n\n(* BoxImpL rule. *)\n\nFixpoint top_boximps (l : list (MPropF V)) : list (MPropF V) :=\nmatch l with\n  | nil => nil\n  | h :: t => match h with\n                | Imp A B => match A with\n                                   | Box C => (Imp (Box C) B) :: top_boximps t\n                                   | _ => top_boximps t\n                                   end\n                | _ => top_boximps t\n              end\nend.\n\nFixpoint pos_top_boximps (l : list (MPropF V)) : (list ((MPropF V) * nat)) :=\nmatch l with\n  | nil => nil\n  | h :: t => match h with\n                | Imp A B => match A with\n                                   | Box C => (Imp (Box C) B, 1) :: (map (fun y => (fst y, S (snd y))) (pos_top_boximps t))\n                                   | _ => (map (fun y => (fst y, S (snd y))) (pos_top_boximps t))\n                                   end\n                | _ => (map (fun y => (fst y, S (snd y))) (pos_top_boximps t))\n              end\nend.\n\nFixpoint prems_BoxImp_L (l : list ((MPropF V) * nat)) (s : (list (MPropF V)) * (MPropF V)) : list (list ((list (MPropF V)) * (MPropF V))) :=\nmatch l with\n  | nil => nil\n  | (C, n) :: t => match n with\n      | 0 => prems_BoxImp_L t s\n      | S m => match C with\n           | Imp A B => match A with\n                               | Box D => [((XBoxed_list (top_boxes (fst s))) ++ [Box D], D); (((fst (nth_split m (remove_nth (S m) C (fst s)))) ++\n                                                 B :: (snd (nth_split m (remove_nth (S m) C (fst s))))), (snd s))]\n                                                 :: (prems_BoxImp_L t s)\n                               | _ => prems_BoxImp_L t s\n                               end\n           | _ => prems_BoxImp_L t s\n           end\n      end\nend.\n\nLemma In_pos_top_boximps_0_False : forall l (A : MPropF V), In (A, 0) (pos_top_boximps l) -> False.\nProof.\n- induction l.\n  * intros. inversion H.\n  * intros. simpl in H. destruct a.\n    1-4: simpl in H ; apply In_InT_pair in H ; apply InT_map_iff in H ; destruct H ;\n    destruct p ; destruct x ; inversion e.\n    2: simpl in H ; apply In_InT_pair in H ; apply InT_map_iff in H ; destruct H ;\n    destruct p ; destruct x ; inversion e.\n    destruct a1.\n    1-5: simpl in H ; apply In_InT_pair in H ; apply InT_map_iff in H ; destruct H ;\n    destruct p ; destruct x ; inversion e.\n    simpl in H. destruct H. inversion H. apply In_InT_pair in H. apply InT_map_iff in H. destruct H.\n    destruct p. destruct x. inversion e.\nQed.\n\nLemma In_pos_top_boximps_split_l : forall l (A : MPropF V) n, In (A, S n) (pos_top_boximps l) ->\n          existsT2 l0 l1, (l = l0 ++ A :: l1) *\n                          (length l0 = n) *\n                          (l0 = fst (nth_split n (remove_nth (S n) A l))) *\n                          (l1 = snd (nth_split n (remove_nth (S n) A l))).\nProof.\ninduction l.\n- intros. simpl. exfalso. simpl in H. destruct H.\n- intros. simpl in H. destruct a.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_boximps_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (# v :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (# v :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n    # v :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (# v :: x))). simpl. reflexivity.\n    rewrite H0. assert ((# v :: x ++ A :: x0) = ((# v :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (# v :: x) x0). simpl (length (# v :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (# v :: x))). simpl. reflexivity.\n    rewrite H. assert ((# v :: x ++ A :: x0) = ((# v :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (# v :: x) x0). simpl (length (# v :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_boximps_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (⊥ V :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (⊥ V :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      ⊥ V :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (⊥ V :: x))). simpl. reflexivity.\n    rewrite H0. assert ((⊥ V :: x ++ A :: x0) = ((⊥ V :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (⊥ V :: x) x0). simpl (length (⊥ V :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (⊥ V :: x))). simpl. reflexivity.\n    rewrite H. assert ((⊥ V :: x ++ A :: x0) = ((⊥ V :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (⊥ V :: x) x0). simpl (length (⊥ V :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_boximps_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (a1 ∧ a2 :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (a1 ∧ a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      a1 ∧ a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (a1 ∧ a2 :: x))). simpl. reflexivity.\n    rewrite H0. assert ((a1 ∧ a2 :: x ++ A :: x0) = ((a1 ∧ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (a1 ∧ a2 :: x) x0). simpl (length (a1 ∧ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (a1 ∧ a2 :: x))). simpl. reflexivity.\n    rewrite H. assert ((a1 ∧ a2 :: x ++ A :: x0) = ((a1 ∧ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (a1 ∧ a2 :: x) x0). simpl (length (a1 ∧ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_boximps_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (a1 ∨ a2 :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (a1 ∨ a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n      a1 ∨ a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (a1 ∨ a2 :: x))). simpl. reflexivity.\n    rewrite H0. assert ((a1 ∨ a2 :: x ++ A :: x0) = ((a1 ∨ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (a1 ∨ a2 :: x) x0). simpl (length (a1 ∨ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (a1 ∨ a2 :: x))). simpl. reflexivity.\n    rewrite H. assert ((a1 ∨ a2 :: x ++ A :: x0) = ((a1 ∨ a2 :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (a1 ∨ a2 :: x) x0). simpl (length (a1 ∨ a2 :: x)) in e2.\n    rewrite <- e2. reflexivity.\n  * destruct a1.\n    + apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_boximps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists (# v → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst (# v → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        # v → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length (# v → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert ((# v → a2 :: x ++ A :: x0) = ((# v → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL (# v → a2 :: x) x0). simpl (length (# v → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length (# v → a2 :: x))). simpl. reflexivity.\n        rewrite H. assert ((# v → a2 :: x ++ A :: x0) = ((# v → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n        pose (nth_split_idR (# v → a2 :: x) x0). simpl (length (# v → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n    + apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_boximps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists (⊥ V → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst (⊥ V → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        ⊥ V → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length (⊥ V → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert ((⊥ V → a2 :: x ++ A :: x0) = ((⊥ V → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL (⊥ V → a2 :: x) x0). simpl (length (⊥ V → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length (⊥ V → a2 :: x))). simpl. reflexivity.\n        rewrite H. assert ((⊥ V → a2 :: x ++ A :: x0) = ((⊥ V → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n        pose (nth_split_idR (⊥ V → a2 :: x) x0). simpl (length (⊥ V → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n    + apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_boximps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists ((a1_1 ∧ a1_2) → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst ((a1_1 ∧ a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        (a1_1 ∧ a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length ((a1_1 ∧ a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert (((a1_1 ∧ a1_2) → a2 :: x ++ A :: x0) = (((a1_1 ∧ a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL ((a1_1 ∧ a1_2) → a2 :: x) x0). simpl (length ((a1_1 ∧ a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length ((a1_1 ∧ a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H. assert (((a1_1 ∧ a1_2) → a2 :: x ++ A :: x0) = (((a1_1 ∧ a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n        pose (nth_split_idR ((a1_1 ∧ a1_2) → a2 :: x) x0). simpl (length ((a1_1 ∧ a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n    + apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_boximps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists ((a1_1 ∨ a1_2) → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst ((a1_1 ∨ a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        (a1_1 ∨ a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length ((a1_1 ∨ a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert (((a1_1 ∨ a1_2) → a2 :: x ++ A :: x0) = (((a1_1 ∨ a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL ((a1_1 ∨ a1_2) → a2 :: x) x0). simpl (length ((a1_1 ∨ a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length ((a1_1 ∨ a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H. assert (((a1_1 ∨ a1_2) → a2 :: x ++ A :: x0) = (((a1_1 ∨ a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n        pose (nth_split_idR ((a1_1 ∨ a1_2) → a2 :: x) x0). simpl (length ((a1_1 ∨ a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n    + apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_boximps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists ((a1_1 → a1_2) → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst ((a1_1 → a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        (a1_1 → a1_2) → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length ((a1_1 → a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert (((a1_1 → a1_2) → a2 :: x ++ A :: x0) = (((a1_1 → a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL ((a1_1 → a1_2) → a2 :: x) x0). simpl (length ((a1_1 → a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length ((a1_1 → a1_2) → a2 :: x))). simpl. reflexivity.\n        rewrite H. assert (((a1_1 → a1_2) → a2 :: x ++ A :: x0) = (((a1_1 → a1_2) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n        pose (nth_split_idR ((a1_1 → a1_2) → a2 :: x) x0). simpl (length ((a1_1 → a1_2) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n    + apply In_InT_pair in H. inversion H.\n      { inversion H1. subst. exists []. exists l. repeat split. simpl.\n        destruct (eq_dec_form ((Box a1) → a2) ((Box a1) → a2)). reflexivity. exfalso. auto. }\n      { subst. apply InT_map_iff in H1. destruct H1. destruct p.\n        destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n        apply InT_In in i. apply In_pos_top_boximps_0_False in i. assumption.\n        apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n        subst. exists ((Box a1) → a2 :: x). exists x0. repeat split.\n        rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n        assert (fst ((Box a1) → a2 :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n        (Box a1) → a2 :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n        assert (S (S (length x)) = S (length ((Box a1) → a2 :: x))). simpl. reflexivity.\n        rewrite H1. assert (((Box a1) → a2 :: x ++ A :: x0) = (((Box a1) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H2. clear H2. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idL ((Box a1) → a2 :: x) x0). simpl (length ((Box a1) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity.\n        rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n        assert (S (S (length x)) = S (length ((Box a1) → a2 :: x))). simpl. reflexivity.\n        rewrite H0. assert (((Box a1) → a2 :: x ++ A :: x0) = (((Box a1) → a2 :: x) ++ A :: x0)). simpl. reflexivity.\n        rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n        pose (nth_split_idR ((Box a1) → a2 :: x) x0). simpl (length ((Box a1) → a2 :: x)) in e2.\n        rewrite <- e2. reflexivity. }\n  * apply In_InT_pair in H. apply InT_map_iff in H. destruct H. destruct p.\n    destruct x. simpl in e. inversion e. subst. destruct n. exfalso.\n    apply InT_In in i. apply In_pos_top_boximps_0_False in i. assumption.\n    apply InT_In in i. pose (IHl A n i). repeat destruct s. repeat destruct p.\n    subst. exists (Box a :: x). exists x0. repeat split.\n    rewrite effective_remove_nth in e1. rewrite effective_remove_nth in e0.\n    assert (fst (Box a :: fst (nth_split (S (length x)) (x ++ x0)), snd (nth_split (S (length x)) (x ++ x0))) =\n    Box a :: fst (nth_split (S (length x)) (x ++ x0))). simpl. reflexivity.\n    assert (S (S (length x)) = S (length (Box a :: x))). simpl. reflexivity.\n    rewrite H0. assert ((Box a :: x ++ A :: x0) = ((Box a :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H1. clear H0. clear H1. rewrite effective_remove_nth.\n    pose (nth_split_idL (Box a :: x) x0). simpl (length (Box a :: x)) in e2.\n    rewrite <- e2. reflexivity.\n    rewrite effective_remove_nth in e0. rewrite effective_remove_nth in e1.\n    assert (S (S (length x)) = S (length (Box a :: x))). simpl. reflexivity.\n    rewrite H. assert ((Box a :: x ++ A :: x0) = ((Box a :: x) ++ A :: x0)). simpl. reflexivity.\n    rewrite H0. clear H. clear H0. rewrite effective_remove_nth.\n    pose (nth_split_idR (Box a :: x) x0). simpl (length (Box a :: x)) in e2.\n    rewrite <- e2. reflexivity.\nQed.\n\nLemma Good_pos_in_pos_top_boximps : forall A B Γ0 Γ1,\n              In (Imp (Box A) B, S (length Γ0)) (pos_top_boximps (Γ0 ++ Imp (Box A) B :: Γ1)).\nProof.\ninduction Γ0.\n- intros. simpl. auto.\n- intros. destruct a.\n  1-4: simpl ; apply InT_In ; apply InT_map_iff ; exists (Imp (Box A) B, S (length Γ0)) ;\n  split ; simpl ; try reflexivity ; apply In_InT_pair ; apply IHΓ0.\n  2: simpl ; apply InT_In ; apply InT_map_iff ; exists (Imp (Box A) B, S (length Γ0)) ;\n  split ; simpl ; try reflexivity ; apply In_InT_pair ; apply IHΓ0.\n  destruct a1.\n  1-5: simpl ; apply InT_In ; apply InT_map_iff ; exists (Imp (Box A) B, S (length Γ0)) ;\n  split ; simpl ; try reflexivity ; apply In_InT_pair ; apply IHΓ0.\n  simpl. right. apply InT_In. apply InT_map_iff. exists (Imp (Box A) B, S (length Γ0)).\n  split. simpl. reflexivity. apply In_InT_pair. apply IHΓ0.\nQed.\n\nLemma BoxImpL_help01 : forall prems s l, InT prems (prems_BoxImp_L l s) ->\n                  (existsT2 n prem1 prem2 A B Γ0 Γ1 C,\n                        (prems = [prem1; prem2]) *\n                        (In ((Imp (Box A) B), S n) l) *\n                        (prem1 = (XBoxed_list (top_boxes (fst s)) ++ [Box A], A)) *\n                        (prem2 = (Γ0 ++ B :: Γ1, C)) *\n                        (C = snd s) *\n                        (Γ0 = (fst (nth_split n (remove_nth (S n) (Imp (Box A) B) (fst s))))) *\n                        (Γ1 = (snd (nth_split n (remove_nth (S n) (Imp (Box A) B) (fst s)))))).\nProof.\nintros prems s. destruct s. induction l0 ; intros.\n- simpl in H. inversion H.\n- simpl (fst (l, m)). destruct a. destruct m0.\n  1-4: simpl in H ; destruct n ; pose (IHl0 H) ; repeat destruct s ; repeat destruct p ; exists x ; exists x0 ; exists x1 ;\n  exists x2 ; exists x3 ; exists x4 ; exists x5 ; exists x6 ; repeat split ; try auto ; apply in_cons ; assumption.\n  2: simpl in H ; destruct n ; pose (IHl0 H) ; repeat destruct s ; repeat destruct p ; exists x ; exists x0 ; exists x1 ;\n  exists x2 ; exists x3 ; exists x4 ; exists x5 ; exists x6 ; repeat split ; try auto ; apply in_cons ; assumption.\n  destruct m0_1.\n  1-5: simpl in H ; destruct n ; pose (IHl0 H) ; repeat destruct s ; repeat destruct p ; exists x ; exists x0 ; exists x1 ;\n  exists x2 ; exists x3 ; exists x4 ; exists x5 ; exists x6 ; repeat split ; try auto ; apply in_cons ; assumption.\n  destruct n.\n  + pose (IHl0 H). repeat destruct s. repeat destruct p. exists x. exists x0. exists x1.\n     exists x2. exists x3. exists x4. exists x5. exists x6. repeat split ; try auto. apply in_cons. assumption.\n  + inversion H.\n    { simpl in H1. simpl in H0. simpl (fst (l, m)) in IHl0. simpl (snd (l, m)) in IHl0.\n      exists n. exists (XBoxed_list (top_boxes l) ++ [Box m0_1], m0_1).\n      exists (fst\n        (nth_split n\n           match n with\n           | 0 => match l with\n                  | [] => []\n                  | B :: tl => if eq_dec_form (Box m0_1 → m0_2) B then tl else B :: tl\n                  end\n           | S _ => match l with\n                    | [] => []\n                    | B :: tl => B :: remove_nth n (Box m0_1 → m0_2) tl\n                    end\n           end) ++\n      m0_2\n      :: snd\n           (nth_split n\n              match n with\n              | 0 => match l with\n                     | [] => []\n                     | B :: tl => if eq_dec_form (Box m0_1 → m0_2) B then tl else B :: tl\n                     end\n              | S _ => match l with\n                       | [] => []\n                       | B :: tl => B :: remove_nth n (Box m0_1 → m0_2) tl\n                       end\n              end), m).\n      exists m0_1. exists m0_2.\n      exists (fst\n        (nth_split n\n           match n with\n           | 0 => match l with\n                  | [] => []\n                  | B :: tl => if eq_dec_form (Box m0_1 → m0_2) B then tl else B :: tl\n                  end\n           | S _ => match l with\n                    | [] => []\n                    | B :: tl => B :: remove_nth n (Box m0_1 → m0_2) tl\n                    end\n           end)).\n      exists (snd\n           (nth_split n\n              match n with\n              | 0 => match l with\n                     | [] => []\n                     | B :: tl => if eq_dec_form (Box m0_1 → m0_2) B then tl else B :: tl\n                     end\n              | S _ => match l with\n                       | [] => []\n                       | B :: tl => B :: remove_nth n (Box m0_1 → m0_2) tl\n                       end\n              end)). exists m. repeat split ; auto. apply in_eq. }\n    { pose (IHl0 H1). repeat destruct s. repeat destruct p. exists x. exists x0. exists x1.\n      exists x2. exists x3. exists x4. exists x5. exists x6. repeat split ; try auto. apply in_cons. assumption. }\nQed.\n\nLemma BoxImpL_help1 : forall prems s, InT prems (prems_BoxImp_L (pos_top_boximps (fst s)) s) -> BoxImpLRule prems s.\nProof.\nintros. pose (@BoxImpL_help01 _ _ _ H). repeat destruct s0. destruct s.\nrepeat destruct p. subst. simpl in i. simpl (fst (l, m)).\nsimpl (fst (l, m)) in H. simpl (snd (l, m)). simpl (snd (l, m)) in H.\napply In_pos_top_boximps_split_l in i.\ndestruct i. destruct s. repeat destruct p.\nsubst. rewrite <- e. rewrite <- e0. apply BoxImpLRule_I.\nrepeat rewrite top_boxes_distr_app. simpl. intro. intros.\nrewrite <- top_boxes_distr_app in H0. apply in_top_boxes in H0. destruct H0. repeat destruct s.\ndestruct p. subst. exists x ; auto.\nrepeat rewrite top_boxes_distr_app. simpl.\nrewrite <- top_boxes_distr_app. apply top_boxes_nobox_gen_ext.\nQed.\n\nLemma BoxImpL_help002 : forall Γ0 Γ1 l C A B,\n           InT [(XBoxed_list (top_boxes (Γ0 ++ Γ1)) ++ [Box A], A);(Γ0 ++ B :: Γ1, C)] (prems_BoxImp_L (((Box A) → B, S (length Γ0)) :: l) (Γ0 ++ (Box A) → B :: Γ1, C)).\nProof.\nintros. unfold prems_BoxImp_L.\nsimpl (fst (Γ0 ++ (Box A) → B :: Γ1, C)). simpl (snd (Γ0 ++ (Box A) → B :: Γ1, C)).\nrepeat rewrite effective_remove_nth. pose (nth_split_idL Γ0 Γ1).\nrewrite <- e. pose (nth_split_idR Γ0 Γ1). rewrite <- e0.\nrepeat rewrite top_boxes_distr_app. simpl.\napply InT_eq.\nQed.\n\nLemma BoxImpL_help02 : forall Γ0 Γ1 C A B l n,\n            BoxImpLRule [(XBoxed_list (top_boxes (Γ0 ++ Γ1)) ++ [Box A], A);(Γ0 ++ B :: Γ1, C)] (Γ0 ++ (Box A) → B :: Γ1, C) ->\n            (length Γ0 = n) ->\n            (In ((Box A) → B, S n) l) ->\n            InT [(XBoxed_list (top_boxes (Γ0 ++ Γ1)) ++ [Box A], A);(Γ0 ++ B :: Γ1, C)] (prems_BoxImp_L l (Γ0 ++ (Box A) → B :: Γ1, C)).\nProof.\ninduction l ; intros.\n- inversion H0.\n- destruct a. destruct m.\n  1-4: subst ; apply In_InT_pair in H0 ; inversion H0 ; subst ; inversion H1 ; subst ; apply InT_In in H1 ;\n    assert (J1: length Γ0 = length Γ0) ; try reflexivity ; pose (IHl _ X J1 H1) ; simpl ; destruct n0 ; assumption ; assumption.\n  2: subst ; apply In_InT_pair in H0 ; inversion H0 ; subst ; inversion H1 ; subst ; apply InT_In in H1 ;\n    assert (J1: length Γ0 = length Γ0) ; try reflexivity ; pose (IHl _ X J1 H1) ; simpl ; destruct n0 ; assumption ; assumption.\n  destruct m1.\n  1-5: subst ; apply In_InT_pair in H0 ; inversion H0 ; subst ; inversion H1 ; subst ; apply InT_In in H1 ;\n    assert (J1: length Γ0 = length Γ0) ; try reflexivity ; pose (IHl _ X J1 H1) ; simpl ; destruct n0 ; assumption ; assumption.\n  apply In_InT_pair in H0. inversion H0.\n    + subst. inversion H2. subst. apply BoxImpL_help002.\n    + subst. assert (J1: (length Γ0) = (length Γ0)). reflexivity. apply InT_In in H2.\n       pose (IHl (length Γ0) X J1 H2). simpl. destruct n0 ; auto. apply InT_cons ; auto.\nQed.\n\nLemma BoxImpL_help2 : forall prems s, BoxImpLRule prems s -> InT prems (prems_BoxImp_L (pos_top_boximps (fst s)) s).\nProof.\nintros. inversion X. subst. simpl. assert (BΓ = top_boxes (Γ0 ++ Γ1)). apply nobox_gen_ext_top_boxes_identity ; auto.\nrewrite H0 in X. rewrite  H0.\npose (@BoxImpL_help02 Γ0 Γ1 C A B (pos_top_boximps (Γ0 ++ (Box A) → B :: Γ1)) (length Γ0)).\napply i ; try assumption ; auto.\napply Good_pos_in_pos_top_boximps.\nQed.\n\nLemma finite_BoxImpL_premises_of_S : forall (s : (list (MPropF V)) * (MPropF V)), existsT2 listBoxImpLprems,\n              (forall prems, ((BoxImpLRule prems s) -> (InT prems listBoxImpLprems)) *\n                             ((InT prems listBoxImpLprems) -> (BoxImpLRule prems s))).\nProof.\nintros. destruct s.\nexists (prems_BoxImp_L (pos_top_boximps l) (l,m)).\nintros. split ; intro.\n- inversion X. subst.\n  pose (BoxImpL_help2 X). auto.\n- apply BoxImpL_help1. simpl. assumption.\nQed.\n\n\n\n\n\n(*------------------------------------------------------------------------------------------------------------------------------------------------------------------- *)\n\n\n\n\n\n(* GLR rule. *)\n\nDefinition prems_Box_R (s : (list (MPropF V)) * (MPropF V)) : list ((list (MPropF V)) * (MPropF V)) :=\nmatch snd s with\n  | Box A => [((XBoxed_list (top_boxes (fst s))) ++ [Box A], A)]\n  | _ => []\nend.\n\nLemma GLR_help1 : forall prem s, InT prem (prems_Box_R s) ->\n                                         GLRRule [prem] s.\nProof.\nintros. destruct s. unfold prems_Box_R in H. simpl in H. destruct m.\n1-6: inversion H. subst. 2: inversion H1. apply GLRRule_I.\n2: apply top_boxes_nobox_gen_ext. intro.\nintros. apply in_top_boxes in H0. destruct H0. repeat destruct s.\ndestruct p ; subst. exists x ; auto.\nQed.\n\nLemma nobox_gen_ext_id_top_boxes : forall Γ BΓ, is_Boxed_list BΓ -> nobox_gen_ext BΓ Γ -> BΓ = top_boxes Γ.\nProof.\ninduction Γ.\n- intros. simpl. inversion X ; auto.\n- intros. inversion X.\n  * subst. destruct a ; simpl. 1-5: exfalso.\n    + assert (In # v (# v :: l)). apply in_eq. pose (H _ H0). destruct e. inversion H1.\n    + assert (In (⊥ V) ((⊥ V) :: l)). apply in_eq. pose (H _ H0). destruct e. inversion H1.\n    + assert (In (a1 ∧ a2) ((a1 ∧ a2) :: l)). apply in_eq. pose (H _ H0). destruct e. inversion H1.\n    + assert (In (a1 ∨ a2) ((a1 ∨ a2) :: l)). apply in_eq. pose (H _ H0). destruct e. inversion H1.\n    + assert (In (a1 → a2) ((a1 → a2) :: l)). apply in_eq. pose (H _ H0). destruct e. inversion H1.\n    + assert (is_Boxed_list l). intro. intros. apply H. apply in_cons ; auto. pose (IHΓ _ H0 X0). rewrite e. auto.\n  * subst. destruct a. 1-5: simpl. 1-5: apply IHΓ ; auto. simpl. exfalso. apply H2. exists a. auto.\nQed.\n\nLemma GLR_help2 : forall prem s, GLRRule [prem] s ->\n                      InT prem (prems_Box_R s).\nProof.\nintros. inversion X. subst. simpl.\nunfold prems_Box_R. simpl. assert (BΓ = top_boxes Γ).\napply nobox_gen_ext_id_top_boxes ; auto. rewrite H. apply InT_eq.\nQed.\n\nLemma finite_GLR_premises_of_S : forall (s : (list (MPropF V)) * (MPropF V)), existsT2 listGLRprems,\n              (forall prems, ((GLRRule prems s) -> (InT prems listGLRprems)) *\n                             ((InT prems listGLRprems) -> (GLRRule prems s))).\nProof.\nintros. destruct s.\nexists (map (fun y => [y]) (prems_Box_R (l,m))).\nintros. split ; intro.\n- inversion X. subst. pose (GLR_help2 X). apply InT_map_iff. exists (XBoxed_list BΓ ++ [Box A], A) ; split ; auto.\n- apply InT_map_iff in H. destruct H. destruct p. subst. apply GLR_help1. simpl. assumption.\nQed.\n\n\n\n\n\n(*------------------------------------------------------------------------------------------------------------------------------------------------------------------- *)\n\n\n\n\n\n(* Initial rules. *)\n\nLemma finite_Id_premises_of_S : forall (s : (list (MPropF V)) * (MPropF V)), existsT2 listIdprems,\n              (forall prems, ((IdRule prems s) -> (InT prems listIdprems)) *\n                             ((InT prems listIdprems) -> (IdRule prems s))).\nProof.\nintros. destruct (dec_Id_rule s).\n- exists [[]]. intros. split ; intro.\n  * inversion H. subst. apply InT_eq.\n  * inversion H. subst. assumption. inversion H1.\n- exists []. intros. split ; intro.\n  * inversion H. subst. exfalso. apply f. assumption.\n  * inversion H.\nQed.\n\nLemma finite_BotL_premises_of_S : forall (s : (list (MPropF V)) * (MPropF V)), existsT2 listBotLprems,\n              (forall prems, ((BotLRule prems s) -> (InT prems listBotLprems)) *\n                             ((InT prems listBotLprems) -> (BotLRule prems s))).\nProof.\nintros. destruct (dec_BotL_rule s).\n- exists [[]]. intros. split ; intro.\n  * inversion H. subst. apply InT_eq.\n  * inversion H. subst. assumption. inversion H1.\n- exists []. intros. split ; intro.\n  * inversion H. subst. exfalso. apply f. assumption.\n  * inversion H.\nQed.\n\n\n\n\n\n(*------------------------------------------------------------------------------------------------------------------------------------------------------------------- *)\n\n\n\n\n\n(* Now that we have the list of all premises of a sequent via all rules, we can combine\n   them all to obtain the list of all potential premises via the PSGL4ip calculus. *)\n\nLemma finite_premises_of_S : forall (s : (list (MPropF V)) * (MPropF V)), existsT2 listprems,\n              (forall prems, ((PSGL4ip_rules prems s) -> (InT prems listprems)) *\n                             ((InT prems listprems) -> (PSGL4ip_rules prems s))).\nProof.\nintro s.\ndestruct (dec_PSGL4ip_rules s).\n- exists []. intros. split. intro. exfalso. apply f. exists prems. assumption.\n  intro. inversion H.\n- destruct (dec_init_rules s).\n  + exists [[]]. intros. split. intros. inversion X. 1-2: inversion H ; subst ; apply InT_eq.\n     1-13: exfalso ; subst ; firstorder. intro. inversion H. subst. destruct s1. apply PSId.\n      auto. apply PSBotL. auto. inversion H1.\n  +  pose (finite_Id_premises_of_S s). destruct s1.\n      pose (finite_BotL_premises_of_S s). destruct s1.\n      pose (finite_AndR_premises_of_S s). destruct s1.\n      pose (finite_AndL_premises_of_S s). destruct s1.\n      pose (finite_OrR1_premises_of_S s). destruct s1.\n      pose (finite_OrR2_premises_of_S s). destruct s1.\n      pose (finite_OrL_premises_of_S s). destruct s1.\n      pose (finite_ImpR_premises_of_S s). destruct s1.\n      pose (finite_AtomImpL1_premises_of_S s). destruct s1.\n      pose (finite_AtomImpL2_premises_of_S s). destruct s1.\n      pose (finite_AndImpL_premises_of_S s). destruct s1.\n      pose (finite_OrImpL_premises_of_S s). destruct s1.\n      pose (finite_ImpImpL_premises_of_S s). destruct s1.\n      pose (finite_BoxImpL_premises_of_S s). destruct s1.\n      pose (finite_GLR_premises_of_S s). destruct s1.\n      exists (x ++ x0 ++ x1 ++ x2 ++ x3 ++ x4 ++ x5 ++ x6 ++ x7 ++ x8 ++ x9 ++ x10 ++ x11 ++ x12 ++ x13).\n      intros. split.\n    * intros. inversion X ; subst. apply InT_or_app. left. apply p. auto.\n       apply InT_or_app ; right ; apply InT_or_app ; left. apply p0. auto.\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; left. apply p1. auto.\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; left. apply p2. auto.\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ;\n       apply InT_or_app ; left. apply p3. auto.\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ;\n       apply InT_or_app ; right ; apply InT_or_app ; left. apply p4. auto.\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ;\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; left. apply p5. auto.\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ;\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; left. apply p6. auto.\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ;\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ;\n       apply InT_or_app ; left. apply p7. auto.\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ;\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ;\n       apply InT_or_app ; right ; apply InT_or_app ; left. apply p8. auto.\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ;\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ;\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; left. apply p9. auto.\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ;\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ;\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; left. apply p10. auto.\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ;\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ;\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ;\n       apply InT_or_app ; left. apply p11. auto.\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ;\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ;\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ;\n       apply InT_or_app ; right ; apply InT_or_app ; left. apply p12. auto.\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ;\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ;\n       apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ; apply InT_or_app ; right ;\n       apply InT_or_app ; right ; apply InT_or_app ; right. apply p13. auto.\n    *  intros. apply InT_app_or in H. destruct H. exfalso. apply p in i. inversion i. subst. auto.\n       apply InT_app_or in i. destruct i. exfalso. apply p0 in i. inversion i. subst. auto.\n       apply InT_app_or in i. destruct i. apply p1 in i ; apply PSAndR ; auto.\n       apply InT_app_or in i. destruct i. apply p2 in i ; apply PSAndL ; auto.\n       apply InT_app_or in i. destruct i. apply p3 in i ; apply PSOrR1 ; auto.\n       apply InT_app_or in i. destruct i. apply p4 in i ; apply PSOrR2 ; auto.\n       apply InT_app_or in i. destruct i. apply p5 in i ; apply PSOrL ; auto.\n       apply InT_app_or in i. destruct i. apply p6 in i ; apply PSImpR ; auto.\n       apply InT_app_or in i. destruct i. apply p7 in i ; apply PSAtomImpL1 ; auto.\n       apply InT_app_or in i. destruct i. apply p8 in i ; apply PSAtomImpL2 ; auto.\n       apply InT_app_or in i. destruct i. apply p9 in i ; apply PSAndImpL ; auto.\n       apply InT_app_or in i. destruct i. apply p10 in i ; apply PSOrImpL ; auto.\n       apply InT_app_or in i. destruct i. apply p11 in i ; apply PSImpImpL ; auto.\n       apply InT_app_or in i. destruct i. apply p12 in i ; apply PSBoxImpL ; auto.\n       apply p13 in i ; apply PSGLR ; auto.\nQed.\n\n(* The next definitions \"flattens\" a list of lists of premises to a list of premises.*)\n\nDefinition list_of_premises (s : (list (MPropF V)) * (MPropF V)) : list ((list (MPropF V)) * (MPropF V)) :=\n         flatten_list (proj1_sigT2 (finite_premises_of_S s)).\n\nLemma InT_list_of_premises_exists_prems : forall s prem, InT prem (list_of_premises s) ->\n            existsT2 prems, (InT prem prems) * (PSGL4ip_rules prems s).\nProof.\nintros. unfold list_of_premises in H.\napply InT_flatten_list_InT_elem in H. destruct H. destruct p.\nexists x. split. auto.\ndestruct (finite_premises_of_S s). pose (p x). destruct p0. apply p0. assumption.\nQed.\n\nLemma exists_prems_InT_list_of_premises : forall s prem,\n            (existsT2 prems, (InT prem prems) * (PSGL4ip_rules prems s)) ->\n            InT prem (list_of_premises s).\nProof.\nintros. destruct X. destruct p. unfold list_of_premises. destruct (finite_premises_of_S s).\npose (p0 x). destruct p1. apply InT_trans_flatten_list with (bs:=x). assumption. simpl. apply i0.\nassumption.\nQed.\n\nLemma find_the_max_mhd : forall concl l\n      (Prem_mhd : forall prems : list ((list (MPropF V)) * (MPropF V)), PSGL4ip_rules prems concl ->\n                  forall prem : (list (MPropF V)) * (MPropF V), InT prem prems ->\n                  existsT2 Dprem : derrec PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True) prem,\n                  is_mhd Dprem)\n      (H1 : forall prem : (list (MPropF V)) * (MPropF V), InT prem l -> InT prem (list_of_premises concl))\n      (H2 : forall (prem : (list (MPropF V)) * (MPropF V)) (J : InT prem l), InT prem (proj1_sigT2\n            (InT_list_of_premises_exists_prems concl (H1 prem J))))\n      (H3 : forall (prem : (list (MPropF V)) * (MPropF V)) (J : InT prem l), PSGL4ip_rules (proj1_sigT2\n            (InT_list_of_premises_exists_prems concl (H1 prem J))) concl)\n      (NotNil: l <> nil),\n\nexistsT2 prem, existsT2 (J0: InT prem l), forall prem' (J1: InT prem' l),\n       (derrec_height (proj1_sigT2 (Prem_mhd\n        (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1 prem' J1)))\n        (H3 prem' J1)\n        prem'\n        (H2 prem' J1))))\n       <=\n       (derrec_height (proj1_sigT2 (Prem_mhd\n        (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1 prem J0)))\n        (H3 prem J0)\n        prem\n        (H2 prem J0)))).\nProof.\ninduction l ; intros.\n- exfalso. apply NotNil. reflexivity.\n- clear NotNil. destruct l.\n  * exists a. assert (InT a [a]). apply InT_eq. exists H. intros. inversion J1. subst.\n    destruct (Prem_mhd (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1 prem' H))) (H3 prem' H) prem' (H2 prem' H)).\n    destruct (Prem_mhd (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1 prem' J1))) (H3 prem' J1) prem' (H2 prem' J1)).\n    simpl. auto. inversion H4.\n  * assert (H1' : forall prem : (list (MPropF V)) * (MPropF V), InT prem (p :: l) -> InT prem (list_of_premises concl)).\n    { intros. apply H1. apply InT_cons. assumption. }\n    assert (Prem_mhd' : forall prems : list ((list (MPropF V)) * (MPropF V)), PSGL4ip_rules prems concl -> forall prem : (list (MPropF V)) * (MPropF V),\n                        InT prem prems -> existsT2 Dprem : derrec PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True)\n                        prem, is_mhd Dprem).\n    { intros. apply Prem_mhd with (prems:= prems) ; try assumption. }\n    assert (H2' : forall (prem : (list (MPropF V)) * (MPropF V)) (J : InT prem (p :: l)), InT prem (proj1_sigT2\n                  (InT_list_of_premises_exists_prems concl (H1' prem J)))).\n    { intros. assert (InT prem (a :: p :: l)). apply InT_cons. assumption. pose (H2 _ H).\n      destruct (InT_list_of_premises_exists_prems concl (H1' prem J)).\n      simpl. destruct p0. assumption. }\n    assert (H3' : forall (prem : (list (MPropF V)) * (MPropF V)) (J : InT prem (p :: l)), PSGL4ip_rules\n                (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1' prem J))) concl).\n    { intros. destruct (InT_list_of_premises_exists_prems concl (H1' prem J)). simpl. destruct p0.\n      assumption. }\n    assert (p :: l <> []). intro. inversion H.\n    pose (IHl Prem_mhd' H1' H2' H3' H). destruct s. destruct s.\n    (* I have a max in p :: l: so I simply need to compare it with a. *)\n    assert (J2: InT a (a :: p :: l)). apply InT_eq.\n    assert (J3: InT x (a :: p :: l)). apply InT_cons. assumption.\n    (* The next assert decides on le between mhd of a and mhd of x. *)\n    pose (dec_le\n      (derrec_height (proj1_sigT2 (Prem_mhd (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1 a J2)))\n      (H3 a J2) a (H2 a J2))))\n      (derrec_height\n       (proj1_sigT2\n          (Prem_mhd' (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1' x x0))) \n             (H3' x x0) x (H2' x x0))))).\n    destruct s.\n    + exists x. exists J3. intros. inversion J1. subst.\n      destruct (Prem_mhd (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1 prem' J1))) \n      (H3 prem' J1) prem' (H2 prem' J1)). simpl.\n      destruct (Prem_mhd (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1 prem' J2))) \n      (H3 prem' J2) prem' (H2 prem' J2)). simpl in l1. unfold is_mhd in i0.\n      pose (i0 x1).\n      destruct (Prem_mhd (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1 x J3))) (H3 x J3) x (H2 x J3)).\n      simpl.\n      destruct (Prem_mhd' (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1' x x0))) \n      (H3' x x0) x (H2' x x0)). simpl in l1.\n      unfold is_mhd in i1. pose (i1 x4). lia.\n      destruct (Prem_mhd' (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1' x x0)))\n      (H3' x x0) x (H2' x x0)). simpl in l0.\n      destruct (Prem_mhd (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1 x J3))) (H3 x J3) x (H2 x J3)).\n      simpl.\n      destruct (Prem_mhd (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1 prem' J1)))). simpl.\n      assert (derrec_height\n     (proj1_sigT2\n        (Prem_mhd' (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1' prem' H4)))\n           (H3' prem' H4) prem' (H2' prem' H4))) <= derrec_height x1).\n      apply (l0 prem' H4). subst.\n      unfold is_mhd in i0. pose (i0 x1).\n      destruct (Prem_mhd' (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1' prem' H4)))\n           (H3' prem' H4) prem' (H2' prem' H4)). simpl in H6. unfold is_mhd in i2. pose (i2 x3). lia.\n    + exists a. exists J2. intros. apply le_False_lt in f.\n      inversion J1.\n      { subst. destruct (Prem_mhd (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1 prem' J1))) \n        (H3 prem' J1) prem' (H2 prem' J1)). simpl.\n        destruct (Prem_mhd (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1 prem' J2))) \n        (H3 prem' J2) prem' (H2 prem' J2)).\n        simpl. unfold is_mhd in i0. pose (i0 x1). lia. }\n      { subst.\n        destruct (Prem_mhd (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1 a J2))) (H3 a J2) a (H2 a J2)).\n        simpl.\n        destruct (Prem_mhd (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1 prem' J1))) \n        (H3 prem' J1) prem' (H2 prem' J1)). simpl.\n        destruct (Prem_mhd' (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1' x x0))) \n             (H3' x x0) x (H2' x x0)). simpl in l0.\n        assert (derrec_height\n       (proj1_sigT2\n          (Prem_mhd' (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1' prem' H4)))\n             (H3' prem' H4) prem' (H2' prem' H4))) <= derrec_height x3). apply l0.\n       destruct (Prem_mhd' (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1' prem' H4)))\n             (H3' prem' H4) prem' (H2' prem' H4)). simpl in H0. simpl in f. unfold is_mhd in i2.\n       pose (i2 x2). lia. }\nQed.\n\nLemma term_IH_help : forall concl,\n     (existsT2 prems, (PSGL4ip_rules prems concl) * (prems <> [])) ->\n     (forall prems, PSGL4ip_rules prems concl -> (forall prem, InT prem prems -> (existsT2 Dprem, @is_mhd prem Dprem)))\n      ->\n     (existsT2 Maxprems Maxprem DMaxprem, (PSGL4ip_rules Maxprems concl) * (@is_mhd Maxprem DMaxprem) * (InT Maxprem Maxprems) *\n        (forall prems prem (Dprem : derrec (PSGL4ip_rules) (fun _ => True) prem), PSGL4ip_rules prems concl -> InT prem prems ->\n            derrec_height Dprem <= derrec_height DMaxprem)).\nProof.\nintros concl FAH Prem_mhd.\npose (list_of_premises concl).\nassert (H1: forall prem, InT prem l -> InT prem (list_of_premises concl)).\nintros. auto.\nassert (H2: forall prem (J: InT prem l), InT prem (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1 prem J)))).\nintros. destruct (InT_list_of_premises_exists_prems concl (H1 prem J)). destruct p. auto.\nassert (H3: forall prem (J: InT prem l),\nPSGL4ip_rules (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1 prem J))) concl).\nintros. destruct (InT_list_of_premises_exists_prems concl (H1 prem J)). destruct p. auto.\nassert (H4: forall prem (J: InT prem l), is_mhd (proj1_sigT2 (Prem_mhd\n        (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1 prem J)))\n        (H3 prem J)\n        prem\n        (H2 prem J)))).\nintros. intro. destruct (Prem_mhd (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1 prem J)))\n(H3 prem J) prem (H2 prem J)). auto.\nassert (l <> []). intro. destruct FAH. destruct p. destruct p.\n- inversion i. subst. auto.\n- inversion b. subst. auto.\n- inversion a. subst. pose (@exists_prems_InT_list_of_premises (Γ, A ∧ B) (Γ, A)).\n  assert (InT (Γ, A) (list_of_premises (Γ, A ∧ B))). apply i.\n  exists [(Γ, A);(Γ, B)]. split. apply InT_eq. apply PSAndR ; assumption.\n  assert (InT (Γ, A) l). auto. rewrite H in H5. inversion H5.\n- inversion a. subst. pose (@exists_prems_InT_list_of_premises (Γ0 ++ A ∧ B :: Γ1, C) (Γ0 ++ A :: B :: Γ1, C)).\n  assert (InT (Γ0 ++ A :: B :: Γ1, C) (list_of_premises (Γ0 ++ A ∧ B :: Γ1, C))). apply i.\n  exists [(Γ0 ++ A :: B :: Γ1, C)]. split. apply InT_eq. apply PSAndL ; assumption.\n  assert (InT (Γ0 ++ A :: B :: Γ1, C) l). auto. rewrite H in H5. inversion H5.\n- inversion o. subst. pose (@exists_prems_InT_list_of_premises (Γ, A ∨ B) (Γ, A)).\n  assert (InT (Γ, A) (list_of_premises (Γ, A ∨ B))). apply i.\n  exists [(Γ, A)]. split. apply InT_eq. apply PSOrR1 ; assumption.\n  assert (InT (Γ, A) l). auto. rewrite H in H5. inversion H5.\n- inversion o. subst. pose (@exists_prems_InT_list_of_premises (Γ, A ∨ B) (Γ, B)).\n  assert (InT (Γ, B) (list_of_premises (Γ, A ∨ B))). apply i.\n  exists [(Γ, B)]. split. apply InT_eq. apply PSOrR2 ; assumption.\n  assert (InT (Γ, B) l). auto. rewrite H in H5. inversion H5.\n- inversion o. subst. pose (@exists_prems_InT_list_of_premises (Γ0 ++ A ∨ B :: Γ1, C) (Γ0 ++ A :: Γ1, C)).\n  assert (InT (Γ0 ++ A :: Γ1, C) (list_of_premises (Γ0 ++ A ∨ B :: Γ1, C))). apply i.\n  exists [(Γ0 ++ A :: Γ1, C);(Γ0 ++ B :: Γ1, C)]. split. apply InT_eq. apply PSOrL ; assumption.\n  assert (InT (Γ0 ++ A :: Γ1, C) l). auto. rewrite H in H5. inversion H5.\n- inversion i. subst. pose (@exists_prems_InT_list_of_premises (Γ0 ++ Γ1, A → B) (Γ0 ++ A :: Γ1, B)).\n  assert (InT(Γ0 ++ A :: Γ1, B) (list_of_premises (Γ0 ++ Γ1, A → B))). apply i0.\n  exists [(Γ0 ++ A :: Γ1, B)]. split. apply InT_eq. apply PSImpR ; assumption.\n  assert (InT (Γ0 ++ A :: Γ1, B) l). auto. rewrite H in H5. inversion H5.\n- inversion a. subst. pose (@exists_prems_InT_list_of_premises (Γ0 ++ # P :: Γ1 ++ # P → A :: Γ2, C) (Γ0 ++ # P :: Γ1 ++ A :: Γ2, C)).\n  assert (InT (Γ0 ++ # P :: Γ1 ++ A :: Γ2, C) (list_of_premises (Γ0 ++ # P :: Γ1 ++ # P → A :: Γ2, C))). apply i.\n  exists [(Γ0 ++ # P :: Γ1 ++ A :: Γ2, C)]. split. apply InT_eq. apply PSAtomImpL1 ; assumption.\n  assert (InT (Γ0 ++ # P :: Γ1 ++ A :: Γ2, C) l). auto. rewrite H in H5. inversion H5.\n- inversion a. subst. pose (@exists_prems_InT_list_of_premises (Γ0 ++ # P → A :: Γ1 ++ # P :: Γ2, C) (Γ0 ++ A :: Γ1 ++ # P :: Γ2, C)).\n  assert (InT (Γ0 ++ A :: Γ1 ++ # P :: Γ2, C) (list_of_premises (Γ0 ++ # P → A :: Γ1 ++ # P :: Γ2, C))). apply i.\n  exists [(Γ0 ++ A :: Γ1 ++ # P :: Γ2, C)]. split. apply InT_eq. apply PSAtomImpL2 ; assumption.\n  assert (InT (Γ0 ++  A :: Γ1 ++ # P :: Γ2, C) l). auto. rewrite H in H5. inversion H5.\n- inversion a. subst. pose (@exists_prems_InT_list_of_premises (Γ0 ++ (A ∧ B) → C :: Γ1, D) (Γ0 ++ A → B → C :: Γ1, D)).\n  assert (InT (Γ0 ++ A → B → C :: Γ1, D) (list_of_premises (Γ0 ++ (A ∧ B) → C :: Γ1, D))). apply i.\n  exists [(Γ0 ++ A → B → C :: Γ1, D)]. split. apply InT_eq. apply PSAndImpL ; assumption.\n  assert (InT(Γ0 ++ A → B → C :: Γ1, D) l). auto. rewrite H in H5. inversion H5.\n- inversion o. subst. pose (@exists_prems_InT_list_of_premises (Γ0 ++ (A ∨ B) → C :: Γ1 ++ Γ2, D) (Γ0 ++ A → C :: Γ1 ++ B → C :: Γ2, D)).\n  assert (InT (Γ0 ++ A → C :: Γ1 ++ B → C :: Γ2, D) (list_of_premises (Γ0 ++ (A ∨ B) → C :: Γ1 ++ Γ2, D))). apply i.\n  exists [(Γ0 ++ A → C :: Γ1 ++ B → C :: Γ2, D)]. split. apply InT_eq. apply PSOrImpL ; assumption.\n  assert (InT (Γ0 ++ A → C :: Γ1 ++ B → C :: Γ2, D) l). auto. rewrite H in H5. inversion H5.\n- inversion i. subst. pose (@exists_prems_InT_list_of_premises (Γ0 ++ (A → B) → C :: Γ1, D) (Γ0 ++ B → C :: Γ1, A → B)).\n  assert (InT (Γ0 ++ B → C :: Γ1, A → B) (list_of_premises (Γ0 ++ (A → B) → C :: Γ1, D))). apply i0.\n  exists [(Γ0 ++ B → C :: Γ1, A → B); (Γ0 ++ C :: Γ1, D)]. split. apply InT_eq. apply PSImpImpL ; assumption.\n  assert (InT (Γ0 ++ B → C :: Γ1, A → B) l). auto. rewrite H in H5. inversion H5.\n- inversion b. subst. pose (@exists_prems_InT_list_of_premises (Γ0 ++ Box A → B :: Γ1, C) (XBoxed_list BΓ ++ [Box A], A)).\n  assert (InT (XBoxed_list BΓ ++ [Box A], A) (list_of_premises (Γ0 ++ Box A → B :: Γ1, C))). apply i.\n  exists [(XBoxed_list BΓ ++ [Box A], A); (Γ0 ++ B :: Γ1, C)]. split. apply InT_eq. apply PSBoxImpL ; assumption.\n  assert (InT (XBoxed_list BΓ ++ [Box A], A) l). auto. rewrite H in H6. inversion H6.\n- inversion g. subst. pose (@exists_prems_InT_list_of_premises (Γ, Box A) (XBoxed_list BΓ ++ [Box A], A)).\n  assert (InT (XBoxed_list BΓ ++ [Box A], A) (list_of_premises (Γ, Box A))). apply i.\n  exists [(XBoxed_list BΓ ++ [Box A], A)]. split. apply InT_eq. apply PSGLR ; assumption.\n  assert (InT (XBoxed_list BΓ ++ [Box A], A) l). auto. rewrite H in H6. inversion H6.\n- pose (find_the_max_mhd Prem_mhd H1 H2 H3 H).\n  destruct s. destruct s. exists (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1 x x0))).\n  exists x. exists (proj1_sigT2 (Prem_mhd (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1 x x0)))\n  (H3 x x0) x (H2 x x0))). repeat split ; try apply H3 ; try apply H4 ; try apply H2.\n  intros prems prem Dprem RA IsPrem.\n  assert (J3: InT prem l).\n  pose (@exists_prems_InT_list_of_premises concl prem). apply i. exists prems. auto.\n  assert (E1: derrec_height Dprem <= derrec_height (proj1_sigT2 (Prem_mhd (proj1_sigT2\n  (InT_list_of_premises_exists_prems concl (H1 prem J3))) (H3 prem J3) prem (H2 prem J3)))).\n  destruct (Prem_mhd (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1 prem J3)))\n  (H3 prem J3) prem (H2 prem J3)). auto.\n  assert (E2: derrec_height (proj1_sigT2 (Prem_mhd (proj1_sigT2 (InT_list_of_premises_exists_prems concl\n  (H1 prem J3))) (H3 prem J3) prem (H2 prem J3))) <=\n  derrec_height (proj1_sigT2 (Prem_mhd (proj1_sigT2 (InT_list_of_premises_exists_prems concl (H1 x x0)))\n  (H3 x x0) x (H2 x x0)))). apply l0. lia.\nQed.\n\nLemma in_drs_concl_in_allT W rules prems ps (cn : W) (drs : dersrec rules prems ps)\n  (dtn : derrec rules prems cn) : in_dersrec dtn drs -> InT cn ps.\nProof.\nintro ind. induction ind. apply InT_eq.\napply InT_cons. assumption.\nQed.\n\nLemma dec_non_nil_prems: forall (concl : ((list (MPropF V)) * (MPropF V))), ((existsT2 prems, (PSGL4ip_rules prems concl) * (prems <> []))) +\n                                       ((existsT2 prems, (PSGL4ip_rules prems concl) * (prems <> [])) -> False).\nProof.\nintros. destruct (dec_init_rules concl).\n- right. intros. destruct X. destruct p. inversion p ; subst ; auto.\n  1-2: inversion H ; auto. 1-13: destruct s ; auto.\n- destruct (dec_PSGL4ip_rules concl).\n  + right. intros. apply f0. destruct X. exists x. destruct p ; auto.\n  + left. destruct s. exists x. inversion p. 1-2: inversion H ; subst ; auto.\n     1-11: subst ; inversion H1 ; subst ; split ; auto ; intro ; inversion H2.\n     1-2: subst ; inversion X ; subst ; split ; auto ; intro ; inversion H2.\nQed.\n\n(* The next theorem claims that every sequent s has a derivation DMax of maximal height. *)\n\nTheorem PSGL4ip_termin_base : forall s, existsT2 (DMax : derrec (PSGL4ip_rules) (fun _ => True) s), (@is_mhd s DMax).\nProof.\n(* Setting up the strong inductions on each. *)\npose (less_than3_strong_inductionT\n    (fun x => (existsT2 DMax : derrec PSGL4ip_rules\n    (fun _ : (list (MPropF V)) * (MPropF V) => True) x, is_mhd DMax))).\napply s. clear s. intros s IH.\n\n(* Now we can do the pen and paper proof. *)\nassert (dersrecnil: dersrec (PSGL4ip_rules) (fun _ => True) nil).\napply dersrec_nil.\npose (dec_PSGL4ip_rules s). destruct s0.\n- assert (forall ps : list ((list (MPropF V)) * (MPropF V)), PSGL4ip_rules ps s -> False).\n  intros. apply f. exists ps. assumption.\n  pose (dpI PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True) s I).\n  exists d. unfold is_mhd. intros. simpl. destruct D1. simpl. auto. exfalso. apply f. exists ps. auto.\n- assert (forall prems, PSGL4ip_rules prems s -> (forall prem, InT prem prems ->\n  (existsT2 Dprem, @is_mhd prem Dprem))).\n  { intros. pose (PSGL4ip_less_than3 X H). apply IH. auto. }\n    destruct (dec_non_nil_prems s).\n    + pose (@term_IH_help s s1 X). repeat destruct s2. destruct p. destruct p. destruct p. inversion p.\n      * inversion H. subst. inversion i.\n      * inversion H. subst. inversion i.\n      * inversion H1. subst. inversion i.\n        { subst. pose (dpI PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True)(Γ, B) I).\n           pose (dlCons d dersrecnil). pose (dlCons x1 d0).\n           pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ, A); (Γ, B)] (Γ, A ∧ B) p d1).\n           exists d2. unfold is_mhd. intros. simpl. rewrite dersrec_height_nil with (ds:=dersrecnil) ; auto.\n           destruct D1.\n           { simpl. lia. }\n           { simpl.\n             assert (forall p (d : derrec PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True) p),\n             in_dersrec d d3 -> derrec_height d <= (derrec_height x1)). intros.\n             pose (in_drs_concl_in_allT X0). subst. pose (l ps p1 d4 p0 i1). assumption.\n             pose (dersrec_height_le H2). lia. } }\n        {  subst. inversion H3 ; subst. 2: inversion H4. pose (dpI PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True) (Γ, A) I).\n           pose (dlCons x1 dersrecnil). pose (dlCons d d0).\n           pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ, A); (Γ, B)] (Γ, A ∧ B) p d1).\n           exists d2. unfold is_mhd. intros. simpl. rewrite dersrec_height_nil with (ds:=dersrecnil) ; auto.\n           destruct D1.\n           { simpl. lia. }\n           { simpl.\n             assert (forall p (d : derrec PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True) p),\n             in_dersrec d d3 -> derrec_height d <= (derrec_height x1)). intros.\n             pose (in_drs_concl_in_allT X0). subst. pose (l ps p1 d4 p0 i1). assumption.\n             pose (dersrec_height_le H2). lia. } }\n      * inversion H1. subst. inversion i. 2: inversion H3. subst.\n        subst. pose (dlCons x1 dersrecnil).\n        pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ0 ++ A :: B :: Γ1, C)] (Γ0 ++ A ∧ B :: Γ1, C) p d).\n        exists d0. unfold is_mhd. intros. simpl. rewrite dersrec_height_nil with (ds:=dersrecnil) ; auto.\n        destruct D1.\n        { simpl. lia. }\n        { simpl.\n          assert (forall p (d : derrec PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True) p),\n          in_dersrec d d1 -> derrec_height d <= (derrec_height x1)). intros.\n          pose (in_drs_concl_in_allT X0). subst. pose (l ps p1 d2 p0 i1). assumption.\n          pose (dersrec_height_le H2). lia. }\n      * inversion H1. subst. inversion i. 2: inversion H3. subst.\n        subst. pose (dlCons x1 dersrecnil).\n        pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ, A)] (Γ, A ∨ B) p d).\n        exists d0. unfold is_mhd. intros. simpl. rewrite dersrec_height_nil with (ds:=dersrecnil) ; auto.\n        destruct D1.\n        { simpl. lia. }\n        { simpl.\n          assert (forall p (d : derrec PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True) p),\n          in_dersrec d d1 -> derrec_height d <= (derrec_height x1)). intros.\n          pose (in_drs_concl_in_allT X0). subst. pose (l ps p1 d2 p0 i1). assumption.\n          pose (dersrec_height_le H2). lia. }\n      * inversion H1. subst. inversion i. 2: inversion H3. subst.\n        subst. pose (dlCons x1 dersrecnil).\n        pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ, B)] (Γ, A ∨ B) p d).\n        exists d0. unfold is_mhd. intros. simpl. rewrite dersrec_height_nil with (ds:=dersrecnil) ; auto.\n        destruct D1.\n        { simpl. lia. }\n        { simpl.\n          assert (forall p (d : derrec PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True) p),\n          in_dersrec d d1 -> derrec_height d <= (derrec_height x1)). intros.\n          pose (in_drs_concl_in_allT X0). subst. pose (l ps p1 d2 p0 i1). assumption.\n          pose (dersrec_height_le H2). lia. }\n      * inversion H1. subst. inversion i.\n        { subst. pose (dpI PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True) (Γ0 ++ B :: Γ1, C) I).\n           pose (dlCons d dersrecnil). pose (dlCons x1 d0).\n           pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ0 ++ A :: Γ1, C); (Γ0 ++ B :: Γ1, C)] (Γ0 ++ A ∨ B :: Γ1, C) p d1).\n           exists d2. unfold is_mhd. intros. simpl. rewrite dersrec_height_nil with (ds:=dersrecnil) ; auto.\n           destruct D1.\n           { simpl. lia. }\n           { simpl.\n             assert (forall p (d : derrec PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True) p),\n             in_dersrec d d3 -> derrec_height d <= (derrec_height x1)). intros.\n             pose (in_drs_concl_in_allT X0). subst. pose (l ps p1 d4 p0 i1). assumption.\n             pose (dersrec_height_le H2). lia. } }\n        { subst. inversion H3 ; subst. 2: inversion H4. pose (dpI PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True) (Γ0 ++ A :: Γ1, C) I). \n           pose (dlCons x1 dersrecnil). pose (dlCons d d0).\n           pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ0 ++ A :: Γ1, C); (Γ0 ++ B :: Γ1, C)] (Γ0 ++ A ∨ B :: Γ1, C) p d1).\n           exists d2. unfold is_mhd. intros. simpl. rewrite dersrec_height_nil with (ds:=dersrecnil) ; auto.\n           destruct D1.\n           { simpl. lia. }\n           { simpl.\n             assert (forall p (d : derrec PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True) p),\n             in_dersrec d d3 -> derrec_height d <= (derrec_height x1)). intros.\n             pose (in_drs_concl_in_allT X0). subst. pose (l ps p1 d4 p0 i1). assumption.\n             pose (dersrec_height_le H2). lia. } }\n      * inversion H1. subst. inversion i. 2: inversion H3. subst.\n        subst. pose (dlCons x1 dersrecnil).\n        pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ0 ++ A :: Γ1, B)] (Γ0 ++ Γ1, A → B) p d).\n        exists d0. unfold is_mhd. intros. simpl. rewrite dersrec_height_nil with (ds:=dersrecnil) ; auto.\n        destruct D1.\n        { simpl. lia. }\n        { simpl.\n          assert (forall p (d : derrec PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True) p),\n          in_dersrec d d1 -> derrec_height d <= (derrec_height x1)). intros.\n          pose (in_drs_concl_in_allT X0). subst. pose (l ps p1 d2 p0 i1). assumption.\n          pose (dersrec_height_le H2). lia. }\n      * inversion H1. subst. inversion i. 2: inversion H3. subst.\n        subst. pose (dlCons x1 dersrecnil).\n        pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ0 ++ # P :: Γ1 ++ A :: Γ2, C)] (Γ0 ++ # P :: Γ1 ++ # P → A :: Γ2, C) p d).\n        exists d0. unfold is_mhd. intros. simpl. rewrite dersrec_height_nil with (ds:=dersrecnil) ; auto.\n        destruct D1.\n        { simpl. lia. }\n        { simpl.\n          assert (forall p (d : derrec PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True) p),\n          in_dersrec d d1 -> derrec_height d <= (derrec_height x1)). intros.\n          pose (in_drs_concl_in_allT X0). subst. pose (l ps p1 d2 p0 i1). assumption.\n          pose (dersrec_height_le H2). lia. }\n      * inversion H1. subst. inversion i. 2: inversion H3. subst.\n        subst. pose (dlCons x1 dersrecnil).\n        pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ0 ++ A :: Γ1 ++ # P :: Γ2, C)] (Γ0 ++ # P → A :: Γ1 ++ # P :: Γ2, C) p d).\n        exists d0. unfold is_mhd. intros. simpl. rewrite dersrec_height_nil with (ds:=dersrecnil) ; auto.\n        destruct D1.\n        { simpl. lia. }\n        { simpl.\n          assert (forall p (d : derrec PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True) p),\n          in_dersrec d d1 -> derrec_height d <= (derrec_height x1)). intros.\n          pose (in_drs_concl_in_allT X0). subst. pose (l ps p1 d2 p0 i1). assumption.\n          pose (dersrec_height_le H2). lia. }\n      * inversion H1. subst. inversion i. 2: inversion H3. subst.\n        subst. pose (dlCons x1 dersrecnil).\n        pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ0 ++ A → B → C :: Γ1, D)] (Γ0 ++ (A ∧ B) → C :: Γ1, D) p d).\n        exists d0. unfold is_mhd. intros. simpl. rewrite dersrec_height_nil with (ds:=dersrecnil) ; auto.\n        destruct D1.\n        { simpl. lia. }\n        { simpl.\n          assert (forall p (d : derrec PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True) p),\n          in_dersrec d d1 -> derrec_height d <= (derrec_height x1)). intros.\n          pose (in_drs_concl_in_allT X0). subst. pose (l ps p1 d2 p0 i1). assumption.\n          pose (dersrec_height_le H2). lia. }\n      * inversion H1. subst. inversion i. 2: inversion H3. subst. subst. pose (dlCons x1 dersrecnil).\n        pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ0 ++ A → C :: Γ1 ++ B → C :: Γ2, D)] (Γ0 ++ (A ∨ B) → C :: Γ1 ++ Γ2, D) p d).\n        exists d0. unfold is_mhd. intros. simpl. rewrite dersrec_height_nil with (ds:=dersrecnil) ; auto.\n        destruct D1.\n        { simpl. lia. }\n        { simpl.\n          assert (forall p (d : derrec PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True) p),\n          in_dersrec d d1 -> derrec_height d <= (derrec_height x1)). intros.\n          pose (in_drs_concl_in_allT X0). subst. pose (l ps p1 d2 p0 i1). assumption.\n          pose (dersrec_height_le H2). lia. }\n      * inversion H1. subst. inversion i.\n        { subst. pose (dpI PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True) (Γ0 ++ C :: Γ1, D) I). pose (dlCons d dersrecnil). pose (dlCons x1 d0).\n           pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ0 ++ B → C :: Γ1, A → B); (Γ0 ++ C :: Γ1, D)] (Γ0 ++ (A → B) → C :: Γ1, D) p d1).\n           exists d2. unfold is_mhd. intros. simpl. rewrite dersrec_height_nil with (ds:=dersrecnil) ; auto.\n           destruct D1.\n           { simpl. lia. }\n           { simpl.\n             assert (forall p (d : derrec PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True) p),\n             in_dersrec d d3 -> derrec_height d <= (derrec_height x1)). intros.\n             pose (in_drs_concl_in_allT X0). subst. pose (l ps p1 d4 p0 i1). assumption.\n             pose (dersrec_height_le H2). lia. } }\n        { subst. inversion H3 ; subst. 2: inversion H4. pose (dpI PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True) (Γ0 ++ B → C :: Γ1, A → B) I).\n           pose (dlCons x1 dersrecnil). pose (dlCons d d0).\n           pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ0 ++ B → C :: Γ1, A → B); (Γ0 ++ C :: Γ1, D)] (Γ0 ++ (A → B) → C :: Γ1, D) p d1).\n           exists d2. unfold is_mhd. intros. simpl. rewrite dersrec_height_nil with (ds:=dersrecnil) ; auto.\n           destruct D1.\n           { simpl. lia. }\n           { simpl.\n             assert (forall p (d : derrec PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True) p),\n             in_dersrec d d3 -> derrec_height d <= (derrec_height x1)). intros.\n             pose (in_drs_concl_in_allT X0). subst. pose (l ps p1 d4 p0 i1). assumption.\n             pose (dersrec_height_le H2). lia. } }\n      * inversion X0. subst. inversion i.\n        { subst. pose (dpI PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True) (Γ0 ++ B :: Γ1, C) I). pose (dlCons d dersrecnil). pose (dlCons x1 d0).\n           pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(XBoxed_list BΓ ++ [Box A], A); (Γ0 ++ B :: Γ1, C)] (Γ0 ++ Box A → B :: Γ1, C) p d1).\n           exists d2. unfold is_mhd. intros. simpl. rewrite dersrec_height_nil with (ds:=dersrecnil) ; auto.\n           destruct D1.\n           { simpl. lia. }\n           { simpl.\n             assert (forall p (d : derrec PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True) p),\n             in_dersrec d d3 -> derrec_height d <= (derrec_height x1)). intros.\n             pose (in_drs_concl_in_allT X2). subst. pose (l ps p1 d4 p0 i1). assumption.\n             pose (dersrec_height_le H1). lia. } }\n        { subst. inversion H2 ; subst. 2: inversion H4. pose (dpI PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True) (XBoxed_list BΓ ++ [Box A], A) I).\n           pose (dlCons x1 dersrecnil). pose (dlCons d d0).\n           pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(XBoxed_list BΓ ++ [Box A], A); (Γ0 ++ B :: Γ1, C)] (Γ0 ++ Box A → B :: Γ1, C) p d1).\n           exists d2. unfold is_mhd. intros. simpl. rewrite dersrec_height_nil with (ds:=dersrecnil) ; auto.\n           destruct D1.\n           { simpl. lia. }\n           { simpl.\n             assert (forall p (d : derrec PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True) p),\n             in_dersrec d d3 -> derrec_height d <= (derrec_height x1)). intros.\n             pose (in_drs_concl_in_allT X2). subst. pose (l ps p1 d4 p0 i1). assumption.\n             pose (dersrec_height_le H1). lia. } }\n      * inversion X0. subst. inversion i. 2: inversion H2. subst. pose (dlCons x1 dersrecnil).\n        pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(XBoxed_list BΓ ++ [Box A], A)] (Γ, Box A) p d).\n        exists d0. unfold is_mhd. intros. simpl. rewrite dersrec_height_nil with (ds:=dersrecnil) ; auto.\n        destruct D1.\n        { simpl. lia. }\n        { simpl.\n          assert (forall p (d : derrec PSGL4ip_rules (fun _ : (list (MPropF V)) * (MPropF V) => True) p),\n          in_dersrec d d1 -> derrec_height d <= (derrec_height x1)). intros.\n          pose (in_drs_concl_in_allT X2). subst. pose (l ps p1 d2 p0 i1). assumption.\n          pose (dersrec_height_le H1). lia. }\n    + destruct s0. inversion p. 3-13: exfalso ; apply f ; exists ps ; split ; inversion H1 ; subst ; auto ; intro ; inversion H2.\n       3-4: exfalso ; apply f ; exists ps ; split ; inversion X0 ; subst ; auto ; intro ; inversion H1.\n      * inversion H. subst. pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [] (Γ0 ++ A :: Γ1, A) p dersrecnil).\n        exists d. unfold is_mhd. intros. simpl. rewrite dersrec_height_nil with (ds:=dersrecnil) ; auto.\n        destruct D1.\n        { simpl. lia. }\n        { simpl. destruct p0. 3-15: exfalso ; apply f ; exists ps ; split.\n          - inversion i. subst. rewrite dersrec_height_nil with (ds:=d0) ; auto.\n          - inversion b. subst. rewrite dersrec_height_nil with (ds:=d0) ; auto.\n          - apply PSAndR ; auto.\n          - intro ; subst ; inversion a.\n          - apply PSAndL ; auto.\n          - intro ; subst ; inversion a.\n          - apply PSOrR1 ; auto.\n          - intro ; subst ; inversion o.\n          - apply PSOrR2 ; auto.\n          - intro ; subst ; inversion o.\n          - apply PSOrL ; auto.\n          - intro ; subst ; inversion o.\n          - apply PSImpR ; auto.\n          - intro ; subst ; inversion i.\n          - apply PSAtomImpL1 ; auto.\n          - intro ; subst ; inversion a.\n          - apply PSAtomImpL2 ; auto.\n          - intro ; subst ; inversion a.\n          - apply PSAndImpL ; auto.\n          - intro ; subst ; inversion a.\n          - apply PSOrImpL ; auto.\n          - intro ; subst ; inversion o.\n          - apply PSImpImpL ; auto.\n          - intro ; subst ; inversion i.\n          - apply PSBoxImpL ; auto.\n          - intro ; subst ; inversion b.\n          - apply PSGLR ; auto.\n          - intro ; subst ; inversion g. }\n      * inversion H. subst. pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [] (Γ0 ++ ⊥ V :: Γ1, A) p dersrecnil).\n        exists d. unfold is_mhd. intros. simpl. rewrite dersrec_height_nil with (ds:=dersrecnil) ; auto.\n        destruct D1.\n        { simpl. lia. }\n        { simpl. destruct p0. 3-15: exfalso ; apply f ; exists ps ; split.\n          - inversion i. subst. rewrite dersrec_height_nil with (ds:=d0) ; auto.\n          - inversion b. subst. rewrite dersrec_height_nil with (ds:=d0) ; auto.\n          - apply PSAndR ; auto.\n          - intro ; subst ; inversion a.\n          - apply PSAndL ; auto.\n          - intro ; subst ; inversion a.\n          - apply PSOrR1 ; auto.\n          - intro ; subst ; inversion o.\n          - apply PSOrR2 ; auto.\n          - intro ; subst ; inversion o.\n          - apply PSOrL ; auto.\n          - intro ; subst ; inversion o.\n          - apply PSImpR ; auto.\n          - intro ; subst ; inversion i.\n          - apply PSAtomImpL1 ; auto.\n          - intro ; subst ; inversion a.\n          - apply PSAtomImpL2 ; auto.\n          - intro ; subst ; inversion a.\n          - apply PSAndImpL ; auto.\n          - intro ; subst ; inversion a.\n          - apply PSOrImpL ; auto.\n          - intro ; subst ; inversion o.\n          - apply PSImpImpL ; auto.\n          - intro ; subst ; inversion i.\n          - apply PSBoxImpL ; auto.\n          - intro ; subst ; inversion b.\n          - apply PSGLR ; auto.\n          - intro ; subst ; inversion g. }\nQed.\n\nDefinition PSGL4ip_drv s := derrec PSGL4ip_rules (fun _ => True) s.\n\nTheorem PSGL4ip_termin : forall s, existsT2 (DMax : PSGL4ip_drv s), (@is_mhd s DMax).\nProof.\nintro s. pose (@PSGL4ip_termin_base s). apply s0 ; reflexivity.\nQed.\n\nTheorem PSGL4ip_termin1 : forall (s : (list (MPropF V)) * (MPropF V)), exists (DMax : derrec PSGL4ip_rules (fun _ => True) s), (is_mhd DMax).\nProof.\nintro s.\npose (PSGL4ip_termin_base s).\ndestruct s0. exists x. assumption.\nQed.\n\nTheorem PSGL4ip_termin2 : forall s, exists (DMax : derrec (PSGL4ip_rules) (fun _ => True) s), (is_mhd DMax).\nProof.\nintro s. pose (@PSGL4ip_termin_base s). destruct s0. exists x. assumption.\nQed.\n\nTheorem PSGL4ip_termin3 : forall (s : (list (MPropF V)) * (MPropF V)), existsT2 (DMax : derrec PSGL4ip_rules (fun _ => True) s), (is_mhd DMax).\nProof.\nintro s. pose (@PSGL4ip_termin_base s). apply s0 ; reflexivity.\nQed.\n\n(* Now we can prove that the maximal height of derivations (mhd) for sequents\n   decreases upwards in the applicability of the proofs. In other words, if a sequent s is the\n   conclusion of an instance of a rule R of PSGL4ip with premises in ps, then for any element s0 of\n   ps we have that (mhd s0) < (mhd s).\n\n   To do so we first define mhd.*)\n\nDefinition mhd (s: (list (MPropF V)) * (MPropF V)) : nat := derrec_height (proj1_sigT2 (@PSGL4ip_termin3 s)).\n\nLemma PSGL4ip_termin_der_is_mhd : forall s, (@is_mhd s (proj1_sigT2 (@PSGL4ip_termin3 s))).\nProof.\nintro s. destruct PSGL4ip_termin3. auto.\nQed.\n\nTheorem RA_mhd_decreases : forall prems concl, (PSGL4ip_rules prems concl) ->\n                             (forall prem, (In prem prems) -> (mhd prem) < (mhd concl)).\nProof.\nassert (dersrecnil: dersrec (PSGL4ip_rules) (fun _ => True) nil).\napply dersrec_nil.\n\nintros. inversion X.\n- inversion H0. subst. inversion H.\n- inversion H0. subst. inversion H.\n- inversion H2. subst. inversion H.\n  * subst. apply le_False_lt. intro.\n    pose (proj1_sigT2 (PSGL4ip_termin3 (Γ, A ∧ B))).\n    pose (proj1_sigT2 (PSGL4ip_termin3 (Γ, A))).\n    pose (proj1_sigT2 (PSGL4ip_termin3 (Γ, B))).\n    pose (dlCons d1 dersrecnil). pose (dlCons d0 d2).\n    pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ, A); (Γ, B)] (Γ, A ∧ B) X d3).\n    assert (E1: derrec_height d0 = mhd (Γ, A)).\n    unfold mhd. auto.\n    assert (E2: derrec_height d = mhd (Γ, A ∧ B)).\n    unfold mhd. auto.\n    assert (E3: derrec_height d1 = mhd (Γ, B)).\n    unfold mhd. auto.\n    assert (@is_mhd (Γ, A ∧ B) d). apply PSGL4ip_termin_der_is_mhd.\n    unfold is_mhd in H2. pose (H4 d4). simpl in l. rewrite dersrec_height_nil in l. rewrite Max.max_0_r in l.\n    lia. reflexivity.\n  * inversion H3. 2: inversion H4. subst. apply le_False_lt. intro.\n    pose (proj1_sigT2 (PSGL4ip_termin3 (Γ, A ∧ B))).\n    pose (proj1_sigT2 (PSGL4ip_termin3 (Γ, A))).\n    pose (proj1_sigT2 (PSGL4ip_termin3 (Γ, B))).\n    pose (dlCons d1 dersrecnil). pose (dlCons d0 d2).\n    pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ, A); (Γ, B)] (Γ, A ∧ B) X d3).\n    assert (E1: derrec_height d0 = mhd (Γ, A)).\n    unfold mhd. auto.\n    assert (E2: derrec_height d = mhd (Γ, A ∧ B)).\n    unfold mhd. auto.\n    assert (E3: derrec_height d1 = mhd (Γ, B)).\n    unfold mhd. auto.\n    assert (@is_mhd (Γ, A ∧ B) d). apply PSGL4ip_termin_der_is_mhd.\n    unfold is_mhd in H2. pose (H5 d4). simpl in l. rewrite dersrec_height_nil in l. rewrite Max.max_0_r in l.\n    lia. reflexivity.\n- inversion H2. subst. inversion H. 2 : inversion H3.\n  subst. apply le_False_lt. intro.\n  pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ A ∧ B :: Γ1, C))).\n  pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ A :: B :: Γ1, C))).\n  pose (dlCons d0 dersrecnil).\n  pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ0 ++ A :: B :: Γ1, C)] (Γ0 ++ A ∧ B :: Γ1, C) X d1).\n  assert (E1: derrec_height d = mhd (Γ0 ++ A ∧ B :: Γ1, C)).\n  unfold mhd. auto.\n  assert (E2: derrec_height d0 = mhd (Γ0 ++ A :: B :: Γ1, C)).\n  unfold mhd. auto.\n  assert (@is_mhd (Γ0 ++ A ∧ B :: Γ1, C) d). apply PSGL4ip_termin_der_is_mhd.\n  unfold is_mhd in H2. pose (H4 d2). simpl in l. rewrite dersrec_height_nil in l ; auto. rewrite Max.max_0_r in l.\n  lia.\n- inversion H2. subst. inversion H. 2 : inversion H3.\n  subst. apply le_False_lt. intro.\n  pose (proj1_sigT2 (PSGL4ip_termin3 (Γ, A ∨ B))).\n  pose (proj1_sigT2 (PSGL4ip_termin3 (Γ, A))).\n  pose (dlCons d0 dersrecnil).\n  pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ, A)] (Γ, A ∨ B) X d1).\n  assert (E1: derrec_height d = mhd (Γ, A ∨ B)).\n  unfold mhd. auto.\n  assert (E2: derrec_height d0 = mhd (Γ, A)).\n  unfold mhd. auto.\n  assert (@is_mhd (Γ, A ∨ B) d). apply PSGL4ip_termin_der_is_mhd.\n  unfold is_mhd in H2. pose (H4 d2). simpl in l. rewrite dersrec_height_nil in l ; auto. rewrite Max.max_0_r in l.\n  lia.\n- inversion H2. subst. inversion H. 2 : inversion H3.\n  subst. apply le_False_lt. intro.\n  pose (proj1_sigT2 (PSGL4ip_termin3 (Γ, A ∨ B))).\n  pose (proj1_sigT2 (PSGL4ip_termin3 (Γ, B))).\n  pose (dlCons d0 dersrecnil).\n  pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ, B)] (Γ, A ∨ B) X d1).\n  assert (E1: derrec_height d = mhd (Γ, A ∨ B)).\n  unfold mhd. auto.\n  assert (E2: derrec_height d0 = mhd (Γ, B)).\n  unfold mhd. auto.\n  assert (@is_mhd (Γ, A ∨ B) d). apply PSGL4ip_termin_der_is_mhd.\n  unfold is_mhd in H2. pose (H4 d2). simpl in l. rewrite dersrec_height_nil in l ; auto. rewrite Max.max_0_r in l.\n  lia.\n- inversion H2. subst. inversion H.\n  * subst. apply le_False_lt. intro.\n    pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ A ∨ B :: Γ1, C))).\n    pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ A :: Γ1, C))).\n    pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ B :: Γ1, C))).\n    pose (dlCons d1 dersrecnil). pose (dlCons d0 d2).\n    pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ0 ++ A :: Γ1, C); (Γ0 ++ B :: Γ1, C)] (Γ0 ++ A ∨ B :: Γ1, C) X d3).\n    assert (E1: derrec_height d0 = mhd (Γ0 ++ A :: Γ1, C)).\n    unfold mhd. auto.\n    assert (E2: derrec_height d = mhd (Γ0 ++ A ∨ B :: Γ1, C)).\n    unfold mhd. auto.\n    assert (E3: derrec_height d1 = mhd (Γ0 ++ B :: Γ1, C)).\n    unfold mhd. auto.\n    assert (@is_mhd (Γ0 ++ A ∨ B :: Γ1, C) d). apply PSGL4ip_termin_der_is_mhd.\n    unfold is_mhd in H2. pose (H4 d4). simpl in l. rewrite dersrec_height_nil in l. rewrite Max.max_0_r in l.\n    lia. reflexivity.\n  * inversion H3. 2: inversion H4. subst. apply le_False_lt. intro.\n    pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ A ∨ B :: Γ1, C))).\n    pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ A :: Γ1, C))).\n    pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ B :: Γ1, C))).\n    pose (dlCons d1 dersrecnil). pose (dlCons d0 d2).\n    pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ0 ++ A :: Γ1, C); (Γ0 ++ B :: Γ1, C)] (Γ0 ++ A ∨ B :: Γ1, C) X d3).\n    assert (E1: derrec_height d0 = mhd (Γ0 ++ A :: Γ1, C)).\n    unfold mhd. auto.\n    assert (E2: derrec_height d = mhd (Γ0 ++ A ∨ B :: Γ1, C)).\n    unfold mhd. auto.\n    assert (E3: derrec_height d1 = mhd (Γ0 ++ B :: Γ1, C)).\n    unfold mhd. auto.\n    assert (@is_mhd (Γ0 ++ A ∨ B :: Γ1, C) d). apply PSGL4ip_termin_der_is_mhd.\n    unfold is_mhd in H2. pose (H5 d4). simpl in l. rewrite dersrec_height_nil in l. rewrite Max.max_0_r in l.\n    lia. reflexivity.\n- inversion H2. subst. inversion H. 2 : inversion H3.\n  subst. apply le_False_lt. intro.\n  pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ Γ1, A → B))).\n  pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ A :: Γ1, B))).\n  pose (dlCons d0 dersrecnil).\n  pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ0 ++ A :: Γ1, B)] (Γ0 ++ Γ1, A → B) X d1).\n  assert (E1: derrec_height d = mhd (Γ0 ++ Γ1, A → B)).\n  unfold mhd. auto.\n  assert (E2: derrec_height d0 = mhd (Γ0 ++ A :: Γ1, B)).\n  unfold mhd. auto.\n  assert (@is_mhd (Γ0 ++ Γ1, A → B) d). apply PSGL4ip_termin_der_is_mhd.\n  unfold is_mhd in H2. pose (H4 d2). simpl in l. rewrite dersrec_height_nil in l ; auto. rewrite Max.max_0_r in l.\n  lia.\n- inversion H2. subst. inversion H. 2: inversion H3.\n  subst. apply le_False_lt. intro.\n  pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ # P :: Γ1 ++ # P → A :: Γ2, C))).\n  pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ # P :: Γ1 ++ A :: Γ2, C))).\n  pose (dlCons d0 dersrecnil).\n  pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ0 ++ # P :: Γ1 ++ A :: Γ2, C)] (Γ0 ++ # P :: Γ1 ++ # P → A :: Γ2, C) X d1).\n  assert (E1: derrec_height d = mhd (Γ0 ++ # P :: Γ1 ++ # P → A :: Γ2, C)).\n  unfold mhd. auto.\n  assert (E2: derrec_height d0 = mhd (Γ0 ++ # P :: Γ1 ++ A :: Γ2, C)).\n  unfold mhd. auto.\n  assert (@is_mhd (Γ0 ++ # P :: Γ1 ++ # P → A :: Γ2, C) d). apply PSGL4ip_termin_der_is_mhd.\n  unfold is_mhd in H2. pose (H4 d2). simpl in l. rewrite dersrec_height_nil in l ; auto. rewrite Max.max_0_r in l.\n  lia.\n- inversion H2. subst. inversion H. 2: inversion H3.\n  subst. apply le_False_lt. intro.\n  pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ # P → A :: Γ1 ++ # P :: Γ2, C))).\n  pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ A :: Γ1 ++ # P :: Γ2, C))).\n  pose (dlCons d0 dersrecnil).\n  pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ0 ++ A :: Γ1 ++ # P :: Γ2, C)] (Γ0 ++ # P → A :: Γ1 ++ # P :: Γ2, C) X d1).\n  assert (E1: derrec_height d = mhd (Γ0 ++ # P → A :: Γ1 ++ # P :: Γ2, C)).\n  unfold mhd. auto.\n  assert (E2: derrec_height d0 = mhd (Γ0 ++ A :: Γ1 ++ # P :: Γ2, C)).\n  unfold mhd. auto.\n  assert (@is_mhd (Γ0 ++ # P → A :: Γ1 ++ # P :: Γ2, C) d). apply PSGL4ip_termin_der_is_mhd.\n  unfold is_mhd in H2. pose (H4 d2). simpl in l. rewrite dersrec_height_nil in l ; auto. rewrite Max.max_0_r in l.\n  lia.\n- inversion H2. subst. inversion H. 2: inversion H3.\n  subst. apply le_False_lt. intro.\n  pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ (A ∧ B) → C :: Γ1, D))).\n  pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ A → B → C :: Γ1, D))).\n  pose (dlCons d0 dersrecnil).\n  pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ0 ++ A → B → C :: Γ1, D)] (Γ0 ++ (A ∧ B) → C :: Γ1, D) X d1).\n  assert (E1: derrec_height d = mhd (Γ0 ++ (A ∧ B) → C :: Γ1, D)).\n  unfold mhd. auto.\n  assert (E2: derrec_height d0 = mhd (Γ0 ++ A → B → C :: Γ1, D)).\n  unfold mhd. auto.\n  assert (@is_mhd (Γ0 ++ (A ∧ B) → C :: Γ1, D) d). apply PSGL4ip_termin_der_is_mhd.\n  unfold is_mhd in H2. pose (H4 d2). simpl in l. rewrite dersrec_height_nil in l ; auto. rewrite Max.max_0_r in l.\n  lia.\n- inversion H2. subst. inversion H. 2: inversion H3.\n  subst. apply le_False_lt. intro.\n  pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ (A ∨ B) → C :: Γ1 ++ Γ2, D))).\n  pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ A → C :: Γ1 ++ B → C :: Γ2, D))).\n  pose (dlCons d0 dersrecnil).\n  pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ0 ++ A → C :: Γ1 ++ B → C :: Γ2, D)] (Γ0 ++ (A ∨ B) → C :: Γ1 ++ Γ2, D) X d1).\n  assert (E1: derrec_height d = mhd(Γ0 ++ (A ∨ B) → C :: Γ1 ++ Γ2, D)).\n  unfold mhd. auto.\n  assert (E2: derrec_height d0 = mhd (Γ0 ++ A → C :: Γ1 ++ B → C :: Γ2, D)).\n  unfold mhd. auto.\n  assert (@is_mhd (Γ0 ++ (A ∨ B) → C :: Γ1 ++ Γ2, D) d). apply PSGL4ip_termin_der_is_mhd.\n  unfold is_mhd in H2. pose (H4 d2). simpl in l. rewrite dersrec_height_nil in l ; auto. rewrite Max.max_0_r in l.\n  lia.\n- inversion H2. subst. inversion H.\n  * subst. apply le_False_lt. intro.\n    pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ (A → B) → C :: Γ1, D))).\n    pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ B → C :: Γ1, A → B))).\n    pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ C :: Γ1, D))).\n    pose (dlCons d1 dersrecnil). pose (dlCons d0 d2).\n    pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ0 ++ B → C :: Γ1, A → B); (Γ0 ++ C :: Γ1, D)] (Γ0 ++ (A → B) → C :: Γ1, D) X d3).\n    assert (E1: derrec_height d0 = mhd (Γ0 ++ B → C :: Γ1, A → B)).\n    unfold mhd. auto.\n    assert (E2: derrec_height d = mhd (Γ0 ++ (A → B) → C :: Γ1, D)).\n    unfold mhd. auto.\n    assert (E3: derrec_height d1 = mhd (Γ0 ++ C :: Γ1, D)).\n    unfold mhd. auto.\n    assert (@is_mhd (Γ0 ++ (A → B) → C :: Γ1, D) d). apply PSGL4ip_termin_der_is_mhd.\n    unfold is_mhd in H2. pose (H4 d4). simpl in l. rewrite dersrec_height_nil in l. rewrite Max.max_0_r in l.\n    lia. reflexivity.\n  * inversion H3. 2: inversion H4. subst. apply le_False_lt. intro.\n    pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ (A → B) → C :: Γ1, D))).\n    pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ B → C :: Γ1, A → B))).\n    pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ C :: Γ1, D))).\n    pose (dlCons d1 dersrecnil). pose (dlCons d0 d2).\n    pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(Γ0 ++ B → C :: Γ1, A → B); (Γ0 ++ C :: Γ1, D)] (Γ0 ++ (A → B) → C :: Γ1, D) X d3).\n    assert (E1: derrec_height d0 = mhd (Γ0 ++ B → C :: Γ1, A → B)).\n    unfold mhd. auto.\n    assert (E2: derrec_height d = mhd (Γ0 ++ (A → B) → C :: Γ1, D)).\n    unfold mhd. auto.\n    assert (E3: derrec_height d1 = mhd (Γ0 ++ C :: Γ1, D)).\n    unfold mhd. auto.\n    assert (@is_mhd (Γ0 ++ (A → B) → C :: Γ1, D) d). apply PSGL4ip_termin_der_is_mhd.\n    unfold is_mhd in H2. pose (H5 d4). simpl in l. rewrite dersrec_height_nil in l. rewrite Max.max_0_r in l.\n    lia. reflexivity.\n- inversion X0. subst. inversion H.\n  * subst. apply le_False_lt. intro.\n    pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ Box A → B :: Γ1, C))).\n    pose (proj1_sigT2 (PSGL4ip_termin3 (XBoxed_list BΓ ++ [Box A], A))).\n    pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ B :: Γ1, C))).\n    pose (dlCons d1 dersrecnil). pose (dlCons d0 d2).\n    pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(XBoxed_list BΓ ++ [Box A], A); (Γ0 ++ B :: Γ1, C)] (Γ0 ++ Box A → B :: Γ1, C) X d3).\n    assert (E1: derrec_height d0 = mhd (XBoxed_list BΓ ++ [Box A], A)).\n    unfold mhd. auto.\n    assert (E2: derrec_height d = mhd (Γ0 ++ Box A → B :: Γ1, C)).\n    unfold mhd. auto.\n    assert (E3: derrec_height d1 = mhd (Γ0 ++ B :: Γ1, C)).\n    unfold mhd. auto.\n    assert (@is_mhd (Γ0 ++ Box A → B :: Γ1, C) d). apply PSGL4ip_termin_der_is_mhd.\n    unfold is_mhd in H2. pose (H3 d4). simpl in l. rewrite dersrec_height_nil in l. rewrite Max.max_0_r in l.\n    lia. reflexivity.\n  * inversion H2. 2: inversion H3. subst. apply le_False_lt. intro.\n    pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ Box A → B :: Γ1, C))).\n    pose (proj1_sigT2 (PSGL4ip_termin3 (XBoxed_list BΓ ++ [Box A], A))).\n    pose (proj1_sigT2 (PSGL4ip_termin3 (Γ0 ++ B :: Γ1, C))).\n    pose (dlCons d1 dersrecnil). pose (dlCons d0 d2).\n    pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(XBoxed_list BΓ ++ [Box A], A); (Γ0 ++ B :: Γ1, C)] (Γ0 ++ Box A → B :: Γ1, C) X d3).\n    assert (E1: derrec_height d0 = mhd (XBoxed_list BΓ ++ [Box A], A)).\n    unfold mhd. auto.\n    assert (E2: derrec_height d = mhd (Γ0 ++ Box A → B :: Γ1, C)).\n    unfold mhd. auto.\n    assert (E3: derrec_height d1 = mhd (Γ0 ++ B :: Γ1, C)).\n    unfold mhd. auto.\n    assert (@is_mhd (Γ0 ++ Box A → B :: Γ1, C) d). apply PSGL4ip_termin_der_is_mhd.\n    unfold is_mhd in H2. pose (H5 d4). simpl in l. rewrite dersrec_height_nil in l. rewrite Max.max_0_r in l.\n    lia. reflexivity.\n- inversion X0. subst. inversion H.\n  * subst. apply le_False_lt. intro.\n    pose (proj1_sigT2 (PSGL4ip_termin3 (Γ, Box A))).\n    pose (proj1_sigT2 (PSGL4ip_termin3 (XBoxed_list BΓ ++ [Box A], A))).\n    pose (dlCons d0 dersrecnil).\n    pose (@derI _ _ (fun _ : (list (MPropF V)) * (MPropF V) => True) [(XBoxed_list BΓ ++ [Box A], A)] (Γ, Box A) X d1).\n    assert (E1: derrec_height d0 = mhd (XBoxed_list BΓ ++ [Box A], A)).\n    unfold mhd. auto.\n    assert (E2: derrec_height d = mhd (Γ, Box A)).\n    unfold mhd. auto.\n    assert (@is_mhd (Γ, Box A) d). apply PSGL4ip_termin_der_is_mhd.\n    unfold is_mhd in H3. pose (H3 d2). simpl in l. rewrite dersrec_height_nil in l. rewrite Max.max_0_r in l.\n    lia. reflexivity.\n  * inversion H2.\nQed.\n", "meta": {"author": "ianshil", "repo": "CE_GL4ip", "sha": "199cde58e85cafe738a7085192a185aaeb164833", "save_path": "github-repos/coq/ianshil-CE_GL4ip", "path": "github-repos/coq/ianshil-CE_GL4ip/CE_GL4ip-199cde58e85cafe738a7085192a185aaeb164833/GL4ip/PSGL4ip_termination.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.27475055564292183}}
{"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 ZArith.\nRequire Import Utils.\nRequire Import BrandRelation.\nRequire Import ForeignData.\nRequire Import Data.\nRequire Import DataLift.\nRequire Import DataNorm.\nRequire Import ForeignOperators.\nRequire Import Iterators.\nRequire Import RecOperators.\nRequire Import OperatorsUtils.\nRequire Import SortBy.\nRequire Export UnaryOperators.\n\nSection UnaryOperatorsSem.\n  Context {fdata:foreign_data}.\n\n  Definition nat_arith_unary_op_eval (op:nat_arith_unary_op) (z:Z) :=\n    match op with\n    | NatAbs => Z.abs z\n    | NatLog2 => Z.log2 z\n    | NatSqrt => Z.sqrt z\n    end.\n\n  Definition float_arith_unary_op_eval (op:float_arith_unary_op) (f:float) :=\n    match op with\n    | FloatNeg => float_neg f\n    | FloatSqrt => float_sqrt f\n    | FloatExp => float_exp f\n    | FloatLog => float_log f\n    | FloatLog10 => float_log10 f\n    | FloatCeil => float_ceil f\n    | FloatFloor => float_floor f\n    | FloatAbs => float_absolute f\n    end.\n\n  Context (h:brand_relation_t).\n  Context {foperators:foreign_operators}.\n\n  Global Instance ToString_data : ToString data\n    := { toString := foreign_operators_unary_data_tostring }.\n\n  Fixpoint defaultDataToString (d:data) : string\n    := match d with\n       | dunit => \"unit\"%string\n       | dnat n => toString n\n       | dfloat n => toString n\n       | dbool b => toString b\n       | dstring s => stringToString s\n       | dcoll l => string_bracket \n                      \"[\"%string\n                      (String.concat \", \"%string\n                              (map defaultDataToString l))\n                      \"]\"%string\n       | drec lsd => string_bracket\n                       \"{\"%string\n                       (String.concat \", \"%string \n                               (map (fun xy => let '(x,y):=xy in \n                                               (append (stringToString x) (append \"->\"%string\n                                                                                  (defaultDataToString y)))\n                                    ) lsd))\n                       \"}\"%string\n       | dleft d => string_bracket\n                      \"Left(\"%string\n                      (defaultDataToString d)\n                      \")\"%string\n       | dright d => string_bracket\n                       \"Right(\"%string\n                       (defaultDataToString d)\n                       \")\"%string\n       | dbrand b d => (string_bracket\n                          \"<\"\n                          (append (@toString _ ToString_brands b)\n                                  (append \":\" (defaultDataToString d)))\n                          \">\")\n       | dforeign fd => toString fd\n       end.\n\n  Definition unary_op_eval (uop:unary_op) (d:data) : option data :=\n    match uop with\n    | OpIdentity => Some d\n    | OpNeg => unudbool negb d\n    | OpRec s => Some (drec ((s,d) :: nil))\n    | OpDot s =>\n      match d with\n      | drec r => edot r s\n      | _ => None\n      end\n    | OpRecRemove s =>\n      match d with\n      | drec r => Some (drec (rremove r s))\n      | _ => None\n      end\n    | OpRecProject sl =>\n      match d with\n      | drec r => Some (drec (rproject r sl))\n      | _ => None\n      end\n    | OpBag => Some (dcoll (d :: nil))\n    | OpSingleton =>\n      match d with\n      | dcoll (d'::nil) => Some (dsome d')\n      | dcoll _ => Some dnone\n      | _ => None\n      end\n    | OpFlatten => \n      lift_oncoll (fun l => (lift dcoll (oflatten l))) d\n    | OpDistinct =>\n      rondcoll (@bdistinct data data_eq_dec) d\n    | OpOrderBy sc =>\n      data_sort sc d (* XXX Some very limited/hackish sorting XXX *)\n    | OpCount =>\n      lift dnat (ondcoll (fun z => Z_of_nat (bcount z)) d)\n    | OpToString =>\n      Some (dstring (foreign_operators_unary_data_tostring d))\n    | OpToText =>\n      Some (dstring (foreign_operators_unary_data_totext d))\n    | OpLength =>\n      unndstring (fun s => Z_of_nat (String.length s)) d\n    | OpSubstring start olen =>\n      match d with\n      | dstring s =>\n        Some (dstring (\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_olen :=\n                      match olen with\n                      | Some 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                      | None => (String.length s) - real_start\n                      end in\n                  (substring real_start real_olen s)))\n      | _ => None\n      end\n    | OpLike pat =>\n      match d with\n      | dstring s => Some (dbool (string_like s pat None))\n      | _ => None\n      end\n    | OpLeft => Some (dleft d)\n    | OpRight => Some (dright d)\n    | OpBrand b => Some (dbrand (canon_brands h b) d)\n    | OpUnbrand =>\n      match d with\n      | dbrand _ d' => Some d'\n      | _ => None\n      end\n    | OpCast b =>\n      match d with\n      | dbrand b' _ =>\n        if (sub_brands_dec h b' b)\n        then\n          Some (dsome d)\n        else\n          Some (dnone)\n      | _ => None\n      end\n    | OpNatUnary op =>\n      match d with\n      | dnat n => Some (dnat (nat_arith_unary_op_eval op n))\n      | _ => None\n      end\n    | OpNatSum => \n      lift dnat (lift_oncoll dsum d)\n    | OpNatMin =>\n      match d with\n      | dcoll l => lifted_min l\n      | _ => None\n      end\n    | OpNatMax =>\n      match d with\n      | dcoll l => lifted_max l\n      | _ => None\n      end\n    | OpNatMean => \n      lift dnat (lift_oncoll darithmean d)\n    | OpFloatOfNat =>\n      match d with\n      | dnat n => Some (dfloat (float_of_int n))\n      | _ => None\n      end\n    | OpFloatUnary op =>\n      match d with\n      | dfloat n => Some (dfloat (float_arith_unary_op_eval op n))\n      | _ => None\n      end\n    | OpFloatTruncate =>\n      match d with\n      | dfloat f => Some (dnat (float_truncate f))\n      | _ => None\n      end\n    | OpFloatSum =>\n      lift_oncoll lifted_fsum d\n    | OpFloatMean =>\n      lift_oncoll lifted_farithmean d\n    | OpFloatBagMin =>\n      lift_oncoll lifted_fmin d\n    | OpFloatBagMax =>\n      lift_oncoll lifted_fmax d\n    | OpForeignUnary fu => foreign_operators_unary_interp h fu d\n    end.\n\n  Lemma data_normalized_edot l s o :\n    edot l s = Some o ->\n    data_normalized h (drec l) ->\n    data_normalized h o.\n  Proof.\n    unfold edot.\n    inversion 2; subst.\n    apply assoc_lookupr_in in H.\n    rewrite Forall_forall in H2.\n    specialize (H2 _ H).\n    simpl in *; trivial.\n  Qed.\n\n  Lemma data_normalized_filter l :\n    data_normalized h (drec l) ->\n    forall f, data_normalized h (drec (filter f l)).\n  Proof.\n    inversion 1; subst; intros.\n    constructor.\n    - apply Forall_filter; trivial.\n    - apply (@sorted_over_filter string ODT_string); trivial.\n  Qed.\n\n  Lemma data_normalized_rremove l :\n    data_normalized h (drec l) ->\n    forall s, data_normalized h (drec (rremove l s)).\n  Proof.\n    unfold rremove; intros.\n    apply data_normalized_filter; trivial.\n  Qed.\n\n   Lemma data_normalized_rproject l :\n    data_normalized h (drec l) ->\n    forall l2, data_normalized h (drec (rproject l l2)).\n  Proof.\n    unfold rremove; intros.\n    unfold rproject.\n    apply data_normalized_filter; trivial.\n  Qed.\n\n  Lemma data_normalized_bdistinct l :\n    data_normalized h (dcoll l) -> data_normalized h (dcoll (bdistinct l)).\n  Proof.\n    inversion 1; subst.\n    constructor.\n    apply bdistinct_Forall; trivial.\n  Qed.\n\n  Lemma dnnone : data_normalized h dnone.\n  Proof.\n    repeat constructor.\n  Qed.\n\n  Lemma dnsome d :\n    data_normalized h d ->\n    data_normalized h (dsome d).\n  Proof.\n    repeat constructor; trivial.\n  Qed.\n\n  Hint Constructors data_normalized Forall : qcert.\n  Hint Resolve dnnone dnsome : qcert.\n  \n  Lemma unary_op_eval_normalized {u d o} :\n    unary_op_eval u d = Some o ->\n    data_normalized h d ->\n    data_normalized h o.\n  Proof.\n    unary_op_cases (destruct u) Case; simpl;\n    try solve [inversion 1; subst; eauto 3 with qcert\n              | destruct d; inversion 1; subst; eauto 3 with qcert].\n    - Case \"OpDot\"%string.\n      destruct d; try discriminate.\n      intros. eapply data_normalized_edot; eauto.\n    - Case \"OpRecRemove\"%string.\n      destruct d; try discriminate.\n      inversion 1; subst.\n      intros; apply data_normalized_rremove; eauto.\n    - Case \"OpRecProject\"%string.\n      destruct d; try discriminate.\n      inversion 1; subst.\n      intros; apply data_normalized_rproject; eauto.\n    - Case \"OpSingleton\"%string.\n      destruct d; simpl; try discriminate.\n      destruct l.\n      + inversion 1. inversion 1; subst; qeauto.\n      + destruct l; inversion 1; subst; eauto 2 with qcert.\n        rewrite <- data_normalized_dcoll; intros [??]; qeauto.\n    - Case \"OpFlatten\"%string.\n      destruct d; simpl; try discriminate.\n      unfold oflatten.\n      intros ll; apply some_lift in ll.\n      destruct ll; subst.\n      intros.\n      inversion H; subst.\n      constructor.\n      apply (lift_flat_map_Forall e H1); intros.\n      match_destr_in H0.\n      inversion H0; subst.\n      inversion H2; trivial.\n    - Case \"OpDistinct\"%string.\n      destruct d; try discriminate.\n      unfold rondcoll.\n      intros ll; apply some_lift in ll.\n      destruct ll; subst.\n      simpl in *. inversion e; subst.\n      intros; apply data_normalized_bdistinct; trivial.\n    - Case \"OpOrderBy\"%string.\n      apply data_sort_normalized.\n    - Case \"OpUnbrand\"%string.\n      destruct d; simpl; try discriminate.\n      inversion 1; subst.\n      inversion 1; subst; trivial.\n    - Case \"OpCast\"%string.\n      destruct d; simpl; try discriminate.\n      match_destr; inversion 1; subst; qeauto.\n    - Case \"OpNatSum\"%string.\n      destruct d; simpl; try discriminate.\n      intros ll; apply some_lift in ll.\n      destruct ll; subst.\n      qeauto.\n    - Case \"OpNatMin\"%string.\n      destruct d; simpl; try discriminate.\n      unfold lifted_min.\n      intros ll; apply some_lift in ll.\n      destruct ll; subst.\n      qeauto.\n    - Case \"OpNatMax\"%string.\n      destruct d; simpl; try discriminate.\n      unfold lifted_min.\n      intros ll; apply some_lift in ll.\n      destruct ll; subst.\n      qeauto.\n    - Case \"OpNatMean\"%string.\n      destruct d; simpl; try discriminate.\n      intros.\n      apply some_lift in H.\n      destruct H as [???]; subst.\n      qeauto.\n    - Case \"OpFloatSum\"%string.\n      destruct d; simpl; try discriminate.\n      intros ll; apply some_lift in ll.\n      destruct ll; subst.\n      qeauto.\n    - Case \"OpFloatMean\"%string.\n      destruct d; simpl; try discriminate.\n      intros.\n      apply some_lift in H.\n      destruct H as [???]; subst.\n      qeauto.\n    - Case \"OpFloatBagMin\"%string.\n      destruct d; simpl; try discriminate.\n      unfold lifted_min.\n      intros ll; apply some_lift in ll.\n      destruct ll; subst.\n      qeauto.\n    - Case \"OpFloatBagMax\"%string.\n      destruct d; simpl; try discriminate.\n      unfold lifted_min.\n      intros ll; apply some_lift in ll.\n      destruct ll; subst.\n      qeauto.\n    - Case \"OpForeignUnary\"%string.\n      intros eqq dn.\n      eapply foreign_operators_unary_normalized in eqq; eauto.\n  Qed.\n\nEnd UnaryOperatorsSem.\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/Operators/UnaryOperatorsSem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.274750549278754}}
{"text": "Require Import Event_system Term_system ConcreteEvidence Cvm_St.\nRequire Import Cvm_Impl Helpers_CvmSemantics CvmSemantics.\nRequire Import Axioms_Io External_Facts Auto AutoApp.\n\nRequire Import Appraisal_Defs Impl_appraisal_alt.\n\nRequire Import Anno_Term_Defs.\n\nRequire Import Coq.Arith.Peano_dec.\n\nRequire Import StructTactics Appraisal_Evidence Helpers_Appraisal.\n\nRequire Import Lia Coq.Program.Tactics Coq.Program.Equality.\n\nRequire Import List.\nImport ListNotations.\n\n(*\nSet Nested Proofs Allowed.\n *)\n\nLemma ggc_app: forall p0 sigbs H4 e',\n    EvSub (ggc p0 sigbs H4) e' ->\n    exists e'',\n      EvSub\n        (ggc p0 (checkSigF H4 p0 sigbs) e'')\n        (build_app_comp_evC e').\nProof.\n  intros.\n  generalizeEverythingElse e'.\n  induction e'; intros;\n    ff.\n  -\n    evSubFacts.\n    edestruct IHe'; eauto.\n  -\n    ff.\n    invc H.\n    +\n      exists ((build_app_comp_evC e')).\n      econstructor.\n    +\n      edestruct IHe'; eauto.\n    \n  -\n    evSubFacts.\n    +\n      edestruct IHe'1; eauto.\n    +\n      edestruct IHe'2; eauto.\n  -\n    evSubFacts.\n    +\n      edestruct IHe'1; eauto.\n    +\n      edestruct IHe'2; eauto.\nDefined.\n\nLemma appraisal_correct_sig : forall t annt e e' p ev,\n    annoP annt t ->\n    not_none_none t ->\n    not_hash_sig_term_ev t e ->\n    cvm_evidence_denote annt p e = e' ->\n\n    sigEvent annt p (et_fun e) ev ->\n    appEvent_Sig_EvidenceC ev (build_app_comp_evC e').\nProof.\n  intros.\n  sigEventFacts.\n  sigEventPFacts.\n\n  edestruct gg_preserved'.\n  2: { eassumption. }\n  2: { eassumption. }\n  eassumption.\n  eassumption.\n  reflexivity.\n\n  destruct_conjs.\n\n  edestruct ggc_app.\n  eassumption.\n\n  econstructor.\n  dd.\n  eassumption.\nDefined.\n\nLemma appraisal_correct : forall t annt e' p ev e,\n    annoP annt t ->\n    not_none_none t ->\n    cvm_evidence_denote annt p e = e' ->\n    measEvent annt p (et_fun e) ev ->\n    appEvent_EvidenceC ev (build_app_comp_evC e').\nProof.\n  intros.\n  measEventFacts.\n  evEventFacts.\n  edestruct uu_preserved'.\n  eassumption.\n  eassumption.\n  eassumption.\n  reflexivity.\n\n  destruct_conjs.\n    (*\n    assert (e0 = et_fun H2).\n    {\n      Search (_ = et_fun _).\n      eapply etfun_reconstruct; eauto.\n    }\n    subst.\n     *)\n\n  apply uuc_app in H5.\n\n  assert (e0 = et_fun H2).\n  {\n    eapply etfun_reconstruct; eauto.\n  }\n  subst.\n  assert (H1 = encodeEv H2).\n  {\n    \n    eapply recon_encodeEv.\n    eapply wf_recon.\n    eassumption.\n    eassumption.\n  }\n  rewrite H6 in *.\n\n  eapply aeuc.\n  eassumption.\n  destruct_conjs.\n\n   eapply ahuc.\n    eassumption.\n    eapply hhc_app.\n    eassumption.\nDefined.\n\n\nRequire Import Impl_appraisal Appraisal_AltImpls_Eq.\n\nLemma appraisal_correct_sig_alt :\n  forall t annt pt e e' tr tr' p p' bits' et' ev ee i i',\n    anno_parP pt t ->\n    annoP_indexed annt t i i' -> \n    well_formed_r_annt annt ->\n    not_none_none t ->\n    not_hash_sig_term_ev t e ->\n    wf_ec ee ->\n    reconstruct_evP ee e ->\n    copland_compile pt\n                    {| st_ev := ee; st_trace := tr; st_pl := p; st_evid := i |} =\n    (Some tt, {| st_ev := (evc bits' et');\n                 st_trace := tr';\n                 st_pl := p';\n                 st_evid := i'|}) ->\n\n    sigEvent annt p (get_et ee) ev ->\n    Some e' = Impl_appraisal.build_app_comp_evC et' bits' ->\n    appEvent_Sig_EvidenceC ev e'.\nProof.\n  intros.\n  wrap_ccp.\n  do_wfec_preserved.\n  do_somerecons.\n  destruct ee.\n  assert (et_fun e = e0).\n  {\n    symmetry.\n    eapply etfun_reconstruct.\n    eauto.\n  }\n  subst.\n  \n  erewrite appraisal_alt.\n  eapply appraisal_correct_sig.\n  econstructor. repeat eexists. invc H0. eassumption.\n  eassumption.\n  eassumption.\n\n \n  eapply cvm_raw_evidence_denote_fact; eauto.\n  eassumption.\n  eassumption.\n  eassumption.\n  reflexivity.\nDefined.\n\nLemma appraisal_correct_sig_alt_et :\n  forall t annt pt bits et et' et'' e e' tr tr' p p' bits' ev i i',\n    anno_parP pt t ->\n    annoP_indexed annt t i i' ->\n    well_formed_r_annt annt ->\n    not_none_none t ->\n    not_hash_sig_term_ev t e ->\n    wf_ec (evc bits et) ->\n    et' = aeval annt p et ->\n    reconstruct_evP (evc bits et) e ->\n    copland_compile pt\n                    {| st_ev := (evc bits et); st_trace := tr; st_pl := p; st_evid := i |} =\n    (Some tt, {| st_ev := (evc bits' et'');\n                 st_trace := tr';\n                 st_pl := p';\n                 st_evid := i'|}) ->\n\n    sigEvent annt p et ev ->\n    Some e' = Impl_appraisal.build_app_comp_evC et' bits' ->\n    appEvent_Sig_EvidenceC ev e'.\nProof.\n  intros.\n  wrap_ccp.\n  assert (et'' =  (aeval annt p et)).\n  {\n    rewrite <- eval_aeval'.\n    \n    assert (t = unanno annt).\n    {\n      invc H0.\n      erewrite <- anno_unanno at 1.\n      rewrite H5.\n      tauto.\n    }\n    subst.\n    \n    eapply cvm_refines_lts_evidence.\n    eassumption.\n    eassumption.\n  }\n\n  subst.\n  invc H7.\n  eapply appraisal_correct_sig_alt; eauto.\nDefined.\n\n\nLemma appraisal_correct_alt :\n  forall t annt pt e' tr tr' p p' bits' et' ev ee i i',\n    anno_parP pt t ->\n    annoP_indexed annt t i i' ->\n    well_formed_r_annt annt ->\n    not_none_none t ->\n    wf_ec ee ->\n    copland_compile pt\n                    {| st_ev := ee; st_trace := tr; st_pl := p; st_evid := i |} =\n    (Some tt, {| st_ev := (evc bits' et');\n                 st_trace := tr';\n                 st_pl := p'; st_evid := i' |}) ->\n\n    measEvent annt p (get_et ee) ev ->\n    Some e' = Impl_appraisal.build_app_comp_evC et' bits' ->\n    appEvent_EvidenceC ev e'.\nProof.\n  intros.\n  wrap_ccp.\n  do_wfec_preserved.\n  do_somerecons.\n  destruct ee.\n  assert (e = et_fun H9).\n  {\n    eapply etfun_reconstruct.\n    eauto.\n  }\n  subst.\n    \n  erewrite appraisal_alt.\n  eapply appraisal_correct.\n  econstructor. repeat eexists. invc H0. eassumption.\n  eassumption.\n  eapply cvm_raw_evidence_denote_fact; eauto.\n\n  eassumption.\n  eassumption.\n  eassumption.\n  reflexivity.\nDefined.\n\nLemma appraisal_correct_alt_et :\n  forall t annt pt e' tr tr' p p' bits bits' et et' et'' ev i i',\n    anno_parP pt t ->\n    annoP_indexed annt t i i' ->\n    well_formed_r_annt annt ->\n    not_none_none t ->\n    wf_ec (evc bits et) ->\n    et' = aeval annt p et ->\n    copland_compile pt\n                    {| st_ev := (evc bits et); st_trace := tr; st_pl := p; st_evid := i |} =\n    (Some tt, {| st_ev := (evc bits' et'');\n                 st_trace := tr';\n                 st_pl := p';\n                 st_evid := i'|}) ->\n\n    measEvent annt p et ev ->\n    Some e' = Impl_appraisal.build_app_comp_evC et' bits' ->\n    appEvent_EvidenceC ev e'.\nProof.\n  intros.\n  wrap_ccp.\n  assert (et'' = (aeval annt p et)).\n  {\n    assert (t = unanno annt).\n    {\n      invc H0.\n      erewrite <- anno_unanno at 1.\n      rewrite H4.\n      tauto.\n    }\n    subst.\n\n    erewrite <- eval_aeval'.\n    eapply cvm_refines_lts_evidence.\n    eassumption.\n    eassumption.\n  }\n  \n  subst.\n\n  eapply appraisal_correct_alt.\n  6: {\n    wrap_ccp.\n    eassumption.\n  }\n  eauto.\n  eauto.\n  eauto.\n  eauto.\n  eauto.\n  eauto.\n  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/Appraisal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2746470791804665}}
{"text": "Require Import TLA.\nRequire Import Rules.\nRequire Import Arith.\nRequire Import ZArith.\nRequire Import Omega.\nRequire Import Setoid.\nRequire Import FunctionalExtensionality.\nRequire Import Basic.\nRequire Import Rules.\n\nOpen Scope tla.\n\nInductive Mode := Record | Play.\n\nModule Type MemParams <: BasicParams.\n  Parameter PatternIsh : Type.\n  Parameter IsPattern : PatternIsh -> Prop.\n  Parameter NilPattern : PatternIsh.\n  Parameter NilPatternPattern : IsPattern NilPattern.\n  Parameter EqNilPatternClassical : forall p, IsPattern p -> p = NilPattern \\/ p <> NilPattern.\n  Parameter MaxMemoryLen : nat.\n  Parameter MaxMemoryLenGtZ : (0 < MaxMemoryLen)%nat.\n\n  Fixpoint IsListPattern (ls : list PatternIsh) : Prop :=\n    match ls with\n      | nil => True\n      | (cons h tl) => IsPattern h /\\ IsListPattern tl\n    end.\n\nEnd MemParams.\n\nModule ParamsFromMem (Params : MemParams) <: BasicParams.\n  Definition PatternIsh := list Params.PatternIsh.\n  Definition IsPattern := Params.IsListPattern.\n  Definition NilPattern : PatternIsh := nil.\n  Theorem NilPatternPattern : IsPattern NilPattern.\n  Proof.\n    unfold IsPattern, NilPattern.\n    simpl. auto.\n  Qed.\n  Theorem EqNilPatternClassical : forall p, IsPattern p -> p = NilPattern \\/ p <> NilPattern.\n  Proof.\n    intros p H.\n    unfold NilPattern, IsPattern.\n    destruct p. left; auto. right; intros F; inversion F.\n  Qed.\nEnd ParamsFromMem.\n\nModule Memory (Params : MemParams).\n  Import Params.\n\n  Hint Resolve NilPatternPattern.\n\n  Record St := {\n      ready : bool;\n      status : MemStatus;\n      mode : Mode;\n      memory : list PatternIsh;\n      output : list PatternIsh}.\n\n  Section Model.\n    Variable st st' : St.\n    Let ready' := (st').(ready). Let ready := st.(ready).\n    Let status' := (st').(status). Let status := st.(status).\n    Let mode' := (st').(mode). Let mode := st.(mode).\n    Let memory' := (st').(memory). Let memory := st.(memory).\n    Let output' := (st').(output). Let output := st.(output).\n\n    Definition TypeInvariant := IsListPattern memory /\\ IsListPattern output.\n\n    Definition Initialize :=\n      ready = false\n      /\\ ready' = true\n      /\\ (mode = Play -> output = nil)\n      /\\ match status' with\n          | Valid => mode' = Record /\\ memory' = nil\n          | _ => mode' = mode /\\ memory' = memory\n         end\n      /\\ output' = output.\n\n    Definition Reset :=\n      ready' = false\n      /\\ memory' = nil\n      /\\ output' = nil\n      /\\ ignore st.\n\n    Definition Flush :=\n      ready = true\n      /\\ status = Valid\n      /\\ mode = Record\n      /\\ memory' = nil\n      /\\ output' = nil\n      /\\ ready' = ready\n      /\\ status' = status\n      /\\ mode' = mode.\n\n    Definition Write p := \n      ready = true\n      /\\ status = Valid\n      /\\ mode = Record\n      /\\ (length memory < MaxMemoryLen)%nat\n      /\\ (p <> NilPattern -> memory' = cons p memory)\n      /\\ (p = NilPattern -> memory' = memory)\n      /\\ ready' = ready\n      /\\ status' = status\n      /\\ mode' = mode\n      /\\ output' = output.\n\n    Definition StartPlay :=\n      ready = true\n      /\\ status = Valid\n      /\\ mode = Record\n      /\\ output = nil\n      /\\ memory <> nil\n      /\\ mode' = Play\n      /\\ ready' = ready /\\ status' = status /\\ memory' = memory /\\ output' = output.\n\n    Definition DoPlay :=\n      ready = true\n      /\\ status = Valid\n      /\\ mode = Play\n      /\\ exists h t, memory = cons h t\n      /\\ memory' = t\n      /\\ output' = cons h output\n      /\\ ready' = ready /\\ status'= status /\\ mode' = mode.\n\n    Definition EndPlay :=\n      ready = true\n      /\\ status = Valid\n      /\\ mode = Play\n      /\\ memory = nil\n      /\\ mode' = Record\n      /\\ output' = output\n      /\\ ready' = ready /\\ status' = status /\\ memory' = memory.\n\n    Definition PowerOn :=\n      ready = false\n      /\\ IsListPattern memory\n      /\\ (length memory <= MaxMemoryLen)%nat\n      /\\ output = nil.\n\n    Definition Next :=\n      Initialize\n      \\/ Reset\n      \\/ Flush\n      \\/ (exists p, IsPattern p /\\ Write p)\n      \\/ StartPlay\n      \\/ DoPlay\n      \\/ EndPlay.\n  End Model.\n\n  Definition Fairness :=\n     WF Initialize\n     `/\\ WF DoPlay\n     `/\\ WF EndPlay.\n\n  Definition Spec := ` PowerOn `/\\ [][Next] `/\\ Fairness.\n\n  Lemma Next_TypeInvariant : forall st st', TypeInvariant st\n      -> Next st st' -> TypeInvariant st'.\n  Proof.\n    intros st st' tst next.\n    unfold TypeInvariant in *.\n    destruct tst as (memst,patst).\n    destruct st, st'. simpl in *.\n    destruct next as [\n      (H0,(H1,(H2,(H3,H4))))\n      |[(H0,(H1,(H2,H3)))\n      |[(H0,(H1,(H2,(H3,(H4,(H5,(H6,H7)))))))\n      |[(p,(isPatP,(H0,(H1,(H2,(H3,(H4,(H5,(H6,(H7,(H8,H9)))))))))))\n      |[(H0,(H1,(H2,(H3,(H4,(H5,(H6,(H7,(H8,H9)))))))))\n      |[(H0,(H1,(H2,(h,(t,(H4,(H5,(H6,(H7,(H8,H9))))))))))\n      |(H0,(H1,(H2,(H3,(H4,(H5,(H6,(H7,H8))))))))\n    ]]]]]];\n    simpl in *.\n    destruct status1; destruct H3 as (H3,H5); rewrite H5; rewrite H4; repeat split; auto.\n    rewrite H1, H2; repeat split; auto.\n    rewrite H3, H4; repeat split; auto.\n    rewrite H9; split; auto.\n    assert (H : p = NilPattern \\/ p <> NilPattern). apply EqNilPatternClassical. auto.\n    destruct H as [H|H]. apply H5 in H. rewrite H. auto.\n    apply H4 in H. rewrite H. split; auto.\n    rewrite H8, H9; repeat split; auto.\n    rewrite H4 in memst. destruct memst as (iPt,memst).\n    rewrite H6, H5; repeat split; auto.\n    rewrite H8. rewrite H5. repeat split; auto.\n  Qed.\n\n  Theorem Spec_TypeInvariant : valid (Spec `=> [] ` TypeInvariant).\n  Proof.\n    apply tla_inv_gen.\n    intros s H. destruct H as (H,_).\n    unfold PowerOn, TypeInvariant in *; simpl in *.\n    destruct H as (_,(H,(_,H0))). rewrite H0. repeat split; auto.\n    intros s. apply Next_TypeInvariant.\n  Qed.\n(*\n  Definition ValidIsDefined st := (st.(ready) = true /\\ st.(status) = Valid) \n                                  -> exists lst, st.(memory) = lst.\n\n  Lemma Next_ValidIsDefined : forall st st', ValidIsDefined st -> Next st st'\n    -> ValidIsDefined st'.\n  Proof.\n    intros st st' valDef next H.\n    destruct H as (H,H0).\n    unfold ValidIsDefined in *.\n    destruct next as [\n    (_,(_,(H1,_)))\n    |[(H1,_)\n    |[(_,(_,(_,(H1,_))))\n    |[(p,(isPatp,(memls,(H1,(_,(_,(_,(_,(H2,(H3,_))))))))))\n    |[(H1,(H2,(_,(_,(_,(_,(_,(H3,_))))))))\n    |[(_,(_,(_,(_,(t,(_,(H1,_)))))))\n    |(_,(_,(_,(H1,(_,(_,(_,(_,H2))))))))]]]]]]; simpl in *.\n    apply H1 in H0. destruct H0 as (_,H0). exists nil. auto.\n    rewrite H1 in H. inversion H.\n    exists nil. auto.\n    assert (H4 : p = NilPattern \\/ p <> NilPattern). apply EqNilPatternClassical; auto.\n    destruct H4 as [H4|H4]. exists memls. apply H3 in H4. rewrite H4. auto.\n    exists ((p :: memls)%list). apply H2 in H4. auto.\n    rewrite H3. apply valDef. split; auto.\n    exists t. auto.\n    rewrite H2. exists nil; auto.\n  Qed.\n\n  Theorem Spec_ValidIsDefined : valid (Spec `=> [] ` ValidIsDefined).\n  Proof.\n    apply tla_inv_gen.\n    intros s H H0. destruct H0 as (H0,H1). destruct H as ((H,_),_). rewrite H0 in H.\n    inversion H.\n    intros s. simpl. apply Next_ValidIsDefined.\n  Qed.\n*)\n  Module FROMMEM := ParamsFromMem (Params).\n  Module BASIC := Basic.Basic (FROMMEM).\n\n  Definition refinement_mapping (st : St) : BASIC.St := \n    match st with\n      | {|  ready := ready0; \n            status := status0; \n            memory := memory0; \n            mode := mode0;\n            output := output0 |} =>\n              {|  BASIC.ready := ready0;\n                  BASIC.status := status0;\n                  BASIC.memory := match mode0 with\n                                  | Record => memory0\n                                  | Play => ((List.rev output0) ++ memory0)%list\n                                  end;\n                  BASIC.output := match mode0 with\n                                  | Record => List.rev output0\n                                  | Play => nil\n                                  end |}\n    end.\n\n  Lemma Next_refinement : forall st st', TypeInvariant st -> Next st st' ->\n      (BASIC.Next (refinement_mapping st) (refinement_mapping st') \\/\n      (refinement_mapping st = refinement_mapping st')).\n  Proof.\n    intros st st' typInv next.\n    unfold Next, BASIC.Next in *.\n    destruct next as [\n      (H0,(H1,(H2,(H3,H4))))\n      |[(H0,(H1,(H2,H3)))\n      |[(H0,(H1,(H2,(H3,(H4,(H5,(H6,H7)))))))\n      |[(p,(isPatP,(H0,(H1,(H2,(H3,(H4,(H5,(H6,(H7,(H8,H9)))))))))))\n      |[(H0,(H1,(H2,(H3,(H4,(H5,(H6,(H7,(H8,H9)))))))))\n      |[(H0,(H1,(H2,(h,(t,(H4,(H5,(H6,(H7,(H8,H9))))))))))\n      |(H0,(H1,(H2,(H3,(H4,(H5,(H6,(H7,H8))))))))\n    ]]]]]].\n\n    left. left. \n    unfold BASIC.Initialize.\n    destruct st, st'; simpl in *. rewrite <- H0, H1, H4.\n    destruct status1; repeat split; auto; destruct H3 as (H3,H5); \n    try (rewrite H3); try (rewrite H5); auto.\n    destruct mode0; auto; intuition; rewrite H; auto.\n\n    left. right. left.\n    unfold BASIC.Reset, ignore.\n    destruct st, st'; simpl in *. rewrite H0, H1, H2; simpl.\n    destruct mode1; repeat split; auto.\n\n    left. right. right. left.\n    unfold Flush, BASIC.Flush in *.\n    destruct st, st'; simpl in *.\n    rewrite H7.\n    rewrite H6, H5, H4, H3, H2, H1. repeat split; auto.\n\n    left. right. right. right. left.\n    unfold Write, BASIC.Write in *.\n    assert (H10 : p = NilPattern \\/ p <> NilPattern). apply EqNilPatternClassical; auto.\n    destruct st, st'; simpl in *.\n    rewrite H8. rewrite H0, H1, H2, H6, H7, H9, H1. \n    destruct H10 as [H10|H10].\n    apply H5 in H10.\n    rewrite H10. exists FROMMEM.NilPattern; intuition.\n    apply H4 in H10. rewrite H10.\n    destruct typInv as (ty,_). simpl in ty.\n    exists ((p :: memory0)%list). repeat split; auto. intros H; inversion H.\n\n    right.\n    destruct st, st'. simpl in *.\n    rewrite H9, H8, H7, H6, H5, H3, H2, H1, H0. simpl in *.\n    auto.\n\n    right.\n    destruct st, st'. simpl in *.\n    rewrite H9, H8, H7, H6, H5, H4, H2, H1, H0.\n    simpl.\n    rewrite <- List.app_assoc.\n    simpl. auto.\n\n    left. right. right. right. right.\n    unfold BASIC.Run.\n    destruct st, st'; simpl in *.\n    rewrite H8, H7, H6, H5, H4, H3, H2, H1, H0.\n    repeat split; auto.\n    rewrite List.app_nil_r. auto.\n    rewrite List.app_nil_r in H. auto.\n  Qed.\n\n\nEnd Memory.\n\n", "meta": {"author": "philipjf", "repo": "AWG-AVOCS-2016", "sha": "c6bf5fd38813bac1a4d34f78c11e13398031dcff", "save_path": "github-repos/coq/philipjf-AWG-AVOCS-2016", "path": "github-repos/coq/philipjf-AWG-AVOCS-2016/AWG-AVOCS-2016-c6bf5fd38813bac1a4d34f78c11e13398031dcff/awg/Memory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2746470733563457}}
{"text": "(** * Propositional self-duality of groupoid categories *)\nRequire Import Category.Core GroupoidCategory.Core Category.Paths Category.Dual.\nRequire Import HoTT.Types HoTT.UnivalenceImpliesFunext.\n\nSet Universe Polymorphism.\nSet Implicit Arguments.\nGeneralizable All Variables.\nSet Asymmetric Patterns.\n\nLocal Open Scope category_scope.\n\nLemma path_groupoid_dual `{Univalence} `{IsTrunc 1 X}\n: (groupoid_category X)^op = groupoid_category X.\nProof.\n  repeat match goal with\n           | _ => intro\n           | _ => progress cbn\n           | _ => reflexivity\n           | _ => apply path_forall\n           | _ => apply (path_universe (symmetry _ _))\n           | _ => exact (center _)\n           | _ => progress rewrite ?transport_path_universe, ?transport_path_universe_V\n           | _ => progress path_category\n           | _ => progress path_induction\n         end.\nQed.\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/GroupoidCategory/Dual.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2746470675322248}}
{"text": "Require Import Platform.tests.Thread0 Platform.tests.ListBuilder Platform.Bootstrap.\n\n\nModule Type S.\n  Variable heapSize : nat.\nEnd S.\n\nModule Make(M : S).\nImport M.\n\nModule M'.\n  Definition globalSched : W := (heapSize + 50) * 4.\nEnd M'.\n\nImport M'.\n\nModule E := ListBuilder.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], \"test\"!\"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 \"test\"!\"main\"\n      end\n    }}.\n\n  Theorem ok0 : moduleOk boot.\n    vcgen; abstract (unfold globalSched, localsInvariantMain; genesis).\n  Qed.\n\n  Definition m1 := link boot E.T.T.m.\n  Definition m := link E.m m1.\n\n  Lemma ok1 : moduleOk m1.\n    link ok0 E.T.T.ok.\n  Qed.\n\n  Theorem ok : moduleOk m.\n    link E.ok ok1.\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/ListBuilderDriver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2746470675322248}}
{"text": "Require Import Coqlib.\nRequire Import Asm.\nRequire Import Globalenvs.\nRequire Import Integers.\n\nRequire Import ProgPropDec.\nRequire Import PeekTactics.\nRequire Import PeekLib.\nRequire Import PregTactics.\nRequire Import StepLib.\nRequire Import AsmBits.\nRequire Import MemoryAxioms.\nRequire Import GlobalPerms.\nRequire Import FindInstrLib.\nRequire Import AsmCallingConv.\n\nLemma step_nextinstr_same_block :\n  forall p rs m md rs' m' md' t,\n    no_PC_overflow_prog p ->\n    step_bits (Genv.globalenv p) (State_bits rs m md) t (State_bits rs' m' md') ->\n    forall b ofs bits b' ofs' bits',\n      rs PC = Values.Vint bits ->\n      psur md bits = Some (b,ofs) ->\n      rs' PC = Values.Vint bits' ->\n      psur md' bits' = Some (b',ofs') ->\n      rs' PC = nextinstr rs PC ->\n      b = b'.\nProof.\n  intros.\n  NP _app step_md step_bits.\n  NP _app step_gp step_bits.\n  NP _app md_extends_step step_bits.\n  repeat break_and.\n  repeat match goal with\n           | [ H : global_perms _ _ |- _ ] => eapply global_perms_valid_globals in H\n         end.\n  assert (is_global (Genv.globalenv p) b ofs). {\n    unfold is_global.\n    left. unfold in_code_range.\n    invs; repeat unify_PC; repeat unify_psur;\n    unfold fundef in *; repeat collapse_match;\n    try NP apex in_range_find_instr find_instr;\n    try omega. \n    rewrite Int.unsigned_zero. omega.\n  } idtac.\n\n  assert (Int.unsigned (Int.add ofs Int.one) = Int.unsigned ofs + 1). {\n    unfold Int.add. rewrite Int.unsigned_one.\n    invs; repeat unify_PC; repeat unify_psur;\n    try solve [\n          erewrite unsigned_repr_PC; eauto;\n          left; replace (Int.unsigned ofs + 1 - 1) with (Int.unsigned ofs) in * by omega; eassumption].\n    rewrite Int.unsigned_zero. rewrite Int.unsigned_repr.\n    omega. unfold Int.max_unsigned.\n    unfold Int.modulus. unfold Int.wordsize.\n    unfold Wordsize_32.wordsize.\n    unfold two_power_nat.\n    unfold shift_nat.\n    simpl. omega.\n  } idtac.\n  erewrite weak_valid_pointer_sur in H2; eauto.\n  break_and.\n  preg_simpl_hyp H5.\n  rewrite H1 in H5.\n  erewrite weak_valid_pointer_sur in H4; eauto.\n  break_and. simpl in H5.\n  unify_PC.\n  app pinj_add H2. instantiate (1 := Int.one) in H2.\n  eapply pinj_extends in H2; eauto.\n  assert (Memory.Mem.weak_valid_pointer m' b (Int.unsigned (Int.add ofs Int.one)) = true). {\n    rewrite Memory.Mem.weak_valid_pointer_spec.\n    rewrite H12. right.\n    replace (Int.unsigned ofs + 1 - 1) with (Int.unsigned ofs) by omega.\n    eapply H9. assumption.\n  } idtac.\n  name (conj H4 H14) Hpsur1. erewrite <- weak_valid_pointer_sur in Hpsur1; eauto.\n  name (conj H2 H15) Hpsur2. erewrite <- weak_valid_pointer_sur in Hpsur2; eauto.\n  unify_psur. reflexivity.\nQed.\n\nDefinition labeled_jump (i : instruction) (l : label) : Prop :=\n  match i with\n    | Pjmp_l l' => l = l'\n    | Pjcc _ l' => l = l'\n    | Pjcc2 _ _ l' => l = l'\n    | Pjmptbl _ ls => In l ls\n    | _ => False\n  end.\n\nInductive in_same_block (s1 s2 : state_bits) : Prop :=\n  | in_b :\n      forall rs m rs' m' b i i' bits bits' md md',\n        s1 = State_bits rs m md ->\n        s2 = State_bits rs' m' md' ->\n        rs PC = Values.Vint bits ->\n        rs' PC = Values.Vint bits' ->\n        psur md bits = Some (b,i) ->\n        psur md' bits' = Some (b,i') ->\n        in_same_block s1 s2.\n\nLemma labeled_jump_same_block : \n  forall p rs m md t rs' m' md' bits b ofs bits' b' ofs' f i,\n    (exists l, labeled_jump i l) ->\n    no_PC_overflow_prog p ->\n    step_bits (Genv.globalenv p) (State_bits rs m md) t (State_bits rs' m' md') ->\n    rs PC = Values.Vint bits ->\n    psur md bits = Some (b,ofs) ->\n    rs' PC = Values.Vint bits' ->\n    psur md' bits' = Some (b',ofs') ->\n    Genv.find_funct_ptr (Genv.globalenv p) b = Some (AST.Internal f) ->\n    find_instr (Int.unsigned ofs) (fn_code f) = Some i ->\n    b = b'.\nProof.\n  intros.\n  invs; repeat unify_PC; repeat unify_psur; unfold fundef in *; try find_one_instr; unify_find_funct_ptr; unify_find_instr; simpl in H; try solve [break_exists; inv_false].\n\n  assert ((exists l', labeled_jump i l' /\\ goto_label_bits md f0 l' b rs m = Nxt rs' m' md') \\/ rs' PC = nextinstr rs PC). {\n    break_exists; destruct i; simpl in H; try inv_false; simpl in H21.\n    left. exists l. split; eauto. simpl. auto.\n    repeat break_match_hyp; try congruence.\n    left. exists l. split; auto. simpl. auto.\n    right. inv H21. reflexivity.\n    repeat break_match_hyp; try congruence; try solve [right; congruence].\n    left. exists l. split; auto. simpl. auto.\n    repeat break_match_hyp; try congruence.\n    left. exists l. split; auto.\n    simpl. app list_nth_z_in Heqo.\n  } idtac.\n\n  destruct H3;\n    try solve [\n          eapply step_nextinstr_same_block; eauto].\n  clear H.\n  break_exists.\n  break_and.\n\n  unfold goto_label_bits in *.\n  repeat break_match_hyp; try congruence.\n  inv H3.\n  clear H21.\n\n  preg_simpl_hyp H4.\n  inv H4.\n\n  app label_pos_find_instr Heqo.\n  assert (is_global (Genv.globalenv p) b (Int.repr (z-1))). {\n    unfold is_global.\n    left. unfold in_code_range.\n    unfold fundef in *. collapse_match.\n    apex in_range_find_instr Heqo.\n    erewrite unsigned_repr_PC; eauto. omega.\n  } idtac.\n\n  assert (Int.unsigned (Int.repr z) - 1 = Int.unsigned (Int.repr (z - 1))). {\n    erewrite unsigned_repr_PC; eauto.\n    erewrite unsigned_repr_PC; eauto.\n  } idtac.    \n  assert (Memory.Mem.weak_valid_pointer m' b (Int.unsigned (Int.repr z)) = true). {\n    rewrite Memory.Mem.weak_valid_pointer_spec.\n    right. eapply global_perms_valid_globals in H23.\n    unfold valid_globals in *.\n    rewrite H7.\n    eapply H23. auto.\n  } idtac.\n\n  name (conj Heqo0 H8) Hpsur.\n  erewrite <- weak_valid_pointer_sur in Hpsur; eauto.\n  congruence.\nQed.\n\n\nLemma step_no_call_nextinstr_or_label :\n  forall p rs m md rs' m' md' t f i,\n    no_PC_overflow_prog p ->\n    no_builtin_clobber_PC_prog p ->\n    step_bits (Genv.globalenv p) (State_bits rs m md) t (State_bits rs' m' md') ->\n    forall b ofs bits b' ofs' bits',\n      rs PC = Values.Vint bits ->\n      psur md bits = Some (b,ofs) ->\n      rs' PC = Values.Vint bits' ->\n      psur md' bits' = Some (b',ofs') ->\n      Genv.find_funct_ptr (Genv.globalenv p) b = Some (AST.Internal f) ->\n      find_instr (Int.unsigned ofs) (fn_code f) = Some i ->\n      ~ is_call_return i ->\n      rs' PC = nextinstr rs PC \\/ (exists l, labeled_jump i l).\nProof.\n  intros.\n    invs; repeat unify_PC; repeat unify_psur;\n    unfold fundef in *; repeat unify_find_funct_ptr;\n    try solve [left; reflexivity]; unify_find_instr.\n\n    Focus 2.\n    left. unfold nextinstr_nf.\n    unfold undef_regs. fold undef_regs.\n    unfold nextinstr.\n    rewrite Pregmap.gss.\n    repeat rewrite Pregmap.gso by congruence.\n    repeat rewrite Pregmap.gss.\n    assert (code_of_prog (fn_code f0) p). {\n      app Genv.find_funct_ptr_inversion H6. unfold code_of_prog.\n      destruct f0. simpl. eauto.\n    } idtac.\n    app H0 H3.\n    app H3 H18.\n    \n    rewrite set_regs_not_in by tauto.\n    rewrite undef_regs_not_in by tauto.\n    reflexivity.\n\n    \n    destruct i;\n      simpl in H22;\n      simpl in H8;\n      try inv_false;\n      try solve [right; simpl; eauto];\n      unfold exec_load_bits in *;\n      unfold exec_store_bits in *;\n      unfold exec_big_load_bits in *;\n      unfold exec_big_store_bits in *;\n      unfold compare_floats in *;\n      unfold compare_floats32 in *;\n      repeat (break_match_hyp; try congruence);\n      try st_inv;\n      try solve [left; preg_simpl; reflexivity].\n    app list_nth_z_in Heqo.\nQed.\n\nLemma step_no_call_same_block :\n  forall p rs m md rs' m' md' t f i,\n    no_PC_overflow_prog p ->\n    no_builtin_clobber_PC_prog p ->\n    step_bits (Genv.globalenv p) (State_bits rs m md) t (State_bits rs' m' md') ->\n    forall b ofs bits b' ofs' bits',\n      rs PC = Values.Vint bits ->\n      psur md bits = Some (b,ofs) ->\n      rs' PC = Values.Vint bits' ->\n      psur md' bits' = Some (b',ofs') ->\n      Genv.find_funct_ptr (Genv.globalenv p) b = Some (AST.Internal f) ->\n      find_instr (Int.unsigned ofs) (fn_code f) = Some i ->\n      ~ is_call_return i ->\n      b = b'.\nProof.\n  intros.\n  NP _app step_no_call_nextinstr_or_label step_bits.\n  break_or.\n  eapply step_nextinstr_same_block; eauto.\n  eapply labeled_jump_same_block; eauto.\nQed.\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/SameBlockLib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2746310371966405}}
{"text": "Require Import Proofs.ScopeInvariant.\nGoal WellScopedProgram program.\nProof.\nrepeat (lazy; constructor).\n(* This is for the NoDup goals: *)\nall: rewrite ?IntSetProofs.In_cons_iff; intuition congruence.\nQed.\nRequire Import Proofs.JoinPointInvariants.\nGoal isJoinPointsValidProgram program.\nProof.\nrepeat (lazy; constructor).\nQed.", "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/core-dumps/proof-suffix.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228758499941, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.27463103719664045}}
{"text": "From Coq Require Import Program.Basics Morphisms.\n\nFrom ITree Require Import\n     ITree\n     ITreeFacts.\n\nFrom ITree.Extra Require Import\n     Secure.SecureEqHalt\n     Secure.SecureEqEuttTrans\n     Secure.SecureEqProgInsens\n.\n\nFrom SecureExample Require Import\n     Utils_tutorial\n     Fin\n     KTreeFin\n     LabelledImp\n     LabelledAsm\n     LabelledImp2Asm\n     LabelledImp2AsmCorrectness\n     LabelledImpHandler\n     LabelledImpTypes\n     LabelledImpTypesProgInsens\n.\n\nImport ITreeNotations.\n\nImport Monads.\nOpen Scope monad_scope.\n\nSection SecurityPreservation.\n\nContext (Γ : var -> sensitivity).\nContext (l : sensitivity).\n\nInstance labell_equiv_equiv {Γ' l'} : Equivalence (labelled_equiv sensitivity_lat Γ' l').\nProof.\n  constructor; red; intros; red; red; intros; auto.\n  - rewrite H; auto.\n  - rewrite H; auto.\nQed.\n\nDefinition labelled_sim : map -> (registers * memory) -> Prop :=\n  fun g_imp g_asm => labelled_equiv sensitivity_lat Γ l g_imp (snd g_asm).\n\nDefinition asm_eq : registers * memory -> registers * memory -> Prop :=\n  fun '(regs1, mem1) '(regs2, mem2) => labelled_equiv sensitivity_lat Γ l mem1 mem2.\n\nLemma state_rel_aux:\n  forall (p1 : map * unit) (p2 : registers * memory * fin 1),\n    rcompose (product_rel (labelled_equiv sensitivity_lat Γ l) eq) (state_invariant TT) p1 p2 ->\n    product_rel labelled_sim TT p1 p2.\nProof.\n  intros [σ [] ] [ [regs mem] ?] Hcomp. inv Hcomp.\n  destruct r2 as [σ' [] ]. destruct REL1. split; red; auto.\n  cbn. red in REL2. destruct REL2 as [Hst _ ]. cbn in *.\n  assert (labelled_equiv _ Γ l σ' mem).\n  { red in Hst. do 2 red. intros. auto. }\n  etransitivity; eauto.\nQed.\n\nLemma state_rel_aux':\n  forall x0 x1 : registers * memory * fin 1,\n    flip\n      (rcompose\n         (flip\n            (rcompose (product_rel (LabelledImpTypes.labelled_equiv sensitivity_lat Γ l) (@eq unit) )\n                      (state_invariant TT))) (state_invariant TT)) x0 x1 ->\n    product_rel asm_eq eq x0 x1.\nProof.\n  intros [ [regs1  mem1] ? ] [ [reg2 mem2] ? ].\n  intros H. inv H. inv REL1. split; cbn.\n  2 :  setoid_rewrite unique_f0; auto.\n   inv REL0. inv REL3. inv REL2. destruct r0. destruct r2. cbn in *.\n   subst. transitivity m0.\n   cbv; intros; auto. transitivity m; auto. cbv; intros; auto.\nQed.\n\nSection ProgressSensitive.\n\nDefinition labelled_bisimilar {A B : Type} (RAB : A -> B -> Prop)\n           (t1 : itree ((impExcE _) +' stateE +' (IOE _)) A ) (t2 : itree ((impExcE _) +'\n Reg +' Memory +' (IOE _)) B) :=\n  forall (g_imp : map) (g_asm : memory) (regs : registers),\n    labelled_equiv _ Γ l g_imp g_asm ->\n    eqit_secure _ (priv_exc_io sensitivity_lat) (product_rel labelled_sim RAB) true true l (interp_imp _ t1 g_imp ) (interp_asm t2 (regs, g_asm)).\n\nLemma compile_preserves_ps_security : forall (c : stmt _),\n    label_state_sec_eutt _ Γ l eq  (interp_imp _ (denote_stmt _ c)) (interp_imp _ (denote_stmt _ c)) ->\n    labelled_bisimilar TT (denote_stmt _ c) (denote_asm (compile c) f0 ) .\nProof.\n  intros s Hsecs. red in Hsecs. red. intros g_imp g_asm regs Hs.\n  assert (labelled_equiv _ Γ l g_imp g_imp). reflexivity.\n  specialize (compile_correct s) as Heutt. do 2 red in Heutt.\n  assert (Renv g_asm g_asm). reflexivity.\n  specialize (Hsecs g_imp g_asm Hs).\n  specialize (Heutt g_asm g_asm regs H0) .\n  specialize (eutt_secure_eqit_secure) as Htrans.\n  eapply Htrans in Heutt; eauto.\n  eapply SecureEqEuttHalt.eqit_secure_RR_imp; try apply Heutt.\n  apply state_rel_aux; auto.\nQed.\n\nLemma compile_preserves_ps_ni : forall (c : stmt _),\n    label_state_sec_eutt _ Γ l eq  (interp_imp _ (denote_stmt _ c)) (interp_imp _ (denote_stmt _ c)) ->\n    forall σ1 σ2, asm_eq σ1 σ2 ->\n             eqit_secure _ (priv_exc_io _) (product_rel asm_eq eq) true true l\n             (interp_asm (denote_asm (compile c) f0) σ1) ((interp_asm (denote_asm (compile c) f0)) σ2).\nProof.\n  intros c Hsecc [regs1 mem1] [regs2 mem2]. intros Hasmeq.\n  assert (labelled_equiv _ Γ l mem1 mem1). reflexivity.\n  assert (labelled_equiv _ Γ l mem2 mem2). reflexivity.\n  specialize (compile_correct c) as Heutt. do 2 red in Heutt.\n  assert (Renv mem1 mem1). reflexivity.\n  assert (Renv mem2 mem2). reflexivity.\n  do 2 red in Hsecc.\n  assert (Hmem12 : labelled_equiv _ Γ l mem1 mem2). auto.\n  specialize (Hsecc mem1 mem2 Hmem12) as Hsecc'.\n  specialize (Heutt mem1 mem1 regs1 H1) as Heutt1.\n  specialize (Heutt mem2 mem2 regs2 H2) as Heutt2.\n  specialize (eutt_secure_eqit_secure) as Htrans.\n  eapply Htrans in Heutt1 as Heutt1'; eauto.\n  eapply Htrans in Heutt2 as Heutt2'; eauto.\n  eapply Htrans in Hsecc'; eauto.\n  apply eqit_secure_sym in Hsecc'.\n  eapply Htrans in Hsecc'; eauto.\n  apply eqit_secure_sym in Hsecc'.\n  eapply SecureEqEuttHalt.eqit_secure_RR_imp; try apply Hsecc'; eauto.\n  intros.\n  apply state_rel_aux'; auto.\nQed.\n\n\nEnd ProgressSensitive.\n\nSection ProgressInsensitive.\n\nDefinition labelled_pi_bisimilar {A B : Type} (RAB : A -> B -> Prop)\n           (t1 : itree ((impExcE _) +' stateE +' (IOE _)) A ) (t2 : itree ((impExcE _) +'\n Reg +' Memory +' (IOE _)) B) :=\n  forall (g_imp : map) (g_asm : memory) (regs : registers),\n    labelled_equiv _ Γ l g_imp g_asm ->\n    pi_eqit_secure _ (priv_exc_io _) (product_rel labelled_sim RAB) true true l (interp_imp _ t1 g_imp ) (interp_asm t2 (regs, g_asm)).\n\nLemma compile_preserves_pi_security : forall (c : stmt _),\n    label_state_pi_sec_eutt _ Γ l eq  (interp_imp _ (denote_stmt _ c)) (interp_imp _ (denote_stmt _ c)) ->\n    labelled_pi_bisimilar TT (denote_stmt _ c) (denote_asm (compile c) f0 ) .\nProof.\n  intros s Hsecs. red in Hsecs. red. intros g_imp g_asm regs Hs.\n  assert (labelled_equiv _ Γ l g_imp g_imp). reflexivity.\n  specialize (compile_correct s) as Heutt. do 2 red in Heutt.\n  assert (Renv g_asm g_asm). reflexivity.\n  specialize (Hsecs g_imp g_asm Hs).\n  specialize (Heutt g_asm g_asm regs H0) .\n  specialize (pi_eqit_secure_mixed_trans) as Htrans.\n  eapply Htrans in Heutt; eauto.\n  eapply pi_eqit_secure_RR_imp; try apply Heutt.\n  apply state_rel_aux; auto.\nQed.\n\nLemma compile_preserves_pi_ni : forall (c : stmt _),\n    label_state_pi_sec_eutt _ Γ l eq  (interp_imp _ (denote_stmt _ c)) (interp_imp _ (denote_stmt _ c)) ->\n    forall σ1 σ2, asm_eq σ1 σ2 ->\n             pi_eqit_secure _ (priv_exc_io _) (product_rel asm_eq eq) true true l\n             (interp_asm (denote_asm (compile c) f0) σ1) ((interp_asm (denote_asm (compile c) f0)) σ2).\nProof.\n  intros c Hsecc [regs1 mem1] [regs2 mem2]. intros Hasmeq.\n  assert (labelled_equiv _ Γ l mem1 mem1). reflexivity.\n  assert (labelled_equiv _ Γ l mem2 mem2). reflexivity.\n  specialize (compile_correct c) as Heutt. do 2 red in Heutt.\n  assert (Renv mem1 mem1). reflexivity.\n  assert (Renv mem2 mem2). reflexivity.\n  do 2 red in Hsecc.\n  assert (Hmem12 : labelled_equiv _ Γ l mem1 mem2). auto.\n  specialize (Hsecc mem1 mem2 Hmem12) as Hsecc'.\n  specialize (Heutt mem1 mem1 regs1 H1) as Heutt1.\n  specialize (Heutt mem2 mem2 regs2 H2) as Heutt2.\n  specialize (pi_eqit_secure_mixed_trans) as Htrans.\n  eapply Htrans in Heutt1 as Heutt1'; eauto.\n  eapply Htrans in Heutt2 as Heutt2'; eauto.\n  eapply Htrans in Hsecc'; eauto.\n  apply pi_eqit_secure_sym in Hsecc'.\n  eapply Htrans in Hsecc'; eauto.\n  apply pi_eqit_secure_sym in Hsecc'.\n  eapply pi_eqit_secure_RR_imp; try apply Hsecc'; eauto.\n  intros.\n  apply state_rel_aux'; auto.\nQed.\n\n\nEnd ProgressInsensitive.\n\n\nEnd SecurityPreservation.\n(*\nstmt :=\n     | throw\n     | try c1 catch c2\n\nitree (state +' IOE +' Exc) tt\n\n\ndenote_throw := trigger Throw\n\n\ndenote_catch\n\n\n\nblock := ...\n         | throw\n\n\ncompile p : asm 1 1\n\n\ncompile p : asm 1 2\n\n*)\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/LabelledImp2AsmNoninterferencePres.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.27463103719664045}}
{"text": "Require Import Terms.\nRequire Import LNaVSyntax.\nRequire Import LNaVBigStep. (* 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\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\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\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, CA (D eUnbound)@bot >>\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_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),_ =>\n      << pc\\_/L, rho, k, CA (D (propagate_nav b))@bot >>\n    | _, _ => \n      << pc, rho, k, CA (D eUnbound)@bot >>\n    end\n  (* s_return *)\n  | << pc, rho, RRet rho' :: k, CA a >> =>\n    << pc, rho', k, CA a >>\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, CA (D eUnbound)@bot >>\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, CA (D eType)@bot >>\n    | Some (D e, l) =>\n      << pc\\_/l, rho, k, CA (D e)@bot >>\n    | _ =>\n      << pc, rho, k, CA (D eUnbound)@bot >>\n    end\n  (* s_tag *)\n  | << pc, rho, k, CR (TTag x) >> =>\n    match get rho x with\n    | Some (b,l) =>\n      << pc, rho, k, CA (tag_box b)@l >>\n    | _ =>\n      << pc, rho, k, CA (D (eUnbound))@bot >>\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, rho, k, CA (bop_box bo b' b'', l0' \\_/ l0'') >>\n    | _, _ =>\n      << pc, rho, k, CA (D (eUnbound))@bot >>\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, CA (D (propagate_nav b))@bot >>\n    | None =>\n      << pc, rho, k, CA (D (eUnbound))@bot >>\n    end\n  (* s_bracket_end *)\n  | << pc, rho, RBrk L' pc' :: k, CA (b@L) >> =>\n    if flows_dec (L \\_/ pc) (L' \\_/ pc') then\n      << pc', rho, k, CA (b@L')>>\n    else\n      << pc', rho, k, CA ((D eBracket)@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, CA (D (eUnbound))@bot >>\n    end\n  (* s_get_pc *)\n  | << pc, rho, k, CR TGetPc >> =>\n    << pc, rho, k, CA (V (VConst (CLab pc)))@bot >>\n  (* s_mk_nav *)\n  | << pc, rho, k, CR (TMkNav x) >> =>\n    match get rho x with\n    | Some (b,l) =>\n      << pc, rho, k, CA (mk_nav_box b)@l >>\n    | _ =>\n      << pc, rho, k, CA (D (eUnbound))@bot >>\n    end\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, CA (D (eUnbound))@bot >>\n    end\n  (* stack underflow (you're already done?) *)\n  | << pc, rho, nil, CA _ >> =>\n      << pc, rho, nil, CA (D (eStack))@bot >>\n  (* terms not from this language *)\n  | << pc, rho, k, CR (TThrow _) >> =>\n      << pc, rho, k, CA (D (eLanguage))@bot >>\n  | << pc, rho, k, CR (TCatch _ _ _) >> =>\n      << pc, rho, k, CA (D (eLanguage))@bot >>\n  end.\n\nDefinition final (c : Cfg) : bool :=\n  match c with\n  | << pc, rho, nil, CA _ >> => 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 ((Atom*Lab)*nat) :=\n  match mstep n t with\n  | (<< pc, rho, nil, CA a >>, m) => Some ((a,pc),m)\n  | _ => None (* looping or need more steps *)\n  end.\n\nDefinition tstep_no := 1000.\n\nDefinition tstep (t : Tm) : option Atom :=\n  match sstep tstep_no t with\n  | Some ((a,_pc), m) => Some a\n  | None => None (* looping or need more steps *)\n  end.\n\n(* Correspondence *)\nFixpoint multistep (n : nat) (c : Cfg) : Cfg :=\n  match n with\n  | S n' => multistep n' (step c)\n  | O => c\n  end.\n\nLemma multistep_trans_general : forall n1 n2 cfg1 cfg2 cfg3,\n  multistep n1 cfg1 = cfg2 ->\n  multistep n2 cfg2 = cfg3 ->\n  exists n3, multistep n3 cfg1 = cfg3.\nProof.\n  intros n1.\n  induction n1; intros n2 cfg1 cfg2 cfg3 Hstep1 Hstep2.\n  Case \"n1 = 0\".\n    exists n2. simpl in Hstep1. subst. reflexivity.\n  Case \"S n1\".\n    simpl in Hstep1.\n    remember (step cfg1) as cfg1'.\n    specialize (IHn1 n2 cfg1' cfg2 cfg3 Hstep1 Hstep2).\n    destruct IHn1 as [n Hstep1'].\n    exists (S n). simpl. rewrite <- Heqcfg1'. assumption.\nQed.\n\nLtac solve_var H k f := exists 1; simpl; rewrite H; destruct k; try destruct f; eauto.\nLtac immediate k f := exists 1; simpl; destruct k; try destruct f; eauto.\n  \nDefinition steps cfg1 cfg2 := exists n, multistep n cfg1 = cfg2.\nHint Unfold steps.\n\nLemma multistep_trans : forall cfg1 cfg2 cfg3,\n  steps cfg1 cfg2 ->\n  steps cfg2 cfg3 ->\n  steps cfg1 cfg3.\nProof.\n  intros cfg1 cfg2 cfg3 Hstep1 Hstep2.\n  destruct Hstep1 as [n1 Hstep1]. destruct Hstep2 as [n2 Hstep2].\n  eauto using multistep_trans_general.\nQed.\n\nLemma big_to_small : forall r t pc a pc' k,\n  r |- t, pc ==> a, pc' ->\n  steps <<pc, r, k, CR t>> <<pc', r, k, CA a>>.\nProof.\n  intros r t pc a pc' k Heval. generalize dependent k.\n  (eval_cases (induction Heval) Case); intro k.\n  Case \"eval_var\". solve_var H k f.\n  Case \"eval_const\". immediate k f.\n  Case \"eval_let\".\n    assert (steps << pc, r, k, CR (TLet x t t') >> << pc, r, RLet x t' :: k, CR t >>)\n      by immediate k f.\n    specialize (IHHeval1 (RLet x t' :: k)).\n    assert (steps << pc', r, RLet x t' :: k, CA a >> << pc', (x,a) :: r, RRet r :: k, CR t' >>)\n      by immediate k f.\n    specialize (IHHeval2 (RRet r :: k)).\n    assert (steps << pc'', x @ a :: r, RRet r :: k, CA a' >> << pc'', r, k, CA a' >>)\n      by immediate k f.\n    eauto using multistep_trans.\n  Case \"eval_abs\". immediate k f.\n  Case \"eval_app\".\n    assert (steps << pc, r, k, CR (TApp x' x'') >> << pc\\_/l, x@a::r', RRet r::k, CR t >>).\n      exists 1; simpl; unfold Atom; rewrite H, H0; destruct k; try destruct f; eauto.\n    specialize (IHHeval (RRet r :: k)).\n    assert (steps <<pc', x@a::r', RRet r :: k, CA a'>> << pc', r, k, CA a'>>)\n      by immediate k f.\n    eauto using multistep_trans.\n  Case \"eval_app_no_abs\".\n    exists 1. simpl. unfold Atom. rewrite H. destruct b; try destruct v; destruct k; try destruct f; \n      try solve [simpl in H0; exfalso; auto]; auto.\n  Case \"eval_inx\".\n    solve_var H k f.\n  Case \"eval_match\".\n    assert (steps << pc, r, k, CR (TMatch x x' t' t'') >> \n                  << pc\\_/l, x'@a::r, RRet r::k, CR (d_choose d t' t'') >>).\n      fold Atom in H. destruct d; solve_var H k f.\n    specialize (IHHeval (RRet r::k)).\n    assert (steps << pc', x'@a::r, RRet r::k, CA a' >> << pc', r, k, CA a' >>).\n      immediate k f.\n    eauto using multistep_trans. \n  Case \"eval_match_no_sum\".\n    exists 1. simpl. unfold Atom. rewrite H. destruct b; try destruct v; destruct k; try destruct f; \n      try solve [simpl in H0; exfalso; auto]; auto.\n  Case \"eval_tag\".\n    fold Atom in H. solve_var H k f.\n  Case \"eval_bop\".\n    fold Atom in H, H0. \n    exists 1; simpl; rewrite H, H0; destruct k; try destruct f; eauto.\n  Case \"eval_bracket\".\n    remember (flows_dec (l'' \\_/ pc') (l \\_/ (pc \\_/ l'))) as flow.\n    assert (steps << pc, r, k, CR (TBracket x t) >> << pc\\_/l',r,RBrk l (pc\\_/l')::k,CR t>>).\n      fold Atom in H. solve_var H k f.\n    specialize (IHHeval (RBrk l (pc\\_/l') ::k)).\n    assert (steps << pc', r, RBrk l (pc \\_/ l') :: k, CA b @ l'' >>\n                  << pc \\_/ l', r, k, CA (if flow then b else D eBracket) @l >>).\n      destruct flow; immediate k f; rewrite <- Heqflow; eauto.\n    eauto using multistep_trans.\n  Case \"eval_bracket_no_lab\".\n    exists 1. simpl. unfold Atom. rewrite H. destruct b; try destruct v; try destruct c; \n      destruct k; try destruct f; try solve [simpl in H0; exfalso; auto]; auto.\n  Case \"eval_label_of\".   \n    fold Atom in H. solve_var H k f.\n  Case \"eval_get_pc\".\n    immediate k f.\n  Case \"eval_mk_nav\".\n    fold Atom in H. solve_var H k f.\n  Case \"eval_to_sum\".\n    fold Atom in H. solve_var H k f.\nQed.\n\n(* MMG: to here.  Started running into some problems lining everything\n   up, since this development is actually rather different from the\n   old one.  I think this general approach will work, but we need to\n   reconcile issues with unbound variables, get rid of stack\n   underflows, and probably relation-ize the step function.  (At which\n   point, we can either prove that the relation and function match, or\n   just redo the previous proof for the relation...)\n*)\n\n(*\nReserved Notation \"r |= cfg , pc1 ==> a , pc2\" (at level 80).\nInductive evalCfg : Env -> Cfg -> Lab -> Atom -> Lab -> Prop :=\n| evalCfgT : forall r pc r' pc' k (t:Tm) a a' pc'' pc''',\n    r' |- t, pc' ==> a, pc'' ->\n    r |= << pc'', r', k, CA a >>, pc ==> a', pc''' ->\n    r |= << pc', r', k, CR t >>, pc ==> a', pc'''\n\n| evalCfgNilA : forall r pc pc' a,\n    r |= << pc, r, nil, CA a >>, pc' ==> a, pc\n(*\n| evalCfgLet : forall r t pc a pc' x t' k a' pc'' pc''',\n    r |- t,pc' ==> a,pc'' ->\n    r |= << pc'', x@a::r, RRet r::k, CR t' >>,pc ==> a',pc''' ->\n    r |= << pc', r, RLet x t'::k, CR t >>,pc ==> a',pc'''\n| evalCfgRet : forall r pc a pc' r' k a1,\n    r |= << pc', r', k, CA a1 >>, pc ==> a, pc' ->\n    r |= << pc', r, RRet r' :: k, CA a1 >>, pc ==> a, pc'\n*)\nwhere \"r |= cfg , pc1 ==> a , pc2\" := (evalCfg r cfg pc1 a pc2).\nHint Constructors evalCfg.\n\n(** [evalCfg] is preserved by stepping back. *)\nLemma evalCfg_anti_step : forall r pc pc' a conf conf',\n  r |= conf', pc ==> a, pc' ->\n  step conf = conf' ->\n  r |= conf, pc ==> a, pc'.\nProof.\nintros r pc pc' a conf conf' HevalCfg Hstep.\ndestruct conf as [[[pc'' r'] k] [t | a']].\nTm_cases (destruct t) Case.\nCase \"TVar\".\n  remember (get r' v) as av.\n  destruct av.\n  simpl in Hstep.\n  rewrite <- Heqav in Hstep.\n  destruct k; try destruct f; subst; \n    solve [eapply evalCfgT; try apply HevalCfg; \n           apply eval_var; unfold maps; rewrite <- Heqav; auto].\n  simpl in Hstep.  \n  destruct k; try destruct f; rewrite <- Heqav in Hstep.\n  subst. invsc HevalCfg.\n  eapply evalCfgT; try apply HevalCfg.\n\nCase \"s_app_l\". invs HevalCfg.\nSCase \"evalCfgAppL\". invs H8. invs H12. invs H13. invs H19. invs H15. eauto.\nCase \"s_app_r\". invs HevalCfg.\nSCase \"evalCfgAppR\". invs H8. eauto.\nCase \"s_classify_r\". invs HevalCfg.\nSCase \"evalCfgLabR\". invs H8. invs H11. invs H12. econstructor; eauto. eauto.\nCase \"s_classify_l\". invs HevalCfg.\nSCase \"evalCfgLabl\". invs H8. eauto.\nCase \"s_lab_of_push\". invs HevalCfg.\nSCase \"evalCfgLabOf\". invs H8. econstructor; eauto. eauto.\nCase \"s_cmp_l\". invs HevalCfg.\nSCase \"evalCfgCmpL\". invs H8. invs H11. invs H12. econstructor; eauto. eauto.\nCase \"s_join_l\". invs HevalCfg.\nSCase \"evalCfgJoinL\". invs H8. invs H11. invs H12. econstructor; eauto. eauto.\nQed.\n\n*)", "meta": {"author": "mgree", "repo": "navdifc", "sha": "cde33f3ef7170b59653e252513ec6fc7ed78983a", "save_path": "github-repos/coq/mgree-navdifc", "path": "github-repos/coq/mgree-navdifc/navdifc-cde33f3ef7170b59653e252513ec6fc7ed78983a/LNaVSmallStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.27450145060804937}}
{"text": "(* Require Import Modal.\nRequire Import SecOrder.  *)\nRequire Export ST_setup.\nRequire Import Correctness_ST_world_model.\nRequire Import List_machinery_impl.\n\n(* A specific choice of pa_l that doesn't alter Ip, as proved below in Lemmas ineffective_Ip\n   and ineffective_Ip - used later in proof of correctness_ST *)\nFixpoint ineffective_pa_l (W : Set) (Ip : predicate -> W -> Prop) (n : nat) \n                     (l : nlist n (* nlist_pred n *)) : nlist_pa W n :=\n  match l with \n  | niln => niln_pa W\n  | consn m P l' => consn_pa W m (Ip P) (ineffective_pa_l W Ip m l')\n  end.\n\nLemma  ineffective_Ip2 : forall (W : Set) (l : list predicate) (Ip : predicate -> W -> Prop) ,  \n   alt_Ip_list Ip (nlist_list_pa W (length l) \n       (ineffective_pa_l W Ip (length l) (list_nlist(*_pred*) l))) l\n   = Ip.\nProof.\n  intros W l.\n  induction l.\n    intros.\n    simpl.\n    reflexivity.\n\n    intros.\n    simpl.\n    rewrite (IHl Ip).\n    rewrite unalt_fun.\n    reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------------- *)\n\nTheorem correctness_ST : forall (W:Set) (R: W -> W -> Prop) (x:FOvariable) \n                        (Iv: FOvariable -> W) (Ip: predicate -> W -> Prop) \n                        (phi:Modal) ,\n       (mturnst_frame W R phi) <-> \n                (SOturnst W Iv Ip R (uni_closed_SO (allFO x (ST phi x)))).\nProof.\n  intros.\n  unfold mturnst_frame.\n  split.\n    unfold uni_closed_SO.\n    intros.\n    apply nlist_list_closed_SO.\n    intros.\n    rewrite <- (Ip_V_Ip W) with (Ip := (alt_Ip_list Ip\n                  (nlist_list_pa W (length (preds_in (allFO x (ST phi x)))) pa_l)\n                  (preds_in (allFO x (ST phi x))))).\n    apply correctness_ST_model.\n    apply H.\n\n    intros.\n    apply (correctness_ST_model W R V phi x Iv).\n    remember (preds_in (allFO x (ST phi x))) as l.\n    assert (alt_Ip_list (V_to_Ip W V)\n       (nlist_list_pa W (length l)\n          (ineffective_pa_l W (V_to_Ip W V) (length l) (list_nlist(*_pred*) l))) l = \n              V_to_Ip W V) as H0.\n      rewrite Heql.\n      apply ineffective_Ip2.\n    rewrite <- H0.\n    apply (nlist_list_closed_SO W Iv R (allFO x (ST phi x)) l (V_to_Ip W V)).\n    rewrite Heql.\n    pose proof (Ip_uni_closed W (allFO x (ST phi x)) Iv Ip (V_to_Ip W V) R H) as H1.\n    apply H1.\nQed.\n\nTheorem correctness_ST_loc : forall (W:Set) (R: W -> W -> Prop) (x:FOvariable) \n                        (Iv: FOvariable -> W) (Ip: predicate -> W -> Prop) (w : W)\n                        (phi:Modal) ,\n       (mturnst_frame_loc W R w phi) <-> \n                (SOturnst W (alt_Iv Iv w x) Ip R (uni_closed_SO (ST phi x))).\nProof.\n  intros.\n  unfold mturnst_frame.\n  split.\n    unfold uni_closed_SO.\n    intros.\n    apply nlist_list_closed_SO.\n    intros.\n    rewrite <- (Ip_V_Ip W) with (Ip := (alt_Ip_list Ip\n                  (nlist_list_pa W (length (preds_in (ST phi x))) pa_l)\n                  (preds_in (ST phi x)))).\n    apply correctness_ST_world.\n    apply H.\n\n    intros. intros V.\n    apply (correctness_ST_world W R V phi w x Iv).\n    remember (preds_in (allFO x (ST phi x))) as l.\n    assert (alt_Ip_list (V_to_Ip W V)\n       (nlist_list_pa W (length l)\n          (ineffective_pa_l W (V_to_Ip W V) (length l) (list_nlist(*_pred*) l))) l = \n              V_to_Ip W V) as H0.\n      rewrite Heql.\n      apply ineffective_Ip2.\n    rewrite <- H0.\n    apply (nlist_list_closed_SO W _ R (ST phi x) l (V_to_Ip W V)).\n    rewrite Heql.\n    pose proof (Ip_uni_closed W (ST phi x) _ Ip (V_to_Ip W V) R H) as H1.\n    apply H1.\nQed.", "meta": {"author": "caitlindabrera", "repo": "Sahlqvist", "sha": "d0a755fb663a6cabc0babb691564cdf575fc8b36", "save_path": "github-repos/coq/caitlindabrera-Sahlqvist", "path": "github-repos/coq/caitlindabrera-Sahlqvist/Sahlqvist-d0a755fb663a6cabc0babb691564cdf575fc8b36/vsSahlq_AiML/Coq code/Correctness_ST.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.2743681360302911}}
{"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 RmiOps.Specs.realm_activate_ops.\nRequire Import RmiOps.LowSpecs.realm_activate_ops.\nRequire Import RmiOps.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       measurement_finish_spec\n       set_rd_state_spec\n    .\n\n  Lemma realm_activate_ops_spec_exists:\n    forall habd habd'  labd rd\n           (Hspec: realm_activate_ops_spec rd habd = Some habd')\n            (Hrel: relate_RData habd labd),\n    exists labd', realm_activate_ops_spec0 rd labd = Some labd' /\\ relate_RData habd' labd'.\n  Proof.\n    intros. destruct Hrel. inv id_rdata. destruct rd.\n    unfold realm_activate_ops_spec0, realm_activate_ops_spec in *.\n    repeat autounfold 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    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/RmiOps/RefProof/realm_activate_ops.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.27436813603029103}}
{"text": "Require Import List.\nRequire Import ListDec.\nExport ListNotations.\n\nRequire Import genT.\nRequire Import PeanoNat.\nRequire Import Lia.\n\nRequire Import Ensembles.\nRequire Import K_Syntax.\nRequire Import K_GHC.\nRequire Import K_logics.\nRequire Import K_extens_interactions.\n\nLemma wThm_irrel : forall A B Γ, wKH_prv (Γ, A --> (B --> A)).\nProof.\nintros A B Γ. apply Ax. apply AxRule_I. apply MA2_I. exists A. exists B. auto.\nQed.\n\nLemma wimp_Id_gen : forall A Γ, wKH_prv (Γ, A --> A).\nProof.\nintros A Γ.\napply MP with (ps:=[(Γ, (((A --> A) --> A) --> A)  --> (A --> A));(Γ, (((A --> A) --> A) --> A))]).\n2: apply MPRule_I. intros. inversion H ; subst.\napply MP with (ps:=[(Γ, (A --> ((A --> A) --> A)) --> (((A --> A) --> A) --> A) --> (A --> A));(Γ, (A --> ((A --> A) --> A)))]).\n2: apply MPRule_I. intros. inversion H0 ; subst.\napply Ax. apply AxRule_I. apply MA1_I. exists A.\nexists ((A --> A) --> A). exists A. auto. inversion H1. 2: inversion H2. subst.\napply Ax. apply AxRule_I. apply MA2_I. exists A.\nexists (A --> A). auto. inversion H0. subst. 2: inversion H1.\napply Ax. apply AxRule_I. apply MA3_I. exists A. exists A. auto.\nQed.\n\nLemma Help8 : forall A B C D Γ,\n  wKH_prv (Γ, (((A --> B) --> (C --> B)) --> D) --> ((C --> A) --> D)).\nProof.\nintros.\napply MP with (ps:=[(Γ, ((C --> A) --> (A --> B) --> (C --> B)) --> ((((A --> B) --> (C --> B)) --> D) --> (C --> A) --> D));\n(Γ, ((C --> A) --> (A --> B) --> (C --> B)))]).\n2: apply MPRule_I. intros.\ninversion H ; subst. apply Ax. apply AxRule_I. apply MA1_I.\nexists (C --> A). exists ((A --> B) --> C --> B). exists D. auto.\ninversion H0. subst. apply Ax. apply AxRule_I. apply MA1_I. exists C. exists A.\nexists B. auto. inversion H1.\nQed.\n\nLemma Help10 : forall A B C Γ,\n  wKH_prv (Γ, ((A --> B) --> C) --> (B --> C)).\nProof.\nintros.\napply MP with (ps:=[(Γ, (B --> (A --> B)) --> ((A --> B) --> C) --> (B --> C));\n(Γ, B --> (A --> B))]).\n2: apply MPRule_I. intros.\ninversion H ; subst. apply Ax. apply AxRule_I. apply MA1_I. exists B. exists (A --> B).\nexists C. auto.\ninversion H0. subst. apply Ax. apply AxRule_I. apply MA2_I. exists B. exists A ; auto.\ninversion H1.\nQed.\n\nLemma Help33 : forall A B C D Γ,\n  wKH_prv (Γ, (A --> (D --> C)) --> ((B --> D) --> (A --> (B --> C)))).\nProof.\nintros.\napply MP with (ps:=[(Γ, ((((D --> C) --> (B --> C)) --> (A --> (B --> C)))--> ((B --> D) --> (A --> (B --> C)))) --> ((A --> (D --> C)) --> ((B --> D) --> (A --> (B --> C)))));\n(Γ, (((D --> C) --> (B --> C)) --> (A --> (B --> C)))--> ((B --> D) --> (A --> (B --> C))))]).\n2: apply MPRule_I. intros.\ninversion H ; subst. apply Help8.\ninversion H0. subst. apply Help8.\ninversion H1.\nQed.\n\nLemma Contr_imp : forall A B Γ,\n  wKH_prv (Γ, (A --> A --> B) --> (A --> B)).\nProof.\nintros.\napply MP with (ps:=[(Γ, ((((A --> B) --> B)  --> (A --> B)) --> (A --> B)) --> ((A --> A --> B) --> (A --> B)));\n(Γ, (((A --> B) --> B)  --> (A --> B)) --> (A --> B))]).\n2: apply MPRule_I. intros. inversion H. subst. apply Help8.\ninversion H0. subst. 2: inversion H1. apply Ax. apply AxRule_I.\napply MA3_I. exists (A --> B). exists B. auto.\nQed.\n\nLemma Help105 : forall A B Γ,\n  wKH_prv (Γ, ((A --> B) --> A) -->  ((A --> B) --> B)).\nProof.\nintros.\napply MP with (ps:=[(Γ, (((A --> B) --> (A --> B) --> B) --> ((A --> B) --> B)) --> ((A --> B) --> A) -->  ((A --> B) --> B));\n(Γ, ((A --> B) --> (A --> B) --> B) --> ((A --> B) --> B))]).\n2: apply MPRule_I. intros. inversion H. subst.\napply Help8. inversion H0. 2: inversion H1. subst. apply Contr_imp.\nQed.\n\nLemma Help316 : forall A B Γ,\n  wKH_prv (Γ, A --> (A --> B) --> B).\nProof.\nintros.\napply MP with (ps:=[(Γ, (((A --> B) --> A) --> ((A --> B) --> B)) --> (A --> (A --> B) --> B));\n(Γ, ((A --> B) --> A) --> ((A --> B) --> B))]).\n 2: apply MPRule_I. intros. inversion H. subst.\napply Help10. inversion H0. subst. apply Help105.\ninversion H1.\nQed.\n\nLemma Swap_imp : forall A B C Γ,\n  wKH_prv (Γ, (A --> B --> C) --> (B --> A --> C)).\nProof.\nintros.\napply MP with (ps:=[(Γ, (B --> (B --> C) --> C) --> ((A --> B --> C) --> B --> A --> C));\n(Γ, B --> (B --> C) --> C)]).\n2: apply MPRule_I. intros. inversion H.\nsubst. apply Help33. inversion H0. subst. apply Help316.\ninversion H1.\nQed.\n\nLemma MetaSwap_imp : forall A B C Γ,\n  wKH_prv (Γ, A --> B --> C) ->\n  wKH_prv (Γ, B --> A --> C).\nProof.\nintros.\napply MP with (ps:=[(Γ, (A --> B --> C) --> (B --> A --> C));\n(Γ, A --> B --> C)]).\n2: apply MPRule_I. intros. inversion H0.\nsubst. apply Swap_imp. inversion H1. subst. auto.\ninversion H2.\nQed.\n\nLemma Trans_imp : forall A B C Γ,\n  wKH_prv (Γ, (A --> B --> C) --> (A --> B) --> A --> C).\nProof.\nintros.\napply MP with (ps:=[(Γ, ((B --> A --> C) --> (A --> B) --> A --> C) --> ((A --> B --> C) --> (A --> B) --> A --> C));\n(Γ, (B --> A --> C) --> (A --> B) --> A --> C)]). 2: apply MPRule_I.\nintros. inversion H. subst.\napply MP with (ps:=[(Γ, ((A --> B --> C) --> (B --> A --> C)) --> ((B --> A --> C) --> (A --> B) --> A --> C) --> ((A --> B --> C) --> (A --> B) --> A --> C));\n(Γ, (A --> B --> C) --> (B --> A --> C))]). 2: apply MPRule_I.\nintros. inversion H0. subst.\napply Ax. apply AxRule_I. apply MA1_I. exists (A --> B --> C).\nexists (B --> A --> C). exists ((A --> B) --> A --> C). auto. inversion H1.\n2: inversion H2. subst. apply Swap_imp. inversion H0.\nsubst.\napply MP with (ps:=[(Γ, ((A --> B) --> ((B --> A --> C) --> A --> C)) --> ((B --> A --> C) --> (A --> B) --> A --> C));\n(Γ, ((A --> B) --> ((B --> A --> C) --> A --> C)))]). 2: apply MPRule_I.\nintros. inversion H1. subst. apply Swap_imp.\ninversion H2. subst. 2: inversion H3.\napply MP with (ps:=[(Γ,  (((B --> A --> C) --> (A --> A --> C)) --> ((B --> A --> C) --> A --> C))--> ((A --> B) --> (B --> A --> C) --> A --> C));\n(Γ, (((B --> A --> C) --> (A --> A --> C)) --> ((B --> A --> C) --> A --> C)))]). 2: apply MPRule_I.\nintros. inversion H3. subst.\napply MP with (ps:=[(Γ,  ((A --> B) --> ((B --> A --> C) --> (A --> A --> C))) --> (((B --> A --> C) --> (A --> A --> C)) --> ((B --> A --> C) --> A --> C)) --> ((A --> B) --> (B --> A --> C) --> A --> C));\n(Γ, ((A --> B) --> ((B --> A --> C) --> (A --> A --> C))))]). 2: apply MPRule_I.\nintros. inversion H4. subst. apply Ax. apply AxRule_I.\napply MA1_I. exists (A --> B). exists (((B --> A --> C) --> (A --> A --> C))).\nexists ((B --> A --> C) --> (A --> C)). auto. inversion H5 ; subst.\n2: inversion H6. apply Ax. apply AxRule_I. apply MA1_I.\nexists A. exists B. exists (A --> C). auto. inversion H4. subst.\n2: inversion H5. 2: inversion H1.\napply MP with (ps:=[(Γ, ((A --> A --> C) --> (A --> C)) --> ((B --> A --> C) --> A --> A --> C) --> (B --> A --> C) --> A --> C);\n(Γ, ((A --> A --> C) --> (A --> C)))]). 2: apply MPRule_I. intros. inversion H5.\nsubst.\napply MP with (ps:=[(Γ, (((B --> A --> C) --> A --> A --> C) --> ((A --> A --> C) --> A --> C) --> (B --> A --> C) --> A --> C) --> (((A --> A --> C) --> A --> C) --> ((B --> A --> C) --> A --> A --> C) --> (B --> A --> C) --> A --> C));\n(Γ, ((B --> A --> C) --> A --> A --> C) --> ((A --> A --> C) --> A --> C) --> (B --> A --> C) --> A --> C)]).\n2: apply MPRule_I. intros. inversion H6. subst. apply Swap_imp. inversion H7.\nsubst. 2: inversion H8. apply Ax. apply AxRule_I. apply MA1_I.\nexists (B --> A --> C). exists (A --> A --> C). exists (A --> C). auto.\ninversion H6. 2: inversion H7. subst. apply Contr_imp.\nQed.\n\nTheorem wKH_Detachment_Theorem : forall s,\n           (wKH_prv s) ->\n           (forall A B Γ, (fst s = Γ) ->\n                          (snd s = A --> B) ->\n                          wKH_prv  (Union _ Γ (Singleton _ (A)), B)).\nProof.\nintros s D. induction D.\n(* Id *)\n- intros A B Γ id1 id2. inversion H. subst. simpl in id2. subst.\n  simpl. apply MP with (ps:=[(Union _ Γ0 (Singleton _ A), Imp A B);(Union _ Γ0 (Singleton _ A), A)]).\n  2: apply MPRule_I. intros. inversion H1. subst. apply Id.\n  apply IdRule_I. apply Union_introl. assumption. inversion H2. subst.\n  apply Id. apply IdRule_I. apply Union_intror. apply In_singleton. inversion H3.\n(* Ax *)\n- intros A B Γ id1 id2. inversion H. subst. simpl in id2. subst. simpl.\n  apply MP with (ps:=[(Union _ Γ0 (Singleton _ A), Imp A B);(Union _ Γ0 (Singleton _ A), A)]).\n  2: apply MPRule_I. intros. inversion H1. subst. apply Ax.\n  apply AxRule_I. assumption. inversion H2. subst. apply Id. apply IdRule_I.\n  apply Union_intror. apply In_singleton. inversion H3.\n(* MP *)\n- intros A B Γ id1 id2. inversion H1. subst. simpl in id2. subst. simpl.\n  assert (J01: List.In (Γ0, A0 --> A --> B) [(Γ0, A0 --> A --> B); (Γ0, A0)]). apply in_eq.\n  assert (J1: Γ0 = Γ0). reflexivity.\n  assert (J2: A0 --> A --> B = A0 --> A --> B). reflexivity.\n  pose (H0 (Γ0, A0 --> A --> B) J01 A0 (Imp A B) Γ0 J1 J2).\n  assert (wKH_prv (Γ0, A --> B)).\n  assert (J3: (forall A1 : MPropF, fst (Union _ Γ0 (Singleton _ A0), A --> B) A1 ->\n  wKH_prv (Γ0, A1))).\n  intro. simpl. intro. inversion H2. subst. apply Id.\n  apply IdRule_I. assumption. subst. inversion H3. subst.\n  assert (J02: List.In (Γ0, A1) [(Γ0, A1 --> A --> B); (Γ0, A1)]). apply in_cons. apply in_eq.\n  pose (H (Γ0, A1) J02). assumption.\n  pose (wKH_comp (Union _ Γ0 (Singleton _ A0), A --> B) w Γ0 J3). simpl in w0. assumption.\n  apply MP with (ps:=[(Union _ Γ0 (Singleton _ A), (Imp A B));(Union _ Γ0 (Singleton _ A), A)]).\n  2: apply MPRule_I. intros. inversion H3. subst.\n  apply MP with (ps:=[(Union _ Γ0 (Singleton _ A), Imp A0 (Imp A B));(Union _ Γ0 (Singleton _ A), A0)]).\n  2: apply MPRule_I. intros. inversion H4. subst.\n  assert (J4: Included _ (fst (Γ0, A0 --> A --> B)) (Union _ Γ0 (Singleton _ A))).\n  simpl. intro. intro. apply Union_introl. assumption. pose (H (Γ0, A0 --> A --> B) J01).\n  pose (wKH_monot (Γ0, A0 --> A --> B) w0 (Union _ Γ0 (Singleton _ A)) J4). assumption.\n  inversion H5. subst.\n  assert (J4: Included _ (fst (Γ0, A0 --> A --> B)) (Union _ Γ0 (Singleton _ A))).\n  simpl. intro. intro. apply Union_introl. assumption.\n  pose (wKH_monot (Γ0, A0)). apply w0. apply H. apply in_cons. apply in_eq.\n  auto. inversion H6. inversion H4. subst. apply Id. apply IdRule_I. apply Union_intror.\n  apply In_singleton. inversion H5.\n(* wNec *)\n- intros A B Γ id1 id2. inversion H1. subst. simpl in id2. subst. inversion id2.\nQed.\n\nTheorem wKH_Deduction_Theorem : forall s,\n           (wKH_prv s) ->\n           (forall A B Γ, (fst s = Union _ Γ (Singleton _ (A))) ->\n                          (snd s = B) ->\n                          wKH_prv (Γ, A --> B)).\nProof.\nintros s D. induction D.\n(* Id *)\n- intros A B Γ id1 id2. inversion H. subst. simpl in id1. subst. simpl. inversion H0.\n  + subst. apply MP with (ps:=[(Γ, A0 --> A --> A0);(Γ, A0)]). 2: apply MPRule_I. intros. inversion H2. subst.\n    apply wThm_irrel. inversion H3. subst. apply Id. apply IdRule_I. assumption.\n    inversion H4.\n  + subst. inversion H1. subst. apply wimp_Id_gen.\n(* Ax *)\n- intros A B Γ id1 id2. inversion H. subst. simpl in id1. subst. simpl.\n  apply MP with (ps:=[(Γ, A0 --> A --> A0);(Γ, A0)]). 2: apply MPRule_I. intros. inversion H1. subst.\n  apply wThm_irrel. inversion H2. subst.\n  apply Ax. apply AxRule_I. assumption. inversion H3.\n(* MP *)\n- intros A B Γ id1 id2. inversion H1. subst. simpl in id1. subst. simpl.\n  assert (J1: Union _ Γ (Singleton _ A) = Union _ Γ (Singleton _ A)). reflexivity.\n  assert (J2: A0 --> B0 = A0 --> B0). reflexivity.\n  assert (J20: List.In (Union (MPropF) Γ (Singleton (MPropF) A), A0 --> B0) [(Union (MPropF) Γ (Singleton (MPropF) A), A0 --> B0); (Union (MPropF) Γ (Singleton (MPropF) A), A0)]).\n  apply in_eq.\n  pose (H0 (Union (MPropF) Γ (Singleton (MPropF) A),  A0 --> B0) J20\n  A (Imp A0 B0) Γ J1 J2).\n  assert (J3: A0 = A0). reflexivity.\n  apply MP with (ps:=[(Γ, (A --> A0) --> (A --> B0));(Γ, A --> A0)]).\n  2: apply MPRule_I. intros. inversion H2. subst.\n  apply MP with (ps:=[(Γ, (A --> (A0 --> B0)) --> (A --> A0) --> (A --> B0));(Γ, A --> (A0 --> B0))]).\n  2: apply MPRule_I. intros. inversion H3. subst.\n  apply Trans_imp. inversion H4. subst. auto. inversion H5. inversion H3.\n  subst.\n  assert (J30: List.In (Union (MPropF) Γ (Singleton (MPropF) A), A0) [(Union (MPropF) Γ (Singleton (MPropF) A), A0 --> B0); (Union (MPropF) Γ (Singleton (MPropF) A), A0)]).\n  apply in_cons. apply in_eq. assert (J40: A0 = A0). reflexivity.\n  pose (H0 (Union (MPropF) Γ (Singleton (MPropF) A), A0) J30\n  A A0 Γ J1 J40). auto. inversion H4.\n(* wNec *)\n- intros A B Γ id1 id2. inversion H1. subst. simpl in id1. subst. simpl.\n  assert (J1: wKH_prv (Empty_set _, Box A0)).\n  apply wNec with (ps:=[(Empty_set _, A0)]). 2: apply wNecRule_I. assumption.\n  assert (J2: Included _ (fst (Empty_set _, Box A0)) Γ). intro. intro. inversion H2.\n  pose (wKH_monot (Empty_set _, Box A0) J1 Γ J2). simpl in w.\n  apply MP with (ps:=[(Γ, (Box A0) --> A --> (Box A0)); (Γ, Box A0)]).\n  2: apply MPRule_I. intros. inversion H2. subst. apply wThm_irrel.\n  inversion H3. subst. 2: inversion H4. assumption.\nQed.\n\nTheorem wKH_Detachment_Deduction_Theorem : forall A B Γ,\n      wKH_prv (Union _ Γ (Singleton _ (A)), B) <-> wKH_prv (Γ, A --> B).\nProof.\nintros. split ; intro.\napply wKH_Deduction_Theorem with (s:=(Union MPropF Γ (Singleton MPropF A), B)) ; auto.\napply wKH_Detachment_Theorem with (s:=(Γ, A --> B)) ; auto.\nQed.\n\n(* ---------------------------------------------------------------------------------------------------------- *)\n\n(* Some results about remove. *)\n\nLemma In_remove : forall (A : MPropF) B (l : list (MPropF)), List.In A (remove eq_dec_form B l) -> List.In A l.\nProof.\nintros A B. induction l.\n- simpl. auto.\n- intro. simpl in H. destruct (eq_dec_form B a).\n  * subst. apply in_cons. apply IHl. assumption.\n  * inversion H.\n    + subst. apply in_eq.\n    + subst. apply in_cons. apply IHl. auto.\nQed.\n\nLemma InT_remove : forall (A : MPropF) B (l : list (MPropF)), InT A (remove eq_dec_form B l) -> InT A l.\nProof.\nintros A B. induction l.\n- simpl. auto.\n- intro. simpl in H. destruct (eq_dec_form B a).\n  * subst. apply InT_cons. apply IHl. assumption.\n  * inversion H.\n    + subst. apply InT_eq.\n    + subst. apply InT_cons. apply IHl. auto.\nQed.\n\nLemma NoDup_remove : forall A (l : list (MPropF)), NoDup l -> NoDup (remove eq_dec_form A l).\nProof.\nintro A. induction l.\n- intro. simpl. apply NoDup_nil.\n- intro H. simpl. destruct (eq_dec_form A a).\n  * subst. apply IHl. inversion H. assumption.\n  * inversion H. subst. apply NoDup_cons. intro. apply H2. apply In_remove with (B:= A).\n    assumption. apply IHl. assumption.\nQed.\n\n\n(* To help for the results about sKH. *)\n\nLemma eq_dec_nat : forall (n m : nat), (n = m) + (n <> m).\nProof.\ninduction n.\n- destruct m.\n  * auto.\n  * auto.\n- intro m. destruct m.\n  * auto.\n  * destruct IHn with (m:=m).\n    + left. lia.\n    + right. lia.\nQed.\n\nLemma thm_irrel_Imp_Box_power : forall (n : nat) (A B : MPropF),\n  wKH_prv (Empty_set _, B --> (Imp_Box_power n A B)).\nProof.\ninduction n ; intros ; simpl.\n- apply wThm_irrel.\n- pose (wKH_Deduction_Theorem (Singleton _ B,  A --> Imp_Box_power n (Box A) B)).\n  apply w ; auto. 2: simpl. clear w.\n  pose (wKH_Deduction_Theorem (Union _ (Singleton _ B) (Singleton _ A),  Imp_Box_power n (Box A) B)).\n  apply w ; auto. clear w. remember (Union MPropF (Singleton MPropF B) (Singleton MPropF A)) as X.\n  apply MP with (ps:=[(X, B --> Imp_Box_power n (Box A) B);(X, B)]).\n  2: apply MPRule_I. intros. inversion H. rewrite <- H0.\n  pose (wKH_monot (Empty_set _, B --> Imp_Box_power n (Box A) B)). apply w ; auto.\n  intro. simpl ; intro. inversion H1. inversion H0. subst. 2: inversion H1.\n  apply Id. apply IdRule_I. apply Union_introl. apply In_singleton.\n  apply Extensionality_Ensembles. split ; intro ; intros. apply Union_intror ; auto.\n  inversion H. inversion H0. auto.\nQed.\n\nLemma Imp_Box_power_le : forall (n m: nat) (A B : MPropF), (n <= m) ->\n  wKH_prv (Empty_set _, (Imp_Box_power n A B) --> (Imp_Box_power m A B)).\nProof.\ninduction n.\n- simpl. destruct m.\n  + simpl. intros. apply wimp_Id_gen.\n  + intros. simpl. assert (J1: 0 <= m). lia.\n     pose (wKH_Deduction_Theorem (Singleton _ (A --> B),  A --> Imp_Box_power m (Box A) B)).\n     apply w ; auto. 2: simpl. clear w.\n     pose (wKH_Deduction_Theorem (Union _ (Singleton _ (A --> B)) (Singleton _ A),  Imp_Box_power m (Box A) B)).\n     apply w ; auto. clear w. remember (Union MPropF (Singleton MPropF (A --> B)) (Singleton MPropF A)) as X.\n     apply MP with (ps:=[(X, B --> Imp_Box_power m (Box A) B);(X, B)]).\n     2: apply MPRule_I. intros. inversion H0. rewrite <- H1.\n     pose (wKH_monot (Empty_set _, B --> Imp_Box_power m (Box A) B)). apply w.\n     apply thm_irrel_Imp_Box_power. intro. intros. inversion H2. inversion H1.\n     rewrite <- H2. 2: inversion H2.\n     apply MP with (ps:=[(X, A --> B);(X, A)]). 2: apply MPRule_I.\n     intros. inversion H3. subst. apply Id. apply IdRule_I. apply Union_introl.\n     apply In_singleton. inversion H4. subst. 2: inversion H5. apply Id.\n     apply IdRule_I. apply Union_intror. apply In_singleton.\n     apply Extensionality_Ensembles. split ; intro ; intros. apply Union_intror. auto.\n     inversion H0. subst. inversion H1. auto.\n- simpl. destruct m.\n  + intros. inversion H.\n  + intros. simpl.\n     pose (wKH_Deduction_Theorem (Singleton _ (A --> Imp_Box_power n (Box A) B),  A --> Imp_Box_power m (Box A) B)).\n     apply w ; auto. 2: simpl. clear w.\n     pose (wKH_Deduction_Theorem (Union _ (Singleton _ (A --> Imp_Box_power n (Box A) B)) (Singleton _ A),  Imp_Box_power m (Box A) B)).\n     apply w ; auto. clear w. remember (Union MPropF (Singleton MPropF (A --> Imp_Box_power n (Box A) B)) (Singleton MPropF A)) as X.\n     apply MP with (ps:=[(X, Imp_Box_power n (Box A) B --> Imp_Box_power m (Box A) B);(X, Imp_Box_power n (Box A) B)]).\n     2: apply MPRule_I. intros. inversion H0. rewrite <- H1.\n     pose (wKH_monot (Empty_set _, Imp_Box_power n (Box A) B --> Imp_Box_power m (Box A) B)). apply w. clear w.\n     apply IHn ; lia. intro. intros. inversion H2. inversion H1.\n     rewrite <- H2. 2: inversion H2.\n     apply MP with (ps:=[(X, A --> Imp_Box_power n (Box A) B);(X, A)]). 2: apply MPRule_I.\n     intros. inversion H3. subst. apply Id. apply IdRule_I. apply Union_introl.\n     apply In_singleton. inversion H4. subst. 2: inversion H5. apply Id.\n     apply IdRule_I. apply Union_intror. apply In_singleton.\n     apply Extensionality_Ensembles. split ; intro ; intros. apply Union_intror. auto.\n     inversion H0. subst. inversion H1. auto.\nQed.\n\nLemma Imp_Box_power_MP_deep : forall (n : nat) (A B C : MPropF),\n  wKH_prv (Empty_set _, (Imp_Box_power n A B) --> (Imp_Box_power n A (B --> C)) --> (Imp_Box_power n A C)).\nProof.\ninduction n.\n- intros. simpl.\n  pose (wKH_Deduction_Theorem (Singleton _ (A --> B),  (A --> B --> C) --> A --> C)).\n  apply w ; auto. 2: simpl. clear w.\n  pose (wKH_Deduction_Theorem (Union _ (Singleton _ (A --> B)) (Singleton _ (A --> B --> C)),  A --> C)).\n  apply w ; auto. clear w.\n  pose (wKH_Deduction_Theorem (Union _ (Union _ (Singleton _ (A --> B)) (Singleton _ (A --> B --> C))) (Singleton _ A),  C)).\n  apply w ; auto. clear w. remember (Union MPropF (Union MPropF (Singleton MPropF (A --> B)) (Singleton MPropF (A --> B --> C))) (Singleton MPropF A)) as X.\n  apply MP with (ps:=[(X, B --> C);(X, B)]). 2: apply MPRule_I.\n  intros. inversion H. rewrite <- H0.\n  apply MP with (ps:=[(X, A --> B --> C);(X, A)]). 2: apply MPRule_I.\n  intros. inversion H1. rewrite <- H2. apply Id. apply IdRule_I.\n  subst. apply Union_introl. apply Union_intror. apply In_singleton.\n  inversion H2. rewrite <- H3. apply Id. apply IdRule_I. subst.\n  apply Union_intror. apply In_singleton. inversion H3. inversion H0.\n  rewrite <- H1. apply MP with (ps:=[(X, A --> B);(X, A)]).\n  intros. 2: apply MPRule_I. inversion H2. rewrite <- H3. apply Id.\n  apply IdRule_I. subst. apply Union_introl. apply Union_introl. apply In_singleton.\n  inversion H3. rewrite <- H4. apply Id. apply IdRule_I. subst. apply Union_intror.\n  apply In_singleton. inversion H4. inversion H1. apply Extensionality_Ensembles.\n  split. intro. intros. inversion H. subst. apply Union_intror. apply In_singleton.\n  intro. intros. inversion H. subst. inversion H0. subst. auto.\n- intros. simpl.\n  pose (wKH_Deduction_Theorem (Singleton _ (A --> Imp_Box_power n (Box A) B),  (A --> (Imp_Box_power n (Box A) (B --> C))) --> A --> Imp_Box_power n (Box A) C)).\n  apply w ; auto. 2: simpl. clear w.\n  pose (wKH_Deduction_Theorem (Union _ (Singleton _ (A --> Imp_Box_power n (Box A) B)) (Singleton _ (A --> (Imp_Box_power n (Box A) (B --> C)))),  A --> Imp_Box_power n (Box A) C)).\n  apply w ; auto. clear w.\n  pose (wKH_Deduction_Theorem (Union _ (Union _ (Singleton _ (A --> Imp_Box_power n (Box A) B)) (Singleton _ (A --> (Imp_Box_power n (Box A) (B --> C))))) (Singleton _ A),  Imp_Box_power n (Box A) C)).\n  apply w ; auto. clear w. remember (Union MPropF (Union MPropF (Singleton MPropF (A --> Imp_Box_power n (Box A) B)) (Singleton MPropF (A --> (Imp_Box_power n (Box A) (B --> C))))) (Singleton MPropF A)) as X.\n  apply MP with (ps:=[(X, (Imp_Box_power n (Box A) (B --> C)) --> Imp_Box_power n (Box A) C);\n  (X, (Imp_Box_power n (Box A) (B --> C)))]). 2: apply MPRule_I.\n  intros. inversion H. rewrite <- H0.\n  apply MP with (ps:=[(X, (Imp_Box_power n (Box A) B) --> (Imp_Box_power n (Box A) (B --> C) --> Imp_Box_power n (Box A) C));(X, Imp_Box_power n (Box A) B)]). 2: apply MPRule_I.\n  intros. inversion H1. rewrite <- H2.\n  pose (wKH_monot ((Empty_set _, Imp_Box_power n (Box A) B --> Imp_Box_power n (Box A) (B --> C) --> Imp_Box_power n (Box A) C))).\n  apply w. apply IHn. intro. simpl. intros. inversion H3.\n  inversion H2. rewrite <- H3.\n  apply MP with (ps:=[(X, A --> Imp_Box_power n (Box A) B);(X, A)]). 2: apply MPRule_I.\n  intros. inversion H4. rewrite <- H5. apply Id. apply IdRule_I.\n  subst. apply Union_introl. apply Union_introl. apply In_singleton.\n  inversion H5. rewrite <- H6. subst. apply Id. apply IdRule_I.\n  apply Union_intror. apply In_singleton. inversion H6. inversion H3.\n  inversion H0. rewrite <- H1.\n  apply MP with (ps:=[(X, A --> Imp_Box_power n (Box A) (B --> C));(X, A)]). 2: apply MPRule_I.\n  intros. inversion H2. rewrite <- H3. subst. apply Id. apply IdRule_I. apply Union_introl.\n  apply Union_intror. apply In_singleton. inversion H3. subst. apply Id. apply IdRule_I.\n  apply Union_intror. apply In_singleton. inversion H4. inversion H1.\n  apply Extensionality_Ensembles. split. intro. intros. inversion H. subst.\n  apply Union_intror. apply In_singleton. intro. intros. inversion H. subst. inversion H0. subst. auto.\nQed.\n\nLemma Distrib_Box_Imp_Box_power : forall (n : nat) (A B : MPropF) Γ,\n  wKH_prv (Γ, (Box (Imp_Box_power n A B)) --> (Imp_Box_power n (Box A) (Box B))).\nProof.\ninduction n ; intros ; cbn.\n- apply Ax. apply AxRule_I. apply MA5_I. exists A. exists B. auto.\n- pose (wKH_Deduction_Theorem (Union _ Γ (Singleton _ (Box (A --> Imp_Box_power n (Box A) B))), Box A --> Imp_Box_power n (Box (Box A)) (Box B))).\n  apply w ; auto. clear w.\n  pose (wKH_Deduction_Theorem (Union _ (Union _ Γ (Singleton _ (Box (A --> Imp_Box_power n (Box A) B)))) (Singleton _ (Box A)), Imp_Box_power n (Box (Box A)) (Box B))).\n  apply w ; auto. clear w. remember (Union MPropF (Union MPropF Γ (Singleton MPropF (Box (A --> Imp_Box_power n (Box A) B)))) (Singleton MPropF (Box A))) as X.\n  apply MP with (ps:=[(X, Box (Imp_Box_power n (Box A) B) --> Imp_Box_power n (Box (Box A)) (Box B));(X, Box (Imp_Box_power n (Box A) B))]).\n  2: apply MPRule_I. intros. inversion H. rewrite <- H0.\n  pose (wKH_monot (Γ, Box (Imp_Box_power n (Box A) B) --> Imp_Box_power n (Box (Box A)) (Box B))).\n  apply w ; cbn ; auto. clear w. subst. intro. intros. apply Union_introl. apply Union_introl. auto.\n  inversion H0. rewrite <- H1. 2: inversion H1.\n  apply MP with (ps:=[(X, Box A --> Box (Imp_Box_power n (Box A) B));(X, Box A)]).\n  2: apply MPRule_I. intros. inversion H2. rewrite <- H3.\n  apply MP with (ps:=[(X, Box (A --> Imp_Box_power n (Box A) B) --> Box A --> Box (Imp_Box_power n (Box A) B));(X, Box (A --> Imp_Box_power n (Box A) B))]).\n  2: apply MPRule_I. intros. inversion H4. rewrite <- H5. apply Ax. apply AxRule_I.\n  apply MA5_I. exists A. exists (Imp_Box_power n (Box A) B). auto. inversion H5.\n  rewrite <- H6. apply Id. subst. apply IdRule_I. apply Union_introl. apply Union_intror.\n  apply In_singleton. inversion H6. inversion H3. subst. apply Id. apply IdRule_I.\n  apply Union_intror. apply In_singleton. inversion H4.\nQed.\n\n(* To help for the completeness of wKH. *)\n\nLemma NegNeg_elim : forall Γ A, wKH_prv (Γ, (A --> Bot) --> Bot) ->\n    wKH_prv (Γ, A).\nProof.\nintros.\napply MP with (ps:=[(Γ, ((A --> Bot) --> A) --> A);(Γ, (A --> Bot) --> A)]).\n2: apply MPRule_I. intros. inversion H0. subst.\napply Ax. apply AxRule_I. apply MA3_I. exists A. exists Bot. auto.\ninversion H1. subst. 2: inversion H2.\napply wKH_Deduction_Theorem with (s:=(Union _ Γ (Singleton _ (A --> Bot)), A)) ; auto.\napply MP with (ps:=[(Union MPropF Γ (Singleton MPropF (A --> Bot)), Bot --> A);\n(Union MPropF Γ (Singleton MPropF (A --> Bot)), Bot)]).\n2: apply MPRule_I. intros. inversion H2. subst. apply Ax. apply AxRule_I.\napply MA4_I. exists A ; auto. inversion H3. subst. 2: inversion H4.\napply wKH_Detachment_Theorem with (s:=(Γ, (A --> Bot) --> Bot)) ; auto.\nQed.\n\n(* To help for the Lindenbaum lemma. *)\n\nLemma Explosion : forall Γ A B,\n  wKH_prv (Γ, (B --> Bot) --> (B --> A)).\nProof.\nintros.\napply wKH_Deduction_Theorem with (s:=(Union _ Γ (Singleton _ (B --> Bot)),  B --> A)) ; auto.\napply wKH_Deduction_Theorem with (s:=(Union _ (Union _ Γ (Singleton _ (B --> Bot))) (Singleton _ B), A)) ; auto.\nremember (Union MPropF (Union MPropF Γ (Singleton MPropF (B --> Bot))) (Singleton MPropF B)) as X.\napply MP with (ps:=[(X, Bot --> A);(X, Bot)]). 2: apply MPRule_I.\nintros. inversion H. subst. apply Ax. apply AxRule_I. apply MA4_I. exists A ; auto.\ninversion H0. 2: inversion H1. rewrite <- H1.\napply MP with (ps:=[(X, B --> Bot);(X, B)]). 2: apply MPRule_I.\nintros. inversion H2. subst. apply Id. apply IdRule_I. apply Union_introl.\napply Union_intror. apply In_singleton. inversion H3. subst.\napply Id. apply IdRule_I. apply Union_intror. apply In_singleton. inversion H4.\nQed.\n\nLemma All_cases_LEM : forall Γ A B,\n  wKH_prv (Γ, ((B --> Bot) --> A) --> (B --> A) --> A).\nProof.\nintros.\napply wKH_Deduction_Theorem with (s:=(Union _ Γ (Singleton _ ((B --> Bot) --> A)),  (B --> A) --> A)) ; auto.\napply wKH_Deduction_Theorem with (s:=(Union _ (Union _ Γ (Singleton _ ((B --> Bot) --> A))) (Singleton _ (B --> A)), A)) ; auto.\nremember (Union MPropF (Union MPropF Γ (Singleton MPropF ((B --> Bot) --> A))) (Singleton MPropF (B --> A))) as X.\napply NegNeg_elim.\napply wKH_Deduction_Theorem with (s:=(Union _ X (Singleton _ (A --> Bot)), Bot)) ; auto.\nremember (Union MPropF X (Singleton MPropF (A --> Bot))) as X0.\napply MP with (ps:=[(X0, A --> Bot);(X0, A)]). 2: apply MPRule_I.\nintros. inversion H. rewrite <- H0. apply Id. apply IdRule_I. subst.\napply Union_intror. apply In_singleton. inversion H0. 2: inversion H1.\nrewrite <- H1.\napply MP with (ps:=[(X0, (B --> Bot) --> A);(X0, B --> Bot)]). 2: apply MPRule_I.\nintros. inversion H2. rewrite <- H3. apply Id. apply IdRule_I. subst.\napply Union_introl. apply Union_introl. apply Union_intror. apply In_singleton.\ninversion H3. rewrite <- H4. 2: inversion H4.\napply wKH_Deduction_Theorem with (s:=(Union _ X0 (Singleton _ B), Bot)) ; auto.\napply MP with (ps:=[(Union MPropF X0 (Singleton MPropF B), A --> Bot);\n(Union MPropF X0 (Singleton MPropF B), A)]). 2: apply MPRule_I.\nintros. inversion H5. rewrite <- H6. apply Id. subst. apply IdRule_I.\napply Union_introl. apply Union_intror. apply In_singleton.\ninversion H6. 2: inversion H7. rewrite <- H7.\napply MP with (ps:=[(Union MPropF X0 (Singleton MPropF B), B --> A);\n(Union MPropF X0 (Singleton MPropF B), B)]). 2: apply MPRule_I.\nintros. inversion H8. rewrite <- H9. apply Id. apply IdRule_I. subst.\napply Union_introl. apply Union_introl. apply Union_intror. apply In_singleton.\ninversion H9. subst. apply Id. apply IdRule_I. apply Union_intror. apply In_singleton.\ninversion H10.\nQed.\n\nLemma Imp_list_Imp : forall l Γ A B,\n    wKH_prv (Γ, list_Imp (A --> B) l) <->\n    wKH_prv (Γ, A --> list_Imp B l).\nProof.\ninduction l ; simpl ; intros.\n- split ; intro ; auto.\n- split ; intro.\n  * apply wKH_Deduction_Theorem with (s:=(Union _ Γ (Singleton _ A), a --> list_Imp B l)) ; auto.\n    apply wKH_Deduction_Theorem with (s:=(Union _ (Union _ Γ (Singleton _ A)) (Singleton _ a), list_Imp B l)) ; auto.\n    assert (Union MPropF (Union MPropF Γ (Singleton MPropF A)) (Singleton MPropF a) =\n    Union MPropF (Union MPropF Γ (Singleton MPropF a)) (Singleton MPropF A)).\n    apply Extensionality_Ensembles. split ; intro ; intros. inversion H0. subst.\n    inversion H1. subst. apply Union_introl. apply Union_introl  ; auto. subst.\n    inversion H2. subst. apply Union_intror. apply In_singleton. subst. apply Union_introl.\n    apply Union_intror. auto. inversion H0. subst. inversion H1. subst. apply Union_introl.\n    apply Union_introl. auto. subst. apply Union_intror. auto. subst.\n    apply Union_introl. apply Union_intror. auto. rewrite H0.\n    apply wKH_Detachment_Theorem with (s:=(Union MPropF Γ (Singleton MPropF a),\n    A --> list_Imp B l)) ; auto. apply IHl.\n    apply wKH_Detachment_Theorem with (s:=(Γ, a --> list_Imp (A --> B) l)) ; auto.\n  * apply wKH_Deduction_Theorem with (s:=(Union _ Γ (Singleton _ a), list_Imp (A --> B) l)) ; auto.\n    apply IHl.\n    apply wKH_Deduction_Theorem with (s:=(Union _ (Union _ Γ (Singleton _ a)) (Singleton _ A), list_Imp B l)) ; auto.\n    assert (Union MPropF (Union MPropF Γ (Singleton MPropF A)) (Singleton MPropF a) =\n    Union MPropF (Union MPropF Γ (Singleton MPropF a)) (Singleton MPropF A)).\n    apply Extensionality_Ensembles. split ; intro ; intros. inversion H0. subst.\n    inversion H1. subst. apply Union_introl. apply Union_introl  ; auto. subst.\n    inversion H2. subst. apply Union_intror. apply In_singleton. subst. apply Union_introl.\n    apply Union_intror. auto. inversion H0. subst. inversion H1. subst. apply Union_introl.\n    apply Union_introl. auto. subst. apply Union_intror. auto. subst.\n    apply Union_introl. apply Union_intror. auto. rewrite <- H0. clear H0.\n    apply wKH_Detachment_Theorem with (s:=(Union MPropF Γ (Singleton MPropF A),\n    a --> list_Imp B l)) ; auto.\n    apply wKH_Detachment_Theorem with (s:=(Γ, A --> a --> list_Imp B l)) ; auto.\nQed.\n\nLemma wKH_Imp_list_Detachment_Deduction_Theorem : forall l (Γ: Ensemble MPropF) A,\n    (forall B : MPropF, (Γ B -> List.In B l) * (List.In B l -> Γ B)) ->\n    ((wKH_prv (Γ, A)) <-> (wKH_prv (Empty_set _, list_Imp A l))).\nProof.\ninduction l ; simpl ; intros.\n- split ; intro.\n  * assert (Γ = Empty_set MPropF). apply Extensionality_Ensembles.\n    split ; intro ; intros. apply H in H1. exfalso ; auto. inversion H1.\n    rewrite H1 in H0 ; auto.\n  * assert (Γ = Empty_set MPropF). apply Extensionality_Ensembles.\n    split ; intro ; intros. apply H in H1. exfalso ; auto. inversion H1.\n    rewrite H1 ; auto.\n- split ; intro.\n  * assert (decidable_eq MPropF). unfold decidable_eq. intros.\n    destruct (eq_dec_form x y). subst. unfold Decidable.decidable. auto.\n    unfold Decidable.decidable. auto.\n    pose (In_decidable H1 a l). destruct d.\n    + assert (J0: forall B : MPropF, (Γ B -> List.In B l) * (List.In B l -> Γ B)).\n       intros. split ; intro. pose (H B). destruct p. apply o in H3. destruct H3.\n       subst. auto. auto. apply H. auto.\n       pose (IHl Γ A J0). apply i in H0.\n       apply MP with (ps:=[(Empty_set MPropF, (list_Imp A l) --> (a --> list_Imp A l));\n       (Empty_set MPropF, list_Imp A l)]).\n       2: apply MPRule_I. intros. inversion H3. subst.\n       apply Ax. apply AxRule_I. apply MA2_I. exists (list_Imp A l).\n       exists a. auto. inversion H4. subst. 2: inversion H5. auto.\n    + assert (J0: forall B : MPropF,\n       ((fun y : MPropF => In MPropF Γ y /\\ y <> a) B -> List.In B l) *\n       (List.In B l -> (fun y : MPropF => In MPropF Γ y /\\ y <> a) B)).\n       intros. split ; intro. destruct H3. pose (H B). destruct p.\n       apply o in H3. destruct H3 ; subst. exfalso. apply H4 ; auto.\n       auto. split ; auto. apply H ; auto. intro. subst. auto.\n       pose (IHl (fun y => (In _ Γ y) /\\ (y <> a)) (a --> A) J0).\n       destruct i. apply Imp_list_Imp. apply H3.\n       apply wKH_Deduction_Theorem with (s:=(Γ, A)) ; simpl ; auto.\n       apply Extensionality_Ensembles. split ; intro ; intros. unfold In.\n       destruct (eq_dec_form a x). subst. apply Union_intror. apply In_singleton.\n       apply Union_introl. unfold In. split ; auto. inversion H5. subst.\n       inversion H6. auto. subst. inversion H6. subst. apply H. auto.\n  * assert (decidable_eq MPropF). unfold decidable_eq. intros.\n    destruct (eq_dec_form x y). subst. unfold Decidable.decidable. auto.\n    unfold Decidable.decidable. auto.\n    pose (In_decidable H1 a l). destruct d.\n    + assert (J0: forall B : MPropF, (Γ B -> List.In B l) * (List.In B l -> Γ B)).\n       intros. split ; intro. pose (H B). destruct p. apply o in H3. destruct H3.\n       subst. auto. auto. apply H. auto.\n       apply Imp_list_Imp in H0.\n       pose (IHl Γ (a --> A)).\n       apply MP with (ps:=[(Γ, a --> A);(Γ, a)]).\n       2: apply MPRule_I. intros. inversion H3. subst. apply i. intros.\n       split ; intros. pose (H B). destruct p. apply o in H4. destruct H4 ; subst.\n       auto. auto. apply H. auto. auto. inversion H4 ; subst.\n       apply Id. apply IdRule_I. apply H. auto. inversion H5.\n    + assert (J0: forall B : MPropF,\n       ((fun y : MPropF => In MPropF Γ y /\\ y <> a) B -> List.In B l) *\n       (List.In B l -> (fun y : MPropF => In MPropF Γ y /\\ y <> a) B)).\n       intros. split ; intro. destruct H3. pose (H B). destruct p.\n       apply o in H3. destruct H3 ; subst. exfalso. apply H4 ; auto.\n       auto. split ; auto. apply H ; auto. intro. subst. auto.\n       pose (IHl (fun y => (In _ Γ y) /\\ (y <> a)) (a --> A) J0).\n       destruct i. apply Imp_list_Imp in H0. apply H4 in H0.\n       pose (wKH_Detachment_Theorem (fun y : MPropF => In MPropF Γ y /\\ y <> a, a --> A)\n       H0 a A (fun y : MPropF => In MPropF Γ y /\\ y <> a)). simpl in w.\n       assert (Γ = Union MPropF (fun y : MPropF => In MPropF Γ y /\\ y <> a)\n       (Singleton MPropF a)).\n       apply Extensionality_Ensembles. split ; intro ; intros. unfold In.\n       destruct (eq_dec_form a x). subst. apply Union_intror. apply In_singleton.\n       apply Union_introl. unfold In. split ; auto. inversion H5. subst.\n       inversion H6. auto. subst. inversion H6. subst. apply H. auto.\n       rewrite H5. apply w ; auto.\nQed.\n\nLemma K_list_Imp : forall l Γ A,\nwKH_rules (Γ, Box (list_Imp A l) --> list_Imp (Box A) (Box_list l)).\nProof.\ninduction l ; simpl ; intros.\n- apply wimp_Id_gen.\n- apply wKH_Deduction_Theorem with (s:=(Union _ Γ (Singleton _ (Box (a --> list_Imp A l))),  Box a --> list_Imp (Box A) (Box_list l))) ; auto.\n  apply wKH_Deduction_Theorem with (s:=(Union _ (Union _ Γ (Singleton _ (Box (a --> list_Imp A l)))) (Singleton _ (Box a)),  list_Imp (Box A) (Box_list l))) ; auto.\n  remember (Union MPropF (Union MPropF Γ (Singleton MPropF (Box (a --> list_Imp A l)))) (Singleton MPropF (Box a))) as X.\n  apply MP with (ps:=[(X, Box (list_Imp A l) --> list_Imp (Box A) (Box_list l));(X,Box (list_Imp A l))]).\n  2: apply MPRule_I. intros. inversion H. rewrite <- H0. auto.\n  inversion H0. 2: inversion H1. rewrite <- H1.\n  apply MP with (ps:=[(X, Box a --> Box (list_Imp A l));(X, Box a)]).\n  2: apply MPRule_I. intros. inversion H2. rewrite <- H3.\n  apply MP with (ps:=[(X, Box (a --> list_Imp A l) --> (Box a --> Box (list_Imp A l)));(X, Box (a --> list_Imp A l))]).\n  2: apply MPRule_I. intros. inversion H4. rewrite <- H5. apply Ax.\n  apply AxRule_I. apply MA5_I. exists a. exists (list_Imp A l). auto.\n  inversion H5. subst. apply Id. apply IdRule_I. apply Union_introl.\n  apply Union_intror. apply In_singleton. inversion H6.\n  inversion H3. subst. apply Id. apply IdRule_I. apply Union_intror.\n  apply In_singleton. inversion H4.\nQed.\n\nLemma Box_distrib_list_Imp : forall l A,\n    wKH_prv (Empty_set MPropF, list_Imp A l) ->\n    wKH_prv (Empty_set MPropF, list_Imp (Box A) (Box_list l)).\nProof.\ninduction l ; simpl ; intros.\n- apply wNec with (ps:=[(Empty_set MPropF, A)]).\n  2: apply wNecRule_I. intros. inversion H0 ; subst ; auto.\n  inversion H1.\n- apply MP with (ps:=[(Empty_set MPropF, (Box (list_Imp A l) --> list_Imp (Box A) (Box_list l)) --> (Box a --> list_Imp (Box A) (Box_list l)));\n  (Empty_set MPropF, Box (list_Imp A l) --> list_Imp (Box A) (Box_list l))]).\n  2: apply MPRule_I. intros. inversion H0. subst.\n  apply MP with (ps:=[(Empty_set MPropF, (Box a --> Box (list_Imp A l)) --> ((Box (list_Imp A l) --> list_Imp (Box A) (Box_list l)) --> (Box a --> list_Imp (Box A) (Box_list l))));\n  (Empty_set MPropF, Box a --> Box (list_Imp A l))]).\n  2: apply MPRule_I. intros. inversion H1. subst.\n  apply Ax. apply AxRule_I. apply MA1_I. exists (Box a).\n  exists (Box (list_Imp A l)). exists (list_Imp (Box A) (Box_list l)). auto.\n  inversion H2 ; subst. 2: inversion H3.\n  apply MP with (ps:=[(Empty_set MPropF, Box (a --> (list_Imp A l)) --> (Box a --> Box (list_Imp A l)));\n  (Empty_set MPropF, Box (a --> (list_Imp A l)))]).\n  2: apply MPRule_I. intros. inversion H3. subst.\n  apply Ax. apply AxRule_I. apply MA5_I. exists a. exists (list_Imp A l).\n  auto. inversion H4. subst. 2: inversion H5.\n  apply wNec with (ps:=[(Empty_set MPropF, a --> list_Imp A l)]).\n  2: apply wNecRule_I. intros. inversion H5 ; subst. 2: inversion H6.\n  auto. inversion H1 ; subst. 2: inversion H2. apply K_list_Imp.\nQed.\n\nLemma In_list_In_Box_list : forall l A,\n    List.In A l -> List.In (Box A) (Box_list l).\nProof.\ninduction l ; intros ; simpl.\n- inversion H.\n- inversion H ;  subst ; auto.\nQed.\n\nLemma In_Box_list_In_list : forall l A,\n     List.In A (Box_list l) -> (exists B, List.In B l /\\ A = Box B).\nProof.\ninduction l ; simpl ; intros.\n- inversion H.\n- destruct H ; subst. exists a. split ; auto. apply IHl in H.\n  destruct H. destruct H. subst. exists x ; auto.\nQed.\n\nLemma K_rule : forall Γ A, wKH_prv (Γ, A) ->\n    wKH_prv ((fun x => (exists B, In _ Γ B /\\ x = Box B)), Box A).\nProof.\nintros. apply wKH_finite in H. simpl in H. destruct H. destruct H. destruct p.\ndestruct e.\npose (wKH_monot (fun x1 : MPropF => exists B : MPropF, List.In B x0 /\\ x1 = Box B, Box A)).\napply w0 ; simpl ; auto. clear w0.\npose (wKH_Imp_list_Detachment_Deduction_Theorem x0 x A H).\napply i0 in w. clear i0.\napply Box_distrib_list_Imp in w.\nremember (fun y => exists B : MPropF, List.In B x0 /\\ y = Box B) as Boxed_x.\npose (wKH_Imp_list_Detachment_Deduction_Theorem (Box_list x0) Boxed_x  (Box A)).\napply i0 in w ; auto. intros. split ; intro. subst. destruct H1. destruct H1. subst.\nsimpl. apply In_list_In_Box_list ; auto. subst. apply In_Box_list_In_list in H1.\nauto. intro. intros. inversion H0. destruct H1. subst. unfold In.\nexists x2 ; split ; auto. apply i. apply H ; auto.\nQed.\n\n", "meta": {"author": "ianshil", "repo": "PhD_thesis", "sha": "af4940397f0d95c1d63a196ab29a3b9f715d9f4e", "save_path": "github-repos/coq/ianshil-PhD_thesis", "path": "github-repos/coq/ianshil-PhD_thesis/PhD_thesis-af4940397f0d95c1d63a196ab29a3b9f715d9f4e/Toolbox_ModLog/Generalized_Hilbert_calculi/K_wKH_meta_interactions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.27436812949192524}}
{"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 A1 A2 B1 B2 C1 C2 D1 D2 IAB IAC IBD P1 R1 I : Universe, ((wd_ IAB IAC /\\ (wd_ IAB IBD /\\ (wd_ C1 P1 /\\ (wd_ C2 P1 /\\ (wd_ IAC P1 /\\ (wd_ D1 R1 /\\ (wd_ D2 R1 /\\ (wd_ IBD R1 /\\ (wd_ IAC IBD /\\ (wd_ B1 B2 /\\ (wd_ D1 D2 /\\ (wd_ A1 A2 /\\ (wd_ C1 C2 /\\ (wd_ B1 C1 /\\ (wd_ B1 C2 /\\ (wd_ B2 C1 /\\ (wd_ B2 C2 /\\ (wd_ A1 D1 /\\ (wd_ A1 D2 /\\ (wd_ A2 D1 /\\ (wd_ A2 D2 /\\ (col_ A1 A2 IAB /\\ (col_ B1 B2 IAB /\\ (col_ A1 A2 IAC /\\ (col_ C1 C2 IAC /\\ (col_ B1 B2 IBD /\\ (col_ D1 D2 IBD /\\ (col_ IAB IAC A1 /\\ (col_ IAB IAC A2 /\\ (col_ IAB IBD B1 /\\ (col_ IAB IBD B2 /\\ (col_ C1 C2 P1 /\\ (col_ D1 D2 R1 /\\ (col_ IAC P1 I /\\ col_ IBD R1 I)))))))))))))))))))))))))))))))))) -> col_ C1 C2 I)).\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_0216.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2743432679563614}}
{"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 SpecLow.\n\n  Definition smc_realm_destroy_spec0 (rd_addr: Z64) (adt: RData) : option (RData * Z64) :=\n    match rd_addr with\n    | VZ64 _rd_addr =>\n      rely is_int64 _rd_addr;\n      when'' _g_rd_base, _g_rd_ofst, adt == find_lock_unused_granule_spec (VZ64 _rd_addr) (VZ64 2) adt;\n      when _t'6 == is_null_spec (_g_rd_base, _g_rd_ofst) adt;\n      rely is_int _t'6;\n      if (_t'6 =? 0) then\n        when'' _rd_base, _rd_ofst, adt == granule_map_spec (_g_rd_base, _g_rd_ofst) 2 adt;\n        when'' _g_rtt_base, _g_rtt_ofst == get_rd_g_rtt_spec (_rd_base, _rd_ofst) adt;\n        rely is_int _g_rtt_ofst;\n        when'' _g_rec_list_base, _g_rec_list_ofst == get_rd_g_rec_list_spec (_rd_base, _rd_ofst) adt;\n        rely is_int _g_rec_list_ofst;\n        when adt == buffer_unmap_spec (_rd_base, _rd_ofst) adt;\n        when adt == granule_lock_spec (_g_rtt_base, _g_rtt_ofst) adt;\n        when' _t'5, adt == get_g_rtt_refcount_spec (_g_rtt_base, _g_rtt_ofst) adt;\n        rely is_int64 _t'5;\n        if (negb (_t'5 =? 0)) then\n          when adt == granule_unlock_spec (_g_rtt_base, _g_rtt_ofst) adt;\n          let _ret := 1 in\n          when adt == granule_unlock_spec (_g_rd_base, _g_rd_ofst) adt;\n          Some (adt, (VZ64 _ret))\n        else\n          when adt == realm_destroy_ops_spec (_g_rtt_base, _g_rtt_ofst) (_g_rec_list_base, _g_rec_list_ofst) (_g_rd_base, _g_rd_ofst) adt;\n          let _ret := 0 in\n          when adt == granule_unlock_spec (_g_rd_base, _g_rd_ofst) adt;\n          Some (adt, (VZ64 _ret))\n      else\n        let _ret := 1 in\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/RmiSMC/LowSpecs/smc_realm_destroy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347362, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.27433344014459066}}
{"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.\nFrom PromisingLib Require Import Language.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Thread.\n\nRequire Import SimMemory.\nRequire Import SimPromises.\nRequire Import SimLocal.\nRequire Import FulfillStep.\nRequire Import MemoryReorder.\nRequire Import Configuration.\nRequire Import SmallStep.\n\nSet Implicit Arguments.\n\n\nDefinition promise_consistent (lc:Local.t): Prop :=\n  forall loc ts from msg\n    (PROMISE: Memory.get loc ts lc.(Local.promises) = Some (from, msg)),\n    Time.lt (lc.(Local.tview).(TView.cur).(View.rlx) loc) ts.\n\nDefinition promise_consistent_th (tid: Ident.t) (c: Configuration.t) : Prop :=\n  forall lst lc\n         (THREAD: IdentMap.find tid c.(Configuration.threads) = Some (lst, lc)),\n  promise_consistent lc.\n\nLemma promise_step_promise_consistent\n      lc1 mem1 loc from to val released lc2 mem2 kind\n      (STEP: Local.promise_step lc1 mem1 loc from to val released lc2 mem2 kind)\n      (CONS: promise_consistent lc2):\n  promise_consistent lc1.\nProof.\n  inv STEP. ii. destruct msg.\n  exploit Memory.promise_promises_get1; eauto. i. des.\n  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: promise_consistent lc2):\n  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 val rel\n      promises1 promises2\n      l t f m\n      (FULFILL: Memory.remove promises1 loc from ts val rel 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 /\\ m.(Message.val) = val /\\ View.opt_le rel m.(Message.released).\nProof.\n  revert TH2. erewrite Memory.remove_o; eauto. condtac; ss; [|congr].\n  des. subst. erewrite Memory.remove_get0 in TH1; eauto. 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: Local.write_step lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind)\n      (CONS: promise_consistent lc2):\n  promise_consistent lc1.\nProof.\n  inv STEP. ii.\n  destruct (Memory.get loc0 ts promises2) as [[]|] eqn:X.\n  - apply CONS in X. eapply TimeFacts.le_lt_lt; eauto.\n    s. etrans; [|apply Time.join_l]. refl.\n  - destruct msg. inv WRITE.\n    exploit Memory.promise_promises_get1; eauto. i. des.\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      (SC: Memory.closed_timemap sc1 mem1)\n      (MEM: Memory.closed mem1)\n      (CONS: promise_consistent lc2):\n  promise_consistent lc1.\nProof.\n  exploit Local.fence_step_future; eauto. i. des.\n  inversion STEP. subst. ii. exploit CONS; eauto. i.\n  eapply TimeFacts.le_lt_lt; eauto. apply TVIEW_FUTURE. \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: promise_consistent th2.(Thread.local))\n      (WF1: Local.wf th1.(Thread.local) th1.(Thread.memory))\n      (SC1: Memory.closed_timemap th1.(Thread.sc) th1.(Thread.memory))\n      (MEM1: Memory.closed th1.(Thread.memory)):\n  promise_consistent th1.(Thread.local).\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 (@Thread.all_step lang) th1 th2)\n      (CONS: promise_consistent th2.(Thread.local))\n      (WF1: Local.wf th1.(Thread.local) th1.(Thread.memory))\n      (SC1: Memory.closed_timemap th1.(Thread.sc) th1.(Thread.memory))\n      (MEM1: Memory.closed th1.(Thread.memory)):\n  promise_consistent th1.(Thread.local).\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: promise_consistent th2.(Thread.local))\n      (WF1: Local.wf th1.(Thread.local) th1.(Thread.memory))\n      (SC1: Memory.closed_timemap th1.(Thread.sc) th1.(Thread.memory))\n      (MEM1: Memory.closed th1.(Thread.memory)):\n  promise_consistent th1.(Thread.local).\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: @Thread.consistent lang th)\n      (WF: Local.wf th.(Thread.local) th.(Thread.memory))\n      (SC: Memory.closed_timemap th.(Thread.sc) th.(Thread.memory))\n      (MEM: Memory.closed th.(Thread.memory)):\n  promise_consistent th.(Thread.local).\nProof.\n  exploit CONS; eauto; try refl. i. des.\n  eapply rtc_tau_step_promise_consistent; (try by destruct th; 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 m\n      (STEP: Local.read_step lc1 mem1 loc to val released ord lc2)\n      (PROMISE: Memory.get loc t lc1.(Local.promises) = Some (f, m))\n      (CONS: promise_consistent lc2):\n  Time.lt to t.\nProof.\n  inv STEP. exploit CONS; eauto. s. i.\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 lc1.(Local.promises) = Some (f, m))\n      (CONS: 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. destruct m.\n    exploit CONS; eauto. i. 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. destruct m.\n    exploit Memory.promise_promises_get1; eauto. i. des.\n    exploit fulfill_unset_promises; eauto. i. des. subst. refl.\nQed.  \n\nLemma thread_step_unset_promises\n      lang loc pf e from ts msg (th1 th2:Thread.t lang)\n      (STEP: Thread.step pf e th1 th2)\n      (TH1: Memory.get loc ts th1.(Thread.local).(Local.promises) = Some (from, msg))\n      (TH2: Memory.get loc ts th2.(Thread.local).(Local.promises) = None):\n  exists ord from val rel,\n  <<EVENT: ThreadEvent.is_writing e = Some (loc, from, ts, val, rel, ord)>> /\\\n  <<ORD: Ordering.le ord Ordering.relaxed>> /\\\n  <<TIME: Time.lt (th1.(Thread.local).(Local.tview).(TView.cur).(View.rlx) loc) ts>>.\nProof.\n  inv STEP.\n  { inv STEP0. inv LOCAL. destruct msg. ss. \n    exploit Memory.promise_promises_get1; eauto. i. des. congr.\n  }\n  destruct msg.\n  inv STEP0; ss; inv LOCAL; ss;\n    (try congr);\n    (try by inv LOCAL0; ss; congr).\n  - inv LOCAL0. inv WRITE.\n    exploit Memory.promise_promises_get1; eauto. i. des.\n    exploit fulfill_unset_promises; eauto. i. des. subst.\n    unfold Memory.get in *.\n    esplits; s; eauto.\n    + edestruct ordering_relaxed_dec; eauto.\n      apply RELEASE in H. des. subst. ss.\n      exploit H; eauto. s. i. subst. inv RELEASED. inv x4.\n      revert H1. unfold TView.write_released. condtac; ss.\n      destruct ord; inv COND. ss.\n    + inv WRITABLE. eauto.\n  - inv LOCAL1. inv LOCAL2. inv WRITE.\n    exploit Memory.promise_promises_get1; eauto. i. des.\n    exploit fulfill_unset_promises; eauto. i. des. subst.\n    unfold Memory.get in *.\n    esplits; s; eauto.\n    + edestruct ordering_relaxed_dec; eauto.\n      apply RELEASE in H. des. subst. ss.\n      exploit H; eauto. s. i. subst. inv RELEASED. inv x4.\n      revert H1. unfold TView.write_released. condtac; ss.\n      destruct ordw; inv COND. ss.\n    + inv WRITABLE. inv READABLE. ss. move TS at bottom.\n      eapply TimeFacts.le_lt_lt; eauto.\n      repeat (etrans; [|apply Time.join_l]). refl.\nQed.\n\nLemma rtc_small_step_unset_promises\n      tid loc ts c1 lst1 lc1 c2 lst2 lc2 from msg withprm\n      (STEPS: rtc (small_step_evt withprm tid) c1 c2)\n      (WF: Configuration.wf c1)\n      (FIND1: IdentMap.find tid c1.(Configuration.threads) = Some (lst1, lc1))\n      (GET1: Memory.get loc ts lc1.(Local.promises) = Some (from, msg))\n      (FIND2: IdentMap.find tid c2.(Configuration.threads) = Some (lst2, lc2))\n      (GET2: Memory.get loc ts lc2.(Local.promises) = None):\n  Time.lt (lc1.(Local.tview).(TView.cur).(View.rlx) loc) ts.\nProof.\n  ginduction STEPS; i; subst.\n  { ss. rewrite FIND1 in FIND2. depdes FIND2.\n    by rewrite GET1 in GET2.\n  }\n  inv H. \n  exploit small_step_future; eauto. intros [WF2 _].\n  inv USTEP. ss. rewrite FIND1 in TID. depdes TID.\n  destruct (Memory.get loc ts lc3.(Local.promises)) as [[t m]|] eqn: PRM.\n  - rewrite IdentMap.gss in IHSTEPS.\n    exploit IHSTEPS; eauto.\n    intro LT. move STEP at bottom.\n    eapply TimeFacts.le_lt_lt; eauto.\n    inv WF. exploit thread_step_tview_le; try exact STEP; eauto. \n    { eapply WF0. rewrite FIND1. eauto. }\n    s. i. apply x1.\n  - guardH PFREE.\n    eapply thread_step_unset_promises in STEP; eauto. des.\n    eauto using small_step_write_lt.\nQed.\n\nLemma promise_consistent_th_small_step\n      tid c1 c2 withprm tid'\n      (STEP: small_step_evt withprm tid c1 c2)\n      (WF: Configuration.wf c1)\n      (FULFILL: promise_consistent_th tid' c2):\n  promise_consistent_th tid' c1.\nProof.\n  destruct (Ident.eq_dec tid' tid); cycle 1.\n  { ii. eapply FULFILL; eauto.\n    inv STEP. inv USTEP. s. rewrite IdentMap.gso; eauto.\n  }\n  subst.\n  ii. destruct (IdentMap.find tid (Configuration.threads c2)) as [[lang2 lc2]|] eqn: THREAD2; cycle 1.\n  { inv STEP. inv USTEP. ss. by rewrite IdentMap.gss in THREAD2. }\n  destruct (Memory.get loc ts (Local.promises lc2)) as [[from2 msg2]|] eqn: PROMISE2; cycle 1.\n  - apply Operators_Properties.clos_rt1n_step in STEP.\n    eapply rtc_small_step_unset_promises; eauto.\n  - eapply FULFILL in PROMISE2; eauto.\n    eapply TimeFacts.le_lt_lt; eauto.\n    inv STEP. inv USTEP. ss.\n    rewrite THREAD in TID. inv TID.\n    rewrite IdentMap.gss in THREAD2. inv THREAD2.\n    inv WF. exploit thread_step_tview_le; try exact STEP; eauto. \n    { eapply WF0. rewrite THREAD. eauto. }\n    s. i. apply x0.\nQed.\n\nLemma promise_consistent_th_rtc_small_step\n      tid c1 c2 withprm tid'\n      (STEP: rtc (small_step_evt withprm tid) c1 c2)\n      (WF: Configuration.wf c1)\n      (FULFILL: promise_consistent_th tid' c2):\n  promise_consistent_th tid' c1.\nProof.\n  ginduction STEP; eauto. \n  i. eapply promise_consistent_th_small_step; eauto.\n  eapply IHSTEP; eauto.\n  inv H. eapply small_step_future; eauto.\nQed.\n\nLemma consistent_promise_consistent_th\n      tid c \n      (WF: Configuration.wf c)\n      (CONSISTENT: Configuration.consistent c):\n  promise_consistent_th tid c.\nProof.\n  ii. assert (X:= WF). inv X. inv WF0. destruct lst as [lang st].\n  exploit CONSISTENT; eauto; try reflexivity.\n  i. des. destruct e2.\n  exploit rtc_thread_step_rtc_small_step; [eauto|..].\n  { ss. eapply rtc_implies, STEPS. apply tau_union. }\n  intro STEPS2. \n  eapply rtc_small_step_unset_promises in STEPS2; eauto.\n  - destruct c. eapply rtc_small_step_future; eauto.\n  - s. rewrite IdentMap.gss. eauto.\n  - ss. rewrite PROMISES. apply Cell.bot_get.\nGrab Existential Variables. exact true.\nQed.\n\nLemma promise_consistent_th_small_step_forward\n      withprm tid e c1 c2\n      (STEP: small_step withprm tid e c1 c2)\n      (PRCONS: forall tid0, promise_consistent_th tid0 c1)\n      (PRCONS2: promise_consistent_th tid c2)\n      (WF: Configuration.wf c1):\n  forall tid0, promise_consistent_th tid0 c2.\nProof.\n  i. s. destruct (Ident.eq_dec tid0 tid) eqn: EQ.\n  - subst. eauto.\n  - ii. exploit small_step_find; eauto.\n    s; intro X. rewrite <-X in THREAD. \n    eapply (PRCONS tid0); eauto.  \nQed.\n\nLemma rtc_promise_consistent_th_small_step_forward\n      withprm tid c1 c2\n      (STEP: rtc (small_step_evt withprm tid) c1 c2)\n      (PRCONS: forall tid0, promise_consistent_th tid0 c1)\n      (PRCONS2: promise_consistent_th tid c2)\n      (WF: Configuration.wf c1):\n  forall tid0, promise_consistent_th tid0 c2.\nProof.\n  apply Operators_Properties.clos_rt_rt1n_iff,\n        Operators_Properties.clos_rt_rtn1_iff in STEP.\n  ginduction STEP; eauto.\n  apply Operators_Properties.clos_rt_rtn1_iff,\n        Operators_Properties.clos_rt_rt1n_iff in STEP.\n  i. inv H. hexploit promise_consistent_th_small_step_forward; eauto; cycle 1.\n  { eapply rtc_small_step_future; eauto.\n    eapply rtc_implies, STEP. eauto. }\n  i. hexploit IHSTEP; eauto.\n  eapply promise_consistent_th_small_step; eauto.\n  eapply rtc_small_step_future; eauto.\n  eapply rtc_implies, STEP. eauto.\nQed.\n\nLemma promise_consistent_th_small_step_backward\n      withprm tid e c1 c2\n      (STEP: small_step withprm tid e c1 c2)\n      (PRCONS: forall tid0, promise_consistent_th tid0 c2)\n      (WF: Configuration.wf c1):\n  forall tid0, promise_consistent_th tid0 c1.\nProof.\n  i. s. destruct (Ident.eq_dec tid0 tid) eqn: EQ.\n  - subst. hexploit promise_consistent_th_small_step; eauto.\n  - ii. exploit small_step_find; eauto.\n    s; intro X. rewrite X in THREAD. \n    eapply (PRCONS tid0); eauto.  \nQed.\n\nLemma rtc_promise_consistent_th_small_step_backward\n      withprm tid c1 c2\n      (STEP: rtc (small_step_evt withprm tid) c1 c2)\n      (PRCONS: forall tid0, promise_consistent_th tid0 c2)\n      (WF: Configuration.wf c1):\n  forall tid0, promise_consistent_th tid0 c1.\nProof.\n  ginduction STEP; eauto.\n  i. inv H. \n  i. hexploit promise_consistent_th_small_step_backward; eauto.\n  i. hexploit IHSTEP; eauto.\n  eapply small_step_future; eauto.\nQed.\n\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/PromiseConsistent.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2743334351188115}}
{"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 A1 A2 B1 B2 C1 C2 D1 D2 IAB IAC IBD P1 R1 I : Universe, ((wd_ IAB IAC /\\ (wd_ IAB IBD /\\ (wd_ C1 P1 /\\ (wd_ C2 P1 /\\ (wd_ IAC P1 /\\ (wd_ D1 R1 /\\ (wd_ D2 R1 /\\ (wd_ IBD R1 /\\ (wd_ IAC IBD /\\ (wd_ B1 B2 /\\ (wd_ D1 D2 /\\ (wd_ A1 A2 /\\ (wd_ C1 C2 /\\ (wd_ B1 C1 /\\ (wd_ B1 C2 /\\ (wd_ B2 C1 /\\ (wd_ B2 C2 /\\ (wd_ A1 D1 /\\ (wd_ A1 D2 /\\ (wd_ A2 D1 /\\ (wd_ A2 D2 /\\ (col_ A1 A2 IAB /\\ (col_ B1 B2 IAB /\\ (col_ A1 A2 IAC /\\ (col_ C1 C2 IAC /\\ (col_ B1 B2 IBD /\\ (col_ D1 D2 IBD /\\ (col_ IAB IAC A1 /\\ (col_ IAB IAC A2 /\\ (col_ IAB IBD B1 /\\ (col_ IAB IBD B2 /\\ (col_ C1 C2 P1 /\\ (col_ D1 D2 R1 /\\ (col_ IAC P1 I /\\ col_ IBD R1 I)))))))))))))))))))))))))))))))))) -> col_ D1 D2 I)).\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_0218.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2743334351188114}}
{"text": "Require Import Word.WordInterface.\nRequire Import Common.Types.\nRequire Import Network.NetworkPacket.\nRequire Import OpenFlow.OpenFlow0x01Types.\n\nDefinition get_packet_handler := switchId -> portId -> packet -> unit.\n\nInductive predicate : Type :=\n  | And : predicate -> predicate -> predicate\n  | Or : predicate -> predicate -> predicate\n  | Not : predicate -> predicate\n  | All : predicate\n  | NoPackets : predicate\n  | Switch : switchId -> predicate\n  | InPort : portId -> predicate\n  | DlSrc : dlAddr -> predicate\n  | DlDst : dlAddr -> predicate.\n  (* TODO(arjun): fill in others *)\n\nInductive action :=\n  | To : portId -> action\n  | ToAll : action\n  | GetPacket : get_packet_handler -> action.\n\nInductive policy :=\n  | Policy : predicate -> list action -> policy\n  | Par : policy -> policy -> policy. (** parallel composition *)\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/NetCore/old/NetCoreTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2742899367186712}}
{"text": "Require Import CoqlibC Maps Postorder.\nRequire Import AST Linking.\nRequire Import ValuesC Memory GlobalenvsC Events Smallstep.\nRequire Import Op Registers ClightC Renumber.\nRequire Import CtypesC CtypingC.\nRequire Import sflib.\nRequire Import IntegersC.\n\nRequire Import MutrecHeader.\nRequire Import MutrecA MutrecAspec.\nRequire Import Simulation.\nRequire Import Skeleton Mod ModSem SimMod SimModSemLift SimSymb SimMemLift AsmregsC MatchSimModSem.\nRequire SoundTop.\nRequire SimMemInjC SimMemInjInvC.\nRequire Import Clightdefs.\nRequire Import CtypesC.\n\nSet Implicit Arguments.\n\n\nDefinition memoized_inv: SimMemInjInv.memblk_invariant :=\n  SimMemInjInv.memblk_invarant_mk\n    (fun mem =>\n       forall\n         chunk ofs ind\n         (BOUND: 0 <= ind < 1000)\n         (INT: chunk = Mint32)\n         (INDEX: size_chunk Mint32 * ind = ofs),\n       exists i,\n         (<<VINT: mem chunk ofs = Some (Vint i)>>) /\\\n         (<<VAL: forall (NZERO: i.(Int.intval) <> 0),\n             (<<MEMO: i = sum (Int.repr ind)>>)>>))\n    (fun chunk ofs p =>\n       exists ind,\n         (<<CHUNK: chunk = Mint32>>) /\\ (<<BOUND: 0 <= ind < 1000>>) /\\\n         (<<INDEX: ofs = size_chunk Mint32 * ind>>) /\\ (<<WRITABLE: p = Writable>>)).\n\nLocal Instance SimMemMemoizedA: SimMem.class := SimMemInjInvC.SimMemInjInv\n                                                 SimMemInjInv.top_inv memoized_inv.\n\nDefinition symbol_memoized: ident -> Prop := eq _memoized.\n\nLemma memoized_inv_store_le i ind blk ofs m_tgt\n      (sm0 sm1: SimMemInjInv.t')\n      (MWF: SimMem.wf sm0)\n      (INVAR: sm0.(SimMemInjInv.mem_inv_tgt) blk)\n      (SUM: i = sum (Int.repr ind))\n      (OFS: ofs = size_chunk Mint32 * ind)\n      (STR: Mem.store Mint32 sm0.(SimMemInjInv.minj).(SimMemInj.tgt) blk ofs (Vint i) = Some m_tgt)\n      (MREL: sm1 = SimMemInjInv.mk\n                     (SimMemInjC.update\n                        (sm0.(SimMemInjInv.minj))\n                        (sm0.(SimMemInjInv.minj).(SimMemInj.src))\n                        m_tgt\n                        (sm0.(SimMemInjInv.minj).(SimMemInj.inj)))\n                     sm0.(SimMemInjInv.mem_inv_src)\n                     sm0.(SimMemInjInv.mem_inv_tgt))\n  :\n    (<<MLE: SimMem.le sm0 sm1>>) /\\\n    (<<MWF: SimMem.wf sm1>>).\nProof.\n  inv MWF. split.\n  - econs; ss; eauto. econs; ss; eauto.\n    + refl.\n    + eapply Mem.store_unchanged_on; eauto.\n      ii. inv WF. exploit INVRANGETGT; eauto. i. des.\n      exfalso. eauto.\n    + eapply SimMemInj.frozen_refl. + eapply SimMemInj.frozen_refl.\n    + ii. eapply Mem.perm_store_2; eauto.\n  - inv WF. econs; ss; eauto.\n    + unfold SimMemInjC.update. econs; ss; eauto.\n      * eapply MemoryC.private_unchanged_inject; eauto.\n        { eapply Mem.store_unchanged_on; eauto.\n          instantiate (1:=~2\n                        loc_out_of_reach (SimMemInj.inj (SimMemInjInv.minj sm0))\n                        (SimMemInj.src (SimMemInjInv.minj sm0))).\n          ss. ii. eapply H0.\n          exploit INVRANGETGT; eauto. i. des. eapply H1. }\n        { ss. }\n      * etrans; eauto.\n        unfold SimMemInj.tgt_private, SimMemInj.valid_blocks in *. ss.\n        ii. des. split; auto. eapply Mem.store_valid_block_1; eauto.\n      * rpapply TGTLE. eapply Mem.nextblock_store; eauto.\n    + ii. exploit SATTGT; eauto. i. inv H. econs; ss.\n      * i. exploit PERMISSIONS; eauto. i.\n        eapply Mem.store_valid_access_1; eauto.\n      * i. exploit LOADVALS; eauto. i. des. destruct (peq blk blk0).\n        { clarify. destruct (zeq ind ind0).\n          - clarify. exists (sum (Int.repr ind0)).\n            esplits; eauto. erewrite Mem.load_store_same; eauto. ss.\n          - exists i. erewrite Mem.load_store_other; eauto.\n            right. clear - n. ss. omega. }\n        { exists i. erewrite Mem.load_store_other; eauto. }\nQed.\n\nSection SIMMODSEM.\n\nVariable skenv_link: SkEnv.t.\nVariable sm_link: SimMem.t.\nLet md_src: Mod.t := (MutrecAspec.module).\nLet md_tgt: Mod.t := (ClightC.module2 prog).\nHypothesis (INCL: SkEnv.includes skenv_link (Mod.sk md_src)).\nHypothesis (WF: SkEnv.wf skenv_link).\nLet ge := (SkEnv.project skenv_link (Mod.sk md_src)).\nLet tge := Build_genv (SkEnv.revive (SkEnv.project skenv_link (Mod.sk md_tgt)) prog) prog.(prog_comp_env).\nDefinition msp: ModSemPair.t :=\n  ModSemPair.mk (md_src skenv_link) (md_tgt skenv_link) (SimMemInjInvC.mk symbol_memoized md_src md_tgt) sm_link.\n\nInductive match_states_internal: nat -> MutrecAspec.state -> Clight.state -> Prop :=\n| match_callstate_nonzero\n    idx i m_src m_tgt\n    fptr\n    (RANGE: 0 <= i.(Int.intval) < MAX)\n    (FINDF: Genv.find_funct (Smallstep.globalenv (modsem2 skenv_link prog)) fptr = Some (Internal func_f))\n    (IDX: (idx > 3)%nat)\n  :\n    match_states_internal idx (Callstate i m_src) (Clight.Callstate fptr (Tfunction\n                                                                            (Tcons tint Tnil) tint cc_default)\n                                                                    [Vint i] Kstop m_tgt)\n| match_returnstate\n    idx i m_src m_tgt\n  :\n    match_states_internal idx (Returnstate i m_src) (Clight.Returnstate (Vint i) Kstop m_tgt)\n.\n\n\n\nInductive match_states\n          (idx: nat) (st_src0: MutrecAspec.state) (st_tgt0: Clight.state) (sm0: SimMem.t): Prop :=\n| match_states_intro\n    (MATCHST: match_states_internal idx st_src0 st_tgt0)\n    (MCOMPATSRC: (get_mem st_src0) = sm0.(SimMem.src))\n    (MCOMPATTGT: (ClightC.get_mem st_tgt0) = sm0.(SimMem.tgt))\n    (MWF: SimMem.wf sm0)\n.\n\nLemma g_blk_exists\n  :\n    exists g_blk,\n      (<<FINDG: Genv.find_symbol\n                  (SkEnv.revive (SkEnv.project skenv_link (CSk.of_program signature_of_function prog)) prog)\n                  g_id = Some g_blk>>)\n      /\\\n      (<<FINDG: Genv.find_funct_ptr\n                  (SkEnv.revive (SkEnv.project skenv_link (CSk.of_program signature_of_function prog)) prog)\n                  g_blk = None>>)\n      /\\\n      (<<FINDG: exists skd, Genv.find_funct_ptr skenv_link g_blk = Some skd /\\\n                            Some (signature_of_type (Tcons tint Tnil) tint cc_default) = Sk.get_csig skd>>)\n.\nProof.\n  exploit (prog_defmap_norepet prog g_id); eauto.\n  { unfold prog_defs_names. ss. repeat (econs; eauto).\n    - ii; ss; des; ss.\n    - ii; ss; des; ss. }\n  { ss. eauto. }\n  intro T; des.\n  exploit SkEnv.project_impl_spec; eauto. intro PROJ.\n  assert(PREC: SkEnv.genv_precise\n                 (SkEnv.revive (SkEnv.project skenv_link (CSk.of_program signature_of_function prog)) prog)\n                 prog).\n  { eapply CSkEnv.project_revive_precise; ss; et. }\n  inv PREC.\n  exploit (P2GE g_id); eauto. i; des. des_ifs.\n  rename b into g_blk.\n  eexists. splits; et.\n  { unfold Genv.find_funct_ptr. des_ifs. }\n  { inv INCL.\n    exploit (CSk.of_program_prog_defmap prog signature_of_function); et. rewrite T. intro S.\n\n    remember ((prog_defmap (CSk.of_program signature_of_function prog)) ! g_id) as U in *.\n    destruct U eqn:V; try (by ss). inv S. inv H1.\n\n    exploit DEFS; eauto. i; des.\n    assert(blk = g_blk).\n    { inv PROJ. exploit SYMBKEEP; et.\n      - instantiate (1:= g_id). unfold defs. des_sumbool. ss. et.\n      - i. rewrite SYMB0 in *. clear - SYMB H. unfold SkEnv.revive in *. rewrite Genv_map_defs_symb in *. ss.\n        rewrite SYMB in *. des. clarify.\n    }\n    clarify. inv MATCH.\n    esplits; eauto.\n    - unfold Genv.find_funct_ptr. rewrite DEF0. et.\n    - ss. des_ifs. clear - H1. inv H1; ss.\n  }\nQed.\n\nLemma match_states_lxsim\n      idx st_src0 st_tgt0 sm0\n      (SIMSK: SimSymb.sim_skenv\n                sm0 (SimMemInjInvC.mk symbol_memoized md_src md_tgt)\n                (SkEnv.project skenv_link (CSk.of_program signature_of_function prog))\n                (SkEnv.project skenv_link (CSk.of_program signature_of_function prog)))\n      (MATCH: match_states idx st_src0 st_tgt0 sm0)\n  :\n    <<XSIM: lxsimL (md_src skenv_link) (md_tgt skenv_link)\n                   (fun st => unit -> exists su m_init, SoundTop.sound_state su m_init st)\n                   top3 (fun _ _ => SimMem.le)\n                   (Ord.lift_idx lt_wf idx) st_src0 st_tgt0 sm0>>\n.\nProof.\n  revert_until tge.\n  pcofix CIH.\n  i.\n  pfold.\n  generalize g_blk_exists; et. i; des.\n  inv MATCH; subst. ss. inv MATCHST; ss; clarify.\n  - (* call *)\n    destruct (classic (i = Int.zero)).\n    + (* zero *)\n      clarify.\n      econs 2. ii.\n      econs 2.\n      { split.\n        - econs 2.\n          + ss. econs 1.\n          + econs 1.\n          + ss.\n        - eapply Ord.lift_idx_spec.\n          instantiate (1:=3%nat). nia. }\n      refl.\n\n      left. pfold.\n      econs 1. i; des.\n      econs 2.\n\n      * split; cycle 1.\n        { apply Ord.lift_idx_spec.\n          instantiate (1:=2%nat). nia. }\n\n        eapply plus_left with (t1 := E0) (t2 := E0); ss.\n        { econs; eauto.\n          { eapply modsem2_determinate; eauto. }\n          econs; eauto.\n          econs; ss; eauto; try (by repeat (econs; ss; eauto)).\n          unfold _x. unfold _t'1. rr. ii; ss. des; ss; clarify.\n        }\n\n        eapply star_left with (t1 := E0) (t2 := E0); ss.\n        { econs; eauto.\n          { eapply modsem2_determinate; eauto. }\n          econs; eauto.\n        }\n\n        eapply star_left with (t1 := E0) (t2 := E0); ss.\n        { econs; eauto.\n          { eapply modsem2_determinate; eauto. }\n          econs; eauto.\n          - repeat econs; et.\n          - ss.\n        }\n\n        eapply star_left with (t1 := E0) (t2 := E0); ss.\n        { econs; eauto.\n          { eapply modsem2_determinate; eauto. }\n          econs; eauto.\n          - repeat econs; et.\n          - ss.\n          - ss.\n        }\n\n        apply star_refl.\n      * refl.\n      * right. eapply CIH; eauto. econs; ss; eauto.\n        replace (Int.repr 0) with (sum Int.zero).\n        { econs; eauto. }\n        { rewrite sum_recurse. des_ifs. }\n\n    + (* nonzero *)\n\n      destruct (Genv.find_symbol\n                  (SkEnv.project skenv_link (CSk.of_program signature_of_function prog))\n                  _memoized) eqn:BLK; cycle 1.\n      { exfalso. clear - INCL BLK. inversion INCL; subst.\n        exploit DEFS; eauto.\n        - instantiate (2:=_memoized). ss.\n        - i. des.\n          exploit SkEnv.project_impl_spec. eapply INCL. i. inv H. ss.\n          exploit SYMBKEEP. instantiate (1:=_memoized). ss. i.\n          rr in H. rewrite H in *. clarify. }\n\n      inv MWF. ss.\n\n      assert (INVAR: SimMemInjInv.mem_inv_tgt sm0 b).\n      { inv SIMSK. ss. inv INJECT.\n        eapply INVCOMPAT; eauto. ss. }\n\n      hexploit SATTGT; eauto. intros SAT0.\n      exploit SAT0; eauto. i. inv H0. ss.\n      hexploit LOADVALS; eauto. i. des.\n\n      destruct (zeq (Int.intval i0) 0).\n      {\n        econs 2. ii.\n        econs 2.\n        { split.\n          - econs 2; ss.\n            + econs 2; eauto.\n              clear - H.\n              exploit Int.eq_false; eauto. i.\n              unfold Int.eq in *. ss. des_ifs.\n            + econs; eauto.\n            + ss.\n          - eapply Ord.lift_idx_spec. eauto. }\n        refl.\n\n        left. pfold.\n        econs.\n        i; des.\n        econs 2; eauto.\n        * esplits; cycle 1.\n          { eapply Ord.lift_idx_spec. eauto. }\n\n          eapply plus_left with (t1 := E0) (t2 := E0); ss.\n          { econs; eauto.\n            { eapply modsem2_determinate; eauto. }\n            econs; eauto.\n            econs; ss; eauto; try (by repeat (econs; ss; eauto)).\n            unfold _x. unfold _t'1. rr. ii; ss. des; ss; clarify.\n          }\n\n          eapply star_left with (t1 := E0) (t2 := E0); ss.\n          { econs; eauto.\n            { eapply modsem2_determinate; eauto. }\n            econs; eauto.\n          }\n\n          eapply star_left with (t1 := E0) (t2 := E0); ss.\n          { econs; eauto.\n            { eapply modsem2_determinate; eauto. }\n            econs; eauto.\n            - repeat econs; et.\n            - ss. rewrite Int.eq_false; ss.\n          }\n\n          eapply star_left with (t1 := E0) (t2 := E0); ss.\n          { econs; eauto.\n            { eapply modsem2_determinate; eauto. }\n            econs; eauto.\n          }\n\n          eapply star_left with (t1 := E0) (t2 := E0); ss.\n          { econs; eauto.\n            { eapply modsem2_determinate; eauto. }\n            econs; eauto.\n          }\n\n          eapply star_left with (t1 := E0) (t2 := E0); ss.\n          { econs; eauto.\n            { eapply modsem2_determinate; eauto. }\n            econs; eauto; swap 1 2.\n            - econs.\n              + ss. econs. econs; ss.\n                * econs.\n                  { eapply eval_Evar_global; ss.\n                    instantiate (1:=b). eauto. }\n                  { econs 2; ss. }\n                * econs; ss.\n                * ss.\n              + econs 1; ss. psimpl.\n                replace (Ptrofs.unsigned (Ptrofs.mul (Ptrofs.repr 4) (Ptrofs.of_ints i)))\n                  with (4 * Int.intval i); cycle 1.\n                { unfold Ptrofs.mul. ss.\n                  destruct i. ss. unfold Ptrofs.of_ints. ss.\n                  unfold Int.signed. ss. des_ifs; cycle 1;\n                  unfold Int.half_modulus, Int.modulus, two_power_nat in *; ss;\n                    unfold MAX in *; rewrite <- Zdiv2_div in *; ss.\n                  { lia. }\n                  repeat rewrite Ptrofs.unsigned_repr. auto.\n                  all : unfold Ptrofs.max_unsigned; rewrite Ptrofs.modulus_power;\n                  unfold Ptrofs.zwordsize, Ptrofs.wordsize, Wordsize_Ptrofs.wordsize; des_ifs; ss; omega. } eauto. }\n\n          eapply star_left with (t1 := E0) (t2 := E0); ss.\n          { econs; eauto.\n            { eapply modsem2_determinate; eauto. }\n            econs; eauto.\n          }\n\n          eapply star_left with (t1 := E0) (t2 := E0); ss.\n          { econs; eauto.\n            { eapply modsem2_determinate; eauto. }\n            econs; eauto.\n          }\n\n          eapply star_left with (t1 := E0) (t2 := E0); ss.\n          { econs; eauto.\n            { eapply modsem2_determinate; eauto. }\n            ss. econs; eauto.\n            - econs; ss.\n              + econs; ss.\n              + econs; ss.\n              + ss.\n            - ss. instantiate (1:=true).\n              unfold Cop.bool_val. ss.\n              unfold Int.eq. unfold Val.of_bool.\n              destruct (zeq (Int.unsigned i0) (Int.unsigned (Int.repr 0))) eqn:EQ; ss. }\n          eapply star_left with (t1 := E0) (t2 := E0); ss.\n          { econs; eauto.\n            { eapply modsem2_determinate; eauto. }\n            econs; eauto.\n          }\n\n          eapply star_left with (t1 := E0) (t2 := E0); ss.\n          { econs; eauto.\n            { eapply modsem2_determinate; eauto. }\n            econs; eauto.\n          }\n\n          eapply star_left with (t1 := E0) (t2 := E0); ss.\n          { econs; eauto.\n            { eapply modsem2_determinate; eauto. }\n            econs; eauto; swap 1 2.\n            - econs.\n              + eapply eval_Evar_global; ss. et.\n              + econs 2; et.\n            - unfold Cop.classify_fun. ss.\n            - repeat econs; ss; et.\n          }\n\n          eapply star_refl.\n\n        * refl.\n\n        * left. pfold. econs 3; et.\n          { econs; eauto. }\n          { econs. econs; eauto. }\n          ii; des.\n          inv ATSRC. ss; clarify.\n\n          unfold Clight.fundef in *.\n          assert(g_fptr = g_blk).\n          { unfold SkEnv.revive in FINDG. rewrite Genv_map_defs_symb in *. clarify. }\n          clarify.\n          eexists (Args.mk _ [Vint (Int.sub i (Int.repr 1))] _).\n          exists sm0.\n          esplits; ss; eauto.\n          { econs; ss; eauto.\n            instantiate (1:=Vptr g_blk Ptrofs.zero).\n            inv SIMSK. inv SIMSKENV. inv INJECT. ss.\n            econs. eapply DOMAIN; eauto.\n            exploit Genv.genv_symb_range. unfold Genv.find_symbol in *. eauto.\n            i. ss. ii.\n            exploit INVCOMPAT; eauto. i. rewrite <- H1 in H0. ss.\n            rewrite Ptrofs.add_zero_l. ss. }\n          { refl. }\n          { econs; eauto. }\n          i. inv AFTERSRC. inv SIMRETV; ss; clarify.\n\n          hexploit Mem.valid_access_store.\n          { instantiate (4:=sm_ret.(SimMemInjInv.minj).(SimMemInj.tgt)).\n            inv MWF. inv WF. exploit SATTGT0; eauto.\n            - inv MLE. erewrite <- MINVEQTGT. eauto.\n            - i. inv H0. hexploit PERMISSIONS0; eauto. ss.\n              esplits; eauto. }\n          intros [m_tgt STR].\n\n          exploit SimMemInjInvC.unlift_wf; try apply MLE; eauto.\n          { econs; eauto. } intros MLE1.\n          exploit memoized_inv_store_le; eauto.\n          i. des.\n\n          esplits.\n          { econs; eauto. }\n          { apply MLE0. }\n\n          left. pfold. econs; eauto. i; des. econs 2; eauto.\n          {\n            esplits; eauto; cycle 1.\n            { instantiate (1:= (Ord.lift_idx lt_wf 14%nat)). eapply Ord.lift_idx_spec; et. }\n\n            eapply plus_left with (t1 := E0) (t2 := E0); ss.\n            { econs; eauto.\n              { eapply modsem2_determinate; eauto. }\n              econs; eauto.\n            }\n\n            eapply star_left with (t1 := E0) (t2 := E0); ss.\n            { econs; eauto.\n              { eapply modsem2_determinate; eauto. }\n              econs; eauto.\n            }\n\n            eapply star_left with (t1 := E0) (t2 := E0); ss.\n            { econs; eauto.\n              { eapply modsem2_determinate; eauto. }\n              econs; eauto. econs; eauto.\n              - econs; eauto. ss.\n              - econs; eauto. ss.\n              - inv RETV. ss. unfold typify. des_ifs. }\n\n            eapply star_left with (t1 := E0) (t2 := E0); ss.\n            { econs; eauto.\n              { eapply modsem2_determinate; eauto. }\n              econs; eauto.\n            }\n\n            eapply star_left with (t1 := E0) (t2 := E0); ss.\n            { econs; eauto.\n              { eapply modsem2_determinate; eauto. }\n              econs; eauto.\n              - econs; eauto. econs; eauto.\n                + econs; eauto.\n                  * eapply eval_Evar_global; ss.\n                    instantiate (1:=b). ss.\n                  * ss. econs 2; eauto.\n                + econs; eauto. ss.\n                + econs; eauto.\n              - econs; eauto. ss.\n              - ss.\n              - ss. psimpl. econs; ss; eauto.\n                rpapply STR. f_equal.\n                + unfold Ptrofs.mul. ss.\n                  destruct i. ss. unfold Ptrofs.of_ints. ss.\n                  unfold Int.signed. ss. des_ifs; cycle 1;\n                  unfold Int.half_modulus, Int.modulus, two_power_nat in *; ss;\n                    unfold MAX in *; rewrite <- Zdiv2_div in *; ss.\n                  { lia. }\n                  repeat rewrite Ptrofs.unsigned_repr. auto.\n                  all : unfold Ptrofs.max_unsigned; rewrite Ptrofs.modulus_power;\n                    unfold Ptrofs.zwordsize, Ptrofs.wordsize, Wordsize_Ptrofs.wordsize; des_ifs; ss; omega.\n                + f_equal.\n                  rewrite Int.repr_unsigned.\n                  rewrite sum_recurse with (i := i). des_ifs.\n                  rewrite Z.eqb_eq in Heq.\n                  exploit Int.eq_spec. instantiate (1:=i). instantiate (1:=Int.zero).\n                  unfold Int.eq. unfold Int.unsigned. rewrite Heq. des_ifs. i. subst i.\n                  rewrite Int.sub_zero_r. rewrite sum_recurse. des_ifs. }\n\n            eapply star_left with (t1 := E0) (t2 := E0); ss.\n            { econs; eauto.\n              { eapply modsem2_determinate; eauto. }\n              econs; eauto.\n            }\n\n            eapply star_left with (t1 := E0) (t2 := E0); ss.\n            { econs; eauto.\n              { eapply modsem2_determinate; eauto. }\n              econs; eauto.\n              - econs; eauto. ss.\n              - econs; eauto.\n              - econs; eauto. }\n\n            eapply star_refl.\n          }\n          { refl. }\n\n          right. eapply CIH.\n          { eapply SimMemInjInvC.sim_skenv_inj_lepriv; cycle 1; eauto.\n            etrans; eauto.\n            { exploit (SimMemLift.lift_priv sm0); eauto. ss. }\n            etrans; eauto; cycle 1.\n            { hexploit SimMem.pub_priv; try apply MLE0. eauto. }\n            etrans; eauto.\n            { hexploit SimMem.pub_priv; try apply MLE; eauto. }\n            hexploit SimMemLift.unlift_priv; revgoals.\n            { intro T. ss. eauto. }\n            { eauto. }\n            { eauto. }\n            { exploit (SimMemLift.lift_priv sm0); eauto. ss. }\n            { econs; eauto. } }\n          { econs; ss.\n            - replace (Int.add (sum (Int.sub i Int.one)) i) with (sum i); cycle 1.\n              { rewrite sum_recurse with (i := i). des_ifs.\n                rewrite Z.eqb_eq in Heq.\n                exploit Int.eq_spec. instantiate (1:=i). instantiate (1:=Int.zero).\n                unfold Int.eq. unfold Int.unsigned. rewrite Heq. des_ifs. i. subst i.\n                rewrite Int.sub_zero_r. rewrite sum_recurse. des_ifs. }\n\n              econs 2.\n          }\n      }\n\n      { hexploit VAL; eauto. i. des. clarify.\n\n        econs 2. ii.\n        econs 2.\n        { split.\n          - econs 2; ss.\n            + econs; eauto.\n            + econs; eauto.\n            + ss.\n          - eapply Ord.lift_idx_spec. eauto. }\n        refl.\n\n        left. pfold.\n        econs.\n        i; des.\n        econs 2; eauto.\n        * esplits; cycle 1.\n          { eapply Ord.lift_idx_spec. eauto. }\n\n          eapply plus_left with (t1 := E0) (t2 := E0); ss.\n          { econs; eauto.\n            { eapply modsem2_determinate; eauto. }\n            econs; eauto.\n            econs; ss; eauto; try (by repeat (econs; ss; eauto)).\n            unfold _x. unfold _t'1. rr. ii; ss. des; ss; clarify.\n          }\n\n          eapply star_left with (t1 := E0) (t2 := E0); ss.\n          { econs; eauto.\n            { eapply modsem2_determinate; eauto. }\n            econs; eauto.\n          }\n\n          eapply star_left with (t1 := E0) (t2 := E0); ss.\n          { econs; eauto.\n            { eapply modsem2_determinate; eauto. }\n            econs; eauto.\n            - repeat econs; et.\n            - ss. rewrite Int.eq_false; ss.\n          }\n\n          eapply star_left with (t1 := E0) (t2 := E0); ss.\n          { econs; eauto.\n            { eapply modsem2_determinate; eauto. }\n            econs; eauto.\n          }\n\n          eapply star_left with (t1 := E0) (t2 := E0); ss.\n          { econs; eauto.\n            { eapply modsem2_determinate; eauto. }\n            econs; eauto.\n          }\n\n          eapply star_left with (t1 := E0) (t2 := E0); ss.\n          { econs; eauto.\n            { eapply modsem2_determinate; eauto. }\n            econs; eauto; swap 1 2.\n            - econs.\n              + ss. econs. econs; ss.\n                * econs.\n                  { eapply eval_Evar_global; ss.\n                    instantiate (1:=b). ss. }\n                  { econs 2; ss. }\n                * econs; ss.\n                * ss.\n              + econs 1; ss. psimpl.\n                replace (Ptrofs.unsigned (Ptrofs.mul (Ptrofs.repr 4) (Ptrofs.of_ints i)))\n                  with (4 * Int.intval i); cycle 1.\n                { unfold Ptrofs.mul. ss.\n                  destruct i. ss. unfold Ptrofs.of_ints. ss.\n                  unfold Int.signed. ss. des_ifs; cycle 1;\n                  unfold Int.half_modulus, Int.modulus, two_power_nat in *; ss;\n                    unfold MAX in *; rewrite <- Zdiv2_div in *; ss.\n                  { lia. }\n                  repeat rewrite Ptrofs.unsigned_repr. auto.\n                  all : unfold Ptrofs.max_unsigned; rewrite Ptrofs.modulus_power;\n                  unfold Ptrofs.zwordsize, Ptrofs.wordsize, Wordsize_Ptrofs.wordsize; des_ifs; ss; omega. } eauto. }\n\n          eapply star_left with (t1 := E0) (t2 := E0); ss.\n          { econs; eauto.\n            { eapply modsem2_determinate; eauto. }\n            econs; eauto.\n          }\n\n          eapply star_left with (t1 := E0) (t2 := E0); ss.\n          { econs; eauto.\n            { eapply modsem2_determinate; eauto. }\n            econs; eauto.\n          }\n\n          eapply star_left with (t1 := E0) (t2 := E0); ss.\n          { econs; eauto.\n            { eapply modsem2_determinate; eauto. }\n            ss. econs; eauto.\n            - econs; ss.\n              + econs; ss.\n              + econs; ss.\n              + ss.\n            - ss. instantiate (1:=false).\n              unfold Cop.bool_val. ss.\n              unfold Int.eq. unfold Val.of_bool.\n              destruct (zeq (Int.unsigned (sum (Int.repr (Int.intval i))))\n                            (Int.unsigned (Int.repr 0))) eqn:EQ; ss. }\n\n          eapply star_left with (t1 := E0) (t2 := E0); ss.\n          { econs; eauto.\n            { eapply modsem2_determinate; eauto. }\n            econs; eauto.\n          }\n\n          eapply star_left with (t1 := E0) (t2 := E0); ss.\n          { econs; eauto.\n            { eapply modsem2_determinate; eauto. }\n            econs; eauto.\n            - econs; ss.\n            - econs.\n            - ss. }\n\n          apply star_refl.\n\n        * refl.\n\n        * right. eapply CIH; eauto.\n          { econs; eauto.\n            - ss. replace (Int.repr (Int.intval i)) with i.\n              + econs; eauto.\n              + symmetry. eapply Int.eqm_repr_eq.\n                eapply Int.eqm_refl2. ss.\n            - econs; eauto. }\n      }\n\n  - (* return *)\n    econs 4; ss; eauto.\n    + refl.\n    + econs; ss; eauto.\nQed.\n\nTheorem sim_modsem\n  :\n    ModSemPair.sim msp\n.\nProof.\n  eapply sim_mod_sem_implies.\n  eapply ModSemPair.simL_intro with (has_footprint := top3) (mle_excl := fun _ _ => SimMem.le).\n  { i. eapply SoundTop.sound_state_local_preservation. }\n  { i. eapply Preservation.local_preservation_noguarantee_weak; eauto. eapply SoundTop.sound_state_local_preservation. }\n  { ii; ss. r. etrans; eauto. }\n  { ii. eauto. }\n  i. ss. esplits; eauto.\n\n  - i. des. inv SAFESRC.\n    esplits; eauto.\n    + refl.\n    + econs; eauto.\n    + instantiate (1:= (Ord.lift_idx lt_wf 15%nat)).\n      inv INITTGT. inv TYP. ss.\n      assert (FD: fd = func_f).\n      { destruct args_src, args_tgt; ss. clarify.\n        inv SIMARGS; ss. clarify. inv VALS. inv H1. inv H3. inv FPTR. ss.\n        des_ifs.\n        inv SIMSKENV. ss. inv SIMSKE. ss. inv INJECT. ss.\n        exploit IMAGE; eauto.\n        { exploit Genv.genv_symb_range.\n          unfold Genv.find_symbol in SYMB. eauto. i. ss. eauto. }\n        ii. des. subst. clarify.\n\n        rewrite Genv.find_funct_ptr_iff in FINDF.\n        unfold Genv.find_def in FINDF. ss.\n        do 2 rewrite MapsC.PTree_filter_map_spec, o_bind_ignore in *.\n        des_ifs.\n        destruct (Genv.invert_symbol\n                    (SkEnv.project skenv_link (CSk.of_program signature_of_function prog)) b2) eqn:SKENVSYMB; ss.\n        unfold o_bind in FINDF. ss.\n        exploit Genv.find_invert_symbol. eauto. i.\n        rewrite H in *. clarify.\n        destruct ((prog_defmap prog) ! f_id) eqn:DMAP; ss. clarify. } clarify.\n\n      inv SIMARGS; ss. rewrite VS in *. inv VALS.\n      inv H3. inv H1.\n      unfold typify_list, zip, typify. ss. des_ifs; ss.\n\n      eapply match_states_lxsim; ss.\n      * inv SIMSKENV; eauto.\n      * econs; eauto.\n        { econs; eauto. omega. }\n\n  - (* init progress *)\n    i.\n    des. inv SAFESRC.\n    inv SIMARGS; ss.\n\n    esplits; eauto. econs; eauto.\n    + instantiate (1:= func_f).\n      ss.\n      inv VALS; ss. inv H1. inv H0. inv FPTR0. ss.\n      des_ifs.\n      inv SIMSKENV. ss. inv SIMSKE. ss. inv INJECT. ss.\n      exploit IMAGE; eauto.\n      { exploit Genv.genv_symb_range.\n        unfold Genv.find_symbol in SYMB. eauto. i. ss. eauto. }\n      ii. des. subst. clarify.\n\n      rewrite Genv.find_funct_ptr_iff in *.\n      unfold Genv.find_def in *; ss.\n      do 2 rewrite MapsC.PTree_filter_map_spec, o_bind_ignore in *.\n      des_ifs.\n      exploit Genv.find_invert_symbol. eauto. i.\n      rewrite H0 in *. clarify.\n    + econs; ss. erewrite <- inject_list_length; eauto.\n      rewrite VS. auto.\nQed.\n\n\nEnd SIMMODSEM.\n\n\nTheorem sim_mod\n  :\n    ModPair.sim (ModPair.mk (MutrecAspec.module) (ClightC.module2 prog) (SimMemInjInvC.mk symbol_memoized (MutrecAspec.module) (ClightC.module2 prog)))\n.\nProof.\n  econs; ss.\n  - econs; ss.\n    + i. inv SS. esplits; ss; eauto.\n      * econs; ss.\n        ii. des. econs.\n        { ii. ss. des. clarify. econs; ss.\n          - ii. eapply PERM; eauto. unfold MAX in *. lia.\n          - eapply Z.divide_factor_l. }\n        { ss. i. clarify. erewrite INIT; ss; eauto.\n          - esplits; eauto. i. rewrite sum_recurse. des_ifs.\n          - lia.\n          - unfold MAX. lia.\n          - eapply Z.divide_factor_l. }\n      * ii. des; clarify.\n    + ii. destruct H. eapply in_prog_defmap in PROG.\n      ss. unfold update_snd in PROG. ss.\n      des; clarify; inv DROP; ss.\n      des; clarify.\n  - ii. ss.\n    inv SIMSKENVLINK. inv SIMSKENV.\n    eapply sim_modsem; eauto.\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/demo/mutrec/MutrecAproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.27425057707139366}}
{"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.\nSet Implicit Arguments.\n\nSection section_ccompat_tm_app_tm.\n\nContext (EV LV : Set).\nContext (Ξ : XEnv EV LV).\nContext (δ₁ δ₂ : EV → eff0) (δ : EV → IRel 𝓤_Sig).\nContext (ρ₁ ρ₂ : LV → lbl0) (ρ : LV → IRel 𝓣_Sig).\nContext (S : ty ∅ EV LV ∅) (σ : ms ∅ EV LV ∅) (ℓ : lbl LV ∅) (E : eff ∅ EV LV ∅).\n\nLemma ccompat_tm_app_tm2 n ξ₁ ξ₂ (v₁ v₂ : val0) (s₁ s₂ : tm0) :\n  n ⊨ 𝓥⟦ Ξ ⊢ (ty_ms (ms_tm S σ) ℓ) ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ v₁ v₂ →\n  n ⊨ 𝓣⟦ Ξ ⊢ S # E ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ s₁ s₂ →\n  n ⊨ 𝓣⟦ Ξ ⊢ (ty_ms σ ℓ) # E ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ (tm_app_tm v₁ s₁) (tm_app_tm v₂ s₂).\nProof.\nintros Hv Hs.\nchange (tm_app_tm (tm_val v₁) s₁)\nwith (ktx_plug (ktx_app_tm2 ktx_hole v₁) s₁).\nchange (tm_app_tm (tm_val v₂) s₂)\nwith (ktx_plug (ktx_app_tm2 ktx_hole v₂) s₂).\neapply plug0 ; try apply Hs ;\n  [ crush | crush | | apply postfix_refl | apply postfix_refl ].\n\niintro ξ₁' ; iintro ξ₂' ; iintro Hξ₁' ; iintro Hξ₂'.\niintro u₁ ; iintro u₂ ; iintro Hu.\nsimpl ktx_plug.\n\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_tm | ].\neapply 𝓣_step_l ; [ apply step_app_tm | ].\niintro_later.\napply 𝓥_in_𝓣.\nsimpl 𝓥_Fun.\nrepeat ieexists ; repeat isplit ; [ crush | assumption | ].\n\nielim_vars Hr ; [ | eassumption | eassumption ].\niespecialize Hr ; ispecialize Hr ; [ eassumption | ].\napply Hr.\nQed.\n\nLemma ccompat_tm_app_tm n ξ₁ ξ₂ (t₁ t₂ s₁ s₂ : tm0) :\n  n ⊨ 𝓣⟦ Ξ ⊢ (ty_ms (ms_tm S σ) ℓ) # E ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ →\n  n ⊨ ( ∀ᵢ ξ₁' ξ₂' (_ : postfix ξ₁ ξ₁') (_ : postfix ξ₂ ξ₂'),\n        𝓣⟦ Ξ ⊢ S # E ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁' ξ₂' s₁ s₂\n      ) →\n  n ⊨ 𝓣⟦ Ξ ⊢ (ty_ms σ ℓ) # E ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ (tm_app_tm t₁ s₁) (tm_app_tm t₂ s₂).\nProof.\nintros Ht Hs.\nchange (tm_app_tm t₁ s₁)\nwith (ktx_plug (ktx_app_tm1 ktx_hole s₁) t₁).\nchange (tm_app_tm t₂ s₂)\nwith (ktx_plug (ktx_app_tm1 ktx_hole s₂) t₂).\neapply plug0 ; try apply Ht ;\n  [ crush | crush | | apply postfix_refl | apply postfix_refl ].\n\niintro ξ₁' ; iintro ξ₂' ; iintro Hξ₁' ; iintro Hξ₂'.\niintro v₁ ; iintro v₂ ; iintro Hv.\nsimpl ktx_plug.\n\nielim_vars Hs ; [ | eassumption | eassumption ].\napply ccompat_tm_app_tm2 ; eauto.\nQed.\n\nEnd section_ccompat_tm_app_tm.\n\n\nSection section_compat_tm_app_tm.\n\nContext (EV LV V : Set).\nContext (Ξ : XEnv EV LV).\nContext (Γ : V → ty ∅ EV LV ∅).\nContext (S : ty ∅ EV LV ∅) (σ : ms ∅ EV LV ∅) (ℓ : lbl LV ∅) (E : eff ∅ EV LV ∅).\n\nLemma compat_tm_app_tm n t₁ t₂ s₁ s₂ :\nn ⊨ ⟦ Ξ Γ ⊢ t₁ ≼ˡᵒᵍ t₂ : (ty_ms (ms_tm S σ) ℓ) # E ⟧ →\nn ⊨ ⟦ Ξ Γ ⊢ s₁ ≼ˡᵒᵍ s₂ : S # E ⟧ →\nn ⊨ ⟦ Ξ Γ ⊢ (tm_app_tm t₁ s₁) ≼ˡᵒᵍ (tm_app_tm t₂ s₂) : (ty_ms σ ℓ) # E ⟧.\nProof.\nintros Ht Hs.\niintro ξ₁ ; iintro ξ₂ ;\niintro δ₁ ; iintro δ₂ ; iintro δ ;\niintro ρ₁ ; iintro ρ₂ ; iintro ρ ;\niintro γ₁ ; iintro γ₂.\niintro Hξ ; iintro Hδ ; iintro Hρ ; iintro Hγ.\nsimpl subst_tm.\neapply ccompat_tm_app_tm.\n+ iespecialize Ht.\n  ispecialize Ht ; [ eassumption | ].\n  ispecialize Ht ; [ eassumption | ].\n  ispecialize Ht ; [ eassumption | ].\n  ispecialize Ht ; [ eassumption | ].\n  apply Ht.\n+ iintro ξ₁' ; iintro ξ₂' ; iintro Hξ₁' ; iintro Hξ₂'.\n  ispecialize Hs ξ₁' ; ispecialize Hs ξ₂' ; iespecialize Hs.\n  ispecialize Hs.\n  { ielim_prop Hξ ; iintro_prop ; eapply 𝜩_monotone ; eauto. }\n  ispecialize Hs.\n  { eapply δ_is_closed_monotone ; eassumption. }\n  ispecialize Hs.\n  { ielim_prop Hρ ; iintro_prop ; eapply ρ₁ρ₂_are_closed_monotone ; eauto. }\n  ispecialize Hs.\n  { eapply 𝜞_monotone ; eauto. }\n  apply Hs.\nQed.\n\nLemma compat_ktx_app_tm1 n T' E' K₁ K₂ s₁ s₂ :\n  n ⊨ ⟦ Ξ Γ ⊢ K₁ ≼ˡᵒᵍ K₂ : T' # E' ⇢ (ty_ms (ms_tm S σ) ℓ) # E ⟧ →\n  n ⊨ ⟦ Ξ Γ ⊢ s₁ ≼ˡᵒᵍ s₂ : S # E ⟧ →\n  n ⊨ ⟦ Ξ Γ ⊢ (ktx_app_tm1 K₁ s₁) ≼ˡᵒᵍ (ktx_app_tm1 K₂ s₂) : T' # E' ⇢ (ty_ms σ ℓ) # E ⟧.\nProof.\nintros HK Hs.\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 ; ispecialize HK ; [ apply Ht | ].\n\nsimpl ktx_plug.\neapply ccompat_tm_app_tm ; [ apply HK | ].\niintro ξ₁'' ; iintro ξ₂'' ; iintro Hξ₁'' ; iintro Hξ₂''.\nispecialize Hs ξ₁''; ispecialize Hs ξ₂'' ; iespecialize Hs.\nispecialize Hs.\n{ ielim_prop Hξ ; iintro_prop ; eapply 𝜩_monotone ; eauto using postfix_trans. }\nispecialize Hs.\n{ eapply δ_is_closed_monotone ; eauto using postfix_trans. }\nispecialize Hs.\n{ ielim_prop Hρ ; iintro_prop ; eapply ρ₁ρ₂_are_closed_monotone ; eauto using postfix_trans. }\nispecialize Hs.\n{ eapply 𝜞_monotone ; eauto using postfix_trans. }\napply Hs.\nQed.\n\nLemma compat_ktx_app_tm2 n T' E' K₁ K₂ v₁ v₂ :\n  n ⊨ ⟦ Ξ Γ ⊢ K₁ ≼ˡᵒᵍ K₂ : T' # E' ⇢ S # E ⟧ →\n  n ⊨ ⟦ Ξ Γ ⊢ v₁ ≼ˡᵒᵍᵥ v₂ : ty_ms (ms_tm S σ) ℓ ⟧ →\n  n ⊨ ⟦ Ξ Γ ⊢ (ktx_app_tm2 K₁ v₁) ≼ˡᵒᵍ (ktx_app_tm2 K₂ v₂) : T' # E' ⇢ (ty_ms σ ℓ) # E ⟧.\nProof.\nintros HK Hs.\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 ; ispecialize HK ; [ apply Ht | ].\n\nsimpl ktx_plug.\neapply ccompat_tm_app_tm2 ; [ | apply HK ].\nispecialize Hs ξ₁'; ispecialize Hs ξ₂' ; iespecialize Hs.\nispecialize Hs.\n{ ielim_prop Hξ ; iintro_prop ; eapply 𝜩_monotone ; eauto using subset_trans. }\nispecialize Hs.\n{ eapply δ_is_closed_monotone ; eauto using subset_trans. }\nispecialize Hs.\n{ ielim_prop Hρ ; iintro_prop ; eapply ρ₁ρ₂_are_closed_monotone ; eauto using subset_trans. }\nispecialize Hs.\n{ eapply 𝜞_monotone ; eauto using subset_trans. }\napply Hs.\nQed.\n\nEnd section_compat_tm_app_tm.\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_tm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2742023990032687}}
{"text": "Require Import HoareDef STB CannonRA CannonMain0 CannonMain1 Cannon1 SimModSem.\nRequire Import Coqlib.\nRequire Import ImpPrelude.\nRequire Import Skeleton.\nRequire Import PCM.\nRequire Import ModSem Behavior.\nRequire Import HTactics ProofMode.\n\nSet Implicit Arguments.\n\n\n\nSection SIMMODSEM.\n\n  Context `{Σ: GRA.t}.\n  Context `{@GRA.inG CannonRA Σ}.\n\n  Let W: Type := Any.t * Any.t.\n\n  Variable GlobalStb: Sk.t -> gname -> option fspec.\n  Hypothesis GlobalStb_fire: forall sk, GlobalStb sk \"fire\" = Some fire_spec.\n\n  Let wf: _ -> W -> Prop :=\n    @mk_wf\n      _\n      unit\n      (fun _ _ _ => (True)%I)\n  .\n\n  Theorem correct: refines2 [CannonMain0.Main 1] [CannonMain1.Main 1 GlobalStb].\n  Proof.\n    eapply adequacy_local2. econs; ss.\n    i. econstructor 1 with (wf:=wf) (le:=top2); et; ss; cycle 1.\n    { exists tt. red. econs. eapply to_semantic. iIntros \"H\". ss. }\n    econs; ss. init. harg.\n    mDesAll. des; clarify. steps.\n    unfold ccallU. steps. rewrite GlobalStb_fire. steps.\n    hcall _ _ with \"A\".\n    { iModIntro. iSplits; ss. }\n    { splits; ss. }\n    mDesAll. des; clarify. steps. 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/cannon/CannonMain01proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.27420239900326865}}
{"text": "From iris Require Import program_logic.weakestpre.\nFrom iris.program_logic Require Import ectx_language ectxi_language.\nFrom st.STLCmuST Require Import lang types typing.\nFrom st.backtranslations.st_sem.correctness.sem_le_st.logrel Require Import lift definition.\n\nLemma rtc_bind_help n e w u σ σ' u' σ'' :\n  nsteps STLCmuST_step n (σ, RunST e) (σ'', of_val u') →\n  rtc STLCmuST_step (σ'', RunST (App (of_val w) (of_val u'))) (σ', of_val u) →\n  rtc STLCmuST_step (σ, RunST (Bind e (of_val w))) (σ', of_val u).\nProof.\n   revert w e u u' σ σ' σ''.\n    induction n => w e u u' σ σ' σ'' Hrd1 Hrd2 /=.\n  - inversion Hrd1 as [Hs1 Hs2 Hs3 Hs4|]; subst.\n    assert (Hkv : to_val (RunST e) = Some u') by\n        by rewrite H to_of_val.\n    exfalso; by inversion Hkv.\n  - inversion Hrd1 as [|Hs1 Hs2 [σ2 e2] Hs4 Hs5 Hs6]; subst; simpl in *.\n    inversion Hs5 as [? ? ? Hfl ? Hhd]; subst.\n    destruct K as [|[] K] using rev_ind; simpl in *;\n      (try rewrite fill_app /= in Hfl); inversion Hfl; subst.\n    + inversion Hhd; subst.\n      * specialize (IHn _ _ _ _ _ _ _ Hs6 Hrd2).\n        apply rtc_l with (y := (σ2, RunST (Bind e' w))); eauto.\n        apply head_prim_step.\n        econstructor.\n        inversion H1 as [K ? ? ?]; subst.\n        eapply (@Ectx_step eff_ectx_lang _ _ _ _ _ _ (K ++ [BindECtx _])); eauto;\n          by rewrite /= (@fill_app eff_ectxi_lang) /=.\n      * inversion Hs6; subst; simpl in *.\n        -- eapply rtc_l; simpl; eauto.\n           apply head_prim_step.\n           econstructor.\n           apply head_prim_step.\n           econstructor; eauto using to_of_val.\n        -- destruct y. erewrite (language.val_stuck) in H1; eauto. inversion H1.\n    + rewrite fill_app in Hs6 Hrd2. specialize (IHn _ _ _ _ _ _ _ Hs6 Hrd2).\n      apply rtc_l with (y := (σ2, (RunST (Bind (fill K e2') (of_val w))))); auto.\n      apply (fill_prim_step [BindLCtx _; RunSTCtx]).\n      apply (fill_prim_step K). by apply head_prim_step.\nQed.\n\nLemma rtc_bind_lemma (σ0 σ1 σ2 σ3 : state) (v f w s r : val) :\n  rtc STLCmuST_step (σ0, RunST v) (σ1, of_val w) →\n  rtc STLCmuST_step (σ1, ((of_val f) (of_val w))) (σ2, of_val s) →\n  rtc STLCmuST_step (σ2, RunST s) (σ3, of_val r) →\n  rtc STLCmuST_step (σ0, RunST (Bind v f)) (σ3, of_val r).\nProof.\n  intros H0 H1 H2. destruct (rtc_nsteps_1 _ _ H0) as [n H0'].\n  apply (rtc_bind_help _ _ _ _ _ _ _ _ H0').\n  apply rtc_transitive with (y := (σ2, RunST s)). by apply (fill_STLCmuST_step_rtc [RunSTCtx]).\n  auto.\nQed.\n\nFrom iris.proofmode Require Import tactics.\nFrom iris.base_logic.lib Require Import invariants gen_heap.\nFrom st.backtranslations.st_sem Require Import ghost heap_emul.base.\nFrom st.STLCmuVS Require Import lang.\nFrom st Require Import resources.\n\nLocal Notation \"l ↦ v\" := (mapsto l (DfracOwn 1) v)\n  (at level 20, format \"l  ↦  v\") : bi_scope.\n\nSection valrel_cons_ren.\n\n  Context `{Σ : !gFunctors} `{sem_le_stΣ_inst : !sem_le_stΣ Σ}.\n\n  (* super boring lemma *)\n  Lemma valrel_typed_cons_ren γ γ' Δ : ∀ τ v v', valrel_typed ((γ,γ') :: Δ) τ.[ren (+1)] v v' ⊣⊢ valrel_typed Δ τ v v'.\n  Proof.\n    iLöb as \"IHlob\".\n    iIntros (τ). iInduction τ as [ | | | τ1 τ2 | τ1 τ2 | τ1 τ2 | τb | | τ1 τ2 | τ1 τ2 ] \"IH\".\n    - setoid_rewrite valrel_typed_TUnit_unfold; auto.\n    - setoid_rewrite valrel_typed_TBool_unfold; auto.\n    - setoid_rewrite valrel_typed_TInt_unfold; auto.\n    - setoid_rewrite valrel_typed_TProd_unfold.\n      iIntros (v v').\n      iSplit.\n      + iIntros \"Hdes\". iDestruct \"Hdes\" as (v1 v2 v1' v2') \"(eq1 & eq2 & H1 & H2)\".\n        repeat iExists _. repeat iSplit; auto. by iApply \"IH\". by iApply \"IH1\".\n      + iIntros \"Hdes\". iDestruct \"Hdes\" as (v1 v2 v1' v2') \"(eq1 & eq2 & H1 & H2)\".\n        repeat iExists _. repeat iSplit; auto. by iApply \"IH\". by iApply \"IH1\".\n    - setoid_rewrite valrel_typed_TSum_unfold.\n      iIntros (v v').\n      iSplit.\n      + iIntros \"Hdes\". iDestruct \"Hdes\" as (v1 v1') \"[(eq1 & eq2 & H) | (eq1 & eq2 & H)]\".\n        * repeat iExists _. iLeft. repeat iSplit; eauto. by iApply \"IH\".\n        * repeat iExists _. iRight. repeat iSplit; eauto. by iApply \"IH1\".\n      + iIntros \"Hdes\". iDestruct \"Hdes\" as (v1 v1') \"[(eq1 & eq2 & H) | (eq1 & eq2 & H)]\".\n        * repeat iExists _. iLeft. repeat iSplit; eauto. by iApply \"IH\".\n        * repeat iExists _. iRight. repeat iSplit; eauto. by iApply \"IH1\".\n    - setoid_rewrite valrel_typed_TArrow_unfold.\n      iIntros (w w'). iSplit.\n      + iIntros \"#H\". iModIntro. iIntros (v v') \"#H1\".\n        iApply (lift_wand _ (valrel_typed ((γ,γ') :: Δ) τ3.[ren (+1)])). iIntros (x x') \"Hxx'\". by iApply \"IH1\".\n        iApply \"H\". by iApply \"IH\".\n      + iIntros \"#H\". iModIntro. iIntros (v v') \"#H1\".\n        iApply (lift_wand _ (valrel_typed (Δ) τ3)). iIntros (x x') \"Hxx'\". by iApply \"IH1\".\n        iApply \"H\". by iApply \"IH\".\n    - setoid_rewrite valrel_typed_TRec_unfold.\n      iIntros (v v'). iSplit.\n      + iIntros \"Hdes\". iDestruct \"Hdes\" as (w w') \"(eq & eq' & H)\".\n        iExists w, w'. repeat iSplit; auto. iNext. iApply \"IHlob\". by asimpl.\n      + iIntros \"Hdes\". iDestruct \"Hdes\" as (w w') \"(eq & eq' & H)\".\n        iExists w, w'. repeat iSplit; auto. iNext.\n        assert (τb.[up (ren (+1))].[TRec τb.[up (ren (+1))]/] =\n                τb.[TRec τb/].[ren (+1)]\n               ) as eq; first by asimpl. rewrite eq. by iApply \"IHlob\".\n    - setoid_rewrite valrel_typed_TVar_unfold. auto.\n    - setoid_rewrite valrel_typed_TSTRef_unfold; auto.\n      destruct τ1; auto; destruct (Δ !! X) as [[γ'' γ''']|] eqn:eq; rewrite /= eq; try done.\n      iIntros (v v'). iSplit.\n      + iIntros \"Hdes\". iDestruct \"Hdes\" as (i l) \"(-> & -> & Hil & H)\". iExists i, l. repeat iSplit; auto.\n        iApply (inv_iff with \"H\"). repeat iModIntro. iSplit.\n        * iIntros \"Hdes\". iDestruct \"Hdes\" as (w w') \"[Hi [Hl Hww']]\". iExists w, w'. iFrame \"Hi Hl\". by iApply \"IH1\".\n        * iIntros \"Hdes\". iDestruct \"Hdes\" as (w w') \"[Hi [Hl Hww']]\". iExists w, w'. iFrame \"Hi Hl\". by iApply \"IH1\".\n      + iIntros \"Hdes\". iDestruct \"Hdes\" as (i l) \"(-> & -> & Hil & H)\". iExists i, l. repeat iSplit; auto.\n        iApply (inv_iff with \"H\"). repeat iModIntro. iSplit.\n        * iIntros \"Hdes\". iDestruct \"Hdes\" as (w w') \"[Hi [Hl Hww']]\". iExists w, w'. iFrame \"Hi Hl\". by iApply \"IH1\".\n        * iIntros \"Hdes\". iDestruct \"Hdes\" as (w w') \"[Hi [Hl Hww']]\". iExists w, w'. iFrame \"Hi Hl\". by iApply \"IH1\".\n    - setoid_rewrite valrel_typed_TST_unfold; auto.\n      destruct τ1; auto; destruct (Δ !! X) as [[γ'' γ''']|] eqn:eq; rewrite /= eq; try done.\n      iIntros (w w'). iSplit.\n      + iIntros \"#H\". iIntros (ps σ). iModIntro. iIntros \"Hσ AuthVals AuthLocs\". iSpecialize (\"H\" $! ps σ with \"Hσ AuthVals AuthLocs\"). iApply (wp_wand with \"H\").\n        iIntros (v) \"Hdes\". iDestruct \"Hdes\" as (w1 w1' ps1 σ1) \"(-> & Hσ1 & Hauth1 & Hauth2 & Hstep & H)\". iExists w1, w1', ps1, σ1. iFrame. iSplit; auto.\n        by iApply \"IH1\".\n      + iIntros \"#H\". iIntros (ps σ). iModIntro. iIntros \"Hσ AuthVals AuthLocs\". iSpecialize (\"H\" $! ps σ with \"Hσ AuthVals AuthLocs\"). iApply (wp_wand with \"H\").\n        iIntros (v) \"Hdes\". iDestruct \"Hdes\" as (w1 w1' ps1 σ1) \"(-> & Hσ1 & Hauth1 & Hauth2 & Hstep & H)\". iExists w1, w1', ps1, σ1. iFrame. iSplit; auto.\n        by iApply \"IH1\".\n  Qed.\n\nEnd valrel_cons_ren.\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/sem_le_st/logrel/compat_help.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.2741681057806229}}
{"text": "Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq tuple.\nRequire Import bitsrep bitsops bitsopsprops monad writer reg instr instrsyntax program programassem cursor.\nRequire Import pecoff cfunc.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nOpen Scope instr_scope.\nOpen Scope string_scope.\n\nRequire Import call.\nExample counterDLL :=\n  GLOBAL Get as \"Get\";\n  GLOBAL Inc as \"Inc\";\n  GLOBAL Counter;\n  SECTION CODE\n    Inc:;;  mkbody_toyfun (MOV ECX, Counter;; INC [ECX]);;\n    Get:;;  mkbody_toyfun (MOV ECX, Counter;; MOV EAX, [ECX]);\n  SECTION DATA\n    Counter:;; dd #0.\n\nCompute makeDLL #x\"00AC0000\" \"counter.dll\" counterDLL.\n\n(*\nRequire Import SPred septac spectac spec safe pointsto cursor instr.\nRequire Import basic basicprog program instrsyntax macros instrrules.\nRequire Import Setoid RelationClasses Morphisms.\n\nExample counterModuleSpec IAT P Inc Get :=\n      (Forall c: DWORD, toyfun Inc (P c ** ECX? ** OSZCP?) (P (c +# 1) ** ECX? ** OSZCP?))\n    //\\\\\n      (Forall c: DWORD, toyfun Get (EAX? ** P c ** ECX? ** OSZCP?) (EAX ~= c ** P c ** ECX? ** OSZCP?))\n    <@ (IAT :-> (Inc, Get)).\n\nExample counterModuleCode (Inc Get Counter: DWORD) :=\n(*  LOCAL Inc; LOCAL Get; LOCAL Counter;*)\n    Inc:;;  mkbody_toyfun (MOV ECX, Counter;; INC [ECX]);;\n    Get:;;  mkbody_toyfun (MOV ECX, Counter;; MOV EAX, [ECX]).\n\nExample counterModuleData :=\n    dd #0.\n\nExample counterModuleIAT Inc Get :=\n    dd Inc;; dd Get.\n\nRequire Import flags.\nTheorem counterModuleCorrect (codeStart codeEnd dataStart:DWORD):\n  |-- Forall Inc, Forall Get,\n      counterModuleSpec codeStart (fun v => dataStart :-> v) Inc Get <@ (codeStart -- codeEnd :-> counterModuleCode Inc Get dataStart).\nProof.\nrewrite /counterModuleSpec.\nrewrite /counterModuleCode.\nspecintros => Inc Get. unfold_program.\n\nspecintros => i1 -> -> i2 i3 -> ->.\nrewrite !empSPL.\nspecsplit.\n(* Inc *)\nspecintros => c.\nrewrite <- spec_reads_merge.\nrewrite <- spec_reads_frame.\n  etransitivity; [|apply toyfun_mkbody]. specintro => iret.\n  rewrite /flagAny. specintros => O S Z C P. autorewrite with push_at.\n  basicapply MOV_RI_rule.\n  basicapply INC_M_rule. rewrite addB0.\n  rewrite /OSZCP. sbazooka. rewrite addB1 addB0. rewrite /regAny.\n  sbazooka.\n  rewrite /OSZCP. ssimpl. reflexivity.\n\n(* Get *)\nspecintros => c.\nrewrite spec_reads_swap.\nrewrite <- spec_reads_frame.\nrewrite <- spec_reads_merge.\nrewrite <- spec_reads_swap.\nrewrite <- spec_reads_frame.\n  etransitivity; [|apply toyfun_mkbody]. specintro => iret.\n  rewrite /flagAny. specintros => O S Z C P. autorewrite with push_at.\n  basicapply MOV_RI_rule.\n  basicapply MOV_RM0_rule. rewrite /regAny. sbazooka.\nQed.\n\nExample useCounterModule IAT : program :=\n  MOV EDI, IAT;; call_toyfun [EDI];;\n  MOV EDI, IAT;; call_toyfun [EDI];;\n  MOV EDI, IAT;; call_toyfun [EDI+4].\n\nExample useCounterModuleCorrect (codeStart codeEnd dataStart Inc Get IAT: DWORD):\n  counterModuleSpec codeStart (fun v => dataStart :-> v) Inc Get\n  |-- basic (EAX?) (useCounterModule IAT) (EAX ~= #2) @\n      (EDI? ** OSZCP? ** retreg?) <@ (IAT :-> (Inc,Get)).\nProof.\n  rewrite /useCounterModule. autorewrite with push_at.\n  rewrite <- spec_reads_frame.\n  eapply basic_seq.\n  basicapply MOV_RI_rule.\n  rewrite /counterModuleSpec.\n  apply landL1.\n  - (*apply lforallL with c.*)\n    eapply basic_basic_context.\n    - have H := toyfun_call. setoid_rewrite spec_at_basic in H. apply H.\n    - by apply spec_later_weaken.\n    - by ssimpl.\n    done.\n  apply lforallL with (a +# 2).\n  eapply basic_basic_context.\n  - have H := toyfun_call. setoid_rewrite spec_at_basic in H. apply H.\n  - by apply spec_later_weaken.\n  - by ssimpl.\n  rewrite -addB_addn. rewrite -[2+2]/4. by ssimpl.\nQed.\n\nExample useCounterSpec IAT :\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/win/counter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2741680986886312}}
{"text": "(** * Push-Button Synthesis of fancy mongomery reduction : Reification Cache *)\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.derive.Derive.\nRequire Import Crypto.Arithmetic.Core.\nRequire Import Crypto.Arithmetic.FancyMontgomeryReduction.\nRequire Import Crypto.PushButtonSynthesis.ReificationCache.\nLocal Open Scope Z_scope.\n\nImport Associational Positional.\nImport FancyMontgomeryReduction.MontgomeryReduction.\n\nLocal Set Keyed Unification. (* needed for making [autorewrite] fast, c.f. COQBUG(https://github.com/coq/coq/issues/9283) *)\n\nModule Export MontgomeryReduction.\n  Derive reified_montred_gen\n         SuchThat (is_reification_of reified_montred_gen montred')\n         As reified_montred_gen_correct.\n  Proof. Time cache_reify (). Time Qed.\n  Module Export ReifyHints.\n#[global]\n    Hint Extern 1 (_ = _) => apply_cached_reification montred' (proj1 reified_montred_gen_correct) : reify_cache_gen.\n#[global]\n    Hint Immediate (proj2 reified_montred_gen_correct) : wf_gen_cache.\n#[global]\n    Hint Rewrite (proj1 reified_montred_gen_correct) : interp_gen_cache.\n  End ReifyHints.\n  Local Opaque reified_montred_gen. (* needed for making [autorewrite] not take a very long time *)\nEnd MontgomeryReduction.\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/FancyMontgomeryReductionReificationCache.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.27414681740588903}}
{"text": "Require Export Relations Wellfounded.\nRequire Import Sat.\nRequire Import ZF ZFcoc ZFuniv_real.\nRequire Import ZFlambda.\nRequire Import Models SnModels.\nRequire GenRealSN.\nSet Implicit Arguments.\n\n(** Strong normalization proof of the Calculus of Constructions.\n    It is based on GenRealSN, so it does support strong eliminations.\n    Inhabitation of all types is obtained by adding the empty set in every\n    type (cf ZFuniv_real). The product is interpreted by the set of *partial*\n    functions.\n *)\n\nModule SN := GenRealSN.MakeModel CC_Real.\nExport SN.\nHint Unfold inX.\nExisting Instance in_ext.\n\n(** Derived properties *)\n\nNotation daimont := Sat.SatSet.daimon.\n\nLemma val_ok_cons_default e T i j :\n  val_ok e i j ->\n  T <> kind ->\n  val_ok (T::e) (V.cons empty i) (I.cons daimont j).\nintros.\napply vcons_add_var; trivial.\nsplit.\n red; auto.\n apply varSAT.\nQed.\n\nLemma El_int_prod U V i :\n  El (int (Prod U V) i) == cc_prod (El (int U i)) (fun x => El (int V (V.cons x i))).\nsimpl.\napply El_prod.\ndo 2 red; intros.\nrewrite H0; reflexivity.\nQed.\n\nLemma El_int_arr U V i :\n  El (int (Prod U (lift 1 V)) i) == cc_arr (El (int U i)) (El (int V i)).\nrewrite El_int_prod.\napply cc_prod_morph; auto with *.\nred; intros.\nrewrite int_cons_lift_eq; reflexivity.\nQed.\n\nLemma Real_int_prod U V i f :\n  f ∈ cc_prod (El (int U i)) (fun x => El (int V (V.cons x i))) ->\n  eqSAT (Real (int (Prod U V) i) f)\n        (piSAT (int U i) (fun x => int V (V.cons x i)) (cc_app f)).\nsimpl; intros.\napply Real_prod.\n do 2 red; intros.\n rewrite H1; reflexivity.\n\n change (f ∈ El (int (Prod U V) i)).\n rewrite El_int_prod; trivial.\nQed.\n\nLemma Real_int_arr U V i f :\n  f ∈ cc_arr (El (int U i)) (El (int V i)) ->\n  eqSAT (Real (int (Prod U (lift 1 V)) i) f)\n        (piSAT (int U i) (fun _ => int V i) (cc_app f)).\nintros.\nrewrite Real_int_prod.\n apply piSAT_morph; auto with *.\n  red; intros.\n  apply int_cons_lift_eq.\n\n  red; intros; apply cc_app_morph; auto with *.\n\n revert H; apply eq_elim; apply cc_prod_ext; auto with *.\n red; intros.\n symmetry; apply El_morph; apply int_cons_lift_eq.\nQed.\n\nLemma kind_ok_trivial T : kind_ok T.\nexists nil.\nexists T; simpl; auto with *.\nexists empty; auto with *.\nQed.\nHint Resolve kind_ok_trivial.\n\n(** ** Extendability *)\nDefinition cst (x:set) : term.\n(* begin show *)\nleft; exists (fun _ =>x) (fun _ =>Lambda.K).\n(* end show *)\n do 2 red; reflexivity.\n do 2 red; reflexivity.\n red; reflexivity.\n red; reflexivity.\nDefined.\n\nDefinition mkSET (x:set) := cst (mkTY x (fun _ => snSAT)).\n\nLemma mkSET_kind e x :\n  typ e (mkSET x) kind.\nred; intros.\nsplit;[discriminate|].\nsplit; trivial.\napply Lambda.sn_K.\nQed.\n\nLemma cst_typ e x y :\n  in_set x y ->\n  typ e (cst x) (mkSET y).\nred; intros.\napply in_int_intro; intros; try discriminate.\napply and_split; intros.\n simpl.\n red; rewrite El_def.\n apply union2_intro2; trivial.\n\n simpl.\n rewrite Real_def.\n  apply Lambda.sn_K.\n\n  reflexivity.\n\n  apply union2_intro2; trivial.\nQed.\nLemma cst_eq_typ e x y :\n  x == y ->\n  eq_typ e (cst x) (cst y).\nred; simpl; intros; trivial.\nQed.\n\nLemma cst_eq_typ_inv x y :\n  eq_typ nil (cst x) (cst y) ->\n  x == y.\nintros.\nassert (val_ok nil (V.nil empty) (I.nil Lambda.K)).\n red; intros.\n destruct n; inversion H0.\napply H in H0.\nsimpl in H0; trivial.\nQed.\n\nLemma mkSET_eq_typ e x y :\n  x == y ->\n  eq_typ e (mkSET x) (mkSET y).\nred; simpl; intros; trivial.\napply mkTY_ext; auto with *.\nQed.\n\nLemma mkSET_eq_typ_inv x y :\n  eq_typ nil (mkSET x) (mkSET y) ->\n  x == y.\nintros.\nassert (val_ok nil (V.nil empty) (I.nil Lambda.K)).\n red; intros.\n destruct n; inversion H0.\napply H in H0.\nsimpl in H0.\napply couple_injection in H0; destruct H0; trivial.\nQed.\n\n\nDefinition sub_typ_covariant : forall e U1 U2 V1 V2,\n  U1 <> kind ->\n  eq_typ e U1 U2 ->\n  sub_typ (U1::e) V1 V2 ->\n  sub_typ e (Prod U1 V1) (Prod U2 V2).\nintros.\napply sub_typ_covariant; trivial.\nunfold eqX, inX; intros.\nrewrite El_prod in H3; trivial.\napply cc_eta_eq in H3; trivial.\nQed.\n\n(** ** Choice *)\n(*Require Import ZFcoc SATtypes.\nModule Lc:=Lambda.\n\nDefinition Ch (X:term) : term.\n(* begin show *)\nleft;\nexists (fun i => mkTY (trunc (El(int X i)))\n                      (fun _ => depSAT(fun Y=>forall x,x ∈El(int X i)->\n                                 inclSAT(cartSAT(Real (int X i) x)unitSAT) Y)\n                                      (fun Y=>Y)))\n       (fun j => tm X j).\n(* end show *)\ndo 2 red; intros.\napply mkTY_ext; intros.\n rewrite H; auto with *.\n\n apply interSAT_morph_subset; simpl; intros; auto with *.\n apply fa_morph; intros z.\n rewrite H; reflexivity.\n\ndo 2 red; intros; apply tm_morph; auto with *.\n\nred; intros; apply tm_liftable.\nred; intros; apply tm_substitutive.\nDefined.\n\n\nDefinition ChI (W:term) : term.\n(* begin show *)\nleft; exists (fun i => empty) (fun j => COUPLE (tm W j) ID).\n(* end show *)\ndo 2 red; intros; reflexivity.\n\ndo 2 red; intros.\nf_equal; trivial.\napply tm_morph; auto with *.\n\n (**)\n red; intros.\n unfold COUPLE; simpl.\n rewrite tm_liftable.\n rewrite Lc.permute_lift; reflexivity.\n (**)\n red; intros.\n unfold COUPLE; simpl.\n rewrite tm_substitutive.\n rewrite Lc.commut_lift_subst; reflexivity.\nDefined.\n\nLemma ChI_typ e X W :\n  X <> kind ->\n  typ e W X ->\n  typ e (ChI W) (Ch X).\nunfold typ.\nintros Xnk tyW; intros.\napply in_int_intro; try discriminate.\napply and_split; simpl; intros.\n red; auto.\n\n red in H0; rewrite El_def in H0.\n specialize tyW with (1:=H).\n apply in_int_not_kind in tyW; trivial.\n destruct tyW.\n rewrite Real_def; intros; auto.\n 2:apply interSAT_morph_subset; simpl; auto with *.\n apply interSAT_intro.\n  exists snSAT; intros.\n  red; intros; apply snSAT_intro.\n  apply sat_sn in H4; trivial.\n\n  intros (Y,?); simpl.\n  apply i0 with (int W i); trivial.\n  apply cartSAT_intro; trivial.\n  apply ID_intro.\nQed.\n\nDefinition ChE (X C:term) : term.\n  left; exists (fun i => ZFrepl.uchoice (fun x => x ∈ Elt (int X i)))\n               (fun j => Lc.App (tm C j) (Lc.Abs (Lc.Abs (Lc.Ref 1)))).\n  admit.\n  admit.\n  admit.\n  admit.\nDefined.\n\nLemma ChE_typ e W X :\n  X <> kind ->\n  typ e W (Ch X) ->\n  typ e (ChE X W) X.\nunfold typ; intros Xnk tyW i j valok.\nspecialize tyW with (1:=valok).\napply in_int_not_kind in tyW;[|discriminate].                     \ndestruct tyW as (tyW,satW).\nred in tyW; simpl in tyW; rewrite El_def in tyW.\nsimpl in satW; rewrite Real_def in satW; trivial.\napply in_int_intro; trivial; try discriminate.\napply and_split; intros.\n red; simpl.\n apply cc_bot_intro.\n apply ZFrepl.uchoice_def.\n split.\n  intros.\n  rewrite <- H; trivial.\n split; intros.\n  admit.\n  admit.\n\n simpl.\n red in H; simpl in H.\n set (w:=ZFrepl.uchoice (fun x => x ∈ Elt(int X i))) in *.\n clearbody w.\n apply depSAT_elim' in satW.\n red in satW.\n eapply cartSAT_case with (X:=Real(int X i) w) (Y:=unitSAT).\n apply satW; intros.\n intros ? h; apply h.\n reflexivity.\n \n eexact (fun _ h => h). \n assert (inSAT (tm W j) ; rewrite El_def in H.\nsplit.\n\n(** ** Unique choice *)\n\nDefinition Tr (X:term) : term.\n(* begin show *)\nleft;\nexists (fun i => mkTY (ZFcoc.trunc (El(int X i)))\n                      (fun _ => interSAT(fun Y:{Y|forall x,x ∈El(int X i)->\n                                           inclSAT(Real (int X i) x) Y}=>proj1_sig Y)))\n       (fun j => tm X j).\n(* end show *)\ndo 2 red; intros.\napply mkTY_ext; intros.\n rewrite H; auto with *.\n\n apply interSAT_morph_subset; simpl; intros; auto with *.\n apply fa_morph; intros z.\n rewrite H; reflexivity.\n\ndo 2 red; intros; apply tm_morph; auto with *.\n\nred; intros; apply tm_liftable.\nred; intros; apply tm_substitutive.\nDefined.\n\nDefinition TrI (W:term) : term.\n(* begin show *)\nleft; exists (fun i => empty) (fun j => tm W j).\n(* end show *)\ndo 2 red; intros; reflexivity.\n\ndo 2 red; intros; apply tm_morph; auto with *.\n\nred; intros; apply tm_liftable.\nred; intros; apply tm_substitutive.\nDefined.\n\nLemma TrI_typ e X W :\n  X <> kind ->\n  typ e W X ->\n  typ e (TrI W) (Tr X).\nunfold typ.\nintros Xnk tyW; intros.\napply in_int_intro; try discriminate.\napply and_split; simpl; intros.\n red; auto.\n\n red in H0; rewrite El_def in H0.\n specialize tyW with (1:=H).\n apply in_int_not_kind in tyW; trivial.\n destruct tyW.\n rewrite Real_def; intros; auto.\n  apply interSAT_intro' with (F:=fun X=>X); intros.\n   apply sat_sn in H2; trivial.\n\n   apply (H3 (int W i)); trivial.\n\n  apply interSAT_morph_subset; simpl; auto with *.\nQed.\n\nDefinition TrE (X P F W:term) : term.\n(* begin show *)\n  left; exists (fun i => cond_set (int W i ∈ Elt (int (Tr X) i))\n                                  (trunc_descr (El(int P i))))\n               (fun j => Lambda.App (tm F j) (tm W j)).\n(* end show *)\ndo 2 red; intros; rewrite H; reflexivity.\n\ndo 2 red; intros; rewrite H; reflexivity.\n\nred; intros.\ndo 2 rewrite tm_liftable.\nreflexivity.\n\nred; intros.\ndo 2 rewrite tm_substitutive.\nreflexivity.\nDefined.\n\nDefinition EQ A t1 t2 :=\n  Prod (Prod A prop) (Prod (App (Ref 0) (lift 1 t1)) (App (Ref 1) (lift 2 t2))).\n\nDefinition IsProp X :=\n  Prod X (Prod (lift 1 X) (EQ (lift 2 X) (Ref 1) (Ref 0))).\n\nLemma TrE_typ e X P Pp F W :\n  P <> kind ->\n  typ e Pp (IsProp P) ->\n  typ e F (Prod X (lift 1 P)) ->\n  typ e W (Tr X) ->\n  typ e (TrE X P F W) P.\nunfold typ; intros Pnk tyPp tyF tyW i j valok.\nspecialize tyPp with (1:=valok); apply in_int_not_kind in tyPp;[|discriminate].\nspecialize tyF with (1:=valok); apply in_int_not_kind in tyF;[|discriminate].\nspecialize tyW with (1:=valok); apply in_int_not_kind in tyW;[|discriminate].\nclear valok.\ndestruct tyPp as (isPp,_).\ndestruct tyF as (tyF,satF).\ndestruct tyW as (tyW,satW).  \napply in_int_intro; trivial; try discriminate.\nsplit; simpl.\n red.\n rewrite Elt_def.\n red in tyW; simpl in tyW; rewrite El_def in tyW.\n apply cc_bot_ax in tyW; destruct tyW.\n  admit.\n rewrite cond_set_ok; trivial.\n apply trunc_ind with (El(int X i)) (fun x => cc_app (int F i) x) (int W i); trivial.\n  admit. (*!*)\n\n  red; intros.\n  admit.\n\n rewrite Elt_def.\n  red; intros.\n\n*)\n\n(***********************************************************************************************)\n\n(** * Consistency out of the strong normalization model *)\n\n(** Another consistency proof. *)\n\nTheorem consistency : forall M, ~ typ List.nil M (Prod prop (Ref 0)).\nred; intros.\napply model_consistency with (FF:=mkTY (singl prf_trm) (fun _ => neuSAT)) in H;\n  trivial.\n apply sn_sort_intro.\n  reflexivity.\n\n  apply one_in_props.\n\n intros.\n red in H0; rewrite El_def  in H0.\n rewrite Real_def; auto with *.\nQed.\n\nPrint Assumptions consistency.\n", "meta": {"author": "barras", "repo": "cic-model", "sha": "dcc38f3104048aa50d230f819085131b16702d3d", "save_path": "github-repos/coq/barras-cic-model", "path": "github-repos/coq/barras-cic-model/cic-model-dcc38f3104048aa50d230f819085131b16702d3d/SN_CC_Real.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2741318781540965}}
{"text": "Require Import Framework FSParameters.\nRequire Export LoggedDiskLayer ListLayer.\nImport ListNotations.\n\nSet Implicit Arguments.\n\nDefinition TransactionCacheOperation :=  HorizontalComposition (ListOperation (addr * value)) (LoggedDiskOperation log_length data_length).\nDefinition TransactionCacheLang := Build_Layer TransactionCacheOperation.\n\nNotation \"'|TCCP|' p\" := (@lift_L1 (ListOperation (addr * value)) (LoggedDiskOperation log_length data_length) (ListLang (addr * value)) _ p) (at level 59).\nNotation \"'|TCDP|' p\" := (@lift_L2 (ListOperation (addr * value)) (LoggedDiskOperation log_length data_length) (LoggedDiskLang log_length data_length) _ p) (at level 59).\nNotation \"'|TCCO|' p\" := (@lift_L1 (ListOperation (addr * value)) (LoggedDiskOperation log_length data_length) (ListLang (addr * value)) _ (Op (ListOperation (addr * value)) p)) (at level 59).\nNotation \"'|TCDO|' p\" := (@lift_L2 (ListOperation (addr * value)) (LoggedDiskOperation log_length data_length) (LoggedDiskLang log_length data_length) _ (Op (LoggedDiskOperation log_length data_length) p)) (at level 59).\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/ComposedLayers/TransactionCache/TransactionCacheLayer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878696277512, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.27403981256373333}}
{"text": "Require Import Poulet4.P4light.Syntax.P4defs.\nRequire Import Poulet4.P4light.Semantics.Semantics.\nRequire Import Coq.Program.Program.\nRequire Import ProD3.core.Core.\nRequire Import ProD3.core.Tofino.\nRequire Import ProD3.examples.count.p4ast.\n\nOpen Scope func_spec.\n\nNotation ident := string.\nNotation path := (list ident).\nNotation Val := (@ValueBase bool).\nNotation Sval := (@ValueBase (option bool)).\n\nDefinition am_ge := ltac:(get_am_ge prog).\nDefinition ge := ltac:(get_ge am_ge prog).\n\nDefinition NoAction_fundef : @fundef Info :=\n  ltac:(get_fd [\"NoAction\"] ge).\n\nDefinition NoAction_spec : func_spec :=\n  WITH,\n    PATH []\n    MOD None []\n    WITH,\n      PRE\n        (ARG []\n        (MEM []\n        (EXT [])))\n      POST\n        (ARG_RET [] ValBaseNull\n        (MEM []\n        (EXT []))).\n\nLemma NoAction_body :\n  func_sound ge NoAction_fundef nil NoAction_spec.\nProof.\n  start_function.\n  step.\n  entailer.\nQed.\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/count/common.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.274039806276561}}
{"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.machine2.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/machine2/cardinal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.274039806276561}}
{"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 {resMethodIndex : Type}.\n  (* The restricted set of method indices *)\n\n  Variable methodMap : resMethodIndex -> MethodIndex extSig.\n  (* Map from restricted to extended method indices *)\n\n  Definition resSig :=\n    {| MethodIndex := resMethodIndex;\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           Methods := extMethods\n        |} =>\n        Build_ADT resSig rep\n                  (fun idx => extMethods (methodMap idx))\n    end.\n\nEnd HideADT.\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/ADT/ADTHide.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160664, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.27403980627656094}}
{"text": "Require Import Definitions.\nRequire Import State.\nRequire Import Step.\nRequire Import BinNat.\nRequire Import BinInt.\nRequire Import String.\n\nDefinition initialState := MkState (const None) (const None).\n\nDefinition opened_fd (s : state) (fd : Z) : Prop :=\n\tfds s fd <> None.\nDefinition opened_file (s : state) (str : string) : Prop :=\n\texists (fd : Z), option_map file (fds s fd) = Some str.\nDefinition opened_file_with_fd (s : state) (f : string) (fd : Z)\n\t:= forall z, option_map file (fds s z) = Some f <-> fd = z.\n\nLemma non_opened_fd_1 (s : state) (fd : Z) (file : string)\n\t: ~ opened_fd s fd -> ~ opened_file_with_fd s file fd.\nProof.\nintros H.\nunfold opened_file_with_fd.\nintro Hf.\napply H.\nunfold opened_fd.\nintro Hf2.\ndestruct (fds s fd) eqn:Heq.\n+ discriminate Hf2.\n+ pose (T := Hf fd).\n\treplace (fds s fd) with (None (A:=fdState)) in T.\n\tunfold option_map in T.\n\tdestruct T.\n\tdiscriminate (H1 eq_refl).\nQed.\n\nLemma opened_file_1 (s : state) (fd : Z) (file : string)\n\t: opened_file_with_fd s file fd -> opened_file s file.\nProof.\nedestruct 1.\neexists.\nnow apply H1.\nQed.\n\nDefinition fileContentKnown (f : string) (s : state) : Prop\n\t:= match (files s f) with\n\t\t| Some fs => forall (n : N), content fs n <> Unknownc\n\t\t| None => False\n\t\tend.\n\nDefinition sameFileContent (f : string) (sStart sEnd : state) : Prop\n\t:= fileContentKnown f sStart\n\t\t/\\ forall (n : N), option_map (fun x => content x n) (files sStart f) = option_map (fun x => content x n) (files sEnd f).\n\nDefinition setFileContent (s : state) (str content : string) : state\n\t:= let (sfd, sfile) := s in\n\t\t let sfile := setFun sfile\n\t\t\t(Some\n\t\t\t\t(MkFileState\n\t\t\t\t\t(Some (N.of_nat (length content)))\n\t\t\t\t\t(addString content 0%N (const Nonec))\n\t\t\t\t)\n\t\t\t) str in\n\t\t\tMkState sfd sfile.\n\nLemma fileContentKnownSetFileContent (file content : string) (s : state)\n\t: fileContentKnown file (setFileContent s file content).\nProof.\nunfold fileContentKnown.\nunfold setFileContent.\ndestruct s.\ncbn.\nrewrite setFunOk.\nintros n.\ncbn.\nassert (forall m, addString content m (const Nonec) n <> Unknownc).\n+ induction content.\n\t- easy.\n\t- intros m.\n\t\tcbn.\n\t\tadmit.\nAdmitted.\n\nLemma setFileContent_fds (s : state) (str content : string) : fds s = fds (setFileContent s str content).\nProof.\nnow destruct s.\nQed.\n\nFixpoint setFileContents (s : state) (contents : list (string * string)) : state\n\t:= match contents with\n\t   | ((fn, fc)::contents)%list => setFileContents (setFileContent s fn fc) contents\n\t\t | _ => s\n\t\t end.\n\nLemma setFileContents_fds (s : state) (contents : list (string * string))\n\t: fds s = fds (setFileContents s contents).\nProof.\ngeneralize s.\ninduction contents; intros.\n+ easy.\n+ simpl.\n\tdestruct a.\n\trewrite <- IHcontents.\n\tapply setFileContent_fds.\nQed.\n\nTransparent abs_step.\n\nSection Abs_step_facts.\n\nVariable s : state.\n\nLemma open_opened_fd (str : string) (fd : Z) (m : FileSystem.mode) (o : FileSystem.options)\n\t: opened_fd (abs_step (FileSystem.Open m o str) fd s) fd.\nProof.\nunfold opened_fd.\ndestruct s.\ncbn.\nnow rewrite setFunOk.\nQed.\n\nLemma open_opened_file_with_fd (str : string) (fd : Z) (m : FileSystem.mode) (o : FileSystem.options)\n\t: ~ opened_file s str (* provable with the precondition *)\n\t\t-> opened_file_with_fd (abs_step (FileSystem.Open m o str) fd s) str fd.\nProof.\nunfold opened_file_with_fd.\ndestruct s eqn:Heq.\nintros.\nconstructor;\n\tintros.\n+ cbn in H0.\n\tcase_dec (fd = z).\n\t- apply H1.\n\t- rewrite setFunOk2 in H0.\n\t\t* absurd (opened_file s str).\n\t\t\t++ now subst.\n\t\t\t++ exists z.\n\t\t\t\tnow subst.\n\t\t* easy.\n+\tsubst.\n\tcbn.\n\tnow rewrite setFunOk.\nQed.\n\nLemma open_opened_file_with_fd2 (str f : string) (fd1 fd2 : Z) (m : FileSystem.mode) (o : FileSystem.options)\n\t: opened_file_with_fd s f fd1\n\t\t-> str <> f\n\t\t-> opened_file_with_fd (abs_step (FileSystem.Open m o str) fd2 s) f fd1.\nProof.\nunfold opened_file_with_fd.\nintros.\ndestruct s.\nconstructor;\n\tintros.\n+ apply H.\n\trewrite <- H1.\n\tcbn.\n\tcase_dec (fd2 = z).\n\t- subst.\n\t\trewrite setFunOk.\n\t\tcbn.\n\t\tdestruct (fds z);\n\t\t\tcbn.\n(*\ncase_dec (fd2 = fd1).\n+ subst.\n\tintros.\n\texfalso.\n\teapply non_opened_fd_1 in H0.\n\tapply H0.\n\tapply H.\n+ intros.\n\tunfold opened_file_with_fd.\n\tunfold opened_file_with_fd in H0.\n\tdestruct s eqn:Heq.\n\tintros.\n\tconstructor;\n\t\tintros.\n\t-\tcase_dec (fd2 = z).\n\t\t* subst.\n\t\t\tcbn in H2.\n\t\t\trewrite setFunOk in H2.\n\t\t\tcbn in H2.\n\t\t\tcbn in H0.\n\t\t\tinversion H2.\n\t\t\tadmit.\n\t\t* apply H0.\n\t\t\tcbn in H2.\n\t\t\tnow rewrite setFunOk2 in H2.\n\t- subst.\n\t\tcbn.\n\t\trewrite setFunOk2.\n\t\t* now apply <- H0.\n\t\t* apply H. *)\nAdmitted.\n\nLemma open_opened_fd2 (fd r : Z) (str : string) (m : FileSystem.mode) (o : FileSystem.options)\n\t: opened_fd s fd -> opened_fd (abs_step (FileSystem.Open m o str) r s) fd.\nProof.\nintros.\nunfold opened_fd.\ndestruct s.\ncbn.\ncase_dec (r = fd).\n+ subst.\n\trewrite setFunOk.\n\tunfold option_map.\n\tnow destruct (fds fd) eqn:Heq.\n+ now rewrite setFunOk2.\nQed.\n\nLemma open_not_opened_file (r : Z) (str file : string) (m : FileSystem.mode) (o : FileSystem.options)\n\t: ~ opened_file s file -> file <> str -> ~ opened_file (abs_step (FileSystem.Open m o str) r s) file.\nProof.\nintros.\ndestruct s.\nunfold opened_file.\ncbn.\nintro Hf.\ninversion Hf.\nclear Hf.\ncase_dec (r = x).\n+ subst.\n\trewrite setFunOk in H1.\n\tcbn in H1.\n\tinversion H1.\n\tnow subst.\n+ rewrite setFunOk2 in H1.\n\t- apply H.\n\t\tnow exists x.\n\t- easy.\nQed.\n\nLemma getSize_opened_fd (fd1 fd2 : Z) (r : N)\n\t: opened_fd s fd1 -> opened_fd (abs_step (FileSystem.GetSize fd2) r s) fd1.\nProof.\nintros.\nnow destruct s.\nQed.\n\nLemma getSize_not_opened_file (file : string) (fd : Z) (r : N)\n\t: ~ opened_file s file -> ~ opened_file (abs_step (FileSystem.GetSize fd) r s) file.\nProof.\nintros.\ndestruct s.\nunfold opened_file.\ncbn.\nintro Hf.\ninversion Hf.\napply H.\nunfold opened_file.\ncbn.\nnow exists x.\nQed.\n\nLemma getSize_opened_file_with_fd (file : string) (fd1 fd2 : Z) (r : N)\n : opened_file_with_fd s file fd1 -> opened_file_with_fd (abs_step (FileSystem.GetSize fd2) r s) file fd1.\nProof.\nintros.\nnow destruct s.\nQed.\n\nLemma read_opened_fd (n : N) (fd1 fd2 : Z) (r : string)\n\t: opened_fd s fd1 -> opened_fd (abs_step (FileSystem.Read n fd2) r s) fd1.\nProof.\nintros.\nunfold opened_fd.\ndestruct s.\ncbn.\ncase_dec (fd2 = fd1).\n+ subst.\n\trewrite changeFunOk.\n\tunfold option_map.\n\tnow destruct (fds fd1) eqn:Heq.\n+ now rewrite changeFunOk2.\nQed.\n\nLemma read_not_opened_file (r file : string) (fd : Z) (n : N)\n\t: ~ opened_file s file -> ~ opened_file (abs_step (FileSystem.Read n fd) r s) file.\nProof.\nintros.\ndestruct s.\nunfold opened_file.\ncbn.\nintro Hf.\ninversion Hf.\napply H.\nunfold opened_file.\ncbn.\nexists x.\nrewrite <- H0.\ncase_dec (fd = x).\n+ subst.\n\trewrite changeFunOk.\n\tunfold option_map.\n\tdestruct (fds x).\n\t- now destruct f.\n\t- reflexivity.\n+ now rewrite changeFunOk2.\nQed.\n\nLemma read_opened_file_with_fd (file : string) (fd1 fd2 : Z) (n : N) (r : string)\n : opened_file_with_fd s file fd1 -> opened_file_with_fd (abs_step (FileSystem.Read n fd2) r s) file fd1.\nProof.\nintros.\ndestruct s.\nunfold opened_file_with_fd.\ncbn.\nintros z.\ncase_dec (fd2 = z).\n+ subst.\n\tsplit; intros.\n\t- unfold opened_file_with_fd in H.\n\t\tapply H.\n\t\trewrite <- H0.\n\t\trewrite changeFunOk.\n\t\tcbn.\n\t\tdestruct (fds z).\n\t\t* now destruct f.\n\t\t* easy.\n\t- subst.\n\t\trewrite changeFunOk.\n\t\tunfold opened_file_with_fd in H.\n\t\tpose (Hr := H z).\n\t\tdestruct Hr.\n\t\trewrite <- H1; try reflexivity.\n\t\tcbn.\n\t\tdestruct (fds z).\n\t\t* now destruct f.\n\t\t* easy.\n+ split; intros.\n\t- unfold opened_file_with_fd in H.\n\t\tapply H.\n\t\tcbn.\n\t\trewrite <- H1.\n\t\tnow rewrite changeFunOk2.\n\t- subst.\n\t\tunfold opened_file_with_fd in H.\n\t\trewrite changeFunOk2.\n\t\t* now apply <- H.\n\t\t* assumption.\nQed.\n\nLemma write_opened_fd (str : string) (fd1 fd2 : Z) (r : unit)\n\t: opened_fd s fd1 -> opened_fd (abs_step (FileSystem.Write str fd2) r s) fd1.\nProof.\nintros.\nunfold opened_fd.\ndestruct s.\ncbn.\ncase_dec (fd2 = fd1).\n+ subst.\n\trewrite changeFunOk.\n\tunfold option_map.\n\tnow destruct (fds fd1) eqn:Heq.\n+ now rewrite changeFunOk2.\nQed.\n\nLemma write_opened_file (str file : string) (fd : Z) (r : unit)\n\t: opened_file s file -> opened_file (abs_step (FileSystem.Write str fd) r s) file.\nProof.\nintros.\ndestruct s.\nunfold opened_file.\ncbn.\ninversion H.\nexists x.\nrewrite <- H0.\ncase_dec (fd = x).\n+ subst.\n\trewrite changeFunOk.\n\tunfold option_map.\n\tcbn.\n\tdestruct (fds x).\n\t- now destruct f.\n\t- reflexivity.\n+ now rewrite changeFunOk2.\nQed.\n\nLemma write_not_opened_file (str file : string) (fd : Z) (r : unit)\n\t: ~ opened_file s file -> ~ opened_file (abs_step (FileSystem.Write str fd) r s) file.\nProof.\nintros.\ndestruct s.\nunfold opened_file.\ncbn.\nintro Hf.\ninversion Hf.\napply H.\nunfold opened_file.\ncbn.\nexists x.\nrewrite <- H0.\ncase_dec (fd = x).\n+ subst.\n\trewrite changeFunOk.\n\tunfold option_map.\n\tdestruct (fds x).\n\t- now destruct f.\n\t- reflexivity.\n+ now rewrite changeFunOk2.\nQed.\n\nLemma write_opened_file_with_fd (file : string) (fd1 fd2 : Z) (r : unit) (str : string)\n : opened_file_with_fd s file fd1 -> opened_file_with_fd (abs_step (FileSystem.Write str fd2) r s) file fd1.\nProof.\nintros.\ndestruct s.\nunfold opened_file_with_fd.\ncbn.\nintros z.\ncase_dec (fd2 = z).\n+ subst.\n\tsplit; intros.\n\t- unfold opened_file_with_fd in H.\n\t\tapply H.\n\t\trewrite <- H0.\n\t\trewrite changeFunOk.\n\t\tcbn.\n\t\tdestruct (fds z).\n\t\t* now destruct f.\n\t\t* easy.\n\t- subst.\n\t\trewrite changeFunOk.\n\t\tunfold opened_file_with_fd in H.\n\t\tpose (Hr := H z).\n\t\tdestruct Hr.\n\t\trewrite <- H1; try reflexivity.\n\t\tcbn.\n\t\tdestruct (fds z).\n\t\t* now destruct f.\n\t\t* easy.\n+ split; intros.\n\t- unfold opened_file_with_fd in H.\n\t\tapply H.\n\t\tcbn.\n\t\trewrite <- H1.\n\t\tnow rewrite changeFunOk2.\n\t- subst.\n\t\tunfold opened_file_with_fd in H.\n\t\trewrite changeFunOk2.\n\t\t* now apply <- H.\n\t\t* assumption.\nQed.\n\nLemma close_opened_fd (fd1 fd2 : Z) (r : unit)\n\t: opened_fd s fd1 -> fd2 <> fd1 -> opened_fd (abs_step (FileSystem.Close fd2) r s) fd1.\nProof.\nintros.\nunfold opened_fd.\ndestruct s.\ncbn.\nnow rewrite setFunOk2.\nQed.\n\nLemma close_not_opened_file (f : string) (fd : Z) (r : unit)\n\t: ~ opened_file s f -> ~ opened_file (abs_step (FileSystem.Close fd) r s) f.\nProof.\nintros.\ndestruct s.\nunfold opened_file.\ncbn.\nintro Hf.\ninversion Hf.\ncase_dec (fd = x).\n+ subst.\n\tnow rewrite setFunOk in H0.\n+ rewrite setFunOk2 in H0.\n\t- apply H.\n\t\tnow exists x.\n\t- easy.\nQed. \n\nLemma close_not_opened_file2 (f : string) (fd : Z) (r : unit)\n\t: opened_file_with_fd s f fd\n\t\t-> ~ opened_file (abs_step (FileSystem.Close fd) r s) f.\nProof.\nintros.\ndestruct s.\nunfold opened_file.\ncbn.\nunfold opened_file_with_fd in H.\nintro Hf.\ninversion Hf.\nclear Hf.\ncase_dec (fd = x).\n+ subst.\n\tnow rewrite setFunOk in H0.\n+ apply H1.\n\tapply (H x).\n\tnow rewrite setFunOk2 in H0.\nQed.\n\nLemma close_opened_file_with_fd (f : string) (fd1 fd2 : Z) (r : unit)\n\t: opened_file_with_fd s f fd1\n\t\t-> fd1 <> fd2 (* provable with the postcondition of the corresponding open *)\n\t\t-> opened_file_with_fd (abs_step (FileSystem.Close fd2) r s) f fd1.\nProof.\nintros.\ndestruct s.\nunfold opened_file_with_fd.\nAdmitted.\n\nLemma unlink_not_opened_file (file z : string) (r : unit)\n\t: ~ opened_file s file -> ~ opened_file (abs_step (FileSystem.Unlink z) r s) file.\nProof.\nintros.\ndestruct s.\nunfold opened_file.\ncbn.\nintro Hf.\ninversion Hf.\napply H.\nunfold opened_file.\ncbn.\nnow exists x.\nQed.\n\nEnd Abs_step_facts.\n", "meta": {"author": "vtourneur", "repo": "coqar", "sha": "b8894ef473c2e3d00ac736f8636460f1accf6de7", "save_path": "github-repos/coq/vtourneur-coqar", "path": "github-repos/coq/vtourneur-coqar/coqar-b8894ef473c2e3d00ac736f8636460f1accf6de7/fileSystem/theories/Spec/Props.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878414043814, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2740397999893885}}
{"text": "Require Import VST.msl.msl_direct.\nRequire Import RamifyCoq.msl_ext.abs_addr.\n\nInstance Join_discrete (A : Type): Join A := fun a1 a2 a3 : A => False.\n\nInstance Perm_discrete (A: Type)  : @Perm_alg A (Join_discrete A).\nProof. constructor; intros; inv H. Qed.\n\nInstance psa_discrete (A: Type) :  @Pos_alg A  (Join_discrete A).\nProof. repeat intro. inv H. Qed.\n\n(* Definition var := nat. *)\nDefinition adr := nat.\n\nDefinition world := (fpm adr adr).\n\nInstance Join_world: Join world := Join_fpm (Join_discrete adr).\n\nInstance Perm_world : Perm_alg world. apply Perm_fpm; apply Perm_discrete. Qed.\n\nInstance Sep_world : Sep_alg world. apply Sep_fpm. Qed.\n\nInstance Canc_world : Canc_alg world. apply Canc_fpm; [intuition | repeat intro; inversion H]. Qed.\n\nInstance Disj_world : Disj_alg world. apply Disj_fpm; repeat intro; [apply Perm_discrete | |]; inversion H. Qed.\n\nInstance Cross_world : Cross_alg world. apply Cross_fpm; [apply Perm_discrete | apply psa_discrete | repeat intro; inv H]. Qed.\n\nInstance Trip_world : @Trip_alg world Join_world.\nProof.\n  repeat intro.\n  destruct ab as [fab Hab]. destruct c as [fc Hc].\n  remember (fun x => match (fab x) with\n                       | Some v => Some v\n                       | None => match (fc x) with\n                                   | Some v' => Some v'\n                                   | None => None\n                                 end\n                     end) as fabc.\n  assert (finMap fabc). {\n    hnf in Hab, Hc. destruct Hab as [lab ?]. destruct Hc as [lc ?].\n    exists (lab ++ lc). intro z; intros.\n    assert (~ In z lab). intro. apply H2. apply in_or_app. left; auto.\n    assert (~ In z lc). intro. apply H2. apply in_or_app. right; auto.\n    hnf in *. simpl in *. specialize (e0 z H4). specialize (e z H3).\n    rewrite Heqfabc. destruct (fab z) eqn:? . inv e. destruct (fc z) eqn:? . inv e0. auto.\n  } exists (exist (finMap (B:=adr)) fabc H2).\n  hnf. simpl. intros. rewrite Heqfabc. destruct (fab x) eqn:? .\n  + destruct (fc x) eqn:? .\n    - destruct a as [fa ?]. destruct b as [fb ?]. hnf in *. simpl in *.\n      specialize (H x). rewrite Heqo in *. inversion H.\n      * specialize (H0 x). rewrite H6, Heqo0 in *. inversion H0. inversion H9.\n      * specialize (H1 x). rewrite H6, Heqo0 in *. inversion H1. inversion H9.\n      * inversion H6.\n    - constructor.\n  + destruct (fc x) eqn:? .\n    - constructor.\n    - constructor.\nDefined.\n\nDefinition adr_conflict (a1 a2 : adr) : bool := if (eq_nat_dec a1 a2) then true else false.\n\nInstance AbsAddr_world : AbsAddr adr adr.\n  apply (mkAbsAddr adr adr adr_conflict); intros; unfold adr_conflict in *.\n  + destruct (eq_nat_dec p1 p2). subst. destruct (eq_nat_dec p2 p2); auto. exfalso; tauto.\n    destruct (eq_nat_dec p2 p1). subst. exfalso; tauto. trivial.\n  + destruct (eq_nat_dec p1 p1). inversion H. exfalso; tauto.\nDefined.\n\nFixpoint extractSome (f : adr -> option adr) (li : list adr) : list adr :=\n  match li with\n    | nil => nil\n    | x :: lx => match f x with\n                   | Some _ => x :: extractSome f lx\n                   | None => extractSome f lx\n                 end\n  end.\n\nLemma world_finite: forall w: world, exists l: list adr, forall a:adr, In a l <-> lookup_fpm w a <> None.\nProof.\n  intro; destruct w as [f [li ?]]; simpl; exists (extractSome f li); split; intros.\n  clear e; induction li; simpl in H; auto.\n  destruct (f a0) eqn: ?. destruct (in_inv H). subst. rewrite Heqo. intro. inversion H0.\n  apply IHli; auto. apply IHli; auto. destruct (in_dec nat_eq_dec a li). clear e.\n  induction li; simpl in *; auto. destruct (f a0) eqn : ?. destruct i. subst. apply in_eq.\n  apply in_cons. apply IHli; auto. destruct i. subst. exfalso; auto. apply IHli; auto.\n  specialize (e a n). exfalso; auto.\nQed.\n\nLemma lookup_fpm_join_sub: forall (w1 w2 : world) x, join_sub w1 w2 -> lookup_fpm w1 x <> None -> lookup_fpm w2 x <> None.\nProof.\n  intros. destruct H as [w3 ?].\n  destruct w1 as [f1 [l1 ?]]. destruct w2 as [f2 [l2 ?]]. destruct w3 as [f3 [l3 ?]]. hnf in H; simpl in *.\n  specialize (H x). inversion H. exfalso; auto. auto. 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/heap_model_direct/SeparationAlgebra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.27401710721326983}}
{"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 invalidate_page_spec0 (addr: Z64) (adt: RData) : option RData :=\n    match addr with\n    | VZ64 _addr =>\n      when adt == barrier_spec  adt;\n      rely is_int64 _addr;\n      when adt == stage2_tlbi_ipa_spec (VZ64 _addr) (VZ64 4096) 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/TableAux/LowSpecs/invalidate_page.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2740171072132698}}
{"text": "Set Implicit Arguments.\n\nSection ADTValue.\n\n  Variable ADTValue : Type.\n\n  Require Import Platform.Cito.SemanticsFacts4.\n  Require Import Platform.Cito.ProgramLogic2.\n  Require Import Platform.Cito.Transit.\n  Require Import Platform.Cito.Semantics.\n\n  Require Import Platform.Cito.GLabel.\n  Require Import Platform.Cito.GLabelMap.\n  Import GLabelMap.\n  Require Import 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 Platform.Cito.GeneralTactics Platform.Cito.GeneralTactics2.\n  Require Import 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_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.", "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/ChangeSpec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.27401710128500545}}
{"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\nContext `{Hcc: CompilerConfiguration}.\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  | G symb ofs => v = symbol_address ge symb ofs\n  | S ofs => v = Val.add sp (Vint ofs)\n  | _ => 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 (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  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 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 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 H. apply make_andimm_correct; auto.\n(* or *)\n  InvApproxRegs. SimplVMA. inv H0; rewrite H. apply make_orimm_correct; auto.\n(* xor *)\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(* default *)\n  exists v; auto.\nQed.\n\nEnd STRENGTH_REDUCTION.\n\nEnd ANALYSIS.\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/ia32/ConstpropOpproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.27396886168062323}}
{"text": "(** * 머리말 *)\n\n(* ################################################################# *)\n(** * 환영합니다 *)\n\n(** _소프트웨어 기초_(신뢰성 있는 소프트웨어의 수학적 기초)의 다양한\n    면들에 대한 전자책 시리즈의 시작점입니다. 강의 주제로 논리의 기본\n    개념, 컴퓨터를 활용한 명제 증명(Computer-assisted theorem\n    proving), 콕 증명 보조기 (Coq proof assistant), 함수형 언어\n    (functional programming), 실행 과정 기반 의미 구조(operational\n    semantics), 호어 논리(Hoare logic), 타입 시스템(static type\n    system)을 다룬다. 고학년 학부생부터 박사과정 학생과 연구자들까지\n    다양한 독자들을 대상으로 한다. 논리나 프로그래밍 언어에 대한 사전\n    지식이 필요하지 않지만 수학을 많이 접했다면 도움이 될 것이다.\n\n    이 강의의 특징은 백 퍼센트 형식화해서 컴퓨터로 검사하도록 구성된\n    것이다. 즉, 전체 텍스트가 콕 스크립트다. 콕의 대화식 세션을 따라\n    텍스트 내용을 읽도록 구성되어 있다. 텍스트의 모든 상세 내용은\n    콕으로 완벽하게 형식화되어 있고, 대부분의 연습문제들을 콕을\n    사용하여 풀어보도록 설계되었다.\n\n    강의 파일들은 대략 한 학기 분량의 핵심적인 장들을 나열하도록\n    구성되어 있고, 일관성 있고 단일 방향성의 이야기로 구성되어 있다.\n    더불어 추가적인 주제들을 다루는 많은 파생된 장들도 있다.  모든\n    핵심적인 장들은 고학년 학부생과 대학원생들에게 적합하다.\n\n    이 책, _논리적 기초_,는 다른 책들을 위한 토대이고, 독자들에게\n    함수형 프로그래밍, 건설적 논리(constructive logic), 콕 증명\n    보조기를 소개한다. *)\n\n\n(* ################################################################# *)\n(** * 개요 *)\n\n(** 신뢰성 있는 소프트웨어를 만드는 것은 어렵다. 현대 시스템들의 크기와\n    복잡도, 개발에 참여하는 많은 개발자들, 다양한 시스템 요구사항들로\n    인해 100%% 보다 훨씬 낮은 정확성이라도 대략 정확하게 소프트웨어를\n    만드는 것조차도 매우 어렵다. 그리고 사회의 다양한 국면과 엮여 \n    정보를 처리함에 따라 버그와 위험으로 인한 비용이 확대된다.\n \n    컴퓨터과학자들과 소프트웨어 공학자들은 이러한 문제들에 대응하기 위해\n    소프트웨어 신뢰성을 높이기 위한 다양한 기법들을\n    개발했다. 소프트웨어 프로젝트 팀들을 관리하는 방법(예를 들어\n    익스트림 프로그래밍)에서부터 라이브러리(예를 들어 모델 뷰\n    컨트롤러, 발행-가입, 등)와 프로그래밍 언어(예를 들어 객체지향\n    프로그래밍, 관점 지향 프로그래밍,...) 설계 철학들, 소프트웨어의\n    성질들을 기술하고 추론하는 수학적 기법과 이 성질들을 검증하기 위한\n    도구들까지 다양하다. 이 강의는 마지막에 언급한 기법들에 초점을\n    맞춘다.\n\n    이 책은 세 가지 개념들을 엮어놓았다.\n\n    (1) 프로그램에 대한 명제를 정밀하게 만들고 정당화하는 _논리_의\n        기본 도구들\n\n    (2) 논리적 주장을 엄밀하게 만들기 위하여 _증명 보조기_를 사용\n\n    (3) 프로그램들에 대한 추론을 단순화하는 프로그래밍 방법으로\n        그리고 프로그래밍과 논리를 연결하는 역할로써 _함수형 프로그래밍_\n\n    [후기] 장에서 추가적으로 읽을만한 문헌을 소개한다.  모든\n    참고문헌들에 대한 서지 정보는 [Bib] 파일에 있다.  *)\n\t  \n(* ================================================================= *)\n(** ** 논리 *)\n\n(** 논리는 _증명_을 주제로 하는 학문 분야다. 증명이란 특정 명제들이\n    참인지 거짓인지에 대한 부정할 수 없는 주장이다. 컴퓨터과학에서\n    논리의 중요한 역할에 대해 설명하는 많은 책들이 있다. 마나(Manna)와\n    월딩거(Waldinger)는 논리를 \"컴퓨터과학의 계산법\"이라 불렀고,\n    할러펜(Halpern)과 그 동료들의 논문 _컴퓨터과학에서 논리의 유별난\n    효과_에서 논리가 어떻게 중요한 도구들과 통찰력들을 제공하는지\n    수십 가지 사례들을 나열하였다. 정말로 \"사실 논리는 수학에서 보다\n    컴퓨터과학에서 훨씬 더 효과적임이 밝혀졌다. 특히 지난 백 년간 논리\n    발전의 많은 자극이 수학으로부터 왔기 때문에 이 사실은 상당히\n    주목할만하다.\"라고 보았다.\n\n    특히 _귀납적 증명_이라는 기초적인 도구들은 컴퓨터과학의 모든 영역에\n    사용된다. 독자 여러분은 분명히 이전에, 아마도 이산수학이나 알고리즘\n    분석에 관한 강의에서 이것들을 보았을 것이다. 하지만 이 강의에서 \n    훨씬 더 깊이 이것들을 살펴볼 것이다. *)\n\n(* ================================================================= *)\n(** ** 증명 보조기 *)\n\n(** 논리와 컴퓨터과학의 아이디어들은 서로 양쪽으로 주고받아왔다. 컴퓨터과학 또한\n    논리에 중요한 기여들을 해왔다. 그중 하나는 논리 명제들을 증명하는 것을 도와주는\n    소프트웨어 도구들을 개발해온 것이다. 이 도구들은 크게 두 가지로 분류할 수 있다.\n\n       - _자동 정리 증명기_는 버튼만 누르면 제시한 명제가 _참_인지\n         _거짓_인지 (또는 _시간이 너무 오래 걸려 모른다_)를\n         리턴한다. 비록 특정 영역들에 국한되어 있지만 근래에 이 기술이\n         크게 발전해왔고 이제 다양한 상황들에서 사용되고 있다. 이\n         도구들의 예를 들면 에스에이티(SAT, boolean SATisfiability)\n         도구들, 에스엠티(SMT, satisfiability modulo theores) 도구들,\n         모델 검사기들이 있다.\n\n       - _증명 보조기_는 어려운 부분들은 사람의 가이드에 의존하되 다소\n         반복적인 부분들을 자동화하여 증명하는 혼합형 도구이다. 널리\n         사용 중인 증명 보조기들로 이사벨(Isabelle), 아그다(Agda),\n         트웰프(Twelf), 에이씨넬투(ACL2), 피브이에스(PVS), 콕(Coq) 등이\n         있다.\n\n    이 강의에서는 콕을 사용한다. 증명 보조기 콕은 1983년에 개발을\n    시작했고 최근에 연구와 산업에 종사하는 다양한 커뮤니티에서 사용하고\n    있다. 콕은 대화식으로 형식적 추론을 만들고 컴퓨터가 확인하는 방식을\n    위한 다양한 기능을 제공하는 환경이다. 콕 시스템의 핵심부는 간단한\n    증명 검사기로 구성되어 있는데, 이 검사기를 통해 오직 정확한 추론\n    단계들만 수행하도록 보장한다. 콕 환경은 이 핵심부에 증명 개발을\n    도와주는 고급 기능들을 제공한다. 방대한 공용 정의들과 보조 정리들\n    라이브러리, 복잡한 증명들을 반자동으로 만들 수 있는 강력한\n    전술(함수), 특정 상황에 맞추어 증명 자동화 전술을 새롭게 정의할 수\n    있는 특별한 목적의 프로그래밍 언어 등이 포함되어 있다.\n\n    콕은 컴퓨터과학과 수학을 넘나드는 거대하고 다양한 분야의 중요한\n    성공 요소가 되고 있다.\n\n    - _프로그래밍 언어를 모델링하는 플랫폼_으로써 복잡한 언어 정의들을\n      기술하고 추론하는 표준 도구가 되었다. 자바카드(JavaCard) 플랫폼의\n      보안성을 검사하는 데 사용되어 보안 분야 인증 표준 CC(Common\n      Criteria)의 최고 등급을 받았다.  x86과 LLVM 어셈블리 언어와 C와\n      같은 프로그래밍 언어의 형식 명세를 기술하는 데 사용되었다.\n\n    - _형식적으로 검증된 소프트웨어와 하드웨어를 개발하기 위한\n      환경_으로써 사용되고 있다. 콤써트(CompCert) 프로젝트에서 C언어\n      최적화 컴파일러를 완벽하게 검증하였고, 써티코스(CertiKos)\n      프로젝트에서 하이퍼바이저를 완전히 검증하였으며, 부동소수점\n      숫자에 관한 알고리즘들의 정확성을 증명했고,\n      써티크립트(CertiCrypt) 프로젝트에서 암호 알고리즘들의 보안성을\n      추론하는 환경의 기초로 이용하고 있다. 오픈소스 리스크\n      파이브(RISC-V) 프로세서의 구현을 검증하는 데에도 사용 중이다.\n\n    - _종속 타입(dependent types)을 제공하는 함수형 프로그래밍을 위한\n      제대로 된 환경_으로써 수많은 혁신들에 영향을 끼쳤다. 예를 들어\n      와이놋(Ynot) 시스템은 \"관계형 호어 추론\" (_호어 논리_의 확장으로\n      이 강의에서 다룰 것이다) 방법을 콕에 녹여냈다.\n\n    - _고차원 논리(higher-order logic)를 위한 증명 보조기_로써 수학\n      분야에서 많은 중요한 결과를 검증하는 데 사용되어 왔다. 증명 안에\n      복잡한 계산을 포함하는 기능을 제공함으로써 네 가지 색\n      정리(4-color theorem)의 증명을 처음으로 형식적으로\n      검증해냈다. 이렇게 검증하기 전에 이 증명은 프로그램을 사용하여\n      많은 상황들을 검사하는 부분이 포함되어 있기 때문에 수학자들\n      사이에서 증명으로 인정할 지에 관하여 논쟁이 있었다. 콕으로\n      형식화하여 프로그램을 실행하여 확인했던 부분의 정확성까지\n      포함해서 모든 부분을 검사하였다. 더 최근에는 페이트 톰슨\n      정리(Feit-Thompson theorem, 유한단순군의 분류에 관한 주요한\n      첫번째 단계)을 콕으로 형식화하는데 더욱 방대한 양의 노력을\n      기울이고 있다.\n\n   만일 콕이라는 이름에 대해 궁금하다면 인리아(INRIA, 콕을 개발한\n   프랑스 국립 연구소)에 있는 공식 웹 사이트에 언급된 설명을\n   보자. \"일부 프랑스 컴퓨터과학자들은 그들이 만든 소프트웨어에 동물\n   종의 이름을 붙이는 전통을 가지고 있다. 카멜(Caml), 엘란(Elan),\n   폭(Foc), 폭스(Phox)는 이런 암묵적인 전통의 예들이다. 프랑스어로\n   '콕'은 수탉을 뜻하기도 하고, 콕이 기초로 하는 이론, 구성\n   계산법(Calculus of Constructions, CoC)의 머리글자들처럼 발음한다.\"\n   수탉은 프랑스의 국가 상징이기도 하며, 씨-오-큐(C-o-q)는 초기에 콕을\n   개발한 사람들 중 티에리 코쿠아(Thierry Coquand)      이름에 포함된 첫\n   번째 세 문자들이기도 하다. *)\n\n(* ================================================================= *)\n(** ** 함수형 프로그래밍 *)\n\n(** _함수형 프로그래밍_이라는 용어는 거의 모든 프로그래밍 언어에서\n    사용할 수 있는 프로그래밍 스타일들을 가리키기도 하고 이 스타일들을\n    강조하여 설계된 프로그래밍 언어들을 말하기도\n    한다. 하스켈(Haskell), 오캐멀(OCaml), 에스엠엘(Standrad ML),\n    에프샵(F##), 스칼라(Scala), 스킴(Scheme), 라킷(Racket),\n    리스프(Common Lisp), 클로져(Clojure), 얼랑(Erlang), 콕 등이 함수형\n    프로그래밍 언어이다.\n\n    함수형 프로그래밍은 수 십 년간 발전되어 왔다. 그 기원은\n    처치(Church)가 1930년대에 발명한 람다 계산법(lambda\n    calculus)이다. 이 시기는 초기 컴퓨터들(적어도 초기 전자 컴퓨터들)\n    보다 앞선다! 하지만 90년대 초에 이르러서야 비로소 산업계\n    엔지니어들과 언어 설계자들이 많은 관심을 보이기 시작했고 제인\n    스트리트 캐피털(Jane St. Capital), 마이크로소프트(Microsoft),\n    페이스북(Facebook), 에릭슨(Ericsson)과 같은 회사들의 고부가가치\n    시스템들에서 중요한 역할을 담당하고 있다.\n\n    함수형 프로그래밍의 가장 기본적인 생각은 가능한 계산은\n    _순수(pure)_해야 한다는 것이다.  즉, 실행 결과는 오로지 결과를\n    내는 것이라는 것이다. 입출력(I/O), 변수의 값을 할당, 포인터를\n    변경하는 것과 같은 _부작용(side effects)_은 없어야 한다는\n    생각이다. 예를 들어, _명령 기반(imperative)_ 정렬 함수는 숫자들\n    리스트를 받아서 숫자들을 가리키는 포인터들을 배열해서 그 리스트\n    안에 순서대로 놓도록 작성한다면, 순수한 정렬 함수는 원래 리스트를\n    받아서 그 리스트의 숫자들을 정렬된 순서로 담고 있는 _새로운_\n    리스트를 리턴한다.\n\n    이런 스타일로 프로그래밍하면 프로그램을 이해하기 쉽고 추론하기\n    쉬운 형태로 작성할 수 있는 혜택이 있다. 자료구조에 대해 연산할 때\n    마다 항상 원래 자료구조는 변경하지 않은 채 두고 모두 새로운 자료\n    구조를 결과로 낸다면 이 자료구조를 공유하는 방식을 고민할 필요가\n    없고, 프로그램의 한 부분을 실행해서 변경이 발생함으로 인해\n    프로그램의 다른 부분이 의존하는 불변 성질을 깨뜨리지 않을까 걱정할\n    필요도 없다. 이러한 사항들은 동시성을 사용하는 시스템들에서 특히\n    중요하다.  동시성 시스템(concurrent systems)에서 변경 가능한\n    상태를 여러 스레드들이 공유하는 것은 치명적인 버그들의 잠재적\n    원인이다. 산업계에서 최근에 함수형 프로그래밍에 관심을 보인 많은\n    부분들이 동시성이 존재하는 상황에서 더 간단하게 동작하도록\n    프로그래밍할 수 있기 때문이다.\n\n\n    최근에 함수형 프로그래밍에 환호하는 또 다른 이유는 첫 번째 이유와\n    연관되어 있는데, 보통 함수형 프로그램들은 명령 기반 프로그램들\n    보다 병렬화가 훨씬 더 쉽기 때문이다.  만일 프로그램을 실행했을 때\n    결과를 내는 것 말고 특별히 다른 효과가 없다면 이 프로그램을\n    어디에서 실행하든 상관없다. 비슷한 얘기로, 프로그램을 실행하면서\n    자료구조가 내부적으로 결코 변경되지 않는다면 프로세서 코어들 또는\n    네트워크를 넘어서 이 자료구조를 자유롭게 복사할 수\n    있다. 하둡(Hadoop)과 같은 대용량 분산 질의 처리기들의 핵심이고\n    구글(Google)에서 전체 웹을 색인하는 데 사용하는\n    \"맵-리듀스(Map-Reduce)\" 프로그래밍 스타일은 함수형 프로그래밍의\n    고전적인 예이다.\n\n    이 강의의 목적을 위하여 함수형 프로그래밍은 앞서 언급한 장점과\n    더불어 또 다른 중요한 매력이 있다. 논리와 컴퓨터과학을 연결하는\n    다리 역할을 하는 것이다.  정말로 콕은 그 자체로 작지만 매우\n    표현력이 높은 함수형 프로그래밍 언어와 논리적 주장들을 서술하고\n    증명하는 데 사용할 도구들의 집합을 조합해놓은 것이다.  더욱이 더\n    자세히 들여다보면 콕의 논리에 관한 것과 프로그래밍에 관한 것은 콕\n    시스템의 동일한 기초 원리(underlying machinery)를 보는 다른\n    관점 들일뿐이라는 것을 발견한다. 즉, _증명과 프로그램_. *)\n\n(* ================================================================= *)\n(** ** 더 자세한 내용 *)\n\n(** 이 책은 자체로 모든 내용을 담으려 했지만 특정 주제들을 더 깊이 탐구하고자 하는\n    독자들은 [후기] 장에서 더 자세한 내용에 대한 제안을 참고할 수 있다.   *)\n\n(* ################################################################# *)\n(** * 강의 진행을 위한 참고 *)\n\n(* ================================================================= *)\n(** ** 책의 장들 간 의존성 *)\n\n(** 이 책의 모든 장들 간의 의존성을 보여주는 다이어그램과 내용들을 연결하는 경로들을\n    [deps.html] 파일에서 확인할 수 있다. *)\n\n(* ================================================================= *)\n(** ** 시스템 요구사항 *)\n\n(** 윈도우, 리눅스, 맥 운영체제에서 콕을 실행할 수 있다. 필요한 사항은:\n\n       - 콕 웹 사이트에서 제공하는 콕을 설치. 8.6 버전을 사용하면 된다.\n\n       - 콕을 대화식으로 사용하기 위해 필요한 통합개발환경(IDE). 현재 두 가지 선택이 가능하다.\n\n           - 프룹 제너럴(Proof General)은 이맥스 기반 통합개발환경이다. 이맥스에 익숙한\n             사용자가 선호하는 선택이다. 콕과 별도의 설치가 필요하다 (구글링 \"Proof General\").\n\n             이맥스를 사용하는 콕 사용자들 중 대범한 사용자라면 확장\n             기능들 [company-coq]과 [control-lock]을 내려받아 사용할\n             수도 있다.\n\n           - CoqIDE는 간단한 독립적인 통합개발환경이다. 콕과 함께 배포되기 때문에 콕을 설치하면\n             바로 사용 가능하다. 처음부터 컴파일해서 사용할 수도 있는데 어떤 환경에서는\n             그래픽 사용자 인터페이스 라이브러리 등 추가 패키지들을 설치해야 컴파일 가능하다. *)\n\n(* ================================================================= *)\n(** ** 연습문제 *)\n\n(** 각 장은 많은 연습문제들을 포함하고 있다. 각 연습문제에 별 등급을 매겨 놓았다.\n\n       - 별 하나: 쉬운 연습문제로 등급을 표시해두었다. 대부분의 독자들은 1,2분 내에\n         풀 수 있을 것이다. 이 별 등급의 연습문제들을 만날 때마다 풀어보는 습관을 갖기 바란다.\n\n       - 별 두 개: 간단한 연습문제들 (5~10분).\n\n       - 별 세 개: 다소 생각을 요구하는 연습문제들 (10분에서 30분).\n\n       - 별 네 개와 다섯 개: 더 어려운 연습문제들 (30분 이상).\n\n    어떤 연습문제들에는 \"고급(Advanced)\"을 붙여 놓았고 다른\n    연습문제들은 \"선택(optional)\"을 붙여 놓았다. 선택 사항이 아니고\n    고급 연습문제들이 아닌 연습문제들만 푸는 것만으로도 핵심적인\n    내용을 잘 커버할 것이다. 선택적 연습문제들은 핵심 개념들과 함께\n    다소 추가적인 연습을 제공하고 일부 독자들에게 흥미를 줄 수 있은\n    부차적인 주제들을 소개한다. 고급 연습문제들은 도전적이고 깊은\n    내용을 원하는 독자들을 위한 것이다.\n\n    _이 연습문제들에 대한 풀이들을 공공장소에 공개하지 않을 것을\n    부탁한다._ 소프트웨어 기초는 스스로 학습과 대학 강의에 널리\n    사용되고 있다. 해답이 쉽게 노출된다면 과제물을 가지고 성적을 주는\n    일반 강의에 훨씬 덜 도움이 될 것이다. 특히 독자들에게 검색\n    엔진으로 찾을 수 있는 어떠한 장소에도 연습문제들의 해답을 올리지\n    않도록 요청한다.   *)\n\n(* ================================================================= *)\n(** ** 콕 파일들을 내려받기 *)\n\n(** 이 책의 배포판에 대한 전체 소스를 포함하는 묶음(tar) 파일에 콕\n    스크립트와 에이치티엠엘(HTML) 파일들이 있는데 아래 주소에서\n    제공한다.\n  \n        http://www.cis.upenn.edu/~bcpierce/sf\n\n    (만일 이 책을 강의의 일부로 사용한다면 그 강의를 담당하는 교수가\n     이 파일들을 직접 수정한 버전을 제공할 수도 있다. 배포판 대신\n     수정판을 사용하세요) *)\n\n(* ================================================================= *)\n(** ** 강의 비디오 *)\n\n(** _논리적 기초_에 관한 집중 여름 강좌들_(2017년 딥스펙 여름 학교의 일부)을\n    아래 주소에서 볼 수 있다. 처음 강의 동영상의 화질이 좋지 않지만 나중에는\n    점점 나아질 것이다. *)\n\n    - https://deepspec.org/event/dsss17/coq_intensive.html\n\n(* ################################################################# *)\n(** * 강사를 위한 메모  *)\n\n(** 강사 본인의 강의에 이 책을 사용한다면, 내용 중에 변경하고,\n    개선하고, 추가하고 싶은 것이 반드시 있을 것이다. 당신이 기여하는 것을 환영합니다!\n\n    만일 라이센스 문구, 서브라이센스 등을 조정해야하는 상황이 발생하는\n    경우 합법성 문제를 단순하게 유지하고 책임을 단일화하기 위해서 이\n    책에 기여하는 모든 사람들(개발자 저장소를 접근하는 모든\n    사람들)에게 각자의 기여한 바에 대한 저작권을 다음과 같이 적절한\n    \"기록의 저자(Author of Record)\"에 부여할 것을 요청한다.\n\n      - 나는 나의 과거와 미래에 기여했던 바에 대한 저작권을 소프트웨어\n        기초 프로젝트에 각 권 또는 요소의 \"기록의 저자\"에 부여하고,\n        소프트웨어 기초의 나머지와 동일한 조항하에 라이센스를\n        부여한다. 현재 시점에 \"기록의 저자\"는 다음과 같음을 이해하고\n        있다. 2016년까지 \"소프트웨어 기초\"로, 2016년부터 각각 \"논리적\n        기초\"와 \"프로그래밍 기초\"로 알려진 1권과 2권에 대해 \"기록의\n        저자\"는 벤자민 피어스이다. 3권 \"함수형 알고리즘 검증\"에 대해\n        \"기록의 저자\"는 안드류 더블류 아펠이다. 이 범위 밖에 있는\n        요소(예를 들어 타입 세팅, 채점 도구, 다른 기반 소프트웨어)들에\n        대해 \"Author of Record\"는 벤자민 피어스이다.\n\n    시작하려면 벤자민 피어스에게 본인 소개와 이 책을 사용할 계획을 서술한 이메일을 보내주세요. 그리고\n    아래 내용도 함께 보내주세요.\n       (1) 위의 저작권 위임 텍스트와\n       (2) 명령어 \"htpasswd -s -n NAME\"를 실행한 결과\n    원하는 사용자 이름을 정해서 NAME을 바꾸면 됩니다.\n\n    서브버전 저장소와 개발자 메일 리스트에 접근할 수 있도록 설정할 것입니다. 이 저장소의\n    [INSTRUCTORS] 파일에서 추가 지시 사항들을 확인할 수 있습니다. *)\n\n(* ################################################################# *)\n(** * 번역 *)\n\n(** 번역을 자원해서 진행하는 팀의 노력 덕분에 \n    [http://proofcafe.org/sf]에서 일본어로 _소프트웨어 기초_를 읽을 수 있습니다.\n    중국어 번역은 진행 중입니다. *)\n\n(* ################################################################# *)\n(** * 감사 *)\n\n(** _소프트웨어 기초_ 시리즈를 개발하는 것을 국립과학재단 엔에스에프\n    익스페디션 그란트 1521523, _딥 스펙에 관한 과학_으로부터 일부\n    지원을 받았습니다.\n\n(** $Date: 2017-08-24 17:13:02 -0400 (Thu, 24 Aug 2017) $ *)\n", "meta": {"author": "kwanghoon", "repo": "sf", "sha": "6937265f0ba88524af8a5e0da1cb19d49c079875", "save_path": "github-repos/coq/kwanghoon-sf", "path": "github-repos/coq/kwanghoon-sf/sf-6937265f0ba88524af8a5e0da1cb19d49c079875/lf/Preface_ko_utf8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.2739521773133345}}
{"text": "(*! Language | Combinational primitives available in all Kôika programs !*)\nRequire Export Koika.Common Koika.Environments Koika.IndexUtils Koika.Types Koika.ErrorReporting.\n\nInductive bits_comparison :=\n  cLt | cGt | cLe | cGe.\n\nInductive bits_display_style :=\n  dBin | dDec | dHex | dFull.\n\nRecord display_options :=\n  { display_strings : bool;\n    display_newline : bool;\n    display_style : bits_display_style }.\n\nModule PrimUntyped.\n  Inductive udisplay :=\n  | UDisplayUtf8\n  | UDisplayValue (opts: display_options).\n\n  Inductive uconv :=\n  | UPack\n  | UUnpack (tau: type)\n  | UIgnore.\n\n  Inductive ubits1 :=\n  | UNot\n  | USExt (width: nat)\n  | UZExtL (width: nat)\n  | UZExtR (width: nat)\n  | URepeat (times: nat)\n  | USlice (offset: nat) (width: nat).\n\n  Inductive ubits2 :=\n  | UAnd\n  | UOr\n  | UXor\n  | ULsl\n  | ULsr\n  | UAsr\n  | UConcat\n  | USel\n  | USliceSubst (offset: nat) (width: nat)\n  | UIndexedSlice (width: nat)\n  | UPlus\n  | UMinus\n  | UMul\n  | UCompare (signed: bool) (c: bits_comparison).\n\n  Inductive ustruct1 :=\n  | UGetField (f: string)\n  | UGetFieldBits (sig: struct_sig) (f: string).\n\n  Inductive ustruct2 :=\n  | USubstField (f: string)\n  | USubstFieldBits (sig: struct_sig) (f: string).\n\n  Inductive uarray1 :=\n  | UGetElement (pos: nat)\n  | UGetElementBits (sig: array_sig) (pos: nat).\n\n  Inductive uarray2 :=\n  | USubstElement (pos: nat)\n  | USubstElementBits (sig: array_sig) (pos: nat).\n\n  Inductive ufn1 :=\n  | UDisplay (fn: udisplay)\n  | UConv (fn: uconv)\n  | UBits1 (fn: ubits1)\n  | UStruct1 (fn: ustruct1)\n  | UArray1 (fn: uarray1).\n\n  Inductive ufn2 :=\n  | UEq (negate: bool)\n  | UBits2 (fn: ubits2)\n  | UStruct2 (fn: ustruct2)\n  | UArray2 (fn: uarray2).\nEnd PrimUntyped.\n\nModule PrimTyped.\n  Inductive fdisplay :=\n  | DisplayUtf8 (len: nat)\n  | DisplayValue (tau: type) (opts: display_options).\n\n  Inductive fconv :=\n    Pack | Unpack | Ignore.\n\n  Inductive lowered1 :=\n  | IgnoreBits (sz: nat)\n  | DisplayBits (fn: fdisplay).\n\n  Inductive fbits1 :=\n  | Not (sz: nat)\n  | SExt (sz: nat) (width: nat)\n  | ZExtL (sz: nat) (width: nat)\n  | ZExtR (sz: nat) (width: nat)\n  | Repeat (sz: nat) (times: nat)\n  | Slice (sz: nat) (offset: nat) (width: nat)\n  | Lowered (fn: lowered1).\n\n  Inductive fbits2 :=\n  | And (sz: nat)\n  | Or (sz: nat)\n  | Xor (sz: nat)\n  | Lsl (bits_sz: nat) (shift_sz: nat)\n  | Lsr (bits_sz: nat) (shift_sz: nat)\n  | Asr (bits_sz: nat) (shift_sz: nat)\n  | Concat (sz1 sz2 : nat)\n  | Sel (sz: nat)\n  | SliceSubst (sz: nat) (offset: nat) (width: nat)\n  | IndexedSlice (sz: nat) (width: nat)\n  | Plus (sz : nat)\n  | Minus (sz : nat)\n  | Mul (sz1 sz2: nat)\n  | EqBits (sz: nat) (negate: bool)\n  | Compare (signed: bool) (c: bits_comparison) (sz: nat).\n\n  Inductive fstruct1 :=\n  | GetField.\n\n  Inductive fstruct2 :=\n  | SubstField.\n\n  Inductive farray1 :=\n  | GetElement.\n\n  Inductive farray2 :=\n  | SubstElement.\n\n  Inductive fn1 :=\n  | Display (fn: fdisplay)\n  | Conv (tau: type) (fn: fconv)\n  | Bits1 (fn: fbits1)\n  | Struct1 (fn: fstruct1) (sig: struct_sig) (f: struct_index sig)\n  | Array1 (fn: farray1) (sig: array_sig) (idx: array_index sig).\n\n  Inductive fn2 :=\n  | Eq (tau: type) (negate: bool)\n  | Bits2 (fn: fbits2)\n  | Struct2 (fn: fstruct2) (sig: struct_sig) (f: struct_index sig)\n  | Array2 (fn: farray2) (sig: array_sig) (idx: array_index sig).\n\n  Definition GetElementBits (sig: array_sig) (idx: array_index sig) : fbits1 :=\n    Slice (array_sz sig) (element_offset_right sig idx) (element_sz sig).\n\n  Definition SubstElementBits (sig: array_sig) (idx: array_index sig) : fbits2 :=\n    SliceSubst (array_sz sig) (element_offset_right sig idx) (element_sz sig).\n\n  Definition GetFieldBits (sig: struct_sig) (idx: struct_index sig) : fbits1 :=\n    Slice (struct_sz sig) (field_offset_right sig idx) (field_sz sig idx).\n\n  Definition SubstFieldBits (sig: struct_sig) (idx: struct_index sig) : fbits2 :=\n    SliceSubst (struct_sz sig) (field_offset_right sig idx) (field_sz sig idx).\nEnd PrimTyped.\n\nModule PrimTypeInference.\n  Import PrimUntyped PrimTyped.\n\n  Definition find_field sig f : result _ fn_tc_error :=\n    opt_result (List_assoc f sig.(struct_fields)) (Arg1, UnboundField f sig).\n\n  Definition check_index sig pos : result (array_index sig) fn_tc_error :=\n    opt_result (Vect.index_of_nat sig.(array_len) pos) (Arg1, OutOfBounds pos sig).\n\n  Definition tc1 (fn: ufn1) (tau1: type): result fn1 fn_tc_error :=\n    match fn with\n    | UDisplay fn =>\n      match fn with\n      | UDisplayUtf8 =>\n        let/res sig := assert_kind (kind_array None) Arg1 tau1 in\n        Success (Display (DisplayUtf8 sig.(array_len)))\n      | UDisplayValue opts =>\n        Success (Display (DisplayValue tau1 opts))\n      end\n    | UConv fn =>\n      Success (match fn with\n               | UPack => Conv tau1 Pack\n               | UUnpack tau => Conv tau Unpack\n               | UIgnore => Conv tau1 Ignore\n               end)\n    | UBits1 fn =>\n      let/res sz1 := assert_kind kind_bits Arg1 tau1 in\n      Success (Bits1 match fn with\n                     | UNot => Not sz1\n                     | USExt width => SExt sz1 width\n                     | UZExtL width => ZExtL sz1 width\n                     | UZExtR width => ZExtR sz1 width\n                     | URepeat times => Repeat sz1 times\n                     | USlice offset width => Slice sz1 offset width\n                     end)\n    | UStruct1 fn =>\n      match fn with\n      | UGetField f =>\n        let/res sig := assert_kind (kind_struct None) Arg1 tau1 in\n        let/res idx := find_field sig f in\n        Success (Struct1 GetField sig idx)\n      | UGetFieldBits sig f =>\n        let/res idx := find_field sig f in\n        Success (Bits1 (GetFieldBits sig idx))\n      end\n    | UArray1 fn =>\n      match fn with\n      | UGetElement pos =>\n        let/res sig := assert_kind (kind_array None) Arg1 tau1 in\n        let/res idx := check_index sig pos in\n        Success (Array1 GetElement sig idx)\n      | UGetElementBits sig pos =>\n        let/res idx := check_index sig pos in\n        Success (Bits1 (GetElementBits sig idx))\n      end\n    end.\n\n  Definition tc2 (fn: ufn2) (tau1: type) (tau2: type): result fn2 fn_tc_error :=\n    match fn with\n    | UEq negate => Success (Eq tau1 negate)\n    | UBits2 fn =>\n      let/res sz1 := assert_kind kind_bits Arg1 tau1 in\n      let/res sz2 := assert_kind kind_bits Arg2 tau2 in\n      Success (Bits2 match fn with\n                     | USel => Sel sz1\n                     | USliceSubst offset width => SliceSubst sz1 offset width\n                     | UIndexedSlice width => IndexedSlice sz1 width\n                     | UAnd => And sz1\n                     | UOr => Or sz1\n                     | UXor => Xor sz1\n                     | ULsl => Lsl sz1 sz2\n                     | ULsr => Lsr sz1 sz2\n                     | UAsr => Asr sz1 sz2\n                     | UConcat => Concat sz1 sz2\n                     | UPlus => Plus sz1\n                     | UMinus => Minus sz1\n                     | UMul => Mul sz1 sz2\n                     | UCompare signed c => Compare signed c sz1\n                     end)\n    | UStruct2 fn =>\n      match fn with\n      | USubstField f =>\n        let/res sig := assert_kind (kind_struct None) Arg1 tau1 in\n        let/res idx := find_field sig f in\n        Success (Struct2 SubstField sig idx)\n      | USubstFieldBits sig f =>\n        let/res idx := find_field sig f in\n        Success (Bits2 (SubstFieldBits sig idx))\n      end\n    | UArray2 fn =>\n      match fn with\n      | USubstElement pos =>\n        let/res sig := assert_kind (kind_array None) Arg1 tau1 in\n        let/res idx := check_index sig pos in\n        Success (Array2 SubstElement sig idx)\n      | USubstElementBits sig pos =>\n        let/res idx := check_index sig pos in\n        Success (Bits2 (SubstElementBits sig idx))\n      end\n    end.\nEnd PrimTypeInference.\n\nModule CircuitSignatures.\n  Import PrimTyped.\n  Import SigNotations.\n\n  Definition DisplaySigma (fn: fdisplay) : Sig 1 :=\n    {$ match fn with\n       | DisplayUtf8 len => array_t {| array_len := len; array_type := bits_t 8 |}\n       | DisplayValue tau _ => tau\n       end ~> unit_t $}.\n\n  Definition CSigma1 (fn: fbits1) : CSig 1 :=\n    match fn with\n    | Not sz => {$ sz ~> sz $}\n    | SExt sz width => {$ sz ~> (Nat.max sz width) $}\n    | ZExtL sz width => {$ sz ~> (Nat.max sz width) $}\n    | ZExtR sz width => {$ sz ~> (Nat.max sz width) $}\n    | Repeat sz times => {$ sz ~> times * sz $}\n    | Slice sz offset width => {$ sz ~> width $}\n    | Lowered fn =>\n      match fn with\n      | DisplayBits fn => CSig_of_Sig (DisplaySigma fn)\n      | IgnoreBits sz => {$ sz ~> 0 $}\n      end\n    end.\n\n  Definition CSigma2 (fn: PrimTyped.fbits2) : CSig 2 :=\n    match fn with\n    | Sel sz => {$ sz ~> (log2 sz) ~> 1 $}\n    | SliceSubst sz offset width => {$ sz ~> width ~> sz $}\n    | IndexedSlice sz width => {$ sz ~> (log2 sz) ~> width $}\n    | And sz => {$ sz ~> sz ~> sz $}\n    | Or sz => {$ sz ~> sz ~> sz $}\n    | Xor sz => {$ sz ~> sz ~> sz $}\n    | Lsl bits_sz shift_sz => {$ bits_sz ~> shift_sz ~> bits_sz $}\n    | Lsr bits_sz shift_sz => {$ bits_sz ~> shift_sz ~> bits_sz $}\n    | Asr bits_sz shift_sz => {$ bits_sz ~> shift_sz ~> bits_sz $}\n    | Concat sz1 sz2 => {$ sz1 ~> sz2 ~> (sz2 + sz1) $}\n    | EqBits sz _ => {$ sz ~> sz ~> 1 $}\n    | Plus sz => {$ sz ~> sz ~> sz $}\n    | Minus sz => {$ sz ~> sz ~> sz $}\n    | Mul sz1 sz2 => {$ sz1 ~> sz2 ~> sz1 + sz2 $}\n    | Compare _ _ sz => {$ sz ~> sz ~> 1 $}\n    end.\nEnd CircuitSignatures.\n\nModule PrimSignatures.\n  Import PrimUntyped PrimTyped CircuitSignatures.\n  Import SigNotations.\n\n  Definition Sigma1 (fn: fn1) : Sig 1 :=\n    match fn with\n    | Conv tau fn =>\n      match fn with\n      | Pack => {$ tau ~> bits_t (type_sz tau) $}\n      | Unpack => {$ bits_t (type_sz tau) ~> tau $}\n      | Ignore => {$ tau ~> unit_t $}\n      end\n    | Display fn => DisplaySigma fn\n    | Bits1 fn => Sig_of_CSig (CSigma1 fn)\n    | Struct1 GetField sig idx => {$ struct_t sig ~> field_type sig idx $}\n    | Array1 GetElement sig idx => {$ array_t sig ~> sig.(array_type) $}\n    end.\n\n  Definition Sigma2 (fn: fn2) : Sig 2 :=\n    match fn with\n    | Eq tau _ => {$ tau ~> tau ~> bits_t 1 $}\n    | Bits2 fn => Sig_of_CSig (CSigma2 fn)\n    | Struct2 SubstField sig idx => {$ struct_t sig ~> field_type sig idx ~> struct_t sig $}\n    | Array2 SubstElement sig idx => {$ array_t sig ~> sig.(array_type) ~> array_t sig $}\n    end.\nEnd PrimSignatures.\n\nModule BitFuns.\n  Definition bitfun_of_predicate {sz} (p: bits sz -> bits sz -> bool) (bs1 bs2: bits sz) :=\n    Ob~(p bs1 bs2).\n\n  Definition sel {sz} (bs: bits sz) (idx: bits (log2 sz)) :=\n    Ob~match Bits.to_index sz idx with\n       | Some idx => Bits.nth bs idx\n       | _ => false (* TODO: x *)\n       end.\n\n  Definition lsl {bits_sz shift_sz} (bs: bits bits_sz) (places: bits shift_sz) :=\n    Bits.lsl (Bits.to_nat places) bs.\n\n  Definition lsr {bits_sz shift_sz} (bs: bits bits_sz) (places: bits shift_sz) :=\n    Bits.lsr (Bits.to_nat places) bs.\n\n  Definition asr {bits_sz shift_sz} (bs: bits bits_sz) (places: bits shift_sz) :=\n    Bits.asr (Bits.to_nat places) bs.\n\n  Definition _eq {tau} {EQ: EqDec tau} (v1 v2: tau) :=\n    Ob~(beq_dec v1 v2).\n\n  Definition _neq {tau} {EQ: EqDec tau} (v1 v2: tau) :=\n    Ob~(negb (beq_dec v1 v2)).\n\n  Fixpoint get_field fields\n           (v: struct_denote fields)\n           (idx: index (List.length fields))\n           {struct fields}\n    : type_denote (snd (List_nth fields idx)).\n    destruct fields, idx, p; cbn.\n    - apply (fst v).\n    - apply (get_field fields (snd v) a).\n  Defined.\n\n  Fixpoint subst_field fields\n           (v: struct_denote fields)\n           (idx: index (List.length fields))\n           (v': type_denote (snd (List_nth fields idx)))\n           {struct fields}\n    : (struct_denote fields).\n    destruct fields, idx, p; cbn.\n    - apply (v', snd v).\n    - apply (fst v, subst_field fields (snd v) a v').\n  Defined.\nEnd BitFuns.\n\nModule CircuitPrimSpecs.\n  Import PrimTyped BitFuns.\n\n  Definition sigma1 (fn: PrimTyped.fbits1) : CSig_denote (CircuitSignatures.CSigma1 fn) :=\n    match fn with\n    | Not _ => fun bs => Bits.neg bs\n    | SExt sz width => fun bs => Bits.extend_end bs width (Bits.msb bs)\n    | ZExtL sz width => fun bs => Bits.extend_end bs width false\n    | ZExtR sz width => fun bs => Bits.extend_beginning bs width false\n    | Repeat sz times => fun bs => Bits.repeat times bs\n    | Slice _ offset width => Bits.slice offset width\n    | Lowered (DisplayBits _) => fun bs => Ob\n    | Lowered (IgnoreBits _) => fun bs => Ob\n    end.\n\n  Definition sigma2 (fn: PrimTyped.fbits2) : CSig_denote (CircuitSignatures.CSigma2 fn) :=\n    match fn with\n    | Sel _ => sel\n    | SliceSubst _ offset width => Bits.slice_subst offset width\n    | IndexedSlice _ width => fun bs offset => Bits.slice (Bits.to_nat offset) width bs\n    | And _ => Bits.and\n    | Or _ => Bits.or\n    | Xor _ => Bits.xor\n    | Lsl _ _ => lsl\n    | Lsr _ _ => lsr\n    | Asr _ _ => asr\n    | Concat _ _ => Bits.app\n    | Plus _ => Bits.plus\n    | Minus _ => Bits.minus\n    | Mul _ _ => Bits.mul\n    | EqBits _ false => _eq\n    | EqBits _ true => _neq\n    | Compare true cLt _ => bitfun_of_predicate Bits.signed_lt\n    | Compare true cGt _ => bitfun_of_predicate Bits.signed_gt\n    | Compare true cLe _ => bitfun_of_predicate Bits.signed_le\n    | Compare true cGe _ => bitfun_of_predicate Bits.signed_ge\n    | Compare false cLt _ => bitfun_of_predicate Bits.unsigned_lt\n    | Compare false cGt _ => bitfun_of_predicate Bits.unsigned_gt\n    | Compare false cLe _ => bitfun_of_predicate Bits.unsigned_le\n    | Compare false cGe _ => bitfun_of_predicate Bits.unsigned_ge\n    end.\nEnd CircuitPrimSpecs.\n\nModule PrimSpecs.\n  Import PrimTyped BitFuns.\n\n  Definition sigma1 (fn: fn1) : Sig_denote (PrimSignatures.Sigma1 fn) :=\n    match fn with\n    | Display fn =>\n      match fn with\n      | DisplayUtf8 _ => fun _ => Ob\n      | DisplayValue tau _ => fun _ => Ob\n      end\n    | Conv tau fn =>\n      match fn with\n      | Pack => fun v => bits_of_value v\n      | Unpack => fun bs => value_of_bits bs\n      | Ignore => fun _ => Ob\n      end\n    | Bits1 fn => CircuitPrimSpecs.sigma1 fn\n    | Struct1 GetField sig idx => fun s => get_field sig.(struct_fields) s idx\n    | Array1 GetElement sig idx => fun a => vect_nth a idx\n    end.\n\n  Definition sigma2 (fn: fn2) : Sig_denote (PrimSignatures.Sigma2 fn) :=\n    match fn with\n    | Eq tau false  => _eq\n    | Eq tau true  => _neq\n    | Bits2 fn => CircuitPrimSpecs.sigma2 fn\n    | Struct2 SubstField sig idx => fun s v => subst_field sig.(struct_fields) s idx v\n    | Array2 SubstElement sig idx => fun a e => vect_replace a idx e\n    end.\nEnd PrimSpecs.\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/Primitives.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.2739021323302521}}
{"text": "\nFrom Coq Require Import ssreflect.\nFrom MetaCoq.Utils Require Import utils.\nFrom MetaCoq.Common Require Import config BasicAst.\nFrom MetaCoq.PCUIC Require Import PCUICAst PCUICAstUtils PCUICCases PCUICLiftSubst\n  PCUICSigmaCalculus.\n\n#[global] Hint Extern 20 (#|?X| = #|?Y|) =>\n  match goal with\n  [ H : All2_fold _ ?X ?Y |- _ ] => apply (All2_fold_length H)\n  | [ H : All2_fold _ ?Y ?X |- _ ] => symmetry; apply (All2_fold_length H)\n  | [ H : on_contexts_over _ _ _ ?X ?Y |- _ ] => apply (All2_fold_length H)\n  | [ H : on_contexts_over _ _ _ ?Y ?X |- _ ] => symmetry; apply (All2_fold_length H)\n   end : pcuic.\n\nLtac pcuic_core :=\n  try (solve [ intuition auto; eauto with pcuic || (try lia || congruence) ]).\n\nLtac pcuic :=\n  pcuic_core || ltac:(try (red; repeat red; cbn in *; pcuic_core)).\n\nDefinition lengths :=\n  (@context_assumptions_expand_lets_ctx,\n   @context_assumptions_subst_context,\n   context_assumptions_fold,\n   @context_assumptions_app,\n   @context_assumptions_map,\n   @context_assumptions_mapi,\n   @context_assumptions_mapi_context,\n   @context_assumptions_smash_context,\n   @context_assumptions_subst_instance,\n   @context_assumptions_lift_context,\n   @inst_case_context_assumptions,\n    @expand_lets_ctx_length, @subst_context_length,\n    @subst_instance_length, @expand_lets_k_ctx_length, @inds_length, @lift_context_length,\n    @app_length, @repeat_length, @List.rev_length, @extended_subst_length, @reln_length,\n    Nat.add_0_r, @app_nil_r, @rev_map_length, @rev_length, @unfold_length,\n    @map_length, @mapi_length, @mapi_rec_length, @map_InP_length,\n    @fold_context_length,\n    @fold_context_k_length, @cofix_subst_length, @fix_subst_length,\n    fix_context_length,\n    @smash_context_length,\n    @arities_context_length,\n    @forget_types_length,\n    @PCUICCases.ind_predicate_context_length,\n    @PCUICCases.cstr_branch_context_length,\n    @PCUICCases.inst_case_branch_context_length,\n    @PCUICCases.inst_case_predicate_context_length,\n    @inst_case_context_length,\n    @ind_predicate_context_length,\n    @map_context_length, @skipn_map_length,\n    @mapi_context_length, idsn_length,\n    @projs_length, ren_ids_length).\n\nLtac len ::=\n  repeat (rewrite !lengths /= //); try solve [lia_f_equal].\n\nTactic Notation \"len\" \"in\" hyp(id) :=\n  repeat (rewrite !lengths /= // in id);\n  try solve [lia_f_equal].\n\n(* Can be used after [move] by ssr tactics, e.g. [rewrite foo => /lens] *)\nNotation \"'lens'\" := ltac:(len) (only parsing).\n\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/Syntax/PCUICTactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.27390213233025207}}
{"text": "From stdpp Require Import gmap.\nFrom iris.heap_lang Require Export lang.\nFrom iris.prelude Require Import options.\n\n(* This file contains some metatheory about the heap_lang language,\n  which is not needed for verifying programs. *)\n\n(* Closed expressions and values. *)\nFixpoint is_closed_expr (X : list string) (e : expr) : bool :=\n  match e with\n  | Val v => is_closed_val v\n  | Var x => bool_decide (x ∈ X)\n  | Rec f x e => is_closed_expr (f :b: x :b: X) e\n  | UnOp _ e | Fst e | Snd e | InjL e | InjR e | Fork e | Free e | Load e =>\n     is_closed_expr X e\n  | App e1 e2 | BinOp _ e1 e2 | Pair e1 e2 | AllocN e1 e2 | Store e1 e2 | FAA e1 e2 =>\n     is_closed_expr X e1 && is_closed_expr X e2\n  | If e0 e1 e2 | Case e0 e1 e2 | CmpXchg e0 e1 e2 | Resolve e0 e1 e2 =>\n     is_closed_expr X e0 && is_closed_expr X e1 && is_closed_expr X e2\n  | NewProph => true\n  end\nwith is_closed_val (v : val) : bool :=\n  match v with\n  | LitV _ => true\n  | RecV f x e => is_closed_expr (f :b: x :b: []) e\n  | PairV v1 v2 => is_closed_val v1 && is_closed_val v2\n  | InjLV v | InjRV v => is_closed_val v\n  end.\n\nLemma is_closed_weaken X Y e : is_closed_expr X e → X ⊆ Y → is_closed_expr Y e.\nProof. revert X Y; induction e; naive_solver (eauto; set_solver). Qed.\n\nLemma is_closed_weaken_nil X e : is_closed_expr [] e → is_closed_expr X e.\nProof. intros. by apply is_closed_weaken with [], list_subseteq_nil. Qed.\n\nLemma is_closed_subst X e x v :\n  is_closed_val v → is_closed_expr (x :: X) e → is_closed_expr X (subst x v e).\nProof.\n  intros Hv. revert X.\n  induction e=> X /= ?; destruct_and?; split_and?; simplify_option_eq;\n    try match goal with\n    | H : ¬(_ ∧ _) |- _ => apply not_and_l in H as [?%dec_stable|?%dec_stable]\n    end; eauto using is_closed_weaken with set_solver.\nQed.\nLemma is_closed_subst' X e x v :\n  is_closed_val v → is_closed_expr (x :b: X) e → is_closed_expr X (subst' x v e).\nProof. destruct x; eauto using is_closed_subst. Qed.\n\n(* Substitution *)\nLemma subst_is_closed X e x es : is_closed_expr X e → x ∉ X → subst x es e = e.\nProof.\n  revert X. induction e=> X /=; rewrite ?bool_decide_spec ?andb_True=> ??;\n    repeat case_decide; simplify_eq/=; f_equal; intuition eauto with set_solver.\nQed.\n\nLemma subst_is_closed_nil e x v : is_closed_expr [] e → subst x v e = e.\nProof. intros. apply subst_is_closed with []; set_solver. Qed.\n\nLemma subst_subst e x v v' :\n  subst x v (subst x v' e) = subst x v' e.\nProof.\n  intros. induction e; simpl; try (f_equal; by auto);\n    simplify_option_eq; auto using subst_is_closed_nil with f_equal.\nQed.\nLemma subst_subst' e x v v' :\n  subst' x v (subst' x v' e) = subst' x v' e.\nProof. destruct x; simpl; auto using subst_subst. Qed.\n\nLemma subst_subst_ne e x y v v' :\n  x ≠ y → subst x v (subst y v' e) = subst y v' (subst x v e).\nProof.\n  intros. induction e; simpl; try (f_equal; by auto);\n    simplify_option_eq; auto using eq_sym, subst_is_closed_nil with f_equal.\nQed.\nLemma subst_subst_ne' e x y v v' :\n  x ≠ y → subst' x v (subst' y v' e) = subst' y v' (subst' x v e).\nProof. destruct x, y; simpl; auto using subst_subst_ne with congruence. Qed.\n\nLemma subst_rec' f y e x v :\n  x = f ∨ x = y ∨ x = BAnon →\n  subst' x v (Rec f y e) = Rec f y e.\nProof. intros. destruct x; simplify_option_eq; naive_solver. Qed.\nLemma subst_rec_ne' f y e x v :\n  (x ≠ f ∨ f = BAnon) → (x ≠ y ∨ y = BAnon) →\n  subst' x v (Rec f y e) = Rec f y (subst' x v e).\nProof. intros. destruct x; simplify_option_eq; naive_solver. Qed.\n\nLemma bin_op_eval_closed op v1 v2 v' :\n  is_closed_val v1 → is_closed_val v2 → bin_op_eval op v1 v2 = Some v' →\n  is_closed_val v'.\nProof.\n  rewrite /bin_op_eval /bin_op_eval_bool /bin_op_eval_int /bin_op_eval_loc;\n    repeat case_match; by naive_solver.\nQed.\n\nLemma heap_closed_alloc σ l n w :\n  (0 < n)%Z →\n  is_closed_val w →\n  map_Forall (λ _ v, from_option is_closed_val true v) (heap σ) →\n  (∀ i : Z, (0 ≤ i)%Z → (i < n)%Z → heap σ !! (l +ₗ i) = None) →\n  map_Forall (λ _ v, from_option is_closed_val true v)\n             (heap_array l (replicate (Z.to_nat n) w) ∪ heap σ).\nProof.\n  intros Hn Hw Hσ Hl.\n  eapply (map_Forall_ind\n            (λ k v, ((heap_array l (replicate (Z.to_nat n) w) ∪ heap σ)\n                       !! k = Some v))).\n  - apply map_Forall_empty.\n  - intros m i x Hi Hix Hkwm Hm.\n    apply map_Forall_insert_2; auto.\n    apply lookup_union_Some in Hix; last first.\n    { eapply heap_array_map_disjoint;\n        rewrite replicate_length Z2Nat.id; auto with lia. }\n    destruct Hix as [(?&?&?&?&?&[-> Hlt%inj_lt]%lookup_replicate_1)%heap_array_lookup|\n                     [j Hj]%elem_of_map_to_list%elem_of_list_lookup_1].\n    + simplify_eq/=. rewrite !Z2Nat.id in Hlt; eauto with lia.\n    + apply map_Forall_to_list in Hσ.\n      by eapply Forall_lookup in Hσ; eauto; simpl in *.\n  - apply map_Forall_to_list, Forall_forall.\n    intros [? ?]; apply elem_of_map_to_list.\nQed.\n\n(* The stepping relation preserves closedness *)\nLemma head_step_is_closed e1 σ1 obs e2 σ2 es :\n  is_closed_expr [] e1 →\n  map_Forall (λ _ v, from_option is_closed_val true v) σ1.(heap) →\n  head_step e1 σ1 obs e2 σ2 es →\n  is_closed_expr [] e2 ∧ Forall (is_closed_expr []) es ∧\n  map_Forall (λ _ v, from_option is_closed_val true v) σ2.(heap).\nProof.\n  intros Cl1 Clσ1 STEP.\n  induction STEP; simpl in *; split_and!;\n    try apply map_Forall_insert_2; try by naive_solver.\n  - subst. repeat apply is_closed_subst'; naive_solver.\n  - unfold un_op_eval in *. repeat case_match; naive_solver.\n  - eapply bin_op_eval_closed; eauto; naive_solver.\n  - by apply heap_closed_alloc.\n  - select (_ !! _ = Some _) ltac:(fun H => by specialize (Clσ1 _ _ H)).\n  - select (_ !! _ = Some _) ltac:(fun H => by specialize (Clσ1 _ _ H)).\n  - case_match; try apply map_Forall_insert_2; by naive_solver.\nQed.\n\nFixpoint subst_map (vs : gmap string val) (e : expr) : expr :=\n  match e with\n  | Val _ => e\n  | Var y => if vs !! y is Some v then Val v else Var y\n  | Rec f y e => Rec f y (subst_map (binder_delete y (binder_delete f vs)) e)\n  | App e1 e2 => App (subst_map vs e1) (subst_map vs e2)\n  | UnOp op e => UnOp op (subst_map vs e)\n  | BinOp op e1 e2 => BinOp op (subst_map vs e1) (subst_map vs e2)\n  | If e0 e1 e2 => If (subst_map vs e0) (subst_map vs e1) (subst_map vs e2)\n  | Pair e1 e2 => Pair (subst_map vs e1) (subst_map vs e2)\n  | Fst e => Fst (subst_map vs e)\n  | Snd e => Snd (subst_map vs e)\n  | InjL e => InjL (subst_map vs e)\n  | InjR e => InjR (subst_map vs e)\n  | Case e0 e1 e2 => Case (subst_map vs e0) (subst_map vs e1) (subst_map vs e2)\n  | Fork e => Fork (subst_map vs e)\n  | AllocN e1 e2 => AllocN (subst_map vs e1) (subst_map vs e2)\n  | Free e => Free (subst_map vs e)\n  | Load e => Load (subst_map vs e)\n  | Store e1 e2 => Store (subst_map vs e1) (subst_map vs e2)\n  | CmpXchg e0 e1 e2 => CmpXchg (subst_map vs e0) (subst_map vs e1) (subst_map vs e2)\n  | FAA e1 e2 => FAA (subst_map vs e1) (subst_map vs e2)\n  | NewProph => NewProph\n  | Resolve e0 e1 e2 => Resolve (subst_map vs e0) (subst_map vs e1) (subst_map vs e2)\n  end.\n\nLemma subst_map_empty e : subst_map ∅ e = e.\nProof.\n  assert (∀ x, binder_delete x (∅:gmap _ val) = ∅) as Hdel.\n  { intros [|x]; by rewrite /= ?delete_empty. }\n  induction e; simplify_map_eq; rewrite ?Hdel; auto with f_equal.\nQed.\nLemma subst_map_insert x v vs e :\n  subst_map (<[x:=v]>vs) e = subst x v (subst_map (delete x vs) e).\nProof.\n  revert vs. induction e=> vs; simplify_map_eq; auto with f_equal.\n  - match goal with\n    | |- context [ <[?x:=_]> _ !! ?y ] =>\n       destruct (decide (x = y)); simplify_map_eq=> //\n    end. by case (vs !! _); simplify_option_eq.\n  - destruct (decide _) as [[??]|[<-%dec_stable|[<-%dec_stable ?]]%not_and_l_alt].\n    + rewrite !binder_delete_insert // !binder_delete_delete; eauto with f_equal.\n    + by rewrite /= delete_insert_delete delete_idemp.\n    + by rewrite /= binder_delete_insert // delete_insert_delete\n        !binder_delete_delete delete_idemp.\nQed.\nLemma subst_map_singleton x v e :\n  subst_map {[x:=v]} e = subst x v e.\nProof. by rewrite subst_map_insert delete_empty subst_map_empty. Qed.\n\nLemma subst_map_binder_insert b v vs e :\n  subst_map (binder_insert b v vs) e =\n  subst' b v (subst_map (binder_delete b vs) e).\nProof. destruct b; rewrite ?subst_map_insert //. Qed.\nLemma subst_map_binder_insert_empty b v e :\n  subst_map (binder_insert b v ∅) e = subst' b v e.\nProof. by rewrite subst_map_binder_insert binder_delete_empty subst_map_empty. Qed.\n\nLemma subst_map_binder_insert_2 b1 v1 b2 v2 vs e :\n  subst_map (binder_insert b1 v1 (binder_insert b2 v2 vs)) e =\n  subst' b2 v2 (subst' b1 v1 (subst_map (binder_delete b2 (binder_delete b1 vs)) e)).\nProof.\n  destruct b1 as [|s1], b2 as [|s2]=> /=; auto using subst_map_insert.\n  rewrite subst_map_insert. destruct (decide (s1 = s2)) as [->|].\n  - by rewrite delete_idemp subst_subst delete_insert_delete.\n  - by rewrite delete_insert_ne // subst_map_insert subst_subst_ne.\nQed.\nLemma subst_map_binder_insert_2_empty b1 v1 b2 v2 e :\n  subst_map (binder_insert b1 v1 (binder_insert b2 v2 ∅)) e =\n  subst' b2 v2 (subst' b1 v1 e).\nProof.\n  by rewrite subst_map_binder_insert_2 !binder_delete_empty subst_map_empty.\nQed.\n\n(* subst_map on closed expressions *)\nLemma subst_map_is_closed X e vs :\n  is_closed_expr X e →\n  (∀ x, x ∈ X → vs !! x = None) →\n  subst_map vs e = e.\nProof.\n  revert X vs. assert (∀ x x1 x2 X (vs : gmap string val),\n    (∀ x, x ∈ X → vs !! x = None) →\n    x ∈ x2 :b: x1 :b: X →\n    binder_delete x1 (binder_delete x2 vs) !! x = None).\n  { intros x x1 x2 X vs ??. rewrite !lookup_binder_delete_None. set_solver. }\n  induction e=> X vs /= ? HX; repeat case_match; naive_solver eauto with f_equal.\nQed.\n\nLemma subst_map_is_closed_nil e vs : is_closed_expr [] e → subst_map vs e = e.\nProof. intros. apply subst_map_is_closed with []; set_solver. Qed.\n", "meta": {"author": "jtassarotti", "repo": "iris-inv-hierarchy", "sha": "b25fe890d72ecb5bafa9db422ece3939d99882ab", "save_path": "github-repos/coq/jtassarotti-iris-inv-hierarchy", "path": "github-repos/coq/jtassarotti-iris-inv-hierarchy/iris-inv-hierarchy-b25fe890d72ecb5bafa9db422ece3939d99882ab/iris_heap_lang/metatheory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.27390213233025207}}
{"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 Tools.Matches Compilers.Compilers Elab.ElabCompilers.\nFrom Pyrosome.Lang Require Import SimpleVSubst SimpleVSTLC SimpleEvalCtx SimpleVCPS.\nImport Core.Notations.\n\nRequire Coq.derive.Derive.\n\nNotation compiler := (compiler string).\n\n(*TODO: repackage this in compilers*)\nImport CompilerDefs.Notations.\n\nDefinition Ectx_cps_def : compiler :=\n  match # from eval_ctx with\n  | {{s #\"Ectx\" \"G\" \"A\" \"B\" }} =>\n    {{s #\"blk\" (#\"ext\" (#\"ext\" \"G\" (#\"neg\" \"B\")) \"A\") }}\n  | {{e #\"[ ]\" \"G\" \"A\"}} =>\n    {{e #\"jmp\" {ovar 1} {ovar 0} }}\n  | {{e #\"plug\" \"G\" \"A\" \"B\" \"E\" \"e\"}} =>\n    bind_k 1 (var \"e\") (var \"A\") (var \"E\")\n  end.\n\n\n\nDerive Ectx_cps\n       SuchThat (elab_preserving_compiler cps_subst\n                                          (cps_lang\n                                             ++ block_subst\n                                             ++ value_subst)\n                                          Ectx_cps_def\n                                          Ectx_cps\n                                          eval_ctx)\n       As Ectx_cps_preserving.\nProof. auto_elab_compiler. Qed.\n#[export] Hint Resolve cps_subst_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/SimpleEvalCtxCPS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2738631569853562}}
{"text": "Require Import HoTT.\nRequire Import UnivalenceAxiom.\nLoad sigma_lemmas.\nLoad trunc_lemmas.\n  \n(* Load stuff. *)\n\n\nRequire Import Functor Category.\n(*These notations are defined elsewhere, but I do not know how to import it.*)\nLocal Notation \"x --> y\" := (morphism _ x y) (at level 99, right associativity, y at level 200) : type_scope.\nNotation \"F '_0' x\" := (Functor.Core.object_of F x) (at level 10, no associativity, only parsing) : object_scope.\nNotation \"F '_1' m\" := (Functor.Core.morphism_of F m) (at level 10, no associativity) : morphism_scope.\nOpen Scope category_scope.\nOpen Scope morphism_scope.\n\n(* Definition diagonal_functor {C : PreCategory} : Functor C (C*C). *)\n(* Proof.   *)\n(*   srapply @Build_Functor. *)\n(*   (* Map on objects *) *)\n(*   - exact (fun c => (c,c)). *)\n(*   (* Map on morphisms *) *)\n(*   - exact (fun c d f => (f, f)). *)\n(*   (* Respect composition *) *)\n(*   - exact (fun c d e f g => idpath). *)\n(*   (* Respect identity *) *)\n(*   - exact (fun c => idpath). *)\n(* Defined. *)\n\nDefinition pair_1 {C D : PreCategory} {c c' : C} {d d' : D} (f : c --> c') (g : d --> d') :\n  morphism (C*D) (c, d) (c', d') := (f,g).\n\n\n(* Definition transport_morphism_Fl {C D : PreCategory} (F : Functor C D) {c1 c2 : C} {d : D} (p : c1 = c2) (f : F c1 --> d): *)\n(*            transport (fun c : C => F c --> d) p f = f o (F _1 (idtoiso C p))^-1. (* (idtoiso D (ap F p))^-1. *) *)\n(* Proof. *)\n(*   induction p. simpl. *)\n(*   apply inverse. *)\n(*   refine (_ @ right_identity D _ _ f). *)\n(*   apply (ap (fun g => f o g)). *)\n(*   apply identity_of. *)\n(* Defined. *)\n\n(* (* Another version that doesn't use the inverse. *)\n(*    Definitionally the inverse isn't given uniquely, and that gives some problems later. . . *)\n(*  *) *)\n(* Definition transport_morphism_Fl' {C D : PreCategory} (F : Functor C D) *)\n(*            {c1 c2 : C} {d : D} (p : c1 = c2) (f : F c1 --> d): *)\n(*   f = transport (fun c : C => F c --> d) p f o (F _1 (idtoiso C p)). *)\n(* Proof. *)\n(*   induction p. simpl. *)\n(*   apply inverse. *)\n(*   refine (_ @ right_identity D _ _ f). *)\n(*   apply (ap (fun g => f o g)). *)\n(*   apply identity_of. *)\n(* Defined.   *)\n\n\nRecord Magma : Type :=\n  { magma_cat :> PreCategory; binary_op : Functor (magma_cat*magma_cat) magma_cat }.\nArguments binary_op {m}.\n\nDefinition binary_op_0 {M : Magma} : ((object M) * (object M) -> object M )%type :=\n  object_of binary_op.\n\n\nLocal Notation \"a + b\" := (Core.object_of binary_op (a, b)). (* Just for printing. *)\nLocal Notation \"a + b\" := (binary_op (a, b)).\n\n(* Definition binary_op_1 {M : Magma} {s1 s2 d1 d2 : object M} : *)\n(*   ((s1 --> d1) * (s2 --> d2))%type -> ((s1 + s2) --> (d1 + d2)). *)\n(* Proof. *)\n(*   intro m. apply (morphism_of binary_op). exact m. *)\n(* Defined. *)\n\nLocal Notation \"f +^ g\" := (binary_op _1 (f, g)) (at level 40). (* This is just for printing *)\nLocal Notation \"f +^ g\" := (binary_op _1 (pair_1 f g)) (at level 40).\n\n\n\n(* Sum of idmaps is the idmap *)\nDefinition sum_idmap {M : Magma} {m n : M} : (identity m +^ identity n) = identity (m + n) :=\n  identity_of binary_op (m, n).\n\n(* Translation from right *)\nDefinition translate_fr {M : Magma} (a : M) : Functor M M.\nProof.\n  refine (Functor.compose (D := M*M) binary_op _).\n  srapply @Build_Functor.\n  (* Objects *)\n  - exact (fun m => (m, a)).\n  (* Morphisms *)\n  - intros m n f. exact (f,identity a).\n  (* Respect composition *)\n  - intros l m n.\n    intros f g.\n    apply path_prod. exact idpath. apply inverse. apply left_identity.\n  (* Respect identity *)\n  - exact (fun _ => idpath).\nDefined.\n\n(* Translation from left *)\nDefinition translate_fl {M : Magma} (a : M) : Functor M M.\nProof.\n  refine (Functor.compose (D := M*M) binary_op _).\n  srapply @Build_Functor.\n  (* Objects *)\n  - exact (fun m => (a, m)).\n  (* Morphisms *)\n  - intros m n f. exact (identity a, f).\n  (* Respect composition *)\n  - intros l m n.\n    intros f g.\n    apply path_prod. apply inverse. apply left_identity. exact idpath. \n  (* Respect identity *)\n  - exact (fun _ => idpath).\nDefined.\n  \n\n\nSection Monoidal_Category.\n  (* Require cancellation law, even if that is not reflected in the name. *)\n  Record Symmetric_Monoidal_Category : Type :=\n    {smon_magma :> Magma ;\n     (* isgroupoid_smon_magma : forall (a b : smon_magma) (f : a --> b), IsIsomorphism f; *)\n     e : smon_magma ;\n     assoc : forall a b c : smon_magma, (a + b) + c --> a + (b + c);\n     iso_assoc : forall a b c : smon_magma, IsIsomorphism (assoc a b c);\n     natural_assoc : forall (a b c a' b' c': smon_magma) (f : a-->a') (g : b --> b') (h : c --> c'),\n       assoc a' b' c' o ((f +^ g) +^ h) = (f +^ (g +^ h)) o assoc a b c;\n     lid : forall a : smon_magma, e + a --> a;\n     iso_lid : forall a : smon_magma, IsIsomorphism (lid a);\n     natural_lid : forall (a a' : smon_magma) (f : a --> a'),\n       lid a' o (1 +^ f) = f o lid a;\n     rid : forall a : smon_magma, a + e --> a;\n     iso_rid : forall a : smon_magma, IsIsomorphism (rid a);\n     natural_rid : forall (a a' : smon_magma) (f : a --> a'),\n       rid a' o (f +^ 1) = f o rid a;\n     symm : forall a b : smon_magma, a + b -->  b + a;\n     natural_sym : forall (a b a' b' : smon_magma) (f : a --> a') (g : b --> b'),\n         symm a' b' o (f +^ g) = (g +^ f) o symm a b;\n     symm_inv : forall a b : smon_magma, symm a b o symm b a = 1;\n     coh_tri : forall a b : smon_magma,\n         (1 +^ lid b) o (assoc a e b) = (rid a +^ 1) ;\n     coh_pent : forall a b c d : smon_magma,\n         (assoc a b (c+d)) o (assoc (a+b) c d)  =\n         (1 +^ assoc b c d) o (assoc a (b+c) d) o (assoc a b c +^ 1);\n     coh_hex : forall a b c : smon_magma,\n         (assoc b c a) o (symm a (b + c)) o (assoc a b c) =\n         (1 +^ symm a c) o (assoc b a c) o (symm a b +^ 1)\n         \n         (* (assoc c a b) o (symm (a+b) c) o assoc a b c = *)\n         (* (symm a c +^ 1) o (assoc a c b) o (1 +^ symm b c); (*I am guessing that this is correct*) *)\n     (* cancellation : forall (s t a : smon_magma) (f g : s --> t), (f +^ identity a) = (g +^ identity a) -> f = g *)\n    }.\n\n  (* Coherence results that are true given the above, but whose proofs are omitted (for now) *)\n  Lemma coh_lid_assoc_lid (M : Symmetric_Monoidal_Category) : forall a b : M,\n      lid M (a + b) o assoc M (e M) a b = (lid M a +^ 1).\n  Admitted.\n\n  \n\n  (*Want to define the category [Sigma] of finite sets and isomorphisms. *)\n  Definition isset_Finite (A : Type) :\n    Finite A -> IsHSet A.\n  Proof.\n    intros [m finA]. strip_truncations.\n    apply (trunc_equiv' (Fin m) finA^-1).\n  Defined.\n  \n  (*obj Sigma := {A : Type & Finite A}\n    morph A B := Equiv (Fin (card A)) (Fin (card B))*)\n\n  (*Definition Sigma_morphism (m n : nat) := Equiv (Fin m) (Fin n).*)\n\n  Definition Sigma_precat : PreCategory.\n  Proof.\n    srapply (@Build_PreCategory {A : Type & Finite A}\n                                (fun A B => Equiv A.1 B.1)).\n                                (* (fun A B => Equiv (Fin (@fcard A.1 A.2)) (Fin (@fcard B.1 B.2)))). *)\n    - (*Identity*)\n      intro m.\n      apply equiv_idmap.\n    - (*Compose*)\n      intros A B C.\n      apply equiv_compose'.\n    - (*Associativity*)\n      intros A B C D.\n      intros e f g.\n      apply ecompose_ee_e.\n    - (*Composing with identity from left*)\n      intros D E. intro f.\n      apply ecompose_1e.\n    - (*Composing with identity from right*)\n      intros D E. intro f.\n      apply ecompose_e1.\n    - intros A B. simpl.\n      srapply @istrunc_equiv. apply isset_Finite. exact B.2.\n  Defined.\n\n  Instance isgroupoid_preSigma (a b : Sigma_precat) (f : a --> b) : IsIsomorphism f.\n  Proof.\n    srapply @Build_IsIsomorphism.\n    - exact (f^-1%equiv).\n    - apply ecompose_Ve.\n    - apply ecompose_eV.\n  Defined.\n\n\n  (* This category is univalent *)\n  (* Prove this by reducing to univalence in types *)\n  (*First: An isomorphism is the same as an equivalence on the underlying type *)\n  Definition equiv_isomorphic_Sigma (A B : Sigma_precat) : (A.1 <~> B.1) <~> Isomorphic A B.\n  Proof.\n    srapply @equiv_adjointify.\n    - (*Inverse*)\n      intro f. apply (@Build_Isomorphic _ A B f _).\n    - (*Underlying map*)\n      exact (@morphism_isomorphic _ A B).\n    - intro g. apply path_isomorphic. exact idpath.\n    - exact (fun _ => idpath).\n  Defined.\n\n  Definition idtoiso_is_path_equiv {A B : Sigma_precat} :\n    @idtoiso Sigma_precat A B =\n    (equiv_isomorphic_Sigma A B) oE (equiv_equiv_path A.1 B.1) oE (equiv_path_sigma_hprop A B)^-1.\n  Proof.\n    apply path_arrow. \n    intros []. apply path_isomorphic. exact idpath.\n  Defined.\n\n  \n  Lemma iscategory_Sigma : IsCategory Sigma_precat.\n    intros A B.\n    rewrite idtoiso_is_path_equiv. exact _.\n  Qed.\n\n  Definition Sigma_cat := Build_Category iscategory_Sigma.\n\n  Definition Sigma_coprod : Functor (Sigma_cat*Sigma_cat) Sigma_cat.\n  Proof.\n    srapply @Build_Functor.\n    - (*Map on objects is sum of types*)\n      intros [A B].\n      exists (A.1 + B.1)%type. apply finite_sum; exact _.2.\n    - (*Map on morphisms.*)\n      (*Fin respects sum*)\n      intros [A B] [C D].\n      unfold morphism. simpl.\n      intros [f g]. apply (equiv_functor_sum' f g).\n    - (*Respects composition*)\n      intros [i1 i2] [j1 j2] [k1 k2].\n      intros [f1 f2] [g1 g2]. simpl.\n      apply path_equiv. apply path_arrow. \n      intros [m | n]; exact idpath.\n    - (*Respects identity*)\n      intros [i j]. simpl.\n      apply path_equiv. apply path_arrow. intros [m | n]; exact idpath.\n  Defined.\n\n  (* Ltac reduce_sigma_morphism := intros; apply path_equiv; apply path_arrow; repeat (intros [?m | ]); intros. *)\n  \n  Definition Sigma : Symmetric_Monoidal_Category.\n  Proof.\n    srapply (@Build_Symmetric_Monoidal_Category (Build_Magma Sigma_cat Sigma_coprod) \n                                                ( Fin 0 ; finite_fin 0 )).\n    - (*Associativity*)\n      intros A B C.\n      apply equiv_sum_assoc.\n    - (* Associativity is natural *)\n      intros A B C A' B' C' f g h. apply path_equiv. apply path_arrow.\n      intros [[l | m] | n]; exact idpath.\n    - (*Left identity*)\n      intro a. apply sum_empty_l.\n    - (*Left identity is natural*)\n      intros A A' f.      \n      apply path_equiv. apply path_arrow. intros [[] | n]. exact idpath.\n    - (*Right identity*)\n      intro a. apply sum_empty_r.\n    - (*Right identity is natural*)\n      intros A A' f. \n      apply path_equiv. apply path_arrow. intros [n | []]. exact idpath.\n    - (*Symmetry*)\n      intros A A'.\n      apply equiv_sum_symm.\n    - (*Symmetry is natural*)\n      intros A A' B B' f g.\n      apply path_equiv. apply path_arrow. intros [m | n]; exact idpath.\n    - (*Symmetry is its own inverse*)\n      intros A B.\n      apply path_equiv. apply path_arrow. intros [m | n]; exact idpath.\n    - (*Coherence triangle*)\n      intros A B.\n      apply path_equiv. apply path_arrow. intros [[m | []] | n]; exact idpath.\n    - (*Coherence pentagon*)\n      intros A B C D.\n      apply path_equiv. apply path_arrow. repeat (intros [ | m]); intros; exact idpath.\n    - (*Coherence hexagon*)\n      simpl. intros A B C.\n      apply path_equiv. apply path_arrow. repeat (intros [ | m]); intros; exact idpath.\n    (* - (* Translations are faithful *) *)\n    (*   (* This proof is not natural in A, but this is a proposition so it doesn't matter. . .*) *)\n    (*   intros S T A f g H. *)\n    (*   apply path_equiv. apply path_arrow. intro s. *)\n    (*   set (collapseA := fun ta : T.1 + A.1%type => *)\n    (*                       match ta with *)\n    (*                       |Datatypes.inl t => t *)\n    (*                       |Datatypes.inr _ => f s (*This is an arbitrary choice.*) *)\n    (*                       end). *)\n    (*   change (f s) with (collapseA ((f +^ 1) (Datatypes.inl s))). *)\n    (*   rewrite H. reflexivity. *)\n  Defined.\n\n  (* Instance isgroupoid_Sigma (A B : Sigma) (f : A --> B) : IsIsomorphism f := isgroupoid_preSigma A B f.  *)\n  \n  Lemma faithful_cancellation_Sigma (S T A : Sigma) (f g : S --> T) :\n    (f +^ identity A) = (g +^ identity A) -> f = g.\n  Proof.\n    (* This proof is not natural in A, but this is a proposition so it doesn't matter. . .*)\n    intro H.\n    apply path_equiv. apply path_arrow. intro s.\n    set (collapseA := fun ta : T.1 + A.1%type =>\n                        match ta with\n                        |Datatypes.inl t => t\n                        |Datatypes.inr _ => f s (*This is an arbitrary choice.*)\n                        end).\n    change (f s) with (collapseA ((f +^ 1) (Datatypes.inl s))).\n    rewrite H. reflexivity.\n  Qed.    \n  \nEnd Monoidal_Category.\n\n(* (* A somewhat stupid tactic that tries to rewrite all the identities *) *)\n(* Ltac moncat_rewrite := *)\n(*   repeat (repeat rewrite natural_assoc; *)\n(*           repeat rewrite natural_lid; *)\n(*           repeat rewrite natural_rid; *)\n(*           repeat rewrite natural_sym; *)\n(*           repeat rewrite symm_inv; *)\n(*           repeat rewrite coh_tri; *)\n(*           repeat rewrite coh_pent; *)\n(*           repeat rewrite coh_hex; *)\n(*           repeat rewrite coh_lid_assoc_lid). *)\n\n\n\n(* Define the group completion of a symmetric monoidal category *)\nSection Group_Completion.\n  (* Definition Magma_prod (M N : Magma) : Magma. *)\n  (* srapply @Build_Magma. *)\n  (* - srapply @Build_Category. *)\n  (*   + exact (M*M). *)\n  (*   + (* *) *)\n  (*     admit. *)\n  (* - srapply @Build_Functor. *)\n  (*   + intros [[a1 a2] [b1 b2]]. simpl. *)\n  (*     exact (a1 + b1, a2 + b2). *)\n  (*   + simpl. *)\n\n  Notation \"( a , b ) --> ( c , d ) \" := (morphism (_ * _) (a, b) (c, d)).\n  (* Notation \" a ==> b \" := (morphism (_ * _) a b) (at level 40). *)\n  (* Notation \"a +p b\" := (Datatypes.fst a + Datatypes.fst b, Datatypes.snd a + Datatypes.snd b) (at level 40). (* Level is just arbitrary. . . *) *)\n\n  (* Assume that M is a symmetric monoidal groupoid with cancellation. *)\n  Variable M : Symmetric_Monoidal_Category.\n  Variable iscategory_M : IsCategory M.\n  Variable isgroupoid_M : forall (a b : M) (f : a --> b), IsIsomorphism f.\n  Variable cancellation_M : forall (s t a : M) (f g : s --> t), (f +^ identity a) = (g +^ identity a) -> f = g.\n  \n  (* Definition isgroupoid (M : Symmetric_Monoidal_Category) : Type := *)\n  (*   forall (a b : M) (f : a --> b), IsIsomorphism f. *)\n  (* Definition monoid_cancellation (M : Symmetric_Monoidal_Category) : Type := *)\n  (*   forall (s t a : M) (f g : s --> t), *)\n  (*     (f +^ identity a) = (g +^ identity a) -> f = g. *)\n\n  Instance isgroupoid_prod : forall (a b : (M*M)%category) (f : a --> b), IsIsomorphism f.\n  Proof.\n    intros [a1 a2] [b1 b2]. intros [f1 f2].\n    srapply @Build_IsIsomorphism; simpl.\n    - exact (f1^-1, f2^-1).\n    - abstract (repeat rewrite left_inverse; reflexivity). \n    - abstract (repeat rewrite right_inverse; reflexivity).\n  Defined.\n\n  (* The diagonal functor *)\n  Definition diag {C : PreCategory} : Functor C (C*C).\n  Proof.\n    srapply @Build_Functor.\n    (* Map on objects *)\n    - exact (fun c => (c,c)).\n    (* On morphisms *)\n    - intros c1 c2 f. exact (f, f).\n    (* Respect composition *) - reflexivity.\n    (* Respect identity. *)   - reflexivity.\n  Defined.\n  \n  (* The induced sum on [M*M] *)\n  (*    [(a1, a2) + (b1, b2) = (a1+b1, a2 + b2)*)\n  Definition sum2 : Functor ((M*M) * (M*M)) (M*M).\n  Proof.\n    refine (Functor.compose (pair (@binary_op M) (@binary_op M) ) _).\n    (* Build a functor swapping 2nd and 3rd component *)\n    (* Use associativity to get to where we can swap. *)\n    refine (Functor.compose (ProductLaws.Associativity.functor M M (M*M)) _).\n    refine (Functor.compose (pair (Functor.identity M) (ProductLaws.Associativity.inverse M M M)) _).\n    (* Now we can swap *)\n    refine (Functor.compose (pair (Functor.identity M) (pair (ProductLaws.Swap.functor M M) (Functor.identity M) )) _).\n    (* Use associativity to get back again *)\n    refine (Functor.compose (pair (Functor.identity M) (ProductLaws.Associativity.functor M M M)) _).\n    exact (ProductLaws.Associativity.inverse M M (M*M)).\n  Defined.\n\n  (* Notation for sum2 on morphisms *)\n  Notation \"f +^+ g\" := (sum2 _1 (pair_1 f g)) (at level 40).\n\n  (* (* Sum of pairs *) *)\n  (* Notation \"a +p b\" := (sum2 (a, b)) (at level 40). *)\n\n  Definition assoc_sum2 (a b c : M*M) : sum2 (sum2 (a,  b), c) --> sum2 (a, (sum2 (b,  c))).\n  Proof.\n    split; apply assoc.\n  Defined.\n\n  (* (* (diag + 1) *) *)\n  (* Definition act_on_prod : Functor (M*(M*M)) (M*M) := sum2 o (pair diag (Identity.identity _))%functor.   *)\n\n  (* (* Just to remind me what [act_on_prod] does on objects *) *)\n  (* Lemma what_is_act_on_prod : forall (s a1 a2 : M), act_on_prod (s, (a1, a2)) = (s + a1, s + a2). *)\n  (*   reflexivity. *)\n  (* Qed.  *)\n  \n  (* Definition act_on_prod (s : M) : Functor (M*M) (M*M). *)\n  (* Proof. *)\n  (*   refine (Functor.compose sum2 _). *)\n  (*   apply Functor.prod. *)\n  (*   (* The constant functor (s,s) *) *)\n  (*   - srapply @Build_Functor. *)\n  (*     + exact (const (s,s)). *)\n  (*     + intros. exact (1,1). *)\n  (*     + intros. rewrite left_identity. reflexivity. *)\n  (*     + reflexivity. *)\n  (*   - apply Identity.identity. *)\n  (* Defined.   *)\n\n  Definition group_completion_morph :\n    (M*M)%category -> (M*M)%category -> Type.\n  Proof.\n    intros a b. (* [a_p a_m] [b_p b_m]. *)\n    exact {s : M & sum2 (diag s, a) --> b}.   (* (s + a_p, s + a_m) --> (b_p, b_m)}. *)\n  Defined.\n\n\n\n  (* Must I start with everything reduced for the notation to be readable? *)\n  Definition equiv_group_completion_morph (a b : M*M) (f g : group_completion_morph a b) :\n    f = g <~> {alpha : f.1 --> g.1 & f.2 = g.2 o ((diag _1 alpha) +^+ 1)}.\n  (* (act_on_prod _1 (pair_1 alpha 1))}. *)\n  (* (pair_1 (alpha +^ 1) (alpha +^ 1))}. *)\n  Proof.\n    destruct a as [a1 a2]. destruct b as [b1 b2]. unfold group_completion_morph in f, g.\n    (* destruct f as [t f]. destruct g as [s g]. simpl. *) (* simpl in f1, f2, g1, g2. *)\n    set (F := Functor.prod (translate_fr a1) (translate_fr a2)).\n    refine (_ oE equiv_path_sigma (fun s : M => F s --> (b1, b2)) _ _).\n    transitivity {p : f.1 = g.1 & f.2 = g.2 o (F _1 (idtoiso M p))}.\n    { apply equiv_functor_sigma_id. intro p.\n      destruct f as [s f]. destruct g as [t g].\n      simpl in p. destruct p. simpl.\n      destruct f as [f1 f2]. destruct g as [g1 g2]. simpl in f1, f2, g1, g2. simpl.\n      apply equiv_concat_r.\n      apply path_prod; simpl; apply inverse; refine (_ @ right_identity M _ _ _);\n        refine (ap (fun g => _ o g) _); apply identity_of. }\n    (*   transitivity (f.2 o (F _1 (idtoiso M p ))^-1 = g.2). *)\n    (*   - apply equiv_concat_l. *)\n    (*     apply iso_moveR_pV. *)\n    (*     apply (transport_morphism_Fl' F p f.2). *)\n    (*   (* Can't find this specific equivalence implemented. . . *) *)\n    (*   - srapply @equiv_adjointify. apply iso_moveL_pM. apply iso_moveR_pV. *)\n    (*     intro q. apply (trunc_morphism (M*M)). *)\n    (*     intro q. apply (trunc_morphism (M*M)). }  *)\n    transitivity ({alpha : f.1 <~=~> g.1 & f.2 = g.2 o pair_1 (morphism_isomorphic +^ 1) (morphism_isomorphic +^ 1)}).\n    { srapply @equiv_functor_sigma'.\n      - exact (BuildEquiv _ _(idtoiso M (y:=g.1)) _).\n      - reflexivity.\n    } clear F.\n    srapply @equiv_functor_sigma'.\n    - srapply @equiv_adjointify.\n      + intro e. exact morphism_isomorphic.\n      + intro e. refine (Build_Isomorphic (isgroupoid_M _ _ e)).\n      + intro e. exact idpath.\n      + intro e. apply path_isomorphic. exact idpath.\n    - reflexivity.\n  Defined.\n\n  \n  Lemma path_group_completion_morph (a b : M*M) (f g : group_completion_morph a b) (alpha : f.1 --> g.1):\n    f.2 = g.2 o ((diag _1 alpha) +^+ 1) -> f = g. (* (pair_1 (alpha +^ 1) (alpha +^ 1)) *)\n  Proof.\n    intro H.\n    exact ((equiv_group_completion_morph a b f g)^-1 (alpha; H))%equiv.\n  Qed.\n  \n  (* (* The following two maps may or may not be equal to the underlying maps of [equiv_group_completion_morph] *) *)\n  (* Definition path_to_sigma {M : Symmetric_Monoidal_Category} (a b : M*M) *)\n  (*            (f g : group_completion_morph M a b) : *)\n  (*   f = g -> {alpha : f.1 --> g.1 & f.2 = g.2 o (pair_1 (alpha +^ 1) (alpha +^ 1))}. *)\n  (* Proof. *)\n  (*   intro p. *)\n  (*   destruct p. *)\n  (*   destruct a as [a1 a2]. destruct b as [b1 b2]. *)\n  (*   destruct f as [s [f1 f2]]. simpl. *)\n  (*   exists (identity s). *)\n  (*   apply inverse. *)\n  (*   refine (_ @ right_identity (M*M) _ _ (f1, f2)). *)\n  (*   apply path_prod; simpl. *)\n  (*   apply (ap (fun g => f1 o g)). apply sum_idmap. *)\n  (*   apply (ap (fun g => f2 o g)). apply sum_idmap. *)\n  (* Defined. *)\n\n  (* Definition path_grp_compl_morph {M : Symmetric_Monoidal_Category} (a b : M*M) *)\n  (*            (f g : group_completion_morph M a b) : *)\n  (*   {alpha : f.1 --> g.1 & f.2 = g.2 o (pair_1 (alpha +^ 1) (alpha +^ 1))} -> f = g. *)\n  (* Proof. *)\n  (*   destruct f as [s  f]. destruct g as [t g]. destruct a as [a1 a2]. destruct b as [b1 b2]. simpl. *)\n  (*   intros [alpha H]. *)\n  (*   srapply @path_sigma; simpl. *)\n  (*   - apply (isotoid M _ _). exact (Build_Isomorphic (isgroupoid_smon_magma M s t alpha )). *)\n  (*   - (* refine (transport_morphism_Fl (translate_fr ) ((isotoid M s t) *) *)\n  (*     (*           {| morphism_isomorphic := alpha; isisomorphism_isomorphic := isgroupoid_smon_magma M s t alpha |}) f *) *)\n  (*     (*                               @ _). *) admit. Abort. *)\n\n  \n\n  Instance isset_group_completion_morph (a b : M*M) :\n    IsHSet (group_completion_morph a b).\n  Proof.\n    intros f g. change (IsTrunc_internal (-1)) with (IsTrunc (-1)).\n    apply (trunc_equiv' {alpha : f.1 --> g.1 & f.2 = g.2 o (pair_1 (alpha +^ 1) (alpha +^ 1))}).\n     refine (equiv_inverse (equiv_group_completion_morph a b f g)).\n    destruct a as [a1 a2]. destruct b as [b1 b2].\n    destruct f as [s f]. destruct g as [t g]. (* simpl in f1, f2, g1, g2. *) simpl.\n    apply trunc_sigma'.\n    - intro alpha. exact _.\n    - intros [e H] [e' H']. simpl in e, H, e', H'. simpl.\n      apply contr_inhabited_hprop. exact _. simpl.\n      srapply @cancellation_M. exact a1.\n      destruct (H'^). clear H'.\n      destruct g as [g g']. simpl in g, g'. simpl in H.\n      pose proof (ap Datatypes.fst H) as fstH. simpl in fstH. clear H. clear g'.\n      srefine ((iso_compose_V_pp (isgroupoid_M _ _ g) _)^ @ _ @ iso_compose_V_pp (isgroupoid_M _ _ g) _).\n      rewrite fstH. exact idpath.\n  Qed.\n\n  Definition group_completion_id (m : M*M) : group_completion_morph m m.\n  Proof.\n  - exists (e M). exact (lid M (fst m), lid M (snd m)).\n  Defined.  \n  \n  Definition group_completion_compose (a b c : M*M)\n             (f : group_completion_morph b c) (g : group_completion_morph a b):\n    (* group_completion_morph b c -> group_completion_morph a b -> *)\n    group_completion_morph a c.\n  Proof.\n    (* destruct a as [a1 a2]. destruct b as [b1 b2]. destruct c as [c1 c2]. *)\n    (* intros [s f] [t [g1 g2]]. simpl in f, g1, g2. *)\n    (* intros [s f] [t g]. *)\n    exists (f.1 + g.1).    \n    refine (f.2 o _).\n    change (diag (f.1 + g.1)) with (sum2 ((f.1, f.1), (g.1, g.1))).    \n    refine (_ o assoc_sum2 _ _ _).\n    apply (morphism_of sum2). exact (1, g.2).\n  Defined.\n\n  (* Some auxiliary lemmas *)\n  Lemma comp_of_addid_fl : forall (a b c s : M) (f : a --> b) (g : b --> c),\n      (identity s) +^ (g o f) = (identity s +^ g) o (identity s +^ f).\n  Proof.\n    intros. rewrite <- composition_of. simpl. rewrite left_identity. reflexivity.\n  Qed.\n\n  Lemma comp_of_addid_fr : forall (a b c s : M) (f : a --> b) (g : b --> c),\n      (g o f) +^ (identity s) = (g +^ identity s) o (f +^ identity s).\n  Proof.\n    intros. rewrite <- composition_of. simpl. rewrite left_identity. reflexivity.\n  Qed.  \n  \n  Lemma comp_of_addid_fl_2 : forall (a b c s : (M*M)%category) (f : a --> b) (g : b --> c),\n      (identity s) +^+ (g o f) = (identity s +^+ g) o (identity s +^+ f).\n  Proof.\n    intros [a1 a2] [b1 b2] [c1 c2] [s1 s2].\n    intros [f1 f2] [g1 g2]. simpl. repeat rewrite <- comp_of_addid_fl. reflexivity.\n  Qed.\n\n  Lemma associative_group_completion :\n    forall (a b c d : (M*M)%category)\n           (f : group_completion_morph a b) (g : group_completion_morph b c) (h : group_completion_morph c d),\n      group_completion_compose a b d (group_completion_compose b c d h g) f =\n      group_completion_compose a c d h (group_completion_compose a b c g f).\n  Proof.\n    intros a b c d.\n    (* intros [r f] [s g] [t h]. *) intros f g h.\n    (* intros [a1 a2] [b1 b2] [c1 c2] [d1 d2]. *)\n    (* intros [r [f1 f2]] [s [g1 g2]] [t [h1 h2]]. simpl in f1, f2, g1, g2, h1, h2. *)\n    srapply @path_group_completion_morph. simpl.\n    - exact (assoc M h.1 g.1 f.1). \n    - change (group_completion_compose a b d (group_completion_compose b c d h g) f).2 with\n      ((h.2 o (1 +^+ g.2 o assoc_sum2 (h.1, h.1) (g.1, g.1) b)) o\n              (1 +^+ f.2 o assoc_sum2 (h.1 + g.1, h.1 + g.1) (f.1, f.1) a)).\n      change (group_completion_compose a c d h (group_completion_compose a b c g f)).2 with\n      (h.2 o (1 +^+ (g.2 o (1 +^+ f.2 o assoc_sum2 (g.1, g.1) (f.1, f.1) a)) o\n                   assoc_sum2 (h.1, h.1) (g.1 + f.1, g.1 + f.1) a)).\n      repeat rewrite associativity.\n      apply (ap (fun m => h.2 o m)).       \n      repeat rewrite comp_of_addid_fl_2.\n      repeat rewrite associativity.\n      refine (ap (fun m => (1 +^+ g.2)  o m) _).\n      (* The nice way to do this is to show that M acts on M*M coherently, but we do it quick and ugly. *)\n      destruct a as [a1 a2]. destruct b as [b1 b2]. destruct c as [c1 c2].\n      destruct f as [r [f1 f2]]. destruct g as [s [g1 g2]]. destruct h as [t [h1 h2]].\n      simpl in f1, f2, g1, g2, h1, h2.\n      transitivity (pair_1 ((1 +^ (1 +^ f1)) o (assoc M t s (r + a1) o assoc M (t + s) r a1))\n                           ((1 +^ (1 +^ f2)) o (assoc M t s (r + a2) o assoc M (t + s) r a2))); simpl; unfold pair_1.\n      { rewrite <- sum_idmap. repeat rewrite <- associativity. repeat rewrite natural_assoc. reflexivity. }\n      { unfold pair_1. repeat rewrite coh_pent. repeat rewrite <- associativity. reflexivity. }\n  Qed.\n\n  Lemma left_id_group_completion : \n    forall (a b : (M * M)%category) (f : group_completion_morph a b),\n      group_completion_compose a b b (group_completion_id b) f = f.\n  Proof.\n    intros [a1 a2] [b1 b2]. intros [s [f1 f2]].\n    srapply @path_group_completion_morph.\n    - simpl. apply lid.\n    - simpl. repeat rewrite <- associativity.\n      repeat rewrite natural_lid. repeat rewrite associativity.\n      repeat rewrite coh_lid_assoc_lid.  reflexivity.\n  Qed.\n\n  Lemma right_id_group_completion :\n    forall (a b : (M * M)%category) (f : group_completion_morph a b),\n      group_completion_compose a a b f (group_completion_id a) = f.\n  Proof.\n    intros [a1 a2] [b1 b2]. intros [s [f1 f2]].\n    srapply @path_group_completion_morph.\n    - simpl. apply rid.\n    - simpl. repeat rewrite coh_tri. reflexivity.\n  Qed.\n      \n\n  (* The object [(a, b)] represents the difference [a-b]. *)\n  Definition group_completion_cat : PreCategory :=\n    Build_PreCategory (group_completion_morph) group_completion_id\n                      group_completion_compose associative_group_completion\n                      left_id_group_completion\n                      right_id_group_completion _.\n\n  (* The functor sending object [a] to [a-0] *)\n  Definition to_group_completion : Functor M group_completion_cat.\n  Proof.\n    srapply @Build_Functor; repeat change Core.object with object.\n    (* Map on objects *)\n    - intro a. exact (a, e M).\n    (* Map on arrows *)\n    - intros a b f. simpl.\n      exists (e M). split; simpl.\n      exact (f o lid M a). apply lid.\n    (* Respects composition *)\n    - intros a b c f g. simpl.\n      srapply @path_group_completion_morph.\n      + simpl. exact (lid M (e M))^-1.\n      + simpl. (* Follows from coherence, but here is a proof. *)\n        apply path_prod; simpl.\n        * repeat rewrite associativity.\n          refine (ap (fun h => g o h) _).\n          repeat rewrite <- associativity.\n          rewrite natural_lid. repeat rewrite associativity.\n          refine (ap (fun h => f o h) _).\n          transitivity (lid M a o 1). rewrite right_identity. reflexivity.\n          refine (ap (fun h => (lid M a) o h) _).\n          repeat rewrite <- associativity.\n          rewrite coh_lid_assoc_lid.\n          rewrite <- composition_of. simpl.\n          rewrite right_inverse. rewrite right_identity. rewrite identity_of. reflexivity.\n        * (* rewrite natural_lid. *)\n          repeat rewrite <- associativity. rewrite natural_lid. repeat rewrite associativity.\n          transitivity (lid M (e M) o 1). rewrite right_identity. reflexivity.\n          refine (ap (fun h => (lid M (e M) o h)) _). repeat rewrite <- associativity.\n          rewrite coh_lid_assoc_lid. rewrite <- composition_of. simpl. rewrite right_inverse.\n          rewrite right_identity. rewrite identity_of. reflexivity.\n    (* Respects identity  *)\n    - intro a. simpl. unfold group_completion_id. simpl. rewrite left_identity. reflexivity.\n  Defined.      \n\n  Definition group_completion_sum : Functor (group_completion_cat * group_completion_cat) group_completion_cat.\n  Proof.\n    srapply @Build_Functor; change Core.object with object.\n    (* Map on objects *)\n    - (* [a1 - a2] and [b1 - b2] goes to [(a1 + a2) - (b1 + b2) *)\n      apply sum2.\n    (* Map on morphisms *)\n    - \n      intros [a a'] [b b']. intros [[s f] [s' f']]. simpl in a, a', b, b'.\n      unfold Datatypes.fst in f. unfold Datatypes.snd in f'.\n      (* intros [[s [f1 f2]] [t [g1 g2]]]. *)\n      exists (s + s').\n      refine (sum2 _1 (pair_1 f f') o _). change (Core.object_of sum2) with (object_of sum2).\n      (* change ((sum2 o (diag, 1))%functor (s + t, sum2 (a, b))) with (sum2 (diag (s + t), sum2 (a, b))). *)\n      (* change (Core.object_of sum2 ((sum2 o (diag, 1))%functor (s, a), (sum2 o (diag, 1))%functor (t, b))) with *)\n      (*        (sum2 (sum2 (diag s, a), sum2 (diag t, b))). *)\n      change (diag (s + s')) with (sum2 (diag s, diag s')).\n      refine ((assoc_sum2 _ _ _)^-1  o _ o assoc_sum2 _ _ _).\n      refine (1 +^+ _).\n      refine (assoc_sum2 _ _ _ o _ o (assoc_sum2 _ _ _)^-1).\n      refine (_ +^+ 1). \n      (* It is more general that the product inherits symmetry, but. . . *)\n      exact (pair_1 (symm M _ _) (symm M _ _)).\n    (* Respect composition *)\n    - (* I have half a proof on paper (ignoring associativity), but I do not want to implement it for now.*)\n      admit.\n      (* simpl. *)\n      (* (* intros [a a'] [b b'] [c c']. *) *)\n      (* intros [[a_p a_n] [a_p' a_n']] [[b_p b_n] [b_p' b_n']] [[c_p c_n] [c_p' c_n']]. *)\n      (* (* intros [[s f] [s' f']]  [[t g] [t' g']]. *) *)\n      (* intros [[s [f_p f_n]] [s' [f_p' f_n']]]  [[t [g_p g_n]] [t' [g_p' g_n']]]. *)\n      (* simpl in f_p, f_n, f_p', f_n', g_p, g_n, g_p', g_n'. simpl. unfold group_completion_compose. simpl. *)\n      (* srapply @path_group_completion_morph. *)\n      (* + simpl. *)\n      (*   refine ((assoc M _ _ _)^-1 o _ o assoc M _ _ _). *)\n      (*   refine (1 +^ _). *)\n      (*   refine (assoc M _ _ _ o _ o (assoc M _ _ _)^-1). *)\n      (*   refine (_ +^ 1). *)\n      (*   apply symm. *)\n      (* + apply path_prod ; simpl. *)\n      (*   * *)\n      (*     (* Don't know why [rewrite <- (composition_of binary_op)] doesn't work directly. . . *) *)\n      (*     assert (comp_of_binary_op : forall (a a' b b' c c' : M) (f : b --> c) (f' : b' --> c') (g : a --> b) (g' : a' --> b'), *)\n      (*                (f o g) +^ (f' o g') = (f +^ f') o (g +^ g')). *)\n      (*     { intros. rewrite <- (composition_of binary_op). simpl. reflexivity. } *)\n      (*     rewrite comp_of_binary_op. repeat rewrite associativity. *)\n      (*     refine (ap (fun f => (g_p +^ g_p') o f) _). *)\n      (*     rewrite comp_of_binary_op.  *)\n      (*     repeat rewrite comp_of_addid_fl. repeat rewrite comp_of_addid_fr. repeat rewrite associativity. *)\n      (*     repeat rewrite <- comp_of_addid_fl. admit. *)\n      (*     * admit. *)\n    (* Respect identity *)\n    - simpl. intros [[a a'] [b b']]. simpl.\n      srapply @path_group_completion_morph.\n      + simpl. apply lid.\n      + simpl. repeat rewrite associativity. admit. (* Coherence *)\n  Admitted.\n\n  (* TODO: Make a section with assumptions that follow from coherence, at use it liberally. *)\n\n  Definition group_completion_moncat : Symmetric_Monoidal_Category.\n    srapply (@Build_Symmetric_Monoidal_Category (Build_Magma group_completion_cat group_completion_sum)\n            (e M, e M)).\n           \n          \n        \n        \n      \n      \n  \nEnd Group_Completion.  \n ", "meta": {"author": "kalfsvag", "repo": "misc_coq", "sha": "9886ed4eb3dfc077afd1d769c910a729475fa173", "save_path": "github-repos/coq/kalfsvag-misc_coq", "path": "github-repos/coq/kalfsvag-misc_coq/misc_coq-9886ed4eb3dfc077afd1d769c910a729475fa173/misc/oldmonoidalcategory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2738187586669416}}
{"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 Coq.Program.Equality.\nRequire Import Definitions Binding.\n\n(** * Record Types *)\n\n(** A record declaration is either a type declaration with equal bounds,\n    or a field declaration.*)\nInductive record_dec : dec -> Prop :=\n| rd_typ : forall A T, record_dec (dec_typ A T T)\n| rd_trm : forall a T, record_dec (dec_trm a T).\n\n(** Given a record declaration, a [record_typ] keeps track of the declaration's\n    field member labels (i.e. names of fields) and type member labels\n    (i.e. names of abstract type members). [record_typ] also requires that the\n    labels are distinct.  *)\nInductive record_typ : typ -> fset label -> Prop :=\n| rt_one : forall D l,\n  record_dec D ->\n  l = label_of_dec D ->\n  record_typ (typ_rcd D) \\{l}\n| rt_cons: forall T ls D l,\n  record_typ T ls ->\n  record_dec D ->\n  l = label_of_dec D ->\n  l \\notin ls ->\n  record_typ (typ_and T (typ_rcd D)) (union ls \\{l}).\n\n(** A [record_type] is a [record_typ] with an unspecified set of labels. The meaning\n    of [record_type] is an intersection of type/field declarations with distinct labels. *)\nDefinition record_type T := exists ls, record_typ T ls.\n\n(** Given a type [T = D1 /\\ D2 /\\ ... /\\ Dn] and member declaration [D], [record_has T D] tells whether\n    [D] is contained in the intersection of [Di]'s. *)\nInductive record_has: typ -> dec -> Prop :=\n| rh_one : forall D,\n    record_has (typ_rcd D) D\n| rh_andl : forall T U D,\n    record_has T D ->\n    record_has (typ_and T U) D\n| rh_andr : forall T U D,\n    record_has U D ->\n    record_has (typ_and T U) D.\n\nHint Constructors record_typ record_has.\n\n(** ** Lemmas About Records and Record Types *)\n\n(** [G ⊢ ds :: U]                          #<br>#\n    [U] is a record type with labels [ls]  #<br>#\n    [ds] are definitions with label [ls']  #<br>#\n    [l \\notin ls']                          #<br>#\n    [―――――――――――――――――――――――――――――――――――]  #<br>#\n    [l \\notin ls] *)\nLemma hasnt_notin : forall G ds ls l U,\n    G /- ds :: U ->\n    record_typ U ls ->\n    defs_hasnt ds l ->\n    l \\notin ls.\nProof.\n\n  Ltac inversion_def_typ :=\n    match goal with\n    | [ H: _ /- _ : _ |- _ ] => inversions H\n    end.\n\n  introv Hds Hrec Hhasnt.\n  inversions Hhasnt. gen ds. induction Hrec; intros; inversions Hds.\n  - inversion_def_typ; simpl in *; case_if; apply* notin_singleton.\n  - apply notin_union; split; simpl in *.\n    + apply* IHHrec. case_if*.\n    + inversion_def_typ; case_if; apply* notin_singleton.\nQed.\n\n(** [labels(D) = labels(D^x)] *)\nLemma open_dec_preserves_label: forall D x i,\n  label_of_dec (open_rec_dec i x D) = label_of_dec D.\nProof.\n  intros. induction D; reflexivity.\nQed.\n\n(** [record_dec D]   #<br>#\n    [――――――――――――――] #<br>#\n    [record_dec D^x] *)\nLemma open_record_dec: forall D x,\n  record_dec D -> record_dec (open_dec x D).\nProof.\n  intros. inversion H; unfold open_dec; constructor.\nQed.\n\n(** [record_typ T]   #<br>#\n    [――――――――――――――] #<br>#\n    [record_typ T^x] *)\nLemma open_record_typ: forall T x ls,\n  record_typ T ls -> record_typ (open_typ x T) ls.\nProof.\n  introv H.\n  induction H; unfold open_typ; simpl;\n    [apply rt_one | apply rt_cons];\n    try apply open_record_dec ; try rewrite open_dec_preserves_label;\n    assumption.\nQed.\n\n(** [record_typ T]   #<br>#\n    [――――――――――――――] #<br>#\n    [record_typ T^x] *)\nLemma open_record_type: forall T x,\n  record_type T -> record_type (open_typ x T).\nProof.\n  introv [ls H]. exists ls. apply open_record_typ.\n  assumption.\nQed.\n\n(** The type of definitions is a record type. *)\nLemma ty_defs_record_type : forall G ds T,\n    G /- ds :: T ->\n    record_type T.\nProof.\n intros. induction H; destruct D;\n    repeat match goal with\n        | [ H: record_type _ |- _ ] =>\n          destruct H\n        | [ Hd: _ /- _ : dec_typ _ _ _ |- _ ] =>\n          inversions Hd\n        | [ Hd: _ /- _ : dec_trm _ _ |- _ ] =>\n          inversions Hd\n    end;\n    match goal with\n    | [ ls: fset label,\n        t: trm_label |- _ ] =>\n      exists (ls \\u \\{ label_trm t })\n    | [ ls: fset label,\n        t: typ_label |- _ ] =>\n      exists (ls \\u \\{ label_typ t })\n    | [ t: trm_label |- _ ] =>\n      exists \\{ label_trm t }\n    | [ t: typ_label |- _ ] =>\n      exists \\{ label_typ t }\n    end;\n    constructor*; try constructor; apply (hasnt_notin H); eauto.\nQed.\n\n(** Opening does not affect the labels of a [record_typ]. *)\nLemma opening_preserves_labels : forall z T ls ls',\n    record_typ T ls ->\n    record_typ (open_typ z T) ls' ->\n    ls = ls'.\nProof.\n  introv Ht Hopen. gen ls'.\n  dependent induction Ht; intros.\n  - inversions Hopen. rewrite* open_dec_preserves_label.\n  - inversions Hopen. rewrite* open_dec_preserves_label.\n    specialize (IHHt ls0 H4). rewrite* IHHt.\nQed.\n\n(** Opening does not affect the labels of a [record_type]. *)\nLemma record_type_open : forall z T,\n    z \\notin fv_typ T ->\n    record_type (open_typ z T) ->\n    record_type T.\nProof.\n  introv Hz H. destruct H. dependent induction H.\n  - exists \\{ l }. destruct T; inversions x. constructor.\n    + destruct d; inversions H.\n      * apply (proj21 open_fresh_typ_dec_injective) in H3.\n        { subst. constructor. }\n        { simpl in Hz; auto. }\n        { simpl in Hz; auto. }\n      * constructor.\n    + destruct d; inversions H.\n      * apply (proj21 open_fresh_typ_dec_injective) in H3.\n        { subst. constructor. }\n        { simpl in Hz; auto. }\n        { simpl in Hz; auto. }\n      * constructor.\n  - destruct T; inversions x. simpl in Hz.\n    assert (Hz': z \\notin fv_typ T1) by auto.\n    destruct (IHrecord_typ T1 z Hz' eq_refl) as [ls' ?]. clear Hz'.\n    destruct T2; inversions H5.\n    destruct d; inversions H0.\n    + exists (ls' \\u \\{ label_typ t }). apply (proj21 open_fresh_typ_dec_injective) in H6.\n      * subst. constructor*.\n        { constructor. }\n        {\n          simpl in H2. pose proof (opening_preserves_labels z H1 H).\n          rewrite* H0.\n        }\n      * simpl in Hz; auto.\n      * simpl in Hz; auto.\n    + exists (ls' \\u \\{ label_trm t }). constructor*.\n      * constructor.\n      * simpl in H2. pose proof (opening_preserves_labels z H1 H).\n        rewrite* H0.\nQed.\n\n(** If [T] is a record type with labels [ls], and [T = ... /\\ D /\\ ...],\n    then [label(D) isin ls]. *)\nLemma record_typ_has_label_in: forall T D ls,\n  record_typ T ls ->\n  record_has T D ->\n  label_of_dec D \\in ls.\nProof.\n  introv Htyp Has. generalize dependent D. induction Htyp; intros.\n  - inversion Has. subst. apply in_singleton_self.\n  - inversion Has; subst; rewrite in_union.\n    + left. apply* IHHtyp.\n    + right. inversions H5. apply in_singleton_self.\nQed.\n\n(** [T = ... /\\ {A: T1..T1} /\\ ...] #<br>#\n    [T = ... /\\ {A: T2..T2} /\\ ...] #<br>#\n    [―――――――――――――――――――――――――――] #<br>#\n    [T1 = T2] *)\nLemma unique_rcd_typ: forall T A T1 T2,\n  record_type T ->\n  record_has T (dec_typ A T1 T1) ->\n  record_has T (dec_typ A T2 T2) ->\n  T1 = T2.\nProof.\n  introv Htype Has1 Has2.\n  generalize dependent T2. generalize dependent T1. generalize dependent A.\n  destruct Htype as [ls Htyp]. induction Htyp; intros; inversion Has1; inversion Has2; subst.\n  - inversion* H3.\n  - inversion* H5.\n  - apply record_typ_has_label_in with (D:=dec_typ A T1 T1) in Htyp.\n    + inversions H9. false* H1.\n    + assumption.\n  - apply record_typ_has_label_in with (D:=dec_typ A T2 T2) in Htyp.\n    + inversions H5. false* H1.\n    + assumption.\n  - inversions H5. inversions* H9.\nQed.\n\n(** [ds = ... /\\ {a = t} /\\ ...]  #<br>#\n    [ds = ... /\\ {a = t'} /\\ ...] #<br>#\n    [―――――――――――――――――――――――――] #<br>#\n    [t = t'] *)\nLemma defs_has_inv: forall ds a t t',\n    defs_has ds (def_trm a t) ->\n    defs_has ds (def_trm a t') ->\n    t = t'.\nProof.\n  intros. unfold defs_has in *.\n  inversions H. inversions H0.\n  rewrite H1 in H2. inversions H2.\n  reflexivity.\nQed.\n\n\n(** * Inert types\n       A type is inert if it is either a dependent function type, or a recursive type\n       whose type declarations have equal bounds (enforced through [record_type]). #<br>#\n       For example, the following types are inert:\n       - [lambda(x: S)T]\n       - [mu(x: {a: T} /\\ {B: U..U})]\n       - [mu(x: {C: {A: T..U}..{A: T..U}})]\n       And the following types are not inert:\n       - [{a: T}]\n       - [{B: U..U}]\n       - [top]\n       - [x.A]\n       - [mu(x: {B: S..T})], where [S <> T]. *)\nInductive inert_typ : typ -> Prop :=\n  | inert_typ_all : forall S T, inert_typ (typ_all S T)\n  | inert_typ_bnd : forall T,\n      record_type T ->\n      inert_typ (typ_bnd T).\n\n(** An inert context is a typing context whose range consists only of inert types. *)\nInductive inert : ctx -> Prop :=\n  | inert_empty : inert empty\n  | inert_all : forall G x T,\n      inert G ->\n      inert_typ T ->\n      x # G ->\n      inert (G & x ~ T).\n\n(** In the proof, it is useful to be able to distinguish record types from\n    other types. A record type is a concatenation of type declarations with equal\n    bounds [{A: T..T}] and field declarations [{a: T}]. *)\n\nHint Constructors inert_typ inert.\n\nLemma inert_concat: forall G' G,\n    inert G ->\n    inert G' ->\n    ok (G & G') ->\n    inert (G & G').\nProof.\n  induction G' using env_ind; introv Hg Hg' Hok.\n  - rewrite* concat_empty_r.\n  - rewrite concat_assoc.\n    inversions Hg'; inversions Hok;\n      rewrite concat_assoc in *; try solve [false* empty_push_inv].\n    destruct (eq_push_inv H) as [Heq1 [Heq2 Heq3]]; subst.\n    destruct (eq_push_inv H3) as [Heq1 [Heq2 Heq3]]; subst.\n    apply inert_all; auto.\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/RecordAndInertTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2738187510793438}}
{"text": "Require Export RecTypes.SpecTypes.\nRequire Export RecTypes.InstTy.\nRequire Export RecTypes.LemmasTypes.\n\nRequire Import StlcIso.SpecEvaluation.\nRequire Import StlcIso.SpecSyntax.\nRequire Import StlcIso.SpecTyping.\nRequire Import StlcIso.LemmasTyping.\nRequire Import StlcIso.LemmasEvaluation.\nRequire Import StlcIso.CanForm.\nRequire Import StlcIso.Fix.\nRequire Import StlcIso.Size.\nRequire Import StlcIso.TypeSafety.\nRequire Import StlcFix.SpecEvaluation.\nRequire Import StlcFix.SpecSyntax.\nRequire Import StlcFix.SpecTyping.\nRequire Import StlcFix.SpecAnnot.\nRequire Import StlcFix.LemmasTyping.\nRequire Import StlcFix.LemmasEvaluation.\nRequire Import StlcFix.CanForm.\nRequire Import StlcFix.Size.\nRequire Import StlcFix.StlcOmega.\nRequire Import StlcFix.TypeSafety.\nRequire Import Common.Relations.\n\nModule F.\n  Include StlcFix.SpecEvaluation.\n  Include StlcFix.SpecSyntax.\n  Include StlcFix.SpecTyping.\n  Include StlcFix.SpecAnnot.\n  Include StlcFix.LemmasTyping.\n  Include StlcFix.LemmasEvaluation.\n  Include StlcFix.CanForm.\n  Include StlcFix.Size.\n  Include StlcFix.TypeSafety.\nEnd F.\n\nModule I.\n  Include RecTypes.SpecTypes.\n  Include RecTypes.InstTy.\n  Include RecTypes.LemmasTypes.\n\n  Include StlcIso.SpecEvaluation.\n  Include StlcIso.SpecSyntax.\n  Include StlcIso.SpecTyping.\n  Include StlcIso.LemmasTyping.\n  Include StlcIso.LemmasEvaluation.\n  Include StlcIso.CanForm.\n  Include StlcIso.Fix.\n  Include StlcIso.Size.\n  Include StlcIso.TypeSafety.\nEnd I.\n\nDefinition UValFI' := fun (S : I.Ty -> F.Ty) (τ : I.Ty) =>\n  let τl := match τ with\n            | I.tunit => F.tunit\n            | I.tbool => F.tbool\n            | I.tarr τ1 τ2 as τ => F.tarr (S τ1) (S τ2)\n            | I.tprod τ1 τ2 as τ => F.tprod (S τ1) (S τ2)\n            | I.tsum τ1 τ2 =>\n              let σ1 := S τ1 in\n              let σ2 := S τ2 in\n              F.tsum σ1 σ2\n            | I.trec τ => S τ[beta1 (I.trec τ)]\n            | I.tvar i => F.tunit\n            end\n  in F.tsum τl F.tunit.\n\nArguments UValFI'/ S τ.\n\nFixpoint UValFI (n : nat) (τ : I.Ty) {struct n} : F.Ty :=\n  match n with\n    | 0 => F.tunit\n    | S n => UValFI' (UValFI n) τ\n  end.\n\nArguments UValFI !n !τ.\n\nDefinition unkUVal (n : nat) : F.Tm :=\n  match n with\n  | 0 => F.unit\n  | _ => F.inr F.unit\n  end.\n\nDefinition unkUValA (n : nat) (τ : I.Ty) : F.TmA :=\n  match n with\n  | 0 => F.a_unit\n  | (S n) => F.a_inr (match τ with\n      | I.tunit => F.tunit\n      | I.tbool => F.tbool\n      | I.tarr τ1 τ2 as τ => F.tarr (UValFI n τ1) (UValFI n τ2)\n      | I.tprod τ1 τ2 as τ => F.tprod (UValFI n τ1) (UValFI n τ2)\n      | I.tsum τ1 τ2 =>\n        let σ1 := UValFI n τ1 in\n        let σ2 := UValFI n τ2 in\n        F.tsum σ1 σ2\n      | I.trec τ => UValFI n τ[beta1 (I.trec τ)]\n      | I.tvar i => F.tunit\n      end) F.tunit F.a_unit\n  end.\n\nLemma unkUVal_unkUValA {n τ} : unkUVal n = eraseAnnot (unkUValA n τ).\nProof.\n  destruct n;\n  now cbn.\nQed.\n\nLemma unkUVal_Value (n : nat) : F.Value (unkUVal n).\nProof.\n  case n; simpl; trivial.\nQed.\n\nLemma unkUValT {Γ n τ} : F.Typing Γ (unkUVal n) (UValFI n τ).\nProof.\n  induction n;\n  eauto using F.Typing.\nQed.\n\nLemma unkUValAT {Γ n τ} : F.AnnotTyping Γ (unkUValA n τ) (UValFI n τ).\nProof.\n  induction n;\n  eauto using F.AnnotTyping.\nQed.\n\n#[export]\nHint Resolve unkUValT : uval_typing.\n#[export]\nHint Resolve unkUValAT : uval_typing.\n\n(* Definition constr_uvalfi {Γ} (n : nat) (τ : I.Ty) (t : F.Tm) {P : ClosedTy τ} {Q : F.Typing Γ t (@UValFI n τ P)} : F.Tm := *)\n(*   F.inl t. *)\n\n(* Definition inUnit_pctx (n : nat) := pinr (pinl phole). *)\n(* Definition inUnit (n : nat) (t : Tm) := pctx_app t (inUnit_pctx n). *)\n(* Arguments inUnit_pctx / n. *)\n\n(* Lemma inUnit_Value {n v} : Value v → Value (inUnit n v). *)\n(* Proof. *)\n(*   simpl; trivial. *)\n(* Qed. *)\n\n(* Lemma inUnit_pctx_T {Γ n} : ⟪Unit_pctx n : Γ , tunit → Γ , UVal (S n) ⟫. *)\n(* Proof. *)\n(*   unfold inUnit_pctx. crushTyping. *)\n(* Qed. *)\n\nLemma inUnitT {Γ n t} : ⟪ Γ ⊢ t : F.tunit ⟫ → ⟪ Γ ⊢ F.inl t : UValFI (S n) I.tunit ⟫.\nProof.\n  intuition.\nQed.\n\n(* Arguments inUnit n t : simpl never. *)\n\nDefinition inBool_pctx (n : nat) : PCtx := pinl phole.\nDefinition inBool (n : nat) (t : Tm): Tm := pctx_app t (inBool_pctx n).\n\nArguments inBool_pctx /n.\n\nLemma inBool_pctx_T {Γ n} : ⟪ ⊢ inBool_pctx n : Γ , tbool → Γ , UValFI (S n) I.tbool ⟫.\nProof.\n  unfold inBool_pctx. unfold UValFI. crushTyping.\nQed.\n\nLemma inBoolT {Γ n t} : ⟪ Γ ⊢ t : tbool ⟫ → ⟪ Γ ⊢ inBool n t : UValFI (S n) I.tbool ⟫.\nProof.\n  unfold inBool. eauto using inBool_pctx_T with typing.\nQed.\n\nLemma inBool_Value {n v} : Value v → Value (inBool n v).\nProof.\n  simpl; trivial.\nQed.\n\nDefinition inProd_pctx (n : nat) : PCtx := pinl phole.\nDefinition inProd (n : nat) (t : Tm) : Tm := pctx_app t (inProd_pctx n).\n\nLemma inProd_pctx_T {Γ n τ₁ τ₂} : ⟪ ⊢ inProd_pctx n : Γ , UValFI n τ₁ × UValFI n τ₂ → Γ , UValFI (S n) (I.tprod τ₁ τ₂)⟫.\nProof.\n  unfold inProd_pctx. crushTyping.\nQed.\n\nLemma inProd_T {Γ n t τ₁ τ₂} : ⟪ Γ ⊢ t : UValFI n τ₁ × UValFI n τ₂ ⟫ → ⟪ Γ ⊢ inProd n t : UValFI (S n) (I.tprod τ₁ τ₂) ⟫.\nProof.\n  unfold inProd. eauto using inProd_pctx_T with typing.\nQed.\n\nLemma inProd_Value {n v} : Value v → Value (inProd n v).\nProof.\n  simpl; trivial.\nQed.\n\n(* Definition inArr_pctx (n : nat) : PCtx := pinr (pinr (pinr (pinr (pinl phole)))). *)\n(* Definition inArr (n : nat) (t : Tm) : Tm := pctx_app t (inArr_pctx n). *)\n\n(* Arguments inArr_pctx / n. *)\n\n(* Lemma inArr_pctx_T {Γ n} : ⟪ ⊢ inArr_pctx n : Γ , UValFI n ⇒ UValFI n → Γ , UValFI (S n) ⟫. *)\n(* Proof. *)\n(*   unfold inArr_pctx. crushTyping. *)\n(* Qed. *)\n\nLemma inArr_T {Γ n t τ τ'} : ⟪ Γ ⊢ t : F.tarr (UValFI n τ) (UValFI n τ') ⟫ → ⟪ Γ ⊢ F.inl t : UValFI (S n) (I.tarr τ τ') ⟫.\nProof.\n  intuition.\nQed.\n\n(* Lemma inArr_Value {n v} : Value v → Value (inArr n v). *)\n(* Proof. *)\n(*   simpl; trivial. *)\n(* Qed. *)\n\n(* Definition inSum_pctx (n : nat) : PCtx := pinr (pinr (pinr (pinr (pinr phole)))). *)\n(* Definition inSum (n : nat) (t : Tm) : Tm := pctx_app t (inSum_pctx n). *)\n\n(* Lemma inSum_pctx_T {Γ n} : ⟪ ⊢ inSum_pctx n : Γ , UVal n ⊎ UVal n → Γ , UVal (S n) ⟫. *)\n(* Proof. *)\n(*   unfold inSum_pctx. crushTyping. *)\n(* Qed. *)\n\nLemma inSum_T {Γ n t τ τ'} : ⟪ Γ ⊢ t : F.tsum (UValFI n τ) (UValFI n τ') ⟫ → ⟪ Γ ⊢ F.inl t : UValFI (S n) (I.tsum τ τ') ⟫.\nProof.\n  intuition.\nQed.\n\n(* Lemma inSum_Value {n v} : Value v → Value (inSum n v). *)\n(* Proof. *)\n(*   simpl; trivial. *)\n(* Qed. *)\n\n(* (t : F.Tm) {P : F.Typing t (UValFI n I.tunit)} : F.Tm := *)\nDefinition case_uvalfi_unit (n : nat) : F.Tm :=\n  let τ := UValFI (S n) I.tunit in\n  let t := F.caseof (F.var 0) (F.var 0) (F.Om F.tunit) in\n  F.abs τ t.\n\nDefinition case_uvalfi_arr (n : nat) (τ1 τ2 : I.Ty) : F.Tm :=\n  let τ := @UValFI (S n) (I.tarr τ1 τ2) in\n  let τ' := F.tarr (UValFI n τ1) (UValFI n τ2) in\n  let t := F.caseof (F.var 0) (F.var 0) (F.Om τ') in\n  F.abs τ t.\n\nLemma uvalfi_expand_arr {n τ1 τ2} :\n  UValFI (S n) (I.tarr τ1 τ2) = F.tsum (F.tarr (UValFI n τ1) (UValFI n τ2)) F.tunit.\nProof.\n  reflexivity.\nQed.\n\nLemma case_uval_arr_typing {Γ n τ1 τ2} :\n  let τ := I.tarr τ1 τ2 in\n  let uval_dest := case_uvalfi_arr n τ1 τ2 in\n  let arg_type := UValFI (S n) τ in\n  let ret_type := F.tarr (UValFI n τ1) (UValFI n τ2) in\n  let type := F.tarr arg_type ret_type in\n  F.Typing Γ uval_dest type.\nProof.\n  intros.\n  unfold uval_dest.\n  unfold type.\n  unfold arg_type.\n  unfold ret_type.\n  (* unfold uval_dest, arg_type, ret_type, type, case_uvalfi_arr. *)\n  (* crushTyping. *)\n  constructor.\n  unfold τ.\n  apply (@F.WtCaseof (F.evar Γ arg_type) (F.var 0) (F.var 0) (F.Om ret_type) ret_type F.tunit ret_type).\n  unfold arg_type.\n  unfold ret_type.\n  constructor.\n  simpl.\n  constructor.\n  constructor.\n  constructor.\n  apply wtOm_tau.\nQed.\n\n\nDefinition case_uvalfi_tsum (n : nat) (τ1 τ2 : I.Ty) : F.Tm :=\n  let τ := UValFI (S n) (I.tsum τ1 τ2) in\n  let τ' := F.tsum (UValFI n τ1) (@UValFI n τ2) in\n  let t := F.caseof (F.var 0) (F.var 0) (F.Om τ') in\n  F.abs τ t.\n\nDefinition case_uvalfi_trec (n : nat) (τb : I.Ty) : F.Tm :=\n  let τ_rec := I.trec τb in\n  let τ := UValFI (S n) τ_rec in\n  let τ' := UValFI n τb[beta1 τ_rec] in\n  let t := F.caseof (F.var 0) (F.var 0) (F.Om τ') in\n  F.abs τ t.\n\nDefinition caseV0 (case₁ : F.Tm) (case₂ : F.Tm) : F.Tm :=\n  F.caseof (F.var 0) (case₁ [wkm↑]) (case₂[wkm↑]).\n\nLemma caseV0_T {Γ : F.Env} {τ₁ τ₂ τ : F.Ty} {case₁ case₂ : F.Tm} :\n  F.Typing (F.evar Γ τ₁) case₁ τ →\n  F.Typing (F.evar Γ τ₂) case₂ τ →\n  F.Typing (F.evar Γ (F.tsum τ₁ τ₂)) (caseV0 case₁ case₂) τ.\nProof.\n  unfold caseV0.\n  F.crushTyping.\nQed.\n\n#[export]\nHint Resolve caseV0_T : uval_typing.\n\nDefinition caseUVal_pctx (τ : F.Ty) := F.pcaseof₁ F.phole (F.var 0) (stlcOmega τ).\nDefinition caseUVal_pctxA (τ : F.Ty) := F.a_pcaseof₁ τ F.tunit τ F.a_phole (F.a_var 0) (stlcOmegaA τ).\n\nDefinition caseUnit_pctx := caseUVal_pctx F.tunit.\nDefinition caseUnit_pctxA (n : nat) := caseUVal_pctxA F.tunit.\nDefinition caseBool_pctx := caseUVal_pctx F.tbool.\nDefinition caseBool_pctxA (n : nat) := caseUVal_pctxA F.tbool.\nDefinition caseProd_pctx (n : nat) (τ1 τ2 : I.Ty) := caseUVal_pctx (F.tprod (UValFI n τ1) (UValFI n τ2)).\nDefinition caseProd_pctxA (n : nat) (τ1 τ2 : I.Ty) := caseUVal_pctxA (F.tprod (UValFI n τ1) (UValFI n τ2)).\nDefinition caseSum_pctx (n : nat) (τ1 τ2 : I.Ty) := caseUVal_pctx (F.tsum (UValFI n τ1) (UValFI n τ2)).\nDefinition caseSum_pctxA (n : nat) (τ1 τ2 : I.Ty) := caseUVal_pctxA (F.tsum (UValFI n τ1) (UValFI n τ2)).\nDefinition caseArr_pctx (n : nat) (τ1 τ2 : I.Ty) := caseUVal_pctx (F.tarr (UValFI n τ1) (UValFI n τ2)).\nDefinition caseArr_pctxA (n : nat) (τ1 τ2 : I.Ty) := caseUVal_pctxA (F.tarr (UValFI n τ1) (UValFI n τ2)).\nDefinition caseRec_pctx (n : nat) (τ : I.Ty) := caseUVal_pctx (UValFI n τ[beta1 (I.trec τ)]).\nDefinition caseRec_pctxA (n : nat) (τ : I.Ty) := caseUVal_pctxA (UValFI n τ[beta1 (I.trec τ)]).\n\nDefinition caseUVal (τ : F.Ty) (t : F.Tm) := F.pctx_app t (caseUVal_pctx τ).\nDefinition caseUValA (τ : F.Ty) (t : F.TmA) := F.pctxA_app t (caseUVal_pctxA τ).\n\n(* Definition caseUValIso (n : nat) (τ : I.Ty) (t : F.Tm) := caseUVal (UValFI n τ) t. *)\n(* Definition caseUValIsoA (n : nat) (τ' τ : I.Ty) (t : F.Tm) := caseUVal (UValFI n τ) t. *)\n\nArguments caseUVal_pctx τ : simpl never.\nArguments caseUVal τ t : simpl never.\n\nDefinition caseUnit t := F.pctx_app t caseUnit_pctx.\nDefinition caseUnitA n t := F.pctxA_app t (caseUnit_pctxA n).\nDefinition caseBool t := F.pctx_app t caseBool_pctx.\nDefinition caseBoolA n t := F.pctxA_app t (caseBool_pctxA n).\nDefinition caseSum n t τ1 τ2 := F.pctx_app t (caseSum_pctx n τ1 τ2).\nDefinition caseSumA n t τ1 τ2 := F.pctxA_app t (caseSum_pctxA n τ1 τ2).\nDefinition caseProd n t τ1 τ2 := F.pctx_app t (caseProd_pctx n τ1 τ2).\nDefinition caseProdA n t τ1 τ2 := F.pctxA_app t (caseProd_pctxA n τ1 τ2).\nDefinition caseArr n t τ1 τ2 := F.pctx_app t (caseArr_pctx n τ1 τ2).\nDefinition caseArrA n t τ1 τ2 := F.pctxA_app t (caseArr_pctxA n τ1 τ2).\nDefinition caseRec n t τ := F.pctx_app t (caseRec_pctx n τ).\nDefinition caseRecA n t τ := F.pctxA_app t (caseRec_pctxA n τ).\n\nLemma caseUnit_pctx_T {Γ n} :\n  ⟪ ⊢ caseUnit_pctx : Γ, UValFI (S n) I.tunit → Γ, F.tunit ⟫.\nProof.\n  unfold caseUnit_pctx, caseUVal_pctx.\n  eauto with typing uval_typing.\nQed.\n\nLemma caseUnit_pctxA_T {Γ n} :\n  ⟪ a⊢ caseUnit_pctxA n : Γ, UValFI (S n) I.tunit → Γ, F.tunit ⟫.\nProof.\n  unfold caseUnit_pctxA, caseUVal_pctxA.\n  cbn.\n  repeat constructor.\nQed.\n\nLemma caseUnit_T {Γ n t} :\n  ⟪ Γ ⊢ t : UValFI (S n) I.tunit ⟫ →\n  ⟪ Γ ⊢ caseUnit t : F.tunit ⟫.\nProof.\n  unfold caseUnit; eauto using caseUnit_pctx_T with typing uval_typing.\nQed.\n\nLemma caseUnitA_T {Γ n t} :\n  ⟪ Γ a⊢ t : UValFI (S n) I.tunit ⟫ →\n  ⟪ Γ a⊢ caseUnitA n t : F.tunit ⟫.\nProof.\n  unfold caseUnitA; eauto using caseUnit_pctxA_T with typing uval_typing.\nQed.\n\nLemma caseUnit_pctx_ectx : ECtx caseUnit_pctx.\nProof. simpl; trivial. Qed.\n\nLemma caseBool_pctx_T {Γ n} :\n  ⟪ ⊢ caseBool_pctx : Γ, UValFI (S n) I.tbool → Γ, F.tbool ⟫.\nProof.\n  unfold caseBool_pctx, caseUVal_pctx.\n  eauto with typing uval_typing.\nQed.\n\nLemma caseBool_pctxA_T {Γ n} :\n  ⟪ a⊢ caseBool_pctxA n : Γ, UValFI (S n) I.tbool → Γ, F.tbool ⟫.\nProof.\n  unfold caseBool_pctxA, caseUVal_pctxA.\n  cbn.\n  repeat constructor.\nQed.\n\nLemma caseBool_T {Γ n t} :\n  ⟪ Γ ⊢ t : UValFI (S n) I.tbool ⟫ →\n  ⟪ Γ ⊢ caseBool t : F.tbool ⟫.\nProof.\n  unfold caseBool; eauto using caseBool_pctx_T with typing uval_typing.\nQed.\n\nLemma caseBoolA_T {Γ n t} :\n  ⟪ Γ a⊢ t : UValFI (S n) I.tbool ⟫ →\n  ⟪ Γ a⊢ caseBoolA n t : F.tbool ⟫.\nProof.\n  unfold caseBoolA; eauto using caseBool_pctxA_T with typing uval_typing.\nQed.\n\nLemma caseBool_pctx_ectx : ECtx caseBool_pctx.\nProof. simpl; trivial. Qed.\n\nLemma caseSum_pctx_T {Γ n τ1 τ2} :\n  ⟪ ⊢ caseSum_pctx n τ1 τ2 : Γ, UValFI (S n) (I.tsum τ1 τ2) → Γ, F.tsum (UValFI n τ1) (UValFI n τ2) ⟫.\nProof.\n  unfold caseSum_pctx, caseUVal_pctx.\n  eauto with typing uval_typing.\nQed.\n\nLemma caseSum_pctxA_T {Γ n τ1 τ2} :\n  ⟪ a⊢ caseSum_pctxA n τ1 τ2 : Γ, UValFI (S n) (I.tsum τ1 τ2) → Γ, F.tsum (UValFI n τ1) (UValFI n τ2) ⟫.\nProof.\n  unfold caseSum_pctxA, caseUVal_pctxA.\n  repeat constructor.\nQed.\n\n\nLemma caseSum_T {Γ n t τ1 τ2} :\n  ⟪ Γ ⊢ t : UValFI (S n) (I.tsum τ1 τ2) ⟫ →\n  ⟪ Γ ⊢ caseSum n t τ1 τ2 : F.tsum (UValFI n τ1) (UValFI n τ2) ⟫.\nProof.\n  unfold caseSum; eauto using caseSum_pctx_T with typing uval_typing.\nQed.\n\n\nLemma caseSumA_T {Γ n t τ1 τ2} :\n  ⟪ Γ a⊢ t : UValFI (S n) (I.tsum τ1 τ2) ⟫ →\n  ⟪ Γ a⊢ caseSumA n t τ1 τ2 : F.tsum (UValFI n τ1) (UValFI n τ2) ⟫.\nProof.\n  unfold caseSumA; eauto using caseSum_pctxA_T with typing uval_typing.\nQed.\n\n\nLemma caseSum_pctx_ectx {n τ τ'} : ECtx (caseSum_pctx n τ τ').\nProof. simpl; trivial. Qed.\n\nLemma eraseAnnot_caseSumA {n t τ₁ τ₂} :\n  eraseAnnot (caseSumA n t τ₁ τ₂) = caseSum n (eraseAnnot t) τ₁ τ₂.\nProof.\n  now cbn.\nQed.\n\nLemma caseProd_pctx_T {Γ n τ1 τ2} :\n  ⟪ ⊢ caseProd_pctx n τ1 τ2 : Γ, UValFI (S n) (I.tprod τ1 τ2) → Γ, F.tprod (UValFI n τ1) (UValFI n τ2) ⟫.\nProof.\n  unfold caseProd_pctx, caseUVal_pctx.\n  eauto with typing uval_typing.\nQed.\n\nLemma caseProd_pctxA_T {Γ n τ1 τ2} :\n  ⟪ a⊢ caseProd_pctxA n τ1 τ2 : Γ, UValFI (S n) (I.tprod τ1 τ2) → Γ, F.tprod (UValFI n τ1) (UValFI n τ2) ⟫.\nProof.\n  unfold caseProd_pctxA, caseUVal_pctxA.\n  repeat constructor.\nQed.\n\n\nLemma caseProd_T {Γ n t τ1 τ2} :\n  ⟪ Γ ⊢ t : UValFI (S n) (I.tprod τ1 τ2) ⟫ →\n  ⟪ Γ ⊢ caseProd n t τ1 τ2 : F.tprod (UValFI n τ1) (UValFI n τ2) ⟫.\nProof.\n  unfold caseProd; eauto using caseProd_pctx_T with typing uval_typing.\nQed.\n\n\nLemma caseProdA_T {Γ n t τ1 τ2} :\n  ⟪ Γ a⊢ t : UValFI (S n) (I.tprod τ1 τ2) ⟫ →\n  ⟪ Γ a⊢ caseProdA n t τ1 τ2 : F.tprod (UValFI n τ1) (UValFI n τ2) ⟫.\nProof.\n  unfold caseProdA; eauto using caseProd_pctxA_T with typing uval_typing.\nQed.\n\n\nLemma caseProd_pctx_ectx {n τ τ'} : ECtx (caseProd_pctx n τ τ').\nProof. simpl; trivial. Qed.\n\nLemma eraseAnnot_caseProdA {n t τ₁ τ₂} :\n  eraseAnnot (caseProdA n t τ₁ τ₂) = caseProd n (eraseAnnot t) τ₁ τ₂.\nProof.\n  now cbn.\nQed.\n\n\nLemma caseArr_pctx_T {Γ n τ1 τ2} :\n  ⟪ ⊢ caseArr_pctx n τ1 τ2 : Γ, UValFI (S n) (I.tarr τ1 τ2) → Γ, F.tarr (UValFI n τ1) (UValFI n τ2) ⟫.\nProof.\n  unfold caseArr_pctx, caseUVal_pctx.\n  eauto with typing uval_typing.\nQed.\n\nLemma caseArr_pctxA_T {Γ n τ1 τ2} :\n  ⟪ a⊢ caseArr_pctxA n τ1 τ2 : Γ, UValFI (S n) (I.tarr τ1 τ2) → Γ, F.tarr (UValFI n τ1) (UValFI n τ2) ⟫.\nProof.\n  unfold caseArr_pctxA, caseUVal_pctxA.\n  repeat constructor.\nQed.\n\nLemma caseArr_T {Γ n t τ1 τ2} :\n  ⟪ Γ ⊢ t : UValFI (S n) (I.tarr τ1 τ2) ⟫ →\n  ⟪ Γ ⊢ caseArr n t τ1 τ2 : F.tarr (UValFI n τ1) (UValFI n τ2) ⟫.\nProof.\n  unfold caseArr; eauto using caseArr_pctx_T with typing uval_typing.\nQed.\n\nLemma caseArrA_T {Γ n t τ1 τ2} :\n  ⟪ Γ a⊢ t : UValFI (S n) (I.tarr τ1 τ2) ⟫ →\n  ⟪ Γ a⊢ caseArrA n t τ1 τ2 : F.tarr (UValFI n τ1) (UValFI n τ2) ⟫.\nProof.\n  unfold caseArrA; eauto using caseArr_pctxA_T with typing uval_typing.\nQed.\n\nLemma caseArr_pctx_ectx {n τ τ'} : ECtx (caseArr_pctx n τ τ').\nProof. simpl; trivial. Qed.\n\nLemma eraseAnnot_caseArrA {n t τ₁ τ₂} :\n  eraseAnnot (caseArrA n t τ₁ τ₂) = caseArr n (eraseAnnot t) τ₁ τ₂.\nProof.\n  now cbn.\nQed.\n\nLemma caseRec_pctx_T {Γ n τ} :\n  ⟪ ⊢ caseRec_pctx n τ : Γ, UValFI (S n) (I.trec τ) → Γ, UValFI n τ[beta1 (I.trec τ)] ⟫.\nProof.\n  unfold caseRec_pctx, caseUVal_pctx.\n  eauto with typing uval_typing.\nQed.\n\nLemma caseRec_T {Γ n t τ} :\n  ⟪ Γ ⊢ t : UValFI (S n) (I.trec τ) ⟫ →\n  ⟪ Γ ⊢ caseRec n t τ : UValFI n τ[beta1 (I.trec τ)] ⟫.\nProof.\n  unfold caseRec; eauto using caseRec_pctx_T with typing uval_typing.\nQed.\n\nLemma caseRec_pctxA_T {Γ n τ} :\n  ⟪ a⊢ caseRec_pctxA n τ : Γ, UValFI (S n) (I.trec τ) → Γ, UValFI n τ[beta1 (I.trec τ)] ⟫.\nProof.\n  unfold caseRec_pctxA, caseUVal_pctxA.\n  repeat constructor.\nQed.\n\nLemma caseRecA_T {Γ n t τ} :\n  ⟪ Γ a⊢ t : UValFI (S n) (I.trec τ) ⟫ →\n  ⟪ Γ a⊢ caseRecA n t τ : UValFI n τ[beta1 (I.trec τ)] ⟫.\nProof.\n  unfold caseRecA; eauto using caseRec_pctxA_T with typing uval_typing.\nQed.\n\nLemma caseRec_pctx_ectx {n τ} : ECtx (caseRec_pctx n τ).\nProof. simpl; trivial. Qed.\n\nLemma eraseAnnot_caseRecA {n t τ} :\n  eraseAnnot (caseRecA n t τ) = caseRec n (eraseAnnot t) τ.\nProof.\n  now cbn.\nQed.\n\n#[export]\nHint Resolve caseUnit_T : uval_typing.\n#[export]\nHint Resolve caseSum_T : uval_typing.\n#[export]\nHint Resolve caseArr_T : uval_typing.\n#[export]\nHint Resolve caseRec_T : uval_typing.\n#[export]\nHint Resolve caseUnitA_T : uval_typing.\n#[export]\nHint Resolve caseSumA_T : uval_typing.\n#[export]\nHint Resolve caseArrA_T : uval_typing.\n#[export]\nHint Resolve caseRecA_T : uval_typing.\n\n(* Lemma caseUVal_eval_bool {n tunk tcunit tcbool tcprod tcsum tcarr v} : *)\n(*   Value v → *)\n(*   caseUVal (inBool n v) tunk tcunit tcbool tcprod tcsum tcarr -->* tcbool [beta1 v]. *)\n(* Proof. *)\n(*   intros vv. *)\n(*   unfold caseUVal, inBool; simpl. *)\n(*   crushEvalsInCaseUVal. *)\n(* Qed. *)\n\n\n(* Lemma caseUVal_pctx_T {Γ n tunk tcunit tcbool tcprod tcsum tcarr τ} : *)\n(*   ⟪ Γ ⊢ tunk : τ ⟫ → *)\n(*   ⟪ Γ ▻ tunit ⊢ tcunit : τ ⟫ → *)\n(*   ⟪ Γ ▻ tbool ⊢ tcbool : τ ⟫ → *)\n(*   (* ⟪ Γ ▻ (UVal n × UVal n) ⊢ tcprod : τ ⟫ → *) *)\n(*   ⟪ Γ ▻ (UVal n ⊎ UVal n) ⊢ tcsum : τ ⟫ → *)\n(*   ⟪ Γ ▻ (UVal n ⇒ UVal n) ⊢ tcarr : τ ⟫ → *)\n(*   ⟪ ⊢ caseUVal_pctx tunk tcunit tcbool tcprod tcsum tcarr : Γ , UVal (S n) → Γ , τ ⟫. *)\n(* Proof. *)\n(*   unfold caseUVal_pctx.  *)\n(*   crushTyping. *)\n(*   eauto with typing uval_typing. *)\n(* Qed. *)\n\n\n(* Lemma caseUVal_T {Γ n tscrut tunk tcunit tcbool tcprod tcsum tcarr τ} : *)\n(*   ⟪ Γ ⊢ tscrut : UVal (S n) ⟫ → *)\n(*   ⟪ Γ ⊢ tunk : τ ⟫ → *)\n(*   ⟪ Γ ▻ tunit ⊢ tcunit : τ ⟫ → *)\n(*   ⟪ Γ ▻ tbool ⊢ tcbool : τ ⟫ → *)\n(*   ⟪ Γ ▻ (UVal n × UVal n) ⊢ tcprod : τ ⟫ → *)\n(*   ⟪ Γ ▻ (UVal n ⊎ UVal n) ⊢ tcsum : τ ⟫ → *)\n(*   ⟪ Γ ▻ (UVal n ⇒ UVal n) ⊢ tcarr : τ ⟫ → *)\n(*   ⟪ Γ ⊢ caseUVal tscrut tunk tcunit tcbool tcprod tcsum tcarr : τ ⟫. *)\n(* Proof. *)\n(*   unfold caseUVal.  *)\n(*   eauto using caseUVal_pctx_T with typing. *)\n(* Qed. *)\n\nArguments UValFI n : simpl never.\n#[export]\nHint Resolve unkUValT : uval_typing.\n#[export]\nHint Resolve inUnitT : uval_typing.\n#[export]\nHint Resolve inBoolT : uval_typing.\n#[export]\nHint Resolve inProd_T : uval_typing.\n#[export]\nHint Resolve inSum_T : uval_typing.\n#[export]\nHint Resolve inArr_T : uval_typing.\n(* #[export]\nHint Resolve inUnit_pctx_T : uval_typing. *)\n(* #[export]\nHint Resolve inBool_pctx_T : uval_typing. *)\n(* #[export]\nHint Resolve inProd_pctx_T : uval_typing. *)\n(* #[export]\nHint Resolve inSum_pctx_T : uval_typing. *)\n(* #[export]\nHint Resolve inArr_pctx_T : uval_typing. *)\n(* #[export]\nHint Resolve caseUVal_pctx_T : uval_typing. *)\n(* #[export]\nHint Resolve caseUVal_T : uval_typing. *)\n\nLocal Ltac crush :=\n  repeat (subst*;\n          repeat rewrite\n          (*   ?protect_wkm_beta1, ?protect_wkm2_beta1, *)\n          (*   ?confine_wkm_beta1, ?confine_wkm2_beta1, *)\n           ?apply_wkm_beta1_up_cancel;\n          (*   ?apply_up_def_S; *)\n          repeat crushDbLemmasMatchH;\n          repeat crushDbSyntaxMatchH;\n          repeat crushStlcSyntaxMatchH;\n          repeat crushTypingMatchH2;\n          repeat crushTypingMatchH;\n          repeat match goal with\n                     [ |- _ ∧ _ ] => split\n                 end;\n          trivial;\n          eauto with ws typing uval_typing eval\n         ).\n\nLemma caseV0_eval_inl {v case₁ case₂ : F.Tm}:\n  F.Value v →\n  F.eval (caseV0 case₁ case₂)[beta1 (F.inl v)] (case₁ [beta1 v]).\nProof.\n  intros vv.\n  unfold caseV0; apply F.eval₀_to_eval; crush.\n  change ((F.caseof (F.var 0) case₁[wkm↑] case₂ [wkm↑])[beta1 (F.inl v)]) with\n  (F.caseof (F.inl v) (case₁[wkm↑][(beta1 (F.inl v))↑]) (case₂[wkm↑][(beta1 (F.inl v))↑])).\n  crush.\nQed.\n\nLemma caseV0_eval_inr {v case₁ case₂ : F.Tm}:\n  F.Value v →\n  F.eval (caseV0 case₁ case₂)[beta1 (F.inr v)] (case₂ [beta1 v]).\nProof.\n  intros vv.\n  unfold caseV0; apply F.eval₀_to_eval; crush.\n  change ((F.caseof (F.var 0) case₁[wkm↑] case₂ [wkm↑])[beta1 (F.inr v)]) with\n  (F.caseof (F.inr v) (case₁[wkm↑][(beta1 (F.inr v))↑]) (case₂[wkm↑][(beta1 (F.inr v))↑])).\n  crush.\nQed.\n\nLemma caseV0_eval {v τ₁ τ₂ case₁ case₂}:\n  F.Value v → F.Typing F.empty v (F.tsum τ₁ τ₂) →\n  (exists v', v = F.inl v' ∧ F.eval (caseV0 case₁ case₂)[beta1 v] case₁[beta1 v']) ∨\n  (exists v', v = F.inr v' ∧ F.eval (caseV0 case₁ case₂)[beta1 v] case₂[beta1 v']).\nProof.\n  intros vv ty.\n  F.stlcCanForm; [left|right]; exists x;\n  crush; eauto using caseV0_eval_inl, caseV0_eval_inr.\nQed.\n\nLocal Ltac crushEvalsInCaseUVal :=\n  repeat\n    (match goal with\n         [ |- (F.evalStar (F.caseof (F.inl _) _ _) _) ] => (eapply (evalStepStar _); [eapply F.eval₀_to_eval; crush|])\n       | [ |- (F.evalStar (F.caseof (F.inr _) _ _) _) ] => (eapply (evalStepStar _); [eapply F.eval₀_to_eval; crush|])\n       | [ |- (F.evalStar ((caseV0 _ _) [beta1 (F.inl _)]) _) ] => (eapply (evalStepStar _); [eapply caseV0_eval_inl; crush|])\n       | [ |- (F.evalStar ((caseV0 _ _) [beta1 (F.inr _)]) _) ] => (eapply (evalStepStar _); [eapply caseV0_eval_inr; crush|])\n       | [ |- (F.evalStar ?t ?t) ] => eauto with *\n     end;\n     try rewrite -> apply_wkm_beta1_cancel\n    ).\n\nLemma caseUVal_eval_unk_diverges {n τ} :\n  not (F.Terminating (caseUVal τ (unkUVal (S n)))).\nProof.\n  unfold caseUVal, unkUVal; simpl.\n  eapply F.divergence_closed_under_eval.\n  apply F.eval₀_to_eval.\n  apply F.eval_case_inr.\n  simpl; trivial.\n  apply stlcOmega_div.\nQed.\n\nLemma caseUnit_eval_unk_diverges {n} :\n  (caseUnit (unkUVal (S n)))⇑.\nProof.\n  unfold caseUnit, unkUVal; simpl.\n  eapply F.divergence_closed_under_eval.\n  apply F.eval₀_to_eval.\n  apply F.eval_case_inr.\n  simpl; trivial.\n  apply stlcOmega_div.\nQed.\n\nLemma caseArr_eval_unk_diverges {n τ1 τ2} :\n  (caseArr n (unkUVal (S n)) τ1 τ2)⇑.\nProof.\n  unfold caseArr, unkUVal; simpl.\n  eapply F.divergence_closed_under_eval.\n  apply F.eval₀_to_eval.\n  apply F.eval_case_inr.\n  simpl; trivial.\n  apply stlcOmega_div.\nQed.\n\nLemma caseSum_eval_unk_diverges {n τ1 τ2} :\n  (caseSum n (unkUVal (S n)) τ1 τ2)⇑.\nProof.\n  unfold caseSum, unkUVal; simpl.\n  eapply F.divergence_closed_under_eval.\n  apply F.eval₀_to_eval.\n  apply F.eval_case_inr.\n  simpl; trivial.\n  apply stlcOmega_div.\nQed.\n\nLemma caseRec_eval_unk_diverges {n τ} :\n  (caseRec n (unkUVal (S n)) τ)⇑.\nProof.\n  unfold caseRec, unkUVal; simpl.\n  eapply F.divergence_closed_under_eval.\n  apply F.eval₀_to_eval.\n  apply F.eval_case_inr.\n  simpl; trivial.\n  apply stlcOmega_div.\nQed.\n\nLemma caseUVal_eval_left {v τ}:\n  Value v →\n  caseUVal τ (F.inl v) -->* v.\nProof.\n  intro vv.\n  unfold caseUVal; simpl.\n  eapply (evalStepStar _).\n  apply eval₀_to_eval.\n  apply eval_case_inl.\n  simpl; trivial.\n  eauto with eval.\nQed.\n\n\nLemma canonUValS_Unit {n v} :\n  F.Value v →\n  ⟪ F.empty ⊢ v : UValFI (S n) I.tunit ⟫ →\n  (v = F.inl F.unit) ∨ (v = F.inr F.unit).\nProof.\n  unfold UValFI.\n  intros.\n  destruct (F.can_form_tsum H H0) as [(? & ? & ?) | (? & ? & ?)];\n  [left | right];\n  assert (F.Value x) by (\n    subst;\n    cbn in H;\n    assumption);\n  pose proof (F.can_form_tunit H3 H2);\n  rewrite H4 in H1;\n  assumption.\nQed.\n\nLemma canonUValS_Bool {n v} :\n  F.Value v →\n  ⟪ F.empty ⊢ v : UValFI (S n) I.tbool ⟫ →\n  (v = F.inl F.true) ∨ (v = F.inl F.false) ∨ (v = F.inr F.unit).\nProof.\n  unfold UValFI.\n  intros.\n  destruct (F.can_form_tsum H H0) as [(? & ? & ?) | (? & ? & ?)];\n  subst; cbn in H; F.stlcCanForm.\n  - now left.\n  - now right; left.\n  - now right; right.\nQed.\n\nLemma canonUValS_Arr {n v τ τ'} :\n  F.Value v →\n  ⟪ F.empty ⊢ v : UValFI (S n) (I.tarr τ τ') ⟫ →\n  (exists v', F.Value v' ∧ (v = F.inl v') ∧ ⟪ F.empty ⊢ v' : F.tarr (UValFI n τ) (UValFI n τ')⟫) ∨ (v = F.inr F.unit).\nProof.\n  unfold UValFI.\n  intros vv ty.\n  destruct (F.can_form_tsum vv ty) as [(? & ? & ?) | (? & ? & ?)];\n  [left | right].\n\n  exists x.\n  split.\n  subst.\n  cbn in vv.\n  assumption.\n  split.\n  assumption.\n  assumption.\n\n  assert (F.Value x) by (\n                         subst;\n                         cbn in vv;\n                         assumption\n                         ).\n\n  pose proof (F.can_form_tunit H1 H0).\n  rewrite H2 in H.\n  assumption.\nQed.\n\nLemma canonUValS_Sum {n v τ τ'} :\n  F.Value v →\n  ⟪ F.empty ⊢ v : UValFI (S n) (I.tsum τ τ') ⟫ →\n  (exists v', F.Value v' ∧ (v = F.inl v') ∧ ⟪ F.empty ⊢ v' : F.tsum (UValFI n τ) (UValFI n τ')⟫) ∨ (v = F.inr F.unit).\nProof.\n  unfold UValFI.\n  intros vv ty.\n  destruct (F.can_form_tsum vv ty) as [(? & ? & ?) | (? & ? & ?)];\n  [left | right].\n\n  exists x.\n  split.\n  subst.\n  cbn in vv.\n  assumption.\n  split.\n  assumption.\n  assumption.\n\n  assert (F.Value x) by (\n                         subst;\n                         cbn in vv;\n                         assumption\n                       ).\n\n  pose proof (F.can_form_tunit H1 H0).\n  rewrite H2 in H.\n  assumption.\nQed.\n\nLemma canonUValS_Prod {n v τ τ'} :\n  F.Value v →\n  ⟪ F.empty ⊢ v : UValFI (S n) (I.tprod τ τ') ⟫ →\n  (exists v', F.Value v' ∧ (v = F.inl v') ∧ ⟪ F.empty ⊢ v' : F.tprod (UValFI n τ) (UValFI n τ')⟫) ∨\n  (v = F.inr F.unit).\nProof.\n  unfold UValFI.\n  intros vv ty.\n  cbn in *.\n  stlcCanForm.\n  - left. exists (F.pair x0 x1).\n    crush.\n  - now right.\nQed.\n\nLemma canonUValS_Rec {n v τ} :\n  F.Value v →\n  ⟪ F.empty ⊢ v : UValFI (S n) (I.trec τ) ⟫ →\n  (exists v', F.Value v' ∧ (v = F.inl v') ∧ ⟪ F.empty ⊢ v' : UValFI n τ[beta1 (I.trec τ)] ⟫) ∨ (v = F.inr F.unit).\nProof.\n  unfold UValFI.\n  intros vv ty.\n  destruct (F.can_form_tsum vv ty) as [(? & ? & ?) | (? & ? & ?)];\n  [left | right].\n  exists x.\n  split.\n  subst.\n  cbn in vv.\n  assumption.\n  split.\n  assumption.\n  assumption.\n\n  assert (F.Value x) by (\n                         subst;\n                         cbn in vv;\n                         assumption\n                       ).\n  pose proof (F.can_form_tunit H1 H0).\n  rewrite H2 in H.\n  assumption.\nQed.\n\n\n(* Lemma canonUVal_Arr {n v τ τ'} : *)\n(*   F.Value v → *)\n(*   ⟪ F.empty ⊢ v : UValFI n (I.tarr τ τ') ⟫ → *)\n(*   (v = F.unit) ∨ (exists v', F.Value v' ∧ (v = F.inl v') ∧ ⟪ F.empty ⊢ v' : F.tarr (UValFI n τ) (UValFI n τ')⟫) ∨ (v = F.inr F.unit). *)\n(* Proof. *)\n(*   intros. *)\n(*   destruct n as [? | ?]. *)\n(*   left. *)\n(*   unfold UValFI in H0. *)\n(*   F.stlcCanForm. *)\n(*   reflexivity. *)\n\n(*   right. *)\n(*   apply (canonUValS_Arr H). *)\n\n\n(* NOTE: for compatibility lemmas, we might need a UVal context and accompanying lemmas *)\n\n(* Lemma canonUValS {n v} : *)\n(*   ⟪ empty ⊢ v : UVal (S n) ⟫ → Value v → *)\n(*   (v = unkUVal (S n)) ∨ *)\n(*   (∃ v', v = inUnit n v' ∧ Value v' ∧ ⟪ empty ⊢ v' : tunit ⟫) ∨ *)\n(*   (∃ v', v = inBool n v' ∧ Value v' ∧ ⟪ empty ⊢ v' : tbool ⟫) ∨ *)\n(*   (∃ v', v = inProd n v' ∧ Value v' ∧ ⟪ empty ⊢ v' : UVal n × UVal n ⟫) ∨ *)\n(*   (∃ v', v = inSum n v' ∧ Value v' ∧ ⟪ empty ⊢ v' : UVal n ⊎ UVal n ⟫) ∨ *)\n(*   (∃ v', v = inArr n v' ∧ Value v' ∧ ⟪ empty ⊢ v' : UVal n ⇒ UVal n ⟫). *)\n(* Proof. *)\n(*   intros ty vv. *)\n(*   unfold UVal in ty; simpl. *)\n(*   (* Apply canonical form lemmas but only as far as we need. *) *)\n(*   stlcCanForm1; *)\n(*     [left|right;stlcCanForm1; *)\n(*        [left|right;stlcCanForm1; *)\n(*           [left|right;stlcCanForm1; *)\n(*                 [left|right;stlcCanForm1; *)\n(*                       [right|left]]]]]. *)\n(*   - stlcCanForm; crush. *)\n(*   - exists x0; crush. *)\n(*   - exists x; crush. *)\n(*   - exists x0; crush. *)\n(*   - exists x; crush. *)\n(*   - exists x; crush. *)\n(* Qed. *)\n\n(* Lemma canonUVal {n v} : *)\n(*   ⟪ empty ⊢ v : UVal n ⟫ → Value v → *)\n(*   (v = unkUVal n) ∨ *)\n(*   ∃ n', n = S n' ∧  *)\n(*         ((∃ v', v = inUnit n' v' ∧ Value v' ∧ ⟪ empty ⊢ v' : tunit ⟫) ∨ *)\n(*          (∃ v', v = inBool n' v' ∧ Value v' ∧ ⟪ empty ⊢ v' : tbool ⟫) ∨ *)\n(*          (∃ v', v = inProd n' v' ∧ Value v' ∧ ⟪ empty ⊢ v' : UVal n' × UVal n' ⟫) ∨ *)\n(*          (∃ v', v = inSum n' v' ∧ Value v' ∧ ⟪ empty ⊢ v' : UVal n' ⊎ UVal n' ⟫) ∨ *)\n(*          (∃ v', v = inArr n' v' ∧ Value v' ∧ ⟪ empty ⊢ v' : UVal n' ⇒ UVal n' ⟫)). *)\n(* Proof. *)\n(*   intros ty vv. *)\n(*   destruct n. *)\n(*   - left. unfold UVal, unkUVal in *. stlcCanForm. trivial. *)\n(*   - destruct (canonUValS ty vv) as [? | ?]. *)\n(*     + left; crush. *)\n(*     + right; crush.  *)\n(* Qed. *)\n\n(* Ltac canonUVal := *)\n(*   match goal with *)\n(*       [ H : Value ?v, H' : ⟪ empty ⊢ ?v : UVal 0 ⟫ |- _ ] => *)\n(*       (unfold UVal in H'; stlcCanForm; subst) *)\n(*     | [ H : Value ?v, H' : ⟪ empty ⊢ ?v : UVal (S _) ⟫ |- _ ] => *)\n(*       (destruct (canonUValS H' H) as  *)\n(*           [?| [(? & ? & ? & ?) *)\n(*               |[(? & ? & ? & ?) *)\n(*                |[(? & ? & ? & ?) *)\n(*                 |[(? & ? & ? & ?) *)\n(*                  |(? & ? & ? & ?)]]]]]; subst) *)\n(*     | [ H : Value ?v, H' : ⟪ empty ⊢ ?v : UVal (S _ + _) ⟫ |- _ ] => *)\n(*       (destruct (canonUValS H' H) as  *)\n(*           [?| [(? & ? & ? & ?) *)\n(*               |[(? & ? & ? & ?) *)\n(*                |[(? & ? & ? & ?) *)\n(*                 |[(? & ? & ? & ?) *)\n(*                  |(? & ? & ? & ?)]]]]]; subst) *)\n(*     | [ H : Value ?v, H' : ⟪ empty ⊢ ?v : UVal _ ⟫ |- _ ] => *)\n(*       (destruct (canonUVal H' H) as  *)\n(*           [?| (? & ? & [(? & ? & ? & ?) *)\n(*                        |[(? & ? & ? & ?) *)\n(*                         |[(? & ? & ? & ?) *)\n(*                          |[(? & ? & ? & ?) *)\n(*                           |(? & ? & ? & ?)]]]])]; subst) *)\n(*   end. *)\n\n(* Lemma caseUVal_eval_unk {n : nat} {tunk tcunit tcbool tcprod tcsum tcarr : F.Tm} : *)\n(*   F.evalStar (caseUVal (F.inr F.unit) tunk tcunit tcbool tcprod tcsum tcarr) tunk. *)\n(* Proof. *)\n(*   unfold caseUVal, unkUVal; simpl. *)\n(*   (* why doesn't crush do the following? *) *)\n(*   assert (Value (inl unit)) by (simpl; trivial). *)\n(*   crushEvalsInCaseUVal. *)\n(*   eauto with *. *)\n(* Qed. *)\n\n(* Lemma caseUVal_eval_unit {n tunk tcunit tcbool tcprod tcsum tcarr v} : *)\n(*   Value v → *)\n(*   caseUVal (inUnit n v) tunk tcunit tcbool tcprod tcsum tcarr -->* tcunit [beta1 v]. *)\n(* Proof. *)\n(*   intros vv. *)\n(*   unfold caseUVal, inUnit; simpl. *)\n(*   crushEvalsInCaseUVal. *)\n(* Qed. *)\n\n(* Lemma caseUVal_eval_bool {n tunk tcunit tcbool tcprod tcsum tcarr v} : *)\n(*   Value v → *)\n(*   caseUVal (inBool n v) tunk tcunit tcbool tcprod tcsum tcarr -->* tcbool [beta1 v]. *)\n(* Proof. *)\n(*   intros vv. *)\n(*   unfold caseUVal, inBool; simpl. *)\n(*   crushEvalsInCaseUVal. *)\n(* Qed. *)\n\n(* Lemma caseUVal_eval_prod {n tunk tcunit tcbool tcprod tcsum tcarr v} : *)\n(*   Value v → *)\n(*   caseUVal (inProd n v) tunk tcunit tcbool tcprod tcsum tcarr -->* tcprod [beta1 v]. *)\n(* Proof. *)\n(*   intros vv. *)\n(*   unfold caseUVal, inProd; simpl. *)\n(*   crushEvalsInCaseUVal. *)\n(* Qed. *)\n\n(* Lemma caseUVal_eval_sum {n tunk tcunit tcbool tcprod tcsum tcarr v} : *)\n(*   Value v → *)\n(*   caseUVal (inSum n v) tunk tcunit tcbool tcprod tcsum tcarr -->* tcsum [beta1 v]. *)\n(* Proof. *)\n(*   intros vv. *)\n(*   unfold caseUVal, inSum; simpl. *)\n(*   crushEvalsInCaseUVal. *)\n(* Qed. *)\n\n(* Lemma caseUVal_eval_arr {n tunk tcunit tcbool tcprod tcsum tcarr v} : *)\n(*   Value v → *)\n(*   caseUVal (inArr n v) tunk tcunit tcbool tcprod tcsum tcarr -->* tcarr [beta1 v]. *)\n(* Proof. *)\n(*   intros vv. *)\n(*   unfold caseUVal, inArr; simpl. *)\n(*   crushEvalsInCaseUVal. *)\n(* Qed. *)\n\n(* Lemma caseUVal_sub {t tunk tcunit tcbool tcprod tcsum tcarr} γ : *)\n(*   (caseUVal t tunk tcunit tcbool tcprod tcsum tcarr)[γ] = *)\n(*   caseUVal (t[γ]) (tunk[γ]) (tcunit[γ↑]) (tcbool[γ↑]) (tcprod[γ↑]) (tcsum[γ↑]) (tcarr[γ↑]). *)\n(* Proof. *)\n(*   unfold caseUVal, caseUVal_pctx, caseV0. cbn.  *)\n(*   crush;  *)\n(*     rewrite <- ?apply_wkm_comm, <- ?(apply_wkm_up_comm);  *)\n(*     reflexivity. *)\n(* Qed. *)\n\n\n(* Arguments caseUVal tscrut tunk tcunit tcbool tcprod tcsum tcarr : simpl never. *)\n(* Arguments caseUVal_pctx tunk tcunit tcbool tcprod tcsum tcarr : simpl never. *)\n\n(* Lemma caseUVal_pctx_ECtx {tunk tcunit tcbool tcprod tcsum tcarr} : *)\n(*   ECtx (caseUVal_pctx tunk tcunit tcbool tcprod tcsum tcarr). *)\n(* Proof. *)\n(*   simpl; trivial. *)\n(* Qed. *)\n\n\n(* Definition caseUVal (n : nat) (tscrut tunk tcunit tcbool tcprod tcsum tcarr : Tm) := *)\n\n\n(* Definition caseUnit_pctx := caseUVal_pctx (stlcOmega tunit) (var 0) (stlcOmega tunit) (stlcOmega tunit) (stlcOmega tunit) (stlcOmega tunit). *)\n(* Definition caseBool_pctx := caseUVal_pctx (stlcOmega tbool) (stlcOmega tbool) (var 0) (stlcOmega tbool) (stlcOmega tbool) (stlcOmega tbool). *)\n(* Definition caseProd_pctx n := caseUVal_pctx (stlcOmega (UVal n × UVal n)) (stlcOmega (UVal n × UVal n)) (stlcOmega (UVal n × UVal n)) (var 0) (stlcOmega (UVal n × UVal n)) (stlcOmega (UVal n × UVal n)). *)\n(* Definition caseSum_pctx n := caseUVal_pctx (stlcOmega (UVal n ⊎ UVal n)) (stlcOmega (UVal n ⊎ UVal n)) (stlcOmega (UVal n ⊎ UVal n)) (stlcOmega (UVal n ⊎ UVal n)) (var 0) (stlcOmega (UVal n ⊎ UVal n)). *)\n(* Definition caseArr_pctx n := caseUVal_pctx (stlcOmega (UVal n ⇒ UVal n)) (stlcOmega (UVal n ⇒ UVal n)) (stlcOmega (UVal n ⇒ UVal n)) (stlcOmega (UVal n ⇒ UVal n)) (stlcOmega (UVal n ⇒ UVal n)) (var 0). *)\n(* Definition caseUnit t := pctx_app t caseUnit_pctx. *)\n(* Definition caseBool t := pctx_app t caseBool_pctx. *)\n(* Definition caseProd n t := pctx_app t (caseProd_pctx n). *)\n(* Definition caseSum n t := pctx_app t (caseSum_pctx n). *)\n(* Definition caseArr n t := pctx_app t (caseArr_pctx n). *)\n\n(* Lemma caseUnit_pctx_ECtx : ECtx caseUnit_pctx. *)\n(* Proof. *)\n(*   simpl; trivial. *)\n(* Qed. *)\n\n(* Lemma caseBool_pctx_ECtx : ECtx caseBool_pctx. *)\n(* Proof. *)\n(*   simpl; trivial. *)\n(* Qed. *)\n\n(* Lemma caseProd_pctx_ECtx {n}: ECtx (caseProd_pctx n). *)\n(* Proof. *)\n(*   simpl; trivial. *)\n(* Qed. *)\n\n(* Lemma caseSum_pctx_ECtx {n}: ECtx (caseSum_pctx n). *)\n(* Proof. *)\n(*   simpl; trivial. *)\n(* Qed. *)\n\n(* Lemma caseArr_pctx_ECtx {n}: ECtx (caseArr_pctx n). *)\n(* Proof. *)\n(*   simpl; trivial. *)\n(* Qed. *)\n\nLemma caseUnit_sub {t γ} :\n  (caseUnit t) [γ] = caseUnit (t [γ]).\nProof.\n  unfold caseUnit; crush.\nQed.\n\n(* Lemma caseBool_sub {t γ} : *)\n(*   caseBool t [γ] = caseBool (t [γ]). *)\n(* Proof. *)\n(*   unfold caseBool; crush. *)\n(* Qed. *)\n\n(* Lemma caseProd_sub {n t γ} : *)\n(*   caseProd n t [γ] = caseProd n (t [γ]). *)\n(* Proof. *)\n(*   unfold caseProd; crush. *)\n(* Qed. *)\n\nLemma caseSum_sub {n t τ τ' γ} :\n  (caseSum n t τ τ') [γ] = caseSum n (t [γ]) τ τ'.\nProof.\n  unfold caseSum; crush.\nQed.\n\nLemma caseArr_sub {n t τ τ' γ} :\n  (caseArr n t τ τ') [γ] = caseArr n (t [γ]) τ τ'.\nProof.\n  unfold caseArr; crush.\nQed.\n\nLemma caseRec_sub {n t τ γ} :\n  (caseRec n t τ) [γ] = caseRec n (t [γ]) τ.\nProof.\n  unfold caseRec; crush.\nQed.\n\nArguments caseUnit t : simpl never.\nArguments caseSum n t τ1 τ2 : simpl never.\nArguments caseArr n t τ1 τ2 : simpl never.\nArguments caseRec n t τ : simpl never.\n\nArguments caseUnitA n t : simpl never.\nArguments caseSumA n t τ1 τ2 : simpl never.\nArguments caseArrA n t τ1 τ2 : simpl never.\nArguments caseRecA n t τ : simpl never.\n\n(* Lemma caseUnit_pctx_T {Γ n} :  *)\n(*   ⟪ ⊢ caseUnit_pctx : Γ , UVal (S n) → Γ , tunit ⟫. *)\n(* Proof. *)\n(*   unfold caseUnit_pctx. *)\n(*   eauto with typing uval_typing. *)\n(* Qed. *)\n\n(* Lemma caseUnit_T {Γ n t} :  *)\n(*   ⟪ Γ ⊢ t : UVal (S n) ⟫ → ⟪ Γ ⊢ caseUnit t : tunit ⟫. *)\n(* Proof. *)\n(*   unfold caseUnit. *)\n(*   eauto using caseUnit_pctx_T with typing. *)\n(* Qed. *)\n\n(* Lemma caseBool_pctx_T {Γ n} :  *)\n(*   ⟪ ⊢ caseBool_pctx : Γ , UVal (S n) → Γ , tbool ⟫. *)\n(* Proof. *)\n(*   unfold caseBool_pctx. *)\n(*   eauto with typing uval_typing. *)\n(* Qed. *)\n\n(* Lemma caseBool_T {Γ n t} :  *)\n(*   ⟪ Γ ⊢ t : UVal (S n) ⟫ → ⟪ Γ ⊢ caseBool t : tbool ⟫. *)\n(* Proof. *)\n(*   unfold caseBool. *)\n(*   eauto using caseBool_pctx_T with typing. *)\n(* Qed. *)\n\n(* Lemma caseProd_pctx_T {Γ n} :  *)\n(*   ⟪ ⊢ caseProd_pctx n : Γ , UVal (S n) → Γ , UVal n × UVal n ⟫. *)\n(* Proof. *)\n(*   unfold caseProd_pctx. *)\n(*   eauto with typing uval_typing. *)\n(* Qed. *)\n\n(* Lemma caseProd_T {Γ n t} :  *)\n(*   ⟪ Γ ⊢ t : UVal (S n) ⟫ → ⟪ Γ ⊢ caseProd n t : UVal n × UVal n ⟫. *)\n(* Proof. *)\n(*   unfold caseProd. *)\n(*   eauto using caseProd_pctx_T with typing. *)\n(* Qed. *)\n\n(* Lemma caseSum_pctx_T {Γ n} :  *)\n(*   ⟪ ⊢ caseSum_pctx n : Γ , UVal (S n) → Γ , UVal n ⊎ UVal n ⟫. *)\n(* Proof. *)\n(*   unfold caseSum_pctx. *)\n(*   eauto with typing uval_typing. *)\n(* Qed. *)\n\n(* Lemma caseSum_T {Γ n t} :  *)\n(*   ⟪ Γ ⊢ t : UVal (S n) ⟫ → ⟪ Γ ⊢ caseSum n t : UVal n ⊎ UVal n ⟫. *)\n(* Proof. *)\n(*   unfold caseSum. *)\n(*   eauto using caseSum_pctx_T with typing. *)\n(* Qed. *)\n\n(* Lemma caseArr_pctx_T {Γ n} :  *)\n(*   ⟪ ⊢ caseArr_pctx n : Γ , UVal (S n) → Γ , UVal n ⇒ UVal n ⟫. *)\n(* Proof. *)\n(*   unfold caseArr_pctx. *)\n(*   eauto with typing uval_typing. *)\n(* Qed. *)\n\n(* Lemma caseArr_T {Γ n t} :  *)\n(*   ⟪ Γ ⊢ t : UVal (S n) ⟫ → ⟪ Γ ⊢ caseArr n t : UVal n ⇒ UVal n ⟫. *)\n(* Proof. *)\n(*   unfold caseArr. *)\n(*   eauto using caseArr_pctx_T with typing. *)\n(* Qed. *)\n\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/UValFI/UVal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.27380205565351945}}
{"text": "(** This file provides a construction to lift a PROP-level binary relation to\nits reflexive transitive closure. *)\nFrom iris.bi.lib Require Export fixpoint.\nFrom iris.proofmode Require Import tactics.\nFrom iris Require Import options.\n\n(* The sections add extra BI assumptions, which is only picked up with \"Type\"*. *)\nSet Default Proof Using \"Type*\".\n\nDefinition bi_rtc_pre `{!BiInternalEq PROP}\n    {A : ofeT} (R : A → A → PROP)\n    (x2 : A) (rec : A → PROP) (x1 : A) : PROP :=\n  (<affine> (x1 ≡ x2) ∨ ∃ x', R x1 x' ∗ rec x')%I.\n\nInstance bi_rtc_pre_mono `{!BiInternalEq PROP}\n    {A : ofeT} (R : A → A → PROP) `{NonExpansive2 R} (x : A) :\n  BiMonoPred (bi_rtc_pre R x).\nProof.\n  constructor; [|solve_proper].\n  iIntros (rec1 rec2) \"#H\". iIntros (x1) \"[Hrec | Hrec]\".\n  { by iLeft. }\n  iRight.\n  iDestruct \"Hrec\" as (x') \"[HP Hrec]\".\n  iDestruct (\"H\" with \"Hrec\") as \"Hrec\". eauto with iFrame.\nQed.\n\nDefinition bi_rtc `{!BiInternalEq PROP}\n    {A : ofeT} (R : A → A → PROP) (x1 x2 : A) : PROP :=\n  bi_least_fixpoint (bi_rtc_pre R x2) x1.\n\nInstance: Params (@bi_rtc) 3 := {}.\nTypeclasses Opaque bi_rtc.\n\nInstance bi_rtc_ne `{!BiInternalEq PROP} {A : ofeT} (R : A → A → PROP) :\n  NonExpansive2 (bi_rtc R).\nProof.\n  intros n x1 x2 Hx y1 y2 Hy. rewrite /bi_rtc Hx. f_equiv=> rec z.\n  solve_proper.\nQed.\n\nInstance bi_rtc_proper `{!BiInternalEq PROP} {A : ofeT} (R : A → A → PROP)\n  : Proper ((≡) ==> (≡) ==> (⊣⊢)) (bi_rtc R).\nProof. apply ne_proper_2. apply _. Qed.\n\nSection bi_rtc.\n  Context `{!BiInternalEq PROP}.\n  Context {A : ofeT}.\n  Context (R : A → A → PROP) `{NonExpansive2 R}.\n\n  Lemma bi_rtc_unfold (x1 x2 : A) :\n    bi_rtc R x1 x2 ≡ bi_rtc_pre R x2 (λ x1, bi_rtc R x1 x2) x1.\n  Proof. by rewrite /bi_rtc; rewrite -least_fixpoint_unfold. Qed.\n\n  Lemma bi_rtc_strong_ind_l x2 Φ :\n    NonExpansive Φ →\n    □ (∀ x1, <affine> (x1 ≡ x2) ∨ (∃ x', R x1 x' ∗ (Φ x' ∧ bi_rtc R x' x2)) -∗ Φ x1) -∗\n    ∀ x1, bi_rtc R x1 x2 -∗ Φ x1.\n Proof.\n    iIntros (?) \"#IH\". rewrite /bi_rtc.\n    by iApply (least_fixpoint_strong_ind (bi_rtc_pre R x2) with \"IH\").\n  Qed.\n\n  Lemma bi_rtc_ind_l x2 Φ :\n    NonExpansive Φ →\n    □ (∀ x1, <affine> (x1 ≡ x2) ∨ (∃ x', R x1 x' ∗ Φ x') -∗ Φ x1) -∗\n    ∀ x1, bi_rtc R x1 x2 -∗ Φ x1.\n  Proof.\n    iIntros (?) \"#IH\". rewrite /bi_rtc.\n    by iApply (least_fixpoint_ind (bi_rtc_pre R x2) with \"IH\").\n  Qed.\n\n  Lemma bi_rtc_refl x : ⊢ bi_rtc R x x.\n  Proof. rewrite bi_rtc_unfold. by iLeft. Qed.\n\n  Lemma bi_rtc_l x1 x2 x3 : R x1 x2 -∗ bi_rtc R x2 x3 -∗ bi_rtc R x1 x3.\n  Proof.\n    iIntros \"H1 H2\".\n    iEval (rewrite bi_rtc_unfold /bi_rtc_pre). iRight.\n    iExists x2. iFrame.\n  Qed.\n\n  Lemma bi_rtc_once x1 x2 : R x1 x2 -∗ bi_rtc R x1 x2.\n  Proof. iIntros \"H\". iApply (bi_rtc_l with \"H\"). iApply bi_rtc_refl. Qed.\n\n  Lemma bi_rtc_trans x1 x2 x3 : bi_rtc R x1 x2 -∗ bi_rtc R x2 x3 -∗ bi_rtc R x1 x3.\n  Proof.\n    iRevert (x1).\n    iApply bi_rtc_ind_l.\n    { solve_proper. }\n    iIntros \"!>\" (x1) \"[H | H] H2\".\n    { by iRewrite \"H\". }\n    iDestruct \"H\" as (x') \"[H IH]\".\n    iApply (bi_rtc_l with \"H\").\n    by iApply \"IH\".\n  Qed.\n\nEnd bi_rtc.\n", "meta": {"author": "SkySkimmer", "repo": "iris", "sha": "186d9ece07e210e92be28eb0e1a42f5d5fe6f1b5", "save_path": "github-repos/coq/SkySkimmer-iris", "path": "github-repos/coq/SkySkimmer-iris/iris-186d9ece07e210e92be28eb0e1a42f5d5fe6f1b5/theories/bi/lib/relations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.27380204863356905}}
{"text": "Require Import Metalib.Metatheory.\nRequire Import Metalib.LibTactics.\nRequire Import Coq.Program.Equality.\nRequire Import Coq.Program.Tactics.\nRequire Import Strings.String.\nRequire Import Lia.\n\nRequire Import Language.\nRequire Import Tactical.\nRequire Import Subtyping.Subtyping.\nRequire Import Subtyping.Splitable.\nRequire Import Subtyping.Toplike.\nRequire Import Appsub.\n\nRequire Import Value.\nRequire Import Disjoint.\nRequire Import PrincipalTyping.\nRequire Import Consistent.\nRequire Import Typing.\nRequire Import Casting.\nRequire Import LocallyNameless.\nRequire Import Application.\n\n(** * Definition *)\n\nInductive step : term -> term -> Prop :=\n| St_Lit : forall n,\n    step (Lit n) (Ann (Lit n) Int)\n| St_Lam : forall e A B,\n    step (Lam A e B) (Ann (Lam A e B) (Arr A B))\n| St_Spl : forall p A A1 A2,\n    pvalue p ->\n    splitable A A1 A2 ->\n    step (Ann p A) (Mrg (Ann p A1) (Ann p A2))\n| St_App : forall f v e,\n    value f -> value v ->\n    papp f (Av v) e ->\n    step (App f v) e\n| St_Prj : forall l v e,\n    value v ->\n    papp v (Al l) e ->\n    step (Prj v l) e    \n| St_Val : forall v v' A,\n    value v ->\n    casting v A v' ->\n    step (Ann v A) v'\n| St_Ann : forall e e' A,\n    not (pvalue e) ->\n    step e e' ->\n    step (Ann e A) (Ann e' A)\n| St_App_L : forall e1 e1' e2,\n    lc e2 ->\n    step e1 e1' ->\n    step (App e1 e2) (App e1' e2)\n| St_App_R : forall v e2 e2',\n    value v ->\n    step e2 e2' ->\n    step (App v e2) (App v e2')\n| St_Rcd : forall l e e',\n    step e e' ->\n    step (Fld l e) (Fld l e')\n| St_Prj_L : forall e e' l,\n    step e e' ->\n    step (Prj e l) (Prj e' l)\n| St_Mrg : forall e1 e1' e2 e2',\n    step e1 e1' ->\n    step e2 e2' ->\n    step (Mrg e1 e2) (Mrg e1' e2')         \n| St_Mrg_L : forall e1 v e1',\n    value v ->\n    step e1 e1' ->\n    step (Mrg e1 v) (Mrg e1' v)\n| St_Mrg_R : forall v e2 e2',\n    value v ->\n    step e2 e2' ->\n    step (Mrg v e2) (Mrg v e2').\n\nHint Constructors step : core.\n\nNotation \"e ⟾ e'\" := (step e e') (at level 68).\n\n(** * Value *)\n\nLemma value_no_step :\n  forall v,\n    value v -> forall e, ~ step v e.\nProof.\n  introv Val.\n  induction v; intros; eauto.\n  - intros St.\n    dependent destruction Val. dependent destruction St; eauto.\n    + eapply IHv1; eauto.\n    + eapply IHv1; eauto.\n    + eapply IHv2; eauto.\n  - dependent destruction Val.\n    destruct H.\n    + intros St. dependent destruction St; eauto.\n    + intros St. dependent destruction St; eauto.\n  - intros St.\n    dependent destruction St.\n    dependent destruction Val.\n    pose proof (IHv Val e'). contradiction.\nQed.\n\nLemma step_lc :\n  forall e e',\n    lc e -> step e e' -> lc e'.\nProof.\n  introv Lc St. gen e'.\n  induction Lc; intros;\n    try solve [dependent destruction St; eauto 3].\n  - dependent destruction St. eapply Lc_Ann. eapply Lc_Lam; eauto.\n  - Case \"App\".\n    dependent destruction St; try solve [econstructor; eauto].\n    pose proof (papp_lc_v e1 e2 e). eauto 3.\n  - dependent destruction St; econstructor; eauto.\n  - dependent destruction St.\n    + econstructor; eapply Lc_Ann; eapply lc_pvalue; eauto.\n    + eapply casting_lc; eauto.\n    + econstructor. eauto.\n  - dependent destruction St. econstructor. eauto.\n  - Case \"Prj\".\n    dependent destruction St; try solve [econstructor; eauto].\n    pose proof (papp_lc_l e l e0). eauto 3.\nQed.\n\nLemma step_uvalue :\n  forall u u',\n    uvalue u -> step u u' -> uvalue u'.\nProof.\n  introv Uv St. gen u'.\n  induction Uv; intros.\n  - dependent destruction St; eauto.\n    eapply Uv_Ann. eapply step_lc; eauto.\n  - dependent destruction St; eauto.\n  - dependent destruction St; eauto.\nQed.\n\nHint Resolve step_uvalue : core.\n\n(** * Determinism *)\n\nSection determinism.\n\nLtac solver1 := try solve [match goal with\n                           | [Val: value ?v, St: step ?v _ |- _] =>\n                               (pose proof (value_no_step _ Val _ St); contradiction)\n                           end].\n\nTheorem determinism:\n  forall e e1 e2 A,\n    typing nil e Inf A ->\n    step e e1 -> step e e2 -> e1 = e2.\nProof.\n  introv Typ St1 St2. gen e2 A.\n  dependent induction St1; intros.\n  - dependent destruction St2; eauto.\n  - dependent destruction St2; eauto.\n  - dependent destruction St2; eauto.\n    subst_splitable. reflexivity.\n  - dependent destruction St2; solver1.\n    dependent destruction Typ.\n    pose proof (papp_determinism_v f v e e0).\n    eapply psub_sound_appsub in H5. eauto.\n  - dependent destruction St2; solver1.\n    dependent destruction Typ.\n    eapply psub_sound_appsub in H3; eauto.\n    pose proof (papp_determinism_l v l e e0). eauto.\n  - dependent destruction St2; eauto; solver1.\n    dependent destruction Typ.\n    dependent destruction Typ.\n    eapply casting_determinism; eauto.\n  - dependent destruction St2; eauto; solver1.\n    f_equal. dependent destruction Typ.\n    dependent destruction Typ; eauto.\n  - dependent destruction St2; solver1.\n    f_equal. dependent destruction Typ; eauto.\n  - dependent destruction St2; solver1.\n    f_equal. dependent destruction Typ; eauto.\n  - dependent destruction St2; solver1.\n    dependent destruction Typ;\n      f_equal; eauto.\n  - dependent destruction St2; solver1.\n    dependent destruction Typ;\n      f_equal; eauto.\n  - dependent destruction St2; solver1.\n    dependent destruction Typ;\n      f_equal; eauto.\n  - dependent destruction St2; solver1.\n    dependent destruction Typ;\n      f_equal; eauto.\n  - dependent destruction St2; solver1.\n    dependent destruction Typ;\n      f_equal; eauto.\nQed.\n\nTheorem determinism_gen :\n  forall e e1 e2 A dir,\n    typing nil e dir A ->\n    step e e1 -> step e e2 -> e1 = e2.\nProof.\n  introv Typ St1 St2.\n  destruct dir.\n  - eapply determinism; eauto.\n  -  dependent destruction Typ.\n     eapply determinism; eauto.\nQed.\n\nEnd determinism.\n\n(** * Consistent *)\n\nInductive step_or_value : term -> term -> Prop :=\n| Sv_V : forall v, value v -> step_or_value v v\n| Sv_S : forall e1 e2, step e1 e2 -> step_or_value e1 e2.\n\nHint Constructors step_or_value : core.\n\nLemma size_term_lg_z :\n  forall e, size_term e > 0.\nProof.\n  introv.\n  dependent induction e; try solve [eauto | simpl; lia].\nQed.\n\nHint Resolve size_term_lg_z : core.\n\nLemma size_term_lg_z_any1 :\n  forall e1 e2,\n    size_term e1 < (size_term e2 + size_term e1).\nProof.\n  introv.\n  assert (size_term e2 > 0). eapply size_term_lg_z.\n  lia.\nQed.\n\nLemma size_term_lg_z_any2 :\n  forall e1 e2,\n    size_term e1 < (size_term e1 + size_term e2).\nProof.\n  introv.\n  assert (size_term e2 > 0). eapply size_term_lg_z.\n  lia.\nQed.\n\nHint Resolve size_term_lg_z_any1 : core.\nHint Resolve size_term_lg_z_any2 : core.\n\nSection step_consistent.\n\nLtac solver1 := match goal with\n                | [St: step (Ann (Lam _ _ _) _) _ |- _] => (dependent destruction St; eauto)\n                end.\n\nLtac solver2 := match goal with\n                | [St: step (Ann _ _) _ |- _] => (dependent destruction St; eauto)\n                end.\n\nLtac solver3 := match goal with\n                | [Val: value ?v, St: step ?v _ |- _] =>\n                    (pose proof (value_no_step _ Val _ St); contradiction)\n                end.\n\nLtac solver4 IHC IH :=\n  eapply IHC; eauto; intros; match goal with\n                             | St: step ?e ?e' |- _ => eapply (IH e e'); eauto; simpl; lia\n                             end.\n\nLemma step_consistent :\n  forall e1 e2 e1' e2' A B,\n    uvalue e1 -> uvalue e2 ->\n    typing nil e1 Inf A -> typing nil e2 Inf B ->\n    consistent e1 e2 ->\n    step_or_value e1 e1' -> step_or_value e2 e2' ->\n    (forall e e' A, size_term e < (size_term e1 + size_term e2) ->\n        typing nil e Inf A -> step e e' -> (exists C, typing nil e' Inf C /\\ isosub C A)) ->\n    consistent e1' e2'.\nProof.\n  introv Uv1 Uv2 Typ1 Typ2 Con Sv1 Sv2 IH. gen A B e1' e2'.\n  dependent induction Con; intros; eauto.\n  - Case \"Lam Lam\".\n    dependent destruction Sv1; dependent destruction Sv2; eauto; try solve [solver1].\n    dependent destruction Typ1. dependent destruction Typ2.\n    solver1. solver1. eapply Con_Mrg_L; eauto.\n  - Case \"Anno Anno\".\n    dependent destruction Sv1; dependent destruction Sv2; eauto; try solve [solver2].\n    dependent destruction Typ1. dependent destruction Typ2.\n    solver2.\n    * solver2. eapply Con_Mrg_L; eauto.\n    * solver2; try solve [solver3].\n      dependent destruction Typ1.\n      pose proof (casting_preservation e v' B0 A) as Cp1.\n      dependent destruction Typ2.\n      pose proof (casting_preservation e v'0 B A0) as Cp2.\n      destruct Cp1; destruct Cp2; eauto. destruct_conjs.\n      eapply casting_consistent; eauto.      \n    * solver2; try solve [solver3].\n      dependent destruction Typ1. dependent destruction Typ2.\n      assert (e' = e'0). eapply determinism; eauto. subst. econstructor; eauto.\n      eapply step_lc; eauto.\n  - Case \"Rcd Rcd\".\n    dependent destruction Uv1. dependent destruction Uv2.\n    dependent destruction Typ1. dependent destruction Typ2.\n    dependent destruction Sv1; dependent destruction Sv2; eauto.\n    + match goal with\n      | St: step _ _, Val: value (Fld _ _) |- _ => dependent destruction St; dependent destruction Val\n      end.\n      eapply Con_Rcd. eapply IHCon; eauto 3. intros. eapply (IH e e'0); eauto. simpl in *. lia.\n    + match goal with\n      | St: step _ _, Val: value (Fld _ _) |- _ => dependent destruction St; dependent destruction Val\n      end.\n      eapply Con_Rcd. eapply IHCon; eauto 3. intros. eapply (IH e e'0); eauto. simpl in *. lia.\n    + match goal with\n      | St1: step _ _, St2: step _ _ |- _ => dependent destruction St1; dependent destruction St2\n      end.\n      eapply Con_Rcd. eapply IHCon; eauto 3. intros. eapply (IH e e'1); eauto. simpl in *. lia.\n  - Case \"Disjoint\".    \n    dependent destruction Sv1; dependent destruction Sv2; eauto.\n    + pose proof (step_uvalue _ _ Uv2 H3).\n      eapply IH in H3; eauto; try lia.\n      destruct H3 as [x Typ]; destruct Typ as [Typ Isub].\n      eapply typing_to_ptype in Typ; eauto.\n      eapply typing_to_ptype in Typ2; eauto. subst_ptype.\n      eapply Con_Dj; eauto. eapply disjoint_iso_l; eauto.\n    + pose proof (step_uvalue _ _ Uv1 H2).\n      eapply IH in H2; eauto; try lia.\n      destruct H2 as [x Typ]; destruct Typ as [Typ Isub].\n      eapply typing_to_ptype in Typ; eauto.\n      eapply typing_to_ptype in Typ1; eauto. subst_ptype.\n      eapply Con_Dj; eauto. eapply disjoint_iso_l; eauto.\n    + pose proof (step_uvalue _ _ Uv1 H2).\n      pose proof (step_uvalue _ _ Uv2 H3).\n      eapply IH in H2; eauto; try lia.\n      eapply IH in H3; eauto; try lia.\n      destruct_conjs.\n      eapply typing_to_ptype in Typ1; eauto.\n      eapply typing_to_ptype in Typ2; eauto. repeat subst_ptype.\n      eapply Con_Dj; eauto. eapply disjoint_iso_l; eauto.\n  - Case \"Merge L\".\n    dependent destruction Sv1; eauto 3.\n    + dependent destruction Typ1;\n        eapply Con_Mrg_L; try solve [solver4 IHCon1 IH | solver4 IHCon2 IH].\n    + dependent destruction Typ1;\n        match goal with\n        | St: step (Mrg _ _) _ |- _ => dependent destruction St\n        end; eapply Con_Mrg_L; try solve [solver4 IHCon1 IH | solver4 IHCon2 IH].\n  - Case \"Merge R\".\n    dependent destruction Sv2; eauto 3.\n    + dependent destruction Typ2;\n        eapply Con_Mrg_R; try solve [solver4 IHCon1 IH | solver4 IHCon2 IH].\n    + dependent destruction Typ2;\n        match goal with\n        | St: step (Mrg _ _) _ |- _ => dependent destruction St\n        end; eapply Con_Mrg_R; try solve [solver4 IHCon1 IH | solver4 IHCon2 IH].\nQed.\n    \nEnd step_consistent.\n\n(** * Preservation *)\n\nLtac ind_term_size s :=\n  assert (SizeInd: exists i, s < i) by eauto;\n  destruct SizeInd as [i SizeInd];\n  repeat match goal with | [ h : term |- _ ] => (gen h) end;\n  induction i as [|i IH]; [\n      intros; match goal with | [ H : _ < 0 |- _ ] => (dependent destruction H) end\n    | intros ].\n\nTheorem preservation :\n  forall e e' A,\n    typing nil e Inf A ->\n    step e e' ->\n    (exists B, typing nil e' Inf B /\\ isosub B A).\nProof.\n  introv Typ St. gen e' A.\n  ind_term_size (size_term e). (* shelved item *)\n  dependent destruction Typ; simpl in SizeInd.\n  - Case \"Lit\".\n    dependent destruction St; eauto.\n    exists Int; eauto.\n  - Case \"Var\".\n    dependent destruction St.\n  - Case \"Lam\".\n    dependent destruction St; eauto.\n    exists (Arr A B). split; eauto.\n  - Case \"Rcd\".\n    dependent destruction St; eauto.\n    exploit (IH e); eauto; try lia. intros IH'. destruct_conjs.\n    eexists. split; eauto.\n  - Case \"Ann\".\n    dependent destruction St.\n    + SCase \"Split\".\n      dependent destruction Typ.\n      exists (And A1 A2). split; eauto.\n      pose proof (sub_inv_splitable_r A B A1 A2) as Sub. destruct Sub; eauto.\n      eapply Ty_Mrg_Uv; eauto.\n    + SCase \"Value\".\n      dependent destruction Typ.\n      eapply casting_preservation; eauto.\n    + SCase \"Ann\".\n      dependent destruction Typ.\n      eapply IH in St; eauto; try lia.\n      destruct St as [C Typ']. destruct Typ' as [Typ'1 Typ'2].\n      pose proof (isosub_to_sub1 _ _ Typ'2).\n      exists B. split; eauto. eapply Ty_Ann; eauto; try solve [eapply sub_transitivity; eauto].\n      eapply Ty_Sub; eauto. eapply sub_transitivity; eauto.     \n  - Case \"App\".\n    dependent destruction St.\n    + pose proof (papp_preservation_v e1 e2 e) as P.\n      eapply P; eauto. eapply psub_sound_appsub; eauto.\n    + eapply IH in St; eauto; try lia. destruct_conjs.\n      eapply psub_sound_appsub in H0.\n      eapply appsub_iso_v in H0; eauto. destruct_conjs.\n      eexists. split; eauto.\n     eapply Ty_App; eauto. eapply psub_complete_appsub; eauto.\n    + eapply IH in St; eauto; try lia. destruct_conjs.\n      eapply psub_sound_appsub in H0.\n      eapply appsub_iso_v in H0; eauto. destruct_conjs.\n      eexists. split; eauto.\n      eapply Ty_App; eauto. eapply psub_complete_appsub; eauto.\n  - Case \"Prj\".\n    dependent destruction St.\n    + pose proof (papp_preservation_l e l e0) as P.\n      eapply P; eauto.\n      eapply psub_sound_appsub; eauto.\n    + eapply IH in St; eauto; try lia. destruct_conjs.\n      eapply psub_sound_appsub in H.\n      eapply appsub_iso_l in H; eauto. destruct_conjs.\n      eexists; split; eauto.\n      eapply Ty_Prj; eauto. eapply psub_complete_appsub; eauto.\n  - Case \"Merge\".\n    dependent destruction St.\n    + eapply IH in St1; eauto; try lia.\n      eapply IH in St2; eauto; try lia. destruct_conjs.      \n      eapply disjoint_iso_l in H; eauto.\n    + eapply IH in St; eauto; try lia. destruct_conjs.\n      eapply disjoint_iso_l in H0; eauto.\n    + eapply IH in St; eauto; try lia. destruct_conjs.\n      eapply disjoint_iso_l in H0; eauto.\n  - Case \"Merge U\".\n    dependent destruction St.    \n    + (* TODO: Automation *)\n      assert (exists C, (typing nil e1' Inf C) /\\ (isosub C A)) by (eapply IH; eauto; lia).\n      assert (exists C, (typing nil e2' Inf C) /\\ (isosub C B)) by (eapply IH; eauto; lia).\n      destruct_conjs. exists (And H3 H4).\n      pose proof (step_uvalue _ _ H0 St1).\n      pose proof (step_uvalue _ _ H1 St2).\n      split; eauto. eapply Ty_Mrg_Uv; eauto.\n      pose proof (Sv_S _ _ St1) as Sov1.\n      pose proof (Sv_S _ _ St2) as Sov2.\n      pose proof (step_consistent u1 u2 e1' e2' A B H0 H1 Typ1 Typ2 H2 Sov1 Sov2) as Sc.\n      eapply Sc. intros. eapply IH; eauto. lia.\n    + assert (exists C, (typing nil e1' Inf C) /\\ (isosub C A)) by (eapply IH; eauto; lia).\n      destruct_conjs. exists (And H4 B).\n      pose proof (step_uvalue _ _ H1 St).\n      split; eauto. eapply Ty_Mrg_Uv; eauto.\n      pose proof (Sv_S _ _ St) as Sov1.\n      pose proof (Sv_V _ H) as Sov2.\n      pose proof (step_consistent u1 u2 e1' u2 A B H1 H2 Typ1 Typ2 H3 Sov1 Sov2) as Sc.\n      eapply Sc; eauto. intros. eapply IH; eauto. lia.\n    + assert (exists C, (typing nil e2' Inf C) /\\ (isosub C B)) by (eapply IH; eauto; lia).\n      destruct_conjs. exists (And A H4).\n      pose proof (step_uvalue _ _ H2 St).\n      split; eauto. eapply Ty_Mrg_Uv; eauto.\n      pose proof (Sv_V _ H) as Sov1.\n      pose proof (Sv_S _ _ St) as Sov2.\n      pose proof (step_consistent u1 u2 u1 e2' A B H1 H2 Typ1 Typ2 H3 Sov1 Sov2) as Sc.\n      eapply Sc; eauto. intros. eapply IH; eauto. lia.\n      Unshelve. eauto.\nQed.\n\nTheorem preservation_chk :\n  forall e e' A,\n    typing nil e Chk A ->\n    step e e' ->\n    typing nil e' Chk A.\nProof.\n  introv Typ St.\n  dependent destruction Typ.\n  pose proof (preservation _ _ _ Typ St). destruct_conjs.\n  eapply Ty_Sub; eauto. eapply isosub_to_sub1 in H2. eapply sub_transitivity; eauto.\nQed.\n\nTheorem preservation_gen :\n  forall e e' A dir,\n    typing nil e dir A ->\n    step e e' ->\n    typing nil e' Chk A.\nProof.\n  introv Typ St.\n  destruct dir.\n  - pose proof (preservation _ _ _ Typ St). destruct_conjs.\n    eapply Ty_Sub; eauto. eapply isosub_to_sub1 in H1. auto.\n  - eapply preservation_chk; eauto.\nQed.\n\n(** * Progress *)\n\nTheorem progress :\n  forall e A dir,\n    typing nil e dir A ->\n    value e \\/ exists e', step e e'.\nProof.\n  introv Typ.\n  dependent induction Typ; eauto 3.\n  - Case \"Rcd\".\n    destruct IHTyp as [Val | St] ; eauto.\n    right. destruct St. exists (Fld l x); eauto.    \n  - Case \"Anno\".\n    destruct IHTyp as [Val | St] ; eauto.\n    + right. eapply casting_progress in Typ; eauto. destruct Typ.\n      exists x. eapply St_Val; eauto.\n    + destruct (pvalue_decidable e) as [Pv | nPv];\n        destruct (splitable_or_ordinary A) as [Spl | Ord]; eauto.\n      * destruct Pv; right; destruct_conjs; eexists; eauto.\n      * destruct St. right. eexists; eauto.\n      * destruct St. right. eexists; eauto.\n  - Case \"App\".\n    right. destruct IHTyp1; destruct IHTyp2; eauto 3; try solve [destruct_conjs; eauto].\n    pose proof (papp_progress_v e1 e2 A B C) as Pa. destruct Pa; eauto.\n    eapply psub_sound_appsub; eauto.\n  - Case \"Prj\".\n    right. destruct IHTyp; eauto 3; try solve [destruct_conjs; eauto].\n    pose proof (papp_progress_l e A B l) as Pa. destruct Pa; eauto.\n    eapply psub_sound_appsub; eauto.\n  - Case \"Merge\".\n    destruct IHTyp1; destruct IHTyp2; eauto 3; try solve [destruct_conjs; eauto].    \n  - Case \"Merge V\".\n    destruct IHTyp1; destruct IHTyp2; eauto 3; try solve [destruct_conjs; eauto].\nQed.\n\n(** * Soundness *)\n\nDefinition relation (X : Type) := X -> X -> Prop.\n\nInductive multi {X : Type} (R : relation X) : relation X :=\n| multi_refl : forall (x : X), multi R x x\n| multi_step : forall (x y z : X), R x y -> multi R y z -> multi R x z.\n\nNotation multistep := (multi step).\n\nDefinition normal_form {X : Type} (R : relation X) (e : X) : Prop :=\n  not (exists e', R e e').\n\nDefinition stuck (e : term) : Prop :=\n  (normal_form step) e /\\ ~ value e.\n\nCorollary soundness :\n  forall e e' A dir,\n    typing nil e dir A ->\n    multistep e e' ->\n    ~ (stuck e').\nProof.\n  introv Typ Mult. unfold stuck.\n  intros [Nf Nval]. unfold normal_form in Nf. gen A dir.\n  dependent induction Mult; intros.\n  - pose proof (progress _ _ _ Typ). destruct H; eauto.\n  - destruct dir.\n    + pose proof (preservation _ _ _ Typ H) as Prv.\n      destruct Prv. destruct H0.\n      eapply IHMult; eauto.\n    + pose proof (preservation_chk _ _ _ Typ H) as Prv.\n      dependent destruction Prv.\n      eapply IHMult; eauto.      \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/core+disjoint/Proof/Reduction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.273802048633569}}
{"text": "Require Import\n  Coq.Strings.String\n  Fiat.ADT\n  Fiat.ADTNotation.\n\nInductive processStartError : Set :=\n  | noSuchFile.\n  (* etc *)\n\nInductive processState : Set :=\n  | running : processState\n  | errored : processStartError -> processState\n  | reaped : processState.\n\nRecord processConf : Set := mkProcessConf\n  { prog : string\n  ; args : list string\n    (* should be a proper dictionary *)\n  ; env : list (string * string)\n  }.\n\n(* Obviously needs fleshing out *)\nDefinition exitStatus := unit.\n\nInductive StartProcessResult : processState -> Prop :=\n  | runningOk : StartProcessResult running\n  | erroredOk : forall x : processStartError, StartProcessResult (errored x).    \n\nDefinition ProcessSpec := Def ADT\n  { rep := processState\n\n  , Def Constructor1 \"startProcess\" (conf : processConf) : rep :=\n    x <- { st | StartProcessResult st };\n    ret x\n\n  ,,Def Method0 \"waitProcess\" (r : rep) : rep * exitStatus :=\n      st <- { x | True };\n      ret (reaped, st)\n  }%ADTParsing.\n", "meta": {"author": "shlevy", "repo": "service-runner", "sha": "14d3b4086840ac8d95edd4e92c49e114ebda6d03", "save_path": "github-repos/coq/shlevy-service-runner", "path": "github-repos/coq/shlevy-service-runner/service-runner-14d3b4086840ac8d95edd4e92c49e114ebda6d03/src/Process.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891307678321, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.273775482258674}}
{"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.prim.prim_constants.\nRequire Import CertiGraph.graph.SpaceUAdjMatGraph2.\nRequire Import CertiGraph.prim.prim_spec2.\n\nLocal Open Scope Z.\n\n\n(***********************VERIFICATION***********************)\n\nDefinition addresses := @nil val.\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\n  Lemma body_getCell: semax_body Vprog Gprog f_getCell getCell_spec.\n  Proof.\n    start_function.\n    unfold SpaceAdjMatGraph'.\n    assert (0 <= size) by lia.\n    assert (Forall (fun list : list Z => Zlength list = size) (@graph_to_mat size g eformat)). {\n      rewrite Forall_forall. intros.\n      unfold graph_to_mat in H3.\n      apply list_in_map_inv in H3. destruct H3 as [? [? _]].\n      subst x. unfold vert_to_list.\n      apply Zlength_map.\n    }\n    assert ((0 <= u * 8 + i < Zlength (map Int.repr (@graph_to_list size g eformat)))). {\n      rewrite Zlength_map, (graph_to_list_Zlength _ _ size); trivial.\n      rewrite <- size_eq.\n      split; [lia|].\n      replace size with (size - 1 + 1) at 2 by lia.\n      rewrite Z.mul_add_distr_r, Z.mul_1_l.\n      apply Z.add_le_lt_mono; try lia.\n      apply Zmult_le_compat_r; lia.\n    }\n    rewrite Zlength_map, (graph_to_list_Zlength _ _ size) in H4; trivial.\n    forward. forward. entailer!. f_equal. f_equal.\n    apply graph_to_list_to_mat; trivial; lia.\n  Qed.\n\nLemma body_initialise_list: semax_body Vprog Gprog f_initialise_list initialise_list_spec.\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 _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 f_prim prim_spec.\nProof.\nstart_function. rename H into Hprecon_1. rename H0 into Hprecon_2. rename H1 into Hprecon_3.\nassert (inf_repable: repable_signed inf). { red. pose proof (inf_representable g). rep_lia. }\nassert (Hsz: 0 < size <= Int.max_signed). { apply (size_representable g). }\nassert (Hsz2: size <= Int.max_signed). { lia. }\nassert (size_repable: repable_signed size). { unfold repable_signed. rep_lia. }\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*)\nforward_call (v_key, (repeat Vundef (Z.to_nat size)), inf).\nassert_PROP (Zlength (map (fun x : Z => Vint (Int.repr x)) garbage) = size). entailer!.\nforward_call (pointer_val_val parent_ptr, (map (fun x : Z => Vint (Int.repr x)) garbage), size).\nclear H garbage.\nforward_call (v_out, (repeat Vundef (Z.to_nat size)), 0).\nassert (Hrbound: 0 <= r < size). apply vert_bound in Hprecon_1; auto.\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: rewrite (upd_Znth_map (fun x => Vint (Int.repr x)) r (repeat inf (Z.to_nat size))); auto.\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.\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; lvar _out (tarray tint size) v_out;\n      lvar _key (tarray tint size) v_key; temp _graph (pointer_val_val gptr);\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_list size g eformat) (pointer_val_val gptr));\n      free_tok v_pq (sizeof tint * size)\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. rewrite inf_eq. 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 ,\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 _pq v_pq; lvar _out (tarray tint size) v_out;\n      temp _parent (pointer_val_val parent_ptr); lvar _key (tarray tint size) 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) (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_list size g eformat) (pointer_val_val gptr));\n      free_tok v_pq (sizeof tint * size)\n    )\n  )\nbreak: (\n  EX mst:G,\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; lvar _out (tarray tint size) v_out;\n      temp _parent (pointer_val_val parent_ptr); lvar _key (tarray tint size) 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_list size g eformat) (pointer_val_val gptr));\n      free_tok v_pq (sizeof tint * size)\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. auto. simpl; auto.\n    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(****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 (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\n  ). entailer!.\n  repeat rewrite Zlength_map in H. 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 [? ?]]. rewrite HZlength_pq_state in H. subst x.\n    rewrite Hinv_6. 2: lia. destruct (in_dec V_EqDec i popped_vertices). rep_lia.\n    rewrite Hinv_5. 2: lia. destruct (V_EqDec i r). auto.\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    rewrite HZlength_pq_state; lia. 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  }\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. lia.\n    apply fold_min_in_list. 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 (\n        temp _u (Vint (Int.repr u)); temp _t'2 (@isEmpty inf pq_state); temp _pq v_pq; lvar _out (tarray tint size) v_out;\n        temp _parent (pointer_val_val parent_ptr); lvar _key (tarray tint size) v_key; temp _graph (pointer_val_val gptr);\n        temp _r (Vint (Int.repr r))\n      )\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_list size g eformat) (pointer_val_val gptr));\n      free_tok v_pq (sizeof tint * size)\n      )\n    )\n  %assert.\n  (*precon*) {\n    Exists parents. Exists keys. Exists upd_pq_state. entailer!.\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.\n    apply weight_representable. 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  } 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      set (k:=Int.max_signed); compute in k; subst k. rewrite inf_eq in H8; lia. }\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    forward_call (v_pq, i, Znth i (Znth u (@graph_to_symm_mat size g)), pq_state').\n    replace (map (fun x : Z => Vint (Int.repr x)) pq_state') with (map Vint (map Int.repr pq_state')).\n    entailer!. rewrite list_map_compose. auto.\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    unfold SpaceAdjMatGraph'.\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    unfold SpaceAdjMatGraph'.\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. lia.\n      apply Hinv2_3. lia.\n      rewrite Z.min_r; lia.\n      replace (Znth i pq_state') with (Znth i upd_pq_state). rewrite H11. rewrite Z.min_r; lia. 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  unfold SpaceAdjMatGraph'.\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 [Hb 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 Hb.\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 Hb. 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  clear H9 H10 H11 H12 H13 H14 H15 H16 H17 H18 H19 H20 H21 H22 Pv_out HPv_out Pv_out0 Pv_key HPv_key Pv_key0.\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). rewrite inf_eq; 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). rewrite inf_eq; 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. rewrite HZlength_pq_state. auto. 2: auto.\n      destruct (V_EqDec x r). rewrite inf_eq in H3; 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. rewrite Zlength_repeat; lia.\n      intros. rewrite Zlength_repeat in H2 by lia.\n      rewrite Znth_repeat_inrange by lia. rewrite Znth_map. 2: rewrite Zlength_map; lia.\n      rewrite Znth_map by lia. rewrite Hinv_6 by 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    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}\nfreeze FR := (data_at _ _ _ v_out)\n               (data_at _ _ _ (pointer_val_val parent_ptr))\n               (data_at _ _ _ v_key)\n               (SpaceAdjMatGraph' _ _ _).\n        forward_call (Tsh, priq_ptr, size, (repeat (inf + 1) (Z.to_nat size))).\nentailer!.\nthaw FR.\nforward.\nExists mst fmst parents.\nTransparent size.\nentailer!.\nGlobal Opaque size.\n}\nQed.\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_prim2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.27377548225867393}}
{"text": "(* modified from iris.base_logic.lib.own *)\n\nFrom iris.algebra Require Import functions gmap proofmode_classes.\nFrom iris.base_logic Require Import algebra.\nFrom iris.proofmode Require Import classes.\nFrom iris_ora.algebra Require Import functions gmap.\nFrom iris_ora.logic Require Export iprop derived.\nImport bi oupred.ouPred ouPred.\nFrom iris.bi Require Export updates.\nFrom iris.prelude Require Import options.\n\nSection ora_transport.\n  Context {A B : ora} (H : A = B).\n  Notation T := (ora_transport H).\n  Lemma ora_transport_updateP (P : A → Prop) (Q : B → Prop) x :\n    x ~~>: P → (∀ y, P y → Q (T y)) → T x ~~>: Q.\n  Proof. destruct H; eauto using cmra_updateP_weaken. Qed.\n  Lemma ora_transport_updateP' (P : A → Prop) x :\n    x ~~>: P → T x ~~>: λ y, ∃ y', y = ora_transport H y' ∧ P y'.\n  Proof. eauto using ora_transport_updateP. Qed.\nEnd ora_transport.\n\n(** The class [inG Σ A] expresses that the ORA [A] is in the list of functors\n[Σ]. This class is similar to the [subG] class, but written down in terms of\nindividual ORAs instead of (lists of) ORA *functors*. This additional class is\nneeded because Coq is otherwise unable to solve type class constraints due to\nhigher-order unification problems. *)\nClass inG (Σ : gFunctors) (A : ora) := InG {\n  inG_id : gid Σ;\n  inG_apply := OrarFunctor_apply (gFunctors_lookup Σ inG_id);\n  inG_prf : A = inG_apply (iPropO Σ) _;\n}.\nGlobal Arguments inG_id {_ _} _.\nGlobal Arguments inG_apply {_ _} _ _ {_}.\n\n(** We use the mode [-] for [Σ] since there is always a unique [Σ]. We use the\nmode [!] for [A] since we can have multiple [inG]s for different [A]s, so we do\nnot want Coq to pick one arbitrarily. *)\nGlobal Hint Mode inG - ! : typeclass_instances.\n\nLemma subG_inG Σ (F : gFunctor) : subG F Σ → inG Σ (OrarFunctor_apply F (iPropO Σ)).\nProof. move=> /(_ 0%fin) /= [j ->]. by exists j. Qed.\n\n(** This tactic solves the usual obligations \"subG ? Σ → {in,?}G ? Σ\" *)\nLtac solve_inG :=\n  (* Get all assumptions *)\n  intros;\n  (* Unfold the top-level xΣ. We need to support this to be a function. *)\n  lazymatch goal with\n  | H : subG (?xΣ _ _ _ _) _ |- _ => try unfold xΣ in H\n  | H : subG (?xΣ _ _ _) _ |- _ => try unfold xΣ in H\n  | H : subG (?xΣ _ _) _ |- _ => try unfold xΣ in H\n  | H : subG (?xΣ _) _ |- _ => try unfold xΣ in H\n  | H : subG ?xΣ _ |- _ => try unfold xΣ in H\n  end;\n  (* Take apart subG for non-\"atomic\" lists *)\n  repeat match goal with\n         | H : subG (gFunctors.app _ _) _ |- _ => apply subG_inv in H; destruct H\n         end;\n  (* Try to turn singleton subG into inG; but also keep the subG for typeclass\n     resolution -- to keep them, we put them onto the goal. *)\n  repeat match goal with\n         | H : subG _ _ |- _ => move:(H); (apply subG_inG in H || clear H)\n         end;\n  (* Again get all assumptions and simplify the functors *)\n  intros; simpl in *;\n  (* We support two kinds of goals: Things convertible to inG;\n     and records with inG and typeclass fields. Try to solve the\n     first case. *)\n  try assumption;\n  (* That didn't work, now we're in for the second case. *)\n  split; (assumption || by apply _).\n\n(** * Definition of the connective [own] *)\nLocal Definition inG_unfold {Σ A} {i : inG Σ A} :\n    inG_apply i (iPropO Σ) -n> inG_apply i (iPrePropO Σ) :=\n  orarFunctor_map _ (iProp_fold, iProp_unfold).\nLocal Definition inG_fold {Σ A} {i : inG Σ A} :\n    inG_apply i (iPrePropO Σ) -n> inG_apply i (iPropO Σ) :=\n  orarFunctor_map _ (iProp_unfold, iProp_fold).\n\nLocal Definition iRes_singleton {Σ A} {i : inG Σ A} (γ : gname) (a : A) : iResUR Σ :=\n  discrete_fun_singleton (inG_id i)\n    {[ γ := inG_unfold (ora_transport inG_prf a) ]}.\nGlobal Instance: Params (@iRes_singleton) 4 := {}.\n\nLocal Definition own_def `{!inG Σ A} (γ : gname) (a : A) : iProp Σ :=\n  ouPred_ownM (iRes_singleton γ a).\nLocal Definition own_aux : seal (@own_def). Proof. by eexists. Qed.\nDefinition own := own_aux.(unseal).\nGlobal Arguments own {Σ A _} γ a.\nLocal Definition own_eq : @own = @own_def := own_aux.(seal_eq).\nLocal Instance: Params (@own) 4 := {}.\n\n(** * Properties about ghost ownership *)\nSection global.\nContext `{i : !inG Σ A}.\nImplicit Types a : A.\n\n(** ** Properties of [iRes_singleton] *)\nLocal Lemma inG_unfold_fold (x : inG_apply i (iPrePropO Σ)) :\n  inG_unfold (inG_fold x) ≡ x.\nProof.\n  rewrite /inG_unfold /inG_fold -orarFunctor_map_compose -{2}[x]orarFunctor_map_id.\n  apply (ne_proper (orarFunctor_map _)); split=> ?; apply iProp_unfold_fold.\nQed.\nLocal Lemma inG_fold_unfold (x : inG_apply i (iPropO Σ)) :\n  inG_fold (inG_unfold x) ≡ x.\nProof.\n  rewrite /inG_unfold /inG_fold -orarFunctor_map_compose -{2}[x]orarFunctor_map_id.\n  apply (ne_proper (orarFunctor_map _)); split=> ?; apply iProp_fold_unfold.\nQed.\nLocal Lemma inG_unfold_validN n (x : inG_apply i (iPropO Σ)) :\n  ✓{n} (inG_unfold x) ↔ ✓{n} x.\nProof.\n  split; [|apply (ora_morphism_validN _)].\n  move=> /(ora_morphism_validN inG_fold). by rewrite inG_fold_unfold.\nQed.\n\nLocal Instance iRes_singleton_ne γ : NonExpansive (@iRes_singleton Σ A _ γ).\nProof. by intros n a a' Ha; apply discrete_fun_singleton_ne; rewrite Ha. Qed.\nLocal Lemma iRes_singleton_validI γ a : ✓ (iRes_singleton γ a) ⊢@{iPropI Σ} ✓ a.\nProof.\n  rewrite /iRes_singleton.\n  rewrite discrete_fun_validI (forall_elim (inG_id i)) discrete_fun_lookup_singleton.\n  rewrite singleton_validI.\n  trans (✓ ora_transport inG_prf a : iProp Σ)%I; last by destruct inG_prf.\n  apply valid_entails=> n. apply inG_unfold_validN.\nQed.\nLocal Lemma iRes_singleton_op γ a1 a2 :\n  iRes_singleton γ (a1 ⋅ a2) ≡ iRes_singleton γ a1 ⋅ iRes_singleton γ a2.\nProof.\n  rewrite /iRes_singleton discrete_fun_singleton_op singleton_op ora_transport_op.\n  f_equiv. apply: singletonM_proper. by rewrite (ora_morphism_op _).\nQed.\n\nLocal Instance iRes_singleton_discrete γ a :\n  Discrete a → Discrete (iRes_singleton γ a).\nProof.\n  intros ?. rewrite /iRes_singleton.\n  apply (discrete_fun_singleton_discrete(B := λ x, uora_ucmraR _)), gmap_singleton_discrete; [apply _|].\n  intros x Hx. assert (ora_transport inG_prf a ≡ inG_fold x) as Ha.\n  { apply (discrete _). by rewrite -Hx inG_fold_unfold. }\n  by rewrite Ha inG_unfold_fold.\nQed.\nLocal Instance iRes_singleton_core_id γ a :\n  OraCoreId a → OraCoreId (iRes_singleton γ a).\nProof.\n  intros. apply discrete_fun_singleton_core_id, gmap_singleton_core_id.\n  by rewrite /OraCoreId -ora_morphism_pcore oracore_id.\nQed.\n\nLocal Lemma later_internal_eq_iRes_singleton γ a r :\n  ▷ (r ≡ iRes_singleton γ a) ⊢@{iPropI Σ}\n  ◇ ∃ b r', r ≡ iRes_singleton γ b ⋅ r' ∧ ▷ (a ≡ b).\nProof.\n  assert (NonExpansive (λ r : iResUR Σ, r (inG_id i) !! γ)).\n  { intros n r1 r2 Hr. f_equiv. by specialize (Hr (inG_id i)). }\n  rewrite (f_equivI (λ r : iResUR Σ, r (inG_id i) !! γ) r).\n  rewrite {1}/iRes_singleton discrete_fun_lookup_singleton lookup_singleton.\n  rewrite option_equivI. case Hb: (r (inG_id _) !! γ)=> [b|]; last first.\n  { by rewrite /bi_except_0 -or_intro_l. }\n  rewrite -except_0_intro.\n  rewrite -(exist_intro (ora_transport (eq_sym inG_prf) (inG_fold b))).\n  rewrite -(exist_intro (discrete_fun_insert (inG_id _) (delete γ (r (inG_id i))) r)).\n  apply and_intro.\n  - apply equiv_internal_eq. rewrite /iRes_singleton.\n    rewrite ora_transport_trans eq_trans_sym_inv_l /=.\n    intros i'. rewrite discrete_fun_lookup_op.\n    destruct (decide (i' = inG_id i)) as [->|?].\n    + rewrite discrete_fun_lookup_insert discrete_fun_lookup_singleton.\n      intros γ'. rewrite lookup_op. destruct (decide (γ' = γ)) as [->|?].\n      * by rewrite lookup_singleton lookup_delete Hb inG_unfold_fold.\n      * by rewrite lookup_singleton_ne // lookup_delete_ne // left_id.\n    + rewrite discrete_fun_lookup_insert_ne //.\n      by rewrite discrete_fun_lookup_singleton_ne // left_id.\n  - apply later_mono. rewrite (f_equivI inG_fold) inG_fold_unfold.\n    apply: (internal_eq_rewrite' _ _ (λ b, a ≡ ora_transport (eq_sym inG_prf) b)%I);\n      [solve_proper|apply internal_eq_sym|].\n    rewrite ora_transport_trans eq_trans_sym_inv_r /=. apply internal_eq_refl.\nQed.\n\n(** ** Properties of [own] *)\nGlobal Instance own_ne γ : NonExpansive (@own Σ A _ γ).\nProof. rewrite !own_eq. solve_proper. Qed.\nGlobal Instance own_proper γ :\n  Proper ((≡) ==> (⊣⊢)) (@own Σ A _ γ) := ne_proper _.\n\nLemma own_op γ a1 a2 : own γ (a1 ⋅ a2) ⊣⊢ own γ a1 ∗ own γ a2.\nProof. by rewrite !own_eq /own_def -ownM_op iRes_singleton_op. Qed.\nLemma own_mono γ a1 a2 : a2 ≼ₒ a1 → own γ a1 ⊢ own γ a2.\nProof. rewrite !own_eq /own_def /iRes_singleton. intros; apply ownM_mono.\n  intros ?. destruct (decide (x = inG_id i)); last by rewrite !discrete_fun_lookup_singleton_ne.\n  subst; rewrite !discrete_fun_lookup_singleton.\n  intros k; destruct (decide (γ = k)); last by rewrite !lookup_singleton_ne.\n  subst; rewrite !lookup_singleton /=.\n  apply ora_morphism_monotone; first by apply _.\n  by destruct inG_prf.\nQed.\n\nGlobal Instance own_mono' γ : Proper (flip (≼ₒ) ==> (⊢)) (@own Σ A _ γ).\nProof. intros a1 a2. apply own_mono. Qed.\n\nLemma own_valid γ a : own γ a ⊢ ✓ a.\nProof. by rewrite !own_eq /own_def ownM_valid iRes_singleton_validI. Qed.\nLemma own_valid_2 γ a1 a2 : own γ a1 -∗ own γ a2 -∗ ✓ (a1 ⋅ a2).\nProof. apply wand_intro_r. by rewrite -own_op own_valid. Qed.\nLemma own_valid_3 γ a1 a2 a3 : own γ a1 -∗ own γ a2 -∗ own γ a3 -∗ ✓ (a1 ⋅ a2 ⋅ a3).\nProof. do 2 apply wand_intro_r. by rewrite -!own_op own_valid. Qed.\nLemma own_valid_r γ a : own γ a ⊢ own γ a ∗ ✓ a.\nProof. apply: bi.persistent_entails_r. apply own_valid. Qed.\nLemma own_valid_l γ a : own γ a ⊢ ✓ a ∗ own γ a.\nProof. by rewrite comm -own_valid_r. Qed.\n\nGlobal Instance own_timeless γ a : Discrete a → Timeless (own γ a).\nProof. rewrite !own_eq /own_def. apply _. Qed.\nGlobal Instance own_core_persistent γ a : OraCoreId a → Persistent (own γ a).\nProof. rewrite !own_eq /own_def; apply _. Qed.\nGlobal Instance own_core_affine γ a : OraCoreId a → Affine (own γ a).\nProof. rewrite /Affine !own_eq /own_def.\n  intros. etrans; last apply ownM_unit_affine.\n  apply ownM_mono.\n  intros j k; simpl.\n  rewrite lookup_empty /= /iRes_singleton.\n  destruct (decide (j = inG_id i)); last by rewrite discrete_fun_lookup_singleton_ne.\n  subst; rewrite discrete_fun_lookup_singleton.\n  destruct (decide (γ = k)); last by rewrite !lookup_singleton_ne.\n  subst; rewrite !lookup_singleton /=.\n  apply ora_morphism_increasing; first by apply _.\n  intros ?.\n  destruct inG_prf; simpl.\n  inversion H as [?? Heq Hcore|]; subst.\n  rewrite -Heq; eapply ora_pcore_increasing; eauto.\nQed.\n\n(*Lemma later_own γ a : ▷ own γ a -∗ ◇ ∃ b, own γ b ∧ ▷ (a ≡ b).\nProof.\n  rewrite own_eq /own_def later_ownM. apply exist_elim=> r.\n  assert (NonExpansive (λ r : iResUR Σ, r (inG_id i) !! γ)).\n  { intros n r1 r2 Hr. f_equiv. by specialize (Hr (inG_id i)). }\n  rewrite internal_eq_sym later_internal_eq_iRes_singleton.\n  rewrite (except_0_intro (ouPred_ownM r)) -except_0_and. f_equiv.\n  rewrite and_exist_l. f_equiv=> b. rewrite and_exist_l. apply exist_elim=> r'.\n  rewrite assoc. apply and_mono_l.\n  etrans; [|apply ownM_mono].\n  - \n  eapply (internal_eq_rewrite' _ _ ouPred_ownM _); [apply and_elim_r|].\n  apply and_elim_l.\n  - simpl. Search or\nQed.*)\n\n(** ** Allocation *)\n(* TODO: This also holds if we just have ✓ a at the current step-idx, as Iris\n   assertion. However, the map_updateP_alloc does not suffice to show this. *)\nLemma own_alloc_strong_dep (f : gname → A) (P : gname → Prop) :\n  pred_infinite P →\n  (∀ γ, P γ → ✓ (f γ)) →\n  ⊢ |==> ∃ γ, ⌜P γ⌝ ∧ own γ (f γ).\nProof.\n  intros HPinf Hf.\n  rewrite -(bupd_mono (∃ m, ⌜∃ γ, P γ ∧ m = iRes_singleton γ (f γ)⌝ ∧ ouPred_ownM m)%I).\n  - rewrite /bi_emp_valid ownM_unit.\n    apply bupd_ownM_updateP, (discrete_fun_singleton_updateP_empty(B := (λ i : fin (gFunctors_len Σ), gmapUR gname (gFunctors_lookup Σ i (iPrePropO Σ) iPreProp_cofe)))\n      _ (λ m : _, ∃ γ, m = {[ γ := inG_unfold (ora_transport inG_prf (f γ)) ]} ∧ P γ));\n      [|naive_solver].\n    apply (alloc_updateP_strong_dep _ P _ (λ γ,\n      inG_unfold (ora_transport inG_prf (f γ)))); [done| |naive_solver].\n    intros γ _ ?.\n    by apply (cmra_morphism_valid inG_unfold), ora_transport_valid, Hf.\n  - apply exist_elim=>m; apply pure_elim_l=>-[γ [Hfresh ->]].\n    by rewrite !own_eq /own_def -(exist_intro γ) pure_True // left_id.\nQed.\nLemma own_alloc_cofinite_dep (f : gname → A) (G : gset gname) :\n  (∀ γ, γ ∉ G → ✓ (f γ)) → ⊢ |==> ∃ γ, ⌜γ ∉ G⌝ ∧ own γ (f γ).\nProof.\n  intros Ha.\n  apply (own_alloc_strong_dep f (λ γ, γ ∉ G))=> //.\n  apply (pred_infinite_set (C:=gset gname)).\n  intros E. set (γ := fresh (G ∪ E)).\n  exists γ. apply not_elem_of_union, is_fresh.\nQed.\nLemma own_alloc_dep (f : gname → A) :\n  (∀ γ, ✓ (f γ)) → ⊢ |==> ∃ γ, own γ (f γ).\nProof.\n  intros Ha. rewrite /bi_emp_valid (own_alloc_cofinite_dep f ∅) //; [].\n  apply bupd_mono, exist_mono=>?. apply: and_elim_r.\nQed.\n\nLemma own_alloc_strong a (P : gname → Prop) :\n  pred_infinite P →\n  ✓ a → ⊢ |==> ∃ γ, ⌜P γ⌝ ∧ own γ a.\nProof. intros HP Ha. eapply (own_alloc_strong_dep (λ _, a)); eauto. Qed.\nLemma own_alloc_cofinite a (G : gset gname) :\n  ✓ a → ⊢ |==> ∃ γ, ⌜γ ∉ G⌝ ∧ own γ a.\nProof. intros Ha. eapply (own_alloc_cofinite_dep (λ _, a)); eauto. Qed.\nLemma own_alloc a : ✓ a → ⊢ |==> ∃ γ, own γ a.\nProof. intros Ha. eapply (own_alloc_dep (λ _, a)); eauto. Qed.\n\n(** ** Frame preserving updates *)\nLemma own_updateP P γ a : a ~~>: P → own γ a ==∗ ∃ a', ⌜P a'⌝ ∧ own γ a'.\nProof.\n  intros Hupd. rewrite !own_eq.\n  rewrite -(bupd_mono (∃ m,\n    ⌜ ∃ a', m = iRes_singleton γ a' ∧ P a' ⌝ ∧ ouPred_ownM m)%I).\n  - apply bupd_ownM_updateP, (discrete_fun_singleton_updateP(B := (λ i : fin (gFunctors_len Σ), gmapUR gname (gFunctors_lookup Σ i (iPrePropO Σ) iPreProp_cofe)))\n       _ (λ m, ∃ x, m = {[ γ := x ]} ∧ ∃ x',\n      x = inG_unfold x' ∧ ∃ a',\n      x' = ora_transport inG_prf a' ∧ P a')); [|naive_solver].\n    apply singleton_updateP', (iso_cmra_updateP' inG_fold).\n    { apply inG_unfold_fold. }\n    { apply (cmra_morphism_op _). }\n    { apply inG_unfold_validN. }\n    by apply ora_transport_updateP'.\n  - apply exist_elim=> m; apply pure_elim_l=> -[a' [-> HP]].\n    rewrite -(exist_intro a').\n    by apply and_intro; [apply pure_intro|].\nQed.\n\nLemma own_update γ a a' : a ~~> a' → own γ a ==∗ own γ a'.\nProof.\n  intros; rewrite (own_updateP (a' =.)); last by apply cmra_update_updateP.\n  apply bupd_mono, exist_elim=> a''. apply pure_elim_l=> -> //.\nQed.\nLemma own_update_2 γ a1 a2 a' :\n  a1 ⋅ a2 ~~> a' → own γ a1 -∗ own γ a2 ==∗ own γ a'.\nProof. intros. apply wand_intro_r. rewrite -own_op. by apply own_update. Qed.\nLemma own_update_3 γ a1 a2 a3 a' :\n  a1 ⋅ a2 ⋅ a3 ~~> a' → own γ a1 -∗ own γ a2 -∗ own γ a3 ==∗ own γ a'.\nProof. intros. do 2 apply wand_intro_r. rewrite -!own_op. by apply own_update. Qed.\nEnd global.\n\nGlobal Arguments own_valid {_ _} [_] _ _.\nGlobal Arguments own_valid_2 {_ _} [_] _ _ _.\nGlobal Arguments own_valid_3 {_ _} [_] _ _ _ _.\nGlobal Arguments own_valid_l {_ _} [_] _ _.\nGlobal Arguments own_valid_r {_ _} [_] _ _.\nGlobal Arguments own_updateP {_ _} [_] _ _ _ _.\nGlobal Arguments own_update {_ _} [_] _ _ _ _.\nGlobal Arguments own_update_2 {_ _} [_] _ _ _ _ _.\nGlobal Arguments own_update_3 {_ _} [_] _ _ _ _ _ _.\n\nLemma own_unit A `{i : !inG Σ (A:uora)} γ : ⊢ |==> own γ (ε:A).\nProof.\n  rewrite /bi_emp_valid ownM_unit !own_eq /own_def.\n  apply bupd_ownM_update, (discrete_fun_singleton_update_empty(B := (λ i : fin (gFunctors_len Σ), gmapUR gname (gFunctors_lookup Σ i (iPrePropO Σ) iPreProp_cofe)))).\n  apply (alloc_unit_singleton_update (inG_unfold (ora_transport inG_prf ε))).\n  - apply (cmra_morphism_valid _), ora_transport_valid, ucmra_unit_valid.\n  - intros x. rewrite -(inG_unfold_fold x) -(cmra_morphism_op inG_unfold).\n    f_equiv. generalize (inG_fold x)=> x'.\n    destruct inG_prf=> /=. by rewrite left_id.\n  - done.\nQed.\n\n(* Global Instance own_unit_affine A `{i : !inG Σ (A:uora)} γ : Affine (own γ (ε:A)).\nProof. apply _. Qed. *)\n\n(** Big op class instances *)\nSection big_op_instances.\n  Context `{!inG Σ (A:uora)}.\n\n  Global Instance own_cmra_sep_homomorphism γ :\n    WeakMonoidHomomorphism op ouPred_sep (≡) (own γ).\n  Proof. split; try apply _. apply own_op. Qed.\n\n  Lemma big_opL_own {B} γ (f : nat → B → A) (l : list B) :\n    l ≠ [] →\n    own γ ([^op list] k↦x ∈ l, f k x) ⊣⊢ [∗ list] k↦x ∈ l, own γ (f k x).\n  Proof. apply (big_opL_commute1 _). Qed.\n  Lemma big_opM_own `{Countable K} {B} γ (g : K → B → A) (m : gmap K B) :\n    m ≠ ∅ →\n    own γ ([^op map] k↦x ∈ m, g k x) ⊣⊢ [∗ map] k↦x ∈ m, own γ (g k x).\n  Proof. apply (big_opM_commute1 _). Qed.\n  Lemma big_opS_own `{Countable B} γ (g : B → A) (X : gset B) :\n    X ≠ ∅ →\n    own γ ([^op set] x ∈ X, g x) ⊣⊢ [∗ set] x ∈ X, own γ (g x).\n  Proof. apply (big_opS_commute1 _). Qed.\n  Lemma big_opMS_own `{Countable B} γ (g : B → A) (X : gmultiset B) :\n    X ≠ ∅ →\n    own γ ([^op mset] x ∈ X, g x) ⊣⊢ [∗ mset] x ∈ X, own γ (g x).\n  Proof. apply (big_opMS_commute1 _). Qed.\n\n  Global Instance own_ora_sep_entails_homomorphism γ :\n    MonoidHomomorphism op ouPred_sep (⊢) (own γ).\n  Proof.\n    split; [split|]; try apply _.\n    - intros. by rewrite own_op.\n    - apply (affine _).\n  Qed.\n\n  Lemma big_opL_own_1 {B} γ (f : nat → B → A) (l : list B) :\n    own γ ([^op list] k↦x ∈ l, f k x) ⊢ [∗ list] k↦x ∈ l, own γ (f k x).\n  Proof. apply (big_opL_commute _). Qed.\n  Lemma big_opM_own_1 `{Countable K} {B} γ (g : K → B → A) (m : gmap K B) :\n    own γ ([^op map] k↦x ∈ m, g k x) ⊢ [∗ map] k↦x ∈ m, own γ (g k x).\n  Proof. apply (big_opM_commute _). Qed.\n  Lemma big_opS_own_1 `{Countable B} γ (g : B → A) (X : gset B) :\n    own γ ([^op set] x ∈ X, g x) ⊢ [∗ set] x ∈ X, own γ (g x).\n  Proof. apply (big_opS_commute _). Qed.\n  Lemma big_opMS_own_1 `{Countable B} γ (g : B → A) (X : gmultiset B) :\n    own γ ([^op mset] x ∈ X, g x) ⊢ [∗ mset] x ∈ X, own γ (g x).\n  Proof. apply (big_opMS_commute _). Qed.\nEnd big_op_instances.\n\n(** Proofmode class instances *)\nSection proofmode_instances.\n  Context `{!inG Σ A}.\n  Implicit Types a b : A.\n\n  Global Instance into_sep_own γ a b1 b2 :\n    IsOp a b1 b2 → IntoSep (own γ a) (own γ b1) (own γ b2).\n  Proof. intros. by rewrite /IntoSep (is_op a) own_op. Qed.\n(*  Global Instance into_and_own p γ a b1 b2 :\n    IsOp a b1 b2 → IntoAnd p (own γ a) (own γ b1) (own γ b2).\n  Proof. intros. by rewrite /IntoAnd (is_op a) own_op sep_and. Qed. *)\n\n  Global Instance from_sep_own γ a b1 b2 :\n    IsOp a b1 b2 → FromSep (own γ a) (own γ b1) (own γ b2).\n  Proof. intros. by rewrite /FromSep -own_op -is_op. Qed.\n(*  (* TODO: Improve this instance with generic own simplification machinery\n  once https://gitlab.mpi-sws.org/iris/iris/-/issues/460 is fixed *)\n  Global Instance combine_sep_as_own γ a b1 b2 :\n    IsOp a b1 b2 → CombineSepAs (own γ b1) (own γ b2) (own γ a).\n  Proof. intros. by rewrite /CombineSepAs -own_op -is_op. Qed.\n  (* TODO: Improve this instance with generic own validity simplification\n  machinery once https://gitlab.mpi-sws.org/iris/iris/-/issues/460 is fixed *)\n  Global Instance combine_sep_gives_own γ b1 b2 :\n    CombineSepGives (own γ b1) (own γ b2) (✓ (b1 ⋅ b2)).\n  Proof.\n    intros. rewrite /CombineSepGives -own_op own_valid.\n    by apply: bi.persistently_intro.\n  Qed.*)\n(*  Global Instance from_and_own_persistent γ a b1 b2 :\n    IsOp a b1 b2 → TCOr (OraCoreId b1) (OraCoreId b2) →\n    FromAnd (own γ a) (own γ b1) (own γ b2).\n  Proof.\n    intros ? Hb. rewrite /FromAnd (is_op a) own_op.\n    destruct Hb; by rewrite persistent_and_sep.\n  Qed.*)\nEnd proofmode_instances.\n", "meta": {"author": "mansky1", "repo": "ora", "sha": "1f6ee54b698e2486fd4b1dd62b816f9269b93615", "save_path": "github-repos/coq/mansky1-ora", "path": "github-repos/coq/mansky1-ora/ora-1f6ee54b698e2486fd4b1dd62b816f9269b93615/theories/logic/own.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.27377548225867393}}
{"text": "Require Import Platform.Cito.CompileStmtSpec.\nRequire Import Bedrock.StringSet.\nRequire Import Platform.Cito.FreeVars.\nRequire Import Platform.Cito.SynReqFactsUtil.\n\nLocal Infix \";;\" := Syntax.Seq (right associativity, at level 95).\n\nRequire Platform.Cito.CompileExpr.\n\nLemma syn_req_Assign_e : forall vars temp_size x e k, syn_req vars temp_size (Syntax.Assign x e ;; k) -> CompileExpr.syn_req vars temp_size e 0.\n  unfold syn_req, CompileExpr.syn_req, in_scope; simpl; intuition.\n  apply Subset_union_left in H; intuition.\n  apply Subset_union_left in H0; intuition.\n  eauto using Max.max_lub_l.\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/Cito/SynReqFacts3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2737392590299488}}
{"text": "Require Import\n  HoTT.Types.Universe\n  HoTT.Basics.Decidable\n  HoTT.Classes.interfaces.abstract_algebra\n  HoTT.Classes.interfaces.integers\n  HoTT.Classes.interfaces.naturals\n  HoTT.Classes.interfaces.rationals\n  HoTT.Classes.interfaces.orders\n  HoTT.Classes.implementations.natpair_integers\n  HoTT.Classes.theory.rings\n  HoTT.Classes.theory.integers\n  HoTT.Classes.theory.dec_fields\n  HoTT.Classes.orders.dec_fields\n  HoTT.Classes.theory.rationals\n  HoTT.Classes.orders.lattices\n  HoTT.Classes.theory.additional_operations\n  HoTT.Classes.theory.premetric\n  HoTT.Classes.implementations.assume_rationals\n  HoTTClasses.cauchy_completion.\n\nRequire Export\n  HoTTClasses.cauchy_reals.base\n  HoTTClasses.cauchy_reals.abs\n  HoTTClasses.cauchy_reals.order.\n\nLocal Set Universe Minimization ToSet.\n\nLemma equiv_0_metric' : forall e u, close e u 0 -> abs u < rat (' e).\nProof.\nintros e u;revert u e;apply (C_ind0 _ (fun u => forall e, _ -> _)).\n- intros q e E.\n  rewrite (equiv_eta_eta_def _) in E. apply Qclose_alt in E.\n  rewrite negate_0,plus_0_r in E.\n  apply rat_lt_preserving. trivial.\n- intros x IH e xi.\n  apply rounded in xi. revert xi.\n  apply (Trunc_ind _);intros [d [d' [He xi]]].\n  rewrite (equiv_lim_eta_def _) in xi.\n  revert xi;apply (Trunc_ind _);intros [n [n' [Hd E1]]].\n  apply IH in E1.\n  rewrite He,Hd.\n  assert (Hrw : (' (n + n' + d')) = ' n' + ' (n + d'))\n  by ring_tac.ring_with_nat.\n  rewrite Hrw;clear Hrw.\n  apply (Rlt_close_rat_plus _ _ E1).\n  apply (non_expanding abs).\n  rewrite qpos_plus_comm. apply (equiv_lim _).\nQed.\n\nDefinition equiv_0_metric@{}\n  := equiv_0_metric'@{UQ UQ}.\n\nLemma equiv_to_metric@{} : forall e u v, close e u v -> abs (u - v) < rat (' e).\nProof.\nintros e u v xi.\nrewrite <-Rabs_idempotent.\napply equiv_0_metric.\nrewrite <-(Rabs_of_0' (v - v));[|apply right_inverse].\napply (non_expanding (fun w => abs (w - v))). trivial.\nQed.\n\nLemma metric_to_equiv_rat_lim@{} (q : Q)\n  (y : Approximation real)\n  (IHy : forall e e0 : Q+, abs (rat q - y e) < rat (' e0) -> close e0 (rat q) (y e))\n  (e : Q+)\n  (E1 : abs (rat q - lim y) < rat (' e))\n  : close e (rat q) (lim y).\nProof.\ngeneralize (R_archimedean _ _ E1). apply (Trunc_ind _);intros [d [E2 E3]].\napply rat_lt_reflecting in E3.\npose proof (snd (flip_pos_minus _ _) E3) as E4.\nassert (Hd : 0 < d).\n{ revert E2;apply (Trunc_ind _).\n  intros [s [s' [F1 [F2 F3]]]].\n  apply rat_le_reflecting in F3.\n  apply lt_le_trans with s';trivial.\n  apply le_lt_trans with s;trivial.\n  apply rat_le_reflecting.\n  transitivity (abs (rat q - lim y));trivial.\n  apply Rabs_nonneg.\n}\npose (D := mkQpos d Hd).\npose (ED := mkQpos _ E4).\nassert (Hrw : e = D + (ED / 4 + ED / 4) + (ED / 4 + ED / 4)).\n{ path_via (D + ED).\n  { apply pos_eq;unfold D, ED.\n    abstract ring_tac.ring_with_integers (NatPair.Z nat).\n  }\n  path_via (D + 4 / 4 * ED).\n  { rewrite pos_recip_r,Qpos_mult_1_l;trivial. }\n  apply pos_eq;abstract ring_tac.ring_with_nat.\n}\nrewrite Hrw.\neapply (equiv_triangle _);[|apply (equiv_lim _)].\napply IHy. apply (Rlt_close_rat_plus _ _ E2).\napply (non_expanding (fun u => abs (rat q - u))).\napply (equiv_symm _),(equiv_lim _).\nQed.\n\nLemma metric_to_equiv_lim_lim@{} (x : Approximation real)\n  (IHx : forall (e : Q+) (v : real) (e0 : Q+),\n        abs (x e - v) < rat (' e0) -> close e0 (x e) v)\n  (y : Approximation real)\n  (IHy : forall e e0 : Q+, abs (lim x - y e) < rat (' e0) -> close e0 (lim x) (y e))\n  (e : Q+)\n  (E1 : abs (lim x - lim y) < rat (' e))\n  : close e (lim x) (lim y).\nProof.\ngeneralize (R_archimedean _ _ E1). apply (Trunc_ind _);intros [d [E2 E3]].\napply rat_lt_reflecting in E3.\npose proof (snd (flip_pos_minus _ _) E3) as E4.\nassert (Hd : 0 < d).\n{ revert E2;apply (Trunc_ind _).\n  intros [s [s' [F1 [F2 F3]]]].\n  apply rat_le_reflecting in F3.\n  apply lt_le_trans with s';trivial.\n  apply le_lt_trans with s;trivial.\n  apply rat_le_reflecting.\n  transitivity (abs (lim x - lim y));trivial.\n  apply Rabs_nonneg.\n}\npose (D := mkQpos d Hd).\npose (ED := mkQpos _ E4).\nassert (Hrw : e = D + (ED / 4 + ED / 4) + (ED / 4 + ED / 4)).\n{ path_via (D + ED).\n  { apply pos_eq;unfold D, ED.\n    abstract ring_tac.ring_with_integers (NatPair.Z nat).\n  }\n  path_via (D + 4 / 4 * ED).\n  { rewrite pos_recip_r,Qpos_mult_1_l;trivial. }\n  apply pos_eq;abstract ring_tac.ring_with_nat.\n}\nrewrite Hrw.\neapply (equiv_triangle _);[|apply (equiv_lim _)].\napply IHy. apply (Rlt_close_rat_plus _ _ E2).\napply (non_expanding (fun u => abs (lim x - u))).\napply (equiv_symm _),(equiv_lim _).\nQed.\n\nLemma metric_to_equiv@{} : forall e u v, abs (u - v) < rat (' e) -> close e u v.\nProof.\nintros e u v;revert u v e;apply (C_ind0 _ (fun u => forall v e, _ -> _));\n[intros q|intros x IHx];\n(apply (C_ind0 _ (fun v => forall e, _ -> _));[intros r|intros y IHy]);\nintros e E1.\n- apply equiv_eta_eta. apply Qclose_alt.\n  apply rat_lt_reflecting,E1.\n- apply metric_to_equiv_rat_lim;auto.\n- apply (equiv_symm _),metric_to_equiv_rat_lim.\n  + intros n n' E;apply (equiv_symm _),IHx.\n    rewrite Rabs_neg_flip. trivial.\n  + rewrite Rabs_neg_flip. trivial.\n- apply metric_to_equiv_lim_lim;auto.\nQed.\n\nLemma equiv_metric_applied_rw'\n  : forall e u v, close e u v = (abs (u - v) < rat (' e)).\nProof.\nintros. apply TruncType.path_iff_ishprop_uncurried.\nsplit.\n- apply equiv_to_metric.\n- apply metric_to_equiv.\nQed.\n\nDefinition equiv_metric_applied_rw@{} := equiv_metric_applied_rw'@{Ularge}.\n\nLemma equiv_metric_rw' : close = fun e u v => abs (u - v) < rat (' e).\nProof.\nrepeat (apply path_forall;intro).\napply equiv_metric_applied_rw.\nQed.\n\nDefinition equiv_metric_rw@{} := equiv_metric_rw'.\n", "meta": {"author": "SkySkimmer", "repo": "HoTTClasses", "sha": "f9affefaa088d02ca7e6e901580ae6f9ff13ca40", "save_path": "github-repos/coq/SkySkimmer-HoTTClasses", "path": "github-repos/coq/SkySkimmer-HoTTClasses/HoTTClasses-f9affefaa088d02ca7e6e901580ae6f9ff13ca40/theories/cauchy_reals/metric.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2737392590299488}}
{"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(* Signed 64-bits integers: these are used to represent Tez amounts *)\n\nRequire Import Bvector.\nRequire Import ZArith.\nRequire Import Zdigits.\n\nDefinition int64 := Bvector 64.\n\nDefinition sign : int64 -> bool := Bsign 63.\n\nDefinition to_Z : int64 -> Z := two_compl_value 63.\n\nDefinition of_Z : Z -> int64 := Z_to_two_compl 63.\n\nDefinition int64_inversion (b : int64) : exists a v, b = Bcons a 63 v :=\n  match b in Vector.t _ (S _) return exists a v, b = Bcons a _ v with\n  | Vector.cons _ a _ v => ex_intro _ a (ex_intro _ v eq_refl)\n  end.\n\nLemma of_Z_to_Z b : of_Z (to_Z b) = b.\nProof.\n  destruct (int64_inversion b) as (a, (v, H)).\n  rewrite H.\n  apply two_compl_to_Z_to_two_compl.\nQed.\n\nDefinition compare (a b : int64) : comparison :=\n  Z.compare (to_Z a) (to_Z b).\n\n(* To avoid a name clash in OCaml extracted code. *)\nDefinition int64_compare (a b : int64) : comparison := compare a b.\n\nLemma compare_eq_iff (a b : int64) : compare a b = Eq <-> a = b.\nProof.\n  unfold compare.\n  rewrite Z.compare_eq_iff.\n  split.\n  - intro H.\n    apply (f_equal of_Z) in H.\n    rewrite of_Z_to_Z in H.\n    rewrite of_Z_to_Z in H.\n    assumption.\n  - apply f_equal.\nQed.\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/int64bv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2737392590299487}}
{"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(*                   Fieska_Tactics.v                                 *)\n(*                                                                    *)\n(*                     Barry Jay                                      *)\n(*                                                                    *)\n(**********************************************************************)\n\nRequire Import Arith Omega Max Bool List.\nRequire Import IntensionalLib.Fieska_calculus.Test.\nRequire Import IntensionalLib.Fieska_calculus.General.\nRequire Import IntensionalLib.Fieska_calculus.Fieska_Terms.\n\nDefinition termred := Fieska -> Fieska -> Prop.\n\nDefinition preserve (R : termred) (P : Fieska -> Prop) :=\n  forall x : Fieska, P x -> forall y : Fieska, R x y -> P y.\n\n\nInductive multi_step : termred -> termred :=\n  | zero_red : forall red M, multi_step red M M\n  | succ_red : forall (red: Fieska-> Fieska -> Prop) M N P, \n                   red M N -> multi_step red N P -> multi_step red M P\n.\n\nInductive sequential : termred -> termred -> termred :=\n  | seq_red : forall (red1 red2 : termred) M N P, \n                red1 M N -> red2 N P -> sequential red1 red2 M P.\n\nHint Resolve zero_red succ_red seq_red\n.\n\nDefinition reflective red := forall (M: Fieska), red M M.\n\nLemma refl_multi_step : forall (red: termred), reflective (multi_step red).\nProof. red; split_all. Qed.\n\nLemma refl_seq : forall (red1 red2: termred),\n                   reflective red1 -> reflective red2 -> reflective(sequential red1 red2).\nProof. red; split_all; eapply2 seq_red. Qed.\n\n\nLtac reflect := match goal with \n| |- reflective (multi_step _) => eapply2 refl_multi_step\n| |- multi_step _ _ _ => try (eapply2 refl_multi_step)\n| |- reflective (sequential _) => eapply2 refl_seq; reflect \n| |- sequential _ _ _ _ => try (eapply2 refl_seq)\n| _ => split_all\nend.\n\n\nLtac one_step := \nmatch goal with \n| |- multi_step _ _ ?N => apply succ_red with N; auto; try red; try reflect\nend.\n\nLtac seq_l := \nmatch goal with \n| |- sequential _ _ ?M ?N => apply seq_red with N; auto; red; reflect\nend.\n\nLtac seq_r := \nmatch goal with \n| |- sequential _ _ ?M ?N => apply seq_red with M; auto; red; reflect\nend.\n\n\nDefinition transitive red := forall (M N P: Fieska), red M N -> red N P -> red M P. \n\nLemma transitive_red : forall red, transitive (multi_step red). \nProof. red; induction 1; split_all. \napply succ_red with N; auto. \nQed. \n\n\nDefinition preserves_app (red : termred) := \nforall M M' N N', red M M' -> red N N' -> red (App M N) (App M' N').\n\n\nLemma preserves_app_multi_step : forall (red: termred), reflective red -> preserves_app red -> preserves_app (multi_step red). \nProof.\nred. induction 3; split_all. generalize H0; induction 1. \nreflect. \napply succ_red with (App M N); auto.\nassert( transitive (multi_step red)) by eapply2 transitive_red.  \napply X0 with (App N0 N); auto. \none_step. \nQed.\n\nLemma preserves_app_seq : forall (red1 red2: termred), preserves_app red1 -> preserves_app red2 -> preserves_app (sequential red1 red2). \nProof.\nred; split_all. \ninversion H1; inversion H2.\napply seq_red with (App N0 N1); auto.\nQed.\n\nHint Resolve preserves_app_multi_step preserves_app_seq .\n\n\nLtac inv1 prop := \nmatch goal with \n| H: prop _ |- _ => inversion H; clear H; inv1 prop\n| H: prop (App  _ _) |- _ => inversion H; clear H; inv1 prop\n| H: prop Op _ |- _ => inversion H; clear H; inv1 prop\n| _ => split_all\n end.\n\n\nDefinition implies_red (red1 red2: termred) := forall M N, red1 M N -> red2 M N. \n\nLemma implies_red_multi_step: forall red1 red2, implies_red red1  (multi_step red2) -> \n                                                implies_red (multi_step red1) (multi_step red2).\nProof. red. \nintros red1 red2 IR M N R; induction R; split_all. \napply transitive_red with N; auto. \nQed. \nLemma implies_red_seq: \n forall red1 red2 red3, \n  implies_red red1  (multi_step red3)  ->  \n  implies_red red2 (multi_step red3) -> \n  implies_red (sequential red1 red2) (multi_step red3) .\nProof. \nred; split_all. inversion H1. apply transitive_red with N0; auto. \nQed. \n\nLtac inv red := \nmatch goal with \n| H: multi_step red (App _ _) _ |- _ => inversion H; clear H; inv red\n| H: multi_step red (Ref _) _ |- _ => inversion H; clear H; inv red\n| H: multi_step red (Op _) _ |- _ => inversion H; clear H; inv red\n| H: red (Ref _) _ |- _ => inversion H; clear H; inv red\n| H: red (App _ _) _ |- _ => inversion H; clear H; inv red\n| H: red (Op _) _ |- _ => inversion H; clear H; inv red\n| H: multi_step red _ (Ref _) |- _ => inversion H; clear H; inv red\n| H: multi_step red _ (App _ _) |- _ => inversion H; clear H; inv red\n| H: multi_step red _ (Op _) |- _ => inversion H; clear H; inv red\n| H: red _ (Ref _) |- _ => inversion H; clear H; inv red\n| H: red _ (App _ _) |- _ => inversion H; clear H; inv red\n| H: red _ (Op _) |- _ => inversion H; clear H; inv red\n| _ => subst; split_all \n end.\n\n\n\nDefinition diamond (red1 red2 : termred) := \nforall M N, red1 M N -> forall P, red2 M P -> exists Q, red2 N Q /\\ red1 P Q. \n\nLemma diamond_flip: forall red1 red2, diamond red1 red2 -> diamond red2 red1. \nProof. unfold diamond; split_all. elim (H M P H1 N H0); split_all. inversion H2; exist x. Qed.\n\nLemma diamond_strip : \nforall red1 red2, diamond red1 red2 -> diamond red1 (multi_step red2). \nProof. intros. \neapply2 diamond_flip. \nred; induction 1; split_all.\nexist P.\nelim (H M P0 H2 N); split_all. \nelim(IHmulti_step H x); split_all. \ninversion H3; inversion H4; exist x0; split; auto.\napply succ_red with x; auto.\ntauto.  \nQed. \n\n\nDefinition diamond_star (red1 red2: termred) := forall  M N, red1 M N -> forall P, red2 M P -> \n  exists Q, red1 P Q /\\ multi_step red2 N Q. \n\nLemma diamond_star_strip: forall red1 red2, diamond_star red1 red2 -> diamond (multi_step red2) red1 .\nProof. \nred. induction 2; split_all. \nexist P.\nelim(H M P0 H2 N H0); split_all. \nelim(IHmulti_step H x); split_all. \ninversion H3; inversion H4; exist x0; split; auto.\napply transitive_red with x; auto. \ntauto.\nQed. \n\nLemma diamond_tiling : \nforall red1 red2, diamond red1 red2 -> diamond (multi_step red1) (multi_step red2).\nProof. \nred.  induction 2; split_all.\nexist P.\nelim(diamond_strip red red2 H M N H0 P0); split_all.\ninversion H3. \nelim(IHmulti_step H x H4); split_all.\ninversion H6. exist x0. split; auto. \napply succ_red with x; auto.\nQed. \n\nHint Resolve diamond_tiling. \n\nLemma diamond_seq: forall red red1 red2, diamond red red1 -> diamond red red2 -> diamond red (sequential red1 red2). \nProof. unfold diamond; split_all. \ninversion H2. \nelim(H M N H1 N0); split_all.\ninversion H9.\n elim(H0 N0 x H11 P); split_all.\ninversion H12. \nexist x0. \nsplit. apply seq_red with x; auto. auto. \nQed.\n\nFixpoint rank (M: Fieska) := \nmatch M with \n| Ref _ => 1\n| Op _ => 1\n| App M1 M2 => S((rank M1) + (rank M2))\nend.\n\nLemma rank_positive: forall M, rank M > 0. \nProof. \ninduction M; split_all; try omega. \nQed. \n\n(* \n\nLtac rank_tac := match goal with \n| |- forall M, ?P  => \n  cut (forall p M, p >= rank M -> P )\n; [ intros H M;  eapply2 H | \nintro p; induction p; intro M;  [ assert(rank M >0) by eapply2 rank_positive; noway |]\n]\nend .\n\n*) \n", "meta": {"author": "Barry-Jay", "repo": "Intensional-computation", "sha": "de09d3e646c1ea50127c5033b46576d8b4773259", "save_path": "github-repos/coq/Barry-Jay-Intensional-computation", "path": "github-repos/coq/Barry-Jay-Intensional-computation/Intensional-computation-de09d3e646c1ea50127c5033b46576d8b4773259/Fieska_calculus/Fieska_Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118791767283, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.2737020821421381}}
{"text": "From CoindSemWhile Require Import SsrExport Trace Language.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(* big-step relational semantics *)\nCoInductive exec: stmt -> state -> trace -> Prop :=\n| exec_skip: forall st, \n    exec Sskip st (Tnil st)\n| exec_assign: forall id a st, \n    exec (Sassign id a) st (Tcons st (Tnil (update id (a st) st)))\n| exec_seq: forall s1 s2 st tr tr',\n    exec s1 st tr ->\n    execseq s2 tr tr' ->\n    exec (Sseq s1 s2) st tr'\n| exec_ifthenelse_true: forall a s1 s2 st tr,\n    is_true (a st) = true ->\n    execseq s1 (Tcons st (Tnil st)) tr ->\n    exec (Sifthenelse a s1 s2) st tr\n| exec_ifthenelse_false: forall a s1 s2 st tr,\n    is_true (a st) = false ->\n    execseq s2 (Tcons st (Tnil st)) tr ->\n    exec (Sifthenelse a s1 s2) st tr\n| exec_while_false: forall a s st,\n    is_true (a st) = false ->\n    exec (Swhile a s) st (Tcons st (Tnil st))\n| exec_while_loop: forall a s st tr tr',\n    is_true (a st) = true ->\n    execseq s (Tcons st (Tnil st)) tr ->\n    execseq (Swhile a s) tr tr' ->\n    exec (Swhile a s) st tr'\n\nwith execseq: stmt -> trace -> trace -> Prop :=\n| execseq_nil: forall st s tr,\n  exec s st tr ->\n  execseq s (Tnil st) tr\n| execseq_cons: forall tr s tr' e,\n  execseq s tr tr' ->\n  execseq s (Tcons e tr) (Tcons e tr').\n\nLemma exec_nil: forall s st st',\nexec s st (Tnil st') -> st = st'.\nProof.\nmove => s; induction s. \n- move => st0 st1  h1. by inversion h1. \n- move => st0 st1 h1. by inversion h1. \n- move => st0 st1 h1. foo h1. foo H4.  \n  move: (IHs1 _ _ H1) => h; subst.\n  move: (IHs2 _ _ H) => h; subst. done. \n- move => st0 st1 h1. foo h1.  foo H5. foo H5. \n- move => st0 st1 h1. foo h1. foo H2. foo H5.  \nQed.\n\nLemma execseq_deterministic0: forall s,\n(forall st tr1 tr2, exec s st tr1 -> exec s st tr2 -> bisim tr1 tr2) ->\nforall tr1 tr2 tr3 tr4,\nbisim tr1 tr2 -> execseq s tr1 tr3 -> execseq s tr2 tr4 -> bisim tr3 tr4.\nProof.\nmove => s hexec. cofix COINDHYP. \nmove => tr1 tr2 tr3 tr4 h1 h2 h3. foo h2.  \n- foo h3. \n  - foo h1. have := hexec _ _ _ H H0; apply.  \n  - by inversion h1. \n- foo h3.  \n  - by inversion h1. \n  - foo h1. have := bisim_cons _ (COINDHYP _ _ _ _ H2 H H0); apply.  \nQed. \n\nLemma exec_seq_deterministic0: forall s1 s2,\n(forall st tr1 tr2, exec s1 st tr1 -> exec s1 st tr2 -> bisim tr1 tr2) ->\n(forall st tr1 tr2, exec s2 st tr1 -> exec s2 st tr2 -> bisim tr1 tr2) ->\nforall st tr1 tr2, exec (Sseq s1 s2) st tr1 ->\nexec (Sseq s1 s2) st tr2 ->\nbisim tr1 tr2.\nProof. \nmove => s1 s2 hexec1 hexec2 st tr1 tr2 h1 h2.\nfoo h1. foo h2. have h3 := hexec1 _ _ _ H1 H2. \nby apply: (execseq_deterministic0 hexec2 h3 H4 H6).   \nQed. \n\nLemma exec_while_deterministic0: forall a s,\n(forall st tr1 tr2, exec s st tr1 -> exec s st tr2 -> bisim tr1 tr2) ->\nforall st tr1 tr2, exec (Swhile a s) st  tr1 ->\nexec (Swhile a s) st tr2 ->\nbisim tr1 tr2.\nProof. \nmove => a s hwhile.  cofix COINDHYP.\nhave COINDHYP2: forall tr1 tr2 tr3 tr4, bisim tr1 tr2 ->\nexecseq (Swhile a s) tr1 tr3 -> execseq (Swhile a s) tr2 tr4 ->\nbisim tr3 tr4. \n* cofix COINDHYP2. move => tr1 tr2 tr3 tr4 h1 h2 h3. foo h2. \n  - foo h3.\n    - foo h1. foo H0. \n      - foo H.   \n        - by apply bisim_reflexive. \n        - rewrite H2 in H5. by inversion H5. \n      - foo H.   \n        - rewrite H6 in H3. by inversion H3. \n        - move => {H3 H2}. foo H5. foo H3. foo H4. foo H5. foo H7. foo H9.\n          by apply: (bisim_cons _ (COINDHYP2 _ _ _ _ (hwhile _ _ _ H1 H2) H6 H5)).\n    - by inversion h1.\n  - foo h3.  \n    - by inversion h1.  \n    - foo h1. by apply: (bisim_cons _ (COINDHYP2 _ _ _ _ H2 H H0)).\n* move =>  st tr1 tr2 h1 h2. foo h1. \n  - foo h2. \n    -  by apply bisim_reflexive. \n    - rewrite H3 in H1. by inversion H1. \n  - foo h2.  \n    - rewrite H1 in H6. by inversion H6. \n    - foo H2. foo H9. foo H4. foo H9. foo H5. foo H8.  \n    have h3 := hwhile _ _ _ H2 H4.\n    by have := bisim_cons _ (COINDHYP2 _ _ _ _ h3 H9 H7); apply.  \nQed.  \n\n(* determinism *)\nLemma exec_deterministic: forall s st,\nforall tr1 tr2, exec s st tr1 ->\nexec s st tr2 -> bisim tr1 tr2.\nProof.\nmove => s; induction s. \n- move => st tr1 tr2 h1 h2. foo h1. foo h2. by apply bisim_nil.\n- move => st tr1 tr2 h1 h2. foo h1. foo h2. by apply bisim_reflexive.  \n- move => st tr1 tr2 h1 h2. by apply: (exec_seq_deterministic0 IHs1 IHs2 h1 h2).\n- move => st tr1 tr2 h1 h2. foo h1.\n  - foo h2.\n    - foo H5. foo H3. foo H7. foo H5. apply bisim_cons. apply: (IHs1 _ _ _ H1 H2).\n    - rewrite H4 in H6. by inversion H6.\n  - foo h2.\n    - rewrite H4 in H6. by inversion H6.\n    - foo H5. foo H3. foo H7. foo H4. foo H5. apply: (bisim_cons _ (IHs2 _ _ _ H1 H3)).\n- move => st tr1 tr2 h1 h2. apply: (exec_while_deterministic0 IHs h1 h2).\nQed.     \n\nLemma execseq_insensitive0: forall s,\n(forall st tr1 tr2, exec s st tr1 -> bisim tr1 tr2 -> exec s st tr2) ->\nforall tr1 tr2 tr3 tr4,\nbisim tr1 tr2 ->\nexecseq s tr1 tr3 -> bisim tr3 tr4 -> execseq s tr2 tr4.\nProof.\nmove => s hexec0. cofix COINDHYP. \nmove => tr1 tr2 tr3 tr4 h1 h2 h3. foo h2. foo h1. \n  by apply (execseq_nil (hexec0 _ _ _ H h3)).  \n- foo h3. foo h1. by apply: (execseq_cons _ (COINDHYP _ _ _ _ H4 H H3)). \nQed.\n\nLemma exec_seq_insensitive0: forall s1 s2,\n(forall st tr1 tr2, exec s1 st tr1 -> bisim tr1 tr2 -> exec s1 st tr2) ->\n(forall st tr1 tr2, exec s2 st tr1 -> bisim tr1 tr2 -> exec s2 st tr2) ->\nforall st tr1 tr2, exec (Sseq s1 s2) st tr1 ->\nbisim tr1 tr2 -> \nexec (Sseq s1 s2) st tr2.\nProof. \nmove => s1 s2 hs1 hs2 st tr1 tr2 h1 h2. foo h1. \napply: (exec_seq H1). foo H4. \n- by apply (execseq_nil (hs2 _ _ _ H h2)).  \n- foo h2. apply execseq_cons. have h2 := bisim_reflexive tr0.  \n  by apply: (execseq_insensitive0 hs2 h2 H H4). \nQed. \n\nLemma exec_while_insensitive0: forall a s,\n(forall st tr1 tr2, exec s st tr1 -> bisim tr1 tr2 -> exec s st tr2) ->\nforall st tr1 tr2, exec (Swhile a s) st tr1 ->\nbisim tr1 tr2 -> \nexec (Swhile a s) st tr2.\nProof. \nmove => a s hwhile.  cofix COINDHYP.\nhave COINDHYP2: forall tr1 tr2 tr3 tr4, bisim tr1 tr2 ->\nexecseq (Swhile a s) tr1 tr3 -> bisim tr3 tr4 -> \nexecseq (Swhile a s) tr2 tr4.\n* cofix COINDHYP2. move => tr1 tr2 tr3 tr4 h1 h2 h3. foo h2. \n  - foo h1. by apply: (execseq_nil (COINDHYP _ _ _ H h3)).\n  - foo h1. foo h3. by apply: (execseq_cons _ (COINDHYP2 _ _ _ _ H3 H H4)). \n- move => st tr1 tr2 h1 h2. foo h1. \n  - foo h2. foo H2. by apply: (exec_while_false _ H3). \n  - foo H2. foo H6. foo H5. foo h2. \n    apply: (exec_while_loop H1 (execseq_cons _ (execseq_nil H2))). \n    by apply: (execseq_cons _ (COINDHYP2 _ _ _ _ (bisim_reflexive tr') H6 H4)).\nQed.      \n\n(* setoid *)\nLemma exec_insensitive: forall s st tr tr',\nexec s st tr -> bisim tr tr' -> exec s st tr'. \nProof. \nmove => s; induction s. \n- move => st tr tr' h1 h2. foo h1. foo h2. by apply exec_skip. \n- move => st tr tr' h1 h2. foo h1. foo h2. foo H2. by apply exec_assign. \n- move => st tr tr' h1 h2. apply: (exec_seq_insensitive0 IHs1 IHs2 h1 h2). \n- move => st tr tr' h1 h2. foo h1.  \n  - foo H5. foo H3. foo h2. apply: (exec_ifthenelse_true _ H4). \n    apply execseq_cons. apply execseq_nil. by apply: (IHs1 _ _ _ H1 H3). \n  - foo H5. foo H3. foo h2. apply: (exec_ifthenelse_false _ H4).\n    apply execseq_cons. apply execseq_nil. by apply: (IHs2 _ _ _ H1 H3).\n- move => st tr tr7 h1 h2. by apply: (exec_while_insensitive0 IHs h1 h2).\nQed.\n\nLemma execseq_insensitive_pre: forall s tr1 tr2 tr3,\nbisim tr1 tr2 -> execseq s tr1 tr3 -> execseq s tr2 tr3.\nProof.\ncofix COINDHYP. move => s tr1 tr2 tr3 h1 h2. foo h2; foo h1.   \n- by apply: (execseq_nil H).\n- apply: execseq_cons. by apply: (COINDHYP _ _ _ _ H3 H). \nQed.\n\nLemma exec_hd: forall s st tr,\nexec s st tr -> hd tr = st.   \nProof.\nmove => s; induction s. \n- move => st tr h1. foo h1. by simpl. \n- move => st tr h1. foo h1. by simpl. \n- move => st tr h1. foo h1. have h1 := IHs1 _ _ H1. foo H4. \n  - simpl. have := IHs2 _ _ H; apply. \n  - by simpl. \n- move => st tr h1. foo h1. \n  - foo H5. by simpl. \n  - foo H5. by simpl. \n- move => st tr h1. foo h1. \n  - by simpl. \n  - foo H2. foo H6. foo H5. by simpl. \nQed.\n\nLemma execseq_hd: forall s tr tr',\nexecseq s tr tr' -> hd tr' = hd tr.\nProof. \nmove => s tr tr' h1. foo h1. \n- simpl. have := exec_hd H; apply. \n- by simpl. \nQed.\n", "meta": {"author": "palmskog", "repo": "coind-sem-while", "sha": "d5b12c2971e2c054a82856a476f9369e8ae9f831", "save_path": "github-repos/coq/palmskog-coind-sem-while", "path": "github-repos/coq/palmskog-coind-sem-while/coind-sem-while-d5b12c2971e2c054a82856a476f9369e8ae9f831/theories/BigRel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.27370207411262276}}
{"text": "\n  (* on part d'un CTS confluent, avec un algo de whnf, ... *)\n\n  Record subtype_dec_CTS : Set := \n    {scts_cr : church_rosser red_step;\n     scts_hn_sort : forall (e : env) (s : sort), head_normal hdr e (Srt s);\n     scts_hn_prod :\n      forall (e : env) (A B : term), head_normal hdr e (Prod A B);\n     scts_whnf :\n      forall (e : env) (t : term),\n      sn red_step e t -> {u : term | red hdr e t u &  head_normal hdr e u};\n     scts_convert_hn :\n      forall (e : env) (x y : term),\n      sn red_step e x ->\n      sn red_step e y -> decide (conv_hn_inv hd_rule e x y);\n     scts_rt_univ_dec : forall s s' : sort, decide (rt_univ s s')}.\n\n\n  Variable the_scts : subtype_dec_CTS.\n\n  (* open it *)\n  Let CR : church_rosser red_step := scts_cr the_scts.\n  Let shn_sort := scts_hn_sort the_scts.\n  Let shn_prod := scts_hn_prod the_scts.\n  Let whnf :\n    forall (e : env) (t : term),\n    sn red_step e t -> {u : term | red hdr e t u &  head_normal hdr e u} :=\n    scts_whnf the_scts.\n  Let conv_hn_dec :\n    forall (e : env) (x y : term),\n    sn red_step e x -> sn red_step e y -> decide (conv_hn_inv hd_rule e x y) :=\n    scts_convert_hn the_scts.\n  Let rt_univ_dec : forall s s' : sort, decide (rt_univ s s') :=\n    scts_rt_univ_dec the_scts.\n\n  Hint Resolve shn_sort shn_prod: pts.\n\n\n  Let inv_cumul_hn := equiv_inv_cumul_hn CR shn_sort shn_prod.\n\n\n  Let f (tr : env * (term * term)) :=\n    match tr with\n    | (e, (t1, t2)) => (e, t1, (e, t2))\n    end.\n\n  Theorem CR_WHNF_inv_cumul_dec :\n   forall (e : env) (x y : term),\n   sn red_step e x -> sn red_step e y -> decide (cumul_hn_inv e x y).\nintros e x y sn0 sn1.\ngeneralize sn0 sn1.\npattern e, x, y in |- *.\napply\n Acc3_rec\n  with (R := fun x y : env * (term * term) => ord_conv hdr (f x) (f y)).\nunfold f in |- *.\nclear sn0 sn1 e x y.\nintros e u v.\ncase u.\ncase v; intros.\nelim rt_univ_dec with s0 s; intros.\nleft.\nauto with pts.\n\nright; red in |- *; intros.\napply b.\ninversion_clear H0; auto with pts.\n\nright; red in |- *; intros.\ninversion_clear H0.\n\nright; red in |- *; intros.\ninversion_clear H0.\n\nright; red in |- *; intros.\ninversion_clear H0.\n\nright; red in |- *; intros.\ninversion_clear H0.\n\nintros.\nelim conv_hn_dec with e (Ref n) v; intros; auto with pts.\nleft.\ninversion_clear a; auto with pts.\n\nright; red in |- *; intros.\napply b.\ninversion_clear H0; auto with pts.\n\nintros.\nelim conv_hn_dec with e (Abs t t0) v; intros; auto with pts.\nleft.\ninversion_clear a; auto with pts.\n\nright; red in |- *; intros.\napply b.\ninversion_clear H0; auto with pts.\n\nintros.\nelim conv_hn_dec with e (App t t0) v; intros; auto with pts.\nleft.\ninversion_clear a; auto with pts.\n\nright; red in |- *; intros.\napply b.\ninversion_clear H0; auto with pts.\n\nintros A B.\ncase v; intros.\nright; red in |- *; intros.\ninversion_clear H0.\n\nright; red in |- *; intros.\ninversion_clear H0.\n\nright; red in |- *; intros.\ninversion_clear H0.\n\nright; red in |- *; intros.\ninversion_clear H0.\n\ncut (sn (ctxt hdr) e A).\ncut (sn (ctxt hdr) e t).\nintros sn2 sn3.\nelim whnf with e A; intros; auto with pts.\nelim whnf with e t; intros; auto with pts.\nelim H with e x0 x; intros.\ncut (rt_cumul e t A).\nintros cv.\ncut (sn (ctxt hdr) (Ax t :: e) B).\ncut (sn (ctxt hdr) (Ax t :: e) t0).\nintros sn4 sn5.\nelim whnf with (Ax t :: e) B; intros; auto with pts.\nelim whnf with (Ax t :: e) t0; intros; auto with pts.\nelim H with (Ax t :: e) x1 x2; intros.\nleft.\napply cuhi_prod; auto with pts.\nred in |- *; red in |- *.\napply rt_trans with x1; auto with pts.\napply rt_trans with x2; auto with pts.\nchange (rt_cumul (Ax t :: e) x1 x2) in |- *.\nauto with pts.\n\nright; red in |- *; intros.\napply b.\ninversion_clear H0.\napply inv_cumul_hn with B t0; auto with pts.\n\napply ord_cv_no_swap with B t0; auto with pts.\n\napply sn_red_sn with B; auto with pts.\n\napply sn_red_sn with t0; auto with pts.\n\napply subterm_sn with e (Prod t t0); auto with pts.\n\napply subterm_sn with e (Prod A B); auto with pts.\n\napply cumul_trans with x0; auto 10 with pts.\napply cumul_trans with x; auto 10 with pts.\n\nright; red in |- *; intros.\ninversion_clear H0.\napply b.\napply inv_cumul_hn with t A; auto with pts.\n\napply ord_cv_swap with t A; auto with pts.\n\napply sn_red_sn with t; auto with pts.\n\napply sn_red_sn with A; auto with pts.\n\napply subterm_sn with e (Prod t t0); auto with pts.\n\napply subterm_sn with e (Prod A B); auto with pts.\n\napply Acc_Acc3.\napply (Acc_inverse_image (env * (term * term)) (value * value)).\nsimpl in |- *.\napply sn_acc_ord_conv; trivial with pts.\nQed.\n\n\n  Theorem CR_WHNF_cumul_dec :\n   forall (e : env) (x y : term),\n   sn red_step e x -> sn red_step e y -> decide (rt_cumul e x y).\nintros.\nelim whnf with e x; intros; auto with pts.\nelim whnf with e y; intros; auto with pts.\nelim CR_WHNF_inv_cumul_dec with e x0 x1; intros.\nleft.\napply cumul_trans with x0; auto 10 with pts.\napply cumul_trans with x1; auto 10 with pts.\n\nright; red in |- *; intros.\napply b.\napply inv_cumul_hn with x y; auto with pts.\n\napply sn_red_sn with x; auto with pts.\n\napply sn_red_sn with y; auto with pts.\nQed.\n\n\n  Lemma cumul_inv_prod : product_inversion rt_cumul.\ncut\n (forall (e : env) (A B C D : term),\n  rt_cumul e (Prod A B) (Prod C D) ->\n  rt_cumul e C A /\\ rt_cumul (Ax C :: e) B D).\nsplit; intros.\nelim H with e A B C D; auto with pts.\n\nelim H with e A B C D; auto with pts.\n\nintros.\ncut (cumul_hn_inv e (Prod A B) (Prod C D)); intros.\ninversion_clear H0; auto with pts.\n\napply inv_cumul_hn with (Prod A B) (Prod C D); auto with pts.\nQed.", "meta": {"author": "coq-contribs", "repo": "pts", "sha": "10a0c39b7e62f8a7ec2afbbe516a21289d065be5", "save_path": "github-repos/coq/coq-contribs-pts", "path": "github-repos/coq/coq-contribs-pts/pts-10a0c39b7e62f8a7ec2afbbe516a21289d065be5/CumulDec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2737020741126227}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\nFrom ITree Require Import ITree.\nFrom Fairness Require Import\n  ITreeLib WFLib Axioms pind PCM Mod ModSim ModSimAux ModSimNat AddWorld ModAddSim Linking.\n\nImport Lia.\nImport OMod.\nImport Mod.\nImport RelationClasses.\n\nSection CLOSE_MONO_SIM.\n\n  Context {M1: Mod.t} {M2_src M2_tgt : Mod.t}.\n  Context {wf_src : WF}.\n  Context `{world : URA.t}.\n\n  Variable I : shared (state M2_src) (state M2_tgt) (ident M2_src) (ident M2_tgt) wf_src nat_wf -> world -> Prop.\n\n  Definition lift_ma :=\n    fun (x : @shared\n            (OMod.close M1 M2_src).(state) (OMod.close M1 M2_tgt).(state)\n            (OMod.close M1 M2_src).(ident) (OMod.close M1 M2_tgt).(ident)\n            (sum_wf wf_src nat_wf) nat_wf)\n      (r : URA.prod threadsRA world)\n    => let '(ths, IM_SRC, IM_TGT, st_src, st_tgt) := x in\n      exists im_src0 ths_ctx0 ths_usr0,\n        let im_ctx0 := pick_ctx IM_TGT in\n        let im_tgt0 := chop_ctx ths_usr0 IM_TGT in\n        IM_SRC = add_ctx im_ctx0 im_src0\n        /\\ NatMapP.Partition ths ths_ctx0 ths_usr0\n        /\\ fst r = global_th ths_ctx0 ths_usr0\n        /\\ fst st_src = fst st_tgt\n        /\\ lifted I (ths_usr0, im_src0, im_tgt0, snd st_src, snd st_tgt) (snd r).\n\n  Opaque lifted threadsRA URA.prod.\n\n  Lemma lift_ma_local_sim_ub R_src R_tgt (RR : R_src -> R_tgt -> Prop) ktr_src itr_tgt\n    : local_sim lift_ma RR (Vis (inl1 (inl1 (inl1 Undefined))) ktr_src) itr_tgt.\n  Proof.\n    (* treat as if tid ∈ ths_ctx *)\n    intros ths IM_SRC0 IM_TGT0 st_src0 st_tgt0 [r_sha_th0 r_sha_w0] [r_ctx_th0 r_ctx_w0] INV0_0 tid ths0 THS0 VALID0_0 IM_TGT1 TID_TGT.\n    simpl in INV0_0. des. subst r_sha_th0. unfold_prod VALID0_0.\n    assert (CTX_TGT : pick_ctx IM_TGT0 = pick_ctx IM_TGT1).\n    { extensionalities i. specialize (TID_TGT (inr (inl i))). ss. }\n    assert (USR_TGT : chop_ctx ths_usr0 IM_TGT0 = chop_ctx ths_usr0 IM_TGT1).\n    { extensionalities i. destruct i as [i|i].\n      - specialize (TID_TGT (inl i)). unfold prism_fmap in *; ss. des_ifs. exfalso.\n        eapply inv_add_new in THS0. des. eapply THS0.\n        eapply Partition_In_right in INV0_1. eapply INV0_1.\n        ss.\n      - specialize (TID_TGT (inr (inr i))). ss.\n    }\n    exists (global_th (TIdSet.add tid ths_ctx0) ths_usr0, r_sha_w0), (local_th_context tid, URA.unit). splits.\n    { exists im_src0, (TIdSet.add tid ths_ctx0), ths_usr0. splits; ss.\n      - subst. rewrite CTX_TGT. ss.\n      - eauto using NatMapP.Partition_sym, Partition_add.\n      - rewrite USR_TGT in INV0_4. ss.\n    }\n    { unfold_prod. split.\n      - eapply inv_add_new in THS0. des; subst. eapply global_th_alloc_context.\n        + eauto.\n        + eapply inv_add_new. split; ss.\n          ii. eapply THS0. eapply (Partition_In_left INV0_1). ss.\n        + ii. eapply THS0. eapply (Partition_In_right INV0_1). ss.\n      - rewrite URA.unit_id. eauto.\n    }\n    i. pfold. eapply pind9_fold. rewrite <- bind_trigger. econs.\n  Qed.\n\n  Notation pind := (fun r => pind9 (__lsim _ _ r) top9).\n  Notation cpn := (cpn9 _).\n  Tactic Notation \"muclo\" uconstr(H) :=\n    eapply gpaco9_uclo; [auto with paco|apply H|].\n\n  Lemma lift_ma_local_sim_usr R_src R_tgt (RR : R_src -> R_tgt -> Prop) itr_src itr_tgt\n        (SIM : local_sim (lifted I) RR itr_src itr_tgt)\n    :\n    forall ths0 im_src0\n           im_tgt0 st_src0 st_tgt0\n           (r_shared0 r_ctx0 : URA.prod threadsRA world)\n           (INV: lift_ma (ths0, im_src0, im_tgt0, st_src0, st_tgt0) r_shared0)\n           (tid : NatMap.key) (ths1 : NatMap.t unit)\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 : thread_id => if tid_dec i tid then Flag.success else Flag.emp))),\n    exists r_shared1 r_own : URA.prod threadsRA world,\n      (<<INV: lift_ma (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\n                (r_shared2 r_ctx2 : URA.prod threadsRA world)\n                (INV: lift_ma (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\n                 (TGT: fair_update im_tgt2 im_tgt3 (prism_fmap inlp (tids_fmap tid ths))),\n            (<<LSIM:\n              forall fs ft : bool,\n                lsim lift_ma tid (fun (r_src: R_src) (r_tgt: R_tgt) (r_ctx: URA.car) '(ths2, im_src1, im_tgt1, st_src1, st_tgt1) =>\n                                    (exists ths3 r_own r_shared,\n                                        (<<TIN: TIdSet.In tid ths2>>) /\\\n                                          (<<THS: NatMap.remove tid ths2 = ths3>>) /\\\n                                          (<<VALID: URA.wf (r_shared ⋅ r_own ⋅ r_ctx)>>) /\\\n                                          (<<INV: lift_ma (ths3, im_src1, im_tgt1, st_src1, st_tgt1) r_shared>>) /\\\n                                          (<<RET: RR r_src r_tgt>>))) fs ft r_ctx2 (map_event (emb_callee M1 M2_src) itr_src) (map_event (OMod.emb_callee M1 M2_tgt) itr_tgt)\n                     (ths, im_src1, im_tgt3, st_src2, st_tgt2) >>))\n  .\n  Proof.\n    (* tid ∈ ths_usr *)\n    intros ths IM_SRC0 IM_TGT0 st_src0 st_tgt0 [r_sha_th0 r_sha_w0] [r_ctx_th0 r_ctx_w0] INV0_0 tid ths0 THS0 VALID0_0. i.\n    simpl in INV0_0. des. subst r_sha_th0. unfold_prod VALID0_0.\n    move SIM at bottom.\n    assert (THS0' : TIdSet.add_new tid ths_usr0 (TIdSet.add tid ths_usr0)).\n    { eapply inv_add_new. split; ss. eapply inv_add_new in THS0. des.\n      eapply Partition_In_right in INV0_1. eauto.\n    }\n    assert (TID_TGT' : fair_update (chop_ctx ths_usr0 IM_TGT0) (chop_ctx (NatSet.add tid ths_usr0) im_tgt1) (prism_fmap inlp (fun i => if Nat.eq_dec i tid then Flag.success else Flag.emp))).\n    { ii. destruct i as [i|i]; ss.\n      - specialize (TID_TGT (inl i)). unfold prism_fmap in *; ss. destruct (Nat.eq_dec i tid); ss.\n        assert (H : tid <> i) by lia.\n        eapply NatMapP.F.add_neq_in_iff with (m := ths_usr0) (e := tt) in H.\n        des_ifs; tauto.\n      - specialize (TID_TGT (inr (inr i))). des_ifs.\n    }\n    specialize (SIM ths_usr0 im_src0 (chop_ctx ths_usr0 IM_TGT0) (snd st_src0) (snd st_tgt0) r_sha_w0 r_ctx_w0 INV0_4 tid (NatSet.add tid ths_usr0) THS0' VALID0_1 (chop_ctx (NatSet.add tid ths_usr0) im_tgt1) TID_TGT').\n    destruct SIM as [r_sha_w1 [r_own_w1 [INV_USR [VALID_USR SIM]]]].\n    exists (global_th ths_ctx0 (NatSet.add tid ths_usr0), r_sha_w1), (local_th_user tid, r_own_w1). splits.\n    { eapply inv_add_new in THS0. des. subst.\n      ss. esplits; ss.\n      - instantiate (1 := im_src0). extensionalities i. destruct i; ss.\n        specialize (TID_TGT (inr (inl i))). ss.\n        unfold pick_ctx. f_equal. ss.\n      - eapply Partition_add; eauto.\n        eapply inv_add_new; eauto.\n      - eapply INV_USR.\n    }\n    { unfold_prod. split.\n      - eapply global_th_alloc_user; eauto.\n        eapply inv_add_new in THS0. des. ii. eapply THS0.\n        eapply Partition_In_left in INV0_1. eapply INV0_1. ss.\n      - eauto.\n    }\n    intros ths2 IM_SRC2 IM_TGT2 st_src2 st_tgt2 [r_sha_th2 r_sha_w2] [r_ctx_th2 r_ctx_w2] INV2_0 VALID2_0 IM_TGT2' TGT fs ft.\n    simpl in INV2_0. destruct INV2_0 as [im_src2 [ths_ctx2 [ths_usr2 INV2_0]]]. des. subst r_sha_th2. unfold_prod VALID2_0.\n    assert (TGT' : @fair_update _ nat_wf (chop_ctx ths_usr2 IM_TGT2) (chop_ctx ths_usr2 IM_TGT2') (prism_fmap inlp (tids_fmap tid ths_usr2))).\n    { eapply chop_ctx_fair_thread2.\n      - eapply Partition_In_right in INV2_1. eapply INV2_1.\n      - eauto.\n    }\n    specialize (SIM ths_usr2 im_src2 (chop_ctx ths_usr2 IM_TGT2) (snd st_src2) (snd st_tgt2) r_sha_w2 r_ctx_w2 INV2_4 VALID2_1 (chop_ctx ths_usr2 IM_TGT2') TGT' fs ft).\n    unfold emb_l, emb_r.\n    eapply pick_ctx_fair_thread in TGT. rewrite TGT in INV2_0.\n    clear - INV2_0 INV2_1 INV2_3 VALID2_0 VALID2_1 SIM.\n    move tid before I.\n    rename\n      ths2 into ths0, ths_ctx2 into ths_ctx0, ths_usr2 into ths_usr0,\n      im_src2 into im_src0, IM_SRC2 into IM_SRC0, IM_TGT2' into IM_TGT0, st_src2 into st_src0, st_tgt2 into st_tgt0,\n      r_sha_w2 into r_sha_w0, r_ctx_th2 into r_ctx_th0, r_ctx_w2 into r_ctx_w0, r_own_w1 into r_own_w0,\n      INV2_0 into INV0, INV2_1 into INV1, INV2_3 into INV2, VALID2_0 into VALID_TH0, VALID2_1 into VALID_W0.\n    revert_until tid. ginit. gcofix CIH. i. gstep. punfold SIM.\n    match type of SIM with pind9 _ _ _ _ ?RR _ _ _ _ _ ?SHA => remember RR as RR_MEM; remember SHA as SHA_MEM end.\n    revert RR ths0 ths_ctx0 ths_usr0 st_src0 st_tgt0 r_sha_w0 r_own_w0 r_ctx_th0 im_src0 IM_SRC0 IM_TGT0 INV0 INV1 INV2 VALID_TH0 VALID_W0 HeqRR_MEM HeqSHA_MEM.\n    pattern R_src, R_tgt, RR_MEM, fs, ft, r_ctx_w0, itr_src, itr_tgt, SHA_MEM.\n    revert R_src R_tgt RR_MEM fs ft r_ctx_w0 itr_src itr_tgt SHA_MEM SIM.\n    eapply pind9_acc. intros rr DEC IH R_src R_tgt RR_MEM fs ft r_ctx_w0 itr_src itr_tgt SHA_MEM. i.\n    clear DEC. subst RR_MEM SHA_MEM.\n    eapply pind9_unfold in PR; eauto with paco. eapply pind9_fold. inv PR.\n    - clear - LSIM VALID_TH0 VALID_W0 INV1 INV2.\n      rewrite ! map_event_ret. econs.\n      ss. des. subst. (* inversion INV2. clear INV2. subst ths_ctx1 ths_usr1 ths3 IM_SRC0. *)\n      exists (NatMap.remove tid ths0), (URA.unit, r_own), (global_th ths_ctx0 (NatMap.remove tid ths_usr0), r_shared).\n      splits; ss.\n      + eapply Partition_In_right; eauto.\n        eapply local_th_user_in_user in VALID_TH0. exact VALID_TH0.\n      + unfold_prod. split.\n        * eapply global_th_dealloc_user; eauto.\n        * ss.\n      + esplits; ss.\n        * eapply local_th_user_in_user in VALID_TH0.\n          eapply Partition_remove; eauto.\n        * eapply lifted_drop_imap; eauto.\n          { i. destruct i as [i|i]; ss.\n            - assert (i = tid \\/ tid <> i) by lia. destruct H.\n              + pose proof NatMap.remove_1 H (m := ths_usr0). des_ifs; unfold le; ss; lia.\n              + pose proof (@NatMapP.F.remove_neq_in_iff _ ths_usr0 tid i H). des_ifs; try tauto; reflexivity.\n            - des_ifs. left. ss.\n          }\n    - rewrite map_event_tau. econs. split; ss.\n      destruct LSIM. eapply IH; eauto.\n    - rewrite map_event_trigger. econs.\n      des. destruct LSIM. exists x. split; ss.\n      eapply IH; eauto.\n    - rewrite map_event_trigger. econs. split; ss.\n      destruct st_src0; ss; subst.\n      destruct LSIM. eapply IH; eauto.\n    - rewrite map_event_trigger. econs. split; ss.\n      destruct LSIM. eapply IH; eauto.\n    - rewrite map_event_trigger. econs.\n    - rewrite map_event_trigger. econs.\n      des. destruct LSIM0. exists (add_ctx (pick_ctx IM_TGT0) im_src1). splits.\n      { clear - FAIR. ii. destruct i as [i|i]; ss.\n        unfold prism_fmap; ss. specialize (FAIR i). des_ifs.\n        - econs. ss.\n        - f_equal. ss.\n      }\n      split; ss. eapply IH; eauto.\n    - rewrite map_event_tau. econs. split; ss.\n      destruct LSIM. eapply IH; eauto.\n    - rewrite map_event_trigger. econs. i. specialize (LSIM x). split; ss.\n      destruct LSIM. eapply IH; eauto.\n    - rewrite map_event_trigger. econs. split; ss.\n      destruct st_tgt0; ss; subst.\n      destruct LSIM. eapply IH; eauto.\n    - rewrite map_event_trigger. econs. split; ss.\n      destruct LSIM. eapply IH; eauto.\n    - rewrite map_event_trigger. econs. intros IM_TGT1 FAIR. split; ss.\n      assert (FAIR' : fair_update (chop_ctx ths_usr0 IM_TGT0) (chop_ctx ths_usr0 IM_TGT1) (prism_fmap inrp f)).\n      { ii. destruct i as [i|i]; ss.\n        - specialize (FAIR (inl i)). ss. des_ifs.\n        - specialize (FAIR (inr (inr i))). ss.\n      }\n      specialize (LSIM (chop_ctx ths_usr0 IM_TGT1) FAIR').\n      destruct LSIM. eapply IH; eauto.\n      + extensionalities i. destruct i; ss. f_equal.\n        specialize (FAIR (inr (inl i))). ss.\n    - rewrite 2 map_event_trigger. econs. i. specialize (LSIM ret). pclearbot.\n      gfinal. left. eapply CIH; eauto.\n    - rewrite 2 map_event_trigger. apply lsim_call.\n      i. specialize (LSIM ret). pclearbot.\n      gfinal. left. eapply CIH; eauto.\n    - match goal with [ |- __lsim _ _ _ _ _ _ _ _ _ (map_event ?EMB _) _ ] => set EMB as emb end.\n      rewrite 2 map_event_trigger.\n      eapply lsim_yieldL. split; ss.\n      replace (trigger Yield) with (trigger (emb unit (subevent unit Yield))) by ss.\n      rewrite <- map_event_trigger.\n      destruct LSIM. eapply IH; eauto.\n    - match goal with [ |- __lsim _ _ _ _ _ _ _ _ (map_event ?EMB _) _ _ ] => set EMB as emb end.\n      rewrite 2 map_event_trigger.\n      eapply lsim_yieldR.\n      { instantiate (1 := (global_th ths_ctx0 ths_usr0, r_shared)).\n        ss. exists im_src0, ths_ctx0, ths_usr0. splits; ss.\n      }\n      { instantiate (1 := (local_th_user tid, r_own)). unfold_prod. split; ss. }\n      intros ths1 IM_SRC1 IM_TGT1 st_src1 st_tgt1 [r_sha_th1 r_sha_w1] [r_ctx_th1 r_ctx_w1] INV1_0 VALID1_0 IM_TGT2 TGT.\n      split; ss. des. unfold_prod VALID1_0.\n      assert (TGT' : fair_update (chop_ctx ths_usr1 IM_TGT1) (chop_ctx ths_usr1 IM_TGT2) (prism_fmap inlp (tids_fmap tid ths_usr1))).\n      { ii. destruct i as [i|i]; ss.\n        - eapply Partition_In_right in INV1_1. specialize (INV1_1 i). specialize (TGT (inl i)). unfold prism_fmap in *; ss.\n          unfold tids_fmap in *. destruct (Nat.eq_dec i tid); ss. des_ifs.\n          exfalso. tauto.\n        - specialize (TGT (inr (inr i))). ss.\n      }\n      specialize (LSIM ths_usr1 im_src1 (chop_ctx ths_usr1 IM_TGT1) (snd st_src1) (snd st_tgt1) r_sha_w1 r_ctx_w1 INV1_4 VALID1_1 (chop_ctx ths_usr1 IM_TGT2) TGT').\n      replace (trigger Yield) with (trigger (emb unit (subevent unit Yield))) by ss.\n      rewrite <- map_event_trigger.\n      destruct LSIM. eapply IH; eauto.\n      + subst. extensionalities i. destruct i as [i|i]; ss. f_equal.\n        specialize (TGT (inr (inl i))). ss.\n      + subst. ss.\n    - rewrite 2 map_event_trigger. eapply lsim_sync.\n      { instantiate (1 := (global_th ths_ctx0 ths_usr0, r_shared)).\n        ss. exists im_src0, ths_ctx0, ths_usr0. splits; ss.\n      }\n      { instantiate (1 := (local_th_user tid, r_own)). unfold_prod. split; ss. }\n      intros ths1 IM_SRC1 IM_TGT1 st_src1 st_tgt1 [r_sha_th1 r_sha_w1] [r_ctx_th1 r_ctx_w1] INV1_0 VALID1_0 IM_TGT2 TGT.\n      ss. des. unfold_prod VALID1_0.\n      assert (TGT' : fair_update (chop_ctx ths_usr1 IM_TGT1) (chop_ctx ths_usr1 IM_TGT2) (prism_fmap inlp (tids_fmap tid ths_usr1))).\n      { ii. destruct i as [i|i]; ss.\n        - eapply Partition_In_right in INV1_1. specialize (INV1_1 i). specialize (TGT (inl i)). unfold prism_fmap in *; ss.\n          unfold tids_fmap in *. destruct (Nat.eq_dec i tid); ss. des_ifs.\n          exfalso. tauto.\n        - specialize (TGT (inr (inr i))). ss.\n      }\n      specialize (LSIM ths_usr1 im_src1 (chop_ctx ths_usr1 IM_TGT1) (snd st_src1) (snd st_tgt1) r_sha_w1 r_ctx_w1 INV1_4 VALID1_1 (chop_ctx ths_usr1 IM_TGT2) TGT').\n      pclearbot.\n      gfinal. left. eapply CIH; eauto.\n      + subst. extensionalities i. destruct i as [i|i]; ss. f_equal.\n        specialize (TGT (inr (inl i))). ss.\n      + subst. ss.\n    - econs. pclearbot. gfinal. left. eapply CIH; eauto.\n  Qed.\n\n  Lemma lift_ma_local_sim_ctx\n        (FSIM: forall (fn : string) (args : Any.t),\n            match funs M2_src fn with\n            | Some ktr_src =>\n                match funs M2_tgt fn with\n                | Some ktr_tgt => local_sim I eq (ktr_src args) (ktr_tgt args)\n                | None => False\n                end\n            | None => match funs M2_tgt fn with\n                      | Some _ => False\n                      | None => True\n                      end\n            end)\n    :\n    forall R (itr: itree _ R),\n      local_sim (lift_ma) eq (close_itree M1 M2_src itr) (close_itree M1 M2_tgt itr)\n  .\n  Proof.\n    i.\n    intros ths IM_SRC0 IM_TGT0 st_src0 st_tgt0 [r_sha_th0 r_sha_w0] [r_ctx_th0 r_ctx_w0] INV0_0 tid ths0 THS0 VALID0_0 IM_TGT1 TID_TGT.\n    simpl in INV0_0. des. subst r_sha_th0. unfold_prod VALID0_0.\n    assert (CTX_TGT : pick_ctx IM_TGT0 = pick_ctx IM_TGT1).\n    { extensionalities i. specialize (TID_TGT (inr (inl i))). ss. }\n    assert (USR_TGT : chop_ctx ths_usr0 IM_TGT0 = chop_ctx ths_usr0 IM_TGT1).\n    { extensionalities i. destruct i as [i|i].\n      - specialize (TID_TGT (inl i)). unfold prism_fmap in *; ss. des_ifs. exfalso.\n        eapply inv_add_new in THS0. des. eapply THS0.\n        eapply Partition_In_right in INV0_1. eapply INV0_1.\n        ss.\n      - specialize (TID_TGT (inr (inr i))). ss.\n    }\n    exists (global_th (TIdSet.add tid ths_ctx0) ths_usr0, r_sha_w0), (local_th_context tid, URA.unit). splits.\n    { exists im_src0, (TIdSet.add tid ths_ctx0), ths_usr0. splits; ss.\n      - subst. rewrite CTX_TGT. ss.\n      - eauto using NatMapP.Partition_sym, Partition_add.\n      - rewrite USR_TGT in INV0_4. ss.\n    }\n    { unfold_prod. split.\n      - eapply inv_add_new in THS0. des; subst. eapply global_th_alloc_context.\n        + eauto.\n        + eapply inv_add_new. split; ss.\n          ii. eapply THS0. eapply (Partition_In_left INV0_1). ss.\n        + ii. eapply THS0. eapply (Partition_In_right INV0_1). ss.\n      - rewrite URA.unit_id. eauto.\n    }\n    intros ths1 IM_SRC1 IM_TGT2 st_src1 st_tgt1 [r_sha_th1 r_sha_w1] [r_ctx_th1 r_ctx_w1] INV1_0 VALID1_0.\n    intros IM_TGT2' TGT fs ft.\n    simpl in INV1_0. des. subst r_sha_th1. unfold_prod VALID1_0.\n    unfold emb_l, emb_r.\n    assert (INV : lift_ma (ths1, IM_SRC1, IM_TGT2', st_src1, st_tgt1) (global_th ths_ctx1 ths_usr1, r_sha_w1)).\n    { ss. exists im_src1, ths_ctx1, ths_usr1. splits; ss.\n      - eapply pick_ctx_fair_thread in TGT. rewrite <- TGT. ss.\n      - eapply shared_rel_wf_lifted; eauto.\n        eapply chop_ctx_fair_thread1; eauto.\n        eapply local_th_context_in_context; eauto.\n    }\n    clear - FSIM INV VALID1_0 VALID1_1. move itr after tid.\n    rename\n      ths1 into ths0, ths_ctx1 into ths_ctx0, ths_usr1 into ths_usr0,\n      IM_SRC1 into IM_SRC0, IM_TGT2' into IM_TGT0, st_src1 into st_src0, st_tgt1 into st_tgt0,\n      r_sha_w1 into r_sha_w0, r_ctx_th1 into r_ctx_th0, r_ctx_w1 into r_ctx_w0,\n      INV into INV0, VALID1_0 into VALID_TH0, VALID1_1 into VALID_W0.\n    revert_until tid. ginit. gcofix CIH. i.\n    destruct_itree itr; [| | destruct e as [[[|]|]|] ].\n    - rewrite 2 close_itree_ret.\n      gstep. eapply pind9_fold. econs. ss.\n      exists (NatSet.remove tid ths0), (URA.unit, URA.unit), (global_th (NatSet.remove tid ths_ctx0) ths_usr0, r_sha_w0).\n      splits; ss.\n      { unfold_prod. split.\n        - eapply global_th_dealloc_context; eauto.\n        - eauto.\n      }\n      { des. inversion INV2. subst ths_ctx1 ths_usr1. exists im_src0, (NatSet.remove tid ths_ctx0), ths_usr0. splits; ss.\n        eapply local_th_context_in_context in VALID_TH0.\n        eauto using NatMapP.Partition_sym, Partition_remove.\n      }\n    - rewrite 2 close_itree_tau.\n      gstep.\n      eapply pind9_fold. econs. split; ss.\n      eapply pind9_fold. econs. split; ss.\n      eapply pind9_fold. econs.\n      gfinal. left. eapply CIH; eauto.\n    - rewrite 2 close_itree_vis_eventE.\n      rewrite <- 2 bind_trigger.\n      gstep. destruct e; ss.\n      + eapply pind9_fold. eapply lsim_chooseR. i. esplit; ss.\n        eapply pind9_fold. eapply lsim_chooseL. exists x. esplit; ss.\n        eapply pind9_fold. econs. split; ss.\n        eapply pind9_fold. econs. split; ss.\n        eapply pind9_fold. eapply lsim_progress.\n        gfinal. left. eapply CIH; eauto.\n      + eapply pind9_fold. eapply lsim_fairR. intros IM_TGT1 FAIR. esplit; ss.\n        eapply pind9_fold. eapply lsim_fairL.\n        des. inversion INV2. subst ths_ctx1 ths_usr1. exists (add_ctx (pick_ctx IM_TGT1) im_src0). split.\n        { subst. ii. destruct i; ss.\n          specialize (FAIR (inr (inl i))). unfold pick_ctx, prism_fmap in *; ss. des_ifs.\n          + econs. ss.\n          + f_equal. ss.\n        }\n        split; ss.\n        eapply pind9_fold. econs. split; ss.\n        eapply pind9_fold. econs. split; ss.\n        eapply pind9_fold. eapply lsim_progress.\n        gfinal. left. des. eapply CIH; eauto.\n        { esplits; eauto. eapply chop_ctx_fair_ctx in FAIR. rewrite <- FAIR. ss. }\n      + eapply pind9_fold. eapply lsim_observe. i.\n        gstep.\n        eapply pind9_fold. econs. split; ss.\n        eapply pind9_fold. econs. split; ss.\n        eapply pind9_fold. econs.\n        gfinal. left. eapply CIH; eauto.\n      + eapply pind9_fold. eapply lsim_UB.\n    - rewrite 2 close_itree_vis_cE.\n      rewrite <- 2 bind_trigger.\n      gstep. destruct c.\n      + eapply pind9_fold. eapply lsim_sync.\n        { eapply INV0. }\n        { instantiate (1 := (local_th_context tid, ε)). unfold_prod. split; ss. }\n        intros ths1 IM_SRC1 IM_TGT1 st_src1 st_tgt1 [r_sha_th1 r_sha_w1] [r_ctx_th1 r_ctx_w1] INV1_0 VALID1_0 IM_TGT1' TGT.\n        simpl in INV1_0. des. subst r_sha_th1. rename im_src0 into im_src1. unfold_prod VALID1_0.\n        gstep.\n        eapply pind9_fold. econs. split; ss.\n        eapply pind9_fold. econs. split; ss.\n        eapply pind9_fold. econs.\n        gfinal. left. eapply CIH; eauto.\n        { exists im_src1, ths_ctx1, ths_usr1. ss. splits; ss.\n          - eapply pick_ctx_fair_thread in TGT. rewrite <- TGT. ss.\n          - eapply shared_rel_wf_lifted; eauto.\n            eapply chop_ctx_fair_thread1; eauto.\n            eapply local_th_context_in_context; eauto.\n        }\n      + eapply pind9_fold. eapply lsim_tidR. esplit; ss.\n        eapply pind9_fold. eapply lsim_tidL. esplit; ss.\n        eapply pind9_fold. econs. split; ss.\n        eapply pind9_fold. econs. split; ss.\n        eapply pind9_fold. eapply lsim_progress.\n        gfinal. left. eapply CIH; eauto.\n    - destruct c. rewrite 2 close_itree_vis_call. simpl.\n      specialize (FSIM fn arg).\n      des_ifs.\n      + rewrite <- 2 bind_trigger.\n        gstep. eapply pind9_fold. eapply lsim_sync; eauto.\n        { instantiate (1:=(local_th_context tid, ε)). unfold_prod; ss. }\n        move FSIM at bottom.\n        eapply local_sim_clos_trans in FSIM; [|econs; exact 0].\n        eapply local_sim_wft_mono with (wft_lt := lt (wf_clos_trans nat_wf)) in FSIM; cycle 1.\n        { i; econs; ss. eauto. }\n\n        i.\n\n        Set Nested Proofs Allowed.\n        Lemma lift_ma_pop_push ths0 im_src im_tgt st_src st_tgt r0 r_ctx\n              tid\n              (INV: lift_ma (ths0, im_src, im_tgt, st_src, st_tgt) r0)\n              (WF: URA.wf (r0 ⋅ (local_th_context tid, ε) ⋅ r_ctx))\n          :\n          exists ths1 r1,\n            (<<INV: lift_ma (ths1, im_src, im_tgt, st_src, st_tgt) r1>>) /\\\n              (<<WF: URA.wf (r1 ⋅ r_ctx)>>) /\\\n              (<<ADD: TIdSet.add_new tid ths1 ths0>>).\n        Proof.\n          red in INV. des. subst. destruct r0, r_ctx. ss. subst.\n          rewrite unfold_prod_wf in WF. rewrite unfold_prod_add in WF. ss. des.\n          hexploit local_th_context_in_context; eauto. i.\n          hexploit Partition_remove.\n          { eapply NatMapP.Partition_sym. eauto. }\n          { eauto. }\n          intros PART. hexploit global_th_dealloc_context; eauto.\n          intros WF1. eexists _, (_, _). esplits.\n          { eauto. }\n          { eapply NatMapP.Partition_sym. eauto. }\n          { ss. }\n          { eauto. }\n          { eauto. }\n          { rewrite URA.unit_id in WF1. rewrite URA.unit_id in WF0.\n            rewrite unfold_prod_wf. rewrite unfold_prod_add. auto.\n          }\n          { rr. econs.\n            { eapply nm_find_rm_eq. }\n            { eapply nm_find_some_rm_add_eq.\n              eapply Partition_In_left in H; eauto.\n              eapply NatMapP.F.in_find_iff in H.\n              destruct (NatMap.find tid ths0) as [[]|]; ss.\n            }\n          }\n        Qed.\n\n        Lemma lift_ma_push_pop ths im_src im_tgt st_src st_tgt r0 r_ctx\n              tid r_own\n              (INV: lift_ma (NatMap.remove tid ths, im_src, im_tgt, st_src, st_tgt) r0)\n              (WF: URA.wf (r0 ⋅ r_own ⋅ r_ctx))\n              (IN: TIdSet.In tid ths)\n          :\n          exists r1,\n            (<<INV: lift_ma (ths, im_src, im_tgt, st_src, st_tgt) r1>>) /\\\n              (<<WF: URA.wf (r1 ⋅ (local_th_context tid, ε) ⋅ r_ctx)>>).\n        Proof.\n          red in INV. des. subst. destruct r0, r_own, r_ctx. ss. subst.\n          rewrite unfold_prod_wf in WF. rewrite unfold_prod_add in WF. ss. des.\n          hexploit global_th_alloc_context.\n          { rewrite <- URA.add_assoc in WF. eapply WF. }\n          { econs.\n            { eapply NatMapP.F.not_find_in_iff. ii.\n              eapply Partition_In_left in H; eauto.\n              eapply NatMap.remove_1 in H; eauto.\n            }\n            { ss. }\n          }\n          { ii. eapply Partition_In_right in H; eauto.\n            eapply NatMap.remove_1 in H; eauto.\n          }\n          i. eexists (_, _). esplits.\n          { ss. }\n          { eapply NatMapP.Partition_sym.\n            eapply Partition_add.\n            { eapply NatMapP.Partition_sym. eauto. }\n            econs; eauto.\n            { eapply NatMapP.F.not_find_in_iff.\n              eapply NatMap.remove_1; eauto.\n            }\n            { eapply nm_find_some_rm_add_eq.\n              instantiate (1:=tt). destruct (NatMap.find tid ths) as [[]|] eqn:EQ; ss.\n              eapply NatMapP.F.not_find_in_iff in EQ; eauto. ss.\n            }\n          }\n          { ss. }\n          { ss. }\n          { eauto. }\n          rewrite unfold_prod_wf. rewrite unfold_prod_add. ss. split.\n          { eapply URA.wf_mon. instantiate (1:=c1). r_wf H. }\n          { eapply URA.wf_mon. instantiate (1:=c2). r_wf WF0. }\n        Qed.\n\n        hexploit lift_ma_pop_push; eauto. i. des.\n        muclo lsim_bindC'_spec. cbn. econs; eauto.\n        * hexploit lift_ma_local_sim_usr; eauto.\n          { instantiate (1:=im_tgt1). ii. unfold prism_fmap; ss. des_ifs. }\n          i. des. hexploit H1; eauto. i.\n          gfinal. right. eapply paco9_mon; [eapply H|]; ss.\n        * i. destruct r_ctx as [r_ctx0 r_ctx2]. destruct shr as [[[[shr0 shr1] shr2] shr3] shr4].\n          muclo lsim_indC_spec. cbn. econs; eauto.\n          muclo lsim_indC_spec. cbn. econs; eauto.\n          des. subst.\n          hexploit lift_ma_push_pop; eauto.\n          i. des. destruct r0.\n          rewrite unfold_prod_wf in WF0. rewrite unfold_prod_add in WF0. ss. des. subst.\n          gbase. eapply CIH; eauto.\n          esplits; eauto.\n      + rewrite <- 2 bind_trigger.\n        gstep. eapply pind9_fold. econs; eauto.\n    - destruct s.\n      rewrite ! close_itree_vis_rmw, <- ! bind_trigger.\n      gstep.\n      eapply pind9_fold. eapply lsim_rmwL. split; ss.\n      eapply pind9_fold. eapply lsim_rmwR. split; ss.\n      eapply pind9_fold. eapply lsim_tauL. split; ss.\n      eapply pind9_fold. eapply lsim_tauR. split; ss.\n      eapply pind9_fold. eapply lsim_progress.\n      des. destruct st_src0, st_tgt0; ss; subst.\n      gbase. eapply CIH; eauto. esplits; eauto.\n  Qed.\n\nEnd CLOSE_MONO_SIM.\n\nSection MODADD_THEOREM.\n\n  Theorem ModClose_mono M1 M2_src M2_tgt :\n    ModSim.mod_sim M2_src M2_tgt ->\n    ModSim.mod_sim (close M1 M2_src) (close M1 M2_tgt).\n  Proof.\n    i. eapply modsim_nat_modsim_exist in H. inv H.\n    (* pose (I' := @lift_ma M1 M2_src M2_tgt _ _ I). *)\n    econstructor 1 with (world:=URA.prod threadsRA world).\n    (* constructor 1 with _ _ _ I'. *)\n    { instantiate (1:=nat_wf). econs. exact 0. }\n    { i. exists (S o0). ss. }\n    intro IM_TGT. specialize (init (chop_ctx NatSet.empty IM_TGT)). des.\n    pose (I' := @lift_ma M1 M2_src M2_tgt _ _ I). exists I'.\n    pose (pick_ctx IM_TGT) as im_ctx.\n    split.\n    { exists (add_ctx im_ctx im_src), (global_th NatSet.empty NatSet.empty, r_shared). ss. split.\n      - exists im_src. exists NatSet.empty, NatSet.empty. splits; ss.\n        + eapply Partition_empty.\n        + exists (chop_ctx NatSet.empty IM_TGT). split; ss. ii. left. ss.\n      - unfold_prod. split; ss. rewrite URA.unfold_wf. econs; ss. eapply Disjoint_empty.\n    }\n    i. unfold close, closed_funs; ss. des_ifs.\n    - eapply lift_ma_local_sim_ctx; eauto.\n  Qed.\n\n  Tactic Notation \"muclo\" uconstr(H) :=\n    eapply gpaco9_uclo; [auto with paco|apply H|].\n\n  Theorem ModClose_assoc M1 M2 M3 :\n    ModSim.mod_sim (close M1 (close M2 M3)) (close (close M1 M2) M3).\n  Proof.\n    econstructor 1 with (world := Unit).\n    { instantiate (1 := nat_wf). econs. exact 0. }\n    { i. exists (S o0). ss. }\n    intro IM_TGT.\n    pose Unit_wf as VALID.\n    pose (conv_im :=\n            (fun im_tgt i =>\n               match i with\n               | inl i => im_tgt (inr (inl (inl i)))\n               | inr (inl i) => im_tgt (inr (inl (inr i)))\n               | inr (inr i) => im_tgt (inr (inr i))\n               end)\n            : @imap (ident_tgt (close (close M1 M2) M3).(ident)) nat_wf ->\n              @imap (close M1 (close M2 M3)).(ident) nat_wf).\n    pose (I := fun (x : @shared\n                        (close M1 (close M2 M3)).(state) (close (close M1 M2) M3).(state)\n                        (close M1 (close M2 M3)).(ident) (close (close M1 M2) M3).(ident)\n                        nat_wf nat_wf)\n                 (w : Unit)\n               => let '(ths, im_src, im_tgt, st_src, st_tgt) := x in\n                 (fst st_src : state M1) = fst (fst st_tgt)\n                 /\\ (fst (snd st_src) : state M2) = snd (fst st_tgt)\n                 /\\ (snd (snd st_src) : state M3) = snd st_tgt\n                 /\\ im_src = conv_im im_tgt\n         ).\n    exists I. split.\n    { exists (conv_im IM_TGT), tt. splits; ss. }\n    i. do 2 (ss; unfold closed_funs). destruct (funs M1 fn); ss.\n    remember (k args) as itr; clear k args Heqitr.\n    ii. exists tt, tt. splits; ss.\n    { des. splits; ss.\n      rewrite INV2. extensionalities i. destruct i as [|[|]].\n      - specialize (TID_TGT (inr (inl (inl i)))); ss.\n      - specialize (TID_TGT (inr (inl (inr i)))); ss.\n      - specialize (TID_TGT (inr (inr i))); ss.\n    }\n    i.\n    assert (INV_CIH : I (ths, im_src1, im_tgt3, st_src2, st_tgt2) tt).\n    { des. ss. splits; ss.\n      rewrite INV3. extensionalities i. destruct i as [|[|]].\n      - specialize (TGT (inr (inl (inl i)))); ss.\n      - specialize (TGT (inr (inl (inr i)))); ss.\n      - specialize (TGT (inr (inr i))); ss.\n    }\n    clear - INV_CIH. move itr after tid. revert_until tid.\n    pose proof Unit_wf as VALID.\n    ginit. gcofix CIH. i. destruct_itree itr.\n    - rewrite ! close_itree_ret.\n      gstep. eapply pind9_fold. eapply lsim_ret.\n      ss. eexists. exists tt, tt. des. splits; ss.\n    - rewrite ! close_itree_tau.\n      gstep.\n      eapply pind9_fold. eapply lsim_tauL. split; ss.\n      eapply pind9_fold. eapply lsim_tauR. split; ss.\n      eapply pind9_fold. eapply lsim_progress.\n      gfinal. left. eapply CIH. des. splits; ss.\n    - destruct e as [[[e|ce]|cae]|s].\n      + rewrite ! close_itree_vis_eventE.\n        rewrite <- ! bind_trigger.\n        destruct e.\n        * gstep. eapply pind9_fold. eapply lsim_chooseR. i. split; ss.\n          eapply pind9_fold. eapply lsim_chooseL. exists x. split; ss.\n          eapply pind9_fold. eapply lsim_tauL. split; ss.\n          rewrite close_itree_tau.\n          eapply pind9_fold. eapply lsim_tauR. split; ss.\n          eapply pind9_fold. eapply lsim_tauR. split; ss.\n          eapply pind9_fold. eapply lsim_progress.\n          gfinal. left. eapply CIH. des. splits; ss.\n        * gstep. eapply pind9_fold. eapply lsim_fairR. i. split; ss.\n          eapply pind9_fold. eapply lsim_fairL. exists (conv_im im_tgt1). split.\n          { des. rewrite INV_CIH2. ii. destruct i as [|[|]].\n            unfold prism_fmap in *. ss.\n            - specialize (FAIR (inr (inl (inl i)))). ss.\n            - specialize (FAIR (inr (inl (inr i)))). ss.\n            - specialize (FAIR (inr (inr i))). ss.\n          }\n          split; ss.\n          eapply pind9_fold. eapply lsim_tauL. split; ss.\n          rewrite close_itree_tau.\n          eapply pind9_fold. eapply lsim_tauR. split; ss.\n          eapply pind9_fold. eapply lsim_tauR. split; ss.\n          eapply pind9_fold. eapply lsim_progress.\n          gfinal. left. eapply CIH. des. splits; ss.\n        * gstep. eapply pind9_fold. eapply lsim_observe. i.\n          gstep. eapply pind9_fold. eapply lsim_tauL. split; ss.\n          rewrite close_itree_tau.\n          eapply pind9_fold. eapply lsim_tauR. split; ss.\n          eapply pind9_fold. eapply lsim_tauR. split; ss.\n          eapply pind9_fold. eapply lsim_progress.\n          gfinal. left. eapply CIH. des. splits; ss.\n        * gstep. eapply pind9_fold. eapply lsim_UB.\n      + rewrite ! close_itree_vis_cE.\n        rewrite <- ! bind_trigger.\n        destruct ce.\n        * gstep. eapply pind9_fold. eapply lsim_sync; ss. i.\n          gstep. eapply pind9_fold. eapply lsim_tauL. split; ss.\n          rewrite close_itree_tau.\n          eapply pind9_fold. eapply lsim_tauR. split; ss.\n          eapply pind9_fold. eapply lsim_tauR. split; ss.\n          eapply pind9_fold. eapply lsim_progress.\n          gfinal. left. eapply CIH. des. splits; ss.\n          { rewrite INV2. extensionalities i. destruct i as [|[|]].\n            - specialize (TGT (inr (inl (inl i)))). ss.\n            - specialize (TGT (inr (inl (inr i)))). ss.\n            - specialize (TGT (inr (inr i))). ss.\n          }\n        * gstep. eapply pind9_fold. eapply lsim_tidR. split; ss.\n          eapply pind9_fold. eapply lsim_tidL. split; ss.\n          eapply pind9_fold. eapply lsim_tauL. split; ss.\n          rewrite close_itree_tau.\n          eapply pind9_fold. eapply lsim_tauR. split; ss.\n          eapply pind9_fold. eapply lsim_tauR. split; ss.\n          eapply pind9_fold. eapply lsim_progress.\n          gfinal. left. eapply CIH. des. splits; ss.\n      + destruct cae. rewrite ! close_itree_vis_call.\n        ss. unfold closed_funs. destruct (funs M2 fn).\n        * rewrite close_itree_vis_cE.\n          rewrite <- ! bind_trigger.\n          rewrite close_itree_bind.\n          gstep. eapply pind9_fold. eapply lsim_sync; ss.\n          i.\n          assert (INV_CIH2 : I (ths1, im_src0, im_tgt2, st_src1, st_tgt1) tt).\n          { des. ss. splits; ss.\n            rewrite INV2.\n            extensionalities i. destruct i as [|[|]].\n            - specialize (TGT (inr (inl (inl i)))). ss.\n            - specialize (TGT (inr (inl (inr i)))). ss.\n            - specialize (TGT (inr (inr i))). ss.\n          }\n          clear - CIH INV_CIH2.\n          gstep. eapply pind9_fold. eapply lsim_tauR. split; ss.\n          eapply pind9_fold. eapply lsim_progress. split; ss.\n          muclo lsim_bindC'_spec. econs.\n          { instantiate (1 := fun r_src r_tgt r_ctx shr => r_src = r_tgt /\\ I shr tt).\n            remember (k0 arg) as itr; clear - INV_CIH2.\n            revert_until r. gcofix CIH. i.\n            pose Unit_wf as VALID.\n            destruct_itree itr.\n            - rewrite ! close_itree_ret.\n              rewrite ! map_event_ret.\n              rewrite ! close_itree_ret.\n              gstep. eapply pind9_fold. eapply lsim_ret. esplits; ss.\n            - rewrite ! close_itree_tau.\n              rewrite ! map_event_tau.\n              rewrite ! close_itree_tau.\n              gstep. eapply pind9_fold. eapply lsim_tauL. split; ss.\n              eapply pind9_fold. eapply lsim_tauR. split; ss.\n              eapply pind9_fold. eapply lsim_progress.\n              gfinal. left. eapply CIH; ss.\n            - destruct e as [[[e|ce]|cae]|s].\n              + rewrite ! close_itree_vis_eventE.\n                rewrite ! map_event_vis. unfold emb_callee; ss.\n                rewrite ! close_itree_vis_eventE.\n                rewrite <- ! bind_trigger.\n                destruct e.\n                * gstep. eapply pind9_fold. eapply lsim_chooseR. i. split; ss.\n                  eapply pind9_fold. eapply lsim_chooseL. exists x. split; ss.\n                  rewrite map_event_tau.\n                  eapply pind9_fold. eapply lsim_tauL. split; ss.\n                  eapply pind9_fold. eapply lsim_tauR. split; ss.\n                  eapply pind9_fold. eapply lsim_progress.\n                  gfinal. left. eapply CIH; ss.\n                * gstep. eapply pind9_fold. eapply lsim_fairR. i. split; ss.\n                  eapply pind9_fold. eapply lsim_fairL. exists (conv_im im_tgt1). split.\n                  { des. rewrite INV_CIH3. ii. destruct i as [|[|]].\n                    unfold prism_fmap in *. ss.\n                    - specialize (FAIR (inr (inl (inl i)))). ss.\n                    - specialize (FAIR (inr (inl (inr i)))). ss.\n                    - specialize (FAIR (inr (inr i))). ss.\n                  }\n                  split; ss.\n                  rewrite map_event_tau.\n                  eapply pind9_fold. eapply lsim_tauL. split; ss.\n                  eapply pind9_fold. eapply lsim_tauR. split; ss.\n                  eapply pind9_fold. eapply lsim_progress.\n                  gfinal. left. eapply CIH; ss.\n                * gstep. eapply pind9_fold. eapply lsim_observe. i.\n                  rewrite map_event_tau.\n                  gstep.\n                  eapply pind9_fold. eapply lsim_tauL. split; ss.\n                  eapply pind9_fold. eapply lsim_tauR. split; ss.\n                  eapply pind9_fold. eapply lsim_progress.\n                  gfinal. left. eapply CIH; ss.\n                * gstep. eapply pind9_fold. eapply lsim_UB.\n              + rewrite ! close_itree_vis_cE.\n                rewrite ! map_event_vis. unfold emb_callee; ss.\n                rewrite ! close_itree_vis_cE.\n                rewrite <- ! bind_trigger.\n                destruct ce.\n                * gstep. eapply pind9_fold. eapply lsim_sync; ss. i.\n                  rewrite map_event_tau.\n                  gstep.\n                  eapply pind9_fold. eapply lsim_tauL. split; ss.\n                  eapply pind9_fold. eapply lsim_tauR. split; ss.\n                  eapply pind9_fold. eapply lsim_progress.\n                  gfinal. left. des. eapply CIH; ss.\n                  { rewrite INV2. extensionalities i. destruct i as [|[|]].\n                    - specialize (TGT (inr (inl (inl i)))). ss.\n                    - specialize (TGT (inr (inl (inr i)))). ss.\n                    - specialize (TGT (inr (inr i))). ss.\n                  }\n                * gstep. eapply pind9_fold. eapply lsim_tidR. split; ss.\n                  eapply pind9_fold. eapply lsim_tidL. split; ss.\n                  rewrite map_event_tau.\n                  eapply pind9_fold. eapply lsim_tauL. split; ss.\n                  eapply pind9_fold. eapply lsim_tauR. split; ss.\n                  eapply pind9_fold. eapply lsim_progress.\n                  gfinal. left. des. eapply CIH; ss.\n              + destruct cae.\n                rewrite ! map_event_vis. unfold emb_callee; ss.\n                rewrite ! close_itree_vis_call.\n                destruct (funs M3 fn).\n                * rewrite map_event_vis.\n                  rewrite <- ! bind_trigger.\n                  gstep. eapply pind9_fold. eapply lsim_sync; ss. i.\n                  assert (INV_CIH4 : I (ths0, im_src1, im_tgt0, st_src0, st_tgt0) tt).\n                  { des. ss. splits; ss.\n                    rewrite INV2.\n                    extensionalities i. destruct i as [|[|]].\n                    - specialize (TGT (inr (inl (inl i)))). ss.\n                    - specialize (TGT (inr (inl (inr i)))). ss.\n                    - specialize (TGT (inr (inr i))). ss.\n                  }\n                  clear - CIH INV_CIH4.\n                  gstep. eapply pind9_fold. eapply lsim_progress.\n                  rewrite map_event_bind.\n                  muclo lsim_bindC'_spec. econs.\n                  { instantiate (1 := fun r_src r_tgt r_ctx shr => r_src = r_tgt /\\ I shr tt).\n                    gfinal. right.\n                    unfold emb_callee. rewrite <- map_event_compose, <- plmap_compose.\n                    eapply paco9_mon. eapply lsim_refl.\n                    - firstorder.\n                      + destruct st_src as [? []], st_tgt as [[] ?]; ss.\n                        unfold Lens.set in *; ss. subst; ss.\n                      + destruct st_src as [? []], st_tgt as [[] ?]; ss.\n                        unfold Lens.set in *; ss. subst; ss.\n                      + destruct st_src as [? []], st_tgt as [[] ?]; ss.\n                        unfold Lens.set in *; ss. subst; ss.\n                    - firstorder.\n                      + subst. ss.\n                      + subst. extensionalities i. destruct i; ss. destruct i; ss.\n                    - firstorder.\n                      + subst. ss.\n                    - firstorder.\n                    - eauto.\n                    - ss.\n                  }\n                  i. destruct shr as [[[[ths2 im_src] im_tgt] st_src] st_tgt]. destruct SAT. subst.\n                  rewrite map_event_tau.\n                  gstep.\n                  eapply pind9_fold. eapply lsim_tauL. split; ss.\n                  eapply pind9_fold. eapply lsim_tauR. split; ss.\n                  eapply pind9_fold. eapply lsim_progress.\n                  gfinal. left. des. eapply CIH; ss.\n                * rewrite map_event_vis.\n                  rewrite <- ! bind_trigger.\n                  gstep. eapply pind9_fold. eapply lsim_UB.\n              + destruct s.\n                rewrite ! map_event_vis. unfold emb_callee; ss.\n                rewrite ! close_itree_vis_rmw.\n                rewrite ! map_event_vis.\n                rewrite <- ! bind_trigger.\n                gstep.\n                eapply pind9_fold. eapply lsim_rmwL. split; ss.\n                eapply pind9_fold. eapply lsim_rmwR. split; ss.\n                rewrite ! map_event_tau.\n                eapply pind9_fold. eapply lsim_tauL. split; ss.\n                eapply pind9_fold. eapply lsim_tauR. split; ss.\n                eapply pind9_fold. eapply lsim_progress.\n                des. destruct st_src1 as [s0 []], st_tgt1 as [[] s2]; ss; subst.\n                gbase. eapply CIH; ss.\n          }\n          i. destruct shr as [[[[ths2 im_src] im_tgt] st_src] st_tgt]. destruct SAT. subst.\n          rewrite close_itree_tau.\n          gstep. eapply pind9_fold. eapply lsim_tauR. split; ss.\n          eapply pind9_fold. eapply lsim_tauL. split; ss.\n          eapply pind9_fold. eapply lsim_progress.\n          gfinal. left. eapply CIH. des. splits; ss.\n        * rewrite ! close_itree_vis_eventE.\n          rewrite <- ! bind_trigger.\n          gstep. eapply pind9_fold. eapply lsim_UB.\n      + destruct s.\n        rewrite ! close_itree_vis_rmw, <- ! bind_trigger.\n        gstep.\n        eapply pind9_fold. eapply lsim_rmwL. split; ss.\n        eapply pind9_fold. eapply lsim_rmwR. split; ss.\n        rewrite ! close_itree_tau.\n        eapply pind9_fold. eapply lsim_tauL. split; ss.\n        eapply pind9_fold. eapply lsim_tauR. split; ss.\n        eapply pind9_fold. eapply lsim_tauR. split; ss.\n        eapply pind9_fold. eapply lsim_progress.\n        des. destruct st_src2 as [s0 []], st_tgt2 as [[] s2]; ss; subst.\n        gbase. eapply CIH; ss.\n        Unshelve. all: exact tt.\n  Qed.\n\nEnd MODADD_THEOREM.\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/ModCloseSim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982315512489, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2736977552548374}}
{"text": "Require Export Bool Ascii String Fin List FunctionalExtensionality Psatz PeanoNat.\nRequire Export Kami.Lib.VectorFacts Kami.Lib.EclecticLib.\n\nRequire Export Kami.Lib.Word Kami.Lib.WordProperties.\nExport ListNotations.\n\nRequire Import Permutation.\nRequire Import ZArith.\n\nGlobal Set Implicit Arguments.\nGlobal Set Asymmetric Patterns.\n\nGlobal Open Scope word_scope.\nGlobal Open Scope nat_scope.\nGlobal Open Scope string_scope.\nGlobal Open Scope vector_scope.\nGlobal Open Scope list_scope.\n\nInductive Kind :=\n| Bool    : Kind\n| Bit     : nat -> Kind\n| Struct  : forall n, (Fin.t n -> Kind) -> (Fin.t n -> string) -> Kind\n| Array   : nat -> Kind -> Kind.\n\nInductive FullKind: Type :=\n| SyntaxKind: Kind -> FullKind\n| NativeKind (t: Type) (c : t) : FullKind.\n\nInductive ConstT: Kind -> Type :=\n| ConstBool: bool -> ConstT Bool\n| ConstBit n: word n -> ConstT (Bit n)\n| ConstStruct n fk fs (fv: forall i, ConstT (fk i)): ConstT (@Struct n fk fs)\n| ConstArray n k (fk: Fin.t n -> ConstT k): ConstT (Array n k).\n\nInductive ConstFullT: FullKind -> Type :=\n| SyntaxConst k: ConstT k -> ConstFullT (SyntaxKind k)\n| NativeConst t (c' : t) : ConstFullT (NativeKind c').\n\nCoercion ConstBool : bool >-> ConstT.\nCoercion ConstBit : word >-> ConstT.\n\nFixpoint getDefaultConst (k: Kind): ConstT k :=\n  match k with\n    | Bool => ConstBool false\n    | Bit n => ConstBit (wzero n)\n    | Struct n fk fs =>\n      ConstStruct fk fs (fun i => getDefaultConst (fk i))\n    | Array n k => ConstArray (fun _ => getDefaultConst k)\n  end.\n\nNotation Default := (getDefaultConst _).\n\nFixpoint getDefaultConstFullKind (k : FullKind) : ConstFullT k :=\n  match k with\n  | SyntaxKind k' => SyntaxConst (getDefaultConst k')\n  | NativeKind t c' => NativeConst c'\n  end.\n\nInductive UniBoolOp: Set :=\n| Neg: UniBoolOp.\n\nInductive CABoolOp: Set :=\n| And: CABoolOp\n(* | Or: CABoolOp *)\n| Xor: CABoolOp.\n\nInductive UniBitOp: nat -> nat -> Set :=\n| Inv n: UniBitOp n n\n| TruncLsb lsb msb: UniBitOp (lsb + msb) lsb\n| TruncMsb lsb msb: UniBitOp (lsb + msb) msb\n| UAnd n: UniBitOp n 1\n| UOr n: UniBitOp n 1\n| UXor n: UniBitOp n 1.\n\nInductive BinSign := SignSS | SignSU | SignUU.\n\nInductive BinBitOp: nat -> nat -> nat -> Set :=\n| Sub n: BinBitOp n n n\n| Div n: BinBitOp n n n\n| Rem n: BinBitOp n n n\n| Sll n m: BinBitOp n m n\n| Srl n m: BinBitOp n m n\n| Sra n m: BinBitOp n m n\n| Concat msb lsb: BinBitOp msb lsb (lsb + msb) (* MSB : n1, LSB : n2 *).\n\nInductive CABitOp: Set :=\n| Add: CABitOp\n| Mul: CABitOp\n| Band: CABitOp\n(* | Bor: CABitOp *)\n| Bxor: CABitOp.\n\nInductive BinBitBoolOp: nat -> nat -> Set :=\n| LessThan n: BinBitBoolOp n n.\n\nFixpoint type (k: Kind): Type :=\n  match k with\n  | Bool => bool\n  | Bit n => word n\n  | Struct n fk fs => forall i, type (fk i)\n  | Array n k' => Fin.t n -> type k'\n  end.\n\nFixpoint evalConstT k (e: ConstT k): type k :=\n  match e in ConstT k return type k with\n    | ConstBool b => b\n    | ConstBit n w => w\n    | ConstStruct n fk fs fv => fun i => evalConstT (fv i)\n    | ConstArray n k' fv => fun i => evalConstT (fv i)\n  end.\n\nSection Phoas.\n  Variable ty: Kind -> Type.\n  Definition fullType k := match k with\n                             | SyntaxKind k' => ty k'\n                             | NativeKind k' c' => k'\n                           end.\n\n  Inductive Expr: FullKind -> Type :=\n  | Var k: fullType k -> Expr k\n  | Const k: ConstT k -> Expr (SyntaxKind k)\n  | UniBool: UniBoolOp -> Expr (SyntaxKind Bool) -> Expr (SyntaxKind Bool)\n  | CABool: CABoolOp -> list (Expr (SyntaxKind Bool)) -> Expr (SyntaxKind Bool)\n  | UniBit n1 n2: UniBitOp n1 n2 -> Expr (SyntaxKind (Bit n1)) -> Expr (SyntaxKind (Bit n2))\n  | CABit n: CABitOp -> list (Expr (SyntaxKind (Bit n))) -> Expr (SyntaxKind (Bit n))\n  | BinBit n1 n2 n3: BinBitOp n1 n2 n3 ->\n                     Expr (SyntaxKind (Bit n1)) -> Expr (SyntaxKind (Bit n2)) ->\n                     Expr (SyntaxKind (Bit n3))\n  | BinBitBool n1 n2: BinBitBoolOp n1 n2 ->\n                      Expr (SyntaxKind (Bit n1)) -> Expr (SyntaxKind (Bit n2)) ->\n                      Expr (SyntaxKind Bool)\n  | ITE k: Expr (SyntaxKind Bool) -> Expr k -> Expr k -> Expr k\n  | Eq k: Expr (SyntaxKind k) -> Expr (SyntaxKind k) -> Expr (SyntaxKind Bool)\n  | ReadStruct n (fk: Fin.t n -> Kind) (fs: Fin.t n -> string)\n               (e: Expr (SyntaxKind (Struct fk fs))) i:\n      Expr (SyntaxKind (fk i))\n  | BuildStruct n (fk: Fin.t n -> Kind) (fs: Fin.t n -> string)\n                (fv: forall i, Expr (SyntaxKind (fk i))):\n      Expr (SyntaxKind (Struct fk fs))\n  | ReadArray n m k: Expr (SyntaxKind (Array n k)) ->\n                   Expr (SyntaxKind (Bit m)) ->\n                   Expr (SyntaxKind k)\n  | ReadArrayConst n k: Expr (SyntaxKind (Array n k)) ->\n                        Fin.t n ->\n                        Expr (SyntaxKind k)\n  | BuildArray n k: (Fin.t n -> Expr (SyntaxKind k)) -> Expr (SyntaxKind (Array n k))\n  | Kor k: list (Expr (SyntaxKind k)) -> Expr (SyntaxKind k)\n  | ToNative k:\n      Expr (SyntaxKind k) -> Expr (@NativeKind (type k) (evalConstT (getDefaultConst k)))\n  | FromNative k: Expr (@NativeKind (type k) (evalConstT (getDefaultConst k))) ->\n                  Expr (SyntaxKind k).\n\n  Definition UpdateArray n m k (e: Expr (SyntaxKind (Array n k)))\n             (i: Expr (SyntaxKind (Bit m)))\n             (v: Expr (SyntaxKind k)) :=\n    BuildArray (fun i' : Fin.t n =>\n                  ITE (Eq i (Const (natToWord _ (proj1_sig (Fin.to_nat i'))))) v\n                      (ReadArrayConst e i')).\n\n  Definition UpdateArrayConst n k (e: Expr (SyntaxKind (Array n k)))\n             (i: Fin.t n)\n             (v: Expr (SyntaxKind k)) :=\n    BuildArray (fun i' : Fin.t n =>\n                  match Fin.eq_dec i i' with\n                  | left _ => v\n                  | right _ => ReadArrayConst e i'\n                  end).\n\n  Definition UpdateStruct n (fk: Fin.t n -> Kind) (fs: Fin.t n -> string)\n             (e: Expr (SyntaxKind (Struct fk fs))) i (v: Expr (SyntaxKind (fk i))) :=\n    BuildStruct fk fs (fun i' => match Fin_eq_dec i i' with\n                                 | left pf =>\n                                   match pf in _ = Y return\n                                         Expr (SyntaxKind (fk Y)) with\n                                   | eq_refl => v\n                                   end\n                                 | right _ => ReadStruct e i'\n                                 end).\n\n  Section BitOps.\n    Definition castBits ni no (pf: ni = no) (e: Expr (SyntaxKind (Bit ni))) :=\n      nat_cast (fun n => Expr (SyntaxKind (Bit n))) pf e.\n\n    Definition Slt n (e1 e2: Expr (SyntaxKind (Bit (n + 1)))) :=\n      Eq (Eq (UniBit (TruncMsb n 1) e1) (UniBit (TruncMsb n 1) e2)) (BinBitBool (LessThan _) e1 e2).\n\n    Definition ConstExtract lsb n msb (e: Expr (SyntaxKind (Bit (lsb + n + msb)))): Expr (SyntaxKind (Bit n)) :=\n      UniBit (TruncMsb lsb n) (UniBit (TruncLsb (lsb + n) msb) e).\n\n    Definition OneExtend msb lsb (e: Expr (SyntaxKind (Bit lsb))): Expr (SyntaxKind (Bit (lsb + msb))) :=\n      (BinBit (Concat msb lsb) (Const (wones msb))) e.\n\n    Definition ZeroExtend msb lsb (e: Expr (SyntaxKind (Bit lsb))): Expr (SyntaxKind (Bit (lsb + msb))) :=\n      (BinBit (Concat msb lsb) (Const (wzero msb))) e.\n\n    Definition SignExtend lsb msb: Expr (SyntaxKind (Bit lsb)) -> Expr (SyntaxKind (Bit (lsb + msb))).\n      refine\n        match lsb return Expr (SyntaxKind (Bit lsb)) -> Expr (SyntaxKind (Bit (lsb + msb))) with\n        | 0 => fun _ => Const (wzero msb)\n        | S m => fun e => BinBit (Concat msb (S m)) (ITE (Eq (UniBit (TruncMsb m 1)\n                                                                     (castBits _ e))\n                                                             (Const (WO~0)%word))\n                                                         (Const (wzero msb))\n                                                         (Const (wones msb))) e\n        end; abstract lia.\n    Defined.\n\n    Fixpoint replicate sz (e: Expr (SyntaxKind (Bit sz))) n : Expr (SyntaxKind (Bit (n * sz))) :=\n      match n with\n      | 0 => Const WO\n      | S m => BinBit (Concat (m * sz) sz) (replicate e m) e\n      end.\n    \n    Definition OneExtendTruncLsb ni no (e: Expr (SyntaxKind (Bit ni))):\n      Expr (SyntaxKind (Bit no)).\n      refine\n        match Compare_dec.lt_dec ni no with\n        | left isLt => castBits _ (@OneExtend (no - ni) ni e)\n        | right isGe => UniBit (TruncLsb no (ni - no)) (castBits _ e)\n        end; abstract lia.\n    Defined.\n\n    Definition ZeroExtendTruncLsb ni no (e: Expr (SyntaxKind (Bit ni))):\n      Expr (SyntaxKind (Bit no)).\n      refine\n        match Compare_dec.lt_dec ni no with\n        | left isLt => castBits _ (@ZeroExtend (no - ni) ni e)\n        | right isGe => UniBit (TruncLsb no (ni - no)) (castBits _ e)\n        end; abstract lia.\n    Defined.\n\n    Definition SignExtendTruncLsb ni no (e: Expr (SyntaxKind (Bit ni))):\n      Expr (SyntaxKind (Bit no)).\n      refine\n        match Compare_dec.lt_dec ni no with\n        | left isLt => castBits _ (@SignExtend ni (no - ni) e)\n        | right isGe => UniBit (TruncLsb no (ni - no)) (castBits _ e)\n        end; abstract Omega.omega.\n    Defined.\n    \n    Definition ZeroExtendTruncMsb ni no (e: Expr (SyntaxKind (Bit ni))):\n      Expr (SyntaxKind (Bit no)).\n      refine\n        match Compare_dec.lt_dec ni no with\n        | left isLt => castBits _ (@ZeroExtend (no - ni) ni e)\n        | right isGe => UniBit (TruncMsb (ni - no) no) (castBits _ e)\n        end; abstract lia.\n    Defined.\n    \n    Definition SignExtendTruncMsb ni no (e: Expr (SyntaxKind (Bit ni))):\n      Expr (SyntaxKind (Bit no)).\n      refine\n        match Compare_dec.lt_dec ni no with\n        | left isLt => castBits _ (@SignExtend ni (no - ni) e)\n        | right isGe => UniBit (TruncMsb (ni - no) no) (castBits _ e)\n        end; abstract Omega.omega.\n    Defined.\n    \n    Fixpoint countLeadingZeros ni no: Expr (SyntaxKind (Bit ni)) -> Expr (SyntaxKind (Bit no)).\n    refine\n      match ni return Expr (SyntaxKind (Bit ni)) -> Expr (SyntaxKind (Bit no)) with\n      | 0 => fun _ => Const (wzero _)\n      | S m => fun e =>\n                 ITE (Eq (UniBit (TruncMsb m 1) (castBits (eq_sym (Nat.add_1_r m)) e)) (Const WO~0))\n                     (CABit Add [Const (natToWord _ 1);\n                                     countLeadingZeros m _ (UniBit (TruncLsb m 1) (castBits (eq_sym (Nat.add_1_r m)) e))])\n                     (Const (wzero _))\n      end.\n    Defined.\n\n    Fixpoint sumSizes n: (Fin.t n -> nat) -> nat :=\n      match n return (Fin.t n -> nat) -> nat with\n      | 0 => fun _ => 0\n      | S m => fun sizes => sumSizes (fun x => sizes (Fin.FS x)) + sizes Fin.F1\n      end.\n\n    Fixpoint size (k: Kind) {struct k} :=\n      match k with\n      | Bool => 1\n      | Bit n => n\n      | Struct n fk fs =>\n        sumSizes (fun i => size (fk i))\n      | Array n k => n * size k\n      end.\n    (* ConstExtract: LSB, MIDDLE, MSB *)\n    (* Concat: MSB, LSB *)\n\n    Fixpoint concatStructExpr n {struct n}:\n      forall (sizes: Fin.t n -> nat)\n             (f: forall i, Expr (SyntaxKind (Bit (sizes i)))),\n        Expr (SyntaxKind (Bit (sumSizes sizes))) :=\n      match n return forall\n          (sizes: Fin.t n -> nat)\n          (f: forall i, Expr (SyntaxKind (Bit (sizes i)))),\n          Expr (SyntaxKind (Bit (sumSizes sizes))) with\n      | 0 => fun _ _ => Const WO\n      | S m => fun sizes f =>\n                 BinBit\n                   (Concat _ _) (f Fin.F1)\n                   (@concatStructExpr m (fun x => (sizes (Fin.FS x))) (fun x => f (Fin.FS x)))\n      end.\n    \n    Fixpoint pack (k: Kind): Expr (SyntaxKind k) -> Expr (SyntaxKind (Bit (size k))).\n      refine\n      match k return Expr (SyntaxKind k) -> Expr (SyntaxKind (Bit (size k))) with\n      | Bool => fun e => (ITE e (Const (WO~1)%word) (Const (WO~0)%word))\n      | Bit n => fun e => e\n      | Struct n fk fs =>\n        fun e =>\n          concatStructExpr (fun i => size (fk i))\n                           (fun i => @pack (fk i) (ReadStruct e i))\n      | Array n k =>\n        fun e =>\n          (fix help i :=\n             match i return Expr (SyntaxKind (Bit (i * size k))) with\n             | 0 => Const WO\n             | S m =>\n               castBits _ (BinBit\n                             (Concat (size k) (m * size k))\n                             (@pack k (ReadArray e (Const (natToWord (Nat.log2_up n) m))))\n                             (help m))\n             end) n\n      end; abstract lia.\n    Defined.\n    \n    Fixpoint sumSizesMsbs n (i: Fin.t n) {struct i}: (Fin.t n -> nat) -> nat :=\n      match i in Fin.t n return (Fin.t n -> nat) -> nat with\n      | Fin.F1 _ => fun _ => 0\n      | Fin.FS m f => fun sizes => sumSizesMsbs f (fun j => sizes (Fin.FS j)) + sizes Fin.F1\n      end.\n\n    Lemma helper_sumSizes n (i: Fin.t n):\n      forall (sizes: Fin.t n -> nat), sumSizes sizes = (sumSizes sizes - (sumSizesMsbs i sizes + sizes i)) + sizes i + sumSizesMsbs i sizes.\n    Proof.\n      induction i; simpl; intros; auto.\n      - lia.\n      - specialize (IHi (fun x => sizes (Fin.FS x))).\n        lia.\n    Qed.\n    \n    Lemma helper_array n (i: Fin.t n):\n      forall size_k,\n        n * size_k = (proj1_sig (Fin.to_nat i) * size_k) + size_k + (n * size_k - ((proj1_sig (Fin.to_nat i) * size_k) + size_k)) .\n    Proof.\n      induction i; simpl; intros; auto.\n      - lia.\n      - case_eq (Fin.to_nat i); simpl; intros.\n        rewrite H in *; simpl in *.\n        rewrite IHi at 1.\n        lia.\n    Qed.\n\n    Fixpoint unpack (k: Kind): Expr (SyntaxKind (Bit (size k))) -> Expr (SyntaxKind k) :=\n      match k return Expr (SyntaxKind (Bit (size k))) -> Expr (SyntaxKind k) with\n      | Bool => fun e => Eq e (Const (WO~1)%word)\n      | Bit _ => fun e => e\n      | Struct n fk fs =>\n        fun e => BuildStruct\n                   _ _\n                   (fun i =>\n                      unpack\n                        _\n                        (ConstExtract\n                           _ _ (sumSizesMsbs i (fun j => size (fk j)))\n                           (@castBits _ _ (helper_sumSizes i (fun j => size (fk j))) e)))\n      | Array n k =>\n        fun e =>\n          BuildArray\n            (fun i => unpack _ (ConstExtract (proj1_sig (Fin.to_nat i) * size k) _ _\n                                             (@castBits _ _ (helper_array _ _) e)))\n      end.\n  End BitOps.\n  \n  Inductive BitFormat :=\n  | Binary\n  | Decimal\n  | Hex.\n\n  Definition FullBitFormat := (nat * BitFormat)%type.\n\n  Inductive FullFormat: Kind -> Type :=\n  | FBool: nat -> BitFormat -> FullFormat Bool\n  | FBit n: nat -> BitFormat -> FullFormat (Bit n)\n  | FStruct n fk fs: (forall i, FullFormat (fk i)) -> FullFormat (@Struct n fk fs)\n  | FArray n k: FullFormat k -> FullFormat (@Array n k).\n\n  Fixpoint fullFormatHex k : FullFormat k :=\n    match k return FullFormat k with\n    | Bool => FBool 1 Hex\n    | Bit n => FBit n ((n+3)/4) Hex\n    | Struct n fk fs => FStruct fk fs (fun i => fullFormatHex (fk i))\n    | Array n k => FArray n (fullFormatHex k)\n    end.\n\n  Fixpoint fullFormatBinary k : FullFormat k :=\n    match k return FullFormat k with\n    | Bool => FBool 1 Binary\n    | Bit n => FBit n n Binary\n    | Struct n fk fs => FStruct fk fs (fun i => fullFormatBinary (fk i))\n    | Array n k => FArray n (fullFormatBinary k)\n    end.\n\n  Fixpoint fullFormatDecimal k : FullFormat k :=\n    match k return FullFormat k with\n    | Bool => FBool 1 Decimal\n    | Bit n => FBit n 0 Decimal\n    | Struct n fk fs => FStruct fk fs (fun i => fullFormatDecimal (fk i))\n    | Array n k => FArray n (fullFormatDecimal k)\n    end.\n\n  Inductive SysT: Type :=\n  | DispString (s: string): SysT\n  | DispExpr k (e: Expr (SyntaxKind k)) (ff: FullFormat k): SysT\n  | Finish: SysT.\n\n  Definition DispHex k (e: Expr (SyntaxKind k)) :=\n    DispExpr e (fullFormatHex k).\n  \n  Definition DispBinary k (e: Expr (SyntaxKind k)) :=\n    DispExpr e (fullFormatBinary k).\n    \n  Definition DispDecimal k (e: Expr (SyntaxKind k)) :=\n    DispExpr e (fullFormatDecimal k).\n\n  Inductive LetExprSyntax k :=\n  | NormExpr (e: Expr (SyntaxKind k)): LetExprSyntax k\n  | SysE (ls: list SysT) (e: LetExprSyntax k): LetExprSyntax k\n  | LetE k' (e: LetExprSyntax k') (cont: ty k' -> LetExprSyntax k): LetExprSyntax k\n  | IfElseE (pred: Expr (SyntaxKind Bool)) k' (t f: LetExprSyntax k') (cont: ty k' -> LetExprSyntax k):\n      LetExprSyntax k.\n    \n  Inductive ActionT (lretT: Kind) : Type :=\n  | MCall (meth: string) s:\n      Expr (SyntaxKind (fst s)) ->\n      (ty (snd s) -> ActionT lretT) ->\n      ActionT lretT\n  | LetExpr k: Expr k -> (fullType k -> ActionT lretT) -> ActionT lretT\n  | LetAction k: ActionT k -> (ty k -> ActionT lretT) -> ActionT lretT\n  | ReadNondet k: (fullType k -> ActionT lretT) -> ActionT lretT\n  | ReadReg (r: string) k: (fullType k -> ActionT lretT) -> ActionT lretT\n  | WriteReg (r: string) k:\n      Expr k -> ActionT lretT -> ActionT lretT\n  | IfElse: Expr (SyntaxKind Bool) -> forall k,\n                                        ActionT k ->\n                                        ActionT k ->\n                                        (ty k -> ActionT lretT) ->\n                                        ActionT lretT\n  | Sys: list SysT -> ActionT lretT -> ActionT lretT\n  | Return: Expr (SyntaxKind lretT) -> ActionT lretT.\n\n  Fixpoint convertLetExprSyntax_ActionT k (e: LetExprSyntax k) :=\n    match e in LetExprSyntax _ return ActionT k with\n    | NormExpr e' => Return e'\n    | LetE _ e' cont => LetAction (convertLetExprSyntax_ActionT e') (fun v => convertLetExprSyntax_ActionT (cont v))\n    | SysE ls cont => Sys ls (convertLetExprSyntax_ActionT cont)\n    | IfElseE pred k' t f cont => IfElse pred (convertLetExprSyntax_ActionT t)\n                                         (convertLetExprSyntax_ActionT f)\n                                         (fun v => convertLetExprSyntax_ActionT (cont v))\n    end.\nEnd Phoas.\n\nDefinition Action (retTy : Kind) := forall ty, ActionT ty retTy.\n\nDefinition Signature := (Kind * Kind)%type.\nDefinition MethodT (sig : Signature) := forall ty, ty (fst sig) -> ActionT ty (snd sig).\n\nNotation Void := (Bit 0).\n\nNotation Attribute A := (string * A)%type (only parsing).\n\nSection RegInitValT.\n  Variable x: FullKind.\n  Definition RegInitValT := option (ConstFullT x).\nEnd RegInitValT.\n\nDefinition RegInitT := Attribute (sigT RegInitValT).\nDefinition DefMethT := Attribute (sigT MethodT).\nDefinition RuleT := Attribute (Action Void).\n\nInductive RegFileInitT (IdxNum: nat) (Data: Kind) :=\n| RFNonFile (init: option (ConstT Data))\n| RFFile (isAscii: bool) (isArg: bool) (file: string) (offset size: nat) (init: Fin.t IdxNum -> ConstT Data).\n\nRecord SyncRead := { readReqName : string ;\n                     readResName : string ;\n                     readRegName : string }.\n\nInductive RegFileReaders :=\n| Async (reads: list string)\n| Sync (isAddr: bool) (reads: list SyncRead).\n\nRecord RegFileBase := { rfIsWrMask : bool ;\n                        rfNum: nat ;\n                        rfDataArray: string ;\n                        rfRead: RegFileReaders ;\n                        rfWrite: string ;\n                        rfIdxNum: nat ;\n                        rfData: Kind ;\n                        rfInit: RegFileInitT rfIdxNum rfData }.\n                       \nInductive BaseModule: Type :=\n| BaseRegFile (rf: RegFileBase)\n| BaseMod (regs: list RegInitT) (rules: list RuleT) (dms: list DefMethT).\n\nInductive Mod: Type :=\n| Base (m: BaseModule): Mod\n| HideMeth (m: Mod) (meth: string): Mod\n| ConcatMod (m1 m2: Mod): Mod.\n\nCoercion Base: BaseModule >-> Mod.\n\nNotation getKindAttr ls := (map (fun x => (fst x, projT1 (snd x))) ls).\n\nDefinition getRegFileRegisters m :=\n  match m with\n  | @Build_RegFileBase isWrMask num dataArray readers write IdxNum Data init =>\n    (dataArray, existT RegInitValT (SyntaxKind (Array IdxNum Data))\n                       match init with\n                       | RFNonFile x => match x with\n                                        | None => None\n                                        | Some init' => Some (SyntaxConst (ConstArray (fun _ => init')))\n                                        end\n                       | RFFile isAscii isArg file offset size init => Some (SyntaxConst (ConstArray init))\n                       end) :: match readers with\n                               | Async _ => nil\n                               | Sync isAddr read =>\n                                 if isAddr\n                                 then map (fun x => (readRegName x, existT RegInitValT (SyntaxKind (Bit (Nat.log2_up IdxNum)))\n                                                                           None)) read\n                                 else map (fun x => (readRegName x, existT RegInitValT (SyntaxKind (Array num Data)) None)) read\n                               end\n  end.\n\nDefinition getRegisters m :=\n  match m with\n  | BaseRegFile rf => getRegFileRegisters rf\n  | BaseMod regs rules dms => regs\n  end.\n\nFixpoint getRules m :=\n  match m with\n  | BaseRegFile rf => nil\n  | BaseMod regs rules dms => rules\n  end.\n\nDefinition getStruct ls :=\n  (Struct (fun i => snd (nth_Fin ls i)) (fun j => fst (nth_Fin ls j))).\nArguments getStruct : simpl never.\n\nDefinition getStructVal ty ls :=\n  (BuildStruct (fun i => snd (nth_Fin (map (@projT1 _ _) ls) i))\n               (fun j => fst (nth_Fin (map (@projT1 _ _) ls) j))\n               (fun k => nth_Fin_map2 (@projT1 _ _) (fun x => Expr ty (SyntaxKind (snd x)))\n                                      ls k (projT2 (nth_Fin ls (Fin.cast k (map_length_red (@projT1 _ _) ls)))))).\nArguments getStructVal : simpl never.\n\nDefinition getStructConst ls :=\n  (ConstStruct (fun i => snd (nth_Fin (map (@projT1 _ _) ls) i))\n               (fun j => fst (nth_Fin (map (@projT1 _ _) ls) j))\n               (fun k => nth_Fin_map2 (@projT1 _ _) (fun x => ConstT (snd x))\n                                      ls k (projT2 (nth_Fin ls (Fin.cast k (map_length_red (@projT1 _ _) ls)))))).\nArguments getStructConst : simpl never. \n\nDefinition WriteRq lgIdxNum Data := (getStruct (cons (\"addr\", Bit lgIdxNum)\n                                                     (cons (\"data\", Data) nil))).\n\n  (* STRUCT_TYPE { \"addr\" :: Bit lgIdxNum ; *)\n  (*               \"data\" :: Data }. *)\n\nDefinition WriteRqMask lgIdxNum num Data := (getStruct (cons (\"addr\", Bit lgIdxNum)\n                                                             (cons (\"data\", Array num Data)\n                                                                   (cons (\"mask\", Array num Bool)\n                                                                         nil)))).\n\n(* Definition WriteRqMask lgIdxNum num Data := STRUCT_TYPE { \"addr\" :: Bit lgIdxNum ; *)\n(*                                                           \"data\" :: Array num Data ; *)\n(*                                                           \"mask\" :: Array num Bool }. *)\n\nDefinition buildNumDataArray num dataArray IdxNum Data ty (idx: ty (Bit (Nat.log2_up IdxNum))) :=\n  ReadReg dataArray (SyntaxKind (Array IdxNum Data))\n          (fun val =>\n             Return (BuildArray (fun i: Fin.t num =>\n                                   ReadArray\n                                     (Var ty _ val)\n                                     (CABit Add (Var ty (SyntaxKind _) idx ::\n                                                     Const ty (natToWord _ (proj1_sig (Fin.to_nat i))) :: nil))))).\n\nDefinition updateNumDataArray num dataArray IdxNum Data ty (idxData: ty (WriteRq (Nat.log2_up IdxNum)\n                                                                                 (Array num Data))):\n  ActionT ty Void :=\n  ReadReg dataArray (SyntaxKind (Array IdxNum Data))\n          (fun val =>\n             WriteReg dataArray\n                      (fold_left (fun newArr i =>\n                                    (UpdateArray newArr\n                                                 (CABit Add (ReadStruct (Var ty (SyntaxKind _) idxData)\n                                                                        Fin.F1 ::\n                                                                        Const ty (natToWord _ (proj1_sig (Fin.to_nat i))) ::\n                                                                        nil))\n                                                 (ReadArrayConst (ReadStruct (Var ty (SyntaxKind _) idxData)\n                                                                             (Fin.FS Fin.F1)) i))) (getFins num)\n                                 (Var ty (SyntaxKind (Array IdxNum Data)) val))\n                      (Return (Const _ WO))).\n\nDefinition updateNumDataArrayMask num dataArray IdxNum Data ty (idxData: ty (WriteRqMask\n                                                                               (Nat.log2_up IdxNum) num Data)):\n  ActionT ty Void :=\n  ReadReg dataArray (SyntaxKind (Array IdxNum Data))\n          (fun val =>\n             WriteReg dataArray\n                      (fold_left (fun newArr i =>\n                                    ITE\n                                      (ReadArrayConst (ReadStruct (Var ty (SyntaxKind _) idxData) (Fin.FS (Fin.FS Fin.F1))) i)\n                                      (UpdateArray newArr\n                                                   (CABit Add (ReadStruct\n                                                                 (Var ty (SyntaxKind _) idxData)\n                                                                 Fin.F1 :: Const ty (natToWord _ (proj1_sig (Fin.to_nat i))) ::\n                                                                 nil))\n                                                   (ReadArrayConst (ReadStruct (Var ty (SyntaxKind _) idxData)\n                                                                               (Fin.FS Fin.F1)) i))\n                                      newArr\n                                 ) (getFins num)\n                                 (Var ty (SyntaxKind (Array IdxNum Data)) val))\n                      (Return (Const _ WO))).\n\nDefinition readRegFile num dataArray (read: list string) IdxNum Data :=\n  (map (fun x => (x, existT MethodT (Bit (Nat.log2_up IdxNum), Array num Data)\n                            (buildNumDataArray num dataArray IdxNum Data))) read).\n\nDefinition writeRegFileFn (isWrMask: bool) num dataArray (write: string) IdxNum Data :=\n  (write,\n   if isWrMask\n   then existT MethodT (WriteRqMask (Nat.log2_up IdxNum) num Data, Void)\n               (updateNumDataArrayMask num dataArray IdxNum Data)\n   else existT MethodT (WriteRq (Nat.log2_up IdxNum) (Array num Data), Void)\n               (updateNumDataArray num dataArray IdxNum Data)).\n\nDefinition readSyncRegFile (isAddr: bool) num dataArray (read: list SyncRead) IdxNum Data :=\n  if isAddr\n  then\n    ((map (fun r =>\n             (readReqName r,\n              existT MethodT (Bit (Nat.log2_up IdxNum), Void)\n                     (fun ty idx =>\n                        WriteReg (readRegName r) (Var ty (SyntaxKind _) idx)\n                                 (Return (Const _ WO)))))) read)\n      ++\n      (map (fun r =>\n              (readResName r,\n               existT MethodT (Void, Array num Data)\n                      (fun ty _ =>\n                         ReadReg (readRegName r) (SyntaxKind (Bit (Nat.log2_up IdxNum)))\n                                 (buildNumDataArray num dataArray IdxNum Data ty))))\n           read)\n  else\n    ((map (fun r =>\n             (readReqName r,\n              existT MethodT (Bit (Nat.log2_up IdxNum), Void)\n                     (fun ty idx =>\n                        LetAction (buildNumDataArray num dataArray IdxNum Data ty idx)\n                                  (fun vals => WriteReg (readRegName r) (Var ty (SyntaxKind _) vals)\n                                                        (Return (Const _ WO)))))) read)\n      ++\n      (map (fun r =>\n              (readResName r,\n               existT MethodT (Void, Array num Data)\n                      (fun ty x =>\n                         ReadReg (readRegName r) (SyntaxKind (Array num Data))\n                                 (fun data =>\n                                    Return (Var ty (SyntaxKind (Array num Data)) data)))))\n           read)).\n\nDefinition getRegFileMethods m :=\n  match m with\n  | @Build_RegFileBase isWrMask num dataArray readers write IdxNum Data init =>\n    writeRegFileFn isWrMask num dataArray write IdxNum Data ::\n                   match readers with\n                   | Async read =>\n                     readRegFile num dataArray read IdxNum Data\n                   | Sync isAddr read =>\n                     readSyncRegFile isAddr num dataArray read IdxNum Data\n                   end\n  end.\n\nFixpoint getMethods m :=\n  match m with\n  | BaseRegFile rf => getRegFileMethods rf\n  | BaseMod regs rules dms => dms\n  end.\n\nFixpoint getAllRegisters m :=\n  match m with\n  | Base m' => getRegisters m'\n  | HideMeth m' s => getAllRegisters m'\n  | ConcatMod m1 m2 => getAllRegisters m1 ++ getAllRegisters m2\n  end.\n\nFixpoint getAllRules m :=\n  match m with\n  | Base m' => getRules m'\n  | HideMeth m' s => getAllRules m'\n  | ConcatMod m1 m2 => getAllRules m1 ++ getAllRules m2\n  end.\n\nFixpoint getAllMethods m :=\n  match m with\n  | Base m' => getMethods m'\n  | HideMeth m' s => getAllMethods m'\n  | ConcatMod m1 m2 => getAllMethods m1 ++ getAllMethods m2\n  end.\n\nFixpoint getHidden m :=\n  match m with\n  | Base _ => []\n  | ConcatMod m1 m2 => getHidden m1 ++ getHidden m2\n  | HideMeth m' s => s :: getHidden m'\n  end.\n\nSection WfBaseMod.\n\n  Variable ty : Kind -> Type.\n  \n  Section WfActionT.\n    Variable regs : list (string * {x : FullKind & RegInitValT x}).\n\n    Inductive WfActionT: forall lretT, ActionT ty lretT -> Prop :=\n    | WfMCall meth s e lretT c: (forall v, WfActionT (c v)) -> @WfActionT lretT (MCall meth s e c)\n    | WfLetExpr k (e: Expr ty k) lretT c: (forall v, WfActionT (c v)) -> @WfActionT lretT (LetExpr e c)\n    | WfLetAction k (a: ActionT ty k) lretT c: WfActionT a -> (forall v, WfActionT (c v)) -> @WfActionT lretT (LetAction a c)\n    | WfReadNondet k lretT c: (forall v, WfActionT (c v)) -> @WfActionT lretT (ReadNondet k c)\n    | WfReadReg r k lretT c: (forall v, WfActionT (c v)) -> In (r, k) (getKindAttr regs) ->\n                             @WfActionT lretT (ReadReg r k c)\n    | WfWriteReg r k (e: Expr ty k) lretT c: WfActionT c  -> In (r, k) (getKindAttr regs) ->\n                                               @WfActionT lretT (WriteReg r e c)\n    | WfIfElse p k (atrue: ActionT ty k) afalse lretT c: (forall v, WfActionT (c v)) -> WfActionT atrue ->\n                                                           WfActionT afalse -> @WfActionT lretT (IfElse p atrue afalse c)\n    | WfSys ls lretT c: WfActionT c -> @WfActionT lretT (Sys ls c)\n    | WfReturn lretT e: @WfActionT lretT (Return e).\n\n    Definition lookup{K X} : (K -> K -> bool) -> K -> list (K * X) -> option X :=\n      fun eqbk key pairs => match List.find (fun p => eqbk key (fst p)) pairs with\n                            | Some p => Some (snd p)\n                            | None => None\n                            end.\n\n    Lemma lookup_cons : forall K V (eqb : K -> K -> bool) k k' v (ps : list (K*V)), lookup eqb k ((k',v)::ps) =\n      if eqb k k' then Some v else lookup eqb k ps.\n    Proof.\n      intros.\n      unfold lookup.\n      unfold find.\n      simpl.\n      destruct (eqb k k'); auto.\n    Qed.\n\n    Fixpoint WfActionT_new{k}(a : ActionT ty k) : Prop :=\n    match a with\n    | MCall meth s e cont => forall x, WfActionT_new (cont x)\n    | LetExpr k e cont => forall x, WfActionT_new (cont x)\n    | LetAction k a cont => (WfActionT_new a /\\ forall x, WfActionT_new (cont x))\n    | ReadNondet k cont => forall x, WfActionT_new (cont x)\n    | ReadReg r k' cont => match lookup String.eqb r regs with\n                           | None => False\n                           | Some (existT k'' _) => k' = k'' /\\ forall x, WfActionT_new (cont x)\n                           end\n    | WriteReg r k' e a => match lookup String.eqb r regs with\n                           | None => False\n                           | Some (existT k'' _) => k' = k'' /\\ WfActionT_new a\n                           end\n    | IfElse e k1 a1 a2 cont => (WfActionT_new a1 /\\ WfActionT_new a2 /\\ forall x, WfActionT_new (cont x))\n    | Sys _ a => WfActionT_new a\n    | Return _ => True\n    end.\n\n    Fixpoint WfRules(rules : list RuleT) :=\n      match rules with\n      | [] => True\n      | r::rs => WfActionT_new (snd r ty) /\\ WfRules rs\n      end.\n\n    Fixpoint WfMeths(meths : list (string * {x : Signature & MethodT x})) :=\n      match meths with\n      | [] => True\n      | m::ms => (forall v, WfActionT_new (projT2 (snd m) ty v)) /\\ WfMeths ms\n      end.\n    \n  End WfActionT.\n\n  Definition WfBaseModule (m : BaseModule) :=\n    (forall rule, In rule (getRules m) -> WfActionT (getRegisters m) (snd rule ty)) /\\\n    (forall meth, In meth (getMethods m) -> forall v, WfActionT (getRegisters m) (projT2 (snd meth) ty v)) /\\\n    NoDup (map fst (getMethods m)) /\\ NoDup (map fst (getRegisters m)) /\\ NoDup (map fst (getRules m)).\n\n  Definition WfBaseModule_new(m : BaseModule) :=\n    (WfRules (getRegisters m) (getRules m)) /\\\n    (WfMeths (getRegisters m) (getMethods m)) /\\\n    (NoDup (map fst (getMethods m))) /\\\n    (NoDup (map fst (getRegisters m))) /\\\n    (NoDup (map fst (getRules m))).\n\n  Section WfActionT'.\n\n  Variable m : BaseModule.\n\n   Inductive WfActionT': forall lretT, ActionT type lretT -> Prop :=\n  | WfMCall' meth s e lretT c v: (WfActionT' (c v)) -> @WfActionT' lretT (MCall meth s e c)\n  | WfLetExpr' k (e: Expr type k) lretT c v: (WfActionT' (c v)) -> @WfActionT' lretT (LetExpr e c)\n  | WfLetAction' k (a: ActionT type k) lretT c v: WfActionT' a -> (WfActionT' (c v)) -> @WfActionT' lretT (LetAction a c)\n  | WfReadNondet' k lretT c v: (WfActionT' (c v)) -> @WfActionT' lretT (ReadNondet k c)\n  | WfReadReg' r k lretT c v: (WfActionT' (c v)) -> In (r, k) (getKindAttr (getRegisters m)) ->\n                           @WfActionT' lretT (ReadReg r k c)\n  | WfWriteReg' r k (e: Expr type k) lretT c: WfActionT' c  -> In (r, k) (getKindAttr (getRegisters m)) ->\n                                             @WfActionT' lretT (WriteReg r e c)\n  | WfIfElse' p k (atrue: ActionT type k) afalse lretT c v: (WfActionT' (c v)) -> WfActionT' atrue ->\n                                                         WfActionT' afalse -> @WfActionT' lretT (IfElse p atrue afalse c)\n  | WfSys' ls lretT c: WfActionT' c -> @WfActionT' lretT (Sys ls c)\n  | WfReturn' lretT e: @WfActionT' lretT (Return e).\n\n  End WfActionT'.\n\nEnd WfBaseMod.\n\n  Lemma WfLetExprSyntax k m (e: LetExprSyntax type k): WfActionT (getRegisters m) (convertLetExprSyntax_ActionT e).\n  Proof.\n    induction e; constructor; auto.\n  Qed.\n\n  Lemma WfLetExprSyntax_new k m (e: LetExprSyntax type k): WfActionT_new (getRegisters m) (convertLetExprSyntax_ActionT e).\n  Proof.\n    induction e; simpl; repeat split; auto.\n  Qed.\n\nSection WfBaseModProofs.\n\nLemma In_getKindAttr : forall r k (regs : list (string * {x : FullKind & RegInitValT x})), In (r,k) (getKindAttr regs) -> In r (map fst regs).\nProof.\n  intros.\n  rewrite in_map_iff in H.\n  dest.\n  inv H.\n  apply in_map; auto.\nQed.\n\nLemma In_lookup : forall r k (regs : list (string * {x : FullKind & RegInitValT x})), NoDup (map fst regs) -> In (r,k) (getKindAttr regs) -> exists k' v, k = k' /\\ lookup String.eqb r regs = Some (existT _ k' v).\nProof.\n  induction regs; intros.\n  - destruct H0.\n  - destruct H0.\n    + destruct a.\n      destruct s0.\n      destruct r0.\n      * inversion H0.\n        exists x; eexists.\n        split.\n        ** auto.\n        ** unfold lookup; simpl.\n           rewrite String.eqb_refl.\n           reflexivity.\n      * inversion H0.\n        exists k; eexists.\n        split.\n        ** auto.\n        ** unfold lookup; simpl.\n           rewrite String.eqb_refl.\n           simpl.\n           reflexivity.\n    + assert (NoDup (map fst regs)).\n      inversion H; auto.\n      destruct (IHregs H1 H0) as [k' [v [Hk' Hv]]].\n      exists k', v.\n      split.\n      * auto.\n      * destruct a.\n        destruct s0.\n        destruct r0.\n        ** rewrite lookup_cons.\n           destruct (r =? s) eqn:G.\n           *** rewrite String.eqb_eq in G.\n               rewrite <- G in H.\n               inversion H.\n               elim H4.\n               eapply In_getKindAttr.\n               exact H0.\n           *** auto.\n        ** rewrite lookup_cons.\n           destruct (r =? s) eqn:G.\n           *** rewrite String.eqb_eq in G.\n               rewrite <- G in H.\n               inversion H.\n               elim H4.\n               eapply In_getKindAttr.\n               exact H0.\n           *** auto.\nQed.\n\nLemma lookup_In : forall r k v regs, lookup String.eqb r (regs) = Some (existT RegInitValT k v) -> In (r,k) (getKindAttr regs).\nProof.\n  induction regs; intros.\n  - discriminate H.\n  - destruct a.\n    destruct s0.\n    rewrite lookup_cons in H.\n    + destruct (r =? s) eqn:G.\n      * rewrite String.eqb_eq in G.\n        inversion H.\n        left; simpl; congruence.\n      * right.\n        apply IHregs.\n        auto.\nQed.\n\nLemma WfActionT_WfActionT_new{ty lret} : forall regs (a : ActionT ty lret), NoDup (map fst regs) -> WfActionT regs a -> WfActionT_new regs a.\nProof.\n  intros.\n  induction a; simpl; intros.\n  - apply H1.\n    inversion H0.\n    EqDep_subst.\n    apply H4.\n  - apply H1.\n    inversion H0.\n    EqDep_subst.\n    apply H4.\n  - inversion H0.\n    split.\n    + apply IHa.\n      EqDep_subst.\n      auto.\n    + EqDep_subst.\n      intro.\n      auto.\n  - inversion H0.\n    apply H1.\n    EqDep_subst.\n    auto.\n  - inversion H0.\n    unfold getRegisters in H7.\n    destruct (In_lookup _ _ _ H H7) as [k' [v [Hk Hv]]].\n    rewrite Hv.\n    split.\n    + auto.\n    + intro.\n      apply H1.\n      EqDep_subst.\n      apply H5.\n  - inversion H0.\n    unfold getRegisters in H7.\n    destruct (In_lookup _ _ _ H H7) as [k' [v [Hk Hv]]].\n    rewrite Hv.\n    split.\n    + auto.\n    + apply IHa.\n      EqDep_subst; auto.\n  - inversion H0.\n   repeat split.\n    + apply IHa1.\n      EqDep_subst.\n      auto.\n    + apply IHa2.\n      EqDep_subst.\n      auto.\n    + intro; apply H1.\n      EqDep_subst.\n      apply H6.\n  - apply IHa.\n    inversion H0.\n    EqDep_subst.\n    auto.\n  - auto.\nQed.\n\nLemma wf_rules_In : forall ty regs rules, NoDup (map fst regs) -> (forall rule : RuleT, In rule rules -> WfActionT regs (snd rule ty)) -> WfRules ty regs rules.\nProof.\n  induction rules; intros.\n  - simpl; auto.\n  - simpl.\n    split.\n    + eapply WfActionT_WfActionT_new.\n      * auto.\n      * apply H0; left; auto.\n    + eapply IHrules.\n      * auto.\n      * intros.\n        apply H0.\n        right; auto.\nQed.\n\nLemma wf_meths_In : forall ty regs dms, NoDup (map fst regs) -> (forall (meth : string * {x : Signature & MethodT x}),\n    In meth dms -> forall v : ty (fst (projT1 (snd meth))), WfActionT regs (projT2 (snd meth) ty v)) -> WfMeths ty regs dms.\nProof.\n  induction dms; intros.\n  - simpl; auto.\n  - simpl.\n    split.\n    + intro; eapply WfActionT_WfActionT_new; auto.\n      apply H0.\n      left; auto.\n    + eapply IHdms.\n      * auto.\n      * intros.\n        apply H0.\n        right; auto.\nQed.\n\n(* \nLemma wf_meths_In_BaseRegFile : forall ty rfs (ms : list (string * {x : Signature & MethodT x})), NoDup (map fst (getRegisters (BaseRegFile rfs))) ->   (forall meth, In meth ms ->\n forall v : ty (fst (projT1 (snd meth))) , WfActionT (BaseRegFile rfs) (projT2 (snd meth) ty v)) -> WfMeths (BaseRegFile rfs) ty ms.\nProof.\n  induction ms; intros.\n  - simpl; auto.\n  - simpl; split.\n    + intro; eapply WfActionT_WfActionT_new.\n      * auto.\n      * apply H0.\n        left; auto.\n    + apply IHms; auto.\n      intros; apply H0; right; auto.\nQed.\n *)\n\nLemma WfBaseModule_WfBaseModule_new : forall ty bm, WfBaseModule ty bm -> WfBaseModule_new ty bm.\nProof.\n  intros ty bm [wf_actions [wf_meths [nodup_meths [nodup_regs nodup_rules]]]].\n  unfold WfBaseModule_new.\n  repeat split; auto.\n  - destruct bm.\n    + exact I.\n    + simpl; eapply wf_rules_In; auto.\n  - eapply wf_meths_In; auto.\nQed.\n\nLemma WfActionT_new_WfActionT{ty lret} : forall (a : ActionT ty lret) m, WfActionT_new m a -> WfActionT m a.\nProof.\n  intros.\n  induction a; simpl in *.\n  - apply WfMCall.\n    intro; apply H0; apply H.\n  - apply WfLetExpr.\n    intro; apply H0; apply H.\n  - apply WfLetAction.\n    + apply IHa; tauto.\n    + intro; apply H0; apply H.\n  - apply WfReadNondet.\n    intro; apply H0; apply H.\n  - apply WfReadReg.\n    + intro; apply H0.\n      destruct lookup.\n      * destruct s; apply H.\n      * destruct H.\n    + destruct lookup eqn:G.\n      * destruct s.\n        destruct H.\n        rewrite H.\n        unfold getRegisters.\n        eapply lookup_In.\n        exact G.\n      * destruct H.\n  - apply WfWriteReg.\n    + apply IHa.\n      destruct lookup.\n      * destruct s; apply H.\n      * destruct H.\n    + destruct lookup eqn:G.\n      * destruct s.\n        destruct H.\n        rewrite H.\n        unfold getRegisters.\n        eapply lookup_In.\n        exact G.\n      * destruct H.\n  - apply WfIfElse.\n    + intro; apply H0; apply H.\n    + tauto.\n    + tauto.\n  - apply WfSys; tauto.\n  - apply WfReturn.\nQed.\n\nLemma WfActionT_new_WfActionT_iff{ty lret} : forall (a : ActionT ty lret) m, NoDup (map fst m) -> WfActionT_new m a <-> WfActionT m a.\nProof.\n  intros; split; intro.\n  - apply WfActionT_new_WfActionT; auto.\n  - apply WfActionT_WfActionT_new; auto.\nQed.\n\nLemma In_wf_rules : forall ty regs rules, NoDup (map fst regs) -> WfRules ty regs rules -> (forall rule : RuleT, In rule rules -> WfActionT regs (snd rule ty)).\nProof.\n  induction rules; intros.\n  - destruct H1.\n  - simpl in H0; destruct H0.\n    destruct H1.\n    + eapply WfActionT_new_WfActionT; congruence.\n    + apply IHrules; auto.\nQed.\n\nLemma In_wf_meths : forall ty regs dms, NoDup (map fst regs) -> WfMeths ty regs dms -> forall meth : string * {x : Signature & MethodT x}, In meth dms -> forall v : ty (fst (projT1 (snd meth))),\n  WfActionT regs (projT2 (snd meth) ty v).\nProof.\n  induction dms; intros.\n  - destruct H1.\n  - simpl in H0; destruct H0.\n    destruct H1.\n    + eapply WfActionT_new_WfActionT.\n      rewrite H1 in H0.\n      apply H0.\n    + apply IHdms; auto.\nQed.\n\nLemma WfBaseModule_new_WfBaseModule : forall ty bm, WfBaseModule_new ty bm -> WfBaseModule ty bm.\nProof.\n  intros ty bm [wf_actions [wf_meths [nodup_meths [nodup_regs nodup_rules]]]].\n  unfold WfBaseModule.\n  repeat split; auto.\n  - intros.\n    + eapply In_wf_rules; eauto.\n  - intros.\n    + eapply In_wf_meths; eauto.\nQed.\n\nLemma WfBaseModule_WfBaseModule_new_iff : forall ty bm, WfBaseModule ty bm <-> WfBaseModule_new ty bm.\nProof.\n  intros ty bm; split; intro.\n  - apply WfBaseModule_WfBaseModule_new; auto.\n  - apply WfBaseModule_new_WfBaseModule; auto.\nQed.\n\nEnd WfBaseModProofs.\n\nInductive WfConcatActionT{ty} : forall lretT, ActionT ty lretT -> Mod -> Prop :=\n| WfConcatMCall meth s e lretT c m' :(forall v, WfConcatActionT (c v) m') -> ~In meth (getHidden m') ->\n                                     @WfConcatActionT ty lretT (MCall meth s e c) m'\n| WfConcatLetExpr k (e : Expr ty k) lretT c m' : (forall v, WfConcatActionT (c v) m') ->\n                                                   @WfConcatActionT ty lretT (LetExpr e c) m'\n| WfConcatLetAction k (a : ActionT ty k) lretT c m' : WfConcatActionT a m' -> (forall v, WfConcatActionT (c v) m') ->\n                                                        @WfConcatActionT ty lretT (LetAction a c) m'\n| WfConcatReadNondet k lretT c m': (forall v, WfConcatActionT (c v) m') -> @WfConcatActionT ty lretT (ReadNondet k c) m'\n| WfConcatReadReg r k lretT c m': (forall v, WfConcatActionT (c v) m') -> @WfConcatActionT ty lretT (ReadReg r k c) m'\n| WfConcatWriteReg r k (e: Expr ty k) lretT c m': WfConcatActionT c m' -> @WfConcatActionT ty lretT (WriteReg r e c) m'\n| WfConcatIfElse p k (atrue: ActionT ty k) afalse lretT c m': (forall v, WfConcatActionT (c v) m') ->\n                                                                WfConcatActionT atrue m' -> WfConcatActionT afalse m' ->\n                                                                @WfConcatActionT ty lretT (IfElse p atrue afalse c) m'\n| WfConcatSys ls lretT c m': WfConcatActionT c m' -> @WfConcatActionT ty lretT (Sys ls c) m'\n| WfConcatReturn lretT e m': @WfConcatActionT ty lretT (Return e) m'.\n\nFixpoint WfConcatActionT_new{ty lret}(a : ActionT ty lret)(m : Mod) : Prop :=\n  match a with\n  | MCall meth s e cont => (~In meth (getHidden m)) /\\ forall x, WfConcatActionT_new (cont x) m\n  | LetExpr k e cont => forall x, WfConcatActionT_new (cont x) m\n  | LetAction k a cont => WfConcatActionT_new a m /\\ forall x, WfConcatActionT_new (cont x) m\n  | ReadNondet k cont => forall x, WfConcatActionT_new (cont x) m\n  | ReadReg r k cont => forall x, WfConcatActionT_new (cont x) m\n  | WriteReg r k e a => WfConcatActionT_new a m\n  | IfElse e k a1 a2 cont => WfConcatActionT_new a1 m /\\ WfConcatActionT_new a2 m /\\ forall x, WfConcatActionT_new (cont x) m\n  | Sys _ a => WfConcatActionT_new a m\n  | Return _ => True\n  end.\n\nLemma WfConcatActionT_WfConcatActionT_new : forall ty lret m (a : ActionT ty lret), WfConcatActionT a m -> WfConcatActionT_new a m.\nProof.\n  intros ty lret m a wf_a.\n  induction a; inversion wf_a; simpl; EqDep_subst; auto.\nQed.\n\nLemma WfConcatActionT_new_WfConcatActionT : forall ty lret m (a : ActionT ty lret), WfConcatActionT_new a m -> WfConcatActionT a m.\nProof.\n  intros ty lret m a wf_a.\n  induction a; simpl in wf_a; econstructor; auto; try tauto.\n  - intro; apply H; apply wf_a.\n  - intro; apply H; apply wf_a.\n  - intro; apply H; apply wf_a; auto.\nQed.\n\nLemma WfConcatActionT_WfConcatActionT_new_iff : forall ty lret m (a : ActionT ty lret), WfConcatActionT a m <-> WfConcatActionT_new a m.\nProof.\n  intros ty lret m a; split; intro.\n  - apply WfConcatActionT_WfConcatActionT_new; auto.\n  - apply WfConcatActionT_new_WfConcatActionT; auto.\nQed.\n\nDefinition WfConcat ty m m' :=\n  (forall rule, In rule (getAllRules m) -> WfConcatActionT (snd rule ty) m') /\\\n  (forall meth, In meth (getAllMethods m) -> forall v, WfConcatActionT (projT2 (snd meth) ty v) m').\n\nDefinition WfConcat_new ty m m' :=\n  (forall rule, In rule (getAllRules m) -> WfConcatActionT_new (snd rule ty) m') /\\\n  (forall meth, In meth (getAllMethods m) -> forall v, WfConcatActionT_new (projT2 (snd meth) ty v) m').\n\nLemma WfConcat_WfConcat_new_iff : forall ty m m', WfConcat ty m m' <-> WfConcat_new ty m m'.\nProof.\n  unfold WfConcat, WfConcat_new; intros; repeat split; intros; destruct H.\n  - rewrite <- WfConcatActionT_WfConcatActionT_new_iff; auto.\n  - rewrite <- WfConcatActionT_WfConcatActionT_new_iff; auto.\n  - rewrite WfConcatActionT_WfConcatActionT_new_iff; auto.\n  - rewrite WfConcatActionT_WfConcatActionT_new_iff; auto.\nQed.\n\nSection WfMod.\n  Variable ty : Kind -> Type.\n  Inductive WfMod : Mod -> Prop :=\n  | BaseWf m (HWfBaseModule: WfBaseModule ty m): WfMod (Base m)\n  | HideMethWf m s (HHideWf: In s (map fst (getAllMethods m))) (HWf: WfMod m): WfMod (HideMeth m s)\n  | ConcatModWf m1 m2 (HDisjRegs: DisjKey (getAllRegisters m1) (getAllRegisters m2))\n                (HDisjRules: DisjKey (getAllRules m1) (getAllRules m2))\n                (HDisjMeths: DisjKey (getAllMethods m1) (getAllMethods m2))\n                (HWf1: WfMod m1) (HWf2: WfMod m2)(WfConcat1: WfConcat ty m1 m2)\n                (WfConcat2 : WfConcat ty m2 m1): WfMod (ConcatMod m1 m2).\n\nFixpoint WfMod_new(m : Mod) : Prop :=\n  match m with\n  | Base m => WfBaseModule_new ty m\n  | HideMeth m s => In s (map fst (getAllMethods m)) /\\ WfMod_new m\n  | ConcatMod m1 m2 => DisjKey (getAllRegisters m1) (getAllRegisters m2) /\\ DisjKey (getAllRules m1) (getAllRules m2) /\\ DisjKey (getAllMethods m1) (getAllMethods m2) /\\\n                         WfMod_new m1 /\\ WfMod_new m2 /\\ WfConcat_new ty m1 m2 /\\ WfConcat_new ty m2 m1\n  end.\n\nEnd WfMod.\n\nLemma WfMod_WfMod_new : forall ty m, WfMod ty m -> WfMod_new ty m.\nProof.\n  intros ty m wf_m; induction m; inversion wf_m; simpl.\n  - rewrite <- WfBaseModule_WfBaseModule_new_iff; auto.\n  - auto.\n  - repeat rewrite <- WfConcat_WfConcat_new_iff; tauto.\nQed.\n\nLemma WfMod_new_WfMod : forall ty m, WfMod_new ty m -> WfMod ty m.\nProof.\n  intros ty m wf_m; induction m; inversion wf_m; simpl.\n  - econstructor; auto; simpl in wf_m.\n    unfold WfBaseModule.\n    unfold WfBaseModule_new in wf_m; dest.\n    repeat split; try auto.\n    + intro; apply In_wf_rules; auto.\n    + intro; apply In_wf_meths; auto.\n  - econstructor; auto.\n  - repeat rewrite <- WfConcat_WfConcat_new_iff in H0; econstructor; try tauto.\nQed.\n\nLemma WfMod_new_WfMod_iff : forall ty m, WfMod_new ty m <-> WfMod ty m.\nProof.\n  intros ty m; split; eauto using WfMod_new_WfMod, WfMod_WfMod_new.\nQed.\n\nRecord ModWf ty : Type := { module :> Mod;\n                            wfMod : WfMod ty module }.\n\nRecord ModWf_new ty : Type := { module_new :> Mod;\n  wfMod_new : WfMod_new ty module_new }.\n\nRecord ModWfOrd ty := { modWf :> ModWf ty;\n                     modOrd : list string }.\n\nRecord ModWfOrd_new ty := { modWf_new :> ModWf_new ty;\n                            modOrd_new : list string }.\n\nRecord BaseModuleWf ty :=\n  { baseModule :> BaseModule ;\n    wfBaseModule : WfBaseModule ty baseModule }.\n\nRecord BaseModuleWf_new ty :=\n  { baseModule_new :> BaseModule ;\n    wfBaseModule_new : WfBaseModule_new ty baseModule_new }.\n\nRecord BaseModuleWfOrd ty :=\n  { baseModuleWf :> BaseModuleWf ty;\n    baseModuleOrd : list string }.\n\nRecord BaseModuleWfOrd_new ty :=\n  { baseModuleWf_new :> BaseModuleWf_new ty ;\n    baseModuleOrd_new : list string }.\n\nDefinition getModWf ty (m: BaseModuleWf ty) :=\n  {| module := m;\n     wfMod := BaseWf (wfBaseModule m) |}.\n\nDefinition getModWfOrd ty (m: BaseModuleWfOrd ty) :=\n  {| modWf := getModWf m;\n     modOrd := baseModuleOrd m |}.\n\nCoercion getModWf: BaseModuleWf >-> ModWf.\nCoercion getModWfOrd: BaseModuleWfOrd >-> ModWfOrd.\n\nSection NoCallActionT.\n  Variable ls: list DefMethT.\n  Variable ty : Kind -> Type.\n  \n  Inductive NoCallActionT: forall k , ActionT ty k -> Prop :=\n  | NoCallMCall meth s e lretT c: ~ In (meth, s) (getKindAttr ls) -> (forall v, NoCallActionT (c v)) -> @NoCallActionT lretT (MCall meth s e c)\n  | NoCallLetExpr k (e: Expr ty k) lretT c: (forall v, NoCallActionT (c v)) -> @NoCallActionT lretT (LetExpr e c)\n  | NoCallLetAction k (a: ActionT ty k) lretT c: NoCallActionT a -> (forall v, NoCallActionT (c v)) -> @NoCallActionT lretT (LetAction a c)\n  | NoCallReadNondet k lretT c: (forall v, NoCallActionT (c v)) -> @NoCallActionT lretT (ReadNondet k c)\n  | NoCallReadReg r k lretT c: (forall v, NoCallActionT (c v)) -> @NoCallActionT lretT (ReadReg r k c)\n  | NoCallWriteReg r k (e: Expr ty k) lretT c: NoCallActionT c  -> @NoCallActionT lretT (WriteReg r e c)\n  | NoCallIfElse p k (atrue: ActionT ty k) afalse lretT c: (forall v, NoCallActionT (c v)) -> NoCallActionT atrue -> NoCallActionT afalse -> @NoCallActionT lretT (IfElse p atrue afalse c)\n  | NoCallSys ls lretT c: NoCallActionT c -> @NoCallActionT lretT (Sys ls c)\n  | NoCallReturn lretT e: @NoCallActionT lretT (Return e).\nEnd NoCallActionT.\n\nSection NoSelfCallBaseModule.\n  Variable m: BaseModule.\n  \n  Definition NoSelfCallRuleBaseModule (rule : Attribute (Action Void)) :=\n    forall ty, NoCallActionT (getMethods m) (snd rule ty).\n  \n  Definition NoSelfCallRulesBaseModule :=\n    forall rule ty, In rule (getRules m) ->\n                    NoCallActionT (getMethods m) (snd rule ty).\n  \n  Definition NoSelfCallMethsBaseModule :=\n    forall meth ty, In meth (getMethods m) ->\n                 forall (arg: ty (fst (projT1 (snd meth)))), NoCallActionT (getMethods m) (projT2 (snd meth) ty arg).\n\n  Definition NoSelfCallBaseModule :=\n    NoSelfCallRulesBaseModule /\\ NoSelfCallMethsBaseModule.\nEnd NoSelfCallBaseModule.\n\n\n\n\n\n\n\n(* Semantics *)\n\nDefinition mk_eq : forall m n, (m =? n)%nat = true -> m = n.\nProof.\n  induction m.\n  - destruct n.\n    + auto.\n    + intro; discriminate.\n  - destruct n.\n    + intro; discriminate.\n    + simpl.\n      intro.\n      f_equal.\n      apply IHm.\n      exact H.\nDefined.\n\nFixpoint Kind_decb(k1 k2 : Kind) : bool.\nProof.\n  refine (\n    match k1,k2 with\n    | Bool, Bool => true\n    | Bit n, Bit m => Nat.eqb n m\n    | Array n k, Array m k' => Nat.eqb n m && Kind_decb k k'\n    | Struct n ks fs, Struct m ks' fs' => _\n    | _,_ => false\n    end).\n  destruct (Nat.eqb n m) eqn:G.\n  exact (Fin_forallb (fun i => Kind_decb (ks i) (ks' (Fin_cast i (mk_eq _ _ G)))) && Fin_forallb (fun i => String.eqb (fs i) (fs' (Fin_cast i (mk_eq _ _ G))))).\n  exact false.\nDefined.\n\nLemma Kind_decb_refl : forall k, Kind_decb k k = true.\nProof.\n  induction k; simpl; auto.\n  - apply Nat.eqb_refl.\n  -\n    rewrite silly_lemma_true with (pf := (Nat.eqb_refl _)) by apply Nat.eqb_refl.\n    rewrite andb_true_iff; split; rewrite Fin_forallb_correct; intros.\n    + rewrite (hedberg Nat.eq_dec _ eq_refl); simpl; apply H.\n    + rewrite (hedberg Nat.eq_dec _ eq_refl); simpl; apply String.eqb_refl.\n  - rewrite andb_true_iff; split; auto.\n    apply Nat.eqb_refl.\nQed.\n\nLemma Kind_decb_eq : forall k1 k2, Kind_decb k1 k2 = true <-> k1 = k2.\nProof.\n  induction k1; intros; destruct k2; split; intro; try (reflexivity || discriminate).\n  - simpl in H; rewrite Nat.eqb_eq in H; congruence.\n  - inversion H; simpl; apply Nat.eqb_refl.\n  - destruct (n =? n0)%nat eqn:G.\n    + simpl in H0.\n      rewrite (@silly_lemma_true bool (n =? n0)%nat _ _ G) in H0 by auto.\n      pose proof G.\n      rewrite Nat.eqb_eq in H1 by auto.\n      rewrite andb_true_iff in H0; destruct H0 as [G1 G2]; rewrite Fin_forallb_correct in G1,G2; subst.\n      rewrite (hedberg Nat.eq_dec _ eq_refl) in G1,G2; simpl in *.\n      setoid_rewrite H in G1.\n      setoid_rewrite String.eqb_eq in G2.\n      f_equal; extensionality i; auto.\n    + simpl in H0.\n      rewrite silly_lemma_false in H0; try discriminate; auto.\n  - rewrite H0; apply Kind_decb_refl.\n  - simpl in H; rewrite andb_true_iff in H.\n    destruct H as [H1 H2]; rewrite Nat.eqb_eq in H1; rewrite IHk1 in H2; congruence.\n  - simpl.\n    rewrite andb_true_iff; inversion H; split.\n    + apply Nat.eqb_refl.\n    + rewrite <- H2, IHk1; reflexivity.\nQed.\n\nLemma Kind_dec (k1 k2 : Kind): {k1 = k2} + {k1 <> k2}.\nProof.\n  destruct (Kind_decb k1 k2) eqn:G.\n  left; abstract (rewrite Kind_decb_eq in G; auto).\n  right; abstract (intro;\n                   rewrite <- Kind_decb_eq in H;\n                   rewrite H in G; discriminate).\nDefined.\n\nDefinition Signature_decb : Signature -> Signature -> bool :=\n  fun '(k,l) '(k',l') => Kind_decb k k' && Kind_decb l l'.\n\nLemma Signature_decb_eq : forall s1 s2, Signature_decb s1 s2 = true <-> s1 = s2.\nProof.\n  intros [] []; simpl; rewrite andb_true_iff; repeat rewrite Kind_decb_eq; firstorder congruence.\nQed.\n\nDefinition Signature_dec (s1 s2 : Signature) : {s1 = s2} + {s1 <> s2}.\nProof.\n  destruct (Signature_decb s1 s2) eqn:G.\n  left; abstract (rewrite <- Signature_decb_eq; auto).\n  right; (intro;\n          rewrite <- Signature_decb_eq in H;\n          rewrite H in G; discriminate).\nDefined.\n\nLemma isEq k: forall (e1: type k) (e2: type k),\n    {e1 = e2} + {e1 <> e2}.\nProof.\n  induction k; intros.\n  - apply bool_dec.\n  - apply weq.\n  - induction n.\n    + left.\n      extensionality x.\n      apply Fin.case0.\n      apply x.\n    + destruct (IHn (fun i => k (Fin.FS i)) (fun i => X (Fin.FS i)) (fun i => s (Fin.FS i))\n                    (fun i => e1 (Fin.FS i)) (fun i => e2 (Fin.FS i))).\n      * destruct (X Fin.F1 (e1 Fin.F1) (e2 Fin.F1)).\n        -- left.\n           extensionality x.\n           apply (Fin.caseS' x); try assumption; apply equal_f_dep; assumption.\n        -- right; intro; subst.\n           apply (n0 eq_refl).\n      * right; intro; subst.\n        apply (n0 eq_refl).\n  - induction n.\n    + left.\n      extensionality x.\n      apply Fin.case0.\n      apply x.\n    + simpl in *.\n      destruct (IHn (fun i => e1 (Fin.FS i)) (fun i => e2 (Fin.FS i))).\n      * destruct (IHk (e1 Fin.F1) (e2 Fin.F1)).\n        -- left.\n           extensionality x.\n           apply (Fin.caseS' x); try assumption; apply equal_f; assumption.\n        -- right; intro; subst.\n           apply (n0 eq_refl).\n      * right; intro; subst.\n        apply (n0 eq_refl).\nDefined.\n\nDefinition evalUniBool (op: UniBoolOp) : bool -> bool :=\n  match op with\n    | Neg => negb\n  end.\n\nDefinition evalCABool (op: CABoolOp) (ws : list bool) : bool :=\n  match op with\n    | And => fold_left andb ws true\n    (* | Or => fold_left orb ws false *)\n    | Xor => fold_left xorb ws false\n  end.\n\nDefinition evalUniBit n1 n2 (op: UniBitOp n1 n2): word n1 -> word n2 :=\n  match op with\n  | Inv n => (@wnot n)\n  | TruncLsb lsb msb => truncLsb \n  | TruncMsb lsb msb => truncMsb\n  | UAnd n =>  fun w => boolToWord 1 (@wuand n w)\n  | UOr n => fun w => boolToWord 1 (@wuor n w)\n  | UXor n => fun w => boolToWord 1 (@wuxor n w)\n  end.\n\nDefinition wneg_simple sz (x: word sz) := wnot x ^+ (natToWord _ 1).\n\nDefinition wminus_simple sz (x y: word sz) := x ^+ (wneg_simple y).\n\nLemma wneg_simple_wneg sz: forall (x: word sz), wneg_simple x = wneg x.\nProof.\n  unfold wneg_simple.\n  intros.\n  rewrite wneg_wnot.\n  rewrite wminus_wplus_undo.\n  reflexivity.\nQed.\n\nLemma wminus_simple_wminus sz: forall (x y: word sz), wminus_simple x y = wsub x y.\nProof.\n  unfold wminus_simple.\n  intros.\n  rewrite wneg_simple_wneg.\n  rewrite wminus_def.\n  reflexivity.\nQed.\n\nDefinition evalBinBit n1 n2 n3 (op: BinBitOp n1 n2 n3)\n  : word n1 -> word n2 -> word n3 :=\n  match op with\n    | Sub n => @wsub n\n    | Div n => @wdiv n\n    | Rem n => @wmod n\n    | Sll n m => (fun x y => wslu x (ZToWord _ (wordVal _ y)))\n    | Srl n m => (fun x y => wsru x (ZToWord _ (wordVal _ y)))\n    | Sra n m => wsra\n    | Concat n1 n2 => wconcat\n  end.\n\nDefinition evalCABit n (op: CABitOp) (ls: list (word n)): word n :=\n  match op with\n    | Add => fold_left (@wadd n) ls (ZToWord n 0)\n    | Mul => fold_left (@wmul n) ls (ZToWord n 1)\n    | Band => fold_left (@wand n) ls  (ZToWord n ((2 ^ (Z.of_nat n)) - 1))\n    (* | Bor => fold_left (@wor n) ls (ZToWord n 0) *)\n    | Bxor => fold_left (@wxor n) ls (ZToWord n 0)\n  end.\n\nDefinition evalBinBitBool n1 n2 (op: BinBitBoolOp n1 n2)\n  : word n1 -> word n2 -> bool :=\n  match op with\n    | LessThan n => fun a b => @wltu n a b\n  end.\n\nDefinition evalConstFullT k (e: ConstFullT k) :=\n  match e in ConstFullT k return fullType type k with\n    | SyntaxConst k' c' => evalConstT c'\n    | NativeConst t c' => c'\n  end.\n\nFixpoint evalKorOpBin (k : Kind) : type k -> type k -> type k :=\n  match k in Kind return (type k -> type k -> type k) with\n  | Bool => orb\n  | Bit n => @wor n\n  | Array n k' => fun a1 a2 => (fun i => (evalKorOpBin k' (a1 i) (a2 i)))\n  | Struct n fv _ => fun (s1 s2 : forall i, type (fv i)) =>\n                     (fun i => (evalKorOpBin (fv i) (s1 i) (s2 i)))\n  end.\n\nDefinition evalKorOp (k : Kind) : list (type k) -> type k -> type k :=\n  fold_left (evalKorOpBin k).\n\n(* maps register names to the values which they currently hold *)\nNotation RegT := (Attribute (sigT (fullType type))).\nDefinition RegsT := (list RegT).\n\n(* a pair of the value sent to a method call and the value it returned *)\nDefinition SignT k := (type (fst k) * type (snd k))%type.\n\n(* a list of simulatenous method call actions made during a single step *)\nNotation MethT := (Attribute (sigT SignT)).\nDefinition MethsT := (list MethT).\n\nSection Semantics.\n  Fixpoint evalExpr exprT (e: Expr type exprT): fullType type exprT :=\n    match e in Expr _ exprT return fullType type exprT with\n      | Var _ v => v\n      | Const _ v => evalConstT v\n      | UniBool op e1 => (evalUniBool op) (@evalExpr _ e1)\n      | CABool op es => evalCABool op (map (@evalExpr _) es)\n      | UniBit n1 n2 op e1 => (evalUniBit op) (@evalExpr _ e1)\n      | BinBit n1 n2 n3 op e1 e2 => (evalBinBit op) (@evalExpr _ e1) (@evalExpr _ e2)\n      | CABit n op es => evalCABit op (map (@evalExpr _) es)\n      | BinBitBool n1 n2 op e1 e2 => (evalBinBitBool op) (@evalExpr _ e1) (@evalExpr _ e2)\n      | ITE _ p e1 e2 => if @evalExpr _ p\n                         then @evalExpr _ e1\n                         else @evalExpr _ e2\n      | Eq _ e1 e2 => getBool (isEq _ (@evalExpr _ e1) (@evalExpr _ e2))\n      | ReadStruct n fk fs e i => (@evalExpr _ e) i\n      | BuildStruct n fk fs fv => fun i => @evalExpr _ (fv i)\n      | ReadArray n m k fv i =>\n        match lt_dec (Z.to_nat (wordVal _ (@evalExpr _ i))) n with\n        | left pf => fun fv => fv (Fin.of_nat_lt pf)\n        | right _ => fun _ => evalConstT (getDefaultConst k)\n        end (@evalExpr _ fv)\n      | ReadArrayConst n k fv i =>\n        (@evalExpr _ fv) i\n      | BuildArray n k fv => fun i => @evalExpr _ (fv i)\n      | Kor k e => evalKorOp k (map (@evalExpr _) e) (evalConstT (getDefaultConst k))\n      | ToNative _ e => evalExpr e\n      | FromNative _ e => evalExpr e\n    end.\n  Arguments evalExpr : simpl nomatch.\n      \n  Fixpoint evalLetExpr k (e: LetExprSyntax type k) :=\n    match e in LetExprSyntax _ _ return type k with\n    | NormExpr e' => evalExpr e'\n    | SysE ls cont => evalLetExpr cont\n    | LetE _ e' cont => evalLetExpr (cont (evalLetExpr e'))\n    | IfElseE pred _ t f cont => evalLetExpr (cont (if evalExpr pred\n                                                    then evalLetExpr t\n                                                    else evalLetExpr f))\n    end.\n  \n  Variable o: RegsT.\n\n  Inductive SemAction:\n    forall k, ActionT type k -> RegsT -> RegsT -> MethsT -> type k -> Prop :=\n  | SemMCall\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      (HSemAction: SemAction (cont mret) readRegs newRegs calls fret):\n      SemAction (MCall meth s marg cont) readRegs newRegs acalls fret\n  | SemLetExpr\n      k (e: Expr type k) retK (fret: type retK)\n      (cont: fullType type k -> ActionT type retK) readRegs newRegs calls\n      (HSemAction: SemAction (cont (evalExpr e)) readRegs newRegs calls fret):\n      SemAction (LetExpr e cont) readRegs newRegs calls fret\n  | SemLetAction\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      (HSemAction: SemAction a readRegs newRegs calls v)\n      (HSemActionCont: SemAction (cont v) readRegsCont newRegsCont callsCont fret)\n      uReadRegs uNewRegs uCalls\n      (HReadRegs: uReadRegs = readRegs ++ readRegsCont)\n      (HNewRegs: uNewRegs = newRegs ++ newRegsCont)\n      (HCalls: uCalls = calls ++ callsCont):\n      SemAction (LetAction a cont) uReadRegs uNewRegs uCalls fret\n  | SemReadNondet\n      valueT (valueV: fullType type valueT)\n      retK (fret: type retK) (cont: fullType type valueT -> ActionT type retK)\n      readRegs newRegs calls\n      (HSemAction: SemAction (cont valueV) readRegs newRegs calls fret):\n      SemAction (ReadNondet _ cont) readRegs newRegs calls fret\n  | SemReadReg\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      (HSemAction: SemAction (cont regV) readRegs newRegs calls fret)\n      (HNewReads: areadRegs = (r, existT _ regT regV) :: readRegs):\n      SemAction (ReadReg r _ cont) areadRegs newRegs calls fret\n  | SemWriteReg\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      (HSemAction: SemAction cont readRegs newRegs calls fret):\n      SemAction (WriteReg r e cont) readRegs anewRegs calls fret\n  | SemIfElseTrue\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: SemAction a readRegs1 newRegs1 calls1 r1)\n      (HSemAction: SemAction (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      SemAction (IfElse p a a' cont) ureadRegs unewRegs ucalls r2\n  | SemIfElseFalse\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: SemAction a' readRegs1 newRegs1 calls1 r1)\n      (HSemAction: SemAction (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      SemAction (IfElse p a a' cont) ureadRegs unewRegs ucalls r2\n  | SemSys\n      (ls: list (SysT type)) k (cont: ActionT type k)\n      r readRegs newRegs calls\n      (HSemAction: SemAction cont readRegs newRegs calls r):\n      SemAction (Sys ls cont) readRegs newRegs calls r\n  | SemReturn\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      SemAction (Return e) readRegs newRegs calls evale.\nEnd Semantics.\n\nInductive RuleOrMeth :=\n| Rle (rn: string)\n| Meth (f: MethT).\n\nNotation getRleOrMeth := (fun x => fst (snd x)).\n\nNotation FullLabel := (RegsT * (RuleOrMeth * MethsT))%type.\n\n\nLemma SignT_dec: forall k1 k2 (s1 s2: SignT (k1, k2)), {s1 = s2} + {s1 <> s2}.\nProof.\n  intros.\n  destruct s1, s2.\n  simpl in *.\n  apply prod_dec; simpl; auto; apply isEq.\nDefined.\n\nSection MethT_dec.\n  (*\n  Asserts that, if the values passed to, and\n  returned by, a method are equal, the Gallina\n  values passed to, and returned by, a method\n  are also equal.\n   *)\n  Lemma method_values_eq\n  :  forall (s : Signature) (x y : SignT s), existT SignT s x = existT SignT s y -> x = y.\n  Proof.\n    intros. inv H.\n    apply (Eqdep_dec.inj_pair2_eq_dec Signature Signature_dec SignT) in H1. auto.\n  Qed.\n\n  (*\n  Asserts that the values passed to and returned\n  by two method calls differ if their signatures\n  differ.\n   *)\n  Lemma method_values_neq \n    :  forall (s r : Signature) (x : SignT s) (y : SignT r), s <> r -> existT SignT s x <> existT SignT r y.\n  Proof.\n    intros.\n    unfold not. intros.\n    inv H0. \n    apply H; reflexivity.\n  Qed.\n    \n  (*Proof (fun s r x y H H0 => H (projT1_eq H0)).*)\n\n  (*\n  Determines whether or not the Gallina terms\n  passed to, and returned by, two method calls\n  are equal.\n   *)\n  Definition method_denotation_values_dec\n    :  forall (s : Signature) (x y : SignT s), {x = y} + {x <> y}\n    := fun s => prod_dec (isEq (fst s)) (isEq (snd s)).\n\n  (*\n  Determines whether or not the values passed to,\n  and returned by, two method calls that have\n  the same Kami signature are equal.\n   *)\n  Definition method_values_dec\n    :  forall (s : Signature) (x y : SignT s), {existT SignT s x = existT SignT s y} + {existT SignT s x <> existT SignT s y}\n    := fun s x y\n       => sumbool_rec\n            (fun _ => {existT SignT s x = existT SignT s y} + {existT SignT s x <> existT SignT s y})\n            (fun H : x = y\n             => left\n                  (eq_ind x\n                          (fun z => existT SignT s x = existT SignT s z)\n                          (eq_refl (existT SignT s x))\n                          y H))\n            (fun H : x <> y\n             => right\n                  (fun H0 : existT SignT s x = existT SignT s y\n                   => H (method_values_eq H0)))\n            (method_denotation_values_dec x y).\n  \n  (*\n  Determines whether or not the values passed to,\n  and returned by, two method calls are equal.\n   *)\n  Definition sigT_SignT_dec\n    :  forall x y: (sigT SignT), {x = y} + {x <> y}\n    := sigT_rect _\n                 (fun (s : Signature) (x : SignT s)\n                  => sigT_rect _\n                               (fun (r : Signature)\n                                => sumbool_rect _\n                                                (fun H : s = r\n                                                 => eq_rect s\n                                                            (fun t => forall y : SignT t, {existT SignT s x = existT SignT t y} + {existT SignT s x <> existT SignT t y})\n                                                            (fun y : SignT s => method_values_dec x y)\n                                                            r H)\n                                                (fun (H : s <> r) (_ : SignT r)\n                                                 => right (method_values_neq H))\n                                                (Signature_dec s r))).\n\n  Lemma MethT_dec: forall s1 s2: MethT, {s1 = s2} + {s1 <> s2}.\n  Proof.\n    intros.\n    destruct s1, s2.\n    apply prod_dec.\n    - apply string_dec.\n    - apply sigT_SignT_dec.\n  Defined.\n  \nEnd MethT_dec.\n  \nFixpoint getNumFromCalls (f : MethT) (l : MethsT) : Z :=\n  match l with\n  |g::l' => match MethT_dec f g with\n            | left _ => 1%Z + (getNumFromCalls f l')\n            | right _ => (getNumFromCalls f l')\n            end\n  |nil => 0\n  end.\n\nDefinition getNumCalls (f : MethT) (l : list FullLabel) :=\n  getNumFromCalls f (concat (map (fun x => (snd (snd x))) l)).\n\nFixpoint getNumFromExecs (f : MethT) (l : list RuleOrMeth) : Z :=\n  match l with\n  |rm::l' => match rm with\n             |Rle _ => (getNumFromExecs f l')\n             |Meth g => match MethT_dec f g with\n                        |left _ => 1%Z + (getNumFromExecs f l')\n                        |right _ => (getNumFromExecs f l')\n                        end\n             end\n  |nil => 0\n  end.\n\nDefinition getNumExecs (f : MethT) (l : list FullLabel) :=\n  getNumFromExecs f (map (fun x => fst (snd x)) l).\n\nDefinition getListFullLabel_diff (f : MethT) (l : list FullLabel) :=\n  ((getNumExecs f l) - (getNumCalls f l))%Z.\n\nDefinition MatchingExecCalls_Base (l : list FullLabel) m :=\n  forall f,\n    In (fst f, projT1 (snd f)) (getKindAttr (getMethods m)) ->\n    (getNumCalls f l <= getNumExecs f l)%Z.\n\nDefinition MatchingExecCalls_Concat (lcall lexec : list FullLabel) mexec :=\n  forall f,\n    (getNumCalls f lcall <> 0%Z) ->\n    In (fst f, projT1 (snd f)) (getKindAttr (getAllMethods mexec)) ->\n    ~In (fst f) (getHidden mexec) /\\\n    (getNumCalls f lcall + getNumCalls f lexec <= getNumExecs f lexec)%Z.\n\nSection BaseModule.\n  Variable m: BaseModule.\n\n  Variable o: RegsT.\n\n  Inductive Substeps: list FullLabel -> Prop :=\n  | NilSubstep (HRegs: getKindAttr o = getKindAttr (getRegisters m)) : Substeps nil\n  | AddRule (HRegs: getKindAttr o = getKindAttr (getRegisters m))\n            rn rb\n            (HInRules: In (rn, rb) (getRules m))\n            reads u cs\n            (HAction: SemAction 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            (HSubstep: Substeps ls):\n      Substeps l\n  | AddMeth (HRegs: getKindAttr o = getKindAttr (getRegisters m))\n            fn fb\n            (HInMeths: In (fn, fb) (getMethods m))\n            reads u cs argV retV\n            (HAction: SemAction 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            (HSubsteps: Substeps ls):\n      Substeps l.\nEnd BaseModule.\n\nInductive Step: Mod -> RegsT -> list FullLabel -> Prop :=\n| BaseStep m o l (HSubsteps: Substeps m o l) (HMatching: MatchingExecCalls_Base l  m):\n    Step (Base m) o l\n| HideMethStep m s o l (HStep: Step m o l)\n               (HHidden : forall v, In (s, projT1 v) (getKindAttr (getAllMethods m)) -> getListFullLabel_diff (s, v) l = 0%Z):\n    Step (HideMeth m s) o l\n| ConcatModStep m1 m2 o1 o2 l1 l2\n                (HStep1: Step m1 o1 l1)\n                (HStep2: Step 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    Step (ConcatMod m1 m2) o l.\n\nDefinition UpdRegs (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\nNotation regInit := (fun (o': RegT) (r: RegInitT)  => fst o' = fst r /\\\n                                                      exists (pf: projT1 (snd o') = projT1 (snd r)),\n                                                        match projT2 (snd r) with\n                                                        | None => True\n                                                        | Some x =>\n                                                          match pf in _ = Y return _ Y with\n                                                          | eq_refl => projT2 (snd o')\n                                                          end = evalConstFullT x\n                                                        end).\n\nFixpoint findReg (s: string) (u: RegsT) :=\n  match u with\n  | x :: xs => if String.eqb s (fst x)\n               then Some (snd x)\n               else findReg s xs\n  | nil => None\n  end.\n\nFixpoint doUpdRegs (u: RegsT) (o: RegsT) :=\n  match o with\n  | x :: o' => match findReg (fst x) u with\n               | Some y => (fst x, y)\n               | None => x\n               end :: doUpdRegs u o'\n  | nil => nil\n  end.\n\nSection Trace.\n  Variable m: Mod.\n  Inductive Trace: RegsT -> list (list FullLabel) -> Prop :=\n  | InitTrace (o': RegsT) ls'\n              (HUpdRegs: (Forall2 regInit o' (getAllRegisters m)))\n              (HTrace: ls' = nil):\n      Trace o' ls'\n  | ContinueTrace o ls l o' ls'\n                  (HOldTrace: Trace o ls)\n                  (HStep: Step m o l)\n                  (HUpdRegs: UpdRegs (map fst l) o o')\n                  (HTrace: ls' = l :: ls):\n      Trace o' ls'.\nEnd Trace.\n\nDefinition WeakInclusion (l1 : list FullLabel) (l2 : list FullLabel) : Prop :=\n  (forall f, getListFullLabel_diff f l1 = getListFullLabel_diff f l2) /\\\n  ((exists rle, In (Rle rle) (map (fun x => fst (snd x)) l2)) ->\n   (exists rle, In (Rle rle) (map (fun x => fst (snd x)) l1))).\n\nDefinition TraceInclusion m1 m2 :=\n forall o1 ls1,\n   Trace m1 o1 ls1 ->\n   exists o2 ls2,\n     Trace m2 o2 ls2 /\\\n     length ls1 = length ls2 /\\\n     (nthProp2 WeakInclusion ls1 ls2).\n\nDefinition TraceEquiv m1 m2 := TraceInclusion m1 m2 /\\ TraceInclusion m2 m1.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n(* Useful functions *)\n\nFixpoint getCallsWithSign k (a: ActionT (fun _ => unit) k) :=\n  match a in ActionT _ _ with\n  | MCall meth k argExpr cont =>\n    (meth, k) :: getCallsWithSign (cont tt)\n  | Return x => nil\n  | LetExpr k' expr cont =>\n    match k' return (fullType (fun _ => unit) k' -> ActionT (fun _ => unit) k) ->\n                    list (string * (Kind * Kind)) with\n    | SyntaxKind k => fun cont => getCallsWithSign (cont tt)\n    | _ => fun _ => nil\n    end cont\n  | LetAction k' a' cont =>\n    getCallsWithSign a' ++ getCallsWithSign (cont tt)\n  | ReadNondet k' cont =>\n    match k' return (fullType (fun _ => unit) k' -> ActionT (fun _ => unit) k) ->\n                    list (string * (Kind * Kind)) with\n    | SyntaxKind k => fun cont =>\n                        getCallsWithSign (cont tt)\n    | _ => fun _ => nil\n    end cont\n  | ReadReg r k' cont =>\n    match k' return (fullType (fun _ => unit) k' -> ActionT (fun _ => unit) k) ->\n                    list (string * (Kind * Kind)) with\n    | SyntaxKind k => fun cont =>\n                        getCallsWithSign (cont tt)\n    | _ => fun _ => nil\n    end cont\n  | WriteReg r k' expr cont =>\n    getCallsWithSign cont\n  | Sys ls cont => getCallsWithSign cont\n  | IfElse pred ktf t f cont =>\n    getCallsWithSign t ++ getCallsWithSign f ++ getCallsWithSign (cont tt)\n  end.\n\nDefinition getCallsWithSignPerRule (rule: Attribute (Action Void)) :=\n  getCallsWithSign (snd rule _).\n\nDefinition getCallsWithSignPerMeth (meth: DefMethT) :=\n  getCallsWithSign (projT2 (snd meth) _ tt).\n\nFixpoint getCallsWithSignPerMod (mm: Mod) :=\n  match mm with\n  | Base m => concat (map getCallsWithSignPerRule (getRules m))++ concat (map getCallsWithSignPerMeth (getMethods m))\n  | HideMeth m _ => getCallsWithSignPerMod m\n  | ConcatMod m1 m2 => getCallsWithSignPerMod m1 ++ getCallsWithSignPerMod m2\n  end.\n\nDefinition getCallsPerMod (m: Mod) := map fst (getCallsWithSignPerMod m).\n\nFixpoint getRegWrites k (a: ActionT (fun _ => unit) k) :=\n  match a in ActionT _ _ with\n  | MCall meth k argExpr cont =>\n    getRegWrites (cont tt)\n  | Return x => nil\n  | LetExpr k' expr cont =>\n    match k' return (fullType (fun _ => unit) k' -> ActionT (fun _ => unit) k) ->\n                    list (string * FullKind) with\n    | SyntaxKind k => fun cont => getRegWrites (cont tt)\n    | _ => fun _ => nil\n    end cont\n  | LetAction k' a' cont =>\n    getRegWrites a' ++ getRegWrites (cont tt)\n  | ReadNondet k' cont =>\n    match k' return (fullType (fun _ => unit) k' -> ActionT (fun _ => unit) k) ->\n                    list (string * FullKind) with\n    | SyntaxKind k => fun cont =>\n                        getRegWrites (cont tt)\n    | _ => fun _ => nil\n    end cont\n  | ReadReg r k' cont =>\n    match k' return (fullType (fun _ => unit) k' -> ActionT (fun _ => unit) k) ->\n                    list (string * FullKind) with\n    | SyntaxKind k => fun cont =>\n                        getRegWrites (cont tt)\n    | _ => fun _ => nil\n    end cont\n  | WriteReg r k' expr cont =>\n    (r, k') :: getRegWrites cont\n  | Sys ls cont => getRegWrites cont\n  | IfElse pred ktf t f cont =>\n    getRegWrites t ++ getRegWrites f ++ getRegWrites (cont tt)\n  end.\n\n\n\n\n\n\n(* Utility functions *)\n\nFixpoint createHide (m: BaseModule) (hides: list string) :=\n  match hides with\n  | nil => Base m\n  | x :: xs => HideMeth (createHide m xs) x\n  end.\n\nFixpoint createHideMod (m : Mod) (hides : list string) : Mod :=\n  match hides with\n  | nil => m\n  | h::hides' => HideMeth (createHideMod m hides') h\n  end.\n\nDefinition getFlat m := BaseMod (getAllRegisters m) (getAllRules m) (getAllMethods m).\n\nDefinition flatten m := createHide (getFlat m) (getHidden m).\n\nDefinition autoHide (m: Mod) := createHideMod m (filter (fun i => existsb (String.eqb i) (getCallsPerMod m))\n                                                        (map fst (getAllMethods m))).\n\nFixpoint separateBaseMod (m: Mod): (list RegFileBase * list BaseModule) :=\n  match m with\n  | Base m' =>\n    match m' with\n    | BaseMod regs rules meths => (nil, BaseMod regs rules meths :: nil)\n    | BaseRegFile rf => (rf :: nil, nil)\n    end\n  | HideMeth m' meth => separateBaseMod m'\n  | ConcatMod m1 m2 =>\n    let '(rfs1, ms1) := separateBaseMod m1 in\n    let '(rfs2, ms2) := separateBaseMod m2 in\n    (rfs1 ++ rfs2, ms1 ++ ms2)\n  end.\n\nDefinition separateMod (m: Mod) :=\n  (getHidden m, separateBaseMod m).\n    \nFixpoint mergeSeparatedBaseMod (bl : list BaseModule) : Mod :=\n  match bl with\n  | b::bl' => ConcatMod (Base b) (mergeSeparatedBaseMod bl')\n  | nil => Base (BaseMod nil nil nil)\n  end.\n\nFixpoint mergeSeparatedBaseFile (rfl : list RegFileBase) : Mod :=\n  match rfl with\n  | rf::rfl' => ConcatMod (Base (BaseRegFile rf))(mergeSeparatedBaseFile rfl')\n  | nil => Base (BaseMod nil nil nil)\n  end.\n\nDefinition mergeSeparatedMod (tup: list string * (list RegFileBase * list BaseModule)) :=\n  createHideMod (ConcatMod (mergeSeparatedBaseFile (fst (snd tup))) (mergeSeparatedBaseMod (snd (snd tup)))) (fst tup).\n \nDefinition concatFlat m1 m2 := BaseMod (getRegisters m1 ++ getRegisters m2)\n                                       (getRules m1 ++ getRules m2)\n                                       (getMethods m1 ++ getMethods m2).\n\n\n\n\n\n\n\n(* Inlining *)\n\nSection inlineSingle.\n  Variable ty: Kind -> Type.\n\n  Fixpoint inlineSingle k (a: ActionT ty k) (f: DefMethT): ActionT ty k :=\n    match a with\n    | MCall g sign arg cont =>\n      match String.eqb (fst f) g with\n      | true =>\n        match Signature_dec sign (projT1 (snd f)) with\n        | left isEq =>\n          LetAction (LetExpr match isEq in _ = Y return Expr ty (SyntaxKind (fst Y)) with\n                             | eq_refl => arg\n                             end (projT2 (snd f) ty))\n                    (fun ret => inlineSingle (match isEq in _ = Y return ty (snd Y) -> ActionT ty k with\n                                              | eq_refl => cont\n                                              end ret) f)\n        | right _ => MCall g sign arg (fun ret => inlineSingle (cont ret) f)\n        end\n      | false => MCall g sign arg (fun ret => inlineSingle (cont ret) f)\n      end\n    | LetExpr _ e cont =>\n      LetExpr e (fun ret => inlineSingle (cont ret) f)\n    | LetAction _ a cont =>\n      LetAction (inlineSingle a f) (fun ret => inlineSingle (cont ret) f)\n    | ReadNondet k c =>\n      ReadNondet k (fun ret => inlineSingle (c ret) f)\n    | ReadReg r k c =>\n      ReadReg r k (fun ret => inlineSingle (c ret) f)\n    | WriteReg r k e a =>\n      WriteReg r e (inlineSingle a f)\n    | IfElse p _ aT aF c =>\n      IfElse p (inlineSingle aT f) (inlineSingle aF f) (fun ret => inlineSingle (c ret) f)\n    | Sys ls c =>\n      Sys ls (inlineSingle c f)\n    | Return e =>\n      Return e\n    end.\n\nEnd inlineSingle.\n\nDefinition inlineSingle_Rule  (f : DefMethT) (rle : RuleT): RuleT :=\n  let (s, a) := rle in\n  (s, fun ty => inlineSingle (a ty) f).\n\nDefinition inlineSingle_Rule_map_BaseModule (f : DefMethT) (m : BaseModule) :=\n  BaseMod (getRegisters m) (map (inlineSingle_Rule f) (getRules m)) (getMethods m).\n\nFixpoint inlineSingle_Rule_in_list (f : DefMethT) (rn : string) (lr : list RuleT) : list RuleT :=\n  match lr with\n  | rle'::lr' => match String.eqb rn (fst rle') with\n                 | false => rle'\n                 | true => inlineSingle_Rule f rle'\n                 end ::(inlineSingle_Rule_in_list f rn lr')\n  | nil => nil\n  end.\n\nDefinition inlineSingle_Rule_BaseModule (f : DefMethT) (rn : string) (m : BaseModule) :=\n  BaseMod (getRegisters m) (inlineSingle_Rule_in_list f rn (getRules m)) (getMethods m).\n\nDefinition inlineSingle_Meth (f : DefMethT) (meth : DefMethT): DefMethT :=\n  let (name, sig_body) := meth in\n  (name,\n   if String.eqb (fst f) name\n   then sig_body\n   else\n     let (sig, body) := sig_body in\n     existT _ sig (fun ty arg => inlineSingle (body ty arg) f)).\n\nDefinition inlineSingle_Meth_map_BaseModule (f : DefMethT) (m : BaseModule) :=\n  BaseMod (getRegisters m) (getRules m) (map (inlineSingle_Meth f) (getMethods m)).\n\nFixpoint inlineSingle_Meth_in_list (f : DefMethT) (gn : string) (lm : list DefMethT) : list DefMethT :=\n  match lm with\n  | meth'::lm' => match String.eqb gn (fst meth') with\n                  | false => meth'\n                  | true => (inlineSingle_Meth f meth')\n                  end ::(inlineSingle_Meth_in_list f gn lm')\n  | nil => nil\n  end.\n\nDefinition inlineSingle_Meth_BaseModule (f : DefMethT) (fn : string) (m : BaseModule) :=\n  BaseMod (getRegisters m) (getRules m) (inlineSingle_Meth_in_list f fn (getMethods m)).\n\nSection inlineSingle_nth.\n  Variable (f : DefMethT).\n  Variable (regs: list RegInitT) (rules: list RuleT) (meths: list DefMethT).\n\n  Definition inlineSingle_BaseModule : BaseModule :=\n    BaseMod regs (map (inlineSingle_Rule f) rules) (map (inlineSingle_Meth f) meths).\n\n  Definition inlineSingle_BaseModule_nth_Meth xs : BaseModule :=\n    BaseMod regs rules (fold_right (transform_nth_right (inlineSingle_Meth f)) meths xs).\n\n  Definition inlineSingle_BaseModule_nth_Rule xs : BaseModule :=\n    BaseMod regs (fold_right (transform_nth_right (inlineSingle_Rule f)) rules xs) meths.\nEnd inlineSingle_nth.\n\nDefinition inlineSingle_Rules_pos meths n rules :=\n  match nth_error meths n with\n  | Some f => map (inlineSingle_Rule f) rules\n  | None => rules\n  end.\n\nDefinition inlineAll_Rules meths rules := fold_left (fun newRules n => inlineSingle_Rules_pos meths n newRules) (seq 0 (length meths)) rules.\n\nDefinition inlineAll_Rules_mod m :=\n  (BaseMod (getRegisters m) (inlineAll_Rules (getMethods m) (getRules m)) (getMethods m)).\n\nDefinition inlineSingle_Meths_pos newMeths n :=\n  match nth_error newMeths n with\n  | Some f => map (inlineSingle_Meth f) newMeths\n  | None => newMeths\n  end.\n\nDefinition inlineAll_Meths meths := fold_left inlineSingle_Meths_pos (seq 0 (length meths)) meths.\n\nDefinition inlineAll_Meths_mod m :=\n  (BaseMod (getRegisters m) (getRules m) (inlineAll_Meths (getMethods m))).\n\nDefinition inlineAll_All regs rules meths :=\n  (BaseMod regs (inlineAll_Rules (inlineAll_Meths meths) rules) (inlineAll_Meths meths)).\n\nDefinition inlineAll_All_mod m :=\n  inlineAll_All (getAllRegisters m) (getAllRules m) (getAllMethods m).\n\nDefinition flatten_inline_everything m :=\n  createHide (inlineAll_All_mod m) (getHidden m).\n\nDefinition removeHides (m: BaseModule) s :=\n  BaseMod (getRegisters m) (getRules m)\n          (filter (fun df => negb (existsb (String.eqb (fst df)) s)) (getMethods m)).\n\nDefinition flatten_inline_remove m :=\n  removeHides (inlineAll_All_mod m) (getHidden m).\n\n(* Last Set of Utility Functions *)\n\nDefinition hiddenBy (meths : list DefMethT) (h : string) : bool :=\n  (existsb (String.eqb h) (map fst meths)).\n\nDefinition getAllBaseMethods (lb : list BaseModule) : (list DefMethT) :=\n  (concat (map getMethods lb)).\n\nDefinition hiddenByBase (lb : list BaseModule) (h : string) : bool :=\n  (hiddenBy (getAllBaseMethods lb) h).\n\nLocal Notation complement f := (fun x => negb (f x)).\n\nDefinition separateHides (tl : list string * (list RegFileBase * list BaseModule)) :\n  (list string * list string) :=\n  (filter (hiddenByBase (map BaseRegFile (fst (snd tl)))) (fst tl),\n   filter (complement (hiddenByBase (map BaseRegFile (fst (snd tl))))) (fst tl)).\n\nDefinition separateModHides (m: Mod) :=\n  let '(hides, (rfs, mods)) := separateMod m in\n  let '(hidesRf, hidesBm) := separateHides (hides, (rfs, mods)) in\n  (hidesRf, (rfs, createHide (inlineAll_All_mod (mergeSeparatedBaseMod mods)) hidesBm)).\n\nDefinition separateModRemove (m : Mod) :=\n  let '(hides, (rfs, mods)) := separateMod m in\n  let '(hidesRf, hidesBm) := separateHides (hides, (rfs, mods)) in\n  (hidesRf, (rfs, removeHides (inlineAll_All_mod (mergeSeparatedBaseMod mods)) hidesBm)).\n\nDefinition baseNoSelfCalls (m : Mod) :=\n  let '(hides, (rfs, mods)) := separateMod m in\n  NoSelfCallBaseModule (inlineAll_All_mod (mergeSeparatedBaseMod mods)).\n\nDefinition separateModHidesNoInline (m : Mod) :=\n  let '(hides, (rfs, mods)) := separateMod m in\n  (hides, (rfs, getFlat (mergeSeparatedBaseMod mods))).\n\n(* Helper functions for struct - Gallina versions of getters and setters *)\n\nLocal Definition option_bind\n  (T U : Type)\n  (x : option T)\n  (f : T -> option U)\n  :  option U\n  := match x with\n       | Some y => f y\n       | None => None\n     end.\n\nLocal Notation \"X >>- F\" := (option_bind X F) (at level 85, only parsing).\n\nFixpoint struct_get_field_index'\n         (name: string) n\n  := match n return\n         forall (get_name : Fin.t n -> string),\n                option (Fin.t n)\n     with\n     | 0 => fun _ => None\n     | S m => fun get_name =>\n       if String.eqb (get_name Fin.F1) name\n       then Some Fin.F1\n       else match struct_get_field_index' name _ (fun i => get_name (Fin.FS i)) with\n            | Some i => Some (Fin.FS i)\n            | None => None\n            end\n     end.\n\nDefinition struct_get_field_index n (kinds: Fin.t n -> Kind) (names: Fin.t n -> string) ty (e: Expr ty (SyntaxKind (Struct kinds names))) name\n  := struct_get_field_index' name names.\n\nLocal Definition struct_get_field_aux\n  (ty: Kind -> Type)\n  (n : nat)\n  (get_kind : Fin.t n -> Kind)\n  (get_name : Fin.t n -> string)\n  (packet : Expr ty (SyntaxKind (Struct get_kind get_name)))\n  (name : string)\n  :  option ({kind : Kind & Expr ty (SyntaxKind kind)})\n  := struct_get_field_index packet name >>-\n       fun index\n         => Some\n              (existT\n                (fun kind : Kind => Expr ty (SyntaxKind kind))\n                (get_kind index)\n                (ReadStruct packet index)).\n\nDefinition struct_get_field\n  (ty: Kind -> Type)\n  (n : nat)\n  (get_value : Fin.t n -> Kind)\n  (get_name : Fin.t n -> string)\n  (packet : Expr ty (SyntaxKind (Struct get_value get_name)))\n  (name : string)\n  (k : Kind)\n  :  option (Expr ty (SyntaxKind k)).\nProof.\nrefine (let y := @struct_get_field_aux ty n get_value get_name packet name in\n        match y with\n        | None => None\n        | Some (existT x y) => _\n        end).\ndestruct (Kind_decb x k) eqn:G.\n- apply Kind_decb_eq in G.\n  subst.\n  exact (Some y).\n- exact None.\nDefined.\n\nDefinition struct_get_field_default\n  (ty: Kind -> Type)\n  (n : nat)\n  (get_value : Fin.t n -> Kind)\n  (get_name : Fin.t n -> string)\n  (packet : Expr ty (SyntaxKind (Struct get_value get_name)))\n  (name : string)\n  (kind : Kind)\n  (default : Expr ty (SyntaxKind kind))\n  :  Expr ty (SyntaxKind kind)\n  := match struct_get_field packet name kind with\n       | Some field_value => field_value\n       | None => default\n     end.\n\nDefinition struct_set_field\n  (ty: Kind -> Type)\n  (n : nat)\n  (get_kind : Fin.t n -> Kind)\n  (get_name : Fin.t n -> string)\n  (packet : Expr ty (SyntaxKind (Struct get_kind get_name)))\n  (name : string)\n  (kind : Kind)\n  (value : Expr ty (SyntaxKind kind))\n  :  option (Expr ty (SyntaxKind (Struct get_kind get_name))).\nProof.\n  refine (let y := struct_get_field_index packet name in\n          match y with\n          | None => None\n          | Some i => _\n          end).\n  destruct (Kind_dec (get_kind i) kind).\n  - subst.\n    exact (Some (UpdateStruct packet i value)).\n  - exact None.\nDefined.\n\nDefinition struct_set_field_default\n           (ty: Kind -> Type)\n           (n : nat)\n           (get_kind : Fin.t n -> Kind)\n           (get_name : Fin.t n -> string)\n           (packet : Expr ty (SyntaxKind (Struct get_kind get_name)))\n           (name : string)\n           (kind : Kind)\n           (value : Expr ty (SyntaxKind kind))\n  : Expr ty (SyntaxKind (Struct get_kind get_name)).\nProof.\n  refine (let y := struct_get_field_index packet name in\n          match y with\n          | None => packet\n          | Some i => _\n          end).\n  destruct (Kind_dec (get_kind i) kind).\n  - subst.\n    exact (UpdateStruct packet i value).\n  - exact packet.\nDefined.\n\nCreate HintDb KamiDb.\nHint Unfold \n     inlineSingle_Meths_pos\n     flatten_inline_remove \n     getHidden\n     getAllRegisters\n     getAllMethods\n     getAllRules\n     inlineAll_All_mod\n     inlineAll_All\n     writeRegFileFn\n     readRegFile\n     createHideMod\n     List.find\n     List.fold_right\n     List.fold_left\n     List.filter\n     List.length\n     List.app\n     List.seq\n     List.nth_error\n     List.map\n     List.concat\n     List.existsb\n     List.nth\n     Datatypes.length\n     Ascii.eqb\n     String.eqb\n     Bool.eqb\n     Datatypes.negb\n     Datatypes.andb\n     Datatypes.orb\n     Datatypes.fst\n     Datatypes.snd\n     String.append\n     EclecticLib.nth_Fin\n  : KamiDb.\n(* TODO\n   + PUAR: Linux/Certikos\n *)\n\n", "meta": {"author": "sifive", "repo": "Kami", "sha": "ffb77238f27b603dbd42d2622ba911740bf5eadf", "save_path": "github-repos/coq/sifive-Kami", "path": "github-repos/coq/sifive-Kami/Kami-ffb77238f27b603dbd42d2622ba911740bf5eadf/Syntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982315512488, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.27369775525483736}}
{"text": "Set Warnings \"-notation-overridden\".\n\nRequire Import Category.Lib.\nRequire Export Category.Structure.Closed.\nRequire Export Category.Instance.Fun.\nRequire Export Category.Instance.Cat.\nRequire Export Category.Instance.Cat.Cartesian.\n\nGeneralizable All Variables.\nSet Primitive Projections.\nSet Universe Polymorphism.\n\nDefinition pairing {A B : Type} (p : A * B) : p = (fst p, snd p) :=\n  match p with (x, y) => eq_refl end.\n\nProgram Instance Cat_Closed : @Closed Cat Cat_Cartesian := {\n  exponent_obj := @Fun;         (* the internal hom is a functor category *)\n  exp_iso := fun A B C =>\n    {| to :=\n       {| morphism := fun F : A × B ⟶ C =>\n          {| fobj := fun x : A =>\n             {| fobj := fun y : B => F (x, y)\n              ; fmap := fun J K (f : J ~{B}~> K) =>\n                  fmap[F] (@id A x, f) |}\n           ; fmap := fun J K (f : J ~{A}~> K) =>\n             {| transform := fun L : B =>\n                  fmap[F] (f, @id B L) |} |} |}\n     ; from :=\n       {| morphism := fun F : A ⟶ [B, C] =>\n          {| fobj := fun x : A × B => F (fst x) (snd x)\n           ; fmap := fun J K (f : J ~{A × B}~> K) =>\n               fmap (snd f) ∘ transform[fmap[F] (fst f)] _ |} |} |}\n}.\nNext Obligation.\n  proper; apply fmap_respects.\n  split; simpl; cat.\nQed.\nNext Obligation.\n  rewrite <- fmap_comp; simpl.\n  apply fmap_respects; split; simpl; cat.\nQed.\nNext Obligation.\n  rewrite <- !fmap_comp.\n  apply fmap_respects; simpl; cat; simpl; cat.\nQed.\nNext Obligation.\n  rewrite <- !fmap_comp.\n  apply fmap_respects; simpl; cat.\nQed.\nNext Obligation.\n  proper; simpl; cat;\n  rewrites; reflexivity.\nQed.\nNext Obligation.\n  simpl; intros.\n  rewrite <- fmap_comp.\n  apply fmap_respects; cat; simpl; cat.\nQed.\nNext Obligation.\n  proper.\n  - isomorphism; simpl.\n    + transform; simpl; intros.\n      * apply x0.\n      * simpl.\n        rewrite e.\n        rewrite !comp_assoc.\n        rewrite iso_to_from; cat.\n      * simpl.\n        rewrite e.\n        rewrite !comp_assoc.\n        rewrite iso_to_from; cat.\n    + transform; simpl; intros.\n      * apply x0.\n      * simpl.\n        rewrite e.\n        rewrite <- !comp_assoc.\n        rewrite iso_to_from; cat.\n      * simpl.\n        rewrite e.\n        rewrite <- !comp_assoc.\n        rewrite iso_to_from; cat.\n    + simpl; cat; apply iso_to_from.\n    + simpl; cat; apply iso_from_to.\n  - apply e.\nQed.\nNext Obligation.\n  proper.\n  rewrite H.\n  comp_left.\n  destruct F; simpl in *.\n  apply fmap_respects.\n  assumption.\nQed.\nNext Obligation.\n  simpl; cat.\n  destruct F; simpl in *.\n  rewrite fmap_id; cat.\nQed.\nNext Obligation.\n  symmetry.\n  rewrite naturality.\n  rewrite <- !comp_assoc.\n  rewrite (comp_assoc (fmap[F o1] h2)).\n  rewrite <- fmap_comp.\n  rewrite naturality.\n  rewrite comp_assoc.\n  destruct F; simpl in *.\n  rewrite <- !fmap_comp.\n  rewrite naturality.\n  reflexivity.\nQed.\nNext Obligation.\n  proper; simpl.\n  - isomorphism.\n    + apply x0.\n    + apply (from (x0 _)).\n    + srewrite (iso_to_from (x0 x1)); cat.\n    + srewrite (iso_from_to (x0 x1)); cat.\n  - simpl.\n    rewrite e.\n    do 2 comp_right.\n    apply naturality.\nQed.\nNext Obligation.\n  constructive; simpl.\n  - transform; simpl; intros.\n    + exact id.\n    + destruct x; simpl in *.\n      rewrite fmap_id; cat.\n    + destruct x; simpl in *.\n      rewrite fmap_id; cat.\n  - transform; simpl; intros.\n    + exact id.\n    + destruct x; simpl in *.\n      rewrite fmap_id; cat.\n    + destruct x; simpl in *.\n      rewrite fmap_id; cat.\n  - simpl; cat.\n  - destruct x; simpl in *.\n    rewrite fmap_id; cat.\n  - destruct x; simpl in *; cat.\nQed.\nNext Obligation.\n  constructive; simpl.\n  - rewrite <- pairing.\n    exact id.\n  - rewrite <- pairing.\n    exact id.\n  - destruct x0; simpl; cat.\n  - destruct x0; simpl; cat.\n  - destruct f; simpl; cat.\n    rewrite <- fmap_comp.\n    apply fmap_respects; simpl; cat.\nQed.\nNext Obligation.\n  constructive; simpl.\n  - rewrite <- pairing.\n    exact id.\n  - rewrite <- pairing.\n    exact id.\n  - destruct x; simpl; cat.\n  - destruct x; simpl; cat.\n  - destruct f; simpl; cat.\n    rewrite <- fmap_comp.\n    apply fmap_respects; simpl; cat.\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/category-theory/Instance/Cat/Closed.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982315512488, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2736977552548373}}
{"text": "Require Import Blech.Defaults.\n\nRequire Import Coq.Setoids.Setoid.\nRequire Import Coq.Classes.SetoidClass.\nRequire Import Coq.Bool.Bool.\n\nRequire Import Blech.Bishop.\nRequire Import Blech.Category.\nRequire Import Blech.Groupoid.\nRequire Import Blech.Groupoid.Core.\nRequire Import Blech.Category.Trv.\nRequire Import Blech.Functor.\nRequire Import Blech.Bicategory.\n\nRequire Blech.Reflect.\n\nImport BishopNotations.\nImport CategoryNotations.\nImport GroupoidNotations.\n\nOpen Scope bishop_scope.\nOpen Scope category_scope.\n\n#[local]\nObligation Tactic := Reflect.category_simpl.\n\n#[program]\nDefinition UndirectedInterval: Bicategory := {|\n  Obj := bool ;\n  Mor _ _ := Trv ;\n\n  id _ := I ;\n  compose _ _ _ :=\n    {|\n      op _ := I ;\n      map _ _ _ := I ;\n    |} ;\n|}.\n\nNext Obligation.\nProof.\n  exists.\n  all: cbn in *.\n  all: intros.\n  - apply I.\n  - apply I.\n  - intros ? ? ?.\n    apply I.\nDefined.\n\nNext Obligation.\nProof.\n  destruct F.\n  apply (Category.id (I: Core Trv)).\nDefined.\n\nNext Obligation.\nProof.\n  destruct F.\n  apply (Category.id (I: Core Trv)).\nDefined.\n\nNext Obligation.\nProof.\n  apply (Category.id (I: Core Trv)).\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/Bicategory/UndirectedInterval.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521102, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2736977495091383}}
{"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 Language.\nFrom PromisingLib Require Import Loc.\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 Pred.\nRequire Import Trace.\n\nRequire Import MemoryMerge.\nRequire Import ReorderCancel.\nRequire Import MemoryProps.\nRequire Import OrderedTimes.\nRequire Import Cover.\nRequire Import Mapping.\n\nSet Implicit Arguments.\n\n\n\nLemma promise_not_cancel_covered_increase prom0 prom1 mem0 mem1\n      loc from to msg kind\n      (PROMISE: Memory.promise prom0 mem0 loc from to msg prom1 mem1 kind)\n      (NOTCANCEL: kind <> Memory.op_kind_cancel)\n      loc0 ts0\n      (COVERED: covered loc0 ts0 mem0)\n  :\n    covered loc0 ts0 mem1.\nProof.\n  inv PROMISE.\n  { erewrite (@add_covered mem1 mem0); eauto. }\n  { erewrite (@split_covered mem1 mem0); eauto. }\n  { erewrite (@lower_covered mem1 mem0); eauto. }\n  { ss. }\nQed.\n\nLemma step_not_cancel_covered_increase lang (th0 th1: Thread.t lang) pf e\n      (STEP: Thread.step pf e th0 th1)\n      (NOTCANCEL: ~ ThreadEvent.is_cancel e)\n      loc0 ts0\n      (COVERED: covered loc0 ts0 (Thread.memory th0))\n  :\n    covered loc0 ts0 (Thread.memory th1).\nProof.\n  inv STEP.\n  { inv STEP0. inv LOCAL. ss.\n    eapply promise_not_cancel_covered_increase; eauto. destruct kind; ss.\n    des_ifs. inv PROMISE; ss.\n  }\n  { inv STEP0. inv LOCAL; auto.\n    { inv LOCAL0. inv WRITE. eapply promise_not_cancel_covered_increase; eauto.\n      destruct kind; ss. inv PROMISE; ss. }\n    { inv LOCAL2. inv WRITE. eapply promise_not_cancel_covered_increase; eauto.\n      destruct kind; ss. inv PROMISE; ss. }\n  }\nQed.\n\nLemma traced_steps_not_cancel_covered_increase lang (th0 th1: Thread.t lang) tr\n      (STEPS: Trace.steps tr th0 th1)\n      (EVENTS: List.Forall (fun em => <<SAT: (fun e => ~ ThreadEvent.is_cancel e) (snd em)>>) tr)\n      loc0 ts0\n      (COVERED: covered loc0 ts0 (Thread.memory th0))\n  :\n    covered loc0 ts0 (Thread.memory th1).\nProof.\n  ginduction STEPS; auto. i. clarify. inv EVENTS.\n  eapply step_not_cancel_covered_increase in STEP; eauto.\nQed.\n\n\n\nSection UNATTACHABLE.\n\n  Inductive unattachable (mem: Memory.t) (loc: Loc.t) (ts: Time.t): Prop :=\n  | unattachable_intro\n      from to msg\n      (MSG: Memory.get loc to mem = Some (from, msg))\n      (FROM: Time.le from ts)\n      (TO: Time.lt ts to)\n  .\n\n  Lemma lower_unattachable mem1 mem0 loc from to msg1 msg2\n        (LOWER: Memory.lower mem0 loc from to msg1 msg2 mem1)\n    :\n      unattachable mem1 = unattachable mem0.\n  Proof.\n    extensionality loc0. extensionality ts0.\n    exploit Memory.lower_get0; eauto. i. des.\n    apply Coq.Logic.PropExtensionality.propositional_extensionality. split; i.\n    { inv H. erewrite Memory.lower_o in MSG; eauto. des_ifs.\n      { ss. des; clarify. econs; eauto. }\n      { econs; eauto. }\n    }\n    { inv H. eapply Memory.lower_get1 in MSG; eauto. des. econs; eauto. }\n  Qed.\n\n  Lemma split_unattachable mem1 mem0 loc ts1 ts2 ts3 msg2 msg3\n        (SPLIT: Memory.split mem0 loc ts1 ts2 ts3 msg2 msg3 mem1)\n    :\n      unattachable mem1 = unattachable mem0.\n  Proof.\n    extensionality loc0. extensionality ts0.\n    exploit split_succeed_wf; eauto. i. des.\n    exploit Memory.split_get0; eauto. i. des.\n    apply Coq.Logic.PropExtensionality.propositional_extensionality. split; i.\n    { inv H. erewrite Memory.split_o in MSG; eauto. des_ifs.\n      { ss. des; clarify. econs; eauto. }\n      { ss. des; clarify. econs; eauto. etrans; eauto. left. auto. }\n      { econs; eauto. }\n    }\n    { inv H. generalize (Memory.split_o loc0 to SPLIT). intros MSG0. des_ifs.\n      { ss. des; clarify. }\n      { ss. des; clarify.\n        destruct (Time.le_lt_dec ts2 ts0).\n        { econs; try apply MSG0; eauto. }\n        { econs; try apply GET1; eauto. }\n      }\n      { erewrite MSG in *. clarify. econs; eauto. }\n    }\n  Qed.\n\n  Lemma add_unattachable mem1 mem0 loc from to msg\n        (ADD: Memory.add mem0 loc from to msg mem1)\n    :\n      unattachable mem1 =\n      (fun loc0 ts0 =>\n         unattachable mem0 loc0 ts0 \\/ (loc0 = loc /\\ Time.le from ts0 /\\ Time.lt ts0 to)).\n  Proof.\n    extensionality loc0. extensionality ts0.\n    exploit add_succeed_wf; eauto. i.  des.\n    exploit Memory.add_get0; eauto. i. des.\n    apply Coq.Logic.PropExtensionality.propositional_extensionality. split; i.\n    { inv H. erewrite Memory.add_o in MSG; eauto. des_ifs.\n      { ss. des; clarify. right. splits; auto. }\n      { left. econs; eauto. }\n    }\n    { des; subst.\n      { inv H. econs; eauto. eapply Memory.add_get1; eauto. }\n      { econs; eauto. }\n    }\n  Qed.\n\nEnd UNATTACHABLE.\n\n\n\nSection LIFT.\n\n  Lemma memory_remove_le_preserve mem0 mem0' mem1 mem1' loc from to msg\n        (REMOVE0: Memory.remove mem0 loc from to msg mem0')\n        (REMOVE1: Memory.remove mem1 loc from to msg mem1')\n        (MLE: Memory.le mem0 mem1)\n  :\n    Memory.le mem0' mem1'.\n  Proof.\n    ii. erewrite Memory.remove_o; eauto.\n    erewrite (@Memory.remove_o mem0' mem0) in LHS; eauto. des_ifs.\n    eapply MLE; eauto.\n  Qed.\n\n  Lemma memory_add_le_preserve mem0 mem0' mem1 mem1' loc from to msg\n        (ADD0: Memory.add mem0 loc from to msg mem0')\n        (ADD1: Memory.add mem1 loc from to msg mem1')\n        (MLE: Memory.le mem0 mem1)\n    :\n      Memory.le mem0' mem1'.\n  Proof.\n    ii. erewrite Memory.add_o; eauto.\n    erewrite (@Memory.add_o mem0' mem0) in LHS; eauto. des_ifs.\n    eapply MLE; eauto.\n  Qed.\n\n  Lemma memory_split_le_preserve mem0 mem0' mem1 mem1' loc ts1 ts2 ts3 msg2 msg3\n        (SPLIT0: Memory.split mem0 loc ts1 ts2 ts3 msg2 msg3 mem0')\n        (SPLIT1: Memory.split mem1 loc ts1 ts2 ts3 msg2 msg3 mem1')\n        (MLE: Memory.le mem0 mem1)\n    :\n      Memory.le mem0' mem1'.\n  Proof.\n    ii. erewrite Memory.split_o; eauto.\n    erewrite (@Memory.split_o mem0' mem0) in LHS; eauto. des_ifs.\n    eapply MLE; eauto.\n  Qed.\n\n  Lemma memory_lower_le_preserve mem0 mem0' mem1 mem1' loc from to msg1 msg2\n        (LOWER0: Memory.lower mem0 loc from to msg1 msg2 mem0')\n        (LOWER1: Memory.lower mem1 loc from to msg1 msg2 mem1')\n        (MLE: Memory.le mem0 mem1)\n    :\n      Memory.le mem0' mem1'.\n  Proof.\n    ii. erewrite Memory.lower_o; eauto.\n    erewrite (@Memory.lower_o mem0' mem0) in LHS; eauto. des_ifs.\n    eapply MLE; eauto.\n  Qed.\n\n  Lemma step_lifting_promise prom0 prom1 mem0 mem1 cap0\n        loc from to msg kind\n        (spaces lefts: Loc.t -> Time.t -> Prop)\n        (PROMISE: Memory.promise prom0 mem0 loc from to msg prom1 mem1 kind)\n        (WRITENOTIN: forall ts (ITV: Interval.mem (from, to) ts), ~ spaces loc ts)\n        (WRITENOTTO: ~ lefts loc to)\n        (SOUND: Memory.le mem0 cap0)\n        (SPACES:\n           forall loc ts (COV: covered loc ts cap0),\n             <<COV: covered loc ts mem0>> \\/ <<SPACE: spaces loc ts>>)\n        (LEFTS:\n           forall loc ts (UNATTACHABLE: unattachable cap0 loc ts),\n             <<COV: unattachable mem0 loc ts>> \\/ <<LEFT: lefts loc ts>>)\n        (MEM0: Memory.closed mem0)\n        (PROM0: Memory.le prom0 mem0)\n        (PROM1: Memory.le prom0 cap0)\n        (NOTCANCEL: kind <> Memory.op_kind_cancel)\n    :\n      exists cap1,\n        (<<STEP: Memory.promise prom0 cap0 loc from to msg prom1 cap1 kind>>) /\\\n        (<<SOUND: Memory.le mem1 cap1>>) /\\\n        (<<SPACES:\n           forall loc ts (COV: covered loc ts cap1),\n             <<COV: covered loc ts mem1>> \\/ spaces loc ts>>) /\\\n        (<<LEFTS:\n           forall loc ts (UNATTACHABLE: unattachable cap1 loc ts),\n             <<COV: unattachable mem1 loc ts>> \\/ lefts loc ts>>).\n  Proof.\n    inv PROMISE.\n    { exploit add_succeed_wf; try apply MEM; eauto. i. des.\n      exploit (@Memory.add_exists cap0 loc from to msg); eauto.\n      { ii. exploit SPACES.\n        { econs; eauto. }\n        i. des.\n        { inv COV. eapply DISJOINT; eauto. }\n        { eapply WRITENOTIN; eauto. }\n      }\n      i. des. esplits.\n      { econs; eauto. i. subst. exploit LEFTS.\n        { econs; eauto.\n          { refl. }\n          { apply memory_get_ts_strong in GET. des; auto.\n            subst. eapply TimeFacts.le_lt_lt; eauto. eapply Time.bot_spec. }\n        }\n        i. des; ss.\n        { inv COV. destruct FROM.\n          { eapply DISJOINT; eauto.\n            { instantiate (1:=to). econs; ss. refl. }\n            { econs; ss. left. eauto. }\n          }\n          { inv H. eapply ATTACH; eauto. }\n        }\n      }\n      { eapply memory_add_le_preserve; eauto. }\n      { i. erewrite add_covered in COV; eauto.\n        erewrite (@add_covered mem1 mem0); eauto. des; eauto.\n        eapply SPACES in COV. des; auto. }\n      { i. erewrite add_unattachable in UNATTACHABLE; eauto.\n        erewrite (@add_unattachable mem1 mem0); eauto. des; auto.\n        eapply LEFTS in UNATTACHABLE. des; auto. }\n    }\n    { des. subst.\n      exploit (@Memory.split_exists_le prom0 cap0); eauto. i. des. esplits.\n      { econs; eauto. }\n      { ii. erewrite Memory.split_o in LHS; eauto.\n        erewrite (@Memory.split_o mem2 cap0); eauto. des_ifs.\n        eapply SOUND; eauto. }\n      { i. erewrite (@split_covered mem2 cap0) in COV; eauto.\n        erewrite (@split_covered mem1 mem0); eauto. }\n      { i. erewrite (@split_unattachable mem2 cap0) in UNATTACHABLE; eauto.\n        erewrite (@split_unattachable mem1 mem0); eauto. }\n    }\n    { des. subst.\n      exploit (@Memory.lower_exists_le prom0 cap0); eauto. i. des. esplits.\n      { econs; eauto. }\n      { ii. erewrite Memory.lower_o in LHS; eauto.\n        erewrite (@Memory.lower_o mem2 cap0); eauto. des_ifs.\n        eapply SOUND; eauto. }\n      { i. erewrite (@lower_covered mem2 cap0) in COV; eauto.\n        erewrite (@lower_covered mem1 mem0); eauto. }\n      { i. erewrite (@lower_unattachable mem2 cap0) in UNATTACHABLE; eauto.\n        erewrite (@lower_unattachable mem1 mem0); eauto. }\n    }\n    { ss. }\n  Qed.\n\n  Lemma step_lifting lang st0 st1 lc0 lc1 sc0 sc1 mem0 mem1 cap0 pf e\n        (spaces lefts: Loc.t -> Time.t -> Prop)\n        (STEP: Thread.step pf e (Thread.mk lang st0 lc0 sc0 mem0) (Thread.mk _ st1 lc1 sc1 mem1))\n        (WRITENOTIN: write_not_in spaces e)\n        (WRITENOTTO: write_not_to lefts e)\n        (NOTCANCEL: ~ ThreadEvent.is_cancel e)\n        (SOUND: Memory.le mem0 cap0)\n        (SPACES:\n           forall loc ts (COV: covered loc ts cap0),\n             <<COV: covered loc ts mem0>> \\/ <<SPACE: spaces loc ts>>)\n        (LEFTS:\n           forall loc ts (UNATACHABLE: unattachable cap0 loc ts),\n             <<COV: unattachable mem0 loc ts>> \\/ <<LEFT: lefts loc ts>>)\n       (MEM0: Memory.closed mem0)\n        (LOCAL0: Local.wf lc0 mem0)\n        (SC0: Memory.closed_timemap sc0 mem0)\n    :\n      exists cap1,\n        (<<STEP: Thread.step pf e (Thread.mk _ st0 lc0 sc0 cap0) (Thread.mk _ st1 lc1 sc1 cap1)>>) /\\\n        (<<SOUND: Memory.le mem1 cap1>>) /\\\n        (<<SPACES:\n           forall loc ts (COV: covered loc ts cap1),\n             <<COV: covered loc ts mem1>> \\/ spaces loc ts>>) /\\\n        (<<UNATTACHABLE:\n           forall loc ts (COV: unattachable cap1 loc ts),\n             <<COV: unattachable mem1 loc ts>> \\/ lefts loc ts>>).\n\n  Proof.\n    inv STEP.\n    { inv STEP0. inv LOCAL. ss.\n      destruct (Memory.op_kind_is_cancel kind) eqn:KIND; ss.\n      { destruct kind; ss. des_ifs. inv PROMISE; ss. }\n      exploit step_lifting_promise; eauto.\n      { eapply LOCAL0. }\n      { transitivity mem0; eauto. eapply LOCAL0. }\n      { destruct kind; ss. }\n      i. des. esplits; eauto. econs. econs.\n      { econs; eauto. eapply memory_concrete_le_closed_msg; eauto. }\n      { ss. destruct kind; ss. }\n    }\n    { inv STEP0. inv LOCAL.\n      { esplits; eauto. }\n      { inv LOCAL1. eapply SOUND in GET. esplits; eauto. }\n      { inv LOCAL1. inv WRITE. exploit step_lifting_promise; eauto.\n        { eapply LOCAL0. }\n        { transitivity mem0; eauto. eapply LOCAL0. }\n        { destruct kind; ss. inv PROMISE; ss. }\n        i. des. esplits; eauto. econs 2; eauto.\n      }\n      { inv LOCAL1. eapply SOUND in GET. inv LOCAL2. inv WRITE.\n        exploit step_lifting_promise; eauto.\n        { eapply LOCAL0. }\n        { transitivity mem0; eauto. eapply LOCAL0. }\n        { destruct kind; ss. inv PROMISE; ss. }\n        i. des. esplits; eauto. econs 2; eauto. econs; eauto. }\n      { esplits; eauto. }\n      { esplits; eauto. }\n      { esplits; eauto. }\n    }\n  Qed.\n\n  Lemma traced_step_lifting lang st0 st1 lc0 lc1 sc0 sc1 mem0 mem1 cap0 tr\n        (spaces lefts: Loc.t -> Time.t -> Prop)\n        (STEPS: Trace.steps tr (Thread.mk lang st0 lc0 sc0 mem0) (Thread.mk _ st1 lc1 sc1 mem1))\n        (EVENTS: List.Forall (fun em => <<SAT: (write_not_in spaces /1\\ write_not_to lefts /1\\ (fun e => ~ ThreadEvent.is_cancel e)) (snd em)>>) tr)\n        (SOUND: Memory.le mem0 cap0)\n        (SPACES:\n           forall loc ts (COV: covered loc ts cap0),\n             <<COV: covered loc ts mem0>> \\/ <<SPACE: spaces loc ts>>)\n        (LEFTS:\n           forall loc ts (UNATACHABLE: unattachable cap0 loc ts),\n             <<COV: unattachable mem0 loc ts>> \\/ <<LEFT: lefts loc ts>>)\n        (MEM0: Memory.closed mem0)\n        (LOCAL0: Local.wf lc0 mem0)\n        (SC0: Memory.closed_timemap sc0 mem0)\n    :\n      exists cap1,\n        (<<STEPS: Trace.steps tr (Thread.mk _ st0 lc0 sc0 cap0) (Thread.mk _ st1 lc1 sc1 cap1)>>) /\\\n        (<<SOUND: Memory.le mem1 cap1>>) /\\\n        (<<SPACES:\n           forall loc ts (COV: covered loc ts cap1),\n             <<COV: covered loc ts mem1>> \\/ spaces loc ts>>) /\\\n        (<<LEFTS:\n           forall loc ts (UNATACHABLE: unattachable cap1 loc ts),\n             <<COV: unattachable mem1 loc ts>> \\/ lefts loc ts>>).\n  Proof.\n    remember (Thread.mk lang st0 lc0 sc0 mem0).\n    remember (Thread.mk lang st1 lc1 sc1 mem1). ginduction STEPS.\n    { i. clarify. esplits; eauto. }\n    { i. clarify. inv EVENTS. ss. des.\n      exploit Thread.step_future; eauto. i. des.\n      destruct th1. ss. exploit step_lifting; eauto. i. des.\n      exploit IHSTEPS; eauto. i. des. exists cap2. splits; auto. econs; eauto.\n    }\n  Qed.\n\nEnd LIFT.\n\n\nFixpoint intervals_sum (l: list (Loc.t * Interval.t)):\n  Loc.t -> Time.t -> Prop :=\n  match l with\n  | [] => bot2\n  | (loc, (from, to))::tl =>\n    fun loc0 ts0 =>\n      (loc0 = loc /\\ Interval.mem (from, to) ts0) \\/\n      intervals_sum tl loc0 ts0\n  end.\n\nFixpoint intervals_sum_left (l: list (Loc.t * Interval.t)):\n  Loc.t -> Time.t -> Prop :=\n  match l with\n  | [] => bot2\n  | (loc, (from, to))::tl =>\n    fun loc0 ts0 =>\n      (loc0 = loc /\\ Time.le from ts0 /\\ Time.lt ts0 to) \\/\n      intervals_sum_left tl loc0 ts0\n  end.\n\nLemma intervals_sum_interval l\n      loc ts\n  :\n    intervals_sum l loc ts <->\n    exists from to,\n      (<<IN: List.In (loc, (from, to)) l>>) /\\ (<<ITV: Interval.mem (from, to) ts>>).\nProof.\n  ginduction l; ss.\n  { i; split; i; ss. des. ss. }\n  { i; split; i; ss.\n    { destruct a. destruct t0. des; clarify.\n      { esplits; eauto. }\n      { eapply IHl in H. des. esplits; eauto. }\n    }\n    { destruct a. destruct t0. des; clarify; eauto. right.\n      eapply IHl. eauto. }\n  }\nQed.\n\nLemma intervals_sum_left_interval l\n      loc ts\n  :\n    intervals_sum_left l loc ts <->\n    exists from to,\n      (<<IN: List.In (loc, (from, to)) l>>) /\\ (<<FROM: Time.le from ts>>) /\\ (<<TO: Time.lt ts to>>).\nProof.\n  ginduction l; ss.\n  { i; split; i; ss. des. ss. }\n  { i; split; i; ss.\n    { destruct a. destruct t0. des; clarify.\n      { esplits; eauto. }\n      { eapply IHl in H. des. esplits; eauto. }\n    }\n    { destruct a. destruct t0. des; clarify; eauto. right.\n      eapply IHl. eauto. }\n  }\nQed.\n\n\nLemma promise_needed_spaces prom0 prom1 mem0 mem1\n      loc from to msg kind\n      (PROMISE: Memory.promise prom0 mem0 loc from to msg prom1 mem1 kind)\n      (WF: kind <> Memory.op_kind_cancel)\n  :\n    ((<<ALREADY: forall ts (ITV: Interval.mem (from, to) ts), covered loc ts mem0>>) /\\\n     (<<COVERED: forall loc ts, covered loc ts mem1 <-> covered loc ts mem0>>))\n    \\/\n    ((<<NEW: forall ts (ITV: Interval.mem (from, to) ts), ~ covered loc ts mem0>>) /\\\n     (<<COVERED: forall loc0 ts0,\n         covered loc0 ts0 mem1 <-> covered loc0 ts0 mem0 \\/ (loc0 = loc /\\ Interval.mem (from, to) ts0)>>) /\\\n     (<<WF: Time.lt from to>>))\n.\nProof.\n  inv PROMISE.\n  { right. exploit add_succeed_wf; try apply MEM. i. des. splits; auto.\n    { ii. inv H. eapply DISJOINT; eauto. }\n    { i. erewrite (@add_covered mem1); eauto. }\n  }\n  { left. exploit split_succeed_wf; try apply MEM. i. des. splits; auto.\n    { ii. econs; eauto. eapply Interval.le_mem; eauto. econs; ss.\n      { refl. }\n      { left. auto. }\n    }\n    { i. eapply split_covered; eauto. }\n  }\n  { left. exploit lower_succeed_wf; try apply MEM. i. des. splits; auto.\n    { ii. econs; eauto. }\n    { i. eapply lower_covered; eauto. }\n  }\n  { ss. }\nQed.\n\nLemma step_needed_spaces lang (th0 th1: Thread.t lang) pf e\n      (times: Loc.t -> Time.t -> Prop)\n      (STEP: Thread.step pf e th0 th1)\n      (NOTCANCEL: ~ ThreadEvent.is_cancel e)\n      (WFTIME: wf_time_evt times e)\n  :\n    ((<<ALREADY: write_not_in (fun loc0 ts0 => ~ covered loc0 ts0 (Thread.memory th0)) e>>) /\\\n     (<<COVERED: forall loc ts, covered loc ts (Thread.memory th1) <-> covered loc ts (Thread.memory th0)>>))\n    \\/\n    exists loc from to,\n      (<<NEW: forall ts (ITV: Interval.mem (from, to) ts), ~ covered loc ts (Thread.memory th0)>>) /\\\n      (<<COVERED: forall loc0 ts0,\n          covered loc0 ts0 (Thread.memory th1) <-> covered loc0 ts0 (Thread.memory th0) \\/ (loc0 = loc /\\ Interval.mem (from, to) ts0)>>) /\\\n      (<<WF: Time.lt from to>>) /\\\n      (<<TIMES: times loc from /\\ times loc to>>) /\\\n      (<<EVENT: write_not_in (fun loc0 ts0 => ~ (loc0 = loc /\\ Interval.mem (from, to) ts0)) e>>).\nProof.\n  inv STEP.\n  { inv STEP0. inv LOCAL. ss.\n    destruct (Memory.op_kind_is_cancel kind) eqn:KIND.\n    { destruct kind; ss. des_ifs. inv PROMISE; ss. }\n    exploit promise_needed_spaces; eauto.\n    { destruct kind; ss. }\n    i. des.\n    { left. splits; auto. }\n    { right. esplits; eauto. }\n  }\n  { inv STEP0. inv LOCAL; try by (splits; eauto); ss.\n    { ss. inv LOCAL0. inv WRITE.\n      exploit promise_needed_spaces; eauto.\n      { destruct kind; ss. inv PROMISE; ss. }\n      i. des.\n      { left. esplits; eauto. }\n      { right. esplits; eauto. }\n    }\n    { ss. inv LOCAL2. inv WRITE.\n      exploit promise_needed_spaces; eauto.\n      { destruct kind; ss. inv PROMISE; ss. }\n      i. des.\n      { left. esplits; eauto. }\n      { right. esplits; eauto. }\n    }\n  }\nQed.\n\n\nInductive reservations_added:\n  forall (l: list (Loc.t * Interval.t)) (mem0 mem1: Memory.t), Prop :=\n| reservations_added_base\n    mem0\n  :\n    reservations_added [] mem0 mem0\n| reservations_added_cons\n    mem0 mem1 mem2 loc from to tl\n    (ADD: Memory.add mem0 loc from to Message.reserve mem1)\n    (TL: reservations_added tl mem1 mem2)\n    (WF: Time.lt from to)\n  :\n    reservations_added ((loc, (from, to))::tl) mem0 mem2\n.\n\nLemma reservations_added_trans l0 l1 mem0 mem1 mem2\n      (ADDED0: reservations_added l0 mem0 mem1)\n      (ADDED1: reservations_added l1 mem1 mem2)\n  :\n    reservations_added (l0 ++ l1) mem0 mem2.\nProof.\n  ginduction l0; eauto.\n  { i. inv ADDED0. ss. }\n  { i. inv ADDED0. exploit IHl0; eauto. i. econs; eauto. }\nQed.\n\n\nLemma reservations_added_cancel\n      loc from to mem0 mem1 mem2 tl\n      (CANCEL: Memory.remove mem1 loc from to Message.reserve mem0)\n      (TL: reservations_added tl mem1 mem2)\n      (WF: Time.lt from to)\n  :\n    reservations_added ((loc, (from, to))::tl) mem0 mem2.\nProof.\n  econs; eauto.\n  exploit (@Memory.add_exists mem0 loc from to Message.reserve); eauto.\n  { i. erewrite Memory.remove_o in GET2; eauto. des_ifs.\n    exploit Memory.get_disjoint.\n    { eapply GET2. }\n    { eapply Memory.remove_get0; eauto. }\n    i. ss. des; clarify. symmetry. auto.\n  }\n  { econs. }\n  i. des. replace mem1 with mem3; auto. eapply Memory.ext.\n  i. erewrite (@Memory.add_o mem3 mem0); eauto.\n  erewrite (@Memory.remove_o mem0 mem1); eauto. des_ifs.\n  ss. des; clarify. symmetry. eapply Memory.remove_get0; eauto.\nQed.\n\nInductive disjoint_intervals\n  :\n    forall (l: list (Loc.t * Interval.t)), Prop :=\n| disjoint_base\n  :\n    disjoint_intervals []\n| disjoint_intervals_cons\n    loc from to tl\n    (TL: disjoint_intervals tl)\n    (NITV: forall ts (ITV: Interval.mem (from, to) ts),\n        ~ intervals_sum tl loc ts)\n    (TS: Time.lt from to)\n  :\n    disjoint_intervals ((loc, (from, to)) :: tl)\n.\nHint Constructors disjoint_intervals.\n\n\n\n\nLemma traced_steps_needed_spaces lang (th0 th1: Thread.t lang) tr\n      (times: Loc.t -> Time.t -> Prop)\n      (STEP: Trace.steps tr th0 th1)\n      (EVENTS: List.Forall (fun em => <<SAT: ((fun e => ~ ThreadEvent.is_cancel e) /1\\ wf_time_evt times) (snd em)>>) tr)\n  :\n    exists l,\n      (<<WRITENOTIN:\n         List.Forall (fun em => <<SAT: write_not_in (fun loc ts => ~ (covered loc ts (Thread.memory th0) \\/ intervals_sum l loc ts)) (snd em)>>) tr>>) /\\\n      (<<DISJOINT: disjoint_intervals l>>) /\\\n      (<<NITV: forall loc ts (ITV: intervals_sum l loc ts), ~ covered loc ts (Thread.memory th0)>>) /\\\n      (<<COVERED: forall loc ts,\n          covered loc ts (Thread.memory th1) <-> covered loc ts (Thread.memory th0) \\/ intervals_sum l loc ts>>) /\\\n      (<<TIMES: List.Forall (fun locitv =>\n                               times (fst locitv) (fst (snd locitv)) /\\\n                               times (fst locitv) (snd (snd locitv))) l>>)\n.\nProof.\n  ginduction STEP; i.\n  { exists []. splits; auto. i. ss. split; auto. i. des; ss. }\n  { subst. inv EVENTS. des. exploit IHSTEP; eauto. i. des.\n    exploit step_needed_spaces; eauto. i. des.\n    { exists l. splits; auto.\n      { econs; eauto.\n        { eapply write_not_in_mon; eauto. i. ss.\n          eapply not_or_and in PR. des. auto. }\n        { eapply List.Forall_impl; eauto. i. ss.\n          eapply write_not_in_mon; eauto. i. ss.\n          erewrite COVERED0; eauto. }\n      }\n      { i. erewrite <- COVERED0; eauto. }\n      { i. erewrite <- COVERED0. eauto. }\n    }\n    { exists ((loc, (from, to)) :: l). splits.\n      { econs.\n        { eapply write_not_in_mon; eauto. ss. i.\n          ii. des. eapply PR. eauto. }\n        { eapply List.Forall_impl; try apply WRITENOTIN; eauto. i. ss.\n          eapply write_not_in_mon; eauto. i. ss.\n          ii. eapply PR. des; auto. eapply COVERED0 in H3. des; auto. }\n      }\n      { econs; eauto. ii. eapply NITV; eauto. eapply COVERED0. auto. }\n      { i. ss. des; clarify; eauto.\n        eapply NITV in ITV. ii. eapply ITV. eapply COVERED0. auto. }\n      { ii. erewrite COVERED. erewrite COVERED0. ss. split; i; des; auto. }\n      { econs; ss. }\n    }\n  }\nQed.\n\nLemma reserve_empty_intervals times lang (th: Thread.t lang) l\n      (DISJOINT: disjoint_intervals l)\n      (NITV: forall loc ts (ITV: intervals_sum l loc ts),\n          ~ covered loc ts (Thread.memory th))\n      (MLE: Memory.le (Local.promises (Thread.local th)) (Thread.memory th))\n      (TIMES: List.Forall (fun locitv =>\n                             times (fst locitv) (fst (snd locitv)) /\\\n                             times (fst locitv) (snd (snd locitv))) l)\n  :\n    exists tr prom' mem',\n      (<<STEPS: Trace.steps tr th (Thread.mk _ (Thread.state th) (Local.mk (Local.tview (Thread.local th)) prom') (Thread.sc th) mem')>>) /\\\n      (<<RESERVETRACE: List.Forall (fun em => <<SAT: (ThreadEvent.is_reserve /1\\ wf_time_evt times) (snd em)>>) tr>>) /\\\n      (<<ADDEDPROM: reservations_added l (Local.promises (Thread.local th)) prom'>>) /\\\n      (<<ADDEDMEM: reservations_added l (Thread.memory th) mem'>>)\n.\nProof.\n  ginduction l; i.\n  { destruct th. destruct local. ss. exists []. esplits; eauto.\n    { econs. }\n    { econs. }\n  }\n  { inv DISJOINT. inv TIMES. ss.\n    exploit (@Memory.add_exists (Thread.memory th) loc from to Message.reserve); eauto.\n    { ii. eapply NITV.\n      { left. eauto. }\n      { econs; eauto. }\n    }\n    { econs. }\n    intros [mem MEM].\n    exploit (@Memory.add_exists_le (Local.promises (Thread.local th)) (Thread.memory th)); eauto.\n    intros [prom PROM].\n    assert (STEP: Thread.step false (ThreadEvent.promise loc from to Message.reserve Memory.op_kind_add) th (Thread.mk _ (Thread.state th) (Local.mk (Local.tview (Thread.local th)) prom) (Thread.sc th) mem)).\n    { destruct th. ss. econs. econs; ss. econs; ss. econs; ss. }\n    exploit (@IHl times lang (Thread.mk _ (Thread.state th) (Local.mk (Local.tview (Thread.local th)) prom) (Thread.sc th) mem)); eauto; ss.\n    { i. erewrite add_covered; eauto. ii. des; subst.\n      { eapply NITV; eauto. }\n      { eapply NITV0; eauto. }\n    }\n    { hexploit step_promises_le; eauto.\n      { econs; eauto. }\n      i. ss.\n    }\n    i. des. esplits.\n    { econs; eauto. }\n    { econs; ss. }\n    { econs; eauto. }\n    { econs; eauto. }\n  }\nQed.\n\nLemma reservations_added_get_same mem1 mem0 l\n      (ADDED: reservations_added l mem0 mem1)\n      loc ts\n      (NIN: forall from, ~ List.In (loc, (from, ts)) l)\n  :\n    Memory.get loc ts mem1 = Memory.get loc ts mem0.\nProof.\n  ginduction ADDED; auto. i.\n  erewrite IHADDED; eauto.\n  { erewrite (@Memory.add_o mem1 mem0); eauto. des_ifs. ss. des; clarify.\n    exfalso. eapply NIN; eauto. }\n  { ii. ss. eapply NIN; eauto. }\nQed.\n\nLemma reservations_added_get_none mem1 mem0 l\n      (ADDED: reservations_added l mem0 mem1)\n      loc from ts\n      (IN: List.In (loc, (from, ts)) l)\n  :\n    Memory.get loc ts mem0 = None.\nProof.\n  ginduction ADDED; ss. i. des; clarify.\n  { eapply Memory.add_get0; eauto. }\n  { eapply IHADDED in IN. erewrite Memory.add_o in IN; eauto. des_ifs. }\nQed.\n\nLemma reservations_added_le_le l mem0 mem1 cap1 cap0\n      (ADDED0: reservations_added l mem0 mem1)\n      (MLE: Memory.le mem1 cap1)\n      (ADDED1: reservations_added l cap0 cap1)\n  :\n    Memory.le mem0 cap0.\nProof.\n  ii. destruct (classic (forall from, ~ List.In (loc, (from, to)) l)).\n  { erewrite <- (@reservations_added_get_same cap1 cap0); eauto.\n    erewrite <- (@reservations_added_get_same mem1 mem0) in LHS; eauto. }\n  { eapply not_all_not_ex in H. des.\n    erewrite reservations_added_get_none in LHS; eauto. ss. }\nQed.\n\nLemma cancel_reservations_added times l prom lang lc\n      (ADDEDPROM: reservations_added l prom (Local.promises lc))\n      (TIMES: List.Forall (fun locitv =>\n                             times (fst locitv) (fst (snd locitv)) /\\\n                             times (fst locitv) (snd (snd locitv))) l)\n  :\n    exists tr,\n      (<<CANCELTRACE: List.Forall (fun em => <<SAT: (ThreadEvent.is_cancel /1\\ wf_time_evt times) (snd em)>>) tr>>) /\\\n    forall\n      (st: Language.state lang) sc mem\n      (MLE: Memory.le (Local.promises lc) mem),\n    exists mem',\n      (<<STEPS: Trace.steps tr (Thread.mk _ st lc sc mem) (Thread.mk _ st (Local.mk (Local.tview lc) prom) sc mem')>>) /\\\n      (<<ADDEDMEM: reservations_added l mem' mem>>)\n.\nProof.\n  ginduction l; i.\n  { exists []. splits; ss. i. destruct lc. ss. inv ADDEDPROM. esplits; eauto. econs. }\n  { inv TIMES. inv ADDEDPROM.\n    exploit IHl; eauto. i. des.\n    eexists (tr++[(Local.mk (Local.tview lc) mem1, ThreadEvent.promise loc from to Message.reserve Memory.op_kind_cancel)]).\n    splits.\n    { eapply Forall_app; eauto. econs; ss. }\n    i. exploit (x0 st sc mem); eauto. i. des.\n    exploit (@Memory.remove_exists mem1 loc from to Message.reserve); eauto.\n    { eapply Memory.add_get0; eauto. } i. des.\n    exploit (@Memory.remove_exists_le mem1 mem'); eauto.\n    { eapply trace_steps_promises_le in STEPS; eauto. } i. des.\n    assert (mem2 = prom).\n    { symmetry. eapply MemoryMerge.add_remove; eauto. } subst.\n    esplits.\n    { eapply Trace.steps_trans.\n      { eapply STEPS. }\n      { econs; eauto. econs 1; eauto. econs; eauto. }\n    }\n    { eapply reservations_added_cancel; eauto. }\n  }\nQed.\n\nLemma step_finte_write_to (e: ThreadEvent.t)\n      (times: Loc.t -> Time.t -> Prop)\n      (EVENT: wf_time_evt times e)\n  :\n    exists (l: list (Loc.t * Time.t)),\n      (<<EVENT: write_not_to (fun loc ts => ~ List.In (loc, ts) l) e>>) /\\\n      (<<TIMES: List.Forall (fun locts => times (fst locts) (snd locts)) l>>).\nProof.\n  destruct e; try by (exists []; esplits; eauto); ss.\n  { exists [(loc, to)]. esplits; ss.\n    { des_ifs. ii. eapply H. auto. }\n    { econs; ss. des. auto. }\n  }\n  { exists [(loc, to)]. esplits; ss.\n    { ii. eapply H. auto. }\n    { econs; ss. des. auto. }\n  }\n  { exists [(loc, tsw)]. esplits; ss.\n    { ii. eapply H. auto. }\n    { econs; ss. des. auto. }\n  }\nQed.\n\nLemma write_not_to_mon P0 P1\n      (LE: P0 <2= P1)\n  :\n    write_not_to P1 <1= write_not_to P0.\nProof.\n  ii. unfold write_not_to in *. des_ifs; auto.\nQed.\n\nLemma traced_steps_finte_write_to (tr: Trace.t)\n      (times: Loc.t -> Time.t -> Prop)\n      (EVENTS: List.Forall (fun em => <<SAT: (wf_time_evt times) (snd em)>>) tr)\n  :\n    exists (l: list (Loc.t * Time.t)),\n      (<<EVENTS: List.Forall (fun em => write_not_to (fun loc ts => ~ List.In (loc, ts) l) (snd em)) tr>>) /\\\n      (<<TIMES: List.Forall (fun locts => times (fst locts) (snd locts)) l>>).\nProof.\n  ginduction tr.\n  { i. inv EVENTS. exists []. esplits; eauto. }\n  { i. inv EVENTS. exploit IHtr; eauto. i. des.\n    exploit (@step_finte_write_to (snd a)); eauto. i. des.\n    exists (l0 ++ l). esplits; eauto.\n    { econs; eauto.\n      { eapply write_not_to_mon; eauto. ii. eapply PR. eapply List.in_or_app; eauto. }\n      { eapply List.Forall_impl; eauto. i. ss.\n        eapply write_not_to_mon; eauto. ii. eapply PR. eapply List.in_or_app; eauto. }\n    }\n    { eapply Forall_app; eauto. }\n  }\nQed.\n\nLemma reserve_write_to (times: Loc.t -> Time.t -> Prop)\n      (DIVERGE: forall loc ts,\n          exists ts',\n            (<<TIMES: times loc ts'>>) /\\\n            (<<TS: Time.lt ts ts'>>))\n      mem\n      (MWF: memory_times_wf times mem)\n      loc ts\n      (TIMES: times loc ts)\n  :\n    (<<ALREADY: unattachable mem loc ts>>) \\/\n    (<<NEW: exists from mem',\n        (<<TS: Time.lt ts from>>) /\\\n        (<<ADD: Memory.add mem loc ts from Message.reserve mem'>>) /\\\n        (<<TIMES: times loc from>>) /\\\n        (<<MWF: memory_times_wf times mem'>>)>>).\nProof.\n  destruct (classic (unattachable mem loc ts)); auto. right.\n  hexploit (@cell_elements_least\n              (mem loc)\n              (fun to => exists from msg,\n                   (<<GET: Memory.get loc to mem = Some (from, msg)>>) /\\\n                   (<<TS: Time.lt ts from>>))).\n  i. des.\n  { hexploit (@Memory.add_exists mem loc ts from0 Message.reserve); ss.\n    { ii. destruct (Time.le_lt_dec from2 ts).\n      { eapply H. econs; eauto.\n        inv LHS. inv RHS. ss. eapply TimeFacts.lt_le_lt; eauto. }\n      { dup GET2. eapply LEAST in GET2.\n        { exploit memory_get_to_mon.\n          { eapply GET1. }\n          { eapply GET0. }\n          { inv LHS. inv RHS. ss. eapply TimeFacts.lt_le_lt; eauto. }\n          i. timetac.\n        }\n        esplits; eauto.\n      }\n    }\n    { econs. }\n    i. des. esplits; eauto.\n    { eapply MWF in GET0. des; auto. }\n    { eapply MWF in GET0. des.\n      ii. erewrite Memory.add_o in GET0; eauto. des_ifs.\n      { ss. des; clarify. }\n      { eapply MWF; eauto. }\n    }\n  }\n  { hexploit (DIVERGE loc ts). i. des.\n    hexploit (@Memory.add_exists mem loc ts ts' Message.reserve); ss.\n    { ii. eapply EMPTY; eauto. esplits; eauto.\n      destruct (Time.le_lt_dec from2 ts); auto. exfalso.\n      eapply H. econs; eauto.\n      inv LHS. inv RHS. ss. eapply TimeFacts.lt_le_lt; eauto. }\n    { econs. }\n    i. des. esplits; eauto.\n    ii. erewrite Memory.add_o in GET; eauto. des_ifs.\n    { ss. des; clarify. }\n    { eapply MWF; eauto. }\n  }\nQed.\n\nLemma reserve_write_tos times lang (th: Thread.t lang) tos\n      (DIVERGE: forall loc ts,\n          exists ts',\n            (<<TIMES: times loc ts'>>) /\\\n            (<<TS: Time.lt ts ts'>>))\n      (MWF: memory_times_wf times (Thread.memory th))\n      (MLE: Memory.le (Local.promises (Thread.local th)) (Thread.memory th))\n      (TIMES: List.Forall (fun locts => times (fst locts) (snd locts)) tos)\n  :\n    exists l tr prom' mem',\n      (<<STEPS: Trace.steps tr th (Thread.mk _ (Thread.state th) (Local.mk (Local.tview (Thread.local th)) prom') (Thread.sc th) mem')>>) /\\\n      (<<RESERVETRACE: List.Forall (fun em => <<SAT: (ThreadEvent.is_reserve /1\\ wf_time_evt times) (snd em)>>) tr>>) /\\\n      (<<ADDEDPROM: reservations_added l (Local.promises (Thread.local th)) prom'>>) /\\\n      (<<ADDEDMEM: reservations_added l (Thread.memory th) mem'>>) /\\\n      (<<WRITETO: forall loc ts (IN: List.In (loc, ts) tos),\n          unattachable mem' loc ts>>) /\\\n      (<<TIMES: List.Forall (fun locitv =>\n                               times (fst locitv) (fst (snd locitv)) /\\\n                               times (fst locitv) (snd (snd locitv))) l>>)\n.\nProof.\n  ginduction tos; i; ss.\n  { exists [], []. destruct th. destruct local. ss. esplits; eauto; ss.\n    { econs. }\n    { econs. }\n  }\n  { inv TIMES. exploit IHtos; eauto. i. des.\n    exploit reserve_write_to.\n    { eauto. }\n    { eapply memory_times_wf_traced in STEPS; eauto.\n      eapply List.Forall_impl; eauto. i. ss. des; auto. }\n    { eauto. }\n    i. ss. des.\n    { exists l, tr. esplits; eauto. i. des; auto. clarify. }\n    { exploit (@Memory.add_exists_le prom' mem'); eauto.\n      { eapply trace_steps_promises_le in STEPS; eauto. }\n      i. des.\n      assert (PROM: Memory.promise prom' mem' (fst a) (snd a) from Message.reserve promises2 mem'0 Memory.op_kind_add).\n      { econs; eauto. ss. }\n      destruct th. esplits.\n      { eapply Trace.steps_trans.\n        { eauto. }\n        { econs 2.\n          { econs 1. econs; eauto. }\n          { econs 1. }\n          { ss. }\n        }\n      }\n      { eapply Forall_app; eauto. econs; ss. }\n      { ss. eapply reservations_added_trans.\n        { eauto. }\n        { econs; eauto. econs. }\n      }\n      { ss. eapply reservations_added_trans.\n        { eauto. }\n        { econs; eauto. econs. }\n      }\n      { i. erewrite add_unattachable; eauto. des; clarify.\n        { right. splits; ss. refl. }\n        { eauto. }\n      }\n      { eapply Forall_app; eauto. }\n    }\n  }\nQed.\n\n\n\nLemma reservations_added_non_covered l mem0 mem1\n      (ADDED: reservations_added l mem0 mem1)\n      loc ts\n      (COVERED: covered loc ts mem0)\n  :\n    ~ intervals_sum l loc ts.\nProof.\n  ginduction l; eauto. i. inv ADDED. ss. ii.\n  des; clarify.\n  { inv COVERED. eapply add_succeed_wf in ADD. des.\n    eapply DISJOINT; eauto. }\n  { eapply IHl; eauto. erewrite add_covered; eauto. }\nQed.\n\nLemma add_unattachable_disjoint mem1 mem0 loc from to msg\n      (ADD: Memory.add mem0 loc from to msg mem1)\n      loc0 ts0\n      (UNATTACHABLE: unattachable mem0 loc0 ts0)\n  :\n    ~ (loc0 = loc /\\ Time.le from ts0 /\\ Time.lt ts0 to).\nProof.\n  ii. des; subst. inv UNATTACHABLE.\n  exploit add_succeed_wf; eauto. i. des.\n  hexploit DISJOINT; eauto. i. eapply disjoint_equivalent2 in H. des; ss.\n  { eapply TS1. eapply TimeFacts.le_lt_lt; eauto. }\n  { eapply Time.lt_strorder. eapply TimeFacts.le_lt_lt.\n    { eapply TS0. } eapply TimeFacts.le_lt_lt.\n    { instantiate (1:=ts0). unfold Time.join. des_ifs. }\n    { unfold Time.meet. des_ifs. }\n  }\nQed.\n\nLemma reservations_added_non_unattachable l mem0 mem1\n      (ADDED: reservations_added l mem0 mem1)\n      loc ts\n      (UNATTACHABLE: unattachable mem0 loc ts)\n  :\n    ~ intervals_sum_left l loc ts.\nProof.\n  ginduction l; eauto. i. inv ADDED. ss. ii.\n  des; clarify.\n  { exploit add_unattachable_disjoint; eauto. }\n  { eapply IHl; eauto. erewrite add_unattachable; eauto. }\nQed.\n\nLemma reservations_added_unattachable l mem0 mem1\n      (ADDED: reservations_added l mem0 mem1)\n      loc ts\n      (UNATTACHABLE: unattachable mem1 loc ts)\n  :\n    unattachable mem0 loc ts \\/ intervals_sum_left l loc ts.\nProof.\n  ginduction l; eauto. i.\n  { inv ADDED. auto. }\n  { i. inv ADDED. eapply IHl in TL; eauto. ss.\n    erewrite add_unattachable in TL; eauto. des; auto. }\nQed.\n\nDefinition eventable (mem prom: Memory.t) (spaces: Loc.t -> Time.t -> Prop)\n           (loc: Loc.t) (ts: Time.t): Prop :=\n  concrete_promised mem loc ts \\/\n  covered loc ts prom \\/\n  spaces loc ts.\n\nDefinition eventable_below (mem prom: Memory.t) (spaces: Loc.t -> Time.t -> Prop)\n           (loc: Loc.t) (ts: Time.t): Prop :=\n  exists to, <<TIME: eventable mem prom spaces loc to>> /\\ <<TS: Time.le ts to>>.\n\nLemma eventable_le_below mem0 prom0 mem1 prom1 spaces\n      (INCR: eventable mem1 prom1 spaces <2= eventable mem0 prom0 spaces)\n  :\n    eventable_below mem1 prom1 spaces <2= eventable_below mem0 prom0 spaces.\nProof.\n  ii. unfold eventable_below in *. des. esplits; eauto.\nQed.\n\n\nLemma event_in_concrete_or_writes_promise (spaces: Loc.t -> Time.t -> Prop)\n      prom0 mem0 loc from to msg prom1 mem1 kind\n      (PROMISE: Memory.promise prom0 mem0 loc from to msg prom1 mem1 kind)\n      (NOTIN: if Memory.op_kind_is_cancel kind\n              then True\n              else (forall ts (ITV: Interval.mem (from, to) ts),\n                       spaces loc ts \\/ covered loc ts mem0))\n      (CLOSED: Memory.closed mem0)\n  :\n    (<<INCR: eventable mem1 prom1 spaces <2= eventable mem0 prom0 spaces>>) /\\\n    (<<FROM: eventable_below mem0 prom0 spaces loc from>>) /\\\n    (<<TO: eventable_below mem0 prom0 spaces loc to>>).\nProof.\n  unfold eventable. inv PROMISE.\n  { exploit add_succeed_wf; try apply MEM; eauto. i. des.\n    splits.\n    { ii. des; auto.\n      { inv PR. erewrite Memory.add_o in GET; eauto. des_ifs.\n        { ss. des; clarify. right. exploit NOTIN; eauto.\n          { econs; eauto. refl. }\n          i. des; auto. inv x. exfalso. eapply DISJOINT; eauto.\n          econs; ss. refl.\n        }\n        { left. econs; eauto. }\n      }\n      { erewrite add_covered in PR; eauto. des; auto. subst.\n        right. right. exploit NOTIN; eauto. i. des; auto.\n        inv x. exfalso. eapply DISJOINT; eauto. }\n    }\n    { exists to. esplits; eauto.\n      { right. right. exploit NOTIN; eauto.\n        { econs; eauto. refl. }\n        i. des; auto. inv x. exfalso. eapply DISJOINT; eauto.\n        econs; ss. refl.\n      }\n      { left. auto. }\n    }\n    { exists to. esplits; eauto.\n      { right. right. exploit NOTIN; eauto.\n        { econs; eauto. refl. }\n        i. des; auto. inv x. exfalso. eapply DISJOINT; eauto.\n        econs; ss. refl.\n      }\n      { refl. }\n    }\n  }\n  { exploit split_succeed_wf; try apply PROMISES; eauto. i. des.\n    splits.\n    { ii. des; auto.\n      { inv PR. erewrite Memory.split_o in GET; eauto. des_ifs.\n        { ss. des; clarify. right. left. econs; eauto.\n          econs; eauto. ss. left. auto. }\n        { ss. des; clarify. right. left. econs; eauto.\n          econs; eauto. ss. refl. }\n        { left. econs; eauto. }\n      }\n      { erewrite split_covered in PR; eauto. }\n    }\n    { exists ts3. esplits; eauto.\n      { right. left. econs; eauto. econs; eauto. refl. }\n      { left. etrans; eauto. }\n    }\n    { exists ts3. esplits; eauto.\n      { right. left. econs; eauto. econs; eauto. refl. }\n      { left. auto. }\n    }\n  }\n  { exploit lower_succeed_wf; try apply PROMISES; eauto. i. des.\n    splits.\n    { ii. des; auto.\n      { inv PR. erewrite Memory.lower_o in GET0; eauto. des_ifs.\n        { ss. des; clarify. right. left. econs; eauto.\n          econs; eauto. ss. refl. }\n        { left. econs; eauto. }\n      }\n      { erewrite lower_covered in PR; eauto. }\n    }\n    { exists to. esplits; eauto.\n      { right. left. econs; eauto. econs; eauto. refl. }\n      { left. eauto. }\n    }\n    { exists to. esplits; eauto.\n      { right. left. econs; eauto. econs; eauto. refl. }\n      { refl. }\n    }\n  }\n  { exploit Memory.remove_get0; try apply PROMISES; eauto. i. des.\n    assert (TS: Time.lt from to).\n    { exploit Memory.remove_get0; try apply MEM; eauto. i. des.\n      inv CLOSED. apply memory_get_ts_strong in GET. des; auto.\n      subst. erewrite INHABITED in GET1. ss. }\n    splits.\n    { ii. des; auto.\n      { inv PR. erewrite Memory.remove_o in GET1; eauto. des_ifs.\n        left. econs; eauto. }\n      { erewrite remove_covered in PR; eauto. des; auto. }\n    }\n    { exists to. esplits; eauto.\n      { right. left. econs; eauto. econs; eauto. refl. }\n      { left. eauto. }\n    }\n    { exists to. esplits; eauto.\n      { right. left. econs; eauto. econs; eauto. refl. }\n      { refl. }\n    }\n  }\nQed.\n\nLemma event_in_concrete_or_writes_write (spaces: Loc.t -> Time.t -> Prop)\n      prom0 mem0 loc from to prom1 mem1 val released kind\n      (PROMISE: Memory.write prom0 mem0 loc from to val released prom1 mem1 kind)\n      (NOTIN: if Memory.op_kind_is_cancel kind\n              then True\n              else (forall ts (ITV: Interval.mem (from, to) ts),\n                       spaces loc ts \\/ covered loc ts mem0))\n      (CLOSED: Memory.closed mem0)\n  :\n    (<<INCR: eventable mem1 prom1 spaces <2= eventable mem0 prom0 spaces>>) /\\\n    (<<FROM: eventable_below mem0 prom0 spaces loc from>>) /\\\n    (<<TO: eventable_below mem0 prom0 spaces loc to>>).\nProof.\n  inv PROMISE.\n  exploit event_in_concrete_or_writes_promise; eauto. i. des. esplits; eauto.\n  i. eapply INCR. unfold eventable in *. des; auto.\n  erewrite remove_covered in PR; eauto. des; auto.\nQed.\n\nLemma step_eventable_time lang (th0 th1: Thread.t lang) pf e\n      (spaces: Loc.t -> Time.t -> Prop)\n      (STEP: Thread.step pf e th0 th1)\n      (WRITENOTIN: write_not_in (fun loc ts => ~ (spaces loc ts \\/ covered loc ts (Thread.memory th0))) e)\n      (CLOSED: Memory.closed (Thread.memory th0))\n  :\n    (<<INCR: eventable (Thread.memory th1) (Local.promises (Thread.local th1)) spaces <2= eventable (Thread.memory th0) (Local.promises (Thread.local th0)) spaces>>) /\\\n    (<<TIMES: tevent_map_weak\n                (fun loc ts fts => ts = fts /\\\n                                   eventable_below (Thread.memory th0) (Local.promises (Thread.local th0)) spaces loc ts) e e>>).\nProof.\n  inv STEP.\n  { inv STEP0; ss. inv LOCAL.\n    eapply event_in_concrete_or_writes_promise in PROMISE; ss.\n    { des. splits; eauto. econs; eauto. }\n    { des_ifs. ii. apply NNPP. eapply WRITENOTIN; eauto. }\n  }\n  { inv STEP0; ss. inv LOCAL; ss; eauto.\n    { splits; auto. econs. }\n    { inv LOCAL0. ss. splits; auto. econs; eauto. split; auto.\n      exists ts. splits; ss.\n      { left. econs; eauto. }\n      { refl. }\n    }\n    { inv LOCAL0. eapply event_in_concrete_or_writes_write in WRITE; eauto.\n      { des. splits; eauto. econs; eauto. }\n      { des_ifs. ii. eapply NNPP. eauto. }\n    }\n    { inv LOCAL1. inv LOCAL2. eapply event_in_concrete_or_writes_write in WRITE; eauto.\n      { des. splits; eauto. econs; eauto. }\n      { des_ifs. ii. eapply NNPP. eauto. }\n    }\n    { inv LOCAL0. ss. splits; auto. econs; eauto. }\n    { inv LOCAL0. ss. splits; auto. econs; eauto. }\n    { inv LOCAL0. ss. splits; auto. econs; eauto. }\n }\nQed.\n\nLemma tevent_map_weak_mon (f0 f1: Loc.t -> Time.t -> Time.t -> Prop)\n      (LE: f0 <3= f1)\n  :\n    tevent_map_weak f0 <2= tevent_map_weak f1.\nProof.\n  i. inv PR; econs; eauto.\nQed.\n\nLemma traced_steps_eventable_time_normal lang (th0 th1: Thread.t lang) tr\n      (spaces: Loc.t -> Time.t -> Prop)\n      (STEPS: Trace.steps tr th0 th1)\n      (WRITENOTIN: List.Forall (fun em => (write_not_in (fun loc ts => ~ (spaces loc ts \\/ covered loc ts (Thread.memory th0))) /1\\ (fun e => ~ ThreadEvent.is_cancel e)) (snd em)) tr)\n      (MEM: Memory.closed (Thread.memory th0))\n      (LOCAL: Local.wf (Thread.local th0) (Thread.memory th0))\n      (SC: Memory.closed_timemap (Thread.sc th0) (Thread.memory th0))\n  :\n    (<<INCR: eventable (Thread.memory th1) (Local.promises (Thread.local th1)) spaces <2= eventable (Thread.memory th0) (Local.promises (Thread.local th0)) spaces>>) /\\\n    (<<TIMES: List.Forall2\n                (fun em fem =>\n                   tevent_map_weak (fun loc ts fts => ts = fts /\\ eventable_below (Thread.memory th0) (Local.promises (Thread.local th0)) spaces loc ts)\n                                   (snd fem) (snd em)) tr tr>>).\nProof.\n  ginduction STEPS.\n  { i. splits; ss. }\n  { i. subst. inv WRITENOTIN.\n    exploit Thread.step_future; eauto. i. des.\n    exploit IHSTEPS; eauto.\n    { eapply List.Forall_impl; eauto.\n      i. ss. des. splits; auto. eapply write_not_in_mon; eauto. i. ss.\n      ii. eapply PR. des; eauto. right.\n      eapply step_not_cancel_covered_increase; eauto. }\n    i. des.\n    hexploit step_eventable_time; eauto.\n    i. des. esplits; eauto. econs; ss; eauto.\n    eapply list_Forall2_impl; eauto.\n    i. ss. eapply tevent_map_weak_mon; eauto.\n    i. ss. des. subst. splits; auto.\n    eapply eventable_le_below; eauto.\n  }\nQed.\n\nLemma traced_steps_eventable_time_cancel lang (th0 th1: Thread.t lang) tr\n      (spaces: Loc.t -> Time.t -> Prop)\n      (STEPS: Trace.steps tr th0 th1)\n      (WRITENOTIN: List.Forall (fun em => ThreadEvent.is_cancel (snd em)) tr)\n      (MEM: Memory.closed (Thread.memory th0))\n      (LOCAL: Local.wf (Thread.local th0) (Thread.memory th0))\n      (SC: Memory.closed_timemap (Thread.sc th0) (Thread.memory th0))\n  :\n    (<<INCR: eventable (Thread.memory th1) (Local.promises (Thread.local th1)) spaces <2= eventable (Thread.memory th0) (Local.promises (Thread.local th0)) spaces>>) /\\\n    (<<TIMES: List.Forall2\n                (fun em fem =>\n                   tevent_map_weak (fun loc ts fts => ts = fts /\\ eventable_below (Thread.memory th0) (Local.promises (Thread.local th0)) spaces loc ts)\n                                   (snd fem) (snd em)) tr tr>>).\nProof.\n  ginduction STEPS.\n  { i. splits; ss. }\n  { i. subst. inv WRITENOTIN.\n    exploit Thread.step_future; eauto. i. des.\n    hexploit step_eventable_time; eauto.\n    { instantiate (1:=spaces). destruct e; ss. des_ifs. }\n    exploit IHSTEPS; eauto. i. des.\n    splits; eauto. econs; eauto.\n    eapply list_Forall2_impl; eauto.\n    i. ss. eapply tevent_map_weak_mon; eauto.\n    i. ss. des. subst. splits; auto.\n    eapply eventable_le_below; eauto.\n  }\nQed.\n\nLemma reservations_added_covered mem0 mem1 l\n      (ADDED: reservations_added l mem0 mem1)\n      loc ts\n  :\n    covered loc ts mem1 <-> (covered loc ts mem0 \\/ intervals_sum l loc ts).\nProof.\n  ginduction l; ss.\n  { i. inv ADDED. split; i; des; ss; auto. }\n  { i. inv ADDED. rewrite IHl; eauto.\n    rewrite (@add_covered mem3 mem0); eauto. split; i; des; auto. }\nQed.\n\nLemma reservations_added_covered_rev mem0 mem1 l\n      (ADDED: reservations_added l mem0 mem1)\n      loc ts\n  :\n    covered loc ts mem0 <-> (covered loc ts mem1 /\\ ~ intervals_sum l loc ts).\nProof.\n  split; i.\n  { split.\n    { eapply reservations_added_covered; eauto. }\n    { eapply reservations_added_non_covered; eauto. }\n  }\n  { des. eapply reservations_added_covered in H; eauto. des; ss. }\nQed.\n\nLemma can_reserve_all_needed times\n      (DIVERGE: forall loc ts,\n          exists ts',\n            (<<TIMES: times loc ts'>>) /\\\n            (<<TS: Time.lt ts ts'>>))\n      lang\n      st0 st1 lc0 lc1 sc0 sc1 mem0 mem1 tr\n      (MWF: memory_times_wf times mem0)\n      (STEPS: Trace.steps tr (Thread.mk lang st0 lc0 sc0 mem0) (Thread.mk lang st1 lc1 sc1 mem1))\n      (EVENTS: List.Forall (fun em => <<SAT: ((fun e => ~ ThreadEvent.is_cancel e) /1\\ wf_time_evt times) (snd em)>>) tr)\n      (MEM: Memory.closed mem0)\n      (LOCAL: Local.wf lc0 mem0)\n      (SC: Memory.closed_timemap sc0 mem0)\n  :\n    exists lc0' mem0' tr_reserve tr_cancel reserves,\n      (<<RESERVESTEPS:\n         Trace.steps tr_reserve (Thread.mk lang st0 lc0 sc0 mem0) (Thread.mk lang st0 lc0' sc0 mem0')>>) /\\\n      (<<RESERVETRACE:\n         List.Forall (fun em => <<SAT: (ThreadEvent.is_reserve /1\\ wf_time_evt times) (snd em)>>) tr_reserve>>) /\\\n      (<<CANCELTRACE: List.Forall (fun em => <<SAT: (ThreadEvent.is_cancel /1\\ wf_time_evt times) (snd em)>>) tr_cancel>>) /\\\n      (<<RESERVEMEM: reservations_added reserves mem0 mem0'>>) /\\\n      (<<CAP:\n         forall cap0'\n                (MLE: Memory.le mem0' cap0'),\n         exists cap0 cap1 ,\n           (<<CANCELSTEPS:\n              Trace.steps tr_cancel (Thread.mk lang st0 lc0' sc0 cap0') (Thread.mk lang st0 lc0 sc0 cap0)>>) /\\\n           (<<STEPS:\n              Trace.steps tr (Thread.mk lang st0 lc0 sc0 cap0) (Thread.mk lang st1 lc1 sc1 cap1)>>) /\\\n           (<<RESERVEMEM: reservations_added reserves cap0 cap0'>>)>>) /\\\n      (<<TIMES: forall max\n                       (MAX: concrete_promise_max_timemap mem0' (Local.promises lc0') max),\n          List.Forall2\n            (fun em fem =>\n               tevent_map_weak (fun loc ts fts => ts = fts /\\ Time.le ts (max loc))\n                               (snd fem) (snd em)) (tr_cancel ++ tr) (tr_cancel ++ tr)>>)\n.\nProof.\n  exploit (@traced_steps_finte_write_to tr); eauto.\n  { eapply List.Forall_impl; eauto. i. ss. des. eauto. }\n  intros [tos ?]. des.\n  exploit traced_steps_needed_spaces; eauto.\n  i. des.\n  exploit reserve_empty_intervals; eauto.\n  { eapply LOCAL. }\n  i. des. ss.\n  assert (MLE: Memory.le prom' mem').\n  { eapply trace_steps_promises_le in STEPS0; eauto. eapply LOCAL. }\n  exploit reserve_write_tos.\n  { eauto. }\n  { eapply memory_times_wf_traced in STEPS0; eauto.\n    eapply List.Forall_impl; eauto. i. ss. des. eauto.\n  }\n  { ss. }\n  { eauto. }\n  i. des. ss.\n  assert (ADDEDPROMALL: reservations_added (l ++ l0) (Local.promises lc0) prom'0).\n  { eapply reservations_added_trans; eauto. }\n  assert (ADDEDMEMALL: reservations_added (l ++ l0) mem0 mem'0).\n  { eapply reservations_added_trans; eauto. }\n  hexploit cancel_reservations_added.\n  { instantiate (1:=Local.mk (Local.tview lc0) prom'0). eapply ADDEDPROMALL. }\n  { eapply Forall_app; eauto. }\n  i. des.\n  assert (CAP: forall cap0'\n                      (MLE: Memory.le mem'0 cap0'),\n             exists cap0 cap1,\n               Trace.steps\n                 tr2\n                 (Thread.mk _ st0 {| Local.tview := Local.tview lc0; Local.promises := prom'0 |} sc0 cap0')\n                 (Thread.mk _ st0 lc0 sc0 cap0) /\\\n               Trace.steps\n                 tr\n                 (Thread.mk _ st0 lc0 sc0 cap0)\n                 (Thread.mk _ st1 lc1 sc1 cap1) /\\\n               (<<ADDED: reservations_added (l ++ l0) cap0 cap0'>>))\n  .\n  { i. ss. exploit (H0 st0 sc0 cap0').\n    { etrans; eauto. eapply trace_steps_promises_le in STEPS1; eauto. }\n    i. des.\n    assert (MLE1: Memory.le mem0 mem'1).\n    { eapply reservations_added_le_le.\n      { eapply ADDEDMEMALL. }\n      { eapply MLE0. }\n      { eauto. }\n    }\n    hexploit traced_step_lifting.\n    { eapply STEPS. }\n    { eapply list_Forall_sum.\n      { eapply list_Forall_sum.\n        { eapply EVENTS. }\n        { eapply EVENTS0. }\n        { instantiate (1:=fun em => <<SAT: ((fun e => ~ ThreadEvent.is_cancel e) /1\\ write_not_to (fun loc ts => ~ List.In (loc, ts) tos)) (snd em)>>).\n          i. ss. des. splits; auto. }\n      }\n      { eapply WRITENOTIN. }\n      i. ss. des. splits; eauto.\n    }\n    { eapply MLE1. }\n    { i. destruct (classic (covered loc ts mem0)); auto. right.\n      ii. des; ss. eapply reservations_added_non_covered in ADDEDMEM1; eauto.\n      eapply ADDEDMEM1. erewrite intervals_sum_interval.\n      erewrite intervals_sum_interval in H1. des. esplits; eauto.\n      eapply List.in_or_app; eauto. }\n    { i. destruct (classic (unattachable mem0 loc ts)); auto. right.\n      ii. des; ss. eapply reservations_added_non_unattachable in ADDEDMEM1; eauto.\n      eapply ADDEDMEM1. erewrite intervals_sum_left_interval.\n      eapply WRITETO in H1. eapply reservations_added_unattachable in H1; eauto.\n      des; ss. }\n    { eauto. }\n    { eauto. }\n    { eauto. }\n    i. des. exists mem'1, cap1.\n    splits; eauto. destruct lc0. ss.\n  }\n  esplits.\n  { eapply Trace.steps_trans.\n    { eapply STEPS0. }\n    { eapply STEPS1. }\n  }\n  { eapply Forall_app; eauto. }\n  { eapply CANCELTRACE. }\n  { eauto. }\n  { i. exploit CAP; eauto. }\n  { i. exploit (CAP mem'0).\n    { refl. }\n    i. des. ss.\n    exploit Trace.steps_future; try apply STEPS0; eauto. i. des. ss.\n    exploit Trace.steps_future; try apply STEPS1; eauto. i. des. ss.\n    exploit Trace.steps_future; try apply x0; eauto. i. des. ss.\n    exploit traced_steps_eventable_time_cancel; try apply x0; eauto; ss.\n    { eapply List.Forall_impl; eauto. i. ss. des. splits; auto. }\n    instantiate (1:=intervals_sum l). i. ss. des.\n    assert (EVENTTIMES: forall loc ts\n                               (EVENTABLE: eventable_below mem'0 prom'0 (intervals_sum l) loc ts),\n               Time.le ts (max loc)).\n    { i. unfold eventable_below in EVENTABLE. des. etrans; eauto.\n      unfold eventable in TIME. des.\n      { inv TIME. eapply MAX in GET. auto. }\n      { inv TIME. eapply MAX in GET. inv ITV. ss. etrans; eauto. }\n      { eapply reservations_added_covered in ADDEDPROM; eauto. des.\n        exploit ADDEDPROM1.\n        { right. eauto. }\n        i. eapply reservations_added_covered in ADDEDPROM0; eauto. des.\n        exploit ADDEDPROM2.\n        { left. eauto. }\n        i. inv x2. eapply MAX in GET. inv ITV. ss. etrans; eauto.\n      }\n    }\n    eapply List.Forall2_app.\n    { eapply list_Forall2_impl; eauto. i. ss.\n      eapply tevent_map_weak_mon; eauto. i. ss. des. subst. splits; auto. }\n    { exploit traced_steps_eventable_time_normal; try apply x1; eauto; ss.\n      { instantiate (1:=intervals_sum l).\n        eapply list_Forall_sum.\n        { eapply EVENTS. }\n        { eapply WRITENOTIN. }\n        i. ss. des. splits; auto.\n        eapply write_not_in_mon; eauto. i. ss. ii. eapply PR.\n        apply or_comm in H. apply or_strengthen in H. des; auto. right.\n        erewrite reservations_added_covered_rev; try apply ADDED; eauto.\n        erewrite reservations_added_covered_rev in SAT; try apply ADDEDMEMALL; eauto.\n      }\n      { i. des. eapply list_Forall2_impl; eauto. i. ss.\n        eapply tevent_map_weak_mon; eauto. i. ss. des. subst. splits; auto.\n        eapply eventable_le_below in PR0; eauto. }\n    }\n  }\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/PreReserve.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2736977495091383}}
{"text": "(* Uniqueness of typing for concise syntax. *)\n\nRequire config.\nRequire Import config_tactics.\nRequire Import syntax.\n\nRequire concise_syntax.\nRequire Import tt.\nRequire ett ptt.\nRequire ptt2ett ett2ptt.\nRequire ptt_admissible.\nRequire ett_sanity ptt_sanity.\nRequire concise_inversion.\nRequire Import tactics config_tactics.\n\nSection Uniqueness.\n\nContext `{configReflection : config.Reflection}.\nContext `{configSimpleProducts : config.SimpleProducts}.\nContext `{configProdEta : config.ProdEta}.\nContext `{configUniverses : config.Universes}.\nContext `{configWithProp : config.WithProp}.\nContext `{configId : config.IdentityTypes}.\nContext `{configWithJ : config.WithJ}.\nContext `{configEmpty : config.WithEmpty}.\nContext `{configUnit : config.WithUnit}.\nContext `{configBool : config.WithBool}.\nContext `{configPi : config.WithPi}.\n\nLocal Existing Instance concise_syntax.Syntax.\nLocal Existing Instance concise_inversion.haveCtxExtendInversion.\nLocal Existing Instance concise_inversion.haveTyIdInversion.\nLocal Existing Instance concise_inversion.haveTyProdInversion.\nLocal Existing Instance concise_inversion.haveTySimProdInversion.\n\n(* Auxiliary inversion lemmas. *)\n\nFixpoint eqctx_ctxextend_left G A D\n         (H : ett.eqctx (ctxextend G A) D) {struct H} :\n  { G' : context &\n    { A' : type &\n      (D = ctxextend G' A') * ett.eqctx G G' * ett.eqtype G A A'\n    }\n  }%type\n\nwith eqctx_ctxextend_right D G A\n                           (H : ett.eqctx D (ctxextend G A)) {struct H} :\n  { G' : context &\n    { A' : type &\n      (D = ctxextend G' A') * ett.eqctx G G' * ett.eqtype G A A'\n    }\n  }%type.\nProof.\n  (**** left ****)\n  - { inversion_clear H ; doConfig.\n\n      (* CtxRefl *)\n      - exists G, A. repeat split.\n        + capply CtxRefl.\n          eapply ptt2ett.sane_isctx.\n          apply (concise_inversion.CtxExtendInversion G A).\n          now eapply ett2ptt.sane_isctx.\n        + capply EqTyRefl.\n          eapply ptt2ett.sane_istype.\n          apply (concise_inversion.CtxExtendInversion G A).\n          now eapply ett2ptt.sane_isctx.\n\n      (* CtxSym *)\n      - destruct (eqctx_ctxextend_right _ _ _ X) as [G' [A' [[eq HG] HA]]].\n        exists G', A'. repeat split ; assumption.\n\n      (* CtxTrans *)\n      - destruct (eqctx_ctxextend_left _ _ _ X2) as [G' [A' [[eq HG] HA]]].\n        subst.\n        destruct (eqctx_ctxextend_left _ _ _ X3) as [G'' [A'' [[eq' HG'] HA']]].\n        exists G'', A''. repeat split.\n        + assumption.\n        + ceapply CtxTrans ; eassumption.\n        + ceapply EqTyTrans.\n          * eassumption.\n          * ceapply EqTyCtxConv ; try eassumption.\n            capply CtxSym ; assumption.\n\n      (* EqCtxExtend *)\n      - exists D0, B. repeat split ; assumption.\n\n    }\n\n  (**** right ****)\n  - { inversion_clear H ; doConfig.\n\n      (* CtxRefl *)\n      - exists G, A. repeat split.\n        + capply CtxRefl.\n          eapply ptt2ett.sane_isctx.\n          apply (concise_inversion.CtxExtendInversion G A).\n          now eapply ett2ptt.sane_isctx.\n        + capply EqTyRefl.\n          eapply ptt2ett.sane_istype.\n          apply (concise_inversion.CtxExtendInversion G A).\n          now eapply ett2ptt.sane_isctx.\n\n      (* CtxSym *)\n      - destruct (eqctx_ctxextend_left _ _ _ X) as [G' [A' [[eq HG] HA]]].\n        exists G', A'. repeat split ; assumption.\n\n      (* CtxTrans *)\n      - destruct (eqctx_ctxextend_right _ _ _ X3) as [G' [A' [[eq HG] HA]]].\n        subst.\n        destruct (eqctx_ctxextend_right _ _ _ X2) as [G'' [A'' [[eq' HG'] HA']]].\n        exists G'', A''. repeat split.\n        + assumption.\n        + ceapply CtxTrans ; eassumption.\n        + ceapply EqTyTrans.\n          * eassumption.\n          * ceapply EqTyCtxConv ; try eassumption.\n            capply CtxSym ; assumption.\n\n      (* EqCtxExtend *)\n      - exists G0, A0. repeat split.\n        + now capply CtxSym.\n        + capply EqTySym.\n          ceapply EqTyCtxConv ; eassumption.\n\n    }\n\nDefined.\n\nDefinition eqctx_ctxextend G A G' A'\n         (H : ett.eqctx (ctxextend G A) (ctxextend G' A')) :\n  (ett.eqctx G G' * ett.eqtype G A A')%type.\nProof.\n  destruct (eqctx_ctxextend_left _ _ _ H) as [G'' [A'' [[eq HG] HA]]].\n  inversion eq. subst.\n  split ; assumption.\nDefined.\n\n\n(* It looks like we need to strengthen some inference\n   rules, as follows: *)\n\nLemma substCtxConv' :\n  forall G G' D sbs (E : ett.eqctx G' G),\n    ett.issubst sbs G D -> ett.issubst sbs G' D.\nProof.\n  intros G G' D sbs E H.\n  ceapply SubstCtxConv.\n  - eassumption.\n  - now capply CtxSym.\n  - capply CtxRefl.\n    now apply (ett_sanity.sane_issubst sbs G D).\nDefined.\n\n(* Injectivity results *)\n\nAxiom admit : forall {A}, A.\nTactic Notation \"admit\" := (exact admit).\n\nFixpoint injProd_left G A B T\n         (H : ett.eqtype G (Prod A B) T) {struct H} :\n  { A' : type &\n    { B' : type &\n      (T = Prod A' B') * ett.eqtype G A A' * ett.eqtype (ctxextend G A) B B'\n    }\n  }%type\n\nwith injProd_right G T A' B'\n                   (H : ett.eqtype G T (Prod A' B')) {struct H} :\n  { A : type &\n    { B : type &\n      (T = Prod A B) * ett.eqtype G A A' * ett.eqtype (ctxextend G A) B B'\n    }\n  }%type.\nProof.\n  (** left **)\n  - { inversion_clear H ; doConfig.\n\n      - destruct (injProd_left _ _ _ _ X) as [A' [B' [[hT hA] hB]]].\n        exists A', B'. repeat split.\n        + assumption.\n        + ceapply EqTyCtxConv ; ehyp.\n        + ceapply EqTyCtxConv.\n          * ehyp.\n          * capply EqCtxExtend.\n            -- assumption.\n            -- ceapply EqTyTrans.\n               ++ eassumption.\n               ++ ceapply EqTySym. assumption.\n\n      - exists A, B. repeat split.\n        + capply EqTyRefl.\n          eapply ptt2ett.sane_istype.\n          apply (concise_inversion.TyProdInversion G A B). hyp.\n        + capply EqTyRefl.\n          eapply ptt2ett.sane_istype.\n          apply (concise_inversion.TyProdInversion G A B). hyp.\n\n      - destruct (injProd_right G T A B X) as [A' [B' [[hT hA] hB]]].\n        exists A', B'. repeat split.\n        + assumption.\n        + capply EqTySym. assumption.\n        + capply EqTySym. ceapply EqTyCtxConv.\n          * ehyp.\n          * capply EqCtxExtend.\n            -- capply CtxRefl. tt_sane.\n            -- hyp.\n\n      - destruct (injProd_left _ _ _ _ X) as [A' [B' [[hT hA] hB]]]. subst.\n        destruct (injProd_left _ _ _ _ X0) as [A'' [B'' [[hT' hA'] hB']]].\n        subst.\n        exists A', B'. repeat split.\n        + admit.\n        + admit.\n        + admit.\n\n      - admit.\n\n      - admit.\n\n      - admit.\n\n      - admit.\n\n      - admit.\n    }\n\n  - admit.\n\nDefined.\n\n\nFixpoint injProd G A A' B B' (H : ett.eqtype G (Prod A B) (Prod A' B')) {struct H} :\n  ett.eqtype G A A' * ett.eqtype (ctxextend G A) B B'.\nProof.\n  destruct (injProd_left _ _ _ _ H) as [A'' [B'' [[eq hA] hB]]].\n  inversion eq. subst.\n  split ; assumption.\nDefined.\n\n(* Tactics for dealing with the conversion cases. *)\n\nLtac doTyConv unique_term' :=\n  ceapply EqTyTrans ;\n  [ eapply unique_term' ;\n    [ ehyp\n    | hyp ]\n  | ceapply EqTyCtxConv ;\n    [ ehyp\n    | hyp ] ].\n\nLtac doCtxConv D' unique_term' :=\n  eapply unique_term' ;\n  [ ehyp\n  | (config apply @CtxTrans with (D := D')) ; hyp ].\n\nLtac doSubstConv unique_subst' :=\n  ceapply CtxTrans ; [\n    eapply unique_subst' ; [\n      ehyp\n    | ceapply CtxTrans ; [\n        ehyp\n      | capply CtxSym ; hyp\n      ]\n    ]\n  | hyp\n  ].\n\n(* The version of the theorem that allows variation of the context. *)\n\nFixpoint unique_term_ctx G u A (H1 : ptt.isterm G u A) {struct H1}:\n  forall B D,\n    ptt.isterm D u B ->\n    ptt.eqctx D G ->\n    ett.eqtype G A B\n\nwith unique_subst G D1 sbs (H1 : ptt.issubst sbs G D1) {struct H1}:\n  forall G' D2 (H2 : ptt.issubst sbs G' D2) (H3 : ptt.eqctx G G'),\n    ett.eqctx D1 D2.\n\nProof.\n  (* unique_term *)\n  { destruct H1 ; doConfig ;\n    simple refine (fix unique_term'' B' D' H2' H3' {struct H2'} := _) ;\n    pose (\n      unique_term' B' D' H1 H2 :=\n        unique_term'' B' D'\n                      H1\n                      (ett2ptt.sane_eqctx D' _ H2)\n    ) ;\n    pose (\n      unique_term_ctx' G u A H1 B D H2 H3 :=\n        unique_term_ctx G u A\n                        H1\n                        B D\n                        (ett2ptt.sane_isterm D u B H2)\n                        (ett2ptt.sane_eqctx D G H3)\n    ) ;\n    pose (\n      unique_subst' G D1 sbs H1 G' D2 H2 H3 :=\n        unique_subst G D1 sbs\n                     H1\n                     G' D2\n                     (ett2ptt.sane_issubst sbs G' D2 H2)\n                     (ett2ptt.sane_eqctx G G' H3)\n    ).\n\n    (* H1: TermTyConv *)\n    - {\n        config apply @EqTyTrans with (B := A).\n        + capply EqTySym. hyp.\n        + eapply (unique_term_ctx G u A) ; eassumption.\n      }\n\n    (* TermCtxConv *)\n    - {\n        ceapply EqTyCtxConv.\n        - eapply unique_term_ctx'.\n          + ehyp.\n          + ehyp.\n          + config apply @CtxTrans with (D := D).\n            * hyp.\n            * capply CtxSym. hyp.\n        - hyp.\n      }\n\n    (* TermSubst *)\n    - { inversion_clear H2' ; doConfig.\n        - doTyConv unique_term'.\n        - doCtxConv D' unique_term'.\n\n        - ceapply CongTySubst.\n          + ceapply SubstRefl. ehyp.\n          + eapply (unique_term_ctx' _ u).\n            * hyp.\n            * ehyp.\n            * { capply CtxSym.\n                apply (@unique_subst' G _ sbs) with (G' := G).\n                - hyp.\n                - eapply substCtxConv'.\n                  + ceapply CtxSym.\n                    ehyp.\n                  + hyp.\n                - capply CtxRefl. hyp.\n              }\n      }\n\n    (* TermVarZero *)\n    - { inversion H2' ; doConfig.\n        - doTyConv unique_term'.\n        - doCtxConv D' unique_term'.\n\n        - { assert (L : ett.eqctx (ctxextend G0 A0) (ctxextend G A)).\n            - rewrite H. hyp.\n            - destruct (eqctx_ctxextend _ _ _ _  L) as [E M].\n              ceapply CongTySubst.\n              + ceapply CongSubstWeak.\n                capply EqTySym.\n                ceapply EqTyCtxConv ; ehyp.\n              + capply EqTySym.\n                ceapply EqTyCtxConv ; ehyp.\n          }\n      }\n\n\n    (* TermVarSucc *)\n      - { inversion H2' ; doConfig.\n          - doTyConv unique_term'.\n          - doCtxConv D' unique_term'.\n\n          - { assert (L : ett.eqctx (ctxextend G0 B0) (ctxextend G B)).\n              - rewrite H. hyp.\n              - destruct (eqctx_ctxextend _ _ _ _  L) as [E M].\n                ceapply CongTySubst.\n                + ceapply CongSubstWeak.\n                  capply EqTySym.\n                  ceapply EqTyCtxConv ; ehyp.\n                + eapply (unique_term_ctx' _ (var k)).\n                  * hyp.\n                  * ehyp.\n                  * hyp.\n            }\n        }\n\n      (* TermAbs *)\n      - { inversion_clear H2' ; doConfig.\n          - doTyConv unique_term'.\n          - doCtxConv D' unique_term'.\n\n          - capply CongProd.\n            + capply EqTyRefl. hyp.\n            + eapply (unique_term_ctx' _ u).\n              * hyp.\n              * ehyp.\n              * capply EqCtxExtend.\n                -- hyp.\n                -- capply EqTyRefl. hyp.\n        }\n\n      (* TermApp *)\n      - { inversion_clear H2'.\n          - doTyConv unique_term'.\n          - doCtxConv D' unique_term'.\n\n          - { ceapply CongTySubst.\n              - ceapply CongSubstZero.\n                + eapply (unique_term_ctx' _ v) ; ehyp.\n                + ceapply EqRefl. hyp.\n              - admit.\n            }\n        }\n\n      (* TermRefl *)\n      - { inversion_clear H2' ; doConfig.\n          - doTyConv unique_term'.\n          - doCtxConv D' unique_term'.\n\n          - config apply EqTyRefl, TyId.\n            + hyp.\n            + hyp.\n        }\n\n      (* TermJ *)\n      - { inversion_clear H2'.\n          - doTyConv unique_term'.\n          - doCtxConv D' unique_term'.\n\n          - { ceapply CongTySubst.\n              - ceapply CongSubstZero.\n                + ceapply EqTyRefl.\n                  capply TyId ; hyp.\n                + ceapply EqRefl. hyp.\n              - ceapply CongTySubst.\n                + { ceapply EqSubstCtxConv.\n                    - ceapply CongSubstShift.\n                      + ceapply CongSubstZero.\n                        * ceapply EqTyRefl. ehyp.\n                        * ceapply EqRefl. hyp.\n                      + ceapply CongId.\n                        * { ceapply CongTySubst.\n                            - ceapply CongSubstWeak.\n                              ceapply EqTyRefl. hyp.\n                            - ceapply EqTyRefl. hyp.\n                          }\n                        * { ceapply CongTermSubst.\n                            - ceapply CongSubstWeak.\n                              ceapply EqTyRefl. hyp.\n                            - ceapply EqRefl. hyp.\n                          }\n                        * ceapply EqRefl. ceapply TermVarZero. hyp.\n                    - ceapply EqCtxExtend.\n                      + hyp.\n                      + { ceapply EqTyTrans.\n                          - ceapply EqTySubstId.\n                            + ceapply SubstZero. hyp.\n                            + ceapply TermSubst.\n                              * ceapply SubstWeak. hyp.\n                              * hyp.\n                            + ceapply TermVarZero. hyp.\n                          - ceapply CongId.\n                            + ceapply EqTySym.\n                              eapply ptt2ett.sane_eqtype.\n                              eapply ptt_admissible.EqTyWeakZero ; hyp.\n                            + eapply ptt2ett.sane_eqterm.\n                              { eapply ptt_admissible.EqSubstWeakZero ; try hyp.\n                                - eapply ett2ptt.sane_istype.\n                                  ceapply TySubst.\n                                  + ceapply SubstZero. hyp.\n                                  + ceapply TySubst.\n                                    * ceapply SubstWeak. hyp.\n                                    * hyp.\n                                - eapply ett2ptt.sane_isterm.\n                                  ceapply TermTyConv.\n                                  + ehyp.\n                                  + eapply ptt2ett.sane_eqtype.\n                                    eapply ptt_admissible.EqTyWeakZero ; hyp.\n                              }\n                            + { ceapply EqTyConv.\n                                - ceapply EqSubstZeroZero. hyp.\n                                - eapply ptt2ett.sane_eqtype.\n                                  eapply ptt_admissible.EqTyWeakZero ; hyp.\n                              }\n                        }\n                    - ceapply CtxRefl.\n                      capply CtxExtend.\n                      capply TyId.\n                      + ceapply TermSubst.\n                        * ceapply SubstWeak. hyp.\n                        * hyp.\n                      + ceapply TermVarZero. hyp.\n                  }\n                + ceapply EqTyRefl. hyp.\n            }\n        }\n\n      (* TermExfalso *)\n      - { inversion_clear H2'.\n          - doTyConv unique_term'.\n          - doCtxConv D' unique_term'.\n\n          - { capply EqTyRefl.\n              ceapply TyCtxConv.\n              + ehyp.\n              + hyp.\n            }\n        }\n\n      (* TermUnit *)\n      - { inversion_clear H2' ; doConfig.\n          - doTyConv unique_term'.\n          - doCtxConv D' unique_term'.\n\n          - (config apply EqTyRefl, TyUnit) ; hyp.\n        }\n\n      (* TermTrue *)\n      - { inversion_clear H2' ; doConfig.\n          - doTyConv unique_term'.\n          - doCtxConv D' unique_term'.\n\n          - (config apply EqTyRefl, TyBool) ; hyp.\n        }\n\n      (* TermFalse *)\n      - { inversion_clear H2' ; doConfig.\n          - doTyConv unique_term'.\n          - doCtxConv D' unique_term'.\n\n          - (config apply EqTyRefl, TyBool) ; hyp.\n        }\n\n      (* TermCond *)\n      - { inversion_clear H2' ; doConfig.\n          - doTyConv unique_term'.\n          - doCtxConv D' unique_term'.\n\n          - { ceapply CongTySubst.\n              - ceapply CongSubstZero.\n                + ceapply EqTyRefl. capply TyBool. hyp.\n                + ceapply EqRefl. hyp.\n              - ceapply EqTyRefl. hyp.\n            }\n        }\n\n      (* TermPair *)\n      - { inversion_clear H2' ; doConfig.\n          - doTyConv unique_term'.\n          - doCtxConv D' unique_term'.\n\n          - { capply EqTyRefl.\n              capply TySimProd.\n              - hyp.\n              - hyp.\n            }\n        }\n\n      (* TermProjOne *)\n      - { inversion_clear H2' ; doConfig.\n          - doTyConv unique_term'.\n          - doCtxConv D' unique_term'.\n\n          - { capply EqTyRefl.\n              ceapply TyCtxConv.\n              - ehyp.\n              - hyp.\n            }\n        }\n\n      (* TermProjTwo *)\n      - { inversion_clear H2' ; doConfig.\n          - doTyConv unique_term'.\n          - doCtxConv D' unique_term'.\n\n          - { capply EqTyRefl.\n              ceapply TyCtxConv.\n              - ehyp.\n              - hyp.\n            }\n        }\n\n      (* TermUniProd *)\n      - { inversion_clear H2' ; doConfig.\n          - doTyConv unique_term'.\n          - doCtxConv D' unique_term'.\n\n          - { capply EqTyRefl.\n              capply TyUni.\n              hyp.\n            }\n        }\n\n      (* TermUniProdProp *)\n      - { inversion_clear H2' ; doConfig.\n          - doTyConv unique_term'.\n          - doCtxConv D' unique_term'.\n\n          - { capply EqTyRefl.\n              capply TyUni.\n              hyp.\n            }\n        }\n\n      (* TermUniId *)\n      - { inversion_clear H2' ; doConfig.\n          - doTyConv unique_term'.\n          - doCtxConv D' unique_term'.\n\n          - { capply EqTyRefl.\n              capply TyUni.\n              hyp.\n            }\n        }\n\n      (* TermUniEmpty *)\n      - { inversion_clear H2' ; doConfig.\n          - doTyConv unique_term'.\n          - doCtxConv D' unique_term'.\n\n          - { capply EqTyRefl.\n              capply TyUni.\n              hyp.\n            }\n        }\n\n      (* TermUniUnit *)\n      - { inversion_clear H2' ; doConfig.\n          - doTyConv unique_term'.\n          - doCtxConv D' unique_term'.\n\n          - { capply EqTyRefl.\n              capply TyUni.\n              hyp.\n            }\n        }\n\n      (* TermUniBool *)\n      - { inversion_clear H2' ; doConfig.\n          - doTyConv unique_term'.\n          - doCtxConv D' unique_term'.\n\n          - { capply EqTyRefl.\n              capply TyUni.\n              hyp.\n            }\n        }\n\n      (* TermUniSimProd *)\n      - { inversion_clear H2' ; doConfig.\n          - doTyConv unique_term'.\n          - doCtxConv D' unique_term'.\n\n          - { capply EqTyRefl.\n              capply TyUni.\n              hyp.\n            }\n        }\n\n      (* TermUniSimProdProp *)\n      - { inversion_clear H2' ; doConfig.\n          - doTyConv unique_term'.\n          - doCtxConv D' unique_term'.\n\n          - { capply EqTyRefl.\n              capply TyUni.\n              hyp.\n            }\n        }\n\n      (* TermUniUni *)\n      - { inversion_clear H2' ; doConfig.\n          - doTyConv unique_term'.\n          - doCtxConv D' unique_term'.\n\n          - { capply EqTyRefl.\n              capply TyUni.\n              hyp.\n            }\n        }\n\n      (* TermUniProp *)\n      - { inversion_clear H2' ; doConfig.\n          - doTyConv unique_term'.\n          - doCtxConv D' unique_term'.\n\n          - { capply EqTyRefl.\n              capply TyUni.\n              hyp.\n            }\n        }\n  }\n\n (* unique_subst *)\n { destruct H1 ;\n   simple refine (fix unique_subst'' G' D2' H2' H3' {struct H2'} := _) ;\n   pose (\n     unique_subst' G' D2' H2' H3' :=\n       unique_subst'' G' D2' H2'\n                      (ett2ptt.sane_eqctx _ G' H3')\n   ).\n\n   (* H1: SubstZero *)\n   - { inversion_clear H2'.\n       - capply EqCtxExtend.\n         + hyp.\n         + capply EqTyRefl. hyp.\n       - doSubstConv unique_subst'.\n     }\n\n   (* H1: SubstWeak *)\n   - { inversion H2'; doConfig.\n       - rewrite <- H1 in H3'.\n         destruct (eqctx_ctxextend G A G0 A).\n         + hyp.\n         + subst. hyp.\n       - doSubstConv unique_subst'.\n     }\n\n   (* H1: SubstShift *)\n   - { inversion H2'; doConfig.\n       - rewrite <- H3 in H3'.\n         destruct (eqctx_ctxextend G (Subst A sbs) G0 (Subst A sbs)).\n         + hyp.\n         + capply EqCtxExtend.\n           * apply (@unique_subst G _ sbs) with (G'0 := G).\n             -- hyp.\n             -- pex. ceapply SubstCtxConv.\n                ++ ehyp.\n                ++ ceapply CtxSym. hyp.\n                ++ capply CtxRefl. hyp.\n             -- pex. capply CtxRefl. hyp.\n           * capply EqTyRefl. hyp.\n       - doSubstConv unique_subst'.\n     }\n\n   (* H1: SubstId *)\n   - { inversion H2'; doConfig.\n       - rewrite <- H1. hyp.\n       - doSubstConv unique_subst'.\n     }\n\n   (* H1: SubstComp *)\n   - { inversion_clear H2'.\n       - eapply (unique_subst _ _ _ H1_0).\n         + ehyp.\n         + eapply ett2ptt.sane_eqctx.\n           eapply (unique_subst _ _ _ H1_).\n           * ehyp.\n           * hyp.\n       - doSubstConv unique_subst'.\n     }\n\n   (* H1: SubstCtxConv *)\n   - config eapply @CtxTrans with (D := D1).\n     + ceapply CtxSym. hyp.\n     + eapply unique_subst.\n       * ehyp.\n       * ehyp.\n       * capply ett2ptt.sane_eqctx.\n         (config eapply @CtxTrans with (D := G2)) ; hyp.\n\n }\n\nDefined.\n\n(* The main theorem as it will probably be used. *)\nCorollary unique_term {G A B u} :\n  ptt.isterm G u A ->\n  ptt.isterm G u B ->\n  ett.eqtype G A B.\n\nProof.\n  intros H1 H2.\n  eapply unique_term_ctx.\n  - eassumption.\n  - eassumption.\n  - apply CtxRefl. hyps.\nDefined.\n\nEnd Uniqueness.\n", "meta": {"author": "TheoWinterhalter", "repo": "formal-type-theory", "sha": "93ac197dfde912d77af9b0f4fd9f7d2422ba7dfc", "save_path": "github-repos/coq/TheoWinterhalter-formal-type-theory", "path": "github-repos/coq/TheoWinterhalter-formal-type-theory/formal-type-theory-93ac197dfde912d77af9b0f4fd9f7d2422ba7dfc/src/concise_uniqueness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2735521581443009}}
{"text": "(* Some issues with polymorphic inductive types *)\n\n(* 1- upper constraints with respect to non polymorphic inductive types *)\n\nUnset Elimination Schemes.\nDefinition Ty := Type (* Top.1 *).\n\nInductive Q (A:Type (* Top.2 *)) : Prop := q : A -> Q A.\nInductive T (B:Type (* Top.3 *)) := t : B -> Q (T B) -> T B.\n(* ajoute Top.4 <= Top.2 inutilement:\n   4 est l'univers utilisé dans le calcul du type polymorphe de T *)\nDefinition C := T Ty.\n(* ajoute Top.1 < Top.3 :\n   Top.3 jour le rôle de pivot pour propager les contraintes supérieures qu'on\n   a sur l'argument B de T: Top.3 sera réutilisé plus tard comme majorant\n   des arguments effectifs de T, propageant à cette occasion les contraintes\n   supérieures sur Top.3 *)\n\n(* We need either that Q is polymorphic on A (though it is in Type) or\n   that the constraint Top.1 < Top.2 is set (and it is not set!) *)\n\n(* 2- upper constraints with respect to unfoldable constants *)\n\nDefinition f (A:Type (* Top.1 *)) := True.\nInductive R := r : f R -> R.\n(* ajoute Top.3 <= Top.1 inutilement:\n   Top.3 est l'univers utilisé dans le calcul du type polymorphe de R *)\n\n(* mais il manque la contrainte que l'univers de R est plus petit que Top.1\n   ce qui l'empêcherait en fait d'être vraiment polymorphe *)\n\n(* 3- constraints with respect to global constants *)\n\nInductive S (A:Ty) := s : A -> S A.\n\n(* Q est considéré polymorphique vis à vis de A alors que le type de A\n   n'est pas une variable mais un univers déjà existant *)\n\n(* Malgré tout la contrainte Ty < Ty est ajoutée (car Ty est vu comme\n   un pivot pour propager les contraintes sur le type A, comme si Q était\n   vraiment polymorphique, ce qu'il n'est pas parce que Ty est une\n   constante). Et heureusement qu'elle est ajouté car elle évite de\n   pouvoir typer \"Q Ty\" *)\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/test-suite/ideal-features/universes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.27355215069069627}}
{"text": "(*********************************************************************************************************************************)\n(* ProgrammingLanguageFlattening                                                                                                 *)\n(*********************************************************************************************************************************)\n\nGeneralizable All Variables.\nRequire Import Preamble.\nRequire Import General.\nRequire Import Categories_ch1_3.\nRequire Import InitialTerminal_ch2_2.\nRequire Import Functors_ch1_4.\nRequire Import Isomorphisms_ch1_5.\nRequire Import ProductCategories_ch1_6_1.\nRequire Import OppositeCategories_ch1_6_2.\nRequire Import Enrichment_ch2_8.\nRequire Import Subcategories_ch7_1.\nRequire Import NaturalTransformations_ch7_4.\nRequire Import NaturalIsomorphisms_ch7_5.\nRequire Import BinoidalCategories.\nRequire Import PreMonoidalCategories.\nRequire Import MonoidalCategories_ch7_8.\nRequire Import Coherence_ch7_8.\nRequire Import Enrichment_ch2_8.\nRequire Import RepresentableStructure_ch7_2.\nRequire Import FunctorCategories_ch7_7.\n\nRequire Import Reification.\nRequire Import NaturalDeduction.\nRequire Import NaturalDeductionCategory.\nRequire Import GeneralizedArrow.\nRequire Import ProgrammingLanguage.\nRequire Import ProgrammingLanguageReification.\nRequire Import SectionRetract_ch2_4.\nRequire Import GeneralizedArrowFromReification.\nRequire Import Enrichments.\nRequire Import ReificationsAndGeneralizedArrows.\n\nSection Flattening.\n\n  Context `(Guest:ProgrammingLanguage) `(Host :ProgrammingLanguage).\n  Context (GuestHost:TwoLevelLanguage Guest Host).\n\n  Definition FlatObject (x:TypesL Host) :=\n    forall y1 y2, not ((reification_r_obj GuestHost y1 y2)=x).\n\n  Instance FlatSubCategory : FullSubcategory (TypesL Host) FlatObject.\n\n    Context  (F:RetractionOfCategories (TypesL Host) (FullSubCategoriesAreCategories FlatSubCategory)).\n\n    Definition FlatteningOfReification HostMonic HostMonoidal :=\n      (ga_functor\n        (@garrow_from_reification\n          (TypesEnrichedInJudgments Guest)\n          (TypesEnrichedInJudgments Host)\n          HostMonic HostMonoidal GuestHost))\n        >>>> F.\n\n    Lemma FlatteningIsNotDestructive HostMonic HostMonoidal : \n      FlatteningOfReification HostMonic HostMonoidal >>>> retraction_retraction F >>>> HomFunctor _ []\n      ≃ (reification_rstar GuestHost).\n      apply if_inv.\n      set (@roundtrip_reification_to_reification (TypesEnrichedInJudgments Guest) (TypesEnrichedInJudgments Host)\n        HostMonic HostMonoidal GuestHost) as q.\n      unfold mf_F in *; simpl in *.\n      eapply if_comp.\n      apply q.\n      clear q.\n      unfold mf_F; simpl.\n      unfold pmon_I.\n      apply (if_respects\n        (garrow_functor (TypesEnrichedInJudgments Guest) HostMonic HostMonoidal GuestHost)\n        (FlatteningOfReification HostMonic HostMonoidal >>>> retraction_retraction F)\n        (HomFunctor (TypesL Host) [])\n        (HomFunctor (TypesL Host) [])); [ idtac | apply (if_id _) ].\n      unfold FlatteningOfReification.\n      unfold mf_F; simpl.\n      apply if_inv.\n      eapply if_comp.\n      apply (if_associativity (garrow_functor (TypesEnrichedInJudgments Guest) HostMonic HostMonoidal GuestHost) F\n               (retraction_retraction F)).\n      eapply if_comp; [ idtac | apply if_right_identity ].\n      apply (if_respects\n        (garrow_functor (TypesEnrichedInJudgments Guest) HostMonic HostMonoidal GuestHost)\n        (garrow_functor (TypesEnrichedInJudgments Guest) HostMonic HostMonoidal GuestHost)\n        (F >>>> retraction_retraction F)\n        (functor_id _)).\n      apply (if_id _).\n      apply retraction_composes.\n      Qed.\n\nEnd Flattening.\n\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/ProgrammingLanguageFlattening2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.27352689671482494}}
{"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.TOpenTClose.\nRequire Export SystemFR.OpenTOpen.\nRequire Export SystemFR.StrictPositivity.\nRequire Export SystemFR.NoTypeFVarLemmas.\nRequire Export SystemFR.ReducibilityUnused.\n\nOpaque makeFresh.\nOpaque PeanoNat.Nat.eq_dec.\nOpaque reducible_values.\nOpaque strictly_positive.\n\nDefinition non_empty ρ A := exists v, [ ρ ⊨ v : A ]v.\n\nLemma instantiate_non_empty:\n  forall ρ A,\n    non_empty ρ A ->\n    exists a, [ ρ ⊨ a : A ]v.\nProof.\n  unfold non_empty; steps; eauto.\nQed.\n\nLtac instantiate_non_empty :=\n  match goal with\n  | H: non_empty ?ρ ?A |- _ =>\n    poseNew (Mark (ρ,A) \"instantiate_non_empty\");\n    pose proof (instantiate_non_empty _ _ H)\n  end.\n\nLemma non_empty_extend:\n  forall ρ A x RC,\n    non_empty ρ A ->\n    reducibility_candidate RC ->\n    valid_interpretation ρ ->\n    ~(x ∈ pfv A type_var) ->\n    non_empty ((x, RC) :: ρ) A.\nProof.\n  unfold non_empty; repeat step || exists v || apply reducible_unused2.\nQed.\n\nLemma strictly_positive_open_aux:\n  forall n T vars rep k,\n    type_nodes T < n ->\n    is_erased_type T ->\n    is_erased_term rep ->\n    strictly_positive T vars ->\n    strictly_positive (open k T rep) vars.\nProof.\n  induction n; destruct T; repeat step || simp_spos || apply no_type_fvar_open || apply IHn ;\n    try lia;\n    try solve [ left; repeat step || apply no_type_fvar_open ];\n    try solve [ right; eexists; eauto; repeat step || apply no_type_fvar_open ].\n\n  right. exists X; repeat step || fv_open || list_utils || rewrite is_erased_term_tfv in * by steps.\n  rewrite <- open_topen;\n    repeat step || apply IHn || autorewrite with bsize in * || apply is_erased_type_topen;\n    eauto with twf wf lia.\nQed.\n\nLemma strictly_positive_open:\n  forall T vars rep k,\n    is_erased_type T ->\n    is_erased_term rep ->\n    strictly_positive T vars ->\n    strictly_positive (open k T rep) vars.\nProof.\n  eauto using strictly_positive_open_aux.\nQed.\n\nLemma push_all_cons:\n  forall X (RC: tree -> Prop) ρ (P: tree -> Prop),\n    (X, fun v => forall a, P a -> RC v) :: push_all P ρ = push_all P ((X, fun a => RC) :: ρ).\nProof.\n  steps.\nQed.\n\nLemma push_is_candidate:\n  forall (ρ : interpretation) (A a : tree) (RC : tree -> Prop),\n    reducibility_candidate RC ->\n    [ ρ ⊨ a : A ]v ->\n    reducibility_candidate (fun v : tree => [ ρ ⊨ a : A ]v -> RC v).\nProof.\n  repeat step || unfold non_empty in * || unfold reducibility_candidate in * || instantiate_any;\n    eauto with fv wf.\nQed.\n\nLemma push_all_is_candidate:\n  forall (ρ : interpretation) (A : tree) (RC : tree -> Prop),\n    reducibility_candidate RC ->\n    non_empty ρ A ->\n    reducibility_candidate (fun v : tree => forall a, [ ρ ⊨ a : A ]v -> RC v).\nProof.\n  repeat step || unfold non_empty in * || unfold reducibility_candidate in * || instantiate_any;\n    eauto with fv wf.\nQed.\n\nLtac find_exists2 :=\n  match goal with\n  | H1: [ ?ρ ⊨ ?a : ?T1 ]v,\n    H2: [ ?ρ ⊨ ?v : open 0 ?T2 ?a ]v\n    |- _ =>\n    exists a\n  end.\n\nLemma no_type_fvar_strictly_positive:\n  forall T vars,\n    is_erased_type T ->\n    no_type_fvar T vars ->\n    strictly_positive T vars.\nProof.\n  induction T; repeat step || simp_spos || destruct_tag || unfold no_type_fvar in * || apply_any || left;\n    try solve [ eapply_any; eauto; repeat step || list_utils ].\nQed.\n\nLtac t_red_is_val :=\n  eapply red_is_val; eauto;\n    repeat step || apply valid_interpretation_append || eapply valid_interpretation_one ||\n    eauto with b_valid_interp; steps;\n    eauto with apply_any.\n\n#[export]\nHint Extern 50 => solve [ t_red_is_val ]: b_red_is_val.\n\nLemma strictly_positive_rename_aux:\n  forall n T T' vars vars' rel,\n    type_nodes T < n ->\n    strictly_positive T vars ->\n    equal_with_relation type_var rel T T' ->\n    similar_sets rel vars vars' ->\n    strictly_positive T' vars'.\nProof.\n  induction n;\n    try solve [ intros; lia ];\n    destruct T; inversion 3;\n    repeat match goal with\n           | _ => step || simp_spos || destruct_tag\n           | H1: equal_with_relation _ ?rel ?T ?T',\n             H2: strictly_positive ?T ?vars |-\n               strictly_positive ?T' ?vars' =>\n             apply IHn with T vars rel\n            end;\n    eauto using no_type_fvar_rename;\n    try lia.\n\n  right.\n  exists (makeFresh ((X :: nil) :: pfv Ts' type_var :: nil));\n    repeat step; try finisher.\n\n  match goal with\n  | H1: equal_with_relation _ ?rel _ _,\n    H2: strictly_positive ?T (?X :: nil) |-\n      strictly_positive (topen 0 ?T' (fvar ?M type_var)) ?vars' =>\n    apply IHn with T (X :: nil) ((X,M) :: rel)\n  end;\n    repeat unfold similar_sets || step || autorewrite with bsize in * || apply equal_with_relation_topen;\n      try lia;\n      try finisher.\nQed.\n\nLemma strictly_positive_rename:\n  forall T T' vars vars' rel,\n    strictly_positive T vars ->\n    equal_with_relation type_var rel T T' ->\n    similar_sets rel vars vars' ->\n    strictly_positive T' vars'.\nProof.\n  eauto using strictly_positive_rename_aux.\nQed.\n\nLemma no_type_fvar_swap:\n  forall T vars i j,\n    no_type_fvar T vars ->\n    no_type_fvar (swap_type_holes T i j) vars.\nProof.\n  unfold no_type_fvar; repeat step || rewrite pfv_swap_type_holes in *; eauto.\nQed.\n\nLemma strictly_positive_swap_aux:\n  forall n T vars i j,\n    type_nodes T < n ->\n    strictly_positive T vars ->\n    strictly_positive (swap_type_holes T i j) vars.\nProof.\n  induction n; destruct T; repeat step || simp_spos || apply_any;\n    try lia;\n    eauto using no_type_fvar_swap.\n  right; 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 strictly_positive_swap:\n  forall T vars i j,\n    strictly_positive T vars ->\n    strictly_positive (swap_type_holes T i j) vars.\nProof.\n  eauto using strictly_positive_swap_aux.\nQed.\n\nLemma strictly_positive_topen_aux:\n  forall n T vars k X,\n    type_nodes T < n ->\n    strictly_positive T vars ->\n    ~(X ∈ vars) ->\n    strictly_positive (topen k T (fvar X type_var)) vars.\nProof.\n  induction n; destruct T; repeat step || simp_spos || apply IHn;\n    eauto using no_type_fvar_in_topen;\n    try lia.\n  right; exists (makeFresh ((X0 :: nil) :: (X :: nil) :: pfv T3 type_var :: pfv (topen (S k) T3 (fvar X type_var)) type_var :: nil)); steps; try finisher.\n\n  rewrite open_swap; repeat step.\n  apply IHn; repeat step || autorewrite with bsize in *;\n    try lia;\n    try finisher.\n  rewrite topen_swap; steps.\n  apply strictly_positive_swap.\n  match goal with\n  | H2: strictly_positive (topen 0 ?T (fvar ?X type_var)) (?X :: nil) |-\n      strictly_positive (topen 0 ?T (fvar ?M type_var)) (?M :: nil) =>\n    apply strictly_positive_rename with (topen 0 T (fvar X type_var)) (X :: nil) ((X,M) :: idrel (pfv T type_var))\n  end;\n    unfold similar_sets;\n    repeat step || apply equal_with_relation_topen;\n    try finisher;\n    eauto using equal_with_relation_refl2;\n    eauto using equal_with_idrel.\nQed.\n\nLemma support_push_one:\n  forall ρ a,\n    support (push_one a ρ) = support ρ.\nProof.\n  unfold push_one; repeat step || rewrite support_map_values.\nQed.\n\nLemma support_push_all:\n  forall ρ P,\n    support (push_all P ρ) = support ρ.\nProof.\n  unfold push_all; repeat step || rewrite support_map_values.\nQed.\n\nLemma strictly_positive_topen:\n  forall T vars k X,\n    strictly_positive T vars ->\n    ~(X ∈ vars) ->\n    strictly_positive (topen k T (fvar X type_var)) vars.\nProof.\n  eauto using strictly_positive_topen_aux.\nQed.\n\nDefinition pre_interpretation := list (nat * (tree -> tree -> Prop)).\n\nFixpoint forall_implies (P: tree -> Prop) (pre_ρ: pre_interpretation) (ρ: interpretation) :=\n  match pre_ρ, ρ with\n  | nil, nil => True\n  | (X,pre_rc) :: pre_ρ', (Y,rc) :: ρ' =>\n      X = Y /\\\n      forall_implies P pre_ρ' ρ' /\\\n      forall (v: tree), (forall a, P a -> pre_rc a v) -> rc v\n  | _, _ => False\n  end.\n\nLemma forall_implies_apply:\n  forall P pre_ρ ρ X pre_rc rc v,\n    forall_implies P pre_ρ ρ ->\n    lookup PeanoNat.Nat.eq_dec pre_ρ X = Some pre_rc ->\n    lookup PeanoNat.Nat.eq_dec ρ X = Some rc ->\n    (forall a, P a -> pre_rc a v) ->\n    rc v.\nProof.\n  induction pre_ρ; destruct ρ; repeat step || eapply_any.\nQed.\n\nLtac t_forall_implies_apply :=\n  match goal with\n  | H1: forall_implies ?P ?pre_ρ ?ρ,\n    H2: lookup _ ?pre_ρ ?X = Some ?prc,\n    H3: lookup _ ?ρ ?X = Some ?rc |- ?rc ?v =>\n    apply (forall_implies_apply _ _ _ _ _ _ _ H1 H2 H3)\n  end.\n\nLemma forall_implies_support:\n  forall P pre_ρ ρ,\n    forall_implies P pre_ρ ρ ->\n    support pre_ρ = support ρ.\nProof.\n  induction pre_ρ; destruct ρ; repeat step || f_equal.\nQed.\n\nLtac t_forall_implies_support :=\n  match goal with\n  | H: forall_implies ?P ?pre_ρ ?ρ |- _ =>\n    poseNew (Mark (pre_ρ,ρ) \"forall_implies_suppoft\");\n    pose proof (forall_implies_support _ _ _ H)\n  end.\n\nLemma forall_implies_equiv:\n  forall P1 P2 pre_ρ ρ,\n    forall_implies P1 pre_ρ ρ ->\n    (forall x, P1 x <-> P2 x) ->\n    forall_implies P2 pre_ρ ρ.\nProof.\n  induction pre_ρ; destruct ρ; steps; eauto with eapply_any.\nQed.\n\nLtac t_forall_implies_equiv :=\n  match goal with\n  | H1: forall_implies ?P1 ?pre_ρ ?ρ |- forall_implies _ ?pre_ρ ?ρ =>\n      apply forall_implies_equiv with P1\n  end.\n\nLemma strictly_positive_append_aux:\n  forall n T vars1 vars2,\n    type_nodes T < n ->\n    strictly_positive T vars1 ->\n    strictly_positive T vars2 ->\n    strictly_positive T (vars1 ++ vars2).\nProof.\n  induction n; destruct T;\n    repeat lia || step || destruct_tag || simp_spos || apply_any;\n      eauto using no_type_fvar_append.\nQed.\n\nLemma strictly_positive_append:\n  forall T vars1 vars2,\n    strictly_positive T vars1 ->\n    strictly_positive T vars2 ->\n    strictly_positive T (vars1 ++ vars2).\nProof.\n  eauto using strictly_positive_append_aux.\nQed.\n\nLemma strictly_positive_cons:\n  forall T X vars,\n    strictly_positive T (X :: nil) ->\n    strictly_positive T vars ->\n    strictly_positive T (X :: vars).\nProof.\n  intros.\n  change (X :: vars) with ((X :: nil) ++ vars);\n    eauto using strictly_positive_append.\nQed.\n\nLemma strictly_positive_topen2:\n  forall T k X vars,\n    ~(X ∈ vars) ->\n    strictly_positive T vars ->\n    strictly_positive (topen k T (fvar X type_var)) (X :: nil) ->\n    strictly_positive (topen k T (fvar X type_var)) (X :: vars).\nProof.\n  intros; apply strictly_positive_cons;\n    repeat step || apply strictly_positive_topen.\nQed.\n\nLemma strictly_positive_rename_one:\n  forall T X Y vars,\n    strictly_positive (topen 0 T (fvar X type_var)) (X :: vars) ->\n    ~(X ∈ pfv T type_var) ->\n    ~(Y ∈ pfv T type_var) ->\n    strictly_positive (topen 0 T (fvar Y type_var)) (Y :: vars).\nProof.\n  intros.\n  apply strictly_positive_rename with (topen 0 T (fvar X type_var)) (X :: vars) ((X,Y) :: idrel (pfv T type_var));\n    repeat step || apply equal_with_relation_topen || unfold similar_sets || rewrite swap_idrel in * || t_idrel_lookup2;\n    eauto using equal_with_idrel.\nQed.\n\nLemma strictly_positive_no_fv:\n  forall T vars,\n    is_erased_type T ->\n    (forall X, X ∈ pfv T type_var -> False) ->\n    strictly_positive T vars.\nProof.\n  intros.\n  apply no_type_fvar_strictly_positive; repeat step || unfold no_type_fvar; 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/StrictPositivityLemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.5, "lm_q1q2_score": 0.27336908337778565}}
{"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 substitution.\n\n\nLemma cover_vars_upto_cequiv {o} :\n  forall vs (a b : @NTerm o) sub,\n    cover_vars_upto (mk_cequiv a b) sub vs\n    <=> cover_vars_upto a sub vs\n        # cover_vars_upto b sub vs.\nProof.\n  intros; unfold cover_vars_upto; simpl.\n  allrw remove_nvars_nil_l; allrw app_nil_r.\n  allrw subvars_app_l; sp.\nQed.\n\n(*\n*** Local Variables:\n*** coq-load-path: (\".\" \"../util/\" \"../terms/\" \"../computation/\" \"../cequiv/\" \"../close/\")\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/terms/cover.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.27331051264885214}}
{"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 multicopy multicopy_util auth_ext.\n\n(** Multicopy operations *)\n\nParameter search : val.\nParameter upsert : val.\n\n(** \\overline{search} in the paper *)\nDefinition search' : val :=\n  λ: \"k\",\n    let: \"t_id\" := NewProph in\n    let: \"p\" := NewProph in\n    let: \"v\" := search \"k\" in\n    resolve_proph: \"p\" to: \"v\";;\n    \"v\".  \n\nSection multicopy_client_level.\n  Context {Σ} `{heapG Σ, !multicopyG Σ}.\n  Notation iProp := (iProp Σ).\n\n  (** Low-level specs of multicopy operations *)\n\n  Parameter search_recency: ∀ N γ_te γ_he γ_s Prot Inv_tpl k v0 t0, \n    ⊢ ⌜k ∈ KS⌝ -∗ \n        mcs_inv N γ_te γ_he γ_s Prot Inv_tpl -∗\n          SR γ_s (k, (v0, t0)) -∗\n              <<< True >>> \n                  search #k @ ⊤ ∖ ↑(mcsN N)\n              <<< ∃ (v: V) (t: T), SR γ_s (k, (v, t)) ∗ ⌜t0 ≤ t⌝ , RET #v >>>.\n\n  Parameter upsert_spec: ∀ N γ_te γ_he γ_s Prot Inv_tpl k (v: V),\n    ⊢ ⌜k ∈ KS⌝ -∗ \n        (ghost_update_protocol N γ_te γ_he Prot k) -∗ \n          mcs_inv N γ_te γ_he γ_s Prot Inv_tpl -∗\n              <<< ∀ t H, MCS γ_te γ_he t H >>> \n                     upsert #k #v @ ⊤ ∖ (↑(mcsN N))\n              <<< MCS γ_te γ_he (t + 1) (H ∪ {[(k, (v, t))]}), RET #() >>>.\n                \n  (** Proof of high-level specs for multicopy opeartions *)                \n\n  Lemma search_spec_intermediate N γ_te γ_he γ_s Inv_tpl γ_td γ_ght (k: K) :\n  ⊢ ⌜k ∈ KS⌝ -∗ \n      mcs_inv N γ_te γ_he γ_s (Prot_help N γ_te γ_he γ_td γ_ght) Inv_tpl -∗ \n          <<< ∀ t H, MCS γ_te γ_he t H >>>\n                search' #k @ ⊤ ∖ (↑(mcsN N) ∪ ↑(threadN N))\n          <<<  ∃ (v': V) (t': T), MCS γ_te γ_he t H \n                            ∗ ⌜map_of_set H !!! k = (v', t')⌝, RET #v' >>>.\n  Proof.\n    iIntros \"% #HInv\" (Φ) \"AU\". wp_lam.\n    rename H0 into k_in_KS.\n    wp_apply wp_new_proph1; try done.\n    iIntros (tid vtid)\"Htid\". wp_pures.\n    wp_apply (typed_proph_wp_new_proph1 IntTypedProph); first done.\n    iIntros (vp p)\"Hproph\". wp_pures. \n    iApply fupd_wp.\n    iInv \"HInv\" as (T0 H0) \"(mcs_high & Htpl)\".\n    iDestruct \"mcs_high\" as \"(>MCS_auth & >HH & >HInit & >HClock & >HUniq & Prot)\".\n    iAssert (⌜∃ v0 t0, ((k, (v0, t0)) ∈ H0 ∧ (∀ v t, (k, (v, t)) ∈ H0 → t ≤ t0) \n                ∧ map_of_set H0 !! k = Some (v0, t0))⌝)%I as \"%\".\n    { pose proof (map_of_set_lookup_cases H0 k) as H'.\n      destruct H' as [H' | H']; try done.\n      iDestruct \"HInit\" as %HInit.\n      destruct H' as [H' _].\n      pose proof H' bot 0 as H'.\n      pose proof HInit k k_in_KS as HInit.\n      contradiction. }\n\n    destruct H1 as [v0 [t0 [kt0_in_H [Max_t0 H_k]]]].\n    iMod (own_update γ_s (● H0) (● H0 ⋅ ◯ {[(k, (v0, t0))]}) with \"[$HH]\") as \"HH\".\n    { apply (auth_update_frac_alloc _ H0 ({[(k, (v0, t0))]})).\n      apply gset_included. clear -kt0_in_H. set_solver. }\n    iDestruct \"HH\" as \"(HH & #SR0)\".\n                     \n    destruct (decide (v0 = vp)) as [v0_eq_vp | v0_neq_vp].\n    - iMod \"AU\" as (T' H') \"[MCS [_ Hcomm]]\"; first by set_solver.\n      iAssert (⌜T' = T0 ∧ H' = H0⌝)%I as \"%\". \n      { iPoseProof (MCS_agree with \"[$MCS_auth] [$MCS]\") as \"(% & %)\".\n        by iPureIntro. }\n      destruct H1 as [H'' H''']. subst T' H'.\n      assert (map_of_set H0 !!! k = (v0, t0)) as M_k.\n      { rewrite lookup_total_alt. rewrite H_k.\n        by simpl. }\n      iSpecialize (\"Hcomm\" $! v0 t0). \n      iMod (\"Hcomm\" with \"[MCS]\") as \"HΦ\".\n      { iFrame. by iPureIntro. } \n      iModIntro. iSplitR \"HΦ Hproph\".\n      iNext; iExists T0, H0; iFrame.\n      iModIntro.\n      awp_apply search_recency without \"HΦ\"; try done.\n      iAaccIntro with \"\"; try done.\n      { iIntros \"_\". iModIntro; try eauto with iFrame. } \n      iIntros (v t) \"(#SR & %)\". rename H1 into t0_le_t.\n      iModIntro. iIntros \"HΦ\". wp_pures.\n      wp_apply (typed_proph_wp_resolve1 IntTypedProph with \"Hproph\"); try done.\n      wp_pures. iModIntro. iIntros \"%\". rename H1 into vp_eq_v. \n      wp_pures. iModIntro.\n      by subst v vp.\n    - iDestruct \"Prot\" as (R hγt)\"(>HR & >Hγt \n                                      & >Domm_hγt & Hstar_reg)\".\n      iAssert (▷ (⌜tid ∉ R⌝ \n                ∗ ([∗ set] t_id ∈ R, Reg N γ_te γ_he γ_ght H0 t_id) \n                ∗ proph1 tid vtid))%I with \"[Hstar_reg Htid]\" \n                as \"(>% & Hstar_reg & Htid)\".\n      { destruct (decide (tid ∈ R)); try done.\n        - iEval (rewrite (big_sepS_elem_of_acc _ (R) tid); \n                                last by eauto) in \"Hstar_reg\".\n          iDestruct \"Hstar_reg\" as \"(Hreg & Hstar_reg')\".\n          iDestruct \"Hreg\" as (? ? ? ? ? ? ? ?)\"(H' & _)\".\n          iAssert (▷ False)%I with \"[H' Htid]\" as \"HF\".\n          iApply (proph1_exclusive tid with \"[Htid]\"); try done.\n          iNext. iExFalso; try done.\n        - iFrame. iNext. by iPureIntro. }\n      rename H1 into tid_notin_R.\n      iMod (own_update γ_td (● R) (● (R ∪ {[tid]})) with \"[$HR]\") as \"HR\".\n      { apply (auth_update_auth _ _ (R ∪ {[tid]})).\n        apply gset_local_update. set_solver. }\n      iMod (own_update γ_td (● (R ∪ {[tid]})) (● (R ∪ {[tid]}) ⋅ ◯ {[tid]}) \n                with \"[$HR]\") as \"(HR & #FP_t)\".\n      { apply (auth_update_frac_alloc _ (R ∪ {[tid]}) ({[tid]})).\n        apply gset_included. clear; set_solver. }\n\n      iMod (own_alloc (to_frac_agree (1) (H0))) \n              as (γ_sy)\"Hfr_t\". { try done. }        \n      iEval (rewrite <-Qp_half_half) in \"Hfr_t\".      \n      iEval (rewrite (frac_agree_op (1/2) (1/2) _)) in \"Hfr_t\". \n      iDestruct \"Hfr_t\" as \"(Hreg_sy1 & Hreg_sy2)\".\n      \n      iDestruct \"Domm_hγt\" as %Domm_hγt.\n      set (<[ tid := to_agree γ_sy ]> hγt) as hγt'.\n      iDestruct (own_update _ _ \n        (● hγt' ⋅ ◯ {[ tid := to_agree γ_sy ]})\n               with \"Hγt\") as \">Hγt\".\n      { apply auth_update_alloc. \n        rewrite /hγt'.\n        apply alloc_local_update; last done.\n        rewrite <-Domm_hγt in tid_notin_R.\n        by rewrite not_elem_of_dom in tid_notin_R*; \n        intros tid_notin_R. }\n      iDestruct \"Hγt\" as \"(Hγt & #Hreg_gh)\".  \n                  \n      iDestruct (laterable with \"AU\") as (AU_later) \"[AU #AU_back]\".\n      iMod (own_alloc (Excl ())) as (γ_tk') \"Token\"; first try done.\n      iAssert (⌜(∀ t', (k, (vp, t')) ∈ H0 → t' < t0)⌝)%I as %HPending. \n      { iDestruct \"HUniq\" as %HUniq. iPureIntro. \n        intros t' kvpt'_in_H. pose proof Max_t0 vp t' kvpt'_in_H as Max_t0.\n        destruct (decide (t0 = t')).\n        - subst t'. pose proof HUniq k t0 v0 vp kt0_in_H kvpt'_in_H as HUniq.\n          done.\n        - clear - Max_t0 n. lia. }\n      iMod (inv_alloc (threadN N) _\n              (∃ H, State γ_sy tid γ_tk' AU_later (Φ) H k vp t0) \n                                    with \"[AU Hreg_sy1]\") as \"#HthInv\".\n      { iNext. iExists H0. iFrame \"Hreg_sy1\". iLeft. \n        unfold Pending. iFrame. by iPureIntro. }\n\n      iModIntro. iSplitR \"Hproph Token\". iNext.\n      iExists T0, H0. iFrame \"Htpl\". iFrame.\n      iExists (R ∪ {[tid]}), hγt'. iFrame.\n      iSplitR. iPureIntro. subst hγt'.\n      apply leibniz_equiv. rewrite dom_insert.\n      rewrite Domm_hγt. clear; set_solver.\n      rewrite (big_sepS_delete _ (R ∪ {[tid]}) tid); last by set_solver.\n      iSplitR \"Hstar_reg\". unfold Reg.\n      iExists AU_later, Φ, k, vp, t0, vtid, γ_tk', γ_sy. iFrame \"∗#\".\n      assert ((R ∪ {[tid]}) ∖ {[tid]} = R) as H' \n                  by (clear -tid_notin_R; set_solver).\n      by rewrite H'.\n            \n      iModIntro. awp_apply search_recency; try done.\n      iAaccIntro with \"\"; try done.\n      { iIntros \"_\". iModIntro; try eauto with iFrame. } \n      iIntros (v t) \"(#SR & %)\". rename H1 into t0_le_t.\n      iModIntro. wp_pures.\n      wp_apply (typed_proph_wp_resolve1 IntTypedProph with \"Hproph\"); try done.\n      wp_pures. iModIntro. iIntros \"%\". subst v. (* rename H1 into vp_eq_v. *)\n      iApply fupd_wp.\n      iInv \"HthInv\" as (H1)\"(>Hth_sy & Hth_or)\".\n      iInv \"HInv\" as (T1 H1') \"(mcs_high & Htpl)\".\n      iDestruct \"mcs_high\" as \"(>MCS_auth & >HH & >Hist & >MaxTS & >Uniq & Prot)\".\n      iDestruct \"Prot\" as (R1 hγt1)\"(>HR & >Hγt \n                                      & >Domm_hγt & Hstar_reg)\".\n      iAssert (⌜tid ∈ R1⌝)%I as \"%\".\n      { iPoseProof (own_valid_2 _ _ _ with \"[$HR] [$FP_t]\") 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        \n      iAssert (▷ (⌜H1' = H1⌝\n               ∗ ([∗ set] t_id ∈ R1, Reg N γ_te γ_he γ_ght H1' t_id)\n               ∗ own (γ_sy) (to_frac_agree (1 / 2) H1) ))%I\n                with \"[Hstar_reg Hth_sy]\" as \"(>% & Hstar_reg & >Hth_sy)\". \n      { iEval (rewrite (big_sepS_elem_of_acc _ (R1) tid); \n                                last by eauto) in \"Hstar_reg\".\n        iDestruct \"Hstar_reg\" as \"(Hreg_t & Hstar_reg')\".\n        iDestruct \"Hreg_t\" as (P' Q' k' vp' t0' vtid' γ_tk'' γ_sy')\n                          \"(Hreg_proph & >Hreg_gh' & >Hreg_sy & Ht_reg')\".\n\n        iCombine \"Hreg_gh\" \"Hreg_gh'\" 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        subst γ_sy'.\n                  \n        iAssert (⌜H1' = H1⌝)%I as \"%\".\n        { iPoseProof (own_valid_2 _ _ _ with \"[$Hth_sy] [$Hreg_sy]\") as \"V_H\".\n          iDestruct \"V_H\" as %V_H.\n          apply frac_agree_op_valid in V_H. destruct V_H as [_ V_H].\n          apply leibniz_equiv_iff in V_H.\n          by iPureIntro. } subst H1'.\n        iSplitR. iNext; by iPureIntro.\n        iSplitR \"Hth_sy\". iApply \"Hstar_reg'\".\n        iNext. iExists P', Q', k', vp', t0', vtid', γ_tk'', γ_sy.\n        iFrame \"∗#\". by iNext. } subst H1'.\n      iAssert (⌜(k, (v0, t0)) ∈ H1⌝)%I as %kv0t0_in_H1.\n      { iPoseProof (own_valid_2 _ _ _ with \"[$HH] [$SR0]\") 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. clear -H''; by set_solver. }  \n      iAssert (⌜(k, (vp, t)) ∈ H1⌝)%I as %kvpt_in_H1.\n      { iPoseProof (own_valid_2 _ _ _ with \"[$HH] [$SR]\") 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. clear -H''; by set_solver. }  \n      iAssert (⌜¬ (∀ t' : nat, (k, (vp, t')) ∈ H1 → t' < t0)⌝)%I as \"%\". \n      { iDestruct \"Uniq\" as %Uniq.\n        iPureIntro. intros H'.\n        pose proof H' t kvpt_in_H1 as H'.\n        destruct (decide (t = t0)).\n        - subst t. \n          pose proof Uniq k t0 vp v0 kvpt_in_H1 kv0t0_in_H1 as Uniq.\n          apply v0_neq_vp. done.\n        - clear -t0_le_t n H'. lia. }  \n      iDestruct \"Hth_or\" as \"[Hth_or | Hth_or]\".\n      { iDestruct \"Hth_or\" as \"(? & >%)\".\n        exfalso. try done. }\n      iDestruct \"Hth_or\" as \"(Hth_or & >%)\".  \n      iDestruct \"Hth_or\" as \"[Hth_or | >Hth_or]\"; last first.\n      { iPoseProof (own_valid_2 _ _ _ with \"[$Token] [$Hth_or]\") as \"%\".\n        exfalso; try done. }\n      \n      iModIntro. iSplitR \"Hth_or Hth_sy Token\".\n      iExists T1, H1; iFrame.\n      iNext. iExists R1, hγt1; iFrame.\n      \n      iModIntro. iSplitL \"Token Hth_sy\".\n      iNext. iExists H1. iFrame \"Hth_sy\". \n      iRight. iFrame \"∗%\".\n      \n      iModIntro. wp_pures. by iModIntro.\n  Qed.\n\n\n  Lemma search_spec_high N γ_te γ_he γ_s Inv_tpl γ_td γ_ght (k: K) :\n  ⊢ ⌜k ∈ KS⌝ -∗ \n      <<< ∀ M, MCS_high N γ_te γ_he γ_s Inv_tpl γ_td γ_ght M >>>\n            search' #k @ ⊤ ∖ (↑(mcsN N) ∪ ↑(threadN N))\n      <<<  ∃ (v: V), MCS_high N γ_te γ_he γ_s Inv_tpl γ_td γ_ght M \n                        ∗ ⌜M !!! k = v⌝, RET #v >>>.\n  Proof.\n    iIntros \"%\" (Φ) \"AU\". rename H0 into k_in_KS.\n    iApply fupd_wp. \n    iMod \"AU\" as (M0)\"[H [Hab _]]\".\n    iDestruct \"H\" as (T0 H0)\"(MCS & M_eq_H & #HInv)\".\n    iMod (\"Hab\" with \"[MCS M_eq_H]\") as \"AU\".\n    iExists T0, H0. iFrame \"∗#\". iModIntro.\n    awp_apply search_spec_intermediate; try done.\n    rewrite /atomic_acc /=. iMod \"AU\" as (M1)\"[H HAU]\".\n    iDestruct \"H\" as (T1 H1)\"(MCS & M_eq_H & _)\".\n    iModIntro. iExists T1, H1. iFrame \"MCS\". iSplit.\n    { iIntros \"MCS\". iDestruct \"HAU\" as \"[Hab _]\".\n      iMod (\"Hab\" with \"[MCS M_eq_H]\") as \"AU\".\n      iExists T1, H1. iFrame \"∗#\". by iModIntro. }\n    iIntros (vr tr)\"(MCS & %)\". rename H2 into H_k.   \n    iDestruct \"M_eq_H\" as %M_eq_H.\n    iAssert (⌜M1 !!! k = vr⌝)%I as \"M_k\".\n    { iPureIntro. rewrite <-M_eq_H. rewrite chop_ts_lookup_total.\n      rewrite H_k. by simpl. }\n    iDestruct \"HAU\" as \"[_ Hcomm]\".\n    iSpecialize (\"Hcomm\" $! vr).\n    iMod (\"Hcomm\" with \"[MCS]\") as \"HΦ\". \n    iFrame \"M_k\". iExists T1, H1. iFrame \"∗#%\".\n    by iModIntro.\n  Qed.\n  \n  Lemma ghost_update_registered (k: K) (v: V) (t: T) (N: namespace) \n                (γ_te γ_he γ_ght: gname) \n                (H1: gset KVT) (R: gset proph_id)  :\n        ⌜map_of_set (H1 ∪ {[k, (v, t)]}) !!! k = (v, t)⌝ -∗\n           MCS_auth γ_te γ_he (t+1) (H1 ∪ {[(k, (v, t))]}) -∗          \n      ([∗ set] t_id ∈ R, Reg N γ_te γ_he γ_ght H1 t_id) \n        ={⊤ ∖ ↑(mcsN N)}=∗ \n      ([∗ set] t_id ∈ R, Reg N γ_te γ_he γ_ght \n                                      (H1 ∪ {[(k, (v, t))]}) t_id)\n       ∗ MCS_auth γ_te γ_he (t+1) (H1 ∪ {[(k, (v, t))]}).\n  Proof.  \n    iIntros \"H1_k MCS_auth\".\n    iDestruct \"H1_k\" as %H1_k.\n    iInduction R as [|tid R' tid_notin_R IH] \"HInd\" using set_ind_L; \n      auto using big_sepS_empty'.\n    rewrite (big_sepS_delete _ ({[tid]} ∪ R') tid); last by set_solver.\n    rewrite (big_sepS_delete _ ({[tid]} ∪ R') tid); last by set_solver.\n    assert (({[tid]} ∪ R') ∖ {[tid]} = R') as HR'. set_solver.\n    rewrite HR'.\n    iIntros \"(Htid & Hbigstar)\". \n    iMod (\"HInd\" with \"[$MCS_auth] Hbigstar\") as \"(H' & MCS_auth)\".\n    iFrame \"H'\".\n    iDestruct \"Htid\" as (P Q k' vp t0 vtid γ_tk γ_sy)\n              \"(Hreg_proph & Hreg_gh & Hreg_sy & #Pau & #Hthinv)\".\n    iInv \"Hthinv\" as (H1')\"Hstate\".\n    iDestruct \"Hstate\" as \"(>Hth_sy & Hstate)\".\n    iAssert (⌜H1' = H1⌝)%I as \"%\". \n    { iPoseProof (own_valid_2 _ _ _ with \"[$Hth_sy] [$Hreg_sy]\") as \"V_H\".\n      iDestruct \"V_H\" as %V_H.\n      apply frac_agree_op_valid in V_H. destruct V_H as [_ V_H].\n      apply leibniz_equiv_iff in V_H.\n      by iPureIntro. } subst H1'.\n    \n    iCombine \"Hreg_sy Hth_sy\" as \"H'\". \n    iEval (rewrite <-frac_agree_op) in \"H'\". \n    iEval (rewrite Qp_half_half) in \"H'\".\n    iMod ((own_update (γ_sy) (to_frac_agree 1 H1) \n                  (to_frac_agree 1 (H1 ∪ {[(k, (v, t))]}))) 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 \"(Hreg_sy & Hth_sy)\".\n\n    iDestruct \"Hstate\" as \"[Hpending | Hdone]\".\n    - iDestruct \"Hpending\" as \"(P & >%)\".\n      rename H0 into HPending.\n      destruct (decide (k' = k)).\n      + subst k'. destruct (decide (vp = v)).\n        * subst vp. \n          assert (t0 ≤ t ∨ t < t0) as H'.\n          { clear; lia. }\n          destruct H' as [H' | H'].\n          ** iDestruct (\"Pau\" with \"P\") as \">AU\".\n             iMod \"AU\" as (t' H1')\"[MCS [_ Hclose]]\". set_solver.\n             iAssert (⌜H1' = H1 ∪ {[(k, (v, t))]}⌝)%I as \"%\".\n             { iPoseProof (MCS_agree with \"[$MCS_auth] [$MCS]\") as \"(% & %)\".\n               by iPureIntro. } subst H1'.\n             iSpecialize (\"Hclose\" $! v t).  \n             iMod (\"Hclose\" with \"[MCS]\") as \"HQ\".\n             { iFrame \"%∗\". }\n             iModIntro. iSplitL \"Hth_sy HQ\".\n             *** iNext. iExists (H1 ∪ {[(k, (v, t))]}).\n                 iFrame. iRight. unfold Done. iSplitL.\n                 iLeft. iFrame.\n                 iPureIntro. exists t.\n                 split. clear; set_solver. lia.\n             *** iModIntro. iFrame.\n                 iExists P, Q, k, v, t0, vtid, γ_tk, γ_sy.\n                 iFrame \"∗#\".\n          ** iModIntro. iSplitL \"Hth_sy P\".\n             *** iNext. iExists (H1 ∪ {[(k, (v, t))]}).\n                 iFrame. iLeft. iFrame.\n                 iPureIntro. intros t'.\n                 rewrite elem_of_union.\n                 intros [H'' | H''].\n                 by apply HPending.\n                 assert (t' = t) by set_solver.\n                 subst t'. done.\n             *** iModIntro. iFrame.\n                 iExists P, Q, k, v, t0, vtid, γ_tk, γ_sy.\n                 iFrame \"∗#\".\n        * iModIntro. iSplitL \"Hth_sy P\".\n          ** iNext. iExists (H1 ∪ {[(k, (v, t))]}).\n             iFrame. iLeft. iFrame.\n             iPureIntro. intros t'.\n             rewrite elem_of_union.\n             intros [H'' | H''].\n             by apply HPending.\n             assert (vp = v) by set_solver.\n             done.\n          ** iModIntro. iFrame.\n             iExists P, Q, k, vp, t0, vtid, γ_tk, γ_sy.\n             iFrame \"∗#\".\n      + iModIntro. iSplitL \"Hth_sy P\".\n        * iNext. iExists (H1 ∪ {[(k, (v, t))]}).\n          iFrame. iLeft. iFrame.\n          iPureIntro. intros t'.\n          rewrite elem_of_union.\n          intros [H'' | H''].\n          by apply HPending.\n          assert (k' = k) by set_solver.\n          done.\n        * iModIntro. iFrame.\n          iExists P, Q, k', vp, t0, vtid, γ_tk, γ_sy.\n          iFrame \"∗#\".                \n    - iModIntro.\n      iSplitR \"Hreg_proph Hreg_sy Hreg_gh MCS_auth\".\n      iNext. iExists (H1 ∪ {[(k, (v, t))]}). iFrame.\n      iRight. iDestruct \"Hdone\" as \"(HQ & %)\".\n      iFrame \"HQ\". iPureIntro. set_solver.\n      iModIntro. iFrame. \n      iExists P, Q, k', vp, t0, vtid, γ_tk, γ_sy.\n      iFrame \"∗#\".                     \n  Qed.\n  \n  Lemma upsert_spec_high N γ_te γ_he γ_s Inv_tpl γ_td γ_ght (k: K) (v: V):\n    ⊢ ⌜k ∈ KS⌝ -∗ \n       <<< ∀ M, MCS_high N γ_te γ_he γ_s Inv_tpl γ_td γ_ght M >>> \n             upsert #k #v @ ⊤ ∖ (↑(mcsN N) ∪ ↑(threadN N))\n       <<< MCS_high N γ_te γ_he γ_s Inv_tpl γ_td γ_ght (<[k := v]> M), RET #() >>>.\n  Proof.\n    iIntros \"%\" (Φ) \"AU\". rename H0 into k_in_KS.\n    iApply fupd_wp. \n    iMod \"AU\" as (M0)\"[H [Hab _]]\".\n    iDestruct \"H\" as (T0 H0)\"(MCS & M_eq_H & #HInv)\".\n    iMod (\"Hab\" with \"[MCS M_eq_H]\") as \"AU\".\n    iExists T0, H0. iFrame \"∗#\". iModIntro.\n    iAssert (ghost_update_protocol N γ_te γ_he \n                (Prot_help N γ_te γ_he γ_td γ_ght) k)%I \n                  as \"Ghost_updP\".\n    { iIntros (v' T' H')\"H1_k MCS_auth\".\n      iDestruct \"H1_k\" as %H1_k.\n      iIntros \"Prot\". \n      iDestruct \"Prot\" as (R hγt)\"(HR & Hγt & Domm_hγt & Hstar_reg)\".\n      iMod (ghost_update_registered k v' T' with \n              \"[] [MCS_auth] [$Hstar_reg]\") \n                 as \"(Hstar_reg & MCS_auth)\"; try done.\n      iModIntro. iFrame \"MCS_auth\".\n      iExists R, hγt. iFrame. }\n    awp_apply upsert_spec; try done.\n    iApply (aacc_aupd_commit with \"AU\"). set_solver.\n    iIntros (M1)\"MCS_high\".\n    iDestruct \"MCS_high\" as (T1 H1)\"(MCS & M_eq_H & _)\".\n    iDestruct \"M_eq_H\" as %M_eq_H.\n    iAssert (⌜HClock T1 H1⌝)%I as %HClock.\n    { by iDestruct \"MCS\" as \"(_ & _ & % & _)\". }\n    iAssert (⌜HUnique H1⌝)%I as %HUniq.\n    { by iDestruct \"MCS\" as \"(_ & _ & _ & %)\". }\n    iAaccIntro with \"MCS\".\n    { iIntros \"MCS\". iModIntro.\n      iSplitL; try eauto with iFrame.\n      iExists T1, H1; iFrame \"∗#%\". } \n    iIntros \"MCS\". \n    iModIntro. iSplitL.\n    iExists (T1 + 1), (H1 ∪ {[(k, (v, T1))]}). iFrame \"∗#\".\n    { iPureIntro. apply symmetry.\n      pose proof map_of_set_insert_eq k v T1 H1 HUniq HClock as H'.\n      apply symmetry in H'. rewrite H'. rewrite <-M_eq_H.\n      by rewrite chop_ts_insert. }\n    iIntros \"HΦ\"; iModIntro; try done.\n  Qed.\n              \nEnd multicopy_client_level.\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/multicopy/multicopy_client_level.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044135, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2733105066176675}}
{"text": "Require Import ModelProperties. \nRequire Import AuxiliaryLemmas. \n \nSection closeIsSecure. \n \nLemma ClosePSS :\n forall (s t : SFSstate) (u : SUBJECT),\n FuncPre5 s -> SecureState s -> TransFunc u s Close t -> SecureState t. \nintros s t Sub FP5 SS TF; inversion TF. \ninversion H. \nunfold SecureState in |- *. \nBreakSS. \nsplit. \nunfold DACSecureState in |- *; intros; simpl in |- *. \nelim (OBJeq_dec o o0); intro y0. \nrewrite <- y0. \nelim (SUBeq_dec Sub u0); intro y1. \nrewrite <- y1. \ncut\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. \nelim (fsecmat (close_sm s Sub o) o). \nintros; split; intro; tauto. \n \nauto. \n \napply Close_smCorr; auto. \n \ncut\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. \ncut\n match fsecmat (secmat s) o with\n | None => True\n | Some y =>\n     (set_In u0 (ActReaders y) -> PreDACRead s u0 o) /\\\n     (set_In u0 (ActWriters y) -> PreDACWrite s u0 o)\n end. \nunfold close_sm at 3 4, PreDACRead, PreDACWrite in |- *; simpl in |- *;\n elim (fsecmat (secmat s) o); elim (fsecmat (close_sm s Sub o) o). \nintros. \nelim H6; elim H5; intros. \nsplit; intro. \napply H7; apply H9; auto. \n \napply H8; apply H10; auto. \n \nauto. \n \ntauto. \n \nauto. \n \nunfold DACSecureState in DAC; apply DAC. \n \napply Close_smCorr2; auto. \n \nreplace (fsecmat (close_sm s Sub o) o0) with (fsecmat (secmat s) o0). \nunfold close_sm, PreDACRead, PreDACWrite in |- *; simpl in |- *;\n unfold DACSecureState, PreDACRead, PreDACWrite in DAC; \n apply DAC. \n \nauto. \n \nunfold MACSecureState in |- *; intros; simpl in |- *. \nelim (OBJeq_dec o o0); intro y0. \nrewrite <- y0. \ncut\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. \ncut\n match fsecmat (secmat s) o, fOSC (objectSC s) o, fSSC (subjectSC s) u0 with\n | None, _, _ => True\n | _, None, _ => True\n | _, _, None => True\n | Some x, Some y, Some z =>\n     set_In u0 (ActReaders x) \\/ set_In u0 (ActWriters x) -> le_sc y z\n end. \nelim (fsecmat (secmat s) o); elim (fsecmat (close_sm s Sub o) o);\n elim (fOSC (objectSC s) o); elim (fSSC (subjectSC s) u0);\n contradiction || trivial. \ntauto. \n \nunfold MACSecureState in MAC; apply MAC. \n \napply Close_smCorr2; auto. \n \nreplace (fsecmat (close_sm s Sub o) o0) with (fsecmat (secmat s) o0). \nunfold MACSecureState in MAC; apply MAC. \n \nauto. \n \nQed. \n \n \nLemma ClosePSP :\n forall (s t : SFSstate) (u : SUBJECT),\n FuncPre5 s -> StarProperty s -> TransFunc u s Close t -> StarProperty t. \nintros s t Sub FP5 SP TF; inversion TF. \ninversion H. \nunfold StarProperty in |- *; simpl in |- *; intros. \ncut\n match\n   fsecmat (secmat s) o1, fsecmat (secmat s) o2, fOSC (objectSC s) o2,\n   fOSC (objectSC s) o1\n with\n | None, _, _, _ => True\n | _, None, _, _ => True\n | _, _, None, _ => True\n | _, _, _, None => True\n | Some w, Some x, Some y, Some z =>\n     set_In u0 (ActWriters w) -> set_In u0 (ActReaders x) -> le_sc y z\n end. \ncut\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. \nelim (OBJeq_dec o o1); elim (OBJeq_dec o o2); intros EQ2 EQ1. \nrewrite <- EQ1; rewrite <- EQ2. \nelim (fsecmat (secmat s) o); elim (fOSC (objectSC s) o);\n elim (fsecmat (close_sm s Sub o) o); intros; auto. \n \nreplace (fsecmat (close_sm s Sub o) o2) with (fsecmat (secmat s) o2). \nrewrite <- EQ1. \nelim (fsecmat (secmat s) o2); elim (fOSC (objectSC s) o);\n elim (fOSC (objectSC s) o2); elim (fsecmat (secmat s) o);\n elim (fsecmat (close_sm s Sub o) o); intros; contradiction || auto. \ntauto. \n \nauto. \n \nreplace (fsecmat (close_sm s Sub o) o1) with (fsecmat (secmat s) o1). \nrewrite <- EQ2. \nelim (fsecmat (secmat s) o1); elim (fOSC (objectSC s) o);\n elim (fOSC (objectSC s) o1); elim (fsecmat (secmat s) o);\n elim (fsecmat (close_sm s Sub o) o); intros; contradiction || auto. \ntauto. \n \nauto. \n \nreplace (fsecmat (close_sm s Sub o) o2) with (fsecmat (secmat s) o2). \nreplace (fsecmat (close_sm s Sub o) o1) with (fsecmat (secmat s) o1). \nauto. \n \nauto. \n \nauto. \n \napply Close_smCorr2; auto. \n \nunfold StarProperty in SP; apply SP. \n \nQed. \n \n \nLemma ClosePCP : forall s t : SFSstate, PreservesControlProp s Close t. \nintros; unfold PreservesControlProp in |- *; intros Sub TF; inversion TF;\n unfold ControlProperty in |- *. \ninversion H. \nsplit. \nintros. \nsplit. \nintros;\n absurd\n  (DACCtrlAttrHaveChanged s\n     (mkSFS (groups s) (primaryGrp s) (subjectSC s) \n        (AllGrp s) (RootGrp s) (SecAdmGrp s) (objectSC s) \n        (acl s) (close_sm s Sub o) (files s) (directories s)) o0); \n auto. \n \nintros;\n absurd\n  (MACObjCtrlAttrHaveChanged s\n     (mkSFS (groups s) (primaryGrp s) (subjectSC s) \n        (AllGrp s) (RootGrp s) (SecAdmGrp s) (objectSC s) \n        (acl s) (close_sm s Sub o) (files s) (directories s)) o0); \n auto. \n \nintros;\n absurd\n  (MACSubCtrlAttrHaveChanged s\n     (mkSFS (groups s) (primaryGrp s) (subjectSC s) \n        (AllGrp s) (RootGrp s) (SecAdmGrp s) (objectSC s) \n        (acl s) (close_sm s Sub o) (files s) (directories s)) u0); \n auto. \n \nQed. \n \n \nEnd closeIsSecure. \n \nHint Resolve ClosePSS ClosePSP ClosePCP. \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/closeIsSecure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2733105066176674}}
{"text": "(** * LogRel.LogicalRelation.ShapeView: relating reducibility witnesses of reducibly convertible types.*)\nFrom LogRel.AutoSubst Require Import core unscoped Ast Extra.\nFrom LogRel Require Import Utils BasicAst Context Notations NormalForms UntypedReduction GenericTyping LogicalRelation DeclarativeInstance.\nFrom LogRel.LogicalRelation Require Import Induction Reflexivity.\n\nSet Universe Polymorphism.\n\nSection ShapeViews.\n  Context `{GenericTypingProperties}.\n\n(** ** Definition *)\n\n(** A shape view is inhabited exactly on the diagonal, ie when the two types are reducible\n  in the same way. *)\n\n  Definition ShapeView@{i j k l i' j' k' l'} Γ\n    A {lA eqTyA redTmA redTyA} B {lB eqTyB redTmB redTyB}\n    (lrA : LogRel@{i j k l} lA Γ A eqTyA redTmA redTyA) (lrB : LogRel@{i' j' k' l'} lB Γ B eqTyB redTmB redTyB) : Set :=\n    match lrA, lrB with\n      | LRU _ _, LRU _ _ => True\n      | LRne _ _, LRne _ _ => True\n      | LRPi _ _ _, LRPi _ _ _ => True\n      | LRNat _ _, LRNat _ _ => True\n      | LREmpty _ _, LREmpty _ _ => True\n      | _, _ => False\n    end.\n\n  Arguments ShapeView Γ A {lA eqTyA redTmA redTyA} B {lB eqTyB redTmB redTyB}\n  !lrA !lrB.\n\n(** ** The main property *)\n\n(** We show that two reducibly convertible types must have the same shape view. Said otherwise,\nif two reducible types are reducibly convertible, then they must be reducible in the same way.\nThis lets us relate different reducibility proofs when we have multiple such proofs, typically\nwhen showing symmetry or transitivity of the logical relation. *)\n\n  Arguments ShapeView Γ A {lA eqTyA redTmA redTyA} B {lB eqTyB redTmB redTyB}\n  !lrA !lrB.\n\n\n  Lemma red_whnf@{i j k l} {Γ A lA eqTyA redTmA eqTmA}\n    (lrA : LogRel@{i j k l} lA Γ A eqTyA redTmA eqTmA) : \n    ∑ nf, [Γ |- A :⇒*: nf] × whnf nf.\n  Proof.\n    destruct lrA as [?? []| ??[] | ??[]| ??[] | ??[]]; eexists; split; tea; constructor; tea.\n    now eapply ty_ne_whne.\n  Defined.\n\n  Lemma eqTy_red_whnf@{i j k l} {Γ A lA eqTyA redTmA eqTmA B}\n    (lrA : LogRel@{i j k l} lA Γ A eqTyA redTmA eqTmA) : \n    eqTyA B -> ∑ nf, [Γ |- B :⇒*: nf] × whnf nf.\n  Proof.\n    destruct lrA as [?? []| ??[] | ??[]| ??[] | ??[]] ; intros []; eexists; split; tea; constructor; tea.\n    now eapply ty_ne_whne.\n  Defined.\n\n\n  Lemma ShapeViewConv@{i j k l i' j' k' l'} {Γ A lA eqTyA redTmA eqTmA B lB eqTyB redTmB eqTmB}\n    (lrA : LogRel@{i j k l} lA Γ A eqTyA redTmA eqTmA) (lrB : LogRel@{i' j' k' l'} lB Γ B eqTyB redTmB eqTmB) :\n    eqTyA B ->\n    ShapeView@{i j k l i' j' k' l'} Γ A B lrA lrB.\n  Proof.\n    intros eqAB.\n    pose (x := eqTy_red_whnf lrA eqAB).\n    pose (y:= red_whnf lrB).\n    pose proof (h := redtywf_det _ _ _ _ (snd x.π2) (snd y.π2) (fst x.π2) (fst y.π2)).\n    revert eqAB x y h. \n    destruct lrA; destruct lrB; intros []; cbn; try easy; try discriminate.\n    all: try now (intros e; rewrite e in ne; apply ty_ne_whne in ne; inversion ne).\n    all: try now (intros e; destruct neA as [? ? ne]; rewrite <- e in ne; apply ty_ne_whne in ne; inversion ne).\n  Qed.\n\n(** ** More properties *)\n\n  Corollary ShapeViewRefl@{i j k l i' j' k' l'} {Γ A lA eqTyA redTmA eqTmA lA' eqTyA' redTmA' eqTmA'}\n    (lrA : LogRel@{i j k l} lA Γ A eqTyA redTmA eqTmA) (lrA' : LogRel@{i' j' k' l'} lA' Γ A eqTyA' redTmA' eqTmA') :\n    ShapeView@{i j k l i' j' k' l'} Γ A A lrA lrA'.\n  Proof.\n    now eapply ShapeViewConv, LRTyEqRefl.\n  Qed.\n\n\n  Definition ShapeView3 Γ\n    A {lA eqTyA redTmA redTyA}\n    B {lB eqTyB redTmB redTyB}\n    C {lC eqTyC redTmC redTyC}\n    (lrA : LogRel lA Γ A eqTyA redTmA redTyA)\n    (lrB : LogRel lB Γ B eqTyB redTmB redTyB)\n    (lrC : LogRel lC Γ C eqTyC redTmC redTyC)\n    : Set :=\n    match lrA, lrB, lrC with\n      | LRU _ _, LRU _ _, LRU _ _ => True\n      | LRne _ _, LRne _ _, LRne _ _ => True\n      | LRPi _ _ _, LRPi _ _ _, LRPi _ _ _ => True\n      | LRNat _ _, LRNat _ _, LRNat _ _ => True\n      | LREmpty _ _, LREmpty _ _, LREmpty _ _ => True\n      | _, _, _ => False\n    end.\n\n\n  Arguments ShapeView3 Γ A {lA eqTyA redTmA redTyA} B {lB eqTyB redTmB redTyB} C {lC eqTyC redTmC redTyC}\n  !lrA !lrB !lrC.\n\n  Lemma combine Γ\n    A {lA eqTyA redTmA redTyA}\n    B {lB eqTyB redTmB redTyB}\n    C {lC eqTyC redTmC redTyC}\n    (lrA : LogRel lA Γ A eqTyA redTmA redTyA)\n    (lrB : LogRel lB Γ B eqTyB redTmB redTyB)\n    (lrC : LogRel lC Γ C eqTyC redTmC redTyC) :\n    ShapeView Γ A B lrA lrB -> ShapeView Γ B C lrB lrC -> ShapeView3 Γ A B C lrA lrB lrC.\n  Proof.  destruct lrA, lrB, lrC; easy. Qed.\n\nEnd ShapeViews.\n", "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/LogicalRelation/ShapeView.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.27329861401810696}}
{"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(*              Definition of FlatMeory                                *)\n(*                                                                     *)\n(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)\n(*                                                                     *)\n(*          Yale Flint Group                                           *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** This file provide the flat memory model (the high memory [from 1G to 3G]) definition and its operations.*)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import Integers.\nRequire Export Memdata.\nRequire Import AST.\nRequire Import Values.\nRequire Import AuxStateDataType.\nRequire Import Constant.\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\nModule FlatMem.\n\n  (** * Flatmem definition and operations*)\n  Inductive flatmem_val :=\n  | HUndef\n  | HByte: byte -> flatmem_val.\n\n  Definition flatmem := ZMap.t flatmem_val. \n\n  (** empty flatmem*)\n  Definition empty_flatmem : flatmem := ZMap.init HUndef.\n\n  (** ** Memory reads. *)\n  (** Convert the flatmem_val to mem_val*)\n  Definition FlatMem2MemVal (hv: flatmem_val): memval :=\n    match hv with\n      | HUndef => Undef\n      | HByte b => Byte b\n    end.\n\n  (** Reading N adjacent bytes in the flatmem start from address [p]. *)\n  Fixpoint getN (n: nat) (p: Z) (c: flatmem) {struct n}: list memval :=\n    match n with\n      | O => nil\n      | S n' => (FlatMem2MemVal c#p) :: getN n' (p + 1) c\n    end.\n\n  (** [load chunk h addr] perform a read in flatmem state [h], at address\n  [addr].  It returns the value of the memory chunk\n  at that address. [None] is returned if the accessed bytes\n  are not readable. *)\n  Definition load (chunk: memory_chunk) (h: flatmem) (addr: Z): val :=\n    (decode_val chunk (getN (size_chunk_nat chunk) addr h)).\n\n  (** [loadv chunk h addr] is similar, but the address [addr] must be a pure address (int value). *)\n  Definition loadv (chunk: memory_chunk) (h: flatmem) (addr: val) : option val :=\n    match addr with\n      | Vint n => Some (load chunk h (Int.unsigned n))\n      | _ => None\n    end.\n\n  (** [loadbytes h addr n] reads [n] consecutive bytes starting at\n  location [addr].  Returns [None] if the accessed locations are\n  not readable. *)\n  Definition loadbytes (h: flatmem) (addr n: Z): (list memval) :=\n    (getN (nat_of_Z n) addr h).\n\n  (** ** Memory stores. *)\n  (** Convert the mem_val to flatmem_val*)\n  Definition Mem2FlatMemVal (mv: memval): flatmem_val :=\n    match mv with\n      | Byte b => (HByte b)\n      | _ => HUndef\n    end.\n\n  (** Writing N adjacent bytes in the flatmem start from address [p]. *)\n  Fixpoint setN (vl: list memval) (p: Z) (c: flatmem) {struct vl}: flatmem :=\n    match vl with\n      | nil => c\n      | v :: vl' => setN vl' (p + 1) (ZMap.set p (Mem2FlatMemVal v) c)\n    end.\n\n  (** [store chunk h addr v] perform a write in flatmem state [h].\n  Value [v] is stored at address [addr].\n  Return the updated memory store, or [None] if the accessed bytes\n  are not writable. *)\n  Definition store (chunk: memory_chunk) (h: flatmem) (addr: Z) (v: val): flatmem :=\n    setN (encode_val chunk v) addr h.\n\n  (** [storev chunk h addr v] is similar, but the address [addr] must be a pure address (int vaule). *)\n  Definition storev (chunk: memory_chunk) (h: flatmem) (addr v: val) : option flatmem :=\n    match addr with\n      | Vint n => Some (store chunk h (Int.unsigned n) v)\n      | _ => None\n    end.\n\n  (** [storebytes h addr bytes] stores the given list of bytes [bytes]\n  starting at location [addr].  Returns updated memory state\n  or [None] if the accessed locations are not writable. *)\n  Definition storebytes (h: flatmem) (addr: Z) (bytes: list memval) : flatmem :=\n    (setN bytes addr h).\n\n  (** ** Properties related to [load] *)\n  Lemma load_result:\n    forall chunk h addr v,\n      load chunk h addr = v ->\n      v = decode_val chunk (getN (size_chunk_nat chunk) addr h).\n  Proof.\n    intros until v. unfold load. \n    intros.\n    congruence.\n  Qed.\n  \n  Theorem load_type:\n    forall h chunk addr v,\n      load chunk h addr = v ->\n      Val.has_type v (type_of_chunk chunk).\n  Proof.\n    intros. exploit load_result; eauto; intros. rewrite H0. \n    apply decode_val_type. \n  Qed.\n\n  Theorem load_cast:\n    forall h chunk addr v,\n      load chunk h addr = 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.\n  Proof.\n    intros. exploit load_result; eauto.\n    set (l := getN (size_chunk_nat chunk) addr h).\n    intros. subst v. apply decode_val_cast. \n  Qed.\n\n  Theorem load_int8_signed_unsigned:\n    forall h addr,\n      load Mint8signed h addr = (Val.sign_ext 8) (load Mint8unsigned h addr).\n  Proof.\n    intros. unfold load.\n    change (size_chunk_nat Mint8signed) with (size_chunk_nat Mint8unsigned).\n    set (cl := getN (size_chunk_nat Mint8unsigned) addr h).\n    unfold decode_val. \n    destruct (proj_bytes cl); auto.\n    simpl. decEq.\n    rewrite Int.sign_ext_zero_ext. \n    trivial.\n    omega.\n  Qed.\n\n  Theorem load_int16_signed_unsigned:\n    forall m ofs,\n      load Mint16signed m ofs = (Val.sign_ext 16) (load Mint16unsigned m ofs).\n  Proof.\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).\n    unfold decode_val. \n    destruct (proj_bytes cl); auto.\n    simpl. decEq.  rewrite Int.sign_ext_zero_ext. auto. \n    omega.\n  Qed.\n\n(*\n  Theorem load_float64al32:\n    forall m ofs v,\n      load Mfloat64 m ofs = v -> load Mfloat64al32 m ofs = v.\n  Proof.\n    unfold load; intros. \n    unfold decode_val in *.\n    change  (size_chunk_nat Mfloat64al32) with (size_chunk_nat Mfloat64).\n    set (cl:= (getN (size_chunk_nat Mfloat64) ofs m)) in *.\n    destruct (proj_bytes cl); auto.\n  Qed.\n\n  Theorem loadv_float64al32:\n    forall m a v,\n      loadv Mfloat64 m a = Some v -> loadv Mfloat64al32 m a = Some v.\n  Proof.\n    unfold loadv; intros. destruct a; auto. \n  Qed.\n*)\n\n  (** ** Properties related to [loadbytes] *)\n  Theorem loadbytes_load:\n    forall chunk m  ofs bytes,\n      loadbytes m ofs (size_chunk chunk) = bytes ->\n      (align_chunk chunk | ofs) ->\n      load chunk m ofs = (decode_val chunk bytes).\n  Proof.\n    unfold loadbytes, load; intros. \n    auto.\n\n    unfold size_chunk.\n    unfold size_chunk_nat.\n    rewrite H.\n    trivial.\n  Qed.\n\n  Theorem load_loadbytes:\n    forall chunk m ofs v,\n      load chunk m ofs = v ->\n      exists bytes, loadbytes m ofs (size_chunk chunk) = bytes\n                    /\\ v = decode_val chunk bytes.\n  Proof.\n    intros. \n    unfold load in H.\n    exists (getN (size_chunk_nat chunk) ofs m); split.\n    unfold loadbytes. \n    unfold size_chunk_nat.\n    trivial.\n    auto.\n  Qed.\n\n  Lemma getN_length:\n    forall c n p, length (getN n p c) = n.\n  Proof.\n    induction n; simpl; intros. auto. decEq; auto.\n  Qed.\n\n  Theorem loadbytes_length:\n    forall m ofs n bytes,\n      loadbytes m ofs n = bytes ->\n      length bytes = nat_of_Z n.\n  Proof.\n    unfold loadbytes; intros.\n    inv H.\n    apply getN_length.\n  Qed.\n\n  Theorem loadbytes_empty:\n    forall m ofs n,\n      n <= 0 -> loadbytes m ofs n = nil.\n  Proof.\n    intros. unfold loadbytes.  rewrite nat_of_Z_neg; auto.\n  Qed.\n\n  Lemma getN_emptymem:\n    forall n ofs,\n      getN n ofs empty_flatmem = list_repeat n Undef.\n  Proof.\n    induction n; intros; simpl.\n    - reflexivity.\n    - decEq.\n      + unfold empty_flatmem.\n        rewrite ZMap.gi. reflexivity.\n      + eauto.      \n  Qed.\n\n  Lemma loadbytes_emptymem:\n    forall ofs len,\n      loadbytes empty_flatmem ofs len = (list_repeat (nat_of_Z len) Undef).\n  Proof.\n    intros. \n    unfold loadbytes.\n    eapply getN_emptymem.\n  Qed.\n  \n  Lemma 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.\n  Proof.\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. \n  Qed.\n\n  Theorem loadbytes_concat:\n    forall m ofs n1 n2 bytes1 bytes2,\n      loadbytes m ofs n1 = bytes1 ->\n      loadbytes m (ofs + n1) n2 = bytes2 ->\n      n1 >= 0 -> n2 >= 0 ->\n      loadbytes m ofs (n1 + n2) = (bytes1 ++ bytes2).\n  Proof.\n    unfold loadbytes; intros.\n    inv H.\n    rewrite Z2Nat.inj_add; try omega.\n    rewrite getN_concat. rewrite nat_of_Z_eq; auto.\n  Qed.\n\n  Theorem loadbytes_split:\n    forall m ofs n1 n2 bytes,\n      loadbytes m ofs (n1 + n2) = bytes ->\n      n1 >= 0 -> n2 >= 0 ->\n      exists bytes1, exists bytes2,\n                       loadbytes m ofs n1 = bytes1 \n                       /\\ loadbytes m (ofs + n1) n2 = bytes2\n                       /\\ bytes = bytes1 ++ bytes2.\n  Proof.\n    unfold loadbytes; intros. \n    rewrite nat_of_Z_plus in H; auto. rewrite getN_concat in H.\n    rewrite nat_of_Z_eq in H; auto.\n    econstructor; econstructor.\n    split. reflexivity. split. reflexivity. congruence.\n  Qed.\n\n  Theorem load_rep:\n    forall ch m1 m2 ofs v1 v2, \n      (forall z, 0 <= z < size_chunk ch -> m1#(ofs+z) = m2#(ofs+z)) ->\n      load ch m1 ofs = v1 ->\n      load ch m2 ofs = v2 ->\n      v1 = v2.\n  Proof.\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    rewrite  H; try omega.\n    trivial.\n    apply IHn.\n    intros.\n    rewrite <- Zplus_assoc.\n    apply H.\n    rewrite inj_S. omega.\n  Qed.\n\n  Theorem load_rep':\n    forall ch m1 m2 ofs1 ofs2 v1 v2, \n      (forall z, 0 <= z < size_chunk ch -> m1#(ofs1+z) = m2#(ofs2+z)) ->\n      load ch m1 ofs1 = v1 ->\n      load ch m2 ofs2 = v2 ->\n      v1 = v2.\n  Proof.\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 ofs1 ofs2 H; induction n; intros; simpl; auto.\n    f_equal.\n    rewrite inj_S in H.\n    replace ofs1 with (ofs1+0) by omega.\n    replace ofs2 with (ofs2+0) by omega.\n    rewrite H; try omega.\n    trivial.\n    apply IHn.\n    intros.\n    repeat rewrite <- Zplus_assoc.\n    apply H.\n    rewrite inj_S. omega.\n  Qed.\n\n  Lemma proj_pointer_undef: \n    forall n addr h,\n      proj_pointer (getN n addr h) = Vundef.\n  Proof.\n    intros.\n    unfold proj_pointer.\n    destruct n.\n    simpl.\n    trivial.\n    \n    unfold getN.\n    unfold FlatMem2MemVal.\n    destruct (ZMap.get addr h); trivial.\n  Qed.\n\n  Lemma load_valid: \n    forall h t addr b ofs,\n      (load t h addr) = Vptr b ofs\n      -> False.\n  Proof.\n    intros.\n    unfold load in H.\n    unfold decode_val in H.\n    rewrite proj_pointer_undef in H.\n    destruct (proj_bytes (getN (size_chunk_nat t) addr h)).\n    destruct t; inv H.\n    destruct t; inv H.\n  Qed.\n\n  Lemma load_inject:\n    forall j chunk h l,\n      val_inject j (load chunk h l) (load chunk h l).\n  Proof.\n    intros.\n    destruct (load chunk h l) as [] eqn:VAL; auto.\n    exfalso; eapply load_valid; eauto.\n  Qed.\n\n  Remark setN_other:\n    forall vl c p q,\n      (forall r, p <= r < p + Z_of_nat (length vl) -> r <> q) ->\n      ZMap.get q (setN vl p c) = ZMap.get q c.\n  Proof.\n    induction vl; intros; simpl.\n    auto. \n    simpl length in H. rewrite inj_S in H.\n    transitivity (ZMap.get q (ZMap.set p (Mem2FlatMemVal a) c)).\n    apply IHvl. intros. apply H. omega.\n    apply ZMap.gso. apply not_eq_sym. apply H. omega. \n  Qed.\n\n  Remark setN_outside:\n    forall vl c p q,\n      q < p \\/ q >= p + Z_of_nat (length vl) ->\n      ZMap.get q (setN vl p c) = ZMap.get q c.\n  Proof.\n    intros. apply setN_other. \n    intros. omega. \n  Qed.\n\n  (*Remark FlatMem_correct:\n    forall a,\n      FlatMem2MemVal (Mem2FlatMemVal a) = a.\n  Proof.\n    unfold FlatMem2MemVal, Mem2FlatMemVal.\n    destruct a.*)\n\n  Lemma getN_setN_list_undef:\n    forall n p c,\n      getN (length (list_repeat n Undef)) p\n           (setN (list_repeat n Undef) p c) =\n      list_repeat (length (list_repeat n Undef)) Undef.\n  Proof.\n    induction n.\n    - simpl. reflexivity.\n    - simpl. intros.\n      decEq.\n      + rewrite setN_outside. \n        * rewrite ZMap.gss. reflexivity.\n        * left. omega.\n      + apply IHn.\n  Qed.\n\n  Lemma getN_setN_list_bytes:\n    forall vl p c,\n      getN (length (inj_bytes vl)) p\n      (setN (inj_bytes vl) p c) = inj_bytes vl.\n  Proof.\n    induction vl.\n    - simpl. reflexivity.\n    - simpl. intros.\n      decEq.\n      + rewrite setN_outside. \n        * rewrite ZMap.gss. reflexivity.\n        * left. omega.\n      + apply IHvl.\n  Qed.\n\n  Lemma getN_setN_list_pointer:\n    forall n b i p c,\n      getN (length (inj_pointer n b i)) p (setN (inj_pointer n b i) p c) =\n      list_repeat (length (inj_pointer n b i)) Undef.\n  Proof.\n    induction n.\n    - simpl. reflexivity.\n    - simpl. intros.\n      decEq.\n      + rewrite setN_outside. \n        * rewrite ZMap.gss. reflexivity.\n        * left. omega.\n      + apply IHn.\n  Qed.\n\n  Remark getN_setN_same:\n    forall v p c chunk,\n      getN (length (encode_val chunk v)) p (setN (encode_val chunk v) p c) = (encode_val chunk v) \\/\n      getN (length (encode_val chunk v)) p (setN (encode_val chunk v) p c) = list_repeat (length (encode_val chunk v)) Undef.\n  Proof.\n    Opaque list_repeat inj_pointer inj_bytes.\n    destruct chunk; destruct v; simpl;\n    try (right; apply getN_setN_list_undef);\n    try (left; apply getN_setN_list_bytes).\n    right. apply getN_setN_list_pointer.\n  Qed.\n\n  (*Remark getN_setN_disjoint:\n    forall vl q c n p,\n      Intv.disjoint (p, p + Z_of_nat n) (q, q + Z_of_nat (length vl)) ->\n      getN n p (setN vl q c) = getN n p c.\n  Proof.\n    intros. apply getN_exten. intros. apply setN_other.\n    intros; red; intros; subst r. eelim H; eauto. \n  Qed.*)\n\n  Remark getN_exten:\n    forall c1 c2 n p,\n      (forall i, p <= i < p + Z_of_nat n -> ZMap.get i c1 = ZMap.get i c2) ->\n      getN n p c1 = getN n p c2.\n  Proof.\n    induction n; intros. \n    - auto. \n    - rewrite inj_S in H. simpl. decEq.\n      + assert (HW: c1 # p = c2 # p).\n        {\n          apply H. omega. \n        }\n        rewrite HW. reflexivity.\n      + apply IHn. intros. apply H. omega.\n  Qed.\n \n  Remark 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.\n  Proof.\n    intros. apply getN_exten.\n    intros. apply setN_other.\n    red; intros; subst.\n    eelim H; intros; omega.\n  Qed.\n\n  Remark getN_setN_same_int:\n    forall v p c chunk,\n      getN (length (encode_val chunk (Vint v))) p (setN (encode_val chunk (Vint v)) p c) = \n      (encode_val chunk (Vint v)).\n  Proof.\n    Opaque list_repeat inj_pointer inj_bytes.\n    destruct chunk; simpl;\n    try (apply getN_setN_list_bytes);\n    try (apply getN_setN_list_undef).\n  Qed.\n\n  (** ** Properties related to [store] *)\n  Section STORE.\n\n    Variable chunk: memory_chunk.\n    Variable m1: flatmem.\n    Variable ofs: Z.\n    Variable v: val.\n    Variable m2: flatmem.\n    Hypothesis STORE: store chunk m1 ofs v = m2.\n\n    Lemma store_flatmem_contents: \n      m2 = (setN (encode_val chunk v) ofs m1).\n    Proof.\n      unfold store in STORE. \n      auto.\n    Qed.\n\n    Lemma loadbytes_store_same:\n      loadbytes m2 ofs (size_chunk chunk) = encode_val chunk v\n      \\/ loadbytes m2 ofs (size_chunk chunk) = list_repeat (length (encode_val chunk v)) Undef.\n    Proof.\n      intros.\n      unfold loadbytes. rewrite store_flatmem_contents; simpl. \n      replace (nat_of_Z (size_chunk chunk)) with (length (encode_val chunk v)).\n      - eapply getN_setN_same.\n      - rewrite encode_val_length. auto.\n    Qed.\n\n    Lemma loadbytes_store_other:\n      forall ofs' n,\n        n <= 0 \\/ ofs' + n <= ofs \\/ ofs + size_chunk chunk <= ofs' ->\n        loadbytes m2 ofs' n = loadbytes m1 ofs' n.\n    Proof.\n      intros. unfold loadbytes. \n      rewrite store_flatmem_contents; simpl.\n      destruct (zle n 0).\n      - rewrite (nat_of_Z_neg _ l). auto.\n      - destruct H. \n        + omega.\n        + apply getN_setN_outside. rewrite encode_val_length.\n          rewrite <- size_chunk_conv.\n          rewrite nat_of_Z_eq. assumption. \n          omega. \n    Qed.\n\n    Lemma load_store_same:\n      forall h ofs i,\n        load Mint32 (store Mint32 h ofs (Vint i)) ofs = Vint i.\n    Proof.\n      intros. unfold load, store. \n      replace (size_chunk_nat Mint32) with (length (encode_val Mint32 (Vint i))).                          \n      - rewrite getN_setN_same_int.\n        specialize (decode_encode_val_general (Vint i) Mint32 Mint32).\n        simpl. trivial.\n      - rewrite encode_val_length. reflexivity.\n    Qed.\n\n    Lemma load_store_other:\n      forall chunk m1 m2 ofs v chunk' ofs',\n        store chunk m1 ofs v = m2 ->\n        ofs' + (size_chunk chunk') <= ofs \\/ ofs + size_chunk chunk <= ofs' ->\n        load chunk' m2 ofs' = load chunk' m1 ofs'.\n    Proof.\n      unfold load, store. intros. rewrite <- H.\n      rewrite getN_setN_outside. reflexivity. \n      rewrite encode_val_length. repeat rewrite <- size_chunk_conv.\n      assumption.\n    Qed.\n\n  End STORE.\n\n  (** * Flatmem injection *)\n  Inductive flatmem_val_inject  : flatmem_val -> flatmem_val -> Prop :=\n    flatmemval_inject_byte : forall n : byte, flatmem_val_inject (HByte n) (HByte n)\n  | flatmemval_inject_undef : forall mv : flatmem_val, flatmem_val_inject HUndef mv.\n\n  Definition flatmem_inj (h1 h2: flatmem) :=\n    forall addr, flatmem_val_inject h1#addr h2#addr.\n\n  (*Definition flatmem_pperm_inj (p: PPermT) (h1 h2: flatmem) :=\n    forall addr, \n      (forall o, ZMap.get (PageI addr) p <> PGHide o) ->\n      FlatMem.flatmem_val_inject h1#addr h2#addr.*)\n\n  Lemma getN_inj:\n    forall f m1 m2,\n      flatmem_inj m1 m2 ->\n      forall n ofs,\n        list_forall2 (memval_inject f) \n                     (getN n ofs m1)\n                     (getN n ofs m2).\n  Proof.\n    induction n; intros; simpl.\n    constructor.\n    constructor.\n    unfold flatmem_inj in H.\n    specialize (H ofs).\n    destruct (m1 # ofs).\n    constructor.\n    inv H.\n    constructor.\n    specialize (IHn (ofs +1)).\n    trivial.\n  Qed.\n\n  (*Lemma getN_pperm_inj:\n    forall f m1 m2 p,\n      flatmem_pperm_inj p m1 m2 ->\n      forall n ofs,\n        (forall ofs',\n           ofs <= ofs' < ofs + (Z_of_nat n) ->\n           forall o,\n             ZMap.get (PageI ofs') p <> PGHide o) ->\n        list_forall2 (memval_inject f) \n                     (getN n ofs m1)\n                     (getN n ofs m2).\n  Proof.\n    induction n; intros; simpl.\n    - constructor.\n    - constructor.\n      + unfold flatmem_pperm_inj in H.\n        assert (HOS: ofs <= ofs < ofs + Z.of_nat (S n)). \n        {\n          rewrite Nat2Z.inj_succ. omega.\n        }\n        specialize (H0 _ HOS).\n        specialize (H _ H0).\n        destruct (m1 # ofs).\n        * constructor.\n        * inv H. constructor.\n      + eapply IHn. intros. eapply H0.\n        rewrite Nat2Z.inj_succ. omega.\n  Qed.*)\n\n  Lemma load_inj:\n    forall m1 m2 chunk ofs v1 f,\n      flatmem_inj  m1 m2 ->\n      load chunk m1 ofs = v1 ->\n      exists v2, load chunk m2 ofs = v2 /\\ val_inject f v1 v2.\n  Proof.\n    intros.\n    unfold load in *.\n    exists (decode_val chunk (getN (size_chunk_nat chunk) ofs m2)).\n    split; trivial.\n    rewrite <- H0.\n    apply decode_val_inject. apply getN_inj; auto. \n  Qed.\n\n  (*Lemma load_pperm_inj:\n    forall m1 m2 chunk ofs v1 f p,\n      flatmem_pperm_inj p m1 m2 ->\n      load chunk m1 ofs = v1 ->\n      (forall ofs',\n         ofs <= ofs' < ofs + (size_chunk chunk) ->\n         forall o,\n           ZMap.get (PageI ofs') p <> PGHide o) ->      \n      exists v2, load chunk m2 ofs = v2 /\\ val_inject f v1 v2.\n  Proof.\n    intros.\n    unfold load in *.\n    exists (decode_val chunk (getN (size_chunk_nat chunk) ofs m2)).\n    split; trivial.\n    rewrite <- H0.\n    apply decode_val_inject. eapply getN_pperm_inj; eauto. \n    rewrite <- size_chunk_conv. assumption.\n  Qed.*)\n\n  Lemma setN_inj:\n    forall f vl1 vl2,\n      list_forall2 (memval_inject f) vl1 vl2 ->\n      forall p c1 c2,\n        (forall q, flatmem_val_inject (c1#q) (c2#(q))) ->\n        (forall q, flatmem_val_inject ((setN vl1 p c1)#q) \n                                     ((setN vl2 (p) c2)#(q))).\n  Proof.\n    induction 1; intros; simpl. \n    auto.\n    apply IHlist_forall2; auto. \n    intros. rewrite ZMap.gsspec at 1. destruct (ZIndexed.eq q0 p). subst q0.\n    rewrite ZMap.gss. \n    destruct a1.\n    constructor.\n    inv H.\n    constructor.\n    constructor.\n    rewrite ZMap.gso. auto. \n    trivial.\n  Qed.\n\n  Lemma store_mapped_inj:\n    forall f chunk m1 ofs v1 n1 n2 m2 v2,\n      flatmem_inj m1 m2 ->\n      store chunk m1 ofs v1 = n1 ->\n      val_inject f v1 v2 ->\n      store chunk m2 (ofs) v2 = n2 ->\n      flatmem_inj n1 n2.\n  Proof.\n    intros.\n    unfold store in *.\n    rewrite <- H0.\n    rewrite <- H2.\n    unfold flatmem_inj in *.\n    \n    apply setN_inj with f; trivial.\n    apply encode_val_inject; auto. \n  Qed.\n\n  (*Lemma setN_pperm_inj:\n    forall f vl1 vl2,\n      list_forall2 (memval_inject f) vl1 vl2 ->\n      forall p c1 c2 pp,\n        (forall q, \n           (forall o, ZMap.get (PageI q) pp <> PGHide o) ->\n           flatmem_val_inject (c1#q) (c2#(q))) ->\n        (forall q, \n           (forall o, ZMap.get (PageI q) pp <> PGHide o) ->\n           flatmem_val_inject ((setN vl1 p c1)#q) \n                              ((setN vl2 (p) c2)#(q))).\n  Proof.\n    induction 1; intros; simpl. \n    auto.\n    eapply IHlist_forall2; eauto. \n    intros. rewrite ZMap.gsspec at 1. destruct (ZIndexed.eq q0 p). subst q0.\n    rewrite ZMap.gss. \n    destruct a1.\n    constructor.\n    inv H.\n    constructor.\n    constructor.\n    rewrite ZMap.gso. auto. \n    trivial.\n  Qed.\n\n  Lemma store_mapped_pperm_inj:\n    forall f chunk m1 ofs v1 n1 n2 m2 v2 p,\n      flatmem_pperm_inj p m1 m2 ->\n      store chunk m1 ofs v1 = n1 ->\n      val_inject f v1 v2 ->\n      store chunk m2 (ofs) v2 = n2 ->\n      flatmem_pperm_inj p n1 n2.\n  Proof.\n    intros.\n    unfold store in *.\n    rewrite <- H0.\n    rewrite <- H2.\n    unfold flatmem_pperm_inj in *.\n    intros.\n    apply setN_pperm_inj with f p; auto.\n    apply encode_val_inject; auto. \n  Qed.\n\n  Lemma setN_pperm_unmapped_inj:\n    forall vl2,\n      forall p c1 c2 pp,\n        (forall ofs', \n           p <= ofs' < p + Z.of_nat (length vl2) ->\n           exists o, ZMap.get (PageI ofs') pp = PGHide o) ->\n        (forall q, \n           (forall o, ZMap.get (PageI q) pp <> PGHide o) ->\n           flatmem_val_inject (c1#q) (c2#(q))) ->\n        (forall q, \n           (forall o, ZMap.get (PageI q) pp <> PGHide o) ->\n           flatmem_val_inject (c1#q) \n                              ((setN vl2 p c2)#(q))).\n  Proof.\n    induction vl2; intros; simpl. \n    - eauto.\n    - eapply IHvl2; eauto. \n      + intros. eapply H. Local Opaque Z.of_nat. simpl.\n        rewrite Nat2Z.inj_succ. omega.\n      + intros.\n        destruct (zeq q0 p); subst.\n        * rewrite ZMap.gss.\n          exploit (H p). simpl.\n          rewrite Nat2Z.inj_succ. omega.\n          intros (o & HF). specialize (H2 o). congruence.\n        * rewrite ZMap.gso; auto. \n  Qed.\n\n  Lemma store_unmapped_pperm_inj:\n    forall chunk m1 ofs n2 m2 v2 p,\n      flatmem_pperm_inj p m1 m2 ->\n      store chunk m2 (ofs) v2 = n2 ->\n      (forall ofs',\n         ofs <= ofs' < ofs + size_chunk chunk ->\n         exists o, ZMap.get (PageI ofs') p = PGHide o) ->\n      flatmem_pperm_inj p m1 n2.\n  Proof.\n    intros.\n    unfold store in *.\n    rewrite <- H0.\n    unfold flatmem_pperm_inj in *.\n    intros.\n    apply setN_pperm_unmapped_inj with p; auto.\n    rewrite encode_val_length.\n    rewrite <- size_chunk_conv. assumption.\n  Qed.*)\n\n  Lemma flatmem_empty_inj: flatmem_inj empty_flatmem empty_flatmem.\n  Proof.\n    unfold flatmem_inj.\n    intros.\n    unfold empty_flatmem.\n    rewrite ZMap.gi.\n    constructor.\n  Qed.\n\n  (*Lemma flatmem_empty_pperm_inj: forall p, flatmem_pperm_inj p empty_flatmem empty_flatmem.\n  Proof.\n    unfold flatmem_pperm_inj.\n    intros.\n    unfold empty_flatmem.\n    rewrite ZMap.gi.\n    constructor.\n  Qed.*)\n\n  Definition free_page (i: Z) (c: flatmem) :=\n    setN (list_repeat (Z.to_nat PgSize) Undef) (i * PgSize) c.\n\n  Lemma setN_free_get:\n    forall n i ofs c,\n      i <= ofs < i + (Z.of_nat n) ->\n      (setN (list_repeat n Undef) i c) # ofs = HUndef.\n  Proof.\n    induction n; intros.\n    - Local Transparent Z.of_nat.\n      simpl in H. omega.\n    - Local Opaque Z.of_nat.\n      rewrite Nat2Z.inj_succ in *.\n      Local Transparent list_repeat. simpl.\n      destruct (zeq ofs i); subst.\n      + rewrite setN_other.\n        * rewrite ZMap.gss. reflexivity.\n        * intros. red; intros HF; subst. omega.\n      + eapply IHn. omega.\n  Qed.\n\n  Lemma free_page_gss:\n    forall addr h,\n      ZMap.get addr (free_page (PageI addr) h) = HUndef.\n  Proof.\n    unfold free_page. intros.\n    eapply setN_free_get.\n    rewrite Z2Nat.id; [|omega].\n    unfold PageI. \n    exploit (Z_div_mod_eq addr PgSize). omega.\n    rewrite Zmult_comm.\n    intros Hrange.\n    exploit (Z_mod_lt addr PgSize). omega.\n    intros Hrange'. omega.\n  Qed.\n\n  Lemma free_page_gso:\n    forall addr i h,\n      i <> PageI addr ->\n      ZMap.get addr (free_page i h) = ZMap.get addr h.\n  Proof.\n    unfold free_page. intros.\n    apply setN_other.\n    rewrite length_list_repeat.\n    rewrite Z2Nat.id; [|omega].\n    red; intros; subst. elim H. clear H.\n    unfold PageI. \n    assert (HP: exists a, addr = i * PgSize + a /\\ 0 <= a < PgSize).\n    {\n      exists (addr - i * PgSize).\n      split; omega.\n    }\n    clear H0. destruct HP as (a & Heq & Hrange).\n    rewrite Heq. clear Heq.\n    rewrite Z_div_plus_full_l; [| omega].\n    rewrite Zdiv_small; trivial. omega. \n  Qed.    \n\n  (*Lemma free_page_pperm_inj:\n    forall pp h h',\n    flatmem_pperm_inj pp h h' ->\n    forall i p,\n      flatmem_pperm_inj (ZMap.set i p pp) (free_page i h) h'.\n  Proof.\n    intros. unfold flatmem_pperm_inj in *.\n    intros. destruct (zeq i (PageI addr)); subst.\n    - rewrite free_page_gss.\n      constructor.\n    - rewrite ZMap.gso in H0; auto.\n      rewrite free_page_gso; auto.\n  Qed.*)\n\n  Lemma free_page_inj:\n    forall h h',\n      flatmem_inj h h' ->\n      forall i,\n        flatmem_inj (free_page i h) h'.\n  Proof.\n    intros. unfold flatmem_inj in *.\n    intros. destruct (zeq i (PageI addr)); subst.\n    - rewrite free_page_gss.\n      constructor.\n    - rewrite free_page_gso; auto.\n  Qed.\n\n  Lemma free_page_inj':\n    forall h h',\n      flatmem_inj h h' ->\n      forall i,\n        flatmem_inj (free_page i h) (free_page i h').\n  Proof.\n    intros. unfold flatmem_inj in *.\n    intros. destruct (zeq i (PageI addr)); subst.\n    - rewrite free_page_gss.\n      constructor.\n    - repeat rewrite free_page_gso; auto.\n  Qed.\n\n  Lemma store_unmapped_inj:\n    forall chunk m1 ofs n2 m2 v2 i,\n      flatmem_inj m1 m2 ->\n      store chunk m2 ofs v2 = n2 ->\n      i * PgSize <= ofs <= i * PgSize + PgSize - (size_chunk chunk) ->\n      flatmem_inj (free_page i m1) n2.\n  Proof.\n    intros. unfold flatmem_inj in *. intros.\n    unfold store in *.\n    rewrite <- H0. \n    destruct (zeq i (PageI addr)); subst.\n    - rewrite free_page_gss. constructor.\n    - rewrite free_page_gso; auto.\n      rewrite setN_other; auto.\n      intros. red; intros; subst. elim n.\n      revert H0 H1. clear; intros.\n      assert (HW: exists a, addr = i * PgSize + a\n                            /\\ 0 <= a < PgSize).\n      {\n        exists (addr - i * PgSize).\n        specialize (size_chunk_range chunk); intros.\n        rewrite encode_val_length in H0.\n        rewrite <- size_chunk_conv in H0. \n        unfold ZIndexed.t in *.\n        split; omega. \n      }\n      revert HW; clear; intros.\n      destruct HW as (a & Heq & Hrange). subst.\n      unfold PageI. \n      rewrite Z_div_plus_full_l; [|omega].\n      rewrite Zdiv_small. omega. assumption.\n  Qed.\n\nEnd FlatMem.\n\nNotation flatmem := FlatMem.flatmem.\n\nSection DirtyPPage.\n\nDefinition dirty_ppage (pperm: PPermT) (hp: flatmem) :=\n  forall i o, ZMap.get i pperm = PGHide o -> \n              forall adr,\n                ZMap.get adr hp = ZMap.get adr (FlatMem.free_page i hp).\n\nLemma dirty_ppage_init:\n  forall h,\n    dirty_ppage (ZMap.init PGUndef) h.\nProof.\n  unfold dirty_ppage. intros. \n  rewrite ZMap.gi in H. congruence.\nQed.\n\nLemma dirty_ppage_gso:\n  forall pp h,\n    dirty_ppage pp h ->\n    forall p,\n      (forall o, p <> PGHide o) ->\n      forall n,\n        dirty_ppage (ZMap.set n p pp) h.\nProof.\n  unfold dirty_ppage; intros.\n  destruct (zeq i n); subst.\n  - rewrite ZMap.gss in H1. subst.\n    elim (H0 o). reflexivity.\n  - rewrite ZMap.gso in H1; eauto 2.\nQed.\n\nLemma dirty_ppage_store_unmaped':\n  forall pp h,\n    dirty_ppage pp h ->\n    forall i,\n      ZMap.get (PageI i) pp = PGAlloc (*o*) ->\n      forall v h' chunk,\n        FlatMem.store chunk h i v = h' ->\n        i mod PgSize <= PgSize - size_chunk chunk ->\n        dirty_ppage pp h'.\nProof.\n  unfold dirty_ppage in *. intros. subst.\n  destruct (zeq i0 (PageI adr)); subst.\n  - rewrite FlatMem.free_page_gss.\n    unfold FlatMem.store.\n    erewrite FlatMem.setN_other.\n    + erewrite H; try apply H3.\n      rewrite FlatMem.free_page_gss.\n      reflexivity.\n    + rewrite encode_val_length. rewrite <- size_chunk_conv.\n      red; intros; subst.\n      assert (HW: PageI adr = PageI i).\n      {\n        unfold PageI.\n        assert (HW: exists a, adr = i + a\n                              /\\ 0 <= a < size_chunk chunk).\n        {\n          exists (adr - i).\n          unfold ZIndexed.t in *.\n          split; omega.\n        }\n        destruct HW as (a & Heq & Hrange); subst.\n        assert (HW: exists b c, i = b * PgSize + c\n                                /\\ 0 <= c <= PgSize - size_chunk chunk).\n        {\n          rewrite (Z_div_mod_eq i PgSize); [|omega].\n          rewrite (Zmult_comm PgSize (i/ PgSize)).\n          esplit; esplit; split. reflexivity.\n          exploit  (Z_mod_lt i PgSize). omega.\n          intros (HP & _).\n          split; try assumption. \n        }\n        destruct HW as (b & c & Heq & Hrange'). rewrite Heq.\n        replace (b * PgSize + c + a) with (b * PgSize + (c + a)) by omega.\n        repeat rewrite Z_div_plus_full_l; try omega.\n        repeat rewrite Zdiv_small; omega.\n      }            \n      congruence.\n  - rewrite FlatMem.free_page_gso; trivial.\nQed.\n\nLemma dirty_ppage_store_unmaped:\n  forall pp h,\n    dirty_ppage pp h ->\n    forall i,\n      ZMap.get (PageI (i * 4)) pp = PGAlloc ->\n      forall v h',\n        FlatMem.store Mint32 h (i * 4) v = h' ->\n        dirty_ppage pp h'.\nProof.\n  intros. eapply dirty_ppage_store_unmaped'; try eassumption. \n  clear. simpl.\n  change 4096 with (1024 * 4).\n  rewrite Zmult_mod_distr_r.\n  apply mod_chunk.\nQed.\n\nLemma dirty_ppage_gss:\n  forall pp h,\n    dirty_ppage pp h ->\n    forall o n,\n      dirty_ppage (ZMap.set n (PGHide o) pp) (FlatMem.free_page n h).\nProof.\n  unfold dirty_ppage; intros.\n  destruct (zeq i n); subst.\n  - destruct (zeq n (PageI adr)); subst.\n    + repeat rewrite FlatMem.free_page_gss.\n      reflexivity.\n    + repeat rewrite FlatMem.free_page_gso; auto.\n  - rewrite ZMap.gso in H0; [|assumption].\n    destruct (zeq n (PageI adr)); subst.\n    + repeat rewrite FlatMem.free_page_gss.\n      rewrite FlatMem.free_page_gso; auto.\n      rewrite FlatMem.free_page_gss.               \n      reflexivity.\n    + destruct (zeq i (PageI adr)); subst.\n      * rewrite FlatMem.free_page_gso.\n        rewrite FlatMem.free_page_gss.               \n        erewrite H; [| eassumption].\n        rewrite FlatMem.free_page_gss.               \n        reflexivity. auto.\n      * repeat rewrite FlatMem.free_page_gso; auto.\nQed.\n\nEnd DirtyPPage.\n\nSection DirtyPPage'.\n\nDefinition dirty_ppage' (pperm: PPermT) (hp: flatmem) :=\n  forall i, ZMap.get i pperm <> PGAlloc ->\n              forall adr,\n                ZMap.get adr hp = ZMap.get adr (FlatMem.free_page i hp).\n\nLemma dirty_ppage'_init:\n  dirty_ppage' (ZMap.init PGUndef) FlatMem.empty_flatmem.\nProof.\n  unfold dirty_ppage'; intros; unfold FlatMem.empty_flatmem.\n  destruct (zeq (PageI adr) i); subst.\n  rewrite ZMap.gi; rewrite FlatMem.free_page_gss; auto.\n  rewrite FlatMem.free_page_gso; auto.\nQed.\n\nLemma dirty_ppage'_gso:\n  forall pp h,\n    dirty_ppage' pp h ->\n      forall n,\n        dirty_ppage' (ZMap.set n PGAlloc pp) h.\nProof.\n  unfold dirty_ppage'; intros.\n  destruct (zeq i n); subst.\n  - rewrite ZMap.gss in H0. contradict H0; auto.\n  - rewrite ZMap.gso in H0; auto.\nQed.\n\nLemma dirty_ppage'_store_unmapped':\n  forall pp h,\n    dirty_ppage' pp h ->\n    forall i,\n      ZMap.get (PageI i) pp = PGAlloc ->\n      forall v h' chunk,\n        FlatMem.store chunk h i v = h' ->\n        i mod PgSize <= PgSize - size_chunk chunk ->\n        dirty_ppage' pp h'.\nProof.\n  unfold dirty_ppage' in *. intros. subst.\n  destruct (zeq i0 (PageI adr)); subst.\n  - rewrite FlatMem.free_page_gss.\n    unfold FlatMem.store.\n    erewrite FlatMem.setN_other.\n    + erewrite H; try apply H3.\n      rewrite FlatMem.free_page_gss.\n      reflexivity.\n    + rewrite encode_val_length. rewrite <- size_chunk_conv.\n      red; intros; subst.\n      assert (HW: PageI adr = PageI i).\n      {\n        unfold PageI.\n        assert (HW: exists a, adr = i + a\n                              /\\ 0 <= a < size_chunk chunk).\n        {\n          exists (adr - i).\n          unfold ZIndexed.t in *.\n          split; omega.\n        }\n        destruct HW as (a & Heq & Hrange); subst.\n        assert (HW: exists b c, i = b * PgSize + c\n                                /\\ 0 <= c <= PgSize - size_chunk chunk).\n        {\n          rewrite (Z_div_mod_eq i PgSize); [|omega].\n          rewrite (Zmult_comm PgSize (i/ PgSize)).\n          esplit; esplit; split. reflexivity.\n          exploit  (Z_mod_lt i PgSize). omega.\n          intros (HP & _).\n          split; try assumption. \n        }\n        destruct HW as (b & c & Heq & Hrange'). rewrite Heq.\n        replace (b * PgSize + c + a) with (b * PgSize + (c + a)) by omega.\n        repeat rewrite Z_div_plus_full_l; try omega.\n        repeat rewrite Zdiv_small; omega.\n      }            \n      congruence.\n  - rewrite FlatMem.free_page_gso; trivial.\nQed.\n\nLemma dirty_ppage'_store_unmapped:\n  forall pp h,\n    dirty_ppage' pp h ->\n    forall i,\n      ZMap.get (PageI (i * 4)) pp = PGAlloc ->\n      forall v h',\n        FlatMem.store Mint32 h (i * 4) v = h' ->\n        dirty_ppage' pp h'.\nProof.\n  intros. eapply dirty_ppage'_store_unmapped'; try eassumption. \n  clear. simpl.\n  change 4096 with (1024 * 4).\n  rewrite Zmult_mod_distr_r.\n  apply mod_chunk.\nQed.\n\nLemma dirty_ppage'_gss:\n  forall pp h,\n    dirty_ppage' pp h ->\n    forall p n,\n      dirty_ppage' (ZMap.set n p pp) (FlatMem.free_page n h).\nProof.\n  unfold dirty_ppage'; intros.\n  destruct (zeq i n); subst.\n  - destruct (zeq n (PageI adr)); subst.\n    + repeat rewrite FlatMem.free_page_gss.\n      reflexivity.\n    + repeat rewrite FlatMem.free_page_gso; auto.\n  - rewrite ZMap.gso in H0; [|assumption].\n    destruct (zeq n (PageI adr)); subst.\n    + repeat rewrite FlatMem.free_page_gss.\n      rewrite FlatMem.free_page_gso; auto.\n      rewrite FlatMem.free_page_gss.               \n      reflexivity.\n    + destruct (zeq i (PageI adr)); subst.\n      * rewrite FlatMem.free_page_gso.\n        rewrite FlatMem.free_page_gss.               \n        erewrite H; [| eassumption].\n        rewrite FlatMem.free_page_gss.               \n        reflexivity. auto.\n      * repeat rewrite FlatMem.free_page_gso; auto.\nQed.\n\nLemma dirty_ppage_strengthen:\n  forall pp h, dirty_ppage' pp h -> dirty_ppage pp h.\nProof.\n  unfold dirty_ppage', dirty_ppage; intros.\n  apply H; rewrite H0; discriminate.\nQed.\n\nEnd DirtyPPage'.", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/flatmem/FlatMemory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.273229247116806}}
{"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\nRequire Export proof1.\n\n\n(*\nLemma cequiv_open_unfold_lib {o} :\n  forall lib,\n    no_undefined_abs_in_lib lib\n    -> forall (t : @NTerm o),\n      wf_term t\n      -> cequiv_open lib t (unfold_lib lib t).\nProof.\n  nterm_ind1s t as [v|f ind|op bs ind] Case; introv isp; allsimpl.\n\n  - Case \"vterm\".\n    rewrite unfold_lib_vterm; eauto 3 with slow.\n\n  - Case \"sterm\".\n    rewrite unfold_lib_sterm.\n    apply implies_cequiv_open_sterm; eauto 3 with slow.\n    rewrite <- unfold_lib_sterm.\n    eauto 3 with slow.\n\n  - Case \"oterm\".\n\nLemma unfold_library_oterm_comp {o} :\n  forall lib op (bs : list (@BTerm o)),\n    reduces_to_al\n      lib\n      (oterm op (unfold_library_bterms lib bs))\n      (unfold_library lib (oterm op bs)).\nProof.\n  induction lib; introv; simpl; autorewrite with slow; eauto 3 with slow.\n  rewrite unfold_entry_op_eq.\n  destruct (dec_op_abs op) as [d|d]; exrepnd; subst; allsimpl.\n\n  - unfold unfold_abs_entry.\n    destruct a; allsimpl.\n    boolvar.\n\n    + assert (found_entry\n                (lib_abs opabs vars rhs correct :: lib)\n                abs\n                (map (unfold_entry_bterm (lib_abs opabs vars rhs correct)) bs)\n                opabs vars rhs correct) as fe.\n      {\n        unfold found_entry; simpl.\n        boolvar; tcsp.\n        apply not_matching_entry_iff in n; tcsp.\n      }\n\n      pose proof (compute_step_lib_success_change_bs\n                    (lib_abs opabs vars rhs correct :: lib)\n                    abs opabs\n                    (map (unfold_entry_bterm (lib_abs opabs vars rhs correct)) bs)\n                    (unfold_library_bterms\n                       lib\n                       (map (unfold_entry_bterm (lib_abs opabs vars rhs correct)) bs))\n                    vars rhs correct) as h.\n      repeat (autodimp h hyp).\n      {\n        unfold unfold_library_bterms.\n        allrw map_map.\n        unfold compose, num_bvars; apply eq_maps; introv i.\n        destruct x as [l t]; simpl; auto.\n      }\n\n      eapply reduces_to_al_if_split2;[exact h|].\n      clear h.\n\n      remember (map (unfold_entry_bterm (lib_abs opabs vars rhs correct)) bs) as bs'.\n\n      unfold mk_instance.\n      destruct rhs as [v ts|f|op bs1].\n\n      *\n\nLemma sosub_sovar_alpha_eq {o} :\n  forall var (ts : list (@SOTerm o)) sub,\n    alpha_eq\n      (sosub sub (sovar var ts))\n      (match sosub_find sub (var, length ts) with\n       | Some (sosk vs u) => lsubst u (combine vs (map (sosub sub) ts))\n       | None => apply_list (mk_var var) (map (sosub sub) ts)\n       end).\nProof.\n  introv.\n  pose proof (unfold_sosub sub (sovar var ts)) as h; exrepnd.\n  inversion h2 as [? ? ? len imp| |]; subst; clear h2.\n  rewrite h1; simpl.\n  allsimpl.\n  remember (sosub_find sub' (var, length ts2)) as sf; symmetry in Heqsf; destruct sf.\n\n  - destruct s.\n    pose proof (sosub_find_some_if_alphaeq_sosub\n                  sub' sub (var, length ts2) (sosk l n)) as q.\n    repeat (autodimp q hyp); eauto 3 with slow.\n    exrepnd.\n    rewrite <- len in q0.\n    rewrite q0.\n    destruct sk'.\n\n    applydup @sosub_find_some in Heqsf; repnd.\n    applydup @sosub_find_some in q0; repnd.\n\n    apply alphaeq_sk_iff_alphaeq_bterm2 in q1; simpl in q1.\n    allrw disjoint_cons_l; repnd.\n\n    assert (disjoint (sub_free_vars (combine l (map (sosub_aux sub') ts2)))\n                     (bound_vars n)) as disj.\n    {\n      rewrite sub_free_vars_combine; autorewrite with slow; auto.\n      rewrite flat_map_map; unfold compose.\n      apply disjoint_sym.\n      eapply disjoint_bound_vars_prop4; try (exact Heqsf1); eauto 2 with slow.\n    }\n    rewrite sub_free_vars_combine in disj; autorewrite with slow; auto.\n    rewrite flat_map_map in disj; unfold compose in disj.\n\n    rewrite <- lsubst_lsubst_aux;\n      [|rewrite range_combine;autorewrite with slow;auto;\n        rewrite flat_map_map;unfold compose;eauto 3 with slow\n      ].\n\n    eapply lsubst_alpha_congr4; try (exact q1);\n    try (rewrite dom_sub_combine);autorewrite with slow; auto.\n\n    apply implies_alphaeq_sub_range_combine; autorewrite with slow; auto; try omega.\n    introv i.\n    rewrite <- map_combine in i.\n    apply in_map_iff in i; exrepnd; ginv.\n\n    SearchAbout (alphaeq (sosub _ _) (sosub _ _)).\n\nQed.\n\n      * admit.\n\n      * admit.\n\n      (* by cases on rhs? *)\n\n      (*\n      apply reduces_to_if_step.\n      csunf; simpl.\n      rewrite h; auto.\n       *)\n\n    + pose proof (IHlib\n                    (Abs abs)\n                    (map (unfold_entry_bterm (lib_abs opabs vars rhs correct)) bs))\n        as q; clear IHlib.\n\n      admit.\n\n      (* Prove something like reduces_to_preserves_agreeing_libraries but\n         assuming that the abstractions are not in the extension to the library.\n         This is going to be useful in all 3 cases.\n       *)\n\n  - pose proof (IHlib op (map (unfold_entry_bterm a) bs)) as q; clear IHlib.\n\n    admit.\nQed.\n\n    pose proof (unfold_library_oterm_comp lib op bs) as h.\n\n    eapply cequiv_open_trans;\n      [|apply reduces_to_al_implies_cequiv_open;\n         [|\n          |]\n      ].\n\n    Focus 4.\n\n    Check unfold_library_oterm_comp.\n    SearchAbout cequiv_open reduces_to.\n\nLemma unfold_library_oterm {o} :\n  forall lib,\n    no_undefined_abs_in_lib lib\n    ->\n    forall op (bs : list (@BTerm o)),\n      unfold_library lib (oterm op bs)\n      = match dec_op_abs op with\n        | inl (existT abs _) =>\n          match unfold_abs lib abs bs with\n          | Some t => unfold_library lib t\n          | None => oterm op (unfold_library_bterms lib bs)\n          end\n        | _ => oterm op (unfold_library_bterms lib bs)\n        end.\nProof.\n  induction lib; introv noundef; introv; simpl; auto;\n  autorewrite with slow; auto;\n  destruct (dec_op_abs op) as [d|d]; exrepnd; subst; allsimpl; auto; repnd;\n  autodimp IHlib hyp.\n\n  - destruct a; allsimpl.\n    boolvar.\n\n    +\n\n    + apply not_matching_entry_iff in n; destruct n.\n      eapply matching_entry_change_bs;try (exact m).\n      unfold unfold_library_bterms.\n      allrw map_map; unfold compose.\n      apply eq_maps; introv i.\n      destruct x as [l t]; unfold num_bvars; simpl; auto.\n\n    + apply not_matching_entry_iff in n; destruct n.\n      eapply matching_entry_change_bs;try (exact m).\n      unfold unfold_library_bterms.\n      allrw map_map; unfold compose.\n      apply eq_maps; introv i.\n      destruct x as [l t]; unfold num_bvars; simpl; auto.\n\n    + rewrite IHlib; simpl.\n      destruct (dec_op_abs (Abs abs)) as [e|e]; exrepnd; ginv; auto.\n      destruct e; eexists; eauto.\n\n  - rewrite unfold_entry_op_eq.\n    destruct (dec_op_abs op) as [e|e]; try (complete (destruct d; auto)); GC.\n    rewrite IHlib.\n    destruct (dec_op_abs op) as [e|e]; try (complete (destruct d; auto)); GC.\n    auto.\nQed.\n\nQed.\n*)\n\n(* THIS IS WHERE I'M AT *)\n\n(*\nLemma exists_all_defined {o} :\n  forall lib,\n    no_undefined_abs_in_lib lib\n    -> forall (t : @NTerm o),\n      isprog t\n      -> cequiv lib t (unfold_lib lib t).\nProof.\n  induction lib; intro nodef; simpl.\n\n  - introv isp; dands.\n\n    unfold unfold_lib; simpl.\n    apply cequiv_nil_abs2bot; auto.\n\n  - introv isp.\n    unfold unfold_lib; allsimpl; repnd.\n    autodimp IHlib hyp.\n    pose proof (IHlib (unfold_entry a t)) as h; clear IHlib.\n    autodimp h hyp; eauto 3 with slow; repnd.\n\n    unfold unfold_lib in h.\n\n    assert (cequiv\n              (a :: lib)\n              (unfold_entry a t)\n              (abs2bot (unfold_library lib (unfold_entry a t)))) as ceq;\n      [|eapply cequiv_trans;[|exact ceq];apply cequiv_unfold_entry;auto].\n\n    (* we prove that using add_entry_to_cequiv (see below) *)\n\nFixpoint all_abstractions_not_defined {o} lib (t : @NTerm o) : obool :=\n  match t with\n  | vterm _ => otrue\n  | sterm f => obseq (fun n => all_abstractions_not_defined lib (f n))\n  | oterm op bs =>\n    oband\n      (bool2obool (negb (found_opid_in_library_sign lib op)))\n      (oball (map (all_abstractions_not_defined_b lib) bs))\n  end\nwith all_abstractions_not_defined_b {o} lib (b : @BTerm o) : obool :=\n       match b with\n       | bterm vs t => all_abstractions_not_defined lib t\n       end.\n\nLemma add_entry_to_approx {o} :\n  forall entry lib (t1 t2 : @NTerm o),\n    wf_term t1\n    -> wf_term t2\n    -> isotrue (all_abstractions_not_defined [entry] t1)\n    -> isotrue (all_abstractions_not_defined [entry] t2)\n    -> approx lib t1 t2\n    -> approx (entry :: lib) t1 t2.\nProof.\n  nterm_ind t1 as [v|f ind|op bs ind] Case;\n  introv wf1 wf2 iso1 iso2 apr; allsimpl; GC.\n\n  Focus 2.\n\n  - Case \"vterm\".\n    inversion apr; subst.\n    constructor.\n\nLemma approx_open_vterm_implies {o} :\n  forall lib v (t : @NTerm o),\n    approx_open lib (vterm v) t -> t = vterm v.\nProof.\n  introv ceq.\n  apply olift_cequiv_approx in ceq; repnd.\n  clear ceq0.\n\n  SearchAbout approx_open vterm.\nQed.\n\nQed.\n\nFocus 2.\n\nXXXXXXXXXXX\n\nQed.\n *)\n\n\nLemma free_vars_unfold_library {o} :\n  forall lib (t : @NTerm o),\n    subset (free_vars (unfold_library lib t)) (free_vars t).\nProof.\n  induction lib; simpl; introv; auto.\n  eapply subset_trans;[apply IHlib|].\n  apply free_vars_unfold_entry.\nQed.\n\nLemma isprog_unfold_library {o} :\n  forall lib (t : @NTerm o),\n    isprog t\n    -> isprog (unfold_library lib t).\nProof.\n  introv isp; allrw @isprog_eq.\n  inversion isp as [cl wf].\n  constructor; allrw @nt_wf_eq; eauto 3 with slow.\n  pose proof (free_vars_unfold_library lib t) as h.\n  rewrite cl in h.\n  apply subset_nil_implies_nil; auto.\nQed.\n\nLemma isprog_unfold_lib {o} :\n  forall lib (t : @NTerm o),\n    isprog t\n    -> isprog (unfold_lib lib t).\nProof.\n  introv isp.\n  apply implies_isprog_abs2bot.\n  apply isprog_unfold_library; auto.\nQed.\n\nDefinition unfold_libc {o} lib (t : @CTerm o) :=\n  match t with\n  | exist _ a p => mk_ct (unfold_lib lib a) (isprog_unfold_lib lib a p)\n  end.\n\nLemma isotrue_all_abs_are_defined_unfold_lib {o} :\n  forall lib1 lib2 (t : @NTerm o),\n    isotrue (all_abstractions_are_defined lib1 (unfold_lib lib2 t)).\nProof.\n  introv.\n  apply isotrue_all_abs_are_defined_abs2bot.\nQed.\n\nLemma isotrue_all_abs_are_defined_cterm_unfold_libc {o} :\n  forall lib1 lib2 (t : @CTerm o),\n    isotrue (all_abstractions_are_defined_cterm lib1 (unfold_libc lib2 t)).\nProof.\n  introv.\n  destruct_cterms.\n  unfold all_abstractions_are_defined_cterm; simpl.\n  apply isotrue_all_abs_are_defined_unfold_lib.\nQed.\nHint Resolve isotrue_all_abs_are_defined_cterm_unfold_libc : slow.\n\nLemma isotrue_all_abs_are_defined_cterm_approx {o} :\n  forall lib (a b : @CTerm o),\n    isotrue (all_abstractions_are_defined_cterm lib a)\n    -> isotrue (all_abstractions_are_defined_cterm lib b)\n    -> isotrue (all_abstractions_are_defined_cterm lib (mkc_approx a b)).\nProof.\n  introv h1 h2.\n  destruct_cterms.\n  allunfold @all_abstractions_are_defined_cterm; allsimpl.\n  autorewrite with slow.\n  apply isotrue_oband; auto.\nQed.\n\nLemma isotrue_all_abs_are_defined_cterm_cequiv {o} :\n  forall lib (a b : @CTerm o),\n    isotrue (all_abstractions_are_defined_cterm lib a)\n    -> isotrue (all_abstractions_are_defined_cterm lib b)\n    -> isotrue (all_abstractions_are_defined_cterm lib (mkc_cequiv a b)).\nProof.\n  introv h1 h2.\n  destruct_cterms.\n  allunfold @all_abstractions_are_defined_cterm; allsimpl.\n  autorewrite with slow.\n  apply isotrue_oband; auto.\nQed.\n\nLemma approx_decomp_cequiv {p} :\n  forall lib a b c d,\n    approx lib (mk_cequiv a b) (@mk_cequiv p c d)\n    <=> approx lib a c # approx lib b d.\nProof.\n  split; unfold mk_cequiv; introv Hyp.\n  - applydup @approx_relates_only_progs in Hyp. repnd.\n    apply  approx_canonical_form2 in Hyp.\n    unfold lblift in Hyp. repnd. allsimpl.\n    alpharelbtd. GC.\n    eapply blift_approx_open_nobnd in Hyp1bt; eauto 3 with slow.\n    eapply blift_approx_open_nobnd in Hyp0bt; eauto 3 with slow.\n  - repnd. applydup @approx_relates_only_progs in Hyp. repnd.\n    applydup @approx_relates_only_progs in Hyp0. repnd.\n    apply approx_canonical_form3.\n    + apply isprogram_ot_iff. allsimpl. dands; auto. introv Hin.\n      dorn Hin;[| dorn Hin]; sp;[|];\n      subst; apply implies_isprogram_bt0; eauto with slow.\n    + apply isprogram_ot_iff. allsimpl. dands; auto. introv Hin.\n      dorn Hin;[| dorn Hin]; sp;[|];\n      subst; apply implies_isprogram_bt0; eauto with slow.\n    + unfold lblift. allsimpl. split; auto.\n      introv Hin. unfold selectbt.\n      repeat(destruct n; try (omega;fail); allsimpl);\n      apply blift_approx_open_nobnd2; sp.\nQed.\n\nLemma cequiv_decomp_cequiv {p} :\n  forall lib a b c d,\n    cequiv lib (mk_cequiv a b) (@mk_cequiv p c d)\n    <=> cequiv lib a c # cequiv lib b d.\nProof.\n  intros.\n  unfold cequiv.\n  generalize (approx_decomp_cequiv lib a b c d); intro.\n  trewrite X; clear X.\n  generalize (approx_decomp_cequiv lib c d a b); intro.\n  trewrite X; clear X.\n  split; sp.\nQed.\n\nLemma cequivc_decomp_cequiv {p} :\n  forall lib a b c d,\n    cequivc lib (mkc_cequiv a b) (@mkc_cequiv p c d)\n    <=> cequivc lib a c # cequivc lib b d.\nProof.\n  destruct a, b, c, d.\n  unfold cequivc, mkc_cequiv; simpl.\n  apply cequiv_decomp_cequiv.\nQed.\n\nLemma cequivc_unfold_lib {o} :\n  forall lib,\n    no_undefined_abs_in_lib lib\n    -> forall (t : @CTerm o),\n      cequivc lib t (unfold_libc lib t).\nProof.\n  (* see above *)\nAdmitted.\n\nDefinition ex_all_defined {o} lib (t : @CTerm o) :=\n  {u : CTerm\n   , ccequivc lib t u\n   /\\ isotrue (all_abstractions_are_defined_cterm lib u) }.\n\nLemma restrict_to_lib_eq_in_nuprl {o} :\n  forall lib (T T' : @CTerm o) eq,\n    no_undefined_abs_in_lib lib\n    -> nuprl lib T T' eq\n    ->\n    (\n      ex_all_defined lib T\n      /\\ forall t t', eq t t' -> ex_all_defined lib t\n    ).\nProof.\n  introv noundef n.\n  dands.\n  - pose proof (cequivc_unfold_lib lib noundef T) as h.\n    exists (unfold_libc lib T); dands; spcast; eauto 3 with slow.\n  - introv e.\n    pose proof (cequivc_unfold_lib lib noundef t) as h.\n    exists (unfold_libc lib t); dands; spcast; eauto 3 with slow.\n\n    (*\n  unfold nuprl in n.\n  remember (univ lib) as ts.\n  close_cases (induction n using @close_ind') Case; subst; introv.\n\n  - Case \"CL_init\".\n    duniv i h.\n\n    revert dependent eq.\n    revert dependent T.\n    revert dependent T'.\n    induction i; introv u; allsimpl; tcsp.\n    repndors; exrepnd; spcast; try (complete (apply IHi in u; tcsp)).\n\n    dands.\n\n    + exists (@mkc_uni o i); dands; simpl; auto.\n      spcast; eauto 3 with slow.\n\n    + introv e.\n      apply u in e; exrepnd.\n\n      remember (univi lib i) as ts.\n      close_cases (induction e0 using @close_ind') SCase; subst; introv.\n\n      * SCase \"CL_init\".\n        match goal with\n        | [ H : univi _ _ _ _ _ |- _ ] => apply IHi in H; sp\n        end.\n\n      * SCase \"CL_int\".\n        allunfold @per_int; repnd; spcast.\n        exists (@mkc_int o); simpl; dands; spcast; eauto 3 with slow.\n\n      * SCase \"CL_atom\".\n        allunfold @per_atom; repnd; spcast.\n        exists (@mkc_atom o); simpl; dands; spcast; eauto 3 with slow.\n\n      * SCase \"CL_uatom\".\n        allunfold @per_uatom; repnd; spcast.\n        exists (@mkc_uatom o); simpl; dands; spcast; eauto 3 with slow.\n\n      * SCase \"CL_base\".\n        allunfold @per_base; repnd; spcast.\n        exists (@mkc_base o); simpl; dands; spcast; eauto 3 with slow.\n\n      * SCase \"CL_approx\".\n        allunfold @per_approx; exrepnd; spcast.\n\n        pose proof (cequivc_unfold_lib lib noundef a) as ha.\n        pose proof (cequivc_unfold_lib lib noundef b) as hb.\n\n        exists (mkc_approx (unfold_libc lib a) (unfold_libc lib b)); simpl; dands; spcast; eauto 3 with slow.\n\n        {\n          eapply cequivc_trans;[apply computes_to_valc_implies_cequivc; eauto|].\n          apply cequivc_decomp_approx; auto.\n        }\n\n        {\n          apply isotrue_all_abs_are_defined_cterm_approx; eauto 3 with slow.\n        }\n\n      * SCase \"CL_cequiv\".\n        allunfold @per_cequiv; exrepnd; spcast.\n\n        pose proof (cequivc_unfold_lib lib noundef a) as ha.\n        pose proof (cequivc_unfold_lib lib noundef b) as hb.\n\n        exists (mkc_cequiv (unfold_libc lib a) (unfold_libc lib b)); simpl; dands; spcast; eauto 3 with slow.\n\n        {\n          eapply cequivc_trans;[apply computes_to_valc_implies_cequivc; eauto|].\n          apply cequivc_decomp_cequiv; auto.\n        }\n\n        {\n          apply isotrue_all_abs_are_defined_cterm_cequiv; eauto 3 with slow.\n        }\n\n      *\n*)\nQed.\n\nLemma tequality_cons_library_entry {o} :\n  forall lib1 lib2 (t1 t2 : @CTerm o) eq,\n    assert (wf_library lib1)\n    -> assert (wf_library lib2)\n    -> libraries_agree_on_intersection lib1 lib2\n    -> no_repeats_lib lib2\n    -> simple_no_undefined_abs_in_lib lib1\n    -> simple_no_undefined_abs_in_lib lib2\n    -> isotrue (all_abstractions_are_defined_cterm lib1 t1)\n    -> isotrue (all_abstractions_are_defined_cterm lib1 t2)\n    -> isotrue (all_abstractions_are_defined_cterm lib2 t1)\n    -> isotrue (all_abstractions_are_defined_cterm lib2 t2)\n    -> nuprl lib1 t1 t2 eq\n    -> nuprl lib2 t1 t2 eq.\nProof.\n  introv wflib1 wflib2 agree norep undef1 undef2;\n  introv iso11 iso12 iso21 iso22 n.\n  allunfold @nuprl.\n\n  remember (univ lib1) as ts.\n  close_cases (induction n using @close_ind') Case; subst.\n\n  (*\n  - Case \"CL_init\".\n    duniv i h.\n\n    induction i; allsimpl; tcsp.\n    repndors; exrepnd; spcast;\n    try (complete (autodimp IHi hyp)).\n\n    apply CL_init.\n    exists (S i); simpl.\n    left; dands; auto; spcast;\n    try (complete (apply computes_to_valc_consistent_with_new_definition; auto)).\n*)\n\n(*\nFocus 6.\n  - Case \"CL_approx\".\n    unfold per_approx in per; exrepnd; spcast.\n    eexists.\n    apply CL_approx.\n    unfold per_approx.\n    eexists; eexists; eexists; eexists; dands; spcast;\n    try (complete (apply computes_to_valc_consistent_with_new_definition; eauto));\n    try (complete (introv; apply t_iff_refl)).\n    allrw @approx_stable_iff; auto.\n*)\n\n  Focus 11.\n\n  - Case \"CL_func\".\n    clear per; spcast.\n    apply CL_func.\n    unfold per_func.\n    exists eqa eqb; dands; auto.\n    unfold type_family.\n    exists A A' v v' B B'; dands; spcast; auto.\n\n    { apply (computes_to_value_preserves_agreeing_libraries lib1 lib2); eauto 2 with slow. }\n\n    { apply (computes_to_value_preserves_agreeing_libraries lib1 lib2); eauto 2 with slow. }\n\n    { apply IHn; auto.\n      admit.\n      admit.\n      admit.\n      admit.\n\n    }\n\n    {\n      introv.\n\n      apply recb; auto.\n    }\n\nXXXXXXXXXXXXXXXXXXX\n\n    rename eq0 into eqa0.\n\n    assert (forall a a' : CTerm,\n               eqa a a' ->\n               exists eq0,\n                 close (e :: lib)\n                       (univ (e :: lib))\n                       (B) [[v \\\\ a]]\n                       (B') [[v' \\\\ a']]\n                       eq0) as recbb.\n    { introv h; apply recb; auto. }\n    clear recb.\n\n    apply choice_teq0 in recbb; exrepnd.\n    rename f into eqb0.\n\n    exists (fun t t' =>\n              forall a a' (e : eqa0 a a'),\n                (eqb0 a a' e) (mkc_apply t a) (mkc_apply t' a')).\n\n  - Case \"CL_init\".\n    duniv i h.\n\n    induction i; allsimpl; tcsp.\n    repndors; exrepnd; spcast.\n\n    + exists (fun A A' => exists eqa, close (e :: lib) (univi (e :: lib) i) A A' eqa).\n      apply CL_init.\n      exists (S i); simpl.\n      left; dands; auto; spcast;\n      try (complete (apply computes_to_valc_consistent_with_new_definition; auto)).\n\n    + autodimp IHi hyp.\n\n  - Case \"CL_int\".\n    exists (equality_of_int (e :: lib)).\n    apply CL_int.\n    allunfold @per_int; repnd; dands; auto; spcast;\n    try (complete (apply computes_to_valc_consistent_with_new_definition; auto)).\n\n  - Case \"CL_atom\".\n    unfold per_atom in per; repnd; spcast.\n    eexists.\n    apply CL_atom.\n    unfold per_atom; repnd; dands; auto; spcast;\n    try (complete (apply computes_to_valc_consistent_with_new_definition; auto)).\n\n  - Case \"CL_uatom\".\n    unfold per_uatom in per; repnd; spcast.\n    eexists.\n    apply CL_uatom.\n    unfold per_uatom; repnd; dands; auto; spcast;\n    try (complete (apply computes_to_valc_consistent_with_new_definition; auto)).\n\n  - Case \"CL_base\".\n    unfold per_base in per; repnd; spcast.\n    eexists.\n    apply CL_base.\n    unfold per_base; repnd; dands; auto; spcast;\n    try (complete (apply computes_to_valc_consistent_with_new_definition; auto)).\n\n  - Case \"CL_approx\".\n    unfold per_approx in per; exrepnd; spcast.\n    eexists.\n    apply CL_approx.\n    unfold per_approx.\n    eexists; eexists; eexists; eexists; dands; spcast;\n    try (complete (apply computes_to_valc_consistent_with_new_definition; eauto));\n    try (complete (introv; apply t_iff_refl)).\n    allrw @approx_stable_iff; auto.\n\n  - Case \"CL_cequiv\".\n    unfold per_cequiv in per; exrepnd; spcast.\n    eexists.\n    apply CL_cequiv.\n    unfold per_cequiv.\n    eexists; eexists; eexists; eexists; dands; spcast;\n    try (complete (apply computes_to_valc_consistent_with_new_definition; eauto));\n    try (complete (introv; apply t_iff_refl)).\n    allrw @cequiv_stable_iff; auto.\n\n  - Case \"CL_eq\".\n    clear per.\n    autodimp IHteq0 hyp; exrepnd.\n    eexists.\n    apply CL_eq.\n    unfold per_eq.\n    eexists; eexists; eexists; eexists; eexists; eexists; eexists; dands; spcast;\n    try (complete (apply computes_to_valc_consistent_with_new_definition; eauto));\n    try (complete (introv; apply t_iff_refl)); eauto.\n    allrw @cequiv_stable_iff; auto.\nQed.\n\nLemma tequality_cons_library_entry {o} :\n  forall lib e (t1 t2 : @CTerm o),\n    !in_lib (opabs_of_lib_entry e) lib\n    -> tequality lib t1 t2\n    -> tequality (e :: lib) t1 t2.\nProof.\n  introv p teq.\n  allunfold @tequality; exrepnd.\n  allunfold @nuprl.\n\n  remember (univ lib) as ts.\n  close_cases (induction teq0 using @close_ind') Case; subst.\n\n  Focus 11.\n\n  - Case \"CL_func\".\n    clear per; spcast.\n    autodimp IHteq0 hyp; exrepnd.\n    rename eq0 into eqa0.\n\n    assert (forall a a' : CTerm,\n               eqa a a' ->\n               exists eq0,\n                 close (e :: lib)\n                       (univ (e :: lib))\n                       (B) [[v \\\\ a]]\n                       (B') [[v' \\\\ a']]\n                       eq0) as recbb.\n    { introv h; apply recb; auto. }\n    clear recb.\n\n    apply choice_teq0 in recbb; exrepnd.\n    rename f into eqb0.\n\n    exists (fun t t' =>\n              forall a a' (e : eqa0 a a'),\n                (eqb0 a a' e) (mkc_apply t a) (mkc_apply t' a')).\n\n  - Case \"CL_init\".\n    duniv i h.\n\n    induction i; allsimpl; tcsp.\n    repndors; exrepnd; spcast.\n\n    + exists (fun A A' => exists eqa, close (e :: lib) (univi (e :: lib) i) A A' eqa).\n      apply CL_init.\n      exists (S i); simpl.\n      left; dands; auto; spcast;\n      try (complete (apply computes_to_valc_consistent_with_new_definition; auto)).\n\n    + autodimp IHi hyp.\n\n  - Case \"CL_int\".\n    exists (equality_of_int (e :: lib)).\n    apply CL_int.\n    allunfold @per_int; repnd; dands; auto; spcast;\n    try (complete (apply computes_to_valc_consistent_with_new_definition; auto)).\n\n  - Case \"CL_atom\".\n    unfold per_atom in per; repnd; spcast.\n    eexists.\n    apply CL_atom.\n    unfold per_atom; repnd; dands; auto; spcast;\n    try (complete (apply computes_to_valc_consistent_with_new_definition; auto)).\n\n  - Case \"CL_uatom\".\n    unfold per_uatom in per; repnd; spcast.\n    eexists.\n    apply CL_uatom.\n    unfold per_uatom; repnd; dands; auto; spcast;\n    try (complete (apply computes_to_valc_consistent_with_new_definition; auto)).\n\n  - Case \"CL_base\".\n    unfold per_base in per; repnd; spcast.\n    eexists.\n    apply CL_base.\n    unfold per_base; repnd; dands; auto; spcast;\n    try (complete (apply computes_to_valc_consistent_with_new_definition; auto)).\n\n  - Case \"CL_approx\".\n    unfold per_approx in per; exrepnd; spcast.\n    eexists.\n    apply CL_approx.\n    unfold per_approx.\n    eexists; eexists; eexists; eexists; dands; spcast;\n    try (complete (apply computes_to_valc_consistent_with_new_definition; eauto));\n    try (complete (introv; apply t_iff_refl)).\n    allrw @approx_stable_iff; auto.\n\n  - Case \"CL_cequiv\".\n    unfold per_cequiv in per; exrepnd; spcast.\n    eexists.\n    apply CL_cequiv.\n    unfold per_cequiv.\n    eexists; eexists; eexists; eexists; dands; spcast;\n    try (complete (apply computes_to_valc_consistent_with_new_definition; eauto));\n    try (complete (introv; apply t_iff_refl)).\n    allrw @cequiv_stable_iff; auto.\n\n  - Case \"CL_eq\".\n    clear per.\n    autodimp IHteq0 hyp; exrepnd.\n    eexists.\n    apply CL_eq.\n    unfold per_eq.\n    eexists; eexists; eexists; eexists; eexists; eexists; eexists; dands; spcast;\n    try (complete (apply computes_to_valc_consistent_with_new_definition; eauto));\n    try (complete (introv; apply t_iff_refl)); eauto.\n    allrw @cequiv_stable_iff; auto.\nQed.\n\nLemma cover_vars_nil_iff_closed {o} :\n  forall (t : @NTerm o), cover_vars t [] <=> closed t.\nProof.\n  introv.\n  rw @cover_vars_eq; simpl.\n  unfold closed.\n  rw subvars_eq; split; intro h; try (rewrite h); auto.\n  remember (free_vars t) as l; clear Heql; destruct l; auto.\n  apply subset_cons_nil in h; tcsp.\nQed.\n\nLemma cover_vars_nil2closed {o} :\n  forall {t : @NTerm o}, cover_vars t [] -> closed t.\nProof.\n  introv cov.\n  apply cover_vars_nil_iff_closed; auto.\nQed.\n\nLemma wfClosed2isprogram {o} :\n  forall {t : @NTerm o},\n    wf_term t\n    -> closed t\n    -> isprogram t.\nProof.\n  introv w c.\n  constructor; eauto 3 with slow.\nQed.\n\nDefinition mk_cterm_wc {o}\n           (t : @NTerm o)\n           (w : wf_term t)\n           (c : cover_vars t []) : CTerm :=\n  mk_cterm t (wfClosed2isprogram w (cover_vars_nil2closed c)).\n\nLemma lsubstc_sub_nil {o} :\n  forall (t : @NTerm o) w c,\n    lsubstc t w [] c = mk_cterm_wc t w c.\nProof.\n  introv.\n  apply cterm_eq; simpl.\n  apply csubst_nil.\nQed.\n\nLemma sequent_true2_cons_library_entry {o} :\n  forall lib e (c : @conclusion o),\n    sequent_true2 lib (mk_baresequent [] c)\n    -> sequent_true2 (e :: lib) (mk_baresequent [] c).\nProof.\n  introv h.\n  allunfold @sequent_true2; exrepnd.\n  exists c0.\n  allrw @sequent_true_eq_VR.\n  allunfold @VR_sequent_true; introv.\n  pose proof (h0 s1 s2) as q; clear h0; simpl in *.\n  intros sim hf.\n  dup sim as sim'.\n  apply similarity_nil_implies in sim'; repnd; subst; allsimpl.\n  pose proof (q (sim_nil lib) (hyps_functionality_nil lib)) as h; clear q; repnd.\n\n  dands.\n\n  - clear h.\n\n    match goal with [ |- tequality _ (lsubstc _ _ _ ?c) _ ] => let c := fresh \"c\" in remember c; clear_eq1 c end.\n    match goal with [ |- tequality _ _ (lsubstc _ _ _ ?c) ] => let c := fresh \"c\" in remember c; clear_eq1 c end.\n    match goal with [ H : tequality _ (lsubstc _ _ _ ?c) _ |- _ ] => let c := fresh \"c\" in remember c; clear_eq1 c end.\n    match goal with [ H : tequality _ _ (lsubstc _ _ _ ?c) |- _ ] => let c := fresh \"c\" in remember c; clear_eq1 c end.\n    proof_irr.\n    allrw @lsubstc_sub_nil.\n\nQed.\n\n(* By assuming [wf_bseq seq], when we start with a sequent with no hypotheses,\n   it means that we have to prove that the conclusion is well-formed and closed.\n *)\nLemma valid_proof {o} :\n  forall ctxt (seq : @baresequent o) (wf : wf_bseq seq),\n    Library ctxt\n    -> proof ctxt seq\n    -> sequent_true2 ctxt seq.\nProof.\n  introv wf Lib p.\n  induction p\n    as [ (* proved sequent       *) seq p\n       | (* isect_eq             *) a1 a2 b1 b2 e1 e2 x1 x2 y i hs niy p1 ih1 p2 ih2\n       | (* approx_refl          *) a hs\n       | (* cequiv_approx        *) a b e1 e2 hs p1 ih1 p2 ih2\n       | (* approx_eq            *) a1 a2 b1 b2 e1 e2 i hs p1 ih1 p2 ih2\n       | (* cequiv_eq            *) a1 a2 b1 b2 e1 e2 i hs p1 ih1 p2 ih2\n       | (* bottom_diverges      *) x hs js\n       | (* cut                  *) B C t u x hs wB covB nixH p1 ih1 p2 ih2\n       | (* equal_in_base        *) a b e F H p1 ih1 ps ihs\n       | (* hypothesis           *) x A G J\n       | (* cequiv_subst_concl   *) C x a b t e H wfa wfb cova covb p1 ih1 p2 ih2\n       | (* approx_member_eq     *) a b e H p ih\n       | (* cequiv_computation   *) a b H p ih\n       | (* function elimination *) A B C a e ea f x z H J wa cova nizH nizJ dzf p1 ih1 p2 ih2\n       ];\n    allsimpl;\n    allrw NVin_iff.\n\n  -\n\nLemma seq_in_library_is_true {o} :\n  forall (ctxt : @ProofContext o) c,\n    Library ctxt\n    -> LIn c (PC_conclusions ctxt)\n    -> sequent_true2 ctxt (mk_baresequent [] c).\nProof.\n  introv Lib.\n  induction Lib; simpl; introv i; tcsp.\n  - autodimp IHLib hyp.\n\nQed.\n\n  - apply (rule_isect_equality2_true3 lib a1 a2 b1 b2 e1 e2 x1 x2 y i hs); simpl; tcsp.\n\n    + unfold args_constraints; simpl; introv h; repndors; subst; tcsp.\n\n    + introv e; repndors; subst; tcsp.\n\n      * apply ih1; auto.\n        apply (rule_isect_equality2_wf2 y i a1 a2 b1 b2 e1 e2 x1 x2 hs); simpl; tcsp.\n\n      * apply ih2; auto.\n        apply (rule_isect_equality2_wf2 y i a1 a2 b1 b2 e1 e2 x1 x2 hs); simpl; tcsp.\n\n  - apply (rule_approx_refl_true3 lib hs a); simpl; tcsp.\n\n  - apply (rule_cequiv_approx2_true3 lib hs a b e1 e2); simpl; tcsp.\n    introv xx; repndors; subst; tcsp.\n\n    apply ih2; auto.\n    apply (rule_cequiv_approx2_wf2 a b e1 e2 hs); simpl; tcsp.\n\n  - apply (rule_approx_eq2_true3 lib a1 a2 b1 b2 e1 e2 i hs); simpl; tcsp.\n    introv xx; repndors; subst; tcsp.\n\n    + apply ih1; auto.\n      apply (rule_approx_eq2_wf2 a1 a2 b1 b2 e1 e2 i hs); simpl; tcsp.\n\n    + apply ih2; auto.\n      apply (rule_approx_eq2_wf2 a1 a2 b1 b2 e1 e2 i hs); simpl; tcsp.\n\n  - apply (rule_cequiv_eq2_true3 lib a1 a2 b1 b2 e1 e2 i hs); simpl; tcsp.\n    introv xx; repndors; subst; tcsp.\n\n    + apply ih1; auto.\n      apply (rule_cequiv_eq2_wf2 a1 a2 b1 b2 e1 e2 i hs); simpl; tcsp.\n\n    + apply ih2; auto.\n      apply (rule_cequiv_eq2_wf2 a1 a2 b1 b2 e1 e2 i hs); simpl; tcsp.\n\n  - apply (rule_bottom_diverges_true3 lib x hs js); simpl; tcsp.\n\n  - apply (rule_cut_true3 lib hs B C t u x); simpl; tcsp.\n\n    + unfold args_constraints; simpl; introv xx; repndors; subst; tcsp.\n\n    + introv xx; repndors; subst; tcsp.\n\n      * apply ih1.\n        apply (rule_cut_wf2 hs B C t u x); simpl; tcsp.\n\n      * apply ih2.\n        apply (rule_cut_wf2 hs B C t u x); simpl; tcsp.\n\n  - apply (rule_equal_in_base2_true3 lib H a b e F); simpl; tcsp.\n\n    introv xx; repndors; subst; tcsp.\n    unfold rule_equal_in_base2_rest in xx; apply in_mapin in xx; exrepnd; subst.\n    pose proof (ihs a0 i) as hh; clear ihs.\n    repeat (autodimp hh hyp).\n    pose proof (rule_equal_in_base2_wf2 H a b e F) as w.\n    apply w; simpl; tcsp.\n    right.\n    apply in_mapin; eauto.\n\n  - apply (rule_hypothesis_true3 lib); simpl; tcsp.\n\n  - apply (rule_cequiv_subst_concl2_true3 lib H x C a b t e); allsimpl; tcsp.\n\n    introv i; repndors; subst; allsimpl; tcsp.\n\n    + apply ih1.\n      apply (rule_cequiv_subst_concl2_wf2 H x C a b t e); simpl; tcsp.\n\n    + apply ih2.\n      apply (rule_cequiv_subst_concl2_wf2 H x C a b t e); simpl; tcsp.\n\n  - apply (rule_approx_member_eq2_true3 lib a b e); simpl; tcsp.\n    introv xx; repndors; subst; tcsp.\n    apply ih.\n    apply (rule_approx_member_eq2_wf2 a b e H); simpl; tcsp.\n\n  - apply (rule_cequiv_computation_true3 lib); simpl; tcsp.\n\n  - apply (rule_function_elimination_true3 lib A B C a e ea f x z); simpl; tcsp.\n\n    introv ih; repndors; subst; tcsp.\n\n    + apply ih1.\n      pose proof (rule_function_elimination_wf2 A B C a e ea f x z H J) as h.\n      unfold wf_rule2, wf_subgoals2 in h; simpl in h.\n      repeat (autodimp h hyp).\n\n    + apply ih2.\n      pose proof (rule_function_elimination_wf2 A B C a e ea f x z H J) as h.\n      unfold wf_rule2, wf_subgoals2 in h; simpl in h.\n      repeat (autodimp h hyp).\nQed.\n\nFixpoint map_option\n         {T U : Type}\n         (f : T -> option U)\n         (l : list T) : option (list U) :=\n  match l with\n  | [] => Some []\n  | t :: ts =>\n    match f t, map_option f ts with\n    | Some u, Some us => Some (u :: us)\n    | _, _ => None\n    end\n  end.\n\nFixpoint map_option_in\n         {T U : Type}\n         (l : list T)\n  : forall (f : forall (t : T) (i : LIn t l), option U), option (list U) :=\n  match l with\n  | [] => fun f => Some []\n  | t :: ts =>\n    fun f =>\n      match f t (@inl (t = t) (LIn t ts) eq_refl), map_option_in ts (fun x i => f x (inr i)) with\n      | Some u, Some us => Some (u :: us)\n      | _, _ => None\n      end\n  end.\n\nFixpoint map_option_in_fun\n         {T U}\n         (l : list T)\n  : (forall t, LIn t l -> option (U t)) -> option (forall t, LIn t l -> U t) :=\n  match l with\n  | [] => fun f => Some (fun t (i : LIn t []) => match i with end)\n  | t :: ts =>\n    fun (f : forall x, LIn x (t :: ts) -> option (U x)) =>\n      match f t (@inl (t = t) (LIn t ts) eq_refl),\n            map_option_in_fun ts (fun x i => f x (inr i)) with\n      | Some u, Some g => Some (fun x (i : LIn x (t :: ts)) =>\n                                   match i with\n                                   | inl e => transport e u\n                                   | inr j => g x j\n                                   end)\n      | _, _ => None\n      end\n  end.\n\nLemma map_option_in_fun2_lem :\n  forall {T : Type }\n         (l : list T)\n         (U : forall (t : T) (i : LIn t l), Type)\n         (f : forall (t : T) (i : LIn t l), option (U t i)),\n    option (forall t (i : LIn t l), U t i).\nProof.\n  induction l; introv f; simpl in *.\n  - left; introv; destruct i.\n  - pose proof (f a (inl eq_refl)) as opt1.\n    destruct opt1 as [u|];[|right].\n    pose proof (IHl (fun x i => U x (inr i)) (fun x i => f x (inr i))) as opt2.\n    destruct opt2 as [g|];[|right].\n    left.\n    introv.\n    destruct i as [i|i].\n    + rewrite <- i.\n      exact u.\n    + apply g.\nDefined.\n\nFixpoint map_option_in_fun2\n         {T : Type }\n         (l : list T)\n  : forall (U : forall (t : T) (i : LIn t l), Type),\n    (forall (t : T) (i : LIn t l), option (U t i))\n    -> option (forall t (i : LIn t l), U t i) :=\n  match l with\n  | [] => fun U f => Some (fun t (i : LIn t []) => match i with end)\n  | t :: ts =>\n    fun (U : forall (x : T) (i : LIn x (t :: ts)), Type)\n        (f : forall x (i : LIn x (t :: ts)), option (U x i)) =>\n      match f t (@inl (t = t) (LIn t ts) eq_refl),\n            @map_option_in_fun2 T ts (fun x i => U x (inr i)) (fun x i => f x (inr i))\n            return option (forall x (i : LIn x (t :: ts)), U x i)\n      with\n      | Some u, Some g => Some (fun x (i : LIn x (t :: ts)) =>\n                                  match i as s return U x s with\n                                  | inl e =>\n                                    internal_eq_rew_dep\n                                      T t\n                                      (fun (x : T) (i : t = x) => U x injL(i))\n                                      u x e\n                                  | inr j => g x j\n                                  end)\n      | _, _ => None\n      end\n  end.\n\nFixpoint finish_pre_proof\n         {o} {seq : @pre_baresequent o} {h : bool} {lib}\n         (prf: pre_proof h lib seq) : option (pre_proof false lib seq) :=\n  match prf with\n  | pre_proof_hole s e => None\n  | pre_proof_isect_eq a1 a2 b1 b2 x1 x2 y i H niyH pa pb =>\n    match finish_pre_proof pa, finish_pre_proof pb with\n    | Some p1, Some p2 => Some (pre_proof_isect_eq _ _ a1 a2 b1 b2 x1 x2 y i H niyH p1 p2)\n    | _, _ => None\n    end\n  | pre_proof_approx_refl a H => Some (pre_proof_approx_refl _ _ a H)\n  | pre_proof_cequiv_approx a b H p1 p2 =>\n    match finish_pre_proof p1, finish_pre_proof p2 with\n    | Some p1, Some p2 => Some (pre_proof_cequiv_approx _ _ a b H p1 p2)\n    | _, _ => None\n    end\n  | pre_proof_approx_eq a1 a2 b1 b2 i H p1 p2 =>\n    match finish_pre_proof p1, finish_pre_proof p2 with\n    | Some p1, Some p2 => Some (pre_proof_approx_eq _ _ a1 a2 b1 b2 i H p1 p2)\n    | _, _ => None\n    end\n  | pre_proof_cequiv_eq a1 a2 b1 b2 i H p1 p2 =>\n    match finish_pre_proof p1, finish_pre_proof p2 with\n    | Some p1, Some p2 => Some (pre_proof_cequiv_eq _ _ a1 a2 b1 b2 i H p1 p2)\n    | _, _ => None\n    end\n  | pre_proof_bottom_diverges x H J => Some (pre_proof_bottom_diverges _ _ x H J)\n  | pre_proof_cut B C x H wB cBH nixH pu pt =>\n    match finish_pre_proof pu, finish_pre_proof pt with\n    | Some p1, Some p2 => Some (pre_proof_cut _ _ B C x H wB cBH nixH p1 p2)\n    | _, _ => None\n    end\n  | pre_proof_equal_in_base a b H p1 pl =>\n    let op := map_option_in_fun (free_vars a) (fun v i => finish_pre_proof (pl v i)) in\n    match finish_pre_proof p1, op with\n    | Some p1, Some g => Some (pre_proof_equal_in_base _ _ a b H p1 g)\n    | _, _ => None\n    end\n  | pre_proof_hypothesis x A G J => Some (pre_proof_hypothesis _ _ x A G J)\n  | pre_proof_cequiv_subst_concl C x a b H wa wb ca cb p1 p2 =>\n    match finish_pre_proof p1, finish_pre_proof p2 with\n    | Some p1, Some p2 => Some (pre_proof_cequiv_subst_concl _ _ C x a b H wa wb ca cb p1 p2)\n    | _, _ => None\n    end\n  | pre_proof_approx_member_eq a b H p1 =>\n    match finish_pre_proof p1 with\n    | Some p1 => Some (pre_proof_approx_member_eq _ _ a b H p1)\n    | _ => None\n    end\n  | pre_proof_cequiv_computation a b H r => Some (pre_proof_cequiv_computation _ _ a b H r)\n  | pre_proof_function_elimination A B C a f x z H J wa cova nizH nizJ dzf p1 p2 =>\n    match finish_pre_proof p1, finish_pre_proof p2 with\n    | Some p1, Some p2 => Some (pre_proof_function_elimination _ _ A B C a f x z H J wa cova nizH nizJ dzf p1 p2)\n    | _, _ => None\n    end\n  end.\n\nDefinition pre2conclusion {o} (c : @pre_conclusion o) (e : @NTerm o) :=\n  match c with\n  | pre_concl_ext T => concl_ext T e\n  | pre_concl_typ T => concl_typ T\n  end.\n\nDefinition pre2baresequent {o} (s : @pre_baresequent o) (e : @NTerm o) :=\n  mk_baresequent\n    (pre_hyps s)\n    (pre2conclusion (pre_concl s) e).\n\nDefinition ExtractProof {o} (seq : @pre_baresequent o) lib :=\n  {e : NTerm & proof lib (pre2baresequent seq e)}.\n\nDefinition mkExtractProof {o} {lib}\n           (seq : @pre_baresequent o)\n           (e : @NTerm o)\n           (p : proof lib (pre2baresequent seq e))\n  : ExtractProof seq lib :=\n  existT _ e p.\n\n(* converts a pre-proof without holes to a proof without holes by\n * generating the extract\n *)\nFixpoint pre_proof2iproof\n         {o} {seq : @pre_baresequent o} {lib}\n         (prf : pre_proof false lib seq)\n  : ExtractProof seq lib  :=\n  match prf with\n  | pre_proof_hole s e => match e with end\n  | pre_proof_isect_eq a1 a2 b1 b2 x1 x2 y i H niyH pa pb =>\n    match pre_proof2iproof pa, pre_proof2iproof pb with\n    | existT e1 p1, existT e2 p2 =>\n      mkExtractProof\n        (pre_rule_isect_equality_concl a1 a2 x1 x2 b1 b2 i H)\n        mk_axiom\n        (proof_isect_eq _ a1 a2 b1 b2 e1 e2 x1 x2 y i H niyH p1 p2)\n (* I need to generalize the rule a bit to allow any extract in subgoals *)\n    end\n  | pre_proof_approx_refl a H =>\n    mkExtractProof\n      (pre_rule_approx_refl_concl a H)\n      mk_axiom\n      (proof_approx_refl _ a H)\n  | pre_proof_cequiv_approx a b H p1 p2 =>\n    match pre_proof2iproof p1, pre_proof2iproof p2 with\n    | existT e1 p1, existT e2 p2 =>\n      mkExtractProof\n        (pre_rule_cequiv_approx_concl a b H)\n        mk_axiom\n        (proof_cequiv_approx _ a b e1 e2 H p1 p2)\n    end\n  | pre_proof_approx_eq a1 a2 b1 b2 i H p1 p2 =>\n    match pre_proof2iproof p1, pre_proof2iproof p2 with\n    | existT e1 p1, existT e2 p2 =>\n      mkExtractProof\n        (pre_rule_approx_eq_concl a1 a2 b1 b2 i H)\n        mk_axiom\n        (proof_approx_eq _ a1 a2 b1 b2 e1 e2 i H p1 p2)\n    end\n  | pre_proof_cequiv_eq a1 a2 b1 b2 i H p1 p2 =>\n    match pre_proof2iproof p1, pre_proof2iproof p2 with\n    | existT e1 p1, existT e2 p2 =>\n      mkExtractProof\n        (pre_rule_cequiv_eq_concl a1 a2 b1 b2 i H)\n        mk_axiom\n        (proof_cequiv_eq _ a1 a2 b1 b2 e1 e2 i H p1 p2)\n    end\n  | pre_proof_bottom_diverges x H J =>\n    mkExtractProof\n      (pre_rule_bottom_diverges_concl x H J)\n      mk_bottom\n      (proof_bottom_diverges _ x H J)\n  | pre_proof_cut B C x H wB cBH nixH pu pt =>\n    match pre_proof2iproof pu, pre_proof2iproof pt with\n    | existT u p1, existT t p2 =>\n      mkExtractProof\n        (pre_rule_cut_concl H C)\n        (subst t x u)\n        (proof_cut _ B C t u x H wB cBH nixH p1 p2)\n    end\n  | pre_proof_equal_in_base a b H p1 pl =>\n    let F := fun v (i : LIn v (free_vars a)) => pre_proof2iproof (pl v i) in\n    let E := fun v i => projT1 (F v i) in\n    let P := fun v i => projT2 (F v i) in\n    match pre_proof2iproof p1 with\n    | existT e p1 =>\n      mkExtractProof\n        (pre_rule_equal_in_base_concl a b H)\n        mk_axiom\n        (proof_equal_in_base _ a b e E H p1 P)\n    end\n  | pre_proof_hypothesis x A G J =>\n    mkExtractProof\n      (pre_rule_hypothesis_concl G J A x)\n      (mk_var x)\n      (proof_hypothesis _ x A G J)\n  | pre_proof_cequiv_subst_concl C x a b H wa wb ca cb p1 p2 =>\n    match pre_proof2iproof p1, pre_proof2iproof p2 with\n    | existT t p1, existT e p2 =>\n      mkExtractProof\n        (pre_rule_cequiv_subst_hyp1 H x C a)\n        t\n        (proof_cequiv_subst_concl _ C x a b t e H wa wb ca cb p1 p2)\n    end\n  | pre_proof_approx_member_eq a b H p1 =>\n    match pre_proof2iproof p1 with\n    | existT e1 p1 =>\n      mkExtractProof\n        (pre_rule_approx_member_eq_concl a b H)\n        mk_axiom\n        (proof_approx_member_eq _ a b e1 H p1)\n    end\n  | pre_proof_cequiv_computation a b H r =>\n    mkExtractProof\n      (pre_rule_cequiv_concl a b H)\n      mk_axiom\n      (proof_cequiv_computation _ a b H r)\n  | pre_proof_function_elimination A B C a f x z H J wa cova nizH nizJ dzf p1 p2 =>\n    match pre_proof2iproof p1, pre_proof2iproof p2 with\n    | existT ea p1, existT e p2 =>\n      mkExtractProof\n        (pre_rule_function_elimination_concl A B C f x H J)\n        (subst e z mk_axiom)\n        (proof_function_elimination _ A B C a e ea f x z H J wa cova nizH nizJ dzf p1 p2)\n    end\n  end.\n\nLemma test {o} :\n  @sequent_true2 o emlib (mk_baresequent [] (mk_conclax ((mk_member mk_axiom mk_unit)))).\nProof.\n  apply valid_proof;\n  [ exact (eq_refl, (eq_refl, eq_refl))\n  | exact (proof_approx_member_eq emlib (mk_axiom) (mk_axiom) (mk_axiom) (nil) (proof_approx_refl emlib (mk_axiom) (nil)))\n          (* This last bit was generated by JonPRL; I've got to generate the whole thing now *)\n  ].\nQed.\n\n\n(*\nInductive test : nat -> Type :=\n| Foo : test 1\n| Bar : test 0.\n\n(* works *)\nDefinition xxx {n : nat} (t : test n) : test n :=\n  match t with\n  | Foo => Foo\n  | Bar => Bar\n  end.\n\n(* works *)\nDefinition yyy {n : nat} (t : test n) : test n :=\n  match t with\n  | Foo => Foo\n  | x => x\n  end.\n\n(* works *)\nDefinition www {n : nat} (t : test n) : option (test n) :=\n  match t with\n  | Foo => Some Foo\n  | Bar => None\n  end.\n\n(* doesn't work *)\nDefinition zzz {n : nat} (t : test n) : test n :=\n  match t with\n  | Foo => Foo\n  | Bar => t\n  end.\n*)\n\nDefinition proof_update_fun {o} lib (s seq : @baresequent o) :=\n  proof lib s -> proof lib seq.\n\nDefinition proof_update {o} lib (seq : @baresequent o) :=\n  {s : @baresequent o & proof_update_fun lib s seq}.\n\nDefinition ProofUpdate {o} lib (seq : @baresequent o) :=\n  option (proof_update lib seq).\n\nDefinition retProofUpd\n           {o} {lib} {seq : @baresequent o}\n           (s : @baresequent o)\n           (f : proof lib s -> proof lib seq)\n  : ProofUpdate lib seq :=\n  Some (existT _ s f).\n\nDefinition idProofUpd\n           {o} {lib}\n           (seq : @baresequent o)\n  : ProofUpdate lib seq :=\n  retProofUpd seq (fun p => p).\n\nDefinition noProofUpd {o} {lib} {seq : @baresequent o}\n  : ProofUpdate lib seq :=\n  None.\n\nDefinition bindProofUpd\n           {o} {lib} {seq1 seq2 : @baresequent o}\n           (pu  : ProofUpdate lib seq1)\n           (puf : proof lib seq1 -> proof lib seq2)\n  : ProofUpdate lib seq2 :=\n  match pu with\n  | Some (existT s f) => retProofUpd s (fun p => puf (f p))\n  | None => None\n  end.\n\nDefinition address := list nat.\n\nFixpoint get_sequent_fun_at_address {o}\n         {lib}\n         {seq  : @baresequent o}\n         (prf  : proof lib seq)\n         (addr : address) : ProofUpdate lib seq :=\n  match prf with\n  | proof_isect_eq a1 a2 b1 b2 e1 e2 x1 x2 y i H niyH pa pb =>\n    match addr with\n    | [] => idProofUpd (rule_isect_equality_concl a1 a2 x1 x2 b1 b2 i H)\n    | 1 :: addr =>\n      bindProofUpd\n        (get_sequent_fun_at_address pa addr)\n        (fun x => proof_isect_eq _ a1 a2 b1 b2 e1 e2 x1 x2 y i H niyH x pb)\n    | 2 :: addr =>\n      bindProofUpd\n        (get_sequent_fun_at_address pb addr)\n        (fun x => proof_isect_eq _ a1 a2 b1 b2 e1 e2 x1 x2 y i H niyH pa x)\n    | _ => noProofUpd\n    end\n  | proof_approx_refl a H =>\n    match addr with\n    | [] => idProofUpd (rule_approx_refl_concl a H)\n    | _ => noProofUpd\n    end\n  | proof_cequiv_approx a b e1 e2 H p1 p2 =>\n    match addr with\n    | [] => idProofUpd (rule_cequiv_approx_concl a b H)\n    | 1 :: addr =>\n      bindProofUpd\n        (get_sequent_fun_at_address p1 addr)\n        (fun x => proof_cequiv_approx _ a b e1 e2 H x p2)\n    | 2 :: addr =>\n      bindProofUpd\n        (get_sequent_fun_at_address p2 addr)\n        (fun x => proof_cequiv_approx _ a b e1 e2 H p1 x)\n    | _ => noProofUpd\n    end\n  | proof_approx_eq a1 a2 b1 b2 e1 e2 i H p1 p2 =>\n    match addr with\n    | [] => idProofUpd (rule_approx_eq_concl a1 a2 b1 b2 i H)\n    | 1 :: addr =>\n      bindProofUpd\n        (get_sequent_fun_at_address p1 addr)\n        (fun x => proof_approx_eq _ a1 a2 b1 b2 e1 e2 i H x p2)\n    | 2 :: addr =>\n      bindProofUpd\n        (get_sequent_fun_at_address p2 addr)\n        (fun x => proof_approx_eq _ a1 a2 b1 b2 e1 e2 i H p1 x)\n    | _ => noProofUpd\n    end\n  | proof_cequiv_eq a1 a2 b1 b2 e1 e2 i H p1 p2 =>\n    match addr with\n    | [] => idProofUpd (rule_cequiv_eq_concl a1 a2 b1 b2 i H)\n    | 1 :: addr =>\n      bindProofUpd\n        (get_sequent_fun_at_address p1 addr)\n        (fun x => proof_cequiv_eq _ a1 a2 b1 b2 e1 e2 i H x p2)\n    | 2 :: addr =>\n      bindProofUpd\n        (get_sequent_fun_at_address p2 addr)\n        (fun x => proof_cequiv_eq _ a1 a2 b1 b2 e1 e2 i H p1 x)\n    | _ => noProofUpd\n    end\n  | proof_bottom_diverges x H J =>\n    match addr with\n    | [] => idProofUpd (rule_bottom_diverges_concl x H J)\n    | _ => noProofUpd\n    end\n  | proof_cut B C t u x H wB cBH nixH pu pt =>\n    match addr with\n    | [] => idProofUpd (rule_cut_concl H C t x u)\n    | 1 :: addr =>\n      bindProofUpd\n        (get_sequent_fun_at_address pu addr)\n        (fun z => proof_cut _ B C t u x H wB cBH nixH z pt)\n    | 2 :: addr =>\n      bindProofUpd\n        (get_sequent_fun_at_address pt addr)\n        (fun z => proof_cut _ B C t u x H wB cBH nixH pu z)\n    | _ => noProofUpd\n    end\n  | proof_equal_in_base a b e F H p1 pl =>\n    match addr with\n    | [] => idProofUpd (rule_equal_in_base_concl a b H)\n    | 1 :: addr =>\n      bindProofUpd\n        (get_sequent_fun_at_address p1 addr)\n        (fun z => proof_equal_in_base _ a b e F H z pl)\n    | _ => noProofUpd (* TODO *)\n    end\n  | proof_hypothesis x A G J =>\n    match addr with\n    | [] => idProofUpd (rule_hypothesis_concl G J A x)\n    | _ => noProofUpd\n    end\n  | proof_cequiv_subst_concl C x a b t e H wa wb ca cb p1 p2 =>\n    match addr with\n    | [] => idProofUpd (rule_cequiv_subst_hyp1 H x C a t)\n    | 1 :: addr =>\n      bindProofUpd\n        (get_sequent_fun_at_address p1 addr)\n        (fun z => proof_cequiv_subst_concl _ C x a b t e H wa wb ca cb z p2)\n    | 2 :: addr =>\n      bindProofUpd\n        (get_sequent_fun_at_address p2 addr)\n        (fun z => proof_cequiv_subst_concl _ C x a b t e H wa wb ca cb p1 z)\n    | _ => noProofUpd\n    end\n  | proof_approx_member_eq a b e H p1 =>\n    match addr with\n    | [] => idProofUpd (rule_approx_member_eq_concl a b H)\n    | 1 :: addr =>\n      bindProofUpd\n        (get_sequent_fun_at_address p1 addr)\n        (fun z => proof_approx_member_eq _ a b e H z)\n    | _ => noProofUpd\n    end\n  | proof_cequiv_computation a b H r =>\n    match addr with\n    | [] => idProofUpd (rule_cequiv_concl a b H)\n    | _ => noProofUpd\n    end\n  | proof_function_elimination A B C a e ea f x z H J wa cova nizH nizJ dzf p1 p2 =>\n    match addr with\n    | [] => idProofUpd (rule_function_elimination_concl A B C e f x z H J)\n    | 1 :: addr =>\n      bindProofUpd\n        (get_sequent_fun_at_address p1 addr)\n        (fun p => proof_function_elimination _ A B C a e ea f x z H J wa cova nizH nizJ dzf p p2)\n    | 2 :: addr =>\n      bindProofUpd\n        (get_sequent_fun_at_address p2 addr)\n        (fun p => proof_function_elimination _ A B C a e ea f x z H J wa cova nizH nizJ dzf p1 p)\n    | _ => noProofUpd\n    end\n  end.\n\nFixpoint get_sequent_at_address {o}\n           {seq  : @baresequent o}\n           {lib}\n           (prf  : proof lib seq)\n           (addr : address) : option baresequent :=\n  match get_sequent_fun_at_address prf addr with\n  | Some (existT s _) => Some s\n  | _ => None\n  end.\n\nDefinition list1 {T} : forall a : T, LIn a [a].\nProof.\n  tcsp.\nQed.\n\n\n(* Looking at how we can define a Nuprl process *)\n\nInductive command {o} :=\n(* add a definition at the head *)\n| COM_add_def :\n    forall (opabs   : opabs)\n           (vars    : list sovar_sig)\n           (rhs     : @SOTerm o)\n           (correct : correct_abs opabs vars rhs),\n      command\n(* tries to complete a proof if it has no holes *)\n| COM_finish_proof :\n    ProofName -> command\n(* focuses to a node in a proof *)\n| COM_focus_proof :\n    ProofName -> address -> command.\n\nDefinition proof_library {o} lib := list (@proof_library_entry o lib).\n\nRecord proof_update_seq {o} lib :=\n  MkProofUpdateSeq\n    {\n      PUS_name  : ProofName;\n      PUS_seq   : @baresequent o;\n      PUS_focus : baresequent;\n      PUS_upd   : proof_update_fun lib PUS_focus PUS_seq\n    }.\n\nDefinition ProofUpdateSeq {o} lib :=\n  option (@proof_update_seq o lib).\n\nRecord NuprlState {o} :=\n  MkNuprlState\n    {\n      NuprlState_def_library   : @library o;\n      NuprlState_proof_library : @proof_library o NuprlState_def_library;\n      NuprlState_focus         : @ProofUpdateSeq o NuprlState_def_library\n    }.\n\nFixpoint proof_consistent_with_new_definition\n         {o} {seq : @baresequent o} {lib}\n         (prf : proof lib seq)\n         (e   : library_entry)\n         (p   : !in_lib (opabs_of_lib_entry e) lib)\n  : proof (e :: lib) seq :=\n  match prf with\n  | proof_isect_eq a1 a2 b1 b2 e1 e2 x1 x2 y i H niyH pa pb =>\n    let p1 := proof_consistent_with_new_definition pa e p in\n    let p2 := proof_consistent_with_new_definition pb e p in\n    proof_isect_eq _ a1 a2 b1 b2 e1 e2 x1 x2 y i H niyH p1 p2\n  | proof_approx_refl a H => proof_approx_refl _ a H\n  | proof_cequiv_approx a b e1 e2 H p1 p2 =>\n    let p1 := proof_consistent_with_new_definition p1 e p in\n    let p2 := proof_consistent_with_new_definition p2 e p in\n    proof_cequiv_approx _ a b e1 e2 H p1 p2\n  | proof_approx_eq a1 a2 b1 b2 e1 e2 i H p1 p2 =>\n    let p1 := proof_consistent_with_new_definition p1 e p in\n    let p2 := proof_consistent_with_new_definition p2 e p in\n    proof_approx_eq _ a1 a2 b1 b2 e1 e2 i H p1 p2\n  | proof_cequiv_eq a1 a2 b1 b2 e1 e2 i H p1 p2 =>\n    let p1 := proof_consistent_with_new_definition p1 e p in\n    let p2 := proof_consistent_with_new_definition p2 e p in\n    proof_cequiv_eq _ a1 a2 b1 b2 e1 e2 i H p1 p2\n  | proof_bottom_diverges x H J => proof_bottom_diverges _ x H J\n  | proof_cut B C t u x H wB cBH nixH pu pt =>\n    let p1 := proof_consistent_with_new_definition pu e p in\n    let p2 := proof_consistent_with_new_definition pt e p in\n    proof_cut _ B C t u x H wB cBH nixH p1 p2\n  | proof_equal_in_base a b ee F H p1 pl =>\n    let p1 := proof_consistent_with_new_definition p1 e p in\n    let g := fun v (i : LIn v (free_vars a)) => proof_consistent_with_new_definition (pl v i) e p in\n    proof_equal_in_base _ a b ee F H p1 g\n  | proof_hypothesis x A G J => proof_hypothesis _ x A G J\n  | proof_cequiv_subst_concl C x a b t ee H wa wb ca cb p1 p2 =>\n    let p1 := proof_consistent_with_new_definition p1 e p in\n    let p2 := proof_consistent_with_new_definition p2 e p in\n    proof_cequiv_subst_concl _ C x a b t ee H wa wb ca cb p1 p2\n  | proof_approx_member_eq a b ee H p1 =>\n    let p1 := proof_consistent_with_new_definition p1 e p in\n    proof_approx_member_eq _ a b ee H p1\n  | proof_cequiv_computation a b H r =>\n    proof_cequiv_computation\n      _ a b H\n      (reduces_to_consistent_with_new_definition a b r e p)\n  | proof_function_elimination A B C a ee ea f x z H J wa cova nizH nizJ dzf p1 p2 =>\n    let p1 := proof_consistent_with_new_definition p1 e p in\n    let p2 := proof_consistent_with_new_definition p2 e p in\n    proof_function_elimination _ A B C a ee ea f x z H J wa cova nizH nizJ dzf p1 p2\n  end.\n\nDefinition NuprlState_add_def_lib {o}\n           (state   : @NuprlState o)\n           (opabs   : opabs)\n           (vars    : list sovar_sig)\n           (rhs     : SOTerm)\n           (correct : correct_abs opabs vars rhs) : NuprlState :=\n  let lib := NuprlState_def_library state in\n  match in_lib_dec opabs lib with\n  | inl _ => state\n  | inr p =>\n    @MkNuprlState\n      o\n      (lib_abs opabs vars rhs correct :: lib)\n      (NuprlState_proof_library state)\n      (NuprlState_focus state)\n  end.\n\nDefinition NuprlState_upd_proof_lib {o}\n           (state : @NuprlState o)\n           (lib   : @proof_library o) : NuprlState :=\n  @MkNuprlState\n    o\n    (NuprlState_def_library state)\n    lib\n    (NuprlState_focus state).\n\nDefinition NuprlState_upd_focus {o}\n           (state : @NuprlState o)\n           (upd   : @ProofUpdateSeq o) : NuprlState :=\n  @MkNuprlState\n    o\n    (NuprlState_def_library state)\n    (NuprlState_proof_library state)\n    upd.\n\nDefinition proof_library_entry_upd_proof {o} {lib}\n           (e : @proof_library_entry o lib)\n           (p : proof lib (proof_library_entry_seq lib e))\n  : proof_library_entry lib :=\n  MkProofLibEntry\n    _\n    _\n    (proof_library_entry_name _ e)\n    (proof_library_entry_seq _ e)\n    h\n    p.\n\nFixpoint finish_proof_in_library {o}\n           (lib : @proof_library o)\n           (name : ProofName) : proof_library :=\n  match lib with\n  | [] => []\n  | p :: ps =>\n    if String.string_dec (proof_library_entry_name p) name\n    then if proof_library_entry_hole p (* no need to finish the proof if it is already finished *)\n         then let p' := option_with_default\n                          (option_map (fun p' => proof_library_entry_upd_proof p p')\n                                      (finish_proof (proof_library_entry_proof p)))\n                          p\n              in p' :: ps\n         else p :: ps\n    else p :: finish_proof_in_library ps name\n  end.\n\nFixpoint focus_proof_in_library {o}\n           (lib : @proof_library o)\n           (name : ProofName)\n           (addr : address) : ProofUpdateSeq :=\n  match lib with\n  | [] => None\n  | p :: ps =>\n    if String.string_dec (proof_library_entry_name p) name\n    then match get_sequent_fun_at_address (proof_library_entry_proof p) addr with\n         | Some (existT s f) =>\n           Some (MkProofUpdateSeq\n                   o\n                   name\n                   (proof_library_entry_hole p)\n                   (proof_library_entry_seq p)\n                   s\n                   f)\n         | None => None\n         end\n    else focus_proof_in_library ps name addr\n  end.\n\nDefinition update {o}\n           (state : @NuprlState o)\n           (com   : command) : NuprlState :=\n  match com with\n  | COM_add_def opabs vars rhs correct =>\n    NuprlState_add_def_lib state opabs vars rhs correct\n  | COM_finish_proof name =>\n    let lib := NuprlState_proof_library state in\n    NuprlState_upd_proof_lib state (finish_proof_in_library lib name)\n  | COM_focus_proof name addr =>\n    let lib := NuprlState_proof_library state in\n    NuprlState_upd_focus state (focus_proof_in_library lib name addr)\n  end.\n\nCoInductive Loop {o} : Type :=\n| proc : (@command o -> Loop) -> Loop.\n\nCoFixpoint loop {o} (state : @NuprlState o) : Loop :=\n  proc (fun c => loop (update state c)).\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/rules/proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.273229247116806}}
{"text": "From mathcomp.ssreflect Require Import all_ssreflect seq.\nFrom mathcomp Require Import finmap.\n\nFrom Paco Require Import paco paco1 paco2.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nRequire Import MPST.Common.\nRequire Import MPST.Local.\nRequire Import MPST.Session.\n\nRequire Import MPST.Projection.IProject.\n\nFixpoint merge (A : eqType) (oL : A) (K : seq A) :=\n  match K with\n  | [::] => Some oL\n  | h::t => if h == oL then merge oL t\n            else None\n  end.\n\nNotation merge_all := (merge_all (@merge _)).\n\nFixpoint partial_proj (l : l_ty) (r : role) : option s_ty :=\n  match l with\n  | l_end => Some (s_end)\n  | l_var v => Some (s_var v)\n  | l_rec L =>\n    match partial_proj L r with\n    | Some s => Some (if s_binds 0 s then s_end else s_rec s)\n    | _ => None\n    end\n    | l_msg a p Ks =>\n      match (fix prj_all Ks r :=\n               match Ks with\n               | [::] => Some [::]\n               | K::Ks =>\n                 match partial_proj K.2.2 r, prj_all Ks r with\n                 | Some s, Some Ks => Some ((K.1, (K.2.1, s)) :: Ks)\n                 | _, _ => None\n                 end\n               end\n            ) Ks r with\n      | Some Ks => if p == r then Some (s_msg a Ks)\n                   else merge_all [seq K.2.2 | K <- Ks]\n      | None => None\n      end\n  end.\n\nFixpoint pprj_all (Ks : seq (lbl * (mty * l_ty))) (r : role)\n  : option (seq (lbl * (mty * s_ty))) :=\n  match Ks with\n  | [::] => Some [::]\n  | K::Ks => match partial_proj K.2.2 r, pprj_all Ks r with\n             | Some s, Some Ks => Some ((K.1, (K.2.1, s)) :: Ks)\n             | _, _ => None\n             end\n  end.\n\nLemma partialproj_all a p Ks r\n  : partial_proj (l_msg a p Ks) r =\n    match pprj_all Ks r with\n    | Some Ks' => if p == r then Some (s_msg a Ks')\n                  else merge_all [seq K.2.2 | K <- Ks']\n    | None => None\n    end.\nProof. by []. Qed.\n\nLemma merge_some (A : eqType)\n      (K : lbl * (mty * A))\n      (Ks : seq (lbl * (mty * A))) L\n  : merge K.2.2 [seq K0.2.2 | K0 <- Ks] == Some L -> K.2.2 = L.\nProof. by elim: Ks=>[/eqP-[]//|K' Ks Ih/=]; case:ifP. Qed.\n\nNotation lmerge_all := (IProject.merge_all simple_merge).\n\nLemma lmerge_some (K : lbl * (mty * l_ty)) (Ks : seq (lbl * (mty * l_ty))) L\n  : simple_merge K.2.2 [seq K0.2.2 | K0 <- Ks] == Some L -> K.2.2 = L.\nProof. by elim: Ks=>[/eqP-[]//|K' Ks Ih/=]; case:ifP. Qed.\n\nLemma merge_pprj L' Ks L p S\n  : simple_merge L' [seq K.2.2 | K <- Ks] == Some L ->\n    partial_proj L p == Some S ->\n    exists Ks', pprj_all Ks p = Some Ks' /\\\n                merge S [seq K.2.2 | K <- Ks'] = Some S.\nProof.\n  elim: Ks=>[_|K' Ks Ih]/=; first (by exists [::]; split); move: Ih.\n  case: ifP=>///eqP<- Ih M_L'; move: (lmerge_some M_L')=>-> /eqP-L_S.\n  rewrite L_S; move: L_S=>/eqP-L_S; move: (Ih M_L' L_S) => [Ks' [Ksp M_S]].\n  by exists ((K'.1, (K'.2.1, S)):: Ks'); rewrite Ksp /= eq_refl M_S.\nQed.\n\nLemma mergeall_pprj Ks L p S\n  : lmerge_all [seq K.2.2 | K <- Ks] == Some L ->\n    partial_proj L p == Some S ->\n    exists Ks', pprj_all Ks p = Some Ks' /\\\n                merge_all [seq K.2.2 | K <- Ks'] = Some S.\nProof.\n  case: Ks=>[//|K Ks]/=; move=> H; move: (lmerge_some H)=>KL.\n  move: KL H=>-> H /eqP-L_S; rewrite L_S; move: L_S=>/eqP-L_S.\n  move: (merge_pprj H L_S)=>[Ks' [Ksp M_S]].\n  by exists ((K.1, (K.2.1, S)) :: Ks'); rewrite Ksp/= M_S.\nQed.\n\nLemma fun_mergeall (A B : eqType) (f : A -> B) (Ks : seq (lbl * (mty * A))) X\n  : injective f ->\n    merge_all [seq f x.2.2 | x <- Ks] == Some (f X) ->\n    merge_all [seq x.2.2 | x <- Ks] == Some X.\nProof.\n  case: Ks=>[//|K Ks/=] I; elim: Ks=>[|K' Ks]//=.\n  - by move=>/eqP-[/I->].\n  - by move=> Ih; case: ifP=>///eqP-[/I->]; rewrite eq_refl=>/Ih.\nQed.\n\nLemma mergeall_fun (A B : eqType) (f : A -> B) (Ks : seq (lbl * (mty * A))) X:\n  merge_all [seq x.2.2 | x <- Ks] == Some X\n  -> merge_all [seq f x.2.2 | x <- Ks] == Some (f X).\nProof.\n  case: Ks=>[//|K Ks/=]; elim: Ks=>[|K' Ks]//=.\n  - by move=>/eqP-[->].\n  - by move=> Ih; case: ifP=>///eqP-[->]; rewrite eq_refl=>/Ih.\nQed.\n\n\nLemma pprjall_merge p Ks KsL L :\n  pprj_all Ks p == Some KsL ->\n  merge_all [seq K0.2.2 | K0 <- KsL] == Some L ->\n  forall K, member K Ks -> partial_proj K.2.2 p == Some L.\nProof.\n  case: KsL=>//= Kl KsL; case: Ks=>//= Kg Ks.\n  case Kg_p: partial_proj => [Lp | //]; case Ks_p: pprj_all => [Ksp | //]/=.\n  move=> Eq; move: Eq Ks_p => /eqP-[<-->] /eqP-Prj Mrg {Kl Ksp}.\n  move:Mrg (merge_some Mrg)=>/=Mrg Eq; move: Eq Mrg Kg_p=>->Mrg /eqP-Kg_p.\n  move=> K [<-//|]; move: Prj Mrg K {Lp Kg_p Kg}.\n  elim: Ks KsL=>//= Kg Ks Ih KsL.\n  case Kg_p: partial_proj => [Lp | //]; case Ks_p: pprj_all => [Ksp | //]/=.\n  move=> Eq; move: Eq Ih Ks_p Kg_p=>/eqP-[<-]//= Ih /eqP-Prj.\n  case: ifP=>[/eqP-> {Lp}|//] /eqP-Kg_p Mrg K [<-//|].\n  by move: Prj=>/Ih/(_ Mrg K).\nQed.\n\nLemma pprjall_some p Ks Ks' :\n  pprj_all Ks p == Some Ks' ->\n  forall K,\n    member K Ks ->\n    exists L, member (K.1, (K.2.1, L)) Ks' /\\ partial_proj K.2.2 p = Some L.\nProof.\n  elim: Ks=>//= Kl Ks Ih in Ks' *.\n  case Kl_p: partial_proj=>[s|//].\n  case Ks_p: pprj_all=>[Ks0|//]; move: Ks_p=>/eqP/Ih-{Ih} Ih.\n  move=>/eqP-[<-] K [E|/Ih-{Ih}[s' [M Kp]]]{Ks'}.\n  - by move: E Kl_p=>-> {Kl}; exists s; split=>//; left.\n  - by exists s'; split=>//; right.\nQed.\n", "meta": {"author": "emtst", "repo": "zooid-cmpst", "sha": "333dcf161ad2130c10c48684494830d12bae3889", "save_path": "github-repos/coq/emtst-zooid-cmpst", "path": "github-repos/coq/emtst-zooid-cmpst/zooid-cmpst-333dcf161ad2130c10c48684494830d12bae3889/theories/Projection/PartialProj.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2731529165032717}}
{"text": "(** * Valid port map relations. *)\n\n(** Defines the relations that check the validity of port maps\n    encountered in the component instantiation statements that are\n    part of the description of an H-VHDL design's behavior.  *)\n\nRequire Import common.CoqLib.\nRequire Import common.GlobalTypes.\nRequire Import common.NatMap.\n\nRequire Import hvhdl.Environment.\nRequire Import hvhdl.SemanticalDomains.\nRequire Import hvhdl.AbstractSyntax.\nRequire Import hvhdl.ExpressionEvaluation.\nRequire Import hvhdl.StaticExpressions.\nRequire Import hvhdl.HVhdlTypes.\n\nOpen Scope N_scope.\n\n(** ** Valid check for input port maps *)\n\n(** Defines the relation that lists the connection of ports in a given\n    input port map, i.e a port map where all formal parts of the\n    associations corresponds to input port identifiers.\n    \n    - [Δ] represents the embedding design in its elaborated version;\n      remember that a port map appears in a design instantiation\n      statement that is part of the behavior description for a\n      embedding design.\n\n    - [Δ__c] is the design instance in its elaborated version.\n\n    - [sst] is the signal store of the default design state being\n      constructed by the elaboration phase.\n\n    - [formals] lists the port identifiers that appears in the formal\n      part of a port map.\n    \n      If a couple [(id, None)] appears in [formals], then [id] appears\n      as a formal part of the port map.\n      \n      If a couple [(id, Some v)] appears in [formals], then [id(v)]\n      appears as formal part of the port map.  *)\n\nInductive ListIPM (Δ Δ__c : ElDesign) (sst : IdMap value) (formals : list (ident * option N)) :\n  list ipassoc -> list (ident * option N) -> Prop :=\n  \n(** An empty list of port associations does not change the [formals] list. *)\n| ListIPMNil : ListIPM Δ Δ__c sst formals [] formals\n\n(** Lists an non-empty list of port associations. *)\n| ListIPMCons :\n    forall ipa lofipas formals' formals'',\n      EIPAssoc Δ Δ__c sst formals ipa formals' ->\n      ListIPM Δ Δ__c sst formals' lofipas formals'' ->\n      ListIPM Δ Δ__c sst formals (ipa :: lofipas) formals''\n\n(** Defines the relation that checks the validity of a single input\n    port map association. *)\n              \nwith EIPAssoc (Δ Δ__c : ElDesign) (sst : IdMap value) (formals : list (ident * option N)) :\n  ipassoc -> list (ident * option N) -> Prop :=\n\n(** Checks an association with a simple port identifier (no index). *)\n| EIPAssocSimple :\n    forall id e v t,\n\n      (* Premises *)\n      VExpr Δ sst EmptyLEnv false e v ->\n      IsOfType v t ->\n\n      (* Side conditions *)\n      (~exists optn, List.In (id, optn) formals) ->  (* (id, optn) ∉ formals *)\n      MapsTo id (Input t) Δ__c -> (* [id ∈ Ins(Δ__c) and Δ__c(id) = t] *)\n\n      (* Conclusion *)\n      EIPAssoc Δ Δ__c sst formals (ipa_ (n_id id) e) (formals ++ [(id, None)])\n\n(** Checks an association with a partial port identifier (with index). *)\n| EIPAssocPartial :\n    forall id ei e v i t l u,\n\n      (* Premises *)\n      IGStaticExpr Δ ei ->\n      VExpr Δ sst EmptyLEnv false e v ->\n      VExpr Δ sst EmptyLEnv false ei (Vnat i) ->\n      IsOfType v t ->\n      IsOfType (Vnat i) (Tnat l u) ->\n      \n      (* Side conditions *)\n      ~List.In (id, None) formals -> (* (id, None) ∉ formals *)\n      ~List.In (id, Some i) formals -> (* (id, Some i) ∉ formals *)\n      MapsTo id (Input (Tarray t l u)) Δ__c ->  (* [id ∈ Ins(Δ__c) and Δ__c(id) = array(t,l,u)] *)\n\n      (* Conclusion *)\n      EIPAssoc Δ Δ__c sst formals (ipa_ (n_xid id ei) e) (formals ++ [(id, Some i)]).\n\n#[export] Hint Constructors ListIPM : hvhdl.\n#[export] Hint Constructors EIPAssoc : hvhdl.\n\n(** Defines the predicate that checks the [formals] list (built by the\n    [ListIPM] relation) against the component environment [Δ__c].\n\n    For all input port identifier declared in the elaborated design\n    [Δ__c], the identifier must appear as a left part of a couple in the\n    [formals] list. If the input port identifier is of the array type,\n    then all its subelements must appear as a left part of a couple in\n    the [formals] list. *)\n\nDefinition CheckFormals (Δ__c : ElDesign) (formals : list (ident * option N)) : Prop :=\n  forall (id : ident) (t : type),\n    MapsTo id (Input t) Δ__c ->\n    match t with\n    | Tbool | Tnat _ _ => List.In (id, None) formals\n    | Tarray t' l u => List.In (id, None) formals \\/ forall i, l <= i <= u -> List.In (id, Some i) formals\n    end.\n\n(** Defines the predicate stating that an input port map is valid. *)\n\nInductive ValidIPM (Δ Δ__c : ElDesign) (sst : IdMap value) (i : inputmap) : Prop :=\n| ValidIPM_ (formals : list (ident * option N)) :  \n  ListIPM Δ Δ__c sst [] i formals ->\n  CheckFormals Δ__c formals ->\n  ValidIPM Δ Δ__c sst i.\n\n(** ** Validity check for output port maps. *)\n\n(** Defines the relation that lists and checks the port identifiers\n    present in an output port map. *)\n\nInductive ListOPM (Δ Δ__c : ElDesign) (formals : list (ident * option N)) :\n  list opassoc -> list (ident * option N) -> Prop :=\n\n(** An empty list of port associations does not change the [formals]\n    list. *)\n| ListOPMNil : ListOPM Δ Δ__c formals [] formals\n\n(** Lists an non-empty list of port associations. *)\n| ListOPMCons :\n    forall opa lofopas formals' formals'',\n      EOPAssoc Δ Δ__c formals opa formals' ->\n      ListOPM Δ Δ__c formals' lofopas formals'' ->\n      ListOPM Δ Δ__c formals (opa :: lofopas) formals''\n\n(** Defines the relation that checks the validity of an output port\n    map association.  *)\n\nwith EOPAssoc (Δ Δ__c : ElDesign) (formals : list (ident * option N)) :\n  opassoc -> list (ident * option N) -> Prop :=\n\n(** Checks an output port map association of the form [idf ⇒ ida],\n    where [ida] refers to a declared signal or an output port\n    identifier of the embedding elaborated design.  *)\n| EOPAssocSimpleToSimple :\n    forall idf ida t,\n      \n      (* Side conditions *)\n      (forall optv, ~List.In (idf, optv) formals) -> \n\n      (* idf and ida have the same type. *)\n      MapsTo idf (Output t) Δ__c -> (* [idf ∈ Outs(Δ__c)] *)\n      (* [ida ∈ Sigs(Δ) ∪ Outs(Δ)] *)\n      MapsTo ida (Internal t) Δ \\/ MapsTo ida (Output t) Δ ->\n\n      (* Conclusion *)\n      EOPAssoc Δ Δ__c formals (opa_simpl idf (Some (n_id ida))) (formals ++ [(idf, None)])\n\n(** Checks an output port map association of the form [idf ⇒ ida(ei)],\n    where the actual part refers to a composite declared signal or\n    output port identifier .  *)\n               \n| EOPAssocSimpleToPartial :\n    forall idf ida ei i t l u,\n\n      (* Premises *)\n      IGStaticExpr Δ ei ->\n      VExpr Δ EmptySStore EmptyLEnv false ei (Vnat i) ->\n      IsOfType (Vnat i) (Tnat l u) ->\n      \n      (* Side conditions *)\n      (forall optv, ~List.In (idf, optv) formals) -> \n\n      (* idf and ida(ei) have the same type. *)\n      MapsTo idf (Output t) Δ__c ->\n      MapsTo ida (Internal (Tarray t l u)) Δ \\/ MapsTo ida (Output (Tarray t l u)) Δ ->\n\n      (* Conclusion *)\n      EOPAssoc Δ Δ__c formals (opa_simpl idf (Some (n_xid ida ei))) (formals ++ [(idf, None)])\n\n(** Checks an output port map association of the form [idf ⇒ open]. *)\n| EOPAssocSimpleToOpen :\n    forall idf t,\n      \n      (* Side conditions *)\n      (forall optv, ~List.In (idf, optv) formals) -> \n      MapsTo idf (Output t) Δ__c ->\n\n      (* Conclusion *)\n      EOPAssoc Δ Δ__c formals (opa_simpl idf None) (formals ++ [(idf,None)])\n\n(** Checks an output port map association of the form [idf(ei) ⇒ ida],\n    where [ida] refers to a declared signal or an output port\n    identifier. *)\n| EOPAssocPartialToSimple :\n    forall idf ei ida i t l u,\n\n      (* Premises *)\n      IGStaticExpr Δ ei ->\n      VExpr Δ EmptySStore EmptyLEnv false ei (Vnat i) ->\n      IsOfType (Vnat i) (Tnat l u) ->\n      \n      (* Side conditions *)\n      ~List.In (idf, None) formals ->\n      ~List.In (idf, Some i) formals ->\n      MapsTo idf (Output (Tarray t l u)) Δ__c ->\n      MapsTo ida (Internal t) Δ \\/ MapsTo ida (Output t) Δ ->\n\n      (* Conclusion *)\n      EOPAssoc Δ Δ__c formals (opa_idx idf ei ($ida)) (formals ++ [(idf, Some i)])\n               \n(** Checks an output port map association of the form [idf(ei) =>\n    ida(ei')], where [ida] refers to a declared signal or an output\n    port identifier. *)\n               \n| EOPAssocPartialToPartial :\n    forall idf ei ida ei' i i' t l u l' u',\n\n      (* Premises *)\n      IGStaticExpr Δ ei ->\n      IGStaticExpr Δ ei' ->\n      VExpr Δ EmptySStore EmptyLEnv false ei (Vnat i) ->\n      VExpr Δ EmptySStore EmptyLEnv false ei' (Vnat i') ->\n      IsOfType (Vnat i) (Tnat l u) ->\n      IsOfType (Vnat i') (Tnat l' u') ->\n      \n      (* Side conditions *)\n      ~List.In (idf, None) formals ->\n      ~List.In (idf, Some i) formals ->\n      MapsTo idf (Output (Tarray t l u)) Δ__c ->\n      MapsTo ida (Internal (Tarray t l' u')) Δ \\/ MapsTo ida (Output (Tarray t l' u')) Δ ->\n\n      (* Conclusion *)\n      EOPAssoc Δ Δ__c formals (opa_idx idf ei (ida$[[ei']])) (formals ++ [(idf, Some i)]).\n\n#[export] Hint Constructors ListOPM : hvhdl.\n#[export] Hint Constructors EOPAssoc : hvhdl.\n\n(** Defines the relation that checks the validity of an output port\n    map. *)\n\nInductive ValidOPM (Δ Δ__c : ElDesign) (o : list opassoc) : Prop :=\n| ValidOPM_ (formals : list (ident * option N)) :  \n  ListOPM Δ Δ__c [] o formals ->\n  ValidOPM Δ Δ__c o.\n    \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/ValidPortMap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2731529091866282}}
{"text": "Require Import Term_Defs Term Eqb_Evidence.\n\nRequire Import StructTactics.\n\nRequire Import PeanoNat Coq.Program.Tactics.\n\n\n(*\nInductive EvSubT: Evidence -> Evidence -> Prop :=\n| evsub_refl_t : forall e : Evidence, EvSubT e e\n| uuSubT: forall e e' i tid l tpl,\n    EvSubT e e' ->\n    EvSubT e (uu i l tpl tid e')\n| ggSubT: forall e e' p,\n    EvSubT e e' ->\n    EvSubT e (gg p e')\n| nnSubT: forall e e' i,\n    EvSubT e e' ->\n    EvSubT e (nn i e').\n*)\n\nInductive req_evidence: AnnoTerm -> Plc -> Plc -> Evidence -> Evidence -> Prop :=\n| is_req_evidence: forall annt t pp p q i e e',\n    events annt pp e (req i p q t e') ->\n    req_evidence annt pp q e e'.\n\nFixpoint check_req (t:AnnoTerm) (pp:Plc) (q:Plc) (e:Evidence) (e':Evidence): bool :=\n  match t with\n  | aatt r rp t' => (eqb_evidence e e' && (Nat.eqb q rp)) || (check_req t' rp q e e')\n  | alseq r t1 t2 => (check_req t1 pp q e e') || (check_req t2 pp q (aeval t1 pp e) e')\n  | abseq r s t1 t2 =>\n    (check_req t1 pp q (splitEv_T_l s e) e') || (check_req t2 pp q (splitEv_T_r s e) e')\n  | abpar r s t1 t2 =>\n    (check_req t1 pp q (splitEv_T_l s e) e') || (check_req t2 pp q (splitEv_T_r s e) e')\n  | _ => false\n  end.\n\nLemma req_implies_check: forall t pp q e e',\n    req_evidence t pp q e e' -> check_req t pp q e e' = true.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros.\n  -\n    destruct a.\n    +\n      cbn.\n      inversion H.\n      solve_by_inversion.\n    +\n      cbn.\n      inversion H.\n      solve_by_inversion.\n    +     \n      cbn.\n      inversion H.\n      solve_by_inversion.\n    +     \n      cbn.\n      inversion H.\n      solve_by_inversion.\n  -\n    \n    invc H.\n    invc H0; subst; cbn.\n    +\n      rewrite Bool.orb_true_iff.\n      left.\n      rewrite Bool.andb_true_iff.\n      split.\n      ++\n        rewrite eqb_eq_evidence.\n        tauto.\n      ++\n        apply Nat.eqb_refl.\n    +\n      rewrite Bool.orb_true_iff.\n      right.\n      eapply IHt.\n      econstructor.\n      eassumption.\n  -\n    cbn.\n    invc H.\n    invc H0.\n    +\n      rewrite Bool.orb_true_iff.\n      left.\n      eapply IHt1.\n      econstructor.\n      eassumption.\n    +\n      rewrite Bool.orb_true_iff.\n      right.\n      eapply IHt2.\n      econstructor.\n      eassumption.\n  -\n    cbn.\n    invc H.\n    invc H0.\n    +\n      rewrite Bool.orb_true_iff.\n      left.\n      eapply IHt1.\n      econstructor.\n      eassumption.\n    +\n      rewrite Bool.orb_true_iff.\n      right.\n      eapply IHt2.\n      econstructor.\n      eassumption.\n  -\n    cbn.\n    invc H.\n    invc H0.\n    +\n      rewrite Bool.orb_true_iff.\n      left.\n      eapply IHt1.\n      econstructor.\n      eassumption.\n    +\n      rewrite Bool.orb_true_iff.\n      right.\n      eapply IHt2.\n      econstructor.\n      eassumption.  \nDefined.\n\nLemma check_implies_req: forall t pp q e e',\n    check_req t pp q e e' = true -> req_evidence t pp q e e'.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros.\n  -\n    destruct a;\n      cbn; try solve_by_inversion.\n  -\n    cbn in *.\n      rewrite Bool.orb_true_iff in H.\n      destruct H.\n      +\n        rewrite Bool.andb_true_iff in H.\n        destruct_conjs.\n        econstructor.\n        rewrite eqb_eq_evidence in *.\n\n        apply EqNat.beq_nat_true in H0.\n        subst.\n        eauto.\n      +\n        \n        assert (req_evidence t n q e e') by eauto.\n        invc H0.\n        econstructor.\n        econstructor.\n        eassumption.\n  -\n    cbn in *. \n    rewrite Bool.orb_true_iff in H.\n    destruct_conjs.\n    destruct H.\n    +\n      assert (req_evidence t1 pp q e e') by eauto.\n      invc H0.\n      econstructor.\n      apply evtslseql.\n      eassumption.\n    +\n      assert (req_evidence t2 pp q (aeval t1 pp e) e') by eauto.\n      invc H0.\n      econstructor.\n      apply evtslseqr.\n      eassumption.\n  -\n    cbn in *.\n    rewrite Bool.orb_true_iff in H.\n    destruct_conjs.\n    destruct H.\n    +\n      assert (req_evidence t1 pp q (splitEv_T_l s e) e') by eauto.\n      invc H0.\n      econstructor.\n      apply evtsbseql.\n      eassumption.\n    +\n      assert (req_evidence t2 pp q (splitEv_T_r s e) e') by eauto.\n      invc H0.\n      econstructor.\n      apply evtsbseqr.\n      eassumption.\n  -\n    cbn in *.\n    rewrite Bool.orb_true_iff in H.\n    destruct_conjs.\n    destruct H.\n    +\n      assert (req_evidence t1 pp q (splitEv_T_l s e) e') by eauto.\n      invc H0.\n      econstructor.\n      apply evtsbparl.\n      eassumption.\n    +\n      assert (req_evidence t2 pp q (splitEv_T_r s e) e') by eauto.\n      invc H0.\n      econstructor.\n      apply evtsbparr.\n      eassumption.\nDefined.\n\n\n(*\n\n(* priv_pol p e --> allow place p to receive evidence with shape e *)\nDefinition priv_pol := Plc -> Evidence -> Prop.\n\nCheck priv_pol.\n\nDefinition satisfies_policy (t:AnnoTerm) (pp:Plc) (ee:Evidence)\n           (q:Plc) (es:Evidence) (pol:priv_pol) :=\n  req_evidence t pp ee q es -> (pol q es).\n\nDefinition test_term: Term := att 1 (asp CPY).\nDefinition test_term_anno := annotated test_term.\nCompute test_term_anno.\n\nDefinition test_init_evidence := uu 1 [] 42 442 mt.\nDefinition test_init_evidence2 := uu 2 [] 42 442 mt.\n\nDefinition test_pol (p:Plc) (e:Evidence) :=\n  match (p,e) with\n  | (1, (uu 1 [] 42 442 mt)) => False\n  | _ => True\n  end.\n    \n    \n\nExample test_term_satisfies_test_pol: forall pp ee q,\n    satisfies_policy test_term_anno pp ee q mt test_pol.\nProof.\n  intros.\n  cbn.\n  unfold test_init_evidence.\n  unfold satisfies_policy.\n  intros.\n  unfold test_pol.\n  cbv.\n  intros.\n  invc H.\n  inv H1.\n  auto.\n  invc H1.\n  auto.\n  solve_by_inversion.\nQed.\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/Priv_Pol.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2731169037284699}}
{"text": "Require Export paconotation pacotac pacodef pacotacuser.\nSet Implicit Arguments.\n\n(** ** Predicates of Arity 9\n*)\n\n(** 1 Mutual Coinduction *)\n\nSection Arg9_1.\n\nDefinition monotone9 T0 T1 T2 T3 T4 T5 T6 T7 T8 (gf: rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8 -> rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8) :=\n  forall x0 x1 x2 x3 x4 x5 x6 x7 x8 r r' (IN: gf r x0 x1 x2 x3 x4 x5 x6 x7 x8) (LE: r <9= r'), gf r' x0 x1 x2 x3 x4 x5 x6 x7 x8.\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 gf : rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8 -> rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8.\nImplicit Arguments gf [].\n\nTheorem paco9_acc: forall\n  l r (OBG: forall rr (INC: r <9= rr) (CIH: l <_paco_9= rr), l <_paco_9= paco9 gf rr),\n  l <9= paco9 gf r.\nProof.\n  intros; assert (SIM: paco9 gf (r \\9/ l) x0 x1 x2 x3 x4 x5 x6 x7 x8) by eauto.\n  clear PR; repeat (try left; do 10 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco9_mon: monotone9 (paco9 gf).\nProof. paco_cofix_auto; repeat (left; do 10 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco9_mult_strong: forall r,\n  paco9 gf (paco9 gf r \\9/ r) <9= paco9 gf r.\nProof. paco_cofix_auto; repeat (left; do 10 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco9_mult: forall r,\n  paco9 gf (paco9 gf r) <9= paco9 gf r.\nProof. intros; eapply paco9_mult_strong, paco9_mon; eauto. Qed.\n\nTheorem paco9_fold: forall r,\n  gf (paco9 gf r \\9/ r) <9= paco9 gf r.\nProof. intros; econstructor; [ |eauto]; eauto. Qed.\n\nTheorem paco9_unfold: forall (MON: monotone9 gf) r,\n  paco9 gf r <9= gf (paco9 gf r \\9/ r).\nProof. unfold monotone9; intros; destruct PR; eauto. Qed.\n\nEnd Arg9_1.\n\nHint Unfold monotone9.\nHint Resolve paco9_fold.\n\nImplicit Arguments paco9_acc            [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_mon            [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_mult_strong    [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_mult           [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_fold           [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_unfold         [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\n\nInstance paco9_inst  T0 T1 T2 T3 T4 T5 T6 T7 T8 (gf : rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8->_) r x0 x1 x2 x3 x4 x5 x6 x7 x8 : paco_class (paco9 gf r x0 x1 x2 x3 x4 x5 x6 x7 x8) :=\n{ pacoacc    := paco9_acc gf;\n  pacomult   := paco9_mult gf;\n  pacofold   := paco9_fold gf;\n  pacounfold := paco9_unfold gf }.\n\n(** 2 Mutual Coinduction *)\n\nSection Arg9_2.\n\nDefinition monotone9_2 T0 T1 T2 T3 T4 T5 T6 T7 T8 (gf: rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8 -> rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8 -> rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8) :=\n  forall x0 x1 x2 x3 x4 x5 x6 x7 x8 r_0 r_1 r'_0 r'_1 (IN: gf r_0 r_1 x0 x1 x2 x3 x4 x5 x6 x7 x8) (LE_0: r_0 <9= r'_0)(LE_1: r_1 <9= r'_1), gf r'_0 r'_1 x0 x1 x2 x3 x4 x5 x6 x7 x8.\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 gf_0 gf_1 : rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8 -> rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8 -> rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8.\nImplicit Arguments gf_0 [].\nImplicit Arguments gf_1 [].\n\nTheorem paco9_2_0_acc: forall\n  l r_0 r_1 (OBG: forall rr (INC: r_0 <9= rr) (CIH: l <_paco_9= rr), l <_paco_9= paco9_2_0 gf_0 gf_1 rr r_1),\n  l <9= paco9_2_0 gf_0 gf_1 r_0 r_1.\nProof.\n  intros; assert (SIM: paco9_2_0 gf_0 gf_1 (r_0 \\9/ l) r_1 x0 x1 x2 x3 x4 x5 x6 x7 x8) by eauto.\n  clear PR; repeat (try left; do 10 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco9_2_1_acc: forall\n  l r_0 r_1 (OBG: forall rr (INC: r_1 <9= rr) (CIH: l <_paco_9= rr), l <_paco_9= paco9_2_1 gf_0 gf_1 r_0 rr),\n  l <9= paco9_2_1 gf_0 gf_1 r_0 r_1.\nProof.\n  intros; assert (SIM: paco9_2_1 gf_0 gf_1 r_0 (r_1 \\9/ l) x0 x1 x2 x3 x4 x5 x6 x7 x8) by eauto.\n  clear PR; repeat (try left; do 10 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco9_2_0_mon: monotone9_2 (paco9_2_0 gf_0 gf_1).\nProof. paco_cofix_auto; repeat (left; do 10 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco9_2_1_mon: monotone9_2 (paco9_2_1 gf_0 gf_1).\nProof. paco_cofix_auto; repeat (left; do 10 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco9_2_0_mult_strong: forall r_0 r_1,\n  paco9_2_0 gf_0 gf_1 (paco9_2_0 gf_0 gf_1 r_0 r_1 \\9/ r_0) (paco9_2_1 gf_0 gf_1 r_0 r_1 \\9/ r_1) <9= paco9_2_0 gf_0 gf_1 r_0 r_1.\nProof. paco_cofix_auto; repeat (left; do 10 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco9_2_1_mult_strong: forall r_0 r_1,\n  paco9_2_1 gf_0 gf_1 (paco9_2_0 gf_0 gf_1 r_0 r_1 \\9/ r_0) (paco9_2_1 gf_0 gf_1 r_0 r_1 \\9/ r_1) <9= paco9_2_1 gf_0 gf_1 r_0 r_1.\nProof. paco_cofix_auto; repeat (left; do 10 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco9_2_0_mult: forall r_0 r_1,\n  paco9_2_0 gf_0 gf_1 (paco9_2_0 gf_0 gf_1 r_0 r_1) (paco9_2_1 gf_0 gf_1 r_0 r_1) <9= paco9_2_0 gf_0 gf_1 r_0 r_1.\nProof. intros; eapply paco9_2_0_mult_strong, paco9_2_0_mon; eauto. Qed.\n\nCorollary paco9_2_1_mult: forall r_0 r_1,\n  paco9_2_1 gf_0 gf_1 (paco9_2_0 gf_0 gf_1 r_0 r_1) (paco9_2_1 gf_0 gf_1 r_0 r_1) <9= paco9_2_1 gf_0 gf_1 r_0 r_1.\nProof. intros; eapply paco9_2_1_mult_strong, paco9_2_1_mon; eauto. Qed.\n\nTheorem paco9_2_0_fold: forall r_0 r_1,\n  gf_0 (paco9_2_0 gf_0 gf_1 r_0 r_1 \\9/ r_0) (paco9_2_1 gf_0 gf_1 r_0 r_1 \\9/ r_1) <9= paco9_2_0 gf_0 gf_1 r_0 r_1.\nProof. intros; econstructor; [ | |eauto]; eauto. Qed.\n\nTheorem paco9_2_1_fold: forall r_0 r_1,\n  gf_1 (paco9_2_0 gf_0 gf_1 r_0 r_1 \\9/ r_0) (paco9_2_1 gf_0 gf_1 r_0 r_1 \\9/ r_1) <9= paco9_2_1 gf_0 gf_1 r_0 r_1.\nProof. intros; econstructor; [ | |eauto]; eauto. Qed.\n\nTheorem paco9_2_0_unfold: forall (MON: monotone9_2 gf_0) (MON: monotone9_2 gf_1) r_0 r_1,\n  paco9_2_0 gf_0 gf_1 r_0 r_1 <9= gf_0 (paco9_2_0 gf_0 gf_1 r_0 r_1 \\9/ r_0) (paco9_2_1 gf_0 gf_1 r_0 r_1 \\9/ r_1).\nProof. unfold monotone9_2; intros; destruct PR; eauto. Qed.\n\nTheorem paco9_2_1_unfold: forall (MON: monotone9_2 gf_0) (MON: monotone9_2 gf_1) r_0 r_1,\n  paco9_2_1 gf_0 gf_1 r_0 r_1 <9= gf_1 (paco9_2_0 gf_0 gf_1 r_0 r_1 \\9/ r_0) (paco9_2_1 gf_0 gf_1 r_0 r_1 \\9/ r_1).\nProof. unfold monotone9_2; intros; destruct PR; eauto. Qed.\n\nEnd Arg9_2.\n\nHint Unfold monotone9_2.\nHint Resolve paco9_2_0_fold.\nHint Resolve paco9_2_1_fold.\n\nImplicit Arguments paco9_2_0_acc            [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_2_1_acc            [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_2_0_mon            [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_2_1_mon            [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_2_0_mult_strong    [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_2_1_mult_strong    [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_2_0_mult           [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_2_1_mult           [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_2_0_fold           [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_2_1_fold           [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_2_0_unfold         [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_2_1_unfold         [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\n\nInstance paco9_2_0_inst  T0 T1 T2 T3 T4 T5 T6 T7 T8 (gf_0 gf_1 : rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8->_) r_0 r_1 x0 x1 x2 x3 x4 x5 x6 x7 x8 : paco_class (paco9_2_0 gf_0 gf_1 r_0 r_1 x0 x1 x2 x3 x4 x5 x6 x7 x8) :=\n{ pacoacc    := paco9_2_0_acc gf_0 gf_1;\n  pacomult   := paco9_2_0_mult gf_0 gf_1;\n  pacofold   := paco9_2_0_fold gf_0 gf_1;\n  pacounfold := paco9_2_0_unfold gf_0 gf_1 }.\n\nInstance paco9_2_1_inst  T0 T1 T2 T3 T4 T5 T6 T7 T8 (gf_0 gf_1 : rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8->_) r_0 r_1 x0 x1 x2 x3 x4 x5 x6 x7 x8 : paco_class (paco9_2_1 gf_0 gf_1 r_0 r_1 x0 x1 x2 x3 x4 x5 x6 x7 x8) :=\n{ pacoacc    := paco9_2_1_acc gf_0 gf_1;\n  pacomult   := paco9_2_1_mult gf_0 gf_1;\n  pacofold   := paco9_2_1_fold gf_0 gf_1;\n  pacounfold := paco9_2_1_unfold gf_0 gf_1 }.\n\n(** 3 Mutual Coinduction *)\n\nSection Arg9_3.\n\nDefinition monotone9_3 T0 T1 T2 T3 T4 T5 T6 T7 T8 (gf: rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8 -> rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8 -> rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8 -> rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8) :=\n  forall x0 x1 x2 x3 x4 x5 x6 x7 x8 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 x7 x8) (LE_0: r_0 <9= r'_0)(LE_1: r_1 <9= r'_1)(LE_2: r_2 <9= r'_2), gf r'_0 r'_1 r'_2 x0 x1 x2 x3 x4 x5 x6 x7 x8.\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 gf_0 gf_1 gf_2 : rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8 -> rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8 -> rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8 -> rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8.\nImplicit Arguments gf_0 [].\nImplicit Arguments gf_1 [].\nImplicit Arguments gf_2 [].\n\nTheorem paco9_3_0_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_0 <9= rr) (CIH: l <_paco_9= rr), l <_paco_9= paco9_3_0 gf_0 gf_1 gf_2 rr r_1 r_2),\n  l <9= paco9_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco9_3_0 gf_0 gf_1 gf_2 (r_0 \\9/ l) r_1 r_2 x0 x1 x2 x3 x4 x5 x6 x7 x8) by eauto.\n  clear PR; repeat (try left; do 10 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco9_3_1_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_1 <9= rr) (CIH: l <_paco_9= rr), l <_paco_9= paco9_3_1 gf_0 gf_1 gf_2 r_0 rr r_2),\n  l <9= paco9_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco9_3_1 gf_0 gf_1 gf_2 r_0 (r_1 \\9/ l) r_2 x0 x1 x2 x3 x4 x5 x6 x7 x8) by eauto.\n  clear PR; repeat (try left; do 10 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco9_3_2_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_2 <9= rr) (CIH: l <_paco_9= rr), l <_paco_9= paco9_3_2 gf_0 gf_1 gf_2 r_0 r_1 rr),\n  l <9= paco9_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco9_3_2 gf_0 gf_1 gf_2 r_0 r_1 (r_2 \\9/ l) x0 x1 x2 x3 x4 x5 x6 x7 x8) by eauto.\n  clear PR; repeat (try left; do 10 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco9_3_0_mon: monotone9_3 (paco9_3_0 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 10 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco9_3_1_mon: monotone9_3 (paco9_3_1 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 10 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco9_3_2_mon: monotone9_3 (paco9_3_2 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 10 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco9_3_0_mult_strong: forall r_0 r_1 r_2,\n  paco9_3_0 gf_0 gf_1 gf_2 (paco9_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_0) (paco9_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_1) (paco9_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_2) <9= paco9_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 10 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco9_3_1_mult_strong: forall r_0 r_1 r_2,\n  paco9_3_1 gf_0 gf_1 gf_2 (paco9_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_0) (paco9_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_1) (paco9_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_2) <9= paco9_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 10 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco9_3_2_mult_strong: forall r_0 r_1 r_2,\n  paco9_3_2 gf_0 gf_1 gf_2 (paco9_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_0) (paco9_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_1) (paco9_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_2) <9= paco9_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 10 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco9_3_0_mult: forall r_0 r_1 r_2,\n  paco9_3_0 gf_0 gf_1 gf_2 (paco9_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco9_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco9_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <9= paco9_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco9_3_0_mult_strong, paco9_3_0_mon; eauto. Qed.\n\nCorollary paco9_3_1_mult: forall r_0 r_1 r_2,\n  paco9_3_1 gf_0 gf_1 gf_2 (paco9_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco9_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco9_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <9= paco9_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco9_3_1_mult_strong, paco9_3_1_mon; eauto. Qed.\n\nCorollary paco9_3_2_mult: forall r_0 r_1 r_2,\n  paco9_3_2 gf_0 gf_1 gf_2 (paco9_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco9_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco9_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <9= paco9_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco9_3_2_mult_strong, paco9_3_2_mon; eauto. Qed.\n\nTheorem paco9_3_0_fold: forall r_0 r_1 r_2,\n  gf_0 (paco9_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_0) (paco9_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_1) (paco9_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_2) <9= paco9_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco9_3_1_fold: forall r_0 r_1 r_2,\n  gf_1 (paco9_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_0) (paco9_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_1) (paco9_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_2) <9= paco9_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco9_3_2_fold: forall r_0 r_1 r_2,\n  gf_2 (paco9_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_0) (paco9_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_1) (paco9_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_2) <9= paco9_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco9_3_0_unfold: forall (MON: monotone9_3 gf_0) (MON: monotone9_3 gf_1) (MON: monotone9_3 gf_2) r_0 r_1 r_2,\n  paco9_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2 <9= gf_0 (paco9_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_0) (paco9_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_1) (paco9_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_2).\nProof. unfold monotone9_3; intros; destruct PR; eauto. Qed.\n\nTheorem paco9_3_1_unfold: forall (MON: monotone9_3 gf_0) (MON: monotone9_3 gf_1) (MON: monotone9_3 gf_2) r_0 r_1 r_2,\n  paco9_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2 <9= gf_1 (paco9_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_0) (paco9_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_1) (paco9_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_2).\nProof. unfold monotone9_3; intros; destruct PR; eauto. Qed.\n\nTheorem paco9_3_2_unfold: forall (MON: monotone9_3 gf_0) (MON: monotone9_3 gf_1) (MON: monotone9_3 gf_2) r_0 r_1 r_2,\n  paco9_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2 <9= gf_2 (paco9_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_0) (paco9_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_1) (paco9_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2 \\9/ r_2).\nProof. unfold monotone9_3; intros; destruct PR; eauto. Qed.\n\nEnd Arg9_3.\n\nHint Unfold monotone9_3.\nHint Resolve paco9_3_0_fold.\nHint Resolve paco9_3_1_fold.\nHint Resolve paco9_3_2_fold.\n\nImplicit Arguments paco9_3_0_acc            [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_3_1_acc            [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_3_2_acc            [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_3_0_mon            [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_3_1_mon            [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_3_2_mon            [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_3_0_mult_strong    [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_3_1_mult_strong    [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_3_2_mult_strong    [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_3_0_mult           [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_3_1_mult           [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_3_2_mult           [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_3_0_fold           [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_3_1_fold           [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_3_2_fold           [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_3_0_unfold         [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_3_1_unfold         [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\nImplicit Arguments paco9_3_2_unfold         [ T0 T1 T2 T3 T4 T5 T6 T7 T8 ].\n\nInstance paco9_3_0_inst  T0 T1 T2 T3 T4 T5 T6 T7 T8 (gf_0 gf_1 gf_2 : rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8->_) r_0 r_1 r_2 x0 x1 x2 x3 x4 x5 x6 x7 x8 : paco_class (paco9_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2 x0 x1 x2 x3 x4 x5 x6 x7 x8) :=\n{ pacoacc    := paco9_3_0_acc gf_0 gf_1 gf_2;\n  pacomult   := paco9_3_0_mult gf_0 gf_1 gf_2;\n  pacofold   := paco9_3_0_fold gf_0 gf_1 gf_2;\n  pacounfold := paco9_3_0_unfold gf_0 gf_1 gf_2 }.\n\nInstance paco9_3_1_inst  T0 T1 T2 T3 T4 T5 T6 T7 T8 (gf_0 gf_1 gf_2 : rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8->_) r_0 r_1 r_2 x0 x1 x2 x3 x4 x5 x6 x7 x8 : paco_class (paco9_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2 x0 x1 x2 x3 x4 x5 x6 x7 x8) :=\n{ pacoacc    := paco9_3_1_acc gf_0 gf_1 gf_2;\n  pacomult   := paco9_3_1_mult gf_0 gf_1 gf_2;\n  pacofold   := paco9_3_1_fold gf_0 gf_1 gf_2;\n  pacounfold := paco9_3_1_unfold gf_0 gf_1 gf_2 }.\n\nInstance paco9_3_2_inst  T0 T1 T2 T3 T4 T5 T6 T7 T8 (gf_0 gf_1 gf_2 : rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8->_) r_0 r_1 r_2 x0 x1 x2 x3 x4 x5 x6 x7 x8 : paco_class (paco9_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2 x0 x1 x2 x3 x4 x5 x6 x7 x8) :=\n{ pacoacc    := paco9_3_2_acc gf_0 gf_1 gf_2;\n  pacomult   := paco9_3_2_mult gf_0 gf_1 gf_2;\n  pacofold   := paco9_3_2_fold gf_0 gf_1 gf_2;\n  pacounfold := paco9_3_2_unfold gf_0 gf_1 gf_2 }.\n\n", "meta": {"author": "siegebell", "repo": "hdcoind", "sha": "572e66a00767ee1e2c0677befe9d2db2271df0a7", "save_path": "github-repos/coq/siegebell-hdcoind", "path": "github-repos/coq/siegebell-hdcoind/hdcoind-572e66a00767ee1e2c0677befe9d2db2271df0a7/paco/src/paco9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.27311690372846986}}
{"text": "Require Import Ynot.\nRequire Import List Ascii.\n\nSet Implicit Arguments.\n\nOpen Local Scope stsepi_scope.\nOpen Local Scope hprop_scope.\n\n(* Mimic open types *)\nAxiom axiom_Action : Set.\nDefinition Action := axiom_Action.\nDefinition Action_model := unit.\n                                \nDefinition Trace := list Action.\nDefinition TraceModel := list Action_model.\n\nAxiom axiom_traced : Trace -> hprop.\nDefinition traced := axiom_traced.\nDefinition traced_model (t: TraceModel) := [True]. \n\nDefinition forever : forall (I : Trace -> hprop)\n  (B : forall t', STsep (t' ~~ traced t' * I t')\n        (fun t'':[Trace] => t' ~~ t'' ~~ traced (t'' ++ t') * I (t'' ++ t')))\n  (t' : [Trace]), \n  STsep (t' ~~ traced t' * I t')\n        (fun _:Empty_set => t' ~~ Exists t'' :@ Trace, traced (t'' ++ t') * I (t'' ++ t') * [False]).\n  refine (fun I B t' =>\n    Fix (fun t => t ~~ traced t * I t)\n        (fun t (_:Empty_set) => t ~~ Exists t'' :@ Trace, traced (t'' ++ t) * I (t'' ++ t) * [False])\n        (fun self t =>\n          tr' <- B t;\n          {{self (inhabit_unpack' t (fun t => inhabit_unpack tr' (fun tr' => tr' ++ t))) }}\n        ) t'); \n  sep fail auto.\nQed.\n\nDefinition foreverInv : forall (CTX : Type) (ctx : CTX) (I : CTX -> Trace -> hprop)\n  (B : forall ctx t', \n         STsep (t' ~~ traced t' * I ctx t')\n               (fun ctx':CTX * [Trace] => t' ~~ t'' :~~ snd ctx' in traced (t'' ++ t') * I (fst ctx') (t'' ++ t')))\n  (t' : [Trace]), \n  STsep (t' ~~ traced t' * I ctx t')\n        (fun _:Empty_set => t' ~~ Exists t'' :@ Trace, Exists ctx' :@ CTX, traced (t'' ++ t') * I ctx' (t'' ++ t') * [False]).\n  intros. refine (\n    Fix2 (fun ctx t => t ~~ traced t * I ctx t)\n         (fun ctx t (_:Empty_set) => t ~~ Exists t'' :@ Trace, Exists ctx' :@ CTX, traced (t'' ++ t) * I ctx' (t'' ++ t) * [False])\n         (fun self ctx t =>\n           ctx' <- B ctx t;\n           {{self (fst ctx') (inhabit_unpack' t (fun t => inhabit_unpack (snd ctx') (fun tr' => tr' ++ t))) }}\n         ) ctx t').\n    solve [ sep fail auto ].\n    solve [ sep fail auto ].\n    sep fail auto. inhabiter. rewrite H in H1. simpl in H1. sep fail auto.\n    solve [ sep fail auto ].\nQed.\n\n(***********************************************)\n\n(* A type of invariant preserving computations\n   that make progress.  We repeat this forever\n   to get a server. *)\n\nDefinition server_t (I: Trace -> Prop) (pf_startable: I nil) := forall (tr: [Trace]),\n STsep                (tr ~~ traced       tr  * [I       tr])\n(fun r:[Trace] => r ~~ tr ~~ traced (r ++ tr) * [I (r ++ tr)] * [r <> nil]).\n\n\nRequire Export RSep.\n", "meta": {"author": "Ptival", "repo": "ynot", "sha": "cd6f28816c41bbef7464b644edeba099d397a01e", "save_path": "github-repos/coq/Ptival-ynot", "path": "github-repos/coq/Ptival-ynot/ynot-cd6f28816c41bbef7464b644edeba099d397a01e/examples/IO/IO.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2731168978783682}}
{"text": "Require Import Coq.omega.Omega.\nRequire Import Coq.Arith.Arith Bedrock.Platform.AutoSep Bedrock.Platform.Bags Bedrock.Platform.Malloc Bedrock.Platform.Queue Bedrock.Platform.Misc.\nImport W_W_Bag.\n\nSet Implicit Arguments.\n\n\nRecord tq_args (world : Type) := {\n  World : world;\n  Pointer : W;\n  Settings : settings;\n  Mem : smem\n}.\n\nModule Type S.\n  Parameter world : Type.\n\n  Parameter 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  Parameter globalInv : world -> W -> hpropB (tq_args world :: nil).\nEnd S.\n\nDefinition localsInvariantExit (pre : vals -> W -> qspec) (rpStashed : bool) (adjustSp : W -> W)\n  (ns : list string) (_ : nat) : assert :=\n  st ~> let sp := adjustSp st#Sp in\n    [| sp <> 0 |]\n    /\\ Ex vs, let res := wordToNat (sel vs \"ss\") - S (length ns) in\n      [| freeable sp (wordToNat (sel vs \"ss\")) |]\n      /\\ qspecOut (pre (sel vs) st#Rv) (fun pre =>\n        ![ locals (\"rp\" :: ns) vs res sp * pre ] st).\n\nNotation \"'PREexit' [ vs ] pre\" := (localsInvariantExit (fun vs _ => pre%qspec%Sep))\n  (at level 89).\n\nNotation \"'PREexit' [ vs , rv ] pre\" := (localsInvariantExit (fun vs rv => pre%qspec%Sep))\n  (at level 89).\n\nModule Make(M : S).\nImport M.\n\n(* What does it mean for a program counter to be valid for a suspended thread? *)\n\nDefinition susp (w : world) (sc pc sp : W) : HProp := fun s m =>\n  (Ex pc_tq : W, [| s.(Labels) (\"threadq\"!\"ADT\")%SP = Some pc_tq |]\n    /\\ ExX (* tq *) : tq_args world, Cptr pc_tq (_ ~> PropX.Forall #0)\n    /\\ ExX (* pre *) : settings * state, Cptr pc #0\n    /\\ ExX (* inv *) : settings * smem, #0 (s, m)\n    /\\ Al st : state, Al w' : world,\n    [| evolve w w' |]\n    /\\ ![ #0 * (fun x y => Lift (Lift (Var0 {| World := w';\n                                               Pointer := sc;\n                                               Settings := x;\n                                               Mem := y |})))\n      * (fun x y => Lift (Lift (globalInv w' sc x y)))\n      * ^[mallocHeap 0] ] (s, st)\n    /\\ [| Regs st Sp = sp |]\n    ---> #1 (s, st))%PropX.\n\nLemma susp_intro : forall specs w sc pc sp P stn st,\n  (exists pc_tq, stn.(Labels) (\"threadq\"!\"ADT\")%SP = Some pc_tq\n    /\\ exists tq, specs pc_tq = Some (fun _ => PropX.Forall tq)\n      /\\ exists pre, specs pc = Some (fun x => pre x)\n        /\\ exists inv, interp specs (![ inv * P ] (stn, st))\n          /\\ forall st' w', interp specs ([| evolve w w' |]\n            /\\ ![ inv\n              * (fun x y => tq {| World := w';\n                                  Pointer := sc;\n                                  Settings := x;\n                                  Mem := y |})\n              * substH (globalInv w' sc) tq * mallocHeap 0 ] (stn, st')\n            /\\ [| Regs st' Sp = sp |]\n            ---> pre (stn, st'))%PropX)\n  -> interp specs (![ susp w sc pc sp * P ] (stn, st)).\n  cptr.\nQed.\n\nLemma susp_elim : forall specs w sc pc sp P stn st,\n  interp specs (![ susp w sc pc sp * P ] (stn, st))\n  -> (exists pc_tq, stn.(Labels) (\"threadq\"!\"ADT\")%SP = Some pc_tq\n    /\\ exists tq, specs pc_tq = Some (fun _ => PropX.Forall tq)\n      /\\ exists pre, specs pc = Some (fun x => pre x)\n        /\\ exists inv, interp specs (![ inv * P ] (stn, st))\n          /\\ forall st' w', interp specs ([| evolve w w' |]\n            /\\ ![ inv * (fun x y => tq {| World := w';\n                                          Pointer := sc;\n                                          Settings := x;\n                                          Mem := y |}) * substH (globalInv w' sc) tq * mallocHeap 0 ] (stn, st')\n            /\\ [| Regs st' Sp = sp |]\n            ---> pre (stn, st'))%PropX).\n  cptr.\n  propxFo; eauto.\n  descend; eauto.\n  rewrite <- sepFormula_eq; descend.\n  step auto_ext.\n  eauto.\n  make_Himp.\n  apply Himp_refl.\nQed.\n\n\nInductive mergeSusp : Prop := MS.\nInductive splitSusp : Prop := SS.\n\nHint Constructors mergeSusp splitSusp.\n\nModule Type TQ.\n  Parameter susps : world -> bag -> W -> HProp.\n  Parameter tq : world -> W -> HProp.\n\n  Axiom tq_extensional : forall w sc, HProp_extensional (tq w sc).\n\n  Axiom susps_empty_bwd : forall w sc, Emp ===> susps w empty sc.\n  Axiom susps_add_bwd : forall w sc b pc sp, pc = pc -> mergeSusp -> susp w sc pc sp * susps w b sc ===> susps w (b %+ (pc, sp)) sc.\n  Axiom susps_del_fwd : forall w sc b pc sp, (pc, sp) %in b -> susps w b sc ===> susp w sc pc sp * susps w (b %- (pc, sp)) sc.\n\n  (* Below, the extra [locals] is a temporary stack for the threadq to use during sensitive\n   * stack manipulations when the threads' own stacks may not be safe to touch. *)\n\n  Axiom tq_fwd : forall w sc, tq w sc ===> Ex b, Ex p, Ex sp, Ex vs, (sc ==*> p, sp) * (sc ^+ $8) =?> 2\n    * locals (\"rp\" :: \"sc\" :: \"ss\" :: \"curPc\" :: \"curSp\" :: \"newPc\" :: \"newSp\" :: nil) vs 14 sp\n    * queue b p * susps w b sc.\n\n  Axiom tq_bwd : forall w sc, (Ex b, Ex p, Ex sp, Ex vs, (sc ==*> p, sp) * (sc ^+ $8) =?> 2\n    * locals (\"rp\" :: \"sc\" :: \"ss\" :: \"curPc\" :: \"curSp\" :: \"newPc\" :: \"newSp\" :: nil) vs 14 sp\n    * queue b p * susps w b sc) ===> tq w sc.\n\n\n  Axiom tq_weaken : forall w w' sc,\n    evolve w w'\n    -> tq w sc ===>* tq w' sc.\nEnd TQ.\n\nModule Tq : TQ.\n  Open Scope Sep_scope.\n\n  Definition susps (w : world) (b : bag) (sc : W) : HProp :=\n    starB (fun p => susp w sc (fst p) (snd p)) b.\n\n  Theorem susps_empty_bwd : forall w sc, Emp ===> susps w empty sc.\n    intros; apply starB_empty_bwd.\n  Qed.\n\n  Theorem susps_add_bwd : forall w sc b pc sp, pc = pc -> mergeSusp -> susp w sc pc sp * susps w b sc ===> susps w (b %+ (pc, sp)) sc.\n    intros; eapply Himp_trans; [ | apply starB_add_bwd ].\n    unfold susps; simpl.\n    apply Himp_star_comm.\n  Qed.\n\n  Theorem susps_del_fwd : forall w sc b pc sp, (pc, sp) %in b -> susps w b sc ===> susp w sc pc sp * susps w (b %- (pc, sp)) sc.\n    intros; eapply Himp_trans; [ apply starB_del_fwd; eauto | apply Himp_refl ].\n  Qed.\n\n  Definition tq (w : world) (sc : W) : HProp :=\n    Ex b, Ex p, Ex sp, Ex vs, (sc ==*> p, sp) * (sc ^+ $8) =?> 2\n      * locals (\"rp\" :: \"sc\" :: \"ss\" :: \"curPc\" :: \"curSp\" :: \"newPc\" :: \"newSp\" :: nil) vs 14 sp\n      * queue b p * susps w b sc.\n\n  Theorem tq_extensional : forall w sc, HProp_extensional (tq w sc).\n    reflexivity.\n  Qed.\n\n  Theorem tq_fwd : forall w sc, tq w sc ===> Ex b, Ex p, Ex sp, Ex vs, (sc ==*> p, sp) * (sc ^+ $8) =?> 2\n    * locals (\"rp\" :: \"sc\" :: \"ss\" :: \"curPc\" :: \"curSp\" :: \"newPc\" :: \"newSp\" :: nil) vs 14 sp\n    * queue b p * susps w b sc.\n    unfold tq; sepLemma.\n  Qed.\n\n  Theorem tq_bwd : forall w sc, (Ex b, Ex p, Ex sp, Ex vs, (sc ==*> p, sp) * (sc ^+ $8) =?> 2\n    * locals (\"rp\" :: \"sc\" :: \"ss\" :: \"curPc\" :: \"curSp\" :: \"newPc\" :: \"newSp\" :: nil) vs 14 sp\n    * queue b p * susps w b sc) ===> tq w sc.\n    unfold tq; sepLemma.\n  Qed.\n\n  Theorem into_ex : forall A (P P' : A -> _),\n    (forall x, P x ===>* P' x)\n    -> exB P ===>* exB P'.\n    unfold HimpWeak; propxFo.\n    apply H in H0; eauto.\n  Qed.\n\n  Theorem into_star : forall P P' Q Q',\n    P ===>* P'\n    -> Q ===>* Q'\n    -> P * Q ===>* P' * Q'.\n    unfold HimpWeak; propxFo.\n    apply H in H1; apply H0 in H4; eauto.\n  Qed.\n\n  Theorem weak_refl : forall P,\n    P ===>* P.\n    unfold HimpWeak; auto.\n  Qed.\n\n  Theorem tq_weaken : forall w w' sc,\n    evolve w w'\n    -> tq w sc ===>* tq w' sc.\n    unfold tq; intros; repeat match goal with\n                                | [ |- exB _ ===>* exB _ ] => apply into_ex; intro\n                                | [ |- (_ * _ ===>* _ * _)%Sep ] => apply into_star; try apply weak_refl\n                              end.\n    apply starB_weaken_weak; intros.\n    unfold HimpWeak; propxFo; descend; eauto.\n    eapply Imply_trans; [ | apply H5 ]; clear H5.\n    descend.\n    apply andL; apply injL; intro.\n    apply andR; [ apply injR | ].\n    eapply evolve_trans; eauto.\n    apply Imply_refl.\n  Qed.\nEnd Tq.\n\nImport Tq.\nExport Tq.\nHint Immediate tq_extensional.\n\nDefinition locals_expose ns vs ss sp := locals ns vs ss sp.\nOpaque mult.\nRequire Import Coq.Arith.Arith.\nTransparent mult.\n\nLemma expose_stack : forall ns vs ss sp,\n  locals_expose ns vs ss sp ===> sp =?> (length ns + ss).\n  unfold locals_expose, locals; intros; eapply Himp_trans; [ | apply allocated_join ].\n  instantiate (1 := length ns).\n  2: omega.\n  Opaque mult.\n  sepLemma.\n  eapply Himp_trans; [ apply Himp_star_comm | ].\n  eapply Himp_star_frame.\n  eapply Himp_trans; [ apply ptsto32m_allocated | ].\n  rewrite length_toArray; apply Himp_refl.\n  apply allocated_shift_base.\n  unfold natToW; rewrite mult_comm; words.\n  omega.\n  Transparent mult.\nQed.\n\nDefinition hints : TacPackage.\n  prepare (tq_fwd, create_stack, expose_stack) (tq_bwd, susps_empty_bwd, susps_add_bwd).\nDefined.\n\n(* What is a valid initial code pointer for a thread, given the requested stack size? *)\n\nDefinition ginv w sc := substH (globalInv w sc) (fun x => tq (World x) (Pointer x) (Settings x) (Mem x)).\n\nDefinition starting (w : world) (sc pc : W) (ss : nat) : HProp := fun s m =>\n  (ExX (* pre *) : settings * state, Cptr pc #0\n    /\\ [| semp m |]\n    /\\ Al st : state, Al vs, Al w',\n      [| evolve w w' |]\n      /\\ [| Regs st Sp <> 0 /\\ freeable (Regs st Sp) (1 + ss) |]\n      /\\ ![ ^[locals (\"rp\" :: nil) vs ss (Regs st Sp) * tq w' sc * ginv w' sc * mallocHeap 0] ] (s, st)\n      ---> #0 (s, st))%PropX.\n\nLocal Hint Resolve split_a_semp_a semp_smem_emp.\n\nLemma starting_intro : forall specs sc w pc ss P stn st,\n  (exists pre, specs pc = Some (fun x => pre x)\n    /\\ interp specs (![ P ] (stn, st))\n    /\\ forall st' vs w', interp specs ([| evolve w w' |]\n      /\\ [| Regs st' Sp <> 0 /\\ freeable (Regs st' Sp) (1 + ss) |]\n      /\\ ![ locals (\"rp\" :: nil) vs ss (Regs st' Sp)\n      * tq w' sc * ginv w' sc * mallocHeap 0 ] (stn, st')\n    ---> pre (stn, st'))%PropX)\n  -> interp specs (![ starting w sc pc ss * P ] (stn, st)).\n  cptr.\nQed.\n\nLemma starting_elim : forall specs w sc pc ss P stn st,\n  interp specs (![ starting w sc pc ss * P ] (stn, st))\n  -> (exists pre, specs pc = Some (fun x => pre x)\n    /\\ interp specs (![ P ] (stn, st))\n    /\\ forall st' vs w', interp specs ([| evolve w w' |]\n      /\\ [| Regs st' Sp <> 0 /\\ freeable (Regs st' Sp) (1 + ss) |]\n      /\\ ![ locals (\"rp\" :: nil) vs ss (Regs st' Sp)\n      * tq w' sc * ginv w' sc * 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  make_Himp.\n  apply Himp_refl.\nQed.\n\nDefinition susp' (w : world) (sc pc sp : W) : HProp := fun s m =>\n  (ExX (* pre *) : settings * state, Cptr pc #0\n    /\\ ExX (* inv *) : settings * smem, #0 (s, m)\n    /\\ Al st : state, Al w' : world,\n    [| evolve w w' |]\n    /\\ ![ #0 * ^[tq w' sc * ginv w' sc * mallocHeap 0] ] (s, st)\n    /\\ [| Regs st Sp = sp |]\n    ---> #1 (s, st))%PropX.\n\nLemma susp_convert : forall specs w sc pc sp P stn st pc_tq,\n  interp specs (![ susp' w sc pc sp * P ] (stn, st))\n  -> Labels stn (labl \"threadq\" \"ADT\") = Some pc_tq\n  -> specs pc_tq = Some (fun _ => PropX.Forall (fun x => tq (World x) (Pointer x) (Settings x) (Mem x)))\n  -> interp specs (![ susp w sc pc sp * P ] (stn, st)).\n  cptr.\n  descend; step auto_ext.\n  eauto.\n  step auto_ext.\nQed.\n\nLemma susp'_intro : forall specs w sc pc sp P stn st,\n  (exists pre, specs pc = Some (fun x => pre x)\n    /\\ exists inv, interp specs (![ inv * P ] (stn, st))\n      /\\ forall st' w', interp specs ([| evolve w w' |]\n        /\\ ![ inv * tq w' sc * ginv w' sc * mallocHeap 0 ] (stn, st')\n        /\\ [| Regs st' Sp = sp |]\n        ---> pre (stn, st'))%PropX)\n  -> interp specs (![ susp' w sc pc sp * P ] (stn, st)).\n  cptr.\n  descend; step auto_ext.\n  eauto.\n  descend; step auto_ext.\nQed.\n\nDefinition initS : spec := SPEC reserving 12\n  Al w,\n  PRE[_] mallocHeap 0\n  POST[R] tq w R * mallocHeap 0.\n\nDefinition isEmptyS : spec := SPEC(\"sc\") reserving 4\n  Al w,\n  PRE[V] tq w (V \"sc\") * mallocHeap 0\n  POST[_] tq w (V \"sc\") * mallocHeap 0.\n\nDefinition spawnWithStackS : spec := SPEC(\"sc\", \"pc\", \"sp\") reserving 14\n  Al w,\n  PRE[V] tq w (V \"sc\") * susp' w (V \"sc\") (V \"pc\") (V \"sp\") * mallocHeap 0\n  POST[_] tq w (V \"sc\") * mallocHeap 0.\n\nDefinition spawnS : spec := SPEC(\"sc\", \"pc\", \"ss\") reserving 18\n  Al w,\n  PRE[V] [| V \"ss\" >= $2 |] * tq w (V \"sc\") * starting w (V \"sc\") (V \"pc\") (wordToNat (V \"ss\") - 1) * mallocHeap 0\n  POST[_] tq w (V \"sc\") * mallocHeap 0.\n\nDefinition localsInvariantExit' (pre : vals -> W -> qspec) (rpStashed : bool) (adjustSp : W -> W)\n  (ns : list string) (_ : nat) : assert :=\n  st ~> let sp := adjustSp st#Sp in\n    Ex vs, qspecOut (pre (sel vs) st#Rv) (fun pre =>\n      ![ locals (\"rp\" :: ns) vs 14 sp * pre ] st).\n\nLocal Notation \"'PREexit'' [ vs ] pre\" := (localsInvariantExit' (fun vs _ => pre%qspec%Sep))\n  (at level 89).\n\nLocal Notation \"'PREexit'' [ vs , rv ] pre\" := (localsInvariantExit' (fun vs rv => pre%qspec%Sep))\n  (at level 89).\n\nDefinition exitS : spec := SPEC(\"sc\", \"ss\") reserving 0\n  Al w,\n  PREexit[V] [| V \"ss\" >= $3 |] * tq w (V \"sc\") * ginv w (V \"sc\") * mallocHeap 0.\n\nLocal Notation \"'bexit' name ( x1 , .. , xN ) [ p ] b 'end'\" :=\n  (let p' := p in\n   let vars := cons x1 (.. (cons xN nil) ..) in\n    {| FName := name;\n      FPrecondition := Precondition p' None;\n      FBody := b%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\nDefinition yieldS : spec := SPEC(\"sc\") reserving 19\n  Al w,\n  PRE[V] tq w (V \"sc\") * ginv w (V \"sc\") * mallocHeap 0\n  POST[_] Ex w', [| evolve w w' |] * tq w' (V \"sc\") * ginv w' (V \"sc\") * mallocHeap 0.\n\n(* Next, some hijinks to prevent unnecessary unfolding of distinct memory cells for the threadq's stack. *)\n\nDefinition stackSize := 21.\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\" :: \"sc\" :: \"ss\" :: \"curPc\" :: \"curSp\" :: \"newPc\" :: \"newSp\" :: nil) + 14.\n  reflexivity.\nQed.\n\nOpaque stackSize.\n\nDefinition yieldInvariantCont (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    Ex vs, qspecOut (pre (sel vs) st#Rv) (fun pre =>\n      ![ ^[locals (\"rp\" :: ns) vs res sp * pre] ] st).\n\nLocal Notation \"'PREy' [ vs ] pre\" := (yieldInvariantCont (fun vs _ => pre%qspec%Sep))\n  (at level 89).\n\nNotation \"'badt' name p 'end'\" :=\n  {| FName := name;\n    FPrecondition := (fun _ => PropX.Forall p);\n    FBody := Diverge;\n    FVars := nil;\n    FReserved := 0 |}\n  (no associativity, at level 95, name at level 0, p at level 0, only parsing) : SPfuncs_scope.\n\nDefinition m := bimport [[ \"malloc\"!\"malloc\" @ [mallocS], \"malloc\"!\"free\" @ [freeS],\n    \"queue\"!\"init\" @ [Queue.initS], \"queue\"!\"isEmpty\" @ [Queue.isEmptyS],\n    \"queue\"!\"enqueue\" @ [enqueueS], \"queue\"!\"dequeue\" @ [dequeueS] ]]\n  bmodule \"threadq\" {{\n    badt \"ADT\"\n      (fun x => tq (World x) (Pointer x) (Settings x) (Mem x))\n    end with bfunction \"init\"(\"q\", \"sp\", \"r\") [initS]\n      \"q\" <-- Call \"queue\"!\"init\"()\n      [PRE[_, R] mallocHeap 0\n       POST[R'] Ex sp, Ex vs, (R' ==*> R, sp) * (R' ^+ $8) =?> 2\n         * locals (\"rp\" :: \"sc\" :: \"ss\" :: \"curPc\" :: \"curSp\" :: \"newPc\" :: \"newSp\" :: nil) vs 14 sp\n         * mallocHeap 0];;\n\n      \"sp\" <-- Call \"malloc\"!\"malloc\"(0, stackSize)\n      [PRE[V, R] R =?> stackSize * mallocHeap 0\n        POST[R'] Ex vs, (R' ==*> V \"q\", R) * (R' ^+ $8) =?> 2 * mallocHeap 0\n         * locals (\"rp\" :: \"sc\" :: \"ss\" :: \"curPc\" :: \"curSp\" :: \"newPc\" :: \"newSp\" :: nil) vs 14 R];;\n\n      Assert [PRE[V] mallocHeap 0\n        POST[R] (R ==*> V \"q\", V \"sp\") * (R ^+ $8) =?> 2 * mallocHeap 0];;\n\n      \"r\" <-- Call \"malloc\"!\"malloc\"(0, 4)\n      [PRE[V, R] R =?> 4\n       POST[R'] [| R' = R |] * (R ==*> V \"q\", V \"sp\") * (R ^+ $8) =?> 2 ];;\n      \"r\" *<- \"q\";;\n      \"r\" + 4 *<- \"sp\";;\n      Return \"r\"\n    end with bfunction \"isEmpty\"(\"sc\") [isEmptyS]\n      \"sc\" <-* \"sc\";;\n      \"sc\" <-- Call \"queue\"!\"isEmpty\"(\"sc\")\n      [PRE[_, R] Emp\n       POST[R'] [| R' = R |] ];;\n      Return \"sc\"\n    end with bfunction \"spawnWithStack\"(\"sc\", \"pc\", \"sp\") [spawnWithStackS]\n      Assert* [(\"threadq\",\"ADT\")] [Al w,\n        PRE[V] tq w (V \"sc\") * susp w (V \"sc\") (V \"pc\") (V \"sp\") * mallocHeap 0\n        POST[_] tq w (V \"sc\") * mallocHeap 0];;\n\n      \"sc\" <-* \"sc\";;\n      Note [mergeSusp];;\n      Call \"queue\"!\"enqueue\"(\"sc\", \"pc\", \"sp\")\n      [Al w, Al b, Al sc,\n        PRE[V] susps w (b %+ (V \"pc\", V \"sp\")) sc\n         POST[_] susps w (b %+ (V \"pc\", V \"sp\")) sc];;\n      Return 0\n    end with bfunction \"spawn\"(\"sc\", \"pc\", \"ss\") [spawnS]\n      \"ss\" <-- Call \"malloc\"!\"malloc\"(0, \"ss\")\n      [Al w, Al ss,\n        PRE[V, R] tq w (V \"sc\") * starting w (V \"sc\") (V \"pc\") (ss - 1) * mallocHeap 0\n          * R =?> ss * [| (ss >= 2)%nat |] * [| R <> 0 |] * [| freeable R ss |]\n        POST[_] tq w (V \"sc\") * mallocHeap 0];;\n\n      Assert [Al w, Al ss, Al vs,\n        PRE[V] tq w (V \"sc\") * starting w (V \"sc\") (V \"pc\") ss * mallocHeap 0\n          * locals (\"rp\" :: nil) vs ss (V \"ss\") * [| V \"ss\" <> 0 |] * [| freeable (V \"ss\") (1 + ss) |]\n        POST[_] tq w (V \"sc\") * mallocHeap 0];;\n\n      Assert* [(\"threadq\",\"ADT\")]\n      [Al w,\n        PRE[V] tq w (V \"sc\") * susp' w (V \"sc\") (V \"pc\") (V \"ss\") * mallocHeap 0\n        POST[_] tq w (V \"sc\") * mallocHeap 0];;\n\n      Call \"threadq\"!\"spawnWithStack\"(\"sc\", \"pc\", \"ss\")\n      [PRE[_] Emp\n       POST[_] Emp];;\n      Return 0\n    end with bexit \"exit\"(\"sc\", \"ss\", \"curPc\", \"curSp\", \"newPc\", \"newSp\") [exitS]\n      Rp <-* \"sc\" + 4;;\n      Rp + 4 *<- \"sc\";;\n      Rp + 8 *<- \"ss\";;\n      Rp + 12 *<- Sp;;\n      Sp <- Rp;;\n\n      Call \"malloc\"!\"free\"(0, \"curPc\", \"ss\")\n      [Al w, Al q, Al qp, Al tsp,\n        PREexit'[V] (V \"sc\" ==*> qp, tsp) * queue q qp * (V \"sc\" ^+ $8) =?> 2\n          * susps w q (V \"sc\") * ginv w (V \"sc\") * mallocHeap 0];;\n\n      \"curPc\" <-* \"sc\";;\n      \"curSp\" <-- Call \"queue\"!\"isEmpty\"(\"curPc\")\n      [Al w, Al q, Al tsp,\n        PREexit'[V, R] [| (q %= empty) \\is R |]\n          * queue q (V \"curPc\") * (V \"sc\" ==*> V \"curPc\", tsp)\n          * (V \"sc\" ^+ $8) =?> 2 * susps w q (V \"sc\") * ginv w (V \"sc\") * mallocHeap 0];;\n\n      If (\"curSp\" = 1) {\n        (* No threads left to run.  Let's loop forever! *)\n        Diverge\n      } else {\n        (* Pick a thread to switch to. *)\n\n        \"curSp\" <- \"sc\" + 8;;\n        Call \"queue\"!\"dequeue\"(\"curPc\", \"curSp\")\n        [Al w, Al q, Al tsp, Al pc, Al sp,\n          PREexit'[V] [| (pc, sp) %in q |] * queue (q %- (pc, sp)) (V \"curPc\")\n            * susps w (q %- (pc, sp)) (V \"sc\") * susp w (V \"sc\") pc sp\n            * (V \"sc\" ==*> V \"curPc\", tsp, pc, sp) * ginv w (V \"sc\") * mallocHeap 0];;\n\n        \"sc\" + 4 *<- Sp;;\n        Rp <-* \"sc\" + 8;;\n        Sp <-* \"sc\" + 12;;\n        IGoto* [(\"threadq\",\"ADT\")] Rp\n      }\n    end with bfunction \"yield\"(\"sc\", \"ss\", \"curPc\", \"curSp\", \"newPc\", \"newSp\") [yieldS]\n      \"ss\" <-* \"sc\";;\n      (* Using \"curPc\" as a temporary before getting to its primary use... *)\n      \"curPc\" <-- Call \"queue\"!\"isEmpty\"(\"ss\")\n      [Al w, Al q, Al tsp, Al vs,\n        PRE[V, R] [| (q %= empty) \\is R |]\n          * queue q (V \"ss\") * (V \"sc\" ==*> V \"ss\", tsp) * (V \"sc\" ^+ $8) =?> 2 * susps w q (V \"sc\")\n          * ginv w (V \"sc\") * mallocHeap 0\n          * locals (\"rp\" :: \"sc\" :: \"ss\" :: \"curPc\" :: \"curSp\" :: \"newPc\" :: \"newSp\" :: nil) vs 14 tsp\n        POST[_] Ex w', [| evolve w w' |] * tq w' (V \"sc\") * ginv w' (V \"sc\") * mallocHeap 0];;\n\n      If (\"curPc\" = 1) {\n        (* No other threads to run.  Simply returning to caller acts like a yield. *)\n        Rp <- $[Sp+0];;\n        IGoto* [(\"threadq\",\"ADT\")] Rp\n      } else {\n        (* Pick a thread to switch to. *)\n        \"curPc\" <- \"sc\" + 8;;\n        Call \"queue\"!\"dequeue\"(\"ss\", \"curPc\")\n        [Al w, Al q, Al tsp, Al vs, Al pc, Al sp,\n          PRE[V] [| (pc, sp) %in q |] * queue (q %- (pc, sp)) (V \"ss\")\n            * susps w (q %- (pc, sp)) (V \"sc\") * susp w (V \"sc\") pc sp\n            * (V \"sc\" ==*> V \"ss\", tsp, pc, sp) * ginv w (V \"sc\") * mallocHeap 0\n            * locals (\"rp\" :: \"sc\" :: \"ss\" :: \"curPc\" :: \"curSp\" :: \"newPc\" :: \"newSp\" :: nil) vs 14 tsp\n          POST[_] Ex w', [| evolve w w' |] * tq w' (V \"sc\") * ginv w' (V \"sc\") * mallocHeap 0];;\n        \"newPc\" <-* \"sc\" + 8;;\n        \"newSp\" <-* \"sc\" + 12;;\n\n        Assert [Al w,\n          PRE[V] susp w (V \"sc\") (V \"newPc\") (V \"newSp\") * tq w (V \"sc\") * ginv w (V \"sc\") * mallocHeap 0\n          POST[_] Ex w', [| evolve w w' |] * tq w' (V \"sc\") * ginv w' (V \"sc\") * mallocHeap 0];;\n\n        (* Initialize the temporary stack with data we will need, then switch to using it as our stack. *)\n        \"curPc\" <-* \"sc\" + 4;;\n        \"ss\" <-* \"sc\";;\n        \"curPc\" + 4 *<- \"sc\";;\n        \"curPc\" + 8 *<- \"ss\";;\n        \"curPc\" + 12 *<- $[Sp+0];;\n        \"curPc\" + 16 *<- Sp;;\n        \"curPc\" + 20 *<- \"newPc\";;\n        \"curPc\" + 24 *<- \"newSp\";;\n        Sp <- \"curPc\";;\n\n        Assert* [(\"threadq\",\"ADT\")]\n        [PREy[V] Ex w, Ex sp, Ex b, (V \"sc\" ==*> V \"ss\", sp) * (V \"sc\" ^+ $8) =?> 2\n          * queue b (V \"ss\") * susps w b (V \"sc\") * ginv w (V \"sc\") * mallocHeap 0\n          * susp w (V \"sc\") (V \"newPc\") (V \"newSp\") * susp w (V \"sc\") (V \"curPc\") (V \"curSp\")];;\n\n        Note [mergeSusp];;\n\n        (* Enqueue current thread; note that variable references below resolve in the temporary stack. *)\n        Call \"queue\"!\"enqueue\"(\"ss\", \"curPc\", \"curSp\")\n        [PREy[V] Ex w, Ex b, Ex p, Ex sp, (V \"sc\" ==*> p, sp) * (V \"sc\" ^+ $8) =?> 2\n          * queue b p * susps w b (V \"sc\") * ginv w (V \"sc\")\n          * mallocHeap 0 * susp w (V \"sc\") (V \"newPc\") (V \"newSp\")];;\n\n        (* Jump to dequeued thread. *)\n        \"sc\" + 4 *<- Sp;;\n        Rp <- \"newPc\";;\n        Sp <- \"newSp\";;\n        IGoto* [(\"threadq\",\"ADT\")] Rp\n      }\n    end\n  }}.\n\nLocal Hint Extern 1 (@eq W _ _) => words.\n\nLtac t := abstract (sep hints;\n  try (apply himp_star_frame; [ reflexivity | apply susps_del_fwd; assumption ]);\n    eauto).\n\nLemma wordBound : forall w : W,\n  natToW 2 <= w\n  -> (wordToNat w >= 2)%nat.\n  intros; pre_nomega;\n    rewrite wordToNat_natToWord_idempotent in * by reflexivity; assumption.\nQed.\n\nLocal Hint Immediate wordBound.\n\nHint Rewrite <- minus_n_O : sepFormula.\n\nTransparent evalInstrs.\n\nTheorem evalInstrs_app_fwd_None : forall stn is1 is2 st,\n  evalInstrs stn st (is1 ++ is2) = None\n  -> evalInstrs stn st is1 = None\n  \\/ exists st', evalInstrs stn st is1 = Some st' /\\ evalInstrs stn st' is2 = None.\n  induction is1; simpl; intuition eauto.\n  destruct (evalInstr stn st a); eauto.\nQed.\n\nTheorem evalInstrs_app_fwd_Some : forall stn is1 is2 st st',\n  evalInstrs stn st (is1 ++ is2) = Some st'\n  -> exists st'', evalInstrs stn st is1 = Some st'' /\\ evalInstrs stn st'' is2 = Some st'.\n  induction is1; simpl; intuition eauto.\n  destruct (evalInstr stn st a); eauto.\n  discriminate.\nQed.\n\nOpaque evalInstrs.\n\nRequire Import Coq.Logic.Eqdep.\n\nHint Immediate evolve_refl.\n\nTheorem ok : moduleOk m.\n  vcgen.\n\n  t.\n\n  t.\n  t.\n  t.\n  t.\n  t.\n  t.\n  t.\n  t.\n  t.\n\n  post.\n  rewrite stackSize_split in H0.\n  assert (NoDup (\"rp\" :: \"sc\" :: \"ss\" :: \"curPc\" :: \"curSp\" :: \"newPc\" :: \"newSp\" :: nil)) by NoDup.\n  evaluate hints; descend; repeat (step hints; descend); auto.\n\n  t.\n  t.\n  t.\n  t.\n  t.\n\n  t.\n  t.\n  t.\n  t.\n  t.\n  t.\n  t.\n  t.\n\n  t.\n  t.\n  t.\n\n  post.\n  toFront ltac:(fun P => match P with\n                           | susp' _ _ _ _ => idtac\n                         end) H0.\n  eapply susp_convert in H0; eauto.\n  t.\n\n  t.\n  t.\n  t.\n  t.\n  t.\n  t.\n  t.\n\n  t.\n  t.\n  t.\n  t.\n  t.\n  t.\n\n  post.\n  match goal with\n    | [ H : context[?X - 1] |- _ ] =>\n      replace X with (length (\"rp\" :: nil) + (X - length (\"rp\" :: nil))) in H\n  end.\n  assert (NoDup (\"rp\" :: nil)) by NoDup.\n  evaluate hints; sep hints; auto.\n  evaluate hints; simpl; omega.\n\n  post; evaluate auto_ext.\n  match goal with\n    | [ H : interp _ _ |- _ ] =>\n      toFront ltac:(fun P => match P with\n                               | starting _ _ _ _ => idtac\n                             end) H;\n      apply starting_elim in H; post; descend\n  end.\n  toFront_conc ltac:(fun P => match P with\n                                | susp' _ _ _ _ => idtac\n                              end);\n  apply susp'_intro; descend.\n  2: instantiate (5 := locals (\"rp\" :: nil) x2 x1 (sel x4 \"ss\")); sep_auto.\n  eauto.\n  eapply Imply_trans; [ | apply H6 ]; clear H6.\n  descend; step auto_ext.\n  step auto_ext.\n  eauto.\n  rewrite H6; auto.\n  step auto_ext.\n  step auto_ext.\n  sep_auto.\n\n  t.\n  sep_auto; auto.\n  t.\n  t.\n  t.\n\n  t.\n\n  post.\n\n  Transparent evalInstrs.\n\n  Transparent evalInstrs.\n\n  Transparent evalInstrs.\n\n  Opaque evalInstrs.\n\n  change (evalInstrs stn st\n    ((Binop Rv (LvMem (Sp + 4)%loc) Plus 4\n      :: Assign Rp (LvMem Rv)\n      :: Binop Rv Rp Plus 4\n      :: Assign (LvMem Rv) (LvMem (Sp + 4)%loc)\n      :: Binop Rv Rp Plus 8\n      :: Assign (LvMem Rv) (LvMem (Sp + 8)%loc)\n      :: Binop Rv Rp Plus 12\n      :: Assign (LvMem Rv) Sp\n      :: Assign Sp Rp :: nil)\n      ++ (Binop Rv Sp Plus 28\n      :: Assign (LvMem (Rv + 4)%loc) 0\n      :: Binop Rv Sp Plus 28\n      :: Assign (LvMem (Rv + 8)%loc) (LvMem (Sp + 12)%loc)\n      :: Binop Rv Sp Plus 28\n      :: Assign (LvMem (Rv + 12)%loc) (LvMem (Sp + 8)%loc)\n      :: Binop Sp Sp Plus 28 :: nil)) = None) in H0.\n\n  apply evalInstrs_app_fwd_None in H0.\n  destruct H0 as [ | [ ? [ ] ] ].\n  evaluate hints.\n  generalize dependent H0; evaluate hints; intro.\n\n  change (locals (\"rp\" :: \"sc\" :: \"ss\" :: \"curPc\" :: \"curSp\" :: \"newPc\" :: \"newSp\" :: nil)\n    (upd (upd (upd x4 \"sc\" (sel x0 \"sc\")) \"ss\" (sel x0 \"ss\")) \"curPc\" (Regs st Sp))\n    14 x5)\n    with (locals_call (\"rp\" :: \"sc\" :: \"ss\" :: \"curPc\" :: \"curSp\" :: \"newPc\" :: \"newSp\" :: nil)\n      (upd (upd (upd x4 \"sc\" (sel x0 \"sc\")) \"ss\" (sel x0 \"ss\")) \"curPc\" (Regs st Sp))\n      14 x5\n      (\"rp\" :: \"base\" :: \"p\" :: \"n\" :: nil) 0 28) in H5.\n  assert (ok_call (\"rp\" :: \"sc\" :: \"ss\" :: \"curPc\" :: \"curSp\" :: \"newPc\" :: \"newSp\" :: nil)\n    (\"rp\" :: \"base\" :: \"p\" :: \"n\" :: nil)\n    14 0 28)\n  by (split; [ simpl; omega\n    | split; [ simpl; omega\n      | split; [ NoDup\n        | reflexivity ] ] ]).\n  evaluate hints.\n\n  propxFo.\n  change (evalInstrs stn x\n    ((Binop Rv (LvMem (Sp + 4)%loc) Plus 4\n      :: Assign Rp (LvMem Rv)\n      :: Binop Rv Rp Plus 4\n      :: Assign (LvMem Rv) (LvMem (Sp + 4)%loc)\n      :: Binop Rv Rp Plus 8\n      :: Assign (LvMem Rv) (LvMem (Sp + 8)%loc)\n      :: Binop Rv Rp Plus 12\n      :: Assign (LvMem Rv) Sp\n      :: Assign Sp Rp :: nil)\n      ++ (Binop Rv Sp Plus 28\n      :: Assign (LvMem (Rv + 4)%loc) 0\n      :: Binop Rv Sp Plus 28\n      :: Assign (LvMem (Rv + 8)%loc) (LvMem (Sp + 12)%loc)\n      :: Binop Rv Sp Plus 28\n      :: Assign (LvMem (Rv + 12)%loc) (LvMem (Sp + 8)%loc)\n      :: Binop Sp Sp Plus 28 :: nil)) = Some st) in H2.\n\n  apply evalInstrs_app_fwd_Some in H2.\n  destruct H2 as [ ? [ ] ].\n  generalize dependent H2; evaluate hints; intro.\n  change (locals (\"rp\" :: \"sc\" :: \"ss\" :: \"curPc\" :: \"curSp\" :: \"newPc\" :: \"newSp\" :: nil)\n    (upd (upd (upd x5 \"sc\" (sel x1 \"sc\")) \"ss\" (sel x1 \"ss\")) \"curPc\" (Regs x Sp))\n    14 x6)\n    with (locals_call (\"rp\" :: \"sc\" :: \"ss\" :: \"curPc\" :: \"curSp\" :: \"newPc\" :: \"newSp\" :: nil)\n      (upd (upd (upd x5 \"sc\" (sel x1 \"sc\")) \"ss\" (sel x1 \"ss\")) \"curPc\" (Regs x Sp))\n      14 x6\n      (\"rp\" :: \"base\" :: \"p\" :: \"n\" :: nil) 2 28) in H6.\n  assert (ok_call (\"rp\" :: \"sc\" :: \"ss\" :: \"curPc\" :: \"curSp\" :: \"newPc\" :: \"newSp\" :: nil)\n    (\"rp\" :: \"base\" :: \"p\" :: \"n\" :: nil)\n    14 2 28)\n  by (split; [ simpl; omega\n    | split; [ simpl; omega\n      | split; [ NoDup\n        | reflexivity ] ] ]).\n  change (locals (\"rp\" :: \"sc\" :: \"ss\" :: nil) x1 (wordToNat (sel x1 \"ss\") - 3) (Regs x Sp))\n  with (locals_expose (\"rp\" :: \"sc\" :: \"ss\" :: nil) x1 (wordToNat (sel x1 \"ss\") - 3) (Regs x Sp)) in H6.\n  evaluate hints.\n  replace (S (S (S (wordToNat (sel x1 \"ss\") - 3)))) with (wordToNat (sel x1 \"ss\")) in H12.\n  descend.\n  step hints.\n  step hints.\n  step hints.\n  unfold localsInvariantExit'; descend; step hints.\n  descend; step hints.\n  descend; step hints.\n  generalize H9; clear.\n  intros; pre_nomega.\n  rewrite wordToNat_natToWord_idempotent in H9 by reflexivity; omega.\n\n  t.\n  t.\n  unfold localsInvariantExit'; t.\n  t.\n  t.\n  t.\n\n  unfold localsInvariantExit'; post; evaluate hints.\n  descend.\n  step hints.\n  2: step hints.\n  eauto.\n  step hints.\n  descend; step hints.\n  descend; step hints.\n  apply susps_del_fwd; assumption.\n\n  t.\n  t.\n\n  post; evaluate hints.\n  match goal with\n    | [ H : interp _ _ |- _ ] =>\n      toFront ltac:(fun P => match P with\n                               | susp _ _ _ _ => idtac\n                             end) H;\n      apply susp_elim in H; post\n  end.\n  descend.\n  step auto_ext.\n  match goal with\n    | [ H : _ |- _ ] => eapply (Imply_sound (H _ _)); clear H; eauto\n  end.\n  propxFo.\n  unfold labl in H7; rewrite H1 in H7; injection H7; clear H1 H7; intros; subst.\n  rewrite H9 in H2; injection H2; clear H2 H9; intros; subst.\n  apply (f_equal (fun f => f (stn, st))) in H.\n  injection H; clear H; intros; subst.\n  do 2 apply inj_pair2 in H; subst; simpl.\n  change (fun x y => tq x2 (sel x7 \"sc\") x y) with (tq x2 (sel x7 \"sc\")).\n  change (fun st m => subst (globalInv x2 (sel x7 \"sc\") st m)\n    (fun x : tq_args world => tq (World x) (Pointer x) (Settings x) (Mem x)))\n    with (ginv x2 (sel x7 \"sc\")).\n  step hints.\n\n  t.\n  t.\n  t.\n  t.\n\n  post.\n  evaluate hints.\n  descend.\n  step hints.\n  step hints.\n  step hints.\n  descend; step hints.\n  instantiate (2 := x8).\n  instantiate (3 := upd x2 \"ss\" x9).\n  descend; cancel hints.\n  sep hints.\n  sep hints.\n  sep hints; auto.\n\n  t.\n  t.\n  t.\n\n  t.\n  t.\n\n  post; evaluate hints; descend.\n  step hints.\n  2: step hints.\n  eauto.\n  step hints.\n  descend; step hints.\n  instantiate (2 := x3).\n  instantiate (3 := upd (upd x6 \"curPc\" (Regs x0 Rv)) \"curPc\" (sel x6 \"sc\" ^+ $8)).\n  descend; cancel hints.\n  step hints.\n  apply himp_star_frame; [ reflexivity | apply susps_del_fwd; assumption ].\n  step hints.\n  sep hints; auto.\n\n  t.\n  t.\n  t.\n  t.\n\n  post; evaluate hints.\n  descend.\n  instantiate (1 := upd (upd (upd (upd (upd (upd x7 \"sc\" (sel x3 \"sc\")) \"ss\" x9) \"curPc\"\n    (sel x3 \"rp\")) \"curSp\" (Regs x0 Sp)) \"newPc\" (sel x3 \"newPc\")) \"newSp\" (sel x3 \"newSp\")); descend.\n  toFront_conc ltac:(fun P => match P with\n                                | susp _ _ (sel _ \"rp\") _ => idtac\n                              end).\n  apply susp_intro; descend; eauto.\n  match goal with\n    | [ _ : context[locals ?ns ?v ?a (Regs ?st Sp)] |- interp specs (![?P * _] _) ] =>\n      equate P (locals ns v a (Regs st Sp) * (fun x y => x2 (x, y)))%Sep\n  end.\n  step hints.\n  step auto_ext.\n  step auto_ext.\n  change (fun (x11 : ST.settings) (y : smem) => tq w' (sel x3 \"sc\") x11 y)\n    with (tq w' (sel x3 \"sc\")).\n  change (fun (st : ST.settings) (m0 : smem) =>\n    subst (globalInv w' (sel x3 \"sc\") st m0)\n      (fun x11 : tq_args world =>\n        tq (World x11) (Pointer x11) (Settings x11) (Mem x11))) with (ginv w' (sel x3 \"sc\")).\n  step auto_ext.\n\n  t.\n  t.\n\n  post; evaluate hints; descend.\n  instantiate (3 := x3).\n  step hints.\n  step hints.\n  step hints.\n  unfold yieldInvariantCont; descend; step hints.\n  instantiate (8 := x3 %+ (sel x0 \"curPc\", sel x0 \"curSp\")).\n  descend; step hints.\n\n  t.\n  t.\n\n  post; evaluate hints.\n  match goal with\n    | [ H : interp _ _ |- _ ] =>\n      toFront ltac:(fun P => match P with\n                               | susp _ _ _ _ => idtac\n                             end) H;\n      apply susp_elim in H; post\n  end.\n  descend.\n  step auto_ext.\n  match goal with\n    | [ H : _ |- _ ] => eapply (Imply_sound (H _ _)); eauto\n  end.\n  unfold labl in H7; rewrite H1 in H7; injection H7; clear H1 H7; intros; subst.\n  rewrite H8 in H2; injection H2; clear H2 H8; intros; subst.\n  apply (f_equal (fun f => f (stn, st))) in H1.\n  injection H1; clear H1; intros; subst.\n  do 2 apply inj_pair2 in H1; subst; simpl.\n  instantiate (1 := x3).\n  change (fun x y => tq x3 (sel x2 \"sc\") x y) with (tq x3 (sel x2 \"sc\")).\n  change (fun st m => subst (globalInv x3 (sel x2 \"sc\") st m)\n    (fun x : tq_args world => tq (World x) (Pointer x) (Settings x) (Mem x)))\n    with (ginv x3 (sel x2 \"sc\")).\n  propxFo.\n  step hints.\nQed.\n\nTransparent stackSize.\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/ThreadQueue.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.273079359144397}}
{"text": "From CoreErlang.BigStep Require Import Tactics.\nFrom CoreErlang.BigStep Require Export FunctionalBigStep.\n\nImport ListNotations.\n\n(**\n  Equivalence between the big-step and functional big-step semantics\n*)\n\nSection Soundness.\n\nLemma restrict_soundness :\nforall {A : Type} {env modules own_module exps a v} {id : nat} {id' eff' eff1 x x0 x1 defexp defval} {f : nat -> Environment -> (list ErlModule) -> string -> nat -> A -> SideEffectList -> ResultType},\n(forall i : nat,\n    i < Datatypes.length (a :: exps) ->\n    exists clock : nat,\n      f clock env modules own_module (nth_def (id' :: x1) id 0 i) (nth i (a :: exps) defexp)\n        (nth_def (eff' :: x0) eff1 [] i) =\n      Result (nth_def (id' :: x1) id 0 (S i)) (inl [nth i (v :: x) defval])\n        (nth_def (eff' :: x0) eff1 [] (S i)))\n->\n(forall i : nat,\n    i < Datatypes.length (exps) ->\n    exists clock : nat,\n      f clock env modules own_module (nth_def x1 id' 0 i) (nth i exps defexp)\n        (nth_def x0 eff' [] i) =\n      Result (nth_def x1 id' 0 (S i)) (inl [nth i x defval])\n        (nth_def x0 eff' [] (S i))).\nProof.\n  intros.\n  assert (S i < S (length exps)) as A1.\n  { simpl. lia. } pose (E := H (S i) A1). \n  destruct E. simpl nth_def in H1. simpl nth in H. exists x2. simpl. exact H1.\nQed.\n(* \nLemma fbs_single_list_soundness :\nforall {exps vals eff ids env id eff1},\n  (forall i : nat,\n    i < Datatypes.length exps ->\n    exists clock : nat,\n      fbs_single clock env (nth_def ids id 0 i) (nth i exps ErrorExp) (nth_def eff eff1 [] i) =\n      Result (nth_def ids id 0 (S i)) (inl [nth i vals ErrorValue])\n        (nth_def eff eff1 [] (S i))) ->\n  length exps = length vals ->\n  length exps = length eff ->\n  length exps = length ids\n->\n  exists clock, fbs_values (fbs_single clock) env id exps eff1 = Result (last ids id) (inl vals) (last eff eff1).\nProof.\n  induction exps; intros.\n  * apply eq_sym, length_zero_iff_nil in H0.\n    apply eq_sym, length_zero_iff_nil in H1.\n    apply eq_sym, length_zero_iff_nil in H2. subst.\n    exists 1. simpl. auto.\n  * pose (EE1 := element_exist _ _ H0).\n    pose (EE2 := element_exist _ _ H1).\n    pose (EE3 := element_exist _ _ H2).\n    destruct EE1 as [v], EE2 as [eff'], EE3 as [id'], H3, H4, H5. subst.\n    inversion H0. inversion H1. inversion H2.\n\n    pose (P := H 0 (Nat.lt_0_succ _)). destruct P as [cl1]. simpl in H3.\n\n    epose (P2 := IHexps _ _ _ _ _ _ (restrict_soundness H) _ _ _).\n    Unshelve.\n    2-4: auto.\n    destruct P2 as [cl2].\n    exists (cl1 + cl2).\n    simpl fbs_values.\n    apply bigger_clock_single with (clock' := cl1 + cl2) in H3. 2: lia.\n    apply bigger_clock_list with (clock' := cl1 + cl2) in H7. \n      2: lia. 2: intros; apply clock_increase_single; auto.\n    rewrite H3, H7.\n    rewrite last_element_equal with (def2 := id).\n    rewrite last_element_equal with (def2 := eff1). auto.\nQed.\n\nLemma fbs_single_list_soundness_exception :\nforall {exps vals eff ids env id eff1 id' ex eff' i},\n(forall j : nat,\n    j < i ->\n    exists clock : nat,\n      fbs_single clock env (nth_def ids id 0 j) (nth j exps ErrorExp) (nth_def eff eff1 [] j) =\n      Result (nth_def ids id 0 (S j)) (inl [nth j vals ErrorValue])\n        (nth_def eff eff1 [] (S j)))\n->\n(exists clock : nat,\n       fbs_single clock env (last ids id) (nth i exps ErrorExp) (last eff eff1) =\n       Result id' (inr ex) eff')\n->\ni < Datatypes.length exps ->\nDatatypes.length vals = i ->\nDatatypes.length eff = i ->\nDatatypes.length ids = i\n->\n  exists clock, fbs_values (fbs_single clock) env id exps eff1 = Result id' (inr ex) eff'.\nProof.\n  induction exps; intros.\n  * inversion H1.\n  * destruct i.\n    - apply length_zero_iff_nil in H2.\n      apply length_zero_iff_nil in H3.\n      apply length_zero_iff_nil in H4. subst.\n      destruct H0. exists x. simpl in *. rewrite H0. auto.\n    - pose (P1 := element_exist _ _ (eq_sym H2)).\n      pose (P2 := element_exist _ _ (eq_sym H3)).\n      pose (P3 := element_exist _ _ (eq_sym H4)).\n      destruct P1 as [v0']. destruct P2 as [eff0']. destruct P3 as [id0'].\n      destruct H5, H6, H7. subst.\n      pose (P := H 0 (Nat.lt_0_succ _)). destruct P. simpl in H5.\n      simpl in H1. apply Nat.succ_lt_mono in H1.\n      simpl in H2, H3, H4.\n      apply eq_add_S in H2. apply eq_add_S in H3. apply eq_add_S in H4.\n      rewrite <- last_element_equal, <- last_element_equal in H0.\n      epose (P2 := IHexps _ _ _ _ _ _ _ _ _ _ _ H0 H1 H2 H3 H4).\n      destruct P2. exists (x2 + x3).\n      simpl.\n      apply bigger_clock_single with (clock' := x2 + x3) in H5.\n      apply bigger_clock_list with (clock' := x2 + x3) in H6.\n      rewrite H5, H6. auto.\n      1, 3: lia.\n      intros. apply clock_increase_single. auto.\n  Unshelve.\n  intros. epose (H (S j) _). exact e.\n  Unshelve.\n  lia.\nQed.\n *)\nLemma fbs_expr_list_soundness :\nforall {exps : list Expression} {vals eff ids env modules own_module id eff1},\n(forall i : nat,\n    i < Datatypes.length exps ->\n    exists clock : nat,\n      fbs_expr clock env modules own_module (nth_def ids id 0 i) (nth i exps ErrorExp) (nth_def eff eff1 [] i) =\n      Result (nth_def ids id 0 (S i)) (inl [nth i vals ErrorValue])\n        (nth_def eff eff1 [] (S i))) ->\n  length exps = length vals ->\n  length exps = length eff ->\n  length exps = length ids\n->\n  exists clock, fbs_values (fbs_expr clock) env modules own_module id exps eff1 = Result (last ids id) (inl vals) (last eff eff1).\nProof.\n  induction exps; intros.\n  * apply eq_sym, length_zero_iff_nil in H0.\n    apply eq_sym, length_zero_iff_nil in H1.\n    apply eq_sym, length_zero_iff_nil in H2. subst.\n    exists 1. simpl. auto.\n  * pose (EE1 := element_exist _ _ H0).\n    pose (EE2 := element_exist _ _ H1).\n    pose (EE3 := element_exist _ _ H2).\n    destruct EE1 as [v], EE2 as [eff'], EE3 as [id'], H3, H4, H5. subst.\n    inversion H0. inversion H1. inversion H2.\n\n    pose (P := H 0 (Nat.lt_0_succ _)). destruct P as [cl1]. simpl in H3.\n\n    epose (P2 := IHexps _ _ _ _ _ _ _ _ (restrict_soundness H) _ _ _).\n    Unshelve.\n    2-4: auto.\n    destruct P2 as [cl2].\n    exists (cl1 + cl2).\n    simpl fbs_values.\n    apply bigger_clock_expr with (clock' := cl1 + cl2) in H3. 2: lia.\n    apply bigger_clock_list with (clock' := cl1 + cl2) in H7. \n      2: lia. 2: intros; apply clock_increase_expr; auto.\n    rewrite H3, H7.\n    rewrite last_element_equal with (def2 := id).\n    rewrite last_element_equal with (def2 := eff1). auto.\nQed.\n\nLemma fbs_expr_list_soundness_exception :\nforall {exps : list Expression} {vals eff ids env modules own_module id eff1 id' ex eff' i},\n(forall j : nat,\n    j < i ->\n    exists clock : nat,\n      fbs_expr clock env modules own_module (nth_def ids id 0 j) (nth j exps ErrorExp) (nth_def eff eff1 [] j) =\n      Result (nth_def ids id 0 (S j)) (inl [nth j vals ErrorValue])\n        (nth_def eff eff1 [] (S j)))\n->\n(exists clock : nat,\n       fbs_expr clock env modules own_module (last ids id) (nth i exps ErrorExp) (last eff eff1) =\n       Result id' (inr ex) eff')\n->\ni < Datatypes.length exps ->\nDatatypes.length vals = i ->\nDatatypes.length eff = i ->\nDatatypes.length ids = i\n->\n  exists clock, fbs_values (fbs_expr clock) env modules own_module id exps eff1 = Result id' (inr ex) eff'.\nProof.\n  induction exps; intros.\n  * inversion H1.\n  * destruct i.\n    - apply length_zero_iff_nil in H2.\n      apply length_zero_iff_nil in H3.\n      apply length_zero_iff_nil in H4. subst.\n      destruct H0. exists x. simpl in *. rewrite H0. auto.\n    - pose (P1 := element_exist _ _ (eq_sym H2)).\n      pose (P2 := element_exist _ _ (eq_sym H3)).\n      pose (P3 := element_exist _ _ (eq_sym H4)).\n      destruct P1 as [v0']. destruct P2 as [eff0']. destruct P3 as [id0'].\n      destruct H5, H6, H7. subst.\n      pose (P := H 0 (Nat.lt_0_succ _)). destruct P. simpl in H5.\n      simpl in H1. apply Nat.succ_lt_mono in H1.\n      simpl in H2, H3, H4.\n      apply eq_add_S in H2. apply eq_add_S in H3. apply eq_add_S in H4.\n      rewrite <- last_element_equal, <- last_element_equal in H0.\n      epose (P2 := IHexps _ _ _ _ _ _ _ _ _ _ _ _ _ H0 H1 H2 H3 H4).\n      destruct P2. exists (x2 + x3).\n      simpl.\n      apply bigger_clock_expr with (clock' := x2 + x3) in H5.\n      apply bigger_clock_list with (clock' := x2 + x3) in H6.\n      rewrite H5, H6. auto.\n      1, 3: lia.\n      intros. apply clock_increase_expr. auto.\n  Unshelve.\n  intros. epose (H (S j) _). exact e.\n  Unshelve.\n  lia.\nQed.\n\nLemma fbs_case_soundness :\nforall {l id' eff2 id'' res eff3 vals env modules own_module i guard exp bindings},\n(forall j : nat,\n     j < i ->\n     forall (gg ee : Expression) (bb : list (Var * Value)),\n     match_clause vals l j = Some (gg, ee, bb) ->\n     exists clock : nat,\n       fbs_expr clock (add_bindings bb env) modules own_module id' gg eff2 = Result id' (inl [ffalse]) eff2) ->\nmatch_clause vals l i = Some (guard, exp, bindings) ->\n(exists clock : nat,\n       fbs_expr clock (add_bindings bindings env) modules  own_module id' guard eff2 =\n       Result id' (inl [ttrue]) eff2) ->\n(exists clock : nat,\n       fbs_expr clock (add_bindings bindings env) modules own_module id' exp eff2 = Result id'' res eff3) ->\nexists clock, fbs_case l env modules own_module id' eff2 vals (fbs_expr clock) = Result id'' res eff3.\nProof.\n  induction l; intros.\n  * inversion H0.\n  * destruct i.\n    - simpl in H0. destruct H1, H2. exists (x + x0).\n      destruct a, p. simpl. destruct (match_valuelist_to_patternlist vals l0).\n      + inversion H0. subst.\n        apply bigger_clock_expr with (clock' := x + x0) in H1. rewrite H1.\n        unfold ttrue. rewrite eqb_refl, Nat.eqb_refl, list_eqb_refl.\n        simpl.\n        apply bigger_clock_expr with (clock' := x + x0) in H2. rewrite H2. auto.\n        1,3: lia. apply effect_eqb_refl.\n      + congruence.\n    - simpl. destruct a, p.\n      case_eq (match_clause vals ((l0, e0, e) :: l) 0); intros.\n       + destruct p, p.\n         pose (H 0 (Nat.lt_0_succ _) _ _ _ H3). simpl in H3. destruct e3.\n         destruct (match_valuelist_to_patternlist vals l0). 2: congruence.\n         inversion H3. subst.\n         epose (IHl id' eff2 id'' res eff3 vals env modules own_module i guard exp bindings _ _ _ _).\n         destruct e. exists (x + x0).\n         apply bigger_clock_expr with (clock' := x + x0) in H4.\n         apply bigger_clock_case with (clock' := x + x0) in H5.\n         rewrite H4. unfold ffalse. simpl.\n         replace (((id' =? id') && list_eqb effect_eqb eff2 eff2)%bool) with true.\n         2: { symmetry. apply andb_true_intro. rewrite Nat.eqb_refl. rewrite effect_list_eqb_refl. auto. }\n         apply H5.\n         \n         Unshelve.\n         all: try lia.\n         ** intros. eapply H with (j := S j). lia.\n            simpl. exact H6.\n         ** exact H0.\n         ** auto.\n         ** auto.\n       + simpl in H3. simpl.\n         destruct (match_valuelist_to_patternlist vals l0). 1: congruence.\n         epose (IHl id' eff2 id'' res eff3 vals env modules own_module i guard exp bindings _ _ _ _).\n         destruct e1. destruct H2. exists (x + x0).\n         apply bigger_clock_expr with (clock' := x + x0) in H2.\n         apply bigger_clock_case with (clock' := x + x0) in H4.\n         rewrite H4. unfold ffalse. simpl. auto.\n         all: lia.\n         Unshelve.\n         ** intros. eapply H with (j := S j). lia.\n            simpl. exact H5.\n         ** exact H0.\n         ** auto.\n         ** auto.\nQed.\n\nTheorem fbs_case_if_clause_sound :\nforall {l env modules own_module eff2 id' vals},\n(forall j : nat,\n     j < Datatypes.length l ->\n     forall (gg ee : Expression) (bb : list (Var * Value)),\n     match_clause vals l j = Some (gg, ee, bb) ->\n     exists clock : nat,\n       fbs_expr clock (add_bindings bb env) modules own_module id' gg eff2 = Result id' (inl [ffalse]) eff2)\n->\nexists clock, fbs_case l env modules own_module id' eff2 vals (fbs_expr clock) = Result id' (inr if_clause) eff2.\nProof.\n  induction l; intros.\n  * exists 0. auto.\n  * destruct a, p.\n    case_eq (match_clause vals ((l0, e0, e) :: l) 0); intros.\n    - destruct p, p.\n      pose (P := H 0 (Nat.lt_0_succ _) _ _ _ H0).\n      simpl in H0.\n      assert (exists clock : nat,\n            fbs_expr clock (add_bindings l1 env) modules own_module id' e1 eff2 = Result id' (inl [ffalse]) eff2). \n      { auto. } clear P. simpl.\n      destruct (match_valuelist_to_patternlist vals l0). 2: congruence.\n      inversion H0. subst. destruct H1.\n      epose (IHl env modules own_module eff2 id' vals _). destruct e.\n      exists (x + x0).\n      apply bigger_clock_expr with (clock' := x + x0) in H1.\n      apply bigger_clock_case with (clock' := x + x0) in H2.\n      rewrite H1, H2.\n      replace (((id' =? id') && list_eqb effect_eqb eff2 eff2)%bool) with true.\n      2: { symmetry. apply andb_true_intro. rewrite Nat.eqb_refl. rewrite effect_list_eqb_refl. auto. }\n      simpl. auto.\n      all: lia.\n      Unshelve.\n      + intros. eapply H with (j := S j). simpl. lia. simpl. exact H3.\n    - simpl.\n      simpl in H0. destruct (match_valuelist_to_patternlist vals l0). 1: congruence.\n      epose (IHl env modules own_module eff2 id' vals _). destruct e1.\n      exists x. rewrite H1. auto.\n      Unshelve.\n      + intros. eapply H with (j := S j). simpl. lia. simpl. exact H2.\nQed.\n\nTheorem fbs_soundness :\n(forall env modules own_module id exp eff id' res eff',\n  | env, modules, own_module, id, exp, eff| -e> | id', res, eff' | \n  ->\n  exists clock, fbs_expr clock env modules own_module id exp eff = Result id' res eff'\n  )(* \n/\\\n(forall env id exp eff id' res eff',\n  | env, id, exp, eff| -s> | id', res, eff' |\n  ->\n  exists clock, fbs_single clock env id exp eff = Result id' res eff')*) .\nProof.\n  intros. induction H.\n  * pose (P := fbs_expr_list_soundness H3 H H0 H1). destruct P.\n    exists (S x). simpl. rewrite H4, H5. auto.\n  * pose (P := fbs_expr_list_soundness_exception H4 IHeval_expr H H0 H1 H2). destruct P. \n    exists (S x). simpl. auto.\n  * exists 1. auto.\n  * exists 1. auto.\n  * exists 1. simpl. rewrite H. auto.\n  * exists 1. simpl. rewrite H. auto.\n  * exists 1. simpl. rewrite H,  H0, H1, H2. auto.\n  * exists 1. auto.\n  * pose (P := fbs_expr_list_soundness H3 H H0 H1). destruct P.\n    exists (S x). simpl. rewrite H4, H5, H6. auto.\n  * destruct IHeval_expr1 as [cl1], IHeval_expr2 as [cl2].\n    exists (S (cl1 + cl2)). simpl.\n    apply bigger_clock_expr with (clock' := cl1 + cl2) in H1.\n    apply bigger_clock_expr with (clock' := cl1 + cl2) in H2.\n    rewrite H1, H2. 2-3: lia. auto.\n  * destruct IHeval_expr1. pose (P := fbs_case_soundness H3 H1 IHeval_expr2 IHeval_expr3). destruct P.\n    exists (S (x + x0)). simpl.\n    apply bigger_clock_expr with (clock' := x + x0) in H6.\n    apply bigger_clock_case with (clock' := x + x0) in H7.\n    rewrite H6. assumption.\n    all: lia.\n  * destruct IHeval_expr1. destruct IHeval_expr2.\n     epose (P := fbs_expr_list_soundness H5 _ _ _).\n    Unshelve. 2-4: auto.\n    destruct P.  exists (S (x + x0 + x1)). simpl.\n    apply bigger_clock_expr with (clock' := x + x0 + x1) in H9.\n    apply bigger_clock_expr with (clock' := x + x0 + x1) in H10.\n    apply bigger_clock_list with (clock' := x + x0 + x1) in H11.\n    rewrite H9. rewrite H10. rewrite H11. rewrite H6.\n    rewrite H7 at 1. rewrite H7 at 1. simpl. rewrite H8. reflexivity.\n    2: intros; apply clock_increase_expr; auto.\n    all: lia.\n  * destruct IHeval_expr1. destruct IHeval_expr2. destruct IHeval_expr3.\n      epose (P := fbs_expr_list_soundness H5 _ _ _).\n    Unshelve. 2-4: auto.\n    destruct P.  exists (S (x + x0 + x1 + x2)). simpl.\n\n    apply bigger_clock_expr with (clock' := x + x0 + x1 + x2) in H8.\n    apply bigger_clock_expr with (clock' := x + x0 + x1 + x2) in H9.\n    apply bigger_clock_expr with (clock' := x + x0 + x1 + x2) in H10.\n    apply bigger_clock_list with (clock' := x + x0 + x1 + x2) in H11.\n    rewrite H8. rewrite H9. rewrite H11.  rewrite H6.  auto.\n    2: intros; apply clock_increase_expr; auto.\n    all: lia. \n  * epose (P := fbs_expr_list_soundness H3 _ _ _).\n    Unshelve. 2-4: auto.\n    destruct P. exists (S x). simpl. rewrite H6.\n    rewrite H4 at 1. rewrite H4 at 1. rewrite <- H5. simpl. auto.\n  * destruct IHeval_expr1, IHeval_expr2.\n    epose (P := fbs_expr_list_soundness H5 _ _ _).\n    Unshelve. 2-4: auto.\n    destruct P. exists (S (x + x0 + x1)). simpl.\n    apply bigger_clock_expr with (clock' := x + x0 + x1) in H7.\n    apply bigger_clock_expr with (clock' := x + x0 + x1) in H8.\n    apply bigger_clock_list with (clock' := x + x0 + x1) in H9.\n    rewrite H7. rewrite H9.\n    apply Nat.eqb_eq in H1. rewrite H1. auto.\n    2: intros; apply clock_increase_expr; auto.\n    all: lia.\n  * destruct IHeval_expr1, IHeval_expr2. exists (S (x + x0)). simpl.\n    apply bigger_clock_expr with (clock' := x + x0) in H2.\n    apply bigger_clock_expr with (clock' := x + x0) in H3.\n    rewrite H2, H3. apply eq_sym, Nat.eqb_eq in H0. rewrite H0. auto.\n    all: lia.\n  * destruct IHeval_expr1, IHeval_expr2. exists (S (x + x0)). simpl.\n    apply bigger_clock_expr with (clock' := x + x0) in H1.\n    apply bigger_clock_expr with (clock' := x + x0) in H2.\n    rewrite H1, H2. auto.\n    all: lia.\n  * destruct IHeval_expr. exists (S x). simpl. auto.\n  * epose (P := fbs_expr_list_soundness H4 _ _ _). destruct P. exists (S x).\n    simpl. unfold exps, vals in H9. rewrite H9.\n    rewrite make_map_consistent. rewrite H5. simpl. rewrite H7, H8. rewrite H6. auto.\n    lia.\n  * destruct IHeval_expr. exists (S x). simpl. rewrite H0. auto.\n  * destruct IHeval_expr1, IHeval_expr2. exists (S (x + x0)). simpl.\n    apply bigger_clock_expr with (clock' := x + x0) in H1.\n    apply bigger_clock_expr with (clock' := x + x0) in H2.\n    rewrite H1, H2. auto.\n    all: lia.\n  * epose (P := fbs_expr_list_soundness_exception H4 IHeval_expr _ _ _ _).\n    destruct P. exists (S x). simpl. rewrite H6. auto.\n  * destruct IHeval_expr1, IHeval_expr2. exists (S (x + x0)). simpl.\n    apply bigger_clock_expr with (clock' := x + x0) in H2.\n    apply bigger_clock_expr with (clock' := x + x0) in H3.\n    rewrite H2, H3. apply eq_sym, Nat.eqb_eq in H0. rewrite H0. auto.\n    all: lia.\n  * destruct IHeval_expr1, IHeval_expr2. exists (S (x + x0)). simpl. simpl in H2.\n    apply bigger_clock_expr with (clock' := x + x0) in H1.\n    apply bigger_clock_expr with (clock' := x + x0) in H2.\n    rewrite H1, H2. auto.\n    all: lia.\n  * destruct IHeval_expr. exists (S x). simpl. rewrite H0. auto.\n  * destruct IHeval_expr. pose (P := fbs_case_if_clause_sound H1).\n    destruct P. exists (S (x + x0)).\n    apply bigger_clock_expr with (clock' := x + x0) in H2.\n    apply bigger_clock_case with (clock' := x + x0) in H3.\n    simpl. rewrite H2, H3. auto. all: lia.\n  * destruct IHeval_expr1. destruct IHeval_expr2.\n    epose (P := fbs_expr_list_soundness_exception H6 IHeval_expr3 _ _ _ _). \n    destruct P. exists (S x + x0 + x1). simpl.\n    apply bigger_clock_expr with (clock' := x + x0 + x1) in H8.\n    apply bigger_clock_expr with (clock' := x + x0 + x1) in H9.\n    apply bigger_clock_list with (clock' := x + x0 + x1) in H10.\n    rewrite H8, H9, H10. reflexivity.\n    2: intros; apply clock_increase_expr; auto.\n    all: lia.\n\n  * destruct IHeval_expr. exists (S x). simpl. rewrite H0. auto.\n  * destruct IHeval_expr1. destruct IHeval_expr2. \n    exists (S (x + x0)). \n    apply bigger_clock_expr with (clock' := x + x0) in H1.\n    apply bigger_clock_expr with (clock' := x + x0) in H2.\n    simpl. rewrite H1. rewrite H2. auto. all: lia.\n  * destruct IHeval_expr1. destruct IHeval_expr2.\n    epose (P := fbs_expr_list_soundness H5 _ _ _). destruct P.\n    apply bigger_clock_expr with (clock' := x + x0 + x1) in H9.\n    apply bigger_clock_expr with (clock' := x + x0 + x1) in H10.\n    apply bigger_clock_list with (clock' := x + x0 + x1) in H11.\n    exists (S (x + x0 + x1)).\n    simpl. rewrite H9. rewrite H10. rewrite H11. subst.\n    2,4,5: lia.\n    - destruct v. 1,3,4,5,6: auto.\n      destruct l. \n      -- congruence.\n      -- auto.\n    - intros. apply clock_increase_expr. auto.\n\n  * destruct IHeval_expr1. destruct IHeval_expr2.\n    epose (P := fbs_expr_list_soundness H5 _ _ _). destruct P.\n    apply bigger_clock_expr with (clock' := x + x0 + x1) in H9.\n    apply bigger_clock_expr with (clock' := x + x0 + x1) in H10.\n    apply bigger_clock_list with (clock' := x + x0 + x1) in H11.\n    exists (S (x + x0 + x1)).\n    simpl. rewrite H9. rewrite H10. rewrite H11. subst.\n    2,4,5: lia.\n    - destruct v'. 1,3,4,5,6: auto.\n      destruct l. \n      -- congruence. \n      -- auto.\n    - intros. apply clock_increase_expr. auto.\n\n  * epose (P := fbs_expr_list_soundness_exception H4 IHeval_expr _ _ _ _). \n    destruct P. exists (S x). simpl. rewrite H6. auto.\n  * destruct IHeval_expr. exists (S x). simpl. rewrite H0. auto.\n  * destruct IHeval_expr1.\n    epose (P := fbs_expr_list_soundness_exception H5 IHeval_expr2 _ _ _ _).\n    destruct P. exists (S (x + x0)). simpl.\n    apply bigger_clock_expr with (clock' := x + x0) in H7.\n    apply bigger_clock_list with (clock' := x + x0) in H8.\n    rewrite H7, H8. auto.\n    1,3: lia. intros. apply clock_increase_expr. auto.\n  * destruct IHeval_expr.\n    epose (P := fbs_expr_list_soundness H4 _ _ _). destruct P.\n    exists (S (x + x0)). simpl.\n    apply bigger_clock_expr with (clock' := x + x0) in H8.\n    apply bigger_clock_list with (clock' := x + x0) in H9.\n    rewrite H8, H9. destruct v; try congruence.\n    1-5: rewrite H6, H7; auto.\n    1,3: lia.\n    intros. apply clock_increase_expr. auto.\n  * destruct IHeval_expr.\n    epose (P := fbs_expr_list_soundness H4 _ _ _). destruct P.\n    exists (S (x + x0)). simpl.\n    apply bigger_clock_expr with (clock' := x + x0) in H8.\n    apply bigger_clock_list with (clock' := x + x0) in H9.\n    rewrite H8, H9.\n    apply Nat.eqb_neq in H5. rewrite H5. rewrite H6, H7. auto.\n    1,3: lia.\n    intros. apply clock_increase_expr. auto.\n  * destruct IHeval_expr. exists (S x). simpl. rewrite H0. auto.\n  * destruct IHeval_expr. exists (S x). simpl. rewrite H0. auto.\n  * epose (P := fbs_expr_list_soundness_exception H5 IHeval_expr _ _ _ _).\n    destruct P. exists (S x). simpl. unfold exps in H7.\n    rewrite H7. auto.\n  Unshelve.\n  all: auto.\n  - unfold exps, vals. rewrite length_make_map_exps, length_make_map_vals. lia. lia.\n  - unfold exps. rewrite length_make_map_exps. auto.\n  - unfold exps. rewrite length_make_map_exps. auto.\n  - unfold exps. rewrite length_make_map_exps. lia.\n  - unfold vals. case_eq (modulo_2 (i)); intros.\n    + rewrite e in H1. rewrite length_make_map_vals.\n      pose (n_div_2_mod_0 _ e). rewrite e0. lia. lia.\n    + rewrite e in H1. rewrite length_make_map_vals2.\n      pose (n_div_2_mod_1 _ e). rewrite e0. lia. lia.\nQed.\n\nEnd Soundness.\n\n\nSection Correctness.\n\nLemma list_expr_correct :\nforall {l env modules own_module id eff id' vl eff' clock},\nfbs_values (fbs_expr clock) env own_module modules id l eff = Result id' (inl vl) eff'\n->\n(\nexists idl effl, \n  length l = length vl /\\\n  length l = length idl /\\\n  length l = length effl /\\\n  eff' = last effl eff /\\\n  id' = last idl id /\\\n  (forall i, i < length l ->\n    fbs_expr clock env own_module modules (nth_def idl id 0 i) (nth i l ErrorExp) (nth_def effl eff [] i) =\n      Result (nth_def idl id 0 (S i)) (inl [nth i vl ErrorValue]) (nth_def effl eff [] (S i))\n  )\n)\n.\nProof.\n  induction l; intros.\n  * inversion H. subst. exists []. exists [].\n    repeat (split; auto).\n    intros. inversion H0.\n  * simpl in H.\n    case_eq (fbs_expr clock env own_module modules id a eff); intros. destruct res.\n    - rewrite H0 in H.\n      destruct v. congruence. destruct v0. 2: congruence.\n      case_eq (fbs_values (fbs_expr clock) env own_module modules id0 l eff0); intros. destruct res.\n         + rewrite H1 in H. inversion H. subst.\n           pose (IHl _ _ _ _ _ _ _ _ _ H1). inversion e. inversion H2.\n           destruct H3, H4, H5, H6, H7.\n           exists (id0 :: x). exists (eff0 :: x0).\n           split. 2: split. 3: split. 4: split. 5: split.\n           1-3 : simpl; lia.\n           ** rewrite last_element_equal with (def2 := eff) in H6. auto.\n           ** rewrite last_element_equal with (def2 := id) in H7. auto.\n           ** intros. destruct i.\n             -- simpl. assumption.\n             -- simpl in H9. \n                (* setoid failure for simple rewrite *)\n                assert (i < length l). { lia. }\n                apply H8. assumption.\n         + rewrite H1 in H. discriminate.\n         + rewrite H1 in H. discriminate.\n         + rewrite H1 in H. discriminate.\n    - rewrite H0 in H. discriminate.\n    - rewrite H0 in H. discriminate.\n    - rewrite H0 in H. discriminate.\nQed.\n\nLemma list_expr_exception_correct :\nforall {l : list Expression} {env modules own_module id eff id' ex eff' clock},\nfbs_values (fbs_expr clock) env modules own_module id l eff = Result id' (inr ex) eff'\n->\n(\nexists vals idl effl, \n  length vals < length l /\\\n  length vals = length idl /\\\n  length vals = length effl /\\\n  (forall i, i < length vals ->\n    fbs_expr clock env modules own_module (nth_def idl id 0 i) (nth i l ErrorExp) (nth_def effl eff [] i) =\n      Result (nth_def idl id 0 (S i)) (inl [nth i vals ErrorValue]) (nth_def effl eff [] (S i))\n  ) /\\\n  fbs_expr clock env modules own_module (last idl id) (nth (length vals) l ErrorExp) (last effl eff) = Result id' (inr ex) eff'\n)\n.\nProof.\n  induction l; intros.\n  * inversion H.\n  * simpl in H.\n    case_eq (fbs_expr clock env modules own_module id a eff); intros. destruct res.\n    - rewrite H0 in H. destruct v. congruence. destruct v0. 2: congruence.\n      case_eq (fbs_values (fbs_expr clock) env modules own_module id0 l eff0); intros. destruct res.\n         + rewrite H1 in H. inversion H.\n         + rewrite H1 in H. inversion H. subst.\n           pose (IHl env modules own_module id0 eff0 id' ex eff' clock H1).\n           destruct e. destruct H2, H2.\n           destruct H2, H3, H4, H5.\n           exists (v::x). exists (id0::x0). exists (eff0::x1).\n           split. 2: split. 3: split. 4: split.\n           all: try (simpl; lia).\n           ** intros. destruct i.\n             -- simpl. assumption.\n             -- apply H5. simpl in H7. lia.\n           ** rewrite last_element_equal with (def2 := id) in H6.\n              rewrite last_element_equal with (def2 := eff) in H6.\n              assumption.\n         + rewrite H1 in H. congruence.\n         + rewrite H1 in H. congruence.\n    - rewrite H0 in H. inversion H. subst.\n      exists []. exists []. exists [].\n      split. 2: split. 3: split. 4: split.\n      all: auto.\n      + simpl. lia.\n      + intros. inversion H1. \n    - rewrite H0 in H. discriminate.\n    - rewrite H0 in H. discriminate.\nQed.\n(* \nLemma list_single_correct :\nforall {l env id eff id' vl eff' clock},\nfbs_values (fbs_single clock) env id l eff = Result id' (inl vl) eff'\n->\n(\nexists idl effl, \n  length l = length vl /\\\n  length l = length idl /\\\n  length l = length effl /\\\n  eff' = last effl eff /\\\n  id' = last idl id /\\\n  (forall i, i < length l ->\n    fbs_single clock env (nth_def idl id 0 i) (nth i l ErrorExp) (nth_def effl eff [] i) =\n      Result (nth_def idl id 0 (S i)) (inl [nth i vl ErrorValue]) (nth_def effl eff [] (S i))\n  )\n)\n.\nProof.\n  induction l; intros.\n  * inversion H. subst. exists []. exists [].\n    repeat (split; auto).\n    intros. inversion H0.\n  * simpl in H.\n    case_eq (fbs_single clock env id a eff); intros. destruct res.\n    - rewrite H0 in H.\n      destruct v. congruence. destruct v0. 2: congruence.\n      case_eq (fbs_values (fbs_single clock) env id0 l eff0); intros. destruct res.\n         + rewrite H1 in H. inversion H. subst.\n           pose (IHl _ _ _ _ _ _ _ H1). inversion e. inversion H2.\n           destruct H3, H4, H5, H6, H7.\n           exists (id0 :: x). exists (eff0 :: x0).\n           split. 2: split. 3: split. 4: split. 5: split.\n           1-3 : simpl; lia.\n           ** rewrite last_element_equal with (def2 := eff) in H6. auto.\n           ** rewrite last_element_equal with (def2 := id) in H7. auto.\n           ** intros. destruct i.\n             -- simpl. assumption.\n             -- simpl in H9. \n                (* setoid failure for simple rewrite *)\n                assert (i < length l). { lia. }\n                apply H8. assumption.\n         + rewrite H1 in H. discriminate.\n         + rewrite H1 in H. discriminate.\n         + rewrite H1 in H. discriminate.\n    - rewrite H0 in H. discriminate.\n    - rewrite H0 in H. discriminate.\n    - rewrite H0 in H. discriminate.\nQed. *)\n\nLemma case_correctness l env modules own_module id0 eff0 v clock id' res eff' :\n  fbs_case l env modules own_module id0 eff0 v  (fbs_expr clock) = Result id' res eff'\n->\n  (exists i guard exp bindings, i < length l /\\\n    match_clause v l i = Some (guard, exp, bindings) /\\\n    (forall j : nat, j < i -> \n      (forall gg ee bb, match_clause v l j = Some (gg, ee, bb) -> \n        (fbs_expr clock (add_bindings bb env) modules own_module id0 gg eff0 = Result id0 (inl [ffalse]) eff0 )\n      )\n\n    ) /\\\n    fbs_expr clock (add_bindings bindings env) modules own_module id0 guard eff0 = Result id0 (inl [ttrue]) eff0 /\\\n    fbs_expr clock (add_bindings bindings env) modules own_module id0 exp eff0 = Result id' res eff')\n\\/\n  ((forall j : nat, j < length l -> \n      (forall gg ee bb, match_clause v l j = Some (gg, ee, bb) -> \n        (fbs_expr clock (add_bindings bb env) modules own_module id0 gg eff0 = Result id0 (inl [ffalse]) eff0 )))\n  /\\\n  res = inr if_clause /\\ id' = id0 /\\ eff' = eff0\n  )\n.\nProof.\n  induction l; intros.\n  * simpl in H. inversion H. subst.\n    right. split. 2: auto. intros. inversion H0.\n  * simpl in H. destruct a, p.\n    case_eq (match_valuelist_to_patternlist v l0); intros; rewrite H0 in H.\n    - case_eq (fbs_expr clock (add_bindings (match_valuelist_bind_patternlist v l0) env)\n        modules own_module id0 e0 eff0); intros; rewrite H1 in H.\n      + destruct res0. 2: congruence. destruct v0. congruence. destruct v1. 2: congruence.\n        case_eq (((id =? id0) && list_eqb effect_eqb eff0 eff)%bool); intros; rewrite H2 in H. 2: congruence.\n        destruct v0; try congruence.\n        destruct l1; try congruence.\n        case_eq ((s =? \"true\")%string); intros; rewrite H3 in H.\n        ** rewrite eqb_eq in H3. apply eq_sym, Bool.andb_true_eq in H2. destruct H2.\n           symmetry in H2, H4. rewrite Nat.eqb_eq in H2.\n           apply effect_list_eqb_eq in H4. subst.\n           left. exists 0, e0, e, (match_valuelist_bind_patternlist v l0).\n           split. 2: split. 3: split. 4: split.\n           -- simpl. lia.\n           -- simpl. rewrite H0. auto.\n           -- intros. inversion H2.\n           -- auto.\n           -- auto.\n        ** case_eq ((s =? \"false\")%string); intros; rewrite H4 in H. 2: congruence.\n           rewrite eqb_eq in H4. subst.\n           pose (P := IHl H). destruct P.\n           -- destruct H4, H4, H4, H4, H4, H5, H6, H7.\n              left. exists (S x), x0, x1, x2.\n              split. 2: split. 3: split. 4: split.\n              all: auto.\n              ++ simpl. lia.\n              ++ intros. destruct j.\n                 *** subst. simpl in H10. rewrite H0 in H10. inversion H10. subst.\n                     unfold ffalse.\n                     apply eq_sym, Bool.andb_true_eq in H2. destruct H2.\n                     symmetry in H2, H11. rewrite Nat.eqb_eq in H2.\n                     apply effect_list_eqb_eq in H11. subst. exact H1.\n                 *** apply Nat.succ_lt_mono in H9.\n                     simpl in H10.\n                     pose (P := H6 j H9 _ _ _ H10). auto.\n          -- right. destruct H4, H5, H6. subst. split. 2: split. 3: split.\n             all: auto.\n             ++ intros. destruct j.\n                *** subst. simpl in H6. rewrite H0 in H6. inversion H6. subst.\n                    apply eq_sym, Bool.andb_true_eq in H2. destruct H2.\n                    symmetry in H2, H7. rewrite Nat.eqb_eq in H2.\n                    apply effect_list_eqb_eq in H7. subst. exact H1.\n                *** simpl in H5. apply Nat.succ_lt_mono in H5.\n                     simpl in H6.\n                     pose (P := H4 j H5 _ _ _ H6). auto.\n      + congruence.\n      + congruence.\n    - pose (P := IHl H). destruct P.\n      + destruct H1, H1, H1, H1, H1, H2, H3, H4.\n        left. exists (S x), x0, x1, x2.\n        split. 2: split. 3: split. 4: split.\n        all: auto.\n        ** simpl. lia.\n        ** intros. destruct j.\n           -- subst. simpl in H7. rewrite H0 in H7. congruence.\n           -- apply Nat.succ_lt_mono in H6.\n              simpl in H7.\n              pose (P := H3 j H6 _ _ _ H7). auto.\n     + right. destruct H1, H2, H3. subst. split. 2: split. 3: split.\n       all: auto.\n       ** intros. destruct j.\n          -- subst. simpl in H3. rewrite H0 in H3. congruence.\n          -- simpl in H2. apply Nat.succ_lt_mono in H2.\n             simpl in H3.\n             pose (P := H1 j H2 _ _ _ H3). auto.\nQed.\n(* \nLemma list_single_exception_correct :\nforall {l : list SingleExpression} {env id eff id' ex eff' clock},\nfbs_values (fbs_single clock) env id l eff = Result id' (inr ex) eff'\n->\n(\nexists vals idl effl, \n  length vals < length l /\\\n  length vals = length idl /\\\n  length vals = length effl /\\\n  (forall i, i < length vals ->\n    fbs_single clock env (nth_def idl id 0 i) (nth i l ErrorExp) (nth_def effl eff [] i) =\n      Result (nth_def idl id 0 (S i)) (inl [nth i vals ErrorValue]) (nth_def effl eff [] (S i))\n  ) /\\\n  fbs_single clock env (last idl id) (nth (length vals) l ErrorExp) (last effl eff) = Result id' (inr ex) eff'\n)\n.\nProof.\n  induction l; intros.\n  * inversion H.\n  * simpl in H.\n    case_eq (fbs_single clock env id a eff); intros. destruct res.\n    - rewrite H0 in H. destruct v. congruence. destruct v0. 2: congruence.\n      case_eq (fbs_values (fbs_single clock) env id0 l eff0); intros. destruct res.\n         + rewrite H1 in H. inversion H.\n         + rewrite H1 in H. inversion H. subst.\n           pose (IHl env id0 eff0 id' ex eff' clock H1).\n           destruct e. destruct H2, H2.\n           destruct H2, H3, H4, H5.\n           exists (v::x). exists (id0::x0). exists (eff0::x1).\n           split. 2: split. 3: split. 4: split.\n           all: try (simpl; lia).\n           ** intros. destruct i.\n             -- simpl. assumption.\n             -- apply H5. simpl in H7. lia.\n           ** rewrite last_element_equal with (def2 := id) in H6.\n              rewrite last_element_equal with (def2 := eff) in H6.\n              assumption.\n         + rewrite H1 in H. congruence.\n         + rewrite H1 in H. congruence.\n    - rewrite H0 in H. inversion H. subst.\n      exists []. exists []. exists [].\n      split. 2: split. 3: split. 4: split.\n      all: auto.\n      + simpl. lia.\n      + intros. inversion H1. \n    - rewrite H0 in H. discriminate.\n    - rewrite H0 in H. discriminate.\nQed. *)\n\nTheorem fbs_expr_correctness :\n(forall clock {env modules own_module id exp eff id' res eff'},\n  fbs_expr clock env modules own_module id exp eff = Result id' res eff'\n ->\n  | env, modules, own_module, id, exp, eff| -e> | id', res, eff' |)\n(* with fbs_single_correctness :\n(forall clock {env id exp eff id' res eff'},\n  fbs_single clock env [] id exp eff = Result id' res eff'\n ->\n  | env, id, exp, eff| -s> | id', res, eff' |) *).\nProof.\n  induction clock; intros.\n  * inversion H.\n  * destruct exp; simpl in H.\n    - destruct res.\n      + apply list_expr_correct in H.  destruct H, H, H, H0, H1, H2, H3. \n      (* CONTINUE *)\n        eapply eval_values with (vals := v) (eff := x0) (ids := x); auto. (* intros.\n        eapply IHclock in H4. exact H4. exact H5. *)  \n      + apply list_expr_exception_correct in H. destruct H, H, H, H, H0, H1, H2.\n        eapply eval_values_ex with (vals := x) (eff := x1) (ids := x0); auto. auto.\n        (*intros. eapply IHclock in H2. exact H2. exact H4. eapply IHclock in H3. exact H3. *)\n    - inversion H. apply eval_nil.\n    - inversion H. apply eval_lit.\n    - case_eq (get_value env (inl v)); intros; rewrite H0 in H.\n      2: congruence. inversion H. apply eval_var. auto.\n    - case_eq (get_value env (inr f)).\n      + intros. rewrite H0 in H.\n        inversion H. apply eval_funid. auto.\n      + intros. rewrite H0 in H. destruct get_own_modfunc eqn:MOD.\n        ++ inversion H. eapply eval_funid_module. all: auto. exact MOD.\n        ++ congruence.\n    - inversion H. apply eval_fun.\n    - case_eq (fbs_expr clock env modules own_module id exp2 eff); intros; rewrite H0 in H.\n      destruct res0. destruct v. congruence. destruct v0. 2: congruence.\n      + apply IHclock in H0.\n        case_eq (fbs_expr clock env modules own_module id0 exp1 eff0); intros; rewrite H1 in H.\n        destruct res0. destruct v0. congruence. destruct v1. 2: congruence.\n        ** apply IHclock in H1. inversion H. subst.\n           eapply eval_cons. exact H0. exact H1.\n        ** apply IHclock in H1. inversion H. subst.\n           eapply eval_cons_hd_ex. exact H0. exact H1.\n        ** congruence.\n        ** congruence.\n      + eapply IHclock in H0. inversion H. subst.\n        eapply eval_cons_tl_ex. exact H0.\n      + congruence.\n      + congruence.\n    - case_eq (fbs_values (fbs_expr clock) env modules own_module id l eff); intros; rewrite H0 in H.\n      destruct res0.\n      + apply list_expr_correct in H0. destruct H0, H0, H0, H1, H2, H3, H4.\n        inversion H. subst.\n        eapply eval_tuple with (vals := v) (eff := x0) (ids := x); auto.\n        (*intros. eapply IHclock in H5. exact H5. exact H3.*)\n      + apply list_expr_exception_correct in H0. destruct H0, H0, H0, H0, H1, H2, H3.\n        inversion H. subst.\n        eapply eval_tuple_ex with (vals := x) (eff := x1) (ids := x0); auto. auto.\n        (*intros. eapply IHclock in H3. exact H3. exact H5. eapply IHclock in H4. exact H4. *)\n      + congruence.\n      + congruence.\n    - case_eq (fbs_expr clock env modules own_module id exp1 eff).\n        -- intros. rewrite H0 in H. destruct res0.\n          --- destruct v; try congruence.\n              destruct v0; try congruence.\n              case_eq (fbs_expr clock env modules own_module id0 exp2 eff0 ).\n                + intros. rewrite H1 in H.\n                  destruct res0.\n                  ++ destruct v0; try congruence.\n                    destruct v1; try congruence.\n                    case_eq (fbs_values (fbs_expr clock) env modules own_module id1 l eff1).\n                        ** intros. rewrite H2 in H.\n                          destruct res0.\n                          *** destruct v. \n                            **** apply IHclock in H0, H1. inversion H. subst.\n                                  apply list_expr_correct in H2.\n                                  destruct H2, H2, H2, H3, H4, H5, H6.\n                                  eapply eval_call_mexp_badarg_ex with\n                                  (params:= l) (fexp:= exp2) (vals:=v1) (eff:=x0) (ids:=x) (id''':= id') (eff4:= eff'); auto.\n                                  exact H0. exact H1. congruence.\n                            **** destruct l0.\n                              ***** destruct v0.\n                                ****** apply IHclock in H0, H1. inversion H. subst.\n                                        apply list_expr_correct in H2.\n                                        destruct H2, H2, H2, H3, H4, H5, H6.\n                                        eapply eval_call_fexp_badarg_ex with\n                                        (params:= l) (fexp:= exp2) (vals:=v1) (eff:=x0) (ids:=x) (id''':= id') (eff4:= eff');  auto.\n                                        exact H0. exact H1. congruence.   \n                                ****** destruct l0. \n                                  ******* destruct get_modfunc eqn:MOD. \n                                          ********  apply IHclock in H0, H1, H.\n                                                    apply list_expr_correct in H2.\n                                                    destruct H2, H2, H2, H3, H4, H5, H6.\n                                                    rewrite H5, H6 in H.\n                                                    eapply eval_call_module with (vals := v1) (eff := x0) (ids := x); auto.\n                                                    exact H0. exact H1.\n                                                    exact MOD. exact H.\n                                          ********  apply IHclock in H0, H1. inversion H. subst.\n                                                    apply list_expr_correct in H2.\n                                                    destruct H2, H2, H2, H3, H4, H5, H6.\n                                                    eapply eval_call with (vals := v1) (eff := x0) (ids := x); auto.\n                                                    exact H0. exact H1. auto.\n                                                    rewrite <- surjective_pairing.\n                                                    rewrite H5. auto. \n                                  ******* apply IHclock in H0, H1. inversion H. subst.\n                                          apply list_expr_correct in H2.\n                                          destruct H2, H2, H2, H3, H4, H5, H6.\n                                          eapply eval_call_fexp_badarg_ex with\n                                          (params:= l) (fexp:= exp2) (vals:=v1) (eff:=x1) (ids:=x0) (id''':= id') (eff4:= eff');  auto.\n                                          exact H0. exact H1. congruence.\n                                ****** apply IHclock in H0, H1. inversion H. subst.\n                                        apply list_expr_correct in H2.\n                                        destruct H2, H2, H2, H3, H4, H5, H6.\n                                        eapply eval_call_fexp_badarg_ex with\n                                        (params:= l) (fexp:= exp2) (vals:=v1) (eff:=x0) (ids:=x) (id''':= id') (eff4:= eff');  auto.\n                                        exact H0. exact H1. congruence.\n                                ****** apply IHclock in H0, H1. inversion H. subst.\n                                        apply list_expr_correct in H2.\n                                        destruct H2, H2, H2, H3, H4, H5, H6.\n                                        eapply eval_call_fexp_badarg_ex with\n                                        (params:= l) (fexp:= exp2) (vals:=v1) (eff:=x0) (ids:=x) (id''':= id') (eff4:= eff');  auto.\n                                        exact H0. exact H1. congruence.\n                                ****** apply IHclock in H0, H1. inversion H. subst.\n                                        apply list_expr_correct in H2.\n                                        destruct H2, H2, H2, H3, H4, H5, H6.\n                                        eapply eval_call_fexp_badarg_ex with\n                                        (params:= l) (fexp:= exp2) (vals:=v1) (eff:=x0) (ids:=x) (id''':= id') (eff4:= eff');  auto.\n                                        exact H0. exact H1. congruence.\n                                ****** apply IHclock in H0, H1. inversion H. subst.\n                                        apply list_expr_correct in H2.\n                                        destruct H2, H2, H2, H3, H4, H5, H6.\n                                        eapply eval_call_fexp_badarg_ex with\n                                        (params:= l) (fexp:= exp2) (vals:=v1) (eff:=x0) (ids:=x) (id''':= id') (eff4:= eff');  auto.\n                                        exact H0. exact H1. congruence.\n                              ***** apply IHclock in H0, H1. inversion H. subst.\n                                    apply list_expr_correct in H2.\n                                    destruct H2, H2, H2, H3, H4, H5, H6.\n                                    eapply eval_call_mexp_badarg_ex with\n                                    (params:= l) (fexp:= exp2) (vals:=v1) (eff:=x1) (ids:=x0) (id''':= id') (eff4:= eff'); auto.\n                                    exact H0. exact H1. congruence.\n                            **** apply IHclock in H0, H1. inversion H. subst.\n                                  apply list_expr_correct in H2.\n                                  destruct H2, H2, H2, H3, H4, H5, H6.\n                                  eapply eval_call_mexp_badarg_ex with\n                                  (params:= l) (fexp:= exp2) (vals:=v1) (eff:=x0) (ids:=x) (id''':= id') (eff4:= eff'); auto.\n                                  exact H0. exact H1. congruence.\n                            **** apply IHclock in H0, H1. inversion H. subst.\n                                  apply list_expr_correct in H2.\n                                  destruct H2, H2, H2, H3, H4, H5, H6.\n                                  eapply eval_call_mexp_badarg_ex with\n                                  (params:= l) (fexp:= exp2) (vals:=v1) (eff:=x0) (ids:=x) (id''':= id') (eff4:= eff'); auto.\n                                  exact H0. exact H1. congruence.\n                            **** apply IHclock in H0, H1. inversion H. subst.\n                                  apply list_expr_correct in H2.\n                                  destruct H2, H2, H2, H3, H4, H5, H6.\n                                  eapply eval_call_mexp_badarg_ex with\n                                  (params:= l) (fexp:= exp2) (vals:=v1) (eff:=x0) (ids:=x) (id''':= id') (eff4:= eff'); auto.\n                                  exact H0. exact H1. congruence.\n                            **** apply IHclock in H0, H1. inversion H. subst.\n                                  apply list_expr_correct in H2.\n                                  destruct H2, H2, H2, H3, H4, H5, H6.\n                                  eapply eval_call_mexp_badarg_ex with\n                                  (params:= l) (fexp:= exp2) (vals:=v1) (eff:=x0) (ids:=x) (id''':= id') (eff4:= eff'); auto.\n                                  exact H0. exact H1. congruence.\n                          *** apply IHclock in H0, H1. inversion H. subst.\n                              apply list_expr_exception_correct in H2.\n                              destruct H2, H2, H2, H2, H3, H4, H5.\n                              eapply eval_call_ex with (vals := x) (eff := x1) (ids := x0); auto.\n                              auto. exact H0. exact H1.\n\n                        ** intros; rewrite H2 in H; congruence.\n                        ** intros; rewrite H2 in H; congruence.\n                  ++ apply IHclock in H0, H1. inversion H. subst.\n                       eapply eval_call_fexp_ex. exact H0. exact H1.\n                + intros. rewrite H1 in H. congruence.\n                + intros. rewrite H1 in H. congruence. \n            \n          --- apply IHclock in H0. inversion H. subst.\n              eapply eval_call_mexp_ex with (params:= l) (fexp:= exp2)  in H0. auto.\n        -- intros. rewrite H0 in H. congruence.\n        -- intros. rewrite H0 in H. congruence. \n        \n    (*TODO: !!!!!!!!!!!!!!!!!!!!*)\n\n      (*+ apply IHclock in H0. apply IHclock in H1.\n      case_eq (fbs_values (fbs_expr clock) env [] id l eff); intros. *)\n        \n    (*case_eq (fbs_values (fbs_expr clock) env [] id l eff); intros; rewrite H0 in H.\n      destruct res0.\n      + apply list_expr_correct in H0. destruct H0, H0, H0, H1, H2, H3, H4.\n        inversion H. subst.\n        eapply eval_call with (vals := v) (eff := x0) (ids := x); auto.\n        (*intros. eapply IHclock in H5. exact H5. exact H3.  *)\n        ** rewrite <- surjective_pairing. auto.\n      + apply list_expr_exception_correct in H0. destruct H0, H0, H0, H0, H1, H2, H3.\n        inversion H. subst.\n        eapply eval_call_ex with (vals := x) (eff := x1) (ids := x0); auto. auto.\n        (*intros. eapply IHclock in H3. exact H3. exact H5. eapply IHclock in H4. exact H4. *)\n      + congruence.\n      + congruence.*)\n    - case_eq (fbs_values (fbs_expr clock) env modules own_module id l eff); intros; rewrite H0 in H.\n      destruct res0.\n      + apply list_expr_correct in H0. destruct H0, H0, H0, H1, H2, H3, H4.\n        inversion H. subst.\n        eapply eval_primop with (vals := v) (eff := x0) (ids := x); auto.\n        (*intros. eapply IHclock in H5. exact H5. exact H3.*)\n        ** rewrite <- surjective_pairing. auto.\n      + apply list_expr_exception_correct in H0. destruct H0, H0, H0, H0, H1, H2, H3.\n        inversion H. subst.\n        eapply eval_primop_ex with (vals := x) (eff := x1) (ids := x0); auto. auto.\n        (*intros. eapply IHclock in H3. exact H3. exact H5. eapply IHclock in H4. exact H4. *)\n      + congruence.\n      + congruence.\n    - case_eq (fbs_expr clock env modules own_module id exp eff); intros; rewrite H0 in H.\n      destruct res0. destruct v. congruence. destruct v0. 2: congruence.\n      + apply IHclock in H0.\n        case_eq (fbs_values (fbs_expr clock) env modules own_module id0 l eff0); intros; rewrite H1 in H.\n        destruct res0; try (apply list_expr_correct in H1; destruct H1, H1, H1, H2, H3, H4, H5).\n        ** destruct v; inversion H; subst.\n          -- eapply eval_app_badfun_ex with (vals := v0) (eff := x0) (ids := x);auto.\n              auto. (*exact H0. intros. eapply IHclock in H6. exact H6. exact H4.*)\n              intros; try (pose (P := H6 j H4); apply fbs_expr_correctness in P; exact P). \n              congruence.\n          -- eapply eval_app_badfun_ex with (vals := v0) (eff := x0) (ids := x);auto.\n              auto. (*exact H0. intros. eapply IHclock in H6. exact H6. exact H4.*)\n              intros; try (pose (P := H6 j H4); apply fbs_expr_correctness in P; exact P).\n              congruence.\n          -- case_eq (Datatypes.length vl =? Datatypes.length v0); intros; rewrite H4 in *.\n            ++ apply Nat.eqb_eq in H4.\n              eapply eval_app with (vals := v0) (eff := x0) (ids := x); auto.\n              *** exact H0.\n              *** auto.\n              (****  intros. eapply IHclock in H6. exact H6. exact H5.*)\n              *** apply IHclock in H8. exact H8.  \n            ++ apply Nat.eqb_neq in H4. inversion H. subst.\n              eapply eval_app_badarity_ex with (vals := v0) (eff := x0) (ids := x); auto.\n              *** exact H0.\n              (**** intros. eapply IHclock in H6. exact H6. auto.*)\n \n          -- eapply eval_app_badfun_ex with (vals := v0) (eff := x0) (ids := x);auto.\n              (*exact H0. intros. eapply IHclock in H6. exact H6. exact H4.*)\n              intros; try (pose (P := H6 j H4); apply fbs_expr_correctness in P; exact P).\n              auto.\n              congruence.\n          -- eapply eval_app_badfun_ex with (vals := v0) (eff := x0) (ids := x);auto.\n              (*exact H0. intros. eapply IHclock in H6. exact H6. exact H4.*)\n              intros; try (pose (P := H6 j H4); apply fbs_expr_correctness in P; exact P).\n              auto.\n              congruence.\n          -- eapply eval_app_badfun_ex with (vals := v0) (eff := x0) (ids := x);auto.\n          (*exact H0. intros. eapply IHclock in H6. exact H6. exact H4.*)\n          intros; try (pose (P := H6 j H4); apply fbs_expr_correctness in P; exact P).\n          auto.\n          congruence.\n          \n         \n    (* 1-2, 4-6: eapply eval_app_badfun_ex with (vals := v0) (eff := x0) (ids := x);auto.\n          -- exact H0. intros. eapply IHclock in H6. exact H6. exact H4.\n          intros; try (pose (P := H6 j H4); apply fbs_expr_correctness in P; exact P).\n          congruence.\n          -- case_eq (Datatypes.length vl =? Datatypes.length v0); intros; rewrite H4 in *.\n             ++ apply Nat.eqb_eq in H4.\n                eapply eval_app with (vals := v0) (eff := x0) (ids := x); auto.\n                *** exact H0.\n                *** auto.\n                *** apply IHclock in H8. auto.\n             ++ apply Nat.eqb_neq in H4. inversion H. subst.\n                eapply eval_app_badarity_ex with (vals := v0) (eff := x0) (ids := x); auto.\n                *** exact H0.*)\n        ** apply list_expr_exception_correct in H1. destruct H1, H1, H1, H1, H2, H3, H4.\n           apply IHclock in H5. inversion H. subst.\n           eapply eval_app_param_ex with (vals := x) (eff := x1) (ids := x0); auto.\n           *** exact H1.\n           *** exact H0.\n           (**** intros. eapply IHclock in H4. exact H4. exact H6.\n           *** exact H5.*)\n        ** congruence.\n        ** congruence.\n      + apply IHclock in H0. inversion H. subst.\n        eapply eval_app_closure_ex. auto.\n      + congruence.\n      + congruence.\n    - case_eq (fbs_expr clock env modules own_module id exp eff); intros; rewrite H0 in H.\n      destruct res0.\n      + apply IHclock in H0.\n        apply case_correctness in H. destruct H.\n        ** destruct H, H, H, H, H, H1, H2, H3.\n           eapply eval_case with (i := x).\n           -- exact H0.\n           -- auto.\n           -- exact H1.\n           -- intros. pose (P := H2 j H5 gg ee bb H6). apply IHclock in P. exact P.\n           -- apply IHclock in H3. auto.\n           -- apply IHclock in H4. auto.\n        ** destruct H, H1, H2. subst. eapply eval_case_clause_ex.\n           -- exact H0.\n           -- intros. pose (P := H j H1 gg ee bb H2). apply IHclock in P. auto.\n      + apply IHclock in H0. inversion H. subst.\n        apply eval_case_pat_ex. auto.\n      + congruence.\n      + congruence.\n    - case_eq (fbs_expr clock env modules own_module id exp1 eff); intros; rewrite H0 in H.\n      destruct res0.\n      + case_eq (Datatypes.length v =? Datatypes.length l); intros; rewrite H1 in H.\n        ** apply Nat.eqb_eq in H1. apply IHclock in H.\n           apply IHclock in H0.\n           eapply eval_let.\n           -- exact H0.\n           -- auto.\n           -- exact H.\n        ** congruence.\n      + inversion H. subst.\n        apply eval_let_ex. apply IHclock in H0. auto.\n      + congruence.\n      + congruence.\n    - case_eq (fbs_expr clock env modules own_module id exp1 eff); intros; rewrite H0 in H.\n      destruct res0. destruct v. congruence. destruct v0. 2: congruence.\n      + apply IHclock in H. apply IHclock in H0.\n        eapply eval_seq. exact H0. exact H.\n      + inversion H. subst.\n        apply eval_seq_ex. apply IHclock in H0. auto.\n      + congruence.\n      + congruence.\n    - eapply eval_letrec. apply IHclock in H. auto.\n    - case_eq (fbs_values (fbs_expr clock) env modules own_module id (make_map_exps l) eff); intros; rewrite H0 in H.\n      destruct res0.\n      + apply list_expr_correct in H0. destruct H0, H0, H0, H1, H2, H3, H4.\n        case_eq (make_map_vals_inverse v); intros; rewrite H6 in H. 2: congruence.\n        destruct p. inversion H. subst.\n        pose (P := make_map_inverse_length _ _ _ H6). destruct P.\n        eapply eval_map with (ids := x) (eff := x0) (kvals := l0) (vvals := l1); auto.\n        ** rewrite length_make_map_exps in H0. lia.\n        ** rewrite length_make_map_exps in H0. lia.\n        ** rewrite length_make_map_exps in H2. lia.\n        ** rewrite length_make_map_exps in H1. lia.\n        ** intros. pose (P := H5 i H7). apply IHclock in P.\n           apply make_map_inverse_relation in H6. subst. exact P.\n        ** apply surjective_pairing.\n     + apply list_expr_exception_correct in H0. destruct H0, H0, H0, H0, H1, H2, H3.\n        inversion H. subst.\n        apply IHclock in H4.\n        assert (exists kvals vvals, x = make_map_vals kvals vvals /\\ length kvals = length vvals + length x mod 2). { apply map_correcness. }\n        destruct H5, H5, H5.\n        eapply eval_map_ex with (ids := x0) (eff := x1) (kvals := x2) (vvals := x3); auto.\n        ** rewrite length_make_map_exps in H0. lia.\n        ** pose (modulo_2 (length x)). destruct o.\n           -- rewrite H7 in H6. rewrite Nat.add_0_r in H6. pose (length_make_map_vals _ _ H6).\n              subst. rewrite H6 in e0. pose (n_div_2_mod_0 _ H7). rewrite <- H2. lia.\n           -- rewrite H7 in H6. rewrite Nat.add_1_r in H6. pose (length_make_map_vals2 _ _ H6).\n              subst. rewrite <- H2. pose (n_div_2_mod_1 _ H7). lia.\n        ** rewrite <- H2. pose (modulo_2 (length x)). destruct o.\n           -- rewrite H7 in *. rewrite Nat.add_0_r in *. pose (length_make_map_vals _ _ H6).\n              pose (n_div_2_mod_0 _ H7). subst. lia.\n           -- rewrite H7 in *. rewrite Nat.add_1_r in *. pose (length_make_map_vals2 _ _ H6).\n              pose (n_div_2_mod_1 _ H7). subst. lia.\n        ** lia.\n        ** intros. rewrite <- H2 in H7. pose (P := H3 j H7). rewrite <- H5. apply IHclock in P. auto.\n        ** rewrite <- H2. auto.\n      + congruence.\n      + congruence.\n    - case_eq (fbs_expr clock env modules own_module id exp1 eff); intros; rewrite H0 in H.\n      destruct res0.\n      + case_eq (Datatypes.length v =? Datatypes.length vl1); intros; rewrite H1 in H.\n        2: congruence.\n        apply Nat.eqb_eq in H1.\n        apply IHclock in H0. apply IHclock in H.\n        eapply eval_try.\n        *** exact H0.\n        *** auto.\n        *** exact H.\n      + apply IHclock in H0.\n        eapply eval_catch.\n        *** exact H0.\n        *** apply IHclock in H. exact H.\n      + congruence.\n      + congruence.\nQed. \n\nEnd Correctness.\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/BigStep/SemanticsEquivalence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.27307935275840983}}
{"text": "From caml5 Require Import\n  prelude.\nFrom caml5.lang Require Import\n  notations\n  proofmode.\nFrom caml5.std Require Export\n  mutex.\n\nRecord condition `{!heapGS Σ} {mutex_unboxed} {mutex : mutex Σ mutex_unboxed} {unboxed : bool} := {\n  condition_make : val ;\n  condition_wait : val ;\n  condition_signal : val ;\n  condition_broadcast : val ;\n\n  condition_inv : val → iProp Σ ;\n\n  condition_inv_persistent t :\n    Persistent (condition_inv t) ;\n\n  condition_make_spec :\n    {{{ True }}}\n      condition_make #()\n    {{{ t, RET t; condition_inv t }}} ;\n\n  condition_wait_spec t mtx P :\n    {{{ condition_inv t ∗ mutex.(mutex_inv) mtx P ∗ mutex.(mutex_locked) mtx ∗ P }}}\n      condition_wait t mtx\n    {{{ RET #(); mutex.(mutex_locked) mtx ∗ P }}} ;\n\n  condition_signal_spec t :\n    {{{ condition_inv t }}}\n      condition_signal t\n    {{{ RET #(); True }}} ;\n\n  condition_broadcast_spec t :\n    {{{ condition_inv t }}}\n      condition_broadcast t\n    {{{ RET #(); True }}} ;\n\n  condition_unboxed :\n    if unboxed then ∀ t,\n      condition_inv t -∗\n      ⌜val_is_unboxed t⌝\n    else\n      True ;\n}.\n#[global] Arguments condition _ {_ _} _ _ : assert.\n#[global] Arguments Build_condition {_ _ _ _} _ {_ _ _ _ _ _} _ _ _ _ _ : assert.\n#[global] Existing Instance condition_inv_persistent.\n\nSection condition.\n  Context `{!heapGS Σ} {mutex_unboxed} {mutex : mutex Σ mutex_unboxed} {unboxed} (condition : condition Σ mutex unboxed).\n\n  #[local] Definition condition_wait_until_aux (cond : val) : val :=\n    rec: \"condition_wait_until_aux\" \"t\" \"mtx\" :=\n      if: cond #() then #() else (\n        condition.(condition_wait) \"t\" \"mtx\" ;;\n        \"condition_wait_until_aux\" \"t\" \"mtx\"\n      ).\n  Definition condition_wait_until cond : val :=\n    λ: \"t\" \"mtx\",\n      condition_wait_until_aux cond \"t\" \"mtx\".\n\n  Definition condition_wait_while (cond : val) :=\n    condition_wait_until (λ: <>, ~ cond #()).\n\n  Lemma condition_wait_until_spec (cond : val) t mtx P Φ :\n    {{{\n      condition.(condition_inv) t ∗ mutex.(mutex_inv) mtx P ∗\n      mutex.(mutex_locked) mtx ∗ P ∗ Φ false ∗\n      {{{ mutex.(mutex_locked) mtx ∗ P ∗ Φ false }}}\n        cond #()\n      {{{ (b : bool), RET #b; mutex.(mutex_locked) mtx ∗ P ∗ Φ b }}}\n    }}}\n      condition_wait_until cond t mtx\n    {{{\n      RET #();\n      mutex.(mutex_locked) mtx ∗ P ∗ Φ true\n    }}}.\n  Proof.\n    iIntros \"%Ψ (#Hinv_t & #Hinv_mtx & Hlocked & HP & HΦ & #Hcond) HΨ\".\n    wp_rec. wp_pures.\n    iLöb as \"HLöb\".\n    wp_rec. wp_pures.\n    wp_apply (\"Hcond\" with \"[$]\"). iIntros \"%b (Hlocked & HP & HΦ)\".\n    destruct b; wp_pures.\n    { iApply \"HΨ\". iFrame. done. }\n    wp_apply (condition_wait_spec _  _ _ P with \"[$]\"). iIntros \"(Hlocked & HP)\".\n    wp_pures.\n    iApply (\"HLöb\" with \"[$] [$] [$] [$]\").\n  Qed.\n\n  Lemma condition_wait_while_spec (cond : val) t mtx P Φ :\n    {{{\n      condition.(condition_inv) t ∗ mutex.(mutex_inv) mtx P ∗\n      mutex.(mutex_locked) mtx ∗ P ∗ Φ true ∗\n      {{{ mutex.(mutex_locked) mtx ∗ P ∗ Φ true }}}\n        cond #()\n      {{{ (b : bool), RET #b; mutex.(mutex_locked) mtx ∗ P ∗ Φ b }}}\n    }}}\n      condition_wait_while cond t mtx\n    {{{\n      RET #();\n      mutex.(mutex_locked) mtx ∗ P ∗ Φ false\n    }}}.\n  Proof.\n    iIntros \"%Ψ (#Hinv_t & #Hinv_mtx & Hlocked & HP & HΦ & #Hcond) HΨ\".\n    wp_apply (condition_wait_until_spec _ _ _ P (λ b, Φ (negb b)) with \"[$Hlocked $HP $HΦ]\"); last done.\n    iFrame \"#\". clear. iIntros \"%Ψ !> (Hlocked & HP & HΦ) HΨ\".\n    wp_pures.\n    wp_apply (\"Hcond\" with \"[$]\"). iIntros \"%b (Hlocked & HP & HΦ)\".\n    destruct b; wp_pures; iApply \"HΨ\"; iFrame; done.\n  Qed.\nEnd condition.\n\n#[global] Opaque condition_wait_until.\n#[global] Opaque condition_wait_while.\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/condition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.272972523822548}}
{"text": "(** STG in COQ by Maciej Piróg, University of Wrocław, 2010 *)\n\n(** This library contains proofs of equivalence of semantics created\nby merging and splitting some rules of the DCPS semantics.\nIn the paper it is done a little different, since it was easier\n(but less readable) to do it in Coq before switching to an\nabstract machine. *)\n\nRequire Export Sem05.\n\n(** * Defunctionalized Continuation Passing Style Semantics 2 *)\n\nReserved Notation \"($ x $ a $ b $ g $ e $ s ^\\\\ c $ d $ h $ f )\"\n  (at level 70, no associativity).\n\nInductive DCPS2 : action -> heapB -> expr -> env -> vars -> stack ->\n  heapB -> expr -> env -> vars -> Prop :=\n\n| D2_Halt : forall Gamma w sigma ps,\n  ($ A $ Gamma $ w $ sigma $ ps $ nil ^\\\\ Gamma $ w $ sigma $ ps)\n\n| D2_Con : forall Gamma Delta C pi w sigma rho qs Ss,\n  ($ A $ Gamma $ Constr C pi $ sigma $ nil $ Ss ^\\\\ Delta $ w $ rho $ qs) ->\n  ($ E $ Gamma $ Constr C pi $ sigma $ nil $ Ss ^\\\\ Delta $ w $ rho $ qs)\n\n| D2_Accum : forall Gamma Delta x xm sigma_xm qn w rs sigma rho Ss,\n  xm <> nil ->\n  env_map sigma xm = Some sigma_xm ->\n  ($ E $ Gamma $ App x nil $ sigma $ sigma_xm ++ qn $ Ss ^\\\\ Delta $ w $ rho $ rs) ->\n  ($ E $ Gamma $ App x xm  $ sigma $ qn             $ Ss ^\\\\ Delta $ w $ rho $ rs)\n\n| D2_App1 : forall Gamma tau p x pn m e sigma ,\n  env_find sigma x = Some (Atom p) ->\n  Gamma p = Some (Lf_n m e, tau) ->\n  m > length pn ->\n  ($ E $ Gamma $ App x nil $ sigma $ pn $ nil ^\\\\ Gamma $ App x nil $ sigma $ pn)\n\n| D2_App2_5 : forall Gamma Delta m e x tau p pn w rs sigma rho Ss,\n  env_find sigma x = Some (Atom p) ->\n  Gamma p = Some (Lf_n m e, tau) ->\n  m <= length pn -> \n  ($ E $ Gamma $ e         $ zip_var_list m (firstn m pn) ++ shift m tau $ skipn m pn $ Ss ^\\\\ Delta $ w $ rho $ rs) ->\n  ($ E $ Gamma $ App x nil $ sigma                                          $ pn         $ Ss ^\\\\ Delta $ w $ rho $ rs)\n\n| D2A_App4 : forall Delta rho C xs p Theta w nu qs Ss,\n  ($ E $ setB Delta p (Lf_n 0 (Constr C xs), trim rho xs) $ Constr C xs $ rho $ nil $ Ss ^\\\\ Theta $ w $ nu $ qs) ->\n  ($ A $ Delta $ Constr C xs $ rho $ nil $ S_upd (Atom p) nil :: Ss ^\\\\ Theta $ w $ nu $ qs)\n\n| D2E_App4_5 : forall Gamma Theta x p w e tau sigma nu rs qs Ss,\n  env_find sigma x = Some (Atom p) -> \n  Gamma p = Some (Lf_u e, tau) ->\n  ($ E $ Gamma $ e         $ tau   $ nil $ S_upd (Atom p) rs :: Ss ^\\\\ Theta $ w $ nu $ qs) ->\n  ($ E $ Gamma $ App x nil $ sigma $ rs $ Ss ^\\\\ Theta $ w $ nu $ qs)\n\n| D2A_App5 : forall EA Delta Theta x p pn y q qk f n w sigma rho nu mu qs Ss,\n  env_find sigma x = Some (Atom p) ->\n  env_find rho y = Some (Atom q) ->\n  Delta q = Some (Lf_n n f, mu) ->\n  length qk < n ->\n  ($ E  $ 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 $ Ss    ^\\\\ Theta $ w $ nu $ qs) ->\n  ($ EA $ Delta $ App y nil $ rho $ qk $ S_upd (Atom p) pn :: Ss ^\\\\ Theta $ w $ nu $ qs)\n\n| D2_Let : forall Gamma Delta sigma rho lfs e w (ats : list nat) rs qs Ss,\n  length ats = length lfs ->\n  (forall a : nat, In a ats -> Gamma a = None) -> \n  ($ E $ 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 $ Ss\n    ^\\\\ Delta $ w $ rho $ qs) ->\n  ($ E $ Gamma $ Letrec lfs e $ sigma $ rs $ Ss ^\\\\ Delta $ w $ rho $ qs)\n\n| D2E_Case_of : forall Gamma Theta e als w rs qs sigma nu Ss,\n  ($ E $ Gamma $ e          $ sigma $ nil $ S_alt als sigma qs :: Ss ^\\\\ Theta $ w $ nu $ rs) ->\n  ($ E $ Gamma $ Case e als $ sigma $ qs $ Ss ^\\\\ Theta $ w $ nu $ rs)\n\n| D2A_Case_of : forall Delta Theta b e0 als ys w c c0 rho_ys rs qs\n  sigma rho nu Ss,\n  length ys = b ->\n  env_map rho ys = Some rho_ys ->\n  select_case als c = Some (Alt c0 b e0) ->\n  ($ E $ Delta $ e0          $ zip_var_list b rho_ys ++ shift b sigma $ qs $ Ss ^\\\\ Theta $ w $ nu $ rs) ->\n  ($ A $ Delta $ Constr c ys $ rho $ nil $ S_alt als sigma qs :: Ss                ^\\\\ Theta $ w $ nu $ rs) \n\nwhere \"($ x $ a $ b $ g $ e $ s ^\\\\ c $ d $ h $ f )\" :=\n  (DCPS2 x a b g e s c d h f).\n\nHint Constructors DCPS2.\n\nLemma DCPS2_complete :\nforall EA Gamma e sigma pn Ss Delta f rho qn,\n  ($ EA $ Gamma $ e $ sigma $ pn $ Ss ^\\  Delta $ f $ rho $ qn) ->\n  ($ EA $ Gamma $ e $ sigma $ pn $ Ss ^\\\\ Delta $ f $ rho $ qn).\nProof with isa; eauto.\nintros.\ninduction H...\ndestruct Ss.\n  (* nil *)\ninversion H2; subst...\n  (* cons *)\ninversion IHDCPS; subst...\nQed.\n\nLemma DCPS2_sound :\nforall EA Gamma e sigma pn Ss Delta f rho qn,\n  ($ EA $ Gamma $ e $ sigma $ pn $ Ss ^\\\\ Delta $ f $ rho $ qn) ->\n  ($ EA $ Gamma $ e $ sigma $ pn $ Ss ^\\  Delta $ f $ rho $ qn).\nProof with isa; eauto.\nintros.\ninduction H...\ndestruct EA...\nQed.\n\n\n(** * Defunctionalized Continuation Passing Style Semantics 3 *)\n\nReserved Notation \"($ x $ a $ b $ g $ e $ s ^\\\\\\ c $ d $ h $ f )\"\n  (at level 70, no associativity).\n\nInductive DCPS3 : action -> heapB -> expr -> env -> vars -> stack ->\n  heapB -> expr -> env -> vars -> Prop :=\n\n| D3_Halt : forall Gamma w sigma ps,\n  ($ A $ Gamma $ w $ sigma $ ps $ nil ^\\\\\\ Gamma $ w $ sigma $ ps)\n\n| D3_Con : forall Gamma Delta C pi w sigma rho qs Ss,\n  ($ A $ Gamma $ Constr C pi $ sigma $ nil $ Ss ^\\\\\\ Delta $ w $ rho $ qs) ->\n  ($ E $ Gamma $ Constr C pi $ sigma $ nil $ Ss ^\\\\\\ Delta $ w $ rho $ qs)\n\n| D3_Accum : forall Gamma Delta x xm sigma_xm qn w rs sigma rho Ss,\n  xm <> nil ->\n  env_map sigma xm = Some sigma_xm ->\n  ($ E $ Gamma $ App x nil $ sigma $ sigma_xm ++ qn $ Ss ^\\\\\\ Delta $ w $ rho $ rs) ->\n  ($ E $ Gamma $ App x xm  $ sigma $ qn             $ Ss ^\\\\\\ Delta $ w $ rho $ rs)\n\n| D3_App1 : forall Gamma tau p x pn m e sigma ,\n  env_find sigma x = Some (Atom p) ->\n  Gamma p = Some (Lf_n m e, tau) ->\n  m > length pn ->\n  ($ E $ Gamma $ App x nil $ sigma $ pn $ nil ^\\\\\\ Gamma $ App x nil $ sigma $ pn)\n\n| D3_App2_5 : forall Gamma Delta m e x tau p pn w rs sigma rho Ss,\n  env_find sigma x = Some (Atom p) ->\n  Gamma p = Some (Lf_n m e, tau) ->\n  m <= length pn -> \n  ($ E $ Gamma $ e         $ zip_var_list m (firstn m pn) ++ shift m tau $ skipn m pn $ Ss ^\\\\\\ Delta $ w $ rho $ rs) ->\n  ($ E $ Gamma $ App x nil $ sigma                                          $ pn         $ Ss ^\\\\\\ Delta $ w $ rho $ rs)\n\n| D3A_App4 : forall Delta rho C xs p Theta w nu qs Ss,\n  ($ E $ setB Delta p (Lf_n 0 (Constr C xs), trim rho xs) $ Constr C xs $ rho $ nil $ Ss ^\\\\\\ Theta $ w $ nu $ qs) ->\n  ($ A $ Delta $ Constr C xs $ rho $ nil $ S_upd (Atom p) nil :: Ss ^\\\\\\ Theta $ w $ nu $ qs)\n\n| D3E_App4_5 : forall Gamma Theta x p w e tau sigma nu rs qs Ss,\n  env_find sigma x = Some (Atom p) -> \n  Gamma p = Some (Lf_u e, tau) ->\n  ($ E $ Gamma $ e         $ tau   $ nil $ S_upd (Atom p) rs :: Ss ^\\\\\\ Theta $ w $ nu $ qs) ->\n  ($ E $ Gamma $ App x nil $ sigma $ rs $ Ss ^\\\\\\ Theta $ w $ nu $ qs)\n\n| D3A_App5 : forall EA Delta Theta x p pn y q qk f n w sigma rho nu mu qs Ss,\n  env_find sigma x = Some (Atom p) ->\n  env_find rho y = Some (Atom q) ->\n  Delta q = Some (Lf_n n f, mu) ->\n  length qk < n ->\n  ($ E $ 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 $ Ss    ^\\\\\\ Theta $ w $ nu $ qs) ->\n  ($ EA $ Delta $ App y nil $ rho $ qk $ S_upd (Atom p) pn :: Ss ^\\\\\\ Theta $ w $ nu $ qs)\n\n| D3_Let : forall Gamma Delta sigma rho lfs e w (ats : list nat) rs qs Ss,\n  length ats = length lfs ->\n  (forall a : nat, In a ats -> Gamma a = None) -> \n  ($ E $ 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 $ Ss\n    ^\\\\\\ Delta $ w $ rho $ qs) ->\n  ($ E $ Gamma $ Letrec lfs e $ sigma $ rs $ Ss ^\\\\\\ Delta $ w $ rho $ qs)\n\n| D3E_Case_of : forall Gamma Theta e als w rs qs sigma nu Ss,\n  ($ E $ Gamma $ e          $ sigma $ nil $ S_alt als sigma qs :: Ss ^\\\\\\ Theta $ w $ nu $ rs) ->\n  ($ E $ Gamma $ Case e als $ sigma $ qs $ Ss ^\\\\\\ Theta $ w $ nu $ rs)\n\n| D3A_Case_of : forall Delta Theta b e0 als ys w c c0 rho_ys rs qs\n  sigma rho nu Ss,\n  length ys = b ->\n  env_map rho ys = Some rho_ys ->\n  select_case als c = Some (Alt c0 b e0) ->\n  ($ E $ Delta $ e0          $ zip_var_list b rho_ys ++ shift b sigma $ qs $ Ss ^\\\\\\ Theta $ w $ nu $ rs) ->\n  ($ A $ Delta $ Constr c ys $ rho $ nil $ S_alt als sigma qs :: Ss                ^\\\\\\ Theta $ w $ nu $ rs) \n\nwhere \"($ x $ a $ b $ g $ e $ s ^\\\\\\ c $ d $ h $ f )\" :=\n  (DCPS3 x a b g e s c d h f).\n\nHint Constructors DCPS3.\n\nLemma DCPS3_complete :\nforall EA Gamma e sigma pn Ss Delta f rho qn,\n  ($ EA $ Gamma $ e $ sigma $ pn $ Ss ^\\\\  Delta $ f $ rho $ qn) ->\n  ($ EA $ Gamma $ e $ sigma $ pn $ Ss ^\\\\\\ Delta $ f $ rho $ qn).\nProof.\nintros.\ninduction H; eauto.\nQed.\n\nLemma DCPS3_sound :\nforall EA Gamma e sigma pn Ss Delta f rho qn,\n  ($ EA $ Gamma $ e $ sigma $ pn $ Ss ^\\\\\\ Delta $ f $ rho $ qn) ->\n  ($ EA $ Gamma $ e $ sigma $ pn $ Ss ^\\\\  Delta $ f $ rho $ qn).\nProof.\nintros.\ninduction H; eauto.\nQed.\n\n\n(** * Defunctionalized Continuation Passing Style Semantics 3 N *)\n\nReserved Notation \"($ x $ a $ b $ g $ e $ s ^^\\\\\\ c $ d $ h $ f ^^ n )\"\n  (at level 70, no associativity).\n\nInductive DCPS3N : action -> heapB -> expr -> env -> vars -> stack ->\n  heapB -> expr -> env -> vars -> nat -> Prop :=\n\n| D3N_Halt : forall Gamma w sigma ps,\n  ($ A $ Gamma $ w $ sigma $ ps $ nil ^^\\\\\\ Gamma $ w $ sigma $ ps ^^ 0)\n\n| D3N_Con : forall Gamma Delta C pi w sigma rho qs Ss N,\n  ($ A $ Gamma $ Constr C pi $ sigma $ nil $ Ss ^^\\\\\\ Delta $ w $ rho $ qs ^^ N) ->\n  ($ E $ Gamma $ Constr C pi $ sigma $ nil $ Ss ^^\\\\\\ Delta $ w $ rho $ qs ^^ S N)\n\n| D3N_Accum : forall Gamma Delta x xm sigma_xm qn w rs sigma rho Ss N,\n  xm <> nil ->\n  env_map sigma xm = Some sigma_xm ->\n  ($ E $ Gamma $ App x nil $ sigma $ sigma_xm ++ qn $ Ss ^^\\\\\\ Delta $ w $ rho $ rs ^^ N) ->\n  ($ E $ Gamma $ App x xm  $ sigma $ qn             $ Ss ^^\\\\\\ Delta $ w $ rho $ rs ^^ S N)\n\n| D3N_App1 : forall Gamma tau p x pn m e sigma,\n  env_find sigma x = Some (Atom p) ->\n  Gamma p = Some (Lf_n m e, tau) ->\n  m > length pn ->\n  ($ E $ Gamma $ App x nil $ sigma $ pn $ nil ^^\\\\\\ Gamma $ App x nil $ sigma $ pn ^^ 0)\n\n| D3N_App2_5 : forall Gamma Delta m e x tau p pn w rs sigma rho Ss N,\n  env_find sigma x = Some (Atom p) ->\n  Gamma p = Some (Lf_n m e, tau) ->\n  m <= length pn -> \n  ($ E $ Gamma $ e         $ zip_var_list m (firstn m pn) ++ shift m tau $ skipn m pn $ Ss ^^\\\\\\ Delta $ w $ rho $ rs ^^ N) ->\n  ($ E $ Gamma $ App x nil $ sigma                                          $ pn         $ Ss ^^\\\\\\ Delta $ w $ rho $ rs ^^ S N)\n\n| D3NA_App4 : forall Delta rho C xs p Theta w nu qs Ss N,\n  ($ E $ setB Delta p (Lf_n 0 (Constr C xs), trim rho xs) $ Constr C xs $ rho $ nil $ Ss ^^\\\\\\ Theta $ w $ nu $ qs ^^ N) ->\n  ($ A $ Delta $ Constr C xs $ rho $ nil $ S_upd (Atom p) nil :: Ss ^^\\\\\\ Theta $ w $ nu $ qs ^^ S N)\n\n| D3NE_App4_5 : forall Gamma Theta x p w e tau sigma nu rs qs Ss N,\n  env_find sigma x = Some (Atom p) -> \n  Gamma p = Some (Lf_u e, tau) ->\n  ($ E $ Gamma $ e         $ tau   $ nil $ S_upd (Atom p) rs :: Ss ^^\\\\\\ Theta $ w $ nu $ qs ^^ N) ->\n  ($ E $ Gamma $ App x nil $ sigma $ rs $ Ss ^^\\\\\\ Theta $ w $ nu $ qs ^^ S N)\n\n| D3NA_App5 : forall EA Delta Theta x p pn y q qk f n w sigma rho nu mu qs Ss N,\n  env_find sigma x = Some (Atom p) ->\n  env_find rho y = Some (Atom q) ->\n  Delta q = Some (Lf_n n f, mu) ->\n  length qk < n ->\n  ($ E $ 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 $ Ss    ^^\\\\\\ Theta $ w $ nu $ qs ^^ N) ->\n  ($ EA $ Delta $ App y nil $ rho $ qk $ S_upd (Atom p) pn :: Ss ^^\\\\\\ Theta $ w $ nu $ qs ^^ S N)\n\n| D3N_Let : forall Gamma Delta sigma rho lfs e w (ats : list nat) rs qs Ss N,\n  length ats = length lfs ->\n  (forall a : nat, In a ats -> Gamma a = None) -> \n  ($ E $ 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 $ Ss\n    ^^\\\\\\ Delta $ w $ rho $ qs ^^ N) ->\n  ($ E $ Gamma $ Letrec lfs e $ sigma $ rs $ Ss ^^\\\\\\ Delta $ w $ rho $ qs ^^ S N)\n\n| D3NE_Case_of : forall Gamma Theta e als w rs qs sigma nu Ss N,\n  ($ E $ Gamma $ e          $ sigma $ nil $ S_alt als sigma qs :: Ss ^^\\\\\\ Theta $ w $ nu $ rs ^^ N) ->\n  ($ E $ Gamma $ Case e als $ sigma $ qs $ Ss ^^\\\\\\ Theta $ w $ nu $ rs ^^ S N)\n\n| D3NA_Case_of : forall Delta Theta b e0 als ys w c c0 rho_ys rs qs\n  sigma rho nu Ss N,\n  length ys = b ->\n  env_map rho ys = Some rho_ys ->\n  select_case als c = Some (Alt c0 b e0) ->\n  ($ E $ Delta $ e0          $ zip_var_list b rho_ys ++ shift b sigma $ qs $ Ss ^^\\\\\\ Theta $ w $ nu $ rs ^^ N) ->\n  ($ A $ Delta $ Constr c ys $ rho $ nil $ S_alt als sigma qs :: Ss                ^^\\\\\\ Theta $ w $ nu $ rs ^^ S N) \n\nwhere \"($ x $ a $ b $ g $ e $ s ^^\\\\\\ c $ d $ h $ f ^^ n )\" :=\n  (DCPS3N x a b g e s c d h f n).\n\nHint Constructors DCPS3N.\n\nLemma DCPS3N_complete :\nforall EA Gamma e sigma pn Ss Delta f rho qn,\n  ($ EA $ Gamma $ e $ sigma $ pn $ Ss ^\\\\\\  Delta $ f $ rho $ qn) ->\n  exists N,\n  ($ EA $ Gamma $ e $ sigma $ pn $ Ss ^^\\\\\\ Delta $ f $ rho $ qn ^^ N).\nProof with eauto.\nintros.\ninduction H; try eauto;\n  destruct IHDCPS3 as [N]; exists (S N); try constructor...\nQed.\n\nLemma DCPS3N_sound :\nforall EA N Gamma e sigma pn Ss Delta f rho qn,\n  ($ EA $ Gamma $ e $ sigma $ pn $ Ss ^^\\\\\\ Delta $ f $ rho $ qn ^^ N) ->\n  ($ EA $ Gamma $ e $ sigma $ pn $ Ss ^\\\\\\  Delta $ f $ rho $ qn).\nProof with isa; eauto.\nintros.\ninduction H...\nQed.\n\n\n(** * Defunctionalized Continuation Passing Style Semantics 4 *)\n\nReserved Notation \"($ x $ a $ b $ g $ e $ s ^\\\\/ c $ d $ h $ f )\"\n  (at level 70, no associativity).\n\nInductive DCPS4 : action -> heapB -> expr -> env -> vars -> stack ->\n  heapB -> expr -> env -> vars -> Prop :=\n\n| D4_Halt : forall Gamma w sigma ps,\n  ($ A $ Gamma $ w $ sigma $ ps $ nil ^\\\\/ Gamma $ w $ sigma $ ps)\n\n| D4_Con : forall Gamma Delta C pi w sigma rho qs Ss,\n  ($ A $ Gamma $ Constr C pi $ sigma $ nil $ Ss ^\\\\/ Delta $ w $ rho $ qs) ->\n  ($ E $ Gamma $ Constr C pi $ sigma $ nil $ Ss ^\\\\/ Delta $ w $ rho $ qs)\n\n| D4_Accum : forall Gamma Delta x xm sigma_xm qn w rs sigma rho Ss,\n  xm <> nil ->\n  env_map sigma xm = Some sigma_xm ->\n  ($ E $ Gamma $ App x nil $ sigma $ sigma_xm ++ qn $ Ss ^\\\\/ Delta $ w $ rho $ rs) ->\n  ($ E $ Gamma $ App x xm  $ sigma $ qn             $ Ss ^\\\\/ Delta $ w $ rho $ rs)\n\n| D4_App1 : forall Gamma tau p x pn m e sigma ,\n  env_find sigma x = Some (Atom p) ->\n  Gamma p = Some (Lf_n m e, tau) ->\n  m > length pn ->\n  ($ E $ Gamma $ App x nil $ sigma $ pn $ nil ^\\\\/ Gamma $ App x nil $ sigma $ pn)\n\n| D4_App2_5 : forall Gamma Delta m e x tau p pn w rs sigma rho Ss,\n  env_find sigma x = Some (Atom p) ->\n  Gamma p = Some (Lf_n m e, tau) ->\n  m <= length pn -> \n  ($ E $ Gamma $ e         $ zip_var_list m (firstn m pn) ++ shift m tau $ skipn m pn $ Ss ^\\\\/ Delta $ w $ rho $ rs) ->\n  ($ E $ Gamma $ App x nil $ sigma                                          $ pn         $ Ss ^\\\\/ Delta $ w $ rho $ rs)\n\n| D4A_App4 : forall Delta rho C xs p Theta w nu qs Ss,\n  ($ E $ setB Delta p (Lf_n 0 (Constr C xs), trim rho xs) $ Constr C xs $ rho $ nil $ Ss ^\\\\/ Theta $ w $ nu $ qs) ->\n  ($ A $ Delta $ Constr C xs $ rho $ nil $ S_upd (Atom p) nil :: Ss ^\\\\/ Theta $ w $ nu $ qs)\n\n| D4E_App4_5 : forall Gamma Theta x p w e tau sigma nu rs qs Ss,\n  env_find sigma x = Some (Atom p) -> \n  Gamma p = Some (Lf_u e, tau) ->\n  ($ E $ Gamma $ e         $ tau   $ nil $ S_upd (Atom p) rs :: Ss ^\\\\/ Theta $ w $ nu $ qs) ->\n  ($ E $ Gamma $ App x nil $ sigma $ rs $ Ss ^\\\\/ Theta $ w $ nu $ qs)\n\n| D4A_App5 : forall Delta Theta x p pn y q qk f n w sigma rho nu mu qs Ss,\n  env_find sigma x = Some (Atom p) ->\n  env_find rho y = Some (Atom q) ->\n  Delta q = Some (Lf_n n f, mu) ->\n  length qk < n ->\n  ($ E $ 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 $ Ss    ^\\\\/ Theta $ w $ nu $ qs) ->\n  ($ E $ Delta $ App y nil $ rho $ qk $ S_upd (Atom p) pn :: Ss ^\\\\/ Theta $ w $ nu $ qs)\n\n| D4_Let : forall Gamma Delta sigma rho lfs e w (ats : list nat) rs qs Ss,\n  length ats = length lfs ->\n  (forall a : nat, In a ats -> Gamma a = None) -> \n  ($ E $ 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 $ Ss\n    ^\\\\/ Delta $ w $ rho $ qs) ->\n  ($ E $ Gamma $ Letrec lfs e $ sigma $ rs $ Ss ^\\\\/ Delta $ w $ rho $ qs)\n\n| D4E_Case_of : forall Gamma Theta e als w rs qs sigma nu Ss,\n  ($ E $ Gamma $ e          $ sigma $ nil $ S_alt als sigma qs :: Ss ^\\\\/ Theta $ w $ nu $ rs) ->\n  ($ E $ Gamma $ Case e als $ sigma $ qs $ Ss ^\\\\/ Theta $ w $ nu $ rs)\n\n| D4A_Case_of : forall Delta Theta b e0 als ys w c c0 rho_ys rs qs\n  sigma rho nu Ss,\n  length ys = b ->\n  env_map rho ys = Some rho_ys ->\n  select_case als c = Some (Alt c0 b e0) ->\n  ($ E $ Delta $ e0          $ zip_var_list b rho_ys ++ shift b sigma $ qs $ Ss ^\\\\/ Theta $ w $ nu $ rs) ->\n  ($ A $ Delta $ Constr c ys $ rho $ nil $ S_alt als sigma qs :: Ss                ^\\\\/ Theta $ w $ nu $ rs) \n\nwhere \"($ x $ a $ b $ g $ e $ s ^\\\\/ c $ d $ h $ f )\" :=\n  (DCPS4 x a b g e s c d h f).\n\nHint Constructors DCPS4.\n\nLemma DCPS4_complete :\nforall N Gamma e sigma pn Ss Delta f rho qn,\n  ($ E $ Gamma $ e $ sigma $ pn $ Ss ^^\\\\\\ Delta $ f $ rho $ qn ^^ N) ->\n  ($ E $ Gamma $ e $ sigma $ pn $ Ss ^\\\\/  Delta $ f $ rho $ qn).\nProof with eauto.\nintro N.\ninduction N using lt_wf_ind; isa.\ninversion H0; subst...\ninversion H0; subst...\nconstructor.\ninversion H7; subst...\nQed.\n\nLemma DCPS4_sound :\nforall EA Gamma e sigma pn Ss Delta f rho qn,\n  ($ EA $ Gamma $ e $ sigma $ pn $ Ss ^\\\\/ Delta $ f $ rho $ qn) ->\n  ($ EA $ Gamma $ e $ sigma $ pn $ Ss ^\\\\\\  Delta $ f $ rho $ qn).\nProof.\nintros.\ninduction H; eauto.\nQed.\n\n\n(** * Defunctionalized Continuation Passing Style Semantics 5 *)\n\nReserved Notation \"($ x $ a $ b $ g $ e $ s ^\\/ c $ d $ h $ f )\"\n  (at level 70, no associativity).\n\nInductive DCPS5 : action -> heapB -> expr -> env -> vars -> stack ->\n  heapB -> expr -> env -> vars -> Prop :=\n\n| D5_Halt : forall Gamma w sigma ps,\n  ($ A $ Gamma $ w $ sigma $ ps $ nil ^\\/ Gamma $ w $ sigma $ ps)\n\n| D5_Con : forall Gamma Delta C pi w sigma rho qs Ss,\n  ($ A $ Gamma $ Constr C pi $ sigma $ nil $ Ss ^\\/ Delta $ w $ rho $ qs) ->\n  ($ E $ Gamma $ Constr C pi $ sigma $ nil $ Ss ^\\/ Delta $ w $ rho $ qs)\n\n| D5_Accum : forall Gamma Delta x xm sigma_xm qn w rs sigma rho Ss,\n  xm <> nil ->\n  env_map sigma xm = Some sigma_xm ->\n  ($ E $ Gamma $ App x nil $ sigma $ sigma_xm ++ qn $ Ss ^\\/ Delta $ w $ rho $ rs) ->\n  ($ E $ Gamma $ App x xm  $ sigma $ qn             $ Ss ^\\/ Delta $ w $ rho $ rs)\n\n| D5_App1 : forall Gamma tau p x pn m e sigma ,\n  env_find sigma x = Some (Atom p) ->\n  Gamma p = Some (Lf_n m e, tau) ->\n  m > length pn ->\n  ($ E $ Gamma $ App x nil $ sigma $ pn $ nil ^\\/ Gamma $ App x nil $ sigma $ pn)\n\n| D5_App2_5 : forall Gamma Delta m e x tau p pn w rs sigma rho Ss,\n  env_find sigma x = Some (Atom p) ->\n  Gamma p = Some (Lf_n m e, tau) ->\n  m <= length pn -> \n  ($ E $ Gamma $ e         $ zip_var_list m (firstn m pn) ++ shift m tau $ skipn m pn $ Ss ^\\/ Delta $ w $ rho $ rs) ->\n  ($ E $ Gamma $ App x nil $ sigma                                          $ pn         $ Ss ^\\/ Delta $ w $ rho $ rs)\n\n| D5A_App4 : forall Delta rho C xs p Theta w nu qs Ss,\n  ($ A $ setB Delta p (Lf_n 0 (Constr C xs), trim rho xs) $ Constr C xs $ rho $ nil $ Ss ^\\/ Theta $ w $ nu $ qs) ->\n  ($ A $ Delta $ Constr C xs $ rho $ nil $ S_upd (Atom p) nil :: Ss ^\\/ Theta $ w $ nu $ qs)\n\n| D5E_App4_5 : forall Gamma Theta x p w e tau sigma nu rs qs Ss,\n  env_find sigma x = Some (Atom p) -> \n  Gamma p = Some (Lf_u e, tau) ->\n  ($ E $ Gamma $ e         $ tau   $ nil $ S_upd (Atom p) rs :: Ss ^\\/ Theta $ w $ nu $ qs) ->\n  ($ E $ Gamma $ App x nil $ sigma $ rs $ Ss ^\\/ Theta $ w $ nu $ qs)\n\n| D5A_App5 : forall Delta Theta x p pn y q qk f n w sigma rho nu mu qs Ss,\n  env_find sigma x = Some (Atom p) ->\n  env_find rho y = Some (Atom q) ->\n  Delta q = Some (Lf_n n f, mu) ->\n  length qk < n ->\n  ($ E $ 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 $ Ss    ^\\/ Theta $ w $ nu $ qs) ->\n  ($ E $ Delta $ App y nil $ rho $ qk $ S_upd (Atom p) pn :: Ss ^\\/ Theta $ w $ nu $ qs)\n\n| D5_Let : forall Gamma Delta sigma rho lfs e w (ats : list nat) rs qs Ss,\n  length ats = length lfs ->\n  (forall a : nat, In a ats -> Gamma a = None) -> \n  ($ E $ 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 $ Ss\n    ^\\/ Delta $ w $ rho $ qs) ->\n  ($ E $ Gamma $ Letrec lfs e $ sigma $ rs $ Ss ^\\/ Delta $ w $ rho $ qs)\n\n| D5E_Case_of : forall Gamma Theta e als w rs qs sigma nu Ss,\n  ($ E $ Gamma $ e          $ sigma $ nil $ S_alt als sigma qs :: Ss ^\\/ Theta $ w $ nu $ rs) ->\n  ($ E $ Gamma $ Case e als $ sigma $ qs $ Ss ^\\/ Theta $ w $ nu $ rs)\n\n| D5A_Case_of : forall Delta Theta b e0 als ys w c c0 rho_ys rs qs\n  sigma rho nu Ss,\n  length ys = b ->\n  env_map rho ys = Some rho_ys ->\n  select_case als c = Some (Alt c0 b e0) ->\n  ($ E $ Delta $ e0          $ zip_var_list b rho_ys ++ shift b sigma $ qs $ Ss ^\\/ Theta $ w $ nu $ rs) ->\n  ($ A $ Delta $ Constr c ys $ rho $ nil $ S_alt als sigma qs :: Ss                ^\\/ Theta $ w $ nu $ rs) \n\nwhere \"($ x $ a $ b $ g $ e $ s ^\\/ c $ d $ h $ f )\" :=\n  (DCPS5 x a b g e s c d h f).\n\nHint Constructors DCPS5.\n\nLemma DCPS5_complete :\nforall EA Gamma e sigma pn Ss Delta f rho qn,\n  ($ EA $ Gamma $ e $ sigma $ pn $ Ss ^\\\\/ Delta $ f $ rho $ qn) ->\n  ($ EA $ Gamma $ e $ sigma $ pn $ Ss ^\\/  Delta $ f $ rho $ qn).\nProof with eauto.\nintros.\ninduction H...\ninversion IHDCPS4; subst...\nQed.\n\nLemma DCPS5_sound :\nforall EA Gamma e sigma pn Ss Delta f rho qn,\n  ($ EA $ Gamma $ e $ sigma $ pn $ Ss ^\\/  Delta $ f $ rho $ qn) ->\n  ($ EA $ Gamma $ e $ sigma $ pn $ Ss ^\\\\/ Delta $ f $ rho $ qn).\nProof.\nintros.\ninduction H; eauto.\nQed.\n\n\n(** * The STG Almost-Machine *)\n\nInductive instruction := Eval | Enter | ReturnCon.\n\nReserved Notation \"($ x $ a $ b $ g $ e $ s ^^^ c $ d $ h $ f )\"\n  (at level 70, no associativity).\n\nInductive ASTG : instruction -> heapB -> expr -> env -> vars -> stack ->\n  heapB -> expr -> env -> vars -> Prop :=\n\n| ASTG_Halt : forall Gamma w sigma ps,\n  ($ ReturnCon $ Gamma $ w $ sigma $ ps $ nil ^^^ Gamma $ w $ sigma $ ps)\n\n| ASTG_Con : forall Gamma Delta C pi w sigma rho qs Ss,\n  ($ ReturnCon $ Gamma $ Constr C pi $ sigma $ nil $ Ss ^^^ Delta $ w $ rho $ qs) ->\n  ($ Eval      $ Gamma $ Constr C pi $ sigma $ nil $ Ss ^^^ Delta $ w $ rho $ qs)\n\n| ASTG_Accum : forall Gamma Delta x xm sigma_xm qn w rs sigma rho Ss,\n  (* We abandon xm <> nil *)\n  env_map sigma xm = Some sigma_xm ->\n  ($ Enter $ Gamma $ App x nil $ sigma $ sigma_xm ++ qn $ Ss ^^^ Delta $ w $ rho $ rs) ->\n  ($ Eval  $ Gamma $ App x xm  $ sigma $ qn             $ Ss ^^^ Delta $ w $ rho $ rs)\n\n| ASTG_App1 : forall Gamma tau p x pn m e sigma ,\n  env_find sigma x = Some (Atom p) ->\n  Gamma p = Some (Lf_n m e, tau) ->\n  m > length pn ->\n  ($ Enter $ Gamma $ App x nil $ sigma $ pn $ nil ^^^ Gamma $ App x nil $ sigma $ pn)\n\n| ASTG_App2_5 : forall Gamma Delta m e x tau p pn w rs sigma rho Ss,\n  env_find sigma x = Some (Atom p) ->\n  Gamma p = Some (Lf_n m e, tau) ->\n  m <= length pn -> \n  ($ Eval  $ Gamma $ e         $ zip_var_list m (firstn m pn) ++ shift m tau $ skipn m pn $ Ss ^^^ Delta $ w $ rho $ rs) ->\n  ($ Enter $ Gamma $ App x nil $ sigma                                          $ pn         $ Ss ^^^ Delta $ w $ rho $ rs)\n\n| ASTGA_App4 : forall Delta rho C xs p Theta w nu qs Ss,\n  ($ ReturnCon $ setB Delta p (Lf_n 0 (Constr C xs), trim rho xs) $ Constr C xs $ rho $ nil $ Ss ^^^ Theta $ w $ nu $ qs) ->\n  ($ ReturnCon $ Delta $ Constr C xs $ rho $ nil $ S_upd (Atom p) nil :: Ss ^^^ Theta $ w $ nu $ qs)\n\n| ASTGE_App4_5 : forall Gamma Theta x p w e tau sigma nu rs qs Ss,\n  env_find sigma x = Some (Atom p) -> \n  Gamma p = Some (Lf_u e, tau) ->\n  ($ Eval  $ Gamma $ e         $ tau   $ nil $ S_upd (Atom p) rs :: Ss ^^^ Theta $ w $ nu $ qs) ->\n  ($ Enter $ Gamma $ App x nil $ sigma $ rs $ Ss ^^^ Theta $ w $ nu $ qs)\n\n| ASTGA_App5 : forall Delta Theta x p pn y q qk f n w sigma rho nu mu qs Ss,\n  env_find sigma x = Some (Atom p) ->\n  env_find rho y = Some (Atom q) ->\n  Delta q = Some (Lf_n n f, mu) ->\n  length qk < n ->\n  ($ Enter $ 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 $ Ss    ^^^ Theta $ w $ nu $ qs) ->\n  ($ Enter $ Delta $ App y nil $ rho $ qk $ S_upd (Atom p) pn :: Ss ^^^ Theta $ w $ nu $ qs)\n\n| ASTG_Let : forall Gamma Delta sigma rho lfs e w (ats : list nat) rs qs Ss,\n  length ats = length lfs ->\n  (forall a : nat, In a ats -> Gamma a = None) -> \n  ($ Eval $ 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 $ Ss\n    ^^^ Delta $ w $ rho $ qs) ->\n  ($ Eval $ Gamma $ Letrec lfs e $ sigma $ rs $ Ss ^^^ Delta $ w $ rho $ qs)\n\n| ASTGE_Case_of : forall Gamma Theta e als w rs qs sigma nu Ss,\n  ($ Eval $ Gamma $ e          $ sigma $ nil $ S_alt als sigma qs :: Ss ^^^ Theta $ w $ nu $ rs) ->\n  ($ Eval $ Gamma $ Case e als $ sigma $ qs $ Ss ^^^ Theta $ w $ nu $ rs)\n\n| ASTGA_Case_of : forall Delta Theta b e0 als ys w c c0 rho_ys rs qs\n  sigma rho nu Ss,\n  length ys = b ->\n  env_map rho ys = Some rho_ys ->\n  select_case als c = Some (Alt c0 b e0) ->\n  ($ Eval $ Delta $ e0          $ zip_var_list b rho_ys ++ shift b sigma $ qs $ Ss ^^^ Theta $ w $ nu $ rs) ->\n  ($ ReturnCon $ Delta $ Constr c ys $ rho $ nil $ S_alt als sigma qs :: Ss                ^^^ Theta $ w $ nu $ rs) \n\nwhere \"($ x $ a $ b $ g $ e $ s ^^^ c $ d $ h $ f )\" :=\n  (ASTG x a b g e s c d h f).\n\nHint Constructors ASTG.\n\nDefinition action_to_instruction (a : action) (e : expr) : instruction :=\nmatch a with\n| A => ReturnCon\n| E => match e with\n  | App _ nil => Enter\n  | _         => Eval\n  end\nend.\n\nLemma ASTG_complete_aux :\nforall EA Gamma e sigma pn Ss Delta f rho qn,\n  ($ EA $ Gamma $ e $ sigma $ pn $ Ss ^\\/  Delta $ f $ rho $ qn) ->\n  ($ action_to_instruction EA e $ Gamma $ e $ sigma $ pn $ Ss ^^^ Delta $ f $ rho $ qn).\nProof with isa.\nintros.\ninduction H...\n(* Case *)\ndestruct xm...\ncase H...\neconstructor; eauto.\n(* Case *)\neconstructor; eauto.\n(* Case *)\ndestruct e; econstructor; eauto.\ndestruct v0; eauto.\napply ASTG_Accum with (sigma_xm := nil); eauto.\n(* Case *)\ndestruct e; econstructor 7; eauto.\ndestruct v0; eauto.\napply ASTG_Accum with (sigma_xm := nil); eauto.\n(* Case *)\neconstructor 8; eauto.\n(* Case *)\ndestruct e; econstructor; eauto.\ndestruct v0; eauto.\napply ASTG_Accum with (sigma_xm := nil); eauto.\n(* Case *)\ndestruct e; econstructor; eauto.\ndestruct v0; eauto.\napply ASTG_Accum with (sigma_xm := nil); eauto.\n(* Case *)\ndestruct e0; econstructor; eauto.\ndestruct v0; eauto.\napply ASTG_Accum with (sigma_xm := nil); eauto.\nQed.\n\nLemma ASTG_complete :\nforall Gamma e sigma pn Ss Delta f rho qn,\n  ($ E    $ Gamma $ e $ sigma $ pn $ Ss ^\\/ Delta $ f $ rho $ qn) ->\n  ($ Eval $ Gamma $ e $ sigma $ pn $ Ss ^^^ Delta $ f $ rho $ qn).\nProof with isa.\nintros.\ndestruct e.\n(* Case *)\ndestruct v0.\n  (* Subcase *)\napply ASTG_Accum with (sigma_xm := nil)...\nfold (action_to_instruction E (App v nil)).\napply ASTG_complete_aux...\n  (* Subcase *)\nfold (action_to_instruction E (App v (v0 :: v1))).\napply ASTG_complete_aux...\n(* Case *)\nfold (action_to_instruction E (Constr c v)).\napply ASTG_complete_aux...\n(* Case *)\nfold (action_to_instruction E (Letrec l e)).\napply ASTG_complete_aux...\n(* Case *)\nfold (action_to_instruction E (Case e l)).\napply ASTG_complete_aux...\nQed.\n\nDefinition instruction_to_action (i : instruction) : action :=\nmatch i with\n| ReturnCon => A\n| _ => E\nend.\n\nLemma ASTG_sound_aux :\nforall REE Gamma e sigma pn Ss Delta f rho qn,\n  ($ REE $ Gamma $ e $ sigma $ pn $ Ss ^^^ Delta $ f $ rho $ qn) ->\n  ($ instruction_to_action REE $ Gamma $ e $ sigma $ pn $ Ss ^\\/ Delta $ f $ rho $ qn).\nProof with isa.\nintros.\ninduction H...\n(* Case *)\ndestruct xm.\n  (* Subcase *)\nsimpl in H.\ninversion H; subst...\n  (* Subcase *)\neapply D5_Accum; eauto.\ndiscriminate.\n(* Case *)\neapply D5_App1; eauto.\n(* Case *)\neapply D5_App2_5; eauto.\n(* Case *)\neapply D5E_App4_5; eauto.\n(* Case *)\neapply D5A_App5; eauto.\n(* Case *)\neconstructor; eauto.\n(* Case *)\neconstructor; eauto.\nQed.\n\nLemma ASTG_sound :\nforall Gamma e sigma pn Ss Delta f rho qn,\n  ($ Eval $ Gamma $ e $ sigma $ pn $ Ss ^^^ Delta $ f $ rho $ qn) ->\n  ($ E    $ Gamma $ e $ sigma $ pn $ Ss ^\\/ Delta $ f $ rho $ qn).\nProof with isa.\nintros.\nfold (instruction_to_action Eval).\napply ASTG_sound_aux...\nQed.\n\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/Sem06.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.272972523822548}}
{"text": "(** Properties of substitutions *)\n\nLemma subst_tau_core:\n  forall t0 t1 t v v' ,\n    v <> v' ->\n    (subst_tau t0 v t) = (subst_tau t1 v' (subst_tau t0 v t)) ->\n     t = (subst_tau t1 v' t).\nProof.\n  induction t; introv Neq Equ; simpls; inversion* Equ; fequals*.\n  case_var*.\n  case_var*.\nQed.\n\nLemma subst_tau_v_core:\n  forall t0 t1 t v v',\n    v <> v' ->\n    (subst_tau_v t0 v t) = (subst_tau_v t1 v' (subst_tau_v t0 v t)) ->\n     t = (subst_tau_v t1 v' t).\nProof.\n  induction t;\n  introv Neq Equ;\n  simpls*.\nQed.\n\nLemma subst_tau_st_core:\n  forall s v v',\n    v <> v' ->\n    forall s0 s1, \n      (subst_tau_st s0 v s) = (subst_tau_st s1 v' (subst_tau_st s0 v s)) ->\n      s = (subst_tau_st s1 v' s).\nProof.\n  apply (St_ind_mutual \n           (fun s : St => \n              forall v v',\n                v <> v' ->\n              forall s0 s1, \n                (subst_tau_st s0 v s) = (subst_tau_st s1 v' (subst_tau_st s0 v s)) ->\n                s = (subst_tau_st s1 v' s))\n           (fun e : E  => \n              forall v v',\n                v <> v' ->\n              forall e0 e1,\n                (subst_tau_e e0 v e) = (subst_tau_e e1 v' (subst_tau_e e0 v e)) ->\n                e = (subst_tau_e e1 v' e))\n           (fun f : F  => \n              forall v v',\n                v <> v' ->\n              forall f0 f1,\n                (subst_tau_f f0 v f) = (subst_tau_f f1 v' (subst_tau_f f0 v f)) ->\n                f = (subst_tau_f f1 v' f))); \n  intros;\n  simpl;\n  fequals;\n  try solve[\n        try inversion H4 as [I4];\n        try inversion H3 as [I3];\n        try inversion H2 as [I2];\n        try inversion H1 as [I1];\n        try solve[applys* H];\n        try solve[applys* H0];\n        try solve[applys* H1];\n        try solve[applys* H2];\n        try solve[applys* H3];\n        try solve[applys* subst_tau_core]].\n\n  destruct v; simpl; reflexivity.\nQed.\n\nLemma subst_tau_e_core:\n  forall e v v',\n    v <> v' ->\n    forall e0 e1, \n      (subst_tau_e e0 v e) = (subst_tau_e e1 v' (subst_tau_e e0 v e)) ->\n      e = (subst_tau_e e1 v' e).\nProof.\n  apply (E_ind_mutual \n           (fun s : St => \n              forall v v',\n                v <> v' ->\n              forall s0 s1, \n                (subst_tau_st s0 v s) = (subst_tau_st s1 v' (subst_tau_st s0 v s)) ->\n                s = (subst_tau_st s1 v' s))\n           (fun e : E  => \n              forall v v',\n                v <> v' ->\n              forall e0 e1,\n                (subst_tau_e e0 v e) = (subst_tau_e e1 v' (subst_tau_e e0 v e)) ->\n                e = (subst_tau_e e1 v' e))\n           (fun f : F  => \n              forall v v',\n                v <> v' ->\n              forall f0 f1,\n                (subst_tau_f f0 v f) = (subst_tau_f f1 v' (subst_tau_f f0 v f)) ->\n                f = (subst_tau_f f1 v' f)));\n  intros;\n  simpl;\n  fequals;\n  try solve[\n        try inversion H4 as [I4];\n        try inversion H3 as [I3];\n        try inversion H2 as [I2];\n        try inversion H1 as [I1];\n        try solve[applys* H];\n        try solve[applys* H0];\n        try solve[applys* H1];\n        try solve[applys* H2];\n        try solve[applys* H3];\n        try solve[applys* subst_tau_core]].\n  destruct v; simpl; reflexivity.\nQed.\n\nLemma subst_tau_f_core:\n  forall f v v',\n    v <> v' ->\n    forall f0 f1, \n      (subst_tau_f f0 v f) = (subst_tau_f f1 v' (subst_tau_f f0 v f)) ->\n      f = (subst_tau_f f1 v' f).\nProof.\n  apply (F_ind_mutual \n           (fun s : St => \n              forall v v',\n                v <> v' ->\n              forall s0 s1, \n                (subst_tau_st s0 v s) = (subst_tau_st s1 v' (subst_tau_st s0 v s)) ->\n                s = (subst_tau_st s1 v' s))\n           (fun e : E  => \n              forall v v',\n                v <> v' ->\n              forall e0 e1,\n                (subst_tau_e e0 v e) = (subst_tau_e e1 v' (subst_tau_e e0 v e)) ->\n                e = (subst_tau_e e1 v' e))\n           (fun f : F  => \n              forall v v',\n                v <> v' ->\n              forall f0 f1,\n                (subst_tau_f f0 v f) = (subst_tau_f f1 v' (subst_tau_f f0 v f)) ->\n                f = (subst_tau_f f1 v' f)));\n  intros;\n  simpl;\n  fequals;\n  try solve[\n        try inversion H4 as [I4];\n        try inversion H3 as [I3];\n        try inversion H2 as [I2];\n        try inversion H1 as [I1];\n        try solve[applys* H];\n        try solve[applys* H0];\n        try solve[applys* H1];\n        try solve[applys* H2];\n        try solve[applys* H3];\n        try solve[applys* subst_tau_core]].\n  destruct v; simpl; reflexivity.\nQed.\n\nLemma open_rec_term_core_term:\n  forall v v',\n    v <> v' ->\n    forall t0 t1 t, \n      (subst_tau_term t0 v t) = (subst_tau_term t1 v' (subst_tau_term t0 v t)) ->\n      t = (subst_tau_term t1 v' t).\nProof.\n  intros; destruct t; inversion H0; simpl; fequals*.\n  apply subst_tau_st_core with (v:=v) (s0:=t0); try assumption.\n  apply subst_tau_e_core with  (v:=v) (e0:=t0); try assumption.\n  apply subst_tau_f_core with  (v:=v) (f0:=t0); try assumption.\nQed.\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/deadcode/badsubstitutions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.272972523822548}}
{"text": "(******************************************************************************)\n(** * Definition of the JSMM memory model *)\n(******************************************************************************)\nFrom hahn Require Import Hahn.\nFrom imm Require Import Events.\nRequire Import Execution_m.\n(*Require Import Execution_eco.*)\n\nSet Implicit Arguments.\nRemove Hints plus_n_O.\n\nSection JSMM_m.\n\nVariable G : execution_m.\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).\n(* Notation \"'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\nDefinition sw := ⦗ Sc ⦘ ⨾ (rf ∩ same_range) ⨾ ⦗ Sc ⦘.\nDefinition hb := (sb ∪ sw)⁺.\n\n(******************************************************************************)\n(** ** Consistency  *)\n(******************************************************************************)\n\nDefinition jsmm_m_consistent (tot : relation actid) (tearfree : actid -> Prop) :=\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  ⟪ Cirr1 :\n      irreflexive (⦗W∩₁Sc⦘ ⨾ tot ⨾ sw⁻¹ ⨾ (tot ∩ same_range)) ⟫ /\\\n  ⟪ Cirr2 :\n      irreflexive (⦗W∩₁Sc⦘ ⨾ hb ⨾\n                   (hb ∩ rf)⁻¹ ⨾ ⦗W∩₁Sc⦘ ⨾ (tot ∩ same_range)) ⟫ /\\\n  ⟪ Cirr3 :\n      irreflexive (⦗W∩₁Sc⦘ ⨾ (tot ∩ same_range) ⨾ ⦗R∩₁Sc⦘ ⨾\n                   (hb ∩ rf)⁻¹ ⨾ hb) ⟫ /\\\n  ⟪ Ctf :\n      functional (⦗tearfree⦘ ⨾ (rf⁻¹ ∩ same_range) ⨾ ⦗tearfree⦘) ⟫.\n\nLemma sw_E x y :\n  Wf_m G -> sw x y -> (E x /\\ E y).\nProof.\n  intros WF H.\n  unfold sw in H.\n  destruct H as [x_ [[H11 H12] [y_ [[H21 H22] [H31 H32]]]]].\n  rewrite <- H11 in H21,H22.\n  rewrite H31 in H21, H22, H32.\n  pose (wf_rfE WF) as Hp.\n  apply Hp in H21.\n  destruct H21 as [x__ [H21_ [y__ [H221_ H222_]]]].\n  destruct H21_.\n  destruct H222_.\n  rewrite H1 in H2.\n  split; assumption.\nQed.\n\nLemma hb_E x y :\n  Wf_m G -> hb x y -> (E x /\\ E y).\nProof.\n  intros WF H.\n  unfold hb in H.\n  split.\n  - eapply ct_doma.\n    + assert (doma (sb ∪ sw) E) as Ha. {\n        unfold doma. intros a b Ha. destruct Ha as [Ha | Ha].\n        - apply sb_E in Ha. apply Ha.\n        - apply sw_E in Ha. apply Ha. apply WF.\n      }\n      apply Ha.\n    + apply H.\n  - eapply ct_domb.\n    + assert (domb (sb ∪ sw) E) as Ha. {\n        unfold domb. intros a b Ha. destruct Ha as [Ha | Ha].\n        - apply sb_E in Ha. apply Ha.\n        - apply sw_E in Ha. apply Ha. apply WF.\n      }\n      apply Ha.\n    + apply H.\nQed.\n\n(******************************************************************************)\n(** ** SC-DRF  *)\n(******************************************************************************)\n\nDefinition data_race_free :=\n  forall x y,\n    hb x y \\/ hb y x \\/\n    (~(W x) /\\ ~(W y)) \\/\n    no_overlap x y \\/\n   (same_range x y /\\ Sc x /\\ Sc y).\n\nDefinition seqcst tot :=\n  irreflexive (rf ⨾ tot) /\\\n  (forall n, \n     irreflexive (⦗W⦘ ⨾ (tot ∩ overlap_on n) ⨾ (rf_on n)⁻¹ ⨾ tot)).\n\nLemma hb_tot_inconsist tot x y :\n  strict_total_order E tot ->\n  hb ⊆ tot->\n  tot x y ->\n  hb y x ->\n  False.\nProof.\n  intros H1 H2 H3 H4.\n  destruct H1 as [[H111 H112] H12].\n  apply H111 with x.\n  pose (H2 _ _ H4) as H.\n  apply (H112 x y x H3 H).\nQed.\n\nLemma spo_hb tot :\n  strict_total_order E tot ->\n  hb ⊆ tot->\n  strict_partial_order hb.\nProof.\n  intros H1 H2.\n  split.\n  - unfold strict_total_order in H1.\n    apply irreflexive_inclusion with tot.\n    + assumption.\n    + apply H1.\n  - unfold hb. intuition.\nQed.\n\nLemma rf_sw x y :\n  rf x y ->\n  same_range x y ->\n  Sc x ->\n  Sc y ->\n  sw x y.\nProof.\n  unfold sw.\n  exists x.\n  split. { intuition. }\n  unfold inter_rel.\n  exists y.\n  intuition.\nQed.\n\nLemma sw_hb x y :\n  sw x y ->\n  hb x y.\nProof.\n  unfold hb.\n  intuition.\nQed.\n\nLemma sw_sc :\n  Wf_m G ->\n  sw = ⦗W∩₁Sc⦘ ⨾ sw ⨾ ⦗R∩₁Sc⦘.\nProof.\n  intros Hwf.\n  apply functional_extensionality.\n  intros x.\n  apply functional_extensionality.\n  intros y.\n  apply PropExtensionality.propositional_extensionality.\n  split.\n  - intros H.\n    unfold sw.\n    unfold sw in H.\n    destruct H as [x_ [H1 [y_ [H21 H22]]]].\n    destruct H1 as [H11 H12].\n    rewrite <- H11 in H21.\n    destruct H22 as [H221 H222].\n    rewrite H221 in H21, H222.\n    assert (W x /\\ R y) as Wx_Ry. { apply rf_w_r. apply Hwf. apply H21. }\n    econstructor.\n    split. { econstructor. reflexivity. econstructor. apply Wx_Ry. apply H12. }\n    econstructor.\n    split. {\n      econstructor.\n      split. { econstructor. reflexivity. assumption. }\n      econstructor.\n      split. { apply H21. }\n      econstructor. reflexivity. assumption.\n    }\n    econstructor. { reflexivity. }\n    econstructor; easy.\n  - intros H.\n    unfold sw.\n    unfold sw in H.\n    destruct H as [x_ [H1 [y_ [[x__ [H21 [y__ [H221 H222]]]] H3]]]].\n    destruct H1 as [H1a H1b].\n    rewrite <- H1a in H21.\n    destruct H21 as [H21a H21b].\n    rewrite <- H21a in H221.\n    destruct H3 as [H3a H3b].\n    rewrite H3a in H3b, H222.\n    destruct H222 as [H222a H222b].\n    rewrite H222a in H222b, H221.\n    econstructor.\n    split. { econstructor. reflexivity. assumption. }\n    econstructor.\n    split. { apply H221. }\n    econstructor. { reflexivity. }\n    assumption.\nQed.\n\nLemma sw_sc_inv :\n  Wf_m G ->\n  sw⁻¹ = ⦗R∩₁Sc⦘ ⨾ sw⁻¹ ⨾ ⦗W∩₁Sc⦘.\nProof.\n  intros Hwf.\n  apply functional_extensionality.\n  intros x.\n  apply functional_extensionality.\n  intros y.\n  apply PropExtensionality.propositional_extensionality.\n  split.\n  - intros H.\n    rewrite sw_sc in H.\n    apply transp_seq in H.\n    rewrite (rel_extensionality ((transp_seq sw (⦗R ∩₁ Sc⦘)))) in H.\n    apply seqA in H.\n    rewrite (rel_extensionality (transp_eqv_rel (R ∩₁ Sc))) in H.\n    rewrite (rel_extensionality (transp_eqv_rel (W ∩₁ Sc))) in H.\n    assumption.\n    apply Hwf.\n  - intros H.\n    rewrite sw_sc.\n    apply transp_seq.\n    rewrite (rel_extensionality ((transp_seq sw (⦗R ∩₁ Sc⦘)))).\n    apply seqA in H.\n    rewrite (rel_extensionality (transp_eqv_rel (R ∩₁ Sc))).\n    rewrite (rel_extensionality (transp_eqv_rel (W ∩₁ Sc))).\n    assumption.\n    apply Hwf.\nQed.\n\nLemma sw_rf_Cirr1_left x y :\n  Wf_m G ->\n  (sw⁻¹) x y -> (⦗R∩₁Sc⦘ ⨾ (rf ∩ same_range)⁻¹ ⨾ ⦗W∩₁Sc⦘) x y.\nProof.\n  intros Hwf H.\n  rewrite sw_sc_inv in H.\n  unfold sw in H.\n  destruct H as [x_ [H1 H2]].\n  destruct H1 as [x_is H11].\n  rewrite <- x_is in H2.\n  econstructor.\n  split. { econstructor. reflexivity. assumption. }\n  destruct H2 as [y_ [[y__ [[H21211 H21212] [x__ [H212221 [H2122221 H2122222]]]]] [H221 H222]]].\n  econstructor.\n  split. { econstructor; rewrite <- H2122221; apply H212221. }\n  econstructor. { rewrite <- H21211. rewrite H221. reflexivity. }\n  rewrite <- H21211. apply H222.\n  apply Hwf.\nQed.\n\nLemma sw_rf_Cirr1_right x y :\n  Wf_m G ->\n  (⦗R∩₁Sc⦘ ⨾ (rf ∩ same_range)⁻¹ ⨾ ⦗W∩₁Sc⦘) x y -> (sw⁻¹) x y.\nProof.\n  intros Hwf H.\n  rewrite sw_sc_inv.\n  unfold sw.\n  destruct H as [x_ [H1 H2]].\n  destruct H1 as [x_is H11].\n  rewrite <- x_is in H2.\n  econstructor.\n  split. { econstructor. reflexivity. assumption. }\n  destruct H2 as [y_ [H21 [H221 H222]]].\n  rewrite H221 in H222, H21.\n  econstructor.\n  split. {\n    econstructor.\n    split. { econstructor. apply H221. rewrite H221. apply H222. }\n    econstructor.\n    split. { apply H21. }\n    econstructor. reflexivity. apply H11.\n  }\n  rewrite H221.\n  econstructor. reflexivity. apply H222.\n  apply Hwf.\nQed.\n\nLemma sw_rf_Cirr1 :\n  Wf_m G ->\n  (sw⁻¹) = (⦗R∩₁Sc⦘ ⨾ (rf ∩ same_range)⁻¹ ⨾ ⦗W∩₁Sc⦘).\nProof.\n  intros Hwf.\n  apply functional_extensionality.\n  intros x.\n  apply functional_extensionality.\n  intros y.\n  apply PropExtensionality.propositional_extensionality.\n  split.\n  apply sw_rf_Cirr1_left.\n  apply Hwf.\n  apply sw_rf_Cirr1_right.\n  apply Hwf.\nQed.\n\nLemma Cirr1_alt tot :\n  Wf_m G ->\n  irreflexive (⦗W∩₁Sc⦘ ⨾ tot ⨾ sw⁻¹ ⨾ (tot ∩ same_range)) = irreflexive (⦗W∩₁Sc⦘ ⨾ tot ⨾ ⦗R∩₁Sc⦘ ⨾ (rf ∩ same_range)⁻¹ ⨾ ⦗W∩₁Sc⦘ ⨾ (tot ∩ same_range)).\nProof.\n  intros Hwf.\n  rewrite sw_rf_Cirr1.\n  repeat rewrite (rel_extensionality (seqA _ _ _)).\n  reflexivity.\n  apply Hwf.\nQed.\n\nLemma drf_tot__hb_sc x y tot :\n  data_race_free ->\n  strict_total_order E tot ->\n  hb ⊆ tot ->\n  tot x y ->\n  is_overlap G x y ->\n  W x \\/ W y ->\n  hb x y \\/ (same_range x y /\\ Sc x /\\ Sc y).\nProof.\n  intros DRF tot_wf hb_in_tot H1 H2 H3.\n  unfold data_race_free in DRF.\n  destruct DRF with x y as [hbXY | [hbYX | [[nWX nWY] | [novrlpXY | [slXY [scX scY]]]]]]; auto.\n  - exfalso.\n    assert (tot y x). { apply hb_in_tot. apply hbYX. }\n    unfold strict_total_order in tot_wf.\n    destruct tot_wf as [[tot_wf11 tot_wf12] tot_wf2].\n    apply tot_wf11 with x.\n    unfold transitive in tot_wf12.\n    apply (tot_wf12 x y x H1 H).\n  - exfalso.\n    destruct H3; contradiction.\n  - exfalso.\n    destruct H2.\n    apply novrlpXY.\nQed.\n\nEnd JSMM_m.\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.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.272972516948216}}
{"text": "From Tealeaves Require Export\n  Theory.Algebraic.Decorated.Monad.ToKleisli\n  Theory.Algebraic.Decorated.Functor.KleisliTheory.\n\nImport Algebraic.Monad.Notations.\nImport Comonad.Notations.\nImport Monoid.Notations.\nImport Product.Notations.\n\n#[local] Generalizable Variables W.\n\n(** ** Properties *)\n(******************************************************************************)\n\n(** ** Kleisli composition *)\n(******************************************************************************)\nSection decorated_monad_kleisli_operations.\n\n  Context\n    (T : Type -> Type)\n    `{DecoratedMonad W T}.\n\n  Import\n    Algebraic.Decorated.Monad.ToKleisli.Operation\n    Algebraic.Monad.ToKleisli.Operation\n    Algebraic.Monad.ToKleisli.Instance.\n\n  Definition kcompose_dm {A B C} :\n    (W * B -> T C) ->\n    (W * A -> T B) ->\n    (W * A -> T C) :=\n    fun g f =>\n      bind T g ∘ shift T ∘ cobind (prod W) (dec T ∘ f).\n\n  Definition prepromote {A B} (w : W) (f : W * A -> T B) :=\n    fun '(w', a) => f (w ● w', a).\n\n  Definition kcomposed_alt {A B C} :\n    (W * B -> T C) ->\n    (W * A -> T B) ->\n    (W * A -> T C) := fun g f '(w, a) => bindd T (prepromote w g) (f (w, a)).\n\n  Theorem kcomposed_equiv {A B C}\n          (g : W * B -> T C) (f : W * A -> T B) :\n    kcomposed_alt g f = kcompose_dm g f.\n  Proof.\n    unfold kcomposed_alt, kcompose_dm. ext [w a].\n    unfold compose; cbn.\n    unfold_ops @Bindd_alg @Bind_alg.\n    unfold id, compose; cbn.\n    unfold shift; cbn.\n    fequal. unfold compose; cbn.\n    compose near (f (w, a)) on left.\n    compose near (dec T (f (w, a))) on right.\n    rewrite (fun_fmap_fmap T).\n    compose near (dec T (f (w, a))) on right.\n    rewrite (fun_fmap_fmap T).\n    compose near (f (w, a)) on right. fequal.\n    fequal. ext [w' b]. easy.\n  Qed.\n\nEnd decorated_monad_kleisli_operations.\n\n#[local] Notation \"g ⋆dm f\" := (kcompose_dm _ g f) (at level 40) : tealeaves_scope.\n\n(** *** Kleisli category laws *)\n(******************************************************************************)\nSection decoratedmonad_kleisli_category.\n\n  Context\n    (T : Type -> Type)\n    `{DecoratedMonad W T}.\n\n  Existing Instance dmon_monoid.\n\n  Import Algebraic.Monad.ToKleisli.Operation.\n  Import Algebraic.Monad.ToKleisli.Instance.\n\n  (** Composition when <<f>> has no substitution *)\n  Theorem dm_kleisli_star1 {A B C} : forall (g : W * B -> T C) (f : W * A -> B),\n      g ⋆dm (ret T ∘ f) = g co⋆ f.\n  Proof.\n    intros. unfold kcompose_dm, cokcompose.\n    ext [w a]. unfold compose. cbn.\n    unfold compose, id; cbn.\n    compose near (f (w, a)) on left.\n    rewrite (dmon_ret W T).\n    unfold compose; cbn.\n    rewrite shift_return.\n    assert (Monoid W).\n    { eapply @dmon_monoid; eauto. }\n    rewrite (monoid_id_l).\n    compose near (w, f (w, a)) on left.\n    now rewrite (kmon_bind0 T).\n  Qed.\n\n  (** Composition when <<f>> is context-agnostic *)\n  Theorem dm_kleisli_star2 {A B C} : forall (g : W * B -> T C) (f : A -> T B),\n      g ⋆dm (f ∘ extract (W ×)) =\n      bind T g ∘ shift T ∘ fmap (W ×) (dec T ∘ f).\n  Proof.\n    intros. unfold kcompose_dm, cokcompose.\n    reassociate <- on left.\n    now rewrite <- (fmap_to_cobind (prod W)).\n  Qed.\n\n  (** Composition when <<g>> has no substitution *)\n  Theorem dm_kleisli_star3 {A B C} : forall (g : W * B -> C) (f : W * A -> T B),\n      (η T ∘ g) ⋆dm f = fmap T g ∘ shift T ∘ cobind (prod W) (dec T ∘ f).\n  Proof.\n    intros. unfold kcompose_dm, kcompose.\n    now rewrite (fmap_to_bind T).\n  Qed.\n\n  (** Composition when <<g>> is context-agnostic *)\n  Theorem dm_kleisli_star4 {A B C} : forall (g : B -> T C) (f : W * A -> T B),\n      (g ∘ extract (prod W)) ⋆dm f = bind T g ∘ f.\n  Proof.\n    intros. unfold kcompose_dm, kcompose.\n    rewrite <- (bind_fmap T).\n    change (?f ∘ fmap T (extract (prod W)) ∘ shift T ∘ ?g) with\n        (f ∘ (fmap T (extract (prod W)) ∘ shift T) ∘ g).\n    rewrite (shift_extract T).\n    repeat reassociate ->. rewrite (extract_cobind (prod W)).\n    fequal. reassociate <- on left.\n    now rewrite (dfun_dec_extract W T).\n  Qed.\n\n  Theorem dm_kleisli_id_r {B C} : forall (g : W * B -> T C),\n      g ⋆dm (ret T ∘ extract (prod W)) = g.\n  Proof.\n    intros. rewrite dm_kleisli_star1.\n    now rewrite (Comonad.cokleisli_id_r).\n  Qed.\n\n  Theorem dm_kleisli_id_l {A B} : forall (f : W * A -> T B),\n      (ret T ∘ extract (prod W)) ⋆dm f = f.\n  Proof.\n    intros. rewrite dm_kleisli_star4.\n    now rewrite (kmon_bind1 T).\n  Qed.\n\n  Theorem dm_kleisli_assoc {A B C D} : forall (h : W * C -> T D) (g : W * B -> T C) (f : W * A -> T B),\n      h ⋆dm (g ⋆dm f) = (h ⋆dm g) ⋆dm f.\n  Proof.\n    intros. unfold kcompose_dm at 3.\n  Abort.\n\nEnd decoratedmonad_kleisli_category.\n\n(** *** Specification for sub-operations *)\n(******************************************************************************)\nSection decoratedmonad_suboperations.\n\n  #[local] Generalizable Variables A B C.\n\n  Context\n    (T : Type -> Type)\n    `{DecoratedMonad W T}.\n\n  Import Algebraic.Monad.ToKleisli.Operation.\n  Import Algebraic.Monad.ToKleisli.Instance.\n  Import Algebraic.Decorated.Monad.ToKleisli.Operation.\n  Import Algebraic.Decorated.Functor.ToKleisli.Operation.\n\n  Lemma fmapd_to_bindd : forall `(f : W * A -> B),\n      fmapd T f = bindd T (ret T ∘ f).\n  Proof.\n    introv. unfold_ops @Fmapd_alg @Bindd_alg.\n    change_right (bind T (ret T ∘ f) ∘ dec T).\n    rewrite <- (bind_fmap T).\n    now rewrite (kmon_bind1 T).\n  Qed.\n\n  Lemma bind_to_bindd : forall `(f : A -> T B),\n      bind T f = bindd T (f ∘ extract (prod W)).\n  Proof.\n    introv. unfold_ops @Bindd_alg.\n    change_right (bind T (f ∘ extract (prod W)) ∘ dec T).\n    rewrite <- (bind_fmap T).\n    reassociate -> on right.\n    now rewrite (dfun_dec_extract W T).\n  Qed.\n\n  Lemma fmap_to_bindd : forall `(f : A -> B),\n      fmap T f = bindd T (ret T ∘ f ∘ extract (prod W)).\n  Proof.\n    introv.\n    Search fmapd fmap.\n    now rewrite (fmap_to_fmapd T), fmapd_to_bindd.\n  Qed.\n\nEnd decoratedmonad_suboperations.\n\n(** ** Interaction between [dec] and [bindd], [bind] *)\n(******************************************************************************)\nSection dec_bindd.\n\n  #[local] Set Keyed Unification.\n\n  Context\n    (T : Type -> Type)\n    `{DecoratedMonad W T}.\n\n  Import Operation.\n  Import Instance.\n  Import Algebraic.Monad.ToKleisli.Operation.\n  Import Algebraic.Monad.ToKleisli.Instance.\n\n  Theorem dec_bindd : forall A B (f : W * A -> T B),\n      dec T ∘ bindd T f =\n      bindd T (shift T ∘ cobind (prod W) (dec T ∘ f)).\n  Proof.\n    intros A ? f. unfold_ops @Bindd_alg.\n    do 2 reassociate <- on left.\n    rewrite (dmon_join W T).\n    reassociate -> near (fmap T f).\n    rewrite (fun_fmap_fmap T).\n    reassociate -> near (fmap T (dec T ∘ f)).\n    rewrite <- (natural (G := T ∘ prod W) (F := T) (ϕ := @dec W T _)).\n    reassociate <- on left.\n    unfold_ops @Fmap_compose.\n    change_left (join T ∘ (fmap T (shift T) ∘ fmap T (fmap (prod W) (dec T ∘ f))) ∘ dec T ∘ dec T).\n    rewrite (fun_fmap_fmap T).\n    reassociate -> on left.\n    rewrite (dfun_dec_dec W T).\n    reassociate <- on left.\n    reassociate -> near (fmap T (cojoin (A:=A) (prod W))).\n    now rewrite (fun_fmap_fmap T).\n  Qed.\n\n  Corollary dec_bind : forall A B (f : W * A -> T B),\n      dec T ∘ bind T f =\n      bindd T (shift T ∘ fmap (prod W) (dec T ∘ f)).\n  Proof.\n    introv. rewrite (bind_to_bindd T).\n    rewrite dec_bindd.\n    fequal. now ext [w a].\n  Qed.\n\nEnd dec_bindd.\n\n(** ** Composition laws for sub-operations *)\n(******************************************************************************)\nSection decoratedmonad_suboperation_composition.\n\n  Context\n    (T : Type -> Type)\n    `{Algebraic.Decorated.Monad.DecoratedMonad W T}.\n\n  Import Instance.\n  Import Operation.\n  Import Algebraic.Monad.ToKleisli.Operation.\n  Import Algebraic.Monad.ToKleisli.Instance.\n  Import Algebraic.Decorated.Monad.ToKleisli.Operation.\n  Import Algebraic.Decorated.Functor.ToKleisli.Operation.\n\n  Lemma kcompose_equiv2  {A B C} : forall (g : W * B -> T C) (f : W * A -> T B),\n      kcompose_dm T g f = Monad.kcompose_dm g f.\n  Proof.\n    intros. unfold Monad.kcompose_dm.\n    rewrite <- (kcomposed_equiv T).\n    unfold kcomposed_alt.\n    ext [w a]. fequal. now ext [w' b].\n  Qed.\n\n  Lemma bindd_fmapd {A B C} : forall (g : W * B -> T C) (f : W * A -> B),\n      bindd T g ∘ fmapd T f = bindd T (g co⋆ f).\n  Proof.\n    introv. rewrite (fmapd_to_bindd T).\n    rewrite (kmond_bindd2 T).\n    rewrite <- kcompose_equiv2.\n    now rewrite (dm_kleisli_star1 T).\n  Qed.\n\n  Corollary bind_bindd {A B C} : forall (g : B -> T C) (f : W * A -> T B),\n      bind T g ∘ bindd T f = bindd T (bind T g ∘ f).\n  Proof.\n    intros. rewrite (bind_to_bindd T).\n    rewrite (bindd_bindd T).\n    rewrite <- kcompose_equiv2.\n    rewrite (dm_kleisli_star4 T).\n    fequal. fequal. unfold_ops @Bind_alg @Bindd_alg.\n    rewrite <- (fun_fmap_fmap T).\n    do 2 reassociate -> on right.\n    now rewrite (dfun_dec_extract W T).\n  Qed.\n\n  Corollary fmapd_bindd {A B C} : forall (g : W * B -> C) (f : W * A -> T B),\n      fmapd T g ∘ bindd T f = bindd T (fmap T g ∘ shift T ∘ cobind (prod W) (dec T ∘ f)).\n  Proof.\n    intros. rewrite (fmapd_to_bindd T).\n    rewrite (bindd_bindd T).\n    rewrite <- kcompose_equiv2.\n    fequal. unfold kcompose_dm.\n    now rewrite (fmap_to_bind T).\n  Qed.\n\n  Corollary bindd_bind {A B C} : forall (g : W * B -> T C) (f : A -> T B),\n      bindd T g ∘ bind T f = bindd T (bind T g ∘ shift T ∘ fmap (prod W) (dec T ∘ f)).\n  Proof.\n    introv. rewrite (bind_to_bindd T).\n    rewrite (bindd_bindd T).\n    rewrite <- kcompose_equiv2.\n    unfold kcompose_dm.\n    reassociate <-. now rewrite <- (fmap_to_cobind (prod W)).\n  Qed.\n\n  Lemma bindd_fmap {A B C} : forall (g : W * B -> T C) (f : A -> B),\n      bindd T g ∘ fmap T f = bindd T (g ∘ fmap (prod W) f).\n  Proof.\n    intros. rewrite (fmap_to_bindd T).\n    rewrite (bindd_bindd T).\n    reassociate -> on left.\n    rewrite <- kcompose_equiv2.\n    rewrite (dm_kleisli_star1 T).\n    unfold cokcompose. now rewrite (fmap_to_cobind (prod W)).\n  Qed.\n\n  Corollary fmap_bindd {A B C} : forall (g : B -> C) (f : W * A -> T B),\n      fmap T g ∘ bindd T f = bindd T (fmap T g ∘ f).\n  Proof.\n    intros. rewrite (fmap_to_bindd T).\n    rewrite (bindd_bindd T).\n    rewrite <- kcompose_equiv2.\n    rewrite <- (fmap_to_bindd T).\n    rewrite (dm_kleisli_star4 T).\n    now rewrite <- (fmap_to_bind T).\n  Qed.\n\nEnd decoratedmonad_suboperation_composition.\n", "meta": {"author": "dunnl", "repo": "tealeaves", "sha": "8dd6ba8acdd097f6e474ae2a1a9b10f5cc9ca65b", "save_path": "github-repos/coq/dunnl-tealeaves", "path": "github-repos/coq/dunnl-tealeaves/tealeaves-8dd6ba8acdd097f6e474ae2a1a9b10f5cc9ca65b/Tealeaves/Kleisli Theory/Decorated/Monad/KleisliTheory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2729725100738839}}
{"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 A B C P Q Q0 Y B0 : Universe, ((wd_ P Q /\\ (wd_ B Q /\\ (wd_ A B /\\ (wd_ P B /\\ (wd_ C B /\\ (wd_ P Q0 /\\ (wd_ C P /\\ (wd_ B B0 /\\ (wd_ A B0 /\\ (wd_ B Q0 /\\ (wd_ A Q0 /\\ (wd_ A C /\\ (wd_ P Y /\\ (wd_ B B0 /\\ (wd_ P Y /\\ (col_ B A P /\\ (col_ Q P Q0 /\\ (col_ B C Y /\\ (col_ P Q0 Y /\\ (col_ B P Y /\\ col_ B0 P Y)))))))))))))))))))) -> col_ B P Q)).\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_0397.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.2729146744398889}}
{"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 DEX_ReturnState := DEX_Heap.t * DEX_ReturnVal.\n\n\n  Inductive DEX_NormalStep (p:DEX_Program) : \n    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, (h, regs)) (pc', (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, (h, regs)) (pc', (h, regs'))\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, (h, regs)) (pc', (h, regs'))\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, (h, regs)) ((DEX_OFFSET.jump pc o), (h, regs))\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, (h, regs)) ((DEX_OFFSET.jump pc o), (h, regs))\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, (h, regs)) (pc', (h, regs))\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, (h, regs)) ((DEX_OFFSET.jump pc o), (h, regs))\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, (h, regs)) (pc', (h, regs))\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, (h, regs)) (pc', (h, regs'))\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, (h, regs)) (pc', (h, regs'))\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, (h, regs)) (pc', (h, regs'))\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, (h, regs)) (pc', (h, regs'))\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, (h, regs)) (pc', (h, regs'))\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, (h, regs)) (pc', (h, regs'))\n\n  | new : forall h m pc pc' regs regs' c rt loc h',\n\n    instructionAt m pc = Some (DEX_New rt c) ->\n    In rt (DEX_Registers.dom regs) ->\n    next m pc = Some pc' ->\n    DEX_Heap.new h p (DEX_Heap.DEX_LocationObject c) = Some (pair loc h') ->\n    regs' = DEX_Registers.update regs rt (Ref loc) -> \n\n    DEX_NormalStep p m (pc,(h,regs)) (pc',(h',regs'))\n\n  | iput : forall h m pc pc' regs f rs ro loc cn k v,\n\n    instructionAt m pc = Some (DEX_Iput k rs ro f) ->\n    In rs (DEX_Registers.dom regs) ->\n    In ro (DEX_Registers.dom regs) ->\n    next m pc = Some pc' ->\n    Some (Ref loc) = DEX_Registers.get regs ro ->\n    Some v = DEX_Registers.get regs rs ->\n    DEX_Heap.typeof h loc = Some (DEX_Heap.DEX_LocationObject cn) -> \n    defined_field p cn f ->\n    assign_compatible p h v (DEX_FIELDSIGNATURE.type (snd f)) ->\n\n    DEX_NormalStep p m (pc,(h,regs)) \n      (pc',(DEX_Heap.update h (DEX_Heap.DEX_DynamicField loc f) v, regs))\n\n  | getfield : forall h m pc pc' regs regs' rt ro loc f k v cn,\n\n    instructionAt m pc = Some (DEX_Iget k rt ro f) ->\n    In rt (DEX_Registers.dom regs) ->\n    In ro (DEX_Registers.dom regs) ->\n    next m pc = Some pc' ->\n    Some (Ref loc) = DEX_Registers.get regs ro ->\n    DEX_Heap.typeof h loc = Some (DEX_Heap.DEX_LocationObject cn) -> \n    defined_field p cn f ->\n    DEX_Heap.get h (DEX_Heap.DEX_DynamicField loc f) = Some v ->    \n    regs' = DEX_Registers.update regs rt v ->\n\n    DEX_NormalStep p m (pc,(h, regs)) (pc',(h, regs'))\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, (h, regs)) (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, (h, regs)) (h, Normal (Some val))\n.\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\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 (h, Normal ov) ->\n     DEX_exec_return p m s (h, Normal ov)\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 \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\n Definition DEX_Reachable P M s s' := \n   exists M',  ClosReflTrans (DEX_ReachableStep P) (M,s) (M',s').", "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_BigStepLoad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.38491214448393357, "lm_q1q2_score": 0.2729100752653612}}
{"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\nRequire Export DistributedReferenceCounting.machine2.alternate.\nRequire Export DistributedReferenceCounting.machine2.invariant0.\nRequire Export DistributedReferenceCounting.machine2.invariant1.\nRequire Export DistributedReferenceCounting.machine2.invariant2.\nRequire Export DistributedReferenceCounting.machine2.invariant3.\nRequire Export DistributedReferenceCounting.machine2.invariant4.\n\nUnset Standard Proposition Elimination Names.\n\n(* Changes\n   - proof of  1  for false_rt_D_queue.\n   - proof of  1  for  legal_alternate.\n   - owner_st_positive and its proof.\n*)\n\nSection INVARIANT5.\n\n(* In this file, we establish the following inequality\n   Int + Sum copy + Sum dec - Sum inc_dec >= 0\n\n*) \n\n\n(* The message queue between a site and the owner has a particular\nstructure.  Messages dec and inc_dec are alternated.\n *)\n\n\nLemma false_rt_D_queue :\n forall (c : Config) (s : Site),\n legal c -> rt c s = false -> D_queue (bm c s owner).\nProof.\n   intros c s H; elim H.\n   simpl in |- *.\n   intro.\n   apply D_empty.\n   \n   simple induction t; simpl in |- *; intros.\n\n   (*  1 *)\n\n   case (eq_queue_dec s1 s s2 owner); intro.\n   decompose [and] a0.\n   generalize a; rewrite H3; unfold access in |- *.\n   rewrite H2; intro.\n   discriminate.\n\n\n   apply D_post_elsewhere; auto.\n\n   (*  2 *)\n   apply D_collect; auto.\n   \n   (*  3 *)\n\n   apply D_post_elsewhere.\n   right.\n   apply (not_owner_inc3 c0 s1 owner H0 s3).\n   apply first_in.\n   auto.\n   apply D_collect.\n   auto.\n   \n   (*  4 *)\n\n   case (eq_queue_dec s2 s s1 owner); intros; simpl in |- *.\n   decompose [and] a.\n   rewrite H3; rewrite H4.\n   apply D_post_dec.\n   \n   apply D_post_elsewhere.\n   auto.\n\n   apply D_collect; auto.\n   \n   (* 5 *)\n\n   case (eq_site_dec s s2); intro.\n   generalize H2; rewrite e1; unfold Set_rec_table in |- *; rewrite that_site.\n   intro; discriminate.\n   \n   apply D_collect.\n   apply H1.\n   generalize H2; unfold Set_rec_table in |- *; rewrite other_site; auto.\n\n   (*  6 *)\n   \n   case (eq_site_dec s s2); intro.\n   generalize H2; rewrite e1; unfold Set_rec_table in |- *; rewrite that_site;\n    intro; discriminate.\n   \n   apply D_post_elsewhere; auto.\n   apply D_collect; auto.\n   apply H1; generalize H2; unfold Set_rec_table in |- *; rewrite other_site;\n    auto.\n\n   (*  7 *)\n   \n   case (eq_site_dec s0 s); intro.\n   rewrite e1; apply D_post_dec.\n   \n   apply D_post_elsewhere; auto.\n   apply H1; generalize H2; unfold Reset_rec_table in |- *;\n    rewrite other_site; auto.\nQed.\n\n\nLemma legal_alternate :\n forall (s : Site) (c : Config), legal c -> alternate (bm c s owner).\nProof.  \n  intros; elim H.\n  apply alt_null.\n  \n  simple induction t; simpl in |- *; intros.\n  \n  (* 1 *)\n\n  case (eq_queue_dec s1 s s2 owner); intro.\n  decompose [and] a0.\n  rewrite H2; rewrite H3; rewrite post_here.\n  apply alt_any_alt; auto.\n  intro; discriminate.\n  \n  rewrite post_elsewhere.\n  auto.\n  \n  auto.\n  \n  (* 2 *)\n  apply alt_collect; auto.\n  \n  (* 3 *)\n  apply alt_post_elsewhere.\n  right.\n  apply (not_owner_inc3 c0 s1 owner H0 s3).\n  apply first_in.\n  auto.\n  apply alt_collect; auto.\n  \n  (* 4 *)\n  \n  case (eq_queue_dec s2 s s1 owner); intros.\n  decompose [and] a.\n  rewrite H2; rewrite H3.\n  apply alt_post_any.\n  intro; discriminate.\n  \n  apply alt_collect; auto.\n  \n  apply alt_post_elsewhere; auto.\n  apply alt_collect; auto.\n  \n  (* 5 *)\n  \n  apply alt_collect; trivial.\n  \n  (* 6 *)\n  \n  case (eq_site_dec s2 s); intro.\n  rewrite e1; apply alt_post_inc.\n  apply alt_collect; trivial.\n  rewrite collect_elsewhere.\n  generalize (false_rt_D_queue c0 s2 H0 e); intro.\n  rewrite e1 in H2.\n  elim H2.\n  auto.\n  auto.\n  case (eq_site_dec s1 s); intro.\n  rewrite e2 in n; auto.\n  auto.\n  apply alt_post_elsewhere; auto.\n  apply alt_collect; trivial.\n  \n  (* 7 *)\n  \n  case (eq_site_dec s0 s); intro.\n  rewrite e1; apply alt_post_any; auto.\n  intro; discriminate.\n  \n  apply alt_post_elsewhere; auto.\nQed.\n\nLemma count_inc_and_dec_alt_queue :\n forall q : queue Message,\n alternate q ->\n (reduce Message dec_count q + 1 >= reduce Message new_inc_count q)%Z.\nProof.\n  intros.\n  elim H.\n  simpl in |- *; omega.\n  \n  intro; simpl in |- *; omega.\n  \n  simpl in |- *; intros.\n  generalize H0; case m; simpl in |- *.\n  intro; omega.\n  \n  intros.\n  elim (H3 s); auto.\n  \n  intro; omega.\n  \n  simpl in |- *; intros.\n  omega.\nQed.\n\n\nLemma count_inc_and_dec_D_queue :\n forall q : queue Message,\n alternate q ->\n D_queue q ->\n (reduce Message dec_count q >= reduce Message new_inc_count q)%Z.\nProof.\n  intros q H.\n  elim H; intros.\n  simpl in |- *; omega.\n  \n  absurd (D_queue (input Message (inc_dec s0) (empty Message))).\n  apply not_D_queue.\n  discriminate.\n  auto.\n  \n  generalize H3.\n  case m.\n  intro; simpl in |- *.\n  generalize (count_inc_and_dec_alt_queue qm H1); intro; omega.\n  \n  intros.\n  absurd (D_queue (input Message (inc_dec s) qm)).\n  apply not_D_queue.\n  discriminate.\n  auto.\n  \n  intros.\n  absurd (D_queue (input Message copy qm)).\n  apply not_D_queue.\n  discriminate.\n  auto.\n  \n  absurd (D_queue (input Message (inc_dec s0) (input Message dec qm))).\n  apply not_D_queue.\n  discriminate.\n  \n  auto.\nQed.\n\n\nLemma copy_count_is_positive :\n forall q : queue Message, (reduce Message copy_count q >= 0)%Z.\nProof.\n  intros.\n  apply reduce_positive_or_null.\n  intro.\n  elim a; simpl in |- *; intros; omega.\nQed.\n\nLemma dec_count_is_positive :\n forall q : queue Message, (reduce Message dec_count q >= 0)%Z.\nProof.\n  intros.\n  apply reduce_positive_or_null.\n  intro.\n  elim a; simpl in |- *; intros; omega.\nQed.\n\n\nLemma invariant5 :\n forall c : Config,\n legal c ->\n forall s : Site,\n (Int (rt c s) + reduce Message dec_count (bm c s owner) +\n  reduce Message copy_count (bm c owner s) -\n  reduce Message new_inc_count (bm c s owner) >= 0)%Z.\n\nProof.\n  intros.\n  generalize (copy_count_is_positive (bm c owner s)); intro.\n  generalize (legal_alternate s c H); intro.\n  case (eq_bool_dec (rt c s)); intro; rewrite e; unfold Int in |- *.\n  generalize (count_inc_and_dec_alt_queue (bm c s owner) H1); intro.\n  omega.\n  \n  generalize (false_rt_D_queue c s H e); intro.\n  generalize (count_inc_and_dec_D_queue (bm c s owner) H1 H2); intro.\n  omega.\nQed.\n\n\n\n\nLet Recv_T := Site -> bool.\n\nLemma other_definition_for_sigma_receive_table :\n forall t : Recv_T,\n sigma_receive_table t =\n sigma_table Site LS Z (Z_id Site) (fun s : Site => Int (t s)).\nProof.\n  intros.\n  unfold sigma_receive_table in |- *.\n  unfold sigma_table in |- *.\n  unfold Z_id in |- *.\n  auto.\nQed.\n\n\nRemark add_reduce : forall x : Z, (x + 1 - 1)%Z = x.\nProof.\n  intro; omega.\nQed.\n\n\nLemma owner_st_positive : forall c : Config, legal c -> (st c owner >= 0)%Z.\nProof.\n  intros.\n  rewrite (invariant4 c H).\n  rewrite other_definition_for_sigma_receive_table.\n  rewrite <- sigma_same_table.\n  rewrite <- sigma_same_table.\n  rewrite <- sigma_same_table2.\n  unfold Z_id in |- *.\n  unfold fun_minus in |- *.\n  unfold fun_sum in |- *.\n  rewrite sigma_sigma_but_owner.\n  rewrite owner_rt_true.\n  rewrite empty_q_to_me.\n  simpl in |- *.\n  simpl in |- *.\n  rewrite add_reduce.\n  unfold sigma_table_but_owner in |- *.\n  apply sigma_but_pos.\n  exact (invariant5 c H).\n  auto.\n  auto.\nQed.\n\n\n\nEnd INVARIANT5.\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/invariant5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2729037844611154}}
{"text": "(*\n * Copyright © 2013 http://io7m.com\n *\n * Permission to use, copy, modify, and/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *)\n(** Virtual paths. *)\nRequire Coq.Lists.List.\nRequire Coq.Strings.String.\nRequire ListAux.\nRequire ListMapWeak.\nRequire ListSetWeak.\nRequire MapWeak.\nRequire Names.\nRequire SetWeak.\n\nImport ListAux.Notations.\n\nOpen Scope string_scope.\nOpen Scope list_scope.\n\n(** A virtual path represents a path in the virtual filesystem.\n\nVirtual paths are always absolute.\n\nThe concrete syntax of virtual paths is given by the following EBNF\ngrammar (where [name] indicates a string representing a \nvalid [Names.name]):\n\n<<\npath = \"/\" , [ name , (\"/\" , name)* ] ;\n>>\n\nA virtual path is conceptually a list of [Names.name],\nwith the empty list representing the root directory. *)\nDefinition t := list Names.t.\n\nDefinition root : t := nil.\n\n(** Some example virtual paths include: [/bin], and \n[/usr/bin/ps]. *)\nExample bin        : t := Names.bin :: nil.\n\nExample usr_bin_ps : t := Names.usr :: Names.bin :: Names.ps :: nil.\n\n(** Because equality of [Names.name] is decidable, equality\n    of [t] is too. *)\nTheorem eq_decidable : forall (p0 p1 : t),\n  {p0 = p1}+{~p0 = p1}.\nProof.\n  apply List.list_eq_dec.\n  apply Names.eq_decidable.\nQed.\n\n(** The property of [p0] being an ancestor of [p1]. [p0] is an ancestor\nof [p1] iff:\n- [p0] is not equal to [p1], and\n- [p0] is a prefix of [p1]\n*)\nDefinition is_ancestor_of (p0 p1 : t) : Prop :=\n  (p0 <> p1) /\\ (ListAux.is_prefix p0 p1).\n\n(** The property of [p0] being the parent of [p1]. [p0] is the parent\nof [p1] iff:\n- [p0] is an ancestor of [p1], and\n- There exists some [x] such that [p0 @@ x = p1]\n*)\nDefinition is_parent_of (p0 p1 : t) : Prop :=\n  (is_ancestor_of p0 p1) /\\ (exists x, p0 @@ x = p1).\n\n(** The [root] path is an ancestor of any non-[root] path. *)\nTheorem is_ancestor_of_root : forall (p : t),\n  p <> root -> is_ancestor_of root p.\nProof.\n  unfold is_ancestor_of.\n  intros p Hn.\n  split.\n    apply not_eq_sym.\n    assumption.\n    induction p as [|px pr].\n      contradict Hn; reflexivity.\n      exact I.\nQed.\n\n(** The [root] path has no ancestors. *)\nTheorem is_ancestor_of_root_false : forall (p : t),\n  ~is_ancestor_of p root.\nProof.\n  unfold is_ancestor_of.\n  induction p; intuition.\nQed.\n\n(** The [root] path has no parent. *)\nTheorem is_parent_of_root_false : forall (p : t),\n  ~is_parent_of p root.\nProof.\n  unfold root.\n  unfold is_parent_of.\n  induction p; intuition.\n    inversion H1.\n    contradict H. apply ListAux.append_element_not_equal.\n    inversion H0.\n    contradict H3.\nQed.\n\n(** Iff a path has a single element, then its parent is the [root]. *)\nTheorem is_parent_of_root_single : forall (x : Names.t),\n  is_parent_of root (x :: nil).\nProof.\n  unfold root.\n  unfold is_parent_of.\n  unfold is_ancestor_of.\n  intro x.\n  split.\n  split.\n    discriminate.\n    exact I.\n    exists x; reflexivity.\nQed.\n\n(** Being an ancestor is decidable. *)\nTheorem is_ancestor_of_decidable : forall (p0 p1 : t),\n  {is_ancestor_of p0 p1}+{~is_ancestor_of p0 p1}.\nProof.\n  unfold is_ancestor_of.\n  intros p0 p1.\n  destruct (eq_decidable p0 p1).\n    right; rewrite e; intuition.\n    destruct (ListAux.is_prefix_decidable Names.eq_decidable p0 p1).\n      left; intuition.\n      right; intuition.\nQed.\n\n(** Being a parent is decidable. *)\nTheorem is_parent_of_decidable : forall (p0 p1 : t),\n  {is_parent_of p0 p1}+{~is_parent_of p0 p1}.\nProof.\n  intros p0 p1.\n  unfold is_parent_of   in *.\n  unfold is_ancestor_of in *.\n  destruct (is_ancestor_of_decidable p0 p1).\n    destruct i.\n    destruct (ListAux.append_element_decidable Names.eq_decidable p0 p1).\n      left; intuition.\n      right; intuition.\n    unfold is_parent_of   in *.\n    unfold is_ancestor_of in *.\n    right; intuition.\nQed.\n\n(** Being an ancestor is transitive. *)\nTheorem is_ancestor_of_transitive : forall (p0 p1 p2 : t),\n  is_ancestor_of p0 p1 -> is_ancestor_of p1 p2 -> is_ancestor_of p0 p2.\nProof.\nAdmitted.\n\n(** The property of [p0] containing [p1]. The path [p0] is said to\ncontain [p1] iff:\n- [p0 = p1], or\n- [p0] is an ancestor of [p1] *)\nDefinition contains (p0 p1 : t) :=\n  (p0 = p1) \\/ (is_ancestor_of p0 p1).\n\n(** [contains] is decidable. *)\nTheorem contains_decidable : forall (p0 p1 : t),\n  {contains p0 p1}+{~contains p0 p1}.\nProof.\n  unfold contains.\n  intros p0 p1.\n  destruct (eq_decidable p0 p1).\n  destruct (is_ancestor_of_decidable p0 p1).\n    left; left; assumption.\n    left; left; assumption.\n  destruct (is_ancestor_of_decidable p0 p1).\n    left; right; assumption.\n    right; tauto.\nQed.\n\n(** All paths contain themselves. *)\nTheorem contains_self : forall (p : t),\n  contains p p.\nProof.\n  left; reflexivity.\nQed.\n\n(** If [p] is contained by [root], then [p = root]. *)\nTheorem contains_is_root : forall (p : t),\n  contains p root -> p = root.\nProof.\n  unfold contains.\n  unfold is_ancestor_of.\n  intros p Hc.\n  induction p as [|ph pr].\n    reflexivity.\n    destruct Hc as [HL|HR].\n      assumption.\n      destruct HR as [HRL HRR].\n        inversion HRR.\nQed.\n\n(** Containment is transitive. *)\nTheorem contains_trans : forall (p q r : t),\n  contains p q -> contains q r -> contains p r.\nProof.\n  intros p q r Hpq Hqr.\n  unfold contains in *.\n  unfold is_ancestor_of in *.\n  destruct Hpq as [HpqL|HpqR].\n    destruct Hqr as [HqrL|HqrR].\n      left; apply (eq_trans HpqL HqrL).\n      rewrite HpqL.\n      right; assumption.\n    destruct Hqr as [HqrL|HqrR].\n      rewrite <- HqrL.\n      right; assumption.\nAdmitted.\n\n(** Paths can be \"subtracted\" to remove common prefixes. This\nis useful for calculating the paths of files inside archives mounted\ninto a filesystem. As an example, if an archive [A] is mounted at\n[/usr] and [A] contains the path [/bin/ps], then\n[subtract /usr/bin/ps /usr = /bin/ps].\n\nSo, if [contains p1 p0], then subtraction removes the first\n[length p1] elements of [p0]. *)\nDefinition subtract (p0 p1 : t) : t :=\n  match contains_decidable p1 p0 with\n  | left _  => List.skipn (length p1) p0\n  | right _ => p0\n  end.\n\n(** As stated, [subtract /usr/bin/ps /usr = /bin/ps]. *)\nExample subtract_usr : subtract usr_bin_ps (Names.usr :: nil) = Names.bin :: Names.ps :: nil.\nProof.\n  compute.\n  destruct contains_decidable as [Hc|Hnc].\n    reflexivity.\n    contradict Hnc.\n      right; compute; intuition.\n      inversion H.\nQed.\n\n(** Attempting to subtract [p1] from [p0] when [p1] does not contain [p0]\ndoes nothing. *)\nTheorem contains_subtract_false : forall (p0 p1 : t),\n  ~contains p1 p0 -> subtract p0 p1 = p0.\nProof.\n  intros p0 p1 Hna.\n  unfold subtract.\n  destruct (contains_decidable p1 p0).\n    contradiction.\n    reflexivity.\nQed.\n\n(** If [p1] contains [p0], then subtracting [p1] from [p0] reduces\nthe length of [p0] by [length p1]. *)\nTheorem contains_subtract_length : forall (p0 p1 : t),\n  contains p1 p0 -> length (subtract p0 p1) = length p0 - length p1.\nProof.\n  intros p0 p1.\n  unfold subtract.\n  destruct (contains_decidable p1 p0).\n    intros; apply ListAux.skipn_length.\n    intros; contradiction.\nQed.\n\n(** If [p0 = p1], then [subtract p0 p1 = root]. *)\nTheorem contains_subtract_is_root : forall (p0 p1 : t),\n  p0 = p1 -> subtract p0 p1 = root.\nProof.\n  intros p0 p1 H_eq.\n  unfold subtract.\n  rewrite H_eq.\n  destruct (contains_decidable p1 p1) as [Hc|Hnc].\n    apply ListAux.skipn_0.\n    contradict Hnc.\n    left; reflexivity.\nQed.\n\n(** Subtracting anything from [root] results in [root]. *)\nTheorem subtract_root : forall (p : t),\n  subtract root p = root.\nProof.\n  intros p.\n  unfold subtract.\n  destruct (contains_decidable p root).\n    destruct p; reflexivity.\n    reflexivity.\nQed.\n\n(** Subtracting anything from [root] results in [root]. *)\nTheorem subtract_from_root : forall (p : t),\n   subtract root p = root.\n Proof.\n   intros p.\n   unfold subtract.\n   destruct (contains_decidable p root).\n     destruct p; reflexivity.\n     reflexivity.\n Qed.\n\n(** Subtracting [root] from [p] results in [p]. *)\nTheorem subtract_root_from : forall p,\n  subtract p root = p.\nProof.\n  intros p.\n  unfold subtract.\n  destruct (contains_decidable root p); reflexivity.\nQed.\n\n(** Subtracting [p] from itself results in [root]. *)\nTheorem subtract_self : forall p,\n  subtract p p = root.\nProof.\n  intros p.\n  unfold subtract.\n  destruct (contains_decidable p p) as [Hc|Hnc].\n    induction p.\n      reflexivity.\n      apply IHp.\n      left; reflexivity.\n    contradict Hnc.\n      left; reflexivity.\nQed.\n\nTheorem contains_subtract_id : forall (p0 p1 : t),\n  contains p0 p1 -> p0 ++ (subtract p1 p0) = p1.\nProof.\n  unfold contains.\n  unfold is_ancestor_of.\n  induction p0 as [|p0h p0r].\n    destruct p1 as [|p1h p1r].\n      intros; simpl. apply subtract_from_root.\n      intros; simpl. apply subtract_root_from.\n    intros p1 H.\n    destruct H as [HL|HR].\n      rewrite HL.\n      rewrite subtract_self.\n      unfold root.\n      auto with *.\n    destruct p1 as [|p1h p1r].\n      destruct HR as [HRL HRR].\n        contradict HRR.\n      destruct HR as [HRL HRR].\n        destruct HRR as [HRRL HRRR].\n          simpl in *.\n          rewrite HRRL.\nAdmitted.\n\n(** The sequential enumeration of the ancestors of [p] is\na list of the ancestors of [p] starting with the most distant\nancestor first.\n\nAs an example, given a path [/usr/bin/ps], a sequential\nenumeration of the ancestors would result in a list\n[/ :: /usr :: /usr/bin :: nil].\n\nThe [Enumeration] module provides a function to calculate the\nenumeration. *)\nModule Type EnumerationSignature.\nParameter enumeration : t -> list t.\n\n(** The [enumeration] of the [root] is empty. *)\nParameter enumeration_root : enumeration root = nil.\n\n(** Therefore, if the enumeration of [p] is empty, then [p = root]. *)\nParameter enumeration_is_root : forall (p : t),\n  enumeration p = nil -> p = root.\n\n(** All paths returned by [enumeration] are ancestors of the original non-empty path. *)\nParameter enumeration_ancestors : forall (p q : t),\n  p <> root -> (List.In q (enumeration p) <-> is_ancestor_of q p).\nEnd EnumerationSignature.\n\n(** The actual implementation of the [enumeration] function. *)\nModule Enumeration <: EnumerationSignature.\n\nDefinition enumeration (e : t) :=\n  match e with\n  | nil    => nil\n  | _ :: _ => ListAux.prefixes e\n  end.\n\n(** The [enumeration] of the [root] is empty. *)\nTheorem enumeration_root :\n  enumeration nil = nil.\nProof.\n  reflexivity.\nQed.\n\n(** Therefore, if the enumeration of [p] is empty, then [p = root]. *)\nTheorem enumeration_is_root : forall (p : t),\n  enumeration p = nil -> p = root.\nProof.\n  induction p as [|ph pr].\n    auto.\n    intros.\n    simpl in H.\n    inversion H.\nQed.\n\n(** All paths returned by [enumeration] are ancestors of the original non-empty path. *)\nTheorem enumeration_ancestors : forall (p q : t),\n  p <> root -> (List.In q (enumeration p) <-> is_ancestor_of q p).\nProof.\n  intros p q H.\n  destruct p.\n    contradict H; reflexivity.\n    unfold enumeration.\n    unfold is_ancestor_of.\n    apply ListAux.prefixes_correct.\nQed.\n\nEnd Enumeration.\n\n(** As stated, [enumeration /usr/bin/ps = [/, /usr, /usr/bin]]. *)\nTheorem enum_example : Enumeration.enumeration usr_bin_ps =\n  nil :: (Names.usr :: nil) :: (Names.usr :: Names.bin :: nil) :: nil.\nProof.\n  compute.\n  reflexivity.\nQed.\n\n(** A map with virtual paths as keys. *)\nModule PathVirtualMapsKey : MapWeak.Parameters with Definition key := t.\n  Definition key              := t.\n  Definition key_eq_decidable := eq_decidable.\nEnd PathVirtualMapsKey.\n\nModule Maps := ListMapWeak.Make(PathVirtualMapsKey).\n\n(** A finite set of virtual paths. *)\nModule PathVirtualSetParameters : SetWeak.Parameters with Definition t := t.\n  Definition t              := t.\n  Definition t_eq_decidable := eq_decidable.\nEnd PathVirtualSetParameters.\n\nModule Sets := ListSetWeak.Make(PathVirtualSetParameters).\n", "meta": {"author": "io7m", "repo": "jvvfs-model2", "sha": "9093a5653a8f3e0b6209af01075f0aa30b6733d5", "save_path": "github-repos/coq/io7m-jvvfs-model2", "path": "github-repos/coq/io7m-jvvfs-model2/jvvfs-model2-9093a5653a8f3e0b6209af01075f0aa30b6733d5/PathVirtual.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2729037844611154}}
{"text": "(** This module proves Theorem 4.3 from the paper. *)\n\nFrom Coq Require Import Program.Equality Omega.\nFrom Rattus Require Export Streams FundamentalProperty.\n\n\n\nFrom Rattus Require Import Tactics.\n\nImport ListNotations.\n\n\n(* We start with the two central lemmas that prove the essence of the\ncausality property. *)\n\n\nLemma causality1 A B nu t vs :\n  closed_type A -> (forall n, isvalue (vs n)) -> (forall n, ctx_empty ⊢ (vs n) ∶ A) -> \n  ctx_empty ⊢ t ∶ Arrow (Str A) (Str B) ->\n  trrel B nu vs (app t (adv (ref thel)),heap_empty).\nProof.\n  intros CTA VT' Cvs' Ty.\n  assert (forall n, vrel_vtype A (vs n)) as VT\n      by (intros; apply trel_vrel;eauto using fund_prop_closed).\n  assert (forall n, closed_term (vs n)) as Cvs\n      by (intros n; eapply typed_closed;eauto).\n  constructor; eauto using closed_heap_empty, typed_closed, heap_empty_fresh.\n  intros s Ts Cs.\n  pose Ty as Ty'.\n  eapply fund_prop with (g:= nil) (Hs := (str_heapseq (tl (tl vs))))\n                        (s := (Some (heap_single thel (vs 0 ∷ ref thel)),\n                                         heap_single thel (vs 1 ∷ ref thel)))\n    in Ty';eauto. rewrite sub_empty_app in Ty' by auto.\n  eapply trel_app; eauto using typed_closed. eauto using str_heapseq_closed.\n  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 closed_tsubst by auto. eauto using vtype_vrel.\n  apply trel_vrel;eauto.  constructor; eauto using closed_heap_alloc, typed_closed.\n\n  apply  fund_prop_closed;eauto.\n  eauto using str_heapseq_closed, closed_heapseq_tail.\n  constructor; eauto using closed_heap_alloc, typed_closed.\n\n  eapply vrel_mono; try eapply thel_vrel;eauto.\n  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. *)\nLemma causality2 A B nu s vs :\n  vtype B -> (forall n, isvalue (vs n)) -> (forall n, ctx_empty ⊢ (vs n) ∶ A) -> \n  trrel B (S nu) vs s -> exists v' s', tred s (vs 0) v' s' /\\ trrel B nu (tl vs) s' /\\ ctx_empty ⊢ v' ∶ B.\nProof.\n  intros VTB V Ty TR. inversion TR;subst.\n  assert (vrel_vtype A (vs 0))  as Ty' by (apply trel_vrel;eauto using fund_prop_closed).\n\n  assert (exists (v' : term) (s : store),\n  {t, (Some (heap_cons h thel (vs 0 ∷ ref thel)), heap_single thel (vs 1 ∷ ref thel))}⇓ {v', s} /\\\n  vrel (S nu) (Str B) (str_heapseq (tl (tl vs))) s v') as Red.\n  eapply H1; try eassumption;eauto using tick_le_refl,str_heapseq_closed, tick_le_refl. \n  constructor; eauto using vtype_vrel_closed,closed_heap_alloc,closed_heap_empty,typed_closed.\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  destruct VR as (VR1 & VR2). autorewrite with vrel' in VR2.\n  destruct VR2 as (l & u & E & M & LR). subst. \n  \n  do 2 eexists. split. econstructor. apply R. split. constructor.\n  - assert (heap_mapsto thel (vs 1 ∷ ref thel) h2') by eauto using mapsto_heap_cons.\n    assert (closed_term (vs 1 ∷ ref thel)) by eauto using vtype_vrel_closed, typed_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,\n                closed_heap_alloc,vtype_vrel_closed.\n    eauto using closed_heap_alloc, typed_closed.\n    eauto using closed_heap_delete, closed_heap_cons_rev.\n  - eauto using vrel_delay_closed. \n  - rewrite heap_cons_delete'. rewrite heap_cons_eq.\n    inversion M. subst. simpl in LR.\n    rewrite heap_overwrite'; eauto using mapsto_heap_cons.\n    eapply trel_adv; try eassumption.\n  - rewrite tsubst_vtype in VR1. eauto using vtype_typing. assumption.\nQed.\n\n(* Finally we use the above two lemmas to prove the causality\nproperty. In particular we construct infinite reduction sequences of\nthe form\n\n  (t0,h0) --[v0/v'0]--> (t1,h1) --[v1/v'1]--> (t2,h2) --[v2/v'2]-->\n  ...\n\nwhere vi is the input value (of type A) given at the ith step and\neach v'i is the corresponding output value (of type B). Such infinite\nreduction sequences are represented by the coinductive type [Sred B vs\n(t0,h0)] defined below, where vs maps i to vi.  *)\n\n\n(* [Tred A vs s] indicates that there is an infinite stream transducer\nreduction that takes inputs [vs], starts with state [s], and produces\nwell-typed output of type A. *)\n\n\nCoInductive Tred (A : type) (vs : nat -> term) (s : state) : Prop :=\n  mkSred (nextState : state) (output : term) :\n         ctx_empty ⊢ output ∶ A ->\n         tred s (vs 0) output nextState ->\n         Tred A (tl vs) nextState -> Tred A vs s.\n\n\n(* [Tred' A vs n s] represents finitary approximations of [Tred A vs\ns] of length n, i.e. the first n reductions. This type is used for\nconstructing the proof of [Tred]. *)\n\n\nInductive Tred' (A : type) (vs : nat -> term) :  nat -> state -> Prop :=\n| mkSred' n s (nextState' : state)\n          (output' : term) :\n    ctx_empty ⊢ output' ∶ A ->\n    tred s (vs 0) output' nextState' ->\n    Tred' A (tl vs) n nextState' -> Tred' A vs (S n) s\n| doneSred' s : Tred' A vs 0 s.\n\n#[global] Hint Constructors Tred' : core.\n\nLemma tred_determ s v v1 v2 s1 s2 : tred s v v1 s1 -> tred s v v2 s2 -> v1 = v2 /\\ s1 = s2.\nProof.\n  intros SR1. intros SR2. dependent destruction SR1. dependent destruction SR2.\n  eapply red_determ in H; eauto. destruct H as (H1 & H2).\n  inversion H1. inversion H2. subst. eauto.\nQed.\n\nLemma tred'_tred' A s vs :\n  (forall n vs, Tred' A vs n s) -> Tred A vs s.\nProof.\n  generalize dependent s. generalize dependent vs. cofix IH. intros vs s SR. \n\n  pose (SR 1 vs) as S1. dependent destruction S1. subst.\n  econstructor;try eassumption.\n  apply IH. intros n vs'.\n\n  pose (SR (S n) (cons (vs 0) vs')) as Sn. dependent destruction Sn.\n  eapply tred_determ in H0;eauto. destruct H0; subst. assumption.\nQed.\n\nLemma tred'_tred A s vs P : (forall n, P (vs n)) ->\n  (forall n vs, (forall n, P (vs n)) -> Tred' A vs n s) ->  Tred A vs s.\nProof.\n  generalize dependent s. generalize dependent vs. cofix IH. intros vs s PS SR . \n\n  pose (SR 1 vs) as S1. dependent destruction S1. subst. auto.\n  econstructor;try eassumption.\n  apply IH. eauto. intros n vs' PS'.\n  assert (forall n : nat, P (cons (vs 0) vs' n)) as PS''.\n  intros. destruct n0; simpl; eauto.\n  pose (SR (S n) (cons (vs 0) vs') PS'') as Sn. dependent destruction Sn.\n  eapply tred_determ in H0;eauto. destruct H0; subst. assumption.\nQed.\n\n\nLemma causality' A B t vs:\n  closed_type A -> vtype B -> ctx_empty ⊢ t ∶ Arrow (Str A) (Str B) ->\n  (forall n, isvalue (vs n)) -> (forall n, ctx_empty ⊢ (vs n) ∶ A) -> \n  forall n, Tred' B vs n (app t (adv (ref thel)), heap_empty).\nProof.\n  intros CTA VTB Ty Vs Ts n.\n  apply causality1 with (nu := n) (vs :=vs) in Ty; eauto.\n  generalize dependent (app t (adv (ref thel)),heap_empty).\n  clear t. generalize dependent vs. induction n;intros.\n  - constructor.\n  - eapply causality2 in Ty;eauto. autodest. \nQed.\n\n\n(* Theorem 4.2 from the paper *)\nTheorem causality A B t vs :\n  closed_type A -> vtype B -> ctx_empty ⊢ t ∶ Arrow (Str A) (Str B) -> \n  (forall n, isvalue (vs n)) -> (forall n, ctx_empty ⊢ (vs n) ∶ A) -> \n  Tred B vs (app t (adv (ref thel)), heap_empty).\nProof.\n  intros. remember (fun v => isvalue v /\\ ctx_empty ⊢ v ∶ A) as P.\n  assert (forall n, P (vs n)) as Pn by (subst;split;eauto).\n\n  eapply tred'_tred with (P:=P). apply Pn. subst. intros.\n  eapply causality'. apply H. eauto. eauto.\n  intros m. pose (H4 m). tauto. intros m. pose (H4 m). tauto.\nQed.\n", "meta": {"author": "pa-ba", "repo": "Rattus-coq", "sha": "4c983c75ffb7c28098298c60466008f03a6a1517", "save_path": "github-repos/coq/pa-ba-Rattus-coq", "path": "github-repos/coq/pa-ba-Rattus-coq/Rattus-coq-4c983c75ffb7c28098298c60466008f03a6a1517/theories/Causality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2727202743968327}}
{"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 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 valid.\nFrom CoqCat Require Import covering.\nFrom CoqCat Require Import crit_sc.\nRequire Import Classical_Prop.\nImport OEEvt.\nSet Implicit Arguments.\n\nModule StableSC (A1 A2: Archi) (dp:Dp).\nModule Wk := (* Hierarchy.*)Weaker A1 A2 dp.\nImport Wk.\nModule Covering := Covering A1b A2 dp.\nImport Covering.\nModule Crit := CritSC A1b A2 dp.\nImport Crit.\nModule VA1 := Valid A1b dp.\nImport VA1.\nModule A1Basic := Basic A1b dp.\n\nModule Preservation := Preservation Cm.\nImport Preservation.\n\n(*A2n=SC*)\nHypothesis rfe2_glob : forall E X,\n  rel_incl (rf_inter X) (A2nWmm.mhb E X).\nHypothesis ppo2_po : forall E, A2.ppo E = po_iico E.\nHypothesis rfi2_ppo2 : forall E X,\n  rel_incl (rf_intra X) (A2.ppo E).\n\nLemma v1_and_no_cy_implies_covered :\n  forall E X,\n  well_formed_event_structure E ->\n  A1bWmm.valid_execution E X ->\n  ~ (exists cy : Rln Event, crit_cy E cy) ->\n  Cm.covered E X Cm.s.\nProof.\nintros E X Hwf Hv1 Hncy e1 e2 [Hc12 [sigma [Hsigma ?]]].\nassert (exists cy : Rln Event, crit_cy E cy) as Hc.\n  exists sigma; auto.\ncontradiction.\nQed.\n\nLemma write_or_read :\n  forall E x,\n  events E x ->\n  writes E x \\/ reads E x.\nProof.\nintros E x Hex.\ncase_eq (action x); intros d l v Hax;\ncase_eq d; intro Hd; [right | left];\n  split; auto; exists l; exists v; subst; auto.\nQed.\n\nLemma tc_dom_in_evts :\n  forall E cy e1 e2,\n  well_formed_event_structure E ->\n  tc (rel_union (rel_inter cy (conflict E)) (rel_union (A1b.ppo E) (pio_llh E))) e1 e2 ->\n  In _ (events E) e1.\nProof.\nintros E cy e1 e2 Hwf Htc.\ninduction Htc as [e1 e2 Hu |]; auto.\n  inversion Hu as [Hcy | Hpo].\n    destruct Hcy as [? [? [? ?]]]; auto.\n    apply A1Basic.po_iico_domain_in_events with e2; auto.\n      inversion Hpo as [Hppo | Hpio].\n      apply A1b.ppo_valid; auto.\n      destruct Hpio as [? [? ?]]; auto.\nQed.\n\nLemma tc_ran_in_evts :\n  forall E cy e1 e2,\n  well_formed_event_structure E ->\n  tc (rel_union (rel_inter cy (conflict E)) (rel_union (A1b.ppo E) (pio_llh E))) e1 e2 ->\n  In _ (events E) e2.\nProof.\nintros E cy e1 e2 Hwf Htc.\ninduction Htc as [e1 e2 Hu |]; auto.\n  inversion Hu as [Hcy | Hpo].\n    destruct Hcy as [? [? [? ?]]]; auto.\n    apply A1Basic.po_iico_range_in_events with e1; auto.\n      inversion Hpo as [Hppo | Hpio].\n      apply A1b.ppo_valid; auto.\n      destruct Hpio as [? [? ?]]; auto.\nQed.\n\nLemma cy_inter_conflict_ppo1_partial_order :\n  forall E cy,\n  well_formed_event_structure E ->\n  acyclic (rel_union (rel_inter cy (conflict E)) (rel_union (A1b.ppo E) (pio_llh E))) ->\n  partial_order (tc (rel_union (rel_inter cy (conflict E)) (rel_union (A1b.ppo E) (pio_llh E))))\n  (events E).\nProof.\nintros E cy Hwf Hac.\n  split; [|split].\n\n    intros e1 Hu; inversion Hu as [e Hd | e Hr].\n    destruct Hd as [e2 H12].\n      apply tc_dom_in_evts with cy e2; auto.\n\n    destruct Hr as [e2 H12].\n      apply tc_ran_in_evts with cy e2; auto.\n\n    intros x1 x2 x3 [H12 H23]; apply trc_ind with x2; auto.\n\n    intros e He; apply (Hac e He).\nQed.\n\nLemma ppo1_in_le :\n  forall E cy,\n  well_formed_event_structure E ->\n  acyclic (rel_union (rel_inter cy (conflict E)) (rel_union (A1b.ppo E) (pio_llh E))) ->\n  rel_incl (A1b.ppo E) (LE (tc (rel_union (rel_inter cy (conflict E)) (rel_union (A1b.ppo E) (pio_llh E))))).\nProof.\nintros E cy Hwf Hacy;\ngeneralize (cy_inter_conflict_ppo1_partial_order Hwf Hacy);\nintro Hpart.\n    assert (Included _ (events E) (events E)) as Htriv.\n    intros e He; auto.\n    generalize (OE Htriv Hpart); intros [Hinc Hle].\nintros x y Hxy.\napply Hinc; apply trc_step; right; left; auto.\nQed.\n\nLemma pio_in_le :\n  forall E cy,\n  well_formed_event_structure E ->\n  acyclic (rel_union (rel_inter cy (conflict E)) (rel_union (A1b.ppo E) (pio_llh E))) ->\n  rel_incl (pio_llh E) (LE (tc (rel_union (rel_inter cy (conflict E)) (rel_union (A1b.ppo E) (pio_llh E))))).\nProof.\nintros E cy Hwf Hacy;\ngeneralize (cy_inter_conflict_ppo1_partial_order Hwf Hacy);\nintro Hpart.\n    assert (Included _ (events E) (events E)) as Htriv.\n    intros e He; auto.\n    generalize (OE Htriv Hpart); intros [Hinc Hle].\nintros x y Hxy.\napply Hinc; apply trc_step; right; right; auto.\nQed.\n\nLemma le_ac :\n  forall E cy,\n  linear_strict_order\n        (LE (tc (rel_union (rel_inter cy (conflict E)) (rel_union (A1b.ppo E) (pio_llh E)))))\n        (events E) ->\n  acyclic (LE (tc (rel_union (rel_inter cy (conflict E)) (rel_union (A1b.ppo E) (pio_llh E))))).\nProof.\nintros E cy Hle x Hx; generalize Hle; intro Hlin;\ndestruct_lin Hle; apply (Hac x).\nrewrite (lso_is_tc Hlin) in Hx; auto.\nQed.\n\nLemma cy_inter_conflict_ppo1_vexec :\n  forall E cy,\n  well_formed_event_structure E ->\n  acyclic (rel_union (rel_inter cy (conflict E)) (rel_union (A1b.ppo E) (pio_llh E))) ->\n  vexec E (tc (rel_union (rel_inter cy (conflict E)) (rel_union (A1b.ppo E) (pio_llh E)))).\nProof.\nintros E cy Hwf Hacy;\ngeneralize (cy_inter_conflict_ppo1_partial_order Hwf Hacy);\nintro Hpart.\n    assert (Included _ (events E) (events E)) as Htriv.\n    intros e He; auto.\n    generalize (OE Htriv Hpart); intros [Hinc Hle].\nsplit; [|split]; auto.\n\n  apply ac_incl with (LE (tc (rel_union (rel_inter cy (conflict E)) (rel_union (A1b.ppo E) (pio_llh E))))); auto.\n    apply le_ac; auto.\n    intros x y Hxy; inversion Hxy; auto.\n    apply ppo1_in_le; auto.\n\n  apply ac_incl with (LE (tc (rel_union (rel_inter cy (conflict E)) (rel_union (A1b.ppo E) (pio_llh E))))); auto.\n    apply le_ac; auto.\n    intros x y Hxy; inversion Hxy; auto.\n    apply pio_in_le; auto.\nQed.\n\nLemma cy_is_or :\n  forall E Y cy,\n  well_formed_event_structure E ->\n  A1bWmm.valid_execution E Y ->\n  acyclic (rel_union (rel_inter cy (conflict E)) (rel_union (A1b.ppo E) (pio_llh E))) ->\n  rel_incl cy (tc (rel_union (rel_inter cy (conflict E)) (A2n.ppo E))) ->\n  (rf Y =\n      so_rfm E (tc (rel_union (rel_inter cy (conflict E)) (rel_union (A1b.ppo E) (pio_llh E))))) ->\n  (ws Y = so_ws (tc (rel_union (rel_inter cy (conflict E)) (rel_union (A1b.ppo E) (pio_llh E))))) ->\n  rel_incl cy (tc (rel_union ((mhbd E Y)) (A2n.ppo E))).\nProof.\nintros E Y cy Hwf Hv Hacy Hi Hrf Hws x y Hxy.\ngeneralize (cy_inter_conflict_ppo1_partial_order Hwf Hacy);\nintro Hpart.\n    assert (Included _ (events E) (events E)) as Htriv.\n    intros e He; auto.\n    generalize (OE Htriv Hpart); intros [Hinc Hle].\n\ngeneralize (Hi x y Hxy); intro Htc.\nclear Hxy.\ninduction Htc as [x y Hu |]; auto.\n  inversion Hu as [Hc | Hppo].\n  destruct Hc as [Hxy Hc].\n  generalize Hc; intros [Hex [Hey [? [? Hw]]]].\n  inversion Hw as [Hwx | Hwy].\n\n    generalize (write_or_read E y Hey); intro Hory.\n    inversion Hory as [Hwy | Hry].\n\n    (*Wx Wy*)\n      apply trc_step; left;\n      split; auto.\n       (*split; auto.*)\n       apply A2nBasic.ws_in_mhb.\n        rewrite Hws; split.\n          apply Hinc; apply trc_step; left; split; auto.\n          exists (loc x); split; split.\n            left; exists y.\n              apply Hinc; apply trc_step; left; split; auto.\n              destruct Hwx as [? [lx [vx Hax]]]; unfold write_to; rewrite Hax.\n              exists vx; unfold loc; rewrite Hax; auto.\n            right; exists x.\n              apply Hinc; apply trc_step; left; split; auto.\n              destruct Hwy as [? [ly [vy Hay]]]; unfold write_to; rewrite Hay.\n              exists vy; rewrite H; unfold loc; rewrite Hay; auto.\n\n     (*Wx Ry -> (ws)?;rf*)\n     destruct_valid Hv.\n     generalize (Hrf_init y Hry); intros [wy [Hwy ?]].\n     generalize (eqEv_dec x wy); intros [Heq | Hneq].\n     apply trc_step; left; split; auto.\n     (*split; auto.*) apply rfe2_glob; split; auto.\n       subst; auto.\n\n       apply trc_ind with wy.\n     assert (ws Y x wy \\/ ws Y wy x) as Horxwy.\n       generalize (Hws_tot (loc x)); intro Hl.\n       destruct_lin Hl.\n         assert (In Event (writes_to_same_loc_l (events E) (loc x)) x) as Hx.\n           split; auto.\n             destruct Hwx as [? [? [vx Hwx]]]; unfold write_to;\n             rewrite Hwx; unfold loc; exists vx; rewrite Hwx; auto.\n         assert (In Event (writes_to_same_loc_l (events E) (loc x)) wy) as Hwwy.\n           split.\n             apply A1Basic.dom_rf_in_events with Y y; auto.\n               split; auto.\n             rewrite H.\n               rewrite <- A1Basic.rf_implies_same_loc2 with E Y wy y.\n             generalize (A1Basic.dom_rf_is_write E Y wy y Hrf_cands H1);\n             intros [? [vy Hwwy]]; unfold write_to;\n             rewrite Hwwy; unfold loc; exists vy; rewrite Hwwy; auto.\n       split; split; auto. auto.\n       generalize (Htot x wy Hneq Hx Hwwy); intro Hor;\n       inversion Hor as [Hxwy | Hwyx]; [left | right].\n         destruct Hxwy; auto. destruct Hwyx; auto.\n\n     inversion Horxwy as [Hxwy | Hwyx].\n     destruct (eqProc_dec (proc_of x) (proc_of wy)) as [Heqp | Hneqp].\n       apply trc_step; right; rewrite ppo2_po.\n       assert (In _ (events E) wy) as Hewy.\n         apply A2nBasic.ran_ws_in_events with Y x; auto.\n         split; auto.\n       generalize (A2nBasic.same_proc_implies_po x wy Hwf Heqp Hex Hewy);\n       intro Hor; inversion Hor; auto.\n       assert (tc (rel_union (com E Y) (pio_llh E)) x x) as Hcuni.\n         apply trc_ind with wy; apply trc_step.\n           left; right; auto.\n           right; split; [|split]; auto.\n           apply sym_eq.\n           apply A1bBasic.ws_implies_same_loc with E Y; auto.\n             split; split; auto.\n           intros [Hrwy [? [lx [vx Hax]]]].\n           destruct Hwx as [? [? [? Hwx]]].\n           rewrite Hax in Hwx; inversion Hwx.\n           unfold acyclic in Hsp; generalize (Hsp x); intro; contradiction.\n\n       apply trc_step; left; split; auto.\n         apply A2nBasic.ws_in_mhb; auto.\n\n       rewrite Hrf in H1; destruct H1 as [? [? Hmax]].\n       assert (In Event\n         (previous_writes E\n            (LE (tc (rel_union (rel_inter cy (conflict E)) (rel_union (A1b.ppo E) (pio_llh E))))) y)\n         x) as Hpwx.\n         split; auto.\n         split; auto.\n         apply Hinc; apply trc_step; inversion Hu as [|Hppo2]; [left | right]; auto.\n         generalize (A2.ppo_valid Hppo2); intro Hpo.\n         generalize (A2nBasic.po_implies_same_proc Hwf Hex Hey Hpo); intro; contradiction.\n\n       assert (LE (tc (rel_union (rel_inter cy (conflict E)) (rel_union (A1b.ppo E) (pio_llh E)))) wy x) as Hle_wyx.\n         rewrite Hws in Hwyx.\n         destruct Hwyx; auto.\n\n       assert (In Event\n         (previous_writes E\n            (LE (tc (rel_union (rel_inter cy (conflict E)) (rel_union (A1b.ppo E) (pio_llh E))))) y)\n         x /\\\n       LE (tc (rel_union (rel_inter cy (conflict E)) (rel_union (A1b.ppo E) (pio_llh E)))) wy x) as Hand.\n         split; auto.\n\n      generalize (Hmax x Hand); intro Heqwyx.\n      assert (x = wy) as Heq'.\n        auto.\n      contradiction.\n\n     destruct (eqProc_dec (proc_of wy) (proc_of y)) as [Heqp | Hneqp].\n       apply trc_step; right.\n       assert (rf_intra Y wy y) as Hrfi.\n         split; auto.\n       apply (rfi2_ppo2 E Hrfi).\n\n       apply trc_step; left; split; auto.\n       apply rfe2_glob; auto. split; auto.\n\n    generalize (write_or_read E x Hex); intro Horx.\n    inversion Horx as [Hwx | Hrx];\n      apply trc_step; left; split; auto.\n\n    (*Wx Wy*)\n       (*split; auto.*)\n       apply A2nBasic.ws_in_mhb.\n        rewrite Hws; split.\n          apply Hinc; apply trc_step; left; split; auto.\n          exists (loc x); split; split.\n            left; exists y.\n              apply Hinc; apply trc_step; left; split; auto.\n              destruct Hwx as [? [lx [vx Hax]]]; unfold write_to; rewrite Hax.\n              unfold loc; exists vx; rewrite Hax; auto.\n            right; exists x.\n              apply Hinc; apply trc_step; left; split; auto.\n              destruct Hwy as [? [ly [vy Hay]]]; unfold write_to; exists vy; rewrite Hay.\n              rewrite H; unfold loc; rewrite Hay; auto.\n\n   (*Rx Wy*)\n      (*split; auto.*)\n      apply A2nBasic.fr_in_mhb.\n        generalize Hrx; intros [Heex Hrrx]; destruct Hwy as [Heey Hwy];\n        split; [|split]; auto.\n        destruct_valid Hv.\n          generalize (Hrf_init x Hrx); intros [wx [Hewx Hwx]];\n          exists wx; split; auto.\n          rewrite Hws; split.\n          destruct_lin Hle.\n          apply Htrans with x; split.\n            rewrite Hrf in Hwx; destruct Hwx as [? Hmax].\n            destruct Hmax as [[? [? ?]] ?]; auto.\n            apply Hinc; apply trc_step; left; split; auto.\n\n            exists (loc x); split; split.\n              left; exists x.\n                rewrite Hrf in Hwx; destruct Hwx as [Hrfx Hmax].\n                destruct Hmax as [Hpw ?].\n                destruct Hpw as [? [? ?]]; auto.\n                generalize (Hrf_cands wx x Hwx);\n                intros [? [? [lx [Hwwx [[vx Hrrrx] ?]]]]].\n                unfold loc; rewrite Hrrrx; auto.\n\n              right; exists x.\n                apply Hinc; apply trc_step; left; split; auto.\n              destruct Hwy as [ly [vy Hay]]; unfold write_to; rewrite Hay.\n              rewrite H; unfold loc; exists vy; rewrite Hay; auto.\n\n  (*x ppo2 y*)\n  apply trc_step; right; auto.\n\n  apply trc_ind with z; auto.\nQed.\n\nLemma mv_implies_mvor :\n  forall E X cy,\n  well_formed_event_structure E ->\n  A1bWmm.valid_execution E X ->\n  crit_cy E cy ->\n  (exists Y, A1bWmm.valid_execution E Y /\\\n     exists cy', crit_cy_or E Y cy').\nProof.\nintros E X cy Hwf Hv1 Hcy.\ndestruct Hcy as [Hmcy [Hnac [Hi Hac1]]].\n\nassert (exists so, vexec E so /\\\n    so_rfm E so = so_rfm E (tc (rel_union (rel_inter cy (conflict E)) (rel_union (A1b.ppo E) (pio_llh E))))  /\\\n    so_ws so = so_ws (tc (rel_union (rel_inter cy (conflict E)) (rel_union (A1b.ppo E) (pio_llh E))))) as Heex.\n  exists (tc (rel_union (rel_inter cy (conflict E)) (rel_union (A1b.ppo E) (pio_llh E)))); split; [|split]; auto.\n  apply cy_inter_conflict_ppo1_vexec; auto.\n\ngeneralize (VA1.ScModel.vexec_is_valid E\n  (so_rfm E (tc (rel_union (rel_inter cy (conflict E)) (rel_union (A1b.ppo E) (pio_llh E)))))\n  (so_ws (tc ((rel_union (rel_inter cy (conflict E)) (rel_union (A1b.ppo E) (pio_llh E)))))) Hwf Heex);\nintros [Y [HvY [Hrf Hws]]]; exists Y; split; auto.\n\nexists cy; split; [|split]; auto.\n  apply cy_is_or; auto.\n  unfold sigma_wf in Hmcy; rewrite union_triv in Hmcy; auto.\nQed.\n\nLemma cy_or_in_ghb2 :\n  forall E X cy,\n  well_formed_event_structure E ->\n  crit_cy_or E X cy ->\n  rel_incl cy (tc (A2nWmm.ghb E X)).\nProof.\nintros E X cy Hwf [Hmcy [? [? ?]]] x y Hxy.\nrewrite ghb2_is_mhb_ppo2.\ngeneralize (Hmcy x y Hxy); intro Htc.\ngeneralize Htc; apply tc_incl.\nintros e1 e2 Hor.\ninversion Hor as [Hmhbd | Hppo2].\n  destruct Hmhbd as [Hmhb ?].\n    left; auto.\n  right; auto.\nQed.\n\nSet Implicit Arguments.\nLemma tc_tc :\n  forall A (r: Rln A) x y,\n  tc (tc r) x y ->\n  tc r x y.\nProof.\nintros A r x y Hxy.\ninduction Hxy; auto.\napply trc_ind with z; auto.\nQed.\n\nLemma ac_implies_tc_ac :\n  forall A (r:Rln A),\n  acyclic r ->\n  acyclic (tc r).\nProof.\nintros A r Hac x Hx.\ngeneralize (tc_tc Hx); intro Htc.\napply (Hac x Htc); auto.\nQed.\nUnset Implicit Arguments.\n\nLemma stability_to_SC :\n  forall E, well_formed_event_structure E ->\n               (exists X, A1bWmm.valid_execution E X) ->\n  ((forall X, (A1bWmm.valid_execution E X -> A2nWmm.valid_execution E X)) <->\n  (~(exists cy, crit_cy E cy))).\nProof.\nintros E Hwf [X Hv1]; split.\n  intros Hp [cy Hcy].\n  generalize (mv_implies_mvor Hwf Hv1 Hcy);\n    intros [Y [Hv1Y [cy' Hcy']]].\n  generalize (Hp Y Hv1Y); intro Hv2.\n  generalize (cy_or_in_ghb2 Hwf Hcy'); intro Hincl.\n  destruct_valid Hv2.\n  assert (acyclic (tc (A2nWmm.ghb E Y))) as Hac.\n    apply ac_implies_tc_ac; auto.\n  generalize (incl_ac Hincl Hac); intro Haccy.\n  destruct Hcy' as [? [? [Hnac ?]]].\n  contradiction.\n\n  intros Hncy Y Hv1Y.\n      generalize (v1_and_no_cy_implies_covered Hwf Hv1Y Hncy); intro Hc.\n      apply prop_implies_v2; auto.\nQed.\n\nEnd StableSC.\n", "meta": {"author": "herd", "repo": "CoqCat", "sha": "e9afddbfe4cd17de335596454b8e9de0dd8ce5c2", "save_path": "github-repos/coq/herd-CoqCat", "path": "github-repos/coq/herd-CoqCat/CoqCat-e9afddbfe4cd17de335596454b8e9de0dd8ce5c2/stable_sc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548511303336, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.27272026306210406}}
{"text": "Require Import Blech.Defaults.\n\nRequire Import Blech.Bishop.\nRequire Import Blech.Category.\nRequire Import Blech.Category.Bsh.\nRequire Import Blech.Category.Op.\nRequire Import Blech.Category.Funct.\n\nImport OpNotations.\n\nDefinition PSh (C: Category): Category := Funct (C ᵒᵖ) Bsh.\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/Category/PSh.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.27265149684898793}}
{"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(** Computation of resource bounds for Linear code. *)\n\nRequire Import FSets FSetAVL.\nRequire Import Coqlib Ordered.\nRequire Intv.\nRequire Import AST.\nRequire Import Op.\nRequire Import Machregs Locations.\nRequire Import Linear.\nRequire Import Conventions.\n\nModule RegOrd := OrderedIndexed (IndexedMreg).\nModule RegSet := FSetAVL.Make (RegOrd).\n\n(** * Resource bounds for a function *)\n\n(** The [bounds] record capture how many local and outgoing stack slots\n  and callee-save registers are used by a function. *)\n\n(** We demand that all bounds are positive or null.\n  These properties are used later to reason about the layout of\n  the activation record. *)\n\nRecord bounds : Type := mkbounds {\n  used_callee_save: list mreg;\n  bound_local: Z;\n  bound_outgoing: Z;\n  bound_stack_data: Z;\n  bound_local_pos: bound_local >= 0;\n  bound_outgoing_pos: bound_outgoing >= 0;\n  bound_stack_data_pos: bound_stack_data >= 0;\n  used_callee_save_norepet: list_norepet used_callee_save;\n  used_callee_save_prop: forall r, In r used_callee_save -> is_callee_save r = true\n}.\n\n(** The following predicates define the correctness of a set of bounds\n    for the code of a function. *)\n\nSection WITHIN_BOUNDS.\n\nVariable b: bounds.\n\nDefinition mreg_within_bounds (r: mreg) :=\n  is_callee_save r = true -> In r (used_callee_save b).\n\nDefinition slot_within_bounds (sl: slot) (ofs: Z) (ty: typ) :=\n  match sl with\n  | Local => ofs + typesize ty <= bound_local b\n  | Outgoing => ofs + typesize ty <= bound_outgoing b\n  | Incoming => True\n  end.\n\nDefinition instr_within_bounds (i: instruction) :=\n  match i with\n  | Lgetstack sl ofs ty r => slot_within_bounds sl ofs ty /\\ mreg_within_bounds r\n  | Lsetstack r sl ofs ty => slot_within_bounds sl ofs ty\n  | Lop op args res => mreg_within_bounds res\n  | Lload chunk addr args dst => mreg_within_bounds dst\n  | Lcall sig ros => size_arguments sig <= bound_outgoing b\n  | Lbuiltin ef args res =>\n       (forall r, In r (params_of_builtin_res res) \\/ In r (destroyed_by_builtin ef) -> mreg_within_bounds r)\n    /\\ (forall sl ofs ty, In (S sl ofs ty) (params_of_builtin_args args) -> slot_within_bounds sl ofs ty)\n  | _ => True\n  end.\n\nEnd WITHIN_BOUNDS.\n\nDefinition function_within_bounds (f: function) (b: bounds) : Prop :=\n  forall instr, In instr f.(fn_code) -> instr_within_bounds b instr.\n\n(** * Inference of resource bounds for a function *)\n\n(** The resource bounds for a function are computed by a linear scan\n  of its instructions. *)\n\nSection BOUNDS.\n\nVariable f: function.\n\nDefinition record_reg (u: RegSet.t) (r: mreg) : RegSet.t :=\n  if is_callee_save r then RegSet.add r u else u.\n\nDefinition record_regs (u: RegSet.t) (rl: list mreg) : RegSet.t :=\n  fold_left record_reg rl u.\n\n(** In the proof of the [Stacking] pass, we only need to bound the\n  registers written by an instruction.  Therefore, we examine the\n  result registers only, not the argument registers. *)\n\nDefinition record_regs_of_instr (u: RegSet.t) (i: instruction) : RegSet.t :=\n  match i with\n  | Lgetstack sl ofs ty r => record_reg u r\n  | Lsetstack r sl ofs ty => record_reg u r\n  | Lop op args res => record_reg u res\n  | Lload chunk addr args dst => record_reg u dst\n  | Lstore chunk addr args src => u\n  | Lcall sig ros => u\n  | Ltailcall sig ros => u\n  | Lbuiltin ef args res =>\n      record_regs (record_regs u (params_of_builtin_res res)) (destroyed_by_builtin ef)\n  | Llabel lbl => u\n  | Lgoto lbl => u\n  | Lcond cond args lbl => u\n  | Ljumptable arg tbl => u\n  | Lreturn => u\n  end.\n\nDefinition record_regs_of_function : RegSet.t :=\n  fold_left record_regs_of_instr f.(fn_code) RegSet.empty.\n\nFixpoint slots_of_locs (l: list loc) : list (slot * Z * typ) :=\n  match l with\n  | nil => nil\n  | S sl ofs ty :: l' => (sl, ofs, ty) :: slots_of_locs l'\n  | R r :: l' => slots_of_locs l'\n  end.\n\nDefinition slots_of_instr (i: instruction) : list (slot * Z * typ) :=\n  match i with\n  | Lgetstack sl ofs ty r => (sl, ofs, ty) :: nil\n  | Lsetstack r sl ofs ty => (sl, ofs, ty) :: nil\n  | Lbuiltin ef args res => slots_of_locs (params_of_builtin_args args)\n  | _ => nil\n  end.\n\nDefinition max_over_list {A: Type} (valu: A -> Z) (l: list A) : Z :=\n  List.fold_left (fun m l => Z.max m (valu l)) l 0.\n\nDefinition max_over_instrs (valu: instruction -> Z) : Z :=\n  max_over_list valu f.(fn_code).\n\nDefinition max_over_slots_of_instr (valu: slot * Z * typ -> Z) (i: instruction) : Z :=\n  max_over_list valu (slots_of_instr i).\n\nDefinition max_over_slots_of_funct (valu: slot * Z * typ -> Z) : Z :=\n  max_over_instrs (max_over_slots_of_instr valu).\n\nDefinition local_slot (s: slot * Z * typ) :=\n  match s with (Local, ofs, ty) => ofs + typesize ty | _ => 0 end.\n\nDefinition outgoing_slot (s: slot * Z * typ) :=\n  match s with (Outgoing, ofs, ty) => ofs + typesize ty | _ => 0 end.\n\nDefinition outgoing_space (i: instruction) :=\n  match i with Lcall sig _ => size_arguments sig | _ => 0 end.\n\nLemma max_over_list_pos:\n  forall (A: Type) (valu: A -> Z) (l: list A),\n  max_over_list valu l >= 0.\nProof.\n  intros until valu. unfold max_over_list.\n  assert (forall l z, fold_left (fun x y => Z.max x (valu y)) l z >= z).\n  induction l; simpl; intros.\n  lia. apply Zge_trans with (Z.max z (valu a)).\n  auto. apply Z.le_ge. apply Z.le_max_l. auto.\nQed.\n\nLemma max_over_slots_of_funct_pos:\n  forall (valu: slot * Z * typ -> Z), max_over_slots_of_funct valu >= 0.\nProof.\n  intros. unfold max_over_slots_of_funct.\n  unfold max_over_instrs. apply max_over_list_pos.\nQed.\n\n(* Move elsewhere? *)\n\nRemark fold_left_preserves:\n  forall (A B: Type) (f: A -> B -> A) (P: A -> Prop),\n  (forall a b, P a -> P (f a b)) ->\n  forall l a, P a -> P (fold_left f l a).\nProof.\n  induction l; simpl; auto.\nQed.\n\nRemark fold_left_ensures:\n  forall (A B: Type) (f: A -> B -> A) (P: A -> Prop) b0,\n  (forall a b, P a -> P (f a b)) ->\n  (forall a, P (f a b0)) ->\n  forall l a, In b0 l -> P (fold_left f l a).\nProof.\n  induction l; simpl; intros. contradiction.\n  destruct H1. subst a. apply fold_left_preserves; auto. apply IHl; auto.\nQed.\n\nDefinition only_callee_saves (u: RegSet.t) : Prop :=\n  forall r, RegSet.In r u -> is_callee_save r = true.\n\nLemma record_reg_only: forall u r, only_callee_saves u -> only_callee_saves (record_reg u r).\nProof.\n  unfold only_callee_saves, record_reg; intros.\n  destruct (is_callee_save r) eqn:CS; auto.\n  destruct (mreg_eq r r0). congruence. apply H; eapply RegSet.add_3; eauto.\nQed.\n\nLemma record_regs_only: forall rl u, only_callee_saves u -> only_callee_saves (record_regs u rl).\nProof.\n  intros. unfold record_regs. apply fold_left_preserves; auto using record_reg_only.\nQed.\n\nLemma record_regs_of_instr_only: forall u i, only_callee_saves u -> only_callee_saves (record_regs_of_instr u i).\nProof.\n  intros. destruct i; simpl; auto using record_reg_only, record_regs_only.\nQed.\n\nLemma record_regs_of_function_only:\n  only_callee_saves record_regs_of_function.\nProof.\n  intros. unfold record_regs_of_function.\n  apply fold_left_preserves. apply record_regs_of_instr_only.\n  red; intros. eelim RegSet.empty_1; eauto.\nQed.\n\nProgram Definition function_bounds := {|\n  used_callee_save := RegSet.elements record_regs_of_function;\n  bound_local := max_over_slots_of_funct local_slot;\n  bound_outgoing := Z.max (max_over_instrs outgoing_space) (max_over_slots_of_funct outgoing_slot);\n  bound_stack_data := Z.max f.(fn_stacksize) 0\n|}.\nNext Obligation.\n  apply max_over_slots_of_funct_pos.\nQed.\nNext Obligation.\n  apply Z.le_ge. eapply Z.le_trans. 2: apply Z.le_max_r.\n  apply Z.ge_le. apply max_over_slots_of_funct_pos.\nQed.\nNext Obligation.\n  apply Z.le_ge. apply Z.le_max_r.\nQed.\nNext Obligation.\n  generalize (RegSet.elements_3w record_regs_of_function).\n  generalize (RegSet.elements record_regs_of_function).\n  induction 1. constructor. constructor; auto.\n  red; intros; elim H. apply InA_alt. exists x; auto.\nQed.\nNext Obligation.\n  apply record_regs_of_function_only. apply RegSet.elements_2.\n  apply InA_alt. exists r; auto.\nQed.\n\n(** We now show the correctness of the inferred bounds. *)\n\nLemma record_reg_incr: forall u r r', RegSet.In r' u -> RegSet.In r' (record_reg u r).\nProof.\n  unfold record_reg; intros. destruct (is_callee_save r); auto. apply RegSet.add_2; auto.\nQed.\n\nLemma record_reg_ok: forall u r, is_callee_save r = true -> RegSet.In r (record_reg u r).\nProof.\n  unfold record_reg; intros. rewrite H. apply RegSet.add_1; auto.\nQed.\n\nLemma record_regs_incr: forall r' rl u, RegSet.In r' u -> RegSet.In r' (record_regs u rl).\nProof.\n  intros. unfold record_regs. apply fold_left_preserves; auto using record_reg_incr.\nQed.\n\nLemma record_regs_ok: forall r rl u, In r rl -> is_callee_save r = true -> RegSet.In r (record_regs u rl).\nProof.\n  intros. unfold record_regs. eapply fold_left_ensures; eauto using record_reg_incr, record_reg_ok.\nQed.\n\nLemma record_regs_of_instr_incr: forall r' u i, RegSet.In r' u -> RegSet.In r' (record_regs_of_instr u i).\nProof.\n  intros. destruct i; simpl; auto using record_reg_incr, record_regs_incr.\nQed.\n\nDefinition defined_by_instr (r': mreg) (i: instruction) :=\n  match i with\n  | Lgetstack sl ofs ty r => r' = r\n  | Lop op args res => r' = res\n  | Lload chunk addr args dst => r' = dst\n  | Lbuiltin ef args res => In r' (params_of_builtin_res res) \\/ In r' (destroyed_by_builtin ef)\n  | _ => False\n  end.\n\nLemma record_regs_of_instr_ok: forall r' u i, defined_by_instr r' i -> is_callee_save r' = true -> RegSet.In r' (record_regs_of_instr u i).\nProof.\n  intros. destruct i; simpl in *; try contradiction; subst; auto using record_reg_ok.\n  destruct H; auto using record_regs_incr, record_regs_ok.\nQed.\n\nLemma record_regs_of_function_ok:\n  forall r i, In i f.(fn_code) -> defined_by_instr r i -> is_callee_save r = true -> RegSet.In r record_regs_of_function.\nProof.\n  intros. unfold record_regs_of_function.\n  eapply fold_left_ensures; eauto using record_regs_of_instr_incr, record_regs_of_instr_ok.\nQed.\n\nLemma max_over_list_bound:\n  forall (A: Type) (valu: A -> Z) (l: list A) (x: A),\n  In x l -> valu x <= max_over_list valu l.\nProof.\n  intros until x. unfold max_over_list.\n  assert (forall c z,\n            let f := fold_left (fun x y => Z.max x (valu y)) c z in\n            z <= f /\\ (In x c -> valu x <= f)).\n    induction c; simpl; intros.\n    split. lia. tauto.\n    elim (IHc (Z.max z (valu a))); intros.\n    split. apply Z.le_trans with (Z.max z (valu a)). apply Z.le_max_l. auto.\n    intro H1; elim H1; intro.\n    subst a. apply Z.le_trans with (Z.max z (valu x)).\n    apply Z.le_max_r. auto. auto.\n  intro. elim (H l 0); intros. auto.\nQed.\n\nLemma max_over_instrs_bound:\n  forall (valu: instruction -> Z) i,\n  In i f.(fn_code) -> valu i <= max_over_instrs valu.\nProof.\n  intros. unfold max_over_instrs. apply max_over_list_bound; auto.\nQed.\n\nLemma max_over_slots_of_funct_bound:\n  forall (valu: slot * Z * typ -> Z) i s,\n  In i f.(fn_code) -> In s (slots_of_instr i) ->\n  valu s <= max_over_slots_of_funct valu.\nProof.\n  intros. unfold max_over_slots_of_funct.\n  apply Z.le_trans with (max_over_slots_of_instr valu i).\n  unfold max_over_slots_of_instr. apply max_over_list_bound. auto.\n  apply max_over_instrs_bound. auto.\nQed.\n\nLemma local_slot_bound:\n  forall i ofs ty,\n  In i f.(fn_code) -> In (Local, ofs, ty) (slots_of_instr i) ->\n  ofs + typesize ty <= bound_local function_bounds.\nProof.\n  intros.\n  unfold function_bounds, bound_local.\n  change (ofs + typesize ty) with (local_slot (Local, ofs, ty)).\n  eapply max_over_slots_of_funct_bound; eauto.\nQed.\n\nLemma outgoing_slot_bound:\n  forall i ofs ty,\n  In i f.(fn_code) -> In (Outgoing, ofs, ty) (slots_of_instr i) ->\n  ofs + typesize ty <= bound_outgoing function_bounds.\nProof.\n  intros. change (ofs + typesize ty) with (outgoing_slot (Outgoing, ofs, ty)).\n  unfold function_bounds, bound_outgoing.\n  apply Zmax_bound_r. eapply max_over_slots_of_funct_bound; eauto.\nQed.\n\nLemma size_arguments_bound:\n  forall sig ros,\n  In (Lcall sig ros) f.(fn_code) ->\n  size_arguments sig <= bound_outgoing function_bounds.\nProof.\n  intros. change (size_arguments sig) with (outgoing_space (Lcall sig ros)).\n  unfold function_bounds, bound_outgoing.\n  apply Zmax_bound_l. apply max_over_instrs_bound; auto.\nQed.\n\n(** Consequently, all machine registers or stack slots mentioned by one\n  of the instructions of function [f] are within bounds. *)\n\nLemma mreg_is_within_bounds:\n  forall i, In i f.(fn_code) ->\n  forall r, defined_by_instr r i ->\n  mreg_within_bounds function_bounds r.\nProof.\n  intros. unfold mreg_within_bounds. intros.\n  exploit record_regs_of_function_ok; eauto. intros.\n  apply RegSet.elements_1 in H2. rewrite InA_alt in H2. destruct H2 as (r' & A & B).\n  subst r'; auto.\nQed.\n\nLemma slot_is_within_bounds:\n  forall i, In i f.(fn_code) ->\n  forall sl ty ofs, In (sl, ofs, ty) (slots_of_instr i) ->\n  slot_within_bounds function_bounds sl ofs ty.\nProof.\n  intros. unfold slot_within_bounds.\n  destruct sl.\n  eapply local_slot_bound; eauto.\n  auto.\n  eapply outgoing_slot_bound; eauto.\nQed.\n\nLemma slots_of_locs_charact:\n  forall sl ofs ty l, In (sl, ofs, ty) (slots_of_locs l) <-> In (S sl ofs ty) l.\nProof.\n  induction l; simpl; intros.\n  tauto.\n  destruct a; simpl; intuition congruence.\nQed.\n\n(** It follows that every instruction in the function is within bounds,\n    in the sense of the [instr_within_bounds] predicate. *)\n\nLemma instr_is_within_bounds:\n  forall i,\n  In i f.(fn_code) ->\n  instr_within_bounds function_bounds i.\nProof.\n  intros;\n  destruct i;\n  generalize (mreg_is_within_bounds _ H); generalize (slot_is_within_bounds _ H);\n  simpl; intros; auto.\n(* call *)\n  eapply size_arguments_bound; eauto.\n(* builtin *)\n  split; intros.\n  apply H1; auto.\n  apply H0. rewrite slots_of_locs_charact; auto.\nQed.\n\nLemma function_is_within_bounds:\n  function_within_bounds f function_bounds.\nProof.\n  intros; red; intros. apply instr_is_within_bounds; auto.\nQed.\n\nEnd BOUNDS.\n\n(** Helper to determine the size of the frame area that holds the contents of saved registers. *)\n\nFixpoint size_callee_save_area_rec (l: list mreg) (ofs: Z) : Z :=\n  match l with\n  | nil => ofs\n  | r :: l =>\n      let ty := mreg_type r in\n      let sz := AST.typesize ty in\n      size_callee_save_area_rec l (align ofs sz + sz)\n  end.\n\nDefinition size_callee_save_area (b: bounds) (ofs: Z) : Z :=\n  size_callee_save_area_rec (used_callee_save b) ofs.\n\nLemma size_callee_save_area_rec_incr:\n  forall l ofs, ofs <= size_callee_save_area_rec l ofs.\nProof.\nLocal Opaque mreg_type.\n  induction l as [ | r l]; intros; simpl.\n- lia.\n- eapply Z.le_trans. 2: apply IHl.\n  generalize (AST.typesize_pos (mreg_type r)); intros.\n  apply Z.le_trans with (align ofs (AST.typesize (mreg_type r))).\n  apply align_le; auto.\n  lia.\nQed.\n\nLemma size_callee_save_area_incr:\n  forall b ofs, ofs <= size_callee_save_area b ofs.\nProof.\n  intros. apply size_callee_save_area_rec_incr.\nQed.\n\n(** Layout of the stack frame and its properties.  These definitions\n  are used in the machine-dependent [Stacklayout] module and in the\n  [Stacking] pass. *)\n\nRecord frame_env : Type := mk_frame_env {\n  fe_size: Z;\n  fe_ofs_link: Z;\n  fe_ofs_retaddr: Z;\n  fe_ofs_local: Z;\n  fe_ofs_callee_save: Z;\n  fe_stack_data: Z;\n  fe_used_callee_save: list mreg\n}.\n", "meta": {"author": "AbsInt", "repo": "CompCert", "sha": "f4ddce910894bf6dbdf83c0642c4b275854b60dd", "save_path": "github-repos/coq/AbsInt-CompCert", "path": "github-repos/coq/AbsInt-CompCert/CompCert-f4ddce910894bf6dbdf83c0642c4b275854b60dd/backend/Bounds.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.27265149684898793}}
{"text": "Require Import Crypto.Compilers.Named.Context.\nRequire Import Crypto.Compilers.Named.Syntax.\nRequire Import Crypto.Compilers.Named.Wf.\nRequire Import Crypto.Compilers.Named.ContextDefinitions.\nRequire Import Crypto.Compilers.Named.ContextProperties.\nRequire Import Crypto.Compilers.Named.ContextProperties.SmartMap.\nRequire Import Crypto.Compilers.Named.InterpretToPHOAS.\nRequire Import Crypto.Compilers.Syntax.\nRequire Import Crypto.Compilers.Wf.\nRequire Import Crypto.Util.PointedProp.\nRequire Import Crypto.Util.Decidable.\nRequire Import Crypto.Util.Option.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nRequire Import Crypto.Util.Tactics.DestructHead.\n\nSection language.\n  Context {base_type_code : Type}\n          {op : flat_type base_type_code -> flat_type base_type_code -> Type}\n          {Name : Type}\n          {base_type_code_dec : DecidableRel (@eq base_type_code)}\n          {Name_dec : DecidableRel (@eq Name)}.\n  Section with_var.\n    Context {var1 var2 : base_type_code -> Type}\n            {Context1 : Context Name var1}\n            {Context2 : Context Name var2}\n            {Context1Ok : ContextOk Context1}\n            {Context2Ok : ContextOk Context2}\n            (failb1 : forall t, @Syntax.exprf base_type_code op var1 (Tbase t))\n            (failb2 : forall t, @Syntax.exprf base_type_code op var2 (Tbase t)).\n\n    Local Ltac t_step :=\n      first [ progress intros\n            | progress unfold dec in *\n            | reflexivity\n            | progress subst\n            | progress inversion_option\n            | erewrite lookupb_extend by assumption\n            | rewrite <- !find_Name_and_val_None_iff\n            | progress break_innermost_match_step\n            | progress break_match_hyps\n            | solve [ eauto using find_Name_and_val_flatten_binding_list ]\n            | congruence\n            | tauto\n            | match goal with\n              | [ H : lookupb (extend _ _ _) _ = _ |- _ ]\n                => erewrite (lookupb_extend _ _ _) in H by assumption\n              | [ H : context[List.In _ (_ ++ _)] |- _ ]\n                => setoid_rewrite List.in_app_iff in H\n              | [ |- context[List.In _ (_ ++ _)] ]\n                => rewrite List.in_app_iff\n              | [ |- context[find_Name_and_val ?tdec ?ndec ?a ?b ?c ?d ?default] ]\n                => lazymatch default with None => fail | _ => idtac end;\n                   rewrite (find_Name_and_val_split tdec ndec (default:=default))\n              | [ H : context[find_Name_and_val ?tdec ?ndec ?a ?b ?c ?d ?default] |- _ ]\n                => lazymatch default with None => fail | _ => idtac end;\n                   rewrite (find_Name_and_val_split tdec ndec (default:=default)) in H\n              | [ H : forall n t, lookupb _ n = None <-> lookupb _ n = None |- context[lookupb _ _ = None] ]\n                => rewrite H\n              | [ H : forall n t, lookupb _ n = None |- context[lookupb _ _ = None] ]\n                => rewrite H\n              end ].\n    Local Ltac t := repeat t_step.\n\n    Lemma wff_interpf_to_phoas\n          (ctx1 : Context1) (ctx2 : Context2)\n          {t} (e : @Named.exprf base_type_code op Name t)\n          (Hwf1 : prop_of_option (Named.wff ctx1 e))\n          (Hwf2 : prop_of_option (Named.wff ctx2 e))\n          G\n          (HG : forall n t v1 v2,\n              lookupb t ctx1 n = Some v1\n              -> lookupb t ctx2 n = Some v2\n              -> List.In (existT _ t (v1, v2)%core) G)\n          (Hctx1_ctx2 : forall n t,\n              lookupb t ctx1 n = None <-> lookupb t ctx2 n = None)\n      : wff G (interpf_to_phoas failb1 ctx1 e) (interpf_to_phoas failb2 ctx2 e).\n    Proof using Context1Ok Context2Ok Name_dec base_type_code_dec.\n      revert dependent G; revert dependent ctx1; revert dependent ctx2; induction e;\n        repeat first [ progress intros\n                     | progress destruct_head' and\n                     | progress break_innermost_match_step\n                     | progress simpl in *\n                     | progress autorewrite with push_prop_of_option in *\n                     | solve [ eauto | tauto ]\n                     | match goal with\n                       | [ |- wff _ _ _ ] => constructor\n                       end ].\n      match goal with H : _ |- _ => eapply H end; t.\n    Qed.\n\n    Lemma wf_interp_to_phoas_gen\n          (ctx1 : Context1) (ctx2 : Context2)\n          {t} (e : @Named.expr base_type_code op Name t)\n          (Hwf1 : Named.wf ctx1 e)\n          (Hwf2 : Named.wf ctx2 e)\n          (Hctx1 : forall n t, lookupb t ctx1 n = None)\n          (Hctx2 : forall n t, lookupb t ctx2 n = None)\n      : wf (interp_to_phoas failb1 ctx1 e) (interp_to_phoas failb2 ctx2 e).\n    Proof using Context1Ok Context2Ok Name_dec base_type_code_dec.\n      constructor; intros.\n      apply wff_interpf_to_phoas; t.\n    Qed.\n\n    Lemma wf_interp_to_phoas\n          {t} (e : @Named.expr base_type_code op Name t)\n          (Hwf1 : Named.wf (Context:=Context1) empty e)\n          (Hwf2 : Named.wf (Context:=Context2) empty e)\n      : wf (interp_to_phoas (Context:=Context1) failb1 empty e) (interp_to_phoas (Context:=Context2) failb2 empty e).\n    Proof using Context1Ok Context2Ok Name_dec base_type_code_dec.\n      apply wf_interp_to_phoas_gen; auto using lookupb_empty.\n    Qed.\n  End with_var.\n\n  Section all.\n    Context {Context : forall var, @Context base_type_code Name var}\n            {ContextOk : forall var, ContextOk (Context var)}\n            (failb : forall var t, @Syntax.exprf base_type_code op var (Tbase t)).\n\n    Lemma Wf_InterpToPHOAS_gen\n          {ctx : forall var, Context var}\n          {t} (e : @Named.expr base_type_code op Name t)\n          (Hctx : forall var n t, lookupb t (ctx var) n = None)\n          (Hwf : forall var, Named.wf (ctx var) e)\n      : Wf (InterpToPHOAS_gen failb ctx e).\n    Proof using ContextOk Name_dec base_type_code_dec.\n      intros ??; apply wf_interp_to_phoas_gen; auto.\n    Qed.\n\n    Lemma Wf_InterpToPHOAS\n          {t} (e : @Named.expr base_type_code op Name t)\n          (Hwf : Named.Wf Context e)\n      : Wf (InterpToPHOAS (Context:=Context) failb e).\n    Proof using ContextOk Name_dec base_type_code_dec.\n      intros ??; apply wf_interp_to_phoas; auto.\n    Qed.\n  End all.\nEnd language.\n\nHint Resolve Wf_InterpToPHOAS : 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/Named/InterpretToPHOASWf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.27265149684898793}}
{"text": "Set Implicit Arguments.\nUnset Strict Implicit.\n\nRequire Import NArith QArith String.\nRequire Import ProofIrrelevance.\n\n(*Avoid clash with Ssreflect*)\nDelimit Scope Q_scope with coq_Qscope.\nDefinition Qcoq := Q.\n\nRequire Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp Require Import all_ssreflect.\nFrom mathcomp Require Import all_algebra.\n\nImport GRing.Theory Num.Def Num.Theory.\n\nRequire Import OUVerT.strings.\nRequire Import OUVerT.extrema OUVerT.dist OUVerT.numerics\n        OUVerT.bigops OUVerT.dyadic.\nRequire Import games compile smooth christodoulou combinators.\nRequire Import OUVerT.listlemmas OUVerT.maplemmas subsettypes.\n\nLocal Open Scope ring_scope.\n\n(******************************************\n  Resource Games are Compilable\n ******************************************)\nInstance resourceEnumerableInstance : Enumerable resource := \n  [:: RYes; RNo].\n\nProgram Instance resourceRefineTypeAxiomInstance\n  : @RefineTypeAxiomClass [finType of resource] _.\nNext Obligation.\n  by split => // r; rewrite mem_enum; case: r. \nQed.\n\nInstance resourceRefineTypeInstance\n  : @RefineTypeClass [finType of resource] _ _.\n\nDefinition ctraffic (N : nat) (m : M.t resource) : N.t :=\n  (M.fold (fun i r acc =>\n             if (i < N)%N\n             then match r with\n                  | RYes => acc + 1\n                  | RNo => acc\n                   end\n             else acc)\n          m 0)%num.\n\nLemma ctraffic_sub0 N (l : seq (M.key * resource)) n :\n  (List.fold_left\n    (fun acc p => \n        if ((nat_of_bin p.1) < N)%N\n          then match p.2 with\n               | RYes => acc + 1\n               | RNo => acc\n               end\n          else acc)\n    l n\n      =\n  (List.fold_left\n    (fun acc p => \n        if ( (nat_of_bin p.1) < N)%N\n          then match p.2 with\n               | RYes => acc + 1\n               | RNo => acc\n               end\n          else acc)\n    l 0 + n))%num.\nProof.\n  move: n.\n  induction l => //=.\n  move => n.\n  case: (a.1 < N)%N => //.\n  case: a.2; rewrite IHl => //=.\n  rewrite (IHl 1%num).\n  rewrite -N.add_assoc.\n  f_equal.\n  apply N.add_comm.\nQed.\n\nLemma ctraffic_subP N l n :\n  (List.fold_left\n    (fun acc p => \n        if (nat_of_bin p.1 < N)%N\n          then match p.2 with\n               | RYes => acc + 1\n               | RNo => acc\n               end\n          else acc)\n    l n\n      =\n  List.fold_left\n    (fun acc p => \n        if (nat_of_bin p.1 < N)%N\n          then match p.2 with\n               | RYes => acc + 1\n               | RNo => acc\n               end\n          else acc)\n    (List.rev l) n)%num.\nProof.\n  rewrite -List.fold_left_rev_right.\n  induction (List.rev l) => //=.\n  rewrite IHl0.\n  case: (a.1 < N)%N => //.\n  case: (a.2) => //.\n  rewrite (ctraffic_sub0 _ _ (n+1)%num) ctraffic_sub0.\n  by rewrite N.add_assoc.\nQed.\n\nLemma ctraffic_filter_sub0 (l : seq (M.key * resource)) n :\n  (List.fold_left\n    (fun acc p => \n      match p.2 with\n      | RYes => acc + 1\n      | RNo => acc\n      end)\n    l n\n      =\n  (List.fold_left\n    (fun acc p => \n      match p.2 with\n      | RYes => acc + 1\n      | RNo => acc\n      end)\n    l 0 + n))%num.\nProof.\n  move: n; induction l => //.\n  move => n => /=.\n  rewrite IHl.\n  case: a.2 => //.\n  rewrite (IHl (0+1)%num) N.add_0_l.\n  rewrite (N.add_comm n 1) N.add_assoc //.\nQed.\n\nLemma ctraffic_subF N l n :\n  (List.fold_left\n    (fun acc p => \n        if (nat_of_bin p.1 < N)%N\n          then match p.2 with\n               | RYes => acc + 1\n               | RNo => acc\n               end\n          else acc)\n    l n\n      =\n  List.fold_left\n    (fun acc p => \n      match p.2 with\n      | RYes => acc + 1\n      | RNo => acc\n      end)\n    (List.filter (fun p => (nat_of_bin p.1 < N)%N) l) n)%num.\nProof.\n  move: n.\n  set f := \n   (fun (acc : N.t) (p : BinNums.N * resource) =>\n    if (p.1 < N)%N\n    then match p.2 with\n        | RYes => (acc + 1)%num\n        | RNo => acc\n        end\n    else acc).\n  set f' :=\n   (fun (acc : N.t) (p : BinNums.N * resource) =>\n   match p.2 with\n   | RYes => (acc + 1)%num\n   | RNo => acc\n   end). \n  induction l => //=.\n  move => n.\n  rewrite ctraffic_sub0 IHl.\n  rewrite /f {2}/f'.\n  case: (a.1 < N)%N => //=.\n  case: a.2.\n  rewrite (ctraffic_filter_sub0 _ (n+1)%num) => //.\n  rewrite -/f'. symmetry. \n  apply ctraffic_filter_sub0.\n  rewrite -ctraffic_filter_sub0 => //.\nQed.\n\nLemma absz_plus a b :\n  0 <= a -> 0 <= b ->\n  @eq nat_eqType (absz (@GRing.add (GRing.Ring.zmodType int_Ring) a b))\n      ((absz a) + (absz b))%N.\nProof. case: a; try auto; case: b => //. Qed.\n\nLemma rat_to_Q_s_add x (pfx : 0 <= x) :\n  (rat_to_Q 1 + rat_to_Q x)%coq_Qscope = rat_to_Q (1 + x).\nProof.\n  have Hx1: (le_rat 0 x) by [].\n  move: pfx. rewrite ge_rat0 in Hx1. rewrite /numq in Hx1. move: Hx1.\n  case: x =>  x.\n  case: x => x1 x2 => /= => pf Hx1 pfx. clear pfx.\n  rewrite /(GRing.add (V := rat_Ring)) /GRing.Zmodule.add => /=.\n  rewrite /addq /addq_subdef => /=.\n  rewrite gcdn1 div.divn1 mul1r mulr1.\n  rewrite rat_to_Q_fracq_pos_leib /rat_to_Q => /=.\n  rewrite /Qplus.\n  rewrite Z.mul_1_r Z.mul_1_l => /=.\n  f_equal.\n  rewrite -int_to_Z_plus.\n  {\n    case_eq (int_to_Z x1).\n    {\n      move => H. rewrite Z.add_0_r.\n      rewrite /int_to_Z.\n      destruct x2. rewrite /int_to_positive.\n      rewrite Z_of_nat_pos_of_nat => //.\n      case/andP: pf => //.\n      case/andP: pf => //.\n    }\n    {\n      move => p H.\n      rewrite /int_to_Z.\n      destruct x2. rewrite /int_to_positive.\n      rewrite Z_of_nat_pos_of_nat => //.\n      case/andP: pf => //.\n      case/andP: pf => //.\n    }\n    {\n      move => p H.\n      rewrite /int_to_Z.\n      destruct x2. rewrite /int_to_positive.\n      rewrite Z_of_nat_pos_of_nat => //.\n      case/andP: pf => //.\n      case/andP: pf => //.\n    }\n  }\n  case/andP: pf => //.\n  {\n    case/andP: pf => H0 H1.\n    move: H1. rewrite /coprime. move => /eqP H1. apply /eqP.\n    rewrite absz_plus; auto.\n    by rewrite gcdnC gcdnDl gcdnC.\n  }\nQed.\n\nLemma Qplus_leib_comm x y:\n  (x + y)%coq_Qscope = (y + x)%coq_Qscope.\nProof.\n  case: x => x1 x2.\n  case: y => y1 y2.\n  rewrite /Qplus /Qnum /Qden => //.\n  f_equal. ring. apply Pmult_comm.\nQed.\n\nLemma Qplus_leib_assoc x y z:\n  (x + (y + z))%coq_Qscope = ((x + y) + z)%coq_Qscope.\nProof.\n  case x => x1 x2.\n  case y => y1 y2.\n  case z => z1 z2.\n  rewrite !/Qplus !/Qnum !/Qden => //.\n  f_equal. ring_simplify.\n  rewrite Pos.mul_comm [(x2 * y2)%positive] Pos.mul_comm.\n  rewrite !Pos2Z.inj_mul !Zmult_assoc //.\n  apply Pmult_assoc.\nQed.\n\nLemma Qplus_leib_0_l x : (0 + x)%coq_Qscope = x.\nProof.\n  case: x => x1 x2.\n  rewrite /Qplus /Qnum /Qden.\n  f_equal. ring.\nQed.\n\nLemma ctraffic_sub_subP (l : seq (M.key*resource)):\n  let f :=\n    (fun acc p => \n      match p.2 with\n      | RYes => (acc + 1)%num\n      | RNo => acc\n      end) in\n  N_to_Q (List.fold_left f l 0)%num\n    =\n  rat_to_Q\n    ((count\n      (fun p => p.2  == RYes)\n      l)%:R).\nProof.\n  induction l => //=.\n  have H : rat_to_Q 1 = 1%coq_Qscope by rewrite /rat_to_Q => //.\n  have Hx : N_to_Q 1 = 1%coq_Qscope by [].\n  have Hy : N_to_Q 0 = 0%coq_Qscope by [].  \n  case: a.2; rewrite ctraffic_filter_sub0 /= N_to_Q_plus IHl; set Y := count _ _.\n  { rewrite Hx natrD -rat_to_Q_s_add.\n    by rewrite Qplus_leib_comm H.\n    have H1: (0%:R <= (count (fun p : M.key * resource => p.2 == RYes) l)%:R).\n    { move => t. by rewrite ler_nat. }\n    by apply: H1. }\n  by rewrite Hy addnC addn0 Qplus_leib_comm Qplus_leib_0_l.\nQed.\n\nDefinition resource_ccost N (i : OrdNat.t) (m : M.t resource) : D :=\n  match M.find i m with\n  | Some RYes => N_to_D (ctraffic N m)\n  | Some RNo => D0\n  | None => D0 (*won't occur when i < N*)\n  end.\n\nGlobal Instance resourceCCostInstance N : CCostClass N resource\n  := resource_ccost N.\n\nDefinition lift_traffic N (s : {ffun 'I_N -> resource})\n  : seq (M.key*resource):=\n map\n  (fun (x : 'I_N) => ((N.of_nat x), s x))\n  (index_enum (ordinal_finType N)).  \n\nLemma list_trafficP N (s : {ffun 'I_N -> resource}) :\n  count (fun j : (M.key*resource) => j.2 == RYes) (lift_traffic s)\n  =\n  count (fun j: ordinal_finType N => s j == RYes)\n    (index_enum (ordinal_finType N)).\nProof.\n  rewrite count_map => /=.\n  rewrite -!sum1_count => //.\nQed.\n\nLemma N_of_nat_of_bin x :\n  N.of_nat (nat_of_bin x) = x.\nProof.\n  rewrite /nat_of_bin.\n  case: x => // p.\n  have H: (nat_of_pos p = Pos.to_nat p). \n  {  elim: p => // p IHp /=.\n     - by rewrite Pos2Nat.inj_xI IHp NatTrec.doubleE -mul2n.\n     - by rewrite Pos2Nat.inj_xO IHp NatTrec.doubleE -mul2n.\n  }\n  rewrite H. by apply positive_nat_N.\nQed.\n\nLemma of_bin_N_of_nat x :\n  nat_of_bin (N.of_nat x) = x.\nProof.\n  case: x => // p => //=.\n  rewrite of_succ_nat_of_nat_plus_1.\n  have H: forall m, nat_of_pos m = Pos.to_nat m.\n  { move => m; elim: m => // m IHp /=.\n     - by rewrite Pos2Nat.inj_xI IHp NatTrec.doubleE -mul2n.\n     - by rewrite Pos2Nat.inj_xO IHp NatTrec.doubleE -mul2n.\n  }\n  rewrite H. rewrite Nat2Pos.id; first by apply addn1.\n  case p => //.\nQed.\n\nLemma InA_NoDupA_Unique A eqA x1 x2 :\n  Equivalence eqA -> \n  forall l, @SetoidList.NoDupA A eqA l ->\n    List.In x1 l ->\n    List.In x2 l ->\n    eqA x1 x2 ->\n      x1 = x2.\nProof.\n  induction l => H0 H1 H2 H3; first by inversion H1.\n  inversion H0; subst.\n  case: H1 => H1; case: H2 => H2; subst => //=.\n  {\n    inversion H0. apply False_rec. apply H6 => //.\n    apply SetoidList.InA_alt.\n    exists x2; split => //.\n  }\n  {\n    inversion H0. apply False_rec. apply H6 => //.\n    apply SetoidList.InA_alt.\n    exists x1; split => //. symmetry => //.\n  }\n  {\n    apply IHl; inversion H0 => //.\n  }\nQed.\n\n(*FIXME: MOVE*)\nLemma eq_Qeq q r : q=r -> Qeq q r.\nProof. by move => ->; apply: Qeq_refl. Qed.                     \n\nProgram Instance resourceRefineCostAxiomInstance N\n  : @RefineCostAxiomClass N [finType of resource] _ _.\nNext Obligation.  \n  rewrite /(ccost) /resourceCCostInstance /resource_ccost.\n  rewrite (H i pf).\n  rewrite /(cost) /resourceCostInstance /= /resourceCostFun /=.\n  case H2: (s _) => //.\n  rewrite /ctraffic M.fold_1 trafficP /traffic' ctraffic_subF.\n  move: (M.elements_3w m) => H1.\n  rewrite N_to_D_to_Q.\n  rewrite ctraffic_sub_subP.\n  apply: eq_Qeq.\n  f_equal.\n  rewrite sum1_count.\n  rewrite -list_trafficP.\n  f_equal.\n  apply /perm_eqP.\n  apply uniq_perm_eq.\n  {\n    induction M.elements => //=.\n    case: (a.1 < N)%N => //=.\n    {\n      apply /andP; split.\n      {\n        inversion H1; subst.\n        apply/negP => H6.\n        apply H4.\n        rewrite mem_filter in H6.\n        case/andP: H6 => H6 H7.\n        apply SetoidList.InA_alt.\n        exists a.\n        split => //.\n        apply list_in_iff in H7. apply H7.\n      }\n      {\n        apply IHl.\n        inversion H1 => //.\n      }\n    }\n    {\n      apply IHl.\n      inversion H1 => //.\n    }\n  }\n  {\n    rewrite /lift_traffic.\n    rewrite map_inj_uniq /index_enum.\n    rewrite -enumT => /=.\n    apply enum_uniq.\n    rewrite /injective => x1 x2 H0.\n    inversion H0.\n    apply Nnat.Nat2N.inj_iff in H4.\n    apply ord_inj in H4 => //.\n  }\n  {\n    rewrite /lift_traffic.\n    rewrite /eq_mem => x.\n    case_eq\n      (x \\in List.filter (fun p : BinNums.N * resource => (p.1 < N)%N)\n         (M.elements (elt:=resource) m)) => H4.\n    {\n       rewrite mem_filter in H4.\n       case/andP: H4 => H4 H5.\n      have H7: exists x', (fun x0 : ordinal N => pair (N.of_nat x0) (s x0)) x' = x.\n      {\n        specialize (H x.1 H4).\n        rewrite MProps.F.elements_o in H.\n        apply SetoidList.findA_NoDupA in H => //;\n          last by constructor => //=; apply N.eq_trans.\n        apply list_in_iff in H5.\n        apply SetoidList.InA_alt in H.\n        case: H => x' H => /=.\n        case: H => H H6.\n        case: H => H' H''.\n        simpl in H', H''.\n        rewrite /N.eq in H'.\n        have H: x = x'.\n        apply InA_NoDupA_Unique\n          with (eqA := (M.eq_key (elt := resource)))\n               (l := (M.elements (elt := resource) m)) => //;\n          first by apply MProps.eqk_equiv.\n        exists (Ordinal H4) => //.\n        destruct x as [x1 x2].\n        destruct x' as [x1' x2'].\n        inversion H. simpl.\n        f_equal => //.\n        dependent rewrite H3.\n        f_equal.\n        apply N_of_nat_of_bin.\n      }\n      case: H7 => x' H7. rewrite -H7.\n      rewrite /index_enum -enumT.\n      rewrite mem_map; first by rewrite mem_enum => //.\n      {\n        rewrite /injective => x1 x2 H0.\n        inversion H0.\n        apply Nnat.Nat2N.inj_iff in H6.\n        apply ord_inj in H6 => //.\n      }        \n    }\n    {\n      rewrite mem_filter in H4.\n      case_eq (x \\in [seq (N.of_nat (nat_of_ord x0), fun_of_fin s x0)\n                | x0 <- index_enum (ordinal_finType N)])=> H5 => //.\n      case/mapP: H5 => y H6 H7.\n      case/andP: H4; split; destruct x as [x1 x2]; inversion H7 => /=.\n      rewrite /index_enum -enumT //= in H6.\n      rewrite of_bin_N_of_nat => //.\n      apply list_in_iff.\n      clear pf H2 H7 H3 H4 H6 x1 x2.\n      simpl in y.\n      destruct y as [yn Hy].\n      move: yn Hy => yn.\n      rewrite -(bin_of_natK yn) => Hy.\n      specialize (H _ Hy).\n      rewrite MProps.F.elements_o in H.\n      apply SetoidList.findA_NoDupA in H => //;\n        last by constructor => //=; apply N.eq_trans.\n      apply SetoidList.InA_alt in H.\n      destruct H as [z H].\n      destruct H as [H H'].\n      destruct H as [H H''].\n      simpl in H. simpl in H''.\n      have Hz: (z = (N.of_nat (Ordinal (n:=N) (m:=bin_of_nat yn) Hy),\n                   s (Ordinal (n:=N) (m:=bin_of_nat yn) Hy))).\n      destruct z as [z1 z2].\n      f_equal. simpl in H. rewrite -H.\n      simpl. rewrite N_of_nat_of_bin => //.\n      simpl in H''. rewrite H'' => //.\n      rewrite -Hz => //.\n    }\n  }\nQed.\n\nInstance resourceRefineCostInstance N\n  : @RefineCostClass N [finType of resource] _ _ _.\n\nInstance resourceCCostMaxInstance N\n  : @CCostMaxClass N [finType of resource] :=\n  N_to_D (N.of_nat N).\n\nInstance resourceRefineCostMaxInstance N\n  : @RefineCostMaxClass N _ (resourceCostMaxInstance _) (resourceCCostMaxInstance _).\nProof.\n  rewrite /RefineCostMaxClass /resourceCCostMaxInstance /resourceCostMaxInstance.\n  apply Qle_lteq.\n  right => //.\n  by rewrite N_to_D_to_Q /= rat_to_Q_N_to_Q.\nQed.\n\nLtac simp :=\n  repeat\n    match goal with\n    | H : ?x = true |- _ =>\n      apply Is_true_eq_left in H; unfold Is_true in H\n    | H : ?x = false |- _ =>\n      apply negbT in H; unfold negb in H\n    | H : context[(?x <= ?N)%N] |- _ =>\n      case: leP H => //; intros\n    | |- context[(?x <= ?N)%N] =>\n      apply /leP => //\n    end.\n\nLtac my_omega :=\n  unfold Dlt,Qlt,Dle,Qle,Dle,D_to_Q,Qle in *; simpl;\n  simp; simpl in *; intros; omega.\n\nLemma D_num_le_spec : forall (p p' : Z) ,\n    Z.le p p' -> \n    Dle {| num := p; den := 1 |} {| num := p'; den := 1 |}%DRed.\nProof.\n  intros.\n  my_omega.\nQed.\n\nLemma le_num_le : forall (n n' : N),\n    (n <= n')%num <-> le n n'.\n  split; intros.\n  apply N.le_equiv in H.\n  rewrite /N.le_alt in H.\n  destruct H.\n  apply Nat.le_equiv.\n  rewrite /Nat.le_alt.\n  exists x.\n  rewrite <- nat_of_add_bin.\n  rewrite H.\n  auto.  \n\n  apply N.le_equiv.\n  rewrite /N.le_alt.\n  apply Nat.le_equiv in H.\n  rewrite /Nat.le_alt in H.\n  destruct H.\n  exists (N.of_nat x).\n  replace n with (N.of_nat (nat_of_bin n)) by apply N_of_nat_of_bin.\n  rewrite -Nat2N.inj_add.\n  rewrite H.\n  apply N_of_nat_of_bin.\nQed.    \n  \nLemma Z_le_inj : forall (n n' : N),\n    (n <= n')%num -> (Z.le (NtoZ n) (NtoZ n')).\nProof.\n  intros.\n  rewrite /NtoZ.\n  induction n => //;\n                   destruct n'; auto => //.\nQed.\nHint Resolve Z_le_inj.\n\nLemma if_not_in_filterN_eq_filterSn : forall \n    (l : list (BinNums.N * resource)) (N : BinNums.N) a,\n  ~SetoidList.InA (M.eq_key (elt:=resource)) (N, a) l->\n  (List.filter (fun p0 : BinNums.N * resource => (nat_of_bin p0.1 < N)%N) l) =\n  (List.filter (fun p0 : BinNums.N * resource => (nat_of_bin p0.1 < N.+1)%N) l).\nProof.\n  assert (forall x y, {M.eq_key (elt := resource) x y} + {~ M.eq_key x y}).\n  destruct x, y; simpl.\n  apply M.E.eq_dec.\n  assert (forall x l, {SetoidList.InA (M.eq_key (elt:=resource)) x l}\n                      + {~ SetoidList.InA (M.eq_key (elt:=resource)) x l}).\n  apply SetoidList.InA_dec; intros; auto.\n  induction l => //.\n  intros N a0 H.\n  simpl.\n  case_eq (a.1 < N)%N => Hlt //.\n  have->: (a.1 < N.+1)%N; auto.\n  f_equal.\n  eapply IHl; eauto.\n  case_eq (a.1 < N.+1)%N => Hlt' //; eauto.\n  exfalso.\n  apply H.\n  constructor.\n  rewrite /M.eq_key /M.Raw.Proofs.PX.eqk /N.eq.\n  simpl.\n  destruct a; simpl in *.\n  apply nat_of_bin_inj.\n  my_omega.\nQed.\n\nLemma ctrafficN_relates_ctrafficSn :\n  forall (x : BinNums.N) l (N : BinNums.N)  a,\n    Datatypes.length\n      (List.filter (fun p0 : BinNums.N * resource=> (p0.1 < N)%N) l) = x\n    ->  \n    Datatypes.length\n      (List.filter (fun p0 : BinNums.N * resource => (p0.1 < N.+1)%N) l) =\n    x.+1 -> \n    ~ SetoidList.InA (M.eq_key (elt:=resource)) (N,a) l ->\n    (Datatypes.length\n       (List.filter (fun p0 : BinNums.N * resource => (p0.1 < N.+1)%N) l)).+1 =\n    x\n.\nProof.\n  intros.\n  apply if_not_in_filterN_eq_filterSn with (N0 := N) in H1.\n  rewrite <- H1 in *.\n  exfalso.\n  rewrite -> H0 in *.\n  omega.\nQed.\n\nLemma ctraffic_Sn_or_normal : forall (l : seq (BinNums.N * resource)) N,\n    let l' :=  (Datatypes.length\n       (List.filter (fun p0 : BinNums.N * resource => (p0.1 < N.+1)%N) l))\n    in \n    SetoidList.NoDupA (M.eq_key (elt:=resource)) l ->\n    l' =\n    (Datatypes.length\n    (List.filter (fun p0 : BinNums.N * resource => (p0.1 < N)%N) l)).+1\n    \\/\n    l' = \n    (Datatypes.length\n       (List.filter (fun p0 : BinNums.N * resource => (p0.1 < N)%N) l)).\nProof.\n  intros l N l' H.\n  unfold l' in *.\n  clear l'.\n  move: N H.\n  induction l => //; auto.\n  move => N H.\n  inversion H as [| x l0 H2 H3 H1]; subst.\n  specialize (IHl N H3).\n  destruct IHl; simpl;\n  repeat match goal with\n         | |- context[if (?x < ?N)%N then _ else _] =>\n           let H := fresh \"C\" in case_eq ((x < N)%N); intros H\n  end; simpl; auto; simp; auto.\n  {\n    have: eq (S (nat_of_bin (@fst BinNums.N resource a))) (S N);\n      first by my_omega.\n    intros x.\n    inversion x.\n    subst.\n    clear n; clear C0; clear p; clear C; clear x.\n    right.\n    have:\n      exists (n:N), (Datatypes.length\n           (List.filter (fun p0 : N * resource => (p0.1 < a.1)%N) l)) = n\n           => [| H4].\n    destruct (Datatypes.length\n      (List.filter (fun p0 : N * resource => (p0.1 < a.1)%N) l)).\n    exists N0;\n    eauto.\n    exists (N.succ (N.of_nat n)).\n    rewrite - Nat2N.inj_succ.\n    rewrite of_bin_N_of_nat.\n    auto.\n    destruct H4.\n    rewrite -> H1 in *.\n    destruct a; simpl in *.\n    apply ctrafficN_relates_ctrafficSn with (a := r); auto.\n  }\n  exfalso.\n  my_omega.\nQed.\n  \nLemma filter_length_ltN_if_nodup : forall l N,\n    SetoidList.NoDupA (M.eq_key (elt:=resource)) l ->\n    (Datatypes.length\n      (List.filter (fun p : BinNums.N * resource => (p.1 < N)%N) l) <= N)%coq_nat.\nProof.\n  intros.\n  induction N => //.\n  {\n    clear -H.\n    induction l => //;\n    simpl in *; \n    inversion H; subst; auto.    \n  }\n    destruct (ctraffic_Sn_or_normal (l:=l) N); intuition; auto.\nQed.\n    \nLemma lt_fold : forall A (f f' : BinNums.N -> A -> N) l n n',\n    (n <= n')%num -> \n    (forall (acc acc': N) x, (acc <= acc')%num ->  f acc x <= f' acc' x)%num-> \n    (le (List.fold_left f l n) (List.fold_left f' l n')).\nProof.\n  induction l => //.\n  intros.\n  simpl.\n  apply le_num_le => //.\n  intros.\n  specialize (IHl (f n a) (f' n' a)).\n  apply IHl; \n  auto.\nQed.\n\nLemma lt_size : forall (N : N) (N0 : BinNums.N)\n                       (l : seq (BinNums.N * resource)),\n    le (List.fold_left\n    (fun (acc : BinNums.N) (p : BinNums.N * resource) =>\n     match p.2 with\n     | RYes => (acc + 1)%num\n     | RNo => acc\n     end) l\n    N0)\n  (List.fold_left (fun (a : BinNums.N) (_ : M.key * resource)\n                   => (N.add a 1)%N) l N0).\nProof.\n  intros.\n  assert (N0 <= N0)%num by \n  apply N.le_refl.\n  apply lt_fold with (f := (fun (acc : BinNums.N) (p : BinNums.N * resource) =>\n     match p.2 with\n     | RYes => (acc + 1)%num\n     | RNo => acc\n     end))\n                     (f' :=\n                        (fun (a : BinNums.N) (_ : M.key * resource) => (N.add a 1))) (l := l)\n                   in H; eauto.\n  intros.\n  case: x.2 => //.\n  apply N.add_le_mono_r; auto.\n  replace acc with (acc + 0)%num.\n  apply N.add_le_mono; auto.\n  compute; intros; discriminate.\n  case acc =>//.\nQed.\n\nLemma ctraffic_ltN_lt : forall (N : N) m,\n  ((ctraffic N m) <= N)%N.\nProof.\n  move => N m.\n  rewrite /ctraffic.\n  rewrite M.fold_1.\n  rewrite ctraffic_subF.\n  specialize (M.elements_3w m); intros nodup.\n  specialize (filter_length_ltN_if_nodup N nodup).\n  generalize dependent (M.elements (elt:=resource) m) => l.\n  generalize dependent ((List.filter (fun p : BinNums.N * resource => (p.1 < N)%N) l)).\n  intros.\n  specialize (lt_size N).\n  intros.\n  specialize (H0 N0 l0 ).\n  generalize dependent ((fun (acc : BinNums.N) (p : BinNums.N * resource) =>\n      match p.2 with\n      | RYes => (acc + 1)%num\n      | RNo => acc\n      end)).\n  intros.\n  move: H0.\n  assert (forall n n', n = n' ->  (List.fold_left (fun (a : BinNums.N) (_ : M.key * resource) => N.add a 1) l0 n) = \n      (List.fold_left (fun (a : BinNums.N) (_ : M.key * resource) => N.succ (N.of_nat (a)))l0 n')); auto.\n  {\n    clear.\n    induction l0 => //.\n    simpl in *.\n    intros.\n    rewrite (IHl0 (N.add n 1) (N.succ (N.of_nat n'))); subst; auto.\n    rewrite -Nat2N.inj_succ.\n    rewrite N.add_1_r.\n    rewrite Nat2N.inj_succ.\n    f_equal.\n    rewrite N_of_nat_of_bin => //.\n  }\n  rewrite (H0 N0 N0); auto.\n  clear H0.\n  intros.\n  apply /leP.\n  assert (forall n n',  n = N.of_nat n' ->  List.fold_left \n         (fun (a : BinNums.N) (_ : M.key * resource) =>\n            N.succ (N.of_nat a)) l0 n =\n          N.of_nat (List.fold_left (fun (x : nat) (_ : M.key * resource) => x.+1) l0 n')).\n  {\n    clear.\n    induction l0 => //.\n    intros.\n    simpl in *.\n    rewrite N_of_nat_of_bin.\n    specialize (IHl0 (N.succ n) (n'.+1)).\n    rewrite IHl0; auto.\n    rewrite Nat2N.inj_succ.\n    f_equal.\n    auto.\n  }\n  specialize (H1 N0 O ).\n  rewrite H1 in H0; auto.\n  rewrite List.fold_left_length in H0.\n  simpl in *.\n  clear H1.\n  generalize dependent (List.fold_left n l0 0%num).\n  intros.\n  rewrite of_bin_N_of_nat in H0.\n  clear -H H0.\n  unfold M.key in H0.\n  unfold N.t in H0.\n  omega.\nQed.\n\nInstance resourceCCostMaxMaxClassInstance N\n  : @CCostMaxMaxClass N [finType of resource] _\n                     _.\nProof.\n  split;\n  rewrite /ccost_fun /resourceCCostInstance /ccostmax_fun;\n  rewrite /resourceCCostMaxInstance;\n  rewrite /resource_ccost.\n  +\n    case: (M.find (elt:=resource) i m) => r //.\n    case r => //.\n    {\n      rewrite /ctraffic.\n      apply MProps.fold_rec_weak => //.\n      intros.\n      case (k < N)%N => //.\n      case e => //.\n      unfold Dle in *.\n      rewrite N_to_D_plus.\n      rewrite Dadd_ok.\n      clear -H0.\n      my_omega.\n    }\n  +\n  rewrite /ccost_fun /resourceCCostInstance /ccostmax_fun.\n  rewrite /resourceCCostMaxInstance.\n  rewrite /resource_ccost.\n  case: (M.find (elt:=resource) i m).\n  move => a.\n  case a.\n  {\n    rewrite /N_to_D.\n    apply D_num_le_spec.\n    apply Z.mul_le_mono_nonneg_l => //.\n    apply Z_le_inj.\n    rewrite le_num_le.\n    rewrite of_bin_N_of_nat.\n    specialize ctraffic_ltN_lt.\n    intros.\n    specialize (H (N.of_nat N) m).\n    case: leP H => //.\n    intros H.\n    rewrite of_bin_N_of_nat in H.\n    auto.\n  }\n  all:\n  destruct N; \n  compute; intros; discriminate; eauto.\nQed.\n\nInstance resource_cgame N\n  : cgame (N:=N) (T:=[finType of resource]) _ _ _ _\n      (resourceGame N).\n\n(** [NOTE Enumerable instances]\n    ~~~~~~~~~~~~~~~~~~~~~~\n    [Enumerable] instances should in general avoid using Ssreflect [enum]. \n    The reason is, extraction (and computation) of [enum ...] doesn't \n    usually (or ever...?) result in usable OCaml terms. Instead, \n    use the [enumerate] function of the underlying type to build the \n    instance at the current type.\n    The example below illustrates the general problem: *)\n\nDefinition resources : list resource := Eval hnf in enum [finType of resource].\nExtraction resources.\n(* let resources =\n  filter\n    (pred_of_simpl\n      (pred_of_mem_pred\n        (mem predPredType (sort_of_simpl_pred pred_of_argType))))\n    (Obj.magic Finite.EnumDef.enum\n      (Finite.clone resource_finType (Finite.coq_class resource_finType))) *)\nDefinition resources' : list resource := Eval hnf in enumerate [finType of resource].\nExtraction resources'.\n(* let resources' =\n  Cons (RYes, (Cons (RNo, Nil))) *)\n\n\n(*********************************************\n Singleton Games are Compilable \n *********************************************)\n\nGlobal Instance singCCostInstance (A : Type) `(Boolable A) N\n  : CCostClass N (singleton A)\n  :=      \n    (fun (i : OrdNat.t) (m : M.t (singleton A)) =>\n      match M.find i m with\n      | Some t => if boolify t then 1 else 0\n      | _ => 0\n      end)%D.\n\nInstance singCTypeInstance (A : Type) (EnumA : Enumerable A)\n    : Enumerable (singleton A) := map (@Wrap Singleton A) (enumerate A).\n\nInstance singCCostMaxInstance (N : nat) (A : Type)\n    : @CCostMaxClass N (singleton A) := 1%D.\n\nSection singletonCompilable.\n  Context {A : finType} {N: nat} `{RefineTypeAxiomClass A} `{Boolable A}.\n\n  Global Program Instance singRefineTypeAxiomInstance\n    : @RefineTypeAxiomClass (singletonType A) (singCTypeInstance _).\n  Next Obligation.\n    generalize H => H1. clear H. case: H1 => H1 H2.\n    split; last first.\n    {\n      rewrite map_inj_uniq. apply H2.\n      rewrite /injective => x1 x2 H3.\n      inversion H3 => //.\n    }\n    rewrite /(enumerate Wrapper Singleton A) /singCTypeInstance.\n    move => r.\n    apply /mapP.\n    case_eq (in_mem r (mem (enum_mem (T:=singletonType A)\n              (mem (sort_of_simpl_pred (pred_of_argType\n                (Wrapper Singleton A))))))) => H3; rewrite H3.\n    {\n      move: H3.\n      case: r => x H3.\n      exists x; last by [].\n      rewrite H1 mem_enum.\n      rewrite mem_enum in H3 => //.\n    }\n    {\n      move => H4.\n      case: H4 => x H4 H5.\n      rewrite H5 in H3.\n      move/negP: H3 => H3.\n      apply H3 => //.\n      rewrite mem_enum => //.\n    }\n  Qed.\n\n  Global Instance singRefineTypeInstance\n    : @RefineTypeClass (singletonType A)  _ _.\n\n  Global Program Instance singRefineCostAxiomInstance `(Boolable A)\n    : RefineCostAxiomClass _ (singCCostInstance _ N).\n  Next Obligation.\n    rewrite /cost_fun /singletonCostInstance /cost_fun.\n    rewrite /ccost_fun /singCCostInstance /ccost_fun.\n    rewrite (H2 i pf).\n    case: (boolify (s (Ordinal (n := N) (m := i) pf))) => //.\n  Qed.\n  \n  Global Instance singRefineCostInstance\n    : @RefineCostClass N (singletonType A) _ _ _.\n\n  Global Instance singRefineCostMaxInstance\n    : @RefineCostMaxClass N _ (singletonCostMaxInstance _ _) (singCCostMaxInstance N A).\n  Proof.\n    rewrite /RefineCostMaxClass /resourceCCostMaxInstance\n            /singletonCostMaxInstance /singCCostMaxInstance => //.\n  Qed.\n\n  Global Instance singCostMaxMaxInstance\n    : CCostMaxMaxClass  (singCCostMaxInstance N A) _.\n  Proof.\n    split; \n    unfold CCostMaxMaxClass;\n    rewrite /ccostmax_fun/singCCostMaxInstance;\n    rewrite /ccost_fun /singCCostInstance.\n    all:\n    case: (M.find (elt:=singleton A) i m); intros;\n      [destruct boolify; eauto | ];\n          compute; intros; try discriminate.\n  Qed.\n\n  Global Instance sing_cgame\n  : @cgame N (singletonType A) _ _ _ (singletonCostInstance H0)\n      _\n      _ (singletonCostMaxAxiomInstance _ A _) _\n      _ _ _ _ singRefineCostMaxInstance _.\n\nEnd singletonCompilable.\n\nModule SingletonCGameTest. Section singletonCGameTest.\n  Context {A : finType} {N : nat} `{Boolable A}.\n  Variable i' : OrdNat.t.\n  Variable t' : M.t (singletonType A).\n  Check ccost_fun (N:=N) i' t'.\nEnd singletonCGameTest. End SingletonCGameTest.  \n\n(**********************************************\n  Sigma games are compilable \n **********************************************)\n\nInstance sigmaCCostMaxInstance (N : nat) (A : Type)\n         (predInstance : PredClass A)\n         (ccostMaxInstance : CCostMaxClass N A)\n  : @CCostMaxClass N {x : A | the_pred x} := ccostMaxInstance.\n\nSection sigmaCompilable.\n  Global Instance sigmaEnumerableInstance (A : Type)\n           (enumerableInstance : Enumerable A)\n           (predInstance : PredClass A)\n    : Enumerable {x : A | the_pred x} :=\n    filter_sigma the_pred (enumerate A).\n\n  Global Program Instance sigmaRefineTypeAxiomInstance\n          (A : finType)\n          `(refineTypeAxiomInstanceA : RefineTypeAxiomClass A)\n          (predInstance : PredClass A)\n    : @RefineTypeAxiomClass [finType of {x : A | the_pred x}] _.\n  Next Obligation.\n    rewrite /RefineTypeAxiomClass in refineTypeAxiomInstanceA.\n    case: refineTypeAxiomInstanceA=> [H0 H1]. rewrite /eq_mem in H0.\n    split.\n    { move=> r. rewrite /enumerable_fun. rewrite /sigmaEnumerableInstance.\n      have ->: (r \\in enum [finType of {x : A | the_pred x}]).\n      { apply mem_enum. }\n      have ->: (r \\in filter_sigma the_pred (enumerate A)).\n      { apply list_in_iff, list_in_filter_sigma.\n        specialize (H0 (proj1_sig r)). apply list_in_iff.\n        rewrite H0. by apply mem_enum. }\n        by []. }\n    { rewrite /enumerable_fun /sigmaEnumerableInstance. clear H0. move: H1.\n      elim: (enumerate A).\n      - by [].\n      - move => a l IHl H1. simpl. simpl in H1. move: H1=> /andP [H1 H2].\n        destruct (to_sigma the_pred a) eqn:Ha. simpl. apply /andP.\n        split. rewrite /in_mem. simpl. apply /negP. move=> Contra.\n        rewrite /in_mem in H1. simpl in H1. move: H1=> /negP H1.\n        rewrite /pred_of_eq_seq in H1. rewrite /pred_of_eq_seq in Contra.\n        \n        have H3: (mem_seq (T:=A) l a).\n        { apply: mem_seq_filter. apply Ha. assumption. }\n        contradiction.\n        apply IHl; assumption. apply IHl; assumption. }\n  Qed.\n\n  Global Instance sigmaRefineTypeInstance (A : finType)\n           (predInstance : PredClass A)\n           `(refineTypeAxiomInstanceA : RefineTypeAxiomClass A)\n    : @RefineTypeClass [finType of {x : A | the_pred x}]  _ _.\n\n  Global Instance sigmaCCostInstance\n           (A : Type) N\n           (predInstance : PredClass A)\n           (ccostA : @CCostClass N A)\n    : CCostClass N {x : A | the_pred x}\n    :=\n      fun (i : OrdNat.t) (m : M.t {x : A | the_pred x}) =>\n        ccost i (M.map (fun x => proj1_sig x) m).\n  \n  Global Program Instance sigmaRefineCostAxiomInstance\n          (N : nat) (A : finType)\n          (predInstance : PredClass A)\n          (costA : CostClass N rat_realFieldType A)\n          (ccostA : CCostClass N A)\n          (refineA : RefineCostAxiomClass costA ccostA)\n    : @RefineCostAxiomClass\n        N [finType of {x : A | the_pred x}]\n        (@sigmaCostInstance N rat_realFieldType A _ costA)\n        (@sigmaCCostInstance A _ _ ccostA).\n  Next Obligation.\n    apply refineA=> j pf'; rewrite ffunE.\n    apply MProps.F.find_mapsto_iff, MProps.F.map_mapsto_iff.\n    specialize (H j pf'); apply MProps.F.find_mapsto_iff in H.\n    by exists (s (Ordinal (n:=N) (m:=j) pf')); split => //.\n  Qed.\n\n  Global Instance sigmaRefineCostInstance (N : nat) (A : finType)\n           (predInstance : PredClass A)\n           (costA : CostClass N rat_realFieldType A)\n           (ccostA : CCostClass N A)\n           (refineA : RefineCostAxiomClass costA ccostA)\n    : @RefineCostClass N [finType of {x : A | the_pred x}] _ _ _.\n\n  Global Instance sigmaCostMaxRefineInstance (N : nat) (A : finType)\n           (predInstance : PredClass A)\n           (costMaxInstance : CostMaxClass N _ A)\n           (ccostMaxInstance : CCostMaxClass N A)\n           (refineCostMaxInstance : RefineCostMaxClass costMaxInstance ccostMaxInstance)\n    : @RefineCostMaxClass N A\n        (sigmaCostMaxInstance predInstance costMaxInstance)\n        (sigmaCCostMaxInstance predInstance ccostMaxInstance).\n  Proof.\n    rewrite /RefineCostMaxClass /sigmaCostMaxInstance\n            /sigmaCCostMaxInstance => //.\n  Qed.\n\n  Global Instance sigmaCostMaxMaxInstance (N : nat) (A : finType)\n         (ccostA : CCostClass N A)\n         (ccostMaxInstance : CCostMaxClass N A)\n         (predInstance : PredClass A)\n         (ccostMaxInstance : CCostMaxClass N A)\n         (ccostMaxMaxInstance : @CCostMaxMaxClass N A _ _ )\n    : CCostMaxMaxClass (T := [finType of {x : A | the_pred x}]) _ _.\n  Proof.\n    rewrite /CCostMaxMaxClass /ccost_fun /ccostmax_fun\n            /sigmaCCostInstance /sigmaCCostMaxInstance => //.\n  Defined.\n\n  Global Instance sigma_cgame (N : nat) (A : finType)\n           (predInstance : PredClass A)\n           (costA : CostClass N rat_realFieldType A)\n           (costAxiomA : @CostAxiomClass N rat_realFieldType A costA)\n           (costMaxA : CostMaxClass N rat_realFieldType A)\n           (costMaxAxiomA : CostMaxAxiomClass _ _)\n           (ccostA : CCostClass N A)\n           (ccostMaxA : CCostMaxClass N A)\n           (refineCostMaxInstanceA : RefineCostMaxClass costMaxA ccostMaxA)\n           (ccostMaxMaxA : @CCostMaxMaxClass N A _ _)\n           `(refineTypeA : RefineTypeClass A)\n           (refineCostAxiomA : @RefineCostAxiomClass N A costA ccostA)\n           (refineCostA : @RefineCostClass N A costA ccostA _)\n           (gA : @game A N rat_realFieldType _ _ _ _)\n           (cgA : @cgame N A _ _ _ _ _ _ _ _ _ _ _ _ _ _ )\n    : @cgame N [finType of {x : A | the_pred x}] _ _ _ _ _ _ _ _ _ _ _\n             _\n             (sigmaCostMaxRefineInstance refineCostMaxInstanceA)\n             (sigmaGameInstance N _ A predInstance gA) .  \nEnd sigmaCompilable.\n\n(***************************************\n  Product Games are compilable \n ***************************************)\n\nInstance prodEnumerableInstance (aT bT : Type)\n         (enumerableA : Enumerable aT)\n         (enumerableB : Enumerable bT)\n  : Enumerable (aT*bT) :=\n  List.list_prod (enumerate aT) (enumerate bT).\n\nProgram Instance prodRefineTypeAxiomInstance\n        (aT bT : finType)\n        `(refineTypeAxiomInstanceA : RefineTypeAxiomClass aT)\n        `(refineTypeAxiomInstanceB : RefineTypeAxiomClass bT)\n  : @RefineTypeAxiomClass [finType of aT*bT] _.\nNext Obligation.\n  rewrite /RefineTypeAxiomClass in refineTypeAxiomInstanceA.\n  rewrite /RefineTypeAxiomClass in refineTypeAxiomInstanceB.\n  case: refineTypeAxiomInstanceA=> [HA0 HA1].\n  case: refineTypeAxiomInstanceB=> [HB0 HB1].\n  split.\n  { move => r. rewrite mem_enum. case: r. move => a b.\n    rewrite /prodEnumerableInstance /enumerable_fun.\n    rewrite /eq_mem in HA0. rewrite /eq_mem in HB0.\n    have H: (List.In (a, b) (List.list_prod (enumerate aT) (enumerate bT))).\n    { apply List.in_prod_iff. split; apply list_in_iff.\n      - by rewrite HA0; apply mem_enum.\n      - by rewrite HB0; apply mem_enum. }\n    apply list_in_iff in H. by rewrite H. }\n    by apply: list_prod_uniq; assumption.\nQed.\n\nInstance prodRefineTypeInstance (aT bT : finType)\n         `(refineTypeAxiomInstanceA : RefineTypeAxiomClass aT)\n         `(refineTypeAxiomInstanceB : RefineTypeAxiomClass bT)\n  : @RefineTypeClass [finType of aT*bT]  _ _.\n\nInstance prodCCostInstance\n       N \n       (aT bT : Type)\n       `(ccostA : CCostClass N aT)\n       `(ccostB : CCostClass N bT)\n  : CCostClass N (aT*bT)\n  :=\n    (fun (i : OrdNat.t) (m : M.t (aT*bT)) =>\n       (ccost i (map_split m).1 +\n         ccost i (map_split m).2))%D.\n\nProgram Instance prodRefineCostAxiomInstance\n        (N : nat) (aT bT : finType)\n        (costA : CostClass N rat_realFieldType aT)\n        (costB : CostClass N rat_realFieldType bT)\n        (ccostA : CCostClass N aT)\n        (ccostB : CCostClass N bT)\n        (refineA : RefineCostAxiomClass costA ccostA)\n        (refineB : RefineCostAxiomClass costB ccostB)\n  : @RefineCostAxiomClass\n      N [finType of aT*bT]\n      (@prodCostInstance N rat_realFieldType aT bT costA costB)\n      (@prodCCostInstance N aT bT ccostA ccostB).\nNext Obligation.\n  have H2: (D_to_Q ((ccost) i (map_split m).1) ==\n            rat_to_Q\n              ((cost) (Ordinal (n:=N) (m:=i) pf) [ffun j => (s j).1]))%coq_Qscope.\n  { apply: refineA => j pf'.\n    rewrite ffunE.\n    specialize (H j pf').\n    move: H. case: (s (Ordinal (n:=N) (m:=j) pf')) => a b H.\n    apply map_split_spec in H.\n    case: H => H0 H1.\n    apply H0. }\n  have H3: (D_to_Q ((ccost) i (map_split m).2) ==\n            rat_to_Q\n              ((cost) (Ordinal (n:=N) (m:=i) pf) [ffun j => (s j).2]))%Q.\n  { apply refineB. move => j pf'.\n    rewrite ffunE.\n    specialize (H j pf').\n    move: H. case: (s (Ordinal (n:=N) (m:=j) pf')) => a b H.\n    apply map_split_spec in H.\n    case: H => H0 H1.\n    apply H1. }\n  rewrite /ccost_fun in H2, H3.\n  rewrite Dadd_ok.\n  rewrite H2 H3 [rat_to_Q (_ + _)] rat_to_Q_red.\n  by apply Qeq_sym; rewrite -rat_to_Q_red rat_to_Q_plus.\nQed.\n\nInstance prodRefineCostInstance (N : nat) (aT bT : finType)\n         (costA : CostClass N rat_realFieldType aT)\n         (costB : CostClass N rat_realFieldType bT)\n         (ccostA : CCostClass N aT)\n         (ccostB : CCostClass N bT)\n         (refineA : RefineCostAxiomClass costA ccostA)\n         (refineB : RefineCostAxiomClass costB ccostB)\n  : @RefineCostClass N [finType of aT*bT] _ _ _.\n\nInstance prodCCostMaxInstance (N : nat) (aT bT : Type)\n         (ccostMaxA : CCostMaxClass N aT)\n         (ccostMaxB : CCostMaxClass N bT)\n  : CCostMaxClass N (aT*bT) := (ccostMaxA + ccostMaxB)%D. \n\nInstance prodRefineMaxCostInstance (N : nat) (aT bT : finType)\n         (costMaxA   : CostMaxClass N _ aT)\n         (ccostMaxA  : CCostMaxClass N aT)\n         (refineMaxA : RefineCostMaxClass costMaxA ccostMaxA)\n         (costMaxB   : CostMaxClass N _ bT)\n         (ccostMaxB  : CCostMaxClass N bT)       \n         (refineMaxB : RefineCostMaxClass costMaxB ccostMaxB)\n  : RefineCostMaxClass\n      (prodCostMaxInstance costMaxA costMaxB)\n      (prodCCostMaxInstance ccostMaxA ccostMaxB).\nProof.\n  rewrite /RefineCostMaxClass /prodCostMaxInstance /prodCCostMaxInstance\n          rat_to_Q_plus Dadd_ok.\n  by apply: Qplus_le_compat.\nQed.\n\n\nLemma split_lt_max :\n  forall (N : nat) aT bT\n         `(costA : CostClass N rat_realFieldType aT)\n         `(costB : CostClass N rat_realFieldType bT)\n         (ccostA : CCostClass N aT)\n         (ccostB : CCostClass N bT)\n         (ccostMaxA  : CCostMaxClass N aT)       \n         (ccostMaxB  : CCostMaxClass N bT)\n         (ccostMaxMaxA : @CCostMaxMaxClass N aT _ _ )\n         (ccostMaxMaxB : @CCostMaxMaxClass N bT _ _ )\n  (m : M.t (aT * bT)) i,\n    (0 <= (ccost_fun (N := N) i (map_split m).1) + (ccost_fun (N := N) i (map_split m).2) <=\n     ccostMaxA + ccostMaxB)%DRed.\nProof.\n  intros.\n  generalize dependent ((map_split m).1) => ma.\n  generalize dependent ((map_split m).2) => mb.\n  have: (0 <= ccost_fun (N := N) i ma <= ccostMaxA)%DRed;\n    last move => H; eauto.\n  have: (0 <= (ccost_fun (N := N) i mb) <= ccostMaxB)%DRed;\n    last move => H1;\n  eauto.\n  generalize dependent ((ccost) i ma).\n  generalize dependent ((ccost) i mb).\n  intros.\n  unfold Dle in *.\n  rewrite !Dadd_ok.\n  destruct H1,H.\n  split.\n  2: apply Qplus_le_compat; auto.\n  clear -H0 H.\n  generalize dependent (D_to_Q d).\n  generalize dependent (D_to_Q d0).\n  intros.\n  unfold D_to_Q in *.\n  simpl in *.\n  assert (0 # 2 == 0)%Q => //.\n  rewrite -> H1 in *.\n  clear H1.\n  clear -H H0.\n  destruct q,q0 => //.\n  unfold Qle in *.\n  simpl in *.\n  ring_simplify in H.\n  ring_simplify in H0.\n  ring_simplify.\n  apply Z.add_nonneg_nonneg;\n  apply Z.mul_nonneg_nonneg => //.\nQed.\n\nInstance prodCostMaxMaxInstance (N : nat) (aT bT : finType)\n         (costA : CostClass N rat_realFieldType aT)\n         (costAxiomA : @CostAxiomClass N rat_realFieldType aT costA)\n         (costB : CostClass N rat_realFieldType bT)\n         (costAxiomB : @CostAxiomClass N rat_realFieldType bT costB)\n         (ccostA : CCostClass N aT)\n         (ccostB : CCostClass N bT)\n         (ccostMaxA  : CCostMaxClass N aT)       \n         (ccostMaxB  : CCostMaxClass N bT)       \n         (ccostMaxMaxA : @CCostMaxMaxClass N aT _ _ )\n         (ccostMaxMaxB : @CCostMaxMaxClass N bT _ _ )\n  : @CCostMaxMaxClass N (aT*bT) _ _ .\nProof.\n  rewrite /CCostMaxMaxClass;\n  rewrite /ccost_fun /ccostmax_fun\n          /prodCCostInstance /prodCCostMaxInstance.\n  intros.\n  apply split_lt_max => //.\nQed.\n\nInstance prod_cgame (N : nat) (aT bT : finType)\n         (costA : CostClass N rat_realFieldType aT)\n         (costAxiomA : @CostAxiomClass N rat_realFieldType aT costA)\n         (ccostA : CCostClass N aT)\n         (costMaxA : CostMaxClass N rat_realFieldType aT)\n         (ccostMaxA  : CCostMaxClass N aT)\n         (costMaxAxiomA : CostMaxAxiomClass costA _)\n         (refineMaxA : RefineCostMaxClass costMaxA ccostMaxA)\n         `(refineTypeA : RefineTypeClass aT)\n         (refineCostAxiomA : @RefineCostAxiomClass N aT costA ccostA)\n         (refineCostA : @RefineCostClass N aT costA ccostA _)\n         (costMaxMaxA : @CCostMaxMaxClass N aT _ _)\n         (gA : @game aT N rat_realFieldType _ _ _ _)\n         (cgA : @cgame N aT _ _ _ _ _ _ _ _ _ _ _ _ _ _)\n         (costB : CostClass N rat_realFieldType bT)\n         (costAxiomB : @CostAxiomClass N rat_realFieldType bT costB)\n         (ccostB : CCostClass N bT)\n         (ccostMaxB : CCostMaxClass N bT)\n         (costMaxB : CostMaxClass N rat_realFieldType bT)\n         (costMaxAxiomB : CostMaxAxiomClass costB _)\n         (refineMaxB : RefineCostMaxClass costMaxB ccostMaxB)\n         `(refineTypeB : RefineTypeClass bT)\n         (refineCostAxiomB : @RefineCostAxiomClass N bT costB ccostB)\n         (costMaxMaxA : @CCostMaxMaxClass N bT _ _)\n         (refineCostB : @RefineCostClass N bT costB ccostB _)\n         (gB : @game bT N rat_realFieldType _ _ _ _)\n         (cgB : @cgame N bT _ _ _ _ _ _ _ _ _ _ _ _ _ _)\n  : @cgame N [finType of aT*bT] _ _ _ _ _ _ _ _ _ _ _\n           _\n           _\n           (prodGameInstance N _ _ _ gA gB).\n\n\nModule ProdCGameTest. Section prodCGameTest.\n  Context {A B : finType} {N : nat} `{cgame N A} `{cgame N B}.\n  Variable i' : OrdNat.t.\n  Variable t' : M.t (A*B).\n  Check ccost_fun (N:=N) i' t'.\nEnd prodCGameTest. End ProdCGameTest.\n\n(*******************************************\n Scalar Games are Compilable \n *******************************************)\n\nInstance scalarEnumerableInstance\n         (A : Type)\n         `(Enumerable A)\n         `(ScalarClass)\n  : Enumerable (scalar scalar_val A) := \n    map (@Wrap (Scalar scalar_val) A) (enumerate A).\n\nDefinition unwrapScalarTree\n           A `(ScalarClass) : M.t (scalar scalar_val A) -> M.t A :=\n  fun m : (M.t (scalar scalar_val A)) =>\n    M.fold (fun i r acc =>\n              M.add i (unwrap r) acc)\n      m (M.empty A).    \n\nGlobal Instance scalarCCostInstance\n         N (A : Type)\n         `(Enumerable A)\n         `(CCostClass N A)\n         `(DyadicScalarClass)\n  : CCostClass N (scalar scalar_val A)\n  :=\n    fun (i : OrdNat.t) (m : M.t (@scalar _ scalar_val A)) =>\n      (dyadic_scalar_val * ccost i (unwrapScalarTree m))%D.\n\nInstance scalarCCostMaxInstance\n         N (A : Type)\n         `(cmax : CCostMaxClass N A)\n         `(DyadicScalarClass)\n  : @CCostMaxClass N (scalar scalar_val A) := (dyadic_scalar_val * cmax)%D.\n\nSection scalarCompilable.\n  Context {A N} `{Hdyadic: DyadicScalarClass} `{cgame N A}.\n\n  Global Program Instance scalarRefineTypeAxiomInstance\n    : @RefineTypeAxiomClass (scalarType scalar_val A) _.\n  Next Obligation.\n    clear H1 H2 ccostMaxMaxClass  refineCostAxiomClass H0 refineCostClass ccostClass\n          costAxiomClass costMaxAxiomClass costClass.\n    generalize H; clear H.\n    rewrite /RefineTypeAxiomClass => H.\n    destruct H; split; last first.\n    {\n      rewrite map_inj_uniq. apply H.\n      rewrite /injective => x1 x2 H3.\n      inversion H3 => //.\n    }\n    rewrite /(enumerate Wrapper Singleton A) /singCTypeInstance.\n    move => r.\n    apply /mapP.\n    case_eq (in_mem\n               r (mem\n                  (enum_mem\n                     (T:=scalarType (rty:=rat_realFieldType) scalar_val A)\n                     (mem (sort_of_simpl_pred (pred_of_argType\n              (Wrapper (Scalar (rty:=rat_realFieldType) scalar_val) A)))))))\n      => H3; rewrite H3.\n    {\n      move: H3.\n      case: r => x H3.\n      exists x; last by [].\n      rewrite H0 mem_enum.\n      rewrite mem_enum in H3 => //.\n    }\n    {\n      move => H4.\n      case: H4 => x H4 H5.\n      rewrite H5 in H3.\n      move/negP: H3 => H3.\n      apply H3 => //.\n      rewrite mem_enum => //.\n    }\n  Qed.\n\n  Global Instance scalarRefineTypeInstance\n    : @RefineTypeClass (scalarType scalar_val A)  _ _.\n\n  Lemma unwrapScalarTree_spec i (t : scalarType scalar_val A) m:\n    M.find i m = Some t ->\n    M.find i (unwrapScalarTree m) = Some (unwrap t).\n  Proof.\n    clear H H0 H1 H2 ccostMaxMaxClass refineCostAxiomClass refineCostClass\n          ccostClass costAxiomClass costMaxAxiomClass costClass.\n    rewrite /unwrapScalarTree.\n    apply MProps.fold_rec_weak.\n    {\n      move => mo m' a' H0 H1 H2.\n      have H3: (forall (k : M.key) e,\n        M.MapsTo k e mo <-> M.MapsTo k e m');\n          first by apply MProps.F.Equal_mapsto_iff; apply H0.\n      apply M.find_2 in H2. apply H3 in H2. apply M.find_1 in H2.\n      apply H1. apply H2.\n    }\n    {\n      move => H. inversion H.\n    }\n    {\n      move => k e a' m' H0 IH. case: e. move => a0 H2 /=.\n      rewrite MProps.F.add_o. case: (MProps.F.eq_dec k i) => H3 //.\n      generalize H2; clear H2.\n      rewrite MProps.F.add_eq_o. move => H2. inversion H2.\n      split => []. by []. apply IH.\n      generalize H2; clear H2.\n      rewrite MProps.F.add_neq_o. move => H2. inversion H2 => //.\n      by [].\n    }\n  Qed.\n\n  Global Program Instance scalarRefineCostAxiomInstance\n    : @RefineCostAxiomClass\n        N (scalarType scalar_val A)\n        (@scalarCostInstance _ _ _ costClass scalar_val)\n        _. \n  Next Obligation.\n    clear H H0 H1 H2\n          refineCostClass costAxiomClass.\n    rewrite /cost_fun /scalarCostInstance /cost_fun.\n    rewrite /(ccost) /scalarCCostInstance /(ccost).\n    rewrite [rat_to_Q (_ * _)] rat_to_Q_red.\n    rewrite -rat_to_Q_red /scalar_val.\n    rewrite rat_to_Q_mul Dmult_ok.\n    generalize (Qeq_dec (rat_to_Q (projT1 dyadic_scalar_val)) 0%Q).\n    case => H0.\n    { rewrite H0 !Qmult_0_l => //.\n      have ->: (D_to_Q dyadic_scalar_val == 0)%Q.\n      { by rewrite dyadic_rat_to_Q H0. }\n      by rewrite Qmult_0_l. }\n    have ->: (D_to_Q dyadic_scalar_val == rat_to_Q (projT1 dyadic_scalar_val))%Q.\n    { apply: dyadic_rat_to_Q. }\n    apply Qmult_inj_l => //.\n    move: refineCostAxiomClass; clear refineCostAxiomClass.\n    rewrite /RefineCostAxiomClass /(ccost) => refineCostAxiomClass.\n    specialize (refineCostAxiomClass pf).\n    rewrite -(@refineCostAxiomClass(unwrapScalarTree m)) => //.\n    move => j pf'. \n    specialize (H3 j pf').\n    apply unwrapScalarTree_spec in H3.\n    rewrite H3. f_equal.\n    rewrite /unwrap_ffun. rewrite ffunE => //.\n  Qed.\n\n  Global Instance scalarRefineCostInstance\n    : @RefineCostClass N (scalarType scalar_val A)\n        (@scalarCostInstance N _ A costClass _) _ _.\n\n  Global Instance scalarRefineCostMaxInstance\n         `(scalarAxiomInstance : @ScalarAxiomClass _ scalar_val)\n    : @RefineCostMaxClass\n        N (scalarType scalar_val A)\n        (scalarCostMaxInstance costMaxClass scalar_val)\n        (scalarCCostMaxInstance ccostMaxClass dyadic_scalar_val).\n  Proof.\n    rewrite /RefineCostMaxClass /scalarCostMaxInstance /scalarCCostMaxInstance.\n    rewrite rat_to_Q_mul Dmult_ok.\n    rewrite /scalar_val.\n    have ->: (rat_to_Q (projT1 dyadic_scalar_val) == D_to_Q dyadic_scalar_val)%Q.\n    { by rewrite dyadic_rat_to_Q. }\n    rewrite Qmult_comm [Qmult (D_to_Q _) _]Qmult_comm.\n    apply Qmult_le_compat_r => //.\n    have H3 : rat_to_Q 0 = 0%Q by rewrite rat_to_Q0.\n    rewrite -H3.\n    have ->: (D_to_Q dyadic_scalar_val == rat_to_Q (projT1 dyadic_scalar_val))%Q.\n    { by apply: dyadic_rat_to_Q. }\n    apply le_rat_to_Q => //.\n  Qed.\n\n  Global Instance scalarCostMaxMaxInstance \n         `(scalarAxiomInstance : @ScalarAxiomClass _ scalar_val)\n         (ccostMaxMax : @CCostMaxMaxClass N A\n                                          _ _ )\n    : @CCostMaxMaxClass N  (scalarType scalar_val A) _ _.\n  Proof.\n    split;\n      rewrite /CCostMaxMaxClass;\n    unfold CCostMaxMaxClass in ccostMaxMax;\n    specialize (ccostMaxMax i (unwrapScalarTree m));\n    rewrite  /ccost_fun;\n    unfold Dle in *;\n    repeat rewrite Dmult_ok;\n    rewrite Qmult_comm;\n    destruct ccostMaxMax.\n    +\n      have: (D_to_Q 0 == 0)%Q => [|ZeroZero] //.\n      rewrite -> ZeroZero in *.\n      apply Qmult_le_0_compat => //; eauto.\n      have H5 : rat_to_Q 0 = 0%Q by rewrite rat_to_Q0.\n      rewrite -H5.\n      have ->: (D_to_Q dyadic_scalar_val == rat_to_Q (projT1 dyadic_scalar_val))%Q.\n      { by apply: dyadic_rat_to_Q. }\n      apply le_rat_to_Q => //.\n    +\n        have->: (Qmult (D_to_Q (dyadic_rat_to_D Hdyadic))\n                     (D_to_Q ccostMaxClass) ==\n               Qmult (D_to_Q ccostMaxClass)\n                     (D_to_Q (dyadic_rat_to_D Hdyadic)))%coq_Qscope.\n      rewrite Qmult_comm => //.\n      apply Qmult_le_compat_r => //.\n      have H5 : rat_to_Q 0 = 0%Q by rewrite rat_to_Q0.\n      rewrite -H5.\n      have ->: (D_to_Q dyadic_scalar_val == rat_to_Q (projT1 dyadic_scalar_val))%Q.\n      { by apply: dyadic_rat_to_Q. }\n      apply le_rat_to_Q => //.\n  Qed.\n\n  Global Instance scalar_cgame\n         `{scalarA : @ScalarAxiomClass _ scalar_val}\n    : @cgame\n        N (scalarType scalar_val A)\n        _ _ _ _ _ _ _ _ _ _ _ _ _\n        (scalarGameInstance _ _ _ _ _).\nEnd scalarCompilable.\n\nModule ScalarCGameTest. Section scalarCGameTest.\n  Context {A : finType} {N : nat} `{cgame N A}\n          `{Hdyad: DyadicScalarClass}\n          `{scalarA : @ScalarAxiomClass _ scalar_val}.\n  Variable i' : OrdNat.t.\n  Variable t' : M.t (@scalarType rat_realFieldType scalar_val A).\n  Check ccost_fun (N:=N) i' t'.\nEnd scalarCGameTest. End ScalarCGameTest.\n\n(**********************************\n Bias Games are Compilable \n **********************************)\n\nDefinition unwrapBiasTree A (q : rat) : M.t (bias q A) -> M.t A :=\n  fun m : (M.t (bias q A)) =>\n    M.fold (fun i r acc =>\n              M.add i (unwrap r) acc)\n      m (M.empty A).    \n\nGlobal Instance biasCCostInstance\n         N (A : Type)\n         `(Enumerable A) `(CCostClass N A)\n         (q : DRat)\n  : CCostClass N (bias (projT1 q) A)\n  :=\n    fun (i : OrdNat.t) (m : M.t (bias (projT1 q) A)) =>\n      (q + ccost i (unwrapBiasTree m))%D.\n  \nInstance biasCCostMaxInstance N (A : Type) `(cmax : CCostMaxClass N A) (q : DRat)\n  : @CCostMaxClass N (bias (projT1 q) A) := (q + cmax)%D.\n\nInstance biasCTypeInstance A (q : DRat)\n         `(Enumerable A)\n  : Enumerable (bias (projT1 q) A) :=\n  map (@Wrap (Bias (projT1 q)) A) (enumerate A).\n\nSection biasCompilable.\n  Context {A N} {q : DRat} `{cgame N A}.\n\n  Global Program Instance biasRefineTypeAxiomInstance\n    : @RefineTypeAxiomClass (biasType (projT1 q) A) _.\n  Next Obligation.\n    clear H1 H2 ccostMaxMaxClass refineCostAxiomClass  H0 refineCostClass\n          ccostClass costAxiomClass costMaxAxiomClass costClass.\n    generalize H; clear H.\n    rewrite /RefineTypeAxiomClass => H.\n    destruct H; split; last first.\n    {\n      rewrite map_inj_uniq. apply H.\n      rewrite /injective => x1 x2 H3.\n      inversion H3 => //.\n    }\n    rewrite /(enumerate Wrapper Singleton A) /singCTypeInstance.\n    move => r.\n    apply /mapP.\n    case_eq (in_mem r (mem (enum_mem (T:=biasType (rty:=rat_realFieldType) q A)\n              (mem (sort_of_simpl_pred (pred_of_argType\n                (Wrapper (Bias (rty:=rat_realFieldType) q) A))))))) => H3; rewrite H3.\n    {\n      move: H3.\n      case: r => x H3.\n      exists x; last by [].\n      rewrite H0 mem_enum.\n      rewrite mem_enum in H3 => //.\n    }\n    {\n      move => H4.\n      case: H4 => x H4 H5.\n      rewrite H5 in H3.\n      move/negP: H3 => H3.\n      apply H3 => //.\n      rewrite mem_enum => //.\n    }\n  Qed.\n\n  Global Instance biasRefineTypeInstance\n    : @RefineTypeClass (biasType (projT1 q) A)  _ _.\n\n  Lemma unwrapBiasTree_spec i (t : biasType (projT1 q) A) m:\n    M.find i m = Some t ->\n      M.find i (unwrapBiasTree m) = Some (unwrap t).\n  Proof.\n    clear H H0 H1 H2 ccostMaxMaxClass refineCostAxiomClass refineCostClass\n          ccostClass costAxiomClass costMaxAxiomClass costClass.\n    rewrite /unwrapBiasTree.\n    apply MProps.fold_rec_weak.\n    {\n      move => mo m' a' H0 H1 H2.\n      have H3: (forall (k : M.key) e,\n        M.MapsTo k e mo <-> M.MapsTo k e m');\n          first by apply MProps.F.Equal_mapsto_iff; apply H0.\n      apply M.find_2 in H2. apply H3 in H2. apply M.find_1 in H2.\n      apply H1. apply H2.\n    }\n    {\n      move => H. inversion H.\n    }\n    {\n      move => k e a' m' H0 IH. case: e. move => a0 H2 /=.\n      rewrite MProps.F.add_o. case: (MProps.F.eq_dec k i) => H3 //.\n      generalize H2; clear H2.\n      rewrite MProps.F.add_eq_o. move => H2. inversion H2.\n      split => []. by []. apply IH.\n      generalize H2; clear H2.\n      rewrite MProps.F.add_neq_o. move => H2. inversion H2 => //.\n      by [].\n    }\n  Qed.\n\n  Global Program Instance biasRefineCostAxiomInstance\n    : @RefineCostAxiomClass _ (biasType (projT1 q) A) (biasCostInstance costClass) _.\n  Next Obligation.\n    clear H H0 H1 H2\n          refineCostClass costAxiomClass.\n    rewrite /cost_fun /biasCostInstance /cost_fun.\n    rewrite /(ccost) /biasCCostInstance /ccost_fun /(ccost).\n    rewrite [rat_to_Q (_ + _)] rat_to_Q_red.\n    rewrite Dadd_ok.\n    rewrite -rat_to_Q_red.\n    rewrite rat_to_Q_plus /scalar_val.\n    rewrite /bias_val.\n    have ->: (D_to_Q q == rat_to_Q (projT1 q))%Q.\n    { by apply: dyadic_rat_to_Q. }\n    move: (Qeq_dec (rat_to_Q q) 0%Q).\n    move: refineCostAxiomClass; clear refineCostAxiomClass.\n    rewrite /RefineCostAxiomClass /(ccost) => refineCostAxiomClass.\n    specialize (refineCostAxiomClass pf) => H.\n    rewrite ->(@refineCostAxiomClass(unwrapBiasTree m)) => //.\n    move => j pf'. \n    specialize (H3 j pf').\n    apply unwrapBiasTree_spec in H3.\n    rewrite H3. f_equal.\n    rewrite /unwrap_ffun. rewrite ffunE => //.\n  Qed.\n\n  Global Instance biasRefineCostInstance\n    : @RefineCostClass N (biasType (projT1 q) A) (biasCostInstance costClass) _ _.\n\n  Global Instance biasRefineCostMaxInstance\n         `(biasAxiomInstance : @BiasAxiomClass _ (projT1 q))\n    : @RefineCostMaxClass N (biasType (projT1 q) A)\n        (biasCostMaxInstance _ _ _ costMaxClass biasAxiomInstance)\n        (biasCCostMaxInstance _ _).\n  Proof.\n    rewrite /RefineCostMaxClass /biasCostMaxInstance /biasCCostMaxInstance\n            rat_to_Q_plus Dadd_ok /bias_val.\n    have ->: (D_to_Q q == rat_to_Q (projT1 q))%Q.\n    { by apply: dyadic_rat_to_Q. }\n    apply Qplus_le_compat => //.    \n    apply Qle_refl.\n  Qed.\n\n  Global Instance biasCostMaxMaxInstance\n         `{@BiasAxiomClass rat_realFieldType q}\n         : @CCostMaxMaxClass N (biasType (projT1 q) A) _ _.\n  Proof.\n    split; \n    rewrite /CCostMaxMaxClass;\n    unfold CCostMaxMaxClass in ccostMaxMaxClass;\n    clear H2;\n    rename ccostMaxMaxClass into H4;\n    specialize (H4 i (unwrapBiasTree m));\n    rewrite  /ccost_fun\n              /biasCCostInstance;\n    rewrite /ccostmax_fun\n            /biasCCostMaxInstance;\n    destruct H4;\n    unfold Dle in *; repeat rewrite Dadd_ok.\n    +\n      have: (D_to_Q 0 == 0)%Q => [| ZeroZero] //.\n      clear -H2 H3 ZeroZero.\n      rewrite -> ZeroZero in *.\n      {\n        move: H2;\n        clear H2.\n        generalize dependent\n                   (D_to_Q ((ccost) i (unwrapBiasTree (A:=A) (q:=projT1 q) m))).\n        unfold BiasAxiomClass in H3.\n        unfold bias_val in *.\n        have: (0 <= D_to_Q q)%Q => //.\n        {\n          apply le_rat_to_Q in H3=> //.\n          clear -H3.\n          move: H3.\n          have->: ((rat_to_Q 0) = 0)%Q => //.\n          rewrite <- dyadic_rat_to_Q => //.\n        }\n        intros H2 q0 H0.\n        generalize dependent (D_to_Q q).\n        intros.\n        unfold Qle in *.\n        simpl in *.\n        ring_simplify in H0.\n        ring_simplify in H1.\n        ring_simplify.\n        apply Z.add_nonneg_nonneg;\n          apply Z.mul_nonneg_nonneg => //.\n      }\n      repeat rewrite Dadd_ok.\n      apply Qplus_le_compat => //.\n      my_omega.\n  Qed.\n\n  Global Instance bias_cgame `{@BiasAxiomClass rat_realFieldType q}\n    : @cgame N (biasType (projT1 q) A) _ _ _ _ _ _\n             (biasCostMaxAxiomInstance _ _ _ _ _ _ _ _)\n             _ _ _ _ _ _ (biasGameInstance _ _ _ _ _).\nEnd biasCompilable.\n\nModule BiasCGameTest. Section biasCGameTest.\n  Context {A : finType} {N : nat} `{cgame N A} {q : DRat}\n          `{biasA : @BiasAxiomClass rat_realFieldType q}.\n  Variable i' : OrdNat.t.\n  Variable t' : M.t (@biasType rat_realFieldType q A).\n  Check ccost_fun (N:=N) i' t'.\nEnd biasCGameTest. End BiasCGameTest.\n\n(***************************\n Unit Games are compilable \n ***************************)\n\nSection unitCompilable.\n  Variable (N : nat).\n\n  Global Instance unitEnumerableInstance : Enumerable Unit :=\n    [:: mkUnit].\n\n  Global Program Instance unitRefineTypeAxiomInstance\n    : @RefineTypeAxiomClass [finType of Unit] _.\n  Next Obligation. by split => // r; rewrite mem_enum; case: r. Qed.\n\n  Global Instance unitRefineTypeInstance\n    : @RefineTypeClass [finType of Unit]  _ _.\n\n  Definition unit_ccost (i : OrdNat.t) (m : M.t Unit) : D := 0.\n\n  Global Instance unitCCostInstance\n    : CCostClass N [finType of Unit] := unit_ccost.\n\n  Global Program Instance unitRefineCostAxiomInstance\n    : @RefineCostAxiomClass N [finType of Unit] _ _.\n  Next Obligation.\n    rewrite /(ccost) /(cost) /unitCostInstance /unitCCostInstance /unit_ccost.\n    by rewrite D_to_Q0 rat_to_Q0.\n  Qed.\n    \n  Global Instance unitRefineCostInstance\n    : @RefineCostClass N [finType of Unit] _ _ _.\n\n  Global Instance unitCCostMaxInstance\n    : @CCostMaxClass N [finType of Unit] := 0%D.\n\n  Global Instance unitrefineCostMaxInstance\n    : @RefineCostMaxClass _ _ (@unitCostMaxInstance N _) unitCCostMaxInstance.\n  Proof.\n    rewrite /RefineCostMaxClass /unitCostMaxInstance /unitCCostMaxInstance.\n    rewrite /rat_to_Q => //.\n  Qed.\n  Global Instance unitCCostMaxMaxInstance\n         : @CCostMaxMaxClass N [finType of Unit] _ _.\n  Proof.\n    rewrite /CCostMaxMaxClass.\n    move => i m.\n    rewrite /ccost_fun /ccostmax_fun /unitCCostInstance\n            /unit_ccost /unitCCostMaxInstance => //.\n  Qed.\n\n  Global Instance unit_cgame : cgame (N:=N) (T:= [finType of Unit]) _ _ _ _ _.\nEnd unitCompilable.\n\n(***************************\n Affine Games are compilable \n ***************************)\n\nSection affineCompilable.\n  Context {A N}\n          `{scalA : DyadicScalarClass}\n          `{scalB : DyadicScalarClass}\n          `{cgame N A}\n          `{Boolable A}\n          (eqA : Eq A) (eqDecA : Eq_Dec eqA).\n\n  Definition affine_preType :=\n    ((@scalarType rat_realFieldType (@dyadic_scalar_val scalA) A) *\n    (@scalarType rat_realFieldType (@dyadic_scalar_val scalB) (singletonType A)))%type.\n\n  Global Instance affineTypePredInstance :\n    PredClass (affine_preType) := affinePredInstance eqDecA.\n\n  Definition affineType := [finType of {x : affine_preType | the_pred x}].\n\n  Section affineGameTest.\n    Variable i' : OrdNat.t.\n    Variable t' : M.t (affine_preType).\n\n    Check ccost_fun (N:=N) i' t'.\n  End affineGameTest.\nEnd affineCompilable.\n\n\n(* Hints to help automatic instance derivation for typclasses eauto. *)\n  Hint Extern 4 (RefineTypeAxiomClass ?t)=>\n  refine (sigmaRefineTypeAxiomInstance _ _ _) : typeclass_instances.\n\n  Hint Extern 4 (CostClass ?n ?r ?t) =>\n  refine (sigmaCostInstance _) : typeclass_instances.\n\n  Hint Extern 1 (ScalarAxiomClass ?r )=> done : typeclass_instances.\n\n  Hint Extern 4 (CostAxiomClass ?c) =>\n  refine (sigmaCostAxiomInstance _ _ _ _ _) : typeclass_instances.\n\n  Hint Extern 4 (RefineCostAxiomClass ?c ?a) =>\n  refine (sigmaRefineCostAxiomInstance _ _ _ _ _ _)\n    : typeclass_instances.\n\n  Hint Extern 4 (RefineCostAxiomClass ?c ?a) =>\n  refine (sigmaCCostInstance _)\n    : typeclass_instances.\n\n  Hint Extern 4 (CostMaxAxiomClass ?cc ?cmc) =>\n  refine (sigmaCostMaxAxiomInstance _ _ _ _ _ _ _)\n    : typeclass_instances.\n\n  Hint Extern 4 (RefineCostMaxClass ?cc ?cmc) =>\n  compute; (try discriminate)\n    : typeclass_instances.\n\n  Hint Extern 4 (RefineTypeClass ?rtac) =>\n  refine  (sigmaRefineTypeInstance _ _ _)\n    : typeclass_instances.\n\n  Hint Extern 4 (RefineCostClass ?rtac) =>\n  refine (sigmaRefineCostInstance _ _)\n    : typeclass_instances.\n\n  Hint Extern 4 (CCostMaxMaxClass ?rtac ?m) =>\n  refine (scalarCostMaxMaxInstance _ _)\n    : typeclass_instances.\n\n", "meta": {"author": "gstew5", "repo": "cage", "sha": "402ed9a7ffb00a2cb64436ad99bd46e2e10047d7", "save_path": "github-repos/coq/gstew5-cage", "path": "github-repos/coq/gstew5-cage/cage-402ed9a7ffb00a2cb64436ad99bd46e2e10047d7/ccombinators.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.27265149029050384}}
{"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.\nFrom mathcomp Require Import div path tuple.\nRequire Import Init_ext ssrZ ZArith_ext String_ext Max_ext.\nRequire Import machine_int seq_ext ssrnat_ext tuple_ext path_ext.\nRequire order finmap.\nImport MachineInt.\nRequire Import C_types C_types_fp C_value.\n\nDeclare Scope C_expr_scope.\n\nLocal Close Scope Z_scope.\nLocal Open Scope zarith_ext_scope.\nLocal Open Scope C_types_scope.\n\nDefinition env_get str {g} (s : g.-env) : option (g.-typ) := assoc_get str s.\n\nInductive binop_ne : Set := and_e | shl_e | or_e | add_e | sub_e | mul_e.\n\nInductive binop_re : Set := neq_e | eq_e | lt_e | le_e | gt_e | ge_e | lor_e | land_e.\n\nDefinition conversion_rank (t : integral) : nat :=\n  match t with\n    | ulong => 50\n    | uint => 40\n    | sint => 40\n    | uchar => 20\n    | schar => 20\n  end.\n\nDefinition is_signed (t : integral) : bool :=\n  match t with\n    | uint => false\n    | sint => true\n    | uchar => false\n    | schar => true\n    | ulong => false\n  end.\n\nModule UnConv.\n\n(** safe unary conversion *)\n\nDefinition safe t1 t2 :=\n  if t1 == t2 then\n    true\n  else if (~~ is_signed t1) && (sizeof_integral t1 < sizeof_integral t2) then\n    true (* NB: do zero-extend *)\n  else if is_signed t1 && is_signed t2 && (sizeof_integral t1 <= sizeof_integral t2) then\n    true (* NB: do sign-extend *)\n  else\n    false.\n\n(** unary conversion : potential data loss *)\n\nDefinition data_loss t1 t2 :=\n  if (~~ is_signed t1) && (sizeof_integral t2 < sizeof_integral t1) then\n    true (* preserve low-order bits *)\n  else if is_signed t1 && is_signed t2 && (sizeof_integral t2 < sizeof_integral t1) then\n    true (* preserve low-order bits *)\n  else if is_signed t1 && (~~ is_signed t2) && (sizeof_integral t2 < sizeof_integral t1) then\n    true (* sign-extend to corresponding signed t2, then convert to unsigned *)\n  else\n    false.\n\n(** unary conversion : potential incorrect interpretation *)\n\nDefinition misinterpret t1 t2 :=\n  if (~~ is_signed t1) && is_signed t2 && (sizeof_integral t1 == sizeof_integral t2) then\n    true (* NB: preserve bit pattern; high-order bit becomes sign bit *)\n  else\n  if is_signed t1 && (~~ is_signed t2) && (sizeof_integral t1 == sizeof_integral t2) then\n    true (* NB: preserve bit pattern; high-order bit loses function as sign bit *)\n  else\n    false.\n\nLemma potential_unsafe_not_safe : forall a b,\n  data_loss a b || misinterpret a b -> ~~ safe a b.\nProof. by move=> [] []. Qed.\n\nGoal forall a b, data_loss a b -> ~~ misinterpret a b.\nProof. by move=> [] []. Abort.\n\nGoal forall a b, misinterpret a b -> ~~ data_loss a b.\nProof. by move=> [] []. Abort.\n\nGoal forall a b, safe a b -> ~~ data_loss a b.\nProof. by move=> [] []. Abort.\n\nGoal forall a b, safe a b -> ~~ misinterpret a b.\nProof. by move=> [] []. Abort.\n\nEnd UnConv.\n\n(** Modulo operation\n    This is a specialized version for powers of 2\n    E.g.,\n    <<\n    ciph_len mod 2 != 0\n    >>\n    becomes\n    <<\n    (bopk_ne mod2n_e (var_e \"ciph_len\") 1) \\!= cst32_0\n    >>\n    because 2 is 2^1 *)\n(* TODO: generalize the modulo operation to mod_e (%) : expr -> expr -> int such that:\n   4 % 3 -> 1\n   4 % 4 -> 0\n   4 % -? -> undefined *)\n\nInductive binopk_e : Set := mod2n_e.\n\nDefinition binopk_e_interp b {n} (x : int n) (k : nat):=\n  match b with\n    | mod2n_e => (@rem n _ (@rem k _ x))\n  end.\n\n(* TODO: generalize ifte_e condition to any integral type? *)\n(* TODO: constructor for hexadecimal constants? *)\nLocal Open Scope C_value_scope.\n\nSection exp_sect.\n\nVariables (g : wfctxt) (sigma : g.-env).\n\nInductive exp : g.-typ -> Type :=\n| var_e : forall str t, env_get str sigma = |_ t _| -> exp t\n| cst_e : forall t, t.-phy -> exp t\n| bop_n : forall t, binop_ne -> (* numerical operators *)\n  exp (ityp: t) -> exp (ityp: t) -> exp (ityp: t)\n| bopk_n : forall t, binopk_e ->\n  exp (ityp: t) -> nat -> exp (ityp: t)\n| bop_r : forall t, binop_re -> (* relational operators *)\n  exp (ityp: t) -> exp (ityp: t) -> exp (g.-ityp: uint)\n| add_p : forall t, exp (:* t) -> exp (ityp: sint) -> exp (:* t)\n| safe_cast : forall t t', exp (ityp: t) ->\n  UnConv.safe t t' -> exp (ityp: t')\n| unsafe_cast : forall t t', exp (ityp: t) ->\n  UnConv.data_loss t t' ||\n  UnConv.misinterpret  t t' -> exp (ityp: t')\n| fldp : forall f tg (t : g.-typ) (e : exp (:* t)) (H : styp tg = t) t',\n  assoc_get f (get_fields g tg) = |_ t' _| ->\n  exp (:* t')\n| eq_p : forall t, exp (:* t) -> exp (:* t) -> exp (g.-ityp: uint)\n| ifte_e : forall t, exp (ityp: uint) -> exp t -> exp t -> exp t.\n\nEnd exp_sect.\n\nArguments exp [g] _ _.\nArguments var_e [g] _ _ _ _.\nArguments cst_e [g] _ _ _.\nArguments bop_n [g] _ _ _ _ _.\nArguments bopk_n [g] _ _ _ _ _.\nArguments bop_r [g] _ _ _ _ _.\nArguments add_p [g] _ _ _ _.\nArguments safe_cast [g] _ _ _ _ _.\nArguments unsafe_cast [g] _ _ _ _ _.\nArguments fldp [g] _ _ [tg] [t] _ _ [t'] _.\nArguments eq_p [g] _ _ _ _.\nArguments ifte_e [g] _ _ _ _ _.\n\nSection vars_sect.\n\nVariable (g : wfctxt) (sigma : g.-env).\n\nFixpoint vars {t : g.-typ} (e : exp sigma t) : g.-env :=\nmatch e with\n  | var_e v t' H => (v, t') :: nil\n  | cst_e _ _ => nil\n  | bop_n _ _ e1 e2 => vars e1 ++ vars e2\n  | bopk_n _ _ e' _ => vars e'\n  | bop_r _ _ e1 e2 => vars e1 ++ vars e2\n  | add_p _ e1 e2 => vars e1 ++ vars e2\n  | safe_cast t t' e' t'_leq_t => vars e'\n  | unsafe_cast t t' e' t'_leq_t => vars e'\n  | fldp str tg t e' H t' Hin => vars e'\n  | eq_p t e1 e2 => vars e1 ++ vars e2\n  | ifte_e _ e1 e2 e3 => vars e1 ++ vars e2 ++ vars e3\nend.\n\nEnd vars_sect.\n\nArguments vars [g sigma] [t] _.\n\nLemma vars_in_ts {g sigma} {t : g.-typ} (e : exp sigma t) : { subset vars e <= sigma }.\nProof.\nelim: e => [ v t0 H x | // | op t0 e1 H1 e2 H2 x | // | op t0 e1 H1 e2 H2 x | t0 e1 H1 e2 H2 x | // | // | // | t0 e1 H1 e2 H2 x | t0 e1 H1 e2 H2 e4 H3 x ].\n- rewrite in_cons; case/orP => // /eqP => ?; subst x; by apply: assoc_get_in H.\n- rewrite mem_cat; case/orP; by [apply H1 | apply H2].\n- rewrite mem_cat; case/orP; by [apply H1 | apply H2].\n- rewrite mem_cat; case/orP; by [apply H1 | apply H2].\n- rewrite mem_cat; case/orP; by [apply H1 | apply H2].\n- rewrite mem_cat; case/orP; [ by apply H1 | ].\n  rewrite mem_cat; case/orP; by [apply H2 | apply H3].\nQed.\n\nNotation \"'[' pv ']c'\" := (cst_e _ _ pv) (at level 9, format \"'[' [  pv  ]c ']'\") : C_expr_scope.\nLocal Open Scope C_expr_scope.\n\nNotation \"'[' i ']pc'\" := ([ [ i ]p ]c) (at level 9, format \"'[' [  i  ]pc ']'\") : C_expr_scope.\n\nNotation \"'[' z ']sc'\" := ([ [ z ]s ]c) (at level 9, format \"'[' [  z  ]sc ']'\") : C_expr_scope.\nNotation \"'[' z ']uc'\" := ([ [ z ]u ]c) (at level 9, format \"'[' [  z  ]uc ']'\") : C_expr_scope.\n\nStructure Cadd g (sigma : g.-env) :=\n  { Cadd_t1 : g.-typ ;\n    Cadd_t2 : g.-typ ;\n    Cadd_add : exp sigma Cadd_t1 -> exp sigma Cadd_t2 -> exp sigma Cadd_t1 }.\n\nCanonical Structure Cadd_i g sigma t :=\n  Build_Cadd g sigma (ityp: t) (ityp: t) (bop_n sigma t add_e).\n\nCanonical Structure Cadd_p g sigma t :=\n  Build_Cadd g sigma (:* t) (ityp: sint) (add_p sigma t).\n\nDefinition Cadd_add_nosimpl g sigma := nosimpl (Cadd_add g sigma).\n\nNotation \"a '\\+' b\" := (Cadd_add_nosimpl _ _ _ a b) (at level 61, left associativity) : C_expr_scope.\n\nStructure Ceq {g sigma} := {\n  Ceq_t : g.-typ ;\n  Ceq_eq : exp sigma Ceq_t -> exp sigma Ceq_t -> exp sigma (g.-ityp: uint)}.\n\nCanonical Structure Ceq_i {g sigma} t :=\n  @Build_Ceq g sigma (g.-ityp: t) (bop_r sigma t eq_e).\n\nCanonical Structure Ceq_p {g sigma} t :=\n  @Build_Ceq g sigma (:* t) (eq_p sigma t).\n\nDefinition Ceq_eq_nosimpl {g} {sigma : g.-env} := nosimpl (@Ceq_eq g sigma).\n\nNotation \"a '\\=' b\" := (Ceq_eq_nosimpl _ a b) (at level 64, left associativity) : C_expr_scope.\n\nNotation \"a '\\&' b\" := (bop_n _ _ and_e a b) (at level 65, left associativity) : C_expr_scope.\nNotation \"a '\\|' b\" := (bop_n _ _ or_e a b) (at level 66, left associativity) : C_expr_scope.\nNotation \"a '\\-' b\" := (bop_n _ _ sub_e a b) (at level 61, left associativity) : C_expr_scope.\nNotation \"a '\\*' b\" := (bop_n _ _ mul_e a b) (at level 58, left associativity) : C_expr_scope.\nNotation \"a '\\<<' b\" := (bop_n _ _ shl_e a b) (at level 62, left associativity) : C_expr_scope.\nNotation \"e \\% n\" := (bopk_n _ _ mod2n_e e n) (at level 57, left associativity) : C_expr_scope.\nNotation \"a '\\!=' b\" := (bop_r _ _ neq_e a b) (at level 64, left associativity) : C_expr_scope.\nNotation \"a '\\<' b\" := (bop_r _ _ lt_e a b) (at level 63, left associativity) : C_expr_scope.\nNotation \"a '\\<=' b\" := (bop_r _ _ le_e a b) (at level 63, left associativity) : C_expr_scope.\nNotation \"a '\\>' b\" := (bop_r _ _ gt_e a b) (at level 63, left associativity) : C_expr_scope.\nNotation \"a '\\>=' b\" := (bop_r _ _ ge_e a b) (at level 63, left associativity) : C_expr_scope.\nNotation \"a '\\&&' b\" := (bop_r _ _ land_e a b) (at level 67, left associativity) : C_expr_scope.\nNotation \"a '\\||' b\" := (bop_r _ _ lor_e a b) (at level 68, left associativity) : C_expr_scope.\nNotation \"e '&->' n\" := (@fldp _ _ n _ _ e erefl _ erefl) (at level 56, left associativity) : C_expr_scope.\nNotation \"e \\? f \\: g\" := (@ifte_e _ _ _ e f g) (at level 69, right associativity) : C_expr_scope.\nNotation \"'[;' t ';]' e\" := (safe_cast _ t e (erefl _)) (at level 6) : C_expr_scope.\nNotation \"'(int)' e\" := (safe_cast _ _ sint e (erefl _)) (at level 6, format \"'[' '(int)'  e ']'\") : C_expr_scope.\nNotation \"'{;' t ';}' e\" := (unsafe_cast _ _ t e (erefl _)) (at level 6) : C_expr_scope.\nNotation \"'(UINT)' e\" := (unsafe_cast _ _ uint e (erefl _)) (at level 6, format \"'[' '(UINT)'  e ']'\") : C_expr_scope.\n\nDefinition NULL {g} {sigma : g.-env} {t : g.-typ} : exp sigma (:* t) := [ @pv0 g (mkptyp t) ]c.\n\n(** a value store is defined w.r.t. a type_store *)\n\nRecord store {g} (sigma : g.-env) :=\n  { store_list :> seq (string * {ty : g.-typ & ty.-phy}) ;\n    Hstore : map (fun x => (x.1, projT1 x.2)) store_list == sigma }.\n\nLemma store_irrelevance {g} (sigma : g.-env) : forall (s1 s2 : store sigma),\n  store_list sigma s1 = store_list sigma s2 -> s1 = s2.\nProof.\ncase=> s1 Hs1 [] s2 Hs2 /= ?; subst s2.\ncongr Build_store; exact: eq_irrelevance.\nQed.\n\nFixpoint sval_store0 {g} (sigma : g.-env) : seq (string * {t: g.-typ & t.-phy}) :=\n  match sigma with\n    | nil => nil\n    | (n, t) :: tl => (n, existT _ _ (@pv0 _ t)) :: sval_store0 tl\n  end.\n\nLemma rval_store0 {g} : forall (sigma : g.-env),\n  map (fun x => (x.1, projT1 x.2)) (sval_store0 sigma) == sigma.\nProof. by elim=> // [[str t] tl] /= /eqP ->. Qed.\n\nDefinition store0 {g} (sigma : g.-env) : store sigma :=\n  Build_store g sigma (sval_store0 sigma) (rval_store0 sigma).\n\nLemma env_get_proj_Some {g} : forall (sigma : g.-env) (s : store sigma) str t,\n  env_get str (map (fun x => (x.1, projT1 x.2)) s) = |_ t _| ->\n  exists y, assoc_get str s = Some y.\nProof.\nelim => [ [] // [] // | [str t] tl IH ].\ncase=> [[|h1 t1] //=] /eqP [] ? ?; subst str t => /eqP H1.\nmove=> str' t'.\nrewrite /env_get /=.\ncase: ifP => [/eqP ? |/negbT H2 H3].\n  subst str'.\n  case=> ?; subst t'.\n  by exists h1.2.\nby apply: IH (Build_store _ _ _ H1) _ t' H3.\nQed.\n\nLemma env_get_proj_Some2 {g} :\n  forall (sigma : g.-env) (s : store sigma) str t y (Hy : y.-phy),\n  assoc_get str sigma = |_ t _| -> assoc_get str s  = |_ existT _ y Hy _| ->\n  t = y.\nProof.\nelim => [ [] // [] // | [str t] tl IH ].\ncase=> [[|h1 t1] /= Hs] // str' t' y Hy.\ncase/eqP : Hs => ? ?; subst str t => /eqP Hs.\ncase: ifP => [/eqP ? | /negbT H2 h3].\n  subst str'.\n  case=> ?; subst t'.\n  by case=> ->.\nby move/(IH (Build_store _ _ _ Hs) str' _ _ Hy h3).\nQed.\n\nSection store_sect.\n\nVariables (g : wfctxt) (sigma : g.-env) (str : string) (t : g.-typ).\n\nLemma store_get_helper (s : store sigma) (Hstr : env_get str sigma = |_ t _|) :\n  forall Hl : {l : {i : g.-typ & i.-phy} & assoc_get str s = |_ l _|},\n  size (projT2 (projT1 Hl)) = sizeof t.\nProof.\nmove=> [] /= [] t' pv /=.\ncase: s => s Hs /=.\nmove/eqP in Hs; subst sigma.\nrewrite /env_get in Hstr.\nrewrite (Hphy _ pv) => H1.\nsuff ? : t' = t by subst.\nelim: s t t' pv H1 Hstr => // h1 t1 IH t_ t' pv /=.\ncase: ifP => [/eqP ? | /negbT H1].\n  subst str.\n  by case => -> [].\nby apply IH.\nQed.\n\nLemma store_get_helper2 (s : store sigma) (Hstr : env_get str sigma = |_ t _|) :\n assoc_get str s = None -> False.\nProof.\ncase: s => s Hs /= H1.\nmove/eqP in Hs; subst sigma.\nrewrite /env_get in Hstr.\nsuff : assoc_get str (map (fun x => (x.1, projT1 x.2)) s) = None by rewrite Hstr.\nelim: s Hstr H1 => // h1 t1 IH /=.\nby case: ifP.\nQed.\n\nDefinition store_get (Hstr : env_get str sigma = |_ t _|) (s : store sigma) : t.-phy.\ncase: (option_dec (assoc_get str s)).\n- move=> Hl.\n  apply mkPhy with (phy2seq (projT2 (projT1 Hl))).\n  apply store_get_helper.\n  exact Hstr.\n- move=> Hneq.\n  apply False_rect.\n  apply (store_get_helper2 _ Hstr Hneq).\nDefined.\n\nLemma store_upd_helper (Hstr : env_get str sigma = |_ t _|) (s : store sigma) val :\n  map (fun x => (x.1, projT1 x.2)) (assoc_upd str (existT _ t val) s) == sigma.\nProof.\ndestruct s as [s Hs] => /=.\nmove/eqP in Hs; subst sigma.\nelim: s t val Hstr => // h1 t1 IH ty val H /=.\ncase: ifP.\n  move/eqP => ?; subst str => /=.\n  rewrite /env_get /= eqxx in H.\n  by case: H => <-.\nmove/negbT => H1 /=.\napply/eqP.\ncongr cons.\napply/eqP/IH.\nby rewrite /env_get /= (negbTE H1) in H.\nQed.\n\nDefinition store_upd (Hstr : env_get str sigma = |_ t _|) val s :=\n  Build_store _ _ _ (store_upd_helper Hstr s val).\n\nLemma store_get_upd_eq (H : env_get str sigma = |_ t _|) val s :\n  store_get H (store_upd H val s) = val.\nProof.\nrewrite /store_get /store_upd /=.\ncase: option_dec => [ | Hcontr] /=.\n- case; move=> [x [phy2seq Hphy]] e.\n  apply mkPhy_irrelevance => /=.\n  have [y Hy] : exists y, assoc_get str s = Some y.\n    apply (env_get_proj_Some _ s str t).\n    case: s e => s Hs /= e.\n    move/eqP in Hs; by subst sigma.\n  rewrite (@assoc_get_upd_eq _ _ _ _ _ y) // in e.\n  case: e => ?; subst t => H1.\n  apply Eqdep.EqdepTheory.inj_pair2 in H1; by subst val.\n- suff: False by done.\n  move: (env_get_proj_Some _ s str t).\n  case: s Hcontr => s Hs /= Hcontr.\n  move/eqP in Hs; subst sigma.\n  case/(_ H) => y Hy.\n  by rewrite (@assoc_get_upd_eq _ _ _ _ _ y) // in Hcontr.\nQed.\n\nLemma store_upd_get_eq (Hstr : assoc_get str sigma = |_ t _|) s :\n  store_upd Hstr (store_get Hstr s) s = s.\nProof.\napply store_irrelevance => /=.\nrewrite /store_get /=.\nhave [y Hy] : exists y, assoc_get str s = Some y.\n  apply: env_get_proj_Some sigma _ _ t _.\n  case: s => s Hs /=.\n  by move/eqP : Hs => ->.\ncase: option_dec => /= s0.\n  apply assoc_upd_inv.\n  rewrite [X in X = _]Hy; congr Some.\n  case: s0 => s0 Hs0 /=.\n  have ? : y = s0 by rewrite Hs0 in Hy; case: Hy.\n  subst s0.\n  case: y Hy Hs0 => y Hy Hs0 Hy_.\n  have ? : y = t by rewrite (env_get_proj_Some2 _ _ _ _ _ _ Hstr Hy_).\n  subst y.\n  congr existT.\n  by apply mkPhy_irrelevance.\napply assoc_upd_inv; by rewrite s0 in Hy.\nQed.\n\nEnd store_sect.\n\nArguments store_get [g] [sigma] [str] [t] _ _.\nArguments store_upd [g] [sigma] [str] [t] _ _ _.\n\nLemma store_get_upd_neq {g} {sigma : g.-env} (s : store sigma) str1 t str2  val\n  (H1 : env_get str1 sigma = Some t) ty' (H2 : env_get str2 sigma = Some ty') :\n  str1 <> str2 ->\n  store_get H2 (store_upd H1 val s) = store_get H2 s.\nProof.\nmove=> str1_str2.\nrewrite /store_get /store_upd /=.\nmove Heq : (option_dec (assoc_get str2 (assoc_upd str1 (existT phy t val) s))) => [s'|].\n- case: s' Heq => [[i [lst Hlst]] /= Hl] Heq.\n  move: (not_eq_sym str1_str2) => {}str1_str2.\n  move Heq_rhs : (option_dec (assoc_get str2 s)) => [s'|].\n  + case: s' Heq_rhs => [[i' [lst' Hlst']] Hl'] Heq_rhs .\n    have ? : lst = lst'.\n      rewrite {Heq Heq_rhs}.\n      rewrite assoc_get_upd_neq // in Hl.\n      rewrite Hl in Hl'.\n      by case: Hl'.\n    subst lst'.\n    by apply mkPhy_irrelevance.\n  + suff : False by done.\n    clear Heq.\n    by rewrite assoc_get_upd_neq // Heq_rhs in Hl.\n- rewrite /False_rect /=.\n  by case: store_get_helper2.\nQed.\n\nProgram Definition safe_cast_phy_sint {g} (v : (ityp: sint).-phy) (t : integral)\n  (H : UnConv.safe sint t) : (ityp: t).-phy :=\n  match t with\n    | sint => v\n    | uint => @False_rect _ _\n    | uchar => @False_rect _ _\n    | schar => @False_rect _ _\n    | ulong => match v with\n                 mkPhy l Hl => mkPhy (g.-ityp: ulong)\n                 match oi32<=i8 l with\n                   | Some i => i8<=i64 (sext (8 * (sizeof_integral ulong - sizeof_integral sint)) i)\n                   | None => @False_rect _ _\n                 end _\n               end\n  end.\n\nObligation Tactic := idtac.\n\nProgram Definition safe_cast_phy_uint {g} (v : (ityp: uint).-phy) (t : integral)\n  (H : UnConv.safe uint t) : (ityp: t).-phy :=\n  match t with\n    | sint => @False_rect _ _\n    | uint => v\n    | uchar => @False_rect _ _\n    | schar => @False_rect _ _\n    | ulong => match v return (ityp: ulong).-phy with\n                 mkPhy l Hl => mkPhy (g.-ityp: ulong) _ _\n               end\n  end.\nNext Obligation.\nTactics.program_simpl.\nDefined.\nNext Obligation.\nTactics.program_simpl.\nDefined.\nNext Obligation.\nTactics.program_simpl.\nDefined.\nNext Obligation.\nintros.\ndestruct (option_dec (oi32_of_i8 l)) as [s|].\ndestruct s as [i Hi].\nexact (i8_of_i64 (zext (8 * (sizeof_integral ulong - sizeof_integral uint)) i)).\napply False_rect.\ncase: (@int_flat_Some _ _ _ (refl_equal _) _ Hl).\nmove: e.\nrewrite /oi32_of_i8 sizeof_ityp.\nby move=> ->.\nDefined.\nNext Obligation.\nintros.\nrewrite /safe_cast_phy_uint_obligation_4.\nrewrite /=.\ndestruct (@option_dec) as [s|].\n  destruct s as [i Hi].\n  by rewrite sizeof_ityp /= /i8_of_i64 size_int_break.\napply False_rect.\ncase: (@int_flat_Some _ _ _ Logic.eq_refl _ Hl).\nmove: e.\nrewrite /oi32_of_i8 sizeof_ityp.\nby move=> ->.\nDefined.\n\nObligation Tactic := Tactics.program_simpl.\n\nProgram Definition safe_cast_phy_uchar {g} (v : (g.-ityp: uchar).-phy) (t : integral)\n  (H : UnConv.safe uchar t) : (ityp: t).-phy :=\n  match v with\n    | mkPhy l Hl =>\n      match l with\n        | h :: nil =>\n          match t with\n            | uchar => v\n            | schar => mkPhy (ityp: schar) v (Hphy (ityp: schar) v)\n            | sint => mkPhy (ityp: sint) (i8<=i32 (zext (8 * (sizeof_integral sint - sizeof_integral uchar)) h)) _\n            | uint => mkPhy (ityp: uint) (i8<=i32 (zext (8 * (sizeof_integral uint - sizeof_integral uchar)) h)) _\n            | ulong => mkPhy (ityp: ulong) (i8<=i64 (zext (8 * (sizeof_integral ulong - sizeof_integral uchar)) h)) _\n          end\n        | _ => @pv0 g (g.-ityp: t) (* dummy; shouldn't happen*)\n      end\n  end.\nNext Obligation.\nrewrite /i8_of_i32 size_int_break sizeof_ityp.\nreflexivity.\nDefined.\nNext Obligation.\nby rewrite /i8_of_i32 size_int_break sizeof_ityp.\nDefined.\nNext Obligation.\nby rewrite /i8_of_i64 size_int_break sizeof_ityp.\nDefined.\n\nLemma safe_cast_phy_uchar_zext {g} (a : @phy g _) H :\n  safe_cast_phy_uchar a sint H = [ zext 24 (i8<=phy a) ]p.\nProof.\ndestruct a as [a Ha].\nhave Ha' : size a = 1 by rewrite Ha sizeof_ityp.\nhave Ha'Ha : Ha' = Ha by apply eq_irrelevance.\nsubst Ha.\ndestruct a as [|h []] => //=.\nby apply mkPhy_irrelevance.\nQed.\n\nProgram Definition safe_cast_phy_schar {g} (v : (g.-ityp: schar).-phy) (t : integral)\n  (H : UnConv.safe schar t) : (ityp: t).-phy :=\n  match v with\n    | mkPhy l Hl =>\n      match l return (ityp: t).-phy with\n        | h :: nil =>\n          match t with\n            | uchar => @False_rect _ _\n            | schar => v\n            | sint => mkPhy (ityp: sint)\n              (i8_of_i32 (sext (8 * (sizeof_integral sint - sizeof_integral schar)) h)) _\n            | uint => @False_rect _ _\n            | ulong => @False_rect _ _\n          end\n        | _ => @pv0 g (g.-ityp: t) (* dummy; shouldn't happen*)\n      end\n  end.\nNext Obligation.\nrewrite /i8_of_i32 size_int_break sizeof_ityp.\nreflexivity.\nDefined.\n\nProgram Definition safe_cast_phy {g t} (pv : (g.-ityp: t).-phy)\n  t' (H : UnConv.safe t t') : (g.-ityp: t').-phy :=\n  match t with\n    | sint => safe_cast_phy_sint pv t' H\n    | uint => safe_cast_phy_uint pv t' H\n    | uchar => safe_cast_phy_uchar pv t' H\n    | schar => safe_cast_phy_schar pv t' H\n    | ulong => pv\n  end.\nNext Obligation. by destruct t'. Defined.\n\nNotation \"'(phyint)' e\" := (safe_cast_phy e sint Logic.eq_refl)\n  (at level 6, format \"'[' '(phyint)'  e ']'\") : C_value_scope.\n\nLemma si32_of_phy_safe_cast_phy_uchar {g} (a : @phy g _) H :\n  si32<=phy (safe_cast_phy a sint H) = zext 24 (i8<=phy a).\nProof.\nrewrite /si32_of_phy /safe_cast_phy -2!Eqdep.Eq_rect_eq.eq_rect_eq.\nby rewrite safe_cast_phy_uchar_zext /= i8_of_i32Ko /=.\nQed.\n\nProgram Definition unsafe_cast_phy {g} {t} (v : (g.-ityp: t).-phy) t'\n  (H : UnConv.data_loss t t' || UnConv.misinterpret t t') : (ityp: t').-phy :=\n  match (t != t') && (sizeof_integral t == sizeof_integral t') with\n    | true =>\n      match v with mkPhy l Hl => mkPhy (ityp: t') l _ end\n    | false =>\n      match is_signed t && ~~ (is_signed t') && (sizeof_integral t < sizeof_integral t') with\n        | true => safe_cast_phy v t' _\n        | false =>\n          match sizeof_integral t' < sizeof_integral t with\n            | true => match v with\n                        mkPhy l Hl => mkPhy (ityp: t') (drop (sizeof_integral t - sizeof_integral t') l) _\n                      end\n            | false => @False_rect _ _\n          end\n      end\n  end.\nNext Obligation.\nmove: t t' H Hl Heq_anonymous.\nby move=> [] [] //=.\nDefined.\nNext Obligation.\nmove: t t' v H Heq_anonymous Heq_anonymous0.\nmove=> [] [] //=.\nDefined.\nNext Obligation.\nrewrite size_drop Hl.\nmove: t t' H Hl Heq_anonymous Heq_anonymous0 Heq_anonymous1.\nmove=> [] [] //=.\nDefined.\nNext Obligation.\nmove: t v t' H Heq_anonymous Heq_anonymous0 Heq_anonymous1.\nmove=> [] [] //=.\nby move=> s Hs [].\nby move=> s Hs [].\nby move=> s Hs [].\nby move=> s Hs [].\nby move=> s Hs [].\nDefined.\n\nDefinition binop_ne_interp b {n} : int n -> int n -> int n :=\n  match b with\n    | and_e => @int_and n\n    | or_e => @int_or n\n    | shl_e => fun e1 e2 => shl '|u2Z e2| e1\n    | add_e => @add n\n    | sub_e => @sub n\n    | mul_e => @mul n\n  end.\n\n(** reasoning over Z, in order to handle unsigned and signed integers in the same manner *)\n\nDefinition binop_re_interp b (x y : Z) : int 32 :=\n  match b with\n    | eq_e => if x == y then Z2u 32 1 else Z2u 32 0\n    | neq_e => if x == y then Z2u 32 0 else Z2u 32 1\n    | lt_e => if Zlt_bool x y then Z2u 32 1 else Z2u 32 0\n    | le_e => if Zle_bool x y then Z2u 32 1 else Z2u 32 0\n    | gt_e => if Zlt_bool y x then Z2u 32 1 else Z2u 32 0\n    | ge_e => if Zle_bool y x then Z2u 32 1 else Z2u 32 0\n    | lor_e => if (x == Z0) && (y == Z0) then Z2u 32 0 else Z2u 32 1\n    | land_e => if (x == Z0) || (y == Z0) then Z2u 32 0 else Z2u 32 1\n  end.\n\nLocal Open Scope machine_int_scope.\n\nReserved Notation \"'[' e ']_' s\" (at level 9, format \"'[' [  e  ]_ s ']'\", no associativity).\n\nFixpoint eval {g sigma t} (s : store sigma) (e : exp sigma t) : t.-phy :=\n  match e with\n    | var_e v t H => store_get H s\n    | cst_e t v => v\n    | bop_r t' b e1 e2 =>\n      match t' as t return (forall (_ : t = t'), (ityp: uint).-phy) with\n        | uint =>\n          match [ e1 ]_ s, [ e2 ]_ s with\n            | mkPhy l1 H1, mkPhy l2 H2 => fun (Heq : uint = t') =>\n                let H'1 := eq_ind_r (fun t => size l1 = sizeof (ityp: t)) H1 Heq in\n                let H'2 := eq_ind_r (fun t => size l2 = sizeof (ityp: t)) H2 Heq in\n                [ binop_re_interp b (u2Z (i32<=i8 l1 H'1)) (u2Z (i32<=i8 l2 H'2)) ]p\n          end\n        | sint =>\n          match [ e1 ]_ s, [ e2 ]_ s with\n            | mkPhy l1 H1, mkPhy l2 H2 => fun (Heq : sint = t') =>\n                let H'1 := eq_ind_r (fun t => size l1 = sizeof (ityp: t)) H1 Heq in\n                let H'2 := eq_ind_r (fun t => size l2 = sizeof (ityp: t)) H2 Heq in\n                [ binop_re_interp b (s2Z (i32<=i8 l1 H'1)) (s2Z (i32<=i8 l2 H'2)) ]p\n          end\n        | uchar =>\n          match [ e1 ]_ s, [ e2 ]_s with\n            | mkPhy l1 H1, mkPhy l2 H2 => fun (Heq : uchar = t') =>\n                let H'1 := eq_ind_r (fun t => size l1 = sizeof (ityp: t)) H1 Heq in\n                let H'2 := eq_ind_r (fun t => size l2 = sizeof (ityp: t)) H2 Heq in\n                [ binop_re_interp b (u2Z (i8_to_i8 l1 H'1)) (u2Z (i8_to_i8 l2 H'2)) ]p\n          end\n        | schar =>\n          match [ e1 ]_ s, [ e2 ]_s with\n            | mkPhy l1 H1, mkPhy l2 H2 => fun (Heq : schar = t') =>\n                let H'1 := eq_ind_r (fun t => size l1 = sizeof (ityp: t)) H1 Heq in\n                let H'2 := eq_ind_r (fun t => size l2 = sizeof (ityp: t)) H2 Heq in\n                [ binop_re_interp b (s2Z (i8_to_i8 l1 H'1)) (s2Z (i8_to_i8 l2 H'2)) ]p\n          end\n        | ulong =>\n          match [ e1 ]_ s, [ e2 ]_ s with\n            | mkPhy l1 H1, mkPhy l2 H2 => fun (Heq : ulong = t') =>\n                let H'1 := eq_ind_r (fun t => size l1 = sizeof (ityp: t)) H1 Heq in\n                let H'2 := eq_ind_r (fun t => size l2 = sizeof (ityp: t)) H2 Heq in\n                [ binop_re_interp b (u2Z (i64<=i8 l1 H'1)) (u2Z (i64<=i8 l2 H'2)) ]p\n          end\n      end erefl\n    | bop_n t' b e1 e2 =>\n      match t' as t return (forall (_ : t = t'), (g.-ityp: t).-phy) with\n        | uint =>\n          match [ e1 ]_ s, [ e2 ]_s with\n            | mkPhy l1 H1, mkPhy l2 H2 => fun (Heq : uint = t') =>\n                let H'1 := eq_ind_r (fun t => size l1 = sizeof (ityp: t)) H1 Heq in\n                let H'2 := eq_ind_r (fun t => size l2 = sizeof (ityp: t)) H2 Heq in\n                [ binop_ne_interp b (i32<=i8 l1 H'1) (i32<=i8 l2 H'2) ]p\n          end\n        | uchar =>\n          match [ e1 ]_ s, [ e2 ]_s with\n            | mkPhy l1 H1, mkPhy l2 H2 => fun (Heq : uchar = t') =>\n                let H'1 := eq_ind_r (fun t => size l1 = sizeof (ityp: t)) H1 Heq in\n                let H'2 := eq_ind_r (fun t => size l2 = sizeof (ityp: t)) H2 Heq in\n                [ binop_ne_interp b (i8_to_i8 l1 H'1) (i8_to_i8 l2 H'2) ]p\n          end\n        | schar =>\n          match [ e1 ]_ s, [ e2 ]_s with\n            | mkPhy l1 H1, mkPhy l2 H2 => fun (Heq : schar = t') =>\n                let H'1 := eq_ind_r (fun t => size l1 = sizeof (ityp: t)) H1 Heq in\n                let H'2 := eq_ind_r (fun t => size l2 = sizeof (ityp: t)) H2 Heq in\n                [ binop_ne_interp b (i8_to_i8 l1 H'1) (i8_to_i8 l2 H'2) ]p\n          end\n        | sint =>\n          match [ e1 ]_ s, [ e2 ]_ s with\n            | mkPhy l1 H1, mkPhy l2 H2 => fun (Heq : sint = t') =>\n                let H'1 := eq_ind_r (fun t => size l1 = sizeof (ityp: t)) H1 Heq in\n                let H'2 := eq_ind_r (fun t => size l2 = sizeof (ityp: t)) H2 Heq in\n                [ binop_ne_interp b (i32<=i8 l1 H'1) (i32<=i8 l2 H'2) ]p\n          end\n        | ulong =>\n          match [ e1 ]_ s, [ e2 ]_ s with\n            | mkPhy l1 H1, mkPhy l2 H2 => fun (Heq : ulong = t') =>\n                let H'1 := eq_ind_r (fun t => size l1 = sizeof (ityp: t)) H1 Heq in\n                let H'2 := eq_ind_r (fun t => size l2 = sizeof (ityp: t)) H2 Heq in\n                [ binop_ne_interp b (i64<=i8 l1 H'1) (i64<=i8 l2 H'2) ]p\n          end\n      end erefl\n    | bopk_n ity b e1 k =>\n      match ity as t return (forall (_ : t = ity), (ityp: t).-phy) with\n        | uint => match [ e1 ]_ s with\n                  | mkPhy l1 H1 => fun (Heq : uint = ity) =>\n                    let H'1 := eq_ind_r (fun t => size l1 = sizeof (ityp: t)) H1 Heq in\n                    [ binopk_e_interp b (i32<=i8 l1 H'1) k ]p\n                  end\n        | sint => match [ e1 ]_ s with\n                  | mkPhy l1 H1 => fun (Heq : sint = ity) =>\n                    let H'1 := eq_ind_r (fun t => size l1 = sizeof (ityp: t)) H1 Heq in\n                    [ binopk_e_interp b (i32<=i8 l1 H'1) k ]p\n                  end\n        | uchar => match [ e1 ]_ s with\n                   | mkPhy l1 H1 => fun (Heq : uchar = ity) =>\n                     let H'1 := eq_ind_r (fun t => size l1 = sizeof (ityp: t)) H1 Heq in\n                     [ binopk_e_interp b (i8_to_i8 l1 H'1) k ]p\n                   end\n        | schar => match [ e1 ]_ s with\n                   | mkPhy l1 H1 => fun (Heq : schar = ity) =>\n                     let H'1 := eq_ind_r (fun t => size l1 = sizeof (ityp: t)) H1 Heq in\n                     [ binopk_e_interp b (i8_to_i8 l1 H'1) k ]p\n                   end\n        | ulong => match [ e1 ]_ s with\n                   | mkPhy l1 H1 => fun (Heq : ulong = ity) =>\n                     let H'1 := eq_ind_r (fun t => size l1 = sizeof (ityp: t)) H1 Heq in\n                     [ binopk_e_interp b (i64<=i8 l1 H'1) k ]p\n                   end\n      end (Logic.eq_refl _)\n     | add_p t e1 e2 =>\n      match [ e1 ]_s, [ e2 ]_s with\n        | mkPhy l1 H1, mkPhy l2 H2 =>\n          let p := ptr<=i8 l1 H1 in\n          let k := i32<=i8 l2 H2 in\n          phy<=ptr t (add_prod p (sizeof t) (Z<=s k))\n      end\n    | safe_cast ty ty' e H => safe_cast_phy [ e ]_s ty' H\n\n    | unsafe_cast ty ty' e H => unsafe_cast_phy [ e ]_s ty' H\n\n    | fldp n tg ty e H ty' Hin =>\n      shift_pointer _ [ e ]_s _ (field_address 0 n ty' (get_fields g tg) (assoc_get_in Hin))\n    | eq_p ty e1 e2 =>\n      if [ e1 ]_s == [ e2 ]_s then [ Z2u 32 1 ]p else [ zero32 ]p\n    | ifte_e ty' e1 e2 e3 =>\n      if is_zero [ e1 ]_s then [ e3 ]_s else [ e2 ]_s\n  end\nwhere \"'[' e ']_' s\" := (eval s e).\nGlobal Opaque eval.\n\nLemma eval_store_upd_notin {g} sigma t :\n  forall (e : exp sigma t) (t' : g.-typ) y (H : env_get y sigma = Some t') pval,\n    y \\notin unzip1 (vars e) ->\n    forall s, [ e ]_ (store_upd H pval s) = [ e ]_ s.\nProof.\nTransparent eval.\nelim : t / => //.\n- move=> x t ts_t t' y ts_t' pval' /= Hy s.\n  rewrite store_get_upd_neq // => ?; subst y.\n  by rewrite in_cons eqxx /= in Hy.\n- move=> b t e1 IH1 e2 IH2 t' y y_t' pval Hyp s.\n  rewrite /unzip1 /= map_cat mem_cat negb_or in Hyp.\n  case/andP : Hyp => ? ?.\n  by rewrite /= IH1 // IH2.\n- move=> b it e IH k t' y y_t' pv Hyp s.\n  by rewrite /= IH.\n- move=> b t e1 IH1 e2 IH2 t' y y_t' pval Hyp s.\n  rewrite /unzip1 /= map_cat mem_cat negb_or in Hyp.\n  case/andP : Hyp => ? ?.\n  by rewrite /= IH1 // IH2.\n- (* add_pe *) move=> t e1 IH1 e2 IH2 t' y H pv Hyp s.\n  rewrite /unzip1 /= map_cat mem_cat negb_or in Hyp.\n  case/andP : Hyp => ? ?.\n  by rewrite /= IH1 // IH2.\n- move=> t t' e IH Hsz t'' y ts_t'' pval'' /= Hin s; by rewrite IH.\n- (* unsafe_cast_e *) move=> t t' e IH Hsz t'' y ts_t'' pval'' /= Hin s; by rewrite IH.\n- move=> str tg t tg_t IH r t' Hin' t'' y y_t'' pval'' /= Hy s; by rewrite IH.\n- move=> t e1 IH1 e2 IH2 t' y y_t' pval' /= Hyp s.\n  rewrite /unzip1 /= map_cat mem_cat negb_or in Hyp.\n  case/andP : Hyp => ? ?.\n  by rewrite /= IH1 // IH2.\n- move=> t e1 IH1 e2 IH2 e3 IH3 t' y y_t' pv Hyp s.\n  rewrite /unzip1 /= !map_cat mem_cat negb_or in Hyp.\n  case/andP : Hyp => H0.\n  rewrite [vars _]/= mem_cat negb_or.\n  case/andP => H1 H2.\n  by rewrite /= IH1 // IH2 // IH3.\nOpaque eval.\nQed.\n\nDefinition subst_exp {g} {sigma : g.-env} str {t' : g.-typ} (str_t' : env_get str sigma = |_ t' _|) (e' : exp sigma t')\n  {t : g.-typ} (e : exp sigma t) : exp sigma t :=\n  exp_rect g sigma\n  (fun (t0 : g.-typ) (_ : exp sigma t0) => exp sigma t0)\n  (fun str0 (t0 : g.-typ) (e0 : env_get str0 sigma = |_ t0 _|) =>\n   match string_dec str0 str with\n   | left Heq =>\n     let str_t0 :  env_get str sigma = |_ t0 _| := eq_rect str0 (fun x => env_get x sigma = |_ t0 _|) e0 _ Heq in\n     (eq_rect t' (exp sigma) e' t0)\n       ((f_equal\n           (fun ot => match ot with |_ t1 _| => t1 | None => t' end)\n           (Logic.trans_eq (Logic.eq_sym str_t') str_t0)) :\n          t' = t0)\n   | right _ => var_e sigma str0 t0 e0\n   end)\n  (cst_e sigma)\n  (fun t0 b (_ IHe1 _ IHe2 : exp sigma (g.-ityp: t0)) =>\n   match b with\n   | and_e => IHe1 \\& IHe2\n   | shl_e => IHe1 \\<< IHe2\n   | or_e => IHe1 \\| IHe2\n   | add_e => IHe1 \\+ IHe2\n   | sub_e => IHe1 \\- IHe2\n   | mul_e => IHe1 \\* IHe2\n   end)\n  (fun t0 b (_ IHe : exp sigma (g.-ityp: t0)) => bopk_n sigma t0 b IHe)\n  (fun t0 b (_ IHe1 _ : exp sigma (g.-ityp: t0)) => bop_r sigma t0 b IHe1)\n  (fun t0 (_ IHe1 : exp sigma (:* t0)) _ => fun x => IHe1 \\+ x)\n  (fun t0 (t'0 : integral) (_ IHe : exp sigma (g.-ityp: t0)) => safe_cast sigma t0 t'0 IHe)\n  (fun t0 t'0 (_ IHe : exp sigma (g.-ityp: t0)) => unsafe_cast sigma t0 t'0 IHe)\n  (fun f tg t1 (_ IHe : exp sigma (:* t1)) (H : styp tg = t1) (t'1 : g.-typ) =>\n     @fldp _ sigma f _ _ IHe H t'1)\n  (fun t0 (_ IHe1 _ : exp sigma (:* t0)) => eq_p sigma t0 IHe1)\n  (fun t0 (_ IHe1 : exp sigma (g.-ityp: uint)) (_ IHe2 _ : exp sigma t0) => ifte_e sigma t0 IHe1 IHe2)\n  t e.\n\nLemma subst_exp_store_upd  {g} {sigma : g.-env} x {t' : g.-typ}\n  {Hx : env_get x sigma = Some t'} (e' : exp sigma t') s {t : g.-typ} (e : exp sigma t) :\n  [ subst_exp x Hx e' e ]_ s = [ e ]_ (store_upd Hx ([ e' ]_ s) s).\nProof.\nTransparent eval.\nelim: t / e => //.\n- move=> str t str_t /=.\n   case: string_dec => [Heq|Hneq].\n  + subst str.\n    have ? : t' = t by rewrite Hx in str_t; case: str_t.\n    subst t'.\n    have ? : Hx = str_t by apply eq_irrelevance.\n    subst Hx.\n    by rewrite store_get_upd_eq -Coq.Logic.Eqdep.Eq_rect_eq.eq_rect_eq.\n  + rewrite store_get_upd_neq //; by apply nesym.\n- by case=> //; case=> //= => e1 -> e2 ->.\n- by move=> t b e /= ->.\n- by move=> t b e1 /= -> e2 ->.\n- by move=> t e1 /= -> e2 ->.\n- by move=> t t_ e1 /= -> i.\n- by move=> t t_ e1 /= -> i.\n- by move=> f tg t e /= -> _ t_.\n- by move=> t e1 /= -> e2 ->.\n- by move=> t e1 /= -> e2 -> e3 ->.\nOpaque eval.\nQed.\n\nLocal Open Scope machine_int_scope.\nLocal Open Scope zarith_ext_scope.\nLocal Open Scope Z_scope.\n\nSection eval_sect.\n\nVariable (g : wfctxt) (sigma : g.-env).\n\n(* NB: generalize? *)\nLemma eval_spec : forall (a : (:* (g.-ityp: uchar)).-phy),\n  [ [phy<=ptr _ (ptr<=phy a `+ `( 8 )_ ptr_len) ]c ]_ (store0 sigma) =\n  [ [ a ]c \\+ [ 8 ]sc ]_ (store0 sigma).\nProof.\ncase=> l Hl.\nrewrite /ptr_of_phy /=.\ncase: option_dec => [ [x Hx] |abs].\nTransparent eval.\n- rewrite /eval /= /phy_of_ptr; apply mkPhy_irrelevance.\n  by rewrite /add_prod i8_of_i32K Z2sK //= (optr_of_i8_bij3 _ _ _ Hx).\nOpaque eval.\n- have [x Hx] : {x | optr<=i8 l = Some x}.\n    apply int_flat_Some; by rewrite Hl sizeof_ptyp.\n  congruence.\nQed.\n\nVariable (s : store sigma).\n\nLemma eval_pv t (pv : @phy g t) : [ [ pv ]c ]_s = pv.\nProof. done. Qed.\n\nLemma size_sc (e : Z) : size [ [ e ]sc : exp sigma (ityp: sint)]_s = 4%nat.\nProof. by rewrite size_int_break. Qed.\n\nLemma s2Z_sc (e : Z) H : - 2 ^^ 31 <= e < 2 ^^ 31 ->\n  Z<=s (i32<=i8 [ [ e ]sc : exp sigma (ityp: sint) ]_s H) = e.\nProof. move=> K. by rewrite i8_of_i32K Z2sK. Qed.\n\nLemma si32_of_phy_sc n : si32<=phy [ [ n ]sc : exp sigma _ ]_ s = Z2s 32 n.\nProof. by rewrite /si32_of_phy /= /= i8_of_i32Ko. Qed.\n\nLemma u2Z_si32_of_phy_safe_cast (e : exp sigma (g.-ityp: uchar)) :\n  u2Z (si32<=phy [ (int) e ]_ s) = u2Z (i8<=phy [ e ]_s).\nProof.\nTransparent eval.\nrewrite /= /si32_of_phy /= /safe_cast_phy_uchar.\nmove He : ([ e ]_s) => [he Hhe].\nhave Hhe' : size he = 1%nat by rewrite Hhe sizeof_ityp.\ndestruct he as [|hehd []] => //.\nby rewrite /= i8_of_i32Ko /= /i8_of_phy /= (u2Z_zext (8 * (4 - 1))).\nOpaque eval.\nQed.\n\nLemma s2Z_si32_of_phy_safe_cast (e : exp sigma (g.-ityp: uchar)) :\n  s2Z (si32<=phy [ (int) e]_ s) = Z<=u (i8<=phy [ e ]_s).\nProof.\nTransparent eval.\nrewrite /= /si32_of_phy /= /safe_cast_phy_uchar.\nmove He : ([ e ]_s) => [he Hhe].\nhave Hhe' : size he = 1%nat by rewrite Hhe sizeof_ityp.\ndestruct he as [|hehd []] => //.\nrewrite /= i8_of_i32Ko /= /i8_of_phy /= s2Z_u2Z_pos'; last first.\n  rewrite (u2Z_zext (8 * (4 - 1))).\n  split; [exact/min_u2Z | exact: (ltZ_trans (max_u2Z _))].\nby rewrite (u2Z_zext (8 * (4 - 1)) hehd).\nOpaque eval.\nQed.\n\nLemma is_zero_or (e1 e2 : exp sigma (ityp: uint)):\n  is_zero [ e1 \\|| e2 ]_s -> is_zero [ e1 ]_s /\\ is_zero [ e2 ]_s.\nProof.\nTransparent eval.\nrewrite /is_zero /=.\nmove H1 : ([ e1 ]_s) => [h1 Hh1].\nmove H2 : ([ e2 ]_s) => [h2 Hh2].\nhave : size h1 = 4%nat by rewrite Hh1 sizeof_ityp.\ncase/oi32_of_i8_Some => x Hx.\nhave : size h2 = 4%nat by rewrite Hh2 sizeof_ityp.\ncase/oi32_of_i8_Some => y Hy.\ncase: ifP => [H _ | H].\n  case/andP : H => H H'.\n  rewrite (_ : Z0 = u2Z zero32) in H; last by rewrite Z2uK.\n  move/eqP/u2Z_inj in H.\n  rewrite (_ : Z0 = u2Z zero32) in H'; last by rewrite Z2uK.\n  move/eqP/u2Z_inj in H'.\n  rewrite -H' in H.\n  move/i32_of_i8_inj : H => ?; subst h2.\n  move/i32_of_i8_bij : H' => ?; subst h1.\n  split; apply/eqP; by apply mkPhy_irrelevance.\ncase/eqP.\nmove/int_break_inj => K.\nby apply Z2u_dis in K.\nOpaque eval.\nQed.\n\nLemma is_zero_or2 (e1 e2 : exp sigma (ityp: uint)) :\n  is_zero [ e1 ]_s -> is_zero [ e2 ]_s -> is_zero [ e1 \\|| e2 ]_s.\nProof.\nTransparent eval.\nrewrite /is_zero => /eqP H1 /eqP H2 /=.\nby rewrite H1 H2 /= i8_of_i32K Z2uK.\nOpaque eval.\nQed.\n\nLemma add_p_0 (t : g.-typ) (e : exp sigma (:* t)) : [ e \\+ [ 0 ]sc ]_ s = [ e ]_ s.\nProof.\nTransparent eval.\nrewrite /=.\nmove e_ov : ([ e ]_ s) => [ov Hov].\nhave : size ov = sizeof_ptr by rewrite Hov sizeof_ptyp.\ncase/optr_of_i8_Some => v ov_v.\nrewrite (optr_of_i8_bij3 _ _ _ ov_v) i8_of_i32K /phy_of_ptr.\napply mkPhy_irrelevance => /=.\nrewrite /add_prod Z2sK //= mulZ0 addi0.\nby apply optr_of_i8_bij.\nOpaque eval.\nQed.\n\nLemma u2Z_ptyp2ptr_nat (t : g.-typ) (e : exp sigma (:* t)) n :\n  - 2 ^^ 31 <= Z_of_nat n < 2 ^^ 31 ->\n  u2Z (ptr<=phy [e ]_ s) + Z<=nat (n * sizeof t) < 2 ^^ ptr_len ->\n  u2Z (ptr<=phy [e \\+ [ Z_of_nat n ]sc ]_ s) = u2Z (ptr<=phy [e ]_ s) + Z<=nat (n * sizeof t).\nProof.\nTransparent eval.\nmove: n; elim => [ | n IH Hn H].\n  by rewrite mul0n [Z_of_nat _]/= add_p_0 addZ0.\nrewrite /ptr_of_phy 2!optr_of_i8_of_phy Z_S [u2Z _]/= i8_of_i32K.\nmove Hes : ( [ e ]_ s) => [es es'].\nhave : size es = sizeof_ptr by rewrite es' sizeof_ptyp.\ncase/optr_of_i8_Some => x es''.\nrewrite (optr_of_i8_bij3 _ _ _ es'') phy_of_ptrK /ptr_of_phy /= es'' /=.\nhave ty_fit : 0 <= Z_of_nat (n.+1 * sizeof t) < 2 ^^ ptr_len.\n  split; first by apply Zle_0_nat.\n  move: (min_u2Z (ptr<=phy [e ]_ s)) => ?; lia.\nrewrite /add_prod Z2sK; last by rewrite Z_S in Hn.\nrewrite (_ : 0 <=? (Z_of_nat n + 1) = true); last by rewrite -Z_S.\nrewrite u2Z_add.\n+ rewrite Z2uK.\n    rewrite mulSn inj_plus inj_mult; ring.\n  rewrite mulSn inj_plus inj_mult in ty_fit.\n  rewrite Zmult_plus_distr_r Zmult_1_r mulZC; lia.\n+ rewrite Z2uK //.\n    rewrite Hes [u2Z _]/= /ptr_of_phy [u2Z _]/= es'' [u2Z _]/= in H.\n    rewrite inj_mult Z_S in H.\n    rewrite mulZC; lia.\n  rewrite inj_mult Z_S in ty_fit.\n  rewrite mulZC; lia.\nOpaque eval.\nQed.\n\nLemma u2Z_ptyp2ptr_1 (t : g.-typ) (e : exp sigma (:* t)) :\n  u2Z (ptr<=phy [e ]_ s) + Z<=nat (sizeof t) < 2 ^^ ptr_len ->\n  u2Z (ptr<=phy [e \\+ [ 1 ]sc ]_ s) = u2Z (ptr<=phy [e ]_ s) + Z<=nat (sizeof t).\nProof.\nmove=> H.\nrewrite (_ : 1%Z = Z_of_nat 1%nat) // -(mult_1_l (sizeof t)).\napply u2Z_ptyp2ptr_nat => //.\nby rewrite mul1n.\nQed.\n\nLemma eval_add_pA t (a : exp sigma (:* t)) b c :\n  0 <= Z<=nat (sizeof t) * s2Z (si32<=phy [ b ]_s) < 2 ^^ 31 ->\n  0 <= Z<=nat (sizeof t) * s2Z (si32<=phy [ c ]_s) < 2 ^^ 31 ->\n  0 <= Z<=nat (sizeof t) * s2Z (si32<=phy [ b ]_s) +\n        Z<=nat (sizeof t) * s2Z (si32<=phy [ c ]_s) < 2 ^^ 31 ->\n  [ a \\+ b \\+ c ]_s = [ a \\+ (b \\+ c) ]_s.\nProof.\nTransparent eval.\nmove=> b_fit c_fit bc_fit.\nmove Heval_c : ( [ c ]_s ) => [c' Hc].\nmove Heval_a : ( [ a ]_s ) => [a' Ha].\nmove Heval_b : ( [ b ]_s ) => [b' Hb].\nrewrite /= Heval_a Heval_c Heval_b /=.\ncase/optr_of_i8_Some : (Ha) => ptr_a' Hptr_a'.\ncase/oi32_of_i8_Some : (Hb) => int_b' Hint_b'.\ncase/oi32_of_i8_Some : (Hc) => int_c' Hint_c'.\nrewrite /= (optr_of_i8_bij3 _ _ _ Hptr_a') i8_of_i32K.\ncongr (phy<=ptr _ _).\nset b'' := i32_of_i8 _ _.\nset c'' := i32_of_i8 _ _.\nhave ? : b'' = int_b'.\n  rewrite /i32_of_i8.\n  apply int_flat_int_flat_ok.\n  by rewrite -Hint_b'.\nsubst int_b'.\nhave ? : c'' = int_c'.\n  rewrite /i32_of_i8.\n  apply int_flat_int_flat_ok.\n  by rewrite -Hint_c'.\nsubst int_c'.\nrewrite i8_of_ptrK add_prodA //.\n- by apply sizeof_gt0.\n- move: b_fit; rewrite Heval_b; by rewrite /si32_of_phy /phy2seq Hint_b'.\n- move: c_fit; rewrite Heval_c; by rewrite /si32_of_phy /phy2seq Hint_c'.\n- move: bc_fit; rewrite Heval_c Heval_b.\n  by rewrite /si32_of_phy /phy2seq Hint_c' Hint_b'.\nOpaque eval.\nQed.\n\n(* works for \\+, \\-, \\|, \\& *)\nLemma si32_of_phy_binop_ne (e1 : exp sigma _) e2 (b : binop_ne) :\n  si32<=phy [bop_n sigma sint b e1 e2 ]_ s =\n  (binop_ne_interp b) (si32<=phy ([ e1 ]_ s)) (si32<=phy ([ e2 ]_ s)).\nProof.\nTransparent eval.\nrewrite /=.\ncase: ([e1]_s) => p Hp.\ncase: ([e2]_s) => p2 Hp2.\nrewrite phy_of_si32K /si32_of_phy /=.\ncase: (oi32_of_i8_Some _ Hp) => x Hx.\ncase: (oi32_of_i8_Some _ Hp2) => y Hy.\nrewrite Hx Hy /=.\nmove: (oi32_of_i8_bij _ _ Hx) => ?; subst.\nmove: (oi32_of_i8_bij _ _ Hy) => ?; subst.\nby rewrite !i8_of_i32K.\nOpaque eval.\nQed.\n\nLemma phy_add_pe (t : g.-typ) (e1 : exp sigma (:* t)) (e2 : exp sigma (g.-ityp: sint)) :\n  0 <=? s2Z (si32<=phy [ e2 ]_ s) ->\n  ptr<=phy [ e1 \\+ e2 ]_ s =\n  ptr<=phy [ e1 ]_s `+ Z2u ptr_len (Z<=nat (sizeof t) * s2Z (si32<=phy [ e2 ]_ s)).\nProof.\nTransparent eval.\nmove=> e2_pos /=.\nmove H1 : ([ e1 ]_ s) => [h1 Hh1].\nmove H2 : ([ e2 ]_ s) => [h2 Hh2].\nhave : size h1 = sizeof_ptr by rewrite Hh1 sizeof_ptyp.\ncase/optr_of_i8_Some => x1 Hx1.\nhave : size h2 = 4%nat by rewrite Hh2 sizeof_ityp.\ncase/oi32_of_i8_Some => x2 Hx2.\nrewrite H2 /si32_of_phy /= Hx2 /= in e2_pos.\nrewrite /add_prod (i32_of_i8_bij3 h2 x2) // e2_pos phy_of_ptrK.\nby rewrite /ptr_of_phy /= Hx1 /= (optr_of_i8_bij3 _ x1) // /si32_of_phy /= Hx2.\nOpaque eval.\nQed.\n\nEnd eval_sect.\n\nNotation \"e '|le~>' val\" :=\n  (fun st hp => @log_mapsto _ _ val (Z.abs_nat (Z<=u (ptr<=phy ([ e ]_st)))) hp)\n  (at level 77, no associativity) : C_expr_scope.\n\nNotation \"e '|pe~>' val\" :=\n  (fun st hp => @phy_mapsto _ _ val (Z.abs_nat (Z<=u (ptr<=phy ([ e ]_st)))) hp)\n  (at level 77, no associativity) : C_expr_scope.\n\n(** boolean expression *)\n\nInductive bexp {g} (sigma : g.-env) :=\n| exp2bexp of exp sigma (g.-ityp: uint)\n| bneg of bexp sigma.\n\nReserved Notation \"'[' e ']b_' s\" (at level 9).\n\nFixpoint beval {g} {sigma : g.-env} (e : bexp sigma) (s : store sigma) : bool :=\n  match e with\n    | exp2bexp e' => ~~ is_zero [ e' ]_ s\n    | bneg e' => negb [ e' ]b_ s\n  end\nwhere \"'[' e ']b_' s\" := (beval e s) : C_expr_scope.\nGlobal Opaque beval.\n\nNotation \"'\\~b' b\" := (bneg _ b) (at level 71, format \"'['  \\~b  b  ']'\") : C_expr_scope. (* NB: logical negation, exists in C? *)\n\nNotation \"'\\b' e\" := (exp2bexp _ e) (at level 70, format \"'['  \\b  e  ']'\") : C_expr_scope.\n\nFixpoint subst_bexp {g} {sigma : g.-env} x {t : g.-typ}\n  (Hx : env_get x sigma = Some t) (e' : exp sigma t) (b : bexp sigma) : bexp sigma :=\n  match b with\n    | exp2bexp e => \\b subst_exp x Hx e' e\n    | bneg b => bneg _ (subst_bexp x Hx e' b)\n  end.\n\nLemma subst_bexp_store_upd {g} {sigma : g.-env} (x : string) {t : g.-typ} {Hx : env_get x sigma = Some t} (e' : exp sigma t) s: forall (b : bexp sigma),\n  [ subst_bexp x Hx e' b ]b_ s = [ b ]b_ (store_upd Hx ([ e' ]_ s) s).\nProof.\nTransparent beval.\nelim => /= [e | b Hind].\n- by rewrite subst_exp_store_upd.\n- by rewrite Hind.\nOpaque beval.\nQed.\n\nFixpoint bvars {g} {sigma : g.-env} (b : bexp sigma) :=\n  match b with\n    | exp2bexp e => vars e\n    | bneg b => bvars b\n  end.\n\nLemma bvars_subset_sigma {g} {sigma : g.-env} :\n  forall (b : bexp sigma), {subset bvars b <= sigma}.\nProof. elim => //=. exact vars_in_ts. Qed.\n\nLemma beval_store_upd_notin {g} sigma :\n  forall (b : bexp sigma) (t : g.-typ) str (str_t : env_get str sigma = Some t) pv,\n    str \\notin unzip1 (bvars b) ->\n    forall s, [ b ]b_ (store_upd str_t pv s) = [ b ]b_ s.\nProof.\nTransparent beval.\nelim => /= [e t str str_t pval Hnotin s | b Hind ty' str str_t pval Hnotin s].\n- by rewrite eval_store_upd_notin.\n- by rewrite Hind.\nOpaque beval.\nQed.\n\nSection beval_sect.\n\nVariable (g : wfctxt) (sigma : g.-env) (s : store sigma).\n\nLemma one_uc : [ \\b ([ 1 ]uc : exp sigma _) ]b_ s.\nProof.\nTransparent beval eval.\nby rewrite /= not_is_zero_1.\nOpaque beval eval.\nQed.\n\nLemma beval_neg_not (b : bexp sigma) : [ \\~b b ]b_ s = ~~ [ b ]b_ s.\nProof. by case b. Qed.\n\nLemma beval_eq_e_eq t (a b : exp sigma (ityp: t)) :\n  [ \\b a \\= b ]b_ s = ([ a ]_ s == [ b ]_ s).\nProof.\nTransparent eval beval.\ncase: t a b => //= a b; case: ([ a ]_ s) => ha Ha; case: ([ b ]_ s) => hb Hb.\n- case: ifP => [ | / negbT H ].\n    move/eqP/u2Z_inj/i32_of_i8_inj => ?; subst hb.\n    rewrite not_is_zero_1.\n    by apply/esym/eqP/mkPhy_irrelevance.\n  rewrite is_zero_0; apply/esym/negbTE.\n  move: H; apply contra.\n  case/eqP => ?; subst ha.\n  by rewrite (_ : Ha = Hb) //; apply/eq_irrelevance.\n- case: ifP => [ | / negbT H ].\n    move/eqP/s2Z_inj/i32_of_i8_inj => ?; subst hb.\n    rewrite not_is_zero_1.\n    by apply/esym/eqP/mkPhy_irrelevance.\n  rewrite is_zero_0; apply/esym/negbTE.\n  move: H; apply contra.\n  case/eqP => ?; subst ha.\n  by rewrite (_ : Ha = Hb) //; apply/eq_irrelevance.\n- case: ifP => [ | / negbT H ].\n    move/eqP/u2Z_inj/i8_to_i8_inj => ?; subst hb.\n    rewrite not_is_zero_1.\n    by apply/esym/eqP/mkPhy_irrelevance.\n  rewrite is_zero_0; apply/esym/negbTE.\n  move: H; apply contra.\n  case/eqP => ?; subst ha.\n  by rewrite (_ : Ha = Hb) //; apply/eq_irrelevance.\n- case: ifP => [ | / negbT H ].\n    move/eqP/s2Z_inj/i8_to_i8_inj => ?; subst hb.\n    rewrite not_is_zero_1.\n    by apply/esym/eqP/mkPhy_irrelevance.\n  rewrite is_zero_0; apply/esym/negbTE.\n  move: H; apply contra.\n  case/eqP => ?; subst ha.\n  by rewrite (_ : Ha = Hb) //; apply/eq_irrelevance.\n- case: ifP => [ | / negbT H ].\n    move/eqP/u2Z_inj/i64_of_i8_inj => ?; subst hb.\n    rewrite not_is_zero_1.\n    by apply/esym/eqP/mkPhy_irrelevance.\n  rewrite is_zero_0; apply/esym/negbTE.\n  move: H; apply contra.\n  case/eqP => ?; subst ha.\n  by rewrite (_ : Ha = Hb) //; apply/eq_irrelevance.\nOpaque eval beval.\nQed.\n\nLemma beval_neq_not_bneg (t : integral) (a b : exp sigma (ityp: t)) :\n [ \\b a \\!= b  ]b_ s = [ \\~b \\b a \\= b ]b_ s.\nProof.\nTransparent eval beval.\nrewrite /= negbK.\nmove Ha : ( [ a ]_s ) => [ha Hha].\nmove Hb : ( [ b ]_s ) => [hb Hhb].\ncase: t a b Hha Ha Hhb Hb => a b Hha _ Hhb _; case: ifP => //= ?.\n- rewrite is_zero_0.\n  apply/esym/negbTE => /=.\n  by rewrite not_is_zero_1.\n  by rewrite is_zero_0 not_is_zero_1.\n- rewrite is_zero_0.\n  apply/esym/negbTE => /=.\n  by rewrite not_is_zero_1.\n  by rewrite is_zero_0 not_is_zero_1.\n- rewrite is_zero_0.\n  apply/esym/negbTE => /=.\n  by rewrite not_is_zero_1.\n  by rewrite is_zero_0 not_is_zero_1.\n- rewrite is_zero_0.\n  apply/esym/negbTE => /=.\n  by rewrite not_is_zero_1.\n  by rewrite is_zero_0 not_is_zero_1.\n- rewrite is_zero_0.\n  apply/esym/negbTE => /=.\n  by rewrite not_is_zero_1.\n  by rewrite is_zero_0 not_is_zero_1.\nOpaque eval beval.\nQed.\n\nLemma beval_neq_not_eq (t : integral) (a b : exp sigma (ityp: t)) :\n  [ \\b a \\!= b  ]b_ s = ([ a ]_ s != [ b ]_ s).\nProof. by rewrite beval_neq_not_bneg beval_neg_not beval_eq_e_eq. Qed.\n\nLemma beval_eq_p_eq (t : g.-typ) (a b : exp sigma (:* t)) :\n  [ \\b a \\= b ]b_ s = ([ a ]_ s == [ b ]_ s).\nProof.\nTransparent eval beval.\nrewrite /=.\ncase: ifP => H; by [rewrite not_is_zero_1 | rewrite is_zero_0].\nOpaque eval beval.\nQed.\n\nLemma beval_bop_r_le_ge (e1 e2 : exp sigma (g.-ityp: sint)) :\n  [ \\b e1 \\<= e2 ]b_ s -> [ \\b e2 \\>= e1 ]b_ s.\nProof.\nTransparent eval beval.\nrewrite /=.\nmove He1 : ( [ e1 ]_s ) => [? ?].\nmove He2 : ( [ e2 ]_s ) => [? ?].\nby case: ifP.\nOpaque eval beval.\nQed.\n\nLemma beval_bop_r_ge_le (e1 e2 : exp sigma (g.-ityp: sint)) :\n  [ \\b e1 \\>= e2 ]b_ s -> [ \\b e2 \\<= e1 ]b_ s.\nProof.\nTransparent eval beval.\nrewrite /=.\nmove He1 : ( [ e1 ]_s ) => [? ?].\nmove He2 : ( [ e2 ]_s ) => [? ?].\nby case: ifP.\nOpaque eval beval.\nQed.\n\n(* NB: see also Ceqpn_add2l in C_expr_equiv *)\nLemma Ceqpn_add2l' t (e : exp sigma (:* t)) e1 e2 :\n  [ \\b e1 \\= e2 ]b_ s -> [ \\b e \\+ e1 \\= e \\+ e2 ]b_ s.\nProof.\nTransparent beval eval.\nrewrite /=.\nmove e1_v1 : ([ e1 ]_s) => [v1 Hv1].\nmove e2_v2 : ([ e2 ]_s) => [v2 Hv2].\nmove e_v : ([ e ]_s) => [v Hv].\ncase: ifP; last by rewrite is_zero_0.\nmove/eqP/s2Z_inj => -> _.\ncase: ifP; first by rewrite not_is_zero_1.\nby rewrite eqxx.\nOpaque beval eval.\nQed.\n\nLemma beval_land_e (e1 e2 : exp sigma (ityp: uint)) :\n  [ \\b e1 \\&& e2 ]b_ s = [ \\b e1 ]b_ s && [ \\b e2 ]b_ s.\nProof.\nTransparent beval eval.\nmove He1_s : ( [ e1 ]_ s ) => e1_pv.\ndestruct e1_pv as [e1_lst He1_lst].\nhave : size e1_lst = 4%nat by rewrite He1_lst sizeof_ityp.\ncase/oi32_of_i8_Some => e1_int He1_int.\nmove He2_s : ( [ e2 ]_ s ) => e2_pv.\ndestruct e2_pv as [e2_lst He2_lst].\nhave : size e2_lst = 4%nat by rewrite He2_lst sizeof_ityp.\ncase/oi32_of_i8_Some => e2_int He2_int.\n- rewrite /= He1_s He2_s /is_zero.\n  case: ifP.\n  + case/orP.\n    * move/eqP.\n      rewrite {1}(_ : Z0 = u2Z (Z2u 32 0)); last by rewrite Z2uK.\n      move/u2Z_inj/i32_of_i8_bij => ?; subst e1_lst.\n      rewrite eq_refl /=.\n      apply/esym/negbTE.\n      rewrite negb_and /= 2!negbK.\n      apply/orP; left.\n      by apply/eqP/mkPhy_irrelevance.\n    * move/eqP.\n      rewrite {1}(_ : Z0 = u2Z (Z2u 32 0)); last by rewrite Z2uK.\n      move/u2Z_inj/i32_of_i8_bij => ?; subst e2_lst.\n      rewrite eq_refl /=.\n      apply/esym/negbTE.\n      rewrite negb_and /= 2!negbK.\n      apply/orP; right.\n      by apply/eqP/mkPhy_irrelevance.\n  + move/negbT; rewrite negb_or.\n    move/andP.\n    rewrite {1}(_ : Z0 = u2Z (Z2u 32 0)); last by rewrite Z2uK.\n    rewrite {2}(_ : Z0 = u2Z (Z2u 32 0)); last by rewrite Z2uK.\n    case=> /eqP He1 /eqP He2.\n    rewrite not_is_zero_1.\n    apply/esym/andP; split.\n    * apply/negP. case/eqP => ?; subst e1_lst.\n      by rewrite i8_of_i32K in He1.\n    * apply/negP. case/eqP => ?; subst e2_lst.\n      by rewrite i8_of_i32K in He2.\nOpaque beval eval.\nQed.\n\nLemma beval_le0_or_e (e1 e2 : exp sigma (ityp: sint)) :\n  [ \\b [ 0 ]sc \\<= e1 ]b_ s && [ \\b [ 0 ]sc \\<= e2 ]b_ s -> [ \\b [ 0 ]sc \\<= (e1 \\| e2) ]b_ s.\nProof.\nTransparent eval beval.\nrewrite /=.\nmove H1 : ([ e1 ]_s) => [h1 Hh1].\nmove H2 : ([ e2 ]_s) => [h2 Hh2].\nrewrite i8_of_i32K.\nhave Hh1' : size h1 = 4%nat by rewrite Hh1 sizeof_ityp.\nhave Hh2' : size h2 = 4%nat by rewrite Hh2 sizeof_ityp.\nhave -> : eq_ind_r (fun t => size h1 = sizeof (ityp: t)) Hh1 erefl = Hh1'.\n  by apply eq_irrelevance.\nhave -> : eq_ind_r (fun t => size h2 = sizeof (ityp: t)) Hh2 erefl = Hh2'.\n  by apply eq_irrelevance.\nrewrite Z2sK //.\ncase/andP.\ncase: ifP => [Ha _ | ]; last by rewrite is_zero_0.\ncase: ifP => [Hb _ | ]; last by rewrite is_zero_0.\nrewrite {1}/phy_of_int_nosimpl /= 2!i8_of_i32K Z2sK //.\ncase: ifP; first by rewrite not_is_zero_1.\nmove/negbT.\nby rewrite (le0_or Ha Hb).\nOpaque eval beval.\nQed.\n\nLemma beval_uchar0 (e : exp sigma (ityp: uchar)) : [ \\b [ 0 ]sc \\<= (int) e ]b_ s.\nProof.\nTransparent eval beval.\nrewrite /= /safe_cast_phy_uchar.\nmove H : ( [ e ]_s ) => [h Hh].\nhave Hh' : size h = 1%nat by rewrite Hh sizeof_ityp.\ndestruct h as [ | h [|] ] => //.\nby rewrite i8_of_i32K Z2sK // i8_of_i32K (s2Z_zext (8 * (4 - 1))) // min_u2Zb not_is_zero_1.\nOpaque eval beval.\nQed.\n\nLemma beval_shl_uchar0 (e : exp sigma (ityp: uchar)) :\n  [ \\b [ 0 ]sc \\<= (int) e \\<< [ 8 ]sc ]b_ s.\nProof.\nTransparent eval beval.\nrewrite /= /safe_cast_phy_uchar.\nmove H : ( [ e ]_s ) => [h Hh].\nhave Hh' : size h = 1%nat by rewrite Hh sizeof_ityp.\ndestruct h as [ | h [|] ] => //.\nrewrite 2!i8_of_i32K -s2Z_u2Z_pos; last by rewrite Z2sK.\nrewrite Z2sK //= 2!i8_of_i32K Z2sK //= (@s2Z_shl 8) //; last first.\n  rewrite (s2Z_zext (8 * (4 - 1))) //.\n  split; last exact: max_u2Z.\n  apply (@leZ_trans Z0) => //; exact: min_u2Z.\nrewrite (s2Z_zext (8 * (4 - 1))) //.\ncase: ifP; first by rewrite not_is_zero_1.\nmove/negbT.\nrewrite -Z.ltb_antisym.\nmove/ltZP.\ncase/Zlt_mult_0_inv.\n  case => abs _.\n  move: (min_u2Z h) => ?; lia.\nby case.\nOpaque eval beval.\nQed.\n\n(* NB: useful? *)\nLemma beval_neq_e_sint (e1 e2 : exp sigma _) :\n  [ \\b e1 \\!= e2 ]b_ s = (si32<=phy ([e1]_ s) != si32<=phy ([e2]_ s)).\nProof.\nTransparent eval beval.\nmove H1 : ([ e1 ]_s) => [h1 Hh1].\nmove H2 : ([ e2 ]_s) => [h2 Hh2].\nhave Hh1' : size h1 = 4%nat by rewrite Hh1 sizeof_ityp.\nhave Hh2' : size h2 = 4%nat by rewrite Hh2 sizeof_ityp.\ncase/oi32_of_i8_Some : Hh1' => x Hx.\ncase/oi32_of_i8_Some : Hh2' => y Hy.\nrewrite /= H1 H2.\ncase: ifP => H.\n  rewrite /si32_of_phy /= Hx /= Hy /= is_zero_0 /=.\n  apply/esym/eqP.\n  move/eqP/s2Z_inj/i32_of_i8_inj : H => ?; subst.\n  by rewrite Hy in Hx; case: Hx.\nrewrite not_is_zero_1.\napply/esym.\nmove/negbT : H; apply contra => /eqP H.\nrewrite /si32_of_phy /= Hx Hy /= in H; subst y.\nmove: (oi32_of_i8_inj _ _ _ Hx Hy) => ?; subst h2.\napply/eqP.\ncongr (Z<=s (i32<=i8 _ _)).\napply eq_irrelevance.\nOpaque eval beval.\nQed.\n\nLemma bop_re_ge_Zge (e1 e2 : exp sigma (g.-ityp: _)) :\n  [ \\b e1 \\>= e2 ]b_ s -> s2Z (si32<=phy [ e1 ]_s) >= s2Z (si32<=phy [ e2 ]_s).\nProof.\nTransparent eval beval.\nrewrite /=.\nmove He1 : ( [ e1 ]_s ) => [he1 Hhe1].\nmove He2 : ( [ e2 ]_s ) => [he2 Hhe2].\ncase: ifP; last by move=> _; rewrite /is_zero eqxx.\nmove/leZP => H _.\napply Z.le_ge.\nset lhs := si32<=phy _.\nset rhs := si32<=phy _.\nset lhs2 := i32_of_i8 _ _ in H.\nset rhs2 := i32_of_i8 _ _ in H.\nhave -> : lhs = lhs2.\n  rewrite /lhs /lhs2 /si32_of_phy /=.\n  have : size he2 = 4%nat by rewrite Hhe2 sizeof_ityp.\n  case/oi32_of_i8_Some => x Hx; rewrite Hx /=.\n  by apply/esym/i32_of_i8_bij2/oi32_of_i8_bij.\nrewrite (_ : rhs = rhs2) // /rhs /rhs2 /si32_of_phy /=.\nhave : size he1 = 4%nat by rewrite Hhe1 sizeof_ityp.\ncase/oi32_of_i8_Some => x Hx; rewrite Hx /=.\nby apply/esym/i32_of_i8_bij2/oi32_of_i8_bij.\nOpaque eval beval.\nQed.\n\nLemma bop_re_le_Zle (e1 e2 : exp sigma (g.-ityp: _)) :\n  [ \\b e1 \\<= e2 ]b_ s -> s2Z (si32<=phy [ e1 ]_s) <= s2Z (si32<=phy [ e2 ]_s).\nProof. move=> H. exact/Z.ge_le/bop_re_ge_Zge/beval_bop_r_le_ge. Qed.\n\nLemma bop_re_lt_Zlt (e1 e2 : exp sigma (g.-ityp: sint)) :\n  [ \\b e1 \\< e2 ]b_ s -> s2Z (si32<=phy [ e1 ]_s) < s2Z (si32<=phy [ e2 ]_s).\nProof.\nTransparent eval beval.\nrewrite /=.\nmove He1 : ( [ e1 ]_s ) => [he1 Hhe1].\nmove He2 : ( [ e2 ]_s ) => [he2 Hhe2].\ncase: ifP; last by move=> _; rewrite /is_zero eqxx.\nmove/ltZP => H _.\nset lhs := si32<=phy _.\nset rhs := si32<=phy _.\nset lhs1 := i32_of_i8 _ _ in H.\nset rhs1 := i32_of_i8 _ _ in H.\nhave -> : lhs = lhs1.\n  rewrite /lhs /lhs1 /si32_of_phy /=.\n  have : size he1 = 4%nat by rewrite Hhe1 sizeof_ityp.\n  case/oi32_of_i8_Some => x Hx; rewrite Hx /=.\n  by apply/esym/i32_of_i8_bij2/oi32_of_i8_bij.\nrewrite (_ : rhs = rhs1) // /rhs /rhs1 /si32_of_phy /=.\nhave : size he2 = 4%nat by rewrite Hhe2 sizeof_ityp.\ncase/oi32_of_i8_Some => x Hx; rewrite Hx /=.\nby apply/esym/i32_of_i8_bij2/oi32_of_i8_bij.\nOpaque eval beval.\nQed.\n\nEnd beval_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/seplogC/C_expr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.27265148373201975}}
{"text": "From Coq Require Import Lia.\n\nFrom Elo Require Export Array.\nFrom Elo Require Export Map.\nFrom Elo Require Export Core0.\n\nLtac splits n :=\n  match n with\n  | O => fail\n  | S O => idtac\n  | S ?n' => split; [| splits n']\n  end.\n\n(* ------------------------------------------------------------------------- *)\n(* Definitions ------------------------------------------------------------- *)\n(* ------------------------------------------------------------------------- *)\n\nDefinition well_typed_memory mt m :=\n  length mt = length m /\\\n  (forall ad, mt / empty |-- (getTM m ad) is (getTY mt ad)).\n\nDefinition well_typed_threads mt ths :=\n  forall tid, exists T, mt / empty |-- (getTM ths tid) is T.\n\nDefinition finished ths :=\n  forall tid, value (getTM ths tid).\n\n(* ------------------------------------------------------------------------- *)\n(* Extends ----------------------------------------------------------------- *)\n(* ------------------------------------------------------------------------- *)\n\nModule Extends.\n  Inductive extends' {A} : list A -> list A -> Prop :=\n    | extends_nil : forall mt,\n      extends' mt nil\n    | extends_cons : forall x mt mt',\n      extends' mt mt' ->\n      extends' (x :: mt) (x :: mt').\n\n    Infix \"extends\" := extends' (at level 50).\n\n    Lemma refl : forall {A} (mt : list A),\n      mt extends mt.\n    Proof.\n      intros. induction mt; eauto using @extends'.\n    Qed.\n\n    Lemma add : forall {A} (mt : list A) a,\n      (add mt a) extends mt.\n    Proof.\n      intros. induction mt; eauto using @extends'.\n    Qed.\n\n    Lemma get : forall (mt mt' : list typ) i,\n      i < length mt' ->\n      mt extends mt' ->\n      getTY mt' i = getTY mt i.\n    Proof.\n      intros *. generalize dependent mt. generalize dependent i.\n      induction mt'; intros * Hlen Hext; try solve [inversion Hlen].\n      inversion Hext; subst. destruct i; trivial.\n      unfold getTY, get. simpl in *. eauto using Lt.lt_S_n.\n    Qed.\n\n    Lemma length : forall {A} (mt mt' : list A) i,\n      i < length mt' ->\n      mt extends mt' ->\n      i < length mt.\n    Proof.\n      intros *. generalize dependent mt. generalize dependent i.\n      induction mt'; intros * Hlen Hext; try solve [inversion Hlen].\n      inversion Hext; subst. destruct i;\n      eauto using PeanoNat.Nat.lt_0_succ, Lt.lt_n_S, Lt.lt_S_n.\n    Qed.\nEnd Extends.\n\nInfix \"extends\" := Extends.extends' (at level 50).\n\n(* ------------------------------------------------------------------------- *)\n(* Weakening --------------------------------------------------------------- *)\n(* ------------------------------------------------------------------------- *)\n\nLemma memory_weakening : forall mt mt' Gamma t T,\n  mt extends mt' ->\n  mt' / Gamma |-- t is T ->\n  mt  / Gamma |-- t is T.\nProof.\n  intros * Hext Htype.\n  induction Htype; eauto using well_typed_term.\n  erewrite Extends.get; eauto using well_typed_term, Extends.length.\nQed.\n\nLemma threads_memory_weakening : forall mt mt' ths,\n  mt' extends mt ->\n  well_typed_threads mt ths ->\n  well_typed_threads mt' ths.\nProof.\n  intros * Hext Hths. intros tid.\n  specialize (Hths tid) as [? ?]. eexists.\n  eauto using memory_weakening.\nQed.\n\nLemma context_weakening : forall mt Gamma Gamma' t T,\n  Gamma includes Gamma' ->\n  mt / Gamma' |-- t is T ->\n  mt / Gamma  |-- t is T.\nProof.\n  intros * Hinc Htype.\n  generalize dependent Gamma.\n  induction Htype; intros * Hinc;\n  eauto 6 using @well_typed_term, safe_preserves_inclusion,\n    update_preserves_inclusion.\nQed.\n\nLemma context_weakening_empty : forall mt Gamma t T,\n  mt / empty |-- t is T ->\n  mt / Gamma |-- t is T.\nProof.\n  intros * Htype.\n  eapply (context_weakening _ _ empty); auto.\n  discriminate.\nQed.\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/old/Preservation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2726218004793949}}
{"text": "(* ***************************************************************** *)\n(* Int.v                                                             *)\n(*                                                                   *)\n(* 2019 Xuan Huang                                                   *)\n(* ***************************************************************** *)\n\n\n(* ################################################################# *)\n(** * Int  *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Value representation (placeholder) *)\n\n(** TODO: use actual implementation such as Coq standard library's\n    or Int32, Int64, Float32, Float64 from OCaml.\n *)\n\nModule Type Rep.\n  Parameter bitwidth: nat.\nEnd Rep.\n\nModule Rep32.\n  Definition bitwidth := 32.\nEnd Rep32.\n\nModule Rep64.\n  Definition bitwidth := 64.\nEnd Rep64.\n\n\n(* ----------------------------------------------------------------- *)\n(** *** Functor *)\n\nModule Type S.\n  Parameter t : Type.\n  Parameter bitwidth: nat.\n\n  Parameter zero : t.\n  Parameter one : t.\n  Parameter min : t.\n  Parameter max : t.\n  Parameter max16 : t.\n\n  Parameter from_nat : nat -> t.\n  Parameter to_nat : t -> nat.\n\n  (* iunop *)\n  Parameter clz    : t -> option t.\n  Parameter ctz    : t -> option t.\n  Parameter popcnt : t -> option t.\n\n  (* ibinop *)\n  Parameter add   : t -> t -> option t.\n  Parameter sub   : t -> t -> option t.\n  Parameter mul   : t -> t -> option t.\n  Parameter div_s : t -> t -> option t.\n  Parameter div_u : t -> t -> option t.\n  Parameter rem_s : t -> t -> option t.\n  Parameter rem_u : t -> t -> option t.\n  Parameter and   : t -> t -> option t.\n  Parameter or    : t -> t -> option t.\n  Parameter xor   : t -> t -> option t.\n  Parameter shl   : t -> t -> option t.\n  Parameter shr_s : t -> t -> option t.\n  Parameter shr_u : t -> t -> option t.\n  Parameter rotl  : t -> t -> option t.\n  Parameter rotr  : t -> t -> option t.\n\n  (* itestop *)\n  Parameter eqz : t -> bool.\n\n  (* iretop *)\n  Parameter eq   : t -> t -> bool.\n  Parameter ne   : t -> t -> bool.\n  Parameter lt_s : t -> t -> bool.\n  Parameter lt_u : t -> t -> bool.\n  Parameter gt_s : t -> t -> bool.\n  Parameter gt_u : t -> t -> bool.\n  Parameter le_s : t -> t -> bool.\n  Parameter le_u : t -> t -> bool.\n  Parameter ge_s : t -> t -> bool.\n  Parameter ge_u : t -> t -> bool.\n\n  (* axioms *)\nEnd S.\n\n\nModule Make (R: Rep) : S.\n  Include R.\n\n  Parameter t : Type.\n\n  Parameter zero : t.\n  Parameter one : t.\n  Parameter min : t.\n  Parameter max : t.\n  Parameter max16 : t.\n\n  Parameter from_nat : nat -> t.\n  Parameter to_nat : t -> nat.\n\n  (* iunop *)\n  Parameter clz    : t -> option t.\n  Parameter ctz    : t -> option t.\n  Parameter popcnt : t -> option t.\n\n  (* ibinop *)\n  Parameter add   : t -> t -> option t.\n  Parameter sub   : t -> t -> option t.\n  Parameter mul   : t -> t -> option t.\n  Parameter div_s : t -> t -> option t.\n  Parameter div_u : t -> t -> option t.\n  Parameter rem_s : t -> t -> option t.\n  Parameter rem_u : t -> t -> option t.\n  Parameter and   : t -> t -> option t.\n  Parameter or    : t -> t -> option t.\n  Parameter xor   : t -> t -> option t.\n  Parameter shl   : t -> t -> option t.\n  Parameter shr_s : t -> t -> option t.\n  Parameter shr_u : t -> t -> option t.\n  Parameter rotl  : t -> t -> option t.\n  Parameter rotr  : t -> t -> option t.\n\n  (* itestop *)\n  Parameter eqz : t -> bool.\n\n  (* iretop *)\n  Parameter eq   : t -> t -> bool.\n  Parameter ne   : t -> t -> bool.\n  Parameter lt_s : t -> t -> bool.\n  Parameter lt_u : t -> t -> bool.\n  Parameter gt_s : t -> t -> bool.\n  Parameter gt_u : t -> t -> bool.\n  Parameter le_s : t -> t -> bool.\n  Parameter le_u : t -> t -> bool.\n  Parameter ge_s : t -> t -> bool.\n  Parameter ge_u : t -> t -> bool.\n\n  (* axioms *)\nEnd Make.\n\n\n(* ----------------------------------------------------------------- *)\n(** *** Make *)\n\nModule I32 := Int.Make(Rep32).\nModule I64 := Int.Make(Rep64).\n", "meta": {"author": "Huxpro", "repo": "WasmCert", "sha": "7b7385ccbaa62b0aaf6b7757e6847c7d5c32933c", "save_path": "github-repos/coq/Huxpro-WasmCert", "path": "github-repos/coq/Huxpro-WasmCert/WasmCert-7b7385ccbaa62b0aaf6b7757e6847c7d5c32933c/coq/Int.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2726218004793949}}
{"text": "(******************************************************************************)\n(* Tactics for proving and using the 'initState_is' lemmas.                   *)\n(******************************************************************************)\n\nRequire opsem.\nImport opsem.Opsem.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Arith.Peano_dec.\nRequire Import Tvc.base_tactics.\nRequire Import Tvc.llvm_tactics_simplify.\n\nLemma instantiate_gv2gvs :\n  forall TD v t a b c,\n    (eq (genericvalues.LLVMgv.fit_gv TD t [(Values.Vint a b, c)]) (Some [(Values.Vint a b, c)])) ->\n    eq v [(Values.Vint a b, c)] ->\n    (eq (fun gv : genericvalues.LLVMgv.GenericValue =>\n           exists gv1 gv2 : genericvalues.LLVMgv.GenericValue,\n             ndopsem.MNDGVs.instantiate_gvs gv1 (ndopsem.MNDGVs.gv2gvs v t) /\\\n             genericvalues.LLVMgv.fit_gv TD t gv1 = Some gv2 /\\\n             ndopsem.MNDGVs.instantiate_gvs gv (ndopsem.MNDGVs.gv2gvs gv2 t))\n        (ndopsem.MNDGVs.gv2gvs v t)).\nProof.\n  intros ? ? ? ? ? ? H' H.\n  subst.\n  extensionality gv.\n  apply Axioms.prop_ext.\n  split.\n\n  intro.\n  decompose_ex H; decompose [and] H; clear H.\n  inversion H0; clear H0; subst.\n  rewrite H' in H2; clear H'.\n  injection H2; intro; clear H2; subst.\n  assumption.\n\n  intro.\n  exists [(Values.Vint a b, c)].\n  exists [(Values.Vint a b, c)].\n  repeat split.\n  assumption.\n  assumption.\nQed.\n\nTransparent productInModuleB_dec.\n\nLtac prove_initState_is_1 :=\n  let H := fresh in\n  intro H;\n  unfold s_genInitState in H;\n  simpl in H;\n  destruct_all_eq_dec;\n  unfold infrastructure.LLVMinfra.productInModuleB_dec in H;\n  unfold productInModuleB in H;\n  unfold InProductsB in H;\n  simpl in H;\n  unfold productEqB in H;\n  unfold sumbool2bool in H;\n  repeat match goal with\n           | [ _ : context [product_dec ?a ?a] |- _ ] =>\n             let H := fresh in\n             destruct (product_dec a a) as [_ | H]; [ | contradiction H; reflexivity ]\n         end;\n  simpl in H;\n  repeat match goal with\n           | [ _ : context [product_dec ?a ?b] |- _ ] =>\n             let H := fresh in\n             destruct (product_dec a b) as [H | _]; [ discriminate H | ]\n             (* XXX this discriminate is very slow; I'm not sure why *)\n         end;\n  simpl in H;\n  (* g, f, mem *)\n  let f := fresh \"f\" in\n  let g := fresh \"g\" in\n  let mem := fresh \"mem\" in\n  let H1 := fresh in\n  match type of H with\n    | eq (match ?e with | Some _ => _ | None => _ end) _ =>\n      destruct e as [[[g f] mem] | ?] eqn:H1; try discriminate\n  end;\n  exists g;\n  exists f;\n  (* Get an equation for mem *)\n  repeat match type of H1 with\n           | eq (match (initFunTable ?m ?f) with | Some _ => _ | None => _ end) _ =>\n             destruct (initFunTable m f) eqn:H2; clear H2; try discriminate\n         end;\n  repeat match type of H1 with\n           | eq (match (initGlobal ?td ?g ?m ?id ?t ?c ?a) with | Some _ => _ | None => _ end) _ =>\n             destruct (initGlobal td g m id t c a) as [[? ?]|] eqn:H2; clear H2; try discriminate\n         end;\n  injection H1; intros ? _ _; clear H1; subst mem;\n  (* Locals *)\n  match type of H with\n    | eq (match ?e with | Some _ => _ | None => _ end) _ =>\n      destruct e eqn:H2; try discriminate\n  end.\n\nLtac prove_initState_is_2 H v i :=\n  erewrite (instantiate_gv2gvs _ v _ _ _ _) in H; [ | | eassumption ]; [ |\n    unfold fit_gv, gv_chunks_match_typb, gv_chunks_match_typb_aux, Values.Val.has_chunkb;\n    let x := fresh \"x\" in\n    destruct (eq_nat_dec _ _) as [? | x]; [ | contradiction x; reflexivity ];\n    destruct i as [? [? ?]];\n    destruct (Coqlib.zle _ _); [ | contradiction ];\n    destruct (Coqlib.zlt _ _); [ | contradiction ];\n    subst;\n    reflexivity ].\n\n(*\nThis tactic expects to find a hypothesis of the form:\n  H : s_genInitState _ _ _ Memory.Mem.empty = Some (cfg, IS)\nfor some variables cfg, IS.  It will clear hypothesis H, and substitute all occurrences of cfg and\nIS for their actual values.\n*)\nLtac destruct_initState initState_is :=\n  let H' := fresh in\n  match goal with [ H : eq (s_genInitState _ _ _ Memory.Mem.empty) (Some (?cfg, ?IS)) |- _ ] =>\n    let H' := fresh in\n    pose proof initState_is as H';\n    decompose_ex H'; decompose [and] H'; clear H';\n    subst cfg IS;\n    clear H\n  end.\n\n(*\n*** Local Variables: ***\n*** coq-prog-name: \"coqtop\" ***\n*** coq-prog-args: (\"-emacs-U\" \"-require\" \"coqharness\" \"-impredicative-set\" \"-R\" \".\" \"Tvc\" \"-R\" \"../../csem/_coq\" \"Csem\" \"-I\" \"../../vellvm-coq84pl2/release/vol/src/Vellvm\" \"-I\" \"../../vellvm-coq84pl2/release/vol/src/Vellvm/ott\" \"-I\" \"../../vellvm-coq84pl2/release/vol/src/Vellvm/monads\" \"-I\" \"../../vellvm-coq84pl2/release/vol/src/Vellvm/compcert\" \"-I\" \"../../vellvm-coq84pl2/release/vol/src/Vellvm/GraphBasics\" \"-I\" \"../../vellvm-coq84pl2/release/vol/src/Vellvm/Dominators\" \"-I\" \"../../vellvm-coq84pl2/release/vol/extralibs/metatheory_8.4\" \"-I\" \"../../vellvm-coq84pl2/release/vol/extralibs/Coq-Equations/src\" \"-R\" \"../../vellvm-coq84pl2/release/vol/extralibs/Coq-Equations/theories\" \"Equations\" \"-I\" \"~/lem/coq-lib\") ***\n*** End: ***\n*)\n", "meta": {"author": "jchl", "repo": "tvc", "sha": "0abd10dfda06b036eac84ecdd43dae1bcf3cefd7", "save_path": "github-repos/coq/jchl-tvc", "path": "github-repos/coq/jchl-tvc/tvc-0abd10dfda06b036eac84ecdd43dae1bcf3cefd7/coq/llvm_tactics_initstate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2726218004793949}}
{"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 TableAux.Spec.\n\nLocal Open Scope Z_scope.\n\nSection Spec.\n\n  Definition table_fold_spec (table: Pointer) (level: Z64) (g_tbl: Pointer) (adt: RData) : option (RData * Z64) :=\n    match level with\n    | VZ64 level =>\n      rely is_int64 level; rely (level >? 0);\n      rely peq (base table) buffer_loc;\n      rely peq (base g_tbl) ginfo_loc;\n      when gidx == (buffer (priv adt)) @ (offset table);\n      let tbl_gidx := offset g_tbl in\n      rely is_gidx gidx;\n      rely prop_dec (gidx = tbl_gidx);\n      let gn := (gs (share adt)) @ gidx in\n      let gn_tbl := (gs (share adt)) @ tbl_gidx in\n      rely prop_dec (glock gn = Some CPU_ID);\n      rely prop_dec (glock gn_tbl = Some CPU_ID);\n      rely g_tag (ginfo gn) =? GRANULE_STATE_TABLE;\n      rely prop_dec (forall i, is_int64 ((g_data (gnorm gn)) @ i) = true);\n      let pgte := (g_data (gnorm gn)) @ 0 in\n      let ipa_state := PTE_TO_IPA_STATE pgte in\n      let base_pa' := __entry_to_phys pgte (level - 1) in\n      let base_pa := __entry_to_phys pgte level in\n      rely is_int64 base_pa; rely is_int64 (base_pa + PGTES_PER_TABLE * GRANULE_SIZE);\n      rely (level =? RTT_PAGE_LEVEL);\n      rely (__addr_is_level_aligned base_pa (level - 1));\n      rely prop_dec (forall i (Hi: 0 <= i < PGTES_PER_TABLE),\n                      let e := (g_data (gnorm gn)) @ i in\n                      let pa := __entry_to_phys e level in\n                      PTE_TO_IPA_STATE e = ipa_state /\\ pa = base_pa + i * GRANULE_SIZE);\n      let new_pgte := (if ipa_state =? IPA_STATE_PRESENT then\n                          Z.lor (Z.lor (IPA_STATE_TO_PTE ipa_state) base_pa') PGTE_S2_BLOCK\n                        else Z.lor (IPA_STATE_TO_PTE ipa_state) base_pa') in\n      rely is_int64 new_pgte;\n      let g' := gn_tbl {ginfo : (ginfo gn_tbl) {g_refcount : g_refcount (ginfo gn_tbl) - PGTES_PER_TABLE}} in\n      Some (adt {share : (share adt) {gs : (gs (share adt)) # tbl_gidx == g'}}, VZ64 new_pgte)\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/TableAux2/Specs/table_fold.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2725273224430819}}
{"text": "Require Import Bool List String PeanoNat.\nRequire Import Common ListSupport FMap Syntax Semantics StepM.\n\nRequire Import Lia.\n\nSet Implicit Arguments.\n\nLocal Open Scope list.\nLocal Open Scope fmap.\n\nLtac inv_steps :=\n  repeat\n    match goal with\n    | [H: steps _ _ _ nil _ |- _] => inv H\n    | [H: steps _ _ _ (_ :: _) _ |- _] => inv H\n    end.\n\nLtac inv_step :=\n  repeat\n    match goal with\n    | [H: step_m _ _ RlblEmpty _ |- _] => inv H\n    | [H: step_m _ _ (RlblIns _) _ |- _] => inv H\n    | [H: step_m _ _ (RlblOuts _) _ |- _] => inv H\n    | [H: step_m _ _ (RlblInt _ _ _ _) _ |- _] => inv H\n    | [H: {| st_oss := _; st_orqs := _; st_msgs := _ |} =\n          {| st_oss := _; st_orqs := _; st_msgs := _ |} |- _] => inv H\n    end.\n\nDefinition lastOIdxOf `{DecValue} (hst: History): option IdxT :=\n  match hst with\n  | RlblInt oidx _ _ _ :: _ => Some oidx\n  | _ => None\n  end.\n\nDefinition oidxOf `{DecValue} (lbl: RLabel) :=\n  match lbl with\n  | RlblInt oidx _ _ _ => Some oidx\n  | _ => None\n  end.\n\nFixpoint oindsOf `{DecValue} (hst: History) :=\n  match hst with\n  | nil => nil\n  | lbl :: hst' => (oidxOf lbl) ::> (oindsOf hst')\n  end.\n\nLemma oindsOf_app:\n  forall `{DecValue} (hst1 hst2: History),\n    oindsOf (hst1 ++ hst2) = oindsOf hst1 ++ oindsOf hst2.\nProof.\n  induction hst1 as [|lbl hst1]; simpl; intros; [reflexivity|].\n  destruct (oidxOf lbl); simpl; auto.\n  rewrite IHhst1; reflexivity.\nQed.\n\nLemma lastOIdxOf_app:\n  forall `{DecValue} (hst1 hst2: History),\n    hst2 <> nil ->\n    lastOIdxOf (hst2 ++ hst1) = lastOIdxOf hst2.\nProof.\n  intros.\n  destruct hst2; [exfalso; auto|].\n  reflexivity.\nQed.\n\nLemma lastOIdxOf_Some_oindsOf_In:\n  forall `{dv: DecValue} (hst: History) loidx,\n    lastOIdxOf hst = Some loidx ->\n    In loidx (oindsOf hst).\nProof.\n  intros.\n  destruct hst as [|lbl hst]; [discriminate|].\n  simpl in H.\n  destruct lbl; try discriminate.\n  inv H.\n  left; reflexivity.\nQed.\n\nLemma steps_object_in_system:\n  forall `{dv: DecValue} `{oifc: OStateIfc} (sys: System) st1 hst st2,\n    steps step_m sys st1 hst st2 ->\n    forall oidx,\n      In oidx (oindsOf hst) ->\n      exists obj,\n        In obj sys.(sys_objs) /\\\n        obj.(obj_idx) = oidx.\nProof.\n  induction 1; simpl; intros; [exfalso; auto|].\n  destruct lbl; simpl in *; auto.\n  destruct H1; subst; auto.\n  inv_step.\n  exists obj; auto.\nQed.\n\nLemma sys_minds_sys_merqs_DisjList:\n  forall `{dv: DecValue} `{oifc: OStateIfc} (sys: System),\n    DisjList (sys_minds sys) (sys_merqs sys).\nProof.\n  intros.\n  eapply DisjList_NoDup; [exact idx_dec|].\n  eapply NoDup_app_weakening_1.\n  rewrite <-app_assoc.\n  apply sys_msg_inds_valid.\nQed.\n\nLemma sys_merqs_sys_merss_DisjList:\n  forall `{dv: DecValue} `{oifc: OStateIfc} (sys: System),\n    DisjList (sys_merqs sys) (sys_merss sys).\nProof.\n  intros.\n  eapply DisjList_NoDup; [exact idx_dec|].\n  eapply NoDup_app_weakening_2.\n  apply sys_msg_inds_valid.\nQed.\n\nLemma sys_minds_sys_merss_DisjList:\n  forall `{dv: DecValue} `{oifc: OStateIfc} (sys: System),\n    DisjList (sys_minds sys) (sys_merss sys).\nProof.\n  intros.\n  eapply DisjList_NoDup; [exact idx_dec|].\n  pose proof (sys_msg_inds_valid sys).\n  rewrite app_assoc in H.\n  apply NoDup_app_comm in H.\n  rewrite app_assoc in H.\n  apply NoDup_app_weakening_1 in H.\n  apply NoDup_app_comm; assumption.\nQed.\n\nLemma ValidMsgsIn_sys_minds:\n  forall `{DecValue} `{oifc: OStateIfc}\n         (sys1: System) (eins: list (Id Msg)),\n    ValidMsgsIn sys1 eins ->\n    forall (sys2: System),\n      sys_minds sys1 = sys_minds sys2 ->\n      sys_merqs sys1 = sys_merqs sys2 ->\n      ValidMsgsIn sys2 eins.\nProof.\n  unfold ValidMsgsIn; intros.\n  dest; split; auto.\n  rewrite <-H1, <-H2; assumption.\nQed.\n\nLemma ValidMsgsOut_sys_minds_sys_merss:\n  forall `{DecValue} `{oifc: OStateIfc}\n         (sys1: System) (eouts: list (Id Msg)),\n    ValidMsgsOut sys1 eouts ->\n    forall (sys2: System),\n      sys_minds sys1 = sys_minds sys2 ->\n      sys_merss sys1 = sys_merss sys2 ->\n      ValidMsgsOut sys2 eouts.\nProof.\n  unfold ValidMsgsOut; intros.\n  dest; split; auto.\n  rewrite <-H1, <-H2; assumption.\nQed.\n\nLemma ValidMsgsExtIn_sys_merqs:\n  forall `{DecValue} `{oifc: OStateIfc}\n         (sys1: System) (eins: list (Id Msg)),\n    ValidMsgsExtIn sys1 eins ->\n    forall (sys2: System),\n      sys_merqs sys1 = sys_merqs sys2 ->\n      ValidMsgsExtIn sys2 eins.\nProof.\n  unfold ValidMsgsExtIn; intros.\n  dest; split; auto.\n  rewrite <-H1; assumption.\nQed.\n\nLemma ValidMsgsExtOut_sys_merss:\n  forall `{DecValue} `{oifc: OStateIfc}\n         (sys1: System) (eouts: list (Id Msg)),\n    ValidMsgsExtOut sys1 eouts ->\n    forall (sys2: System),\n      sys_merss sys1 = sys_merss sys2 ->\n      ValidMsgsExtOut sys2 eouts.\nProof.\n  unfold ValidMsgsExtOut; intros.\n  dest; split; auto.\n  rewrite <-H1; assumption.\nQed.\n\nLemma extRssOf_In_sys_merss_FirstMP:\n  forall `{DecValue} `{oifc: OStateIfc} (sys: System) msgs1 msgs2,\n    extRssOf sys msgs1 = extRssOf sys msgs2 ->\n    forall mout,\n      In (idOf mout) (sys_merss sys) ->\n      FirstMP msgs1 (idOf mout) (valOf mout) ->\n      FirstMP msgs2 (idOf mout) (valOf mout).\nProof.\n  unfold extRssOf; intros.\n  eapply qsOf_In_FirstMP; eauto.\nQed.\n\nCorollary extRssOf_SubList_sys_merss_FirstMP:\n  forall `{dv: DecValue} `{oifc: OStateIfc} (sys: System) msgs1 msgs2,\n    extRssOf sys msgs1 = extRssOf sys msgs2 ->\n    forall mouts,\n      SubList (idsOf mouts) (sys_merss sys) ->\n      Forall (FirstMPI msgs1) mouts ->\n      Forall (FirstMPI msgs2) mouts.\nProof.\n  induction mouts; simpl; intros; [constructor|].\n  apply SubList_cons_inv in H0; dest.\n  inv H1; constructor; auto.\n  unfold FirstMPI in *.\n  eauto using extRssOf_In_sys_merss_FirstMP.\nQed.\n\nCorollary extRssOf_ValidMsgsExtOut_sys_merss_FirstMP:\n  forall `{dv: DecValue} `{oifc: OStateIfc} (sys: System) msgs1 msgs2,\n    extRssOf sys msgs1 = extRssOf sys msgs2 ->\n    forall mouts,\n      ValidMsgsExtOut sys mouts ->\n      Forall (FirstMPI msgs1) mouts ->\n      Forall (FirstMPI msgs2) mouts.\nProof.\n  intros.\n  destruct H0.\n  eauto using extRssOf_SubList_sys_merss_FirstMP.\nQed.\n\nLemma init_IntMsgsEmpty:\n  forall `{DecValue} `{oifc: OStateIfc} (sys: System),\n    IntMsgsEmpty sys (emptyMP Msg).\nProof.\n  intros; red; intros.\n  reflexivity.\nQed.\n\nLemma steps_locks_unaffected:\n  forall `{dv: DecValue} `{oifc: OStateIfc} (sys: System) s1 hst s2,\n    steps step_m sys s1 hst s2 ->\n    forall oidx,\n      ~ In oidx (oindsOf hst) ->\n      s1.(st_orqs)@[oidx] = s2.(st_orqs)@[oidx].\nProof.\n  induction 1; simpl; intros; auto.\n  inv H0; auto; simpl in *.\n  destruct (idx_dec (obj_idx obj) oidx); subst; [exfalso; auto|].\n  mred.\n  apply IHsteps; auto.\nQed.\n\nLemma steps_singleton:\n  forall `{DecValue} `{oifc: OStateIfc} (sys: System) st1 lbl st2,\n    step_m sys st1 lbl st2 ->\n    steps step_m sys st1 [lbl] st2.\nProof.\n  intros.\n  repeat econstructor.\n  assumption.\nQed.\n\nLemma steps_split:\n  forall {SystemT StateT LabelT}\n         (step: Step SystemT StateT LabelT) sys st1 st2 ll,\n    steps step sys st1 ll st2 ->\n    forall ll1 ll2,\n      ll = ll2 ++ ll1 ->\n      exists sti,\n        steps step sys st1 ll1 sti /\\\n        steps step sys sti ll2 st2.\nProof.\n  induction 1; simpl; intros.\n  - apply eq_sym, app_eq_nil in H; dest; subst.\n    eexists; split; econstructor.\n  - destruct ll2.\n    + simpl in H1; subst.\n      specialize (IHsteps ll nil eq_refl).\n      destruct IHsteps as [tsi [? ?]].\n      inv H2.\n      eexists; split.\n      * econstructor; eauto.\n      * econstructor.\n    + simpl in H1; inv H1.\n      specialize (IHsteps _ _ eq_refl).\n      destruct IHsteps as [sti [? ?]].\n      eexists; split; eauto.\n      econstructor; eauto.\nQed.\n\nLemma steps_append:\n  forall {SystemT StateT LabelT}\n         (step: Step SystemT StateT LabelT) sys st1 ll1 st2,\n    steps step sys st1 ll1 st2 ->\n    forall ll2 st3,\n      steps step sys st2 ll2 st3 ->\n      steps step sys st1 (ll2 ++ ll1) st3.\nProof.\n  induction 2; simpl; intros; [auto|].\n  econstructor; eauto.\nQed.\n\nLemma reachable_init:\n  forall {SystemT StateT LabelT} `{HasInit SystemT StateT} `{HasLabel LabelT}\n         (step: Step SystemT StateT LabelT) sys,\n    Reachable (steps step) sys (initsOf sys).\nProof.\n  eexists; econstructor.\nQed.\n\nLemma reachable_steps:\n  forall {SystemT StateT LabelT} `{HasInit SystemT StateT} `{HasLabel LabelT}\n         (step: Step SystemT StateT LabelT) sys st1,\n    Reachable (steps step) sys st1 ->\n    forall ll st2,\n      steps step sys st1 ll st2 ->\n      Reachable (steps step) sys st2.\nProof.\n  unfold Reachable; intros; dest.\n  eexists; eapply steps_append; eauto.\nQed.\n\nLemma behaviorOf_app:\n  forall {LabelT} `{HasLabel LabelT} (hst1 hst2: list LabelT),\n    behaviorOf (hst1 ++ hst2) =\n    behaviorOf hst1 ++ behaviorOf hst2.\nProof.\n  induction hst1; simpl; intros; auto.\n  rewrite IHhst1.\n  destruct (getLabel a); reflexivity.\nQed.\n\nTheorem refines_refl:\n  forall {SystemT StateT LabelT} `{HasInit SystemT StateT} `{HasLabel LabelT}\n         (ss: Steps SystemT StateT LabelT) sys, ss # ss |-- sys ⊑ sys.\nProof.\n  unfold Refines; intros.\n  assumption.\nQed.\n\nTheorem refines_trans:\n  forall {SystemT1 StateT1} `{HasInit SystemT1 StateT1}\n         {SystemT2 StateT2} `{HasInit SystemT2 StateT2}\n         {LabelT} `{HasLabel LabelT}\n         (ss1: Steps SystemT1 StateT1 LabelT)\n         (ss2: Steps SystemT2 StateT2 LabelT)\n         s1 s2,\n    ss1 # ss2 |-- s1 ⊑ s2 ->\n    forall {SystemT3 StateT3} `{HasInit SystemT3 StateT3}\n           (ss3: Steps SystemT3 StateT3 LabelT) s3,\n      ss2 # ss3 |-- s2 ⊑ s3 ->\n      ss1 # ss3 |-- s1 ⊑ s3.\nProof.\n  unfold Refines; intros.\n  specialize (H5 _ (H3 _ H6)).\n  assumption.\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/SemFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2725273224430819}}
{"text": "(** * Functoriality of functor category construction *)\nRequire Import Category.Core Functor.Core FunctorCategory.Core Functor.Pointwise.Core Functor.Pointwise.Properties Category.Dual Category.Prod Cat.Core ExponentialLaws.Law4.Functors.\n\nSet Universe Polymorphism.\nSet Implicit Arguments.\nGeneralizable All Variables.\nSet Asymmetric Patterns.\n\nLocal Open Scope category_scope.\nLocal Open Scope type_scope.\n\n(** ** [(_ → _)] is a functor [catᵒᵖ × cat → cat] *)\nSection functor.\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  Hypothesis has_functor_categories : forall C D : cat, P (C.1 -> D.1).\n\n  Local Open Scope category_scope.\n\n  Definition functor_uncurried\n  : object ((cat^op * cat) -> cat)\n    := Eval cbv zeta in\n        let object_of := (fun CD => (((fst CD).1 -> (snd CD).1);\n                                     has_functor_categories (fst CD) (snd CD)))\n        in Build_Functor\n             (cat^op * cat) cat\n             object_of\n             (fun CD C'D' FG => pointwise (fst FG) (snd FG))\n             (fun _ _ _ _ _ => Functor.Pointwise.Properties.composition_of _ _ _ _)\n             (fun _ => Functor.Pointwise.Properties.identity_of _ _).\n\n  Definition functor : object (cat^op -> (cat -> cat))\n    := ExponentialLaws.Law4.Functors.inverse _ _ _ functor_uncurried.\nEnd functor.\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/FunctorCategory/Functorial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.27252732244308187}}
{"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 0\n*)\n\n(** 1 Mutual Coinduction *)\n\nSection Arg0_1.\n\nDefinition monotone0 (gf: rel0 -> rel0) :=\n  forall r r' (IN: gf r) (LE: r <0= r'), gf r'.\n\nVariable gf : rel0 -> rel0.\nArguments gf : clear implicits.\n\nTheorem paco0_acc: forall\n  l r (OBG: forall rr (INC: r <0= rr) (CIH: l <_paco_0= rr), l <_paco_0= paco0 gf rr),\n  l <0= paco0 gf r.\nProof.\n  intros; assert (SIM: paco0 gf (r \\0/ l)) by eauto.\n  clear PR; repeat (try left; do 1 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco0_mon: monotone0 (paco0 gf).\nProof. paco_cofix_auto; repeat (left; do 1 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco0_mult_strong: forall r,\n  paco0 gf (upaco0 gf r) <0= paco0 gf r.\nProof. paco_cofix_auto; repeat (left; do 1 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco0_mult: forall r,\n  paco0 gf (paco0 gf r) <0= paco0 gf r.\nProof. intros; eapply paco0_mult_strong, paco0_mon; eauto. Qed.\n\nTheorem paco0_fold: forall r,\n  gf (upaco0 gf r) <0= paco0 gf r.\nProof. intros; econstructor; [ |eauto]; eauto. Qed.\n\nTheorem paco0_unfold: forall (MON: monotone0 gf) r,\n  paco0 gf r <0= gf (upaco0 gf r).\nProof. unfold monotone0; intros; destruct PR; eauto. Qed.\n\nEnd Arg0_1.\n\nHint Unfold monotone0.\nHint Resolve paco0_fold.\n\nArguments paco0_acc            : clear implicits.\nArguments paco0_mon            : clear implicits.\nArguments paco0_mult_strong    : clear implicits.\nArguments paco0_mult           : clear implicits.\nArguments paco0_fold           : clear implicits.\nArguments paco0_unfold         : clear implicits.\n\nInstance paco0_inst  (gf : rel0->_) r : paco_class (paco0 gf r) :=\n{ pacoacc    := paco0_acc gf;\n  pacomult   := paco0_mult gf;\n  pacofold   := paco0_fold gf;\n  pacounfold := paco0_unfold gf }.\n\n(** 2 Mutual Coinduction *)\n\nSection Arg0_2.\n\nDefinition monotone0_2 (gf: rel0 -> rel0 -> rel0) :=\n  forall r_0 r_1 r'_0 r'_1 (IN: gf r_0 r_1) (LE_0: r_0 <0= r'_0)(LE_1: r_1 <0= r'_1), gf r'_0 r'_1.\n\nVariable gf_0 gf_1 : rel0 -> rel0 -> rel0.\nArguments gf_0 : clear implicits.\nArguments gf_1 : clear implicits.\n\nTheorem paco0_2_0_acc: forall\n  l r_0 r_1 (OBG: forall rr (INC: r_0 <0= rr) (CIH: l <_paco_0= rr), l <_paco_0= paco0_2_0 gf_0 gf_1 rr r_1),\n  l <0= paco0_2_0 gf_0 gf_1 r_0 r_1.\nProof.\n  intros; assert (SIM: paco0_2_0 gf_0 gf_1 (r_0 \\0/ l) r_1) by eauto.\n  clear PR; repeat (try left; do 1 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco0_2_1_acc: forall\n  l r_0 r_1 (OBG: forall rr (INC: r_1 <0= rr) (CIH: l <_paco_0= rr), l <_paco_0= paco0_2_1 gf_0 gf_1 r_0 rr),\n  l <0= paco0_2_1 gf_0 gf_1 r_0 r_1.\nProof.\n  intros; assert (SIM: paco0_2_1 gf_0 gf_1 r_0 (r_1 \\0/ l)) by eauto.\n  clear PR; repeat (try left; do 1 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco0_2_0_mon: monotone0_2 (paco0_2_0 gf_0 gf_1).\nProof. paco_cofix_auto; repeat (left; do 1 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco0_2_1_mon: monotone0_2 (paco0_2_1 gf_0 gf_1).\nProof. paco_cofix_auto; repeat (left; do 1 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco0_2_0_mult_strong: forall r_0 r_1,\n  paco0_2_0 gf_0 gf_1 (upaco0_2_0 gf_0 gf_1 r_0 r_1) (upaco0_2_1 gf_0 gf_1 r_0 r_1) <0= paco0_2_0 gf_0 gf_1 r_0 r_1.\nProof. paco_cofix_auto; repeat (left; do 1 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco0_2_1_mult_strong: forall r_0 r_1,\n  paco0_2_1 gf_0 gf_1 (upaco0_2_0 gf_0 gf_1 r_0 r_1) (upaco0_2_1 gf_0 gf_1 r_0 r_1) <0= paco0_2_1 gf_0 gf_1 r_0 r_1.\nProof. paco_cofix_auto; repeat (left; do 1 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco0_2_0_mult: forall r_0 r_1,\n  paco0_2_0 gf_0 gf_1 (paco0_2_0 gf_0 gf_1 r_0 r_1) (paco0_2_1 gf_0 gf_1 r_0 r_1) <0= paco0_2_0 gf_0 gf_1 r_0 r_1.\nProof. intros; eapply paco0_2_0_mult_strong, paco0_2_0_mon; eauto. Qed.\n\nCorollary paco0_2_1_mult: forall r_0 r_1,\n  paco0_2_1 gf_0 gf_1 (paco0_2_0 gf_0 gf_1 r_0 r_1) (paco0_2_1 gf_0 gf_1 r_0 r_1) <0= paco0_2_1 gf_0 gf_1 r_0 r_1.\nProof. intros; eapply paco0_2_1_mult_strong, paco0_2_1_mon; eauto. Qed.\n\nTheorem paco0_2_0_fold: forall r_0 r_1,\n  gf_0 (upaco0_2_0 gf_0 gf_1 r_0 r_1) (upaco0_2_1 gf_0 gf_1 r_0 r_1) <0= paco0_2_0 gf_0 gf_1 r_0 r_1.\nProof. intros; econstructor; [ | |eauto]; eauto. Qed.\n\nTheorem paco0_2_1_fold: forall r_0 r_1,\n  gf_1 (upaco0_2_0 gf_0 gf_1 r_0 r_1) (upaco0_2_1 gf_0 gf_1 r_0 r_1) <0= paco0_2_1 gf_0 gf_1 r_0 r_1.\nProof. intros; econstructor; [ | |eauto]; eauto. Qed.\n\nTheorem paco0_2_0_unfold: forall (MON: monotone0_2 gf_0) (MON: monotone0_2 gf_1) r_0 r_1,\n  paco0_2_0 gf_0 gf_1 r_0 r_1 <0= gf_0 (upaco0_2_0 gf_0 gf_1 r_0 r_1) (upaco0_2_1 gf_0 gf_1 r_0 r_1).\nProof. unfold monotone0_2; intros; destruct PR; eauto. Qed.\n\nTheorem paco0_2_1_unfold: forall (MON: monotone0_2 gf_0) (MON: monotone0_2 gf_1) r_0 r_1,\n  paco0_2_1 gf_0 gf_1 r_0 r_1 <0= gf_1 (upaco0_2_0 gf_0 gf_1 r_0 r_1) (upaco0_2_1 gf_0 gf_1 r_0 r_1).\nProof. unfold monotone0_2; intros; destruct PR; eauto. Qed.\n\nEnd Arg0_2.\n\nHint Unfold monotone0_2.\nHint Resolve paco0_2_0_fold.\nHint Resolve paco0_2_1_fold.\n\nArguments paco0_2_0_acc            : clear implicits.\nArguments paco0_2_1_acc            : clear implicits.\nArguments paco0_2_0_mon            : clear implicits.\nArguments paco0_2_1_mon            : clear implicits.\nArguments paco0_2_0_mult_strong    : clear implicits.\nArguments paco0_2_1_mult_strong    : clear implicits.\nArguments paco0_2_0_mult           : clear implicits.\nArguments paco0_2_1_mult           : clear implicits.\nArguments paco0_2_0_fold           : clear implicits.\nArguments paco0_2_1_fold           : clear implicits.\nArguments paco0_2_0_unfold         : clear implicits.\nArguments paco0_2_1_unfold         : clear implicits.\n\nInstance paco0_2_0_inst  (gf_0 gf_1 : rel0->_) r_0 r_1 : paco_class (paco0_2_0 gf_0 gf_1 r_0 r_1) :=\n{ pacoacc    := paco0_2_0_acc gf_0 gf_1;\n  pacomult   := paco0_2_0_mult gf_0 gf_1;\n  pacofold   := paco0_2_0_fold gf_0 gf_1;\n  pacounfold := paco0_2_0_unfold gf_0 gf_1 }.\n\nInstance paco0_2_1_inst  (gf_0 gf_1 : rel0->_) r_0 r_1 : paco_class (paco0_2_1 gf_0 gf_1 r_0 r_1) :=\n{ pacoacc    := paco0_2_1_acc gf_0 gf_1;\n  pacomult   := paco0_2_1_mult gf_0 gf_1;\n  pacofold   := paco0_2_1_fold gf_0 gf_1;\n  pacounfold := paco0_2_1_unfold gf_0 gf_1 }.\n\n(** 3 Mutual Coinduction *)\n\nSection Arg0_3.\n\nDefinition monotone0_3 (gf: rel0 -> rel0 -> rel0 -> rel0) :=\n  forall r_0 r_1 r_2 r'_0 r'_1 r'_2 (IN: gf r_0 r_1 r_2) (LE_0: r_0 <0= r'_0)(LE_1: r_1 <0= r'_1)(LE_2: r_2 <0= r'_2), gf r'_0 r'_1 r'_2.\n\nVariable gf_0 gf_1 gf_2 : rel0 -> rel0 -> rel0 -> rel0.\nArguments gf_0 : clear implicits.\nArguments gf_1 : clear implicits.\nArguments gf_2 : clear implicits.\n\nTheorem paco0_3_0_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_0 <0= rr) (CIH: l <_paco_0= rr), l <_paco_0= paco0_3_0 gf_0 gf_1 gf_2 rr r_1 r_2),\n  l <0= paco0_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco0_3_0 gf_0 gf_1 gf_2 (r_0 \\0/ l) r_1 r_2) by eauto.\n  clear PR; repeat (try left; do 1 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco0_3_1_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_1 <0= rr) (CIH: l <_paco_0= rr), l <_paco_0= paco0_3_1 gf_0 gf_1 gf_2 r_0 rr r_2),\n  l <0= paco0_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco0_3_1 gf_0 gf_1 gf_2 r_0 (r_1 \\0/ l) r_2) by eauto.\n  clear PR; repeat (try left; do 1 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco0_3_2_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_2 <0= rr) (CIH: l <_paco_0= rr), l <_paco_0= paco0_3_2 gf_0 gf_1 gf_2 r_0 r_1 rr),\n  l <0= paco0_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco0_3_2 gf_0 gf_1 gf_2 r_0 r_1 (r_2 \\0/ l)) by eauto.\n  clear PR; repeat (try left; do 1 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco0_3_0_mon: monotone0_3 (paco0_3_0 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 1 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco0_3_1_mon: monotone0_3 (paco0_3_1 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 1 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco0_3_2_mon: monotone0_3 (paco0_3_2 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 1 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco0_3_0_mult_strong: forall r_0 r_1 r_2,\n  paco0_3_0 gf_0 gf_1 gf_2 (upaco0_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco0_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco0_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <0= paco0_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 1 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco0_3_1_mult_strong: forall r_0 r_1 r_2,\n  paco0_3_1 gf_0 gf_1 gf_2 (upaco0_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco0_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco0_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <0= paco0_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 1 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco0_3_2_mult_strong: forall r_0 r_1 r_2,\n  paco0_3_2 gf_0 gf_1 gf_2 (upaco0_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco0_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco0_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <0= paco0_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 1 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco0_3_0_mult: forall r_0 r_1 r_2,\n  paco0_3_0 gf_0 gf_1 gf_2 (paco0_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco0_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco0_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <0= paco0_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco0_3_0_mult_strong, paco0_3_0_mon; eauto. Qed.\n\nCorollary paco0_3_1_mult: forall r_0 r_1 r_2,\n  paco0_3_1 gf_0 gf_1 gf_2 (paco0_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco0_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco0_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <0= paco0_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco0_3_1_mult_strong, paco0_3_1_mon; eauto. Qed.\n\nCorollary paco0_3_2_mult: forall r_0 r_1 r_2,\n  paco0_3_2 gf_0 gf_1 gf_2 (paco0_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco0_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco0_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <0= paco0_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco0_3_2_mult_strong, paco0_3_2_mon; eauto. Qed.\n\nTheorem paco0_3_0_fold: forall r_0 r_1 r_2,\n  gf_0 (upaco0_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco0_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco0_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <0= paco0_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco0_3_1_fold: forall r_0 r_1 r_2,\n  gf_1 (upaco0_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco0_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco0_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <0= paco0_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco0_3_2_fold: forall r_0 r_1 r_2,\n  gf_2 (upaco0_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco0_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco0_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <0= paco0_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco0_3_0_unfold: forall (MON: monotone0_3 gf_0) (MON: monotone0_3 gf_1) (MON: monotone0_3 gf_2) r_0 r_1 r_2,\n  paco0_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2 <0= gf_0 (upaco0_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco0_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco0_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2).\nProof. unfold monotone0_3; intros; destruct PR; eauto. Qed.\n\nTheorem paco0_3_1_unfold: forall (MON: monotone0_3 gf_0) (MON: monotone0_3 gf_1) (MON: monotone0_3 gf_2) r_0 r_1 r_2,\n  paco0_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2 <0= gf_1 (upaco0_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco0_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco0_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2).\nProof. unfold monotone0_3; intros; destruct PR; eauto. Qed.\n\nTheorem paco0_3_2_unfold: forall (MON: monotone0_3 gf_0) (MON: monotone0_3 gf_1) (MON: monotone0_3 gf_2) r_0 r_1 r_2,\n  paco0_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2 <0= gf_2 (upaco0_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco0_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco0_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2).\nProof. unfold monotone0_3; intros; destruct PR; eauto. Qed.\n\nEnd Arg0_3.\n\nHint Unfold monotone0_3.\nHint Resolve paco0_3_0_fold.\nHint Resolve paco0_3_1_fold.\nHint Resolve paco0_3_2_fold.\n\nArguments paco0_3_0_acc            : clear implicits.\nArguments paco0_3_1_acc            : clear implicits.\nArguments paco0_3_2_acc            : clear implicits.\nArguments paco0_3_0_mon            : clear implicits.\nArguments paco0_3_1_mon            : clear implicits.\nArguments paco0_3_2_mon            : clear implicits.\nArguments paco0_3_0_mult_strong    : clear implicits.\nArguments paco0_3_1_mult_strong    : clear implicits.\nArguments paco0_3_2_mult_strong    : clear implicits.\nArguments paco0_3_0_mult           : clear implicits.\nArguments paco0_3_1_mult           : clear implicits.\nArguments paco0_3_2_mult           : clear implicits.\nArguments paco0_3_0_fold           : clear implicits.\nArguments paco0_3_1_fold           : clear implicits.\nArguments paco0_3_2_fold           : clear implicits.\nArguments paco0_3_0_unfold         : clear implicits.\nArguments paco0_3_1_unfold         : clear implicits.\nArguments paco0_3_2_unfold         : clear implicits.\n\nInstance paco0_3_0_inst  (gf_0 gf_1 gf_2 : rel0->_) r_0 r_1 r_2 : paco_class (paco0_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) :=\n{ pacoacc    := paco0_3_0_acc gf_0 gf_1 gf_2;\n  pacomult   := paco0_3_0_mult gf_0 gf_1 gf_2;\n  pacofold   := paco0_3_0_fold gf_0 gf_1 gf_2;\n  pacounfold := paco0_3_0_unfold gf_0 gf_1 gf_2 }.\n\nInstance paco0_3_1_inst  (gf_0 gf_1 gf_2 : rel0->_) r_0 r_1 r_2 : paco_class (paco0_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) :=\n{ pacoacc    := paco0_3_1_acc gf_0 gf_1 gf_2;\n  pacomult   := paco0_3_1_mult gf_0 gf_1 gf_2;\n  pacofold   := paco0_3_1_fold gf_0 gf_1 gf_2;\n  pacounfold := paco0_3_1_unfold gf_0 gf_1 gf_2 }.\n\nInstance paco0_3_2_inst  (gf_0 gf_1 gf_2 : rel0->_) r_0 r_1 r_2 : paco_class (paco0_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) :=\n{ pacoacc    := paco0_3_2_acc gf_0 gf_1 gf_2;\n  pacomult   := paco0_3_2_mult gf_0 gf_1 gf_2;\n  pacofold   := paco0_3_2_fold gf_0 gf_1 gf_2;\n  pacounfold := paco0_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/paco0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.27252732244308187}}
{"text": "(* DEC1 language development.\n   Paolo Torrini, \n   Universite' Lille-1 - CRIStAL-CNRS\n*)\n(* weakening lemmas *)\n\nRequire Export Basics.\n\nRequire Export EnvLibA.\nRequire Export RelLibA.\n\nRequire Export Coq.Program.Equality.\nRequire Import Coq.Init.Specif.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Omega.\nRequire Import Coq.Lists.List.\n\nRequire Import StaticSemA.\nRequire Import DynamicSemA.\n\nImport ListNotations.\n\nModule Weaken (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 DynamicI := Dynamic IdT.\nExport DynamicI.\n\n\nLemma QValWeakening (env env': valEnv)\n      (n1 n2: W)\n      (q1 q2: QValue):\n  QVStep env (Conf QValue n1 q1) (Conf QValue n2 q2) ->\n  QVStep (env ++ env') (Conf QValue n1 q1) (Conf QValue n2 q2).\nProof.\n  intros. \n  inversion X; subst.\n  constructor.\n  inversion X0; subst.\n  eapply override_simpl1 with (env2:=env') in H.\n  constructor.\n  rewrite H.\n  inversion X0; subst.\n  assumption.\nDefined.\n\n\nLemma QFunWeakening (env env': funEnv)\n      (n1 n2: W)\n      (q1 q2: QFun):\n  QFStep env (Conf QFun n1 q1) (Conf QFun n2 q2) ->\n  QFStep (env ++ env') (Conf QFun n1 q1) (Conf QFun n2 q2).\nProof.\n  intros. \n  inversion X; subst.\n  constructor.\n  inversion X0; subst.\n  eapply override_simpl1 with (env2:=env') in H.\n  constructor.\n  rewrite H.\n  inversion X0; subst.\n  assumption.\nDefined.\n  \n\nLemma weaken \n           (fenv fenv': funEnv) (env env': valEnv)\n           (n1 n2: W) (e1 e2: Exp):\n      EClosure fenv env (Conf Exp n1 e1) (Conf Exp n2 e2) ->\n      EClosure (fenv ++ fenv') (env ++ env')\n               (Conf Exp n1 e1) (Conf Exp n2 e2).\nProof.\n  intros.  \n  dependent induction X.\n  constructor.\n  destruct p2 as [n0 e0].\n  specialize (IHX n0 n2 e0 e2 eq_refl eq_refl).\n  econstructor.\n  Focus 2.\n  eassumption.\n\n  (***)\n\n  clear IHX.\n  clear X.\n  rename e into H.\n  clear n2 e2.\n  revert fenv' env'.\n  \n  (***)\n\n    eapply (EStep_mut (fun fenv env c1 c2\n (ExIH: EStep fenv env c1 c2) => forall fenv' env',    \n  EStep (fenv ++ fenv') (env ++ env') \n        c1 c2)\n  (fun fenv env c1 c2\n  (PsIH: PrmsStep fenv env c1 c2) => forall fenv' env', \n  PrmsStep (fenv ++ fenv') (env ++ env') \n           c1 c2)).\n\n  - intros.\n    constructor.\n  - intros.                     \n    constructor.\n    eapply QValWeakening.\n    assumption.\n  - intros.\n    constructor.\n  - intros.\n    constructor.\n    eapply QValWeakening.\n    assumption.\n  - intros.\n    constructor.\n  - intros.\n    constructor.\n    eapply X.\n  - intros.    \n    constructor.    \n  - intros.  \n    constructor.    \n    eapply X.\n  - intros.        \n    constructor. \n  - intros. \n    econstructor.\n    + reflexivity.\n    + reflexivity.\n    + rewrite app_assoc.\n      rewrite app_assoc.\n      specialize (X fenv'0 env'0).\n      rewrite e2 in X.\n      rewrite e3 in X.\n      eapply X. \n  - intros.\n    econstructor.\n    auto.\n    eassumption.\n    assumption.\n    assumption.\n  - intros.\n    econstructor.\n    eassumption.\n    assumption.\n    assumption.\n  - intros.  \n    econstructor.\n    eapply X.    \n  - intros.\n    econstructor.\n    eapply QFunWeakening.       \n    assumption.    \n  - intros.\n    constructor.\n  - intros.\n    constructor.\n  - intros.\n    constructor.\n    eapply X.\n  - intros.\n    constructor.\n    eapply X.                 \n  - intros.\n    constructor.      \n    eapply X.     \n  - assumption.\nDefined.    \n\n\n\nDefinition FunWeaken :=\n     fun (f: Fun) (ft: FTyp) \n         (k: FunTyping f ft) => True.    \n      \nDefinition QFunWeaken :=\n     fun (ftenv: funTC) (fenv: funEnv)\n         (q: QFun) (ft: FTyp) \n         (k: QFunTyping ftenv fenv q ft) =>\n       MatchEnvsT FunTyping fenv ftenv ->\n       forall (ftenv': funTC) (fenv': funEnv),\n          MatchEnvsT FunTyping fenv' ftenv' ->\n          QFunTyping (ftenv ++ ftenv') (fenv ++ fenv') q ft.\n          \nDefinition ExpWeaken :=\n     fun (ftenv: funTC) (tenv: valTC) (fenv: funEnv)\n         (e: Exp) (t: VTyp) \n         (k: ExpTyping ftenv tenv fenv e t) =>\n   MatchEnvsT FunTyping fenv ftenv ->\n   forall (ftenv': funTC) (tenv': valTC) (fenv': funEnv),\n       MatchEnvsT FunTyping fenv' ftenv' -> \n       ExpTyping (ftenv ++ ftenv') (tenv ++ tenv') (fenv ++ fenv') e t.\n\n\nDefinition PrmsWeaken :=\n     fun (ftenv: funTC) (tenv: valTC) (fenv: funEnv)\n         (ps: Prms) (pt: PTyp) \n         (k: PrmsTyping ftenv tenv fenv ps pt) => \n   MatchEnvsT FunTyping fenv ftenv ->\n   forall (ftenv': funTC) (tenv': valTC) (fenv': funEnv),\n       MatchEnvsT FunTyping fenv' ftenv' -> \n       PrmsTyping (ftenv ++ ftenv') (tenv ++ tenv') (fenv ++ fenv') ps pt.\n\n\n\nDefinition ExpWeaken_rect :=\n  ExpTyping_str_rect \n                     FunWeaken QFunWeaken \n                     ExpWeaken PrmsWeaken. \n\nLemma weakenTyping \n           (ftenv: funTC) (tenv: valTC) (fenv: funEnv) \n           (e: Exp) (t: VTyp):\n   ExpTyping ftenv tenv fenv e t ->\n   MatchEnvsT FunTyping fenv ftenv ->\n   forall (ftenv': funTC) (tenv': valTC) (fenv': funEnv),\n       MatchEnvsT FunTyping fenv' ftenv' -> \n       ExpTyping (ftenv ++ ftenv') (tenv ++ tenv') (fenv ++ fenv') e t.\nProof.\n  eapply ExpWeaken_rect.\n  - unfold Par_SSL, ExpWeaken.\n    intros.\n    constructor.\n  - unfold Par_SSL, ExpWeaken.\n    intros.\n    constructor.\n    auto.\n    auto.\n    auto.\n  - unfold Par_SSA.\n    constructor.\n  - unfold Par_SSA.\n    econstructor.\n    eauto.\n    auto.\n  - unfold Par_SSB, Par_SSA.\n    intros.    \n    econstructor.\n    exact m0.\n    exact m1. \n    auto.\n    auto.\n    auto.\n    auto.\n    eauto.\n  - unfold ExpWeaken, FunWeaken.\n    intros.\n    constructor.    \n  - unfold ExpWeaken, FunWeaken.\n    intros.\n    constructor.\n  - unfold QFunWeaken, FunWeaken.\n    intros.\n    constructor.\n    auto.\n  - unfold QFunWeaken, FunWeaken, Par_SSB, Par_SSA.\n    intros.\n    econstructor.\n    instantiate (1:=f).\n    inversion m; subst.\n    rewrite <- app_assoc.\n    rewrite <- app_assoc.\n    rewrite <- app_comm_cons.\n    rewrite <- app_comm_cons.\n    econstructor.\n    assumption.    \n    exact X3.\n    eapply appEnvLemmaT.\n    exact X4.\n    exact X1.\n    assumption.\n    reflexivity.\n    reflexivity.\n  - unfold ExpWeaken.\n    intros.\n    constructor.\n    inversion k; subst.\n    constructor.\n    auto.\n    constructor.\n    inversion X1; subst.\n    constructor.\n    constructor.\n    inversion X2; subst.\n    rewrite (override_simpl1 tenv0 tenv' x (vtyp T1)).\n    exact H.\n    exact H.\n  - unfold ExpWeaken.\n    intros.\n    constructor.\n    inversion k; subst.\n    constructor.\n    auto.    \n    constructor.\n    inversion X1; subst.\n    constructor.\n    constructor.\n    inversion X2; subst.\n    rewrite (override_simpl1 tenv0 tenv' x t0).\n    exact H.\n    exact H.\n\n  - unfold ExpWeaken.\n    intros.\n    specialize (X X1 ftenv' tenv' fenv' X2). \n    specialize (X0 X1 ftenv' tenv' fenv' X2). \n    econstructor.\n    exact X.\n    exact X0.\n  - unfold ExpWeaken.\n    intros.\n    specialize (X X1 ftenv' tenv' fenv' X2). \n    econstructor.     \n    exact X.\n    eapply X0.\n    exact X1.\n    exact X2.    \n  - unfold ExpWeaken.\n    intros.\n    econstructor.\n    exact k1.\n    eapply overrideEnvLemmaT.\n    exact X0.\n    exact X1.\n    exact m2.\n    reflexivity.\n    reflexivity.\n    reflexivity.    \n    assert (MatchEnvsT FunTyping (fenvP ++ fenv0) (ftenvP ++ ftenv0)).\n    eapply overrideEnvLemmaT.\n    exact m2.    \n    exact m1.\n    rewrite h1 in X.\n    rewrite h2 in X.\n    rewrite h3 in X.\n    \n    specialize (X X2 ftenv'0 tenv'0 fenv'0 X1).\n    repeat rewrite app_assoc. \n    auto.\n  - unfold ExpWeaken, QFunWeaken, PrmsWeaken.\n    intros.\n    econstructor.\n    reflexivity.\n    \n    eapply overrideEnvLemmaT.\n    assumption.    \n    assumption.\n    eapply X.    \n    assumption.\n    assumption.\n    rewrite h in X0.\n    eapply X0.\n    assumption.\n    assumption.\n  - unfold ExpWeaken.\n    intros.\n    constructor.  \n    assumption.\n  - unfold ExpWeaken.\n    intros.\n    constructor.\n    eapply X.\n    assumption.\n    assumption.\n    eapply X0.\n    assumption.    \n    assumption.\n    eapply X1.\n    assumption.    \n    assumption.\n  - unfold Par_SSL, PrmsWeaken, ExpWeaken.\n    intros.\n    constructor.\n    induction X.\n    constructor.\n    constructor. \n    eapply p0.    \n    assumption.\n    assumption.\n    eapply IHX.\n    inversion m; subst.\n    exact X3.\nDefined.\n\n\nDefinition PrmsWeaken_rect :=\n  PrmsTyping_str_rect \n                     FunWeaken QFunWeaken \n                     ExpWeaken PrmsWeaken. \n\n\nLemma weakenPrmsTyping \n           (ftenv: funTC) (tenv: valTC) (fenv: funEnv) \n           (ps: Prms) (pt: PTyp):\n   PrmsTyping ftenv tenv fenv ps pt ->\n   MatchEnvsT FunTyping fenv ftenv ->\n   forall (ftenv': funTC) (tenv': valTC) (fenv': funEnv),\n       MatchEnvsT FunTyping fenv' ftenv' -> \n       PrmsTyping (ftenv ++ ftenv') (tenv ++ tenv') (fenv ++ fenv') ps pt.\nProof.\n  eapply PrmsWeaken_rect.\n  - unfold Par_SSL, ExpWeaken.\n    intros.\n    constructor.\n  - unfold Par_SSL, ExpWeaken.\n    intros.\n    constructor.\n    auto.\n    auto.\n    auto.\n  - unfold Par_SSA.\n    constructor.\n  - unfold Par_SSA.\n    econstructor.\n    eauto.\n    auto.\n  - unfold Par_SSB, Par_SSA.\n    intros.    \n    econstructor.\n    exact m0.\n    exact m1. \n    auto.\n    auto.\n    auto.\n    auto.\n    eauto.\n  - unfold ExpWeaken, FunWeaken.\n    intros.\n    constructor.    \n  - unfold ExpWeaken, FunWeaken.\n    intros.\n    constructor.\n  - unfold QFunWeaken, FunWeaken.\n    intros.\n    constructor.\n    auto.\n  - unfold QFunWeaken, FunWeaken, Par_SSB, Par_SSA.\n    intros.\n    econstructor.\n    instantiate (1:=f).\n    inversion m; subst.\n    rewrite <- app_assoc.\n    rewrite <- app_assoc.\n    rewrite <- app_comm_cons.\n    rewrite <- app_comm_cons.\n    econstructor.\n    assumption.    \n    exact X3.\n    eapply appEnvLemmaT.\n    exact X4.\n    exact X1.\n    assumption.\n    reflexivity.\n    reflexivity.\n  - unfold ExpWeaken.\n    intros.\n    constructor.\n    inversion k; subst.\n    constructor.\n    auto.\n    constructor.\n    inversion X1; subst.\n    constructor.\n    constructor.\n    inversion X2; subst.\n    rewrite (override_simpl1 tenv0 tenv' x (vtyp T1)).\n    exact H.\n    exact H.\n  - unfold ExpWeaken.\n    intros.\n    constructor.\n    inversion k; subst.\n    constructor.\n    auto.    \n    constructor.\n    inversion X1; subst.\n    constructor.\n    constructor.\n    inversion X2; subst.\n    rewrite (override_simpl1 tenv0 tenv' x t).\n    exact H.\n    exact H.\n\n  - unfold ExpWeaken.\n    intros.\n    specialize (X X1 ftenv' tenv' fenv' X2). \n    specialize (X0 X1 ftenv' tenv' fenv' X2). \n    econstructor.\n    exact X.\n    exact X0.\n  - unfold ExpWeaken.\n    intros.\n    specialize (X X1 ftenv' tenv' fenv' X2). \n    econstructor.     \n    exact X.\n    eapply X0.\n    exact X1.\n    exact X2.    \n  - unfold ExpWeaken.\n    intros.\n    econstructor.\n    exact k1.\n    eapply overrideEnvLemmaT.\n    exact X0.\n    exact X1.\n    exact m2.\n    reflexivity.\n    reflexivity.\n    reflexivity.    \n    assert (MatchEnvsT FunTyping (fenvP ++ fenv0) (ftenvP ++ ftenv0)).\n    eapply overrideEnvLemmaT.\n    exact m2.    \n    exact m1.\n    rewrite h1 in X.\n    rewrite h2 in X.\n    rewrite h3 in X.\n    \n    specialize (X X2 ftenv'0 tenv'0 fenv'0 X1).\n    repeat rewrite app_assoc. \n    auto.\n  - unfold ExpWeaken, QFunWeaken, PrmsWeaken.\n    intros.\n    econstructor.\n    reflexivity.\n    \n    eapply overrideEnvLemmaT.\n    assumption.    \n    assumption.\n    eapply X.    \n    assumption.\n    assumption.\n    rewrite h in X0.\n    eapply X0.\n    assumption.\n    assumption.\n  - unfold ExpWeaken.\n    intros.\n    constructor.  \n    assumption.\n  - unfold ExpWeaken.\n    intros.\n    constructor.\n    eapply X.\n    assumption.\n    assumption.\n    eapply X0.\n    assumption.    \n    assumption.\n    eapply X1.\n    assumption.    \n    assumption.\n  - unfold Par_SSL, PrmsWeaken, ExpWeaken.\n    intros.\n    constructor.\n    induction X.\n    constructor.\n    constructor. \n    eapply p0.    \n    assumption.\n    assumption.\n    eapply IHX.\n    inversion m; subst.\n    exact X3.\nDefined.\n\n\nEnd Weaken.\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/DEC1/WeakenA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.27250944012291983}}
{"text": "\nRequire Import Coq.Program.Basics.\nRequire Import Coq.Lists.List.\nImport ListNotations.\nRequire Import Coq.Sorting.Permutation.\n\nRequire Import GenericTactics.\nRequire Import GenericLemmas.\nRequire Import Names.\nRequire Import AST.\nRequire Import BodyTypeDefs.\nRequire Import Skeleton.\nRequire Import ProgramDef.\nRequire Import Unique.\nRequire Import Sublist.\nRequire Import Subterm.\nRequire Import Typechecker.\nRequire Import Permutations.\n\nRequire Import InlineComatch.\nRequire Import LiftComatch.\n\nFixpoint extract_local_gfuns_expr (e : expr) : list QName :=\n  match e with\n  | E_Var x => []\n  | E_Constr _ args => concat (map extract_local_gfuns_expr args)\n  | E_DestrCall _ e args => (extract_local_gfuns_expr e) ++ (concat (map extract_local_gfuns_expr args))\n  | E_FunCall _ args => concat (map extract_local_gfuns_expr args)\n  | E_GenFunCall _ args => concat (map extract_local_gfuns_expr args)\n  | E_ConsFunCall _ e args => (extract_local_gfuns_expr e) ++ (concat (map extract_local_gfuns_expr args))\n  | E_Match qn e bs cases rtype =>\n    (extract_local_gfuns_expr e)\n      ++ (concat (map (fun exp_typ => extract_local_gfuns_expr (fst exp_typ)) bs))\n      ++ (concat (map (fun sn_exp => extract_local_gfuns_expr (snd sn_exp)) cases))\n  | E_CoMatch qn bs cocases =>\n    (concat (map (fun exp_typ => extract_local_gfuns_expr (fst exp_typ)) bs))\n      ++ (concat (map (fun sn_exp => extract_local_gfuns_expr (snd sn_exp)) cocases))\n  | E_Let e1 e2 => (extract_local_gfuns_expr e1) ++ (extract_local_gfuns_expr e2)\n  end.\n\nDefinition extract_local_gfuns_program (p : program) : list QName :=\n  (flat_map extract_local_gfuns_expr (map snd (program_fun_bods p)))\n  ++ (flat_map extract_local_gfuns_expr (map snd (flat_map snd (program_gfun_bods_g p))))\n  ++ (flat_map extract_local_gfuns_expr (map snd (flat_map snd (program_gfun_bods_g p)))).\n\nFixpoint extract_gfuns_depth_one (cs: gfun_bods) (qn : QName) : list QName :=\n  match cs with\n  | [] => []\n  | ((qn',e) :: cs') =>\n    if eq_QName qn qn'\n    then flat_map (fun x => extract_local_gfuns_expr (snd x)) e\n    else extract_gfuns_depth_one cs' qn\n  end.\n\nFixpoint extract_gfuns_by_depth (fuel : nat) (cs : gfun_bods) (qns: list QName) : list QName :=\n  match fuel with\n  | 0 => []\n  | S n => let new_qns := map (extract_gfuns_depth_one cs) qns in\n          let new_cs  := filter (fun bod => negb (existsb (eq_QName (fst bod)) (concat new_qns))) cs in\n          let new_rec := map (extract_gfuns_by_depth n new_cs) new_qns in\n          concat (zipWith cons qns new_rec)\n  end.\n\nDefinition sort_gfuns_for_inline (p : program) (cs: gfun_bods) : gfun_bods :=\n  let qns := extract_local_gfuns_program p in\n  let fuel := length cs in\n  sort_by_index_list (fun qn bod => eq_QName qn (fst bod))  (extract_gfuns_by_depth fuel cs qns) cs.\n\nLemma extract_gfuns_depth_one_unique: forall (cs : gfun_bods) (qn : QName),\n    unique (flat_map extract_local_gfuns_expr (map snd (flat_map snd cs))) ->\n    unique (extract_gfuns_depth_one cs qn).\nProof.\n  intros cs qn H_uniq.\n  induction cs; simpl; auto.\n  destruct a as [qn_a e_a]; simpl in *.\n  rewrite map_app in H_uniq;\n    rewrite flat_map_app in H_uniq;\n    unique_app_destr_tac.\n  match_destruct_tac; auto.\n  clear - H_uniq0.\n  rewrite flat_map_concat_map in *.\n  rewrite map_compose in H_uniq0; auto.\nQed.\n\n\nLemma extract_gfuns_by_depth_permutes: forall p : program,\n    \n    unique ((flat_map extract_local_gfuns_expr (map snd (flat_map snd (program_gfun_bods_l p))))\n              ++ (extract_local_gfuns_program p)) ->\n    Permutation (extract_gfuns_by_depth (length (program_gfun_bods_l p)) (program_gfun_bods_l p) (extract_local_gfuns_program p)) (map fst (program_gfun_bods_l p)).\nProof.\n  intros p H_uniq.\n  generalize dependent (extract_local_gfuns_program p).\n  intro orig_qns; intros.\n  pose proof (skeleton_gfun_sigs_names_unique_l (program_skeleton p)) as H_uniq_gfuns;\n    pose proof (program_has_all_gfun_bods_l p);\n    unfold gfun_sigs_names_unique in H_uniq_gfuns; unfold has_all_gfun_bods in H;\n      rewrite H in H_uniq_gfuns; clear H.\n  unfold extract_gfuns_by_depth in *; simpl.\n\n  induction (program_gfun_bods_l p) as [| bod bods]; auto.\n  simpl in H_uniq_gfuns.\n  inversion_clear H_uniq_gfuns as [| _x _xx H_nin H_uniq_bod].\nAdmitted. (* check Results.v for details on missing proofs *)\n    \nLemma sort_gfuns_for_inline_permutes': forall (p : program),\n    unique (flat_map extract_local_gfuns_expr (map snd (flat_map snd (program_gfun_bods_l p))) ++ extract_local_gfuns_program p) ->\n    Permutation (program_gfun_bods_l p) (sort_gfuns_for_inline p (program_gfun_bods_l p)).\nProof.\n  intros p H.\n  unfold sort_gfuns_for_inline.\n  apply sort_by_index_list_permutes.\n  exists fst.\n  split; [ | symmetry; apply eq_QName_eq].\n  apply extract_gfuns_by_depth_permutes; easy.\nQed.\n\nLemma sort_gfuns_for_inline_permutes: forall (p : program),\n    Permutation (program_gfun_bods_l p) (sort_gfuns_for_inline p (program_gfun_bods_l p)).\nProof.\nAdmitted. (* check Results.v for details on missing proofs *)\n\nDefinition new_gfun_sigs_l (s : skeleton) (qns: list QName) :=\n  sort_by_index_list (fun qn sig => eq_QName qn (fst sig)) qns (skeleton_gfun_sigs_l s).\n\nLemma new_gfun_sigs_in_cdts_l: forall (s : skeleton) (qns : list QName)\n                                (H: Permutation qns (map fst (skeleton_gfun_sigs_l s))),\n    gfun_sigs_in_cdts (skeleton_cdts s) (new_gfun_sigs_l s qns).\nProof.\n  intros s qns H.\n  unfold gfun_sigs_in_cdts.\n  unfold new_gfun_sigs_l.\n  eapply Permutation_Forall;\n  [ | pose proof (skeleton_gfun_sigs_in_cdts_l s); unfold gfun_sigs_in_cdts in H0; eauto].\n  apply sort_by_index_list_permutes.\n  exists fst; split; auto.\n  clear; intros a b.\n  split; apply eq_QName_eq; auto.\nQed.\n\nLemma new_gfun_sigs_names_unique_l: forall (s : skeleton) (qns : list QName)\n                                (H: Permutation qns (map fst (skeleton_gfun_sigs_l s))),\n    gfun_sigs_names_unique (new_gfun_sigs_l s qns).\nProof.\n  intros s qns H.\n  pose proof (skeleton_gfun_sigs_names_unique_l s).\n  unfold gfun_sigs_names_unique in *.\n  unfold new_gfun_sigs_l.\n  eapply Permutation_unique; [| eassumption].\n  apply Permutation_map.\n  apply sort_by_index_list_permutes.\n  exists fst; split; auto.\n  clear; intros a b.\n  split; apply eq_QName_eq.\nQed.\n\nDefinition sort_gfuns_for_inline_skeleton (s : skeleton) (qns: list QName)\n           (H: Permutation qns (map fst (skeleton_gfun_sigs_l s)))\n            : skeleton :=\n  let gfun_sigs := new_gfun_sigs_l s qns in\n  {|\n    skeleton_dts := skeleton_dts s;\n    skeleton_ctors := skeleton_ctors s;\n    skeleton_dts_ctors_in_dts := skeleton_dts_ctors_in_dts s;\n    skeleton_dts_ctor_names_unique := skeleton_dts_ctor_names_unique s;\n    skeleton_cdts := skeleton_cdts s;\n    skeleton_dtors := skeleton_dtors s;\n    skeleton_cdts_dtors_in_cdts := skeleton_cdts_dtors_in_cdts s;\n    skeleton_cdts_dtor_names_unique := skeleton_cdts_dtor_names_unique s;\n    skeleton_dts_cdts_disjoint := skeleton_dts_cdts_disjoint s;\n    skeleton_fun_sigs := skeleton_fun_sigs s;\n    skeleton_fun_sigs_names_unique := skeleton_fun_sigs_names_unique s;\n    skeleton_cfun_sigs_g := skeleton_cfun_sigs_g s;\n    skeleton_cfun_sigs_in_dts_g := skeleton_cfun_sigs_in_dts_g s;\n    skeleton_cfun_sigs_names_unique_g := skeleton_cfun_sigs_names_unique_g s;\n    skeleton_cfun_sigs_l := skeleton_cfun_sigs_l s;\n    skeleton_cfun_sigs_in_dts_l := skeleton_cfun_sigs_in_dts_l s;\n    skeleton_cfun_sigs_names_unique_l := skeleton_cfun_sigs_names_unique_l s;\n    skeleton_gfun_sigs_g := skeleton_gfun_sigs_g s;\n    skeleton_gfun_sigs_in_cdts_g := skeleton_gfun_sigs_in_cdts_g s;\n    skeleton_gfun_sigs_names_unique_g := skeleton_gfun_sigs_names_unique_g s;\n    skeleton_gfun_sigs_l := gfun_sigs;\n    skeleton_gfun_sigs_in_cdts_l := new_gfun_sigs_in_cdts_l s qns H;\n    skeleton_gfun_sigs_names_unique_l := new_gfun_sigs_names_unique_l s qns H;\n  |}.\n\nDefinition sort_gfuns_for_inline_bods (p : program) : gfun_bods :=\n  sort_gfuns_for_inline p (program_gfun_bods_l p).\n\nLemma sorted_gfuns_permutation_of_original_sigs: forall (p : program),\n    Permutation (map fst (sort_gfuns_for_inline_bods p))\n                (map fst (skeleton_gfun_sigs_l (program_skeleton p))).\nProof.\n  intros p.\n  unfold sort_gfuns_for_inline_bods.\n  pose proof (sort_gfuns_for_inline_permutes p).\n  apply (Permutation_map fst) in H.\n  apply Permutation_sym in H.\n  eapply (perm_trans); [ eassumption | ].\n  pose proof (program_has_all_gfun_bods_l p).\n  unfold has_all_gfun_bods in H0; rewrite H0; auto.\nQed.\n\nLemma sort_gfuns_for_inline_bods_Permutation_with_gfun_bods: forall (p : program),\n    Permutation (program_gfun_bods_l p) (sort_gfuns_for_inline_bods p).\nProof.\n  intros p.\n  unfold sort_gfuns_for_inline_bods.\n  apply sort_gfuns_for_inline_permutes.\nQed.\n\nDefinition new_skeleton (p : program) :=\n  let sorted := sort_gfuns_for_inline_bods p in\n  sort_gfuns_for_inline_skeleton (program_skeleton p) (map fst sorted) (sorted_gfuns_permutation_of_original_sigs p).\n\nLemma new_skeleton_tc:\n  forall (p : program) (e : expr) (ctxt : list TypeName) (t : TypeName),\n    (program_skeleton p / ctxt |- e : t) ->\n    new_skeleton p / ctxt |- e : t.\nProof.\n  intros p e ctxt t H.\n  unfold new_skeleton.\n  gen_dep (ctxt, t);\n    induction e using expr_strong_ind; intros;\n      match goal with\n      | [ H: _ / _ |- _ : _ |- _ ] =>\n        inversion_clear H\n      end.\n  - apply T_Var; auto.\n  - eapply T_Constr; eauto.\n    clear H1.\n    gen_induction cargs ls.\n    + inversion_clear H2.\n      apply ListTypeDeriv_Nil.\n    + destruct cargs; inversion_clear H2.\n      inversion_clear H.\n      apply ListTypeDeriv_Cons; auto.\n  - eapply T_DestrCall; eauto.\n    clear H1.\n    gen_induction dargs ls; destruct dargs; inversion_clear H3; try apply ListTypeDeriv_Nil.\n    inversion_clear H.\n    apply ListTypeDeriv_Cons; auto.\n  - eapply T_FunCall; eauto.\n    clear H1.\n    gen_induction argts ls; destruct argts; inversion_clear H2; try apply ListTypeDeriv_Nil.\n    inversion_clear H.\n    apply ListTypeDeriv_Cons; auto.\n  - eapply T_GlobalConsFunCall; eauto.\n    clear H1.\n    gen_induction argts ls; destruct argts; inversion_clear H3; try apply ListTypeDeriv_Nil.\n    inversion_clear H.\n    apply ListTypeDeriv_Cons; auto.\n  - eapply T_LocalConsFunCall; eauto.\n    clear H1.\n    gen_induction argts ls; destruct argts; inversion_clear H3; try apply ListTypeDeriv_Nil.\n    inversion_clear H.\n    apply ListTypeDeriv_Cons; auto.\n  - eapply T_GlobalGenFunCall; eauto.\n    clear H1.\n    gen_induction argts ls; destruct argts; inversion_clear H2; try apply ListTypeDeriv_Nil.\n    inversion_clear H.\n    apply ListTypeDeriv_Cons; auto.\n  - eapply T_LocalGenFunCall; eauto.\n    + match goal with\n      | [ H: In _ ?ls |- In _ ?ls'] =>\n        eapply Permutation_in; [ | eassumption ]\n      end.\n      unfold sort_gfuns_for_inline_skeleton; simpl.\n      unfold new_gfun_sigs_l.\n      apply sort_by_index_list_permutes.\n      exists fst; split; [ | intros; split; apply eq_QName_eq ].\n      apply sorted_gfuns_permutation_of_original_sigs.\n    + clear H1.\n    gen_induction argts ls; destruct argts; inversion_clear H2; try apply ListTypeDeriv_Nil.\n    inversion_clear H.\n    apply ListTypeDeriv_Cons; auto.\n  - eapply T_Match; eauto.\n    + subst. clear - H4 H0.\n      gen_induction bindings_types bindings_exprs; destruct bindings_types; inversion_clear H4; try apply ListTypeDeriv_Nil.\n      simpl in H0; inversion_clear H0.\n      apply ListTypeDeriv_Cons; auto.\n    + clear - H7 H.\n      gen_induction ctorlist ls; destruct ctorlist; inversion_clear H7; try apply ListTypeDeriv'_Nil.\n      inversion_clear H; simpl.\n      apply ListTypeDeriv'_Cons; auto.\n  - eapply T_CoMatch; eauto.\n    + subst. clear - H3 H0.\n      gen_induction bindings_types bindings_exprs; destruct bindings_types; inversion_clear H3; try apply ListTypeDeriv_Nil.\n      simpl in H0; inversion_clear H0.\n      apply ListTypeDeriv_Cons; auto.\n    + clear - H6 H.\n      gen_induction dtorlist ls; destruct dtorlist; inversion_clear H6; try apply ListTypeDeriv'_Nil.\n      inversion_clear H; simpl.\n      apply ListTypeDeriv'_Cons; auto.\n  - eapply T_Let; eauto.\nQed.\n\nLemma new_program_fun_bods_tc: forall (p : program),\n    fun_bods_typecheck (new_skeleton p) (program_fun_bods p).\nProof.\n  intros p.\n  pose proof (program_fun_bods_typecheck p).\n  unfold fun_bods_typecheck in *.\n  match goal with\n  | [ H: Forall ?P1 ?ls |- Forall ?P2 ?ls ] =>\n    apply (@Forall_impl _ P1); auto\n  end.\n  clear; intros a H.\n  repeat match goal with\n         | [ H: exists _, _ |- _ ] =>\n           inversion_clear H\n         end.\n  inversion_clear H0.\n  repeat eexists; eauto.\n  apply new_skeleton_tc; assumption.\nQed.\n\nLemma new_program_cfun_bods_g_tc: forall (p : program),\n    cfun_bods_g_typecheck (new_skeleton p) (program_cfun_bods_g p).\nProof.\n  intros p.\n  pose proof (program_cfun_bods_typecheck_g p).\n  unfold cfun_bods_g_typecheck in *.\n  match goal with\n  | [ H: Forall ?P1 ?ls |- Forall ?P2 ?ls ] =>\n    apply (@Forall_impl _ P1); auto\n  end.\n  clear; intros a H.\n  repeat match goal with\n         | [ H: exists _, _ |- _ ] =>\n           inversion_clear H\n         end.\n  inversion_clear H0.\n  repeat eexists; eauto.\n  apply new_skeleton_tc; assumption.\nQed.\n\nLemma new_program_cfun_bods_l_tc: forall (p : program),\n    cfun_bods_l_typecheck (new_skeleton p) (program_cfun_bods_l p).\nProof.\n  intros p.\n  pose proof (program_cfun_bods_typecheck_l p).\n  unfold cfun_bods_l_typecheck in *.\n  match goal with\n  | [ H: Forall ?P1 ?ls |- Forall ?P2 ?ls ] =>\n    apply (@Forall_impl _ P1); auto\n  end.\n  clear; intros a H.\n  repeat match goal with\n         | [ H: exists _, _ |- _ ] =>\n           inversion_clear H\n         end.\n  inversion_clear H0.\n  repeat eexists; eauto.\n  apply new_skeleton_tc; assumption.\nQed.\n\nLemma new_program_gfun_bods_g_tc: forall (p : program),\n    gfun_bods_g_typecheck (new_skeleton p) (program_gfun_bods_g p).\nProof.\n  intros p.\n  pose proof (program_gfun_bods_typecheck_g p).\n  unfold gfun_bods_g_typecheck in *.\n  match goal with\n  | [ H: Forall ?P1 ?ls |- Forall ?P2 ?ls ] =>\n    apply (@Forall_impl _ P1); auto\n  end.\n  clear; intros a H.\n  repeat match goal with\n         | [ H: exists _, _ |- _ ] =>\n           inversion_clear H\n         end.\n  inversion_clear H.\n  repeat eexists; eauto.\n  apply new_skeleton_tc; assumption.\nQed.\n\nLemma new_program_gfun_bods_l_tc: forall (p : program),\n    gfun_bods_l_typecheck (new_skeleton p) (sort_gfuns_for_inline_bods p).\nProof.\n  intros p.\n  pose proof (program_gfun_bods_typecheck_l p).\n  unfold gfun_bods_l_typecheck in *.\n  match goal with\n  | [ H: Forall ?P1 _ |- Forall ?P2 _ ] =>\n    apply (@Forall_impl _ P1); auto\n  end.\n  - clear; intros a H.\n    repeat match goal with\n           | [ H: exists _, _ |- _ ] =>\n             inversion_clear H\n           end.\n    inversion_clear H.\n    repeat eexists; eauto;\n      [ | apply new_skeleton_tc; eassumption].\n    unfold new_skeleton.\n    pose proof UtilsSkeleton.lookup_gfun_sig_name_correct_l as E.\n    specialize (E _ _ _ H0); simpl in *; subst.\n    unfold sort_gfuns_for_inline_skeleton; simpl;\n    unfold UtilsSkeleton.lookup_gfun_sig_l in *;\n    unfold UtilsSkeleton.lookup_gfun_sig_x in *; simpl.\n    pose proof (skeleton_gfun_sigs_names_unique_l (program_skeleton p)) as H;\n      unfold gfun_sigs_names_unique in H.\n    match goal with\n    | [ H: find _ ?l' = Some ?sig |- find _ ?l = Some _ ] => \n      eapply (unique_sig_lookup l sig)\n    end.\n    + apply find_in in H0.\n      unfold new_gfun_sigs_l.\n      eapply Permutation_in; [ | eassumption].\n      apply sort_by_index_list_permutes.\n      exists fst; split;\n        [ | clear; intros; split; apply eq_QName_eq ].\n      apply sorted_gfuns_permutation_of_original_sigs.\n    + match goal with\n      | [ H: unique ?ls |- _ ] =>\n        apply (Permutation_unique ls); auto\n      end.\n      apply Permutation_map.\n      unfold new_gfun_sigs_l.\n      apply sort_by_index_list_permutes.\n      exists fst; split;\n        [ | clear; intros; split; apply eq_QName_eq ].\n      apply sorted_gfuns_permutation_of_original_sigs.\n  - match goal with\n    | [ H: Forall ?P ?ls |- Forall ?P ?ls' ] =>\n      apply (Permutation_Forall P ls); auto\n    end.\n    apply  sort_gfuns_for_inline_bods_Permutation_with_gfun_bods.\nQed.\n\nLemma new_program_has_all_gfun_bods_l: forall (p : program),\n    has_all_gfun_bods (skeleton_gfun_sigs_l (new_skeleton p)) (sort_gfuns_for_inline_bods p).\nProof.\n  intros p.\n  pose proof (program_has_all_gfun_bods_l p).\n  unfold has_all_gfun_bods in *.\n  unfold new_skeleton.\n  unfold sort_gfuns_for_inline_skeleton; simpl.\n  unfold new_gfun_sigs_l.\n  pose proof (skeleton_gfun_sigs_names_unique_l (program_skeleton p)).\n  unfold gfun_sigs_names_unique in H0.\n  rewrite H in H0.\n  match goal with\n  | [  |- context [sort_by_index_list ?f ?index ?to_sort] ] => \n    apply (sort_by_index_list_sorted_like_index f index to_sort)\n  end;\n   [ unfold sort_gfuns_for_inline_bods;\n    match goal with\n    | [ H: unique ?ls |- _ ] =>\n      apply (Permutation_unique ls); auto\n    end;\n    apply Permutation_map;\n    apply sort_gfuns_for_inline_permutes\n    | apply sorted_gfuns_permutation_of_original_sigs\n    | intros; split; apply eq_QName_eq ].\nQed.\n\nLemma new_program_match_names_unique: forall (p : program),\n    match_names_unique (program_fun_bods p)\n                       (program_cfun_bods_g p ++ program_cfun_bods_l p)\n                       (program_gfun_bods_g p ++ (sort_gfuns_for_inline_bods p)).\nProof.\n  intros p.\n  pose proof (program_match_names_unique p).\n  unfold match_names_unique in *.\n  repeat (repeat rewrite map_app in *; rewrite concat_app in * ).\n  match goal with\n  | [ H: unique ?ls |- unique ?ls' ] =>\n    apply (Permutation_unique ls); eauto\n  end.\n  repeat apply Permutation_app; auto.\n  repeat (repeat apply Permutation_concat; apply Permutation_map).\n  apply sort_gfuns_for_inline_bods_Permutation_with_gfun_bods.\nQed.\n\nLemma new_program_comatch_names_unique: forall (p : program),\n    comatch_names_unique (program_fun_bods p)\n                         (program_cfun_bods_g p ++ program_cfun_bods_l p)\n                         (program_gfun_bods_g p ++ (sort_gfuns_for_inline_bods p)).\nProof.\n  intros p.\n  pose proof (program_comatch_names_unique p).\n  unfold comatch_names_unique in *.\n  repeat (repeat rewrite map_app in *; rewrite concat_app in * ).\n  match goal with\n  | [ H: unique ?ls |- unique ?ls' ] =>\n    apply (Permutation_unique ls); eauto\n  end.\n  repeat apply Permutation_app; auto.\n  repeat (repeat apply Permutation_concat; apply Permutation_map).\n  apply sort_gfuns_for_inline_bods_Permutation_with_gfun_bods.\nQed.\n\nDefinition sort_gfuns_for_inline_program (p : program) : program :=\n  let sorted := sort_gfuns_for_inline_bods p in\n  let new_skel := new_skeleton p in\n  {|\n    program_skeleton := new_skel;\n    program_fun_bods := program_fun_bods p;\n    program_has_all_fun_bods := program_has_all_fun_bods p;\n    program_fun_bods_typecheck := new_program_fun_bods_tc p;\n    program_cfun_bods_g := program_cfun_bods_g p;\n    program_has_all_cfun_bods_g := program_has_all_cfun_bods_g p;\n    program_cfun_bods_typecheck_g := new_program_cfun_bods_g_tc p;\n    program_cfun_bods_l := program_cfun_bods_l p;\n    program_has_all_cfun_bods_l := program_has_all_cfun_bods_l p;\n    program_cfun_bods_typecheck_l := new_program_cfun_bods_l_tc p;\n    program_gfun_bods_g := program_gfun_bods_g p;\n    program_has_all_gfun_bods_g := program_has_all_gfun_bods_g p;\n    program_gfun_bods_typecheck_g := new_program_gfun_bods_g_tc p;\n    program_gfun_bods_l := sorted;\n    program_has_all_gfun_bods_l := new_program_has_all_gfun_bods_l p;\n    program_gfun_bods_typecheck_l := new_program_gfun_bods_l_tc p;\n    program_match_names_unique := new_program_match_names_unique p;\n    program_comatch_names_unique := new_program_comatch_names_unique p;\n  |}.\n\nLemma contains_at_most_list_Permutation: forall (qn : QName) (ls ls' : list expr),\n    Permutation ls ls' ->\n    contains_at_most_one_local_gfun_call_list qn ls ->\n    contains_at_most_one_local_gfun_call_list qn ls'.\nProof.\n  intros qn ls ls' H_per H_most.\n  inversion_clear H_most as [H_no|H_one]; [ left; eapply Permutation_Forall; eauto | right ].\n  induction H_per; auto.\n  - inversion_clear H_one.\n    + apply contains_one_local_gfun_call_list_here; auto.\n      eapply Permutation_Forall; eauto.\n    + apply contains_one_local_gfun_call_list_there; auto.\n  - repeat match goal with\n           | [ H: contains_one_local_gfun_call_list _ (_ :: _) |- _ ] =>\n             inversion_clear H\n           end;\n      repeat match goal with\n             | [ H: Forall _ (_ :: _) |- _ ] =>\n               inversion_clear H\n             end.\n    + apply contains_one_local_gfun_call_list_there; auto.\n      apply contains_one_local_gfun_call_list_here; auto.\n    + apply contains_one_local_gfun_call_list_here; auto.\n    + repeat apply contains_one_local_gfun_call_list_there; auto.\nQed.\n\nLemma sort_gfuns_for_inline_preserves_local_gfuns_only_used_once: forall (p : program),\n    local_gfuns_only_used_once p ->\n    local_gfuns_only_used_once (sort_gfuns_for_inline_program p).\nProof.\n  intros p H.\n  unfold local_gfuns_only_used_once in *.\n  unfold sort_gfuns_for_inline_program in *; simpl.\n  unfold new_gfun_sigs_l.\n  match goal with\n  | [ H: Forall ?P1 _ |- Forall ?P2 ?ls ] =>\n    apply (@Forall_impl _ P1)\n  end.\n  - intro qn.\n    apply contains_at_most_list_Permutation.\n    repeat apply Permutation_app; auto.\n    apply Permutation_map.\n    repeat rewrite flat_map_concat_map.\n    apply Permutation_concat.\n    apply Permutation_map.\n    apply sort_gfuns_for_inline_bods_Permutation_with_gfun_bods.\n  - match goal with\n    | [ H: Forall ?P ?ls |- Forall ?P ?ls' ] => \n      eapply (Permutation_Forall P); [ | eapply H]\n    end.\n    apply Permutation_map.\n    apply sort_by_index_list_permutes.\n    exists fst; split;\n      [ | clear; intros; split; apply eq_QName_eq].\n    apply sorted_gfuns_permutation_of_original_sigs.\nQed.\n\nLemma sort_gfuns_for_inline_ordered_gfun: forall (p : program),\n    local_gfuns_only_used_once p ->\n    inline_ordered_gfun (sort_gfuns_for_inline_bods p).\nProof.\n  intros p H.\n  unfold sort_gfuns_for_inline_bods.\n  unfold sort_gfuns_for_inline.\nAdmitted. (* check Results.v for details on missing proofs *)\n\nTheorem sort_gfuns_for_inline_program_ordered_gfun: forall (p : program),\n    local_gfuns_only_used_once p ->\n    inline_ordered_gfun (program_gfun_bods_l (sort_gfuns_for_inline_program p)).\nProof.\n  intros p H. simpl.\n  apply sort_gfuns_for_inline_ordered_gfun; assumption.\nQed.\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/InlineLiftComatch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030761371502, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2725094333220977}}
{"text": "Require Export Bedrock.Platform.Cito.StringMap Bedrock.Platform.Cito.StringMapFacts.\nRequire Export Bedrock.Platform.Cito.SyntaxExpr Bedrock.Platform.Facade.DFacade.\nRequire Import Bedrock.Platform.Facade.DFacadeFacts2.\nRequire Import Coq.Setoids.Setoid.\n\nAdd Parametric Morphism {av} : (@eval av)\n    with signature (StringMap.Equal ==> eq ==> eq)\n      as eval_Morphism.\nProof.\n  eauto using DFacadeFacts2.eval_Morphism.\nQed.\n\nLemma IL_weqb_refl : forall x,\n    IL.weqb x x = true.\nProof.\n  unfold IL.weqb.\n  intros; rewrite Word.weqb_true_iff; reflexivity.\nQed.\n\nLemma IL_weqb_sound : forall x y,\n    IL.weqb x y = true -> x = y.\nProof.\n  eauto using Word.weqb_sound.\nQed.\n\nAdd Parametric Morphism {av} {env} {prog} : (@Safe av env prog)\n    with signature (StringMap.Equal ==> iff)\n      as Safe_Morphism.\nProof.\n  eauto using DFacadeFacts2.Safe_Morphism.\nQed.\n\nAdd Parametric Morphism {av} {env} {prog} : (@RunsTo av env prog)\n    with signature (StringMap.Equal ==> StringMap.Equal ==> iff)\n      as RunsTo_Morphism.\nProof.\n  eauto using DFacadeFacts2.RunsTo_Morphism.\nQed.\n\nRequire Import GLabelMap GLabelMapFacts.\nRequire Import Program.Basics.\n\nAdd Parametric Morphism av\n  : (@RunsTo av)\n    with signature\n    (GLabelMap.Equal ==> eq ==> StringMap.Equal ==> StringMap.Equal ==> impl)\n      as Proper_RunsTo.\nProof.\n  unfold impl; intros.\n  revert y y1 y2 H0 H1 H.\n  induction H2; intros.\n  - econstructor; rewrite <- H0, <- H1; eauto.\n  - econstructor 2; eauto.\n    eapply IHRunsTo1; eauto.\n    reflexivity.\n    eapply IHRunsTo2; eauto.\n    reflexivity.\n  - econstructor 3; eauto.\n    unfold is_true, eval_bool.\n    setoid_rewrite <- H0; apply H.\n  - econstructor 4; eauto.\n    unfold is_false, eval_bool.\n    setoid_rewrite <- H0; apply H.\n  - econstructor 5; eauto.\n    unfold is_true, eval_bool.\n    setoid_rewrite <- H0; apply H.\n    eapply IHRunsTo1; eauto.\n    reflexivity.\n    eapply IHRunsTo2; eauto.\n    reflexivity.\n  - econstructor 6; eauto.\n    unfold is_false, eval_bool.\n    setoid_rewrite <- H1; apply H.\n    rewrite <- H1, <- H2; eauto.\n  - econstructor 7;\n    rewrite <- H2; eauto.\n    rewrite <- H1; symmetry; eauto.\n  - econstructor 8; eauto.\n    rewrite <- H8; eauto.\n    rewrite <- H6; eauto.\n    rewrite <- H6; eauto.\n    rewrite <- H7.\n    subst st'; subst st'0; rewrite <- H6; eauto.\n  - econstructor 9; eauto.\n    rewrite <- H9; eauto.\n    rewrite <- H7; eauto.\n    rewrite <- H7; eauto.\n    eapply IHRunsTo; eauto.\n    reflexivity.\n    reflexivity.\n    subst st'; subst st'0; subst output; rewrite <- H8.\n    rewrite <- H7; eauto.\nQed.\n\nAdd Parametric Morphism av\n  : (@Safe av)\n    with signature\n    (GLabelMap.Equal ==> eq ==> StringMap.Equal ==> impl)\n      as Proper_Safe.\nProof.\n  unfold impl; intros.\n  rewrite <- H0.\n  apply Safe_coind with (R := fun st ext => Safe x st ext); eauto.\n  - intros; inversion H2; subst; intuition.\n    eapply H4.\n    setoid_rewrite H; eauto.\n  - intros; inversion H2; subst; intuition.\n  - intros; inversion H2; try subst; intuition.\n    left; intuition eauto.\n    subst loop; subst loop1; subst loop2.\n    rewrite <- H4.\n    eapply H8.\n    rewrite H; eauto.\n  - intros; inversion H2; try subst; intuition.\n    eauto.\n  - intros; inversion H2; try subst; intuition.\n    + eexists; intuition eauto.\n      left; eexists; intuition eauto.\n      rewrite <- H; eauto.\n    + eexists; intuition eauto.\n      right; eexists; intuition eauto.\n      rewrite <- H; eauto.\n      eapply H12; eauto.\n      rewrite H; eauto.\n      eapply H12.\n      rewrite H; eauto.\nQed.\n\nAdd Parametric Morphism elt\n  : (@GLabelMapFacts.UWFacts.WFacts.P.update elt)\n    with signature\n    (GLabelMap.Equal ==> GLabelMap.Equal ==> GLabelMap.Equal)\n      as GLabelMapFacts_UWFacts_WFacts_P_update_morphism.\nProof.\n  apply GLabelMapFacts.UWFacts.WFacts.P.update_m.\nQed.\n\nLtac isDeterministicStmtConstructor stmt :=\n  match stmt with\n  | Skip => idtac\n  | Seq _ _ => idtac\n  | Assign _ _ => idtac\n  | _ => fail 1 \"This statement has multiple RunsTo and Safe constructors\"\n  end.\n\nLtac isSafelyInvertibleStmtConstructor stmt :=\n  match stmt with\n  | Skip => idtac\n  | Seq _ _ => idtac\n  | If _ _ _ => idtac\n  | Call _ _ _ => idtac\n  | Assign _ _ => idtac\n  | _ => fail 1 \"Not a safely invertible constructor\"\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/CertifiedExtraction/PureFacadeLemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.27245975144145085}}
{"text": "Set Implicit Arguments.\n\nRequire Import AutoSep.\n\nDefinition empty_vs : vals := fun _ => $0.\n\nDefinition has_extra_stack sp offset e_stack e_stack_real :=\n  ((sp ^+ $4) =*> $(e_stack) *\n   (sp ^+ $8 ^+ $(4 * offset)) =?> e_stack_real)%Sep.\n\nDefinition cptr_AlX G (p : W) (stn : settings) a : propX _ _ G :=\n  (ExX, \n   Cptr p #0 /\\\n   Al st : state, \n           AlX : settings * smem,\n                 a (stn, st) ---> #1 (stn, st))%PropX.\n\nRequire Import ADT.\n\nModule Make (Import E : ADT).\n\n  Require Import Semantics.\n  Module Import SemanticsMake := Semantics.Make E.\n\n  Fixpoint make_triples pairs (outs : list ArgOut) :=\n    match pairs, outs with\n      | p :: ps, o :: os => {| Word := fst p; ADTIn := snd p; ADTOut := o |} :: make_triples ps os\n      | _, _ => nil\n    end.\n\n  Definition store_pair heap (p : W * ArgIn) :=\n    match snd p with\n      | inl _ => heap\n      | inr a => heap_upd heap (fst p) a\n    end.\n\n  Definition make_heap pairs := fold_left store_pair pairs heap_empty.\n\n  Require Import RepInv.\n\n  Module Make (Import R : RepInv E).\n\n    Require Import Bags.\n\n    Definition is_heap (h : Heap) : HProp := starL (fun p => rep_inv (fst p) (snd p)) (heap_elements h).\n\n    Section TopSection.\n\n      Definition is_state sp rp e_stack e_stack_real vars (v : State) temps : HProp :=\n        (\n          locals vars (fst v) 0 (sp ^+ $8) *\n          array temps (sp ^+ $8 ^+ $(4 * length vars)) *\n          is_heap (snd v) *\n          sp =*> rp *\n          has_extra_stack sp (length vars + length temps) e_stack e_stack_real\n        )%Sep.\n\n      Require Import Malloc.\n      Require Import Basics.\n\n      Definition layout_option addr ret : HProp :=\n        match ret with\n          | None  => ([| True |])%Sep\n          | Some a => rep_inv addr a\n        end.\n\n      Definition word_scalar_match (p : W * ArgIn) :=\n        let word := fst p in\n        let in_ := snd p in\n        match in_ with\n          | inl w => word = w\n          | _ => True\n        end.\n\n      Definition good_scalars pairs := List.Forall word_scalar_match pairs.\n\n      Open Scope type.\n\n      Require Import ConvertLabel.\n      (* universe inconsistency *)\n      Set Printing Universes.\n      Definition internal_spec G fs spec st : propX _ _ (settings * smem :: G) :=\n        (Ex v, Ex rp, Ex e_stack,\n         ![^[is_state st#Sp rp e_stack e_stack (ArgVars spec) v nil * mallocHeap 0] * #0] st /\\\n         let stn := fst st in\n         let env := (from_bedrock_label_map (Labels stn), fs stn) in\n         [| Safe env (Body spec) v |] /\\\n         (st#Rp, stn) \n           @@@ (\n             st' ~> Ex v', Ex rp', \n             (* the callee needn't have the right extra stack size recorded in the end, but the extra stack should be there *)\n             Ex e_stack',\n             ![^[ is_state st'#Sp rp' e_stack' e_stack (ArgVars spec) v' nil * mallocHeap 0] * #1] st' /\\\n             [| exists vs', \n                RunsTo env (Body spec) v (vs', snd v') /\\ \n                st'#Rv = sel vs' (RetVar spec) /\\\n                st'#Sp = st#Sp |]))%PropX.\n\n      Definition foreign_spec G spec st : propX _ _ (settings * smem :: G) :=\n        (Ex pairs, Ex rp, Ex e_stack,\n         let heap := make_heap pairs in\n         ![^[is_state st#Sp rp e_stack e_stack nil (empty_vs, heap) (map fst pairs) * mallocHeap 0] * #0] st /\\\n         let stn := fst st in\n         [| disjoint_ptrs pairs /\\\n            good_scalars pairs /\\\n            PreCond spec (map snd pairs) |] /\\\n         (st#Rp, stn) \n           @@@ (\n             st' ~> Ex args', Ex addr, Ex ret, Ex rp', Ex outs,\n             let t := decide_ret addr ret in\n             let ret_w := fst t in\n             let ret_a := snd t in\n             let triples := make_triples pairs outs in\n             let heap := fold_left store_out triples heap in\n             (* the callee needn't have the right extra stack size recorded in the end, but the extra stack should be there *)\n             Ex vs, Ex e_stack',\n             ![^[is_state st#Sp rp' e_stack' e_stack nil (vs, heap) args' * layout_option ret_w ret_a * mallocHeap 0] * #1] st' /\\\n             [| length outs = length pairs /\\\n                PostCond spec (map (fun x => (ADTIn x, ADTOut x)) triples) ret /\\\n                length args' = length triples /\\\n                st'#Rv = ret_w /\\\n                st'#Sp = st#Sp |]))%PropX.\n\n      Definition funcs_ok stn (fs : settings -> W -> option Callee) : PropX W (settings * state) := \n        ((Al i, Al spec,\n          [| fs stn i = Some (Internal spec) |] \n            ---> cptr_AlX i stn (internal_spec _ fs spec)) /\\\n         (Al i, Al spec, \n          [| fs stn i = Some (Foreign spec) |] \n            ---> cptr_AlX i stn (foreign_spec _ spec)))%PropX.\n\n      Section vars.\n\n        Variable vars : list string.\n        \n        Variable temp_size : nat.\n\n        Definition inv_template rv_precond rv_postcond s : assert := \n          st ~> Ex fs, \n          let stn := fst st in\n          funcs_ok stn fs /\\\n          ExX, Ex v, Ex temps, Ex rp, Ex e_stack,\n          ![^[is_state st#Sp rp e_stack e_stack vars v temps * mallocHeap 0] * #0] st /\\\n          let env := (from_bedrock_label_map (Labels stn), fs stn) in\n          [| Safe env s v /\\\n             length temps = temp_size /\\\n             rv_precond st#Rv v |] /\\\n          (rp, stn) \n            @@@ (\n              st' ~> Ex v', Ex temps',\n              ![^[is_state st'#Sp rp e_stack e_stack vars v' temps' * mallocHeap 0] * #1] st' /\\\n              [| RunsTo env s v v' /\\\n                 length temps' = temp_size /\\\n                 st'#Sp = st#Sp /\\\n                 rv_postcond st'#Rv (fst v') |]).\n\n        Definition inv := inv_template (fun _ _ => True).\n        \n      End vars.\n\n    End TopSection.\n\n  End Make.\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/Inv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2724597454880826}}
{"text": "Set Primitive Projections.\n\nInductive ConeF (X A : Type) : Type :=\n| Z : A -> ConeF X A\n| S : X -> ConeF X A.\n\nArguments Z {X A} _.\nArguments S {X A} _.\n\nCoInductive Cone (A : Type) : Type := MkCone\n{\n  Out : ConeF (Cone A) A;\n}.\n\nArguments MkCone {A} _.\nArguments Out {A} _.\n\n", "meta": {"author": "wkolowski", "repo": "Typonomikon", "sha": "ff2166a3391f0fd77ba8de1b948dfe954fe9b997", "save_path": "github-repos/coq/wkolowski-Typonomikon", "path": "github-repos/coq/wkolowski-Typonomikon/Typonomikon-ff2166a3391f0fd77ba8de1b948dfe954fe9b997/code/Coind/Cone.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.27245974548808255}}
{"text": "From isla Require Import opsem.\n\nDefinition a18 : isla_trace :=\n  Smt (DeclareConst 38%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"R1\" [] (RegVal_Base (Val_Symbolic 38%Z)) Mk_annot :t:\n  Smt (DefineConst 39%Z (Val (Val_Symbolic 38%Z) Mk_annot)) Mk_annot :t:\n  Smt (DefineConst 44%Z (Manyop (Bvmanyarith Bvadd) [Manyop (Bvmanyarith Bvadd) [Unop (ZeroExtend 64%N) (Val (Val_Symbolic 39%Z) Mk_annot) Mk_annot; Val (Val_Bits (BV 128%N 0xffffffffffffffff%Z)) Mk_annot] Mk_annot; Val (Val_Bits (BV 128%N 0x1%Z)) Mk_annot] Mk_annot)) Mk_annot :t:\n  Smt (DefineConst 48%Z (Unop (Extract 63%N 0%N) (Val (Val_Symbolic 44%Z) Mk_annot) Mk_annot)) Mk_annot :t:\n  Smt (DefineConst 61%Z (Manyop Concat [Manyop Concat [Manyop Concat [Manyop (Bvmanyarith Bvor) [Manyop (Bvmanyarith Bvand) [Val (Val_Bits (BV 1%N 0x0%Z)) Mk_annot; Unop (Bvnot) (Val (Val_Bits (BV 1%N 0x1%Z)) Mk_annot) Mk_annot] Mk_annot; Unop (Extract 0%N 0%N) (Binop ((Bvarith Bvlshr)) (Val (Val_Symbolic 48%Z) Mk_annot) (Unop (Extract 63%N 0%N) (Val (Val_Bits (BV 128%N 0x3f%Z)) Mk_annot) Mk_annot) Mk_annot) Mk_annot] Mk_annot; Ite (Binop (Eq) (Val (Val_Symbolic 48%Z) Mk_annot) (Val (Val_Bits (BV 64%N 0x0%Z)) Mk_annot) Mk_annot) (Val (Val_Bits (BV 1%N 0x1%Z)) Mk_annot) (Val (Val_Bits (BV 1%N 0x0%Z)) Mk_annot) Mk_annot] Mk_annot; Ite (Binop (Eq) (Unop (ZeroExtend 64%N) (Val (Val_Symbolic 48%Z) Mk_annot) Mk_annot) (Val (Val_Symbolic 44%Z) Mk_annot) Mk_annot) (Val (Val_Bits (BV 1%N 0x0%Z)) Mk_annot) (Val (Val_Bits (BV 1%N 0x1%Z)) Mk_annot) Mk_annot] Mk_annot; Ite (Binop (Eq) (Unop (SignExtend 64%N) (Val (Val_Symbolic 48%Z) Mk_annot) Mk_annot) (Manyop (Bvmanyarith Bvadd) [Manyop (Bvmanyarith Bvadd) [Unop (SignExtend 64%N) (Val (Val_Symbolic 39%Z) Mk_annot) Mk_annot; Val (Val_Bits (BV 128%N 0xffffffffffffffffffffffffffffffff%Z)) Mk_annot] Mk_annot; Val (Val_Bits (BV 128%N 0x1%Z)) Mk_annot] Mk_annot) Mk_annot) (Val (Val_Bits (BV 1%N 0x0%Z)) Mk_annot) (Val (Val_Bits (BV 1%N 0x1%Z)) Mk_annot) Mk_annot] Mk_annot)) Mk_annot :t:\n  Smt (DefineConst 63%Z (Unop (Extract 3%N 3%N) (Val (Val_Symbolic 61%Z) Mk_annot) Mk_annot)) Mk_annot :t:\n  WriteReg \"PSTATE\" [Field \"N\"] (RegVal_Struct [(\"N\", RegVal_Base (Val_Symbolic 63%Z))]) Mk_annot :t:\n  Smt (DefineConst 64%Z (Unop (Extract 2%N 2%N) (Val (Val_Symbolic 61%Z) Mk_annot) Mk_annot)) Mk_annot :t:\n  WriteReg \"PSTATE\" [Field \"Z\"] (RegVal_Struct [(\"Z\", RegVal_Base (Val_Symbolic 64%Z))]) Mk_annot :t:\n  Smt (DefineConst 65%Z (Unop (Extract 1%N 1%N) (Val (Val_Symbolic 61%Z) Mk_annot) Mk_annot)) Mk_annot :t:\n  WriteReg \"PSTATE\" [Field \"C\"] (RegVal_Struct [(\"C\", RegVal_Base (Val_Symbolic 65%Z))]) Mk_annot :t:\n  Smt (DefineConst 66%Z (Unop (Extract 0%N 0%N) (Val (Val_Symbolic 61%Z) Mk_annot) Mk_annot)) Mk_annot :t:\n  WriteReg \"PSTATE\" [Field \"V\"] (RegVal_Struct [(\"V\", RegVal_Base (Val_Symbolic 66%Z))]) Mk_annot :t:\n  Smt (DeclareConst 67%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"_PC\" [] (RegVal_Base (Val_Symbolic 67%Z)) Mk_annot :t:\n  Smt (DefineConst 68%Z (Manyop (Bvmanyarith Bvadd) [Val (Val_Symbolic 67%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 68%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/example/a18.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2723887326027793}}
{"text": "(*\nCopyright © 2008 Russell O’Connor\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis proof and associated documentation files (the \"Proof\"), to deal in\nthe Proof without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Proof, and to permit persons to whom the Proof is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Proof.\n\nTHE PROOF IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE PROOF OR THE USE OR OTHER DEALINGS IN THE PROOF.\n*)\nRequire Import QArith.Qround.\nRequire Import CoRN.metric2.Metric.\nRequire Import CoRN.metric2.ProductMetric.\nRequire Import CoRN.metric2.UniformContinuity.\nRequire Export CoRN.reals.fast.RasterizeQ.\nRequire Import CoRN.reals.fast.Interval.\nRequire Export CoRN.metric2.Graph.\nRequire Import CoRN.model.totalorder.QMinMax.\nRequire Export CoRN.model.totalorder.QposMinMax.\n\n(**\n* Plotting\nPlotting a uniformly continuous function on a finite interval consists\nof producing the graph of a function as a compact set, approximating that\ngraph, and finally rasterizing that approximation.\n\nA range for the plot must be provided. We choose to clamp the plotted\nfunction so that it lies inside the specified range.  Thus we plot\n[compose (clip b t) f] rather than [f].\n\nAfterwards we will plot more general located subsets of the plane:\n- Each blank pixels is correct, meaning there are no points of the subset\n  inside the rectangular regions it represents. In other words, filled\n  pixels cover the subset.\n- Each filled pixel means there exists a point of the subset inside its\n  rectangular region, or inside one of the adjacent pixels. Thus when we\n  zoom in the filled pixels, we will see more structure.\n- The pixels overlap, meaning each edge belongs to the 2 pixels that\n  touch it, and each corner belongs to the 4 pixels that touch it.\n \n*)\n\nLocal Open Scope uc_scope.\n\nSection PlotPath.\nVariable (from to:Q).\nHypothesis Hfromto:from<=to.\n\nVariable (l r:Q).\nHypothesis Hlr : l < r.\n\nVariable (b t:Q).\nHypothesis Hbt : b < t.\n\nVariable n : positive.\n\nLet w := r - l.\nLet h := t - b.\n\nLemma wpos : 0 < w.\nProof.\n  apply Qlt_minus_iff in Hlr. exact Hlr.\nQed.\n\nLemma hpos : 0 < h.\nProof.\n  apply Qlt_minus_iff in Hbt. exact Hbt.\nQed.\n\n(* Compute the number of pixels on the Y-axis to make square pixels. *)\nLet m : positive := Z.to_pos (Qceiling ((t-b) * inject_Z (Z.pos n) / (r-l))).\n\n(**\nHalf the error in the Plot example, since we need to approximate twice.\n*)\nLet err := Qpos_max ((1 # 8 * n) * (exist _ _ wpos))\n                    ((1 # 8 * m) * (exist _ _ hpos)).\n\nVariable path:Q_as_MetricSpace --> Complete Q2.\n\n(** The actual plot function.\n    The approximation of PathImage make a list (Complete Q2), ie a list\n    of points in the real plane. Those points still need to be approximated\n    by rational numbers, which map approximate does. *)\nDefinition PlotPath : positive * positive * Q * sparse_raster n m\n  := (n, m, 2#1,\n      sparse_raster_data n m\n    (map\n       (fun x : Z =>\n        rasterize2 n m t l b r\n          ((let (approximate, _) :=\n              path\n                (from +\n                 (to - from) * (2 * x + 1 # 1) /\n                 (2 *\n                  Z.pos\n                    (Z.to_pos\n                       (Qceiling\n                          ((to - from) /\n                           (inject_Z 2 *\n                            proj1_sig (FinEnum_map_modulus (1 # 1) (mu path) err)))))\n                  # 1)) in\n            approximate) err))\n       (iterateN_succ 0\n          (Z.to_pos\n             (Qceiling\n                ((to - from) /\n                 (inject_Z 2 * proj1_sig (FinEnum_map_modulus (1 # 1) (mu path) err)))))))).\n\nDefinition PlotPath_slow : positive * positive * Q * sparse_raster n m\n  := (n, m, 2#1,\n      RasterizeQ2 \n        (map (fun x : Q_as_MetricSpace => approximate (path x) err)\n             (approximate (CompactIntervalQ Hfromto)\n                          (FinEnum_map_modulus (1 # 1) (mu path) err)))\n        n m t l b r).\n\nLemma PlotPath_correct : eq PlotPath PlotPath_slow.\nProof.\n  unfold PlotPath, PlotPath_slow, RasterizeQ2.\n  rewrite map_map.\n  unfold CompactIntervalQ, approximate.\n  unfold CompactIntervalQ_raw, UniformPartition.\n  rewrite map_map.\n  reflexivity.\nQed.\n\nEnd PlotPath.\n\n\nLemma plFEQ : PrelengthSpace (FinEnum Q_as_MetricSpace).\nProof.\n apply FinEnum_prelength.\n  apply locatedQ.\n apply QPrelengthSpace.\nQed.\n\n\nSection Plot.\n\nVariable (l b:Q).\nVariable w h:Qpos.\n\nLet r:=l+proj1_sig w.\nLet t:=b+proj1_sig h.\n\nLet clip := uc_compose (boundBelow b) (boundAbove t).\n\nVariable f : Q_as_MetricSpace --> CR.\n\nLemma lrle : l <= r.\nProof.\n  rewrite <- (Qplus_0_r l).\n  unfold r. apply Qplus_le_r, Qpos_nonneg.\nQed.\n\nDefinition graphQ f : Compact Q2\n  := CompactGraph_b f plFEQ (CompactIntervalQ lrle).\n\nLemma graphQ_bonus : forall e x y,\n    In (x, y) (approximate (graphQ (uc_compose clip f)) e)\n    -> l <= x <= r /\\ b <= y <= t.\nProof.\n intros [e|] x y;[|intros; contradiction].\n simpl.\n unfold Cjoin_raw.\n Opaque CompactIntervalQ.\n simpl.\n unfold FinCompact_raw.\n rewrite map_map.\n rewrite -> in_map_iff.\n unfold graphPoint_b_raw; simpl.\n unfold Couple_raw; simpl.\n intros [z [Hz0 Hz1]].\n inversion Hz0.\n subst x. subst y.\n clear Hz0.\n split.\n eapply CompactIntervalQ_bonus_correct.\n apply Hz1.\n split. apply Qmax_ub_l.\n apply Qmax_lub.\n rewrite <- (Qplus_0_r b).\n unfold t. apply Qplus_le_r, Qpos_nonneg.\n apply Qmin_lb_l.\nQed.\n\nVariable n m : positive. (* Number of horizontal and vertical pixels *)\n\nLet err := Qpos_max ((1 # 4 * n) * w)\n                    ((1 # 4 * m) * h).\n\n(** [PlotQ] is the function that computes the pixels. *)\nDefinition PlotQ : sparse_raster n m\n  := RasterizeQ2 (approximate (graphQ (uc_compose clip f)) err) n m t l b r.\n\nLocal Open Scope raster.\n\n(** The resulting plot is close to the graph of [f] *)\nTheorem Plot_correct :\n  @ball (Compact Q2)\n        (proj1_sig (err + Qpos_max ((1 # 2 * n) * w) ((1 # 2 * m) * h))%Qpos)\n        (graphQ (uc_compose clip f))\n        (Cunit (CentersOfPixels (PixelizeQ2 PlotQ) (l,t) (r,b))).\nProof.\n apply ball_triangle with (Cunit (approximate (graphQ (uc_compose clip f)) err)).\n  apply ball_approx_r.\n unfold Compact.\n rewrite -> ball_Cunit.\n apply ball_sym.\n  split. apply Qpos_nonneg.\n  apply RasterizeQ2_correct.\n  intros. \n  destruct (InStrengthen H) as [[zx xy] [Hz0 [Hz1 Hz2]]].\n  simpl in Hz1, Hz2.\n  apply Qball_0 in Hz1.\n  apply Qball_0 in Hz2.\n  rewrite -> Hz1, Hz2.\n  eapply graphQ_bonus.\n  apply Hz0.\nQed.\n\nEnd Plot.\n\n(** Some nice notation for the graph of f. *)\nNotation \"'graphCR' f [ l '..' r ]\" :=\n (graphQ l r (refl_equal _) f) (f at level 0) : raster.\n\n(*\n(* Some graph examples *)\nLocal Open Scope raster. (* enables pretty printing of rasters *)\nDefinition id_raster : raster _ _\n  := PlotQ 0 1 eq_refl 0 1 eq_refl (@Cunit Q_as_MetricSpace) 30 30.\nCompute id_raster.\n\nRequire Import CoRN.reals.fast.CRexp.\nDefinition exp_raster\n  := PlotQ (-2) 1 eq_refl 0 3 eq_refl (exp_bound_uc 3) 30 30.\nCompute exp_raster.\n*)\n\n(* Difficult to make tail-recursive, because the current vector\n   has no clear size to declare. Vector.map is not tail-recursive either. *)\nFixpoint PlotLine (A : CR*CR -> Prop) (i:nat)\n           (r step:Q) (y : CR) (d e:Q) (ltde : d < e)\n           (loc : LocatedSubset (ProductMS CR CR) A)\n           { struct i }\n  : list bool :=\n  match i with\n  | O => nil\n  | S p =>\n    cons (let xi := inject_Q_CR (r - inject_Z (Z.of_nat i) * step)%Q in\n          if loc d e (xi,y) ltde then false else true)\n         (PlotLine A p r step y d e ltde loc)\n  end.\n\nFixpoint PlotSubset_fix (A : CR*CR -> Prop) (n j:nat)\n         (b r stepX stepY:Q) (d e:Q) (ltde : d < e)\n         (loc : LocatedSubset (ProductMS CR CR) A)\n         { struct j }\n  : list (list bool) :=\n  match j with\n  | O => nil\n  | S p => let yj := inject_Q_CR (b + inject_Z (Z.of_nat j) * stepY)%Q in\n          cons (PlotLine A n r stepX yj d e ltde loc)\n               (PlotSubset_fix A n p b r stepX stepY d e ltde loc)\n  end. \n\nDefinition PlotRadius (n m : positive) (t l b r : Q) : Q\n  := Qmax ((r-l) * (1#n))%Q\n          ((t-b) * (1#m))%Q.\n\nLemma PlotRadiusInc\n  : forall n m t l b r,\n    l < r -> (1#2) * PlotRadius n m t l b r < PlotRadius n m t l b r.\nProof.\n  intros. rewrite <- (Qmult_1_l (PlotRadius n m t l b r)) at 2.\n  apply Qmult_lt_r.\n  2: reflexivity. apply (Qlt_le_trans _ ((r-l) * (1#n))%Q).\n  apply Qlt_minus_iff in H.\n  apply (Qpos_ispos (exist _ _ H * (1 # n))).\n  apply Qmax_ub_l.\nQed.\n \nDefinition PlotSubset {A : CR*CR -> Prop} (n m : positive) (t l b r : Q) \n           (ltlr : l < r) (loc : LocatedSubset (ProductMS CR CR) A)\n  : raster n m\n  := let stepX := ((r-l) * (1#n))%Q in\n     let stepY := ((t-b) * (1#m))%Q in\n     (* A pixel is a square ball and its radius it half its side. *)\n     raster_data\n       _ _\n       (PlotSubset_fix A (Pos.to_nat n) (Pos.to_nat m) (b-(1#2)*stepY) (r+(1#2)*stepX)\n                       stepX stepY _ _\n                       (PlotRadiusInc n m t l b r ltlr) loc).\n\n(*\nDefinition PlotDiagLocated := (PlotSubset\n         10 10 (1#1) (0#1) (0#1) (1#1) eq_refl\n         (undistrib_Located (CompactIsLocated\n         _ (graphQ 0 1 eq_refl (@Cunit Q_as_MetricSpace))\n         (ProductMS_located locatedQ locatedQ)))).\nLocal Open Scope raster. (* enables pretty printing of rasters *)\nTime Eval vm_compute in PlotDiagLocated.\n*)\n\n\n(* The blank pixels have no points of the subset, in other words\n   the filled pixels cover the subset. *)\nLemma PlotLine_blank\n  : forall (A : CR*CR -> Prop) (n i:nat) (ltni : (n < i)%nat)\n      (r step:Q) (x y z : CR) (d e:Q) (ltde : d < e)\n      (loc : LocatedSubset (ProductMS CR CR) A),\n    ball d x (inject_Q_CR (r - inject_Z (Z.of_nat (i-n)) * step)%Q)\n    -> ball d y z\n    -> nth n (PlotLine A i r step y d e ltde loc) false = false\n    -> ~A (x,z).\nProof.\n  induction n.\n  - intros. intro abs.\n    destruct i. exfalso; inversion ltni.\n    simpl in H1.\n    destruct (loc d e\n             (@pair (@RegularFunction Q Qball) (@RegularFunction Q Qball)\n                (inject_Q_CR\n                   (Qminus r (Qmult (inject_Z (Zpos (Pos.of_succ_nat i))) step))) y)\n             ltde).\n    2: discriminate. clear H1.\n    specialize (n (x,z) abs).\n    contradict n. split.\n    + unfold fst.\n      apply ball_sym.\n      exact H.\n    + exact H0.\n  - intros. intro abs. \n    destruct i. inversion ltni. simpl in H1.\n    revert abs.\n    refine (IHn i (lt_S_n n i ltni) r step x y z d e\n                ltde loc _ H0 H1).\n    replace (i-n)%nat with (S i - S n)%nat by reflexivity.\n    exact H.\nQed.\n\nLemma PlotSubset_fix_blank\n  : forall (A : CR*CR -> Prop) (x y : CR) (i j n m:nat)\n      (ltin : (i < n)%nat) (ltjm : (j < m)%nat)\n      (b r stepX stepY:Q) (d e:Q) (ltde : d < e)\n      (loc : LocatedSubset (ProductMS CR CR) A),\n    ball d x (inject_Q_CR (r - inject_Z (Z.of_nat (n-i)) * stepX)%Q)\n    -> ball d y (inject_Q_CR (b + inject_Z (Z.of_nat (m-j)) * stepY)%Q)\n    -> nth i\n        (nth j (PlotSubset_fix A n m b r stepX stepY\n                                    d e ltde loc) \n             nil)\n        false = false\n    -> ~A (x,y).\nProof.\n  induction j.\n  - intros. intro abs.\n    destruct m. exfalso; inversion ltjm.\n    simpl in H1.\n    refine (PlotLine_blank\n              A i n ltin r stepX x\n              (' (b + inject_Z (Z.pos (Pos.of_succ_nat m)) * stepY)%Q)%CR\n              y d e ltde loc H _ H1 abs).\n    apply ball_sym.\n    exact H0.\n  - intros. intro abs.\n    destruct m. inversion ltjm.\n    simpl in H1.\n    apply (IHj n m ltin (lt_S_n j m ltjm) b r stepX stepY\n                    d e ltde loc H H0 H1 abs).\nQed.\n\nLemma PlotSubset_blank\n  : forall {A : CR*CR -> Prop} (i j : nat) (n m : positive) (t l b r : Q) (x y : CR)\n      (ltin : (i < Pos.to_nat n)%nat) (ltjm : (j < Pos.to_nat m)%nat) (ltlr : l < r)\n      (loc : LocatedSubset (ProductMS CR CR) A),\n    RasterIndex (PlotSubset n m t l b r ltlr loc) j i = false\n    -> let stepX := ((r-l) * (1#n))%Q in\n      let stepY := ((t-b) * (1#m))%Q in \n      ball ((1#2)*(Qmax stepX stepY)) x\n           (inject_Q_CR (l + (inject_Z (Z.of_nat i) + (1#2)) * stepX)%Q)\n      -> ball ((1#2)*(Qmax stepX stepY)) y\n             (inject_Q_CR (t - (inject_Z (Z.of_nat j) + (1#2)) * stepY)%Q)\n      -> ~A (x,y).\nProof.\n  intros. \n  setoid_replace (l + (inject_Z (Z.of_nat i)+(1#2)) * stepX)%Q\n    with ((r + (1#2)*stepX) - inject_Z (Z.of_nat (Pos.to_nat n - i)) * stepX)%Q\n    in H0. \n  setoid_replace (t - (inject_Z (Z.of_nat j) + (1#2)) * stepY)%Q\n    with ((b-(1#2)*stepY) + inject_Z (Z.of_nat (Pos.to_nat m - j)) * stepY)%Q\n    in H1. \n  exact (PlotSubset_fix_blank\n           A x y i j (Pos.to_nat n) (Pos.to_nat m) ltin ltjm\n           _ _ stepX stepY\n           ((1#2)*(Qmax stepX stepY)) \n           (Qmax stepX stepY)\n           (PlotRadiusInc n m t l b r ltlr) loc\n           H0 H1 H).\n  - unfold canonical_names.equiv, stdlib_rationals.Q_eq.\n    rewrite Nat2Z.inj_sub.\n    unfold Zminus. rewrite Q.Zplus_Qplus, inject_Z_opp.\n    rewrite <- (Qplus_inj_r _ _ ((inject_Z (Z.of_nat j)+(1#2)) * stepY)).\n    ring_simplify.\n    rewrite positive_nat_Z.\n    unfold stepY.\n    rewrite <- Qmult_assoc.\n    setoid_replace ((1 # m) * inject_Z (Z.pos m)) with 1%Q by reflexivity.\n    rewrite Qmult_1_r. ring.\n    apply (le_trans _ (S j)).\n    apply le_S, le_refl. exact ltjm. \n  - unfold canonical_names.equiv, stdlib_rationals.Q_eq.\n    rewrite Nat2Z.inj_sub.\n    unfold Zminus. rewrite Q.Zplus_Qplus, inject_Z_opp.\n    rewrite positive_nat_Z.\n    rewrite <- (Qplus_inj_r _ _ (stepX * inject_Z (Z.pos n)\n                                -inject_Z (Z.of_nat i) * stepX\n                                - (1#2)*stepX)).\n    ring_simplify.\n    unfold stepX.\n    rewrite <- Qmult_assoc.\n    setoid_replace ((1 # n) * inject_Z (Z.pos n)) with 1%Q by reflexivity.\n    rewrite Qmult_1_r. ring.\n    apply (le_trans _ (S i)).\n    apply le_S, le_refl. exact ltin.\nQed.\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/fast/Plot.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2723887262933196}}
{"text": "From ExtLib.Structures Require Import Monad MonadWriter MonadExc Monoid.\nRequire Import ExtLib.Data.Monads.WriterMonad.\n\nFrom ExtLib.Structures Require Export MonadWriter MonadExc Monoid.\n\nImport MonadNotation.\n\nOpen Scope monad.\n\nSection Error.\n\n(* Error type *)\nContext {E : Type}.\n(* Log type that must implement monoid typeclass *)\nContext {T : Type}.\nContext {MT : Monoid T}.\n\n(* Custom monad parametrized by Error type, Log type and return type *)\nDefinition errW A := T -> E + (T * A).\n\nGlobal Instance Monad_errW : Monad errW := {\n  ret := fun _ x => fun w => inr (w, x) ;\n  bind := fun _ _ m f => fun w => match m w with\n                            | inl v => inl v\n                            | inr (w', x) => f x (monoid_plus MT w w')\n                            end\n}.\n\nGlobal Instance Exception_errW : MonadExc E errW := {\n  raise := fun _ v => fun w => inl v ;\n  catch := fun _ c h => fun w => match c w with\n                           | inl v => h v w\n                           | inr x => inr x\n                           end\n}.\n\nGlobal Instance Writer_errW : MonadWriter MT errW := {\n  tell := fun w => fun _ => inr (w, tt) ;\n  listen := fun _ m => fun w => match m w with \n                          | inl v => inl v \n                          | inr (w', x) => inr (w', (x, w'))\n                          end ;\n  pass := fun _ m => fun w => match m w with\n                        | inl v => inl v\n                        | inr (w', (x, f)) => inr (f w', x)\n                        end ;\n}.\n\n(* Run monad and get inner value *)\nDefinition evalErrW {A : Type} (e : errW A) (init : T) : option A := \n  match e init with\n  | inl _ => None\n  | inr (_, v) => Some v\n  end.\n\n(* Run monad and get log value *)\nDefinition execErrW {A : Type} (e : errW A) (init : T) : option T :=\n  match e init with\n  | inl _ => None\n  | inr (w, _) => Some w\n  end.\n\nEnd Error.\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/ErrorWithWriter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.27238872629331956}}
{"text": "Require Import FunctionalExtensionality.\n\nRequire Import MirrorCore.TypesI.\nRequire Import MirrorCore.Lambda.AppN.\nRequire Import MirrorCore.Lambda.Red.\nRequire Import MirrorCore.Lambda.RedAll.\nRequire Import MirrorCore.RTac.Simplify.\n\nRequire Import Charge.ModularFunc.BaseFunc.\nRequire Import Charge.ModularFunc.ListFunc.\nRequire Import Charge.ModularFunc.ListType.\nRequire Import Charge.ModularFunc.BaseType.\nRequire Import Charge.ModularFunc.SemiEqDecTyp.\nRequire Import Charge.ModularFunc.Denotation.\n\nRequire Import Charge.Tactics.Lists.ListTacs.\nRequire Import Charge.Tactics.Base.DenotationTacs.\nRequire Import Charge.Tactics.Base.MirrorCoreTacs.\n\nRequire Import ExtLib.Core.RelDec.\n\nSection Zip.\n  Context {typ func : Type} {RType_typ : RType typ} {RSym_func : RSym func}.\n  Context {LT : ListType typ} {LTD : ListTypeD LT}. \n  Context {BT : BaseType typ} {BTD : BaseTypeD BT}.\n  Context {BF : BaseFunc typ func} {LF: ListFunc typ func}.\n  Context {Heq : RelDec (@eq typ)} {HC : RelDec_Correct Heq}.\n  Context {Heqd : SemiEqDecTyp typ} {HeqdOk : SemiEqDecTypOk Heqd}.\n  Context {Typ2_Fun : Typ2 RType_typ Fun}.\n  Context {Typ0_Prop : Typ0 RType_typ Prop}.\n  Context {BFOk : BaseFuncOk typ func} {LFOk : ListFuncOk typ func}.\n\n  Context {RTypeOk_typ : RTypeOk}.\n  Context {RSymOk_func : RSymOk RSym_func}.\n  Context {Typ2Ok_Fun : Typ2Ok Typ2_Fun}.\n\n  Fixpoint zipExpr (t u : typ) (e1 e2 : expr typ func) : expr typ func :=\n    match e1 with\n      | App (App (Inj f) x) xs =>\n        match listS f with\n          | Some (pCons _) =>\n            match e2 with\n              | App (App (Inj g) y) ys =>\n                match listS g with\n                  | Some (pCons _) => mkCons (tyProd t u) (mkPair t u x y) (zipExpr t u xs ys)\n                  | _ => mkZip t u e1 e2\n                end\n              | Inj g =>\n                match listS g with\n                  | Some (pNil _) => mkNil (tyProd t u)\n                  | _ => mkZip t u e1 e2\n                end\n              | _ => mkZip t u e1 e2\n            end\n          | _ => mkZip t u e1 e2\n        end\n      | Inj f =>\n        match listS f with\n          | Some (pNil _) => mkNil (tyProd t u)\n          | _ => mkZip t u e1 e2\n        end\n      | _ => mkZip t u e1 e2\n    end.\n  \n  (* This function should have lst is it's third arguments, but for reasons that I cannot figure out at the moment\n     the function does not reduce with lst as the last argument. *)\n     \n  Fixpoint zipExprConst_left (t u : typ) (lst : list (typD u)) (e : expr typ func) : expr typ func :=\n    match lst with\n      | nil => mkNil (tyProd t u)\n      | y :: ys => \n        match e with\n\t      | App (App (Inj f) x) xs =>\n\t        match listS f with\n\t          | Some (pCons _) => mkCons (tyProd t u) (mkPair t u x (mkConst u y)) (zipExprConst_left t u ys xs)\n\t          | _ => mkZip t u e (mkConst (tyList u) (listR lst))\n\t        end\n\t      | Inj f =>\n\t        match listS f with\n\t          | Some (pNil _) => mkNil (tyProd t u)\n\t          | _ => mkZip t u e (mkConst (tyList u) (listR lst))\n\t        end\n\t      | _ => mkZip t u e (mkConst (tyList u) (listR lst))\n      end\n    end.\n\n  Fixpoint zipExprConst_right (t u : typ) (lst : list (typD t)) (e : expr typ func) : expr typ func :=\n    match lst with\n      | nil => mkNil (tyProd t u)\n      | x :: xs => \n        match e with\n\t      | App (App (Inj f) y) ys =>\n\t        match listS f with\n\t          | Some (pCons _) => mkCons (tyProd t u) (mkPair t u (mkConst t x) y) (zipExprConst_right t u xs ys)\n\t          | _ => mkZip t u (mkConst (tyList t) (listR lst)) e\n\t        end\n\t      | Inj f =>\n\t        match listS f with\n\t          | Some (pNil _) => mkNil (tyProd t u)\n\t          | _ => mkZip t u (mkConst (tyList t) (listR lst)) e\n\t        end\n\t      | _ => mkZip t u (mkConst (tyList t) (listR lst)) e\n      end\n    end.\n  \n  Lemma combine_nil {A B : Type} (lst : list A) : combine lst (@nil B) = nil.\n  Proof.\n    destruct lst; reflexivity.\n  Qed.\n\n  Lemma trmR_nil_eq {T U : Type} {t : typ} (eq1 : typD t = T) (eq2 : typD t = U) :\n    trmR nil (listE eq1) = trmR nil (listE eq2).\n  Proof.\n    clear.\n    unfold listE, eq_ind, trmR, eq_rect_r, eq_rect, eq_sym, id.\n    generalize (btList t).\n    revert eq1 eq2.\n    remember (tyList t).\n    generalize dependent (typD t); intros; subst.\n    destruct eq2.\n    \n    generalize dependent (typD (tyList t)).\n    intros; subst. reflexivity.\n  Qed.\n   \n    Lemma trmR_cons_eq (t : typ) T (x : T) (xs : list T) (e : typD t = T) :\n      trmR (x :: xs) (listE e) = trmR ((trmR x e) :: (trmD (trmR xs (listE e)) (listE eq_refl))) (listE eq_refl).\n    Proof.\n      unfold trmR, trmD, listE, eq_ind, eq_rect_r, eq_rect, eq_sym, id.\n      generalize (btList t).\n      generalize dependent (typD t); intros; subst.\n      generalize dependent (typD (tyList t)); intros; subst. reflexivity.\n    Qed.\n\n\n  Lemma zipExprConst_left_sound tus tvs (t u : typ) (xs : expr typ func) (ys : list (typD u))\n    (xsD : ExprI.exprT tus tvs (typD (tyList t)))\n    (Hxs : ExprDsimul.ExprDenote.exprD' tus tvs (tyList t) xs = Some xsD) :\n\tExprDsimul.ExprDenote.exprD' tus tvs (tyList (tyProd t u)) (zipExprConst_left t u ys xs) =\n\t  Some (ExprDsimul.ExprDenote.exprT_App (ExprDsimul.ExprDenote.exprT_App (fun _ _ => zipD t u) xsD) (fun _ _ => listR ys)).\n  Proof.\n    generalize dependent xs. generalize dependent xsD.\n    induction ys; simpl; intros.\n    + rewrite listR_nil. \n      reduce. \n      rewriteD @combine_nil.\n      rewrite mkNil_sound.\n      erewrite trmR_nil_eq. reflexivity.\n    + do 3 (destruct_exprs; try (apply mkZip_sound; [assumption | apply mkConst_sound])).\n      * reduce.\n        rewrite mkNil_sound.\n        simpl.\n        erewrite trmR_nil_eq. reflexivity.\n      * do 2 (destruct_exprs; try (apply mkZip_sound; [assumption | apply mkConst_sound])).\n        reduce.\n        erewrite mkCons_sound; try eassumption; [| eapply mkPair_sound; [eassumption | apply mkConst_sound] | eapply IHys; eassumption].\n        simpl. \n        unfold consD, zipD, pairD, tyArrR2, tyArrR2', tyArrR', tyArrD, tyArrD'.\n        do 6 rewrite exprT_App_tyArrD.\n        unfold tyArrD, tyArrD'.\n        repeat rewriteD @trmDR.\n        unfold listR. unfold listD.\n        unfold prodR.\n        rewriteD @trmDR.\n        symmetry.\n        rewriteD trmR_cons_eq. reflexivity.\n  Qed.\n\n  Lemma zipExprConst_right_sound tus tvs (t u : typ) (xs : list (typD t)) (ys : expr typ func) \n    (ysD : ExprI.exprT tus tvs (typD (tyList u)))\n    (Hys : ExprDsimul.ExprDenote.exprD' tus tvs (tyList u) ys = Some ysD) :\n\tExprDsimul.ExprDenote.exprD' tus tvs (tyList (tyProd t u)) (zipExprConst_right t u xs ys) =\n\t  Some (ExprDsimul.ExprDenote.exprT_App (ExprDsimul.ExprDenote.exprT_App (fun _ _ => zipD t u) (fun _ _ => listR xs)) ysD).\n  Proof.\n    generalize dependent ys. generalize dependent ysD.\n    induction xs; simpl; intros.\n    + rewrite listR_nil. \n      reduce.\n      rewriteD mkNil_sound.\n      simpl. erewrite trmR_nil_eq; reflexivity.\n    + do 3 (destruct_exprs; try (apply mkZip_sound; [apply mkConst_sound| assumption])).\n      * reduce.\n        rewrite mkNil_sound.\n        simpl.\n        erewrite trmR_nil_eq; reflexivity.\n      * do 2 (destruct_exprs; try (apply mkZip_sound; [apply mkConst_sound | assumption])).\n        reduce.\n        erewrite mkCons_sound; try eassumption; [| eapply mkPair_sound; [apply mkConst_sound | eassumption] | eapply IHxs; eassumption].\n        unfold consD, zipD, pairD, tyArrR2, tyArrR2', tyArrR', tyArrD, tyArrD'.\n        do 6 rewrite exprT_App_tyArrD.\n        unfold tyArrD, tyArrD'.\n        repeat rewriteD @trmDR.\n        unfold listR. unfold listD.\n        unfold prodR.\n        rewriteD @trmDR. simpl.\n        symmetry.\n        rewriteD trmR_cons_eq. reflexivity.\n  Qed.\n\n\n  Lemma zipExprOk tus tvs (t u : typ) (xs ys : expr typ func) \n    (xsD : ExprI.exprT tus tvs (typD (tyList t))) (ysD : ExprI.exprT tus tvs (typD (tyList u)))\n    (Hxs : ExprDsimul.ExprDenote.exprD' tus tvs (tyList t) xs = Some xsD)\n    (Hys : ExprDsimul.ExprDenote.exprD' tus tvs (tyList u) ys = Some ysD) : \n    ExprDsimul.ExprDenote.exprD' tus tvs (tyList (tyProd t u)) (zipExpr t u xs ys) =\n      Some (ExprDsimul.ExprDenote.exprT_App (ExprDsimul.ExprDenote.exprT_App (fun _ _ => zipD t u) xsD) ysD).\n  Proof.\n    generalize dependent ys; generalize dependent xsD; generalize dependent ysD.\n    induction xs using expr_strong_ind; simpl; intros;\n      try (apply mkZip_sound; eassumption).\n    + do 2 (destruct_exprs; try (apply mkZip_sound; eassumption)).\n      reduce.\n      rewriteD mkNil_sound. simpl.\n      erewrite trmR_nil_eq; reflexivity.\n    + do 7 (destruct_exprs; try (apply mkZip_sound; eassumption)).\n      * reduce.\n        rewriteD @combine_nil.\n        erewrite trmR_nil_eq. rewrite mkNil_sound. reflexivity.\n      * do 2 (destruct_exprs; try (apply mkZip_sound; eassumption)).\n        reduce. simpl.\n        erewrite mkCons_sound; [| eapply mkPair_sound; eassumption | eapply H; [repeat constructor | eassumption | eassumption]].\n        unfold consD, zipD, pairD, tyArrR2, tyArrR2', tyArrR', tyArrD, tyArrD'. simpl.\n        repeat rewrite exprT_App_tyArrD.\n        unfold tyArrD, tyArrD'.\n        repeat rewrite @trmDR.\n        unfold listR, listD, prodR.\n        repeat rewriteD @trmDR. simpl.\n        symmetry.\n        rewriteD trmR_cons_eq. reflexivity.\n  Qed.\n    \n  Definition zipTac  (_ : list (option (expr typ func))) (e : expr typ func) (args : list (expr typ func)) : expr typ func :=\n    match listS e with\n      | Some (pZip t u) =>\n        match args with\n          | xs :: ys :: nil =>\n            match baseS xs, baseS ys with\n              | Some (pConst v xs'), Some (pConst w ys') =>\n                match type_cast v (tyList t), type_cast w (tyList u) with\n                  | Some pfxs, Some pfys =>\n                    mkConst (tyList (tyProd t u))\n                      (listR (eq_rect _ list\n                        (combine (listD (eq_rect _ typD xs' _ pfxs))\n                           (listD (eq_rect _ typD ys' _ pfys))) _ (eq_sym (btProd t u))))\n                  | _, _ => apps e args\n                end \n              | Some (pConst v xs'), None => \n                match type_cast v (tyList t) with\n                  | Some pf => zipExprConst_right t u (listD (eq_rect _ typD xs' _ pf)) ys\n                  | None => apps e args\n                end\n              | None, Some (pConst v ys') => \n                match type_cast v (tyList u) with\n                  | Some pf => zipExprConst_left t u (listD (eq_rect _ typD ys' _ pf)) xs\n                  | None => apps e args\n                end\n              | _, _ => zipExpr t u xs ys\n            end\n          | _ => apps e args\n        end\n      | _ => apps e args\n    end.\nRequire Import MirrorCore.Lambda.ExprD.\nCheck typeof_expr.\n  Lemma zipTacOk : partial_reducer_ok (zipTac nil).\n  Proof.\n    unfold partial_reducer_ok; intros.\n    eexists; split; [|reflexivity].\n    unfold zipTac.\n    do 6 (destruct_exprs; try assumption).\n    destruct_exprs.\n    Focus 2.\n    (* Here we have a problem at H as we have to prove False from\n       tyList = tyArr.\n    *)\n    (*\nred_exprD_hyp.\nforward_step.\nforward_step.\nforward_step.\nLocate typ2_cast.\ninversion H.\nforward_step.\nrepeat forward_step.\n  (try red_exprD_hyp); repeat forward_step; (repeat exprD_saturate_types); (repeat (first [rewrite_in_match | bf_rewrite_in_match])); (try red_exprD_goal); repeat (\n        first [red_unfold | red_rewrite]).\n    \n    rewrite zipExprOk.\n    destruct_exprs; [|apply zipExprOk].\n    destruct_exprs; (try (reduce; apply zipExprOk; [reduce | eassumption])).\n    destruct_exprs. destruct e1; try congruence.\n    destruct_exprs; (try (reduce; apply zipExprOk; reduce)).\n    destruct_exprs; try assumption.\n    destruct_exprs; try assumption.\n\t+ reduce.\n\t  unfold zipD, fun_to_typ2.\n\t  do 2 rewrite exprT_App_wrap. reflexivity.\n\t+ destruct_exprs; try assumption.\n\t  reduce.\n\t  erewrite zipExprConst_right_sound; [|eassumption].\n\t  unfold zipD, fun_to_typ2.\n\t  do 4 rewrite exprT_App_wrap.\n\t  rewriteD listDR. reflexivity.\n\t+ do 2 (destruct_exprs; (try (reduce; apply zipExprOk; reduce; assumption))).\n      destruct_exprs; try assumption.\n      reduce.\n\t  erewrite zipExprConst_left_sound; [|eassumption].\n\t  unfold zipD, fun_to_typ2.\n\t  do 3 rewrite exprT_App_wrap.\n\t  rewrite listDR. reflexivity.\n   *)\n   admit.\n   admit.\n   admit.\n   admit.\n   \n   \n  Qed.\n  \nDefinition ZIP := SIMPLIFY (typ := typ) (fun _ _ _ _ => beta_all zipTac).\n\nEnd Zip.", "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/Lists/Zip.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2723071008776031}}
{"text": "(************************************************************\n* Core Caml                                                 *\n* Small-big-step semantics                                  *\n*************************************************************)\n\nSet Implicit Arguments.\nRequire Export LibEnv CoreCaml_Syntax.\n\n\n(*==========================================================*)\n(* * Updated Definitions *)\n\n\n(************************************************************)\n(* ** Syntax of the language *)\n\n(** Grammar of values *)\n\nInductive val : Type :=\n  | val_cst : cst -> val\n  | val_loc : loc -> val\n  | val_abs : option var -> pat -> trm -> val\n  | val_constr : constr -> list val -> val\n  | val_tuple : list val -> val\n  | val_record : list (lab*val) -> val\n\n(** Grammar of terms *)\n\nwith trm : Type :=\n  | trm_var : var -> trm\n  | trm_cst : cst -> trm\n  | trm_abs : option var -> pat -> trm -> trm\n  | trm_constr : constr -> list trm -> trm\n  | trm_tuple : list trm -> trm\n  | trm_record : list (lab*trm) -> trm\n  | trm_unary : prim -> trm -> trm\n  | trm_binary : prim -> trm -> trm -> trm\n  | trm_lazy_binary : prim -> trm -> trm -> trm\n  | trm_app : trm -> trm -> trm\n  | trm_seq : trm -> trm -> trm\n  | trm_let : pat -> trm -> trm -> trm\n  | trm_get : trm -> lab -> trm\n  | trm_set : trm -> lab -> trm -> trm\n  | trm_if : trm -> trm -> option trm -> trm\n  | trm_while : trm -> trm -> trm\n  | trm_for : var -> dir -> trm -> trm -> trm -> trm\n  | trm_match : trm -> list branch -> trm\n  | trm_try : trm -> list branch -> trm\n  | trm_assert : trm -> trm\n  | trm_rand : trm\n\n(** including intermediate forms for the semantics *)\n\n  | trm_val : val -> trm\n  | trm_match_1 : val -> list branch -> trm -> trm -> trm\n  | trm_try_1 : val -> list branch -> trm\n  | trm_try_2 : val -> list branch -> trm -> trm -> trm\n\nwith branch : Type :=\n  | branch_intro : pat -> option trm -> trm -> branch.\n\n(** Representation of the memory store *)\n\nDefinition mem := Heap.heap loc val.\n\n\n(************************************************************)\n(* ** Auxiliary definitions *)\n\n(** Substitution *)\n\nDefinition inst := LibEnv.env val.\n\nParameter subst : forall (x:var) (v:val) (t:trm), trm.\nParameter substs : forall (i:inst) (t:trm), trm.\n\n(** [val] is inhabited *)\n\nInstance val_inhab : Inhab val.\nProof. intros. apply (Inhab_of_val (val_cst (cst_bool true))). Qed.\n\n(** Coercions *)\n(*\nCoercion cst_int : Z >-> cst.\nCoercion cst_bool : bool >-> cst.\nCoercion pat_var : var >-> pat.\n*)\nCoercion val_loc : loc >-> val.\nCoercion val_cst : cst >-> val.\n\n(** Shortnames for lists of terms and values *)\n\nDefinition trms := list trm.\nDefinition vals := list val.\nDefinition labtrms := list (lab*trm).\nDefinition labvals := list (lab*val).\n\n(** Shortcuts for building terms and values *)\n\nDefinition val_exn k := val_constr k nil.\n\nDefinition val_unit := val_constr constr_unit nil.\n\n(** Fresh locations *)\n\nDefinition fresh (m:mem) l :=\n  ~ Heap.indom m l.\n\n\n(************************************************************)\n(* ** Auxiliary definitions specific to small-step *)\n\nCoercion trm_val : val >-> trm.\n\n(** From list of values to list of terms *)\n\nDefinition trms_vals (vs : vals) : trms :=\n  LibList.map trm_val vs.\n\nDefinition trms_lab_vals (avs : labvals) : labtrms :=\n  LibList.map (fun av => let '(a,v) := av in (a, trm_val v)) avs.\n\n(** Auxiliary terms *)\n\nDefinition trm_raise := trm_unary prim_raise.\n\nDefinition trm_error k := trm_raise (val_exn k).\n\n\n\n(*==========================================================*)\n(* * Definitions *)\n\nImplicit Types x : var.\nImplicit Types c : cst.\nImplicit Types f : prim.\nImplicit Types k : constr.\nImplicit Types v : val.\nImplicit Types t : trm.\nImplicit Types m : mem.\nImplicit Types b : branch.\nImplicit Types a : lab.\nImplicit Types l : loc.\nImplicit Types i : inst.\nImplicit Types n : int.\nImplicit Types r : bool.\n\n\n(************************************************************)\n(* ** Auxiliary semantics definitions *)\n\n(** Semantics of Pattern matching *)\n\nInductive matching (i : inst) : val -> pat -> Prop :=\n  | matching_var : forall x v,\n      LibEnv.binds x v i ->\n      matching i v (pat_var x)\n  | matching_wild : forall v,\n      matching i v pat_wild\n  | matching_alias : forall x v p,\n      matching i v p ->\n      LibEnv.binds x v i ->\n      matching i v (pat_alias p x)\n  | matching_or : forall v p p1 p2,\n      matching i v p ->\n      (p = p1 \\/ p = p2) ->\n      matching i v (pat_or p1 p2)\n  | matching_cst : forall c,\n      matching i c (pat_cst c)\n  | matching_constr : forall k vs ps,\n      Forall2 (matching i) vs ps ->\n      matching i (val_constr k vs) (pat_constr k ps)\n  | matching_tuple : forall vs ps,\n      Forall2 (matching i) vs ps ->\n      matching i (val_tuple vs) (pat_tuple ps)\n  | matching_record_nil : forall avs,\n      matching i (val_tuple avs) (pat_tuple nil)\n  | matching_record_cons : forall avs a v p aps,\n      LibListAssoc.Assoc a v avs ->\n      matching i v p ->\n      matching i (val_record avs) (pat_record aps) ->\n      matching i (val_record avs) (pat_record ((a,p)::aps)).\n\nDefinition mismatching v p :=\n  forall i, ~ matching i v p.\n\n(** Semantics of primitive equality *)\n\nParameter primitive_eq : val -> val -> bool -> Prop.\n\n\n\n(************************************************************)\n(* ** Reduction contexts *)\n\n(** Grammar of contexts *)\n\nInductive ctx :=\n  | ctx_hole : ctx\n  | ctx_constr : constr -> list val -> ctx -> list trm -> ctx\n  | ctx_tuple : list val -> ctx -> list trm -> ctx\n  | ctx_record : list (lab*val) -> lab -> ctx -> list (lab*trm) -> ctx\n  | ctx_unary : prim -> ctx -> ctx\n  | ctx_binary_1 : prim -> ctx -> trm -> ctx\n  | ctx_binary_2 : prim ->val -> ctx -> ctx\n  | ctx_lazy_binary : prim ->ctx -> trm -> ctx\n  | ctx_app_1 : ctx -> trm -> ctx\n  | ctx_app_2 : val -> ctx -> ctx\n  | ctx_seq : ctx -> trm -> ctx\n  | ctx_let : pat -> ctx -> trm -> ctx\n  | ctx_get : ctx -> lab -> ctx\n  | ctx_set_1 : ctx -> lab -> trm -> ctx\n  | ctx_set_2 : val -> lab -> ctx -> ctx\n  | ctx_if : ctx -> trm -> option trm -> ctx\n  | ctx_for_1 : var -> dir -> ctx -> trm -> trm -> ctx\n  | ctx_for_2 : var -> dir -> val -> ctx -> trm -> ctx\n  | ctx_match : ctx -> list branch -> ctx\n  | ctx_try : ctx -> list branch -> ctx\n  | ctx_assert : ctx -> ctx\n  | ctx_match_1 : val -> list branch -> ctx -> trm -> ctx\n  | ctx_try_2 : val -> list branch -> ctx -> trm -> ctx.\n\nImplicit Types C : ctx.\n\n(** Application of contexts *)\n\nFixpoint ctx_apply C t :=\n  let r C' := ctx_apply C' t in\n  match C with\n  | ctx_hole => t\n  | ctx_constr k vs C' ts => trm_constr k (trms_vals vs ++ (r C') :: ts)\n  | ctx_tuple vs C' ts => trm_tuple (trms_vals vs ++ (r C') :: ts)\n  | ctx_record avs a C' ats => trm_record (trms_lab_vals avs ++ (a, (r C')) :: ats)\n  | ctx_unary f C' => trm_unary f (r C')\n  | ctx_binary_1 f C' t2 => trm_binary f (r C') t2\n  | ctx_binary_2 f v1 C' => trm_binary f v1 (r C')\n  | ctx_lazy_binary f C' t2 => trm_lazy_binary f (r C') t2\n  | ctx_app_1 C' t2 => trm_app (r C') t2\n  | ctx_app_2 v1 C' => trm_app v1 (r C')\n  | ctx_seq C' t2 => trm_seq (r C') t2\n  | ctx_let p C' t2 => trm_let p (r C') t2\n  | ctx_get C' a => trm_get (r C') a\n  | ctx_set_1 C' a t2 => trm_set (r C') a t2\n  | ctx_set_2 v1 a C' => trm_set v1 a (r C')\n  | ctx_if C' t2 ot3 => trm_if (r C') t2 ot3\n  | ctx_for_1 x d C' t2 t3 => trm_for x d (r C') t2 t3\n  | ctx_for_2 x d v1 C' t3 => trm_for x d v1 (r C') t3\n  | ctx_match C' bs => trm_match (r C') bs\n  | ctx_try C' bs => trm_try (r C') bs\n  | ctx_assert C' => trm_assert (r C')\n  | ctx_match_1 v bs C' t => trm_match_1 v bs (r C') t\n  | ctx_try_2 v bs C' t => trm_try_2 v bs (r C') t\n  end.\n\n(** Contexts that do not contain [try] construct *)\n\nFixpoint ctx_notry C :=\n  let r := ctx_notry in\n  match C with\n  | ctx_try C' bs => False\n  | ctx_hole => True\n  | ctx_constr k vs C' ts => r C'\n  | ctx_tuple vs C' ts => r C'\n  | ctx_record avs a C' ats => r C'\n  | ctx_unary f C' => r C'\n  | ctx_binary_1 f C' t2 => r C'\n  | ctx_binary_2 f v1 C' => r C'\n  | ctx_lazy_binary f C' t2 => r C'\n  | ctx_app_1 C' t2 => r C'\n  | ctx_app_2 v1 C' => r C'\n  | ctx_seq C' t2 => r C'\n  | ctx_let p C' t2 => r C'\n  | ctx_get C' a => r C'\n  | ctx_set_1 C' a t2 => r C'\n  | ctx_set_2 v1 a C' => r C'\n  | ctx_if C' t2 ot3 => r C'\n  | ctx_for_1 x d C' t2 t3 => r C'\n  | ctx_for_2 x d v1 C' t3 => r C'\n  | ctx_match C' bs => r C'\n  | ctx_assert C' => r C'\n  | ctx_match_1 v bs C' t => r C'\n  | ctx_try_2 v bs C' t => r C'\n  end.\n\n\n(************************************************************)\n(* ** Small-step reduction relation *)\n\n(** Configuration *)\n\nDefinition conf := (trm * mem)%type.\n\n(** Reduction *)\n\nReserved Notation \"t1 '/' m1 '--->' t2 '/' m2\"\n  (at level 40, m1 at level 30, t2 at level 30, m2 at level 30).\n\nInductive step : binary conf :=\n\n  | step_ctx : forall C t1 m1 t2 m2,\n      t1 / m1 ---> t2 / m2 ->\n      (ctx_apply C t1) / m1 --->\n      (ctx_apply C t2) / m2\n  | step_raise : forall C v m,\n      ctx_notry C ->\n      (ctx_apply C (trm_raise v)) / m --->\n      (trm_raise v) / m\n\n  | step_abs : forall oy p t m,\n      (trm_abs oy p t) / m --->\n      (val_abs oy p t) / m\n  | step_constr : forall k vs m,\n      (trm_constr k (trms_vals vs)) / m --->\n      (val_constr k vs) / m\n  | step_tuple : forall vs m,\n      (trm_tuple (trms_vals vs)) / m --->\n      (val_tuple vs) / m\n\n  | step_unary_not : forall r m,\n      (trm_unary prim_not r) / m --->\n      (neg r) / m\n  | step_unary_neg : forall n m,\n      (trm_unary prim_not n) / m --->\n      (cst_int (-n)) / m\n  | step_binary_eq : forall v1 v2 r m,\n      primitive_eq v1 v2 r ->\n      (trm_binary prim_eq v1 v2) / m --->\n      r / m\n  | step_binary_add : forall n1 n2 m,\n      (trm_binary prim_add n1 n2) / m --->\n      (n1+n2) / m\n  | step_binary_sub : forall n1 n2 m,\n      (trm_binary prim_sub n1 n2) / m --->\n      (n1-n2) / m\n  | step_binary_mul : forall n1 n2 m,\n      (trm_binary prim_mul n1 n2) / m --->\n      (n1*n2) / m\n  | step_binary_div_notzero : forall n1 n2 m,\n      n2 <> 0 ->\n      (trm_binary prim_div n1 n2) / m --->\n      (Z.div n1 n2) / m\n  | step_binary_div_zero : forall n1 n2 m,\n      (trm_binary prim_div n1 0) / m --->\n      (trm_error constr_div_by_zero) / m\n  | step_lazy_binary_and_true : forall v1 t2 m,\n      (trm_lazy_binary prim_and true t2) / m --->\n      t2 / m\n  | step_lazy_binary_and_false : forall v1 t2 m,\n      (trm_lazy_binary prim_and false t2) / m --->\n      false / m\n  | step_lazy_binary_or_true : forall v1 t2 m,\n      (trm_lazy_binary prim_or true t2) / m --->\n      true / m\n  | step_lazy_binary_or_false : forall v1 t2 m,\n      (trm_lazy_binary prim_or false t2) / m --->\n      t2 / m\n\n  | step_app_mismatch : forall p oy t3 v2 m,\n      mismatching v2 p ->\n      (trm_app (val_abs oy p t3) v2) / m --->\n      (trm_error constr_matching_failure) / m\n  | step_app_match : forall i p oy t3 t4 t5 v2 m,\n      matching i v2 p ->\n      t4 = substs i t3 ->\n      t5 = match oy with\n         | None => t4\n         | Some y => (subst y (val_abs oy p t3) t4) end ->\n      (trm_app (val_abs None p t3) v2) / m --->\n      t5 / m\n\n  | step_seq : forall v1 t2 m,\n      (trm_seq v1 t2) / m --->\n      t2 / m\n  | step_let_match : forall i p x v1 t2 m,\n      matching i v1 p ->\n      (trm_let p v1 t2) / m --->\n      (substs i t2) / m\n  | step_let_mismatch : forall p x v1 t2 m,\n       mismatching v1 p ->\n      (trm_let p v1 t2) / m --->\n      (trm_error constr_matching_failure) / m\n\n  | step_record : forall avs l m1 m2,\n      fresh m1 l ->\n      m2 = Heap.write m1 l (val_record avs) ->\n      (trm_record (trms_lab_vals avs)) / m1 --->\n      l / m2\n  | step_get : forall l a v avs m,\n      Heap.binds m l (val_record avs) ->\n      LibListAssoc.Assoc a v avs ->\n      (trm_get l a) / m --->\n      v / m\n  | step_set : forall l a v avs m1 m2,\n      Heap.binds m1 l (val_record avs) ->\n      m2 = Heap.write m1 l (val_record ((a,v)::avs)) ->\n      (trm_set l a v) / m1 --->\n      val_unit / m2\n\n  | step_while : forall t1 t2 m,\n      (trm_while t1 t2) / m --->\n      (trm_if t1 (trm_seq t2 (trm_while t1 t2)) None) / m\n  | step_if_true : forall t2 ot3 m,\n      (trm_if true t2 ot3) / m --->\n      t2 / m\n  | step_if_false_none : forall t2 m,\n      (trm_if false t2 None) / m --->\n      val_unit / m\n  | step_if_false_some : forall t2 t3 m,\n      (trm_if false t2 (Some t3)) / m --->\n      t3 / m\n  | step_for_upto_leq : forall x n1 n2 t3 m,\n      n1 <= n2 ->\n      (trm_for x dir_upto n1 n2 t3) / m --->\n      (trm_seq (trm_let x n1 t3) (trm_for x dir_upto (n1+1) n2 t3)) / m\n  | step_for_upto_gt : forall x n1 n2 t3 m,\n      n1 > n2 ->\n      (trm_for x dir_upto n1 n2 t3) / m --->\n      val_unit / m\n  | step_for_downto_geq : forall x n1 n2 t3 m,\n      n1 >= n2 ->\n      (trm_for x dir_downto n1 n2 t3) / m --->\n      (trm_seq (trm_let x n1 t3) (trm_for x dir_upto (n1-1) n2 t3)) / m\n  | step_for_downto_lt : forall x n1 n2 t3 m,\n      n1 < n2 ->\n      (trm_for x dir_downto n1 n2 t3) / m --->\n      val_unit / m\n\n  | step_match_nil : forall v m,\n      (trm_match v nil) / m --->\n      (trm_error constr_matching_failure) / m\n  | step_match_cons_mismatch : forall v p bs ot1 t2 m,\n      mismatching v p ->\n      (trm_match v ((branch_intro p ot1 t2)::bs)) / m --->\n      (trm_match v bs) / m\n  | step_match_cons_match_unguarded : forall v p bs t2 i m,\n      matching i v p ->\n      (trm_match v ((branch_intro p None t2)::bs)) / m --->\n      (substs i t2) / m\n  | step_match_cons_match_guarded : forall v p bs t1 t2 i m,\n      matching i v p ->\n      (trm_match v ((branch_intro p (Some t1) t2)::bs)) / m --->\n      (trm_match_1 v bs (substs i t1) (substs i t2)) / m\n  | step_match_1_true : forall v bs t2 m,\n      (trm_match_1 v bs true t2) / m --->\n      t2 / m\n  | step_match_1_false : forall v bs t2 m,\n      (trm_match_1 v bs false t2) / m --->\n      (trm_match v bs) / m\n\n  | step_try_val : forall v bs m,\n      (trm_try v bs) / m ---> v / m\n  | step_try_raise : forall v bs m,\n      (trm_try (trm_raise v) bs) / m --->\n      (trm_try_1 v bs) / m\n  | step_try_1_nil : forall v m,\n      (trm_try_1 v nil) / m --->\n      (trm_raise v) / m\n  | step_try_1_cons_mismatch : forall v p bs ot1 t2 m,\n      mismatching v p ->\n      (trm_try_1 v ((branch_intro p ot1 t2)::bs)) / m --->\n      (trm_try_1 v bs) / m\n  | step_try_1_cons_match_unguarded : forall v p bs t2 i m,\n      matching i v p ->\n      (trm_try_1 v ((branch_intro p None t2)::bs)) / m --->\n      (substs i t2) / m\n  | step_try_1_cons_match_guarded : forall v p bs t1 t2 i m,\n      matching i v p ->\n      (trm_try_1 v ((branch_intro p (Some t1) t2)::bs)) / m --->\n      (trm_try_2 v bs (substs i t1) (substs i t2)) / m\n  | step_try_2_true : forall v bs t2 m,\n      (trm_try_2 v bs true t2) / m --->\n      t2 / m\n  | step_try_2_false : forall v bs t2 m,\n      (trm_try_2 v bs false t2) / m --->\n      (trm_try_1 v bs) / m\n\n  | step_assert_true : forall m,\n      (trm_assert true) / m --->\n      val_unit / m\n  | step_assert_false : forall m,\n      (trm_assert false) / m --->\n      (trm_error constr_assert_failure) / m\n\n  | step_rand : forall m z,\n      trm_rand / m --->\n      (val_cst z) / m\n\nwhere \"t1 / m1 ---> t2 / m2\" := (step (t1:trm,m1) (t2:trm,m2)).\n\n\n\n\n(************************************************************)\n(* ** Complete reduction sequences *)\n\n(** Complete evaluation  [TODO]\n\nDefinition sredstar t t' := (rtclosure step) t t'.\n\nDefinition sredplus t t' := (tclosure step) t t'.\n\nDefinition sredval t v := sredstar t v.\n\nDefinition sredexn t v := sredstar t (trm_raise v).\n\nDefinition sdiverge t := (infclosure step) t.\n\n*)", "meta": {"author": "charguer", "repo": "formalmetacoq", "sha": "0f24ffe7416352c1a275671d8d857f8aa6a5bb39", "save_path": "github-repos/coq/charguer-formalmetacoq", "path": "github-repos/coq/charguer-formalmetacoq/formalmetacoq-0f24ffe7416352c1a275671d8d857f8aa6a5bb39/pretty/CoreCaml_Small.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.4843800842769843, "lm_q1q2_score": 0.27230709377139134}}
{"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\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. econstructor.\n       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. *)\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    econstructor; eauto.\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. 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": "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/old/fc_preservation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2721880933541551}}
{"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 TableAux.Specs.invalidate_pages_in_block.\nRequire Import TableAux.LowSpecs.invalidate_pages_in_block.\nRequire Import TableAux.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       barrier_spec\n       stage2_tlbi_ipa_spec\n    .\n\n  Lemma invalidate_pages_in_block_spec_exists:\n    forall habd habd'  labd addr\n      (Hspec: invalidate_pages_in_block_spec addr habd = Some habd')\n      (Hrel: relate_RData habd labd),\n    exists labd', invalidate_pages_in_block_spec0 addr labd = Some labd' /\\ relate_RData habd' labd'.\n  Proof.\n    intros. destruct Hrel. inv id_rdata.\n    unfold invalidate_pages_in_block_spec, invalidate_pages_in_block_spec0 in *. repeat autounfold in *.\n    repeat simpl_hyp Hspec; inv Hspec.\n    eexists. split. reflexivity. constructor.\n    replace (2097152 / 4096) with 512 by reflexivity.\n    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/TableAux/RefProof/invalidate_pages_in_block.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.27204249135854697}}
{"text": "From Relational Require Import OrderEnrichedCategory GenericRulesSimple.\n\nSet Warnings \"-notation-overridden,-ambiguous-paths\".\nFrom mathcomp Require Import all_ssreflect all_algebra reals distr realsum\n  ssrnat ssreflect ssrfun ssrbool ssrnum eqtype choice seq.\nSet Warnings \"notation-overridden,ambiguous-paths\".\n\nFrom Crypt Require Import Axioms ChoiceAsOrd SubDistr Couplings\n  UniformDistrLemmas FreeProbProg Theta_dens RulesStateProb UniformStateProb\n  pkg_core_definition chUniverse pkg_composition pkg_rhl\n  Package Prelude.\n\nFrom Coq Require Import Utf8.\nFrom extructures Require Import ord fset fmap.\n\nSet Bullet Behavior \"Strict Subproofs\".\nSet Default Goal Selector \"!\".\nSet Primitive Projections.\n\nImport Num.Def.\nImport Num.Theory.\n\nImport PackageNotation.\n\nModule Type ROParams.\n\n  Parameter Query : finType.\n  Parameter Random : finType.\n\n  Parameter Query_pos : Positive #|Query|.\n  Parameter Random_pos : Positive #|Random|.\n\nEnd ROParams.\n\nModule RO (π : ROParams).\n\n  Import π.\n\n  #[local] Existing Instance Query_pos.\n  #[local] Existing Instance Random_pos.\n\n  Definition chQuery := 'fin #|Query|.\n  Definition chRandom := 'fin #|Random|.\n  Notation \" 'query \" := chQuery (in custom pack_type at level 2).\n  Notation \" 'random \" := chRandom (in custom pack_type at level 2).\n\n  Definition i_random := #|Random|.\n  Definition INIT : nat := 0.\n  Definition QUERY : nat := 1.\n\n  Definition queries_loc : Location := (chMap chQuery chRandom ; 2).\n  Definition RO_locs : {fset Location} := fset [:: queries_loc].\n\n  Definition RO_exports :=\n    [interface\n      val #[ INIT ] : 'unit → 'unit ;\n      val #[ QUERY ] : 'query → 'random\n    ].\n\n  Definition RO : package RO_locs [interface] RO_exports :=\n    [package\n      def #[ INIT ] (_ : 'unit) : 'unit\n      {\n        put queries_loc := emptym ;;\n        ret Datatypes.tt\n      } ;\n      def #[ QUERY ] (q : 'query) : 'random\n      {\n        queries ← get queries_loc ;;\n        match queries q with\n        | Some r =>\n          ret r\n        | None =>\n          r ← sample uniform i_random ;;\n          put queries_loc := setm queries q r ;;\n          ret r\n        end\n      }\n    ].\n\nEnd RO.\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/examples/RandomOracle.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.27204249135854697}}
{"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 Lia.\nFrom Coq Require Import Strings.String.\nFrom Coq Require Import Logic.Eqdep_dec.\nFrom Coq Require Import Logic.FunctionalExtensionality.\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 Induction_Expr.\n\nLemma alpha_equiv_refl : forall e,\n  alpha_equiv_rel e e.\nProof.\n  induction e using expr_ind; intros.\n  - apply alpha_equiv_rel_id.\n  - apply alpha_equiv_rel_let.\n    apply H. apply same_structure_refl.\n    intros.\n    apply H0.\n    apply rename_keeps_structure.\n  - apply alpha_equiv_rel_num.\n  - apply alpha_equiv_rel_str. apply eqb_refl.\n  - apply alpha_equiv_rel_plus.\n    apply H. apply same_structure_refl.\n    apply H0. apply same_structure_refl.\n  - apply alpha_equiv_rel_times.\n    apply H. apply same_structure_refl.\n    apply H0. apply same_structure_refl.\n  - apply alpha_equiv_rel_cat.\n    apply H. apply same_structure_refl.\n    apply H0. apply same_structure_refl.\n  - apply alpha_equiv_rel_len.\n    apply H. apply same_structure_refl.\nQed.\n\nLemma alpha_equiv_sym : forall e e',\n  alpha_equiv_rel e e' -> alpha_equiv_rel e' e.\nProof.\n  intros e e' H. induction H.\n  - apply alpha_equiv_rel_id.\n  - apply alpha_equiv_rel_let.\n    assumption.\n    intros. apply H1; assumption.\n  - apply alpha_equiv_rel_num.\n  - apply alpha_equiv_rel_str.\n    rewrite eqb_sym. assumption.\n  - apply alpha_equiv_rel_plus; assumption.\n  - apply alpha_equiv_rel_times; assumption.\n  - apply alpha_equiv_rel_cat; assumption.\n  - apply alpha_equiv_rel_len; assumption.\nQed.\n\nLemma alpha_equiv_have_same_structure : forall e e',\n  alpha_equiv_rel e e' -> same_structure e e'.\nProof.\n  intros e e' H. induction H; simpl; auto; constructor; auto.\n  remember (max (get_fresh_var e2) (get_fresh_var e2')) as z.\n  apply (same_structure_trans _ (rename e2 x z) _).\n  apply rename_keeps_structure.\n  apply (same_structure_trans _ (rename e2' x' z) _).\n  apply H1.\n  subst z.\n  apply (fresh_var_not_in_all_vars_left e2 e2').\n  subst z.\n  apply (fresh_var_not_in_all_vars_right e2 e2').\n  apply same_structure_sym.\n  apply rename_keeps_structure.\nQed.\n\nLemma diff_constructor_not_alpha : forall e e',\n  diff_constructor e e' ->\n  forall e'' e''',\n    same_structure e e'' -> same_structure e' e''' ->\n    alpha_equiv_rel e'' e''' -> False.\nProof.\n  intros.\n  assert (H3 := alpha_equiv_have_same_structure e'' e''' H2).\n  assert (H4 := same_structure_trans e e'' e''' H0 H3).\n  apply same_structure_sym in H1.\n  assert (H5 := same_structure_trans e e''' e' H4 H1).\n  clear H0 H1 H2 H3 H4 e'' e'''. rename H5 into H2.\n  destruct e.\n  all: destruct e'.\n  all: inversion H.\n  all: inversion H2.\nQed.\n\nLemma alpha_equiv_same_free_vars : forall e e',\n  alpha_equiv_rel e e' -> free_vars e = free_vars e'.\nProof.\n  intros e e' H. induction H; simpl; auto.\n  - rewrite <- IHalpha_equiv_rel.\n    remember (max\n      (get_fresh_var (ELet e1 x e2))\n      (get_fresh_var (ELet e1' x' e2'))\n    ) as z.\n    assert (XZ : (x =? z) = false).\n    {\n      assert (T := fresh_var_not_in_all_vars_left (ELet e1 x e2) (ELet e1' x' e2')).\n      rewrite <- Heqz in T.\n      simpl in T. unfold unionSet in T.\n      apply orb_false_iff in T.\n      destruct T.\n      unfold updateSet in H3.\n      destruct (x =? z). discriminate.\n      reflexivity.\n    }\n    assert (X'Z : (x' =? z) = false).\n    {\n      assert (T := fresh_var_not_in_all_vars_right (ELet e1 x e2) (ELet e1' x' e2')).\n      rewrite <- Heqz in T.\n      simpl in T. unfold unionSet in T.\n      apply orb_false_iff in T.\n      destruct T.\n      unfold updateSet in H3.\n      destruct (x' =? z). discriminate.\n      reflexivity.\n    }\n    assert (Zfresh : all_vars e2 z = false).\n    {\n      assert (T := fresh_var_not_in_all_vars_left (ELet e1 x e2) (ELet e1' x' e2')).\n      rewrite <- Heqz in T.\n      simpl in T. unfold unionSet in T.\n      apply orb_false_iff in T. destruct T.\n      unfold updateSet in H3.\n      destruct (x =? z). discriminate. assumption.\n    }\n    assert (Zfresh' : all_vars e2' z = false).\n    {\n      assert (T := fresh_var_not_in_all_vars_right (ELet e1 x e2) (ELet e1' x' e2')).\n      rewrite <- Heqz in T.\n      simpl in T. unfold unionSet in T.\n      apply orb_false_iff in T. destruct T.\n      unfold updateSet in H3.\n      destruct (x' =? z). discriminate. assumption.\n    }\n    assert (T2 : alpha_equiv_rel (rename e2 x z) (rename e2' x' z)).\n    { apply H0; assumption. }\n    assert (T3 : free_vars (rename e2 x z) = free_vars (rename e2' x' z)).\n    { apply H1; assumption. }\n    assert (T4 := rename_removes_free_vars e2 x z XZ).\n    assert (T5 := rename_removes_free_vars e2' x' z X'Z).\n    assert (T6 := rename_keeps_other_free_vars e2 x z).\n    assert (T7 := rename_keeps_other_free_vars e2' x' z).\n    assert (R : removeFromSet (free_vars e2) x = removeFromSet (free_vars e2') x').\n    {\n      apply functional_extensionality. intros.\n      unfold removeFromSet.\n      case_eq (x =? x0); case_eq (x' =? x0); intros.\n      reflexivity.\n      apply Nat.eqb_eq in H3. subst x0.\n      rewrite Nat.eqb_sym in H2.\n      assert (T8 := T7 x H2 XZ).\n      rewrite <- T3 in T8.\n      symmetry. rewrite T8. assumption.\n      apply Nat.eqb_eq in H2. subst x0.\n      rewrite Nat.eqb_sym in H3.\n      assert (T9 := T6 x' H3 X'Z).\n      rewrite T3 in T9.\n      rewrite T5 in T9.\n      assumption.\n      rewrite Nat.eqb_sym in H2.\n      rewrite Nat.eqb_sym in H3.\n      case_eq (x0 =? z); intros.\n      + apply Nat.eqb_eq in H4. subst x0.\n        rewrite not_in_expr_not_free.\n        rewrite not_in_expr_not_free.\n        all: auto.\n      + assert (T8 := T7 x0 H2 H4).\n        assert (T9 := T6 x0 H3 H4).\n        rewrite T8. rewrite T9.\n        rewrite T3. reflexivity.\n    }\n    rewrite R. reflexivity.\n  - rewrite IHalpha_equiv_rel1. rewrite IHalpha_equiv_rel2. auto.\n  - rewrite IHalpha_equiv_rel1. rewrite IHalpha_equiv_rel2. auto.\n  - rewrite IHalpha_equiv_rel1. rewrite IHalpha_equiv_rel2. 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_AlphaEquiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883592602049, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.27204248487560295}}
{"text": "(******************************************************************************)\n(** * Definition of the Power memory model *)\n(******************************************************************************)\nFrom hahn Require Import Hahn.\nRequire Import Events.\nRequire Import Execution.\n\nSet Implicit Arguments.\n\nSection Power_ppo.\n\nVariable G : execution.\n\nNotation \"'E'\" := (acts_set G).\nNotation \"'lab'\" := (lab G).\nNotation \"'sb'\" := (sb G).\nNotation \"'rf'\" := (rf G).\nNotation \"'co'\" := (co G).\nNotation \"'rmw'\" := (rmw G).\nNotation \"'data'\" := (data G).\nNotation \"'addr'\" := (addr G).\nNotation \"'ctrl'\" := (ctrl G).\nNotation \"'deps'\" := (deps G).\nNotation \"'fre'\" := (fre G).\nNotation \"'rfe'\" := (rfe G).\nNotation \"'coe'\" := (coe G).\nNotation \"'rfi'\" := (rfi G).\nNotation \"'fri'\" := (fri G).\nNotation \"'fr'\" := (fr G).\nNotation \"'detour'\" := (detour G).\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)).\nNotation \"'RW'\" := (R ∪₁ W).\nNotation \"'FR'\" := (F ∪₁ R).\nNotation \"'FW'\" := (F ∪₁ W).\n\nNotation \"'F^isync'\" := (F ∩₁ (fun a => is_true (is_rlx lab a))).\n\nImplicit Type WF : Wf G.\n\n(******************************************************************************)\n(** ** PPO components *)\n(******************************************************************************)\n\nDefinition ctrli := ⦗R⦘ ⨾ ctrl ⨾ ⦗F^isync⦘ ⨾  sb.\n\nDefinition rdw := (fre ⨾ rfe) ∩ sb.\n\nDefinition ii0 := addr ∪ data ∪ rdw ∪ rfi.\nDefinition ci0 := ctrli ⨾ ⦗RW⦘ ∪ detour.\nDefinition cc0 := data ∪ ctrl ⨾ ⦗RW⦘ ∪ addr ⨾ sb^? ⨾ ⦗RW⦘.\n\nInductive ii x y : Prop :=\n      II0   : ii0 x y -> ii x y\n    | CI    : ci x y -> ii x y\n    | IC_CI : forall z, ic x z -> ci z y -> ii x y\n    | II_II : forall z, ii x z -> ii z y -> ii x y\nwith ic x y : Prop := \n    | II    : ii x y -> ic x y\n    | CC    : cc x y -> ic x y\n    | IC_CC : forall z, ic x z -> cc z y -> ic x y\n    | II_IC : forall z, ii x z -> ic z y -> ic x y\nwith ci x y : Prop := \n      CI0   : ci0 x y -> ci x y\n    | CI_II : forall z, ci x z -> ii z y -> ci x y\n    | CC_CI : forall z, cc x z -> ci z y -> ci x y\nwith cc x y : Prop := \n      CC0   : cc0 x y -> cc x y\n    | CI_   : ci x y -> cc x y\n    | CI_IC : forall z, ci x z -> ic z y -> cc x y\n    | CC_CC : forall z, cc x z -> cc z y -> cc x y.\n\nScheme ii_rec := Minimality for ii Sort Prop\n  with ic_rec := Minimality for ic Sort Prop\n  with ci_rec := Minimality for ci Sort Prop\n  with cc_rec := Minimality for cc Sort Prop.\n\nCombined Scheme ppo_comp_ind from ii_rec, ic_rec, ci_rec, cc_rec.\n\n(* Preserved program order *)\nDefinition ppo := ⦗R⦘ ⨾ ii ⨾ ⦗R⦘ ∪ ⦗R⦘ ⨾ ic ⨾ ⦗W⦘.\n\n(******************************************************************************)\n(** ** Relations in graph *)\n(******************************************************************************)\n\nLemma wf_ctrliE WF: ctrli ≡ ⦗E⦘ ⨾ ctrli ⨾ ⦗E⦘.\nProof using.\nsplit; [|basic_solver].\nunfold ctrli.\nsin_rewrite (wf_ctrlE WF).\nsin_rewrite (wf_sbE).\nbasic_solver 42.\nQed.\n\nLemma wf_rdwE WF: rdw ≡ ⦗E⦘ ⨾ rdw ⨾ ⦗E⦘.\nProof using.\nsplit; [|basic_solver].\nunfold rdw.\nsin_rewrite (wf_freE WF).\nsin_rewrite (wf_rfeE WF).\nbasic_solver 42.\nQed.\n\nLemma wf_ii0E WF: ii0 ≡ ⦗E⦘ ⨾ ii0 ⨾ ⦗E⦘.\nProof using.\nsplit; [|basic_solver].\nunfold ii0.\nrewrite (wf_addrE WF) at 1.\nrewrite (wf_dataE WF) at 1.\nrewrite (wf_rdwE WF) at 1.\nrewrite (wf_rfiE WF) at 1.\nbasic_solver 42.\nQed.\n\nLemma wf_ci0E WF: ci0 ≡ ⦗E⦘ ⨾ ci0 ⨾ ⦗E⦘.\nProof using.\nsplit; [|basic_solver].\nunfold ci0.\nrewrite (wf_ctrliE WF) at 1.\nrewrite (wf_detourE WF) at 1.\nbasic_solver 42.\nQed.\n\nLemma wf_cc0E WF: cc0 ≡ ⦗E⦘ ⨾ cc0 ⨾ ⦗E⦘.\nProof using.\nsplit; [|basic_solver].\nunfold cc0.\nrewrite (wf_dataE WF) at 1.\nrewrite (wf_ctrlE WF) at 1.\nrewrite (wf_addrE WF) at 1.\nrewrite (wf_sbE) at 1.\nbasic_solver 42.\nQed.\n\nLemma wf_helperE WF:\nforall x y,\n(ii x y -> E x /\\ E y) /\\\n(ic x y -> E x /\\ E y) /\\\n(ci x y -> E x /\\ E y) /\\ \n(cc x y -> E x /\\ E y).\nProof using.\ngeneralize (dom_to_doma (wf_ii0E WF)) (dom_to_domb (wf_ii0E WF)).\ngeneralize (dom_to_doma (wf_ci0E WF)) (dom_to_domb (wf_ci0E WF)).\ngeneralize (dom_to_doma (wf_cc0E WF)) (dom_to_domb (wf_cc0E WF)).\nunfolder; intros A1 A2 A3 A4 A5 A6.\napply ppo_comp_ind; basic_solver.\nQed.\n\nLemma wf_iiE WF: ii ≡ ⦗E⦘ ⨾ ii ⨾ ⦗E⦘.\nProof using.\nsplit; [|basic_solver].\nunfolder; ins; splits; try done; eapply wf_helperE in H; desf.\nQed.\n\nLemma wf_icE WF: ic ≡ ⦗E⦘ ⨾ ic ⨾ ⦗E⦘.\nProof using.\nsplit; [|basic_solver].\nunfolder; ins; splits; try done; eapply wf_helperE in H; desf.\nQed.\n\nLemma wf_ciE WF: ci ≡ ⦗E⦘ ⨾ ci ⨾ ⦗E⦘.\nProof using.\nsplit; [|basic_solver].\nunfolder; ins; splits; try done; eapply wf_helperE in H; desf.\nQed.\n\nLemma wf_ccE WF: cc ≡ ⦗E⦘ ⨾ cc ⨾ ⦗E⦘.\nProof using.\nsplit; [|basic_solver].\nunfolder; ins; splits; try done; eapply wf_helperE in H; desf.\nQed.\n\nLemma wf_ppoE WF: ppo ≡ ⦗E⦘ ⨾ ppo ⨾ ⦗E⦘.\nProof using.\nsplit; [|basic_solver].\nunfold ppo.\nrewrite (wf_iiE WF) at 1.\nrewrite (wf_icE WF) at 1.\nbasic_solver 42.\nQed.\n\n(******************************************************************************)\n(** ** Domains and codomains  *)\n(******************************************************************************)\n\nLemma wf_ctrliD : ctrli ⊆ ⦗R⦘ ⨾ ctrli.\nProof using.\nunfold ctrli; basic_solver 12.\nQed.\n\nLemma wf_rdwD WF : rdw ≡ ⦗R⦘ ⨾ rdw ⨾ ⦗R⦘.\nProof using.\nsplit; [|basic_solver].\nunfold rdw.\nsin_rewrite (wf_freD WF).\nsin_rewrite (wf_rfeD WF).\nbasic_solver 42.\nQed.\n\nLemma wf_ppoD WF: ppo ≡ ⦗R⦘ ⨾ ppo ⨾ ⦗RW⦘.\nProof using.\nsplit; [|basic_solver].\nunfold ppo.\ntype_solver 42.\nQed.\n\nLemma wf_ii0D WF: ii0 ≡ ⦗RW⦘ ⨾ ii0 ⨾ ⦗RW⦘.\nProof using.\nsplit; [|basic_solver].\nunfold ii0.\nrewrite (wf_addrD WF) at 1.\nrewrite (wf_dataD WF) at 1.\nrewrite (wf_rdwD WF) at 1.\nrewrite (wf_rfiD WF) at 1.\ntype_solver 42.\nQed.\n\nLemma wf_ci0D WF: ci0 ≡ ⦗RW⦘ ⨾ ci0 ⨾ ⦗RW⦘.\nProof using.\nsplit; [|basic_solver].\nunfold ci0.\nrewrite wf_ctrliD at 1.\nrewrite (wf_detourD WF) at 1.\nbasic_solver 42.\nQed.\n\nLemma wf_cc0D WF: cc0 ≡ ⦗RW⦘ ⨾ cc0 ⨾ ⦗RW⦘.\nProof using.\nsplit; [|basic_solver].\nunfold cc0.\nrewrite (wf_dataD WF) at 1.\nrewrite (wf_ctrlD WF) at 1.\nrewrite (wf_addrD WF) at 1.\nbasic_solver 42.\nQed.\n\nLemma wf_helperD WF:\nforall x y,\n(ii x y -> RW x /\\ RW y) /\\\n(ic x y -> RW x /\\ RW y) /\\\n(ci x y -> RW x /\\ RW y) /\\ \n(cc x y -> RW x /\\ RW y).\nProof using.\ngeneralize (dom_to_doma (wf_ii0D WF)) (dom_to_domb (wf_ii0D WF)).\ngeneralize (dom_to_doma (wf_ci0D WF)) (dom_to_domb (wf_ci0D WF)).\ngeneralize (dom_to_doma (wf_cc0D WF)) (dom_to_domb (wf_cc0D WF)).\nunfolder; intros A1 A2 A3 A4 A5 A6.\napply ppo_comp_ind; basic_solver.\nQed.\n\nLemma wf_iiD WF: ii ≡ ⦗RW⦘ ⨾ ii ⨾ ⦗RW⦘.\nProof using.\nsplit; [|basic_solver].\nunfolder; ins; splits; try done; eapply (wf_helperD WF) in H; desc; eauto.\nQed.\n\nLemma wf_icD WF: ic ≡ ⦗RW⦘ ⨾ ic ⨾ ⦗RW⦘.\nProof using.\nsplit; [|basic_solver].\nunfolder; ins; splits; try done; eapply (wf_helperD WF) in H; desc; eauto.\nQed.\n\nLemma wf_ciD WF: ci ≡ ⦗RW⦘ ⨾ ci ⨾ ⦗RW⦘.\nProof using.\nsplit; [|basic_solver].\nunfolder; ins; splits; try done; eapply (wf_helperD WF) in H; desc; eauto.\nQed.\n\nLemma wf_ccD WF: cc ≡ ⦗RW⦘ ⨾ cc ⨾ ⦗RW⦘.\nProof using.\nsplit; [|basic_solver].\nunfolder; ins; splits; try done; eapply (wf_helperD WF) in H; desc; eauto.\nQed.\n\n(******************************************************************************)\n(** ** Inclusion *)\n(******************************************************************************)\nLemma ctrli_in_sb WF : ctrli ⊆ sb.\nProof using. \nunfold ctrli.\nrewrite (ctrl_in_sb WF).\ngeneralize (@sb_trans G); basic_solver.\nQed.\n\nLemma ctrli_sb : ctrli ⨾ sb ⊆ ctrli.\nProof using.\nunfold ctrli.\ngeneralize (@sb_trans G); basic_solver 12.\nQed.\n\nLemma ctrli_in_ctrl WF : ctrli ⊆ ctrl.\nProof using. \nunfold ctrli.\ngeneralize (ctrl_sb WF); basic_solver.\nQed.\n\nLemma ii0_in_ii : ii0 ⊆ ii.\nProof using. vauto. Qed.\nLemma ci0_in_ci : ci0 ⊆ ci.\nProof using. vauto. Qed.\nLemma cc0_in_cc : cc0 ⊆ cc.\nProof using. vauto. Qed.\n\nLemma ci_in_ii : ci ⊆ ii.\nProof using. vauto. Qed.\nLemma ci_in_ic : ci ⊆ ic.\nProof using. vauto. Qed.\nLemma ii_in_ic : ii ⊆ ic.\nProof using. vauto. Qed.\nLemma ci_in_cc : ci ⊆ cc.\nProof using. vauto. Qed.\nLemma cc_in_ic : cc ⊆ ic.\nProof using. vauto. Qed.\n\nLemma ic_ci_in_ii : ic ⨾ ci ⊆ ii.\nProof using. unfolder; ins; desf; vauto. Qed.\nLemma ii_ii_in_ii : ii ⨾ ii ⊆ ii.\nProof using. unfolder; ins; desf; vauto. Qed.\nLemma ic_cc_in_ic : ic ⨾ cc ⊆ ic.\nProof using. unfolder; ins; desf; vauto. Qed.\nLemma ii_ic_in_ic : ii ⨾ ic ⊆ ic.\nProof using. unfolder; ins; desf; vauto. Qed.\nLemma ci_ii_in_ci : ci ⨾ ii ⊆ ci.\nProof using. unfolder; ins; desf; vauto. Qed.\nLemma cc_ci_in_ci : cc ⨾ ci ⊆ ci.\nProof using. unfolder; ins; desf; vauto. Qed.\nLemma ci_ic_in_cc : ci ⨾ ic ⊆ cc.\nProof using. unfolder; ins; desf; vauto. Qed.\nLemma cc_cc_in_cc : cc ⨾ cc ⊆ cc.\nProof using. unfolder; ins; desf; vauto. Qed.\nLemma ii_cc_in_ic : ii ⨾ cc ⊆ ic.\nProof using. unfolder; ins; desf; vauto. Qed.\n\nLemma ii0_in_sb WF: ii0 ⊆ sb.\nProof using.\nunfold ii0, rdw; ie_unfolder.\nrewrite addr_in_sb, data_in_sb; try done.\nbasic_solver 42.\nQed.\n\nLemma ci0_in_sb WF: ci0 ⊆ sb.\nProof using.\nunfold ci0, Execution.detour.\nrewrite ctrli_in_sb; try done.\nbasic_solver 42.\nQed.\n\nLemma cc0_in_sb WF: cc0 ⊆ sb.\nProof using.\nunfold cc0.\nrewrite addr_in_sb, data_in_sb, ctrl_in_sb; try done.\ngeneralize (@sb_trans G).\nbasic_solver 42.\nQed.\n\nLemma in_sb_helper WF:\nforall x y,\n(ii x y -> sb x y) /\\\n(ic x y -> sb x y) /\\\n(ci x y -> sb x y) /\\ \n(cc x y -> sb x y).\nProof using.\ngeneralize (ii0_in_sb WF) (ci0_in_sb WF) (cc0_in_sb WF).\ngeneralize (@sb_trans G).\nunfolder; intros A A1 A2 A3.\napply ppo_comp_ind; basic_solver.\nQed.\n\nLemma ii_in_sb WF: ii ⊆ sb.\nProof using.\nunfolder; ins; splits; try done; eapply in_sb_helper in H; desf.\nQed.\n\nLemma ic_in_sb WF: ic ⊆ sb.\nProof using.\nunfolder; ins; splits; try done; eapply in_sb_helper in H; desf.\nQed.\n\nLemma ci_in_sb WF: ci ⊆ sb.\nProof using.\nunfolder; ins; splits; try done; eapply in_sb_helper in H; desf.\nQed.\n\nLemma cc_in_sb WF: cc ⊆ sb.\nProof using.\nunfolder; ins; splits; try done; eapply in_sb_helper in H; desf.\nQed.\nLemma ppo_in_sb WF : ppo ⊆ sb.\nProof using.\nunfold ppo.\nrewrite ii_in_sb, ic_in_sb; try done.\nbasic_solver.\nQed.\n\nLemma rdw_in_ppo WF : rdw ⊆ ppo.\nProof using.\nunfold ppo.\nrewrite (wf_rdwD WF).\nrewrite <- ii0_in_ii.\nunfold ii0; basic_solver 42.\nQed.\n\nLemma rfi_in_ii : rfi ⊆ ii.\nProof using.\nrewrite <- ii0_in_ii.\nunfold ii0; basic_solver 42.\nQed.\n\nLemma detour_in_ci : detour ⊆ ci.\nProof using.\nrewrite <- ci0_in_ci.\nunfold ci0; basic_solver 42.\nQed.\n\nLemma detour_in_ii : detour ⊆ ii.\nProof using.\nby rewrite <- ci_in_ii, detour_in_ci.\nQed.\n\nLemma data_in_ii : data ⊆ ii.\nProof using.\nrewrite <- ii0_in_ii.\nunfold ii0; basic_solver 42.\nQed.\n\nLemma addr_in_ii : addr ⊆ ii.\nProof using.\nrewrite <- ii0_in_ii.\nunfold ii0; basic_solver 42.\nQed.\n\nLemma ctrl_in_cc : ctrl ⨾ ⦗RW⦘ ⊆ cc.\nProof using.\nrewrite <- cc0_in_cc.\nunfold cc0; basic_solver 42.\nQed.\n\nLemma addr_sb_in_cc : addr ⨾ sb^? ⨾ ⦗RW⦘ ⊆ cc.\nProof using.\nrewrite <- cc0_in_cc.\nunfold cc0; basic_solver 42.\nQed.\n\nLemma deps_in_ppo WF: deps ⨾ ⦗W⦘ ⊆ ppo.\nProof using.\nunfold Execution.deps, ppo.\nrewrite (wf_dataD WF), (wf_addrD WF), (wf_ctrlD WF).\nrewrite data_in_ii, addr_in_ii.\ngeneralize ii_in_ic cc_in_ic ctrl_in_cc.\nbasic_solver 42.\nQed.\n\nLemma addrsbW_in_ppo WF: addr ⨾ sb ⨾ ⦗W⦘ ⊆ ppo.\nProof using.\nunfold ppo.\nrewrite <- cc_in_ic, <- cc0_in_cc.\nrewrite (wf_addrD WF) at 1.\nunfold cc0; basic_solver 42.\nQed.\n\nLemma rdw_rbi_in_rbi WF: rdw ⨾ fri ⊆ fri.\nProof using.\nunfold rdw; ie_unfolder.\ngeneralize (rf_fr WF) (fr_co WF) (@sb_trans G).\nbasic_solver 42.\nQed.\n\nLemma ctrli_fri_in_ci0 WF: ctrli ⨾ fri ⊆ ci0.\nProof using.\nrewrite (wf_friD WF).\narewrite (⦗R⦘ ⨾ fri ⊆ sb).\nby ie_unfolder; basic_solver.\nsin_rewrite ctrli_sb.\nunfold ci0; type_solver.\nQed.\n\nLemma ctrli_fri_in_cc0 WF: ctrli ⨾ fri ⊆ cc0.\nProof using.\nrewrite (wf_friD WF).\narewrite (⦗R⦘ ⨾ fri ⊆ sb).\nby ie_unfolder; basic_solver.\nsin_rewrite ctrli_sb.\nrewrite (ctrli_in_ctrl WF).\nunfold cc0; basic_solver 12.\nQed.\n\nLemma R_ci0_W_in_ppo : ⦗R⦘ ⨾ ci0 ⨾ ⦗W⦘ ⊆ ppo.\nProof using.\nunfold ppo.\nrewrite <- ci_in_ic, <- ci0_in_ci.\nbasic_solver.\nQed.\n\n\n(******************************************************************************)\n(** ** L <-> PPO components *)\n(******************************************************************************)\n(* Single-transition definition *)\nInductive L x y : Prop :=\n  | L_cc      : cc0 x y -> L x y\n  | L_Li      : Li x y -> L x y\n  | L_L_cc    : forall z, L x z -> cc0 z y -> L x y\nwith Li x y : Prop :=\n  | Li_ci     : ci0 x y -> Li x y\n  | Li_ii     : ii0 x y -> Li x y\n  | Li_L_ci   : forall z, L x z -> ci0 z y -> Li x y\n  | Li_Li_ii  : forall z, Li x z -> ii0 z y -> Li x y.\n\nScheme L_rec := Minimality for L Sort Prop\n  with Li_rec := Minimality for Li Sort Prop.\n\nCombined Scheme L_comb from L_rec, Li_rec.\n\n\nLemma L_in_union : L ⊆ ii ∪ ic ∪ ci ∪ cc.\nProof using.\n  red; ins.\n  apply L_rec with (x:=x) \n  (P:=fun y => (ii ∪ ic ∪ ci ∪ cc) x y) (P0:=fun y => (ii ∪ ci) x y);\n  auto; ins; try vauto; try (by unfolder in *; desf; (right + left); vauto).\n  - left; left; right; unfolder in *; desf; vauto.\n    assert (ci ⊆ ic) by (unfolder; vauto).\n    apply H3 in H1; vauto.\nQed.\n\nLemma seq_alt A (r r' r'' : relation A) :\n  (forall x y, r' x y -> forall z, r z x -> r'' z y) <->\n  r ⨾ r' ⊆ r''.\nProof using.\n  split.\n  - ins; red; ins; unfold seq in H0; desf; eapply H; eauto; edone.\n  - unfolder; ins; apply H; eexists; splits; eauto.\nQed.\n\nLemma basic_to_transitional : \n  (Li^? ⨾ ii ⊆ Li) /\\\n  (Li^? ⨾ ic ⊆ L) /\\\n  (L^? ⨾ ci ⊆ Li) /\\\n  (L^? ⨾ cc ⊆ L).\nProof using.\n  rewrite <- !seq_alt.\n  cut (forall x y, \n    (ii x y -> forall z, Li^? z x -> Li z y) /\\ \n    (ic x y -> forall z, Li^? z x -> L z y) /\\\n    (ci x y -> forall z, L^? z x -> Li z y) /\\\n    (cc x y -> forall z, L^? z x -> L z y)).\n  { ins; splits; ins; desf;\n    specialize (H x y); desf; eauto. }\n  apply ppo_comp_ind with \n  (*ii*) (P:=fun x y => forall z, (Li^?) z x -> Li z y)\n  (*ic*) (P0:=fun x y => forall z, (Li^?) z x -> L z y)\n  (*ci*) (P1:=fun x y => forall z, (L^?) z x -> Li z y)\n  (*cc*) (P2:=fun x y => forall z, (L^?) z x -> L z y);\n  rewrite ?seq_alt;\n  (* base cases *)\n  try (by unfolder; ins; desf; vauto);\n  ins;\n  (* single derivations *)\n  try (by apply H2; right; apply H0);\n  (* double derivations *)\n  try (by apply H0; red in H1; desf; (left + right); vauto);\n  by apply L_Li, H0.\nQed.\n\nLemma L_Li_in_ppo_components : Li ⊆ ii ∪ ci /\\ L ⊆ ii ∪ ic ∪ ci ∪ cc.\nProof using.\n  unfolder.\n  assert (forall x y,\n    (L x y -> ii x y \\/ ic x y \\/ ci x y \\/ cc x y) /\\ \n    (Li x y -> ii x y \\/ ci x y)\n  ).\n  { ins; apply L_comb with\n      (P := fun y => ii x y \\/ ic x y \\/ ci x y \\/ cc x y)\n      (P0 := fun y => ii x y \\/ ci x y);\n    auto; ins.\n    all: try by vauto.\n    all: try by (desf; by (left + right); vauto).\n    all: try by (desf; by repeat right; vauto).\n    desf; by (right; left + (repeat right)); vauto.\n  }\n  split; ins; specialize (H x y); desf; intuition.\nQed.\n\nLemma Li_is_ii : Li ≡ ii.\nProof using.\n  split.\n  - arewrite (Li ⊆ ii ∪ ci) by apply L_Li_in_ppo_components.\n    rewrite ci_in_ii.\n    basic_solver.\n  - generalize basic_to_transitional.\nbasic_solver 12.\nQed.\n\nLemma L_is_ic : L ≡ ic.\nProof using.\n  split.\n  - arewrite (L ⊆ ii ∪ ic ∪ ci ∪ cc) by apply L_Li_in_ppo_components.\n  rewrite ii_in_ic, ci_in_ic, cc_in_ic; basic_solver.\n  - red; ins.\n    assert (Li^? ⨾ ic ⊆ L) by apply basic_to_transitional.\n    apply H0; eexists; splits; eauto.\nQed.\n\nLemma wf_LD WF: L ⊆ ⦗RW⦘ ⨾ L ⨾ ⦗RW⦘.\nProof using.\nby rewrite L_is_ic; apply wf_icD. \nQed.\n\nLemma wf_LiD WF: Li ⊆ ⦗RW⦘ ⨾ Li ⨾ ⦗RW⦘.\nProof using.\nby rewrite Li_is_ii; apply wf_iiD. \nQed.\n\nLemma L_in_ppo : ⦗R⦘ ⨾ L ⨾ ⦗W⦘ ⊆ ppo.\nProof using.\nrewrite L_is_ic; unfold ppo; basic_solver.\nQed.\n\nLemma Li_in_ppo WF: ⦗R⦘ ⨾ Li ⊆ ppo.\nProof using.\nrewrite Li_is_ii; unfold ppo.\nrewrite (wf_iiD WF) at 1.\ngeneralize ii_in_ic.\nbasic_solver 42.\nQed.\n\nLemma Li_in_L : Li ⊆ L.\nProof using. vauto. Qed.\n\nLemma ppo_in_L WF: ppo ⊆ ⦗R⦘ ⨾ L.\nProof using.\nunfold ppo.\nrewrite L_is_ic, ii_in_ic.\nrewrite (wf_icD WF) at 3.\nbasic_solver.\nQed.\n\nLemma ppo_R_in_R_Li WF: ppo ⨾ ⦗R⦘ ⊆ ⦗R⦘ ⨾ Li.\nProof using.\nrewrite (wf_ppoD WF), Li_is_ii.\nunfold ppo; type_solver 12.\nQed.\n\nLemma ppo_W_in_R_L WF: ppo ⨾ ⦗W⦘ ⊆ ⦗R⦘ ⨾ L.\nProof using.\nrewrite (wf_ppoD WF), L_is_ic.\nunfold ppo; type_solver 12.\nQed.\n\n(******************************************************************************)\n(** ** Extra *)\n(******************************************************************************)\n\nLemma deps_in_cc: deps ⨾ ⦗RW⦘ ⊆ cc.\nProof using.\nrewrite <- cc0_in_cc.\nunfold Execution.deps, cc0; basic_solver 42.\nQed.\n\nLemma deps_in_ic : deps ⨾ ⦗RW⦘ ⊆ ic.\nProof using.\nrewrite <- cc_in_ic.\nby apply deps_in_cc.\nQed.\n\n(*\nLemma ctrl_sb_W_in_ppo WF: ctrl ⨾ sb ⨾ ⦗W⦘ ⊆ ppo ⨾ ⦗W⦘.\nProof using.\nunfold ppo.\nrewrite (wf_ctrlD WF).\nrewrite !seqA.\nsin_rewrite (ctrl_sb WF).\nrewrite <- cc_in_ic.\nrewrite <- ctrl_in_cc.\nbasic_solver 42.\nQed.\n*)\n\nLemma ctrli_RW_in_ic: ctrli ⨾ ⦗RW⦘ ⊆ ic.\nProof using.\nrewrite <- ci_in_ic, <- ci0_in_ci; vauto.\nQed.\n\nLemma ctrli_R_in_ii: ctrli ⨾ ⦗RW⦘ ⊆ ii.\nProof using.\nrewrite <- ci_in_ii, <- ci0_in_ci; vauto.\nQed.\n\nLemma ctrl_ctrli_in_ii WF: ctrl ⨾ ctrli ⨾ ⦗RW⦘ ⊆ ii.\nProof using.\nrewrite wf_ctrliD.\nunfolder; ins; desc.\neapply CI, CC_CI.\napply CC0; unfold cc0; basic_solver 12.\napply CI0; unfold ci0; basic_solver 12.\nQed.\n\n\nLemma ctrl_ctrli_RW_in_ppo WF: ctrl ⨾ ctrli ⨾ ⦗RW⦘ ⊆ ppo.\nProof using.\nrewrite (wf_ctrlD WF).\narewrite (⦗RW⦘ ⊆ ⦗RW⦘ ⨾ ⦗RW⦘) by basic_solver.\nsin_rewrite (ctrl_ctrli_in_ii WF).\nunfold ppo.\ngeneralize ii_in_ic.\nbasic_solver 12.\nQed.\n\nLemma ctrli_RW_in_ppo WF : ctrli ⨾ ⦗RW⦘ ⊆ ppo.\nProof using.\nunfold ppo.\nrewrite wf_ctrliD.\ngeneralize ctrli_RW_in_ic, ctrli_R_in_ii.\nbasic_solver 12.\nQed.\n\n(******************************************************************************)\n(** ** Propositions *)\n(******************************************************************************)\n\nLemma ppo_trans : transitive ppo.\nProof using.\n  unfold transitive, ppo; unfolder.\n  ins; desf; try type_solver.\n  by left; exists z2; split; auto; exists z; vauto.\n  by right; exists z2; split; auto; exists z; splits; vauto.\nQed.\n\nLemma ct_ppo_ctrli_rw_in_ppo WF : (ppo ∪ ctrli)⁺ ⨾ ⦗RW⦘ ⊆ ppo.\nProof using.\napply ct_ind_left with (P:= fun r => r ⨾ ⦗RW⦘).\n- by eauto with hahn.\n- generalize ctrli_RW_in_ppo; basic_solver.\n- ins; rewrite !seqA, H.\n  rewrite (dom_l (wf_ppoD WF)) at 2. \n  relsf.\n  arewrite (ctrli ⨾ ⦗R⦘ ⊆ ppo).\n  by generalize ctrli_RW_in_ppo; basic_solver.\n  generalize ppo_trans; basic_solver.\nQed.\n\nLemma deps_R_in_ppo WF: \n  (deps ∪ addr ⨾ sb) ⨾ ⦗R⦘ ⨾ sb ⨾ ⦗W⦘ ⊆ ppo.\nProof using.\n arewrite ((deps ∪ addr ⨾ sb) ⨾ ⦗R⦘ ⊆ ctrl ∪ addr ⨾ sb^?).\n  by unfold Execution.deps; rewrite (wf_dataD WF); type_solver 42.\nrelsf.\nsin_rewrite (ctrl_sb WF).\narewrite (ctrl ⊆ deps).\ngeneralize (addrsbW_in_ppo WF) (deps_in_ppo WF).\ngeneralize (@sb_trans G).\nbasic_solver 42.\nQed.\n\nLemma ci0_fri WF:  ci0 ⨾ fri ⊆ ppo ∪ co.\nProof using.\nunfold ci0.\nrewrite wf_ctrliD at 1.\nrewrite (wf_friD WF) at 1.\ngeneralize (ctrli_fri_in_ci0 WF), (R_ci0_W_in_ppo).\ngeneralize (detour_fr_in_co WF).\nie_unfolder.\nbasic_solver 42.\nQed.\n\nLemma L_ctrli_fri WF:  ⦗R⦘ ⨾  L ⨾ ctrli ⨾ fri ⊆ ppo.\nProof using.\nrewrite (dom_r (wf_friD WF)).\nrewrite <- L_in_ppo.\nrewrite (ctrli_in_ctrl WF).\narewrite (fri ⊆ sb).\nsin_rewrite (ctrl_sb WF). \nunfolder; splits; auto; desf.\napply L_L_cc with z; auto.\nunfold cc0; basic_solver 20.\nQed.\n\nLemma ppo_fri WF : ppo ⨾ fri ⊆ ppo ∪ ppo ⨾ co ∪ co ∪ fri.\nProof using.\nrewrite (wf_friD WF) at 1.\nrels.\nsin_rewrite ppo_R_in_R_Li; auto.\nred; ins. unfolder in H; desf.\nunfolder in H; desf; subst.\nrename y into c, x into a, z into b.\napply Li_rec with (P:=L a)\n (P0:=(fun b => fri b c -> (ppo ∪ ppo ⨾ co ∪ co ∪ fri) a c)) in H2; eauto; ins; vauto.\n- cut ((ppo ∪ co) a c).\n  by basic_solver.\n  generalize (ci0_fri WF).\n  basic_solver.\n- (* ii0 *)\n  red in H3; unfolder in H3; desf.\n  + (* addr *)\n    generalize (addrsbW_in_ppo WF).\n    ie_unfolder.\n    unfolder in *.\n    basic_solver 12.\n    + (* data *)\n    exfalso.\n    apply (wf_dataD WF) in H3.\n    apply (wf_friD WF) in H4.\n    unfolder in *; type_solver.\n    + (* rdw *)\n    generalize (rdw_rbi_in_rbi WF); basic_solver 12.\n    + (* rf∙ *)\n    generalize (rf_fr WF).\n    ie_unfolder.\n    unfolder in *;  basic_solver 12.\n- (* ci0 *)\n  unfold ci0 in *; unfolder in *; desf.\n  + (* ctrli *)\n    generalize (L_ctrli_fri WF); basic_solver 12.\n  + (* ctrli *)\n    generalize (L_ctrli_fri WF); basic_solver 12.\n  + (* detour *)\n    apply (wf_detourD WF) in H5.\n    generalize (detour_fr_in_co WF) L_in_ppo.\n    ie_unfolder.\n    unfolder in *; basic_solver 42.\n- unfold ii0 in *; unfolder in *; desf.\n  + (* addr *)\n    hahn_rewrite (wf_friD WF) in H6; unfolder in H6; desc.\n    do 3 left.\n    apply L_in_ppo.\n    unfolder. splits; auto. \n    apply L_L_cc with z; vauto.\n    unfold cc0.\n    ie_unfolder.\n    unfolder in *; basic_solver 42.\n  + (* data *)\n    exfalso.\n    apply (wf_dataD WF) in H5.\n    apply (wf_friD WF) in H6.\n    unfolder in *; type_solver.\n  + (* rdw *)\n    generalize (rdw_rbi_in_rbi WF).\n    basic_solver 12.\n  + (* rf∙ *)\n    do 2 left; right.\n    eexists.\n    split.\n    * generalize L_in_ppo, L_Li.\n      apply (wf_rfiD WF) in H5.\n      unfolder in *; basic_solver 12.\n    * generalize (rf_fr WF).\n      ie_unfolder.\n      unfolder in *; basic_solver.\nQed.\n\nLemma deps_rfi WF : \n  (data ∪ ctrl ∪ addr ⨾ sb^? ∪ rfi)⁺ ⊆ ctrl ∪ addr ⨾ sb^? ∪ ii ⨾ (ctrl ∪ addr ⨾ sb^?)^?.\nProof using.\neapply ct_ind_left with (P:= fun x : _ => x).\nby eauto with hahn.\nby rewrite <- ii0_in_ii; unfold ii0; basic_solver 12.\nintros k H; desf; rewrite H; clear H.\nrewrite rfi_in_ii, data_in_ii at 1.\narewrite (ii ∪ ctrl ∪ addr ⨾ sb^? ∪ ii ⊆ ii ∪ ctrl ∪ addr ⨾ sb^?).\nrewrite !seq_union_l; unionL.\n- by generalize ii_ii_in_ii; basic_solver 12.\n- rewrite (ctrl_in_sb WF) at 2 3.\nrewrite (ii_in_sb WF) at 1.\nrewrite (addr_in_sb WF) at 1 2.\ngeneralize (ctrl_sb WF) (@sb_trans G); basic_solver 12.\n- rewrite (ctrl_in_sb WF) at 1 2.\nrewrite (ii_in_sb WF) at 1.\nrewrite (addr_in_sb WF) at 2 3.\ngeneralize (@sb_trans G); basic_solver 12.\nQed.\n\nLemma r_deps_rfi WF: ⦗R⦘ ⨾ (data ∪ ctrl ∪ addr ⨾ sb^? ∪ rfi)⁺ ⨾ ⦗W⦘ ⊆ ppo.\nProof using.\nrewrite (deps_rfi WF).\nunfold ppo.\nrewrite (wf_ctrlD WF) at 1.\nrewrite (dom_l (wf_iiD WF)) at 1.\ngeneralize addr_sb_in_cc, ctrl_in_cc, ii_in_ic, ii_cc_in_ic, cc_in_ic; basic_solver 22.\nQed.\n\n(*\nLemma r_deps_rfi_w WF : ⦗R⦘ ⨾ (deps ∪ rfi)⁺ ⨾ ⦗W⦘ ⊆ ppo ⨾ ⦗W⦘.\nProof using.\nrewrite (deps_rfi WF).\nunfold ppo.\nrewrite (wf_ctrlD WF) at 1.\nrewrite (dom_l (wf_iiD WF)) at 1.\ngeneralize ctrl_in_cc, ii_in_ic, ii_cc_in_ic, cc_in_ic; basic_solver 22.\nQed.\n*)\n\nLemma ppo_detour_ppo WF : ppo ⨾  detour ⨾  ppo^?  ⊆ ppo.\nProof using.\nrewrite (wf_detourD WF).\nunfold ppo.\nrewrite detour_in_ci.\nrelsf; rewrite !seqA.\narewrite_false !(⦗R⦘ ⨾ ⦗W⦘); [by type_solver|].\ngeneralize ic_ci_in_ii, ii_ii_in_ii, ii_ic_in_ic; basic_solver 22.\nQed.\n\nLemma ppo_rt_detour_ppo WF : ppo ⨾ (detour ⨾ ppo^?)⁺ ⊆ ppo.\nProof using.\neapply ct_ind_left. \nby eauto with hahn.\napply (ppo_detour_ppo WF).\nintros k H; desf; rewrite !seqA.\nby sin_rewrite (ppo_detour_ppo WF).\nQed.\n\nLemma r_ct_ppo_detour_ppo WF: ⦗R⦘ ⨾ (ppo ∪ ctrli ∪ detour)⁺ ⨾ ⦗RW⦘ ⊆ ppo.\nProof using.\nrewrite path_union.\nrewrite (dom_l (wf_detourD WF)) at 1.\nrelsf.\nrewrite (ct_ppo_ctrli_rw_in_ppo WF).\narewrite (⦗W⦘ ⊆ ⦗RW⦘).\narewrite !((ppo ∪ ctrli)＊ ⨾ ⦗RW⦘ ⊆ ppo^?).\nby generalize (ct_ppo_ctrli_rw_in_ppo WF); basic_solver 12.\narewrite !((ppo ∪ ctrli)＊ ⨾ ⦗RW⦘ ⊆ ppo^?).\nby generalize (ct_ppo_ctrli_rw_in_ppo WF); basic_solver 12.\napply inclusion_union_l.\nby basic_solver.\nrewrite ct_seq_swap, ct_begin.\nrewrite (dom_l (wf_detourD WF)) at 1; rewrite !seqA.\narewrite (⦗R⦘ ⨾ ppo^? ⨾ ⦗W⦘ ⊆ ppo) by type_solver.\narewrite (detour ⨾ ppo^? ⨾ (detour ⨾ ppo^?)＊ ⊆ (detour ⨾ ppo^?)⁺).\nby rewrite <- seqA, <- ct_begin.\napply (ppo_rt_detour_ppo WF).\nQed.\n\n\n\n\n\n\n\nEnd Power_ppo.\n", "meta": {"author": "weakmemory", "repo": "imm", "sha": "7942cc3f204cabca065b8fbf749323c398bc0973", "save_path": "github-repos/coq/weakmemory-imm", "path": "github-repos/coq/weakmemory-imm/imm-7942cc3f204cabca065b8fbf749323c398bc0973/src/hardware/Power_ppo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573377, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.272042478392659}}
{"text": "Definition pair@{i} (T:Type@{i}) (t:T): (T*T) := (t,t).\n\nPrint pair.\n\nCheck (pair True I).\n\n\nRequire Import Template.Template.\nQuote Definition ps := pair nat 0.\nRequire Import String.\nRequire Import Ascii.\nOpen Scope string_scope.\nRequire Import List.\nImport ListNotations.\nPrint ps.\n\nDefinition idT@{i} (T:Type@{i}) : Type@{i} := T.\n\nRequire Import Template.Ast.\nMake Definition ps_from_syntax := \n(Ast.tApp (Ast.tConst \"Top.pair\")\n  [Ast.tInd (Ast.mkInd \"Coq.Init.Datatypes.nat\" 0);\n  Ast.tConstruct (Ast.mkInd \"Coq.Init.Datatypes.nat\" 0) 0]).\n  \nPrint ps_from_syntax.\n\nMake Definition idn_from_syntax := \n(Ast.tApp (Ast.tConst \"Top.idT\")\n  [Ast.tInd (Ast.mkInd \"Coq.Init.Datatypes.nat\" 0)]).\n\nSet Universe Minimization.\n\nPrint idn_from_syntax.\n\n\n(*\nDefinition pair2@{i} (T:Type) (t:T): (T*T) := (t,t).\nTop.6 is unbound.\n*)\n\n(*\nDefinition pair2@{i} (T:Type): Type@{i} := list T.\nError: Universe {Top.18} is unbound.\n*)\n\n(*\nDefinition pair2@{i} (T:Type@{i}): Type := list T.\nError: Universe {Top.22} is unbound.\nCan't mix global and local universes?\n*)\n\nDefinition pair2@{i j} (T:Type@{i}): Type@{j} :=  T.\n\nDefinition xx := (pair2 nat).\nPrint xx.\nUnset Universe Minimization.\nDefinition xxx := (pair2 nat).\nPrint xxx.\n(*\nxx = pair2 nat\n     : Type@{Top.30}\n*)\nPrint xx.\n(*\nxx = pair2 nat\n     : Type@{Top.30}\nwhy same?\n*)\n\nDefinition pair4@{i} (T:Type@{i}) (t:T) : (T*(Type@{i})) \n  := @Coq.Init.Datatypes.pair T (Type@{i}) t T.\n\nPrint Universes.\n\nCheck (pair2 nat).\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/univPoly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032313, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2720144460014655}}
{"text": "Require Import Bool Omega Setoid Program.\nRequire Export Schema Category SmallSchema SmallCategory.\nRequire Import Common EquivalenceClass.\nRequire Import NaturalEquivalence ComputableCategory SNaturalEquivalence ComputableSchemaCategory SmallFunctor SmallTranslation.\n\nSet Implicit Arguments.\n\nSet Asymmetric Patterns.\n\nSet Universe Polymorphism.\n\nSection Schema_Category_Equivalence.\n  Variable C : SmallCategory.\n  Variable S : SmallSchema.\n\n  Hint Rewrite concatenate_noedges_p concatenate_p_noedges concatenate_addedge.\n  Hint Rewrite <- concatenate_prepend_equivalent.\n  Hint Rewrite concatenate_associative.\n\n  Hint Rewrite sconcatenate_noedges_p sconcatenate_p_noedges sconcatenate_addedge.\n  Hint Rewrite <- sconcatenate_prepend_equivalent.\n  Hint Rewrite sconcatenate_associative.\n\n  Hint Extern 1 (@RelationsEquivalent _ _ _ (PathsEquivalent _) _ _ _ _) => apply addedge_equivalent.\n  Hint Extern 1 (@RelationsEquivalent _ _ _ (PathsEquivalent _) _ _ _ _) => apply PreCompose.\n\n  Hint Extern 1 (@RelationsEquivalent _ _ _ (SPathsEquivalent _) _ _ _ _) => apply saddedge_equivalent.\n  Hint Extern 1 (@RelationsEquivalent _ _ _ (SPathsEquivalent _) _ _ _ _) => apply SPreCompose.\n\n  Definition path2path' s d (p : path S s d) : path' (Edge S) s d := p.\n  Definition spath2spath' s d (p : spath S s d) : spath' (SEdge S) s d := p.\n\n  Hint Rewrite concatenate_p_noedges concatenate_noedges_p concatenate_associative.\n  Hint Rewrite sconcatenate_p_noedges sconcatenate_noedges_p sconcatenate_associative.\n\n  Ltac replace_noedges' :=\n    match goal with\n      | [ H : ?rel NoEdges ?x |- _ ] => rewrite <- H in *; clear H\n      | [ H : ?rel ?x NoEdges |- _ ] => rewrite H in *; clear H\n      | [ H : ?rel SNoEdges ?x |- _ ] => rewrite <- H in *; clear H\n      | [ H : ?rel ?x SNoEdges |- _ ] => rewrite H in *; clear H\n    end.\n\n  Ltac replace_noedges :=\n        repeat replace_noedges';\n          repeat (rewrite concatenate_p_noedges in * || rewrite concatenate_noedges_p in *);\n            repeat (rewrite sconcatenate_p_noedges in * || rewrite sconcatenate_noedges_p in *).\n\n  Ltac clear_paths :=\n    repeat match goal with\n             | [ H : path' _ _ _ |- _ ] => subst H || clear H\n             | [ H : spath' _ _ _ |- _ ] => subst H || clear H\n           end.\n\n  Ltac replace_paths_equivalent' :=\n    try replace_noedges;\n      try solve [ assumption || symmetry; assumption ];\n        clear_paths;\n        repeat match goal with\n                 | [ H : context[PathsEquivalent] |- _ ] => rewrite <- H in *; clear H\n                 | [ H : context[SPathsEquivalent] |- _ ] => rewrite <- H in *; clear H\n               end; clear_paths; repeat rewrite concatenate_associative in *; repeat rewrite sconcatenate_associative in *; try reflexivity || symmetry;\n        repeat match goal with\n                 | [ H : context[PathsEquivalent] |- _ ] => rewrite H in *; clear H\n                 | [ H : context[SPathsEquivalent] |- _ ] => rewrite H in *; clear H\n               end; clear_paths; repeat rewrite concatenate_associative in *; repeat rewrite sconcatenate_associative in *; try reflexivity || symmetry.\n\n  (* TODO: Speed this up, automate this better. *)\n  Definition saturate : SmallCategory.\n    refine {| SObject := S;\n      SMorphism := (fun s d => EquivalenceClass (@SPathsEquivalent S s d));\n      (* foo := 1; *) (* uncommenting this line gives \"Anomaly: uncaught exception Not_found. Please report.\"  Maybe I should report this?  But I haven't figured out a minimal test case. *)\n      SIdentity := (fun _ => @classOf _ (@SPathsEquivalent S _ _) (Reflexive _ _ _) (Symmetric _ _ _) (Transitive _ _ _)\n        SNoEdges);\n      SCompose := (fun s d d' m1 m2 => @apply2_to_class _ _ _ _ _ (@SPathsEquivalent S _ _) (Reflexive _ _ _) (Symmetric _ _ _) (Transitive _ _ _)\n        (@sconcatenate S S.(SEdge) s d d') (@sconcatenate_mor S s d d') m2 m1)\n    |}; abstract (\n      intros; apply forall__eq; intros; split; intros; simpl in *; destruct_hypotheses; clear_paths; clear_InClass;\n        try (replace_noedges; assumption || symmetry; assumption);\n          repeat (replace_InClass; try eexists; eauto); clear_InClass; replace_paths_equivalent'\n    ).\n(* abstract (intros; solve [ t | match goal with\n                                          | [ p : path _ _ _ |- _ ] => solve [ induction p; t ]\n                                        end ]).*)\n  Defined.\n\n  Fixpoint scompose_morphism_path s d (p : spath' C.(SMorphism) s d) : SMorphism _ s d :=\n    match p with\n      | SNoEdges => SIdentity s\n      | SAddEdge _ _ p' E => SCompose E (scompose_morphism_path p')\n    end.\n\n  Hint Rewrite SAssociativity.\n\n  Lemma scompose_morphism_path_alt : forall s d d' (E : Morphism C s d) (p : spath' _ d d'),\n    scompose_morphism_path (sprepend p E) = SCompose (scompose_morphism_path p) E.\n    induction p; simpl; autorewrite with core; auto.\n  Qed.\n\n  Hint Rewrite scompose_morphism_path_alt.\n\n  Definition unsaturate : SmallSchema.\n    refine {| SVertex := C;\n      SEdge := C.(SMorphism);\n      SPathsEquivalent' := (fun s d (p p' : _ s d) => scompose_morphism_path p = scompose_morphism_path p')\n    |}; abstract (t; etransitivity; eauto).\n  Defined.\nEnd Schema_Category_Equivalence.\n\nSection CategorySchemaCategory_RoundTrip.\n  Variable C : SmallCategory.\n\n  Hint Rewrite sconcatenate_noedges_p sconcatenate_p_noedges sconcatenate_addedge.\n  Hint Rewrite <- sconcatenate_prepend_equivalent.\n  Hint Rewrite sconcatenate_associative.\n\n  Hint Extern 1 (@RelationsEquivalent _ _ _ (SPathsEquivalent _) _ _ _ _) => apply addedge_equivalent.\n  Hint Extern 1 (@RelationsEquivalent _ _ _ (SPathsEquivalent _) _ _ _ _) => apply PreCompose.\n\n  Hint Rewrite sconcatenate_p_noedges sconcatenate_noedges_p sconcatenate_associative.\n\n  Ltac replace_noedges' :=\n    match goal with\n      | [ H : ?rel NoEdges ?x |- _ ] => rewrite <- H in *; clear H\n      | [ H : ?rel SNoEdges ?x |- _ ] => rewrite <- H in *; clear H\n      | [ H : ?rel ?x NoEdges |- _ ] => rewrite H in *; clear H\n      | [ H : ?rel ?x SNoEdges |- _ ] => rewrite H in *; clear H\n    end.\n\n  Ltac replace_noedges :=\n        repeat replace_noedges';\n          repeat (rewrite concatenate_p_noedges in * || rewrite concatenate_noedges_p in * ||\n            rewrite sconcatenate_p_noedges in * || rewrite sconcatenate_noedges_p in *).\n\n  Ltac clear_paths :=\n    repeat match goal with\n             | [ H : path' _ _ _ |- _ ] => subst H || clear H\n             | [ H : spath' _ _ _ |- _ ] => subst H || clear H\n           end.\n\n  Ltac replace_paths_equivalent' :=\n    try replace_noedges;\n      try solve [ assumption || symmetry; assumption ];\n        clear_paths;\n        repeat match goal with\n                 | [ H : context[PathsEquivalent] |- _ ] => rewrite <- H in *; clear H\n                 | [ H : context[SPathsEquivalent] |- _ ] => rewrite <- H in *; clear H\n               end; clear_paths; repeat rewrite sconcatenate_associative in *; try reflexivity || symmetry;\n        repeat match goal with\n                 | [ H : context[PathsEquivalent] |- _ ] => rewrite H in *; clear H\n                 | [ H : context[SPathsEquivalent] |- _ ] => rewrite H in *; clear H\n               end; clear_paths; repeat rewrite sconcatenate_associative in *; try reflexivity || symmetry.\n\n\n  Hint Rewrite scompose_morphism_path_alt.\n\n  Hint Rewrite LeftIdentity RightIdentity.\n\n  Lemma scompose_morphism_path_distr s d d' (x : spath' _ s d) (y : spath' _ d d') : scompose_morphism_path C (sconcatenate x y) = SCompose (scompose_morphism_path C y) (scompose_morphism_path C x).\n    induction x; t_with t'.\n  Qed.\n\n  Hint Rewrite scompose_morphism_path_distr.\n\n  Definition sautrate_unsaturate_functor_to : SmallFunctor C (saturate (unsaturate C)).\n    refine {| SObjectOf := (fun x : C => x : (saturate (unsaturate C)));\n      SMorphismOf := (fun s d m => @classOf (spath' _ s d) _ (Reflexive _ _ _) (Symmetric _ _ _) (Transitive _ _ _) (SAddEdge SNoEdges m))\n    |};\n    abstract (t_with t'; unfold RelationsEquivalent in *; apply forall__eq; t_with t'; destruct_hypotheses; subst;\n      t_with t'; repeat eexists (AddEdge NoEdges _); eauto; t_with t'; t_rev_with t').\n  Defined.\n\n  Definition sautrate_unsaturate_roundtrip_category : Category := ComputableCategory\n    (fun b => match b with\n                | true => C\n                | false => saturate (unsaturate C)\n              end).\n\n  Definition sautrate_unsaturate_functor_to_morphism : Morphism sautrate_unsaturate_roundtrip_category true false := sautrate_unsaturate_functor_to.\n\n  Section chooser.\n    Variable chooser : forall s d, forall cls : EquivalenceClass (SPathsEquivalent (unsaturate C) s d),\n      { m : _ | exists v, m = scompose_morphism_path C v /\\ InClass cls v }.\n\n    Ltac simpl_chooser :=\n      repeat match goal with\n               | [ |- context[proj1_sig (chooser ?m)] ] =>\n                 let hyp := constr:(proj2_sig (chooser m)) in\n                   let T := type of hyp in\n                     match goal with\n                       | [ H : T |- _ ] => fail 1\n                       | _ => let H := fresh in assert (H := hyp)\n                     end\n             end; simpl in *.\n\n  (* XXX TODO: Automate this better. *)\n    Definition sautrate_unsaturate_functor_from : SmallFunctor (saturate (unsaturate C)) C.\n      refine {| SObjectOf := (fun x : saturate (unsaturate C) => x : C);\n        SMorphismOf := (fun s d m => proj1_sig (chooser m))\n      |};\n      abstract (\n        repeat simpl in *; intros; unfold RelationsEquivalent in *;\n          simpl_chooser; destruct_hypotheses;\n          clear_InClass; unfold equiv in *; t_with t'\n      ).\n    Defined.\n\n    Lemma sautrate_unsaturate_roundtrip_natural_equivalence' : CategoriesNaturallyEquivalent C (saturate (unsaturate C)).\n      unfold CategoriesNaturallyEquivalent.\n      exists sautrate_unsaturate_functor_to.\n      exists sautrate_unsaturate_functor_from.\n      split;\n        match goal with\n          | [ |- FunctorsNaturallyEquivalent ?F ?G ] => cut (F = G);\n            try solve [ let H := fresh in intro H; rewrite H; reflexivity ]\n        end; functor_eq; simpl_chooser; destruct_hypotheses; try apply forall__eq; repeat split; intros; simpl in *;\n        clear_InClass; unfold equiv, RelationsEquivalent in *; simpl in *; t_with t'; t_rev_with t'.\n    Qed.\n\n    Lemma sautrate_unsaturate_roundtrip' : @CategoryIsomorphism sautrate_unsaturate_roundtrip_category _ _\n      (sautrate_unsaturate_functor_to : Morphism sautrate_unsaturate_roundtrip_category true false).\n      simpl; unfold CategoryIsomorphism'.\n      exists sautrate_unsaturate_functor_from.\n      split; simpl; sfunctor_eq; simpl_chooser;\n        destruct_hypotheses; unfold equiv, RelationsEquivalent in *; simpl in *; t_with t';\n        apply forall__eq; intros; split; intros; replace_InClass; unfold equiv, RelationsEquivalent in *; simpl in *;\n          autorewrite with core in *; assumption.\n    Qed.\n  End chooser.\n\n  Section chooser'.\n    Ltac simpl_chooser chooser :=\n      repeat match goal with\n               | [ |- context[proj1_sig (chooser ?s ?d ?m)] ] =>\n                 let hyp := constr:(proj2_sig (chooser s d m)) in\n                   let T := type of hyp in\n                     match goal with\n                       | [ H : T |- _ ] => fail 1\n                       | _ => let H := fresh in assert (H := hyp)\n                     end\n             end; simpl in *; t_rev_with t'.\n\n    Lemma sautrate_unsaturate_functor_from_unique chooser chooser'\n      : sautrate_unsaturate_functor_from chooser = sautrate_unsaturate_functor_from chooser'.\n      unfold sautrate_unsaturate_functor_from.\n      sfunctor_eq; simpl_chooser chooser; simpl_chooser chooser'; destruct_hypotheses;\n      clear_InClass; unfold equiv, RelationsEquivalent in *; t_with t'.\n    Qed.\n\n    Lemma sat_unsat_exist_helper'' A B : forall f : A -> B, f = (fun x => f x).\n      intros; apply functional_extensionality_dep; intros; reflexivity.\n    Qed.\n\n    Lemma sat_unsat_exist_helper' A (f f' : A -> Prop) x x' H H' H'' : f = f' -> exist f x H = exist f x' H' -> exist f x H ~= exist f' x' H''.\n      intros H0 H1; etransitivity; eauto.\n      subst.\n      assert (H' = H'') by (apply proof_irrelevance).\n      subst.\n      rewrite H1; clear H1.\n      reflexivity.\n    Qed.\n\n    Lemma sat_unsat_exist_helper A (f : A -> Prop) x x' H H' : exist f x H = exist f x' H' -> exist f x H = exist (fun v => f v) x' H'.\n      intros; apply JMeq_eq; eapply sat_unsat_exist_helper'; eauto;\n        apply sat_unsat_exist_helper''.\n    Qed.\n\n    Lemma sat_unsat_exist_helper2 A (f : A -> Prop) x x' H H' : x = x' -> exist f x H = exist f x' H'.\n      intro; repeat subst; f_equal; apply proof_irrelevance.\n    Qed.\n\n    (* XXX TODO: Automate this better. *)\n    Lemma sautrate_unsaturate_functor_from_exists' :\n      forall s d, forall cls : EquivalenceClass (SPathsEquivalent (unsaturate C) s d),\n        exists! choice : { m : _ | exists v, m = scompose_morphism_path C v /\\ InClass cls v }, True.\n      intros s d cls.\n      destruct (ClassInhabited cls) as [ x H ].\n      simpl.\n      eexists (exist _ (scompose_morphism_path C x) (ex_intro _ x (conj (eq_refl _) H))).\n      constructor; trivial; intros x' ?.\n      destruct x' as [ x' H' ].\n      destruct_hypotheses; simpl in *.\n      subst x'.\n      apply sat_unsat_exist_helper2; replace_InClass; assumption.\n    Qed.\n\n    Lemma sautrate_unsaturate_functor_from_chooser_unique\n      (chooser chooser' : forall s d\n        (cls : EquivalenceClass ((SPathsEquivalent (unsaturate C)) s d)),\n        { m : _ | exists v, m = scompose_morphism_path C v /\\ InClass cls v}) :\n      chooser = chooser'.\n    Proof.\n      repeat (apply functional_extensionality_dep; intro).\n      destruct chooser, chooser'; destruct_hypotheses.\n      apply sat_unsat_exist_helper2; clear_InClass;\n        unfold equiv, RelationsEquivalent, SPathsEquivalent', unsaturate in *; simpl in *; t_with t'.\n    Qed.\n\n    Lemma chooser_helper s d (cls : EquivalenceClass ((SPathsEquivalent (unsaturate C)) s d)) : (exists _ :\n      forall s' d' (cls' : EquivalenceClass ((SPathsEquivalent (unsaturate C)) s' d')),\n        s = s' -> d = d' -> cls ~= cls' ->\n        { m : _ | exists v, m = scompose_morphism_path C v /\\ InClass cls' v}, True).\n    Proof.\n      destruct (ClassInhabited cls) as [ x H ].\n      constructor; intros; repeat subst; trivial.\n      exists (scompose_morphism_path C x); exists x; split; trivial.\n    Qed.\n\n    (* [Require Import] here, because otherwise [sat_unsat_exist_helper2]\n       depends on [classic], because [classic |- proof_irrelevance] *)\n    Require Import ClassicalUniqueChoice.\n\n    Lemma dependent_unique_choice_unique : forall (A : Type) (B : A -> Type) (R : forall x, B x -> Prop),\n      (forall x : A, exists! y, R x y) ->\n      exists! f : (forall x, B x), forall x, R x (f x).\n      intros A B R H.\n      destruct (dependent_unique_choice _ _ _ H) as [ f ].\n      exists f; split; try assumption.\n      intros f' ?.\n      apply functional_extensionality_dep; intro x.\n      repeat match goal with\n               | [ H : forall _ : A, _ |- _ ] => specialize (H x)\n             end.\n      destruct H as [ y [ H'0 H'1 ] ].\n      pose (H'1 (f x)); pose (H'1 (f' x)).\n      intuition.\n      etransitivity; symmetry; eauto.\n    Qed.\n\n    Lemma dependent_unique_choice_unique_true : forall (A : Type) (B : A -> Type),\n      (forall x : A, exists! y : B x, True) ->\n      exists! f : (forall x, B x), True.\n      intros A B H.\n      destruct (dependent_unique_choice _ _ _ H) as [ f ].\n      exists f; split; trivial.\n      intros f' ?.\n      apply functional_extensionality_dep; intro x.\n      repeat match goal with\n               | [ H : forall _ : A, _ |- _ ] => specialize (H x)\n             end.\n      destruct H as [ y [ H'0 H'1 ] ].\n      pose (H'1 (f x)); pose (H'1 (f' x)).\n      intuition.\n      etransitivity; symmetry; eauto.\n    Qed.\n\n    Lemma chooser_exists : exists! _ : (forall s d\n      (cls : EquivalenceClass ((SPathsEquivalent (unsaturate C)) s d)),\n      { m : _ | exists v, m = scompose_morphism_path C v /\\ InClass cls v }), True.\n      repeat match goal with\n               | [ |- exists! _ : (forall s : ?T, @?f s), True ] => cut (forall s : T, exists! _ : f s, True);\n                 try solve [ let H := fresh in intro H; exact (@dependent_unique_choice_unique_true _ _ H) ];\n                   intros\n             end.\n      apply sautrate_unsaturate_functor_from_exists'.\n    Qed.\n  End chooser'.\n\n  Theorem sautrate_unsaturate_roundtrip_natrual_equivalence : CategoriesNaturallyEquivalent (saturate (unsaturate C)) C.\n    destruct chooser_exists as [ chooser H ].\n    symmetry. exact (sautrate_unsaturate_roundtrip_natural_equivalence' chooser).\n  Qed.\n\n\n  Theorem sautrate_unsaturate_roundtrip : @CategoryIsomorphism' sautrate_unsaturate_roundtrip_category _ _\n    (sautrate_unsaturate_functor_to : Morphism sautrate_unsaturate_roundtrip_category true false).\n    destruct chooser_exists as [ chooser H ].\n    apply CategoryIsomorphism2Isomorphism'. exact (sautrate_unsaturate_roundtrip' chooser).\n  Qed.\nEnd CategorySchemaCategory_RoundTrip.\n\nSection SchemaCategorySchema_RoundTrip.\n  Variable C : SmallSchema.\n\n  Hint Rewrite sconcatenate_noedges_p sconcatenate_p_noedges sconcatenate_addedge.\n  Hint Rewrite <- sconcatenate_prepend_equivalent.\n  Hint Rewrite sconcatenate_associative.\n\n  Hint Extern 1 (@RelationsEquivalent _ _ _ (SPathsEquivalent _) _ _ _ _) => apply saddedge_equivalent.\n  Hint Extern 1 (@RelationsEquivalent _ _ _ (SPathsEquivalent _) _ _ _ _) => apply SPreCompose.\n\n  Hint Rewrite sconcatenate_p_noedges sconcatenate_noedges_p sconcatenate_associative.\n\n  Ltac replace_noedges' :=\n    match goal with\n      | [ H : ?rel NoEdges ?x |- _ ] => rewrite <- H in *; clear H\n      | [ H : ?rel SNoEdges ?x |- _ ] => rewrite <- H in *; clear H\n      | [ H : ?rel ?x NoEdges |- _ ] => rewrite H in *; clear H\n      | [ H : ?rel ?x SNoEdges |- _ ] => rewrite H in *; clear H\n    end.\n\n  Ltac replace_noedges :=\n        repeat replace_noedges'; repeat (rewrite sconcatenate_p_noedges in * || rewrite sconcatenate_noedges_p in *).\n\n  Ltac clear_paths :=\n    repeat match goal with\n             | [ H : spath' _ _ _ |- _ ] => subst H || clear H\n           end.\n\n  Ltac replace_paths_equivalent' :=\n    try replace_noedges;\n      try solve [ assumption || symmetry; assumption ];\n        clear_paths;\n        repeat match goal with\n                 | [ H : context[SPathsEquivalent] |- _ ] => rewrite <- H in *; clear H\n               end; clear_paths; repeat rewrite sconcatenate_associative in *; try reflexivity || symmetry;\n        repeat match goal with\n                 | [ H : context[SPathsEquivalent] |- _ ] => rewrite H in *; clear H\n               end; clear_paths; repeat rewrite sconcatenate_associative in *; try reflexivity || symmetry.\n\n\n  Hint Rewrite scompose_morphism_path_alt.\n\n  Hint Rewrite SLeftIdentity SRightIdentity.\n  Hint Rewrite scompose_morphism_path_distr.\n\n  Definition unsaturate_saturate_translation_to_PathOf s d (e : C.(SEdge) s d) : spath (unsaturate (saturate C)) s d :=\n    SAddEdge SNoEdges (@classOf (spath' _ s d) _ (Reflexive _ _ _) (Symmetric _ _ _) (Transitive _ _ _) (SAddEdge SNoEdges e)).\n\n  Hint Unfold unsaturate_saturate_translation_to_PathOf.\n\n  Lemma unsaturate_saturate_translation_to_PathOf_InClass s d (p : spath C s d) :\n    InClass (scompose_morphism_path (saturate C) (stransferPath _ unsaturate_saturate_translation_to_PathOf p)) p.\n    induction p; simpl; repeat esplit; try reflexivity; t_with t'; try apply AddEdge_mor; try reflexivity; assumption.\n  Qed.\n\n  Hint Rewrite sconcatenate_p_addedge.\n  Hint Resolve unsaturate_saturate_translation_to_PathOf_InClass.\n\n  Ltac unsaturate_saturate_translation_to_PathOf_InClass' :=\n    unfold path, spath in *;\n    match goal with\n      | [ H : InClass ?C _, p : spath' _ _ _ |- _ ] =>\n        assert (InClass C p) by (apply unsaturate_saturate_translation_to_PathOf_InClass);\n          clear_InClass; unfold equiv in *;\n            try match goal with\n                  | [ H : InClass C _, H' : context[C] |- _ ] => fail 1\n                  | [ H : InClass C _ |- context[C] ] => fail 1\n                  | [ H : InClass C _ |- _ ] => clear H\n                  | _ => idtac\n                end\n      | [ p : spath' _ _ _ |- InClass ?C _ ] =>\n        assert (InClass C p) by (apply unsaturate_saturate_translation_to_PathOf_InClass);\n          clear_InClass; unfold equiv in *\n    end.\n\n  Ltac unsaturate_saturate_translation_to_PathOf_InClass := repeat unsaturate_saturate_translation_to_PathOf_InClass'.\n\n  Lemma unsaturate_saturate_translation_to_PathOf_equivalent s d (p : spath C s d) :\n    SPathsEquivalent _ _ _ (stransferPath _ unsaturate_saturate_translation_to_PathOf p)\n    (SAddEdge SNoEdges (@classOf (spath' _ s d) _ (Reflexive _ _ _) (Symmetric _ _ _) (Transitive _ _ _) p)).\n    induction p; unfold RelationsEquivalent, unsaturate_saturate_translation_to_PathOf in *; simpl;\n    apply forall__eq; intros; split; intros; simpl in *; destruct_hypotheses; replace_noedges; repeat esplit; try reflexivity;\n      eauto; autorewrite with core in *;\n        try solve [ eauto || symmetry; eauto || etransitivity; eauto; try (symmetry; eauto) ];\n          repeat match goal with\n                   | [ H : context[@eq] |- _ ] => clear H\n                 end.\n    unsaturate_saturate_translation_to_PathOf_InClass.\n    replace_paths_equivalent'.\n  Qed.\n\n  Definition unsautrate_saturate_translation_to : SmallTranslation C (unsaturate (saturate C)).\n    refine {| SVertexOf := (fun x : C => x : (unsaturate (saturate C)));\n      SPathOf := unsaturate_saturate_translation_to_PathOf (* (fun s d e => AddEdge NoEdges (@classOf (path' _ s d) _ (Reflexive _ _ _) (Symmetric _ _ _) (Transitive _ _ _) (AddEdge NoEdges e))) *)\n    |};\n    abstract (\n      t_with t'; unfold RelationsEquivalent, unsaturate_saturate_translation_to_PathOf in *; apply forall__eq; t_with t';\n        unsaturate_saturate_translation_to_PathOf_InClass;\n        solve [ assumption || symmetry; assumption || etransitivity; eauto; symmetry; eauto ]\n    ).\n  Defined.\n\n  Lemma unsaturate_saturate_cmp_eq_eqv s d (p1 p2 : spath (unsaturate (saturate C)) s d) :\n    (scompose_morphism_path (saturate C) p1 = scompose_morphism_path (saturate C) p2) =\n    (SPathsEquivalent _ _ _ p1 p2).\n    simpl; unfold RelationsEquivalent in *; trivial.\n  Qed.\n\n  Definition unsautrate_saturate_roundtrip_category : Category := ComputableSchemaCategory\n    (fun b => match b with\n                | true => C\n                | false => unsaturate (saturate C)\n              end).\n\n  Section chooser.\n    Variable chooser : forall s d, forall cls : EquivalenceClass ((SPathsEquivalent C) s d),\n      { p : _ | InClass cls p }.\n\n    Ltac simpl_chooser :=\n      repeat match goal with\n               | [ |- context[proj1_sig (chooser ?m)] ] =>\n                 let hyp := constr:(proj2_sig (chooser m)) in\n                   let T := type of hyp in\n                     match goal with\n                       | [ H : T |- _ ] => fail 1\n                       | _ => let H := fresh in assert (H := hyp); try rewrite <- H in *\n                     end\n             end; simpl in *; trivial.\n\n    Ltac simpl_chooser_more := simpl_chooser;\n      repeat match goal with\n               | [ H : context[proj1_sig (chooser ?m)] |- _ ] =>\n                 let hyp := constr:(proj2_sig (chooser m)) in\n                   let T := type of hyp in\n                     match goal with\n                       | [ H : T |- _ ] => fail 1\n                       | _ => let H := fresh in assert (H := hyp); try rewrite <- H in *\n                     end\n             end; simpl in *; trivial.\n\n    Definition unsaturate_saturate_translation_from_PathOf s d (e : Edge (unsaturate (saturate C)) s d) : path C s d :=\n      proj1_sig (chooser e).\n\n    Hint Unfold unsaturate_saturate_translation_from_PathOf.\n\n    Lemma unsaturate_saturate_translation_from_PathOf_eqv s d (p : spath (unsaturate (saturate C)) s d) :\n      SPathsEquivalent _ _ _\n      (stransferPath _ (fun s d (e : SEdge (unsaturate (saturate C)) s d) => proj1_sig (chooser e)) p)\n      (proj1_sig (chooser (scompose_morphism_path (saturate C) p))).\n      induction p; simpl in *; simpl_chooser_more.\n      destruct_hypotheses; clear_InClass.\n      unfold equiv in *.\n      repeat_subst_mor_of_type @spath'.\n      match goal with\n        | [ H : _ |- _ ] => rewrite H; apply sconcatenate_mor; eauto\n      end.\n    Qed.\n\n    Hint Rewrite sconcatenate_p_addedge.\n    Hint Resolve unsaturate_saturate_translation_from_PathOf_eqv.\n\n    Definition unsautrate_saturate_translation_from : SmallTranslation (unsaturate (saturate C)) C.\n      refine {| SVertexOf := (fun x : unsaturate (saturate C) => x : C);\n        SPathOf := (fun s d e => proj1_sig (chooser e))\n      |};\n      abstract (\n        repeat simpl in *; intros; unfold RelationsEquivalent in *;\n          do 2 (etransitivity; try apply unsaturate_saturate_translation_from_PathOf_eqv; symmetry);\n            match goal with\n              | [ H : _ |- _ ] => rewrite H; reflexivity\n            end\n      ).\n    Defined.\n\n    Hint Rewrite apply2_to_classOf unsaturate_saturate_translation_to_PathOf_equivalent.\n\n    (* TODO: Simplify this proof. *)\n    Lemma unsautrate_saturate_roundtrip' : @CategoryIsomorphism unsautrate_saturate_roundtrip_category _ _\n      (@classOf _ _ (@SmallTranslationsEquivalent_refl _ _) (@SmallTranslationsEquivalent_sym _ _) (@SmallTranslationsEquivalent_trans _ _)\n        unsautrate_saturate_translation_to : Morphism unsautrate_saturate_roundtrip_category true false).\n      eexists (@classOf _ _ (@SmallTranslationsEquivalent_refl _ _) (@SmallTranslationsEquivalent_sym _ _) (@SmallTranslationsEquivalent_trans _ _)\n        unsautrate_saturate_translation_from).\n      split; stranslation_eq; rewrite apply2_to_classOf;\n        apply forall__eq; intros; split; intros;\n          clear_InClass; unfold equiv in *;\n            repeat_subst_mor_of_type @SmallTranslation;\n            repeat esplit; intros; eauto; try reflexivity; simpl in *; autorewrite with core in *;\n              unfold RelationsEquivalent in *;\n                unfold STransferPath, unsautrate_saturate_translation_to, unsautrate_saturate_translation_from in *;\n                  simpl; try rewrite unsaturate_saturate_translation_to_PathOf_equivalent;\n                    autorewrite with core in *;\n                      simpl_chooser; auto; try solve [ symmetry; auto ];\n                        simpl;\n                          autorewrite with core;\n                            apply forall__eq; intros; split; intros; simpl in *; destruct_hypotheses; auto;\n                              repeat (clear_InClass; eexists; eauto; try reflexivity); clear_InClass;\n                                unfold equiv in *; auto;\n                                  repeat_subst_mor_of_type @spath'; autorewrite with core; reflexivity.\n    Qed.\n  End chooser.\n\n  Section chooser'.\n    Ltac simpl_chooser chooser :=\n      repeat match goal with\n               | [ |- context[proj1_sig (chooser ?s ?d ?m)] ] =>\n                 let hyp := constr:(proj2_sig (chooser s d m)) in\n                   let T := type of hyp in\n                     match goal with\n                       | [ H : T |- _ ] => fail 1\n                       | _ => let H := fresh in assert (H := hyp)\n                     end\n             end; simpl in *; t_rev_with t'.\n\n    Lemma unsautrate_saturate_translation_from_unique chooser chooser'\n      : SmallTranslationsEquivalent (unsautrate_saturate_translation_from chooser) (unsautrate_saturate_translation_from chooser').\n      unfold unsautrate_saturate_translation_from.\n      stranslation_eqv; simpl_chooser chooser; simpl_chooser chooser'; destruct_hypotheses;\n      clear_InClass; unfold equiv, RelationsEquivalent in *; t_with t'.\n    Qed.\n\n    (* XXX TODO: Automate this better. *)\n    Lemma unsautrate_saturate_translation_from_exists' :\n      forall s d, forall cls : EquivalenceClass ((SPathsEquivalent C) s d),\n        exists choice : { p : _ | InClass cls p }, True.\n      intros s d cls.\n      destruct (ClassInhabited cls) as [ x H ].\n      simpl.\n      eexists (exist _ x H).\n      trivial.\n    Qed.\n\n    Require Import IndefiniteDescription.\n\n    Lemma unsat_sat_chooser_exists : exists _ : (forall s d\n      (cls : EquivalenceClass ((SPathsEquivalent C) s d)),\n      { p : _ | InClass cls p }), True.\n      constructor; trivial; intros s d cls.\n      apply constructive_indefinite_description.\n      destruct (unsautrate_saturate_translation_from_exists' cls) as [ [ p H ] ].\n      eexists; eauto.\n    Qed.\n  End chooser'.\n\n  Theorem unsautrate_saturate_roundtrip : @CategoryIsomorphism' unsautrate_saturate_roundtrip_category _ _\n    (@classOf _ _ (@SmallTranslationsEquivalent_refl _ _) (@SmallTranslationsEquivalent_sym _ _) (@SmallTranslationsEquivalent_trans _ _)\n      unsautrate_saturate_translation_to : Morphism unsautrate_saturate_roundtrip_category true false).\n    destruct unsat_sat_chooser_exists as [ chooser H ].\n    apply CategoryIsomorphism2Isomorphism'. exact (unsautrate_saturate_roundtrip' chooser).\n  Qed.\nEnd SchemaCategorySchema_RoundTrip.\n\nSection CatSchIsomorphic.\n  Section Cat2Sch.\n    Variable O : Type.\n    Variable Object2Cat : O -> Category.\n\n    Local Coercion Object2Cat : O >-> Category.\n\n    Set Printing Universes.\n(*    Definition Cat2Sch := ComputableSchemaCategory (fun o => unsaturate o).*)\n\n  End Cat2Sch.\nEnd CatSchIsomorphic.\n", "meta": {"author": "CategoricalData", "repo": "catdb", "sha": "ce74dd70c52116a29f4589fd8d12c6439181254e", "save_path": "github-repos/coq/CategoricalData-catdb", "path": "github-repos/coq/CategoricalData-catdb/catdb-ce74dd70c52116a29f4589fd8d12c6439181254e/CategorySchemaEquivalence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.27195984457650524}}
{"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 core 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 Hilecop utils. *)\n\n\n\n\n\n\n(** * Completeness of [update_time_intervals]. *)\n\nSection UpdateTimeIntervalsComplete.\n\n  (** Completeness lemma for [update_time_intervals]. *)\n\n  Lemma update_time_intervals_complete :\n    forall (sitpn : Sitpn)\n           (s s': SitpnState)\n           (time_value : nat)\n           (env : Condition -> nat -> bool)\n           (ditvals new_ditvals : list (Trans * DynamicTimeInterval)),\n      IsWellDefinedSitpn sitpn ->\n      IsWellDefinedSitpnState sitpn s ->\n      IsWellDefinedSitpnState sitpn s' ->\n      SitpnSemantics sitpn s s' time_value env falling_edge ->\n\n      (* Hypotheses on ditvals and new_ditvals. *)\n      IsDecListCons ditvals (d_intervals s) ->\n      Permutation (fs (new_ditvals ++ ditvals)) (fs (d_intervals s')) ->\n      incl new_ditvals (d_intervals s') ->\n      NoDup (fs (new_ditvals ++ ditvals)) ->\n\n      (* Conclusion. *)\n      exists ditvals' : list (Trans * DynamicTimeInterval),\n        update_time_intervals sitpn s ditvals new_ditvals = Some ditvals'\n        /\\ Permutation ditvals' (d_intervals s').\n  Proof.\n    intros sitpn s s' time_value env ditvals.\n    induction ditvals;\n      intros new_ditvals Hwell_def_sitpn Hwell_def_s Hwell_def_s'\n             Hspec His_dec_list Hperm_app Hincl_newd Hnodup_fs_newd.\n\n    (* BASE CASE, ditvals = []. *)\n    - simpl; exists new_ditvals; split.\n\n      (* Proves equality. *)\n      + trivial.\n\n      (* Proves Permutation new_ditvals (d_intervals s'). \n         Strategy: use lemma [permutation_fs_permutation]. *)\n      +\n        (* Builds premises to apply [permutation_fs_permutation] *)\n\n        (* Builds NoDup (fs new_ditvals) *)\n\n        rewrite app_nil_r in Hnodup_fs_newd.\n\n        (* Builds NoDup (fs (d_intervals s')) *)\n\n        explode_well_defined_sitpn_state Hwell_def_s'.\n        assert (H := Hnodup_state_ditvals).\n        clear_well_defined_sitpn_state.\n        rename Hnodup_state_ditvals into Hnodup_fs_ditvals_s'.\n\n        (* Builds Permutation (fs new_ditvals) (fs (d_intervals s')) *)\n\n        rewrite app_nil_r in Hperm_app.\n\n        (* Applies [permutation_fs_permutation]. *)\n\n        apply (permutation_fs_permutation\n                 new_ditvals (d_intervals s') Hnodup_fs_newd Hnodup_fs_ditvals_s'\n                 Hincl_newd Hperm_app).\n\n    (* INDUCTION CASE. *)\n    - simpl; destruct a; case_eq (s_intervals sitpn t).\n\n      (* CASE (s_intervals sitpn t) = Some stc_itval *)\n      + intros sitval Heq_some_sitval.\n        case_eq (is_sensitized sitpn (marking s) (lneighbours sitpn t) t).\n\n        (* CASE (is_sensitized sitpn (marking s) (lneighbours sitpn t) t) = Some b *)\n        * intros b His_sens; destruct b.\n           \n          (* CASE (is_sensitized sitpn (marking s) (lneighbours sitpn t) t) = Some true *)\n          -- case_eq (in_list Nat.eq_dec (fired s) t); intros Hin_list.\n\n             (* CASE in_list Nat.eq_dec (fired s) t = true *)\n             ++ specialize (IHditvals (new_ditvals ++ [(t, active (dec_itval sitval))])).\n\n                (* Strategy: apply IHditvals, then we need premises. *)\n\n                (* Builds incl (new_ditvals ++ [(t, active (dec_itval sitval))]) (d_intervals s') \n                   To do that, we need to show (t, active (dec_itval sitval)) ∈ (d_intervals s') using\n                   Hspec.\n                 *)\n                assert (Hin_t_ditvalss' : In (t, active (dec_itval sitval)) (d_intervals s')).\n                {\n                  \n                  (* Strategy: get the right Sitpn semantics rule from\n                               Hspec and specialize it. *)\n                  inversion Hspec.\n                  clear H H0 H1 H2 H3 H4 H5 H6 H8 H9 H10 H11 H12 H13.\n                  rename H7 into Hsens_and_fired_reset.\n\n                  (* Gets In t (fs (d_intervals s)) *)\n                  deduce_in_from_is_dec_list_cons His_dec_list as Hin_t_fs_ditvals.\n                  apply in_fst_split in Hin_t_fs_ditvals.\n\n                  (* Gets In (t, true) (reset s) \\/ In t (fired s) *)\n                  specialize (in_list_correct Nat.eq_dec (fired s) t Hin_list) as Hin_fired.\n                  specialize (or_intror (In (t, true) (reset s)) Hin_fired) as Hreset_or_fired.\n\n                  (* Gets IsSensitized /\\ (In (t, true) (reset s) \\/ In t (fired s)) \n                     by specializing is_sensitized_correct. *)\n\n                  assert (Hin_t_transs := Hin_t_fs_ditvals).\n                  explode_well_defined_sitpn_state Hwell_def_s.\n                  rewrite <- (Hwf_state_ditvals t) in Hin_t_transs.\n                  apply proj1 in Hin_t_transs.\n\n                  specialize (is_sensitized_correct\n                                (marking s) t Hwell_def_sitpn\n                                Hwf_state_marking Hin_t_transs His_sens)\n                    as His_sens_spec.\n\n                  clear_well_defined_sitpn_state.\n                  specialize (conj His_sens_spec Hreset_or_fired) as Hw_sens_fired.\n\n                  (* Gets ~IsSensitized \\/ ... *)\n                  specialize (or_intror (~ IsSensitized sitpn (marking s) t) Hw_sens_fired)\n                    as Hv_notsens_sens.\n\n                  symmetry in Heq_some_sitval.\n                  apply (Hsens_and_fired_reset t sitval Hin_t_fs_ditvals Hv_notsens_sens\n                                               Heq_some_sitval).\n                }\n                \n                (* Then, we can deduce incl (new_ditvals ++ [(t, active (dec_itval sitval))]) (d_intervals s') *)\n                assert (Hincl_newd_app : incl (new_ditvals ++ [(t, active (dec_itval sitval))]) (d_intervals s')).\n                {\n                  intros x Hin_app.\n                  apply in_app_or in Hin_app.\n                  inversion_clear Hin_app as [Hin_x_newd | Heq_x_t];\n                    [ apply (Hincl_newd x Hin_x_newd) |\n                      inversion_clear Heq_x_t as [Heq | Hin_nil];\n                      [ rewrite <- Heq; assumption |\n                        inversion Hin_nil\n                      ]\n                    ].\n                }\n\n                (* Builds IsDecListCons ditvals (d_intervals s) *)\n                apply is_dec_list_cons_cons in His_dec_list.\n                \n                (* Builds Permutation and NoDup hyps by rewriting IH. *) \n\n                unfold fs in Hperm_app.\n                rewrite fst_split_app in Hperm_app.\n                rewrite fst_split_cons_app in Hperm_app.\n                simpl in Hperm_app.\n\n                unfold fs in Hnodup_fs_newd.\n                rewrite fst_split_app in Hnodup_fs_newd.\n                rewrite fst_split_cons_app in Hnodup_fs_newd.\n                simpl in Hnodup_fs_newd.\n                \n                unfold fs in IHditvals.\n                rewrite fst_split_app in IHditvals.\n                rewrite fst_split_app in IHditvals.\n                simpl in IHditvals.\n\n                rewrite <- app_assoc in IHditvals.\n\n                (* Applies IHditvals *)\n                apply (IHditvals Hwell_def_sitpn Hwell_def_s Hwell_def_s' Hspec\n                                 His_dec_list Hperm_app Hincl_newd_app Hnodup_fs_newd).\n\n             (* CASE in_list Nat.eq_dec (fired s) t = false *)\n             ++ case_eq (get_value Nat.eq_dec t (reset s)).\n\n                (* CASE (get_value Nat.eq_dec t (reset s)) = Some b *)\n                ** intros b Hget_v_some; destruct b.\n\n                   (* CASE (get_value Nat.eq_dec t (reset s)) = Some true *)\n                   --- specialize (IHditvals (new_ditvals ++ [(t, active (dec_itval sitval))])).\n\n                       (* Strategy: apply IHditvals, then we need premises. *)\n\n                       (* Builds incl (new_ditvals ++ [(t, active (dec_itval sitval))]) (d_intervals s') \n                          To do that, we need to show (t, active (dec_itval sitval)) ∈ (d_intervals s') using\n                          Hspec.\n                        *)\n                       assert (Hin_t_ditvalss' : In (t, active (dec_itval sitval)) (d_intervals s')).\n                       {\n                         \n                         (* Strategy: get the right Sitpn semantics rule from\n                               Hspec and specialize it. *)\n                         inversion Hspec.\n                         clear H H0 H1 H2 H3 H4 H5 H6 H8 H9 H10 H11 H12 H13.\n                         rename H7 into Hsens_and_fired_reset.\n\n                         (* Gets In t (fs (d_intervals s)) *)\n                         deduce_in_from_is_dec_list_cons His_dec_list as Hin_t_fs_ditvals.\n                         apply in_fst_split in Hin_t_fs_ditvals.\n\n                         (* Gets In (t, true) (reset s) \\/ In t (fired s) *)\n                         specialize (get_value_correct Nat.eq_dec t (reset s) Hget_v_some) as Hin_ttrue_reset.\n                         specialize (or_introl (In t (fired s)) Hin_ttrue_reset) as Hreset_or_fired.\n\n                         (* Gets IsSensitized /\\ (In (t, true) (reset s) \\/ In t (fired s)) \n                            by specializing is_sensitized_correct. *)\n\n                         assert (Hin_t_transs := Hin_t_fs_ditvals).\n                         explode_well_defined_sitpn_state Hwell_def_s.\n                         rewrite <- (Hwf_state_ditvals t) in Hin_t_transs.\n                         apply proj1 in Hin_t_transs.\n\n                         specialize (is_sensitized_correct\n                                       (marking s) t Hwell_def_sitpn\n                                       Hwf_state_marking Hin_t_transs His_sens)\n                           as His_sens_spec.\n\n                         clear_well_defined_sitpn_state.\n                         specialize (conj His_sens_spec Hreset_or_fired) as Hw_sens_fired.\n\n                         (* Gets ~IsSensitized \\/ ... *)\n                         specialize (or_intror (~ IsSensitized sitpn (marking s) t) Hw_sens_fired)\n                           as Hv_notsens_sens.\n\n                         symmetry in Heq_some_sitval.\n                         apply (Hsens_and_fired_reset t sitval Hin_t_fs_ditvals Hv_notsens_sens\n                                                      Heq_some_sitval).\n                       }\n                       \n                       (* Then, we can deduce incl (new_ditvals ++ [(t, active (dec_itval sitval))]) (d_intervals s') *)\n                       assert (Hincl_newd_app : incl (new_ditvals ++ [(t, active (dec_itval sitval))]) (d_intervals s')).\n                       {\n                         intros x Hin_app.\n                         apply in_app_or in Hin_app.\n                         inversion_clear Hin_app as [Hin_x_newd | Heq_x_t];\n                           [ apply (Hincl_newd x Hin_x_newd) |\n                             inversion_clear Heq_x_t as [Heq | Hin_nil];\n                             [ rewrite <- Heq; assumption |\n                               inversion Hin_nil\n                             ]\n                           ].\n                       }\n\n                       (* Builds IsDecListCons ditvals (d_intervals s) *)\n                       apply is_dec_list_cons_cons in His_dec_list.\n                       \n                       (* Builds Permutation and NoDup hyps by rewriting IH. *) \n\n                       unfold fs in Hperm_app.\n                       rewrite fst_split_app in Hperm_app.\n                       rewrite fst_split_cons_app in Hperm_app.\n                       simpl in Hperm_app.\n\n                       unfold fs in Hnodup_fs_newd.\n                       rewrite fst_split_app in Hnodup_fs_newd.\n                       rewrite fst_split_cons_app in Hnodup_fs_newd.\n                       simpl in Hnodup_fs_newd.\n                       \n                       unfold fs in IHditvals.\n                       rewrite fst_split_app in IHditvals.\n                       rewrite fst_split_app in IHditvals.\n                       simpl in IHditvals.\n\n                       rewrite <- app_assoc in IHditvals.\n\n                       (* Applies IHditvals *)\n                       apply (IHditvals Hwell_def_sitpn Hwell_def_s Hwell_def_s' Hspec\n                                        His_dec_list Hperm_app Hincl_newd_app Hnodup_fs_newd).\n                       \n                   (* CASE (get_value Nat.eq_dec t (reset s)) = Some false *)\n                   --- destruct d.\n\n                       (* CASE d = active t0 *)\n                       +++ specialize (IHditvals (new_ditvals ++ [(t, active (dec_itval t0))])).\n\n                           (* Strategy: apply IHditvals, then we need premises. *)\n\n                           (* Builds incl (new_ditvals ++ [(t, active (dec_itval t0))]) (d_intervals s') \n                              To do that, we need to show (t, active (dec_itval t0)) ∈ (d_intervals s') using\n                              Hspec.\n                            *)\n                           assert (Hin_t_ditvalss' : In (t, active (dec_itval t0)) (d_intervals s')).\n                           {\n                             \n                             (* Strategy: get the right Sitpn semantics rule from\n                                          Hspec and specialize it. *)\n                             inversion Hspec.\n                             clear H H0 H1 H2 H3 H4 H5 H6 H7 H9 H10 H11 H12.\n                             rename H8 into Hsens_and_notfired_reset.\n\n                             (* Gets In t (fs (d_intervals s)) *)\n                             deduce_in_from_is_dec_list_cons His_dec_list as Hin_t_ditvals.\n\n                             (* Gets IsSensitized by specializing is_sensitized_correct. *)\n                             assert (Hin_t_transs := Hin_t_ditvals).\n                             apply in_fst_split in Hin_t_transs.\n                             explode_well_defined_sitpn_state Hwell_def_s.\n                             rewrite <- (Hwf_state_ditvals t) in Hin_t_transs.\n                             apply proj1 in Hin_t_transs.\n\n                             specialize (is_sensitized_correct\n                                           (marking s) t Hwell_def_sitpn\n                                           Hwf_state_marking Hin_t_transs His_sens)\n                               as His_sens_spec.\n                             clear_well_defined_sitpn_state.\n                             \n                             (* Gets In (t, false) (reset s) *)\n                             specialize (get_value_correct Nat.eq_dec t (reset s) Hget_v_some) as Hin_tfalse_reset.\n\n                             (* Gets ~In t (fired s) *)\n                             specialize (not_in_list_correct Nat.eq_dec (fired s) t Hin_list) as Hnot_in_t_fired.\n\n                             apply (Hsens_and_notfired_reset t t0 Hin_t_ditvals His_sens_spec\n                                                             Hin_tfalse_reset Hnot_in_t_fired).\n                           }\n                           \n                           (* Then, we can deduce incl (new_ditvals ++ [(t, active (dec_itval t0))]) (d_intervals s') *)\n                           assert (Hincl_newd_app : incl (new_ditvals ++ [(t, active (dec_itval t0))]) (d_intervals s')).\n                           {\n                             intros x Hin_app.\n                             apply in_app_or in Hin_app.\n                             inversion_clear Hin_app as [Hin_x_newd | Heq_x_t];\n                               [ apply (Hincl_newd x Hin_x_newd) |\n                                 inversion_clear Heq_x_t as [Heq | Hin_nil];\n                                 [ rewrite <- Heq; assumption |\n                                   inversion Hin_nil\n                                 ]\n                               ].\n                           }\n\n                           (* Builds IsDecListCons ditvals (d_intervals s) *)\n                           apply is_dec_list_cons_cons in His_dec_list.\n                           \n                           (* Builds Permutation and NoDup hyps by rewriting IH. *) \n\n                           unfold fs in Hperm_app.\n                           rewrite fst_split_app in Hperm_app.\n                           rewrite fst_split_cons_app in Hperm_app.\n                           simpl in Hperm_app.\n\n                           unfold fs in Hnodup_fs_newd.\n                           rewrite fst_split_app in Hnodup_fs_newd.\n                           rewrite fst_split_cons_app in Hnodup_fs_newd.\n                           simpl in Hnodup_fs_newd.\n                           \n                           unfold fs in IHditvals.\n                           rewrite fst_split_app in IHditvals.\n                           rewrite fst_split_app in IHditvals.\n                           simpl in IHditvals.\n\n                           rewrite <- app_assoc in IHditvals.\n\n                           (* Applies IHditvals *)\n                           apply (IHditvals Hwell_def_sitpn Hwell_def_s Hwell_def_s' Hspec\n                                            His_dec_list Hperm_app Hincl_newd_app Hnodup_fs_newd).\n\n                       (* CASE d = blocked *)\n                       +++ specialize (IHditvals (new_ditvals ++ [(t, blocked)])).\n\n                           (* Strategy: apply IHditvals, then we need premises. *)\n\n                           (* Builds incl (new_ditvals ++ [(t, blocked)]) (d_intervals s') \n                              To do that, we need to show (t, blocked) ∈ (d_intervals s') using\n                              Hspec.\n                            *)\n                           assert (Hin_t_ditvalss' : In (t, blocked) (d_intervals s')).\n                           {\n                             \n                             (* Strategy: get the right Sitpn semantics rule from\n                                          Hspec and specialize it. *)\n                             inversion Hspec.\n                             clear H H0 H1 H2 H3 H4 H5 H6 H7 H8 H10 H11 H12 H13.\n                             rename H9 into Hsens_and_notfired_reset.\n\n                             (* Gets In t (fs (d_intervals s)) *)\n                             deduce_in_from_is_dec_list_cons His_dec_list as Hin_t_ditvals.\n\n                             (* Gets IsSensitized by specializing is_sensitized_correct. *)\n                             assert (Hin_t_transs := Hin_t_ditvals).\n                             apply in_fst_split in Hin_t_transs.\n                             explode_well_defined_sitpn_state Hwell_def_s.\n                             rewrite <- (Hwf_state_ditvals t) in Hin_t_transs.\n                             apply proj1 in Hin_t_transs.\n\n                             specialize (is_sensitized_correct\n                                           (marking s) t Hwell_def_sitpn\n                                           Hwf_state_marking Hin_t_transs His_sens)\n                               as His_sens_spec.\n                             clear_well_defined_sitpn_state.\n                             \n                             (* Gets In (t, false) (reset s) *)\n                             specialize (get_value_correct Nat.eq_dec t (reset s) Hget_v_some) as Hin_tfalse_reset.\n\n                             (* Gets ~In t (fired s) *)\n                             specialize (not_in_list_correct Nat.eq_dec (fired s) t Hin_list) as Hnot_in_t_fired.\n\n                             apply (Hsens_and_notfired_reset t Hin_t_ditvals His_sens_spec\n                                                             Hin_tfalse_reset Hnot_in_t_fired).\n                           }\n                           \n                           (* Then, we can deduce incl (new_ditvals ++ [(t, blocked)]) (d_intervals s') *)\n                           assert (Hincl_newd_app : incl (new_ditvals ++ [(t, blocked)]) (d_intervals s')).\n                           {\n                             intros x Hin_app.\n                             apply in_app_or in Hin_app.\n                             inversion_clear Hin_app as [Hin_x_newd | Heq_x_t];\n                               [ apply (Hincl_newd x Hin_x_newd) |\n                                 inversion_clear Heq_x_t as [Heq | Hin_nil];\n                                 [ rewrite <- Heq; assumption |\n                                   inversion Hin_nil\n                                 ]\n                               ].\n                           }\n\n                           (* Builds IsDecListCons ditvals (d_intervals s) *)\n                           apply is_dec_list_cons_cons in His_dec_list.\n                           \n                           (* Builds Permutation and NoDup hyps by rewriting IH. *) \n\n                           unfold fs in Hperm_app.\n                           rewrite fst_split_app in Hperm_app.\n                           rewrite fst_split_cons_app in Hperm_app.\n                           simpl in Hperm_app.\n\n                           unfold fs in Hnodup_fs_newd.\n                           rewrite fst_split_app in Hnodup_fs_newd.\n                           rewrite fst_split_cons_app in Hnodup_fs_newd.\n                           simpl in Hnodup_fs_newd.\n                           \n                           unfold fs in IHditvals.\n                           rewrite fst_split_app in IHditvals.\n                           rewrite fst_split_app in IHditvals.\n                           simpl in IHditvals.\n\n                           rewrite <- app_assoc in IHditvals.\n\n                           (* Applies IHditvals *)\n                           apply (IHditvals Hwell_def_sitpn Hwell_def_s Hwell_def_s' Hspec\n                                            His_dec_list Hperm_app Hincl_newd_app Hnodup_fs_newd).\n                         \n                (* CASE (get_value Nat.eq_dec t (reset s)) = None *)\n                ** intros Hget_v_reset.\n\n                   deduce_in_from_is_dec_list_cons His_dec_list as Hin_t_fs_reset.\n                   apply in_fst_split in Hin_t_fs_reset.\n                   explode_well_defined_sitpn_state Hwell_def_s.\n                   rewrite <- (Hwf_state_ditvals t) in Hin_t_fs_reset.\n                   rewrite (Hwf_state_reset t) in Hin_t_fs_reset.\n                   clear_well_defined_sitpn_state.\n\n                   specialize (get_value_no_error Nat.eq_dec t (reset s) Hin_t_fs_reset)\n                     as Hex_get_v.\n                   inversion_clear Hex_get_v as (value & Hget_v_some).\n                   rewrite Hget_v_reset in Hget_v_some.\n                   inversion Hget_v_some.\n\n          (* CASE (is_sensitized sitpn (marking s) (lneighbours sitpn t) t) = Some false *)\n          -- specialize (IHditvals (new_ditvals ++ [(t, active (dec_itval sitval))])).\n\n             (* Strategy: apply IHditvals, then we need premises. *)\n\n             (* Builds incl (new_ditvals ++ [(t, active (dec_itval sitval))]) (d_intervals s') \n                   To do that, we need to show (t, active (dec_itval sitval)) ∈ (d_intervals s') using\n                   Hspec.\n              *)\n             assert (Hin_t_ditvalss' : In (t, active (dec_itval sitval)) (d_intervals s')).\n             {\n               \n               (* Strategy: get the right Sitpn semantics rule from\n                               Hspec and specialize it. *)\n               inversion Hspec.\n               clear H H0 H1 H2 H3 H4 H5 H6 H8 H9 H10 H11 H12 H13.\n               rename H7 into Hsens_and_fired_reset.\n\n               (* Gets In t (fs (d_intervals s)) *)\n               deduce_in_from_is_dec_list_cons His_dec_list as Hin_t_fs_ditvals.\n               apply in_fst_split in Hin_t_fs_ditvals.\n\n               (* Gets ~IsSensitized \\/ ... *)\n               assert (Hin_t_transs := Hin_t_fs_ditvals).\n               explode_well_defined_sitpn_state Hwell_def_s.\n               rewrite <- (Hwf_state_ditvals t) in Hin_t_transs.\n               apply proj1 in Hin_t_transs.\n\n               assert (Hnot_sens := His_sens).\n               rewrite (not_is_sensitized_iff (marking s) t Hwell_def_sitpn\n                                              Hwf_state_marking Hin_t_transs)\n                 in Hnot_sens.\n               clear_well_defined_sitpn_state.\n               specialize (or_introl\n                             (IsSensitized sitpn (marking s) t\n                              /\\ (In (t, true) (reset s) \\/ In t (fired s)))\n                             Hnot_sens)\n                 as Hv_notsens_sens.\n               \n               symmetry in Heq_some_sitval.\n               apply (Hsens_and_fired_reset t sitval Hin_t_fs_ditvals Hv_notsens_sens\n                                            Heq_some_sitval).\n             }\n             \n             (* Then, we can deduce incl (new_ditvals ++ [(t, active (dec_itval sitval))]) (d_intervals s') *)\n             assert (Hincl_newd_app : incl (new_ditvals ++ [(t, active (dec_itval sitval))]) (d_intervals s')).\n             {\n               intros x Hin_app.\n               apply in_app_or in Hin_app.\n               inversion_clear Hin_app as [Hin_x_newd | Heq_x_t];\n                 [ apply (Hincl_newd x Hin_x_newd) |\n                   inversion_clear Heq_x_t as [Heq | Hin_nil];\n                   [ rewrite <- Heq; assumption |\n                     inversion Hin_nil\n                   ]\n                 ].\n             }\n\n             (* Builds IsDecListCons ditvals (d_intervals s) *)\n             apply is_dec_list_cons_cons in His_dec_list.\n             \n             (* Builds Permutation and NoDup hyps by rewriting IH. *) \n\n             unfold fs in Hperm_app.\n             rewrite fst_split_app in Hperm_app.\n             rewrite fst_split_cons_app in Hperm_app.\n             simpl in Hperm_app.\n\n             unfold fs in Hnodup_fs_newd.\n             rewrite fst_split_app in Hnodup_fs_newd.\n             rewrite fst_split_cons_app in Hnodup_fs_newd.\n             simpl in Hnodup_fs_newd.\n             \n             unfold fs in IHditvals.\n             rewrite fst_split_app in IHditvals.\n             rewrite fst_split_app in IHditvals.\n             simpl in IHditvals.\n\n             rewrite <- app_assoc in IHditvals.\n\n             (* Applies IHditvals *)\n             apply (IHditvals Hwell_def_sitpn Hwell_def_s Hwell_def_s' Hspec\n                              His_dec_list Hperm_app Hincl_newd_app Hnodup_fs_newd).\n            \n        (* CASE (is_sensitized sitpn (marking s) (lneighbours sitpn t) t) = None, \n           impossible regarding the hypotheses.\n         *)\n        * intros His_sens_eq_none.\n           \n           (* Strategy: specialize [is_sensitized_no_error] then contradiction. \n         \n              To specialize [is_sensitized_no_error], we need:\n              incl (flatten_neighbours (lneighbours sitpn t)) (fs (marking s))\n            *)\n\n           deduce_in_from_is_dec_list_cons His_dec_list as Hin_td_sditvals.\n           specialize (in_fst_split t d (d_intervals s) Hin_td_sditvals) as Hin_fs_sditvals.\n           explode_well_defined_sitpn_state Hwell_def_s.\n           rewrite <- (Hwf_state_ditvals t) in Hin_fs_sditvals.\n           apply proj1 in Hin_fs_sditvals.\n           rename Hin_fs_sditvals into Hin_t_transs.\n           clear_well_defined_sitpn_state.\n\n           (* Specializes in_transs_incl_flatten *)\n           specialize (in_transs_incl_flatten t Hwell_def_sitpn Hin_t_transs)\n             as Hincl_fl_fls.\n\n           (* Gets incl (flatten_ln) places from IsWDSitpn, then use transitivity \n              to get incl flatten_n flatten_ln.\n            *)\n           explode_well_defined_sitpn.     \n           unfold NoUnknownPlaceInNeighbours in Hunk_pl_neigh.\n           specialize (incl_tran Hincl_fl_fls Hunk_pl_neigh) as Hincl_fn_fln.\n\n           (* Gets places = (fs (marking s)) from IsWDSitpnState sitpn s *)\n           explode_well_defined_sitpn_state Hwell_def_s.\n           rewrite Hwf_state_marking in Hincl_fn_fln.\n\n           (* Finally specializes is_sensitized_no_error *)\n           specialize (is_sensitized_no_error sitpn (marking s) t Hincl_fn_fln)\n             as Hex_is_sens.\n           inversion_clear Hex_is_sens as (b & His_sens_eq_some).\n           rewrite His_sens_eq_none in His_sens_eq_some; inversion His_sens_eq_some.\n           \n      (* CASE (s_intervals sitpn t) = None, \n         impossible regarding [IsWellDefinedSitpnState sitpn s]. \n       *)\n      + intros Heq_none_sitval.\n        explode_well_defined_sitpn_state Hwell_def_s.\n        deduce_in_from_is_dec_list_cons His_dec_list as Hin_td_sditvals.\n        specialize (in_fst_split t d (d_intervals s) Hin_td_sditvals) as Hin_fs_sditvals.\n        rewrite <- (Hwf_state_ditvals t) in Hin_fs_sditvals.\n        apply proj2 in Hin_fs_sditvals.\n        contradiction.\n  Qed.\n           \nEnd UpdateTimeIntervalsComplete.\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/SitpnFallingEdgeTimeComplete.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.27192803161602486}}
{"text": "(** Monads with an open structure to give more freedom to the run operations\n    The last state of this file was frozen during a refactoring, but cooperative\n    threads and coroutines are working. *)\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\nClass Monad : Type := {\n  I : Type;\n  E : Type;\n  O : Type;\n  O_of_I : I -> O}.\n\nModule M.\n  Inductive t {m : Monad} (A : Type) : Type :=\n  | new : (I -> Result.t A E (t A) * O) -> t A.\n\n  Definition open {m : Monad} A (x : t A) :=\n    match x with\n    | new x' => x'\n    end.\nEnd M.\n\nInstance Id : Monad := {\n  I := unit;\n  E := Empty_set;\n  O := unit;\n  O_of_I := fun _ => tt}.\n\nDefinition ret {m : Monad} A (x : A) : M.t A :=\n  M.new (fun i => (Val x, O_of_I i)).\n\nFixpoint bind {m : Monad} A B (x : M.t A) (f : A -> M.t B) : M.t B :=\n  M.new (fun i =>\n    match M.open x i with\n    | (Val x, o) => (Mon (f x), o)\n    | (Err e, o) => (Err e, o)\n    | (Mon x, o) => (Mon (bind x f), o)\n    end).\n\nDefinition seq {m : Monad} A B (x : M.t A) (f : M.t B) : M.t B :=\n  bind x (fun _ => f).\n\nFixpoint run {m : Monad} A (x : M.t A) (I_of_O : O -> I) (i : I) : (A + E) * O :=\n  match M.open x i with\n  | (Val x, o) => (inl x, o)\n  | (Err e, o) => (inr e, o)\n  | (Mon x, o) => run x I_of_O (I_of_O o)\n  end.\n\nDefinition combine (m1 m2 : Monad) : Monad := {|\n  I := @I m1 * @I m2;\n  E := @E m1 + @E m2;\n  O := @O m1 * @O m2;\n  O_of_I := fun i =>\n    let (i1, i2) := i in\n    (O_of_I i1, O_of_I i2)|}.\n\nInfix \"++\" := combine.\n\nFixpoint combine_id (m : Monad) A (x : @M.t (Id ++ m) A) : @M.t m A :=\n  M.new (fun i =>\n    match M.open x (tt, i) with\n    | (Val x, (_, o)) => (Val x, o)\n    | (Err (inr e), (_, o)) => (Err e, o)\n    | (Err (inl e), _) => match e with end\n    | (Mon x, (_, o)) => (Mon (combine_id x), o)\n    end).\n\nFixpoint combine_commut (m1 m2 : Monad) A (x : @M.t (m1 ++ m2) A)\n  : @M.t (m2 ++ m1) A :=\n  M.new (m := m2 ++ m1) (fun i =>\n    let (i2, i1) := i in\n    match M.open x (i1, i2) with\n    | (Val x, (o1, o2)) => (Val x, (o2, o1))\n    | (Err e, (o1, o2)) =>\n      (Err (match e with\n      | inl e1 => inr e1\n      | inr e2 => inl e2\n      end), (o2, o1))\n    | (Mon x', (o1, o2)) => (Mon (combine_commut x'), (o2, o1))\n    end).\n\nFixpoint combine_assoc_left (m1 m2 m3 : Monad) A (x : @M.t ((m1 ++ m2) ++ m3) A)\n  : @M.t (m1 ++ (m2 ++ m3)) A :=\n  M.new (m := m1 ++ (m2 ++ m3)) (fun i =>\n    match i with\n    | (i1, (i2, i3)) =>\n      match M.open x ((i1, i2), i3) with\n      | (Val x, ((o1, o2), o3)) => (Val x, (o1, (o2, o3)))\n      | (Err e, ((o1, o2), o3)) =>\n        let e := match e with\n          | inl (inl e1) => inl e1\n          | inl (inr e2) => inr (inl e2)\n          | inr e3 => inr (inr e3)\n          end in\n        (Err e, (o1, (o2, o3)))\n      | (Mon x, ((o1, o2), o3)) => (Mon (combine_assoc_left x), (o1, (o2, o3)))\n      end\n    end).\n\nFixpoint combine_assoc_right (m1 m2 m3 : Monad) A (x : @M.t (m1 ++ (m2 ++ m3)) A)\n  : @M.t ((m1 ++ m2) ++ m3) A :=\n  M.new (m := (m1 ++ m2) ++ m3) (fun i =>\n    match i with\n    | ((i1, i2), i3) =>\n      match M.open x (i1, (i2, i3)) with\n      | (Val x, (o1, (o2, o3))) => (Val x, ((o1, o2), o3))\n      | (Err e, (o1, (o2, o3))) =>\n        let e := match e with\n          | inl e1 => inl (inl e1)\n          | inr (inl e2) => inl (inr e2)\n          | inr (inr e3) => inr e3\n          end in\n        (Err e, ((o1, o2), o3))\n      | (Mon x, (o1, (o2, o3))) => (Mon (combine_assoc_right x), ((o1, o2), o3))\n      end\n    end).\n\nFixpoint gret {m m' : Monad} A (x : @M.t m' A) : @M.t (m ++ m') A :=\n  M.new (m := m ++ m') (fun i =>\n    let (i1, i2) := i in\n    let o1 := O_of_I i1 in\n    match M.open x i2 with\n    | (Val x, o2) => (Val x, (o1, o2))\n    | (Err e, o2) => (Err (inr e), (o1, o2))\n    | (Mon x, o2) => (Mon (gret x), (o1, o2))\n    end).\n\nInstance Option : Monad := {\n  I := unit;\n  E := unit;\n  O := unit;\n  O_of_I := fun _ => tt}.\n\nDefinition option_none A : @M.t Option A :=\n  M.new (fun _ => (Err tt, tt)).\n\nDefinition option_run A (x : @M.t Option A) : option A :=\n  match run x (fun _ => tt) tt with\n  | (inl x', _) => Some x'\n  | _ => None\n  end.\n\nInstance Error (E : Type) : Monad := {\n  I := unit;\n  E := E;\n  O := unit;\n  O_of_I := fun _ => tt}.\n\nDefinition raise E A (e : E) : @M.t (Error E) A :=\n  M.new (m := Error E) (fun _ => (Err e, tt)).\n\nInstance Print (A : Type) : Monad := {\n  I := list A;\n  E := Empty_set;\n  O := list A;\n  O_of_I := fun i => i}.\n\nDefinition print A (x : A) : @M.t (Print A) unit :=\n  M.new (m := Print A) (fun i =>\n    (Val tt, x :: i)).\n\nInstance State (S : Type) : Monad := {\n  I := S;\n  E := Empty_set;\n  O := S;\n  O_of_I := fun i => i}.\n\nDefinition read (S : Type) : @M.t (State S) S :=\n  M.new (m := State S) (fun s => (Val s, s)).\n\nDefinition write (S : Type) (x : S) : @M.t (State S) unit :=\n  M.new (m := State S) (fun _ => (Val tt, x)).\n\nInstance Loop : Monad := {\n  I := nat;\n  E := unit;\n  O := nat;\n  O_of_I := fun i => i}.\n\nFixpoint local_run {m m' : Monad} A\n  (x : @M.t (m ++ m') A) (I_of_O : @O m -> @I m) (i_m : @I m)\n  : @M.t (Error (@E m) ++ m') A :=\n  M.new (m := Error (@E m) ++ m') (fun i =>\n    let (_, i_m') := i in\n    match M.open x (i_m, i_m') with\n    | (r, (o_m, o_m')) =>\n      let r := match r with\n        | Val x => Val x\n        | Err e => Err e\n        | Mon x => Mon (local_run x I_of_O (I_of_O o_m))\n        end in\n      (r, (tt, o_m'))\n    end).\n\n(*Fixpoint local_run_with_break {m m' : Monad} A\n  (x : @M.t (m ++ m') A) (I_of_O : @O m -> option (@I m)) (i_m : @I m)\n  : @M.t (Error (@E m) ++ m') (A + @M.t (m ++ m') A) :=\n  M.new (m := Error (@E m) ++ m') (fun i =>\n    let (_, i_m') := i in\n    match M.open x (i_m, i_m') with\n    | (inl xe, (o_m, o_m')) =>\n      let o := (tt, o_m') in\n      match xe with\n      | inl x => (inl (inl (inl x)), o)\n      | inr (inl e_m) => (inl (inr (inl e_m)), o)\n      | inr (inr e_m') => (inl (inr (inr e_m')), o)\n      end\n    | (inr x, (o_m, o_m')) =>\n      let o := (tt, o_m') in\n      match I_of_O o_m with\n      | Some i'_m => (inr (local_run_with_break x I_of_O i'_m), o)\n      | None => (inl (inl (inr x)), o)\n      end\n    end).\n\nFixpoint local_run_with_break_n {m m' : Monad} A\n  (x : @M.t (m ++ m') A) (I_of_O : @O m -> option (@I m)) (i_m : @I m) (n : nat)\n  : @M.t (Error (@E m) ++ m') (A + @M.t (m ++ m') A) :=\n  match n with\n  | 0 => ret (inr x)\n  | S n' => bind (local_run_with_break x I_of_O i_m) (fun x =>\n    match x with\n    | inl r => ret (inl r)\n    | inr x => local_run_with_break_n x I_of_O i_m n'\n    end)\n  end.\n\nDefinition local_run_with_break_terminate {m m' : Monad} A\n  (x : @M.t (m ++ m') A) (I_of_O : @O m -> option (@I m)) (i_m : @I m)\n  : @M.t (Error (@E m) ++ m') A :=\n  let fix aux (x : @M.t (m ++ m') A) (i'_m : @I m) : @M.t (Error (@E m) ++ m') A :=\n    M.new (m := Error (@E m) ++ m') (fun i =>\n      let (_, i_m') := i in\n      match (M.open x) (i'_m, i_m') with\n      | (inl xe, (o_m, o_m')) =>\n        let o := (tt, o_m') in\n        match xe with\n        | inl x => (inl (inl x), o)\n        | inr (inl e_m) => (inl (inr (inl e_m)), o)\n        | inr (inr e_m') => (inl (inr (inr e_m')), o)\n        end\n      | (inr x, (o_m, o_m')) =>\n        let o := (tt, o_m') in\n        match I_of_O o_m with\n        | Some i'_m => (inr (aux x i'_m), o)\n        | None => (inr (aux x i_m), o)\n        end\n      end) in\n  aux x i_m.*)\n\n(** Breaks *)\nInstance Breaker : Monad := {\n  I := unit;\n  E := Empty_set;\n  O := bool; (* if we do a break *)\n  O_of_I := fun _ => false}.\n\nDefinition break : @M.t Breaker unit :=\n  M.new (fun _ => (Val tt, true)).\n\nFixpoint local_run_with_break {m : Monad} A (x : @M.t (Breaker ++ m) A)\n  : @M.t m (A + @M.t (Breaker ++ m) A) :=\n  M.new (m := m) (fun i =>\n    match M.open x (tt, i) with\n    | (r, (true, o)) =>\n      (Val (inr (M.new (m := Breaker ++ m) (fun i =>\n        (r, (false, O_of_I (snd i)))))), o)\n    | (Val x, (false, o)) => (Val (inl x), o)\n    | (Err e, (false, o)) =>\n      match e with\n      | inl e_break => match e_break with end\n      | inr e_m => (Err e_m, o)\n      end\n    | (Mon x, (false, o)) => (Mon (local_run_with_break x), o)\n    end).\n\nFixpoint local_run_with_break_n {m : Monad} A (x : @M.t (Breaker ++ m) A) (a : @M.t m unit) (n : nat)\n  : @M.t m (A + @M.t (Breaker ++ m) A) :=\n  match n with\n  | 0 => ret (inr x)\n  | S n' => bind (local_run_with_break x) (fun x =>\n    match x with\n    | inl x => ret (inl x)\n    | inr x => seq a (local_run_with_break_n x a n')\n    end)\n  end.\n\nFixpoint local_run_with_break_terminate {m : Monad} A (x : @M.t (Breaker ++ m) A) (a : @M.t m unit)\n  : @M.t m A :=\n  M.new (m := m) (fun i =>\n    match M.open x (tt, i) with\n    | (Val x, (_, o)) => (Val x, o)\n    | (Err e, (_, o)) =>\n      match e with\n      | inl e_break => match e_break with end\n      | inr e_m => (Err e_m, o)\n      end\n    | (Mon x, (_, o)) => (Mon (seq a (local_run_with_break_terminate x a)), o)\n    end).\n\n(** Coroutines *)\nDefinition Waiter (m : Monad) (A B : Type) : Monad :=\n  Breaker ++ State ((A -> @M.t m B) * bool).\n\nModule Coroutine.\n  Definition t {m : Monad} (A B T : Type) := @M.t (Waiter m A B ++ m) T.\n\n  Definition break_if_not_fresh {m : Monad} A B : t A B unit :=\n    combine_commut (gret (\n      bind (m := Waiter m A B) (gret (read _)) (fun f_fresh =>\n        let (_, fresh) := f_fresh in\n        if fresh then\n          ret tt\n        else\n          combine_commut (gret break)))).\n\n  Definition use_and_consume {m : Monad} A B (a : A) : t A B B :=\n    combine_assoc_right (gret (combine_commut (\n      bind (m := m ++ State _) (gret (read _)) (fun f_fresh : _ * _ =>\n        let (f, _) := f_fresh in\n        seq (gret (write (f, false)))\n          (combine_commut (gret (f a))))))).\n\n  Definition yield {m : Monad} A B (a : A) : t A B B :=\n    seq (break_if_not_fresh _ _) (use_and_consume _ a).\n\n  (*Definition I_of_O {m : Monad} A B (o : @O (Waiter m A B)) : option (@I (Waiter m A B)) :=\n    match o with\n    | ((f, fresh), break) =>\n      if break then\n        None\n      else\n        Some (f, fresh)\n    end.*)\n\n  (*Definition inject_new_f {m : Monad} A B (f : A -> M.t B) : @M.t (State ((A -> @M.t m B) * bool)) unit :=\n    write (f, true).*)\n\n  (*Definition force {m : Monad} A B T (x : t A B T) (f : A -> M.t B) : M.t (T + t A B T) :=\n    local_run (m' := m) (local_run_with_break x) (fun o => o) (f, true).\n\n  Definition force {m : Monad} A B T (x : t A B T) (f : A -> M.t B) : M.t (T + t A B T) :=\n    sum_id (local_run_with_break x (I_of_O (B := _)) (f, true)).\n\n  Definition force_n {m : Monad} A B T (x : t A B T) (n : nat) (f : A -> M.t B) : M.t (T + t A B T) :=\n    sum_id (local_run_with_break_n x (I_of_O (B := _)) (f, true) n).\n\n  Definition terminate {m : Monad} A B T (x : t A B T) (f : A -> M.t B) : M.t T :=\n    sum_id (local_run_with_break_terminate x (I_of_O (B := _)) (f, true)).\nEnd Coroutine.\n\nFixpoint iter_list {m : Monad} A (l : list A) : Coroutine.t A unit unit :=\n  match l with\n  | nil => ret tt\n  | x :: l' => seq (Coroutine.yield _ x) (iter_list l')\n  end.\n\nDefinition test_it {m : Monad} := iter_list [1; 5; 7; 2].\n\nDefinition test1 := Coroutine.terminate test_it (fun x => print x).\nCompute run test1 (fun o => o) nil.\n\nDefinition test2 n := seq\n  (Coroutine.force_n test_it n (fun x => print x))\n  (ret tt).\nDefinition test2_run n := run (test2 n) (fun o => o) nil.\nCompute test2_run 0.\nCompute test2_run 1.\nCompute test2_run 2.\nCompute test2_run 3.\nCompute test2_run 4.\nCompute test2_run 5.\n\nDefinition test3 := Coroutine.terminate test_it (fun x =>\n  if eq_nat_dec x 7 then\n    gret (m := Print nat) (raise _ \"x is equal to 7\")\n  else\n    combine_commut (gret (m := Error string) (print x))).\n\nCompute run test3 (fun o => o) (nil, tt).\n\n(** Cooperative threads *)\nInstance Breaker : Monad := {\n  I := Stream bool;\n  E := Empty_set;\n  O := Stream bool * bool; (* if we did a break *)\n  O_of_I := fun s => (s, false)}.\n\nDefinition break : @M.t Breaker unit :=\n  M.new (fun s =>\n    (inl (inl tt), (Streams.tl s, Streams.hd s))).\n\nFixpoint join_aux {m : Monad} A B (x : @M.t (Breaker ++ m) A) :=\n  fix aux (y : @M.t (Breaker ++ m) B) (left_first : bool) : @M.t (Breaker ++ m) (A * B):=\n    if left_first then\n      M.new (fun i =>\n        match (M.open x) i with\n        | (inl xe, o) =>\n          match xe with\n          | inl x => (inr (bind y (fun y => ret (x, y))), o)\n          | inr e => (inl (inr e), o)\n          end\n        | (inr x, ((s, breaking), o)) =>\n          if breaking then\n            (inr (join_aux _ x y false), ((s, false), o))\n          else\n            (inr (join_aux _ x y true), ((s, false), o))\n        end)\n    else\n      M.new (fun i =>\n        match (M.open y) i with\n        | (inl ye, o) =>\n          match ye with\n          | inl y => (inr (bind x (fun x => ret (x, y))), o)\n          | inr e => (inl (inr e), o)\n          end\n        | (inr y, ((s, breaking), o)) =>\n          if breaking then\n            (inr (aux y true), ((s, false), o))\n          else\n            (inr (aux y false), ((s, false), o))\n        end).\n\nDefinition join {m : Monad} A B (x : @M.t (Breaker ++ m) A) (y : @M.t (Breaker ++ m) B)\n  : @M.t (Breaker ++ m) (A * B) :=\n  join_aux x y true.\n\n(* join (print 12; break; print 13) (print 23; break; print 0) *)\nDefinition test4 := join\n  (seq (gret (print 12)) (seq (combine_commut (gret break)) (gret (print 13))))\n  (seq (gret (print 23)) (seq (combine_commut (gret break)) (gret (print 0)))).\n\nDefinition test4_run s :=\n  run test4 (fun o => let (sb, o) := o in (fst sb, o)) (s, nil).\n\nCompute test4_run (Streams.const false).\nCompute test4_run (Streams.const true).*)\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/implicit-monads/OpenMonads.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.27192803161602486}}
{"text": "(* -*- coding: utf-8 -*- *)\n(*      This file is distributed under the terms of the      *)\n(*       GNU Lesser General Public License Version 2.1       *)\n(* Author: Sosuke Moriguchi *)\n(* Extended implementation from MSetRBT *)\n\n(** * XSetRBT : Implementation of XSetInterface via Red-Black trees *)\n\n(** This file is extension of [MSetRBT] to implement extensions in XSetInterface. *)\n\nRequire XSetGenTree.\nRequire Import Bool List BinPos Pnat Setoid SetoidList NPeano.\nLocal Open Scope list_scope.\n\n(* For nicer extraction, we create induction principles\n   only when needed *)\nLocal Unset Elimination Schemes.\nLocal Unset Case Analysis Schemes.\n\n(** An extra function not (yet?) in XSetInterface.Sets *)\n\nModule Type XSetRemoveMin (Import M:XSetInterface.Sets).\n\n Parameter remove_min : t -> option (elt * t).\n\n Axiom remove_min_spec1 : forall s k s',\n  remove_min s = Some (k,s') ->\n   min_elt s = Some k /\\ remove k s [=] s'.\n\n Axiom remove_min_spec2 : forall s, remove_min s = None -> Empty s.\n\nEnd XSetRemoveMin.\n\n(** The type of color annotation. *)\n\nInductive color := Red | Black.\n\nModule Color.\n Definition t := color.\nEnd Color.\n\n(** * Ops : the pure functions *)\n\nModule Ops (X:Orders.OrderedType) <: XSetInterface.Ops X.\n\n(** ** Generic trees instantiated with color *)\n\n(** We reuse a generic definition of trees where the information\n    parameter is a color. Functions like mem or fold are also\n    provided by this generic functor. *)\n\nInclude XSetGenTree.Ops X Color.\n\nDefinition t := tree.\nLocal Notation Rd := (Node Red).\nLocal Notation Bk := (Node Black).\n\n(** ** Basic tree *)\n\nDefinition singleton (k: elt) : tree := Bk Leaf k Leaf.\n\n(** ** Changing root color *)\n\nDefinition makeBlack t :=\n match t with\n | Leaf => Leaf\n | Node _ a x b => Bk a x b\n end.\n\nDefinition makeRed t :=\n match t with\n | Leaf => Leaf\n | Node _ a x b => Rd a x b\n end.\n\n(** ** Balancing *)\n\n(** We adapt when one side is not a true red-black tree.\n    Both sides have the same black depth. *)\n\nDefinition lbal l k r :=\n match l with\n | Rd (Rd a x b) y c => Rd (Bk a x b) y (Bk c k r)\n | Rd a x (Rd b y c) => Rd (Bk a x b) y (Bk c k r)\n | _ => Bk l k r\n end.\n\nDefinition rbal l k r :=\n match r with\n | Rd (Rd b y c) z d => Rd (Bk l k b) y (Bk c z d)\n | Rd b y (Rd c z d) => Rd (Bk l k b) y (Bk c z d)\n | _ => Bk l k r\n end.\n\n(** A variant of [rbal], with reverse pattern order.\n    Is it really useful ? Should we always use it ? *)\n\nDefinition rbal' l k r :=\n match r with\n | Rd b y (Rd c z d) => Rd (Bk l k b) y (Bk c z d)\n | Rd (Rd b y c) z d => Rd (Bk l k b) y (Bk c z d)\n | _ => Bk l k r\n end.\n\n(** Balancing with different black depth.\n    One side is almost a red-black tree, while the other is\n    a true red-black tree, but with black depth + 1.\n    Used in deletion. *)\n\nDefinition lbalS l k r :=\n match l with\n | Rd a x b => Rd (Bk a x b) k r\n | _ =>\n   match r with\n   | Bk a y b => rbal' l k (Rd a y b)\n   | Rd (Bk a y b) z c => Rd (Bk l k a) y (rbal' b z (makeRed c))\n   | _ => Rd l k r (* impossible *)\n   end\n end.\n\nDefinition rbalS l k r :=\n match r with\n | Rd b y c => Rd l k (Bk b y c)\n | _ =>\n   match l with\n   | Bk a x b => lbal (Rd a x b) k r\n   | Rd a x (Bk b y c) => Rd (lbal (makeRed a) x b) y (Bk c k r)\n   | _ => Rd l k r (* impossible *)\n   end\n end.\n\n(** ** Insertion *)\n\nFixpoint ins x s :=\n match s with\n | Leaf => Rd Leaf x Leaf\n | Node c l y r =>\n   match X.compare x y with\n   | Eq => s\n   | Lt =>\n     match c with\n     | Red => Rd (ins x l) y r\n     | Black => lbal (ins x l) y r\n     end\n   | Gt =>\n     match c with\n     | Red => Rd l y (ins x r)\n     | Black => rbal l y (ins x r)\n     end\n   end\n end.\n\nDefinition add x s := makeBlack (ins x s).\n\n(** ** Deletion *)\n\nFixpoint append (l:tree) : tree -> tree :=\n match l with\n | Leaf => fun r => r\n | Node lc ll lx lr =>\n   fix append_l (r:tree) : tree :=\n   match r with\n   | Leaf => l\n   | Node rc rl rx rr =>\n     match lc, rc with\n     | Red, Red =>\n       let lrl := append lr rl in\n       match lrl with\n       | Rd lr' x rl' => Rd (Rd ll lx lr') x (Rd rl' rx rr)\n       | _ => Rd ll lx (Rd lrl rx rr)\n       end\n     | Black, Black =>\n       let lrl := append lr rl in\n       match lrl with\n       | Rd lr' x rl' => Rd (Bk ll lx lr') x (Bk rl' rx rr)\n       | _ => lbalS ll lx (Bk lrl rx rr)\n       end\n     | Black, Red => Rd (append_l rl) rx rr\n     | Red, Black => Rd ll lx (append lr r)\n     end\n   end\n end.\n\nFixpoint del x t :=\n match t with\n | Leaf => Leaf\n | Node _ a y b =>\n   match X.compare x y with\n   | Eq => append a b\n   | Lt =>\n     match a with\n     | Bk _ _ _ => lbalS (del x a) y b\n     | _ => Rd (del x a) y b\n     end\n   | Gt =>\n     match b with\n     | Bk _ _ _ => rbalS a y (del x b)\n     | _ => Rd a y (del x b)\n     end\n   end\n end.\n\nDefinition remove x t := makeBlack (del x t).\n\n(** ** Removing minimal element *)\n\nFixpoint delmin l x r : (elt * tree) :=\n match l with\n | Leaf => (x,r)\n | Node lc ll lx lr =>\n   let (k,l') := delmin ll lx lr in\n   match lc with\n   | Black => (k, lbalS l' x r)\n   | Red => (k, Rd l' x r)\n   end\n end.\n\nDefinition remove_min t : option (elt * tree) :=\n match t with\n | Leaf => None\n | Node _ l x r =>\n   let (k,t) := delmin l x r in\n   Some (k, makeBlack t)\n end.\n\n(** ** Tree-ification\n\n    We rebuild a tree of size [if pred then n-1 else n] as soon\n    as the list [l] has enough elements *)\n\nDefinition bogus : tree * list elt := (Leaf, nil).\n\nNotation treeify_t := (list elt -> tree * list elt).\n\nDefinition treeify_zero : treeify_t :=\n fun acc => (Leaf,acc).\n\nDefinition treeify_one : treeify_t :=\n fun acc => match acc with\n | x::acc => (Rd Leaf x Leaf, acc)\n | _ => bogus\n end.\n\nDefinition treeify_cont (f g : treeify_t) : treeify_t :=\n fun acc =>\n match f acc with\n | (l, x::acc) =>\n   match g acc with\n   | (r, acc) => (Bk l x r, acc)\n   end\n | _ => bogus\n end.\n\nFixpoint treeify_aux (pred:bool)(n: positive) : treeify_t :=\n match n with\n | xH => if pred then treeify_zero else treeify_one\n | xO n => treeify_cont (treeify_aux pred n) (treeify_aux true n)\n | xI n => treeify_cont (treeify_aux false n) (treeify_aux pred n)\n end.\n\nFixpoint plength_aux (l:list elt)(p:positive) := match l with\n | nil => p\n | _::l => plength_aux l (Pos.succ p)\nend.\n\nDefinition plength l := plength_aux l 1.\n\nDefinition treeify (l:list elt) :=\n fst (treeify_aux true (plength l) l).\n\n(** ** Filtering *)\n\nFixpoint filter_aux (f: elt -> bool) s acc :=\n match s with\n | Leaf => acc\n | Node _ l k r =>\n   let acc := filter_aux f r acc in\n   if f k then filter_aux f l (k::acc)\n   else filter_aux f l acc\n end.\n\nDefinition filter (f: elt -> bool) (s: t) : t :=\n treeify (filter_aux f s nil).\n\nFixpoint partition_aux (f: elt -> bool) s acc1 acc2 :=\n match s with\n | Leaf => (acc1,acc2)\n | Node _ sl k sr =>\n   let (acc1, acc2) := partition_aux f sr acc1 acc2 in\n   if f k then partition_aux f sl (k::acc1) acc2\n   else partition_aux f sl acc1 (k::acc2)\n end.\n\nDefinition partition (f: elt -> bool) (s:t) : t*t :=\n  let (ok,ko) := partition_aux f s nil nil in\n  (treeify ok, treeify ko).\n\n(** ** Union, intersection, difference *)\n\n(** union of the elements of [l1] and [l2] into a third [acc] list. *)\n\nFixpoint union_list l1 : list elt -> list elt -> list elt :=\n match l1 with\n | nil => @rev_append _\n | x::l1' =>\n    fix union_l1 l2 acc :=\n    match l2 with\n    | nil => rev_append l1 acc\n    | y::l2' =>\n       match X.compare x y with\n       | Eq => union_list l1' l2' (x::acc)\n       | Lt => union_l1 l2' (y::acc)\n       | Gt => union_list l1' l2 (x::acc)\n       end\n    end\n end.\n\nDefinition linear_union s1 s2 :=\n  treeify (union_list (rev_elements s1) (rev_elements s2) nil).\n\nFixpoint inter_list l1 : list elt -> list elt -> list elt :=\n match l1 with\n | nil => fun _ acc => acc\n | x::l1' =>\n    fix inter_l1 l2 acc :=\n    match l2 with\n    | nil => acc\n    | y::l2' =>\n       match X.compare x y with\n       | Eq => inter_list l1' l2' (x::acc)\n       | Lt => inter_l1 l2' acc\n       | Gt => inter_list l1' l2 acc\n       end\n    end\n end.\n\nDefinition linear_inter s1 s2 :=\n  treeify (inter_list (rev_elements s1) (rev_elements s2) nil).\n\nFixpoint diff_list l1 : list elt -> list elt -> list elt :=\n match l1 with\n | nil => fun _ acc => acc\n | x::l1' =>\n    fix diff_l1 l2 acc :=\n    match l2 with\n    | nil => rev_append l1 acc\n    | y::l2' =>\n       match X.compare x y with\n       | Eq => diff_list l1' l2' acc\n       | Lt => diff_l1 l2' acc\n       | Gt => diff_list l1' l2 (x::acc)\n       end\n    end\n end.\n\nDefinition linear_diff s1 s2 :=\n  treeify (diff_list (rev_elements s1) (rev_elements s2) nil).\n\n(** [compare_height] returns:\n  - [Lt] if [height s2] is at least twice [height s1];\n  - [Gt] if [height s1] is at least twice [height s2];\n  - [Eq] if heights are approximately equal.\n  Warning: this is not an equivalence relation! but who cares.... *)\n\nDefinition skip_red t :=\n match t with\n | Rd t' _ _ => t'\n | _ => t\n end.\n\nDefinition skip_black t :=\n match skip_red t with\n | Bk t' _ _ => t'\n | t' => t'\n end.\n\nFixpoint compare_height (s1x s1 s2 s2x: tree) : comparison :=\n match skip_red s1x, skip_red s1, skip_red s2, skip_red s2x with\n | Node _ s1x' _ _, Node _ s1' _ _, Node _ s2' _ _, Node _ s2x' _ _ =>\n   compare_height (skip_black s1x') s1' s2' (skip_black s2x')\n | _, Leaf, _, Node _ _ _ _ => Lt\n | Node _ _ _ _, _, Leaf, _ => Gt\n | Node _ s1x' _ _, Node _ s1' _ _, Node _ s2' _ _, Leaf =>\n   compare_height (skip_black s1x') s1' s2' Leaf\n | Leaf, Node _ s1' _ _, Node _ s2' _ _, Node _ s2x' _ _ =>\n   compare_height Leaf s1'  s2'  (skip_black s2x')\n | _, _, _, _ => Eq\n end.\n\n(** When one tree is quite smaller than the other, we simply\n    adds repeatively all its elements in the big one.\n    For trees of comparable height, we rather use [linear_union]. *)\n\nDefinition union (t1 t2: t) : t :=\n match compare_height t1 t1 t2 t2 with\n | Lt => fold add t1 t2\n | Gt => fold add t2 t1\n | Eq => linear_union t1 t2\n end.\n\nDefinition diff (t1 t2: t) : t :=\n match compare_height t1 t1 t2 t2 with\n | Lt => filter (fun k => negb (mem k t2)) t1\n | Gt => fold remove t2 t1\n | Eq => linear_diff t1 t2\n end.\n\nDefinition inter (t1 t2: t) : t :=\n match compare_height t1 t1 t2 t2 with\n | Lt => filter (fun k => mem k t2) t1\n | Gt => filter (fun k => mem k t1) t2\n | Eq => linear_inter t1 t2\n end.\n\nEnd Ops.\n\n(** * MakeRaw : the pure functions and their specifications *)\n\nModule Type MakeRaw (X:Orders.OrderedType) <: XSetInterface.RawSets X.\nInclude Ops X.\n\n(** Generic definition of binary-search-trees and proofs of\n    specifications for generic functions such as mem or fold. *)\n\nInclude XSetGenTree.Props X Color.\n\nLocal Notation Rd := (Node Red).\nLocal Notation Bk := (Node Black).\n\nLocal Hint Immediate MX.eq_sym.\nLocal Hint Unfold In lt_tree gt_tree Ok.\nLocal Hint Constructors InT bst.\nLocal Hint Resolve MX.eq_refl MX.eq_trans MX.lt_trans @ok.\nLocal Hint Resolve lt_leaf gt_leaf lt_tree_node gt_tree_node.\nLocal Hint Resolve lt_tree_not_in lt_tree_trans gt_tree_not_in gt_tree_trans.\nLocal Hint Resolve elements_spec2.\n\n(** ** Singleton set *)\n\nLemma singleton_spec x y : InT y (singleton x) <-> X.eq y x.\nProof.\n unfold singleton; intuition_in.\nQed.\n\nInstance singleton_ok x : Ok (singleton x).\nProof.\n unfold singleton; auto.\nQed.\n\n(** ** makeBlack, MakeRed *)\n\nLemma makeBlack_spec s x : InT x (makeBlack s) <-> InT x s.\nProof.\n destruct s; simpl; intuition_in.\nQed.\n\nLemma makeRed_spec s x : InT x (makeRed s) <-> InT x s.\nProof.\n destruct s; simpl; intuition_in.\nQed.\n\nInstance makeBlack_ok s `{Ok s} : Ok (makeBlack s).\nProof.\n destruct s; simpl; ok.\nQed.\n\nInstance makeRed_ok s `{Ok s} : Ok (makeRed s).\nProof.\n destruct s; simpl; ok.\nQed.\n\n(** ** Generic handling for red-matching and red-red-matching *)\n\nDefinition isblack t :=\n match t with Bk _ _ _ => True | _ => False end.\n\nDefinition notblack t :=\n match t with Bk _ _ _ => False | _ => True end.\n\nDefinition notred t :=\n match t with Rd _ _ _ => False | _ => True end.\n\nDefinition rcase {A} f g t : A :=\n match t with\n | Rd a x b => f a x b\n | _ => g t\n end.\n\nInductive rspec {A} f g : tree -> A -> Prop :=\n | rred a x b : rspec f g (Rd a x b) (f a x b)\n | relse t : notred t -> rspec f g t (g t).\n\nFact rmatch {A} f g t : rspec (A:=A) f g t (rcase f g t).\nProof.\ndestruct t as [|[|] l x r]; simpl; now constructor.\nQed.\n\nDefinition rrcase {A} f g t : A :=\n match t with\n | Rd (Rd a x b) y c => f a x b y c\n | Rd a x (Rd b y c) => f a x b y c\n | _ => g t\n end.\n\nNotation notredred := (rrcase (fun _ _ _ _ _ => False) (fun _ => True)).\n\nInductive rrspec {A} f g : tree -> A -> Prop :=\n | rrleft a x b y c : rrspec f g (Rd (Rd a x b) y c) (f a x b y c)\n | rrright a x b y c : rrspec f g (Rd a x (Rd b y c)) (f a x b y c)\n | rrelse t : notredred t -> rrspec f g t (g t).\n\nFact rrmatch {A} f g t : rrspec (A:=A) f g t (rrcase f g t).\nProof.\ndestruct t as [|[|] l x r]; simpl; try now constructor.\ndestruct l as [|[|] ll lx lr], r as [|[|] rl rx rr]; now constructor.\nQed.\n\nDefinition rrcase' {A} f g t : A :=\n match t with\n | Rd a x (Rd b y c) => f a x b y c\n | Rd (Rd a x b) y c => f a x b y c\n | _ => g t\n end.\n\nFact rrmatch' {A} f g t : rrspec (A:=A) f g t (rrcase' f g t).\nProof.\ndestruct t as [|[|] l x r]; simpl; try now constructor.\ndestruct l as [|[|] ll lx lr], r as [|[|] rl rx rr]; now constructor.\nQed.\n\n(** Balancing operations are instances of generic match *)\n\nFact lbal_match l k r :\n rrspec\n   (fun a x b y c => Rd (Bk a x b) y (Bk c k r))\n   (fun l => Bk l k r)\n   l\n   (lbal l k r).\nProof.\n exact (rrmatch _ _ _).\nQed.\n\nFact rbal_match l k r :\n rrspec\n   (fun a x b y c => Rd (Bk l k a) x (Bk b y c))\n   (fun r => Bk l k r)\n   r\n   (rbal l k r).\nProof.\n exact (rrmatch _ _ _).\nQed.\n\nFact rbal'_match l k r :\n rrspec\n   (fun a x b y c => Rd (Bk l k a) x (Bk b y c))\n   (fun r => Bk l k r)\n   r\n   (rbal' l k r).\nProof.\n exact (rrmatch' _ _ _).\nQed.\n\nFact lbalS_match l x r :\n rspec\n  (fun a y b => Rd (Bk a y b) x r)\n  (fun l =>\n    match r with\n    | Bk a y b => rbal' l x (Rd a y b)\n    | Rd (Bk a y b) z c => Rd (Bk l x a) y (rbal' b z (makeRed c))\n    | _ => Rd l x r\n    end)\n  l\n  (lbalS l x r).\nProof.\n exact (rmatch _ _ _).\nQed.\n\nFact rbalS_match l x r :\n rspec\n  (fun a y b => Rd l x (Bk a y b))\n  (fun r =>\n    match l with\n    | Bk a y b => lbal (Rd a y b) x r\n    | Rd a y (Bk b z c) => Rd (lbal (makeRed a) y b) z (Bk c x r)\n    | _ => Rd l x r\n    end)\n  r\n  (rbalS l x r).\nProof.\n exact (rmatch _ _ _).\nQed.\n\n(** ** Balancing for insertion *)\n\nLemma lbal_spec l x r y :\n   InT y (lbal l x r) <-> X.eq y x \\/ InT y l \\/ InT y r.\nProof.\n case lbal_match; intuition_in.\nQed.\n\nInstance lbal_ok l x r `(Ok l, Ok r, lt_tree x l, gt_tree x r) :\n Ok (lbal l x r).\nProof.\n destruct (lbal_match l x r); ok.\nQed.\n\nLemma rbal_spec l x r y :\n   InT y (rbal l x r) <-> X.eq y x \\/ InT y l \\/ InT y r.\nProof.\n case rbal_match; intuition_in.\nQed.\n\nInstance rbal_ok l x r `(Ok l, Ok r, lt_tree x l, gt_tree x r) :\n Ok (rbal l x r).\nProof.\n destruct (rbal_match l x r); ok.\nQed.\n\nLemma rbal'_spec l x r y :\n   InT y (rbal' l x r) <-> X.eq y x \\/ InT y l \\/ InT y r.\nProof.\n case rbal'_match; intuition_in.\nQed.\n\nInstance rbal'_ok l x r `(Ok l, Ok r, lt_tree x l, gt_tree x r) :\n Ok (rbal' l x r).\nProof.\n destruct (rbal'_match l x r); ok.\nQed.\n\nHint Rewrite In_node_iff In_leaf_iff\n makeRed_spec makeBlack_spec lbal_spec rbal_spec rbal'_spec : rb.\n\nLtac descolor := destruct_all Color.t.\nLtac destree t := destruct t as [|[|] ? ? ?].\nLtac autorew := autorewrite with rb.\nTactic Notation \"autorew\" \"in\" ident(H) := autorewrite with rb in H.\n\n(** ** Insertion *)\n\nLemma ins_spec : forall s x y,\n InT y (ins x s) <-> X.eq y x \\/ InT y s.\nProof.\n induct s x.\n - intuition_in.\n - intuition_in. setoid_replace y with x; eauto.\n - descolor; autorew; rewrite IHl; intuition_in.\n - descolor; autorew; rewrite IHr; intuition_in.\nQed.\nHint Rewrite ins_spec : rb.\n\nInstance ins_ok s x `{Ok s} : Ok (ins x s).\nProof.\n induct s x; auto; descolor;\n (apply lbal_ok || apply rbal_ok || ok); auto;\n intros y; autorew; intuition; order.\nQed.\n\nLemma add_spec' s x y :\n InT y (add x s) <-> X.eq y x \\/ InT y s.\nProof.\n unfold add. now autorew.\nQed.\n\nHint Rewrite add_spec' : rb.\n\nLemma add_spec s x y `{Ok s} :\n InT y (add x s) <-> X.eq y x \\/ InT y s.\nProof.\n apply add_spec'.\nQed.\n\nInstance add_ok s x `{Ok s} : Ok (add x s).\nProof.\n unfold add; auto_tc.\nQed.\n\n(** ** Balancing for deletion *)\n\nLemma lbalS_spec l x r y :\n  InT y (lbalS l x r) <-> X.eq y x \\/ InT y l \\/ InT y r.\nProof.\n case lbalS_match.\n - intros; autorew; intuition_in.\n - clear l. intros l _.\n   destruct r as [|[|] rl rx rr].\n   * autorew. intuition_in.\n   * destree rl; autorew; intuition_in.\n   * autorew. intuition_in.\nQed.\n\nInstance lbalS_ok l x r :\n forall `(Ok l, Ok r, lt_tree x l, gt_tree x r), Ok (lbalS l x r).\nProof.\n case lbalS_match; intros.\n - ok.\n - destruct r as [|[|] rl rx rr].\n   * ok.\n   * destruct rl as [|[|] rll rlx rlr]; intros; ok.\n     + apply rbal'_ok; ok.\n       intros w; autorew; auto.\n     + intros w; autorew.\n       destruct 1 as [Hw|[Hw|Hw]]; try rewrite Hw; eauto.\n   * ok. autorew. apply rbal'_ok; ok.\nQed.\n\nLemma rbalS_spec l x r y :\n  InT y (rbalS l x r) <-> X.eq y x \\/ InT y l \\/ InT y r.\nProof.\n case rbalS_match.\n - intros; autorew; intuition_in.\n - intros t _.\n   destruct l as [|[|] ll lx lr].\n   * autorew. intuition_in.\n   * destruct lr as [|[|] lrl lrx lrr]; autorew; intuition_in.\n   * autorew. intuition_in.\nQed.\n\nInstance rbalS_ok l x r :\n forall `(Ok l, Ok r, lt_tree x l, gt_tree x r), Ok (rbalS l x r).\nProof.\n case rbalS_match; intros.\n - ok.\n - destruct l as [|[|] ll lx lr].\n   * ok.\n   * destruct lr as [|[|] lrl lrx lrr]; intros; ok.\n     + apply lbal_ok; ok.\n       intros w; autorew; auto.\n     + intros w; autorew.\n       destruct 1 as [Hw|[Hw|Hw]]; try rewrite Hw; eauto.\n   * ok. apply lbal_ok; ok.\nQed.\n\nHint Rewrite lbalS_spec rbalS_spec : rb.\n\n(** ** Append for deletion *)\n\nLtac append_tac l r :=\n induction l as [| lc ll _ lx lr IHlr];\n [intro r; simpl\n |induction r as [| rc rl IHrl rx rr _];\n   [simpl\n   |destruct lc, rc;\n     [specialize (IHlr rl); clear IHrl\n     |simpl;\n      assert (Hr:notred (Bk rl rx rr)) by (simpl; trivial);\n      set (r:=Bk rl rx rr) in *; clearbody r; clear IHrl rl rx rr;\n      specialize (IHlr r)\n     |change (append _ _) with (Rd (append (Bk ll lx lr) rl) rx rr);\n      assert (Hl:notred (Bk ll lx lr)) by (simpl; trivial);\n      set (l:=Bk ll lx lr) in *; clearbody l; clear IHlr ll lx lr\n     |specialize (IHlr rl); clear IHrl]]].\n\nFact append_rr_match ll lx lr rl rx rr :\n rspec\n  (fun a x b => Rd (Rd ll lx a) x (Rd b rx rr))\n  (fun t => Rd ll lx (Rd t rx rr))\n  (append lr rl)\n  (append (Rd ll lx lr) (Rd rl rx rr)).\nProof.\n exact (rmatch _ _ _).\nQed.\n\nFact append_bb_match ll lx lr rl rx rr :\n rspec\n  (fun a x b => Rd (Bk ll lx a) x (Bk b rx rr))\n  (fun t => lbalS ll lx (Bk t rx rr))\n  (append lr rl)\n  (append (Bk ll lx lr) (Bk rl rx rr)).\nProof.\n exact (rmatch _ _ _).\nQed.\n\nLemma append_spec l r x :\n InT x (append l r) <-> InT x l \\/ InT x r.\nProof.\n revert r.\n append_tac l r; autorew; try tauto.\n - (* Red / Red *)\n   revert IHlr; case append_rr_match;\n    [intros a y b | intros t Ht]; autorew; tauto.\n - (* Black / Black *)\n   revert IHlr; case append_bb_match;\n    [intros a y b | intros t Ht]; autorew; tauto.\nQed.\n\nHint Rewrite append_spec : rb.\n\nLemma append_ok : forall x l r `{Ok l, Ok r},\n lt_tree x l -> gt_tree x r -> Ok (append l r).\nProof.\n append_tac l r.\n - (* Leaf / _ *)\n   trivial.\n - (* _ / Leaf *)\n   trivial.\n - (* Red / Red *)\n   intros; inv.\n   assert (IH : Ok (append lr rl)) by (apply IHlr; eauto). clear IHlr.\n   assert (X.lt lx rx) by (transitivity x; eauto).\n   assert (G : gt_tree lx (append lr rl)).\n    { intros w. autorew. destruct 1; [|transitivity x]; eauto. }\n   assert (L : lt_tree rx (append lr rl)).\n    { intros w. autorew. destruct 1; [transitivity x|]; eauto. }\n   revert IH G L; case append_rr_match; intros; ok.\n - (* Red / Black *)\n   intros; ok.\n   intros w; autorew; destruct 1; eauto.\n - (* Black / Red *)\n   intros; ok.\n   intros w; autorew; destruct 1; eauto.\n - (* Black / Black *)\n   intros; inv.\n   assert (IH : Ok (append lr rl)) by (apply IHlr; eauto). clear IHlr.\n   assert (X.lt lx rx) by (transitivity x; eauto).\n   assert (G : gt_tree lx (append lr rl)).\n    { intros w. autorew. destruct 1; [|transitivity x]; eauto. }\n   assert (L : lt_tree rx (append lr rl)).\n    { intros w. autorew. destruct 1; [transitivity x|]; eauto. }\n   revert IH G L; case append_bb_match; intros; ok.\n    apply lbalS_ok; ok.\nQed.\n\n(** ** Deletion *)\n\nLemma del_spec : forall s x y `{Ok s},\n InT y (del x s) <-> InT y s /\\ ~X.eq y x.\nProof.\ninduct s x.\n- intuition_in.\n- autorew; intuition_in.\n  assert (X.lt y x') by eauto. order.\n  assert (X.lt x' y) by eauto. order.\n  order.\n- destruct l as [|[|] ll lx lr]; autorew;\n  rewrite ?IHl by trivial; intuition_in; order.\n- destruct r as [|[|] rl rx rr]; autorew;\n  rewrite ?IHr by trivial; intuition_in; order.\nQed.\n\nHint Rewrite del_spec : rb.\n\nInstance del_ok s x `{Ok s} : Ok (del x s).\nProof.\ninduct s x.\n- trivial.\n- eapply append_ok; eauto.\n- assert (lt_tree x' (del x l)).\n  { intro w. autorew; trivial. destruct 1. eauto. }\n  destruct l as [|[|] ll lx lr]; auto_tc.\n- assert (gt_tree x' (del x r)).\n  { intro w. autorew; trivial. destruct 1. eauto. }\n  destruct r as [|[|] rl rx rr]; auto_tc.\nQed.\n\nLemma remove_spec s x y `{Ok s} :\n InT y (remove x s) <-> InT y s /\\ ~X.eq y x.\nProof.\nunfold remove. now autorew.\nQed.\n\nHint Rewrite remove_spec : rb.\n\nInstance remove_ok s x `{Ok s} : Ok (remove x s).\nProof.\nunfold remove; auto_tc.\nQed.\n\n(** ** Removing the minimal element *)\n\nLemma delmin_spec l y r c x s' `{O : Ok (Node c l y r)} :\n delmin l y r = (x,s') ->\n  min_elt (Node c l y r) = Some x /\\ del x (Node c l y r) = s'.\nProof.\n revert y r c x s' O.\n induction l as [|lc ll IH ly lr _].\n - simpl. intros y r _ x s' _. injection 1; intros; subst.\n   now rewrite MX.compare_refl.\n - intros y r c x s' O.\n   simpl delmin.\n   specialize (IH ly lr). destruct delmin as (x0,s0).\n   destruct (IH lc x0 s0); clear IH; [ok|trivial|].\n   remember (Node lc ll ly lr) as l.\n   simpl min_elt in *.\n   intros E.\n   replace x0 with x in * by (destruct lc; now injection E).\n   split.\n   * subst l; intuition.\n   * assert (X.lt x y).\n     { inversion_clear O.\n       assert (InT x l) by now apply min_elt_spec1. auto. }\n     simpl. case X.compare_spec; try order.\n     destruct lc; injection E; clear E; intros; subst l s0; auto.\nQed.\n\nLemma remove_min_spec1 s x s' `{Ok s}:\n remove_min s = Some (x,s') ->\n  min_elt s = Some x /\\ remove x s = s'.\nProof.\n unfold remove_min.\n destruct s as [|c l y r]; try easy.\n generalize (delmin_spec l y r c).\n destruct delmin as (x0,s0). intros D.\n destruct (D x0 s0) as (->,<-); auto.\n fold (remove x0 (Node c l y r)).\n inversion_clear 1; auto.\nQed.\n\nLemma remove_min_spec2 s : remove_min s = None -> Empty s.\nProof.\n unfold remove_min.\n destruct s as [|c l y r].\n - easy.\n - now destruct delmin.\nQed.\n\nLemma remove_min_ok (s:t) `{Ok s}:\n match remove_min s with\n | Some (_,s') => Ok s'\n | None => True\n end.\nProof.\n generalize (remove_min_spec1 s).\n destruct remove_min as [(x0,s0)|]; auto.\n intros R. destruct (R x0 s0); auto. subst s0. auto_tc.\nQed.\n\n(** ** Treeify *)\n\nNotation ifpred p n := (if p then pred n else n%nat).\n\nDefinition treeify_invariant size (f:treeify_t) :=\n forall acc,\n size <= length acc ->\n let (t,acc') := f acc in\n cardinal t = size /\\ acc = elements t ++ acc'.\n\nLemma treeify_zero_spec : treeify_invariant 0 treeify_zero.\nProof.\n intro. simpl. auto.\nQed.\n\nLemma treeify_one_spec : treeify_invariant 1 treeify_one.\nProof.\n intros [|x acc]; simpl; auto; inversion 1.\nQed.\n\nLemma treeify_cont_spec f g size1 size2 size :\n treeify_invariant size1 f ->\n treeify_invariant size2 g ->\n size = S (size1 + size2) ->\n treeify_invariant size (treeify_cont f g).\nProof.\n intros Hf Hg EQ acc LE. unfold treeify_cont.\n specialize (Hf acc).\n destruct (f acc) as (t1,acc1).\n destruct Hf as (Hf1,Hf2).\n  { transitivity size; trivial. subst. auto with arith. }\n destruct acc1 as [|x acc1].\n  { exfalso. revert LE. apply Nat.lt_nge. subst.\n    rewrite <- app_nil_end, <- elements_cardinal; auto with arith. }\n specialize (Hg acc1).\n destruct (g acc1) as (t2,acc2).\n destruct Hg as (Hg1,Hg2).\n  { revert LE. subst.\n    rewrite app_length, <- elements_cardinal. simpl.\n    rewrite Nat.add_succ_r, <- Nat.succ_le_mono.\n    apply Nat.add_le_mono_l. }\n simpl. rewrite elements_node, app_ass. now subst.\nQed.\n\nLemma treeify_aux_spec n (p:bool) :\n treeify_invariant (ifpred p (Pos.to_nat n)) (treeify_aux p n).\nProof.\n revert p.\n induction n as [n|n|]; intros p; simpl treeify_aux.\n - eapply treeify_cont_spec; [ apply (IHn false) | apply (IHn p) | ].\n   rewrite Pos2Nat.inj_xI.\n   assert (H := Pos2Nat.is_pos n). apply Nat.neq_0_lt_0 in H.\n   destruct p; simpl; intros; rewrite Nat.add_0_r; trivial.\n   now rewrite <- Nat.add_succ_r, Nat.succ_pred; trivial.\n - eapply treeify_cont_spec; [ apply (IHn p) | apply (IHn true) | ].\n   rewrite Pos2Nat.inj_xO.\n   assert (H := Pos2Nat.is_pos n). apply Nat.neq_0_lt_0 in H.\n   rewrite <- Nat.add_succ_r, Nat.succ_pred by trivial.\n   destruct p; simpl; intros; rewrite Nat.add_0_r; trivial.\n   symmetry. now apply Nat.add_pred_l.\n - destruct p; [ apply treeify_zero_spec | apply treeify_one_spec ].\nQed.\n\nLemma plength_aux_spec l p :\n  Pos.to_nat (plength_aux l p) = length l + Pos.to_nat p.\nProof.\n revert p. induction l; simpl; trivial.\n intros. now rewrite IHl, Pos2Nat.inj_succ, Nat.add_succ_r.\nQed.\n\nLemma plength_spec l : Pos.to_nat (plength l) = S (length l).\nProof.\n unfold plength. rewrite plength_aux_spec. apply Nat.add_1_r.\nQed.\n\nLemma treeify_elements l : elements (treeify l) = l.\nProof.\n assert (H := treeify_aux_spec (plength l) true l).\n unfold treeify. destruct treeify_aux as (t,acc); simpl in *.\n destruct H as (H,H'). { now rewrite plength_spec. }\n subst l. rewrite plength_spec, app_length, <- elements_cardinal in *.\n destruct acc.\n * now rewrite app_nil_r.\n * exfalso. revert H. simpl.\n   rewrite Nat.add_succ_r, Nat.add_comm.\n   apply Nat.succ_add_discr.\nQed.\n\nLemma treeify_spec x l (Hs : Ok (treeify l)) : InT x (treeify l) <-> InA X.eq x l.\nProof.\n intros. now rewrite <- elements_spec1, treeify_elements.\nQed.\n\nLemma treeify_ok l : sort X.lt l -> Ok (treeify l).\nProof.\n intros. apply elements_sort_ok. rewrite treeify_elements; auto.\nQed.\n\n\n(** ** Filter *)\n\nLemma filter_app A f (l l':list A) :\n List.filter f (l ++ l') = List.filter f l ++ List.filter f l'.\nProof.\n induction l as [|x l IH]; simpl; trivial.\n destruct (f x); simpl; now rewrite IH.\nQed.\n\nLemma filter_aux_elements s f acc :\n filter_aux f s acc = List.filter f (elements s) ++ acc.\nProof.\n revert acc.\n induction s as [|c l IHl x r IHr]; simpl; trivial.\n intros acc.\n rewrite elements_node, filter_app. simpl.\n destruct (f x); now rewrite IHl, IHr, app_ass.\nQed.\n\nLemma filter_elements s f :\n elements (filter f s) = List.filter f (elements s).\nProof.\n unfold filter.\n now rewrite treeify_elements, filter_aux_elements, app_nil_r.\nQed.\n\nInstance filter_ok s f `(Ok s) : Ok (filter f s).\nProof.\n apply elements_sort_ok.\n rewrite filter_elements.\n apply filter_sort with X.eq; auto_tc.\nQed.\n\nLemma filter_spec s x f (Hs : Ok s) :\n Proper (X.eq==>Logic.eq) f ->\n (InT x (filter f s) <-> InT x s /\\ f x = true).\nProof.\n intros Hf.\n rewrite <- elements_spec1, filter_elements, filter_InA, elements_spec1;\n  auto_tc.\n split; auto.\nQed.\n\nLemma filter_spec' s x f (Hs : Ok s) :\n InT x (filter f s) -> InT x s.\nProof.\n rewrite <- (elements_spec1_w s).\n rewrite <- elements_spec1, filter_elements; auto_tc.\n induction (elements s); simpl; auto.\n destruct (f a); intuition.\n inversion_clear H; intuition.\nQed.\n\n(** ** Partition *)\n\nLemma partition_aux_spec s f acc1 acc2 :\n partition_aux f s acc1 acc2 =\n  (filter_aux f s acc1, filter_aux (fun x => negb (f x)) s acc2).\nProof.\n revert acc1 acc2.\n induction s as [ | c l Hl x r Hr ]; simpl.\n - trivial.\n - intros acc1 acc2.\n   destruct (f x); simpl; now rewrite Hr, Hl.\nQed.\n\nLemma partition_spec s f :\n partition f s = (filter f s, filter (fun x => negb (f x)) s).\nProof.\n unfold partition, filter. now rewrite partition_aux_spec.\nQed.\n\nLemma partition_spec1 s f `(Ok s) :\n Proper (X.eq==>Logic.eq) f ->\n Equal (fst (partition f s)) (filter f s).\nProof. now rewrite partition_spec. Qed.\n\nLemma partition_spec1' s x f `(Ok s) :\n InT x (fst (partition f s)) -> InT x s.\nProof. rewrite partition_spec. simpl. now apply filter_spec'. Qed.\n\nLemma partition_spec2 s f `(Ok s) :\n Proper (X.eq==>Logic.eq) f ->\n Equal (snd (partition f s)) (filter (fun x => negb (f x)) s).\nProof. now rewrite partition_spec. Qed.\n\nLemma partition_spec2' s x f `(Ok s) :\n InT x (snd (partition f s)) -> InT x s.\nProof. rewrite partition_spec. simpl. now apply filter_spec'. Qed.\n\nInstance partition_ok1 s f `(Ok s) : Ok (fst (partition f s)).\nProof. rewrite partition_spec; now apply filter_ok. Qed.\n\nInstance partition_ok2 s f `(Ok s) : Ok (snd (partition f s)).\nProof. rewrite partition_spec; now apply filter_ok. Qed.\n\n\n(** ** An invariant for binary list functions with accumulator. *)\n\nLtac inA :=\n rewrite ?InA_app_iff, ?InA_cons, ?InA_nil, ?InA_rev in *; auto_tc.\n\nRecord INV l1 l2 acc : Prop := {\n l1_sorted : sort X.lt (rev l1);\n l2_sorted : sort X.lt (rev l2);\n acc_sorted : sort X.lt acc;\n l1_lt_acc x y : InA X.eq x l1 -> InA X.eq y acc -> X.lt x y;\n l2_lt_acc x y : InA X.eq x l2 -> InA X.eq y acc -> X.lt x y}.\nLocal Hint Resolve l1_sorted l2_sorted acc_sorted.\n\nLemma INV_init s1 s2 `(Ok s1, Ok s2) :\n INV (rev_elements s1) (rev_elements s2) nil.\nProof.\n rewrite !rev_elements_rev.\n split; rewrite ?rev_involutive; auto; intros; now inA.\nQed.\n\nLemma INV_sym l1 l2 acc : INV l1 l2 acc -> INV l2 l1 acc.\nProof.\n destruct 1; now split.\nQed.\n\nLemma INV_drop x1 l1 l2 acc :\n  INV (x1 :: l1) l2 acc -> INV l1 l2 acc.\nProof.\n intros (l1s,l2s,accs,l1a,l2a). simpl in *.\n destruct (sorted_app_inv _ _ l1s) as (U & V & W); auto.\n split; auto.\nQed.\n\nLemma INV_eq x1 x2 l1 l2 acc :\n  INV (x1 :: l1) (x2 :: l2) acc -> X.eq x1 x2 ->\n  INV l1 l2 (x1 :: acc).\nProof.\n intros (U,V,W,X,Y) EQ. simpl in *.\n destruct (sorted_app_inv _ _ U) as (U1 & U2 & U3); auto.\n destruct (sorted_app_inv _ _ V) as (V1 & V2 & V3); auto.\n split; auto.\n - constructor; auto. apply InA_InfA with X.eq; auto_tc.\n - intros x y; inA; intros Hx [Hy|Hy].\n   + apply U3; inA.\n   + apply X; inA.\n - intros x y; inA; intros Hx [Hy|Hy].\n   + rewrite Hy, EQ; apply V3; inA.\n   + apply Y; inA.\nQed.\n\nLemma INV_lt x1 x2 l1 l2 acc :\n  INV (x1 :: l1) (x2 :: l2) acc -> X.lt x1 x2 ->\n  INV (x1 :: l1) l2 (x2 :: acc).\nProof.\n intros (U,V,W,X,Y) EQ. simpl in *.\n destruct (sorted_app_inv _ _ U) as (U1 & U2 & U3); auto.\n destruct (sorted_app_inv _ _ V) as (V1 & V2 & V3); auto.\n split; auto.\n - constructor; auto. apply InA_InfA with X.eq; auto_tc.\n - intros x y; inA; intros Hx [Hy|Hy].\n   + rewrite Hy; clear Hy. destruct Hx; [order|].\n     transitivity x1; auto. apply U3; inA.\n   + apply X; inA.\n - intros x y; inA; intros Hx [Hy|Hy].\n   + rewrite Hy. apply V3; inA.\n   + apply Y; inA.\nQed.\n\nLemma INV_rev l1 l2 acc :\n INV l1 l2 acc -> Sorted X.lt (rev_append l1 acc).\nProof.\n intros. rewrite rev_append_rev.\n apply SortA_app with X.eq; eauto with *.\n intros x y. inA. eapply l1_lt_acc; eauto.\nQed.\n\n(** ** union *)\n\nLemma union_list_ok l1 l2 acc :\n INV l1 l2 acc -> sort X.lt (union_list l1 l2 acc).\nProof.\n revert l2 acc.\n induction l1 as [|x1 l1 IH1];\n  [intro l2|induction l2 as [|x2 l2 IH2]];\n   intros acc inv.\n - eapply INV_rev, INV_sym; eauto.\n - eapply INV_rev; eauto.\n - simpl. case X.compare_spec; intro C.\n   * apply IH1. eapply INV_eq; eauto.\n   * apply (IH2 (x2::acc)). eapply INV_lt; eauto.\n   * apply IH1. eapply INV_sym, INV_lt; eauto. now apply INV_sym.\nQed.\n\nInstance linear_union_ok s1 s2 `(Ok s1, Ok s2) :\n Ok (linear_union s1 s2).\nProof.\n unfold linear_union. now apply treeify_ok, union_list_ok, INV_init.\nQed.\n\nInstance fold_add_ok s1 s2 `(Ok s1, Ok s2) :\n Ok (fold add s1 s2).\nProof.\n rewrite fold_spec_w, <- fold_left_rev_right.\n unfold elt in *.\n induction (rev (elements s1)); simpl; unfold flip in *; auto_tc.\nQed.\n\nInstance union_ok s1 s2 `(Ok s1, Ok s2) : Ok (union s1 s2).\nProof.\n unfold union. destruct compare_height; auto_tc.\nQed.\n\nLemma union_list_spec x l1 l2 acc :\n InA X.eq x (union_list l1 l2 acc) <->\n  InA X.eq x l1 \\/ InA X.eq x l2 \\/ InA X.eq x acc.\nProof.\n revert l2 acc.\n induction l1 as [|x1 l1 IH1].\n - intros l2 acc; simpl. rewrite rev_append_rev. inA. tauto.\n - induction l2 as [|x2 l2 IH2]; intros acc; simpl.\n   * rewrite rev_append_rev. inA. tauto.\n   * case X.compare_spec; intro C.\n     + rewrite IH1, !InA_cons, C; tauto.\n     + rewrite (IH2 (x2::acc)), !InA_cons. tauto.\n     + rewrite IH1, !InA_cons; tauto.\nQed.\n\nLemma linear_union_spec s1 s2 x (Hs1 : Ok s1) (Hs2 : Ok s2) :\n InT x (linear_union s1 s2) <-> InT x s1 \\/ InT x s2.\nProof.\n unfold linear_union.\n rewrite treeify_spec, union_list_spec, !rev_elements_rev.\n rewrite !InA_rev, InA_nil, !elements_spec1_w by auto_tc.\n tauto.\n apply linear_union_ok; auto.\nQed.\n\nLemma fold_add_spec s1 s2 x (Hs1 : Ok s1) (Hs2 : Ok s2) :\n InT x (fold add s1 s2) <-> InT x s1 \\/ InT x s2.\nProof.\n rewrite fold_spec_w, <- fold_left_rev_right.\n rewrite <- (elements_spec1 s1), <- InA_rev by auto_tc.\n unfold elt in *.\n induction (rev (elements s1)); simpl.\n - rewrite InA_nil. tauto.\n - unfold flip. rewrite add_spec', IHl, InA_cons. tauto.\nQed.\n\nLemma union_spec' s1 s2 x (Hs1 : Ok s1) (Hs2 : Ok s2) :\n InT x (union s1 s2) <-> InT x s1 \\/ InT x s2.\nProof.\n unfold union. destruct compare_height.\n - apply linear_union_spec; auto.\n - apply fold_add_spec; auto.\n - rewrite fold_add_spec; auto. tauto.\nQed.\n\nLemma union_spec : forall s1 s2 y `{Ok s1, Ok s2},\n (InT y (union s1 s2) <-> InT y s1 \\/ InT y s2).\nProof.\n apply union_spec'.\nQed.\n\n(** ** inter *)\n\nLemma inter_list_ok l1 l2 acc :\n INV l1 l2 acc -> sort X.lt (inter_list l1 l2 acc).\nProof.\n revert l2 acc.\n induction l1 as [|x1 l1 IH1]; [|induction l2 as [|x2 l2 IH2]]; simpl.\n - eauto.\n - eauto.\n - intros acc inv.\n   case X.compare_spec; intro C.\n   * apply IH1. eapply INV_eq; eauto.\n   * apply (IH2 acc). eapply INV_sym, INV_drop, INV_sym; eauto.\n   * apply IH1. eapply INV_drop; eauto.\nQed.\n\nInstance linear_inter_ok s1 s2 `(Ok s1, Ok s2) :\n Ok (linear_inter s1 s2).\nProof.\n unfold linear_inter. now apply treeify_ok, inter_list_ok, INV_init.\nQed.\n\nInstance inter_ok s1 s2 `(Ok s1, Ok s2) : Ok (inter s1 s2).\nProof.\n unfold inter. destruct compare_height; auto_tc.\nQed.\n\nLemma inter_list_spec x l1 l2 acc :\n sort X.lt (rev l1) ->\n sort X.lt (rev l2) ->\n (InA X.eq x (inter_list l1 l2 acc) <->\n   (InA X.eq x l1 /\\ InA X.eq x l2) \\/ InA X.eq x acc).\nProof.\n revert l2 acc.\n induction l1 as [|x1 l1 IH1].\n - intros l2 acc; simpl. inA. tauto.\n - induction l2 as [|x2 l2 IH2]; intros acc.\n   * simpl. inA. tauto.\n   * simpl. intros U V.\n     destruct (sorted_app_inv _ _ U) as (U1 & U2 & U3); auto.\n     destruct (sorted_app_inv _ _ V) as (V1 & V2 & V3); auto.\n     case X.compare_spec; intro C.\n     + rewrite IH1, !InA_cons, C; tauto.\n     + rewrite (IH2 acc); auto. inA. intuition; try order.\n       assert (X.lt x x1) by (apply U3; inA). order.\n     + rewrite IH1; auto. inA. intuition; try order.\n       assert (X.lt x x2) by (apply V3; inA). order.\nQed.\n\nLemma linear_inter_spec s1 s2 x `(Ok s1, Ok s2) :\n InT x (linear_inter s1 s2) <-> InT x s1 /\\ InT x s2.\nProof.\n unfold linear_inter.\n rewrite !rev_elements_rev, treeify_spec, inter_list_spec.\n - rewrite !InA_rev, InA_nil, !elements_spec1 by auto_tc. tauto.\n - rewrite rev_involutive; auto_tc.\n - rewrite rev_involutive; auto_tc.\n - apply treeify_ok. apply inter_list_ok.\n   repeat rewrite <- rev_elements_rev.\n   apply INV_init; auto.\nQed.\n\nLocal Instance mem_proper s `(Ok s) :\n Proper (X.eq ==> Logic.eq) (fun k => mem k s).\nProof.\n intros x y EQ. apply Bool.eq_iff_eq_true; rewrite !mem_spec; auto.\n now rewrite EQ.\nQed.\n\nLemma inter_spec s1 s2 y `{Ok s1, Ok s2} :\n InT y (inter s1 s2) <-> InT y s1 /\\ InT y s2.\nProof.\n unfold inter. destruct compare_height.\n - now apply linear_inter_spec.\n - rewrite filter_spec, mem_spec by auto_tc; tauto.\n - rewrite filter_spec, mem_spec by auto_tc; tauto.\nQed.\n\n(** ** difference *)\n\nLemma diff_list_ok l1 l2 acc :\n INV l1 l2 acc -> sort X.lt (diff_list l1 l2 acc).\nProof.\n revert l2 acc.\n induction l1 as [|x1 l1 IH1];\n  [intro l2|induction l2 as [|x2 l2 IH2]];\n    intros acc inv.\n - eauto.\n - unfold diff_list. eapply INV_rev; eauto.\n - simpl. case X.compare_spec; intro C.\n   * apply IH1. eapply INV_drop, INV_sym, INV_drop, INV_sym; eauto.\n   * apply (IH2 acc). eapply INV_sym, INV_drop, INV_sym; eauto.\n   * apply IH1. eapply INV_sym, INV_lt; eauto. now apply INV_sym.\nQed.\n\nInstance diff_inter_ok s1 s2 `(Ok s1, Ok s2) :\n Ok (linear_diff s1 s2).\nProof.\n unfold linear_inter. now apply treeify_ok, diff_list_ok, INV_init.\nQed.\n\nInstance fold_remove_ok s1 s2 `(Ok s1) `(Ok s2) :\n Ok (fold remove s1 s2).\nProof.\n rewrite fold_spec_w, <- fold_left_rev_right.\n unfold elt in *.\n induction (rev (elements s1)); simpl; unfold flip in *; auto_tc.\nQed.\n\nInstance diff_ok s1 s2 `(Ok s1, Ok s2) : Ok (diff s1 s2).\nProof.\n unfold diff. destruct compare_height; auto_tc.\nQed.\n\nLemma diff_list_spec x l1 l2 acc :\n sort X.lt (rev l1) ->\n sort X.lt (rev l2) ->\n (InA X.eq x (diff_list l1 l2 acc) <->\n   (InA X.eq x l1 /\\ ~InA X.eq x l2) \\/ InA X.eq x acc).\nProof.\n revert l2 acc.\n induction l1 as [|x1 l1 IH1].\n - intros l2 acc; simpl. inA. tauto.\n - induction l2 as [|x2 l2 IH2]; intros acc.\n   * intros; simpl. rewrite rev_append_rev. inA. tauto.\n   * simpl. intros U V.\n     destruct (sorted_app_inv _ _ U) as (U1 & U2 & U3); auto.\n     destruct (sorted_app_inv _ _ V) as (V1 & V2 & V3); auto.\n     case X.compare_spec; intro C.\n     + rewrite IH1; auto. f_equiv. inA. intuition; try order.\n       assert (X.lt x x1) by (apply U3; inA). order.\n     + rewrite (IH2 acc); auto. f_equiv. inA. intuition; try order.\n       assert (X.lt x x1) by (apply U3; inA). order.\n     + rewrite IH1; auto. inA. intuition; try order.\n       left; split; auto. destruct 1. order.\n       assert (X.lt x x2) by (apply V3; inA). order.\nQed.\n\nLemma linear_diff_spec s1 s2 x `(Ok s1, Ok s2) :\n InT x (linear_diff s1 s2) <-> InT x s1 /\\ ~InT x s2.\nProof.\n unfold linear_diff.\n rewrite !rev_elements_rev, treeify_spec, diff_list_spec.\n - rewrite !InA_rev, InA_nil, !elements_spec1 by auto_tc. tauto.\n - rewrite rev_involutive; auto_tc.\n - rewrite rev_involutive; auto_tc.\n - apply treeify_ok. apply diff_list_ok.\n   repeat rewrite <- rev_elements_rev.\n   apply INV_init; auto.\nQed.\n\nLemma fold_remove_spec s1 s2 x `(Ok s1) `(Ok s2) :\n  InT x (fold remove s1 s2) <-> InT x s2 /\\ ~InT x s1.\nProof.\n rewrite fold_spec_w, <- fold_left_rev_right.\n rewrite <- (elements_spec1 s1), <- InA_rev by auto_tc.\n unfold elt in *.\n induction (rev (elements s1)); simpl; intros.\n - rewrite InA_nil. intuition.\n - unfold flip in *. rewrite remove_spec, IHl, InA_cons. tauto.\n   clear IHl. induction l; simpl; auto_tc.\nQed.\n\nLemma diff_spec s1 s2 y `{Ok s1, Ok s2} :\n InT y (diff s1 s2) <-> InT y s1 /\\ ~InT y s2.\nProof.\n unfold diff. destruct compare_height.\n - now apply linear_diff_spec.\n - rewrite filter_spec, Bool.negb_true_iff,\n     <- Bool.not_true_iff_false, mem_spec;\n    intuition.\n    intros x1 x2 EQ. f_equal. now apply mem_proper.\n - now apply fold_remove_spec.\nQed.\n\nEnd MakeRaw.\n\n(** * Balancing properties\n\n    We now prove that all operations preserve a red-black invariant,\n    and that trees have hence a logarithmic depth.\n*)\n\nModule BalanceProps(X:Orders.OrderedType)(Import M : MakeRaw X).\n\nLocal Notation Rd := (Node Red).\nLocal Notation Bk := (Node Black).\nImport M.MX.\n\n(** ** Red-Black invariants *)\n\n(** In a red-black tree :\n    - a red node has no red children\n    - the black depth at each node is the same along all paths.\n    The black depth is here an argument of the predicate. *)\n\nInductive rbt : nat -> tree -> Prop :=\n | RB_Leaf : rbt 0 Leaf\n | RB_Rd n l k r :\n   notred l -> notred r -> rbt n l -> rbt n r -> rbt n (Rd l k r)\n | RB_Bk n l k r : rbt n l -> rbt n r -> rbt (S n) (Bk l k r).\n\n(** A red-red tree is almost a red-black tree, except that it has\n    a _red_ root node which _may_ have red children. Note that a\n    red-red tree is hence non-empty, and all its strict subtrees\n    are red-black. *)\n\nInductive rrt (n:nat) : tree -> Prop :=\n | RR_Rd l k r : rbt n l -> rbt n r -> rrt n (Rd l k r).\n\n(** An almost-red-black tree is almost a red-black tree, except that\n    it's permitted to have two red nodes in a row at the very root (only).\n    We implement this notion by saying that a quasi-red-black tree\n    is either a red-black tree or a red-red tree. *)\n\nInductive arbt (n:nat)(t:tree) : Prop :=\n | ARB_RB : rbt n t -> arbt n t\n | ARB_RR : rrt n t -> arbt n t.\n\n(** The main exported invariant : being a red-black tree for some\n    black depth. *)\n\nClass Rbt (t:tree) :=  RBT : exists d, rbt d t.\n\n(** ** Basic tactics and results about red-black *)\n\nScheme rbt_ind := Induction for rbt Sort Prop.\nLocal Hint Constructors rbt rrt arbt.\nLocal Hint Extern 0 (notred _) => (exact I).\nLtac invrb := intros; invtree rrt; invtree rbt; try contradiction.\nLtac desarb := match goal with H:arbt _ _ |- _ => destruct H end.\nLtac nonzero n := destruct n as [|n]; [try split; invrb|].\n\nLemma rr_nrr_rb n t :\n rrt n t -> notredred t -> rbt n t.\nProof.\n destruct 1 as [l x r Hl Hr].\n destruct l, r; descolor; invrb; auto.\nQed.\n\nLocal Hint Resolve rr_nrr_rb.\n\nLemma arb_nrr_rb n t :\n arbt n t -> notredred t -> rbt n t.\nProof.\n destruct 1; auto.\nQed.\n\nLemma arb_nr_rb n t :\n arbt n t -> notred t -> rbt n t.\nProof.\n destruct 1; destruct t; descolor; invrb; auto.\nQed.\n\nLocal Hint Resolve arb_nrr_rb arb_nr_rb.\n\n(** ** A Red-Black tree has indeed a logarithmic depth *)\n\nDefinition redcarac s := rcase (fun _ _ _ => 1) (fun _ => 0) s.\n\nLemma rb_maxdepth s n : rbt n s -> maxdepth s <= 2*n + redcarac s.\nProof.\n induction 1.\n - simpl; auto.\n - replace (redcarac l) with 0 in * by now destree l.\n   replace (redcarac r) with 0 in * by now destree r.\n   simpl maxdepth. simpl redcarac.\n   rewrite Nat.add_succ_r, <- Nat.succ_le_mono.\n   now apply Nat.max_lub.\n - simpl. rewrite <- Nat.succ_le_mono.\n   apply Nat.max_lub; eapply Nat.le_trans; eauto;\n   [destree l | destree r]; simpl;\n   rewrite !Nat.add_0_r, ?Nat.add_1_r; auto with arith.\nQed.\n\nLemma rb_mindepth s n : rbt n s -> n + redcarac s <= mindepth s.\nProof.\n induction 1; simpl.\n - trivial.\n - rewrite Nat.add_succ_r.\n   apply -> Nat.succ_le_mono.\n   replace (redcarac l) with 0 in * by now destree l.\n   replace (redcarac r) with 0 in * by now destree r.\n   now apply Nat.min_glb.\n - apply -> Nat.succ_le_mono. rewrite Nat.add_0_r.\n   apply Nat.min_glb; eauto with arith.\nQed.\n\nLemma maxdepth_upperbound s : Rbt s ->\n maxdepth s <= 2 * log2 (S (cardinal s)).\nProof.\n intros (n,H).\n eapply Nat.le_trans; [eapply rb_maxdepth; eauto|].\n transitivity (2*(n+redcarac s)).\n - rewrite Nat.mul_add_distr_l. apply Nat.add_le_mono_l.\n   rewrite <- Nat.mul_1_l at 1. apply Nat.mul_le_mono_r.\n   auto with arith.\n - apply Nat.mul_le_mono_l.\n   transitivity (mindepth s).\n   + now apply rb_mindepth.\n   + apply mindepth_log_cardinal.\nQed.\n\nLemma maxdepth_lowerbound s : s<>Leaf ->\n log2 (cardinal s) < maxdepth s.\nProof.\n apply maxdepth_log_cardinal.\nQed.\n\n\n(** ** Singleton *)\n\nLemma singleton_rb x : Rbt (singleton x).\nProof.\n unfold singleton. exists 1; auto.\nQed.\n\n(** ** [makeBlack] and [makeRed] *)\n\nLemma makeBlack_rb n t : arbt n t -> Rbt (makeBlack t).\nProof.\n destruct t as [|[|] l x r].\n - exists 0; auto.\n - destruct 1; invrb; exists (S n); simpl; auto.\n - exists n; auto.\nQed.\n\nLemma makeRed_rr t n :\n rbt (S n) t -> notred t -> rrt n (makeRed t).\nProof.\n destruct t as [|[|] l x r]; invrb; simpl; auto.\nQed.\n\n(** ** Balancing *)\n\nLemma lbal_rb n l k r :\n arbt n l -> rbt n r -> rbt (S n) (lbal l k r).\nProof.\ncase lbal_match; intros; desarb; invrb; auto.\nQed.\n\nLemma rbal_rb n l k r :\n rbt n l -> arbt n r -> rbt (S n) (rbal l k r).\nProof.\ncase rbal_match; intros; desarb; invrb; auto.\nQed.\n\nLemma rbal'_rb n l k r :\n rbt n l -> arbt n r -> rbt (S n) (rbal' l k r).\nProof.\ncase rbal'_match; intros; desarb; invrb; auto.\nQed.\n\nLemma lbalS_rb n l x r :\n arbt n l -> rbt (S n) r -> notred r -> rbt (S n) (lbalS l x r).\nProof.\n intros Hl Hr Hr'.\n destruct r as [|[|] rl rx rr]; invrb. clear Hr'.\n revert Hl.\n case lbalS_match.\n - destruct 1; invrb; auto.\n - intros. apply rbal'_rb; auto.\nQed.\n\nLemma lbalS_arb n l x r :\n arbt n l -> rbt (S n) r -> arbt (S n) (lbalS l x r).\nProof.\n case lbalS_match.\n - destruct 1; invrb; auto.\n - clear l. intros l Hl Hl' Hr.\n   destruct r as [|[|] rl rx rr]; invrb.\n   * destruct rl as [|[|] rll rlx rlr]; invrb.\n     right; auto using rbal'_rb, makeRed_rr.\n   * left; apply rbal'_rb; auto.\nQed.\n\nLemma rbalS_rb n l x r :\n rbt (S n) l -> notred l -> arbt n r -> rbt (S n) (rbalS l x r).\nProof.\n intros Hl Hl' Hr.\n destruct l as [|[|] ll lx lr]; invrb. clear Hl'.\n revert Hr.\n case rbalS_match.\n - destruct 1; invrb; auto.\n - intros. apply lbal_rb; auto.\nQed.\n\nLemma rbalS_arb n l x r :\n rbt (S n) l -> arbt n r -> arbt (S n) (rbalS l x r).\nProof.\n case rbalS_match.\n - destruct 2; invrb; auto.\n - clear r. intros r Hr Hr' Hl.\n   destruct l as [|[|] ll lx lr]; invrb.\n   * destruct lr as [|[|] lrl lrx lrr]; invrb.\n     right; auto using lbal_rb, makeRed_rr.\n   * left; apply lbal_rb; auto.\nQed.\n\n\n(** ** Insertion *)\n\n(** The next lemmas combine simultaneous results about rbt and arbt.\n    A first solution here: statement with [if ... then ... else] *)\n\nDefinition ifred s (A B:Prop) := rcase (fun _ _ _ => A) (fun _ => B) s.\n\nLemma ifred_notred s A B : notred s -> (ifred s A B <-> B).\nProof.\n destruct s; descolor; simpl; intuition.\nQed.\n\nLemma ifred_or s A B : ifred s A B -> A\\/B.\nProof.\n destruct s; descolor; simpl; intuition.\nQed.\n\nLemma ins_rr_rb x s n : rbt n s ->\n ifred s (rrt n (ins x s)) (rbt n (ins x s)).\nProof.\ninduction 1 as [ | n l k r | n l k r Hl IHl Hr IHr ].\n- simpl; auto.\n- simpl. rewrite ifred_notred in * by trivial.\n  elim_compare x k; auto.\n- rewrite ifred_notred by trivial.\n  unfold ins; fold ins. (* simpl is too much here ... *)\n  elim_compare x k.\n  * auto.\n  * apply lbal_rb; trivial. apply ifred_or in IHl; intuition.\n  * apply rbal_rb; trivial. apply ifred_or in IHr; intuition.\nQed.\n\nLemma ins_arb x s n : rbt n s -> arbt n (ins x s).\nProof.\n intros H. apply (ins_rr_rb x), ifred_or in H. intuition.\nQed.\n\nInstance add_rb x s : Rbt s -> Rbt (add x s).\nProof.\n intros (n,H). unfold add. now apply (makeBlack_rb n), ins_arb.\nQed.\n\n(** ** Deletion *)\n\n(** A second approach here: statement with ... /\\ ... *)\n\nLemma append_arb_rb n l r : rbt n l -> rbt n r ->\n (arbt n (append l r)) /\\\n (notred l -> notred r -> rbt n (append l r)).\nProof.\nrevert r n.\nappend_tac l r.\n- split; auto.\n- split; auto.\n- (* Red / Red *)\n  intros n. invrb.\n  case (IHlr n); auto; clear IHlr.\n  case append_rr_match.\n  + intros a x b _ H; split; invrb.\n    assert (rbt n (Rd a x b)) by auto. invrb. auto.\n  + split; invrb; auto.\n- (* Red / Black *)\n  split; invrb. destruct (IHlr n) as (_,IH); auto.\n- (* Black / Red *)\n  split; invrb. destruct (IHrl n) as (_,IH); auto.\n- (* Black / Black *)\n  nonzero n.\n  invrb.\n  destruct (IHlr n) as (IH,_); auto; clear IHlr.\n  revert IH.\n  case append_bb_match.\n  + intros a x b IH; split; destruct IH; invrb; auto.\n  + split; [left | invrb]; auto using lbalS_rb.\nQed.\n\n(** A third approach : Lemma ... with ... *)\n\nLemma del_arb s x n : rbt (S n) s -> isblack s -> arbt n (del x s)\nwith del_rb s x n : rbt n s -> notblack s -> rbt n (del x s).\nProof.\n{ revert n.\n  induct s x; try destruct c; try contradiction; invrb.\n  - apply append_arb_rb; assumption.\n  - assert (IHl' := del_rb l x). clear IHr del_arb del_rb.\n    destruct l as [|[|] ll lx lr]; auto.\n    nonzero n. apply lbalS_arb; auto.\n  - assert (IHr' := del_rb r x). clear IHl del_arb del_rb.\n    destruct r as [|[|] rl rx rr]; auto.\n    nonzero n. apply rbalS_arb; auto. }\n{ revert n.\n  induct s x; try assumption; try destruct c; try contradiction; invrb.\n  - apply append_arb_rb; assumption.\n  - assert (IHl' := del_arb l x). clear IHr del_arb del_rb.\n    destruct l as [|[|] ll lx lr]; auto.\n    nonzero n. destruct n as [|n]; [invrb|]; apply lbalS_rb; auto.\n  - assert (IHr' := del_arb r x). clear IHl del_arb del_rb.\n    destruct r as [|[|] rl rx rr]; auto.\n    nonzero n. apply rbalS_rb; auto. }\nQed.\n\nInstance remove_rb s x : Rbt s -> Rbt (remove x s).\nProof.\n intros (n,H). unfold remove.\n destruct s as [|[|] l y r].\n - apply (makeBlack_rb n). auto.\n - apply (makeBlack_rb n). left. apply del_rb; simpl; auto.\n - nonzero n. apply (makeBlack_rb n). apply del_arb; simpl; auto.\nQed.\n\n(** ** Treeify *)\n\nDefinition treeify_rb_invariant size depth (f:treeify_t) :=\n forall acc,\n size <= length acc ->\n  rbt depth (fst (f acc)) /\\\n  size + length (snd (f acc)) = length acc.\n\nLemma treeify_zero_rb : treeify_rb_invariant 0 0 treeify_zero.\nProof.\n intros acc _; simpl; auto.\nQed.\n\nLemma treeify_one_rb : treeify_rb_invariant 1 0 treeify_one.\nProof.\n intros [|x acc]; simpl; auto; inversion 1.\nQed.\n\nLemma treeify_cont_rb f g size1 size2 size d :\n treeify_rb_invariant size1 d f ->\n treeify_rb_invariant size2 d g ->\n size = S (size1 + size2) ->\n treeify_rb_invariant size (S d) (treeify_cont f g).\nProof.\n intros Hf Hg H acc Hacc.\n unfold treeify_cont.\n specialize (Hf acc).\n destruct (f acc) as (l, acc1). simpl in *.\n destruct Hf as (Hf1, Hf2). { subst. eauto with arith. }\n destruct acc1 as [|x acc2]; simpl in *.\n - exfalso. revert Hacc. apply Nat.lt_nge. rewrite H, <- Hf2.\n   auto with arith.\n - specialize (Hg acc2).\n   destruct (g acc2) as (r, acc3). simpl in *.\n   destruct Hg as (Hg1, Hg2).\n   { revert Hacc.\n     rewrite H, <- Hf2, Nat.add_succ_r, <- Nat.succ_le_mono.\n     apply Nat.add_le_mono_l. }\n   split; auto.\n   now rewrite H, <- Hf2, <- Hg2, Nat.add_succ_r, Nat.add_assoc.\nQed.\n\nLemma treeify_aux_rb n :\n exists d, forall (b:bool),\n  treeify_rb_invariant (ifpred b (Pos.to_nat n)) d (treeify_aux b n).\nProof.\n induction n as [n (d,IHn)|n (d,IHn)| ].\n - exists (S d). intros b.\n   eapply treeify_cont_rb; [ apply (IHn false) | apply (IHn b) | ].\n   rewrite Pos2Nat.inj_xI.\n   assert (H := Pos2Nat.is_pos n). apply Nat.neq_0_lt_0 in H.\n   destruct b; simpl; intros; rewrite Nat.add_0_r; trivial.\n   now rewrite <- Nat.add_succ_r, Nat.succ_pred; trivial.\n - exists (S d). intros b.\n   eapply treeify_cont_rb; [ apply (IHn b) | apply (IHn true) | ].\n   rewrite Pos2Nat.inj_xO.\n   assert (H := Pos2Nat.is_pos n). apply Nat.neq_0_lt_0 in H.\n   rewrite <- Nat.add_succ_r, Nat.succ_pred by trivial.\n   destruct b; simpl; intros; rewrite Nat.add_0_r; trivial.\n   symmetry. now apply Nat.add_pred_l.\n - exists 0; destruct b;\n    [ apply treeify_zero_rb | apply treeify_one_rb ].\nQed.\n\n(** The black depth of [treeify l] is actually a log2, but\n    we don't need to mention that. *)\n\nInstance treeify_rb l : Rbt (treeify l).\nProof.\n unfold treeify.\n destruct (treeify_aux_rb (plength l)) as (d,H).\n exists d.\n apply H.\n now rewrite plength_spec.\nQed.\n\n(** ** Filtering *)\n\nInstance filter_rb f s : Rbt (filter f s).\nProof.\n unfold filter; auto_tc.\nQed.\n\nInstance partition_rb1 f s : Rbt (fst (partition f s)).\nProof.\n unfold partition. destruct partition_aux. simpl. auto_tc.\nQed.\n\nInstance partition_rb2 f s : Rbt (snd (partition f s)).\nProof.\n unfold partition. destruct partition_aux. simpl. auto_tc.\nQed.\n\n(** ** Union, intersection, difference *)\n\nInstance fold_add_rb s1 s2 : Rbt s2 -> Rbt (fold add s1 s2).\nProof.\n intros. rewrite fold_spec_w, <- fold_left_rev_right. unfold elt in *.\n induction (rev (elements s1)); simpl; unfold flip in *; auto_tc.\nQed.\n\nInstance fold_remove_rb s1 s2 : Rbt s2 -> Rbt (fold remove s1 s2).\nProof.\n intros. rewrite fold_spec_w, <- fold_left_rev_right. unfold elt in *.\n induction (rev (elements s1)); simpl; unfold flip in *; auto_tc.\nQed.\n\nLemma union_rb s1 s2 : Rbt s1 -> Rbt s2 -> Rbt (union s1 s2).\nProof.\n intros. unfold union, linear_union. destruct compare_height; auto_tc.\nQed.\n\nLemma inter_rb s1 s2 : Rbt s1 -> Rbt s2 -> Rbt (inter s1 s2).\nProof.\n intros. unfold inter, linear_inter. destruct compare_height; auto_tc.\nQed.\n\nLemma diff_rb s1 s2 : Rbt s1 -> Rbt s2 -> Rbt (diff s1 s2).\nProof.\n intros. unfold diff, linear_diff. destruct compare_height; auto_tc.\nQed.\n\nEnd BalanceProps.\n\n(** * Final Encapsulation *)\n\nModule Type XSetInterface_Sets_Ext := XSetInterface.Sets <+ XSetRemoveMin.\n\nModule Make (X: Orders.OrderedType) <:\n XSetInterface_Sets_Ext with Module E := X.\n Module Raw. Include MakeRaw X. End Raw.\n Include XSetInterface.Raw2Sets X Raw.\n\n Definition opt_ok (x:option (elt * Raw.t)) :=\n  match x with Some (_,s) => Raw.Ok s | None => True end.\n\n Definition mk_opt_t (x: option (elt * Raw.t))(P: opt_ok x) :\n   option (elt * t) :=\n match x as o return opt_ok o -> option (elt * t) with\n | Some (k,s') => fun P : Raw.Ok s' => Some (k, Mkt s')\n | None => fun _ => None\n end P.\n\n Definition remove_min s : option (elt * t) :=\n  mk_opt_t (Raw.remove_min (this s)) (Raw.remove_min_ok s).\n\n Lemma remove_min_spec1 s x s' :\n  remove_min s = Some (x,s') ->\n   min_elt s = Some x /\\ Equal (remove x s) s'.\n Proof.\n destruct s as (s,Hs).\n unfold remove_min, mk_opt_t, min_elt, remove, Equal, In; simpl.\n generalize (fun x s' => @Raw.remove_min_spec1 s x s' Hs).\n set (P := Raw.remove_min_ok s). clearbody P.\n destruct (Raw.remove_min s) as [(x0,s0)|]; try easy.\n intros H U. injection U. clear U; intros; subst. simpl.\n destruct (H x s0); auto. subst; intuition.\n Qed.\n\n Lemma remove_min_spec2 s : remove_min s = None -> Empty s.\n Proof.\n destruct s as (s,Hs).\n unfold remove_min, mk_opt_t, Empty, In; simpl.\n generalize (Raw.remove_min_spec2 s).\n set (P := Raw.remove_min_ok s). clearbody P.\n destruct (Raw.remove_min s) as [(x0,s0)|]; now intuition.\n Qed.\n\nEnd Make.\n", "meta": {"author": "chiguri", "repo": "XSets", "sha": "12d545eec473a0075b4067d1f6d362a9788548f3", "save_path": "github-repos/coq/chiguri-XSets", "path": "github-repos/coq/chiguri-XSets/XSets-12d545eec473a0075b4067d1f6d362a9788548f3/XSetRBT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.5234203489363239, "lm_q1q2_score": 0.27192803161602475}}
{"text": "(* begin hide *)\n(**********************************************************************)\n(* Equations                                                          *)\n(* Copyright (c) 2009-2021 Matthieu Sozeau <matthieu.sozeau@inria.fr> *)\n(**********************************************************************)\n(* This file is distributed under the terms of the                    *)\n(* GNU Lesser General Public License Version 2.1                      *)\n(**********************************************************************)\n(* end hide *)\n(** * Definitional interpreter for STLC extended with references\n\n  This is a port of the first part of \"Intrinsically-Typed Definitional\n  Interpreters for Imperative Languages\", Poulsen, Rouvoet, Tolmach,\n  Krebbers and Visser. POPL'18.\n\n  It uses well-typed and well-scoped syntax and a monad indexed over an\n  indexed set of stores to define an interpreter for an imperative\n  programming language.\n\n  This showcases the use of dependent pattern-matching and\n  pattern-matching lambdas in Equations. We implement a variant where\n  store extension is resolved using type class resolution as well as the\n  dependent-passing style version. *)\n\nRequire Import Program.Basics Program.Tactics.\nRequire Import Coq.Vectors.VectorDef.\nRequire Import List.\nImport ListNotations.\nRequire Import Utf8.\nFrom Equations Require Import Equations.\n\nSet Warnings \"-notation-overridden\".\n(** The Σ notation of equations clashes with the Σ's used below,\n    so we redefine the Σ notation using ∃ instead.\n *)\n\nNotation \"'∃' x .. y , P\" := (sigma (fun x => .. (sigma (fun y => P)) ..))\n  (at level 200, x binder, y binder, right associativity,\n  format \"'[  ' '[  ' ∃  x  ..  y ']' ,  '/' P ']'\") : type_scope.\n\nNotation \"( x , .. , y , z )\" :=\n  (@sigmaI _ _ x .. (@sigmaI _ _ y z) ..)\n      (right associativity, at level 0,\n       format \"( x ,  .. ,  y ,  z )\") : equations_scope.\n\nNotation \" x .1 \" := (pr1 x) (at level 3, format \"x .1\") : equations_scope.\nNotation \" x .2 \" := (pr2 x) (at level 3, format \"x .2\") : equations_scope.\n\nLocal Open Scope equations_scope.\n\nSet Equations Transparent.\n\n(** [t] is just [Vector.t] here. *)\nDerive Signature NoConfusion NoConfusionHom for t.\n\n(** Types include unit, bool, function types and references *)\nInductive Ty : Set :=\n| unit : Ty\n| bool : Ty\n| arrow (t u : Ty) : Ty\n| ref : Ty -> Ty.\n\nDerive NoConfusion for Ty.\n\nInfix \"⇒\" := arrow (at level 80).\n\nDefinition Ctx := list Ty.\n\nReserved Notation \" x ∈ s \" (at level 70, s at level 10).\n\n#[universes(template)]\nInductive In {A} (x : A) : list A -> Type :=\n| here {xs} : x ∈ (x :: xs)\n| there {y xs} : x ∈ xs -> x ∈ (y :: xs)\nwhere \" x ∈ s \" := (In x s).\nDerive Signature NoConfusion for In.\n\nArguments here {A x xs}.\nArguments there {A x y xs} _.\n\nInductive Expr : Ctx -> Ty -> Set :=\n| tt {Γ} : Expr Γ unit\n| true {Γ} : Expr Γ bool\n| false {Γ} : Expr Γ bool\n| ite {Γ t} : Expr Γ bool -> Expr Γ t -> Expr Γ t -> Expr Γ t\n| var {Γ} {t} : In t Γ -> Expr Γ t\n| abs {Γ} {t u} : Expr (t :: Γ) u -> Expr Γ (t ⇒ u)\n| app {Γ} {t u} : Expr Γ (t ⇒ u) -> Expr Γ t -> Expr Γ u\n| new {Γ t} : Expr Γ t -> Expr Γ (ref t)\n| deref {Γ t} : Expr Γ (ref t) -> Expr Γ t\n| assign {Γ t} : Expr Γ (ref t) -> Expr Γ t -> Expr Γ unit.\n\n(** We derive both [NoConfusion] and [NoConfusionHom] principles here, the later\n    allows to simplify pattern-matching problems on [Expr] which would otherwise\n    require K. It relies on an inversion analysis of every constructor, showing\n    that the context and type indexes in the conclusions of every constructor\n    are forced arguments. *)\nDerive Signature NoConfusion NoConfusionHom for Expr.\n\n#[universes(template)]\nInductive All {A} (P : A -> Type) : list A -> Type :=\n| all_nil : All P []\n| all_cons {x xs} : P x -> All P xs -> All P (x :: xs).\nArguments all_nil {A} {P}.\nArguments all_cons {A P x xs} _ _.\nDerive Signature NoConfusion NoConfusionHom for All.\n\nSection MapAll.\n  Context {A} {P Q : A -> Type} (f : forall x, P x -> Q x).\n\n  Equations map_all {l : list A} : All P l -> All Q l :=\n   | all_nil := all_nil\n   | all_cons p ps := all_cons (f _ p) (map_all ps).\n\n  Equations map_all_in {l : list A} (f : forall x, x ∈ l -> P x -> Q x) : All P l -> All Q l :=\n    | f, all_nil := all_nil\n    | f,  all_cons p ps := all_cons (f _ here p) (map_all_in (fun x inl => f x (there inl)) ps).\nEnd MapAll.\n\nDefinition StoreTy := list Ty.\n\nInductive Val : Ty -> StoreTy -> Set :=\n| val_unit {Σ} : Val unit Σ\n| val_true {Σ} : Val bool Σ\n| val_false {Σ} : Val bool Σ\n| val_closure {Σ Γ t u} : Expr (t :: Γ) u -> All (fun t => Val t Σ) Γ -> Val (t ⇒ u) Σ\n| val_loc {Σ t} : t ∈ Σ -> Val (ref t) Σ.\n\nDerive Signature NoConfusion NoConfusionHom for Val.\n\nDefinition Env (Γ : Ctx) (Σ : StoreTy) : Set := All (fun t => Val t Σ) Γ.\n\nDefinition Store (Σ : StoreTy) := All (fun t => Val t Σ) Σ.\n\nEquations lookup : forall {A P xs} {x : A}, All P xs -> x ∈ xs -> P x :=\n  lookup (all_cons p _) here := p;\n  lookup (all_cons _ ps) (there ins) := lookup ps ins.\n\nEquations update : forall {A P xs} {x : A}, All P xs -> x ∈ xs -> P x -> All P xs :=\n  update (all_cons p ps) here        p' := all_cons p' ps;\n  update (all_cons p ps) (there ins) p' := all_cons p (update ps ins p').\n\nEquations lookup_store {Σ t} : t ∈ Σ -> Store Σ -> Val t Σ :=\n  lookup_store l σ := lookup σ l.\n\nEquations update_store {Σ t} : t ∈ Σ -> Val t Σ -> Store Σ -> Store Σ :=\n  update_store l v σ := update σ l v.\n\nDefinition store_incl (Σ Σ' : StoreTy) := sigma (fun Σ'' => Σ' = Σ'' ++ Σ).\nInfix \"⊑\" := store_incl (at level 10).\n\nEquations app_assoc {A} (x y z : list A) : x ++ y ++ z = (x ++ y) ++ z :=\n  app_assoc nil y z := eq_refl;\n  app_assoc (cons x xs) y z := f_equal (cons x) (app_assoc xs y z).\n\nSection StoreIncl.\n  Equations pres_in {Σ Σ'} (incl : Σ ⊑ Σ') t (p : t ∈ Σ) : t ∈ Σ' :=\n    pres_in (Σ'', eq_refl) t p := aux Σ''\n       where aux Σ'' : t ∈ (Σ'' ++ Σ) :=\n       aux nil := p;\n       aux (cons ty tys) := there (aux tys).\n\n  Equations refl_incl {Σ} : Σ ⊑ Σ := refl_incl := ([], eq_refl).\n\n  Equations trans_incl {Σ Σ' Σ''} (incl : Σ ⊑ Σ') (incl' : Σ' ⊑ Σ'') : Σ ⊑ Σ'' :=\n    trans_incl (p, eq_refl) (q, eq_refl) := (q ++ p, app_assoc _ _ _).\n\n  Equations store_ext_incl {Σ t} : Σ ⊑ (t :: Σ) :=\n    store_ext_incl := ([t], eq_refl).\n\n  Context {Σ Σ'} (incl : Σ ⊑ Σ').\n\n  Equations weaken_val {t} (v : Val t Σ) : Val t Σ' := {\n   weaken_val (@val_unit ?(Σ)) := val_unit;\n   weaken_val val_true := val_true;\n   weaken_val val_false := val_false;\n   weaken_val (val_closure b e) := val_closure b (weaken_vals e);\n   weaken_val (val_loc H) := val_loc (pres_in incl _ H) }\n  where weaken_vals {l} (a : All (fun t => Val t Σ) l) : All (fun t => Val t Σ') l :=\n  weaken_vals all_nil := all_nil;\n  weaken_vals (all_cons p ps) := all_cons (weaken_val p) (weaken_vals ps).\n\n  Equations weakenv_vals {l} a : @weaken_vals l a = map_all (fun t v => weaken_val v) a :=\n    weakenv_vals all_nil := eq_refl;\n    weakenv_vals (all_cons p ps) := f_equal (all_cons (weaken_val p)) (weakenv_vals ps).\n\n  Definition weaken_env {Γ} (v : Env Γ Σ) : Env Γ Σ' := map_all (@weaken_val) v.\n\nEnd StoreIncl.\n\nInfix \"⊚\" := trans_incl (at level 10).\n\nEquations M : forall (Γ : Ctx) (P : StoreTy -> Type) (Σ : StoreTy), Type :=\n  M Γ P Σ := forall (E : Env Γ Σ) (μ : Store Σ), option (∃ Σ' (μ' : Store Σ') (_ : P Σ'), Σ ⊑ Σ').\n\nEquations bind {Σ Γ} {P Q : StoreTy -> Type} (f : M Γ P Σ) (g : ∀ {Σ'}, P Σ' -> M Γ Q Σ') : M Γ Q Σ :=\n  bind f g E μ with f E μ :=\n     | None := None\n     | Some (Σ', μ', x, ext) with g _ x (weaken_env ext E) μ' :=\n          | None := None;\n          | Some (_, μ'', y, ext') := Some (_, μ'', y, ext ⊚ ext').\n\nInfix \">>=\" := bind (at level 20, left associativity).\n\nDefinition transp_op {Γ Σ P} (x : Store Σ -> P Σ) : M Γ P Σ :=\n  fun E μ => Some (Σ, μ, x μ, refl_incl).\n\nEquations ret : ∀ {Γ Σ P}, P Σ → M Γ P Σ :=\n  ret (Σ:=Σ) a E μ := Some (Σ, μ, a, refl_incl).\n\nEquations getEnv : ∀ {Γ Σ}, M Γ (Env Γ) Σ :=\n  getEnv (Σ:=Σ) E μ := Some (Σ, μ, E, refl_incl).\n\nEquations usingEnv {Γ Γ' Σ P} (E : Env Γ Σ) (m : M Γ P Σ) : M Γ' P Σ :=\n  usingEnv E m E' μ := m E μ.\n\nEquations timeout : ∀ {Γ Σ P}, M Γ P Σ :=\n  timeout _ _ := None.\n\nSection StoreOps.\n  Context {Σ : StoreTy} {Γ : Ctx} {t : Ty}.\n\n  Equations storeM (v : Val t Σ) : M Γ (Val (ref t)) Σ :=\n    storeM v E μ :=\n      let v : Val t (t :: Σ) := weaken_val store_ext_incl v in\n      let μ' := map_all (fun t' => weaken_val store_ext_incl) μ in\n      Some (t :: Σ, all_cons v μ', val_loc here, store_ext_incl).\n\n  Equations derefM (l : t ∈ Σ) : M Γ (Val t) Σ :=\n    derefM l := transp_op (lookup_store l).\n\n  Equations updateM (l : t ∈ Σ) (v : Val t Σ) : M Γ (Val unit) Σ :=\n    updateM l v E μ := Some (Σ, update_store l v μ, val_unit, refl_incl).\nEnd StoreOps.\n\nReserved Notation \"P ⊛ Q\" (at level 10).\n\nInductive storepred_prod (P Q : StoreTy -> Type) : StoreTy -> Type :=\n  | storepred_pair {Σ} : P Σ -> Q Σ -> (P ⊛ Q) Σ\nwhere \"P ⊛ Q\" := (storepred_prod P Q).\nArguments storepred_pair {P Q Σ}.\n\nClass Weakenable (P : StoreTy -> Type) : Type :=\n  weaken : forall {Σ Σ'}, Σ ⊑ Σ' -> P Σ -> P Σ'.\n\n#[local] Instance val_weaken {t} : Weakenable (Val t) := fun Σ Σ' incl => weaken_val incl.\n#[local] Instance env_weaken {Γ} : Weakenable (Env Γ) := fun Σ Σ' incl => weaken_env incl.\n#[local] Instance loc_weaken (t : Ty) : Weakenable (In t) := fun Σ Σ' incl => pres_in incl t.\n\nClass IsIncludedOnce (Σ Σ' : StoreTy) : Type := is_included_once : Σ ⊑ Σ'.\n#[local] Hint Mode IsIncludedOnce + + : typeclass_instances.\n\n#[local] Instance IsIncludedOnce_ext {T} Σ : IsIncludedOnce Σ (T :: Σ) := store_ext_incl.\n\nClass IsIncluded (Σ Σ' : StoreTy) : Type := is_included : Σ ⊑ Σ'.\n#[local] Hint Mode IsIncluded + + : typeclass_instances.\n\n#[local] Instance IsIncluded_refl Σ : IsIncluded Σ Σ := refl_incl.\n#[local] Instance IsIncluded_trans Σ Σ' Σ'' : IsIncludedOnce Σ Σ' -> IsIncluded Σ' Σ'' -> IsIncluded Σ Σ'' :=\n  fun H H' => trans_incl H H'.\n\nEquations wk {Σ Σ' P} {W : Weakenable P} (p : P Σ) {incl : IsIncluded Σ Σ'} : P Σ' :=\n  wk p := weaken incl p.\n\nEquations bind_ext {Σ Γ} {P Q : StoreTy -> Type} (f : M Γ P Σ) (g : ∀ {Σ'} `{IsIncluded Σ Σ'}, P Σ' -> M Γ Q Σ') : M Γ Q Σ :=\n  bind_ext f g E μ with f E μ :=\n    { | None := None;\n      | Some (Σ', μ', x, ext) with g _ ext x (weaken_env ext E) μ' :=\n          { | None := None;\n            | Some (_, μ'', y, ext') := Some (_, μ'', y, ext ⊚ ext') } }.\n\nInfix \">>='\" := bind_ext (at level 20, left associativity).\n\nEquations eval_ext (n : nat) {Γ Σ t} (e : Expr Γ t) : M Γ (Val t) Σ :=\n  | 0, _                := timeout\n  | S k, tt           := ret val_unit\n  | S k, true         := ret val_true\n  | S k, false        := ret val_false\n  | S k, ite b tr fa    := eval_ext k b >>=' λ{ | _ | ext | val_true => eval_ext k tr;\n                                                      | _ | ext | val_false => eval_ext k fa }\n\n  | S k, var x        := getEnv >>=' fun {Σ ext} E => ret (lookup E x)\n  | S k, abs x        := getEnv >>=' fun {Σ ext} E => ret (val_closure x E)\n  | S k, @app Γ A B e1 e2 :=\n      eval_ext k e1 >>=' λ{ | _ | ext | val_closure e' E =>\n      eval_ext k e2 >>=' fun {Σ' ext'} v => usingEnv (all_cons v (wk (P:=Env _) E)) (eval_ext k e')}\n  | S k, new e      := eval_ext k e >>=' fun {Σ ext} v => storeM v\n  | S k, deref l    := eval_ext k l >>=' λ{ | _ | ext | val_loc l' => derefM l' }\n  | S k, assign l e := eval_ext k l >>=' λ{ | _ | ext | val_loc l' =>\n                                eval_ext k e >>=' λ{ | _ | ext' | v => updateM (wk l') (wk v) }}.\n\nEquations strength {Σ Γ} {P Q : StoreTy -> Type} {w : Weakenable Q} (m : M Γ P Σ) (q : Q Σ) : M Γ (P ⊛ Q) Σ :=\n  strength m q E μ with m E μ => {\n    | None => None\n    | Some (Σ', μ', p, ext) => Some (Σ', μ', storepred_pair p (weaken ext q), ext) }.\n\nInfix \"^\" := strength.\n\n(* Issue: improve pattern matching lambda to have implicit arguments implicit.\n   Hard because Coq does not keep the implicit status of bind's [g] argument. *)\n\nEquations eval (n : nat) {Γ Σ t} (e : Expr Γ t) : M Γ (Val t) Σ :=\n  eval 0 _                := timeout;\n  eval (S k) tt           := ret val_unit;\n  eval (S k) true         := ret val_true;\n  eval (S k) false        := ret val_false;\n  eval (S k) (ite b tr fa)  := eval k b >>= λ{ | _ | val_true => eval k tr;\n                                             | _ | val_false => eval k fa };\n\n  eval (S k) (var x)      := getEnv >>= fun Σ E => ret (lookup E x);\n  eval (S k) (abs x)      := getEnv >>= fun Σ E => ret (val_closure x E);\n  eval (S k) (app e1 e2) :=\n      eval k e1 >>= λ{ | _ | val_closure e' E =>\n                             (eval k e2 ^ E) >>= fun Σ' '(storepred_pair v E) => usingEnv (all_cons v E) (eval k e')};\n  eval (S k) (new e)      := eval k e >>= fun Σ v => storeM v;\n  eval (S k) (deref l)    := eval k l >>= λ{ | _ | val_loc l' => derefM l' };\n  eval (S k) (assign l e) := eval k l >>= λ{ | _ | val_loc l' =>\n                             (eval k e ^ l') >>= λ{ | _ | storepred_pair v l'' => updateM l'' v }}.\n\nDefinition idu : Expr [] (unit ⇒ unit) :=\n  abs (var here).\n\nDefinition idapp : Expr [] unit := app idu tt.\n\n(** All definitions are axiom-free (and actually not even dependent on a provable UIP instance), so\n everything computes. *)\nEval vm_compute in eval 100 idapp all_nil all_nil.\n\nDefinition neg : Expr [] (bool ⇒ bool) :=\n  abs (ite (var here) false true).\n\nDefinition letref {t u} (v : Expr [] t) (b : Expr [ref t] u) : Expr [] u :=\n  app (abs b) (new v).\nObligation Tactic := idtac.\n\nEquations in_app_weaken {Σ Σ' Σ'' : StoreTy} {t} (p : t ∈ (Σ ++ Σ'')) : t ∈ (Σ ++ Σ' ++ Σ'') by struct Σ :=\n  in_app_weaken (Σ:=nil) p := pres_in (Σ', eq_refl) t p;\n  in_app_weaken (Σ:=cons _ tys) here := here;\n  in_app_weaken (Σ:=cons _ tys) (there p) := there (in_app_weaken p).\n\nEquations pres_in_prefix {Σ Σ' Σ''} (incl : Σ' ⊑ Σ'') {t} (p : t ∈ (Σ ++ Σ')) : t ∈ (Σ ++ Σ'') :=\n  pres_in_prefix (Σ'', eq_refl) p := in_app_weaken p.\n\n(** [Equations?] enters refinement mode, which can be used to solve the case of variables in proof mode. *)\nEquations? weaken_expr {Γ Γ' t u} (e1 : Expr (Γ ++ Γ') t) : Expr (Γ ++ u :: Γ') t :=\n  weaken_expr tt              := tt;\n  weaken_expr true            := true;\n  weaken_expr false           := false;\n  weaken_expr (ite b tr fa)   := ite (weaken_expr b) (weaken_expr tr) (weaken_expr fa);\n  weaken_expr (var (t:=ty) x) := var _;\n  weaken_expr (abs (t:=t) x)  := abs (weaken_expr (Γ := t :: Γ) x);\n  weaken_expr (app e1 e2)     := app (weaken_expr e1) (weaken_expr e2);\n  weaken_expr (new e)         := new (weaken_expr e);\n  weaken_expr (deref l)       := deref (weaken_expr l);\n  weaken_expr (assign l e)    := assign (weaken_expr l) (weaken_expr e).\nProof.\n  clear weaken_expr. apply (pres_in_prefix (Σ' := Γ') ([u], eq_refl) x).\nDefined.\n\nDefinition seq {Γ u} (e1 : Expr Γ unit) (e2 : Expr Γ u) : Expr Γ u :=\n  app (abs (weaken_expr (Γ := []) e2)) e1.\n\n(* let x = ref true in\n   x := false; !x *)\n\nDefinition letupdate : Expr [] bool :=\n  letref true (seq (assign (var here) false) (deref (var here))).\n\nEval vm_compute in eval 100 letupdate all_nil all_nil.\n(** [[\n   = Some ([bool], all_cons val_false all_nil, val_false, [bool], eq_refl)\n   : option (∃ (Σ' : StoreTy) (_ : Store Σ') (_ : Val bool Σ'), [] ⊑ Σ')\n   ]]\n*)\n", "meta": {"author": "mattam82", "repo": "Coq-Equations", "sha": "5603bfff39f3866eed8f010591b5503d5776fa4e", "save_path": "github-repos/coq/mattam82-Coq-Equations", "path": "github-repos/coq/mattam82-Coq-Equations/Coq-Equations-5603bfff39f3866eed8f010591b5503d5776fa4e/examples/definterp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2717293381434518}}
{"text": "(**\nCoLoR, a Coq library on rewriting and termination.\nSee the COPYRIGHTS and LICENSE files.\n\n- Adam Koprowski, 2006-04-27\n\nThe beta-reduction relation of simply typed lambda-calculus\nis introduced in this file.\n*)\n\nSet Implicit Arguments.\n\nFrom CoLoR Require Import RelExtras ListExtras TermsRed TermsConv LogicUtil.\nFrom Coq Require Import Setoid Lia.\n\nModule TermsBeta (Sig : TermsSig.Signature).\n\n  Module Export TR := TermsRed.TermsRed Sig.\n\n  Definition beta_subst : forall M (Mapp: isApp M)\n    (MLabs: isAbs (appBodyL Mapp)),\n    correct_subst (absBody MLabs) {x/(lift (appBodyR Mapp) 1)}.\n\n  Proof.\n    intros M Mapp MLabs.\n    apply one_var_subst_correct.\n    rewrite lift_type.\n    rewrite absBody_env.\n    unfold decl, VarD; simpl.\n    intros A' eqT.\n    inversion eqT.\n    destruct M as [EM PtM TM TypM].\n    destruct TypM; try contr.\n    rewrite (@abs_type (appBodyL Mapp) MLabs A B); trivial.\n    rewrite lift_env.\n    rewrite absBody_env.\n    unfold liftedEnv, finalSeg; simpl.\n    rewrite initialSeg_full; try solve [auto with datatypes | lia].\n    unfold decl; apply env_comp_cons.\n    rewrite appBodyL_env.\n    rewrite appBodyR_env.\n    apply env_comp_refl.\n    auto.\n  Defined.\n\n  Lemma beta_env : forall M (Mapp: isApp M) (MLabs: isAbs (appBodyL Mapp)),\n    env (subst (beta_subst M Mapp MLabs)) = None :: env M.\n\n  Proof.\n    intros.\n    rewrite subst_env; simpl.\n    unfold subst_ran; simpl.\n    rewrite lift_env; simpl.\n    unfold liftedEnv; simpl.\n    rewrite absBody_env; simpl.\n    rewrite appBodyL_env; simpl.\n    rewrite finalSeg_full; simpl.\n    rewrite appBodyR_env; simpl.\n    rewrite env_sub_empty.\n    rewrite env_sum_double; trivial.\n  Qed.\n\n  Lemma beta_lowering : forall M (Mapp: isApp M) (MLabs: isAbs (appBodyL Mapp)),\n    env (subst (beta_subst M Mapp MLabs)) |= 0 :! .\n\n  Proof. intros. rewrite beta_env. right; trivial. Qed.\n\n  Inductive BetaStep : relation Term :=\n  | Beta: forall M (Mapp: isApp M) (MLabs: isAbs (appBodyL Mapp)),\n      BetaStep M\n      (lower (subst (beta_subst M Mapp MLabs)) (beta_lowering M Mapp MLabs)).\n\n  Definition BetaReduction := Reduction BetaStep.\n\n  Notation \"M -b-> N\" := (BetaReduction M N) (at level 30).\n\n  Lemma beta_type: forall M (Mapp: isApp M) (MLabs: isAbs (appBodyL Mapp)),\n    absType MLabs = type (appBodyR Mapp).\n\n  Proof.\n    intros.\n    destruct M as [??? typingM].\n    destruct typingM; try contr.\n    assert (type (appBodyL Mapp) = A --> B).\n    trivial.\n    rewrite (abs_type (appBodyL Mapp) MLabs H); trivial.\n  Qed.\n\n  Lemma beta_notFunS: forall M N, M -b-> N -> isFunS M -> False.\n\n  Proof.\n    intros M N MN.\n    term_inv M.\n    unfold Tr in MN.\n    inversion MN; term_inv M.\n    inversion H; try_solve.\n  Qed.\n\n  Lemma beta_direct_funApp : forall M (Mapp: isApp M)\n    (MLabs: isAbs (appBodyL Mapp)), isFunS (appHead M) -> False.\n\n  Proof.\n    intros M Mapp MLabs Mhead.\n    absurd (isFunS (appHead M)); trivial.\n    rewrite (appHead_app M Mapp) in Mhead.\n    assert (MLnotApp: ~isApp (appBodyL Mapp)).\n    apply abs_isnot_app; trivial.\n    rewrite (appHead_notApp (appBodyL Mapp) MLnotApp) in Mhead.\n    exfalso. term_inv (appBodyL Mapp).\n  Qed.\n\n  Lemma app_beta_isapp : forall M N f,\n    M -b-> N -> term (appHead M) = ^f -> isApp N.\n\n  Proof.\n    intro M; term_inv M.\n     (* function symbol *)\n    intros; exfalso.\n    apply beta_notFunS with Tr N; trivial.\n    unfold Tr; auto with terms.\n     (* application *)\n    intros N f MbN Mhead.\n    inversion MbN; try solve [contr | trivial].\n     (* direct beta step *)\n    exfalso. inversion H.\n    apply beta_direct_funApp with Tr I; eauto with terms.\n  Qed.\n\n  Lemma app_beta_headSymbol : forall M N f, M -b-> N -> term (appHead M) = ^f ->\n    term (appHead N) = ^f.\n\n  Proof.\n    destruct M as [E Pt T TypM].\n    induction TypM; simpl; intros N f' Nbeta Mhead; try discr;\n      inversion Nbeta; try contr.\n    inversion H; contr.\n     (* 1) direct beta reduction (left applicant - abstraction) *)\n    inversion H. exfalso.\n    apply beta_direct_funApp with (buildT (TApp TypM1 TypM2)) Mapp0;\n      eauto with terms.\n     (* 2) beta reduction in left part of application *)\n    term_inv N.\n    unfold Tr.\n    rewrite appHead_app_explicit.\n    apply IHTypM1 with (N := @appBodyL (buildT (TApp T1 T2)) I).\n    simpl; trivial.\n    rewrite appHead_app_explicit in Mhead; trivial.\n     (* 3) beta reduction in right part of application *)\n    term_inv N.\n    rewrite <- Mhead.\n    unfold Tr.\n    rewrite !appHead_app_explicit.\n    congruence.\n  Qed.\n\n  Lemma app_beta_funS : forall M N,\n    isFunS (appHead M) -> M -b-> N -> isFunS (appHead N).\n\n  Proof.\n    intros.\n    destruct (funS_fun (appHead M) H) as [f Mf].\n    apply funS_is_funS with f.\n    apply (app_beta_headSymbol H0 Mf).\n  Qed.\n\n  Lemma app_beta_args : forall M N f,\n    isApp M -> M -b-> N -> term (appHead M) = ^f ->\n    exists l, exists el, isArg (fst el) M /\\ isArg (snd el) N\n      /\\ fst el -b-> snd el /\\\n      appArgs M = fst l ++ fst el::snd l /\\ appArgs N = fst l ++ snd el::snd l.\n\n  Proof.\n    destruct M as [E Pt T TypM].\n    induction TypM; try solve [intros; inversion H].\n    intros N f Mapp MbetaN Mhead.\n    inversion MbetaN; try contr.\n    inversion H. exfalso.\n    apply beta_direct_funApp with (buildT (TApp TypM1 TypM2)) Mapp1;\n      eauto with terms.\n     (* -) beta in left argument *)\n    simpl in *.\n    rewrite (appHead_app (buildT (TApp TypM1 TypM2)) I) in Mhead; \n      trivial.\n    case (isApp_dec (buildT TypM1)).\n    intro M1app.\n     (*   - M = @(@(...), _) *)\n    destruct (IHTypM1 (appBodyL Napp) f) \n      as [[al ar] [[tl tr] [tlM [trN [tltr [Margs Nargs]]]]]];\n      simpl in *; trivial.\n    exists (al, ar ++ appBodyR Napp::nil); exists (tl, tr); \n      repeat split; simpl; trivial.\n    apply appArg_left with I; trivial.\n    apply appArg_left with Napp; trivial.\n    rewrite (appArgs_app (buildT (TApp TypM1 TypM2)) I); simpl.\n    rewrite Margs; rewrite H0.\n    rewrite <- ass_app; auto with datatypes.\n    rewrite (appArgs_app N Napp); simpl.\n    rewrite Nargs.\n    rewrite <- ass_app; auto with datatypes.\n     (*   - M = @(_, _) *)\n    intro M1nApp; simpl in *.\n    rewrite appHead_notApp in Mhead; simpl in Mhead. exfalso.\n    apply beta_notFunS with (buildT TypM1) (appBodyL Napp); \n      eauto with terms.\n    trivial.\n     (* -) beta in right argument *)\n    term_inv N.\n    exists (appArgs (buildT TypM1), nil(A:=Term)).\n    exists (buildT TypM2, buildT T2); repeat split; simpl; trivial.\n    apply appArg_right with I; trivial.\n    apply appArg_right with I; trivial.\n    rewrite appArgs_app with (buildT (TApp TypM1 TypM2)) I; trivial.\n    rewrite appArgs_app with Tr I.\n    rewrite H0; trivial.\n  Qed.\n\n  Lemma app_beta_args_eq : forall M N Q f,\n    isApp M -> M -b-> N -> term (appHead M) = ^f ->\n    isArg Q N -> (isArg Q M \\/ (exists2 Mb, Mb -b-> Q & isArg Mb M)).\n\n  Proof.\n    intros M N Q f Mapp MbN Mhead QargN.\n    destruct (app_beta_args Mapp MbN Mhead) as \n      [[al ar] [[tl tr] [tlM [trN [tltr [Margs Nargs]]]]]];\n      simpl in * .\n    unfold isArg in QargN; rewrite Nargs in QargN.\n    destruct (in_app_or QargN).\n    left.\n    unfold isArg; rewrite Margs; auto with datatypes.\n    inversion H.\n    right; exists tl.\n    rewrite <- H0; trivial.\n    unfold isArg; rewrite Margs; auto with datatypes.\n    left.\n    unfold isArg; rewrite Margs; auto with datatypes.\n  Qed.\n\n  Lemma beta_funS_normal : forall M N, isFunS M -> ~(M -b-> N).\n\n  Proof. intros M N Mf MN. inversion MN; inversion H; term_inv M. Qed.\n\n  Lemma beta_var_normal : forall M N, isVar M -> ~(M -b-> N).\n\n  Proof. intros M N Mvar MN. inversion MN; inversion H; term_inv M. Qed.\n\n  Lemma betaStep_env_preserving : forall M N, BetaStep M N -> env M = env N.\n\n  Proof.\n    intros.\n    inversion H.\n    rewrite lower_env.\n    rewrite beta_env.\n    unfold loweredEnv, finalSeg; simpl.\n    rewrite initialSeg_full; trivial.\n    lia.\n  Qed.\n\n  Lemma beta_env_preserving : forall M N, M -b-> N -> env M = env N.\n\n  Proof.\n    intros.\n    apply Red_env_preserving with BetaStep; trivial.\n    apply betaStep_env_preserving.\n  Qed.\n\n  Lemma betaStep_type_preserving : forall M N, BetaStep M N -> type M = type N.\n\n  Proof.\n    intros.\n    inversion H.\n    rewrite lower_type.\n    rewrite subst_type.\n    destruct M as [ME MPt MT M].\n    destruct M; try contr.\n    assert (MlT: type (appBodyL Mapp0) = A --> B); [simpl; trivial | idtac].\n    rewrite (absBody_type (appBodyL Mapp0) MLabs MlT); simpl; trivial.\n  Qed.\n\n  Lemma subject_reduction : forall M N, M -b-> N -> type M = type N.\n\n  Proof.\n    intros.\n    apply Red_type_preserving with BetaStep; trivial.\n    apply betaStep_type_preserving.\n  Qed.\n\n  Lemma beta_monotonous : monotonous BetaReduction.\n\n  Proof. unfold BetaReduction; apply red_monotonous. Qed.\n\n  Lemma betaStep_conv_comp_aux : forall M M' N N' Q, M ~(Q) M' -> N ~(Q) N' ->\n    BetaStep M N -> env M' = env N' -> BetaStep M' N'.\n\n  Proof.\n    intros M M' N N' Q MQM' NQN' MN M'N'env.\n    inversion MN.\n    assert (M'app: isApp M').\n    assert (MM' : M ~ M') by (exists Q; trivial).\n    rewrite <- MM'; trivial.\n    assert (M'Labs: isAbs (appBodyL M'app)).\n    setoid_replace (appBodyL M'app) with (appBodyL Mapp0); trivial.\n    apply app_conv_app_left.\n    sym; exists Q; trivial.\n    replace N' with (lower (subst (beta_subst M' M'app M'Labs)) \n      (beta_lowering M' M'app M'Labs)).\n    constructor.\n    rewrite terms_lift_eq with (lower (subst (beta_subst M' M'app M'Labs))\n      (beta_lowering M' M'app M'Labs)) N'; trivial.\n    apply term_eq.\n    autorewrite with terms datatypes using unfold liftedEnv, loweredEnv; simpl.\n    rewrite M'N'env; trivial.\n    rewrite prelift_prelower.\n    autorewrite with terms.\n    rewrite <- lift_term.\n    apply (@presubst_singleton_conv_sim \n      (term (absBody MLabs)) (term (absBody M'Labs))\n      (lift (appBodyR Mapp0) 1) (lift (appBodyR M'app) 1) (envSubst_lift1 Q)\n      (term (lift N 1)) (term (lift N' 1))\n    ).\n    destruct Q; simpl; trivial.\n    assert (Conv: (absBody MLabs) ~(envSubst_lift1 Q) (absBody M'Labs)).\n    apply abs_conv_absBody_aux.\n    apply app_conv_app_left_aux; trivial.\n    destruct Conv; trivial.\n    apply terms_conv_conv_lift.\n    apply app_conv_app_right_aux; trivial.\n    assert (Conv: (lift N 1) ~(envSubst_lift1 Q) (lift N' 1)).\n    apply terms_conv_conv_lift; trivial.\n    destruct Conv; trivial.\n    rewrite <- H0.\n    rewrite prelift_prelower.\n    autorewrite with terms using trivial.\n  Qed.\n\n  Lemma beta_conv_comp : forall M M' N N' Q,\n    M ~(Q) M' -> N ~(Q) N' -> M -b-> N -> env M' = env N' -> M' -b-> N'.\n\n  Proof.\n    intros.\n    unfold BetaReduction.\n    apply red_conv_comp with M N Q; trivial.\n    intros.\n    apply betaStep_conv_comp_aux with M0 N0 Q0; trivial.\n  Qed.\n\n  Lemma subst_at0 : forall M G (MG: correct_subst M (None :: lift_subst G 1)),\n    env M |= 0 :! -> env (subst MG) |= 0 :! .\n\n  Proof.\n    intros.\n    rewrite subst_env.\n    destruct (env M).\n    rewrite subst_ran_cons_none.\n    destruct (subst_empty_dec G); simpl.\n    rewrite subst_ran_lifted_empty; trivial.\n    rewrite subst_ran_lifted_ne; solve [trivial | constructor 2; trivial].\n    destruct o.\n    destruct H; try_solve.\n    simpl.\n    rewrite subst_ran_cons_none.\n    destruct (subst_empty_dec G); simpl.\n    rewrite subst_ran_lifted_empty; trivial.\n    rewrite subst_ran_lifted_ne; solve [trivial | constructor 2; trivial].\n  Qed.\n\n  Lemma subst_envs_comp_cons : forall G,\n    subst_envs_comp G -> subst_envs_comp (None :: G).\n\n  Proof.\n    intros.\n    intros i j Ti Tj Gi Gj.\n    destruct i; destruct j.\n    try_solve.\n    inversion Gi.\n    inversion Gj.\n    apply (H i j).\n    inversion Gi; trivial.\n    inversion Gj; trivial.\n  Qed.\n\n  Lemma correct_subst_lift : forall M N G (M0: env M |= 0 :!),\n    correct_subst N G -> N = lower M M0 ->\n    correct_subst M (None :: lift_subst G 1).\n\n  Proof.\n    intros ???? [envNG domNG ranNG] H.\n    rewrite H in domNG.\n    rewrite H in ranNG.\n    rewrite lower_env in domNG.\n    rewrite lower_env in ranNG.\n    clear H.\n    constructor.\n    apply subst_envs_comp_cons.\n    apply lifted_subst_envs_comp; trivial.\n    destruct (env M).\n    apply env_comp_empty.\n    destruct o.\n    destruct M0; try_solve.\n    simpl.\n    rewrite subst_dom_lifted.\n    apply env_comp_cons; auto.\n    unfold loweredEnv in domNG.\n    simpl in domNG.\n    rewrite finalSeg_cons in domNG; trivial.\n    simpl.\n    rewrite subst_ran_cons_none.\n    rewrite subst_dom_lifted.\n    destruct (subst_empty_dec G).\n    rewrite subst_ran_lifted_empty; trivial.\n    simpl; apply env_comp_sym; apply env_comp_empty.\n    rewrite subst_ran_lifted_ne; trivial.\n    simpl.\n    destruct (env M).\n    apply env_comp_empty.\n    destruct o.\n    destruct M0; try_solve.\n    apply env_comp_cons; auto.\n    unfold loweredEnv in ranNG.\n    simpl in ranNG.\n    rewrite finalSeg_cons in ranNG; trivial.\n  Qed.\n\n  Lemma lower_subst_aux : forall M G i, env M |= i :! ->\n    presubst_aux (prelower_aux (term M) i) i (copy i None ++ G) = \n    prelower_aux (presubst_aux (term M) i\n      (copy i None ++ None :: lift_subst G 1)) i.\n\n  Proof.\n    destruct M as [E Pt TM M].\n    induction M; intros G i Mi; unfold prelower, presubst; simpl.\n     (* variable *)\n    destruct (Compare_dec.le_gt_dec i x); simpl.\n    destruct (eq_nat_dec i x).\n     (*   - x = i *)\n    rewrite e in Mi.\n    exfalso; eapply varD_UD_absurd; eauto.\n     (*   - x > i *)\n    destruct x; simpl. lia.\n    replace (copy i None ++ None :: lift_subst G 1) with \n      ((None :: copy i None) ++ lift_subst G 1).\n    simpl.\n    repeat rewrite nth_app_right; rewrite copy_length; try lia.\n    destruct (varSubst_dec G (x - i)) as [[T GT] | Gn].\n    rewrite GT, (nth_lift_subst_s G 1 (x - i) GT), !lift_term, <- prelift_fold.\n    apply prelower_prelift.\n    set (w := var_notSubst_lift 1 Gn).\n    inversion Gn; inversion w; rewrite H; rewrite H0; simpl;\n      destruct (Compare_dec.le_gt_dec i (S x)); \n\tsolve [trivial | lia].\n    rewrite <- list_app_first_last.\n    rewrite <- copy_add; trivial.\n    rewrite <- app_nil_end; trivial.\n     (*   - x < i *)\n    rewrite !nth_app_left, nth_copy_in.\n    simpl.\n    destruct (Compare_dec.le_gt_dec i x); trivial.\n    lia.\n    lia.\n    rewrite copy_length; lia.\n    rewrite copy_length; lia.\n     (* function symbol *)\n    trivial.\n     (* abstraction *)\n    set (w := IHM G (S i)).\n    simpl in w.\n    rewrite w; trivial.\n     (* application *)\n    rewrite IHM1; trivial.\n    rewrite IHM2; trivial.\n  Qed.\n\n  Lemma lower_subst : forall M N G (M0: env M |= 0 :!) (MG: correct_subst N G)\n    (MG': correct_subst M (None :: lift_subst G 1))\n    (MG'0: env (subst MG') |= 0 :! := (subst_at0 G MG' M0)),\n    N = lower M M0 -> subst MG = lower (subst MG') MG'0.\n\n  Proof.\n    intros.\n    apply term_eq; autorewrite with terms; rewrite H; autorewrite with terms.\n\n    destruct M as [envM ???].\n    autorewrite with terms using simpl.\n    unfold loweredEnv; simpl.\n    destruct (subst_empty_dec G).\n    destruct envM; simpl.\n    autorewrite with terms; trivial.\n    autorewrite with terms datatypes; trivial.\n    destruct o; autorewrite with datatypes; trivial.\n    destruct envM; simpl.\n    autorewrite with datatypes terms.\n    destruct (subst_ran G); trivial.\n    destruct o; autorewrite with datatypes terms using simpl; trivial.\n\n    unfold presubst, prelower.\n    apply (lower_subst_aux M G M0).\n  Qed.\n\n  Lemma lower_eq : forall M N (M0: env M |= 0 :!) (N0: env N |= 0 :!), M = N ->\n    lower M M0 = lower N N0.\n\n  Proof.\n    intros.\n    apply term_eq.\n    rewrite !lower_env; rewrite H; trivial.\n    rewrite !lower_term; rewrite H; trivial.\n  Qed.\n\n  Lemma subst_single_eq : forall M M' P P' (MP: correct_subst M {x/P})\n    (MP': correct_subst M' {x/P'}), M = M' -> P = P' -> subst MP = subst MP'.\n\n  Proof.\n    intros.\n    apply term_eq.\n    rewrite !subst_env, H, H0; trivial.\n    rewrite !subst_term, H, H0; trivial.\n  Qed.\n\n  Lemma double_subst_aux : forall M P G i\n    (PG: correct_subst P (None :: lift_subst G 1)),\n    presubst_aux (presubst_aux M i (copy i None ++ {x/P}))\n    i (copy (S i) None ++ lift_subst G 1) =\n    presubst_aux (presubst_aux M i (copy (S i) None ++ lift_subst G 1))\n    i (copy i None ++ {x/subst PG}).\n\n  Proof.\n    induction M; unfold presubst; intros; simpl.\n\n    destruct (Compare_dec.gt_eq_gt_dec i x) as [[x_gt_i | x_eq_i] | x_lt_i].\n    rewrite nth_beyond; autorewrite with terms datatypes; simpl; try lia.\n    replace (None :: copy i None ++ lift_subst G 1) with \n      (copy (S i) None ++ lift_subst G 1); trivial.\n    rewrite nth_app_right; autorewrite with terms datatypes; try lia.\n    destruct (varSubst_dec G (x - S i)) as [[T GT] | Gn].\n    rewrite (var_subst_lift 1 GT), !lift_term, <- prelift_fold,\n      presubst_beyond; trivial.\n    autorewrite with datatypes using simpl; try lia.\n    destruct (var_notSubst_lift 1 Gn); rewrite H; \n      replace (%x) with (prelift (%0) x); trivial;\n      rewrite presubst_beyond; solve \n\t[ trivial\n\t| autorewrite with datatypes using simpl; try lia\n\t].\n\n    rewrite x_eq_i.\n    rewrite nth_app_right; autorewrite with datatypes using try lia.\n    rewrite <- Minus.minus_n_n; simpl.\n    replace (None :: copy x None ++ lift_subst G 1) with \n      (copy (S x) None ++ lift_subst G 1); trivial.\n    rewrite nth_app_left; autorewrite with datatypes terms using simpl;\n      try lia.\n    rewrite nth_app_right; autorewrite with datatypes terms using simpl;\n      try lia.\n    rewrite <- Minus.minus_n_n; simpl.\n    autorewrite with terms.\n    rewrite <- presubst_prelift_comm; simpl.\n    rewrite subst_lift_subst; simpl.\n    rewrite lift_subst_distr.\n    rewrite lift_empty_subst.\n    rewrite <- copy_add; trivial.\n\n    replace (None :: copy i None ++ lift_subst G 1) with \n      (copy (S i) None ++ lift_subst G 1); trivial.\n    rewrite !nth_app_left; autorewrite with terms datatypes using simpl;\n      try lia.\n    replace (None :: copy i None ++ lift_subst G 1) with \n      (copy (S i) None ++ lift_subst G 1); trivial.\n    replace (None :: copy i (None (A:=Term)))\n      with (copy (S i) (None (A:=Term))); trivial.\n    rewrite !nth_app_left; autorewrite with terms datatypes using simpl;\n      try lia.\n    rewrite nth_app_left; autorewrite with terms datatypes using trivial.\n\n    trivial.\n    replace (None :: copy i None ++ {x/P}) with \n      (copy (S i) None ++ {x/P}); trivial.\n    replace (None :: None :: copy i None ++ lift_subst G 1) with \n      (copy (S (S i)) None ++ lift_subst G 1); trivial.\n    replace (None :: copy i None ++ {x/subst PG}) with \n      (copy (S i) None ++ {x/subst PG}); trivial.\n    rewrite (IHM P G (S i) PG); trivial.\n    replace (None :: copy i None ++ lift_subst G 1) with \n      (copy (S i) None ++ lift_subst G 1); trivial.\n    rewrite <- IHM1.\n    rewrite <- IHM2.\n    trivial.\n  Qed.\n\n  Lemma double_subst : forall M G P (MP: correct_subst M {x/P}) \n    (MPG: correct_subst (subst MP) (None :: lift_subst G 1))\n    (MG: correct_subst M (None :: lift_subst G 1))\n    (PG: correct_subst P (None :: lift_subst G 1)) \n    (MGP: correct_subst (subst MG) {x/subst PG}), subst MPG = subst MGP.\n\n  Proof.\n    intros.\n    apply term_eq.\n\n    autorewrite with terms.\n    cut (tail (env M) [+] tail (env P) [-] subst_dom G [+] subst_ran G =\n      tail (env M) [-] subst_dom G [+] subst_ran G [+] \n      (tail (env P) [-] subst_dom G [+] subst_ran G)).\n    destruct (subst_empty_dec G).\n    (*SLOW*)destruct (env M); destruct (env P); try destruct o;\n      try destruct o0; simpl; (autorewrite with terms using simpl); try_solve.\n    (*VERY SLOW*)destruct (env M); destruct (env P); try destruct o;\n      try destruct o0; simpl; (autorewrite with terms using simpl); \n      try destruct (subst_ran G); try destruct (subst_dom G);\n      try destruct e; try destruct o; try destruct o0; try_solve.\n    rewrite env_sum_assoc.\n    rewrite <- (env_sum_assoc (subst_ran G)).\n    rewrite env_sum_remove_double.\n    rewrite <- env_sum_assoc.\n    rewrite env_sub_move; trivial.\n\n    autorewrite with terms datatypes.\n    unfold presubst.\n    set (w := double_subst_aux (term M) G 0 PG).\n    simpl in w; trivial.\n  Qed.\n\n  Lemma double_lift : forall M G\n    (CS: correct_subst (lift M 1) (None :: lift_subst G 1))\n    (CS': correct_subst M G), subst CS = lift (subst CS') 1.\n\n  Proof.\n    intros.\n    apply term_eq.\n    destruct (subst_empty_dec G); \n      autorewrite with terms datatypes using unfold liftedEnv; simpl; trivial.\n    autorewrite with terms.\n    replace (None :: lift_subst G 1) with (copy (S 0) None ++ lift_subst G 1);\n    trivial.\n    apply presubst_prelift_comm.\n  Qed.\n\n  Lemma subst_on_beta : forall M (Mapp: isApp M) (MLabs: isAbs (appBodyL Mapp))\n    G (CS: correct_subst M G)\n    (CSin: correct_subst (absBody MLabs) (None :: lift_subst G 1))\n    (CSapp: isApp (subst CS) := app_subst_app Mapp CS)\n    (CSLabs: isAbs (appBodyL CSapp)),\n    subst CSin = absBody CSLabs.\n\n  Proof.\n    intros; apply term_eq.\n\n    assert (absType MLabs = absType CSLabs).\n    apply type_eq_absType_eq. \n    unfold CSapp; apply type_appBodyL_subst.\n    destruct (subst_empty_dec G); autorewrite with terms using unfold decl;\n      try_solve.\n\n    autorewrite with terms datatypes using simpl.\n    rewrite (absBody_term (appBodyL CSapp) CSLabs (A := absType MLabs)\n      (Pt := presubst (term (absBody MLabs)) (None :: lift_subst G 1)));\n      trivial.\n    rewrite (appBodyL_term (subst CS) (PtL := \\absType MLabs => \n      presubst (term (absBody MLabs)) (None::lift_subst G 1)) \n      (PtR := presubst (term (appBodyR Mapp)) G)); trivial.\n    autorewrite with terms.\n    rewrite (app_term M Mapp).\n    rewrite (abs_term (appBodyL Mapp) MLabs).\n    unfold presubst; simpl.\n    rewrite subst_lift_subst; trivial.\n  Qed.\n\n  Lemma beta_lower_subst : forall M N G (Mapp: isApp M)\n    (MLabs: isAbs (appBodyL Mapp)) \n    (MN: correct_subst M G) (NS: correct_subst N G)\n    (MNS_app: isApp (subst MN) := app_subst_app Mapp MN) \n    (MNS_Labs: isAbs (appBodyL MNS_app)),\n    N = lower (subst (beta_subst M Mapp MLabs)) (beta_lowering M Mapp MLabs) ->\n    subst NS = lower (subst (beta_subst (subst MN) MNS_app MNS_Labs)) \n      (beta_lowering (subst MN) MNS_app MNS_Labs).\n\n  Proof.\n    intros.\n    set (s0 := correct_subst_lift (subst (beta_subst M Mapp MLabs)) \n      (beta_lowering M Mapp MLabs) NS H).\n    rewrite (lower_subst (beta_lowering M Mapp MLabs) NS s0 H).\n    apply lower_eq.\n    assert (s1: correct_subst (absBody MLabs) (None :: lift_subst G 1)).\n    inversion MN; inversion NS; inversion s0; prove_correct_subst.\n    assert\n      (s2: correct_subst (lift (appBodyR Mapp) 1) (None :: lift_subst G 1)).\n    inversion MN; inversion NS; inversion s0; prove_correct_subst.\n    assert (s3: correct_subst (subst s1) {x/subst s2}).\n    constructor.\n    apply subst_envs_comp_single.\n    assert (forall E, {x/type (appBodyR Mapp)} [<->] Some (absType MLabs) :: E).\n    intro; apply env_comp_cons.\n    auto with terms.\n    left; rewrite beta_type; trivial.\n    destruct (subst_empty_dec G); autorewrite with terms using simpl; auto.\n    destruct (subst_empty_dec G);\n      autorewrite with terms datatypes using simpl; auto with terms.\n    rewrite (double_subst G (beta_subst M Mapp MLabs) s0 s1 s2 s3).\n    apply term_eq.\n    destruct (subst_empty_dec G);\n      autorewrite with datatypes terms using simpl; trivial.\n    autorewrite with datatypes terms using simpl.\n    assert (Leq: presubst (term (absBody MLabs)) (None :: lift_subst G 1) = \n      term (absBody MNS_Labs)).\n    cut (term (subst s1) = term (absBody MNS_Labs)).\n    autorewrite with terms.\n    intro; rewrite H0; trivial.\n    rewrite (subst_on_beta Mapp MLabs MN s1 MNS_Labs); trivial.\n    assert (R'eq: subst (subst_appR_c Mapp MN) = appBodyR MNS_app).\n    destruct (app_subst Mapp MN).\n    rewrite <- H1.\n    rewrite (app_proof_irr (subst MN) (app_subst_app Mapp MN) MNS_app); trivial.\n    assert (Req: subst s2 = lift (appBodyR MNS_app) 1).\n    rewrite (double_lift s2 (subst_appR_c Mapp MN)).\n    rewrite R'eq; trivial.\n    try_solve.\n  Qed.\n\n  Lemma betaStep_subst_stable : forall M N G (MS: correct_subst M G)\n    (NS: correct_subst N G), BetaStep M N -> BetaStep (subst MS) (subst NS).\n\n  Proof.\n    intros M N G MS NS MN.\n    inversion MN.\n    set (MNS_app := app_subst_app Mapp0 MS).\n    assert (MNS_Labs: isAbs (appBodyL MNS_app)).\n    eapply abs_isAbs.\n    assert (MS_term : term (subst MS) = presubst_aux (term (appBodyL Mapp0)) \n      0 G [presubst_aux (term (appBodyR Mapp0)) 0 G]).\n    rewrite subst_term; term_inv M.\n    rewrite (appBodyL_term (subst MS) MS_term).\n    rewrite (abs_term (appBodyL Mapp0) MLabs).\n    simpl; eauto.\n    rewrite (beta_lower_subst Mapp0 MLabs MS NS MNS_Labs); auto.\n    constructor.\n  Qed.\n\n  Lemma beta_subst_stable : forall M N G (MS: correct_subst M G)\n    (NS: correct_subst N G), M -b-> N -> subst MS -b-> subst NS.\n\n  Proof.\n    destruct M as [E Pt T M]; induction M; intros.\n\n     (* variable *)\n    absurd (buildT (TVar v) -b-> N); trivial.\n    apply beta_var_normal; simpl; trivial.\n\n     (* function symbol *)\n    absurd (buildT (TFun E f) -b-> N); trivial.\n    apply beta_funS_normal; simpl; trivial.\n\n     (* abstraction *)\n    inversion H; try_solve.\n    inversion H0; try_solve.\n    clear Mabs.\n    assert (Mabs: isAbs (buildT (TAbs M))).\n    simpl; trivial.\n    destruct (abs_subst Mabs MS) as [Ms_type Ms_body].\n    destruct (abs_subst Nabs NS) as [Ns_type Ns_body].\n    constructor 4 with (abs_subst_abs Mabs MS) (abs_subst_abs Nabs NS).\n    rewrite Ms_type; rewrite Ns_type; trivial.\n    rewrite Ms_body; rewrite Ns_body.\n    apply IHM; trivial.\n\n     (* application *)\n    inversion H; try_solve.\n     (*  - beta reduction *)\n    constructor 1.\n    apply betaStep_subst_stable; trivial.\n\n     (*  - reduction in left argument *)\n    clear Mapp; assert (Mapp: isApp (buildT (TApp M1 M2))); simpl; trivial.\n    destruct (app_subst Mapp MS) as [Ml Mr].\n    destruct (app_subst Napp NS) as [Nl Nr].\n    constructor 2 with (app_subst_app Mapp MS) (app_subst_app Napp NS).\n    rewrite Ml; rewrite Nl; apply IHM1; trivial.\n    rewrite Mr; rewrite Nr; trivial.\n    apply term_eq.\n    rewrite !subst_env, <- H1; trivial.\n    rewrite !subst_term, <- H1; trivial.\n\n     (*  - reduction in right argument *)\n    clear Mapp; assert (Mapp: isApp (buildT (TApp M1 M2))); simpl; trivial.\n    destruct (app_subst Mapp MS) as [Ml Mr].\n    destruct (app_subst Napp NS) as [Nl Nr].\n    constructor 3 with (app_subst_app Mapp MS) (app_subst_app Napp NS).\n    rewrite Mr; rewrite Nr; apply IHM2; trivial.\n    rewrite Ml; rewrite Nl; trivial.\n    apply term_eq.\n    rewrite !subst_env, <- H1; trivial.\n    rewrite !subst_term, <- H1; trivial.\n  Qed.\n\n  Lemma beta_abs_reduct : forall M (Mabs: isAbs M) N, M -b-> N ->\n    exists Nabs: isAbs N, absBody Mabs -b-> absBody Nabs.\n\n  Proof.\n    intros M Mabs N MN.\n    inversion MN; term_inv M; try_solve.\n    inversion H; try_solve.\n    exists Nabs; trivial.\n  Qed.\n\n  Lemma beta_app_reduct : forall M N (Mapp: isApp M),\n    M -b-> N ->\n    (exists MLabs: isAbs (appBodyL Mapp),\n      N = lower (subst (beta_subst M Mapp MLabs)) (beta_lowering M Mapp MLabs))\n    \\/ exists Napp: isApp N, \n      (appBodyL Mapp  =   appBodyL Napp /\\ appBodyR Mapp -b-> appBodyR Napp)\n      \\/ (appBodyL Mapp -b-> appBodyL Napp /\\ appBodyR Mapp  =   appBodyR Napp).\n\n  Proof.\n    intros M N Mapp MN.\n    inversion MN; term_inv M; try_solve.\n    left; inversion H.\n    exists MLabs.\n    rewrite (app_proof_irr Tr Mapp Mapp1); trivial.\n    right; exists Napp; fo.\n    right; exists Napp; fo.\n  Qed.\n\n  Lemma beta_var_consistent : forall M N,\n    M -b-> N -> envSubset (activeEnv N) (activeEnv M).\n\n  Proof.\n    intros.\n    apply red_var_consistent with BetaStep; trivial.\n    clear M N H; intros M N MN.\n    destruct MN.\n    rewrite activeEnv_lower.\n    rewrite (activeEnv_app M Mapp).\n    rewrite (activeEnv_abs (appBodyL Mapp) MLabs).\n    destruct (isVarDecl_dec (activeEnv (absBody MLabs)) 0) as [[B Ml0] | Mln].\n    assert (Mlb0: exists A, activeEnv (absBody MLabs) |= 0 := A).\n    exists B; trivial.\n    rewrite (singleton_subst_activeEnv_subst (beta_subst M Mapp MLabs)\n      (singletonSubst_cond (lift (appBodyR Mapp) 1)) Mlb0).\n    rewrite (activeEnv_lift (appBodyR Mapp) 1).\n    simpl; autorewrite with datatypes using unfold loweredEnv; simpl.\n    apply env_subset_refl.\n    rewrite (singleton_subst_activeEnv_noSubst (beta_subst M Mapp MLabs) Mln\n      (singletonSubst_cond (lift (appBodyR Mapp) 1))); trivial.\n    unfold loweredEnv; autorewrite with datatypes using simpl.\n    apply env_subset_sum_l.\n    simpl.\n    apply env_comp_subset with (tail (env (subst (beta_subst M Mapp MLabs)))) \n      (env (appBodyR Mapp)).\n    autorewrite with terms datatypes using simpl; auto with terms.\n    apply env_subset_tail; apply activeEnv_subset.\n    apply activeEnv_subset.\n    rewrite finalSeg1_tail.\n    apply env_subset_refl.\n  Qed.\n\n  Lemma betaStep_dec: forall M N, {BetaStep M N} + {~BetaStep M N}.\n\n  Proof.\n    intros.\n    destruct (isApp_dec M) as [Mapp | Mnapp].\n    destruct (isAbs_dec (appBodyL Mapp)) as [MLabs | MLnabs].\n    destruct (eq_Term_dec N (lower (subst (beta_subst M Mapp MLabs))\n      (beta_lowering M Mapp MLabs))).\n    left; rewrite e; constructor.\n    right; intro MN; inversion MN.\n    apply n; rewrite <- H0.\n    apply term_eq.\n    autorewrite with terms using trivial.\n    autorewrite with terms using trivial.\n    replace (absBody MLabs0) with (absBody MLabs).\n    replace (appBodyR Mapp1) with (appBodyR Mapp); trivial.\n    term_inv M.\n    apply absBody_eq; term_inv M.\n    right; intro MN; inversion MN.\n    absurd (isAbs (appBodyL Mapp1)); trivial.\n    replace (appBodyL Mapp1) with (appBodyL Mapp); trivial.\n    term_inv M.\n    right; intro MN; inversion MN; try_solve.\n  Qed.\n\n  Lemma beta_dec: forall M N, {M -b-> N} + {~ M -b-> N}.\n\n  Proof.\n    intros; unfold BetaReduction.\n    apply red_dec.\n    apply betaStep_dec.\n  Qed.\n\nEnd TermsBeta.\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/TermsBeta.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2717293306137525}}
{"text": "From Hammer Require Import Hammer.\n\nRequire Import ExtLib.Structures.Maps.\nRequire Import ExtLib.Structures.Functor.\nRequire Import ExtLib.Data.Option.\nRequire Import ExtLib.Data.Positive.\nRequire Import ExtLib.Tactics.Cases.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nSection pmap.\nVariable T : Type.\nInductive pmap : Type :=\n| Empty\n| Branch : option T -> pmap -> pmap -> pmap.\n\nDefinition pmap_here (m : pmap) : option T :=\nmatch m with\n| Empty => None\n| Branch d _ _ => d\nend.\n\nDefinition pmap_left (m : pmap) : pmap :=\nmatch m with\n| Empty => Empty\n| Branch _ l _ => l\nend.\n\nDefinition pmap_right (m : pmap) : pmap :=\nmatch m with\n| Empty => Empty\n| Branch _ _ r => r\nend.\n\nFixpoint pmap_lookup (p : positive) (m : pmap) {struct p} : option T :=\nmatch m with\n| Empty => None\n| Branch d l r =>\nmatch p with\n| xH => d\n| xO p => pmap_lookup p l\n| xI p => pmap_lookup p r\nend\nend.\n\nFixpoint pmap_insert (p : positive) (v : T) (m : pmap) {struct p} : pmap :=\nmatch p with\n| xH => Branch (Some v) (pmap_left m) (pmap_right m)\n| xO p =>\nBranch (pmap_here m) (pmap_insert p v (pmap_left m)) (pmap_right m)\n| xI p =>\nBranch (pmap_here m) (pmap_left m) (pmap_insert p v (pmap_right m))\nend.\n\nDefinition branch (o : option T) (l r : pmap) : pmap :=\nmatch o , l , r with\n| None , Empty , Empty => Empty\n| _ , _ , _ => Branch o l r\nend.\n\nFixpoint pmap_remove (p : positive) (m : pmap) {struct p} : pmap :=\nmatch m with\n| Empty => Empty\n| Branch d l r =>\nmatch p with\n| xH => branch None l r\n| xO p => branch d (pmap_remove p l) r\n| xI p => branch d l (pmap_remove p r)\nend\nend.\n\nDefinition pmap_empty : pmap := Empty.\n\nFixpoint pmap_union (f m : pmap) : pmap :=\nmatch f with\n| Empty => m\n| Branch d l r =>\nBranch (match d with\n| Some x => Some x\n| None => pmap_here m\nend) (pmap_union l (pmap_left m)) (pmap_union r (pmap_right m))\nend.\n\nGlobal Instance Map_pmap : Map positive T pmap :=\n{ empty := pmap_empty\n; add := pmap_insert\n; remove := pmap_remove\n; lookup := pmap_lookup\n; union := pmap_union\n}.\n\nLemma tilde_1_inj_neg : forall k k',\n(k~1)%positive <> (k'~1)%positive -> k <> k'.\nProof. hammer_hook \"FMapPositive\" \"FMapPositive.tilde_1_inj_neg\".\ninduction k; destruct k'; intuition;\ntry match goal with\n| H : _ = _ |- _ => inversion H; clear H; subst\nend; intuition eauto.\nQed.\n\nLemma tilde_0_inj_neg : forall k k',\n(k~0)%positive <> (k'~0)%positive -> k <> k'.\nProof. hammer_hook \"FMapPositive\" \"FMapPositive.tilde_0_inj_neg\".\ninduction k; destruct k'; intuition;\ntry match goal with\n| H : _ = _ |- _ => inversion H; clear H; subst\nend; intuition eauto.\nQed.\n\nLemma pmap_lookup_insert_empty : forall k k' v,\nk <> k' ->\npmap_lookup k' (pmap_insert k v Empty) = None.\nProof. hammer_hook \"FMapPositive\" \"FMapPositive.pmap_lookup_insert_empty\".\ninduction k; destruct k'; simpl; intros;\neauto using tilde_0_inj_neg, tilde_1_inj_neg.\ndestruct k'; simpl; auto.\ndestruct k'; simpl; auto.\ndestruct k'; simpl; auto.\ndestruct k'; simpl; auto.\ncongruence.\nQed.\n\nLemma lookup_empty : forall k, pmap_lookup k Empty = None.\nProof. hammer_hook \"FMapPositive\" \"FMapPositive.lookup_empty\".\ndestruct k; reflexivity.\nQed.\n\nHint Rewrite lookup_empty pmap_lookup_insert_empty\nusing (eauto using tilde_1_inj_neg, tilde_1_inj_neg) : pmap_rw.\n\nLemma pmap_lookup_insert_eq\n: forall (m : pmap) (k : positive) (v : T),\npmap_lookup k (pmap_insert k v m) = Some v.\nProof. hammer_hook \"FMapPositive\" \"FMapPositive.pmap_lookup_insert_eq\".\nintros m k; revert m.\ninduction k; simpl; intros; forward; Cases.rewrite_all_goal; eauto.\nQed.\n\nLemma pmap_lookup_insert_Some_neq\n: forall (m : pmap) (k : positive) (v : T) (k' : positive),\nk <> k' ->\nforall v' : T,\npmap_lookup k' m = Some v' <-> pmap_lookup k' (pmap_insert k v m) = Some v'.\nProof. hammer_hook \"FMapPositive\" \"FMapPositive.pmap_lookup_insert_Some_neq\".\nintros m k; revert m.\ninduction k; simpl; intros; forward; Cases.rewrite_all_goal;\nautorewrite with pmap_rw; eauto.\n{ destruct k'; simpl; destruct m; simpl;\nautorewrite with pmap_rw; Cases.rewrite_all_goal; try reflexivity.\nerewrite IHk; eauto using tilde_1_inj_neg. reflexivity. }\n{ destruct k'; simpl; destruct m; simpl;\nautorewrite with pmap_rw; Cases.rewrite_all_goal; try reflexivity; try congruence.\nerewrite IHk. reflexivity. eauto using tilde_0_inj_neg. }\n{ destruct k'; simpl; destruct m; simpl;\nautorewrite with pmap_rw; Cases.rewrite_all_goal; try reflexivity; try congruence. }\nQed.\n\nLemma pmap_lookup_insert_None_neq\n: forall (m : pmap) (k : positive) (v : T) (k' : positive),\nk <> k' ->\npmap_lookup k' m = None <-> pmap_lookup k' (pmap_insert k v m) = None.\nProof. hammer_hook \"FMapPositive\" \"FMapPositive.pmap_lookup_insert_None_neq\".\nintros m k; revert m.\ninduction k; simpl; intros; forward; Cases.rewrite_all_goal;\nautorewrite with pmap_rw; eauto.\n{ destruct k'; simpl; destruct m; simpl;\nautorewrite with pmap_rw; Cases.rewrite_all_goal; try reflexivity.\nerewrite IHk; eauto using tilde_1_inj_neg. reflexivity. }\n{ destruct k'; simpl; destruct m; simpl;\nautorewrite with pmap_rw; Cases.rewrite_all_goal; try reflexivity; try congruence.\nerewrite IHk. reflexivity. eauto using tilde_0_inj_neg. }\n{ destruct k'; simpl; destruct m; simpl;\nautorewrite with pmap_rw; Cases.rewrite_all_goal; try reflexivity; try congruence. }\nQed.\n\nLemma pmap_lookup_insert_neq\n: forall (m : pmap) (k : positive) (v : T) (k' : positive),\nk <> k' ->\nforall v' : T,\npmap_lookup k' (pmap_insert k v m) = pmap_lookup k' m.\nProof. hammer_hook \"FMapPositive\" \"FMapPositive.pmap_lookup_insert_neq\".\nintros.\nremember (pmap_lookup k' m).\ndestruct o; [\napply pmap_lookup_insert_Some_neq; intuition |\napply pmap_lookup_insert_None_neq; intuition].\nQed.\n\nLemma pmap_lookup_remove_eq\n: forall (m : pmap) (k : positive) (v : T),\npmap_lookup k (pmap_remove k m) <> Some v.\nProof. hammer_hook \"FMapPositive\" \"FMapPositive.pmap_lookup_remove_eq\".\ninduction m; destruct k; simpl; intros; try congruence.\n{ destruct o; simpl; eauto.\ndestruct m1; simpl; eauto.\ndestruct (pmap_remove k m2) eqn:?; try congruence.\nrewrite <- Heqp. eauto. }\n{ destruct o; simpl; eauto.\ndestruct (pmap_remove k m1) eqn:?; try congruence.\n- destruct m2; try congruence; eauto.\ndestruct k; simpl; congruence.\n- rewrite <- Heqp. eauto. }\n{ destruct m1; try congruence.\ndestruct m2; try congruence. }\nQed.\n\nLemma pmap_lookup_remove_neq\n: forall (m : pmap) (k k' : positive),\nk <> k' ->\nforall v' : T, pmap_lookup k' m = Some v' <-> pmap_lookup k' (pmap_remove k m) = Some v'.\nProof. hammer_hook \"FMapPositive\" \"FMapPositive.pmap_lookup_remove_neq\".\ninduction m.\nLocal Ltac t :=\nunfold branch;\nrepeat match goal with\n| |- context [ match ?X with _ => _ end ] =>\nlazymatch X with\n| match _ with _ => _ end => fail\n| _ => destruct X eqn:?; subst; try tauto\nend\nend.\n{ destruct k; simpl; split; try congruence. }\n{ destruct k', k; simpl; intros; try solve [ t; rewrite lookup_empty; tauto ].\n{ assert (k <> k') by congruence.\nrewrite IHm2; eauto. simpl. t. rewrite lookup_empty. tauto. }\n{ assert (k <> k') by congruence.\nrewrite IHm1; eauto. simpl. t. rewrite lookup_empty. tauto. } }\nQed.\n\nGlobal Instance MapOk_pmap : MapOk (@eq _) Map_pmap.\nProof. hammer_hook \"FMapPositive\" \"FMapPositive.MapOk_pmap\".\nrefine {| mapsto := fun k v m => pmap_lookup k m = Some v |}.\n{ abstract (induction k; simpl; congruence). }\n{ abstract (induction k; simpl; intros; forward). }\n{ eauto using pmap_lookup_insert_eq. }\n{ eauto using pmap_lookup_insert_Some_neq. }\n{ eauto using pmap_lookup_remove_eq. }\n{ eauto using pmap_lookup_remove_neq. }\nDefined.\n\nDefinition from_list : list T -> pmap :=\n(fix from_list acc i ls {struct ls} :=\nmatch ls with\n| nil => acc\n| List.cons l ls =>\nfrom_list (pmap_insert i l acc) (Pos.succ i) ls\nend) Empty 1%positive.\n\nEnd pmap.\n\nArguments Empty {_}.\nArguments Branch {_} _ _ _.\n\nSection fmap.\nVariables T U : Type.\nVariable f : T -> U.\n\nFixpoint fmap_pmap (m : pmap T) : pmap U :=\nmatch m with\n| Empty => Empty\n| Branch h l r => Branch (fmap f h) (fmap_pmap l) (fmap_pmap r)\nend.\n\nTheorem fmap_lookup : forall a b m,\nmapsto a b m ->\nmapsto a (f b) (fmap_pmap m).\nProof. hammer_hook \"FMapPositive\" \"FMapPositive.fmap_lookup\".\ninduction a; destruct m; simpl; intros; try congruence.\n{ eapply IHa. eapply H. }\n{ eapply IHa; eapply H. }\n{ subst. auto. }\nQed.\n\nTheorem fmap_lookup_bk : forall a b m,\nmapsto a b (fmap_pmap m) ->\nexists b', mapsto a b' m /\\ f b' = b.\nProof. hammer_hook \"FMapPositive\" \"FMapPositive.fmap_lookup_bk\".\ninduction a; destruct m; simpl; intros; try congruence.\n{ eapply IHa. eapply H. }\n{ eapply IHa. eapply H. }\n{ destruct o; try congruence. eexists; split; eauto. inversion H; auto. }\nQed.\n\nEnd fmap.\n\nRequire Import ExtLib.Core.Type.\n\nSection type.\nVariable T : Type.\nVariable tT : type T.\n\nInstance type_pmap : type (pmap T) :=\ntype_from_equal\n(fun l r =>\n(forall k v,\nmapsto k v l -> exists v', mapsto k v' r /\\ equal v v')\n/\\ (forall k v,\nmapsto k v r -> exists v', mapsto k v' l /\\ equal v v')).\n\nEnd type.\n\nGlobal Instance Functor_pmap : Functor pmap :=\n{ fmap := fmap_pmap }.\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/coq-ext-lib/FMapPositive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.27172933061375243}}
{"text": "(***\n * Oqarina\n * Copyright 2021 Carnegie Mellon University.\n *\n * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING\n * INSTITUTE MATERIAL IS FURNISHED ON AN \"AS-IS\" BASIS. CARNEGIE MELLON\n * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR\n * IMPLIED, AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF\n * FITNESS FOR PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS\n * OBTAINED FROM USE OF THE MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT\n * MAKE ANY WARRANTY OF ANY KIND WITH RESPECT TO FREEDOM FROM PATENT,\n * TRADEMARK, OR COPYRIGHT INFRINGEMENT.\n *\n * Released under a BSD (SEI)-style license, please see license.txt or\n * contact permission@sei.cmu.edu for full terms.\n *\n * [DISTRIBUTION STATEMENT A] This material has been approved for public\n * release and unlimited distribution.  Please see Copyright notice for\n * non-US Government use and distribution.\n *\n * This Software includes and/or makes use of the following Third-Party\n * Software subject to its own license:\n *\n * 1. Coq theorem prover (https://github.com/coq/coq/blob/master/LICENSE)\n * Copyright 2021 INRIA.\n *\n * 2. Coq JSON (https://github.com/liyishuai/coq-json/blob/comrade/LICENSE)\n * Copyright 2021 Yishuai Li.\n *\n * DM21-0762\n***)\n\nRequire Import Coq.Lists.List.\nImport ListNotations. (* from List *)\n\nRequire Import Oqarina.coq_utils.all.\nRequire Import Oqarina.core.all.\nImport NaturalTime.\nRequire Import Oqarina.formalisms.DEVS.classic.all.\nRequire Import Oqarina.formalisms.lts.\n\nSection Traffic_Light.\n\n(*\n\nTraffic Light example\n=====================\n\nIn this section, we model the traffic light example from\n:math:`\\cite{vantendelooIntroductionClassicDEVS2018}`. This example is a direct transcription in Coq of the various types and functions definitions and yield no complexity. It is kept for testing and documentation purposes.\n\n*)\n\nInductive X_tl :=\n    | toAuto | toManual.\n\nInductive Y_tl :=\n    | show_green | show_yellow | show_red | turn_off.\n\nInductive S_tl :=\n    | GREEN | YELLOW | RED | GOING_MANUAL | GOING_AUTO | MANUAL.\n\nDefinition Q_tl : Type := Q S_tl.\n\nDefinition Q_init_tl : Q_tl := {| st := GREEN ; e := 0 |}.\n\nDefinition δint_tl (s : S_tl) : S_tl :=\n    match s with\n        | GREEN => YELLOW\n        | YELLOW => RED\n        | RED => GREEN\n        | GOING_MANUAL => MANUAL\n        | GOING_AUTO => RED\n        | _ => s\n    end.\n\nDefinition δext_tl (q : Q_tl) (x : X_tl) : S_tl :=\n    match q.(st), x  with\n        | GREEN,toManual => GOING_MANUAL\n        | YELLOW, toManual => GOING_MANUAL\n        | RED,toManual => GOING_MANUAL\n        | MANUAL, toAuto => GOING_AUTO\n        |  _, _ => q.(st)\n    end.\n\nDefinition Y_output_tl : Type := Y_output Y_tl.\n\nDefinition λ_tl (s : S_tl) : Y_output_tl :=\n    match s with\n        | GREEN  => y show_yellow\n        | YELLOW  => y show_red\n        | RED  => y show_green\n        | GOING_MANUAL  => y turn_off\n        | GOING_AUTO  => y show_red\n        | _ => no_output Y_tl\n    end.\n\nDefinition ta_tl (s : S_tl) : Time :=\n    match s with\n        | GREEN  => 1\n        | YELLOW  => 2\n        | RED  => 3\n        | GOING_MANUAL  => 0\n        | GOING_AUTO  => 0\n        | MANUAL => 10 (* infinity *)\n    end.\n\n(* From these specifications, we define the corresponding Coq data types.\nFirst, a type representing the interface of a TrafficLight_Devs\n(:coq:`TrafficLight_DEVS_Type`), then the DEVS atomic model itself.\n*)\n\nDefinition TrafficLight_DEVS_type : Type := DEVS_Atomic_Model S_tl X_tl Y_tl.\n\nDefinition TrafficLight_DEVS : TrafficLight_DEVS_type := {|\n    devs_atomic_id := (Id \"TrafficLight\");\n\n    Q_init := Q_init_tl;\n\n    ta := ta_tl;\n    δint := δint_tl;\n    λ := λ_tl ;\n    δext := δext_tl;\n|}.\n\n(* Then, we instantiate the DEVS model to build on instance, or simulator. *)\n\nDefinition TrafficLight_DEVS_Simulator_type : Type :=\n    DEVS_Simulator S_tl X_tl Y_tl.\n\nDefinition TL_Initial := Instantiate_DEVS_Simulator\n    (Id \"TrafficLighti\") TrafficLight_DEVS.\n\n(* From that point, we can simulate the Traffic Light. *)\n\nDefinition TL_Coordinator := Iniitialize_DEVS_Root_Coordinator TL_Initial.\n\nDefinition TLC_Step1 := DEVS_Simulation_Step TL_Coordinator None.\nLemma TLC_Step1_OK :\n    (Print_DEVS_State TLC_Step1) = dbg 0 1 GREEN [].\nProof.\n    trivial.\nQed.\n\nDefinition TLC_Step2 := DEVS_Simulation_Step TLC_Step1 None.\nLemma TLC_Step2_OK :\n    (Print_DEVS_State TLC_Step2) = dbg 1 3 YELLOW [].\nProof.\n    trivial.\nQed.\n\nDefinition TLC_Step3 := DEVS_Simulation_Step TLC_Step2 None.\nLemma TLC_Step3_OK :\n    (Print_DEVS_State TLC_Step3) = dbg 3 6 RED [].\nProof.\n    trivial.\nQed.\n\nDefinition TLC_Step4 := DEVS_Simulation_Step TLC_Step3 None.\nLemma TLC_Step4_OK :\n    (Print_DEVS_State TLC_Step4) = dbg 6 7 GREEN [].\nProof.\n    trivial.\nQed.\n\n(* LTS variant of the Traffic LIght DEVS. We introduce a variant of the step\nfunction that drops the output to compare the states with the previous\nsimulation run.*)\n\nDefinition TL_LTS := LTS_Of_DEVS TL_Initial.\n\nExample TL_LTS_1 := step_lts (Init TL_LTS) (i X_tl Y_tl 0) .\nCompute Print_DEVS_Simulator TL_LTS_1.\n\nLemma TL_LTS_1_OK :\n    Print_DEVS_Simulator TL_LTS_1 = Print_DEVS_Simulator TLC_Step1.(astate).\nProof.\n    trivial.\nQed.\n\nEnd Traffic_Light.\n(*| .. coq:: |*)\n\nSection Traffic_Light_Coupled.\n(*\n\nTraffic Light couple example\n============================\n\nIn this section, we build a naive coupled DEVS model out of the Traffic Light example. The coupled model is made of a single node. We use this as a first verification step that the coupled DEVS model made of one atonmic model has the same behavior.\n\n*)\n\nDefinition Traffic_Light_Coupled := {|\n    devs_coupled_model_id := Id \"traffic_light_coupled\" ;\n    D := [ TL_Initial ] ;\n    Select := @Default_Select_Function S_tl X_tl Y_tl ;\n    Z_f :=  (fun (i : identifier) (y : Y_output_tl) => toManual) ;\n    I := Default_I_Function;\n|}.\n\nDefinition TL_coupled_atomic := Map_DEVS_Coupled_Model Traffic_Light_Coupled.\n\nDefinition TL_coupled_initial :=\n    Instantiate_DEVS_Simulator (Id \"traffic_light_coupled_instance\")\n    TL_coupled_atomic.\n\nDefinition TL_Coordinator_coupled := Iniitialize_DEVS_Root_Coordinator TL_coupled_initial.\n\nDefinition TLCC_Step1 := DEVS_Simulation_Step TL_Coordinator_coupled None.\nLemma TLCC_Step1_OK :\n    (Print_DEVS_Simulator TLCC_Step1.(astate)) =\n        dbg 0 1 [{| st := GREEN; e := 0 |}] [].\nProof.\n    trivial.\nQed.\n\nDefinition TLCC_Step2 := DEVS_Simulation_Step TLCC_Step1 None.\nLemma TLCC_Step2_OK :\n    (Print_DEVS_Simulator TLCC_Step2.(astate)) =\n    dbg 1 3 [{| st := YELLOW; e := 0 |}] [].\nProof.\n    trivial.\nQed.\n\nDefinition TLCC_Step3 := DEVS_Simulation_Step TLCC_Step2 None.\nLemma TLCC_Step3_OK :\n    (Print_DEVS_Simulator TLCC_Step3.(astate)) =\n    dbg 3 6 [{| st := RED; e := 0 |}] [].\nProof.\n    trivial.\nQed.\n\nDefinition TLCC_Step4 := DEVS_Simulation_Step TLCC_Step3 None.\nLemma TLCC_Step4_OK :\n    (Print_DEVS_Simulator TLCC_Step4.(astate)) =\n    dbg 6 7 [{| st := GREEN; e := 0 |}] [].\nProof.\n    trivial.\nQed.\n\nEnd Traffic_Light_Coupled.\n(*| .. coq:: |*)\n", "meta": {"author": "Oqarina", "repo": "oqarina", "sha": "5a5ea65688188e462b20d30ee4e5eba08285f629", "save_path": "github-repos/coq/Oqarina-oqarina", "path": "github-repos/coq/Oqarina-oqarina/oqarina-5a5ea65688188e462b20d30ee4e5eba08285f629/examples/DEVS/traffic_light.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.27172933061375243}}
{"text": "Require Import 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) Vundef = Vint t0 /\\\n              Znth ((5 * (Z.of_nat n) + 4 * 1) mod 16) (map Vint xs) Vundef = Vint t1 /\\\n              Znth ((5 * (Z.of_nat n) + 4 * 2) mod 16) (map Vint xs) Vundef = Vint t2 /\\\n              Znth ((5 * (Z.of_nat n) + 4 * 3) mod 16) (map Vint xs) Vundef = 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\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 Vundef =Vint mval),\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 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  (Sfor (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 _aux\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 _aux tuint)))\n     (Sset _m\n        (Ebinop Oadd (Etempvar _m tint) (Econst_int (Int.repr 1) tint) tint)))\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].\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 Vundef = Znth mm wlist Vundef)\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; 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 with (d:=Vundef). omega.\n  intros kk K. apply H1. omega. }\nTime Qed. (*16.8*)\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  (initialized_list [_i] (func_tycontext f_core SalsaVarSpecs SalsaFunSpecs))\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         (Sfor (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) (Econst_int (Int.repr 4) tint) tint)\n                        (Ssequence\n                           (Sset _index\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) (Econst_int (Int.repr 16) tint)\n                                 tint))\n                           (Ssequence\n                              (Sset _aux\n                                 (Ederef\n                                    (Ebinop Oadd (Evar _x (tarray tuint 16)) \n                                       (Etempvar _index tint) (tptr tuint)) tuint))\n                              (Sassign\n                                 (Ederef\n                                    (Ebinop Oadd (Evar _t (tarray tuint 4)) \n                                       (Etempvar _m tint) (tptr tuint)) tuint) \n                                 (Etempvar _aux tuint))))\n                        (Sset _m (Ebinop Oadd (Etempvar _m tint) (Econst_int (Int.repr 1) tint) tint)))\n                     (Ssequence\n                        (Ssequence\n                           (Sset _aux\n                              (Ederef\n                                 (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                    (Econst_int (Int.repr 0) tint) (tptr tuint)) tuint))\n                           (Ssequence\n                              (Sset _aux1\n                                 (Ederef\n                                    (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                       (Econst_int (Int.repr 3) tint) (tptr tuint)) tuint))\n                              (Ssequence\n                                 (Sset _aux\n                                    (Ebinop Oadd (Etempvar _aux tuint) (Etempvar _aux1 tuint) tuint))\n                                 (Ssequence\n                                    (Ssequence\n                                       (Scall (Some _t'5)\n                                          (Evar _L32\n                                             (Tfunction (Tcons tuint (Tcons tint Tnil)) tuint\n                                                cc_default))\n                                          [Etempvar _aux tuint; Econst_int (Int.repr 7) tint])\n                                       (Sset _aux (Etempvar _t'5 tuint)))\n                                    (Ssequence\n                                       (Sset _aux1\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 _aux1\n                                             (Ebinop Oxor (Etempvar _aux1 tuint)\n                                                (Etempvar _aux tuint) tuint))\n                                          (Sassign\n                                             (Ederef\n                                                (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                                   (Econst_int (Int.repr 1) tint) \n                                                   (tptr tuint)) tuint) (Etempvar _aux1 tuint))))))))\n                        (Ssequence\n                           (Ssequence\n                              (Sset _aux\n                                 (Ederef\n                                    (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                       (Econst_int (Int.repr 1) tint) (tptr tuint)) tuint))\n                              (Ssequence\n                                 (Sset _aux1\n                                    (Ederef\n                                       (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                          (Econst_int (Int.repr 0) tint) \n                                          (tptr tuint)) tuint))\n                                 (Ssequence\n                                    (Sset _aux\n                                       (Ebinop Oadd (Etempvar _aux tuint) \n                                          (Etempvar _aux1 tuint) tuint))\n                                    (Ssequence\n                                       (Ssequence\n                                          (Scall (Some _t'6)\n                                             (Evar _L32\n                                                (Tfunction (Tcons tuint (Tcons tint Tnil)) tuint\n                                                   cc_default))\n                                             [Etempvar _aux tuint; Econst_int (Int.repr 9) tint])\n                                          (Sset _aux (Etempvar _t'6 tuint)))\n                                       (Ssequence\n                                          (Sset _aux1\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 _aux1\n                                                (Ebinop Oxor (Etempvar _aux1 tuint)\n                                                   (Etempvar _aux 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                                                (Etempvar _aux1 tuint))))))))\n                           (Ssequence\n                              (Ssequence\n                                 (Sset _aux\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 _aux1\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 _aux\n                                          (Ebinop Oadd (Etempvar _aux tuint) \n                                             (Etempvar _aux1 tuint) tuint))\n                                       (Ssequence\n                                          (Ssequence\n                                             (Scall (Some _t'7)\n                                                (Evar _L32\n                                                   (Tfunction (Tcons tuint (Tcons tint Tnil)) tuint\n                                                      cc_default))\n                                                [Etempvar _aux tuint; Econst_int (Int.repr 13) tint])\n                                             (Sset _aux (Etempvar _t'7 tuint)))\n                                          (Ssequence\n                                             (Sset _aux1\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 _aux1\n                                                   (Ebinop Oxor (Etempvar _aux1 tuint)\n                                                      (Etempvar _aux 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                                                   (Etempvar _aux1 tuint))))))))\n                              (Ssequence\n                                 (Ssequence\n                                    (Sset _aux\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 _aux1\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 _aux\n                                             (Ebinop Oadd (Etempvar _aux tuint)\n                                                (Etempvar _aux1 tuint) tuint))\n                                          (Ssequence\n                                             (Ssequence\n                                                (Scall (Some _t'8)\n                                                   (Evar _L32\n                                                      (Tfunction (Tcons tuint (Tcons tint Tnil))\n                                                         tuint cc_default))\n                                                   [Etempvar _aux tuint;\n                                                   Econst_int (Int.repr 18) tint])\n                                                (Sset _aux (Etempvar _t'8 tuint)))\n                                             (Ssequence\n                                                (Sset _aux1\n                                                   (Ederef\n                                                      (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                                         (Econst_int (Int.repr 0) tint) \n                                                         (tptr tuint)) tuint))\n                                                (Ssequence\n                                                   (Sset _aux1\n                                                      (Ebinop Oxor (Etempvar _aux1 tuint)\n                                                         (Etempvar _aux 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                                                      (Etempvar _aux1 tuint))))))))\n                                 (Sfor (Sset _m (Econst_int (Int.repr 0) tint))\n                                    (Ebinop Olt (Etempvar _m tint) (Econst_int (Int.repr 4) tint)\n                                       tint)\n                                    (Ssequence\n                                       (Sset _aux\n                                          (Ederef\n                                             (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                                (Etempvar _m tint) (tptr tuint)) tuint))\n                                       (Ssequence\n                                          (Sset _aux1\n                                             (Ebinop Oadd\n                                                (Ebinop Omul (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) tint))\n                                          (Sassign\n                                             (Ederef\n                                                (Ebinop Oadd (Evar _w (tarray tuint 16))\n                                                   (Etempvar _aux1 tuint) \n                                                   (tptr tuint)) tuint) (Etempvar _aux tuint))))\n                                    (Sset _m\n                                       (Ebinop Oadd (Etempvar _m tint) (Econst_int (Int.repr 1) tint)\n                                          tint))))))))\n                  (Sset _j (Ebinop Oadd (Etempvar _j tint) (Econst_int (Int.repr 1) tint) tint)))\n               (Sfor (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 _aux\n                        (Ederef\n                           (Ebinop Oadd (Evar _w (tarray tuint 16)) (Etempvar _m tint) (tptr tuint))\n                           tuint))\n                     (Sassign\n                        (Ederef\n                           (Ebinop Oadd (Evar _x (tarray tuint 16)) (Etempvar _m tint) (tptr tuint))\n                           tuint) (Etempvar _aux tuint)))\n                  (Sset _m (Ebinop Oadd (Etempvar _m tint) (Econst_int (Int.repr 1) tint) tint))))\n            (Sset _i (Ebinop Oadd (Etempvar _i tint) (Econst_int (Int.repr 1) tint) tint)))\n\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.\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) Vundef) as [t0 T0].\n      rewrite RZL; apply Z_mod_lt; omega.\n    destruct (Znth_mapVint r ((5 * j + 4 * 1) mod 16) Vundef) as [t1 T1].\n      rewrite RZL; apply Z_mod_lt; omega.\n    destruct (Znth_mapVint r ((5 * j + 4 * 2) mod 16) Vundef) as [t2 T2].\n      rewrite RZL; apply Z_mod_lt; omega.\n    destruct (Znth_mapVint r ((5 * j + 4 * 3) mod 16) Vundef) as [t3 T3].\n      rewrite RZL; apply Z_mod_lt; omega.\n    eapply semax_post.\n    2: apply (Jbody _ FR c k h nonce out w x y t i j r I J wlist _ _ _ _ T0 T1 T2 T3).\n    intros; apply andp_left2.\n    unfold POSTCONDITION, abbreviate.\n    apply assert_lemmas.normal_ret_assert_derives'.\n    Intros W. Exists W. old_go_lower. 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.\n  Focus 2. 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  intros ? ?. apply andp_left2.\n    unfold POSTCONDITION, abbreviate.\n    apply assert_lemmas.normal_ret_assert_derives'.\n  Exists wints. rewrite Z.add_comm, Z2Nat.inj_add; try omega.\n  old_go_lower. Time entailer!. (*4.3*)(*TODO: eliminate old_go_lower*)\n  rewrite SnuffleS, R; trivial.\n  thaw FR2; cancel. }\napply andp_left2; apply derives_refl. \nTime Qed. (*11.891 secs (3.562u,0.s) (successful)*)", "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_loop3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2717262936380233}}
{"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.\nImplicit Arguments gf [].\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\nImplicit Arguments paco4_acc            [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_mon            [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_mult_strong    [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_mult           [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_fold           [ T0 T1 T2 T3 ].\nImplicit Arguments 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.\nImplicit Arguments gf_0 [].\nImplicit Arguments gf_1 [].\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\nImplicit Arguments paco4_2_0_acc            [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_2_1_acc            [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_2_0_mon            [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_2_1_mon            [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_2_0_mult_strong    [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_2_1_mult_strong    [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_2_0_mult           [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_2_1_mult           [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_2_0_fold           [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_2_1_fold           [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_2_0_unfold         [ T0 T1 T2 T3 ].\nImplicit Arguments 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.\nImplicit Arguments gf_0 [].\nImplicit Arguments gf_1 [].\nImplicit Arguments gf_2 [].\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\nImplicit Arguments paco4_3_0_acc            [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_3_1_acc            [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_3_2_acc            [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_3_0_mon            [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_3_1_mon            [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_3_2_mon            [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_3_0_mult_strong    [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_3_1_mult_strong    [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_3_2_mult_strong    [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_3_0_mult           [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_3_1_mult           [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_3_2_mult           [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_3_0_fold           [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_3_1_fold           [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_3_2_fold           [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_3_0_unfold         [ T0 T1 T2 T3 ].\nImplicit Arguments paco4_3_1_unfold         [ T0 T1 T2 T3 ].\nImplicit Arguments 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": "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/paco4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2717262936380233}}
{"text": "From iris.proofmode Require Import\n  proofmode.\n\nFrom caml5 Require Import\n  prelude.\nFrom caml5 Require Export\n  base.\nFrom caml5.algebra Require Import\n  lib.auth_Z_max.\n\nClass AuthZMaxG Σ := {\n  auth_Z_max_G_inG : inG Σ auth_Z_max_R ;\n}.\n#[local] Existing Instance auth_Z_max_G_inG.\n\nDefinition auth_Z_max_Σ := #[\n  GFunctor auth_Z_max_R\n].\n#[global] Instance subG_auth_Z_max_Σ Σ :\n  subG auth_Z_max_Σ Σ →\n  AuthZMaxG Σ.\nProof.\n  solve_inG.\nQed.\n\nSection auth_Z_max_G.\n  Context `{!AuthZMaxG Σ}.\n  Implicit Types n m p : Z.\n\n  Definition auth_Z_max_auth γ dq n :=\n    own γ (auth_Z_max_auth dq n).\n  Definition auth_Z_max_frag γ n :=\n    own γ (auth_Z_max_frag n).\n\n  #[global] Instance auth_Z_max_auth_timeless γ dq n :\n    Timeless (auth_Z_max_auth γ dq n).\n  Proof.\n    apply _.\n  Qed.\n  #[global] Instance auth_Z_max_auth_persistent γ n :\n    Persistent (auth_Z_max_auth γ DfracDiscarded n).\n  Proof.\n    apply _.\n  Qed.\n  #[global] Instance auth_Z_max_frag_timeless γ n :\n    Timeless (auth_Z_max_frag γ n).\n  Proof.\n    apply _.\n  Qed.\n  #[global] Instance auth_Z_max_frag_persistent γ n :\n    Persistent (auth_Z_max_frag γ n).\n  Proof.\n    apply _.\n  Qed.\n\n  #[global] Instance auth_Z_max_auth_fractional γ n :\n    Fractional (λ q, auth_Z_max_auth γ (DfracOwn q) n).\n  Proof.\n    intros ?*. rewrite -own_op -auth_Z_max_auth_dfrac_op //.\n  Qed.\n  #[global] Instance auth_Z_max_auth_as_fractional γ q n :\n    AsFractional (auth_Z_max_auth γ (DfracOwn q) n) (λ q, auth_Z_max_auth γ (DfracOwn q) n) q.\n  Proof.\n    split; done || apply _.\n  Qed.\n\n  Lemma auth_Z_max_auth_persist γ dq n :\n    auth_Z_max_auth γ dq n ==∗\n    auth_Z_max_auth γ DfracDiscarded n.\n  Proof.\n    iApply own_update. apply auth_Z_max_auth_persist.\n  Qed.\n\n  Lemma auth_Z_max_alloc n :\n    ⊢ |==> ∃ γ,\n      auth_Z_max_auth γ (DfracOwn 1) n.\n  Proof.\n    iMod (own_alloc (auth_Z_max.auth_Z_max_auth (DfracOwn 1) n)) as \"(% & ?)\".\n    { apply auth_Z_max_auth_valid. }\n    naive_solver.\n  Qed.\n\n  Lemma auth_Z_max_auth_valid γ dq a :\n    auth_Z_max_auth γ dq a -∗\n    ⌜✓ dq⌝.\n  Proof.\n    iIntros. iDestruct (own_valid with \"[$]\") as %?%auth_Z_max_auth_dfrac_valid. done.\n  Qed.\n  Lemma auth_Z_max_auth_combine γ dq1 n1 dq2 n2 :\n    auth_Z_max_auth γ dq1 n1 -∗\n    auth_Z_max_auth γ dq2 n2 -∗\n      auth_Z_max_auth γ (dq1 ⋅ dq2) n1 ∗\n      ⌜n1 = n2⌝.\n  Proof.\n    iIntros \"H●1 H●2\". iCombine \"H●1 H●2\" as \"H●\".\n    iDestruct (own_valid with \"H●\") as %(? & <-)%auth_Z_max_auth_dfrac_op_valid.\n    rewrite -auth_Z_max_auth_dfrac_op. naive_solver.\n  Qed.\n  Lemma auth_Z_max_auth_valid_2 γ dq1 n1 dq2 n2 :\n    auth_Z_max_auth γ dq1 n1 -∗\n    auth_Z_max_auth γ dq2 n2 -∗\n    ⌜✓ (dq1 ⋅ dq2) ∧ n1 = n2⌝.\n  Proof.\n    iIntros \"H●1 H●2\".\n    iDestruct (auth_Z_max_auth_combine with \"H●1 H●2\") as \"(H● & %)\".\n    iDestruct (auth_Z_max_auth_valid with \"H●\") as %?.\n    done.\n  Qed.\n  Lemma auth_Z_max_auth_agree γ dq1 n1 dq2 n2 :\n    auth_Z_max_auth γ dq1 n1 -∗\n    auth_Z_max_auth γ dq2 n2 -∗\n    ⌜n1 = n2⌝.\n  Proof.\n    iIntros \"H●1 H●2\".\n    iDestruct (auth_Z_max_auth_valid_2 with \"H●1 H●2\") as %?. naive_solver.\n  Qed.\n  Lemma auth_Z_max_auth_exclusive γ n1 n2 :\n    auth_Z_max_auth γ (DfracOwn 1) n1 -∗\n    auth_Z_max_auth γ (DfracOwn 1) n2 -∗\n    False.\n  Proof.\n    iIntros \"H●1 H●2\".\n    iDestruct (auth_Z_max_auth_valid_2 with \"H●1 H●2\") as %(? & _). done.\n  Qed.\n\n  Lemma auth_Z_max_frag_get γ q n :\n    auth_Z_max_auth γ q n -∗\n    auth_Z_max_frag γ n.\n  Proof.\n    apply own_mono, auth_Z_max_included.\n  Qed.\n  Lemma auth_Z_max_frag_le {γ n} n' :\n    (n' ≤ n)%Z →\n    auth_Z_max_frag γ n -∗\n    auth_Z_max_frag γ n'.\n  Proof.\n    intros. apply own_mono, auth_Z_max_frag_mono. done.\n  Qed.\n\n  Lemma auth_Z_max_valid γ dq n m :\n    auth_Z_max_auth γ dq n -∗\n    auth_Z_max_frag γ m -∗\n    ⌜m ≤ n⌝%Z.\n  Proof.\n    iIntros \"H●1 H●2\".\n    iDestruct (own_valid_2 with \"H●1 H●2\") as %?%auth_Z_max_both_dfrac_valid.\n    naive_solver.\n  Qed.\n\n  Lemma auth_Z_max_update {γ n} n' :\n    (n ≤ n')%Z →\n    auth_Z_max_auth γ (DfracOwn 1) n ==∗\n    auth_Z_max_auth γ (DfracOwn 1) n'.\n  Proof.\n    iIntros \"% H●\".\n    iMod (own_update with \"H●\"); first apply auth_Z_max_auth_update; done.\n  Qed.\nEnd auth_Z_max_G.\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/base_logic/lib/auth_Z_max.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947425132314, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2717150727871118}}
{"text": "Require Export unscoped header_extensible.\nRequire Export existentialsyntax implicativesyntax.\nRequire Import classical_deduction implicative_deduction.\n\nReserved Notation \"A ⊢ p\" (at level 70).\nReserved Notation \"A ⊢_exst p\" (at level 70).\n\nNotation \"∃ p\" := (inj (Exist _ p)) (at level 60).\n\nSection Existential.\n  Context {Sigma : Signature}.\n\n  Variable form : Type.\n  Variable retract : retract (form_existential form) form.\n  Variable subst_form : (fin -> term) -> form -> form.\n\n  Variable nd : list form -> form -> Prop.\n  Notation \"A ⊢ p\" := (nd A p) (at level 70).\n\n  Definition up_ctx (A : list form) := map (subst_form (S >> var_term)) A.\n  Inductive nd_exst (A : list form) : form -> Prop :=\n    | ndEI p t : A ⊢ subst_form (scons t (var_term)) p -> A ⊢_exst (∃ p)\n    | ndEE p q : A ⊢ (∃ p) -> p :: (up_ctx A) ⊢ subst_form (S >> var_term) q -> A ⊢_exst q\n  where \"A ⊢_exst p\" := (nd_exst A p).\n  Variable agree : forall A p, A ⊢_exst p -> A ⊢ p.\n\n  Variable weakening : forall A B p, A ⊢ p -> incl A B -> B ⊢ p.\n  Lemma weakening_exst A B p : A ⊢_exst p -> incl A B -> B ⊢ p.\n  Proof. revert B. destruct 1; intro Hinc; apply agree; [ now apply (ndEI _ p t), (weakening A) | apply (ndEE _ p q) ].\n    -now apply (weakening A).\n    -apply (weakening (p::up_ctx A)), incl_cons; [assumption | now left | apply incl_tl ].\n      unfold up_ctx. now apply incl_map.\n  Defined.\n\n  Variable retract_implicative : included form_implicative form.\n\n  Variable translate : form -> form.\n  Definition translate_exst (p : form_existential form) : _ := match p with\n    | Exist _ q => ¬¬(∃ (translate q))\n  end.\n  Notation \"« p »\" := (translate p).\n  Notation \"«/ A »\" := (map translate A).\n\n\n  Variable agree_cls : forall A p, nd_classic _ _ nd A p -> A ⊢ p.\n  Variable agree_imp : forall A p, nd_imp _ _ nd A p -> A ⊢ p.\n  Variable imp_nd : forall A p, nd_imp _ _ nd A p -> A ⊢ p.\n  Variable subst_form_inj : forall sigma p, subst_form sigma (inj p) = subst_form_existential _ subst_form _ sigma p.\n  Variable translation_inj : forall p, «inj p» = translate_exst  p.\n  Variable aux : forall p, subst_form (scons (var_term 0) (var_term)) (subst_form (up_term_term (S >> var_term)) p) = p.\n  Variable translation_bwd : forall A p, A ⊢ «p» <-> A ⊢ p.\n  Lemma translation_bwd_exst A p: A ⊢ (translate_exst p) <-> A ⊢ inj p.\n  Proof. destruct p. cbn. split; intro.\n    - assert (Hc : A ⊢ ∃ «f»). {now apply agree_cls,ndDN. }\n      apply (ndEE _ _ (∃ f)) in Hc. now apply agree. rewrite subst_form_inj. cbn. apply agree,(ndEI _ _ (var_term 0)).\n      rewrite aux. apply translation_bwd, agree_imp,ndHyp. now left.\n    -apply agree_imp,ndII,agree_imp,(ndIE _ _ _ _ (∃«f»)). apply agree_imp,ndHyp. now left.\n      apply (weakening A). 2:now apply incl_tl. apply (ndEE _ _ (∃«f»)) in H. now apply agree.\n      rewrite subst_form_inj. cbn. apply agree,(ndEI _ _ (var_term 0)). rewrite aux. apply translation_bwd.\n      apply agree_imp,ndHyp. now left.\n  Defined.\n\n  Variable subst_dn : forall sigma p, subst_form sigma (¬¬p) = ¬¬(subst_form sigma p).\n  Variable translation_subst : forall sigma q, «subst_form sigma q» = subst_form sigma «q».\n  Lemma translation_subst_exst sigma p :  « subst_form_existential _ subst_form _ sigma p » = subst_form sigma (translate_exst p).\n  Proof. destruct p; cbn. unfold Exist_. rewrite translation_inj. cbn. rewrite subst_dn. repeat apply congr_Impl_.\n    rewrite subst_form_inj. cbn. apply congr_Exist_; apply translation_subst. all: reflexivity.\n  Defined.\n\n  Variable cut : forall A p q,  A ⊢ p -> (p :: A) ⊢ q -> A ⊢ q.\n  Lemma translation_helper_exst A p : A ⊢ (¬¬(translate_exst p)) -> A ⊢ translate_exst p.\n  Proof. destruct p. cbn. intro. apply (cut _ _ _ H). apply agree_imp,ndII,agree_imp,(ndIE _ _ _ _ (¬¬¬(∃«f»))).\n    apply agree_imp,ndHyp. right. now left. apply agree_imp,ndII,agree_imp,(ndIE _ _ _ _ (¬(∃«f»))).\n    apply agree_imp,ndHyp. now left. apply agree_imp,ndHyp. right. now left.\n  Defined.\n\n  Lemma translation_map A: up_ctx «/A» = «/up_ctx A».\n  Proof. unfold up_ctx. repeat rewrite map_map. apply map_ext. intro p. symmetry. apply translation_subst.\n  Qed.\nEnd Existential.\n\nSection translation.\n  Context {Sigma : Signature}.\n\n  Variable form : Type.\n  Variable nd : list form -> form -> Prop.\n  Variable cnd : list form -> form -> Prop.\n  Variable subst_form : (fin -> term) -> form -> form.\n  Variable retract_implicative : included form_implicative form.\n  Variable retract_existential : included form_existential form.\n  Variable translate : form -> form.\n\n  Notation \"A ⊢[ nd ] p\" := (@nd_exst _ _ _ subst_form nd A p) (at level 70).\n  Notation \"« p »\" := (translate p).\n  Notation \"«/ A »\" := (map translate A).\n\n  Variable translation_inj : forall p, «inj p» = translate_exst _ _ _ translate p.\n  Variable translation_subst : forall sigma q, «subst_form sigma q» = subst_form sigma «q».\n\n  Variable agree_cnd : forall A p, A ⊢[cnd] p -> cnd A p.\n  Variable embed : forall A p, nd A p -> cnd A p.\n  Lemma embed_exst A p : A ⊢[nd] p -> cnd A p.\n  Proof. destruct 1; apply agree_cnd. now apply (ndEI _ _ _ _ _ _ t), embed. apply (ndEE _ _ _ _ _ p); now apply embed.\n  Defined.\n\n  Variable weakening : forall A B p, nd A p -> incl A B -> nd B p.\n\n(*   Lemma dn_int_exst A p: A ⊢[nd] p -> A ⊢[nd] (¬¬p).\n  Proof. intro. apply imp_nd, ndII, imp_nd, (ndIE _ _ _ _ p).\n    -apply imp_nd, ndHyp. now left.\n    -now apply (weakening_exst _ _ _ _ weakening A), incl_tl.\n  Qed. *)\n  Variable dni : forall A p, nd A p -> nd A (¬¬p).\n\n  Variable agree_nd : forall A p, A ⊢[nd] p -> nd A p. \n  Variable agree_cls : forall A p, nd_classic _ _ cnd A p -> cnd A p.\n  Variable agree_imp : forall A p, nd_imp _ _ nd A p -> nd A p.\n  Variable translation_helper : forall A p, nd A (¬¬«p») -> nd A «p».\n\n  Variable translation : forall A p, cnd A p -> nd «/A» «p».\n  Lemma translation_exst A p: A ⊢[cnd] p -> nd «/A» «p».\n  Proof. destruct 1.\n    -rewrite translation_inj. cbn.\n     apply agree_imp,ndII,agree_imp,(ndIE _ _ _ _ (∃«p»)). apply agree_imp,ndHyp. now left.\n     apply agree_nd. apply (ndEI _ _ _ _ _ _ t). apply (weakening «/A»). 2: now apply incl_tl.\n     rewrite <- translation_subst. now apply translation.\n    -apply translation_helper,agree_imp,ndII,agree_imp,(ndIE _ _ _ _ (¬∃«p»)).\n     apply (weakening «/A»). 2: now apply incl_tl. apply translation in H. rewrite translation_inj in H. now cbn in H.\n     apply agree_imp,ndII,agree_imp,(ndIE _ _ _ _ «q»). apply agree_imp,ndHyp. right. now left.\n     apply agree_nd,(ndEE _ _ _ _ _ «p»). apply agree_imp,ndHyp. now left.\n     apply (weakening «/p::(up_ctx _ subst_form A)»). rewrite <- translation_subst. now apply translation.\n     { unfold incl. destruct 1. now left. unfold up_ctx. repeat rewrite map_cons. do 3 right.\n       rewrite <- translation_map in H1. now unfold up_ctx in H1. apply translation_subst. }\n  Defined.\nEnd translation.", "meta": {"author": "ralvrz", "repo": "ModularFOL", "sha": "400fc000889a34b66cf6adec0caf205714eef547", "save_path": "github-repos/coq/ralvrz-ModularFOL", "path": "github-repos/coq/ralvrz-ModularFOL/ModularFOL-400fc000889a34b66cf6adec0caf205714eef547/existential_deduction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160666, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2716677018935901}}
{"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 PCMLarge WFLibLarge.\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": "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/GenYOrd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878414043816, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.27166769566083976}}
{"text": "From iris.prelude Require Import options.\nRequire Import cpdt.CpdtTactics.\nRequire Import coq_tricks.Deex.\nRequire Import Burrow.trees.\nRequire Import Burrow.locations.\nRequire Import Burrow.indexing.\nRequire Import Burrow.gmap_utils.\n\nFrom stdpp Require Import countable.\n\nSection Relive.\n\nContext {M} `{!EqDecision M} `{!TPCM M}.\n\nDefinition reserved_get_or_unit_relive (reserved: Lifetime * M) (old: Lifetime) (new: Lifetime) : M :=\n  match reserved with\n  | (my_lt, m) => if decide (multiset_le my_lt old /\\ ¬ multiset_le my_lt new) then m else unit\n  end.\n\nDefinition sum_reserved_over_lifetime_relive (reserved: listset (Lifetime * M)) (old: Lifetime) (new: Lifetime) :=\n  set_fold (λ reserved m , dot m (reserved_get_or_unit_relive reserved old new)) unit reserved.\n  \nGlobal Instance sum_reserved_over_lifetime_relive_proper :\n  Proper ((≡) ==> (=) ==> (=) ==> (=)) (sum_reserved_over_lifetime_relive).\nProof.\n  unfold sum_reserved_over_lifetime_relive.\n  unfold Proper, \"==>\". intros. subst.\n  have p := set_fold_proper (=) ((λ (reserved : Lifetime * M) (m : M), dot m (reserved_get_or_unit_relive reserved y0 y1))).\n  unfold Proper in p. unfold \"==>\" in p. \n  eapply p.\n  ** typeclasses eauto.\n  ** typeclasses eauto.\n  ** intros. crush.\n  ** intros. rewrite <- tpcm_assoc. rewrite <- tpcm_assoc.\n      f_equal. apply tpcm_comm.\n  ** trivial.\nQed.\n\nDefinition relive_cell (cell: Cell M) (old: Lifetime) (new: Lifetime) : Cell M :=\n  match cell with\n  | CellCon m res =>\n      CellCon (sum_reserved_over_lifetime_relive res old new) ∅\n  end.\n  \nDefinition relive_cell_exc (cell: Cell M) (old: Lifetime) (new: Lifetime) (exc: Lifetime * M)\n      : Cell M :=\n  match cell with\n  | CellCon m res =>\n      CellCon (sum_reserved_over_lifetime_relive (res ∖ {[ exc ]}) old new) ∅\n  end.\n\nGlobal Instance relive_cell_proper : Proper ((≡) ==> (=) ==> (=) ==> (≡)) relive_cell.\nProof.\n  unfold Proper, \"==>\". intros. subst. unfold relive_cell. destruct x, y.\n  inversion H. setoid_rewrite H1. trivial.\nQed.\n\nGlobal Instance relive_cell_exc_proper : Proper ((≡) ==> (=) ==> (=) ==> (=) ==> (≡)) relive_cell_exc.\nProof.\n  unfold Proper, \"==>\". intros. subst. unfold relive_cell_exc. destruct x, y.\n  inversion H. setoid_rewrite H1. trivial.\nQed.\n\nLemma relive_cell_triv old new\n  : triv_cell ≡ relive_cell triv_cell old new.\nProof. trivial. Qed.\n  \nEnd Relive.\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/burrow/relive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878414043816, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2716676956608397}}
{"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 O E Eprime A B C Oprime Aprime Bprime Cprime Eprimeprime Bprimeprime C2 C3 : Universe, ((wd_ O E /\\ (wd_ Oprime Eprime /\\ (wd_ A O /\\ (wd_ B O /\\ (wd_ C O /\\ (wd_ A E /\\ (wd_ Eprimeprime O /\\ (wd_ O Oprime /\\ (wd_ Bprimeprime O /\\ (wd_ Bprime Oprime /\\ (wd_ Oprime C /\\ (wd_ Eprimeprime A /\\ (wd_ E Eprimeprime /\\ (wd_ E Eprime /\\ (wd_ O Eprime /\\ (wd_ Oprime Eprimeprime /\\ (wd_ E Oprime /\\ (wd_ Bprimeprime C /\\ (wd_ Bprime C3 /\\ (wd_ B Bprimeprime /\\ (wd_ Eprime C2 /\\ (wd_ Aprime C2 /\\ (wd_ Oprime Aprime /\\ (wd_ A Aprime /\\ (wd_ C Cprime /\\ (wd_ B Bprime /\\ (col_ O E A /\\ (col_ O E B /\\ (col_ O E C /\\ (col_ Oprime Eprime Aprime /\\ (col_ Oprime Eprime Bprime /\\ (col_ Oprime Eprime Cprime /\\ (col_ O Eprimeprime Bprimeprime /\\ (col_ O Eprimeprime Oprime /\\ (col_ O Eprimeprime C2 /\\ (col_ O Eprimeprime C3 /\\ (col_ O A C /\\ (col_ O Oprime C /\\ col_ A Oprime C)))))))))))))))))))))))))))))))))))))) -> col_ Oprime O E)).\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_1292.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.705785040214066, "lm_q2_score": 0.38491214448393357, "lm_q1q2_score": 0.2716652333734754}}
{"text": "From st.prelude Require Import autosubst.\nFrom st.STLCmuVS Require Import lang typing tactics.\nFrom st.STLCmu Require Import types.\nFrom st.STLCmuVS.lib Require Import fixarrow omega.\n\nInductive action :=\n  | Guard\n  | Assert.\n\nDefinition FstSndga (ga : action) : expr → expr :=\n  match ga with\n  | Guard => Fst\n  | Assert => Snd\n  end.\n\nDefinition opp_action (ga : action) :=\n  match ga with\n  | Guard => Assert\n  | Assert => Guard\n  end.\n\nDefinition fixgenTRecga (gb ab : val) : val :=\n  (LamV (* 1 → ((τ → τ) × (τ → τ)) *) (\n       LamV (* 1 *) (\n           ( LamV (Fold (gb.{ren (+2)} (Unfold %0))) , (* τ → τ *)\n             LamV (Fold (ab.{ren (+2)} (Unfold %0))) (* τ → τ *)\n           )\n         )\n     )\n  )%Eₙₒ.\n\nLemma fixgenTRecga_subst (gb ab : val) (σ : var → expr) : (fixgenTRecga gb ab).{σ} = fixgenTRecga gb.{up σ} ab.{up σ}.\nProof. rewrite /fixgenTRecga. repeat rewrite -val_subst_valid. by asimpl. Qed.\n\n(* Lemma App_fixgenTRecga_STLCmuVS_step (gb ab : val) (e : expr) : *)\n(*   STLCmuVS_step (fixgenTRecga gb ab (Lam e)) *)\n(* ((LamV ( *)\n(*            ( LamV (Fold ((of_val gb).[Lam e.[ren (0 .: (+3))] .: ren (+2)] (Unfold %0))) , (* τ → τ *) *)\n(*              LamV (Fold ((of_val ab).[Lam e.[ren (0 .: (+3))] .: ren (+2)] (Unfold %0))) (* τ → τ *) *)\n(*            ) *)\n(*          )))%Eₙₒ. *)\n(* Proof. *)\n(*   assert ( *)\n(* (of_val (LamV ( *)\n(*            ( LamV (Fold ((of_val gb).[Lam e.[ren (0 .: (+3))] .: ren (+2)] (Unfold %0))) , (* τ → τ *) *)\n(*              LamV (Fold ((of_val ab).[Lam e.[ren (0 .: (+3))] .: ren (+2)] (Unfold %0))) (* τ → τ *) *)\n(*            ) *)\n(*          )))%Eₙₒ = *)\n(* ((LamV ( *)\n(*            ( LamV (Fold ((of_val gb).[ren (+2)] (Unfold %0))) , (* τ → τ *) *)\n(*              LamV (Fold ((of_val ab).[ren (+2)] (Unfold %0))) (* τ → τ *) *)\n(*            ) *)\n(*          )))%Eₙₒ.[Lam e/] *)\n(*     ) as ->. by asimpl. *)\n(*   apply head_prim_step. eapply App_Lam_head_step. by simpl. *)\n(* Qed. *)\n\nLemma fixgenTRecga_typed (gb ab : val) Γ τb\n      (pgb : (TUnit ⟶ ((TRec τb ⟶ TRec τb) × (TRec τb ⟶ TRec τb)))%Tₙₒ :: Γ ⊢ₙₒ gb : τb.[TRec τb/] ⟶ τb.[TRec τb/])\n      (pab : (TUnit ⟶ ((TRec τb ⟶ TRec τb) × (TRec τb ⟶ TRec τb)))%Tₙₒ :: Γ ⊢ₙₒ ab : τb.[TRec τb/] ⟶ τb.[TRec τb/]) :\n  Γ ⊢ₙₒ fixgenTRecga gb ab :\n    (TUnit ⟶ ((TRec τb ⟶ TRec τb) × (TRec τb ⟶ TRec τb))) ⟶ (TUnit ⟶ ((TRec τb ⟶ TRec τb) × (TRec τb ⟶ TRec τb))).\nProof.\n  constructor. constructor. constructor.\n  constructor. constructor. apply App_typed with (τ1 := τb.[TRec τb/]). rewrite -val_subst_valid.\n  apply context_weakening2. apply pgb.\n  constructor. by constructor.\n  constructor. constructor. apply App_typed with (τ1 := τb.[TRec τb/]). rewrite -val_subst_valid.\n  apply context_weakening2. apply pab.\n  constructor. by constructor.\nQed.\n\nGlobal Opaque fixgenTRecga.\n\n(* Lemma test (t : expr) : t = (ids 1).[up (ren (+2))]. *)\n(* asimpl.  *)\nFixpoint ga_pair (ga : action) (τ : type) : val :=\n  (match τ with\n   | TUnit => match ga with\n             | Guard => LamV %0\n             | Assert => LamV (Seq %0 ())\n             end\n   | TBool => match ga with\n             | Guard => LamV %0\n             | Assert => LamV (If %0 true false)\n             end\n   | TInt => match ga with\n            | Guard => LamV %0\n            | Assert => LamV (%0 + 0)\n            end\n   | TProd τ1 τ2 => LamV (LetIn (Fst %0) (LetIn (Snd %1) ((ga_pair ga τ1).{ren (+3)} %1, (ga_pair ga τ2).{ren (+3)} %0)))\n   | TSum τ1 τ2 => LamV (Case %0 (InjL ((ga_pair ga τ1).{ren (+2)} %0)) (InjR ((ga_pair ga τ2).{ren (+2)} %0)))\n   | TArrow τ1 τ2 => LamV (Lam ((ga_pair ga τ2).{ren (+2)} (%1 ((ga_pair (opp_action ga) τ1).{ren (+2)} %0))))\n   | TRec τb => let β := fixgenTRecga (ga_pair Guard τb) (ga_pair Assert τb) in\n               LamV (FstSndga ga (LamV (FixArrow β.{ren (+2)} %0(*_*)) ()) %0)\n   | TVar X => LamV (FstSndga ga (Var (S X) ()) %0)\n   end)%Eₙₒ.\n\n(* We never actually need typedness of ga; but it serves as a good sanity check *)\nLemma ga_typed_gen (τ : type) (τs : list type) (pτn : Closed_n (length τs) τ) (ga : action) :\n  map (fun τ => (TUnit ⟶ (τ ⟶ τ) × (τ ⟶ τ))%Tₙₒ) τs ⊢ₙₒ (ga_pair ga τ) : (τ.[subst_list τs] ⟶ τ.[subst_list τs]).\nProof.\n  generalize dependent ga.\n  generalize dependent τs.\n  induction τ as [ | | | τ1 IHτ1 τ2 IHτ2 | τ1 IHτ1 τ2 IHτ2 | τ1 IHτ1 τ2 IHτ2 | τb IHτb | X ]; intros τs Cnτ ga;\n    try by (destruct ga; by repeat econstructor).\n  - repeat econstructor; fold ga_pair.\n    rewrite -val_subst_valid. apply context_weakening3. apply IHτ1. closed_solver.\n    rewrite -val_subst_valid. apply context_weakening3. apply IHτ2. closed_solver.\n  - repeat econstructor; fold ga_pair.\n    rewrite -val_subst_valid. apply context_weakening2. apply IHτ1. closed_solver.\n    rewrite -val_subst_valid. apply context_weakening2. apply IHτ2. closed_solver.\n  - repeat econstructor; fold ga_pair.\n    rewrite -val_subst_valid. apply context_weakening2. apply IHτ2. closed_solver.\n    rewrite -val_subst_valid. apply context_weakening2. apply IHτ1. closed_solver.\n  - (* TRec *) destruct ga.\n    + constructor. fold ga_pair.\n      apply App_typed with (τ1 := (TRec τb).[subst_list τs]). 2: by constructor.\n      eapply Fst_typed.\n      apply App_typed with (τ1 := TUnit). 2: by constructor. apply Lam_typed.\n      apply App_typed with (τ1 := TUnit). 2: by constructor.\n      apply FixArrow_typed. rewrite -val_subst_valid. apply context_weakening2. apply fixgenTRecga_typed.\n      * asimpl. change (TRec τb.[up (subst_list τs)] .: subst_list τs) with (subst_list (TRec τb.[up (subst_list τs)] :: τs)).\n        rewrite -map_cons. apply IHτb with (ga := Guard). closed_solver.\n      * asimpl. change (TRec τb.[up (subst_list τs)] .: subst_list τs) with (subst_list (TRec τb.[up (subst_list τs)] :: τs)).\n        rewrite -map_cons. apply IHτb with (ga := Assert). closed_solver.\n    + constructor. fold ga_pair.\n      eapply App_typed. 2: by constructor.\n      eapply Snd_typed.\n      apply App_typed with (τ1 := TUnit). 2: by constructor. apply Lam_typed.\n      apply App_typed with (τ1 := TUnit). 2: by constructor.\n      apply FixArrow_typed. rewrite -val_subst_valid. apply context_weakening2.\n      simpl. apply fixgenTRecga_typed.\n      * asimpl. change (TRec τb.[up (subst_list τs)] .: subst_list τs) with (subst_list (TRec τb.[up (subst_list τs)] :: τs)).\n        rewrite -map_cons. apply IHτb with (ga := Guard). closed_solver.\n      * asimpl. change (TRec τb.[up (subst_list τs)] .: subst_list τs) with (subst_list (TRec τb.[up (subst_list τs)] :: τs)).\n        rewrite -map_cons. apply IHτb with (ga := Assert). closed_solver.\n  - (* TVar *)\n    destruct (TVar_subst_list_closed_n_length _ _ Cnτ) as [τ [eq ->]].\n    destruct ga; repeat econstructor; simpl; by rewrite list_lookup_fmap eq /=.\nQed.\n\nLemma ga_pair_typed (τ : type) (pτn : Closed τ) (ga : action) :\n  [] ⊢ₙₒ (ga_pair ga τ) : (τ ⟶ τ).\nProof.\n  cut (map (fun τ => (TUnit ⟶ (τ ⟶ τ) × (τ ⟶ τ))%Tₙₒ) [] ⊢ₙₒ (ga_pair ga τ) : (τ.[subst_list []] ⟶ τ.[subst_list []])).\n  by asimpl. by apply ga_typed_gen.\nQed.\n\nLemma ga_pair_closed (τ : type) (pτn : Closed τ) (ga : action) :\n  Closed (of_val (ga_pair ga τ)).\nProof.\n  intro σ. change 0 with (length ([] : list type)).\n  apply (typed_n_closed [] (TArrow τ τ)). by apply ga_pair_typed.\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/backtranslations/sem_syn/sem_le_syn/guard_assert.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.2715801777686696}}
{"text": "(**************************  uc/OS-II  ******************************)\n(*************************** OS_TIME.C ******************************)\n(******Proofs for API Fucntion:  void* OSTimeDly(INT16U ticks)*******)\n(************************C Source Code:******************************)\n(* \nvoid  OSTimeDly (INT16U ticks)\n{\n1  if (ticks > 0)\n   {\n2    OS_ENTER_CRITICAL();\n3    if(OSTCBCur -> OSTCBPrio == OS_PRIO_IDLE)\n     {\n4      OS_EXIT_CRITICAL;\n5      reutrn;\n     }\n6    if (OSTCBCur->OSTCBStat == OS_STAT_RDY && OSTCBCur -> OSTCBDly == 0)\n     {\n7      if ((OSRdyTbl[OSTCBCur->OSTCBY] &= ~OSTCBCur->OSTCBBitX) == 0)\n       {\n8        OSRdyGrp &= ~OSTCBCur->OSTCBBitY;\n       }\n9      OSTCBCur->OSTCBDly = ticks;\n10       OS_EXIT_CRITICAL();\n11      OS_Sched();\n     }\n12   else \n13     OS_EXIT_CRITICAL();\n   }\n14 return;\n}\n*)\n(*********************************************************************)\n\nRequire Import ucos_include.\nRequire Import OSTimeDlyPure.\nRequire Import time_absop_rules.\n\nOpen Scope code_scope.\n(* OSTimeDelay Proof *)\nOpen Scope int_scope.\n\nLemma val_inj_ltu_true:\nforall i,\nval_inj\n         (if Int.ltu ($ 0) i\n          then Some (Vint32 Int.one)\n          else Some (Vint32 Int.zero)) <> Vint32 Int.zero ->\nInt.ltu ($ 0) i = true.\nProof.\n  intros.\n  remember (Int.ltu ($ 0) i) as Hi.\n  destruct Hi; auto.\nQed.\n\n\nLemma val_inj_ltu_false:\n  forall i,val_inj\n             (if Int.ltu ($ 0) i\n              then Some (Vint32 Int.one)\n              else Some (Vint32 Int.zero)) = Vint32 Int.zero \\/\n           val_inj\n             (if Int.ltu ($ 0) i\n              then Some (Vint32 Int.one)\n              else Some (Vint32 Int.zero)) = Vnull ->\n           i = Int.zero.\nProof.\n  intros.\n  destruct H;\n    match goal with\n      | H : context [if ?x then _ else _ ] |- _ =>\n        let y := fresh in  remember x as y ; destruct y; simpl in H; tryfalse\n    end.\n  apply ltu_zero_eq_zero;eauto.\n  int auto.\nQed.\n(*\nLtac solve_if_neq :=\n  match goal with\n  |  |- context[if ?c then _ else _] =>   \n     try solve \n         [ let x := fresh in\n           (destruct c; simpl; introv x; tryfalse) |\n           apply true_if_else_true;\n             apply Zle_is_le_bool;\n             try rewrite byte_max_unsigned_val; \n             try rewrite max_unsigned_val; \n             try omega; auto\n         ]\n\n  end.\n\nLtac pure_auto := first [ do 2 solve_if_neq | go | pauto'].\n*)\n\nLemma OSTimeDlyProof :\n  forall vl p r tid ,\n    Some p = BuildPreA' os_api OSTimeDly dlyapi vl OSLInv tid init_lg ->\n    Some r = BuildRetA' os_api OSTimeDly dlyapi vl OSLInv tid init_lg ->\n    exists t d1 d2 s,\n      os_api OSTimeDly = Some (t, d1, d2, s) /\\\n      {| OS_spec, GetHPrio, OSLInv, I, r, Afalse |} |-tid {{ p }} s {{ Afalse }}.\nProof.\n  init_spec.\n  \n(* if----------------------L1*)\n  hoare forward; pure_auto.\n  Focus 2.\n  instantiate (1 := <||END None||>  **\n                           LV ticks @ Int16u |-> Vint32 i **\n                           Aie true **\n                           Ais nil **\n                           Acs nil ** Aisr empisr ** A_dom_lenv ((ticks, Int16u) :: nil) ** p_local OSLInv tid init_lg).\n\n  hoare forward.\n  hoare forward.\n  \n  hoare unfold pre.\n  hoare abscsq.\n  apply noabs_oslinv.\n  eapply  OSTimeDly_high_level_step_1.\n  eapply val_inj_ltu_false; auto.\n  pure_auto.\n  hoare forward.\n  (* en_crit---------------L2*)\n  pure intro.\n  assert (Int.ltu ($ 0) i = true).\n  remember (Int.ltu ($ 0) i) as X.\n  destruct X;unfolds in H;simpl in H;tryfalse;auto.\n  clear H H0 H2.\n  hoare forward prim.\n  hoare unfold.\n  (* if idle ---------------L3*)\n  hoare forward.\n  pure_auto.\n  pure_auto.\n  pure intro.\n  instantiate (1:=Afalse).\n  (*------------------------L4*)\n  assert (Int.eq i4 ($ OS_IDLE_PRIO) =true).\n  destruct (Int.eq i4 ($ OS_IDLE_PRIO));unfolds in H4;simpl in H4;tryfalse;auto.\n  clear H4 H5 H12.\n  unfold1 TCBList_P in H10;simpljoin.\n  unfold TCBNode_P in *.\n  destruct x2.\n  destruct p.\n  simpljoin.\n  unfold V_OSTCBNext, V_OSTCBMsg, V_OSTCBPrio in *.\n  unfold TcbJoin in *.\n  assert (TcbMod.get v'21 x = Some (p, t, m)).\n  lets H100 : TcbMod.get_sig_some x (p, t, m).\n  eapply TcbMod.join_get_get_l; eauto.\n  assert (TcbMod.get v'13 x = Some (p, t, m)).\n  eapply TcbMod.join_get_get_r; eauto.\n  unfolds in H25.\n  inverts H25.\n  lets Hx: Int.eq_spec p ($ OS_IDLE_PRIO).\n  rewrite H23 in Hx.\n  subst p.\n  inverts H4.\n  hoare abscsq.\n  apply noabs_oslinv.\n  eapply OSTimeDly_high_level_step_4;eauto.\n  pure_auto.\n\n  hoare forward prim.\n  unfold AOSTCBList.\n  sep pauto;eauto.\n  sep cancel tcbdllflag.\n  unfold tcbdllseg.\n  unfold dllseg at 2;fold dllseg.\n  sep pauto.\n  unfold node.\n  sep pauto.\n  splits; pauto.\n  unfolds;simpl;auto.\n  unfolds;simpl;auto.\n  simpl;auto.\n  do 4 eexists;splits;eauto.\n  unfolds.\n  splits;eauto.\n  simpl;auto.\n  (* return----------------------L5*)\n  hoare forward.\n  \n  (* if rdy ---------------L6*)\n  hoare forward.\n  pure intro.\n  assert (Int.eq i4 ($ OS_IDLE_PRIO) = false) as Hnidle.\n  clear -H4.\n  destruct (Int.eq i4 ($ OS_IDLE_PRIO));auto;destruct H4;simpl in H;tryfalse.\n  clear H4.\n  hoare forward;pure_auto.\n  pure intro.\n  (*-----------------------L4*)\n  assert (Int.eq i5 ($ OS_STAT_RDY) =true).\n  destruct (Int.eq i5 ($ OS_STAT_RDY));destruct (Int.eq i6 ($ 0));unfolds in H4;simpl in H4;tryfalse;auto.\n  assert (Int.eq i6  ($ 0) = true) as Hdly0.\n  destruct (Int.eq i5 ($ OS_STAT_RDY));destruct (Int.eq i6 ($ 0));unfolds in H4;simpl in H4;tryfalse;auto.\n  clear H4 H5 H12.\n  hoare unfold.\n  assert (TCBList_P (Vptr (v'23, Int.zero))\n                    ((v'22\n                        :: v'18\n                        :: x7\n                        :: x6\n                        :: Vint32 i6\n                        :: Vint32 i5\n                        :: Vint32 i4\n                        :: Vint32 i3\n                        :: Vint32 i2\n                        :: Vint32 i1 :: Vint32 i0 :: nil) :: v'9)\n                    v'10 v'21) as Htcblistp.\n  auto.\n  unfold1 TCBList_P in H10; simpljoin.\n  unfold TCBNode_P in *.\n  rename e into H10.\n  rename e0 into H25.\n  rename j into  H26.\n  rename t into H27.\n  rename t0 into H28.\n  destruct x2.\n  destruct p.\n  simpljoin.\n  unfold V_OSTCBNext, V_OSTCBMsg, V_OSTCBPrio in *.\n  unfold TcbJoin in *.\n  assert (TcbMod.get v'21 x = Some (p, t, m)).\n  lets H100 : TcbMod.get_sig_some x (p, t, m).\n  eapply TcbMod.join_get_get_l; eauto.\n  assert (TcbMod.get v'13 x = Some (p, t, m)).\n  eapply TcbMod.join_get_get_r; eauto.\n  assert ((Int.unsigned i2 < 8)%Z).\n  unfold RL_TCBblk_P in r; simpljoin.\n  unfold V_OSTCBY in H34; simpl in H34; inverts H34.\n  pauto.\n  assert (length v'10 = 8%nat).\n  pauto.\n  assert (exists i4,\n            nth_val' (Z.to_nat (Int.unsigned i2)) v'10 = Vint32 i4 /\\\n            Int.unsigned i4 <= 255)%Z.\n  apply array_int8u_nth_lt_len; auto.\n  rewrite H31.\n  clear - H30.\n  apply Nat2Z.inj_lt.\n  rewrite Z2Nat.id; int auto.\n  simpljoin.\n  hoare forward.\n  pure_auto.\n  rewrite H32; simpl; pure_auto.\n  pure_auto.\n(*  pure_auto. *)\n  rewrite H32; simpl; pure_auto.\n  pure_auto.\n\n  (* if -----------------------L5*)\n  \n  hoare unfold.\n  hoare forward.\n  pure_auto.\n  rewrite H32; simpl val_inj.\n  rewrite update_nth_val_len_eq.\n  rewrite H31.\n  simpl; auto.\n  \n  rewrite H32; simpl val_inj.\n  rewrite len_lt_update_get_eq.\n  simpl.\n  cut (Int.unsigned (Int.and x2 (Int.not i1)) <=? Byte.max_unsigned = true)%Z.\n  intros H100; rewrite H100; auto.\n  apply leb_bytemax_true_intro.\n  apply int_lemma1; auto.\n  rewrite H31; simpl; auto.\n\n  rewrite H32; simpl val_inj.\n  rewrite len_lt_update_get_eq.\n  simpl.\n  pure_auto.\n  rewrite H31; simpl; auto.\n  unfold AOSRdyGrp.\n  hoare_assign.\n  pure_auto.\n  pure_auto.\n  rule_type_val_match_elim; simpl; auto.\n  pure_auto.\n\n  hoare forward.\n  lets Hst: low_stat_rdy_imp_high r H23 Hdly0;eauto.\n  subst.\n  hoare forward.\n  pure_auto.\n  hoare abscsq.\n  apply noabs_oslinv.\n  eapply OSTimeDly_high_level_step_2; eauto.\n  pure_auto.\n  unfold AECBList in *.\n  instantiate (1 := <||END None||> ** Aie true **\n                       Ais nil **\n                       Acs nil **\n                       Aisr empisr ** p_local OSLInv (v'23, Int.zero) init_lg ** LV ticks @ Int16u |-> Vint32 i ** A_dom_lenv ((ticks, Int16u) :: nil)).\n  hoare forward prim.\n  unfold AECBList in *.\n  instantiate (1 := LV ticks @ Int16u |-> Vint32 i ** A_dom_lenv ((ticks, Int16u) :: nil)).\n  sep semiauto.\n  sep cancel evsllseg.\n  sep cancel Astruct.\n  sep cancel dllseg.\n  sep cancel dllseg.\n  sep lift 3%nat in H10.\n  sep lift 3%nat.\n  eapply tcbdllflag_hold;eauto.\n  apply tcbdllflag_hold_middle.\n  simpl;auto.\n  rule_type_val_match_elim; simpl val_inj.\n  rewrite H32; simpl val_inj.\n  split.\n  eapply event_wait_rl_tbl_grp';eauto.\n  rewrite len_lt_update_get_eq in H36.\n  rewrite H32 in H36.\n  simpl in H36.\n  destruct (Int.eq (x2&ᵢInt.not i1) ($ 0));simpl in H36;tryfalse;auto.\n  rewrite H31.\n  unfolds OS_RDY_TBL_SIZE.\n  simpl Z.of_nat.\n  auto.\n  eapply idle_in_rtbl_hold;eauto.\n  \n  rule_type_val_match_elim; simpl; auto.\n  cut (Int.unsigned (i4&ᵢInt.not i0) <=? Byte.max_unsigned = true)%Z.\n  intros H100;rewrite H100; auto.\n  apply leb_bytemax_true_intro.\n  apply int_lemma1; auto.\n\n  split.\n  apply array_type_vallist_match_hold; auto.\n  rewrite H31; simpl; auto.\n  apply Nat2Z.inj_lt.\n  clear - H30.\n  rewrite Z2Nat.id; int auto.\n\n  rewrite H32; simpl.\n  cut (Int.unsigned (x2&ᵢInt.not i1) <=? Byte.max_unsigned = true)%Z.\n  intros H100; rewrite H100; auto.\n  apply leb_bytemax_true_intro.\n  apply int_lemma1; auto.\n\n  rewrite update_nth_val_len_eq.\n  simpl; auto.\n\n  eapply R_PrioTbl_P_hold1; eauto.\n\n  rewrite H32.\n  simpl.\n  \n  eapply rtbl_remove_RL_RTbl_PrioTbl_P_hold with (prio:= p) ;eauto;\n  (funfold r; try rewrite Int.repr_unsigned; auto).\n\n  apply nth_val'_imp_nth_val_int;auto.\n  \n  eapply ECBList_P_hold1;eauto.\n  instantiate (1 := (TcbMod.set v'21 (v'23, Int.zero)\n                                (p, wait os_stat_time  i, m))).\n  rewrite H32; simpl val_inj.\n  \n  3:apply TcbMod.join_set_r; eauto;unfold TcbMod.indom;eauto.\n\n  eapply TCBList_P_tcb_dly_hold;eauto.\n  \n  eapply TcbMod_join_impl_prio_neq_cur_r;eauto.\n\n  eapply R_PrioTbl_P_impl_prio_neq_cur; eauto.\n  funfold r; auto.\n  apply nth_val'_imp_nth_val_int;auto.\n  rewrite H32; simpl val_inj.\n  eapply TCBList_P_tcb_dly_hold';eauto; (funfold r; try rewrite Int.repr_unsigned; auto).\n  eapply TcbMod_join_impl_prio_neq_cur_l;eauto.\n  eapply R_PrioTbl_P_impl_prio_neq_cur; eauto.\n  apply nth_val'_imp_nth_val_int;auto.\n  unfolds; simpl; auto.\n  unfolds; simpl; auto.\n  split; auto.\n  pure_auto.\n  eapply RH_CurTCB_hold1; eauto.\n  eapply RH_TCBList_ECBList_P_hold1; eauto.\n  simpl; auto.\n\n\n  (**hoare forward**)\n\n  hoare forward.\n  instantiate (1:=  LV ticks @ Int16u |-> Vint32 i **\n                       A_dom_lenv ((ticks, Int16u) :: nil)).\n  sep auto.\n  eauto.\n  unfolds;simpl;auto.\n  simpl;auto.\n  sep auto.\n  sep cancel p_local.\n  simpl; auto.\n  sep auto.\n  sep cancel p_local.\n  simpl; auto.\n  unfold getasrt in H10.\n  unfold OS_SchedPost  in H10.\n  unfold OS_SchedPost' in H10.\n  sep auto.\n  inverts H25; auto.\n\n  (* if false  *)\n  lets Hst: low_stat_rdy_imp_high r r0 Hdly0;eauto.\n  subst.\n  hoare forward.\n  pauto.\n  hoare abscsq.\n  apply noabs_oslinv.\n  eapply OSTimeDly_high_level_step_2;eauto.\n  can_change_aop_solver.\n  unfold AECBList in *.\n  hoare forward prim.\n  unfold AECBList in *.\n  instantiate (1 := LV ticks @ Int16u |-> Vint32 i ** A_dom_lenv ((ticks, Int16u) :: nil)).\n  sep semiauto.\n  sep cancel evsllseg.\n  sep cancel Astruct.\n  sep cancel dllseg.\n  sep cancel dllseg.\n  sep lift 3%nat in H10.\n  sep lift 3%nat.\n  \n  eapply tcbdllflag_hold;eauto.\n  apply tcbdllflag_hold_middle.\n  simpl;auto.\n  rule_type_val_match_elim; simpl val_inj.\n  rewrite H32; simpl val_inj.\n  split.\n  eapply event_wait_rl_tbl_grp'';eauto.\n  rewrite H32 in H34.\n  rewrite len_lt_update_get_eq in H34.\n  clear -H34.\n  unfold val_inj in H34.\n  simpl in H34.\n  destruct ( Int.eq (x2&ᵢInt.not i1) ($ 0));tryfalse;auto.\n  destruct H34;tryfalse.\n  rewrite H31.\n  simpl Z.of_nat.\n  auto.\n  eapply idle_in_rtbl_hold;eauto.\n  \n  split.\n  apply array_type_vallist_match_hold; auto.\n  rewrite H31; simpl; auto.\n  apply Nat2Z.inj_lt.\n  clear -H30.\n  rewrite Z2Nat.id; int auto.\n\n  rewrite H32; simpl.\n  cut (Int.unsigned (x2&ᵢInt.not i1) <=? Byte.max_unsigned = true)%Z.\n  intros H100; rewrite H100; auto.\n  apply leb_bytemax_true_intro.\n  apply int_lemma1; auto.\n\n  rewrite update_nth_val_len_eq.\n  simpl; auto.\n  \n  eapply R_PrioTbl_P_hold1; eauto.\n\n  rewrite H32.\n  simpl.\n  eapply rtbl_remove_RL_RTbl_PrioTbl_P_hold with (prio:= p) ;eauto;\n  (funfold r; try rewrite Int.repr_unsigned; auto).\n  apply nth_val'_imp_nth_val_int;auto.\n  eapply ECBList_P_hold1;eauto.\n  instantiate (1 := (TcbMod.set v'21 (v'23, Int.zero)\n                                (p, wait os_stat_time i, m))).\n  rewrite H32; simpl val_inj.\n  \n  3:apply TcbMod.join_set_r; eauto;unfold TcbMod.indom;eauto.\n  eapply TCBList_P_tcb_dly_hold;eauto.\n  eapply TcbMod_join_impl_prio_neq_cur_r;eauto.\n\n  eapply R_PrioTbl_P_impl_prio_neq_cur; eauto.\n  funfold r; auto.\n  apply nth_val'_imp_nth_val_int;auto.\n  rewrite H32; simpl val_inj.\n  eapply TCBList_P_tcb_dly_hold';eauto;   \n  (funfold r; try rewrite Int.repr_unsigned; auto).\n  eapply TcbMod_join_impl_prio_neq_cur_l;eauto.\n  eapply R_PrioTbl_P_impl_prio_neq_cur; eauto.\n  apply nth_val'_imp_nth_val_int;auto.\n  unfolds; simpl; auto.\n\n  unfolds; simpl; auto.\n\n  split; auto.\n  pauto.\n  eapply RH_CurTCB_hold1; eauto.\n  eapply RH_TCBList_ECBList_P_hold1; eauto.\n  simpl; auto.\n\n  (*hoare forward*)\n  hoare forward.\n\n  instantiate (1:=  LV ticks @ Int16u |-> Vint32 i **\n           A_dom_lenv ((ticks, Int16u) :: nil)).\n  sep auto.\n  eauto.\n  unfolds;simpl;auto.\n  simpl;auto.\n  sep auto.\n  inverts H25.\n  sep cancel 1%nat 1%nat.\n  simpl ; auto.\n  unfold getasrt.\n  unfold OS_SchedPre.\n  unfold OS_SchedPre'.\n  sep auto.\n  sep cancel 1%nat 1%nat.\n  simpl; auto.\n   unfold getasrt in H10.\n  unfold OS_SchedPost in H10.\n  unfold OS_SchedPost' in H10.\n  sep auto.\n  inverts H25; auto.\n\n  pure intro.\n  assert (Int.eq i5 ($ OS_STAT_RDY)=false \\/ Int.eq i6 ($ 0) = false).\n  clear -H4.\n  unfold val_inj in H4;destruct (Int.eq i5 ($ OS_STAT_RDY));destruct (Int.eq i6 ($ 0));simpl in H4;tryfalse;auto.\n  assert (Int.ltu Int.zero Int.one && Int.ltu Int.zero Int.one = true).\n  unfolds.\n  \n  assert ( Int.ltu Int.zero Int.one = true).\n  clear;int auto.\n  rewrite H.\n  auto.\n  rewrite H in H4.\n  destruct H4;tryfalse.\n\n  assert (TCBList_P (Vptr (v'23, Int.zero))\n                    ((v'22\n                        :: v'18\n                        :: x7\n                        :: x6\n                        :: Vint32 i6\n                        :: Vint32 i5\n                        :: Vint32 i4\n                        :: Vint32 i3\n                        :: Vint32 i2\n                        :: Vint32 i1 :: Vint32 i0 :: nil) :: v'9)\n                    v'10 v'21) as X.\n  auto.\n  unfold1 TCBList_P in H10.\n  simpljoin.\n  unfold TCBNode_P in *.\n  destruct x2.\n  destruct p.\n  simpljoin.\n  lets Hx: low_stat_nordy_imp_high r0 H5.\n  \n  unfolds in j.\n  assert (TcbMod.get v'21 x = Some (p, t1, m)).\n  lets H100 : TcbMod.get_sig_some x (p, t1, m).\n  eapply TcbMod.join_get_get_l; eauto.\n  assert (TcbMod.get v'13 x = Some (p, t1, m)).\n  eapply TcbMod.join_get_get_r; eauto.\n\n  hoare abscsq.\n  apply noabs_oslinv.\n  eapply OSTimeDly_high_level_step_3;eauto.\n  inverts e.\n  eauto.\n  can_change_aop_solver.\n  instantiate (1:= <|| END None ||>  ** p_local OSLInv (v'23, Int.zero) init_lg **\n                           Aisr empisr **\n                           Aie true **\n                           Ais nil **\n                           Acs nil **\n                           LV ticks @ Int16u |-> Vint32 i ** A_dom_lenv ((ticks, Int16u) :: nil)).\n  hoare forward prim.\n\n  unfold AOSTCBList.\n  sep pauto;eauto.\n  unfold tcbdllseg.\n  unfold dllseg at 2;fold dllseg.\n  sep pauto.\n  unfold node.\n  sep pauto.\n  splits; pure_auto.\n  unfolds;simpl;auto.\n  unfolds;simpl;auto.\n  simpl;auto.\n  destruct H4.\n  sep auto.\n  sep auto.\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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\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": "brightfu", "repo": "CertiuCOS2", "sha": "1b7e588056a23bc32a9e442a240de3002b16eefb", "save_path": "github-repos/coq/brightfu-CertiuCOS2", "path": "github-repos/coq/brightfu-CertiuCOS2/CertiuCOS2-1b7e588056a23bc32a9e442a240de3002b16eefb/coqimp/certiucos/proofs/time/OSTimeDlyProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.27158017776866955}}
{"text": "Require compcert.common.Events.\n\nImport Coqlib.\nImport Values.\nImport Memory.\nImport Globalenvs.\nExport Events.\n\n(** [CompCertX:test-compcert-protect-stack] For CompCertX, we are\n going to instantiate CompCert with a non-trivial predicate for\n \"writable memory blocks\", ensuring that the stack locations of the\n caller are not \"writable\", and thus not overwritten by the compiled code.\n *)\n\nClass WritableBlockAllowGlobals\n      WB\n      `{wb_ops: WritableBlockOps WB} :=\n  {\n    writable_block_allow_globals:\n      forall {F V} (ge: Genv.t F V) i b,\n        Genv.find_symbol ge i = Some b ->\n        writable_block ge b\n  }.\n\nSection WITHMEM.\nContext `{memory_model_ops: Mem.MemoryModelOps}.\n\nLemma protect_inject:\n  forall (m_init: mem) f\n         (Hincr: inject_incr (Mem.flat_inj (Mem.nextblock m_init)) f)\n         (Hsep: inject_separated (Mem.flat_inj (Mem.nextblock m_init)) f m_init m_init)\n         b1 b2 o\n         (Hf: f b1 = Some (b2, o))\n         n\n         (Hn: Ple n (Mem.nextblock m_init))\n  ,\n        ((Ple n b1 /\\ Plt b1 (Mem.nextblock m_init)) <-> (Ple n b2 /\\ Plt b2 (Mem.nextblock m_init))).\nProof.\n  intros.\n  case_eq (Mem.flat_inj (Mem.nextblock m_init) b1).\n   intros ? Hinj.\n   generalize Hinj.\n   unfold Mem.flat_inj. destruct (plt b1 (Mem.nextblock m_init)); try discriminate.\n   injection 1; intros; subst.\n   apply Hincr in Hinj.\n   replace b2 with b1  in * by congruence.\n   tauto.\n  intro.\n  exploit Hsep; eauto.\n  unfold Mem.valid_block.\n  xomega.\nQed.\n\nDefinition writable_block\n           (m_init: mem)\n           (F V: Type)\n           (ge: Genv.t F V)\n           (b: block)\n: Prop\n  :=\n    ~ (Ple (Genv.genv_next ge) b /\\ Plt b (Mem.nextblock m_init)).\nGlobal Arguments writable_block _ [_ _] _ _.\n\nTheorem global_writable_block:\n  forall m_init\n         (F V: Type)\n         (ge: Genv.t F V)\n         i b,\n    Genv.find_symbol ge i = Some b ->\n    writable_block m_init ge b.\nProof.\n  intros.\n  exploit Genv.genv_symb_range; eauto.\n  unfold writable_block. xomega.\nQed.\n\nTheorem callee_writable_block:\n  forall m_init b,\n    ~ Mem.valid_block m_init b ->\n    forall (F V: Type)\n           (ge: Genv.t F V),\n      writable_block m_init ge b.\nProof.\n  unfold Mem.valid_block, writable_block.\n  intros. xomega.\nQed.\n\nTheorem writable_block_genv_next:\n  forall m_init \n         (F1 V1 F2 V2: Type) (ge1: Genv.t F1 V1) (ge2: Genv.t F2 V2)\n         (Hnext: Genv.genv_next ge2 = Genv.genv_next ge1)\n         b,\n    writable_block m_init ge2 b = writable_block m_init ge1 b.\nProof.\n  unfold writable_block. intros. congruence.\nQed.\n\nTheorem writable_block_inject:\n  forall m_init\n         (F V: Type)\n         (ge: Genv.t F V)\n         (Hn: Ple (Genv.genv_next ge) (Mem.nextblock m_init))\n         f\n         (Hincr: inject_incr (Mem.flat_inj (Mem.nextblock m_init)) f)\n         (Hsep: inject_separated (Mem.flat_inj (Mem.nextblock m_init)) f m_init m_init)\n         b1 b2 o\n         (Hf: f b1 = Some (b2, o))\n  ,\n  writable_block m_init ge b1 -> writable_block m_init ge b2.\nProof.\n  unfold writable_block. intros.\n  rewrite <- protect_inject; eauto.\nQed.\n\nGlobal Instance writable_block_with_init_mem_ops:\n  WritableBlockWithInitMemOps writable_block.\nProof.\n  constructor.\n  intro. constructor.\nDefined.\n\nGlobal Instance writable_block_with_init_mem:\n  WritableBlockWithInitMem writable_block.\nProof.\n  constructor.\n  intro. constructor.\n   unfold Events.writable_block, writable_block_with_init_mem, writable_block.\n   congruence.\n  unfold writable_block_with_init_mem, writable_block.\n  intros; eapply writable_block_inject; eauto.\nQed.  \n\nGlobal Instance writable_block_ops\n       (m: mem):\n  WritableBlockOps (writable_block m).\nProof.\n  eauto using writable_block_with_init_mem_writable_block_ops.\nDefined.\n\nGlobal Instance Hwritable_block\n       (m: mem):\n  WritableBlock (writable_block m).\nProof.\n  typeclasses eauto.\nQed.\n\nGlobal Instance Hwritable_block_allow_globals\n       (m: mem):\n  WritableBlockAllowGlobals (writable_block m).\nProof.\n  constructor. \n  apply global_writable_block.\nQed.\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/compcertx/common/EventsX.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.27157998280467}}
{"text": "(* Functional implementation of Salsa20 whose\n   structure matches the one of tweetnacl.c implementation,\n   plus proof of coorrectness wrt Salsa20.v\n\n   Lennart Beringer, June 2015*)\n(*Processing time for this file: approx 13mins*)\nRequire Import VST.floyd.proofauto.\nLocal Open Scope logic.\nRequire Import List. Import ListNotations.\n(*Require Import general_lemmas.\n\nRequire Import split_array_lemmas.*)\nRequire Import ZArith.\nLocal Open Scope Z.\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_loop1.\nRequire Import tweetnacl20140427.verif_fcore_loop2.\nRequire Import tweetnacl20140427.verif_fcore_loop3.\n\nRequire Import tweetnacl20140427.verif_fcore_epilogue_htrue.\nRequire Import tweetnacl20140427.verif_fcore_epilogue_hfalse.\n\nOpaque littleendian_invert. Opaque Snuffle.Snuffle.\n\nLemma HFalse_inv16_char: forall l xs ys,\n  HFalse_inv l 16 xs ys ->\n  Zlength xs = 16 -> Zlength ys=16 ->\n  exists sum, Some sum = sumlist xs ys /\\\n  l = QuadChunks2ValList (map littleendian_invert sum).\nProof. intros. destruct H.\n destruct (listGE16 l) as\n  [v0 [v1 [v2 [v3 [v4 [v5 [v6 [v7 [v8 [v9 [v10 [v11 [v12 [v13 [v14 [v15 [t1 [T1 L1]]]]]]]]]]]]]]]]]]. lia.\n rewrite H in L1; simpl in L1.\n destruct (listGE16 t1) as\n  [v16 [v17 [v18 [v19 [v20 [v21 [v22 [v23 [v24 [v25 [v26 [v27 [v28 [v29 [v30 [v31 [t2 [T2 L2]]]]]]]]]]]]]]]]]]. lia.\n rewrite L1 in L2; simpl in L2.\n destruct (listGE16 t2) as\n  [v32 [v33 [v34 [v35 [v36 [v37 [v38 [v39 [v40 [v41 [v42 [v43 [v44 [v45 [v46 [v47 [t3 [T3 L3]]]]]]]]]]]]]]]]]]. lia.\n rewrite L2 in L3; simpl in L3.\n destruct (listGE16 t3) as\n  [v48 [v49 [v50 [v51 [v52 [v53 [v54 [v55 [v56 [v57 [v58 [v59 [v60 [v61 [v62 [v63 [t4 [T4 L4]]]]]]]]]]]]]]]]]]. lia.\n rewrite L3 in L4; simpl in L4.\n apply Zlength_nil_inv in L4. subst t3 t4 t2 t1. clear L1 L2 L3 H. simpl in T1.\n destruct (listD16 _ H0) as\n  [x0 [x1 [x2 [x3 [x4 [x5 [x6 [x7 [x8 [x9 [x10 [x11 [x12 [x13 [x14 [x15 A1]]]]]]]]]]]]]]]].\n destruct (listD16 _ H1) as\n  [y0 [y1 [y2 [y3 [y4 [y5 [y6 [y7 [y8 [y9 [y10 [y11 [y12 [y13 [y14 [y15 B1]]]]]]]]]]]]]]]].\nsubst l xs ys.\neexists; split. reflexivity.\nunfold Znth in H2. simpl.\ndestruct (H2 0) as [x [X [y [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y. rewrite <- Q; clear Q.\ndestruct (H2 1) as [x [X [y [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y. rewrite <- Q; clear Q.\ndestruct (H2 2) as [x [X [y [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y. rewrite <- Q; clear Q.\ndestruct (H2 3) as [x [X [y [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y. rewrite <- Q; clear Q.\ndestruct (H2 4) as [x [X [y [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y. rewrite <- Q; clear Q.\ndestruct (H2 5) as [x [X [y [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y. rewrite <- Q; clear Q.\ndestruct (H2 6) as [x [X [y [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y. rewrite <- Q; clear Q.\ndestruct (H2 7) as [x [X [y [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y. rewrite <- Q; clear Q.\ndestruct (H2 8) as [x [X [y [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y. rewrite <- Q; clear Q.\ndestruct (H2 9) as [x [X [y [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y. rewrite <- Q; clear Q.\ndestruct (H2 10) as [x [X [y [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y. rewrite <- Q; clear Q.\ndestruct (H2 11) as [x [X [y [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y. rewrite <- Q; clear Q.\ndestruct (H2 12) as [x [X [y [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y. rewrite <- Q; clear Q.\ndestruct (H2 13) as [x [X [y [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y. rewrite <- Q; clear Q.\ndestruct (H2 14) as [x [X [y [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y. rewrite <- Q; clear Q.\ndestruct (H2 15) as [x [X [y [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y. rewrite <- Q; clear Q.\nreflexivity.\nQed.\n\nLemma TP C1 C2 C3 C4 N1 N2 N3 N4 intsums OUT: Zlength intsums = 16 -> Zlength OUT = 32 ->\n  hPosLoop3 4 (hPosLoop2 4 intsums (C1, C2, C3, C4) (N1, N2, N3, N4)) OUT =\n QuadByte2ValList (littleendian_invert (Int.sub (Znth 0 intsums)  (littleendian C1))) ++\n QuadByte2ValList (littleendian_invert (Int.sub (Znth 5 intsums)  (littleendian C2))) ++\n QuadByte2ValList (littleendian_invert (Int.sub (Znth 10 intsums) (littleendian C3))) ++\n QuadByte2ValList (littleendian_invert (Int.sub (Znth 15 intsums) (littleendian C4))) ++\n QuadByte2ValList (littleendian_invert (Int.sub (Znth 6 intsums)  (littleendian N1))) ++\n QuadByte2ValList (littleendian_invert (Int.sub (Znth 7 intsums)  (littleendian N2))) ++\n QuadByte2ValList (littleendian_invert (Int.sub (Znth 8 intsums)  (littleendian N3))) ++\n QuadByte2ValList (littleendian_invert (Int.sub (Znth 9 intsums)  (littleendian N4))).\nProof. intros.\nrewrite Zlength_length in H, H0. simpl in H, H0.\ndestruct intsums; simpl in H. lia. rename i into v0.\ndestruct intsums; simpl in H. lia. rename i into v1.\ndestruct intsums; simpl in H. lia. rename i into v2.\ndestruct intsums; simpl in H. lia. rename i into v3.\ndestruct intsums; simpl in H. lia. rename i into v4.\ndestruct intsums; simpl in H. lia. rename i into v5.\ndestruct intsums; simpl in H. lia. rename i into v6.\ndestruct intsums; simpl in H. lia. rename i into v7.\ndestruct intsums; simpl in H. lia. rename i into v8.\ndestruct intsums; simpl in H. lia. rename i into v9.\ndestruct intsums; simpl in H. lia. rename i into v10.\ndestruct intsums; simpl in H. lia. rename i into v11.\ndestruct intsums; simpl in H. lia. rename i into v12.\ndestruct intsums; simpl in H. lia. rename i into v13.\ndestruct intsums; simpl in H. lia. rename i into v14.\ndestruct intsums; simpl in H. lia. rename i into v15.\ndestruct intsums; simpl in H. 2: lia. clear H. simpl.\nunfold Znth. simpl.\ndestruct OUT; simpl in H0. lia. rename v into u0.\ndestruct OUT; simpl in H0. lia. rename v into u1.\ndestruct OUT; simpl in H0. lia. rename v into u2.\ndestruct OUT; simpl in H0. lia. rename v into u3.\ndestruct OUT; simpl in H0. lia. rename v into u4.\ndestruct OUT; simpl in H0. lia. rename v into u5.\ndestruct OUT; simpl in H0. lia. rename v into u6.\ndestruct OUT; simpl in H0. lia. rename v into u7.\ndestruct OUT; simpl in H0. lia. rename v into u8.\ndestruct OUT; simpl in H0. lia. rename v into u9.\ndestruct OUT; simpl in H0. lia. rename v into u10.\ndestruct OUT; simpl in H0. lia. rename v into u11.\ndestruct OUT; simpl in H0. lia. rename v into u12.\ndestruct OUT; simpl in H0. lia. rename v into u13.\ndestruct OUT; simpl in H0. lia. rename v into u14.\ndestruct OUT; simpl in H0. lia. rename v into u15.\ndestruct OUT; simpl in H0. lia. rename v into u16.\ndestruct OUT; simpl in H0. lia. rename v into u17.\ndestruct OUT; simpl in H0. lia. rename v into u18.\ndestruct OUT; simpl in H0. lia. rename v into u19.\ndestruct OUT; simpl in H0. lia. rename v into u20.\ndestruct OUT; simpl in H0. lia. rename v into u21.\ndestruct OUT; simpl in H0. lia. rename v into u22.\ndestruct OUT; simpl in H0. lia. rename v into u23.\ndestruct OUT; simpl in H0. lia. rename v into u24.\ndestruct OUT; simpl in H0. lia. rename v into u25.\ndestruct OUT; simpl in H0. lia. rename v into u26.\ndestruct OUT; simpl in H0. lia. rename v into u27.\ndestruct OUT; simpl in H0. lia. rename v into u28.\ndestruct OUT; simpl in H0. lia. rename v into u29.\ndestruct OUT; simpl in H0. lia. rename v into u30.\ndestruct OUT; simpl in H0. lia. rename v into u31.\ndestruct OUT; simpl in H0. 2: lia. clear H0. simpl. reflexivity. lia. lia.\nQed.\n\nDefinition HTrue_inv intsums xs ys:Prop:=\nZlength intsums = 16 /\\\n        (forall j, 0 <= j < 16 ->\n           exists xj, exists yj,\n           Znth j (map Vint xs) = Vint xj /\\\n           Znth j (map Vint ys) = Vint yj /\\\n           Znth j (map Vint intsums) = Vint (Int.add yj xj)).\n\nLemma HTrue_inv_char l xs ys: Zlength xs = 16 -> Zlength ys=16 ->\n      HTrue_inv l xs ys -> Some l = sumlist xs ys.\nProof. rewrite sumlist_symm. intros LX LY [H L].\n destruct (listD16 _ LX) as\n  [x0 [x1 [x2 [x3 [x4 [x5 [x6 [x7 [x8 [x9 [x10 [x11 [x12 [x13 [x14 [x15 A1]]]]]]]]]]]]]]]].\n destruct (listD16 _ LY) as\n  [y0 [y1 [y2 [y3 [y4 [y5 [y6 [y7 [y8 [y9 [y10 [y11 [y12 [y13 [y14 [y15 B1]]]]]]]]]]]]]]]].\n destruct (listD16 _ H) as\n  [z0 [z1 [z2 [z3 [z4 [z5 [z6 [z7 [z8 [z9 [z10 [z11 [z12 [z13 [z14 [z15 C1]]]]]]]]]]]]]]]].\nsubst xs ys l.\nunfold Znth in L.\ndestruct (L 0) as [x [y [X [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y; inv Q.\ndestruct (L 1) as [x [y [X [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y; inv Q.\ndestruct (L 2) as [x [y [X [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y; inv Q.\ndestruct (L 3) as [x [y [X [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y; inv Q.\ndestruct (L 4) as [x [y [X [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y; inv Q.\ndestruct (L 5) as [x [y [X [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y; inv Q.\ndestruct (L 6) as [x [y [X [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y; inv Q.\ndestruct (L 7) as [x [y [X [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y; inv Q.\ndestruct (L 8) as [x [y [X [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y; inv Q.\ndestruct (L 9) as [x [y [X [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y; inv Q.\ndestruct (L 10) as [x [y [X [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y; inv Q.\ndestruct (L 11) as [x [y [X [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y; inv Q.\ndestruct (L 12) as [x [y [X [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y; inv Q.\ndestruct (L 13) as [x [y [X [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y; inv Q.\ndestruct (L 14) as [x [y [X [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y; inv Q.\ndestruct (L 15) as [x [y [X [Y Q]]]]; try lia.\nsimpl in X, Y, Q. symmetry in X, Y; inv X; inv Y; inv Q. reflexivity.\nQed.\n\nDefinition fcore_EpiloguePOST t y x w nonce out c k h OUT\n  (data : SixteenByte * SixteenByte * (SixteenByte * SixteenByte)) :=\nmatch data with ((Nonce, C), K) =>\nEX xs:_, EX ys:_,\nPROP (ys = prepare_data data /\\ Snuffle 20 ys = Some xs)\nLOCAL (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 (CoreInSEP data (nonce, c, k);\n       data_at Tsh (tarray tuint 16) (map Vint ys) y;\n       data_at_ Tsh (tarray tuint 4) t; data_at_ Tsh (tarray tuint 16) w;\n       if Int.eq (Int.repr h) Int.zero\n         then EX l:_,\n          !!HFalse_inv l 16 xs ys &&\n          (data_at Tsh (tarray tuchar 64) l out *\n           data_at Tsh (tarray tuint 16) (map Vint xs) x)\n         else EX intsums:_, !!(HTrue_inv intsums xs ys) &&\n            (data_at Tsh (tarray tuchar 32)\n               (hPosLoop3 4 (hPosLoop2 4 intsums C Nonce) OUT) out\n             * data_at Tsh (tarray tuint 16)\n                 (map Vint (hPosLoop2 4 intsums C Nonce)) x))\nend. \n\nOpaque Snuffle. Opaque hPosLoop2. Opaque hPosLoop3. \n\nLemma HTruePOST F t y x w nonce out c k h snuffleRes l data OUT:\n      Snuffle 20 l = Some snuffleRes ->\n      Int.eq (Int.repr h) Int.zero = false ->\n      l = prepare_data data ->\n      F |-- (data_at_ Tsh (tarray tuint 4) t * data_at_ Tsh (tarray tuint 16) w)%logic ->\n      HTruePostCond F t y x w nonce out c k h snuffleRes l data OUT\n|-- fcore_EpiloguePOST t y x w nonce out c k h OUT data.\nProof. intros.\nunfold HTruePostCond, fcore_EpiloguePOST.\ndestruct data as [[? ?] [? ?]].\nExists snuffleRes l.\nrewrite H0, <- H1, H. clear - H2.\nTime normalize. (*1.4*)\n Exists intsums.\n go_lowerx. (* must do this explicitly because it's not an ENTAIL *)\n Time entailer!; auto. (*6.8*)\nQed.\n\nLemma HFalsePOST F t y x w nonce out c k h snuffleRes l data OUT:\n      Snuffle 20 l = Some snuffleRes ->\n      Int.eq (Int.repr h) Int.zero = true ->\n      l = prepare_data data ->\n      F |-- ((CoreInSEP data (nonce, c,k) * data_at_ Tsh (tarray tuint 4) t *\n             data_at_ Tsh (tarray tuint 16) w))%logic ->\n      HFalsePostCond F t y x w nonce out c k h snuffleRes l\n     |-- fcore_EpiloguePOST t y x w nonce out c k h OUT data.\nProof. intros.\nunfold HFalsePostCond, fcore_EpiloguePOST.\ndestruct data as [[? ?] [? ?]].\nExists snuffleRes l.\nrewrite H0, <- H1, H. clear - H2.\ngo_lowerx. (* must do this explicitly because it's not an ENTAIL *)\nTime entailer!. (*3.4*)\nIntros intsums. Exists intsums; entailer!. apply H2.\nQed.\n\nOpaque HTruePostCond. Opaque HFalsePostCond.\n\nLemma core_spec_ok: semax_body SalsaVarSpecs SalsaFunSpecs\n       f_core core_spec.\nProof. unfold core_spec, f_core_POST.\nstart_function. abbreviate_semax.\nrename v_t into t.\nrename v_y into y.\nrename v_x into x.\nrename v_w into w.\nfreeze [0;1;2;3;4] FR1.\nTime assert_PROP (Zlength OUT = Z.max 0 (OutLen h)) as ZL_OUT by entailer!.\nrewrite Z.max_r in ZL_OUT.\n2:{ unfold OutLen. simple_if_tac; lia. }\n(* apply semax_seq with (Q:=fcore_EpiloguePOST t y x w nonce out c k h OUT data). *)\nthaw FR1. freeze [0;1;3;5] FR2.\neapply semax_seq.\napply (f_core_loop1 Espec (FRZL FR2) c k h nonce out w x y t data); trivial.\n(*/FOR(i,16) y[i] = x[i]*)\nIntros xInit. red in H. rename H into XInit.\nthaw FR2. freeze [0;2;3;5] FR3.\nsubst MORE_COMMANDS; unfold abbreviate.\neapply semax_seq.\napply (f_core_loop2 _ (FRZL FR3) c k h nonce out w x y t data); trivial.\n    (* mkConciseDelta SalsaVarSpecs SalsaFunSpecs f_core Delta.*)\n\n    Intros YS.\n    destruct H as [? [? [? [? [? [? [? [? ?]]]]]]]].\n    assert (L31: Zlength (x3 ++ x1) = 16) by (rewrite H1; reflexivity).\n    rewrite Zlength_app, H3 in L31. destruct x1. 2:{ rewrite Zlength_cons', Z.add_assoc in L31. specialize (Zlength_nonneg x1); intros; lia. }\n    rewrite app_nil_r in *. clear L31; subst x0. clear H3 H1 x3.\n    assert (LX: Zlength xInit = 16).\n      rewrite XInit. rewrite upd_upto_Zlength; trivial. simpl; lia.\n    rewrite <- H0, Zlength_app, H2 in LX. destruct x2. 2:{ rewrite Zlength_cons', Z.add_assoc in LX. specialize (Zlength_nonneg x2); intros; lia. }\n    rewrite app_nil_r in *. clear LX; subst YS. rename H2 into xInit_Zlength.\n\n    rewrite upd_upto_char in XInit. 2: reflexivity.\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\n    thaw FR3. subst xInit.\n    freeze [2;3;5] FR4.\n    remember [C1; K1; K2; K3; K4; C2; N1; N2; N3; N4; C3; L1; L2; L3; L4; C4] as xInit.\n    forward_seq.\n    eapply semax_post_flipped'.\n    apply (f_core_loop3 _ (FRZL FR4) c k h nonce out w x y t (map littleendian xInit)).\n    intros. apply andp_left2. apply derives_refl.\n    Intros snuffleRes. rename H into RES.\n\n    freeze [0;1;2;3] FR5.\n    Time forward_if (fcore_EpiloguePOST t y x w nonce out c k h OUT\n               ((N1, N2, N3, N4), (C1, C2, C3, C4), ((K1, K2, K3, K4), (L1, L2, L3, L4)))). (*4.8*)\n    - (*apply typed_true_tint_Vint in H.*)\n      assert (HOUTLEN: OutLen h = 32). unfold OutLen. rewrite Int.eq_false; trivial.\n      thaw FR5. thaw FR4. rewrite HOUTLEN in *. freeze [3;4] FR6.\n      force_sequential.\n      eapply semax_post_flipped'.\n      eapply (verif_fcore_epilogue_htrue Espec (FRZL FR6) t y x w nonce out c k h\n                     OUT snuffleRes (map littleendian xInit)\n                     (((N1, N2, N3, N4), (C1, C2, C3, C4)), (K1, K2, K3, K4, (L1, L2, L3, L4)))).\n        apply andp_left2.\n        apply HTruePOST; trivial. rewrite Int.eq_false; trivial.\n        subst xInit; reflexivity.\n        thaw FR6. cancel.\n    - (*unfold typed_false in H. simpl in H. inversion H. apply negb_false_iff in H1. clear H.*)\n      assert (HOUTLEN: OutLen h = 64). unfold OutLen; rewrite H; trivial.\n      thaw FR5. thaw FR4. rewrite HOUTLEN in *. freeze [1;3;4] FR6.\n      drop_LOCAL 0%nat.\n      eapply semax_post_flipped'.\n      apply (verif_fcore_epilogue_hfalse Espec (FRZL FR6)\n            t y x w nonce out c k h OUT).\n      apply andp_left2.\n        apply HFalsePOST; trivial. rewrite H. trivial. subst; trivial.\n        thaw FR6. cancel.\n- \n   clear - ZL_OUT. clearbody Delta_specs.\n   set (data :=(N1, N2, N3, N4, (C1, C2, C3, C4),\n  (K1, K2, K3, K4, (L1, L2, L3, L4)))).\n  change (N1, N2, N3, N4, (C1, C2, C3, C4),\n             (K1, K2, K3, K4, (L1, L2, L3, L4))) with data.\n   destruct data as [[Nonce C] [Key1 Key2]].\n   unfold fcore_EpiloguePOST.\n    Intros snuffleRes ys. subst ys.\n    destruct (Int.eq (Int.repr h) Int.zero) eqn:hh.\n + Intros l. Exists l. rename H into H99. entailer!.\n    rewrite Zlength_map in H1.\n    specialize (Snuffle_length _ _ _  H0 (prepare_data_length _ )); intros L.\n    unfold fcore_result.\n    unfold Snuffle20, bind. rewrite H0; clear H0.\n        destruct (HFalse_inv16_char _ _ _ H99) as [sums [SUMS1 SUMS2]].\n          rewrite Zlength_correct, L; reflexivity. trivial.\n        rewrite <- SUMS1, <- SUMS2. rewrite hh. auto.\n        unfold fcorePOST_SEP, OutLen.  \n        rewrite hh. auto.\n  +  Intros intsums.   unfold fcorePOST_SEP.\n      Exists (hPosLoop3 4 (hPosLoop2 4 intsums C Nonce) OUT).\n      rename H into H99. entailer!.    unfold fcore_result.\n    unfold Snuffle20, bind. rewrite H0.\n      apply HTrue_inv_char in H99. rewrite <- H99.\n      rewrite hh.\n    rewrite Zlength_map in H1.\n    specialize (Snuffle_length _ _ _  H0 (prepare_data_length _ )); intros L.\n      destruct Nonce as [[[? ?] ?] ?]. destruct C as [[[? ?] ?] ?].\n     auto.\n      rewrite <- TP with (OUT:=OUT).\n      unfold fcorePOST_SEP, OutLen. auto.\n       rewrite Zlength_correct, (sumlist_length _ _ _ H99), prepare_data_length; trivial.\n        rewrite ZL_OUT. unfold OutLen; rewrite hh. trivial.\n    specialize (Snuffle_length _ _ _  H0 (prepare_data_length _ )); intros L.\n        rewrite Zlength_correct, L; reflexivity.\n        rewrite Zlength_correct, prepare_data_length; reflexivity.\n     unfold OutLen. rewrite hh. auto.\nTime Qed. (*20 versus 58*)", "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.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.27154355007283354}}
{"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(* Revised December 2002 *)\n\n(****************************************************************************)\n(*                                                                          *)\n(*                                                                          *)\n(*  Z_to_Q.v                                                                *)\n(*                                                                          *)\n(*  Details of the coercion between integers and rationals                  *)\n(*                                                                          *)\n(*                                                                          *)\n(*  Samuel Boutin                                                           *)\n(*  Coq V5.10                                                               *)\n(*  June  1995                                                              *)\n(*                                                                          *)\n(*                                                                          *)\n(****************************************************************************)\n(*                              Z_to_Q.v                                    *)\n(****************************************************************************)\n\nRequire Import quotient.\nRequire Import subset.\nRequire Import HS.\nRequire Import AC.\nRequire Import intnumbers.\nRequire Import rational_defs.\n\nSection Integers_are_Rationals.\n\nRequire Import productSyntax.\n\nOpen Scope INT_scope.\n\nLemma one_is_a_denominator : 1 <= 1.\n\nred in |- *; simpl in |- *.\nrewrite (Reduce_prop Z_typ Z_rel).\nred in |- *; simpl in |- *.\nrewrite (Reduce_prop Z_typ Z_rel).\nred in |- *; simpl in |- *.\napply le_n; auto.\nQed.\n\nDefinition fromZ_to_Q (x : Z) : Q := |(x, %+ (1) one_is_a_denominator) |q.\n\n\nEnd Integers_are_Rationals.\n(*\nGrammar rational final :=\n[ \"{\" integer:expr($c) \"}\" ] -> [<<(fromZ_to_Q $c)>>].\n*)\n", "meta": {"author": "coq-contribs", "repo": "rational", "sha": "9738e3672b597c485001257baee9cfaf1419948d", "save_path": "github-repos/coq/coq-contribs-rational", "path": "github-repos/coq/coq-contribs-rational/rational-9738e3672b597c485001257baee9cfaf1419948d/Rational/Z_to_Q.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.27148777043861516}}
{"text": "\nRequire Import Infrastructure.\nRequire Import SourceProperty.\nRequire Import LR.\nRequire Import Compatibility.\n\n\n(* BEGIN_FUNDAMENTAL *)\nTheorem fundamental_prop:  forall Δ Γ E A e e' dir,\n    has_type Δ Γ E dir A e ->\n    has_type Δ Γ E dir A e' ->\n    E_open Δ Γ e e' A A.\nProof with eauto using swft_wft, swfe_wfe, elaboration_well_type, subtype_well_type, swft_from_swfe, swfe_notin.\n  introv Ty1. gen e'.\n  induction Ty1; introv Ty2.\n\n  - Case \"top\".\n\n    apply top_compatibility...\n  - Case \"lit\".\n    inverts Ty2.\n    apply lit_compatibility...\n\n  - Case \"var\".\n    inverts Ty2.\n    apply var_compatibility...\n\n  - Case \"app\".\n    inverts Ty2 as.\n    introv Ty1 Ty2.\n    lets H: inference_unique Ty1_1 Ty1.\n    inverts H.\n    forwards : IHTy1_1...\n    forwards : IHTy1_2...\n    eapply app_compatibility...\n\n  - Case \"merge\".\n    inverts Ty2 as Ty1 Ty2 ?.\n    forwards : IHTy1_1 Ty1.\n    forwards : IHTy1_2 Ty2.\n    eapply pair_compatibility...\n\n  - Case \"anno\".\n    inverts Ty2.\n    eapply IHTy1...\n\n  - Case \"tabs\".\n    inverts Ty2.\n    pick_fresh X.\n    eapply tabs_compatibility...\n    forwards : H0...\n    assert (Wfte : swfte ([(X, A)] ++ DD))...\n    inverts Wfte...\n\n  - Case \"tapp\".\n    inverts Ty2.\n    forwards Eq : inference_unique Ty1 H5.\n    inverts Eq.\n    forwards : IHTy1...\n    eapply tapp_compatibility...\n\n  - Case \"rcd\".\n    inverts Ty2.\n    forwards : IHTy1...\n    apply record_compatibility...\n\n  - Case \"proj\".\n    inverts Ty2.\n    forwards : IHTy1...\n    apply record_compatibility in H...\n\n  - Case \"abs\".\n    inverts Ty2.\n    pick_fresh x.\n    forwards Imp : H8 x...\n    forwards Imp2 : H1 Imp...\n    eapply abs_compatibility...\n    eapply uniq_from_swfte...\n    inverts H2.\n\n  - Case \"capp\".\n    inverts Ty2.\n    inverts Ty1.\n    lets : inference_unique Ty1 H1.\n    substs.\n    forwards : IHTy1 H1.\n    eapply coercion_compatibility1...\n    eapply coercion_compatibility2...\nQed.\n\n\n(* ********************************************************************** *)\n(** * Expression contexts *)\n\n(* Context replacement is not substitution, ott has difficulity generating correct definition *)\n\nInductive CTyp : CC -> stctx -> sctx -> dirflag -> sty -> stctx -> sctx -> dirflag -> sty -> cc -> Prop :=    (* defn CTyp *)\n | CTyp_empty1 : forall (DD:stctx) (GG:sctx) (A:sty),\n     lc_sty A ->\n     CTyp C_Empty DD GG Inf A DD GG Inf A cc_empty\n | CTyp_empty2 : forall (DD:stctx) (GG:sctx) (A:sty),\n     lc_sty A ->\n     CTyp C_Empty DD GG Chk A DD GG Chk A cc_empty\n | CTyp_appL1 : forall (CC5:CC) (ee2:sexp) (DD:stctx) (GG:sctx) (A:sty) (DD':stctx) (GG':sctx) (A2:sty) (cc5:cc) (e:exp) (A1:sty),\n     CTyp CC5 DD GG Inf A DD' GG' Inf (sty_arrow A1 A2) cc5 ->\n     has_type DD' GG' ee2 Chk A1 e ->\n     CTyp (C_AppL CC5 ee2) DD GG Inf A DD' GG' Inf A2 (cc_appL cc5 e)\n | CTyp_appL2 : forall (CC5:CC) (ee2:sexp) (DD:stctx) (GG:sctx) (A:sty) (DD':stctx) (GG':sctx) (A2:sty) (cc5:cc) (e:exp) (A1:sty),\n     CTyp CC5 DD GG Chk A DD' GG' Inf (sty_arrow A1 A2) cc5 ->\n     has_type DD' GG' ee2 Chk A1 e ->\n     CTyp (C_AppL CC5 ee2) DD GG Chk A DD' GG' Inf A2 (cc_appL cc5 e)\n | CTyp_appR1 : forall (ee1:sexp) (CC5:CC) (DD:stctx) (GG:sctx) (A:sty) (DD':stctx) (GG':sctx) (A2:sty) (e:exp) (cc5:cc) (A1:sty),\n     CTyp CC5 DD GG Inf A DD' GG' Chk A1 cc5 ->\n     has_type DD' GG' ee1 Inf (sty_arrow A1 A2) e ->\n     CTyp (C_AppRd ee1 CC5) DD GG Inf A DD' GG' Inf A2 (cc_appR e cc5)\n | CTyp_appR2 : forall (ee1:sexp) (CC5:CC) (DD:stctx) (GG:sctx) (A:sty) (DD':stctx) (GG':sctx) (A2:sty) (e:exp) (cc5:cc) (A1:sty),\n     CTyp CC5 DD GG Chk A DD' GG' Chk A1 cc5 ->\n     has_type DD' GG' ee1 Inf (sty_arrow A1 A2) e ->\n     CTyp (C_AppRd ee1 CC5) DD GG Chk A DD' GG' Inf A2 (cc_appR e cc5)\n | CTyp_mergeL1 : forall (CC5:CC) (ee2:sexp) (DD:stctx) (GG:sctx) (A:sty) (DD':stctx) (GG':sctx) (A1 A2:sty) (cc5:cc) (e:exp),\n     CTyp CC5 DD GG Inf A DD' GG' Inf A1 cc5 ->\n     has_type DD' GG' ee2 Inf A2 e ->\n     disjoint DD' A1 A2 ->\n     CTyp (C_MergeL CC5 ee2) DD GG Inf A DD' GG' Inf (sty_and A1 A2) (cc_pairL cc5 e)\n | CTyp_mergeL2 : forall (CC5:CC) (ee2:sexp) (DD:stctx) (GG:sctx) (A:sty) (DD':stctx) (GG':sctx) (A1 A2:sty) (cc5:cc) (e:exp),\n     CTyp CC5 DD GG Chk A DD' GG' Inf A1 cc5 ->\n     has_type DD' GG' ee2 Inf A2 e ->\n     disjoint DD' A1 A2 ->\n     CTyp (C_MergeL CC5 ee2) DD GG Chk A DD' GG' Inf (sty_and A1 A2) (cc_pairL cc5 e)\n | CTyp_mergeR1 : forall (ee1:sexp) (CC5:CC) (DD:stctx) (GG:sctx) (A:sty) (DD':stctx) (GG':sctx) (A1 A2:sty) (e:exp) (cc5:cc),\n     CTyp CC5 DD GG Inf A DD' GG' Inf A2 cc5 ->\n     has_type DD' GG' ee1 Inf A1 e ->\n     disjoint DD' A1 A2 ->\n     CTyp (C_MergeR ee1 CC5) DD GG Inf A DD' GG' Inf (sty_and A1 A2) (cc_pairR e cc5)\n | CTyp_mergeR2 : forall (ee1:sexp) (CC5:CC) (DD:stctx) (GG:sctx) (A:sty) (DD':stctx) (GG':sctx) (A1 A2:sty) (e:exp) (cc5:cc),\n     CTyp CC5 DD GG Chk A DD' GG' Inf A2 cc5 ->\n     has_type DD' GG' ee1 Inf A1 e ->\n     disjoint DD' A1 A2 ->\n     CTyp (C_MergeR ee1 CC5) DD GG Chk A DD' GG' Inf (sty_and A1 A2) (cc_pairR e cc5)\n | CTyp_rcd1 : forall (l:i) (CC5:CC) (DD:stctx) (GG:sctx) (A:sty) (DD':stctx) (GG':sctx) (B:sty) (cc5:cc),\n     CTyp CC5 DD GG Inf A DD' GG' Inf B cc5 ->\n     CTyp (C_Rcd l CC5) DD GG Inf A DD' GG' Inf (sty_rcd l B) cc5\n | CTyp_rcd2 : forall (l:i) (CC5:CC) (DD:stctx) (GG:sctx) (A:sty) (DD':stctx) (GG':sctx) (B:sty) (cc5:cc),\n     CTyp CC5 DD GG Chk A DD' GG' Inf B cc5 ->\n     CTyp (C_Rcd l CC5) DD GG Chk A DD' GG' Inf (sty_rcd l B) cc5\n | CTyp_proj1 : forall (CC5:CC) (l:i) (DD:stctx) (GG:sctx) (A:sty) (DD':stctx) (GG':sctx) (B:sty) (cc5:cc),\n     CTyp CC5 DD GG Inf A DD' GG' Inf (sty_rcd l B) cc5 ->\n     CTyp (C_Proj CC5 l) DD GG Inf A DD' GG' Inf B cc5\n | CTyp_proj2 : forall (CC5:CC) (l:i) (DD:stctx) (GG:sctx) (A:sty) (DD':stctx) (GG':sctx) (B:sty) (cc5:cc),\n     CTyp CC5 DD GG Chk A DD' GG' Inf (sty_rcd l B) cc5 ->\n     CTyp (C_Proj CC5 l) DD GG Chk A DD' GG' Inf B cc5\n | CTyp_anno1 : forall (CC5:CC) (A:sty) (DD:stctx) (GG:sctx) (B:sty) (DD':stctx) (GG':sctx) (cc5:cc),\n     CTyp CC5 DD GG Inf B DD' GG' Chk A cc5 ->\n     CTyp (C_Anno CC5 A) DD GG Inf B DD' GG' Inf A cc5\n | CTyp_anno2 : forall (CC5:CC) (A:sty) (DD:stctx) (GG:sctx) (B:sty) (DD':stctx) (GG':sctx) (cc5:cc),\n     CTyp CC5 DD GG Chk B DD' GG' Chk A cc5 ->\n     CTyp (C_Anno CC5 A) DD GG Chk B DD' GG' Inf A cc5\n | CTyp_abs1 : forall (x:expvar) (CC5:CC) (DD:stctx) (GG:sctx) (A:sty) (DD':stctx) (GG':sctx) (A1 A2:sty) (cc5:cc),\n     CTyp CC5 DD GG Inf A DD'  (( x ~ A1 )++ GG' )  Chk A2 cc5 ->\n     swft DD' A1 ->\n     swfte DD' ->\n     x `notin` dom GG' ->\n     CTyp (C_Lam x CC5) DD GG Inf A DD' GG' Chk (sty_arrow A1 A2) (cc_lam x cc5)\n | CTyp_abs2 : forall (x:expvar) (CC5:CC) (DD:stctx) (GG:sctx) (A:sty) (DD':stctx) (GG':sctx) (A1 A2:sty) (cc5:cc),\n     CTyp CC5 DD GG Chk A DD'  (( x ~ A1 )++ GG' )  Chk A2 cc5 ->\n     swft DD' A1 ->\n     swfte DD' ->\n     x `notin` dom GG' ->\n     CTyp (C_Lam x CC5) DD GG Chk A DD' GG' Chk (sty_arrow A1 A2) (cc_lam x cc5)\n | CTyp_tabs1 : forall X (L:vars) (B:sty) (CC5:CC) (DD:stctx) (GG:sctx) (A:sty) (DD':stctx) (GG':sctx) (B':sty) (cc5:cc),\n     CTyp CC5 DD GG Inf A  (( X ~ B )++ DD' )  GG' Inf  ( open_sty_wrt_sty B' (sty_var_f X) )  cc5   ->\n     swft DD' B ->\n     swfe DD' GG' ->\n     swfte DD' ->\n     X `notin` dom GG' ->\n     X `notin` dom DD' ->\n     X `notin` fv_sty_in_sty B' ->\n     X `notin` fv_sty_in_sty B' ->\n     CTyp (C_tabs X B CC5) DD GG Inf A DD' GG' Inf (sty_all B B') (cc_tabs X cc5)\n | CTyp_tabs2 : forall X (L:vars) (B:sty) (CC5:CC) (DD:stctx) (GG:sctx) (A:sty) (DD':stctx) (GG':sctx) (B':sty) (cc5:cc),\n     CTyp CC5 DD GG Chk A  (( X ~ B )++ DD' )  GG' Inf  ( open_sty_wrt_sty B' (sty_var_f X) )  cc5   ->\n     swft DD' B ->\n     swfe DD' GG' ->\n     swfte DD' ->\n     X `notin` dom GG' ->\n     X `notin` dom DD' ->\n     X `notin` fv_sty_in_sty B' ->\n     X `notin` fv_sty_in_sty B' ->\n     CTyp (C_tabs X B CC5) DD GG Chk A DD' GG' Inf (sty_all B B') (cc_tabs X cc5)\n | CTyp_tapp1 : forall (CC5:CC) (B:sty) (DD:stctx) (GG:sctx) (A:sty) (DD':stctx) (GG':sctx) (A2:sty) (cc5:cc) (A1:sty),\n     CTyp CC5 DD GG Inf A DD' GG' Inf (sty_all A1 A2) cc5 ->\n     swfte DD' ->\n     swft DD' B ->\n     disjoint DD' B A1 ->\n     mono  B  ->\n     CTyp (C_tapp CC5 B) DD GG Inf A DD' GG' Inf  (open_sty_wrt_sty  A2   B )  (cc_tapp cc5  (sty2ty  B ) )\n | CTyp_tapp2 : forall (CC5:CC) (B:sty) (DD:stctx) (GG:sctx) (A:sty) (DD':stctx) (GG':sctx) (A2:sty) (cc5:cc) (A1:sty),\n     CTyp CC5 DD GG Chk A DD' GG' Inf (sty_all A1 A2) cc5 ->\n     swfte DD' ->\n     swft DD' B ->\n     disjoint DD' B A1 ->\n     mono  B  ->\n     CTyp (C_tapp CC5 B) DD GG Chk A DD' GG' Inf  (open_sty_wrt_sty  A2   B )  (cc_tapp cc5  (sty2ty  B ) ).\n\nHint Constructors CTyp.\n\n(** ** Context replacement *)\n\nFixpoint appctx (ctx : cc) (t : exp) : exp :=\n  match ctx with\n  | cc_empty => t\n  | cc_lam x c => exp_abs (close_exp_wrt_exp x (appctx c t))\n  | cc_tabs X c => exp_tabs (close_exp_wrt_ty X (appctx c t))\n  | cc_tapp c T => exp_tapp (appctx c t) T\n  | cc_appL c t2 => exp_app (appctx c t) t2\n  | cc_appR t1 c => exp_app t1 (appctx c t)\n  | cc_pairL c t2 => exp_pair (appctx c t) t2\n  | cc_pairR t1 c => exp_pair t1 (appctx c t)\n  | cc_co co c => exp_capp co (appctx c t)\n  end.\n\n\n\n(* BEGIN_CONGRUENCE *)\nLemma congruence : forall Δ Δ' Γ Γ' E1 E2 A A' e1 e2 dir dir' C c,\n    CTyp C Δ Γ dir A Δ' Γ' dir' A' c ->\n    has_type Δ Γ E1 dir A e1 ->\n    has_type Δ Γ E2 dir A e2 ->\n    E_open Δ Γ e1 e2 A A ->\n    E_open Δ' Γ' (appctx c e1) (appctx c e2) A' A'.\nProof with eauto.\n  introv Ctx.\n  gen E1 E2 e1 e2.\n  induction Ctx; introv Ty1 Ty2 EH; simpls...\n\n  - Case \"appL1\".\n    lets : IHCtx Ty1 Ty2 EH...\n    lets : fundamental_prop H H.\n    eapply app_compatibility...\n\n  - Case \"appL2\".\n    lets : IHCtx Ty1 Ty2 EH...\n    lets : fundamental_prop H H.\n    eapply app_compatibility...\n\n  - Case \"appR1\".\n    lets : IHCtx Ty1 Ty2 EH...\n    lets : fundamental_prop H H.\n    eapply app_compatibility...\n\n  - Case \"appR2\".\n    lets : IHCtx Ty1 Ty2 EH...\n    lets : fundamental_prop H H.\n    eapply app_compatibility...\n\n  - Case \"mergeL1\".\n    lets : IHCtx Ty1 Ty2 EH...\n    lets : fundamental_prop H H.\n    eapply pair_compatibility...\n\n  - Case \"mergeL2\".\n    lets : IHCtx Ty1 Ty2 EH...\n    lets : fundamental_prop H H.\n    eapply pair_compatibility...\n\n  - Case \"mergeR1\".\n    lets : IHCtx Ty1 Ty2 EH...\n    lets : fundamental_prop H H.\n    eapply pair_compatibility...\n\n  - Case \"mergeR2\".\n    lets : IHCtx Ty1 Ty2 EH...\n    lets : fundamental_prop H H.\n    eapply pair_compatibility...\n\n  - Case \"rcd1\".\n    lets : IHCtx Ty1 Ty2 EH...\n    apply record_compatibility...\n\n  - Case \"rcd2\".\n    lets : IHCtx Ty1 Ty2 EH...\n    apply record_compatibility...\n\n  - Case \"proj1\".\n    lets : IHCtx Ty1 Ty2 EH...\n    lets HH : record_compatibility...\n    apply HH in H...\n\n  - Case \"proj2\".\n    lets : IHCtx Ty1 Ty2 EH...\n    lets HH : record_compatibility...\n    apply HH in H...\n\n  - Case \"abs1\".\n    lets : IHCtx Ty1 Ty2 EH...\n    apply abs_compatibility with (x := x)...\n    rewrite fv_exp_in_exp_close_exp_wrt_exp...\n    rewrite fv_exp_in_exp_close_exp_wrt_exp...\n    repeat rewrite~ open_exp_wrt_exp_close_exp_wrt_exp.\n\n  - Case \"abs2\".\n    lets : IHCtx Ty1 Ty2 EH...\n    apply abs_compatibility with (x := x)...\n    rewrite fv_exp_in_exp_close_exp_wrt_exp...\n    rewrite fv_exp_in_exp_close_exp_wrt_exp...\n    repeat rewrite open_exp_wrt_exp_close_exp_wrt_exp...\n\n  - Case \"tabs1\".\n    lets : IHCtx Ty1 Ty2 EH...\n    apply tabs_compatibility with (X := X)...\n    rewrite fv_ty_in_exp_close_exp_wrt_ty...\n    rewrite fv_ty_in_exp_close_exp_wrt_ty...\n    repeat rewrite~ open_exp_wrt_ty_close_exp_wrt_ty...\n\n  - Case \"tabs2\".\n    lets : IHCtx Ty1 Ty2 EH...\n    apply tabs_compatibility with (X := X)...\n    rewrite fv_ty_in_exp_close_exp_wrt_ty...\n    rewrite fv_ty_in_exp_close_exp_wrt_ty...\n    repeat rewrite~ open_exp_wrt_ty_close_exp_wrt_ty...\n\n\n  - Case \"tapp\".\n    lets : IHCtx Ty1 Ty2 EH...\n    eapply tapp_compatibility...\n\n  - Case \"tapp\".\n    lets : IHCtx Ty1 Ty2 EH...\n    eapply tapp_compatibility...\n\nQed.\n\n\n\nDefinition kleene_equiv t1 t2 :=\n  exists k, t1 ->* (exp_lit k) /\\ t2 ->* (exp_lit k).\n\n\nDefinition ctx_equiv Δ Γ E1 E2 A := forall e1 e2 dir dir' C c,\n    has_type Δ Γ E1 dir A e1 ->\n    has_type Δ Γ E2 dir A e2 ->\n    CTyp C Δ Γ dir A nil nil dir' sty_nat c ->\n    kleene_equiv (appctx c e1) (appctx c e2).\n\n\n(* BEGIN_ADEQUACY *)\nLemma adequacy : forall e1 e2,\n    E_open nil nil e1 e2 sty_nat sty_nat ->\n    kleene_equiv e1 e2.\nProof with eauto.\n  introv EH.\n  destruct EH as (WF1 & WF2 & ? & ? & EH).\n  specializes EH rel_d_empty rel_g_empty...\n  simpls...\n  destruct EH as (? & ? & ? & ? & ? & ? & ? & ? & ? & ? & VH)...\n  destruct VH...\n  unfolds.\n  exists n...\nQed.\n\n\n(* BEGIN_COHERENCE *)\nTheorem coherence : forall Δ Γ E A,\n    ctx_equiv Δ Γ E E A.\nProof with eauto.\n  intros.\n  unfolds.\n  introv Ty1 Ty2 Ctx.\n  lets H : fundamental_prop Ty1 Ty2.\n  lets HH : congruence Ctx Ty1 Ty2 H.\n  apply adequacy in HH...\nQed.\n", "meta": {"author": "bixuanzju", "repo": "phd-thesis-artifact", "sha": "0c95f67db0d97e5a7629a5a81f819a50d4c0a17b", "save_path": "github-repos/coq/bixuanzju-phd-thesis-artifact", "path": "github-repos/coq/bixuanzju-phd-thesis-artifact/phd-thesis-artifact-0c95f67db0d97e5a7629a5a81f819a50d4c0a17b/coq/poly/Coherence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.27148777043861516}}
{"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 INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Correctness proof for operator strength reduction. *)\n\nRequire Import Coqlib Compopts.\nRequire Import Integers Floats Values Memory Globalenvs Events.\nRequire Import Op Registers RTL ValueDomain ValueAOp ValueAnalysis.\nRequire Import ConstpropOp.\n\nLocal Transparent Archi.ptr64.\n\nSection STRENGTH_REDUCTION.\n\nVariable bc: block_classification.\nVariable ge: genv.\nHypothesis GENV: genv_match bc ge.\nVariable sp: block.\nHypothesis STACK: bc sp = BCstack.\nVariable ae: AE.t.\nVariable e: regset.\nVariable m: mem.\nHypothesis MATCH: ematch bc e ae.\n\nLemma match_G:\n  forall r id ofs,\n  AE.get r ae = Ptr(Gl id ofs) -> Val.lessdef e#r (Genv.symbol_address ge id ofs).\nProof.\n  intros. apply vmatch_ptr_gl with bc; auto. rewrite <- H. apply MATCH.\nQed.\n\nLemma match_S:\n  forall r ofs,\n  AE.get r ae = Ptr(Stk ofs) -> Val.lessdef e#r (Vptr sp ofs).\nProof.\n  intros. apply vmatch_ptr_stk with bc; auto. rewrite <- H. apply MATCH.\nQed.\n\nLtac InvApproxRegs :=\n  match goal with\n  | [ H: _ :: _ = _ :: _ |- _ ] =>\n        injection H; clear H; intros; InvApproxRegs\n  | [ H: ?v = AE.get ?r ae |- _ ] =>\n        generalize (MATCH r); rewrite <- H; clear H; intro; InvApproxRegs\n  | _ => idtac\n  end.\n\nLtac SimplVM :=\n  match goal with\n  | [ H: vmatch _ ?v (I ?n) |- _ ] =>\n      let E := fresh in\n      assert (E: v = Vint n) by (inversion H; auto);\n      rewrite E in *; clear H; SimplVM\n  | [ H: vmatch _ ?v (L ?n) |- _ ] =>\n      let E := fresh in\n      assert (E: v = Vlong n) by (inversion H; auto);\n      rewrite E in *; clear H; SimplVM\n  | [ H: vmatch _ ?v (F ?n) |- _ ] =>\n      let E := fresh in\n      assert (E: v = Vfloat n) by (inversion H; auto);\n      rewrite E in *; clear H; SimplVM\n  | [ H: vmatch _ ?v (FS ?n) |- _ ] =>\n      let E := fresh in\n      assert (E: v = Vsingle n) by (inversion H; auto);\n      rewrite E in *; clear H; SimplVM\n  | [ H: vmatch _ ?v (Ptr(Gl ?id ?ofs)) |- _ ] =>\n      let E := fresh in\n      assert (E: Val.lessdef v (Genv.symbol_address ge id ofs)) by (eapply vmatch_ptr_gl; eauto);\n      clear H; SimplVM\n  | [ H: vmatch _ ?v (Ptr(Stk ?ofs)) |- _ ] =>\n      let E := fresh in\n      assert (E: Val.lessdef v (Vptr sp ofs)) by (eapply vmatch_ptr_stk; eauto);\n      clear H; SimplVM\n  | _ => idtac\n  end.\n\nLemma const_for_result_correct:\n  forall a op v,\n  const_for_result a = Some op ->\n  vmatch bc v a ->\n  exists v', eval_operation ge (Vptr sp Ptrofs.zero) op nil m = Some v' /\\ Val.lessdef v v'.\nProof.\n  unfold const_for_result; intros; destruct a; inv H; SimplVM.\n- (* integer *)\n  exists (Vint n); auto.\n- (* long *)\n  exists (Vlong n); auto.\n- (* float *)\n  destruct (Compopts.generate_float_constants tt); inv H2. exists (Vfloat f); auto.\n- (* single *)\n  destruct (Compopts.generate_float_constants tt); inv H2. exists (Vsingle f); auto.\n- (* pointer *)\n  destruct p; try discriminate; SimplVM.\n  + (* global *)\n    inv H2. exists (Genv.symbol_address ge id ofs); auto.\n  + (* stack *)\n    inv H2. exists (Vptr sp ofs); split; auto. simpl. rewrite Ptrofs.add_zero_l; auto.\nQed.\n\nLemma eval_static_shift_correct: forall s v a,\n  eval_shift s (Vint v) a = Vint (eval_static_shift s v a).\nProof.\n  intros; destruct s; simpl; rewrite ? a32_range; auto.\nQed.\n\nLemma eval_static_shiftl_correct: forall s v a,\n  eval_shiftl s (Vlong v) a = Vlong (eval_static_shiftl s v a).\nProof.\n  intros; destruct s; simpl; rewrite ? a64_range; auto.\nQed.\n\nLemma eval_static_extend_correct: forall x v a,\n  eval_extend x (Vint v) a = Vlong (eval_static_extend x v a).\nProof.\n  unfold eval_extend, eval_static_extend; intros; destruct x; simpl; rewrite ? a64_range; auto.\nQed.\n\nLemma cond_strength_reduction_correct:\n  forall cond args vl,\n  vl = map (fun r => AE.get r ae) args ->\n  let (cond', args') := cond_strength_reduction cond args vl in\n  eval_condition cond' e##args' m = eval_condition cond e##args m.\nProof.\n  intros until vl. unfold cond_strength_reduction.\n  case (cond_strength_reduction_match cond args vl); simpl; intros; InvApproxRegs; SimplVM.\n- apply Val.swap_cmp_bool.\n- auto.\n- apply Val.swap_cmpu_bool.\n- auto.\n- rewrite eval_static_shift_correct; auto.\n- rewrite eval_static_shift_correct; auto.\n- apply Val.swap_cmpl_bool.\n- auto.\n- apply Val.swap_cmplu_bool.\n- auto.\n- rewrite eval_static_shiftl_correct; auto.\n- rewrite eval_static_shiftl_correct; auto.\n- destruct (Float.eq_dec n1 Float.zero).\n  subst n1. simpl. destruct (e#r2); simpl; auto. rewrite Float.cmp_swap. auto.\n  simpl. rewrite H1; auto.\n- destruct (Float.eq_dec n2 Float.zero).\n  subst n2. simpl. auto.\n  simpl. rewrite H1; auto.\n- destruct (Float.eq_dec n1 Float.zero).\n  subst n1. simpl. destruct (e#r2); simpl; auto. rewrite Float.cmp_swap. auto.\n  simpl. rewrite H1; auto.\n- destruct (Float.eq_dec n2 Float.zero); simpl; auto.\n  subst n2; auto.\n  rewrite H1; auto.\n- destruct (Float32.eq_dec n1 Float32.zero).\n  subst n1. simpl. destruct (e#r2); simpl; auto. rewrite Float32.cmp_swap. auto.\n  simpl. rewrite H1; auto.\n- destruct (Float32.eq_dec n2 Float32.zero).\n  subst n2. simpl. auto.\n  simpl. rewrite H1; auto.\n- destruct (Float32.eq_dec n1 Float32.zero).\n  subst n1. simpl. destruct (e#r2); simpl; auto. rewrite Float32.cmp_swap. auto.\n  simpl. rewrite H1; auto.\n- destruct (Float32.eq_dec n2 Float32.zero); simpl; auto.\n  subst n2; auto.\n  rewrite H1; auto.\n- auto.\nQed.\n\nLemma make_cmp_base_correct:\n  forall c args vl,\n  vl = map (fun r => AE.get r ae) args ->\n  let (op', args') := make_cmp_base c args vl in\n  exists v, eval_operation ge (Vptr sp Ptrofs.zero) op' e##args' m = Some v\n         /\\ Val.lessdef (Val.of_optbool (eval_condition c e##args m)) v.\nProof.\n  intros. unfold make_cmp_base.\n  generalize (cond_strength_reduction_correct c args vl H).\n  destruct (cond_strength_reduction c args vl) as [c' args']. intros EQ.\n  econstructor; split. simpl; eauto. rewrite EQ. auto.\nQed.\n\nLemma make_cmp_correct:\n  forall c args vl,\n  vl = map (fun r => AE.get r ae) args ->\n  let (op', args') := make_cmp c args vl in\n  exists v, eval_operation ge (Vptr sp Ptrofs.zero) op' e##args' m = Some v\n         /\\ Val.lessdef (Val.of_optbool (eval_condition c e##args m)) v.\nProof.\n  intros c args vl.\n  assert (Y: forall r, vincl (AE.get r ae) (Uns Ptop 1) = true ->\n             e#r = Vundef \\/ e#r = Vint Int.zero \\/ e#r = Vint Int.one).\n  { intros. apply vmatch_Uns_1 with bc Ptop. eapply vmatch_ge. eapply vincl_ge; eauto. apply MATCH. }\n  unfold make_cmp. case (make_cmp_match c args vl); intros.\n- unfold make_cmp_imm_eq.\n  destruct (Int.eq_dec n Int.one && vincl v1 (Uns Ptop 1)) eqn:E1.\n+ simpl in H; inv H. InvBooleans. subst n.\n  exists (e#r1); split; auto. simpl.\n  exploit Y; eauto. intros [A | [A | A]]; rewrite A; simpl; auto.\n+ destruct (Int.eq_dec n Int.zero && vincl v1 (Uns Ptop 1)) eqn:E0.\n* simpl in H; inv H. InvBooleans. subst n.\n  exists (Val.xor e#r1 (Vint Int.one)); split; auto. simpl.\n  exploit Y; eauto. intros [A | [A | A]]; rewrite A; simpl; auto.\n* apply make_cmp_base_correct; auto.\n- unfold make_cmp_imm_ne.\n  destruct (Int.eq_dec n Int.zero && vincl v1 (Uns Ptop 1)) eqn:E0.\n+ simpl in H; inv H. InvBooleans. subst n.\n  exists (e#r1); split; auto. simpl.\n  exploit Y; eauto. intros [A | [A | A]]; rewrite A; simpl; auto.\n+ destruct (Int.eq_dec n Int.one && vincl v1 (Uns Ptop 1)) eqn:E1.\n* simpl in H; inv H. InvBooleans. subst n.\n  exists (Val.xor e#r1 (Vint Int.one)); split; auto. simpl.\n  exploit Y; eauto. intros [A | [A | A]]; rewrite A; simpl; auto.\n* apply make_cmp_base_correct; auto.\n- unfold make_cmp_imm_eq.\n  destruct (Int.eq_dec n Int.one && vincl v1 (Uns Ptop 1)) eqn:E1.\n+ simpl in H; inv H. InvBooleans. subst n.\n  exists (e#r1); split; auto. simpl.\n  exploit Y; eauto. intros [A | [A | A]]; rewrite A; simpl; auto.\n+ destruct (Int.eq_dec n Int.zero && vincl v1 (Uns Ptop 1)) eqn:E0.\n* simpl in H; inv H. InvBooleans. subst n.\n  exists (Val.xor e#r1 (Vint Int.one)); split; auto. simpl.\n  exploit Y; eauto. intros [A | [A | A]]; rewrite A; simpl; auto.\n* apply make_cmp_base_correct; auto.\n- unfold make_cmp_imm_ne.\n  destruct (Int.eq_dec n Int.zero && vincl v1 (Uns Ptop 1)) eqn:E0.\n+ simpl in H; inv H. InvBooleans. subst n.\n  exists (e#r1); split; auto. simpl.\n  exploit Y; eauto. intros [A | [A | A]]; rewrite A; simpl; auto.\n+ destruct (Int.eq_dec n Int.one && vincl v1 (Uns Ptop 1)) eqn:E1.\n* simpl in H; inv H. InvBooleans. subst n.\n  exists (Val.xor e#r1 (Vint Int.one)); split; auto. simpl.\n  exploit Y; eauto. intros [A | [A | A]]; rewrite A; simpl; auto.\n* apply make_cmp_base_correct; auto.\n- apply make_cmp_base_correct; auto.\nQed.\n\nLemma make_select_correct:\n  forall c ty r1 r2 args vl,\n  vl = map (fun r => AE.get r ae) args ->\n  let (op', args') := make_select c ty r1 r2 args vl in\n  exists v, eval_operation ge (Vptr sp Ptrofs.zero) op' e##args' m = Some v\n         /\\ Val.lessdef (Val.select (eval_condition c e##args m) e#r1 e#r2 ty) v.\nProof.\n  unfold make_select; intros.\n  destruct (resolve_branch (eval_static_condition c vl)) as [b|] eqn:RB.\n- exists (if b then e#r1 else e#r2); split.\n+ simpl. destruct b; auto.\n+ destruct (eval_condition c e##args m) as [b'|] eqn:EC; simpl; auto.\n  assert (b = b').\n  { eapply resolve_branch_sound; eauto. \n    rewrite <- EC. apply eval_static_condition_sound with bc. \n    subst vl. exact (aregs_sound _ _ _ args MATCH). }\n  subst b'. apply Val.lessdef_normalize.\n- generalize (cond_strength_reduction_correct c args vl H).\n  destruct (cond_strength_reduction c args vl) as [cond' args']; intros EQ.\n  econstructor; split. simpl; eauto. rewrite EQ; 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 (Vptr sp Ptrofs.zero) op e##args m = Some v /\\ Val.lessdef (Val.add e#r (Vint n)) v.\nProof.\n  intros. unfold make_addimm.\n  predSpec Int.eq Int.eq_spec n Int.zero; intros.\n  subst. exists (e#r); split; auto.\n  destruct (e#r); simpl; rewrite ?Int.add_zero; auto.\n  exists (Val.add e#r (Vint n)); split; auto.\nQed.\n\nLemma make_shlimm_correct:\n  forall n r1 r2,\n  e#r2 = Vint n ->\n  let (op, args) := make_shlimm n r1 r2 in\n  exists v, eval_operation ge (Vptr sp Ptrofs.zero) op e##args m = Some v /\\ Val.lessdef (Val.shl e#r1 (Vint n)) v.\nProof.\nLocal Opaque mk_amount32.\n  intros; unfold make_shlimm.\n  predSpec Int.eq Int.eq_spec n Int.zero; intros. subst.\n  exists (e#r1); split; auto. destruct (e#r1); simpl; auto. rewrite Int.shl_zero. auto.\n  destruct (Int.ltu n Int.iwordsize) eqn:L.\n  econstructor; split. simpl. eauto. rewrite mk_amount32_eq; auto.\n  econstructor; split. simpl. eauto. rewrite H; auto.\nQed.\n\nLemma make_shrimm_correct:\n  forall n r1 r2,\n  e#r2 = Vint n ->\n  let (op, args) := make_shrimm n r1 r2 in\n  exists v, eval_operation ge (Vptr sp Ptrofs.zero) op e##args m = Some v /\\ Val.lessdef (Val.shr e#r1 (Vint n)) v.\nProof.\n  intros; unfold make_shrimm.\n  predSpec Int.eq Int.eq_spec n Int.zero; intros. subst.\n  exists (e#r1); split; auto. destruct (e#r1); simpl; auto. rewrite Int.shr_zero. auto.\n  destruct (Int.ltu n Int.iwordsize) eqn:L.\n  econstructor; split. simpl. eauto. rewrite mk_amount32_eq; auto.\n  econstructor; split. simpl. eauto. rewrite H; auto.\nQed.\n\nLemma make_shruimm_correct:\n  forall n r1 r2,\n  e#r2 = Vint n ->\n  let (op, args) := make_shruimm n r1 r2 in\n  exists v, eval_operation ge (Vptr sp Ptrofs.zero) op e##args m = Some v /\\ Val.lessdef (Val.shru e#r1 (Vint n)) v.\nProof.\n  intros; unfold make_shruimm.\n  predSpec Int.eq Int.eq_spec n Int.zero; intros. subst.\n  exists (e#r1); split; auto. destruct (e#r1); simpl; auto. rewrite Int.shru_zero. auto.\n  destruct (Int.ltu n Int.iwordsize) eqn:L.\n  econstructor; split. simpl. eauto. rewrite mk_amount32_eq; auto.\n  econstructor; split. simpl. eauto. rewrite H; auto.\nQed.\n\nLemma make_mulimm_correct:\n  forall n r1 r2,\n  e#r2 = Vint n ->\n  let (op, args) := make_mulimm n r1 r2 in\n  exists v, eval_operation ge (Vptr sp Ptrofs.zero) op e##args m = Some v /\\ Val.lessdef (Val.mul e#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 (e#r1); simpl; auto. rewrite Int.mul_zero; auto.\n  predSpec Int.eq Int.eq_spec n Int.one; intros. subst.\n  exists (e#r1); split; auto. destruct (e#r1); simpl; auto. rewrite Int.mul_one; auto.\n  destruct (Int.is_power2 n) eqn:?; intros.\n  rewrite (Val.mul_pow2 e#r1 _ _ Heqo). econstructor; split. simpl; eauto.\n  rewrite mk_amount32_eq; auto. eapply Int.is_power2_range; eauto.\n  econstructor; split; eauto. simpl. rewrite H; auto.\nQed.\n\nLemma make_divimm_correct:\n  forall n r1 r2 v,\n  Val.divs e#r1 e#r2 = Some v ->\n  e#r2 = Vint n ->\n  let (op, args) := make_divimm n r1 r2 in\n  exists w, eval_operation ge (Vptr sp Ptrofs.zero) op e##args m = Some w /\\ Val.lessdef v w.\nProof.\n  intros; unfold make_divimm.\n  predSpec Int.eq Int.eq_spec n Int.one; intros. subst. rewrite H0 in H.\n  destruct (e#r1) eqn:?;\n    try (rewrite Val.divs_one in H; exists (Vint i); split; simpl; try rewrite Heqv0; auto);\n    inv H; auto.\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 e#r1 e#r2 = Some v ->\n  e#r2 = Vint n ->\n  let (op, args) := make_divuimm n r1 r2 in\n  exists w, eval_operation ge (Vptr sp Ptrofs.zero) op e##args m = Some w /\\ Val.lessdef v w.\nProof.\n  intros; unfold make_divuimm.\n  predSpec Int.eq Int.eq_spec n Int.one; intros. subst. rewrite H0 in H.\n  destruct (e#r1) eqn:?;\n    try (rewrite Val.divu_one in H; exists (Vint i); split; simpl; try rewrite Heqv0; auto);\n    inv H; auto.\n  destruct (Int.is_power2 n) eqn:?.\n  econstructor; split. simpl; eauto.\n  rewrite mk_amount32_eq by (eapply Int.is_power2_range; eauto).\n  rewrite H0 in H. erewrite Val.divu_pow2 by eauto. auto.\n  exists v; auto.\nQed.\n\nLemma make_andimm_correct:\n  forall n r x,\n  vmatch bc e#r x ->\n  let (op, args) := make_andimm n r x in\n  exists v, eval_operation ge (Vptr sp Ptrofs.zero) op e##args m = Some v /\\ Val.lessdef (Val.and e#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 (e#r); simpl; auto. rewrite Int.and_zero; auto.\n  predSpec Int.eq Int.eq_spec n Int.mone; intros.\n  subst n. exists (e#r); split; auto. destruct (e#r); simpl; auto. rewrite Int.and_mone; auto.\n  destruct (match x with Uns _ k => Int.eq (Int.zero_ext k (Int.not n)) Int.zero\n                       | _ => false end) eqn:UNS.\n  destruct x; try congruence.\n  exists (e#r); split; auto.\n  inv H; auto. simpl. replace (Int.and i n) with i; auto.\n  generalize (Int.eq_spec (Int.zero_ext n0 (Int.not n)) Int.zero); rewrite UNS; intro EQ.\n  Int.bit_solve. destruct (zlt i0 n0).\n  replace (Int.testbit n i0) with (negb (Int.testbit Int.zero i0)).\n  rewrite Int.bits_zero. simpl. rewrite andb_true_r. auto.\n  rewrite <- EQ. rewrite Int.bits_zero_ext by lia. rewrite zlt_true by auto.\n  rewrite Int.bits_not by auto. apply negb_involutive.\n  rewrite H6 by auto. 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 (Vptr sp Ptrofs.zero) op e##args m = Some v /\\ Val.lessdef (Val.or e#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 (e#r); split; auto. destruct (e#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 (e#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 (Vptr sp Ptrofs.zero) op e##args m = Some v /\\ Val.lessdef (Val.xor e#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 (e#r); split; auto. destruct (e#r); simpl; auto. rewrite Int.xor_zero; auto.\n  predSpec Int.eq Int.eq_spec n Int.mone; intros.\n  subst n. exists (Val.notint e#r); split; auto.\n  econstructor; split; eauto. auto.\nQed.\n\nLemma make_addlimm_correct:\n  forall n r,\n  let (op, args) := make_addlimm n r in\n  exists v, eval_operation ge (Vptr sp Ptrofs.zero) op e##args m = Some v /\\ Val.lessdef (Val.addl e#r (Vlong n)) v.\nProof.\n  intros. unfold make_addlimm.\n  predSpec Int64.eq Int64.eq_spec n Int64.zero; intros.\n  subst. exists (e#r); split; auto.\n  destruct (e#r); simpl; auto; rewrite ? Int64.add_zero, ? Ptrofs.add_zero; auto.\n  exists (Val.addl e#r (Vlong n)); split; auto.\nQed.\n\nLemma make_shllimm_correct:\n  forall n r1 r2,\n  e#r2 = Vint n ->\n  let (op, args) := make_shllimm n r1 r2 in\n  exists v, eval_operation ge (Vptr sp Ptrofs.zero) op e##args m = Some v /\\ Val.lessdef (Val.shll e#r1 (Vint n)) v.\nProof.\nLocal Opaque mk_amount64.\n  intros; unfold make_shllimm.\n  predSpec Int.eq Int.eq_spec n Int.zero; intros. subst.\n  exists (e#r1); split; auto. destruct (e#r1); simpl; auto.\n  unfold Int64.shl'. rewrite Z.shiftl_0_r, Int64.repr_unsigned. auto.\n  destruct (Int.ltu n Int64.iwordsize') eqn:L.\n  econstructor; split. simpl. eauto. rewrite mk_amount64_eq; auto.\n  econstructor; split. simpl. eauto. rewrite H; auto.\nQed.\n\nLemma make_shrlimm_correct:\n  forall n r1 r2,\n  e#r2 = Vint n ->\n  let (op, args) := make_shrlimm n r1 r2 in\n  exists v, eval_operation ge (Vptr sp Ptrofs.zero) op e##args m = Some v /\\ Val.lessdef (Val.shrl e#r1 (Vint n)) v.\nProof.\n  intros; unfold make_shrlimm.\n  predSpec Int.eq Int.eq_spec n Int.zero; intros. subst.\n  exists (e#r1); split; auto. destruct (e#r1); simpl; auto.\n  unfold Int64.shr'. rewrite Z.shiftr_0_r, Int64.repr_signed. auto.\n  destruct (Int.ltu n Int64.iwordsize') eqn:L.\n  econstructor; split. simpl. eauto. rewrite mk_amount64_eq; auto.\n  econstructor; split. simpl. eauto. rewrite H; auto.\nQed.\n\nLemma make_shrluimm_correct:\n  forall n r1 r2,\n  e#r2 = Vint n ->\n  let (op, args) := make_shrluimm n r1 r2 in\n  exists v, eval_operation ge (Vptr sp Ptrofs.zero) op e##args m = Some v /\\ Val.lessdef (Val.shrlu e#r1 (Vint n)) v.\nProof.\n  intros; unfold make_shrluimm.\n  predSpec Int.eq Int.eq_spec n Int.zero; intros. subst.\n  exists (e#r1); split; auto. destruct (e#r1); simpl; auto.\n  unfold Int64.shru'. rewrite Z.shiftr_0_r, Int64.repr_unsigned. auto.\n  destruct (Int.ltu n Int64.iwordsize') eqn:L.\n  econstructor; split. simpl. eauto. rewrite mk_amount64_eq; auto.\n  econstructor; split. simpl. eauto. rewrite H; auto.\nQed.\n\nLemma make_mullimm_correct:\n  forall n r1 r2,\n  e#r2 = Vlong n ->\n  let (op, args) := make_mullimm n r1 r2 in\n  exists v, eval_operation ge (Vptr sp Ptrofs.zero) op e##args m = Some v /\\ Val.lessdef (Val.mull e#r1 (Vlong n)) v.\nProof.\n  intros; unfold make_mullimm.\n  predSpec Int64.eq Int64.eq_spec n Int64.zero; intros. subst.\n  exists (Vlong Int64.zero); split; auto. destruct (e#r1); simpl; auto. rewrite Int64.mul_zero; auto.\n  predSpec Int64.eq Int64.eq_spec n Int64.one; intros. subst.\n  exists (e#r1); split; auto. destruct (e#r1); simpl; auto. rewrite Int64.mul_one; auto.\n  destruct (Int64.is_power2' n) eqn:?; intros.\n  econstructor; split. simpl; eauto. \n  rewrite mk_amount64_eq by (eapply Int64.is_power2'_range; eauto).\n  destruct (e#r1); simpl; auto.\n  erewrite Int64.is_power2'_range by eauto.\n  erewrite Int64.mul_pow2' by eauto. auto.\n  econstructor; split; eauto. simpl; rewrite H; auto.\nQed.\n\nLemma make_divlimm_correct:\n  forall n r1 r2 v,\n  Val.divls e#r1 e#r2 = Some v ->\n  e#r2 = Vlong n ->\n  let (op, args) := make_divlimm n r1 r2 in\n  exists w, eval_operation ge (Vptr sp Ptrofs.zero) op e##args m = Some w /\\ Val.lessdef v w.\nProof.\n  intros; unfold make_divlimm.\n  destruct (Int64.is_power2' n) eqn:?. destruct (Int.ltu i (Int.repr 63)) eqn:?.\n  rewrite H0 in H. econstructor; split. simpl; eauto. eapply Val.divls_pow2; eauto. auto.\n  exists v; auto.\n  exists v; auto.\nQed.\n\nLemma make_divluimm_correct:\n  forall n r1 r2 v,\n  Val.divlu e#r1 e#r2 = Some v ->\n  e#r2 = Vlong n ->\n  let (op, args) := make_divluimm n r1 r2 in\n  exists w, eval_operation ge (Vptr sp Ptrofs.zero) op e##args m = Some w /\\ Val.lessdef v w.\nProof.\n  intros; unfold make_divluimm.\n  destruct (Int64.is_power2' n) eqn:?.\n  econstructor; split. simpl; eauto.\n  rewrite mk_amount64_eq by (eapply Int64.is_power2'_range; eauto).\n  rewrite H0 in H. destruct (e#r1); inv H. destruct (Int64.eq n Int64.zero); inv H2.\n  simpl.\n  erewrite Int64.is_power2'_range by eauto.    \n  erewrite Int64.divu_pow2' by eauto.  auto. \n  exists v; auto.\nQed.\n\nLemma make_andlimm_correct:\n  forall n r x,\n  let (op, args) := make_andlimm n r x in\n  exists v, eval_operation ge (Vptr sp Ptrofs.zero) op e##args m = Some v /\\ Val.lessdef (Val.andl e#r (Vlong n)) v.\nProof.\n  intros; unfold make_andlimm.\n  predSpec Int64.eq Int64.eq_spec n Int64.zero; intros.\n  subst n. exists (Vlong Int64.zero); split; auto. destruct (e#r); simpl; auto. rewrite Int64.and_zero; auto.\n  predSpec Int64.eq Int64.eq_spec n Int64.mone; intros.\n  subst n. exists (e#r); split; auto. destruct (e#r); simpl; auto. rewrite Int64.and_mone; auto.\n  econstructor; split; eauto. auto.\nQed.\n\nLemma make_orlimm_correct:\n  forall n r,\n  let (op, args) := make_orlimm n r in\n  exists v, eval_operation ge (Vptr sp Ptrofs.zero) op e##args m = Some v /\\ Val.lessdef (Val.orl e#r (Vlong n)) v.\nProof.\n  intros; unfold make_orlimm.\n  predSpec Int64.eq Int64.eq_spec n Int64.zero; intros.\n  subst n. exists (e#r); split; auto. destruct (e#r); simpl; auto. rewrite Int64.or_zero; auto.\n  predSpec Int64.eq Int64.eq_spec n Int64.mone; intros.\n  subst n. exists (Vlong Int64.mone); split; auto. destruct (e#r); simpl; auto. rewrite Int64.or_mone; auto.\n  econstructor; split; eauto. auto.\nQed.\n\nLemma make_xorlimm_correct:\n  forall n r,\n  let (op, args) := make_xorlimm n r in\n  exists v, eval_operation ge (Vptr sp Ptrofs.zero) op e##args m = Some v /\\ Val.lessdef (Val.xorl e#r (Vlong n)) v.\nProof.\n  intros; unfold make_xorlimm.\n  predSpec Int64.eq Int64.eq_spec n Int64.zero; intros.\n  subst n. exists (e#r); split; auto. destruct (e#r); simpl; auto. rewrite Int64.xor_zero; auto.\n  predSpec Int64.eq Int64.eq_spec n Int64.mone; intros.\n  subst n. exists (Val.notl e#r); split; auto.\n  econstructor; split; eauto. auto.\nQed.\n\nLemma make_mulfimm_correct:\n  forall n r1 r2,\n  e#r2 = Vfloat n ->\n  let (op, args) := make_mulfimm n r1 r1 r2 in\n  exists v, eval_operation ge (Vptr sp Ptrofs.zero) op e##args m = Some v /\\ Val.lessdef (Val.mulf e#r1 e#r2) v.\nProof.\n  intros; unfold make_mulfimm.\n  destruct (Float.eq_dec n (Float.of_int (Int.repr 2))); intros.\n  simpl. econstructor; split. eauto. rewrite H; subst n.\n  destruct (e#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  e#r1 = Vfloat n ->\n  let (op, args) := make_mulfimm n r2 r1 r2 in\n  exists v, eval_operation ge (Vptr sp Ptrofs.zero) op e##args m = Some v /\\ Val.lessdef (Val.mulf e#r1 e#r2) v.\nProof.\n  intros; unfold make_mulfimm.\n  destruct (Float.eq_dec n (Float.of_int (Int.repr 2))); intros.\n  simpl. econstructor; split. eauto. rewrite H; subst n.\n  destruct (e#r2); simpl; auto. rewrite Float.mul2_add; auto.\n  rewrite Float.mul_commut; auto.\n  simpl. econstructor; split; eauto.\nQed.\n\nLemma make_mulfsimm_correct:\n  forall n r1 r2,\n  e#r2 = Vsingle n ->\n  let (op, args) := make_mulfsimm n r1 r1 r2 in\n  exists v, eval_operation ge (Vptr sp Ptrofs.zero) op e##args m = Some v /\\ Val.lessdef (Val.mulfs e#r1 e#r2) v.\nProof.\n  intros; unfold make_mulfsimm.\n  destruct (Float32.eq_dec n (Float32.of_int (Int.repr 2))); intros.\n  simpl. econstructor; split. eauto. rewrite H; subst n.\n  destruct (e#r1); simpl; auto. rewrite Float32.mul2_add; auto.\n  simpl. econstructor; split; eauto.\nQed.\n\nLemma make_mulfsimm_correct_2:\n  forall n r1 r2,\n  e#r1 = Vsingle n ->\n  let (op, args) := make_mulfsimm n r2 r1 r2 in\n  exists v, eval_operation ge (Vptr sp Ptrofs.zero) op e##args m = Some v /\\ Val.lessdef (Val.mulfs e#r1 e#r2) v.\nProof.\n  intros; unfold make_mulfsimm.\n  destruct (Float32.eq_dec n (Float32.of_int (Int.repr 2))); intros.\n  simpl. econstructor; split. eauto. rewrite H; subst n.\n  destruct (e#r2); simpl; auto. rewrite Float32.mul2_add; auto.\n  rewrite Float32.mul_commut; auto.\n  simpl. econstructor; split; eauto.\nQed.\n\nLemma make_zext_correct:\n  forall s r x,\n  vmatch bc e#r x ->\n  let (op, args) := make_zext s r x in\n  exists v, eval_operation ge (Vptr sp Ptrofs.zero) op e##args m = Some v /\\ Val.lessdef (Val.zero_ext s e#r) v.\nProof.\n  intros; unfold make_zext. destruct (vincl x (Uns Ptop s)) eqn:INCL.\n- exists e#r; split; auto.\n  assert (V: vmatch bc e#r (Uns Ptop s)).\n  { eapply vmatch_ge; eauto. apply vincl_ge; auto. }\n  inv V; simpl; auto. rewrite is_uns_zero_ext in H4 by auto. rewrite H4; auto.\n- econstructor; split; simpl; eauto.\nQed.\n\nLemma make_sext_correct:\n  forall s r x,\n  vmatch bc e#r x ->\n  let (op, args) := make_sext s r x in\n  exists v, eval_operation ge (Vptr sp Ptrofs.zero) op e##args m = Some v /\\ Val.lessdef (Val.sign_ext s e#r) v.\nProof.\n  intros; unfold make_sext. destruct (vincl x (Sgn Ptop s)) eqn:INCL.\n- exists e#r; split; auto.\n  assert (V: vmatch bc e#r (Sgn Ptop s)).\n  { eapply vmatch_ge; eauto. apply vincl_ge; auto. }\n  inv V; simpl; auto. rewrite is_sgn_sign_ext in H4 by auto. rewrite H4; auto.\n- econstructor; split; simpl; eauto.\nQed.\n\nLemma op_strength_reduction_correct:\n  forall op args vl v,\n  vl = map (fun r => AE.get r ae) args ->\n  eval_operation ge (Vptr sp Ptrofs.zero) op e##args m = Some v ->\n  let (op', args') := op_strength_reduction op args vl in\n  exists w, eval_operation ge (Vptr sp Ptrofs.zero) op' e##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- (* add 1 *)\n  rewrite Val.add_commut in H0. InvApproxRegs; SimplVM; inv H0. apply make_addimm_correct; auto.\n- (* add 2 *)\n  InvApproxRegs; SimplVM; inv H0. apply make_addimm_correct; auto.\n- (* addshift *)\n  InvApproxRegs; SimplVM; inv H0. rewrite eval_static_shift_correct. apply make_addimm_correct; auto.\n- (* sub *)\n  InvApproxRegs; SimplVM; inv H0. rewrite Val.sub_add_opp. apply make_addimm_correct; auto.\n- (* subshift *)\n  InvApproxRegs; SimplVM; inv H0. rewrite eval_static_shift_correct, Val.sub_add_opp. apply make_addimm_correct; auto.\n- (* mul 1 *)\n  rewrite Val.mul_commut in H0. InvApproxRegs; SimplVM; inv H0. apply make_mulimm_correct; auto.\n- (* mul 2*)\n  InvApproxRegs; SimplVM; inv H0. apply make_mulimm_correct; auto.\n- (* divs *)\n  assert (e#r2 = Vint n2). clear H0. InvApproxRegs; SimplVM; auto.\n  apply make_divimm_correct; auto.\n- (* divu *)\n  assert (e#r2 = Vint n2). clear H0. InvApproxRegs; SimplVM; auto.\n  apply make_divuimm_correct; auto.\n- (* and 1 *)\n  rewrite Val.and_commut in H0. InvApproxRegs; SimplVM; inv H0. apply make_andimm_correct; auto.\n- (* and 2 *)\n  InvApproxRegs; SimplVM; inv H0. apply make_andimm_correct; auto.\n- (* andshift *)\n  InvApproxRegs; SimplVM; inv H0. rewrite eval_static_shift_correct. apply make_andimm_correct; auto.\n- (* andimm *)\n  inv H; inv H0. apply make_andimm_correct; auto.\n- (* or 1 *)\n  rewrite Val.or_commut in H0. InvApproxRegs; SimplVM; inv H0. apply make_orimm_correct; auto.\n- (* or 2 *)\n  InvApproxRegs; SimplVM; inv H0. apply make_orimm_correct; auto.\n- (* orshift *)\n  InvApproxRegs; SimplVM; inv H0. rewrite eval_static_shift_correct. apply make_orimm_correct; auto.\n- (* xor 1 *)\n  rewrite Val.xor_commut in H0. InvApproxRegs; SimplVM; inv H0. apply make_xorimm_correct; auto.\n- (* xor 2 *)\n  InvApproxRegs; SimplVM; inv H0. apply make_xorimm_correct; auto.\n- (* xorshift *)\n  InvApproxRegs; SimplVM; inv H0. rewrite eval_static_shift_correct. apply make_xorimm_correct; auto.\n- (* bic *)\n  InvApproxRegs; SimplVM; inv H0. apply make_andimm_correct; auto.\n- (* bicshift *)\n  InvApproxRegs; SimplVM; inv H0. rewrite eval_static_shift_correct. apply make_andimm_correct; auto.\n- (* orn *)\n  InvApproxRegs; SimplVM; inv H0. apply make_orimm_correct; auto.\n- (* ornshift *)\n  InvApproxRegs; SimplVM; inv H0. rewrite eval_static_shift_correct. apply make_orimm_correct; auto.\n- (* eor *)\n  InvApproxRegs; SimplVM; inv H0. apply make_xorimm_correct; auto.\n- (* eorshift *)\n  InvApproxRegs; SimplVM; inv H0. rewrite eval_static_shift_correct. apply make_xorimm_correct; auto.\n- (* shl *)\n  InvApproxRegs; SimplVM; inv H0. apply make_shlimm_correct; auto.\n- (* shr *)\n  InvApproxRegs; SimplVM; inv H0. apply make_shrimm_correct; auto.\n- (* shru *)\n  InvApproxRegs; SimplVM; inv H0. apply make_shruimm_correct; auto.\n- (* zext *)\n  InvApproxRegs; SimplVM; inv H0. apply make_zext_correct; auto.\n- (* sext *)\n  InvApproxRegs; SimplVM; inv H0. apply make_sext_correct; auto.\n- (* addl 1 *)\n  rewrite Val.addl_commut in H0. InvApproxRegs; SimplVM; inv H0. apply make_addlimm_correct; auto.\n- (* addl 2 *)\n  InvApproxRegs; SimplVM; inv H0. apply make_addlimm_correct; auto.\n- (* addshift *)\n  InvApproxRegs; SimplVM; inv H0. rewrite eval_static_shiftl_correct. apply make_addlimm_correct; auto.\n- (* addext *)\n  InvApproxRegs; SimplVM; inv H0. rewrite eval_static_extend_correct. apply make_addlimm_correct; auto.\n- (* subl *)\n  InvApproxRegs; SimplVM; inv H0. rewrite Val.subl_addl_opp. apply make_addlimm_correct; auto.\n- (* sublshift *)\n  InvApproxRegs; SimplVM; inv H0. rewrite eval_static_shiftl_correct, Val.subl_addl_opp. apply make_addlimm_correct; auto.\n- (* sublextend *)\n  InvApproxRegs; SimplVM; inv H0. rewrite eval_static_extend_correct, Val.subl_addl_opp. apply make_addlimm_correct; auto.\n- (* mull 1 *)\n  rewrite Val.mull_commut in H0. InvApproxRegs; SimplVM; inv H0. apply make_mullimm_correct; auto.\n- (* mull 2 *)\n  InvApproxRegs; SimplVM; inv H0. apply make_mullimm_correct; auto.\n- (* divl *)\n  assert (e#r2 = Vlong n2). clear H0. InvApproxRegs; SimplVM; auto.\n  apply make_divlimm_correct; auto.\n- (* divlu *)\n  assert (e#r2 = Vlong n2). clear H0. InvApproxRegs; SimplVM; auto.\n  apply make_divluimm_correct; auto.\n- (* andl 1 *)\n  rewrite Val.andl_commut in H0. InvApproxRegs; SimplVM; inv H0. apply make_andlimm_correct; auto.\n- (* andl 2 *)\n  InvApproxRegs; SimplVM; inv H0. apply make_andlimm_correct; auto.\n- (* andlshift *)\n  InvApproxRegs; SimplVM; inv H0. rewrite eval_static_shiftl_correct. apply make_andlimm_correct; auto.\n- (* andlimm *)\n  inv H; inv H0. apply make_andlimm_correct; auto.\n- (* orl 1 *)\n  rewrite Val.orl_commut in H0. InvApproxRegs; SimplVM; inv H0. apply make_orlimm_correct; auto.\n- (* orl 2 *)\n  InvApproxRegs; SimplVM; inv H0. apply make_orlimm_correct; auto.\n- (* orlshift *)\n  InvApproxRegs; SimplVM; inv H0. rewrite eval_static_shiftl_correct. apply make_orlimm_correct; auto.\n- (* xorl 1 *)\n  rewrite Val.xorl_commut in H0. InvApproxRegs; SimplVM; inv H0. apply make_xorlimm_correct; auto.\n- (* xorl 2 *)\n  InvApproxRegs; SimplVM; inv H0. apply make_xorlimm_correct; auto.\n- (* xorlshift *)\n  InvApproxRegs; SimplVM; inv H0. rewrite eval_static_shiftl_correct. apply make_xorlimm_correct; auto.\n- (* bicl *)\n  InvApproxRegs; SimplVM; inv H0. apply make_andlimm_correct; auto.\n- (* biclshift *)\n  InvApproxRegs; SimplVM; inv H0. rewrite eval_static_shiftl_correct. apply make_andlimm_correct; auto.\n- (* ornl *)\n  InvApproxRegs; SimplVM; inv H0. apply make_orlimm_correct; auto.\n- (* ornlshift *)\n  InvApproxRegs; SimplVM; inv H0. rewrite eval_static_shiftl_correct. apply make_orlimm_correct; auto.\n- (* eorl *)\n  InvApproxRegs; SimplVM; inv H0. apply make_xorlimm_correct; auto.\n- (* eorlshift *)\n  InvApproxRegs; SimplVM; inv H0. rewrite eval_static_shiftl_correct. apply make_xorlimm_correct; auto.\n- (* shll *)\n  InvApproxRegs; SimplVM; inv H0. apply make_shllimm_correct; auto.\n- (* shrl *)\n  InvApproxRegs; SimplVM; inv H0. apply make_shrlimm_correct; auto.\n- (* shrlu *)\n  InvApproxRegs; SimplVM; inv H0. apply make_shrluimm_correct; auto.\n- (* cond *)\n  inv H0. apply make_cmp_correct; auto.\n- (* select *)\n  inv H0. apply make_select_correct; congruence.\n- (* mulf 1 *)\n  InvApproxRegs; SimplVM; inv H0. rewrite <- H2. apply make_mulfimm_correct; auto.\n- (* mulf 2 *)\n  InvApproxRegs; SimplVM; inv H0. fold (Val.mulf (Vfloat n1) e#r2).\n  rewrite <- H2. apply make_mulfimm_correct_2; auto.\n- (* mulfs 1 *)\n  InvApproxRegs; SimplVM; inv H0. rewrite <- H2. apply make_mulfsimm_correct; auto.\n- (* mulfs 2 *)\n  InvApproxRegs; SimplVM; inv H0. fold (Val.mulfs (Vsingle n1) e#r2).\n  rewrite <- H2. apply make_mulfsimm_correct_2; auto.\n- (* default *)\n  exists v; auto.\nQed.\n\nLemma addr_strength_reduction_correct:\n  forall addr args vl res,\n  vl = map (fun r => AE.get r ae) args ->\n  eval_addressing ge (Vptr sp Ptrofs.zero) addr e##args = Some res ->\n  let (addr', args') := addr_strength_reduction addr args vl in\n  exists res', eval_addressing ge (Vptr sp Ptrofs.zero) addr' e##args' = Some res' /\\ Val.lessdef res res'.\nProof.\n  intros until res. unfold addr_strength_reduction.\n  destruct (addr_strength_reduction_match addr args vl); simpl;\n  intros VL EA; InvApproxRegs; SimplVM; try (inv EA).\n- econstructor; split; eauto. inv H0; simpl; auto. rewrite H2.\n  unfold Genv.symbol_address. destruct (Genv.find_symbol ge symb); auto.\n- rewrite Ptrofs.add_zero_l. econstructor; split; eauto.\n  inv H0; auto. rewrite H2; auto.\n- rewrite Ptrofs.add_zero_l. econstructor; split; eauto. \n  inv H; auto. rewrite H3; auto.\n- rewrite Ptrofs.add_zero_l. econstructor; split; eauto. \n  inv H0; auto. rewrite H3. rewrite Ptrofs.add_commut; auto.\n- econstructor; split; eauto. rewrite Val.addl_commut. auto.\n- econstructor; split; eauto.\n- rewrite Ptrofs.add_zero_l. rewrite a64_range. econstructor; split; eauto.\n  inv H; auto. rewrite H3; auto.\n- rewrite a64_range. econstructor; split; eauto.\n- rewrite Ptrofs.add_zero_l, eval_static_extend_correct.\n  econstructor; split; eauto. inv H; auto. rewrite H3; auto.\n- rewrite eval_static_extend_correct. \n  econstructor; split; eauto.\n- exists res; auto.\nQed.\n\nEnd STRENGTH_REDUCTION.\n", "meta": {"author": "AbsInt", "repo": "CompCert", "sha": "f4ddce910894bf6dbdf83c0642c4b275854b60dd", "save_path": "github-repos/coq/AbsInt-CompCert", "path": "github-repos/coq/AbsInt-CompCert/CompCert-f4ddce910894bf6dbdf83c0642c4b275854b60dd/aarch64/ConstpropOpproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808532, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2714316341904266}}
{"text": "Require Import ConcurExec.\nRequire Import Morphisms.\nRequire Import ProofAutomation.\nRequire Import Helpers.ListStuff.\nRequire Import List.\nRequire Import Omega.\n\nImport ListNotations.\n\nGlobal Set Implicit Arguments.\nGlobal Generalizable All Variables.\n\n\n(** Inclusion of traces across state abstraction *)\n\nSection StateAbstraction.\n\n  Variable OpLo : Type -> Type.\n\n  Variable StateLo : Type.\n  Variable StateHi : Type.\n  Variable absR : StateLo -> StateHi -> Prop.\n\n  Variable lo_step : OpSemantics OpLo StateLo.\n  Variable hi_step : OpSemantics OpLo StateHi.\n\n  Hint Constructors exec_tid.\n\n  Definition op_abs := forall T (op : OpLo T) s1 s1' s2 tid r evs,\n    absR s1 s2 ->\n    lo_step op tid s1 r s1' evs ->\n      exists s2',\n        absR s1' s2' /\\\n        hi_step op tid s2 r s2' evs.\n\n  Variable op_abs_holds : op_abs.\n\n  Theorem atomic_exec_abs : forall `(p : proc OpLo T) s1 s1' s2 tid r evs,\n    absR s1 s2 ->\n    atomic_exec lo_step p tid s1 r s1' evs ->\n      exists s2',\n        absR s1' s2' /\\\n        atomic_exec hi_step p tid s2 r s2' evs.\n  Proof.\n    intros.\n    generalize dependent s2.\n    induct H0; eauto.\n    - edestruct IHatomic_exec1; intuition eauto.\n      edestruct IHatomic_exec2; intuition eauto.\n    - eapply op_abs_holds in H; eauto; deex.\n      eexists; eauto.\n    - edestruct IHatomic_exec; intuition eauto.\n  Qed.\n\n  Theorem exec_tid_abs : forall `(p : proc OpLo T) s1 s1' s2 tid res spawned evs,\n    absR s1 s2 ->\n    exec_tid lo_step tid s1 p s1' res spawned evs ->\n      exists s2',\n        absR s1' s2' /\\\n        exec_tid hi_step tid s2 p s2' res spawned evs.\n  Proof.\n    intros.\n    induct H0; eauto.\n    - eapply op_abs_holds in H0; eauto; deex.\n      eexists; eauto.\n    - eapply atomic_exec_abs in H0; eauto; deex.\n      eexists; eauto.\n  Qed.\n\n  Theorem trace_incl_abs :\n    forall s1 s2 (ts : threads_state OpLo) tr,\n      absR s1 s2 ->\n      exec lo_step s1 ts tr ->\n      exec hi_step s2 ts tr.\n  Proof.\n    intros.\n    generalize dependent s2.\n    induct H0; eauto.\n    - eapply exec_tid_abs in H3; propositional; eauto.\n  Qed.\n\nEnd StateAbstraction.\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/Abstraction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2714025177952416}}
{"text": "From Tealeaves.Classes Require Export\n  Functor\n  Monad\n  Decorated.Functor\n  Decorated.Monad\n  Traversable.Functor\n  Traversable.Monad\n  DT.Functor\n  DT.Monad.\n\nFrom Tealeaves.Classes.Kleisli Require Export\n  Monad\n  Decorated.Functor\n  Decorated.Monad\n  Traversable.Functor\n  Traversable.Monad\n  DT.Functor\n  DT.Monad.\n\nImport Monoid.Notations.\nImport Product.Notations.\nImport Functor.Notations.\nImport Kleisli.Monad.Notations.\nImport Kleisli.Decorated.Monad.Notations.\nImport Kleisli.Traversable.Monad.Notations.\nImport Kleisli.DT.Monad.Notations.\nImport Comonad.Notations.\n\n#[local] Generalizable Variables A B C.\n\nModule Operations.\n  Section with_kleisli.\n\n    Context\n      (W : Type)\n      (T : Type -> Type)\n      `{Binddt W T T}\n      `{Return T}.\n\n    #[export] Instance Join_Binddt: Join T := fun A => binddt T (fun A => A) (B := A) (A := T A) (extract (W ×)).\n    #[export] Instance Decorate_Binddt: Decorate W T := fun A => binddt T (fun A => A) (ret T).\n    #[export] Instance Dist_Binddt: Dist T := fun G _ _ _ A => binddt T G (fmap G (ret T) ∘ extract (W ×)).\n\n  End with_kleisli.\nEnd Operations.\n\nImport Operations.\n\nSection with_monad.\n\n  Context\n    (W : Type)\n    (T : Type -> Type)\n    `{Kleisli.DT.Monad.Monad W T}.\n\n  Import DT.Monad.Derived.\n\n  (** *** Monad instance *)\n  (******************************************************************************)\n  Lemma ret_natural : Natural (@ret T _).\n  Proof.\n    constructor.\n    - typeclasses eauto.\n    - typeclasses eauto.\n    - intros. unfold_ops @Fmap_Binddt.\n      rewrite (kdtm_binddt0 W T _ _ (G := fun A => A)).\n      reflexivity.\n  Qed.\n\n  Lemma join_natural : Natural (@join T _).\n  Proof.\n    constructor.\n    - typeclasses eauto.\n    - typeclasses eauto.\n    - intros.\n      unfold_ops @Fmap_compose.\n      unfold_ops @Fmap_Binddt.\n      unfold_ops @Join_Binddt.\n      do 4 change (binddt T (fun A0 : Type => A0) ?f) with (bindd T (T := T) f).\n      unfold_compose_in_compose.\n      rewrite (kmond_bindd2_T W T). (* left *)\n      rewrite (kmond_bindd2_T W T). (* right *)\n      rewrite (Decorated.Monad.Derived.dm_kleisli_star2 T).\n      reassociate -> near (extract (W ×)).\n      rewrite (Derived.dm_kleisli_star1 T).\n      fequal.\n      rewrite cokleisli_id_l.\n      reflexivity.\n  Qed.\n\n  Lemma join_ret : `(join T ∘ ret T = @id (T A)).\n  Proof.\n    intros.\n    unfold_ops @Join_Binddt.\n    unfold_compose_in_compose.\n    rewrite (kdtm_binddt0 W T _ _ (G := fun A => A)).\n    now rewrite bimonad_baton.\n  Qed.\n\n  Lemma join_fmap_ret : `(join T ∘ fmap T (ret T) = @id (T A)).\n  Proof.\n    intros.\n    unfold_ops @Fmap_Binddt.\n    unfold_ops @Join_Binddt.\n    unfold_compose_in_compose.\n    change (binddt T (fun A0 : Type => A0) (extract (prod W) (A := T A)))\n      with (fmap (fun A => A) (binddt T (fun A0 : Type => A0) (extract (prod W) (A := T A)))).\n    rewrite (kdtm_binddt2 W T _ _ _ (G1 := fun A => A) (G2 := fun A => A)).\n    rewrite (dtm_kleisli_70 W T).\n    rewrite <- (natural (ϕ := @extract (W ×) _)).\n    change (fmap (fun A => A) ?f) with f.\n    rewrite <- (kdtm_binddt1 W T).\n    fequal. now rewrite Mult_compose_identity1.\n    now rewrite Mult_compose_identity1.\n  Qed.\n\n  Lemma join_join :\n    `(join T ∘ join T (A := T A) = join T ∘ fmap T (join T)).\n  Proof.\n    intros.\n    unfold_ops @Join_Binddt.\n    unfold_compose_in_compose.\n    unfold compose at 4. (* hidden  *)\n    rewrite (binddt_fmap T (fun A => A) _ _ _ (extract (W ×)) (binddt T (fun A0 : Type => A0) (extract (prod W)))).\n    do 3 change (binddt T (fun A0 : Type => A0) ?f) with (bindd T (T := T) f).\n    (* Merge LHS *)\n    rewrite (kmond_bindd2 T).\n    fequal. ext [w a]. cbn.\n    now rewrite preincr_extract2.\n  Qed.\n\n  #[local] Instance: Classes.Monad.Monad T :=\n    {| mon_ret_natural := ret_natural;\n       mon_join_natural := join_natural;\n       mon_join_ret := join_ret;\n       mon_join_fmap_ret := join_fmap_ret;\n       mon_join_join := join_join;\n    |}.\n\n  (** *** Decorated functor instance *)\n  (******************************************************************************)\n  Lemma dec_dec : forall (A : Type),\n      dec T ∘ dec T = fmap T (cojoin (W ×)) ∘ dec T (A := A).\n  Proof.\n    intros.\n    unfold_ops @Decorate_Binddt.\n    change (fmap T (coμ (prod W) (A := A)))\n      with (fmap (fun A => A) (fmap T (coμ (A := A) (prod W)))).\n    rewrite (fmap_binddt T (fun A => A)); try typeclasses eauto.\n    do 3 change (binddt T (fun A0 : Type => A0) ?f) with (bindd T (T := T) f).\n    (* Merge LHS *)\n    rewrite (kmond_bindd2 T).\n    fequal.\n    change (ret T) with (ret T ∘ (@id (W * A))) at 2.\n    rewrite (Derived.dm_kleisli_star1 T).\n    change (fmap (fun A => A) ?f) with f.\n    rewrite (natural (ϕ := @ret T _ )).\n    change (fmap (fun A => A) ?f) with f.\n    ext [w a]. cbn. reflexivity.\n  Qed.\n\n  Lemma dec_extract : forall (A : Type),\n      fmap T (extract (W ×)) ∘ dec T = @id (T A).\n  Proof.\n    intros.\n    unfold_ops @Decorate_Binddt.\n    unfold_ops @Fmap_Binddt.\n    do 2 change (binddt T (fun A0 : Type => A0) ?f) with (bindd T (T := T) f).\n    rewrite (kmond_bindd2 T).\n    rewrite (Derived.dm_kleisli_star2 T).\n    rewrite Monad.ToFunctor.kcompose01.\n    change (ret T (A := W * A)) with (ret T ∘ @id (W * A)).\n    reassociate <-. change (?g ∘ id) with g.\n    rewrite (natural (ϕ := @ret T _ )).\n    apply (kmond_bindd1 T).\n  Qed.\n\n  Lemma dec_natural : Natural (@dec W T _).\n  Proof.\n    constructor.\n    - typeclasses eauto.\n    - typeclasses eauto.\n    - intros. unfold_ops @Fmap_compose.\n      unfold_ops @Fmap_Binddt.\n      unfold_ops @Decorate_Binddt.\n      do 2 change (binddt T (fun A0 : Type => A0) ?f) with (bindd T (T := T) f).\n      rewrite (kmond_bindd2 T).\n      rewrite (kmond_bindd2 T).\n      fequal.\n      change (ret T (A := W * A)) with (ret T ∘ @id (W * A)).\n      rewrite (Derived.dm_kleisli_star5 T).\n      reassociate -> near (extract (W ×)).\n      rewrite (Derived.dm_kleisli_star1 T).\n      now rewrite cokcompose_misc1.\n  Qed.\n\n  #[local] Instance: Decorated.Functor.DecoratedFunctor W T :=\n    {| dfun_dec_natural := dec_natural;\n       dfun_dec_dec := dec_dec;\n       dfun_dec_extract := dec_extract;\n    |}.\n\n  (** *** Decorated monad instance *)\n  (******************************************************************************)\n  Lemma dmon_ret_ : forall (A : Type),\n      dec T ∘ ret T = ret T ∘ pair Ƶ (B:=A).\n  Proof.\n    intros.\n    unfold_ops @Decorate_Binddt.\n    change (binddt T (fun A0 : Type => A0) ?f) with (bindd T (T := T) f).\n    now rewrite (kmond_bindd0 T).\n  Qed.\n\n  Lemma dmon_join_ : forall (A : Type),\n      dec T ∘ join T (A:=A) = join T ∘ fmap T (shift T) ∘ dec T ∘ fmap T (dec T).\n  Proof.\n    intros. unfold shift, strength.\n    unfold_ops @Decorate_Binddt.\n    unfold_ops @Fmap_Binddt.\n    unfold_ops @Join_Binddt.\n    repeat change (binddt T (fun A0 : Type => A0) ?f) with (bindd T (T := T) f).\n    unfold_compose_in_compose.\n    repeat rewrite (kmond_bindd2 T).\n    fequal. reassociate -> near (extract (W ×)).\n    rewrite (Derived.dm_kleisli_star1 T).\n    rewrite (Derived.dm_kleisli_star1 T).\n    rewrite cokcompose_misc1.\n    rewrite cokleisli_id_l.\n    rewrite (Derived.dm_kleisli_star2 T).\n    ext [w t].\n    unfold Monad.kcompose.\n    rewrite (Monad.kmon_bind0 T).\n    unfold compose; cbn.\n    compose near t on right.\n    rewrite (kmond_bindd2 T).\n    compose near t on right.\n    rewrite (kmond_bindd2 T).\n    fequal. ext [w' a].\n    cbn. compose near (w', a) on right.\n    rewrite (kmond_bindd0 T).\n    unfold compose. cbn.\n    compose near (w', a) on right.\n    rewrite preincr_ret.\n    unfold compose; cbn.\n    compose near (id w, (w', a)) on right.\n    rewrite (kmond_bindd0 T).\n    rewrite preincr_ret.\n    reflexivity.\n  Qed.\n\n  #[local] Instance: Decorated.Monad.DecoratedMonad W T :=\n    {| dmon_ret := dmon_ret_;\n       dmon_join := dmon_join_;\n    |}.\n\n  (** *** Traversable functor instance *)\n  (******************************************************************************)\n  Lemma dist_natural_T : forall (G : Type -> Type) (H2 : Fmap G) (H3 : Pure G) (H4 : Mult G),\n      Applicative G -> Natural (@dist T _ G H2 H3 H4).\n  Proof.\n    intros. constructor.\n    - typeclasses eauto.\n    - typeclasses eauto.\n    - intros.\n      unfold_ops @Fmap_compose @Dist_Binddt @Fmap_Binddt.\n      change_left (fmap G (fmap T f) ∘ bindt T G (fmap G (ret T))).\n      rewrite (fmap_bindt T G).\n      rewrite (fun_fmap_fmap G).\n      (* RHS *)\n      change_right (\n          bindt T G (fmap G (ret T)) ∘\n            bind T (ret T ∘ fmap G f)).\n      rewrite (bindt_bind T G).\n      reassociate <- on right.\n      rewrite (ktm_bindt0 T); [|assumption].\n      rewrite (fun_fmap_fmap G).\n      rewrite (natural (ϕ := @ret T _)).\n      reflexivity.\n  Qed.\n\n  Lemma dist_morph_T : forall (G1 G2 : Type -> Type) (H2 : Fmap G1) (H3 : Pure G1) (H4 : Mult G1) (H5 : Fmap G2)\n                         (H6 : Pure G2) (H7 : Mult G2) (ϕ : forall A : Type, G1 A -> G2 A),\n      ApplicativeMorphism G1 G2 ϕ -> forall A : Type, dist T G2 ∘ fmap T (ϕ A) = ϕ (T A) ∘ dist T G1.\n  Proof.\n    introv morph. inversion morph.\n    intros.\n    unfold_ops @Dist_Binddt @Fmap_Binddt.\n    change (fmapdt T G2 (extract (prod W)) ∘ fmap T (ϕ A)\n            = ϕ (T A) ∘ traverse T G1 (@id (G1 A))).\n    change (@Fmap_Binddt T W H0 H)\n      with (@Derived.Fmap_Fmapdt T W _).\n    rewrite (Derived.fmapdt_fmap T G2).\n    rewrite (trf_traverse_morphism T).\n    rewrite <- (natural (ϕ := @extract (W ×) _)).\n    reflexivity.\n  Qed.\n\n  Lemma dist_unit_T : forall A : Type,\n      dist T (fun A0 : Type => A0) = @id (T A).\n  Proof.\n    intros. unfold_ops @Dist_Binddt.\n    apply (kdtm_binddt1 W T).\n  Qed.\n\n  Lemma dist_linear_T : forall (G1 : Type -> Type) (H2 : Fmap G1) (H3 : Pure G1) (H4 : Mult G1),\n      Applicative G1 ->\n      forall (G2 : Type -> Type) (H6 : Fmap G2) (H7 : Pure G2) (H8 : Mult G2),\n        Applicative G2 -> forall A : Type, dist T (G1 ∘ G2) (A := A) = fmap G1 (dist T G2) ∘ dist T G1.\n  Proof.\n    intros. unfold_ops @Dist_Binddt.\n    rewrite (kdtm_binddt2 W T); try typeclasses eauto.\n    fequal.\n    rewrite (kcompose_dtm_33 W T).\n    change (fmap G1 (ret T (A := G2 A))) with (fmap G1 (ret T) ∘ @id (G1 (G2 A))).\n    rewrite (Derived.kcompose_tm31 (fmap G2 (ret T))).\n    reflexivity.\n  Qed.\n\n  #[export] Instance: Traversable.Functor.TraversableFunctor T :=\n    {| dist_natural := dist_natural_T;\n       dist_morph := dist_morph_T;\n       dist_unit := dist_unit_T;\n       dist_linear := dist_linear_T;\n    |}.\n\n  (** *** Decorated Traversable functor instance *)\n  (******************************************************************************)\n  Lemma dtfun_compat_T : forall (G : Type -> Type) (H2 : Fmap G) (H3 : Pure G) (H4 : Mult G),\n      Applicative G -> forall A : Type,\n        dist T G ∘ fmap T (strength G) ∘ dec (A := G A) T = fmap G (dec T) ∘ dist T G.\n  Proof.\n    intros. unfold_ops @Dist_Binddt @Fmap_Binddt @Decorate_Binddt.\n    change (fmapdt T G (extract (prod W)) ∘ fmapd T (strength G ∘ extract (prod W)) ∘ fmapd T (@id (W * G A)) =\n              fmap G (fmapd T id) ∘ fmapdt T G (extract (prod W))).\n    rewrite (fmapdt_fmapd T G).\n    rewrite (fmapdt_fmapd T G).\n    rewrite (fmapd_fmapdt T G).\n    rewrite (cobind_id (W ×)).\n    rewrite (fun_fmap_id G).\n    fequal. ext [w a].\n    reflexivity.\n  Qed.\n\n  #[export] Instance: DT.Functor.DecoratedTraversableFunctor W T :=\n    {| dtfun_compat := dtfun_compat_T;\n    |}.\n\n  (** *** Traversable monad instance *)\n  (******************************************************************************)\n  Lemma trvmon_ret_T : forall (G : Type -> Type) (H3 : Fmap G) (H4 : Pure G) (H5 : Mult G),\n      Applicative G -> forall A : Type, dist T G ∘ ret T (A := G A) = fmap G (ret T).\n  Proof.\n    intros. unfold_ops @Dist_Binddt @Fmap_Binddt.\n    rewrite (kdtm_binddt0 W T); [|assumption].\n    ext a. reflexivity.\n  Qed.\n\n\n  Lemma trvmon_join_T : forall (G : Type -> Type) (H3 : Fmap G) (H4 : Pure G) (H5 : Mult G),\n      Applicative G -> forall A : Type, dist T G ∘ join T = fmap G (join T) ∘ dist (T ∘ T) G (A := A).\n  Proof.\n    intros.\n    unfold_ops @Dist_compose.\n    unfold_ops @Dist_Binddt @Fmap_Binddt @Join_Binddt.\n    change_left (bindt T G (fmap G (ret T)) ∘ bind T (@id (T (G A)))).\n    change_right (fmap G (bind T (@id (T A)))\n                    ∘ (bindt T G (fmap G (ret T))\n                         ∘ bind T (ret T ∘ bindt T G (fmap G (ret T))))).\n    rewrite (bindt_bind T G).\n    rewrite (bindt_bind T G).\n    reassociate <-. rewrite (ktm_bindt0 T); [|typeclasses eauto].\n    rewrite (bind_bindt T G).\n    reassociate <- on right.\n    rewrite (fun_fmap_fmap G).\n    rewrite (kmon_bind0 T).\n    rewrite (fun_fmap_id G).\n    reflexivity.\n  Qed.\n\n  #[export] Instance: Traversable.Monad.TraversableMonad T :=\n    {| trvmon_ret := trvmon_ret_T;\n      trvmon_join := trvmon_join_T;\n    |}.\n\n  (** *** Decorated Traversable monad instance *)\n  (******************************************************************************)\n  #[export] Instance: DT.Monad.DecoratedTraversableMonad W T :=\n    ltac:(constructor; typeclasses eauto).\n\nEnd with_monad.\n\n#[local] Generalizable Variables T W.\n\nModule AlgebraicToKleisli.\n\n  Context\n    `{Monoid W}\n    `{fmapT : Fmap T}\n    `{distT : Dist T}\n    `{joinT : Join T}\n    `{decorateT : Decorate W T}\n    `{Return T}\n    `{! Classes.DT.Monad.DecoratedTraversableMonad W T}.\n\n  #[local] Instance binddt' : Binddt W T T := ToKleisli.Binddt_ddj T.\n\n  Definition fmap' : Fmap T := Derived.Fmap_Binddt T.\n  Definition join' : Join T := Operations.Join_Binddt W T.\n  Definition decorate' : Decorate W T := Operations.Decorate_Binddt W T.\n  Definition dist' : Dist T := Operations.Dist_Binddt W T.\n\n  Goal fmapT = fmap'.\n  Proof.\n    unfold fmap'. unfold_ops @Derived.Fmap_Binddt.\n    unfold binddt, binddt'.\n    unfold_ops @ToKleisli.Binddt_ddj.\n    ext A B f.\n    unfold_ops @Fmap_I.\n    rewrite (dist_unit T).\n    change (?f ∘ id) with f.\n    do 2 rewrite <- (fun_fmap_fmap T).\n    do 2 reassociate <- on right.\n    rewrite (mon_join_fmap_ret T).\n    change (id ∘ ?f) with f.\n    reassociate -> on right.\n    rewrite (dfun_dec_extract W T).\n    reflexivity.\n  Qed.\n\n  Goal forall G `{Applicative G}, @distT G _ _ _ = @dist' G _ _ _.\n  Proof.\n    intros.\n    unfold dist'. unfold_ops @Operations.Dist_Binddt.\n    unfold binddt, binddt'.\n    unfold_ops @ToKleisli.Binddt_ddj.\n    ext A.\n    rewrite <- (fun_fmap_fmap T).\n    unfold_compose_in_compose.\n    reassociate <- on right.\n    reassociate -> near (fmap T (fmap G (ret T (A := A)))).\n    change (fmap T (fmap G (ret T (A := A))))\n      with ((fmap (T ○ G) (ret T (A := A)))).\n    rewrite <- (natural (ϕ := @dist T _ G _ _ _)).\n    unfold_ops @Fmap_compose.\n    reassociate <- on right.\n    rewrite (fun_fmap_fmap G).\n    rewrite (mon_join_fmap_ret T).\n    rewrite (fun_fmap_id G).\n    reassociate -> on right.\n    rewrite (dfun_dec_extract W T).\n    reflexivity.\n  Qed.\n\n  Goal joinT = join'.\n  Proof.\n    unfold join'. unfold_ops @Operations.Join_Binddt.\n    unfold binddt, binddt'.\n    unfold_ops @ToKleisli.Binddt_ddj.\n    ext A.\n    rewrite (dist_unit T).\n    reassociate -> on right.\n    rewrite (dfun_dec_extract W T).\n    reflexivity.\n  Qed.\n\n  Goal decorateT = decorate'.\n  Proof.\n    unfold decorate'. unfold_ops @Operations.Decorate_Binddt.\n    unfold binddt, binddt'.\n    unfold_ops @ToKleisli.Binddt_ddj @Fmap_I.\n    ext A.\n    rewrite (dist_unit T).\n    change (?f ∘ id) with f.\n    rewrite (mon_join_fmap_ret T).\n    reflexivity.\n  Qed.\n\nEnd AlgebraicToKleisli.\n\nModule KleisliToAlgebraic.\n\n  Context\n    `{binddtT : Binddt W T T}\n    `{Monoid W}\n    `{Return T}\n    `{! Classes.Kleisli.DT.Monad.Monad W T}.\n\n  #[local] Instance fmap' : Fmap T := Derived.Fmap_Binddt T.\n  #[local] Instance dist' : Dist T := Operations.Dist_Binddt W T.\n  #[local] Instance join' : Join T := Operations.Join_Binddt W T.\n  #[local] Instance decorate' : Decorate W T := Operations.Decorate_Binddt W T.\n\n  Definition binddt' : Binddt W T T := ToKleisli.Binddt_ddj T.\n\n  Import Derived.\n\n  Goal forall G `{Applicative G}, @binddtT G _ _ _ = @binddt' G _ _ _ .\n  Proof.\n    intros.\n    unfold binddt'. unfold_ops @ToKleisli.Binddt_ddj.\n    ext A B f.\n    unfold fmap at 2, fmap', Fmap_Binddt.\n    unfold dist, dist', Dist_Binddt.\n    unfold dec, decorate', Decorate_Binddt.\n    change_right (fmap G (join T) ∘ bindt T G (fmap G (ret T))\n                    ∘ fmap T f ∘ bindd T (ret T)).\n    reassociate -> on right.\n    unfold fmap'.\n    change (@Fmap_Binddt T W _ _) with (@Derived.Fmap_Bindd T _ W _).\n    rewrite (Derived.fmap_bindd T).\n    reassociate -> on right.\n    unfold_compose_in_compose.\n    rewrite (Derived.bindt_bindd T G).\n    reassociate <- on right.\n    Set Keyed Unification.\n    rewrite (Kleisli.DT.Monad.Derived.bindt_fmap T G).\n    Unset Keyed Unification.\n    rewrite (ktm_bindt0 T); [| assumption].\n    unfold join, join'; unfold_ops @Operations.Join_Binddt.\n    unfold compose at 2.\n    rewrite (kdtm_binddt2 W T _ _ _ (G1 := G) (G2 := fun A => A)).\n    change_left (binddt T G f).\n    fequal. now rewrite Mult_compose_identity1.\n    change (extract (A := ?A) (W ×)) with (id ∘ extract (A := A) (W ×)).\n    rewrite (Derived.dtm_kleisli_37 W T (A := A) (C := B) (B := T B) (G2 := fun A => A)).\n    rewrite (@Traversable.Monad.Derived.kcompose_tm21 T _ _ _ G); [|assumption].\n    rewrite (fun_fmap_id G).\n    reflexivity.\n  Qed.\n\nEnd KleisliToAlgebraic.\n", "meta": {"author": "dunnl", "repo": "tealeaves", "sha": "8dd6ba8acdd097f6e474ae2a1a9b10f5cc9ca65b", "save_path": "github-repos/coq/dunnl-tealeaves", "path": "github-repos/coq/dunnl-tealeaves/tealeaves-8dd6ba8acdd097f6e474ae2a1a9b10f5cc9ca65b/Tealeaves/Classes/Equivalences/DT/Monad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.27140251779524155}}
{"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(*          Refinement proof for PTIntro layer                         *)\n(*                                                                     *)\n(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)\n(*                                                                     *)\n(*          Yale Flint Group                                           *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** This file provide the contextual refinement proof between MAL layer and MPTIntro layer*)\nRequire Import PTIntroGenDef.\nRequire Export PTIntroGenAccessorDef.\n\n(** * Definition of the refinement relation*)\nSection Refinement.\n\n  Section WITHMEM.\n\n    Context `{Hstencil: Stencil}.\n    Context `{Hmem: Mem.MemoryModel}.\n    Context `{Hmwd: UseMemWithData mem}.\n    \n    Require Import LoadStoreSem1.\n    Require Import XOmega.\n    Require Import HostAccess1.\n    Require Import GuestAccessIntel1.\n    Require Import HostAccess2.\n    Require Import LoadStoreGeneral.\n\n    Notation lLoad := (fun F V => exec_loadex1 (F:=F) (V:=V)).\n    Notation hLoad := (fun F V => exec_loadex2 (F:=F) (V:=V)).\n\n    Lemma load_correct:\n      load_accessor_sim_def HDATAOps LDATAOps (one_crel HDATA LDATA) hLoad lLoad.\n    Proof.\n      unfold load_accessor_sim_def. intros.\n      pose proof H2 as Hmatch.\n      inv H2. inv match_extcall_states.\n\n      unfold exec_loadex2 in *. \n      unfold exec_loadex1. \n      unfold exec_host_load1, exec_host_load2 in *. inv H4.\n      exploit (eval_addrmode_correct ge1 ge2 a); eauto. intros HW.\n      Local Opaque Z.sub.\n      simpl in *. revert H1. inv match_related. subrewrite''. intros HLoad.\n      destruct (eval_addrmode ge1 a rs1) eqn: Hev; contra_inv.\n      - (* addr is Vint*)\n        inv HW. destruct (ihost d2) eqn:HPH; contra_inv.\n        destruct (pg d2) eqn:HPE; contra_inv.\n        destruct (ikern d2) eqn:HPK; contra_inv.\n        specialize (valid_PT refl_equal).\n        + (* host *)\n          generalize match_match; intros HM. inv match_match. \n          inv H1. inv relate_PT_re. \n          * (* PT = -1 *)\n            rewrite <- H7 in valid_PT; omega.  \n          * assert (HFB: Genv.find_symbol ge2 PTPool_LOC = Some b).\n            {\n              inv H0. congruence.\n            }\n            rewrite HFB. lift_trivial. subrewrite'.\n            assert (valid_PT': 0 <= PT d1 < 64) by omega.\n            specialize (H5 _ valid_PT').\n            set (pt := (ZMap.get (PT d1) (ptpool d1))) in *. inv H5.\n            assert (HI: 0<= PDX (Int.unsigned i) <= PDX Int.max_unsigned).\n            {\n              specialize (Int.unsigned_range_2 i).\n              clear. unfold PDX. Local Transparent Z.sub.\n              xomega. Local Opaque Z.sub.\n            }\n            specialize (H7 _ HI).\n            destruct H7 as [v[HLD [_ HP]]].    \n            assert (HI1: 0<= PTX (Int.unsigned i) <= PTX Int.max_unsigned).\n            {\n              unfold PTX; change ((Int.max_unsigned / 4096) mod 1024) with 1023.\n              specialize (Z_mod_lt (Int.unsigned i/PgSize) one_k).\n              omega.\n            }\n            (*unfold PMap, ZMap.t, PMap.t in *.*)\n            inv HP; try rewrite <- H9 in HLoad; try rewrite <- H5 in HLoad; contra_inv.\n            pose proof relate_PMap_re as HPP.\n            inv HPP. specialize (H9 _ valid_PT' _ HI pi pdx).\n            rewrite H5 in H9. specialize (H9 refl_equal _ HI1).\n            destruct H9 as [v1[HLD1 HP]].\n            rewrite Int.unsigned_repr; [|rewrite_omega]. \n            rewrite HLD, H7.\n            rewrite Z_div_plus_full_l; [|omega].\n            rewrite (Zdiv_small PT_PERM_PTU); [|omega].\n            rewrite Z.add_0_r. rewrite HLD1. clear HLD1.\n            destruct (zle (Int.unsigned i mod 4096) (4096 - size_chunk chunk)); contra_inv.\n            destruct (Zdivide_dec (align_chunk chunk) (Int.unsigned i mod 4096)\n                                  (Memdata.align_chunk_pos chunk)); contra_inv.\n            inv HP; try rewrite <- H11 in HLoad; contra_inv. \n            {\n              change (Int.unsigned Int.zero mod 4096) with 0; simpl.\n              eapply pagefault_correct; eauto.\n            }\n            {\n              rewrite <- H9 in HLoad; contra_inv. rewrite H12.\n              assert (HW1: (padr * PgSize + v) mod PgSize = v mod PgSize).\n              {\n                rewrite Zplus_mod.\n                rewrite Z_mod_mult.\n                rewrite Z.add_0_l.\n                apply Zmod_mod.\n              }\n              assert (HW2: (padr * PgSize + v) / PgSize = padr).\n              {\n                rewrite Z_div_plus_full_l; [|omega].\n                rewrite (Zdiv_small v). omega.\n                functional inversion H11; subst; omega.\n              }\n              rewrite HW1, HW2.\n              functional inversion H11; rewrite <- H13 in HLoad; contra_inv;\n              (rewrite Zmod_small; trivial; [|omega]; simpl;\n               eapply exec_flatmem_load_correct; eauto).\n            }\n        + (* guest *)\n          eapply guest_intel_load_correct1; eauto.\n      - (* adr is (b,ofs) *)\n        inv HW; subdestruct; eapply loadl_correct; eauto.\n    Qed.\n\n  End WITHMEM.\n\nEnd Refinement.", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/mm/PTIntroGenAccessor0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.4035668537353745, "lm_q1q2_score": 0.27133078320510245}}
{"text": "\nRequire Import VST.floyd.proofauto.\nRequire Import sll_singleton.\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 sll_card : Set :=\n    | sll_card_0 : sll_card\n    | sll_card_1 : sll_card -> sll_card.\n\nFixpoint sll (x: val) (s: (list Z)) (self_card: sll_card) {struct self_card} : mpred := match self_card with\n    | sll_card_0  =>  !!((x : val) = nullval) && !!((s : list Z) = ([] : list Z)) && emp\n    | sll_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)) * (sll (nxt : val) (s1 : list Z) (_alpha_513 : sll_card))\nend.\n\n\nDefinition sll_singleton_spec :=\n  DECLARE _sll_singleton\n   WITH x: val, p: val, a: val\n   PRE [ tint, (tptr (Tunion _sslval noattr)) ]\n   PROP( ssl_is_valid_int((x : val)); is_pointer_or_null((p : val)); is_pointer_or_null((a : val)) )\n   PARAMS(x; p)\n   SEP ((data_at Tsh (tarray (Tunion _sslval noattr) 1) [(inr (a : val))] (p : val)))\n   POST[ tvoid ]\n   EX y: val,\n   EX elems: (list Z),\n   EX _alpha_514: sll_card,\n   PROP( ((elems : list Z) = ([(force_signed_int (x : val))] : list Z)); is_pointer_or_null((y : val)) )\n   LOCAL()\n   SEP ((data_at Tsh (tarray (Tunion _sslval noattr) 1) [(inr (y : val))] (p : val)); (sll (y : val) (elems : list Z) (_alpha_514 : sll_card))).\n\nLemma sll_x_valid_pointerP x s self_card: sll x s self_card |-- valid_pointer x. Proof. destruct self_card; simpl; entailer;  entailer!; eauto. Qed.\nHint Resolve sll_x_valid_pointerP : valid_pointer.\nLemma sll_local_factsP x s self_card :\n  sll x s self_card|-- !!(((((x : val) = nullval)) -> (self_card = sll_card_0))/\\(((~ ((x : val) = nullval))) -> (exists _alpha_513, self_card = sll_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 sll_local_factsP : saturate_local.\nLemma unfold_sll_card_0  (x: val) (s: (list Z)) : sll x s (sll_card_0 ) =  !!((x : val) = nullval) && !!((s : list Z) = ([] : list Z)) && emp. Proof. auto. Qed.\nLemma unfold_sll_card_1 (_alpha_513 : sll_card) (x: val) (s: (list Z)) : sll x s (sll_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)) * (sll (nxt : val) (s1 : list Z) (_alpha_513 : sll_card)). Proof. auto. Qed.\nDefinition Gprog : funspecs :=\n  ltac:(with_library prog [sll_singleton_spec; malloc_spec]).\n\nLemma body_sll_singleton : semax_body Vprog Gprog f_sll_singleton sll_singleton_spec.\nProof.\nstart_function.\nssl_open_context.\nassert_PROP (isptr p). { entailer!. }\ntry rename a into a2.\nforward.\nforward_call (tarray (Tunion _sslval noattr) 2).\nIntros y2.\nassert_PROP (isptr y2). { entailer!. }\nforward.\nforward.\nforward.\nforward; entailer!.\nExists (y2 : val).\nExists ([(x : Z)] : list Z).\nExists (sll_card_1 (sll_card_0  : sll_card) : sll_card).\nssl_entailer.\nrewrite (unfold_sll_card_1 (sll_card_0  : sll_card)) at 1.\nExists (x : Z).\nExists ([] : list Z).\nExists nullval.\nssl_entailer.\nrewrite (unfold_sll_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_sll_singleton.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.27123343086368157}}
{"text": "Require Import FJ_tactics.\nRequire Import List.\nRequire Import Functors.\nRequire Import FunctionalExtensionality.\nRequire Import MonadLib.\nRequire Import Names.\nRequire Import EffPure.\nRequire Import EffState.\nRequire Import EffExcept.\nRequire Export ESoundS.\n\nSection ESoundES.\n\n  Variable D : Set -> Set.\n  Context {Fun_D : Functor D}.\n\n  Variable E : Set -> Set.\n  Context {Fun_E : Functor E}.\n\n  Variable V : Set -> Set.\n  Context {Fun_V : Functor V}.\n\n  Variable (ME : Set -> Set). (* Evaluation Monad. *)\n  Context {Fun_M : Functor ME}.\n  Context {Mon_M : Monad ME}.\n  Context {Exception_ME : Exception ME Datatypes.unit}.\n  Context {StateM_ME : StateM ME (list (Names.Value V))}.\n  Context {Fail_ME : FailMonad ME}.\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\n  Context {eq_DType_DT : forall T, FAlgebra eq_DTypeName T (eq_DTypeR D) D}.\n  Context {eq_DType_eq_DT : PAlgebra eq_DType_eqName D D (UP'_P (eq_DType_eq_P D))}.\n  Context {eq_DType_neq_D : PAlgebra eq_DType_neqName D D (UP'_P (eq_DType_neq_P D))}.\n\n  Context {Typeof_E : forall T, FAlgebra TypeofName T (typeofR D MT) E}.\n\n  Context {evalM_E : FAlgebra EvalName (Exp E) (evalMR V ME) E}.\n  Context {evalM_E' : forall T, FAlgebra EvalName T (evalMR V ME) E}.\n\n  Variable TypContext : Set.\n  Variable WFV : (WFValue_i D V TypContext -> Prop) -> WFValue_i D V TypContext -> Prop.\n  Context {funWFV : iFunctor WFV}.\n\n  Variable WFVM : (WFValueM_i D V MT ME TypContext -> Prop) -> WFValueM_i D V MT ME TypContext -> Prop.\n  Context {funWFVM : iFunctor WFVM}.\n\n  Context {TypContextCE : ConsExtensionC TypContext}.\n  Context {TypContext_WFE : WF_EnvC V TypContext}.\n\n  Context {Sub_WFVM_Base_WFVM : Sub_iFunctor (WFValueM_base D V MT ME TypContext WFV) WFVM}.\n  Context {Sub_WFVM_State_WFVM : Sub_iFunctor (WFValueM_State D V MT ME TypContext) WFVM}.\n  Context {Sub_WFVM_Except_WFVM : Sub_iFunctor (WFValueM_Except D V MT ME _) WFVM}.\n\n  Context {TypContext_S : SigTypContextC D TypContext}.\n  Context {TypContext_SCE : SigConsExtensionC D TypContext _ _}.\n\n  Section Except_State_Sound_Sec.\n\n    Variable WFV' : (WFValue_i D V (list (DType D)) -> Prop) -> WFValue_i D V (list (DType D)) -> Prop.\n    Context {funWFV' : iFunctor WFV'}.\n\n    Variable WFVM' : (WFValueM_i D V MT ME (list (DType D)) -> Prop) ->\n      WFValueM_i D V MT ME (list (DType D)) -> Prop.\n    Context {funWFVM' : iFunctor WFVM'}.\n\n    Definition Except_State_Sound_P (i : WFValueM_i D V MT ME (list (DType D))) :=\n      forall T (env : list (Value V)),\n        WF_Env (WF_EnvC := DType_Env_WFE D V WFV') _ env (wfvm_S _ _ _ _ _ i) ->\n        fmap (@proj1_sig _ _) (wfvm_T _ _ _ _ _ i) = return_ (proj1_sig T) ->\n        (exists v : Value V, exists env', exists Sigma' : list (DType D),\n          (put env) >> wfvm_v _ _ _ _ _ i = put env' >> return_ (M := ME) v /\\\n          WFValueC D V _ WFV' Sigma' v T) \\/\n        (exists t, exists env', exists Sigma' : list (DType D),\n          put env >> wfvm_v _ _ _ _ _ i = put env' >> throw t\n        /\\ WF_Env (WF_EnvC := DType_Env_WFE D V WFV') _ env' Sigma'\n        /\\ (forall n T, lookup (wfvm_S _ _ _ _ _ i) n = Some T -> lookup Sigma' n = Some T)).\n\n    Inductive Except_State_Sound_Name := except_state_sound_name.\n\n    Global Instance Except_State_Sound_WFVM_State :\n      iPAlgebra Except_State_Sound_Name Except_State_Sound_P\n      (WFValueM_State (TypContext_WFE := DType_Env_WFE _ _ WFV') D V MT ME (list (DType D))).\n    Proof.\n      econstructor.\n      unfold iAlgebra; intros; apply ind_alg_WFVM_State with (State_M := StateM_ME)\n        (TypContextCE := DType_Env_CE _) (TypContext_WFE := DType_Env_WFE _ _ WFV');\n        try assumption; unfold Except_State_Sound_P; simpl; intros.\n      (* WFVM_Get *)\n      destruct (H0 env H1 T0 env H1 H2) as [[v [env' [Sigma' [eval_eq WF_v_T]]]]\n        | [[] [env' [Sigma' [k_eq [WF_env_Sigma' Sigma'_Cons]]]]]].\n      left; exists v; exists env'; exists Sigma'.\n      unfold wbind; rewrite associativity.\n      generalize put_get as put_get'; intros; unfold wbind in put_get'; rewrite put_get'.\n      rewrite <- associativity.\n      rewrite <- left_unit.\n      split; unfold wbind; auto.\n      right; exists tt; exists env'; exists Sigma';\n        unfold wbind; rewrite associativity; repeat split; auto.\n      generalize put_get; unfold wbind; intros pg; rewrite pg;\n        rewrite <- associativity; rewrite <- left_unit; auto.\n      (* WFVM_Put *)\n      unfold wbind; rewrite associativity.\n      generalize put_put as put_put'; intros; unfold wbind in put_put'; rewrite put_put';\n        clear put_put'.\n      destruct (H2 T0 env H0 H4) as [[v [env' [Sigma'' [eval_eq WF_v_T]]]]\n        | [[] [env' [Sigma'' [k_eq [WF_env_Sigma'' Sigma''_Cons]]]]]].\n      left; exists v; exists env'; exists Sigma''; split; auto.\n      right; exists tt; exists env'; exists Sigma''; split; auto.\n    Qed.\n\n    Context {WFV_proj1_b_WFV : iPAlgebra WFV_proj1_b_Name (WFV_proj1_b_P D V _ WFV') WFV'}.\n\n    Global Instance Except_State_Sound_WFVM_Base :\n      iPAlgebra Except_State_Sound_Name Except_State_Sound_P (WFValueM_base D V MT ME _ WFV').\n    Proof.\n      econstructor.\n      unfold iAlgebra; intros; apply ind_alg_WFVM_base with (WFV := WFV')\n        (Fail_MT := Fail_MT) (Monad_ME := Mon_M);\n        try assumption; unfold Except_State_Sound_P; simpl; intros.\n      (* WFVM_Return' *)\n      left; exists v; exists env; exists Sigma; split; auto.\n      destruct H1 as [mt' mt'_eq]; subst.\n      rewrite fmap_fusion in H3.\n      destruct (fmap_exists _ _ _ _ _ H3) as [[T' T_eq] T'_eq].\n      simpl in *; subst; auto.\n      destruct T0 as [T0 T0_UP'].\n      apply (WFV_proj1_b _ _ _ _ _ _ H0); simpl; auto.\n      simpl in T'_eq; congruence.\n      (* WFVM_Untyped' *)\n      simpl in H1; apply sym_eq in H1.\n      unfold wbind in H1;\n        rewrite fmap_m, <- associativity, bind_fail in H1.\n      apply FailMonad_Disc in H1; destruct H1; auto.\n    Defined.\n\n    Context {ME_eq_dec' : forall (A : Set) (mte : ME A) (env : list (Names.Value (Fun_V := Fun_V) V)),\n      (exists a : A, exists env' : list (Names.Value (Fun_V := Fun_V) V),\n        wbind (H := Mon_M) (put (StateM := StateM_ME) env)\n        mte = wbind (H := Mon_M) (put (StateM := StateM_ME) env') (return_ (Monad := Mon_M) a)) \\/\n      (exists env', put env >> mte = put env' >> throw tt)}.\n    Context {MT_eq_dec : forall (A : Set) (mta : MT A),\n      {exists a, mta = return_ a} + {mta = fail}}.\n\n    Section Except_State_Sound_WFVM_Except_Sec.\n      (* Section with one possible put_catch law. *)\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_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      Context {Put_Exception_Disc :\n        forall (A : Set) (a : A) env env' n,\n          (put env >>= fun _ => return_ a) <> put env' >>= fun _ => throw n}.\n\n      Global Instance Except_State_Sound_WFVM_Except :\n        iPAlgebra Except_State_Sound_Name Except_State_Sound_P (WFValueM_Except D V MT ME _).\n      Proof.\n        econstructor.\n        unfold iAlgebra; intros; apply ind_alg_WFVM_Except with (Exception_ME := Exception_ME)\n          (Fail_MT := Fail_MT) (eq_DType_DT := eq_DType_DT) (TypContextCE := DType_Env_CE _);\n          try assumption; unfold Except_State_Sound_P; simpl; intros.\n      (* throw case *)\n        simpl; right; exists tt; exists env; exists Sigma; split; auto.\n      (* catch case *)\n        destruct (MT_eq_dec _ mte) as [[T' mte_eq] | mte_eq]; subst.\n        destruct (MT_eq_dec _ mth) as [[T'' mth_eq] | mth_eq]; subst.\n        repeat rewrite <- left_unit in H3.\n        caseEq (eq_DType _ (proj1_sig T') T''); rewrite H4 in H3.\n        destruct (H0 _ _ H2 H3) as [[v' [env' [Sigma' [ek'_eq WF_v'_T']]]] |\n          [[] [env' [Sigma' [ek'_eq [WF_env'_Sigma' Sigma'_Cons]]]]]].\n        destruct (ME_eq_dec' _ e' env) as [[v'' [env'' e'_eq]] | [env'' e'_eq]];\n          subst.\n        left; exists v'; exists env'; exists Sigma'; split; auto.\n        unfold wbind; rewrite associativity, put_catch.\n        unfold Value in *|-*; unfold wbind in e'_eq, ek'_eq; rewrite e'_eq, <- put_catch,\n          catch_return, <- ek'_eq, associativity, e'_eq; auto.\n        unfold Value in *|-*; unfold wbind in *|-*; rewrite associativity in ek'_eq;\n          rewrite e'_eq in ek'_eq; rewrite <- associativity, bind_throw in ek'_eq.\n        elimtype False; eapply Put_Exception_Disc with (a := v') (env' := env'') (env := env');\n          eauto with typeclass_instances; unfold wbind; rewrite <- left_unit; eauto.\n        destruct (ME_eq_dec' _ e' env) as [[v'' [env'' e'_eq]] | [env'' e'_eq]];\n          subst.\n        right; exists tt; exists env'; exists Sigma'; unfold wbind in *|-*; split; auto.\n        unfold Value in *|-*; rewrite associativity, e'_eq in ek'_eq.\n        rewrite associativity, put_catch, e'_eq, <- put_catch, catch_return; auto.\n        unfold Value in *|-*; unfold wbind in *|-*; rewrite associativity, e'_eq, <- associativity in ek'_eq.\n        rewrite rewrite_do with (m' := fun _ => throw tt) in ek'_eq.\n        destruct (H1 tt Sigma' Sigma'_Cons T env' WF_env'_Sigma') as\n          [[v'' [env''' [Sigma''' [ek''_eq WF_v''_T'']]]] |\n            [[] [env''' [Sigma''' [ek''_eq [WF_env'''_Sigma''' Sigma'''_Cons]]]]]].\n        rewrite <- H3.\n        rewrite (rewrite_do) with (m' := fun U => kT U T'').\n        rewrite (rewrite_do) with (m := fun U => return_ T' >>= _) (m' := fun U => kT U T').\n        apply kt_eq; rewrite (eq_DType_eq _ _ _ H4); auto.\n        apply functional_extensionality; intros; rewrite <- left_unit; auto.\n        apply functional_extensionality; intros; rewrite <- left_unit; auto.\n        left; exists v''; exists env'''; exists Sigma'''; split; auto.\n        unfold wbind in *|-*; rewrite associativity, put_catch, e'_eq.\n        rewrite (put_throw _ _ _ _ _ ek'_eq), <-put_catch, catch_throw',\n          <- associativity; auto.\n        right; exists tt; exists env'''; exists Sigma'''; repeat split; auto.\n        unfold wbind in *|-*.\n        unfold wbind in *|-*; rewrite associativity, put_catch, e'_eq.\n        rewrite (put_throw _ _ _ _ _ ek'_eq), <-put_catch, catch_throw',\n          <- associativity; auto.\n        rewrite bind_throw; reflexivity.\n        elimtype False; eapply FailMonad_Disc with (M := MT) (a := (proj1_sig T)) (mb := kT');\n          eauto with typeclass_instances; unfold wbind;\n            rewrite fmap_m in H3; rewrite <- associativity in H3;\n              rewrite rewrite_do with (m' := fun _ : C => fail) in H3; auto;\n                apply functional_extensionality; intros; repeat rewrite bind_fail; auto.\n        rewrite <- left_unit in H3.\n        elimtype False; eapply FailMonad_Disc with (M := MT) (a := (proj1_sig T)) (mb := kT');\n          eauto with typeclass_instances; unfold wbind;\n            rewrite fmap_m in H3; rewrite <- associativity in H3;\n              rewrite rewrite_do with (m' := fun _ : C => fail) in H3; auto;\n                apply functional_extensionality; intros; repeat rewrite bind_fail; auto.\n        elimtype False; eapply FailMonad_Disc with (M := MT) (a := (proj1_sig T)) (mb := kT');\n          eauto with typeclass_instances; unfold wbind;\n            rewrite fmap_m in H3; rewrite <- associativity in H3;\n              rewrite rewrite_do with (m' := fun _ : C => fail) in H3; auto;\n                apply functional_extensionality; intros; repeat rewrite bind_fail; auto.\n      Qed.\n\n    End Except_State_Sound_WFVM_Except_Sec.\n\n    Section Except_State_Sound_WFVM_Except_Sec2.\n      (* Section with the other possible put_catch law. *)\n      Context {put_catch' : forall (A : Set) (env : list (Value V)) e h,\n        put env >>= (fun _ => catch (A := A) e h) =\n        catch (put env >>= fun _ => e) (fun t => put env >>= fun _ => (h t))}.\n      Context {Put_Exception_Disc :\n        forall (A B : Set) (a : A) env env' n,\n          (put env >>= fun _ => return_ a) <> put env' >>= fun _ => throw n}.\n\n      Lemma put_catch'' : forall (A : Set) (env env' : list (Value V)) (e : ME A) h,\n        catch (put env >>= fun _ => e) (fun t => put env' >>= fun _ => (h t)) =\n        put env >> catch e (fun t => put env' >>= (fun _ => h t)).\n      Proof.\n        intros; generalize (put_put env env'); unfold wbind; intros put_put'.\n        rewrite put_catch'.\n        assert ((fun t : Datatypes.unit => put env' >>= (fun _ : Datatypes.unit => h t))\n          = (fun t : Datatypes.unit =>\n            put env >>=\n            (fun _ : Datatypes.unit => put env' >>= (fun _ : Datatypes.unit => h t)))) as H\n        by (apply functional_extensionality; destruct x; rewrite associativity, put_put'; auto).\n        rewrite H; auto.\n      Qed.\n\n      Global Instance Except_State_Sound_WFVM_Except2 :\n        iPAlgebra Except_State_Sound_Name Except_State_Sound_P (WFValueM_Except D V MT ME _).\n      Proof.\n        econstructor.\n        unfold iAlgebra; intros; apply ind_alg_WFVM_Except with (Exception_ME := Exception_ME)\n          (Fail_MT := Fail_MT) (eq_DType_DT := eq_DType_DT) (TypContextCE := DType_Env_CE _);\n          try assumption; unfold Except_State_Sound_P; simpl; intros.\n      (* throw case *)\n        simpl; right; exists tt; exists env; exists Sigma; split; auto.\n      (* catch case *)\n        destruct (MT_eq_dec _ mte) as [[T' mte_eq] | mte_eq]; subst.\n        destruct (MT_eq_dec _ mth) as [[T'' mth_eq] | mth_eq]; subst.\n        repeat rewrite <- left_unit in H3.\n        caseEq (eq_DType _ (proj1_sig T') T''); rewrite H4 in H3.\n        destruct (H0 _ _ H2 H3) as [[v' [env' [Sigma' [ek'_eq WF_v'_T']]]] |\n          [[] [env' [Sigma' [ek'_eq [WF_env'_Sigma' Sigma'_Cons]]]]]].\n        destruct (ME_eq_dec' _ e' env) as [[v'' [env'' e'_eq]] | [env'' e'_eq]];\n          subst.\n        left; exists v'; exists env'; exists Sigma'; split; auto.\n        unfold wbind; rewrite associativity, put_catch'.\n        unfold Value in *|-*; unfold wbind in e'_eq, ek'_eq; rewrite e'_eq.\n        rewrite put_catch'', catch_return, <- ek'_eq, associativity, e'_eq; auto.\n        unfold Value in *|-*; unfold wbind in *|-*; rewrite associativity in ek'_eq;\n          rewrite e'_eq in ek'_eq; rewrite <- associativity, bind_throw in ek'_eq.\n        elimtype False; eapply Put_Exception_Disc with (a := v') (env' := env'') (env := env');\n          eauto with typeclass_instances; unfold wbind; rewrite <- left_unit; eauto.\n        destruct (ME_eq_dec' _ e' env) as [[v'' [env'' e'_eq]] | [env'' e'_eq]];\n          subst.\n        right; exists tt; exists env'; exists Sigma'; unfold wbind in *|-*; split; auto.\n        unfold Value in *|-*; rewrite associativity, e'_eq in ek'_eq.\n        rewrite associativity, put_catch', e'_eq, put_catch'', catch_return; auto.\n        unfold Value in *|-*; unfold wbind in *|-*; rewrite associativity, e'_eq, <- associativity in ek'_eq.\n        rewrite rewrite_do with (m' := fun _ => throw tt) in ek'_eq.\n        destruct (H1 tt Sigma (fun _ _ => id) T env H2) as\n          [[v'' [env''' [Sigma''' [ek''_eq WF_v''_T'']]]] |\n            [[] [env''' [Sigma''' [ek''_eq [WF_env'''_Sigma''' Sigma'''_Cons]]]]]].\n        rewrite <- H3.\n        rewrite (rewrite_do) with (m' := fun U => kT U T'').\n        rewrite (rewrite_do) with (m := fun U => return_ T' >>= _) (m' := fun U => kT U T').\n        apply kt_eq; rewrite (eq_DType_eq _ _ _ H4); auto.\n        apply functional_extensionality; intros; rewrite <- left_unit; auto.\n        apply functional_extensionality; intros; rewrite <- left_unit; auto.\n        left; exists v''; exists env'''; exists Sigma'''; split; auto.\n        generalize put_put; unfold wbind; intros put_put'.\n        unfold wbind in *|-*; rewrite associativity, put_catch', e'_eq,\n          put_catch'', catch_throw'; unfold wbind; rewrite associativity,\n            put_put', <- associativity; auto.\n        right; exists tt; exists env'''; exists Sigma'''; repeat split; auto.\n        generalize put_put; unfold wbind in *|-*; intros put_put'.\n        unfold wbind in *|-*; rewrite associativity, put_catch', e'_eq,\n          put_catch'', catch_throw'; unfold wbind; rewrite associativity,\n            put_put', <- associativity; auto.\n        rewrite bind_throw; auto.\n        elimtype False; eapply FailMonad_Disc with (M := MT) (a := (proj1_sig T)) (mb := kT');\n          eauto with typeclass_instances; unfold wbind;\n            rewrite fmap_m in H3; rewrite <- associativity in H3;\n              rewrite rewrite_do with (m' := fun _ : C => fail) in H3; auto;\n                apply functional_extensionality; intros; repeat rewrite bind_fail; auto.\n        rewrite <- left_unit in H3.\n        elimtype False; eapply FailMonad_Disc with (M := MT) (a := (proj1_sig T)) (mb := kT');\n          eauto with typeclass_instances; unfold wbind;\n            rewrite fmap_m in H3; rewrite <- associativity in H3;\n              rewrite rewrite_do with (m' := fun _ : C => fail) in H3; auto;\n                apply functional_extensionality; intros; repeat rewrite bind_fail; auto.\n        elimtype False; eapply FailMonad_Disc with (M := MT) (a := (proj1_sig T)) (mb := kT');\n          eauto with typeclass_instances; unfold wbind;\n            rewrite fmap_m in H3; rewrite <- associativity in H3;\n              rewrite rewrite_do with (m' := fun _ : C => fail) in H3; auto;\n                apply functional_extensionality; intros; repeat rewrite bind_fail; auto.\n      Qed.\n\n    End Except_State_Sound_WFVM_Except_Sec2.\n\n    Context {Except_State_Sound_WFVM : iPAlgebra Except_State_Sound_Name Except_State_Sound_P WFVM'}.\n    Context {eval_soundness'_Exp_E : forall (typeof_rec : UP'_F E -> typeofR D MT)\n      (eval_rec : Names.Exp E -> evalMR V ME),\n      P2Algebra ES'_ExpName E E E\n      (UP'_P2\n        (eval_soundness'_P D V E MT ME _ WFVM'\n          Datatypes.unit E Fun_E\n          (fun _ _ _ _ => True)\n          tt typeof_rec eval_rec f_algebra\n          (f_algebra (FAlgebra := evalM_E' (@Names.Exp E Fun_E)))))}.\n    Context {WF_MAlg_typeof : WF_MAlgebra Typeof_E}.\n    Context {WF_MAlg_eval : WF_MAlgebra evalM_E'}.\n\n    Theorem eval_Except_State_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 := evalM_E') 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 := evalM_E') 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      intros e Sigma.\n      apply (ifold_ WFVM' _ (ip_algebra (iPAlgebra := Except_State_Sound_WFVM)) _\n        (eval_State_soundness (eval_soundness'_Exp_E := eval_soundness'_Exp_E) _ _ _ MT ME WFVM' e Sigma)).\n    Qed.\n\n  End Except_State_Sound_Sec.\n\nEnd ESoundES.\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/ESound/ESoundES.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521105, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2712311117426701}}
{"text": "Require Import Coq.Strings.String.\nRequire Import Coq.PArith.BinPos.\nRequire Import ExtLib.Core.RelDec.\nRequire Import ExtLib.Data.String.\nRequire Import ExtLib.Data.Nat.\nRequire Import ExtLib.Data.HList.\nRequire Import MirrorCore.Lemma. \nRequire Import MirrorCore.TypesI.\nRequire Import MirrorCore.Lambda.Expr.\nRequire Import MirrorCore.RTac.RTac.\nRequire Import MirrorCore.provers.DefaultProver.\nRequire MirrorCore.syms.SymEnv.\nRequire MirrorCore.syms.SymSum.\nRequire Import MirrorCore.Subst.FMapSubst.\nRequire Import MirrorCore.Lambda.ExprLift.\nRequire Import MirrorCore.Lambda.ExprSubst.\nRequire Import MirrorCore.Lambda.ExprUnify_simul.\nRequire Import MirrorCore.Lambda.Red.\nRequire Import MirrorCore.Lambda.AppN. \nRequire Import MirrorCore.Lambda.RedAll.\nRequire Import MirrorCore.Lambda.ExprVariables.\nRequire Import Charge.ModularFunc.ILogicFunc.\nRequire Import Charge.Tactics.OrderedCanceller.\nRequire Import Charge.Tactics.BILNormalize.\nRequire Import Charge.Tactics.SynSepLog.\nRequire Import Charge.Tactics.SepLogFold.\n\nRequire Import Java.Tactics.Semantics.\nRequire Import Java.Func.JavaType.\nRequire Import Java.Func.JavaFunc.\n\nRequire Import Charge.ModularFunc.BILogicFunc.\n\nRequire Import Charge.Tactics.Rtac.ReifyLemma.\n\nRequire Import Charge.Tactics.Rtac.PullConjunct.\n\nRequire Import MirrorCore.Reify.Reify.\n\nRequire Import Java.Func.Reify.\n\nRequire Import Charge.Tactics.Rtac.Subst.\n\n\nRequire Import Java.Language.Lang.\nRequire Import Java.Language.Program.\n \nRequire Import Charge.Tactics.Rtac.Apply.\nRequire Import Charge.Tactics.Rtac.Cancellation.\nRequire Import Charge.Tactics.Rtac.Intro.\nRequire Import Charge.Tactics.Rtac.EApply.\nRequire Import Charge.Tactics.Rtac.Instantiate.\n\nRequire Import Coq.Arith.Peano_dec.\n\nFixpoint mkStars n P Q : expr typ func := \n\tmatch n with\n\t\t| 0 => mkStar tySasn P Q\n\t\t| S n => mkStar tySasn (mkStars n P Q) (mkStars n P Q)\n\tend.\n\t\nDefinition cancelTest n :=\n      mkForall tySasn tyProp\n      (mkForall tySasn tyProp\n          (mkEntails tySasn (mkStars n (Var 0) (Var 1)) (mkStars n (Var 1) (Var 0)))).\n          \nSection blurb.\n\nContext {fs : Environment}.\n          \nTime Eval vm_compute in typeof_expr nil nil (cancelTest 10).\nCheck THEN.\nCheck runOnGoals.\nTime Eval vm_compute in \n\t(THEN (REPEAT 10 (INTRO typ func)) \n\t(runOnGoals (CANCELLATION typ func tySasn is_pure))) \n\t\tnil nil 0 0 (CTop nil nil) (ctx_empty (expr := expr typ func)) (cancelTest 10).\n\nFixpoint search_NoDup\n    {A} (A_dec: forall a b: A, {a=b}+{a=b->False}) (l: list A) : option (NoDup l) :=\n  match l with\n  | nil => Some (NoDup_nil A)\n  | a::l' =>\n      match search_NoDup A_dec l' with\n      | Some nodup =>\n          match In_dec A_dec a l' with\n          | left isin => None\n          | right notin => \n \t\t\tmatch search_NoDup A_dec l' with\n \t\t\t\t| Some pf => Some (NoDup_cons _ notin pf)\n \t\t\t\t| None => None         \n            end\n          end\n      | None => None\n      end\n  end.\n(*\n\n\nDefinition list_notin_set lst s :=\n  \tfold_right (fun a acc => andb (SS.for_all (fun b => negb (string_dec a b)) s) acc) true lst.\n\nDefinition method_specI : stac typ (expr typ func) subst :=\n  fun tus tvs s lst e =>\n    match e with\n    \t| mkEntails [l, mkProgEq [mkProg [P]], mkMethodSpec [C, m, mkVarList [args], mkString [r], p, q]] => \n    \t      match C, m with\n    \t        | Inj (inl (inr (pString Cname))), Inj (inl (inr (pString Mname))) => \n    \t          match SM.find Cname (p_classes P) with\n    \t          \t| Some Class => \n    \t          \t  match SM.find Mname (c_methods Class) with\n    \t          \t    | Some Method => \n\t\t\t\t\t\t  match search_NoDup Coq.Strings.String.string_dec args with\n\t\t\t\t\t\t  \t| Some pf => \n\t\t\t\t\t\t  \t  match eq_nat_dec (length args) (length (m_params Method)) with\n\t\t\t\t\t\t  \t    | left pf' => \n\t\t\t\t\t\t  \t      if list_notin_set args (modifies (m_body Method)) then\n\t\t\t\t\t\t  \t        More tus tvs s lst \n\t\t\t\t\t\t  \t        mkEntails [l, mkProgEq [mkProg [P]], \n\t\t\t\t\t\t  \t                      mkTriple [mkApplyTruncSubst [tyAsn, p, mkSubstList [mkVarList [args], mkExprList [map E_var (m_params Method)]] ], mkCmd [m_body Method], \n\t\t\t\t\t\t  \t                               mkApplyTruncSubst [tyAsn, q, mkSubstList [mkVarList [r::args], mkConsExprList [App fEval (mkExpr [m_ret Method]), mkExprList[map E_var (m_params Method)]]] ]]]\n\t\t\t\t\t\t  \t      else\n\t\t\t\t\t\t  \t        @Fail _ _ _\n\t\t\t\t\t\t  \t    | right _ => @Fail _ _ _\n\t\t\t\t\t\t  \t  end \n\t\t\t\t\t\t  \t| None => @Fail _ _ _\n\t\t\t\t\t\t  end\n    \t          \t    | None => @Fail _ _ _\n    \t          \t  end\n    \t          \t| None => @Fail _ _ _\n    \t          end\n    \t        | _, _ => @Fail _ _ _\n    \t      end\n      \t| _ => @Fail _ _ _\n    end.\n*)\n\n(** Skip **)\nDefinition skip_lemma : lemma typ (expr typ func) (expr typ func).\nreify_lemma reify_imp rule_skip.\nDefined.\nPrint skip_lemma.\n\nLemma skip_lemma_sound : \n\tlemmaD (exprD'_typ0 (T:=Prop)) nil nil skip_lemma.\nProof.\n  unfold lemmaD; simpl; intros.\n  unfold exprT_App, exprT_Inj, Rcast_val, Rcast in * ; simpl in *.\n  apply rule_skip. apply H.\nQed.\n\nExample test_skip_lemma : test_lemma skip_lemma. Admitted.\n\nDefinition skip_lemma2 : lemma typ (expr typ func) (expr typ func).\nreify_lemma reify_imp rule_skip2.\nDefined.\nPrint skip_lemma2.\n\nExample test_skip_lemma2 : test_lemma skip_lemma2. Admitted.\n\nDefinition seq_lemma (c1 c2 : cmd) : lemma typ (expr typ func) (expr typ func).\nProof.\n  reify_lemma reify_imp (@rule_seq c1 c2).\nDefined.\nPrint seq_lemma.\n\nLemma seq_lemma_sound c1 c2 : \n\tlemmaD (exprD'_typ0 (T:=Prop)) nil nil (seq_lemma c1 c2).\nProof.\n  unfold lemmaD; simpl; intros.\n  unfold exprT_App, exprT_Inj, Rcast_val, Rcast in * ; simpl in *.\n  eapply rule_seq; [apply H | apply H0].\nQed.\n\nExample test_seq_lemma (c1 c2 : cmd) : test_lemma (seq_lemma c1 c2). Admitted.\n\nDefinition if_lemma (e : dexpr) (c1 c2 : cmd) : lemma typ (expr typ func) (expr typ func).\nProof.\n  reify_lemma reify_imp (@rule_if e c1 c2).\nDefined.\n\nRequire Import ExtLib.Tactics.\n(*\nLemma if_lemma_sound e c1 c2 : \n\tlemmaD (exprD'_typ0 (T:=Prop)) nil nil (if_lemma e c1 c2).\nProof.\n  remember (exprD nil nil (evalDExpr e) tyExpr).\n  Check rule_if.\n  unfold lemmaD; simpl.\n  unfold lemmaD', exprD'_typ0.\n  unfold le\n  unfold if_lemma.\n  destruct o.\n  unfold exprD in Heqo. simpl in Heqo.\n  remember (ExprDsimul.ExprDenote.exprD' nil nil tyVal (evalDExpr e)).\n  destruct o; inv_all; subst; try congruence.\n  unfold lemmaD, lemmaD', exprD'_typ0, ExprDsimul.ExprDenote.exprD'; simpl in *; intros.\n unfold ExprDsimul.ExprDenote.exprD' in *; simpl in *; intros.\n unfold exprT_App, exprT_Inj, Rcast_val, Rcast in *; simpl in *.\n unfold OpenFunc.typ2_cast_bin, OpenFunc.typ3_cast_bin in *; simpl in *.\n unfold exprT, OpenT in *; simpl in *.\n rewrite <- Heqo0.\n unfold ExprDsimul.ExprDenote.exprD' in Heqo0. simpl in Heqo0.\n rewrite <- Heqo0.\n repeat red.\n setoid_rewrite <- Heqo.\n rewrite <- Heqo.\n    unfold exprT_App, exprT_Inj, Rcast_val, Rcast in * ; simpl in *.\n    eapply rule_if; [eapply H | eapply H0].\n  + unfold lemmaD; simpl; intros.\n    unfold exprT_App, exprT_Inj, Rcast_val, Rcast in * ; simpl in *.\n    eapply rule_if; [eapply H | eapply H0].\n  + unfold lemmaD; simpl; intros.\n    unfold exprT_App, exprT_Inj, Rcast_val, Rcast in * ; simpl in *.\n    eapply rule_if; [eapply H | eapply H0].\n\n  Print if_lemma.\n  vm_compute.\n  unfold lemmaD'. simpl.\n  unfold exprD'_typ0. simpl.\n  unfold ExprDsimul.ExprDenote.exprD'.\n  simpl.\n  unfold if_lemma. simpl.\n  apply rule_skip. apply H.\nQed.\n*)\nExample test_if_lemma e (c1 c2 : cmd) : test_lemma (if_lemma e c1 c2). Admitted.\n\nDefinition read_lemma (x y : var) (f : field) : lemma typ (expr typ func) (expr typ func).\nProof.  \n  reify_lemma reify_imp (@rule_read_fwd x y f).\nDefined.\n\nLemma read_lemma_sound x y f : \n\tlemmaD (exprD'_typ0 (T:=Prop)) nil nil (read_lemma x y f).\nProof.\n  (*\n  unfold lemmaD; simpl; intros.\n  unfold exprT_App, exprT_Inj, Rcast_val, Rcast, OpenFunc.typ3_cast_bin, OpenFunc.typ2_cast_bin, eq_rect_r in * ; simpl in *.\n  eapply rule_read_fwd; [eapply H | eapply H0].\n  *)\n  admit.\nQed.\n\n\nExample test_read_lemma x y f : test_lemma (read_lemma x y f). Admitted.\n\nSet Printing Width 140.\n\nDefinition write_lemma (x : var) (f : field) (e : dexpr) : lemma typ (expr typ func) (expr typ func).\nProof.\n  reify_lemma reify_imp (@rule_write_fwd x f e).\nDefined.\n(*\nLemma write_lemma_sound x f e : \n\tlemmaD (exprD'_typ0 (T:=Prop)) nil nil (write_lemma x f e).\nProof.\n  induction e.\n  Check evalDExpr.\n  unfold lemmaD, lemmaD'; simpl; intros.\n  unfold exprT_App, exprT_Inj, Rcast_val, Rcast, OpenFunc.typ3_cast_bin, OpenFunc.typ2_cast_bin, eq_rect_r, \n  fPointsto, typ2_cast_bin, BaseFunc.mkString; simpl.\n  unfold exprD'_typ0; simpl.\n  unfold ExprDsimul.ExprDenote.exprD'; simpl.\n  vm_compute.\n  eapply rule_write_fwd; [eapply H | eapply H0].\nQed.\n*)\n\nExample test_write_lemma x f e : test_lemma (write_lemma x f e). Admitted.\n\nDefinition assign_lemma (x : var) (e : dexpr) : lemma typ (expr typ func) (expr typ func).\nProof.\n  reify_lemma reify_imp (@rule_assign_fwd x e).\nDefined.\nPrint assign_lemma.\nExample test_assign_lemma x e : test_lemma (assign_lemma x e). Admitted.\n\nDefinition alloc_lemma (x : var) (C : class) : lemma typ (expr typ func) (expr typ func).\nProof.\n  reify_lemma reify_imp (@rule_alloc_fwd x C).\nDefined.\nExample test_alloc_lemma x C : test_lemma (alloc_lemma x C). Admitted.\n\nDefinition pull_exists_lemma : lemma typ (expr typ func) (expr typ func).\nProof.\n  reify_lemma reify_imp (@pull_exists val).\nDefined.\nExample test_pull_exists_lemma : test_lemma pull_exists_lemma. Admitted.\nEval vm_compute in pull_exists_lemma.\n\nDefinition ent_exists_right_lemma : lemma typ (expr typ func) (expr typ func).\nProof.\n  reify_lemma reify_imp (@ent_left_exists val).\nDefined.\nExample test_pull_exists_lemma2 : test_lemma ent_exists_right_lemma. Admitted.\n\nDefinition eq_to_subst_lemma : lemma typ (expr typ func) (expr typ func).\nProof.\n  reify_lemma reify_imp eq_to_subst.\nDefined.\nEval vm_compute in eq_to_subst_lemma.\nExample test_eq_lemma : test_lemma (eq_to_subst_lemma). Admitted.\nCheck rule_static_complete.\nDefinition scall_lemma (x : Lang.var) (C : class) (m : string) (es : list dexpr) \n  : lemma typ (expr typ func) (expr typ func).\nProof.\n  reify_lemma reify_imp rule_static_complete.\nQed.\n\nPrint scall_lemma.\n\nPrint pull_exists_lemma.\n\nExample test_pull_exists : test_lemma (pull_exists_lemma). Admitted.\n\nRequire Import Charge.ModularFunc.BaseFunc.\n\nRequire Import ExtLib.Tactics.\n\nRequire Import Charge.ModularFunc.ListFunc.\n\nRequire Import MirrorCore.Lambda.ExprTac.\n(*\n\n  Lemma foldTacOk : partial_reducer_ok foldTac.\n  Proof.\n    unfold partial_reducer_ok; intros.\n    unfold foldTac.\n    remember (listS e); destruct o; [| exists val; tauto].\n    destruct l; try (exists val; tauto).\n    destruct es; try (exists val; tauto).\n    destruct es; try (exists val; tauto).\n    destruct es; try (exists val; tauto).\n    destruct e2; try (exists val; tauto).\n    destruct f; try (exists val; tauto).\n    \n    destruct j; try (exists val; tauto).\n    destruct es; try (exists val; tauto).\n    destruct e; simpl in Heqo; try congruence.\n    destruct f; simpl in Heqo; try congruence.\n    destruct s; simpl in Heqo; try congruence.\n    destruct s; simpl in Heqo; try congruence.\n    destruct s; simpl in Heqo; try congruence.\n    destruct s; simpl in Heqo; try congruence.\n    inv_all; subst.\n    autorewrite with exprD_rw in H; simpl in H; forward; inv_all; subst.\n    autorewrite with exprD_rw in H; simpl in H; forward; inv_all; subst; [|apply _].\n    autorewrite with exprD_rw in H; simpl in H; forward; inv_all; subst; [|apply _].\n    autorewrite with exprD_rw in H0; simpl in H0; forward; inv_all; subst; [|apply _].\n    autorewrite with exprD_rw in H2; simpl in H2; forward; inv_all; subst; [|apply _].\n    unfold funcAs in H2. \n    Opaque type_cast.\n    simpl in H2. forward; inv_all; subst. red in r. inv_all.\n    inversion r; subst.\n    rewrite (UIP_refl r) in H4. unfold Rcast in H4; simpl in H4.\n    inversion H4; unfold eq_rect_r in H6; simpl in H6.\n    subst. clear H4.\n    clear H2 r.\n    Opaque beta.\n    simpl.\n    unfold exprT_App, eq_rect_r. simpl.\n    cut (exists val' : exprT tus tvs (typD t),\n  ExprDsimul.ExprDenote.exprD' tus tvs t\n    (fold_right\n       (fun (x : string) (acc : expr typ func) =>\n        beta (beta (App (App e0 (mkString x)) acc))) e1 l) = Some val' /\\\n  (forall (us : hlist typD tus) (vs : hlist typD tvs),\n   fold_right (e4 us vs) (e3 us vs) (exprT_Inj tus tvs l us vs) = val' us vs)).\n   intros [? [? ?]].\n   eexists; split; [eassumption | intros; apply H4].\n    induction l; simpl; intros.\n\n    + exists e3; tauto.\n    + destruct IHl as [? [? ?]].\n      eexists; split; [|intros; reflexivity].\n\n  Lemma exprD'_remove_beta tus tvs t e de (H : exprD' tus tvs e t = Some de) :\n    exprD' tus tvs (beta e) t = Some de.\n  Proof.\n    pose proof (beta_sound tus tvs e t).\n    unfold exprD' in *. simpl in *. forward; inv_all; subst.\n\tRequire Import FunctionalExtensionality.\n\tf_equal. symmetry.\n    apply functional_extensionality; intros.\n    apply functional_extensionality; intros.\n    apply H2.\n  Qed.\n  \n  \n      do 2 (apply exprD'_remove_beta).\n      unfold exprD'. simpl.\n      \n      red_exprD; [|apply _].\n      pose proof (exprD_typeof_Some).\n      specialize (H5  _ _ _ _ _ _ _ _ _ _ _ _ _ H2). rewrite H5; clear H5.\n      red_exprD; [|apply _].\n      forward; inv_all; subst.\n      unfold mkString. forward.\n      red_exprD; [|apply _]. \n      Transparent type_cast.\n      unfold funcAs. simpl.\n\t  f_equal. unfold exprT_App; simpl. \n\t  unfold eq_rect_r. simpl.\n\t  apply functional_extensionality; intros.\n\t  apply functional_extensionality; intros.\n\t  rewrite H4. reflexivity.\nQed.\nSearchAbout partial_reducer_ok.\n\nPrint partial_reducer_ok.\nPrint apps_reducer.\nPrint full_reducer_ok.\nPrint full_reducer.\nCheck @idred.\nSearchAbout idred.\nPrint idred.\nPrint idred'.\nCheck @beta_all.\n\nDefinition FOLD := SIMPLIFY (typ := typ) (fun _ _ _ _ => (beta_all (fun _ => foldTac))).\n\nRequire Import ExtLib.Tactics.Consider.\nRequire Import ExtLib.Tactics.\nRequire Import MirrorCore.Lambda.RedAll.\nPrint partial_reducer.\n\n(*\n  Lemma foldTacOk2 : partial_reducer_ok foldTac.\n  Proof.\n    unfold full_reducer_ok; intros.\n    Print var_termsP.\n    Print partial_reducer_ok.\n    unfold exprT, OpenT in P.\n    unfold foldTac.\n    remember (listS e). destruct o.\n    Focus 2.\n    simpl.\n  Qed.\n*)\nLemma FOLD_sound : rtac_sound FOLD.\nProof.\n  admit.\n  (*\n  unfold FOLD.\n  apply SIMPLIFY_sound.\n  intros; simpl.\n  forward.\n  rewrite <- H.\n  simpl.\n  unfold Ctx.propD, exprD'_typ0 in H3; forward; inv_all; subst.\n  destruct (beta_all_sound foldTacOk _ _ e0 H3) as [v [H4 H5]].\n  apply beta_all_sound.\n  Check beta_all_sound.\n  (* beta_all_sound is missing *)\n  \n  *)\nQed.\n\n*)\n\nCheck apps.\nDefinition BETA := SIMPLIFY (typ := typ) (fun _ _ _ _ => beta_all (fun _ => @apps typ func)).\n\nLemma BETA_sound : rtac_sound BETA.\nProof.\n  unfold BETA.\n  apply SIMPLIFY_sound.\n  intros; simpl; forward.\n  (*\n  SearchAbout full_reducer.\n  assert (full_reducer_ok (fun _ => apps (sym := func))). {\n    clear.\n    intros e vars tus tvs tus' tvs' P Hvars es t targs Hexpr.\n  }\n  unfold full_reducer_ok.\n  \n  Print full_reducer.\n  pose proof (beta_all_sound).\n  SearchAbout beta_all.\n  rewrite <- H.*)\n  admit.\nQed.\n\nDefinition THEN' := @MirrorCore.RTac.Then.THEN typ (expr typ func).\nRequire Import Charge.Tactics.Rtac.Minify.\n\nLet EAPPLY lem := THEN' (EAPPLY typ func lem) (MINIFY typ func).\n\nDefinition THEN (r1 r2 : rtac typ (expr typ func)) := \n  THEN (THEN (THEN (INSTANTIATE typ func) (runOnGoals r1)) (runOnGoals (INSTANTIATE typ func))) (runOnGoals r2).\n\nCheck SUBST.\n\nDefinition EQSUBST := THEN (EAPPLY eq_to_subst_lemma) (SUBST (ilp := ilp) (bilp := bilp) typ func).\n\n(*\nNotation \"'ap_eq' '[' x ',' y ']'\" :=\n\t (ap (T := Fun stack) (ap (T := Fun stack) (pure (T := Fun stack) (@eq val)) x) y).\n*)\n\nRequire Import Charge.ModularFunc.OpenFunc.\nRequire Import Charge.ModularFunc.BaseFunc.\nRequire Import Charge.ModularFunc.EmbedFunc.\n\nDefinition match_ap_eq (e : expr typ func) : bool :=\n\tmatch e with \n\t  | App emb (App (App f (App (App g (App h e)) x)) y) =>\n\t  \tmatch embedS emb, open_funcS f, open_funcS g, open_funcS h, baseS e with\n\t  \t\t| Some (eilf_embed _ _), Some (of_ap _ _), Some (of_ap _ _), Some (of_const _), Some (pEq _) => true\n\t  \t\t| _, _, _, _, _ => false\n\t  \tend\n\t  | _ => false\n\tend.\nCheck @PULLCONJUNCTL.\nInstance notehu : RelDec (@eq (expr typ func)).\napply RelDec_eq_expr.\napply _.\napply _.\nsplit.\na\n\nDefinition PULLEQL := @PULLCONJUNCTL typ func RType_typ _ _ _ match_ap_eq _ _ _.\n\n                        (*\n\tTHEN (INSTANTIATE typ func subst) (runOnGoals (THEN (THEN (TRY FIELD_LOOKUP) \n\t\t(runOnGoals (CANCELLATION typ func subst tySpec (fun _ => false)))) (runOnGoals FOLD))) ::\n\t\tsolve_entailment :: nil).\n\t           *)\nRequire Import Charge.SetoidRewrite.AutoSetoidRewrite.\nRequire Import Charge.SetoidRewrite.Base.\nRequire Import Charge.SetoidRewrite.ILSetoidRewrite.\nRequire Import Charge.SetoidRewrite.BILSetoidRewrite.\n\n  Definition spec_respects (e : expr typ func) (_ : list (RG (expr typ func)))\n\t   (rg : RG (expr typ func)) : m (expr typ func) :=\n\t   match e with\n\t     | Inj (inr pTriple) =>\n\t       rg_bind (unifyRG (@rel_dec (expr typ func) _ _) rg\n\t         (RGrespects (RGflip (RGinj (fEntails tySasn)))\n\t           (RGrespects (RGinj (fEq tyCmd))\n\t             (RGrespects (RGinj (fEntails tySasn))\n\t               (RGinj (fEntails tySpec))))))\n\t         (fun _ => rg_ret fTriple)\n\t     | _ => rg_fail\n\t   end.\n\nDefinition step_unfold vars rw :=\n  setoid_rewrite vars _ (fEntails : typ -> expr typ func) rw\n    (sr_combine il_respects\n               (sr_combine (@il_respects_reflexive typ func _ _ _ ilops _ _)\n                                        (sr_combine bil_respects\n                                                    (sr_combine eq_respects \n                                                    (sr_combine spec_respects refl)))))\n    (fun _ => rw_fail).\n    \n  Definition STEP_REWRITE rw : rtac typ (expr typ func) :=\n    fun tus tvs lus lvs c s e =>\n      match step_unfold (getVars c) rw tyProp e with\n        | Some (e', _) => More s (GGoal e')\n        | _ => More s (GGoal e)\n      end.\n\nDefinition PULL_TRIPLE_EXISTS : rtac typ (expr typ func) :=\n  THEN (THEN (EAPPLY pull_exists_lemma) (INTRO typ func)) BETA.\n\nDefinition solve_entailment (rw : rewriter (typ := typ) (func := func)) : rtac typ (expr typ func) :=\n\tTHEN (INSTANTIATE typ func) \n\t\t(FIRST (SOLVE (CANCELLATION typ func tySasn is_pure) ::\n\t           (THEN (THEN (THEN (THEN PULLEQL (REPEAT 1000 EQSUBST)) \n\t           (STEP_REWRITE rw)) (REPEAT 1000 (INTRO typ func))) \n\t              (CANCELLATION typ func tySasn is_pure)::\n\t           nil))).\n\nDefinition solve_alloc rw : rtac typ (expr typ func) :=\n    THEN (INSTANTIATE typ func)\n    (FIRST (SOLVE (CANCELLATION typ func tySpec (fun _ => false)) ::\n                        FIELD_LOOKUP ::\n                        THEN FOLD (solve_entailment rw) :: nil)).\n\nDefinition simStep (rw : rewriter (typ := typ) (func := func)) (r : rtac typ (expr typ func)) :=\n    THEN (THEN (THEN (THEN (SUBST typ func)\n    \t(TRY PULL_TRIPLE_EXISTS)) (STEP_REWRITE rw)) (REPEAT 10 PULL_TRIPLE_EXISTS)) r.\n\nFixpoint tripleE (c : cmd) rw : rtac typ (expr typ func) :=\n\tmatch c with\n\t    | cskip => simStep rw (THEN (EAPPLY skip_lemma) (solve_entailment rw))\n\t    | calloc x C => simStep rw (THEN (EAPPLY (alloc_lemma x C)) \n\t        (FIRST (solve_alloc rw::solve_entailment rw::nil)))\n\t\t| cseq c1 c2 => simStep rw (THEN' (EAPPLY (seq_lemma c1 c2))\n\t\t    (THENK (runOnGoals (TRY (tripleE c1 rw))) (THENK (MINIFY typ func) (runOnGoals (tripleE c2 rw)))))\n\t\t| cassign x e => simStep rw (THEN (EAPPLY (assign_lemma x e)) (solve_entailment rw))\n\t\t| cread x y f => simStep rw (THEN (EAPPLY (read_lemma x y f)) (solve_entailment rw))\n\t\t| cif e c1 c2 => simStep rw (THEN (EAPPLY (if_lemma e c1 c2)) (solve_entailment rw))\n\t\t| cwrite x f e => simStep rw (THEN (EAPPLY (write_lemma x f e)) (solve_entailment rw))\n\t\t| _ => IDTAC\n\tend.\n\nDefinition symE rw : rtac typ (expr typ func) :=\n\t(fun tus tvs n m ctx s e => \n\t\t(match e return rtac typ (expr typ func) with \n\t\t\t| App (App (Inj f) G) H =>\n\t\t\t  match ilogicS f, H with\n\t\t\t  \t| Some (ilf_entails tySpec), (* tySpec is a pattern, should be checked for equality with tySpec *)\n\t\t\t  \t  App (App (App (Inj (inr pTriple)) P) Q) (Inj (inr (pCmd c))) =>\n\t\t\t  \t  \ttripleE c rw\n\t\t\t  \t| _, _ => FAIL\n\t\t\t  end\n\t\t\t| _ => FAIL\n\t\tend) tus tvs n m ctx s e).  \n\nDefinition runTac rw := \n   (THEN (THEN (REPEAT 1000 (INTRO typ func)) (symE rw)) \n\t(INSTANTIATE typ func)).\n\t\nLemma runTac_sound rw : rtac_sound (runTac rw).\nProof.\n  admit.\nQed.\n\nDefinition mkPointsto (x : expr typ func) (f : field) (e : expr typ func) : expr typ func :=\n   mkAp tyVal tyAsn \n        (mkAp tyString (tyArr tyVal tyAsn)\n              (mkAp tyVal (tyArr tyString (tyArr tyVal tyAsn))\n                    (mkConst (tyArr tyVal (tyArr tyString (tyArr tyVal tyAsn))) \n                             fPointsto)\n                    x)\n              (mkConst tyString (mkString f)))\n        e.\n        \nRequire Import Java.Semantics.OperationalSemantics.\nRequire Import Java.Logic.SpecLogic.\nRequire Import Java.Logic.AssertionLogic.\nRequire Import Java.Examples.ListClass.\nRequire Import Charge.Logics.ILogic.\n\nFixpoint seq_skip n := \n\tmatch n with\n\t  | 0 => cskip\n\t  | S n => cseq cskip (seq_skip n)\n\tend.\n\nRequire Import ExtLib.Structures.Applicative.\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\nDefinition testSkip n : Prop :=\n  forall (G : spec) (P : sasn), G |-- triple P P (seq_skip n).\n\nLemma INTRO_sound : rtac_sound (INTRO typ func).\nProof.\n  admit.\nQed.\n\nRequire Import Java.Tactics.Tactics.\nCheck IDTAC_sound.\n\nLtac rtac_result reify term_table tac :=\n\t  let name := fresh \"e\" in\n\t  match goal with\n\t    | |- ?P => \n\t      reify_aux reify term_table P name;\n\t      let t := eval vm_compute in (typeof_expr nil nil name) in\n\t      let goal := eval unfold name in name in \n\t      match t with\n\t        | Some ?t =>\n\t          let goal_result := constr:(run_tac tac (GGoal name)) in \n\t          let result := eval vm_compute in goal_result in \n\t          idtac result\n\t        | None => idtac \"expression \" goal \"is ill typed\" t \n\t      end\n\t  end.\n\t  \nLemma test_skip_lemma3 : testSkip 10.\nProof.\n  idtac \"start\".\n  unfold testSkip; simpl.\n  \n  Time run_rtac reify_imp term_table (@runTac_sound rw_fail).\nTime Qed.\n\nDefinition test_alloc : expr typ func :=\n\tmkEntails tySpec (mkProgEq (mkProg ListProg))\n\t\t(mkTriple (mkTrue tySasn) (mkCmd (cseq (calloc \"x\" \"NodeC\") cskip)) (mkFalse tySasn)).\n\nRequire Import Charge.Logics.BILogic.\n  \n  Lemma test_alloc_correct : \n  prog_eq ListProg |-- triple empSP lfalse ((calloc \"x\" \"NodeC\");;Skip).\nProof.\n  Time run_rtac reify_imp term_table (@runTac_sound rw_fail).\n  unfold open_func_symD. simpl.\n  admit.\nQed.\n\nLemma test_read : ltrue |-- \n    triple \n      (ap_pointsto [(\"o\": var), (\"f\" : field), pure (T := Fun (Lang.stack)) (vint 3)] ** \n       ap_pointsto [(\"o\": var), (\"g\" : field), pure (T := Fun (Lang.stack)) (vint 4)]) \n      (ap_pointsto [(\"o\": var), (\"f\": field), pure (T := Fun (Lang.stack)) (vint 3)] ** \n      (ap_pointsto [(\"o\": var), (\"g\": field), pure (T := Fun (Lang.stack)) (vint 4)]))\n      (cseq (cread \"x\" \"o\" \"f\") (cseq (cread \"y\" \"o\" \"g\") cskip)).                    \nProof.\n  Time run_rtac reify_imp term_table (@runTac_sound rw_fail).\nQed.\n\nLemma test_write :\n\tltrue |--\n\ttriple\n      (ap_pointsto [(\"o\": var), (\"f\" : field), pure (T := Fun (Lang.stack)) (vint 3)]) \n      (ap_pointsto [(\"o\": var), (\"f\": field), pure (T := Fun (Lang.stack)) (vint 4)])\n      (cseq (cwrite \"o\" \"f\" (E_val (vint 4))) cskip).                    \nProof.\n  Time run_rtac reify_imp term_table (@runTac_sound rw_fail).\nQed.\n\nRequire Import BinInt.\n\nFixpoint mkSwapPre n : sasn :=\n\tmatch n with\n\t  | 0   => empSP\n\t  | S n => ap_pointsto [(\"o\": Lang.var), (append \"f\" (nat2string10 n) : field), \n\t  \t                     (eval (E_val (vint (Z.of_nat n))))] **\n\t           mkSwapPre n\n\tend.  \n\n\t\nFixpoint mkSwapPostAux n m :=\n  match n with\n    | 0 => empSP\n\t| S n => ap_pointsto [(\"o\": Lang.var), (append \"f\" (nat2string10 n) : field), \n\t  \t                     (eval (E_val (vint (Z.of_nat (m - (S n))))))] **\n\t         mkSwapPostAux n m\n  end.           \n  \nDefinition mkSwapPost n := mkSwapPostAux n n.\n\nFixpoint mkRead n c :=\n\tmatch n with\n\t  | 0 => c\n\t  | S n => cseq (cread ((append \"x\" (nat2string10 n):Lang.var)) (\"o\":Lang.var) ((append \"f\" (nat2string10 n)):field))\n\t                (mkRead n c)\n    end.\n\t\t\t\t\t\t\nFixpoint mkWriteAux n m c :=\n\tmatch n with\n\t  | 0 => c\n\t  | S n => cseq (cwrite (\"o\":Lang.var) (append \"f\" (nat2string10 n)) (E_var (append \"x\" (nat2string10 (m - (S n))))))\n\t                (mkWriteAux n m c)\n    end.\n\nDefinition mkWrite n c := mkWriteAux n n c.\n\nDefinition mkSwapProg (n : nat) (c : cmd) := mkRead n (mkWrite n c).\n\t\nDefinition mkSwap n :=\n\tltrue |-- triple (mkSwapPre n) (mkSwapPost n) (mkSwapProg n cskip).\n\nSet Printing Depth 100.\n\n  Opaque ap.\n\nLemma test_swap : \n|--\n( {[ap_pointsto  [\"o\", (\"f\")%string, eval (E_val (vint 5))] **\n    ap_pointsto  [\"o\", (\"g\")%string, eval (E_val (vint 6))] ** empSP]}\n (\"x\")%string R= \"o\" [(\"f\")%string];;\n (\"y\")%string R= \"o\" [(\"g\")%string];;\n \"o\" [(\"f\")%string] W= E_var (\"y\")%string;;\n \"o\" [(\"g\")%string] W=E_var (\"x\")%string;; Skip\n {[ap_pointsto  [\"o\", (\"f\")%string, eval (E_val (vint 6))] **\n   ap_pointsto  [\"o\", (\"g\")%string, eval (E_val (vint 5))] ** empSP]} ).\nProof.\n  Time run_rtac reify_imp term_table (@runTac_sound rw_fail).\nQed.\n\n\n\n\nLemma test_skip_lemma4 : testSkip 10.\nProof.\n  unfold testSkip; simpl.\n  \n  Time run_rtac reify_imp term_table (@runTac_sound rw_fail).\nTime Qed.\n\n\n\n\n\n\nPrint rtac_sound.\nPrint rtac_spec.\n\nLemma test_swap2 : mkSwap 20.\nProof.\n  unfold mkSwap, mkSwapPre, mkSwapPost, mkSwapProg, mkSwapPostAux, mkRead, mkWrite, mkWriteAux.\n  \n  Time run_rtac reify_imp term_table (@runTac_sound rw_fail).\nTime Qed.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nEnd blurb.\n\nInstance EmptyEnv : Environment := {\n  java_env := SymEnv.from_list nil\n}.\n\n\nDefinition ASSUMPTION : rtac typ (expr typ func) :=\n  EASSUMPTION (fun _ _ _ _ x y s => if x ?[ eq ] y then Some s else None).\n\nLemma ASSUMPTION_sound : rtac_sound ASSUMPTION.\nProof.\n  admit.\nQed.\n\nLtac rtac_derive_soundness :=\n  repeat first [ eapply IDTAC_sound\n               | eapply ASSUMPTION_sound\n               | eapply FAIL_sound\n               | eapply INSTANTIATE_sound\n               | eapply INTRO_sound\n               | eapply FIRST_sound ; Forall_rtac_derive_soundness\n               | eapply SOLVE_sound ; rtac_derive_soundness\n               | eapply THEN_sound ;\n                 [ rtac_derive_soundness\n                 | rtacK_derive_soundness ]\n               | eapply TRY_sound ; rtac_derive_soundness\n               | eapply REPEAT_sound ; rtac_derive_soundness\n               | eapply AT_GOAL_sound ; [ intros ; rtac_derive_soundness ]\n               | eapply APPLY_sound ; [ simpl ] (* TODO(gmalecha): Needs to change *)\n               | eapply EAPPLY_sound ; [ simpl ]  (* TODO(gmalecha): Needs to change *)\n               ]\nwith rtacK_derive_soundness :=\n  first [ solve [eauto]\n        | eapply runOnGoals_sound ; rtac_derive_soundness\n        ]\nwith Forall_rtac_derive_soundness :=\n  repeat first [ \n                 eapply Forall_nil\n               | eapply Forall_cons ;\n                 [ try rtac_derive_soundness\n                 | try Forall_rtac_derive_soundness ] ].\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nLemma LTrue : True.\nProof.\n  apply I.\nQed.\n\nDefinition true_lemma : lemma typ (expr typ func) (expr typ func).\nreify_lemma reify_imp LTrue.\nDefined.\nPrint true_lemma.\n(*\ntrue_lemma = \n{| vars := nil; premises := nil; \n  concl := Inj (inl (inl (inl (inl (inl (inl (inl (inr (ilf_true tyProp))))))))) |}\n     : lemma typ (expr typ func) (expr typ func)\n*)\nLemma true_lemma_sound : \n\tlemmaD (exprD'_typ0 (T:=Prop)) nil nil true_lemma.\nProof.\n  compute.\n  apply LTrue.\nQed.\n\nDefinition AUTO := APPLY typ func true_lemma.\n\nLemma AUTO_sound : rtac_sound AUTO.\nProof.\n  admit.\nQed.\n\nLemma test_true : True.\nProof.\n  run_rtac reify_imp term_table AUTO_sound.\nQed.\n  \nPrint test_true.\n\n\n\n\n(*\n\ntest_true = \nlet tbl := FMapPositive.PositiveMap.Leaf (SymEnv.function RType_typ) in\nlet e := mkTrue tyProp in\nrun_rtac_Solved AUTO (TopSubst (expr typ func) nil nil) e AUTO_sound\n  (eq_refl<:run_tac AUTO (GGoal (mkTrue tyProp)) = Solved (TopSubst (expr typ func) nil nil))\n     : True\n\n*)\n\n\n\n\n\n\n\n\n\n\n\nLemma andI (P Q : Prop) (HP : P) (HQ : Q) : P /\\ Q.\nProof.\n  tauto.\nQed.\n\nDefinition andI_lemma : lemma typ (expr typ func) (expr typ func).\nProof.\n  reify_lemma reify_imp andI.\nDefined.\nPrint andI_lemma.\nLemma andI_lemma_sound : \n\tlemmaD (exprD'_typ0 (T:=Prop)) nil nil andI_lemma.\nProof.\n  compute. intros. apply andI. assumption. assumption.\nQed.\n\nDefinition AUTO' := \n  THEN (REPEAT 10 (INTRO typ func)) \n    (FIRST (THEN (APPLY typ func andI_lemma) ASSUMPTION ::\n      (APPLY typ func true_lemma) :: ASSUMPTION :: nil)).\n    \nLemma AUTO'_sound : rtac_sound AUTO'.\nProof.\n  unfold AUTO'.\n  rtac_derive_soundness.\n  admit.\n  admit.\nQed.\n\nLemma test_and : forall (P Q R : Prop), Q -> P -> R -> P /\\ Q.\nProof.\n  run_rtac reify_imp term_table AUTO'_sound.\nQed.\n\nPrint test_and.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nLemma orI1 (P Q : Prop) (HP : P) : P \\/ Q.\nProof.\n  tauto.\nQed.\n\nLemma orI2 (P Q : Prop) (HQ : Q) : P \\/ Q.\nProof.\n  tauto.\nQed.\n\nDefinition orI1_lemma : lemma typ (expr typ func) (expr typ func).\nProof.\n  reify_lemma reify_imp orI1.\nDefined.\n\nDefinition orI2_lemma : lemma typ (expr typ func) (expr typ func).\nProof.\n  reify_lemma reify_imp orI2.\nDefined.\n\nLemma orI1_lemma_sound : \n\tlemmaD (exprD'_typ0 (T:=Prop)) nil nil orI1_lemma.\nProof.\n  compute. intros. apply orI1. assumption.\nQed.\n\nLemma orI2_lemma_sound : \n\tlemmaD (exprD'_typ0 (T:=Prop)) nil nil orI1_lemma.\nProof.\n  compute. intros. apply orI1. assumption.\nQed.\n\nDefinition AUTO'' := \n  REC 20\n    (fun rec => THEN (REPEAT 10 (INTRO typ func)) \n      (FIRST \n        (THEN (APPLY typ func andI_lemma) rec ::\n        (THEN (APPLY typ func orI1_lemma) rec) ::\n        (THEN (APPLY typ func orI2_lemma) rec) ::\n        (APPLY typ func true_lemma) :: ASSUMPTION :: nil)))\n    FAIL.\n    \nLemma AUTO''_sound : rtac_sound AUTO''.\nProof.\n  unfold AUTO''.\n  (* rtac_derive_soundness. *)\n  admit.\nQed.\n\nLemma test_and2 : forall (P Q R T : Prop),\n\t Q -> P -> R -> (P /\\ Q /\\ R) \\/\n\t    (Q /\\ T /\\ (R /\\ R) /\\ (P /\\ Q) /\\ Q).\nProof.\n  run_rtac reify_imp term_table AUTO''_sound.\nQed.\n(*\nLtac run_rtac reify term_table tac_sound :=\n  match type of tac_sound with\n    | rtac_sound ?tac =>\n\t  let name := fresh \"e\" in\n\t  match goal with\n\t    | |- ?P => \n\t      reify_aux reify term_table P name;\n\t      let t := eval vm_compute in (typeof_expr nil nil name) in\n\t      let goal := eval unfold name in name in\n\t      match t with\n\t        | Some ?t =>\n\t          let goal_result := constr:(run_tac tac (GGoal name)) in \n\t          let result := eval vm_compute in goal_result in\n\t          match result with\n\t            | More_ ?s ?g => \n\t              cut (goalD_Prop nil nil g); [\n\t                let goal_resultV := g in\n\t               (* change (goalD_Prop nil nil goal_resultV -> exprD_Prop nil nil name);*)\n\t                exact_no_check (@run_rtac_More _ tac _ _ _ tac_sound\n\t                \t(@eq_refl (Result (CTop nil nil)) (More_ s goal_resultV) <:\n\t                \t   run_tac tac (GGoal goal) = (More_ s goal_resultV)))\n\t                | cbv_denote\n\t              ]\n\t            | Solved ?s =>\n\t              exact_no_check (@run_rtac_Solved _ tac s name tac_sound \n\t                (@eq_refl (Result (CTop nil nil)) (Solved s) <: run_tac tac (GGoal goal) = Solved s))\n\t            | Fail => idtac \"Tactic\" tac \"failed.\"\n\t            | _ => idtac \"Error: run_rtac could not resolve the result from the tactic :\" tac\n\t          end\n\t        | None => idtac \"expression \" goal \"is ill typed\" t\n\t      end\n\t  end\n\t| _ => idtac tac_sound \"is not a soudness theorem.\"\n  end.\n  *)\nRequire Import Charge.Tactics.Rtac.PullQuant.\n  \nLemma PULL_EXISTSL_sound : rtac_sound (THEN (REPEAT 10 (INTRO typ func)) (PULL_EXISTSL typ func ilops)).\nProof.\n  admit.\nQed.\n\nLemma test_pull_quant_left  (P : sasn) (Q : nat -> sasn) :\n  P //\\\\ (Exists x : nat, Q x) |-- P.\nProof.\n  run_rtac reify_imp term_table PULL_EXISTSL_sound.\n  \n  Print func.\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/Tactics/SymEx.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2712311117426701}}
{"text": "Require Import Relations.Relation_Operators.\nRequire Import RelationClasses.\n\nRequire Import Automation.\nRequire Import Prog.\n\n(** Here we prove some basic sanity checks on prog and its semantics. *)\n\nLocal Hint Constructors exec.\n\nTheorem can_crash_at_begin : forall `(p: prog T) w,\n    can_crash ->\n    exec p w (Crashed w).\nProof.\n  eauto.\nQed.\n\nTheorem can_crash_at_end : forall `(p: prog T) w v w',\n    can_crash ->\n    exec p w (Finished v w') ->\n    exec p w (Crashed w').\nProof.\n  (* This is a slightly harder proof strategy (induction over the programs is\n  more straightforward), but this proof doesn't require finite programs! *)\n  intros.\n  remember (Finished v w').\n  induction H0;\n    try match goal with\n        | [ H: _ = Finished _ _ |- _ ] =>\n          inversion H; subst; clear H\n        end; eauto.\nQed.\n\nLocal Hint Resolve can_crash_at_begin can_crash_at_end.\n\n(** These are the monad laws\n\nTODO: explain what the monad is and what these monad laws mean (specifically,\nwe're proving that exec treats programs up to the monad laws as equivalences\nbetween programs).\n *)\n\nDefinition exec_equiv T (p: prog T) p' :=\n  forall w r, exec p w r <-> exec p' w r.\n\nInstance exec_equiv_equiv T : Equivalence (exec_equiv (T:=T)).\nProof.\n  constructor; hnf; unfold exec_equiv; intros;\n    repeat match goal with\n           | [ H: forall (w:world) (r: Result T), _,\n                 w: world,\n                 r: Result T |- _ ] =>\n             specialize (H w r)\n           end; intuition.\nQed.\n\nLtac cleanup_exec :=\n  match goal with\n  | [ H: exec (Ret _) _ ?r |- _ ] =>\n    first [ is_var r |\n            apply exec_ret in H; safe_intuition; subst ]\n  end.\n\nTheorem monad_left_id : forall T T' (p: T' -> prog T) v,\n    exec_equiv (Bind (Ret v) p) (p v).\nProof.\n  unfold exec_equiv; split; intros.\n  - inv_exec; try cleanup_exec; eauto.\n  - eapply ExecBindFinished; eauto.\nQed.\n\nTheorem monad_right_id : forall `(p: prog T),\n    exec_equiv (Bind p (fun v => Ret v)) p.\nProof.\n  unfold exec_equiv; split; intros.\n  - destruct r; inv_exec; try cleanup_exec; eauto.\n  - destruct r; eauto.\nQed.\n\nTheorem monad_assoc : forall `(p1: prog T)\n                        `(p2: T -> prog T')\n                        `(p3: T' -> prog T''),\n    exec_equiv (Bind (Bind p1 p2) p3) (Bind p1 (fun v => Bind (p2 v) p3)).\nProof.\n  unfold exec_equiv; split; intros.\n  - destruct r; repeat (inv_exec; eauto).\n  - destruct r; repeat (inv_exec; eauto).\nQed.\n\n(** invert a bind execution *)\nLemma exec_bind : forall T T' `(p: prog T) (p': T -> prog T')\n                    w r,\n    exec (Bind p p') w r ->\n    (exists v w', exec p w (Finished v w') /\\\n             exec (p' v) w' r) \\/\n    (exists w', exec p w (Crashed w') /\\\n           r = Crashed w').\nProof.\n  intros.\n  inv_exec; eauto.\nQed.\n\nLocal Hint Constructors rexec.\n\nTheorem rexec_equiv : forall T (p p': prog T) `(rec: prog R) w r,\n    exec_equiv p p' ->\n    rexec p' rec w r ->\n    rexec p rec w r.\nProof.\n  intros.\n  inv_rexec.\n  apply H in H1; eauto.\n  apply H in H1; eauto.\nQed.\n\n(* When a program finishes, its recovery procedure is irrelevant. *)\nLemma rexec_finish_any_rec : forall `(p: prog T)\n                               `(rec: prog R)\n                               `(rec': prog R')\n                               w v w',\n    rexec p rec w (RFinished v w') ->\n    rexec p rec' w (RFinished v w').\nProof.\n  intros.\n  inversion H; subst; eauto.\nQed.\n\nLemma rexec_recover_bind_inv : forall `(p: prog T)\n                                 `(p': T -> prog T')\n                                 `(rec: prog R)\n                                 w rv w'',\n    rexec (Bind p p') rec w (Recovered rv w'') ->\n    rexec p rec w (Recovered rv w'') \\/\n    exists v w', rexec p rec w (RFinished v w') /\\\n            rexec (p' v) rec w' (Recovered rv w'').\nProof.\n  intros.\n  inversion H; subst.\n  inv_exec.\n  - left; eauto.\n  - right.\n    descend; intuition eauto.\n  - left; eauto.\nQed.\n\nLocal Hint Constructors exec_recover.\n\nArguments clos_refl_trans_1n {A} R _ _.\n\n(** Invert looped recovery execution for a bind in the recovery procedure. The\nwment essentially breaks down the execution of recovering with [_ <- p; p']\ninto three stages:\n\n- First, p runs until it finishes without crashing.\n- Next, p' is repeatedly run using p as the recovery procedure, crashing and\n  recovering in a loop. The return value in [p' rv] comes from p and is passed\n  from iteration to the next, initialized with the run of p in the first step.\n- Finally, the computer stops crashing and [p' rv] can run to completion.\n *)\nLemma exec_recover_bind_inv : forall `(p: prog R)\n                                `(p': R -> prog R')\n                                w rv' w'',\n    exec_recover (Bind p p') w rv' w'' ->\n    exists rv1 w1, exec_recover p w rv1 w1 /\\\n                  exists rv2 w2,\n                    clos_refl_trans_1n\n                      (fun '(rv, w) '(rv', w') =>\n                         rexec (p' rv) p w (Recovered rv' w'))\n                      (rv1, w1) (rv2, w2) /\\\n                    exec (p' rv2) w2 (Finished rv' w'').\nProof.\n  induction 1.\n  - inv_exec; eauto 10 using rt1n_refl.\n  - repeat deex.\n    inv_exec; eauto 10.\n    descend; intuition eauto.\n    descend; intuition eauto.\n    eapply rt1n_trans; eauto.\n    simpl; eauto.\nQed.\n", "meta": {"author": "mit-pdos", "repo": "deepspec-pocs", "sha": "699767342c0daf4657f03ef8f7a7a3ba91e79a6e", "save_path": "github-repos/coq/mit-pdos-deepspec-pocs", "path": "github-repos/coq/mit-pdos-deepspec-pocs/deepspec-pocs-699767342c0daf4657f03ef8f7a7a3ba91e79a6e/src/Refinement/ProgTheorems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2711683109873147}}
{"text": "\nLoad \"ExtraProof_1\".\n\n(*******************if EQ(x1 , x2) then x1 else y = if EQ(x1 ,x2) then x2 else y***************************************)\n\n\n\n\nTheorem Example11_M:   (if_then_else_M (EQ_M  (Mvar 1) (Mvar 2)) (Mvar 1) (Mvar 3)) # (if_then_else_M (EQ_M  (Mvar 1) (Mvar 2)) (Mvar 2) (Mvar 3)) .\nProof.\nintros.\nrewrite EQmsg .\n(assert(H1:  (EQ_M (if_then_else_M (Bvar 0) (Mvar 1) (Mvar 3) ) (if_then_else_M (Bvar 0) (Mvar 2) (Mvar 3) )) ## (if_then_else_B (Bvar 0) (EQ_M  (Mvar 1) (if_then_else_M (Bvar 0) (Mvar 2) (Mvar 3) ))  (EQ_M  (Mvar 3) (if_then_else_M (Bvar 0) (Mvar 2) (Mvar 3) ))))).\napply IFMORPH_M3 with (n:=0) (n1:=1)(n2:=2)(n3:=3)  .\napply Forall_ELM_EVAL_B  with (n:=0) (b:= (EQ_M (Mvar 1) (Mvar 2))) in H1.\nsimpl in H1.\nassert (H2: (if_then_else_B (Bvar 0)\n    [[4 := if_then_else_M (Bvar 0) (Mvar 2) (Mvar 3)]](EQ_M (Mvar 1) (Mvar 4))\n    [[4 := if_then_else_M (Bvar 0) (Mvar 2) (Mvar 3)]](EQ_M (Mvar 3) (Mvar 4))) ##\n  ( if_then_else_B (Bvar 0) [[4 := Mvar 2]](EQ_M (Mvar 1) (Mvar 4))\n    [[4 := Mvar 3]](EQ_M (Mvar 3) (Mvar 4))) ).\napply Ex9msg_bol1 with (b:= (Bvar 0))(n1:=2)(n2:=3)(n3:=2)(n4:=3)(n5:=4)(n6:= 4) (b1:= (EQ_M (Mvar 1) (Mvar 4))) (b2:= (EQ_M (Mvar 3) (Mvar 4))) .\nsimpl in H2.\napply Forall_ELM_EVAL_B  with (n:=0) (b:= (EQ_M (Mvar 1) (Mvar 2))) in H2.\nsimpl in H2.\nrewrite H2 in H1 .\nrewrite H1.\nassert (H3:   (EQ_M (Mvar 3) (Mvar 3)) ##   TRue).\napply EQmsg with (x:=(Mvar 3))( y:= (Mvar 3)).\nreflexivity. \nrewrite H3.\n(***\nsetoid_replace  (if_then_else_B (EQ_M (Mvar 1) (Mvar 2)) (EQ_M (Mvar 1) (Mvar 2))\n   (EQ_M (Mvar 3) (Mvar 3))) with  (if_then_else_B (EQ_M (Mvar 1) (Mvar 2)) (EQ_M (Mvar 1) (Mvar 2))\n   (TRue)) using relation EQb.\n**)\nassert (H4: (if_then_else_B (Bvar 0) TRue FAlse) ## (Bvar 0)).\napply IFTF with (n:=0).\napply Forall_ELM_EVAL_B2 with (n :=0)(b:= (EQ_M (Mvar 1) (Mvar 2))) in H4.\nsimpl  in H4.\nassert(H6:  (if_then_else_B (Bvar 0) (Bvar 0) TRue) ## (if_then_else_B (Bvar 0) TRue TRue)).\napply IFEVAL_B with (n:=0) (b1:=(Bvar 0)) (b2:= TRue) .\napply Forall_ELM_EVAL_B with (n :=0)(b:= (EQ_M (Mvar 1) (Mvar 2))) in H6.\nsimpl  in H6.\nrewrite H6.\napply IFSAME_B.\nQed.\n\n\nTheorem Example11_B:    (if_then_else_B (EQ_B  (Bvar 1) (Bvar 2)) (Bvar 1) (Bvar 3)) ## ( if_then_else_B (EQ_B  (Bvar 1) (Bvar 2)) (Bvar 2) (Bvar 3) ).\nProof.\nintros.\nrewrite EQ_Bool .\n(assert(H1:  (EQ_B (if_then_else_B (Bvar 0) (Bvar 1) (Bvar 3) ) (if_then_else_B (Bvar 0) (Bvar 2) (Bvar 3) )) ## (if_then_else_B (Bvar 0) (EQ_B  (Bvar 1) (if_then_else_B (Bvar 0) (Bvar 2) (Bvar 3) ))  (EQ_B  (Bvar 3) (if_then_else_B (Bvar 0) (Bvar 2) (Bvar 3) ))))).\nassert (H2 : (EQ_B (if_then_else_B (Bvar 0) (Bvar 1) (Bvar  3)) (Bvar 4)) ## ( if_then_else_B (Bvar 0) (EQ_B (Bvar 1) (Bvar 4) ) (EQ_B (Bvar 3) (Bvar 4)))).\napply IFMORPH_B3 with  (n:=0) (n1:=1).\napply Forall_ELM_EVAL_B  with (n:=4) (b:= if_then_else_B (Bvar 0) (Bvar 2) (Bvar 3) )in H2.\nsimpl in H2.\napply H2.\napply Forall_ELM_EVAL_B  with (n:=0) (b:= (EQ_B (Bvar 1) (Bvar 2))) in H1.\nsimpl in H1.\nassert (H2:  (if_then_else_B (Bvar 0) (EQ_B (Bvar 1) (if_then_else_B (Bvar 0) (Bvar 2) (Bvar 3) ) )   (EQ_B (Bvar 3) (if_then_else_B (Bvar 0) (Bvar 2) (Bvar 3) ) )) ## (if_then_else_B (Bvar 0) (EQ_B (Bvar 1) (Bvar 2) ) ( EQ_B (Bvar 3) (Bvar 3))  )).\napply Ex9bol_bol1 with (n1:=2)(n2:=3)(n3:=2)(n4:=3)(n5:=4)(n6:= 4) (b1:= (EQ_B (Bvar 1) (Bvar 4))) (b2:= (EQ_B (Bvar 3) (Bvar 4))) .\napply Forall_ELM_EVAL_B  with (n:=0) (b:= (EQ_B (Bvar 1) (Bvar 2))) in H2.\nsimpl in H2.\nrewrite H1 .\nrewrite H2.\nassert (H3:   (EQ_B (Bvar 3) (Bvar 3)) ## TRue).\napply EQ_Bool with (x:=(Bvar 3))( y:= (Bvar 3)).\nreflexivity.\nrewrite H3. \n(***setoid_replace  (if_then_else_B (EQ_B (Bvar 1) (Bvar 2)) (EQ_B (Bvar 1) (Bvar 2))\n   (EQ_B (Bvar 3) (Bvar 3))) with  (if_then_else_B (EQ_B (Bvar 1) (Bvar 2)) (EQ_B (Bvar 1) (Bvar 2))\n   (TRue)) using relation EQb. **)\nassert (H4: (if_then_else_B (Bvar 0) TRue FAlse) ## (Bvar 0)).\napply IFTF with (n:=0).\napply Forall_ELM_EVAL_B2 with (n :=0)(b:= (EQ_B (Bvar 1) (Bvar 2))) in H4.\nsimpl  in H4.\nassert(H6: (if_then_else_B (Bvar 0) (Bvar 0) TRue) ## ( if_then_else_B (Bvar 0) TRue TRue)).\napply IFEVAL_B with (n:=0) (b1:=(Bvar 0)) (b2:= TRue) .\napply Forall_ELM_EVAL_B with (n :=0)(b:= (EQ_B (Bvar 1) (Bvar 2))) in H6.\nsimpl  in H6.\nrewrite H6.\napply IFSAME_B.\nQed.\n\n\nAxiom Example11_B1: forall (n1 n2 n3 :nat), (if_then_else_B (EQ_B  (Bvar n1) (Bvar n2)) (Bvar n1) (Bvar n3))  ## ( if_then_else_B (EQ_B  (Bvar n1) (Bvar n2)) (Bvar n2) (Bvar n3)).\nAxiom Example11_B2: forall (n1 n2 n3 :nat),  (if_then_else_B (EQ_M  (Mvar n1) (Mvar n2)) (Bvar n1) (Bvar n3))  ## (if_then_else_B (EQ_M  (Mvar n1) (Mvar n2)) (Bvar n2) (Bvar n3)).\nAxiom Example11_M1:forall(n1 n2 n3:nat),   (if_then_else_M (EQ_M  (Mvar n1) (Mvar n2)) (Mvar n1) (Mvar n3) ) # (if_then_else_M (EQ_M  (Mvar n1) (Mvar n2)) (Mvar n2) (Mvar n3)).\nAxiom Example11_M2:forall(n1 n2 n3:nat),   (if_then_else_M (EQ_B  (Bvar n1) (Bvar n2)) (Mvar n1) (Mvar n3) ) # (if_then_else_M (EQ_B  (Bvar n1) (Bvar n2)) (Mvar n2) (Mvar n3)).\n", "meta": {"author": "ajayeeralla", "repo": "compSoundProofsWOracleMoves", "sha": "8480855887a9092d16dc183ce6ed19315a3ffa96", "save_path": "github-repos/coq/ajayeeralla-compSoundProofsWOracleMoves", "path": "github-repos/coq/ajayeeralla-compSoundProofsWOracleMoves/compSoundProofsWOracleMoves-8480855887a9092d16dc183ce6ed19315a3ffa96/Example11.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.27116830409672554}}
{"text": "Set Implicit Arguments.\n\nRequire Import Platform.Facade.DFacade.\nRequire Import Platform.Facade.Notations.\nImport Notations.OpenScopes.\n\nSection ADTValue.\n\n  Variable ADTValue : Type.\n  Variables ArraySeq_newSpec ArraySeq_writeSpec ArraySeq_readSpec ArraySeq_deleteSpec ListSet_newSpec ListSet_addSpec ListSet_sizeSpec ListSet_deleteSpec : AxiomaticSpec ADTValue.\n\n  Definition count_unique :=\n    module\n    import {\n      \"ADT\"!\"ArraySeq_new\" ==> ArraySeq_newSpec;\n      \"ADT\"!\"ArraySeq_write\" ==> ArraySeq_writeSpec;\n      \"ADT\"!\"ArraySeq_read\" ==> ArraySeq_readSpec;\n      \"ADT\"!\"ArraySeq_delete\" ==> ArraySeq_deleteSpec;\n      \"ADT\"!\"ListSet_new\" ==> ListSet_newSpec;\n      \"ADT\"!\"ListSet_add\" ==> ListSet_addSpec;\n      \"ADT\"!\"ListSet_size\" ==> ListSet_sizeSpec;\n      \"ADT\"!\"ListSet_delete\" ==> ListSet_deleteSpec\n    }\n    define {\n      def \"count\" = func(\"arr\", \"len\") {\n        \"set\" <-- call_ \"ADT\"!\"ListSet_new\"();\n        \"i\" <- 0;\n        while_ (\"i\" < \"len\") {\n          \"e\" <-- call_ \"ADT\"!\"ArraySeq_read\" (\"arr\", \"i\");\n          call_ \"ADT\"!\"ListSet_add\"(\"set\", \"e\");\n          \"i\" <- \"i\" + 1\n        };\n        \"ret\" <-- call_ \"ADT\"!\"ListSet_size\"(\"set\");\n        call_ \"ADT\"!\"ListSet_delete\"(\"set\")\n      };\n      def \"main\" = func() {\n(*\n        \"arr\" <-- call_ \"ADT\"!\"ArraySeq_new\"(3);;\n        call_ \"ADT\"!\"ArraySeq_write\"(\"arr\", 0, 10);;\n        call_ \"ADT\"!\"ArraySeq_write\"(\"arr\", 1, 20);;\n        call_ \"ADT\"!\"ArraySeq_write\"(\"arr\", 2, 10);;\n        \"ret\" <-- call_ \"count\"!\"count\" (\"arr\", 3);;\n        call_ \"ADT\"!\"ArraySeq_delete\"(\"arr\")\n*)\n        \"ret\" <- 0\n      }\n    }.\n\n  Require Import Platform.Facade.CompileDFModule.\n\n  Definition gmodule := compile_to_gmodule count_unique \"count_unique\" eq_refl.\n\n  (* test executability *)\n  Require Import Platform.Cito.GoodModuleDec.\n  Require Import Platform.Cito.IsGoodModule.\n\n  Goal is_good_module gmodule = true. Proof. exact eq_refl. Qed.\n\nEnd ADTValue.\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/Facade/examples/NotationExample.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2711683040967255}}
{"text": "Require Import Category.\n\nSet Universe Polymorphism.\n\nInstance Coq : Category := {|\n  object := Type;\n  morphism A B := A -> B;\n  id A a := a;\n  composition A B C f g a := g (f a)\n|}.\nProof.\n  all: intros; reflexivity.\nDefined.", "meta": {"author": "konne88", "repo": "category-theory", "sha": "883c4edd35ad47c82300315d1cd5c7f9238bede6", "save_path": "github-repos/coq/konne88-category-theory", "path": "github-repos/coq/konne88-category-theory/category-theory-883c4edd35ad47c82300315d1cd5c7f9238bede6/Construction/Coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.27104394532080195}}
{"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 O E Eprime A B C Oprime Aprime Bprime Cprime Eprimeprime C2 B0 : Universe, ((wd_ O E /\\ (wd_ Oprime Eprime /\\ (wd_ A O /\\ (wd_ B O /\\ (wd_ C O /\\ (wd_ A E /\\ (wd_ Eprimeprime O /\\ (wd_ O Oprime /\\ (wd_ E Eprimeprime /\\ (wd_ Eprimeprime A /\\ (wd_ E Eprime /\\ (wd_ O Eprime /\\ (wd_ Oprime Eprimeprime /\\ (wd_ E Oprime /\\ (wd_ Eprime C2 /\\ (wd_ Aprime C2 /\\ (wd_ Oprime Aprime /\\ (wd_ A Aprime /\\ (wd_ C Cprime /\\ (wd_ B Bprime /\\ (col_ O E A /\\ (col_ O E B /\\ (col_ O E C /\\ (col_ Oprime Eprime Aprime /\\ (col_ Oprime Eprime Bprime /\\ (col_ Oprime Eprime Cprime /\\ (col_ O Eprimeprime O /\\ (col_ O Eprimeprime Oprime /\\ (col_ O Eprimeprime C2 /\\ (col_ Eprimeprime B O /\\ col_ O E B0)))))))))))))))))))))))))))))) -> col_ O E Eprimeprime)).\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_1281.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.37387583672470853, "lm_q1q2_score": 0.2710114854668007}}
{"text": "From iris.algebra Require Import frac agree.\nFrom iris.proofmode Require Import tactics.\nFrom iris.program_logic Require Import adequacy.\n\nFrom fae_gtlc_mu Require Import refinements.gradual_static.logical_relation.\nFrom fae_gtlc_mu Require Import cast_calculus.lang stlc_mu.lang.\n\nSection adequacy.\n  Context `{!inG Σ specR, !invPreG Σ}.\n\n  Lemma adequacy\n    (e : cast_calculus.lang.expr) (e' : stlc_mu.lang.expr) (τ : cast_calculus.types.type) :\n    (∀ `{!implG Σ, !specG Σ}, [] ⊨ e ≤log≤ e' : τ) →\n    (cast_calculus.lang.Halts e) →\n    (stlc_mu.lang.Halts e').\n  Proof.\n    intros Hlog Hsteps.\n    (** Using Iris' adequacy result for weakest preconditions to prove that e' Halts (assuming that the right WP holds) *)\n    cut (adequate MaybeStuck e tt (λ _ _, ∃ v', rtc erased_step ([e'], tt) (of_val v' :: [], tt))).\n    { rewrite /cast_calculus.lang.Halts in Hsteps. destruct 1. naive_solver. }\n    eapply (wp_adequacy Σ); first by apply _.\n    (** Actually prove that the right WP holds *)\n    iIntros (Hinv ?).\n    (* Allocate two halfs at e' to specify static part *)\n    iMod (own_alloc ((((1/2)%Qp , to_agree e') ⋅ ((1/2)%Qp , to_agree e')) : specR)) as (spec_name) \"[Hs1 Hs2]\".\n    { rewrite -pair_op frac_op' Qp_half_half agree_idemp.\n      apply pair_valid; split; try done; try by apply frac_valid'. }\n    set (SpecΣ := SpecG Σ inG0 spec_name).\n    set (ImplΣ := ImplG Σ Hinv).\n    (* Allocate invariant with e' using one of the halfs *)\n    iMod (inv_alloc specN _ (initially_body e') with \"[Hs1]\") as \"#Hinitially\".\n    { iNext. iExists e'. iSplit; eauto. }\n    iExists (λ _ _, True%I), (λ _, True%I); iSplitR; first done.\n    (* Proving goal by obtaining the WP in the conclusion of Hlog *)\n    iApply wp_fupd. iApply (wp_wand with \"[-]\").\n    - (* Using conclusion in Hlog *) iPoseProof (Hlog ImplΣ SpecΣ [] e' with \"[]\") as \"Hrel\".\n      { iSplit; auto. iApply interp_env_nil. }\n      replace e with (e.[cast_calculus.typing_lemmas.env_subst [] ]) at 2 by by asimpl.\n      iApply (\"Hrel\" $! []). asimpl; iFrame.\n    - (* Given postcondition in WP of Hlog and invariant, we continue proving the goal *)\n      iModIntro. simpl. iIntros (v'). iDestruct 1 as (v2) \"[Hj #Hinterp]\".\n      iExists v2.\n      (* open invariant to get contents *)\n      iInv specN as \">Hinv\" \"Hclose\".\n      (* prove that e'' must correspond to v2 *)\n      iDestruct \"Hinv\" as (e'') \"[He'' %]\".\n      iDestruct (own_valid_2 with \"He'' Hj\") as %Hvalid.\n      rewrite -pair_op frac_op' Qp_half_half in Hvalid.\n      move: Hvalid=> /pair_valid [_ /agree_op_inv' b]. apply leibniz_equiv in b. subst.\n      (* close invariant *) iMod (\"Hclose\" with \"[-]\") as \"_\". iExists v2. auto.\n      iIntros \"!> !%\". eauto.\n  Qed.\n\nEnd adequacy.\n\nDefinition actualΣ : gFunctors := #[ invΣ ; GFunctor specR ].\n\nInstance subG_inG_specR {Σ} : subG (GFunctor specR) Σ → inG Σ specR.\nProof. solve_inG. Qed.\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/adequacy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.27101148102248085}}
{"text": "(*! Understanding conflicts and forwarding, with modules !*)\nRequire Import Koika.Frontend.\n\nModule Import Queue32.\n  Inductive reg_t := empty | data.\n  Definition R reg :=\n    match reg with\n    | empty => bits_t 1\n    | data => bits_t 32\n    end.\n\n  Definition dequeue0: UInternalFunction reg_t empty_ext_fn_t :=\n    {{ fun dequeue0 () : bits_t 32 =>\n         guard(!read0(empty)); write0(empty, Ob~1); read0(data) }}.\n\n  Definition enqueue0: UInternalFunction reg_t empty_ext_fn_t :=\n    {{ fun enqueue0 (val: bits_t 32) : unit_t =>\n         guard(read0(empty)); write0(empty, Ob~0); write0(data, val) }}.\n\n  Definition dequeue1: UInternalFunction reg_t empty_ext_fn_t :=\n    {{ fun dequeue1 () : bits_t 32 =>\n         guard(!read1(empty)); write1(empty, Ob~1); read1(data) }}.\nEnd Queue32.\n\nInductive reg_t :=\n| in0: Queue32.reg_t -> reg_t\n| in1: Queue32.reg_t -> reg_t\n| fifo: Queue32.reg_t -> reg_t\n| out: Queue32.reg_t -> reg_t.\n\nInductive rule_name_t := deq0 | deq1 | process.\n\nDefinition R (reg: reg_t) : type :=\n  match reg with\n  | in0 st => Queue32.R st\n  | in1 st => Queue32.R st\n  | fifo st => Queue32.R st\n  | out st => Queue32.R st\n  end.\n\nDefinition urules (rl: rule_name_t) : uaction reg_t empty_ext_fn_t :=\n  match rl with\n  | deq0 =>\n    {{ fifo.(enqueue0)(in0.(dequeue0)()) }}\n  | deq1 =>\n    {{ fifo.(enqueue0)(in1.(dequeue0)()) }}\n  | process =>\n    {{ out.(enqueue0)(|32`d412| + fifo.(dequeue1)()) }}\n  end.\n\nDefinition rules : rule_name_t -> rule R empty_Sigma :=\n  tc_rules R empty_Sigma urules.\n\nDefinition pipeline : scheduler :=\n  deq0 |> deq1 |> process |> done.\n\nDefinition external (r: rule_name_t) := false.\n\nDefinition r (reg: reg_t) : R reg :=\n  match reg with\n  | in0 empty => Ob~0\n  | in0 data => Bits.of_nat _ 42\n  | in1 empty => Ob~0\n  | in1 data => Bits.of_nat _ 73\n  | fifo empty => Ob~1\n  | fifo data => Bits.zero\n  | out empty => Ob~1\n  | out data => Bits.zero\n  end.\n\nDefinition cr := ContextEnv.(create) r.\n\nDefinition interp_result :=\n  tc_compute (commit_update cr (interp_scheduler cr empty_sigma rules pipeline)).\n\nDefinition circuits :=\n  compile_scheduler rules external pipeline.\n\nDefinition package :=\n  {| ip_koika := {| koika_reg_types := R;\n                   koika_reg_init reg := r reg;\n                   koika_ext_fn_types := empty_Sigma;\n                   koika_rules := rules;\n                   koika_rule_external := external;\n                   koika_scheduler := pipeline;\n                   koika_module_name := \"conflicts_modular\" |};\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 \"conflicts_modular.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/examples/conflicts_modular.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2710024127569286}}
{"text": "Require Import Coq.omega.Omega.\nRequire Import Bedrock.Platform.AutoSep.\nRequire Import Coq.Lists.List.\n\nSet Implicit Arguments.\n\nSection TopSection.\n\n  Local Open Scope nat.\n\n  Opaque mult.\n\n  Lemma ptsto32m'_out : forall p ls n,\n    ptsto32m' nil p n ls ===> ptsto32m nil p n ls.\n    induction ls; simpl; intros.\n    apply Himp_refl.\n    eapply Himp_trans; [ apply Himp_star_frame; [ apply Himp_refl\n      | apply IHls ] | ].\n    destruct ls; simpl in *.\n    destruct n.\n    replace (p ^+ $0) with p by words.\n    eapply Himp_trans; [ apply Himp_star_comm | ].\n    apply Himp_star_Emp.\n    eapply Himp_trans; [ apply Himp_star_comm | ].\n    apply Himp_star_Emp.\n    destruct n; simpl.\n    replace (p ^+ $0) with p by words.\n    apply Himp_refl.\n    apply Himp_refl.\n  Qed.\n\n  Lemma ptsto32m'_in : forall p ls n,\n    ptsto32m nil p n ls ===> ptsto32m' nil p n ls.\n    induction ls; simpl; intros.\n    apply Himp_refl.\n    eapply Himp_trans; [ | apply Himp_star_frame; [ apply Himp_refl\n      | apply IHls ] ].\n    destruct ls; simpl in *.\n    destruct n.\n    replace (p ^+ $0) with p by words.\n    eapply Himp_trans; [ | apply Himp_star_comm ].\n    apply Himp_star_Emp'.\n    eapply Himp_trans; [ | apply Himp_star_comm ].\n    apply Himp_star_Emp'.\n    destruct n; simpl.\n    replace (p ^+ $0) with p by words.\n    apply Himp_refl.\n    apply Himp_refl.\n  Qed.\n\n  Lemma ptsto32m'_split' : forall p ls2 ls1 base,\n    ptsto32m' nil p base (ls1 ++ ls2) ===>\n    star (ptsto32m' nil p base ls1)\n    (ptsto32m' nil (p ^+ $ (4 * length ls1)) base ls2).\n    induction ls1; simpl; intros.\n\n    change (4 * 0) with 0.\n    replace (p ^+ $0) with p by words.\n    apply Himp_star_Emp'.\n\n    eapply Himp_trans; [ apply Himp_star_frame; [\n      apply Himp_refl | apply IHls1 ] | ].\n    sepLemma.\n    eapply Himp_trans; [ apply ptsto32m'_shift_base' | ].\n    instantiate (1 := 4).\n    auto.\n    apply Himp_refl'; f_equal; try omega.\n    unfold natToW.\n    rewrite <- wplus_assoc.\n    rewrite <- natToWord_plus.\n    do 2 f_equal.\n    auto.\n  Qed.\n\n  Lemma ptsto32m'_split : forall p ls pos base,\n    pos <= length ls\n    -> ptsto32m' nil p base ls ===>\n    star (ptsto32m' nil p base (firstn pos ls))\n    (ptsto32m' nil (p ^+ $ (4 * pos)) base (skipn pos ls)).\n    intros.\n    pattern ls at 1.\n    replace ls with (firstn pos ls ++ skipn pos ls).\n    replace (4 * pos) with (4 * length (firstn pos ls)).\n    apply ptsto32m'_split'.\n    rewrite firstn_length.\n    rewrite Min.min_l; auto.\n    apply firstn_skipn.\n  Qed.\n\n  Lemma ptsto32m'_elim : forall p ls base,\n    ptsto32m' nil p base ls ===> (p ^+ $ base) =?> length ls.\n    induction ls; simpl; intros.\n\n    apply Himp_refl.\n\n    apply Himp_star_frame.\n    sepLemma.\n    eapply Himp_trans; [ | apply allocated_shift_base ].\n    eapply Himp_trans; [ | apply IHls ].\n    apply Himp_refl.\n    do 2 rewrite <- wplus_assoc.\n    do 2 rewrite <- natToWord_plus.\n    do 2 f_equal.\n    omega.\n    auto.\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/SepHintsUtil.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.27100241275692855}}
{"text": "Require Import compcert.lib.Coqlib.\nRequire Import List. Import ListNotations.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import VST.floyd.functional_base.\n\nRequire Import sha.ByteBitRelations. (* TODO this is only here because of bitsToBytes *)\n\nModule Type ABSTRACT_ENTROPY.\n\nParameter stream: Type.\n\nInductive error_code: Type :=\n| catastrophic_error\n| generic_error\n.\n\nInductive result X: Type: Type :=\n| success: X -> stream -> @result X\n| error : error_code -> stream -> @result X\n.\n\nArguments success {X} _ _.\nArguments error {X} _ _.\n\nParameter get_bytes: nat -> stream -> result (list byte).\nParameter get_bits: nat -> stream -> result (list bool).\n\nEnd ABSTRACT_ENTROPY.\n\nModule OPTIONAL_ENTROPY <: ABSTRACT_ENTROPY.\n\nDefinition stream: Type := nat -> option bool.\n\nInductive error_code: Type :=\n| catastrophic_error\n| generic_error\n.\n\nInductive result X: Type: Type :=\n| success: X -> stream -> @result X\n| error : error_code -> stream -> @result X\n.\n\nArguments success {X} _ _.\nArguments error {X} _ _.\n\nFixpoint get_bits (k: nat) (s: stream): result (list bool) :=\n  match k with\n    | O => success [] s\n    | S k' => match get_bits k' s with\n                | error e s' => error  e s'\n                | success b s' =>\n                  match s' O with\n                    | None => error catastrophic_error (fun i => match Nat.compare i k' with\n                                                                   | Lt => s i\n                                                                   | Eq | Gt => s (1 + i)%nat\n                                                                 end\n                                                       )\n                    | Some e => success (b ++ [e]) (fun i => s (k + i)%nat)\n                  end\n              end\n  end.\n\nExample get_bits_test1:\n  forall bits s output s',\n    bits = [Some false; Some true; Some false; Some false] ->\n    s = (fun i => nth i bits None) ->\n    success output s' = get_bits (length bits) s ->\n    s' = (fun i => s (length bits + i)%nat) /\\ output = [false; true; false; false].\nProof.\n  intros.\n  subst.\n  inv H1.\n  split.\n  extensionality i. destruct i; reflexivity.\n  reflexivity.\nQed.\n\nExample get_bits_test2:\n  forall bits s output s' s'',\n    bits = [Some false; None; Some true; Some false; Some false] ->\n    s = (fun i => nth i bits None) ->\n    error catastrophic_error s' = get_bits 4%nat s ->\n    success output s'' = get_bits 4%nat s' ->\n    s'' = (fun i => s (length bits + i)%nat) /\\ output = [false; true; false; false].\nProof.\n  intros.\n  subst.\n  inv H1.\n  inv H2.\n  split.\n  extensionality i. reflexivity.\n  reflexivity.\nQed.\n\nExample get_bits_test3:\n  forall bits s output s' s'',\n    bits = [None; Some false; Some true; Some false; Some false] ->\n    s = (fun i => nth i bits None) ->\n    error catastrophic_error s' = get_bits 4%nat s ->\n    success output s'' = get_bits 4%nat s' ->\n    s'' = (fun i => s (length bits + i)%nat) /\\ output = [false; true; false; false].\nProof.\n  intros.\n  subst.\n  inv H1.\n  inv H2.\n  split.\n  extensionality i. reflexivity.\n  reflexivity.\nQed.\n\nExample get_bits_test4:\n  forall bits s output s' s'',\n    bits = [Some false; Some true; Some false; None; Some false] ->\n    s = (fun i => nth i bits None) ->\n    error catastrophic_error s' = get_bits 4%nat s ->\n    success output s'' = get_bits 4%nat s' ->\n    s'' = (fun i => s (length bits + i)%nat) /\\ output = [false; true; false; false].\nProof.\n  intros.\n  subst.\n  inv H1.\n  inv H2.\n  split.\n  extensionality i. reflexivity.\n  reflexivity.\nQed.\n(*\nFixpoint get_bits_concrete (k: nat) (s: stream) (max: nat): @result (list bool) :=\n  match k with\n    | O => success [] s\n    | S k' =>\n      match s (max - k)%nat with\n        | None => error catastrophic_error (fun i => s (1 + i)%nat)\n        | Some bit =>\n          match get_bits_concrete k' s max with\n            | error e s' => error e (fun i => match Nat.compare i (max - k)%nat with\n                                                  | Gt => s' i\n                                                  | Eq | Lt => s i\n                                     end)\n            | success b s' => success (bit::b) (fun i => s (k + i)%nat)\n          end\n      end\n  end\n.\nLemma get_bits_concrete_correct:\n  forall k s, get_bits k s = get_bits_concrete k s k.\nProof.\n  intros k.\n  induction k as [|k']; [reflexivity|].\n  intros s.\n  simpl.\n  rewrite IHk'. clear IHk'.\n  replace (k' - k')%nat with O by lia.\n  remember (s O) as sO.\n  destruct sO.\n  {\n    (* s 0 <> None *)\n    (*\n    remember (get_bits_concrete k' s k') as result.\n    destruct result as [string s' | e s'].\n    {\n      remember (get_bits_concrete k' s (S k')) as result2.\n      destruct result2 as [string2 s'2 | e2 s'2].\n      {\n        (* case where both result return success *)\n        generalize dependent s.\n        induction k' as [|k'']; intros.\n        simpl in *. inv Heqresult. inv Heqresult2. rewrite <- HeqsO. auto.\n        simpl in *. replace (k'' - k'')%nat with O in * by lia. rewrite <- HeqsO in *.\n        rewrite IHk''.\n      }\n      unfold get_bits_concrete.\n    }\n*)\n    induction k' as [|k''].\n    {\n      simpl. rewrite <- HeqsO.\n      reflexivity.\n    }\n    simpl.\n    replace (k'' - k'')%nat with O by lia.\n    rewrite <- HeqsO in *.\n    replace (match k'' with\n             | 0%nat => S k''\n             | S l => (k'' - l)%nat\n             end) with 1%nat by (destruct k''; lia).\n\n  }\n  {\n    destruct k' as [|k''].\n    {\n      simpl. rewrite <- HeqsO.\n      replace (fun i : nat =>\n      match Nat.compare i 0 with\n      | Eq => s (S i)\n      | Lt => s i\n      | Gt => s (S i)\n      end) with (fun i => s (S i)); [reflexivity|].\n      extensionality i.\n      destruct i as [|i']; reflexivity.\n    }\n    simpl.\n    replace (k'' - k'')%nat with O by lia; rewrite <- HeqsO.\n    reflexivity.\n  }\n  simpl.\n  *)\n\nDefinition get_bytes (k: nat) (s: stream): result (list byte) :=\n  match get_bits (8 * k)%nat s with\n    | success bits s' => success (bitsToBytes bits) s'\n    | error e s' => error e s'\n  end\n.\n\nEnd OPTIONAL_ENTROPY.\n\nModule ENTROPY := OPTIONAL_ENTROPY.\n\nDefinition get_entropy (security_strength min_length max_length: Z) (prediction_resistance: bool) s :=\n           ENTROPY.get_bytes (Z.to_nat min_length) s.", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/hmacdrbg/entropy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.27092967025420883}}
{"text": "(* This file is the second part of [stack_alloc_proof.v] that was split to\n   ease the development process.\n*)\n\n(* ** Imports and settings *)\nFrom mathcomp Require Import all_ssreflect all_algebra.\nFrom mathcomp Require Import word_ssrZ.\nRequire Import psem psem_facts compiler_util.\nRequire Export stack_alloc stack_alloc_proof.\nRequire Import byteset.\nRequire Import Psatz.\nImport Utf8.\n\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLocal Open Scope vmap.\nLocal Open Scope seq_scope.\nLocal Open Scope Z_scope.\n\nImport Region.\n\n(* When the boolean is set to false, some checks are disable. On the Coq side,\n   we want to perform all the checks, so we set it to true.\n*)\nNotation alloc_fd   := (alloc_fd true).\nNotation alloc_i    := (alloc_i true).\nNotation alloc_prog := (alloc_prog true).\n\nSection INIT.\n\nVariable global_data : seq u8.\nVariable global_alloc : seq (var * wsize * Z).\n\nLet glob_size := Z.of_nat (size global_data).\n\nContext\n  {asm_op syscall_state : Type}\n  {ep : EstateParams syscall_state}\n  {spp : SemPexprParams}\n  {sip : SemInstrParams asm_op syscall_state}\n  (rip : pointer)\n  (no_overflow_glob_size : no_overflow rip glob_size)\n  (mglob : Mvar.t (Z * wsize))\n  (hmap : init_map (Z.of_nat (size global_data)) global_alloc = ok mglob).\n\nLemma init_mapP : forall x1 ofs1 ws1,\n  Mvar.get mglob x1 = Some (ofs1, ws1) -> [/\\\n    ofs1 mod wsize_size ws1 = 0,\n    0 <= ofs1 /\\ ofs1 + size_slot x1 <= glob_size &\n    (forall x2 ofs2 ws2,\n      Mvar.get mglob x2 = Some (ofs2, ws2) -> x1 <> x2 ->\n      ofs1 + size_slot x1 <= ofs2 \\/ ofs2 + size_slot x2 <= ofs1)].\nProof.\n  move: hmap; rewrite /init_map.\n  t_xrbindP=> -[mglob' size] hfold /=.\n  case: ZleP => [hle|//] [?] x1 ofs1 ws1 hget; subst mglob'.\n  have: [/\\ ofs1 mod wsize_size ws1 = 0,\n    0 <= ofs1 /\\ ofs1 + size_slot x1 <= size &\n    ∀ x2 ofs2 ws2,\n      Mvar.get mglob x2 = Some (ofs2, ws2) -> x1 ≠ x2 ->\n      ofs1 + size_slot x1 <= ofs2 ∨ ofs2 + size_slot x2 <= ofs1];\n  last first.\n  + by move=> [h1 h2 h3]; split=> //; lia.\n  move: hfold x1 ofs1 ws1 hget.\n  have: 0 <= (Mvar.empty (Z * wsize), 0).2 /\\\n    forall x1 ofs1 ws1,\n    Mvar.get (Mvar.empty (Z * wsize), 0).1 x1 = Some (ofs1, ws1) -> [/\\\n    ofs1 mod wsize_size ws1 = 0,\n    0 <= ofs1 /\\ ofs1 + size_slot x1 <= (Mvar.empty (Z * wsize), 0).2 &\n      (forall x2 ofs2 ws2,\n        Mvar.get (Mvar.empty (Z * wsize), 0).1 x2 = Some (ofs2, ws2) -> x1 <> x2 ->\n        ofs1 + size_slot x1 <= ofs2 \\/ ofs2 + size_slot x2 <= ofs1)].\n  + done.\n  elim: global_alloc (Mvar.empty _, 0).\n  + by move=> [mglob0 size0] [_ hbase2] /= [<- <-].\n  move=> [[x wsx] ofsx] l ih [mglob0 size0] /= [hbase1 hbase2].\n  t_xrbindP=> -[mglob1 size1].\n  case: ZleP => [h1|//].\n  case: eqP => [h2|//].\n  move=> [<- <-].\n  apply ih.\n  split=> /=.\n  + by have := size_slot_gt0 x; lia.\n  move=> x1 ofs1 ws1.\n  rewrite Mvar.setP.\n  case: eqP => [|_].\n  + move=> <- [<- <-].\n    split.\n    + by rewrite -Zland_mod.\n    + by lia.\n    move=> x2 ofs2 ws2.\n    rewrite Mvar.setP.\n    case: eqP => [//|_].\n    by move=> /hbase2 [_ ? _] _; right; lia.\n  move=> /hbase2 [???]; split=> //.\n  + by have := size_slot_gt0 x; lia.\n  move=> x2 ofs2 ws2.\n  rewrite Mvar.setP.\n  case: eqP; last by eauto.\n  by move=> <- [<- _] _; left; lia.\nQed.\n\nLemma init_map_align x1 ofs1 ws1 :\n  Mvar.get mglob x1 = Some (ofs1, ws1) -> ofs1 mod wsize_size ws1 = 0.\nProof. by move=> /init_mapP [? _ _]. Qed.\n\nLemma init_map_bounded x1 ofs1 ws1 :\n  Mvar.get mglob x1 = Some (ofs1, ws1) ->\n  0 <= ofs1 /\\ ofs1 + size_slot x1 <= glob_size.\nProof. by move=> /init_mapP [_ ? _]. Qed.\n\nLemma init_map_disjoint x1 ofs1 ws1 :\n  Mvar.get mglob x1 = Some (ofs1, ws1) ->\n  forall x2 ofs2 ws2,\n    Mvar.get mglob x2 = Some (ofs2, ws2) -> x1 <> x2 ->\n    ofs1 + size_slot x1 <= ofs2 \\/ ofs2 + size_slot x2 <= ofs1.\nProof. by move=> /init_mapP [_ _ ?]. Qed.\n\n\nVariable (P : uprog) (ev: @extra_val_t _ progUnit).\nNotation gd := (p_globs P).\n\nHypothesis hglobs : check_globs gd mglob global_data.\n\nLemma check_globP gd :\n  check_glob mglob global_data gd ->\n  exists ofs ws,\n    Mvar.get mglob gd.1 = Some (ofs, ws) /\\\n    forall k w,\n      get_val_byte (gv2val gd.2) k = ok w ->\n      nth 0%R global_data (Z.to_nat (ofs + k)) = w.\nProof.\n  rewrite /check_glob.\n  case heq: Mvar.get => [[ofs ws]|//].\n  move=> h; eexists _, _; (split; first by reflexivity); move: h.\n  move /init_map_bounded in heq.\n  case: gd.2.\n  + move=> ws' w /andP [] /leP; rewrite size_drop => hle /eqP hw.\n    move=> k u /=.\n    case: andP => //; rewrite !zify => hbound [<-].\n    rewrite Z2Nat.inj_add; try lia.\n    rewrite -nth_drop -(@nth_take (Z.to_nat (wsize_size ws')));\n      last by apply /ltP; apply Z2Nat.inj_lt; lia.\n    rewrite /LE.wread8.\n    f_equal.\n    apply (LE.decode_inj (sz:=ws')).\n    + rewrite size_take size_drop LE.size_encode.\n      by case: ltP; lia.\n    + rewrite size_take size_drop.\n      by case: ltP; lia.\n    by rewrite -hw LE.decodeK.\n  move=> len a /andP [] /leP; rewrite size_drop => hle /allP hread.\n  move=> k w /dup[] /get_val_byte_bound /= hbound hw.\n  apply /eqP; rewrite Z2Nat.inj_add; try lia.\n  move: (hread (Z.to_nat k)).\n  rewrite Z2Nat.id; last by lia.\n  rewrite hw nth_drop.\n  apply.\n  rewrite mem_iota; apply /andP; split; first by apply /leP; lia.\n  by apply /ltP; apply Z2Nat.inj_lt; lia.\nQed.\n\nLemma check_globsP g gv :\n  get_global_value gd g = Some gv ->\n  exists ofs ws,\n    Mvar.get mglob g = Some (ofs, ws) /\\\n    forall k w,\n      get_val_byte (gv2val gv) k = ok w ->\n      nth 0%R global_data (Z.to_nat (ofs + k)) = w.\nProof.\n  move: hglobs; rewrite /check_globs.\n  elim: gd => // -[g' gv'] gd ih /= /andP [/check_globP h1 /ih h2].\n  case: eqP => [|//].\n  by move=> -> [<-].\nQed.\n\nSection LOCAL.\n\nVariable sao : stk_alloc_oracle_t.\nVariable stack : Mvar.t (Z * wsize).\n\nHypothesis hlayout : init_stack_layout mglob sao = ok stack.\n\nLemma init_stack_layoutP :\n  [/\\ 0 <= sao.(sao_ioff),\n      sao.(sao_ioff) <= sao.(sao_size) &\n      forall x1 ofs1 ws1,\n        Mvar.get stack x1 = Some (ofs1, ws1) -> [/\\\n          (ws1 <= sao.(sao_align))%CMP,\n          ofs1 mod wsize_size ws1 = 0,\n          sao.(sao_ioff) <= ofs1 /\\ ofs1 + size_slot x1 <= sao.(sao_size),\n          (forall x2 ofs2 ws2,\n            Mvar.get stack x2 = Some (ofs2, ws2) -> x1 <> x2 ->\n            ofs1 + size_slot x1 <= ofs2 \\/ ofs2 + size_slot x2 <= ofs1) &\n          Mvar.get mglob x1 = None]].\nProof.\n  move: hlayout; rewrite /init_stack_layout.\n  t_xrbindP=> /ZleP hioff -[stack' size] hfold.\n  rewrite zify.\n  case: ZleP => [hle|//] [?]; subst stack'.\n  have: sao.(sao_ioff) <= size /\\\n    forall x1 ofs1 ws1,\n    Mvar.get stack x1 = Some (ofs1, ws1) -> [/\\\n      (ws1 ≤ sao_align sao)%CMP, ofs1 mod wsize_size ws1 = 0,\n      sao.(sao_ioff) <= ofs1 /\\ ofs1 + size_slot x1 <= size,\n      (forall x2 ofs2 ws2,\n        Mvar.get stack x2 = Some (ofs2, ws2) -> x1 <> x2 ->\n        ofs1 + size_slot x1 <= ofs2 \\/ ofs2 + size_slot x2 <= ofs1) &\n      Mvar.get mglob x1 = None];\n  last first.\n  + move=> [h1 h2]; split => //; first by lia.\n    by move=> x1 ofs1 ws1 /h2 [?????]; split=> //; lia.\n  move: hfold.\n  have: sao.(sao_ioff) <= (Mvar.empty (Z * wsize), sao.(sao_ioff)).2 /\\\n    forall x1 ofs1 ws1,\n    Mvar.get (Mvar.empty (Z * wsize), sao.(sao_ioff)).1 x1 = Some (ofs1, ws1) -> [/\\\n      (ws1 <= sao.(sao_align))%CMP,\n      ofs1 mod wsize_size ws1 = 0,\n      sao.(sao_ioff) <= ofs1 /\\ ofs1 + size_slot x1 <= (Mvar.empty (Z * wsize), sao.(sao_ioff)).2,\n      (forall x2 ofs2 ws2,\n        Mvar.get (Mvar.empty (Z * wsize), sao.(sao_ioff)).1 x2 = Some (ofs2, ws2) -> x1 <> x2 ->\n        ofs1 + size_slot x1 <= ofs2 \\/ ofs2 + size_slot x2 <= ofs1) &\n      Mvar.get mglob x1 = None].\n  + by split => //=; apply Z.le_refl.\n  elim: sao.(sao_slots) (Mvar.empty _, sao.(sao_ioff)).\n  + by move=> [stack0 size0] /= hbase [<- <-].\n  move=> [[x wsx] ofsx] l ih [stack0 size0] /= [hbase1 hbase2].\n  t_xrbindP=> -[stack1 size1].\n  case: Mvar.get => //.\n  case heq: Mvar.get => //.\n  case: ifP => [|//]; rewrite zify => /ZleP h1.\n  case: ifP => [h2|//].\n  case: eqP => [h3|//].\n  move=> [<- <-].\n  apply ih.\n  split=> /=.\n  + by have := size_slot_gt0 x; lia.\n  move=> x1 ofs1 ws1.\n  rewrite Mvar.setP.\n  case: eqP => [|_].\n  + move=> <- [<- <-].\n    split=> //.\n    + by rewrite -Zland_mod.\n    + by lia.\n    move=> x2 ofs2 ws2.\n    rewrite Mvar.setP.\n    case: eqP => [|_]; first by congruence.\n    by move=> /hbase2 [_ _ ? _]; lia.\n  move=> /hbase2 /= [????]; split=> //.\n  + by have := size_slot_gt0 x; lia.\n  move=> x2 ofs2 ws2.\n  rewrite Mvar.setP.\n  case: eqP; last by eauto.\n  by move=> <- [<- _]; lia.\nQed.\n\nLemma init_stack_layout_size_ge0 : 0 <= sao.(sao_size).\nProof. by have [? ? _] := init_stack_layoutP; Psatz.lia. Qed.\n\nLemma init_stack_layout_stack_align x1 ofs1 ws1 :\n  Mvar.get stack x1 = Some (ofs1, ws1) -> (ws1 <= sao.(sao_align))%CMP.\nProof. by have [_ _ h] := init_stack_layoutP => /h [? _ _ _ _]. Qed.\n\nLemma init_stack_layout_align x1 ofs1 ws1 :\n  Mvar.get stack x1 = Some (ofs1, ws1) -> ofs1 mod wsize_size ws1 = 0.\nProof. by have [_ _ h] := init_stack_layoutP => /h [_ ? _ _ _]. Qed.\n\nLemma init_stack_layout_bounded_ioff x1 ofs1 ws1 :\n  Mvar.get stack x1 = Some (ofs1, ws1) ->\n  sao.(sao_ioff) <= ofs1 /\\ ofs1 + size_slot x1 <= sao.(sao_size).\nProof. by have [_ _ h] := init_stack_layoutP => /h [_ _ ? _ _]. Qed.\n\nLemma init_stack_layout_bounded x1 ofs1 ws1 :\n  Mvar.get stack x1 = Some (ofs1, ws1) ->\n  0 <= ofs1 /\\ ofs1 + size_slot x1 <= sao.(sao_size).\nProof. have [? _ h] := init_stack_layoutP => /h [_ _ ? _ _]; lia. Qed.\n\nLemma init_stack_layout_disjoint x1 ofs1 ws1 :\n  Mvar.get stack x1 = Some (ofs1, ws1) ->\n  forall x2 ofs2 ws2,\n    Mvar.get stack x2 = Some (ofs2, ws2) -> x1 <> x2 ->\n    ofs1 + size_slot x1 <= ofs2 \\/ ofs2 + size_slot x2 <= ofs1.\nProof. by have [_ _ h] := init_stack_layoutP => /h [_ _ _ ? _]. Qed.\n\nLemma init_stack_layout_not_glob x1 ofs1 ws1 :\n  Mvar.get stack x1 = Some (ofs1, ws1) -> Mvar.get mglob x1 = None.\nProof. by have [_ _ h] := init_stack_layoutP => /h [_ _ _ _ ?]. Qed.\n\n(* We pack the hypotheses about slots in a record for the sake of simplicity. *)\nRecord wf_Slots (Slots : Sv.t) Addr (Writable:slot-> bool) Align := {\n  wfsl_no_overflow : forall s, Sv.In s Slots -> no_overflow (Addr s) (size_slot s);\n  wfsl_disjoint : forall s1 s2, Sv.In s1 Slots -> Sv.In s2 Slots -> s1 <> s2 ->\n    Writable s1 -> disjoint_zrange (Addr s1) (size_slot s1) (Addr s2) (size_slot s2);\n  wfsl_align : forall s, Sv.In s Slots -> is_align (Addr s) (Align s);\n  wfsl_not_glob : forall s, Sv.In s Slots -> Writable s ->\n    0 < glob_size -> disjoint_zrange rip glob_size (Addr s) (size_slot s)\n}.\n\nVariable rsp : pointer.\nHypothesis no_overflow_size : no_overflow rsp sao.(sao_size).\nHypothesis disjoint_zrange_globals_locals :\n  0 < glob_size -> 0 < sao.(sao_size) ->\n  disjoint_zrange rip glob_size rsp sao.(sao_size).\nHypothesis rip_align : is_align rip U256.\n  (* could be formulated [forall ws, is_align rip ws] (cf. extend_mem) *)\nHypothesis rsp_align : is_align rsp sao.(sao_align).\n\nDefinition Slots_slots (m : Mvar.t (Z * wsize)) :=\n  SvP.MP.of_list (map fst (Mvar.elements m)).\n\nLemma in_Slots_slots m s :\n  Sv.In s (Slots_slots m) <-> Mvar.get m s <> None.\nProof.\n  rewrite /Slots_slots; split.\n  + move=> /SvP.MP.of_list_1 /SetoidList.InA_alt.\n    move=> [_ [<- /InP /mapP]].\n    move=> [[s' ?]] /Mvar.elementsP /= ??; subst s'.\n    by congruence.\n  move=> hget.\n  apply SvP.MP.of_list_1; apply SetoidList.InA_alt.\n  exists s; split=> //.\n  apply /InP; apply /mapP.\n  case heq: (Mvar.get m s) => [ofs_align|//].\n  exists (s, ofs_align) => //.\n  by apply /Mvar.elementsP.\nQed.\n\nDefinition Offset_slots (m : Mvar.t (Z * wsize)) s :=\n  match Mvar.get m s with\n  | Some (ofs, _) => ofs\n  | _ => 0\n  end.\n\nDefinition Align_slots (m : Mvar.t (Z * wsize)) s :=\n  match Mvar.get m s with\n  | Some (_, ws) => ws\n  | _ => U8\n  end.\n\nDefinition Slots_globals := Slots_slots mglob.\nDefinition Addr_globals s := (rip + wrepr _ (Offset_slots mglob s))%R.\nDefinition Writable_globals (s:slot) := false.\nDefinition Align_globals := Align_slots mglob.\n\nDefinition Slots_locals := Slots_slots stack.\nDefinition Addr_locals s := (rsp + wrepr _ (Offset_slots stack s))%R.\nDefinition Writable_locals (s:slot) := true.\nDefinition Align_locals := Align_slots stack.\n\nVariable params : seq var_i.\nVariables vargs1 vargs2 : seq value.\nVariable scs1 : syscall_state.\nVariable m1 m2 : mem.\n\nHypothesis Hargs : Forall3 (wf_arg glob_size rip m1 m2) sao.(sao_params) vargs1 vargs2.\nHypothesis Hdisj : disjoint_values sao.(sao_params) vargs1 vargs2.\nHypothesis Hsub : Forall3 (fun opi (x:var_i) v => opi <> None -> subtype x.(vtype) (type_of_val v)) sao.(sao_params) params vargs1.\n\n(* [param_info] is registered as [eqType], so that we can use all operators of\n   the [seq] library on sequences containing [param_info]s.\n   Is it the right place to perform this registration?\n*)\nDefinition param_info_beq pi1 pi2 :=\n  [&& pi1.(pp_ptr) == pi2.(pp_ptr),\n      pi1.(pp_writable) == pi2.(pp_writable) &\n      pi1.(pp_align) == pi2.(pp_align)].\n\nLemma param_info_axiom : Equality.axiom param_info_beq.\nProof.\n  move=> [ptr1 w1 al1] [ptr2 w2 al2].\n  by apply:(iffP and3P) => /= [[/eqP -> /eqP -> /eqP ->] | [-> -> ->]].\nQed.\n\nDefinition param_info_eqMixin := Equality.Mixin param_info_axiom.\nCanonical  param_info_eqType  := EqType param_info param_info_eqMixin.\n\n(* We would have liked to do the same for values, but this is impossible\n   because of arrays, thus we still have non-eqType in our sequences, which is painful.\n*)\n\nDefinition param_tuples :=\n  let s := zip params (zip sao.(sao_params) (zip vargs1 vargs2)) in\n  pmap (fun '(x, (opi, (v1, v2))) =>\n    omap (fun pi => (x.(v_var), (pi, (v1, v2)))) opi) s.\n\nDefinition Slots_params := SvP.MP.of_list (map fst param_tuples).\n\n(* For a parameter slot [s], [get_pi] returns the param_info and the two values\n   (in the source and in the target) that correspond to it.\n*)\nDefinition get_pi s := assoc param_tuples s.\n\nDefinition Addr_params s :=\n  match get_pi s with\n  | Some (_, (_, Vword sz w)) => if (sz == Uptr)%CMP\n                                 then zero_extend Uptr w\n                                 else 0%R\n  | _                         => 0%R\n  end.\n\nDefinition Writable_params s :=\n  match get_pi s with\n  | Some (pi, _) => pi.(pp_writable)\n  | None         => false\n  end.\n\nDefinition Align_params s :=\n  match get_pi s with\n  | Some (pi, _) => pi.(pp_align)\n  | None         => U8\n  end.\n\n(* Slots : glob + stack + params *)\nDefinition Slots :=\n  Sv.union Slots_globals (Sv.union Slots_locals Slots_params).\n\nLemma in_Slots s :\n  Sv.In s Slots <->\n    Sv.In s Slots_globals \\/ Sv.In s Slots_locals \\/ Sv.In s Slots_params.\nProof. by rewrite /Slots; rewrite !Sv.union_spec. Qed.\n\nDefinition pick_slot A (f_globals f_locals f_params : slot -> A) s :=\n  if Sv.mem s Slots_globals then f_globals s\n  else if Sv.mem s Slots_locals then f_locals s\n  else f_params s.\n\nDefinition Addr := pick_slot Addr_globals Addr_locals Addr_params.\nDefinition Writable := pick_slot Writable_globals Writable_locals Writable_params.\nDefinition Align := pick_slot Align_globals Align_locals Align_params.\n\nLemma wunsigned_Addr_globals s ofs ws :\n  Mvar.get mglob s = Some (ofs, ws) ->\n  wunsigned (Addr_globals s) = wunsigned rip + ofs.\nProof.\n  clear disjoint_zrange_globals_locals.\n  move=> hget.\n  rewrite /Addr_globals /Offset_slots hget.\n  rewrite wunsigned_add //.\n  have hbound := init_map_bounded hget.\n  move: no_overflow_glob_size; rewrite /no_overflow zify => hover.\n  have := wunsigned_range rip.\n  have := size_slot_gt0 s.\n  by lia.\nQed.\n\nLemma zbetween_Addr_globals s :\n  Sv.In s Slots_globals ->\n  zbetween rip glob_size (Addr_globals s) (size_slot s).\nProof.\n  move=> /in_Slots_slots.\n  case heq: Mvar.get => [[ofs ws]|//] _.\n  rewrite /zbetween !zify (wunsigned_Addr_globals heq).\n  have hbound := init_map_bounded heq.\n  by lia.\nQed.\n\nLemma wunsigned_Addr_locals s ofs ws :\n  Mvar.get stack s = Some (ofs, ws) ->\n  wunsigned (Addr_locals s) = wunsigned rsp + ofs.\nProof.\n  clear disjoint_zrange_globals_locals.\n  move=> hget.\n  rewrite /Addr_locals /Offset_slots hget.\n  rewrite wunsigned_add //.\n  have hbound := init_stack_layout_bounded hget.\n  move: no_overflow_size; rewrite /no_overflow zify => hover.\n  have := wunsigned_range rsp.\n  have := size_slot_gt0 s.\n  by lia.\nQed.\n\nLemma zbetween_Addr_locals s :\n  Sv.In s Slots_locals ->\n  zbetween rsp sao.(sao_size) (Addr_locals s) (size_slot s).\nProof.\n  move=> /in_Slots_slots.\n  case heq: Mvar.get => [[ofs ws]|//] _.\n  rewrite /zbetween !zify (wunsigned_Addr_locals heq).\n  have hbound := init_stack_layout_bounded heq.\n  by lia.\nQed.\n\nLemma zbetween_Addr_locals_ioff s :\n  wunsigned (rsp + wrepr _ sao.(sao_ioff)) = wunsigned rsp + sao.(sao_ioff) ->\n  Sv.In s Slots_locals ->\n  zbetween (rsp + wrepr _ sao.(sao_ioff)) (sao.(sao_size) - sao.(sao_ioff)) (Addr_locals s) (size_slot s).\nProof.\n  move=> hadd /in_Slots_slots.\n  case heq: Mvar.get => [[ofs ws]|//] _.\n  rewrite /zbetween !zify (wunsigned_Addr_locals heq).\n  have hbound := init_stack_layout_bounded_ioff heq.\n  rewrite hadd.\n  by lia.\nQed.\n\nLemma disjoint_globals_locals : disjoint Slots_globals Slots_locals.\nProof.\n  apply /disjointP => s /in_Slots_slots ? /in_Slots_slots.\n  case heq: Mvar.get => [[ofs ws]|//].\n  by move /init_stack_layout_not_glob in heq.\nQed.\n\nLemma pick_slot_globals s :\n  Sv.In s Slots_globals ->\n  forall A (f_globals f_locals f_params : slot -> A),\n  pick_slot f_globals f_locals f_params s = f_globals s.\nProof. by rewrite /pick_slot => /Sv_memP ->. Qed.\n\nLemma pick_slot_locals s :\n  Sv.In s Slots_locals ->\n  forall A (f_globals f_locals f_params : slot -> A),\n  pick_slot f_globals f_locals f_params s = f_locals s.\nProof.\n  rewrite /pick_slot.\n  case: Sv_memP => [|_].\n  + by move /disjointP : disjoint_globals_locals => h /h.\n  by move=> /Sv_memP ->.\nQed.\n\n\nVariable vripn : Ident.ident.\nLet vrip0 := {| vtype := spointer; vname := vripn |}.\nVariable vrspn : Ident.ident.\nLet vrsp0 := {| vtype := spointer; vname := vrspn |}.\nVariable vlen : Ident.ident.\nLet vxlen0 := {| vtype := spointer; vname := vlen |}.\nVariable locals1 : Mvar.t ptr_kind.\nVariable rmap1 : region_map.\nVariable vnew1 : Sv.t.\nHypothesis hlocal_map : init_local_map vrip0 vrsp0 vxlen0 mglob stack sao = ok (locals1, rmap1, vnew1).\nVariable vnew2 : Sv.t.\nVariable locals2 : Mvar.t ptr_kind.\nVariable rmap2 : region_map.\nVariable alloc_params : seq (option sub_region * var_i).\nHypothesis hparams : init_params mglob stack vnew1 locals1 rmap1 sao.(sao_params) params = ok (vnew2, locals2, rmap2, alloc_params).\n\nLemma uniq_param_tuples : uniq (map fst param_tuples).\nProof.\n  have: uniq (map fst param_tuples) /\\\n    forall x, x \\in map fst param_tuples -> Mvar.get locals1 x = None;\n  last by move=> [].\n  rewrite /param_tuples.\n  move: hparams; rewrite /init_params.\n  elim: sao.(sao_params) params vargs1 vargs2 vnew1 locals1 rmap1 vnew2 locals2 rmap2 alloc_params;\n    first by move=> [|??] [|??] [|??].\n  move=> opi sao_params ih [|x params'] [|varg1 vargs1'] [|varg2 vargs2'] //.\n  move=> vnew0 locals0 rmap0 vnew2' locals2' rmap2' alloc_params' /=.\n  t_xrbindP=> -[[[vnew1' locals1'] rmap1'] alloc_param'] _.\n  case heq: Mvar.get => //.\n  case: opi => [pi|]; last first.\n  + by move=> [<- <- <- <-] [[[??]?]?] /ih -/(_ vargs1' vargs2').\n  t_xrbindP => _ _ _.\n  case: Mvar.get => //.\n  case: Mvar.get => //.\n  case: Mvar.get => //.\n  move=> [_ ? _ _]; subst locals1'.\n  move=> [[[_ _] _] _] /ih -/(_ vargs1' vargs2') [ih1 ih2] _ _.\n  split=> /=.\n  + apply /andP; split=> //.\n    apply /negP => /ih2.\n    by rewrite Mvar.setP_eq.\n  move=> y; rewrite in_cons => /orP.\n  case.\n  + by move=> /eqP ->.\n  move=> /ih2.\n  by rewrite Mvar.setP; case: eqP.\nQed.\n\nLemma in_Slots_params s :\n  Sv.In s Slots_params <-> get_pi s <> None.\nProof.\n  rewrite /Slots_params /get_pi SvP.MP.of_list_1 SetoidList.InA_alt.\n  split.\n  + move=> [] _ [<-] /InP /in_map [[x [opi v]] hin ->].\n    by have -> := mem_uniq_assoc hin uniq_param_tuples.\n  case heq: assoc => [[pi [v1 v2]]|//] _.\n  exists s; split=> //.\n  apply /InP; apply /in_map.\n  exists (s, (pi, (v1, v2))) => //.\n  by apply assoc_mem'.\nQed.\n\nLemma init_params_not_glob_nor_stack s pi :\n  get_pi s = Some pi ->\n  Mvar.get mglob s = None /\\ Mvar.get stack s = None.\nProof.\n  rewrite /get_pi /param_tuples.\n  move: hparams; rewrite /init_params.\n  elim: params sao.(sao_params) vargs1 vargs2 vnew1 locals1 rmap1 vnew2 locals2 rmap2 alloc_params;\n    first by move=> [|??] [|??] [|??].\n  move=> x params' ih [|opi2 sao_params] [|varg1 vargs1'] [|varg2 vargs2'] //.\n  move=> vnew0 locals0 rmap0 vnew2' locals2' rmap2' alloc_params' /=.\n  t_xrbindP=> -[[[??]?]?] _.\n  case: Mvar.get => //.\n  case: opi2 => [pi2|]; last first.\n  + by move=> [<- <- <- <-] [[[??]?]?] /ih{ih}ih _ _; apply ih.\n  t_xrbindP => _ _ _.\n  case: Mvar.get => //.\n  case heq1: Mvar.get => //.\n  case heq2: Mvar.get => //.\n  move=> _ [[[_ _] _] _] /ih{ih}ih _ _ /=.\n  case: eqP => [-> //|_].\n  by apply ih.\nQed.\n\nLemma get_pi_Forall :\n  List.Forall (fun '(x, (opi, (v1, v2))) =>\n    forall pi, opi = Some pi -> get_pi x.(v_var) = Some (pi, (v1, v2)))\n    (zip params (zip sao.(sao_params) (zip vargs1 vargs2))).\nProof.\n  apply List.Forall_forall.\n  move=> [x [opi [v1 v2]]] hin pi ?; subst opi.\n  rewrite /get_pi.\n  apply: mem_uniq_assoc uniq_param_tuples.\n  rewrite /param_tuples.\n  have [s1 [s2 ->]] := List.in_split _ _ hin.\n  rewrite pmap_cat.\n  by apply List.in_app_iff; right; left.\nQed.\n\n(* We perform an induction while we could use properties of zip and List.In,\n   but it seems simpler in this case.\n*)\nLemma get_pi_wf_arg s pi v1 v2 :\n  get_pi s = Some (pi, (v1, v2)) -> wf_arg glob_size rip m1 m2 (Some pi) v1 v2.\nProof.\n  rewrite /get_pi => -/(assoc_mem' (w:=_)).\n  rewrite /param_tuples.\n  elim: Hargs params; first by move=> [].\n  move=> opi varg1 varg2 sao_params vargs1' vargs2' hrin _ ih [//|param params'].\n  case: opi hrin => [pi'|] hrin; last by apply ih.\n  by move=> [[_ <- <- <-] //|]; apply ih.\nQed.\n\nLemma get_pi_size_le s pi v1 v2 :\n  get_pi s = Some (pi, (v1, v2)) -> size_slot s <= size_val v1.\nProof.\n  rewrite /get_pi => -/(assoc_mem' (w:=_)).\n  rewrite /param_tuples.\n  elim: Hsub vargs2; first by move=> [].\n  move=> opi x varg1 sao_params params' vargs1' hsub _ ih [//|varg2 vargs2'].\n  case: opi hsub => [pi'|] hsub; last by apply ih.\n  move=> [[<- _ <- _] //|]; last by apply ih.\n  apply size_of_le.\n  by apply hsub.\nQed.\n\n(* TODO: move (and cf. dummy_info in array_init.v) *)\n(* We need a var to give to nth as a default value *)\nDefinition dummy_var := {| vtype := sbool; vname := \"\"%string |}.\n\nLemma get_pi_nth s pi v1 v2 :\n  get_pi s = Some (pi, (v1, v2)) ->\n  exists k,\n    [/\\ nth dummy_var (map v_var params) k = s,\n        nth None sao.(sao_params) k = Some pi,\n        nth (Vbool true) vargs1 k = v1 &\n        nth (Vbool true) vargs2 k = v2].\nProof.\n  rewrite /get_pi => -/(assoc_mem' (w:=_)).\n  rewrite /param_tuples.\n  elim: sao.(sao_params) params vargs1 vargs2; first by move=> [|??] [|??] [|??].\n  move=> opi sao_params ih [|x params'] [|varg1 vargs1'] [|varg2 vargs2'] //.\n  case: opi => [pi'|].\n  + move=> /=.\n    case.\n    + by move=> [-> -> -> ->]; exists 0%nat.\n    by move=> /ih{ih} [k ih]; exists (S k).\n  by move=> /ih{ih} [k ih]; exists (S k).\nQed.\n\nLemma disjoint_globals_params : disjoint Slots_globals Slots_params.\nProof.\n  apply /disjointP => s /in_Slots_slots ? /in_Slots_params.\n  case heq: get_pi => [pi|//].\n  by have [] := init_params_not_glob_nor_stack heq; congruence.\nQed.\n\nLemma disjoint_locals_params : disjoint Slots_locals Slots_params.\nProof.\n  apply /disjointP => s /in_Slots_slots ? /in_Slots_params.\n  case heq: get_pi => [pi|//].\n  by have [] := init_params_not_glob_nor_stack heq; congruence.\nQed.\n\nLemma pick_slot_params s :\n  Sv.In s Slots_params ->\n  forall A (f_globals f_locals f_params : slot -> A),\n  pick_slot f_globals f_locals f_params s = f_params s.\nProof.\n  rewrite /pick_slot.\n  case: Sv_memP => [|_].\n  + by move /disjointP : disjoint_globals_params => h /h.\n  case: Sv_memP => //.\n  by move /disjointP : disjoint_locals_params => h /h.\nQed.\n\nLemma disjoint_zrange_globals_params :\n  forall s, Sv.In s Slots_params -> Writable_params s ->\n  0 < glob_size -> disjoint_zrange rip glob_size (Addr_params s) (size_slot s).\nProof.\n  move=> s hin hw hgsize.\n  have /in_Slots_params := hin.\n  case hpi: get_pi => [[pi [varg1 varg2]]|//] _.\n  rewrite /Addr_params hpi.\n  have /= := get_pi_wf_arg hpi.\n  move=> [p [? hargp]]; subst varg2.\n  move: hw; rewrite /Writable_params hpi => hw.\n  have := hargp.(wap_writable_not_glob) hw hgsize.\n  apply disjoint_zrange_incl_r.\n  rewrite eq_refl zero_extend_u.\n  by apply: zbetween_le (get_pi_size_le hpi).\nQed.\n\nHypothesis Hdisjoint_zrange_locals :\n  Forall3 (fun opi varg1 varg2 =>\n    forall pi, opi = Some pi ->\n    forall (p:pointer), varg2 = Vword p ->\n    0 < sao.(sao_size) ->\n    disjoint_zrange rsp sao.(sao_size) p (size_val varg1)) sao.(sao_params) vargs1 vargs2.\n\nLemma disjoint_zrange_locals_params :\n  forall s, Sv.In s Slots_params -> 0 < sao.(sao_size) ->\n  disjoint_zrange rsp sao.(sao_size) (Addr_params s) (size_slot s).\nProof.\n  move=> s hin hlt.\n  have /in_Slots_params := hin.\n  case hpi: get_pi => [[pi [varg1 varg2]]|//] _.\n  rewrite /Addr_params hpi.\n  have /= := get_pi_wf_arg hpi.\n  move=> [p [? hargp]]; subst varg2.\n  have hle := get_pi_size_le hpi.\n  apply (disjoint_zrange_incl_r (zbetween_le _ hle)).\n  have [k [hnth1 hnth2 hnth3 hnth4]] := get_pi_nth hpi.\n  rewrite -hnth3.\n  rewrite eq_refl zero_extend_u.\n  by apply (Forall3_nth Hdisjoint_zrange_locals None (Vbool true) (Vbool true)\n    (nth_not_default hnth2 ltac:(discriminate)) _ hnth2 _ hnth4 hlt).\nQed.\n\nLemma wf_Slots_params :\n  wf_Slots Slots_params Addr_params Writable_params Align_params.\nProof.\n  split.\n  + move=> s /in_Slots_params.\n    case hpi: get_pi => [[pi [v1 v2]]|//] _.\n    have [p [? hargp]] := get_pi_wf_arg hpi; subst v2.\n    have hle := get_pi_size_le hpi.\n    rewrite /Addr_params hpi.\n    apply: no_overflow_incl hargp.(wap_no_overflow).\n    rewrite eq_refl zero_extend_u.\n    by apply zbetween_le.\n  + move=> sl1 sl2 /in_Slots_params hsl1 /in_Slots_params hsl2 hneq.\n    case hpi1: get_pi hsl1 => [[pi1 [v11 v12]]|//] _.\n    case hpi2: get_pi hsl2 => [[pi2 [v21 v22]]|//] _.\n    have [p1 [? hargp1]] := get_pi_wf_arg hpi1; subst v12.\n    have [p2 [? hargp2]] := get_pi_wf_arg hpi2; subst v22.\n    rewrite /Writable_params /Addr_params !hpi1 hpi2 => hw1.\n    have hle1 := get_pi_size_le hpi1.\n    have hle2 := get_pi_size_le hpi2.\n    have [k1 [hnth11 hnth12 hnth13 hnth14]] := get_pi_nth hpi1.\n    have [k2 [hnth21 hnth22 hnth23 hnth24]] := get_pi_nth hpi2.\n    have := Hdisj hnth12 hnth14 hnth22 hnth24 ltac:(congruence) hw1.\n    rewrite hnth13 hnth23.\n    rewrite eq_refl 2!zero_extend_u.\n    by apply: disjoint_zrange_incl; apply zbetween_le.\n  + move=> s /in_Slots_params.\n    case hpi: get_pi => [[pi [v1 v2]]|//] _.\n    have [p [? hargp]] := get_pi_wf_arg hpi; subst v2.\n    rewrite /Addr_params /Align_params hpi.\n    rewrite eq_refl zero_extend_u.\n    by apply hargp.(wap_align).\n  by apply disjoint_zrange_globals_params.\nQed.\n\nLemma Haddr_no_overflow : forall s, Sv.In s Slots -> no_overflow (Addr s) (size_slot s).\nProof.\n  move=> s /in_Slots [hin|[hin|hin]].\n  + rewrite /Addr (pick_slot_globals hin).\n    apply: no_overflow_incl no_overflow_glob_size.\n    by apply zbetween_Addr_globals.\n  + rewrite /Addr (pick_slot_locals hin).\n    apply: no_overflow_incl no_overflow_size.\n    by apply zbetween_Addr_locals.\n  rewrite /Addr (pick_slot_params hin).\n  by apply wf_Slots_params.\nQed.\n\nLemma Hdisjoint_writable : forall s1 s2, Sv.In s1 Slots -> Sv.In s2 Slots -> s1 <> s2 ->\n  Writable s1 -> disjoint_zrange (Addr s1) (size_slot s1) (Addr s2) (size_slot s2).\nProof.\n  move=> sl1 sl2 hin1 hin2 hneq hw.\n  have hover1 := Haddr_no_overflow hin1.\n  have hover2 := Haddr_no_overflow hin2.\n  move /in_Slots : hin1 => [hin1|[hin1|hin1]].\n  + by move: hw; rewrite /Writable (pick_slot_globals hin1).\n  + move /in_Slots : hin2 => [hin2|[hin2|hin2]].\n    + apply disjoint_zrange_sym.\n      apply: disjoint_zrange_incl (disjoint_zrange_globals_locals _ _).\n      + rewrite /Addr (pick_slot_globals hin2).\n        by apply (zbetween_Addr_globals hin2).\n      + rewrite /Addr (pick_slot_locals hin1).\n        by apply (zbetween_Addr_locals hin1).\n      + move /in_Slots_slots : hin2.\n        case heq: Mvar.get => [[ofs ws]|//] _.\n        have := init_map_bounded heq.\n        have := size_slot_gt0 sl2.\n        by lia.\n      move /in_Slots_slots : hin1.\n      case heq: Mvar.get => [[ofs ws]|//] _.\n      have := init_stack_layout_bounded heq.\n      have := size_slot_gt0 sl1.\n      by lia.\n    + split=> //.\n      rewrite /Addr (pick_slot_locals hin1) (pick_slot_locals hin2).\n      move /in_Slots_slots : hin1.\n      case heq1 : Mvar.get => [[ofs1 ws1]|//] _.\n      move /in_Slots_slots : hin2.\n      case heq2 : Mvar.get => [[ofs2 ws2]|//] _.\n      rewrite (wunsigned_Addr_locals heq1).\n      rewrite (wunsigned_Addr_locals heq2).\n      have := init_stack_layout_disjoint heq1 heq2 hneq.\n      by lia.\n    rewrite /Addr (pick_slot_locals hin1) (pick_slot_params hin2).\n    apply: disjoint_zrange_incl_l (disjoint_zrange_locals_params hin2 _).\n    + by apply (zbetween_Addr_locals hin1).\n    move /in_Slots_slots : hin1.\n    case heq: Mvar.get => [[ofs ws]|//] _.\n    have := init_stack_layout_bounded heq.\n    have := size_slot_gt0 sl1.\n    by lia.\n  move /in_Slots : hin2 => [hin2|[hin2|hin2]].\n  + rewrite /Addr (pick_slot_params hin1) (pick_slot_globals hin2).\n    rewrite /Writable (pick_slot_params hin1) in hw.\n    apply disjoint_zrange_sym.\n    apply: disjoint_zrange_incl_l (disjoint_zrange_globals_params hin1 hw _).\n    + by apply (zbetween_Addr_globals hin2).\n    move /in_Slots_slots : hin2.\n    case heq: Mvar.get => [[ofs ws]|//] _.\n    have := init_map_bounded heq.\n    have := size_slot_gt0 sl2.\n    by lia.\n  + rewrite /Addr (pick_slot_params hin1) (pick_slot_locals hin2).\n    apply disjoint_zrange_sym.\n    apply: disjoint_zrange_incl_l (disjoint_zrange_locals_params hin1 _).\n    + by apply (zbetween_Addr_locals hin2).\n    move /in_Slots_slots : hin2.\n    case heq: Mvar.get => [[ofs ws]|//] _.\n    have := init_stack_layout_bounded heq.\n    have := size_slot_gt0 sl2.\n    by lia.\n  rewrite /Addr (pick_slot_params hin1) (pick_slot_params hin2).\n  rewrite /Writable (pick_slot_params hin1) in hw.\n  by apply wf_Slots_params.\nQed.\n\nLemma Hslot_align : forall s, Sv.In s Slots -> is_align (Addr s) (Align s).\nProof.\n  move=> s /in_Slots [hin|[hin|hin]].\n  + rewrite /Addr /Align !(pick_slot_globals hin).\n    move /in_Slots_slots : hin.\n    case heq: Mvar.get => [[ofs ws]|//] _.\n    rewrite /Addr_globals /Offset_slots /Align_globals /Align_slots heq.\n    apply is_align_add.\n    + apply: is_align_m rip_align.\n      by apply wsize_ge_U256.\n    rewrite WArray.arr_is_align.\n    by apply /eqP; apply (init_map_align heq).\n  + rewrite /Addr /Align !(pick_slot_locals hin).\n    move /in_Slots_slots : hin.\n    case heq: Mvar.get => [[ofs ws]|//] _.\n    rewrite /Addr_locals /Offset_slots /Align_locals /Align_slots heq.\n    apply is_align_add.\n    + apply: is_align_m rsp_align.\n      by apply (init_stack_layout_stack_align heq).\n    rewrite WArray.arr_is_align.\n    by apply /eqP; apply (init_stack_layout_align heq).\n  rewrite /Addr /Align !(pick_slot_params hin).\n  by apply wf_Slots_params.\nQed.\n\nLemma Hwritable_not_glob :\n  forall s, Sv.In s Slots -> Writable s ->\n  0 < glob_size -> disjoint_zrange rip glob_size (Addr s) (size_slot s).\nProof.\n  move=> s /in_Slots [hin|[hin|hin]].\n  + by rewrite /Writable (pick_slot_globals hin).\n  + move=> _ hlt.\n    apply: disjoint_zrange_incl_r (disjoint_zrange_globals_locals _ _) => //.\n    + rewrite /Addr (pick_slot_locals hin).\n      by apply (zbetween_Addr_locals hin).\n    move /in_Slots_slots : hin.\n    case heq: Mvar.get => [[ofs ws]|//] _.\n    have := init_stack_layout_bounded heq.\n    have := size_slot_gt0 s.\n    by lia.\n  rewrite /Writable /Addr !(pick_slot_params hin).\n  by apply wf_Slots_params.\nQed.\n\nLemma Hwf_Slots : wf_Slots Slots Addr Writable Align.\nProof.\n  split.\n  + by apply Haddr_no_overflow.\n  + by apply Hdisjoint_writable.\n  + by apply Hslot_align.\n  by apply Hwritable_not_glob.\nQed.\n\nDefinition lmap locals' vnew' := {|\n  vrip := vrip0;\n  vrsp := vrsp0;\n  vxlen := vxlen0;\n  globals := mglob;\n  locals := locals';\n  vnew := vnew'\n|}.\n\nLemma init_map_wf g ofs ws :\n  Mvar.get mglob g = Some (ofs, ws) ->\n  wf_global rip Slots Addr Writable Align g ofs ws.\nProof.\n  move=> hget.\n  have hin: Sv.In g Slots_globals.\n  + by apply in_Slots_slots; congruence.\n  split=> /=.\n  + by apply in_Slots; left.\n  + by rewrite /Writable (pick_slot_globals hin).\n  + by rewrite /Align (pick_slot_globals hin) /Align_globals /Align_slots hget.\n  by rewrite /Addr (pick_slot_globals hin) /Addr_globals /Offset_slots hget.\nQed.\n\nLemma init_map_wf_rmap vnew' s1 s2 :\n  (forall i, 0 <= i < glob_size ->\n    read (emem s2) (rip + wrepr Uptr i)%R U8 = ok (nth 0%R global_data (Z.to_nat i))) ->\n  wf_rmap (lmap (Mvar.empty _) vnew') Slots Addr Writable Align P empty s1 s2.\nProof.\n  clear disjoint_zrange_globals_locals.\n  move=> heqvalg.\n  split=> //=.\n  move=> y sry bytesy vy.\n  rewrite /check_gvalid /=.\n  case: (@idP (is_glob y)) => // hg.\n  case heq: Mvar.get => [[ofs ws]|//] [<- <-].\n  rewrite get_gvar_glob // => /get_globalI [v [hv -> hty]].\n  split=> // off _ w hget.\n  rewrite /sub_region_addr /= wrepr0 GRing.addr0.\n  have hin: Sv.In y.(gv) Slots_globals.\n  + by apply in_Slots_slots; congruence.\n  rewrite /Addr (pick_slot_globals hin) /Addr_globals /Offset_slots heq.\n  rewrite -GRing.addrA -wrepr_add.\n  rewrite heqvalg.\n  + f_equal.\n    have /check_globsP := hv.\n    rewrite heq => -[? [? [[<- _]]]].\n    by apply.\n  have := init_map_bounded heq.\n  have := get_val_byte_bound hget; rewrite hty.\n  by lia.\nQed.\n\nLemma add_alloc_wf_pmap locals1' rmap1' vnew1' x pki locals2' rmap2' vnew2' :\n  add_alloc mglob stack (x, pki) (locals1', rmap1', vnew1') = ok (locals2', rmap2', vnew2') ->\n  wf_pmap (lmap locals1' vnew1') rsp rip Slots Addr Writable Align ->\n  wf_pmap (lmap locals2' vnew2') rsp rip Slots Addr Writable Align.\nProof.\n  move=> hadd hpmap.\n  case: (hpmap) => /= htlen hnew1 hneq1 hneq2 hneq3 hnew2 hnew3 hrip hrsp hglobals hlocals hnew.\n  move: hadd => /=.\n  case: Sv_memP => [//|hnnew].\n  case hregx: Mvar.get => //.\n  set wf_pmap := wf_pmap. (* hack due to typeclass interacting badly *)\n  t_xrbindP=> {rmap2'} -[[sv pk] rmap2'] hpki [<- _ <-].\n  case: pki hpki.\n  + move=> s z sc.\n    case heq: Mvar.get => [[ofs ws]|//].\n    case: ifP => [/and3P []|//].\n    rewrite !zify => h1 h2 h3 [<- <- _].\n    split=> //=.\n    + by move=> y pky; rewrite Mvar.setP; case: eqP => // ?; apply hneq3.\n    + move=> y pky.\n      rewrite Mvar.setP.\n      case: eqP.\n      + move=> <- [<-].\n        case: sc heq => heq.\n        + have hin: Sv.In s Slots_locals.\n          + by apply in_Slots_slots; congruence.\n          split=> //=.\n          + by apply in_Slots; right; left.\n          + by rewrite /Writable (pick_slot_locals hin).\n          + by rewrite /Align (pick_slot_locals hin) /Align_locals /Align_slots heq.\n          by rewrite /Addr (pick_slot_locals hin) /Addr_locals /Offset_slots heq.\n        have hin: Sv.In s Slots_globals.\n        + by apply in_Slots_slots; congruence.\n        split=> //=.\n        + by apply in_Slots; left.\n        + by rewrite /Writable (pick_slot_globals hin).\n        + by rewrite /Align (pick_slot_globals hin) /Align_globals /Align_slots heq.\n        by rewrite /Addr (pick_slot_globals hin) /Addr_globals /Offset_slots heq.\n      move=> hneq /hlocals.\n      case: pky => //=.\n      + move=> p [] hty1 hty2 hrip' hrsp' hnew' hneq'.\n        split=> //=.\n        rewrite /get_local /= => w wr.\n        rewrite Mvar.setP.\n        case: eqP => //.\n        by move=> _; apply hneq'.\n      move=> sy ofsy wsy zy yf [] hslot hty hlen hofs hw hal hcmp hal2 haddr hnew' hneq'.\n      split=> //=.\n      rewrite /get_local /= => w sw ofsw wsw zw wf.\n      rewrite Mvar.setP.\n      case: eqP => //.\n      by move=> _; apply hneq'.\n    move=> y pky.\n    rewrite Mvar.setP.\n    case: eqP.\n    + by move=> <- _.\n    by move=> _; apply hnew.\n  + move=> p.\n    case harr: is_sarr => //=.\n    case: Sv_memP => [//|hnnew2].\n    case heq0: Mvar.get => //.\n    case: eqP => [hty|//] /= [<- <- _].\n    split=> //=.\n    + by apply SvD.F.add_2.\n    + move=> y pky; rewrite Mvar.setP; case: eqP => ?; last by apply hneq3.\n      by move=> [?] ?; subst y p pky; elim hnnew2.\n    + by apply SvD.F.add_2.\n    + by apply SvD.F.add_2.\n    + move=> y pky.\n      rewrite Mvar.setP.\n      case: eqP.\n      + move=> <- [<-].\n        split=> //=.\n        + by congruence.\n        + by congruence.\n        + by apply SvD.F.add_1.\n        rewrite /get_local /= => w wr.\n        rewrite Mvar.setP.\n        case: eqP => //.\n        by move=> hneq /hlocals /wfr_new /=; congruence.\n      move=> hneq /hlocals.\n      case: pky => //=.\n      + move=> p' [] /= hty1 hty2 hrip' hrsp' hnew' hneq'.\n        split=> //=.\n        + by apply SvD.F.add_2.\n        rewrite /get_local /= => w wr.\n        rewrite Mvar.setP.\n        case: eqP.\n        + by move=> _ [<-]; congruence.\n        by move=> _; apply hneq'.\n      move=> sy ofsy wsy zy yf [] hslot hty' hlen hofs hw hal hcmp hal2 haddr hnew' hneq'.\n      split=> //=.\n      + by apply SvD.F.add_2.\n      move=> w sw ofsw wsw zw wf.\n      rewrite /get_local /= Mvar.setP.\n      case: eqP => //.\n      by move=> _; apply hneq'.\n    move=> y pky.\n    rewrite Mvar.setP.\n    case: eqP.\n    + move=> <- _.\n      have ?: x <> p.\n      + by move /is_sarrP: harr => [n]; congruence.\n      by move=> /SvD.F.add_3; auto.\n    move=> ? /dup[] ? /hnew ?.\n    have ?: p <> y by congruence.\n    by move=> /SvD.F.add_3; auto.\n  move=> s z f.\n  case harr: is_sarr => //.\n  case heq: Mvar.get => [[ofs ws]|//].\n  case: Sv_memP => [//|hnnew2].\n  case: eqP => [//|hneq0].\n  case heqf: Mvar.get => //.\n  case: ifP => [/and5P []|//].\n  move=> h1.\n  rewrite !zify.\n  move=> h2 /eqP; rewrite (Zland_mod _ Uptr) => h3 h4 h5 [<- <- _].\n  split=> //=.\n  + by apply SvD.F.add_2.\n  + by move=> y pky; rewrite Mvar.setP; case: eqP => // ?; apply hneq3.\n  + by apply SvD.F.add_2.\n  + by apply SvD.F.add_2.\n  + move=> y pky.\n    rewrite Mvar.setP.\n    case: eqP.\n    + move=> <- [<-].\n      have hin: Sv.In s Slots_locals.\n      + by apply in_Slots_slots; congruence.\n      split=> //=.\n      + by apply in_Slots; right; left.\n      + by rewrite /Writable (pick_slot_locals hin).\n      + by rewrite /Align (pick_slot_locals hin) /Align_locals /Align_slots heq.\n      + by rewrite WArray.arr_is_align; apply /eqP.\n      + by rewrite /Addr (pick_slot_locals hin) /Addr_locals /Offset_slots heq.\n      + by apply SvD.F.add_1.\n      move=> w sw ofsw wsw zw wf.\n      rewrite /get_local /= Mvar.setP.\n      case: eqP => //.\n      by move=> _ /hlocals /wfs_new /=; congruence.\n    move=> hneq /hlocals.\n    case: pky => //=.\n    + move=> p [] hty1 hty2 hrip' hrsp' hnew' hneq'.\n      split=> //=.\n      + by apply SvD.F.add_2.\n      move=> w wr /=.\n      rewrite /get_local /= Mvar.setP.\n      case: eqP => //.\n      by move=> _; apply hneq'.\n    move=> sy ofsy wsy zy yf [] /= hslot hty' hlen hofs hw hal hcmp hal2 haddr hnew' hneq'.\n    split=> //=.\n    + by apply SvD.F.add_2.\n    move=> w sw ofsw wsw zw wf.\n    rewrite /get_local /= Mvar.setP.\n    case: eqP.\n    + by move=> _ [_ _ _ _ <-]; congruence.\n    by move=> _; apply hneq'.\n  move=> y pky.\n  rewrite Mvar.setP.\n  case: eqP.\n  + move=> <- _.\n    by move=> /SvD.F.add_3; auto.\n  move=> ? /dup[] ? /hnew ?.\n  have ?: f <> y by congruence.\n  by move=> /SvD.F.add_3; auto.\nQed.\n\nLemma add_alloc_wf_rmap locals1' rmap1' vnew1' x pki locals2' rmap2' vnew2' s2 :\n  wf_pmap (lmap locals1' vnew1') rsp rip Slots Addr Writable Align ->\n  add_alloc mglob stack (x, pki) (locals1', rmap1', vnew1') = ok (locals2', rmap2', vnew2') ->\n  let: s1 := {| escs := scs1; emem := m1; evm := vmap0 |} in\n  wf_rmap (lmap locals1' vnew1') Slots Addr Writable Align P rmap1' s1 s2 ->\n  wf_rmap (lmap locals2' vnew2') Slots Addr Writable Align P rmap2' s1 s2.\nProof.\n  move=> hpmap hadd hrmap.\n  case: (hrmap) => hwfsr hval hptr.\n  move: hadd => /=.\n  case: Sv_memP => [//|hnnew].\n  case hregx: Mvar.get => //.\n  set wf_rmap := wf_rmap. (* hack due to typeclass interacting badly *)\n  t_xrbindP=> {rmap2'} -[[sv pk] rmap2'] hpki [<- <- <-].\n  case: pki hpki.\n  + move=> s z sc.\n    case heq: Mvar.get => [[ofs ws]|//].\n    case: ifP => [/and3P []|//].\n    rewrite !zify => h1 h2 h3 [<- <- <-].\n    case: sc heq => heq.\n    + split.\n      + move=> y sry.\n        rewrite Mvar.setP.\n        case: eqP.\n        + move=> <- [<-].\n          have hin: Sv.In s Slots_locals.\n          + by apply in_Slots_slots; congruence.\n          split; split=> //=.\n          + by apply in_Slots; right; left.\n          + by rewrite /Writable (pick_slot_locals hin).\n          by rewrite /Align (pick_slot_locals hin) /Align_locals /Align_slots heq.\n        by move=> _; apply hwfsr.\n      + move=> y sry bytesy vy /check_gvalid_set_move [].\n        + move=> [hg ? _ _]; subst x.\n          rewrite get_gvar_nglob; last by apply /negP.\n          rewrite /get_var /= Fv.get0.\n          case: vtype => //= len [<-].\n          split=> // off _ w /=.\n          rewrite WArray.get_empty.\n          by case: ifP.\n        by move=> [] _; apply hval.\n      move=> y sry.\n      rewrite /get_local /=.\n      rewrite !Mvar.setP.\n      case: eqP.\n      + move=> _ [<-].\n        by eexists.\n      move=> hneq /hptr [pky [hly hpky]].\n      exists pky; split=> //.\n      case: pky hly hpky => //= sy ofsy wsy zy yf hly hpky.\n      rewrite /check_stack_ptr get_var_bytes_set_move_bytes /=.\n      case: eqP => //=.\n      case: eqP => //.\n      by have /wf_locals /wfs_new /= := hly; congruence.\n    split=> //.\n    move=> y sry /hptr.\n    rewrite /get_local /= => -[pky [hly hpky]].\n    exists pky; split=> //.\n    rewrite Mvar.setP.\n    by case: eqP; first by congruence.\n  + move=> p.\n    case harr: is_sarr => //=.\n    case: Sv_memP => [//|hnnew2].\n    case heq0: Mvar.get => //.\n    case: eqP => [hty|//] /= [<- <- <-].\n    split=> //=.\n    move=> y sry /hptr.\n    rewrite /get_local /= => -[pky [hly hpky]].\n    exists pky; split=> //.\n    rewrite Mvar.setP.\n    by case: eqP; first by congruence.\n  move=> s z f.\n  case harr: is_sarr => //.\n  case heq: Mvar.get => [[ofs ws]|//].\n  case: Sv_memP => [//|hnnew2].\n  case: eqP => [//|hneq0].\n  case heqf: Mvar.get => //.\n  case: ifP => [/and5P []|//].\n  move=> h1.\n  rewrite !zify.\n  move=> h2 /eqP; rewrite (Zland_mod _ Uptr) => h3 h4 h5 [<- <- <-].\n  split=> //.\n  move=> y sry /hptr.\n  rewrite /get_local /= => -[pky [hly hpky]].\n  exists pky; split=> //.\n  rewrite Mvar.setP.\n  by case: eqP; first by congruence.\nQed.\n\nLemma init_local_map_wf_pmap :\n  wf_pmap (lmap locals1 vnew1) rsp rip Slots Addr Writable Align.\nProof.\n  move: hlocal_map; rewrite /init_local_map.\n  set wf_pmap := wf_pmap. (* hack due to typeclass interacting badly *)\n  t_xrbindP=> /eqP hneq1 /eqP hneq2 -[[locals1' rmap1'] vnew1'] hfold [???];\n    subst locals1' rmap1' vnew1'.\n  move: hfold.\n  have: wf_pmap (lmap (Mvar.empty ptr_kind, empty, Sv.add vxlen0 (Sv.add vrip0 (Sv.add vrsp0 Sv.empty))).1.1\n                      (Mvar.empty ptr_kind, empty, Sv.add vxlen0 (Sv.add vrip0 (Sv.add vrsp0 Sv.empty))).2) rsp rip\n                      Slots Addr Writable Align.\n  + split=> //=.\n    + by apply SvD.F.add_1.\n    + by apply/SvD.F.add_2/SvD.F.add_1.\n    + by do 2 apply SvD.F.add_2; apply SvD.F.add_1.\n    by apply init_map_wf.\n  elim: sao.(sao_alloc) (Mvar.empty _, _, _).\n  + by move=> /= [[locals0 rmap0] vnew0] ? [<- _ <-].\n  move=> [x pki] l ih [[locals0 rmap0] vnew0] /= hpmap.\n  t_xrbindP=> -[[locals1' rmap1'] vnew1'] halloc.\n  apply ih.\n  by apply (add_alloc_wf_pmap halloc hpmap).\nQed.\n\nLemma init_local_map_wf_rmap s2 :\n  let: s1 := {| escs := scs1; emem := m1; evm := vmap0 |} in\n  (forall i, 0 <= i < glob_size ->\n    read (emem s2) (rip + wrepr Uptr i)%R U8 = ok (nth 0%R global_data (Z.to_nat i))) ->\n  wf_rmap (lmap locals1 vnew1) Slots Addr Writable Align P rmap1 s1 s2.\nProof.\n  move=> heqvalg.\n  move: hlocal_map; rewrite /init_local_map.\n  set wf_rmap := wf_rmap. (* hack due to typeclass interacting badly *)\n  t_xrbindP=> /eqP hneq1 /eqP hneq2 -[[locals1' rmap1'] vnew1'] hfold [???]; subst locals1' rmap1' vnew1'.\n  move: hfold.\n  have: wf_pmap (lmap (Mvar.empty ptr_kind, empty, Sv.add vxlen0 (Sv.add vrip0 (Sv.add vrsp0 Sv.empty))).1.1\n                      (Mvar.empty ptr_kind, empty, Sv.add vxlen0 (Sv.add vrip0 (Sv.add vrsp0 Sv.empty))).2) rsp rip\n                      Slots Addr Writable Align\n     /\\ wf_rmap (lmap (Mvar.empty ptr_kind, empty, Sv.add vxlen0 (Sv.add vrip0 (Sv.add vrsp0 Sv.empty))).1.1\n                      (Mvar.empty ptr_kind, empty, Sv.add vxlen0 (Sv.add vrip0 (Sv.add vrsp0 Sv.empty))).2)\n                Slots Addr Writable Align P (Mvar.empty ptr_kind, empty, Sv.add vxlen0 (Sv.add vrip0 (Sv.add vrsp0 Sv.empty))).1.2 \n            {| escs := scs1; emem := m1; evm := vmap0 |} s2.\n  + split.\n    + split=> //=.\n      + by apply/SvD.F.add_1.\n      + by apply/SvD.F.add_2/SvD.F.add_1.\n      + by apply/SvD.F.add_2/SvD.F.add_2/SvD.F.add_1. \n      by apply init_map_wf.\n    by apply init_map_wf_rmap.\n  elim: sao.(sao_alloc) (Mvar.empty _, _, _).\n  + by move=> /= [[locals0 rmap0] vnew0] [??] [<- <- <-].\n  move=> [x pki] l ih [[locals0 rmap0] vnew0] /= [hpmap hrmap].\n  t_xrbindP=> -[[locals1' rmap1'] vnew1'] halloc.\n  apply ih.\n  split.\n  + apply (add_alloc_wf_pmap halloc hpmap).\n  by apply (add_alloc_wf_rmap hpmap halloc hrmap).\nQed.\n\nLemma init_param_wf_pmap vnew1' locals1' rmap1' sao_param (param:var_i) vnew2' locals2' rmap2' alloc_param :\n  init_param mglob stack (vnew1', locals1', rmap1') sao_param param =\n    ok (vnew2', locals2', rmap2', alloc_param) ->\n  wf_pmap (lmap locals1' vnew1') rsp rip Slots Addr Writable Align ->\n  wf_pmap (lmap locals2' vnew2') rsp rip Slots Addr Writable Align.\nProof.\n  move=> hparam hpmap.\n  case: (hpmap) => /= htlen hnew1 hneq1 hneq2 hneq3 hnew2 hnew3 hrip hrsp hglobals hlocals hnew.\n  move: hparam => /=.\n  set wf_pmap := wf_pmap. (* hack due to typeclass interacting badly *)\n  t_xrbindP=> /Sv_memP hnnew.\n  case heq: Mvar.get => //.\n  case: sao_param => [pi|[<- <- _ _] //].\n  t_xrbindP=> /eqP hregty /Sv_memP hnnew2 harrty.\n  case heq1: Mvar.get => //.\n  case heq2: Mvar.get => //.\n  case heq3: Mvar.get => //.\n  move=> [<- <- _ _].\n  split=> //=.\n  + by apply SvD.F.add_2.\n  + move=> y pky; rewrite Mvar.setP; case: eqP => ?; last by apply hneq3.\n    by move=> [?] h; subst y pky; elim hnnew2; rewrite -h.\n  + by apply SvD.F.add_2.\n  + by apply SvD.F.add_2.\n  + move=> y pky.\n    rewrite Mvar.setP.\n    case: eqP.\n    + move=> <- [<-] /=.\n      split=> //=.\n      + by congruence.\n      + by congruence.\n      + by apply SvD.F.add_1.\n      move=> w wr.\n      rewrite /get_local /= Mvar.setP.\n      case: eqP => //.\n      by move=> _ /hlocals /wfr_new /=; congruence.\n    move=> ? /hlocals.\n    case: pky => //=.\n    + move=> p [] /= hty1 hty2 hrip' hrsp' hnew' hneq'.\n      split=> //=.\n      + by apply SvD.F.add_2.\n      move=> w wr.\n      rewrite /get_local /= Mvar.setP.\n      case: eqP.\n      + by move=> _ [<-]; congruence.\n      by move=> _; apply hneq'.\n    move=> sy ofsy wsy zy yf [] /= hslot hty' hlen hofs hw hal hcmp hal2 haddr hnew' hneq'.\n    split=> //=.\n    + by apply SvD.F.add_2.\n    move=> w sw ofsw wsw zw wf.\n    rewrite /get_local /= Mvar.setP.\n    case: eqP => //.\n    by move=> _; apply hneq'.\n  move=> y pky.\n  rewrite Mvar.setP.\n  case: eqP.\n  + move=> <- _.\n    have ?: param.(v_var) <> pi.(pp_ptr).\n    + by move /is_sarrP : harrty => [n]; congruence.\n    by move=> /SvD.F.add_3; auto.\n  move=> ? /dup[] ? /hnew ?.\n  have ?: pi.(pp_ptr) <> y by congruence.\n  by move=> /SvD.F.add_3; auto.\nQed.\n\nLemma valid_state_init_param rmap m0 s1 s2 vnew1' locals1' sao_param (param:var_i) vnew2' locals2' rmap2' alloc_param :\n  wf_pmap (lmap locals1' vnew1') rsp rip Slots Addr Writable Align ->\n  valid_state (lmap locals1' vnew1') glob_size rsp rip Slots Addr Writable Align P rmap m0 s1 s2 ->\n  init_param mglob stack (vnew1', locals1', rmap) sao_param param = ok (vnew2', locals2', rmap2', alloc_param) ->\n  forall s1' varg1 varg2,\n  write_var param varg1 s1 = ok s1' ->\n  (forall pi, sao_param = Some pi -> get_pi param = Some (pi, (varg1, varg2))) ->\n  wf_arg glob_size rip (emem s1) (emem s2) sao_param varg1 varg2 ->\n  exists s2',\n  write_var alloc_param.2 varg2 s2 = ok s2' /\\\n  valid_state (lmap locals2' vnew2') glob_size rsp rip Slots Addr Writable Align P rmap2' m0 s1' s2'.\nProof.\n  move=> hpmap hvs hparam.\n  have hpmap2 := init_param_wf_pmap hparam hpmap.\n  move: hparam => /=.\n  t_xrbindP=> /Sv_memP hnnew.\n  case heq1: Mvar.get => [//|].\n  case: sao_param => [pi|]; last first.\n  + move=> [<- <- <- <-].\n    move=> s1' varg1 varg2 hw _ ->.\n    move: hw.\n    rewrite /write_var; t_xrbindP => vm1 hvm1 <- /=.\n    by apply: set_varP hvm1 => [v' hv <- | hb hv <-]; rewrite /write_var /set_var hv /= ?hb /=;\n      eexists;(split;first by reflexivity); apply valid_state_set_var.\n  t_xrbindP=> /eqP hty1 /Sv_memP hnnew2 /is_sarrP [n hty2].\n  case heq2: Mvar.get => //.\n  case heq3: Mvar.get => //.\n  case heq4: Mvar.get => //.\n  move=> [? ? <- <-]; subst vnew2' locals2'.\n  move=> s1' varg1 varg2 hw /(_ _ refl_equal) hpi [w [? hargp]]; subst varg2.\n  rewrite /write_var /set_var /=.\n  case: pi.(pp_ptr) hty1 hpmap2 => /= _ pin -> /=.\n  set p := {| vname := pin |} => hpmap2.\n  eexists; split; first by reflexivity.\n  move: hw; rewrite /write_var.\n  set valid_state := valid_state. (* hack due to typeclass interacting badly *)\n  t_xrbindP => vm1 hvm1 <- /=.\n  apply: set_varP hvm1; last by rewrite {1}hty2.\n  case: param hty2 hnnew heq1 heq3 heq4 hpi hpmap2 => -[_ paramn] paramii /= -> /=.\n  set param := {| vname := paramn |} => hnnew heq1 heq3 heq4 hpi hpmap2.\n  move=> a1 /to_arrI [n2 [a2 [? hcast]]] <-; subst varg1.\n  set sr := sub_region_full _ _.\n  have hin: Sv.In sr.(sr_region).(r_slot) Slots_params.\n  + by apply in_Slots_params => /=; congruence.\n  have hwf: wf_sub_region Slots Writable Align sr (sarr n).\n  + split; split=> /=.\n    + by apply in_Slots; right; right.\n    + by rewrite /Writable (pick_slot_params hin) /Writable_params hpi.\n    + by rewrite /Align (pick_slot_params hin) /Align_params hpi.\n    + by lia.\n    by lia.\n  have haddr: w = sub_region_addr Addr sr.\n  + rewrite /sub_region_addr /= wrepr0 GRing.addr0.\n    rewrite /Addr (pick_slot_params hin) /= /Addr_params hpi.\n    by rewrite eq_refl zero_extend_u.\n  rewrite haddr -(WArray.castK a1).\n  apply (valid_state_set_move_regptr hpmap2 (x := param) (v:=Varr a1) (p:=p)) => //; last first.\n  + split=> //.\n    move=> off _ w' hget.\n    rewrite -haddr.\n    apply hargp.(wap_read).\n    by apply (cast_get8 hcast).\n  + by rewrite /get_local /= Mvar.setP_eq.\n  case:(hvs) => hscs hvalid hdisj hincl hincl2 hunch hrip hrsp heqvm hwfr heqmem hglobv htop.\n  split=> //.\n  + move=> x /=.\n    rewrite Mvar.setP.\n    case: eqP => //.\n    move=> ? hlx hnnew3.\n    apply heqvm => //.\n    move=> ?; apply hnnew3.\n    by apply Sv.add_spec; right.\n  case: (hwfr) => hwfsr hval hptr; split=> //.\n  move=> y sry /hptr.\n  rewrite /get_local /= => -[pky [hly hpky]].\n  exists pky; split=> //.\n  rewrite Mvar.setP.\n  by case: eqP => //; congruence.\nQed.\n\nLemma init_params_wf_pmap :\n  wf_pmap (lmap locals2 vnew2) rsp rip Slots Addr Writable Align.\nProof.\n  move: hparams.\n  set wf_pmap := wf_pmap. (* hack due to typeclass interacting badly *)\n  have := init_local_map_wf_pmap.\n  elim: sao.(sao_params) params vnew1 locals1 rmap1 vnew2 locals2 rmap2 alloc_params.\n  + by move=> [|//] ??????? hbase [<- <- _ _].\n  move=> opi sao_params ih [//|param params'].\n  move=> vnew0 locals0 rmap0 vnew2' locals2' rmap2' alloc_params' hpmap.\n  rewrite /init_params /=.\n  apply rbindP => -[[[vnew1' locals1'] rmap1'] alloc_param] hparam.\n  t_xrbindP=> -[[[??]?]?] /ih{ih}ih [<- <- _] _.\n  apply ih.\n  by apply (init_param_wf_pmap hparam).\nQed.\n\nLemma valid_state_init_params m0 vm1 vm2 :\n  let: s1 := {| escs := scs1; emem := m1; evm := vm1 |} in\n  let: s2 := {| escs := scs1; emem := m2; evm := vm2 |} in\n  valid_state (lmap locals1 vnew1) glob_size rsp rip Slots Addr Writable Align P rmap1 m0 s1 s2 ->\n  forall s1',\n  write_vars params vargs1 s1 = ok s1' ->\n  exists s2',\n  write_vars (map snd alloc_params) vargs2 s2  = ok s2' /\\\n  valid_state (lmap locals2 vnew2) glob_size rsp rip Slots Addr Writable Align P rmap2 m0 s1' s2'.\nProof.\n  move=> hvs.\n  have {hvs}:\n     wf_pmap (lmap locals1 vnew1) rsp rip Slots Addr Writable Align /\\\n     valid_state (lmap locals1 vnew1) glob_size rsp rip Slots Addr Writable Align P rmap1 m0 \n        {| escs := scs1; emem := m1; evm := vm1 |} {| escs := scs1; emem := m2; evm := vm2 |}.\n  + split=> //.\n    by apply init_local_map_wf_pmap.\n  elim: Hargs params get_pi_Forall vnew1 locals1 rmap1 vnew2 locals2 rmap2 alloc_params hparams vm1 vm2.\n  + move=> [|//] _ ??????? [<- <- <- <-] vm1 vm2 [_ hvs] _ [<-].\n    by eexists.\n  move=> opi varg1 varg2 sao_params vargs1' vargs2' hrin _ ih [//|x params'].\n  move=> /= /List_Forall_inv [hpi hforall].\n  move=> vnew0 locals0 rmap0 vnew2' locals2' rmap2' alloc_params'.\n  rewrite /init_params /=.\n  apply: rbindP=> -[[[vnew1' locals1'] rmap1'] alloc_param] hparam.\n  t_xrbindP=> -[[[??]?]?] /ih{ih}ih [<- <- <-] <- vm1 vm2 [hpmap hvs].\n  move=> s1'' s1' hs1' hs1''.\n  have [//|s2' [hs2' hvs']] := valid_state_init_param hpmap hvs hparam hs1' _ hrin.\n  rewrite /= hs2'.\n  move: hs1' hs2'.\n  rewrite /write_var.\n  t_xrbindP=> /= vm1' hvm1' ? vm2' hvm2' ?; subst s1' s2'.\n  have hpmap' := init_param_wf_pmap hparam hpmap.\n  have [//|s2'' [hs2'' hvs'']] := ih _ _ _ (conj hpmap' hvs') _ hs1''.\n  rewrite hs2''.\n  by eexists.\nQed.\n\nLemma init_param_alloc_param vnew1' locals1' rmap1' sao_param (param:var_i) vnew2' locals2' rmap2' alloc_param :\n  init_param mglob stack (vnew1', locals1', rmap1') sao_param param = ok (vnew2', locals2', rmap2', alloc_param) ->\n  forall varg1 varg2,\n  (forall pi, sao_param = Some pi -> get_pi param = Some (pi, (varg1, varg2))) ->\n  forall sr, fst alloc_param = Some sr ->\n  varg2 = Vword (sub_region_addr Addr sr).\nProof.\n  rewrite /init_param.\n  t_xrbindP=> _.\n  case: Mvar.get => //.\n  case: sao_param => [pi|].\n  + t_xrbindP => _ _ _.\n    case: Mvar.get => //.\n    case: Mvar.get => //.\n    case: Mvar.get => //.\n    move=> [_ _ _ <-] /=.\n    move=> varg1 varg2 /(_ _ refl_equal) hpi sr [<-].\n    rewrite /sub_region_addr /= wrepr0 GRing.addr0.\n    have hin: Sv.In param Slots_params.\n    + by apply in_Slots_params; congruence.\n    rewrite /Addr (pick_slot_params hin) /Addr_params hpi.\n    have [p [-> _]] := get_pi_wf_arg hpi.\n    by rewrite eq_refl zero_extend_u.\n  by move=> [_ _ _ <-].\nQed.\n\nLemma init_params_alloc_params :\n  List.Forall2 (fun osr varg2 => forall sr, osr = Some sr -> varg2 = Vword (sub_region_addr Addr sr)) (map fst alloc_params) vargs2.\nProof.\n  elim: Hargs params get_pi_Forall vnew1 locals1 rmap1 vnew2 locals2 rmap2 alloc_params hparams.\n  + move=> [|//] _ ??????? [_ _ _ <-].\n    by constructor.\n  move=> opi varg1 varg2 sao_params vargs1' vargs2' _ _ ih [//|param params'].\n  move=> /= /List_Forall_inv [hpi hforall].\n  move=> vnew0 locals0 rmap0 vnew2' locals2' rmap2' alloc_params'.\n  rewrite /init_params /=.\n  apply: rbindP=> -[[[vnew1' locals1'] rmap1'] alloc_param] hparam.\n  t_xrbindP=> -[[[??]?]?] /ih{ih}ih _ <- /=.\n  constructor; last by apply ih.\n  by apply (init_param_alloc_param hparam hpi).\nQed.\n\nLemma init_params_alloc_params_not_None :\n  List.Forall2 (fun osr opi => osr <> None -> opi <> None) (map fst alloc_params) sao.(sao_params).\nProof.\n  elim: sao.(sao_params) params vnew1 locals1 rmap1 vnew2 locals2 rmap2 alloc_params hparams.\n  + move=> [|//] ??????? [_ _ _ <-].\n    by constructor.\n  move=> opi sao_params ih [//|x params'].\n  move=> vnew0 locals0 rmap0 vnew2' locals2' rmap2' alloc_params'.\n  rewrite /init_params /=.\n  apply: rbindP=> -[[[vnew1' locals1'] rmap1'] alloc_param] hparam.\n  t_xrbindP=> -[[[??]?]?] /ih{ih}ih _ <- /=.\n  constructor=> //.\n  move: hparam.\n  t_xrbindP=> _.\n  case: Mvar.get => //.\n  case: opi => [//|].\n  by move=> [_ _ _ <-].\nQed.\n\nLemma init_params_sarr :\n  List.Forall2 (fun opi (x:var_i) => opi <> None -> is_sarr x.(vtype)) sao.(sao_params) params.\nProof.\n  elim: sao.(sao_params) params vnew1 locals1 rmap1 vnew2 locals2 rmap2 alloc_params hparams.\n  + by move=> [|//] _ _ _ _ _ _ _ _.\n  move=> opi sao_params ih [//|x params'].\n  move=> vnew0 locals0 rmap0 vnew2' locals2' rmap2' alloc_params'.\n  rewrite /init_params /=.\n  apply: rbindP=> -[[[vnew1' locals1'] rmap1'] alloc_param] hparam.\n  t_xrbindP=> -[[[_ _] _] _] /ih{ih}ih _ _.\n  constructor=> //.\n  move: hparam.\n  t_xrbindP=> _.\n  case: Mvar.get => //.\n  case: opi => [pi|//].\n  by t_xrbindP.\nQed.\n\n(* [m2] is (at least) [m1] augmented with data [data] at address [rip]. *)\nRecord extend_mem (m1 m2:mem) (rip:pointer) (data:seq u8) := {\n  em_no_overflow : no_overflow rip (Z.of_nat (size data));\n    (* [rip] is able to store a block large enough *)\n  em_align       : is_align rip U256;\n    (* [rip] is 32-bytes aligned (and thus is 1,2,4,8,16-bytes aligned) *)\n    (* could be formulated, [forall ws, is_align rip ws] *)\n  em_read_old8   : forall p, validw m1 p U8 -> read m1 p U8 = read m2 p U8;\n    (* [m2] contains [m1] *)\n  em_fresh       : forall p, validw m1 p U8 -> disjoint_zrange rip (Z.of_nat (size data)) p (wsize_size U8);\n   (* the bytes in [rip; rip + Z.of_nat (size data) - 1] are disjoint from the valid bytes of [m1] *)\n  em_valid       : forall p, validw m1 p U8 || between rip (Z.of_nat (size data)) p U8 -> validw m2 p U8;\n    (* [m2] contains at least [m1] and [rip; rip + Z.of_nat (size data) - 1] *)\n  em_read_new    : forall i, 0 <= i < Z.of_nat (size data) ->\n                     read m2 (rip + wrepr _ i)%R U8 = ok (nth 0%R data (Z.to_nat i))\n    (* the memory at address [rip] contains [data] *)\n}.\n\n(* TODO: should we assume init_stk_state = ok ... as section hypothesis and reason about it,\n   it would in particular ease the proof of params <> locals, since we would have the properties\n   of alloc_stack_spec to reason with. The advantages are not clear. For now, I leave it like this.\n*)\n(* cf. init_stk_stateI in merge_varmaps_proof *)\nLemma init_stk_state_valid_state m3 sz' ws :\n  extend_mem m1 m2 rip global_data ->\n  alloc_stack_spec m2 ws sao.(sao_size) sao.(sao_ioff) sz' m3 ->\n  rsp = top_stack m3 ->\n  vripn <> vrspn ->\n  let s2 := {| escs := scs1; emem := m3; evm := vmap0.[vrsp0 <- ok (pword_of_word rsp)].[vrip0 <- ok (pword_of_word rip)] |} in\n  valid_state (lmap locals1 vnew1) glob_size rsp rip Slots Addr Writable Align P rmap1 m2 {| escs := scs1; evm := vmap0; emem := m1 |} s2.\nProof.\n  clear disjoint_zrange_globals_locals.\n  move=> hext hass hrsp hneq /=.\n  constructor=> //=.\n  + move=> s w hin hb.\n    rewrite hass.(ass_valid); apply /orP.\n    case /in_Slots : hin => [hin|[hin|hin]].\n    + left.\n      apply hext.(em_valid).\n      apply /orP; right.\n      apply: zbetween_trans hb.\n      rewrite /Addr (pick_slot_globals hin).\n      by apply (zbetween_Addr_globals hin).\n    + right.\n      apply: zbetween_trans hb.\n      rewrite /Addr (pick_slot_locals hin).\n      have := (ass_add_ioff hass). rewrite -{1 2}hrsp => hadd.\n      have := zbetween_Addr_locals_ioff hadd hin.\n      by rewrite hrsp.\n    left.\n    have /in_Slots_params := hin.\n    case hpi: get_pi => [[pi [v1 v2]]|//] _.\n    have [p [? hargp]] := get_pi_wf_arg hpi; subst v2.\n    apply hargp.(wap_valid).\n    apply: zbetween_trans hb.\n    rewrite /Addr (pick_slot_params hin) /Addr_params hpi.\n    rewrite eq_refl zero_extend_u.\n    by apply (zbetween_le _ (get_pi_size_le hpi)).\n  + move=> s w hin hvalid.\n    case /in_Slots : hin => [hin|[hin|hin]].\n    + rewrite /Addr (pick_slot_globals hin).\n      apply (disjoint_zrange_incl_l (zbetween_Addr_globals hin)).\n      by apply: hext.(em_fresh) hvalid.\n    + rewrite /Addr (pick_slot_locals hin).\n      apply: (disjoint_zrange_incl_l (zbetween_Addr_locals hin)).\n      have hvalid2: validw m2 w U8.\n      + apply hext.(em_valid).\n        by rewrite hvalid.\n      have hdisj := hass.(ass_fresh) hvalid2.\n      split.\n      + by apply no_overflow_size.\n      + by apply is_align_no_overflow; apply is_align8.\n      by rewrite hrsp; apply or_comm.\n    have /in_Slots_params := hin.\n    case hpi: get_pi => [[pi [v1 v2]]|//] _.\n    have [p [? hargp]] := get_pi_wf_arg hpi; subst v2.\n    apply: disjoint_zrange_incl_l (hargp.(wap_fresh) hvalid).\n    rewrite /Addr (pick_slot_params hin) /Addr_params hpi.\n    rewrite eq_refl zero_extend_u.\n    by apply (zbetween_le _ (get_pi_size_le hpi)).\n  + move=> p hvalid.\n    rewrite hass.(ass_valid); apply /orP; left.\n    by apply hext.(em_valid); apply /orP; left.\n  + move=> p hvalid.\n    by rewrite hass.(ass_valid); apply /orP; left.\n  + by move=> p hvalid1 hvalid2 hdisj; apply hass.(ass_read_old8).\n  + by rewrite get_var_eq.\n  + rewrite get_var_neq; first by rewrite get_var_eq.\n    by rewrite /vrip0 /vrsp0; congruence.\n  + move=> x /= hget hnnew.\n    rewrite !get_var_neq //.\n    + by have /rsp_in_new /= := init_local_map_wf_pmap; congruence.\n    by have /rip_in_new /= := init_local_map_wf_pmap; congruence.\n  + apply init_local_map_wf_rmap.\n    move=> i hi /=.\n    rewrite -hass.(ass_read_old8); first by apply hext.(em_read_new).\n    apply hext.(em_valid); apply /orP; right.\n    apply: between_byte hi.\n    + by apply hext.(em_no_overflow).\n    by apply zbetween_refl.\n  + move=> w hvalid.\n    rewrite -hass.(ass_read_old8); first by apply hext.(em_read_old8).\n    by apply hext.(em_valid); apply /orP; left.\n  + move=> p hb.\n    by apply hext.(em_valid); apply /orP; right.\nQed.\n\n(* It is not clear whether we should use the size of the value [varg1] or the\n   size of the corresponding parameter [x] in this definition. Initially,\n   we used the latter, but at one point it seemed easier to use the former.\n   Since several proofs have been reworked since, this choice could be rethought.\n   At least, it works with the current formulation.\n*)\nDefinition disjoint_from_writable_param p opi varg1 varg2 :=\n  forall pi p2, opi = Some pi -> varg2 = @Vword Uptr p2 -> pi.(pp_writable) ->\n  disjoint_zrange p2 (size_val varg1) p (wsize_size U8).\n\n(* [disjoint_from_writable_params] correctly captures the notion of being\n   disjoint from writable param slots\n*)\nLemma disjoint_from_writable_params_param_slots p :\n  Forall3 (disjoint_from_writable_param p) sao.(sao_params) vargs1 vargs2 ->\n  forall s, Sv.In s Slots_params -> Writable_params s ->\n  disjoint_zrange (Addr_params s) (size_slot s) p (wsize_size U8).\nProof.\n  move=> hdisj s hin.\n  have /in_Slots_params := hin.\n  case hpi: get_pi => [[pi [v1 v2]]|//] _.\n  have [p2 [? hargp]] := get_pi_wf_arg hpi; subst v2.\n  rewrite /Writable_params /Addr_params hpi => hw.\n  have [i [hnth1 hnth2 hnth3 hnth4]] := get_pi_nth hpi.\n  have hi := nth_not_default hnth2 ltac:(discriminate).\n  have := Forall3_nth hdisj None (Vbool true) (Vbool true) hi.\n  move: hi; have [-> _] := size_fmapM2 hparams => hi.\n  rewrite hnth2 hnth4 => /(_ _ _ refl_equal refl_equal hw).\n  apply disjoint_zrange_incl_l.\n  rewrite eq_refl zero_extend_u.\n  apply: zbetween_le.\n  rewrite hnth3.\n  by apply: get_pi_size_le hpi.\nQed.\n\n(* If p is [disjoint_from_writable_params] and from local variables, it is\n   disjoint from all writable params.\n*)\nCorollary disjoint_from_writable_params_all_slots p :\n  Forall3 (disjoint_from_writable_param p) sao.(sao_params) vargs1 vargs2 ->\n  disjoint_zrange rsp sao.(sao_size) p (wsize_size U8) ->\n  forall s, Sv.In s Slots -> Writable s ->\n  disjoint_zrange (Addr s) (size_slot s) p (wsize_size U8).\nProof.\n  move=> hdisj1 hdisj2 s hin hw.\n  case /in_Slots : hin => [hin|[hin|hin]].\n  + by move: hw; rewrite /Writable (pick_slot_globals hin).\n  + rewrite /Addr (pick_slot_locals hin).\n    by apply (disjoint_zrange_incl_l (zbetween_Addr_locals hin)).\n  rewrite /Writable (pick_slot_params hin) in hw.\n  rewrite /Addr (pick_slot_params hin).\n  by apply (disjoint_from_writable_params_param_slots hdisj1).\nQed.\n\nEnd LOCAL.\n\nLemma valid_state_extend_mem pmap rsp Slots Addr Writable Align rmap m0 s1 s2 :\n  wf_Slots Slots Addr Writable Align ->\n  valid_state pmap glob_size rsp rip Slots Addr Writable Align P rmap m0 s1 s2 ->\n  extend_mem (emem s1) (emem s2) rip global_data ->\n  forall rmap' s1' s2',\n  valid_state pmap glob_size rsp rip Slots Addr Writable Align P rmap' m0 s1' s2' ->\n  validw (emem s1) =2 validw (emem s1') ->\n  validw (emem s2) =2 validw (emem s2') ->\n  extend_mem (emem s1') (emem s2') rip global_data.\nProof.\n  move=> hwf hvs hext rmap' s1' s2' hvs' hvalideq1 hvalideq2.\n  case:(hext) => hover halign hold hfresh hvalid hnew.\n  split=> //=.\n  + exact: vs_eq_mem hvs'.\n  + by move=> p hvalidp; apply hfresh; rewrite hvalideq1.\n  + by move=> p; rewrite -hvalideq1 -hvalideq2; apply hvalid.\n  move=> i hi.\n  have hb: between rip glob_size (rip + wrepr _ i)%R U8.\n  + apply: between_byte hi => //.\n    by apply zbetween_refl.\n  have hvalid0: validw m0 (rip + wrepr _ i)%R U8.\n  + exact: vs_glob_valid.\n  have hnvalid1: ~ validw (emem s1) (rip + wrepr _ i)%R U8.\n  + move=> /hfresh.\n    by apply zbetween_not_disjoint_zrange.\n  have hdisjoint: forall s, Sv.In s Slots -> Writable s ->\n    disjoint_zrange (Addr s) (size_slot s) (rip + wrepr Uptr i) (wsize_size U8).\n  + move=> s hin hw.\n    apply disjoint_zrange_sym.\n    apply (disjoint_zrange_incl_l hb).\n    apply hwf.(wfsl_not_glob) => //.\n    by lia.\n  rewrite -hnew // -vs_unchanged //; last by rewrite -hvalideq1.\n  exact: vs_unchanged.\nQed.\n\nSection PROC.\n\nVariable (P' : sprog).\nHypothesis P'_globs : P'.(p_globs) = [::].\n\nContext\n  (saparams : stack_alloc_params)\n  (hsaparams : h_stack_alloc_params saparams).\n\nVariable (local_alloc : funname -> stk_alloc_oracle_t).\nVariable (fresh_reg_ : string → stype → string).\nHypothesis Halloc_fd : forall fn fd,\n  get_fundef P.(p_funcs) fn = Some fd ->\n  exists2 fd', alloc_fd saparams P'.(p_extra) mglob fresh_reg_ local_alloc fn fd = ok fd' &\n               get_fundef P'.(p_funcs) fn = Some fd'.\n\n(* RAnone -> export function (TODO: rename RAexport?) *)\nDefinition enough_size m sao :=\n  let sz :=\n    if is_RAnone sao.(sao_return_address) then\n      sao.(sao_size) + sao.(sao_extra_size) + wsize_size sao.(sao_align) - 1\n    else\n      round_ws sao.(sao_align) (sao.(sao_size) + sao.(sao_extra_size))\n  in\n  allocatable_stack m (sao.(sao_max_size) - sz).\n\nRecord wf_sao rsp m sao := {\n  wf_sao_size     : enough_size m sao;\n  wf_sao_align    : is_align rsp sao.(sao_align);\n}.\n\nLemma stack_stable_wf_sao rsp m1 m2 sao :\n  stack_stable m1 m2 ->\n  wf_sao rsp m1 sao ->\n  wf_sao rsp m2 sao.\nProof.\n  move=> hss [hsize halign]; split=> //.\n  rewrite /enough_size /allocatable_stack.\n  by rewrite -(ss_top_stack hss) -(ss_limit hss).\nQed.\n\nLet Pi_r s1 (i1:instr_r) s2 :=\n  forall pmap rsp Slots Addr Writable Align rmap1 rmap2 ii1 c2,\n  wf_pmap pmap rsp rip Slots Addr Writable Align ->\n  wf_Slots Slots Addr Writable Align ->\n  forall sao,\n  alloc_i saparams pmap local_alloc sao rmap1 (MkI ii1 i1) = ok (rmap2, c2) ->\n  forall m0 s1', valid_state pmap glob_size rsp rip Slots Addr Writable Align P rmap1 m0 s1 s1' ->\n  extend_mem (emem s1) (emem s1') rip global_data ->\n  wf_sao rsp (emem s1') sao ->\n  exists s2', sem P' rip s1' c2 s2' /\\\n              valid_state pmap glob_size rsp rip Slots Addr Writable Align P rmap2 m0 s2 s2'.\n\nLet Pi s1 (i1:instr) s2 :=\n  forall pmap rsp Slots Addr Writable Align rmap1 rmap2 c2,\n  wf_pmap pmap rsp rip Slots Addr Writable Align ->\n  wf_Slots Slots Addr Writable Align ->\n  forall sao,\n  alloc_i saparams pmap local_alloc sao rmap1 i1 = ok (rmap2, c2) ->\n  forall m0 s1', valid_state pmap glob_size rsp rip Slots Addr Writable Align P rmap1 m0 s1 s1' ->\n  extend_mem (emem s1) (emem s1') rip global_data ->\n  wf_sao rsp (emem s1') sao ->\n  exists s2', sem P' rip s1' c2 s2' /\\\n              valid_state pmap glob_size rsp rip Slots Addr Writable Align P rmap2 m0 s2 s2'.\n\nLet Pc s1 (c1:cmd) s2 :=\n  forall pmap rsp Slots Addr Writable Align rmap1 rmap2 c2,\n  wf_pmap pmap rsp rip Slots Addr Writable Align ->\n  wf_Slots Slots Addr Writable Align ->\n  forall sao,\n  fmapM (alloc_i saparams pmap local_alloc sao) rmap1 c1 = ok (rmap2, c2) ->\n  forall m0 s1', valid_state pmap glob_size rsp rip Slots Addr Writable Align P rmap1 m0 s1 s1' ->\n  extend_mem (emem s1) (emem s1') rip global_data ->\n  wf_sao rsp (emem s1') sao ->\n  exists s2', sem P' rip s1' (flatten c2) s2' /\\\n              valid_state pmap glob_size rsp rip Slots Addr Writable Align P rmap2 m0 s2 s2'.\n\nLet Pfor (i1: var_i) (vs: seq Z) (s1: estate) (c: cmd) (s2: estate) := True.\n\nDefinition alloc_ok (SP:sprog) fn m2 :=\n  forall fd, get_fundef (p_funcs SP) fn = Some fd ->\n  allocatable_stack m2 fd.(f_extra).(sf_stk_max) /\\\n  (~ is_RAnone fd.(f_extra).(sf_return_address) -> is_align (top_stack m2) fd.(f_extra).(sf_align)).\n\n(* [glob_size] and [rip] were section variables in stack_alloc_proof.v, they\n   are section variables in this file too. Can we put everything in the same\n   section? Probably not if the file is split.\n*)\nDefinition wf_args m1 m2 fn :=\n  Forall3 (wf_arg glob_size rip m1 m2) (local_alloc fn).(sao_params).\nDefinition wf_results m vargs1 vargs2 fn :=\n  Forall3 (wf_result m vargs1 vargs2) (local_alloc fn).(sao_return).\n\nDefinition disjoint_from_writable_params fn p :=\n  Forall3 (disjoint_from_writable_param p) (local_alloc fn).(sao_params).\nDefinition mem_unchanged_params fn ms m0 m vargs1 vargs2 :=\n  forall p, validw m0 p U8 -> ~ validw ms p U8 -> disjoint_from_writable_params fn p vargs1 vargs2 ->\n  read m0 p U8 = read m p U8.\n\nLet Pfun (scs1: syscall_state) (m1: mem) (fn: funname) (vargs: seq value) \n         (scs2: syscall_state) (m2: mem) (vres: seq value) :=\n  forall m1' vargs',\n    extend_mem m1 m1' rip global_data ->\n    wf_args m1 m1' fn vargs vargs' ->\n    disjoint_values (local_alloc fn).(sao_params) vargs vargs' ->\n    alloc_ok P' fn m1' ->\n    exists m2' vres',\n      sem_call P' rip scs1 m1' fn vargs' scs2 m2' vres' /\\\n      extend_mem m2 m2' rip global_data /\\\n      wf_results m2' vargs vargs' fn vres vres' /\\\n      mem_unchanged_params fn m1 m1' m2' vargs vargs'.\n\nLocal Lemma Hskip : sem_Ind_nil Pc.\nProof.\n  move=> s pmap rsp Slots Addr Writable Align rmap1 rmap2 /= c2 hpmap hwf sao [??] m0 s' hv hext hsao;subst rmap1 c2.\n  exists s'; split => //; exact: Eskip.\nQed.\n\nLocal Lemma Hcons : sem_Ind_cons P ev Pc Pi.\nProof.\n  move=> s1 s2 s3 i c hhi Hi hhc Hc pmap rsp Slots Addr Writable Align rmap1 rmap3 c1 hpmap hwf sao /=.\n  t_xrbindP => -[rmap2 i'] hi {rmap3} [rmap3 c'] hc /= <- <- m0 s1' hv hext hsao.\n  have [s2' [si hv2]]:= Hi _ _ _ _ _ _ _ _ _ hpmap hwf _ hi _ _ hv hext hsao.\n  have hsao2 := stack_stable_wf_sao (sem_stack_stable_sprog si) hsao.\n  have hext2 := valid_state_extend_mem hwf hv hext hv2 (sem_I_validw_stable_uprog hhi) (sem_validw_stable_sprog si).\n  have [s3' [sc hv3]]:= Hc _ _ _ _ _ _ _ _ _ hpmap hwf _ hc _ _ hv2 hext2 hsao2.\n  by exists s3'; split => //; apply: sem_app; [exact: si|exact: sc].\nQed.\n\nLocal Lemma HmkI : sem_Ind_mkI P ev Pi_r Pi.\nProof.\n  move=> ii i s1 s2 _ Hi pmap rsp Slots Addr Writable Align rmap1 rmap2 c' hpmap hwf sao ha m0 s1' hv hext hsao.\n  apply: Hi; eauto.\nQed.\n\nLocal Lemma Hassgn : sem_Ind_assgn P Pi_r.\nProof.\n  move=> s1 s1' r tag ty e v v' hv htr hw pmap rsp Slots Addr Writable Align rmap1 rmap2 ii1 c2 hpmap hwf sao /=.\n  case: ifPn => [/is_sarrP [n ?]| _ ]; t_xrbindP.\n  + move => [rmap2' i2'] halloc /= ?? m0 s2 hvs hext hsao; subst rmap2' c2 ty.\n    have [s2' [hs2' hvs']] := alloc_array_move_initP hwf.(wfsl_no_overflow) hwf.(wfsl_disjoint) hwf.(wfsl_align) hpmap P'_globs hsaparams hvs hv htr hw halloc.\n    by exists s2'; split => //; apply sem_seq1; constructor.\n  move=> e' he1 [rmap2' x'] hax /= ?? m0 s2 hvs hext hsao; subst rmap2' c2.\n  have he := alloc_eP hwf.(wfsl_no_overflow) hwf.(wfsl_align) hpmap hvs he1.\n  have htyv':= truncate_val_has_type htr.\n  have [s2' [/= hw' hvs']]:= alloc_lvalP hwf.(wfsl_no_overflow) hwf.(wfsl_disjoint) hwf.(wfsl_align) hpmap hax hvs htyv' hw.\n  exists s2'; split=> //.\n  by apply sem_seq1; constructor; apply: Eassgn; eauto; rewrite P'_globs; auto.\nQed.\n\nLocal Lemma Hopn : sem_Ind_opn P Pi_r.\nProof.\n  move=> s1 s2 t o xs es.\n  rewrite /sem_sopn; t_xrbindP=> vs va hes hop hw pmap rsp Slots Addr Writable Align rmap1 rmap2 ii1 c2 hpmap hwf sao /=.\n  t_xrbindP => es' he [rmap4 x'] ha /= ? <- m0 s1' hvs hext hsao; subst rmap4.\n  have [s2' [hw' hvalid']] := alloc_lvalsP hwf.(wfsl_no_overflow) hwf.(wfsl_disjoint) hwf.(wfsl_align) hpmap ha hvs (sopn_toutP hop) hw.\n  exists s2'; split=> //.\n  apply sem_seq1; do 2! constructor.\n  by rewrite /sem_sopn P'_globs (alloc_esP hwf.(wfsl_no_overflow) hwf.(wfsl_align) hpmap hvs he hes) /= hop.\nQed.\n\nLocal Lemma Hsyscall : sem_Ind_syscall P Pi_r.\nProof.\n  move=> s1 scs m s2 o xs es ves vxs hves hvxs hs2.\n  move=> pmap rsp Slots Addr Writable Align rmap1 rmap2 ii1 c2 hpmap hwf sao /=.\n  move=> hsyscall m0 s1' hvs hext hsao.\n  by apply (alloc_syscallP hwf.(wfsl_no_overflow) hwf.(wfsl_disjoint) hpmap P' hsyscall hvs hves hvxs hs2).\nQed.\n\nLocal Lemma Hif_true : sem_Ind_if_true P ev Pc Pi_r.\nProof.\n  move=> s1 s2 e c1 c2 Hse _ Hc pmap rsp Slots Addr Writable Align rmap1 rmap2 ii1 c hpmap hwf sao /=.\n  t_xrbindP => e' he [rmap4 c1'] hc1 [rmap5 c2'] hc2 /= ?? m0 s1' hv hext hsao; subst rmap2 c.\n  have := alloc_eP hwf.(wfsl_no_overflow) hwf.(wfsl_align) hpmap hv he Hse; rewrite -P'_globs => he'.\n  have [s2' [Hsem Hvalid']] := Hc _ _ _ _ _ _ _ _ _ hpmap hwf _ hc1 _ _ hv hext hsao.\n  exists s2'; split; first by apply sem_seq1;constructor;apply: Eif_true.\n  by apply: valid_state_Incl Hvalid'; apply incl_Incl; apply incl_merge_l.\nQed.\n\nLocal Lemma Hif_false : sem_Ind_if_false P ev Pc Pi_r.\nProof.\n  move=> s1 s2 e c1 c2 Hse _ Hc pmap rsp Slots Addr Writable Align rmap1 rmap2 ii1 c hpmap hwf sao /=.\n  t_xrbindP => e' he [rmap4 c1'] hc1 [rmap5 c2'] hc2 /= ?? m0 s1' hv hext hsao; subst rmap2 c.\n  have := alloc_eP hwf.(wfsl_no_overflow) hwf.(wfsl_align) hpmap hv he Hse; rewrite -P'_globs => he'.\n  have [s2' [Hsem Hvalid']] := Hc _ _ _ _ _ _ _ _ _ hpmap hwf _ hc2 _ _ hv hext hsao.\n  exists s2'; split; first by apply sem_seq1; constructor; apply: Eif_false.\n  by apply: valid_state_Incl Hvalid'; apply incl_Incl; apply incl_merge_r.\nQed.\n\nLemma loop2P ii check_c2 n rmap rmap' e' c1' c2': \n  loop2 ii check_c2 n rmap = ok (rmap', (e', (c1', c2'))) ->\n  exists rmap1 rmap2, Incl rmap1 rmap /\\ check_c2 rmap1 = ok ((rmap', rmap2), (e', (c1', c2'))) /\\ incl rmap1 rmap2.\nProof.\n  elim: n rmap => //= n hrec rmap; t_xrbindP => -[[rmap1 rmap2] [e1 [c11 c12]]] hc2 /=; case: ifP.\n  + move=> hi [] ????;subst.\n    by exists rmap; exists rmap2;split => //; apply Incl_refl.\n  move=> _ /hrec [rmap3 [rmap4 [h1 [h2 h3]]]]; exists rmap3, rmap4; split => //.\n  by apply: (Incl_trans h1); apply incl_Incl; apply incl_merge_l.\nQed.\n\nLocal Lemma Hwhile_true : sem_Ind_while_true P ev Pc Pi_r.\nProof.\n  move=> s1 s2 s3 s4 a c1 e c2 hhi Hc1 Hv hhi2 Hc2 _ Hwhile pmap rsp Slots Addr Writable Align\n    rmap1 rmap2 ii1 c hpmap hwf sao /=.\n  t_xrbindP => -[rmap4 [e' [c1' c2']]] /loop2P [rmap5 [rmap6 [hincl1 []]]].\n  t_xrbindP => -[rmap7 c11] hc1 /= e1 he [rmap8 c22] /= hc2 ????? hincl2 ??.\n  subst c rmap4 rmap7 rmap8 e1 c11 c22 => m0 s1' /(valid_state_Incl hincl1) hv hext hsao.\n  have [s2' [hs1 hv2]]:= Hc1 _ _ _ _ _ _ _ _ _ hpmap hwf _ hc1 _ _ hv hext hsao.\n  have := alloc_eP hwf.(wfsl_no_overflow) hwf.(wfsl_align) hpmap hv2 he Hv; rewrite -P'_globs => he'.\n  have hsao2 := stack_stable_wf_sao (sem_stack_stable_sprog hs1) hsao.\n  have hext2 := valid_state_extend_mem hwf hv hext hv2 (sem_validw_stable_uprog hhi) (sem_validw_stable_sprog hs1).\n  have [s3' [hs2 /(valid_state_Incl (incl_Incl hincl2)) hv3]]:= Hc2 _ _ _ _ _ _ _ _ _ hpmap hwf _ hc2 _ _ hv2 hext2 hsao2.\n  set c := [::MkI _ _].\n  have /= := Hwhile _ _ _ _ _ _ rmap5 rmap2 ii1 c hpmap hwf sao.\n  have hsao3 := stack_stable_wf_sao (sem_stack_stable_sprog hs2) hsao2.\n  have hext3 := valid_state_extend_mem hwf hv2 hext2 hv3 (sem_validw_stable_uprog hhi2) (sem_validw_stable_sprog hs2).\n  rewrite Loop.nbP /= hc1 /= he /= hc2 /= hincl2 /= => /(_ erefl _ _ hv3 hext3 hsao3) [s4'] [/sem_seq1_iff/sem_IE hs3 hv4].\n  exists s4';split => //; apply sem_seq1; constructor; apply: Ewhile_true; eassumption.\nQed.\n\nLocal Lemma Hwhile_false : sem_Ind_while_false P ev Pc Pi_r.\nProof.\n  move=> s1 s2 a c1 e c2 _ Hc1 Hv pmap rsp Slots Addr Writable Align rmap1 rmap2 ii1 c hpmap hwf sao /=.\n  t_xrbindP => -[rmap4 [e' [c1' c2']]] /loop2P [rmap5 [rmap6 [hincl1 []]]].\n  t_xrbindP => -[rmap7 c11] hc1 /= e1 he [rmap8 c22] /= hc2 ????? hincl2 ??.\n  subst c rmap4 rmap7 rmap8 e1 c11 c22 => m0 s1' /(valid_state_Incl hincl1) hv hext hsao.\n  have [s2' [hs1 hv2]]:= Hc1 _ _ _ _ _ _ _ _ _ hpmap hwf _ hc1 _ _ hv hext hsao.\n  have := alloc_eP hwf.(wfsl_no_overflow) hwf.(wfsl_align) hpmap hv2 he Hv; rewrite -P'_globs => he'.\n  by exists s2';split => //; apply sem_seq1; constructor; apply: Ewhile_false; eassumption.\nQed.\n\nLocal Lemma Hfor : sem_Ind_for P ev Pi_r Pfor.\nProof. by []. Qed.\n\nLocal Lemma Hfor_nil : sem_Ind_for_nil Pfor.\nProof. by []. Qed.\n\nLocal Lemma Hfor_cons : sem_Ind_for_cons P ev Pc Pfor.\nProof. by []. Qed.\n\nLemma get_var_bytes_set_clear_bytes rv sr ofs len r y :\n  get_var_bytes (set_clear_bytes rv sr ofs len) r y =\n    let bytes := get_var_bytes rv r y in\n    if sr.(sr_region) != r then bytes\n    else\n      let i := interval_of_zone (sub_zone_at_ofs sr.(sr_zone) ofs len) in\n      ByteSet.remove bytes i.\nProof.\n  rewrite /set_clear_bytes /get_var_bytes.\n  rewrite get_bytes_map_setP.\n  case: eqP => [->|] //=.\n  by rewrite get_bytes_clear.\nQed.\n\nLemma alloc_fd_max_size_ge0 pex fn fd fd' :\n  alloc_fd saparams pex mglob fresh_reg_ local_alloc fn fd = ok fd' ->\n  0 <= (local_alloc fn).(sao_max_size).\nProof.\n  rewrite /alloc_fd /alloc_fd_aux /=.\n  t_xrbindP=> ?? hlayout [[??]?] hlocal_map.\n  t_xrbindP=> -[[[??]?]?] hparams.\n  t_xrbindP=> /ZleP hextra /ZleP hmax _ _ _ _.\n  have hsize := init_stack_layout_size_ge0 hlayout.\n  case: is_RAnone hmax.\n  + have := wsize_size_pos (local_alloc fn).(sao_align).\n    by lia.\n  have := round_ws_range (local_alloc fn).(sao_align) ((local_alloc fn).(sao_size) + (local_alloc fn).(sao_extra_size)).\n  by lia.\nQed.\n\nLemma disjoint_set_clear rmap sr ofs len x :\n  ByteSet.disjoint (get_var_bytes (set_clear_pure rmap sr ofs len) sr.(sr_region) x) (ByteSet.full (interval_of_zone (sub_zone_at_ofs sr.(sr_zone) ofs len))).\nProof.\n  rewrite get_var_bytes_set_clear_bytes eq_refl /=.\n  apply /ByteSet.disjointP => n.\n  by rewrite ByteSet.fullE ByteSet.removeE => /andP [_ /negP ?].\nQed.\n\nLemma wf_rmap_scs pmap Slots Addr Writable Align rmap s1 s2 scs: \n  wf_rmap pmap Slots Addr Writable Align P rmap s1 s2 ->\n  wf_rmap pmap Slots Addr Writable Align P rmap (with_scs s1 scs) (with_scs s2 scs).\nProof. by case. Qed.\n \n(* TODO: in [vundef_type], we could maybe change the [sarr] case, now [is_sarr t = false] is an argument of Vundef *)\nLocal Lemma Hcall : sem_Ind_call P ev Pi_r Pfun.\nProof.\n  move=> s1 scs2 m1 s1' ii rs fn args vargs1 vres1 hvargs1 hsem1 Hf hs1'.\n  move=> pmap rsp Slots Addr Writable Align rmap0 rmap2 ii1 c hpmap hwfsl sao /=.\n  t_xrbindP => -[rmap2' i2'] /= halloc ?? m0 s2 hvs hext hsao; subst rmap2' c.\n  move: halloc; rewrite /alloc_call /assert_check.\n  t_xrbindP=> -[rmap1 es] hcargs.\n  t_xrbindP=> -[{rmap2}rmap2 rs2] hcres /ZleP hsize hle /= <- <-.\n\n  (* evaluation of the arguments *)\n  have [vargs2 [hvargs2 hargs hdisj haddr hclear]] :=\n    alloc_call_argsP hwfsl.(wfsl_no_overflow) hwfsl.(wfsl_disjoint) hwfsl.(wfsl_align) hwfsl.(wfsl_not_glob) hpmap hvs hcargs hvargs1.\n\n  (* function call *)\n  have [fd1 hfd1]: exists fd, get_fundef P.(p_funcs) fn = Some fd.\n  + have [fd1 [hfd1 _]] := sem_callE hsem1.\n    by exists fd1.\n  have [fd2 halloc hfd2] := Halloc_fd hfd1.\n  have hmax := alloc_fd_max_size_ge0 halloc.\n  move: halloc hfd2; rewrite /alloc_fd.\n  t_xrbindP=> {fd2}fd2 _ <- hfd2.\n  have halloc_ok: alloc_ok P' fn (emem s2).\n  + rewrite /alloc_ok hfd2 => _ [<-] /=.\n    split.\n    + rewrite /allocatable_stack.\n      move: hsao.(wf_sao_size); rewrite /enough_size /allocatable_stack.\n      by lia.\n    move=> _.\n    have := hsao.(wf_sao_align).\n    have /vs_top_stack -> := hvs.\n    by apply is_align_m.\n  have [m2 [vres2 [hsem2 [hext' [hresults hunch]]]]] := Hf _ _ hext hargs hdisj halloc_ok.\n\n  (* after function call, we have [valid_state] for [rmap1] where all writable arguments\n     have been cleared.\n  *)\n  have hvs': valid_state pmap glob_size rsp rip Slots Addr Writable Align P rmap1 m0 (with_mem s1 m1) (with_mem s2 m2).\n  + have [hcargsx _] := alloc_call_argsE hcargs.\n    set l :=\n      seq.pmap (fun '(bsr, ty) =>\n        match bsr with\n        | Some (true, sr) => Some (sub_region_at_ofs sr (Some 0) (size_of ty), ty)\n        | _               => None\n        end) (zip (map fst es) (map type_of_val vargs1)).\n    have hlin: forall sr ty, (sr, ty) \\in l <->\n      exists k sr', [/\\ ty = type_of_val (nth (Vbool true) vargs1 k),\n                        nth None (map fst es) k = Some (true, sr') &\n                        sr = sub_region_at_ofs sr' (Some 0) (size_of ty)].\n    + move=> sr ty.\n      rewrite /l mem_pmap -(rwP mapP) /=.\n      have heqsize: size (map fst es) = size (map type_of_val vargs1).\n      + rewrite 2!size_map.\n        have [_ <-] := size_fmapM2 hcargsx.\n        by have [? _] := Forall3_size hargs.\n      split.\n      + move=> [[[[[|//] sr']|//] ty'] hin [??]]; subst sr ty'.\n        move: hin.\n        move=> /nthP -/(_ (None, sbool)).\n        rewrite size1_zip heqsize // => -[k hk].\n        rewrite (nth_zip _ _ _ heqsize) => -[hsr' <-].\n        exists k, sr'; split=> //.\n        rewrite (nth_map (Vbool true)) //.\n        by move: hk; rewrite size_map.\n      move=> [k [sr' [-> hsr' ->]]].\n      exists (Some (true, sr'), type_of_val (nth (Vbool true) vargs1 k)) => //.\n      apply /(nthP (None, sbool)).\n      exists k.\n      + rewrite size1_zip -?heqsize //.\n        apply (nth_not_default hsr' ltac:(discriminate)).\n      rewrite (nth_zip _ _ _ heqsize) hsr' (nth_map (Vbool true)) //.\n      move: heqsize; rewrite (size_map _ vargs1) => <-.\n      apply (nth_not_default hsr' ltac:(discriminate)).\n\n    have hvs' := valid_state_incl (alloc_call_args_aux_incl hcargsx) hvs.\n    apply (valid_state_holed_rmap hwfsl.(wfsl_no_overflow) hwfsl.(wfsl_disjoint) hpmap hvs'\n             (sem_call_validw_stable_uprog hsem1) (sem_call_stack_stable_sprog hsem2)\n             (sem_call_validw_stable_sprog hsem2) hext'.(em_read_old8) (l:=l)).\n    + apply List.Forall_forall => -[sr ty] /InP.\n      rewrite hlin => -[k [sr' [-> hsr' ->]]] /=.\n      split.\n      + have [_ hwf'] := Forall3_nth haddr None (Vbool true) (Vbool true) (nth_not_default hsr' ltac:(discriminate)) _ _ hsr'.\n        apply (sub_region_at_ofs_wf hwf' (ofs:=Some 0)).\n        by move=> _ [<-]; lia.\n      by apply (Forall_nth (alloc_call_args_aux_writable hcargsx) None (nth_not_default hsr' ltac:(discriminate)) _ hsr').\n    + move=> p hvalid1 hvalid2 hdisj'.\n      symmetry; apply hunch => //.\n      apply (nth_Forall3 None (Vbool true) (Vbool true)).\n      + by have [? _] := Forall3_size hargs.\n      + by have [_ ?] := Forall3_size hargs.\n      move=> i hi pi p2 hpi hp2 hw.\n      have [sr hsr] := Forall2_nth (alloc_call_args_aux_not_None hcargsx) None None hi _ hpi.\n      rewrite hw in hsr.\n      have := Forall3_nth haddr None (Vbool true) (Vbool true) (nth_not_default hsr ltac:(discriminate)) _ _ hsr.\n      rewrite hp2 => -[[?] hwf']; subst p2.\n      have {hw}hw := Forall_nth (alloc_call_args_aux_writable hcargsx) None (nth_not_default hsr ltac:(discriminate)) _ hsr.\n      have /List.Forall_forall -/(_ (sub_region_at_ofs sr (Some 0) (size_val (nth (Vbool true) vargs1 i)), type_of_val (nth (Vbool true) vargs1 i))) := hdisj'.\n      rewrite -sub_region_addr_offset wrepr0 GRing.addr0.\n      apply.\n      apply /InP /hlin.\n      by exists i, sr.\n    apply List.Forall_forall => -[sr ty] /InP /hlin [i [sr' [-> hsr' ->]]] x.\n    have hincl := Forall2_nth hclear None (Vbool true) (nth_not_default hsr' ltac:(discriminate)) _ hsr'.\n    apply (disjoint_incl_l (incl_get_var_bytes _ _ hincl)) => /=.\n    by apply disjoint_set_clear.\n  have {hvs'} hvs' :\n    valid_state pmap glob_size rsp rip Slots Addr Writable Align P rmap1 m0 (with_scs (with_mem s1 m1) scs2) \n                                                                            (with_scs (with_mem s2 m2) scs2).\n  + by case: hvs' => *; split => //; apply wf_rmap_scs.\n  (* writing of the returned values *)\n  have [s2' [hs2' hvs'']] := alloc_call_resP hwfsl.(wfsl_no_overflow) hwfsl.(wfsl_disjoint) hpmap hvs' hcres haddr hresults hs1'.\n\n  exists s2'; split=> //.\n  apply sem_seq1; constructor; econstructor; rewrite ?P'_globs; eauto.\n  by case: hvs => <- *.\nQed.\n\n(* Not sure at all if this is the right way to do the proof. *)\nLemma wbit_subword (ws ws' : wsize) i (w : word ws) k :\n  wbit_n (word.subword i ws' w) k = (k < ws')%nat && wbit_n w (k + i).\nProof.\n  rewrite /wbit_n.\n  case: ltP.\n  + move=> /ltP hlt.\n    by rewrite word.subwordE word.wbit_t2wE (nth_map 0%R) ?size_enum_ord // nth_enum_ord.\n  rewrite /nat_of_wsize => hle.\n  rewrite word.wbit_word_ovf //.\n  by apply /ltP; lia.\nQed.\n\n(* TODO: is this result generic enough to be elsewhere ? *)\nLemma zero_extend_wread8 (ws ws' : wsize) (w : word ws) :\n  (ws' <= ws)%CMP ->\n  forall off,\n    0 <= off < wsize_size ws' ->\n    LE.wread8 (zero_extend ws' w) off = LE.wread8 w off.\nProof.\n  move=> /wsize_size_le /(Z.divide_pos_le _ _ (wsize_size_pos _)) hle off hoff.\n  rewrite /LE.wread8 /LE.encode /split_vec.\n  have hmod: forall (ws:wsize), ws %% U8 = 0%nat.\n  + by move=> [].\n  have hdiv: forall (ws:wsize), ws %/ U8 = Z.to_nat (wsize_size ws).\n  + by move=> [].\n  have hlt: (Z.to_nat off < Z.to_nat (wsize_size ws))%nat.\n  + by apply /ltP /Z2Nat.inj_lt; lia.\n  have hlt': (Z.to_nat off < Z.to_nat (wsize_size ws'))%nat.\n  + by apply /ltP /Z2Nat.inj_lt; lia.\n  rewrite !hmod !addn0.\n  rewrite !(nth_map 0%nat) ?size_iota ?hdiv // !nth_iota // !add0n.\n  apply /eqP/eq_from_wbit_n => i.\n  rewrite !wbit_subword; f_equal.\n  rewrite wbit_zero_extend.\n  have -> //: (i + Z.to_nat off * U8 <= wsize_size_minus_1 ws')%nat.\n  rewrite -ltnS -/(nat_of_wsize ws').\n  apply /ltP.\n  have := ltn_ord i; rewrite -/(nat_of_wsize _) => /ltP hi.\n  have /ltP ? := hlt'.\n  have <-: (Z.to_nat (wsize_size ws') * U8 = ws')%nat.\n  + by case: (ws').\n  by rewrite -!multE -!plusE; nia.\nQed.\n\n(* Actually, I think we could have proved something only for arrays, since we\n   use this result when the target value is a pointer, in which case the source\n   value is an array. But it is not clear whether we know that the source value\n   is an array at the point where we need this lemma. And now that we have this\n   more general version...\n*)\nLemma value_uincl_get_val_byte v1 v2 :\n  value_uincl v1 v2 ->\n  forall off w,\n    get_val_byte v1 off = ok w ->\n    get_val_byte v2 off = ok w.\nProof.\n  move=> /value_uinclE; case: v1 => //= > [? [? [-> H]]] >.\n  + by case: H => _; apply.\n  case: ifP => //=; rewrite !zify; move: H => /andP[hle /eqP ->] hoff.\n  have hle' := Z.divide_pos_le _ _ (wsize_size_pos _) (wsize_size_le hle).\n  move=> <-; rewrite ifT; last by rewrite !zify; lia.\n  by f_equal; symmetry; apply zero_extend_wread8.\nQed.\n\n(* We don't need the hypothesis that [varg1] and [varg1'] are arrays, since\n   we have the powerful [value_uincl_get_val_byte]. If we had a weaker version,\n   we should probably add this hypothesis.\n*)\nLemma value_uincl_wf_arg_pointer m1 m2 pi varg1 varg1' p :\n  value_uincl varg1' varg1 ->\n  wf_arg_pointer glob_size rip m1 m2 pi varg1 p ->\n  wf_arg_pointer glob_size rip m1 m2 pi varg1' p.\nProof.\n  move=> huincl [halign hover hvalid hfresh hwnglob hread].\n  have hle := size_of_le (value_uincl_subtype huincl).\n  split=> //.\n  + by apply (no_overflow_incl (zbetween_le _ hle)).\n  + move=> w hb; apply hvalid.\n    apply: zbetween_trans hb.\n    by apply zbetween_le.\n  + move=> w /hfresh.\n    apply disjoint_zrange_incl_l.\n    by apply zbetween_le.\n  + move=> hw hgsize.\n    apply: disjoint_zrange_incl_r (hwnglob hw hgsize).\n    by apply zbetween_le.\n  by move=> off w /(value_uincl_get_val_byte huincl) /hread.\nQed.\n\nLemma mapM2_truncate_val_wf_args m1 m2 fn vargs1 vargs2 :\n  wf_args m1 m2 fn vargs1 vargs2 ->\n  forall tyin vargs1',\n  mapM2 ErrType truncate_val tyin vargs1 = ok vargs1' ->\n  exists vargs2',\n    mapM2 ErrType truncate_val\n      (map2 (fun o ty =>\n        match o with\n        | Some _ => spointer\n        | None => ty\n        end) (sao_params (local_alloc fn)) tyin) vargs2 = ok vargs2' /\\\n    wf_args m1 m2 fn vargs1' vargs2'.\nProof.\n  rewrite /wf_args.\n  elim {vargs1 vargs2}.\n  + move=> [|//] /= _ [<-].\n    eexists; split; first by reflexivity.\n    by constructor.\n  move=> opi varg1 varg2 sao_params vargs1 vargs2 harg _ ih [//|ty tyin] /=.\n  t_xrbindP=> _ varg1' hvarg1' vargs1' /ih{ih}[vargs2' [htr hargs]] <-.\n  rewrite htr /=.\n  case: opi harg => [pi|].\n  + move=> [p [-> hargp]].\n    rewrite /truncate_val /= truncate_word_u /=.\n    eexists; split; first by reflexivity.\n    constructor=> //.\n    exists p; split=> //.\n    apply: value_uincl_wf_arg_pointer hargp.\n    by apply (truncate_value_uincl hvarg1').\n  move=> /= ->.\n  rewrite hvarg1' /=.\n  eexists; split; first by reflexivity.\n  by constructor.\nQed.\n\n(* If the parameter is a reg ptr, [varg2] is a pointer, and is equal to [varg2']. *)\nLemma mapM2_truncate_val_ptr_eq m1 m2 fn vargs1 vargs2 :\n  wf_args m1 m2 fn vargs1 vargs2 ->\n  forall tyin vargs2',\n  mapM2 ErrType truncate_val\n    (map2 (fun o ty =>\n          match o with\n          | Some _ => spointer\n          | None => ty\n          end) (sao_params (local_alloc fn)) tyin) vargs2 = ok vargs2' ->\n  Forall3 (fun opi varg varg' => opi <> None -> varg = varg') (local_alloc fn).(sao_params) vargs2 vargs2'.\nProof.\n  elim {vargs1 vargs2}.\n  + by move=> /= _ _ [<-]; constructor.\n  move=> opi varg1 varg2 sao_params vargs1 vargs2 harg _ ih [//|ty tyin] /=.\n  t_xrbindP=> _ varg2' hvarg2' vargs2' /ih{ih}ih <-.\n  constructor=> //.\n  case: opi harg hvarg2' => [pi|//] [p [-> ?]].\n  rewrite /truncate_val /= truncate_word_u.\n  by move=> [<-].\nQed.\n\nLemma value_uincl_disjoint_values m1 m2 fn vargs1 vargs2 :\n  wf_args m1 m2 fn vargs1 vargs2 ->\n  disjoint_values (local_alloc fn).(sao_params) vargs1 vargs2 ->\n  forall vargs1' vargs2',\n  List.Forall2 value_uincl vargs1' vargs1 ->\n  Forall3 (fun opi varg varg' => opi <> None -> varg = varg') (local_alloc fn).(sao_params) vargs2 vargs2' ->\n  disjoint_values (local_alloc fn).(sao_params) vargs1' vargs2'.\nProof.\n  move=> hargs hdisj vargs1' vargs2' hincl hptreq.\n  move=> i1 pi1 w1 i2 pi2 w2 hpi1 hw1 hpi2 hw2 hneq hw.\n  have := Forall3_nth hptreq None (Vbool true) (Vbool true).\n  move=> /dup[].\n  move=> /(_ _ (nth_not_default hpi1 ltac:(discriminate))); rewrite hpi1 => /(_ ltac:(discriminate)); rewrite hw1 => hw1'.\n  move=> /(_ _ (nth_not_default hpi2 ltac:(discriminate))); rewrite hpi2 => /(_ ltac:(discriminate)); rewrite hw2 => hw2'.\n  have := hdisj _ _ _ _ _ _ hpi1 hw1' hpi2 hw2' hneq hw.\n  have := Forall2_nth hincl (Vbool true) (Vbool true).\n  have -> := Forall2_size hincl.\n  have [<- _] := Forall3_size hargs.\n  move=> /dup[].\n  move=> /(_ _ (nth_not_default hpi1 ltac:(discriminate))) /value_uincl_subtype /size_of_le hle1.\n  move=> /(_ _ (nth_not_default hpi2 ltac:(discriminate))) /value_uincl_subtype /size_of_le hle2.\n  by apply disjoint_zrange_incl; apply zbetween_le.\nQed.\n\nLemma value_uincl_wf_result_pointer m vargs1 vargs2 i vr1 vr1' p :\n  value_uincl vr1' vr1 ->\n  wf_result_pointer m vargs1 vargs2 i vr1 p ->\n  wf_result_pointer m vargs1 vargs2 i vr1' p.\nProof.\n  move=> huincl [hargs hsub hread].\n  have hsub' := value_uincl_subtype huincl.\n  split=> //.\n  + by apply: subtype_trans hsub.\n  by move=> off w /(value_uincl_get_val_byte huincl) /hread.\nQed.\n\nLemma mapM2_truncate_val_wf_results m vargs1 vargs2 fn vres1 vres2 :\n  wf_results m vargs1 vargs2 fn vres1 vres2 ->\n  forall tyout vres1',\n  mapM2 ErrType truncate_val tyout vres1 = ok vres1' ->\n  exists vres2',\n    mapM2 ErrType truncate_val\n      (map2 (fun o ty =>\n        match o with\n        | Some _ => spointer\n        | None => ty\n        end) (sao_return (local_alloc fn)) tyout) vres2 = ok vres2' /\\\n    wf_results m vargs1 vargs2 fn vres1' vres2'.\nProof.\n  rewrite /wf_results.\n  elim {vres1 vres2}.\n  + move=> [|//] /= _ [<-].\n    eexists; split; first by reflexivity.\n    by constructor.\n  move=> i vr1 vr2 sao_returns vres1 vres2 hresult _ ih [//|ty tyout] /=.\n  t_xrbindP=> _ vr1' hvr1' vres1' /ih{ih}[vres2' [htr hresults]] <-.\n  rewrite htr /=.\n  case: i hresult => [i|].\n  + move=> [p [-> hresultp]].\n    rewrite /truncate_val /= truncate_word_u /=.\n    eexists; split; first by reflexivity.\n    constructor=> //.\n    eexists; split; first by reflexivity.\n    apply: value_uincl_wf_result_pointer hresultp.\n    by apply (truncate_value_uincl hvr1').\n  move=> /= ->.\n  rewrite hvr1' /=.\n  eexists; split; first by reflexivity.\n  by constructor.\nQed.\n\nHypothesis rip_rsp_neq : P'.(p_extra).(sp_rip) <> P'.(p_extra).(sp_rsp).\n\n(* could probably be written\n   Forall2 (fun x v2 => is_sarr x.(vtype) -> size_slot x <= size_val v) l params\n   But maybe more complex to use?\n*)\nLemma write_vars_subtype A (l:seq (option A)) params :\n  List.Forall2 (fun o (x:var_i) => o <> None -> is_sarr x.(vtype)) l params ->\n  forall vargs1 s1 s2,\n  write_vars params vargs1 s1 = ok s2 ->\n  Forall3 (fun o (x:var_i) v => o <> None -> subtype x.(vtype) (type_of_val v)) l params vargs1.\nProof.\n  elim {l params}.\n  + by move=> [|//] _ _ _; constructor.\n  move=> o x l params harr _ ih [//|varg1 vargs1] /=.\n  t_xrbindP=> s1 s3 s2 hw /ih{ih}ih.\n  constructor=> //.\n  move=> /harr /is_sarrP [n hty].\n  move: hw; rewrite /write_var.\n  t_xrbindP=> vm1 hvm1 _.\n  apply: set_varP hvm1; last by rewrite {1}hty.\n  move=> t h _; move: t h; rewrite hty /=.\n  by move=> _ /to_arrI [n' [_ [-> /WArray.cast_len /ZleP]]] /=.\nQed.\n\nLemma alloc_stack_spec_wf_args m1 m2 fn vargs1 vargs2 ws sz ioff sz' m3 :\n  wf_args m1 m2 fn vargs1 vargs2 ->\n  alloc_stack_spec m2 ws sz ioff sz' m3 ->\n  wf_args m1 m3 fn vargs1 vargs2.\nProof.\n  move=> hargs hass.\n  apply: Forall3_impl hargs.\n  move=> [pi|//] varg1 _ [p [-> hargp]].\n  eexists; split; first by reflexivity.\n  case: hargp => halign hover hvalid hfresh hwnglob hread.\n  split=> //.\n  + by move=> ??; rewrite hass.(ass_valid) hvalid.\n  move=> off w /dup[] /get_val_byte_bound hoff /hread.\n  rewrite hass.(ass_read_old8) //.\n  apply hvalid.\n  apply: between_byte hoff => //.\n  by apply zbetween_refl.\nQed.\n\nLemma alloc_stack_spec_extend_mem m1 m2 ws sz ioff sz' m3 :\n  extend_mem m1 m2 rip global_data ->\n  alloc_stack_spec m2 ws sz ioff sz' m3 ->\n  extend_mem m1 m3 rip global_data.\nProof.\n  move=> hext hass.\n  case:(hext) => hover halign hold hfresh hvalid hnew.\n  split=> //.\n  + move=> ??; rewrite hold //.\n    apply hass.(ass_read_old8).\n    by apply hvalid; apply /orP; left.\n  + move=> ? /hvalid.\n    by rewrite hass.(ass_valid) => ->.\n  move=> i hi; rewrite -hnew //.\n  symmetry.\n  apply hass.(ass_read_old8).\n  apply hvalid; apply /orP; right.\n  apply: between_byte hi => //.\n  by apply zbetween_refl.\nQed.\n\nLemma free_stack_spec_extend_mem m1 m2 m3 :\n  extend_mem m1 m2 rip global_data ->\n  free_stack_spec m2 m3 ->\n  (forall p, validw m1 p U8 || between rip (Z.of_nat (size global_data)) p U8 -> validw m3 p U8) ->\n  extend_mem m1 m3 rip global_data.\nProof.\n  move=> hext hfss hincl.\n  case:(hext) => hover halign hold hfresh hvalid hnew.\n  split=> //.\n  + move=> p ?.\n    rewrite -hfss.(fss_read_old8); first by apply hold.\n    apply hincl.\n    by apply /orP; left.\n  move=> i hi.\n  rewrite -hfss.(fss_read_old8); first by apply hnew.\n  apply hincl.\n  apply /orP; right.\n  apply: between_byte hi => //.\n  by apply zbetween_refl.\nQed.\n\nLemma value_uincl_wf_results m1 m2 fn vargs1 vargs2 vargs1' vargs2' m vres1 vres2 :\n  wf_args m1 m2 fn vargs1 vargs2 ->\n  List.Forall2 value_uincl vargs1' vargs1 ->\n  Forall3 (fun opi varg varg' => opi <> None -> varg = varg') (local_alloc fn).(sao_params) vargs2 vargs2' ->\n  List.Forall (fun oi => forall i, oi = Some i -> nth None (local_alloc fn).(sao_params) i <> None) (local_alloc fn).(sao_return) ->\n  wf_results m vargs1' vargs2' fn vres1 vres2 ->\n  wf_results m vargs1 vargs2 fn vres1 vres2.\nProof.\n  move=> hargs hincl hptreq hnnone.\n  apply Forall3_impl_in.\n  move=> [i|//] vr1 vr2 hoi _ _ [p [-> hresultp]].\n  exists p; split; first by reflexivity.\n  have /List.Forall_forall -/(_ _ hoi _ refl_equal) := hnnone.\n  case hpi: nth => [pi|//] _.\n  case: (hresultp) => hrargs hsub hread.\n  split=> //.\n  + by rewrite (Forall3_nth hptreq None (Vbool true) (Vbool true)\n      (nth_not_default hpi ltac:(discriminate)) ltac:(congruence)).\n  have := Forall2_nth hincl (Vbool true) (Vbool true).\n  have -> := Forall2_size hincl.\n  have [<- _] := Forall3_size hargs.\n  move=> /(_ _ (nth_not_default hpi ltac:(discriminate))).\n  move=> /value_uincl_subtype.\n  by apply subtype_trans.\nQed.\n\nLemma free_stack_spec_wf_results m1 m2 fn vargs1 vargs2 m3 m3' vres1 vres2 :\n  wf_args m1 m3 fn vargs1 vargs2 ->\n  validw m3 =2 validw m3' ->\n  free_stack_spec m2 m3' ->\n  List.Forall (fun oi => forall i, oi = Some i -> nth None (local_alloc fn).(sao_params) i <> None) (local_alloc fn).(sao_return) ->\n  wf_results m2 vargs1 vargs2 fn vres1 vres2 ->\n  wf_results m3' vargs1 vargs2 fn vres1 vres2.\nProof.\n  move=> hargs hvalid hfss hforall.\n  apply Forall3_impl_in.\n  move=> [i|//] vr1 vr2 hoi _ _ [p [-> hresultp]].\n  exists p; split; first by reflexivity.\n  have /List.Forall_forall -/(_ _ hoi _ refl_equal) := hforall.\n  case hpi: nth => [pi|//] _.\n  case: (hresultp) => hrargs hsub hread.\n  split=> //.\n  move=> off w /dup[] /get_val_byte_bound hoff.\n  rewrite -hfss.(fss_read_old8); first by apply hread.\n  have := Forall3_nth hargs None (Vbool true) (Vbool true) (nth_not_default hpi ltac:(discriminate)).\n  rewrite hpi /= hrargs.\n  move=> [_ [[<-] hargp]].\n  rewrite -hvalid.\n  apply hargp.(wap_valid).\n  apply: between_byte hoff.\n  + by apply (no_overflow_incl (zbetween_le _ (size_of_le hsub)) hargp.(wap_no_overflow)).\n  by apply: zbetween_le (size_of_le hsub).\nQed.\n\nLemma value_uincl_disjoint_from_writable_params fn vargs1 vargs1' vargs2 vargs2' p :\n  List.Forall2 value_uincl vargs1' vargs1 ->\n  Forall3 (fun opi varg varg' => opi <> None -> varg = varg') (local_alloc fn).(sao_params) vargs2 vargs2' ->\n  disjoint_from_writable_params fn p vargs1 vargs2 ->\n  disjoint_from_writable_params fn p vargs1' vargs2'.\nProof.\n  rewrite /disjoint_from_writable_params.\n  move=> hincl hptreq hdisj.\n  elim: {vargs1 vargs2} hdisj vargs1' hincl vargs2' hptreq.\n  + move=> _ /List_Forall2_inv_r -> [|??] /List_Forall3_inv // _.\n    by constructor.\n  move=> opi varg1 varg2 sao_params vargs1 vargs2 hdisj _ ih.\n  move=> _ /List_Forall2_inv_r [varg1' [vargs1' [-> [hincl /ih{ih}ih]]]].\n  move=> [|varg2' vargs2'] /List_Forall3_inv // [hptreq /ih{ih}ih].\n  constructor=> //.\n  move=> pi p2 ?? hw; subst opi varg2'.\n  apply (disjoint_zrange_incl_l (zbetween_le _ (size_of_le (value_uincl_subtype hincl)))).\n  rewrite /disjoint_from_writable_param in hdisj.\n  by apply (hdisj _ _ refl_equal (hptreq ltac:(discriminate)) hw).\nQed.\n\n(* sem_call has 7 steps that are reflected in this proof:\n  - truncate_val of args,\n  - init_state,\n  - write_vars of args,\n  - execution of the body,\n  - get_var of results,\n  - truncate_val of results,\n  - finalize.\n*)\nLocal Lemma Hproc : sem_Ind_proc P ev Pc Pfun.\nProof.\n  move=> scs1 m1 _ _ fn fd vargs1' vargs1 _ s1 s1' vres1 vres1' hfd hvargs1' /= [<-] hs1 hsem1 Hc hvres1 hvres1' -> ->.\n  move=> m2 vargs2 hext hargs hdisjv hok.\n  have [fd2 halloc hfd2] := Halloc_fd hfd.\n  move: halloc; rewrite /alloc_fd /alloc_fd_aux /=.\n  t_xrbindP=> fd2' stack hlayout [[locals1 rmap1] vnew1] hlocal_map.\n  t_xrbindP=> -[[[vnew2 locals2] rmap2] alloc_params] hparams.\n  t_xrbindP=> /ZleP hextra /ZleP hmax.\n  move=> [rmap3 c] halloc.\n  t_xrbindP=> res hcresults ??; subst fd2 fd2'.\n\n  (* truncate_val of args *)\n  have [vargs2' [hvargs2' hargs']] := mapM2_truncate_val_wf_args hargs hvargs1'.\n  have huincl := mapM2_truncate_value_uincl hvargs1'.\n  have hptreq := mapM2_truncate_val_ptr_eq hargs hvargs2'.\n  have hdisjv' := value_uincl_disjoint_values hargs hdisjv huincl hptreq.\n\n  (* init_state *)\n  have [m2' halloc_stk]: exists m2',\n    alloc_stack m2 (sao_align (local_alloc fn)) (sao_size (local_alloc fn)) (sao_ioff (local_alloc fn))\n                   (sao_extra_size (local_alloc fn)) = ok m2'.\n  + apply Memory.alloc_stack_complete.\n    have [h1 h2 _] := init_stack_layoutP hlayout.\n    apply /and4P; split.\n    1-3: by apply/ZleP.\n    move: hok; rewrite /alloc_ok => /(_ _ hfd2) /=; rewrite /allocatable_stack => -[hallocatable hal].\n    case: is_RAnone hal hmax => [_|-> //] hmax; last by apply /ZleP; lia.\n    case: is_align; last by apply /ZleP; lia.\n    apply /ZleP.\n    have := round_ws_range (sao_align (local_alloc fn)) (sao_size (local_alloc fn) + sao_extra_size (local_alloc fn)).\n    by lia.\n  have hass := Memory.alloc_stackP halloc_stk.\n  set fex := {| sf_align := _ |} in hfd2.\n  set rsp := top_stack m2'.\n  have hinit:\n    init_stk_state fex (p_extra P') rip {| escs := scs1; emem := m2; evm := vmap0 |} =\n    ok\n      {|\n        escs := scs1;\n        emem := m2';\n        evm := vmap0\n          .[\n            {|\n              vtype := spointer;\n              vname := P'.(p_extra).(sp_rsp);\n            |} <- ok (pword_of_word rsp)\n          ]\n          .[\n            {|\n              vtype := spointer;\n              vname := P'.(p_extra).(sp_rip);\n            |} <- ok (pword_of_word rip)\n          ];\n      |}.\n  + by rewrite /init_stk_state halloc_stk /=  sumbool_of_boolET !pword_of_wordE.\n  have hover := ass_no_overflow hass.\n  have hargs'' := alloc_stack_spec_wf_args hargs' hass.\n  have hext' := alloc_stack_spec_extend_mem hext hass.\n\n  have hdisj_glob_locals: 0 < glob_size -> 0 < (local_alloc fn).(sao_size) ->\n    disjoint_zrange rip glob_size rsp (sao_size (local_alloc fn)).\n  + move=> hlt1 hlt2.\n    apply disjoint_zrange_sym.\n    apply disjoint_zrange_U8 => //.\n    move=> k hk.\n    have hb: between rip glob_size (rip + wrepr _ k)%R U8.\n    + apply: between_byte hk => //.\n      by apply zbetween_refl.\n    (* TODO: use disjoint_zrange in ass_fresh? *)\n    have /hass.(ass_fresh) hfresh: validw m2 (rip + wrepr _ k)%R U8.\n    + apply hext.(em_valid).\n      by rewrite hb orbT.\n    apply disjoint_zrange_sym.\n    split=> //.\n    by apply: (no_overflow_incl hb).\n  have hdisj_locals_params:\n    Forall3 (fun opi varg1 varg2 => forall pi, opi = Some pi ->\n      forall (p:pointer), varg2 = Vword p -> 0 < (local_alloc fn).(sao_size) -> disjoint_zrange rsp (local_alloc fn).(sao_size) p (size_val varg1))\n    (sao_params (local_alloc fn)) vargs1' vargs2'.\n  + apply: Forall3_impl hargs'.\n    move=> opi varg1 varg2 harg pi ? p ? hlt; subst opi varg2.\n    case: harg => _ [[<-] hargp].\n    apply disjoint_zrange_U8 => //.\n    + by apply size_of_gt0.\n    + by apply hargp.(wap_no_overflow).\n    move=> k hk.\n    have hb: between p (size_val varg1) (p + wrepr _ k) U8.\n    + apply: between_byte hk.\n      + by apply hargp.(wap_no_overflow).\n      by apply zbetween_refl.\n    have hfresh := hass.(ass_fresh) (hargp.(wap_valid) hb).\n    apply disjoint_zrange_sym.\n    split=> //.\n    by apply: no_overflow_incl hb hargp.(wap_no_overflow).\n\n  have hsub := write_vars_subtype (init_params_sarr hparams) hs1. (* 'backported' from write_vars of args *)\n  set vxlen := (fresh_reg_ _ _) in halloc.\n  have /= hvs := init_stk_state_valid_state hlayout hover\n    scs1 hargs' hsub hlocal_map hparams hext hass refl_equal rip_rsp_neq.\n  have hpmap := init_params_wf_pmap hlayout rsp vargs1' vargs2' hlocal_map hparams.\n  have hslots := Hwf_Slots hlayout hover hdisj_glob_locals hext.(em_align)\n    hass.(ass_align_stk) hargs' hdisjv' hsub hparams hdisj_locals_params.\n\n  (* write_vars of args *)\n  have [s2 [hs2 hvs']] := valid_state_init_params hlayout hargs'' hlocal_map hparams hvs hs1.\n  have hext'': extend_mem (emem s1) (emem s2) rip global_data.\n  + have /= <- := write_vars_emem hs1.\n    by have /= <- := write_vars_emem hs2.\n\n  have hsao: wf_sao rsp (emem s2) (local_alloc fn).\n  + have /= <- := write_vars_emem hs2.\n    split.\n    + rewrite /enough_size /allocatable_stack.\n      split; first by lia.\n      rewrite /top_stack hass.(ass_frames) /= hass.(ass_limit).\n      move: hok; rewrite /alloc_ok => /(_ _ hfd2) /= []; rewrite /allocatable_stack.\n      have hsize := init_stack_layout_size_ge0 hlayout.\n      assert (hge := wunsigned_range (stack_limit m2)).\n      have hpos := wsize_size_pos (sao_align (local_alloc fn)).\n      case: is_RAnone hmax.\n      + move=> hmax hok _.\n        have hbound: 0 <= sao_size (local_alloc fn) + sao_extra_size (local_alloc fn)\n                  /\\ sao_size (local_alloc fn) + sao_extra_size (local_alloc fn) <= wunsigned (top_stack m2).\n        + by lia.\n        have := @top_stack_after_alloc_bounded _ _ (local_alloc fn).(sao_align) _ hbound.\n        by lia.\n      move=> hmax hok1 hok2.\n      rewrite (top_stack_after_aligned_alloc _ (hok2 _)) //.\n      rewrite wunsigned_add; first by lia.\n      split; first by lia.\n      assert (hrange := wunsigned_range (top_stack m2)).\n      have [? _] := round_ws_range (sao_align (local_alloc fn)) (sao_size (local_alloc fn) + sao_extra_size (local_alloc fn)).\n      by lia.\n   by apply hass.(ass_align_stk).\n\n  (* execution of the body *)\n  have [s2' [hsem2 hvs''']] := Hc _ _ _ _ _ _ _ _ _ hpmap hslots _ halloc _ _ hvs' hext'' hsao.\n  have hext''' := valid_state_extend_mem hslots hvs' hext'' hvs''' (sem_validw_stable_uprog hsem1) (sem_validw_stable_sprog hsem2).\n\n  (* get_var of results *)\n  have harr: List.Forall2 (fun osr (x : var_i) => osr <> None -> is_sarr (vtype x)) (map fst alloc_params) (f_params fd).\n  + by apply: (Forall2_trans _ (init_params_alloc_params_not_None hparams) (init_params_sarr hparams)); auto.\n  have hsub' := write_vars_subtype harr hs1.\n  have haddr := init_params_alloc_params rsp hargs'' hparams.\n  have [vres2 [hvres2 hresults]] := check_resultsP hvs''' hsub' haddr hcresults hvres1.\n\n  (* truncate_val of results *)\n  have [vres2' [hvres2' hresults']] := mapM2_truncate_val_wf_results hresults hvres1'.\n  have hnnone: List.Forall (fun oi => forall i, oi = Some i -> nth None (sao_params (local_alloc fn)) i <> None)\n                           (sao_return (local_alloc fn)).\n  + apply: List.Forall_impl (check_results_alloc_params_not_None hcresults).\n    move=> oi hnnone i ?; subst oi.\n    move: hnnone => /(_ _ refl_equal).\n    case hsr: nth => [sr|//] _.\n    apply (Forall2_nth (init_params_alloc_params_not_None hparams) None None (nth_not_default hsr ltac:(discriminate))).\n    by rewrite hsr.\n  have hresults'' := value_uincl_wf_results hargs huincl hptreq hnnone hresults'.\n\n  (* finalize *)\n  have hfss := Memory.free_stackP (emem s2').\n  have hvalideq1: validw m1 =2 validw (emem s1').\n  + have /= -> := write_vars_emem hs1.\n    by apply (sem_validw_stable_uprog hsem1).\n  have hvalideq2: validw m2 =2 validw (free_stack (emem s2')).\n  + apply: (alloc_free_validw_stable hass _ _ hfss);\n      have /= -> := write_vars_emem hs2.\n    + by apply (sem_stack_stable_sprog hsem2).\n    by apply (sem_validw_stable_sprog hsem2).\n  have hresults''' := free_stack_spec_wf_results hargs hvalideq2 hfss hnnone hresults''.\n\n  exists (free_stack (emem s2')), vres2'.\n  split.\n  + by econstructor; eauto; case: hvs'''.\n  split.\n  + apply (free_stack_spec_extend_mem hext''' hfss).\n    move=> p.\n    rewrite -hvalideq1 -hvalideq2.\n    by apply hext.(em_valid).\n  split=> //.\n  rewrite /mem_unchanged_params.\n  move=> p hvalid1 hvalid2 hdisjp.\n  rewrite -hfss.(fss_read_old8) -?hvalideq2 //.\n  have /vs_unchanged := hvs'''; apply => //.\n  + by rewrite -hvalideq1.\n  apply (disjoint_from_writable_params_all_slots hlayout hover hargs'' hsub hparams).\n  + by apply (value_uincl_disjoint_from_writable_params huincl hptreq hdisjp).\n  have ? := hass.(ass_fresh) hvalid1.\n  split.\n  + by apply hover.\n  + apply is_align_no_overflow.\n    by apply is_align8.\n  by apply or_comm.\nQed.\n\nLemma check_cP scs1 m1 fn vargs scs2 m2 vres : sem_call P ev scs1 m1 fn vargs scs2 m2 vres -> \n   Pfun scs1 m1 fn vargs scs2 m2 vres.\nProof.\n  exact:\n    (sem_call_Ind\n       Hskip\n       Hcons\n       HmkI\n       Hassgn\n       Hopn\n       Hsyscall\n       Hif_true\n       Hif_false\n       Hwhile_true\n       Hwhile_false\n       Hfor\n       Hfor_nil\n       Hfor_cons\n       Hcall\n       Hproc).\nQed.\n\nEnd PROC.\n\nEnd INIT.\n\nSection HSAPARAMS.\n\nContext\n  {asm_op syscall_state : Type}\n  {ep : EstateParams syscall_state}\n  {spp : SemPexprParams}\n  {sip : SemInstrParams asm_op syscall_state}\n  (saparams : stack_alloc_params)\n  (hsaparams : h_stack_alloc_params saparams)\n  (fresh_reg_ : Ident.ident -> stype -> Ident.ident).\n\nLemma get_alloc_fd p_extra mglob oracle fds1 fds2 :\n  map_cfprog_name (alloc_fd saparams p_extra mglob fresh_reg_ oracle) fds1 = ok fds2 ->\n  forall fn fd1,\n  get_fundef fds1 fn = Some fd1 ->\n  exists2 fd2, alloc_fd saparams p_extra mglob fresh_reg_ oracle fn fd1 = ok fd2 &\n               get_fundef fds2 fn = Some fd2.\nProof.\n  move=> hmap fn fd1.\n  by apply: get_map_cfprog_name_gen hmap.\nQed.\n\n(* Here are informal descriptions of the predicates used in the theorem.\n\n   - extend_mem m1 m2 rip data: [m2] is a memory that contains at least [m1]\n       and (disjointly) data [data] at adress [rip];\n\n   - wf_args: link between the values taken as arguments in the source and the target\n       (complex predicate if the argument is a reg ptr, just equality otherwise);\n\n   - disjoint_values: the writable [reg ptr]s taken as arguments point to memory zones\n       that are pairwise disjoint and disjoint from the zones pointed to by\n       non writable [reg ptr]s;\n\n   - alloc_ok: the call is possible in the target (there is enough space in the\n       stack, and the top of the stack is aligned if the callee is not an export function);\n\n   - wf_results: link between the values returned in the source and the target\n       (complex predicate if the result is a reg ptr, just equality otherwise);\n\n   - mem_unchanged_params: the function call does not modify the stack region,\n      except for the regions pointed to by the writable [reg ptr]s given as arguments.\n*)\nTheorem alloc_progP nrip nrsp data oracle_g oracle (P: uprog) (SP: sprog) fn:\n  alloc_prog saparams fresh_reg_ nrip nrsp data oracle_g oracle P = ok SP ->\n  forall ev scs1 m1 vargs1 scs1' m1' vres1,\n    sem_call P ev scs1 m1 fn vargs1 scs1' m1' vres1 ->\n    forall rip m2 vargs2,\n      extend_mem m1 m2 rip data ->\n      wf_args data rip oracle m1 m2 fn vargs1 vargs2 ->\n      disjoint_values (oracle fn).(sao_params) vargs1 vargs2 ->\n      alloc_ok SP fn m2 ->\n      exists m2' vres2,\n        sem_call SP rip scs1 m2 fn vargs2 scs1' m2' vres2 /\\\n        extend_mem m1' m2' rip data /\\\n        wf_results oracle m2' vargs1 vargs2 fn vres1 vres2 /\\\n        mem_unchanged_params oracle fn m1 m2 m2' vargs1 vargs2.\nProof.\n  move=> hprog ev scs1 m1 vargs1 scs1' m1' vres1 hsem1 rip m2 vargs2 hext hargs hdisj halloc.\n  move: hprog; rewrite /alloc_prog.\n  t_xrbindP=> mglob hmap.\n  case: eqP => [//|hneq].\n  case: ifP => [hcheck|//].\n  t_xrbindP=> fds hfds.\n  set P' := {| p_funcs := _ |} => ?; subst SP.\n\n  have [fd1 hfd1]: exists fd, get_fundef (p_funcs P) fn = Some fd.\n  + have [fd1 [hfd1 _]] := sem_callE hsem1.\n    by exists fd1.\n  by apply (check_cP\n              hext.(em_no_overflow)\n              hmap\n              hcheck\n              (P':=P')\n              refl_equal\n              hsaparams\n              (get_alloc_fd hfds)\n              hneq\n              hsem1\n              hext\n              hargs\n              hdisj\n              halloc).\nQed.\n\nLemma alloc_prog_get_fundef nrip nrsp data oracle_g oracle (P: uprog) (SP: sprog) :\n  alloc_prog saparams fresh_reg_ nrip nrsp data oracle_g oracle P = ok SP →\n  exists2 mglob,\n    init_map (Z.of_nat (size data)) oracle_g = ok mglob &\n    ∀ fn fd,\n    get_fundef (p_funcs P) fn = Some fd →\n    exists2 fd',\n      alloc_fd saparams {| sp_rsp := nrsp ; sp_rip := nrip ; sp_globs := data |} mglob fresh_reg_ oracle fn fd = ok fd' &\n      get_fundef (p_funcs SP) fn = Some fd'.\nProof.\n  rewrite /alloc_prog; t_xrbindP => mglob ->.\n  case: eqP => // _.\n  case: ifP => // _.\n  t_xrbindP => fds ok_fds <- {SP} /=.\n  exists mglob; first reflexivity.\n  exact: get_alloc_fd.\nQed.\n\nLemma alloc_fd_checked_sao p_extra mglob oracle fn fd fd' :\n  alloc_fd saparams p_extra mglob fresh_reg_ oracle fn fd = ok fd' →\n  [/\\ size (sao_params (oracle fn)) = size (f_params fd) & size (sao_return (oracle fn)) = size (f_res fd) ].\nProof.\n  rewrite /alloc_fd/alloc_fd_aux/check_results.\n  t_xrbindP => ?? _ [[? ?] ?] _.\n  t_xrbindP => [] [[[? ?] ?] ?] ok_params.\n  t_xrbindP => _ _ [? ?] _.\n  t_xrbindP => ? _ ok_results; subst.\n  split.\n  - by case: (size_fmapM2 ok_params).\n  by case: (size_mapM2 ok_results).\nQed.\n\nEnd HSAPARAMS.\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_proof_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2709296636763177}}
{"text": "Require Import GLS_PSGLS_calcs.\nRequire Import List.\nExport ListNotations.\n\nRequire Import genT gen.\nRequire Import ddT.\nRequire Import gen_tacs.\nRequire Import gen_seq.\nRequire Import List_lemmasT.\nRequire Import existsT.\nRequire Import univ_gen_ext.\nRequire Import GLS_PSGLS_list_lems.\nRequire Import dd_fc.\nRequire Import PeanoNat.\nRequire Import strong_inductionT.\nRequire Import PSGLS_termination_measure.\nRequire Import PSGLS_termination.\nRequire Import GLS_exch.\nRequire Import GLS_ctr.\nRequire Import GLS_wkn.\nRequire Import GLS_PSGLS_remove_list.\nRequire Import GLS_PSGLS_dec.\nRequire Import GLS_inv_ImpR_ImpL.\nRequire Import Lia.\n\nDelimit Scope My_scope with M.\nOpen Scope My_scope.\nSet Implicit Arguments.\n\nTheorem GLS_cut_adm_main : forall n k A s Γ0 Γ1 Δ0 Δ1,\n                      (n = size_form A) ->\n                      (k = mhd s) ->\n                      (s = (Γ0 ++ Γ1, Δ0 ++ Δ1)) ->\n                      (GLS_prv (Γ0 ++ Γ1, Δ0 ++ A :: Δ1)) ->\n                      (GLS_prv (Γ0 ++ A :: Γ1, Δ0 ++ Δ1)) ->\n                      (GLS_prv s).\nProof.\n(* The proof is by induction on, first, size_form of the cut formula and on, second, the mhd\n   of the sequent-conclusion. *)\n(* We set up the strong induction on n properly first. *)\npose (d:=strong_inductionT (fun (x:nat) => forall k A s Γ0 Γ1 Δ0 Δ1,\n                      x = size_form A ->\n                      (k = mhd s) ->\n                      (s = (Γ0 ++ Γ1, Δ0 ++ Δ1)) ->\n                      ((GLS_prv (Γ0 ++ Γ1, Δ0 ++ A :: Δ1)) ->\n                      (GLS_prv (Γ0 ++ A :: Γ1, Δ0 ++ Δ1)) ->\n                      (GLS_prv s)))).\napply d. clear d. intros n PIH.\npose (d:=strong_inductionT (fun (x:nat) => forall A s Γ0 Γ1 Δ0 Δ1,\n                      n = size_form A ->\n                      (x = mhd s) ->\n                      (s = (Γ0 ++ Γ1, Δ0 ++ Δ1)) ->\n                      ((GLS_prv (Γ0 ++ Γ1, Δ0 ++ A :: Δ1)) ->\n                      (GLS_prv (Γ0 ++ A :: Γ1, Δ0 ++ Δ1)) ->\n                      (GLS_prv s)))).\napply d. clear d. intros k SIH.\n\n(* Now we do the actual proof-theoretical work. *)\nassert (DersNilF: dersrec GLS_rules (fun _ : Seq => False) []).\napply dersrec_nil.\nassert (DersNilT: dersrec GLS_rules (fun _ : Seq => True) []).\napply dersrec_nil.\nassert (PSDersNilF: dersrec PSGLS_rules (fun _ : Seq => False) []).\napply dersrec_nil.\nassert (PSDersNilT: dersrec PSGLS_rules (fun _ : Seq => True) []).\napply dersrec_nil.\n\nintros A s Γ0 Γ1 Δ0 Δ1 size MHD E D0 D1. inversion D0. inversion H.\ninversion D1. inversion H0.\n\ninversion X ; subst.\n\n(* Left rule is IdP *)\n- inversion H1. subst. apply list_split_form in H3. repeat destruct H3.\n  * destruct s.\n    + repeat destruct p. subst. inversion X1.\n    (* Right rule is IdP *)\n    { inversion H. subst. assert (J0 : InT (# P0) (Γ0 ++ # P :: Γ1)). rewrite <- H6. apply InT_or_app.\n      right. apply InT_eq. apply InT_app_or in J0. destruct J0.\n      - apply InT_split in i. destruct i. destruct s. subst. rewrite H2. repeat rewrite <- app_assoc.\n        assert (IdPRule [] (x ++ (# P0 :: x0) ++ Γ1, Δ2 ++ # P0 :: Δ3)). apply IdPRule_I. apply IdP in H0.\n        pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n        (ps:=[]) (x ++ (# P0 :: x0) ++ Γ1, Δ2 ++ # P0 :: Δ3) H0 DersNilF). assumption.\n      - inversion i.\n        + inversion H3. subst.\n          assert (IdPRule [] (Γ2 ++ # P0 :: Γ3, Δ2 ++ # P0 :: Δ3)). apply IdPRule_I. apply IdP in H0.\n          pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n          (ps:=[]) (Γ2 ++ # P0 :: Γ3, Δ2 ++ # P0 :: Δ3) H0 DersNilF). assumption.\n        + apply InT_split in H3. destruct H3. destruct s. subst.\n          assert (J0 : InT (# P0) (Γ2 ++ # P :: Γ3)). rewrite H2. apply InT_or_app.\n          right. apply InT_or_app. right. apply InT_eq. apply InT_split in J0. destruct J0. destruct  s.\n          rewrite e. assert (IdPRule [] (x1 ++ # P0 :: x2, Δ2 ++ # P0 :: Δ3)).\n          apply IdPRule_I. apply IdP in H0.\n          pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n          (ps:=[]) (x1 ++ # P0 :: x2, Δ2 ++ # P0 :: Δ3) H0 DersNilF). assumption. }\n    (* Right rule is BotL *)\n    { inversion H. subst. assert (J0 : InT (⊥) (Γ0 ++ # P :: Γ1)). rewrite <- H6. apply InT_or_app.\n      right. apply InT_eq. apply InT_app_or in J0. destruct J0.\n      - apply InT_split in i. destruct i. destruct s. subst. rewrite H2. rewrite <- app_assoc.\n        assert (BotLRule [] (x ++ (⊥ :: x0) ++ Γ1, Δ0 ++ Δ1)). apply BotLRule_I. apply BotL in H0.\n        pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n        (ps:=[]) (x ++ (⊥ :: x0) ++ Γ1, Δ0 ++ Δ1) H0 DersNilF). assumption.\n      - inversion i.\n        + inversion H3.\n        + apply InT_split in H3. destruct H3. destruct s. subst. rewrite H2. rewrite app_assoc.\n          assert (BotLRule [] ((Γ0 ++ x) ++ ⊥ :: x0, Δ0 ++ Δ1)). apply BotLRule_I. apply BotL in H0.\n          pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n          (ps:=[]) ((Γ0 ++ x) ++ ⊥ :: x0, Δ0 ++ Δ1) H0 DersNilF). assumption. }\n    (* Right rule is ImpR *)\n    { inversion H. subst. assert (InT  # P (Γ0 ++ Γ1)). rewrite <- H2. apply InT_or_app.\n      right. apply InT_eq. apply InT_app_or in H0. destruct H0.\n      - apply InT_split in i. destruct i.\n        destruct s. subst. repeat rewrite <- app_assoc in D1. simpl in D1.\n        assert (E0: derrec_height D1 = derrec_height D1). reflexivity.\n        assert (J0 : ctr_L # P (x ++ # P :: x0 ++ # P :: Γ1, Δ0 ++ Δ1)\n        (x ++ # P :: x0 ++ Γ1, Δ0 ++ Δ1)). apply ctr_LI.\n        pose (@GLS_hpadm_ctr_L (derrec_height D1) (x ++ # P :: x0 ++ # P :: Γ1, Δ0 ++ Δ1)\n        D1 E0 (x ++ # P :: x0 ++ Γ1, Δ0 ++ Δ1) (# P) J0). destruct s. clear l. rewrite H2.\n        rewrite <- app_assoc. rewrite H7. assumption.\n      - apply InT_split in i. destruct i. destruct s. subst.\n        assert (E0: derrec_height D1 = derrec_height D1). reflexivity.\n        assert (J0 : ctr_L # P (Γ0 ++ # P :: x ++ # P :: x0, Δ0 ++ Δ1)\n        (Γ0 ++ # P :: x ++ x0, Δ0 ++ Δ1)). apply ctr_LI.\n        pose (@GLS_hpadm_ctr_L (derrec_height D1) (Γ0 ++ # P :: x ++ # P :: x0, Δ0 ++ Δ1)\n        D1 E0 (Γ0 ++ # P :: x ++ x0, Δ0 ++ Δ1) (# P) J0). destruct s. clear l. rewrite H2.\n        assert (J5 : list_exch_L (Γ0 ++ # P :: x ++ x0, Δ0 ++ Δ1) (Γ0 ++ x ++ # P :: x0, Δ0 ++ Δ1)).\n        assert (Γ0 ++ # P :: x ++ x0 = Γ0 ++ [# P] ++ x ++ [] ++  x0). reflexivity. rewrite H0. clear H0.\n        assert (Γ0 ++ x ++ # P :: x0 = Γ0 ++ [] ++ x ++ [# P] ++ x0). reflexivity. rewrite H0. clear H0.\n        apply list_exch_LI. pose (GLS_adm_list_exch_L x1 J5). rewrite H7. assumption. }\n    (* Right rule is ImpL *)\n    { inversion H. subst. assert (InT  # P (Γ0 ++ Γ1)). rewrite <- H2. apply InT_or_app.\n      right. apply InT_eq. apply InT_app_or in H0. destruct H0.\n      - apply InT_split in i. destruct i.\n        destruct s. subst. repeat rewrite <- app_assoc in D1. simpl in D1.\n        assert (E0: derrec_height D1 = derrec_height D1). reflexivity.\n        assert (J0 : ctr_L # P (x ++ # P :: x0 ++ # P :: Γ1, Δ0 ++ Δ1)\n        (x ++ # P :: x0 ++ Γ1, Δ0 ++ Δ1)). apply ctr_LI.\n        pose (@GLS_hpadm_ctr_L (derrec_height D1) (x ++ # P :: x0 ++ # P :: Γ1, Δ0 ++ Δ1)\n        D1 E0 (x ++ # P :: x0 ++ Γ1, Δ0 ++ Δ1) (# P) J0). destruct s. clear l. rewrite H2.\n        rewrite <- app_assoc. rewrite H7. assumption.\n      - apply InT_split in i. destruct i. destruct s. subst.\n        assert (E0: derrec_height D1 = derrec_height D1). reflexivity.\n        assert (J0 : ctr_L # P (Γ0 ++ # P :: x ++ # P :: x0, Δ0 ++ Δ1)\n        (Γ0 ++ # P :: x ++ x0, Δ0 ++ Δ1)). apply ctr_LI.\n        pose (@GLS_hpadm_ctr_L (derrec_height D1) (Γ0 ++ # P :: x ++ # P :: x0, Δ0 ++ Δ1)\n        D1 E0 (Γ0 ++ # P :: x ++ x0, Δ0 ++ Δ1) (# P) J0). destruct s. clear l. rewrite H2.\n        assert (J5 : list_exch_L (Γ0 ++ # P :: x ++ x0, Δ0 ++ Δ1) (Γ0 ++ x ++ # P :: x0, Δ0 ++ Δ1)).\n        assert (Γ0 ++ # P :: x ++ x0 = Γ0 ++ [# P] ++ x ++ [] ++  x0). reflexivity. rewrite H0. clear H0.\n        assert (Γ0 ++ x ++ # P :: x0 = Γ0 ++ [] ++ x ++ [# P] ++ x0). reflexivity. rewrite H0. clear H0.\n        apply list_exch_LI. pose (GLS_adm_list_exch_L x1 J5). rewrite H7. assumption. }\n    (* Right rule is GLR *)\n    { inversion X3. subst. assert (InT  # P (Γ0 ++ Γ1)). rewrite <- H2. apply InT_or_app.\n      right. apply InT_eq. apply InT_app_or in H. destruct H.\n      - apply InT_split in i. destruct i.\n        destruct s. subst. repeat rewrite <- app_assoc in D1. simpl in D1.\n        assert (E0: derrec_height D1 = derrec_height D1). reflexivity.\n        assert (J0 : ctr_L # P (x ++ # P :: x0 ++ # P :: Γ1, Δ0 ++ Δ1)\n        (x ++ # P :: x0 ++ Γ1, Δ0 ++ Δ1)). apply ctr_LI.\n        pose (@GLS_hpadm_ctr_L (derrec_height D1) (x ++ # P :: x0 ++ # P :: Γ1, Δ0 ++ Δ1)\n        D1 E0 (x ++ # P :: x0 ++ Γ1, Δ0 ++ Δ1) (# P) J0). destruct s. clear l. rewrite H2.\n        rewrite <- app_assoc. rewrite H6. assumption.\n      - apply InT_split in i. destruct i. destruct s. subst.\n        assert (E0: derrec_height D1 = derrec_height D1). reflexivity.\n        assert (J0 : ctr_L # P (Γ0 ++ # P :: x ++ # P :: x0, Δ0 ++ Δ1)\n        (Γ0 ++ # P :: x ++ x0, Δ0 ++ Δ1)). apply ctr_LI.\n        pose (@GLS_hpadm_ctr_L (derrec_height D1) (Γ0 ++ # P :: x ++ # P :: x0, Δ0 ++ Δ1)\n        D1 E0 (Γ0 ++ # P :: x ++ x0, Δ0 ++ Δ1) (# P) J0). destruct s. clear l. rewrite H2.\n        assert (J5 : list_exch_L (Γ0 ++ # P :: x ++ x0, Δ0 ++ Δ1) (Γ0 ++ x ++ # P :: x0, Δ0 ++ Δ1)).\n        assert (Γ0 ++ # P :: x ++ x0 = Γ0 ++ [# P] ++ x ++ [] ++  x0). reflexivity. rewrite H. clear H.\n        assert (Γ0 ++ x ++ # P :: x0 = Γ0 ++ [] ++ x ++ [# P] ++ x0). reflexivity. rewrite H. clear H.\n        apply list_exch_LI. pose (GLS_adm_list_exch_L x1 J5). rewrite H6. assumption. }\n    + repeat destruct s. repeat destruct p. subst. assert (IdPRule []  (Γ2 ++ # P :: Γ3, (Δ0 ++ x0) ++ # P :: Δ3)).\n      apply IdPRule_I. rewrite <- app_assoc in H. apply IdP in H.\n      pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n      (ps:=[])  (Γ2 ++ # P :: Γ3, Δ0 ++ x0 ++ # P :: Δ3) H DersNilF). assumption.\n  * repeat destruct s. repeat destruct p. subst. assert (IdPRule [] (Γ2 ++ # P :: Γ3, Δ2 ++ # P :: x ++ Δ1)).\n    apply IdPRule_I. apply IdP in H. rewrite <- app_assoc.\n    pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n    (ps:=[]) (Γ2 ++ # P :: Γ3, Δ2 ++ (# P :: x) ++ Δ1) H DersNilF). assumption.\n\n(* Left rule is BotL *)\n- inversion H1. subst. assert (BotLRule [] (Γ2 ++ ⊥ :: Γ3, Δ0 ++ Δ1)).\n  apply BotLRule_I. apply BotL in H.\n  pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n  (ps:=[]) (Γ2 ++ ⊥ :: Γ3, Δ0 ++ Δ1) H DersNilF).\n  assumption.\n\n(* Left rule is ImpR *)\n- inversion H1. subst. apply list_split_form in H3. destruct H3.\n  * destruct s.\n    + repeat destruct p. subst. inversion X1.\n      (* Right rule is IdP *)\n      { inversion H. subst. assert (J0 : InT (# P) (Γ0 ++ (A0 → B) :: Γ1)). rewrite <- H6. apply InT_or_app.\n        right. apply InT_eq. apply InT_app_or in J0. destruct J0.\n        - apply InT_split in i. destruct i. destruct s. subst. rewrite H2. rewrite <- app_assoc.\n          assert (IdPRule [] (x ++ (# P :: x0) ++ Γ1, Δ2 ++ # P :: Δ3)). apply IdPRule_I. apply IdP in H0.\n          pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n          (ps:=[]) (x ++ (# P :: x0) ++ Γ1, Δ2 ++ # P :: Δ3) H0 DersNilF). assumption.\n        - inversion i.\n          * inversion H3.\n          * apply InT_split in H3. destruct H3. destruct s. subst. rewrite H2. rewrite app_assoc.\n            assert (IdPRule [] ((Γ0 ++ x) ++ # P :: x0, Δ2 ++ # P :: Δ3)). apply IdPRule_I. apply IdP in H0.\n            pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n            (ps:=[]) ((Γ0 ++ x) ++ # P :: x0, Δ2 ++ # P :: Δ3) H0 DersNilF). assumption. }\n      (* Right rule is BotL *)\n      { inversion H. subst. rewrite H2. assert (J0 : InT (⊥) (Γ0 ++ (A0 → B) :: Γ1)). rewrite <- H6. apply InT_or_app.\n        right. apply InT_eq. apply InT_app_or in J0. destruct J0.\n        - apply InT_split in i. destruct i. destruct s. subst. rewrite <- app_assoc.\n          assert (BotLRule [] (x ++ (⊥ :: x0) ++ Γ1, Δ0 ++ Δ1)). apply BotLRule_I. apply BotL in H0.\n          pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n          (ps:=[]) (x ++ (⊥ :: x0) ++ Γ1, Δ0 ++ Δ1) H0 DersNilF). assumption.\n        - inversion i.\n          * inversion H3.\n          * apply InT_split in H3. destruct H3. destruct s. subst. rewrite app_assoc.\n            assert (BotLRule [] ((Γ0 ++ x) ++ ⊥ :: x0, Δ0 ++ Δ1)). apply BotLRule_I. apply BotL in H0.\n            pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n            (ps:=[]) ((Γ0 ++ x) ++ ⊥ :: x0, Δ0 ++ Δ1) H0 DersNilF). assumption. }\n      (* Right rule is ImpR *)\n      { inversion H. subst. inversion X0. inversion X2. subst. clear X4. clear X6. rewrite <- H7 in D1.\n        assert (J1 : list_exch_L (Γ4 ++ A :: Γ5, Δ2 ++ B0 :: Δ3) (A :: Γ0 ++ A0 → B :: Γ1, Δ2 ++ B0 :: Δ3)).\n        assert (Γ4 ++ A :: Γ5 = [] ++ [] ++ Γ4 ++ [A] ++ Γ5). reflexivity. rewrite H0. clear H0.\n        assert (A :: Γ0 ++ A0 → B :: Γ1 = [] ++ [A] ++ Γ4 ++ [] ++ Γ5). rewrite <- H6. reflexivity.\n        rewrite H0. clear H0. apply list_exch_LI. pose (d:=GLS_adm_list_exch_L X5 J1). rewrite H2.\n        assert (ImpRRule [([] ++ A :: Γ0 ++ Γ1, Δ2 ++ B0 :: Δ3)] ([] ++ Γ0 ++ Γ1, Δ2 ++ A → B0 :: Δ3)). apply ImpRRule_I.\n        simpl in H0.\n        assert (J3: PSGLS_rules [(A :: Γ0 ++ Γ1, Δ2 ++ B0 :: Δ3)] (Γ0 ++ Γ1, Δ2 ++ A → B0 :: Δ3)).\n        apply PSImpR ; try intro ; try apply f ; try rewrite <- H7 ; try auto ; try assumption.\n        assert (J31: GLS_rules [(A :: Γ0 ++ Γ1, Δ2 ++ B0 :: Δ3)] (Γ0 ++ Γ1, Δ2 ++ A → B0 :: Δ3)).\n        apply ImpR ; try assumption.\n        assert (J21: In (A :: Γ0 ++ Γ1, Δ2 ++ B0 :: Δ3) [(A :: Γ0 ++ Γ1, Δ2 ++ B0 :: Δ3)]). apply in_eq.\n        pose (RA_mhd_decreases J3 _ J21). rewrite <- H7 in SIH.\n        assert (J5: size_form (A0 → B) = size_form (A0 → B)). reflexivity.\n        assert (J6: mhd (A :: Γ0 ++ Γ1, Δ2 ++ B0 :: Δ3) = mhd (A :: Γ0 ++ Γ1, Δ2 ++ B0 :: Δ3)). reflexivity.\n        assert (J7 : (A :: Γ0 ++ Γ1, Δ2 ++ B0 :: Δ3) = ((A :: Γ0) ++ Γ1, [] ++ Δ2 ++ B0 :: Δ3)). reflexivity.\n        pose (d0:=@SIH (mhd (A :: Γ0 ++ Γ1, Δ2 ++ B0 :: Δ3)) l (A0 → B) (A :: Γ0 ++ Γ1, Δ2 ++ B0 :: Δ3)\n        (A :: Γ0) Γ1 [] (Δ2 ++ B0 :: Δ3) J5 J6 J7). simpl in d0.\n        assert (J8 : list_exch_R (Γ0 ++ Γ1, Δ0 ++ A0 → B :: Δ1) (Γ0 ++ Γ1, A0 → B :: Δ2 ++ A → B0 :: Δ3)).\n        assert (Δ0 ++ A0 → B :: Δ1 = [] ++ [] ++ Δ0 ++ [A0 → B] ++ Δ1). reflexivity. rewrite H3. clear H3.\n        assert (A0 → B :: Δ2 ++ A → B0 :: Δ3 = [] ++ [A0 → B] ++ Δ0 ++ [] ++ Δ1). rewrite H7.\n        reflexivity. rewrite H3. clear H3. apply list_exch_RI. pose (d1:=GLS_adm_list_exch_R D0 J8).\n        assert (ImpRRule [([] ++ A :: Γ0 ++ Γ1, (A0 → B :: Δ2) ++ B0 :: Δ3)] ([] ++ Γ0 ++ Γ1, (A0 → B :: Δ2) ++ A → B0 :: Δ3)).\n        apply ImpRRule_I. simpl in H3. pose (d2:=ImpR_inv d1 H3). pose (d3:=d0 d2 d). pose (dlCons d3 DersNilF).\n        apply ImpR in H0 ; try intro ; try apply f ; try rewrite <- H7 ; try auto ; try assumption.\n        pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n        (ps:=[(A :: Γ0 ++ Γ1, Δ2 ++ B0 :: Δ3)]) (Γ0 ++ Γ1, Δ2 ++ A → B0 :: Δ3) H0 d4). assumption. }\n      (* Right rule is ImpL *)\n      { inversion H. subst. inversion X0. inversion X2. subst. clear X4. inversion X6. subst. clear X7.\n        clear X6. apply list_split_form in H6. destruct H6.\n        - destruct s.\n          * repeat destruct p. inversion e0. subst. rewrite H2.\n            assert (J1 : list_exch_L (Γ2 ++ A0 :: Γ3, Δ0 ++ B :: Δ1) (A0 :: Γ0 ++ Γ1, Δ0 ++ B :: Δ1)).\n            assert (Γ2 ++ A0 :: Γ3 = [] ++ [] ++ Γ2 ++ [A0] ++ Γ3). reflexivity. rewrite H0. clear H0.\n            assert (A0 :: Γ0 ++ Γ1 = [] ++ [A0] ++ Γ2 ++ [] ++ Γ3). rewrite <- H2. reflexivity.\n            rewrite H0. clear H0. apply list_exch_LI. pose (d:=GLS_adm_list_exch_L X3 J1).\n            assert (J2 : list_exch_R (A0 :: Γ0 ++ Γ1, Δ0 ++ B :: Δ1) (A0 :: Γ0 ++ Γ1, B :: Δ2 ++ Δ3)).\n            assert (Δ0 ++ B :: Δ1 = [] ++ [] ++ Δ0 ++ [B] ++ Δ1). reflexivity. rewrite H0. clear H0.\n            assert (B :: Δ2 ++ Δ3 = [] ++ [B] ++ Δ0 ++ [] ++ Δ1). rewrite H7. reflexivity. rewrite H0. clear H0.\n            apply list_exch_RI. pose (d0:=GLS_adm_list_exch_R d J2).\n            assert (J3: size_form A0 < size_form (A0 → B)). simpl. lia.\n            assert (J4: size_form A0 = size_form A0). reflexivity.\n            assert (J5: mhd (Γ2 ++ Γ3, B :: Δ2 ++ Δ3) = mhd (Γ2 ++ Γ3, B :: Δ2 ++ Δ3)). reflexivity.\n            assert (J6: (Γ2 ++ Γ3, B :: Δ2 ++ Δ3) = ([] ++ Γ2 ++ Γ3, (B :: Δ2) ++ Δ3)). reflexivity.\n            pose (d1:=PIH _ J3 (mhd (Γ2 ++ Γ3, B :: Δ2 ++ Δ3)) A0 (Γ2 ++ Γ3, B :: Δ2 ++ Δ3) [] (Γ2 ++ Γ3)\n            (B :: Δ2) Δ3 J4 J5 J6). simpl in d1.\n            assert (J7 : wkn_R B (Γ2 ++ Γ3, Δ2 ++ A0 :: Δ3) (Γ2 ++ Γ3, B :: Δ2 ++ A0 :: Δ3)).\n            assert ((Γ2 ++ Γ3, Δ2 ++ A0 :: Δ3) = (Γ2 ++ Γ3, [] ++ Δ2 ++ A0 :: Δ3)). reflexivity. rewrite H0. clear H0.\n            assert ((Γ2 ++ Γ3, B :: Δ2 ++ A0 :: Δ3) = (Γ2 ++ Γ3, [] ++ B :: Δ2 ++ A0 :: Δ3)).\n            reflexivity. rewrite H0. clear H0. apply wkn_RI. rewrite <- H2 in X5.\n            assert (J8 : derrec_height X5 = derrec_height X5).\n            reflexivity. pose (GLS_wkn_R X5 J8 J7). destruct s. rewrite <- H2 in d0. pose (d2:=d1 x d0).\n            assert (J9: size_form B < size_form (A0 → B)). simpl. lia.\n            assert (J10: size_form B = size_form B). reflexivity.\n            assert (J11: mhd (Γ2 ++ Γ3, Δ2 ++ Δ3) = mhd (Γ2 ++ Γ3, Δ2 ++ Δ3)). reflexivity.\n            assert (J12: (Γ2 ++ Γ3, Δ2 ++ Δ3) = (Γ2 ++ Γ3, [] ++ Δ2 ++ Δ3)). reflexivity.\n            pose (d3:=PIH _ J9 (mhd (Γ2 ++ Γ3, Δ2 ++ Δ3)) B (Γ2 ++ Γ3, Δ2 ++ Δ3) Γ2 Γ3\n            [] (Δ2 ++ Δ3) J10 J11 J12). simpl in d3.\n            assert (J30 : list_exch_L (Γ0 ++ B :: Γ1, Δ2 ++ Δ3) (B :: Γ2 ++ Γ3, Δ2 ++ Δ3)).\n            assert (Γ0 ++ B :: Γ1 = [] ++ [] ++ Γ0 ++ [B] ++ Γ1). reflexivity. rewrite H0. clear H0.\n            assert (B :: Γ2 ++ Γ3 = [] ++ [B] ++ Γ0 ++ [] ++ Γ1). rewrite H2. reflexivity.\n            rewrite H0. clear H0. apply list_exch_LI. pose (d4:=GLS_adm_list_exch_L X4 J30).\n            assert (J40 : list_exch_L (B :: Γ2 ++ Γ3, Δ2 ++ Δ3) (Γ2 ++ B :: Γ3, Δ2 ++ Δ3)).\n            assert (Γ2 ++ B :: Γ3 = [] ++ [] ++ Γ2 ++ [B] ++ Γ3). reflexivity. rewrite H0. clear H0.\n            assert (B :: Γ2 ++ Γ3 = [] ++ [B] ++ Γ2 ++ [] ++ Γ3). reflexivity. rewrite H0. clear H0.\n            apply list_exch_LI. pose (d5:=GLS_adm_list_exch_L d4 J40). pose (d3 d2 d5). rewrite <- H2. assumption.\n          * repeat destruct s. repeat destruct p. subst. rewrite H2. repeat rewrite <- app_assoc in X5. repeat rewrite <- app_assoc in X4.\n            simpl in X4. simpl in X5.\n            assert (J1 : list_exch_R (Γ0 ++ x0 ++ A → B0 :: Γ5, Δ0 ++ A0 → B :: Δ1) (Γ0 ++ x0 ++ A → B0 :: Γ5, A0 → B :: Δ2 ++ Δ3)).\n            assert (Δ0 ++ A0 → B :: Δ1 = [] ++ [] ++ Δ0 ++ [A0 → B] ++ Δ1). reflexivity. rewrite H0. clear H0.\n            assert (A0 → B :: Δ2 ++ Δ3 = [] ++ [A0 → B] ++ Δ0 ++ [] ++ Δ1). rewrite H7. reflexivity. rewrite H0. clear H0. apply list_exch_RI.\n            pose (d:=GLS_adm_list_exch_R D0 J1).\n            assert (ImpLRule [((Γ0 ++ x0) ++ Γ5, Δ2 ++ A :: Δ3); ((Γ0 ++ x0) ++ B0 :: Γ5, Δ2 ++ Δ3)] ((Γ0 ++ x0) ++ A → B0 :: Γ5, Δ2 ++ Δ3)).\n            apply ImpLRule_I. simpl in H0. repeat rewrite <- app_assoc in H0.\n            assert (J3: PSGLS_rules [(Γ0 ++ x0 ++ Γ5, Δ2 ++ A :: Δ3); (Γ0 ++ x0 ++ B0 :: Γ5, Δ2 ++ Δ3)] (Γ0 ++ x0 ++ A → B0 :: Γ5, Δ2 ++ Δ3)).\n            apply PSImpL ; try intro ; try apply f ; try rewrite <- H7 ; try repeat rewrite <- app_assoc ; try auto ; try assumption.\n            assert (J21: In (Γ0 ++ x0 ++ Γ5, Δ2 ++ A :: Δ3) [(Γ0 ++ x0 ++ Γ5, Δ2 ++ A :: Δ3); (Γ0 ++ x0 ++ B0 :: Γ5, Δ2 ++ Δ3)]). apply in_eq.\n            pose (RA_mhd_decreases J3 _ J21). rewrite <- H7 in SIH.\n            assert (J5: size_form (A0 → B) = size_form (A0 → B)). reflexivity.\n            assert (J6: mhd (Γ0 ++ x0 ++ Γ5, Δ2 ++ A :: Δ3) = mhd (Γ0 ++ x0 ++ Γ5, Δ2 ++ A :: Δ3)). reflexivity.\n            assert (J7 : (Γ0 ++ x0 ++ Γ5, Δ2 ++ A :: Δ3) = (Γ0 ++ x0 ++ Γ5, [] ++ Δ2 ++ A :: Δ3)). reflexivity.\n            pose (d0:=@SIH (mhd (Γ0 ++ x0 ++ Γ5, Δ2 ++ A :: Δ3)) l (A0 → B) (Γ0 ++ x0 ++ Γ5, Δ2 ++ A :: Δ3)\n            Γ0 (x0 ++ Γ5) [] (Δ2 ++ A :: Δ3) J5 J6 J7). simpl in d0.\n            assert (J22: In (Γ0 ++ x0 ++ B0 :: Γ5, Δ2 ++ Δ3) [(Γ0 ++ x0 ++ Γ5, Δ2 ++ A :: Δ3); (Γ0 ++ x0 ++ B0 :: Γ5, Δ2 ++ Δ3)]).\n            apply in_cons. apply in_eq. pose (RA_mhd_decreases J3 _ J22).\n            assert (J8: size_form (A0 → B) = size_form (A0 → B)). reflexivity.\n            assert (J9: mhd (Γ0 ++ x0 ++ B0 :: Γ5, Δ2 ++ Δ3) = mhd (Γ0 ++ x0 ++ B0 :: Γ5, Δ2 ++ Δ3)). reflexivity.\n            assert (J10: (Γ0 ++ x0 ++ B0 :: Γ5, Δ2 ++ Δ3) = (Γ0 ++ x0 ++ B0 :: Γ5, [] ++ Δ2 ++ Δ3)). reflexivity.\n            pose (d1:=@SIH (mhd (Γ0 ++ x0 ++ B0 :: Γ5, Δ2 ++ Δ3)) l0 (A0 → B) (Γ0 ++ x0 ++ B0 :: Γ5, Δ2 ++ Δ3)\n            Γ0 (x0 ++ B0 :: Γ5) [] (Δ2 ++ Δ3) J8 J9 J10). simpl in d1.\n            assert (ImpLRule [((Γ0 ++ x0) ++ Γ5, (A0 → B :: Δ2) ++ A :: Δ3); ((Γ0 ++ x0) ++ B0 :: Γ5, (A0 → B :: Δ2) ++ Δ3)] ((Γ0 ++ x0) ++ A → B0 :: Γ5, (A0 → B :: Δ2) ++ Δ3)).\n            apply ImpLRule_I. repeat rewrite <- app_assoc in H3. pose (ImpL_inv d H3). destruct p as [d2 d3].\n            pose (d4:=d0 d2 X5). pose (d5:=d1 d3 X4). apply ImpL in H0 ; try intro ; try apply f ; try repeat rewrite <- app_assoc ; try rewrite <- H7 ;\n            try repeat rewrite app_nil_r ; try auto ; try assumption. pose (dlCons d5 DersNilF). pose (dlCons d4 d6).\n            pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n            (ps:=[(Γ0 ++ x0 ++ Γ5, Δ2 ++ A :: Δ3); (Γ0 ++ x0 ++ B0 :: Γ5, Δ2 ++ Δ3)]) (Γ0 ++ x0 ++ A → B0 :: Γ5, Δ2 ++ Δ3) H0 d7).\n            assumption.\n        - repeat destruct s. repeat destruct p. subst. rewrite H2. rewrite <- app_assoc. rewrite <- app_assoc in D0.\n          assert (J1 : list_exch_R (Γ4 ++ (A → B0 :: x) ++ Γ1, Δ0 ++ A0 → B :: Δ1) (Γ4 ++ (A → B0 :: x) ++ Γ1, A0 → B :: Δ2 ++ Δ3)).\n          assert (Δ0 ++ A0 → B :: Δ1 = [] ++ [] ++ Δ0 ++ [A0 → B] ++ Δ1). reflexivity. rewrite H0. clear H0.\n          assert (A0 → B :: Δ2 ++ Δ3 = [] ++ [A0 → B] ++ Δ0 ++ [] ++ Δ1). rewrite H7. reflexivity. rewrite H0. clear H0. apply list_exch_RI.\n          pose (d:=GLS_adm_list_exch_R D0 J1).\n          assert (ImpLRule [(Γ4 ++ x ++ Γ1, Δ2 ++ A :: Δ3); (Γ4 ++ (B0 :: x) ++ Γ1, Δ2 ++ Δ3)] (Γ4 ++ (A → B0 :: x) ++ Γ1, Δ2 ++ Δ3)).\n          apply ImpLRule_I. simpl in H0.\n          assert (J3: PSGLS_rules [(Γ4 ++ x ++ Γ1, Δ2 ++ A :: Δ3); (Γ4 ++ B0 :: x ++ Γ1, Δ2 ++ Δ3)] (Γ4 ++ A → B0 :: x ++ Γ1, Δ2 ++ Δ3)).\n          apply PSImpL ; try intro ; try apply f ; try rewrite <- H7 ; try repeat rewrite <- app_assoc ; try auto ; try assumption.\n          assert (J21: In (Γ4 ++ x ++ Γ1, Δ2 ++ A :: Δ3) [(Γ4 ++ x ++ Γ1, Δ2 ++ A :: Δ3); (Γ4 ++ B0 :: x ++ Γ1, Δ2 ++ Δ3)]). apply in_eq.\n          pose (RA_mhd_decreases J3 _ J21). rewrite <- H7 in SIH. rewrite <- app_assoc in SIH.\n          assert (J5: size_form (A0 → B) = size_form (A0 → B)). reflexivity.\n          assert (J6: mhd (Γ4 ++ x ++ Γ1, Δ2 ++ A :: Δ3) = mhd (Γ4 ++ x ++ Γ1, Δ2 ++ A :: Δ3)). reflexivity.\n          assert (J7 : (Γ4 ++ x ++ Γ1, Δ2 ++ A :: Δ3) = ((Γ4 ++ x) ++ Γ1, [] ++ Δ2 ++ A :: Δ3)). rewrite <- app_assoc. reflexivity.\n          pose (d0:=@SIH (mhd (Γ4 ++ x ++ Γ1, Δ2 ++ A :: Δ3)) l (A0 → B) (Γ4 ++ x ++ Γ1, Δ2 ++ A :: Δ3)\n          (Γ4 ++ x) Γ1 [] (Δ2 ++ A :: Δ3) J5 J6 J7). simpl in d0. repeat rewrite <- app_assoc in d0.\n          assert (J22: In (Γ4 ++ B0 :: x ++ Γ1, Δ2 ++ Δ3) [(Γ4 ++ x ++ Γ1, Δ2 ++ A :: Δ3); (Γ4 ++ B0 :: x ++ Γ1, Δ2 ++ Δ3)]).\n          apply in_cons. apply in_eq. pose (RA_mhd_decreases J3 _ J22).\n          assert (J8: size_form (A0 → B) = size_form (A0 → B)). reflexivity.\n          assert (J9: mhd (Γ4 ++ B0 :: x ++ Γ1, Δ2 ++ Δ3) = mhd (Γ4 ++ B0 :: x ++ Γ1, Δ2 ++ Δ3)). reflexivity.\n          assert (J10: (Γ4 ++ B0 :: x ++ Γ1, Δ2 ++ Δ3) = ((Γ4 ++ B0 :: x) ++ Γ1, [] ++ Δ2 ++ Δ3)). rewrite <- app_assoc. reflexivity.\n          pose (d1:=@SIH (mhd (Γ4 ++ B0 :: x ++ Γ1, Δ2 ++ Δ3)) l0 (A0 → B) (Γ4 ++ B0 :: x ++ Γ1, Δ2 ++ Δ3)\n          (Γ4 ++ B0 :: x) Γ1 [] (Δ2 ++ Δ3) J8 J9 J10). simpl in d1.\n          assert (ImpLRule [(Γ4 ++ x ++ Γ1, (A0 → B :: Δ2) ++ A :: Δ3); (Γ4 ++ (B0 :: x) ++ Γ1, (A0 → B :: Δ2) ++ Δ3)] (Γ4 ++ (A → B0 :: x) ++ Γ1, (A0 → B :: Δ2) ++ Δ3)).\n          apply ImpLRule_I. repeat rewrite <- app_assoc in H3. pose (ImpL_inv d H3). destruct p as [d2 d3].\n          pose (d4:=d0 d2 X5). repeat rewrite <- app_assoc in d1. pose (d5:=d1 d3 X4). apply ImpL in H0 ; try intro ; try apply f ; try repeat rewrite <- app_assoc ; try rewrite <- H7 ;\n          try repeat rewrite app_nil_r ; try auto ; try assumption. pose (dlCons d5 DersNilF). pose (dlCons d4 d6).\n          pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n          (ps:=[(Γ4 ++ x ++ Γ1, Δ2 ++ A :: Δ3); (Γ4 ++ B0 :: x ++ Γ1, Δ2 ++ Δ3)]) (Γ4 ++ (A → B0 :: x) ++ Γ1, Δ2 ++ Δ3) H0 d7).\n          assumption. }\n      (* Right rule is GLR *)\n      { inversion X3. subst. rewrite H2.\n        assert (GLRRule [(XBoxed_list BΓ ++ [Box A], [A])] (Γ0 ++ Γ1, Δ2 ++ Box A :: Δ3)).\n        apply GLRRule_I ; try assumption.\n        apply univ_gen_ext_splitR in X4. destruct X4. destruct s. repeat destruct p. subst.\n        apply univ_gen_ext_combine. assumption. apply univ_gen_ext_not_In_delete in u0. assumption.\n        intro. assert (In (A0 → B) (x ++ x0)). apply in_or_app. auto. apply H5 in H0. destruct H0.\n        inversion H0. apply GLR in X5.\n        pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n        (ps:=[(XBoxed_list BΓ ++ [Box A], [A])]) (Γ0 ++ Γ1, Δ2 ++ Box A :: Δ3) X5 X2).\n        assumption. }\n    + repeat destruct s. repeat destruct p. subst.\n      assert (J5 : list_exch_L (Γ0 ++ A :: Γ1, Δ0 ++ x0 ++ A0 → B :: Δ3) (A :: Γ2 ++ Γ3, Δ0 ++ x0 ++ A0 → B :: Δ3)).\n      rewrite H2. assert (Γ0 ++ A :: Γ1 = [] ++ [] ++ Γ0 ++ [A] ++ Γ1). reflexivity. rewrite H. clear H.\n      assert (A :: Γ0 ++ Γ1 = [] ++ [A] ++ Γ0 ++ [] ++ Γ1). reflexivity. rewrite H. clear H.\n      apply list_exch_LI. pose (d:=GLS_adm_list_exch_L D1 J5).\n      assert (ImpRRule [((A :: Γ2) ++ A0 :: Γ3, (Δ0 ++ x0) ++ B :: Δ3)] ((A :: Γ2) ++ Γ3, (Δ0 ++ x0) ++ A0 → B :: Δ3)).\n      apply ImpRRule_I. repeat rewrite <- app_assoc in H. pose (d0:=ImpR_inv d H).\n      assert (ImpRRule [(Γ2 ++ A0 :: Γ3, (Δ0 ++ x0) ++ B :: Δ3)] (Γ2 ++ Γ3, (Δ0 ++ x0) ++ A0 → B :: Δ3)).\n      apply ImpRRule_I. repeat rewrite <- app_assoc in H0.\n      assert (PSGLS_rules [(Γ2 ++ A0 :: Γ3, Δ0 ++ x0 ++ B :: Δ3)] (Γ2 ++ Γ3, Δ0 ++ x0 ++ A0 → B :: Δ3)).\n      apply PSImpR ; try intro ; try apply f ; try rewrite <- H2 ; try rewrite <- app_assoc ; try auto ; try assumption.\n      assert (GLS_rules [(Γ2 ++ A0 :: Γ3, Δ0 ++ x0 ++ B :: Δ3)] (Γ2 ++ Γ3, Δ0 ++ x0 ++ A0 → B :: Δ3)).\n      apply ImpR. assumption.\n      assert (J21: In (Γ2 ++ A0 :: Γ3, Δ0 ++ x0 ++ B :: Δ3) [(Γ2 ++ A0 :: Γ3, Δ0 ++ x0 ++ B :: Δ3)]). apply in_eq.\n      pose (RA_mhd_decreases X3 (Γ2 ++ A0 :: Γ3, Δ0 ++ x0 ++ B :: Δ3) J21).\n      assert (J2 : mhd (Γ2 ++ A0 :: Γ3, Δ0 ++ x0 ++ B :: Δ3) = mhd (Γ2 ++ A0 :: Γ3, Δ0 ++ x0 ++ B :: Δ3)). reflexivity.\n      assert (J3 : size_form A = size_form A). reflexivity.\n      assert (J4 : (Γ2 ++ A0 :: Γ3, Δ0 ++ x0 ++ B :: Δ3) = ([] ++ Γ2 ++ A0 :: Γ3, Δ0 ++ x0 ++ B :: Δ3)).\n      repeat rewrite <- app_assoc. reflexivity. rewrite <- H2 in SIH.\n      pose (d1:=@SIH (mhd (Γ2 ++ A0 :: Γ3, Δ0 ++ x0 ++ B :: Δ3)) l A (Γ2 ++ A0 :: Γ3, Δ0 ++ x0 ++ B :: Δ3)\n      [] (Γ2 ++ A0 :: Γ3) Δ0 (x0 ++ B :: Δ3) J3 J2 J4). repeat rewrite <- app_assoc in d1. simpl in d1.\n      inversion X0. subst. clear X6. repeat rewrite <- app_assoc in X5. pose (d2:=d1 X5 d0). pose (dlCons d2 DersNilF).\n      pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n      (ps:=[(Γ2 ++ A0 :: Γ3, Δ0 ++ x0 ++ B :: Δ3)]) (Γ2 ++ Γ3, Δ0 ++ x0 ++ A0 → B :: Δ3) X4 d3). assumption.\n  * repeat destruct s. repeat destruct p. subst. repeat rewrite <- app_assoc. repeat rewrite <- app_assoc in D1.\n    assert (J5 : list_exch_L (Γ0 ++ A :: Γ1, Δ2 ++ (A0 → B :: x) ++ Δ1) (A :: Γ2 ++ Γ3, Δ2 ++ (A0 → B :: x) ++ Δ1)).\n    assert (Γ0 ++ A :: Γ1 = [] ++ [] ++ Γ0 ++ [A] ++ Γ1). reflexivity. rewrite H. clear H.\n    assert (A :: Γ2 ++ Γ3 = [] ++ [A] ++ Γ0 ++ [] ++ Γ1). rewrite H2. reflexivity. rewrite H. clear H.\n    apply list_exch_LI. pose (d:=GLS_adm_list_exch_L D1 J5).\n    assert (ImpRRule [((A :: Γ2) ++ A0 :: Γ3, Δ2 ++ B :: x ++ Δ1)] ((A :: Γ2) ++ Γ3, Δ2 ++ (A0 → B :: x) ++ Δ1)).\n    apply ImpRRule_I. repeat rewrite <- app_assoc in H. pose (d0:=ImpR_inv d H).\n    assert (ImpRRule [(Γ2 ++ A0 :: Γ3, Δ2 ++ (B :: x) ++ Δ1)] (Γ2 ++ Γ3, Δ2 ++ (A0 → B :: x) ++ Δ1)).\n    apply ImpRRule_I.\n    assert (PSGLS_rules [(Γ2 ++ A0 :: Γ3, Δ2 ++ (B :: x) ++ Δ1)] (Γ2 ++ Γ3, Δ2 ++ (A0 → B :: x) ++ Δ1)).\n    apply PSImpR ; try intro ; try apply f ; try repeat rewrite <- app_assoc ; try rewrite <- H2 ; try auto ; try assumption.\n    assert (GLS_rules [(Γ2 ++ A0 :: Γ3, Δ2 ++ (B :: x) ++ Δ1)] (Γ2 ++ Γ3, Δ2 ++ (A0 → B :: x) ++ Δ1)).\n    apply ImpR ; try assumption.\n    assert (J21: In (Γ2 ++ A0 :: Γ3, Δ2 ++ (B :: x) ++ Δ1) [(Γ2 ++ A0 :: Γ3, Δ2 ++ (B :: x) ++ Δ1)]). apply in_eq.\n    pose (RA_mhd_decreases X3 (Γ2 ++ A0 :: Γ3, Δ2 ++ (B :: x) ++ Δ1) J21). rewrite <- H2 in SIH.\n    assert (J2 : mhd (Γ2 ++ A0 :: Γ3, Δ2 ++ (B :: x) ++ Δ1) = mhd (Γ2 ++ A0 :: Γ3, Δ2 ++ (B :: x) ++ Δ1)).\n    repeat rewrite <- app_assoc. reflexivity.\n    assert (J3 : size_form A = size_form A). reflexivity.\n    assert (J4 : (Γ2 ++ A0 :: Γ3, Δ2 ++ (B :: x) ++ Δ1) = ([] ++ Γ2 ++ A0 :: Γ3, (Δ2 ++ B :: x) ++ Δ1)).\n    repeat rewrite <- app_assoc. reflexivity. repeat rewrite <- app_assoc in SIH.\n    pose (d1:=@SIH (mhd (Γ2 ++ A0 :: Γ3, Δ2 ++ (B :: x) ++ Δ1)) l A (Γ2 ++ A0 :: Γ3, Δ2 ++ (B :: x) ++ Δ1)\n    [] (Γ2 ++ A0 :: Γ3) (Δ2 ++ (B :: x)) Δ1 J3 J2 J4). simpl in d1. repeat rewrite <- app_assoc in d1.\n    inversion X0. subst. pose (d2:=d1 X5 d0). pose (dlCons d2 DersNilF).\n    pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n    (ps:=[(Γ2 ++ A0 :: Γ3, Δ2 ++ (B :: x) ++ Δ1)]) (Γ2 ++ Γ3, Δ2 ++ (A0 → B :: x) ++ Δ1) X4 d3). assumption.\n\n(* Left rule is ImpL *)\n- inversion H1. subst. inversion X0. inversion X4. subst. clear X6. clear X4.\n  assert (J5 : list_exch_L (Γ0 ++ A :: Γ1, Δ0 ++ Δ1) (A :: Γ2 ++ A0 → B :: Γ3, Δ0 ++ Δ1)).\n  rewrite H2. assert (Γ0 ++ A :: Γ1 = [] ++ [] ++ Γ0 ++ [A] ++ Γ1).\n  reflexivity. rewrite H. clear H.\n  assert (A :: Γ0 ++ Γ1 = [] ++ [A] ++ Γ0 ++ [] ++ Γ1). reflexivity. rewrite H. clear H.\n  apply list_exch_LI. pose (d:=GLS_adm_list_exch_L D1 J5). rewrite H3 in X5.\n  assert (J40 : list_exch_R (Γ2 ++ Γ3, Δ2 ++ A0 :: Δ3) (Γ2 ++ Γ3, A0 :: Δ0 ++ A :: Δ1)).\n  rewrite <- H3. assert (Δ2 ++ A0 :: Δ3 = [] ++ [] ++ Δ2 ++ [A0] ++ Δ3).\n  reflexivity. rewrite H. clear H.\n  assert (A0 :: Δ2 ++ Δ3 = [] ++ [A0] ++ Δ2 ++ [] ++ Δ3). reflexivity. rewrite H. clear H.\n  apply list_exch_RI. pose (d0:=GLS_adm_list_exch_R X3 J40).\n  assert (ImpLRule [(A :: Γ2 ++ Γ3, [] ++ A0 :: Δ0 ++ Δ1); (A :: Γ2 ++ B :: Γ3, [] ++ Δ0 ++ Δ1)] (A :: Γ2 ++ A0 → B :: Γ3, [] ++ Δ0 ++ Δ1)).\n  assert ((A :: Γ2 ++ A0 → B :: Γ3, [] ++ Δ0 ++ Δ1) = ((A :: Γ2) ++ A0 → B :: Γ3, [] ++ Δ0 ++ Δ1)). reflexivity.\n  rewrite H. clear H.\n  assert ((A :: Γ2 ++ Γ3, [] ++ A0 :: Δ0 ++ Δ1) = ((A :: Γ2) ++ Γ3, [] ++ A0 :: Δ0 ++ Δ1)). reflexivity.\n  rewrite H. clear H.\n  assert ((A :: Γ2 ++ B :: Γ3, [] ++ Δ0 ++ Δ1) = ((A :: Γ2) ++ B :: Γ3, [] ++ Δ0 ++ Δ1)). reflexivity.\n  rewrite H. clear H. apply ImpLRule_I. simpl in H. pose (ImpL_inv d H). destruct p as [d1 d2].\n  assert (ImpLRule [(Γ2 ++ Γ3, [] ++ A0 :: Δ0 ++ Δ1); (Γ2 ++ B :: Γ3, [] ++ Δ0 ++ Δ1)] (Γ2 ++ A0 → B :: Γ3, [] ++ Δ0 ++ Δ1)).\n  apply ImpLRule_I. simpl in H0.\n  assert (PSGLS_rules [(Γ2 ++ Γ3, A0 :: Δ0 ++ Δ1); (Γ2 ++ B :: Γ3, Δ0 ++ Δ1)] (Γ2 ++ A0 → B :: Γ3, Δ0 ++ Δ1)).\n  apply PSImpL ; try intro ; try apply f ; try rewrite <- H2 ; try rewrite <- app_assoc ; try auto ; try assumption.\n  assert (GLS_rules [(Γ2 ++ Γ3, A0 :: Δ0 ++ Δ1); (Γ2 ++ B :: Γ3, Δ0 ++ Δ1)] (Γ2 ++ A0 → B :: Γ3, Δ0 ++ Δ1)).\n  apply ImpL. assumption.\n  assert (J21: In (Γ2 ++ Γ3, A0 :: Δ0 ++ Δ1) [(Γ2 ++ Γ3, A0 :: Δ0 ++ Δ1); (Γ2 ++ B :: Γ3, Δ0 ++ Δ1)]).\n  apply in_eq. pose (RA_mhd_decreases X4 (Γ2 ++ Γ3, A0 :: Δ0 ++ Δ1) J21).\n  assert (J2 : mhd (Γ2 ++ Γ3, A0 :: Δ0 ++ Δ1) = mhd (Γ2 ++ Γ3, A0 :: Δ0 ++ Δ1)). reflexivity.\n  assert (J3 : size_form A = size_form A). reflexivity.\n  assert (J4 : (Γ2 ++ Γ3, A0 :: Δ0 ++ Δ1) = ([] ++ Γ2 ++ Γ3, (A0 :: Δ0) ++ Δ1)).\n  repeat rewrite <- app_assoc. reflexivity. rewrite <- H2 in SIH.\n  pose (d3:=@SIH (mhd (Γ2 ++ Γ3, A0 :: Δ0 ++ Δ1)) l A (Γ2 ++ Γ3, A0 :: Δ0 ++ Δ1)\n  [] (Γ2 ++ Γ3) (A0 :: Δ0) Δ1 J3 J2 J4). repeat rewrite <- app_assoc in d3. simpl in d3.\n  pose (d4:=d3 d0 d1).\n  assert (J31: In (Γ2 ++ B :: Γ3, Δ0 ++ Δ1) [(Γ2 ++ Γ3, A0 :: Δ0 ++ Δ1); (Γ2 ++ B :: Γ3, Δ0 ++ Δ1)]).\n  apply in_cons. apply in_eq. pose (RA_mhd_decreases X4 (Γ2 ++ B :: Γ3, Δ0 ++ Δ1) J31).\n  assert (J32 : mhd (Γ2 ++ B :: Γ3, Δ0 ++ Δ1) = mhd (Γ2 ++ B :: Γ3, Δ0 ++ Δ1)). reflexivity.\n  assert (J33 : size_form A = size_form A). reflexivity.\n  assert (J34 : (Γ2 ++ B :: Γ3, Δ0 ++ Δ1) = ([] ++ Γ2 ++ B :: Γ3, Δ0 ++ Δ1)).\n  repeat rewrite <- app_assoc. reflexivity.\n  pose (d5:=@SIH (mhd (Γ2 ++ B :: Γ3, Δ0 ++ Δ1)) l0 A (Γ2 ++ B :: Γ3, Δ0 ++ Δ1)\n  [] (Γ2 ++ B :: Γ3) Δ0 Δ1 J33 J32 J34). repeat rewrite <- app_assoc in d5. simpl in d5.\n  pose (d6:=d5 X5 d2). pose (dlCons d6 DersNilF). pose (dlCons d4 d7).\n  pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n  (ps:=[(Γ2 ++ Γ3, A0 :: Δ0 ++ Δ1); (Γ2 ++ B :: Γ3, Δ0 ++ Δ1)]) (Γ2 ++ A0 → B :: Γ3, Δ0 ++ Δ1) X6 d8). assumption.\n\n(* Left rule is GLR *)\n- inversion X3. subst. apply list_split_form in H2. destruct H2.\n  * destruct s.\n    + repeat destruct p. subst. inversion X1.\n      (* Right rule is IdP *)\n      { inversion H. subst. assert (J0 : InT (# P) (Γ0 ++ Box A0 :: Γ1)). rewrite <- H5. apply InT_or_app.\n        right. apply InT_eq. apply InT_app_or in J0. destruct J0.\n        - apply InT_split in i. destruct i. destruct s. subst. rewrite <- app_assoc.\n          assert (IdPRule [] (x ++ (# P :: x0) ++ Γ1, Δ2 ++ # P :: Δ3)). apply IdPRule_I. apply IdP in H0.\n          pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n          (ps:=[]) (x ++ (# P :: x0) ++ Γ1, Δ2 ++ # P :: Δ3) H0 DersNilF). assumption.\n        - inversion i.\n          * inversion H2.\n          * apply InT_split in H2. destruct H2. destruct s. subst. rewrite app_assoc.\n            assert (IdPRule [] ((Γ0 ++ x) ++ # P :: x0, Δ2 ++ # P :: Δ3)). apply IdPRule_I. apply IdP in H0.\n            pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n            (ps:=[]) ((Γ0 ++ x) ++ # P :: x0, Δ2 ++ # P :: Δ3) H0 DersNilF). assumption. }\n      (* Right rule is BotL *)\n      { inversion H. subst. assert (J0 : InT (⊥) (Γ0 ++ Box A0 :: Γ1)). rewrite <- H5. apply InT_or_app.\n        right. apply InT_eq. apply InT_app_or in J0. destruct J0.\n        - apply InT_split in i. destruct i. destruct s. subst. rewrite <- app_assoc.\n          assert (BotLRule [] (x ++ (⊥ :: x0) ++ Γ1, Δ0 ++ Δ1)). apply BotLRule_I. apply BotL in H0.\n          pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n          (ps:=[]) (x ++ (⊥ :: x0) ++ Γ1, Δ0 ++ Δ1) H0 DersNilF). assumption.\n        - inversion i.\n          * inversion H2.\n          * apply InT_split in H2. destruct H2. destruct s. subst. rewrite app_assoc.\n            assert (BotLRule [] ((Γ0 ++ x) ++ ⊥ :: x0, Δ0 ++ Δ1)). apply BotLRule_I. apply BotL in H0.\n            pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n            (ps:=[]) ((Γ0 ++ x) ++ ⊥ :: x0, Δ0 ++ Δ1) H0 DersNilF). assumption. }\n      (* Right rule is ImpR *)\n      { inversion H. subst. inversion X2. subst. clear X6. rewrite <- H6 in D1.\n        assert (J1 : list_exch_L (Γ2 ++ A :: Γ3, Δ2 ++ B :: Δ3) (A :: Γ0 ++ Box A0 :: Γ1, Δ2 ++ B :: Δ3)).\n        assert (Γ2 ++ A :: Γ3 = [] ++ [] ++ Γ2 ++ [A] ++ Γ3). reflexivity. rewrite H0. clear H0.\n        assert (A :: Γ0 ++ Box A0 :: Γ1 = [] ++ [A] ++ Γ2 ++ [] ++ Γ3). rewrite <- H5. reflexivity.\n        rewrite H0. clear H0. apply list_exch_LI. pose (d:=GLS_adm_list_exch_L X5 J1).\n        assert (ImpRRule [([] ++ A :: Γ0 ++ Γ1, Δ2 ++ B :: Δ3)] ([] ++ Γ0 ++ Γ1, Δ2 ++ A → B :: Δ3)). apply ImpRRule_I.\n        simpl in H0.\n        assert (J3: PSGLS_rules [(A :: Γ0 ++ Γ1, Δ2 ++ B :: Δ3)] (Γ0 ++ Γ1, Δ2 ++ A → B :: Δ3)).\n        apply PSImpR ; try intro ; try apply f ; try rewrite <- H6 ; try auto ; try assumption.\n        assert (J31: GLS_rules [(A :: Γ0 ++ Γ1, Δ2 ++ B :: Δ3)] (Γ0 ++ Γ1, Δ2 ++ A → B :: Δ3)).\n        apply ImpR ; try assumption.\n        assert (J21: In (A :: Γ0 ++ Γ1, Δ2 ++ B :: Δ3) [(A :: Γ0 ++ Γ1, Δ2 ++ B :: Δ3)]). apply in_eq.\n        pose (RA_mhd_decreases J3 _ J21). rewrite <- H6 in SIH.\n        assert (J5: size_form (Box A0) = size_form (Box A0)). reflexivity.\n        assert (J6: mhd (A :: Γ0 ++ Γ1, Δ2 ++ B :: Δ3) = mhd (A :: Γ0 ++ Γ1, Δ2 ++ B :: Δ3)). reflexivity.\n        assert (J7 : (A :: Γ0 ++ Γ1, Δ2 ++ B :: Δ3) = ((A :: Γ0) ++ Γ1, [] ++ Δ2 ++ B :: Δ3)). reflexivity.\n        pose (d0:=@SIH (mhd (A :: Γ0 ++ Γ1, Δ2 ++ B :: Δ3)) l (Box A0) (A :: Γ0 ++ Γ1, Δ2 ++ B :: Δ3)\n        (A :: Γ0) Γ1 [] (Δ2 ++ B :: Δ3) J5 J6 J7). simpl in d0.\n        assert (J8 : list_exch_R (Γ0 ++ Γ1, Δ0 ++ Box A0 :: Δ1) (Γ0 ++ Γ1, Box A0 :: Δ2 ++ A → B :: Δ3)).\n        assert (Δ0 ++ Box A0 :: Δ1 = [] ++ [] ++ Δ0 ++ [Box A0] ++ Δ1). reflexivity. rewrite H2. clear H2.\n        assert (Box A0 :: Δ2 ++ A → B :: Δ3 = [] ++ [Box A0] ++ Δ0 ++ [] ++ Δ1). rewrite H6.\n        reflexivity. rewrite H2. clear H2. apply list_exch_RI. pose (d1:=GLS_adm_list_exch_R D0 J8).\n        assert (ImpRRule [([] ++ A ::Γ0 ++ Γ1, (Box A0 :: Δ2) ++ B :: Δ3)] ([] ++ Γ0 ++ Γ1, (Box A0 :: Δ2) ++ A → B :: Δ3)).\n        apply ImpRRule_I. simpl in H2. pose (d2:=ImpR_inv d1 H2). pose (d3:=d0 d2 d). pose (dlCons d3 DersNilF).\n        apply ImpR in H0 ; try intro ; try apply f ; try rewrite <- H7 ; try auto ; try assumption.\n        pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n        (ps:=[(A :: Γ0 ++ Γ1, Δ2 ++ B :: Δ3)]) (Γ0 ++ Γ1, Δ2 ++ A → B :: Δ3) H0 d4). assumption. }\n      (* Right rule is ImpL *)\n      { inversion H. subst. apply list_split_form in H5. destruct H5.\n        - destruct s.\n          + repeat destruct p. inversion e0.\n          + repeat destruct s. repeat destruct p. subst. repeat rewrite <- app_assoc in H. repeat rewrite <- app_assoc in X2.\n            assert (J2: list_exch_R (Γ0 ++ x0 ++ A → B :: Γ3, Δ0 ++ Box A0 :: Δ1) (Γ0 ++ x0 ++ A → B :: Γ3, Box A0 :: Δ2 ++ Δ3)).\n            assert (Δ0 ++ Box A0 :: Δ1 = [] ++ [] ++ Δ0 ++ [Box A0] ++ Δ1). reflexivity. rewrite H0. clear H0.\n            assert (Box A0 :: Δ2 ++ Δ3 = [] ++ [Box A0] ++ Δ0 ++ [] ++ Δ1). rewrite H6. reflexivity. rewrite H0. clear H0.\n            apply list_exch_RI. pose (d:=GLS_adm_list_exch_R D0 J2).\n            assert (ImpLRule [((Γ0 ++ x0) ++ Γ3, (Box A0 :: Δ2) ++ A :: Δ3); ((Γ0 ++ x0) ++ B :: Γ3, (Box A0 :: Δ2) ++ Δ3)]\n            ((Γ0 ++ x0) ++ A → B :: Γ3, (Box A0 :: Δ2) ++ Δ3)). apply ImpLRule_I. simpl in H.\n            repeat rewrite <- app_assoc in H0. pose (ImpL_inv d H0). destruct p as [d0 d1].\n            assert (ImpLRule [((Γ0 ++ x0) ++ Γ3, Δ2 ++ A :: Δ3); ((Γ0 ++ x0) ++ B :: Γ3, Δ2 ++ Δ3)]\n            ((Γ0 ++ x0) ++ A → B :: Γ3, Δ2 ++ Δ3)). apply ImpLRule_I. repeat rewrite <- app_assoc in H0.\n            repeat rewrite <- app_assoc in H2.\n            assert (J3: PSGLS_rules [(Γ0 ++ x0 ++ Γ3, Δ2 ++ A :: Δ3); (Γ0 ++ x0 ++ B :: Γ3, Δ2 ++ Δ3)]\n            (Γ0 ++ x0 ++ A → B :: Γ3, Δ2 ++ Δ3)).\n            apply PSImpL ; try intro ; try apply f ; try rewrite <- app_assoc ;\n            try rewrite <- H6 ; try auto ; try assumption.\n            assert (J30: GLS_rules [(Γ0 ++ x0 ++ Γ3, Δ2 ++ A :: Δ3); (Γ0 ++ x0 ++ B :: Γ3, Δ2 ++ Δ3)]\n            (Γ0 ++ x0 ++ A → B :: Γ3, Δ2 ++ Δ3)). apply ImpL ; try assumption.\n            assert (J5: In (Γ0 ++ x0 ++ Γ3, Δ2 ++ A :: Δ3) [(Γ0 ++ x0 ++ Γ3, Δ2 ++ A :: Δ3); (Γ0 ++ x0 ++ B :: Γ3, Δ2 ++ Δ3)]).\n            apply in_eq.\n            assert (J9: In (Γ0 ++ x0 ++ B :: Γ3, Δ2 ++ Δ3) [(Γ0 ++ x0 ++ Γ3, Δ2 ++ A :: Δ3); (Γ0 ++ x0 ++ B :: Γ3, Δ2 ++ Δ3)]).\n            apply in_cons. apply in_eq.\n            pose (RA_mhd_decreases J3 _ J5). pose (RA_mhd_decreases J3 _ J9). repeat rewrite <- app_assoc in SIH. rewrite <- H6 in SIH.\n            assert (J6: size_form (Box A0) = size_form (Box A0)). reflexivity.\n            assert (J7: mhd (Γ0 ++ x0 ++ Γ3, Δ2 ++ A :: Δ3) = mhd (Γ0 ++ x0 ++ Γ3, Δ2 ++ A :: Δ3)). reflexivity.\n            assert (J8: (Γ0 ++ x0 ++ Γ3, Δ2 ++ A :: Δ3) = (Γ0 ++ x0 ++ Γ3, [] ++ Δ2 ++ A :: Δ3)). reflexivity.\n            pose (d2:=@SIH (mhd (Γ0 ++ x0 ++ Γ3, Δ2 ++ A :: Δ3)) l (Box A0) (Γ0 ++ x0 ++ Γ3, Δ2 ++ A :: Δ3)\n            Γ0 (x0 ++ Γ3) [] (Δ2 ++ A :: Δ3) J6 J7 J8). simpl in d2. inversion X2. subst. inversion X6. clear X6.\n            clear X8. subst. pose (d3:=d2 d0 X5).\n            assert (J10: mhd (Γ0 ++ x0 ++ B :: Γ3, Δ2 ++ Δ3) = mhd (Γ0 ++ x0 ++ B :: Γ3, Δ2 ++ Δ3)). reflexivity.\n            assert (J11: (Γ0 ++ x0 ++ B :: Γ3, Δ2 ++ Δ3) = (Γ0 ++ x0 ++ B :: Γ3, [] ++ Δ2 ++ Δ3)). reflexivity.\n            pose (d4:=@SIH (mhd (Γ0 ++ x0 ++ B :: Γ3, Δ2 ++ Δ3)) l0 (Box A0) (Γ0 ++ x0 ++ B :: Γ3, Δ2 ++ Δ3)\n            Γ0 (x0 ++ B :: Γ3) [] (Δ2 ++ Δ3) J6 J10 J11). simpl in d4. pose (d5:=d4 d1 X7).\n            pose (dlCons d5 DersNilF). pose (dlCons d3 d6).\n            pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n            (ps:=[(Γ0 ++ x0 ++ Γ3, Δ2 ++ A :: Δ3); (Γ0 ++ x0 ++ B :: Γ3, Δ2 ++ Δ3)]) (Γ0 ++ x0 ++ A → B :: Γ3, Δ2 ++ Δ3) J30 d7).\n            assumption.\n        - repeat destruct s. repeat destruct p. subst. rewrite <- app_assoc in D0.\n          assert (J2: list_exch_R (Γ2 ++ (A → B :: x) ++ Γ1, Δ0 ++ Box A0 :: Δ1) (Γ2 ++ (A → B :: x) ++ Γ1, Box A0 :: Δ2 ++ Δ3)).\n          assert (Δ0 ++ Box A0 :: Δ1 = [] ++ [] ++ Δ0 ++ [Box A0] ++ Δ1). reflexivity. rewrite H0. clear H0.\n          assert (Box A0 :: Δ2 ++ Δ3 = [] ++ [Box A0] ++ Δ0 ++ [] ++ Δ1). rewrite H6. reflexivity. rewrite H0. clear H0.\n          apply list_exch_RI. pose (d:=GLS_adm_list_exch_R D0 J2).\n          assert (ImpLRule [(Γ2 ++ x ++ Γ1, (Box A0 :: Δ2) ++ A :: Δ3); (Γ2 ++ B :: x ++ Γ1, (Box A0 :: Δ2) ++ Δ3)]\n          (Γ2 ++ (A → B :: x) ++ Γ1, (Box A0 :: Δ2) ++ Δ3)). apply ImpLRule_I. repeat rewrite <- app_assoc in H0.\n          pose (ImpL_inv d H0). destruct p as [d0 d1]. rewrite <- app_assoc.\n          assert (ImpLRule [(Γ2 ++ x ++ Γ1, Δ2 ++ A :: Δ3); (Γ2 ++ B :: x ++ Γ1, Δ2 ++ Δ3)]\n          (Γ2 ++ (A → B :: x) ++ Γ1, Δ2 ++ Δ3)). apply ImpLRule_I.\n          assert (J3: PSGLS_rules [(Γ2 ++ x ++ Γ1, Δ2 ++ A :: Δ3); (Γ2 ++ B :: x ++ Γ1, Δ2 ++ Δ3)]\n          (Γ2 ++ (A → B :: x) ++ Γ1, Δ2 ++ Δ3)).\n          apply PSImpL ; try intro ; try apply f ; try rewrite <- app_assoc ;\n          try rewrite <- H6 ; try auto ; try assumption.\n          assert (J30: GLS_rules [(Γ2 ++ x ++ Γ1, Δ2 ++ A :: Δ3); (Γ2 ++ B :: x ++ Γ1, Δ2 ++ Δ3)]\n          (Γ2 ++ (A → B :: x) ++ Γ1, Δ2 ++ Δ3)). apply ImpL ; try assumption.\n          assert (J5: In (Γ2 ++ x ++ Γ1, Δ2 ++ A :: Δ3) [(Γ2 ++ x ++ Γ1, Δ2 ++ A :: Δ3); (Γ2 ++ B :: x ++ Γ1, Δ2 ++ Δ3)]).\n          apply in_eq.\n          assert (J9: In (Γ2 ++ B :: x ++ Γ1, Δ2 ++ Δ3) [(Γ2 ++ x ++ Γ1, Δ2 ++ A :: Δ3); (Γ2 ++ B :: x ++ Γ1, Δ2 ++ Δ3)]).\n          apply in_cons. apply in_eq.\n          pose (RA_mhd_decreases J3 _ J5). pose (RA_mhd_decreases J3 _ J9). repeat rewrite <- app_assoc in SIH. rewrite <- H6 in SIH.\n          assert (J6: size_form (Box A0) = size_form (Box A0)). reflexivity.\n          assert (J7: mhd (Γ2 ++ x ++ Γ1, Δ2 ++ A :: Δ3) = mhd (Γ2 ++ x ++ Γ1, Δ2 ++ A :: Δ3)). reflexivity.\n          assert (J8: (Γ2 ++ x ++ Γ1, Δ2 ++ A :: Δ3) = ((Γ2 ++ x) ++ Γ1, [] ++ Δ2 ++ A :: Δ3)). rewrite <- app_assoc. reflexivity.\n          pose (d2:=@SIH (mhd (Γ2 ++ x ++ Γ1, Δ2 ++ A :: Δ3)) l (Box A0) (Γ2 ++ x ++ Γ1, Δ2 ++ A :: Δ3)\n          (Γ2 ++ x) Γ1 [] (Δ2 ++ A :: Δ3) J6 J7 J8). simpl in d2. inversion X2. subst. inversion X6. clear X6.\n          clear X8. subst. repeat rewrite <- app_assoc in d2. pose (d3:=d2 d0 X5).\n          assert (J10: mhd (Γ2 ++ B :: x ++ Γ1, Δ2 ++ Δ3) = mhd (Γ2 ++ B :: x ++ Γ1, Δ2 ++ Δ3)). reflexivity.\n          assert (J11: (Γ2 ++ B :: x ++ Γ1, Δ2 ++ Δ3) = ((Γ2 ++ B :: x) ++ Γ1, [] ++ Δ2 ++ Δ3)). rewrite <- app_assoc. reflexivity.\n          pose (d4:=@SIH (mhd (Γ2 ++ B :: x ++ Γ1, Δ2 ++ Δ3)) l0 (Box A0) (Γ2 ++ B :: x ++ Γ1, Δ2 ++ Δ3)\n          (Γ2 ++ B :: x) Γ1 [] (Δ2 ++ Δ3) J6 J10 J11). simpl in d4. repeat rewrite <- app_assoc in d4. pose (d5:=d4 d1 X7).\n          pose (dlCons d5 DersNilF). pose (dlCons d3 d6).\n          pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n          (ps:=[(Γ2 ++ x ++ Γ1, Δ2 ++ A :: Δ3); (Γ2 ++ B :: x ++ Γ1, Δ2 ++ Δ3)]) (Γ2 ++ (A → B :: x) ++ Γ1, Δ2 ++ Δ3) J30 d7).\n          assumption. }\n      (* Right rule is GLR *)\n      { inversion X5. subst. inversion X0. subst. clear X8. inversion X2. subst. clear X9.\n        pose (univ_gen_ext_splitR _ _ X4). repeat destruct s. repeat destruct p.\n        pose (univ_gen_ext_splitR _ _ X6). repeat destruct s. repeat destruct p. subst. inversion u2.\n        - subst.\n          assert ((XBoxed_list (x ++ x0) ++ [Box A0], [A0]) = ((XBoxed_list (x ++ x0) ++ [Box A0]) ++ [], [] ++ [A0])).\n          repeat rewrite <- app_assoc. reflexivity.\n          assert (X7': derrec GLS_rules (fun _ : Seq => False) ((XBoxed_list (x ++ x0) ++ [Box A0]) ++ [], [] ++ [A0])).\n          rewrite <- H. assumption.\n          assert (J1: wkn_L (Box A) ((XBoxed_list (x ++ x0) ++ [Box A0]) ++ [], [] ++ [A0]) ((XBoxed_list (x ++ x0) ++ [Box A0]) ++ (Box A) :: [], [] ++ [A0])).\n          apply wkn_LI. assert (J2: derrec_height X7' = derrec_height X7'). reflexivity.\n          pose (GLS_wkn_L _ J2 J1). destruct s. clear l0. clear J2. clear X7'. clear J1.\n          assert (J3: wkn_R A ((XBoxed_list (x ++ x0) ++ [Box A0]) ++ [Box A], [] ++ [A0]) ((XBoxed_list (x ++ x0) ++ [Box A0]) ++ [Box A], [] ++ A :: [A0])).\n          apply wkn_RI. assert (J4: derrec_height x2 = derrec_height x2). reflexivity.\n          pose (GLS_wkn_R _ J4 J3). destruct s. clear l0. clear J4. clear J3. clear x2. clear H. simpl in x3.\n          rewrite XBox_app_distrib in x3. repeat rewrite <- app_assoc in x3.\n          rewrite XBox_app_distrib in X8. repeat rewrite <- app_assoc in X8. simpl in X8.\n          assert ((XBoxed_list x1 ++ A0 :: Box A0 :: XBoxed_list l ++ [Box A], [A]) =\n          (XBoxed_list x1 ++ (A0 :: [Box A0]) ++ [] ++ XBoxed_list l ++ [Box A], [A])).\n          reflexivity. rewrite H in X8. clear H.\n          assert (J5: list_exch_L (XBoxed_list x1 ++ [A0; Box A0] ++ [] ++ XBoxed_list l ++ [Box A], [A])\n          (XBoxed_list x1 ++ XBoxed_list l ++ [] ++ [A0; Box A0] ++ [Box A], [A])).\n          apply list_exch_LI.\n          pose (d:=GLS_adm_list_exch_L X8 J5). simpl in d. rewrite app_assoc in d.\n          rewrite <- XBox_app_distrib in d. assert (x1 ++ l = x ++ x0).\n          apply nobox_gen_ext_injective with (l:=(Γ0 ++ Γ1)) ; try assumption.\n          intro. intros. apply H4. apply in_or_app. apply in_app_or in H. destruct H.\n          auto. right. apply in_cons. assumption. apply univ_gen_ext_combine ; assumption.\n          rewrite H in d. clear J5. clear X8. simpl in x3. rewrite app_assoc in x3.\n          rewrite <- XBox_app_distrib in x3.\n          assert (J6: size_form A0 < size_form (Box A0)). simpl. lia.\n          assert (J7: size_form A0 = size_form A0). reflexivity.\n          assert (J8: mhd (XBoxed_list (x ++ x0) ++ [Box A0; Box A], [A]) =\n          mhd (XBoxed_list (x ++ x0) ++ [Box A0; Box A], [A])). reflexivity.\n          assert (J9: (XBoxed_list (x ++ x0) ++ [Box A0; Box A], [A]) =\n          (XBoxed_list (x ++ x0) ++ [Box A0; Box A], [A] ++ [])). rewrite app_nil_r. reflexivity.\n          pose (d0:=@PIH (size_form A0) J6 (mhd (XBoxed_list (x ++ x0) ++ [Box A0; Box A], [A]))\n          A0 (XBoxed_list (x ++ x0) ++ [Box A0; Box A], [A]) (XBoxed_list (x ++ x0)) (Box A0 :: [Box A])\n          [A] [] J7 J8 J9). rewrite app_nil_r in d0. pose (d1:=d0 x3 d).\n          assert (GLRRule [(XBoxed_list (x ++ x0) ++ [Box A0], [A0])] (x ++ x0, [Box A0])).\n          assert ((x ++ x0, [Box A0]) = (x ++ x0, [] ++ Box A0 :: [])). reflexivity. rewrite H0. clear H0.\n          apply GLRRule_I.\n          assumption. apply univ_gen_ext_refl.\n          assert (GLS_rules [(XBoxed_list (x ++ x0) ++ [Box A0], [A0])] (x ++ x0, [Box A0])).\n          apply GLR. assumption.\n          pose (dlCons X7 DersNilF).\n          pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n          (ps:=[(XBoxed_list (x ++ x0) ++ [Box A0], [A0])]) (x ++ x0, [Box A0]) X10 d2).\n          assert ([Box A0] = [Box A0] ++ []). reflexivity. rewrite H0 in d3.\n          assert (wkn_R A (x ++ x0, [Box A0] ++ []) (x ++ x0, [Box A0] ++ A :: [])). apply wkn_RI.\n          assert (J10: derrec_height d3 = derrec_height d3). reflexivity.\n          pose (GLS_wkn_R _ J10 H2). destruct s. clear l0. clear J10. clear H0. clear d3.\n          clear d2. clear X10. clear X8. clear J6. clear J8. clear J9.\n          assert (J20: derrec_height x2 = derrec_height x2). reflexivity.\n          pose (@GLS_XBoxed_list_wkn_L (derrec_height x2) (x ++ x0) [] [] ([Box A0] ++ [A])).\n          repeat rewrite app_nil_r in s. repeat rewrite app_nil_l in s. pose (s x2 J20).\n          destruct s0. clear l0. clear J20. clear s. clear x2.\n          assert (XBoxed_list (x ++ x0) = XBoxed_list (x ++ x0) ++ []). rewrite app_nil_r. reflexivity.\n          rewrite H0 in x4. clear H0.\n          assert (wkn_L (Box A) (XBoxed_list (x ++ x0) ++ [], [Box A0] ++ [A]) (XBoxed_list (x ++ x0) ++ (Box A) :: [], [Box A0] ++ [A])).\n          apply wkn_LI.\n          assert (J10: derrec_height x4 = derrec_height x4). reflexivity.\n          pose (GLS_wkn_L _ J10 H0). destruct s. clear l0. clear J10. clear x4. clear H0.\n          assert (GLRRule [(XBoxed_list (x ++ x0) ++ [Box A], [A])] (Γ0 ++ Γ1, Δ0 ++ Δ1)).\n          rewrite <- H5. apply GLRRule_I ; try assumption.\n          destruct (dec_init_rules (Γ0 ++ Γ1, Δ2 ++ Box A :: Δ3)).\n          + repeat destruct s.\n            * apply IdP in i. pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n              (ps:=[]) (Γ0 ++ Γ1, Δ2 ++ Box A :: Δ3) i DersNilF). assumption.\n            * inversion i. apply Id_all_form.\n            * apply BotL in b. pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n              (ps:=[]) (Γ0 ++ Γ1, Δ2 ++ Box A :: Δ3) b DersNilF). assumption.\n          + assert (PSGLS_rules [(XBoxed_list (x ++ x0) ++ [Box A], [A])] (Γ0 ++ Γ1, Δ0 ++ Δ1)).\n            apply PSGLR ; try intro ; try apply f ; try rewrite H5 ; try auto ; try assumption.\n            assert (J40: GLS_rules [(XBoxed_list (x ++ x0) ++ [Box A], [A])] (Γ0 ++ Γ1, Δ0 ++ Δ1)).\n            apply GLR ; try assumption.\n            assert (l0: mhd (XBoxed_list (x ++ x0) ++ [Box A], [A]) < mhd (Γ0 ++ Γ1, Δ0 ++ Δ1)).\n            assert (J30 : In (XBoxed_list (x ++ x0) ++ [Box A], [A]) [(XBoxed_list (x ++ x0) ++ [Box A], [A])]).\n            apply in_eq. pose (RA_mhd_decreases X10 _ J30). assumption.\n            assert (J10: size_form (Box A0) = size_form (Box A0)). reflexivity.\n            assert (J11: mhd (XBoxed_list (x ++ x0) ++ [Box A], [A]) = mhd (XBoxed_list (x ++ x0) ++ [Box A], [A])). reflexivity.\n            assert (J12: (XBoxed_list (x ++ x0) ++ [Box A], [A]) = (XBoxed_list (x ++ x0) ++ [Box A], [] ++ [A]) ). reflexivity.\n            pose (d2:=@SIH (mhd (XBoxed_list (x ++ x0) ++ [Box A], [A])) l0 (Box A0) (XBoxed_list (x ++ x0) ++ [Box A], [A])\n            (XBoxed_list (x ++ x0)) [Box A] [] [A] J10 J11 J12). simpl in d2. pose (d3:=d2 x2 d1). pose (dlCons d3 DersNilF).\n            pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n            (ps:=[(XBoxed_list (x ++ x0) ++ [Box A], [A])]) (Γ0 ++ Γ1, Δ0 ++ Δ1) J40 d4).\n            rewrite H5. assumption.\n        - exfalso. apply H2. exists A0. reflexivity. }\n    + repeat destruct s. repeat destruct p. subst.\n      assert (GLRRule [(XBoxed_list BΓ ++ [Box A0], [A0])] (Γ0 ++ Γ1, (Δ0 ++ x0) ++ Box A0 :: Δ3)).\n      apply GLRRule_I ; try assumption. repeat rewrite <- app_assoc in X5.\n      assert (GLS_rules [(XBoxed_list BΓ ++ [Box A0], [A0])] (Γ0 ++ Γ1, Δ0 ++ x0 ++ Box A0 :: Δ3)).\n      apply GLR. assumption.\n      pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n      (ps:=[(XBoxed_list BΓ ++ [Box A0], [A0])]) (Γ0 ++ Γ1, Δ0 ++ x0 ++ Box A0 :: Δ3) X6 X0). assumption.\n  * repeat destruct s. repeat destruct p. subst. rewrite <- app_assoc.\n    assert (GLRRule [(XBoxed_list BΓ ++ [Box A0], [A0])] (Γ0 ++ Γ1, Δ2 ++ (Box A0 :: x) ++ Δ1)).\n    apply GLRRule_I ; try assumption.\n    assert (GLS_rules [(XBoxed_list BΓ ++ [Box A0], [A0])] (Γ0 ++ Γ1, Δ2 ++ (Box A0 :: x) ++ Δ1)).\n    apply GLR. assumption.\n    pose (derI (rules:=GLS_rules) (prems:=fun _ : Seq => False)\n    (ps:=[(XBoxed_list BΓ ++ [Box A0], [A0])]) (Γ0 ++ Γ1, Δ2 ++ (Box A0 :: x) ++ Δ1) X6 X0). assumption.\nQed.\n\nTheorem GLS_cut_adm : forall A Γ0 Γ1 Δ0 Δ1,\n                      (GLS_prv (Γ0 ++ Γ1, Δ0 ++ A :: Δ1)) ->\n                      (GLS_prv (Γ0 ++ A :: Γ1, Δ0 ++ Δ1)) ->\n                      (GLS_prv (Γ0 ++ Γ1, Δ0 ++ Δ1)).\nProof.\nintros.\nassert (J1: size_form A = size_form A). reflexivity.\nassert (J2: mhd (Γ0 ++ Γ1, Δ0 ++ Δ1) = mhd (Γ0 ++ Γ1, Δ0 ++ Δ1)). reflexivity.\nassert (J3: (Γ0 ++ Γ1, Δ0 ++ Δ1) = (Γ0 ++ Γ1, Δ0 ++ Δ1)). reflexivity.\npose (@GLS_cut_adm_main (size_form A) (mhd (Γ0 ++ Γ1, Δ0 ++ Δ1)) A\n(Γ0 ++ Γ1, Δ0 ++ Δ1) Γ0 Γ1 Δ0 Δ1 J1 J2 J3). auto.\nQed.\n\n\n", "meta": {"author": "ianshil", "repo": "PhD_thesis", "sha": "af4940397f0d95c1d63a196ab29a3b9f715d9f4e", "save_path": "github-repos/coq/ianshil-PhD_thesis", "path": "github-repos/coq/ianshil-PhD_thesis/PhD_thesis-af4940397f0d95c1d63a196ab29a3b9f715d9f4e/Cut_Elim_GLS/GLS_additive_cut.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.2709296636763177}}
{"text": "Require Import Stlc.SpecTyping.\nRequire Import Stlc.SpecEquivalent.\nRequire Import Stlc.LemmasEvaluation.\nRequire Import Stlc.LemmasTyping.\nRequire Import Utlc.SpecEquivalent.\nRequire Import Utlc.LemmasEvaluation.\n\nRequire Import Compiler.Erase.\nRequire Import Compiler.Compiler.\nRequire Import Compiler.ProtectConfine.\n\nRequire Import UVal.UVal.\n\nRequire Import LogRel.PseudoType.\nRequire Import LogRel.LemmasPseudoType.\nRequire Import LogRel.LR.\nRequire Import LogRel.LemmasLR.\n\nRequire Import BackTrans.InjectExtract.\nRequire Import BackTrans.UpgradeDowngrade.\nRequire Import BackTrans.Emulate.\n\nRequire Import Omega.\n\nLemma equivalencePreservation {t₁ t₂ τ} :\n  ⟪ S.empty ⊢ t₁ : τ ⟫ →\n  ⟪ S.empty ⊢ t₂ : τ ⟫ →\n  ⟪ S.empty ⊢ t₁ ≃ t₂ : τ ⟫ →\n  ⟨ 0 ⊢ compile τ t₁ ≃ compile τ t₂ ⟩.\nProof.\n  revert t₁ t₂ τ.\n  enough (∀ {t₁ t₂ τ},\n            ⟪ S.empty ⊢ t₁ : τ ⟫ →\n            ⟪ S.empty ⊢ t₂ : τ ⟫ →\n            ⟪ S.empty ⊢ t₁ ≃ t₂ : τ ⟫ →\n            ∀ {C}, WsPCtx 0 0 C →\n                 U.Terminating (U.pctx_app (compile τ t₁) C) → U.Terminating (U.pctx_app (compile τ t₂) C)) as Hltor\n      by (intros t₁ t₂ τ ty1 ty2 ceq;\n          assert (⟪ S.empty ⊢ t₂ ≃ t₁ : τ ⟫)\n            by (apply S.pctx_equiv_symm; assumption);\n          split;\n          refine (Hltor _ _ _ _ _ _ _ _); assumption).\n  intros t₁ t₂ τ ty₁ ty₂ ceq Cu sCu term.\n  \n  destruct (U.Terminating_TerminatingN term) as [n termN]; clear term.\n\n  assert (⟪ pempty ⊩ t₁ ⟦ dir_gt , S n ⟧ erase t₁ : embed τ ⟫) as lre₁\n      by (change pempty with (embedCtx (repEmulCtx pempty));\n          eapply erase_correct;\n          cbn; assumption).\n  assert (⟪ pempty ⊩ S.app (inject (S (S n)) τ) t₁ ⟦ dir_gt , S n ⟧ U.app (protect τ) (erase t₁) : pEmulDV (S (S n)) precise ⟫) as lrpe₁\n      by (eapply inject_works_open;\n          eauto using dwp_precise with arith).\n  fold (compile τ t₁) in lrpe₁.\n\n  assert (⟪ ⊩ emulate_pctx (S (S n)) Cu ⟦ dir_gt , S n ⟧ Cu :\n              pempty , pEmulDV (S (S n)) precise → pempty , pEmulDV (S (S n)) precise ⟫) as lrem₁ by\n      (change pempty with (toEmulDV (S (S n)) precise 0);\n       eapply emulate_pctx_works; eauto using dwp_precise with arith).\n\n  pose proof (proj2 lrem₁ _ _ lrpe₁) as lrfull₁.\n\n  assert (S.Terminating (S.pctx_app (S.app (inject (S (S n)) τ) t₁)\n                                    (emulate_pctx (S (S n)) Cu))) as termS\n    by (eapply (adequacy_gt lrfull₁ termN); eauto with arith).\n\n  change (S.app (inject (S (S n)) τ) t₁) with (S.pctx_app t₁ (S.papp₂ (inject (S (S n)) τ) S.phole)) in termS.\n  rewrite <- S.pctx_cat_app in termS. \n\n  assert (⟪ ⊢ emulate_pctx (S (S n)) Cu : S.empty, UVal (S (S n)) → S.empty, UVal (S (S n)) ⟫)\n    by (change S.empty with (toUVals (S (S n)) 0);\n        eapply emulate_pctx_T; assumption).\n\n  assert (S.Terminating (S.pctx_app t₂ (S.pctx_cat\n                 (S.papp₂ (inject (S (S n)) τ) S.phole)\n                 (emulate_pctx (S (S n)) Cu)))) as termS'\n    by (eapply ceq; eauto;\n        eapply pctxtyping_cat; crushTyping;\n        eauto using injectT, emulate_pctx_T).\n\n  destruct (S.Terminating_TerminatingN termS') as [m termSm']; clear termS'.\n\n  assert (⟪ pempty ⊩ t₂ ⟦ dir_lt , S m ⟧ erase t₂ : embed τ ⟫) as lre₂\n      by (change pempty with (embedCtx (repEmulCtx pempty));\n          eapply erase_correct;\n          cbn; assumption).\n  assert (⟪ pempty ⊩ S.app (inject (S (S n)) τ) t₂ ⟦ dir_lt , S m ⟧ U.app (protect τ) (erase t₂) : pEmulDV (S (S n)) imprecise ⟫) as lrpe₂\n      by (eapply inject_works_open;\n          eauto using dwp_imprecise).\n  fold (compile τ t₁) in lrpe₂.\n\n  assert (⟪ ⊩ emulate_pctx (S (S n)) Cu ⟦ dir_lt , S m ⟧ Cu :\n              pempty , pEmulDV (S (S n)) imprecise → pempty , pEmulDV (S (S n)) imprecise ⟫) as lrem₂ by\n      (change pempty with (toEmulDV (S (S n)) imprecise 0);\n       eapply emulate_pctx_works; eauto using dwp_imprecise).\n\n  pose proof (proj2 lrem₂ _ _ lrpe₂) as lrfull₂.\n  rewrite S.pctx_cat_app in termSm'.\n\n  eapply (adequacy_lt lrfull₂ termSm'); eauto with arith.\nQed.\n\nLemma fullAbstraction {t₁ t₂ τ} :\n  ⟪ S.empty ⊢ t₁ : τ ⟫ →\n  ⟪ S.empty ⊢ t₂ : τ ⟫ →\n  ⟪ S.empty ⊢ t₁ ≃ t₂ : τ ⟫ ↔\n  ⟨ 0 ⊢ compile τ t₁ ≃ compile τ t₂ ⟩.\nProof.\n  intros.\n  split;\n  eauto using equivalenceReflection, equivalencePreservation.\nQed.\n\nLemma equivalenceReflectionDF {C₁ C₂ τᵢ τₒ} :\n  ⟪ ⊢ C₁ : S.empty , τᵢ → S.empty , τₒ ⟫ ->\n  ⟪ ⊢ C₂ : S.empty , τᵢ → S.empty , τₒ ⟫ ->\n                                (* (⟨ ⊢ (compile_pctx τᵢ C₁) ≃ (compile_pctx τᵢ C₂) : dom Γᵢ → 0 ⟩). *)\n  PCtxEquivalentCtx 0 (compile_pctx τᵢ C₁) (compile_pctx τᵢ C₂) ->\n  ⟪ ⊢ C₁ ≃ C₂ : S.empty , τᵢ → τₒ  ⟫.\nProof.\n  revert C₁ C₂ τᵢ τₒ.\n  enough (forall (C₁ C₂ : Stlc.SpecSyntax.PCtx) (τᵢ τₒ : Ty),\n            ⟪ ⊢ C₁ : S.empty, τᵢ → S.empty, τₒ ⟫ ->\n            ⟪ ⊢ C₂ : S.empty, τᵢ → S.empty, τₒ ⟫ ->\n            PCtxEquivalentCtx 0 (compile_pctx τᵢ C₁) (compile_pctx τᵢ C₂) ->\n            forall (t : Tm), ⟪ S.empty ⊢ t : τᵢ ⟫ -> Stlc.SpecEvaluation.Terminating (Stlc.SpecSyntax.pctx_app t C₁) ->\n              Stlc.SpecEvaluation.Terminating (Stlc.SpecSyntax.pctx_app t C₂)).\n  {\n    intros C₁ C₂ τᵢ τₒ tyC₁ tyC₂ seq t tyT.\n    split.\n    - intros termC₁.\n      eapply (H C₁ C₂ τᵢ τₒ tyC₁ tyC₂ seq t tyT termC₁).\n    - intros termC₂.\n      refine (H C₂ C₁ τᵢ τₒ tyC₂ tyC₁ _ t tyT termC₂).\n      eapply U.pctx_equiv_ctx_symm.\n      intuition.\n  }\n\n  intros C₁ C₂ τᵢ τₒ tyC₁ tyC₂ seq t tyT term.\n\n  destruct (S.Terminating_TerminatingN term) as [n termN]; clear term.\n  unfold compile_pctx in seq.\n\n  assert (⟪ ⊩ C₁ ⟦ dir_lt , S n ⟧ erase_pctx C₁ : pempty , embed τᵢ → pempty , embed τₒ ⟫) as lrC₁\n  by (change pempty with (embedCtx (repEmulCtx pempty));\n      eapply erase_ctx_correct; cbn; assumption).\n\n  assert (⟪ pempty ⊩ t ⟦ dir_lt , S n ⟧ U.app (confine τᵢ) (erase t) : embed τᵢ ⟫) as lrct\n  by (eapply confine_transp_open;\n      change pempty with (embedCtx S.empty);\n      eapply erase_correct;\n      assumption).\n\n  pose proof (proj2 lrC₁ _ _ lrct) as lrfull₁.\n\n  assert (U.Terminating (U.pctx_app (U.app (confine τᵢ) (erase t)) (erase_pctx C₁))) as termU₁\n  by (eapply (adequacy_lt lrfull₁ termN); eauto with arith).\n\n  assert (U.Terminating (U.pctx_app (U.app (confine τᵢ) (erase t)) (erase_pctx C₂))) as termU₂.\n  { specialize (seq (erase t)).\n    rewrite ?pctx_cat_app in seq.\n    eapply seq.\n    change 0 with (dom S.empty).\n    eapply (erase_scope _ _ _ tyT).\n    cbn. assumption.\n  }\n\n  destruct (U.Terminating_TerminatingN termU₂) as [n₂ termUN₂].\n  refine (adequacy_gt (n := S n₂) _ termUN₂ _); [|omega].\n\n  assert (⟪ ⊩ C₂ ⟦ dir_gt , S n₂ ⟧ erase_pctx C₂ : pempty , embed τᵢ → pempty , embed τₒ ⟫) as lrC₂\n  by (change pempty with (embedCtx (repEmulCtx pempty));\n      eapply erase_ctx_correct; cbn; assumption).\n\n  eapply (proj2 lrC₂).\n  eapply confine_transp_open.\n  change pempty with (embedCtx S.empty).\n  eapply erase_correct.\n  assumption.\nQed.\n\nLemma equivalencePreservationDF {C₁ C₂ τᵢ τₒ} :\n  ⟪ ⊢ C₁ : S.empty , τᵢ → S.empty , τₒ ⟫ ->\n  ⟪ ⊢ C₂ : S.empty , τᵢ → S.empty , τₒ ⟫ ->\n                                (* (⟨ ⊢ (compile_pctx τᵢ C₁) ≃ (compile_pctx τᵢ C₂) : dom Γᵢ → 0 ⟩). *)\n  ⟪ ⊢ C₁ ≃ C₂ : S.empty , τᵢ → τₒ  ⟫ ->\n  PCtxEquivalentCtx 0 (compile_pctx τᵢ C₁) (compile_pctx τᵢ C₂).\nProof.\n  revert C₁ C₂ τᵢ τₒ.\n  enough (forall (C₁ C₂ : Stlc.SpecSyntax.PCtx) (τᵢ τₒ : Ty),\n            ⟪ ⊢ C₁ : S.empty, τᵢ → S.empty, τₒ ⟫ ->\n            ⟪ ⊢ C₂ : S.empty, τᵢ → S.empty, τₒ ⟫ ->\n            ⟪ ⊢ C₁ ≃ C₂ : S.empty, τᵢ → τₒ ⟫ ->\n            forall (t : UTm), wsUTm 0 t ->\n                         (pctx_app t (compile_pctx τᵢ C₁))⇓ → (pctx_app t (compile_pctx τᵢ C₂)) ⇓ ).\n  {\n    intros C₁ C₂ τᵢ τₒ tyC₁ tyC₂ seq t tyT.\n    split.\n    - intros termC₁.\n      eapply (H C₁ C₂ τᵢ τₒ tyC₁ tyC₂ seq t tyT termC₁).\n    - intros termC₂.\n      refine (H C₂ C₁ τᵢ τₒ tyC₂ tyC₁ _ t tyT termC₂).\n      eapply S.pctx_equiv_ctx_symm.\n      intuition.\n  }\n\n  intros C₁ C₂ τᵢ τₒ tyC₁ tyC₂ seq t tyT term.\n\n  destruct (U.Terminating_TerminatingN term) as [n termN]; clear term.\n  unfold compile_pctx in *.\n  rewrite ?U.pctx_cat_app in *.\n  cbn in *.\n\n  assert (⟪ ⊩ C₁ ⟦ dir_gt , S n ⟧ erase_pctx C₁ : pempty , embed τᵢ → pempty , embed τₒ ⟫) as lrC₁\n  by (change pempty with (embedCtx (repEmulCtx pempty));\n      eapply erase_ctx_correct; cbn; assumption).\n\n  assert (⟪ pempty ⊩ S.app (extract (S (S n)) τᵢ) (emulate (S (S n)) t) ⟦ dir_gt , S n ⟧ U.app (confine τᵢ) t : embed τᵢ ⟫) as lrct\n  by (eapply extract_works_open;\n      eauto using dwp_precise with arith;\n      change pempty with (toEmulDV (S (S n)) precise 0);\n      eapply emulate_works;\n      eauto using dwp_precise with arith;\n      assumption).\n\n  pose proof (proj2 lrC₁ _ _ lrct) as lrfull₁.\n\n\n  assert (S.Terminating (S.pctx_app (S.app (extract (S (S n)) τᵢ) (emulate (S (S n)) t)) C₁)) as termS₁\n  by (eapply (adequacy_gt lrfull₁ termN); eauto with arith).\n\n  assert (S.Terminating (S.pctx_app (S.app (extract (S (S n)) τᵢ) (emulate (S (S n)) t)) C₂)) as termS₂\n  by (eapply seq;\n    crushTyping;\n    eauto using extractT;\n    change S.empty with (toUVals (S (S n)) 0);\n    eapply emulate_T;\n    assumption).\n\n  destruct (S.Terminating_TerminatingN termS₂) as [n₂ termSN₂].\n  refine (adequacy_lt (n := S n₂) _ termSN₂ _); [|omega].\n\n  assert (⟪ ⊩ C₂ ⟦ dir_lt , S n₂ ⟧ erase_pctx C₂ : pempty , embed τᵢ → pempty , embed τₒ ⟫) as lrC₂\n  by (change pempty with (embedCtx (repEmulCtx pempty));\n      eapply erase_ctx_correct; cbn; assumption).\n\n  eapply lrC₂.\n  eapply extract_works_open.\n  - eauto using dwp_imprecise with arith.\n  - change pempty with (toEmulDV (S (S n)) imprecise 0).\n    eapply emulate_works; [|assumption].\n    eauto using dwp_imprecise with arith.\nQed.\n\nLemma fullAbstractionDF {C₁ C₂ : Stlc.SpecSyntax.PCtx} {τᵢ τₒ} :\n  ⟪ ⊢ C₁ : S.empty , τᵢ → S.empty , τₒ ⟫ ->\n  ⟪ ⊢ C₂ : S.empty , τᵢ → S.empty , τₒ ⟫ ->\n  ⟪ ⊢ C₁ ≃ C₂ : S.empty , τᵢ → τₒ  ⟫ ↔\n                                (* (⟨ ⊢ (compile_pctx τᵢ C₁) ≃ (compile_pctx τᵢ C₂) : dom Γᵢ → 0 ⟩). *)\n   PCtxEquivalentCtx 0 (compile_pctx τᵢ C₁) (compile_pctx τᵢ C₂).\nProof.\n  intros.\n  split;\n  eauto using equivalencePreservationDF, equivalenceReflectionDF.\nQed.\n\nPrint Assumptions fullAbstraction.\nPrint Assumptions fullAbstractionDF.\n", "meta": {"author": "dominiquedevriese", "repo": "facomp-stlc-coq", "sha": "77043e68813d3a7ed8926802191638f063de1544", "save_path": "github-repos/coq/dominiquedevriese-facomp-stlc-coq", "path": "github-repos/coq/dominiquedevriese-facomp-stlc-coq/facomp-stlc-coq-77043e68813d3a7ed8926802191638f063de1544/FullAbstraction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.27092966367631766}}
{"text": "Require Import Cosa.Lib.Header.\nRequire Import Cosa.Lib.Relation.\nRequire Import Cosa.Lib.Predicate.\nRequire Import Cosa.Lib.MapReduce.\nRequire Import Cosa.Concrete.ConcreteFragment.\nRequire Import Cosa.Abstract.Valuation.\nImport Coq.Classes.EquivDec.\nImport Values.\nImport List.ListNotations.\nRequire Import Coq.Lists.SetoidPermutation.\nRequire Import Cosa.Nominal.Set.\nRequire Import Cosa.Nominal.CompcertInstances.\n\n(** The bare graphs consitute the memory model of the shape domain.\n    They are to be paired with a numerical domain to make a complete\n    abstract domain. *)\n\n(** Basic types *)\n\n(** Types of the nodes of the graph. *)\nDefinition node : Type := Atom.\nInstance node_nominal : Nominal node := perm_nominal.\n\nDefinition node_eq_dec := Pos.eq_dec.\n\nInstance node_eq_dec_inst : EquivDec.EqDec node eq.\nProof. exact node_eq_dec. Qed.\n\nModule NodeTree := AtomTree.\n\n(** In this version offsets are concrete [int], however, in more\n    fine-grain world, they would be abstract expressions. *)\nDefinition offs := int.\nInstance offs_nominal : Nominal offs := discrete_nominal.\n\n(** Representation of pointers in the abstract graph. *)\nDefinition off_node := (node * offs)%type.\nHint Unfold off_node : equivariant.\n\n\n(** Spiwack: I'm really not sure it matters wether valuation are\n    finitely supported or not.  Concretely a finitely supported\n    valuation is constant except on a finite set of atoms. This is not\n    unreasonable to ask, but it may prove harder to achieve than\n    expected. And it may not be needed, after all, what really matter\n    are sets of valuations. Truth be told: this file seems indifferent\n    to whether valuations are finitely supported or not. Up to the\n    fact, of course, that some [Nominal] instances would have to be\n    changed into [Action]. So we'll see in further files which choice\n    works best. *)\nNotation valuation := (node -fs-> val).\n\n\n(** Concrete states *)\n\n\n(** A graph contretises to a pair of a valuation and a concrete heap\n    fragment.  The valuation maps nodes to their addresses or their\n    numerical value. *)\nDefinition conc := (valuation * ConcreteFragment.fragment)%type.\nHint Unfold conc : equivariant.\n\nInstance fragment_nominal : Nominal ConcreteFragment.fragment :=\n  Nominal.Set.discrete_nominal\n.\n\nProgram Instance conc_nominal : Nominal conc := prod_nominal _ _ _ _ .\n\n(** We extend the separating star on concrete heap fragments to\n    concrete graph representations. *)\nDefinition star : conc -> conc -> conc -> Prop := Relation.pair teq ConcreteFragment.star.\nDefinition estar := extension2 star.\n\nLemma equivariant_teq (A:Type) `(Action A) : Equivariant teq.\nProof.\n  apply equivariant_alt₃.\n  intros π x y z. simpl. apply prop_extensionality.\n  assert (forall π x y z, teq x y z -> teq (π·x) (π·y) (π·z)) as h.\n  { clear. intros π x y z [].\n    constructor. }\n  split.\n  + intros h'. eapply (h (op_p π)) in h'.\n    solve_act.\n  + eauto.\nQed.\n(* Hint EResolve equivariant_teq : equivariant. *)\nHint Extern 0 (Equivariant teq) => eapply equivariant_teq : equivariant.\n\nLemma equivariant_fragment_star : Equivariant ConcreteFragment.star.\nProof. easy. Qed.\n(* Hint EResolve equivariant_fragment_star : equivariant. *)\nHint Extern 0 (Equivariant ConcreteFragment.star) => eapply equivariant_fragment_star : equivariant.\n\nLemma equivariant_relation_pair\n      A `(Action A) B `(Action B) : Equivariant (@Relation.pair A B).\nProof.\n  apply equivariant_alt₂. intros π r₁ r₂.\n  unfold Relation.pair.\n  extensionality x; extensionality y; extensionality z. simpl.\n  reflexivity.\nQed.\n(* Hint EResolve equivariant_relation_pair : equivariant. *)\nHint Extern 0 (Equivariant Relation.pair) => eapply equivariant_relation_pair : equivariant.\n\n\n(* arnaud: v'erifier que ce helper est bien n'ecessaire/utile *)\n(** Help the proof search when there is [conc] instead of an explicit product. *)\nCorollary equivariant_relation_pair_conc :\n          @Equivariant (_->_->conc -> conc -> conc -> Prop) _ (@Relation.pair valuation ConcreteFragment.fragment).\nProof. narrow_equivariant. Qed.\n(* Hint EResolve equivariant_relation_pair_conc : equivariant. *)\nHint Extern 0 (@Equivariant (_->_->conc->conc->conc->Prop) _ Relation.pair) => eapply equivariant_relation_pair_conc : equivariant.\n\nLemma equivariant_star : Equivariant star.\nProof. unfold star. narrow_equivariant. Qed.\n(* Hint EResolve equivariant_star : equivariant. *)\nHint Extern 0 (Equivariant star) => eapply equivariant_star : equivariant.\n\nLemma equivariant_extension2 A `(Action A) B `(Action B) C `(Action C) :\n  Equivariant (@extension2 A B C).\nProof.\n  apply equivariant_alt₁. intros π r.\n  extensionality p; extensionality q; extensionality z. unfold extension2. simpl.\n  apply prop_extensionality. simplify_act.\n  firstorder (simplify_act; firstorder).\nQed.\n(* Hint EResolve equivariant_extension2 : equivariant. *)\nHint Extern 0 (Equivariant extension2) => eapply equivariant_extension2 : equivariant.\n\nCorollary equivariant_estar : Equivariant estar.\nProof. narrow_equivariant. Qed.\n(* Hint EResolve equivariant_estar : equivariant. *)\nHint Extern 0 (Equivariant estar) => eapply equivariant_estar : equivariant.\n\nDefinition empty (s:conc) : Prop := ConcreteFragment.empty (snd s).\n\nLemma empty_equivariant : Equivariant empty.\nProof. now unfold Equivariant. Qed.\n(* Hint EResolve empty_equivariant : equivariant. *)\nHint Extern 0 (Equivariant empty) => eapply empty_equivariant : equivariant.\n\nLemma empty_spec : empty = Predicate.pair (fun _ => True) ConcreteFragment.empty.\nProof.\n  apply Predicate.equiv_eq; intro s.\n  unfold empty, Predicate.pair.\n  firstorder.\nQed.\n\nInstance star_associative : Associative eq estar.\nProof. unfold estar; typeclasses eauto. Qed.\n\nInstance star_commutative : Commutative eq estar.\nProof. unfold estar; typeclasses eauto. Qed.\n\nInstance star_empty_neutral : LeftNeutral eq estar empty.\nProof. rewrite empty_spec; unfold estar; typeclasses eauto. Qed.\n\nInstance estar_increasing : Proper (Subset==>Subset==>Subset) estar.\nProof. unfold estar; typeclasses eauto. Qed.\n\nLemma estar_continuous_2 I (x:℘ conc) (f:I->℘ conc):\n  estar x (Join (Γ:=[conc]) f) = Join (Γ:=[conc]) (fun i => estar x (f i)).\nProof.\n  unfold estar.\n  apply extension2_continuous_2.\nQed.\n\n\n(** Definition of the graph itself *)\n\n\n(** Abstract representation for a block. The idea is that a node is\n    either a numerical value or a block. Numerical values in a block\n    will therefore be represented as an extra indirection. In pointers\n    pointing to a value node, the offset must be 0.\n\n    In Xisa, blocks have a number of meta data that we shall ignore in\n    a first step. These meta data are not crucial for correctness, and\n    can be added easily later. *)\nRecord pt_edge := {\n  destination : off_node;\n  size : AST.memory_chunk\n}.\n\nProgram Instance pt_edge_nominal : Nominal pt_edge :=\n  nominal_of_iso\n    (fun e => (e.(destination),e.(size)))\n    (fun e' => {| destination := fst e' ; size := snd e' |})\n    _ _\n.\nNext Obligation.\n  (* [x] should not have been introduced. *)\n  revert x.\n  (* / *)\n  intros [].\n  easy.\nQed.\n\nRemark equivariant_destination : Equivariant destination.\nProof. now apply equivariant_alt₁. Qed.\n(* Hint EResolve equivariant_destination : equivariant. *)\nHint Extern 0 (Equivariant destination) => eapply equivariant_destination : equivariant.\n\nRemark equivariant_size : Equivariant size.\nProof. now apply equivariant_alt₁. Qed.\n(* Hint EResolve equivariant_size : equivariant. *)\nHint Extern 0 (Equivariant size) => eapply equivariant_size : equivariant.\n\nDefinition block := list (offs*pt_edge).\n\nInstance block_nominal : Nominal block := list_nominal _ _.\n\nInductive γ_point_to₀ (α:node) (o:offs) (c:AST.memory_chunk) (β:node) (o':offs) (f:fragment) (ν:valuation) : Prop :=\n| γ_point_to_offs : forall b i b' i',\n    ν α = Vptr b i ->\n    snd f = memory_range b (Int.add i o) c ->\n    ν β = Vptr b' i' ->\n    ConcreteFragment.reads f c b o (Vptr b' (Int.add i' o')) ->\n    γ_point_to₀ α o c β o' f ν\n| γ_point_to_normal : forall b i,\n    ν α = Vptr b i ->\n    snd f = memory_range b (Int.add i o) c ->\n    o' = Int.zero ->\n    ConcreteFragment.reads f c b o (ν β) ->\n    γ_point_to₀ α o c β o' f ν\n.\n\nDefinition γ_point_to α o c β o' : ℘ conc :=\n  fun s => γ_point_to₀ α o c β o' (snd s) (fst s)\n.\n\nDefinition γ_block (α:node) (b:block) : ℘ conc :=\n  list_reduce estar empty (\n      List.map (fun edge =>\n                  γ_point_to α \n                             (fst edge)\n                             (snd edge).(size)\n                             (fst (snd edge).(destination))\n                             (snd (snd edge).(destination))\n      ) b\n  )\n.\n\nSection Graph.\n\n  (** Graphs contain both \"point to edges\" representing individual\n      memory cells, and summarised edges which stands for larger\n      regions. Summarised edges are instantiated to inductive region\n      and inductive segment in [Cosa.Shape.Inductive]. *)\n\n  Context {summary:Type} (γ_summary : summary -> node -> ℘ conc).\n  Context {summary_nominal:Nominal summary} (equivariant_γ_summary : Equivariant γ_summary).\n  (* Hint EResolve equivariant_γ_summary : equivariant. *)\n  Hint Extern 0 (Equivariant γ_summary) => eapply equivariant_γ_summary : equivariant.\n  \n\n  Inductive edge :=\n  | Point_to (b:block)\n  | Summarized (s:summary)\n  .\n\n  Program Instance edge_nominal : Nominal edge :=\n    nominal_of_iso\n      (fun e =>\n         match e return _ with Point_to b => inl b | Summarized s => inr s end)\n      (fun e =>\n         match e return _ with inl b => Point_to b | inr s => Summarized s end)\n      _ _\n  .\n  Next Obligation.\n    (* [x] should not have been introduced *)\n    revert x.\n    (* / *)\n    intros [|]; easy.\n  Qed.\n  Next Obligation.\n    (* [x] should not have been introduced *)\n    revert x.\n    (* / *)\n    intros [|]; easy.\n  Qed.\n\n  Definition γ_edge (α:node) (e:edge) :=\n    match e with\n    | Point_to b => γ_block α b\n    | Summarized s => γ_summary s α\n    end\n  .\n\n  Definition t := NodeTree.t edge.\n\n  Global Instance graph_nominal : Nominal t := Nominal.Set.map_nominal _ _.\n\n  Definition equiv : t -> t -> Prop := AtomTree_Properties.Equal (eqA:=eq) _.\n\n  Global Instance equiv_equivalence : Equivalence equiv.\n  Proof.\n    unfold equiv.\n    apply AtomTree_Properties.Equal_Equivalence.\n  Qed.\n\n  Lemma equiv_alt g₁ g₂ : equiv g₁ g₂ <-> (forall α, g₁!α = g₂!α).\n  Proof. apply ptree_equal_eq_alt. Qed.\n\n  Definition γ := ptree_map_reduce γ_edge estar empty.\n\n  Lemma γ_equiv g₁ g₂ : equiv g₁ g₂ -> γ g₁ = γ g₂.\n  Proof.\n    intros h.\n    apply ptree_permutation_equiv in h.\n    unfold γ.\n    rewrite !ptree_map_reduce_spec.\n    rewrite h.\n    reflexivity.\n  Qed.\n\n  Lemma γ_disjoint_union (g₁ g₂:t) :\n    ptree_disjoint g₁ g₂ ->\n    γ (ptree_union g₁ g₂) = estar (γ g₁) (γ g₂).\n  Proof.\n    intros g₁_g₂_d.\n    unfold γ.\n    apply ptree_disjoint_map_reduce; (typeclasses eauto||assumption).\n  Qed.\n\n  (** This theorem (following from the continuity of [estar]) can be\n      seen as the crux of edge unfolding. It is, however, unused. *)\n  Theorem star_disjoint_union I (g₁ g₂:t) (g:I->t) :\n    ptree_disjoint g₁ g₂ ->\n    γ g₂ ⊆ Join (Γ:=[conc]) (fun i => γ (g i)) ->\n    (forall i, ptree_disjoint g₁ (g i)) ->\n    γ (ptree_union g₁ g₂) ⊆ Join (Γ:=[conc]) (fun i => γ (ptree_union g₁ (g i))).\n  Proof.\n    intros g₁_g₂_d g_spec g₁_g_d.\n    rewrite γ_disjoint_union; [|assumption].\n    rewrite g_spec.\n    rewrite estar_continuous_2.\n    apply Join_increasing; rewrite sub_cons; intro i.\n    rewrite γ_disjoint_union; [|eauto].\n    reflexivity.\n  Qed.\n\n  Lemma single_out_one_edge (g:t) α :\n    forall e, g!α = Some e ->\n    γ g = estar (γ (NodeTree.remove α g)) (γ_edge α e).\n  Proof.\n    intros * h.\n    set (g' := NodeTree.remove α g).\n    set (gα := NodeTree.set α e (NodeTree.empty _)).\n    assert (ptree_disjoint g' gα) as g'_gα_d.\n    { unfold ptree_disjoint.\n      intros β e₁ e₂ hg' hgα.\n      unfold g',gα in hg',hgα.\n      CPTree.simplify;congruence. }\n    assert (Graph.equiv g (ptree_union g' gα)) as g_g'_gα.\n    { unfold Graph.equiv,AtomTree_Properties.Equal.\n      intros β.\n      generalize (node_eq_dec α β).\n      intros [ <- | α_neq_β ].\n      + rewrite h.\n        unfold ptree_union.\n        rewrite NodeTree.gcombine; [|easy].\n        unfold g',gα.\n        CPTree.simplify.\n        reflexivity.\n      + unfold ptree_union.\n        rewrite NodeTree.gcombine; [|easy].\n        unfold g',gα.\n        CPTree.simplify.\n        now destruct (g!β). }\n    transitivity (γ (ptree_union g' gα)).\n    { now apply γ_equiv. }\n    assert (γ_edge α e = γ gα) as ->.\n    { unfold γ; rewrite ptree_map_reduce_spec.\n      assert ([(α,e)] = AtomTree.elements gα) as <-.\n      { clear.\n        apply singleton_eq_norepet.\n        { intros [β e']; split.\n          - intros h.\n            apply NodeTree.elements_complete in h.\n            unfold gα in h.\n            CPTree.simplify; congruence.\n          - intros h; simpl in h.\n            rewrite h; clear β e' h.\n            apply NodeTree.elements_correct.\n            unfold gα.\n            CPTree.simplify; congruence. }\n        apply ptree_elements_norepet. }\n      simpl.\n      now rewrite left_neutrality. }\n    now apply γ_disjoint_union.\n  Qed.\n\n  Corollary single_out_one_edge_set (g:t) α e :\n    g!α = None ->\n    γ (NodeTree.set α e g) = estar (γ g) (γ_edge α e).\n  Proof.\n    intros h₁.\n    set (g' := (NodeTree.set α e g)).\n    rewrite (single_out_one_edge g' α e).\n    { f_equal.\n      apply γ_equiv,equiv_alt.\n      intros β. unfold g'; clear g'.\n      CPTree.simplify; congruence. }\n    unfold g'; clear g'.\n    CPTree.simplify; congruence.\n  Qed.\n\n  Theorem star_summarized_edge (g:t) α :\n    forall sm, g!α = Some (Summarized sm) ->\n    forall s:conc, s ∈ γ g ->\n    exists (s₁ s₂:conc),\n      s₁ ∈ γ (NodeTree.remove α g) /\\ s₂ ∈ γ_summary sm α /\\ star s₁ s₂ s.\n  Proof.\n    intros * h₁ * h₂.\n    apply single_out_one_edge in h₁.\n    rewrite h₁ in h₂; clear h₁.\n    unfold estar,extension2 in h₂.\n    destruct h₂ as [ s₁ [ s₂ [ h₁ [ h₂ h₃ ]]]].\n    exists s₁; exists s₂.\n    decompose_concl; eauto.\n  Qed.\n\n  Lemma γ_empty : γ (NodeTree.empty _) = empty.\n  Proof.\n    unfold γ; rewrite ptree_map_reduce_spec.\n    replace (AtomTree.elements (NodeTree.empty edge)) with (@nil (positive*edge)).\n    + easy.\n    + assert (forall x, ~List.In x (AtomTree.elements (NodeTree.empty edge))) as h.\n      { intros [α e] h.\n        apply AtomTree.elements_complete in h.\n        CPTree.simplify; congruence. }\n      destruct (AtomTree.elements (NodeTree.empty edge)) as [ | x l ].\n      * reflexivity.\n      * specialize (h x); simpl in h.\n        contradiction h.\n        now left.\n  Qed.\n\n  (** The concretisation is equivariant. *)\n\n  (* arnaud: Notation a deplacer *)\n  Notation \"`⟨ x ⟩\" := (exist _ x _).\n\n  Lemma γ_point_to_equivariant : Equivariant γ_point_to.\n  Proof.\n    rewrite equivariant_alt₁.\n    intros π α.\n    apply act_float_l. simpl.\n    extensionality o;\n      extensionality c; extensionality β; extensionality o'; extensionality νf.\n    destruct νf as [ν f]. unfold γ_point_to. simpl.\n    apply prop_extensionality.\n    assert (forall π α o c β o' ν f,\n              γ_point_to₀ (π·α) o c (π·β) o' f (π·ν) -> γ_point_to₀ α o c β o' f ν) as h.\n    (* arnaud: voir `a utiliser solve_act dans cette sous-preuve *)\n    { clear. intros * [ b i b' i' h₁ h₂ h₃ h₄ | b i h₁ h₂ h₃ h₄ ];\n        econstructor (solve[\n          simpl in *;\n          rewrite <- ?perm_comp', ?op_p_spec_l in *|-; simpl in *;\n          eassumption]). }\n    split.\n    + intros h₁.\n      eapply h.\n      apply_eq h₁.\n      * solve_act.\n      * reflexivity.\n    + intros h₁.\n      apply (h (op_p π)).\n      (* arnaud: mettre fs_extensionality dans solve_act pour simplifier le reste de la preuve. *)\n      apply_eq h₁.\n      * simpl.\n        now rewrite <- perm_comp', op_p_spec_l; simpl.\n      * now rewrite <- perm_comp', op_p_spec_r; simpl.\n      * apply fs_extensionality. extensionality δ. simpl.\n        now rewrite <- perm_comp', op_p_spec_l; simpl.\n  Qed.\n  (* Hint EResolve γ_point_to_equivariant : equivariant. *)\n  Hint Extern 0 (Equivariant γ_point_to) => eapply γ_point_to_equivariant : equivariant.\n\n  (* arnaud: peut-etre deplacer tout ca *)\n\n  Lemma list_reduce_equivariant A `(Action A) : Equivariant (@list_reduce A).\n  Proof.\n    rewrite equivariant_alt₁.\n    intros π f. extensionality s; extensionality l.\n    revert s.\n    induction l as [ | x l h ].\n    + intros s. simpl.\n      solve_act.\n    + intros s. unfold list_reduce in *.\n      simpl List.fold_left.\n      rewrite h. simpl.\n      solve_act.\n  Qed.\n  (* Hint EResolve list_reduce_equivariant : equivariant. *)\n  Hint Extern 0 (Equivariant list_reduce) => eapply list_reduce_equivariant : equivariant.\n\n  Program Instance option_action A `(Action A) : Action (option A) := {|\n    act π o := match o return _ with Some x => Some (π·x) | None => None end\n  |}.\n  Next Obligation.\n    autounfold.\n    intros π₁ π₂ hπ x y <-.\n    now destruct x; rewrite ?hπ.\n  Qed.\n  Next Obligation.\n    (* [x] should not have been introduced *)\n    revert x.\n    (* / *)\n    now intros [?|]; rewrite ?act_id.\n  Qed.\n  Next Obligation.\n    (* [x] should not have been introduced *)\n    revert x.\n    (* / *)\n    now intros [?|]; rewrite ?act_comp.\n  Qed.\n\n  Lemma map_action_alt_eq A `(Action A) π (m:AtomTree.t A) :\n    forall α, (π·m)!α = π·(m!((op_p π)·α)).\n  Proof.\n    assert (forall o₁ o₂:option A, (forall v, o₁ = Some v <-> o₂ = Some v) -> o₁ = o₂) as rem.\n    { clear.\n      destruct o₁; destruct o₂; try firstorder congruence.\n      (* no idea why the last case isn't solved by [firstorder congruence] *)\n      intros h. symmetry. rewrite <- h.\n      easy. }\n    intros α.\n    apply rem. intros v.\n    rewrite map_action_alt.\n    rewrite <- act_float_r.\n    reflexivity.\n  Qed.\n\n\n  Lemma equivariant_map_set A `(Action A) : Equivariant (@AtomTree.set A).\n  Proof.\n    apply equivariant_alt₃.\n    intros π α x m.\n    apply AtomTree.unicity. intros β.\n    rewrite map_action_alt_eq.\n    destruct (Pos.eq_dec (π·α) β) as [ <- | nβ ].\n    { simplify_act.\n      now AtomTree.simplify. }\n    assert (α <> (op_p π)·β) as nβ'.\n    { intros ?. apply nβ.\n      now apply act_float_r. }\n    AtomTree.simplify.\n    apply map_action_alt_eq.\n  Qed.\n  (* Hint EResolve equivariant_map_set : equivariant. *)\n  Hint Extern 0 (Equivariant AtomTree.set) => eapply equivariant_map_set : equivariant.\n    \n\n  Lemma ptree_map_reduce_equivariant A `(Action A) B `(Action B)\n    (f:node->A->B) (ef:Equivariant f)\n    (r:B->B->B) (er:Equivariant r) `(Associative _ eq r) `(Commutative _ eq r)\n    (n:B) (en:Equivariant n) `(LeftNeutral _ eq r n) :\n    Equivariant (ptree_map_reduce f r n).\n  Proof.\n    unfold Equivariant, support. intros π _.\n    unfold ptree_map_reduce at 2. extensionality m.\n    apply AtomTree_Properties.fold_rec.\n    + intros m₁ m₂ b h.\n      apply AtomTree.unicity in h. rewrite <- h.\n      easy.\n    + apply en. intros **; AtomSet.fsetdec'.\n    + intros m' b α a hk₁ hk₂ h.\n      simpl. change (map_action_f A H (op_p π) (CPTree.set α a m')) with ((op_p π)·(CPTree.set α a m')).\n      generalize equivariant_map_set. intros hset.\n      eapply equivariant_alt₃ in hset. erewrite <- hset.\n      rewrite ptree_set_map_reduce; [|typeclasses eauto ..|].\n      * eapply equivariant_alt₂ in er. erewrite <- er.\n        simpl in h|-*. rewrite h.\n        eapply equivariant_alt₂ in ef. erewrite <- ef.\n        solve_act.\n      * rewrite map_action_alt_eq.\n        simplify_act.\n        now rewrite hk₁.\n  Qed.\n  (* Hint EResolve ptree_map_reduce_equivariant : equivariant. *)\n  Hint Extern 4 (Equivariant (ptree_map_reduce _ _ _)) => eapply ptree_map_reduce_equivariant : equivariant.\n\n(* arnaud: unused right now\n  Lemma act_app_up A `(Action A) B `(Action B) π (f:A->B) (x:A) : (π·f) x = π·(f ((op_p π)·x)).\n  Proof.\n    reflexivity.\n  Qed.\n\n  Lemma act_app_down A `(Action A) B `(Action B) π (f:A->B) (x:A): π·(f x) = (π·f) (π·x).\n  Proof.\n    simpl.\n    solve_act.\n  Qed.\n\n  Lemma equivariant_cancel {A} `{Action A} (f:A) :\n    Equivariant f -> forall π, π·f = f.\n  Proof.\n    intros h π. apply h.\n    intros **.\n    AtomSet.fsetdec'.\n  Qed.\n\n  (* Doesn't handle the dependent product case gracefully. *)\n  Ltac push_equivariant :=\n    erewrite ?act_app_up; (* eliminates β-redexes *)\n    erewrite ?act_app_down; (* pushes permutation as deeply as possible *)\n    repeat match goal with\n    | |- appcontext[?p·?f] =>\n         erewrite (equivariant_cancel f);[|solve[narrow_equivariant]]\n    end\n  .\n*)\n\n\n\n  (* arnaud: /peut-etre deplacer tout ca *)\n\n\n  Lemma γ_block_equivariant : Equivariant γ_block.\n  Proof.\n    unfold γ_block.\n    combinatorize.\n    narrow_equivariant.\n  Qed.\n  (* Hint EResolve γ_block_equivariant : equivariant. *)\n  Hint Extern 0 (Equivariant γ_block) => eapply γ_block_equivariant : equivariant.\n\n  Lemma γ_edge_equivariant : Equivariant γ_edge.\n  Proof.\n    apply equivariant_alt₂.\n    intros π α [e|e].\n    + generalize γ_block_equivariant; intros h.\n      eapply equivariant_alt₂ in h.\n      eapply h.\n    + eapply equivariant_alt₂ in equivariant_γ_summary.\n      eapply equivariant_γ_summary.\n  Qed.\n  (* Hint EResolve γ_edge_equivariant : equivariant. *)\n  Hint Extern 0 (Equivariant γ_edge) => eapply γ_edge_equivariant : equivariant.\n\n  Lemma γ_equivariant : Equivariant γ.\n  Proof.\n    unfold γ.\n    typeclasses eauto with equivariant typeclass_instances.\n  Qed.\n\n\n  (* (** The valuation matters only on the node of the graph. *) *)\n\n  (* Definition belongs_to_point_to α (o:offs) (c:AST.memory_chunk) β (o':offs) : ℘ node := *)\n  (*   fun δ => δ = α \\/ δ = β *)\n  (* . *)\n\n  (* (* Lemma valuation_not_fixed_point_to α o chunk β o' f: *) *)\n  (* (*   central (belongs_to_point_to α o chunk β o') *) *)\n  (* (*           (fun ν => (ν,f) ∈ γ_point_to α o chunk β o'). *) *)\n  (* (* Proof. *) *)\n  (* (*   unfold central. intros δ γ hδ hγ ν h₁. *) *)\n  (* (*   unfold belongs_to_point_to in *. *) *)\n  (* (*   destruct h₁; simpl in *. *) *)\n  (* (*   + eleft; eauto; simpl. *) *)\n  (* (*     * unfold Valuation.swap. *) *)\n  (* (*       destruct (α == δ) as [ <- | _ ]. *) *)\n  (* (*       { clear -hδ; firstorder. } *) *)\n  (* (*       destruct (α == γ) as [ <- | _ ]. *) *)\n  (* (*       { clear -hγ; firstorder. } *) *)\n  (* (*       easy. *) *)\n  (* (*     * unfold Valuation.swap. *) *)\n  (* (*       destruct (β == δ) as [ <- | _ ]. *) *)\n  (* (*       { clear -hδ; firstorder. } *) *)\n  (* (*       destruct (β == γ) as [ <- | _ ]. *) *)\n  (* (*       { clear -hγ; firstorder. } *) *)\n  (* (*       easy. *) *)\n  (* (*   + eright; eauto; simpl. *) *)\n  (* (*     * unfold Valuation.swap. *) *)\n  (* (*       destruct (α == δ) as [ <- | _ ]. *) *)\n  (* (*       { clear -hδ; firstorder. } *) *)\n  (* (*       destruct (α == γ) as [ <- | _ ]. *) *)\n  (* (*       { clear -hγ; firstorder. } *) *)\n  (* (*       easy. *) *)\n  (* (*     * replace (Valuation.swap δ γ ν β) with (ν β). *) *)\n  (* (*       { easy. } *) *)\n  (* (*       unfold Valuation.swap. *) *)\n  (* (*       destruct (β == δ) as [ <- | _ ]. *) *)\n  (* (*       { clear -hδ; firstorder. } *) *)\n  (* (*       destruct (β == γ) as [ <- | _ ]. *) *)\n  (* (*       { clear -hγ; firstorder. } *) *)\n  (* (*       easy. *) *)\n  (* (* Qed. *) *)\n\n  (* Definition belongs_to_block α b : ℘ node := *)\n  (*   (fun β => β = α) ∪ (* case where the block is empty *) *)\n  (*   list_reduce union ∅ *)\n  (*               (List.map  *)\n  (*                  (fun oe => *)\n  (*                     belongs_to_point_to *)\n  (*                       α (fst oe) (snd oe).(size)  *)\n  (*                       (fst (snd oe).(destination)) (snd (snd oe).(destination)) *)\n  (*                  ) b *)\n  (*               ) *)\n  (* . *)\n\n  (* (* Lemma valuation_not_fixed_block α b f : *) *)\n  (* (*   central (belongs_to_block α b) *) *)\n  (* (*           (fun ν => (ν,f) ∈ γ_block α b). *) *)\n  (* (* Proof. *) *)\n  (* (*   unfold central. intros β δ hβ hδ ν. revert f. *) *)\n  (* (*   induction b as [ | p b hb ]; intros f h₁. *) *)\n  (* (*   - (* b = [] *) *) *)\n  (* (*     unfold γ_block in *; simpl in *. *) *)\n  (* (*     unfold empty in *; simpl in *. *) *)\n  (* (*     assumption. *) *)\n  (* (*   - (* b = p::b *) *) *)\n  (* (*     unfold γ_block in h₁ |- *. *) *)\n  (* (*     rewrite list_map_cons,(list_reduce_cons eq); [ | typeclasses eauto .. ]. *) *)\n  (* (*     rewrite list_map_cons,(list_reduce_cons eq) in h₁; [ | typeclasses eauto .. ]. *) *)\n  (* (*     destruct h₁ as [ [ ν₁ f₁ ] [ [ ν₂ f₂ ] [ h₂ [ h₃ [ h₄ h₅ ]]]]]; simpl in h₄,h₅. *) *)\n  (* (*     destruct h₄. *) *)\n  (* (*     exists (Valuation.swap β δ ν₁,f₁); exists (Valuation.swap β δ ν₁,f₂). *) *)\n  (* (*     decompose_concl. *) *)\n  (* (*     + apply valuation_not_fixed_point_to. *) *)\n  (* (*       * clear -hβ; unfold belongs_to_block in hβ. *) *)\n  (* (*         intros h. *) *)\n  (* (*         apply hβ. *) *)\n  (* (*         right. *) *)\n  (* (*         rewrite list_map_cons,(list_reduce_cons eq); [ | typeclasses eauto .. ]. *) *)\n  (* (*         now left. *) *)\n  (* (*       * clear -hδ; unfold belongs_to_block in hδ. *) *)\n  (* (*         intros h. *) *)\n  (* (*         apply hδ. *) *)\n  (* (*         right. *) *)\n  (* (*         rewrite list_map_cons,(list_reduce_cons eq); [ | typeclasses eauto .. ]. *) *)\n  (* (*         now left. *) *)\n  (* (*       * assumption. *) *)\n  (* (*     + apply hb. *) *)\n  (* (*       * clear -hβ; unfold belongs_to_block in hβ. *) *)\n  (* (*         intros h. *) *)\n  (* (*         apply hβ. *) *)\n  (* (*         destruct h. *) *)\n  (* (*         { now left. } *) *)\n  (* (*         right. *) *)\n  (* (*         rewrite list_map_cons,(list_reduce_cons eq); [ | typeclasses eauto .. ]. *) *)\n  (* (*         now right. *) *)\n  (* (*       * clear -hδ; unfold belongs_to_block in hδ. *) *)\n  (* (*         intros h. *) *)\n  (* (*         apply hδ. *) *)\n  (* (*         destruct h. *) *)\n  (* (*         { now left. } *) *)\n  (* (*         right. *) *)\n  (* (*         rewrite list_map_cons,(list_reduce_cons eq); [ | typeclasses eauto .. ]. *) *)\n  (* (*         now right. *) *)\n  (* (*       * apply h₃. *) *)\n  (* (*     + split; simpl. *) *)\n  (* (*       { constructor. } *) *)\n  (* (*       assumption. *) *)\n  (* (* Qed. *) *)\n\n  (* (** spiwack: in a more general setting, summaries should control *)\n  (*     some nodes.  It would come as an extra piece of data of type *)\n  (*     [summary -> ℘ node], for instance. *) *)\n  (* Definition belongs_to_summary α (sm:summary) : ℘ node := *)\n  (*   fun δ => δ = α *)\n  (* . *)\n\n  (* (* Hypothesis valuation_not_fixed_summary : forall α sm f, *) *)\n  (* (*   central (belongs_to_summary α sm) *) *)\n  (* (*           (fun ν => (ν,f) ∈ γ_summary sm α). *) *)\n\n  (* Definition belongs_to_edge α e : ℘ node := *)\n  (*   match e with *)\n  (*   | Point_to b => belongs_to_block α b *)\n  (*   | Summarized sm => belongs_to_summary α sm *)\n  (*   end *)\n  (* . *)\n  \n  (* (* Lemma valuation_not_fixed_edge α e f : *) *)\n  (* (*   central (belongs_to_edge α e) *) *)\n  (* (*           (fun ν => (ν,f) ∈ γ_edge α e). *) *)\n  (* (* Proof. *) *)\n  (* (*   unfold central. intros β δ hβ hδ ν h₁. *) *)\n  (* (*   unfold γ_edge. *) *)\n  (* (*   destruct e as [ b | sm ]. *) *)\n  (* (*   + (* e = Point_to b *) *) *)\n  (* (*     simpl in h₁. *) *)\n  (* (*     apply valuation_not_fixed_block; eauto. *) *)\n  (* (*   + (* e = Summarized sm *) *) *)\n  (* (*     simpl in h₁. *) *)\n  (* (*     apply valuation_not_fixed_summary; eauto. *) *)\n  (* (* Qed. *) *)\n\n  (* Definition belongs_to_graph (g:t) : ℘ node := *)\n  (*   ptree_map_reduce belongs_to_edge union ∅ g *)\n  (* . *)\n\n  (* Global Instance belongs_to_graph_equiv : Proper (equiv ==> eq) belongs_to_graph. *)\n  (* Proof. *)\n  (*   unfold Proper,respectful,belongs_to_graph. *)\n  (*   intros g₁ g₂ h. *)\n  (*   rewrite !ptree_map_reduce_spec. *)\n  (*   apply ptree_permutation_equiv in h. *)\n  (*   rewrite h. *)\n  (*   reflexivity. *)\n  (* Qed. *)\n  (* Global Instance belongs_to_graph_equiv' : Proper (equiv ==> eq ==> eq) belongs_to_graph. *)\n  (* Proof. *)\n  (*   unfold Proper,respectful. *)\n  (*   intros g₁ g₂ h₁ α ? <-. *)\n  (*   apply equal_f. *)\n  (*   now rewrite h₁. *)\n  (* Qed. *)\n\n  (* Lemma belongs_to_graph_remove (g:t) α : *)\n  (*   forall β,  β ∈ belongs_to_graph (NodeTree.remove α g) -> β ∈ belongs_to_graph g. *)\n  (* Proof. *)\n  (*   intros *. *)\n  (*   destruct (g!α) as [ e | ] eqn:h₁. *)\n  (*   + (* g!α = Some e *) *)\n  (*     set (g' := NodeTree.remove α g). *)\n  (*     assert (equiv g (NodeTree.set α e g')) as h₂. *)\n  (*     { apply equiv_alt; intros δ. *)\n  (*       unfold g'; clear g'. *)\n  (*       CPTree.simplify; congruence. } *)\n  (*     intros h₃. *)\n  (*     erewrite belongs_to_graph_equiv'; [|eauto..]. *)\n  (*     unfold belongs_to_graph in *. *)\n  (*     rewrite ptree_set_map_reduce; [|typeclasses eauto..|]. *)\n  (*     * now right. *)\n  (*     * unfold g' in *; clear g'. *)\n  (*       CPTree.simplify; congruence. *)\n  (*   + (* g!α = None *) *)\n  (*     rewrite belongs_to_graph_equiv'; eauto. *)\n  (*     apply equiv_alt; intros δ. *)\n  (*     CPTree.simplify; congruence. *)\n  (* Qed. *)\n\n  (* (* Theorem valuation_not_fixed (g:t) f : *) *)\n  (* (*   central (belongs_to_graph g) *) *)\n  (* (*           (fun ν => (ν,f) ∈ γ g). *) *)\n  (* (* Proof. *) *)\n  (* (*   revert f; unfold γ; unfold ptree_map_reduce. *) *)\n  (* (*   apply AtomTree_Properties.fold_rec. *) *)\n  (* (*   { intros g₁ g₂ P g₁_g₂ h₂ f α β h₃ h₄ ν' h₅. *) *)\n  (* (*     apply equiv_alt in g₁_g₂. *) *)\n  (* (*     eapply h₂; clear h₂. *) *)\n  (* (*     + intros h; apply h₃. *) *)\n  (* (*       now apply belongs_to_graph_equiv in g₁_g₂; rewrite <- g₁_g₂. *) *)\n  (* (*     + intros h; apply h₄. *) *)\n  (* (*       now apply belongs_to_graph_equiv in g₁_g₂; rewrite <- g₁_g₂. *) *)\n  (* (*     + assumption. } *) *)\n  (* (*   { intros f α β hα hβ ν h. *) *)\n  (* (*     unfold empty; simpl. *) *)\n  (* (*     unfold empty in h; simpl in h. *) *)\n  (* (*     assumption. } *) *)\n  (* (*   intros g' P α e h₁ h₂ h f β δ hβ hδ ν h₃. *) *)\n  (* (*   destruct h₃ as [ [ ν₁ f₁ ] [ [ ν₂ f₂ ] [ h₃₁ [ h₃₂ [ h₃₃ h₃₄ ]]]]]; simpl in h₃₃,h₃₄. *) *)\n  (* (*   destruct h₃₃. *) *)\n  (* (*   exists (Valuation.swap β δ ν₁,f₁); exists (Valuation.swap β δ ν₁,f₂). *) *)\n  (* (*   decompose_concl. *) *)\n  (* (*   + apply h. *) *)\n  (* (*     * clear -h₁ hβ. *) *)\n  (* (*       intros h; apply hβ. *) *)\n  (* (*       unfold belongs_to_graph. *) *)\n  (* (*       rewrite ptree_set_map_reduce; [|typeclasses eauto..|easy]. *) *)\n  (* (*       now right. *) *)\n  (* (*     * clear -h₁ hδ. *) *)\n  (* (*       intros h; apply hδ. *) *)\n  (* (*       unfold belongs_to_graph. *) *)\n  (* (*       rewrite ptree_set_map_reduce; [|typeclasses eauto..|easy]. *) *)\n  (* (*       now right. *) *)\n  (* (*     * assumption. *) *)\n  (* (*   + apply valuation_not_fixed_edge. *) *)\n  (* (*     * clear -h₁ hβ. *) *)\n  (* (*       intros h; apply hβ. *) *)\n  (* (*       unfold belongs_to_graph. *) *)\n  (* (*       rewrite ptree_set_map_reduce; [|typeclasses eauto..|easy]. *) *)\n  (* (*       now left. *) *)\n  (* (*     * clear -h₁ hδ. *) *)\n  (* (*       intros h; apply hδ. *) *)\n  (* (*       unfold belongs_to_graph. *) *)\n  (* (*       rewrite ptree_set_map_reduce; [|typeclasses eauto..|easy]. *) *)\n  (* (*       now left. *) *)\n  (* (*     * assumption. *) *)\n  (* (*   + constructor; simpl. *) *)\n  (* (*     * constructor. *) *)\n  (* (*     * assumption. *) *)\n  (* (* Qed. *) *)\n\n  (* (* Corollary valuation_not_fixed_iter (g:t) : *) *)\n  (* (*   forall (p:permutation), permutation_not_in p (belongs_to_graph g) -> *) *)\n  (* (*   forall ν f, (ν,f) ∈ γ g -> (p@ν,f) ∈ γ g. *) *)\n  (* (* Proof. *) *)\n  (* (*   intros **. *) *)\n  (* (*   apply central_permutation with (belongs_to_graph g). *) *)\n  (* (*   + apply valuation_not_fixed. *) *)\n  (* (*   + assumption. *) *)\n  (* (*   + assumption. *) *)\n  (* (* Qed. *) *)\n\n  (* Lemma domain_belongs g : *)\n  (*   forall α e, g!α = Some e -> *)\n  (*   α ∈ belongs_to_graph g. *)\n  (* Proof. *)\n  (*   unfold belongs_to_graph, belongs_to_graph, ptree_map_reduce. *)\n  (*   apply AtomTree_Properties.fold_rec. *)\n  (*   { intros g₁ g₂ P h₁ h₂ α e h₃. *)\n  (*     apply h₂ with e. *)\n  (*     now rewrite h₁. } *)\n  (*   { intros ** h. *)\n  (*     CPTree.simplify; congruence. } *)\n  (*   intros g₁ P α e h₁ h₂ h₃ β e' h₄. *)\n  (*   CPTree.simplify. *)\n  (*   - right. *)\n  (*     destruct e; simpl. *)\n  (*     + unfold belongs_to_block. *)\n  (*       now left. *)\n  (*     + unfold belongs_to_summary. *)\n  (*       reflexivity. *)\n  (*   - left ; eauto. *)\n  (* Qed. *)\n\nEnd Graph.\n\nArguments t summary : clear implicits.\n(* Hint EResolve @γ_equivariant : equivariant. *)\nHint Extern 0 (Equivariant (γ _)) => eapply @γ_equivariant : equivariant.\n\n\n(** the concretisation are increasing with respect to the concretisation of summarized\n    edges. *)\nInstance γ_edge_increasing s :\n  Proper (sub (Γ:=[s;node;conc]) ==> eq ==> eq ==> sub (Γ:=[conc])) γ_edge.\nProof.\n  unfold Proper, respectful.\n  intros γ₁ γ₂ γ₁_sub_γ₂ α ? <- e ? <-.\n  unfold γ_edge.\n  destruct e as [ b | sm ].\n  - (* e = point_to b *)\n    reflexivity.\n  - (* e = summarized sm *)\n    simpl in *.\n    eauto.\nQed.\n\nInstance γ_increasing s :\n  Proper (sub (Γ:=[s;node;conc]) ==> equiv ==> sub (Γ:=[conc])) γ.\nProof.\n  unfold Proper, respectful.\n  intros γ₁ γ₂ γ₁_sub_γ₂ g₁ g₂ g₁_eq_g₂.\n  eapply γ_equiv in g₁_eq_g₂.\n  rewrite <- g₁_eq_g₂; clear g₂ g₁_eq_g₂.\n  unfold γ.\n  rewrite !ptree_map_reduce_spec.\n  apply list_reduce_proper.\n  { typeclasses eauto. }\n  { typeclasses eauto. }\n  { reflexivity. }\n  apply list_map_plr; [ typeclasses eauto | | reflexivity ].\n  unfold respectful.\n  intros e ? <-.\n  rewrite γ₁_sub_γ₂.\n  reflexivity.\nQed.", "meta": {"author": "aspiwack", "repo": "cosa", "sha": "2d808236e71f2289033dff6b74a3f57311df9a14", "save_path": "github-repos/coq/aspiwack-cosa", "path": "github-repos/coq/aspiwack-cosa/cosa-2d808236e71f2289033dff6b74a3f57311df9a14/Shape/Graph.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.2709296570984265}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VFA.Maps.\nRequire Import VFA.SearchTree.\nRequire Import WandDemo.SearchTree_ext.\nRequire Import WandDemo.bst.\nRequire Import WandDemo.bst_lemmas.\nRequire Import WandDemo.VST_lemmas.\nRequire Import WandDemo.spec_bst.\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\nLtac simpl_compb := first [ rewrite if_trueb by (apply NPeano.Nat.ltb_lt; rewrite Nat2Z.inj_lt; omega)\n                          | rewrite if_falseb by (apply NPeano.Nat.ltb_nlt; rewrite Nat2Z.inj_lt; omega)].\n\nImport PartialTreeRep_WandQFrame_Func_Hole.\n\nDefinition lookup_inv (p0: val) (t0: tree val) (x: nat): environ -> mpred :=\n  EX p: val, EX t: tree val, EX P: tree val -> tree val,\n  PROP(lookup nullval x t = lookup nullval x t0; P t = t0)\n  LOCAL(temp _p p; temp _x (Vint (Int.repr (Z.of_nat x))))\n  SEP(tree_rep t p; partial_tree_rep P p0 p).\n\nOpaque tree_rep.\nArguments tree_rep: simpl never.\n\nLemma body_lookup: semax_body Vprog Gprog f_lookup lookup_spec.\nProof.\n  start_function.\n  unfold Map_rep.\n  Intros t0.\n  apply (semax_post'' (PROP () LOCAL (temp ret_temp (lookup nullval x t0)) SEP (tree_rep t0 p0))); auto.\n  {\n    unfold Map_rep.\n    Exists t0.\n    entailer!.\n    symmetry; apply lookup_relate; auto.\n  }\n  clear H0 H1.\n  forward_while (lookup_inv p0 t0 x).\n  * (* precondition implies loop invariant *)\n    Exists p0 t0 (fun t: tree val => t). entailer!.\n    apply emp_partial_tree_rep_H.\n  * (* type-check loop condition *)\n    entailer!.\n  * (* loop body preserves invariant *)\n    destruct t; rewrite tree_rep_spec at 1. normalize.\n    Intros qa qb.\n    forward.\n    forward_if; [ | forward_if ].\n    + (* then clause: x<y *)\n      forward. (* q=q<-left *)\n      Exists (qa, t1, fun t1 => P (T t1 k v0 t2)). unfold fst,snd.\n      entailer!.\n      - rewrite <- H0; simpl.\n        simpl_compb; auto.\n      - sep_apply (partial_tree_rep_singleton_left t2 k v0 p qa qb); auto.\n        apply partial_tree_rep_partial_tree_rep.\n    + (* else-then clause: y<x *)\n      forward. (* q=q<-right *)\n      Exists (qb,t2, fun t2 => P (T t1 k v0 t2)). unfold fst,snd.\n      entailer!.\n      - rewrite <- H0; simpl.\n        simpl_compb; simpl_compb; auto.\n      - sep_apply (partial_tree_rep_singleton_right t1 k v0 p qa qb); auto.\n        apply partial_tree_rep_partial_tree_rep.\n    + (* else-else clause: x=y *)\n      assert (x=k) by omega. subst x. clear H H4 H5.\n      forward. (* v=q->value *)\n      forward. (* return v; *)\n      entailer!.\n      - rewrite <- H0; simpl.\n        simpl_compb; simpl_compb; auto.\n      - sep_apply (tree_rep_internal t1 k v0 t2 p qa qb); auto.\n        apply tree_rep_partial_tree_rep.\n  * (* after the loop *)\n    forward. (* return NULL; *)\n    entailer!.\n    apply tree_rep_partial_tree_rep.\nQed.\n\nLemma body_turn_left: semax_body Vprog Gprog f_turn_left turn_left_spec.\nProof.\n  start_function.\n  rewrite (tree_rep_spec (T _ _ _ _)).\n  Intros pb pc.\n  forward. (* mid=r->left *)\n  forward. (* l->right=mid *)\n  forward. (* r->left=l *)\n  forward. (* _l = r *)\n  forward. (* return *)\n  (* TODO: simplify the following proof *)\n  Exists pc.\n  entailer!.\n  rewrite (tree_rep_spec (T _ _ _ _)).\n  Exists pa pb.\n  entailer!.\nQed.\n\nImport PartialTreeboxRep_WandQFrame_Func_Hole.\n\nDefinition pushdown_left_inv (b_res: val) (t_res: tree val): environ -> mpred :=\n  EX b: val, EX ta: tree val, EX x: nat, EX v: val, EX tb: tree val, EX P: tree val -> tree val,\n  PROP  (P (pushdown_left ta tb) = t_res)\n  LOCAL (temp _t b)\n  SEP   (treebox_rep (T ta x v tb) b; partial_treebox_rep P b_res b).\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)).\n  + (* Precondition *)\n    unfold pushdown_left_inv.\n    Exists b ta x v tb (fun t: tree val => t).\n    entailer!.\n    sep_apply (treebox_rep_internal ta x v tb b p); auto.\n    entailer!.\n    apply emp_partial_treebox_rep_H.\n  + (* Loop body *)\n    unfold pushdown_left_inv.\n    clear x v H H0.\n    Intros b0 ta0 x vx tbc0 P.\n    rewrite treebox_rep_tree_rep.\n    Intros p0.\n    forward. (* p = *t; *)\n    rewrite tree_rep_spec.\n    Intros pa pbc.\n    forward. (* q = p->right *)\n    forward_if.\n    - subst.\n      assert_PROP (tbc0 = (@E _)).\n        1: entailer!.\n      subst.\n      forward. (* q=p->left *)\n      forward. (* *t=q *)\n      forward_call (p0, sizeof t_struct_tree). (* freeN(p, sizeof ( *p )); *)\n      {\n        entailer!.\n        rewrite memory_block_data_at_ by auto.\n        cancel.\n      }\n      forward. (* return *)\n      rewrite (tree_rep_spec E).\n      rewrite <- H.\n      eapply derives_trans; [| apply (treebox_rep_partial_treebox_rep _ _ b0)].\n      entailer!.\n      simpl.\n      rewrite treebox_rep_tree_rep.\n      Exists pa.\n      cancel.\n    - destruct tbc0 as [| tb0 y vy tc0].\n        { rewrite (tree_rep_spec E). normalize. }\n      forward_call (ta0, x, vx, tb0, y, vy, tc0, b0, p0, pa, pbc). (* turn_left(t, p, q); *)\n      Intros pc.\n      forward. (* t = &q->left; *) simpl in H.\n      Exists (field_address t_struct_tree [StructField _left] pbc) ta0 x vx tb0 (fun t => P (T t y vy tc0)).\n      entailer!.\n      unfold_data_at (data_at _ _ _ pbc).\n      rewrite (treebox_rep_tree_rep (T _ _ _ _)). Exists p0. rewrite (field_at_data_at _ _ [StructField _left]); cancel.\n      eapply derives_trans; [| apply (partial_treebox_rep_partial_treebox_rep _ _ _ b0)].\n      cancel.\n      eapply derives_trans; [| apply partial_treebox_rep_singleton_left; auto].\n      cancel.\n      rewrite treebox_rep_tree_rep. Exists pc. rewrite field_at_data_at; cancel.\nQed.\n\nDefinition delete_inv (b0: val) (t0: tree val) (x: nat): environ -> mpred :=\n  EX b: val, EX t: tree val, EX P: tree val -> tree val,\n  PROP(P (delete x t) = delete x t0)\n  LOCAL(temp _t b; temp _x (Vint (Int.repr (Z.of_nat x))))\n  SEP(treebox_rep t b; partial_treebox_rep P b0 b).\n\nLemma body_delete: semax_body Vprog Gprog f_delete delete_spec.\nProof.\n  start_function.\n  forward_loop (delete_inv b t x).\n  * (* Precondition *)\n    unfold delete_inv.\n    Exists b t (fun t: tree val => t). entailer!.\n    apply emp_partial_treebox_rep_H.\n  * (* Loop body *)\n    unfold delete_inv.\n    Intros b1 t1 P.\n    rewrite treebox_rep_tree_rep. Intros p1.\n    forward. (* p = *t; *)\n    forward_if.\n    + (* then clause *)\n      subst p1.\n      assert_PROP (t1= (@E _)).\n        1: entailer!.\n      subst t1. rewrite (tree_rep_spec E). rewrite !prop_true_andp by auto.\n      forward. (* return; *)\n      rewrite <- H0.\n      eapply derives_trans; [| apply (treebox_rep_partial_treebox_rep _ _ b1); auto].\n      cancel.\n      rewrite treebox_rep_spec; Exists nullval; simpl.\n      entailer!.\n    + (* else clause *)\n      destruct t1.\n        { rewrite (tree_rep_spec E). normalize. }\n      rewrite tree_rep_treebox_rep; Intros.\n      clear H1.\n      forward. (* y=p->key; *)\n      forward_if; [ | forward_if ].\n      - (* Inner if, then clause: x<k *)\n        forward. (* t=&p->left *)\n        unfold delete_inv.\n        Exists (field_address t_struct_tree [StructField _left] p1) t1_1 (fun t => P (T t k v t1_2)).\n        entailer!.\n       ** rewrite <- H0.\n          simpl; simpl_compb; auto.\n       ** sep_apply (partial_treebox_rep_singleton_left t1_2 k v p1 b1); auto.\n          apply partial_treebox_rep_partial_treebox_rep.\n      - (* Inner if, second branch:  k<x *)\n        forward. (* t=&p->right *)\n        unfold delete_inv.\n        Exists (field_address t_struct_tree [StructField _right] p1) t1_2 (fun t => P (T t1_1 k v t)).\n        entailer!.\n       ** rewrite <- H0.\n          simpl; simpl_compb; simpl_compb; auto.\n       ** sep_apply (partial_treebox_rep_singleton_right t1_1 k v p1 b1); auto.\n          apply partial_treebox_rep_partial_treebox_rep.\n      - (* Inner if, third branch: x=k *)\n        assert (x=k) by omega.\n        subst x.\n        forward_call (t1_1, k, v, t1_2, b1, p1).\n        forward. (* return *)\n        rewrite <- H0.\n        simpl; simpl_compb; simpl_compb.\n        apply treebox_rep_partial_treebox_rep.\nQed.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/wand_demo/wand_demo/verif_bst_other.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2709296570984265}}
{"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   Some K Lemmas.\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_Ok_Lemmas Cyclone_LN_Types_Lemmas.\nRequire Export Cyclone_Fset_Lemmas Cyclone_Get_Lemmas.\nRequire Export Cyclone_WFD_Lemmas.\nClose Scope list_scope.\nImport LibEnvNotations.\nImport LVPE.LibVarPathEnvNotations.\n\nLemma K_weakening:\n  forall tau d,\n    K d tau A ->\n    forall d',\n      WFD d ->\n      extends d d' ->\n      K d'     tau A.\nProof.\n  introv Kempty.\n  induction Kempty; try solve[auto].\n  intros.\n  apply_fresh K_utype; intros.\n  assert(I: y \\notin L); auto.\n  intros.\n  apply_fresh K_etype; intros.\n  assert(I: y \\notin L); auto.\nQed.  \n\nLemma K_empty_var:\n  forall v k, \n    K empty (ftvar v) k -> False.\nProof.\n  intros.\n  inversions H.\n  rewrite get_empty in H2.\n  inversion H2.\n  inversions H0.\n  rewrite get_empty in H2.\n  inversion H2.\nQed.\nHint Immediate K_empty_var.\n\n(* I need a stronger lemma, = or to rewrite. *)\n\nLemma open_var_fv_eq : forall t n x,\n    T.fv (T.open_rec n (ftvar x) t) = (T.fv t \\u \\{x}) \\/\n    T.fv (T.open_rec n (ftvar x) t) = (T.fv t).\nProof.\n  intros t.\n  induction t; intros; simpl; try case_nat; auto with fset;\n  try solve[\n        simpl;\n        left;\n        rewrite union_empty_l;\n        auto with fset].\n(* Bug ugly won't ltac. *)\n\n  specialize(IHt1 n x);\n  specialize(IHt2 n x);\n  inversion IHt1; inversion IHt2;\n  rewrite H; rewrite H0.\n  left.\n  rewrite <- union_assoc.\n  rewrite <- union_assoc.\n  rewrite* union_middle_shuffle.\n  left.\n  rewrite <- union_assoc.\n  rewrite <- union_assoc.\n  rewrite* union_middle_r.\n  left.\n  rewrite* <- union_assoc.  \n  right*.\n\n  specialize(IHt1 n x);\n  specialize(IHt2 n x);\n  inversion IHt1; inversion IHt2;\n  rewrite H; rewrite H0.\n  left.\n  rewrite <- union_assoc.\n  rewrite <- union_assoc.\n  rewrite* union_middle_shuffle.\n  left.\n  rewrite <- union_assoc.\n  rewrite <- union_assoc.\n  rewrite* union_middle_r.\n  left.\n  rewrite* <- union_assoc.  \n  right*.  \nQed.  \n\nLemma fv_var:\n  forall A alpha tau (d : env A), \n    alpha \\notin T.fv tau ->\n    T.fv tau \\c \\{ alpha} \\u dom d ->\n    T.fv tau \\c dom d.\nProof.\n  intros.\n  induction tau; simpl; simpl in H; simpl in H0; auto with fset.\n  assert(alpha <> v); auto.\n  lets: subset_remove_r (fset Tau).\n  apply subset_remove_r with (b:= alpha); auto.\n  assert(alpha \\notin T.fv tau1); auto.\n  assert(alpha \\notin T.fv tau2); auto.\n  specialize (IHtau1 H1).\n  specialize (IHtau2 H2).\n  assert(H3 : (T.fv tau1 \\u T.fv tau2 \\c \\{ alpha} \\u dom d)); auto.\n  apply subset_remove_l_r in H0.  \n  apply subset_remove_l_l in H3.\n  auto with fset.\n\n  assert(H3 : (T.fv tau1 \\u T.fv tau2 \\c \\{ alpha} \\u dom d)); auto.\n  apply subset_remove_l_r in H0.  \n  apply subset_remove_l_l in H3.\n  auto with fset.  \nQed.  \n\nLemma fv_var_2:\n  forall A alpha tau (d : env A), \n    alpha \\notin T.fv tau ->\n    T.fv tau \\u \\{ alpha} \\c \\{ alpha} \\u dom d ->\n    T.fv tau \\c dom d.\nProof.\n  intros.\n  apply subset_remove_l_r in H0.\n  apply fv_var with (alpha:= alpha); auto.\nQed.\n\nLemma K_fv:\n  forall tau d k,\n    WFD d ->\n    K d tau k ->\n    T.fv tau \\c fv_delta d.\nProof.\n(* BUG ugly, repetition, will not ltac *)\n  introv WFDd Kd.\n  induction Kd; assert(ok d); auto; try solve[simpl; auto with fset].\n\n  pick_fresh alpha.\n  assert(NI: alpha \\notin L); auto.\n  assert(OKda: ok(d & alpha ~ k)); auto.\n  assert(WFDda: WFD(d & alpha ~k)); auto.\n  specialize (H0 alpha NI OKda WFDda).\n  lets: open_var_fv_eq tau 0 alpha.\n  inversion H2.\n  rewrite H3 in H0.\n  unfold fv_delta.\n  unfold fv_delta in H0.\n  rewrite dom_push in H0.\n  apply fv_var_2 with (alpha:=alpha); auto.\n  rewrite H3 in H0.\n  unfold fv_delta in H0.\n  unfold fv_delta.\n  apply fv_var with (alpha:= alpha); auto.\n  unfold fv_delta in H0.\n  unfold fv_delta.\n  rewrite dom_push in H0.\n  auto.  \n\n  pick_fresh alpha.\n  assert(NI: alpha \\notin L); auto.\n  assert(OKda: ok(d & alpha ~ k)); auto.\n  assert(WFDda: WFD(d & alpha ~k)); auto.\n  specialize (H0 alpha NI OKda WFDda).\n  lets: open_var_fv_eq tau 0 alpha.\n  inversion H2.\n  rewrite H3 in H0.\n  unfold fv_delta.\n  unfold fv_delta in H0.\n  rewrite dom_push in H0.\n  apply fv_var_2 with (alpha:=alpha); auto.\n  rewrite H3 in H0.\n  unfold fv_delta in H0.\n  unfold fv_delta.\n  apply fv_var with (alpha:= alpha); auto.\n  unfold fv_delta in H0.\n  unfold fv_delta.\n  rewrite dom_push in H0.\n  auto.  \nQed.\n\nLemma K_empty_closed:\n  forall tau k,\n    K empty tau k ->\n    T.fv tau = \\{}.\nProof.\n  intros.\n  lets: K_fv tau (@empty Kappa).\n  apply H0 in H.\n  unfold fv_delta in H.\n  rewrite dom_empty in H.\n  apply contained_in_empty in H; auto.\n  auto.\nQed.\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.5/Cyclone_K_Lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.270916620841027}}
{"text": "Require config.\nRequire Import config_tactics.\n\nRequire Import syntax.\nRequire Import tt.\nRequire ptt ett.\n\nSection Ptt2Ett.\n\nContext `{configReflection : config.Reflection}.\nContext `{configBinaryProdType : config.BinaryProdType}.\nContext `{configProdEta : config.ProdEta}.\nContext `{configUniverses : config.Universes}.\nContext `{configPropType : config.PropType}.\nContext `{configIdType : config.IdType}.\nContext `{configIdEliminator : config.IdEliminator}.\nContext `{configEmptyType : config.EmptyType}.\nContext `{configUnitType : config.UnitType}.\nContext `{configBoolType : config.BoolType}.\nContext `{configProdType : config.ProdType}.\nContext `{configSyntax : syntax.Syntax}.\n\nFixpoint sane_isctx G (P : ptt.isctx G) : ett.isctx G\n\nwith sane_issubst sbs G D (P : ptt.issubst sbs G D) {struct P} : ett.issubst sbs G D\n\nwith sane_istype G A (P : ptt.istype G A) {struct P} : ett.istype G A\n\nwith sane_isterm G u A (P : ptt.isterm G u A) {struct P} : ett.isterm G u A\n\nwith sane_eqctx G D (P : ptt.eqctx G D) {struct P} : ett.eqctx G D\n\nwith sane_eqsubst sbs sbt G D (P : ptt.eqsubst sbs sbt G D) {struct P} : ett.eqsubst sbs sbt G D\n\nwith sane_eqtype G A B (P : ptt.eqtype G A B) {struct P} : ett.eqtype G A B\n\nwith sane_eqterm G u v A (P : ptt.eqterm G u v A) {struct P} : ett.eqterm G u v A.\n\nProof.\n  all:unfold ett.isctx in *.\n  all:unfold ett.issubst in *.\n  all:unfold ett.istype in *.\n  all:unfold ett.isterm in *.\n  all:unfold ett.eqctx in *.\n  all:unfold ett.eqsubst in *.\n  all:unfold ett.eqtype in *.\n  all:unfold ett.eqterm in *.\n\n  (* sane_isctx *)\n  - { destruct P; doConfig.\n      - now apply CtxEmpty.\n      - capply CtxExtend. auto.\n    }\n\n  (* sane_issubst *)\n  - { destruct P; doConfig.\n\n      (* SubstZero *)\n      - capply SubstZero ; auto.\n\n      (* SubstWeak *)\n      - capply SubstWeak ; auto.\n\n      (* SubstShift *)\n      - { capply SubstShift ; auto. }\n\n      (* SubstId *)\n      - capply SubstId ; auto.\n\n      (* SubstComp *)\n       - { config apply @SubstComp with (D := D) ; auto. }\n\n       (* SubstTerminal *)\n       - { capply SubstTerminal ; auto. }\n\n      (* SubstCtxConv *)\n      - { config apply @SubstCtxConv with (G1 := G1) (D1 := D1) ; auto. }\n  }\n\n  (* sane_istype *)\n  - { destruct P; doConfig.\n\n      (* TyCtxConv *)\n      - config apply @TyCtxConv with (G := G) ; auto.\n\n      (* TySubst *)\n      - config apply @TySubst with (D := D) ; auto.\n\n      (* TyProd *)\n      - capply TyProd ; auto.\n\n      (* TyId *)\n      - capply TyId ; auto.\n\n      (* TyEmpty *)\n      - capply TyEmpty ; auto.\n\n      (* TyUnit *)\n      - capply TyUnit ; auto.\n\n      (* TyBool *)\n      - capply TyBool ; auto.\n\n      (* TyBinaryProd *)\n      - capply TyBinaryProd ; auto.\n\n      (* TyUni *)\n      - capply TyUni ; auto.\n\n      (* TyEl *)\n      - ceapply TyEl ; eauto.\n  }\n\n  (* sane_isterm *)\n  - { destruct P; doConfig.\n\n      (* TermTyConv *)\n       - apply @TermTyConv with (A := A) ; auto.\n\n      (* TermCtxConv *)\n      - apply @TermCtxConv with (G := G) ; auto.\n\n      (* TermSubst *)\n      - apply @TermSubst with (D := D) ; auto.\n\n      (* TermVarZero *)\n      - apply TermVarZero ; auto.\n\n      (* TermVarSucc *)\n      - apply TermVarSucc ; auto.\n\n      (* TermAbs *)\n      - apply TermAbs ; auto.\n\n      (* TermApp *)\n      - apply TermApp ; auto.\n\n      (* TermRefl *)\n      - apply TermRefl ; auto.\n\n      (* TermJ *)\n      - apply TermJ ; auto.\n\n      (* TermExfalso *)\n      - apply TermExfalso ; auto.\n\n      (* TermUnit *)\n      - apply TermUnit ; auto.\n\n      (* TermTrue *)\n      - apply TermTrue ; auto.\n\n      (* TermFalse *)\n      - apply TermFalse ; auto.\n\n      (* TermCond *)\n      - apply TermCond ; auto.\n\n      (* TermPair *)\n      - apply TermPair ; auto.\n\n      (* TermProjOne *)\n      - apply TermProjOne ; auto.\n\n      (* TermProjTwo *)\n      - apply TermProjTwo ; auto.\n\n      (* TermUniProd *)\n      - apply TermUniProd ; auto.\n\n      (* TermUniProdProp *)\n      - apply TermUniProdProp ; auto.\n\n      (* TermUniId *)\n      - apply TermUniId ; auto.\n\n      (* TermUniEmpty *)\n      - apply TermUniEmpty ; auto.\n\n      (* TermUniUnit *)\n      - apply TermUniUnit ; auto.\n\n      (* TermUniBool *)\n      - apply TermUniBool ; auto.\n\n      (* TermUniBinaryProd *)\n      - apply TermUniBinaryProd ; auto.\n\n      (* TermUniBinaryProdProp *)\n      - apply TermUniBinaryProdProp ; auto.\n\n      (* TermUniUni *)\n      - apply TermUniUni ; auto.\n\n      (* TermUniProp *)\n      - apply TermUniProp ; auto.\n  }\n\n  (* sane_eqctx *)\n  - { destruct P; doConfig.\n\n      (* CtxRefl *)\n      - apply CtxRefl ; auto.\n\n      (* CtxSym *)\n      - apply CtxSym ; auto.\n\n      (* CtxTrans *)\n      - apply @CtxTrans with (D := D) ; auto.\n\n      (* EqCtxEmpty *)\n      - apply CtxRefl, CtxEmpty.\n\n      (* EqCtxExtend *)\n      - apply EqCtxExtend ; auto.\n  }\n\n  (* sane_eqsubst *)\n  - { destruct P; doConfig.\n\n      (* SubstRefl *)\n      - apply SubstRefl ; auto.\n\n      (* SubstSym *)\n      - apply SubstSym ; auto.\n\n      (* SubstTrans *)\n      - apply @SubstTrans with (sb2 := sb2) ; auto.\n\n      (* CongSubstZero *)\n      - apply @CongSubstZero with (G := G) ; auto.\n\n      (* CongSubstWeak *)\n      - apply CongSubstWeak ; auto.\n\n      (* CongSubstShift *)\n      - apply CongSubstShift ; auto.\n\n      (* CongSubstComp *)\n      - apply @CongSubstComp with (D := D) ; auto.\n\n      (* EqSubstCtxConv *)\n      - apply @EqSubstCtxConv with (G1 := G1) (D1 := D1) ; auto.\n\n      (* CompAssoc *)\n      - apply @CompAssoc with (D := D) (E := E) ; auto.\n\n      (* WeakNat *)\n      - apply WeakNat ; auto.\n\n      (* WeakZero *)\n      - apply WeakZero ; auto.\n\n      (* ShiftZero *)\n      - apply ShiftZero ; auto.\n\n      (* CompShift *)\n      - apply @CompShift with (D := D) ; auto.\n\n      (* CompIdRight *)\n      - apply CompIdRight ; auto.\n\n      (* CompIdLeft *)\n      - apply CompIdLeft ; auto.\n  }\n\n  (* sane_eqtype *)\n  - { destruct P; doConfig.\n\n      (* EqTyCtxConv *)\n      - apply @EqTyCtxConv with (G := G) ; auto.\n\n      (* EqTyRefl*)\n      - apply EqTyRefl ; auto.\n\n      (* EqTySym *)\n      - apply EqTySym ; auto.\n\n      (* EqTyTrans *)\n      - apply @EqTyTrans with (B := B) ; auto.\n\n      (* EqTyIdSubst *)\n      - apply EqTyIdSubst ; auto.\n\n      (* EqTySubstComp *)\n      - apply @EqTySubstComp with (D := D) (E := E) ; auto.\n\n      (* EqTySubstProd *)\n      - apply @EqTySubstProd with (D := D) ; auto.\n\n      (* EqTySubstId *)\n      - apply @EqTySubstId with (D := D) ; auto.\n\n      (* EqTySubstEmpty *)\n      - apply @EqTySubstEmpty with (D := D) ; auto.\n\n      (* EqTySubstUnit *)\n      - apply @EqTySubstUnit with (D := D) ; auto.\n\n      (* EqTySubstBool *)\n      - apply @EqTySubstBool with (D := D) ; auto.\n\n      (* EqTyExfalso *)\n      - apply @EqTyExfalso with (u := u) ; auto.\n\n      (* CongProd *)\n      - apply CongProd ; auto.\n\n      (* CongId *)\n      - apply CongId ; auto.\n\n      (* CongTySubst *)\n      - apply @CongTySubst with (D := D) ; auto.\n\n      (* CongBinaryProd *)\n      - apply CongBinaryProd ; auto.\n\n      (* EqTySubstBinaryProd *)\n      - apply @EqTySubstBinaryProd with (D := D) ; auto.\n\n      (* EqTySubstUni *)\n      - apply @EqTySubstUni with (D := D) ; auto.\n\n      (* ElProd *)\n      - eapply ElProd ; eauto.\n\n      (* ElProdProp *)\n      - eapply ElProdProp ; eauto.\n\n      (* ElId *)\n      - eapply ElId ; eauto.\n\n      (* ElSubst *)\n      - eapply ElSubst ; eauto.\n\n      (* ElEmpty *)\n      - eapply ElEmpty ; eauto.\n\n      (* ElUnit *)\n      - eapply ElUnit ; eauto.\n\n      (* ElBool *)\n      - eapply ElBool ; eauto.\n\n      (* ElBinaryProd *)\n      - eapply ElBinaryProd ; eauto.\n\n      (* ElBinaryProdProp *)\n      - eapply ElBinaryProdProp ; eauto.\n\n      (* ElUni *)\n      - apply ElUni ; auto.\n\n      (* ElProp *)\n      - apply ElProp ; auto.\n\n      (* CongEl *)\n      - eapply CongEl ; eauto.\n  }\n\n  (* sane_eqterm *)\n  - { destruct P ; doConfig.\n\n      (* EqTyConv *)\n      - apply @EqTyConv with (A := A) ; auto.\n\n      (* EqCtxConv *)\n      - apply @EqCtxConv with (G := G) ; auto.\n\n      (* EqRefl *)\n      - apply EqRefl ; auto.\n\n      (* EqSym *)\n      - apply EqSym ; auto.\n\n      (* EqTrans *)\n      - apply @EqTrans with (v := v) ; auto.\n\n      (* EqIdSubst *)\n      - apply EqIdSubst ; auto.\n\n      (* EqSubstComp *)\n      - apply @EqSubstComp with (D := D) (E := E) ; auto.\n\n      (* EqSubstWeak *)\n      - apply EqSubstWeak ; auto.\n\n\n      (* EqSubstZeroZero *)\n      - apply EqSubstZeroZero ; auto.\n\n      (* EqSubstZeroSucc *)\n      - apply EqSubstZeroSucc ; auto.\n\n      (* EqSubstShiftZero *)\n      - apply @EqSubstShiftZero with (D := D) ; auto.\n\n      (* EqSubstShiftSucc *)\n      - apply @EqSubstShiftSucc with (D := D) ; auto.\n\n      (* EqSubstAbs *)\n      - apply @EqSubstAbs with (D := D) ; auto.\n\n      (* EqSubstApp *)\n      - apply @EqSubstApp with (D := D) ; auto.\n\n      (* EqSubstRefl *)\n      - apply @EqSubstRefl with (D := D) ; auto.\n\n      (* EqSubstJ *)\n      - apply @EqSubstJ with (D := D) ; auto.\n\n     (* This rule is subsumed by EqTermExfalso *)\n      (* EqSubstExfalso *)\n      - apply @EqSubstExfalso with (D := D) ; auto.\n\n      (* EqSubstUnit *)\n      - apply @EqSubstUnit with (D := D) ; auto.\n\n      (* EqSubstTrue *)\n      - apply @EqSubstTrue with (D := D) ; auto.\n\n      (* EqSubstFalse *)\n      - apply @EqSubstFalse with (D := D) ; auto.\n\n      (* EqSubstCond *)\n      - apply @EqSubstCond with (D := D) ; auto.\n\n      (* EqTermExfalso *)\n      - apply @EqTermExfalso with (w := w) ; auto.\n\n      (* UnitEta *)\n      - apply UnitEta ; auto.\n\n      (* EqReflection *)\n      - apply @EqReflection with (p := p) ; auto.\n\n      (* ProdBeta *)\n      - apply ProdBeta ; auto.\n\n      (* CondTrue *)\n      - apply CondTrue ; auto.\n\n      (* CondFalse *)\n      - apply CondFalse ; auto.\n\n      (* ProdEta *)\n      - apply ProdEta ; auto.\n\n      (* JRefl *)\n      - apply JRefl ; auto.\n\n      (* CongAbs *)\n      - apply CongAbs ; auto.\n\n      (* CongApp *)\n      - apply CongApp ; auto.\n\n      (* CongRefl *)\n      - apply CongRefl ; auto.\n\n      (* CongJ *)\n      - apply CongJ ; auto.\n\n      (* CongCond *)\n      - apply CongCond ; auto.\n\n      (* CongTermSubst *)\n      - apply @CongTermSubst with (D := D) ; auto.\n\n      (* CongPair *)\n      - apply CongPair ; auto.\n\n      (* CongProjOne *)\n      - apply CongProjOne ; auto.\n\n      (* CongProjTwo *)\n      - apply CongProjTwo ; auto.\n\n      (* EqSubstPair *)\n      - apply @EqSubstPair with (D := D) ; auto.\n\n      (* EqSubstProjOne *)\n      - apply @EqSubstProjOne with (D := D) ; auto.\n\n      (* EqSubstProjTwo *)\n      - apply @EqSubstProjTwo with (D := D) ; auto.\n\n      (* ProjOnePair *)\n      - apply ProjOnePair ; auto.\n\n      (* ProjTwoPair *)\n      - apply ProjTwoPair ; auto.\n\n      (* PairEta *)\n      - apply PairEta ; auto.\n\n      (* EqSubstUniProd *)\n      - apply @EqSubstUniProd with (D := D) ; auto.\n\n      (* EqSubstUniProdProp *)\n      - apply @EqSubstUniProdProp with (D := D) ; auto.\n\n      (* EqSubstUniId *)\n      - apply @EqSubstUniId with (D := D) ; auto.\n\n      (* EqSubstUniEmpty *)\n      - apply @EqSubstUniEmpty with (D := D) ; auto.\n\n      (* EqSubstUniUnit *)\n      - apply @EqSubstUniUnit with (D := D) ; auto.\n\n      (* EqSubstUniBool *)\n      - apply @EqSubstUniBool with (D := D) ; auto.\n\n      (* EqSubstUniBinaryProd *)\n      - apply @EqSubstUniBinaryProd with (D := D) ; auto.\n\n      (* EqSubstUniBinaryProdProp *)\n      - apply @EqSubstUniBinaryProdProp with (D := D) ; auto.\n\n      (* EqSubstUniUni *)\n      - apply @EqSubstUniUni with (D := D) ; auto.\n\n      (* EqSubstUniProp *)\n      - apply @EqSubstUniProp with (D := D) ; auto.\n\n      (* CongUniProd *)\n      - apply CongUniProd ; auto.\n\n      (* CongUniProdProp *)\n      - apply CongUniProdProp ; auto.\n\n      (* CongUniId *)\n      - apply CongUniId ; auto.\n\n      (* CongUniBinaryProd *)\n      - apply CongUniBinaryProd ; auto.\n\n      (* CongUniBinaryProdProp *)\n      - apply CongUniBinaryProdProp ; auto.\n    }\nDefined.\n\nEnd Ptt2Ett.", "meta": {"author": "TheoWinterhalter", "repo": "formal-type-theory", "sha": "93ac197dfde912d77af9b0f4fd9f7d2422ba7dfc", "save_path": "github-repos/coq/TheoWinterhalter-formal-type-theory", "path": "github-repos/coq/TheoWinterhalter-formal-type-theory/formal-type-theory-93ac197dfde912d77af9b0f4fd9f7d2422ba7dfc/src/ptt2ett.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.27091660852924493}}
{"text": "Require Export MinBFTinv.\nRequire Export MinBFTprops2.\nRequire Export MinBFTrun.\n\n\nSection MinBFTass_new.\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  Opaque KE_TOWNS.\n  Opaque KE_ID_BEFORE.\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    unfold ui_has_counter in h.\n    repnd; 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 h1; ginv.\n    rewrite h2 in h0; ginv.\n    unfold disseminate_data in *; exrepnd; simpl in *.\n\n    unfold M_byz_state_sys_on_event in *; simpl in *.\n    unfold M_byz_state_sys_before_event in *; simpl in *.\n    unfold M_byz_output_sys_on_event in *.\n    revert dependent o.\n    rewrite h2 in *; simpl in *.\n    introv out dout.\n\n    applydup preserves_usig_id in h4 as eqid; auto;[].\n\n    (*pose proof (M_byz_compose_step_trusted e (MinBFTlocalSys c2) (incr_n_proc (USIG_comp c2))) as h.\n    repeat (autodimp h hyp); eauto 3 with minbft.\n    exrepnd; simpl in *.*)\n\n    rewrite M_byz_output_ls_on_event_as_run in out; simpl in *.\n\n    apply map_option_Some in h4; exrepnd; rev_Some; simpl in *; minbft_simp.\n    apply map_option_Some in h5; exrepnd; rev_Some; simpl in *; minbft_simp.\n\n    rewrite M_byz_run_ls_on_event_unroll2 in h1; simpl in *.\n\n    match goal with\n    | [ H : context[M_byz_run_ls_before_event ?ls ?e] |- _ ] =>\n      remember (M_byz_run_ls_before_event ls e) as run; symmetry in Heqrun\n    end.\n    apply M_byz_run_ls_before_event_ls_is_minbft in Heqrun.\n    repndors; exrepnd; subst; simpl in *.\n\n    { unfold M_byz_output_ls_on_this_one_event in *; simpl in *.\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      unfold M_byz_run_ls_on_input in *; simpl in *.\n      unfold data_is_in_out, event2out in *; simpl in *.\n\n      remember (trigger e) as trig; symmetry in Heqtrig.\n      destruct trig; simpl in *; tcsp.\n\n      { match goal with\n        | [ H : context[M_run_ls_on_input ?ls ?cn ?i] |- _ ] =>\n          remember (M_run_ls_on_input ls cn i) as oni; symmetry in Heqoni\n        end.\n        repnd; simpl in *; subst; simpl in *; minbft_simp.\n        applydup (M_run_ls_on_input_ls_is_minbft_new (msg_comp_name 0)) in Heqoni.\n        exrepnd; subst; simpl in *; ginv; simpl in *.\n        apply in_flat_map in dout; exrepnd; simpl in *.\n\n        unfold M_run_ls_on_input in *; simpl in *.\n        autorewrite with minbft in *; simpl in *.\n\n        Time minbft_dest_msg Case;\n          repeat (simpl in *; autorewrite with minbft in *; smash_minbft2); repndors; smash_minbft2;\n            unfold lower_out_break in *; simpl in *; minbft_simp;\n            repeat (repndors; ginv; subst; tcsp; simpl in *; tcsp);\n            unfold ui_has_counter, ui2counter, state_of_trusted in *; simpl in *;\n              try (eexists; dands;[| | |right;eauto|]; simpl; auto; try omega);\n              try (rename_hyp_with invalid_prepare inv);\n              try (complete (eapply data_is_owned_by_invalid_prepare_implies_false in inv; eauto; tcsp));\n              try (rename_hyp_with invalid_commit invc);\n              try (eapply data_is_owned_by_invalid_commit_not_pil_implies_false in invc; eauto; tcsp);\n              remember (usig_counters u) as K; destruct K; simpl in *; tcsp;\n                destruct n; simpl in *; tcsp; try omega;\n                  try (complete (f_equal; apply Max.max_l; try omega));\n                  try (complete (left; dands; try omega; apply les_reflexive));\n                  try (complete (left; dands; try apply les_reflexive; apply lt_n_S; apply Nat.max_lt_iff; left; try omega)). }\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        unfold ui_has_counter, ui2counter, state_of_trusted in *; simpl in *.\n        eexists; dands;[| | |right;eauto|]; simpl; auto; try omega; eauto 3 with minbft. } }\n\n    { unfold M_byz_output_ls_on_this_one_event in *; simpl in *.\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      unfold M_byz_run_ls_on_input in *; simpl in *.\n      unfold data_is_in_out, event2out in *; simpl in *.\n\n      remember (trigger e) as trig; symmetry in Heqtrig.\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      unfold ui_has_counter, ui2counter, state_of_trusted in *; simpl in *.\n      eexists; dands;[| | |right;eauto|]; simpl; auto; try omega; eauto 3 with minbft. }\n  Qed.\n  Hint Resolve ASSUMPTION_generates_new_true : minbft.\n\nEnd MinBFTass_new.\n\n\nHint Resolve ASSUMPTION_generates_new_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_new.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804196836382, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2709166085292448}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\nRequire Import Program.\nRequire Import Arith.\nRequire Import Permutation.\nRequire Import SetoidList.\nRequire Import SetoidPermutation.\nRequire Import Lists.List.\nRequire Import Lia.\nFrom Fairness Require Import\n  Mod\n  FairSim\n  Concurrency\n  FIFOSched\n  SchedSim.\nFrom ExtLib Require Import FMapAList.\n\nSection SIM.\n\n  Context {_Ident : ID}.\n\n  Variable wf : WF.\n  Variable State : Type.\n  Variable R : Type.\n\n  Let thread R := thread _Ident (sE State) R.\n  Import Th.\n\n  Theorem ssim_nondet_fifo\n    p_src p_tgt tid ths_src ths_tgt\n    (THREADS : Permutation (TIdSet.elements ths_src) ths_tgt)\n    (TID : ~ NatMap.In tid ths_src)\n    : forall m_tgt, exists m_src, @ssim nat_wf nat_wf R R R eq p_src m_src p_tgt m_tgt\n                          (sched_nondet R (tid, ths_src))\n                          (sched_fifo R (tid, ths_tgt)).\n  Proof.\n    i.\n\n    remember (fun (i : thread_id) => List.length ths_tgt + 1) as m_src.\n    assert (M_SRC0 : m_src tid > List.length ths_tgt) by (subst; lia).\n    assert (M_SRC1 : forall i tid, nth_error ths_tgt i = Some tid -> m_src tid > i).\n    { subst. i. eapply nth_error_Some' in H. lia. }\n    clear Heqm_src.\n    exists m_src.\n\n    revert p_src p_tgt m_src m_tgt tid ths_src ths_tgt THREADS TID M_SRC0 M_SRC1.\n    pcofix CIH. i.\n\n    rewrite unfold_sched_nondet.\n    rewrite unfold_sched_fifo.\n    rewrite ! bind_trigger.\n    pfold. econs. intros [].\n    - left.\n      destruct (NatMap.is_empty ths_src) eqn: H.\n      + eapply NatMap.is_empty_2 in H.\n        eapply Empty_nil in H.\n        rewrite H in THREADS.\n        eapply Permutation_nil in THREADS.\n        subst ths_tgt.\n        pfold. econs; ss.\n      + assert (~ TIdSet.Empty ths_src).\n        { ii. eapply NatMap.is_empty_1 in H0. rewrite H in H0; ss. }\n        clear H. eapply Empty_nil_neg in H0.\n        destruct ths_tgt as [| tid' ths_tgt' ].\n        { symmetry in THREADS. eapply Permutation_nil in THREADS. ss. }\n        pfold. eapply ssim_chooseL. exists tid'. unfold nm_pop.\n        replace (NatMap.find tid' ths_src) with (Some tt); cycle 1.\n        { symmetry. eapply find_1. eapply NatSet_In_MapsTo. eapply In_NatSetIn.\n          rewrite THREADS. econs; ss.\n        }\n        rewrite bind_trigger.\n        eapply ssim_fairL.\n        remember (fun i => if Nat.eq_dec i tid'\n                        then List.length ths_tgt' + 1\n                        else if NatMapP.F.In_dec (NatMap.remove tid' ths_src) i\n                             then m_src i - 1\n                             else m_src i) as m_src'.\n        exists m_src'. splits.\n        { ii. unfold tids_fmap; ss. des_ifs.\n          assert (List.In i (TIdSet.elements ths_src)).\n          { eapply NatSetIn_In. eapply NatMapP.F.remove_neq_in_iff with (x := tid'). eauto. ss. }\n          rewrite THREADS in H. eapply In_nth_error in H. destruct H as [i' H].\n          enough (m_src i > i') by lia. eapply M_SRC1; eauto.\n        }\n        do 3 econs; eauto. right. eapply CIH.\n        * eapply NatSet_Permutation_remove. eapply THREADS.\n        * eapply NatMap.remove_1; ss.\n        * subst. des_if; ss. lia.\n        * subst. i. des_if.\n          -- eapply nth_error_Some' in H. lia.\n          -- enough (m_src tid0 > 1 + i) by (des_if; lia). eapply M_SRC1. eauto.\n    - left.\n      match goal with\n      | [ |- paco10 _ _ _ _ _ _ _ _ _ _ _ (match ?x with\n                                          | [] => _\n                                          | t' :: ts' => _\n                                          end)] => destruct x as [| tid' ths_tgt'] eqn: E_ths_tgt\n      end.\n      { eapply app_eq_nil in E_ths_tgt. des. ss. }\n      pfold. eapply ssim_chooseL. exists tid'. unfold nm_pop.\n      replace (NatMap.find tid' (TIdSet.add tid ths_src)) with (Some tt); cycle 1.\n      { symmetry. eapply find_1.\n        destruct ths_tgt; ss; inversion E_ths_tgt; subst.\n        - eapply NatMap.add_1; ss.\n        - eapply NatMap.add_2.\n          + intro. subst. eapply TID. eapply In_NatSetIn. rewrite THREADS. econs; ss.\n          + eapply NatSet_In_MapsTo. eapply In_NatSetIn. rewrite THREADS. econs; ss.\n      }\n      rewrite bind_trigger. eapply ssim_fairL.\n      remember (fun i => if Nat.eq_dec i tid'\n                      then List.length ths_tgt' + 1\n                      else if NatMapP.F.In_dec (NatMap.remove tid' (NatSet.add tid ths_src)) i\n                           then m_src i - 1\n                           else m_src i) as m_src'.\n      exists m_src'. splits.\n      { ii. unfold tids_fmap; ss. des_ifs.\n        assert (i = tid \\/ i <> tid) by lia. destruct H; try (subst; lia).\n        assert (List.In i (TIdSet.elements ths_src)).\n        { eapply NatSetIn_In. exists tt. eapply NatSet_In_MapsTo, NatMap.remove_3, NatMap.add_3 in i0; eauto. }\n        rewrite THREADS in H0. eapply In_nth_error in H0. destruct H0 as [i' H0].\n        enough (m_src i > i') by lia. eapply M_SRC1; eauto.\n      }\n      do 3 econs; ss. right. unfold NatMap.key in *. eapply CIH.\n      + eapply NatSet_Permutation_remove.\n        rewrite NatSet_Permutation_add.\n        * eapply Permutation_refl' in E_ths_tgt. rewrite Permutation_app_comm in E_ths_tgt. eapply E_ths_tgt.\n        * intro H. eapply TID. eapply H.\n        * ss.\n      + eapply NatMap.remove_1; ss.\n      + subst. des_if; ss. lia.\n      + subst. i. des_if.\n        * eapply nth_error_Some' in H. lia.\n        * enough (m_src tid0 > 1 + i) by (des_if; lia).\n          assert (nth_error (ths_tgt ++ [tid]) (1 + i) = Some tid0) by (rewrite E_ths_tgt; ss).\n          assert (1 + i < List.length ths_tgt \\/ 1 + i >= List.length ths_tgt) by lia.\n          destruct H1.\n          -- rewrite nth_error_app1 in H0 by ss. eapply M_SRC1; eauto.\n          -- rewrite nth_error_app2 in H0 by ss.\n             assert (1 + i - List.length ths_tgt = 0)\n               by (destruct (1 + i - List.length ths_tgt) as [|[]] in *; ss).\n             rewrite H2 in H0. inversion H0. subst. lia.\n  Qed.\n\n  Lemma gsim_nondet_fifo tid st (ths : @threads _Ident (sE State) R)\n    : gsim nat_wf nat_wf eq\n           (interp_all st ths tid)\n           (interp_all_fifo st ths tid).\n  Proof. \n    eapply ssim_implies_gsim.\n    { instantiate (1 := fun x => x). ss. }\n    eapply ssim_nondet_fifo; ss.\n    eapply NatMap.remove_1; ss.\n    Unshelve. all: exact true.\n  Qed.\n\n\n  Definition sched_fifo_set: schedulerT R :=\n    fun '(tid, tset) => @sched_fifo R (tid, TIdSet.elements tset).\n\n  Theorem fifo_is_fair: isFairSch (_Ident:=_Ident) R (sched_fifo_set).\n  Proof.\n    eapply ssim_isFairSch.\n    4:{ i. eapply ssim_nondet_fifo. apply Permutation_refl. eapply NatMap.remove_1. ss. }\n    { instantiate (1:=id). auto. }\n    { econs. exact 0. }\n    { i. exists (S o0). ss. }\n    Unshelve. all: exact true.\n  Qed.\n\nEnd SIM.\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/example/FIFOSchedSim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.27089587160379774}}
{"text": "\nRequire Import compcert.common.Events.\nRequire Import compcert.common.Values.\nRequire Import compcert.common.Memory.\n\nRequire Import VST.msl.Coqlib2.\n\nImport BinInt.\nImport List.\nImport Relation_Definitions.\nImport RelationClasses.\n\n\n\n(** *Monotonicity (inject_incr)*)\nClass Inject_Monotonic {A:Type}(R: meminj -> relation A):=\n  monotonicity: forall j j' a1 a2,\n    R j a1 a2 ->\n    inject_incr j j' ->\n    R j' a1 a2.\n\nLtac emonotonicity:=\n  try (unfold Inject_Monotonic);\n  eapply monotonicity.\n\n\nInstance list_map_rel_monotonicity:\n  forall {A} {R: meminj -> relation A},\n    Inject_Monotonic R ->\n    Inject_Monotonic (fun j => list_map_rel (R j)).\nProof.\n  intros ? ? ? j j' vals1.\n  induction vals1; intros.\n  - inversion H0; subst. constructor.\n  - inversion H0; subst. constructor; auto.\n    + emonotonicity; eauto.\nQed.\n\nLemma list_map_rel_monotonicity':\n  forall {A} {R: meminj -> relation A},\n    (forall j j' vals1 vals2,\n        R j vals1 vals2 ->\n        inject_incr j j' ->\n        R j' vals1 vals2) ->\n    forall j j' vals1 vals2,\n      (list_map_rel (R j)) vals1 vals2 ->\n      inject_incr j j' ->\n      (list_map_rel (R j')) vals1 vals2.\nProof.\n  intros ? ? ? j j' vals1.\n  eapply list_map_rel_monotonicity.\n  unfold Inject_Monotonic. eapply H.\nQed.\nInstance memval_inject_monotonic:\n  Inject_Monotonic memval_inject:=\n  memval_inject_incr.\nInstance list_memval_inject_monotonic:\n  Inject_Monotonic list_memval_inject.\nProof.\n  eapply list_map_rel_monotonicity.\n  emonotonicity.\nQed.\nInstance inject_hi_low_monotonic:\n  Inject_Monotonic inject_hi_low.\nProof. intros ???? H H0.\n       inversion H; subst.\n       econstructor. apply H0; auto.\nQed.\nInstance list_inject_hi_low_monotonic:\n  Inject_Monotonic list_inject_hi_low.\nProof. eapply list_map_rel_monotonicity; emonotonicity. Qed.\n\nInstance inject_mem_effect_monotonic:\n  Inject_Monotonic Events.inject_mem_effect.\nProof.\n  intros ??????.\n  inversion H; subst;\n    econstructor; eauto.\n  - emonotonicity; eassumption.\n  - emonotonicity; eassumption.\nQed.\nInstance list_inject_mem_effect_monotonic :\n  Inject_Monotonic Events.list_inject_mem_effect.\nProof.\n  emonotonicity.\nQed.\n\n\n(** *strict_injection_evolution *)\n\nInductive injection_evolution_effect:\n  meminj -> meminj ->\n  Events.mem_effect -> Events.mem_effect -> Prop:=\n|EffEvolWrite: forall b1 b2 ofs1 ofs2 mvs1 mvs2 j,\n    Events.inject_mem_effect\n      j\n      (common.Events.Write b1 ofs1 mvs1)\n      (common.Events.Write b2 ofs2 mvs2) ->\n    injection_evolution_effect\n      j j\n      (common.Events.Write b1 ofs1 mvs1)\n      (common.Events.Write b2 ofs2 mvs2)\n|EffEvolAlloc: forall j j' (b1 b2:block) ofs1 ofs1',\n    j b1 = None -> (* Do we need this? *)\n    j' = (fun b => if eq_block b b1 then\n                  Some (b2, 0%Z) else j b) ->\n    injection_evolution_effect\n      j j'\n      (common.Events.Alloc b1 ofs1 ofs1')\n      (common.Events.Alloc b2 ofs1 ofs1')\n|EffEvolFree: forall  j ls1 ls2,\n    Events.inject_mem_effect j\n                             (common.Events.Free ls1)\n                             (common.Events.Free ls2) ->\n    injection_evolution_effect\n      j j\n      (common.Events.Free ls1)\n      (common.Events.Free ls2).\n\nInductive strict_injection_evolution:\n  meminj -> meminj ->\n  list Events.mem_effect -> list Events.mem_effect -> Prop:=\n| EvolutionNil: forall j,\n    strict_injection_evolution j j nil nil\n| EvolutionCons: forall j j' j'' ev1 ev2 ls1 ls2,\n    injection_evolution_effect j j' ev1 ev2 ->\n    strict_injection_evolution j' j'' ls1 ls2 ->\n    strict_injection_evolution\n      j j''\n      (ev1::ls1) (ev2::ls2).\n\nLemma evolution_inject_effect:\n  forall j j' ev1 ev2,\n    injection_evolution_effect j j' ev1 ev2 ->\n    Events.inject_mem_effect j' ev1 ev2.\nProof.\n  intros. inversion H; subst; eauto.\n  econstructor.\n  destruct (eq_block b1 b1); eauto.\n  contradict n; reflexivity.\nQed.\nLemma effect_evolution_incr:\n  forall j j' ev1 ev2,\n    injection_evolution_effect j j' ev1 ev2 ->\n    inject_incr j j'.\nProof.\n  intros. inversion H; subst;\n            try eapply inject_incr_refl.\n  intros b1' b2' delt HH.\n  destruct (eq_block b1' b1); auto.\n  + subst. congruence.\nQed.\nLemma evolution_inject_incr:\n  forall j j' lev1 lev2,\n    strict_injection_evolution j j' lev1 lev2 ->\n    inject_incr j j'.\nProof.\n  intros j j' lev1; revert j j'.\n  induction lev1; intros.\n  - inversion H; subst.\n    eapply inject_incr_refl.\n  - inversion H; subst.\n    eapply (inject_incr_trans _ j'0).\n    + eapply effect_evolution_incr; eassumption.\n    + eapply IHlev1.\n      eauto.\nQed.\n\nLemma evolution_list_inject_mem:\n  forall j j' lev1 lev2,\n    strict_injection_evolution j j' lev1 lev2 ->\n    Events.list_inject_mem_effect j' lev1 lev2.\nProof.\n  intros j j' lev1; revert j j'.\n  induction lev1; intros.\n  - inversion H; subst. econstructor.\n  - inversion H; subst. econstructor.\n    + eapply evolution_inject_effect in H4.\n      eapply inject_mem_effect_monotonic; try eassumption.\n      eapply evolution_inject_incr; eassumption.\n    + eapply IHlev1; eauto.\nQed.\n\n\n(** *Lessdef*)\nInstance list_map_rel_preorder {A} (R: relation A) {Pre: PreOrder R}:\n  PreOrder (list_map_rel R).\nProof. constructor.\n       - intros ls; induction ls; econstructor; auto.\n         reflexivity.\n       - intros ls1.\n         induction ls1; intros. \n         + inversion H; subst; inversion H0; subst. constructor.\n         + inversion H; subst; inversion H0; subst. constructor; eauto.\n           etransitivity; eauto.\nQed.\n\n\nInductive memval_lessdef: relation memval:=\n| MvUndefLessDef : forall mv, memval_lessdef Undef mv \n| MvBytelLessDef : forall b, memval_lessdef (Byte b) (Byte b)\n| MvReflLessDef : forall v v' q n,\n    Val.lessdef v v' ->\n    memval_lessdef (Fragment v q n) (Fragment v' q n).\nInstance memval_lessdef_preorder: PreOrder memval_lessdef.\nProof. constructor.\n       - intros x; destruct x; econstructor. apply Val.lessdef_refl.\n       - intros x y z ? ?.\n         inversion H; subst; inversion H0; subst; econstructor.\n         eapply Val.lessdef_trans; eassumption.\nQed.\n\nInductive effect_lessdef:\n  relation Events.mem_effect:=\n| EvWriteLessDef:\n    forall b ofs mvs mvs',\n      (list_map_rel memval_lessdef) mvs mvs' ->\n      effect_lessdef (common.Events.Write b ofs mvs)\n                     (common.Events.Write b ofs mvs')\n| EvReflLessDef: forall eff,  effect_lessdef eff eff.\nInstance effect_lessdef_preorder: PreOrder effect_lessdef.\nProof. constructor.\n       - intros x; destruct x; econstructor. reflexivity.\n       - intros x y z ? ?.\n         inversion H; subst; inversion H0; subst; econstructor; try eassumption.\n         + etransitivity; eassumption.\nQed.\n\nDefinition effects_lessdef:\n  relation (list Events.mem_effect):=\n  Events.list_map_rel effect_lessdef.\n\n\n(** *Consecutive*)\nInductive consecutive: block -> list Events.mem_effect -> Prop:=\n| consecutiveNil: forall nb,\n    consecutive nb nil\n| consecutiveWrite: forall nb b ofs mvals lev',\n    (b <= nb)%positive -> (* needed?*)\n    consecutive nb lev' ->\n    consecutive nb ((common.Events.Write b ofs mvals):: lev')\n| consecutiveAlloc: forall nb b ofs mvals lev',\n    (b = nb)%positive -> (* needed?*)\n    consecutive (Pos.succ nb) lev' ->\n    consecutive nb ((common.Events.Alloc b ofs mvals):: lev')\n| consecutiveFree: forall nb lsbzz lev',\n    (Forall (fun x => (fst (fst x)) <= nb)%positive lsbzz) ->\n    consecutive nb lev' ->\n    consecutive nb ((common.Events.Free lsbzz):: lev').\nLemma consecutive_monotonic:\n  forall nb lev0 lev,\n    effects_lessdef lev0 lev ->\n    consecutive nb lev ->\n    consecutive nb lev0.\nProof.\n  intros nb lev0. revert nb.\n  induction lev0; intros.\n  - econstructor.\n  - inversion H; subst.\n    inversion H0; subst;\n      inversion H3; subst;\n        econstructor; eauto.\nQed.\n\n(** *Section Diagrams *) \nRecord diagram\n       (nb: block) (j j': meminj)\n       (lev1 lev2: list Events.mem_effect):=\n  { Dincr: inject_incr j j'\n    ; Dinj: Events.list_inject_mem_effect j' lev1 lev2\n    ; Dconsec: consecutive nb lev2\n  }.\n\nRecord principled_diagram\n       (nb: block) (j j': meminj)\n       (lev1 lev2: list Events.mem_effect):=\n  { PDevol: strict_injection_evolution j j' lev1 lev2\n    ; PDinj_str: Events.list_inject_mem_effect_strong j' lev1 lev2\n    ; PDconsec: consecutive nb lev2\n  }.\n\nInductive principled_diagram':\n  block -> meminj -> meminj -> list Events.mem_effect -> Prop :=\n|build_pd': forall  nb j j0 lev1 lev20,\n    principled_diagram nb j j0 lev1 lev20 ->\n    principled_diagram' nb j j0 lev1.\nInductive diagram':\n  block -> meminj -> meminj -> list Events.mem_effect -> Prop :=\n|build_d': forall nb j j' lev1 lev2,\n    diagram nb j j' lev1 lev2 ->\n    diagram' nb j j' lev1.\n\n\n\n\n\n(** *Principaled Effects and values*)\nLemma principaled_val_exists:\n  forall j v1 v2,\n    Val.inject j v1 v2 ->\n    exists v20,\n      Events.inject_strong j v1 v20 /\\\n      Val.lessdef v20 v2.\nProof.\n  intros. induction H;\n            try (eexists; split; econstructor); eassumption.\nQed.\nLemma principaled_memval_exists:\n  forall j mv1 mv2,\n    memval_inject j mv1 mv2 ->\n    exists mv20,\n      Events.memval_inject_strong j mv1 mv20 /\\\n      memval_lessdef mv20 mv2.\nProof.\n  intros. induction H;\n            try solve[eexists; split; econstructor].\n  - eapply principaled_val_exists in H.\n    destruct H as (v20&?&?).\n    eexists; split. econstructor; eassumption.\n    econstructor; eauto.\nQed.\nLemma principaled_memvals_exists:\n  forall j mv1 mv2,\n    Events.list_memval_inject j mv1 mv2 ->\n    exists mv20,\n      Events.list_memval_inject_strong j mv1 mv20 /\\\n      Events.list_map_rel memval_lessdef mv20 mv2.\nProof.\n  intros. induction H; subst.\n  - exists nil; split; econstructor.\n  - destruct (principaled_memval_exists _ _ _ H) as (v20&?&?).\n    destruct IHlist_map_rel as (mv20&?&?).\n    exists (v20::mv20); split. constructor; eassumption.\n    econstructor; eauto.\nQed.\nLemma principaled_effect_exists:\n  forall j eff1 eff2,\n    Events.inject_mem_effect j eff1 eff2 ->\n    exists eff20,\n      Events.inject_mem_effect_strong j eff1 eff20 /\\\n      effect_lessdef eff20 eff2.\nProof.\n  intros. inversion H; subst;\n            try solve[eexists; split; econstructor; eauto].\n  + destruct (principaled_memvals_exists _ _ _ H1) as (mv20&?&?).\n    eexists; split. econstructor; eauto.\n    econstructor; eassumption.\nQed.\nLemma principaled_effects_exists:\n  forall j lev1 lev2,\n    Events.list_inject_mem_effect j lev1 lev2 ->\n    exists lev20,\n      Events.list_inject_mem_effect_strong j lev1 lev20 /\\\n      effects_lessdef lev20 lev2.\nProof.\n  intros j lev1 lev2; revert j lev1.\n  induction lev2; intros.\n  - inversion H; subst.\n    exists nil; split; econstructor.\n  - inversion H; subst; clear H.\n    destruct (principaled_effect_exists _ _ _ H3) as (eff20&?&?).\n    destruct (IHlev2 _ _ H4) as (lev20&?&?).\n    eexists; split.\n    + econstructor; eassumption.\n    + econstructor; eassumption.\nQed.\n\nLemma principaled_injection_exists:\n  forall j j' lev1 lev2 lev20,\n    strict_injection_evolution j j' lev1 lev2 ->\n    Events.list_inject_mem_effect_strong j' lev1 lev20 ->\n    effects_lessdef lev20 lev2 ->\n    strict_injection_evolution j j' lev1 lev20.\nProof.\n  intros j j' lev1; revert j j'.\n  induction lev1; intros.\n  - inversion H0; inversion H; subst. econstructor.\n  - inversion H0; inversion H; subst; inversion H1; \n      subst.\n    econstructor; eauto.\n    + \n\n\n      admit. (*  injection_evolution_effect j j'0 a ev2 \n                                     effect_lessdef b ev2\n                                     injection_evolution_effect j j'0 a b*) \nAdmitted.\n\nLemma principled_diagram_exists:\n  forall nb j j' lev1 lev2,\n    strict_injection_evolution j j' lev1 lev2 ->\n    consecutive nb lev2 ->\n    exists lev20,\n      principled_diagram nb j j' lev1 lev20 /\\\n      effects_lessdef lev20 lev2.\nProof.\n  intros.\n  pose proof (evolution_list_inject_mem _ _ _ _ H).\n  destruct (principaled_effects_exists _ _ _ H1) as (lev20 & HH & Horder).\n  exists lev20.\n  econstructor; repeat split.\n  - \n    eapply principaled_injection_exists; eauto.\n  - eauto.\n  - \n    eapply consecutive_monotonic; eassumption.\n  - assumption.\nQed.\nLemma principled_diagram_exists':\n  forall (nb : block) (j j' : meminj) (lev1 lev2 : list Events.mem_effect),\n    strict_injection_evolution j j' lev1 lev2 ->\n    consecutive nb lev2 ->\n    principled_diagram' nb j j' lev1.\nProof.\n  intros.\n  edestruct principled_diagram_exists as (?&?&?); eauto.\n  econstructor; eauto.\nQed.\nLemma consecutive_head:\n  forall nb ev ls,\n    consecutive nb (ev :: ls) ->\n    consecutive nb (ev :: nil).\nProof. intros. inversion H; subst;\n                 econstructor; auto; constructor.\nQed.\nDefinition nextblock_eff (nb:block) (ev:mem_effect):=\n  match ev with\n  | Write _ _ _ => nb\n  | Alloc _ _ _ => Pos.succ nb\n  | Free _ => nb\n  end.\nLemma consecutive_tail:\n  forall nb ev ls,\n    consecutive nb (ev :: ls) ->\n    consecutive (nextblock_eff nb ev ) (ls).\nProof. intros. inversion H; subst; simpl; auto. Qed.\n\n\nLemma inject_lessdef:\n  forall j' j0 : meminj,\n    inject_incr j0 j' ->\n    forall v1 v3 v2 : val,\n      Val.inject j' v1 v2 ->\n      inject_strong j0 v1 v3 -> Val.lessdef v3 v2.\nProof.\n  intros j' j0 Hincr v1 v3 v2 H0 H1.\n  inversion H0; subst;\n    inversion H1; subst;\n      try solve[constructor].\n  - apply Hincr in H4.\n    rewrite H4 in H; inversion H; subst.\n    constructor.\nQed.\nLemma inject_memval_lessdef:\n  forall (a : memval) (j' j0 : meminj),\n    inject_incr j0 j' ->\n    forall b b0 : memval,\n      memval_inject j' a b ->\n      memval_inject_strong j0 a b0 -> memval_lessdef b0 b.\nProof.\n  intros a j' j0 H b b0 H4 H5.\n  inversion H4; subst;\n    inversion H5; subst;\n      try solve[constructor].\n  - constructor.\n    eapply inject_lessdef; eassumption.\nQed.\nLemma list_inject_memval_lessdef:\n  forall (j' j0 : meminj) (mvs1 mvs2 : list memval),\n    inject_incr j0 j' ->\n    forall vals2 : list memval,\n      list_memval_inject j' mvs1 vals2 ->\n      list_memval_inject_strong j0 mvs1 mvs2 ->\n      list_map_rel memval_lessdef mvs2 vals2.\nProof.\n  intros j' j0 mvs1. revert j' j0.\n  induction mvs1; intros.\n  - inversion H0; subst;\n      inversion H1; subst;\n        constructor.\n  - inversion H0; subst;\n      inversion H1; subst;\n        try solve[econstructor; eauto].\n    econstructor.\n    \n    +eapply inject_memval_lessdef; eassumption.\n    + eapply IHmvs1; eassumption.\nQed.\n\nLemma list_inject_hi_low_lessdef:\n  forall j0 j ls1 ls2 ls20,\n    inject_incr j0 j ->\n    list_inject_hi_low j0 ls1 ls20 ->\n    list_inject_hi_low j ls1 ls2 ->\n    ls20 = ls2.\nProof.\n  intros j0 j ls1; revert j0 j.\n  induction ls1; intros.\n  - inversion H0; subst;\n      inversion H1; subst; auto.\n  - inversion H0; subst;\n      inversion H1; subst; auto.\n    f_equal.\n    + clear - H4 H5 H.\n      inversion H4; subst;\n        inversion H5; subst.\n      apply H in H0; rewrite H0 in H7.\n      inversion H7; subst. reflexivity.\n    + eapply IHls1; eassumption.\nQed.\n\nLemma incr_inject_strong:\n  forall (j0 j0' : meminj) v1 v2,\n    inject_incr j0 j0' ->\n    inject_strong j0' v1 v2 ->\n    Val.inject j0 v1 v2 ->\n    inject_strong j0 v1 v2.\nProof.\n  intros.\n  inversion H0; subst;\n    inversion H1; subst;\n      econstructor; eauto.\nQed.\nLemma incr_memval_inject_strong:\n  forall (j0 j0' : meminj) (val1 val2 : memval),\n    inject_incr j0 j0' ->\n    memval_inject_strong j0' val1 val2 ->\n    memval_inject j0 val1 val2 ->\n    memval_inject_strong j0 val1 val2.\nProof.\n  intros.\n  inversion H0; subst;\n    inversion H1; subst;\n      econstructor; eauto.\n  eapply incr_inject_strong; eassumption.\nQed.\nLemma incr_list_memval_inject_strong:\n  forall (j0 j0' : meminj) (vals1 vals2 : list memval),\n    inject_incr j0 j0' ->\n    list_memval_inject_strong j0' vals1 vals2 ->\n    list_memval_inject j0 vals1 vals2 -> list_memval_inject_strong j0 vals1 vals2.\nProof.\n  intros j0 j0' vals1; revert j0 j0'.\n  induction vals1; intros j0 j0' vals2 H0 H3 H11.\n  - inversion H3; subst;\n      inversion H11; subst;\n        econstructor; eauto.\n  - inversion H3; subst;\n      inversion H11; subst;\n        econstructor; eauto.\n    \n    eapply incr_memval_inject_strong; eassumption.\n    eapply IHvals1; eauto.\nQed.\nLemma evolution_injection_lessdef:\n  forall j j' j0 ev1 ev2 ev20 nb,\n    inject_incr j j' ->\n    injection_evolution_effect j j0 ev1 ev2 ->\n    inject_mem_effect_strong j0 ev1 ev2 ->\n    inject_mem_effect j' ev1 ev20 ->\n    consecutive nb (ev2 :: nil) ->\n    consecutive nb (ev20 :: nil) ->\n    effect_lessdef ev2 ev20.\nProof.\n  intros\n    ??????? Hincr Hevol Hinj_str Hinject Hconsec Hconsec'.\n  inversion Hevol; subst; clear Hevol;\n    inversion Hinject; subst; clear Hinject.\n  - inversion Hinj_str; subst.\n    apply Hincr in H2.\n    rewrite H2 in H4; inversion H4; subst.\n    econstructor.\n    \n    eapply list_inject_memval_lessdef; eassumption.\n  - inversion Hconsec; subst.\n    inversion Hconsec'; subst.\n    econstructor.\n  - inversion H; subst.\n    inversion Hinj_str; subst.\n    eapply list_inject_hi_low_lessdef in H1; eauto.\n    subst; econstructor.\nQed.\nLemma incr_inject_mem_effect_strong:\n  forall j0 j0' ev1 ev2,\n    inject_mem_effect_strong j0' ev1 ev2 ->\n    inject_incr j0 j0' ->\n    inject_mem_effect j0 ev1 ev2 ->\n    inject_mem_effect_strong j0 ev1 ev2.\nProof.\n  intros.\n  inversion H; subst;\n    inversion H1; subst;\n      econstructor; eauto.\n  - apply H0 in H6;\n      rewrite H2 in H6;\n      inversion H6; subst.\n    eapply incr_list_memval_inject_strong; eassumption.\nQed.\n\n\nLemma principled_diagram_correct:\n  forall nb j j' j0 lev1 lev2 lev20,\n    principled_diagram nb j j0 lev1 lev20 ->\n    diagram nb j j' lev1 lev2 ->\n    inject_incr j0 j' /\\  effects_lessdef lev20 lev2.\nProof.\n  intros nb j j' j0 lev1; revert nb j j' j0 .\n  induction lev1; intros.\n  - inversion H as [Hevol Hinj_str Hconsec];\n      inversion H0 as [Hincr  Hinj Hconsec'].\n    inversion Hevol; inversion Hinj; subst.\n    split; auto. reflexivity.\n  -  inversion H as [Hevol Hinj_str Hconsec];\n       inversion H0 as [Hincr  Hinj Hconsec'].\n     inversion Hevol; inversion Hinj; subst.\n     inversion Hinj_str; subst.\n\n     assert (Hincr0: inject_incr j'0 j0).\n     { eapply evolution_inject_incr; eassumption. }\n     \n     assert (Hpdiagram: principled_diagram (nextblock_eff nb ev2) j'0 j0 lev1 ls2).\n     { econstructor; eauto.\n       eapply consecutive_tail; eassumption. }\n\n     assert (Hdiagram: diagram (nextblock_eff nb b) j'0 j' lev1 l2).\n     {  econstructor; try eassumption.\n        - clear - Hincr H5 H10 Hconsec' Hconsec.\n          inversion H5; subst; eauto.\n          inversion H10; subst.\n          intros ????.\n          if_tac in H0; subst; auto.\n          + inversion H0; subst.\n            inversion Hconsec'; subst.\n            inversion Hconsec; subst.\n            auto.\n        - eapply consecutive_tail; eassumption.\n     }\n\n     assert (Hlessdef: effect_lessdef ev2 b).\n     { \n       eapply (evolution_injection_lessdef j j'); try eassumption.\n       * eapply incr_inject_mem_effect_strong; try eassumption.\n         inversion H5; subst; eauto.\n         -- eapply evolution_inject_effect; eassumption.\n       * eapply consecutive_head; eauto.\n       * eapply consecutive_head; eauto. }\n     \n     replace (nextblock_eff nb b) with (nextblock_eff nb ev2) in Hdiagram by\n         (inversion Hlessdef; reflexivity).\n     \n     edestruct (IHlev1 _ _ _ _ _ _ Hpdiagram Hdiagram) as (Hincr'&Hlessdef').\n     split.\n     + assumption.\n     + econstructor; auto.\nQed.\n\nLemma principled_diagram_correct':\n  forall (nb : block)\n    (j j' j0 : meminj)\n    (lev1: list Events.mem_effect),\n    principled_diagram' nb j j0 lev1 ->\n    diagram' nb j j' lev1 ->\n    inject_incr j0 j'.\nProof.\n  intros * H1 H2; inversion H1; inversion H2;subst; \n    eapply principled_diagram_correct; eassumption.\nQed.\n\n\n\n  \n  Record same_visible (m1 m2: mem):=\n    { same_cur:\n        forall b ofs p,\n          (Mem.perm m1 b ofs Cur p <->\n                Mem.perm m2 b ofs Cur p);\n      same_visible12:\n        forall b ofs,\n          Mem.perm m1 b ofs Cur Readable ->\n          (Maps.ZMap.get ofs (Maps.PMap.get b (Mem.mem_contents m1))) =\n          (Maps.ZMap.get ofs (Maps.PMap.get b (Mem.mem_contents m2)));\n      same_visible21:\n        forall b ofs,\n          Mem.perm m2 b ofs Cur Readable ->\n          (Maps.ZMap.get ofs (Maps.PMap.get b (Mem.mem_contents m1))) =\n          (Maps.ZMap.get ofs (Maps.PMap.get b (Mem.mem_contents m2)));\n    }.\n  Instance same_vis_equiv: (Equivalence same_visible).\n  Admitted.\n\n\n\n(** *mem_interference with mem_effect *)\nSection MemInterference.\n  Definition mem_effect_forward: mem -> Events.mem_effect -> mem -> Prop.\n  (* Definition mem_effect_forward m ev m':= \n         execute ev in m, without checking for permissions.\n   *)\n  Admitted.\n  \n  Inductive mem_interference: mem -> list Events.mem_effect -> mem -> Prop:=\n  | Nil_mem_interference: forall m, mem_interference m nil m\n  | Build_mem_interference: forall m m' m'' ev lev,\n      mem_effect_forward m ev m' ->\n      mem_interference m' lev m'' ->\n      mem_interference m (ev::lev) m''.\n  (* OLD_mem_interference:= Mem.unchanged_on (loc_readable_cur m) m *)\n\n  Lemma mem_interference_one:\n    forall m m' ev, \n      mem_effect_forward m ev m' ->\n      mem_interference m (ev::nil) m'.\n  Proof. intros; econstructor; [eauto| econstructor].\n  Qed.\n\n  Lemma mem_interference_trans:\n    forall lev lev' m m' m'', \n      mem_interference m lev m' ->\n      mem_interference m' lev' m'' ->\n      mem_interference m (lev ++ lev') m''.\n  Proof.\n    induction lev.\n    - simpl; intros.\n      inversion H; subst; auto.\n    - simpl; intros.\n      inversion H; subst; auto.\n      econstructor; eauto.\n  Qed.\n\n  Lemma mem_effect_forward_determ:\n    forall eff m m1' m2',\n      mem_effect_forward m eff m1' -> \n      mem_effect_forward m eff m2' ->\n      m1' = m2'.\n  Proof.\n    intros. \n  Admitted.\n  Lemma mem_interference_determ:\n    forall lev m m1' m2',\n      mem_interference m lev m1' -> \n      mem_interference m lev m2' ->\n      m1' = m2'.\n  Proof.\n    intros lev; induction lev; intros.\n    - inversion H; subst;\n        inversion H0; subst; reflexivity.\n    - inversion H; subst; inversion H0; subst.\n      pose proof (mem_effect_forward_determ\n                    _ _ _ _\n                    H4 H5); subst.\n      eapply IHlev; eassumption.\n  Qed.\n\n  \nLemma interference_same_visible:\n  forall m m' lev, mem_interference m lev m' ->\n              same_visible m m'.\nAdmitted.\n\nEnd MemInterference.\n\n\nDefinition consecutive_until: block -> list Events.mem_effect -> block -> Prop.\nAdmitted.\nLemma consecutive_until_cat:\n  forall lev lev' b b' b'',\n    consecutive_until b lev b' ->\n    consecutive_until b' lev' b'' ->\n    consecutive_until b (lev ++ lev') b''.\nProof.\nAdmitted.\nLemma consecutive_until_consecutive:\n  forall lev b b',\n    consecutive_until b lev b' ->\n    consecutive b lev.\nProof.\nAdmitted.\n\nLemma strict_inj_evolution_cat:\n  forall j j' j'' lev1 lev1' lev2 lev2' nb nb' nb'',\n    strict_injection_evolution j j' lev1 lev2 ->\n    strict_injection_evolution j' j'' lev1' lev2' ->\n    consecutive_until nb lev2 nb' ->\n    consecutive_until nb' lev2' nb'' ->\n    strict_injection_evolution j j'' (lev1++lev1') (lev2++lev2').\nProof.\nAdmitted.\n\nLemma interference_consecutive: forall m lev m',\n    mem_interference m lev m' ->\n    consecutive (Mem.nextblock m) lev.\nProof.\n  intros. induction lev; try econstructor.\nAdmitted.\nLemma interference_consecutive_until:\n  forall {m lev m'},\n    mem_interference m lev m' ->\n    consecutive_until (Mem.nextblock m) lev (Mem.nextblock m').\nProof. Admitted.\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/concurrency/compiler/diagrams.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.27073188951632116}}
{"text": "Require Import String ZArith Basics.\nFrom ConCert Require Import Ast Notations PCUICTranslate PCUICtoTemplate.\nFrom ConCert Require Import Utils Prelude SimpleBlockchain CustomTactics.\nRequire Import List PeanoNat ssrbool.\n\nImport ListNotations.\nFrom MetaCoq.Template Require Import All.\n\nImport MonadNotation.\nImport BaseTypes.\nOpen Scope list.\n\nImport AcornBlockchain.\n\nImport Lia.\n\nRun TemplateProgram\n      (mkNames [\"State\" ; \"mkState\"; \"count\"; \"dummy\";\n                \"Res\" ; \"Error\";\n                \"Msg\"; \"Tick\"; \"NOP\";\n               \"Action\"; \"Transfer\"; \"Empty\" ] \"_coq\").\n\nImport ListNotations.\n\nDefinition state_syn : global_dec :=\n  [\\ record State := mkState { count : Nat ; \n                               dummy : Bool} \\].\n\nSet Nonrecursive Elimination Schemes.\nMake Inductive (global_to_tc state_syn).\n\nDefinition msg_syn :=\n  [\\ data Msg =\n   Tick [_] |\n   NOP [_] \\].\n\nMake Inductive (global_to_tc msg_syn).\n\nPrint Msg_coq.\n\n  Notation \"'Tick'\" :=\n    (pConstr Tick []) ( in custom pat at level 0).\n  Notation \"'NOP'\" :=\n    (pConstr NOP []) ( in custom pat at level 0).\n\n  Notation \"'Just' x\" :=\n    (pConstr \"Some\" [x]) (in custom pat at level 0,\n                             x constr at level 4).\n  Notation \"'Nothing'\" := (pConstr \"None\" [])\n                            (in custom pat at level 0).\n  (** Projections *)\n  Notation \"'count' a\" :=\n    [| {eConst count} {a} |]\n      (in custom expr at level 0).\n  \n  Notation \"'dummy' a\" :=\n    [| {eConst dummy} {a} |]\n      (in custom expr at level 0).\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\n Definition actions_ty := [! \"list\" \"SimpleActionBody\" !].\n\n  Notation \"'Result'\" := [!\"prod\" State (\"list\" \"SimpleActionBody\") !]\n                           (in custom type at level 2).\n\n  Notation \"'Just' a\" := [| {eConstr \"option\" \"Some\"}  {eTy [! Result!]} {a}|]\n                           (in custom expr at level 0,\n                               a custom expr at level 1).\n\n  Notation \"'Pair' a b\" := [| {eConstr \"prod\" \"pair\"}\n                               {eTy (tyInd State)}\n                               {eTy actions_ty} {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\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 \"'Nothing'\" := (eApp (eConstr \"option\" \"None\") (eTy [!Result!]))\n                      (in custom expr at level 0).\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  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  Notation \"0 'z'\" := (eConstr \"Z\" \"Z0\") (in custom expr at level 0).\n\n  Import Prelude.\n  (** Generating string constants for variable names *)\n\n  Run 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 ..]  *)\n  Notation \"'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\n  Notation SCtx := \"SimpleContractCallContext\".\n  Definition test := [| 1 |].\n  Unset Printing Notations.\n  Print test.\n  Make Definition test_coq :=\n        (expr_to_tc Σ' (indexify nil test)).\n      Print test_coq.\n  Set Printing Notations.\n  \n  Module CrowdfundingContract.\n    Import AcornBlockchain.\n    Module Init.\n      Import Notations.\n          Definition crowdfunding_init : expr :=\n            [| \\c : SCtx => \\dl : Nat => \\g : Money => mkState dl False|].\n          Make Definition init :=\n            (expr_to_tc Σ' (indexify nil crowdfunding_init)).\n          Check init.\n    End Init.\n    Module Receive.\n      Import Notations.\n      Import Prelude.\n      \n      Notation SCtx := \"SimpleContractCallContext\".\n      Notation SChain := \"SimpleChain\".\n      Definition counter : expr :=\n        [| \\chain : SChain =>  \\c : SCtx => \\m : Msg => \\s : State =>\n           case m : Msg return Maybe Result of\n            | Tick ->\n              Just (Pair (mkState (Suc(count s)) False) Nil )\n            | NOP -> Just (Pair s Nil )\n            |].\n      Compute (expr_to_tc Σ' (indexify nil counter)).\n      Make Definition receive :=\n        (expr_to_tc Σ' (indexify nil counter)).\n      Print receive.\n    End Receive.\n\n\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/Counter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.27073188951632104}}
{"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 ResourceProtocol.\nSection ResourceProtocol.\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).\nNotation client := nid (only parsing).\n\nDefinition value := nat.\n\nInductive request :=\n| Update of client * epoch * value\n| Read of client * epoch.\n\nDefinition request_eq (r1 r2 : request) : bool :=\n  match r1, r2 with\n  | Update x1, Update x2 => x1 == x2\n  | Read x1, Read x2 => x1 == x2\n  | _, _ => false\n  end.\n\nLemma request_eqP : Equality.axiom request_eq.\nProof.\n  case=>x[]y; do? [by constructor];\n  apply: (iffP eqP); congruence.\nQed.\n\nCanonical request_eqMixin := EqMixin request_eqP.\nCanonical request_eqType := Eval hnf in EqType request request_eqMixin.\n\nRecord server_state :=\n  ServerState {\n      current_epoch : epoch;\n      current_value : value;\n      outstanding : seq request\n    }.\n\nDefinition update_tag := 0.\nDefinition update_response_tag := 1.\nDefinition read_tag := 2.\nDefinition read_response_tag := 3.\n\nDefinition msg_from_client ms :=\n  (tag ms == update_tag /\\ exists e v, tms_cont ms = [:: e; v]) \\/\n  (tag ms == read_tag /\\ exists e, tms_cont ms = [:: e]).\n\nDefinition msg_from_server ms :=\n  (tag ms == update_response_tag /\\ exists e v b, tms_cont ms = [:: e; v; b]) \\/\n  (tag ms == read_response_tag /\\\n     ((exists e v, tms_cont ms = [:: e; v] (* success *)) \\/\n      (exists e, tms_cont ms = [:: e] (* failure *)))).\n\nDefinition coh_msg pkt :=\n  if from pkt == server\n  then to pkt \\in clients /\\ msg_from_server (content pkt)\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 :=\n  [Pred h | h = Heap.empty].\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        client_local_coh h].\n\nDefinition soup_coh : Pred soup :=\n  [Pred s |\n    valid s /\\\n    forall m ms, find m s = Some ms -> active ms -> coh_msg ms].\n\nLemma soup_coh_post_msg d m:\n    soup_coh (dsoup d) -> coh_msg m -> soup_coh (post_msg (dsoup d) m).1.\nProof.\nmove=>[H1 H2]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.\nQed.\n\nDefinition state_coh d :=\n  forall n, n \\in nodes -> local_coh n (getLocal n d).\n\nDefinition resource_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: resource_coh d -> valid (dstate d).\nProof. by case. Qed.\n\nLemma l2 d: resource_coh d -> valid (dsoup d).\nProof. by case; case. Qed.\n\nLemma l3 d: resource_coh d -> dom (dstate d) =i nodes.\nProof. by case. Qed.\n\nDefinition ResourceCoh := CohPred (CohPredMixin l1 l2 l3).\n\nLemma consume_coh d m : ResourceCoh 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 -> ResourceCoh 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) (tag : nat) (msg : seq nat) \n  : server_state :=\n  if to \\in clients\n  then if tag == update_response_tag \n       then if msg is [:: e; v; b]\n            then let: r := Update (to, e, v) \n                 in if current_epoch ss <= e\n                    then ServerState e v (seq.rem r (outstanding ss))\n                    else ServerState (current_epoch ss) (current_value ss) (seq.rem r (outstanding ss))\n            else ss\n       else if tag == read_response_tag\n       then if msg is e :: _\n            then let: r := Read (to, e)\n                 in ServerState (current_epoch ss) (current_value ss) (seq.rem r (outstanding ss))\n            else ss\n       else ss\n  else ss.\n\nDefinition server_recv_step (ss : server_state) (from : nid)\n           (mtag : nat) (mbody : seq nat) : server_state :=\n  if mtag == update_tag\n  then\n    if mbody is [:: e; v]\n    then ServerState (current_epoch ss) (current_value ss) (cons (Update (from, e, v)) (outstanding ss))\n    else ss\n  else (* mtag == read_tag *)\n    if mbody is [:: e]\n    then ServerState (current_epoch ss) (current_value ss) (cons (Read (from, e)) (outstanding ss))\n    else ss.\n\nSection GetterLemmas.\n\nLemma getLocal_coh n d (C : ResourceCoh 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       getLocal n d = Unit.\nProof.\n  by case: C=>_ _ _ /(_ n)G; rewrite /local_coh/=.\nQed.\n\nLemma getLocal_server_st_tp d (C : ResourceCoh 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 *.\nby rewrite findPt /=; case=><-.\nQed.\n\nDefinition getSt_server d (C : ResourceCoh 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 0 [::]\n  end (erefl _).\n\nLemma getSt_server_K d (C : ResourceCoh 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\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 nat -> 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).\n\nNotation coh := ResourceCoh.\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 the_tag msg).\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  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=>?[].\nrewrite /server_step.\nby eexists _, 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_update_response_prec (ss : server_state) to m :=\n  exists e v b e0 v0 outstanding, \n    m = [:: e; v; b] /\\\n    let: r := Update (to, e, v) \n    in r \\in outstanding /\\\n       ss = ServerState e0 v0 outstanding /\\ \n       b = if e0 <= e then 1 else 0.\n\nProgram Definition server_send_update_response_trans : send_trans ResourceCoh :=\n  @server_send_trans update_response_tag server_send_update_response_prec _.\nNext Obligation.\ncase: H=>/eqP->H; rewrite /coh_msg eqxx; split=>//=.\ncase: H0=>[e][v][b][e0][v0][out][]->[U][_]->.  \nrewrite /msg_from_server /= eqxx. left. split=>//. by eexists _, _, _. \nQed.\n\nDefinition server_send_read_response_prec (ss : server_state) to m :=\n  exists e e0 v0 outstanding, \n    ss = ServerState e0 v0 outstanding /\\ \n    let: r := Read (to, e) \n    in r \\in outstanding /\\ \n       m = if e0 <= e \n           then [:: e; v0 ] \n           else [:: e].\n\nProgram Definition server_send_read_response_trans : send_trans ResourceCoh :=\n  @server_send_trans read_response_tag server_send_read_response_prec _.\nNext Obligation.\ncase: H=>/eqP->H; rewrite /coh_msg eqxx; split=>//=.\ncase: H0=>[e][e0][v0][out][_][R]->.\nrewrite /msg_from_server /= eqxx. right. split=>//. \nby case: ifP=>_; [left; eexists _,_|right; eexists].\nQed.\n\nEnd ServerSendTransitions.\n\nSection ServerGenericReceiveTransitions.\n\nNotation coh := ResourceCoh.\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 : nid) t :=\n  (t == read_tag) || (t == update_tag).\n\nDefinition server_msg_wf d (C : ResourceCoh d) (this from : nid) :=\n  [pred m : TaggedMessage | s_matches_tag (getSt_server C) from (tag m)].\n\nDefinition server_recv_update_trans := rs_recv_trans update_tag server_msg_wf.\n\nDefinition server_recv_read_trans := rs_recv_trans read_tag server_msg_wf.\n\nEnd ServerReceiveTransitions.\n\nSection ClientGenericSendTransitions.\n\nDefinition HClient this to := (this \\in clients /\\ to == server).\n\nVariable the_tag : nat.\n\nVariable prec : nid -> seq nat -> Prop.\n\nHypothesis prec_safe :\n  forall this to m,\n    HClient this to ->\n    prec to m ->\n    msg_from_client (TMsg the_tag m).\n\nNotation coh := ResourceCoh.\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, coh d & prec n msg].\n\nLemma client_send_safe_coh this to d m : client_send_safe this to d m -> coh d.\nProof. by case. 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 P. \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  Some Heap.empty.\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 _ P/=. \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.\nby rewrite client_not_server// (cohVl C)/=.\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=>?[].\nby eexists _, 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_update_prec (to : nid) (m : seq nat) :=\n  exists e v, m = [:: e; v].\n\nProgram Definition client_send_update_trans : send_trans ResourceCoh :=\n  @client_send_trans update_tag client_send_update_prec _.\nNext Obligation.\nby left.\nQed.\n\nDefinition client_send_read_prec (to : nid) (m : seq nat) :=\n  exists e, m = [:: e].\n\nProgram Definition client_send_read_trans : send_trans ResourceCoh :=\n  @client_send_trans read_tag client_send_read_prec _.\nNext Obligation.\nby right.\nQed.\n\nEnd ClientSendTransitions.\n\nSection ClientGenericReceiveTransitions.\n\nNotation coh := ResourceCoh.\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    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 /resource_coh.\nsplit=>/=.\nby apply: consume_coh.\nby apply: coh_dom_upd.\nby 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).\nby move=>n Ni/=; move: (Y n Ni)=>L; rewrite -(getLocalU) // (cohVl C).\nQed.\n\nDefinition rc_recv_trans := ReceiveTrans rc_step_coh.\n\nEnd ClientGenericReceiveTransitions.\n\nSection ClientReceiveTransitions.\n\nDefinition client_msg_wf d (_ : ResourceCoh d) (this from : nid) :=\n  [pred m : TaggedMessage | true].\n\nDefinition client_recv_update_response_trans := rc_recv_trans update_response_tag client_msg_wf.\n\nDefinition client_recv_read_response_trans := rc_recv_trans read_response_tag client_msg_wf.\n\nEnd ClientReceiveTransitions.\n\nSection Protocol.\n\nVariable l : Label.\n\n(* All send-transitions *)\nDefinition resource_sends :=\n  [::\n     server_send_update_response_trans;\n     server_send_read_response_trans;\n     client_send_update_trans;\n     client_send_read_trans\n  ].\n\n(* All receive-transitions *)\nDefinition resource_receives :=\n  [::\n     server_recv_update_trans;\n     server_recv_read_trans;\n     client_recv_update_response_trans;\n     client_recv_read_response_trans\n  ].\n\nProgram Definition ResourceProtocol : protocol :=\n  @Protocol _ l _ resource_sends resource_receives _ _.\n\nEnd Protocol.\n\nEnd ResourceProtocol.\n\nModule Exports.\nSection Exports.\n\nDefinition ResourceProtocol := ResourceProtocol.\n\nEnd Exports.\nEnd Exports.\n\nEnd ResourceProtocol.\n\nExport ResourceProtocol.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/ResourceProtocol.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290152, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2707244209369256}}
{"text": "(*\n * Listkit: A library for working with lists in Coq.\n * Copyright Ezra Cooper, 2008-2020.\n *)\n\nRequire Import List.\n\nRequire Export NthError.\n\nRequire Export Foreach.\n\nRequire Export All.\n\nLemma nth_error_foreach_ty :\n  forall A P v n xs,\n    nth_error xs n = value v -> foreach_ty A xs P -> P v.\nProof.\n induction n; simpl; intros; (destruct xs; [discriminate | ]).\n  destruct X as [H0 ?].\n  inversion H.\n  congruence.\n firstorder.\nQed.\n\nLemma nth_error_In:\n  forall A xs x (v:A),\n    nth_error xs x = value v -> ListSet.set_In v xs.\nProof.\n induction xs; unfold nth_error; simpl.\n  intros.\n  destruct x; discriminate.\n intros x v H.\n destruct x.\n  inversion H.\n  auto.\n right.\n eapply IHxs; eauto.\nQed.\n\nLemma nth_error_all:\n  forall A xs x v f,\n    nth_error xs x = value v ->\n    all A f xs ->\n    f v.\nProof.\n induction xs; unfold all; simpl; intros.\n  unfold nth_error in H.\n   destruct x; discriminate.\n apply H0.\n destruct x; simpl in *.\n  left; inversion H; auto.\n right.\n apply nth_error_In with x; auto.\nQed.\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/Listkit/listkit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.27072441411920817}}
{"text": "Require bedrock2.BasicC64Semantics bedrock2.NotationsCustomEntry.\nImport BinInt String List.ListNotations.\nLocal Open Scope string_scope. Local Open Scope Z_scope. Local Open Scope list_scope.\nRequire Import coqutil.Macros.ident_to_string.\n\nSection chacha20.\n  Import bedrock2.Syntax Syntax.Coercions NotationsCustomEntry.\n\n  Local Notation \"x <<<= n\" := (cmd.set (ident_to_string! x) (expr.op bopname.slu (ident_to_string! x) n)) (in custom bedrock_cmd at level 0, x ident, n bigint).\n  Local Notation \"x ^= e\" := (cmd.set (ident_to_string! x) (expr.op bopname.xor (ident_to_string! x) e)) (in custom bedrock_cmd at level 0, x ident, e custom bedrock_expr).\n  Local Notation \"x += e\" := (cmd.set (ident_to_string! x) (expr.op bopname.add (ident_to_string! x) e)) (in custom bedrock_cmd at level 0, x ident, e custom bedrock_expr).\n\n  Definition chacha20_quarter : func :=\n    (\"chacha20_quarter\", ([\"a\";\"b\";\"c\";\"d\"], [\"a\";\"b\";\"c\";\"d\"], bedrock_func_body:(\n      a += b; d ^= a; d <<<= 16;\n      c += d; b ^= c; b <<<= 12;\n      a += b; d ^= a; d <<<= 8;\n      c += d; b ^= c; b <<<= 7\n    ))).\n\n  Local Notation \"'xorout' o x\" := (\n      let addr := bedrock_expr:(out+coq:(expr.literal(4*o))) in\n      bedrock_cmd:(store4($addr, load4($addr)^$(expr.var (ident_to_string! x)))))\n      (in custom bedrock_cmd at level 0, o bigint, x ident).\n\n  Definition chacha20_block : func :=\n    (* NOTE: I (REDACTED) don't understand why xorout needs these *)\n    let x0  := \"x0\" in let x1  := \"x1\" in let x2  := \"x2\" in let x3  := \"x3\" in\n    let x4  := \"x4\" in let x5  := \"x5\" in let x6  := \"x6\" in let x7  := \"x7\" in\n    let x8  := \"x8\" in let x9  := \"x9\" in let x10 := \"x10\" in let x11 := \"x11\" in\n    let x12 := \"x12\" in let x13 := \"x13\" in let x14 := \"x14\" in let x15 := \"x15\" in\n    (\"chacha20_block\", ([\"out\"; \"key\"; \"nonce\"; \"countervalue\"], [], bedrock_func_body:(\n      x0 = $0x61707865;   x1 = $0x3320646e;   x2 = $0x79622d32;    x3 = $0x6b206574;\n      x4 = load4(key);           x5 = load4(key+$4);   x6 = load4(key+$8);    x7 = load4(key+$12);\n      x8 = load4(key+$16);  x9 = load4(key+$20); x10 = load4(key+$24);  x11 = load4(key+$28);\n      x12 = countervalue;       x13 = load4(nonce);        x14 = load4(nonce+$4); x15 = load4(nonce+$8);\n      i = $0; while (i < $10) { i += $1;\n        (x0, x4,  x8, x12) = chacha20_quarter( x0, x4, x8,  x12);\n        (x1, x5,  x9, x13) = chacha20_quarter( x1, x5, x9,  x13);\n        (x2, x6, x10, x14) = chacha20_quarter( x2, x6, x10, x14);\n        (x3, x7, x11, x15) = chacha20_quarter( x3, x7, x11, x15);\n        (x0, x5, x10, x15) = chacha20_quarter( x0, x5, x10, x15);\n        (x1, x6, x11, x12) = chacha20_quarter( x1, x6, x11, x12);\n        (x2, x7,  x8, x13) = chacha20_quarter( x2, x7, x8,  x13);\n        (x3, x4,  x9,  x1) = chacha20_quarter( x3, x4, x9,  x14)\n      };\n      x0 += $0x61707865;  x1 += $0x3320646e;   x2 += $0x79622d32;    x3 += $0x6b206574;\n      x4 += load4(key);          x5 += load4(key+$4);   x6 += load4(key+$8);    x7 += load4(key+$12);\n      x8 += load4(key+$16); x9 += load4(key+$20); x10 += load4(key+$24);  x11 += load4(key+$28);\n      x12 += countervalue;      x13 += load4(nonce);        x14 += load4(nonce+$4); x15 += load4(nonce+$8);\n      xorout  0  x0;   xorout 1 x1; xorout 2   x2;  xorout 3  x3;\n      xorout  4  x4;   xorout 5 x5; xorout 6   x6;  xorout 7  x7;\n      xorout  8  x8;   xorout 9 x9; xorout 10 x10; xorout 11 x11;\n      xorout 12 x12; xorout 13 x13; xorout 14 x14; xorout 15 x15\n  ))).\nEnd chacha20.\n\n(*\nRequire bedrock2.ToCString.\nExample chacha20_block_c_string := Eval vm_compute in\n  ToCString.c_module [chacha20_quarter; chacha20_block].\nPrint chacha20_block_c_string.\n*)\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/chacha20.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.27072441411920817}}
{"text": "From 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.backtranslations.un_syn Require Import expressions universe.base.\n\nInductive refinement :=\n  | syn_le_un (* syntactically-typed in universe ≤ untyped *)\n  | un_le_syn. (* untyped ≤ syntactically-typed in universe *)\n\nExisting Class refinement.\n\nSection definitions.\n\n  Context `{Σ : !gFunctors}.\n  Context `{irisGS_inst : !irisGS STLCmuVS_lang Σ}.\n\n  Context {rfn : refinement}.\n\n  Definition s : stuckness := MaybeStuck.\n    (* match rfn with *)\n    (* | syn_le_un => NotStuck *)\n    (* | un_le_syn => MaybeStuck (* untyped can of course get stuck *) *)\n    (* end. *)\n\n  Definition canon_tc_lift (tc : type_constructor) (Ψ : valO -n> valO -n> iPropO Σ) (xᵢ xₛ : valO) : iPropO Σ :=\n    (match tc with\n     | TCUnit => ⌜ xᵢ = ()%Vₙₒ ⌝ ∧ ⌜ xₛ = ()%Vₙₒ ⌝\n     | TCBool => ∃ b : bool, ⌜ xᵢ = b%Vₙₒ ⌝ ∧ ⌜ xₛ = b ⌝\n     | TCInt => ∃ z : Z, ⌜ xᵢ = z%Vₙₒ ⌝ ∧ ⌜ xₛ = z ⌝\n     | TCProd => ∃ v1 v2 v1' v2', ⌜ xᵢ = (v1, v2)%Vₙₒ ⌝ ∧ ⌜ xₛ = (v1', v2')%Vₙₒ ⌝ ∧ (▷ Ψ v1 v1') ∗ (▷ Ψ v2 v2')\n     | TCSum => ∃ vi vi', (⌜ xᵢ = InjLV vi ⌝ ∧ ⌜ xₛ = InjLV vi' ⌝ ∧ ▷ Ψ vi vi') ∨\n                         (⌜ xᵢ = InjRV vi ⌝ ∧ ⌜ xₛ = InjRV vi' ⌝ ∧ ▷ Ψ vi vi')\n     | TCArrow => ∃ e , ⌜ xᵢ = LamV e ⌝ ∧ ▷ □ (∀ w w', Ψ w w' -∗ lift s Ψ e.[of_val w/] (of_val xₛ w'))\n     | TCRec => ∃ w w', ⌜ xᵢ = FoldV w ⌝ ∧ ⌜ xₛ = FoldV w' ⌝ ∧ ▷ Ψ w w'\n     end)%I.\n\n  Definition valrel_gen_pre (Ψ : valO -n> valO -n> iPropO Σ) (vᵢ vₛ : valO) : iPropO Σ :=\n    match rfn with\n    | syn_le_un => (∃ tc vᵢ', ⌜ vᵢ = inject_val tc vᵢ' ⌝ ∧ canon_tc_lift tc Ψ vᵢ' vₛ)%I\n    | un_le_syn => (∃ tc vₛ', ⌜ vₛ = inject_val tc vₛ' ⌝ ∧ canon_tc_lift tc Ψ vᵢ vₛ')%I\n    end.\n\n  Definition valrel_gen (Ψ : valO -n> valO -n> iPropO Σ) : valO -n> valO -n> iPropO Σ := λne v v', valrel_gen_pre Ψ v v'.\n\n  Instance valrel_gen_contractive : Contractive valrel_gen.\n  Proof.\n    intros n P1 P2 dl. rewrite /valrel_gen. intros v v'. simpl.\n    rewrite /valrel_gen_pre; destruct rfn; f_equiv; intro tc; rewrite /inject_val /InjVTC /canon_tc_lift; destruct tc; rewrite /lift; solve_contractive.\n  Qed.\n\n  Definition valrel := fixpoint valrel_gen.\n\n  Lemma valrel_unfold v1 v2 : fixpoint valrel_gen v1 v2 ≡ valrel_gen (fixpoint valrel_gen) v1 v2.\n  Proof. do 2 f_equiv. by rewrite -fixpoint_unfold. Qed.\n\n  Global Instance valrel_persistent u v' : Persistent (valrel u v').\n  Proof.\n    rewrite /Persistent. revert u v'. iLöb as \"IHlob\". iIntros (u v') \"Huv'\".\n    rewrite valrel_unfold /= /valrel_gen_pre. destruct rfn.\n    { iDestruct \"Huv'\" as (tc v) \"[-> Hvv']\".\n    iExists tc, v. iSplit; auto. destruct tc; try by iDestruct \"Hvv'\" as \"#Hvv'\".\n    - simpl; fold valrel. iDestruct \"Hvv'\" as (v1 v2 v1' v2') \"(-> & -> & H1 & H2)\".\n      iExists v1, v2, v1', v2'. repeat iSplit; auto.\n      iApply bi.later_persistently_1. iNext. by iApply \"IHlob\".\n      iApply bi.later_persistently_1. iNext. by iApply \"IHlob\".\n    - simpl; fold valrel. iDestruct \"Hvv'\" as (vi vi') \"[(-> & -> & H) | (-> & -> & H)]\".\n      iExists _, _. iLeft. repeat iSplit; auto. iApply bi.later_persistently_1. by iApply \"IHlob\".\n      iExists _, _. iRight. repeat iSplit; auto. iApply bi.later_persistently_1. by iApply \"IHlob\".\n    - simpl. fold valrel. iDestruct \"Hvv'\" as (w w') \"(-> & -> & H)\".\n      iExists _,_. repeat iSplit; auto. iApply bi.later_persistently_1. by iApply \"IHlob\". }\n    { iDestruct \"Huv'\" as (tc v) \"[-> Hvv']\".\n    iExists tc, v. iSplit; auto. destruct tc; try by iDestruct \"Hvv'\" as \"#Hvv'\".\n    - simpl; fold valrel. iDestruct \"Hvv'\" as (v1 v2 v1' v2') \"(-> & -> & H1 & H2)\".\n      iExists v1, v2, v1', v2'. repeat iSplit; auto.\n      iApply bi.later_persistently_1. iNext. by iApply \"IHlob\".\n      iApply bi.later_persistently_1. iNext. by iApply \"IHlob\".\n    - simpl; fold valrel. iDestruct \"Hvv'\" as (vi vi') \"[(-> & -> & H) | (-> & -> & H)]\".\n      iExists _, _. iLeft. repeat iSplit; auto. iApply bi.later_persistently_1. by iApply \"IHlob\".\n      iExists _, _. iRight. repeat iSplit; auto. iApply bi.later_persistently_1. by iApply \"IHlob\".\n    - simpl. fold valrel. iDestruct \"Hvv'\" as (w w') \"(-> & -> & H)\".\n      iExists _,_. repeat iSplit; auto. iApply bi.later_persistently_1. by iApply \"IHlob\". }\n  Qed.\n\n  Definition exprel : exprO -n> exprO -n> iPropO Σ :=\n    λne eᵢ eₛ, lift s valrel eᵢ eₛ.\n\n  Definition open_exprel (n : nat) (e : expr) (e' : expr) : Prop :=\n    ∀ (us : list val) (vs' : list val), length us = n →\n      ([∗ list] uᵢ ; vᵢ' ∈ us ; vs', valrel uᵢ vᵢ') ⊢\n        exprel e.[subst_list_val us] e'.[subst_list_val vs'].\n\n  Lemma open_exprel_nil e e' : (⊢ exprel e e') -> open_exprel 0 e e'.\n  Proof. iIntros (Hee' vs vs' Hl) \"Hvv'\". destruct vs, vs'; try by inversion Hl. asimpl. iApply Hee'. Qed.\n\n  Lemma open_exprel_nil' e e' : open_exprel 0 e e' → (⊢ exprel e e').\n  Proof. iIntros (Hee'). iDestruct (Hee' [] []) as \"H\". auto. asimpl. by iApply \"H\". Qed.\n\n  Definition ctx_rel (n m : nat)\n             (C : ctx)\n             (C' : ctx) :=\n    ∀ e e' , open_exprel n e e' → open_exprel m (fill_ctx C e) (fill_ctx C' e').\n\n  Lemma ctx_rel_app (n m l : nat) (C1 C1' C2 C2' : ctx) :\n    ctx_rel n m C2 C2' → ctx_rel m l C1 C1' →\n    ctx_rel n l (C1 ++ C2) (C1' ++ C2').\n  Proof. intros H2 H1 e e' Hee'. rewrite -!fill_ctx_app. apply H1, H2, Hee'. Qed.\n\nEnd definitions.\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/un_syn/logrel/definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.27068259648465637}}
{"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\nInductive bst (x : ptr) (sz : nat) (lo : nat) (hi : nat) (h : heap) : Prop :=\n| bst_1 of (x) == (null) of\n  (hi) == (0) /\\ (lo) == (7) /\\ (sz) == (0) /\\ h = empty\n| bst_2 of ~~ ((x) == (null)) of\n  exists (sz1 : nat) (sz2 : nat) (v : nat) (hi2 : nat) (hi1 : nat) (lo1 : nat) (lo2 : nat) (l : ptr) (r : ptr),\n  exists h_bst_lsz1lo1hi1_0 h_bst_rsz2lo2hi2_1,\n  (0) <= (sz1) /\\ (0) <= (sz2) /\\ (0) <= (v) /\\ (hi) == ((if (hi2) <= (v) then v else hi2)) /\\ (hi1) <= (v) /\\ (lo) == ((if (v) <= (lo1) then v else lo1)) /\\ (sz) == (((1) + (sz1)) + (sz2)) /\\ (v) <= (7) /\\ (v) <= (lo2) /\\ h = x :-> (v) \\+ x .+ 1 :-> (l) \\+ x .+ 2 :-> (r) \\+ h_bst_lsz1lo1hi1_0 \\+ h_bst_rsz2lo2hi2_1 /\\ bst l sz1 lo1 hi1 h_bst_lsz1lo1hi1_0 /\\ bst r sz2 lo2 hi2 h_bst_rsz2lo2hi2_1.\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/common.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.27068258546251345}}
{"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 C T Dprime Pprime Cprime Dprimeprime Pprimeprime Z Zprime : Universe, ((wd_ P Q /\\ (wd_ A T /\\ (wd_ T C /\\ (wd_ A C /\\ (wd_ Cprime Pprimeprime /\\ (wd_ T Pprime /\\ (wd_ Z Zprime /\\ (wd_ T Cprime /\\ (wd_ Dprimeprime Cprime /\\ (wd_ Dprime T /\\ (wd_ Zprime T /\\ (wd_ Z T /\\ (wd_ T Pprimeprime /\\ (wd_ T Dprimeprime /\\ (wd_ Cprime C /\\ (wd_ A Dprime /\\ (wd_ Pprime Cprime /\\ (col_ A T Zprime /\\ (col_ Zprime T Z /\\ (col_ T C Z /\\ (col_ Cprime Dprimeprime Pprimeprime /\\ (col_ T Cprime A /\\ col_ T Dprime Pprime)))))))))))))))))))))) -> col_ A T 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_0556.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.2706564492836651}}
{"text": "Require Import FP.Data.Ascii.\nRequire Import FP.Data.String.\nRequire Import FP.Data.List.\nRequire Import FP.Data.N.\nRequire Import FP.Data.NRelations.\nRequire Import FP.Data.NStructures.\nRequire Import FP.Data.Function.\nRequire Import FP.Structures.Monad.\nRequire Import FP.Structures.Functor.\nRequire Import FP.Structures.EqDec.\nRequire Import FP.Structures.Show.\nRequire Import FP.Structures.Comonad.\nRequire Import FP.Structures.Foldable.\nRequire Import FP.Structures.Functor.\nRequire Import FP.Structures.FUnit.\nRequire Import FP.Structures.Iterable.\nRequire Import FP.Structures.Applicative.\nRequire Import FP.Structures.Additive.\nRequire Import FP.Structures.Applicative.\nRequire Import FP.Structures.Functor.\nRequire Import FP.Structures.FZero.\nRequire Import FP.Structures.Traversable.\nRequire Import FP.Structures.Monad.\nRequire Import FP.Structures.Comonad.\nRequire Import FP.Data.PrettyI.\nRequire Import FP.Structures.Monoid.\n\nImport AdditiveNotation.\nImport MonadNotation.\nImport EqDecNotation.\nImport ApplicativeNotation.\nImport FunctionNotation.\nImport CharNotation.\nImport ListNotation.\nImport MonoidNotation.\nImport ComonadNotation.\nImport StringNotation.\nImport NNotation.\n\nSection coercions.\n  Context {m} {M:FUnit m} {MP:FZero m}.\n  Definition coerce_cons {A} (xs:list A) : m (A*list A) :=\n    match xs with\n    | [] => fzero\n    | x::xs => funit (x,xs)\n    end.\nEnd coercions.\n\nSection Show.\n  Context {A} {AS:Show A}.\n\n  Section list_show.\n    Variable (R:Type) (SR:ShowResult R).\n\n    Fixpoint list_show_inner (xL:list A) : R :=\n      match xL with\n      | nil => gunit\n      | x::xL' =>\n             raw_string \"; \"\n          ** show x\n          ** list_show_inner xL'\n      end.\n          \n    Definition list_show (xL:list A) : R :=\n      match xL with\n      | nil => raw_string \"[]\"\n      | x::nil =>\n             raw_char \"[\"%char\n          ** show x\n          ** raw_char \"]\"%char\n      | x1::x2::xL =>\n             raw_char \"[\"%char\n          ** show x1\n          ** list_show_inner (x2::xL)\n          ** raw_char \"]\"%char\n      end.\n  End list_show.\n\n  Global Instance list_Show : Show (list A) := { show := list_show }.\nEnd Show.\n\nSection Pretty.\n  Context {A} {SP:Pretty A}.\n\n  Fixpoint list_pretty_inner (xL:list A) :=\n    match xL with\n    | nil => nil_d\n    | x::xL =>\n        text_d \"; \" `concat_d`\n        nest_d 2 (pretty x) `concat_d`\n        line_d `concat_d`\n        list_pretty_inner xL\n    end.\n\n  Fixpoint list_pretty (xL:list A) : doc :=\n    match xL with\n    | [] => text_d \"[]\"\n    | [x] =>\n      group_d begin\n        text_d \"[ \" `concat_d`\n        nest_d 2 (pretty x) `concat_d`\n        line_d `concat_d`\n        text_d \"]\"\n      end\n    | x1::x2::xL =>\n      group_d begin\n        text_d \"[ \" `concat_d`\n        nest_d 2 (pretty x1) `concat_d`\n        line_d `concat_d`\n        list_pretty_inner (x2::xL) `concat_d`\n        text_d \"]\"\n      end\n    end.\n  Global Instance list_Pretty : Pretty (list A) := { pretty := list_pretty }.\n    \nEnd Pretty.\n\nSection Monoid.\n  Context {A:Type}.\n  Global Instance list_Monoid : Monoid (list A) :=\n    { monoid_times := app\n    ; monoid_unit := nil\n    }.\nEnd Monoid.\n\nFixpoint list_cofold {A} {m} {M:Comonad m} {B}\n    (f:A -> m B -> B) (bM:m B) (xs:list A) : B :=\n  match xs with\n  | [] => coret bM\n  | x::xs =>\n      let bM := codo bM => list_cofold f bM xs in\n      f x bM\n  end.\nInstance list_Foldable {A} : Foldable A (list A) :=\n  { cofold := @list_cofold _ }.\n\nFixpoint list_coiter {A} {m} {M:Comonad m} {B}\n    (f:m B -> A -> B) (bM:m B) (xs:list A) : B :=\n  match xs with\n  | [] => coret bM\n  | x::xs =>\n      let bM := codo bM => f bM x in\n      list_coiter f bM xs\n  end.\nInstance list_Iterable {A} : Iterable A (list A) :=\n  { coiter := @list_coiter _ }.\n\nFixpoint list_sequence {u} {uA:Applicative u} {A}\n    (xs:list (u A)) : u (list A) :=\n  match xs with\n  | nil => funit nil\n  | x::xs' => funit cons <@> x <@> list_sequence xs'\n  end.\nInstance list_Traversable : Traversable list :=\n  { tsequence := @list_sequence }.\n\nDefinition list_mbuild {A} {m} {M:Monad m}\n  (fld:forall {B}, (A -> B -> B) -> B -> m B) : m (list A) :=\n    fld cons nil.\nInstance list_Buildable {A} : Buildable A (list A) :=\n  { mbuild := @list_mbuild _ }.\n    \nInstance list_FMap : FMap list :=\n  { fmap := @map }.\n\nFixpoint zip {A B} (xs:list A) (ys:list B) : list (A*B) :=\n  match xs,ys with\n  | nil,_ => nil\n  | _,nil => nil\n  | x::xs',y::ys' => (x,y)::zip xs' ys'\n  end.\n\nFixpoint zip_with {A B C} (f:A -> B -> C) (xs:list A) (ys:list B) : list C :=\n  match xs,ys with\n  | nil, _ => nil\n  | _, nil => nil\n  | x::xs',y::ys' => f x y::zip_with f xs' ys'\n  end.\n\nFixpoint unzip {A B} (xys:list (A*B)) : list A * list B :=\n  match xys with\n  | nil => (nil, nil)\n  | (x,y)::xys' =>\n      let (xs,ys) := unzip xys'\n      in (x::xs,y::ys)\n  end.\n\nFixpoint nth {A} (n:N) (xs:list A) : option A :=\n  match xs with\n  | [] => None\n  | x::xs => if n =! 0 then Some x else nth (n - 1) xs\n  end.\n\nSection Monad.\n  Definition list_funit {A} (a:A) : list A := [a].\n  Global Instance list_FUnit : FUnit list :=\n    { funit := @list_funit }.\n                                    \n  Fixpoint list_bind {A B} (xs:list A) (f:A -> list B) : list B :=\n    match xs with\n    | [] => []\n    | x::xs => f x ** list_bind xs f\n    end.\n  Global Instance list_MBind : MBind list :=\n    { bind := @list_bind }.\nEnd Monad.\n\n(*\nSection MonadPlus.\n  Definition list_mzero {A} : list A := [].\n  Definition list_mplus {A B} (xs:list A) (ys:list B) : list (A+B) :=\n    fmap inl xs ** fmap inr ys.\n  Global Instance list_MonadPlus : MonadPlus list :=\n    { mzero := @list_mzero\n    ; mplus := @list_mplus\n    }.\nEnd MonadPlus.\n*)\n\nSection Groupish.\n  Context {T} {T_GTimes : GTimes T} {T_GUnit : GUnit T}.\n\n  Definition gproductr := foldr gtimes gunit.\n  Definition gproductl := foldl gtimes gunit.\nEnd Groupish.\n\n(*\nSection Alternative.\n  Context {t} {F:FMap t} {A:Alternative t}.\n\n  Definition fchoices {A} : list (t A) -> t A := foldr fchoice fzero.\nEnd Alternative.\n*)\n\nFixpoint replicateM {m A} {M:Monad m} (n:nat) (aM:m A) : m (list A) :=\n  match n with\n  | O => ret nil\n  | S n' =>\n      x <- aM ;;\n      xs <- replicateM n' aM ;;\n      ret $ cons x xs\n  end.", "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/ListStructures.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.2704424765702841}}
{"text": "Set Implicit Arguments.\nRequire Import Metalib.Metatheory.\nRequire Import Program.Equality.\nRequire Export Equiv.\n\n\nLemma label_transform3: forall (X X0:atom) T D,\n    X \\notin fl_tt T \\u {{X0}} ->\n    type D ->\n    open_tt (subst_label X (subst_tt X (typ_label X D) T))\n             (typ_label X0 (open_tt (subst_label X (subst_tt X (typ_label X D) T)) X0))\n      = subst_label X (subst_tt X (typ_label X D) (open_tt T (typ_label X0 (open_tt T X0)))).\nProof with auto.\n  intros.\n  rewrite  subst_tt_open_tt ...\n  rewrite subst_label_open_tt ...\n  f_equal...\n  rewrite drop_label_reverse_type...  \n  rewrite drop_label_reverse_type...\n  solve_notin.\nQed.\n\nLemma label_transform4 : forall (X X0:atom) T D,\n    X \\notin fl_tt T \\u {{X0}} ->\n    type D ->\n    (open_tt (subst_label X (subst_tt X (typ_label X D) T)) X0) = (subst_label X (subst_tt X (typ_label X D) (open_tt T X0))).\nProof with auto.\n  intros.\n  rewrite <- subst_label_open_tt_var...\n  f_equal...\n  rewrite subst_tt_open_tt_var...\nQed.  \n\n\nLemma binds_subst_label_existial : forall E X Y T U,\n    binds X (bind_sub U) (map (drop_label Y) (map (subst_tb Y (typ_label Y T)) E)) ->\n    exists Q,\n      binds X (bind_sub Q) E.\nProof with auto.\n  induction E;intros;simpl in *...\n  analyze_binds H...\n  destruct a.\n  analyze_binds H...\n  2: {\n    destruct IHE with (X:=X) (Y:=Y) (U:=U) (T:=T)...\n    exists x...\n  }  \n  destruct b;simpl in *.\n  + dependent destruction BindsTacVal.\n    exists t...\n  + inversion BindsTacVal.\n  + inversion BindsTacVal.\nQed.\n\n\nLemma binds_subst_label_existial_lb : forall E X Y T U,\n    binds X (bind_sub_lb U) (map (drop_label Y) (map (subst_tb Y (typ_label Y T)) E)) ->\n    exists Q,\n      binds X (bind_sub_lb Q) E.\nProof with auto.\n  induction E;intros;simpl in *...\n  analyze_binds H...\n  destruct a.\n  analyze_binds H...\n  2: {\n    destruct IHE with (X:=X) (Y:=Y) (U:=U) (T:=T)...\n    exists x...\n  }  \n  destruct b;simpl in *.\n  + inversion BindsTacVal.\n  + dependent destruction BindsTacVal.\n    exists t...\n  + inversion BindsTacVal.\nQed.\n\nLemma WF_narrowing_env_subst_inv: forall E1 E2 (X:atom) Y S,\n    WF (map (subst_tb Y S) E1 ++ Y ~ bind_sub typ_top ++ E2) X ->\n    WF (E1 ++ Y ~ bind_sub typ_top ++ E2) X.\nProof with auto.\n  induction E1;intros...\n  simpl in *.\n  destruct a.\n  dependent destruction H...\n  + analyze_binds H...\n    -\n      destruct b.\n      * apply WF_var with (U:=t)...\n      * simpl in *.\n        inversion BindsTacVal...  \n      * simpl in *.\n        inversion BindsTacVal...\n    -\n      rewrite_env (nil ++ (a~ b) ++ E1 ++ (Y, bind_sub typ_top) :: E2).\n      apply WF_weakening...\n      apply IHE1  with (S:=S)...\n      apply WF_var with (U:=U)...\n    -\n      apply WF_var with (U:=typ_top)...\n    -\n      apply WF_var with (U:=U)...\n  + analyze_binds H...\n    -\n      destruct b.\n      * apply WF_var with (U:=t)...\n      * apply WF_var_lb with (U:=t)...\n      * simpl in *.\n        inversion BindsTacVal...\n    -\n      rewrite_env (nil ++ (a~ b) ++ E1 ++ (Y, bind_sub typ_top) :: E2).\n      apply WF_weakening...\n      apply IHE1  with (S:=S)...\n      apply WF_var_lb with (U:=U)...\n    -\n      apply WF_var_lb with (U:=U)...\nQed.   \n\n(* Lemma sub_map_inv_var: forall X Y X0 C E1 E2, \n    X <> Y -> X0 <> Y ->\n  sub (map (subst_tb Y C) E1 ++ (Y, bind_sub typ_top) :: E2) X X0 ->\n  sub (map (subst_tb Y C) E1 ++ (Y, bind_sub typ_top) :: E2) X0 X ->\n  wf_env (E1 ++ (Y, bind_sub typ_top) :: E2) ->\n  sub (E1 ++ (Y, bind_sub typ_top) :: E2) X X0.\nProof with auto.\n  intros.\n  pose proof suba_sub_tvar_chain H1.\n  pose proof suba_sub_tvar_chain H2.\n  destruct H4 as [W1 ?].\n  destruct H5 as [W2 ?].\n  pose proof sub_tvar_chain_antisym H4 H5.\n  subst.\n  apply sa_fvar...\n  get_well_form.\n  apply WF_narrowing_env_subst_inv in H6...\nQed. *)\n\nLemma drop_label_reverse_wf: forall E1 E2 C D A X,\n    WF (map (drop_label X) (map (subst_tb X (typ_label X C)) E1) ++\n            (X, bind_sub typ_top) :: E2)\n       (subst_label X (subst_tt X (typ_label X D) A)) ->\n    X \\notin fl_tt A -> type D ->\n    WF (E1 ++ (X, bind_sub typ_top) :: E2) A.\nProof with auto.\n  intros.\n  assert (type A) as HA.\n  get_type...\n  rewrite drop_label_reverse_type in H... \n  apply type_to_rec in HA.\n  generalize dependent E1.\n  generalize dependent E2.\n  generalize dependent C.\n  generalize dependent D.\n  generalize dependent X.\n  induction HA;intros;simpl in *;try solve [dependent destruction H;auto]...\n  -\n    destruct (X==X0);subst...\n    +\n      apply WF_var with (U:=typ_top)...\n    +\n      simpl in H...\n      dependent destruction H...\n      * analyze_binds H...\n        apply binds_subst_label_existial in BindsTac.\n        destruct_hypos.\n        apply WF_var with (U:=x)...\n        apply WF_var with (U:=U)...\n      * analyze_binds H...\n        apply binds_subst_label_existial_lb in BindsTac.\n        destruct_hypos.\n        apply WF_var_lb with (U:=x)...\n        apply WF_var_lb with (U:=U)...\n  -\n    dependent destruction H.\n    constructor...\n    apply IHHA1 with (C:=C) (D:=D)...\n    apply IHHA2 with (C:=C) (D:=D)...\n  -\n    dependent destruction H5.\n    apply WF_rec with (L:=L \\u L0 \\u {{X}});intros...\n    +\n      rewrite_env ((X0 ~ bind_sub typ_top ++ E1) ++ (X, bind_sub typ_top) :: E2).\n      apply H2 with (C:=C) (D:=D)...\n      solve_notin.\n      rewrite <- subst_tt_open_tt_var...\n      rewrite  subst_label_open_tt_var...\n      apply H5...\n    +\n      rewrite_env ((X0 ~ bind_sub typ_top ++ E1) ++ (X, bind_sub typ_top) :: E2).\n      apply H0 with (C:=C) (D:=D)...\n      solve_notin.\n      rewrite <- label_transform3...\n      apply H6...\n  -\n    dependent destruction H3.\n    apply WF_all with (L:=L \\u L0 \\u {{X}});intros...\n    +\n      apply IHHA with (C:=C) (D:=D)...\n    +\n      rewrite_env ((X0 ~ bind_sub T1 ++ E1) ++ (X, bind_sub typ_top) :: E2).\n      apply H0 with (C:=C) (D:=D)...\n      solve_notin.\n      rewrite <- label_transform4...\n      simpl.\n      rewrite drop_label_reverse_type...\n      assert (T1 = subst_label X (subst_tt X (typ_label X D) T1)).\n      rewrite drop_label_reverse_type ...\n      rewrite H6.\n      apply H4...\n  -\n    dependent destruction H3.\n    apply WF_all_lb with (L:=L \\u L0 \\u {{X}});intros...\n    +\n      apply IHHA with (C:=C) (D:=D)...\n    +\n      rewrite_env ((X0 ~ bind_sub_lb T1 ++ E1) ++ (X, bind_sub typ_top) :: E2).\n      apply H0 with (C:=C) (D:=D)...\n      solve_notin.\n      rewrite <- label_transform4...\n      simpl.\n      rewrite drop_label_reverse_type...\n      assert (T1 = subst_label X (subst_tt X (typ_label X D) T1)).\n      rewrite drop_label_reverse_type ...\n      rewrite H6.\n      apply H4...\n  -\n    destruct (l==X);subst...\n    +\n      apply notin_union  in H0.\n      destruct_hypos.\n      apply test_solve_notin_7 in H0.\n      destruct H0.\n    +\n      dependent destruction H.\n      constructor...\n      apply IHHA with (C:=C) (D:=D)...\nQed.      \n\n\n    \nLemma WF_nominal_inversion: forall E1 E2 X A (X0:atom) D C,\n    WF (X0 ~ bind_sub typ_top ++\n           map (subst_tb X (typ_label X (open_tt C X))) E1 ++ (X, bind_sub typ_top) :: E2)\n          (open_tt (subst_tt X (typ_label X (open_tt D X)) A) X0)->\n    X \\notin {{X0}} \\u fl_tt A  ->\n    wf_env (X0 ~ bind_sub typ_top ++\n           map (subst_tb X (typ_label X (open_tt C X))) E1 ++ (X, bind_sub typ_top) :: E2) ->\n    type (open_tt D X) ->\n    WF (X0 ~ bind_sub typ_top ++ E1 ++ (X, bind_sub typ_top) :: E2) (open_tt A X0) .\nProof with auto.\n  intros.\n  rewrite subst_tt_open_tt_var in H...\n  rewrite_env ((X0 ~ bind_sub typ_top ++\n           map (subst_tb X (typ_label X (open_tt C X))) E1) ++ (X, bind_sub typ_top) :: E2) in H.\n  apply WF_drop_label in H...\n  simpl in H...\n  rewrite_env ((X0 ~ bind_sub typ_top ++ E1) ++ (X, bind_sub typ_top) :: E2).\n  apply drop_label_reverse_wf with (C:=open_tt C X) (D:=open_tt D X)...\n  solve_notin.\nQed.\n\nLtac solve_bind_inv :=\nrepeat match goal with\n| H: sub _ _ (typ_fvar ?X) |- _ => inversion H;clear H\n| H: sub _ (typ_fvar ?X) _ |- _ => inversion H;clear H\nend;subst;\nlet InvTac := fresh \"InvTac\" in\nmatch goal with\n| [ H1: binds ?X (bind_sub_lb _) ?E ,\n  H2: binds ?X (bind_sub _) ?E |- _ ] =>\n  pose proof binds_ub_lb_invalid _ _ _ H1 H2 as InvTac\nend;\ntry solve [exfalso;apply InvTac;apply uniq_from_wf_env;get_well_form;auto].\n\n\nLemma binds_ub_lb_invalid_ext: forall E1 E2 X X1 S U B U0,\n  binds X (bind_sub_lb U) \n      (map (subst_tb X1 S) E1 ++ (X1, bind_sub B) :: E2) ->\n  binds X (bind_sub U0) (E1 ++ (X1, bind_sub B) :: E2) ->\n  wf_env (E1 ++ (X1,bind_sub B) :: E2) -> \n  False.\nProof with auto.\n  intros.\n  destruct (X == X1).\n  + subst. analyze_binds_uniq H0. apply uniq_from_wf_env...\n    apply binds_mid_eq in H... inversion H.\n  + apply binds_map_free_sub with (S:=S) in H0...\n      analyze_binds H.\n      { analyze_binds H0.\n        + pose proof binds_ub_lb_invalid _ _ _ BindsTac BindsTac0.\n          apply H. apply uniq_from_wf_env in H1.\n          apply uniq_app_1 in H1. apply uniq_map_2...\n        + apply in_split in BindsTac0.\n          destruct_hypos. subst E2.\n          apply uniq_from_wf_env in H1.\n          apply fresh_app_l with (x:=X) (a:=bind_sub (subst_tt X1 S U0)) in H1...\n          apply binds_In in BindsTac. rewrite dom_map in BindsTac... }\n      { analyze_binds H0.\n        + apply in_split in BindsTac0. \n          destruct_hypos. subst E2.\n          apply uniq_from_wf_env in H1.\n          apply fresh_app_l with (x:=X) (a:=bind_sub_lb U) in H1...\n          apply binds_In in BindsTac. rewrite dom_map in BindsTac...\n        + pose proof binds_ub_lb_invalid _ _ _ BindsTac0 BindsTac.\n          apply H. apply uniq_from_wf_env in H1.\n          apply uniq_app_2 in H1. inversion H1...\n      }\nQed.\n\n\nLemma subst_reverse_equiv: forall A,\n    type4rec A -> forall B, type4rec B ->\n    forall X C D E1 E2 S,\n    X \\notin fl_tt A \\u fl_tt B \\u fv_tt S \\u fv_tt C \\u fv_tt D->\n    equiv (map (subst_tb X (typ_label X (open_tt S X))) E1 ++ (X, bind_sub typ_top) :: E2 ) (subst_tt X (typ_label X (open_tt C X)) A) (subst_tt X (typ_label X (open_tt D X)) B) ->\n    equiv (E1 ++ (X, bind_sub typ_top) :: E2) A B ->\n    WF ((X, bind_sub typ_top) :: E2) (open_tt C X) ->\n    WF ((X, bind_sub typ_top) :: E2) (open_tt D X) ->\n    WF ((X, bind_sub typ_top) :: E2) (open_tt S X) ->\n    wf_env (E1 ++ (X, bind_sub typ_top) :: E2) ->\n    (equiv ((X, bind_sub typ_top) ::E2) (open_tt C X)  (open_tt D X) \\/ (X \\notin fv_tt A \\u fv_tt B )) .\nProof with auto.\n  unfold equiv.\n  intros A HA;induction HA;\n    intros B HB;induction HB;intros;destruct_hypos;simpl in *;try solve [inversion H0|\n      inversion H1|inversion H2|inversion H3|inversion H4|inversion H5|inversion H6|inversion H7|inversion H8|inversion H9|inversion H10|destruct (X==X0);subst;auto;inversion H0\n      ]...\n  - destruct (X == X0)... subst X0.\n    dependent destruction H7...\n  -\n    destruct (X==X0);subst...\n    inversion H6. subst.\n    apply binds_mid_eq in H9... inversion H9.\n      apply uniq_from_wf_env...\n  -\n    destruct (X==X1);destruct (X0==X1);subst...\n    +\n      dependent destruction H0.\n      dependent destruction H7.\n      left.\n      apply wf_env_cons in H5...\n      apply sub_strengthening_env in H0...\n      apply sub_strengthening_env in H7...\n    +\n      inversion H0...\n      subst. inversion H6;subst...\n      2:{ apply binds_mid_eq in H10... inversion H10. apply uniq_from_wf_env... }\n      pose proof binds_ub_lb_invalid_ext _ _ _ _ _ _ _ _ H9 H10.\n      destruct H8...\n    +\n      inversion H7...\n      subst. inversion H1;subst...\n      2:{ apply binds_mid_eq in H10... inversion H10. apply uniq_from_wf_env... }\n      pose proof binds_ub_lb_invalid_ext _ _ _ _ _ _ _ _ H9 H10.\n      destruct H8...\n  - solve_bind_inv.\n  - solve_bind_inv.\n  - solve_bind_inv.\n  - solve_bind_inv.\n  - solve_bind_inv.\n  - solve_bind_inv.\n  -\n    dependent destruction H0.\n    dependent destruction H7.\n    dependent destruction H1.\n    dependent destruction H6.\n    clear IHHB1 IHHB2.\n    destruct IHHA1 with (B:=T0) (X:=X) (C:=C) (D:=D) (E1:=E1) (E2:=E2) (S:=S)...\n    destruct IHHA2 with (B:=T3) (X:=X) (C:=C) (D:=D) (E1:=E1) (E2:=E2) (S:=S)...\n  - solve_bind_inv.\n  -\n    clear H4 H6.\n    dependent destruction H8.\n    dependent destruction H15.\n    dependent destruction H12.\n    dependent destruction H15.\n    pick fresh Y.\n    assert (type (open_tt C X)) by (get_type;auto).\n    assert (type (open_tt D X)) by (get_type;auto).\n    destruct H0 with (X:=Y) (X0:=X) (B:=open_tt T0 (typ_label Y (open_tt T0 Y))) (C:=C) (D:=D) (E1:=Y~bind_sub typ_top ++E1) (E2:=E2) (S:=S)...\n    +\n      solve_notin.\n    +\n      split.\n      *\n        rewrite_env (Y ~ bind_sub typ_top ++\n                     map (subst_tb X (typ_label X (open_tt S X))) E1 ++ (X, bind_sub typ_top) :: E2).\n      rewrite subst_tt_open_tt_twice...\n      rewrite subst_tt_open_tt_twice...\n      *\n        rewrite_env (Y ~ bind_sub typ_top ++\n                     map (subst_tb X (typ_label X (open_tt S X))) E1 ++ (X, bind_sub typ_top) :: E2).\n      rewrite subst_tt_open_tt_twice...\n      rewrite subst_tt_open_tt_twice...\n    +\n      split.\n      *\n        apply H14...\n      *\n        apply H17...\n    +      \n      rewrite_env (Y ~ bind_sub typ_top ++ E1 ++ (X, bind_sub typ_top) :: E2)...\n    +\n      right.\n      apply notin_union in H24.\n      destruct_hypos.\n      apply notin_fv_open_inv in H24.\n      apply notin_fv_open_inv in H25...\n  -\n    solve_bind_inv.\n  -    \n    clear H2 IHHB.\n    dependent destruction H4.\n    dependent destruction H11.\n    dependent destruction H5.\n    dependent destruction H10.\n    destruct IHHA with (B:=T0) (X:=X) (C:=C) (D:=D) (E1:=E1) (E2:= E2) (S:=S)...\n    clear IHHA.\n    pick fresh Y.\n    destruct H0 with (B:=open_tt T3 Y) (X:=Y) (X0:=X) (C:=C) (D:=D) (E1:=Y ~ bind_sub T1 ++E1) (E2:=E2) (S:=S);clear H0...\n    +\n      solve_notin.\n    +\n      split.\n      *\n        rewrite <- subst_tt_open_tt_var...\n        rewrite <- subst_tt_open_tt_var...\n        rewrite_env (nil ++ Y ~ bind_sub (subst_tt X (typ_label X (open_tt S X)) T1) ++ map (subst_tb X (typ_label X (open_tt S X))) E1 ++ (X, bind_sub typ_top) :: E2).\n        apply sub_narrowing with (Q:=subst_tt X (typ_label X (open_tt D X)) T0)...\n        --\n          clear Fr.\n          assert (subst_tt X (typ_label X (open_tt D X)) T0 = subst_tt X (typ_label X (open_tt S X)) T0).\n          {\n            rewrite <- subst_tt_fresh...\n            rewrite <- subst_tt_fresh...\n          }\n          rewrite H0.\n          assert (equiv (X ~ bind_sub typ_top ++ E2) (typ_label X (open_tt S X)) (typ_label X (open_tt S X))).\n          {\n            apply wf_env_cons in H10.\n            unfold equiv;split;constructor;\n            apply Reflexivity...\n          }\n          apply equiv_sub_subst...\n        --\n          apply H2...\n        --\n          get_type...\n        --\n          get_type...\n      *\n        rewrite <- subst_tt_open_tt_var...\n        rewrite <- subst_tt_open_tt_var...\n        rewrite_env (nil ++ Y ~ bind_sub (subst_tt X (typ_label X (open_tt S X)) T1) ++ map (subst_tb X (typ_label X (open_tt S X))) E1 ++ (X, bind_sub typ_top) :: E2).\n        apply sub_narrowing with (Q:=subst_tt X (typ_label X (open_tt C X)) T1)...\n        --\n          clear Fr.\n          assert (subst_tt X (typ_label X (open_tt C X)) T1 = subst_tt X (typ_label X (open_tt S X)) T1).\n          {\n            rewrite <- subst_tt_fresh...\n            rewrite <- subst_tt_fresh...\n          }\n          rewrite H0.\n          assert (equiv (X ~ bind_sub typ_top ++ E2) (typ_label X (open_tt S X)) (typ_label X (open_tt S X))).\n          {\n            apply wf_env_cons in H10.\n            unfold equiv;split;constructor;\n            apply Reflexivity...\n          }\n          apply equiv_sub_subst_refl...\n          get_well_form...\n        --\n          apply H4...\n        --\n          get_type...\n        --\n          get_type...\n    +\n      split.\n      *\n        rewrite_env (nil ++ Y ~ bind_sub T1 ++ E1 ++ (X, bind_sub typ_top) :: E2).\n        apply sub_narrowing with (Q:=T0)...\n        apply H5...\n      *\n        rewrite_env (Y ~ bind_sub T1 ++ E1 ++ (X, bind_sub typ_top) :: E2).\n        apply H6...        \n    +\n      rewrite_env (Y ~ bind_sub T1 ++ E1 ++ (X, bind_sub typ_top) :: E2)...\n      constructor...\n      get_well_form...\n    +\n      right.\n      apply notin_union in H12.\n      destruct_hypos.\n      apply notin_fv_open_inv in H0.\n      apply notin_fv_open_inv in H12.\n      solve_notin.\n  -\n    solve_bind_inv.\n  -\n    clear H2 IHHB.\n    dependent destruction H4.\n    dependent destruction H11.\n    dependent destruction H5.\n    dependent destruction H10.\n    destruct IHHA with (B:=T0) (X:=X) (C:=C) (D:=D) (E1:=E1) (E2:= E2) (S:=S)...\n    clear IHHA.\n    pick fresh Y.\n    destruct H0 with (B:=open_tt T3 Y) (X:=Y) (X0:=X) (C:=C) (D:=D) (E1:=Y ~ bind_sub_lb T1 ++E1) (E2:=E2) (S:=S);clear H0...\n    +\n      solve_notin.\n    +\n      split.\n      *\n        rewrite <- subst_tt_open_tt_var...\n        rewrite <- subst_tt_open_tt_var...\n        rewrite_env (nil ++ Y ~ bind_sub_lb (subst_tt X (typ_label X (open_tt S X)) T1) ++ map (subst_tb X (typ_label X (open_tt S X))) E1 ++ (X, bind_sub typ_top) :: E2).\n        apply sub_narrowing_lb with (Q:=subst_tt X (typ_label X (open_tt D X)) T0)...\n        --\n          clear Fr.\n          assert (subst_tt X (typ_label X (open_tt D X)) T0 = subst_tt X (typ_label X (open_tt S X)) T0).\n          {\n            rewrite <- subst_tt_fresh...\n            rewrite <- subst_tt_fresh...\n          }\n          rewrite H0.\n          assert (equiv (X ~ bind_sub typ_top ++ E2) (typ_label X (open_tt S X)) (typ_label X (open_tt S X))).\n          {\n            apply wf_env_cons in H10.\n            unfold equiv;split;constructor;\n            apply Reflexivity...\n          }\n          apply equiv_sub_subst...\n        --\n          apply H2...\n        --\n          get_type...\n        --\n          get_type...\n      *\n        rewrite <- subst_tt_open_tt_var...\n        rewrite <- subst_tt_open_tt_var...\n        rewrite_env (nil ++ Y ~ bind_sub_lb (subst_tt X (typ_label X (open_tt S X)) T1) ++ map (subst_tb X (typ_label X (open_tt S X))) E1 ++ (X, bind_sub typ_top) :: E2).\n        apply sub_narrowing_lb with (Q:=subst_tt X (typ_label X (open_tt C X)) T1)...\n        --\n          clear Fr.\n          assert (subst_tt X (typ_label X (open_tt C X)) T1 = subst_tt X (typ_label X (open_tt S X)) T1).\n          {\n            rewrite <- subst_tt_fresh...\n            rewrite <- subst_tt_fresh...\n          }\n          rewrite H0.\n          assert (equiv (X ~ bind_sub typ_top ++ E2) (typ_label X (open_tt S X)) (typ_label X (open_tt S X))).\n          {\n            apply wf_env_cons in H10.\n            unfold equiv;split;constructor;\n            apply Reflexivity...\n          }\n          apply equiv_sub_subst_refl...\n          get_well_form...\n        --\n          apply H4...\n        --\n          get_type...\n        --\n          get_type...\n    +\n      split.\n      *\n        rewrite_env (nil ++ Y ~ bind_sub_lb T1 ++ E1 ++ (X, bind_sub typ_top) :: E2).\n        apply sub_narrowing_lb with (Q:=T0)...\n        apply H5...\n      *\n        rewrite_env (Y ~ bind_sub_lb T1 ++ E1 ++ (X, bind_sub typ_top) :: E2).\n        apply H6...        \n    +\n      rewrite_env (Y ~ bind_sub_lb T1 ++ E1 ++ (X, bind_sub typ_top) :: E2)...\n      constructor...\n      get_well_form...\n    +\n      right.\n      apply notin_union in H12.\n      destruct_hypos.\n      apply notin_fv_open_inv in H0.\n      apply notin_fv_open_inv in H12.\n      solve_notin.\n\n  -\n    solve_bind_inv.\n  -\n    dependent destruction H0...\n    dependent destruction H7...\n    dependent destruction H1.\n    dependent destruction H6.\n    clear IHHB.\n    destruct IHHA with (B:=A0) (X:=X) (C:=C) (D:=D) (E1:=E1) (E2:=E2) (S:=S)...   \nQed.\n\n", "meta": {"author": "juda", "repo": "dissertation-artifacts", "sha": "924adb42dac97d5fae9c288bf26808d3037d3aa0", "save_path": "github-repos/coq/juda-dissertation-artifacts", "path": "github-repos/coq/juda-dissertation-artifacts/dissertation-artifacts-924adb42dac97d5fae9c288bf26808d3037d3aa0/coq_fsub/coq_fsub_all/Reverse.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2704424765702841}}
{"text": "(* Use of idents bound to ltac names in a \"match\" *)\n\nDefinition foo : Type.\nProof.\n  let x := fresh \"a\" in\n  refine (forall k : nat * nat, let '(x, _) := k in (_ : Type)).\n  exact (a = a).\nDefined.\nGoal foo.\nintros k. elim k. (* elim because elim keeps names *)\nintros.\nCheck a. (* We check that the name is \"a\" *)\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/5414.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.4843800842769843, "lm_q1q2_score": 0.270442476570284}}
{"text": "From Coq Require Import\n     List\n     Logic.FunctionalExtensionality.\n\nFrom Heapster Require Import\n     Permissions\n     SepStep.\n\nFrom ITree Require Import\n     ITree\n     Basics.Basics\n     ITreeFacts\n     Events.State\n     Events.StateFacts\n     Events.Nondeterminism\n     Events.Exception\n     Eq.EqAxiom.\n\nRequire Import Paco.paco.\n\nImport ITreeNotations.\nImport ListNotations.\nImport ITree.Basics.Basics.Monads.\n\nLocal Open Scope itree_scope.\n\nLtac rewritebisim lem := pose proof lem as bisim;\n                         eapply bisimulation_is_eq in bisim;\n                         setoid_rewrite bisim;\n                         clear bisim.\n\nLtac rewritebisim_in lem H := pose proof lem as bisim;\n                              eapply bisimulation_is_eq in bisim;\n                              setoid_rewrite bisim in H;\n                              clear bisim.\n\nVariant modifyE S : Type -> Type :=\n| Modify : (S -> S) -> modifyE S S.\n\n(** return one of the elements in [x :: xs], as well as the complete list of unchosen elements *)\nFixpoint choose' {E} `{nondetE -< E} {X} (x : X) (xs : list X) (rest : list X) :\n  itree E (X * list X)\n  := match xs with\n     | [] => Ret (x, rest)\n     | x' :: xs => or\n                   (Ret (x, (x' :: xs) ++ rest)) (* [x] *)\n                   (choose' x' xs (x :: rest)) (* not [x] *)\n     end.\nDefinition choose {E} `{nondetE -< E} {X} x xs : itree E (X * list X) :=\n  choose' x xs [].\n\nDefinition E config := modifyE config +' nondetE.\n\nSection parallel.\n  Parameter config : Type.\n\n  Definition thread := stateT config (itree (E config)) unit.\n\n  Definition par_match par (curr : itree (E config) (config * unit)) (rest : list thread)\n    : itree (E config) (config * unit) :=\n    match (observe curr) with\n    | RetF (s', _) => match rest with\n                     | [] => Ret (s', tt)\n                     | h :: t => Tau (par (h s') t)\n                     end\n    | TauF t => Tau (par t rest)\n    | VisF (inl1 e) k =>\n      match e in modifyE _ C return (C -> itree (E config) (config * unit)) -> _ with\n      | Modify _ f =>\n        fun k' =>\n          '(curr', rest') <- choose k' rest;;\n          Vis (inl1 (Modify _ f)) (fun s' => (par (curr' s') rest'))\n      end k\n    | VisF (inr1 e) k =>\n      vis e (fun b => par (k b) rest)\n    end.\n  CoFixpoint par := par_match par.\n  Lemma rewrite_par curr rest : par curr rest = par_match par curr rest.\n  Proof.\n    apply bisimulation_is_eq.\n    revert curr rest.\n    ginit. gcofix CIH. intros. gstep. unfold par. red. reflexivity.\n  Qed.\n\n  (* Not true using ≅, need equivalence that involves nondeterminism: *)\n  (* Lemma par_unit : *)\n  (*   forall t s, par (fun s => Ret (s, tt)) [t] s ≅ par t [fun s => Ret (s, tt)] s. *)\n  (* Proof. *)\n  (*   intros. rewrite rewrite_par. unfold par_match. simpl. *)\n  (*   (* do 2 rewrite rewrite_par. *) *)\n  (*   rewrite (rewrite_par t [_]). *)\n  (*   unfold par_match. simpl. *)\n  (*   destruct (observe (t s)) eqn:?. *)\n  (*   - destruct r. pstep. (* rewrite rewrite_par. unfold par_match. *) constructor. *)\n  (*     left. *)\n  (*     do 2 rewrite rewrite_par. unfold par_match. rewrite Heqi. simpl. *)\n  (*     pstep. constructor; auto. *)\n  (*   - pstep. constructor. left. revert Heqi. revert t t0 s. pcofix CIH. intros. *)\n  (*     do 2 rewrite rewrite_par. unfold par_match. rewrite Heqi. *)\n  (*     rewrite (rewrite_par (fun _ => t0) _). unfold par_match. rewrite Heqi. simpl. *)\n  (*   - destruct e. *)\n  (* Qed. *)\nEnd parallel.\n\n(* the config is our last known state *before* giving up control *)\nVariant typing_gen {R} typing (p : perm) (Q : R -> @Perms config) :\n  config -> itree (E config) (R) -> Prop :=\n| typing_gen_ret r c :\n    pre p c ->\n    (* (forall c', rely p c c' -> p ∈ Q (c', r)) -> *)\n    p ∈ Q r ->\n    typing_gen typing p Q c (Ret r)\n| typing_gen_tau t p' c :\n    pre p c ->\n    sep_step p p' ->\n    typing p' Q c t ->\n    typing_gen typing p Q c (Tau t)\n| typing_gen_vis k f p' c :\n    pre p c ->\n    (forall c, pre p c -> guar p c (f c)) ->\n    sep_step p p' ->\n    (forall c', rely p (f c) c' -> typing p' Q (f c) (k c')) ->\n    typing_gen typing p Q c (Vis (inl1 (Modify _ f)) k)\n(* (* other events. TODO: generalize E *) *)\n| typing_gen_e X c p' (e : nondetE X) k :\n    pre p c ->\n    sep_step p p' ->\n    (forall x, typing p' Q c (k x)) ->\n    typing_gen typing p Q c (Vis (inr1 e) k)\n.\n\nLemma typing_gen_mon {R} : monotone4 (@typing_gen R).\nProof.\n  repeat intro. inversion IN; subst; econstructor; eauto.\nQed.\nHint Resolve typing_gen_mon : paco.\n\nDefinition typing_ {R} := paco4 (@typing_gen R) bot4.\n\nLemma typing__rely {R} p Q c c' (t : itree (E config) (R)) :\n  rely p c c' ->\n  typing_ p Q c t ->\n  typing_ p Q c' t.\nProof.\n  revert p Q c c' t. pcofix CIH. intros p Q c c' t Hrely Ht.\n  pinversion Ht; subst.\n  - pstep. constructor. respects. intros. apply H0; auto. (* etransitivity; eauto. *)\n  - pstep. econstructor; eauto. right. eapply CIH; eauto. eapply sep_step_rely; eauto.\n  - pstep. econstructor; eauto. right.\n    assert (rely p (f c) (f c')) by admit.\n    assert (rely p (f c) c'0) by (etransitivity; eauto).\n    eapply CIH.\n    + eapply sep_step_rely; eauto. (* apply H1. apply H5. *)\n    + specialize (H2 _ H5). pclearbot. apply H2.\n  - pstep. econstructor; eauto. right. eapply CIH; eauto. eapply sep_step_rely; eauto.\n    apply H1.\nAdmitted.\n\nLemma typing__lte {R} p Q Q' c (t : itree (E config) R) :\n  typing_ p Q c t ->\n  (forall r, Q r ⊨ Q' r) ->\n  typing_ p Q' c t.\nProof.\n  revert p Q Q' c t. pcofix CIH. intros p Q Q' c t Htyping Hlte.\n  pstep. pinversion Htyping; pclearbot; subst; econstructor; eauto.\n  - intros. apply Hlte; eauto.\n  - intros. specialize (H2 _ H3). pclearbot. eauto.\n  - intros. specialize (H1 x). eauto.\nQed.\n\n(* Lemma typing__lte' p p' Q c (t : itree (E config) (config * unit)) : *)\n(*   typing_ p Q c t -> *)\n(*   p <= p' -> *)\n(*   typing_ p' Q c t. *)\n(* Proof. *)\n(*   revert p p' Q c t. pcofix CIH. intros p p' Q c t Ht Hlte. *)\n(*   pinversion Ht; subst. *)\n(*   - pstep. constructor; auto. *)\n(*     + apply Hlte. *)\n(*     + eapply Perms_upwards_closed; eauto. *)\n(* Qed. *)\n\n(* Definition typing {R} P Q (t : stateT config (itree (E config)) R) := *)\n(*   forall p c, p ∈ P -> pre p c -> typing_ p Q (t c). *)\nDefinition typing {R} P Q (t : itree (E config) R) :=\n  forall p c, p ∈ P -> pre p c -> typing_ p Q c t.\n\nLemma typing_lte {R} P P' (Q Q' : config * R -> Perms) t: (* (t : stateT config (itree (E config)) R) : *)\n  typing P Q t ->\n  P' ⊨ P ->\n  (forall r, Q r ⊨ Q' r) ->\n  typing P' Q' t.\nProof.\n  repeat intro. eapply typing__lte; eauto.\nQed.\n\nLemma typing__bind {R S} p Q1 Q2 c\n      (t1 : itree (E config) R)\n      (t2 : R -> itree (E config) S)\n      r' :\n  typing_ p Q1 c t1 ->\n  (forall r p c, p ∈ Q1 r ->\n            pre p c ->\n            paco4 typing_gen r' p Q2 c (t2 r)) ->\n  paco4 typing_gen r' p Q2 c (bind t1 t2).\nProof.\n  revert p Q1 Q2 c t1 t2. pcofix CIH. intros p Q1 Q2 c t1 t2 Ht1 Ht2.\n  pinversion Ht1; subst.\n  - rewritebisim @bind_ret_l.\n    eapply paco4_mon; eauto.\n  - rewritebisim @bind_tau.\n    pstep. econstructor; eauto. right. eapply CIH; eauto.\n  - rewritebisim @bind_vis. pstep. econstructor; eauto. intros.\n    right. eapply CIH; eauto.\n    specialize (H2 _ H3). pclearbot. apply H2.\n  - rewritebisim @bind_vis. pstep. econstructor; eauto. intros.\n    right. eapply CIH; eauto. apply H1.\nQed.\n\nLemma typing_bind {R S} P Q1 Q2\n      (t1 : itree (E config) R)\n      (t2 : R -> itree (E config) S) :\n  typing P Q1 t1 ->\n  (forall r, typing (Q1 r) Q2 (t2 r)) ->\n  typing P Q2 (bind t1 t2).\nProof.\n  intros Ht1 Ht2 p c Hp Hpre.\n  eapply typing__bind; eauto. (* intros. eapply Ht2; eauto. apply H; reflexivity. *)\nQed.\n\nLemma typing__tau {R} p (Q : R -> Perms) c t :\n  typing_ p Q c t ->\n  typing_ p Q c (Tau t).\nProof.\n  intros Ht.\n  pinversion Ht; subst; simpl; try solve [pstep; econstructor; try reflexivity; eauto].\nQed.\n\n(* Lemma typing__par_empty p Q c t : *)\n(*   typing_ p Q c t -> *)\n(*   typing_ p Q c (par t []). *)\n(* Proof. *)\n(*   revert p t c. *)\n(*   pcofix CIH. *)\n(*   intros p t c Ht. *)\n(*   rewrite rewrite_par. unfold par_match. *)\n(*   pinversion Ht; subst; simpl. *)\n(*   - destruct r0. pstep. constructor; auto. *)\n(*   - pstep. econstructor; eauto. (* right. eapply CIH; eauto. *) *)\n(*   - pstep. unfold choose, choose'. *)\n(*     assert ((fun _ : config => x_ <- Ret (k, []);; let (curr', rest') := x_ in Vis (inl1 (Modify config f)) (fun s' => par curr' rest' s')) = *)\n(*             (fun _ => Vis (inl1 (Modify config f)) (fun s' => par k [] s'))). *)\n(*     { apply functional_extensionality. intros. *)\n(*       rewritebisim @bind_ret_l. reflexivity. } *)\n(*     unfold thread, stateT in H4. rewrite H4. *)\n\n(* TODO after this point *)\nLemma typing__par_empty p Q c t :\n  typing_ p Q c t ->\n  typing_ p Q c (par t []).\nProof.\n  revert p t c.\n  pcofix CIH.\n  intros p t c Ht.\n  rewrite rewrite_par. unfold par_match.\n  pinversion Ht; subst; simpl.\n  - destruct r0, u. pstep. constructor; auto.\n  - pstep. econstructor; eauto. (* right. eapply CIH; eauto. *)\n  - pstep. unfold choose, choose'.\n    rewritebisim @bind_ret_l.\n    econstructor; eauto.\n    clear Ht H.\n    right. eapply CIH; eauto.\n    specialize (H2 _ H). pclearbot. eauto.\n  - pstep. econstructor; eauto. intros. right. apply CIH. apply H1.\nQed.\n\nLemma typing_par_empty P Q t :\n  typing P Q t ->\n  typing P Q (par t []).\nProof.\n  intros Ht p c Hp Hpre. apply typing__par_empty; auto.\nQed.\n\nLemma typing__frame p p' r (Q : unit -> Perms) R c t :\n  typing_ p Q c t ->\n  r ∈ R ->\n  p ** r <= p' ->\n  pre p' c ->\n  typing_ p' (fun c' => Q c' * R) c t.\nProof.\n  revert p p' r Q R t c.\n  pcofix CIH. intros p p' r' Q R t c Ht Hr Hp' Hpre.\n  pinversion Ht; subst.\n  - destruct r0. pstep. constructor; auto.\n    (* apply Hp'. *)\n    eapply Perms_upwards_closed; eauto. apply sep_conj_Perms_perm; auto.\n    (* apply H0; auto. apply Hp'; auto. *)\n  - pstep. econstructor; auto.\n    + eapply sep_step_lte; eauto. eapply sep_step_sep_conj_l.\n      apply Hp' in Hpre. apply Hpre.\n      apply H0.\n    + right. eapply CIH; eauto. reflexivity.\n      split; [| split]. pinversion H1; auto.\n      apply Hp'. apply Hpre.\n      apply H0. apply Hp' in Hpre. apply Hpre.\n  - pstep. econstructor; auto.\n    (* + apply Hp'. constructor. left. auto. *)\n    + intros. apply Hp'. constructor. left. apply H0. apply Hp'; auto.\n    + eapply sep_step_lte; eauto. eapply sep_step_sep_conj_l.\n      apply Hp' in Hpre. apply Hpre.\n      apply H1.\n    + intros. right.\n      assert (rely p (f c) c').\n      { apply Hp'. auto. }\n      specialize (H2 _ H4). pclearbot.\n      eapply CIH; eauto. reflexivity.\n      split; [| split].\n      * pinversion H2; auto.\n      * pose proof Hpre as Hpre'. apply Hp' in Hpre'. destruct Hpre' as (Hp & Hr' & Hsep).\n        specialize (H0 _ Hp). apply Hsep in H0. respects. (* etransitivity; eauto. apply Hp'. auto. apply Hp'; auto. *)\n      * apply H1. apply Hp' in Hpre. apply Hpre.\n  - pstep. econstructor; eauto.\n    + eapply sep_step_lte; eauto. eapply sep_step_sep_conj_l.\n      apply Hp' in Hpre. apply Hpre.\n      apply H0.\n    + intros. specialize (H1 x). right. eapply CIH; eauto. reflexivity.\n      split; [| split]. pinversion H1; auto.\n      apply Hp'. auto.\n      apply Hp' in Hpre. apply H0. apply Hpre.\nQed.\n\nLemma typing__frame' p p' r (Q R : (config * unit) -> Perms) t c :\n  typing_ p Q c t ->\n  (forall c', rely r c c' -> r ∈ R (c', tt)) ->\n  r ** p <= p' ->\n  pre p' c ->\n  typing_ p' (fun c => R c * Q c) c t.\nAdmitted.\n(* Proof. *)\n(*   revert p p' r Q R t c. *)\n(*   pcofix CIH. intros p p' r' Q R t c Ht Hr Hp' Hpre. *)\n(*   pinversion Ht; subst. *)\n(*   - pstep. constructor; auto. destruct r0. intros. *)\n(*     eapply Perms_upwards_closed; eauto. apply sep_conj_Perms_perm; auto. *)\n(*     + apply Hr; auto. apply Hp'; auto. *)\n(*     + apply H0; auto. apply Hp'; auto. *)\n(*   - pstep. econstructor; auto. *)\n(*     + eapply sep_step_lte; eauto. eapply sep_step_sep_conj_r. *)\n(*       apply Hp' in Hpre. destruct Hpre as (_ & _ & Hpre). symmetry in Hpre. apply Hpre. *)\n(*       apply H0. *)\n(*     + right. eapply CIH; eauto. reflexivity. *)\n(*       (* intros. apply Hr. apply Hp'. eapply sep_step_rely; eauto. *) *)\n\n(*       split; [| split]. *)\n(*       apply Hp'. apply Hpre. *)\n(*       pinversion H1; auto. *)\n(*       symmetry. apply H0. apply Hp' in Hpre. *)\n(*       destruct Hpre as (_ & _ & Hpre). symmetry in Hpre. apply Hpre. *)\n(*   - pstep. econstructor; eauto. *)\n(*     + apply Hp'. constructor. right. auto. *)\n(*     + eapply sep_step_lte; eauto. eapply sep_step_sep_conj_r; eauto. *)\n(*       apply Hp' in Hpre. destruct Hpre as (_ & _ & Hpre). symmetry in Hpre. apply Hpre. *)\n(*     + intros. right. *)\n(*       assert (rely p c' c''). *)\n(*       { apply Hp'. auto. } *)\n(*       specialize (H2 _ H4). pclearbot. *)\n(*       eapply CIH; eauto. 2: reflexivity. *)\n\n(*       intros. apply Hr. etransitivity; eauto. *)\n(*       apply Hp' in Hpre. destruct Hpre as (_ & _ & Hsep). transitivity c'. *)\n(*       apply Hsep; auto. apply Hp'; auto. *)\n\n(*       split; [| split]. *)\n(*       * pose proof Hpre as Hpre'. apply Hp' in Hpre'. destruct Hpre' as (_ & _ & Hsep). *)\n(*         apply Hsep in H0. respects. etransitivity; eauto. apply Hp'. auto. apply Hp'; auto. *)\n(*       * pinversion H2; auto. *)\n(*       * symmetry. apply H1. apply Hp' in Hpre. *)\n(*         destruct Hpre as (_ & _ & Hpre). symmetry in Hpre. apply Hpre. *)\n(*   - pstep. econstructor; eauto. *)\n(*     + eapply sep_step_lte; eauto. eapply sep_step_sep_conj_r; eauto. *)\n(*       apply Hp' in Hpre. destruct Hpre as (_ & _ & Hpre). symmetry in Hpre. apply Hpre. *)\n(*     + intros. specialize (H1 x). right. eapply CIH; eauto. reflexivity. *)\n(*       split; [| split]. *)\n(*       apply Hp'. auto. *)\n(*       pinversion H1; auto. *)\n(*       symmetry. apply Hp' in Hpre. apply H0. *)\n(*       destruct Hpre as (_ & _ & Hpre). symmetry in Hpre. apply Hpre. *)\n(* Qed. *)\n\n(* Lemma typing_frame P P' (Q : config * unit -> Perms) t : *)\n(*   typing P Q t -> *)\n(*   typing (P * P') (fun r => Q r * P') t. *)\n(* Proof. *)\n(*   intros Ht p'' c (p & p' & Hp & Hp' & Hlte) Hpre. *)\n(*   specialize (Ht _ _ Hp). *)\n(*   revert Ht Hp Hp' Hlte. revert P P' Q t p p'' p'. *)\n(*   pcofix CIH. intros. pinversion Ht; subst; simpl. *)\n(*   - destruct r0. pstep. constructor; auto. *)\n(*     admit. *)\n(*     intros. eapply Perms_upwards_closed; eauto. *)\n(*     apply sep_conj_Perms_perm; auto. apply H0. apply Hlte; auto. *)\n(*   - pstep. econstructor; auto. *)\n(*     + eapply sep_step_lte; eauto. eapply sep_step_sep_conj_l. *)\n(*       apply Hp' in Hpre. apply Hpre. *)\n(*       apply H0. *)\n\n(*     2: { *)\n(*       right. eapply CIH; eauto. *)\n\n(*     eapply typing__frame; eauto. apply H; auto. apply H3. auto. *)\n(* Qed. *)\n\nLemma typing__par p1 p2 p Q1 Q2 c t1 t2 :\n  typing_ p1 Q1 c t1 ->\n  typing_ p2 Q2 c (t2 c) ->\n  p1 ** p2 <= p ->\n  pre p c ->\n  typing_ p (fun c => Q1 c * Q2 c) c (par t1 [t2]).\nProof.\n  revert p1 p2 p c t1 t2. pcofix CIH. intros p1 p2 p c t1 t2 Ht1 Ht2 Hlte Hpre.\n  rewrite rewrite_par. unfold par_match.\n  (* assert (Hguar1: guar p1 c c) by reflexivity. specialize (Ht1 _ Hguar1). *)\n  pinversion Ht1; subst; simpl.\n  - destruct r0, u. pstep. econstructor; eauto. reflexivity. left.\n    eapply paco4_mon_bot; eauto. eapply typing__frame'; eauto.\n    apply typing__par_empty. apply Ht2; intuition.\n    intros; eauto.\n  - pstep. econstructor; eauto.\n    2: { right. eapply CIH. apply H3. apply Ht2.\n         reflexivity. split; [| split]; auto.\n         pinversion H3; auto.\n         apply Hlte; auto.\n         apply H1. apply Hlte in Hpre. apply Hpre.\n    }\n    etransitivity; eauto. apply sep_step_lte'; eauto.\n    apply sep_step_sep_conj_l; auto. apply Hlte in Hpre. apply Hpre.\n  - unfold choose, choose', or. rewritebisim @bind_vis. simpl.\n    pstep. econstructor; eauto. reflexivity.\n    intros []; left; rewritebisim @bind_ret_l.\n    + pstep. econstructor; auto.\n      * apply Hlte. constructor 1; auto.\n      * eapply sep_step_lte; eauto. apply sep_step_sep_conj_l; eauto.\n        apply Hlte in Hpre. apply Hpre.\n      * intros. right. eapply CIH; eauto.\n        -- assert (Hrely : rely p1 c' c''). apply Hlte; auto.\n           specialize (H4 _ Hrely). pclearbot. eauto.\n        -- apply Hlte in H3. destruct H3.\n           (* eapply typing_rely. transitivity c'; eauto. *)\n           (* apply Hlte in Hpre. destruct Hpre as (_ & _ & Hsep). *)\n        (* apply Hsep; eauto. auto. *)\n           admit.\n        -- reflexivity.\n        -- split; [| split].\n           ++ apply Hlte in H3. destruct H3. specialize (H4 _ H3).\n              pclearbot. pinversion H4; auto.\n           ++ respects; auto. apply Hlte; eauto.\n              apply Hlte in Hpre. pose proof Hpre as (_ & _ & Hsep).\n              respects; eauto. apply Hsep; eauto. apply Hpre.\n           ++ apply H2; auto. apply Hlte in Hpre. apply Hpre.\n    + admit.\n  - pstep. econstructor; auto.\n    2: { intros. specialize (H3 x). right. eapply CIH. apply H3. eauto. reflexivity.\n         split; [| split].\n         - pinversion H3; auto.\n         - apply Hlte; auto.\n         - apply H1. apply Hlte in Hpre. apply Hpre. }\n    eapply sep_step_lte; eauto. apply sep_step_sep_conj_l; auto.\n    apply Hlte in Hpre. apply Hpre.\nAdmitted.\n\nLemma typing_par P1 P2 (Q1 Q2 : config * unit -> Perms) t1 t2 :\n  typing P1 Q1 t1 ->\n  typing P2 Q2 t2 ->\n  typing (P1 * P2) (fun c => Q1 c * Q2 c) (par t1 [t2]).\nProof.\n\n  repeat intro. destruct H1 as (? & ? & ? & ? & ?).\n  eapply typing__par; eauto. unfold typing in *.\n  apply H; auto. apply H4; auto.\n  apply H0; auto. apply H4; auto.\n\n  (* (* revert t1 t2 P1 P2 Q1 Q2. *) *)\n  (* intros Ht1 Ht2 p c (p1 & p2 & Hp1 & Hp2 & Hlte) Hpre. *)\n  (* assert (Hpre1 : pre p1 c). { apply Hlte; auto. } *)\n  (* assert (Hpre2 : pre p2 c). { apply Hlte; auto. } *)\n  (* specialize (Ht1 _ _ Hp1 Hpre1). *)\n  (* specialize (Ht2 _ _ Hp2 Hpre2). *)\n  (* revert Ht1 Ht2 Hp1 Hp2 Hlte Hpre Hpre1 Hpre2. revert t1 t2 c p1 p2 p (* P1 P2 Q1 Q2 *). *)\n  (* (* pcofix CIH. *) intros t1 t2 c p1 p2 p (* P1 P2 Q1 Q2 *). *)\n  (* intros Ht1 Ht2 Hp1 Hp2 Hlte Hpre Hpre1 Hpre2. *)\n  (* rewrite rewrite_par. unfold par_match. pinversion Ht1; subst; simpl. *)\n  (* - destruct r0. pstep. econstructor; eauto. reflexivity. left. *)\n  (*   eapply paco4_mon_bot; eauto. eapply typing__frame'; eauto. *)\n  (*   apply typing__par_empty. apply Ht2; auto. *)\n  (*   intros; eauto. *)\n  (* - pstep. econstructor; eauto. *)\n  (*   2: { right. eapply CIH. apply H3. apply Ht2. all: auto. *)\n  (*        admit. (* we need typing_ version... *) *)\n  (*        reflexivity. split; [| split]; auto. *)\n  (*        pinversion H3; auto. *)\n  (*        apply H1. apply Hlte in Hpre. apply Hpre. *)\n  (*        pinversion H3; auto. *)\n  (*   } *)\n  (*   etransitivity; eauto. apply sep_step_lte'; eauto. *)\n  (*   apply sep_step_sep_conj_l; auto. apply Hlte in Hpre. apply Hpre. *)\n  (* - unfold choose, choose', or. rewritebisim @bind_vis. simpl. *)\n  (*   pstep. econstructor; eauto. reflexivity. *)\n  (* - eapply typing_par_empty in Ht2. *)\n  (*   red in Ht2. *)\n  (*   eapply paco4_mon_bot. apply Ht2; eauto. admi.t *)\n  (*   intros. eauto. *)\n  (* - *)\nQed.\n", "meta": {"author": "GaloisInc", "repo": "heapster-formalization", "sha": "1c5ed40a556a2b45f8f137ba475eb4bca76dcc70", "save_path": "github-repos/coq/GaloisInc-heapster-formalization", "path": "github-repos/coq/GaloisInc-heapster-formalization/heapster-formalization-1c5ed40a556a2b45f8f137ba475eb4bca76dcc70/src/Modify.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.27044246945067957}}
{"text": "Require Import BoolProd Coq.Lists.Streams.\n\nDeclare ML Module \"mTranslateStream\".\nOpen Scope my_scope.\n\n\n(* For the internal of the plugin. *)\nDefinition timesBool := fun Aᵗ => Aᵗ × bool.\nDefinition pairTrue   := fun (Aᵗ : Type) => (Aᵗ, true).\n\n\nCoFixpoint id {A : Type} (x : A) : Stream A :=\n  Cons x (id x).\n\n\n(* This translation implements a constructive version of the negation of stream extensionality. *)\n\n(* EqSt is bisimilarity. *)\nImplement notStreamExt : forall (A : Type),\n    A -> {s1 : Stream A & {s2 : Stream A & EqSt s1 s2 /\\ (s1 = s2 -> False)}}\n  using timesBool pairTrue.\nProof.\n  compute. intros A x. exists (id x, true). exists (id x, false). cbn. split.\n  - apply EqSt_reflex.\n  - intro H.  apply (f_equal snd) in H; cbn in H. discriminate H.\nDefined.\n\n\n(* ** Some check of the translation on other types. *** *)\n\nImplement f : {P : Prop & {Q : Prop &  ((P -> Q) -> (Q -> P) -> P = Q) -> False}}\n                using timesBool pairTrue.\nAbort.\n\nImplement foo : forall A B : Type, forall (f g : A -> B), forall x, f x = g x\n                using timesBool pairTrue.\nAbort.\n\nImplement wqd : forall (A : Type) (B : A -> Prop), forall x, B x\n                using timesBool pairTrue.\ncompute.\nAbort.", "meta": {"author": "CoqHott", "repo": "Program-translations-CC-omega", "sha": "6e809d216d6579b5a81398d679f17095c430e1c3", "save_path": "github-repos/coq/CoqHott-Program-translations-CC-omega", "path": "github-repos/coq/CoqHott-Program-translations-CC-omega/Program-translations-CC-omega-6e809d216d6579b5a81398d679f17095c430e1c3/Coq plugins/TestStream.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300698514778, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.2704123557509799}}
{"text": "Require Import Raft.\n\nSection TermSanityInterface.\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 no_entries_past_current_term_host net :=\n    forall (h : name) e,\n      In e (log (nwState net h)) ->\n      eTerm e <= currentTerm (nwState net h).\n\n  Definition no_entries_past_current_term_nw net :=\n    forall e p 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      eTerm e <= t.\n\n  Definition no_entries_past_current_term net :=\n    no_entries_past_current_term_host net /\\\n    no_entries_past_current_term_nw net.\n\n  Class term_sanity_interface : Prop :=\n    {\n      no_entries_past_current_term_invariant :\n        forall net,\n          raft_intermediate_reachable net ->\n          no_entries_past_current_term net\n    }.\nEnd TermSanityInterface.", "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/TermSanityInterface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.27041235095640936}}
{"text": "Require Import TreeIAux.\nLemma leftisthp2consistent_maket0 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((not (u_1 = i_0))/\\(not (treei_ancestor  iti_0 u_1 u_0))/\\(treei_member  iti_0 u_0)/\\(treei_ancestor  iti_2 u_1 u_0)/\\(treei_member  iti_2 u_0)/\\(treei_member  iti_0 u_1)/\\(treei_member  iti_2 u_1)) -> (treei_ancestor  iti_1 u_1 u_0)).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket1 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((not (u_1 = i_0))/\\(not (treei_member  iti_0 u_0))/\\(treei_ancestor  iti_2 u_1 u_0)/\\(treei_member  iti_2 u_0)/\\(treei_member  iti_0 u_1)/\\(treei_member  iti_2 u_1)) -> (treei_ancestor  iti_1 u_1 u_0)).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket2 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((not (u_1 = i_0))/\\(not (treei_member  iti_0 u_0))/\\(treei_ancestor  iti_2 u_1 u_0)/\\(treei_member  iti_2 u_0)/\\(treei_member  iti_0 u_1)/\\(treei_member  iti_2 u_1)) -> (treei_member  iti_1 u_1)).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket3 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((not (treei_ancestor  iti_2 u_1 u_0))/\\(treei_member  iti_2 u_0)/\\(treei_member  iti_0 u_1)/\\(treei_member  iti_2 u_1)) -> (not (u_1 = i_0))).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket4 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((not (treei_ancestor  iti_2 u_1 u_0))/\\(treei_member  iti_2 u_0)/\\(treei_member  iti_0 u_1)/\\(treei_member  iti_2 u_1)) -> (not (treei_ancestor  iti_0 u_1 u_0))).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket5 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((not (treei_member  iti_2 u_0))/\\(treei_member  iti_0 u_1)/\\(treei_member  iti_2 u_1)) -> (not (treei_ancestor  iti_0 u_1 u_0))).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket6 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((not (treei_member  iti_2 u_0))/\\(treei_member  iti_0 u_1)/\\(treei_member  iti_2 u_1)) -> (not (treei_member  iti_0 u_0))).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket7 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((not (treei_member  iti_2 u_0))/\\(treei_member  iti_0 u_1)/\\(treei_member  iti_2 u_1)) -> (not (treei_ancestor  iti_2 u_1 u_0))).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket8 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((not (treei_member  iti_0 u_1))/\\(treei_member  iti_2 u_1)) -> (not (treei_ancestor  iti_0 u_1 u_0))).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket9 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((treei_member  iti_1 u_0)/\\(treei_member  iti_1 u_1)/\\(not (treei_member  iti_0 u_1))/\\(treei_member  iti_2 u_1)) -> (treei_member  iti_2 u_0)).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket10 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((treei_ancestor  iti_1 u_1 u_0)/\\(treei_member  iti_1 u_0)/\\(treei_member  iti_1 u_1)/\\(not (treei_member  iti_0 u_1))/\\(treei_member  iti_2 u_1)) -> (treei_ancestor  iti_2 u_1 u_0)).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket11 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((u_1 = i_0)/\\(not (treei_ancestor  iti_1 u_1 u_0))/\\(treei_member  iti_1 u_0)/\\(treei_member  iti_1 u_1)/\\(not (treei_member  iti_0 u_1))/\\(treei_member  iti_2 u_1)) -> (treei_ancestor  iti_2 i_0 u_0)).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket12 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((not (u_1 = i_0))/\\(not (treei_ancestor  iti_1 u_1 u_0))/\\(treei_member  iti_1 u_0)/\\(treei_member  iti_1 u_1)/\\(not (treei_member  iti_0 u_1))/\\(treei_member  iti_2 u_1)) -> (not (treei_ancestor  iti_2 u_1 u_0))).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket13 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((treei_ancestor  iti_2 u_1 u_0)/\\(not (treei_member  iti_1 u_0))/\\(treei_member  iti_1 u_1)/\\(not (treei_member  iti_0 u_1))/\\(treei_member  iti_2 u_1)) -> (u_1 = i_0)).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket14 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((treei_ancestor  iti_2 u_1 u_0)/\\(not (treei_member  iti_1 u_0))/\\(treei_member  iti_1 u_1)/\\(not (treei_member  iti_0 u_1))/\\(treei_member  iti_2 u_1)) -> (treei_member  iti_0 u_0)).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket15 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((treei_member  iti_0 u_0)/\\(not (treei_ancestor  iti_2 u_1 u_0))/\\(not (treei_member  iti_1 u_0))/\\(treei_member  iti_1 u_1)/\\(not (treei_member  iti_0 u_1))/\\(treei_member  iti_2 u_1)) -> (treei_member  iti_2 u_0)).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket16 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((treei_member  iti_0 u_0)/\\(not (treei_ancestor  iti_2 u_1 u_0))/\\(not (treei_member  iti_1 u_0))/\\(treei_member  iti_1 u_1)/\\(not (treei_member  iti_0 u_1))/\\(treei_member  iti_2 u_1)) -> (not (u_1 = i_0))).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket17 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((treei_member  iti_2 u_0)/\\(not (treei_member  iti_0 u_0))/\\(not (treei_ancestor  iti_2 u_1 u_0))/\\(not (treei_member  iti_1 u_0))/\\(treei_member  iti_1 u_1)/\\(not (treei_member  iti_0 u_1))/\\(treei_member  iti_2 u_1)) -> (u_0 = i_0)).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket18 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((not (treei_member  iti_1 u_1))/\\(not (treei_member  iti_0 u_1))/\\(treei_member  iti_2 u_1)) -> (u_1 = i_0)).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket19 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((not (treei_member  iti_1 u_1))/\\(not (treei_member  iti_0 u_1))/\\(treei_member  iti_2 u_1)) -> (not (treei_ancestor  iti_1 i_0 u_0))).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket20 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((treei_ancestor  iti_2 i_0 u_0)/\\(treei_member  iti_2 u_0)/\\(not (treei_member  iti_1 u_1))/\\(not (treei_member  iti_0 u_1))/\\(treei_member  iti_2 u_1)) -> (not (i_0 = u_0))).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket21 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((not (treei_ancestor  iti_2 i_0 u_0))/\\(treei_member  iti_2 u_0)/\\(not (treei_member  iti_1 u_1))/\\(not (treei_member  iti_0 u_1))/\\(treei_member  iti_2 u_1)) -> (i_0 = u_0)).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket22 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((not (treei_member  iti_2 u_0))/\\(not (treei_member  iti_1 u_1))/\\(not (treei_member  iti_0 u_1))/\\(treei_member  iti_2 u_1)) -> (not (treei_member  iti_1 u_0))).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket23 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((not (treei_member  iti_2 u_0))/\\(not (treei_member  iti_1 u_1))/\\(not (treei_member  iti_0 u_1))/\\(treei_member  iti_2 u_1)) -> (not (treei_ancestor  iti_2 i_0 u_0))).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket24 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((not (treei_member  iti_2 u_1))) -> (not (treei_ancestor  iti_0 u_1 u_0))).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket25 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((not (treei_member  iti_2 u_1))) -> (not (u_1 = i_0))).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket26 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((not (treei_member  iti_2 u_1))) -> (not (treei_ancestor  iti_2 u_1 u_0))).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket27 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((not (treei_member  iti_0 u_0))/\\(treei_member  iti_2 u_0)/\\(not (treei_member  iti_2 u_1))) -> (not (treei_member  iti_0 u_1))).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket28 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((not (treei_member  iti_0 u_0))/\\(treei_member  iti_2 u_0)/\\(not (treei_member  iti_2 u_1))) -> (not (treei_member  iti_1 u_1))).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket29 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((not (treei_member  iti_2 u_0))/\\(not (treei_member  iti_2 u_1))) -> (not (treei_member  iti_0 u_1))).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket30 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((not (treei_member  iti_2 u_0))/\\(not (treei_member  iti_2 u_1))) -> (not (treei_member  iti_1 u_1))).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket31 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((not (u_1 = u_0))/\\(not (treei_member  iti_2 u_0))/\\(not (treei_member  iti_2 u_1))) -> (not (u_0 = i_0))).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket32 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((not (u_1 = u_0))/\\(not (treei_member  iti_2 u_0))/\\(not (treei_member  iti_2 u_1))) -> (not (treei_member  iti_0 u_0))).\nProof. solve_imaket; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma leftisthp2consistent_maket33 (i_0:nat) (iti_0:treei nat) (iti_1:treei nat) (iti_2:treei nat) (u_0:nat) (u_1:nat) : (imaket_spec  i_0 iti_0 iti_1 iti_2) -> (((not (u_1 = u_0))/\\(not (treei_member  iti_2 u_0))/\\(not (treei_member  iti_2 u_1))) -> (not (treei_member  iti_1 u_0))).\nProof. solve_imaket; 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/Verifyleftisthp2consistentmaket.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.270345727335514}}
{"text": "Require Import floyd.base.\nRequire Import floyd.client_lemmas.\nRequire Import floyd.assert_lemmas.\n\nLocal Open Scope logic.\n\nLemma typed_true_nullptr:\n forall v t t',\n   typed_true tint (force_val (sem_cmp Ceq (tptr t) (tptr t') v (Vint Int.zero))) ->\n   v=nullval.\nProof.\n intros.\n destruct v; inv H.\n pose proof (Int.eq_spec i Int.zero).\n destruct (Int.eq i Int.zero); inv H1.\n reflexivity.\nQed.\n\nLemma typed_true_nullptr':\n  forall  {cs: compspecs}  t t' v,\n    typed_true tint (eval_binop Oeq (tptr t) (tptr t') v nullval) -> v=nullval.\nProof.\n intros. unfold eval_binop, typed_true in H.\n destruct v; inv H; auto.\n pose proof (Int.eq_spec i Int.zero).\n destruct (Int.eq i Int.zero); inv H1.\n reflexivity.\nQed.\n\nLemma typed_true_Oeq_nullval:\n forall  {cs: compspecs}  v t t',\n   local (`(typed_true tint) (`(eval_binop Oeq (tptr t) (tptr t')) v `nullval)) |--\n   local (`(eq nullval) v).\nProof.\nintros.\n intro rho; unfold local, lift1; unfold_lift.\n apply prop_derives; intro.\n destruct (v rho); inv H.\n pose proof (Int.eq_spec i Int.zero).\n destruct (Int.eq i Int.zero); inv H1.\n reflexivity.\nQed.\n\nDefinition  binary_operation_to_comparison (op: binary_operation) :=\n match op with\n | Oeq => Some (@eq Z)\n | Cop.One => Some Zne\n | Olt => Some Z.lt\n | Ole => Some Z.le\n | Ogt => Some Z.gt\n | Oge => Some Z.ge\n | _ => None\n end.\n\n(*\nLemma typed_true_binop_int:\n  forall op op' e1 e2 Espec  {cs: compspecs} Delta P Q R c Post,\n   binary_operation_to_comparison op = Some op' ->\n   typeof e1 = tint ->\n   typeof e2 = tint ->\n   (PROPx P (LOCALx (tc_env Delta :: Q) (SEPx R))) |--  tc_expr Delta e1 ->\n   (PROPx P (LOCALx (tc_env Delta :: Q) (SEPx R))) |-- tc_expr Delta e2 ->\n  @semax cs Espec Delta (PROPx P (LOCALx\n      (`op' (`force_signed_int (eval_expr e1)) (`force_signed_int (eval_expr e2))\n          :: Q) (SEPx R))) c Post ->\n  @semax cs Espec Delta (PROPx P (LOCALx\n      (`(typed_true\n          (typeof (Ebinop op e1 e2 tint)))\n          (eval_expr (Ebinop op e1 e2 tint)) :: Q) (SEPx R))) c Post.\nProof.\nintros.\neapply semax_pre; [clear H4 | apply H4].\neapply derives_trans with\n (tc_expr Delta e1 && (tc_expr Delta e2\n   && PROPx P (LOCALx (tc_environ Delta :: `(typed_true (typeof (Ebinop op e1 e2 tint)))(eval_expr (Ebinop op e1 e2 tint)) :: Q) (SEPx R)))).\nrewrite <- andp_assoc.\napply andp_right; auto.\ndo 2 rewrite <- insert_local.\nrewrite <- andp_assoc.\nrewrite (andp_comm (local _)).\nrewrite andp_assoc.\napply andp_left2.\nrewrite insert_local.\napply andp_right; auto.\nclear H2 H3.\n(*do 2 rewrite insert_local.*)\nunfold PROPx, LOCALx; intro rho; simpl.\nnormalize.\nautorewrite with norm1 norm2; normalize.\nrewrite <- andp_assoc.\napply andp_derives; auto.\neapply derives_trans.\napply andp_derives; apply typecheck_expr_sound; auto.\nnormalize. split; auto.\nrewrite H1,H0 in *.\nclear H5 H2 H0 H1.\ndestruct (eval_expr e1 rho); inv H6.\ndestruct (eval_expr e2 rho); inv H7.\nunfold force_signed_int, force_int.\nunfold typed_true, eval_binop in H4.\ndestruct op; inv H; simpl in H4.\npose proof (Int.eq_spec i i0); destruct (Int.eq i i0); subst; auto.\n contradiction H4; auto.\nunfold Zne.\npose proof (Int.eq_spec i i0); destruct (Int.eq i i0); subst; auto.\ncontradict H.\nrewrite <- (Int.repr_signed i).\nrewrite <- (Int.repr_signed i0).\nf_equal; auto.\nunfold Int.lt in H4.\ndestruct (zlt (Int.signed i) (Int.signed i0)); auto; contradict H4; auto.\nunfold Int.lt in H4.\ndestruct (zlt (Int.signed i0) (Int.signed i)); auto; try omega; contradict H4; auto.\nunfold Int.lt in H4.\ndestruct (zlt (Int.signed i0) (Int.signed i)); auto; try omega; contradict H4; auto.\nunfold Int.lt in H4.\ndestruct (zlt (Int.signed i) (Int.signed i0)); auto; try omega; contradict H4; auto.\nQed.\n*)\n\nDefinition  binary_operation_to_opp_comparison (op: binary_operation) :=\n match op with\n | Oeq => Some Zne\n | Cop.One => Some (@eq Z)\n | Olt => Some Z.ge\n | Ole => Some Z.gt\n | Ogt => Some Z.le\n | Oge => Some Z.lt\n | _ => None\n end.\n\n(*\nLemma typed_false_binop_int:\n  forall op op' e1 e2 Espec  {cs: compspecs} Delta P Q R c Post,\n   binary_operation_to_opp_comparison op = Some op' ->\n   typeof e1 = tint ->\n   typeof e2 = tint ->\n   (PROPx P (LOCALx (tc_environ Delta :: Q) (SEPx R))) |-- (tc_expr Delta e1) ->\n   (PROPx P (LOCALx (tc_environ Delta :: Q) (SEPx R))) |-- (tc_expr Delta e2) ->\n  @semax cs Espec Delta (PROPx P (LOCALx\n      (`op' (`force_signed_int (eval_expr e1)) (`force_signed_int (eval_expr e2))\n          :: Q) (SEPx R))) c Post ->\n  @semax cs Espec Delta (PROPx P (LOCALx\n      (`(typed_false\n          (typeof (Ebinop op e1 e2 tint)))\n          (eval_expr (Ebinop op e1 e2 tint)) :: Q) (SEPx R))) c Post.\nProof.\nintros.\neapply semax_pre; [clear H4 | apply H4].\neapply derives_trans with\n ( local (tc_environ Delta) && ((tc_expr Delta e1) && ( (tc_expr Delta e2)\n   && PROPx P (LOCALx (tc_environ Delta :: `(typed_false (typeof (Ebinop op e1 e2 tint)))(eval_expr (Ebinop op e1 e2 tint)) :: Q) (SEPx R))))).\napply andp_right.\nrewrite <- insert_local. apply andp_left1; auto.\nrewrite <- andp_assoc.\napply andp_right; auto.\ndo 2 rewrite <- insert_local.\nrewrite <- andp_assoc.\nrewrite (andp_comm (local _)).\nrewrite andp_assoc.\napply andp_left2.\nrewrite insert_local.\napply andp_right; auto.\nclear H2 H3.\nunfold PROPx, LOCALx; intro rho; simpl.\nunfold local,lift1 at 1.\napply derives_extract_prop; intro TCE.\neapply derives_trans.\napply andp_derives; [ apply typecheck_expr_sound; auto | ].\napply andp_derives; [ apply typecheck_expr_sound; auto | ].\napply derives_refl.\nnormalize. autorewrite with norm1 norm2; normalize.\napply andp_right; auto. apply prop_right.\nsplit; auto.\nclear H6 TCE.\nrewrite H0 in *; rewrite H1 in *.\nclear H0 H1 H4.\ndestruct (eval_expr e1 rho); inv H2.\ndestruct (eval_expr e2 rho); inv H3.\nunfold force_signed_int, force_int.\nunfold typed_true, eval_binop in H5.\ndestruct op; inv H; simpl in H5.\npose proof (Int.eq_spec i i0); destruct (Int.eq i i0); inv H5; auto.\nintro; apply H.\nrewrite <- (Int.repr_signed i).\nrewrite <- (Int.repr_signed i0).\nf_equal; auto.\npose proof (Int.eq_spec i i0); destruct (Int.eq i i0); inv H5; auto.\nunfold Int.lt in H5.\ndestruct (zlt (Int.signed i) (Int.signed i0)); inv H5; auto.\nunfold Int.lt in H5.\ndestruct (zlt (Int.signed i0) (Int.signed i)); inv H5; omega.\nunfold Int.lt in H5.\ndestruct (zlt (Int.signed i0) (Int.signed i)); inv H5; omega.\nunfold Int.lt in H5.\ndestruct (zlt (Int.signed i) (Int.signed i0)); inv H5; omega.\nQed.\n*)\n\nLemma typed_false_One_nullval:\n forall  {cs: compspecs}  v t t',\n   local (`(typed_false tint) (`(eval_binop Cop.One (tptr t) (tptr t')) v `nullval)) |--\n    local (`(eq nullval) v).\nProof.\nintros.\n intro rho; unfold local, lift1; unfold_lift.\n apply prop_derives; intro.\n destruct (v rho); inv H.\n pose proof (Int.eq_spec i Int.zero).\n destruct (Int.eq i Int.zero); inv H1.\n reflexivity.\nQed.\n\nLemma typed_true_One_nullval:\n forall  {cs: compspecs}  v t t',\n   local (`(typed_true tint) (`(eval_binop Cop.One (tptr t) (tptr t')) v `nullval)) |--\n   local (`(ptr_neq nullval) v).\nProof.\nintros.\n intro rho; unfold local, lift1; unfold_lift.\n apply prop_derives; intro.\n unfold ptr_neq, ptr_eq; simpl; intro.\n destruct (v rho); try contradiction.\n pose proof (Int.eq_spec Int.zero i). destruct H0. rewrite H0 in H1.\n subst. inv H.\nQed.\n\n\nLemma typed_false_Oeq_nullval:\n forall  {cs: compspecs} v t t',\n   local (`(typed_false tint) (`(eval_binop Oeq (tptr t) (tptr t')) v `nullval)) |--\n   local (`(ptr_neq nullval) v).\nProof.\nintros. subst.\n unfold_lift; intro rho.  unfold local, lift1; apply prop_derives; intro.\n intro. apply ptr_eq_e in H0. rewrite <- H0 in H.\n inv H.\nQed.\n\nLemma local_entail_at:\n  forall n S T (H: local (locald_denote S) |-- local (locald_denote T))\n    P Q R,\n    nth_error Q n = Some S ->\n    PROPx P (LOCALx Q (SEPx R)) |--\n    PROPx P (LOCALx (replace_nth n Q T) (SEPx R)).\nProof.\n intros.\n unfold PROPx, LOCALx; simpl; intro rho;  apply andp_derives; auto.\n apply andp_derives; auto.\n unfold local, lift1.\n specialize (H rho). unfold local,lift1 in H.\n revert Q H0; induction n; destruct Q; simpl; intros; inv H0.\n unfold_lift; repeat rewrite prop_and.\n apply andp_derives; auto.\n  unfold_lift; repeat rewrite prop_and.\n apply andp_derives; auto.\nQed.\n\nLemma local_entail_at_semax_0:\n  forall Espec {cs: compspecs}Delta P Q1 Q1' Q R c Post,\n   local (locald_denote Q1) |-- local (locald_denote Q1') ->\n   @semax cs Espec Delta (PROPx P (LOCALx (Q1'::Q) (SEPx R))) c Post  ->\n   @semax cs Espec Delta (PROPx P (LOCALx (Q1::Q) (SEPx R))) c Post.\nProof.\nintros.\neapply semax_pre0.\neapply (local_entail_at 0).\napply H. reflexivity.\nauto.\nQed.\n\n(*\nLtac simplify_typed_comparison :=\nmatch goal with\n| |- semax _ (PROPx _ (LOCALx (`(typed_true _) ?A :: _) _)) _ _ =>\n (eapply typed_true_binop_int;\n   [reflexivity | reflexivity | reflexivity\n   | try solve [go_lower; apply prop_right; auto ]\n   | try solve [go_lower; apply prop_right; auto ]\n   | ])\n ||\n  (let a := fresh \"a\" in set (a:=A); simpl in a; unfold a; clear a;\n   eapply local_entail_at_semax_0; [\n    first [ apply typed_true_Oeq_nullval\n           | apply typed_true_One_nullval\n           ]\n    |  ])\n| |- semax _ (PROPx _ (LOCALx (`(typed_false _) ?A :: _) _)) _ _ =>\n (eapply typed_false_binop_int;\n   [reflexivity | reflexivity | reflexivity\n   | try solve [go_lower; apply prop_right; auto ]\n   | try solve [go_lower; apply prop_right; auto ]\n   | ])\n ||\n  let a := fresh \"a\" in set (a:=A); simpl in a; unfold a; clear a;\n   eapply local_entail_at_semax_0; [\n    first [ apply typed_false_Oeq_nullval\n           | apply typed_false_One_nullval\n           ]\n    |  ]\n| |- _ => idtac\nend.\n*)\n\nDefinition compare_pp op p q :=\n   match p with\n            | Vptr b z =>\n               match q with\n               | Vptr b' z' => if eq_block b b'\n                              then Vint (if Int.cmpu op z z' then Int.one else Int.zero)\n                              else Vundef\n               | _ => Vundef\n               end\n             | _ => Vundef\n   end.\n\nLemma force_sem_cmp_pp:\n  forall op p q,\n  isptr p -> isptr q ->\n  force_val (sem_cmp_pp op p q) =\n   match op with\n   | Ceq => Vint (if eq_dec p q then Int.one else Int.zero)\n   | Cne => Vint (if eq_dec p q then Int.zero else Int.one)\n   | _ => compare_pp op p q\n   end.\nProof.\nintros.\ndestruct p; try contradiction.\ndestruct q; try contradiction.\nunfold sem_cmp_pp.\ndestruct op; simpl; auto.\nif_tac. if_tac. inv H2. rewrite Int.eq_true; reflexivity.\nrewrite Int.eq_false by congruence; reflexivity.\nif_tac. congruence. reflexivity.\nif_tac. if_tac. inv H2. rewrite Int.eq_true by auto. reflexivity.\nrewrite Int.eq_false by congruence; reflexivity.\nrewrite if_false by congruence. reflexivity.\nif_tac; [destruct (Int.ltu i i0); reflexivity | reflexivity].\nif_tac; [destruct (Int.ltu i0 i); reflexivity | reflexivity].\nif_tac; [destruct (Int.ltu i0 i); reflexivity | reflexivity].\nif_tac; [destruct (Int.ltu i i0); reflexivity | reflexivity].\nQed.\n\nHint Rewrite force_sem_cmp_pp using (now auto) : norm.\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/floyd/compare_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.27034039009353517}}
{"text": "(* -*- coq-prog-args: (\"-emacs\" \"-indices-matter\" \"-type-in-type\") -*- *)\n\nRequire Export Utf8_core.\nRequire Import HoTT HoTT.hit.Truncations Connectedness.\nRequire Import Limit.\nRequire Import PathGroupoid_ Forall_ Equivalences_ epi_mono reflective_subuniverse modalities OPaths.\nRequire Import sheaf_base_case.\nRequire Import sheaf_def_and_thm.\n\n\nSet Universe Polymorphism.\nGlobal Set Primitive Projections. \n\nLocal Open Scope path_scope.\nLocal Open Scope type_scope.\n\nContext `{ua: Univalence}.\nContext `{fs: Funext}.\n\nLocal Definition n0 := sheaf_def_and_thm.n0.\nLocal Definition n := sheaf_def_and_thm.n.\nLocal Definition mod_nj := sheaf_def_and_thm.mod_nj.\nLocal Definition nj := sheaf_def_and_thm.nj.\nLocal Definition j_is_nj := sheaf_def_and_thm.j_is_nj.\nLocal Definition j_is_nj_unit := sheaf_def_and_thm.j_is_nj_unit.\nLocal Definition islex_mod_nj := sheaf_def_and_thm.islex_mod_nj.\nLocal Definition islex_nj := sheaf_def_and_thm.islex_nj.\nLocal Definition lex_compat := sheaf_def_and_thm.lex_compat.\n\n  \nLocal Open Scope Opath_scope.\n\nModule Export OTid.\n\n  Private Inductive OTid (A:TruncType (n.+1)) : Type :=\n    | Ot : A -> (OTid A).\n\n  Arguments Ot {A} a.\n\n  Axiom Otp : forall {A:TruncType (n.+1)} (a b:A), O nj (BuildTruncType _ (a = b)) -> Ot a = Ot b.\n\n  Axiom Otp_1 : forall {A:TruncType (n.+1)} (a:A), Otp a a °1 = 1.\n\n  Definition OTid_ind (A:TruncType (n.+1)) (P : OTid A -> Type)\n             (Ot' : forall a, P (Ot a))\n             (Otp' : forall a b p, transport P (Otp a b p) (Ot' a) = Ot' b)\n             (Otp_1' : forall a, transport2 P (Otp_1 a) (Ot' a) = Otp' a a °1)\n    : forall w, P w\n    := fun w => match w with\n                |Ot a => fun _ => Ot' a\n                end Otp_1'.\n\n  Axiom OTid_ind_beta_Otp : forall (A:TruncType (n.+1)) (P : OTid A -> Type)\n             (Ot' : forall a, P (Ot a))\n             (Otp' : forall a b p, transport P (Otp a b p) (Ot' a) = Ot' b)\n             (Otp_1' : forall a, transport2 P (Otp_1 a) (Ot' a) = Otp' a a °1)\n             a b p,\n      apD (OTid_ind A P Ot' Otp' Otp_1') (Otp a b p) = Otp' a b p.\n\n  Axiom OTid_ind_beta_Otp_1 : forall (A:TruncType (n.+1)) (P : OTid A -> Type)\n             (Ot' : forall a, P (Ot a))\n             (Otp' : forall a b p, transport P (Otp a b p) (Ot' a) = Ot' b)\n             (Otp_1' : forall a, transport2 P (Otp_1 a) (Ot' a) = Otp' a a °1)\n             a,\n      apD02 (OTid_ind A P Ot' Otp' Otp_1') (Otp_1 a) @ (concat_p1 _) @ (Otp_1' a) = OTid_ind_beta_Otp A P Ot' Otp' Otp_1' a a °1.\n        \n        \nEnd OTid.\n\nDefinition OTid_rec (A:TruncType (n.+1)) (P:Type)\n           (Ot': A -> P)\n           (Otp' : forall (a b:A) (p:O nj (BuildTruncType _ (a=b))), Ot' a = Ot' b)\n           (Otp_1' : forall a, Otp' a a °1 = 1)\n  : OTid A -> P.\nProof.\n  simple refine (OTid_ind _ _ Ot' (fun a b p => transport_const _ _ @ Otp' a b p)  _).\n  intro a.\n  pose (p:=whiskerR (transport2_const (A:=OTid A) (B:= P) (Otp_1 a) (Ot' a) @ concat_p1 _)^ (Otp' a a °1)). cbn in p.\n  pose (p1:=(whiskerL (transport2 (λ _ : OTid A, P) (Otp_1 a) (Ot' a)) (Otp_1' a) @ concat_p1 _)^).\n  exact (p1 @ p).\nDefined.\n\nDefinition OT_rec_beta_Otp (A:TruncType (n.+1)) (P:Type)\n           (Ot': A -> P)\n           (Otp' : forall (a b:A) (p:O nj (BuildTruncType _ (a=b))), Ot' a = Ot' b)\n           (Otp_1' : forall a, Otp' a a °1 = 1)\n           a b p\n  : ap (OTid_rec A P Ot' Otp' Otp_1') (Otp a b p) = Otp' a b p.\nProof.\n  simple refine (cancelL (transport_const (Otp a b p) (Ot' a)) _ _ _).\n  pose (e1:= OTid_ind_beta_Otp A (λ _ : OTid A, P) Ot'\n        (λ (a0 b0 : A) (p1 : O nj (BuildTruncType _ (a0 = b0))),\n         transport_const (Otp a0 b0 p1) (Ot' a0) @ Otp' a0 b0 p1)\n        (λ a0 : A,\n         (whiskerL (transport2 (λ _ : OTid A, P) (Otp_1 a0) (Ot' a0))\n            (Otp_1' a0) @\n          concat_p1 (transport2 (λ _ : OTid A, P) (Otp_1 a0) (Ot' a0)))^ @\n         whiskerR\n           (transport2_const (Otp_1 a0) (Ot' a0) @\n            concat_p1 (transport2 (λ _ : OTid A, P) (Otp_1 a0) (Ot' a0)))^\n         (Otp' a0 a0 °1)) a b p). \n\n  pose (e2:= apD_const (OTid_ind A (λ _ : OTid A, P) Ot'\n        (λ (a0 b0 : A) (p2 : O nj (BuildTruncType _ (a0 = b0))),\n         transport_const (Otp a0 b0 p2) (Ot' a0) @ Otp' a0 b0 p2)\n        (λ a0 : A,\n         (whiskerL (transport2 (λ _ : OTid A, P) (Otp_1 a0) (Ot' a0))\n            (Otp_1' a0) @\n          concat_p1 (transport2 (λ _ : OTid A, P) (Otp_1 a0) (Ot' a0)))^ @\n         whiskerR\n           (transport2_const (Otp_1 a0) (Ot' a0) @\n            concat_p1 (transport2 (λ _ : OTid A, P) (Otp_1 a0) (Ot' a0)))^\n         (Otp' a0 a0 °1))) (Otp a b p)).\n  exact (e2^@ e1).\nDefined.\n\nDefinition OT_rec_beta_Otp_1 (A:TruncType (n.+1)) (P:Type)\n           (Ot': A -> P)\n           (Otp' : forall (a b:A) (p:O nj (BuildTruncType _ (a=b))), Ot' a = Ot' b)\n           (Otp_1' : forall a, Otp' a a °1 = 1)\n           a\n  : ap02 (OTid_rec A P Ot' Otp' Otp_1') (Otp_1 a) = OT_rec_beta_Otp A P Ot' Otp' Otp_1' a a °1 @ (Otp_1' a).\nProof.\n  apply (cancel2L (transport2_const (Otp_1 a) (Ot' a))).\n  apply (cancelL (apD_const (OTid_rec A P Ot' Otp' Otp_1') (Otp a a °1))).\n  apply (cancelR _ _ (concat_p_pp (q:=transport_const _ _))^).\n  apply (cancelR _ _ (whiskerL (transport2 _ (Otp_1 a) (Ot' a)) (apD_const (OTid_rec A P Ot' Otp' Otp_1') 1)^)).\n  simple refine ((apD02_const (OTid_rec A P Ot' Otp' Otp_1') (Otp_1 a) )^ @ _).\n  apply (cancelR _ _ (concat_p1 (transport2 (λ _ : OTid A, P) (Otp_1 a) (Ot' a)))).\n  apply (cancelR _ _ ((whiskerL (transport2 (λ _ : OTid A, P) (Otp_1 a) (Ot' a)) (Otp_1' a) @\n                                concat_p1 (transport2 (λ _ : OTid A, P) (Otp_1 a) (Ot' a)))^ @\n                                                                                             whiskerR\n                                                                                             (transport2_const (Otp_1 a) (Ot' a) @\n                                                                                                               concat_p1 (transport2 (λ _ : OTid A, P) (Otp_1 a) (Ot' a)))^\n                      (Otp' a a °1))).\n  Opaque concat_p_pp.\n  simple refine (OTid_ind_beta_Otp_1 _ _ _ _ _ _ @ _); cbn.\n  apply (cancelL (apD_const\n                    (OTid_ind A (λ _ : OTid A, P) Ot'\n                           (λ (a0 b0 : A) (p2 : O nj (BuildTruncType _ (a0 = b0))),\n                            transport_const (Otp a0 b0 p2) (Ot' a0) @ Otp' a0 b0 p2)\n                           (λ a0 : A,\n                                   (whiskerL (transport2 (λ _ : OTid A, P) (Otp_1 a0) (Ot' a0))\n                                             (Otp_1' a0) @\n                                             concat_p1\n                                             (transport2 (λ _ : OTid A, P) (Otp_1 a0) (Ot' a0)))^ @\n                                                                                                  whiskerR\n                                                                                                  (transport2_const (Otp_1 a0) (Ot' a0) @\n                                                                                                                    concat_p1\n                                                                                                                    (transport2 (λ _ : OTid A, P) (Otp_1 a0) (Ot' a0)))^\n                                   (Otp' a0 a0 °1))) (Otp a a °1))^).\n\n  apply (@equiv_inj _ _ _ (isequiv_cancelL (transport_const (Otp a a °1) (Ot' a))\n                                           (ap (OTid_rec A P Ot' Otp' Otp_1') (Otp a a °1))\n                                           (Otp' a a °1))).\n\n  path_via (OT_rec_beta_Otp A P Ot' Otp' Otp_1' a a °1).\n  apply (@equiv_inj _ _ _ (isequiv_inverse _ (feq:= isequiv_cancelL (transport_const (Otp a a °1) (Ot' a))\n                                                                    (ap (OTid_rec A P Ot' Otp' Otp_1') (Otp a a °1))\n                                                                    (Otp' a a °1)))).\n  rewrite eissect. cbn. repeat rewrite concat_pp_p.\n  rewrite concat_V_pp.\n  rewrite !inv_pp. repeat rewrite concat_p_pp. rewrite concat_pp_V.\n\n  rewrite whiskerR_pp. \n  rewrite whiskerR_RV.\n  rewrite <- (apD (λ u, (whiskerR (concat_p1 (transport2 (λ _ : OTid A, P) (Otp_1 a) (Ot' a)))\n                                  u)) (Otp_1' a)^).\n  cbn. rewrite transport_paths_FlFr. cbn. rewrite !ap_V; rewrite !inv_V.\n  rewrite !concat_ap_pFq. rewrite ap_idmap. rewrite !inv_pp; rewrite !inv_V.\n  rewrite !concat_p_pp. rewrite concat_pV_p. rewrite (concat_p1 ((transport2_const (Otp_1 a) (Ot' a) @@\n                                                                                   (OT_rec_beta_Otp A P Ot' Otp' Otp_1' a a °1 @ Otp_1' a)) @\n                                                                                                                                             (concat_p_pp )^)).\n  rewrite whiskerR_RV.\n  apply moveL_pV.\n  unfold whiskerR at 1, whiskerL at 1.\n  rewrite concat_concat2. cbn.\n  rewrite (concat_1p (transport2_const (Otp_1 a) (Ot' a))).\n  rewrite (concat_p1 (OT_rec_beta_Otp A P Ot' Otp' Otp_1' a a °1)).\n  simple refine ((concat_p1 _)^ @ _). rewrite !concat_pp_p.\n  match goal with\n  |[|- _ = (?P @@ ?Q) @ ?R] => path_via (((P @ 1) @@ Q) @ R)\n  end.\n  2: rewrite (concat_p1 (transport2_const (Otp_1 a) (Ot' a))); reflexivity.\n  rewrite <- concat_concat2.\n  rewrite !concat_pp_p. apply whiskerL.\n  rewrite !concat_p_pp. apply moveL_pV. rewrite concat_1p.\n  rewrite !concat_pp_p. simple refine ((concat_p1 _)^@ _).\n  apply whiskerL. cbn.\n  pose (rew:= @triangulator _ _ _ _ (transport2 (λ _ : OTid A, P) (Otp_1 a) (Ot' a)) 1).\n  apply moveL_Vp in rew. rewrite rew; clear rew. cbn.\n  rewrite inv_pp. cbn. rewrite concat_1p. symmetry; apply concat_pV.\nQed.\n\n\nLemma path_OT_lemma (A:(n.+1)-Type) (B:Type)\n      (α β :OTid A -> B)\n      (eq1: α o Ot == β o Ot)\n      (eq2: forall a b p, eq1 a @ ap β (Otp a b p) = ap α (Otp a b p) @ eq1 b)\n      (eq3: forall a,  (eq2 a a °1)\n                      = transport (λ U, eq1 a @ ap β U = ap α U @ eq1 a) (Otp_1 a)^ (concat_p1 (eq1 a) @ (concat_1p (eq1 a))^))\n  : ∀ a : A,\n    transport2 (λ w : OTid A, α w = β w) (Otp_1 a) (eq1 a) =\n    transport_paths_FlFr (Otp a a °1) (eq1 a) @\n                         (concat_pp_p (p:=(ap α (Otp a a °1))^)\n                          (q:=eq1 a)\n                            (r:=ap β (Otp a a °1))\n                            @ cancelL (ap α (Otp a a °1))\n                            ((ap α (Otp a a °1))^ @ (eq1 a @ ap β (Otp a a °1))) \n                            (eq1 a)\n                            (concat_p_Vp (ap α (Otp a a °1)) (eq1 a @ ap β (Otp a a °1)) @ eq2 a a °1)).\nProof.\n  intro a; cbn.\n  rewrite eq3; clear eq3. clear eq2. generalize (eq1 a). intro p. clear eq1.\n  unfold cancelL.\n  pose (rew :=@transport_paths_FlFr _ _ (λ U:Ot a = Ot a, p @ ap β U) (λ U:Ot a = Ot a, ap α U @ p)).\n  rewrite rew; clear rew.\n  cbn.\n  repeat rewrite concat_pp_p.\n  rewrite ap_V. rewrite inv_V.\n  repeat rewrite whiskerL_pp.\n  symmetry.\n  \n  match goal with\n  |[|- ?PP1 @ (?PP2 @ ((?PP3 @ (?PP4 @ ((?PP5 @ (?PP6 @ ?PP7)) @ ?PP8)) @ ?PP9))) = ?PP10] =>\n   set (P1 := PP1);\n     set (P2 := PP2);\n     set (P3 := PP3);\n     set (P4 := PP4);\n     set (P5 := PP5);\n     set (P6 := PP6);\n     set (P7 := PP7);\n     set (P8 := PP8);       \n     set (P9 := PP9);\n     set (P10 := PP10)\n  end.\n  rewrite (@concat_pp_p _ _ _ _ _ P3 (P4 @ ((P5 @ (P6 @ P7)) @ P8)) P9).\n  rewrite (@concat_pp_p _ _ _ _ _ P4 ((P5 @ (P6 @ P7)) @ P8) P9).\n  repeat rewrite (@concat_pp_p _ _ _ _ _ P5 _ _).\n  repeat rewrite (@concat_pp_p _ _ _ _ _ P6 _ _).\n  repeat rewrite (@concat_pp_p _ _ _ _ _ P7 _ _).\n\n  unfold P1; clear P1.\n  match goal with\n  |[|- ?ff _ p @ _ = _]\n   => rewrite <- (apD (λ U, ff U p) (Otp_1 a)^)\n  end.\n  cbn.\n  rewrite (transport_paths_FlFr (f:= λ U, transport (λ x : OTid A, α x = β x) U p)\n                                (g:= λ U, ((ap α U)^ @ p) @ ap β U)).\n  rewrite ap_V. rewrite inv_V.\n\n  unfold P10. rewrite transport2_is_ap.\n  repeat rewrite concat_pp_p.\n  match goal with\n  |[|- _ = ?XX] => path_via (XX @ 1)\n  end.\n  apply whiskerL.\n  rewrite ap_V.\n  do 3 apply moveR_Vp.\n  match goal with\n  |[|- _ = ?PP11 @ (?PP12 @ ?PP13)]\n   => set (P11 := PP11); set (P12 := PP12); set (P13 := PP13); cbn in *\n  end.\n\n  unfold P3; clear P3.\n\n  rewrite <- (apD (λ U, (concat_V_pp (ap α U)\n                                     ((ap α U)^ @ (p @ ap β U)))^) (Otp_1 a)^).\n  cbn.\n  rewrite (transport_paths_FlFr (f:=(λ U : Ot a = Ot a, (ap α U)^ @ (p @ ap β U)))\n                                (g:=λ U : Ot a = Ot a, (ap α U)^ @ (ap α U @ ((ap α U)^ @ (p @ ap β U))))).\n  rewrite ap_V. rewrite inv_V.\n  match goal with\n  |[|- _ @ (((?PP31 @ ?PP32) @ ?PP33) @ _) = _] =>\n   set (P31 := PP31); set (P32 := PP32); set (P33 := PP33); cbn in *\n  end.\n  repeat rewrite (@concat_pp_p _ _ _ _ _ P31).\n  repeat rewrite (@concat_pp_p _ _ _ _ _ P32).\n  rewrite (@concat_p_pp _ _ _ _ _ P2 P31 _).\n\n  assert (rr: P11 @ (concat_pp_p) = (P2 @ P31)).\n  { unfold P2, P31, P11.\n    rewrite concat_ap_FpFq_pp_p. rewrite concat_ap_FpFq_p_pp.\n    unfold whiskerR, whiskerL. \n    repeat rewrite concat_p_pp. apply whiskerR.\n    reflexivity. }\n  destruct rr.\n  rewrite (@concat_pp_p _ _ _ _ _ P11).\n  apply whiskerL.\n  match goal with |[|- ?PP1 @ _ = _] => set (P1 := PP1) end.\n  clear P10; clear P11.\n  \n  do 2 apply moveR_Mp.\n  repeat rewrite (concat_p_pp (r:=P9)). apply moveR_pM.\n  unfold P9.\n  rewrite <- (apD (λ U, (concat_V_pp (ap α U) p)^) (Otp_1 a)^). simpl.\n  rewrite (transport_paths_Fr (g:= λ U, (ap α U)^ @ (ap α U @ p))).\n  clear P2.\n  repeat rewrite (concat_p_pp (r:=P8)).\n  apply moveR_pM.\n  set (P2 := ap (λ U : Ot a = Ot a, (ap α U)^ @ (ap α U @ p)) (Otp_1 a)^).\n  \n  unfold P8.\n  rewrite <- (apD (λ U, whiskerL (z:=β (Ot a)) (q:= 1 @ p) (r := ap α (Otp a a °1) @ p) (ap α U)^) (Otp_1 a)^).\n  rewrite transport_arrow.\n  simpl.\n  rewrite transport_const.\n  rewrite transport_paths_FlFr.\n  do 2 rewrite inv_pp. \n  repeat rewrite ap_V. rewrite whiskerL_LV. repeat rewrite inv_V.\n  match goal with\n  |[|- _ = _ @ (?PP16 @ (?PP15 @ ?PP14)) ] =>\n   set (P14 := PP14); set (P15 := PP15); set (P16 := PP16); simpl in P14, P15, P16\n  end.\n  unfold P4.\n  rewrite <- (apD (λ U, (whiskerL (ap α U)^\n                         (concat_p_Vp (ap α U) (p @ ap β U)))) (Otp_1 a)^).\n  simpl.\n  rewrite transport_paths_FlFr. simpl.\n  rewrite ap_V. rewrite inv_V.\n  match goal with\n  |[|- _ @ (((?PP17 @ ?PP18) @ ?PP19) @ _) = _]\n   => set (P17:=PP17); set (P18 := PP18); set (P19 := PP19)\n  end.\n  clear P4. clear P8. clear P9. clear P31.\n  unfold P6, P7; clear P6; clear P7.\n  rewrite <- (apD (λ U, (whiskerL (ap α U)^ (concat_p1 p) @\n                                                          whiskerL (ap α U)^ (concat_1p p)^)) (Otp_1 a)^).\n  simpl.\n  rewrite transport_paths_FlFr.\n  rewrite ap_V. rewrite inv_V.\n  match goal with\n  |[|- _ @ (_ @ (_ @ ((?PP6 @ ?PP7) @ ?PP8))) = _]\n   => set (P6:=PP6); set (P7:=PP7); set (P8:=PP8)\n  end.\n  \n  unfold P5; clear P5.\n  rewrite <- (apD (λ U, whiskerL (q:=p @ ap β (Otp a a °1)) (r:=p@1) (ap α U)^) (Otp_1 a)^).\n  rewrite transport_arrow.\n  rewrite transport_const. rewrite transport_paths_FlFr.\n  simpl.\n  rewrite ap_V. rewrite inv_V.\n  repeat rewrite (concat_p_pp (r:=P8)).\n  repeat rewrite (concat_p_pp (r:=P14)).\n\n  unfold P8, P14. repeat rewrite ap_V. apply whiskerR. clear P8; clear P14.\n  repeat rewrite (concat_pp_p (p:=P17)).\n  rewrite <- (concat_pp_p (p:=P33) (q:=P17)).\n  unfold P33, P17; clear P33; clear P17.\n  rewrite ap_V. rewrite concat_Vp.\n  match goal with |[|- 1 @ ?XX = _] => rewrite (concat_1p XX) end.\n  pose (p1 := whiskerL_1p (concat_p_Vp 1 (p @ 1))). simpl in p1.\n  apply moveL_pV in p1.\n  apply moveL_Mp in p1.\n  unfold P18; clear P18; rewrite p1; clear p1.\n  unfold P15; clear P15.\n  pose (p1 := whiskerL_1p (ap (λ U : Ot a = Ot a, ap α U @ p) (Otp_1 a))). simpl in p1.\n  apply moveL_pV in p1.\n  apply moveL_Mp in p1.\n  rewrite p1; clear p1.\n  unfold P7; clear P7.\n  pose (p1 := whiskerL_1p (concat_p1 p)). simpl in p1.\n  apply moveL_pV in p1.\n  apply moveL_Mp in p1.\n  rewrite p1; clear p1.\n  pose (p1 := whiskerL_1p (concat_1p p)^). simpl in p1.\n  apply moveL_pV in p1.\n  apply moveL_Mp in p1.\n  rewrite p1; clear p1.\n  pose (p1 := whiskerL_1p (ap (λ U : Ot a = Ot a, p @ ap β U) (Otp_1 a))). simpl in p1.\n  apply moveL_pV in p1.\n  apply moveL_Mp in p1.\n  rewrite p1; clear p1.\n  repeat rewrite concat_pp_p.\n  unfold  P19, P6, P32, P1, P12, P13, P2, P16.\n  clear P19; clear P6; clear P32; clear P1; clear P12; clear P13; clear P2; clear P16.\n  (* rewrite inv_V. *)\n  rewrite (concat_p1 (concat_1p p)).\n  match goal with\n  |[|- ?PP1 @ (?PP2 @ (?PP3 @ (?PP4 @ (?PP5 @ (?PP6 @ (?PP7 @ (?PP8 @ (?PP9 @ (?PP10 @ (?PP11 @ (?PP12 @ (?PP13 @ (?PP14 @ (?PP15 @ (?PP16)))))))))))))))\n       =\n       ?PP17 @ (?PP18 @ ((?PP19 @ ?PP20) @ ((?PP21 @ ?PP22) @ (?PP23 @ (?PP24 @ (?PP25 @ ?PP26))))))] =>\n   set (P1 := PP1);\n     set (P2 := PP2);\n     set (P3 := PP3);\n     set (P4 := PP4);\n     set (P5 := PP5);\n     set (P6 := PP6);\n     set (P7 := PP7);\n     set (P8 := PP8);       \n     set (P9 := PP9);\n     set (P10 := PP10);\n     set (P11 := PP11);\n     set (P12 := PP12);\n     set (P13 := PP13);\n     set (P14 := PP14);\n     set (P15 := PP15);\n     set (P16 := PP16);\n     set (P17 := PP17);\n     set (P18 := PP18);\n     set (P19 := PP19);\n     set (P20 := PP20);\n     set (P21 := PP21);\n     set (P22 := PP22);\n     set (P23 := PP23);\n     set (P24 := PP24);\n     set (P25 := PP25);\n     set (P26 := PP26)\n  end.\n  repeat rewrite (concat_p_pp (r:=P16)).\n  apply whiskerR. clear P16.\n  assert (rr : 1 = P14 @ P13).\n  symmetry. unfold P13, P14. apply concat_pV.\n  destruct rr. rewrite (concat_p1 P13).\n  clear P15. clear P20. simpl in *.\n  assert (rr: P1 @ (P2 @ P3) = P17).\n  { unfold P1, P2, P3, P17.\n    clear P1; clear P2; clear P17;\n    clear P3; clear P4; clear P5; clear P6; clear P7; clear P8; clear P9\n    ; clear P10; clear P11; clear P12; clear P13; clear P14; clear P18; clear P19\n    ; clear P21; clear P22; clear P23; clear P24; clear P25; clear P26.\n    destruct p. reflexivity. }\n  destruct rr.\n  repeat rewrite concat_pp_p.\n  do 3 apply whiskerL. \n  clear P1; clear P2; clear P26.\n\n  assert (rr: P18 @ (P19 @ P14) = P11 @ P12).\n  { unfold P18, P19, P14, P11, P12. cbn.\n    clear P3; clear P4; clear P5; clear P6; clear P7; clear P8; clear P9\n    ; clear P10; clear P11; clear P12; clear P13; clear P14; clear P18; clear P19\n    ; clear P21; clear P22; clear P23; clear P24; clear P25.\n    destruct p; reflexivity. }\n  rewrite (concat_p_pp  (q:= (P19 @ P14))).\n  rewrite rr; clear rr.\n  rewrite (concat_p_pp (p:=P9)).\n  unfold P9, P10. rewrite concat_Vp. rewrite (concat_1p (P11 @ (P12 @ P13))).\n  clear P9; clear P10.\n  rewrite (concat_p_pp (p:=P3)).\n  unfold P3 at 1, P11 at 1. rewrite concat_Vp.\n  rewrite (concat_1p (P12 @ P13)).\n  clear P3.\n  assert (rr: P4 @ (P5 @ (P6 @ P7)) = P11).\n  { repeat rewrite (concat_p_pp (r:=P7)).\n    apply moveR_pM.\n\n    unfold P4, P5, P6, P7, P11.\n    clear P4; clear P5; clear P6; clear P7; clear P8\n    ; clear P11; clear P12; clear P13; clear P14; clear P18; clear P19\n    ; clear P21; clear P22; clear P23; clear P24; clear P25.\n    rewrite <- (ap_V (λ U : Ot a = Ot a, p @ ap β U) (Otp_1 a)).\n    rewrite ap_V. apply moveR_Vp.\n\n    rewrite <- (apD (λ U, concat_1p (p @ ap β U)) (Otp_1 a)^).\n    simpl.\n    rewrite transport_paths_FlFr. simpl.\n    rewrite ap_V. rewrite inv_V.\n    repeat rewrite concat_p_pp.\n    match goal with\n    |[|- ?P1 @ (?P2 @ ?P3) = _]\n     => rewrite (concat_p_pp (p:=P1))\n    end. apply whiskerR.\n    match goal with\n    |[|- ?P1 @ (?P2 @ ?P3) = _]\n     => rewrite (concat_p_pp (p:=P1))\n    end. apply whiskerR.\n    rewrite concat_ap_Fpq.\n    unfold whiskerR.\n    rewrite concat_ap_pFq. unfold whiskerL.\n    rewrite concat_concat2. rewrite (concat_p1 (ap (λ u : Ot a = Ot a, (ap α u)^) (Otp_1 a))).\n    rewrite (concat_1p (ap (λ u : Ot a = Ot a, p @ ap β u) (Otp_1 a))).\n    rewrite concat_ap_FpFq_p_pp.\n    unfold whiskerR, whiskerL.\n    rewrite concat_pp_p. apply moveL_Mp.\n    rewrite concat2_inv.\n    rewrite concat_concat2.\n    rewrite concat_Vp.\n    rewrite (concat_1p (ap (λ u : Ot a = Ot a, p @ ap β u) (Otp_1 a))).\n    rewrite concat_ap_pFq. unfold whiskerL.\n    rewrite (concat2_p_pp). reflexivity. }\n  rewrite (concat_pp_p (p:=P11)).\n  destruct rr.\n  rewrite (concat_pp_p (p:=P4)); apply whiskerL.\n  rewrite (concat_pp_p (p:=P5)); apply whiskerL.\n  rewrite (concat_pp_p (p:=P6)); apply whiskerL.\n  do 2 apply whiskerL.\n  clear P4; clear P5; clear P6; clear P7; clear P8; clear P12.\n  clear P14; clear P18; clear P19.\n  unfold P13, P21, P22, P23, P24, P25.\n  clear P13; clear P21; clear P22; clear P23; clear P24; clear P25.\n  rewrite <- (apD (λ U, concat_1p (ap α U @ p)) (Otp_1 a)^).\n  rewrite transport_paths_FlFr. simpl.\n  repeat rewrite ap_V. rewrite inv_V.\n  repeat rewrite concat_pp_p. rewrite concat_Vp.\n  rewrite (concat_p1).\n  apply moveL_Vp.\n  repeat rewrite (concat_p_pp (r:=(concat_1p (1 @ p)))). apply moveL_pM.\n  match goal with\n  |[|- ?XX = _] => assert (rr: 1 = XX)\n  end.\n  { destruct p. reflexivity. }\n  destruct rr.\n  apply moveL_Vp. rewrite concat_p1.\n  rewrite concat_ap_Fpq.\n  rewrite concat_ap_pFq. unfold whiskerR, whiskerL.\n  rewrite concat_concat2.\n  rewrite concat_p1, (concat_1p (ap (λ u : Ot a = Ot a, ap α u @ p) (Otp_1 a))).\n  rewrite concat_ap_FFpq_p_pp. rewrite concat_ap_Fpq.\n  unfold whiskerR. simpl.\n  rewrite <- concat2_p_pp. reflexivity.\nQed.\n\nLemma path_OT (A:(n.+1)-Type) (B:Type)\n      (α β :OTid A -> B)\n      (eq1: α o Ot == β o Ot)\n      (eq2: forall a b p, eq1 a @ ap β (Otp a b p) = ap α (Otp a b p) @ eq1 b)\n      (eq3: forall a,  (eq2 a a °1)\n                      = transport (λ U, eq1 a @ ap β U = ap α U @ eq1 a) (Otp_1 a)^ (concat_p1 (eq1 a) @ (concat_1p (eq1 a))^))\n  : α == β.\nProof.\n  simple refine (OTid_ind _ _ _ _ _).\n  - exact eq1.\n  - intros a b p.\n    simple refine (transport_paths_FlFr _ _ @ _).\n    etransitivity; try apply concat_pp_p.\n    apply (cancelL (ap α (Otp a b p))).\n    etransitivity; try apply eq2.\n    apply concat_p_Vp.\n  - rapply path_OT_lemma. exact eq3.\nDefined.\n\nLemma path_OT_compute (A:(n.+1)-Type) (B:Type)\n      (α β :OTid A -> B)\n      (eq1: α o Ot == β o Ot)\n      (eq2: forall a b p, eq1 a @ ap β (Otp a b p) = ap α (Otp a b p) @ eq1 b)\n      (eq3: forall a,  (eq2 a a °1)\n                       = transport (λ U, eq1 a @ ap β U = ap α U @ eq1 a) (Otp_1 a)^ (concat_p1 (eq1 a) @ (concat_1p (eq1 a))^)) x\n  : path_OT A B α β eq1 eq2 eq3 (Ot x) = eq1 x.\nProof.\n  reflexivity.\nDefined.\n\nLemma equiv_ap_OTid_fun {X Y:TruncType (n.+1)} (e: X -> Y)\n  : OTid X -> OTid Y.\nProof.\n  simple refine (OTid_rec _ _ _ _ _).\n  intro x; apply Ot; exact (e x).\n  intros a b p; cbn. apply Otp.\n  exact (Oap e p).\n  intro a; cbn. etransitivity; [apply (ap (Otp (e a) (e a)) (Oap_1 e))| apply Otp_1].\nDefined.\n\nLemma isequiv_ap_OTid_path {X Y:TruncType (n.+1)} (e: X = Y :> Type)\n  : IsEquiv (equiv_ap_OTid_fun (equiv_path _ _ e)).\nProof.\n  destruct X as [X tX], Y as [Y tY]; cbn in *.\n  destruct e; cbn in *.\n  assert (r: tX = tY) by apply path_ishprop. destruct r.\n  simple refine (isequiv_homotopic idmap _).\n  \n  simple refine (path_OT _ _ _ _ _ _ _).\n  - intro x; reflexivity.\n  - intros a b p; cbn.\n    simple refine (concat_1p _ @ _ @ (concat_p1 _)^).\n    unfold equiv_ap_OTid_fun. cbn.\n    simple refine (OT_rec_beta_Otp _ _ _ _ _ _ _ _ @ _ @ (ap_idmap _)^).\n    cbn.\n    apply ap.\n    apply Oap_idmap.\n  - intro a; cbn. rewrite transport_paths_FlFr.\n    rewrite concat_ap_Fpq; rewrite concat_ap_pFq.\n    apply moveR_pV. do 3 rewrite concat_pp_p.\n    pose (rew:= whiskerR_p1 (ap (ap idmap) (Otp_1 a)^)).\n    rewrite concat_pp_p in rew; apply moveL_Vp in rew; rewrite rew; clear rew.\n    cbn. apply moveL_Vp. do 4 rewrite concat_p_pp.\n    pose (rew:= whiskerL_1p (ap (ap (equiv_ap_OTid_fun idmap)) (Otp_1 a)^)).\n    rewrite concat_pp_p in rew; apply moveL_Vp in rew; rewrite rew; clear rew.\n    cbn. rewrite !concat_1p. rewrite !ap_V.\n    rewrite <- (ap02_is_ap _ _ (equiv_ap_OTid_fun idmap) _ _ _ _ (Otp_1 a)).\n    unfold equiv_ap_OTid_fun. cbn.\n    rewrite OT_rec_beta_Otp_1. rewrite inv_pp. rewrite concat_pV_p.\n    rewrite <- (apD (λ U, ap_idmap U) (Otp_1 a)^).\n    rewrite transport_paths_FlFr. cbn. rewrite !ap_V.\n    rewrite (ap_idmap (Otp_1 a)). rewrite concat_p1. rewrite !inv_pp.\n    rewrite !inv_V. rewrite concat_p_pp. simple refine (_ @ concat_1p _). apply whiskerR.\n    apply moveR_pM. rewrite concat_1p. simple refine (_ @ concat_p1 _).\n    rewrite !concat_pp_p. apply whiskerL.\n    rewrite <- ap_V. rewrite <- ap_pp.\n    path_via ((ap (Otp a a) (idpath °1))).\n    apply ap. apply moveR_Vp. simple refine (_ @ (concat_p1 _)^).\n    apply (Oap_idmap_Oap_1 a).\nQed.\n\nLemma isequiv_ap_OTid `{ua: Univalence} {X Y:TruncType (n.+1)} (e: X <~> Y)\n  : IsEquiv (equiv_ap_OTid_fun e).\nProof.\n  simple refine (isequiv_homotopic (equiv_ap_OTid_fun (equiv_path _ _ (path_universe_uncurried e))) _).\n  exact ua.\n  apply (isequiv_ap_OTid_path (path_universe_uncurried e)).\n  rewrite equiv_path_path_universe_uncurried. intro; reflexivity.\nQed.\n\nLemma equiv_ap_OTid {X Y:TruncType (n.+1)} (e: X <~> Y)\n  : OTid X <~> OTid Y.\nProof.\n  exists (equiv_ap_OTid_fun e).\n  apply isequiv_ap_OTid.\nDefined.\n\nSection OT_telescope.\n  \n  Context `{ua: Univalence}.\n  Context `{fs: Funext}.\n\n  Definition OTtelescope_aux (X:TruncType (n.+1)) (m: nat)\n  : TruncType (n.+1).\n    induction m as [|m U].\n    - exact X. \n    - exact (BuildTruncType _ (Trunc (n.+1) (OTid U))).\n  Defined.\n\n  Definition OTtelescope (X:TruncType (n.+1)) \n  : diagram mappingtelescope_graph.\n    simple refine (Build_diagram _ _ _).\n    - intros m. exact (OTtelescope_aux X m).\n    - intros n m q; destruct q; simpl.\n      intro x. apply tr. apply Ot. exact x.\n  Defined.\n\n    \nEnd OT_telescope.\n\n", "meta": {"author": "KevinQuirin", "repo": "sheafification", "sha": "0c3cd7d76d4122befed0015bf1f0d53e1a978e49", "save_path": "github-repos/coq/KevinQuirin-sheafification", "path": "github-repos/coq/KevinQuirin-sheafification/sheafification-0c3cd7d76d4122befed0015bf1f0d53e1a978e49/OT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.27034039009353517}}
{"text": "From Coq Require Import ssreflect ssrfun ssrbool.\nRequire Import Setoid.\nRequire Import List.\nRequire Import Ensembles.\nRequire Import Coq.Strings.String.\n\nFrom Coq Require Import Logic.Classical_Prop.\nFrom stdpp Require Import countable infinite.\nFrom stdpp Require Import pmap gmap mapset fin_sets propset.\nRequire Import stdpp_ext.\n\nRequire Import extralibrary.\n\nFrom MatchingLogic Require Export\n  Signature\n  Pattern\n  Substitution\n  Freshness\n  SyntacticConstruct\n  PatternContext\n  ApplicationContext\n  SyntaxLemmas.FreshnessSubstitution\n  SyntaxLemmas.PatternCtxApplicationCtx\n  SyntaxLemmas.FreshnessApplicationCtx\n  SyntaxLemmas.ApplicationCtxSubstitution\n  wftactics\n.\n\nImport MatchingLogic.Substitution.Notations.\n\nClose Scope boolean_if_scope.\n\nSection syntax.\n  Context {Σ : Signature}.\n  Open Scope ml_scope.\n\n  Inductive is_subformula_of_ind : Pattern -> Pattern -> Prop :=\n  | sub_eq ϕ₁ ϕ₂ : ϕ₁ = ϕ₂ -> is_subformula_of_ind ϕ₁ ϕ₂\n  | sub_app_l ϕ₁ ϕ₂ ϕ₃ : is_subformula_of_ind ϕ₁ ϕ₂ -> is_subformula_of_ind ϕ₁ (patt_app ϕ₂ ϕ₃)\n  | sub_app_r ϕ₁ ϕ₂ ϕ₃ : is_subformula_of_ind ϕ₁ ϕ₃ -> is_subformula_of_ind ϕ₁ (patt_app ϕ₂ ϕ₃)\n  | sub_imp_l ϕ₁ ϕ₂ ϕ₃ : is_subformula_of_ind ϕ₁ ϕ₂ -> is_subformula_of_ind ϕ₁ (patt_imp ϕ₂ ϕ₃)\n  | sub_imp_r ϕ₁ ϕ₂ ϕ₃ : is_subformula_of_ind ϕ₁ ϕ₃ -> is_subformula_of_ind ϕ₁ (patt_imp ϕ₂ ϕ₃)\n  | sub_exists ϕ₁ ϕ₂ : is_subformula_of_ind ϕ₁ ϕ₂ -> is_subformula_of_ind ϕ₁ (patt_exists ϕ₂)\n  | sub_mu ϕ₁ ϕ₂ : is_subformula_of_ind ϕ₁ ϕ₂ -> is_subformula_of_ind ϕ₁ (patt_mu ϕ₂)\n  .\n\n  Fixpoint is_subformula_of ϕ₁ ϕ₂ : bool :=\n    (decide_rel (=) ϕ₁ ϕ₂)\n    || match ϕ₂ with\n       | patt_app l r | patt_imp l r => is_subformula_of ϕ₁ l || is_subformula_of ϕ₁ r\n       | patt_exists phi | patt_mu phi => is_subformula_of ϕ₁ phi\n       | _ => false\n       end.\n\n  Lemma is_subformula_of_P ϕ₁ ϕ₂ : reflect (is_subformula_of_ind ϕ₁ ϕ₂) (is_subformula_of ϕ₁ ϕ₂).\n  Proof.\n    unfold is_subformula_of.\n    remember ϕ₂. revert p Heqp.\n\n    (* TODO *)\n    induction ϕ₂; move=> p Heqp; destruct (decide_rel (=) ϕ₁ p) eqn:Heq2;\n                           rewrite Heqp; rewrite -Heqp; rewrite Heq2; simpl; rewrite Heqp;\n                             try (apply ReflectT; subst; apply sub_eq; reflexivity);\n                             try (apply ReflectF; intros Contra; inversion Contra; subst; contradiction).\n    all: fold is_subformula_of in *.\n    - destruct (IHϕ₂1 ϕ₂1),(IHϕ₂2 ϕ₂2); simpl; try reflexivity.\n      + apply ReflectT. apply sub_app_l. assumption.\n      + apply ReflectT. apply sub_app_l. assumption.\n      + apply ReflectT. apply sub_app_r. assumption.\n      + apply ReflectF. intros Contra. inversion Contra; subst; contradiction.\n    - destruct (IHϕ₂1 ϕ₂1),(IHϕ₂2 ϕ₂2); simpl; try reflexivity.\n      + apply ReflectT. apply sub_imp_l. assumption.\n      + apply ReflectT. apply sub_imp_l. assumption.\n      + apply ReflectT. apply sub_imp_r. assumption.\n      + apply ReflectF. intros Contra. inversion Contra; subst; contradiction.\n    - destruct (IHϕ₂ ϕ₂). reflexivity.\n      + apply ReflectT. apply sub_exists. assumption.\n      + apply ReflectF. intros Contra. inversion Contra; subst; contradiction.\n    - destruct (IHϕ₂ ϕ₂). reflexivity.\n      + apply ReflectT. apply sub_mu. assumption.\n      + apply ReflectF. intros Contra. inversion Contra; subst; contradiction.\n  Qed.\n\n  Lemma is_subformula_of_refl ϕ:\n    is_subformula_of ϕ ϕ = true.\n  Proof.\n    destruct (is_subformula_of_P ϕ ϕ).\n    - reflexivity.\n    - assert (H: is_subformula_of_ind ϕ ϕ).\n      apply sub_eq. reflexivity. contradiction.\n  Qed.\n\n  Lemma bsvar_subst_contains_subformula ϕ₁ ϕ₂ dbi :\n    bsvar_occur ϕ₁ dbi = true ->\n    is_subformula_of_ind ϕ₂ (ϕ₁^[svar: dbi ↦ ϕ₂]).\n  Proof.\n    generalize dependent dbi.\n    induction ϕ₁; intros dbi H; simpl; simpl in H; try inversion H.\n    - case_match; subst.\n      + case_match; try lia. constructor. reflexivity.\n      + congruence.\n    - specialize (IHϕ₁1 dbi). specialize (IHϕ₁2 dbi).\n      move: H H1 IHϕ₁1 IHϕ₁2.\n      case: (bsvar_occur ϕ₁1 dbi); case: (bsvar_occur ϕ₁2 dbi); move=> H H1 IHϕ₁₁ IHϕ₁₂.\n      + apply sub_app_l. auto.\n      + apply sub_app_l. auto.\n      + apply sub_app_r. auto.\n      + done.\n    - specialize (IHϕ₁1 dbi). specialize (IHϕ₁2 dbi).\n      move: H H1 IHϕ₁1 IHϕ₁2.\n      case: (bsvar_occur ϕ₁1 dbi); case: (bsvar_occur ϕ₁2 dbi); move=> H H1 IHϕ₁₁ IHϕ₁₂.\n      + apply sub_imp_l. auto.\n      + apply sub_imp_l. auto.\n      + apply sub_imp_r. auto.\n      + done.\n    - apply sub_exists. auto.\n    - apply sub_mu. apply IHϕ₁. auto.\n  Qed.\n\n  Lemma bevar_subst_contains_subformula ϕ₁ ϕ₂ dbi :\n    bevar_occur ϕ₁ dbi = true ->\n    is_subformula_of_ind ϕ₂ (ϕ₁^[evar: dbi ↦ ϕ₂]).\n  Proof.\n    generalize dependent dbi.\n    induction ϕ₁; intros dbi H; simpl; simpl in H; try inversion H.\n    - case_match; subst.\n      + case_match; try lia. constructor. reflexivity.\n      + congruence.\n    - specialize (IHϕ₁1 dbi). specialize (IHϕ₁2 dbi).\n      move: H H1 IHϕ₁1 IHϕ₁2.\n      case: (bevar_occur ϕ₁1 dbi); case: (bevar_occur ϕ₁2 dbi); move=> H H1 IHϕ₁₁ IHϕ₁₂.\n      + apply sub_app_l. auto.\n      + apply sub_app_l. auto.\n      + apply sub_app_r. auto.\n      + done.\n    - specialize (IHϕ₁1 dbi). specialize (IHϕ₁2 dbi).\n      move: H H1 IHϕ₁1 IHϕ₁2.\n      case: (bevar_occur ϕ₁1 dbi); case: (bevar_occur ϕ₁2 dbi); move=> H H1 IHϕ₁₁ IHϕ₁₂.\n      + apply sub_imp_l. auto.\n      + apply sub_imp_l. auto.\n      + apply sub_imp_r. auto.\n      + done.\n    - apply sub_exists. auto.\n    - apply sub_mu. apply IHϕ₁. auto.\n  Qed.\n\n\n  Lemma free_evars_subformula ϕ₁ ϕ₂ :\n    is_subformula_of_ind ϕ₁ ϕ₂ -> free_evars ϕ₁ ⊆ free_evars ϕ₂.\n  Proof.\n    intros H. induction H.\n    * subst. apply PreOrder_Reflexive.\n    * simpl. eapply PreOrder_Transitive.\n      apply IHis_subformula_of_ind.\n      apply union_subseteq_l.\n    * simpl. eapply PreOrder_Transitive.\n      apply IHis_subformula_of_ind.\n      apply union_subseteq_r.\n    * simpl. eapply PreOrder_Transitive.\n      apply IHis_subformula_of_ind.\n      apply union_subseteq_l.\n    * simpl. eapply PreOrder_Transitive.\n      apply IHis_subformula_of_ind.\n      apply union_subseteq_r.\n    * simpl. auto.\n    * simpl. auto.\n  Qed.\n\n  Corollary evar_fresh_in_subformula x ϕ₁ ϕ₂ :\n    is_subformula_of_ind ϕ₁ ϕ₂ ->\n    evar_is_fresh_in x ϕ₂ ->\n    evar_is_fresh_in x ϕ₁.\n  Proof.\n    unfold evar_is_fresh_in.\n    intros Hsub Hfresh.\n    apply free_evars_subformula in Hsub.\n    auto.\n  Qed.\n\n  Corollary evar_fresh_in_subformula' x ϕ₁ ϕ₂ :\n    is_subformula_of ϕ₁ ϕ₂ ->\n    evar_is_fresh_in x ϕ₂ ->\n    evar_is_fresh_in x ϕ₁.\n  Proof.\n    intros Hsub Hfr.\n    pose proof (H := elimT (is_subformula_of_P ϕ₁ ϕ₂) Hsub).\n    eapply evar_fresh_in_subformula. eauto. auto.\n  Qed.\n\n  Lemma free_svars_subformula ϕ₁ ϕ₂ :\n    is_subformula_of_ind ϕ₁ ϕ₂ -> free_svars ϕ₁ ⊆ free_svars ϕ₂.\n  Proof.\n    intros H. induction H.\n    * subst. apply PreOrder_Reflexive.\n    * simpl. eapply PreOrder_Transitive.\n      apply IHis_subformula_of_ind.\n      apply union_subseteq_l.\n    * simpl. eapply PreOrder_Transitive.\n      apply IHis_subformula_of_ind.\n      apply union_subseteq_r.\n    * simpl. eapply PreOrder_Transitive.\n      apply IHis_subformula_of_ind.\n      apply union_subseteq_l.\n    * simpl. eapply PreOrder_Transitive.\n      apply IHis_subformula_of_ind.\n      apply union_subseteq_r.\n    * simpl. auto.\n    * simpl. auto.\n  Qed.\n\n  Corollary svar_fresh_in_subformula x ϕ₁ ϕ₂ :\n    is_subformula_of_ind ϕ₁ ϕ₂ ->\n    svar_is_fresh_in x ϕ₂ ->\n    svar_is_fresh_in x ϕ₁.\n  Proof.\n    unfold svar_is_fresh_in.\n    intros Hsub Hfresh.\n    apply free_svars_subformula in Hsub.\n    auto.\n  Qed.\n\n  Lemma free_evars_bsvar_subst ϕ₁ ϕ₂ dbi:\n    free_evars (ϕ₁^[svar: dbi ↦ ϕ₂]) ⊆ free_evars ϕ₁ ∪ free_evars ϕ₂.\n  Proof.\n    generalize dependent dbi.\n    induction ϕ₁; intros db; simpl.\n    - apply union_subseteq_l.\n    - apply empty_subseteq.\n    - apply empty_subseteq.\n    - case_match; set_solver.\n    - apply empty_subseteq.\n    - specialize (IHϕ₁1 db).\n      specialize (IHϕ₁2 db).\n      remember (free_evars (ϕ₁1^[svar: db ↦ ϕ₂])) as A1.\n      remember (free_evars (ϕ₁2^[svar: db ↦ ϕ₂])) as A2.\n      remember (free_evars ϕ₁1) as B1.\n      remember (free_evars ϕ₁2) as B2.\n      remember (free_evars ϕ₂) as C.\n      rewrite <- union_assoc_L.\n      rewrite {1}[B2 ∪ C]union_comm_L.\n      rewrite -{1}[C]union_idemp_L.\n      rewrite -[C ∪ C ∪ B2]union_assoc_L.\n      rewrite [B1 ∪ _]union_assoc_L.\n      rewrite [C ∪ B2]union_comm_L.\n      apply union_mono; auto.\n    - apply empty_subseteq.\n    - specialize (IHϕ₁1 db).\n      specialize (IHϕ₁2 db).\n      remember (free_evars (ϕ₁1^[svar: db ↦ ϕ₂])) as A1.\n      remember (free_evars (ϕ₁2^[svar: db ↦ ϕ₂])) as A2.\n      remember (free_evars ϕ₁1) as B1.\n      remember (free_evars ϕ₁2) as B2.\n      remember (free_evars ϕ₂) as C.\n      rewrite <- union_assoc_L.\n      rewrite {1}[B2 ∪ C]union_comm_L.\n      rewrite -{1}[C]union_idemp_L.\n      rewrite -[C ∪ C ∪ B2]union_assoc_L.\n      rewrite [B1 ∪ _]union_assoc_L.\n      rewrite [C ∪ B2]union_comm_L.\n      apply union_mono; auto.\n    - auto.\n    - auto.\n  Qed.\n\n  Lemma free_svars_bevar_subst ϕ₁ ϕ₂ dbi:\n    free_svars (ϕ₁^[evar: dbi ↦ ϕ₂]) ⊆ free_svars ϕ₁ ∪ free_svars ϕ₂.\n  Proof.\n    generalize dependent dbi.\n    induction ϕ₁; intros db; simpl.\n    - apply empty_subseteq.\n    - apply union_subseteq_l.\n    - case_match; set_solver.\n    - apply empty_subseteq.\n    - apply empty_subseteq.\n    - specialize (IHϕ₁1 db).\n      specialize (IHϕ₁2 db).\n      remember (free_svars (ϕ₁1^[evar: db ↦ ϕ₂])) as A1.\n      remember (free_svars (ϕ₁2^[evar: db ↦ ϕ₂])) as A2.\n      remember (free_svars ϕ₁1) as B1.\n      remember (free_svars ϕ₁2) as B2.\n      remember (free_svars ϕ₂) as C.\n      rewrite <- union_assoc_L.\n      rewrite {1}[B2 ∪ C]union_comm_L.\n      rewrite -{1}[C]union_idemp_L.\n      rewrite -[C ∪ C ∪ B2]union_assoc_L.\n      rewrite [B1 ∪ _]union_assoc_L.\n      rewrite [C ∪ B2]union_comm_L.\n      apply union_mono; auto.\n    - apply empty_subseteq.\n    - specialize (IHϕ₁1 db).\n      specialize (IHϕ₁2 db).\n      remember (free_svars (ϕ₁1^[evar: db ↦ ϕ₂])) as A1.\n      remember (free_svars (ϕ₁2^[evar: db ↦ ϕ₂])) as A2.\n      remember (free_svars ϕ₁1) as B1.\n      remember (free_svars ϕ₁2) as B2.\n      remember (free_svars ϕ₂) as C.\n      rewrite <- union_assoc_L.\n      rewrite {1}[B2 ∪ C]union_comm_L.\n      rewrite -{1}[C]union_idemp_L.\n      rewrite -[C ∪ C ∪ B2]union_assoc_L.\n      rewrite [B1 ∪ _]union_assoc_L.\n      rewrite [C ∪ B2]union_comm_L.\n      apply union_mono; auto.\n    - auto.\n    - auto.\n  Qed.\n\n  Lemma free_evars_bsvar_subst_1 ϕ₁ ϕ₂ dbi:\n    free_evars ϕ₁ ⊆ free_evars (ϕ₁^[svar: dbi ↦ ϕ₂]).\n  Proof.\n    generalize dependent dbi.\n    induction ϕ₁; intros dbi; simpl; try apply reflexivity.\n    - apply empty_subseteq.\n    - apply union_mono; auto.\n    - apply union_mono; auto.\n    - auto.\n    - auto.\n  Qed.\n\n  Lemma free_svars_bevar_subst_1 ϕ₁ ϕ₂ dbi:\n    free_svars ϕ₁ ⊆ free_svars (ϕ₁^[evar: dbi ↦ ϕ₂]).\n  Proof.\n    generalize dependent dbi.\n    induction ϕ₁; intros dbi; simpl; try apply reflexivity.\n    - apply empty_subseteq.\n    - apply union_mono; auto.\n    - apply union_mono; auto.\n    - auto.\n    - auto.\n  Qed.\n\n  Corollary free_evars_bsvar_subst_eq ϕ₁ ϕ₂ dbi:\n    bsvar_occur ϕ₁ dbi ->\n    free_evars (ϕ₁^[svar: dbi ↦ ϕ₂]) = free_evars ϕ₁ ∪ free_evars ϕ₂.\n  Proof.\n    intros H.\n    apply (anti_symm subseteq).\n    - apply free_evars_bsvar_subst.\n    - apply union_least.\n      + apply free_evars_bsvar_subst_1.\n      + pose proof (Hsub := bsvar_subst_contains_subformula ϕ₁ ϕ₂ dbi H).\n        apply free_evars_subformula. auto.\n  Qed.\n\n  Corollary free_svars_bevar_subst_eq ϕ₁ ϕ₂ dbi:\n    bevar_occur ϕ₁ dbi ->\n    free_svars (ϕ₁^[evar: dbi ↦ ϕ₂]) = free_svars ϕ₁ ∪ free_svars ϕ₂.\n  Proof.\n    intros H.\n    apply (anti_symm subseteq).\n    - apply free_svars_bevar_subst.\n    - apply union_least.\n      + apply free_svars_bevar_subst_1.\n      + pose proof (Hsub := bevar_subst_contains_subformula ϕ₁ ϕ₂ dbi H).\n        apply free_svars_subformula. auto.\n  Qed.\n\n  Lemma wfc_mu_aux_implies_not_bsvar_occur phi ns :\n    well_formed_closed_mu_aux phi ns ->\n    bsvar_occur phi ns = false.\n  Proof.\n    move: ns.\n    induction phi; intros ns Hwfc; simpl; simpl in Hwfc; auto.\n    - repeat case_match; try lia. congruence.\n    - apply andb_true_iff in Hwfc.\n      destruct Hwfc as [Hwfc1 Hwfc2].\n      destruct (bsvar_occur phi1 ns) eqn:Heq1, (bsvar_occur phi2 ns) eqn:Heq2; simpl.\n      rewrite IHphi1 in Heq1. assumption. congruence.\n      rewrite IHphi1 in Heq1. assumption. congruence.\n      rewrite IHphi2 in Heq2. assumption. congruence.\n      rewrite IHphi2 in Heq2. assumption. congruence.\n    - apply andb_true_iff in Hwfc.\n      destruct Hwfc as [Hwfc1 Hwfc2].\n      destruct (bsvar_occur phi1 ns) eqn:Heq1, (bsvar_occur phi2 ns) eqn:Heq2; simpl.\n      rewrite IHphi1 in Heq1. assumption. congruence.\n      rewrite IHphi1 in Heq1. assumption. congruence.\n      rewrite IHphi2 in Heq2. assumption. congruence.\n      rewrite IHphi2 in Heq2. assumption. congruence.\n  Qed.\n\n  Lemma wfc_ex_aux_implies_not_bevar_occur phi ne :\n    well_formed_closed_ex_aux phi ne ->\n    bevar_occur phi ne = false.\n  Proof.\n    move: ne.\n    induction phi; intros ne Hwfc; simpl; simpl in Hwfc; auto.\n    - apply bool_decide_eq_false.\n      case_match;[lia|congruence].\n    - apply andb_true_iff in Hwfc.\n      destruct Hwfc as [Hwfc1 Hwfc2].\n      erewrite IHphi1; eauto.\n    - apply andb_true_iff in Hwfc.\n      destruct Hwfc as [Hwfc1 Hwfc2].\n      erewrite IHphi1, IHphi2; eauto.\n  Qed.\n\n  Corollary wfc_mu_implies_not_bsvar_occur phi n :\n    well_formed_closed_mu_aux phi 0 ->\n    ~ bsvar_occur phi n.\n  Proof.\n    intros H.\n    erewrite wfc_mu_aux_implies_not_bsvar_occur. exact notF.\n    unfold well_formed_closed in H.\n    eapply well_formed_closed_mu_aux_ind.\n    2: eassumption. lia.\n  Qed.\n\n  Lemma wfc_ex_implies_not_bevar_occur phi n :\n    well_formed_closed_ex_aux phi 0 ->\n    bevar_occur phi n = false.\n  Proof.\n    intros H.\n    erewrite wfc_ex_aux_implies_not_bevar_occur.\n    { reflexivity. }\n    eapply well_formed_closed_ex_aux_ind.\n    2: apply H.\n    lia.\n  Qed.\n\n  Lemma not_bsvar_occur_bsvar_subst phi psi n:\n    well_formed_closed_mu_aux psi 0 -> well_formed_closed_mu_aux phi n ->\n    ~ bsvar_occur (phi^[svar: n ↦ psi]) n.\n  Proof.\n    move: n.\n    induction phi; intros n' H H0; simpl; auto.\n    - intros Hcontra.\n      case_match.\n      + subst. simpl in Hcontra. case_match.\n        * lia.\n        * congruence.\n      + apply wfc_mu_implies_not_bsvar_occur with (n := n') in H. congruence.\n      + subst. simpl in Hcontra. inversion H0. case_match.\n        * lia.\n        * congruence.\n    - intros Hcontra.\n      destruct (bsvar_occur (phi1^[svar: n' ↦ psi]) n') eqn:Heq1, (bsvar_occur (phi2^[svar: n' ↦ psi]) n') eqn:Heq2.\n      + eapply IHphi2; eauto. now apply andb_true_iff in H0.\n      + eapply IHphi1; eauto. now apply andb_true_iff in H0.\n      + eapply IHphi2; eauto. now apply andb_true_iff in H0.\n      + simpl in Hcontra. congruence.\n    - intros Hcontra.\n      destruct (bsvar_occur ((phi1^[svar: n' ↦ psi])) n')\n               eqn:Heq1, (bsvar_occur ((phi2^[svar: n' ↦ psi])) n') eqn:Heq2.\n      + eapply IHphi1; eauto. now apply andb_true_iff in H0.\n      + eapply IHphi1; eauto. now apply andb_true_iff in H0.\n      + eapply IHphi2; eauto. now apply andb_true_iff in H0.\n      + simpl in Hcontra. congruence.\n  Qed.\n\n  Lemma not_bsvar_occur_impl_no_neg_occ_and_no_pos_occ phi n:\n    ~ bsvar_occur phi n ->\n    no_negative_occurrence_db_b n phi && no_positive_occurrence_db_b n phi.\n  Proof.\n    move: n.\n    induction phi; intros n' H; simpl; simpl in H; cbn; auto.\n    - unfold not in H.\n      case_match; auto.\n    - destruct (bsvar_occur phi1 n') eqn: Heq3;\n        destruct (bsvar_occur phi2 n') eqn:Heq4;\n        simpl; auto.\n      specialize (IHphi1 n'). specialize (IHphi2 n').\n      rewrite Heq3 in IHphi1. rewrite Heq4 in IHphi2. clear Heq3 Heq4.\n      specialize (IHphi1 ssrbool.not_false_is_true).\n      specialize (IHphi2 ssrbool.not_false_is_true).\n      apply andb_true_iff in IHphi1.\n      apply andb_true_iff in IHphi2.\n      destruct IHphi1 as [H1n H1p].\n      destruct IHphi2 as [H2n H2p].\n      rewrite H1n. rewrite H1p. rewrite H2n. rewrite H2p.\n      simpl. reflexivity.\n    - destruct (bsvar_occur phi1 n') eqn: Heq3;\n        destruct (bsvar_occur phi2 n') eqn:Heq4;\n        simpl; auto.\n      specialize (IHphi1 n'). specialize (IHphi2 n').\n      rewrite Heq3 in IHphi1. rewrite Heq4 in IHphi2. clear Heq3 Heq4.\n      specialize (IHphi1 ssrbool.not_false_is_true).\n      specialize (IHphi2 ssrbool.not_false_is_true).\n      apply andb_true_iff in IHphi1.\n      apply andb_true_iff in IHphi2.\n      destruct IHphi1 as [H1n H1p].\n      destruct IHphi2 as [H2n H2p].\n      fold no_negative_occurrence_db_b no_positive_occurrence_db_b.\n      rewrite H1n. rewrite H1p. rewrite H2n. rewrite H2p.\n      simpl. reflexivity.\n  Qed.\n\n  Corollary not_bsvar_occur_impl_pos_occ_db phi n:\n    ~ bsvar_occur phi n ->\n    no_positive_occurrence_db_b n phi.\n  Proof.\n    intros H.\n    pose proof (H1 := not_bsvar_occur_impl_no_neg_occ_and_no_pos_occ _ _ H).\n    now apply andb_true_iff in H1.\n  Qed.\n\n  Corollary not_bsvar_occur_impl_neg_occ_db phi n:\n    ~ bsvar_occur phi n ->\n    no_negative_occurrence_db_b n phi.\n  Proof.\n    intros H.\n    pose proof (H1 := not_bsvar_occur_impl_no_neg_occ_and_no_pos_occ _ _ H).\n    now apply andb_true_iff in H1.\n  Qed.\n\n\n\n\n  Lemma x_eq_fresh_impl_x_notin_free_evars x ϕ:\n    x = fresh_evar ϕ ->\n    x ∉ free_evars ϕ.\n  Proof.\n    intros H.\n    rewrite H.\n    unfold fresh_evar.\n    apply set_evar_fresh_is_fresh'.\n  Qed.\n\n  Hint Resolve x_eq_fresh_impl_x_notin_free_evars : core.\n\nEnd syntax.\n\nModule Notations.\n  (* TODO: change Bot and Top to unicode symbols *)\n  (* TODO: this associativity is wrong! However, stdpp disallows defining it otherwise. We could use @ instead, associated to the left *)\n  Notation \"a $ b\" := (patt_app a b) (at level 65, right associativity) : ml_scope.\n  Notation \"'Bot'\" := patt_bott : ml_scope.\n  Notation \"⊥\" := patt_bott : ml_scope.\n  Notation \"a ---> b\"  := (patt_imp a b) (at level 75, right associativity) : ml_scope.\n  Notation \"'ex' , phi\" := (patt_exists phi) (at level 80) : ml_scope.\n  Notation \"'mu' , phi\" := (patt_mu phi) (at level 80) : ml_scope.\n\n  (*Notation \"AC [ p ]\" := (subst_ctx AC p) (at level 90) : ml_scope.*)\n  Notation \"C [ p ]\" := (emplace C p) (at level 90) : ml_scope.\n\nEnd Notations.\n\nModule BoundVarSugar.\n  (* Element variables - bound *)\n  Notation b0 := (patt_bound_evar 0).\n  Notation b1 := (patt_bound_evar 1).\n  Notation b2 := (patt_bound_evar 2).\n  Notation b3 := (patt_bound_evar 3).\n  Notation b4 := (patt_bound_evar 4).\n  Notation b5 := (patt_bound_evar 5).\n  Notation b6 := (patt_bound_evar 6).\n  Notation b7 := (patt_bound_evar 7).\n  Notation b8 := (patt_bound_evar 8).\n  Notation b9 := (patt_bound_evar 9).\n\n  Notation B0 := (patt_bound_svar 0).\n  Notation B1 := (patt_bound_svar 1).\n  Notation B2 := (patt_bound_svar 2).\n  Notation B3 := (patt_bound_svar 3).\n  Notation B4 := (patt_bound_svar 4).\n  Notation B5 := (patt_bound_svar 5).\n  Notation B6 := (patt_bound_svar 6).\n  Notation B7 := (patt_bound_svar 7).\n  Notation B8 := (patt_bound_svar 8).\n  Notation B9 := (patt_bound_svar 9).\n\nEnd BoundVarSugar.\n\n#[export]\n Hint Resolve\n evar_is_fresh_in_richer\n set_evar_fresh_is_fresh\n set_svar_fresh_is_fresh\n x_eq_fresh_impl_x_notin_free_evars\n  : core.\n\n#[export]\n Hint Extern 0 (is_true (@well_formed _ _)) => unfold is_true : core.\n\n#[export]\n Hint Resolve well_formed_bott : core.\n\n#[export]\n Hint Resolve well_formed_imp : core.\n\n#[export]\n Hint Resolve well_formed_app : core.\n\n#[export]\n Hint Resolve wf_sctx : core.\n\n#[export]\n Hint Resolve well_formed_ex_app : core.\n\n#[export]\n Hint Resolve well_formed_impl_well_formed_ex : core.\n\n#[export]\n Hint Resolve well_formed_free_evar_subst : core.\n\n#[export]\n Hint Resolve well_formed_free_evar_subst_0 : core.\n\n#[export]\n Hint Resolve <- evar_is_fresh_in_exists : core.\n\n#[export]\n Hint Resolve evar_is_fresh_in_evar_quantify : core.\n\n(* Tactics for resolving goals involving sets *)\n(*\n        eauto 5 using @sets.elem_of_union_l, @sets.elem_of_union_r with typeclass_instances.\n *)\n(*\n  eauto depth using @sets.union_subseteq_l, @sets.union_subseteq_r\n    with typeclass_instances.\n *)\n\n(*\n#[export]\n Hint Extern 10 (free_evars _ ⊆ free_evars _) => solve_free_evars_inclusion : core.\n *)\n\n\n#[export]\n Hint Resolve wf_imp_wfc : core.\n\n#[export]\n Hint Resolve wfc_ex_implies_not_bevar_occur : core.\n\nSection with_signature.\n  Context {Σ : Signature}.\n  Open Scope ml_scope.\n\n  Definition evar_quantify_ctx (x : evar) (n : db_index) (C : PatternCtx) : PatternCtx :=\n    match decide (x = pcEvar C)  with\n    | left _ => C\n    | right pf => Build_PatternCtx (pcEvar C) ((pcPattern C)^{{evar: x ↦ n}})\n    end.\n\n  Lemma is_linear_context_evar_quantify (x : evar) (n : db_index) (C : PatternCtx) :\n    is_linear_context C ->\n    is_linear_context (evar_quantify_ctx x n C).\n  Proof.\n    intros Hlin. unfold evar_quantify_ctx.\n    unfold is_linear_context in *.\n    destruct (decide (x = pcEvar C)); simpl.\n    - assumption.\n    - destruct C. simpl in *.\n      rename pcEvar into pcEvar0. rename pcPattern into pcPattern0.\n      assert (count_evar_occurrences pcEvar0 (pcPattern0^{{evar: x ↦ n}})\n              = count_evar_occurrences pcEvar0 pcPattern0).\n      {\n        clear Hlin.\n        move: n.\n        induction pcPattern0; intros n'; simpl in *; try lia.\n        + destruct (decide (x0 = pcEvar0)); subst; simpl in *.\n          * destruct (decide (x = pcEvar0)); try contradiction; simpl in *.\n            destruct (decide (pcEvar0 = pcEvar0)); try contradiction. reflexivity.\n          * destruct (decide (x = x0)); simpl; try reflexivity.\n            destruct (decide (x0 = pcEvar0)); try contradiction.\n            reflexivity.\n        + rewrite IHpcPattern0_1. rewrite IHpcPattern0_2. reflexivity.\n        + rewrite IHpcPattern0_1. rewrite IHpcPattern0_2. reflexivity.\n        + rewrite IHpcPattern0. reflexivity.\n        + rewrite IHpcPattern0. reflexivity.\n      }\n      congruence.\n  Qed.\n\n  Definition svar_quantify_ctx (X : svar) (n : db_index) (C : PatternCtx) : PatternCtx :=\n    Build_PatternCtx (pcEvar C) ((pcPattern C)^{{svar: X ↦ n}}).\n\n  Lemma is_linear_context_svar_quantify (X : svar) (n : db_index) (C : PatternCtx) :\n    is_linear_context C ->\n    is_linear_context (svar_quantify_ctx X n C).\n  Proof.\n    intros Hlin. unfold svar_quantify_ctx. unfold is_linear_context in *.\n    destruct C. simpl in *.\n    rename pcEvar into pcEvar0. rename pcPattern into pcPattern0.\n    assert (count_evar_occurrences pcEvar0 (pcPattern0^{{svar: X ↦ n}})\n            = count_evar_occurrences pcEvar0 pcPattern0).\n    {\n      clear Hlin.\n      move: n.\n      induction pcPattern0; intros n'; simpl in *; try lia.\n      + case_match; subst; simpl in *; reflexivity.\n      + rewrite IHpcPattern0_1. rewrite IHpcPattern0_2. reflexivity.\n      + rewrite IHpcPattern0_1. rewrite IHpcPattern0_2. reflexivity.\n      + rewrite IHpcPattern0. reflexivity.\n      + rewrite IHpcPattern0. reflexivity.\n    }\n    congruence.\n  Qed.\n\n  Lemma svar_quantify_free_evar_subst ψ ϕ x X n:\n    ψ^[[evar: x ↦ ϕ]]^{{svar: X ↦ n}} =\n    ψ^{{svar: X ↦ n}}^[[evar: x ↦ ϕ^{{svar: X ↦ n}}]].\n  Proof.\n    move: n.\n    induction ψ; intros n'; simpl; auto.\n    - case_match.\n      + auto.\n      + simpl. reflexivity.\n    - case_match; reflexivity.\n    - rewrite IHψ1. rewrite IHψ2. reflexivity.\n    - rewrite IHψ1. rewrite IHψ2. reflexivity.\n    - rewrite IHψ. reflexivity.\n    - rewrite IHψ. Fail reflexivity.\n  Abort. (* OOPS, does not hold. The problem is that [free_evar_subst'] does not wrap the target\n            in nest_mu. *)\n\n\n  Lemma svar_quantify_emplace X n C ϕ:\n    (emplace C ϕ)^{{svar: X ↦ n}} = emplace (svar_quantify_ctx X n C) (ϕ^{{svar: X ↦ n}}).\n  Proof.\n    destruct C.\n    unfold svar_quantify_ctx,emplace. simpl.\n  Abort.\n\n  Lemma evar_quantify_subst_ctx x n AC ϕ:\n    x ∉ AC_free_evars AC ->\n    (subst_ctx AC ϕ)^{{evar: x ↦ n}} = subst_ctx AC (ϕ^{{evar: x ↦ n}}).\n  Proof.\n    intros Hx.\n    induction AC.\n    - reflexivity.\n    - simpl. simpl in Hx.\n      rewrite IHAC.\n      { set_solver. }\n      rewrite [p^{{evar: x ↦ n}}]evar_quantify_fresh.\n      unfold evar_is_fresh_in. set_solver.\n      reflexivity.\n    - simpl. simpl in Hx.\n      rewrite IHAC.\n      { set_solver. }\n      rewrite [p^{{evar: x ↦ n}}]evar_quantify_fresh.\n      unfold evar_is_fresh_in. set_solver.\n      reflexivity.\n  Qed.\n\n  \n\n   Lemma wfp_free_svar_subst ϕ ψ X:\n    well_formed_closed_mu_aux ψ 0 ->\n    well_formed_positive ψ = true ->\n    well_formed_positive ϕ = true ->\n    svar_has_negative_occurrence X ϕ = false ->\n    well_formed_positive (ϕ^[[svar: X ↦ ψ]]) = true\n  with wfp_neg_free_svar_subst ϕ ψ X:\n    well_formed_closed_mu_aux ψ 0 ->\n    well_formed_positive ψ = true ->\n    well_formed_positive ϕ = true ->\n    svar_has_positive_occurrence X ϕ = false ->\n    well_formed_positive (ϕ^[[svar: X ↦ ψ]]) = true.\n  Proof.\n    - intros Hwfcψ Hwfpψ Hwfpϕ Hnoneg.\n      induction ϕ; simpl; auto.\n      + case_match; [|reflexivity].\n        assumption.\n      + cbn in Hnoneg. cbn in Hwfpϕ.\n        apply orb_false_iff in Hnoneg.\n        destruct_and!.\n        specialize (IHϕ1 ltac:(assumption) ltac:(assumption)).\n        specialize (IHϕ2 ltac:(assumption) ltac:(assumption)).\n        split_and!; auto.\n      + cbn in Hnoneg. cbn in Hwfpϕ.\n        apply orb_false_iff in Hnoneg.\n        destruct_and!.\n        pose proof (IH1 := wfp_neg_free_svar_subst ϕ1 ψ X ltac:(assumption)).\n        feed specialize IH1.\n        { assumption. }\n        { assumption. }\n        { assumption. }\n        specialize (IHϕ2 ltac:(assumption)).\n        split_and!; auto.\n      + cbn in Hnoneg. cbn in Hwfpϕ. destruct_and!.\n        rewrite IHϕ. assumption. assumption. split_and!; auto.\n        rewrite nno_free_svar_subst.\n        assumption. assumption.\n    -\n      intros Hwfcψ Hwfpψ Hwfpϕ Hnoneg.\n      induction ϕ; simpl; auto.\n      + case_match; [|reflexivity].\n        assumption.\n      + cbn in Hnoneg. cbn in Hwfpϕ.\n        apply orb_false_iff in Hnoneg.\n        destruct_and!.\n        specialize (IHϕ1 ltac:(assumption) ltac:(assumption)).\n        specialize (IHϕ2 ltac:(assumption) ltac:(assumption)).\n        split_and!; auto.\n      + cbn in Hnoneg. cbn in Hwfpϕ.\n        apply orb_false_iff in Hnoneg.\n        destruct_and!.\n        pose proof (IH1 := wfp_free_svar_subst ϕ1 ψ X ltac:(assumption)).\n        feed specialize IH1.\n        { assumption. }\n        { assumption. }\n        { assumption. }\n        specialize (IHϕ2 ltac:(assumption)).\n        split_and!; auto.\n      + cbn in Hnoneg. cbn in Hwfpϕ. destruct_and!.\n        rewrite IHϕ. assumption. assumption. split_and!; auto.\n        rewrite nno_free_svar_subst.\n        assumption. assumption.\n  Qed.\n\n  Lemma count_evar_occurrences_bevar_subst pcEvar ϕ ψ k:\n    count_evar_occurrences pcEvar ψ = 0 ->\n    count_evar_occurrences pcEvar (ϕ^[evar: k ↦ ψ]) = count_evar_occurrences pcEvar ϕ.\n  Proof.\n    intros H.\n    move: k.\n    induction ϕ; intros k; simpl; auto.\n    - case_match; auto.\n  Qed.\n\n  Lemma count_evar_occurrences_evar_open pcEvar ϕ x:\n    pcEvar <> x ->\n    count_evar_occurrences pcEvar (ϕ^{evar: 0 ↦ x}) = count_evar_occurrences pcEvar ϕ.\n  Proof.\n    intros H. apply count_evar_occurrences_bevar_subst. simpl. case_match; congruence.\n  Qed.\n\n\n  Lemma count_evar_occurrences_svar_open x dbi ϕ ψ:\n    count_evar_occurrences x ψ = 0 ->\n    count_evar_occurrences x (ϕ^[svar: dbi ↦ ψ]) = count_evar_occurrences x ϕ.\n  Proof.\n    move: dbi.\n    induction ϕ; intros dbi H; simpl; auto.\n    case_match; auto.\n  Qed.\n\n  Lemma free_evar_subst_bsvar_subst ϕ ψ ξ x dbi:\n    well_formed_closed_mu_aux ξ 0 ->\n    evar_is_fresh_in x ψ ->\n    (ϕ^[svar: dbi ↦ ψ])^[[evar:x ↦ ξ]]\n    = (ϕ^[[evar:x ↦ ξ]])^[svar: dbi ↦ ψ].\n  Proof.\n    move: dbi.\n    induction ϕ; intros dbi H1 H2; simpl; auto.\n    - repeat case_match; auto.\n      erewrite well_formed_bsvar_subst. reflexivity.\n      2: eassumption.\n      lia.\n    - repeat case_match; auto.\n      apply free_evar_subst_no_occurrence. assumption.\n    - rewrite IHϕ1; auto. rewrite IHϕ2; auto.\n    - rewrite IHϕ1; auto. rewrite IHϕ2; auto.\n    - rewrite IHϕ; auto.\n    - rewrite IHϕ; auto.\n  Qed.\n\n  Lemma wf_svar_open_from_wf_mu X ϕ:\n    well_formed (patt_mu ϕ) ->\n    well_formed (ϕ^{svar: 0 ↦ X}).\n  Proof.\n    intros H. (*compoundDecomposeWfGoal.\n    apply (unary_wfxy_compose _).*) wf_auto2.\n    (*\n    wf_auto2_fast_done.\n    compositeSimplifyAllWfHyps.\n    wf_auto2_composite_step.\n    wf_auto2_composite_step.\n    Set Printing All.\n    Search well_formed svar_open.\n    wf_auto2.\n    destruct_and!;\n        [ (apply wfp_svar_open; auto)\n        | (apply wfc_mu_aux_body_mu_imp1; assumption)\n        | (apply wfc_ex_aux_body_mu_imp1; assumption)\n        ].\n    *)\n  Qed.\n\n\n  Lemma wfcex_after_subst_impl_wfcex_before ϕ ψ x dbi:\n    well_formed_closed_ex_aux (ϕ^[[evar:x ↦ ψ]]) dbi = true ->\n    well_formed_closed_ex_aux ϕ dbi = true.\n  Proof.\n    intros Hsubst.\n    move: dbi Hsubst.\n    induction ϕ; intros dbi Hsubst; simpl in *; try reflexivity; auto with nocore.\n    - apply andb_prop in Hsubst. destruct Hsubst as [Hsubst1 Hsubst2].\n      specialize (IHϕ1 dbi Hsubst1).\n      specialize (IHϕ2 dbi Hsubst2).\n      rewrite IHϕ1 IHϕ2.\n      reflexivity.\n    - apply andb_prop in Hsubst. destruct Hsubst as [Hsubst1 Hsubst2].\n      specialize (IHϕ1 dbi Hsubst1).\n      specialize (IHϕ2 dbi Hsubst2).\n      rewrite IHϕ1 IHϕ2.\n      reflexivity.\n  Qed.\n\n  Lemma wfcmu_after_subst_impl_wfcmu_before ϕ ψ x dbi:\n    well_formed_closed_mu_aux (ϕ^[[evar:x ↦ ψ]]) dbi = true ->\n    well_formed_closed_mu_aux ϕ dbi = true.\n  Proof.\n    intros Hsubst.\n    move: dbi Hsubst.\n    induction ϕ; intros dbi Hsubst; simpl in *; try reflexivity; auto with nocore.\n    - apply andb_prop in Hsubst. destruct Hsubst as [Hsubst1 Hsubst2].\n      specialize (IHϕ1 dbi Hsubst1).\n      specialize (IHϕ2 dbi Hsubst2).\n      rewrite IHϕ1 IHϕ2.\n      reflexivity.\n    - apply andb_prop in Hsubst. destruct Hsubst as [Hsubst1 Hsubst2].\n      specialize (IHϕ1 dbi Hsubst1).\n      specialize (IHϕ2 dbi Hsubst2).\n      rewrite IHϕ1 IHϕ2.\n      reflexivity.\n  Qed.\n\n  Lemma nno_after_subst_impl_nno_before ϕ ψ x dbi:\n    no_negative_occurrence_db_b dbi (ϕ^[[evar:x ↦ ψ]]) = true ->\n    no_negative_occurrence_db_b dbi ϕ = true\n  with npo_after_subst_impl_npo_before ϕ ψ x dbi:\n    no_positive_occurrence_db_b dbi (ϕ^[[evar:x ↦ ψ]]) = true ->\n    no_positive_occurrence_db_b dbi ϕ = true.\n  Proof.\n    - move: dbi.\n      induction ϕ; intros dbi Hsubst; cbn in *; try reflexivity; auto with nocore.\n      + apply andb_prop in Hsubst. destruct Hsubst as [Hsubst1 Hsubst2].\n        specialize (IHϕ1 dbi Hsubst1).\n        specialize (IHϕ2 dbi Hsubst2).\n        rewrite IHϕ1. rewrite IHϕ2.\n        reflexivity.\n      + apply andb_prop in Hsubst. destruct Hsubst as [Hsubst1 Hsubst2].\n        fold no_positive_occurrence_db_b in Hsubst1.\n        fold no_positive_occurrence_db_b.\n        specialize (IHϕ2 dbi Hsubst2).\n        rewrite IHϕ2.\n        erewrite npo_after_subst_impl_npo_before.\n        reflexivity. eassumption.\n    - move: dbi.\n      induction ϕ; intros dbi Hsubst; cbn in *; try reflexivity; auto with nocore.\n      + apply andb_prop in Hsubst. destruct Hsubst as [Hsubst1 Hsubst2].\n        specialize (IHϕ1 dbi Hsubst1).\n        specialize (IHϕ2 dbi Hsubst2).\n        rewrite IHϕ1. rewrite IHϕ2.\n        reflexivity.\n      + apply andb_prop in Hsubst. destruct Hsubst as [Hsubst1 Hsubst2].\n        fold no_negative_occurrence_db_b in Hsubst1.\n        fold no_negative_occurrence_db_b.\n        specialize (IHϕ2 dbi Hsubst2).\n        rewrite IHϕ2.\n        erewrite nno_after_subst_impl_nno_before.\n        reflexivity. eassumption.\n  Qed.\n\n  Lemma wfp_after_subst_impl_wfp_before ϕ ψ x:\n    well_formed_positive (ϕ^[[evar:x ↦ ψ]]) = true ->\n    well_formed_positive ϕ = true.\n  Proof.\n    intros Hsubst.\n    move: Hsubst.\n    induction ϕ; intros Hsubst; simpl in *; try reflexivity; auto with nocore.\n    - apply andb_prop in Hsubst. destruct Hsubst as [Hsubst1 Hsubst2].\n      specialize (IHϕ1 Hsubst1).\n      specialize (IHϕ2 Hsubst2).\n      rewrite IHϕ1. rewrite IHϕ2.\n      reflexivity.\n    - apply andb_prop in Hsubst. destruct Hsubst as [Hsubst1 Hsubst2].\n      specialize (IHϕ1 Hsubst1).\n      specialize (IHϕ2 Hsubst2).\n      rewrite IHϕ1. rewrite IHϕ2.\n      reflexivity.\n    - apply andb_prop in Hsubst. destruct Hsubst as [Hnno Hsubst]. \n      specialize (IHϕ Hsubst).\n      rewrite IHϕ.\n      erewrite nno_after_subst_impl_nno_before.\n      reflexivity. eassumption.\n  Qed.\n\n  Lemma wf_after_subst_impl_wf_before ϕ ψ x:\n    well_formed (ϕ^[[evar:x ↦ ψ]]) = true ->\n    well_formed ϕ = true.\n  Proof.\n    intros H.\n    unfold well_formed,well_formed_closed in *.\n    destruct_and!.\n    split_and!.\n    - eapply wfp_after_subst_impl_wfp_before. eassumption.\n    - eapply wfcmu_after_subst_impl_wfcmu_before. eassumption.\n    - eapply wfcex_after_subst_impl_wfcex_before. eassumption.\n  Qed.\n\n  Lemma wf_emplaced_impl_wf_context (C : PatternCtx) (ψ : Pattern) :\n    well_formed (emplace C ψ) = true ->\n    PC_wf C.\n  Proof.\n    intros H.\n    unfold emplace in H. unfold PC_wf.\n    eapply wf_after_subst_impl_wf_before.\n    eassumption.\n  Qed.\n\n  Global Instance evar_is_fresh_in_dec (x : evar) (p : Pattern) :\n    Decision (evar_is_fresh_in x p).\n  Proof.\n    unfold evar_is_fresh_in.\n    apply not_dec. apply gset_elem_of_dec.\n  Defined.\n\n  Definition evar_is_fresh_in_list (x : evar) (l : list Pattern) :=\n    Forall (evar_is_fresh_in x) l.\n\n  Global Instance evar_is_fresh_in_list_dec (x : evar) (l : list Pattern) :\n    Decision (evar_is_fresh_in_list x l).\n  Proof.\n    unfold Decision. unfold evar_is_fresh_in_list.\n    apply Forall_dec.\n    intros p.\n    apply evar_is_fresh_in_dec.\n  Defined.\n\n  Lemma evar_fresh_in_foldr x g l:\n  evar_is_fresh_in x (foldr patt_imp g l) <-> evar_is_fresh_in x g /\\ evar_is_fresh_in_list x l.\n  Proof.\n  induction l; simpl; split; intros H.\n  - split;[assumption|]. unfold evar_is_fresh_in_list. apply Forall_nil. exact I.\n  - destruct H as [H _]. exact H.\n  - unfold evar_is_fresh_in_list,evar_is_fresh_in in *. simpl in *.\n    split;[set_solver|].\n    apply Forall_cons.\n    destruct IHl as [IHl1 IHl2].\n    split;[set_solver|].\n    apply IHl1. set_solver.\n  - unfold evar_is_fresh_in_list,evar_is_fresh_in in *. simpl in *.\n    destruct IHl as [IHl1 IHl2].\n    destruct H as [H1 H2].\n    inversion H2; subst.\n    specialize (IHl2 (conj H1 H4)).\n    set_solver.\n  Qed.\n\n  Global Instance svar_is_fresh_in_dec (X : svar) (p : Pattern) :\n    Decision (svar_is_fresh_in X p).\n  Proof.\n    unfold svar_is_fresh_in.\n    apply not_dec. apply gset_elem_of_dec.\n  Defined.\n\n  Definition svar_is_fresh_in_list (X : svar) (l : list Pattern) :=\n    Forall (svar_is_fresh_in X) l.\n\n  Global Instance svar_is_fresh_in_list_dec (X : svar) (l : list Pattern) :\n    Decision (svar_is_fresh_in_list X l).\n  Proof.\n    unfold Decision. unfold svar_is_fresh_in_list.\n    apply Forall_dec.\n    intros p.\n    apply svar_is_fresh_in_dec.\n  Defined.\n\n  Lemma wfc_ex_lower ϕ n:\n    bevar_occur ϕ n = false ->\n    well_formed_closed_ex_aux ϕ (S n) = true ->\n    well_formed_closed_ex_aux ϕ n = true.\n  Proof.\n    intros H1 H2.\n    move: n H1 H2.\n    induction ϕ; intros n' H1 H2; simpl in *; auto.\n    - repeat case_match; auto. lia.\n    - apply orb_false_elim in H1. destruct_and!.\n      erewrite -> IHϕ1 by eassumption.\n      erewrite -> IHϕ2 by eassumption.\n      reflexivity.\n    - apply orb_false_elim in H1. destruct_and!.\n      erewrite -> IHϕ1 by eassumption.\n      erewrite -> IHϕ2 by eassumption.\n      reflexivity.\n  Qed.\n\n  Lemma wfc_mu_lower ϕ n:\n    bsvar_occur ϕ n = false ->\n    well_formed_closed_mu_aux ϕ (S n) = true ->\n    well_formed_closed_mu_aux ϕ n = true.\n  Proof.\n    intros H1 H2.\n    move: n H1 H2.\n    induction ϕ; intros n' H1 H2; simpl in *; auto.\n    - repeat case_match; auto. lia.\n    - apply orb_false_elim in H1. destruct_and!.\n      erewrite -> IHϕ1 by eassumption.\n      erewrite -> IHϕ2 by eassumption.\n      reflexivity.\n    - apply orb_false_elim in H1. destruct_and!.\n      erewrite -> IHϕ1 by eassumption.\n      erewrite -> IHϕ2 by eassumption.\n      reflexivity.\n  Qed.\n\n  Lemma wf_ex_quan_impl_wf (x : evar) (ϕ : Pattern):\n    bevar_occur ϕ 0 = false ->\n    well_formed (exists_quantify x ϕ) = true ->\n    well_formed ϕ = true.\n  Proof.\n    intros H0 H. unfold exists_quantify in H.\n    unfold well_formed, well_formed_closed in *. destruct_and!. simpl in *.\n    split_and!.\n    - eapply wfp_evar_quan_impl_wfp. eassumption.\n    - eapply wfcmu_evar_quan_impl_wfcmu. eassumption.\n    - apply wfcex_evar_quan_impl_wfcex in H3.\n      apply wfc_ex_lower; assumption.\n  Qed.\n\n  Lemma bevar_occur_evar_open_2 dbi x ϕ:\n    well_formed_closed_ex_aux ϕ dbi ->\n    bevar_occur (ϕ^{evar: dbi ↦ x}) dbi = false.\n  Proof.\n    move: dbi.\n    unfold evar_open.\n    induction ϕ; intros dbi Hwf; simpl; try reflexivity.\n    - case_match; simpl; auto.\n      case_match; try lia. simpl in Hwf. case_match; [lia | congruence ].\n    - simpl in Hwf. destruct_and!.\n      rewrite IHϕ1; auto. rewrite IHϕ2; auto.\n    - simpl in Hwf. destruct_and!.\n      rewrite IHϕ1; auto. rewrite IHϕ2; auto.\n    - rewrite IHϕ; auto.\n    - rewrite IHϕ; auto.\n  Qed.\n\n  Lemma bsvar_occur_svar_open_2 dbi X ϕ:\n    well_formed_closed_mu_aux ϕ dbi ->\n    bsvar_occur (ϕ^{svar: dbi ↦ X}) dbi = false.\n  Proof.\n    move: dbi.\n    unfold svar_open.\n    induction ϕ; intros dbi Hwf; simpl; try reflexivity.\n    - case_match; simpl; auto.\n      case_match; try lia. simpl in Hwf. case_match; [lia | congruence ].\n    - simpl in Hwf. destruct_and!.\n      rewrite IHϕ1; auto. rewrite IHϕ2; auto.\n    - simpl in Hwf. destruct_and!.\n      rewrite IHϕ1; auto. rewrite IHϕ2; auto.\n    - rewrite IHϕ; auto.\n    - rewrite IHϕ; auto.\n  Qed.\n\n  Lemma svar_has_negative_occurrence_free_evar_subst\n    (ϕ ψ: Pattern) (x : evar) (X : svar) :\n    svar_is_fresh_in X ψ ->\n    svar_has_negative_occurrence X ϕ^[[evar:x↦ψ]] = svar_has_negative_occurrence X ϕ\n  with svar_has_positive_occurrence_free_evar_subst\n    (ϕ ψ: Pattern) (x : evar) (X : svar) :\n    svar_is_fresh_in X ψ ->\n    svar_has_positive_occurrence X ϕ^[[evar:x↦ψ]] = svar_has_positive_occurrence X ϕ\n  .\n  Proof.\n    {\n      intros HXψ.\n      induction ϕ; cbn in *; try reflexivity.\n      {\n        destruct (decide (x = x0)).\n        {\n          apply svar_hno_false_if_fresh.\n          exact HXψ.\n        }\n        {\n          cbn. reflexivity.\n        }\n      }\n      {\n        by rewrite IHϕ1 IHϕ2.\n      }\n      {\n        fold svar_has_positive_occurrence.\n        rewrite IHϕ2.\n        rewrite svar_has_positive_occurrence_free_evar_subst.\n        { exact HXψ. }\n        reflexivity.\n      }\n      {\n        exact IHϕ.\n      }\n      {\n        exact IHϕ.\n      }\n    }\n    {\n      intros HXψ.\n      induction ϕ; cbn in *; try reflexivity.\n      {\n        destruct (decide (x = x0)).\n        {\n          apply svar_hpo_false_if_fresh.\n          exact HXψ.\n        }\n        {\n          cbn. reflexivity.\n        }\n      }\n      {\n        by rewrite IHϕ1 IHϕ2.\n      }\n      {\n        fold svar_has_negative_occurrence.\n        rewrite IHϕ2.\n        rewrite svar_has_negative_occurrence_free_evar_subst.\n        { exact HXψ. }\n        reflexivity.\n      }\n      {\n        exact IHϕ.\n      }\n      {\n        exact IHϕ.\n      }\n    }\n  Qed.\n    \n\n  Fixpoint maximal_mu_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_mu_depth_to depth E ψ₁)\n        (maximal_mu_depth_to depth E ψ₂)\n    | patt_app ψ₁ ψ₂\n      => Nat.max\n        (maximal_mu_depth_to depth E ψ₁)\n        (maximal_mu_depth_to depth E ψ₂)\n    | patt_exists ψ' =>\n      maximal_mu_depth_to depth E ψ'\n    | patt_mu ψ' =>\n      maximal_mu_depth_to (S depth) E ψ'\n    end.\n\n\n  Fixpoint maximal_mu_depth_to_sv (depth : nat) (V : svar) (ψ : 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_evar _ => 0\n    | patt_free_svar V' =>\n      match (decide (V' = V)) with\n      | left _ => depth\n      | right _ => 0\n      end\n    | patt_imp ψ₁ ψ₂\n      => Nat.max\n        (maximal_mu_depth_to_sv depth V ψ₁)\n        (maximal_mu_depth_to_sv depth V ψ₂)\n    | patt_app ψ₁ ψ₂\n      => Nat.max\n        (maximal_mu_depth_to_sv depth V ψ₁)\n        (maximal_mu_depth_to_sv depth V ψ₂)\n    | patt_exists ψ' =>\n      maximal_mu_depth_to_sv depth V ψ'\n    | patt_mu ψ' =>\n      maximal_mu_depth_to_sv (S depth) V ψ'\n    end.\n\n  Lemma maximal_mu_depth_to_svar_open depth E n X ψ:\n  maximal_mu_depth_to depth E (ψ^{svar: n ↦ X})\n    = maximal_mu_depth_to depth E ψ.\n  Proof.\n    unfold svar_open.\n    move: depth n.\n    induction ψ; intros depth n'; simpl; try reflexivity; auto.\n    {\n      case_match; simpl; try reflexivity.\n    }\n  Qed.\n\n\n  Lemma maximal_mu_depth_to_sv_evar_open depth V n X ψ:\n    maximal_mu_depth_to_sv depth V (ψ^{evar: n ↦ X})\n    = maximal_mu_depth_to_sv depth V ψ.\n  Proof.\n    unfold evar_open.\n    move: depth n.\n    induction ψ; intros depth n'; simpl; try reflexivity; auto.\n    {\n      case_match; simpl; try reflexivity.\n    }\n  Qed.\n\n  Lemma evar_open_mu_depth depth E n x ψ:\n    E <> x ->\n    maximal_mu_depth_to depth E (ψ^{evar: n ↦ x})\n    = maximal_mu_depth_to depth E ψ.\n  Proof.\n    intros Hne.\n    unfold evar_open.\n    move: depth n.\n    induction ψ; intros depth n'; simpl; try reflexivity; auto.\n    {\n      case_match; simpl; try reflexivity.\n      case_match; simpl; try reflexivity.\n      subst. contradiction.\n    }\n  Qed.\n\n  Lemma svar_open_mu_depth_sc depth V n x ψ:\n  V <> x ->\n  maximal_mu_depth_to_sv depth V (ψ^{svar: n ↦ x})\n  = maximal_mu_depth_to_sv depth V ψ.\n  Proof.\n    intros Hne.\n    unfold svar_open.\n    move: depth n.\n    induction ψ; intros depth n'; simpl; try reflexivity; auto.\n    {\n      case_match; simpl; try reflexivity.\n      case_match; simpl; try reflexivity.\n      subst. contradiction.\n    }\n  Qed.\n\n  Lemma svar_open_mu_depth depth E n X ψ:\n    maximal_mu_depth_to depth E (ψ^{svar: n ↦ X})\n    = maximal_mu_depth_to depth E ψ.\n  Proof.\n    unfold svar_open.\n    move: depth n.\n    induction ψ; intros depth n'; simpl; try reflexivity; auto.\n    {\n      case_match; simpl; try reflexivity.\n    }\n  Qed.\n\n  Lemma maximal_mu_depth_to_0 E ψ depth:\n    E ∉ free_evars ψ ->\n    maximal_mu_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_mu_depth_to_sv_0 V ψ depth:\n    V ∉ free_svars ψ ->\n    maximal_mu_depth_to_sv depth V ψ = 0.\n  Proof.\n    intros Hnotin.\n    move: V 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_mu_depth_to_S E ψ depth:\n    E ∈ free_evars ψ ->\n    maximal_mu_depth_to (S depth) E ψ\n    = S (maximal_mu_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_mu_depth_to_0 with (depth := S depth) in n\n          as n'.\n        apply maximal_mu_depth_to_0 with (depth := depth) in n.\n        rewrite n. lia. \n      }\n      {\n        rewrite IHψ2. assumption.\n        apply maximal_mu_depth_to_0 with (depth := S depth) in n\n          as n'.\n        apply maximal_mu_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_mu_depth_to_0 with (depth := S depth) in n\n          as n'.\n        apply maximal_mu_depth_to_0 with (depth := depth) in n.\n        rewrite n. lia. \n      }\n      {\n        rewrite IHψ2. assumption.\n        apply maximal_mu_depth_to_0 with (depth := S depth) in n\n          as n'.\n        apply maximal_mu_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 maximal_mu_depth_to_sv_S V ψ depth:\n    V ∈ free_svars ψ ->\n    maximal_mu_depth_to_sv (S depth) V ψ\n    = S (maximal_mu_depth_to_sv depth V ψ).\n  Proof.\n    intros Hin.\n    move: V depth Hin.\n    induction ψ; intros V depth Hin; simpl in *; try set_solver.\n    { case_match. reflexivity. set_solver. }\n    {\n      destruct (decide (V ∈ free_svars ψ1)),(decide (V ∈ free_svars ψ2)).\n      {\n        rewrite IHψ1. assumption. rewrite IHψ2. assumption. simpl. reflexivity.\n      }\n      {\n        rewrite IHψ1. assumption.\n        apply maximal_mu_depth_to_sv_0 with (depth := S depth) in n\n          as n'.\n        apply maximal_mu_depth_to_sv_0 with (depth := depth) in n.\n        rewrite n. lia. \n      }\n      {\n        rewrite IHψ2. assumption.\n        apply maximal_mu_depth_to_sv_0 with (depth := S depth) in n\n          as n'.\n        apply maximal_mu_depth_to_sv_0 with (depth := depth) in n.\n        rewrite n. lia. \n      }\n      {\n        exfalso. set_solver.\n      }\n    }\n    {\n      destruct (decide (V ∈ free_svars ψ1)),(decide (V ∈ free_svars ψ2)).\n      {\n        rewrite IHψ1. assumption. rewrite IHψ2. assumption. simpl. reflexivity.\n      }\n      {\n        rewrite IHψ1. assumption.\n        apply maximal_mu_depth_to_sv_0 with (depth := S depth) in n\n          as n'.\n        apply maximal_mu_depth_to_sv_0 with (depth := depth) in n.\n        rewrite n. lia. \n      }\n      {\n        rewrite IHψ2. assumption.\n        apply maximal_mu_depth_to_sv_0 with (depth := S depth) in n\n          as n'.\n        apply maximal_mu_depth_to_sv_0 with (depth := depth) in n.\n        rewrite n. lia. \n      }\n      {\n        exfalso. set_solver.\n      }\n    }\n  Qed.\n\n  Definition mu_in_evar_path E ψ sdepth\n  := negb (Nat.eqb 0 (maximal_mu_depth_to sdepth E ψ)).\n\n\n\nEnd with_signature.\n\n\n(* TODO remove these hints *)\n\n#[export]\n Hint Resolve well_formed_positive_svar_quantify : core.\n\n#[export]\n Hint Resolve no_positive_occurrence_svar_quantify : core.\n\n#[export]\n Hint Resolve no_negative_occurrence_svar_quantify : core.\n\n#[export]\n Hint Resolve wfc_impl_no_neg_occ : core.\n\n#[export]\n Hint Resolve wfp_free_svar_subst : core.\n\n#[export]\n Hint Resolve wfp_neg_free_svar_subst : core.\n\n\n#[export]\n Hint Resolve svar_quantify_closed_ex : core.\n\n#[export]\n Hint Resolve svar_quantify_closed_mu : core.\n\n#[export]\n Hint Resolve evar_quantify_positive : core.\n\n#[export]\n Hint Resolve evar_quantify_closed_mu : core.\n\n#[export]\n Hint Resolve evar_quantify_closed_ex : core.\n\n#[export]\n Hint Resolve wfp_evar_open : core.\n\n#[export]\n Hint Resolve wfc_mu_aux_body_ex_imp1 : core.\n\n#[export]\n Hint Resolve wfc_ex_aux_body_ex_imp1 : core.\n\n#[export]\nHint Resolve bevar_subst_positive_2 : core.\n\n#[export]\nHint Resolve wfc_mu_aux_bevar_subst : core.\n\n#[export]\nHint Resolve wfc_ex_aux_bevar_subst : core.\n\n#[export]\nHint Resolve wfp_svar_open : core.\n\n#[export]\n Hint Resolve wfc_mu_free_evar_subst : core.", "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/Syntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2703403835906434}}
{"text": "(* Sections taking care of let-ins for inductive types *)\n\nSection Foo.\n\nInductive foo (A : Type) (x : A) (y := x) (y : A) := Foo.\n\nEnd Foo.\n\nSection Foo2.\n\nVariable B : Type.\nVariable b : B.\nLet c := b.\nInductive foo2 (A : Type) (x : A) (y := x) (y : A) := Foo2 : c=c -> foo2 A x y.\n\nEnd Foo2.\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/5755.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.27034038359064333}}
{"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 H K O L Hprime Kprime Oprime Lprime Kprimeprime Lprimeprime I Iprime : Universe, ((wd_ Oprime Kprimeprime /\\ (wd_ Oprime Kprime /\\ (wd_ Oprime Lprimeprime /\\ (wd_ Oprime Lprime /\\ (wd_ O H /\\ (wd_ K I /\\ (wd_ I L /\\ (wd_ K L /\\ (wd_ O I /\\ (wd_ Oprime Iprime /\\ (wd_ Iprime Lprimeprime /\\ (wd_ Kprimeprime Iprime /\\ (wd_ Iprime Lprimeprime /\\ (wd_ Kprimeprime Lprimeprime /\\ (wd_ K O /\\ (col_ Oprime Kprime Kprimeprime /\\ (col_ Oprime Lprime Lprimeprime /\\ (col_ K I L /\\ (col_ Oprime Iprime Hprime /\\ (col_ O I H /\\ (col_ Kprimeprime Iprime Lprimeprime /\\ col_ Kprimeprime Oprime Iprime))))))))))))))))))))) -> col_ Kprime Oprime Lprime)).\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_0805.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2702919713367572}}
{"text": "Require Import BGPSpec.\nRequire Import Miscy.\nRequire Import Fairness.\nRequire Import Environment.\nRequire Import Evolution.\nRequire Import InitState.\n\nSection GaoRexford.\n  Context `{PR:@PrefixClass}.\n  Context `{IT:@InternetTopologyClass}.\n  Context `{AT:@AttributesClass IT}.\n  Context `{IP:@InitialPrefixClass PR IT AT}.\n  Context `{OD:@OrderingClass IT AT}.\n  Context `{RU:@RuleClass IT AT PR IP OD}.\n  Context `{IS:@InitialState PR IT AT IP OD RU}.\n\n  Definition TO := @fullMeshTopology IT.\n  Definition PA := @pathAttributesAttributes IT AT.\n  Definition CO := @configClass IT AT PR IP OD RU.\n\n  Variable e:@evolutionFrom _ (@FairTransition PR TO PA CO) s0.\n\n  Definition InternetConverges : Type. \n    refine { A:(forall (p:Prefix) x (r:router x), RoutingInformation) | _ }.\n    refine (eventually _ (@FairTransition PR TO PA CO) (fun s => _) (s0;e)).\n    refine (forall (x:AS) (r:router x) (p:Prefix), _ : Prop).\n    refine (locRIB (routerState (networkState' s) (x;r)) p = A p x r).\n  Defined.\n\n  (* \n  above is the trusted definition of what \n  it means for the internet to converge\n  ----------------------------------------------\n  below is the proof that the internet converges \n  *)\n\n  Require Import Evolution.\n  Require Import Claims.\n  Require Import DominantConvergence.\n  Require Import InternalConvergence.\n  Require Import BGPConvergence.\n  Require Import EvolutionLemmas.\n  Require Import Sugar.\n  Require Import PathInvariant.\n  \n  Opaque export'.\n  Opaque import'.\n  Opaque eqDecide.\n  Opaque enumerate.\n  Opaque argMax.\n\n  Definition CV := convergence (s0;e).\n\n  Section SinglePrefix.\n    Variable prefix:Prefix.\n\n    Definition SP := singlePrefixClass prefix.\n    Existing Instance SP.\n \n    Definition BC := @bgpConvergence PR IT AT IP OD RU IS e SP.\n\n    Definition CD := @convergenceDefinitions PR IT AT IP OD RU CV SP BC.\n\n    Definition LC := @linkConverges PR IT AT IP OD RU IS e prefix.\n\n    Definition AC := @asConvergenceLemmas PR IT AT IP OD RU CV SP BC.\n\n    Definition RouterPrefixConverges : Type.\n      refine (forall x (r:router x), _).\n      refine {a : RoutingInformation | @converges _ CV (fun s => _)}. \n      refine (locRIB (ribs s x r) p = a).\n    Defined.\n\n    Definition routerPrefixConverges : RouterPrefixConverges. \n      specialize (@Claim2 PR IT AT IP SP CD LC AC); intros h.\n      intros x r.\n      specialize (h x r).\n      apply indefinite_description.\n      destruct h as [i [a h]].\n      unfold StableRouter in h.\n      eexists.\n      refine (impliedConverges _ _ (combineConverges _ \n               (alwaysEConverges e (ribsFromInConverges e)) h)); clear h.\n      intros s [ribsIn [hI hA]].\n      destruct (ribsIn p x r) as [loc _].\n      rewrite loc; clear loc.\n      unfold bestImport, imports in *.\n      cbn in *.\n      rewrite hI.\n      rewrite hA.\n      reflexivity.\n    Defined.      \n  End SinglePrefix.\n\n  Lemma internetConverges : InternetConverges.\n    unfold InternetConverges.\n    specialize (routerPrefixConverges); intros h.\n    unfold RouterPrefixConverges in h.\n    refine ((fun h' => _) (fun p x => _)); revgoals. {\n      exact (swap_ex_forall (h p x)). \n    } clear h; rename h' into h.\n    refine ((fun h' => _) (fun p => _)); revgoals. {\n      exact (swap_ex_forall (h p)). \n    } clear h; rename h' into h.\n    apply swap_ex_forall in h.\n    cbn in h.\n    destruct h as [A h].\n    exists A.\n    refine (_ : @converges _ CV _).\n    apply (distributeForallConverges _); intros x.\n    apply (distributeForallConverges _); intros r.\n    apply (distributeForallConverges _); intros p.\n    apply h.\n  Qed.\nEnd GaoRexford.\n", "meta": {"author": "uwplse", "repo": "bagpipe", "sha": "67a38c4c6def7fb270a045b4afa668d22e293be7", "save_path": "github-repos/coq/uwplse-bagpipe", "path": "github-repos/coq/uwplse-bagpipe/bagpipe-67a38c4c6def7fb270a045b4afa668d22e293be7/src/bagpipe/coq/GaoRexford/InternetConverges.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.27029196664886435}}
{"text": "From fae_gtlc_mu.refinements.static_gradual Require Export compat_cast.defs.\nFrom fae_gtlc_mu.cast_calculus Require Export lang.\n\nSection compat_cast_identity.\n  Context `{!implG Σ,!specG Σ}.\n  Local Hint Resolve to_of_val : core.\n\n  (** The case `atomic_Base` in our proof by induction on the alternative consistency relation. *)\n  Lemma back_cast_ar_base_base:\n    ∀ A : list (type * type), back_cast_ar (atomic_Base A).\n  Proof.\n    intros A.\n    rewrite /back_cast_ar. iIntros (ei' K' v v' fs) \"(#Hfs & #Hvv' & #Hei' & Hv')\".\n    rewrite interp_rw_TUnit.\n    iDestruct \"Hvv'\" as \"%\"; inversion H. simpl in *. rewrite H0 H1. clear v v' H H0 H1.\n    asimpl. wp_head.\n    iMod (step_pure _ ei' K'\n                    (Cast Unit TUnit TUnit)\n                    Unit with \"[Hv']\") as \"Hv'\". intros. eapply IdBase. by simpl. auto.\n    iSplitR. done. done. asimpl. wp_value. iExists UnitV. iSplitL. done. rewrite interp_rw_TUnit. done.\n  Qed.\n\n  (** The case `atomic_Unknown` in our proof by induction on the alternative consistency relation. *)\n  Lemma back_cast_ar_star_star:\n    ∀ A : list (type * type), back_cast_ar (atomic_Unknown A).\n  Proof.\n    intros A.\n    rewrite /back_cast_ar. iIntros (ei' K' v v' fs) \"(#Hfs & #Hvv' & #Hei' & Hv')\".\n    asimpl. wp_head.\n    iMod (step_pure _ ei' K'\n                    (Cast v' ⋆ ⋆)\n                    v' with \"[Hv']\") as \"Hv'\". intros. eapply IdStar. by simpl. auto.\n    iSplitR. done. done. asimpl. wp_value. iExists v'. iSplitL. done. done.\n  Qed.\n\nEnd compat_cast_identity.\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/identity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.27024872702915137}}
{"text": "(** * LogRel.Fundamental: declarative typing implies the logical relation for any generic instance. *)\nFrom LogRel.AutoSubst Require Import core unscoped Ast Extra.\nFrom LogRel Require Import Utils BasicAst Notations Context NormalForms Weakening\n  DeclarativeTyping DeclarativeInstance GenericTyping LogicalRelation Validity.\nFrom LogRel.LogicalRelation Require Import Escape Irrelevance Reflexivity Transitivity Universe Weakening Neutral Induction NormalRed.\nFrom LogRel.Substitution Require Import Irrelevance Properties Conversion Reflexivity SingleSubst Escape.\nFrom LogRel.Substitution.Introductions Require Import Application Universe Pi Lambda Var Nat Empty SimpleArr.\n\nSet Primitive Projections.\nSet Universe Polymorphism.\nSet Polymorphic Inductive Cumulativity.\nSet Printing Primitive Projection Parameters.\n\n(** ** Definitions *)\n\n(** These records bundle together all the validity data: they do not only say that the\nrelevant relation holds, but also that all its boundaries hold as well. For instance,\nFundTm tells that not only the term is valid at a given type, but also that this type is\nitself valid, and that the context is as well. This is needed because the definition of\nlater validity relations depends on earlier ones, and makes using the fundamental lemma\neasier, because we can simply invoke it to get all the validity properties we need. *)\n\nDefinition FundCon `{GenericTypingProperties}\n  (Γ : context) : Type := [||-v Γ ].\n\nModule FundTy.\n  Record FundTy `{GenericTypingProperties} {Γ : context} {A : term}\n  : Type := {\n    VΓ : [||-v Γ ];\n    VA : [ Γ ||-v< one > A | VΓ ]\n  }.\n\n  Arguments FundTy {_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _}.\nEnd FundTy.\n\nExport FundTy(FundTy,Build_FundTy).\n\nModule FundTyEq.\n  Record FundTyEq `{GenericTypingProperties}\n    {Γ : context} {A B : term}\n  : Type := {\n    VΓ : [||-v Γ ];\n    VA : [ Γ ||-v< one > A | VΓ ];\n    VB : [ Γ ||-v< one > B | VΓ ];\n    VAB : [ Γ ||-v< one > A ≅ B | VΓ | VA ]\n  }.\n  Arguments FundTyEq {_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _}.\nEnd FundTyEq.\n\nExport FundTyEq(FundTyEq,Build_FundTyEq).\n\nModule FundTm.\n  Record FundTm `{GenericTypingProperties}\n    {Γ : context} {A t : term}\n  : Type := {\n    VΓ : [||-v Γ ];\n    VA : [ Γ ||-v< one > A | VΓ ];\n    Vt : [ Γ ||-v< one > t : A | VΓ | VA ];\n  }.\n  Arguments FundTm {_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _}.\nEnd FundTm.\n\nExport FundTm(FundTm,Build_FundTm).\n\nModule FundTmEq.\n  Record FundTmEq `{GenericTypingProperties}\n    {Γ : context} {A t u : term}\n  : Type := {\n    VΓ : [||-v Γ ];\n    VA : [ Γ ||-v< one > A | VΓ ];\n    Vt : [ Γ ||-v< one > t : A | VΓ | VA ];\n    Vu : [ Γ ||-v< one > u : A | VΓ | VA ];\n    Vtu : [ Γ ||-v< one > t ≅ u : A | VΓ | VA ];\n  }.\n  Arguments FundTmEq {_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _}.\nEnd FundTmEq.\n\nExport FundTmEq(FundTmEq,Build_FundTmEq).\n\nModule FundSubst.\n  Record FundSubst `{GenericTypingProperties}\n    {Γ Δ : context} {wfΓ : [|- Γ]} {σ : nat -> term}\n  : Type := {\n    VΔ : [||-v Δ ] ;\n    Vσ : [VΔ | Γ ||-v σ : Δ | wfΓ] ;\n  }.\n  Arguments FundSubst {_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _}.\nEnd FundSubst.\n\nExport FundSubst(FundSubst,Build_FundSubst).\n\nModule FundSubstConv.\n  Record FundSubstConv `{GenericTypingProperties}\n    {Γ Δ : context} {wfΓ : [|- Γ]} {σ σ' : nat -> term}\n  : Type := {\n    VΔ : [||-v Δ ] ;\n    Vσ : [VΔ | Γ ||-v σ : Δ | wfΓ] ;\n    Vσ' : [VΔ | Γ ||-v σ' : Δ | wfΓ ] ;\n    Veq : [VΔ | Γ ||-v σ ≅ σ' : Δ | wfΓ | Vσ] ;\n  }.\n  Arguments FundSubstConv {_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _}.\nEnd FundSubstConv.\n\nExport FundSubstConv(FundSubstConv,Build_FundSubstConv).\n\n(** ** The main proof *)\n\n(** Each cases of the fundamental lemma is proven separately, and the final proof simply\nbrings them all together. *)\n\nSection Fundamental.\n  (** We need to have in scope both the declarative instance and a generic one, which we use\n  for the logical relation. *)\n  Context `{GenericTypingProperties}.\n  Import DeclarativeTypingData.\n\n  Lemma FundConNil : FundCon ε.\n  Proof.\n  unshelve econstructor.\n  + unshelve econstructor.\n    - intros; exact unit.\n    - intros; exact unit.\n  + constructor.\n  Qed.\n\n  Lemma FundConCons (Γ : context) (A : term)\n  (wfΓ : [ |-[ de ] Γ]) (fΓ : FundCon Γ) (tA : [Γ |-[ de ] A]) (fA : FundTy Γ A) : FundCon (Γ,, A).\n  Proof.\n    destruct fA as [ VΓ VA ].\n    eapply validSnoc. exact VA.\n  Qed.\n\n  Lemma FundTyU (Γ : context) (tΓ : [ |-[ de ] Γ]) (fΓ : FundCon Γ) : FundTy Γ U.\n  Proof.\n    unshelve econstructor.\n    - assumption.\n    - unshelve econstructor.\n      + intros * _. apply LRU_.  \n        econstructor; tea; [constructor|]. \n        cbn; eapply redtywf_refl; gen_typing.\n      + intros * _ _. simpl. constructor.\n        cbn; eapply redtywf_refl; gen_typing.\n  Qed.\n\n  Lemma FundTyPi (Γ : context) (F G : term)\n    (tF : [Γ |-[ de ] F]) (fF : FundTy Γ F)\n    (tG : [Γ,, F |-[ de ] G]) (fG : FundTy (Γ,, F) G)\n    : FundTy Γ (tProd F G).\n  Proof.\n    destruct fF as [ VΓ VF ]. destruct fG as [ VΓF VG ].\n    econstructor.\n    unshelve eapply (PiValid VΓ).\n    - assumption.\n    - now eapply irrelevanceValidity.\n  Qed.\n\n  Lemma FundTyUniv (Γ : context) (A : term)\n    (tA : [Γ |-[ de ] A : U]) (fA : FundTm Γ U A)\n    : FundTy Γ A.\n  Proof.\n    destruct fA as [ VΓ VU [ RA RAext ] ]. econstructor.\n    unshelve econstructor.\n    - intros * vσ.\n      eapply UnivEq. exact (RA _ _ wfΔ vσ).\n    - intros * vσ' vσσ'.\n      eapply UnivEqEq. exact (RAext _ _ _ wfΔ vσ vσ' vσσ').\n  Qed.\n\n  Lemma FundTmVar : forall (Γ : context) (n : nat) decl,\n    [ |-[ de ] Γ] -> FundCon Γ ->\n    in_ctx Γ n decl -> FundTm Γ decl (tRel n).\n  Proof.\n    intros Γ n d wfΓ FΓ hin; induction hin;\n      destruct (invValiditySnoc FΓ) as [l [VΓ [VA _]]]; clear FΓ.\n    - renToWk; rewrite <- (wk1_ren_on Γ d d).\n      eexists _ _; unshelve eapply var0Valid; tea.\n      now eapply embValidTyOne.\n    - renToWk; rewrite <- (wk1_ren_on Γ d' d).\n      destruct (IHhin (boundary_ctx_ctx wfΓ) VΓ); cbn in *.\n      econstructor. set (ρ := wk1 _).\n      replace (tRel _) with (tRel n)⟨ρ⟩ by (unfold ρ; now bsimpl).\n      unshelve eapply wk1ValidTm; cycle 1; tea; now eapply irrelevanceValidity.\n  Qed.\n\n  Lemma FundTmProd : forall (Γ : context) (A B : term),\n    [Γ |-[ de ] A : U] -> FundTm Γ U A ->\n    [Γ,, A |-[ de ] B : U] ->\n    FundTm (Γ,, A) U B -> FundTm Γ U (tProd A B).\n  Proof.\n    intros * ? [] ? []; econstructor.\n    eapply PiValidU; irrValid.\n    Unshelve. \n    3: eapply UValid. \n    2: eapply univValid. \n    all:tea.\n  Qed.\n\n  Lemma FundTmLambda : forall (Γ : context) (A B t : term),\n    [Γ |-[ de ] A] ->\n    FundTy Γ A ->\n    [Γ,, A |-[ de ] t : B] ->\n    FundTm (Γ,, A) B t -> FundTm Γ (tProd A B) (tLambda A t).\n  Proof.\n    intros * ?[]?[]; econstructor.\n    eapply lamValid; irrValid.\n    Unshelve. all: irrValid.\n  Qed.\n\n  Lemma FundTmApp : forall (Γ : context) (f a A B : term),\n    [Γ |-[ de ] f : tProd A B] ->\n    FundTm Γ (tProd A B) f ->\n    [Γ |-[ de ] a : A] -> FundTm Γ A a -> FundTm Γ B[a..] (tApp f a).\n  Proof.\n    intros * ?[]?[]; econstructor.\n    now eapply appValid.\n    Unshelve. all: irrValid.\n  Qed.\n\n  Lemma FundTmConv : forall (Γ : context) (t A B : term),\n    [Γ |-[ de ] t : A] -> FundTm Γ A t ->\n    [Γ |-[ de ] A ≅ B] -> FundTyEq Γ A B -> FundTm Γ B t.\n  Proof.\n    intros * ?[]?[]; econstructor. \n    eapply conv; irrValid.\n    Unshelve. all: tea.\n  Qed.\n\n  Lemma FundTyEqPiCong : forall (Γ : context) (A B C D : term),\n    [Γ |-[ de ] A ] ->\n    FundTy Γ A ->\n    [Γ |-[ de ] A ≅ B] ->\n    FundTyEq Γ A B ->\n    [Γ,, A |-[ de ] C ≅ D] ->\n    FundTyEq (Γ,, A) C D -> FundTyEq Γ (tProd A C) (tProd B D).\n  Proof.\n    intros * ?[]?[]?[]; econstructor.\n    - eapply PiValid. eapply irrelevanceLift; tea; irrValid.\n    - eapply PiCong. 1: eapply irrelevanceLift; tea.\n      all: irrValid.\n    Unshelve. all: tea; irrValid.\n  Qed.\n\n  Lemma FundTyEqRefl : forall (Γ : context) (A : term),\n    [Γ |-[ de ] A] -> FundTy Γ A -> FundTyEq Γ A A.\n  Proof.\n    intros * ?[]; unshelve econstructor; tea; now eapply reflValidTy.\n  Qed.\n\n  Lemma FundTyEqSym : forall (Γ : context) (A B : term),\n    [Γ |-[ de ] A ≅ B] -> FundTyEq Γ A B -> FundTyEq Γ B A.\n  Proof.\n    intros * ? [];  unshelve econstructor; tea.\n    now eapply symValidEq.\n  Qed.\n\n  Lemma FundTyEqTrans : forall (Γ : context) (A B C : term),\n    [Γ |-[ de ] A ≅ B] -> FundTyEq Γ A B ->\n    [Γ |-[ de ] B ≅ C] -> FundTyEq Γ B C ->\n    FundTyEq Γ A C.\n  Proof.\n    intros * ?[]?[]; unshelve econstructor; tea. 1:irrValid.\n    eapply transValidEq; irrValid.\n    Unshelve. tea.\n  Qed.\n\n  Lemma FundTyEqUniv : forall (Γ : context) (A B : term),\n    [Γ |-[ de ] A ≅ B : U] -> FundTmEq Γ U A B -> FundTyEq Γ A B.\n  Proof.\n    intros * ?[]; unshelve econstructor; tea.\n    1,2: now eapply univValid.\n    now eapply univEqValid.\n  Qed.\n\n  Lemma FundTmEqBRed : forall (Γ : context) (a t A B : term),\n    [Γ |-[ de ] A] ->\n    FundTy Γ A ->\n    [Γ,, A |-[ de ] t : B] ->\n    FundTm (Γ,, A) B t ->\n    [Γ |-[ de ] a : A] ->\n    FundTm Γ A a -> FundTmEq Γ B[a..] (tApp (tLambda A t) a) t[a..].\n  Proof.\n    intros * ?[]?[]?[]; econstructor.\n    - eapply appValid. eapply lamValid. irrValid.\n    - unshelve epose (substSTm _ _).\n      8-12: irrValid.\n      tea.\n    - unshelve epose (betaValid VA _ _ _). 2,5-7:irrValid.\n      Unshelve. all: tea; try irrValid.\n  Qed.\n\n  Lemma FundTmEqPiCong : forall (Γ : context) (A B C D : term),\n    [Γ |-[ de ] A : U] -> FundTm Γ U A ->\n    [Γ |-[ de ] A ≅ B : U] -> FundTmEq Γ U A B ->\n    [Γ,, A |-[ de ] C ≅ D : U] -> FundTmEq (Γ,, A) U C D ->\n    FundTmEq Γ U (tProd A C) (tProd B D).\n  Proof.\n    intros * ?[]?[]?[].\n    assert (VA' : [Γ ||-v<one> A | VΓ]) by now eapply univValid.\n    assert [Γ ||-v<one> A ≅ B | VΓ | VA'] by (eapply univEqValid; irrValid).\n    opector; tea.\n    - edestruct FundTmProd. 5: irrValid.\n      1,3: eapply ty_sound; now eapply escapeTm.\n      all: unshelve econstructor; irrValid.\n    - edestruct FundTmProd. 5: irrValid.\n      1,3: eapply ty_sound; eapply escapeTm; tea.\n      1: eapply irrelevanceTmLift; tea; irrValid.\n      1: unshelve econstructor; irrValid.\n      opector.\n      + eapply validSnoc; now eapply univValid.\n      + eapply irrelevanceLift; irrValid.\n      + eapply irrelevanceTmLift; irrValid.\n    - unshelve epose (PiCongTm _ _ _ _ _ _ _ _ _ _ _).\n      16: irrValid.\n      2: tea.\n      2,3,8: irrValid.\n      all: try irrValid.\n      + now eapply univValid.\n      + eapply irrelevanceLift; irrValid.\n      + eapply irrelevanceTmLift; irrValid.\n      Unshelve.\n      all: try irrValid.\n      1: unshelve eapply irrelevanceLift; cycle 3; try irrValid.\n      unshelve eapply univValid; cycle 1; try irrValid.\n  Qed.\n\n  Lemma FundTmEqAppCong : forall (Γ : context) (a b f g A B : term),\n    [Γ |-[ de ] f ≅ g : tProd A B] -> FundTmEq Γ (tProd A B) f g ->\n    [Γ |-[ de ] a ≅ b : A] -> FundTmEq Γ A a b ->\n    FundTmEq Γ B[a..] (tApp f a) (tApp g b).\n  Proof.\n    intros * ?[]?[]; econstructor.\n    - eapply appValid; irrValid.\n    - eapply conv. 2: eapply appValid; irrValid.\n      eapply substSΠeq; try irrValid.\n      1: eapply reflValidTy.\n      now eapply symValidTmEq.\n    - eapply appcongValid; irrValid.\n    Unshelve. all: irrValid.\n  Qed.\n\n  Lemma FundTmEqFunExt : forall (Γ : context) (f g A B : term),\n    [Γ |-[ de ] A] -> FundTy Γ A ->\n    [Γ |-[ de ] f : tProd A B] -> FundTm Γ (tProd A B) f ->\n    [Γ |-[ de ] g : tProd A B] -> FundTm Γ (tProd A B) g ->\n    [Γ,, A |-[ de ] tApp (f⟨↑⟩) (tRel 0) ≅ tApp (g⟨↑⟩) (tRel 0) : B] -> FundTmEq (Γ,, A) B (tApp (f⟨↑⟩) (tRel 0)) (tApp (g⟨↑⟩) (tRel 0)) ->\n    FundTmEq Γ (tProd A B) f g.\n  Proof.\n    intros * ?[]?[VΓ0 VA0]?[]?[].\n    assert [Γ ||-v< one > g : tProd A B | VΓ0 | VA0].\n    1:{\n      eapply conv. \n      2: irrValid.\n      eapply symValidEq. eapply PiCong.\n      eapply irrelevanceLift. \n      1,3,4: eapply reflValidTy.\n      irrValid.\n    }\n    econstructor. \n    3: eapply etaeqValid. \n    5: do 2 rewrite wk1_ren_on.\n    Unshelve. all: irrValid.\n  Qed.\n\n  Lemma FundTmEqRefl : forall (Γ : context) (t A : term),\n    [Γ |-[ de ] t : A] -> FundTm Γ A t ->\n    FundTmEq Γ A t t.\n  Proof.\n    intros * ?[]; econstructor; tea; now eapply reflValidTm.\n  Qed.\n\n  Lemma FundTmEqSym : forall (Γ : context) (t t' A : term),\n    [Γ |-[ de ] t ≅ t' : A] -> FundTmEq Γ A t t' ->\n    FundTmEq Γ A t' t.\n  Proof.\n    intros * ?[]; econstructor; tea; now eapply symValidTmEq.\n  Qed.\n\n  Lemma FundTmEqTrans : forall (Γ : context) (t t' t'' A : term),\n    [Γ |-[ de ] t ≅ t' : A] -> FundTmEq Γ A t t' ->\n    [Γ |-[ de ] t' ≅ t'' : A] -> FundTmEq Γ A t' t'' ->\n    FundTmEq Γ A t t''.\n  Proof.\n    intros * ?[]?[]; econstructor; tea.\n    1: irrValid.\n    eapply transValidTmEq; irrValid.\n  Qed.\n\n  Lemma FundTmEqConv : forall (Γ : context) (t t' A B : term),\n    [Γ |-[ de ] t ≅ t' : A] -> FundTmEq Γ A t t' ->\n    [Γ |-[ de ] A ≅ B] -> FundTyEq Γ A B ->\n    FundTmEq Γ B t t'.\n  Proof.\n    intros * ?[]?[]; econstructor.\n    1,2: eapply conv; irrValid.\n    eapply convEq; irrValid.\n    Unshelve. all: irrValid.\n  Qed.\n\n  Lemma FundTyNat : forall Γ : context, [ |-[ de ] Γ] -> FundCon Γ -> FundTy Γ tNat.\n  Proof.\n    intros ???; unshelve econstructor; tea;  eapply natValid.\n  Qed.\n\n  Lemma FundTmNat : forall Γ : context, [ |-[ de ] Γ] -> FundCon Γ -> FundTm Γ U tNat.\n  Proof.\n    intros ???; unshelve econstructor; tea.\n    2: eapply natTermValid.\n  Qed.\n\n  Lemma FundTmZero : forall Γ : context, [ |-[ de ] Γ] -> FundCon Γ -> FundTm Γ tNat tZero.\n  Proof.\n    intros; unshelve econstructor; tea. \n    2:eapply zeroValid.\n  Qed.\n\n  Lemma FundTmSucc : forall (Γ : context) (n : term),\n    [Γ |-[ de ] n : tNat] -> FundTm Γ tNat n -> FundTm Γ tNat (tSucc n).\n  Proof.\n    intros * ?[]; unshelve econstructor; tea.\n    eapply irrelevanceTm; eapply succValid; irrValid.\n    Unshelve. tea.\n  Qed.\n\n  Lemma FundTmNatElim : forall (Γ : context) (P hz hs n : term),\n    [Γ,, tNat |-[ de ] P] ->\n    FundTy (Γ,, tNat) P ->\n    [Γ |-[ de ] hz : P[tZero..]] ->\n    FundTm Γ P[tZero..] hz ->\n    [Γ |-[ de ] hs : elimSuccHypTy P] ->\n    FundTm Γ (elimSuccHypTy P) hs ->\n    [Γ |-[ de ] n : tNat] ->\n    FundTm Γ tNat n -> FundTm Γ P[n..] (tNatElim P hz hs n).\n  Proof.\n    intros * ?[]?[]?[]?[]; unshelve econstructor; tea.\n    2: eapply natElimValid; irrValid.\n    Unshelve. all: irrValid.\n  Qed.\n\n  Lemma FundTyEmpty : forall Γ : context, [ |-[ de ] Γ] -> FundCon Γ -> FundTy Γ tEmpty.\n  Proof.\n    intros ???; unshelve econstructor; tea;  eapply emptyValid.\n  Qed.\n\n  Lemma FundTmEmpty : forall Γ : context, [ |-[ de ] Γ] -> FundCon Γ -> FundTm Γ U tEmpty.\n  Proof.\n    intros ???; unshelve econstructor; tea.\n    2: eapply emptyTermValid.\n  Qed.\n\n  Lemma FundTmEmptyElim : forall (Γ : context) (P n : term),\n    [Γ,, tEmpty |-[ de ] P] ->\n    FundTy (Γ,, tEmpty) P ->\n    [Γ |-[ de ] n : tEmpty] ->\n    FundTm Γ tEmpty n -> FundTm Γ P[n..] (tEmptyElim P n).\n  Proof.\n    intros * ?[]?[]; unshelve econstructor; tea.\n    2: eapply emptyElimValid; irrValid.\n    Unshelve. 1,2: irrValid. \n  Qed.\n\n  Lemma FundTmEqSuccCong : forall (Γ : context) (n n' : term),\n    [Γ |-[ de ] n ≅ n' : tNat] ->\n    FundTmEq Γ tNat n n' -> FundTmEq Γ tNat (tSucc n) (tSucc n').\n  Proof.\n    intros * ?[]; unshelve econstructor; tea.\n    1,2: eapply irrelevanceTm; eapply succValid; irrValid.\n    eapply irrelevanceTmEq; eapply succcongValid; irrValid.\n    Unshelve. all: tea.\n  Qed.\n\n  Lemma FundTmEqNatElimCong : forall (Γ : context)\n      (P P' hz hz' hs hs' n n' : term),\n    [Γ,, tNat |-[ de ] P ≅ P'] ->\n    FundTyEq (Γ,, tNat) P P' ->\n    [Γ |-[ de ] hz ≅ hz' : P[tZero..]] ->\n    FundTmEq Γ P[tZero..] hz hz' ->\n    [Γ |-[ de ] hs ≅ hs' : elimSuccHypTy P] ->\n    FundTmEq Γ (elimSuccHypTy P) hs hs' ->\n    [Γ |-[ de ] n ≅ n' : tNat] ->\n    FundTmEq Γ tNat n n' ->\n    FundTmEq Γ P[n..] (tNatElim P hz hs n) (tNatElim P' hz' hs' n').\n  Proof.\n    intros * ?[? VP0 VP0']?[VΓ0]?[]?[].\n    pose (VN := natValid (l:=one) VΓ0).\n    assert (VP' : [ _ ||-v<one> P' | validSnoc VΓ0 VN]) by irrValid. \n    assert [Γ ||-v< one > hz' : P'[tZero..] | VΓ0 | substS VP' (zeroValid VΓ0)]. 1:{\n      eapply conv. 2: irrValid.\n      eapply substSEq. 2,3: irrValid.\n      1: eapply reflValidTy.\n      2: eapply reflValidTm.\n      all: eapply zeroValid.\n    }\n    assert [Γ ||-v< one > hs' : elimSuccHypTy P' | VΓ0 | elimSuccHypTyValid VΓ0 VP']. 1:{\n      eapply conv. 2: irrValid.\n      eapply elimSuccHypTyCongValid; irrValid.\n    } \n    unshelve econstructor; tea.\n    2: eapply natElimValid; irrValid.\n    + eapply conv.\n      2: eapply irrelevanceTm; now eapply natElimValid.\n      eapply symValidEq. \n      eapply substSEq; tea. \n      2,3: irrValid.\n      eapply reflValidTy.\n    + eapply natElimCongValid; tea; try irrValid.\n    Unshelve. all: try irrValid.\n    1: eapply zeroValid.\n    1: unshelve eapply substS; try irrValid.\n  Qed.\n\n  Lemma FundTmEqNatElimZero : forall (Γ : context) (P hz hs : term),\n    [Γ,, tNat |-[ de ] P] ->\n    FundTy (Γ,, tNat) P ->\n    [Γ |-[ de ] hz : P[tZero..]] ->\n    FundTm Γ P[tZero..] hz ->\n    [Γ |-[ de ] hs : elimSuccHypTy P] ->\n    FundTm Γ (elimSuccHypTy P) hs ->\n    FundTmEq Γ P[tZero..] (tNatElim P hz hs tZero) hz.\n  Proof.\n    intros * ?[]?[]?[]; unshelve econstructor; tea.\n    3: irrValid.\n    3: eapply natElimZeroValid; irrValid.\n    eapply natElimValid; irrValid.\n    Unshelve. irrValid.\n  Qed.\n\n  Lemma FundTmEqNatElimSucc : forall (Γ : context) (P hz hs n : term),\n    [Γ,, tNat |-[ de ] P] ->\n    FundTy (Γ,, tNat) P ->\n    [Γ |-[ de ] hz : P[tZero..]] ->\n    FundTm Γ P[tZero..] hz ->\n    [Γ |-[ de ] hs : elimSuccHypTy P] ->\n    FundTm Γ (elimSuccHypTy P) hs ->\n    [Γ |-[ de ] n : tNat] ->\n    FundTm Γ tNat n ->\n    FundTmEq Γ P[(tSucc n)..] (tNatElim P hz hs (tSucc n))\n      (tApp (tApp hs n) (tNatElim P hz hs n)).\n  Proof.\n    intros * ?[]?[]?[]?[]; unshelve econstructor; tea.\n    4: eapply natElimSuccValid; irrValid.\n    1: eapply natElimValid; irrValid.\n    eapply simple_appValid.\n    2: eapply natElimValid; irrValid.\n    eapply irrelevanceTm'.\n    2: now eapply appValid.\n    now bsimpl.\n    Unshelve. all: try irrValid.\n    eapply simpleArrValid; eapply substS; tea.\n    1,2: irrValid.\n    eapply succValid; irrValid.\n  Qed.\n\n  Lemma FundTmEqEmptyElimCong : forall (Γ : context)\n      (P P' n n' : term),\n    [Γ,, tEmpty |-[ de ] P ≅ P'] ->\n    FundTyEq (Γ,, tEmpty) P P' ->\n    [Γ |-[ de ] n ≅ n' : tEmpty] ->\n    FundTmEq Γ tEmpty n n' ->\n    FundTmEq Γ P[n..] (tEmptyElim P n) (tEmptyElim P' n').\n  Proof.\n    intros * ?[? VP0 VP0']?[VΓ0].\n    pose (VN := emptyValid (l:=one) VΓ0).\n    assert (VP' : [ _ ||-v<one> P' | validSnoc VΓ0 VN]) by irrValid.\n    unshelve econstructor; tea.\n    2: eapply emptyElimValid; irrValid.\n    + eapply conv.\n      2: eapply irrelevanceTm; now eapply emptyElimValid.\n      eapply symValidEq.\n      eapply substSEq; tea.\n      2,3: irrValid.\n      eapply reflValidTy.\n    + eapply emptyElimCongValid; tea; try irrValid.\n    Unshelve. all: try irrValid.\n    1: unshelve eapply substS; try irrValid.\n  Qed.\n\nLemma Fundamental : (forall Γ : context, [ |-[ de ] Γ ] -> FundCon (ta := ta) Γ)\n    × (forall (Γ : context) (A : term), [Γ |-[ de ] A] -> FundTy (ta := ta) Γ A)\n    × (forall (Γ : context) (A t : term), [Γ |-[ de ] t : A] -> FundTm (ta := ta) Γ A t)\n    × (forall (Γ : context) (A B : term), [Γ |-[ de ] A ≅ B] -> FundTyEq (ta := ta) Γ A B)\n    × (forall (Γ : context) (A t u : term), [Γ |-[ de ] t ≅ u : A] -> FundTmEq (ta := ta) Γ A t u).\n  Proof.\n  apply WfDeclInduction.\n  + apply FundConNil.\n  + apply FundConCons.\n  + apply FundTyU.\n  + apply FundTyPi.\n  + apply FundTyNat.\n  + apply FundTyEmpty.\n  + apply FundTyUniv.\n  + apply FundTmVar.\n  + apply FundTmProd.\n  + apply FundTmLambda.\n  + apply FundTmApp.\n  + apply FundTmNat.\n  + apply FundTmZero.\n  + apply FundTmSucc.\n  + apply FundTmNatElim.\n  + apply FundTmEmpty.\n  + apply FundTmEmptyElim.\n  + apply FundTmConv.\n  + apply FundTyEqPiCong.\n  + apply FundTyEqRefl.\n  + apply FundTyEqUniv.\n  + apply FundTyEqSym.\n  + apply FundTyEqTrans.\n  + apply FundTmEqBRed.\n  + apply FundTmEqPiCong.\n  + apply FundTmEqAppCong.\n  + apply FundTmEqFunExt.\n  + apply FundTmEqSuccCong.\n  + apply FundTmEqNatElimCong.\n  + apply FundTmEqNatElimZero.\n  + apply FundTmEqNatElimSucc.\n  + apply FundTmEqEmptyElimCong.\n  + apply FundTmEqRefl.\n  + apply FundTmEqConv.\n  + apply FundTmEqSym.\n  + apply FundTmEqTrans.\n  Qed.\n\n(** ** Well-typed substitutions are also valid *)\n\n  Corollary Fundamental_subst Γ Δ σ (wfΓ : [|-[ta] Γ ]) :\n    [|-[de] Δ] ->\n    [Γ |-[de]s σ : Δ] ->\n    FundSubst Γ Δ wfΓ σ.\n  Proof.\n    intros HΔ.\n    induction 1 as [|σ Δ A Hσ IH Hσ0].\n    - exists validEmpty.\n      now constructor.\n    - inversion HΔ as [|?? HΔ' HA] ; subst ; clear HΔ ; refold.\n      destruct IH ; tea.\n      apply Fundamental in Hσ0 as [?? Hσ0].\n      cbn in *.\n      eapply reducibleTm in Hσ0.\n      eapply Fundamental in HA as [].\n      unshelve econstructor.\n      1: now eapply validSnoc.\n      unshelve econstructor.\n      + now eapply irrelevanceSubst.\n      + cbn; irrelevance0.\n        2: eassumption.\n        reflexivity.\n  Qed.\n\n  Corollary Fundamental_subst_conv Γ Δ σ σ' (wfΓ : [|-[ta] Γ ]) :\n    [|-[de] Δ] ->\n    [Γ |-[de]s σ ≅ σ' : Δ] ->\n    FundSubstConv Γ Δ wfΓ σ σ'.\n  Proof.\n    intros HΔ.\n    induction 1 as [|σ τ Δ A Hσ IH Hσ0].\n    - unshelve econstructor.\n      1: eapply validEmpty.\n      all: now econstructor.\n    - inversion HΔ as [|?? HΔ' HA] ; subst ; clear HΔ ; refold.\n      destruct IH ; tea.\n      apply Fundamental in Hσ0 as [?? Hσ0 Hτ0 Ηστ] ; cbn in *.\n      eapply Fundamental in HA as [? HA].\n      unshelve econstructor.\n      + now eapply validSnoc.\n      + unshelve econstructor.\n        1: now irrValid.\n        cbn.\n        irrelevanceRefl.\n        now eapply reducibleTm.\n      + unshelve econstructor.\n        1: now eapply irrelevanceSubst.\n        cbn.\n        unshelve irrelevanceRefl.\n        2: now unshelve eapply HA ; tea ; irrValid.\n        cbn.\n        unshelve eapply LRTmRedConv.\n        3: now eapply reducibleTy.\n        * irrelevanceRefl.\n          unshelve eapply HA ; tea.\n          all: now irrValid.\n        * irrelevanceRefl.\n          now eapply reducibleTm.\n      + unshelve econstructor ; cbn in *.\n        * now irrValid.\n        * irrelevanceRefl.\n          now eapply reducibleTmEq.\n  Qed.\n\nEnd Fundamental.\n", "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/Fundamental.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.27024872028474856}}
{"text": "From Undecidability Require Import Synthetic.DecidabilityFacts Synthetic.SemiDecidabilityFacts Synthetic.EnumerabilityFacts Synthetic.ListEnumerabilityFacts reductions partial embed_nat ReducibilityFacts truthtables.\nRequire Import Setoid Program Lia List.\n\nAxiom φ : nat -> nat -> option nat.\n\nAxiom EAB : forall p, enumerable p <-> exists c, enumerator (φ c) p.\n\nDefinition W c x := exists n, φ c n = Some x.\n\nLemma W_spec : forall p, enumerable p <-> exists c, forall x, p x <-> W c x.\nProof.\n  eapply EAB.\nQed.\n\nLemma do_EA p : enumerable p -> exists c, forall x, p x <-> W c x.\nProof.\n  eapply W_spec.\nQed.\n\nAxiom s : nat -> nat -> nat.\n\nAxiom SMN : forall c x y, W (s c x) y <-> W c ⟨x,y⟩.\n\nDefinition EAs := exists φ, forall p : nat -> nat -> Prop, enumerable (fun! ⟨x,y⟩ => p x y) ->\n                                        exists c : nat -> nat, forall x, enumerator (φ (c x)) (p x).\n\nLemma EAS' :\n  forall p : nat -> nat -> Prop, enumerable (fun! ⟨x,y⟩ => p x y) ->\n                                        exists c : nat -> nat, forall x y, W (c x) y <-> p x y.\nProof.\n  intros p Hp.\n  destruct (do_EA _ Hp) as [c Hc].\n  exists (fun x => s c x). intros x y.\n  now rewrite SMN, <- Hc, embedP.\nQed.\n\nLemma EAS :\n  forall p : nat -> nat -> Prop, enumerable (uncurry p) ->\n                                        exists c : nat -> nat, forall x y, W (c x) y <-> p x y.\nProof.\n  intros p Hp. eapply EAS'.\n  eapply enumerable_red. 4: exact Hp.\n  exists (fun! ⟨x,y⟩ => (x,y)).\n  - intros xy. now destruct (unembed xy) as [x y].\n  - eauto.\n  - now eapply discrete_prod; eapply discrete_nat.\nQed.\n\nLemma EAS_datatype X (p : X -> nat -> Prop) (x0 : X) :\n  datatype X ->\n  enumerable (uncurry p) ->\n  exists c : X -> nat, forall x y, W (c x) y <-> p x y.\nProof.\n  intros (I & R & HIR) Ep.\n  destruct (EAS (fun x y => if R x is Some l then p l y else p x0 y)) as [c Hc].\n  - eapply enumerable_red.\n    4: eapply Ep.\n    + exists (fun '(x, y) => if R x is Some l then (l,y) else (x0, y)).\n      intros [x y]. cbn.\n      destruct (R x); reflexivity.\n    + eauto.\n    + eapply discrete_prod. eapply datatype_discrete. now exists I, R.\n      eapply discrete_nat.\n  - exists (fun l => c (I l)). intros. now rewrite Hc, HIR.\nQed.\n\nLemma EAS_list (p : list nat -> nat -> Prop) : enumerable (uncurry p) ->\n                                      exists c : list nat -> nat, forall x y, W (c x) y <-> p x y.\nProof.\n  intros. eapply EAS_datatype; eauto.\n  - exact nil.\n  - eapply enumerable_discrete_datatype.\n    eapply discrete_list, discrete_nat.\n    eauto. \nQed.\n\nLemma List_id : exists c_l, forall (l : list nat), forall x, W (c_l l) x <-> List.In x l.\nProof.\n  eapply EAS_list.\n  eapply decidable_enumerable. 2:eauto.\n  eapply decidable_iff. econstructor.\n  intros [x y]. cbn. exact _. \nQed.\n\nNotation π1 := (fun! ⟨x, y⟩ => x).\nNotation π2 := (fun! ⟨x, y⟩ => y).\n\nLemma enumerable_W : enumerable (fun '(x, y) => W x y).\nProof.\n  exists (fun p => let (n,m) := unembed p in if φ n m is Some m then Some (n, m) else None).\n  intros [n m].\n  split.\n  - intros H.\n    cbv in H. destruct H as [n' H].\n    exists (embed (n, n')). rewrite embedP. cbn. now rewrite H.\n  - unfold W.\n    intros [p H].\n    destruct (unembed p) as [n' m'].\n    exists m'.\n    destruct (φ n' m') eqn:E; inversion H; now subst.\nQed.\n\nLemma W_maximal (p : nat -> Prop) :\n  enumerable p -> p ⪯ₘ uncurry W.\nProof.\n  intros Hp.\n  destruct (do_EA p Hp) as [c Hc].\n  exists (fun x => (c, x)). exact Hc.\nQed.\n\nLemma SMN' : forall f, exists k, forall c x, W (k c) x <-> W c (f x).\nProof.\n  intros f.\n  eapply EAS.\n  eapply enumerable_red with (q := uncurry W).\n  - exists (fun '(x,y) => (x, f y)). now intros [x y].\n  - eauto.\n  - eapply discrete_prod; now eapply discrete_nat.\n  - eapply enumerable_W.\nQed.\n\nLemma TT : \n  forall f : nat -> { Q : list nat & truthtable}, \n    exists c : list nat -> nat, forall l x, W (c l) x <-> eval_tt (projT2 (f x)) (List.map (fun x => negb (inb (uncurry Nat.eqb) x l)) (projT1 (f x))) = false.\nProof.\n  intros f.\n  eapply EAS_list.\n  eapply decidable_enumerable. 2:eauto.\n  eapply decidable_iff. econstructor.\n  intros [x y]. cbn. exact _. \nQed.\n\n\nTactic Notation \"intros\" \"⟨\" ident(n) \",\" ident(m) \"⟩\" :=\n  let nm := fresh \"nm\" in\n  let E := fresh \"E\" in\n  intros nm; destruct (unembed nm) as [n m] eqn:E.\n\nLemma EAS_datatype_direct X (p : X -> nat -> Prop) (x0 : X) :\n  datatype X ->\n  enumerable (uncurry p) ->\n  exists c : X -> nat, forall x y, W (c x) y <-> p x y.\nProof.\n  intros (I & R & (R' & HIR) % (retraction_to_tight _ _ _) ) Hp.\n  assert (enumerable (fun! ⟨n,m⟩ => if R' n is Some x then p x m else False)). {\n    destruct Hp as [e He].\n    exists (fun n => if e n is Some (x, m) then Some ⟨I x, m⟩ else None).\n    intros ⟨n,m⟩.\n    split.\n    - destruct (R' n) eqn:ER; [ intros [n' H] % (He (_,_)) | intros []].\n      exists n'. rewrite H. f_equal.\n      rewrite <- embedP. rewrite unembedP.\n      rewrite <- (@unembedP nm), E. repeat f_equal. now eapply HIR.\n    - intros [n' H]. destruct (e n') as [ [x m'] | ] eqn:E2; try congruence.\n      inv H. rewrite embedP in E. inv E. destruct (HIR x) as [-> _].\n      eapply (He (_,_)). eauto.\n  }\n\n  destruct (do_EA _ H) as [c Hc].\n  exists (fun x => s c (I x)).\n  intros x y.\n  rewrite SMN, <- Hc, embedP.\n  now destruct (HIR x) as [-> _].\nQed.\n\nDefinition K0 c := W c c.\n\nLemma K0_not_enumerable : ~ enumerable (compl K0).\nProof.\n  intros [c Hc] % do_EA. specialize (Hc c).\n  unfold K0, compl in Hc. tauto.\nQed.\n\nLemma W_uncurry_red:\n  (fun! ⟨ n, m ⟩ => W n m) ⪯ₘ uncurry W.\nProof.\n  exists (fun! ⟨n,m⟩ => (n,m)). intros nm. destruct (unembed nm) as [n m]. reflexivity.\nQed.\n\nLemma K0_red:\n  K0 ⪯ₘ uncurry W.\nProof.\n  exists (fun n => (n,n)). intros n. reflexivity.\nQed.\n\nLemma W_uncurry_red':\n  uncurry W ⪯ₘ (fun! ⟨ n, m ⟩ => W n m).\nProof.\n  exists (fun '(n,m) => ⟨n,m⟩). intros [n m]. now rewrite embedP.\nQed.\n\nHint Resolve discrete_prod discrete_nat : core.\n\nLemma W_not_enumerable : ~ enumerable (compl (uncurry W)).\nProof.\n  eapply not_coenumerable; eauto.\n  - eapply K0_red.\n  - eapply K0_not_enumerable. \nQed.\n\nLemma K0_enum : enumerable K0.\nProof.\n  eapply enumerable_red with (q := uncurry W).\n  eapply K0_red. all:eauto.\n  eapply enumerable_W.\nQed.\n\nLemma red_tt_not_red_m :\n  compl K0 ⪯ₜₜ K0 /\\ ~ compl K0 ⪯ₘ K0.\nProof.\n  split.\n  - eapply red_tt_complement.\n  - intros H % enumerable_red.\n    + now eapply K0_not_enumerable.\n    + eauto.\n    + eapply discrete_nat.\n    + eapply K0_enum.\nQed.\n\nNotation \"m-complete p\" := (forall q : nat -> Prop, enumerable q -> q ⪯ₘ p) (at level 10).\n\nLemma m_complete_W :\n  m-complete (fun! ⟨n,m⟩ =>  W n m).\nProof.\n  intros q [c Hc] % do_EA.\n  exists (fun x => ⟨c,x⟩). intros x.\n  now rewrite embedP.\nQed.\n\nLemma enum_iff (p : nat -> Prop) : enumerable p <-> semi_decidable p.\nProof.\n  split.\n  - intros H. eapply enumerable_semi_decidable. eapply discrete_nat. eassumption.\n  - intros H. eapply semi_decidable_enumerable. eauto. eauto.\nQed.\n\nLemma generative_W :   generative (fun! ⟨ n, m ⟩ => W n m).\nProof.\n  eapply unbounded_generative. intros x y; destruct (PeanoNat.Nat.eq_dec x y); eauto.\n  destruct (do_EA (fun _ => True)) as [c_top H_top]. {\n    eapply decidable_enumerable. 2:eauto. exists (fun _ => true). firstorder.\n  }\n  intros n. exists (map (fun m => ⟨c_top,m⟩) (seq 0 n)). split.\n  now rewrite map_length, seq_length. split.\n  eapply NoDup_map. intros ? ? E % (f_equal unembed). rewrite !embedP in E. congruence. eapply seq_NoDup.\n  intros ? (? & <- & ?) % in_map_iff. rewrite embedP. firstorder.\nQed.\n", "meta": {"author": "uds-psl", "repo": "constructive-and-synthetic-reducibility-in-coq", "sha": "3bd7c2e7c311d17bb93a9edcd55e39fc1ad9aa9d", "save_path": "github-repos/coq/uds-psl-constructive-and-synthetic-reducibility-in-coq", "path": "github-repos/coq/uds-psl-constructive-and-synthetic-reducibility-in-coq/constructive-and-synthetic-reducibility-in-coq-3bd7c2e7c311d17bb93a9edcd55e39fc1ad9aa9d/Axioms/EA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.27024871354034563}}
{"text": "\n(* Mechanized proof of the preservation of consensus by the transaction flow *) \n(* The invariant established is formalized as the proposition cl *)\n\nRequire Import Logic.FunctionalExtensionality.\nRequire Import Lia.\n\nRequire Import LibTactics.\nRequire Import SfLib.\nRequire Import MyUtils. \nRequire Import Entities. \nRequire Import TransFlow. \n\nLemma eq_mp :\n  forall (mp1 mp2 : mp_tp key val),\n    (forall k, mp1 k = mp2 k) -> mp1 = mp2.\nProof. intros; apply functional_extensionality; assumption. Qed.\n\nDefinition k_step_peer_add_blk (hf : hash_func) (pid : peer_id) \n  := k_R config (step_rel_act hf (Act_peer_add_blk pid)). \n\nDefinition ep_of_epcc (epcc : chaincode_id -> option (prod endorsement_pol chaincode)) :=\n  fun (ccid : chaincode_id) =>\n    match epcc ccid with\n      Some (ep, cc) => Some ep\n    | None => None\n    end.\n\nDefinition same_ep_ledger (peers peers' : mp_tp peer_id peer_node) pid :=\n  forall pn pn', \n    peers pid = Some pn ->\n    peers' pid = Some pn' ->\n    (ep_of_epcc pn.(peer_ep_cc) = ep_of_epcc pn'.(peer_ep_cc) /\\\n     pn.(peer_ledger) = pn'.(peer_ledger)).\n\nLemma same_ep_ledger_transitive :\n  forall peers peers' peers'' pid, \n    (peers pid <> None <-> peers'' pid <> None) ->\n    same_ep_ledger peers peers'' pid ->\n    same_ep_ledger peers'' peers' pid ->\n    same_ep_ledger peers peers' pid.\nProof.\n  introv.\n  intros H_peers_peers''_none. \n  intros H_same_lgr1 H_same_lgr2. \n  unfold same_ep_ledger in *.\n  intros.\n  rewrite H in H_peers_peers''_none.\n  assert (peers'' pid <> None). \n  {\n    intro H_contra. rewrite H_contra in H_peers_peers''_none.\n    inversion H_peers_peers''_none.\n    assert (Some pn <> None) by (intro contra; inversion contra).\n    apply H1 in H3. apply H3. auto. \n  }\n  assert (exists pn'', peers'' pid = Some pn'').\n  {\n    destruct (peers'' pid). exists p. auto.\n    apply ex_falso_quodlibet. apply H1. auto. \n  }\n  inversion H2 as [pn'' H_pn''].\n  specialize (H_same_lgr1 pn pn'' H H_pn'').\n  specialize (H_same_lgr2 pn'' pn' H_pn'' H0).\n  inversion H_same_lgr1; inversion H_same_lgr2; split; congruence.   \nQed.\n\nLemma add_pmsg_preserves_ledger :\n  forall peers peers' pmsg pn_idxs pid, \n    peers' = add_pmsg_for_peers pmsg peers pn_idxs -> \n    (\n      (peers pid <> None <-> peers' pid <> None) /\\\n      (same_ep_ledger peers peers' pid)\n    ).\nProof.\n  introv.\n  intro H_peers'_peers.\n  gen peers. \n  induction pn_idxs.\n  (* base case *)\n  intros. \n  unfold add_pmsg_for_peers in H_peers'_peers.\n  simpl in  H_peers'_peers.\n  subst.\n  split.\n  intuition.\n  unfold same_ep_ledger. intros.\n  rewrite H in H0. inversion H0; subst.\n  auto. \n  (* inductive caes *)\n  intros. \n  unfold add_pmsg_for_peers in H_peers'_peers.\n  simpl in H_peers'_peers.\n  remember\n    (func_upd peer_id (option peer_node) beq_peer_id_dec peers a\n              match peers a with\n              | Some pr => Some (peer_add_trans_propose_msg pr pmsg)\n              | None => None\n              end) as peers1.\n  specialize (IHpn_idxs peers1).\n  unfold add_pmsg_for_peers in IHpn_idxs. \n  specialize (IHpn_idxs H_peers'_peers).\n  inversion IHpn_idxs as [H_peers1_peers'_none H_peers1_peers'_lgr]; \n    clear IHpn_idxs.\n  clear H_peers'_peers.\n  assert (H_first: \n            (peers pid <> None <-> peers1 pid <> None) /\\\n            (same_ep_ledger peers peers1 pid)). \n  {\n    destruct (beq_peer_id_dec a pid).\n    (* a = pid *)\n    rewrite e in Heqpeers1. \n    rewrite Heqpeers1.\n    rewrite func_upd_eq.\n    assert (H_peers_pid : (exists p, peers pid = Some p) \\/ peers pid = None).\n    {\n      destruct (peers pid).\n      left. exists p. auto.\n      right; auto. \n    }\n    inversion H_peers_pid as [H_some | H_none].\n    (* exists p, peers pid = Some p *)\n    inversion H_some as [p0 H_p0].\n    rewrite H_p0. \n    split.\n    split; (intro; intro H_neq; inversion H_neq).\n\n    (* same_ledger *)\n    unfold same_ep_ledger.\n    intros.\n    rewrite H_p0 in H.\n    inverts H. \n    rewrite func_upd_eq in H0. \n    inverts H0.\n    unfold peer_add_trans_propose_msg.\n    simpl. \n    auto.\n    (* peers pid = None *)\n    rewrite H_none.\n    split. intuition.\n    unfold same_ep_ledger.\n    introv. rewrite H_none. \n    intro H_contra. inversion H_contra. \n\n    (* a <> pid *)\n    rewrite Heqpeers1.\n    rewrite func_upd_neq; auto. \n    split. intuition.\n    unfold same_ep_ledger. intros.\n    rewrite func_upd_neq in H0; auto. \n    split; congruence; auto.\n  }\n  inversion H_first as [H_peers_peers1_none H_peers_peers1_lgr]; \n    clear H_first.\n  split.\n  intuition.\n  eapply same_ep_ledger_transitive; eauto. \n  \nQed.\n\nDefinition same_ep_ledger_in_peers (peers peers' : mp_tp peer_id peer_node) := \n  forall pid, \n    (\n      (peers pid <> None <-> peers' pid <> None) /\\\n      (same_ep_ledger peers peers' pid) \n    ).\n\nDefinition same_ep_ledger_ext (peers1 peers2 : mp_tp peer_id peer_node) pid1 pid2 :=\n  forall pn1 pn2, \n    peers1 pid1 = Some pn1 ->\n    peers2 pid2 = Some pn2 ->\n    (ep_of_epcc pn1.(peer_ep_cc) = ep_of_epcc pn2.(peer_ep_cc) /\\ \n     pn1.(peer_ledger) = pn2.(peer_ledger)). \n\nDefinition same_ep_ledger_in_peers_ext\n           (peers1 peers2 : mp_tp peer_id peer_node) pid1 pid2 :=\n    (\n      (peers1 pid1 <> None <-> peers2 pid2 <> None) /\\\n      (same_ep_ledger_ext peers1 peers2 pid1 pid2) \n    ). \n\nDefinition ord_blks_ext (os os' : ordering_service) :=  \n  forall sn,\n    os.(os_blks_created) sn <> None ->\n    os.(os_blks_created) sn = os'.(os_blks_created) sn.\n\nLemma cli_prop_step_preservation :\n  forall hf clients peers os clients' peers' os' cli_id pn_idxs, \n    step hf clients peers os clients' peers' os' (Act_cli_prop cli_id pn_idxs) -> \n    ((same_ep_ledger_in_peers peers peers') /\\ os = os'). \nProof.\n  introv. intro H_step.\n  inversion H_step.\n  rename H5 into H_peers_peers'.\n  split.\n  unfold same_ep_ledger_in_peers. intros.\n  cut ((peers pid <> None <-> peers' pid <> None) /\\\n       (same_ep_ledger peers peers' pid)). \n  intro.\n  inversion H5 as [H_same_peer_emptiness H_same_lgr].\n  auto. \n  eapply add_pmsg_preserves_ledger; eauto.\n  auto.\nQed.\n\nLemma peer_resp_step_preservation :\n  forall hf clients peers os clients' peers' os' peer_id cli_id, \n  step hf clients peers os clients' peers' os' (Act_peer_resp peer_id cli_id) ->\n  (same_ep_ledger_in_peers peers peers' /\\ os = os').\nProof.\n  intros.\n  rename H into H_step.\n  inversion H_step.\n  rename H1 into H_peers_peer_id. \n  rename H2 into H_pn_ledger.\n  rename H3 into H_pmsg.\n  rename H4 into H_tx.\n  rename H5 into H_tid.\n  rename H6 into H_ed_code. \n  rename H7 into H_op_in_lst.\n  rename H8 into H_ccode_ws. \n  rename H9 into H_rwsets.\n  rename H10 into H_prop.\n  rename H11 into H_ep_sig.\n  rename H12 into H_emsg.\n  rename H13 into H_clients. \n  rename H14 into H_clients'.\n  rename H15 into H_peers'. \n  rename H16 into H_os'_os.\n  clear H. clear H0. \n\n  split; auto. (* os' = os *)\n\n  unfold same_ep_ledger_in_peers.\n  introv.\n\n  destruct (beq_peer_id_dec pid peer_id).\n  (* pid = peer_id *)\n  split.\n  (* same peer emptiness *)\n  rewrite e in *. \n  rewrite H_peers'. rewrite mp_upd_eq.\n  rewrite H_peers_peer_id.\n  split; (intro; intro contra; inversion contra).\n  \n  (* same_ep_ledger *)\n  unfold same_ep_ledger.\n  rewrite e in *. \n  introv.\n  intros H_peers_pid H_peers'_pid. \n  rewrite H_peers' in H_peers'_pid.\n  rewrite mp_upd_eq in H_peers'_pid.\n  inversion H_peers'_pid.\n  unfold upd_peer_pmsgs in H0. \n  assert (pn = pn0) by congruence.\n  subst.\n  simpl. auto. \n  \n  (* pid <> peer_id *)\n  split.\n  (* same peer emptiness *)\n  rewrite H_peers'.\n  rewrite mp_upd_neq; auto.\n  intuition.\n\n  (* same_ep_ledger *)\n  unfold same_ep_ledger.\n  introv.\n  intros H_peers_pid H_peers'_pid. \n  rewrite H_peers' in H_peers'_pid.\n  rewrite mp_upd_neq in H_peers'_pid; auto.\n  rewrite H_peers_pid in H_peers'_pid.\n  inversion H_peers'_pid; subst.\n  auto.\n  \nQed.\n\nLemma peer_drop_prop_preservation : \n  forall hf clients peers os clients' peers' os' peer_id, \n    step hf clients peers os clients' peers' os' (Act_peer_drop_prop peer_id) -> \n    (same_ep_ledger_in_peers peers peers' /\\ os = os'). \nProof.\n  introv.\n  intro H_step.\n  inversion H_step.\n  rename H0 into H_peers_peer_id.\n  rename H1 into H_pmsgs.\n  rename H2 into H_peers'.\n  rename H3 into H_clients'.\n  rename H4 into H_os'.\n  clear H. \n\n  split; auto. (* os = os' *)\n\n  unfold same_ep_ledger_in_peers.\n  introv.\n\n  destruct (beq_peer_id_dec pid peer_id).\n  \n  (* pid = peer_id *)\n  rewrite e in *.\n  split.\n  (* same peer emptiness *)\n  rewrite H_peers'.\n  rewrite mp_upd_eq. rewrite H_peers_peer_id.\n  split; (intro; intro contra; inversion contra).\n  \n  (* same ledger *)\n  unfold same_ep_ledger.\n  introv.\n  intros H_peers_peer_id' H_peers'_peer_id. \n  rewrite H_peers_peer_id in H_peers_peer_id'.\n  inversion H_peers_peer_id'; subst. \n  rewrite mp_upd_eq in H_peers'_peer_id.\n  inversion H_peers'_peer_id.\n  unfold ep_of_epcc. simpl.\n  unfold upd_peer_pmsgs in H0.\n  rewrite <- H0 in *; simpl in *.\n  split; auto. \n  \n  (* pid <> peer_id *)\n  split.\n  rewrite H_peers'. rewrite mp_upd_neq; auto.\n  intuition.\n\n  (* same ledger *)\n  unfold same_ep_ledger.\n  introv.\n  intros H_peers_pid H_peers'_pid. \n  rewrite H_peers' in H_peers'_pid.\n  rewrite mp_upd_neq in H_peers'_pid; auto. \n  rewrite H_peers_pid in H_peers'_pid.\n  inversion H_peers'_pid; subst. \n  intuition.\nQed.\n\nLemma same_peers_impl_same_ep_lgr :\n  forall peers peers' pid, \n    peers = peers' -> same_ep_ledger peers peers' pid. \nProof.\n  unfold same_ep_ledger.\n  intros. \n  subst. rewrite H0 in H1.\n  inversion H1; subst.\n  split; auto.\nQed. \n  \nLemma same_peers_impl_same_ep_lgr_in_peers : \n  forall peers peers', \n    peers = peers' -> same_ep_ledger_in_peers peers peers'. \nProof.\n  introv.\n  intro H_peer_eq_peers'.\n  unfold same_ep_ledger_in_peers.\n  introv.\n  rewrite H_peer_eq_peers'. \n  intuition. \n  apply same_peers_impl_same_ep_lgr; auto.  \nQed.\n\nLemma cli_send_trans_preservation : \n  forall hf clients peers os clients' peers' os' cli_id, \n    step hf clients peers os clients' peers' os' (Act_cli_send_trans cli_id) -> \n    ((same_ep_ledger_in_peers peers peers') /\\ (ord_blks_ext os os')). \nProof.\n  introv.\n  intro H_step.\n  inversion H_step.\n  rename H12 into H_peers'. \n  rename H13 into H_os'.\n  \n  clear H.\n  split.\n  apply same_peers_impl_same_ep_lgr_in_peers; auto.\n  unfold ord_blks_ext.\n  introv.\n  intro H_os_blks_chid_sn_nn.\n  rewrite H_os'.\n  unfold upd_os_pending_trans.\n  simpl. auto. \nQed.\n\nLemma os_blks_ext_refl :\n  forall os, ord_blks_ext os os. \nProof. intros. unfold ord_blks_ext. intros. auto. Qed. \n  \nLemma os_eq_ext :\n  forall os1 os2, os1 = os2 -> ord_blks_ext os1 os2. \nProof. introv; intro H_os_eq; inversion H_os_eq; apply os_blks_ext_refl; auto. Qed. \n\nLemma cli_drop_prop_preservation : \n  forall hf clients peers os clients' peers' os' cli_id, \n    step hf clients peers os clients' peers' os' (Act_cli_drop_prop cli_id) -> \n    ((same_ep_ledger_in_peers peers peers') /\\ (ord_blks_ext os os')). \nProof.\n  introv.\n  intro H_step.\n  inversion H_step.\n  split; \n    [apply same_peers_impl_same_ep_lgr_in_peers; auto |\n     apply os_eq_ext; auto].\nQed. \n\nLemma os_crt_preservation : \n  forall hf clients peers os clients' peers' os', \n    step hf clients peers os clients' peers' os' (Act_ord_crt_blk) -> \n    ((same_ep_ledger_in_peers peers peers') /\\ (ord_blks_ext os os')).\nProof. \n  introv.\n  intro H_step.\n  inversion H_step.\n  rename H8 into H_os''.\n  rename H9 into H_os'.\n  split.\n  apply same_peers_impl_same_ep_lgr_in_peers; auto.\n  unfold ord_blks_ext.\n  introv.\n  intro H_os_blks_crt_nn.\n  rewrite H_os'' in H_os'.\n  unfold upd_os_pending_trans in H_os'.\n  unfold inc_os_blk_num in H_os'; simpl in H_os'.\n  unfold upd_os_last_blk_hash in H_os'; simpl in H_os'.\n  unfold os_record_new_blk in H_os'; simpl in H_os'.\n  rewrite H_os'; simpl.\n  rewrite H5. unfold blk_no. simpl.\n  rewrite H4.  \n  assert (H_sn_ne: sn <> S last_blk_no).\n  { intro H_eq. subst. apply H_os_blks_crt_nn. auto. }\n  rewrite mp_upd_neq; auto.\nQed.\n\nLemma peer_add_blk_preservation :\n  forall hf clients peers os clients' peers' os' pid1 pid2, \n    step hf clients peers os clients' peers' os' (Act_peer_add_blk pid1) ->\n    pid2 <> pid1 ->\n    (same_ep_ledger_in_peers_ext peers peers' pid2 pid2 /\\ os = os').\nProof.\n  introv.\n  intros H_step H_pids_neq.\n  inversion H_step; subst.\n  split; auto.\n  unfold same_ep_ledger_in_peers_ext.\n  rewrite mp_upd_neq; auto. \n  split. \n  split; intro; auto.\n  unfold same_ep_ledger_ext.\n  introv. intros H_peers_pid2 H_mp_upd.\n  rewrite mp_upd_neq in H_mp_upd; auto. \n  rewrite H_mp_upd in H_peers_pid2.\n  inversion H_peers_pid2; auto.\nQed.\n\nLemma peer_add_blks_preserves_os :\n  forall hf k clients peers os clients' peers' os' pid,\n    k_step_peer_add_blk hf pid k \n                        (clients, (peers, os)) (clients', (peers', os')) ->\n    os = os'.\nProof.\n  induction k.\n  intros.\n  inverts H. auto.\n  intros.\n  inverts H.\n  inverts H1.\n  inversion H as\n      [peers0 [os0 [clients'' [peers'' [os'' H_body]]]]]; clear H.\n  inversion H_body as [H_eq1 [H_eq2 H_step]]; clear H_body.\n  inversion H_eq1; subst.\n  inverts H_step.\n  fold (k_step_peer_add_blk hf pid k) in H2.\n  apply IHk in H2.\n  auto.\nQed.   \n      \nLemma some_implies_nn :\n  forall (A : Type) (x : option A) e, x = Some e -> x <> None.\nProof.\n  intros.\n  destruct x.\n  intro. inversion H0. inversion H.\nQed.\n\nLemma nn_implies_some :\n  forall (A : Type) (x : option A), x <> None -> (exists e, x = Some e).\nProof.\n  intros.\n  destruct x.\n  exists a; auto.\n  apply ex_falso_quodlibet; apply H; auto.\nQed.\n\nLemma nn_ex_1 :\n  forall (A : Type) (x1 x2 : option A) a1,\n    (x1 <> None <-> x2 <> None) ->\n    x1 = Some a1 ->\n    (exists a2, x2 = Some a2).\nProof.\n  intros.\n  apply nn_implies_some.\n  apply H.\n  eapply some_implies_nn; eauto.\nQed.\n\nLemma nn_ex_2 :\n  forall (A : Type) (x1 x2 : option A) a2,\n    (x1 <> None <-> x2 <> None) ->\n    x2 = Some a2 ->\n    (exists a1, x1 = Some a1).\nProof.\n  intros; eapply nn_ex_1; eauto; intuition. \nQed. \n\nLemma same_ep_lgr_implies :\n  forall peers peers' pid pn', \n    same_ep_ledger_in_peers peers peers' -> \n    peers' pid = Some pn' -> \n    (exists pn,\n        (peers pid = Some pn /\\\n         pn.(peer_ledger) = pn'.(peer_ledger) /\\\n         ep_of_epcc pn.(peer_ep_cc) = ep_of_epcc pn'.(peer_ep_cc))). \nProof.\n  introv. \n  intro H_same_lgr_in_peers.\n  intro H_peers'_pid.\n  unfold same_ep_ledger_in_peers in *.\n  specialize (H_same_lgr_in_peers pid).\n  inversion H_same_lgr_in_peers as [H_same_peer_emptiness H_same_lgr].\n  clear H_same_lgr_in_peers.\n  \n  assert (H_ex_pn : exists pn, peers pid = Some pn)\n    by (eapply nn_ex_2; eauto). \n  inversion H_ex_pn as [pn H_peers_pid]; clear H_ex_pn.\n  exists pn.\n  split; auto.\n  unfold same_ep_ledger in *.\n  specialize (H_same_lgr pn pn' H_peers_pid H_peers'_pid).\n  intuition. \nQed.\n\nLemma same_ep_lgr_implies_ext :\n  forall peers1 peers2 pid1 pid2 pn1, \n    same_ep_ledger_in_peers_ext peers1 peers2 pid1 pid2 -> \n    peers1 pid1 = Some pn1 -> \n    (exists pn2,\n        (peers2 pid2 = Some pn2 /\\\n         pn2.(peer_ledger) = pn1.(peer_ledger) /\\\n         ep_of_epcc pn2.(peer_ep_cc) = ep_of_epcc pn1.(peer_ep_cc))). \nProof.\n  introv.\n  intros H_same_eplgr_ext H_peers1_pid1.\n  unfold same_ep_ledger_in_peers_ext in H_same_eplgr_ext.\n  inversion H_same_eplgr_ext as [H_same_peer_emptiness H_same_lgr_ext].\n  clear H_same_eplgr_ext.\n\n  assert (H_ex_pn: exists pn, peers2 pid2 = Some pn).\n  { eapply nn_ex_1; eauto. }\n  inversion H_ex_pn as [pn2 H_peers2_pid2]; clear H_ex_pn.\n  exists pn2.\n  split; auto.\n  unfold same_ep_ledger_ext in H_same_lgr_ext.\n  specialize (H_same_lgr_ext pn1 pn2 H_peers1_pid1 H_peers2_pid2).\n  intuition. \nQed. \n\nLemma same_ep_ledger_sym :\n  forall peers1 peers2 pid, \n    same_ep_ledger peers1 peers2 pid -> same_ep_ledger peers2 peers1 pid. \nProof.\n  intros.\n  unfold same_ep_ledger in *.\n  intros.\n  specialize (H pn' pn H1 H0). \n  intuition. \nQed.\n                      \nLemma same_ledger_in_peers_sym :\n  forall peers1 peers2, \n    same_ep_ledger_in_peers peers1 peers2 -> same_ep_ledger_in_peers peers2 peers1. \nProof.\n  introv.\n  intro H_same_ledger_12.\n  unfold same_ep_ledger_in_peers in *.\n  introv.\n  specialize (H_same_ledger_12 pid).\n  inversion H_same_ledger_12 as [H_peers12 H_same_ledger]. \n  split.\n  intuition.\n  apply same_ep_ledger_sym; auto.\nQed.\n\nLemma peer_add_blk_simulate :\n  forall clients1 peers1 os1 clients1' peers1' os1' clients2 peers2 os2\n         hf peer_id, \n    same_ep_ledger_in_peers peers1 peers2 ->\n    ord_blks_ext os1 os2 ->\n    step_rel_act hf (Act_peer_add_blk peer_id)\n                 (clients1, (peers1, os1)) (clients1', (peers1', os1')) ->\n    (exists clients2' peers2' os2',\n        (\n          step_rel_act hf (Act_peer_add_blk peer_id) \n                       (clients2, (peers2, os2)) (clients2', (peers2', os2')) /\\\n          same_ep_ledger_in_peers peers1' peers2' /\\ ord_blks_ext os1' os2'\n        )\n    ).\nProof.\n  introv.\n  intros H_same_lgr H_ord_blks H_step_rel_act.\n  inversion H_step_rel_act.\n  inversion H as\n      [peers0 [os0 [clients0' [peers0' [os0' H_step_0]]]]]; clear H.\n  inversion H_step_0 as [H_eq1 [H_eq2 H_step_core]]; clear H_step_0. \n  inversion H_eq1; clear H_eq1. \n  rewrite <- H0 in *; rewrite <- H1 in *; rewrite <- H2 in *.\n  clear H0; clear H1; clear H2. \n  inversion H_eq2; clear H_eq2. \n  rewrite <- H0 in *; rewrite <- H1 in *; rewrite <- H2 in *.\n  clear H0; clear H1; clear H2.\n  inversion H_step_core.\n  clear H. \n  rename pn into pn1. \n  rename H0 into H_peers1_peer_id.\n  rename H1 into H_os_blks_1. \n  rename H2 into H_new_blk_1.\n  rename H3 into H_lgr_1.\n  rename H4 into H_last_blk_1.\n  rename H5 into H_txs_validate_1. \n  rename H6 into H_new_blk'_1.\n  rename H7 into H_clients1'.\n  rename H8 into H_peers1'.\n  rename H9 into  H_os1'.\n\n  assert (H_ex_pn_right: \n            (exists pn2,\n                (peers2 peer_id = Some pn2 /\\\n                 (pn2.(peer_ledger) = pn1.(peer_ledger) /\\\n                  ep_of_epcc pn2.(peer_ep_cc) = ep_of_epcc pn1.(peer_ep_cc))))). \n  {\n    assert (same_ep_ledger_in_peers peers2 peers1).\n    { intro. apply same_ledger_in_peers_sym; auto. }\n    eapply same_ep_lgr_implies; eauto. \n  }\n  inversion H_ex_pn_right as [pn2 [H_peers2_peer_id [H_same_peer_lgr H_same_ep]]];\n    clear H_ex_pn_right.\n\n  exists clients2.\n  exists (mp_upd Entities.peer_id peer_node beq_peer_id_dec peers2 peer_id\n                 (peer_update_ledger pn2 new_blk' wsc')). \n  exists os2.\n  split.\n  \n  (* step_rel_act on the right *)\n\n  unfold step_rel_act.\n  repeat eexists.\n  eapply Step_peer_add_block with\n      (peer_id0 := peer_id) (pn := pn2) \n      (blks := blks) (wsc := wsc) (wsc' := wsc') (new_blk := new_blk); eauto. \n  unfold ord_blks_ext in H_ord_blks.\n  rewrite <- H_os_blks_1. symmetry.\n  apply H_ord_blks.\n  eapply some_implies_nn; eauto. \n  congruence.\n\n  unfold ep_of_epcc in H_same_ep.\n  congruence. \n\n  split.\n  rewrite H_peers1'. \n  unfold same_ep_ledger_in_peers.\n  introv.\n  destruct (beq_peer_id_dec pid peer_id).\n  (* pid = peer_id *)\n  subst. unfold same_ep_ledger. \n  repeat rewrite mp_upd_eq.\n  split. split; (intro; intro H_contra; inversion H_contra).\n  intros. inversion H; subst. inversion H0; subst.\n  unfold peer_update_ledger.\n  simpl.\n  split.\n  congruence. \n  rewrite H_same_peer_lgr. auto.\n  (* pid <> peer_id *)\n  unfold peer_update_ledger; simpl.\n  split. \n  repeat (rewrite mp_upd_neq; auto).\n  apply H_same_lgr; auto.\n  unfold same_ep_ledger; simpl.\n  repeat (rewrite mp_upd_neq; auto). \n  intros. \n  unfold same_ep_ledger_in_peers in H_same_lgr.\n  assert (H_same_ep_ledger:  same_ep_ledger peers1 peers2 pid)\n    by (apply H_same_lgr; auto).\n  unfold same_ep_ledger in H_same_ep_ledger.\n  eapply H_same_ep_ledger; eauto.\n\n  (* ord_blks_ext os1' os2 chid *)\n  rewrite H_os1'. assumption.\n\nQed.\n\nLemma peer_add_blk_simulate_ext :\n  forall clients1 peers1 os1 clients1' peers1' os1' clients2 peers2 os2\n         hf pid1 pid2, \n    same_ep_ledger_in_peers_ext peers1 peers2 pid1 pid2 ->\n    ord_blks_ext os1 os2 ->\n    step_rel_act hf (Act_peer_add_blk pid1)\n                 (clients1, (peers1, os1)) (clients1', (peers1', os1')) ->\n    (exists clients2' peers2' os2',\n        (\n          step_rel_act hf (Act_peer_add_blk pid2) \n                       (clients2, (peers2, os2)) (clients2', (peers2', os2')) /\\\n          same_ep_ledger_in_peers_ext peers1' peers2' pid1 pid2 /\\ ord_blks_ext os1' os2'\n        )\n    ).\nProof.\n  introv.\n  intros H_same_eplgr_in_peers_ext H_ord_blks_ext H_step_rel_1.\n  inversion H_step_rel_1.\n  inversion H as\n      [peers0 [os0 [clients0' [peers0' [os0' H_step_0]]]]]; clear H.\n  inversion H_step_0 as [H_eq1 [H_eq2 H_step_core]]; clear H_step_0. \n  inversion H_eq1; clear H_eq1. \n  rewrite <- H0 in *; rewrite <- H1 in *; rewrite <- H2 in *.\n  clear H0; clear H1; clear H2. \n  inversion H_eq2; clear H_eq2. \n  rewrite <- H0 in *; rewrite <- H1 in *; rewrite <- H2 in *.\n  clear H0; clear H1; clear H2.\n  inversion H_step_core.\n  clear H. \n  rename pn into pn1. \n  rename H0 into H_peers1_peer_id.\n  rename H1 into H_os_blks_1. \n  rename H2 into H_new_blk_1.\n  rename H3 into H_lgr_1.\n  rename H4 into H_last_blk_1.\n  rename H5 into H_txs_validate_1. \n  rename H6 into H_new_blk'_1.\n  rename H7 into H_clients1'.\n  rename H8 into H_peers1'.\n  rename H9 into  H_os1'.\n\n  assert (H_ex_pn_right: \n            (exists pn2,\n                (peers2 pid2 = Some pn2 /\\\n                 (pn2.(peer_ledger) = pn1.(peer_ledger) /\\\n                  ep_of_epcc pn2.(peer_ep_cc) = ep_of_epcc pn1.(peer_ep_cc))))).\n  { eapply same_ep_lgr_implies_ext; eauto. }\n  \n  inversion H_ex_pn_right as [pn2 [H_peers2_peer_id [H_same_peer_lgr H_same_ep]]];\n    clear H_ex_pn_right.\n\n  exists clients2.\n  exists (mp_upd Entities.peer_id peer_node beq_peer_id_dec peers2 pid2\n                 (peer_update_ledger pn2 new_blk' wsc')). \n  exists os2.\n  split.\n  \n  (* step_rel_act on the right *)\n  unfold step_rel_act.\n  repeat eexists.\n  eapply Step_peer_add_block with\n      (peer_id0 := pid2) (pn := pn2) \n      (blks := blks) (wsc := wsc) (wsc' := wsc') (new_blk := new_blk); eauto. \n  unfold ord_blks_ext in H_ord_blks_ext.\n  rewrite <- H_os_blks_1. symmetry.\n  apply H_ord_blks_ext.\n  eapply some_implies_nn; eauto. \n  congruence.\n  unfold ep_of_epcc in H_same_ep.\n  congruence. \n\n  (* same_ep_ledger_in_peers_ext *)\n  split.\n  rewrite H_peers1'. \n  unfold same_ep_ledger_in_peers_ext.\n  repeat rewrite mp_upd_eq.\n  split.\n  (* same ledger emptiness *) \n  split; intro; intro; discriminate.\n  (* same_ep_ledger_ext *)\n  unfold same_ep_ledger_ext.\n  introv.\n  repeat rewrite mp_upd_eq.\n  intros. inversion H; subst. inversion H0; subst. clear H. clear H0. \n  unfold peer_update_ledger.\n  simpl.\n  split.\n  congruence. \n  rewrite H_same_peer_lgr. auto.\n\n  (* ord_blks_ext *)\n  rewrite H_os1'. auto.\nQed. \n\nLemma peer_add_blk_simulate_k_steps :\n  forall clients1 peers1 os1 clients1' peers1' os1' clients2 peers2 os2\n         hf peer_id k, \n    same_ep_ledger_in_peers peers1 peers2 ->\n    ord_blks_ext os1 os2 -> \n    k_step_peer_add_blk hf peer_id k \n                        (clients1, (peers1, os1)) (clients1', (peers1', os1')) -> \n    (exists clients2' peers2' os2',\n        (\n          k_step_peer_add_blk hf peer_id k \n                              (clients2, (peers2, os2)) (clients2', (peers2', os2')) /\\\n          same_ep_ledger_in_peers peers1' peers2' /\\\n          ord_blks_ext os1' os2'\n        )\n    ).\nProof.\n  intros. \n  gen clients1 peers1 os1 clients2 peers2 os2. \n  induction k. \n  (* base case *)\n  intros.\n  exists clients2. exists peers2. exists os2.\n  split.\n  econstructor; eauto. \n  inversion H1; subst.\n  split; auto.\n  (* inductive case *)\n  introv.\n  intro H_S_k_step_left.\n  introv.\n  intro H_same_ep_ledger_in_peers.\n  introv. \n  intro H_os_blks_ext. \n  inversion H_S_k_step_left.\n  clear H2. clear H3. clear x. clear x'. \n  destruct x''.\n  destruct p.\n  rename m into clients1''. rename m0 into peers1''. rename o into os1''.\n  eapply peer_add_blk_simulate with (clients2 := clients2) in H0; eauto.\n  inversion H0 as [clients2'' [peers2'' [os2'' H_body]]]; clear H0.\n  inversion H_body as\n      [H_step_rel_right [H_same_ep_lgr_in_peers'' H_ord_blks_ext'']]; \n    clear H_body.\n  eapply IHk with (clients2 := clients2'') in H_same_ep_lgr_in_peers''; eauto.\n  rename H_same_ep_lgr_in_peers'' into H_ex_sim_k_step_right.\n  inversion H_ex_sim_k_step_right as \n      [clients2' [peers2' [os2' H_body]]]; clear H_ex_sim_k_step_right.\n  inversion H_body as [H_sim_k_steps_right [H_same_ep_lgr' H_ord_blks_ext']];\n    clear H_body. \n  exists clients2'. exists peers2'. exists os2'.\n  split.\n  econstructor; eauto.\n  split; auto. \nQed.\n\nLemma peer_add_blk_simulate_k_steps_ext :\n  forall clients1 peers1 os1 clients1' peers1' os1' clients2 peers2 os2\n         hf pid1 pid2 k, \n    same_ep_ledger_in_peers_ext peers1 peers2 pid1 pid2 ->\n    ord_blks_ext os1 os2 -> \n    k_step_peer_add_blk hf pid1 k \n                        (clients1, (peers1, os1)) (clients1', (peers1', os1')) -> \n    (exists clients2' peers2' os2',\n        (\n          k_step_peer_add_blk hf pid2 k \n                              (clients2, (peers2, os2)) (clients2', (peers2', os2')) /\\\n          same_ep_ledger_in_peers_ext peers1' peers2' pid1 pid2 /\\\n          ord_blks_ext os1' os2'\n        )\n    ).\nProof.\n  intros. \n  gen clients1 peers1 os1 clients2 peers2 os2. \n  induction k. \n  (* base case *)\n  intros.\n  exists clients2. exists peers2. exists os2.\n  split.\n  econstructor; eauto. \n  inversion H1; subst.\n  split; auto.\n  (* inductive case *)\n  introv.\n  intro H_S_k_step_left.\n  introv.\n  intro H_same_ep_ledger_in_peers_ext.\n  introv. \n  intro H_os_blks_ext. \n  inversion H_S_k_step_left.\n  clear H2. clear H3. clear x. clear x'. \n  destruct x''.\n  destruct p.\n  rename m into clients1''. rename m0 into peers1''. rename o into os1''.\n  eapply peer_add_blk_simulate_ext with (clients2 := clients2) in H0; eauto.\n  inversion H0 as [clients2'' [peers2'' [os2'' H_body]]]; clear H0.\n  inversion H_body as\n      [H_step_rel_right [H_same_ep_lgr_in_peers''_ext H_ord_blks_ext'']]; \n    clear H_body.\n  eapply IHk with (clients2 := clients2'') in H_same_ep_lgr_in_peers''_ext; eauto.\n  rename H_same_ep_lgr_in_peers''_ext into H_ex_sim_k_step_right.\n  inversion H_ex_sim_k_step_right as \n      [clients2' [peers2' [os2' H_body]]]; clear H_ex_sim_k_step_right.\n  inversion H_body as [H_sim_k_steps_right [H_same_ep_lgr'_ext H_ord_blks_ext']];\n    clear H_body. \n  exists clients2'. exists peers2'. exists os2'.\n  split.\n  econstructor; eauto.\n  split; auto. \nQed.\n\nLemma step_preserves_peer_ep_cc :\n  forall hf clients peers os clients' peers' os' act pid pn pn', \n    step hf clients peers os clients' peers' os' act ->\n    peers pid = Some pn ->\n    peers' pid = Some pn' ->\n    ep_of_epcc pn.(peer_ep_cc) = ep_of_epcc pn'.(peer_ep_cc).\nProof.\n  intros.\n  inversion H.\n\n  (* cli_prop *)\n  assert (H_same_eplgr: \n      (peers pid <> None <-> peers' pid <> None) /\\\n      (same_ep_ledger peers peers' pid)\n    ).\n  { eapply add_pmsg_preserves_ledger; eauto. }\n  inversion H_same_eplgr as [H_same_nn H_same_ep_lgr];\n    clear H_same_eplgr. \n  unfold same_ep_ledger in H_same_ep_lgr. \n  specialize (H_same_ep_lgr pn pn' H0 H1).\n  inversion H_same_ep_lgr.\n  auto.\n\n  (* peer_resp *)\n  rewrite H16 in H1.\n  destruct (beq_peer_id_dec pid peer_id).\n  (* pid = peer_id *)\n  rewrite e in *.\n  rewrite mp_upd_eq in H1.\n  inversion H1; subst.\n  simpl. congruence.\n  (* pid <> peer_id *)\n  rewrite mp_upd_neq in H1. \n  congruence. intuition.\n\n  (* peer_drop_prop *)\n  rewrite H4 in H1. \n  destruct (beq_peer_id_dec pid peer_id).\n  (* pid = peer_id *)\n  rewrite e in *.\n  rewrite mp_upd_eq in H1.\n  inversion H1; subst.\n  simpl. congruence.\n  (* pid <> peer_id *)\n  rewrite mp_upd_neq in H1.\n  congruence. intuition.\n\n  (* cli_send_trans *)\n  congruence.\n\n  (* cli_drop_prop *)\n  congruence.\n\n  (* ord_crt_blk *)\n  congruence.\n\n  (* peer_add_blk *)\n  rewrite H10 in H1.\n  destruct (beq_peer_id_dec pid peer_id).\n  (* pid = peer_id *)\n  rewrite e in *.\n  rewrite mp_upd_eq in H1.\n  inversion H1; subst.\n  unfold peer_update_ledger. simpl. \n  congruence.\n  (* pid <> peer_id *)\n  rewrite mp_upd_neq in H1.\n  congruence. intuition.\n  \nQed.\n\nLemma peer_add_blk_preserve_pn_emptiness :\n  forall hf pid clients peers os clients' peers' os' pn, \n    step_rel_act hf\n                 (Act_peer_add_blk pid)\n                 (clients, (peers, os)) (clients', (peers', os')) ->\n  peers pid = Some pn -> \n  (exists pn', peers' pid = Some pn').\nProof.\n  intros.\n  inversion H; subst.\n  inversion H1 as [peers0 [os0 [clients'0 [peers'0 [os'0 H_body]]]]]; clear H1.\n  inversion H_body as [H_eq1 [H_eq2 H_step]]; clear H_body.\n  inversion H_eq1; subst. inversion H_eq2; subst.\n  inversion H_step; subst.\n  rewrite mp_upd_eq.\n  eexists; eauto.\nQed. \n\nLemma steps_preserve_peer_ep_cc :\n  forall hf pid k clients peers os clients' peers' os' pn pn', \n    k_step_peer_add_blk hf pid k (clients, (peers, os)) (clients', (peers', os')) -> \n    peers pid = Some pn ->\n    peers' pid = Some pn' -> \n    ep_of_epcc pn.(peer_ep_cc) = ep_of_epcc pn'.(peer_ep_cc).\nProof.\n  induction k.\n  intros.\n  inverts H. congruence.\n  intros.\n  inverts H.\n  remember H3 as H_step_rel.\n  clear HeqH_step_rel. \n  inverts H3.\n  fold (k_step_peer_add_blk hf pid k) in H4.\n\n  inversion H as [peers0 [os0 [clients'' [peers'' [os'' H_body]]]]]; clear H. \n  inversion H_body as [H_eq1 [H_eq2 H_step]]; clear H_body.\n  inversion H_eq1; subst.\n\n  assert (H_ex_pn'': exists pn'', peers'' pid = Some pn'').\n  { eapply peer_add_blk_preserve_pn_emptiness; eauto. }\n  inversion H_ex_pn'' as [pn'' H_peers''_pid]; clear H_ex_pn''. \n  \n  asserts_rewrite (ep_of_epcc pn.(peer_ep_cc) = ep_of_epcc pn''.(peer_ep_cc)).\n  { eapply step_preserves_peer_ep_cc; eauto. }\n  \n  eapply IHk; eauto. \nQed. \n  \nDefinition cl \n           (hf : hash_func) \n           (clients : mp_tp client_id client)\n           (peers : mp_tp peer_id peer_node)\n           (os : ordering_service) : Prop :=\n  forall pid1 pid2 pn1 pn2,\n    pid1 <> pid2 -> \n    peers pid1 = Some pn1 ->\n    peers pid2 = Some pn2 ->\n    (\n      ep_of_epcc pn1.(peer_ep_cc) = ep_of_epcc pn2.(peer_ep_cc) /\\\n      (\n        forall blks1 blks2 wsc1 wsc2, \n          (pn1.(peer_ledger) = (Ledger (BC blks1) wsc1) ->\n           pn2.(peer_ledger) = (Ledger (BC blks2) wsc2) ->\n           List.length blks1 <= List.length blks2 -> (\n             blks1 = firstn (List.length blks1) blks2 /\\\n             (exists peers' clients' os' pn1',\n                 k_step_peer_add_blk\n                   hf pid1 ((List.length blks2) - (List.length blks1))\n                   (clients, (peers, os)) (clients', (peers', os')) /\\ \n                 peers' pid1 = Some pn1' /\\\n                 pn1'.(peer_ledger) = pn2.(peer_ledger))))\n      )\n    ). \n\nLemma ledger_preserved_impl_invariant_preserved :\n  forall hf clients peers os clients' peers' os', \n    cl hf clients peers os ->\n    same_ep_ledger_in_peers peers peers' -> \n    ord_blks_ext os os' -> \n    cl hf clients' peers' os'.\nProof.\n  introv.\n  intros H_cl H_same_ep_ledger_in_peers H_ord_blks_ext.\n  unfold cl. \n  introv.\n  intros H_pid1_neq_pid2 H_peers'_pid1 H_peers'_pid2.\n\n  rename pn1 into pn1'. rename pn2 into pn2'.\n  assert (H_ex_pn: \n            (exists pn1,\n                (peers pid1 = Some pn1 /\\\n                 pn1.(peer_ledger) = pn1'.(peer_ledger) /\\\n                 ep_of_epcc (pn1.(peer_ep_cc)) = ep_of_epcc (pn1'.(peer_ep_cc))))).  \n  { eapply same_ep_lgr_implies; eauto. }\n  inversion H_ex_pn as [pn1 [H_peers_pid1 [H_eq_lgr1 H_eq_ep1]]]; clear H_ex_pn. \n\n  assert (H_ex_pn: \n            (exists pn2,\n                (peers pid2 = Some pn2 /\\\n                 pn2.(peer_ledger) = pn2'.(peer_ledger) /\\\n                 ep_of_epcc pn2.(peer_ep_cc) = ep_of_epcc pn2'.(peer_ep_cc)))). \n  { eapply same_ep_lgr_implies; eauto. } \n  inversion H_ex_pn as [pn2 [H_peers_pid2 [H_eq_lgr2 H_eq_ep2]]]; clear H_ex_pn.\n  \n  specialize (H_cl pid1 pid2 pn1 pn2 H_pid1_neq_pid2).\n  specialize (H_cl H_peers_pid1 H_peers_pid2).\n  inversion H_cl as [H_ep_cc_eq H_forall]; clear H_cl.\n  split.\n  congruence. \n\n  introv. \n  intros H_lgr1' H_lgr2' H_blk_len_lt'.\n  rename blks1 into blks1'. rename blks2 into blks2'.\n\n  rename H_forall into H_cl. \n  specialize (H_cl blks1' blks2').\n  specialize (H_cl wsc1 wsc2). \n  rewrite <- H_eq_lgr1 in H_lgr1'.\n  rewrite <- H_eq_lgr2 in H_lgr2'. \n  specialize (H_cl H_lgr1' H_lgr2'). \n  specialize (H_cl H_blk_len_lt').\n  inversion H_cl as [H_blks_prefix H_catch_up].\n  clear H_cl.\n  \n  split.\n  (* bc prefix *) \n  auto.\n  (* eventual agreement in bc and wsc *)\n  inversion H_catch_up as [peers'' [clients'' [os'' [pn1'' H_body]]]]; \n    clear H_catch_up.\n  inversion H_body as [H_k_step_from_orig [H_peers''_pid1 H_lgr'']]; \n    clear H_body. \n  \n  eapply peer_add_blk_simulate_k_steps with\n      (clients2 := clients') (peers2 := peers') (os2 := os') in H_k_step_from_orig;\n    eauto. \n  rename H_k_step_from_orig into H_sim_res.\n  inversion H_sim_res\n    as [clients''' [peers''' [os''' [H_k_steps''' [H_same_eplgr''' H_ord_ext''']]]]].\n  clear H_sim_res. \n  exists peers'''. exists clients'''. exists os'''.\n\n  unfold same_ep_ledger_in_peers in H_same_eplgr'''.\n  specialize (H_same_eplgr''' pid1). \n  inversion H_same_eplgr''' as [H_same_peer_emptiness''' H_same_ep_lgr'''];\n    clear H_same_ep_lgr'''.\n  assert (H_ex_pn''': exists pn1''', peers''' pid1 = Some pn1''').\n  { eapply nn_ex_1; eauto. }\n  inversion H_ex_pn''' as [pn1''' H_peers'''_pid1]; clear H_ex_pn'''.\n  \n  exists pn1'''. \n  split.\n  auto.\n  split.\n  auto. \n\n  assert (H_same_eplgr_final : same_ep_ledger peers'' peers''' pid1).\n  { inversion H_same_eplgr''' as [Ha Hb]; auto. }\n  unfold same_ep_ledger in H_same_eplgr_final. \n  specialize (H_same_eplgr_final pn1'' pn1''').\n  specialize (H_same_eplgr_final H_peers''_pid1 H_peers'''_pid1).\n  inversion H_same_eplgr_final as [H_ep_eq_final H_lgr_eq_final];\n    clear H_same_eplgr_final.\n  congruence.\n  \nQed.\n\nLemma blk_step_extends_bc :\n  forall hf clients peers os clients' peers' os' pid pn pn' blks blks' wsc wsc', \n    step hf clients peers os clients' peers' os' (Act_peer_add_blk pid) ->\n    peers pid = Some pn ->\n    peers' pid = Some pn' ->\n    pn.(peer_ledger) = Ledger (BC blks) wsc ->\n    pn'.(peer_ledger) = Ledger (BC blks') wsc' ->\n    exists new_blk, blks' = List.app blks (new_blk :: nil).\nProof.\n  introv.\n  intros H_step H_peers_pid H_peers'_pid H_ledger_pn H_ledger_pn'.\n  inversion H_step.\n  rename H8 into H_peers'.\n  unfold peer_update_ledger in H_peers'. simpl in H_peers'.\n  unfold upd_peer_ledger in H_peers'. simpl in H_peers'. \n  rewrite H_peers' in H_peers'_pid.\n  simpl in H_peers'_pid.\n  rewrite <- H in *.\n  rewrite mp_upd_eq in H_peers'_pid.\n  inversion H_peers'_pid; subst.\n  simpl in H_ledger_pn'.\n  rewrite H3 in H_ledger_pn'.\n  inversion H_ledger_pn'; subst.\n  assert (H_eq: pn = pn0) by congruence.\n  assert (H_eq_blks: blks = blks0) by congruence.\n  exists (Blk new_hdr new_trans_lst flags).\n  congruence.\nQed.\n\nLemma blk_step_peer_intact :\n  forall hf clients peers os clients' peers' os' pid1 pid2, \n    step hf clients peers os clients' peers' os' (Act_peer_add_blk pid1) ->\n    pid1 <> pid2 -> \n    peers' pid2 = peers pid2. \nProof.\n  introv.\n  intros H_step H_pid_neq.\n  inversion H_step; subst.\n  rewrite mp_upd_neq; auto.\nQed.\n\nLemma trans_validate_deterministic :\n  forall tx ep ws ws1 ws2 flag1 flag2, \n    trans_validate tx ep ws ws1 flag1 ->\n    trans_validate tx ep ws ws2 flag2 ->\n    (ws1 = ws2 /\\ flag1 = flag2).\nProof.   \n  introv.\n  intro H_tx_validate1.\n  intro H_tx_validate2.\n  inversion H_tx_validate1; subst.\n  inversion H_tx_validate2; subst.\n\n  (* validated on both sides *)\n  \n  inversion H; subst.\n  clear H2. clear H6. clear H1. clear H5. clear H0. clear H4. \n  split. 2: { auto. }\n  apply functional_extensionality.\n  intro k.\n  specialize (H3 k). specialize (H7 k).\n  inversion H3.\n  \n  inversion H7.\n  inversion H0; inversion H1; congruence.\n  inversion H0.\n  inversion H1.\n  inversion H5 as [vl [vl' [vr [H_wset0_k H_ws_k]]]]; clear H5.\n  rewrite H2 in H_wset0_k.\n  inversion H_wset0_k.\n  inversion H5 as [vl [vr [H_wset0_k H_rem]]]; clear H5.\n  rewrite H2 in H_wset0_k.\n  inversion H_wset0_k.\n  \n  inversion H7.\n  inversion H0.\n  inversion H2 as [vl [vl' [vr [H_wset0_k H_ws_k]]]]; clear H2.\n  inversion H1. rewrite H2 in H_wset0_k. inversion H_wset0_k.\n  inversion H2 as [vl [vr [H_wset0_k H_rem]]]; clear H2. \n  inversion H1. rewrite H2 in H_wset0_k.\n  inversion H_wset0_k.\n\n  inversion H0.\n  inversion H1.\n  inversion H2 as [vl [vl' [vr [H_wset0_k [H_ws_k H_ws1_k]]]]]; clear H2.\n  inversion H4 as [vl'' [vl''' [vr' [H_wset0_k' [H_ws_k' H_ws2_k]]]]]; clear H4.\n  rewrite H_ws_k' in H_ws_k. inversion H_ws_k; subst.\n  congruence.\n  inversion H2 as [vl [vl' [vr [H_wset0_k H_rem]]]]; clear H2.\n  inversion H4 as [vl'' [vr' [H_wset0_k' H_rem']]]; clear H4.\n  rewrite H_wset0_k in H_wset0_k'. inversion H_wset0_k'.\n  inversion H1.\n  inversion H2 as [vl [vr [H_wset0_k H_rem]]]; clear H2. \n  inversion H4 as [vl' [vl'' [vr' [H_wset0_k' [H_ws_k H_ws2_k]]]]]; clear H1.\n  rewrite H_wset0_k in H_wset0_k'.\n  inversion H_wset0_k'.\n  inversion H2 as [vl [vr [H_wset0_k [H_ws_k H_ws1_k]]]]; clear H2.\n  inversion H4 as [vl' [vr' [H_wset0_k' [H_ws_k' H_ws2_k]]]]; clear H4.\n  congruence.\n\n  (* validated on one side but not the other -- contradiction *)\n  inversion H; subst. \n  inversion H4.\n  congruence. \n  inversion H5. congruence. \n  inversion H6 as [k [vr [H_rset0_k H_all_vl]]]; clear H6.\n  specialize (H2 k vr H_rset0_k).\n  inversion H2 as [vl H_ws2_k]; clear H2.\n  specialize (H_all_vl vl). congruence.\n\n  inversion H_tx_validate2; subst.\n  inversion H; subst.\n  inversion H0.\n  congruence.\n  inversion H5.\n  congruence.\n  inversion H6 as [k [vr [H_rset0_k H_all]]]; clear H6.\n  specialize (H3 k vr H_rset0_k).\n  inversion H3 as [vl H_ws1_k]; clear H3.\n  specialize (H_all vl).\n  congruence.\n\n  (* not validated on either side *)\n  split; auto.\n  \nQed.\n\nLemma trans_lst_validate_deterministic:\n  forall trans_lst wsc wsc1 wsc2 flags1 flags2 pn, \n   trans_lst_validate trans_lst\n          (fun ccid : chaincode_id =>\n           match peer_ep_cc pn ccid with\n           | Some (a, _) => Some a | None => None\n           end) wsc wsc1 flags1 ->\n   trans_lst_validate trans_lst\n          (fun ccid : chaincode_id =>\n           match peer_ep_cc pn ccid with\n           | Some (a, _) => Some a | None => None \n           end) wsc wsc2 flags2 ->\n   (wsc1 = wsc2 /\\ flags1 = flags2).\nProof.\n  induction trans_lst.\n  (* trans_lst = [] *)\n  intros. \n  inversion H; subst.\n  inversion H0; subst. split; auto.\n\n  (* trans_lst = a :: _ *)\n  intros.\n  inversion H; subst.\n  inversion H0; subst. \n  clear H. clear H0.\n  assert (H_eq: ws = ws0) by congruence.\n  rewrite H_eq in *.\n  assert (H_eq': ed_pol = ed_pol0) by congruence.\n  rewrite H_eq' in *. \n  assert (H_conj: ws' = ws'0 /\\ flg = flg0).\n  { eapply trans_validate_deterministic; eauto. }\n  inversion H_conj as [H_ws_eq H_flg_eq].\n  clear H_conj. \n  remember (mp_upd chaincode_id world_state beq_cc_id_dec wsc (tx_ccid a) ws')\n    as mp_upd_ws'.\n  assert (H_mp_upd_ws'_eq_ws'0:\n            mp_upd_ws' =\n            mp_upd chaincode_id world_state beq_cc_id_dec wsc (tx_ccid a) ws'0). \n  { rewrite Heqmp_upd_ws'. congruence. }\n  rewrite <- H_mp_upd_ws'_eq_ws'0 in H15.\n  specialize (IHtrans_lst (mp_upd_ws') wsc1 wsc2).\n  specialize (IHtrans_lst flgs flgs0 pn). \n  specialize (IHtrans_lst H11 H15).\n  inversion IHtrans_lst. \n  split; congruence.\nQed.\n\nLemma nth_ex :\n  forall (A : Type) (lst : list A),\n    List.length lst > 0 -> \n    exists e, nth_error lst (List.length lst - 1) = Some e.\nProof.\n  induction lst. \n  intros. simpl in H. inversion H.\n  intros.\n  destruct lst.\n  simpl. exists a; auto.\n  assert (List.length (a0 :: lst) > 0).\n  simpl. lia.\n  apply IHlst in H0.\n  simpl.\n  simpl in H0.\n  asserts_rewrite (List.length lst = List.length lst - 0).\n  lia. auto.\nQed.\n\nLemma peer_blk_step_deterministic :\n  forall hf pid clients peers os clients1 peers1 os1 clients2 peers2 os2, \n    step_rel_act hf (Act_peer_add_blk pid)\n                 (clients, (peers, os)) (clients1, (peers1, os1)) ->\n    step_rel_act hf (Act_peer_add_blk pid) \n                 (clients, (peers, os)) (clients2, (peers2, os2)) ->\n    (clients1 = clients2 /\\ peers1 = peers2 /\\ os1 = os2).\nProof.\n  introv. \n  intros step_rel_act1 step_rel_act2.\n  inverts step_rel_act1.\n  inverts step_rel_act2.\n  inversion H as [peers0 [os0 [clients' [peers' [os' H_body]]]]]; clear H.\n  inversion H_body as [H_eq_conf1 [H_eq_conf2 H_step]]; clear H_body.\n  inverts H_eq_conf1.\n  inverts H_eq_conf2.\n  inversion H0 as [peers [os [clients'' [peers'' [os'' H_body]]]]]; clear H0.\n  inversion H_body as [H_eq_conf1' [H_eq_conf2' H_step']]; clear H_body. \n  inverts H_eq_conf1'.\n  inverts H_eq_conf2'. \n  inversion H_step; subst.\n  inversion H_step'; subst.\n  split. auto. split. 2: { auto. }\n  assert (H_pn_eq_pn0: pn = pn0) by congruence.\n  rewrite H_pn_eq_pn0 in *. clear H_pn_eq_pn0. \n  assert (H_wsc_eq_wsc0: wsc = wsc0) by congruence.\n  rewrite H_wsc_eq_wsc0 in *. clear H_wsc_eq_wsc0.\n  assert (H_blks_eq_blks0: blks = blks0) by congruence.\n  rewrite H_blks_eq_blks0 in *. clear H_blks_eq_blks0.  \n\n  clear H_step. clear H_step'.\n  assert (H_cases: List.length blks0 = 0 \\/ List.length blks0 > 0).\n  { destruct (List.length blks0); lia. }\n  inversion H_cases.\n  (* List.length blks0 = 0 *)\n  inversion H4. inversion H9.\n  specialize (H7 H).\n  specialize (H12 H).\n  rewrite H7 in H1. rewrite H12 in H6.\n  rewrite H1 in H6.\n  inversion H6; subst.\n  \n  assert (H_wsc_flg_eq: wsc' = wsc'0 /\\ flags = flags0).\n  { eapply trans_lst_validate_deterministic; eauto. }\n  inversion H_wsc_flg_eq.\n  congruence. \n  \n  (* length blks0 > 0 *)\n  assert (H_ex_blk':\n            exists blk', nth_error blks0 (Datatypes.length blks0 - 1) = Some blk').\n  { eapply nth_ex; eauto. }\n  inversion H_ex_blk' as [blk' H_nth_error]; clear H_ex_blk'. \n\n  inversion H4 as [H_zero H_gt_zero]; clear H4. clear H_zero. \n  specialize (H_gt_zero H). \n  specialize (H_gt_zero blk' H_nth_error).\n  inversion H_gt_zero as [H_blk_no H_blk_prev_hash]; clear H_gt_zero. \n\n  inversion H9 as [H_zero' H_gt_zero']; clear H9. clear H_zero'. \n  specialize (H_gt_zero' H).\n  specialize (H_gt_zero' blk' H_nth_error).\n  inversion H_gt_zero' as [H_blk_no' H_blk_prev_hash']; clear H_gt_zero'.\n  \n  rewrite H_blk_no in *. rewrite H_blk_no' in *.\n  rewrite H1 in H6. inversion H6; subst.\n\n  assert (H_wsc_flg_eq': wsc' = wsc'0 /\\ flags = flags0).\n  { eapply trans_lst_validate_deterministic; eauto. }\n  inversion H_wsc_flg_eq'.\n  congruence. \n\nQed.\n\nLemma peer_add_blk_ext_bc :\n  forall hf clients peers os clients' peers' os' pid pn pn' blks blks' wsc wsc',  \n    step_rel_act hf\n                 (Act_peer_add_blk pid) (clients, (peers, os))\n                 (clients', (peers', os')) -> \n    peers pid = Some pn ->\n    peers' pid = Some pn' ->\n    pn.(peer_ledger) = Ledger (BC blks) wsc -> \n    pn'.(peer_ledger) = Ledger (BC blks') wsc' ->  \n    (exists blk', List.app blks [blk'] = blks'). \nProof.\n  introv.\n  intro H_step_rel_act.\n  intros H_peers_pid H_peers'_pid H_ledger_pn H_ledger_pn'.\n  inversion H_step_rel_act; subst.\n  inversion H as\n      [peers0 [os0 [clients'0 [peers'0 [os'0 H_body]]]]]; clear H.\n  inversion H_body as [H_eq1 [H_eq2 H_step]]; clear H_body.\n  inversion H_eq1; subst.\n  inversion H_eq2; subst.\n  assert (exists blk', blks' = List.app blks [blk']).\n  { eapply blk_step_extends_bc; eauto. }\n  inversion H. exists x0. auto.\nQed. \n\nLemma peer_add_blks_preserve_pn_emptiness :\n  forall hf pid k clients peers os clients' peers' os' pn,\n    k_step_peer_add_blk hf pid k \n                        (clients, (peers, os)) (clients', (peers', os')) -> \n    peers pid = Some pn -> \n    (exists pn', peers' pid = Some pn'). \nProof.\n  induction k.\n  intros.\n  inverts H. rewrite H0. exists pn. auto.\n  intros. \n  inverts H.\n  inverts H2.\n  inversion H as [peers0 [os0 [clients'' [peers'' [os'' [H_eq1 [H_eq2 H_step]]]]]]];\n    clear H.\n  inverts H_eq1. inversion H_eq2; subst.\n  fold  (k_step_peer_add_blk hf pid k) in H3.\n  assert (H_ex1: exists pn'', peers'' pid = Some pn'').\n  {\n    eapply peer_add_blk_preserve_pn_emptiness; eauto.\n    econstructor. repeat eexists. eauto.\n  }\n  inversion H_ex1 as [pn'' H_peer''_pid]; clear H_ex1. \n  specialize (IHk clients'' peers'' os'' clients' peers' os' pn'' H3 H_peer''_pid).\n  auto.\nQed. \n\nLemma peer_add_blks_ext_bc : \n  forall hf pid k clients peers os clients' peers' os' pn pn' blks blks' wsc wsc', \n    k_step_peer_add_blk hf pid k \n                        (clients, (peers, os)) (clients', (peers', os')) -> \n    peers pid = Some pn ->\n    peers' pid = Some pn' ->\n    pn.(peer_ledger) = Ledger (BC blks) wsc -> \n    pn'.(peer_ledger) = Ledger (BC blks') wsc' ->  \n    (exists blks'', (List.length blks'' = k /\\ List.app blks blks'' = blks')).\nProof.\n  induction k.\n  (* base case *)\n  intros.\n  inversion H; subst.\n  assert (H_eq: pn = pn') by congruence.\n  assert (H_eq': blks = blks') by congruence.\n  rewrite H_eq'. \n  exists []. simpl. split; auto. autorewrite with list. auto.\n\n  (* inductive case *)\n  intros.\n  inversion H; subst.\n  destruct x'' as [clients'' [peers'' os'']].\n\n  assert (H_ex_pn'': exists pn'', peers'' pid = Some pn'').\n  { eapply peer_add_blk_preserve_pn_emptiness; eauto. }\n  inversion H_ex_pn'' as [pn'' H_pn'']; clear H_ex_pn''.\n  assert (H_ex: exists blks1 wsc1, peer_ledger pn'' = Ledger (BC blks1) wsc1).\n  { destruct (peer_ledger pn''). destruct b. repeat eexists; eauto. }\n  inversion H_ex as [blks1 [wsc1 H_pn''_ledger]]; clear H_ex. \n\n  assert (H_ex_blks'_step_1: exists blk', List.app blks [blk'] = blks1).\n  { eapply peer_add_blk_ext_bc; eauto. }\n  \n  fold (k_step_peer_add_blk hf pid) in H6.\n  specialize (IHk clients'' peers'' os'' clients' peers' os').\n  specialize (IHk pn'' pn' blks1 blks' wsc1 wsc'). \n  specialize (IHk H6 H_pn'' H1 H_pn''_ledger H3).\n  inversion IHk as [blks0 [H_len_blks0 H_ext]]; clear IHk.\n  inversion H_ex_blks'_step_1 as [blk1 H_blks1]; clear H_ex_blks'_step_1.\n  rewrite <- H_blks1 in H_ext.\n  assert (((blks ++ [blk1]) ++ blks0)%list = (blks ++ ([blk1] ++ blks0))%list).\n  { symmetry. eapply app_assoc. }\n  simpl in H4.\n\n  exists (blk1 :: blks0).\n  simpl. split; congruence.\nQed.\n\nLemma peer_add_blk_local :\n  forall hf clients peers os clients' peers' os' pid pid', \n    pid <> pid' -> \n    step hf clients peers os clients' peers' os' (Act_peer_add_blk pid) ->\n    peers pid' = peers' pid'.\nProof.\n  intros.\n  inverts H0. \n  rewrite mp_upd_neq; auto.\nQed.   \n\n\n(* proof of the main theorem *)\n\nTheorem consensus_preserved : \n  forall hf clients peers os clients' peers' os' act,\n    cl hf clients peers os ->\n    step hf clients peers os clients' peers' os' act ->\n    cl hf clients' peers' os'. \nProof. \n  introv. \n  intro H_cl.\n  intro H_step.\n  inversion H_step.\n\n  (* Act_cli_prop cli_id target_pn_idxs = act *) \n  rename H5 into H_act.\n  rewrite <- H_act in H_step.\n  assert (H_lgr_os_rel: same_ep_ledger_in_peers peers peers' /\\ os = os').\n  { eapply cli_prop_step_preservation; eauto. }\n  inversion H_lgr_os_rel as [H_lgr_rel H_os_rel].\n  assert (H_os_ext : ord_blks_ext os os'). \n  { apply os_eq_ext; auto. }\n  eapply ledger_preserved_impl_invariant_preserved; eauto. \n\n  (* Act_peer_resp peer_id cli_id = act *) \n  rename H15 into H_act.\n  rewrite <- H_act in H_step.\n  assert (H_lgr_os_rel: same_ep_ledger_in_peers peers peers' /\\ os = os'). \n  { eapply peer_resp_step_preservation; eauto. }\n  inversion H_lgr_os_rel as [H_lgr_rel H_os_rel].\n  assert (H_os_ext : ord_blks_ext os os'). \n  { apply os_eq_ext; auto. }\n  eapply ledger_preserved_impl_invariant_preserved; eauto.\n\n  (* Act_peer_drop_prop peer_id = act *) \n  rename H4 into H_act.\n  rewrite <- H_act in H_step.\n  assert (H_lgr_os_rel: same_ep_ledger_in_peers peers peers' /\\ os = os').\n  { eapply peer_drop_prop_preservation; eauto. } \n  inversion H_lgr_os_rel as [H_lgr_rel H_os_rel].\n  assert (H_os_ext : ord_blks_ext os os'). \n  { apply os_eq_ext; auto. }\n  eapply ledger_preserved_impl_invariant_preserved; eauto.\n\n  (* Act_cli_send_trans cli_id = act *) \n  rename H13 into H_act.\n  rewrite <- H_act in H_step.\n  assert (H_lgr_os_rel: same_ep_ledger_in_peers peers peers' /\\ ord_blks_ext os os').\n  { eapply cli_send_trans_preservation; eauto. }\n  inversion H_lgr_os_rel. \n  eapply ledger_preserved_impl_invariant_preserved; eauto. \n\n  (* Act_cli_drop_prop cli_id = act *)\n  rename H6 into H_act.\n  rewrite <- H_act in H_step.\n  assert (H_lgr_os_rel: same_ep_ledger_in_peers peers peers' /\\ ord_blks_ext os os'). \n  { eapply cli_drop_prop_preservation; eauto. }\n  inversion H_lgr_os_rel.\n  eapply ledger_preserved_impl_invariant_preserved; eauto.\n\n  (* Act_ord_crt_blk = act *)\n  rename H10 into H_act.\n  rewrite <- H_act in H_step.\n  assert (H_lgr_os_rel: same_ep_ledger_in_peers peers peers' /\\ ord_blks_ext os os').\n  { eapply os_crt_preservation; eauto. }\n  inversion H_lgr_os_rel.\n  eapply ledger_preserved_impl_invariant_preserved; eauto.\n\n  (* Act_peer_add_blk peer_id = act *) \n  rename H9 into H_act.\n  rewrite <- H_act in H_step.\n  \n  unfold cl.\n  introv. \n\n  rename H7 into H_peers'.\n  \n  assert (H_peer_id: peer_id = pid1 \\/ peer_id = pid2 \\/\n                     peer_id <> pid1 /\\ peer_id <> pid2).\n  {\n    destruct (beq_peer_id_dec peer_id pid1);\n      destruct (beq_peer_id_dec peer_id pid2).\n    left; intuition. left; auto. right; left; auto.\n    right; right; intuition. \n  }\n\n  inversion H_peer_id.\n  \n  (* peer_id = pid1 -- the step is taken by the first peer *) \n  rename H7 into H_peer_id_eq_pid1.\n  intros H_pid_neq H_peers'_pid1 H_peers'_pid2.\n\n  assert (H_same_ep_after_step:\n            ep_of_epcc pn.(peer_ep_cc) = ep_of_epcc pn1.(peer_ep_cc)).\n  { eapply step_preserves_peer_ep_cc; eauto. congruence. }\n  rewrite <- H_same_ep_after_step.\n  assert (H_pid2_same_pn: peers' pid2 = peers pid2).\n  { eapply blk_step_peer_intact; eauto. congruence. }\n  assert (H_peers_pid2: peers pid2 = Some pn2)\n    by congruence. \n  unfold cl in H_cl.\n  specialize (H_cl pid1 pid2 pn pn2 H_pid_neq).\n  assert (H_peers_pid1: peers pid1 = Some pn) by congruence. \n  specialize (H_cl H_peers_pid1 H_peers_pid2).\n  inversion H_cl as [H_eq_ep_cc H_forall]. split. auto.\n  clear H_cl. \n  rename H_forall into H_cl. \n\n  introv. \n  intros H_ledger_pn1 H_ledger_pn2 H_len_blks_le.\n  rename pn1 into pn1'. rename pn2 into pn2'.\n  rename blks1 into blks1'. rename blks2 into blks2'.\n  rename wsc1 into wsc1'. rename wsc2 into wsc2'. \n\n  rewrite H_peer_id_eq_pid1 in *.\n\n  assert (H_blks_extend: exists new_blk, blks1' = List.app blks (new_blk :: nil)).\n  { eapply blk_step_extends_bc; eauto. }\n  inversion H_blks_extend as [blk' H_blks1'_blks]; clear H_blks_extend.\n    \n  rename pn into pn1. rename blks into blks1. rename wsc into wsc1. \n  \n  assert (H_orig_lst_len_le: List.length blks1 <= List.length blks2').\n  {\n    rewrite H_blks1'_blks in H_len_blks_le.\n    autorewrite with list in H_len_blks_le.\n    lia. \n  }\n\n  specialize (H_cl blks1 blks2' wsc1 wsc2').\n  specialize (H_cl H2 H_ledger_pn2). \n  specialize (H_cl H_orig_lst_len_le).\n  inversion H_cl as [H_blks1_firstn H_ex]; clear H_cl.\n  inversion H_ex as [peers'' [clients'' [os'' [pn1'' H_body]]]]; clear H_ex. \n  inversion H_body as [H_k_step_orig [H_peers''_pid1 H_peer_ledger_pn1'']];\n    clear H_body.\n  \n  assert (H_len_diff_pre_post:\n            List.length blks2' - List.length blks1 =\n            S (List.length blks2' - List.length blks1')).\n  {\n    rewrite H_blks1'_blks. autorewrite with list.\n    assert (List.length blks2' >= (List.length blks1 + 1)).\n    { rewrite H_blks1'_blks in H_len_blks_le.\n      autorewrite with list in H_len_blks_le. simpl in H_len_blks_le.\n      auto with arith. }\n    simpl. lia.\n  }\n  rewrite H_len_diff_pre_post in H_k_step_orig. \n  inversion H_k_step_orig.\n  clear H11. (* x = (clients, (peers, os)) *)\n  clear H12. (* x' = (clients'', (peers'', os'')) *)\n  rename H9 into H_step_rel_act.\n  rename H10 into H_k_R.\n  fold (k_step_peer_add_blk hf pid1) in H_k_R.\n  assert (H_step_rel_act_0:\n            step_rel_act hf (Act_peer_add_blk pid1)\n                         (clients, (peers, os)) (clients', (peers', os'))).\n  { unfold step_rel_act. repeat eexists; eauto. }\n  \n  assert (H_post_eq: x'' = (clients', (peers', os'))).\n  {\n    destruct x''. destruct p.\n    assert (m = clients' /\\ m0 = peers' /\\ o = os'). \n    { eapply peer_blk_step_deterministic; eauto. }\n    inversion H9 as [H_eq1 [H_eq2 H_eq3]]; clear H9.\n    congruence. \n  }\n  rewrite H_post_eq in *.\n\n  assert (H_ex_blks'':\n            exists blks'',\n             (List.length blks'' = (Datatypes.length blks2' - Datatypes.length blks1')\n              /\\ List.app blks1' blks'' = blks2')). \n  {\n    rewrite H_ledger_pn2 in H_peer_ledger_pn1''.\n    eapply peer_add_blks_ext_bc; eauto.\n  }\n  inversion H_ex_blks'' as [blks'' [H_len_blks'' H_blks2'_blks1']]; clear H_ex_blks''.\n  split.\n  (*  blks1' = firstn (Datatypes.length blks1') blks2' *)\n  specialize (firstn_app (List.length blks1') blks1' blks'').\n  intro H_pre_firstn_eq.\n  rewrite H_blks2'_blks1' in H_pre_firstn_eq.\n  rewrite H_pre_firstn_eq.\n  asserts_rewrite (List.length blks1' - List.length blks1' = 0). lia. \n  simpl. autorewrite with list.\n  symmetry. apply firstn_all.\n  (* ability to catch up *)\n  exists peers''. exists clients''. exists os''.\n  exists pn1''.\n  split; auto. \n  \n  inversion H7.\n  (* peer_id = pid2 -- the step is taken by the second peer *)\n  \n  intros H_pid_neq H_peers'_pid1 H_peers'_pid2.\n\n  assert (H_pid1_same_pn: peers' pid1 = peers pid1). \n  { eapply blk_step_peer_intact; eauto. congruence. }\n  assert (H_peers_pid1: peers pid1 = Some pn1)\n    by congruence.\n  \n  assert (H_same_ep_after_step:\n            ep_of_epcc pn.(peer_ep_cc) = ep_of_epcc pn2.(peer_ep_cc)).\n  { eapply step_preserves_peer_ep_cc; eauto. congruence. }\n  rewrite <- H_same_ep_after_step.\n\n  assert (H_peers_pid2: peers pid2 = Some pn) by congruence.\n\n  remember H_cl as H_lgr_agreement.\n  clear HeqH_lgr_agreement. \n  unfold cl in H_lgr_agreement. \n  specialize (H_lgr_agreement pid1 pid2 pn1 pn H_pid_neq). \n  specialize (H_lgr_agreement H_peers_pid1 H_peers_pid2).\n  inversion H_lgr_agreement as [H_eq_ep_cc H_forall]. split. auto.\n  clear H_lgr_agreement. clear H_forall. \n\n  introv. \n  intros H_ledger_pn1 H_ledger_pn2 H_len_blks_le. \n  rename pn1 into pn1'. rename pn2 into pn2'.\n  rename blks1 into blks1'. rename blks2 into blks2'.\n  rename wsc1 into wsc1'. rename wsc2 into wsc2'.\n  \n  rename H9 into H_peer_id_eq_pid2. \n  rewrite H_peer_id_eq_pid2 in *.\n\n  rename pn into pn2.\n  rename blks into blks2.\n  rename wsc into wsc2.\n\n  assert (H_blks_extend: exists new_blk, blks2' = List.app blks2 (new_blk :: nil)).\n  { eapply blk_step_extends_bc; eauto. }\n  inversion H_blks_extend as [blk' H_blks2'_blks2]; clear H_blks_extend.\n\n  assert (H_orig_blks_len_cases:\n            List.length blks1' > List.length blks2 \\/\n            List.length blks1' <= List.length blks2) by lia.          \n  inversion H_orig_blks_len_cases.\n  \n  (* original blockchain for pid1 longer than original blockchain for pid2 *)\n  rename H9 into H_len_blks1'_gt_blks2.\n\n  specialize (H_cl pid2 pid1 pn2 pn1'). \n  assert (H_pid2_neq_pid1:  pid2 <> pid1) by auto with arith.\n  specialize (H_cl H_pid2_neq_pid1).\n  specialize (H_cl H H_peers_pid1).\n  inversion H_cl as [H_eq_ep H_forall]; clear H_cl.\n  rename H_forall into H_cl. \n  specialize (H_cl blks2 blks1' wsc2 wsc1').\n  specialize (H_cl H2 H_ledger_pn1).\n  assert (H_len_le: List.length blks2 <= List.length blks1') by auto with arith. \n  specialize (H_cl H_len_le). \n  inversion H_cl as [H_blks2_firstn_blks1' H_ex]; clear H_cl.\n  inversion H_ex as [peers'' [clients'' [os'' [pn'' H_body]]]]; clear H_ex.\n  inversion H_body as [H_k_step_peer_add_blk [H_peers''_pid2 H_peer_ledger_pn'']];\n    clear H_body.\n  \n  assert (H_len_diff: Datatypes.length blks1' - Datatypes.length blks2 = 1).\n  {\n    rewrite H_blks2'_blks2 in H_len_blks_le.\n    autorewrite with list in H_len_blks_le. \n    simpl in H_len_blks_le.\n    lia. \n  }\n\n  rewrite H_len_diff in H_k_step_peer_add_blk.\n  inversion H_k_step_peer_add_blk. clear H12. clear H13. \n  inversion H11. rewrite H14 in *. clear H14. \n  rename H10 into H_step_rel_act_2.\n  assert (H_step_rel_act_1:\n            step_rel_act hf (Act_peer_add_blk pid2)\n                         (clients, (peers, os)) (clients', (peers', os'))).\n  { econstructor. repeat eexists; eauto. }\n  assert (H_eq_3: clients' = clients'' /\\ peers' = peers'' /\\ os' = os'').\n  { eapply peer_blk_step_deterministic; eauto. }\n  inversion H_eq_3 as [H_eq_clients [H_eq_peers H_eq_os]]; clear H_eq_3.   \n  \n  rewrite <- H_eq_clients in *.\n  rewrite <- H_eq_peers in *.\n  rewrite <- H_eq_os in *.\n  assert (H_lgr_eq: pn1'.(peer_ledger) = pn2'.(peer_ledger))\n    by congruence. \n  assert (H_blks_eq: blks1' = blks2') by congruence. \n  split.\n  rewrite H_blks_eq. symmetry. apply firstn_all.\n  \n  exists peers'. exists clients'. exists os'. exists pn1'.\n  asserts_rewrite (List.length blks2' - List.length blks1' = 0).\n  { rewrite H_blks_eq. auto with arith. }\n  split.\n  econstructor; eauto. \n  split; auto.\n\n  rename H9 into H_len_blks1'_le_blks2. \n\n  unfold cl in H_cl.\n  \n  specialize (H_cl pid1 pid2 pn1' pn2).\n  specialize (H_cl H_pid_neq).\n  specialize (H_cl H_peers_pid1 H).\n  inversion H_cl as [H_eq_ep H_forall]; clear H_cl.\n  rename H_forall into H_cl.\n  specialize (H_cl blks1' blks2).\n  specialize (H_cl wsc1' wsc2).\n  specialize (H_cl H_ledger_pn1 H2).\n  specialize (H_cl H_len_blks1'_le_blks2).\n  inversion H_cl as [H_firstn_blks H_ex]; clear H_cl.\n  inversion H_ex as [peers'' [clients'' [os'' [pn1'' H_body]]]]; clear H_ex.\n  inversion H_body as [H_k_step [H_peers''_pid1 H_lgr_eq'']]; clear H_body.\n\n  assert (H_same_eplgr_ext:\n            same_ep_ledger_in_peers_ext peers peers' pid1 pid1 /\\ os = os'). \n  { eapply peer_add_blk_preservation; eauto. }\n  inversion H_same_eplgr_ext as [H_same_eplgr_in_peers_ext H_eq_os_os'];\n    clear H_same_eplgr_ext.\n  \n  assert (H_ord_blks_ext: ord_blks_ext os os').\n  { rewrite H_eq_os_os'. apply os_blks_ext_refl. }\n\n  assert (H''': \n    exists clients''' peers''' os''',\n      (\n        k_step_peer_add_blk hf pid1 (List.length blks2 - List.length blks1') \n                            (clients', (peers', os')) (clients''', (peers''', os''')) /\\\n        same_ep_ledger_in_peers_ext peers'' peers''' pid1 pid1 /\\\n        ord_blks_ext os'' os''')\n  ).\n  { eapply peer_add_blk_simulate_k_steps_ext; eauto. }\n  \n  inversion H''' as\n      [clients'''\n         [peers'''\n            [os''' [H_k_step_peer_add_blk''' [H_same_eplgr''' H_ord_blks_ext''']]]]];\n    clear H'''.\n\n  assert (H_same_eplgr__''': same_ep_ledger_in_peers_ext peers peers''' pid2 pid1).\n  {\n    unfold same_ep_ledger_in_peers_ext.\n    unfold same_ep_ledger_in_peers_ext in H_same_eplgr'''.\n    inversion H_same_eplgr''' as\n        [H_peers''_peers'''_pid1_same_nn H_same_eplgr_ext_''_'''_pid1];\n      clear H_same_eplgr'''.\n    assert (H_ex_pn''': exists pn''', peers''' pid1 = Some pn''').\n    { eapply peer_add_blks_preserve_pn_emptiness; eauto. }\n    inversion H_ex_pn'''. \n    assert (H_peers'''_pid1_nn: peers''' pid1 <> None).\n    { eapply some_implies_nn; eauto. }\n    assert (H_peers_pid2_nn: peers pid2 <> None).\n    { eapply some_implies_nn; eauto. }\n    split.\n    split; intro; auto.\n    unfold same_ep_ledger_ext.\n    intros pn20 pn1'''0. intros H_peers_pid2_res H_peers'''_pid1_res.\n    rewrite H in H_peers_pid2_res.\n    inversion H_peers_pid2_res. rewrite <- H11 in *.\n    unfold same_ep_ledger_ext in H_same_eplgr_ext_''_'''_pid1.\n    rewrite <- H_lgr_eq''.\n    specialize (H_same_eplgr_ext_''_'''_pid1 pn1'' pn1'''0).\n    specialize (H_same_eplgr_ext_''_'''_pid1 H_peers''_pid1 H_peers'''_pid1_res).\n    inversion H_same_eplgr_ext_''_'''_pid1 as [H_ep_eq_''_''' H_lgr_eq_''_'''];\n      clear H_same_eplgr_ext_''_'''_pid1.\n    split; auto.\n    rewrite <- H_eq_ep.\n    eapply steps_preserve_peer_ep_cc; eauto. \n  }\n  assert (H_ord_blks_ext__''': ord_blks_ext os os'''). \n  {\n    assert (os' = os''').\n    { eapply peer_add_blks_preserves_os; eauto. }\n    assert (os = os''') by congruence.\n    rewrite <- H10. \n    apply os_blks_ext_refl. \n  }\n  assert (H'''':\n            exists clients'''' peers'''' os'''',\n             step_rel_act hf (Act_peer_add_blk pid1)\n                          (clients''', (peers''', os'''))\n                          (clients'''', (peers'''', os'''')) /\\\n             same_ep_ledger_in_peers_ext peers' peers'''' pid2 pid1 /\\\n             ord_blks_ext os' os'''').\n  {\n    eapply peer_add_blk_simulate_ext; eauto. \n    econstructor. repeat eexists. eauto.\n  }\n  inversion H'''' as\n      [clients_4\n         [peers_4\n            [os_4\n               [H_step_rel_4 [H_same_eplgr_4 H_ord_blks_4]]]]]; clear H''''.\n\n  split.\n  \n  rewrite H_blks2'_blks2.\n  rewrite firstn_app.\n  asserts_rewrite (Datatypes.length blks1' - Datatypes.length blks2 = 0). \n  { lia. } \n  simpl. autorewrite with list. auto.\n\n  unfold same_ep_ledger_in_peers_ext in H_same_eplgr_4.\n  inversion H_same_eplgr_4.  \n  assert (peers' pid2 <> None) by (eapply some_implies_nn; eauto).\n  assert (peers_4 pid1 <> None) by intuition.\n  apply nn_implies_some in H12.\n  inversion H12 as [pn_4 H_peers_4_pid1]; clear H12. \n\n  exists peers_4. exists clients_4. exists os_4.\n  exists pn_4.\n  split.\n\n  assert (H_lst_len_suc:\n            List.length blks2' - List.length blks1' =\n            S (List.length blks2 - List.length blks1')).\n  {\n    rewrite H_blks2'_blks2.\n    autorewrite with list. simpl. \n    lia.\n  }\n  rewrite H_lst_len_suc.  \n  eapply k_back; eauto.\n\n  split. auto.\n\n  unfold same_ep_ledger_ext in H10.\n  specialize (H10 pn2' pn_4 H_peers'_pid2 H_peers_4_pid1).\n  inversion H10. congruence.\n\n  (* peer_id <> pid1 /\\ peer_id <> pid2 *)\n\n  inversion H9 as [H_peer_id_ne_pid1 H_peer_id_ne_pid2]; clear H9. \n\n  assert (peers pid1 = peers' pid1).\n  { eapply peer_add_blk_local; eauto. }\n  assert (peers pid2 = peers' pid2).\n  { eapply peer_add_blk_local; eauto. }\n\n  intros H_neq_pid1_pid2 H_peers'_pid1 H_peers'_pid2.\n\n  assert (H_peers_pid1: peers pid1 = Some pn1) by congruence.\n  assert (H_peers_pid2: peers pid2 = Some pn2) by congruence. \n  \n  unfold cl in H_cl.\n  specialize (H_cl pid1 pid2 pn1 pn2 H_neq_pid1_pid2).\n  specialize (H_cl H_peers_pid1 H_peers_pid2).\n\n  inversion H_cl as [H_eq_ep H_forall]; clear H_cl.\n  split. auto. \n  intros. \n  specialize (H_forall blks1 blks2 wsc1 wsc2 H11 H12 H13).\n  inversion H_forall as [H_firstn H_ex]; clear H_forall.\n  split. auto.\n  inversion H_ex as\n      [peers''\n         [clients''\n            [os''\n               [pn1'' [H_k_step_orig [H_peers''_pid1 H_peer_lgr_orig]]]]]];\n    clear H_ex.  \n  \n  eapply peer_add_blk_simulate_k_steps_ext\n    with (clients2 := clients') (peers2 := peers') (os2 := os')\n         (pid1 := pid1) (pid2 := pid1) \n    in H_k_step_orig.\n  inversion H_k_step_orig as\n      [clients''' [peers''' [os''' [H_k_step' [H_same_ep_lgr' H_ord_blks']]]]];\n    clear H_k_step_orig.\n  exists peers'''. exists clients'''. exists os'''. \n  unfold same_ep_ledger_in_peers in H_same_ep_lgr'.\n  inversion H_same_ep_lgr'.\n  assert (peers'' pid1 <> None) by (eapply some_implies_nn; eauto).\n  assert (peers''' pid1 <> None) by intuition.\n  assert (H_ex: exists pn1''', peers''' pid1 = Some pn1''')\n    by (eapply nn_implies_some; eauto).\n  inversion H_ex as [pn1''' H_peers'''_pid1]; clear H_ex.\n  exists pn1'''.\n  split. auto.\n  split. auto.\n  rewrite <- H_peer_lgr_orig.\n  unfold same_ep_ledger_in_peers_ext in H_same_ep_lgr'.\n  inversion H_same_ep_lgr'.\n  unfold same_ep_ledger_ext in H19. \n  specialize (H19 pn1'' pn1''' H_peers''_pid1 H_peers'''_pid1).\n  inversion H19; symmetry; auto.\n\n  unfold same_ep_ledger_in_peers_ext.\n  rewrite <- H9. \n  split. intuition.\n  unfold same_ep_ledger_ext.\n  intros.\n  asserts_rewrite (pn0 = pn1). congruence.\n  asserts_rewrite (pn3 = pn1). congruence.\n  split; auto.\n\n  inverts H_step. apply os_blks_ext_refl.\n\nQed. \n                  \n", "meta": {"author": "lixm", "repo": "hf-trans-flow", "sha": "f2aeab28074cc79a3596caf85802fcd1e543642e", "save_path": "github-repos/coq/lixm-hf-trans-flow", "path": "github-repos/coq/lixm-hf-trans-flow/hf-trans-flow-f2aeab28074cc79a3596caf85802fcd1e543642e/Safety.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2702463815540565}}
{"text": "Add LoadPath \"/home/user/Downloads/archives/math-comp-mathcomp-1.7.0/\".\n(*Add mathcomp \"/home/user/Downloads/archives/math-comp-mathcomp-1.7.0/mathcomp\".*)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype seq.\nFrom mathcomp Require Import ssrnat.\n\nLemma is_true_locked_true : locked true. \nProof. \nPrint locked.\nPrint master_key.\nby unlock. \nShow Proof.\nCompute ((fun evar_0_ : (fun u : unit => is_true ((let 'tt := u in id) true)) tt =>\n  match\n    master_key as u\n    return ((fun u0 : unit => is_true ((let 'tt := u0 in id) true)) u)\n  with\n  | tt => evar_0_\n  end) is_true_true).\nQed.\n\nPrint erefl.\nPrint Logic.eq_refl.\n(*Set Implicit Arguments.*)\nSection Hilb.\nVariables A B C:Prop.\nLemma HilbS : (A->B->C)->(A->B)->A->C.\nProof.\nmove=> aibic.\nmove=> aib a.\nmove: aibic.\nShow Proof.\napply.\nShow Proof.\n by [].\nShow Proof.\nby apply: aib.\nShow Proof.\nDefined.\nEval compute in (fun (aibic : A -> B -> C) (aib : A -> B) (a : A) =>\n (fun top_assumption_ : A -> B -> C =>\n  (fun evar_0_ : A => [eta top_assumption_ evar_0_]) a (aib a)) aibic).\n\n\nEnd Hilb.", "meta": {"author": "georgydunaev", "repo": "TRASH", "sha": "36b24517b8c51817e1b8eb39df945d30c287162b", "save_path": "github-repos/coq/georgydunaev-TRASH", "path": "github-repos/coq/georgydunaev-TRASH/TRASH-36b24517b8c51817e1b8eb39df945d30c287162b/mathcomp/learning.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2701785591087517}}
{"text": "Require Import Raft.\nRequire Import RaftRefinementInterface.\n\nSection RequestVoteMaxIndexMaxTerm.\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\n  Definition requestVote_maxIndex_maxTerm (net : network) : Prop :=\n    forall t h p n mi mt,\n      currentTerm (snd (nwState net h)) = t ->\n      type (snd (nwState net h)) = Candidate ->\n      In p (nwPackets net) ->\n      pBody p = RequestVote t n mi mt ->\n      pSrc p = h ->\n      maxIndex (log (snd (nwState net h))) = mi /\\\n      maxTerm (log (snd (nwState net h))) = mt.\n\n  Class requestVote_maxIndex_maxTerm_interface : Prop :=\n    {\n      requestVote_maxIndex_maxTerm_invariant :\n        forall net,\n          refined_raft_intermediate_reachable net ->\n          requestVote_maxIndex_maxTerm net\n    }.\nEnd RequestVoteMaxIndexMaxTerm.", "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/RequestVoteMaxIndexMaxTermInterface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.2701785591087517}}
{"text": "Require Export Quorum.\nRequire Export Process.\nRequire Export DTimeQ.\nRequire Export ComponentSM.\nRequire Export ComponentSM2.\nRequire Export CalculusSM_derived6.\nRequire Export CalculusSM_tacs2.\nRequire Export toString.\nRequire Export List.\n\n\n(* Contains out implementation of PBFT *)\nSection AbstractPaxos.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { dtc : @DTimeContext }.\n\n  Definition round := nat.\n  Definition round_deq := deq_nat.\n  Definition round_lt_dec := lt_dec.\n  Definition round_le_dec := le_dec.\n\n  Class Paxos_context :=\n    {\n      (* types *)\n      node   : Set;\n      value  : Set;\n      quorum : Set;\n\n      (* round numbers are simply numbers *)\n\n      (* functions *)\n      is_proposer   : node -> round -> bool;\n      forms_quorum  : list node -> bool;\n      default_value : node -> value;\n\n      (* axioms *)\n      value_deq : Deq value;\n      node_deq  : Deq node;\n\n      num_nodes;\n      node2nat : node -> nat_n num_nodes;\n      node_bij : bijective node2nat;\n\n      is_proposer_inj :\n        forall n1 n2 r,\n          is_proposer n1 r = true\n          -> is_proposer n2 r = true\n          -> n1 = n2;\n\n      quorum_intersection :\n        forall l1 l2,\n          forms_quorum l1 = true\n          -> forms_quorum l2 = true\n          -> exists n, In n l1 /\\ In n l2\n    }.\n\n  Context { pc : Paxos_context }.\n\n  Global Instance Paxos_I_Node : Node := MkNode node node_deq.\n\n  Lemma some_inj_rev :\n    forall (n : node) (m : name), Some m = Some n -> n = m.\n  Proof.\n    introv xx; ginv; auto.\n  Qed.\n\n  Lemma inj_node : injective (fun n : node => n).\n  Proof.\n    introv; tcsp.\n  Qed.\n\n  Global Instance paxos_I_Quorum : Quorum_context :=\n    MkQuorumContext\n      node\n      num_nodes\n      node_deq\n      node2nat\n      node_bij\n      (fun n => n)\n      Some\n      (fun n => eq_refl (Some n))\n      some_inj_rev\n      inj_node.\n\n  Definition nodes : list node := nodes.\n\n  Record start    := mk_start    { start_R :> round; }.\n  Record one_a    := mk_one_a    { one_a_R :> round; }.\n  Record one_b    := mk_one_b    { one_b_N : node; one_b_R : round; one_b_maxr : round; one_b_maxv : value; }.\n  Record vote     := mk_vote     { vote_N : node; vote_R : round; vote_V : value; }.\n  Record decision := mk_decision { decision_N : node; decision_R : round; decision_V : value; }.\n\n  Definition MAINname := msg_comp_name 0.\n\n  (* ******************************************* *)\n  (* *** entries hold [one_b] messages and proposed values *** *)\n  Record entry :=\n    MkEntry\n      { entry_round    : round;\n        entry_one_bs   : list one_b;\n        entry_votes    : list vote;\n        entry_proposal : option value; }.\n\n  Definition entries := list entry.\n\n  Fixpoint find_entry (r : round) (l : entries) : option entry :=\n    match l with\n    | [] => None\n    | entry :: l =>\n      if round_deq r (entry_round entry)\n      then Some entry\n      else find_entry r l\n    end.\n\n  Definition proposed_entry (e : entry) : bool :=\n    is_some (entry_proposal e).\n\n  Definition entry2one_b_nodes (e : entry) : list node :=\n    map one_b_N (entry_one_bs e).\n\n  (* gets all the nodes that voted for [v] *)\n  Definition entry2vote_nodes (v : value) (e : entry) : list node :=\n    map vote_N\n        (filter\n           (fun x => if value_deq v (vote_V x) then true else false)\n           (entry_votes e)).\n\n  Definition entry2voters (e : entry) : list node := map vote_N (entry_votes e).\n\n  (* We add [b] to the list if there's not already a message from the same node in the list *)\n  Fixpoint add_one_b_to_list (b : one_b) (l : list one_b) : list one_b :=\n    match l with\n    | [] => [b]\n    | b' :: l =>\n      if node_deq (one_b_N b) (one_b_N b') then b' :: l\n      else b' :: add_one_b_to_list b l\n    end.\n\n  Definition add_one_b_to_entry (b : one_b) (e : entry) : entry :=\n    MkEntry\n      (entry_round e)\n      (add_one_b_to_list b (entry_one_bs e))\n      (entry_votes e)\n      (entry_proposal e).\n\n  Definition upd_none {A} (o : option A) (a : A) :=\n    match o with\n    | Some _ => o\n    | None => Some a\n    end.\n\n  Fixpoint add_vote_to_list (v : vote) (l : list vote) : list vote :=\n    match l with\n    | [] => [v]\n    | v' :: l =>\n      if node_deq (vote_N v) (vote_N v') then v' :: l\n      else v' :: add_vote_to_list v l\n    end.\n\n  Definition is_vote_from_proposer (v : vote) : bool := is_proposer (vote_N v) (vote_R v).\n\n  Definition upd_proposal (vop : option value) (v : vote) : option value :=\n    if is_vote_from_proposer v\n    then upd_none vop (vote_V v)\n    else vop.\n\n  Definition add_vote_to_entry (v : vote) (e : entry) : entry :=\n    MkEntry\n      (entry_round e)\n      (entry_one_bs e)\n      (add_vote_to_list v (entry_votes e))\n      (upd_proposal (entry_proposal e) v).\n\n  Definition one_b2entry (b : one_b) : entry :=\n    MkEntry (one_b_R b) [b] [] None.\n\n  Definition vote2entry (v : vote) : entry :=\n    MkEntry (vote_R v) [] [v] (upd_proposal None v).\n\n  Fixpoint add_one_b (b : one_b) (l : entries) : entry * entries :=\n    match l with\n    | [] => let entry := one_b2entry b in (entry, [entry])\n    | entry :: entries =>\n      if round_deq (one_b_R b) (entry_round entry)\n      then\n        let entry' := add_one_b_to_entry b entry\n        in (entry', entry' :: entries)\n      else\n        let (entry', entries') := add_one_b b entries\n        in (entry', entry :: entries')\n    end.\n\n  Fixpoint add_vote (v : vote) (l : entries) : entry * entries :=\n    match l with\n    | [] => let entry := vote2entry v in (entry,[entry])\n    | entry :: entries =>\n      if round_deq (vote_R v) (entry_round entry)\n      then\n        let entry' := add_vote_to_entry v entry in\n        (entry', entry' :: entries)\n      else\n        let (entry',entries') := add_vote v entries in\n        (entry', entry :: entries')\n    end.\n\n  Fixpoint find_voted_value_from_votes (n : node) (l : list vote) : option value :=\n    match l with\n    | [] => None\n    | v :: vs =>\n      if node_deq (vote_N v) n\n      then Some (vote_V v)\n      else find_voted_value_from_votes n vs\n    end.\n\n  Fixpoint find_latest_value_from_votes (n : node) (v : value) (low high : round) (l : entries) : round * value :=\n    match l with\n    | [] => (low,v)\n    | entry :: entries =>\n      let r := entry_round entry in\n      if round_lt_dec r high then\n        if round_lt_dec low r then\n          (* we might as well pick the proposal in the entry *)\n          match find_voted_value_from_votes n (entry_votes entry) with\n          | Some v' => find_latest_value_from_votes n v' r high entries\n          | None => find_latest_value_from_votes n v low high entries\n          end\n        else find_latest_value_from_votes n v low high entries\n      else find_latest_value_from_votes n v low high entries\n    end.\n\n  Fixpoint find_voted_value_from_one_bs (v : value) (low high : round) (l : list one_b) : round * value :=\n    match l with\n    | [] => (low,v)\n    | b :: bs =>\n      let r' := one_b_maxr b in\n      let v' := one_b_maxv b in\n      if r' <? high\n      then\n        if low <? r'\n        then find_voted_value_from_one_bs v' r' high bs\n        else find_voted_value_from_one_bs v low high bs\n      else find_voted_value_from_one_bs v low high bs\n    end.\n\n  Definition vote2my slf (v : vote) : vote := mk_vote slf (vote_R v) (vote_V v).\n\n  Definition is_my_vote slf (v : vote) : bool := if node_deq slf (vote_N v) then true else false.\n\n\n  (* ******************************************* *)\n  (* *** MAIN state *** *)\n  Record MAIN_state :=\n    MkState {\n        st_current_round : round;\n        st_entries       : entries;\n      }.\n\n  Definition initial_state_at (r : round) : MAIN_state := MkState r [].\n\n  (* 0 is not used though *)\n  Definition initial_round : round := 0.\n\n  Definition initial_state : MAIN_state := initial_state_at initial_round.\n\n  Definition has_left_round (r : round) (s : MAIN_state) : bool := r <? st_current_round s.\n  Definition valid_round (r : round) : bool := initial_round <? r.\n  Definition new_round (r : round) (s : MAIN_state) : bool := st_current_round s <? r.\n  Definition same_round (r1 r2 : round) : bool := if round_deq r1 r2 then true else false.\n\n  Definition same_node (n1 n2 : node) : bool := if node_deq n1 n2 then true else false.\n\n  Definition update_last_round (r : round) (s : MAIN_state) : MAIN_state :=\n    MkState\n      (if round_lt_dec r (st_current_round s) then st_current_round s else r)\n      (st_entries s).\n\n  Definition log_one_b (b : one_b) (s : MAIN_state) : entry * MAIN_state :=\n    let (entry, entries) := add_one_b b (st_entries s) in\n    (entry, MkState (st_current_round s) entries).\n\n  Definition log_vote (v : vote) (s : MAIN_state) : entry * MAIN_state :=\n    let (entry,entries) := add_vote v (st_entries s) in\n    (entry, MkState (st_current_round s) entries).\n\n  Definition is_new_vote slf entry := if in_dec node_deq slf (entry2voters entry) then false else true.\n\n  Definition has_proposed (v : value) (e : entry) : bool :=\n    match entry_proposal e with\n    | Some v' => if value_deq v v' then true else false\n    | None => false\n    end.\n\n  (* On receipt of a vote [v], a node generates a new vote if [v] is a proposal, i.e.,\n      (1) [v] is from the proposer of the corresponding round\n      (2) We stored the vote of the proposer\n      (3) We haven't voted before\n      (4) We're not the proposer *)\n  Definition valid_my_vote slf v entry : bool :=\n    (is_vote_from_proposer v)\n      && (has_proposed (vote_V v) entry)\n      && (is_new_vote slf entry)\n      && (negb (same_node slf (vote_N v))).\n\n  Definition log_my_vote slf v entry state :=\n    if valid_my_vote slf v entry\n    then log_vote (vote2my slf v) state\n    else (entry,state).\n\n\n  (* ******************************************* *)\n  (* *** messages *** *)\n  Inductive Paxos_msg : Set :=\n  | paxos_start    (s : start)\n  | paxos_one_a    (a : one_a)\n  | paxos_one_b    (b : one_b)\n  | paxos_vote     (v : vote)\n  | paxos_decision (d : decision).\n\n  Global Instance Paxos_I_Msg : Msg := MkMsg Paxos_msg.\n\n  Definition send_one_a    (a : one_a)    (n : list name) : DirectedMsg := MkDMsg (paxos_one_a a)    n ('0).\n  Definition send_one_b    (b : one_b)    (n : list name) : DirectedMsg := MkDMsg (paxos_one_b b)    n ('0).\n  Definition send_vote     (v : vote)     (n : list name) : DirectedMsg := MkDMsg (paxos_vote v)     n ('0).\n  Definition send_decision (d : decision) (n : list name) : DirectedMsg := MkDMsg (paxos_decision d) n ('0).\n\n  Definition other_nodes (n : node) : list node := remove_elt node_deq n nodes.\n\n  Definition broadcast2others (slf : node) F : DirectedMsg := F (other_nodes slf).\n  Definition broadcast2all F : DirectedMsg := F nodes.\n\n  Definition send_my_vote (slf : node) entry (v : vote) : DirectedMsgs :=\n    if valid_my_vote slf v entry\n    then [broadcast2others slf (send_vote (vote2my slf v))]\n    else [].\n\n  Definition Paxos_msg2status (m : Paxos_msg) : msg_status :=\n    match m with\n    | paxos_start    _ => MSG_STATUS_EXTERNAL\n    | paxos_one_a    _ => MSG_STATUS_PROTOCOL\n    | paxos_one_b    _ => MSG_STATUS_PROTOCOL\n    | paxos_vote     _ => MSG_STATUS_PROTOCOL\n    | paxos_decision _ => MSG_STATUS_PROTOCOL\n    end.\n\n  Definition Paxos_msg2sender (_ : name) (m : Paxos_msg) : option name :=\n    match m with\n    | paxos_start    s => None\n    | paxos_one_a    a => None\n    | paxos_one_b    b => Some (one_b_N b)\n    | paxos_vote     v => Some (vote_N v)\n    | paxos_decision d => Some (decision_N d)\n    end.\n\n\n  (* ******************************************* *)\n  (* *** instances *** *)\n  Global Instance Paxos_I_IOTrustedFun : IOTrustedFun := MkIOTrustedFun (fun _ => MkIOTrusted unit unit tt).\n  Global Instance Paxos_I_trustedStateFun : trustedStateFun := MkTrustedStateFun (fun _ => MAIN_state).\n  Global Instance Paxos_I_Key : Key := MkKey unit unit.\n  Global Instance paxos_I_AuthTok : AuthTok := MkAuthTok unit Deq_unit.\n  Global Instance Paxos_I_MsgStatus : MsgStatus := MkMsgStatus Paxos_msg2status.\n  Global Instance Paxos_I_Data : Data := MkData Paxos_msg.\n  Global Instance Paxos_I_baseFunIO : baseFunIO := MkBaseFunIO (fun (nm : CompName) => CIOdef).\n  Global Instance Paxos_I_baseStateFun : baseStateFun :=\n    MkBaseStateFun (fun (nm : CompName) =>\n                      if CompNameKindDeq (comp_name_kind nm) msg_comp_name_kind\n                      then MAIN_state\n                      else unit).\n  Definition paxos_get_contained_auth_data (m : msg) : list AuthenticatedData := [MkAuthData m [tt]].\n  Global Instance Paxos_I_ContainedAuthData : ContainedAuthData := MkContainedAuthData paxos_get_contained_auth_data.\n  Global Instance Paxos_I_DataAuth : DataAuth := MkDataAuth Paxos_msg2sender.\n\n\n  (* ******************************************* *)\n  (* *** message handling notation *** *)\n  Definition on_start {A} (m : Paxos_msg) (d : unit -> Proc A) (f : start -> Proc A) : Proc A :=\n    match m with paxos_start s => f s | _ => d tt end.\n  Notation \"a >>os>>=( d ) f\" := (on_start a d f) (at level 80, right associativity).\n\n  Definition on_one_a {A} (m : Paxos_msg) (d : unit -> Proc A) (f : one_a -> Proc A) : Proc A :=\n    match m with paxos_one_a a => f a | _ => d tt end.\n  Notation \"a >>oa>>=( d ) f\" := (on_one_a a d f) (at level 80, right associativity).\n\n  Definition on_one_b {A} (m : Paxos_msg) (d : unit -> Proc A) (f : one_b -> Proc A) : Proc A :=\n    match m with paxos_one_b b => f b | _ => d tt end.\n  Notation \"a >>ob>>=( d ) f\" := (on_one_b a d f) (at level 80, right associativity).\n\n  Definition on_vote {A} (m : Paxos_msg) (d : unit -> Proc A) (f : vote -> Proc A) : Proc A :=\n    match m with paxos_vote v => f v | _ => d tt end.\n  Notation \"a >>ov>>=( d ) f\" := (on_vote a d f) (at level 80, right associativity).\n\n  (* ******************************************* *)\n  (* *** handlers *** *)\n  Definition handle_start (slf : node) : UProc MAINname MAIN_state :=\n    fun state m =>\n      m >>os>>=(fun _ => [R](state,[])) fun s =>\n      if negb (is_proposer slf s) then [R](state,[]) else\n      if (start_R s <=? st_current_round state) then [R](state,[]) else\n      let state1 := update_last_round s state in\n      [R](state1,[broadcast2others slf (send_one_a (mk_one_a s))]).\n\n  (* 1a are sent by proposers *)\n  Definition handle_one_a (slf : node) : UProc MAINname MAIN_state :=\n    fun state m =>\n      m >>oa>>=(fun _ => [R](state,[])) fun a =>\n      if negb (new_round a state) then [R](state,[]) else\n      let d := default_value slf in\n      (* maxv is the value to propose *)\n      let (maxr,maxv) := find_latest_value_from_votes slf d 0 a (st_entries state) in\n      let b := mk_one_b slf a maxr maxv in\n      let state1 := update_last_round a state in\n      let (entry,state2) := log_one_b b state1 in\n      [R] (state2, [broadcast2others slf (send_one_b b)]).\n\n  (* 1b are handle by proposers *)\n  Definition handle_one_b (slf : node) : UProc MAINname MAIN_state :=\n    fun state m =>\n      m >>ob>>=(fun _ => [R](state,[])) fun b =>\n      let bround := one_b_R b in\n      let cround := st_current_round state in\n      if negb (same_round bround cround) then [R](state,[]) else\n      if negb (is_proposer slf cround) then [R](state,[]) else\n      let (entry, state1) := log_one_b b state in\n      if proposed_entry entry then [R](state1,[]) else\n      let q := entry2one_b_nodes entry in\n      if negb (forms_quorum q) then [R](state1,[]) else\n      let d := default_value slf in\n      (* v is the value to propose *)\n      let (maxr,maxv) := find_voted_value_from_one_bs d 0 cround (entry_one_bs entry) in\n      let vote := mk_vote slf cround maxv in\n      let (_,state2) := log_vote vote state1 in\n      [R](state2,[broadcast2others slf (send_vote vote)]).\n\n  Definition handle_vote (slf : node) : UProc MAINname MAIN_state :=\n    fun state m =>\n      m >>ov>>=(fun _ => [R](state,[])) fun v =>\n      let round := vote_R v in\n      let val   := vote_V v in\n      if has_left_round round state then [R](state,[]) else\n      let (entry1,state1) := log_vote v state in\n      let (entry2,state2) := log_my_vote slf v entry1 state1 in\n      let q := entry2vote_nodes val entry2 in\n      if negb (forms_quorum q) then [R](state2,send_my_vote slf entry1 v) else\n      let d := mk_decision slf round (vote_V v) in\n      [R](state2, broadcast2others slf (send_decision d) :: send_my_vote slf entry1 v).\n\n  Definition handle_decision (slf : node) : UProc MAINname MAIN_state :=\n    fun state m => [R](state,[]).\n\n  Definition MAIN_update (slf : node) : M_Update 0 MAINname _ :=\n    fun (s : MAIN_state) m =>\n      interp_s_proc\n        (match m with\n         | paxos_start    _ => handle_start    slf s m\n         | paxos_one_a    _ => handle_one_a    slf s m\n         | paxos_one_b    _ => handle_one_b    slf s m\n         | paxos_vote     _ => handle_vote     slf s m\n         | paxos_decision _ => handle_decision slf s m\n         end).\n\n  Notation PaxosLS := (LocalSystem 1 0).\n\n  Definition MAIN_comp n (s : MAIN_state) : n_proc 1 MAINname := build_m_sm (MAIN_update n) s.\n  Definition PaxosLocalSys n (s : MAIN_state) : PaxosLS := [MkPProc _ (MAIN_comp n s)].\n  Definition PaxosfunLevelSpace := MkFunLevelSpace (fun _ => 1) (fun _ => 0).\n  Definition PaxosSys : M_USystem PaxosfunLevelSpace := fun n => PaxosLocalSys n initial_state.\n\n\n  (* ******************************************* *)\n  (* *** well-formedness of paxos state machines *** *)\n  Create HintDb paxos.\n  Create HintDb paxos2.\n  Hint Resolve implies_authenticated_messages_were_sent_non_byz_usys : paxos paxos2.\n  Hint Rewrite @run_process_on_list_haltedProc : paxos paxos2.\n\n  Lemma are_procs_PaxosLs : forall n s, are_procs_n_procs (PaxosLocalSys n s).\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_PaxosLs : paxos.\n\n  Lemma wf_PaxosLs : forall n s, wf_procs (PaxosLocalSys n s).\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_PaxosLs : paxos.\n\n  Lemma are_procs_PaxosSys : are_procs_sys PaxosSys.\n  Proof.\n    unfold PaxosSys; introv; simpl; eauto 3 with comp paxos.\n  Qed.\n  Hint Resolve are_procs_PaxosSys : paxos.\n\n  Lemma wf_PaxosSys : wf_sys PaxosSys.\n  Proof.\n    unfold PaxosSys; introv; simpl; eauto 3 with comp paxos.\n  Qed.\n  Hint Resolve wf_PaxosSys : paxos.\n\n  Lemma PaxosSys_preserves_subs :\n    sys_preserves_subs PaxosSys.\n  Proof.\n    introv; eauto 3 with comp paxos.\n  Qed.\n  Hint Resolve PaxosSys_preserves_subs : paxos.\n\n  Lemma sys_non_trusted_PaxosSys : sys_non_trusted PaxosSys.\n  Proof.\n    introv; simpl; tcsp.\n  Qed.\n  Hint Resolve sys_non_trusted_PaxosSys : paxos.\n\n  Lemma similar_sms_at_paxos_replica :\n    forall r s (p : n_proc 1 _),\n      similar_sms p (MAIN_comp r s)\n      -> exists s', p = MAIN_comp 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 s p,\n      similar_procs (MkPProc MAINname (MAIN_comp r s)) p\n      -> exists s', p = MkPProc MAINname (MAIN_comp r s').\n  Proof.\n    introv sim.\n    inversion sim as [? ? ? ? sims]; clear sim; subst.\n    repeat sp_exI; subst.\n    apply similar_sms_sym in sims.\n    apply similar_sms_at_paxos_replica in sims; exrepnd; subst; eauto.\n  Qed.\n\n  Lemma similar_subs_PaxosLocalSys :\n    forall r s ls,\n      similar_subs (PaxosLocalSys r s) ls\n      -> exists s', ls = PaxosLocalSys r s'.\n  Proof.\n    introv sim.\n    inversion sim; subst; simpl in *.\n    apply similar_procs_MAIN in simp; exrepnd; subst; simpl in *.\n    inversion sims; subst.\n    exists s'; dands; tcsp.\n  Qed.\n\n  Lemma similar_subs_PaxosLocalSys_implies :\n    forall n s (ls : n_procs 1),\n      similar_subs (PaxosLocalSys n s) ls\n      -> exists s', ls = PaxosLocalSys n s'.\n  Proof.\n    introv sim.\n    apply similar_subs_PaxosLocalSys in sim; exrepnd; subst; eauto.\n  Qed.\n\n  Lemma M_run_ls_before_event_ls_is_paxos :\n    forall {eo : EventOrdering}\n           (e  : Event)\n           (n  : name)\n           (s  : MAIN_state)\n           (ls : LocalSystem 1 0),\n      M_run_ls_before_event (PaxosLocalSys n s) e = Some ls\n      -> exists (s' : MAIN_state), ls = PaxosLocalSys n s'.\n  Proof.\n    introv run.\n    apply M_run_ls_before_event_preserves_subs in run; eauto 3 with comp paxos.\n    repnd; simpl in *.\n    apply similar_subs_PaxosLocalSys_implies in run2; auto.\n  Qed.\n\n  Lemma M_run_ls_on_event_ls_is_paxos :\n    forall {eo : EventOrdering}\n           (e  : Event)\n           (r  : name)\n           (s  : MAIN_state)\n           (ls : LocalSystem 1 0),\n      M_run_ls_on_event (PaxosLocalSys r s) e = Some ls\n      -> exists s', ls = PaxosLocalSys r s'.\n  Proof.\n    introv run.\n    apply M_run_ls_on_event_preserves_subs in run; eauto 3 with comp paxos.\n    repnd; simpl in *.\n    apply similar_subs_PaxosLocalSys_implies in run2; auto.\n  Qed.\n\n  Lemma eq_PaxosLocalSys_implies :\n    forall n s1 s2,\n      PaxosLocalSys n s1 = PaxosLocalSys n s2\n      -> s1 = s2.\n  Proof.\n    introv h.\n    apply eq_cons in h; repnd.\n    apply decomp_p_nproc in h0.\n    inversion h0; subst; auto.\n  Qed.\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_Paxos :\n    forall {O} n s m subs (F : n_procs 1 -> option MAIN_state * DirectedMsgs -> O),\n      M_break (M_run_sm_on_input (MAIN_comp n s) m) subs F\n      = match m with\n        | paxos_start    _ => M_break (interp_s_proc (handle_start    n s m)) (decr_n_procs subs) (lower_out_break subs F)\n        | paxos_one_a    _ => M_break (interp_s_proc (handle_one_a    n s m)) (decr_n_procs subs) (lower_out_break subs F)\n        | paxos_one_b    _ => M_break (interp_s_proc (handle_one_b    n s m)) (decr_n_procs subs) (lower_out_break subs F)\n        | paxos_vote     _ => M_break (interp_s_proc (handle_vote     n s m)) (decr_n_procs subs) (lower_out_break subs F)\n        | paxos_decision _ => M_break (interp_s_proc (handle_decision n 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_Paxos : paxos.\n\n\n  (* ******************************************* *)\n  (* *** standard tactics *** *)\n  Ltac paxos_simplifier_step :=\n    match goal with\n    | [ H : true = false |- _ ] => inversion H\n    | [ H : false = true |- _ ] => inversion H\n\n    | [ H : broadcast2others _ (send_one_a    _) = send_vote _ _ |- _ ] => complete (inversion H)\n    | [ H : broadcast2others _ (send_one_b    _) = send_vote _ _ |- _ ] => complete (inversion H)\n    | [ H : broadcast2others _ (send_decision _) = send_vote _ _ |- _ ] => complete (inversion H)\n\n    | [ H : broadcast2others _ (send_one_a _) = send_decision _ _ |- _ ] => complete (inversion H)\n    | [ H : broadcast2others _ (send_one_b _) = send_decision _ _ |- _ ] => complete (inversion H)\n    | [ H : broadcast2others _ (send_vote  _) = send_decision _ _ |- _ ] => complete (inversion H)\n\n    | [ H : send_one_a _ _ = send_one_b _ _ |- _ ] => complete (inversion H)\n    | [ H : send_one_b _ _ = send_one_a _ _ |- _ ] => complete (inversion H)\n    | [ H : send_one_a _ _ = send_vote  _ _ |- _ ] => complete (inversion H)\n    | [ H : send_vote _ _  = send_one_a _ _ |- _ ] => complete (inversion H)\n    | [ H : send_one_b _ _ = send_vote  _ _ |- _ ] => complete (inversion H)\n    | [ H : send_vote _ _  = send_one_b _ _ |- _ ] => complete (inversion H)\n\n    | [ H : broadcast2others _ (?F _) = ?F _ _ |- _ ] => inversion H; clear H; subst\n\n    | [ H : n_procs 0 |- _ ] => rewrite (n_procs_0 H) in *; simpl in *; clear H\n    | [ H : ret _ _ _ = (_,_) |- _ ] => unfold ret in H\n    | [ H : (_,_) = (_,_) |- _ ] => apply pair_inj in H; repnd\n    | [ H : Some _ = Some _ |- _ ] => apply Some_inj in H\n    | [ x : _, H : ?x = _ |- _ ] => subst x\n    | [ x : _, H : _ = ?x |- _ ] => subst x\n\n    | [ H : PaxosLocalSys ?r _ = PaxosLocalSys ?r _ |- _ ] => apply eq_PaxosLocalSys_implies in H; repnd\n    | [ H : PaxosLocalSys ?r _ = _ |- _ ] => apply eq_PaxosLocalSys_implies in H; repnd\n    | [ H : _ = PaxosLocalSys ?r _ |- _ ] => apply eq_PaxosLocalSys_implies in H; repnd\n    end.\n\n  Ltac paxos_simp := repeat (paxos_simplifier_step; simpl in * ).\n\n  Ltac unfold_handler :=\n    match goal with\n    | [ H : context[ handle_start    ] |- _ ] => unfold handle_start    in H\n    | [ H : context[ handle_one_a    ] |- _ ] => unfold handle_one_a    in H\n    | [ H : context[ handle_one_b    ] |- _ ] => unfold handle_one_b    in H\n    | [ H : context[ handle_vote     ] |- _ ] => unfold handle_vote     in H\n    | [ H : context[ handle_decision ] |- _ ] => unfold handle_decision in H\n    end.\n\n  Ltac unfold_handler_concl :=\n    match goal with\n    | [ |- context[ handle_start    ] ] => unfold handle_start\n    | [ |- context[ handle_one_a    ] ] => unfold handle_one_a\n    | [ |- context[ handle_one_b    ] ] => unfold handle_one_b\n    | [ |- context[ handle_vote     ] ] => unfold handle_vote\n    | [ |- context[ handle_decision ] ] => unfold handle_decision\n    end.\n\n  Ltac paxos_simplifier :=\n    let stac := (fun _ => paxos_simplifier_step) in\n    simplifier stac.\n\n  Ltac paxos_dest_all name :=\n    let stac := fun _ => paxos_simplifier_step in\n    let ftac := fun _ => try (fold DirectedMsgs in * ) in\n    dest_all\n      name\n      stac\n      ftac.\n\n  Ltac smash_paxos_tac tac :=\n    let stac := fun _ => paxos_simplifier_step in\n    let ftac := fun _ => try (fold DirectedMsgs in * ) in\n    let atac := fun _ => repeat (autorewrite with paxos paxos2 comp kn eo proc in *;simpl in * ) in\n    smash_byzeml_tac\n      tac\n      stac\n      ftac\n      atac.\n\n  Ltac smash_paxos_tac_at H tac :=\n    let stac := fun _ => paxos_simplifier_step in\n    let ftac := fun _ => try (fold DirectedMsgs in * ) in\n    let atac := fun _ => repeat (autorewrite with paxos paxos2 comp kn eo proc in H;simpl in H) in\n    smash_byzeml_tac\n      tac\n      stac\n      ftac\n      atac.\n\n  (* As opposed to the one above, this one doesn't contain paxos2 *)\n  Ltac smash_paxos_tac_ tac :=\n    let stac := fun _ => paxos_simplifier_step in\n    let ftac := fun _ => try (fold DirectedMsgs in * ) in\n    let atac := fun _ => repeat (autorewrite with paxos comp kn eo proc in *;simpl in * ) in\n    smash_byzeml_tac\n      tac\n      stac\n      ftac\n      atac.\n\n  Ltac smash_paxos1  := let tac := fun _ => (eauto 1  with paxos) in smash_paxos_tac tac.\n  Ltac smash_paxos2  := let tac := fun _ => (eauto 2  with paxos) in smash_paxos_tac tac.\n  Ltac smash_paxos3  := let tac := fun _ => (eauto 3  with paxos) in smash_paxos_tac tac.\n  Ltac smash_paxos4  := let tac := fun _ => (eauto 4  with paxos) in smash_paxos_tac tac.\n  Ltac smash_paxos5  := let tac := fun _ => (eauto 5  with paxos) in smash_paxos_tac tac.\n  Ltac smash_paxos6  := let tac := fun _ => (eauto 6  with paxos) in smash_paxos_tac tac.\n  Ltac smash_paxos7  := let tac := fun _ => (eauto 7  with paxos) in smash_paxos_tac tac.\n  Ltac smash_paxos8  := let tac := fun _ => (eauto 8  with paxos) in smash_paxos_tac tac.\n  Ltac smash_paxos9  := let tac := fun _ => (eauto 9  with paxos) in smash_paxos_tac tac.\n  Ltac smash_paxos10 := let tac := fun _ => (eauto 10 with paxos) in smash_paxos_tac tac.\n\n  Ltac smash_paxos1_at  H := let tac := fun _ => (eauto 1  with paxos) in smash_paxos_tac_at H tac.\n  Ltac smash_paxos2_at  H := let tac := fun _ => (eauto 2  with paxos) in smash_paxos_tac_at H tac.\n  Ltac smash_paxos3_at  H := let tac := fun _ => (eauto 3  with paxos) in smash_paxos_tac_at H tac.\n  Ltac smash_paxos4_at  H := let tac := fun _ => (eauto 4  with paxos) in smash_paxos_tac_at H tac.\n  Ltac smash_paxos5_at  H := let tac := fun _ => (eauto 5  with paxos) in smash_paxos_tac_at H tac.\n  Ltac smash_paxos6_at  H := let tac := fun _ => (eauto 6  with paxos) in smash_paxos_tac_at H tac.\n  Ltac smash_paxos7_at  H := let tac := fun _ => (eauto 7  with paxos) in smash_paxos_tac_at H tac.\n  Ltac smash_paxos8_at  H := let tac := fun _ => (eauto 8  with paxos) in smash_paxos_tac_at H tac.\n  Ltac smash_paxos9_at  H := let tac := fun _ => (eauto 9  with paxos) in smash_paxos_tac_at H tac.\n  Ltac smash_paxos10_at H := let tac := fun _ => (eauto 10 with paxos) in smash_paxos_tac_at H tac.\n\n  Ltac smash_paxos_1  := let tac := fun _ => (eauto 1  with paxos) in smash_paxos_tac_ tac.\n  Ltac smash_paxos_2  := let tac := fun _ => (eauto 2  with paxos) in smash_paxos_tac_ tac.\n  Ltac smash_paxos_3  := let tac := fun _ => (eauto 3  with paxos) in smash_paxos_tac_ tac.\n  Ltac smash_paxos_4  := let tac := fun _ => (eauto 4  with paxos) in smash_paxos_tac_ tac.\n  Ltac smash_paxos_5  := let tac := fun _ => (eauto 5  with paxos) in smash_paxos_tac_ tac.\n  Ltac smash_paxos_6  := let tac := fun _ => (eauto 6  with paxos) in smash_paxos_tac_ tac.\n  Ltac smash_paxos_7  := let tac := fun _ => (eauto 7  with paxos) in smash_paxos_tac_ tac.\n  Ltac smash_paxos_8  := let tac := fun _ => (eauto 8  with paxos) in smash_paxos_tac_ tac.\n  Ltac smash_paxos_9  := let tac := fun _ => (eauto 9  with paxos) in smash_paxos_tac_ tac.\n  Ltac smash_paxos_10 := let tac := fun _ => (eauto 10 with paxos) in smash_paxos_tac_ tac.\n\n  Ltac smash_paxos := smash_paxos3.\n\n  Ltac post_paxos_dest_msg :=\n    simpl in *;\n    autorewrite with comp paxos paxos2 in *; simpl in *;\n    repeat unfold_handler;\n    repeat unfold_handler_concl;\n    smash_paxos.\n\n  Ltac pre_paxos_dest_msg c :=\n    match goal with\n    | [ H : Paxos_msg |- _ ] =>\n      destruct H;\n      [ Case_aux c \"Start\"\n      | Case_aux c \"OneA\"\n      | Case_aux c \"OneB\"\n      | Case_aux c \"Vote\"\n      | Case_aux c \"Decision\"\n      ]\n    end.\n\n  Ltac paxos_dest_msg c :=\n    progress (pre_paxos_dest_msg c);\n    post_paxos_dest_msg.\n\n  Ltac paxo_finish_eexists :=\n    repeat match goal with\n           | [ |- ex _ ] => eexists\n           end;\n    dands; eauto; eauto 3 with eo.\n\n  Ltac rename_hyp_with oldname newname :=\n    match goal with\n    | [ H : context[oldname] |- _ ] => rename H into newname\n    end.\n\n\n  (* ******************************************* *)\n  (* *** instantiation of the knowledge calculus *** *)\n\n  Record kdata : Type := mk_data { data_n : node; data_r : round ; data_v : value }.\n  Definition trust := kdata.\n  Definition trust2owner (t : trust) : option node := Some (data_n t).\n\n  Definition vote2kdata (v : vote) :=\n    match v with\n    | mk_vote n r v => mk_data n r v\n    end.\n\n  Definition decision2kdata (d : decision) :=\n    match d with\n    | mk_decision n r v => mk_data n r v\n    end.\n\n  Definition msg2data (m : Paxos_msg) : list kdata :=\n    match m with\n    | paxos_start s => []\n    | paxos_one_a a => []\n    | paxos_one_b b => []\n    | paxos_vote v => [vote2kdata v]\n    | paxos_decision d => [(*decision2kdata d*)]\n    end.\n\n  Definition auth2data (a : AuthenticatedData) : list kdata := msg2data (am_data a).\n  Definition auth2trust (a : AuthenticatedData) : list trust := auth2data a.\n\n  Global Instance Paxos_I_ComponentTrust : ComponentTrust :=\n    MkComponentTrust trust auth2trust (fun cn out => None) trust2owner.\n\n  Definition trust2data (t : trust) : kdata := t.\n  Definition gen_for (d : kdata) (t : trust) := d = t.\n  Definition data2owner (d : kdata) : option node := Some (data_n d).\n\n  Lemma inj_no_data : injective trust2data.\n  Proof.\n    introv; destruct n, m; tcsp.\n  Qed.\n\n  Definition sim_data (d1 d2 : kdata) : Prop :=\n    match d1, d2 with\n    | mk_data n1 r1 v1, mk_data n2 r2 v2 => n1 = n2 /\\ r1 = r2\n    end.\n\n  Lemma sim_data_sym : symmetric _ sim_data.\n  Proof.\n    introv; destruct x, y; simpl; tcsp.\n  Qed.\n  Hint Resolve sim_data_sym : paxos.\n\n  Lemma sim_data_trans : transitive _ sim_data.\n  Proof.\n    introv; destruct x, y, z; introv a b; simpl in *; repnd; subst; tcsp.\n  Qed.\n  Hint Resolve sim_data_trans : paxos.\n\n  Lemma sim_data_refl : reflexive _ sim_data.\n  Proof.\n    introv; destruct x; simpl in *; tcsp.\n  Qed.\n  Hint Resolve sim_data_refl : paxos.\n\n  Lemma sim_data_equiv : equivalence _ sim_data.\n  Proof.\n    split; eauto 2 with paxos.\n  Qed.\n  Hint Resolve sim_data_equiv : paxos.\n\n  Lemma collision_res :\n    forall (t : trust) (d1 d2 : kdata),\n      gen_for d1 t -> gen_for d2 t -> sim_data d1 d2 -> d1 = d2.\n  Proof.\n    introv h q; unfold gen_for in *; tcsp; subst; tcsp.\n  Qed.\n\n  Definition same_trust2owner :\n    forall (t : trust), data2owner (trust2data t) = trust2owner t.\n  Proof.\n    tcsp.\n  Qed.\n\n  Definition data2trust (d : kdata) : list trust := [d].\n\n  Lemma data2trust_correct : forall t, In t (data2trust (trust2data t)).\n  Proof.\n    introv; simpl; destruct t; tcsp.\n  Qed.\n\n  Lemma auth2trust_correct :\n    forall a t, In t (auth2trust a) <-> exists d, In t (data2trust d) /\\ In d (auth2data a).\n  Proof.\n    introv; simpl; split; intro h; exrepnd; repndors; subst; tcsp; eauto.\n  Qed.\n\n  Definition mem_comp : CompName := MAINname.\n  Definition trust_comp : PreCompName := MAINname.\n\n  Definition in_entries (d : kdata) (l : entries) : Prop :=\n    exists entry,\n      find_entry (data_r d) l = Some entry\n      /\\ entry_proposal entry = Some (data_v d).\n\n  Definition knows (d : kdata) (m : MAIN_state) : Prop :=\n    in_entries d (st_entries m).\n\n  Lemma knows_dec : forall (d : kdata) (m : MAIN_state), decidable (knows d m).\n  Proof.\n    introv.\n    unfold knows, in_entries.\n    remember (find_entry (data_r d) (st_entries m)) as fe; symmetry in Heqfe.\n    destruct fe;[|right; intro xx; exrepnd; ginv];[].\n    destruct e as [r one_bs votes valueop].\n    destruct valueop;[|right; intro xx; exrepnd; ginv];[].\n    destruct (value_deq v (data_v d)); subst;[|right; intro xx; exrepnd; ginv];[].\n    left; eexists; dands; try reflexivity.\n  Qed.\n\n  Lemma no_initial_memory :\n    forall n i, on_state_of_component MAINname (PaxosSys n) (fun s => ~ knows i s).\n  Proof.\n    introv h; simpl in *; unfold knows, in_entries in *; exrepnd; simpl in *; ginv.\n  Qed.\n\n  Definition id := round.\n  Definition id_lt (r1 r2 : id) : Prop := r1 < r2.\n  Definition id_lt_trans : transitive _ id_lt := Nat.lt_trans.\n  Definition id_lt_arefl  : antireflexive id_lt := Nat.lt_irrefl.\n  Definition trust_has_id (t : trust) (i : id) : Prop := data_r t = i.\n\n  Lemma trust_has_id_pres : forall t a b c, trust_has_id t a -> trust_has_id t c -> (id_lt a b \\/ a = b) -> (id_lt b c \\/ b = c) -> trust_has_id t b.\n  Proof.\n    introv h q u v.\n    repndors; subst; tcsp.\n    unfold trust_has_id, id_lt in *; subst; try omega.\n  Qed.\n\n  Definition sim_trust := sim_data.\n\n  Lemma sim_trust_equiv : equivalence _ sim_trust.\n  Proof.\n    unfold sim_trust; eauto 3 with paxos.\n  Qed.\n\n  Lemma sim_trust_pres : forall t t' a b, trust_has_id t a -> trust_has_id t b -> sim_trust t t' -> trust_has_id t' a -> trust_has_id t' b.\n  Proof.\n    unfold trust_has_id; introv h q v w; subst; auto.\n  Qed.\n\n  Definition getId (s : MAIN_state) : id := st_current_round s.\n\n  Definition ExtPrim := unit.\n  Definition ext_prim_interp (eo : EventOrdering) (e : Event) (p : ExtPrim) : Prop := False.\n\n\n  Global Instance Paxos_I_KnowledgeComponents : KnowledgeComponents :=\n    MkKnowledgeComponents\n      kdata\n      trust2data\n      inj_no_data\n      gen_for\n      sim_data\n      sim_data_sym\n      collision_res\n      data2owner\n      same_trust2owner\n      auth2data\n      data2trust\n      data2trust_correct\n      auth2trust_correct\n      mem_comp\n      trust_comp\n      knows\n      knows_dec\n      PaxosfunLevelSpace\n      PaxosSys\n      no_initial_memory\n      msg2data\n      id\n      id_lt\n      id_lt_trans\n      id_lt_arefl\n      trust_has_id\n      trust_has_id_pres\n      sim_trust\n      sim_trust_equiv\n      sim_trust_pres\n      getId\n      ExtPrim\n      ext_prim_interp.\n\n  Definition create (eo : EventOrdering) (e : Event) (a : data) : list unit := [tt].\n  Definition verify (eo : EventOrdering) (e : Event) (a : AuthenticatedData) : bool := true.\n\n  Global Instance Paxos_I_ComponentAuth : ComponentAuth :=\n    MkComponentAuth create verify.\n\n\n  (* ******************************************* *)\n  (* *** properties *** *)\n\n  Lemma in_entries_cons :\n    forall d a s,\n      in_entries d (a :: s)\n      <-> if round_deq (data_r d) (entry_round a)\n          then entry_proposal a = Some (data_v d)\n          else in_entries d s.\n  Proof.\n    introv; unfold in_entries; split; intro h; exrepnd; smash_paxos2; eauto.\n  Qed.\n  Hint Rewrite in_entries_cons : paxos.\n\n  Lemma in_entries_nil : forall d, in_entries d [] <-> False.\n  Proof.\n    introv; unfold in_entries; split; intro h; exrepnd; smash_paxos2; eauto.\n  Qed.\n  Hint Rewrite in_entries_nil : paxos.\n\n  Lemma add_one_b_preserves_in_entries :\n    forall b d s e s',\n      add_one_b b s = (e, s')\n      -> in_entries d s\n      -> in_entries d s'.\n  Proof.\n    induction s; introv add i; simpl in *; repeat smash_paxos2.\n  Qed.\n  Hint Resolve add_one_b_preserves_in_entries : paxos.\n\n  Lemma add_vote_preserves_in_entries :\n    forall b d s e s',\n      add_vote b s = (e, s')\n      -> in_entries d s\n      -> in_entries d s'.\n  Proof.\n    induction s; introv add i; simpl in *; repeat smash_paxos2.\n    unfold upd_proposal, upd_none; smash_paxos2.\n  Qed.\n  Hint Resolve add_vote_preserves_in_entries : paxos.\n\n  Lemma log_one_b_preserves_knows :\n    forall b d s e s',\n      log_one_b b s = (e, s')\n      -> knows d s\n      -> knows d s'.\n  Proof.\n    introv log kn.\n    destruct s as [r l]; unfold log_one_b in *; simpl in *; smash_paxos2.\n    unfold knows in *; simpl in *; smash_paxos2.\n  Qed.\n  Hint Resolve log_one_b_preserves_knows : paxos.\n\n  Lemma log_vote_preserves_knows :\n    forall b d s e s',\n      log_vote b s = (e, s')\n      -> knows d s\n      -> knows d s'.\n  Proof.\n    introv log kn.\n    destruct s as [r l]; unfold log_vote in *; simpl in *; smash_paxos2.\n    unfold knows in *; simpl in *; smash_paxos2.\n  Qed.\n  Hint Resolve log_vote_preserves_knows : paxos.\n\n  Lemma log_my_vote_preserves_knows :\n    forall n b d x s e s',\n      log_my_vote n b x s = (e, s')\n      -> knows d s\n      -> knows d s'.\n  Proof.\n    introv log kn.\n    destruct s as [r l]; unfold log_my_vote in *; simpl in *; smash_paxos2.\n  Qed.\n  Hint Resolve log_my_vote_preserves_knows : paxos.\n\n  Lemma update_last_round_preserves_knows :\n    forall d a s,\n      knows d s\n      -> knows d (update_last_round a s).\n  Proof.\n    introv kn; tcsp.\n  Qed.\n  Hint Resolve update_last_round_preserves_knows : paxos.\n\n  Lemma in_entries_unique :\n    forall s a b,\n      in_entries a s\n      -> in_entries b s\n      -> sim_data a b\n      -> a = b.\n  Proof.\n    induction s; introv kna knb sim; repeat smash_paxos2;\n      destruct a0, b; simpl in *; repnd; subst; try congruence.\n  Qed.\n  Hint Resolve in_entries_unique : paxos.\n\n  Lemma knows_unique :\n    forall s a b,\n      knows a s\n      -> knows b s\n      -> sim_data a b\n      -> a = b.\n  Proof.\n    introv kna knb sim; unfold knows in *; simpl in *; smash_paxos2.\n  Qed.\n  Hint Resolve knows_unique : paxos.\n\n  Lemma data_is_in_out_implies_dmsg_is_in_out :\n    forall {eo : EventOrdering} (e : Event) (o : event2out 0 e) d,\n      data_is_in_out d o\n      -> exists m, dmsg_is_in_out m o /\\ In d (msg2data (dmMsg m)).\n  Proof.\n    introv h.\n    unfold event2out, data_is_in_out, dmsg_is_in_out in *.\n    remember (trigger e) as trig.\n    destruct trig; simpl in *; tcsp.\n    apply in_flat_map; auto.\n  Qed.\n\n  Definition not_in_entries r (l : entries) : Prop :=\n    match find_entry r l with\n    | Some e => entry_proposal e = None\n    | None => True\n    end.\n\n  Lemma not_in_entries_cons :\n    forall r a l,\n      not_in_entries r (a :: l)\n      <-> if round_deq r (entry_round a)\n          then entry_proposal a = None\n          else not_in_entries r l.\n  Proof.\n    unfold not_in_entries; introv; simpl; smash_paxos2; split; intro h; tcsp.\n  Qed.\n  Hint Rewrite not_in_entries_cons : paxos.\n\n  Lemma in_entries_add_vote_if_not_in :\n    forall l n r v e k,\n      is_proposer n r = true\n      -> not_in_entries r l\n      -> add_vote (mk_vote n r v) l = (e, k)\n      -> in_entries (mk_data n r v) k.\n  Proof.\n    induction l; introv isp ni add; simpl in *; repeat smash_paxos2;\n      unfold upd_proposal, upd_none, is_vote_from_proposer; smash_paxos2.\n  Qed.\n  Hint Resolve in_entries_add_vote_if_not_in : paxos.\n\n  Lemma knows_log_vote_if_not_in :\n    forall s n r v e s',\n      is_proposer n r = true\n      -> log_vote (mk_vote n r v) s = (e, s')\n      -> not_in_entries r (st_entries s)\n      -> knows (mk_data n r v) s'.\n  Proof.\n    introv isp lv nkn.\n    unfold knows, log_vote in *; simpl in *; smash_paxos2.\n  Qed.\n\n  Lemma add_one_b_implies_find_entry :\n    forall b s e s',\n      add_one_b b s = (e, s')\n      -> find_entry (one_b_R b) s' = Some e.\n  Proof.\n    induction s; introv h; simpl in *; repeat smash_paxos2.\n  Qed.\n  Hint Resolve add_one_b_implies_find_entry : paxos.\n\n  Lemma log_one_b_implies_find_entry :\n    forall b s e s',\n      log_one_b b s = (e, s')\n      -> find_entry (one_b_R b) (st_entries s') = Some e.\n  Proof.\n    introv h.\n    unfold log_one_b in *; smash_paxos2.\n  Qed.\n  Hint Resolve log_one_b_implies_find_entry : paxos.\n\n  Lemma is_some_false_iff :\n    forall {T} (o : option T), is_some o = false <-> o = None.\n  Proof.\n    unfold is_some; introv; split; destruct o; intro h; subst; tcsp.\n  Qed.\n  Hint Rewrite @is_some_false_iff : paxos.\n\n  Lemma find_entry_not_proposed_implies_not_in_entries :\n    forall r l e,\n      find_entry r l = Some e\n      -> proposed_entry e = false\n      -> not_in_entries r l.\n  Proof.\n    introv h q; unfold not_in_entries; allrw.\n    unfold proposed_entry in *; smash_paxos2.\n  Qed.\n  Hint Resolve find_entry_not_proposed_implies_not_in_entries : paxos.\n\n  Lemma add_vote_implies_find_entry :\n    forall v s e s',\n      add_vote v s = (e, s')\n      -> find_entry (vote_R v) s' = Some e.\n  Proof.\n    induction s; introv h; simpl in *; repeat smash_paxos2.\n  Qed.\n  Hint Resolve add_vote_implies_find_entry : paxos.\n\n  Lemma log_vote_implies_find_entry :\n    forall v s e s',\n      log_vote v s = (e, s')\n      -> find_entry (vote_R v) (st_entries s') = Some e.\n  Proof.\n    introv h.\n    unfold log_vote in *; smash_paxos2.\n  Qed.\n  Hint Resolve log_vote_implies_find_entry : paxos.\n\n  Lemma data_v_vote2kdata : forall v, data_v (vote2kdata v) = vote_V v.\n  Proof.\n    destruct v; tcsp.\n  Qed.\n  Hint Rewrite data_v_vote2kdata : paxos.\n\n  Lemma data_r_vote2kdata : forall v, data_r (vote2kdata v) = vote_R v.\n  Proof.\n    destruct v; tcsp.\n  Qed.\n  Hint Rewrite data_r_vote2kdata : paxos.\n\n  Lemma add_vote_preserves_proposal :\n    forall v s e s' e' x,\n      add_vote v s = (e', s')\n      -> find_entry (vote_R v) s = Some e\n      -> entry_proposal e = Some x\n      -> entry_proposal e' = Some x.\n  Proof.\n    induction s; introv h q w; simpl in *; smash_paxos2.\n    allrw; unfold upd_proposal; simpl; smash_paxos2.\n  Qed.\n\n  Lemma valid_my_vote_implies_entry_proposal :\n    forall n v e,\n      valid_my_vote n v e = true\n      -> entry_proposal e = Some (vote_V v).\n  Proof.\n    introv h; unfold valid_my_vote, has_proposed in *; smash_paxos2.\n  Qed.\n  Hint Resolve valid_my_vote_implies_entry_proposal : paxos.\n\n  Lemma knows_log_my_vote :\n    forall n v s s1 e1 e2 s2 d m,\n      log_vote v s = (e1, s1)\n      -> log_my_vote n v e1 s1 = (e2, s2)\n      -> In d (msg2data (dmMsg m))\n      -> In m (send_my_vote n e1 v)\n      -> knows d s2.\n  Proof.\n    introv lv lmv im isv.\n    unfold knows, log_my_vote, log_vote, send_my_vote, vote2my in *; simpl in *; smash_paxos2.\n    applydup add_vote_implies_find_entry in Heqx1; simpl in *.\n    applydup add_vote_implies_find_entry in Heqx0; simpl in *.\n    exists e2; dands; smash_paxos2.\n    eapply add_vote_preserves_proposal; eauto; smash_paxos2.\n  Qed.\n\n  Definition logged_vote (v : vote) (s : MAIN_state) :=\n    exists r x,\n      find_entry r (st_entries s) = Some x\n      /\\ In v (entry_votes x).\n\n  Lemma logged_vote_initial_state :\n    forall v, logged_vote v initial_state <-> False.\n  Proof.\n    introv; unfold logged_vote; simpl; split; intro h; exrepnd; tcsp.\n  Qed.\n  Hint Rewrite logged_vote_initial_state : paxos.\n\n  Lemma logged_vote_initial_state_at :\n    forall v r, logged_vote v (initial_state_at r) <-> False.\n  Proof.\n    introv; unfold logged_vote; simpl; split; intro h; exrepnd; tcsp.\n  Qed.\n  Hint Rewrite logged_vote_initial_state_at : paxos.\n\n  Lemma update_last_round_initial_state :\n    forall r,\n      valid_round r = true\n      -> update_last_round r initial_state = initial_state_at r.\n  Proof.\n    introv h; unfold update_last_round, valid_round in *; smash_paxos2.\n  Qed.\n  (*Hint Rewrite update_last_round_initial_state : paxos.*)\n\n  Lemma log_one_b_initial_state_at :\n    forall b r,\n      log_one_b b (initial_state_at r)\n      = (one_b2entry b, MkState r [one_b2entry b]).\n  Proof.\n    tcsp.\n  Qed.\n  Hint Rewrite log_one_b_initial_state_at : paxos.\n\n  Lemma log_one_b_initial_state :\n    forall b,\n      log_one_b b initial_state\n      = (one_b2entry b, MkState initial_round [one_b2entry b]).\n  Proof.\n    tcsp.\n  Qed.\n  Hint Rewrite log_one_b_initial_state : paxos.\n\n  Lemma log_vote_initial_state :\n    forall v,\n      log_vote v initial_state\n      = (vote2entry v, MkState initial_round [vote2entry v]).\n  Proof.\n    tcsp.\n  Qed.\n  Hint Rewrite log_vote_initial_state : paxos.\n\n  Lemma logged_vote_one_b2entry :\n    forall v r b,\n      logged_vote v (MkState r [one_b2entry b]) <-> False.\n  Proof.\n    introv; split; intro h; tcsp.\n    unfold logged_vote in *; exrepnd; smash_paxos2.\n  Qed.\n  Hint Rewrite logged_vote_one_b2entry : paxos.\n\n  Lemma find_entry_add_one_b_implies :\n    forall b l e k r x,\n      add_one_b b l = (e, k)\n      -> find_entry r k = Some x\n      -> (exists x', find_entry r l = Some x' /\\ r = one_b_R b /\\ x = add_one_b_to_entry b x')\n         \\/ (find_entry r l = Some x /\\ r <> one_b_R b)\n         \\/ (find_entry r l = None /\\ x = one_b2entry b).\n  Proof.\n    induction l; introv add fe; simpl in *; repeat smash_paxos2; eauto; allrw; tcsp.\n  Qed.\n\n  Lemma find_entry_add_vote_implies :\n    forall v l e k r x,\n      add_vote v l = (e, k)\n      -> find_entry r k = Some x\n      -> (exists x', find_entry r l = Some x' /\\ r = vote_R v /\\ x = add_vote_to_entry v x')\n         \\/ (find_entry r l = Some x /\\ r <> vote_R v)\n         \\/ (find_entry r l = None /\\ x = vote2entry v).\n  Proof.\n    induction l; introv add fe; simpl in *; repeat smash_paxos2; eauto; allrw; tcsp.\n  Qed.\n\n  Lemma logged_vote_log_one_b :\n    forall b s e s' v,\n      log_one_b b s = (e, s')\n      -> logged_vote v s'\n      -> logged_vote v s.\n  Proof.\n    introv log i; unfold logged_vote, log_one_b in *; exrepnd; smash_paxos2;\n      eapply find_entry_add_one_b_implies in i0; eauto; repndors; exrepnd; subst; simpl in *; tcsp;\n        try (complete (eexists; eexists; dands; eauto)).\n  Qed.\n  Hint Resolve logged_vote_log_one_b : paxos.\n\n  Lemma in_add_vote_to_list_implies :\n    forall v v' l,\n      In v (add_vote_to_list v' l)\n      -> v = v' \\/ In v l.\n  Proof.\n    induction l; introv i; simpl in *; tcsp; repeat smash_paxos2.\n    repndors; subst; tcsp.\n  Qed.\n\n  Lemma logged_vote_log_vote :\n    forall s v v' e s',\n      log_vote v' s = (e,s')\n      -> logged_vote v s'\n      -> (v = v' \\/ logged_vote v s).\n  Proof.\n    introv lv i; unfold logged_vote, log_vote in *; exrepnd; smash_paxos2.\n    eapply find_entry_add_vote_implies in i0; eauto; repndors; exrepnd; subst; simpl in *; tcsp;\n      try (complete (eexists; eexists; dands; eauto)); try complete (right; eauto).\n    apply in_add_vote_to_list_implies in i1; repndors; tcsp.\n    right; eauto.\n  Qed.\n\n  Lemma logged_vote_log_my_vote :\n    forall s n e0 v v' e s',\n      log_my_vote n v' e0 s = (e,s')\n      -> logged_vote v s'\n      -> ((v = vote2my n v' /\\ valid_my_vote n v' e0 = true) \\/ logged_vote v s).\n  Proof.\n    introv lv i; unfold log_my_vote in *; smash_paxos2.\n    eapply logged_vote_log_vote in i; eauto; repndors; tcsp.\n  Qed.\n\n  Lemma logged_vote_vote2entry :\n    forall v r w,\n      logged_vote v (MkState r [vote2entry w]) <-> v = w.\n  Proof.\n    introv; split; intro h; subst; tcsp;\n      unfold logged_vote in *; exrepnd; smash_paxos2.\n    exists (vote_R w) (vote2entry w); smash_paxos2.\n  Qed.\n  Hint Rewrite logged_vote_vote2entry : paxos.\n\n  Lemma find_latest_value_from_votes_nil :\n    forall n v low high,\n      find_latest_value_from_votes n v low high [] = (low,v).\n  Proof.\n    tcsp.\n  Qed.\n  Hint Rewrite find_latest_value_from_votes_nil : paxos.\n\n  Lemma valid_round_if_gt :\n    forall r r0,\n      r0 < r\n      -> valid_round r = true.\n  Proof.\n    introv h; unfold valid_round, initial_round; smash_paxos2; try omega.\n  Qed.\n  Hint Resolve valid_round_if_gt : paxos.\n\n  Definition wf_entries (l : entries) :=\n    no_repeats (map entry_round l)\n    /\\ forall x,\n      In x l\n      -> (forall b, In b (entry_one_bs x) -> one_b_R b = entry_round x)\n         /\\ (forall v, In v (entry_votes x) -> vote_R v = entry_round x).\n\n  Definition wf_state (s : MAIN_state) := wf_entries (st_entries s).\n\n  Lemma wf_state_initial_state : wf_state initial_state.\n  Proof.\n    split; simpl; tcsp.\n  Qed.\n  Hint Resolve wf_state_initial_state : paxos.\n\n  Lemma update_last_round_preserves_wf_state :\n    forall a s,\n      wf_state s\n      -> wf_state (update_last_round a s).\n  Proof.\n    tcsp.\n  Qed.\n  Hint Resolve update_last_round_preserves_wf_state : paxos.\n\n  Lemma implies_wf_entries_cons :\n    forall x l,\n      wf_entries (x :: l)\n      <-> ((forall b, In b (entry_one_bs x) -> one_b_R b = entry_round x)\n           /\\ (forall v, In v (entry_votes x) -> vote_R v = entry_round x)\n           /\\ wf_entries l\n           /\\ ~ In (entry_round x) (map entry_round l)).\n  Proof.\n    introv; split; intro h; repnd; dands; tcsp; try (complete (apply h; tcsp)).\n    { destruct h as [norep imp]; simpl in *.\n      rewrite no_repeats_cons in *; repnd.\n      split; tcsp.\n      introv xx; apply imp; tcsp. }\n    { destruct h as [norep imp]; simpl in *.\n      rewrite no_repeats_cons in *; repnd; tcsp. }\n    { destruct h2 as [norep imp].\n      split; simpl in *.\n      { rewrite no_repeats_cons; dands; tcsp. }\n      introv xx; simpl in *; repndors; subst; tcsp.\n      apply imp in xx; tcsp. }\n  Qed.\n\n  Lemma in_add_one_b_to_list_implies :\n    forall x b l,\n      In x (add_one_b_to_list b l)\n      -> x = b \\/ In x l.\n  Proof.\n    induction l; introv h; simpl in *; tcsp; smash_paxos2; repndors; subst; tcsp.\n  Qed.\n\n  Lemma add_one_b_preserves_entry_rounds_rev :\n    forall b l e k,\n      add_one_b b l = (e, k)\n      -> eqset (map entry_round k) (one_b_R b :: map entry_round l).\n  Proof.\n    induction l; introv h; simpl in *; smash_paxos2.\n    { introv; split; intro h; simpl in *; repndors; subst; tcsp. }\n    pose proof (IHl e x1) as IHl; autodimp IHl hyp.\n    introv; split; intro h; simpl in *; repndors; subst; tcsp.\n    { apply IHl in h; simpl in *; tcsp. }\n    { right; apply IHl; simpl; tcsp. }\n    { right; apply IHl; simpl; tcsp. }\n  Qed.\n\n  Lemma add_vote_preserves_entry_rounds_rev :\n    forall v l e k,\n      add_vote v l = (e, k)\n      -> eqset (map entry_round k) (vote_R v :: map entry_round l).\n  Proof.\n    induction l; introv h; simpl in *; smash_paxos2.\n    { introv; split; intro h; simpl in *; repndors; subst; tcsp. }\n    pose proof (IHl e x1) as IHl; autodimp IHl hyp.\n    introv; split; intro h; simpl in *; repndors; subst; tcsp.\n    { apply IHl in h; simpl in *; tcsp. }\n    { right; apply IHl; simpl; tcsp. }\n    { right; apply IHl; simpl; tcsp. }\n  Qed.\n\n  Lemma add_one_b_preserves_wf_entries :\n    forall b l e k,\n      add_one_b b l = (e, k)\n      -> wf_entries l\n      -> wf_entries k.\n  Proof.\n    induction l; introv h q; simpl in *; tcsp; smash_paxos2;\n      apply implies_wf_entries_cons; repnd; dands; simpl in *; tcsp;\n        try (apply implies_wf_entries_cons in q; repnd; tcsp);\n        try (complete (introv xx; repndors; subst; tcsp));\n        try (complete (eapply IHl; eauto));\n        try (complete (introv xx; apply in_add_one_b_to_list_implies in xx; repndors; subst; tcsp));\n        try (complete (apply add_one_b_preserves_entry_rounds_rev in Heqx;\n                       intro xx; destruct q; apply Heqx in xx; simpl in *; tcsp)).\n  Qed.\n  Hint Resolve add_one_b_preserves_wf_entries : paxos.\n\n  Lemma add_vote_preserves_wf_entries :\n    forall v l e k,\n      add_vote v l = (e, k)\n      -> wf_entries l\n      -> wf_entries k.\n  Proof.\n    induction l; introv h q; simpl in *; tcsp; smash_paxos2;\n      apply implies_wf_entries_cons; repnd; dands; simpl in *; tcsp;\n        try (apply implies_wf_entries_cons in q; repnd; tcsp);\n        try (complete (introv xx; repndors; subst; tcsp));\n        try (complete (eapply IHl; eauto));\n        try (complete (introv xx; apply in_add_vote_to_list_implies in xx; repndors; subst; tcsp));\n        try (complete (apply add_vote_preserves_entry_rounds_rev in Heqx;\n                       intro xx; destruct q; apply Heqx in xx; simpl in *; tcsp)).\n  Qed.\n  Hint Resolve add_vote_preserves_wf_entries : paxos.\n\n  Lemma log_one_b_preserves_wf_state :\n    forall b s e s',\n      log_one_b b s = (e, s')\n      -> wf_state s\n      -> wf_state s'.\n  Proof.\n    introv h wf; unfold log_one_b, wf_state in *; smash_paxos2.\n  Qed.\n  Hint Resolve log_one_b_preserves_wf_state : paxos.\n\n  Lemma log_vote_preserves_wf_state :\n    forall b s e s',\n      log_vote b s = (e, s')\n      -> wf_state s\n      -> wf_state s'.\n  Proof.\n    introv h wf; unfold log_vote, wf_state in *; smash_paxos2.\n  Qed.\n  Hint Resolve log_vote_preserves_wf_state : paxos.\n\n  Lemma log_my_vote_preserves_wf_state :\n    forall n b x s e s',\n      log_my_vote n b x s = (e, s')\n      -> wf_state s\n      -> wf_state s'.\n  Proof.\n    introv h wf; unfold log_my_vote in *; smash_paxos2.\n  Qed.\n  Hint Resolve log_my_vote_preserves_wf_state : paxos.\n\n  Lemma log_vote_implies_logged_vote :\n    forall w s e s' x,\n      log_vote w s = (e, s')\n      -> In x (entry_votes e)\n      -> logged_vote x s'.\n  Proof.\n    introv log i; unfold logged_vote, log_vote in *; exrepnd; smash_paxos2.\n    apply add_vote_implies_find_entry in Heqx0.\n    exists (vote_R w) e; allrw; tcsp.\n  Qed.\n  Hint Resolve log_vote_implies_logged_vote : paxos.\n\n  Lemma wf_state_log_vote_in_entry_votes_implies :\n    forall v s e s' v',\n      wf_state s\n      -> log_vote v s = (e, s')\n      -> In v' (entry_votes e)\n      -> vote_R v = vote_R v'.\n  Proof.\n    introv wf lv i.\n    unfold log_vote, wf_state in *; smash_paxos2.\n    remember (st_entries s) as l; clear Heql.\n    revert dependent x1.\n    induction l; introv h; simpl in *; tcsp; smash_paxos2;\n      allrw implies_wf_entries_cons; repnd;\n        simpl in *; repndors; subst; tcsp.\n    { apply in_add_vote_to_list_implies in i; repndors; subst; tcsp.\n      apply wf1 in i; try congruence. }\n    { autodimp IHl hyp; pose proof (IHl x2) as IHl; autodimp IHl hyp. }\n  Qed.\n\n  Lemma in_entry2vote_nodes :\n    forall n val e,\n      In n (entry2vote_nodes val e)\n      -> exists v,\n        In v (entry_votes e)\n        /\\ vote_N v = n\n        /\\ vote_V v = val.\n  Proof.\n    introv i.\n    apply in_map_iff in i; exrepnd.\n    apply filter_In in i0; repnd; smash_paxos2; eauto.\n  Qed.\n\n  Lemma log_my_vote_implies_find_entry :\n    forall n v x s e s',\n      log_my_vote n v x s = (e, s')\n      -> (find_entry (vote_R v) (st_entries s') = Some e\n          \\/ (e = x /\\ s = s' /\\ valid_my_vote n v x = false)).\n  Proof.\n    introv h.\n    unfold log_my_vote in *; smash_paxos2.\n    apply log_vote_implies_find_entry in h; smash_paxos2.\n  Qed.\n\n  Lemma add_vote_implies_equal_entry_round :\n    forall v s e s',\n      add_vote v s = (e, s')\n      -> vote_R v = entry_round e.\n  Proof.\n    induction s; introv h; simpl in *; smash_paxos2.\n  Qed.\n\n  Lemma log_vote_implies_equal_entry_round :\n    forall v s e s',\n      log_vote v s = (e, s')\n      -> vote_R v = entry_round e.\n  Proof.\n    unfold log_vote; introv h; simpl in *; smash_paxos2.\n    apply add_vote_implies_equal_entry_round in Heqx; auto.\n  Qed.\n\n  Lemma log_my_vote_implies_equal_entry_round :\n    forall n v e1 s1 e2 s2,\n      log_my_vote n v e1 s1 = (e2, s2)\n      -> vote_R v = entry_round e2 \\/ e1 = e2.\n  Proof.\n    introv h; unfold log_my_vote in h; smash_paxos2.\n    apply log_vote_implies_equal_entry_round in h; smash_paxos2.\n  Qed.\n\n  Lemma mk_vote_eta :\n    forall v, mk_vote (vote_N v) (vote_R v) (vote_V v) = v.\n  Proof.\n    destruct v; auto.\n  Qed.\n  Hint Rewrite mk_vote_eta : paxos.\n\n  Definition by_quorum (F : node -> Prop) : Prop :=\n    exists q,\n      forms_quorum q = true\n      /\\ forall m, In m q -> F m.\n\n  Lemma forms_quorum_pos :\n    forall q, forms_quorum q = true -> 0 < length q.\n  Proof.\n    introv h; dup h as w.\n    eapply quorum_intersection in h; eauto; exrepnd.\n    destruct q; simpl in *; tcsp; try omega.\n  Qed.\n\n  Lemma implies_in_add_vote_to_list :\n    forall v v' l,\n      In v l\n      -> In v (add_vote_to_list v' l).\n  Proof.\n    induction l; introv i; simpl in *; tcsp; repeat smash_paxos2.\n    repndors; subst; tcsp.\n  Qed.\n\n  Lemma log_vote_preserves_logged_vote :\n    forall s v v' e s',\n      log_vote v' s = (e,s')\n      -> logged_vote v s\n      -> logged_vote v s'.\n  Proof.\n    introv lv i; unfold logged_vote, log_vote in *; exrepnd; smash_paxos2.\n    remember (st_entries s) as l; clear Heql.\n    exists r.\n    revert dependent e.\n    revert dependent x2.\n    induction l; introv h; simpl in *; tcsp; smash_paxos2.\n    { eexists; dands; eauto.\n      apply implies_in_add_vote_to_list; auto. }\n    { exists x; dands; tcsp. }\n    { eexists; dands; eauto. }\n  Qed.\n  Hint Resolve log_vote_preserves_logged_vote : paxos.\n\n  Lemma log_my_vote_preserves_logged_vote :\n    forall s v n v' x e s',\n      log_my_vote n v' x s = (e,s')\n      -> logged_vote v s\n      -> logged_vote v s'.\n  Proof.\n    introv lv i; unfold log_my_vote in *; smash_paxos2.\n  Qed.\n  Hint Resolve log_my_vote_preserves_logged_vote : paxos.\n\n  Lemma log_one_b_preserves_logged_vote :\n    forall b s e s' v,\n      log_one_b b s = (e, s')\n      -> logged_vote v s\n      -> logged_vote v s'.\n  Proof.\n    introv log i; unfold logged_vote, log_one_b in *; exrepnd; smash_paxos2.\n    exists r.\n    remember (st_entries s) as l; clear Heql.\n    revert e x2 Heqx0; induction l; introv h; simpl in *; smash_paxos2;\n      try (complete (eexists; dands; eauto)).\n  Qed.\n  Hint Resolve log_one_b_preserves_logged_vote : paxos.\n\n  Lemma find_entry_implies_eq_entry_round :\n    forall r l e,\n      find_entry r l = Some e\n      -> entry_round e = r.\n  Proof.\n    induction l; introv h; simpl in *; smash_paxos2.\n  Qed.\n\n  Lemma find_entry_implies_in :\n    forall r l e,\n      find_entry r l = Some e\n      -> In e l.\n  Proof.\n    induction l; introv h; simpl in *; smash_paxos2.\n  Qed.\n\n  Lemma log_vote_preserves_in_entry_votes :\n    forall v s e' s' e,\n      log_vote v s = (e', s')\n      -> find_entry (vote_R v) (st_entries s) = Some e\n      -> In v (entry_votes e)\n      -> In v (entry_votes e').\n  Proof.\n    introv h q i.\n    unfold log_vote in *; smash_paxos2.\n    remember (st_entries s) as l; clear Heql.\n    revert e' x1 Heqx.\n    induction l; introv h; simpl in *; smash_paxos2.\n    apply implies_in_add_vote_to_list; auto.\n  Qed.\n\n  Definition logged_one_b (b : one_b) (s : MAIN_state) :=\n    exists r x,\n      find_entry r (st_entries s) = Some x\n      /\\ In b (entry_one_bs x).\n\n  Lemma logged_one_b_initial_state :\n    forall b, logged_one_b b initial_state <-> False.\n  Proof.\n    introv; unfold logged_one_b; simpl; split; intro h; exrepnd; tcsp.\n  Qed.\n  Hint Rewrite logged_one_b_initial_state : paxos.\n\n  Lemma logged_one_b_initial_state_at :\n    forall b r, logged_one_b b (initial_state_at r) <-> False.\n  Proof.\n    introv; unfold logged_one_b; simpl; split; intro h; exrepnd; tcsp.\n  Qed.\n  Hint Rewrite logged_one_b_initial_state_at : paxos.\n\n  Lemma logged_one_b_one_b2entry :\n    forall b r b',\n      logged_one_b b (MkState r [one_b2entry b']) <-> b' = b.\n  Proof.\n    introv; split; intro h; tcsp.\n    { unfold logged_one_b in *; exrepnd; smash_paxos2. }\n    { subst; unfold logged_one_b; simpl.\n      exists (one_b_R b); smash_paxos2; eexists; dands; eauto.\n      simpl; tcsp. }\n  Qed.\n  Hint Rewrite logged_one_b_one_b2entry : paxos.\n\n  Lemma logged_one_b_log_one_b :\n    forall s b b' e s',\n      log_one_b b' s = (e,s')\n      -> logged_one_b b s'\n      -> (b = b' \\/ logged_one_b b s).\n  Proof.\n    introv lv i; unfold logged_one_b, log_one_b in *; exrepnd; smash_paxos2.\n    eapply find_entry_add_one_b_implies in i0; eauto; repndors; exrepnd; subst; simpl in *; tcsp;\n      try (complete (eexists; eexists; dands; eauto)); try complete (right; eauto).\n    apply in_add_one_b_to_list_implies in i1; repndors; tcsp.\n    right; eauto.\n  Qed.\n\n  Lemma logged_one_b_update_last_round :\n    forall b r s,\n      logged_one_b b (update_last_round r s) = logged_one_b b s.\n  Proof.\n    tcsp.\n  Qed.\n  Hint Rewrite logged_one_b_update_last_round : paxos.\n\n  Lemma logged_one_b_log_vote :\n    forall s b v e s',\n      log_vote v s = (e,s')\n      -> logged_one_b b s'\n      -> logged_one_b b s.\n  Proof.\n    introv lv i; unfold logged_one_b, log_vote in *; exrepnd; smash_paxos2.\n    eapply find_entry_add_vote_implies in i0; eauto; repndors; exrepnd; subst; simpl in *; tcsp;\n      try (complete (eexists; eexists; dands; eauto)); try complete (right; eauto).\n  Qed.\n\n  Lemma logged_one_b_log_my_vote :\n    forall s n e b v e' s',\n      log_my_vote n v e s = (e',s')\n      -> logged_one_b b s'\n      -> logged_one_b b s.\n  Proof.\n    introv lv i; unfold log_my_vote in *; smash_paxos2.\n    eapply logged_one_b_log_vote in i; eauto; repndors; tcsp.\n  Qed.\n\n  Lemma logged_one_b_vote2entry :\n    forall b r v,\n      logged_one_b b (MkState r [vote2entry v]) <-> False.\n  Proof.\n    introv; split; intro h; tcsp.\n    unfold logged_one_b in *; exrepnd; smash_paxos2.\n  Qed.\n  Hint Rewrite logged_one_b_vote2entry : paxos.\n\n  Lemma log_vote_preserves_logged_one_b :\n    forall s b v e s',\n      log_vote v s = (e,s')\n      -> logged_one_b b s\n      -> logged_one_b b s'.\n  Proof.\n    introv lv i; unfold logged_one_b, log_vote in *; exrepnd; smash_paxos2.\n    remember (st_entries s) as l; clear Heql.\n    exists r.\n    revert dependent e.\n    revert dependent x2.\n    induction l; introv h; simpl in *; tcsp; smash_paxos2;\n      try (complete (eexists; dands; eauto)).\n  Qed.\n\n  Lemma log_my_vote_preserves_logged_one_b :\n    forall s n e b v e' s',\n      log_my_vote n v e s = (e',s')\n      -> logged_one_b b s\n      -> logged_one_b b s'.\n  Proof.\n    introv lv i; unfold log_my_vote in *; smash_paxos2.\n    eapply log_vote_preserves_logged_one_b; eauto.\n  Qed.\n\n  Lemma add_one_b_implies_equal_entry_round :\n    forall b s e s',\n      add_one_b b s = (e, s')\n      -> one_b_R b = entry_round e.\n  Proof.\n    induction s; introv h; simpl in *; smash_paxos2.\n  Qed.\n\n  Lemma log_one_b_implies_equal_entry_round :\n    forall b s e s',\n      log_one_b b s = (e, s')\n      -> one_b_R b = entry_round e.\n  Proof.\n    unfold log_one_b; introv h; simpl in *; smash_paxos2.\n    apply add_one_b_implies_equal_entry_round in Heqx; auto.\n  Qed.\n\n  Lemma valid_my_vote_implies_not_proposer :\n    forall n v e,\n      valid_my_vote n v e = true\n      -> is_proposer n (vote_R v) = false.\n  Proof.\n    introv h.\n    unfold valid_my_vote, is_vote_from_proposer, same_node in h; smash_paxos2.\n    remember (is_proposer n (vote_R v)) as b; symmetry in Heqb; destruct b; auto.\n    eapply is_proposer_inj in h; try exact Heqb; tcsp.\n  Qed.\n\n  Definition is_vote {eo : EventOrdering} (e : Event) :=\n    exists (v : vote), trigger_op e = Some (paxos_vote v).\n\n  Definition is_one_a {eo : EventOrdering} (e : Event) :=\n    exists (a : one_a), trigger_op e = Some (paxos_one_a a).\n\n  Definition is_one_b {eo : EventOrdering} (e : Event) :=\n    exists (b : one_b), trigger_op e = Some (paxos_one_b b).\n\n  Definition logged_similar_vote (v : vote) (s : MAIN_state) :=\n    exists v',\n      logged_vote v' s /\\ vote_N v = vote_N v' /\\ vote_R v = vote_R v'.\n\n  Lemma in_add_vote_to_list :\n    forall v vs,\n      ~ In (vote_N v) (map vote_N vs)\n      -> In v (add_vote_to_list v vs).\n  Proof.\n    induction vs; introv ni; simpl in *; smash_paxos2; apply not_or in ni; repnd; tcsp.\n  Qed.\n\n  Lemma find_entry_implies_in_entry_rounds :\n    forall r l e,\n      find_entry r l = Some e\n      -> In r (map entry_round l).\n  Proof.\n    introv find.\n    applydup find_entry_implies_in in find.\n    applydup find_entry_implies_eq_entry_round in find; subst.\n    apply in_map_iff; eexists; eauto.\n  Qed.\n\n  Lemma log_vote_implies_logged :\n    forall v s1 e s2,\n      wf_state s1\n      -> log_vote v s1 = (e, s2)\n      -> logged_vote v s2 \\/ logged_similar_vote v s1.\n  Proof.\n    introv wf h.\n    unfold log_vote in *; smash_paxos2.\n    unfold logged_similar_vote, logged_vote; simpl.\n    unfold wf_state in *.\n    remember (st_entries s1) as l; clear Heql.\n    revert e x1 Heqx wf.\n    induction l; introv h wf; simpl in *; smash_paxos2.\n\n    { unfold find_entry; simpl.\n      left.\n      exists (vote_R v); smash_paxos2; eexists; dands; eauto; simpl; tcsp. }\n\n    { destruct a as [r bs vs prp]; simpl in *; subst.\n      rewrite implies_wf_entries_cons in *; simpl in *; repnd.\n      unfold add_vote_to_entry; simpl.\n      destruct (in_dec node_deq (vote_N v) (map vote_N vs)) as [d|d].\n\n      { right.\n        apply in_map_iff in d; exrepnd.\n        applydup wf1 in d0.\n        exists x; dands; tcsp.\n        exists (vote_R x); smash_paxos2.\n        eexists; dands; eauto. }\n\n      { left.\n        exists (vote_R v); smash_paxos2.\n        eexists; dands; eauto; simpl.\n        apply in_add_vote_to_list; auto. } }\n\n    { rewrite implies_wf_entries_cons in *; simpl in *; repnd.\n      pose proof (IHl e x2) as IHl; repeat (autodimp IHl hyp).\n      repndors; exrepnd.\n\n      { applydup add_vote_preserves_entry_rounds_rev in Heqx as eqs.\n        applydup find_entry_implies_eq_entry_round in IHl0 as eqr; subst.\n        applydup find_entry_implies_in_entry_rounds in IHl0 as j.\n        left.\n        exists (entry_round x); smash_paxos2.\n        { destruct wf; apply eqs in j; simpl in *; repndors; tcsp; try congruence. }\n        eexists; dands; eauto. }\n\n      { right.\n        exists v'; dands; auto.\n        exists r x; smash_paxos2.\n        apply find_entry_implies_in_entry_rounds in IHl3; tcsp. } }\n  Qed.\n\n  Lemma logged_vote_implies_logged_similar_votes :\n    forall v s, logged_vote v s -> logged_similar_vote v s.\n  Proof.\n    introv h; exists v; dands; tcsp.\n  Qed.\n  Hint Resolve logged_vote_implies_logged_similar_votes : paxos.\n\n  Lemma log_vote_preserves_logged_similar_vote :\n    forall v s1 e s2 v',\n      log_vote v s1 = (e, s2)\n      -> logged_similar_vote v' s1\n      -> logged_similar_vote v' s2.\n  Proof.\n    introv log h.\n    unfold logged_similar_vote in *; exrepnd.\n    exists v'0; dands; tcsp.\n    eapply log_vote_preserves_logged_vote; eauto.\n  Qed.\n  Hint Resolve log_vote_preserves_logged_similar_vote : paxos.\n\n  Lemma find_voted_value_from_votes_some_implies :\n    forall n vs val,\n      find_voted_value_from_votes n vs = Some val\n      -> exists v,\n        In v vs\n        /\\ vote_N v = n\n        /\\ vote_V v = val.\n  Proof.\n    induction vs; introv find; simpl in *; smash_paxos2; eauto.\n    { apply IHvs in find; exrepnd; eauto. }\n  Qed.\n\n  Lemma find_voted_value_from_votes_none_implies :\n    forall n vs,\n      find_voted_value_from_votes n vs = None\n      -> forall v, In v vs -> vote_N v <> n.\n  Proof.\n    induction vs; introv find; simpl in *; smash_paxos2; eauto.\n    introv xx; repndors; subst; tcsp.\n    apply IHvs; auto.\n  Qed.\n\n  Lemma find_latest_value_from_votes_implies :\n    forall l n v low high r v',\n      wf_entries l\n      -> find_latest_value_from_votes n v low high l = (r, v')\n      ->\n      (r = low\n       /\\ v' = v\n       /\\ forall e x,\n           In e l\n           -> low < entry_round e < high\n           -> In x (entry_votes e)\n           -> vote_N x <> n)\n      \\/ (exists e,\n             find_entry r l = Some e\n             /\\ low < r < high\n             /\\ In (mk_vote n r v') (entry_votes e)\n             /\\ forall r' e' w,\n                 low < r' < high\n                 -> find_entry r' l = Some e'\n                 -> In (mk_vote n r' w) (entry_votes e')\n                 -> r' <= r).\n  Proof.\n    induction l; introv wf find; simpl in *; smash_paxos2; tcsp; try omega;\n      try (complete (allrw implies_wf_entries_cons; repnd;\n                     apply IHl in find; repndors; exrepnd; subst; tcsp; try omega;\n                     try (complete (left; dands; tcsp; introv xx; repndors; subst; tcsp; try (complete (apply find; auto));\n                                    introv w z; eapply find_voted_value_from_votes_none_implies in Heqx; eauto));\n                     right; exists e; dands; tcsp; GC; try omega;\n                     introv h q z; smash_paxos2; try omega;\n                     try (complete (eapply find_voted_value_from_votes_none_implies in Heqx; eauto; simpl in *; tcsp));\n                     destruct (le_dec r' r); tcsp;\n                     applydup find_entry_implies_in in q;\n                     applydup wf2 in q0; repnd;\n                     applydup q1 in z; simpl in *; subst;\n                     apply find0 in z; smash_paxos2; try omega)).\n\n    { allrw implies_wf_entries_cons; repnd.\n      apply IHl in find; repndors; exrepnd; subst; tcsp; try omega.\n      right; exists a; dands; tcsp; GC.\n      { apply find_voted_value_from_votes_some_implies in Heqx; exrepnd; subst.\n        applydup wf1 in Heqx1.\n        rewrite <- Heqx0; autorewrite with paxos; auto. }\n      { introv h q z; smash_paxos2; try omega.\n        apply find_entry_implies_in in q.\n        destruct (le_dec r' (entry_round a)); tcsp.\n        applydup wf2 in q; repnd.\n        applydup q0 in z; simpl in *; subst.\n        apply find in z; smash_paxos2; try omega. } }\n\n    { allrw implies_wf_entries_cons; repnd.\n      apply IHl in find; repndors; exrepnd; subst; tcsp; try omega.\n      destruct wf.\n      apply find_entry_implies_in_entry_rounds in find1; auto. }\n  Qed.\n\n  Lemma find_voted_value_from_one_bs_prop1 :\n    forall bs v low high,\n      find_voted_value_from_one_bs v low high bs = (low,v)\n      \\/ exists b,\n        In b bs\n        /\\ find_voted_value_from_one_bs v low high bs = (one_b_maxr b, one_b_maxv b)\n        /\\ low < one_b_maxr b < high.\n  Proof.\n    induction bs; introv; simpl in *; tcsp; smash_paxos2;\n      try (complete (pose proof (IHbs v low high) as IHbs; repndors; tcsp;\n                     try (complete (right; exists a; dands; tcsp));\n                     try (complete (exrepnd; right; exists b; dands; tcsp; try omega)))).\n    pose proof (IHbs (one_b_maxv a) (one_b_maxr a) high) as IHbs; repndors; tcsp;\n      try (complete (right; exists a; dands; tcsp));\n      try (complete (exrepnd; right; exists b; dands; tcsp; try omega)).\n  Qed.\n\n  Lemma find_voted_value_from_one_bs_prop2 :\n    forall n r mr mv bs v low high,\n      In (mk_one_b n r mr mv) bs\n      -> low < mr < high\n      -> exists b,\n          In b bs\n          /\\ find_voted_value_from_one_bs v low high bs = (one_b_maxr b, one_b_maxv b)\n          /\\ mr <= one_b_maxr b < high.\n  Proof.\n    induction bs; introv i cond; simpl in *; tcsp.\n    repndors; subst; simpl in *; smash_paxos2; GC; try omega;\n      try (complete (destruct (lt_dec (one_b_maxr a) mr); try omega;\n                     pose proof (IHbs v low high) as q;\n                     repeat (autodimp q hyp); exrepnd;\n                     exists b; dands; tcsp)).\n\n    { pose proof (find_voted_value_from_one_bs_prop1 bs mv mr high) as q.\n      repndors; exrepnd.\n      { eexists; dands; eauto. }\n      { exists b; dands; tcsp; try omega. } }\n\n    { destruct (lt_dec (one_b_maxr a) mr); try omega.\n\n      { pose proof (IHbs (one_b_maxv a) (one_b_maxr a) high) as q.\n        repeat (autodimp q hyp); exrepnd.\n        exists b; dands; tcsp. }\n\n      pose proof (find_voted_value_from_one_bs_prop1 bs (one_b_maxv a) (one_b_maxr a) high) as q.\n      repndors; exrepnd.\n      { exists a; dands; tcsp; try omega. }\n      { exists b; dands; tcsp; try omega. } }\n  Qed.\n\n\n  (* === === *)\n\n\n  Lemma send_vote_from_location_step :\n    forall (eo : EventOrdering) (e : Event) n r v l m s,\n      In (send_vote (mk_vote n r v) l) (M_output_ls_on_this_one_event (PaxosLocalSys m s) e)\n      -> n = m.\n  Proof.\n    introv i.\n    apply in_M_output_ls_on_this_one_event_implies in i.\n    exrepnd; simpl in *; ginv; simpl in *.\n    paxos_dest_msg m0; try (unfold send_my_vote in *; repndors; smash_paxos2).\n  Qed.\n\n  Lemma send_vote_from_location :\n    forall (eo : EventOrdering) (e : Event) n r v l,\n      In (send_vote (mk_vote n r v) l) (M_output_sys_on_event PaxosSys e)\n      -> n = loc e.\n  Proof.\n    introv out.\n    unfold M_output_sys_on_event in *; simpl in *.\n    allrw @M_output_ls_on_event_as_run; exrepnd; simpl in *.\n    applydup M_run_ls_before_event_ls_is_paxos in out1.\n    exrepnd; subst; simpl in *; ginv; simpl in *.\n    apply send_vote_from_location_step in out0; auto.\n  Qed.\n\n  Lemma paxos_preserves_knows_step :\n    forall {eo : EventOrdering} (e : Event) d, preserves_knows_step e d.\n  Proof.\n    introv cor run eqst kn; simpl in *; unfold PaxosSys in *; simpl in *.\n    apply M_run_ls_before_event_ls_is_paxos in run; exrepnd; subst.\n    unfold state_of_component in eqst; simpl in *; ginv.\n    unfold M_run_ls_on_this_one_event.\n    unfold isCorrect in *.\n    remember (trigger_op e) as trig; destruct trig; tcsp;[]; GC; rev_Some; simpl in *.\n    unfold M_run_ls_on_input_ls, M_run_ls_on_input, on_comp; simpl.\n    paxos_dest_msg m;\n      try (complete (eexists; eexists; dands; try reflexivity; simpl; smash_paxos3)).\n  Qed.\n  Hint Resolve paxos_preserves_knows_step : paxos.\n\n  Lemma ASSUMPTION_knowledge_preserved_true :\n    forall {eo : EventOrdering} (e : Event), interpret e ASSUMPTION_knowledge_preserved_step.\n  Proof.\n    introv h; simpl in *.\n    remember (direct_pred e) as dp; symmetry in Heqdp; destruct dp; tcsp.\n    eapply knows_after_preserved_step; smash_paxos2.\n  Qed.\n  Hint Resolve ASSUMPTION_knowledge_preserved_true : paxos.\n\n  Lemma ASSUMPTION_knows_unique_true :\n    forall {eo : EventOrdering} (e : Event), interpret e ASSUMPTION_knows_unique.\n  Proof.\n    introv h; simpl in *; repnd; unfold knows_after in *; exrepnd.\n    eapply state_after_eq_state_after_implies_eq_mem in h0; try exact h1; subst; simpl in *.\n    f_equal; smash_paxos2.\n  Qed.\n  Hint Resolve ASSUMPTION_knows_unique_true : paxos.\n\n  Lemma ASSUMPTION_disseminate_new_true :\n    forall {eo : EventOrdering} (e : Event), interpret e ASSUMPTION_disseminate_new.\n  Proof.\n    introv h; simpl in *; exrepnd; subst.\n    unfold disseminate_data, knows_after in *; exrepnd; simpl in *.\n    apply data_is_in_out_implies_dmsg_is_in_out in h1; exrepnd.\n    eapply M_byz_output_sys_on_event_implies_M_output_sys_on_event in h0; eauto; smash_paxos2.\n\n    unfold M_output_sys_on_event in *; simpl in *.\n    apply M_output_ls_on_event_as_run in h0; exrepnd.\n    unfold state_after, M_state_sys_on_event, M_state_ls_on_event; simpl.\n    rewrite M_run_ls_on_event_unroll2; allrw; simpl.\n    apply M_run_ls_before_event_ls_is_paxos in h0; exrepnd; subst; simpl in *.\n\n    apply in_M_output_ls_on_this_one_event_implies in h3; exrepnd; simpl in *; ginv.\n    unfold M_run_ls_on_this_one_event; simpl; allrw; simpl.\n    unfold M_run_ls_on_input_ls, M_run_ls_on_input, on_comp, state_of_component in *; simpl in *.\n    paxos_dest_msg m0; eexists; dands; repndors; smash_paxos2;\n        try (complete (eexists; dands; try reflexivity));\n        try (complete (eapply knows_log_my_vote; eauto; smash_paxos3));\n        try (complete (eapply knows_log_vote_if_not_in; eauto; smash_paxos3));\n        try (complete (unfold same_round in *; smash_paxos3; eapply knows_log_vote_if_not_in; eauto; allrw <-; smash_paxos3)).\n  Qed.\n  Hint Resolve ASSUMPTION_disseminate_new_true : paxos.\n\n  Lemma unique_votes :\n    forall (eo : EventOrdering) (e1 e2 : Event) n r v1 v2 l1 l2,\n      In (send_vote (mk_vote n r v1) l1) (M_output_sys_on_event PaxosSys e1)\n      -> In (send_vote (mk_vote n r v2) l2) (M_output_sys_on_event PaxosSys e2)\n      -> v1 = v2.\n  Proof.\n    introv outa outb.\n    applydup send_vote_from_location in outa.\n    applydup send_vote_from_location in outb.\n    simpl in *.\n\n    assert (ex_node_e e1) as ex1 by (unfold ex_node_e; allrw; simpl; eauto).\n    assert (ex_node_e e2) as ex2 by (unfold ex_node_e; allrw; simpl; eauto).\n\n    Opaque ASSUMPTION_knowledge_preserved_step ASSUMPTION_disseminate_new ASSUMPTION_knows_unique.\n    let tac := (fun _ => eauto 3 with paxos) in\n    let smash := (fun _ => smash_paxos2) in\n    use_rule (DERIVED_RULE_disseminate_once_true\n                n (MkEventN e1 ex1) (MkEventN e1 ex1) (MkEventN e2 ex2)\n                [] [] (mk_data n r v1) (mk_data n r v2))\n             tac smash;\n      try (complete (introv xx; eapply in_M_output_sys_on_event_implies_disseminate; eauto; simpl; tcsp)).\n  Qed.\n\n  (* This could be derived from our knowledge theory *)\n  Lemma received_votes :\n    forall {eo : EventOrdering} (e : Event) n s v,\n      M_run_ls_on_event (PaxosLocalSys n initial_state) e = Some (PaxosLocalSys n s)\n      -> logged_vote v s\n      -> exists (e' : Event),\n          e' ⊑ e\n          /\\ ((trigger_op e' = Some (paxos_vote v)(* /\\ vote_N v <> n*))\n              \\/ (In (send_vote v (other_nodes n)) (M_output_ls_on_event (PaxosSys n) e') /\\ vote_N v = n)).\n  Proof.\n    intros eo e.\n    induction e as [e ind] using predHappenedBeforeInd_type.\n    introv run i.\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; ginv.\n    applydup M_run_ls_before_event_ls_is_paxos in run1; exrepnd; subst; smash_paxos2.\n\n    unfold M_run_ls_on_input_ls, M_run_ls_on_input, on_comp in run2; simpl in *.\n    paxos_dest_msg a0;\n      rewrite M_run_ls_before_event_unroll_on in run1;\n      destruct (dec_isFirst e); repeat smash_paxos2;\n        repeat (rewrite update_last_round_initial_state in *; auto; smash_paxos2;first[ idtac;[] | fail]);\n        try (complete (eapply ind in run1; eauto; eauto 3 with eo; exrepnd; exists e'; dands; eauto 3 with eo));\n        try (eapply logged_vote_log_my_vote in i; eauto;[]; repndors; subst; smash_paxos2; try omega);\n        try (eapply logged_vote_log_vote in i; eauto;[]; repndors; subst; smash_paxos2; try omega);\n        try (eapply logged_vote_log_one_b in i; eauto;[]);\n        try (complete (eapply ind in run1; eauto 3 with eo; exrepnd; eexists; dands; eauto; eauto 3 with eo));\n        try (complete (exists e; dands; eauto 3 with eo;\n                       right; unfold M_output_ls_on_event; simpl; rewrite M_run_ls_before_event_unroll_on;\n                       destruct (dec_isFirst e); tcsp; simpl;\n                       unfold PaxosSys, M_output_ls_on_this_one_event, M_run_ls_on_input_out, M_run_ls_on_input, on_comp;\n                       repeat (allrw; simpl; try (unfold send_my_vote); smash_paxos2; tcsp))).\n  Qed.\n\n  Lemma send_vote_implies :\n    forall {eo : EventOrdering} (e : Event) v dst delay,\n      (MkDMsg (paxos_vote v) dst delay) ∈ PaxosSys ⇝ e\n      -> dst = other_nodes (loc e) /\\ delay = '0.\n  Proof.\n    introv send.\n    unfold M_output_sys_on_event in *; simpl in *.\n    allrw @M_output_ls_on_event_as_run; exrepnd; simpl in *.\n    apply in_M_output_ls_on_this_one_event_implies in send0; exrepnd; simpl in *.\n    applydup M_run_ls_before_event_ls_is_paxos in send1; exrepnd; subst; simpl in *; ginv; simpl in *.\n    paxos_dest_msg m;\n      try (complete (unfold lower_out_break, PaxosLocalSys, send_my_vote in *;\n                     simpl in *; repndors; smash_paxos2; inversion send0; tcsp)).\n  Qed.\n\n  Lemma send_one_b_implies :\n    forall {eo : EventOrdering} (e : Event) b dst delay,\n      (MkDMsg (paxos_one_b b) dst delay) ∈ PaxosSys ⇝ e\n      -> dst = other_nodes (loc e) /\\ delay = '0.\n  Proof.\n    introv send.\n    unfold M_output_sys_on_event in *; simpl in *.\n    allrw @M_output_ls_on_event_as_run; exrepnd; simpl in *.\n    apply in_M_output_ls_on_this_one_event_implies in send0; exrepnd; simpl in *.\n    applydup M_run_ls_before_event_ls_is_paxos in send1; exrepnd; subst; simpl in *; ginv; simpl in *.\n    paxos_dest_msg Case;\n      try (complete (unfold lower_out_break, PaxosLocalSys, send_my_vote in *;\n                     simpl in *; repndors; smash_paxos2; inversion send0; tcsp)).\n  Qed.\n\n  Lemma sent_vote :\n    forall {eo : EventOrdering} (e : Event) L e' v,\n      AXIOM_authenticated_messages_were_sent_or_byz eo PaxosSys\n      -> have_correct_traces_before nodes L\n      -> e' ⊑ e\n      -> In e L\n      -> trigger_op e' = Some (paxos_vote v)\n      -> exists e'',\n          e'' ≺ e'\n          /\\ In (send_vote v (other_nodes (loc e''))) (M_output_sys_on_event PaxosSys e'')\n          /\\ vote_N v = loc e''.\n  Proof.\n    introv sendbyz cor lee i trig.\n    pose proof (sendbyz e' (MkAuthData (paxos_vote v) [tt]) (MkOpTrust _ None I)) as senda.\n    simpl in senda.\n    repeat (autodimp senda hyp); try (complete (allrw; simpl; tcsp));[].\n    exrepnd; repndors; exrepnd; ginv.\n\n    { repndors; tcsp; ginv; simpl in *.\n      autodimp senda5 hyp; ginv.\n      inversion senda4 as [eqloca]; clear senda4.\n      applydup send_vote_implies in senda5; repnd; subst; eauto. }\n\n    { assert (e'' ≼ e') as lte' by eauto 3 with eo.\n      pose proof (cor (loc e'') e'' e) as cor; simpl in cor.\n      pose proof (nodes_prop (loc e'')) as prp; tcsp.\n      repeat (autodimp cor hyp); tcsp; eauto 3 with eo.\n      apply correct_is_not_byzantine in senda6; tcsp; eauto 3 with eo. }\n  Qed.\n\n  Lemma wf_state_before :\n    forall {eo : EventOrdering} (e : Event) n s,\n      M_run_ls_before_event (PaxosSys n) e = Some (PaxosLocalSys n s)\n      -> wf_state s.\n  Proof.\n    intros eo e; induction e as [e ind] using predHappenedBeforeInd_type; introv eqst.\n    rewrite M_run_ls_before_event_unroll in eqst.\n    destruct (dec_isFirst e) as [d|d]; smash_paxos2.\n    apply map_option_Some in eqst; exrepnd; rev_Some.\n    pose proof (ind (local_pred e)) as ind; autodimp ind hyp; eauto 3 with eo.\n    unfold PaxosSys in *; simpl in *.\n    applydup M_run_ls_before_event_ls_is_paxos in eqst1; exrepnd; subst.\n    apply ind in eqst1; clear ind.\n    apply map_option_Some in eqst0; exrepnd; smash_paxos2.\n    unfold M_run_ls_on_input_ls, M_run_ls_on_input, on_comp in eqst2; simpl in *.\n    paxos_dest_msg Case.\n  Qed.\n\n  Lemma decisions_from_quorums_of_votes :\n    forall (eo : EventOrdering) (e : Event) r v n l,\n      AXIOM_authenticated_messages_were_sent_or_byz eo PaxosSys\n      -> have_correct_traces_before nodes [e]\n      -> In (send_decision (mk_decision n r v) l) (M_output_sys_on_event PaxosSys e)\n      -> by_quorum (fun m =>\n                      exists e',\n                        e' ≼ e\n                        /\\ loc e' = m\n                        /\\ In (send_vote (mk_vote m r v) (other_nodes m)) (M_output_sys_on_event PaxosSys e')).\n  Proof.\n    introv sendbyz cor outa.\n    unfold M_output_sys_on_event in outa; simpl in *.\n    allrw @M_output_ls_on_event_as_run; exrepnd; simpl in *.\n\n    pose proof (M_run_ls_on_event_unroll2 (PaxosSys (loc e)) e) as runOn; simpl in *.\n    rewrite outa1 in runOn; simpl in *.\n    apply in_M_output_ls_on_this_one_event_implies in outa0.\n    exrepnd; simpl in *.\n\n    unfold M_run_ls_on_this_one_event in runOn.\n    rewrite outa2 in *; simpl in *.\n    unfold M_run_ls_on_input_ls, M_run_ls_on_input, on_comp in *.\n    rewrite outa3 in *; simpl in *.\n\n    applydup M_run_ls_before_event_ls_is_paxos in outa1.\n    exrepnd; subst; simpl in *; ginv; simpl in *.\n\n    paxos_dest_msg Case;\n      try (repndors; unfold lower_out_break, PaxosLocalSys, send_my_vote in *;\n           simpl in *; repndors; smash_paxos2; try (complete (inversion outa0; tcsp))).\n\n    { Case \"Vote\".\n      applydup wf_state_before in outa1 as wf.\n      eexists; dands; eauto;[].\n      introv i; apply in_entry2vote_nodes in i; exrepnd; subst.\n\n      assert (vote_R v = vote_R v0) as eqr.\n      { applydup log_vote_preserves_wf_state in Heqx0; auto.\n        unfold log_my_vote in *; smash_paxos2.\n        { eapply wf_state_log_vote_in_entry_votes_implies in Heqx1; eauto. }\n        { eapply wf_state_log_vote_in_entry_votes_implies in Heqx0; eauto. } }\n\n      rewrite <- i0, <- eqr; autorewrite with paxos.\n\n      assert (logged_vote v x3) as logv.\n      { apply log_my_vote_implies_find_entry in Heqx1; repndors; repnd; subst; smash_paxos2.\n        eexists; eexists; dands; eauto. }\n      eapply received_votes in logv;[|exact runOn]; exrepnd.\n      repndors; repnd.\n\n      { eapply (sent_vote e [e]) in logv0; simpl; tcsp.\n        exrepnd.\n        exists e''; dands; eauto 4 with eo; auto; try congruence. }\n\n      applydup localLe_implies_loc in logv1.\n      exists e'; dands; eauto 3 with eo; try congruence.\n      unfold M_output_sys_on_event; auto; try congruence. }\n  Qed.\n\n  Lemma received_votes_before :\n    forall {eo : EventOrdering} (e : Event) n s v,\n      M_run_ls_before_event (PaxosLocalSys n initial_state) e = Some (PaxosLocalSys n s)\n      -> logged_vote v s\n      -> exists (e' : Event),\n          e' ⊏ e\n          /\\ ((trigger_op e' = Some (paxos_vote v)(* /\\ vote_N v <> n*))\n              \\/ (In (send_vote v (other_nodes n)) (M_output_ls_on_event (PaxosSys n) e') /\\ vote_N v = n)).\n  Proof.\n    introv run log.\n    rewrite M_run_ls_before_event_unroll_on in run.\n    destruct (dec_isFirst e) as [d|d]; repeat smash_paxos2.\n    eapply received_votes in run; eauto.\n    exrepnd.\n    exists e'; dands; eauto 3 with eo.\n  Qed.\n\n  Lemma logged_votes_were_sent :\n    forall {eo : EventOrdering} (e : Event) s v,\n      AXIOM_authenticated_messages_were_sent_or_byz eo PaxosSys\n      -> have_correct_traces_before nodes [e]\n      -> M_run_ls_before_event (PaxosLocalSys (loc e) initial_state) e = Some (PaxosLocalSys (loc e) s)\n      -> logged_vote v s\n      -> exists (e' : Event),\n          e' ≺ e\n          /\\ In (send_vote v (other_nodes (loc e'))) (M_output_ls_on_event (PaxosSys (loc e')) e')\n          /\\ vote_N v = loc e'.\n  Proof.\n    introv send cor run log.\n    eapply received_votes_before in log; eauto.\n    exrepnd; repndors; repnd.\n\n    { pose proof (sent_vote e [e] e' v) as q; simpl in q.\n      repeat (autodimp q hyp); eauto 3 with eo; exrepnd.\n      exists e''; dands; eauto 3 with eo. }\n\n    { applydup local_implies_loc in log1.\n      exists e'; dands; eauto 3 with eo; try congruence. }\n  Qed.\n\n  Lemma vote_after_proposal :\n    forall (eo : EventOrdering) (e : Event) n r v l,\n      AXIOM_authenticated_messages_were_sent_or_byz eo PaxosSys\n      -> have_correct_traces_before nodes [e]\n      -> In (send_vote (mk_vote n r v) l) (M_output_sys_on_event PaxosSys e)\n      -> exists e',\n          e' ≼ e\n          /\\ is_proposer (loc e') r = true\n          /\\ In (send_vote (mk_vote (loc e') r v) (other_nodes (loc e'))) (M_output_sys_on_event PaxosSys e').\n  Proof.\n    intros eo e; induction e as [e ind] using HappenedBeforeInd_type.\n    introv sendbyz cor outa.\n    unfold M_output_sys_on_event in outa; simpl in *.\n    allrw @M_output_ls_on_event_as_run; exrepnd; simpl in *.\n\n    pose proof (M_run_ls_on_event_unroll2 (PaxosSys (loc e)) e) as runOn; simpl in *.\n    rewrite outa1 in runOn; simpl in *.\n    apply in_M_output_ls_on_this_one_event_implies in outa0.\n    exrepnd; simpl in *.\n\n    unfold M_run_ls_on_this_one_event in runOn.\n    rewrite outa2 in *; simpl in *.\n    unfold M_run_ls_on_input_ls, M_run_ls_on_input, on_comp in *.\n    rewrite outa3 in *; simpl in *.\n\n    applydup M_run_ls_before_event_ls_is_paxos in outa1.\n    exrepnd; subst; simpl in *; ginv; simpl in *.\n\n    paxos_dest_msg Case.\n\n    { Case \"OneB\".\n      exists e; dands; eauto 3 with eo.\n\n      unfold M_output_sys_on_event; simpl in *.\n      allrw @M_output_ls_on_event_as_run; allrw; eexists; dands; eauto.\n      unfold M_output_ls_on_this_one_event; allrw; simpl.\n      unfold M_run_ls_on_input_out, M_run_ls_on_input, on_comp; simpl.\n      repeat smash_paxos2. }\n\n    { Case \"Vote\".\n      unfold lower_out_break in outa0; simpl in *.\n      unfold send_my_vote in outa0; smash_paxos2.\n\n      pose proof (sent_vote e [e] e v0) as q; simpl in q.\n      repeat (autodimp q hyp); eauto 3 with eo.\n      exrepnd.\n      exists e''.\n      dands; eauto 3 with eo.\n      { unfold valid_my_vote, is_vote_from_proposer in *; smash_paxos2. }\n      { rewrite <- q0; autorewrite with paxos; rewrite q0; tcsp. } }\n\n    { Case \"Vote\".\n      repndors; smash_paxos2.\n      unfold send_my_vote in outa0; smash_paxos2.\n\n      pose proof (sent_vote e [e] e v0) as q; simpl in q.\n      repeat (autodimp q hyp); eauto 3 with eo.\n      exrepnd.\n      exists e''.\n      dands; eauto 3 with eo.\n      { unfold valid_my_vote, is_vote_from_proposer in *; smash_paxos2. }\n      { rewrite <- q0; autorewrite with paxos; rewrite q0; tcsp. } }\n  Qed.\n\n  Lemma received_one_bs :\n    forall {eo : EventOrdering} (e : Event) n s b,\n      M_run_ls_on_event (PaxosLocalSys n initial_state) e = Some (PaxosLocalSys n s)\n      -> logged_one_b b s\n      -> exists (e' : Event),\n          e' ⊑ e\n          /\\ ((trigger_op e' = Some (paxos_one_b b)(* /\\ vote_N v <> n*))\n              \\/ (In (send_one_b b (other_nodes n)) (M_output_ls_on_event (PaxosSys n) e') /\\ one_b_N b = n)).\n  Proof.\n    intros eo e.\n    induction e as [e ind] using predHappenedBeforeInd_type.\n    introv run i.\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; ginv.\n    applydup M_run_ls_before_event_ls_is_paxos in run1; exrepnd; subst; smash_paxos2.\n\n    unfold M_run_ls_on_input_ls, M_run_ls_on_input, on_comp in run2; simpl in *.\n    paxos_dest_msg Case;\n      rewrite M_run_ls_before_event_unroll_on in run1;\n      destruct (dec_isFirst e); repeat smash_paxos2;\n        repeat (rewrite update_last_round_initial_state in *; auto; smash_paxos2;first[ idtac;[] | fail]);\n        try (eapply logged_one_b_log_my_vote in i; eauto;[]; repndors; subst; smash_paxos2; try omega);\n        try (eapply logged_one_b_log_vote in i; eauto;[]; repndors; subst; smash_paxos2; try omega);\n        try (eapply logged_one_b_log_one_b in i; eauto;[]; repndors; subst; smash_paxos2; try omega);\n        try (complete (eapply ind in run1; eauto; eauto 3 with eo; exrepnd; exists e'; dands; eauto 3 with eo));\n        try (complete (exists e; dands; eauto 3 with eo;\n                       right; unfold M_output_ls_on_event; simpl; rewrite M_run_ls_before_event_unroll_on;\n                       destruct (dec_isFirst e); tcsp; simpl;\n                       unfold PaxosSys, M_output_ls_on_this_one_event, M_run_ls_on_input_out, M_run_ls_on_input, on_comp;\n                       repeat (allrw; simpl; try (unfold send_my_vote); smash_paxos2; tcsp))).\n  Qed.\n\n  Lemma sent_one_b :\n    forall {eo : EventOrdering} (e : Event) L e' b,\n      AXIOM_authenticated_messages_were_sent_or_byz eo PaxosSys\n      -> have_correct_traces_before nodes L\n      -> e' ⊑ e\n      -> In e L\n      -> trigger_op e' = Some (paxos_one_b b)\n      -> exists e'',\n          e'' ≺ e'\n          /\\ In (send_one_b b (other_nodes (loc e''))) (M_output_sys_on_event PaxosSys e'')\n          /\\ one_b_N b = loc e''.\n  Proof.\n    introv sendbyz cor lee i trig.\n    pose proof (sendbyz e' (MkAuthData (paxos_one_b b) [tt]) (MkOpTrust _ None I)) as senda.\n    simpl in senda.\n    repeat (autodimp senda hyp); try (complete (allrw; simpl; tcsp));[].\n    exrepnd; repndors; exrepnd; ginv.\n\n    { repndors; tcsp; ginv; simpl in *.\n      autodimp senda5 hyp; ginv.\n      inversion senda4 as [eqloca]; clear senda4.\n      applydup send_one_b_implies in senda5; repnd; subst; eauto. }\n\n    { assert (e'' ≼ e') as lte' by eauto 3 with eo.\n      pose proof (cor (loc e'') e'' e) as cor; simpl in cor.\n      pose proof (nodes_prop (loc e'')) as prp; tcsp.\n      repeat (autodimp cor hyp); tcsp; eauto 3 with eo.\n      apply correct_is_not_byzantine in senda6; tcsp; eauto 3 with eo. }\n  Qed.\n\n  Lemma logged_one_bs_were_sent_on :\n    forall {eo : EventOrdering} (e : Event) s b,\n      AXIOM_authenticated_messages_were_sent_or_byz eo PaxosSys\n      -> have_correct_traces_before nodes [e]\n      -> M_run_ls_on_event (PaxosLocalSys (loc e) initial_state) e = Some (PaxosLocalSys (loc e) s)\n      -> logged_one_b b s\n      -> exists (e' : Event),\n          e' ≼ e\n          /\\ In (send_one_b b (other_nodes (loc e'))) (M_output_ls_on_event (PaxosSys (loc e')) e')\n          /\\ one_b_N b = loc e'.\n  Proof.\n    introv send cor run log.\n    eapply received_one_bs in log; eauto.\n    exrepnd; repndors; repnd.\n\n    { pose proof (sent_one_b e [e] e' b) as q; simpl in q.\n      repeat (autodimp q hyp); eauto 3 with eo; exrepnd.\n      exists e''; dands; eauto 4 with eo. }\n\n    { applydup localLe_implies_loc in log1.\n      exists e'; dands; eauto 3 with eo; try congruence. }\n  Qed.\n\n  Lemma send_vote_implies_current_round :\n    forall {eo : EventOrdering} (e : Event) v l,\n      send_vote v l ∈ PaxosSys ⇝ e\n      -> exists s1 s2,\n        M_run_ls_before_event (PaxosLocalSys (loc e) initial_state) e = Some (PaxosLocalSys (loc e) s1)\n        /\\ M_run_ls_on_event (PaxosLocalSys (loc e) initial_state) e = Some (PaxosLocalSys (loc e) s2)\n        /\\ (is_one_b e \\/ is_vote e)\n        /\\ st_current_round s1 <= vote_R v\n        /\\ logged_similar_vote v s2.\n  Proof.\n    introv send.\n    unfold M_output_sys_on_event in send; simpl in *.\n    allrw @M_output_ls_on_event_as_run; exrepnd; simpl in *.\n    apply in_M_output_ls_on_this_one_event_implies in send0; exrepnd; simpl in *.\n    applydup M_run_ls_before_event_ls_is_paxos in send1.\n    exrepnd; subst; simpl in *; ginv; simpl in *.\n    applydup wf_state_before in send1 as wf.\n    unfold PaxosSys in *; allrw.\n    rewrite M_run_ls_on_event_unroll2; allrw; simpl.\n    unfold M_run_ls_on_this_one_event, M_run_ls_on_input_ls, M_run_ls_on_input, on_comp; simpl; allrw; simpl.\n    clear send1.\n\n    paxos_dest_msg Case; eexists; eexists; dands; try reflexivity; smash_paxos2;\n      try (complete (unfold is_one_b, is_vote; allrw; eauto));\n      try (complete (applydup log_vote_implies_logged in Heqx5; repndors; smash_paxos2));\n      try (complete (repndors; smash_paxos2;\n                     unfold lower_out_break, send_my_vote in *; simpl in *; smash_paxos2;\n                     unfold has_left_round, log_my_vote in *; smash_paxos2;\n                     applydup log_vote_implies_logged in Heqx1; repndors; smash_paxos2)).\n  Qed.\n\n  Lemma logged_votes_were_sent_on :\n    forall {eo : EventOrdering} (e : Event) s v,\n      AXIOM_authenticated_messages_were_sent_or_byz eo PaxosSys\n      -> have_correct_traces_before nodes [e]\n      -> M_run_ls_on_event (PaxosLocalSys (loc e) initial_state) e = Some (PaxosLocalSys (loc e) s)\n      -> logged_vote v s\n      -> exists (e' : Event),\n          e' ≼ e\n          /\\ In (send_vote v (other_nodes (loc e'))) (M_output_ls_on_event (PaxosSys (loc e')) e')\n          /\\ vote_N v = loc e'.\n  Proof.\n    introv send cor run log.\n    eapply received_votes in log; eauto.\n    exrepnd; repndors; repnd.\n\n    { pose proof (sent_vote e [e] e' v) as q; simpl in q.\n      repeat (autodimp q hyp); eauto 3 with eo; exrepnd.\n      exists e''; dands; eauto 4 with eo. }\n\n    { applydup localLe_implies_loc in log1.\n      exists e'; dands; eauto 3 with eo; try congruence. }\n  Qed.\n\n  Lemma unique_votes2 :\n    forall (eo : EventOrdering) (e1 e2 : Event) v1 v2 l1 l2,\n      AXIOM_authenticated_messages_were_sent_or_byz eo PaxosSys\n      -> have_correct_traces_before nodes [e1,e2]\n      -> In (send_vote v1 l1) (M_output_sys_on_event PaxosSys e1)\n      -> In (send_vote v2 l2) (M_output_sys_on_event PaxosSys e2)\n      -> vote_R v1 = vote_R v2\n      -> vote_V v1 = vote_V v2.\n  Proof.\n    introv send cor outa outb eqr.\n    destruct v1 as [n1 r1 v1].\n    destruct v2 as [n2 r2 v2].\n    simpl in *; subst.\n    apply vote_after_proposal in outa; eauto 3 with eo.\n    apply vote_after_proposal in outb; eauto 3 with eo.\n    exrepnd.\n\n    assert (loc e'0 = loc e') as eqloc.\n    { eapply is_proposer_inj in outa2; try exact outb2; auto. }\n    rewrite eqloc in *.\n    eapply unique_votes in outa0; try exact outb0; auto.\n  Qed.\n\n  Lemma send_vote_implies_current_round2 :\n    forall {eo : EventOrdering} (e : Event) v l,\n      AXIOM_authenticated_messages_were_sent_or_byz eo PaxosSys\n      -> have_correct_traces_before nodes [e]\n      -> send_vote v l ∈ PaxosSys ⇝ e\n      -> exists s1 s2,\n        M_run_ls_before_event (PaxosLocalSys (loc e) initial_state) e = Some (PaxosLocalSys (loc e) s1)\n        /\\ M_run_ls_on_event (PaxosLocalSys (loc e) initial_state) e = Some (PaxosLocalSys (loc e) s2)\n        /\\ (is_one_b e \\/ is_vote e)\n        /\\ st_current_round s1 <= vote_R v\n        /\\ logged_vote v s2.\n  Proof.\n    introv ax cor send.\n    applydup send_vote_implies_current_round in send; exrepnd.\n    exists s1 s2; dands; auto.\n    unfold logged_similar_vote in *; exrepnd.\n    dup send0 as log.\n    eapply logged_votes_were_sent_on in log; eauto; exrepnd.\n    eapply unique_votes2 in send; try exact log2; smash_paxos2; eauto 3 with eo;[].\n    assert (v' = v) by (destruct v, v'; simpl in *; subst; tcsp); subst; auto.\n  Qed.\n\n  Lemma send_one_b_implies_current_round :\n    forall {eo : EventOrdering} (e : Event) b l,\n      send_one_b b l ∈ PaxosSys ⇝ e\n      -> exists s1 s2,\n        M_run_ls_before_event (PaxosLocalSys (loc e) initial_state) e = Some (PaxosLocalSys (loc e) s1)\n        /\\ M_run_ls_on_event (PaxosLocalSys (loc e) initial_state) e = Some (PaxosLocalSys (loc e) s2)\n        /\\ is_one_a e\n        /\\ st_current_round s1 < st_current_round s2\n        /\\ st_current_round s2 = one_b_R b\n        /\\ (one_b_maxr b,one_b_maxv b) = find_latest_value_from_votes (loc e) (default_value (loc e)) 0 (st_current_round s2) (st_entries s1).\n  Proof.\n    introv send.\n    unfold M_output_sys_on_event in send; simpl in *.\n    allrw @M_output_ls_on_event_as_run; exrepnd; simpl in *.\n    apply in_M_output_ls_on_this_one_event_implies in send0; exrepnd; simpl in *.\n    applydup M_run_ls_before_event_ls_is_paxos in send1.\n    exrepnd; subst; simpl in *; ginv; simpl in *.\n    unfold PaxosSys in *; allrw.\n    rewrite M_run_ls_on_event_unroll2; allrw; simpl.\n    unfold M_run_ls_on_this_one_event, M_run_ls_on_input_ls, M_run_ls_on_input, on_comp; simpl; allrw; simpl.\n    clear send1.\n\n    paxos_dest_msg Case;\n      repndors; smash_paxos2;\n        try (complete (unfold lower_out_break, send_my_vote in *; simpl in *; repeat smash_paxos2; inversion send0));\n        eexists; eexists; dands; try reflexivity; try (complete (unfold is_one_a; allrw; eauto));\n          try (complete (unfold new_round in *; smash_paxos2;\n                         apply implies_eq_snd in Heqx1; simpl in *; subst;\n                         unfold log_one_b; smash_paxos2; try omega)).\n  Qed.\n\n  Lemma proposal_from_one_bs :\n    forall (eo : EventOrdering) (e : Event) v l,\n      AXIOM_authenticated_messages_were_sent_or_byz eo PaxosSys\n      -> have_correct_traces_before nodes [e]\n      -> In (send_vote v l) (M_output_sys_on_event PaxosSys e)\n      -> vote_N v = loc e\n      -> is_proposer (loc e) (vote_R v) = true\n      -> exists bs,\n          forms_quorum (map one_b_N bs) = true\n          /\\ vote_V v = snd (find_voted_value_from_one_bs (default_value (loc e)) 0 (vote_R v) bs)\n          /\\ forall b,\n            In b bs\n            -> exists e',\n              e' ≺ e\n              /\\ one_b_R b = vote_R v\n              /\\ one_b_N b = loc e'\n              /\\ In (send_one_b b (other_nodes (loc e'))) (M_output_sys_on_event PaxosSys e').\n  Proof.\n    intros eo e; induction e as [e ind] using HappenedBeforeInd_type.\n    introv sendbyz cor outa eqv isp.\n    unfold M_output_sys_on_event in outa; simpl in *.\n    allrw @M_output_ls_on_event_as_run; exrepnd; simpl in *.\n\n    pose proof (M_run_ls_on_event_unroll2 (PaxosSys (loc e)) e) as runOn; simpl in *.\n    rewrite outa1 in runOn; simpl in *.\n    apply in_M_output_ls_on_this_one_event_implies in outa0.\n    exrepnd; simpl in *.\n\n    unfold M_run_ls_on_this_one_event in runOn.\n    rewrite outa2 in *; simpl in *.\n    unfold M_run_ls_on_input_ls, M_run_ls_on_input, on_comp in *.\n    rewrite outa3 in *; simpl in *.\n\n    applydup M_run_ls_before_event_ls_is_paxos in outa1.\n    exrepnd; subst; simpl in *; ginv; simpl in *.\n\n    paxos_dest_msg Case.\n\n    { Case \"OneB\".\n      exists (entry_one_bs x0); dands; tcsp; try (complete (allrw; simpl; auto)).\n      introv i.\n\n      assert (logged_one_b b0 x5) as log.\n      { eapply log_vote_preserves_logged_one_b; eauto.\n        eexists; eexists; dands; eauto; smash_paxos2. }\n\n      eapply logged_one_bs_were_sent_on in log; eauto; tcsp.\n      exrepnd.\n\n      assert (e' ≺ e) as lte.\n      { destruct log1 as [w|w]; tcsp; subst;[].\n        apply send_one_b_implies_current_round in log2 as z; exrepnd.\n        unfold is_one_a in *; exrepnd.\n        rewrite z6 in *; ginv. }\n\n      exists e'; dands; auto; try congruence.\n      unfold same_round in *; smash_paxos2.\n      applydup log_one_b_implies_equal_entry_round in Heqx1.\n      assert (In x0 (st_entries x1)) as j.\n      { apply log_one_b_implies_find_entry in Heqx1; apply find_entry_implies_in in Heqx1; auto. }\n      assert (wf_state s') as wfs by (eapply wf_state_before; eauto).\n      eapply log_one_b_preserves_wf_state in wfs; eauto.\n      apply wfs in j; repnd.\n      apply j0 in i; try congruence. }\n\n    { Case \"Vote\".\n      unfold lower_out_break in outa0; simpl in *.\n      unfold send_my_vote in outa0; smash_paxos2.\n      rename_hyp_with valid_my_vote valid.\n      apply valid_my_vote_implies_not_proposer in valid; smash_paxos2. }\n\n    { Case \"Vote\".\n      repndors; smash_paxos2.\n      unfold lower_out_break in outa0; simpl in *.\n      unfold send_my_vote in outa0; smash_paxos2.\n      rename_hyp_with valid_my_vote valid.\n      apply valid_my_vote_implies_not_proposer in valid; smash_paxos2. }\n  Qed.\n\n  Lemma round_increases_step :\n    forall {eo : EventOrdering} (e : Event) n s1 s2,\n      M_run_ls_on_this_one_event (PaxosLocalSys n s1) e = Some (PaxosLocalSys n s2)\n      -> st_current_round s1 <= st_current_round s2.\n  Proof.\n    introv run.\n    apply option_map_Some in run; exrepnd.\n    unfold M_run_ls_on_this_one_event, M_run_ls_on_input_ls, M_run_ls_on_input, on_comp in *; simpl in *.\n    paxos_dest_msg Case; try omega;\n      try (rename_hyp_with log_one_b logb; apply implies_eq_snd in logb; simpl in *; subst; unfold log_one_b in *; smash_paxos2; try omega);\n      try (rename_hyp_with log_my_vote logm; apply implies_eq_snd in logm; simpl in *; subst; unfold log_my_vote in *; smash_paxos2; try omega);\n      try (rename_hyp_with log_vote logv; apply implies_eq_snd in logv; simpl in *; subst; unfold log_vote in *; smash_paxos2; try omega).\n  Qed.\n\n  Lemma round_increases_on :\n    forall {eo : EventOrdering} (e1 e2 : Event) s1 s2,\n      e1 ⊑ e2\n      -> M_run_ls_on_event (PaxosLocalSys (loc e1) initial_state) e1 = Some (PaxosLocalSys (loc e1) s1)\n      -> M_run_ls_on_event (PaxosLocalSys (loc e2) initial_state) e2 = Some (PaxosLocalSys (loc e2) s2)\n      -> st_current_round s1 <= st_current_round s2.\n  Proof.\n    intros eo e1 e2; induction e2 as [e2 ind] using predHappenedBeforeInd_type; introv lee runa runb.\n    apply decomp_local_le in lee; repndors; repnd; subst.\n\n    { rewrite runa in runb; smash_paxos2. }\n\n    pose proof (ind (local_pred e2)) as ind; autodimp ind hyp.\n    pose proof (ind s1) as ind.\n    rewrite M_run_ls_on_event_unroll in runb.\n    destruct (dec_isFirst e2) as [d|d]; smash_paxos2.\n    apply map_option_Some in runb; exrepnd; rev_Some.\n    applydup M_run_ls_before_event_ls_is_paxos in runb1; exrepnd; subst.\n    rewrite <- M_run_ls_before_event_as_M_run_ls_on_event_pred in ind; eauto 3 with eo.\n    rewrite runb1 in ind.\n    pose proof (ind s') as ind.\n    repeat (autodimp ind hyp).\n    eapply le_trans;eauto.\n    apply round_increases_step in runb0; auto.\n  Qed.\n\n  Lemma round_increases_on_before :\n    forall {eo : EventOrdering} (e1 e2 : Event) s1 s2,\n      e1 ⊏ e2\n      -> M_run_ls_on_event (PaxosLocalSys (loc e1) initial_state) e1 = Some (PaxosLocalSys (loc e1) s1)\n      -> M_run_ls_before_event (PaxosLocalSys (loc e2) initial_state) e2 = Some (PaxosLocalSys (loc e2) s2)\n      -> st_current_round s1 <= st_current_round s2.\n  Proof.\n    introv lte runa runb.\n    apply local_implies_pred_or_local in lte; repndors; exrepnd.\n\n    { rewrite M_run_ls_before_event_as_M_run_ls_on_event_pred in runb; eauto 3 with eo.\n      apply pred_implies_local_pred in lte; subst; autorewrite with eo in *.\n      rewrite runa in runb; smash_paxos2. }\n\n    rewrite M_run_ls_before_event_as_M_run_ls_on_event_pred in runb; eauto 3 with eo.\n    assert (loc e2 = loc (local_pred e2)) as eqloc by (autorewrite with eo; auto).\n    rewrite eqloc in runb.\n    eapply round_increases_on in runb; try exact runa; auto 2 with eo.\n    apply pred_implies_local_pred in lte1; subst; eauto 2 with eo.\n  Qed.\n\n  Lemma preserves_logged_vote_step :\n    forall {eo : EventOrdering} (e : Event) n s1 s2 v,\n      M_run_ls_on_this_one_event (PaxosLocalSys n s1) e = Some (PaxosLocalSys n s2)\n      -> logged_vote v s1\n      -> logged_vote v s2.\n  Proof.\n    introv run log.\n    apply option_map_Some in run; exrepnd.\n    unfold M_run_ls_on_this_one_event, M_run_ls_on_input_ls, M_run_ls_on_input, on_comp in *; simpl in *.\n    paxos_dest_msg Case.\n  Qed.\n\n  Lemma preserves_logged_vote_on_before :\n    forall {eo : EventOrdering} (e1 e2 : Event) s1 s2 v,\n      e1 ⊏ e2\n      -> M_run_ls_on_event (PaxosLocalSys (loc e1) initial_state) e1 = Some (PaxosLocalSys (loc e1) s1)\n      -> M_run_ls_before_event (PaxosLocalSys (loc e2) initial_state) e2 = Some (PaxosLocalSys (loc e2) s2)\n      -> logged_vote v s1\n      -> logged_vote v s2.\n  Proof.\n    intros eo e1 e2; induction e2 as [e2 ind] using predHappenedBeforeInd_type; introv lte runa runb log.\n    apply local_implies_pred_or_local in lte; exrepnd; repndors; exrepnd.\n\n    { rewrite M_run_ls_before_event_as_M_run_ls_on_event_pred in runb; eauto 3 with eo.\n      apply pred_implies_local_pred in lte; subst; autorewrite with eo in *.\n      rewrite runa in runb; smash_paxos2. }\n\n    pose proof (ind e) as ind; autodimp ind hyp.\n    rewrite M_run_ls_before_event_as_M_run_ls_on_event_pred in runb; eauto 3 with eo.\n    assert (loc e2 = loc (local_pred e2)) as eqloc by (autorewrite with eo; auto).\n    rewrite eqloc in runb.\n    apply pred_implies_local_pred in lte1; subst.\n\n    rewrite M_run_ls_on_event_unroll2 in runb; apply map_option_Some in runb; exrepnd; rev_Some.\n    applydup M_run_ls_before_event_ls_is_paxos in runb1; exrepnd; subst.\n    pose proof (ind s1 s' v) as ind; repeat (autodimp ind hyp).\n    eapply preserves_logged_vote_step; eauto.\n  Qed.\n\n  Lemma sent_one_b_pos :\n    forall {eo : EventOrdering} (e : Event) n r maxr maxv l,\n      In (send_one_b (mk_one_b n r maxr maxv) l) (M_output_sys_on_event PaxosSys e)\n      -> 0 < r.\n  Proof.\n    introv send.\n    apply send_one_b_implies_current_round in send; exrepnd; simpl in *; omega.\n  Qed.\n\n  Lemma sent_vote_pos :\n    forall {eo : EventOrdering} (e : Event) n r v l,\n      AXIOM_authenticated_messages_were_sent_or_byz eo PaxosSys\n      -> have_correct_traces_before nodes [e]\n      -> In (send_vote (mk_vote n r v) l) (M_output_sys_on_event PaxosSys e)\n      -> 0 < r.\n  Proof.\n    introv ax cor send.\n    apply vote_after_proposal in send; auto; exrepnd.\n    apply proposal_from_one_bs in send0; auto; eauto 3 with eo; exrepnd; simpl in *.\n    pose proof (forms_quorum_pos (map one_b_N bs)) as h; autodimp h hyp.\n    destruct bs; simpl in *; tcsp.\n    pose proof (send3 o) as send3; autodimp send3 hyp; exrepnd; tcsp; subst.\n    destruct o; simpl in *.\n    apply sent_one_b_pos in send5; auto.\n  Qed.\n\n  Lemma sent_decision_pos :\n    forall {eo : EventOrdering} (e : Event) n r v l,\n      AXIOM_authenticated_messages_were_sent_or_byz eo PaxosSys\n      -> have_correct_traces_before nodes [e]\n      -> In (send_decision (mk_decision n r v) l) (M_output_sys_on_event PaxosSys e)\n      -> 0 < r.\n  Proof.\n    introv ax cor send.\n    apply decisions_from_quorums_of_votes in send; auto.\n    unfold by_quorum in send; exrepnd.\n    pose proof (forms_quorum_pos q) as h; autodimp h hyp.\n    destruct q; simpl in *; tcsp.\n    pose proof (send0 n0) as send0; autodimp send0 hyp; exrepnd; tcsp.\n    apply sent_vote_pos in send2; eauto 3 with eo.\n  Qed.\n\n  Lemma send_one_b_implies_send_vote :\n    forall {eo : EventOrdering} (e : Event) b l,\n      AXIOM_authenticated_messages_were_sent_or_byz eo PaxosSys\n      -> have_correct_traces_before nodes [e]\n      -> 0 < one_b_maxr b\n      -> send_one_b b l ∈ PaxosSys ⇝ e\n      -> exists e',\n        e' ≺ e\n        /\\ send_vote (mk_vote (loc e') (one_b_maxr b) (one_b_maxv b)) (other_nodes (loc e')) ∈ PaxosSys ⇝ e'.\n  Proof.\n    introv ax cor ltr send.\n    apply send_one_b_implies_current_round in send; exrepnd.\n    symmetry in send1.\n    applydup wf_state_before in send0 as wf.\n    apply find_latest_value_from_votes_implies in send1; tcsp;[].\n    repndors; exrepnd; try omega.\n\n    assert (logged_vote (mk_vote (loc e) (one_b_maxr b) (one_b_maxv b)) s1) as log.\n    { exists (one_b_maxr b) e0; dands; tcsp. }\n    eapply logged_votes_were_sent in log; eauto;[].\n    exrepnd; simpl in *.\n    rewrite log0 in log2.\n    exists e'; dands; tcsp.\n  Qed.\n\n  Lemma vote_after_decision :\n    forall (eo : EventOrdering) (e1 e2 : Event) n1 n2 r1 r2 v1 v2 l1 l2,\n      AXIOM_authenticated_messages_were_sent_or_byz eo PaxosSys\n      -> have_correct_traces_before nodes [e1, e2]\n      -> In (send_decision (mk_decision n1 r1 v1) l1) (M_output_sys_on_event PaxosSys e1)\n      -> In (send_vote (mk_vote n2 r2 v2) l2) (M_output_sys_on_event PaxosSys e2)\n      -> r1 <= r2\n      -> v1 = v2.\n  Proof.\n    intros eo e1 e2; induction e2 as [e2 ind] using HappenedBeforeInd_type.\n    introv sendbyz cor outa outb ltr.\n\n    applydup sent_decision_pos in outa as posa; eauto 3 with eo;[].\n    dup outa as senddec.\n    apply decisions_from_quorums_of_votes in outa; eauto 2 with eo;[].\n\n    apply le_lt_or_eq in ltr; repndors;\n      [|subst; unfold by_quorum in outa; exrepnd;\n        pose proof (forms_quorum_pos q) as h; autodimp h hyp;\n        destruct q; simpl in *; tcsp;\n        pose proof (outa0 n) as outa0; autodimp outa0 hyp; exrepnd;\n        eapply unique_votes2 in outb; try exact outa2; simpl in *; tcsp; eauto 3 with eo];[].\n\n    apply vote_after_proposal in outb; eauto 3 with eo;[]; exrepnd.\n    apply proposal_from_one_bs in outb0; eauto 3 with eo;[]; exrepnd.\n    simpl in *.\n    unfold by_quorum in outa; exrepnd.\n\n    pose proof (quorum_intersection q (map one_b_N bs)) as quor.\n    repeat (autodimp quor hyp); exrepnd.\n    apply in_map_iff in quor0; exrepnd; subst.\n    apply outa0 in quor1 as quora.\n    apply outb3 in quor2 as quorb.\n    hide_hyp outa0; hide_hyp outb3.\n    exrepnd.\n    destruct x as [n r maxr maxv]; simpl in *; subst.\n\n    applydup send_vote_implies_current_round2 in quora0 as runa; exrepnd; simpl in *; eauto 3 with eo;[].\n    applydup send_one_b_implies_current_round in quorb0 as runb; exrepnd; simpl in *;[].\n\n    pose proof (tri_if_same_loc e'1 e'0) as tri; autodimp tri hyp.\n    destruct tri as [tri|[tri|tri] ];\n      [|subst; unfold is_one_a, is_one_b, is_vote in *; exrepnd;\n        rewrite runb5 in *; repndors; exrepnd; ginv\n       |eapply round_increases_on_before in runb2; try exact runa0; auto; try omega];[].\n\n    assert (logged_vote (mk_vote (loc e'1) r1 v1) s0) as log.\n    { eapply preserves_logged_vote_on_before; eauto. }\n\n    symmetry in runb1.\n    dup runb1 as fv.\n\n    applydup wf_state_before in runb0 as wf.\n    apply find_latest_value_from_votes_implies in fv; tcsp;[].\n    destruct fv as [fv|fv]; repnd.\n    { unfold logged_vote in log; exrepnd.\n      apply find_entry_implies_in in log0.\n      apply fv in log1; simpl in *; tcsp.\n      apply wf in log0; repnd.\n      apply log0 in log1; simpl in *; subst; split; tcsp. }\n\n    exrepnd.\n    assert (r1 <= maxr) as ler.\n    { unfold logged_vote in log; exrepnd.\n      rewrite <- quorb3 in fv0.\n      eapply fv0 in log1; auto; try omega.\n      applydup find_entry_implies_eq_entry_round in log0; subst.\n      applydup find_entry_implies_in in log0.\n      apply wf in log2; simpl in *; subst; auto; repnd.\n      apply log2 in log1; simpl in *; subst; auto. }\n\n    dup quor2 as fbs.\n    apply (find_voted_value_from_one_bs_prop2 _ _ _ _ _ (default_value (loc e')) 0 r2) in fbs; exrepnd; try omega;[].\n    rewrite fbs2; simpl.\n\n    show_hyp outb3.\n    apply outb3 in fbs1; exrepnd.\n    destruct b as [n r maxr' maxv']; simpl in *.\n    apply send_one_b_implies_send_vote in fbs4; simpl; tcsp; try omega; eauto 4 with eo;[].\n    exrepnd; simpl in *.\n\n    pose proof (ind e'3) as ind.\n    autodimp ind hyp; eauto 3 with eo;[].\n    pose proof (ind n1 (loc e'3) r1 maxr' v1 maxv' l1 (other_nodes (loc e'3))) as ind.\n    repeat (autodimp ind hyp); eauto 5 with eo; try omega.\n  Qed.\n\n  (* This could be derived from our knowledge theory *)\n  Lemma safety_le :\n    forall (eo : EventOrdering) (e1 e2 : Event) n1 n2 r1 r2 v1 v2 l1 l2,\n      AXIOM_authenticated_messages_were_sent_or_byz eo PaxosSys\n      -> have_correct_traces_before nodes [e1, e2]\n      -> r1 <= r2\n      -> In (send_decision (mk_decision n1 r1 v1) l1) (M_output_sys_on_event PaxosSys e1)\n      -> In (send_decision (mk_decision n2 r2 v2) l2) (M_output_sys_on_event PaxosSys e2)\n      -> v1 = v2.\n  Proof.\n    introv sendbyz cor ler outa outb.\n    apply decisions_from_quorums_of_votes in outb; eauto 2 with eo;[].\n    unfold by_quorum in *; exrepnd.\n    pose proof (forms_quorum_pos q) as h; autodimp h hyp.\n    destruct q; simpl in *; tcsp.\n    pose proof (outb0 n) as outb0; autodimp outb0 hyp; exrepnd.\n    eapply vote_after_decision in outa; try exact outb2; eauto 3 with eo.\n  Qed.\n\n  Lemma safety :\n    forall (eo : EventOrdering) (e1 e2 : Event) n1 n2 r1 r2 v1 v2 l1 l2,\n      AXIOM_authenticated_messages_were_sent_or_byz eo PaxosSys\n      -> have_correct_traces_before nodes [e1, e2]\n      -> In (send_decision (mk_decision n1 r1 v1) l1) (M_output_sys_on_event PaxosSys e1)\n      -> In (send_decision (mk_decision n2 r2 v2) l2) (M_output_sys_on_event PaxosSys e2)\n      -> v1 = v2.\n  Proof.\n    introv sendbyz cor outa outb.\n    destruct (lt_dec r1 r2) as [d|d].\n    { eapply safety_le in outb; try exact outa; auto; try omega. }\n    { eapply safety_le in outa; try exact outb; auto; try omega; eauto 3 with eo. }\n  Qed.\n\nEnd AbstractPaxos.\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/Paxos/AbstractPaxos.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.27013580625692174}}
{"text": "Require Export ComponentSM3.\nRequire Export TrIncprops2.\n\n\nSection TrIncsm_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 les_update_counter :\n    forall l a b, les l (update_counter a b l).\n  Proof.\n    induction l; introv; simpl; tcsp.\n    destruct a0; simpl; tcsp.\n    dands; try apply max_prop2; apply les_reflexive.\n  Qed.\n  Hint Resolve les_update_counter : minbft.\n\n  Lemma getCounter_nil :\n    forall cid, getCounter cid [] = 0.\n  Proof.\n    introv; unfold getCounter; simpl; destruct cid; auto.\n  Qed.\n  Hint Rewrite getCounter_nil : minbft.\n\n  Lemma getCounter_0_cons :\n    forall a l, getCounter 0 (a :: l) = a.\n  Proof.\n    tcsp.\n  Qed.\n  Hint Rewrite getCounter_0_cons : minbft.\n\n  Lemma pos_implies_not_all_zeros_nil :\n    forall cid new,\n      0 < new\n      -> ~ all_zeros (update_counter cid new []).\n  Proof.\n    induction cid; introv h q; simpl in *; tcsp.\n    { destruct new; simpl in *; tcsp. }\n    { apply IHcid in q; tcsp. }\n  Qed.\n  Hint Resolve pos_implies_not_all_zeros_nil : minbft.\n\n  Lemma implies_lts_update_counter :\n    forall cid new l,\n      getCounter cid l < new\n      -> lts l (update_counter cid new l).\n  Proof.\n    induction cid; introv h; simpl in *; tcsp.\n\n    { destruct l; simpl in *; tcsp; autorewrite with minbft in *.\n\n      { destruct new; simpl; tcsp. }\n\n      { left; dands; eauto 3 with minbft; try apply les_reflexive.\n        apply Nat.max_lt_iff; tcsp. } }\n\n    { destruct l; simpl in *; tcsp; autorewrite with minbft in *; eauto 3 with minbft. }\n  Qed.\n  Hint Resolve implies_lts_update_counter : minbft.\n\n  Lemma USIG_sm_mon :\n    forall n l s1 s2,\n      trusted_run_sm_on_inputs s1 (USIG_comp n) l = s2\n      -> trinc_counters s1 = trinc_counters s2\n         \\/\n         lts (trinc_counters s1) (trinc_counters s2).\n  Proof.\n    unfold trusted_run_sm_on_inputs.\n    induction l; introv run; simpl in *; subst; tcsp.\n    destruct a; repnd; simpl in *; tcsp;[].\n    unfold update_state in *; simpl in *.\n    autorewrite with comp in *.\n\n    unfold try_update_TRINC in *; simpl in *; dest_cases w;[].\n\n    match goal with\n    | [ |- _ \\/ lts (trinc_counters ?a) (trinc_counters ?b) ] =>\n      pose proof (IHl (update_TRINC msg0 msg s1) b) as IHl\n    end; repeat (autodimp IHl hyp); simpl in *; repndors; tcsp; try omega; smash_minbft2.\n\n    { right; rewrite <- IHl; eauto 3 with minbft. }\n\n    { right; eapply lts_transitive;[|eauto]; eauto 3 with minbft. }\n  Qed.\n\nEnd TrIncsm_mon.\n\n\nHint Resolve les_update_counter : minbft.\nHint Resolve pos_implies_not_all_zeros_nil : minbft.\nHint Resolve implies_lts_update_counter : minbft.\n\nHint Rewrite getCounter_nil : minbft.\nHint Rewrite getCounter_0_cons : 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/TrIncsm_mon.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.2701138290241814}}
{"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.\n\n\n(*****************************************************************************)\n(*                   We define now the Mini-ML dynamic semantics \n                     in the style of Natural Semantics  *)\n(*****************************************************************************)\n\nInductive val_of_with_injection : label -> val -> oitenv -> expr -> val -> Prop :=\n| Val_of_with_injection_Num :\n  forall (l:label) (vl:val) (v:Z) (c:oitenv),\n    val_of_with_injection l vl c (Num v) (V_Num v)\n| Val_of_with_injection_Ident :\n  forall (l:label) (vl v:val) (c:oitenv) (i:identifier) (uu:oitval),\n    assoc_ident_in_oitenv i c = Ident_in_oitenv uu\n    -> Some v = instantiate_oitval l vl uu\n    -> val_of_with_injection l vl c (Var i) v\n| Val_of_with_injection_Lambda :\n  forall (l:label) (vl v:val) (c:oitenv) (c':env) (x:identifier) (e:expr),\n    Some c' = instantiate_oitenv l vl c\n    -> v = V_Closure x e c'\n    -> val_of_with_injection l vl c (Lambda x e) v\n| Val_of_with_injection_Rec :\n  forall (l:label) (vl v:val) (c:oitenv) (c':env) (f x:identifier) (e:expr),\n    Some c' = instantiate_oitenv l vl c\n    -> v = V_Rec_Closure f x e c'\n    -> val_of_with_injection l vl c (Rec f x e) v\n| Val_of_with_injection_Apply :\n  forall (l:label) (vl:val) (c:oitenv) (c1:env) (e1 e2 e:expr) (x:identifier) (v2 v:val),\n    val_of_with_injection l vl c e1 (V_Closure x e c1)\n    -> val_of_with_injection l vl c e2 v2\n    -> val_of_with_injection l vl (OITEnv_cons x (val_to_oitval v2) (env_to_oitenv c1)) e v\n    -> val_of_with_injection l vl c (Apply e1 e2) v\n| Val_of_with_injection_Apply_rec :\n  forall (l:label) (vl:val) (c : oitenv) (c1 : env) (e1 e2 e : expr) (f x : identifier) (v2 v : val),\n    val_of_with_injection l vl c e1 (V_Rec_Closure f x e c1) ->\n    val_of_with_injection l vl c e2 v2 ->\n    val_of_with_injection l vl (env_to_oitenv (add_env  f (V_Rec_Closure f x e c1) (add_env x v2 c1))) e v ->\n    val_of_with_injection l vl c (Apply e1 e2) v\n| Val_of_with_injection_Let_in :\n  forall (l:label) (vl:val) (c : oitenv) (i : identifier) (e1 e2 : expr) (v1 v2 : val),\n    val_of_with_injection l vl c e1 v1\n    -> val_of_with_injection l vl (OITEnv_cons i (val_to_oitval v1) c) e2 v2\n    -> val_of_with_injection l vl c (Let_in i e1 e2) v2\n\n| Val_of_with_injection_If_true :\n  forall (l:label) (vl:val) (c : oitenv) (e e1 e2 : expr) (v : val),\n    val_of_with_injection l vl c e (V_Bool true)\n    -> val_of_with_injection l vl c e1 v\n    -> val_of_with_injection l vl c (If e e1 e2) v\n\n| Val_of_with_injection_If_false :\n  forall (l:label) (vl:val) (c : oitenv) (e e1 e2 : expr) (v : val),\n    val_of_with_injection l vl c e (V_Bool false)\n    -> val_of_with_injection l vl c e2 v\n    -> val_of_with_injection l vl c (If e e1 e2) v\n\n| Val_of_with_injection_Match : \n  forall (l:label) (vl:val) (c:oitenv) (c_p:env) (e e1 : expr) (p : pattern) (v v_e : val) (br2 : option (identifier*expr)),\n    val_of_with_injection l vl c e v_e\n    -> is_filtered v_e p = Filtered_result_Match c_p\n    -> val_of_with_injection l vl (conc_oitenv (env_to_oitenv c_p) c) e1 v\n    -> val_of_with_injection l vl c (Expr_match e (p,e1) br2) v\n| Val_of_with_injection_Match_var : \n  forall (l:label) (vl:val) (c : oitenv) (e e1 e2 : expr) (p : pattern) (v v_e : val) (x : identifier),\n    val_of_with_injection l vl c e v_e\n    -> is_filtered v_e p = Filtered_result_Match_var\n    -> val_of_with_injection l vl (OITEnv_cons x (val_to_oitval v_e) c) e2 v\n    -> val_of_with_injection l vl c (Expr_match e (p,e1) (Some (x,e2))) v\n\n| Val_of_with_injection_Constr0 : forall (l:label) (vl:val)  c n,\n  val_of_with_injection l vl c (Constr0 n) (V_Constr0 n) \n| Val_of_with_injection_Constr1 : forall (l:label) (vl:val)  c n e v,\n  val_of_with_injection l vl c e v\n  -> val_of_with_injection l vl c (Constr1 n e) (V_Constr1 n v) \n\n| Val_of_with_injection_Couple : forall (l:label) (vl:val)  c (e1 e2 : expr) (v1 v2 : val),\n  val_of_with_injection l vl c e1 v1\n  -> val_of_with_injection l vl c e2 v2\n  -> val_of_with_injection l vl c (Couple e1 e2) (V_Couple v1 v2)\n\n| Val_of_with_injection_Annot_eq : forall (l:label) (vl:val) c (e : expr),\n  val_of_with_injection l vl c (Annot l e) vl\n\n| Val_of_with_injection_Annot_neq : forall (l:label) (vl:val) c (l' : label) (e : expr) v,\n  val_of_with_injection l vl c e v\n  -> neq_label l l'\n  -> val_of_with_injection l vl c (Annot l' e) v\n  .\n\n\nHint Constructors val_of_with_injection : val_of_with_injection.\n\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/injection_operational_semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.2701138290241814}}
{"text": "Require Export Iron.Language.SystemF2Effect.Value.\nRequire Export Iron.Language.SystemF2Effect.Step.Frame.\nRequire Export Iron.Language.SystemF2Effect.Step.FreshF.\nRequire Export Iron.Language.SystemF2Effect.Step.SuppF.\nRequire Export Iron.Language.SystemF2Effect.Store.\nRequire Export Iron.Language.SystemF2Effect.Store.LiveE.\n\n(********************************************************************)\n(* Type of a frame stack.\n   The frame stack is like a continuation that takes an expression of\n   a certain type and produces a new expression. *)\nInductive\n TypeF :  kienv -> tyenv\n       -> stenv -> stprops\n       -> stack -> ty -> ty\n       -> ty -> Prop :=\n | TfNil\n   :  forall ke te se sp t\n   ,  KindT  ke sp t KData\n   -> TypeF  ke te se sp nil t t (TBot KEffect)\n\n | TfConsLet\n   :  forall ke te se sp fs t1 x2 t2 e2 t3 e3\n   ,  KindT  ke sp t1 KData\n   -> TypeX  ke (te :> t1) se sp                    x2 t2 e2\n   -> TypeF  ke te         se sp fs                 t2 t3 e3\n   -> TypeF  ke te         se sp (fs :> FLet t1 x2) t1 t3 (TSum e2 e3)\n\n | TfConsPriv\n   :  forall ke te se sp fs t1 t2 e2 p\n   ,  In (SRegion p) sp\n   -> NoPrivFs p fs\n   -> LiveE  fs e2\n   -> TypeF  ke te se sp fs                   t1 t2 e2\n   -> TypeF  ke te se sp (fs :> FPriv None p) t1 t2 e2\n\n | TfConsExt\n   :  forall ke te se sp fs t0 t1 e2 p1 p2\n   ,  In (SRegion p1) sp\n   -> In (SRegion p2) sp\n   -> FreshFs     p2 fs\n   -> FreshSuppFs p2 se fs\n   -> LiveE  fs (TSum e2 (TAlloc (TRgn p1)))\n   -> TypeF  ke te se sp fs                         (mergeT p1 p2 t0) t1 e2\n   -> TypeF  ke te se sp (fs :> FPriv (Some p1) p2) t0 t1 (TSum e2 (TAlloc (TRgn p1))).\n\nHint Constructors TypeF.\n\n\n(* Invert all hypothesis that are compound typing statements. *)\nLtac inverts_typef :=\n repeat (try\n  (match goal with\n   | [ H: TypeF _ _ _ _ (_ :> FLet  _ _) _ _ _ |- _ ] => inverts H\n   | [ H: TypeF _ _ _ _ (_ :> FPriv _ _) _ _ _ |- _ ] => inverts H\n   end);\n try inverts_type).\n\n\n(********************************************************************)\nLemma typeF_kindT_effect\n :  forall ke te se sp fs t1 t2 e\n ,  TypeF  ke te se sp fs t1 t2 e\n -> KindT  ke sp e KEffect.\nProof.\n intros.\n induction H; auto.\n - eapply KiSum; eauto.\n - eapply KiSum; auto.\n   eapply KiCon1; snorm.\nQed.\nHint Resolve typeF_kindT_effect.\n\n\nLemma typeF_kindT_wfT\n :  forall ke te se sp fs t1 t2 e\n ,  TypeF  ke te se sp fs t1 t2 e\n -> WfT (length ke) e.\nProof. eauto. Qed.\nHint Resolve typeF_kindT_wfT.\n\n\nLemma typeF_kindT_t1\n :  forall ke te se sp fs t1 t2 e\n ,  TypeF  ke te se sp fs t1 t2 e\n -> KindT  ke sp t1 KData.\nProof.\n intros. induction H; eauto 2.\nQed.\nHint Resolve typeF_kindT_t1.\n\n\nLemma typeF_kindT_t2\n :  forall ke te se sp fs t1 t2 e\n ,  TypeF  ke te se sp fs t1 t2 e\n -> KindT  ke sp t2 KData.\nProof. intros. induction H; auto. Qed.\nHint Resolve typeF_kindT_t2.\n\n\n(********************************************************************)\nLemma typeF_coversFs\n :  forall ke te se sp fs t1 t2 e\n ,  TypeF  ke te se sp fs t1 t2 e\n -> CoversFs se fs.\nProof.\n intros. gen ke te se sp t1 t2 e.\n induction fs as [|f]; intros.\n - eauto.\n - eapply Forall_cons; eauto.\n   + inverts H.\n     * eapply typeX_coversX; eauto.\n     * unfold CoversF; snorm.\n     * unfold CoversF; snorm.\n   + inverts H; eapply IHfs; eauto.\nQed.\n\n\nLemma typeF_stenv_snoc\n :  forall ke te se sp fs t1 t2 t3 e\n ,  ClosedT t3\n -> TypeF ke te se         sp fs t1 t2 e\n -> TypeF ke te (t3 <: se) sp fs t1 t2 e.\nProof.\n intros.\n induction H0; eauto.\n\n - eapply TfConsExt; auto.\n   eapply freshSuppFs_coveredFs.\n   eapply typeF_coversFs; eauto. auto.\nQed.\nHint Resolve typeF_stenv_snoc.\n\n\nLemma typeF_stprops_snoc\n :  forall ke te se sp fs t1 t2 p e\n ,  TypeF  ke te se sp        fs t1 t2 e\n -> TypeF  ke te se (p <: sp) fs t1 t2 e.\nProof. intros. induction H; eauto. Qed.\nHint Resolve typeF_stprops_snoc.\n\n\nLemma typeF_freshFs\n :  forall ke te se sp fs t1 t2 e p\n ,  not (In (SRegion p) sp)\n -> TypeF ke te se sp fs t1 t2 e\n -> FreshFs p fs.\nProof.\n intros. gen ke te se sp t1 t2 e.\n induction fs; intros; auto.\n destruct a.\n - inverts H0.\n   eapply freshFs_cons; eauto.\n   simpl. rip. eauto.\n   eapply freshX_typeX; eauto.\n - inverts H0.\n   * eapply freshFs_cons; eauto.\n     lets D: (@in_not_in stprop) H4 H.\n     have (p <> n) by congruence.\n     simpl. auto.\n    * eapply freshFs_cons; eauto.\n     snorm.\n      + lets D: (@in_not_in stprop) H5 H.\n        congruence.\n      + lets D: (@in_not_in stprop) H5 H.\n        congruence.\nQed.\nHint Resolve typeF_freshFs.\n\n\nLemma typeF_freshSuppFs\n :  forall ke te se sp fs t1 t2 e p\n ,  not (In (SRegion p) sp)\n -> TypeF ke te se sp fs t1 t2 e\n -> FreshSuppFs p se fs.\nProof.\n intros. gen ke te se sp t1 t2 e.\n induction fs as [|f]; intros; auto.\n eapply Forall_cons; auto.\n - clear IHfs.\n   destruct f; snorm; inverts H0.\n   + simpl.\n     eapply freshSuppX_typeX; eauto.\n - inverts H0; eapply IHfs; eauto.\nQed.\n\n\nLemma typeF_allocRegion_noprivFs\n : forall ke te se sp fs t1 t2 e p\n ,  p = allocRegion sp\n -> TypeF ke te se sp fs t1 t2 e\n -> NoPrivFs p fs.\nProof.\n intros.\n eapply freshFs_noprivFs.\n eapply typeF_freshFs.\n lets D: allocRegion_fresh sp.\n rewrite <- H in D. eauto. eauto.\nQed.\nHint Resolve typeF_allocRegion_noprivFs.\n\n\nLemma typeF_mergeTE\n :  forall ke te se sp fs t1 t2 e p1 p2\n ,  FreshFs     p2 fs\n -> FreshFreeFs p2 te fs\n -> FreshSuppFs p2 se fs\n -> TypeF ke te se sp fs t1 t2 e\n -> TypeF ke (mergeTE p1 p2 te) (mergeTE p1 p2 se) sp fs t1 t2 e.\nProof.\n intros. gen ke te se sp t1 t2 e. gen p1 p2.\n induction fs as [|f]; intros.\n\n Case \"nil\".\n { inverts H2. eauto.\n }\n\n Case \"cons\".\n { destruct f.\n\n   - SCase \"FLet\".\n     have (FreshFs p2 fs). rip.\n\n     have HF: (FreshF  p2 (FLet t e0))\n      by (eapply freshFs_tail; eauto).\n     unfold FreshF in HF. rip.\n\n     inverts H2.\n     eapply TfConsLet; auto.\n     + rewrite mergeTE_rewind; auto.\n       eapply mergeX_typeX_freshX; eauto.\n       * inverts H0; snorm.\n       * inverts H1; snorm.\n     + eapply IHfs; eauto.\n\n   - SCase \"FPriv\".\n     inverts H2.\n     * eapply TfConsPriv; auto.\n       eapply IHfs; eauto.\n     * eapply TfConsExt; eauto.\n       have (FreshSuppFs p2 se fs).\n       eapply freshSuppFs_mergeTE; auto.\n }\nQed.\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/Step/TypeF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2701138219752063}}
{"text": "\nFrom mathcomp Require Import ssreflect ssrfun eqtype seq ssrint.\nFrom CoqUtils Require Import fmap fset word.\n\nRequire Extraction.\nRequire extraction.ExtrOcamlString.\n\nRequire Import Intermediate.Machine.\nRequire Import Common.Definitions.\nRequire Import MicroPolicies.Instance.\nRequire Import MicroPolicies.Printer.\nRequire Import I2MP.Encode.\nRequire Import I2MP.Linearize.\n\nRequire Import MicroPolicies.Utils.\nImport DoNotation.\n\nDefinition test_program : Intermediate.program :=\n  let c0 := [fmap (0, [:: ICall 1 0; IReturn])] in\n  let c0_i := Component.mkCompInterface\n                fset0\n                (fset [:: (1, 0)]) in\n  let c1 := [fmap (0, [:: IConst (IInt 5) R_COM; IReturn])] in\n  let c1_i := Component.mkCompInterface\n                (fset [:: 0])\n                fset0 in\n  Intermediate.mkProg\n    [fmap (0, c0_i); (1, c1_i)] (* Interface: nothing imported/exported*)\n    [fmap (0, c0); (1, c1)] (* code *)\n    (emptym) (* Pre-allocated buffers *)\n    (Some 0). (* Main procedure idtac *)\n\n\nDefinition test_alloc : Intermediate.program :=\n  let c0 := [fmap (0, [:: IConst (IInt 5) R_ONE ; IAlloc R_COM R_ONE; IReturn])] in\n  let c0_i := Component.mkCompInterface fset0 fset0 in\n  Intermediate.mkProg\n    emptym (* Interface: nothing imported/exported*)\n    [fmap (0, c0)] (* code *)\n    (emptym) (* Pre-allocated buffers *)\n    (Some 0). (* Main procedure idtac *)\n\nDefinition test_program_machine := load (encode (linearize test_program)).\nDefinition test_alloc_machine := load (encode (linearize test_alloc)).\n\nExtraction \"/tmp/tl_test.ml\" coqstring_of_state test_program_machine test_alloc_machine stepf.\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/Examples/TL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621764862150636, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.27011381492623115}}
{"text": "(* begin hide *)\n\nFrom mathcomp Require Import all_ssreflect.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nSet Asymmetric Patterns.\n\nFrom Equations Require Import Equations.\n\nRequire Import String.\nRequire Import QString.\n\nRequire Import SeqExtra.\n\n\nNotation Name := string.\n\n(* end hide *)\n(**\n   #<div class=\"jumbotron\">\n      <div class=\"container\">\n        <h1 class=\"display-4\">GraphQL Response</h1>\n        <p class=\"lead\">\n         This file contains the basic building blocks to define a GraphQL Response.\n        </p>\n         \n  </div>\n</div>#\n *)\n\nSection Response.\n\n  (* Unsetting because the automatically generated induction principle is not good enough. *)\n  Unset Elimination Schemes.\n\n  Variable (Scalar : eqType).\n  \n  (** * Response\n      ----\n      Here we define a general Response structure, which is in essence a JSON tree.\n      We later use this definition to build a GraphQL Response.     \n\n      A response can be either:\n      - an optional _scalar_ values (to account for null values),\n      - an object, mapping keys to other responses, or\n      - an array of response values.\n   *)\n  Inductive ResponseValue : Type :=\n  | Leaf : option Scalar -> ResponseValue\n  | Object : seq (Name * ResponseValue) -> ResponseValue\n  | Array : seq ResponseValue -> ResponseValue.\n  \n  Set Elimination Schemes.\n\n  \n  (** * GraphQL Response \n      ----      \n      \n      A GraphQL Response is, in essence, a JSON Object, mapping keys \n      to other response values.\n   *)  \n  Definition GraphQLResponse := seq (Name * ResponseValue).\n\n  \n\n  (** We define some auxiliary definitions *)\n  (** ---- *)\n  (**\n     Gets the size of the response tree.\n   *)\n  \n  Equations rsize (response : ResponseValue) : nat :=\n    {\n      rsize (Leaf _) := 1;\n      rsize (Object rt) := (lrsize rt).+1;\n      rsize (Array rt) := (list_size rsize rt).+1\n    }\n  where lrsize (r : seq (Name * ResponseValue)) : nat :=\n          {\n            lrsize [::] := 0;\n            lrsize (hd :: tl) := rsize hd.2 + lrsize tl\n          }.\n  \n\n  (** ---- *)\n  (**\n     This predicate checks whether the responses are non-redundant.\n     \n     Non-redundancy means that there are no duplicated keys.\n   *)\n  \n  Equations is_non_redundant (response : ResponseValue) : bool :=\n          {\n            is_non_redundant (Leaf _) := true;\n\n            is_non_redundant (Object rt) := are_non_redundant rt;\n\n            is_non_redundant (Array rt) := all is_non_redundant rt\n          }\n  where are_non_redundant (responses : seq (Name * ResponseValue)) : bool  :=\n    {\n      are_non_redundant [::] := true;\n\n      are_non_redundant ((k, q) :: qs) := [&& is_non_redundant q,\n                                          all (fun kq => kq.1 != k) qs &\n                                          are_non_redundant qs]\n    }.\n  \n  \n  \nEnd Response.\n\n(* begin hide *)\nArguments ResponseValue [Scalar].\nArguments Leaf [Scalar].\nArguments Object [Scalar].\nArguments Array [Scalar].\nArguments is_non_redundant [Scalar].\nArguments are_non_redundant [Scalar].\n(* end hide *)\n\nDelimit Scope response_scope with RESP.\nOpen Scope response_scope.\n\nNotation \"{- ρ -}\" := (Object ρ) : response_scope.\n\n\n(** ---- *)\n(** \n    #<div>\n        <a href='GraphCoQL.Query.html' class=\"btn btn-light\" role='button'>Previous ← Query</a>\n        <a href='GraphCoQL.QuerySemantics.html' class=\"btn btn-info\" role='button'>Continue Reading → Query Semantics</a>\n    </div>#\n*)\n\n  \n  ", "meta": {"author": "imfd", "repo": "GraphCoQL", "sha": "681edcdcdf982151f4d1f74bb2a42f15b527317c", "save_path": "github-repos/coq/imfd-GraphCoQL", "path": "github-repos/coq/imfd-GraphCoQL/GraphCoQL-681edcdcdf982151f4d1f74bb2a42f15b527317c/src/Response.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.27011381492623115}}
{"text": "Require Import Omega.\nRequire Import Bool.\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.\nRequire Import Loc.\n\nRequire Import Event.\nRequire Import Time.\n\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\n\nRequire Import Cover.\nRequire Import Mapping.\nRequire Import Pred.\nRequire Import Trace.\nRequire Import MemoryProps.\nRequire Import PFConsistent.\nRequire Import PFConsistentStrong.\n\nSet Implicit Arguments.\n\nModule FutureCertify.\n  Section FutureCertify.\n    Variable (lang: language).\n\n    Lemma cap_steps_current_steps\n          th0 th1 mem1 sc1\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          (CAP: Memory.cap (Thread.memory th0) mem1)\n          (SC_MAX: Memory.max_concrete_timemap mem1 sc1)\n          (STEPS: rtc (@Thread.tau_step lang)\n                      (Thread.mk lang (Thread.state th0) (Thread.local th0) sc1 mem1)\n                      th1)\n          (CONSISTENT: Local.promise_consistent (Thread.local th1))\n      :\n        exists lc' sc' mem',\n          (<<STEPS: rtc (@Thread.tau_step lang)\n                        th0\n                        (Thread.mk lang (Thread.state th1) lc' sc' mem')>>) /\\\n          (<<CONSISTENT: Local.promise_consistent lc'>>)\n    .\n    Proof.\n      eapply pred_steps_thread_steps in STEPS.\n      destruct th0, th1. ss.\n      hexploit steps_map.\n      { eapply ident_map_le. }\n      { eapply ident_map_bot. }\n      { eapply ident_map_eq. }\n      { i. eapply ident_map_mappable_evt. }\n      { eapply STEPS. }\n      { ss. }\n      { ss. }\n      { ss. }\n      { eapply Local.cap_wf; eauto. }\n      { eapply LOCAL. }\n      { eauto. }\n      { eapply Memory.cap_closed; eauto. }\n      { eauto. }\n      { eapply Memory.max_concrete_timemap_closed; eauto. }\n      { eapply map_ident_in_memory_local; eauto; ss.\n        eapply ident_map_lt.\n      }\n      { econs.\n        { i. destruct msg as [val released|]; auto. right.\n          exists to, from, (Message.concrete val released), (Message.concrete val released).\n          eapply Memory.cap_inv in GET; eauto. des; ss. esplits; eauto.\n          { refl. }\n          { eapply ident_map_message. }\n          { refl. }\n        }\n        { i. eapply CAP in GET. left. exists fto, ffrom, fto, ffrom. splits; ss.\n          { refl. }\n          { refl. }\n          { i. econs; eauto. }\n        }\n      }\n      { eapply mapping_map_lt_collapsable_unwritable. eapply ident_map_lt. }\n      { eapply ident_map_timemap. }\n      { eapply Memory.max_concrete_timemap_spec; eauto.\n        eapply Memory.cap_closed_timemap; eauto. }\n      { instantiate (1:=fun _ => True). ss. }\n      i. des. esplits.\n      { eapply rtc_implies; try apply STEP. i. inv H. inv TSTEP. econs; eauto. }\n      { inv LOCAL0. eapply promise_consistent_mon; cycle 1; eauto.\n        { refl. }\n        eapply promise_consistent_map; eauto.\n        { eapply ident_map_le; eauto. }\n        { eapply ident_map_eq; eauto. }\n      }\n    Qed.\n\n    Definition future_certify lang (e:Thread.t lang): Prop :=\n      forall sc1 mem1\n        (FUTURE: Memory.future_weak (Thread.memory e) mem1)\n        (FUTURE: TimeMap.le (Thread.sc e) sc1)\n        (WF: Local.wf (Thread.local e) mem1)\n        (SC: Memory.closed_timemap sc1 mem1)\n        (MEM: Memory.closed mem1),\n        (<<FAILURE: Thread.steps_failure (Thread.mk lang (Thread.state e) (Thread.local e) sc1 mem1)>>) \\/\n        exists e2,\n          (<<STEPS: rtc (@Thread.tau_step lang) (Thread.mk lang (Thread.state e) (Thread.local e) sc1 mem1) e2>>) /\\\n          (<<PROMISES: (Local.promises (Thread.local e2)) = Memory.bot>>).\n\n    Lemma future_certify_exists\n          e\n          (LOCAL: Local.wf (Thread.local e) (Thread.memory e))\n          (MEMORY: Memory.closed (Thread.memory e))\n          (SC: Memory.closed_timemap (Thread.sc e) (Thread.memory e))\n          (CONSISTENT: @Thread.consistent lang e):\n      future_certify e.\n    Proof.\n      eapply consistent_pf_consistent_super_strong in CONSISTENT; eauto. des.\n      exploit (@concrete_promise_max_timemap_exists (Thread.memory e) (Local.promises (Thread.local e))).\n      { eapply MEMORY. } i. des.\n      ii. exploit (CONSISTENT0 mem1 TimeMap.bot sc1); eauto. i. des.\n      eapply Trace.silent_steps_tau_steps in STEPS; cycle 1.\n      { eapply List.Forall_impl; eauto. i. ss. des. auto. }\n      unguard. des.\n      { left. unfold Thread.steps_failure. destruct e1. ss. esplits; eauto. }\n      { right. esplits; eauto. }\n    Qed.\n\n    Lemma future_consistent\n          e sc' mem'\n          (LOCAL: Local.wf (Thread.local e) (Thread.memory e))\n          (MEMORY: Memory.closed (Thread.memory e))\n          (SC: Memory.closed_timemap (Thread.sc e) (Thread.memory e))\n          (CONSISTENT: @Thread.consistent lang e)\n          (SC_FUTURE: TimeMap.le (Thread.sc e) sc')\n          (MEM_FUTURE: Memory.future_weak (Thread.memory e) mem')\n          (LOCAL': Local.wf (Thread.local e) mem')\n          (MEMORY': Memory.closed mem')\n          (SC': Memory.closed_timemap sc' mem'):\n      Thread.consistent (Thread.mk lang (Thread.state e) (Thread.local e) sc' mem').\n    Proof.\n      ii. ss.\n      eapply future_certify_exists; try exact CONSISTENT; eauto.\n      - etrans; eauto. eapply Memory.cap_future_weak; eauto.\n      - etrans; eauto.\n        hexploit Memory.cap_closed_timemap; try exact SC'; eauto. i.\n        hexploit Memory.max_concrete_timemap_spec; eauto.\n      - eapply Local.cap_wf; eauto.\n      - eapply Memory.max_concrete_timemap_closed; eauto.\n      - eapply Memory.cap_closed; eauto.\n    Qed.\n  End FutureCertify.\nEnd FutureCertify.\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/FutureCertify.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.27010165842381223}}
{"text": "\n(** following discussions with J. Gross, D. Grayson and V. Voevodsky *)\n\nRequire Import Foundations.Generalities.uuu.\nRequire Import Foundations.Generalities.uu0.\nRequire Import Foundations.hlevel1.hProp.\nRequire Import Foundations.hlevel2.hSet.\n\n\nRequire Import RezkCompletion.pathnotations.\nImport RezkCompletion.pathnotations.PathNotations.\nRequire Import RezkCompletion.auxiliary_lemmas_HoTT.\nRequire Import RezkCompletion.precategories.\nRequire Import RezkCompletion.functors_transformations.\nRequire Import RezkCompletion.limits.aux_lemmas_HoTT.\n\nLocal Notation \"a --> b\" := (precategory_morphisms a b)(at level 50).\nLocal Notation \"f ;; g\" := (compose f g)(at level 50).\nLocal Notation \"# F\" := (functor_on_morphisms F)(at level 3).\n\nSection Cone.\n\nVariables J C : precategory.\n\nVariable F : functor J C.\n\nDefinition ConeData := total2 (\n  fun a : C => forall j : J, a --> F j).\n\nDefinition ConeTop (a : ConeData) : C := pr1 a.\nDefinition ConeMor (a : ConeData) (j : J) : ConeTop a --> F j := (pr2 a) j.\n\nLemma eq_ConeData_eq (a b : ConeData) (p q : a == b) :\n   base_paths _ _ p == base_paths _ _ q -> p == q.\nProof.\n  intro H.\n  apply (eq_equalities_between_pairs _ _ _ _ _ _ H).\n  apply uip.\n  apply (impred 2); intro j.\n  apply (pr2 (_ --> _ )).\nDefined.\n\nDefinition ConeProp (a : ConeData) :=\n  forall j j' (f : j --> j'), ConeMor a j ;; #F f == ConeMor a j'.\n\nLemma isaprop_ConeProp (a : ConeData) : isaprop (ConeProp a).\nProof.\n  repeat (apply impred; intro).\n  apply (pr2 (_ --> _)).\nQed.\n\nDefinition Cone := total2 (fun a : ConeData => ConeProp a).\n\n\nDefinition ConeData_from_Cone : Cone -> ConeData := fun a => pr1 a.\n\nLemma eq_Cone_eq (a b : Cone) (p q : a == b) :\n   base_paths _ _ (base_paths _ _ p) == \n   base_paths _ _ (base_paths _ _ q) -> p == q.\nProof.\n  intro H.\n  assert (H2 : base_paths _ _ p == base_paths _ _ q).\n  apply eq_ConeData_eq.\n  apply H.\n  apply (eq_equalities_between_pairs _ _ _ _ _ _ H2).\n  apply uip.\n  apply isasetaprop.\n  apply isaprop_ConeProp.\nDefined.\n\n\nCoercion ConeData_from_Cone : Cone >-> ConeData.\n\nDefinition ConeProp_from_Cone (a : Cone) : ConeProp a := pr2 a.\nCoercion ConeProp_from_Cone : Cone >-> ConeProp.\n\n\nLemma cone_prop (a : Cone) : \n  forall j j' (f : j --> j'), ConeMor a j ;; #F f == ConeMor a j'.\nProof.\n  exact (pr2 a).\nQed.\n\nDefinition Cone_eq (a b : Cone) : pr1 a == pr1 b -> a == b.\nProof.\n  intro H.\n  apply (total2_paths H).\n  apply proofirrelevance.\n  apply isaprop_ConeProp.\nDefined.\n\nDefinition Cone_Mor (M N : Cone) := \n  total2 (fun f : ConeTop M --> ConeTop N =>\n        forall j : J, f ;; ConeMor N j == ConeMor M j).\n\n\nLemma isaset_Cone_Mor (M N : Cone) : isaset (Cone_Mor M N).\nProof.\n  apply (isofhleveltotal2 2).\n  apply (pr2 (_ --> _ )).\n  intros.\n  apply hlevelntosn.\n  apply impred.\n  intros.\n  apply (pr2 (_ --> _ )).\nQed.\n\nDefinition ConeConnect {M N : Cone} (f : Cone_Mor M N) : \n    ConeTop M --> ConeTop N := pr1 f.\n\nLemma Cone_Mor_eq (M N : Cone) (f g : Cone_Mor M N) : \n   ConeConnect f == ConeConnect g -> f == g.\nProof.\n  intro H.\n  apply (total2_paths H).\n  apply proofirrelevance.\n  apply impred; intro; apply (pr2 (_ --> _)).\nQed.\n\nLemma cone_mor_prop M N (f : Cone_Mor M N) : \n    forall j : J, ConeConnect f ;; ConeMor N j == ConeMor M j.\nProof.\n  exact (pr2 f).\nQed.\n\nDefinition Cone_id (A : Cone) : Cone_Mor A A.\nProof.\n  exists (identity _).\n  intros; apply id_left.\nDefined.\n\n\nDefinition Cone_comp (A B D : Cone) (f : Cone_Mor A B)\n        (g : Cone_Mor B D) : Cone_Mor A D.\nProof.\n  exists (ConeConnect f ;; ConeConnect g).\n  intro j.\n  (* make this proof opaque *)\n  rewrite <- assoc.\n  rewrite cone_mor_prop.\n  rewrite cone_mor_prop.\n  apply idpath.\nDefined.\n\n\nDefinition Cone_precategory_ob_mor : precategory_ob_mor := \n   precategory_ob_mor_pair Cone \n   (fun a b => hSetpair (Cone_Mor a b) (isaset_Cone_Mor a b)).\n\nDefinition Cone_precategory_data : precategory_data.\nProof.\n  exists Cone_precategory_ob_mor.\n  exists Cone_id.\n  exact Cone_comp.\nDefined.\n\nLemma is_precategory_Cone : is_precategory Cone_precategory_data.\nProof.\n  repeat split; simpl.\n  \n  intros;\n  apply Cone_Mor_eq;\n  simpl; apply id_left.\n  \n  intros;\n  apply Cone_Mor_eq;\n  simpl; apply id_right.\n  \n  intros; \n  apply Cone_Mor_eq;\n  simpl; apply assoc.\nQed.\n  \nDefinition CONE : precategory := tpair _ _ is_precategory_Cone.\n\n\n\n(* this should not need the pr1 before f *)\n\nDefinition iso_projects_from_CONE (a b : CONE) (f : iso a b) :\n  is_isomorphism (ConeConnect (pr1 f)).\nProof.\n  exists (ConeConnect (inv_from_iso f)).\n  split; simpl.\n  apply (base_paths _ _ (pr1 (pr2 (pr2 f)))).\n  apply (base_paths _ _ (pr2 (pr2 (pr2 f)))).\nDefined.\n\nDefinition ConeConnectIso {a b : CONE} (f : iso a b) :\n   iso (ConeTop (pr1 a)) (ConeTop (pr1 b)) := \n tpair _ _ (iso_projects_from_CONE a b f).\n\nLemma ConeConnectIso_identity_iso (a : CONE) :\n   ConeConnectIso (identity_iso a) == identity_iso _ .\nProof.\n  apply eq_iso.\n  apply idpath.\nQed.\n\nLemma ConeConnectIso_inj (a b : CONE) (f g : iso a b) :\n   ConeConnectIso f == ConeConnectIso g -> f == g.\nProof.\n  intro H.\n  apply eq_iso; simpl in *.\n  apply Cone_Mor_eq.\n  apply (base_paths _ _ H).\nQed.\n\n\nSection CONE_category.\n\nHypothesis is_cat_C : is_category C.\n\n\nDefinition isotoid_CONE_pr1 (a b : CONE) : iso a b -> pr1 a == pr1 b.\nProof.\n  intro f.\n  apply (total2_paths (isotoid _ is_cat_C (ConeConnectIso f))).\n  pathvia ((fun c : J =>\n     idtoiso (!isotoid C is_cat_C (ConeConnectIso f));; pr2 (pr1 a) c)).\n  apply transportf_isotoid_dep'.\n  apply funextsec.\n  intro t.\n  pathvia (idtoiso (isotoid C is_cat_C (iso_inv_from_iso (ConeConnectIso f)));;\n       pr2 (pr1 a) t).\n  apply cancel_postcomposition.\n  apply maponpaths. apply maponpaths.\n  apply inv_isotoid.\n  pathvia (iso_inv_from_iso (ConeConnectIso f);; pr2 (pr1 a) t).\n  apply cancel_postcomposition.\n  set (H := idtoiso_isotoid _ is_cat_C _ _ (iso_inv_from_iso (ConeConnectIso f))).\n  simpl in *.\n  apply (base_paths _ _ H).\n  simpl.\n  apply (pr2 (inv_from_iso f)).\nDefined.\n\nDefinition isotoid_CONE {a b : CONE} : iso a b -> a == b.\nProof.\n  intro f.\n  apply Cone_eq.\n  apply (isotoid_CONE_pr1 _ _ f).\nDefined.\n\n\nLemma eq_CONE_pr1 (M N : CONE) (p q : M == N) : base_paths _ _ p == base_paths _ _ q -> p == q.\nProof.\n  intro H.\n  simpl in *.\n  apply (eq_equalities_between_pairs _ _ _ _ _ _ H).\n  apply proofirrelevance.\n  apply isapropifcontr.\n  apply isaprop_ConeProp.\nDefined.\n  \n \nLemma base_paths_isotoid_CONE (M : CONE):\nbase_paths (pr1 M) (pr1 M)\n      (base_paths M M (isotoid_CONE (identity_iso M))) ==\n    base_paths (pr1 M) (pr1 M) (idpath (pr1 M)).\nProof.\n  pathvia (base_paths (pr1 M) (pr1 M) (isotoid_CONE_pr1 M M (identity_iso M))).\n  unfold Cone_eq.\n  apply maponpaths. \n  apply base_total_path.\n  pathvia (isotoid C is_cat_C (ConeConnectIso (identity_iso M))).\n  unfold isotoid_CONE_pr1.\n  apply base_total_path.\n  pathvia (isotoid C is_cat_C (identity_iso (ConeTop (pr1 M)))).\n  apply maponpaths, ConeConnectIso_identity_iso.\n  apply isotoid_identity_iso.\nDefined.\n\n\nLemma isotoid_CONE_idtoiso (M N : CONE) : forall p : M == N, isotoid_CONE (idtoiso p) == p.\nProof.\n  intro p.\n  induction p.\n  apply eq_Cone_eq.\n  apply base_paths_isotoid_CONE.\nQed.\n\n\n\nLemma ConeConnect_idtoiso (M N : CONE) (p : M == N):\n  ConeConnect (pr1 (idtoiso p)) == idtoiso ((base_paths _ _ (base_paths _ _  p))).\nProof.\n  destruct p.\n  apply idpath.\nQed.\n\nLemma idtoiso_isotoid_CONE (M N : CONE) : forall f : iso M N, idtoiso (isotoid_CONE f) == f.\nProof.\n  intro f.\n  apply eq_iso.\n  simpl.\n  apply Cone_Mor_eq.\n  rewrite ConeConnect_idtoiso.\n  unfold isotoid_CONE.\n  unfold Cone_eq.\n  rewrite base_total_path.\n  unfold isotoid_CONE_pr1.\n  rewrite base_total_path.\n  simpl.\n  rewrite idtoiso_isotoid.\n  apply idpath.\nQed.\n\n\nLemma is_category_CONE : is_category CONE.\nProof.\n  unfold is_category.\n  intros a b.\n  apply (gradth _  (@isotoid_CONE a b)).\n  apply isotoid_CONE_idtoiso.\n  apply idtoiso_isotoid_CONE.\nDefined.\n\nEnd CONE_category.\n\nEnd Cone.\n\nImplicit Arguments CONE [J C].\nImplicit Arguments ConeConnect [J C].\n", "meta": {"author": "benediktahrens", "repo": "rezk_completion", "sha": "851ea2e2c8364a4ff40cdaea9d5b4f94ee17f82d", "save_path": "github-repos/coq/benediktahrens-rezk_completion", "path": "github-repos/coq/benediktahrens-rezk_completion/rezk_completion-851ea2e2c8364a4ff40cdaea9d5b4f94ee17f82d/limits/cones.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.63341027751814, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2700364782474813}}
{"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\n(** * PPT.v: Theory of probabilistic polynomial time programs *)\n\nSet Implicit Arguments.\n\nRequire Import BaseProp.\n\nOpen Scope nat_scope.\n\n\n(** User-defined operators and distributions *)\nModule Type UPPT (Sem:SEM) (ST:SEM_THEORY Sem).\n \n Export Sem.\n Export ST.\n \n Implicit Arguments T.size [k t].\n\n (** PPT expression *)\n Definition PPT_expr (t:T.type) (e:E.expr t) \n  (F:polynomial -> polynomial) \n  (G:polynomial -> polynomial) : Prop := \n  forall k (m:Mem.t k) p,\n   (forall t (x:Var.var t), \n    Vset.mem x (fv_expr e) -> T.size (m x) <= peval p k)  ->\n   let (v,n) := E.ceval_expr e m in\n    T.size v <= peval (F p) k /\\\n    n <= peval (G p) k.\n\n (** PPT support *)\n Definition PPT_support t (s:E.support t)\n  (F:polynomial -> polynomial) \n  (G:polynomial -> polynomial) : Prop :=\n  forall k (m:Mem.t k) p,\n   (forall t (x:Var.var t), \n    Vset.mem x (fv_distr s) -> T.size (m x) <= peval p k)  ->\n   let (l,n) := E.ceval_support s m in\n    (forall v, In v l -> T.size v <= peval (F p) k) /\\\n    n <= peval (G p) k.\n\n Parameter utsize : UT.t -> nat.\n\n Parameter utsize_default_poly : nat -> polynomial.\n\n Parameter utsize_default_poly_spec : forall r ut,\n  utsize ut <= r -> \n  forall k, UT.size (UT.default k ut) <= peval (utsize_default_poly r) k.\n\n Parameter uop_poly : Uop.t -> bool.\n\n Parameter uop_poly_spec : forall o (la:dlist E.expr (O.targs (O.Ouser o))),\n   uop_poly o ->\n   (forall t (e:E.expr t), @DIn _ E.expr _ e _ la -> \n    exists F, exists G, PPT_expr e F G) ->\n   exists F, exists G, PPT_expr (E.Eop (O.Ouser o) la) F G.\n\n Parameter usupport_poly : forall t, US.usupport t -> bool.\n\n Parameter usupport_poly_spec : forall t (us:US.usupport t),\n  usupport_poly us ->\n  exists F, exists G, PPT_support (E.Duser us) F G.\n\nEnd UPPT.\n\n\n(** Decision procedure for PPT programs and expressions *)\nModule Make_PPT (Sem:SEM) (ST:SEM_THEORY Sem) (U:UPPT Sem ST).\n\n Import U.\n\n Module VarP := MkEqBool_Leibniz_Theory Var.\n Module VsetP := MkSet_Theory Vset.\n\n Implicit Arguments T.size [k t]. \n\n Fixpoint tsize (t:T.type) : nat :=\n  match t with \n  | T.User ut => utsize ut\n  | T.Pair t1 t2 => tsize t1 + tsize t2 + 1\n  | T.Sum t1 t2 => tsize t1 + tsize t2 + 1\n  | _ => 0\n  end.\n\n (** PPT expression *)\n Definition PPT_expr (t:T.type) (e:E.expr t) \n  (F:polynomial -> polynomial) \n  (G:polynomial -> polynomial) : Prop :=\n  forall k (m:Mem.t k) p,\n   (forall t (x:Var.var t), \n    Vset.mem x (fv_expr e) -> T.size (m x) <= peval p k)  ->\n   let (v,n) := E.ceval_expr e m in\n    T.size v <= peval (F p) k /\\\n    n <= peval (G p) k.\n\n (** PPT support *)\n Definition PPT_support t (s:E.support t)\n  (F:polynomial -> polynomial) \n  (G:polynomial -> polynomial) : Prop :=\n  forall k (m:Mem.t k) p,\n   (forall t (x:Var.var t), \n    Vset.mem x (fv_distr s) -> T.size (m x) <= peval p k)  ->\n   let (l,n) := E.ceval_support s m in\n    (forall v, In v l -> T.size v <= peval (F p) k) /\\\n    n <= peval (G p) k.\n\n\n (** Expressions *)\n \n Lemma PPT_bool : forall b:bool, \n  PPT_expr b (fun _ => pcst 1) (fun _ => pcst 1).\n Proof.\n  unfold PPT_expr; intros; simpl.\n  rewrite pcst_spec; auto.\n Qed.\n \n Lemma PPT_nat : forall n:nat, \n  PPT_expr n (fun _ => size_nat n) (fun _ => size_nat n).\n Proof.\n  unfold PPT_expr; intros; simpl.\n  rewrite pcst_spec; auto.\n Qed.\n\n Lemma PPT_Z : forall n:Z, \n  PPT_expr n (fun _ => size_Z n) (fun _ => size_Z n).\n Proof.\n  unfold PPT_expr; intros; simpl.\n  rewrite pcst_spec; auto.\n Qed.\n\n Lemma PPT_enil : forall t, \n  PPT_expr (Nil t)  (fun _ => pcst 1) (fun _ => pcst 1).\n Proof.\n  unfold PPT_expr; intros; simpl.\n  rewrite pcst_spec; auto.\n Qed.\n\n Lemma PPT_var : forall t (x:Var.var t),\n  PPT_expr x (fun p => p) (fun _ => pcst 1).\n Proof.\n  unfold PPT_expr; intros; simpl.\n  split; [ | rewrite pcst_spec; trivial].\n  apply H; simpl. \n  unfold fv_expr; simpl.\n  apply Vset.add_correct; trivial.\n Qed.\n\n Lemma PPT_eq : forall t (e1:E.expr t) (e2:E.expr t) F1 G1 F2 G2,\n  PPT_expr e1 F1 G1 -> PPT_expr e2 F2 G2 ->\n  PPT_expr (E.Eop (O.Oeq_ t) {e1, e2})\n   (fun p => pcst 1)\n   (fun p => pplus (pplus (F1 p) (F2 p)) (pplus (G1 p) (G2 p))).\n Proof.\n  unfold PPT_expr; intros t e1 e2 F1 G1 F2 G2 He1 He2 k m p Hm.\n  split; simpl.\n  rewrite pcst_spec; trivial.\n  rewrite pplus_spec.\n  generalize (He1 k m p) (He2 k m p); clear He1 He2.\n  case_eq (E.ceval_expr e1 m); simpl.\n  case_eq (E.ceval_expr e2 m); simpl.\n  intros i n Heqi i0 n0 Heqi0 Hi Hi0.\n  destruct Hi.\n  intros; apply Hm; simpl.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].  \n  unfold fv_expr; simpl.\n  apply fv_expr_rec_subset.\n  destruct Hi0.\n  intros; apply Hm; simpl.\n  apply Vset.subset_correct with (fv_expr e2); [ | trivial].  \n  unfold fv_expr at 2; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec.\n  apply VsetP.subset_union_l.\n  apply plus_le_compat.\n  rewrite E.ceval_expr_spec, Heqi0; trivial.\n  rewrite E.ceval_expr_spec, Heqi; trivial.\n  simpl; rewrite pplus_spec.\n  apply plus_le_compat; trivial.\n  rewrite plus_0_r, pplus_spec.\n  apply plus_le_compat; trivial.\n Qed.\n\n Lemma List_size_length : forall k t (l:T.interp k (T.List t)),\n   length l <= T.size (k:=k) (t:=T.List t) l.\n Proof.\n  induction l; simpl; auto.\n  apply le_n_S; apply le_trans with (1:= IHl); apply le_plus_r.\n Qed.\n\n Lemma cexistsb_count : forall A (f:A -> bool * nat) p l,\n   (forall a, In a l -> snd (f a) <= p) ->\n   forall n, snd (cexistsb f l n) <= length l * p + n.\n Proof.\n  induction l; simpl; intros; trivial.\n  case_eq (f a); intros.\n  assert (n0 <= p).\n   assert (W:= H a); rewrite H0 in W; simpl in W; apply W; auto.\n  destruct b; simpl.\n  rewrite plus_comm; apply plus_le_compat; trivial.\n  apply le_trans with (1:= H1).\n  apply le_plus_l.\n  assert (forall a0 : A, In a0 l -> snd (f a0) <= p) by (intros; apply H; auto).\n  apply le_trans with (1:= IHl H2 (n + n0)).\n  rewrite (plus_comm p), <- plus_assoc, (plus_comm p).\n  apply plus_le_compat;[trivial | apply plus_le_compat; trivial].\n Qed.\n\n Lemma cforallb_count : forall A (f:A -> bool * nat) p l,\n   (forall a, In a l -> snd (f a) <= p) ->\n   forall n, snd (cforallb f l n) <= length l * p + n.\n Proof.\n  induction l; simpl; intros; trivial.\n  case_eq (f a); intros.\n  assert (n0 <= p).\n   assert (W:= H a); rewrite H0 in W; simpl in W; apply W; auto.\n  destruct b; simpl.\n  assert (forall a0 : A, In a0 l -> snd (f a0) <= p) by (intros; apply H; auto).\n  apply le_trans with (1:= IHl H2 (n + n0)).\n  rewrite (plus_comm p), <- plus_assoc, (plus_comm p).\n  apply plus_le_compat;[trivial | apply plus_le_compat; trivial].\n  rewrite plus_comm; apply plus_le_compat; trivial.\n  apply le_trans with (1:= H1).\n  apply le_plus_l.\n Qed.\n\n Lemma cfind_default_count : forall A (f:A -> bool * nat) p l def,\n   (forall a, In a l -> snd (f a) <= p) ->\n   forall n, snd (cfind_default f l n def) <= length l * p + n.\n Proof.\n  induction l; simpl; intros; trivial.\n  unfold cfind_default in *; simpl.\n  case_eq (f a); intros.\n  assert (n0 <= p).\n   assert (W:= H a); rewrite H0 in W; simpl in W; apply W; auto.\n  destruct b; simpl.\n  rewrite plus_comm; apply plus_le_compat; trivial.\n  apply le_trans with (1:= H1).\n  apply le_plus_l.\n  assert (forall a0 : A, In a0 l -> snd (f a0) <= p) by (intros; apply H; auto).\n  apply le_trans with (1:= IHl def H2 (n + n0)).\n  rewrite (plus_comm p), <- plus_assoc, (plus_comm p).\n  apply plus_le_compat;[trivial | apply plus_le_compat; trivial].\n Qed.\n\n Lemma List_size_le : forall k t (l:T.interp k (T.List t)),\n    forall a: T.interp k t, In a l -> T.size (k:=k) (t:=t) a <= T.size (k:=k) (t:=T.List t) l.\n Proof.\n  induction l; simpl; intros a0 Hin; destruct Hin; apply le_S.\n  rewrite H; apply le_plus_l.\n  apply le_trans with (1:= IHl _ H); apply le_plus_r.\n Qed.\n\n Lemma PPT_length : forall t e F G,\n  PPT_expr e F G ->\n  PPT_expr (E.Eop (O.Olength t) {e}) \n  (fun p => pplus 1 (F p)) (fun p => pplus (F p) (G p)).\n Proof.\n  unfold PPT_expr; intros t e F G0 He k m p H.\n  generalize (He k m p H); clear H He.\n  simpl; rewrite E.ceval_expr_spec.\n  case (E.ceval_expr e m); intros l n [Hl Hn].\n  assert (W:length l <= peval (F p) k).\n   apply le_trans with (2:= Hl); refine (List_size_length l).\n  simpl fst; split.\n  rewrite pplus_spec, pcst_spec.\n  apply le_trans with (S (length l)).\n  case (length l).  \n  trivial.\n  intro n0; apply le_trans with (S n0); auto with arith.\n  apply size_nat_le; auto with arith.\n  simpl; apply le_n_S; trivial.\n  simpl; rewrite plus_0_r, pplus_spec; apply plus_le_compat; trivial.\n Qed.\n\n Lemma PPT_Zlength : forall t e F G,\n  PPT_expr e F G ->\n  PPT_expr (E.Eop (O.OZlength t) {e}) \n  (fun p => pplus 1 (F p)) (fun p => pplus (F p) (G p)).\n Proof.\n  unfold PPT_expr; intros t e F G0 He k m p H.\n  generalize (He k m p H); clear H He.\n  simpl; rewrite E.ceval_expr_spec.\n  case (E.ceval_expr e m); intros l n [Hl Hn].\n  assert (W:length l <= peval (F p) k).\n   apply le_trans with (2:= Hl); refine (List_size_length l).\n  simpl fst; split.\n  rewrite pplus_spec, pcst_spec.\n  apply le_trans with (S (length l)).\n  case (length l).  \n  trivial.\n  intro n0; apply le_trans with (S n0); auto with arith.\n  unfold size_Z; rewrite Zabs_nat_Z_of_nat.\n  apply size_nat_le; auto with arith.\n  simpl; apply le_n_S; trivial.\n  simpl; rewrite plus_0_r, pplus_spec; apply plus_le_compat; trivial.\n Qed.\n\n Lemma PPT_head : forall t e F G,\n  PPT_expr e F G ->\n  PPT_expr (E.Eop (O.Ohd t) {e}) \n   (fun p => pplus (T.default_poly t) (F p)) (fun p => pplus 1 (G p)).\n Proof.\n  unfold PPT_expr; intros t e F G0 He k m p H.\n  generalize (He k m p H); clear H He.\n  simpl; rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e m) as [l]; simpl; intros; split.\n  destruct l as [ | a l].\n  eapply le_trans; [ | apply pplus_le_l].\n  simpl; apply T.default_poly_spec.\n  destruct H as [H _]; simpl in H |- *.\n  eapply le_trans; [ | apply pplus_le_r].\n  apply le_trans with (2:=H); auto with arith.\n  destruct H.\n  rewrite plus_0_r, pplus_spec, pcst_spec; apply le_n_S; trivial.\n Qed.\n\n Lemma PPT_tail : forall t e F G,\n  PPT_expr e F G ->\n  PPT_expr (E.Eop (O.Otl t) {e}) F (fun p => pplus 1 (G p)).\n Proof.\n  unfold PPT_expr; intros t e F G0 He k m p H.\n  generalize (He k m p H); clear H He.\n  simpl; rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e m); simpl; intros [H1 H2]; split.\n  destruct i; simpl in H1 |- *.\n  trivial.\n  eapply le_trans; [ |apply H1].\n  auto with arith.\n  rewrite plus_0_r, pplus_spec, pcst_spec; apply le_n_S; trivial.\n Qed.\n\n Lemma PPT_fst : forall t1 t2 e F G,\n  PPT_expr e F G ->\n  PPT_expr (E.Eop (O.Ofst t1 t2) {e}) F (fun p => pplus 1 (G p)).\n Proof.\n  unfold PPT_expr; intros t1 t2 e F G0 He k m p H.\n  generalize (He k m p H); clear H He.\n  simpl; rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e m); simpl; intros [H1 H2]; split.\n  eapply le_trans; [ |apply H1]; auto with arith.\n  rewrite plus_0_r, pplus_spec, pcst_spec; apply le_n_S; trivial.\n Qed.\n\n Lemma PPT_snd : forall t1 t2 e F G,\n  PPT_expr e F G ->\n  PPT_expr (E.Eop (O.Osnd t1 t2) {e}) F (fun p => pplus 1 (G p)).\n Proof.\n  unfold PPT_expr; intros t1 t2 e F G0 He k m p H.\n  generalize (He k m p H); clear H He.\n  simpl; rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e m); simpl; intros [H1 H2]; split.\n  eapply le_trans; [ |apply H1]; auto with arith.\n  rewrite plus_0_r, pplus_spec, pcst_spec; apply le_n_S; trivial.\n Qed.\n\n Lemma PPT_Ocons : forall t e1 e2 F1 G1 F2 G2,\n  PPT_expr e1 F1 G1 ->\n  PPT_expr e2 F2 G2 ->\n  PPT_expr (E.Eop (O.Ocons t) {e1, e2})\n  (fun p => pplus 1 (pplus (F1 p) (F2 p))) (fun p => pplus 1 (pplus (G1 p) (G2 p))).\n Proof.\n  unfold PPT_expr; intros t e1 e2 F1 G1 F2 G2 He1 He2 k m p H.\n  generalize (He1 k m p); generalize (He2 k m p); clear He1 He2.\n  simpl; repeat rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e1 m); destruct (E.ceval_expr e2 m);\n   simpl; intros H1 H2.\n  destruct H1.\n  intros t0 x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e2); [ | trivial].\n  unfold fv_expr at 2; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec.\n  apply VsetP.subset_union_l.\n  destruct H2.\n  intros t0 x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].\n  unfold fv_expr; simpl.\n  apply fv_expr_rec_subset.\n  split.\n  rewrite pplus_spec, pplus_spec, pcst_spec.\n  apply le_n_S; apply plus_le_compat; tauto.\n  rewrite plus_0_r, pplus_spec, pplus_spec, pcst_spec.\n  apply le_n_S; apply plus_le_compat; trivial.\n Qed.\n\n Lemma PPT_Oappend : forall t e1 e2 F1 G1 F2 G2,\n  PPT_expr e1 F1 G1 ->\n  PPT_expr e2 F2 G2 ->\n  PPT_expr (E.Eop (O.Oappend t) {e1, e2})\n  (fun p => pplus (F1 p) (F2 p)) (fun p => pplus (F1 p) (pplus (G1 p) (G2 p))).\n Proof.\n  unfold PPT_expr; intros t e1 e2 F1 G1 F2 G2 He1 He2 k m p H.\n  generalize (He1 k m p); generalize (He2 k m p); clear He1 He2.\n  simpl; repeat rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e1 m); destruct (E.ceval_expr e2 m);\n   simpl; intros H1 H2.\n  destruct H1.\n  intros t0 x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e2); [ | trivial].\n  unfold fv_expr at 2; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec.\n  apply VsetP.subset_union_l.\n  destruct H2.\n  intros t0 x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].\n  unfold fv_expr; simpl.\n  apply fv_expr_rec_subset.\n  split.\n  rewrite pplus_spec.\n  apply le_trans with (fold_right\n       (fun (v : T.interp k t) (n : nat) => S (T.size (k:=k) (t:=t) v + n)) 1\n       i + peval (F2 p) k).\n  generalize i; clear H2 i.\n  induction i; simpl; intros.\n   apply le_trans with (1:= H0); apply le_S; trivial.\n   apply le_n_S.\n   rewrite <- plus_assoc; apply plus_le_compat; trivial.\n  apply plus_le_compat; trivial.\n  repeat rewrite pplus_spec; repeat apply plus_le_compat; trivial.\n  apply le_trans with (1:= List_size_length i); trivial.\n  rewrite plus_0_r; trivial.\n Qed.\n\n Lemma PPT_pair : forall t1 t2 e1 e2 F1 G1 F2 G2,\n  PPT_expr e1 F1 G1 ->\n  PPT_expr e2 F2 G2 ->\n  PPT_expr (E.Eop (O.Opair t1 t2) {e1, e2}) \n  (fun p => pplus 1 (pplus (F1 p) (F2 p))) (fun p => pplus 1 (pplus (G1 p) (G2 p))).\n Proof.\n  unfold PPT_expr; intros t1 t2 e1 e2 F1 G1 F2 G2 He1 He2 k m p H.\n  generalize (He1 k m p); generalize (He2 k m p); clear He1 He2.\n  simpl; repeat rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e1 m); destruct (E.ceval_expr e2 m); \n   simpl; intros H1 H2.\n  destruct H1.\n  intros t0 x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e2); [ | trivial].\n  unfold fv_expr at 2; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec.\n  apply VsetP.subset_union_l.\n  destruct H2.\n  intros t0 x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].\n  unfold fv_expr; simpl.\n  apply fv_expr_rec_subset.\n  split.\n  rewrite pplus_spec, pplus_spec, pcst_spec.\n  apply le_n_S; apply plus_le_compat; tauto.\n  rewrite plus_0_r, pplus_spec, pplus_spec, pcst_spec.\n  apply le_n_S; apply plus_le_compat; trivial.\n Qed.\n\n Lemma PPT_in_dom : forall t1 t2 e1 e2 F1 G1 F2 G2,\n  PPT_expr e1 F1 G1 ->\n  PPT_expr e2 F2 G2 ->\n  PPT_expr (E.Eop (O.Oin_dom t1 t2) {e1, e2})\n  (fun p => pcst 1) (fun p => pplus (pplus (pmult (F2 p) (pplus (F1 p) (F2 p))) (pcst 1)) (pplus (G2 p) (G1 p))).\n Proof.\n  unfold PPT_expr; intros t1 t2 e1 e2 F1 G1 F2 G2 He1 He2 k m p H.\n  generalize (He1 k m p); generalize (He2 k m p); clear He1 He2.\n  simpl; repeat rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e1 m) as [x nx].\n  case (E.ceval_expr e2 m); intros l n Hl Hn.\n  destruct Hn.\n  intros; apply H; unfold fv_expr; simpl.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].\n  apply fv_expr_rec_subset.\n  destruct Hl.\n  intros; apply H; unfold fv_expr; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec; auto with set.\n  unfold O.ceval_op; simpl; fold (T.interp k t2).\n  case_eq (cexistsb\n      (fun v1 : T.interp k t1 * T.interp k t2 =>\n       (T.i_eqb k t1 x (fst v1), O.eq_cost k t1 x (fst v1))) l 1); intros.\n  split;[rewrite pcst_spec; trivial | ].\n  match type of H4 with cexistsb ?F l _ = _ => set (f := F) in H4 end.\n  assert (forall a : T.interp k t1 * T.interp k t2,\n     In a l -> snd (f a) <= peval (pplus (F1 p) (F2 p)) k).\n   unfold f; intros; simpl; unfold O.eq_cost.\n   rewrite pplus_spec; apply plus_le_compat; trivial.\n   assert (W:= List_size_le l a H5); simpl in W.\n   apply le_trans with (2:= H2); apply le_trans with (2:= W).\n   apply le_S; apply le_plus_l.\n  assert (W:= @cexistsb_count _ f (peval (pplus (F1 p) (F2 p)) k) l H5 1).\n  rewrite pplus_spec; apply plus_le_compat.\n  rewrite H4 in W; simpl in W.\n  apply le_trans with (1:= W).\n  repeat (rewrite pplus_spec || rewrite pmult_spec).\n  apply plus_le_compat;[apply mult_le_compat; trivial | rewrite pcst_spec; trivial].\n  apply le_trans with (2:= H2); refine (List_size_length l).\n  rewrite plus_0_r, plus_comm, pplus_spec.\n  apply plus_le_compat; trivial.\n Qed.\n\n Lemma PPT_img : forall t1 t2 e1 e2 F1 G1 F2 G2,\n  PPT_expr e1 F1 G1 ->\n  PPT_expr e2 F2 G2 ->\n  PPT_expr (E.Eop (O.Oimg t1 t2) {e1, e2})\n  (fun p => pplus (F2 p) (T.default_poly t2)) \n  (fun p => pplus (pplus (pmult (F2 p) (pplus (F1 p) (F2 p))) (pcst 1)) (pplus (G2 p) (G1 p))).\n Proof.\n  unfold PPT_expr; intros t1 t2 e1 e2 F1 G1 F2 G2 He1 He2 k m p H.\n  generalize (He1 k m p); generalize (He2 k m p); clear He1 He2.\n  simpl; repeat rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e1 m) as [x nx].\n  case (E.ceval_expr e2 m); intros l n Hl Hn.\n  destruct Hn.\n  intros; apply H; unfold fv_expr; simpl.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].\n  apply fv_expr_rec_subset.\n  destruct Hl.\n  intros; apply H; unfold fv_expr; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec; auto with set.\n  unfold O.ceval_op; simpl; fold (T.interp k t2).\n  case_eq (cfind_default\n              (fun v1 : T.interp k t1 * T.interp k t2 =>\n               (T.i_eqb k t1 x (fst v1), O.eq_cost k t1 x (fst v1))) l 1\n              (T.default k t1, T.default k t2)); intros.\n  split.\n  assert (W:= @find_cfind_default _ \n             (fun v1 : T.interp k t1 * T.interp k t2 => T.i_eqb k t1 x (fst v1))\n             (fun v1 : T.interp k t1 * T.interp k t2 =>\n                (T.i_eqb k t1 x (fst v1), O.eq_cost k t1 x (fst v1)))\n             (T.default k t1, T.default k t2)\n             (fun x => refl_equal _)\n             l 1).\n  rewrite H4 in W; simpl in W; rewrite <- W.\n  unfold find_default; rewrite pplus_spec.\n  case_eq (find (fun v1 : T.interp k t1 * T.interp k t2 => T.i_eqb k t1 x (fst v1)) l); intros.\n  destruct (find_In _ _ H5).\n  apply le_trans with (peval (F2 p) k);[ | apply le_plus_l].\n  apply le_trans with (T.size (k:=k) (t:= T.Pair t1 t2) p1).\n  destruct p1; simpl; apply le_S; apply le_plus_r.\n  apply le_trans with (2:= H2); apply List_size_le; trivial.\n  apply le_trans with (peval (T.default_poly t2) k).\n  simpl; apply T.default_poly_spec.\n  apply le_plus_r.\n  rewrite pplus_spec; apply plus_le_compat.\n  match type of H4 with cfind_default ?F l _ _ = _ => set (f := F) in H4 end.\n  assert (forall a : T.interp k t1 * T.interp k t2,\n     In a l -> snd (f a) <= peval (pplus (F1 p) (F2 p)) k).\n   unfold f; intros; simpl; unfold O.eq_cost.\n   rewrite pplus_spec; apply plus_le_compat; trivial.\n   assert (W:= List_size_le l a H5); simpl in W.\n   apply le_trans with (2:= H2); apply le_trans with (2:= W).\n   apply le_S; apply le_plus_l.\n  assert (W:= @cfind_default_count _ f (peval (pplus (F1 p) (F2 p)) k) l (T.default k t1, T.default k t2) H5 1).\n  rewrite H4 in W; simpl in W.\n  rewrite pplus_spec, pcst_spec.\n  apply le_trans with (1:= W); apply plus_le_compat;[ | trivial].\n  repeat (rewrite pplus_spec || rewrite pmult_spec).\n  apply mult_le_compat;[ | trivial].\n  apply le_trans with (2:= H2); refine (List_size_length l).\n  rewrite plus_0_r, plus_comm, pplus_spec.\n  apply plus_le_compat; trivial.\n Qed.\n\n  Lemma PPT_in_range : forall t1 t2 e1 e2 F1 G1 F2 G2,\n  PPT_expr e1 F1 G1 ->\n  PPT_expr e2 F2 G2 ->\n  PPT_expr (E.Eop (O.Oin_range t1 t2) {e1, e2})\n  (fun p => pcst 1) (fun p => pplus (pplus (pmult (F2 p) (pplus (F1 p) (F2 p))) (pcst 1)) (pplus (G2 p) (G1 p))).\n Proof.\n  unfold PPT_expr; intros t1 t2 e1 e2 F1 G1 F2 G2 He1 He2 k m p H.\n  generalize (He1 k m p); generalize (He2 k m p); clear He1 He2.\n  simpl; repeat rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e1 m) as [x nx].\n  case (E.ceval_expr e2 m); intros l n Hl Hn.\n  destruct Hn.\n  intros; apply H; unfold fv_expr; simpl.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].\n  apply fv_expr_rec_subset.\n  destruct Hl.\n  intros; apply H; unfold fv_expr; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec; auto with set.\n  unfold O.ceval_op; simpl; fold (T.interp k t1).\n  case_eq (cexistsb\n      (fun v1 : T.interp k t1 * T.interp k t2 =>\n       (T.i_eqb k t2 x (snd v1), O.eq_cost k t2 x (snd v1))) l 1); intros.\n  split;[rewrite pcst_spec; trivial | ].\n  match type of H4 with cexistsb ?F l _ = _ => set (f := F) in H4 end.\n  assert (forall a : T.interp k t1 * T.interp k t2,\n     In a l -> snd (f a) <= peval (pplus (F1 p) (F2 p)) k).\n   unfold f; intros; simpl; unfold O.eq_cost.\n   rewrite pplus_spec; apply plus_le_compat; trivial.\n   assert (W:= List_size_le l a H5); simpl in W.\n   apply le_trans with (2:= H2); apply le_trans with (2:= W).\n   apply le_S; apply le_plus_r.\n  assert (W:= @cexistsb_count _ f (peval (pplus (F1 p) (F2 p)) k) l H5 1).\n  rewrite pplus_spec; apply plus_le_compat.\n  rewrite H4 in W; simpl in W.\n  apply le_trans with (1:= W).\n  repeat (rewrite pplus_spec || rewrite pmult_spec).\n  apply plus_le_compat;[apply mult_le_compat; trivial | rewrite pcst_spec; trivial].\n  apply le_trans with (2:= H2); refine (List_size_length l).\n  rewrite plus_0_r, plus_comm, pplus_spec.\n  apply plus_le_compat; trivial.\n Qed.\n\n Lemma PPT_mem : forall t1 e1 e2 F1 G1 F2 G2,\n  PPT_expr e1 F1 G1 ->\n  PPT_expr e2 F2 G2 ->\n  PPT_expr (E.Eop (O.Omem t1) {e1, e2})\n  (fun p => pcst 1) (fun p => pplus (pplus (pmult (F2 p) (pplus (F1 p) (F2 p))) (pcst 1)) (pplus (G2 p) (G1 p))).\n Proof.\n  unfold PPT_expr; intros t1 e1 e2 F1 G1 F2 G2 He1 He2 k m p H.\n  generalize (He1 k m p); generalize (He2 k m p); clear He1 He2.\n  simpl; repeat rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e1 m) as [x nx].\n  case (E.ceval_expr e2 m); intros l n Hl Hn.\n  destruct Hn.\n  intros; apply H; unfold fv_expr; simpl.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].\n  apply fv_expr_rec_subset.\n  destruct Hl.\n  intros; apply H; unfold fv_expr; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec; auto with set.\n  unfold O.ceval_op; simpl; fold (T.interp k t1).\n  case_eq (cexistsb\n      (fun v1 : T.interp k t1 =>\n       (T.i_eqb k t1 x v1, O.eq_cost k t1 x v1)) l 1); intros.\n  split;[rewrite pcst_spec; trivial | ].\n  match type of H4 with cexistsb ?F l _ = _ => set (f := F) in H4 end.\n  assert (forall a : T.interp k t1 ,\n     In a l -> snd (f a) <= peval (pplus (F1 p) (F2 p)) k).\n   unfold f; intros; simpl; unfold O.eq_cost.\n   rewrite pplus_spec; apply plus_le_compat; trivial.\n   assert (W:= List_size_le l a H5); simpl in W.\n   apply le_trans with (2:= H2); apply le_trans with (2:= W); trivial.\n  assert (W:= @cexistsb_count _ f (peval (pplus (F1 p) (F2 p)) k) l H5 1).\n  rewrite pplus_spec; apply plus_le_compat.\n  rewrite H4 in W; simpl in W.\n  apply le_trans with (1:= W).\n  repeat (rewrite pplus_spec || rewrite pmult_spec).\n  apply plus_le_compat;[apply mult_le_compat; trivial | rewrite pcst_spec; trivial].\n  apply le_trans with (2:= H2); refine (List_size_length l).\n  rewrite plus_0_r, plus_comm, pplus_spec.\n  apply plus_le_compat; trivial.\n Qed.\n\n Lemma PPT_nth : forall t1 e1 e2 F1 G1 F2 G2,\n  PPT_expr e1 F1 G1 ->\n  PPT_expr e2 F2 G2 ->\n  PPT_expr (E.Eop (O.Onth t1) {e1, e2})\n    (fun p => pplus (F2 p)(T.default_poly t1))\n    (fun p => pplus (F2 p) (pplus (G2 p) (G1 p))).\n Proof.\n  unfold PPT_expr; intros t1 e1 e2 F1 G1 F2 G2 He1 He2 k m p H.\n  generalize (He1 k m p); generalize (He2 k m p); clear He1 He2.\n  simpl; repeat rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e1 m) as [x nx].\n  case (E.ceval_expr e2 m); intros l n Hl Hn.\n  destruct Hn.\n  intros; apply H; unfold fv_expr; simpl.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].\n  apply fv_expr_rec_subset.\n  destruct Hl.\n  intros; apply H; unfold fv_expr; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec; auto with set.\n  simpl; split; rewrite pplus_spec.\n  destruct (nth_in_or_default x l (T.default k t1)).\n  apply le_trans with (1:= List_size_le l  (nth x l (T.default k t1)) i).\n  apply le_trans with (1:= H2); apply le_plus_l.\n  apply le_trans with (peval (T.default_poly t1) k).\n  unfold T.interp; rewrite e; apply T.default_poly_spec.\n  apply le_plus_r.\n  apply plus_le_compat.\n  apply le_trans with (1 := List_size_length l); trivial.\n  rewrite plus_0_r, pplus_spec, plus_comm; apply plus_le_compat; trivial.\n Qed.\n\n Lemma PPT_le : forall e1 e2 F1 G1 F2 G2,\n  PPT_expr e1 F1 G1 -> \n  PPT_expr e2 F2 G2 -> \n  PPT_expr (E.Eop O.Ole {e1, e2}) \n   (fun _ => 1) \n   (fun p => pplus (F1 p) (pplus (G1 p) (G2 p))).\n Proof.\n  unfold PPT_expr; intros e1 e2 F1 G1 F2 G2 He1 He2 k m p H.\n  generalize (He1 k m p); clear He1.\n  generalize (He2 k m p); clear He2.\n  simpl; rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e1 m) as [n Hn].\n  destruct (E.ceval_expr e2 m) as [n2 Hn2]; simpl; split.\n  rewrite pcst_spec; trivial.\n  destruct H0.\n  intros t x Hx; apply H.\n  unfold fv_expr; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec; auto with set.\n  destruct H1.\n  intros t x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].\n  unfold fv_expr; simpl.\n  apply fv_expr_rec_subset.\n  repeat rewrite pplus_spec; apply plus_le_compat; trivial.\n  rewrite plus_0_r; apply plus_le_compat; trivial.\n Qed.\n\n Lemma PPT_Zle : forall e1 e2 F1 G1 F2 G2,\n  PPT_expr e1 F1 G1 -> \n  PPT_expr e2 F2 G2 -> \n  PPT_expr (E.Eop O.OZle {e1, e2}) \n   (fun _ => 1) \n   (fun p => pplus (F1 p) (pplus (G1 p) (G2 p))).\n Proof.\n  unfold PPT_expr; intros e1 e2 F1 G1 F2 G2 He1 He2 k m p H.\n  generalize (He1 k m p); clear He1.\n  generalize (He2 k m p); clear He2.\n  simpl; rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e1 m) as [n Hn].\n  destruct (E.ceval_expr e2 m) as [n2 Hn2]; simpl; split.\n  rewrite pcst_spec; trivial.\n  destruct H0.\n  intros t x Hx; apply H.\n  unfold fv_expr; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec; auto with set.\n  destruct H1.\n  intros t x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].\n  unfold fv_expr; simpl.\n  apply fv_expr_rec_subset.\n  repeat rewrite pplus_spec; apply plus_le_compat; trivial.\n  rewrite plus_0_r; apply plus_le_compat; trivial.\n Qed.\n\n Lemma PPT_lt : forall e1 e2 F1 G1 F2 G2,\n  PPT_expr e1 F1 G1 -> \n  PPT_expr e2 F2 G2 -> \n  PPT_expr (E.Eop O.Olt {e1, e2}) \n   (fun _ => 1)\n   (fun p => pplus (F2 p) (pplus (G1 p) (G2 p))).\n Proof.\n  unfold PPT_expr; intros e1 e2 F1 G1 F2 G2 He1 He2 k m p H.\n  generalize (He1 k m p); clear He1.\n  generalize (He2 k m p); clear He2.\n  simpl; rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e1 m) as [v1 n1].\n  destruct (E.ceval_expr e2 m) as [v2 n2].\n  simpl; split.\n  rewrite pcst_spec; trivial.\n  destruct H0.\n  intros t x Hx; apply H.\n  unfold fv_expr; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec; auto with set.\n  destruct H1.\n  intros t x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].\n  unfold fv_expr; simpl.\n  apply fv_expr_rec_subset.\n  repeat rewrite pplus_spec; apply plus_le_compat; trivial.\n  rewrite plus_0_r; apply plus_le_compat; trivial.\n Qed.\n\n Lemma PPT_Zlt : forall e1 e2 F1 G1 F2 G2,\n  PPT_expr e1 F1 G1 -> \n  PPT_expr e2 F2 G2 -> \n  PPT_expr (E.Eop O.OZlt {e1, e2}) \n   (fun _ => 1)\n   (fun p => pplus (F2 p) (pplus (G1 p) (G2 p))).\n Proof.\n  unfold PPT_expr; intros e1 e2 F1 G1 F2 G2 He1 He2 k m p H.\n  generalize (He1 k m p); clear He1.\n  generalize (He2 k m p); clear He2.\n  simpl; rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e1 m) as [v1 n1].\n  destruct (E.ceval_expr e2 m) as [v2 n2].\n  simpl; split.\n  rewrite pcst_spec; trivial.\n  destruct H0.\n  intros t x Hx; apply H.\n  unfold fv_expr; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec; auto with set.\n  destruct H1.\n  intros t x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].\n  unfold fv_expr; simpl.\n  apply fv_expr_rec_subset.\n  repeat rewrite pplus_spec; apply plus_le_compat; trivial.\n  rewrite plus_0_r; apply plus_le_compat; trivial.\n Qed.\n\n Lemma PPT_Zgt : forall e1 e2 F1 G1 F2 G2,\n  PPT_expr e1 F1 G1 -> \n  PPT_expr e2 F2 G2 -> \n  PPT_expr (E.Eop O.OZgt {e1, e2}) \n   (fun _ => 1)\n   (fun p => pplus (F2 p) (pplus (G1 p) (G2 p))).\n Proof.\n  unfold PPT_expr; intros e1 e2 F1 G1 F2 G2 He1 He2 k m p H.\n  generalize (He1 k m p); clear He1.\n  generalize (He2 k m p); clear He2.\n  simpl; rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e1 m) as [v1 n1].\n  destruct (E.ceval_expr e2 m) as [v2 n2].\n  simpl; split.\n  rewrite pcst_spec; trivial.\n  destruct H0.\n  intros t x Hx; apply H.\n  unfold fv_expr; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec; auto with set.\n  destruct H1.\n  intros t x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].\n  unfold fv_expr; simpl.\n  apply fv_expr_rec_subset.\n  repeat rewrite pplus_spec; apply plus_le_compat; trivial.\n  rewrite plus_0_r; apply plus_le_compat; trivial.\n Qed.\n\n Lemma PPT_Zge : forall e1 e2 F1 G1 F2 G2,\n  PPT_expr e1 F1 G1 -> \n  PPT_expr e2 F2 G2 -> \n  PPT_expr (E.Eop O.OZge {e1, e2}) \n   (fun _ => 1)\n   (fun p => pplus (F2 p) (pplus (G1 p) (G2 p))).\n Proof.\n  unfold PPT_expr; intros e1 e2 F1 G1 F2 G2 He1 He2 k m p H.\n  generalize (He1 k m p); clear He1.\n  generalize (He2 k m p); clear He2.\n  simpl; rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e1 m) as [v1 n1].\n  destruct (E.ceval_expr e2 m) as [v2 n2].\n  simpl; split.\n  rewrite pcst_spec; trivial.\n  destruct H0.\n  intros t x Hx; apply H.\n  unfold fv_expr; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec; auto with set.\n  destruct H1.\n  intros t x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].\n  unfold fv_expr; simpl.\n  apply fv_expr_rec_subset.\n  repeat rewrite pplus_spec; apply plus_le_compat; trivial.\n  rewrite plus_0_r; apply plus_le_compat; trivial.\n Qed.\n   \n Lemma PPT_Zopp : forall e F G,\n  PPT_expr e F G -> \n  PPT_expr (E.Eop O.OZopp {e}) \n   (fun p => F p)\n   (fun p => pplus (F p) (G p)).\n Proof.\n  unfold PPT_expr; intros e F G He k m p H.\n  generalize (He k m p); clear He.\n  simpl; rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e m) as [v n].\n  simpl; split.\n  destruct H0.\n  intros t x Hx; apply H.\n  unfold fv_expr; simpl.\n  apply Hx.\n  unfold size_Z, Zabs_nat in *.\n  destruct v; simpl in *; trivial.\n  destruct H0.\n  intros t x Hx; apply H.\n  unfold fv_expr; simpl.\n  apply Hx.\n  rewrite pplus_spec; apply plus_le_compat; trivial.\n  omega.\n Qed.\n\n Lemma PPT_Zdiv : forall e1 e2 F1 G1 F2 G2,\n  PPT_expr e1 F1 G1 -> \n  PPT_expr e2 F2 G2 -> \n  PPT_expr (E.Eop O.OZdiv {e1, e2}) \n   (fun p => pplus (F1 p) (pcst 1))\n   (fun p => pplus (F1 p) (pplus (G1 p) (G2 p))).\n Proof.\n  unfold PPT_expr; intros e1 e2 F1 G1 F2 G2 He1 He2 k m p H.\n  generalize (He1 k m p); clear He1.\n  generalize (He2 k m p); clear He2.\n  simpl; repeat rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e1 m) as [v1 n1].\n  destruct (E.ceval_expr e2 m) as [v2 n2].\n  simpl; split.\n  destruct H0.\n  intros t x Hx; apply H.\n  unfold fv_expr; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec; auto with set.\n  destruct H1.\n  intros t x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].\n  unfold fv_expr; simpl.\n  apply fv_expr_rec_subset.\n  unfold size_Z in *.\n\n  assert (forall p1 p2,  \n    size_nat (Zabs_nat (Zpos p1)) <= (F1 p) k ->\n    size_nat (Zabs_nat (Zpos p1 / Zpos p2)) <= (F1 p) k).\n  intros.\n  apply le_trans with (2 := H4).\n  apply size_nat_monotonic.\n  apply Zabs_nat_le.\n  split.\n  apply Z_div_pos; auto with zarith.\n  apply Zdiv_le_upper_bound; auto with zarith.\n  apply Zgt_lt.\n  apply Zgt_pos_0.\n  apply Zle_trans with ((Zpos p1) * 1)%Z.\n  auto with zarith.\n  apply Zmult_le_compat; auto with zarith.\n  generalize (Zgt_pos_0 p2); omega.\n\n  rewrite pplus_spec, pcst_spec.\n  destruct v1; destruct v2; auto; simpl; try omega.\n  \n  apply le_trans with ((F1 p) k); auto with zarith.\n\n  rewrite <- (Zopp_involutive (Zneg p1)).\n  rewrite Zopp_neg.\n  destruct (Z_eq_dec (Zmod (Zpos p0) (Zpos p1)) 0%Z).\n  rewrite Z_div_zero_opp_r; trivial.\n  cutrewrite (Zabs_nat (- (Zpos p0 / Zpos p1)) = Zabs_nat (Zpos p0 / Zpos p1)).\n  apply le_trans with ((F1 p) k); auto with zarith.\n  destruct (Zpos p0 / Zpos p1)%Z; simpl; auto.\n  rewrite Z_div_nz_opp_r; trivial.\n  cutrewrite (Zabs_nat (- (Zpos p0 / Zpos p1) - 1) = Zabs_nat (Zpos p0 / Zpos p1 + 1)).\n  rewrite Zabs_nat_Zplus; simpl; auto with arith.\n  apply le_trans with (1 := size_nat_plus _ _); simpl.\n  apply plus_le_compat; auto.\n  apply Z_div_pos; auto with zarith.\n  omega.\n  assert (forall x, Zabs_nat x = Zabs_nat (- x)).\n  intros x; destruct x; auto.\n  rewrite H5.\n  f_equal; ring.\n\n  rewrite <- (Zopp_involutive (Zneg p0)).\n  rewrite Zopp_neg.\n  destruct (Z_eq_dec (Zmod (Zpos p0) (Zpos p1)) 0%Z).\n  rewrite Z_div_zero_opp_full; trivial.\n  cutrewrite (Zabs_nat (- (Zpos p0 / Zpos p1)) = Zabs_nat (Zpos p0 / Zpos p1)).\n  apply le_trans with ((F1 p) k); auto with zarith.\n  destruct (Zpos p0 / Zpos p1)%Z; simpl; auto.\n  rewrite Z_div_nz_opp_full; trivial.\n  cutrewrite (Zabs_nat (- (Zpos p0 / Zpos p1) - 1) = Zabs_nat (Zpos p0 / Zpos p1 + 1)).\n  rewrite Zabs_nat_Zplus; simpl; auto with arith.\n  apply le_trans with (1 := size_nat_plus _ _); simpl.\n  apply plus_le_compat; auto.\n  apply Z_div_pos; auto with zarith.\n  omega.\n  assert (forall x, Zabs_nat x = Zabs_nat (- x)).\n  intros x; destruct x; auto.\n  rewrite H5.\n  f_equal; ring.\n\n  rewrite <- (Zopp_involutive (Zneg p0)), <- (Zopp_involutive (Zneg p1)).\n  repeat rewrite Zopp_neg.\n  rewrite Zdiv_opp_opp.\n  apply le_trans with ((F1 p) k); auto with zarith.\n  repeat rewrite pplus_spec.\n  destruct H0.\n  intros t x Hx; apply H.\n  unfold fv_expr; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec; auto with set.\n  destruct H1.\n  intros t x Hx; apply H.\n  unfold fv_expr; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec; auto with set.\n  omega.\nQed.\n\n Lemma PPT_Zmod : forall e1 e2 F1 G1 F2 G2,\n  PPT_expr e1 F1 G1 -> \n  PPT_expr e2 F2 G2 -> \n  PPT_expr (E.Eop O.OZmod {e1, e2}) \n   (fun p => F2 p)\n   (fun p => pplus (F2 p) (pplus (G1 p) (G2 p))).\n Proof.\n  unfold PPT_expr; intros e1 e2 F1 G1 F2 G2 He1 He2 k m p H.\n  generalize (He1 k m p); clear He1.\n  generalize (He2 k m p); clear He2.\n  simpl; repeat rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e1 m) as [v1 n1].\n  destruct (E.ceval_expr e2 m) as [v2 n2].\n  simpl; intros.\n  destruct H0.\n  intros t x Hx; apply H.\n  unfold fv_expr; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec; auto with set.\n  destruct H1.\n  intros t x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].\n  unfold fv_expr; simpl.\n  apply fv_expr_rec_subset.\n  split.\n  apply le_trans with (2 := H0).\n  destruct v2; simpl.\n  rewrite Zmod_0_r; auto.\n  unfold size_Z.\n  apply size_nat_monotonic.\n  apply Zabs_nat_le.\n  generalize (Z_mod_lt v1 (Zpos p0)); intros.\n  destruct H4.\n  apply Zgt_pos_0.\n  omega.\n  rewrite <- (Zopp_involutive (Zneg p0)).\n  rewrite Zopp_neg.\n  destruct (Z_eq_dec (Zmod v1 (Zpos p0)) 0%Z).\n  rewrite Z_mod_zero_opp_r; trivial.\n  unfold size_Z; simpl; auto.\n  apply size_nat_positive.\n  rewrite Z_mod_nz_opp_r; trivial.\n  unfold size_Z.\n  apply size_nat_monotonic.\n  assert (forall x, Zabs_nat x = Zabs_nat (- x)).\n  intros x; destruct x; auto.\n  rewrite H4.\n  cutrewrite (- (v1 mod Zpos p0 - Zpos p0) = Zpos p0 - (v1 mod Zpos p0))%Z;[ | ring].\n  rewrite Zabs_nat_Zminus.\n  rewrite <- H4.\n  omega.\n  generalize (Z_mod_lt v1 (Zpos p0)); intros.\n  destruct H5.\n  apply Zgt_pos_0.\n  omega.\n  repeat rewrite pplus_spec.\n  omega.\n Qed.\n\n Lemma PPT_not : forall e F G,\n  PPT_expr e F G -> \n  PPT_expr (E.Eop O.Onot {e})\n   (fun _ => 1)\n   (fun p => pplus 1 (G p)).\n Proof.\n  unfold PPT_expr; intros e F G0 He k m p H.\n  generalize (He k m p); clear He.\n  simpl; destruct (E.ceval_expr e m) as [n Hn]; split.\n  rewrite pcst_spec; trivial.  \n  destruct (H0 H).\n  rewrite pplus_spec, plus_0_r, pcst_spec; apply le_n_S; trivial.\n Qed.\n\n Lemma PPT_and : forall e1 e2 F1 G1 F2 G2,\n  PPT_expr e1 F1 G1 -> \n  PPT_expr e2 F2 G2 -> \n  PPT_expr (E.Eop O.Oand {e1, e2})\n   (fun _ => 1)\n   (fun p => pplus 1 (pplus (G1 p) (G2 p))).\n Proof.\n  unfold PPT_expr; intros e1 e2 F1 G1 F2 G2 He1 He2 k m p H.\n  generalize (He1 k m p); clear He1.\n  generalize (He2 k m p); clear He2.\n  simpl; destruct (E.ceval_expr e1 m) as [n Hn].\n  destruct (E.ceval_expr e2 m) as [n2 Hn2]; simpl; split.\n  rewrite pcst_spec; trivial.\n  destruct H0.\n  intros t x Hx; apply H.\n  unfold fv_expr; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec; auto with set.\n  destruct H1.\n  intros t x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].\n  unfold fv_expr; simpl.\n  apply fv_expr_rec_subset.\n  rewrite pplus_spec, pplus_spec, pcst_spec; apply le_n_S.\n  rewrite plus_0_r; apply plus_le_compat; trivial.\n Qed.\n\n Lemma PPT_or : forall e1 e2 F1 G1 F2 G2,\n  PPT_expr e1 F1 G1 -> \n  PPT_expr e2 F2 G2 -> \n  PPT_expr (E.Eop O.Oor {e1, e2})\n   (fun _ => 1)\n   (fun p => pplus 1 (pplus (G1 p) (G2 p))).\n Proof.\n  unfold PPT_expr; intros e1 e2 F1 G1 F2 G2 He1 He2 k m p H.\n  generalize (He1 k m p); clear He1.\n  generalize (He2 k m p); clear He2.\n  simpl; destruct (E.ceval_expr e1 m) as [n Hn].\n  destruct (E.ceval_expr e2 m) as [n2 Hn2]; simpl; split.\n  rewrite pcst_spec; trivial.\n  destruct H0.\n  intros t x Hx; apply H.\n  unfold fv_expr; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec; auto with set.\n  destruct H1.\n  intros t x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].\n  unfold fv_expr; simpl.\n  apply fv_expr_rec_subset.\n  rewrite pplus_spec, pplus_spec, pcst_spec; apply le_n_S.\n  rewrite plus_0_r; apply plus_le_compat; trivial.\n Qed.\n\n Lemma PPT_imp : forall e1 e2 F1 G1 F2 G2,\n  PPT_expr e1 F1 G1 -> \n  PPT_expr e2 F2 G2 -> \n  PPT_expr (E.Eop O.Oimp {e1, e2})\n   (fun _ => 1)\n   (fun p => pplus 1 (pplus (G1 p) (G2 p))).\n Proof.\n  unfold PPT_expr; intros e1 e2 F1 G1 F2 G2 He1 He2 k m p H.\n  generalize (He1 k m p); clear He1.\n  generalize (He2 k m p); clear He2.\n  simpl; destruct (E.ceval_expr e1 m) as [n Hn].\n  destruct (E.ceval_expr e2 m) as [n2 Hn2]; simpl; split.\n  rewrite pcst_spec; trivial.\n  destruct H0.\n  intros t x Hx; apply H.\n  unfold fv_expr; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec; auto with set.\n  destruct H1.\n  intros t x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].\n  unfold fv_expr; simpl.\n  apply fv_expr_rec_subset.\n  rewrite pplus_spec, pplus_spec, pcst_spec; apply le_n_S.\n  rewrite plus_0_r; apply plus_le_compat; trivial.\n Qed.\n\n Lemma PPT_if : forall t e1 (e2 e3:E.expr t) F1 G1 F2 G2 F3 G3,\n  PPT_expr e1 F1 G1 ->\n  PPT_expr e2 F2 G2 ->\n  PPT_expr e3 F3 G3 ->\n  PPT_expr (E.Eop (O.Oif t) {e1, e2, e3})\n   (fun p => pplus (F2 p) (F3 p))\n   (fun p => pplus (S 0) (pplus (G1 p) (pplus (G2 p) (G3 p)))).\n Proof.\n  unfold PPT_expr; intros t e1 e2 e3 F1 G1 F2 G2 F3 G3 He1 He2 He3 k m p H.\n  generalize (He1 k m p); clear He1.\n  generalize (He2 k m p); clear He2.\n  generalize (He3 k m p); clear He3.\n  simpl; repeat rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e1 m) as [v1 n1].\n  destruct (E.ceval_expr e2 m) as [v2 n2].\n  destruct (E.ceval_expr e3 m) as [v3 n3].\n  simpl; intros.\n  destruct H0.\n  intros t0 x Hx; apply H.\n  unfold fv_expr; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  fold (fv_expr_extend e3 (fv_expr_extend e2 (fv_expr_rec Vset.empty e1))).\n  rewrite union_fv_expr_spec; auto with set.\n  destruct H1.\n  intros t0 x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e2); [ | trivial].\n  unfold fv_expr; simpl.  \n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  fold (fv_expr_extend e3 (fv_expr_extend e2 (fv_expr_rec Vset.empty e1))).\n  rewrite union_fv_expr_spec; rewrite union_fv_expr_spec; auto with set.\n  destruct H2.\n  intros t0 x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].\n  unfold fv_expr; simpl.  \n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  fold (fv_expr_extend e3 (fv_expr_extend e2 (fv_expr_rec Vset.empty e1))).\n  rewrite union_fv_expr_spec; rewrite union_fv_expr_spec; auto with set.\n  split.\n  case v1.\n  eapply le_trans; [ |  apply pplus_le_l]; trivial.\n  eapply le_trans; [ |  apply pplus_le_r]; trivial.\n  rewrite pplus_spec, pplus_spec, pplus_spec, pcst_spec.\n  apply le_n_S.\n  rewrite plus_0_r; apply plus_le_compat; trivial.\n  apply plus_le_compat; trivial.\n Qed.\n\n Lemma PPT_add : forall e1 e2 F1 G1 F2 G2,\n  PPT_expr e1 F1 G1 ->\n  PPT_expr e2 F2 G2 ->\n  PPT_expr (E.Eop O.Oadd {e1, e2})\n  (fun p => pplus (F1 p) (F2 p))\n  (fun p => pplus (F1 p) (pplus (G1 p) (G2 p))).\n Proof.\n  unfold PPT_expr; intros e1 e2 F1 G1 F2 G2 He1 He2 k m p H.\n  generalize (He1 k m p); generalize (He2 k m p); clear He1 He2.\n  simpl; repeat rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e2 m). \n  destruct (E.ceval_expr e1 m).\n  intros H2 H1.\n  destruct H1 as [HF1 HG1].\n  intros t x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].\n  unfold fv_expr; simpl.\n  apply fv_expr_rec_subset. \n  destruct H2 as [HF2 HG2].\n  intros t x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e2); [ | trivial].\n  unfold fv_expr at 2; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec.\n  apply VsetP.subset_union_l.\n  simpl; split.\n  rewrite pplus_spec.\n  eapply le_trans; [apply size_nat_plus | ].\n  apply plus_le_compat; trivial.\n  rewrite pplus_spec; apply plus_le_compat.\n  trivial.\n  rewrite plus_0_r, pplus_spec; apply plus_le_compat; trivial.\n Qed.\n\n Lemma ineq_triang_Zabs_nat : forall a b,\n  Zabs_nat (a + b) <= Zabs_nat a + Zabs_nat b.\n Proof.\n  intros.\n  induction a; simpl; induction b; simpl; auto with zarith.\n  rewrite nat_of_P_plus_morphism; trivial.\n\n  generalize (lt_eq_lt_dec (nat_of_P p) (nat_of_P p0)); intro Helim; elim Helim;\n     [ intro Helim'; elim Helim';clear Helim' | ]; intro H; clear Helim.\n  rewrite (nat_of_P_lt_Lt_compare_complement_morphism p p0 H); simpl.\n  rewrite nat_of_P_minus_morphism.\n  apply le_trans with (nat_of_P p0).\n  apply le_minus.\n  apply le_plus_r.\n  apply nat_of_P_gt_Gt_compare_complement_morphism.\n  change (nat_of_P p < nat_of_P p0); trivial.\n \n  assert (Heq := nat_of_P_inj p p0 H);subst.\n  rewrite Pcompare_refl; simpl; trivial.\n  rewrite <- nat_of_P_plus_morphism; trivial.\n  apply lt_le_weak.\n  apply lt_O_nat_of_P.\n\n  rewrite (nat_of_P_gt_Gt_compare_complement_morphism p p0 H); simpl.\n  rewrite nat_of_P_minus_morphism.\n  apply le_trans with (nat_of_P p).\n  apply le_minus.\n  apply le_plus_l.\n  apply nat_of_P_gt_Gt_compare_complement_morphism.\n  change (nat_of_P p0 < nat_of_P p); trivial.\n\n   generalize (lt_eq_lt_dec (nat_of_P p) (nat_of_P p0)); intro Helim; elim Helim;\n     [ intro Helim'; elim Helim';clear Helim' | ]; intro H; clear Helim.\n    rewrite (nat_of_P_lt_Lt_compare_complement_morphism p p0 H); simpl.\n  rewrite nat_of_P_minus_morphism.\n  apply le_trans with (nat_of_P p0).\n  apply le_minus.\n  apply le_plus_r.\n  apply nat_of_P_gt_Gt_compare_complement_morphism.\n  change (nat_of_P p < nat_of_P p0); trivial.\n\n  assert (Heq := nat_of_P_inj p p0 H);subst.\n  rewrite Pcompare_refl; simpl; trivial.\n  rewrite <- nat_of_P_plus_morphism; trivial.\n  apply lt_le_weak.\n  apply lt_O_nat_of_P.\n\n  rewrite (nat_of_P_gt_Gt_compare_complement_morphism p p0 H); simpl.\n  rewrite nat_of_P_minus_morphism.\n  apply le_trans with (nat_of_P p).\n  apply le_minus.\n  apply le_plus_l.\n  apply nat_of_P_gt_Gt_compare_complement_morphism.\n  change (nat_of_P p0 < nat_of_P p); trivial.\n  \n  rewrite nat_of_P_plus_morphism; trivial.\n Qed.\n\n Lemma ineq_triang_Zabs_nat_minus : forall a b,\n  Zabs_nat (a - b) <= Zabs_nat a + Zabs_nat b.\n Proof.\n  intros.\n  induction a; simpl; induction b; simpl; auto with zarith.\n\n  generalize (lt_eq_lt_dec (nat_of_P p) (nat_of_P p0)); intro Helim; elim Helim;\n     [ intro Helim'; elim Helim';clear Helim' | ]; intro H; clear Helim.\n  rewrite (nat_of_P_lt_Lt_compare_complement_morphism p p0 H); simpl.\n  rewrite nat_of_P_minus_morphism.\n  apply le_trans with (nat_of_P p0).\n  apply le_minus.\n  apply le_plus_r.\n  apply nat_of_P_gt_Gt_compare_complement_morphism.\n  change (nat_of_P p < nat_of_P p0); trivial.\n \n  assert (Heq := nat_of_P_inj p p0 H);subst.\n  rewrite Pcompare_refl; simpl; trivial.\n  rewrite <- nat_of_P_plus_morphism; trivial.\n  apply lt_le_weak.\n  apply lt_O_nat_of_P.\n\n  rewrite (nat_of_P_gt_Gt_compare_complement_morphism p p0 H); simpl.\n  rewrite nat_of_P_minus_morphism.\n  apply le_trans with (nat_of_P p).\n  apply le_minus.\n  apply le_plus_l.\n  apply nat_of_P_gt_Gt_compare_complement_morphism.\n  change (nat_of_P p0 < nat_of_P p); trivial.\n\n  rewrite nat_of_P_plus_morphism; trivial.\n  rewrite nat_of_P_plus_morphism; trivial.\n\n   generalize (lt_eq_lt_dec (nat_of_P p) (nat_of_P p0)); intro Helim; elim Helim;\n     [ intro Helim'; elim Helim';clear Helim' | ]; intro H; clear Helim.\n    rewrite (nat_of_P_lt_Lt_compare_complement_morphism p p0 H); simpl.\n  rewrite nat_of_P_minus_morphism.\n  apply le_trans with (nat_of_P p0).\n  apply le_minus.\n  apply le_plus_r.\n  apply nat_of_P_gt_Gt_compare_complement_morphism.\n  change (nat_of_P p < nat_of_P p0); trivial.\n\n  assert (Heq := nat_of_P_inj p p0 H);subst.\n  rewrite Pcompare_refl; simpl; trivial.\n  rewrite <- nat_of_P_plus_morphism; trivial.\n  apply lt_le_weak.\n  apply lt_O_nat_of_P.\n\n  rewrite (nat_of_P_gt_Gt_compare_complement_morphism p p0 H); simpl.\n  rewrite nat_of_P_minus_morphism.\n  apply le_trans with (nat_of_P p).\n  apply le_minus.\n  apply le_plus_l.\n  apply nat_of_P_gt_Gt_compare_complement_morphism.\n  change (nat_of_P p0 < nat_of_P p); trivial.\n Qed.\n\n Lemma PPT_Zadd : forall e1 e2 F1 G1 F2 G2,\n  PPT_expr e1 F1 G1 ->\n  PPT_expr e2 F2 G2 ->\n  PPT_expr (E.Eop O.OZadd {e1, e2})\n  (fun p => pplus (F1 p) (F2 p))\n  (fun p => pplus (F1 p) (pplus (G1 p) (G2 p))).\n Proof.\n  unfold PPT_expr; intros e1 e2 F1 G1 F2 G2 He1 He2 k m p H.\n  generalize (He1 k m p); generalize (He2 k m p); clear He1 He2.\n  simpl; repeat rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e2 m). \n  destruct (E.ceval_expr e1 m).\n  intros H2 H1.\n  destruct H1 as [HF1 HG1].\n  intros t x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].\n  unfold fv_expr; simpl.\n  apply fv_expr_rec_subset. \n  destruct H2 as [HF2 HG2].\n  intros t x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e2); [ | trivial].\n  unfold fv_expr at 2; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec.\n  apply VsetP.subset_union_l.\n  simpl; split.\n  rewrite pplus_spec.\n  unfold size_Z in * |- *.\n  \n  apply le_trans with (size_nat ((Zabs_nat i0) + (Zabs_nat i))).\n  apply size_nat_monotonic.\n  apply ineq_triang_Zabs_nat.\n  apply le_trans with (size_nat (Zabs_nat i0) + size_nat (Zabs_nat i)).\n  apply size_nat_plus.\n  apply plus_le_compat; trivial.\n  rewrite plus_0_r, pplus_spec; apply plus_le_compat; trivial.\n  rewrite pplus_spec; apply plus_le_compat; trivial.\n Qed.\n\n Lemma PPT_sub : forall e1 e2 F1 G1 F2 G2,\n  PPT_expr e1 F1 G1 ->\n  PPT_expr e2 F2 G2 ->\n  PPT_expr (E.Eop O.Osub {e1, e2})\n  (fun p => F1 p)\n  (fun p => pplus (F2 p) (pplus (G1 p) (G2 p))).\n Proof.\n  unfold PPT_expr; intros e1 e2 F1 G1 F2 G2 He1 He2 k m p H.\n  generalize (He1 k m p); generalize (He2 k m p); clear He1 He2.\n  simpl; repeat rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e2 m) as [v1 n1].  \n  destruct (E.ceval_expr e1 m) as [v2 n2].\n  intros H2 H1.\n  destruct H1 as [HF1 HG1].\n  intros t x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].\n  unfold fv_expr; simpl.\n  apply fv_expr_rec_subset. \n  destruct H2 as [HF2 HG2].\n  intros t x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e2); [ | trivial].\n  unfold fv_expr at 2; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec.\n  apply VsetP.subset_union_l.\n  simpl; split.\n\n  apply le_trans with (size_nat v2).\n  apply size_nat_monotonic; omega.\n  trivial.\n  rewrite pplus_spec, pplus_spec.  \n  apply plus_le_compat; trivial.\n  rewrite plus_0_r.\n  apply plus_le_compat; trivial.\n Qed. \n\n Lemma PPT_Zsub : forall e1 e2 F1 G1 F2 G2,\n  PPT_expr e1 F1 G1 ->\n  PPT_expr e2 F2 G2 ->\n  PPT_expr (E.Eop O.OZsub {e1, e2})\n  (fun p => pplus (F1 p) (F2 p))\n  (fun p => pplus (F2 p) (pplus (G1 p) (G2 p))).\n Proof.\n  unfold PPT_expr; intros e1 e2 F1 G1 F2 G2 He1 He2 k m p H.\n  generalize (He1 k m p); generalize (He2 k m p); clear He1 He2.\n  simpl; repeat rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e2 m) as [v1 n1].  \n  destruct (E.ceval_expr e1 m) as [v2 n2].\n  intros H2 H1.\n  destruct H1 as [HF1 HG1].\n  intros t x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].\n  unfold fv_expr; simpl.\n  apply fv_expr_rec_subset. \n  destruct H2 as [HF2 HG2].\n  intros t x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e2); [ | trivial].\n  unfold fv_expr at 2; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec.\n  apply VsetP.subset_union_l.\n  simpl; split.\n\n  unfold size_Z in * |- *.\n  apply le_trans with (size_nat (Zabs_nat v1 + Zabs_nat v2)).\n  apply size_nat_monotonic.\n  rewrite plus_comm.\n  apply  ineq_triang_Zabs_nat_minus.\n  rewrite pplus_spec.\n  apply le_trans with (size_nat (Zabs_nat v1) + size_nat (Zabs_nat v2)).\n  apply size_nat_plus.\n  rewrite plus_comm.\n  apply plus_le_compat; trivial.  \n\n  rewrite pplus_spec, pplus_spec.  \n  apply plus_le_compat; trivial.\n  rewrite plus_0_r.\n  apply plus_le_compat; trivial.\n Qed.\n\n Lemma PPT_mul : forall e1 e2 F1 G1 F2 G2,\n  PPT_expr e1 F1 G1 ->\n  PPT_expr e2 F2 G2 ->\n  PPT_expr (E.Eop O.Omul {e1, e2})\n   (fun p => pplus (F1 p) (F2 p))\n   (fun p => pplus (pmult (F1 p) (F2 p)) (pplus (G1 p) (G2 p))).\n Proof.\n  unfold PPT_expr; intros e1 e2 F1 G1 F2 G2 He1 He2 k m p H.\n  generalize (He1 k m p); generalize (He2 k m p); clear He1 He2.\n  simpl; repeat rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e2 m). \n  destruct (E.ceval_expr e1 m).\n  intros H2 H1.\n  destruct H1 as [HF1 HG1].\n  intros t x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].\n  unfold fv_expr; simpl.\n  apply fv_expr_rec_subset. \n  destruct H2 as [HF2 HG2].\n  intros t x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e2); [ | trivial].\n  unfold fv_expr at 2; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec.\n  apply VsetP.subset_union_l.\n  simpl; split.\n\n  rewrite pplus_spec.\n  eapply le_trans; [apply size_nat_mult | ].\n  apply plus_le_compat; trivial.\n\n  rewrite pplus_spec, pmult_spec; apply plus_le_compat.\n  apply mult_le_compat; trivial.\n  rewrite plus_0_r, pplus_spec; apply plus_le_compat; trivial.\n Qed.\n\n Lemma PPT_Zmul : forall e1 e2 F1 G1 F2 G2,\n  PPT_expr e1 F1 G1 ->\n  PPT_expr e2 F2 G2 ->\n  PPT_expr (E.Eop O.OZmul {e1, e2})\n   (fun p => pplus (F1 p) (F2 p))\n   (fun p => pplus (pmult (F1 p) (F2 p)) (pplus (G1 p) (G2 p))).\n Proof.\n  unfold PPT_expr; intros e1 e2 F1 G1 F2 G2 He1 He2 k m p H.\n  generalize (He1 k m p); generalize (He2 k m p); clear He1 He2.\n  simpl; repeat rewrite E.ceval_expr_spec.\n  destruct (E.ceval_expr e2 m). \n  destruct (E.ceval_expr e1 m).\n  intros H2 H1.\n  destruct H1 as [HF1 HG1].\n  intros t x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e1); [ | trivial].\n  unfold fv_expr; simpl.\n  apply fv_expr_rec_subset. \n  destruct H2 as [HF2 HG2].\n  intros t x Hx; apply H.\n  apply Vset.subset_correct with (fv_expr e2); [ | trivial].\n  unfold fv_expr at 2; simpl.\n  fold (fv_expr_extend e2 (fv_expr_rec Vset.empty e1)).\n  rewrite union_fv_expr_spec.\n  apply VsetP.subset_union_l.\n  simpl; split.\n\n  unfold size_Z in * |- *.\n  rewrite pplus_spec.\n  rewrite Zabs_nat_mult.\n  apply le_trans with ((size_nat (Zabs_nat i0) + size_nat ( Zabs_nat i))).\n  apply size_nat_mult.\n  apply plus_le_compat; trivial.  \n\n  rewrite pplus_spec, pmult_spec; apply plus_le_compat.\n  apply mult_le_compat; trivial.\n  rewrite plus_0_r, pplus_spec; apply plus_le_compat; trivial.\n Qed.\n\n\n (** Supports *)\n\n Lemma PPT_Dbool : PPT_support E.Dbool (fun p => pplus p 1) (fun p => 1).\n Proof.  \n  intros k m p Hm.\n  simpl; split.\n  intros b Hb.\n  apply le_trans with (peval 1 k).\n  rewrite pcst_spec; trivial.\n  apply pplus_le_r.\n  rewrite pcst_spec; trivial.\n Qed.\n\n Lemma PPT_Dnat : forall e Fe Ge,\n  PPT_expr e Fe Ge ->\n  PPT_support (E.Dnat e) Fe Ge.\n Proof.\n  intros e Fe Ge He k m p Hm; simpl.\n  generalize (He k m p Hm); clear He Hm.\n  case (E.ceval_expr e m); intros v n [H1 H2]; split.\n  intros v0 Hin.\n  apply le_trans with (size_nat v); [clear H1 | trivial].\n  apply size_nat_monotonic.\n  induction v.\n  simpl in Hin; case Hin; intro H; [subst; trivial | elim H].\n  replace (S v) with (v + 1) in Hin by (rewrite plus_comm; trivial).\n  rewrite seq_append in Hin.\n  simpl in Hin; case Hin; intro H; clear Hin. \n  rewrite <- H; apply le_O_n.\n  case (in_app_or _ _ _ H); clear H; intro Hin.\n  apply le_trans with v; [ | apply le_S; trivial].\n  apply IHv; right; trivial.\n  simpl in Hin; case Hin; intro H; [subst; trivial | elim H].\n  trivial.\n Qed.\n\n Lemma In_seqZ_le :\n   forall (n : nat) (m i : Z), In i (seqZ m n) -> (m <= i < Z_of_nat n + m)%Z.\n Proof.\n   induction n; intros.\n   elim H.\n   simpl seqZ in H.\n   simpl In in H.\n   destruct H; subst.\n   split.\n   omega.\n   apply Zle_lt_trans with (Z_of_nat 0%nat + i)%Z.\n   omega.\n   apply Zplus_lt_compat_r.\n   apply inj_lt.\n   omega.\n   apply IHn in H.\n   destruct H.\n   split.\n   omega.\n   rewrite inj_S.\n   omega.\n Qed.\n\n Lemma PPT_DZ : forall e1 e2 F1 F2 G1 G2,\n   PPT_expr e1 F1 G1 ->\n   PPT_expr e2 F2 G2 ->\n   PPT_support (E.DZ e1 e2)\n   (fun p => pplus 1 (pplus (F1 p) (F2 p)))\n   (fun p => pplus (G1 p) (G2 p)).\n Proof.\n  intros e1 e2 F1 F2 G1 G2 H1 H2 k m p Hm; simpl.\n  generalize (H1 k m p); clear H1.\n  generalize (H2 k m p); clear H2.\n  destruct (E.ceval_expr e1 m).\n  destruct (E.ceval_expr e2 m).\n  intros.\n  simpl in Hm.\n  rewrite pplus_spec, pplus_spec, pcst_spec, pplus_spec.\n  destruct H; [ intros; apply Hm; auto with set | ].\n  destruct H0;[ intros; apply Hm; auto with set | ].\n  split; simpl in *; intros.\n  unfold Z_support in H3.\n  case_eq (Zle_bool i i0); intros; rewrite H4 in H3.\n  apply Zle_bool_imp_le in H4.\n  apply In_seqZ_le in H3.\n  rewrite inj_Zabs_nat in H3.\n  rewrite Zabs_eq in H3;[ | omega].\n  apply le_trans with (size_Z i + size_Z i0).\n  unfold size_Z.\n  destruct (Z_lt_le_dec 0 v).\n  apply le_trans with ( size_nat (Zabs_nat i0)).\n  apply size_nat_monotonic.\n  apply Zabs_nat_le.\n  omega.\n  omega.\n  apply le_trans with ( size_nat (Zabs_nat i)).\n  apply size_nat_monotonic.  \n  assert (forall x, Zabs_nat x = Zabs_nat (- x)).\n  intros x; destruct x; auto.\n  rewrite (H5 v), (H5 i).\n  apply Zabs_nat_le.\n  omega.\n  omega.\n  omega.\n  destruct H3; subst.\n  unfold size_Z; simpl.\n  omega.\n  elim H3.\n  omega.\nQed.\n\n Lemma PPT_prod : forall t1 t2 (s1 : E.support t1) (s2 : E.support t2) F1 F2 G1 G2,\n   PPT_support s1 F1 G1 ->\n   PPT_support s2 F2 G2 ->\n   PPT_support (E.Dprod s1 s2) \n   (fun p => pplus 1 (pplus (F1 p) (F2 p))) \n   (fun p => pmult (G1 p) (G2 p)).\n Proof.\n  intros t1 t2 s1 s2 F1 F2 G1 G2 H1 H2 k m p Hm; simpl.\n  generalize (H1 k m p); clear H1.\n  generalize (H2 k m p); clear H2.\n  destruct (E.ceval_support s1 m).\n  destruct (E.ceval_support s2 m).\n  intros.\n  simpl in Hm.\n  rewrite pplus_spec, pmult_spec, pcst_spec, pplus_spec.\n  destruct H; [ intros; apply Hm; auto with set | ].\n  destruct H0;[ intros; apply Hm; auto with set | ].\n  split;[ destruct v as [v1 v2]; simpl in *; intro | ].\n  apply le_n_S.\n  apply in_prod_iff in H3.\n  apply plus_le_compat.\n  apply H0; tauto.\n  apply H; tauto.\n  apply mult_le_compat; trivial.\n Qed.\n\n\n (** PPT commands *)\n\n Section PPT.\n\n  Variable E : env.\n  Variable r : nat.\n \n  (** Bounded state *)\n  Definition bound k (p q:polynomial) (mn:Mem.t k * nat) : Prop :=\n   let (m,n) := mn in  \n    (forall t, tsize t <= r -> forall x:Var.var t, T.size (m x) <= peval p k) /\\ \n    n <= peval q k.\n\n  Implicit Arguments bound [k].\n\n  (** Polynomial sequence of distributions.\n    If the probability of reaching a certain final state [(m,c)] is\n    positive, then (asymptotically):\n     - the size of the values in [m] is bounded by a polynomial, and\n     - the final cost [c] is bounded by a polynomial\n  *)\n  Definition PPT (c:cmd)\n   (F:polynomial -> polynomial) \n   (G:polynomial -> polynomial) : Prop :=\n   forall k (d:Distr (Mem.t k * nat)) p q,\n    range (bound p q) d ->\n    range (bound (F p) (pplus q (G p))) (Mlet d ([[[c]]] E)).\n\n  Lemma PPT_unit : forall c F G, \n   PPT c F G ->\n   forall k (mn:Mem.t k * nat) p q,\n    bound p q mn ->\n    range (bound (F p) (pplus q (G p))) ([[[c]]] E mn).\n  Proof.\n   intros c F G0 Hc k mn p q Hmn.\n   generalize (Hc k (Munit mn) p q).  \n   unfold range; simpl; intros; auto.\n  Qed.\n\n  Lemma PPT_assign : forall t (x:Var.var t) (e:E.expr t) F G,\n   PPT_expr e F G ->\n   (forall t (x:Var.var t), Vset.mem x (fv_expr e) -> tsize t <= r) ->\n   PPT [x <- e] (fun p => pplus (F p) p) G.\n  Proof.\n   unfold PPT, PPT_expr; intros t x e F G0 He Hr k d p q Hd f Hf.\n   rewrite Mlet_simpl.\n   rewrite <- (Hd (fun mn => mu ([[[ [x <- e] ]]] E mn) f)); [trivial | ].\n   intros (m,n) [Hm1 Hm2]; rewrite cdeno_assign_elim; simpl.\n   generalize (He k m p); clear He.\n   case (E.ceval_expr e m); intros v n0 He.\n   destruct He as [W1 W2]; trivial.\n   intros t0 y Hy; apply Hm1.\n   apply Hr with y; trivial.\n   apply Hf; split.\n\n   (* mem *)\n   intros t0 Ht0 y; simpl.\n   generalize (Var.veqb_spec_dep x y).\n   case (Var.veqb x y); intro W.\n   inversion W; subst; simpl; clear H1 H2.\n   rewrite Mem.get_upd_same.\n   apply le_trans with (peval (F p) k).\n   trivial.\n   apply pplus_le_l.\n   rewrite Mem.get_upd_diff.\n   apply le_trans with (peval p k).\n   apply (Hm1 t0); auto.\n   apply pplus_le_r.\n   intro Heq; elim W; inversion Heq; trivial.\n\n   (* cost *)\n   apply le_trans with (peval q k + n0).\n   auto with arith.\n   rewrite pplus_spec; auto with arith.\n  Qed.\n\n  Lemma PPT_random : forall t (x:Var.var t) (s:E.support t) F G,\n   PPT_support s F G ->\n   (forall t (x:Var.var t), Vset.mem x (fv_distr s) -> tsize t <= r) ->\n   PPT [x <$- s] (fun p => pplus (F p) p) G.\n  Proof.\n   unfold PPT; intros t x s Fs Gs Hs Hr k d p q Hd f Hf.\n   rewrite Mlet_simpl.\n   rewrite <- (Hd (fun mn => mu ([[[ [x <$- s] ]]] E mn) f)); [trivial | ].\n   intros (m,n) [Hm1 Hm2]; rewrite cdeno_random_elim.\n   simpl fst; simpl snd.\n   generalize (Hs k m p); clear Hs.\n   case (E.ceval_support s m); intros l n0 H.\n   destruct H as [Hl Hn0].\n   intros t0 y Hy; apply Hm1.\n   apply Hr with y; trivial.\n\n   symmetry; refine (sum_dom_zero _ _ _ _ Hl _).\n   intros v Hv; symmetry.\n   apply Hf; split.\n   intros t0 Ht0 x0.\n   generalize (Var.veqb_spec_dep x x0).   \n   case (Var.veqb x x0); intro W.\n   inversion W; subst; simpl; clear H1 H2.\n   rewrite Mem.get_upd_same.\n   eapply le_trans; [ | apply pplus_le_l]; trivial.\n   rewrite Mem.get_upd_diff.\n   eapply le_trans; [ | apply pplus_le_r]; trivial.\n   apply Hm1; trivial.\n   intro Heq; elim W.\n   injection Heq; intros; subst.\n   rewrite (T.inj_pair2 H); trivial.\n\n   rewrite pplus_spec; apply plus_le_compat; trivial.\n  Qed. \n\n  Lemma PPT_nil : PPT nil (fun p => p) (fun _ => 0).\n  Proof.\n   unfold PPT; intros k d p q Hd f Hf.\n   rewrite Mlet_simpl.\n   apply Oeq_trans with (mu d f).\n   apply Hd.\n   intros (m,n) Hmn; apply Hf.\n   unfold bound; rewrite pplus_spec, pcst_spec; destruct Hmn; auto with arith.\n   apply mu_stable_eq.  \n   refine (ford_eq_intro _); intro.\n   rewrite cdeno_nil_elim; trivial.\n  Qed.\n\n  Lemma PPT_cons : forall i c Fi Fc Gi Gc,\n   PPT [i] Fi Gi ->\n   PPT c Fc Gc ->\n   PPT (i::c) (fun p => Fc (Fi p)) (fun p => pplus (Gi p) (Gc (Fi p))).\n  Proof.\n   unfold PPT; intros.\n   apply range_stable_eq with \n    (Mlet (Mlet d ([[[ [i] ]]] E)) ([[[c]]] E)).\n   intros; rewrite Mcomp.\n   apply Mlet_eq_compat; trivial.\n   apply ford_eq_intro; intro.\n   apply eq_distr_intro; intro.\n   rewrite cdeno_cons_elim; trivial.\n   unfold bound in H0 |- *; intros.\n   rewrite <- pplus_assoc.\n   apply (H0 k (Mlet d ([[[ [i] ]]] E))).\n   intro; unfold bound in H; apply H; trivial.\n  Qed.\n\n  Lemma PPT_cond : forall e c1 c2 Fe Ge Fc1 Fc2 Gc1 Gc2,\n   PPT_expr e Fe Ge ->\n   (forall t (x:Var.var t), Vset.mem x (fv_expr e) -> tsize t <= r) ->\n   PPT c1 Fc1 Gc1 ->\n   PPT c2 Fc2 Gc2 ->\n   PPT [If e then c1 else c2]\n    (fun p => pplus (Fe p) (pplus (Fc1 p) (Fc2 p)))\n    (fun p => pplus (Ge p) (pplus (Gc1 p) (Gc2 p))).\n  Proof.\n   unfold PPT, PPT_expr.\n   intros e c1 c2 Fe Ge Fc1 Fc2 Gc1 Gc2 He Hr Hc1 Hc2 k d p q Hd f Hf.\n   apply Ole_antisym; [trivial | ].\n\n   apply Ole_trans with (mu d\n    (fplus\n     (fun mn => mu ([[[c1]]] E (fst mn, snd mn + snd (E.ceval_expr e (fst mn)))) f)\n     (fun mn => mu ([[[c2]]] E (fst mn, snd mn + snd (E.ceval_expr e (fst mn)))) f))).\n   rewrite Mlet_simpl; refine (mu_le_compat _ _).\n   trivial.\n   apply ford_le_intro; intro m.\n   unfold fplus; rewrite cdeno_cond_elim.\n   case (E.ceval_expr e (fst m)); intro b; case b; trivial.  \n\n   rewrite (mu_le_plus d).\n   apply Ole_trans with (0 + 0)%U; [apply Uplus_le_compat | auto]. \n\n   apply Ole_trans with (\n    mu \n    (Mlet \n     (Mlet d (fun mn => Munit (fst mn, snd mn + snd (E.ceval_expr e (fst mn)))))\n     ([[[c1]]] E)) f); [trivial | ].\n   apply Oeq_le; symmetry.\n   refine (Hc1 k _ p (pplus q (Ge p)) _ _ _).\n   refine (range_Mlet _ _ _ (P:=bound p q)).\n   exact Hd.\n   intros (m,n) [H1 H2] g Hg; simpl.\n   apply Hg; split.\n   exact H1.\n   rewrite pplus_spec.\n   apply plus_le_compat.\n   exact H2.\n   generalize (He k m p).\n   case (E.ceval_expr e m); simpl; intros i n0 H.\n   destruct H; [ | trivial].\n   intros t x Hx; apply H1.\n   apply Hr with x; trivial.\n\n   intros (m,n) [H1 H2].\n   apply Hf; split.\n   intros; apply le_trans with (peval (Fc1 p) k); [auto |].\n   eapply le_trans; [ | apply pplus_le_r ]; apply pplus_le_l.\n   eapply le_trans; [apply H2 | ].\n   repeat rewrite pplus_spec.\n   rewrite plus_assoc; auto with arith.\n\n   apply Ole_trans with (\n    mu \n    (Mlet \n     (Mlet d (fun mn => Munit (fst mn, snd mn + snd (E.ceval_expr e (fst mn)))))\n     ([[[c2]]] E)) f); [trivial | ].\n   apply Oeq_le; symmetry.\n   refine (Hc2 k _ p (pplus q (Ge p)) _ _ _).\n   refine (range_Mlet _ _ _ (P:=bound p q)).\n   exact Hd.\n   intros (m,n) [H1 H2] g Hg; simpl.\n   apply Hg; split.\n   exact H1.\n   rewrite pplus_spec.\n   apply plus_le_compat.\n   exact H2.\n   generalize (He k m p).\n   case (E.ceval_expr e m); simpl; intros i n0 H. \n   destruct H; [ | trivial].\n   intros t x Hx; apply H1.\n   apply Hr with x; trivial.\n\n   intros (m,n) [H1 H2].\n   apply Hf; split.\n   intros; apply le_trans with (peval (Fc2 p) k); [auto |].\n   eapply le_trans; [ | apply pplus_le_r ]; apply pplus_le_r.\n   eapply le_trans; [apply H2 | ].\n   repeat rewrite pplus_spec.\n   rewrite plus_assoc; auto with arith.\n  Qed.\n\n  Lemma PPT_call : forall t (x:Var.var t) (f:Proc.proc t) (la:E.args (Proc.targs f)) \n   Fa Ga Fb Gb Fr Gr,\n   (forall k (m:Mem.t k) p,\n    (forall t (x:Var.var t), tsize t <= r -> T.size (m x) <= peval p k) ->\n    bound (Fa p) (Ga p) (cinit_mem E f la m)) ->\n\n   PPT (proc_body E f) Fb Gb ->\n\n   (forall t (x:Var.var t), Vset.mem x (fv_expr (proc_res E f)) -> tsize t <= r) ->\n   PPT_expr (proc_res E f) Fr Gr ->\n\n   PPT [x <c- f with la]\n    (fun p => pplus p (pplus (Fb (Fa p)) (Fr (Fb (Fa p)))))\n    (fun p => pplus (Ga p) (pplus (Gb (Fa p)) (Gr (Fb (Fa p))))).\n  Proof.\n   unfold PPT; intros t x f la Fa Ga Fb Gb Fr Gr Ha Hb Ht Hr k d p q Hd.\n\n   apply range_stable_eq with\n    (Mlet d \n     (fun mn => \n      Mlet (Mlet (Munit (cinit_mem E f la (fst mn)))\n       (fun mn' =>\n        ([[[ proc_body E f ]]] E (fst mn', snd mn + snd mn'))))\n      (fun mn'' => \n       Munit (fst (creturn_mem E x f (fst mn) (fst mn'')),\n        snd (creturn_mem E x f (fst mn) (fst mn'')) + snd mn'')))).\n   apply eq_distr_intro; intro g.\n   repeat rewrite Mlet_simpl.\n   apply mu_stable_eq.\n   refine (ford_eq_intro _); intros (m,n).\n   rewrite cdeno_call_elim; trivial.\n\n   refine (range_Mlet _ _ _ (P:=bound p q)).\n   trivial.\n   intros (m,n) Hmn.\n   refine (range_Mlet _ _ _ \n    (P:=bound (Fb (Fa p)) (pplus q (pplus (Ga p) (Gb (Fa p))))) ).\n\n   intros g Hg; simpl.\n   refine (Hb k \n    (Munit (fst (cinit_mem E f la m),\n            n + snd (cinit_mem E f la m))) (Fa p) (pplus q (Ga p))\n   _ _ _).\n   intros ga Hga; simpl; apply Hga.\n   destruct Hmn as [Hmn1 Hmn2].\n   generalize (Ha k m p); simpl.\n   destruct (cinit_mem E f la m) as (m',n'); intro H.\n   destruct H; intros.\n   apply (Hmn1 t0); auto.\n   split; simpl.\n   trivial.\n   rewrite pplus_spec; apply plus_le_compat; trivial.\n   intros (m',n') [H1 H2].\n   apply Hg.\n   split.\n   auto.\n   rewrite <- pplus_assoc; trivial.\n\n   intros (m',n') [H1 H2] gr Hgr.\n   simpl; apply Hgr.\n   rewrite creturn_mem_spec_l, creturn_mem_spec_r.\n   split.\n\n   intros t0 Ht0 x0.\n   generalize (Var.veqb_spec_dep x x0).   \n   case (Var.veqb x x0); intro W.\n   inversion W; subst; simpl; clear H3 H4.\n   rewrite return_mem_dest.\n   generalize (Hr k m' ((Fb (Fa p)))). \n   rewrite E.ceval_expr_spec.\n   case (E.ceval_expr (proc_res E f) m'); intros v n0 H.\n   destruct H; simpl fst.\n   intros t1 y Hy.\n   apply H1; apply Ht with y; trivial.\n   eapply le_trans; [ |apply pplus_le_r].\n   eapply le_trans; [ |apply pplus_le_r]; trivial.\n\n   destruct Hmn as [Hmn1 Hmn2].\n   assert (W1:Var.mkV x <> x0).\n   intro Heq; elim W.\n   injection Heq; intros; subst.\n   rewrite (T.inj_pair2 H); trivial.\n   case_eq (Var.vis_local x0); rewrite (Var.vis_local_local); intro Hl.\n   rewrite return_mem_local with (1:=W1) (2:=Hl). \n   eapply le_trans; [ | apply pplus_le_l]; auto.\n\n   assert (~Var.is_local x0) by trivialb.\n   rewrite <- Var.global_local in H.\n   rewrite return_mem_global with (1:=W1) (2:=H).\n   eapply le_trans; [ | apply pplus_le_r].\n   eapply le_trans; [ | apply pplus_le_l]; auto.\n\n   rewrite <- pplus_assoc, <- pplus_assoc, pplus_spec.\n   rewrite plus_comm.\n   apply plus_le_compat.\n   rewrite pplus_assoc; trivial.\n\n   generalize (Hr k m' ((Fb (Fa p)))).     \n   case (E.ceval_expr (proc_res E f) m'); intros v n0 H.\n   destruct H; [ | trivial].\n   intros t0 y Hy.\n   apply H1; apply Ht with y; trivial.\n  Qed.\n\n  Definition PPT_cmd c := exists F, exists G, PPT c F G.\n\n  Definition PPT_proc' (t:T.type) (f:Proc.proc t) : Prop :=\n   (forall t (x:Var.var t), Vset.mem x (fv_expr (proc_res E f)) -> tsize t <= r) /\\\n   PPT_cmd (proc_body E f) /\\\n   exists F, exists G, PPT_expr (proc_res E f) F G.\n    \n  Record PPT_info' :=\n   mkPPT_info {\n    ppt_info :> forall t (f:Proc.proc t), bool;\n    ppt_spec : forall t (f:Proc.proc t), ppt_info f -> PPT_proc' f\n   }.\n\n  Open Scope bool_scope.\n\n  Fixpoint expr_poly t (e:E.expr t) {struct e} : bool :=\n   match e with\n   | E.Ecte _ _ => true\n   | E.Evar _ _ => true\n   | E.Eop op la =>\n     match op, la with\n     | O.Olength _, dcons _ _ e dnil => expr_poly e\n     | O.OZlength _, dcons _ _ e dnil => expr_poly e \n     | O.Ohd _, dcons _ _ e dnil => expr_poly e\n     | O.Otl _, dcons _ _ e dnil => expr_poly e\n     | O.Ocons _, dcons _ _ e1 (dcons _ _ e2 dnil) => \n       expr_poly e1 && expr_poly e2\n     | O.Oappend _, dcons _ _ e1 (dcons _ _ e2 dnil) =>\n       expr_poly e1 && expr_poly e2\n     | O.Omem _, dcons _ _ e1 (dcons _ _ e2 dnil) =>\n       expr_poly e1 && expr_poly e2\n     | O.Oin_dom _ _, dcons _ _ e1 (dcons _ _ e2 dnil) => \n       expr_poly e1 && expr_poly e2\n     | O.Oin_range _ _, dcons _ _ e1 (dcons _ _ e2 dnil) => \n       expr_poly e1 && expr_poly e2 \n     | O.Oimg _ _, dcons _ _ e1 (dcons _ _ e2 dnil) =>\n       expr_poly e1 && expr_poly e2\n     | O.Onth _, dcons _ _ e1 (dcons _ _ e2 dnil) =>\n       expr_poly e1 && expr_poly e2\n     | O.Opair _ _, dcons _ _ e1 (dcons _ _ e2 dnil) => \n       expr_poly e1 && expr_poly e2\n     | O.Ofst _ _, dcons _ _ e dnil => expr_poly e     \n     | O.Osnd _ _, dcons _ _ e dnil => expr_poly e\n     | O.Oinl _ _, dcons _ _ e dnil => expr_poly e\n     | O.Oinr _ _, dcons _ _ e dnil => expr_poly e\n     | O.Oisl _ _, dcons _ _ e dnil => expr_poly e\n     | O.Oprojl _ _, dcons _ _ e dnil => expr_poly e\n     | O.Oprojr _ _, dcons _ _ e dnil => expr_poly e\n     | O.Osome _ , dcons _ _ e dnil => expr_poly e\n     | O.Oissome _, dcons _ _ e dnil => expr_poly e\n     | O.Oprojo _, dcons _ _ e dnil => expr_poly e\n     | O.Oeq_ _, dcons _ _ e1 (dcons _ _ e2 dnil) => \n       expr_poly e1 && expr_poly e2\n     | O.Oadd, dcons _ _ e1 (dcons _ _ e2 dnil) => \n       expr_poly e1 && expr_poly e2\n     | O.Osub, dcons _ _ e1 (dcons _ _ e2 dnil) =>\n       expr_poly e1 && expr_poly e2\n     | O.Omul, dcons _ _ e1 (dcons _ _ e2 dnil) => \n       expr_poly e1 && expr_poly e2\n     | O.Ole, dcons _ _ e1 (dcons _ _ e2 dnil) => \n       expr_poly e1 && expr_poly e2\n     | O.Olt, dcons _ _ e1 (dcons _ _ e2 dnil) => \n       expr_poly e1 && expr_poly e2     \n     | O.OZadd, dcons _ _ e1 (dcons _ _ e2 dnil) => \n       expr_poly e1 && expr_poly e2\n     | O.OZsub, dcons _ _ e1 (dcons _ _ e2 dnil) =>\n       expr_poly e1 && expr_poly e2\n     | O.OZmul, dcons _ _ e1 (dcons _ _ e2 dnil) => \n       expr_poly e1 && expr_poly e2\n     | O.OZle, dcons _ _ e1 (dcons _ _ e2 dnil) => \n       expr_poly e1 && expr_poly e2\n     | O.OZlt, dcons _ _ e1 (dcons _ _ e2 dnil) => \n       expr_poly e1 && expr_poly e2\n     | O.OZge, dcons _ _ e1 (dcons _ _ e2 dnil) => \n       expr_poly e1 && expr_poly e2\n     | O.OZgt, dcons _ _ e1 (dcons _ _ e2 dnil) => \n       expr_poly e1 && expr_poly e2\n     | O.OZopp, dcons _ _ e dnil => \n       expr_poly e\n     | O.OZdiv, dcons _ _ e1 (dcons _ _ e2 dnil) => \n       expr_poly e1 && expr_poly e2\n     | O.OZmod, dcons _ _ e1 (dcons _ _ e2 dnil) => \n       expr_poly e1 && expr_poly e2\n     | O.Onot, dcons _ _ e1 dnil => expr_poly e1\n     | O.Oand, dcons _ _ e1 (dcons _ _ e2 dnil) =>\n       expr_poly e1 && expr_poly e2\n     | O.Oor, dcons _ _ e1 (dcons _ _ e2 dnil) => \n       expr_poly e1 && expr_poly e2\n     | O.Oimp, dcons _ _ e1 (dcons _ _ e2 dnil) => \n       expr_poly e1 && expr_poly e2\n     | O.Oif _ , dcons _ _ e1 (dcons _ _ e2 (dcons _ _ e3 dnil)) => \n       expr_poly e1 && expr_poly e2 && expr_poly e3\n     | O.Ouser o, _ => uop_poly o && dforallb expr_poly la\n     | _, _ => false\n     end\n   | E.Eexists t x e1 e2 => expr_poly e1 && expr_poly e2\n   | E.Eforall t x e1 e2 => expr_poly e1 && expr_poly e2\n   | E.Efind t x e1 e2 => expr_poly e1 && expr_poly e2\n   end.\n\n  Lemma expr_poly_spec : forall t (e:E.expr t),\n   expr_poly e ->\n   exists F, exists G, PPT_expr e F G.\n  Proof.\n   induction e using E.expr_ind2 with\n    (Pl := fun l la => forall t (e:E.expr t), \n      DIn t e la -> expr_poly e -> exists F, exists G, PPT_expr e F G).\n\n   (* Ecst *)\n   intro He.\n   destruct c; simpl.\n\n    (* Bool *)\n    exists (fun _ => pcst 1).\n    exists (fun _ => pcst 1).\n    apply PPT_bool.\n\n    (* Nat *)\n    exists (fun _ => pcst (size_nat n)).\n    exists (fun _ => pcst (size_nat n)).\n    apply PPT_nat.\n\n    (* Z *)\n    exists (fun _ => pcst (size_Z z)).\n    exists (fun _ => pcst (size_Z z)).\n    apply PPT_Z.\n\n    (* Enil *)\n    exists (fun _ => pcst 1).\n    exists (fun _ => pcst 1).   \n    apply PPT_enil.\n \n    (* Enone *)\n    exists (fun _ => pcst 1).\n    exists (fun _ => pcst 1).   \n    unfold PPT_expr; intros; simpl.\n    rewrite pcst_spec; auto.\n\n   (* Evar *)\n   intro He.\n   exists (fun p => p).\n   exists (fun _ => pcst 1).   \n   apply PPT_var.\n\n   (* Eop *)\n   intro Hla.\n   rename args into la.\n   destruct op; try discriminate.\n \n    (* O.Olength *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    destruct (IHe _ x) as [Fe [Ge He] ].\n    left; trivial.\n    trivial.\n    exists (fun p : polynomial => pplus 1 (Fe p)).\n    exists (fun p : polynomial => pplus (Fe p) (Ge p)).\n    apply PPT_length; trivial.\n\n    (* O.OZlength *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    destruct (IHe _ x) as [Fe [Ge He] ].\n    left; trivial.\n    trivial.\n    exists (fun p : polynomial => pplus 1 (Fe p)).\n    exists (fun p : polynomial => pplus (Fe p) (Ge p)).\n    apply PPT_Zlength; trivial.\n\n    (* Ohd *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    destruct (IHe _ x) as [Fe [Ge He] ].\n    left; trivial.\n    trivial.\n    exists (fun p => pplus (T.default_poly t) (Fe p)).\n    exists (fun p => pplus (pcst 1) (Ge p)).\n    apply PPT_head; trivial.\n\n    (* Otl *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    destruct (IHe _ x) as [Fe [Ge He] ].\n    left; trivial.\n    trivial.\n    exists (fun p => Fe p).\n    exists (fun p => pplus (pcst 1) (Ge p)).\n    apply PPT_tail; trivial.\n\n    (* Ocons *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    exists (fun p : polynomial => pplus 1 (pplus (Fe1 p) (Fe2 p))).\n    exists (fun p : polynomial => pplus 1 (pplus (Ge1 p) (Ge2 p))).\n    apply PPT_Ocons; trivial.\n\n    (* Oappend *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    exists (fun p => pplus (Fe1 p) (Fe2 p)).\n    exists (fun p => pplus (Fe1 p) (pplus (Ge1 p) (Ge2 p))).\n    apply PPT_Oappend; trivial.\n\n    (* Omem *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    exists (fun _ : polynomial => 1).\n    exists (fun p : polynomial =>\n     pplus (pplus (pmult (Fe2 p) (pplus (Fe1 p) (Fe2 p))) 1)\n     (pplus (Ge2 p) (Ge1 p))).\n    apply PPT_mem; trivial.\n\n    (* Oin_dom *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    exists (fun p => pcst 1).\n    exists (fun p => pplus (pplus (pmult (Fe2 p) (pplus (Fe1 p) (Fe2 p))) 1)\n            (pplus (Ge2 p) (Ge1 p))).\n    apply PPT_in_dom; trivial.\n\n    (* Oin_range *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    exists (fun p => pcst 1).\n    exists (fun p => pplus (pplus (pmult (Fe2 p) (pplus (Fe1 p) (Fe2 p))) 1)\n            (pplus (Ge2 p) (Ge1 p))).\n    apply PPT_in_range; trivial.\n\n    (* Oimg *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    exists (fun p => pplus (Fe2 p) (T.default_poly t0)).\n    exists (fun p => pplus (pplus (pmult (Fe2 p) (pplus (Fe1 p) (Fe2 p))) 1)\n            (pplus (Ge2 p) (Ge1 p))).\n    apply PPT_img; trivial.\n\n    (* Onth *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    exists (fun p => pplus (Fe2 p) (T.default_poly t)).\n    exists (fun p => pplus (Fe2 p) (pplus (Ge2 p) (Ge1 p))).\n    apply PPT_nth with Fe1; trivial.\n\n    (* Opair *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    exists (fun p => pplus 1 (pplus (Fe1 p) (Fe2 p))).\n    exists (fun p => pplus (pcst 1) (pplus (Ge1 p) (Ge2 p))).\n    apply PPT_pair; trivial.\n\n    (* Ofst *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    destruct (IHe _ x) as [Fe [Ge He] ].\n    left; trivial.\n    trivial.\n    exists (fun p => Fe p).\n    exists (fun p => pplus (pcst 1) (Ge p)).\n    apply PPT_fst; trivial.\n\n    (* Osnd *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    destruct (IHe _ x) as [Fe [Ge He] ].\n    left; trivial.\n    trivial.\n    exists (fun p => Fe p).\n    exists (fun p => pplus (pcst 1) (Ge p)).\n    apply PPT_snd; trivial.\n\n    (* Oinl *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    destruct (IHe _ x) as [Fe [Ge He] ].\n    left; trivial.\n    trivial.\n    exists (fun p => pplus 1 (Fe p)).\n    exists (fun p => pplus 1 (Ge p)).\n    intros k m p H2.\n    generalize (He k m p H2); clear He H2.\n    simpl.\n    rewrite E.ceval_expr_spec.\n    case (E.ceval_expr x m); simpl.\n    intros i n [? ?]; split.\n    rewrite pplus_spec, pcst_spec; apply le_n_S; trivial. \n    rewrite pplus_spec, pcst_spec; apply le_n_S; rewrite plus_0_r; trivial.\n  \n    (* Oinr *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    destruct (IHe _ x) as [Fe [Ge He] ].\n    left; trivial.\n    trivial.\n    exists (fun p => pplus 1 (Fe p)).\n    exists (fun p => pplus 1 (Ge p)).\n    intros k m p H2.\n    generalize (He k m p H2); clear He H2.\n    simpl.\n    rewrite E.ceval_expr_spec.\n    case (E.ceval_expr x m); simpl.\n    intros i n [? ?]; split.\n    rewrite pplus_spec, pcst_spec; apply le_n_S; trivial. \n    rewrite pplus_spec, pcst_spec; apply le_n_S; rewrite plus_0_r; trivial.\n\n    (* Oisl *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    destruct (IHe _ x) as [Fe [Ge He] ].\n    left; trivial.\n    trivial.\n    exists (fun p => 1).\n    exists (fun p => pplus 1 (Ge p)).\n    intros k m p H2.\n    generalize (He k m p H2); clear He H2.\n    simpl.  \n    case (E.ceval_expr x m); simpl.\n    intros [i1 | i2] n [? ?]; split.\n    rewrite pcst_spec; trivial.\n    rewrite pplus_spec, pcst_spec; apply le_n_S; rewrite plus_0_r; trivial.\n    rewrite pcst_spec; trivial.\n    rewrite pplus_spec, pcst_spec; apply le_n_S; rewrite plus_0_r; trivial.\n \n    (* Oprojl *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    destruct (IHe _ x) as [Fe [Ge He] ].\n    left; trivial.\n    trivial.\n    exists (fun p => pplus (T.default_poly t) (Fe p)).\n    exists (fun p => pplus 1 (Ge p)).\n    intros k m p H2.\n    generalize (He k m p H2); clear He H2.\n    simpl.  \n    rewrite E.ceval_expr_spec.\n    case (E.ceval_expr x m); simpl.\n    intros [i1 | i2] n [? ?]; split.\n    rewrite pplus_spec; apply le_trans with (Fe p k); auto with arith.   \n    rewrite pplus_spec, pcst_spec; apply le_n_S; rewrite plus_0_r; trivial.\n    rewrite pplus_spec; apply le_trans with (1:=T.default_poly_spec k t); auto with arith.\n    rewrite pplus_spec, pcst_spec; apply le_n_S; rewrite plus_0_r; trivial.\n\n    (* Oprojr *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    destruct (IHe _ x) as [Fe [Ge He] ].\n    left; trivial.\n    trivial.\n    exists (fun p => pplus (T.default_poly t0) (Fe p)).\n    exists (fun p => pplus 1 (Ge p)).\n    intros k m p H2.\n    generalize (He k m p H2); clear He H2.\n    simpl.  \n    rewrite E.ceval_expr_spec.\n    case (E.ceval_expr x m); simpl.\n    intros [i1 | i2] n [? ?]; split.\n    rewrite pplus_spec; apply le_trans with (1:=T.default_poly_spec k t0); auto with arith.\n    rewrite pplus_spec, pcst_spec; apply le_n_S; rewrite plus_0_r; trivial.  \n    rewrite pplus_spec; apply le_trans with (Fe p k); auto with arith.   \n    rewrite pplus_spec, pcst_spec; apply le_n_S; rewrite plus_0_r; trivial.\n\n    (* Osome *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    destruct (IHe _ x) as [Fe [Ge He] ].\n    left; trivial.\n    trivial.\n    exists (fun p => pplus 1 (Fe p)).\n    exists (fun p => pplus 1 (Ge p)).\n    intros k m p H2.\n    generalize (He k m p H2); clear He H2.\n    simpl.  \n    rewrite E.ceval_expr_spec.\n    case (E.ceval_expr x m); simpl.\n    intros i n [? ?]; split.\n    rewrite pplus_spec, pcst_spec; apply le_n_S; trivial.\n    rewrite pplus_spec, pcst_spec; apply le_n_S; rewrite plus_0_r; trivial.  \n\n    (* Oissome *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    destruct (IHe _ x) as [Fe [Ge He] ].\n    left; trivial.\n    trivial.\n    exists (fun p => 1).\n    exists (fun p => pplus 1 (Ge p)).\n    intros k m p H2.\n    generalize (He k m p H2); clear He H2.\n    simpl.  \n    case (E.ceval_expr x m); simpl.\n    intros i n [? ?]; split.\n    rewrite pcst_spec; trivial.\n    rewrite pplus_spec, pcst_spec; apply le_n_S; rewrite plus_0_r; trivial.\n\n    (* Oprojo *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    destruct (IHe _ x) as [Fe [Ge He] ].\n    left; trivial.\n    trivial.\n    exists (fun p => pplus (T.default_poly t) (Fe p)).\n    exists (fun p => pplus 1 (Ge p)).\n    intros k m p H2.\n    generalize (He k m p H2); clear He H2.\n    simpl.  \n    rewrite E.ceval_expr_spec.\n    case (E.ceval_expr x m); simpl.\n    intros [i | ] n [? ?]; split.\n    rewrite pplus_spec; apply le_trans with (Fe p k); auto with arith.   \n    rewrite pplus_spec, pcst_spec; apply le_n_S; rewrite plus_0_r; trivial.\n    rewrite pplus_spec; apply le_trans with (1:=T.default_poly_spec k t); auto with arith.\n    rewrite pplus_spec, pcst_spec; apply le_n_S; rewrite plus_0_r; trivial.\n      \n    (* Oeq_ *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    exists (fun p => pcst 1).\n    exists (fun p => pplus (pplus (Fe1 p) (Fe2 p)) (pplus (Ge1 p) (Ge2 p))).\n    apply PPT_eq; eauto.\n  \n    (* Oadd *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    exists (fun p => pplus (Fe1 p) (Fe2 p)).\n    exists (fun p => pplus (Fe1 p) (pplus (Ge1 p) (Ge2 p))).\n    apply PPT_add; trivial.\n\n    (* Osub *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    exists (fun p => Fe1 p).\n    exists (fun p => pplus (Fe2 p) (pplus (Ge1 p) (Ge2 p))).\n    apply PPT_sub; trivial.\n\n    (* Omul *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    exists (fun p => pplus (Fe1 p) (Fe2 p)).\n    exists (fun p => pplus (pmult (Fe1 p) (Fe2 p)) (pplus (Ge1 p) (Ge2 p))).\n    apply PPT_mul; trivial.\n\n    (* Ole *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    exists (fun _ => pcst 1).\n    exists (fun p => pplus (Fe1 p) (pplus (Ge1 p) (Ge2 p))).\n    apply PPT_le with Fe2; trivial.\n  \n    (* Olt *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    exists (fun _ => pcst 1).\n    exists (fun p => pplus (Fe2 p) (pplus (Ge1 p) (Ge2 p))).\n    apply PPT_lt with Fe1; trivial.\n\n    (* OZadd *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    exists (fun p => pplus (Fe1 p) (Fe2 p)).\n    exists (fun p => pplus (Fe1 p) (pplus (Ge1 p) (Ge2 p))).\n    apply PPT_Zadd; trivial.\n\n    (* OZsub *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    exists (fun p => pplus (Fe1 p) (Fe2 p)).\n    exists (fun p => pplus (Fe2 p) (pplus (Ge1 p) (Ge2 p))).\n    apply PPT_Zsub; trivial.\n\n    (* OZmul *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    exists (fun p => pplus (Fe1 p) (Fe2 p)).\n    exists (fun p => pplus (pmult (Fe1 p) (Fe2 p)) (pplus (Ge1 p) (Ge2 p))).\n    apply PPT_Zmul; trivial.\n\n\n    (* OZle *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    exists (fun _ => pcst 1).\n    exists (fun p => pplus (Fe1 p) (pplus (Ge1 p) (Ge2 p))).\n    apply PPT_Zle with Fe2; trivial.\n  \n    (* OZlt *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    exists (fun _ => pcst 1).\n    exists (fun p => pplus (Fe2 p) (pplus (Ge1 p) (Ge2 p))).\n    apply PPT_Zlt with Fe1; trivial.\n\n    (* OZge *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    exists (fun _ => pcst 1).\n    exists (fun p => pplus (Fe2 p) (pplus (Ge1 p) (Ge2 p))).\n    eapply PPT_Zge with Fe1; trivial.\n  \n    (* OZgt *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    exists (fun _ => pcst 1).\n    exists (fun p => pplus (Fe2 p) (pplus (Ge1 p) (Ge2 p))).\n    apply PPT_Zgt with Fe1; trivial.\n\n    (* OZopp *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    simpl in Hla; trivial.\n    exists (fun p => Fe1 p).\n    exists (fun p => pplus (Fe1 p) (Ge1 p)).\n    apply PPT_Zopp; trivial.\n\n    (* OZdiv *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    exists (fun p => pplus (Fe1 p) 1).\n    exists (fun p => pplus (Fe1 p) (pplus (Ge1 p) (Ge2 p))).\n    apply PPT_Zdiv with Fe2; trivial.\n\n    (* OZmod *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    exists (fun p => Fe2 p).\n    exists (fun p => pplus (Fe2 p) (pplus (Ge1 p) (Ge2 p))).\n    apply PPT_Zmod with Fe1; trivial.\n\n    (* Onot *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    simpl in Hla; trivial.\n    exists (fun _ => pcst 1).\n    exists (fun p => pplus 1 (Ge1 p)).\n    apply PPT_not with Fe1; trivial.\n\n    (* Oand *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    exists (fun _ => pcst 1).\n    exists (fun p => pplus 1 (pplus (Ge1 p) (Ge2 p))).\n    apply PPT_and with Fe1 Fe2; trivial.\n\n    (* Oor *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    exists (fun _ => pcst 1).\n    exists (fun p => pplus 1 (pplus (Ge1 p) (Ge2 p))).\n    apply PPT_or with Fe1 Fe2; trivial.\n\n    (* Oimp *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    exists (fun _ => pcst 1).\n    exists (fun p => pplus 1 (pplus (Ge1 p) (Ge2 p))).\n    apply PPT_imp with Fe1 Fe2; trivial.\n\n    (* Oif *)\n    T.dlist_inversion la.\n    rewrite Heq in IHe, Hla |- *.\n    simpl in Hla; unfold is_true in Hla.\n    apply andb_prop in Hla; destruct Hla.\n    apply andb_prop in H; destruct H.\n    destruct (IHe _ x) as [Fe1 [Ge1 He1] ].\n    left; trivial.\n    trivial.\n    destruct (IHe _ x0) as [Fe2 [Ge2 He2] ].\n    right; left; trivial.\n    trivial.\n    destruct (IHe _ x1) as [Fe3 [Ge3 He3] ].\n    right; right; left; trivial.\n    trivial.\n    exists (fun p => pplus (Fe2 p) (Fe3 p)).\n    exists (fun p => pplus 1 (pplus (Ge1 p) (pplus (Ge2 p) (Ge3 p)))).\n    apply PPT_if with Fe1; trivial.\n\n    (* Ouser *)\n    simpl in Hla; apply andb_prop in Hla; destruct Hla.\n    apply uop_poly_spec; trivial.\n    intros; apply IHe.\n    trivial.\n    rewrite dforallb_forall in H0.\n    apply H0; trivial. \n    intros t1 t2; case_eq (T.eq_dec t1 t2); intros.\n    left; trivial.\n    apply T.eq_dec_r in H2; right; trivial.\n\n    (* Eexists *)\n    simpl; intros.\n    rewrite is_true_andb in H; destruct H.\n    exists (fun _ => pcst 1).\n    destruct (IHe1 H) as (F1, (G1, H1)).\n    destruct (IHe2 H0) as (F2, (G2, H2)).\n    unfold PPT_expr in H1, H2.\n    exists (fun p => pplus (pmult (F2 p) (G1 (pplus p (F2 p)))) (G2 p)).\n    red.\n    intros k m p Hfv; simpl.\n    case_eq (E.ceval_expr e2 m).\n    intros l2 n2; case_eq (cexistsb (fun v0 : T.interp k t => E.ceval_expr e1 (m {!v <-- v0!})) l2 n2).\n    intros b n1 Heq1 Heq2; split.\n    rewrite pcst_spec; trivial.\n    match type of Heq1 with cexistsb ?F l2 n2 = _ => set (f := F) in Heq1 end.\n    assert (W:= H2 k m p); rewrite Heq2 in W; destruct W.\n    intros; apply Hfv; unfold fv_expr; simpl; fold (fv_expr e2); auto with set.   \n    assert (forall a : T.interp k t,\n     In a l2 -> snd (f a) <= peval (G1 (pplus p (F2 p))) k).\n       intros; unfold f.  \n       assert (W:= H1 k (m {!v <-- a!}) (pplus p (F2 p))).\n       case_eq (E.ceval_expr e1 (m {!v <-- a!})); intros.\n       rewrite H6 in W; destruct W;[ | trivial].\n       intros; rewrite pplus_spec.\n       destruct (Var.eq_dec v x).\n       inversion e; simpl; rewrite Mem.get_upd_same.\n       apply le_trans with (peval (F2 p) k);[ | apply le_plus_r].\n       apply le_trans with (2:= H3).\n       apply List_size_le; trivial.\n       rewrite Mem.get_upd_diff;[ | trivial].\n       assert (Vset.mem x (fv_expr (E.Eexists v e1 e2))).\n         unfold fv_expr; simpl; fold (fv_expr e2); auto with set.\n       apply le_trans with (1:= Hfv _ _ H8); apply le_plus_l.\n    assert (W:= @cexistsb_count _ f (peval (G1 (pplus p (F2 p))) k) l2 H5 n2).\n    rewrite Heq1 in W; simpl in W.\n    apply le_trans with (1:= W).\n    rewrite pplus_spec; apply plus_le_compat;[ | trivial].  \n    rewrite pmult_spec; apply mult_le_compat_r.\n    apply le_trans with (2:= H3).\n    exact (@List_size_length k t l2).\n\n    (* Eforall *)\n    simpl; intros.\n    rewrite is_true_andb in H; destruct H.\n    exists (fun _ => pcst 1).\n    destruct (IHe1 H) as (F1, (G1, H1)).\n    destruct (IHe2 H0) as (F2, (G2, H2)).\n    unfold PPT_expr in H1, H2.\n    exists (fun p => pplus (pmult (F2 p) (G1 (pplus p (F2 p)))) (G2 p)).\n    red.\n    intros k m p Hfv; simpl.\n    case_eq (E.ceval_expr e2 m).\n    intros l2 n2; case_eq (cforallb (fun v0 : T.interp k t => E.ceval_expr e1 (m {!v <-- v0!})) l2 n2).\n    intros b n1 Heq1 Heq2; split.\n    rewrite pcst_spec; trivial.\n    match type of Heq1 with cforallb ?F l2 n2 = _ => set (f := F) in Heq1 end.\n    assert (W:= H2 k m p); rewrite Heq2 in W; destruct W.\n    intros; apply Hfv; unfold fv_expr; simpl; fold (fv_expr e2); auto with set.   \n    assert (forall a : T.interp k t,\n     In a l2 -> snd (f a) <= peval (G1 (pplus p (F2 p))) k).\n       intros; unfold f.  \n       assert (W:= H1 k (m {!v <-- a!}) (pplus p (F2 p))).\n       case_eq (E.ceval_expr e1 (m {!v <-- a!})); intros.\n       rewrite H6 in W; destruct W;[ | trivial].\n       intros; rewrite pplus_spec.\n       destruct (Var.eq_dec v x).\n       inversion e; simpl; rewrite Mem.get_upd_same.\n       apply le_trans with (peval (F2 p) k);[ | apply le_plus_r].\n       apply le_trans with (2:= H3).\n       apply List_size_le; trivial.\n       rewrite Mem.get_upd_diff;[ | trivial].\n       assert (Vset.mem x (fv_expr (E.Eexists v e1 e2))).\n         unfold fv_expr; simpl; fold (fv_expr e2); auto with set.\n       apply le_trans with (1:= Hfv _ _ H8); apply le_plus_l.\n    assert (W:= @cforallb_count _ f (peval (G1 (pplus p (F2 p))) k) l2 H5 n2).\n    rewrite Heq1 in W; simpl in W.\n    apply le_trans with (1:= W).\n    rewrite pplus_spec; apply plus_le_compat;[ | trivial].  \n    rewrite pmult_spec; apply mult_le_compat_r.\n    apply le_trans with (2:= H3).\n    exact (@List_size_length k t l2).\n\n    (* Efind *)\n    simpl; intros.\n    rewrite is_true_andb in H; destruct H.\n    destruct (IHe1 H) as (F1, (G1, H1)).\n    destruct (IHe2 H0) as (F2, (G2, H2)).\n    unfold PPT_expr in H1, H2.\n    exists (fun p => pplus (F2 p) (T.default_poly t)).\n    exists (fun p => pplus (pmult (F2 p) (G1 (pplus p (F2 p)))) (G2 p)).\n    red.\n    intros k m p Hfv; simpl.\n    case_eq (E.ceval_expr e2 m).\n    intros l2 n2; case_eq (cfind_default (fun v0 : T.interp k t => E.ceval_expr e1 (m {!v <-- v0!}))\n      l2 n2 (T.default k t)).\n    intros r1 n1 Heq1 Heq2.\n    assert (HH:= H2 k m p).\n    rewrite Heq2 in HH; destruct HH as (HH1, HH2).\n    intros; apply Hfv; unfold fv_expr; simpl; fold (fv_expr e2); auto with set.  \n    split.\n    assert (X : forall x : T.interp k t,\n     (fun v0 : T.interp k t => E.eval_expr e1 (m {!v <-- v0!})) x =\n     fst ((fun v0 : T.interp k t => E.ceval_expr e1 (m {!v <-- v0!})) x)).\n     intros; apply E.ceval_expr_spec.\n    assert (W:= @find_cfind_default _\n             (fun v0 : T.interp k t => E.eval_expr e1 (m {!v <-- v0!}))\n             (fun v0 : T.interp k t => E.ceval_expr e1 (m {!v <-- v0!}))\n             (T.default k t) X l2 n2). \n    rewrite Heq1 in W; simpl in W; rewrite <- W.\n    unfold find_default; rewrite pplus_spec.\n    case_eq (find (fun v0 : T.interp k t => E.eval_expr e1 (m {!v <-- v0!})) l2); intros.\n    destruct (find_In _ _ H3).\n    apply le_trans with (peval (F2 p) k);[ | apply le_plus_l].\n    apply le_trans with (2:= HH1).\n    apply List_size_le; trivial.\n    apply le_trans with (peval (T.default_poly t) k).\n    apply T.default_poly_spec.\n    apply le_plus_r.\n    match type of Heq1 with cfind_default ?F _ _ _ = _ => set (f := F) in Heq1 end.\n    assert (forall a : T.interp k t,\n     In a l2 -> snd (f a) <= peval (G1 (pplus p (F2 p))) k).\n       intros; unfold f.  \n       assert (W:= H1 k (m {!v <-- a!}) (pplus p (F2 p))).\n       case_eq (E.ceval_expr e1 (m {!v <-- a!})); intros.\n       rewrite H4 in W; destruct W;[ | trivial].\n       intros; rewrite pplus_spec.\n       destruct (Var.eq_dec v x).\n       inversion e; simpl; rewrite Mem.get_upd_same.\n       apply le_trans with (peval (F2 p) k);[ | apply le_plus_r].\n       apply le_trans with (2:= HH1).\n       apply List_size_le; trivial.\n       rewrite Mem.get_upd_diff;[ | trivial].\n       assert (Vset.mem x (fv_expr (E.Efind v e1 e2))).\n         unfold fv_expr; simpl; fold (fv_expr e2); auto with set.\n       apply le_trans with (1:= Hfv _ _ H6); apply le_plus_l.\n    assert (W:= @cfind_default_count _ f _ l2 (T.default k t) H3 n2).\n    rewrite Heq1 in W; apply le_trans with (1:= W).\n    rewrite pplus_spec; apply plus_le_compat; trivial.\n    rewrite pmult_spec; apply mult_le_compat; trivial.\n    apply le_trans with (2:= HH1).\n    apply (List_size_length l2).\n  \n   (* Nil *)\n   intros t e Hin; elim Hin.\n\n   (* Cons *)\n   intros t0 e0 Hin He0.\n   simpl in Hin; case Hin; intro H.\n   inversion H; clear H2 H3; subst.\n   rewrite (T.eq_dep_eq H) in He0 |- *; apply IHe; trivial.\n   auto.\n  Qed.\n\n  Fixpoint support_poly t (s:E.support t) : bool :=\n   match s with \n   | E.Dbool => true\n   | E.Dnat e => expr_poly e\n   | E.DZ e1 e2 => expr_poly e1 && expr_poly e2\n   | E.Duser _ us => usupport_poly us\n   | E.Dprod _ _ s1 s2 => support_poly s1 && support_poly s2\n   end.\n\n  Lemma support_poly_spec : forall t (s:E.support t),\n   support_poly s ->\n   exists F, exists G, PPT_support s F G.\n  Proof.\n   intros t s.\n   induction s.\n\n   (* Dbool *)\n   intros _.\n   exists (fun p => pplus p 1). \n   exists (fun _ => pcst 1).\n   apply PPT_Dbool.\n\n   (* Dnat *)\n   intros Hs; simpl in Hs.\n   destruct (expr_poly_spec _ Hs) as [Fe [Ge He] ].\n   exists Fe.\n   exists Ge.\n   apply PPT_Dnat; trivial.\n\n   (* DZ *)\n   intros Hs; simpl in Hs.   \n   apply andb_true_iff in Hs.\n   destruct Hs.\n   destruct (expr_poly_spec _ H) as [F1 [G1 H1] ].\n   destruct (expr_poly_spec _ H0) as [F2 [G2 H2] ].\n   exists (fun p : polynomial => pplus 1 (pplus (F1 p) (F2 p))).\n   exists (fun p : polynomial => pplus (G1 p) (G2 p)).\n   apply PPT_DZ; trivial.\n\n   (* Duser *)\n   intro; apply usupport_poly_spec; trivial.\n \n   (* Dprod *)\n   intro H; simpl in H; apply andb_prop in H.\n   destruct IHs1 as [F1 [ G1 H1 ] ]; [ tauto | ].\n   destruct IHs2 as [F2 [ G2 H2 ] ]; [ tauto | ].\n   exists (fun p : polynomial => pplus 1 (pplus (F1 p) (F2 p))).\n   exists (fun p : polynomial => pmult (G1 p) (G2 p)).\n   apply PPT_prod; trivial.\n  Qed.\n\n\n  Section CMD_POLY.\n   \n   Variable proc_poly : PPT_info'.\n\n   Definition args_poly l (le:dlist E.expr l) := dforallb (expr_poly) le.\n\n   Lemma args_poly_aux : forall l (la:dlist E.expr l),\n    args_poly la  ->\n    (forall t (e:E.expr t), DIn t e la -> forall t0 (x:Var.var t0), Vset.mem x (fv_expr e) -> tsize t0 <= r) ->\n    exists F,\n    forall t (e:E.expr t),\n     DIn t e la ->\n      forall k (m:Mem.t k) p,\n       (forall t (x:Var.var t), tsize t <= r -> T.size (m x) <= peval p k) ->\n       T.size (E.eval_expr e m) <= peval (F p) k.\n   Proof.\n    intros l la.\n    induction l as [e1 [la' Heq] | ]; intros Hla Hr.\n    \n    rewrite (T.l_eq_dep_eq (dlist_nil la)).\n    exists (fun p => p); intros t1 e He; elim He.\n\n    destruct (dlist_cons la) as [e1 [la' Heq] ].\n    rewrite (T.l_eq_dep_eq Heq) in Hla, Hr |- *; clear la Heq.\n    simpl in Hla.\n    case_eq (expr_poly e1).\n    intros W; rewrite W in Hla.\n    destruct (expr_poly_spec _ W) as [Fe [Ge He] ].\n    destruct (IHl la' Hla) as [F Ha]; clear IHl.\n    intros t e0 He0 t0 x Hx.\n    refine (Hr _ _ _ _ _ Hx); simpl; auto.\n    \n    exists (fun p => pplus (Fe p) (F p)).\n    intros t0 e0 He0 k m p Hm.\n    simpl in He0; case He0; intro Heq.\n    inversion Heq; intros; subst.\n    rewrite (T.inj_pair2 H2) in *; clear H1 H2 Heq.\n    generalize (He k m p).\n    rewrite E.ceval_expr_spec; case (E.ceval_expr e1 m).    \n    intros i n H.\n    destruct H as [Hv Hn].\n    intros t x Hx; apply Hm.\n    refine (Hr _ _ _ _ _ Hx); simpl; auto.\n\n    eapply le_trans; [ | apply pplus_le_l]; trivial.\n\n    eapply le_trans; [ | apply pplus_le_r].\n    apply (Ha t0 e0 Heq); trivial.\n\n    intro H; rewrite H in Hla; discriminate.\n   Qed.\n\n   Fixpoint tsize_default_poly r : polynomial :=\n    pplus (utsize_default_poly r)\n    match r with\n     | O => 1\n     | S r' => pplus 1 (pplus (tsize_default_poly r') (tsize_default_poly r'))\n    end.\n  \n   Lemma tsize_default_poly_le : forall r n, \n    1 <= peval (tsize_default_poly r) n.\n   Proof.\n    induction r0; simpl; intros.\n    rewrite pplus_spec, pcst_spec; omega.\n    rewrite pplus_spec, pplus_spec, pcst_spec; omega.\n   Qed.\n\n   Lemma tsize_default_poly_spec : forall t,\n    tsize t <= r -> \n    forall k, T.size (T.default k t) <= peval (tsize_default_poly r) k.\n   Proof.\n   intro t; generalize t r; clear t.\n    induction t; simpl; intros.\n\n    destruct r0; simpl.\n    eapply le_trans; [ | apply pplus_le_l].\n    apply utsize_default_poly_spec; trivial.\n    eapply le_trans; [ | apply pplus_le_l].\n    apply utsize_default_poly_spec; trivial.\n\n    apply tsize_default_poly_le.   \n    apply tsize_default_poly_le.\n    apply tsize_default_poly_le.\n    apply tsize_default_poly_le.\n    apply tsize_default_poly_le.\n\n    destruct r0; [omega | ].\n    simpl.\n    repeat rewrite pplus_spec.\n    eapply le_trans; [ | apply le_plus_r].\n    rewrite pcst_spec; apply le_n_S; apply plus_le_compat.\n    apply IHt1; omega.\n    apply IHt2; omega.\n\n    destruct r0; [omega | ].\n    simpl.\n    repeat rewrite pplus_spec.\n    eapply le_trans; [ | apply le_plus_r].\n    rewrite pcst_spec; apply le_n_S.\n    eapply le_trans; [ | apply le_plus_r].\n    apply IHt1; omega.\n\n    apply tsize_default_poly_le.\n   Qed.\n       \n   Lemma args_poly_spec : forall t (f:Proc.proc t) (la:E.args (Proc.targs f)),\n    args_poly la ->\n    (forall t (e:E.expr t), DIn t e la -> forall t0 (x:Var.var t0), Vset.mem x (fv_expr e) -> tsize t0 <= r) ->\n    exists F, exists G,\n     forall k (m:Mem.t k) p,\n      (forall t (x:Var.var t), tsize t <= r -> T.size (m x) <= peval p k) ->      \n      bound (pplus (tsize_default_poly r) (pplus p (F p))) (G p) (cinit_mem E f la m).\n   Proof.   \n    intros t f la.\n    destruct f; simpl in la.\n    set (f:=Proc.mkP pname targs tres). \n    induction targs.\n    \n    intros _ Hr.\n    rewrite (T.l_eq_dep_eq (dlist_nil la)).\n    exists (fun _ => 0).\n    exists (fun _ => 0).\n    intros k m p Hm.\n    unfold bound; rewrite (surjective_pairing (cinit_mem E f (dnil _) m)).\n    rewrite cinit_mem_spec_l, cinit_mem_spec_r; split; [ | apply le_O_n].\n    simpl.\n    intros t Ht x.\n    generalize (lookup_init_mem E f (dnil _) m x).\n    generalize (get_arg_Some2 x (proc_params E f) (dnil _)).\n    simpl (Proc.targs f); case (get_arg x (lt1:=nil) (proc_params E f) (dnil E.expr)).\n    intros e V W; rewrite W; clear W.\n    elim (V e); trivial.\n\n    intros _ W; rewrite W.\n    destruct x; intros.\n    rewrite <- Mem.global_spec; trivial.\n    eapply le_trans; [ | apply pplus_le_r]; \n    eapply le_trans; [ | apply pplus_le_l].\n    apply (Hm t); auto.\n\n    rewrite Mem.global_local; trivial.\n    eapply le_trans; [ | apply pplus_le_l].\n    apply tsize_default_poly_spec; trivial.\n \n    destruct (dlist_cons la) as [e [la' Hla'] ]; intros Hla Hr.\n    destruct (args_poly_aux la Hla Hr) as [F Haux]; generalize Hla; clear Hla.\n    rewrite (T.l_eq_dep_eq Hla') in Haux, Hr |- *; clear Hla'; simpl.\n    case_eq (expr_poly e); intro H1; try (intro; discriminate).\n    case_eq (args_poly la'); intro H2; try (intro; discriminate); intros _.\n    destruct (expr_poly_spec _ H1) as [Fe [Ge He] ].\n    destruct (IHtargs la' H2) as [Fa [Ga Ha] ].\n    intros t e0 He0 t0 x Hx.\n    apply Hr with (2:=Hx); simpl; auto.\n \n    exists F.\n    exists (fun p => pplus (Ge p) (Ga p)).\n    intros k m p Hm.\n    unfold bound; rewrite (surjective_pairing (cinit_mem E f (dcons _ e la') m)).\n    rewrite cinit_mem_spec_l, cinit_mem_spec_r; split.\n    \n    intros t Hx x.\n    generalize (lookup_init_mem E f (dcons _ e la') m x).\n    generalize (get_arg_Some2 x (proc_params E f) (dcons _ e la')).\n    simpl (Proc.targs f).\n    case (get_arg x (lt1:=a::targs) (proc_params E f) (dcons _ e la')).\n    intros e0 V W; rewrite W; clear W.\n    eapply le_trans; [ | apply pplus_le_r].\n    eapply le_trans; [ | apply pplus_le_r]; auto.\n  \n    intros _ W; rewrite W.\n    destruct x; intros.\n    rewrite <- Mem.global_spec; trivial.\n    eapply le_trans; [ | apply pplus_le_r].\n    eapply le_trans; [ | apply pplus_le_l]; auto.\n\n    rewrite Mem.global_local; trivial.\n    eapply le_trans; [ | apply pplus_le_l].\n    apply tsize_default_poly_spec; trivial.\n\n    simpl.\n    rewrite pplus_spec, plus_comm.\n    apply plus_le_compat.\n    generalize (He k m p); case (E.ceval_expr e m).\n    intros ? ? H; destruct H.\n    intros t x Hx; apply Hm.\n    apply Hr with (2:=Hx); simpl; auto.\n    trivial.\n    generalize (Ha k m p).\n    unfold bound; rewrite (surjective_pairing (cinit_mem E (Proc.mkP pname targs tres) la' m)).   \n    rewrite cinit_mem_spec_r; tauto.\n   Qed.\n \n   Open Scope bool_scope.\n\n   Fixpoint instr_poly (i:I.instr) {struct i} : bool :=\n    match i with\n    | I.Instr (I.Assign _ x e) => \n      expr_poly e && \n      Vset.forallb \n       (fun x => match x with Var.mkV t _ => Compare_dec.leb (tsize t) r end) \n       (fv_expr e)\n    | I.Instr (I.Random _ x s) => \n      support_poly s && \n      Vset.forallb \n       (fun x => match x with Var.mkV t _ => Compare_dec.leb (tsize t) r end) \n       (fv_distr s)\n    | I.Cond e c1 c2 => \n      expr_poly e && \n      Vset.forallb \n       (fun x => match x with Var.mkV t _ => Compare_dec.leb (tsize t) r end) \n       (fv_expr e) &&\n      forallb instr_poly c1 && \n      forallb instr_poly c2\n    | I.Call t x f la => \n      args_poly la && \n      dforallb (fun t (e:E.expr t) => \n       Vset.forallb\n        (fun x => match x with Var.mkV t _ => Compare_dec.leb (tsize t) r end) \n        (fv_expr e)) la &&\n       proc_poly _ f\n    | _ => false\n    end.\n\n   Definition cmd_poly := forallb instr_poly.\n\n   Lemma cmd_poly_spec : forall c, \n    cmd_poly c = true ->\n    exists F, exists G, PPT c F G.\n   Proof.\n    induction c using I.cmd_ind with\n     (Pi:=fun i => instr_poly i = true -> exists Fi, exists Gi, PPT [i] Fi Gi).\n\n     (* baseInstr *)\n     destruct i.\n\n      (* Assign *)\n      intros Hi; simpl in Hi.\n      apply andb_prop in Hi; destruct Hi as [Hi Hr].\n      destruct (expr_poly_spec _ Hi) as [ Fe [Ge He] ].\n      exists (fun p => pplus (Fe p) p); exists Ge.\n      apply PPT_assign; trivial.\n      intros t0 x Hx.\n      apply leb_complete.\n      apply fold_is_true.\n      refine (Vset.forallb_correct _ Hr Hx).\n      intros y z H.\n      unfold Vset.E.eq in H; rewrite H; trivial.\n\n      (* Random *)\n      intro Hi; simpl in Hi.\n      apply andb_prop in Hi; destruct Hi as [Hi Hr].\n      destruct (support_poly_spec _ Hi) as [ Fs [Gs Hs] ].\n      exists (fun p => pplus (Fs p) p); exists Gs.\n      apply PPT_random; trivial.\n      intros t0 x Hx.\n      apply leb_complete.\n      apply fold_is_true.\n      refine (Vset.forallb_correct _ Hr Hx).\n      intros y z H.\n      unfold Vset.E.eq in H; rewrite H; trivial.\n\n      (* Cond *)\n      intro Hi; simpl in Hi.\n      apply andb_prop in Hi; destruct Hi as [Hi H2].\n      apply andb_prop in Hi; destruct Hi as [Hi H1].\n      apply andb_prop in Hi; destruct Hi as [H0 Hr].\n      destruct (expr_poly_spec _ H0) as [ Fe [Ge He] ].\n      destruct (IHc1 H1) as [ Fc1 [Gc1 Hc1] ].\n      destruct (IHc2 H2) as [ Fc2 [Gc2 Hc2] ].\n      exists (fun p => pplus (Fe p) (pplus (Fc1 p) (Fc2 p))).\n      exists (fun p => pplus (Ge p) (pplus (Gc1 p) (Gc2 p))).\n      apply PPT_cond; trivial.\n      intros t0 x Hx.\n      apply leb_complete.\n      apply fold_is_true.\n      refine (Vset.forallb_correct _ Hr Hx).\n      intros y z H.\n      unfold Vset.E.eq in H; rewrite H; trivial.\n\n      (* While *)\n      intros; discriminate.\n\n      (* Call *)\n      intro Hi; simpl in Hi.\n      apply andb_prop in Hi; destruct Hi as [Hi H0].\n      apply andb_prop in Hi; destruct Hi as [H1 H2].\n\n      destruct (ppt_spec _ _ H0) as [H3 [ [Fb [Gb Hb] ]  [Fr [Gr Hr] ] ] ]. \n      destruct (args_poly_spec _ _ H1) as [ Fa [Ga Ha] ].\n      intros t0 e He0 t1 y Hy.\n      apply leb_complete.\n      apply fold_is_true.\n      assert (Hdec:forall t1 t2:T.type, sumbool (t1 = t2) (t1 <> t2)).\n      intros t2 t3; generalize (T.eqb_spec t2 t3); case (T.eqb t2 t3); auto.\n      rewrite (dforallb_forall Hdec\n       (fun t (e:E.expr t) =>\n          Vset.forallb\n            (fun x =>\n             match x with\n             | Var.mkV t _ => Compare_dec.leb (tsize t) r\n             end) (fv_expr e)) ) in H2.\n      refine (Vset.forallb_correct _ (H2 t0 e He0) Hy).\n      intros w z H.\n      unfold Vset.E.eq in H; rewrite H; trivial.\n      exists (fun p => pplus p (pplus (Fb (pplus (tsize_default_poly r) (pplus p (Fa p)))) \n        (Fr (Fb (pplus (tsize_default_poly r) (pplus p (Fa p))))))).\n      exists (fun p => pplus (Ga p) (pplus (Gb (pplus (tsize_default_poly r) (pplus p (Fa p)))) \n        (Gr (Fb (pplus (tsize_default_poly r) (pplus p (Fa p))))))).\n      apply PPT_call; trivial.\n\n     intro.\n     exists (fun p => p).\n     exists (fun _ => 0).\n     apply PPT_nil; trivial.\n\n     intro H; simpl in H.\n     apply andb_prop in H; destruct H as [H0 H1].\n     destruct (IHc H0) as [ Fi [Gi Hi] ].\n     destruct (IHc0 H1) as [ Fc [Gc Hc] ].\n     exists (fun p => Fc (Fi p)).\n     exists (fun p => pplus (Gi p) (Gc (Fi p))).\n     apply PPT_cons; trivial.\n    Qed.\n\n  End CMD_POLY.\n\n  Definition res_poly (t:T.type) (p:Proc.proc t) : bool :=\n   Vset.forallb \n    (fun x => match x with Var.mkV t _ => Compare_dec.leb (tsize t) r end)\n    (fv_expr (proc_res E p)).\n\n   Lemma res_poly_spec : forall t (p:Proc.proc t), \n    res_poly p ->\n    forall t (x:Var.var t),\n     Vset.mem x (fv_expr (proc_res E p)) -> tsize t <= r.\n   Proof.\n    intros ? ? H ? ? H0.\n    apply leb_complete; apply fold_is_true.\n    refine (Vset.forallb_correct _ H H0).\n    intros ? ? Heq; unfold Vset.E.eq in Heq; rewrite Heq; trivial.\n   Qed.\n\n End PPT.\n\n Definition tsize_limit := 10.\n\n Definition PPT_proc E := PPT_proc' E tsize_limit. \n\n Definition PPT_info E := PPT_info' E tsize_limit.\n\n Definition PPT_empty_info E : PPT_info E := \n  mkPPT_info (fun t (f:Proc.proc t) => false) \n   (fun _ f => false_true_elim (PPT_proc E f)).\n\n Definition PPT_add_info E (pi:PPT_info E) t (p:Proc.proc t) : PPT_info E.\n  intros E pi t p.\n  case_eq (res_poly E tsize_limit p); intro Hres; [ | exact pi].\n  case_eq (cmd_poly pi (proc_body E p)); intro Hp; [ | exact pi].\n  case_eq (expr_poly (proc_res E p)); intro He; [ | exact pi].\n  refine (\n   mkPPT_info \n   (fun t (f:Proc.proc t) => if Proc.eqb f p then true else pi t f)\n   _).\n  intros t0 f.\n  generalize (Proc.eqb_spec_dep f p).\n  case (Proc.eqb f p); intros H H0.\n  inversion H; subst.\n  rewrite (T.inj_pair2 H4).\n  split; [ | split].\n  refine (res_poly_spec Hres).\n  refine (cmd_poly_spec pi (proc_body E p) Hp).\n  refine (expr_poly_spec _ He).\n  apply (ppt_spec pi); trivial. \n Defined.\n\n Definition PPT_add_adv_info : forall E t (A:Proc.proc t),\n  PPT_info E -> \n  PPT_proc E A ->\n  PPT_info E.  \n  intros E' t A pi HA.\n  refine (mkPPT_info (fun _ f => if Proc.eqb f A then true else pi _ f) _).\n  intros t0 f.\n  generalize (Proc.eqb_spec_dep f A).\n  case (Proc.eqb f A); intros H H0.\n  inversion H; subst.\n  rewrite (T.inj_pair2 H4).\n  apply HA.\n  apply ppt_spec with pi; trivial.\n Defined.\n\n Ltac PPT_tac pi :=\n  match goal with\n   |- PPT_cmd _ _ ?c =>\n   let Heq := fresh \"Heq\" in\n   let res := fresh \"res\" in\n    compute_assertion Heq res (cmd_poly pi c);\n    refine (cmd_poly_spec pi c Heq)\n  end.\n\n Ltac PPT_proc_tac pi :=\n  match goal with\n   |- PPT_proc ?E ?p =>\n   let Heq := fresh \"Heq\" in\n   let res := fresh \"res\" in\n    split; \n     [ refine (res_poly_spec _); trivial |\n       split; \n       [ compute_assertion Heq res (cmd_poly pi (proc_body E p)); \n         refine (cmd_poly_spec pi (proc_body E p) Heq) |\n         refine (expr_poly_spec (proc_res E p) _); trivial ] ]\n  end.\n\nEnd Make_PPT.\n", "meta": {"author": "EasyCrypt", "repo": "certicrypt", "sha": "7b3cd2fe4a317aec38dfff9eec902b265c575587", "save_path": "github-repos/coq/EasyCrypt-certicrypt", "path": "github-repos/coq/EasyCrypt-certicrypt/certicrypt-7b3cd2fe4a317aec38dfff9eec902b265c575587/Semantics/PPT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778403, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.27003647234706263}}
{"text": "Require Import SpecCert.x86.Architecture.ProcessorUnit.ProcessorUnit_rec.\nRequire Import SpecCert.Address.\nRequire Import SpecCert.Interval.\n\nDefinition interrupts_are_disabled\n           (p :ProcessorUnit) :=\n  cli p = true.\n\nDefinition interrupts_are_enabled\n           (p :ProcessorUnit) :=\n  cli p = false.\n\nDefinition will_process_interrupt\n           (p :ProcessorUnit)\n           (i :Interrupt) :=\n  i = SMI \\/ interrupts_are_enabled p.\n\nDefinition is_in_smm\n           (p :ProcessorUnit) :=\n  (in_smm p) = true.\n\nDefinition is_inside_smrr\n           (p  :ProcessorUnit)\n           (pa :PhysicalAddress) :=\n  is_inside_interval (address_offset pa) (interval (smrr p)).\n\nDefinition smrr_hit\n           (p  :ProcessorUnit)\n           (pa :PhysicalAddress) :=\n  is_in_smm p /\\ is_inside_smrr p pa.", "meta": {"author": "lthms", "repo": "speccert", "sha": "8c1edfb173548af0e9ca3c4e24d43726401fdb71", "save_path": "github-repos/coq/lthms-speccert", "path": "github-repos/coq/lthms-speccert/speccert-8c1edfb173548af0e9ca3c4e24d43726401fdb71/src/x86/Architecture/ProcessorUnit/ProcessorUnit_prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2700364723470626}}
{"text": "Require Import AllInRel Util Map Envs Exp IL Annotation Coherence DecSolve.\nRequire Import Liveness.Liveness Restrict Allocation Indexwise.\n\nSet Implicit Arguments.\nUnset Printing Records.\n\n(** ** Coherence is decidable *)\n\nDefinition srd_dec DL s a\n  : Computable (srd DL s a).\nProof.\n  hnf. revert DL a.\n  sinduction s; simpl.\n  - edestruct a as [|lv a'| |]; [dec_right| | dec_right| dec_right].\n    edestruct (X x0); [ eauto | dec_solve | dec_right].\n  - edestruct a as [?|?|lv als alt|]; [dec_right| dec_right| | dec_right].\n    edestruct (X x1), (X x2); eauto; [ | dec_right| |dec_right ]; dec_solve.\n  - destruct a; [ | dec_right | dec_right | dec_right].\n    destruct (get_dec DL (counted l)) as [[[G'|] ?]|?]; [| dec_right | dec_right].\n    dec_solve.\n  - destruct a; [ | dec_right | dec_right | dec_right]. dec_solve.\n  - destruct a as [?|?|lv als alt| ]; [dec_right| dec_right| dec_right|].\n    ensure (length F = length sa).\n    edestruct (X x) with (DL:=Some ⊝ (getAnn ⊝ sa) \\\\ (fst ⊝ F) ++ DL); eauto; [ |dec_right].\n    edestruct (indexwise_R_dec'\n                 (R:=fun x y =>\n                       srd (restr (getAnn y \\ of_list (fst x))\n                                  ⊝ (Some ⊝ (getAnn ⊝ sa) \\\\ (fst ⊝ F) ++ DL))\n                           (snd x) y) (LA:=F) (LB:=sa)).\n    intros. eapply X; eauto.\n    dec_solve. dec_right.\n    Grab Existential Variables. eauto. eauto. eauto. eauto.\nDefined.\n\n(** ** local injectivity is decidable *)\n\n\nLocal Hint Extern 1 =>\nmatch goal with\n  [ H : annotation _ _ |- annotation _ _ ] => inv H; eassumption\nend.\n\nDefinition locally_inj_dec (ϱ:env var) (s:stmt) (lv:ann (set var)) (an:annotation s lv)\n  : {locally_inj ϱ s lv} + {~ locally_inj ϱ s lv}.\nProof.\n  revert ϱ lv an.\n  sind s; intros; destruct s; destruct lv; try solve [ exfalso; inv an ].\n  - ensure (injective_on a ϱ).\n    edestruct (IH s); eauto. dec_solve. dec_right.\n  - ensure (injective_on a ϱ).\n    edestruct (IH s1); eauto; [|dec_right].\n    edestruct (IH s2); eauto; [|dec_right]. dec_solve.\n  - ensure (injective_on a ϱ); dec_solve.\n  - ensure (injective_on a ϱ); dec_solve.\n  - ensure (injective_on a ϱ).\n    ensure (length F = length sa).\n    edestruct (IH s); eauto; [| dec_solve].\n    edestruct (indexwise_R_dec' (R:=fun x y => locally_inj ϱ (snd x) y) (LA:=F) (LB:=sa));\n      try dec_solve.\n    intros. eapply IH; eauto. inv an; eauto.\nDefined.\n\nInstance locally_inj_dec_inst (ϱ:env var) (s:stmt) (lv:ann (set var))\n         `{Computable (annotation s lv)}\n  : Computable (locally_inj ϱ s lv).\nProof.\n  destruct H as [].\n  hnf; eauto using locally_inj_dec.\n  right; intro; eauto using locally_inj_annotation.\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/Coherence/AllocationValidator.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2700364723470626}}
{"text": "Require Import Coq.Logic.ProofIrrelevance.\nRequire Import CertiGraph.lib.Ensembles_ext.\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.graph_gen.\nRequire Import CertiGraph.graph.graph_relation.\nRequire Import CertiGraph.graph.subgraph2.\n\nModule SIMPLE_MARK_GRAPH.\nSection SIMPLE_MARK_GRAPH.\n\n  Context {V : Type}.\n  Context {E : Type}.\n  Context {EV: EqDec V eq}.\n  Context {EE: EqDec E eq}.\n\n  Section SINGLE_GRAPH_LEM.\n\n  Context (g: PreGraph V E).\n\n(*\n  Definition reachable_sub_markedgraph (G: Gph) x: Gph :=\n    Build_MarkedGraph _ _ (reachable_subgraph G x) (marked G).\n\n  Definition unmarked (g: Gph): NodePred g := negateP (marked g).\n\n  Lemma unmarked_spec (g: Gph): forall x, (unmarked g) x <-> ~ (marked g) x.\n  Proof. apply negateP_spec. Qed.\n*)\n  Definition mark1 (m1 : NodePred V) (n : V) (m2 : NodePred V) : Prop :=\n    vvalid g n /\\ m2 n /\\ forall n', n <> n' -> (m1 n' <-> m2 n').\n\n  Definition mark (m1 : NodePred V) (root : V) (m2 : NodePred V) : Prop :=\n    (forall n,  g |= root ~o~> n satisfying (negateP m1) -> m2 n) /\\\n    (forall n, ~g |= root ~o~> n satisfying (negateP m1) -> (m1 n <-> m2 n)).\n\n  Inductive mark_list: NodePred V -> list V -> NodePred V -> Prop :=\n  | mark_list_nil: forall m m0, (m ~=~ m0)%NodePred -> mark_list m nil m0\n  | mark_list_cons: forall m m0 m1 v vs, mark m v m0 -> mark_list m0 vs m1 -> mark_list m (v :: vs) m1\n  .\n\n  Lemma mark1_marked: forall m1 root m2,\n                        mark1 m1 root m2 ->\n                        forall n, m1 n -> m2 n.\n  Proof.\n    intros. destruct H as [? [? ?]].\n    destruct_eq_dec root n.\n    subst. auto. specialize (H2 n H3). tauto.\n  Qed.\n\n  (* The first subtle lemma *)\n  Lemma mark1_unmarked : forall m1 root m2 n,\n    mark1 m1 root m2 ->\n    g |= root ~o~> n satisfying (negateP m1) ->\n    n = root \\/ exists child, edge g root child /\\ g |= child ~o~> n satisfying (negateP m2).\n  Proof.\n    intros. rewrite reachable_acyclic in H0. destruct H0 as [p [? ?]]. destruct p as [v p].\n    assert (v = root) by (destruct H1 as [[? _] _]; simpl in H1; auto). subst v. destruct p.\n    + left. destruct H1 as [[? ?] _]. simpl in H2. auto.\n    + right. exists (dst g e). change (root, e :: p) with (path_glue (root, e :: nil) (dst g e, p)) in H1.\n      apply (reachable_by_path_split_glue g) with (n := dst g e) in H1. 2: red; simpl; auto.\n      destruct H1. split.\n      - destruct H1 as [_ [[? [? [? ?]]] _]]. hnf. subst root. rewrite step_spec. do 2 (split; auto). exists e; auto.\n      - exists (dst g e, p). destruct H2 as [? [? ?]]. split; [|split]; auto.\n        rewrite path_prop_equiv in H4 |-* ; auto. rewrite epath_to_vpath_cons_eq in H0. 2: destruct H1 as [_ [[? _] _]]; auto.\n        apply NoDup_cons_2 in H0. rewrite in_path_eq_epath_to_vpath in H0; auto. intros. specialize (H4 _ H5).\n        destruct H as [? [? ?]]. rewrite negateP_spec in H4 |- *. rewrite <- H7; auto.\n        intro. apply H0. subst; auto.\n  Qed.\n\n  (* Not the best name in the world... *)\n  Lemma mark1_reverse_unmark: forall m1 root m2,\n    mark1 m1 root m2 ->\n    forall n1 n2,\n      g |= n1 ~o~> n2 satisfying (negateP m2) ->\n      g |= n1 ~o~> n2 satisfying (negateP m1).\n  Proof.\n    intros. destruct H0 as [p [? ?]]. exists p. split; trivial.\n    destruct H1. destruct H as [? [? ?]].\n    split. auto.\n    rewrite path_prop_equiv in H2 |- *; auto.\n    intros. specialize (H2 _ H5). specialize (H4 n).\n    spec H4. intro. subst n. hnf in H3. hnf in H2. apply H2; auto.\n    rewrite negateP_spec in H2 |- *; tauto.\n  Qed.\n\n  Lemma mark_exists: forall m x,\n    vvalid g x ->\n    ReachDecidable g x (negateP m) ->\n    {m': NodePred V | mark m x m'}.\n  Proof.\n    intros. destruct ((node_pred_dec (negateP m)) x).\n    + exists (existT (fun P => forall x, {P x} + {~ P x})\n                     (fun y => g |= x ~o~> y satisfying (negateP m) \\/ (m) y)\n                     (fun y => sumbool_dec_or (X y) (node_pred_dec (m) y))).\n      split.\n      - intros; subst; hnf. auto.\n      - split; intros; subst; simpl in *; tauto.\n    + exists (m). split; intros.\n      - destruct H0 as [path ?].\n        apply (reachable_by_path_In g _ _ _ _ x) in H0.\n        hnf in H0. tauto. destruct H0 as [[? _] _]. destruct path; simpl in H0; inversion H0. hnf; left; auto.\n      - reflexivity.\n  Qed.\n\n  Lemma mark1_exists: forall m x, vvalid g x -> {m': NodePred V | mark1 m x m'}.\n  Proof.\n    intros. destruct ((node_pred_dec m) x).\n    + exists m. split; auto. split; [exact a |]. intros; reflexivity.\n    + assert (forall y, {y = x \\/ m y} + {~ (y = x \\/ m y)}).\n      1: {\n        intros.\n        apply sumbool_dec_or.\n        + apply equiv_dec.\n        + apply node_pred_dec.\n      }\n      exists (existT _ (fun y => y = x \\/ m y) X). split.\n      * auto.\n      * split; [simpl; auto |].\n        intros; simpl.\n        assert (n' <> x) by congruence. tauto.\n  Qed.\n\n  (* The second subtle lemma.  Maybe needs a better name? *)\n  Lemma mark_unmarked: forall m1 root m2 n1 n2,\n                         vvalid g root ->\n                         ReachDecidable g root (negateP m1)->\n                         mark m1 root m2 ->\n                         g |= n1 ~o~> n2 satisfying (negateP m1) ->\n                         (g |= n1 ~o~> n2 satisfying (negateP m2)) \\/ (m2 n2).\n  Proof.\n    intros until n2. intros HH ENUMC; intros. destruct H0 as [p ?].\n    (* This was a very handy LEM. *)\n    destruct (exists_list_dec _ (epath_to_vpath g p) (fun n => g |= root ~o~> n satisfying (negateP m1))) as [?H | ?H].\n    1: apply ENUMC.\n    + right. destruct H as [? _]. apply H.\n      destruct H1 as [n [? ?]]. apply reachable_by_trans with n; trivial.\n      rewrite in_path_eq_epath_to_vpath in H1. 2: destruct H0 as [_ [? _]]; auto.\n      destruct (reachable_by_path_split_in g _ _ _ _ _ H0 H1) as [p1 [p2 [? [? ?]]]].\n      exists p2. trivial.\n    + left. exists p. destruct H0. split; trivial. clear H0.\n      destruct H2. destruct H as [_ ?]. split; auto.\n      rewrite path_prop_equiv in H2 |-* ; auto.\n      intros x ?. specialize (H2 x H3). specialize (H x).\n      spec H. intro. apply H1. exists x. rewrite in_path_eq_epath_to_vpath; auto.\n      rewrite negateP_spec in H2 |- *; tauto.\n  Qed.\n\n  Lemma mark_unmarked_strong: forall m1 root m2 n1 n2,\n                                vvalid g root ->\n                                ReachDecidable g root (negateP m1) ->\n                                mark m1 root m2 ->\n                                g |= n1 ~o~> n2 satisfying (negateP m1) ->\n                                Decidable (g |= n1 ~o~> n2 satisfying (negateP m2)).\n  Proof.\n    intros.\n    pose proof mark_unmarked _ _ _ _ _ H X H0 H1.\n    destruct (node_pred_dec (m2) n2); [| left; tauto].\n    right.\n    intro.\n    rewrite reachable_by_eq_subgraph_reachable in H3.\n    apply reachable_foot_valid in H3.\n    simpl in H3.\n    destruct H3.\n    rewrite negateP_spec in H4; tauto.\n  Qed.\n\n  Lemma mark_invalid: forall m1 root m2,\n                         ~ vvalid g root ->\n                         mark m1 root m2 ->\n                         (m1 ~=~ m2)%NodePred.\n  Proof.\n    intros.\n    destruct H0 as [? ?].\n    intro; intros.\n    apply H1.\n    intro.\n    apply reachable_by_head_valid in H2.\n    tauto.\n  Qed.\n\n  Lemma mark_invalid_refls: forall m root,\n                         ~ vvalid g root ->\n                         mark m root m.\n  Proof.\n    intros.\n    split.\n    + intros.\n      apply reachable_by_head_valid in H0.\n      tauto.\n    + intros.\n      reflexivity.\n  Qed.\n\n  Lemma mark_marked_root: forall (m1: NodePred V) root m2,\n                         m1 root ->\n                         mark m1 root m2 ->\n                         (m1 ~=~ m2)%NodePred.\n  Proof.\n    intros.\n    destruct H0 as [? ?].\n    intro; intros.\n    apply H1.\n    intro.\n    rewrite reachable_by_eq_subgraph_reachable in H2.\n    apply reachable_head_valid in H2.\n    simpl in H2.\n    unfold predicate_vvalid in H2.\n    rewrite negateP_spec in H2.\n    tauto.\n  Qed.\n\n  Lemma mark_marked_root_refls: forall (m: NodePred V) root,\n                         m root ->\n                         mark m root m.\n  Proof.\n    intros.\n    split.\n    + intros.\n      apply reachable_by_head_prop in H0.\n      rewrite negateP_spec in H0.\n      tauto.\n    + intros.\n      reflexivity.\n  Qed.\n\n  Lemma mark_markeds: forall m1 root m2,\n                       mark m1 root m2 ->\n                       ReachDecidable g root (negateP m1) ->\n                       forall n, m1 n -> m2 n.\n  Proof.\n    intros. destruct H as [? ?].\n    destruct (X n). auto. specialize (H1 n n0). tauto.\n  Qed.\n\n  Lemma mark_marked_strong:\n    forall m1 root m2 n,\n      mark m1 root m2 ->\n      ReachDecidable g root (negateP m1) ->\n      g |= root ~o~> n satisfying (negateP m1) \\/ m1 n ->\n      m2 n.\n  Proof.\n    intros.\n    destruct H0; [| eapply mark_markeds; eauto].\n    destruct H.\n    eapply H; eauto.\n  Qed.\n\n  (* Maybe a better name? *)\n  Lemma mark_reverse_unmarked: forall m1 root m2,\n                                 mark m1 root m2 ->\n                                 forall n1 n2,\n                                 ReachDecidable g root (negateP m1) ->\n                                 g |= n1 ~o~> n2 satisfying (negateP m2) ->\n                                 g |= n1 ~o~> n2 satisfying (negateP m1).\n  Proof.\n    intros.\n    eapply reachable_by_weaken; [| eauto].\n    change (@app_node_pred _ (negateP m2)) with (Complement _ (projT1 m2)).\n    change (@app_node_pred _ (negateP m1)) with (Complement _ (projT1 m1)).\n    apply Complement_Included_rev.\n    intro; apply mark_markeds with (root := root); auto.\n  Qed.\n\n  Lemma mark_reverse_unmarked_strong:\n    forall m1 root m2,\n      mark m1 root m2 ->\n      forall n1 n2,\n      ReachDecidable g root (negateP m1) ->\n      g |= n1 ~o~> n2 satisfying (negateP m2) ->\n      (predicate_partialgraph g (Complement _ (reachable_by g root (negateP m1)))) |= n1 ~o~> n2 satisfying (negateP m1).\n  Proof.\n    intros.\n    rewrite reachable_by_eq_partialgraph_reachable.\n    rewrite partial_partialgraph.\n    rewrite <- reachable_by_eq_partialgraph_reachable.\n    eapply reachable_by_weaken; [| eauto].\n    change (@app_node_pred _ (negateP m2)) with (Complement _ (projT1 m2)).\n    change (@app_node_pred _ (negateP m1)) with (Complement _ (projT1 m1)).\n    rewrite Intersection_Complement.\n    apply Complement_Included_rev.\n    intro x; unfold Ensembles.In.\n    rewrite Union_spec.\n    apply mark_marked_strong; auto.\n  Qed.\n\n  Lemma mark_preserved_reach_decidable: forall m1 root m2 x,\n    vvalid g root ->\n    ReachDecidable g x (negateP m1) ->\n    ReachDecidable g root (negateP m1) ->\n    mark m1 root m2 ->\n    ReachDecidable g x (negateP m2).\n  Proof.\n    intros. intro. destruct (X y).\n    + apply (mark_unmarked_strong m1 root); auto.\n    + right. intro. apply n. apply (mark_reverse_unmarked _ root m2); auto.\n  Qed.\n\n  Lemma ind_RV_DEC: forall (P: NodePred V -> list V -> NodePred V -> Prop),\n    (forall m m', (m ~=~ m')%NodePred -> P m nil m') ->\n    (forall m v m' l m'',\n      P m' l m'' ->\n      forall\n        (R_DEC: forall x, In x (v :: l) -> ReachDecidable g x (negateP m))\n        (V_DEC: forall x, In x (v :: l) -> Decidable (vvalid g x)),\n      mark m v m' ->\n      mark_list m' l m'' ->\n      P m (v :: l) m'') ->\n    (forall m l m',\n      (forall x, In x l -> ReachDecidable g x (negateP m)) ->\n      (forall x, In x l -> Decidable (vvalid g x)) ->\n      mark_list m l m' ->\n      P m l m').\n  Proof.\n    intros P H_nil IH m l m' R_DEC V_DEC ?.\n    induction H.\n    + apply H_nil; auto.\n    + apply (IH m v m0 vs m1); auto.\n      apply IHmark_list.\n      - destruct (V_DEC v (or_introl eq_refl)) as [?H | ?H].\n        * intros.\n          apply (mark_preserved_reach_decidable m v); auto.\n          1: apply R_DEC; right; auto.\n          1: apply R_DEC; left; auto.\n        * pose proof mark_invalid m v m0 H1 H.\n          intros.\n          apply (ReachDecidable_si g g (negateP m)); [reflexivity | | apply R_DEC; right; auto].\n          hnf in H2 |- *; clear - H2.\n          intros; specialize (H2 x).\n          rewrite !negateP_spec; tauto.\n      - intros; apply V_DEC; right; auto.\n  Qed.\n\n  Lemma mark_list_marked: forall m1 l m2\n    (R_DEC: forall x, In x l -> ReachDecidable g x (negateP m1))\n    (V_DEC: forall x, In x l -> Decidable (vvalid g x)),\n    mark_list m1 l m2 ->\n    forall n : V, m1 n -> m2 n.\n  Proof.\n    apply (ind_RV_DEC (fun m1 l m2 => forall n : V, m1 n -> m2 n)).\n    + intros.\n      rewrite <- (H n).\n      auto.\n    + intros.\n      apply H.\n      apply (mark_markeds m v m'); auto.\n      apply R_DEC; left; auto.\n  Qed.\n\n  Lemma mark_list_get_marked: forall m1 l m2\n    (R_DEC: forall x, In x l -> ReachDecidable g x (negateP m1))\n    (V_DEC: forall x, In x l -> Decidable (vvalid g x)),\n    mark_list m1 l m2 ->\n    forall z n,\n    In z l ->\n    g |= z ~o~> n satisfying (negateP m1) ->\n    m2 n.\n  Proof.\n    apply (ind_RV_DEC (fun m1 l m2 =>\n            forall z n : V, In z l -> g |= z ~o~> n satisfying (negateP m1) -> m2 n)).\n    + intros.\n      inversion H0.\n    + intros.\n      destruct H2.\n      - subst z. apply (mark_list_marked m' l m''); auto.\n        * intros.\n          apply (mark_preserved_reach_decidable m v m'); auto.\n          1: apply reachable_by_head_valid in H3; auto.\n          1: apply R_DEC; right; auto.\n          1: apply R_DEC; left; auto.\n        * intros; apply V_DEC; right; auto.\n        * destruct H0 as [? _]; auto.\n      - destruct (V_DEC v (or_introl eq_refl)).\n        1: {\n          apply (mark_unmarked m v m') in H3; auto; [| apply R_DEC; left; auto].\n          destruct H3.\n          + apply (H z); auto.\n          + apply (mark_list_marked m' l); auto.\n            - intros.\n              apply (mark_preserved_reach_decidable m v m'); auto.\n              * apply R_DEC; right; auto.\n              * apply R_DEC; left; auto.\n            - intros; apply V_DEC; right; auto.\n        }\n        1: {\n          pose proof (mark_invalid m v m' n0 H0).\n          apply (H z); auto.\n          erewrite si_reachable_by in H3; [exact H3 | reflexivity |].\n          hnf in H4 |- *; clear - H4.\n          intros.\n          specialize (H4 x).\n          rewrite !negateP_spec.\n          tauto.\n        }\n  Qed.\n\n  Lemma mark_list_preserve_marked: forall m1 l m2\n    (R_DEC: forall x, In x l -> ReachDecidable g x (negateP m1))\n    (V_DEC: forall x, In x l -> Decidable (vvalid g x)),\n    mark_list m1 l m2 ->\n    forall n,\n    (forall x, In x l -> ~ g |= x ~o~> n satisfying (negateP m1)) ->\n    (m1 n <-> m2 n).\n  Proof.\n    apply (ind_RV_DEC (fun m1 l m2 =>\n            forall n,\n           (forall x, In x l -> ~ g |= x ~o~> n satisfying (negateP m1)) ->\n           (m1 n <-> m2 n))).\n    + intros. apply H.\n    + intros.\n      rewrite <- H.\n      - destruct H0 as [_ ?].\n        apply H0, H2.\n        left; auto.\n      - intros.\n        intro.\n        apply (mark_reverse_unmarked m v m') in H4; [| auto | apply R_DEC; left; auto].\n        apply (H2 x); auto.\n        right; auto.\n  Qed.\n\n  Lemma mark_mark1_mark: forall m1 root l m2 m3\n    (R_DEC: forall x, In x l -> ReachDecidable g x (negateP m2))\n    (V_DEC: forall x, In x l -> Decidable (vvalid g x)),\n    vvalid g root -> (negateP m1) root ->\n    step_list g root l ->\n    mark1 m1 root m2 ->\n    mark_list m2 l m3 ->\n    mark m1 root m3.\n  Proof.\n    intros. split; intros.\n    + apply (mark1_unmarked _ _ _ _ H2) in H4. destruct H4.\n      - subst n. destruct H2 as [_ [? _]].\n        eapply mark_list_marked; eauto.\n      - destruct H4 as [z [? ?]]. unfold edge in H4; rewrite <- (H1 z) in H4. destruct H4 as [_ [_ ?]].\n        eapply mark_list_get_marked; eauto.\n    + assert (m1 n <-> m2 n). {\n        destruct H2 as [? [? ?]].\n        apply H6. intro. apply H4. subst. apply reachable_by_refl; auto.\n      } rewrite H5.\n      assert (forall x, In x l -> ~ g |= x ~o~> n satisfying (negateP m2)). {\n        intros. intro.\n        destruct (V_DEC x H6).\n        + apply (mark1_reverse_unmark m1 root) in H7; auto.\n          apply H4. apply H1 in H6.\n          apply edge_reachable_by with x; auto.\n          unfold edge; auto.\n        + apply reachable_by_head_valid in H7; tauto.\n      }\n      eapply mark_list_preserve_marked; eauto.\n  Qed.\n\n  Lemma mark_func: forall m root m1 m2 (R_DEC: ReachDecidable g root (negateP m)),\n                     mark m root m1 ->\n                     mark m root m2 ->\n                     (m1 ~=~ m2)%NodePred.\n  Proof.\n    intros.\n    intro; intros.\n    destruct H as [? ?].\n    destruct H0 as [? ?].\n    destruct (R_DEC n).\n    - specialize (H n r). specialize (H0 n r). tauto.\n    - specialize (H2 n n0). specialize (H1 n n0). tauto.\n  Qed.\n\n  Lemma mark1_mark_list_vi: forall m1 root l m2 m3 m4\n                                   (R_DEC: forall x, In x l -> ReachDecidable g x (negateP m2))\n                                   (V_DEC: forall x, In x l -> Decidable (vvalid g x))\n                                   (R_DEC': ReachDecidable g root (negateP m1)),\n                              vvalid g root -> (negateP m1) root ->\n                              step_list g root l ->\n                              mark1 m1 root m2 ->\n                              mark_list m2 l m3 ->\n                              mark m1 root m4 ->\n                              (m3 ~=~ m4)%NodePred.\n  Proof.\n    intros. assert (mark m1 root m3).\n    apply (mark_mark1_mark _ _ l m2); auto.\n    apply (mark_func m1 root); auto.\n  Qed.\n\n  Lemma mark_marked_reachable_conflict: forall m1 root m2 n\n    (R_DEC: ReachDecidable g root (negateP m1)),\n    mark m1 root m2 ->\n    Included (reachable_by g n (negateP m2)) (Complement _ (reachable_by g root (negateP m1))).\n  Proof.\n    intros.\n    intro n'; unfold Ensembles.In; intros.\n    eapply mark_reverse_unmarked_strong in H0; [| eauto | eauto].\n    apply reachable_by_is_reachable in H0.\n    rewrite <- reachable_by_eq_partialgraph_reachable in H0.\n    apply reachable_by_foot_prop in H0.\n    auto.\n  Qed.\n\n  Lemma mark_list_marked_reachable_conflict: forall m1 l m2\n    (R_DEC: forall x, In x l -> ReachDecidable g x (negateP m1))\n    (V_DEC: forall x, In x l -> Decidable (vvalid g x)),\n    mark_list m1 l m2 ->\n    forall n,\n    Included (reachable_by g n (negateP m2)) (Complement _ (reachable_by_through_set g l (negateP m1))).\n  Proof.\n    intros.\n    intro n'; unfold Complement, Ensembles.In; intros.\n    intros [? [? ?]].\n    pose proof mark_list_get_marked _ _ _ R_DEC V_DEC H x n' H1.\n    apply reachable_by_foot_prop in H0.\n    change ((negateP m2) n') with (~ (m2 n')) in H0.\n    tauto.\n  Qed.\n\n(*\n\n  Lemma mark_unreachable: forall g1 root g2,\n    mark g1 root g2 ->\n    forall n, ~ (reachable g1 root n) -> @node_label _ _ _ g1 n = @node_label _ _ _ g2 n.\n  Proof.\n    intros. destruct H as [? [? ?]].\n    apply H2.\n    intro. apply H0.\n    generalize (reachable_by_subset_reachable g1 root unmarked n); intro.\n    intuition.\n  Qed.\n\n  Lemma mark_unreachable_subgraph:\n    forall g1 root g2, mark g1 root g2 -> (unreachable_subgraph g1 (root :: nil)) -=- (unreachable_subgraph g2 (root :: nil)).\n  Proof.\n    intros. generalize H; intro. split; [|split]; intros; destruct H as [? [? ?]]; specialize (H v); destruct H. simpl.\n    unfold unreachable_valid. split; intros; destruct H4; split. rewrite <- H. apply H4. intro; apply H5; clear H5.\n    unfold reachable_through_set in *. destruct H6 as [s [? ?]]. exists s. split; auto. apply in_inv in H5. destruct H5. subst.\n    destruct H0 as [? _]. apply si_sym in H0. apply (si_reachable _ _ s H0). auto. inversion H5. rewrite H. auto.\n    intro; apply H5; clear H5. destruct H6 as [s [? ?]]. exists s. split; auto. apply in_inv in H5. destruct H5. subst.\n    destruct H0 as [? _]. apply (si_reachable _ _ s H0). auto. inversion H5. simpl in H1. hnf in H1. destruct H1.\n    assert (~ (reachable g1 root v)). intro; apply H5; clear H5. exists root. split. apply in_eq. auto.\n    apply (mark_unreachable _ _ _ H0 v H6). auto.\n  Qed.\n\n*)\n\n  End SINGLE_GRAPH_LEM.\n\n  #[export] Instance mark1_proper: Proper (structurally_identical ==> node_pred_equiv ==> eq ==> node_pred_equiv ==> iff) mark1.\n  Proof.\n    hnf; intros g1 g2 Hg.\n    do 3 (hnf; intros).\n    subst.\n    revert g1 g2 x y x1 y1 Hg H H1.\n    assert (forall g1 g2 x y x1 y1, g1 ~=~ g2 -> x ~=~ y%NodePred -> x1 ~=~ y1%NodePred -> mark1 g1 x y0 x1 -> mark1 g2 y y0 y1);\n      [| intros; split; apply H; auto; symmetry; auto].\n    unfold mark1.\n    intros.\n    rewrite (H1 y0) in H2.\n    rewrite (proj1 H) in H2.\n    split; [| split]; try tauto.\n    destruct H2 as [_ [_ ?]].\n    intros; specialize (H2 n').\n    rewrite (H0 n'), (H1 n') in H2.\n    tauto.\n  Qed.\n\n  Lemma mark_proper_strong: forall (g g': PreGraph V E) m1 root m2,\n    ((predicate_partialgraph g (reachable_by g root (negateP m1))) ~=~\n    (predicate_partialgraph g' (reachable_by g' root (negateP m1)))) ->\n    (mark g m1 root m2 <-> mark g' m1 root m2).\n  Proof.\n    assert (forall (g g': PreGraph V E) m1 root m2,\n    ((predicate_partialgraph g (reachable_by g root (negateP m1))) ~=~\n    (predicate_partialgraph g' (reachable_by g' root (negateP m1)))) ->\n    mark g m1 root m2 -> mark g' m1 root m2).\n    2: intros; split; apply H; auto; symmetry; auto.\n    unfold mark; intros.\n    split; intros; destruct H0.\n    + apply H0.\n      pose proof partialgraph_si_node_prop n g g' _ _ H.\n      spec H3.\n      1: {\n        intros ? ?.\n        apply reachable_by_foot_valid in H4.\n        auto.\n      }\n      spec H3.\n      1: {\n        intros ? ?.\n        apply reachable_by_foot_valid in H4.\n        auto.\n      }\n      tauto.\n    + apply H2.\n      pose proof partialgraph_si_node_prop n g g' _ _ H.\n      spec H3.\n      1: {\n        intros ? ?.\n        apply reachable_by_foot_valid in H4.\n        auto.\n      }\n      spec H3.\n      1: {\n        intros ? ?.\n        apply reachable_by_foot_valid in H4.\n        auto.\n      }\n      tauto.\n  Qed.\n\n  Lemma mark_list_proper_strong: forall (g g': PreGraph V E) m1 l m2\n    (R_DEC: forall x, In x l -> ReachDecidable g x (negateP m1))\n    (V_DEC: forall x, In x l -> Decidable (vvalid g x))\n    (R_DEC': forall x, In x l -> ReachDecidable g' x (negateP m1))\n    (V_DEC': forall x, In x l -> Decidable (vvalid g' x)),\n    ((predicate_partialgraph g (reachable_by_through_set g l (negateP m1))) ~=~\n    (predicate_partialgraph g' (reachable_by_through_set g' l (negateP m1)))) ->\n    (mark_list g m1 l m2 <-> mark_list g' m1 l m2).\n  Proof.\n    intros.\n    assert (forall (g: PreGraph V E) m1 l m2\n    (R_DEC: forall x, In x l -> ReachDecidable g x (negateP m1))\n    (V_DEC: forall x, In x l -> Decidable (vvalid g x)),\n    mark_list g m1 l m2 ->\n    forall (g': PreGraph V E),\n    ((predicate_partialgraph g (reachable_by_through_set g l (negateP m1))) ~=~\n    (predicate_partialgraph g' (reachable_by_through_set g' l (negateP m1)))) ->\n    mark_list g' m1 l m2).\n    2: intros; split; intros; eapply H0; eauto; symmetry; eauto; reflexivity.\n    intro.\n    apply (ind_RV_DEC g0 (fun m l m' => forall g'0 : PreGraph V E,\n   (predicate_partialgraph g0 (reachable_by_through_set g0 l (negateP m))) ~=~\n   (predicate_partialgraph g'0 (reachable_by_through_set g'0 l (negateP m))) ->\n   mark_list g'0 m l m')); intros.\n    + constructor.\n      auto.\n    + econstructor.\n      - pose proof mark_proper_strong g0 g'0 m v m'.\n        spec H4; [| rewrite <- H4; auto].\n        eapply si_stronger_partialgraph with (p := (reachable_by g0 v (negateP m))); [| | exact H3]; intros.\n        * assert (g0 |= v ~o~> v0 satisfying (negateP m) ->\n            reachable_by_through_set g0 (v :: l0) (negateP m) v0); [intro | tauto].\n          exists v; split; [simpl |]; auto.\n        * pose proof reachable_by_partialgraph_reachable_by_equiv g0 (reachable_by_through_set g0 (v :: l0) (negateP m)) (negateP m) v.\n          spec H5; [intro; intros; exists v; split; [simpl |]; auto |].\n          pose proof reachable_by_partialgraph_reachable_by_equiv g'0 (reachable_by_through_set g'0 (v :: l0) (negateP m)) (negateP m) v.\n          spec H6; [intro; intros; exists v; split; [simpl |]; auto |].\n          rewrite H3 in H5.\n          rewrite <- H5 in H6.\n          clear H5.\n          rewrite Same_set_spec in H6.\n          specialize (H6 v0).\n          assert (g'0 |= v ~o~> v0 satisfying (negateP m) ->\n            reachable_by_through_set g'0 (v :: l0) (negateP m) v0); [intro | tauto].\n          exists v; split; [simpl |]; auto.\n      - apply H0.\n        eapply si_stronger_partialgraph with (p := (reachable_by_through_set g0 l0 (negateP m'))); [| | eauto]; intros.\n        * assert (reachable_by_through_set g0 l0 (negateP m') v0 ->\n            reachable_by_through_set g0 (v :: l0) (negateP m) v0); [intro | tauto].\n          destruct H4 as [vv [? ?]]; exists vv; split; [simpl |]; auto.\n          eapply reachable_by_weaken; [| eauto].\n          apply Complement_Included_rev; intro; eapply mark_markeds; [eauto |].\n          apply R_DEC0; simpl; auto.\n        * assert (reachable_by_through_set g'0 l0 (negateP m') v0 <->\n            reachable_by_through_set g0 l0 (negateP m') v0).\n          1: {\n            apply ex_iff; intro.\n            apply and_iff_compat_l_weak; intro.\n            pose proof reachable_by_partialgraph_reachable_by_equiv g0 (reachable_by_through_set g0 (v :: l0) (negateP m)) (negateP m') x.\n            spec H5.\n            1: {\n              intro; intros; exists x.\n              split; [simpl; auto |].\n              eapply reachable_by_weaken; eauto.\n              apply Complement_Included_rev; intro; eapply mark_markeds; [eauto |].\n              apply R_DEC0; simpl; auto.\n            }\n            pose proof reachable_by_partialgraph_reachable_by_equiv g'0 (reachable_by_through_set g'0 (v :: l0) (negateP m)) (negateP m') x.\n            spec H6.\n            1: {\n              intro; intros; exists x.\n              split; [simpl; auto |].\n              eapply reachable_by_weaken; eauto.\n              apply Complement_Included_rev; intro; eapply mark_markeds; [eauto |].\n              apply R_DEC0; simpl; auto.\n            }\n            rewrite H3 in H5.\n            rewrite <- H5 in H6.\n            rewrite Same_set_spec in H6.\n            clear H5; apply H6.\n          }\n          assert (reachable_by_through_set g'0 l0 (negateP m') v0 ->\n            reachable_by_through_set g'0 (v :: l0) (negateP m) v0); [clear H4; intro | tauto].\n          destruct H4 as [vv [? ?]]; exists vv; split; [simpl |]; auto.\n          eapply reachable_by_weaken; [| eauto].\n          apply Complement_Included_rev; intro; eapply mark_markeds; [eauto |].\n          apply R_DEC0; simpl; auto.\n  Qed.\n\n  #[export] Instance mark_proper: Proper (structurally_identical ==> node_pred_equiv ==> eq ==> node_pred_equiv ==> iff) mark.\n  Proof.\n    hnf; intros g1 g2 Hg.\n    do 3 (hnf; intros).\n    subst.\n    revert g1 g2 x y x1 y1 Hg H H1.\n    assert (forall g1 g2 x y x1 y1, g1 ~=~ g2 -> x ~=~ y%NodePred -> x1 ~=~ y1%NodePred -> mark g1 x y0 x1 -> mark g2 y y0 y1);\n      [| intros; split; apply H; auto; symmetry; auto].\n    unfold mark.\n    intros; destruct H2.\n    split.\n    + intros.\n      rewrite <- (H1 n); apply H2; auto.\n      rewrite si_reachable_by; [exact H4 | auto |].\n      hnf; intros.\n      rewrite !negateP_spec; specialize (H0 x0); tauto.\n    + intros.\n      rewrite <- (H0 n), <- (H1 n); apply H3; auto.\n      rewrite si_reachable_by; [exact H4 | auto |].\n      hnf; intros.\n      rewrite !negateP_spec; specialize (H0 x0); tauto.\n  Qed.\n\n  #[export] Instance mark_list_proper: Proper (structurally_identical ==> node_pred_equiv ==> eq ==> node_pred_equiv ==> iff) mark_list.\n  Proof.\n    hnf; intros g1 g2 Hg.\n    do 3 (hnf; intros).\n    subst.\n    revert g1 g2 x y x1 y1 Hg H H1.\n    assert (forall g1 g2 x y x1 y1, g1 ~=~ g2 -> x ~=~ y%NodePred -> x1 ~=~ y1%NodePred -> mark_list g1 x y0 x1 -> mark_list g2 y y0 y1);\n      [| intros; split; apply H; auto; symmetry; auto].\n    intros; subst.\n    revert g2 y y1 H H0 H1; induction H2; intros.\n    + apply mark_list_nil.\n      rewrite <- H1, <- H2, H; reflexivity.\n    + apply mark_list_cons with m0.\n      - rewrite <- H0, <- H1; auto.\n      - apply IHmark_list; [auto | reflexivity | auto].\n  Qed.\n\nEnd SIMPLE_MARK_GRAPH.\nEnd SIMPLE_MARK_GRAPH.\n\n#[local] Existing Instances SIMPLE_MARK_GRAPH.mark1_proper SIMPLE_MARK_GRAPH.mark_proper SIMPLE_MARK_GRAPH.mark_list_proper.\n\nModule MarkGraph.\n\nClass MarkGraphSetting (DV: Type) := {\n  label_marked: DV -> Prop;\n  label_mark: DV -> DV;\n  label_unmark: DV -> DV;\n  marked_dec: forall x, {label_marked x} + {~ label_marked x};\n  label_mark_sound: forall x, ~ label_marked x -> label_marked (label_mark x);\n  label_unmark_sound: forall x, label_marked x -> ~ label_marked (label_unmark x)\n}.\n\nSection MarkGraph.\n\nContext {V E: Type}.\nContext {EV: EqDec V eq}.\nContext {EE: EqDec E eq}.\nContext {DV DE DG: Type}.\nContext {MGS: MarkGraphSetting DV}.\nContext {P: LabeledGraph V E DV DE DG -> Type}.\n\nNotation Graph := (GeneralGraph V E DV DE DG P).\nLocal Coercion pg_lg : LabeledGraph >-> PreGraph.\nLocal Coercion lg_gg : GeneralGraph >-> LabeledGraph.\n\nDefinition marked (g: Graph) : NodePred V.\n  refine (existT _ (fun v => label_marked (vlabel g v)) _).\n  intros.\n  apply marked_dec.\nDefined.\n\nDefinition unmarked (g: Graph) (v: V) : Prop := negateP (marked g) v.\n\nDefinition mark1 (g1 : Graph) (n : V) (g2 : Graph) : Prop :=\n  g1 ~=~ g2 /\\\n  vvalid g1 n /\\\n  marked g2 n /\\\n  forall n', n <> n' -> (marked g1 n' <-> marked g2 n').\n\nDefinition mark (g1 : Graph) (root : V) (g2 : Graph) : Prop :=\n  g1 ~=~ g2 /\\\n  (forall n, g1 |= root ~o~> n satisfying (unmarked g1) -> marked g2 n) /\\\n  (forall n, ~ g1 |= root ~o~> n satisfying (unmarked g1) -> (marked g1 n <-> marked g2 n)).\n\nInductive mark_list: Graph -> list V -> Graph -> Prop :=\n| mark_list_nil: forall g, mark_list g nil g\n| mark_list_cons: forall (g g0 g1: Graph) v vs, mark g v g0 -> mark_list g0 vs g1 -> mark_list g (v :: vs) g1\n.\n\nDefinition inj (g: Graph): NodePred V.\n  exists (fun v => label_marked (vlabel g v)).\n  intros; apply marked_dec.\nDefined.\n(*\n#[export] Instance inj_proper: Proper ((fun (g1 g2: Graph) => (g1 ~=~ g2)%LabeledGraph) ==> node_pred_equiv) inj.\nProof.\n  hnf; intros.\n  intro; simpl.\n  destruct H as [_ [? _]].\n  rewrite H.\n  tauto.\nDefined.\n*)\nLemma mark1_inj: forall (g1 g2: Graph) (v: V), mark1 g1 v g2 <-> (g1 ~=~ g2 /\\ SIMPLE_MARK_GRAPH.mark1 g1 (inj g1) v (inj g2)).\nProof.\n  intros.\n  unfold mark1, SIMPLE_MARK_GRAPH.mark1.\n  simpl.\n  unfold marked.\n  tauto.\nQed.\n\nLemma mark_inj: forall (g1 g2: Graph) (v: V), mark g1 v g2 <-> (g1 ~=~ g2 /\\ SIMPLE_MARK_GRAPH.mark g1 (inj g1) v (inj g2)).\nProof.\n  intros.\n  unfold mark, SIMPLE_MARK_GRAPH.mark.\n  simpl.\n  unfold marked.\n  tauto.\nQed.\n\nLemma mark_list_inj: forall (g1 g2: Graph) (vs: list V), mark_list g1 vs g2 -> (g1 ~=~ g2 /\\ SIMPLE_MARK_GRAPH.mark_list g1 (inj g1) vs (inj g2)).\nProof.\n  intros.\n  induction H.\n  - split; [reflexivity |].\n    constructor.\n    reflexivity.\n  - rewrite mark_inj in H.\n    split; [transitivity g0; tauto |].\n    apply SIMPLE_MARK_GRAPH.mark_list_cons with (inj g0); [tauto |].\n    rewrite (proj1 H); tauto.\nQed.\n\nLemma vertex_update_mark1: forall (g1: Graph) x (g2: Graph),\n  g1 ~=~ g2 ->\n  vvalid g1 x ->\n  unmarked g1 x ->\n  vlabel g2 x = label_mark (vlabel g1 x) ->\n  (forall y, x <> y -> vlabel g2 y = vlabel g1 y) ->\n  (forall e, elabel g2 e = elabel g1 e) ->\n  mark1 g1 x g2.\nProof.\n  intros.\n  split; [| split; [| split]]; auto.\n  + simpl.\n    rewrite H2.\n    apply label_mark_sound.\n    apply H1.\n  + intros y HH; specialize (H3 y HH). clear - H3.\n    simpl.\n    rewrite H3.\n    reflexivity.\nQed.\n\nLemma mark_invalid_refl: forall (g: Graph) root, ~ vvalid g root -> mark g root g.\nProof.\n  intros.\n  pose proof SIMPLE_MARK_GRAPH.mark_invalid_refls g (inj g) root H.\n  rewrite -> mark_inj.\n  split; [reflexivity | auto].\nQed.\n\nLemma mark_marked_root_refl: forall (g: Graph) root, marked g root -> mark g root g.\nProof.\n  intros.\n  pose proof SIMPLE_MARK_GRAPH.mark_marked_root_refls g (inj g) root H.\n  rewrite -> mark_inj.\n  split; [reflexivity | auto].\nQed.\n\nLemma mark_marked: forall (g1: Graph) root (g2: Graph),\n  mark g1 root g2 ->\n  ReachDecidable g1 root (unmarked g1) ->\n  forall n, marked g1 n -> marked g2 n.\nProof.\n  intros.\n  rewrite mark_inj in H.\n  destruct H.\n  apply @SIMPLE_MARK_GRAPH.mark_markeds with (n := n) in H1; auto.\nQed.\n\nLemma mark1_mark_list_mark: forall (g1: Graph) root l (g2 g3: Graph)\n  (R_DEC: forall x, In x l -> ReachDecidable g2 x (unmarked g2))\n  (V_DEC: forall x, In x l -> Decidable (vvalid g1 x))\n  (R_DEC': ReachDecidable g1 root (unmarked g1)),\n  vvalid g1 root ->\n  (unmarked g1) root ->\n  step_list g1 root l ->\n  mark1 g1 root g2 ->\n  mark_list g2 l g3 ->\n  mark g1 root g3.\nProof.\n  intros.\n  rewrite mark1_inj in H2.\n  apply mark_list_inj in H3.\n  rewrite mark_inj.\n  split; [transitivity g2; tauto |].\n  apply SIMPLE_MARK_GRAPH.mark_mark1_mark with l (inj g2); auto.\n  + intros.\n    eapply ReachDecidable_si; [symmetry; exact (proj1 H2) | | eauto].\n    intro; intros.\n    unfold unmarked; rewrite negateP_spec; simpl.\n    reflexivity.\n  + tauto.\n  + rewrite <- (proj1 H2) in H3 at 2; tauto.\nQed.\n\nEnd MarkGraph.\nEnd MarkGraph.\n", "meta": {"author": "CertiGraph", "repo": "CertiGraph", "sha": "1be51414c139f8bc16b3e22f72989e454c37ce3c", "save_path": "github-repos/coq/CertiGraph-CertiGraph", "path": "github-repos/coq/CertiGraph-CertiGraph/CertiGraph-1be51414c139f8bc16b3e22f72989e454c37ce3c/graph/marked_graph.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2700364723470626}}
{"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 * AbsExecute.v\n * This file contains the basic hoare triple definition and many auxiliary theorems\n * and definitions related to forward propagation.\n *\n * Some key definitions:\n *     absExecute\n *     hoare_triple\n *     strengthenPost\n *     assign\n *     basic_assign\n *     load_traverse\n *     load\n *     store\n *     new_thm\n *     delete_thm\n *     if_statement\n *     while\n *     mergeStates\n *\n **********************************************************************************)\n\nRequire Import Omega.\nRequire Export SfLib.\nRequire Export ImpHeap.\nRequire Export AbsState.\nRequire Export PickElement.\nRequire Export AbsStateInstance.\nRequire Export Tactics.\nRequire Export Classical.\nRequire Export FunctionalExtensionality.\n\n(* ***************************************************************************\n *\n * absExecute is the top level predicate that defines what execution of a\n * statement does to the abstract state.\n *\n * Parameters:\n *     ff - function specifications (see ceval in ImpHeap.v)\n *     c - command being executed (see ImpHeap.v)\n *     s - AbsState before execution\n *     s' - AbsState after execution\n *     r - result (see ceval in ImpHeap.v)\n *\n * The intuition behind this definition is that if s is true before executing\n * c, then s' will be true afterwards.  realizeState is used to relate\n * the abstract states to the concrete states and ceval is used to relate\n * the pre- and post- concrete states.\n *\n ***************************************************************************)\n\n  Fixpoint In {A:Type} (a:A) (l:list A) : Prop :=\n    match l with\n      | nil => False\n      | b :: m => b = a \\/ In a m\n    end.\n\nDefinition absExecute (ff : functions) (c : com) (s : absState) (s' : absState) (r : list absExp) (s'' : absState)  (exc : id -> (absExp * absState)) : Prop :=\n    forall st st' i x, \n        realizeState s nil st ->\n        ((exists st', exists r, ceval ff st c st' r) /\\\n         ((ceval ff st c st' NoResult -> realizeState s' nil st') \\/\n          (ceval ff st c st' (Return x) -> (forall rx, In rx r -> absEval (fst st') nil rx = NatValue x /\\ realizeState s'' nil st')) \\/\n          (ceval ff st c st' (Exception i x) -> (absEval (fst st') nil (fst (exc i)) = NatValue x /\\ realizeState (snd (exc i)) nil st')))).\n\n\nFixpoint evalList env el vl : Prop :=\n    match (el,vl) with\n    | (nil,nil) => True\n    | (ef::er,vf::vr) => absEval env nil ef = vf /\\ evalList env er vr\n    | (_,_) => False\n    end.\n\n(*\n * mergeReturnStates specifies where states need to be merged at the end of processing an if-then-else\n *)\nDefinition mergeReturnStates (Q1 : absState) (Q2 : absState) (Q : absState) (R1 : list absExp) (R2 : list absExp) (R : list absExp) :=\n    (forall s v, realizeState Q1 nil s -> evalList (fst s) R1 v-> (realizeState Q nil s /\\ evalList (fst s) R v)) /\\\n    (forall s v, realizeState Q2 nil s -> evalList (fst s) R2 v-> (realizeState Q nil s /\\ evalList (fst s) R v)).\n\n(* Our Hoare triple notation is based on the absExecute definition *)\nDefinition hoare_triple (P : absState) c (Q : absState) r Qr exc :=\n           absExecute (fun x => fun y => fun z => fun a => fun b => False) c P Q r Qr exc.\n\nNotation \"{{ P }} c {{ Q }}\" := (hoare_triple P c Q (#0) AbsNone (fun x => (#0,AbsNone))) (at level 90).\n\nNotation \"{{ P }} c {{ Q 'return' rr 'with' QQ }}\" := (hoare_triple P c Q rr QQ (fun x => (#0,AbsNone))) (at level 90).\n\n(* **************************************************************************\n *\n * Post condition strengthening\n *\n * **************************************************************************)\n\nFixpoint equivEvalList env el1 el2 : Prop :=\n    match (el1,el2) with\n    | (nil,nil) => True\n    | (ef::er,vf::vr) => absEval env nil ef = absEval env nil vf /\\ equivEvalList env er vr\n    | (_,_) => False\n    end.\n\nTheorem strengthenPost : forall (P : absState) c Q r Q' QQ QQ' r',\n    {{ P }} c {{ Q return r with QQ }} ->\n    (forall s, realizeState Q nil s -> realizeState Q' nil s) ->\n    (forall s, realizeState QQ nil s -> realizeState QQ' nil s) ->\n    (forall s, realizeState QQ nil s -> realizeState QQ' nil s ->\n        equivEvalList (fst s) r r' ) ->\n    {{ P }} c {{ Q' return r' with QQ' }}.\nProof. admit.\n    (*unfold hoare_triple. unfold absExecute. intros.\n\n    assert (forall st st' : state,\n    realizeState P nil st ->\n    (exists (st'0 : state) (r : result),\n       ceval\n         (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n          False) st c st'0 r)).\n    intros.\n    assert ((exists (st'0 : state) (r : result),\n       ceval\n         (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n          False) st0 c st'0 r) /\\\n    (ceval\n       (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n        False) st0 c st' r -> realizeState Q nil st')).\n    eapply H. apply H2. inversion H3. apply H4.\n\n    assert (forall st st' : state,\n    realizeState P nil st -> (ceval\n       (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n        False) st c st' r -> realizeState Q nil st')).\n    intros.\n    assert ((exists (st'00 : state) (r : result),\n       ceval\n         (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n          False) st0 c st'00 r) /\\\n    (ceval\n       (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n        False) st0 c st'0 r -> realizeState Q nil st'0)).\n    eapply H. apply H3. inversion H5. apply H7. apply H4.\n\n    split.\n\n    eapply H2. apply st'. apply H1.\n\n    intros. apply H0. eapply H3. apply H1. apply H4.*)\nAdmitted.\n\n(* **************************************************************************\n *\n * Theorem for SKIP\n *\n * **************************************************************************)\n\nTheorem skip_thm : forall (P:absState) r,\n    {{ P }}SKIP{{ P return r with AbsNone }}.\nProof. admit. Admitted.\n\n(* **************************************************************************\n *\n * Theorem for RETURN\n *\n * **************************************************************************)\n\nTheorem return_thm : forall (P:absState) e r,\n    r = convertToAbsExp e ->\n    {{ P }}RETURN e{{ AbsNone return (r::nil) with P }}.\nProof. admit. Admitted.\n\n(* **************************************************************************\n *\n * Theorems for statement composition\n *\n * **************************************************************************)\nTheorem compose : forall (P:absState) c1 P' c2 Q R r1 r2 R' Q' rm,\n    {{ P }} c1 {{ Q return r1 with P' }} ->\n    {{ Q }} c2 {{ R return r2 with Q' }} ->\n    mergeReturnStates P' Q' R' r1 r2 rm ->\n    {{ P }} c1;c2 {{ R return rm with R' }}.\nProof. admit.\n    (*unfold hoare_triple. unfold absExecute. intros.\n\n    assert (forall st st' : state,\n    realizeState P nil st ->\n    (exists (st'0 : state) (r : result),\n       ceval\n         (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n          False) st c1 st'0 r)).\n    intros.\n    assert ((exists (st'0 : state) (r : result),\n       ceval\n         (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n          False) st0 c1 st'0 r) /\\\n    (ceval\n       (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n        False) st0 c1 st' NoResult -> realizeState P' nil st')).\n    eapply H. apply H3. inversion H4. apply H5.\n\n    assert (forall st st' : state,\n    realizeState P nil st -> (ceval\n       (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n        False) st c1 st' NoResult -> realizeState P' nil st')).\n    intros.\n    assert ((exists (st'00 : state) (r : result),\n       ceval\n         (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n          False) st0 c1 st'00 r) /\\\n    (ceval\n       (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n        False) st0 c1 st'0 NoResult -> realizeState P' nil st'0)).\n    eapply H. apply H4. inversion H6. apply H8. apply H5.\n\n    assert (forall st st' : state,\n    realizeState P' nil st ->\n    (exists (st'0 : state) (r : result),\n       ceval\n         (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n          False) st c2 st'0 r)).\n    intros.\n    assert ((exists (st'0 : state) (r : result),\n       ceval\n         (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n          False) st0 c2 st'0 r) /\\\n    (ceval\n       (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n        False) st0 c2 st' r -> realizeState Q nil st')).\n    eapply H1. eapply H5. inversion H6. apply H7.\n\n    assert (forall st st' : state,\n    realizeState P' nil st -> (ceval\n       (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n        False) st c2 st' r -> realizeState Q nil st')).\n    intros.\n    assert ((exists (st'00 : state) (r : result),\n       ceval\n         (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n          False) st0 c2 st'00 r) /\\\n    (ceval\n       (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n        False) st0 c2 st'0 r -> realizeState Q nil st'0)).\n    eapply H1. apply H6. inversion H8. apply H10. apply H7.\n\n    split.\n\n    assert (realizeState P nil st). apply H2.\n\n    eapply H3 in H2.\n    inversion H2. subst. inversion H9. destruct x0. eapply H5 in H4.\n    inversion H4. inversion H10.\n    eapply ex_intro. eapply ex_intro. eapply CESeq1. eapply H9. eapply H11.\n    eapply x.\n    eapply H7. eapply H9.\n    eapply ex_intro. eapply ex_intro.\n    eapply CESeq2. apply H9.\n    eapply ex_intro. eapply ex_intro. eapply CESeq3. apply H9. apply st.\n\n    intros.\n\n    (inversion H7; subst; clear H7). apply H0 in H12. eapply H6 in H12.\n    apply H12. apply H15. apply H2.\n\n    assert ((Return v)=NoResult). eapply H. apply H14. inversion H7.\n    assert (Exception name val=NoResult). eapply H. apply H14. inversion H7.*)\nAdmitted.\n\n(* **************************************************************************\n *\n * Theorems for assignment\n *\n ****************************************************************************)\n\n(*\n *  The intent of the next several definitions is to build up a concept of\n *  a valid expression.  The informal idea is that if an AbsExp expression 'e'\n *  is valid with respect to an AbsState 's', then the result of evaluating\n *  the expression for any set of variable assignments which satisfy the\n *  's' will be a NatValue (and not a NoValue or anything else).\n *)\n\n(*\n * This function identifies key variables in an expression.  If all of these\n * variables are defined in the state (meaning that they have a NatValue rather\n * than NoValue), then the result of evaluating the expression will be a\n * NatValue.  If the result 'None' is returned, then no such set of key\n * variables can be determined.\n *)\nFixpoint keyVariables (e : absExp) : option (list id) := \n    match e with\n    | (AbsFun (AbsPlusId) (l::r::nil)) =>\n            match (keyVariables l,keyVariables r) with\n            | (Some l,Some r) => Some (l++r)\n            | _ => None\n            end\n    | (AbsFun (AbsMinusId) (l::r::nil)) =>\n            match (keyVariables l,keyVariables r) with\n            | (Some l,Some r) => Some (l++r)\n            | _ => None\n            end\n    | (AbsFun (AbsTimesId) (l::r::nil)) =>\n            match (keyVariables l,keyVariables r) with\n            | (Some l,Some r) => Some (l++r)\n            | _ => None\n            end\n    | (AbsFun (AbsEqualId) (l::r::nil)) =>\n            match (keyVariables l,keyVariables r) with\n            | (Some l,Some r) => Some (l++r)\n            | _ => None\n            end\n    | (AbsFun (AbsLessId) (l::r::nil)) =>\n            match (keyVariables l,keyVariables r) with\n            | (Some l,Some r) => Some (l++r)\n            | _ => None\n            end\n    | (AbsFun (AbsMemberId) (l::_::nil)) => keyVariables l\n    | (AbsFun (AbsIncludeId) (l::_::nil)) => keyVariables l\n    | (AbsFun (AbsNotId) (l::nil)) => keyVariables l\n    | (AbsVar i) => Some (i::nil)\n    | (AbsConstVal (NatValue x)) => Some nil\n    | _ => None\n    end.\n\nFixpoint is_kv (x : id) (kv : list id) :=\n   match kv with\n   | nil    => false\n   | (a::b) => if beq_id x a then true else is_kv x b\n   end.\n\nDefinition is_key_variable (x : id) (kv : option (list id)) :=\n   match kv with\n   | None => false\n   | Some y => is_kv x y\n   end.\n\n(*\n * This definition determines whether an AbsState 's' defines a constraint that\n * requires the variable 'id' to have an assigned value.  The rule used here is that\n * 's' is required to be assigned if it is a key variable in either the first expression\n * of an AbsPredicate or TREE or either the first or second predicate in an AbsCell.\n *)\nFixpoint basicVarAssigned (s : absState) id : bool :=\n   match s with\n   | AbsStar s1 s2 => if basicVarAssigned s1 id then true else basicVarAssigned s2 id\n   | AbsExistsT s => basicVarAssigned s id\n   | AbsExists l s => basicVarAssigned s id\n   (*| AbsAll i l s => basicVarAssigned s id*)\n   (*| AbsEach l s => basicVarAssigned s id*)\n   | AbsEmpty => false\n   | AbsLeaf (AbsPredicateId) (p::nil) => is_key_variable id (keyVariables p)\n   | AbsLeaf (AbsCellId) (f::s::nil) => if beq_absExp f (AbsVar id) then true else beq_absExp s (AbsVar id)\n   | AbsLeaf (AbsTreeId) (f::_) => beq_absExp f (AbsVar id)\n   | _ => false\n   end.\n\nFixpoint getRoot (s : absState) : absState :=\n    match s with\n    | AbsExistsT s => getRoot s\n    | _ => s\n    end.\n\n(*\n * VarAssigned is a little more powerful rule for picking out variables that are\n * required to be assigned a value.  In contains all of the rules of\n * basicVarAssigned plus a rule stating that if there is a predicate making the\n * variable equal to some other expression and that expression is the root of a\n * TREE, then the variable must be assigned.  Note that the something else might\n * be an AbsQVar which is not covered by keyVariables.\n *)\nInductive varAssigned : absState -> id -> Prop :=\n  | VarAssignedBasic : forall s v , basicVarAssigned s v = true ->\n                                    varAssigned s v\n  | VarAssignedPredicate1 : forall s v xx e a b c yy r,\n                            r = getRoot s ->\n                            spickElement r ([!!v ==== e]) xx ->\n                            spickElement xx (TREE(e,a,b,c)) yy ->\n                            varAssigned s v.\n\nHint Constructors varAssigned.\n\n(*\n * A Valid expression is one in which the VarAssigned predicate holds for\n * each of the key variables.\n *)\nDefinition validExpression\n                           (s : absState)\n                           (e : absExp) :=\n                                 forall x vars,\n                                 keyVariables e <> None /\\\n                                 (Some vars = keyVariables e ->\n                                 In x vars ->\n                                 varAssigned s x).\n\nTheorem quantifyExp :\n                    forall (x : absExp) (e:env) v val ee vars,\n                    val = NatValue (e v) ->\n                    absEval (override e v ee) (val::vars) (quantifyAbsVar x 0 0 v) =\n                    absEval e vars x.\nProof. admit.\n    (*intro x. induction x using abs_ind'.\n\n    crunch.\n\n    crunch. remember (beq_id id v). destruct b. crunch. crunch. unfold override. crunch.\n    crunch.\n\n    assert (forall (e : env) (v : SfLibExtras.id) (val : @Value ev) (ee : nat) vars,\n     (map\n     (absEval (override e v ee)\n        (NatValue (e v) :: vars)) (map (fun x : absExp => quantifyAbsVar x v) l)) =\n     (map (absEval e vars) l)).\n         induction l.\n         crunch.\n         crunch. rewrite H0. rewrite IHl. crunch. crunch. crunch. crunch.\n\n     crunch.\n     unfold quantifyAbsVar. fold (@quantifyAbsVar ev eq f).\n     crunch. rewrite H0. crunch. crunch. apply (NatValue 0).*)\nAdmitted.\n\nTheorem quantifyExpList :\n                    forall (l : list absExp) (e:env) x v val vars,\n                    val = NatValue (e v) ->\n                    (map (absEval (override e v x) (val::vars))\n                         (map (fun x0 => quantifyAbsVar x0 0 0 v) l))=\n                    (map (absEval e vars) l).\nProof. admit.\n    (*induction l.\n        crunch.\n        crunch. erewrite quantifyExp. erewrite IHl. crunch. crunch. crunch.*)\nAdmitted.\n\nTheorem mapFirsts {t} :\n        forall rl l v x,\n        @allFirsts (@Value t) state rl l -> allFirsts rl (map (fun ss => (fst ss,(override (fst (snd ss)) v x, snd (snd ss)))) l).\nProof.\n    induction rl.\n    crunch. inversion H. crunch.\n    crunch. inversion H. subst. clear H. crunch. apply AFCons. apply IHrl. crunch.\nQed.\n\nTheorem mapSeconds {t} :\n    forall sl l v x,\n    @allSeconds state (@Value t) sl l ->\n    allSeconds\n        (map (fun s => (override (fst s) v x,snd s)) sl)\n        (map\n            (fun ss : Value * (env * heap) =>\n                (fst ss, (override (fst (snd ss)) v x, snd (snd ss)))) l).\nProof.\n    induction sl.\n        crunch. inversion H. subst. crunch.\n        intros. inversion H. subst. clear H. crunch. eapply ASCons. eapply IHsl.\n        crunch.\nQed.\n\nTheorem mapFoldCompose :\n    forall states v x (st : state),\n    fold_compose states st ->\n    fold_compose\n         (map (fun s : env * heap => (override (fst s) v x, snd s)) states)\n         (override (fst st) v x, snd st).\nProof.\n    induction states.\n        crunch. inversion H. crunch. eapply FCNil.\n\n        crunch. inversion H. subst. clear H. eapply FCCons.\n            eapply IHstates. crunch.\n            unfold concreteCompose in H4. crunch.\n            unfold concreteCompose. crunch. rewrite <- H. crunch.\n            rewrite H1. crunch.\nQed.\n\nTheorem mapProp :\n        forall l v x y,\n                 In y (map\n                      (fun ss : (@Value unit) * (env * heap) =>\n                       (fst ss, (override (fst (snd ss)) v x, snd (snd ss)))) l) ->\n                 (exists y', (y = (fst y',(override (fst (snd y')) v x, snd (snd y'))) /\\ In y' l)).\nProof.\n    induction l.\n        crunch.\n\n        crunch. inversion H. subst. clear H. crunch. destruct a. crunch. destruct p.\n        crunch. apply ex_intro with (x := (v0, (e, h))). crunch.\n        assert (exists y', y = (fst y', (override (fst (snd y')) v x, snd (snd y'))) /\\\n            (In y' l)). eapply IHl. crunch.\n        crunch. apply ex_intro with (x := x0). crunch.\nQed.\n\nTheorem envProp'' :\n    forall states s e h, In s states -> fold_compose states (e,h) -> fst s = e.\nProof.\n    induction states.\n        crunch.\n\n        crunch. inversion H. subst. clear H.\n            inversion H0. subst. clear H0. unfold concreteCompose in H4. crunch.\n            subst. clear H. inversion H0. subst. clear H0. eapply IHstates. crunch.\n            instantiate (1 := (snd rstate)). unfold concreteCompose in H5. crunch.\n            destruct rstate. crunch.\nQed.\n\nTheorem envProp''' {t1} {t2} :\n    forall states s l, @allSeconds t1 t2 states l -> In s l -> In (snd s) states.\nProof.\n    induction states.\n        crunch. inversion H. subst. crunch.\n\n        intros. crunch. inversion H. subst. clear H. inversion H0. subst. clear H0.\n        left. crunch. right. eapply IHstates. crunch. crunch.\nQed.\n\nTheorem envProp {t} :\n    forall xl l (states : list state) st,\n    In xl l -> @allSeconds state (@Value t) states l -> fold_compose states st -> (fst st = fst (snd xl)).\nProof.\n    intros. erewrite <- envProp'' with (e := (fst st)) (s := (snd xl)) (states := states).\n    crunch.\n    eapply envProp'''. crunch. crunch. instantiate (1 := snd st). destruct st.\n    crunch.\nQed.\n\nTheorem quantify1gen :\n                    forall (P : absState) state v x val vars,\n                    val = NatValue (fst state v) ->\n                    realizeState P vars state -> realizeState (quantifyAbsVarState P 0 0 v) (val::vars)\n                                            (override (fst state) v x, snd state).\nProof. admit.\n    (*intro P. induction P.\n\n    crunch. unfold quantifyAbsVarState. fold (@quantifyAbsVarState ev eq f t ac).\n    inversion H0. subst. clear H0. eapply RSExists. crunch. erewrite quantifyExp.\n    unfold env_p in H3. crunch. crunch.\n    unfold env_p in H3. crunch.\n    apply ex_intro with (x := x0).\n    crunch. apply IHP. crunch. crunch.\n\n    crunch. unfold quantifyAbsVarState. fold (@quantifyAbsVarState ev eq f t ac).\n    inversion H0. subst. clear H0. eapply RSExistsU. crunch.\n    apply ex_intro with (x := x0).\n    crunch. apply IHP. crunch. crunch.\n\n    crunch. unfold quantifyAbsVarState. fold (@quantifyAbsVarState ev eq f t ac).\n    inversion H0. subst. clear H0. eapply RSAll. crunch. erewrite quantifyExp.\n    unfold env_p in H3. crunch. crunch.\n    unfold env_p in H3. crunch.\n    crunch. apply IHP. crunch. apply H6. *crunch?* crunch.\n\n    crunch. unfold quantifyAbsVarState. fold (@quantifyAbsVarState ev eq f t ac).\n    inversion H0. subst. clear H0. eapply RSEach. crunch. erewrite quantifyExp.\n    unfold env_p in H3. crunch. crunch.\n    eapply mapFirsts. crunch.\n    crunch. unfold env_p in H3.\n    eapply mapSeconds. crunch.\n    unfold env_p in H3. crunch.\n    eapply mapProp in H. crunch.\n    eapply IHP. crunch.\n    erewrite envProp. crunch. crunch. crunch. crunch.\n    eapply H6. destruct x1. *crunch?* crunch.\n    eapply mapFoldCompose. crunch.\n\n    crunch. inversion H0. subst. clear H0. eapply RSCompose.\n    eapply IHP1.\n    instantiate (1 := s1). unfold concreteCompose in H6. crunch.\n    assert (fst state v = fst s1 v).\n    rewrite <- H1. reflexivity.\n    rewrite H4. crunch. crunch.\n    eapply IHP2.\n    instantiate (1 := s2). unfold concreteCompose in H6. crunch.\n    assert (fst state v = fst s2 v).\n    rewrite <- H. rewrite <- H1. reflexivity.\n    rewrite H4. crunch.\n    crunch.\n    unfold concreteCompose in H6. crunch.\n    unfold concreteCompose. crunch.\n    instantiate (1 := x).\n    instantiate (1 := x).\n    assert (override (fst s1) v x = override (fst s2) v x).\n    rewrite H. reflexivity. crunch.\n    assert (override (fst state) v x = override (fst s1) v x).\n    rewrite <- H1. reflexivity. crunch.\n\n    crunch. inversion H0. subst. clear H0. eapply RSOrComposeL.\n    eapply IHP1.\n    reflexivity. apply H4.\n    subst. clear H0. eapply RSOrComposeR.\n    eapply IHP2.\n    reflexivity. apply H4.\n\n    crunch. inversion H0. subst. clear H0. eapply RSEmpty.\n        intros. simpl. apply H.\n\n    crunch. inversion H0. subst. clear H0. eapply RSR. simpl. rewrite quantifyExpList.\n    crunch. crunch. apply H5.\n\n    crunch. inversion H0. subst. clear H0.\n    eapply RSAccumulate.\n    simpl. rewrite quantifyExp. apply H6.\n    crunch.\n    simpl. reflexivity. unfold env_p in H8.\n    apply H8.\n\n    simpl. rewrite quantifyExp. unfold env_p in H6.\n apply H6.\n    simpl in H5.\n    remember (fst state v). destruct o.\n        rewrite quantifyExpList.\n rewrite quantifyExpList. 2:apply H5.\n\n unfold quantifyAbsVarState. fold (@quantifyAbsVarState ev eq f t ac).\n        unfold instantiateState. fold (@instantiateState ev eq f t ac).\n    inversion H0. subst. clear H0.\n    eapply RSR. crunch. rewrite quantifyExpList. crunch. crunch.\n\n    crunch. inversion H0.*)\nAdmitted.\n\nTheorem quantify1 :\n                    forall (P : absState) state v x val bindings,\n                    val = NatValue (fst state v) ->\n                    realizeState P bindings state -> realizeState (quantifyAbsVarState P 0 0 v) (val::bindings)\n                                            (override (fst state) v x, snd state).\nProof.\n    crunch. eapply quantify1gen. crunch. crunch.\nQed.\n\nTheorem absEvalSimp : forall (e : absExp) n (st : state) v x bindings,\n        n = fst st v ->\n        (absEval (override (fst st) v x) ((NatValue n)::bindings)\n                 (quantifyAbsVar e 0 0 v)) =\n        (absEval (fst st) bindings e).\nProof.\n    (*induction e using abs_ind'.\n\n    crunch.\n\n    crunch. remember (beq_id id v). destruct b. unfold override. crunch. unfold override. crunch.\n\n    crunch.\n\n    assert (forall (n : nat) (st : state) (v : SfLibExtras.id) (x : nat) bindings,\n        n = fst st v ->\n        (map (absEval (override (fst st) v x) ((NatValue n)::bindings))\n                (map (fun x0 : absExp => quantifyAbsVar x0 v) l)) =\n        (map (absEval (fst st) bindings) l)).\n        induction l. crunch.\n        crunch.\n        rewrite IHl. crunch. rewrite H0. crunch. crunch. crunch. crunch. crunch.\n        rewrite H0. crunch. crunch. *) admit.\nAdmitted.\n\nTheorem absEvalSimp2 : forall (e : absExp) (st : state) v x bindings,\n        0 = fst st v ->\n        (absEval (override (fst st) v x) ((NatValue 0)::bindings)\n                 (quantifyAbsVar e 0 0 v)) =\n        (absEval (fst st) bindings e).\nProof. admit.\n    (*induction e using abs_ind'.\n\n    crunch.\n\n    crunch. remember (beq_id id v). destruct b. unfold override. crunch. unfold override. crunch.\n\n    crunch.\n\n    rewrite <- H. reflexivity.\n\n    simpl. unfold override. crunch. crunch. crunch.\n\n    assert (forall (n : nat) (st : state) (v : SfLibExtras.id) (x : nat) bindings,\n        0 = fst st v ->\n        (map (absEval (override (fst st) v x) ((NatValue 0)::bindings))\n                (map (fun x0 : absExp => quantifyAbsVar x0 v) l)) =\n        (map (absEval (fst st) bindings) l)).\n        induction l. crunch.\n        crunch.\n        rewrite IHl. rewrite H1. crunch. crunch. crunch. apply 0. crunch. rewrite H1. crunch. \n        apply 0. crunch.*)\nAdmitted.\n\nTheorem existsEvalDecompose_a :\n    forall e (a : absExp) a0 i bindings,\n    (i = 2 \\/ i = 3 \\/ i = 4 \\/ i = 5 \\/ i = 6 \\/ i = 7 \\/ i = 8) ->\n    (exists x : nat,\n        (absEval e bindings (AbsFun (Id i) (a :: a0 :: nil))) = NatValue x) ->\n    (exists x : nat, (absEval e bindings a)= NatValue x).\nProof.\n    (*crunch.\n\n    unfold supportsBasicFunctionality in H. unfold supportsFunctionality in H.\n    crunch.\n\n    unfold absEval in H2. simpl in H2. fold (@absEval ev eq f) in H2.\n    erewrite H1 in H2. Focus 3. reflexivity. simpl in H2.\n\n    remember (absEval e bindings a). destruct v.\n        apply ex_intro with (x := n). crunch.\n        remember (absEval e bindings a0). destruct v.\n            caseAnalysis;inversion H2.\n            caseAnalysis;inversion H2.\n            caseAnalysis;inversion H2.\n            caseAnalysis;inversion H2.\n            caseAnalysis;inversion H2.\n            caseAnalysis;inversion H2.\n    omega. *)\nAdmitted.\n\nTheorem existsEvalDecompose_b :\n    forall e (a : absExp) a0 i bindings,\n    (i = 2 \\/ i = 3 \\/ i = 4 \\/ i=5 \\/ i=6) ->\n    (exists x : nat,\n        (absEval e bindings (AbsFun (Id i) (a :: a0 :: nil))) = NatValue x) ->\n    (exists x : nat, (absEval e bindings a0)= NatValue x).\nProof.\n    (*crunch.\n\n    unfold supportsBasicFunctionality in H. unfold supportsFunctionality in H.\n    crunch.\n\n    unfold absEval in H2. simpl in H2. fold (@absEval ev eq f) in H2.\n    erewrite H1 in H2. Focus 3. reflexivity. simpl in H2.\n\n    remember (absEval e bindings a0). destruct v.\n        apply ex_intro with (x := n). crunch.\n        remember (absEval e bindings a). destruct v.\n            caseAnalysis;inversion H2.\n            caseAnalysis;inversion H2.\n            caseAnalysis;inversion H2.\n            caseAnalysis;inversion H2.\n        remember (absEval e bindings a). destruct v.\n            caseAnalysis;inversion H2.\n            caseAnalysis;inversion H2.\n            caseAnalysis;inversion H2.\n            caseAnalysis;inversion H2.\n        remember (absEval e bindings a). destruct v.\n            caseAnalysis;inversion H2.\n            caseAnalysis;inversion H2.\n            caseAnalysis;inversion H2.\n            caseAnalysis;inversion H2.\n    omega.*)\n    admit.\nAdmitted.\n\nTheorem existsEvalDecompose :\n    forall e (a : absExp) bindings i,\n    (i = 10) ->\n    (exists x : nat,\n        (absEval e bindings (AbsFun (Id i) (a :: nil))) = NatValue x) ->\n    (exists x : nat, (absEval e bindings a)= NatValue x).\nProof.\n    (*crunch.\n\n    unfold supportsBasicFunctionality in H. unfold supportsFunctionality in H.\n    crunch.\n\n    unfold absEval in H0. simpl in H0. fold (@absEval ev eq f) in H0.\n    erewrite H1 in H0. Focus 3. reflexivity. simpl in H0.\n\n    remember (absEval e bindings a). destruct v.\n    apply ex_intro with (x := n). crunch.\n    inversion H0. inversion H0. inversion H0.\n\n    omega.*)\n    admit.\nAdmitted.\n\n(*Theorem defineWhenKeys {ev} {eq} {f} {t} {ac} {u} :\n    forall (val : absExp) vars e v bindings,\n    supportsBasicFunctionality ev eq f t ac u ->\n    Some vars = keyVariables val ->\n    In v vars ->\n    (exists x, (absEval e bindings val)=(NatValue x)) ->\n    None <> e v.\nProof.\n    induction val using abs_ind'.\n\n    crunch.\n\n    crunch.\n    destruct (e v). crunch. inversion H0. subst.\n\n    crunch.\n\n    crunch.\n\n    destruct id. destruct n. crunch. destruct n. crunch. destruct n. destruct l. crunch.\n    destruct l. crunch. destruct l. remember (keyVariables a). destruct o.\n    remember (keyVariables a0). destruct o. crunch.\n    inversion H2.\n    eapply H1. crunch. crunch. crunch.\n    eapply existsEvalDecompose_a. crunch. Focus 2. apply ex_intro with (x := x). crunch. crunch.\n    eapply H. crunch. crunch. crunch.\n    eapply existsEvalDecompose_b. crunch. Focus 2. apply ex_intro with (x := x). crunch. crunch.\n    crunch. crunch. crunch.\n\n    destruct n. destruct l. crunch. destruct l. crunch. destruct l.\n    remember (keyVariables a). destruct o.\n    remember (keyVariables a0). destruct o. crunch.\n    inversion H2.\n    eapply H1. crunch. crunch. crunch.\n    eapply existsEvalDecompose_a. crunch. Focus 2. apply ex_intro with (x := x). crunch. crunch.\n    eapply H. crunch. crunch. crunch.\n    eapply existsEvalDecompose_b. crunch. Focus 2. apply ex_intro with (x := x). crunch. crunch.\n    crunch. crunch. crunch.\n\n    destruct n. destruct l. crunch. destruct l. crunch. destruct l.\n    remember (keyVariables a). destruct o.\n    remember (keyVariables a0). destruct o. crunch.\n    inversion H2.\n    eapply H1. crunch. crunch. crunch.\n    eapply existsEvalDecompose_a. crunch. Focus 2. apply ex_intro with (x := x). crunch. right. crunch.\n    eapply H. crunch. crunch. crunch.\n    eapply existsEvalDecompose_b. crunch. Focus 2. apply ex_intro with (x := x). crunch. right. crunch.\n    crunch. crunch. crunch.\n\n    destruct n. destruct l. crunch. destruct l. crunch. destruct l.\n    remember (keyVariables a). destruct o.\n    remember (keyVariables a0). destruct o. crunch.\n    inversion H2.\n    eapply H1. crunch. crunch. crunch.\n    eapply existsEvalDecompose_a. crunch. Focus 2. apply ex_intro with (x := x). crunch. right. right. crunch.\n    eapply H. crunch. crunch. crunch.\n    eapply existsEvalDecompose_b. crunch. Focus 2. apply ex_intro with (x := x). crunch. right. right. crunch.\n\n    remember (keyVariables a). destruct o.\n    remember (keyVariables a0). destruct o. crunch. inversion H. subst. clear H. inversion H5. subst. clear H5.\n    eapply H3. crunch. crunch. crunch.\n    eapply existsEvalDecompose_a. crunch. Focus 2. apply ex_intro with (x := x). crunch. right. right. crunch.\n    crunch.\n\n    remember (keyVariables a0). destruct o. crunch.\n    eapply H. crunch. crunch. crunch.\n    eapply existsEvalDecompose_b. crunch. Focus 2. apply ex_intro with (x := x). crunch. right. right. crunch.\n    crunch. crunch.\n\n    destruct n. destruct l. crunch. destruct l. crunch. destruct l.\n    remember (keyVariables a). destruct o.\n    remember (keyVariables a0). destruct o. crunch.\n    inversion H2.\n    eapply H1. crunch. crunch. crunch.\n    eapply existsEvalDecompose_a. crunch. Focus 2. apply ex_intro with (x := x). crunch. right. right. right. crunch.\n    eapply H. crunch. crunch. crunch.\n    eapply existsEvalDecompose_b. crunch. Focus 2. apply ex_intro with (x := x). crunch. right. right. right. crunch.\n    crunch. crunch. crunch.\n\n    destruct n. destruct l. crunch. destruct l. crunch. destruct l.\n    crunch.\n    eapply H3. crunch. crunch. crunch.\n    eapply existsEvalDecompose_a. crunch. Focus 2. apply ex_intro with (x := x). crunch. right. right. right. right. crunch.\n    crunch.\n\n    destruct n. destruct l. crunch. destruct l. crunch. destruct l.\n    crunch.\n    eapply H3. crunch. crunch. crunch.\n    eapply existsEvalDecompose_a. crunch. Focus 2. apply ex_intro with (x := x). crunch. right. right. right. right. right. crunch.\n    crunch.\n\n    destruct n. crunch. destruct n. destruct l. crunch. destruct l. crunch.\n    eapply H3. crunch. crunch. crunch.\n    eapply existsEvalDecompose. crunch. Focus 2. apply ex_intro with (x := x). crunch.\n    crunch.\n    crunch. crunch. crunch.\nQed.\n\nTheorem is_kv_thm : forall l v, is_kv v l = true -> In v l.\nProof.\n    induction l.\n    intros. inversion H.\n    intros. unfold is_kv in H. remember (beq_id v a). destruct b. eapply beq_id_eq in Heqb.\n    subst. simpl. left. reflexivity. simpl. right. eapply IHl. fold is_kv in H. crunch.\nQed.\n\nTheorem validEval {ev} {eq} {f} {t} {ac} {u} :\n        forall a v e x bindings,\n               supportsBasicFunctionality ev eq f t ac u ->\n               @absEval ev eq f e bindings a = @NatValue ev x ->\n               is_key_variable v (keyVariables a)=true ->\n               (None <> e v).\nProof.\n    intros.\n\n    remember (keyVariables a).  destruct o. eapply defineWhenKeys.\n    crunch. eapply Heqo. inversion H1. apply is_kv_thm. crunch.\n    eapply ex_intro. apply H0. inversion H1.\nQed.*)\n\n(*Theorem validHasAssignBasic {ev} {eq} {f} {t} {ac} {u} :\n        forall (P : @absState ev eq f t ac) v vars e h,\n               supportsBasicFunctionality ev eq f t ac u ->\n               realizeState P vars (e,h) ->\n               basicVarAssigned P v = true ->\n               (None <> e v).\nProof. adxxxmit.\n    induction P.\n\n    crunch. inversion H0. subst. clear H0. crunch. eapply IHP. crunch. crunch. crunch.\n\n    crunch. inversion H0. subst. clear H0. crunch. eapply IHP. crunch. crunch. crunch.\n\n    crunch.\n\n    crunch.\n\n    crunch. inversion H0. subst. clear H0. remember (basicVarAssigned P1 v).\n        destruct b. inversion H8. crunch. destruct s1. destruct s2. crunch.\n        eapply IHP1. crunch. crunch. crunch.\n        destruct s1. destruct s2. crunch. inversion H8. crunch. eapply IHP2. crunch. crunch.\n        crunch.\n\n    crunch.\n\n    crunch. inversion H. crunch.\n    inversion H1. subst. clear H1.\n    destruct i. destruct n. crunch. destruct n. crunch. destruct l. crunch. destruct l.\n    inversion H0. subst. clear H0.\n    eapply H5 in H13. 2:crunch. 2:crunch. inversion H13.\n    remember (absEval e vars a). destruct v0.\n    eapply validEval. crunch. instantiate (1 := n). rewrite Heqv0. reflexivity. crunch.\n    inversion H0. inversion H0. inversion H0. inversion H9.\n\n    destruct n. destruct l. crunch. inversion H0. subst. clear H0.\n    crunch. eapply H5 in H13. 2:crunch. 2:crunch. inversion H13. subst. clear H13.\n    destruct a. inversion H9. inversion H9. subst. clear H9.\n    remember (beq_id i v). destruct b. eapply beq_id_eq in Heqb. subst.\n    inversion H0. destruct (e v). crunch. inversion H11. crunch.\n    inversion H9. inversion H9.\n\n    destruct n. destruct l. crunch. destruct l. crunch. destruct l.\n\n    inversion H0. subst. clear H0. eapply H5 in H13. 2:crunch. 2:crunch.\n    inversion H13. subst. clear H13.\n\n    destruct a. inversion H9. subst. clear H9.\n\n        destruct a0. inversion H13. inversion H13. remember (beq_id i v). destruct b.\n        eapply beq_id_eq in Heqb. subst. inversion H1. destruct (e v). crunch.\n        inversion H14. crunch. inversion H13. inversion H13.\n\n        crunch. remember (beq_id i v). destruct b. eapply beq_id_eq in Heqb. subst.\n        destruct (e v). crunch. inversion H0.\n        destruct a0. inversion H9. inversion H9. remember (beq_id i0 v). destruct b.\n        eapply beq_id_eq in Heqb0. subst. inversion H1. destruct (e v). crunch.\n        inversion H14. crunch. inversion H9. inversion H9.\n\n        inversion H9.\n        destruct a0. inversion H13. inversion H13. remember (beq_id i v). destruct b.\n        eapply beq_id_eq in Heqb. subst. inversion H1. destruct (e v). crunch.\n        inversion H15. crunch. inversion H13. inversion H13.\n\n        inversion H9. subst. clear H9.\n        destruct a0. inversion H13. inversion H13. remember (beq_id i0 v). destruct b.\n        eapply beq_id_eq in Heqb. subst. inversion H1. destruct (e v). crunch.\n        inversion H14. crunch. inversion H13. inversion H13.\n\n        crunch. crunch. crunch.\n\n    intros. inversion H0.\nQed.*)\n\n(*Theorem validPickElement {ev} {eq} {f} {t} {ac} {u} :\n    forall (s : @absState ev eq f t ac) st v val xx vars bindings,\n    supportsBasicFunctionality ev eq f t ac u ->\n    realizeState s bindings st ->\n    spickElement s ([val]) xx ->\n    Some vars = keyVariables val ->\n    In v vars ->\n    None <> fst st v.\nProof. admxxit.\n    crunch.\n\n    destruct st.\n\n    assert (forall (s : @absState ev eq f t ac) xx p,\n            spickElement s p xx ->\n            p = ([val]) ->\n            (exists h, realizeState s bindings (e, h)) ->\n            In v vars ->\n            None <> e v).\n    intros. induction H4.\n\n        apply IHspickElement. crunch.\n\n        crunch. inversion H5. subst. clear H5.\n        unfold concreteCompose in H13. destruct s1. destruct s2. crunch.\n        apply ex_intro with (x := h0). crunch.\n\n        apply IHspickElement. crunch.\n\n        crunch. inversion H5. subst. clear H5.\n        unfold concreteCompose in H13. destruct s1. destruct s2. crunch.\n        apply ex_intro with (x := h1). crunch.\n\n        inversion H5.\n\n        crunch. inversion H4. subst. clear H4.\n\n        inversion H. crunch.\n\n        destruct i. eapply H9 in H12. Focus 2. crunch.\n\n        crunch. inversion H5. subst. clear H5. inversion H12. subst. clear H12. crunch.\n\n        eapply defineWhenKeys. crunch. crunch. crunch.\n        apply ex_intro with (x := e0).\n            remember (@absEval ev eq f e bindings val). destruct v0.\n            crunch. inversion H5. subst. rewrite Heqv0. reflexivity.\n            inversion H5. inversion H5. inversion H5.\n\n        inversion H5. omega. inversion H5.\n\n    crunch. eapply H4. crunch. crunch. eapply ex_intro. crunch. crunch.\nQed.*)\n\n(*Theorem validHasAssign1 {ev} {eq} {f} {t} {ac} {u} :\n    forall st v (P: @absState ev eq f t ac) bindings,\n        supportsBasicFunctionality ev eq f t ac u ->\n        realizeState P bindings st ->\n        varAssigned P v ->\n        None <> fst st v.\nProof.\n    crunch.\n\n    induction H1.\n\n    destruct st.\n    eapply validHasAssignBasic. crunch. crunch. crunch.\n    admxxit. * Note that this is special case that is only meaningful if VarAssignedPredicate1\n              is used in validating the application of the assign tactic *\nQed.*)\n(*    eapply validPickElement. crunch. crunch. crunch. rewrite H2. crunch. crunch.\nQed.*)\n\nTheorem validKeyVariablesSubterm :\n    forall ff x l, keyVariables (AbsFun ff l)<>None ->\n                   ff <> AbsMemberId -> ff <> AbsIncludeId ->\n                   In x l -> keyVariables x<>None.\nProof. admit.\n    (*crunch.\n\n    destruct ff. destruct n. crunch. destruct n. crunch.\n    destruct n. destruct l. crunch. destruct l. crunch.\n    destruct l.\n\n    remember (keyVariables a). destruct o. remember (keyVariables a0).\n    destruct o. inversion H2. subst. clear H2. rewrite <- Heqo. crunch.\n    inversion H3. subst. clear H3. rewrite <- Heqo0. crunch. inversion H4.\n\n    crunch. crunch. crunch.\n\n    destruct n. destruct l. crunch.  destruct l. crunch.\n    destruct l.\n\n    remember (keyVariables a). destruct o. remember (keyVariables a0).\n    destruct o. inversion H2. subst. clear H2. rewrite <- Heqo. crunch.\n    inversion H3. subst. clear H3. rewrite <- Heqo0. crunch. inversion H4.\n\n    crunch. crunch. crunch.\n\n    destruct n. destruct l. crunch.  destruct l. crunch.\n    destruct l.\n\n    remember (keyVariables a). destruct o. remember (keyVariables a0).\n    destruct o. inversion H2. subst. clear H2. rewrite <- Heqo. crunch.\n    inversion H3. subst. clear H3. rewrite <- Heqo0. crunch. inversion H4.\n\n    crunch. crunch. crunch.\n\n    destruct n. destruct l. crunch.  destruct l. crunch.\n    destruct l.\n\n    remember (keyVariables a). destruct o. remember (keyVariables a0).\n    destruct o. inversion H2. subst. clear H2. rewrite <- Heqo. crunch.\n    inversion H3. subst. clear H3. rewrite <- Heqo0. crunch. inversion H4.\n\n    crunch. crunch. crunch.\n\n    destruct n. destruct l. crunch.  destruct l. crunch.\n    destruct l.\n\n    remember (keyVariables a). destruct o. remember (keyVariables a0).\n    destruct o. inversion H2. subst. clear H2. rewrite <- Heqo. crunch.\n    inversion H3. subst. clear H3. rewrite <- Heqo0. crunch. inversion H4.\n\n    crunch. crunch. crunch.\n\n    destruct n. destruct l. elim H. reflexivity.  destruct l. crunch.\n    destruct l.\n\n    crunch. crunch.\n\n    destruct n. crunch.\n\n    destruct n. crunch. destruct n. destruct l. crunch.\n\n    destruct l. inversion H2. subst. apply H. crunch.\n\n    crunch. crunch. crunch.*)\nAdmitted.\n\nTheorem keyVariablesSubset :\n    forall ff x l v vars1 vars2, In x l ->\n                                 keyVariables (AbsFun ff l) = Some vars1 ->\n                                 ff <> AbsMemberId -> ff <> AbsIncludeId ->\n                                 keyVariables x = Some vars2 -> In v vars2 -> In v vars1.\nProof. admit.\n    (*crunch.\n    destruct ff. destruct n. crunch. destruct n. crunch. destruct n.\n\n    destruct l. crunch. destruct l. crunch. destruct l.\n\n    remember (keyVariables a). destruct o. remember (keyVariables a0).\n    destruct o. crunch. inversion H. subst. rewrite <- Heqo in H3. crunch.\n    crunch. crunch. crunch. crunch.\n\n    destruct n. destruct l. crunch. destruct l. crunch. destruct l.\n\n    remember (keyVariables a). destruct o. remember (keyVariables a0).\n    destruct o. crunch. inversion H. subst. rewrite <- Heqo in H3. crunch.\n    crunch. crunch. crunch. crunch.\n\n    destruct n. destruct l. crunch. destruct l. crunch. destruct l.\n\n    remember (keyVariables a). destruct o. remember (keyVariables a0).\n    destruct o. crunch. inversion H. subst. rewrite <- Heqo in H3. crunch.\n    crunch. crunch. crunch. crunch.\n\n    destruct n. destruct l. crunch. destruct l. crunch. destruct l.\n\n    remember (keyVariables a). destruct o. remember (keyVariables a0).\n    destruct o. crunch. inversion H. subst. rewrite <- Heqo in H3. crunch.\n    crunch. crunch. crunch. crunch.\n\n    destruct n. destruct l. crunch. destruct l. crunch. destruct l.\n\n    remember (keyVariables a). destruct o. remember (keyVariables a0).\n    destruct o. crunch. inversion H. subst. rewrite <- Heqo in H3. crunch.\n    crunch. crunch. crunch. crunch.\n\n    destruct n. destruct l. crunch. destruct l. crunch. destruct l.\n\n    remember (keyVariables a). destruct o. remember (keyVariables a0).\n    destruct o. crunch. inversion H. subst. rewrite <- Heqo in H3. crunch.\n    crunch. crunch. crunch. crunch.\n\n    destruct n. destruct l. crunch. destruct l. crunch. destruct l.\n\n    crunch. crunch.\n\n    destruct n.\n\n    crunch.\n\n    destruct n. crunch. destruct l. crunch. destruct l.\n    inversion H. subst. clear H. rewrite H3 in H0. crunch. crunch. crunch.\n    crunch. crunch.*)\nAdmitted.\n\nTheorem validExpressionProp :\n    forall (P : absState) i l x,\n        In x l ->\n        i<>AbsMemberId -> i<>AbsIncludeId ->\n        validExpression P (AbsFun i l) ->\n        validExpression P x.\nProof.\n    (*crunch. unfold validExpression in H2.\n    unfold validExpression. intros. split.\n    eapply validKeyVariablesSubterm.\n        apply H2. apply (Id 0). crunch apply nil. crunch?\n    crunch. crunch. crunch.\n\n    remember (keyVariables (AbsFun i l)). destruct o. \n    intros. eapply H2. reflexivity.\n    eapply keyVariablesSubset. crunch. rewrite Heqo. reflexivity.\n    crunch. crunch. rewrite <- H3. reflexivity. crunch.\n    assert (@None (list id) <> None). eapply H2. apply x0. apply vars. crunch\n    elim H3. reflexivity.*) admit.\nAdmitted. (* Crunch problems *)\n\n(*Theorem validHasAssign {ev} {eq} {f} {t} {ac} {u} :\n    forall st v (P: @absState ev eq f t ac) bindings,\n        supportsBasicFunctionality ev eq f t ac u ->\n        realizeState P bindings st ->\n        validExpression P (!!v) ->\n        None <> fst st v.\nProof.\n    unfold validExpression. intros. eapply validHasAssign1.\n    crunch. crunch. eapply H1.\n    unfold keyVariables. crunch. crunch.\nQed.*)\n\nFixpoint noMemberExpression (e : absExp) :=\n    match e with\n    | AbsFun x l => (x <> AbsMemberId /\\ x <> AbsIncludeId /\\\n                     (fold_right (fun x y => x /\\ y) True (map noMemberExpression l)))\n    | _ => True\n    end.\n\n(*Theorem noMemberPropagate {ev} {eq} {f} :\n        forall ff l x, noMemberExpression (@AbsFun ev eq f ff l) -> In x l ->\n                       noMemberExpression x.\nProof.\n    induction l.\n\n    crunch.\n\n    crunch.\n        inversion H0. crunch.\n\n        eapply IHl. crunch. crunch.\nQed.*)\n\n(*Theorem absEvalSimp2 {ev} {eq} {f} {t} {ac} {u} :\n                     forall y (st : state) v x (e : absExp)\n                            (P : @absState ev eq f t ac) bindings,\n        supportsBasicFunctionality ev eq f t ac u ->\n        None = fst st v ->\n        realizeState P bindings st ->\n        validExpression P e ->\n        noMemberExpression e ->\n        (absEval (override (fst st) v x) (y::bindings)\n                 (quantifyAbsVar e v)) =\n        (absEval (fst st) bindings e).\nProof.\n    induction e using abs_ind'.\n\n    crunch.\n\n    crunch.\n    remember (beq_id id v). destruct b. apply beq_id_eq in Heqb. subst. crunch.\n        crunch.\n        assert (None <> fst st v). eapply validHasAssign.\n        crunch. crunch. crunch. rewrite H0 in H4. *crunch* crunch.\n        intros.\n        crunch. unfold override. rewrite beq_id_comm. rewrite <- Heqb. crunch.\n\n    crunch.\n\n    intros. unfold quantifyAbsVar. fold (@quantifyAbsVar ev eq f).\n    unfold instantiateExp. fold (@instantiateExp ev eq f).\n\n    simpl.\n\n    assert (forall (l : list absExp), (map (absEval (override (fst st) v x) (y::bindings))\n        (map (fun x0 : absExp => quantifyAbsVar x0 v) l))=\n         (map (fun x0 => absEval (override (fst st) v x) (y::bindings) (quantifyAbsVar x0 v)) l)).\n        crunch.\n        induction l0.\n            crunch.\n\n            crunch. rewrite IHl0. crunch.\n\n    rewrite H5.\n\n    assert (forall x, In x l -> noMemberExpression x).\n        intros. eapply noMemberPropagate. crunch. crunch. \n    assert (forall (e : absExp), In e l ->\n        (absEval (override (fst st) v x) (y::bindings)\n                 (quantifyAbsVar e v)) =\n        (absEval (fst st) bindings e)). crunch.\n        eapply reduceAll in H. Focus 2. crunch.\n        erewrite H with (P := P) (bindings := bindings). crunch. crunch. crunch. crunch.\n        eapply validExpressionProp. crunch. crunch. crunch. crunch. apply H6. crunch.\n\n    assert (forall ll, subset ll l -> (map\n     (fun x0 : absExp =>\n      absEval (override (fst st) v x) (y::bindings)\n        (quantifyAbsVar x0 v)) ll) =\n     (map (absEval (fst st) bindings) ll)).\n\n        induction ll. crunch.\n\n        unfold subset. fold (@subset absExp). crunch.\n        rewrite H7. rewrite IHll. crunch. crunch. crunch.\n\n    rewrite H8. reflexivity.\n\n    assert (forall t (x : list t), x = (nil++x)).\n        crunch.\n    rewrite H9. apply subsetAppend.\nQed.*)\n\n(*Theorem absEvalHasNatValue {ev} {eq} {f} {t} {ac} {u} :\n                        forall e (st : state) bindings\n                               (P : @absState ev eq f t ac),\n        supportsBasicFunctionality ev eq f t ac u ->\n        validExpression P e ->\n        realizeState P bindings st ->\n        (exists x, NatValue x = (absEval (fst st) bindings e)).\nProof.\n    adxmit.\nQed.*)\n\nTheorem absEvalAeval :\n                        forall e (st : state) bindings,\n        (NatValue (aeval st e)) =\n        (absEval (fst st) bindings (convertToAbsExp e)).\nProof.\n    admit.\n    (*induction e.\n\n    crunch. intros. simpl. reflexivity.\n\n    crunch.\n    inversion H.\n    crunch. erewrite H0. 3:reflexivity.\n    erewrite <- IHe1. erewrite <- IHe2. crunch. crunch. crunch. crunch.\n\n    crunch.\n    inversion H.\n    crunch. erewrite H0. 3:reflexivity.\n    erewrite <- IHe1. erewrite <- IHe2. crunch. crunch. crunch. crunch.\n\n    crunch.\n    inversion H.\n    crunch. erewrite H0. 3:reflexivity.\n    erewrite <- IHe1. erewrite <- IHe2. crunch. crunch. crunch. crunch.\n\n    crunch.\n    inversion H.\n    crunch. erewrite H0. 3:reflexivity.\n    erewrite <- IHe1. erewrite <- IHe2.\n    crunch. crunch.\n    unfold basicEval. destruct (beq_nat (aeval st e1) (aeval st e2)). crunch. crunch.\n    crunch. crunch. crunch.\n\n    crunch.\n    inversion H.\n    crunch. erewrite H0. 3:reflexivity.\n    erewrite H0. 3:reflexivity.\n    erewrite <- IHe1. erewrite <- IHe2. unfold basicEval. simpl.\n       destruct (ble_nat (aeval st e1) (aeval st e2)). crunch. crunch. crunch. crunch. crunch.\n       crunch.\n\n    crunch.\n    inversion H.\n    crunch. erewrite H0. 3:reflexivity.\n    erewrite <- IHe1. erewrite <- IHe2. crunch.\n    unfold basicEval. destruct (beq_nat (aeval st e1) 0). crunch. crunch.\n    crunch. crunch. crunch.\n\n    crunch.\n    inversion H.\n    crunch. erewrite H0. 3:reflexivity.\n    erewrite <- IHe1. erewrite <- IHe2. crunch.\n    unfold basicEval. destruct (beq_nat (aeval st e1) 0). crunch. crunch. crunch. crunch.\n        crunch.\n\n    crunch.\n    inversion H.\n    crunch. erewrite H0. 3:reflexivity.\n    erewrite <- IHe. crunch.\n    unfold basicEval. destruct (beq_nat (aeval st e) 0). crunch. crunch.\n    crunch. crunch.*)\nAdmitted.\n\nTheorem absPredicateCompose :\n    forall P p state bindings,\n    realizeState P bindings state ->\n    realizeState (AbsLeaf AbsPredicateId (p::nil)) bindings (fst state,empty_heap) ->\n    realizeState (AbsStar ([p]) P) bindings state.\nProof.\n    (*crunch. inversion H. crunch. inversion H1. subst. eapply H5 in H13.\n    2:crunch. crunch. inversion H13. subst. clear H13. crunch.\n    eapply RSCompose. crunch. crunch. unfold concreteCompose. crunch.\n    left. unfold empty_heap. crunch. crunch.*) admit.\nAdmitted.\n\n(*Theorem validExpressionValue {ev} {eq} {f} {t : id -> list (@Value ev) -> heap -> Prop} {ac} {u} :\n        forall e (P : @absState ev eq f t ac) st bindings,\n        supportsBasicFunctionality ev eq f t ac u ->\n        validExpression P e ->\n        realizeState P bindings st ->\n        (exists x, absEval (fst st) bindings e=NatValue x).\nProof.\n    induction e using abs_ind'.\n\n    crunch. unfold validExpression in H0. crunch. destruct c. eapply ex_intro. crunch.\n        crunch. assert (@None (list id) <> None). apply H0. apply (Id 0). apply nil. crunch.\n        crunch. assert (@None (list id) <> None). apply H0. apply (Id 0). apply nil. crunch.\n        crunch. assert (@None (list id) <> None). apply H0. apply (Id 0). apply nil. crunch.\n\n    crunch. unfold validExpression in H0. crunch.\n    assert (None <> fst st id). eapply validHasAssign1.\n        crunch. crunch. eapply H0. crunch. crunch.\n    remember (fst st id). destruct o. apply ex_intro with (x := n). crunch.\n    elim H2. crunch.\n\n    crunch. unfold validExpression in H0. unfold keyVariables in H0.\n    assert (@None (list id) <> None).\n    apply H0. apply (Id 0). apply nil. crunch.\n\n    crunch. remember H1. clear Heqv.\n    unfold validExpression in H1. unfold keyVariables in H1. fold (@keyVariables ev eq f) in H1.\n\n    destruct id. destruct n.\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    destruct n.\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    destruct n. destruct l.\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    destruct l.\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    destruct l.\n\n    crunch. inversion H0. crunch. erewrite H4. 3:crunch.\n    assert (exists x, absEval (fst st) bindings a = NatValue x).\n        eapply H3. crunch. crunch. crunch. eapply validExpressionProp. 4:apply v.\n        crunch. intro X. inversion X. *crunch* intro X. inversion X. crunch.\n    assert (exists x, absEval (fst st) bindings a0 = NatValue x).\n        eapply H. crunch. crunch. crunch. eapply validExpressionProp. 4:apply v.\n        crunch. intro X. inversion X. *crunch* intro X. inversion X. crunch.\n    crunch. rewrite H13. rewrite H12.\n    crunch. eapply ex_intro. crunch. crunch.\n\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    destruct n. destruct l.\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    destruct l.\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    destruct l.\n\n    crunch. inversion H0. crunch. erewrite H4. 3:crunch.\n    assert (exists x, absEval (fst st) bindings a = NatValue x).\n        eapply H3. crunch. crunch. crunch. eapply validExpressionProp. 4:apply v.\n        crunch. intro X. inversion X. *crunch* intro X. inversion X. crunch.\n    assert (exists x, absEval (fst st) bindings a0 = NatValue x).\n        eapply H. crunch. crunch. crunch. eapply validExpressionProp. 4:apply v.\n        crunch. intro X. inversion X. *crunch* intro X. inversion X. crunch.\n    crunch. rewrite H13. rewrite H12.\n    crunch. eapply ex_intro. crunch. crunch.\n\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    destruct n. destruct l.\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    destruct l.\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    destruct l.\n\n    crunch. inversion H0. crunch. erewrite H4. 3:crunch.\n    assert (exists x, absEval (fst st) bindings a = NatValue x).\n        eapply H3. crunch. crunch. crunch. eapply validExpressionProp. 4:apply v.\n        crunch. intro X. inversion X. *crunch* intro X. inversion X. crunch.\n    assert (exists x, absEval (fst st) bindings a0 = NatValue x).\n        eapply H. crunch. crunch. crunch. eapply validExpressionProp. 4:apply v.\n        crunch. intro X. inversion X. *crunch* intro X. inversion X. crunch.\n    crunch. rewrite H13. rewrite H12.\n    crunch. eapply ex_intro. crunch. crunch.\n\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    destruct n. destruct l.\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    destruct l.\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    destruct l.\n\n    crunch. inversion H0. crunch. erewrite H4. 3:crunch.\n    assert (exists x, absEval (fst st) bindings a = NatValue x).\n        eapply H3. crunch. crunch. crunch. eapply validExpressionProp. 4:apply v.\n        crunch. intro X. inversion X. *crunch* intro X. inversion X. crunch.\n    assert (exists x, absEval (fst st) bindings a0 = NatValue x).\n        eapply H. crunch. crunch. crunch. eapply validExpressionProp. 4:apply v.\n        crunch. intro X. inversion X. *crunch* intro X. inversion X. crunch.\n    crunch. rewrite H13. rewrite H12.\n    crunch. unfold basicEval. destruct (beq_nat x0 x). eapply ex_intro. crunch. eapply ex_intro. crunch. crunch.\n\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    destruct n. destruct l.\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    destruct l.\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    destruct l.\n\n    crunch. inversion H0. crunch. erewrite H4. 3:crunch.\n    assert (exists x, absEval (fst st) bindings a = NatValue x).\n        eapply H3. crunch. crunch. crunch. eapply validExpressionProp. 4:apply v.\n        crunch. intro X. inversion X. *crunch* intro X. inversion X. crunch.\n    assert (exists x, absEval (fst st) bindings a0 = NatValue x).\n        eapply H. crunch. crunch. crunch. eapply validExpressionProp. 4:apply v.\n        crunch. intro X. inversion X. *crunch* intro X. inversion X. crunch.\n    crunch. rewrite H13. rewrite H12.\n    crunch. unfold basicEval. destruct (ble_nat x x0). eapply ex_intro. crunch. eapply ex_intro. crunch. crunch.\n\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    destruct n. destruct l.\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    destruct l.\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    destruct l.\n\n    crunch. inversion H0. crunch. erewrite H4. 3:crunch.\n    assert (exists x, absEval (fst st) bindings a = NatValue x).\n        eapply H3. crunch. crunch. crunch.\n    crunch. rewrite H12. crunch. unfold basicEval.\n    destruct (Rmember x\n          (convertAbsValue (fun _ : ev => tt) (absEval (fst st) bindings a0))).\n    eapply ex_intro. crunch. eapply ex_intro. crunch. crunch.\n\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    destruct n. destruct l.\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    destruct l.\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    destruct l.\n\n    crunch. inversion H0. crunch. erewrite H4. 3:crunch.\n    assert (exists x, absEval (fst st) bindings a = NatValue x).\n        eapply H3. crunch. crunch. crunch.\n    crunch. rewrite H12. crunch. unfold basicEval.\n    destruct (Rinclude x\n          (convertAbsValue (fun _ : ev => tt) (absEval (fst st) bindings a0))).\n    eapply ex_intro. crunch. eapply ex_intro. crunch. crunch.\n\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    destruct n.\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    destruct n. destruct l.\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    destruct l.\n\n    crunch. inversion H0. crunch. erewrite H. 3:crunch.\n    assert (exists x, absEval (fst st) bindings a = NatValue x).\n        eapply H3. crunch. crunch. crunch.\n    crunch. rewrite H11. crunch. unfold basicEval.\n    destruct (beq_nat x 0).\n    eapply ex_intro. crunch. eapply ex_intro. crunch. crunch.\n\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\n    assert (@None (list id) <> None). apply H1. apply (Id 0). apply nil. crunch.\nQed.*)\n\nTheorem noMemberTheorem : forall e, noMemberExpression (convertToAbsExp e).\nProof.\n    induction e.\n\n    crunch. crunch. crunch. intro X. inversion X. (*crunch*) intro X. inversion X.\n    crunch. intro X. inversion X. intro X. inversion X.\n    crunch. intro X. inversion X. intro X. inversion X.\n    crunch. intro X. inversion X. intro X. inversion X.\n    crunch. intro X. inversion X. intro X. inversion X.\n    crunch. intro X. inversion X. intro X. inversion X.\n    crunch. intro X. inversion X. intro X. inversion X.\n    crunch. intro X. inversion X. intro X. inversion X.\n    crunch. intro X. inversion X. intro X. inversion X.\nQed.\n\nTheorem validExpressionValue :\n    forall e env b, exists x, absEval env b (convertToAbsExp e)=NatValue x.\nProof.\n    (*induction e.\n\n    intros. eapply ex_intro. simpl. reflexivity.\n\n    intros. simpl. destruct (env i). eapply ex_intro. reflexivity. eapply ex_intro. reflexivity.\n\n    intros. simpl. inversion x. erewrite H. 3:reflexivity. 2:omega.\n    assert (exists x : nat, absEval env b (convertToAbsExp e1) = NatValue x).\n    eapply IHe1. \n    assert (exists x : nat, absEval env b (convertToAbsExp e2) = NatValue x).\n    eapply IHe2.\n    inversion H1. subst. clear H1. inversion H2. subst. clear H2. rewrite H1. rewrite H3.\n        simpl. eapply ex_intro. reflexivity.\n\n    intros. simpl. inversion x. erewrite H. 3:reflexivity. 2:omega.\n    assert (exists x : nat, absEval env b (convertToAbsExp e1) = NatValue x).\n    eapply IHe1. \n    assert (exists x : nat, absEval env b (convertToAbsExp e2) = NatValue x).\n    eapply IHe2.\n    inversion H1. subst. clear H1. inversion H2. subst. clear H2. rewrite H1. rewrite H3.\n        simpl. eapply ex_intro. reflexivity.\n\n    intros. simpl. inversion x. erewrite H. 3:reflexivity. 2:omega.\n    assert (exists x : nat, absEval env b (convertToAbsExp e1) = NatValue x).\n    eapply IHe1. \n    assert (exists x : nat, absEval env b (convertToAbsExp e2) = NatValue x).\n    eapply IHe2.\n    inversion H1. subst. clear H1. inversion H2. subst. clear H2. rewrite H1. rewrite H3.\n        simpl. eapply ex_intro. reflexivity.\n\n    intros. simpl. inversion x. erewrite H. 3:reflexivity. 2:omega.\n    assert (exists x : nat, absEval env b (convertToAbsExp e1) = NatValue x).\n    eapply IHe1. \n    assert (exists x : nat, absEval env b (convertToAbsExp e2) = NatValue x).\n    eapply IHe2.\n    inversion H1. subst. clear H1. inversion H2. subst. clear H2. rewrite H1. rewrite H3.\n        simpl. unfold basicEval. remember (beq_nat x0 x1). destruct b0.\n        eapply ex_intro. reflexivity. eapply ex_intro. reflexivity.\n\n    intros. simpl. inversion x. erewrite H. 3:reflexivity. 2:omega. erewrite H. 3:reflexivity. 2:omega.\n    assert (exists x : nat, absEval env b (convertToAbsExp e1) = NatValue x).\n    eapply IHe1. \n    assert (exists x : nat, absEval env b (convertToAbsExp e2) = NatValue x).\n    eapply IHe2.\n    inversion H1. subst. clear H1. inversion H2. subst. clear H2. rewrite H1. rewrite H3.\n        simpl. unfold basicEval. remember (ble_nat x0 x1). destruct b0.\n        simpl. eapply ex_intro. reflexivity. simpl. eapply ex_intro. reflexivity.\n\n    intros. simpl. inversion x. erewrite H. 3:reflexivity. 2:omega.\n    assert (exists x : nat, absEval env b (convertToAbsExp e1) = NatValue x).\n    eapply IHe1. \n    assert (exists x : nat, absEval env b (convertToAbsExp e2) = NatValue x).\n    eapply IHe2.\n    inversion H1. subst. clear H1. inversion H2. subst. clear H2. rewrite H1. rewrite H3.\n        simpl. unfold basicEval. remember (beq_nat x0 0). destruct b0.\n        simpl. eapply ex_intro. reflexivity. simpl. eapply ex_intro. reflexivity.\n\n    intros. simpl. inversion x. erewrite H. 3:reflexivity. 2:omega.\n    assert (exists x : nat, absEval env b (convertToAbsExp e1) = NatValue x).\n    eapply IHe1. \n    assert (exists x : nat, absEval env b (convertToAbsExp e2) = NatValue x).\n    eapply IHe2.\n    inversion H1. subst. clear H1. inversion H2. subst. clear H2. rewrite H1. rewrite H3.\n        simpl. unfold basicEval. remember (beq_nat x0 0). destruct b0.\n        simpl. eapply ex_intro. reflexivity. simpl. eapply ex_intro. reflexivity.\n\n    intros. simpl. inversion x. erewrite H. 3:reflexivity. 2:omega.\n    assert (exists x : nat, absEval env b (convertToAbsExp e) = NatValue x).\n    eapply IHe. \n    inversion H1. subst. clear H1. rewrite H2.\n        simpl. unfold basicEval. remember (beq_nat x0 0). destruct b0.\n        simpl. eapply ex_intro. reflexivity. simpl. eapply ex_intro. reflexivity.*)\n    admit.\nAdmitted.\n\nTheorem assign  :\n    forall P v e Q,\n        Q = (AbsUpdateVar P v (convertToAbsExp e)) ->\n        {{ P }} v ::= e {{ Q return (#0::nil) with AbsNone }}.\nProof. admit.\n    (*crunch. unfold hoare_triple. unfold absExecute. crunch.\n    eapply ex_intro. eapply ex_intro.\n    eapply CEAss.\n    crunch.\n    inversion H0. subst. clear H0.\n\n    eapply RSExistsU. eapply ex_intro. crunch.\n    eapply absPredicateCompose. crunch.\n    eapply quantify1. crunch. crunch.\n    eapply RSR. crunch.\n\n    inversion x. crunch. eapply H1. instantiate (1 := ((NatValue 1)::nil)).\n    Focus 2.\n    assert (forall s x y, override s x y x = y).\n    unfold override. crunch. rewrite <- beq_id_refl. crunch.\n    rewrite H5.\n\n    erewrite H0. Focus 3. crunch.\n    erewrite absEvalSimp.\n    assert (exists x, (absEval (fst st) nil (@convertToAbsExp ev eq f e)=@NatValue ev x)).\n    eapply validExpressionValue. inversion H7. subst. clear H7.\n    simpl. unfold basicEval.\n    remember (absEval (fst st) nil (convertToAbsExp e)).\n    destruct v0. simpl.\n    remember (beq_nat (aeval st e) n). destruct b. reflexivity.\n    inversion H8. subst. clear H8.\n        crunch. erewrite <- absEvalAeval in Heqv0. inversion Heqv0.  subst.\n        rewrite <- beq_nat_refl in Heqb. inversion Heqb.\n\n    apply x.\n    inversion H8. inversion H8. inversion H8.\n    reflexivity. omega.\n    apply Heqo.\n\n    simpl.\n    assert (exists x, (absEval (fst st) nil (@convertToAbsExp ev eq f e)=@NatValue ev x)).\n    eapply validExpressionValue. inversion H7. subst. clear H7.\n\n    unfold basicEval.\n    erewrite absEvalSimp2.\n    remember (absEval (fst st) nil (convertToAbsExp e)).\n    destruct v0. simpl. inversion H8. subst. clear H8.\n    remember (beq_nat (aeval st e) x0). destruct b. reflexivity.\n    erewrite <- absEvalAeval in Heqv0. inversion Heqv0. subst. clear Heqv0.\n    rewrite <- beq_nat_refl in Heqb. inversion Heqb.\n    apply x.\n\n    inversion H8. inversion H8. inversion H8.\n    crunch. crunch.\n    eapply BTStatePredicate.\n        intro X. inversion X.\n        crunch. crunch.\nGrab Existential Variables.\n    apply x. *)\nAdmitted.\n\nDefinition id_fun {e} := fun (x:e) => x.\n\n\n(*Theorem sbasic1 :\n    forall x, convertAbsValue (fun _ : unit => tt) x=x.\nProof. intros. induction x using value_ind'. simpl. reflexivity. simpl.\n reflexivity. simpl. destruct v. reflexivity.\n    simpl.   assert ((map (convertAbsValue (fun _ : unit => tt)) l) = l).\n        induction l. simpl. reflexivity. simpl. simpl in H. inversion H. rewrite H0.\n        rewrite IHl. reflexivity. apply H1.\n    rewrite H0. reflexivity.\nQed.\n\nTheorem sbasic2 :\n    forall l, (map (convertAbsValue (fun _ : unit => tt)) l) = l.\nProof. induction l. simpl. reflexivity.\n    simpl. rewrite sbasic1. rewrite IHl. reflexivity.\nQed. \n\nTheorem sbasic3 :\n    forall c (e:absExp), (convertAbsExp e)=e.\nProof.\n    intros. induction e using abs_ind'.\n    unfold convertAbsExp. rewrite sbasic1. reflexivity.\n    unfold convertAbsExp. reflexivity.\n    unfold convertAbsExp. reflexivity.\n    simpl. assert ((map (convertAbsExp (fun _ : unit => tt)) l)=l).\n           induction l. simpl. reflexivity.\n           simpl. simpl in H. inversion H. rewrite H0. rewrite IHl. reflexivity. apply H1.\n    rewrite H0. reflexivity.\nQed.*)\n\n(*Theorem sbasic : supportsBasicFunctionality unit eq_unit unitEval basicState (@basicAccumulate unit eq_unit unitEval) tt.\nProof.\n    unfold supportsBasicFunctionality. unfold supportsFunctionality.\n    split. intros. unfold unitEval. rewrite sbasic2 in H0. subst. rewrite sbasic1. reflexivity.\n    split. intros. rewrite sbasic2 in H0. subst. rewrite sbasic1. reflexivity.\n    split. intros. rewrite sbasic2 in H0. subst. apply H.\n    split. intros. rewrite sbasic2 in H0. subst. apply H.\n    split. intros. rewrite sbasic2. rewrite sbasic2. rewrite sbasic1. rewrite sbasic3. apply H.\n    intros. rewrite sbasic2. rewrite sbasic2. rewrite sbasic1. rewrite sbasic3. apply H. admit.\nAdmitted.*)\n\n(*Hint Resolve sbasic.*)\n\n(*Definition basicAssign := @assign unit eq_unit unitEval basicState basicAccumulate tt.*)\n\n(* **************************************************************************\n *\n * Theorems and definitions for new\n *\n ****************************************************************************)\n\nFixpoint add_cells (n : nat) (base : absState) : absState :=\n    match n with\n    | 0 => base\n    | (S n1) => (AbsStar (v(0)++++#n1 |-> v(n)) (add_cells n1 base))\n    end.\n\nFixpoint n_quant (n : nat) (s : absState) : absState :=\n    match n with\n    | 0 => s\n    | (S n1) => n_quant n1 (AbsExistsT s)\n    end.\n\nFixpoint pushNState (s : absState) (n : nat) :=\n    match n with\n    | 0 => s\n    | S n1 => pushNState (addStateVar 0 s) n1\n    end.\n\nTheorem new_thm : forall P v size Q,\n    Q = n_quant (S size) (AbsExistsT (add_cells size\n                                         (AbsStar ([!!v====v(0)])\n                                          (quantifyAbsVarState (pushNState P (S size)) 1 0 v)))) ->\n    {{ P }} (NEW v,(ANum size)) {{ Q return (#0::nil) with AbsNone }}.\nProof.\n    admit.\nAdmitted.\n\nLtac new_thm :=\n    eapply new_thm;simpl;reflexivity.\n\nTheorem del_thm : forall P v size Q vv,\n    vv = convertToAbsExp v ->\n    Q = AbsMagicWand P (n_quant (S size) (add_cells size ([vv====v(0)]))) ->\n    ((exists s, realizeState P nil s) -> (exists s, realizeState Q nil s)) ->\n    {{ P }} (DELETE v,(ANum size)) {{ Q return (#0::nil) with AbsNone }}.\nProof. admit. Admitted.\n\nLtac del_thm :=\n    eapply del_thm;simpl;reflexivity.\n\n\n(* **************************************************************************\n *\n * Theorems and definitions for store\n *\n ****************************************************************************)\n\nFixpoint replaceRoot (s : absState) (r : absState) : absState :=\n    match s with\n    | AbsExistsT s => AbsExistsT (replaceRoot s r)\n    | _ => r\n    end.\n\nFixpoint rootCount (s : absState) : nat :=\n    match s with\n    | AbsExistsT s => S(rootCount s)\n    | _ => 0\n    end.\n\nTheorem store : forall P ll l v vv,\n    ll = (convertToAbsExp l) ->\n    vv = convertToAbsExp v ->\n    (forall s n, realizeState P nil s -> ((NatValue n)=(absEval (env_p s) nil ll) -> (heap_p s) n<>None)) ->\n    {{ P }} CStore l v {{ (AbsUpdateLoc P ll vv) return (#0::nil) with AbsNone }}.\nProof. admit. Admitted.\n\nLtac store := eapply store;\n              [(simpl;reflexivity)|(simpl;reflexivity)|solveSPickElement|\n               (simpl;reflexivity)].\n\nTheorem store_array : forall P r r' (bb : absExp) base ll l v vv var Q size c bb,\n    r = getRoot P ->\n    c = rootCount P ->\n    ll = convertToAbsExp l ->\n    bb = convertToAbsExp base ->\n    vv = convertToAbsExp v ->\n    spickElement r (ARRAY(bb, size, (AbsQVar var))) r' ->\n    (forall ss, realizeState P nil ss -> absEval (fst ss) nil (ll <<<< size)=NatValue 1) ->\n    Q = (AbsExistsT (replaceRoot P (AbsLeaf (Id 4) ((addExpVar 0 bb)::(addExpVar 0 size)::(AbsQVar (var+1))::nil) ** (AbsLeaf (Id 1) ((vv====(nth(AbsQVar (var+1),(addExpVar 0 ll))))::nil)) ** (replaceStateExp (AbsQVar (var+1)) (replacenth(AbsQVar (var+1),(addExpVar 0 ll),(AbsQVar 0))) (addStateVar 0 r'))))) ->\n    {{ P }} CStore (base+++l) v {{ Q return (#0::nil) with AbsNone }}.\nProof. admit. Admitted.\n\n(* **************************************************************************\n *\n * Theorems and definitions for load\n *\n ****************************************************************************)\n\nInductive UnfContext :=\n    | UnfCExistsT : UnfContext\n    | UnfCUpdateVar : id -> absExp -> UnfContext\n    | UnfCUpdateWithLoc : id -> absExp -> UnfContext\n    | UnfCUpdateLoc : absExp -> absExp -> UnfContext\n    | UnfCMagicWand : absState -> UnfContext\n    | UnfCStar : absState -> UnfContext\n    .\n\nFixpoint getRootTraceLoadTraverse (e:absExp) (s : absState) : option (absState * list UnfContext) :=\n    match s with\n    | AbsExistsT s => match getRootTraceLoadTraverse e s with\n                      | Some (s,l) => Some (s,(UnfCExistsT::l))\n                      | None => None\n                      end\n    | AbsUpdateVar s i v => if hasVarExp e i then None\n                            else match getRootTraceLoadTraverse e s with\n                                 | Some (s,l) => Some (s,((UnfCUpdateVar i v)::l))\n                                 | None => None\n                                 end\n    | AbsUpdateWithLoc s i v => if hasVarExp e i then None\n                                else match getRootTraceLoadTraverse e s with\n                                     | Some (s,l) => Some (s,((UnfCUpdateWithLoc i v)::l))\n                                     | None => None\n                                     end\n    | AbsStar x y => match x,y with\n                     | ([a]),b => match getRootTraceLoadTraverse e b with\n                                  | Some (s,l) => Some (s,(UnfCStar ([a]))::l)\n                                  | None => None\n                                  end\n                     | b,([a]) => match getRootTraceLoadTraverse e b with\n                                  | Some (s,l) => Some (s,(UnfCStar ([a]))::l)\n                                  | None => None\n                                  end\n                     | _,_ => Some (s,nil)\n                     end\n    | AbsUpdateLoc s i v => None\n    (*| AbsMagicWand a b => (UnfCMagicWand b)::(getUnfoldTrace a)*)\n    | _ => Some (s,nil)\n    end.\n\nFixpoint finishState (s : absState) (l : list (UnfContext)) :=\n    match l with\n    | UnfCExistsT::r => AbsExistsT (finishState s r)\n    | (UnfCUpdateVar i v)::r => (AbsUpdateVar (finishState s r) i v)\n    | (UnfCUpdateWithLoc i v)::r => AbsUpdateWithLoc (finishState s r) i v\n    | (UnfCUpdateLoc i v)::r => AbsUpdateLoc (finishState s r) i v\n    | (UnfCMagicWand d)::r => AbsMagicWand (finishState s r) d\n    | (UnfCStar x)::r => AbsStar (finishState s r) (x)\n    | nil => s\n    end.\n(*\n * This theorem creates a tactic that allows one to retain an inTree relationship after\n * an operation that causes one to traverse a pointer to a child node in a TREE type\n * data structure.  See the proof of loopInvariant for an example of this rule's use.\n *)\nTheorem load_traverse : forall v (r:absState) r' r'' ff vve vv (PPP:absState) Q t root heap size fields,\n    vv = convertToAbsExp vve ->\n    Some (r,t) = getRootTraceLoadTraverse (AbsVar v) PPP ->\n    spickElement r ([vv inTree heap]) r' ->\n    spickElement r' (TREE(root,heap,size,fields)) r'' ->\n    Q = AbsExistsT\n    (finishState\n                             (AbsStar\n                                 ([(!!v)====#0 \\\\//\n                                   (!!v) inTree (quantifyAbsVar (addExpVar 0 heap) 0 0 v)])\n                                 (AbsStar\n                                     ([nth(nth(quantifyAbsVar (find((addExpVar 0 heap),vv)) 0 0 v,#(ff+1)),#0)====(AbsVar v)])\n                                     (quantifyAbsVarState r 0 0 v))) t) ->\n    {{ PPP }} CLoad v (APlus vve (ANum ff)) {{ Q return (#0::nil) with AbsNone }}.\nProof. admit. Admitted.\n\nLtac load_traverse := eapply load_traverse;[\n        (simpl; reflexivity) |\n        (simpl; reflexivity) |\n        solveSPickElement |\n        solveSPickElement |\n        (simpl; reflexivity)].\n\nFixpoint findCell (state : absState) (loc : absExp) :=\n   match state with\n   | AbsLeaf i (l::val::nil) => if beq_id i AbsCellId && beq_absExp l loc then Some val else None\n   | AbsStar l r => match findCell l loc with\n                       | Some v => Some v\n                       | None => findCell r loc\n                       end\n   | _ => None\n   end.\n\n(*\n * load theorem.  This theorem allows one to propagate over a statement that loads a heap\n * cell value into a variable.  See the loopInvariant proof in TreeTraversal.v for an\n * example of this rule's use.\n *)\nTheorem load : forall (P:absState) v loc ll,\n    ll = (convertToAbsExp loc) ->\n    {{ P }} CLoad v loc {{ (AbsUpdateWithLoc P v ll) return (#0::nil) with AbsNone }}.\nProof. admit. Admitted.\n\nTheorem loadUpdateProp : forall (P:absState) v loc (Q:absState)  vv val,\n    v<>vv ->\n    {{ P }} CLoad v loc {{ Q return (#0::nil) with AbsNone }} ->\n    {{ (AbsUpdateVar P vv val) }} CLoad v loc {{ (AbsUpdateVar Q vv val) return (#0::nil) with AbsNone }}.\nProof.\n    admit.\nAdmitted.\n\nTheorem load_array : forall P r r' (bb : absExp) base ll l v var Q size c bb,\n    r = getRoot P ->\n    c = rootCount P ->\n    ll = convertToAbsExp l ->\n    bb = convertToAbsExp base ->\n    spickElement r (AbsLeaf (Id 4) (bb::size::(AbsQVar var)::nil)) r' ->\n    (forall ss, realizeState P nil ss -> absEval (fst ss) nil (ll <<<< size)=@NatValue unit 1) ->\n    Q = (AbsExistsT (replaceRoot P (AbsStar\n                           ([(!!v)====(quantifyAbsVar (nth((AbsQVar var),ll)) 0 0 v)])\n                           (quantifyAbsVarState r 0 0 v)))) ->\n    {{ P }} CLoad v (base+++l) {{ Q return (#0::nil) with AbsNone }}.\nProof. admit. Admitted.\n\n(* **************************************************************************\n *\n * Theorems for delete\n *\n ****************************************************************************)\n\nFixpoint removeCell (state : absState) (loc : absExp) :=\n   match state with\n   | AbsLeaf i (l::val::nil) => if beq_id AbsCellId i && beq_absExp l loc then Some AbsEmpty else None\n   | AbsExistsT s => match removeCell s loc with\n                         | Some x => Some (AbsExistsT x)\n                         | None => None\n                         end\n   | AbsStar l r => match removeCell l loc with\n                       | Some x => Some (AbsStar x r)\n                       | None => match removeCell r loc with\n                                 | Some x => Some (AbsStar l x)\n                                 | None => None\n                                 end\n                       end\n   | _ => None\n   end.\n\nFixpoint removeCells (state : absState) (loc : absExp) (n : nat) :=\n    match n with\n    | 0 => Some state\n    | S 0 => match removeCell state loc with\n             | None => None\n             | Some s => Some s\n             end\n    | S n1 => match (removeCell state (loc++++#n1)) with\n                  | None => None\n                  | Some s => removeCells s loc n1\n                  end\n    end.\n\n(*\n * This is the rule for forward propagating over a DELETE statement.  See loopInvariant\n * in TreeTraversal.v for an example of this rule's use.\n *)\nTheorem delete_thm :\n    forall (P:absState) v (loc:absExp) (Q:absState) n exp nn,\n    \n    loc = convertAbsExp (convertToAbsExp v) ->\n    AbsConstVal n = convertAbsExp (convertToAbsExp exp) ->\n    Some Q = removeCells P loc nn ->\n    n = NatValue nn ->\n    {{ P }} DELETE v,exp {{ Q return (#0::nil) with AbsNone }}.\nProof. admit. Admitted.\n\n(*Definition delete_thm_basic := @delete_thm unit eq_unit\n                                           (@basicEval unit)\n                                           (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit)) tt.*)\n\n(* **************************************************************************\n *\n * Theorems for if\n *\n ****************************************************************************)\n\nTheorem cevalFalse : forall f r st st' b1 c1 c2,\n      aeval st b1 = 0 ->\n      ceval f st (CIf b1 c1 c2) st' r ->\n      ceval f st c2 st' r.\nProof.\n    admit.\n    (*intros.  inversion H0. subst. rewrite H in H8. elim H8. reflexivity. subst. apply H9.*)\nAdmitted.\n\nTheorem cevalTrue : forall f r st st' b1 c1 c2,\n      aeval st b1 <> 0 ->\n      ceval f st (CIf b1 c1 c2) st' r ->\n      ceval f st c1 st' r.\nProof.\n    intros. inversion H0. subst. apply H9. subst. rewrite H8 in H. elim H. reflexivity.\nQed.\n\n(*\n * mergeStates specifies where states need to be merged at the end of processing an if-then-else\n *)\nDefinition mergeStates(Q1 : absState) (Q2 : absState) (Q : absState) :=\n    (forall s, realizeState Q1 nil s -> realizeState Q nil s) /\\\n    (forall s, realizeState Q2 nil s -> realizeState Q nil s).\n\n(*\n * Rule for propagating over an if-then-else\n *)\nTheorem if_statement: forall (P:absState) Q1 Q2 Q Q1' Q2' Qm r1 r2 rm b l r,\n    {{(AbsStar ([convertToAbsExp b]) P)}}l{{Q1 return r1 with Q1' }} ->\n    {{(AbsStar ([~~(convertToAbsExp b)]) P)}}r{{Q2 return r2 with Q2' }} ->\n    mergeReturnStates  Q1' Q2' Qm r1 r2 rm ->\n    mergeStates Q1 Q2 Q ->\n    {{P}}CIf b l r{{Q return rm with Qm}}.\nProof. admit.\n    (*unfold hoare_triple. unfold mergeStates. unfold absExecute. intros. inversion H2. subst. clear H2.\n\n    assert (forall (st st' : state), realizeState ([convertToAbsExp b] ** P) nil st ->\n               (exists (st'0:state) (r:result),\n                   ceval\n                       (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n                            False) st l st'0 r)).\n    intros.\n    assert ((exists (st'0 : state) (r : result),\n       ceval\n         (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n          False) st0 l st'0 r) /\\\n    (ceval\n       (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n        False) st0 l st' res -> realizeState Q1 nil st')).\n    eapply H0. apply H2.\n\n    inversion H6. subst. clear H6. apply H7.\n\n    assert (forall st st' : state,\n    realizeState ([convertToAbsExp b] ** P) nil st ->\n    (ceval\n       (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n        False) st l st' res -> realizeState Q1 nil st')).\n    intros.\n    assert ((exists (st'0 : state) (r : result),\n       ceval\n         (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n          False) st0 l st'0 r) /\\\n    (ceval\n       (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n        False) st0 l st'0 res -> realizeState Q1 nil st'0)).\n    eapply H0. apply H6.\n    inversion H8. subst. clear H8. apply H10. apply H7.\n\n    assert (forall st st' : state,\n     realizeState ([~~ (convertToAbsExp b)] ** P) nil st ->\n     (exists (st'0 : state) (r0 : result),\n        ceval\n          (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n           False) st r st'0 r0)).\n    intros.\n    assert ((exists (st'0 : state) (r0 : result),\n        ceval\n          (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n           False) st0 r st'0 r0) /\\\n     (ceval\n        (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n         False) st0 r st'0 res -> realizeState Q2 nil st'0)).\n    eapply H1. apply H7.\n\n    inversion H8. subst. clear H8. apply H9.\n\n    assert (forall st st' : state,\n     realizeState ([~~ (convertToAbsExp b)] ** P) nil st ->\n     (ceval\n        (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n         False) st r st' res -> realizeState Q2 nil st')).\n    intros.\n    assert ((exists (st'0 : state) (r0 : result),\n        ceval\n          (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n           False) st0 r st'0 r0) /\\\n     (ceval\n        (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n         False) st0 r st'0 res -> realizeState Q2 nil st'0)).\n    eapply H1. apply H8.\n    inversion H10. subst. clear H10. apply H12. apply H9.\n\n    split.\n\n    clear H6. clear H8.\n\n    remember (aeval st b). destruct n.\n\n    assert (\n        (exists (st'0 : state) (r0 : result),\n  ceval\n    (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n     False) st r st'0 r0) ->\n        (exists (st'0 : state) (r0 : result),\n  ceval\n    (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n     False) st (CIf b l r) st'0 r0)\n    ).\n    intros. inversion H6. subst. clear H6. inversion H8. subst. clear H8.\n    eapply ex_intro. eapply ex_intro. apply CEIfFalse. rewrite Heqn. reflexivity. apply H6.\n\n    eapply H6. eapply H7. apply st. eapply RSCompose. eapply RSR. unfold map. reflexivity.\n    inversion H. subst. inversion H9. subst. clear H9. inversion H11. subst. clear H11.\n    eapply H9. 3:omega. eapply BTStatePredicate.\n    instantiate (1 := aeval st (ALnot b)). simpl. rewrite <- Heqn. unfold beq_nat. intro X. inversion X.\n\n    instantiate (1:=(fst st,empty_heap)). simpl. unfold empty_heap. reflexivity.\n\n    simpl.\n\n    erewrite H8. rewrite <- Heqn. simpl. 2:omega. 2:simpl. 2:reflexivity.\n    erewrite <- absEvalAeval. rewrite <- Heqn. simpl. reflexivity.\n    apply H.\n\n    apply H3. unfold concreteCompose. simpl.\n    split. reflexivity. split. reflexivity. split. intros. left. unfold empty_heap. reflexivity.\n    unfold compose_heaps. unfold empty_heap.\n\n    eapply functional_extensionality. reflexivity.\n\n    assert (\n        (exists (st'0 : state) (r0 : result),\n  ceval\n    (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n     False) st l st'0 r0) ->\n        (exists (st'0 : state) (r0 : result),\n  ceval\n    (fun (_ : id) (_ : state) (_ : list nat) (_ : state) (_ : result) =>\n     False) st (CIf b l r) st'0 r0)\n    ).\n    intros. inversion H6. subst. clear H6. inversion H8. subst. clear H8.\n    eapply ex_intro. eapply ex_intro. apply CEIfTrue. rewrite <- Heqn. intro X. inversion X. apply H6.\n\n    eapply H6. eapply H2. apply st. eapply RSCompose. eapply RSR. unfold map. reflexivity.\n    inversion H. subst. inversion H9. subst. clear H9. inversion H11. subst. clear H11.\n    eapply H9. 3:omega. eapply BTStatePredicate.\n    instantiate (1 := aeval st b). simpl. rewrite <- Heqn. intro X. inversion X.\n\n    instantiate (1:=(fst st,empty_heap)). simpl. unfold empty_heap. reflexivity.\n\n    simpl.\n\n    rewrite <- Heqn. simpl.\n    erewrite <- absEvalAeval. rewrite <- Heqn. simpl. reflexivity.\n    apply H.\n\n    apply H3. unfold concreteCompose. simpl.\n    split. reflexivity. split. reflexivity. split. intros. left. unfold empty_heap. reflexivity.\n    unfold compose_heaps. unfold empty_heap.\n\n    eapply functional_extensionality. reflexivity.\n\n    intros.\n\n    remember (aeval st b). destruct n.\n\n    apply H5. eapply H8.\n\n    eapply RSCompose. eapply RSR. unfold map. reflexivity.\n\n    inversion H. subst. inversion H11. subst. clear H11. inversion H13. subst. clear H13.\n    eapply H11. 3:omega. eapply BTStatePredicate. instantiate (1:= aeval st (ALnot b)).\n    simpl. rewrite <- Heqn. simpl. intro X. inversion X.\n\n    instantiate (1 := (fst st,empty_heap)). simpl. unfold empty_heap. reflexivity.\n\n    simpl.\n\n    rewrite <- Heqn. simpl.\n\n    erewrite <- absEvalAeval. rewrite <- Heqn. erewrite H10. 2:omega. 2:simpl. 2:reflexivity.\n    simpl. reflexivity. apply H.\n    apply H3. unfold concreteCompose. simpl.\n    split. reflexivity. split. reflexivity. split. intros. left. unfold empty_heap. reflexivity.\n    unfold compose_heaps. unfold empty_heap.\n\n    eapply functional_extensionality. reflexivity.\n\n    eapply cevalFalse. instantiate (1 := b). erewrite <- Heqn. reflexivity.\n    eapply H9.\n\n    apply H4. eapply H6.\n\n    eapply RSCompose. eapply RSR. unfold map. reflexivity.\n\n    inversion H. subst. inversion H11. subst. clear H11. inversion H13. subst. clear H13.\n    eapply H11. 3:omega. eapply BTStatePredicate. instantiate (1:= aeval st b).\n    simpl. rewrite <- Heqn. simpl. intro X. inversion X.\n\n    instantiate (1 := (fst st,empty_heap)). simpl. unfold empty_heap. reflexivity.\n\n    simpl.\n\n    rewrite <- Heqn. simpl.\n\n    erewrite <- absEvalAeval. rewrite <- Heqn. reflexivity.\n    apply H.\n    apply H3. unfold concreteCompose. simpl.\n    split. reflexivity. split. reflexivity. split. intros. left. unfold empty_heap. reflexivity.\n    unfold compose_heaps. unfold empty_heap.\n\n    eapply functional_extensionality. reflexivity.\n\n    eapply cevalTrue. instantiate (1 := b). erewrite <- Heqn. intro X. inversion X.\n    eapply H9.*)\nAdmitted.\n\n(* **************************************************************************\n *\n * Theorems for while\n *\n ****************************************************************************)\n\n\nTheorem while_aux : forall c b ff (invariant: absState) res c1 st1 st1',\n   (forall st st' res, realizeState (AbsStar ([convertToAbsExp b]) invariant) nil st ->\n                       ceval ff st c st' res ->\n                       realizeState invariant nil st') ->\n    realizeState invariant nil st1 ->\n    c1 = (WHILE b DO c LOOP) ->\n    ceval ff st1 c1 st1' res ->\n    realizeState (AbsStar (match res with | NoResult => [~~(convertToAbsExp b)] | _ => AbsEmpty end) invariant) nil st1'.\nProof.\n    admit. (*intros. induction H3.\n\n    inversion H2. inversion H2. inversion H2. inversion H2. inversion H2. inversion H2. inversion H2.\n    inversion H2. inversion H2. inversion H2. inversion H2. inversion H2. subst. clear H2.\n\n    eapply RSCompose. instantiate (1 := (fst st,empty_heap)).\n    eapply RSR. simpl. inversion H. erewrite H2. reflexivity. omega. simpl. reflexivity.\n    inversion H. inversion H4. inversion H6. eapply H7.\n    eapply BTStatePredicate.\n    Focus 3. simpl. unfold basicEval. erewrite <- absEvalAeval. simpl.\n    remember (beq_nat (aeval st b) 0). destruct b0. simpl. reflexivity.\n    apply beq_nat_neq in Heqb0. rewrite H3 in Heqb0. elim Heqb0. reflexivity.\n    apply H.\n    omega.\n    intros. simpl. unfold empty_heap. reflexivity. omega. apply H1.\n    unfold concreteCompose.\n    split. simpl. reflexivity.\n    split. simpl. reflexivity.\n    split. intros. left. simpl. unfold empty_heap. reflexivity.\n    unfold compose_heaps. simpl. apply functional_extensionality. intros. reflexivity.\n\n    inversion H2. subst. clear H2.\n\n    assert (realizeState ([convertToAbsExp b] ** invariant) nil st).\n    eapply RSCompose. instantiate (1 := (fst st, empty_heap)).\n    eapply RSR. simpl. unfold env_p. erewrite <- absEvalAeval. reflexivity. apply H.\n    inversion H. inversion H4. inversion H6. eapply H7. 2:instantiate (1:=(NatValue _::nil)).\n    2:simpl. 2:reflexivity.\n    apply BTStatePredicate. apply H3.\n    intros. simpl. unfold empty_heap. reflexivity. omega. apply H1.\n    unfold concreteCompose.\n    split. simpl. reflexivity.\n    split. simpl. reflexivity.\n    split. intros. left. simpl. unfold empty_heap. reflexivity.\n    unfold compose_heaps. simpl. apply functional_extensionality. intros. reflexivity.\n    eapply H0 in H2. Focus 2. eapply H3_.\n    eapply IHceval2. apply H0. apply H2. reflexivity.\n\n    inversion H2. subst. clear H2.\n    eapply RSCompose. instantiate (1 := (fst st', empty_heap)).\n    eapply RSEmpty. simpl. intros. unfold empty_heap. reflexivity. eapply H0.\n    eapply RSCompose. instantiate (1 := (fst st,empty_heap)).\n    eapply RSR. simpl. reflexivity. inversion H.  inversion H5. inversion H7.\n    eapply H8.\n    eapply BTStatePredicate.\n    Focus 3. simpl. unfold basicEval. erewrite <- absEvalAeval. simpl. reflexivity.\n    apply H.\n    apply H3.\n    intros. simpl. unfold empty_heap. reflexivity. omega. apply H1.\n    unfold concreteCompose.\n    split. simpl. reflexivity.\n    split. simpl. reflexivity.\n    split. intros. left. simpl. unfold empty_heap. reflexivity.\n    unfold compose_heaps. simpl. apply functional_extensionality. intros. reflexivity.\n    apply H4.\n    unfold concreteCompose.\n    split. simpl. reflexivity.\n    split. simpl. reflexivity.\n    split. intros. left. simpl. unfold empty_heap. reflexivity.\n    unfold compose_heaps. simpl. apply functional_extensionality. intros. reflexivity.\n\n    inversion H2. subst. clear H2.\n    eapply RSCompose. instantiate (1 := (fst st', empty_heap)).\n    eapply RSEmpty. simpl. intros. unfold empty_heap. reflexivity. eapply H0.\n    eapply RSCompose. instantiate (1 := (fst st,empty_heap)).\n    eapply RSR. simpl. reflexivity. inversion H.  inversion H5. inversion H7.\n    eapply H8.\n    eapply BTStatePredicate.\n    Focus 3. simpl. unfold basicEval. erewrite <- absEvalAeval. simpl. reflexivity.\n    apply H.\n    apply H3.\n    intros. simpl. unfold empty_heap. reflexivity. omega. apply H1.\n    unfold concreteCompose.\n    split. simpl. reflexivity.\n    split. simpl. reflexivity.\n    split. intros. left. simpl. unfold empty_heap. reflexivity.\n    unfold compose_heaps. simpl. apply functional_extensionality. intros. reflexivity.\n    apply H4.\n    unfold concreteCompose.\n    split. simpl. reflexivity.\n    split. simpl. reflexivity.\n    split. intros. left. simpl. unfold empty_heap. reflexivity.\n    unfold compose_heaps. simpl. apply functional_extensionality. intros. reflexivity.\n\n    inversion H2. inversion H2. inversion H2. inversion H2. inversion H2. inversion H2.\n    inversion H2.*)\nAdmitted.\n\nTheorem while_aux2 : forall c b ff (invariant: absState) c1 st1,\n   (forall st, exists st', exists res, realizeState (AbsStar ([convertToAbsExp b]) invariant) nil st ->\n                                       ceval ff st c st' res ->\n                                       realizeState invariant nil st') ->\n    realizeState invariant nil st1 ->\n    c1 = (WHILE b DO c LOOP) ->\n    (exists st'', exists res', ceval ff st1 c1 st'' res').\nProof. admit. Admitted.\n(*    intros. eapply ex_intro. eapply ex_intro.\n    induction H1.\n    inversion H2. inversion H2. inversion H2. inversion H2. inversion H2. inversion H2. inversion H2.\n    inversion H2. inversion H2. inversion H2. inversion H2.\n    inversion H2. subst.\n    apply H1.*)\n\n\n\n(*\n * Rule for propagating over a while.  When creating a proof, one will usually have to\n * fill in the expression 'invariant'.\n *)\nTheorem whileThm : forall (state: absState) c b invariant res Q,\n   {{AbsStar ([convertToAbsExp b]) invariant}} c {{invariant return res with Q}} ->\n   (forall x, realizeState state nil x -> realizeState invariant nil x) ->\n   {{state}} (WHILE b DO c LOOP) {{ (AbsStar ([~~(convertToAbsExp b)]) invariant) return res with Q}}.\nProof. admit.\n    (*unfold hoare_triple. unfold absExecute. intros.\n\n    split.\n\n    eapply while_aux2.\n        apply H. intros. eapply ex_intro. eapply ex_intro. intros.\n        assert (forall st st' : ImpHeap.state,\n        realizeState ([convertToAbsExp b] ** invariant) nil st ->\n            (exists (st'0 : ImpHeap.state) (r : result),\n               ceval\n                 (fun (_ : id) (_ : ImpHeap.state) (_ : list nat)\n                    (_ : ImpHeap.state) (_ : result) => False) st c st'0 r)).\n        intros.\n        assert((exists (st'0 : ImpHeap.state) (r : result),\n          ceval\n            (fun (_ : id) (_ : ImpHeap.state) (_ : list nat)\n               (_ : ImpHeap.state) (_ : result) => False) st1 c st'0 r) /\\\n       (ceval\n          (fun (_ : id) (_ : ImpHeap.state) (_ : list nat)\n             (_ : ImpHeap.state) (_ : result) => False) st1 c st' res ->\n        realizeState invariant nil st')).\n        apply H0. eapply H5.\n        inversion H6. subst. clear H6.\n        apply H7.\n        apply H2. apply H2. reflexivity.\n\n    eapply while_aux.\n        apply H. intros.\n        assert(forall st' st0 res, realizeState ([convertToAbsExp b] ** invariant) nil st0 ->\n            (ceval\n          (fun (_ : id) (_ : ImpHeap.state) (_ : list nat)\n             (_ : ImpHeap.state) (_ : result) => False) st0 c st' res) ->\n          realizeState invariant nil st').\n        intros.\n        assert((exists (st'0 : ImpHeap.state) (r : result),\n          ceval\n            (fun (_ : id) (_ : ImpHeap.state) (_ : list nat)\n               (_ : ImpHeap.state) (_ : result) => False) st1 c st'0 r) /\\\n       (ceval\n          (fun (_ : id) (_ : ImpHeap.state) (_ : list nat)\n             (_ : ImpHeap.state) (_ : result) => False) st1 c st'1 res1 ->\n        realizeState invariant nil st'1)).\n        apply H0. apply H5.\n\n        inversion H7. subst. clear H7. apply H9. apply H6.\n\n        eapply H5. apply H3. apply H4.\n        apply H1. apply H2. reflexivity.\n\nGrab Existential Variables. apply NoResult.*)\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", "meta": {"author": "kendroe", "repo": "CoqPIE", "sha": "946009445e532dd4632a11a58a64f72a1dd28304", "save_path": "github-repos/coq/kendroe-CoqPIE", "path": "github-repos/coq/kendroe-CoqPIE/CoqPIE-946009445e532dd4632a11a58a64f72a1dd28304/PEDANTIC/AbsExecute.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.42632159254749025, "lm_q1q2_score": 0.2700364664466438}}
{"text": "From solutions Require Export sem_typed.\n\n(** Semantic operator typing *)\nClass SemTyUnboxed `{!heapG Σ} (A : sem_ty Σ) :=\n  sem_ty_unboxed v :\n    A v -∗ ⌜ val_is_unboxed v ⌝.\n\nClass SemTyUnOp `{!heapG Σ} (op : un_op) (A B : sem_ty Σ) :=\n  sem_ty_un_op v :\n    A v -∗ ∃ w, ⌜ un_op_eval op v = Some w ⌝ ∧ B w.\n\nClass SemTyBinOp `{!heapG Σ} (op : bin_op) (A1 A2 B : sem_ty Σ) :=\n  sem_ty_bin_op v1 v2 :\n    A1 v1 -∗ A2 v2 -∗ ∃ w, ⌜ bin_op_eval op v1 v2 = Some w ⌝ ∧ B w.\n\nSection sem_operators.\n  Context `{!heapG Σ}.\n  Implicit Types A B : sem_ty Σ.\n\n  (* Unboxed types *)\n  Global Instance sem_ty_unit_unboxed : SemTyUnboxed ().\n  Proof. by iIntros (v ->). Qed.\n  Global Instance sem_ty_bool_unboxed : SemTyUnboxed sem_ty_bool.\n  Proof. iIntros (v). by iDestruct 1 as (b) \"->\". Qed.\n  Global Instance sem_ty_int_unboxed : SemTyUnboxed sem_ty_int.\n  Proof. iIntros (v). by iDestruct 1 as (i) \"->\". Qed.\n  Global Instance sem_ty_ref_unboxed A : SemTyUnboxed (ref A).\n  Proof. iIntros (v). by iDestruct 1 as (i ->) \"?\". Qed.\n\n  (* Operator typing *)\n  Global Instance sem_ty_un_op_int op : SemTyUnOp op sem_ty_int sem_ty_int.\n  Proof. iIntros (?). iDestruct 1 as (i) \"->\". destruct op; eauto. Qed.\n  Global Instance sem_ty_un_op_bool : SemTyUnOp NegOp sem_ty_bool sem_ty_bool.\n  Proof. iIntros (?). iDestruct 1 as (i) \"->\". eauto. Qed.\n\n  Global Instance sem_ty_bin_op_eq A : SemTyUnboxed A → SemTyBinOp EqOp A A sem_ty_bool.\n  Proof.\n    iIntros (? v1 v2) \"A1 _\". rewrite /bin_op_eval /sem_ty_car /=.\n    iDestruct (sem_ty_unboxed with \"A1\") as %Hunb.\n    rewrite decide_True; last solve_vals_compare_safe.\n    eauto.\n  Qed.\n  Global Instance sem_ty_bin_op_arith op :\n    TCElemOf op [PlusOp; MinusOp; MultOp; QuotOp; RemOp;\n                 AndOp; OrOp; XorOp; ShiftLOp; ShiftROp] →\n    SemTyBinOp op sem_ty_int sem_ty_int sem_ty_int.\n  Proof.\n    iIntros (? v1 v2); iDestruct 1 as (i1) \"->\"; iDestruct 1 as (i2) \"->\".\n    repeat match goal with H : TCElemOf _ _ |- _ => inversion_clear H end;\n      rewrite /sem_ty_car /=; eauto.\n  Qed.\n  Global Instance sem_ty_bin_op_compare op :\n    TCElemOf op [LeOp; LtOp] →\n    SemTyBinOp op sem_ty_int sem_ty_int sem_ty_bool.\n  Proof.\n    iIntros (? v1 v2); iDestruct 1 as (i1) \"->\"; iDestruct 1 as (i2) \"->\".\n    repeat match goal with H : TCElemOf _ _ |- _ => inversion_clear H end;\n      rewrite /sem_ty_car /=; eauto.\n  Qed.\n  Global Instance sem_ty_bin_op_bool op :\n    TCElemOf op [AndOp; OrOp; XorOp] →\n    SemTyBinOp op sem_ty_bool sem_ty_bool sem_ty_bool.\n  Proof.\n    iIntros (? v1 v2); iDestruct 1 as (i1) \"->\"; iDestruct 1 as (i2) \"->\".\n    repeat match goal with H : TCElemOf _ _ |- _ => inversion_clear H end;\n      rewrite /sem_ty_car /=; eauto.\n  Qed.\nEnd sem_operators.\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/solutions/sem_operators.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2700309200088422}}
{"text": "(* Generic tools for proving properties of (privileged) concrete machine code. *)\n\nRequire Import ZArith.\nRequire Import Lia.\nRequire Import List.\nRequire Import Utils.\nRequire Import LibTactics.\nImport ListNotations.\n\nRequire Utils.\nRequire Import Instr Memory.\nRequire Import Lattices.\nRequire Import Concrete.\nRequire Import CodeGen.\nRequire Import ConcreteMachine.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import ConcreteExecutions.\nRequire Import EquivDec.\nRequire Import CodeTriples.\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).\nDefinition HProp := memory -> stack -> Prop.\n\nDefinition extension_comp (P : HProp) :=\n  forall m1 m2 s, P m1 s -> extends m1 m2 -> P m2 s.\n\nLtac go_match :=\n  try match goal with\n    | H1: extends ?m1 ?m2,\n      H2: extends ?m2 ?m3 |- _ => assert (Hext_trans: extends m1 m3) by (unfold extends in *; eauto)\n  end;\n  let H := fresh \"H\" in\n  try (simpl; intros ? ? H);\n    repeat match goal with\n             | [H: match ?sss with _ => _ end |- _ ] =>\n               destruct sss ; intuition ;\n               try (substs; eauto)\n           end.\n\nLtac split_vc :=\n  (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\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\nLtac run1 L := eapply rte_step; eauto; eapply L; eauto.\n\nSection CodeSpecs.\nLocal Open Scope Z_scope.\n\nVariable cblock : block.\nVariable stamp_cblock : Mem.stamp cblock = Kernel.\nVariable table : CSysTable.\n\nNotation cstep := (cstep cblock table).\nNotation runsToEscape := (runsToEscape cblock table).\nNotation HT := (HT cblock table).\nNotation HTEscape := (HTEscape cblock table).\n\n(* To stop struggling with [replace]s *)\nLemma cstep_branchnz_p' : forall m fh i s pcv pcl offv av al pc',\n       read_m pcv fh = Some (BranchNZ offv) ->\n       pc' = (if av =? 0 then pcv + 1 else pcv + offv) ->\n       cstep (CState m fh i ((Vint av, al) ::: s) (pcv, pcl) true) Silent\n             (CState m fh i s (pc',handlerTag) true).\nProof.\n  intros. subst.\n  [> once (econstructor; solve [eauto]) ..].\nQed.\n\nDefinition imemory : Type := list Instr.\nDefinition stack : Type := list CStkElmt.\nDefinition code := list Instr.\nDefinition state := CS.\n\n(* ================================================================ *)\n(* Specs for concrete code *)\n\nLtac nil_help :=   replace (@nil CEvent) with (op_cons Silent (@nil CEvent)) by reflexivity.\n\nLemma add_spec : forall Q,\n  HT [Add]\n     (fun m0 s0 =>\n        exists v1 t1 v2 t2 vr s,\n          s0 = (v1,t1) ::: (v2,t2) ::: s /\\\n          add v1 v2 = Some vr /\\\n          Q m0 ((vr,handlerTag) ::: s))\n     Q.\nProof.\n  unfold CodeTriples.HT; split_vc; subst; run1 cstep_add_p.\nQed.\n\nLemma sub_spec : forall Q,\n  HT [Sub]\n     (fun m0 s0 =>\n        exists v1 t1 v2 t2 vr s,\n          s0 = (v1,t1) ::: (v2,t2) ::: s /\\\n          Memory.sub v1 v2 = Some vr /\\\n          Q m0 ((vr,handlerTag) ::: s))\n     Q.\nProof.\n  unfold CodeTriples.HT; split_vc; subst; run1 cstep_sub_p.\nQed.\n\nLemma dup_spec:\n  forall n Q,\n  HT [Dup n]\n     (fun m s => exists x, index_list n s = Some x /\\ Q m (x :: s))\n     Q.\nProof.\n  unfold CodeTriples.HT; split_vc; subst; run1 cstep_dup_p.\nQed.\n\nLemma swap_spec: forall n Q,\n  HT [Swap n]\n     (fun m s => exists y s0 x s', s = y::s0 /\\\n                                   index_list n s = Some x /\\\n                                   update_list n y (x::s0) = Some s' /\\\n                                   Q m s')\n     Q.\nProof.\n  unfold CodeTriples.HT; split_vc; subst; run1 cstep_swap_p.\nQed.\n\nLemma push_spec: forall v Q,\n  HT [Push v]\n     (fun m s => Q m (CData (Vint v,handlerTag) :: s))\n     Q.\nProof.\n  unfold CodeTriples.HT; split_vc; subst; run1 cstep_push_p.\nQed.\n\nLemma PushCachePtr_spec : forall Q,\n  HT [PushCachePtr]\n     (fun m s =>\n        Q m (CData (Vptr (cblock, 0),handlerTag) :: s))\n     Q.\nProof.\n  unfold CodeTriples.HT; split_vc; subst; run1 cstep_push_cache_ptr_p.\nQed.\n\n\nLemma load_spec : forall Q,\n  HT [Load]\n     (fun m s0 => exists p t x s,\n                    s0 = (Vptr p,t) ::: s /\\\n                    Mem.stamp (fst p) = Kernel /\\\n                    load p m = Some x /\\\n                    Q m (x ::: s))\n     Q.\nProof.\n  unfold CodeTriples.HT; split_vc; subst; run1 cstep_load_p.\nQed.\n\nLemma unpack_spec : forall Q,\n  HT [Unpack]\n     (fun m s => exists x l s0,\n                   s = (x,l):::s0 /\\\n                   Q m ((l,handlerTag):::(x,handlerTag):::s0))\n     Q.\nProof.\n  unfold CodeTriples.HT; split_vc; subst; run1 cstep_unpack_p.\nQed.\n\nLemma pack_spec : forall Q,\n  HT [Pack]\n     (fun m s => exists x t l l0 s0,\n                   s = (l,t):::(x,l0):::s0 /\\\n                   Q m ((x,l):::s0))\n     Q.\nProof.\n  unfold CodeTriples.HT; split_vc; subst; run1 cstep_pack_p.\nQed.\n\n\nLemma pop_spec: forall Q,\n  HT [Pop]\n     (fun m s => exists v vl s0, s = (v,vl):::s0 /\\ Q m s0)\n     Q.\nProof.\n  unfold CodeTriples.HT; split_vc; subst; run1 cstep_pop_p.\nQed.\n\nLemma nop_spec: forall Q, HT [Noop] Q Q.\nProof.\n  unfold CodeTriples.HT; split_vc; subst; run1 cstep_nop_p.\nQed.\n\nLemma store_spec : forall Q,\n  HT [Store]\n     (fun (m0 : memory) (s0 : stack) =>\n        exists p al v m s,\n          Mem.stamp (fst p) = Kernel /\\\n          s0 = (Vptr p, al) ::: v ::: s /\\ store p v m0 = Some m /\\ Q m s)\n     Q.\nProof.\n  unfold CodeTriples.HT; split_vc; subst; run1 cstep_store_p.\nQed.\n\n\nLemma alloc_spec : forall Q : _ -> _ -> Prop,\n  HT [Alloc]\n     (fun m0 s0 => exists s t xv xl cnt,\n                     s0 = (Vint cnt,t) ::: (xv, xl) ::: s /\\\n                     cnt >= 0 /\\\n                     (forall b m,\n                        c_alloc Kernel cnt (xv,xl) m0 = Some (b, m) ->\n                        Q m ((Vptr (b, 0),handlerTag):::s)))\n     Q.\nProof.\n  intros. unfold CodeTriples.HT. intros.\n  inv H.\n  destruct H0 as (s & t & xv & xl & cnt & ? & ? & ?).\n  assert (ALLOC: exists b m',\n                   c_alloc Kernel cnt (xv,xl) mem0 = Some(b,m')).\n  { unfold c_alloc, alloc, zreplicate.\n    destruct (Z_lt_dec cnt 0); try lia.\n    match goal with\n      | |- context [Some ?p = Some _] => destruct p\n    end.\n    eauto. }\n  split_vc; subst; run1 cstep_alloc_p.\nQed.\n\nLemma getoff_spec : forall Q : _ -> _ -> Prop,\n  HT [GetOff]\n     (fun m s =>\n        exists p t s0,\n          s = (Vptr p, t) ::: s0 /\\\n          forall t', Q m ((Vint (snd p), t') ::: s0))\n     Q.\nProof.\n  unfold CodeTriples.HT; split_vc; subst; run1 cstep_getoff_p.\nQed.\n\nLemma genEq_spec : forall Q,\n  HT genEq\n     (fun m s => exists v1 t1 v2 t2 s0 ,\n                   s = (v1,t1):::(v2,t2):::s0 /\\\n                   Q m ((val_eq v1 v2,handlerTag):::s0))\n     Q.\nProof.\n  unfold genEq. unfold CodeTriples.HT; split_vc; run1 cstep_eq_p.\nQed.\n\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\nLemma push_cptr_spec :\n  forall v Q,\n    HT (push_cptr v)\n       (fun m s => Q m ((Vptr (cblock, v), handlerTag) ::: s))\n       Q.\nProof.\n  unfold push_cptr.\n  intros.\n  build_vc ltac:(idtac).\n  split_vc.\n  replace (v + 0) with v by lia. auto.\nQed.\n\nLemma loadFromCache_spec: forall ofs (Q : _ -> _ -> Prop),\n  HT (loadFromCache ofs)\n     (fun m s =>\n        exists v,\n          value_on_cache cblock m ofs v /\\\n          forall t, Q m (CData (v, t) :: s))\n     Q.\nProof.\n  intros.\n  unfold loadFromCache.\n  build_vc ltac:(try eapply push_cptr_spec).\n  split_vc'.\n  intros m s (? & [] & POST).\n  split_vc.\nQed.\n\nLemma storeAt_spec: forall a Q,\n  HT (storeAt a)\n     (fun m0 s0 => exists vl s m,\n                     s0 = vl ::: s /\\\n                     store (cblock, a) vl m0 = Some m /\\\n                     Q m s)\n     Q.\nProof.\n  intros.\n  unfold storeAt.\n  build_vc ltac:(try eapply push_cptr_spec).\n  split_vc; subst.\n  intuition; eauto. (* split_vc can't quite manage the order *)\nQed.\n\nLemma skipNZ_continuation_spec_NZ: forall c P v,\n  v <> 0 ->\n  HT   (skipNZ (length c) ++ c)\n       (fun m s => (exists s' l, s = CData (Vint v,l) :: s'\n                                 /\\ P m s'))\n       P.\nProof.\n  unfold CodeTriples.HT; split_vc.\n\n  (* massage to match the rule we want to run *)\n  match goal with\n    | |- context[n + ?z] =>\n      replace (n + z) with (if v =? 0 then n + 1 else n + z)\n  end.\n  run1 cstep_branchnz_p.\n  rewrite <- Z.eqb_neq in H. rewrite H. auto.\nQed.\n\nLemma skipNZ_spec_Z: forall n P v,\n  v = 0 ->\n  HT   (skipNZ n)\n       (fun m s => (exists s' l, s = CData (Vint v,l) :: s'\n                                 /\\ P m s'))\n       P.\nProof.\n  unfold CodeTriples.HT; split_vc; run1 cstep_branchnz_p.\nQed.\n\nLemma skipNZ_continuation_spec_Z: forall c P Q v,\n  v = 0 ->\n  HT   c P Q  ->\n  HT   (skipNZ (length c) ++ c)\n       (fun m s => (exists s' l, s = CData (Vint v,l) :: s'\n                                 /\\ P m s'))\n       Q.\nProof.\n  intros c P Q v l Hv HTc.\n  eapply HT_compose.\n  eapply skipNZ_spec_Z; auto.\n  auto.\nQed.\n\nLemma skip_spec: forall c P,\n  HT   (skip (length c) ++ c)\n       P\n       P.\nProof.\n  intros c P.\n  eapply HT_strengthen_premise.\n  { unfold skip.\n    rewrite app_ass.\n    eapply HT_compose; try eapply push_spec.\n    eapply skipNZ_continuation_spec_NZ with (v:= 1); lia. }\n  simpl. intros.\n  repeat eexists. auto.\nQed.\n\nLemma ifNZ_spec_Z: forall v t f P Q,\n  HT   f P Q ->\n  v = 0 ->\n  HT   (ifNZ t f)\n       (fun m s => (exists s' l, s = CData (Vint v,l) :: s' /\\ P m s'))\n       Q.\nProof.\n  intros v l t f P Q HTf Hveq0.\n  unfold ifNZ.\n  rewrite app_ass.\n  eapply HT_compose.\n\n  apply skipNZ_spec_Z; auto.\n\n  eapply HT_compose; eauto.\n\n  apply skip_spec.\nQed.\n\nLemma ifNZ_spec_NZ: forall v t f P Q,\n  HT   t P Q ->\n  v <> 0 ->\n  HT   (ifNZ t f)\n       (fun m s => (exists s' l, s = CData (Vint v,l) :: s' /\\ P m s'))\n       Q.\nProof.\n  intros v l t f P Q HTt Hveq0.\n  unfold ifNZ.\n  rewrite <- app_ass.\n  eapply HT_compose; eauto.\n  apply skipNZ_continuation_spec_NZ; auto.\nQed.\n\nLemma ifNZ_spec_helper: forall v t f Pt Pf Q,\n  HT   t Pt Q ->\n  HT   f Pf Q ->\n  HT   (ifNZ t f)\n       (fun m s => ((v <> 0 -> exists s' l, s = CData (Vint v,l) :: s' /\\ Pt m s') /\\\n                    (v =  0 -> exists s' l, s = CData (Vint v,l) :: s' /\\ Pf m s')))\n       Q.\nProof.\n  intros v l t f Pt Pf Q HTt HTf.\n  eapply HT_decide_join' with (D := fun v => v = 0).\n  apply ifNZ_spec_NZ.\n  apply ifNZ_spec_Z.\n  intros; lia.\n  auto.\n  auto.\nQed.\n\nLemma ifNZ_spec: forall t f Pt Pf Q,\n  HT   t Pt Q ->\n  HT   f Pf Q ->\n  HT   (ifNZ t f)\n       (fun m s => (exists v l s', s = CData (Vint v,l) :: s' /\\\n                                   (v <> 0 -> Pt m s') /\\\n                                   (v =  0 -> Pf m s')))\n       Q.\nProof.\n  intros t f Pt Pf Q HTt HTf.\n  eapply HT_forall_exists. intros v.\n  eapply HT_forall_exists. intros l.\n  eapply HT_forall_exists. intros s'.\n  eapply HT_strengthen_premise.\n  eapply ifNZ_spec_helper; eauto.\n  intros m s (? & H1 & H2). subst.\n  destruct (dec_eq v 0); subst; intuition;\n    eexists; intuition eauto.\nQed.\n\nLemma ite_spec: forall c t f (P Pt Pf: HProp) Q,\n  let P' := fun m s => exists v l s', s = (Vint v,l) ::: s' /\\\n                                      (v <> 0 -> Pt m s') /\\\n                                      (v =  0 -> Pf m s') in\n  HT   c P P' ->\n  HT   t Pt Q ->\n  HT   f Pf Q ->\n  HT   (ite c t f) P Q.\nProof.\n  intros c t f P Pt Pf Q P' HTc HTt HTf.\n  unfold ite.\n  eapply HT_compose.\n  apply HTc.\n  apply ifNZ_spec.\n  auto.\n  auto.\nQed.\n\nLemma cases_spec_base: forall d P Q,\n  HT   d P Q -> HT   (cases nil d) P Q.\nProof.\n  auto.\nQed.\n\nLemma cases_spec_step: forall c b cbs d P (Pt Pf Q: HProp),\n  let P' := fun m s => exists v l s', s = (Vint v,l) ::: s' /\\\n                                      (v <> 0 -> Pt m s') /\\\n                                      (v =  0 -> Pf m s') in\n  HT   c P P' ->\n  HT   b Pt Q ->\n  HT   (cases cbs d) Pf Q ->\n  HT   (cases ((c,b)::cbs) d) P Q.\nProof.\n  intros.\n  eapply ite_spec; eauto.\nQed.\n\n(* [HProp] with ghost variables *)\nDefinition GProp := memory -> stack -> HProp.\n(* Ghost prop Hoare triple *)\nDefinition GT (c: code) (P: HProp) (Q: GProp) := forall m0 s0,\n  HT c (fun m s => P m0 s0 /\\ m = m0 /\\ s = s0)\n       (Q m0 s0).\n\nLemma GT_consequence':\n  forall (c : code) (P' P: HProp) (Q Q': GProp),\n    GT c P Q ->\n    (forall m s, P' m s -> P m s) ->\n    (forall m0 s0 m s, P m0 s0 -> Q m0 s0 m s -> Q' m0 s0 m s) ->\n    GT c P' Q'.\nProof.\n  unfold GT; intros.\n  eapply HT_consequence'; jauto.\nQed.\n\nDefinition HFun  := memory -> stack -> Z.\n\nLemma cases_spec_base_GT_specialized: forall cnil P Qnil,\n  GT cnil P Qnil ->\n  GT (cases [] cnil) P Qnil.\nProof.\nunfold GT; intros; eapply cases_spec_base.\n  eapply HT_strengthen_premise; eauto.\nQed.\n\nDefinition GT_push_v (c: code) (P: HProp) (v: HFun): Prop :=\n  GT c P (fun m0 s0 m s => P m0 s0 /\\\n                           m = m0 /\\\n                           exists t, s = CData (Vint (v m0 s0), t) :: s0).\nDefinition GT_guard_v (b: code) (P: HProp) (v: HFun) (Q: GProp): Prop :=\n  GT b (fun m s => P m s /\\ v m s <> 0) Q.\n\nLemma cases_spec_step_GT_specialized: forall c v b cbs cnil P Qb Qcbs,\n  GT_push_v c P v ->\n  GT_guard_v b P v Qb ->\n  GT (cases cbs cnil) P Qcbs ->\n  GT (cases ((c,b)::cbs) cnil)\n     P\n     (fun m0 s0 m s => (v m0 s0 <> 0 -> Qb m0 s0 m s) /\\\n                       (v m0 s0 = 0 -> Qcbs m0 s0 m s)).\nProof.\n  intros c vc b cbs d P Qb Qcbs Hc Hb Hcbs.\n  intros m0 s0.\n  pose (Hc m0 s0) as Hcm0s0.\n  eapply ite_spec with (Pt := (fun m s => P m0 s0 /\\ m = m0 /\\ s = s0 /\\ vc m0 s0 <> 0))\n                       (Pf := (fun m s => P m0 s0 /\\ m = m0 /\\ s = s0 /\\ vc m0 s0 =  0)).\n  eapply HT_weaken_conclusion.\n  exact Hcm0s0.\n\n  intros m s (POST & ? & t & ?). subst.\n  exists (vc m0 s0).\n  exists t.\n  exists s0.\n  intuition; subst; auto.\n\n  apply (HT_consequence' _ _ _ _ _ _ _ (Hb m0 s0)); intuition.\n  elimtype False; jauto.\n\n  fold cases.\n  apply (HT_consequence' _ _ _ _ _ _ _ (Hcbs m0 s0)); intuition.\n  elimtype False; jauto.\nQed.\n\nSection IndexedCasesSpec.\n\nVariable cnil: code.\nVariable Qnil: GProp.\nVariable I: Type.\nVariable genC genB: I -> code.\nVariable genQ: I -> GProp.\nVariable genV: I -> HFun.\n\n(* XXX: make these folds ? *)\nDefinition indexed_post: (list I) -> GProp :=\n  fix f (indices: list I) :=\n    fun m0 s0 m s =>\n      match indices with\n      | []            => Qnil m0 s0 m s\n      | i :: indices' => (genV i m0 s0 <> 0 -> genQ i m0 s0 m s) /\\\n                         (genV i m0 s0 =  0 -> f indices' m0 s0 m s)\n      end.\n\nVariable P: HProp.\nDefinition indexed_hyps: (list I) -> Prop :=\n  fix f (indices: list I) :=\n    match indices with\n    | []            => True\n    | i :: indices' => GT_push_v (genC i) P (genV i) /\\\n                       GT_guard_v (genB i) P (genV i) (genQ i) /\\\n                       f indices'\n    end.\n\nLemma indexed_cases_spec: forall is,\n  GT cnil P Qnil ->\n  indexed_hyps is ->\n  GT (indexed_cases cnil genC genB is)\n     P\n     (indexed_post is).\nProof.\n  induction is; intros.\n  - eapply cases_spec_base_GT_specialized; eauto.\n  - simpl in *.\n    eapply cases_spec_step_GT_specialized; iauto.\nQed.\n\nEnd IndexedCasesSpec.\n\nSection GT_ext.\n\nDefinition GT_ext (c: code) (P: HProp) (Q: GProp) :=\n  forall m0 s0,\n    HT c\n       (fun m s => P m0 s0 /\\ extends m0 m /\\ s = s0)\n       (Q m0 s0).\n\nLemma GT_consequence'_ext:\n  forall (c : code) (P' P: HProp) (Q Q': GProp),\n    GT_ext c P Q ->\n    (forall m s, P' m s -> P m s) ->\n    (forall m0 s0 m s, P m0 s0 -> Q m0 s0 m s -> Q' m0 s0 m s) ->\n    GT_ext c P' Q'.\nProof.\n  unfold GT_ext; intros.\n  eapply HT_consequence'; jauto.\nQed.\n\nLemma cases_spec_base_GT_ext_specialized: forall cnil P Qnil,\n  GT_ext cnil P Qnil ->\n  GT_ext (cases [] cnil) P Qnil.\nProof.\nunfold GT_ext; intros; eapply cases_spec_base.\n  eapply HT_strengthen_premise; eauto.\nQed.\n\nDefinition GT_push_v_ext (c: code) (P: HProp) (v: HFun): Prop :=\n  GT_ext c P (fun m0 s0 m s => exists t, P m0 s0 /\\\n                               extends m0 m /\\\n                               s = CData (Vint (v m0 s0), t) :: s0).\nDefinition GT_guard_v_ext (b: code) (P: HProp) (v: HFun) (Q: GProp): Prop :=\n  GT_ext b (fun m s => P m s /\\ v m s <> 0) Q.\n\nLemma cases_spec_step_GT_ext_specialized: forall c v b cbs cnil P Qb Qcbs,\n  GT_push_v_ext c P v ->\n  GT_guard_v_ext b P v Qb ->\n  GT_ext (cases cbs cnil) P Qcbs ->\n  GT_ext (cases ((c,b)::cbs) cnil)\n     P\n     (fun m0 s0 m s =>   (v m0 s0 <> 0 -> Qb m0 s0 m s)\n                         /\\ (v m0 s0 = 0 -> Qcbs m0 s0 m s)).\nProof.\n  intros c vc b cbs d P Qb Qcbs Hc Hb Hcbs.\n  intros m0 s0.\n  pose (Hc m0 s0) as Hcm0s0.\n  eapply ite_spec with (Pt := (fun m s => P m0 s0 /\\ extends m0 m /\\ s = s0 /\\ vc m0 s0 <> 0))\n                       (Pf := (fun m s => P m0 s0 /\\ extends m0 m /\\ s = s0 /\\ vc m0 s0 =  0)).\n  - eapply HT_weaken_conclusion.\n    eapply Hc.\n    go_match.\n    split_vc.\n  - eapply HT_consequence'.\n    + eapply Hb; eauto.\n    + intros. intuition.\n      * eapply H0.\n      * elimtype False; jauto.\n      * auto.\n      * auto.\n    + intros.\n      destruct H as [m' [s' [HPm0s0 [Hextm0 [Hs' Hcond]]]]]. substs.\n      split; eauto.\n      intuition.\n  - fold cases.\n    eapply HT_consequence'.\n    eapply Hcbs.\n    simpl. iauto.\n    intros. intuition.\n    elimtype False; jauto.\nQed.\n\nSection IndexedCasesSpec_EXT.\n\nVariable cnil: code.\nVariable Qnil: GProp.\nVariable I: Type.\nVariable genC genB: I -> code.\nVariable genQ: I -> GProp.\nVariable genV: I -> HFun.\n\n(* XXX: make these folds ? *)\nDefinition indexed_post_ext: (list I) -> GProp :=\n  fix f (indices: list I) :=\n    fun m0 s0 m s =>\n      match indices with\n      | []            => Qnil m0 s0 m s\n      | i :: indices' =>\n                         (genV i m0 s0 <> 0 -> genQ i m0 s0 m s) /\\\n                         (genV i m0 s0 =  0 -> f indices' m0 s0 m s)\n      end.\n\nVariable P: HProp.\nDefinition indexed_hyps_ext: (list I) -> Prop :=\n  fix f (indices: list I) :=\n    match indices with\n    | []            => True\n    | i :: indices' => GT_push_v_ext (genC i) P (genV i) /\\\n                       GT_guard_v_ext (genB i) P (genV i) (genQ i) /\\\n                       f indices'\n    end.\n\nLemma indexed_cases_spec_ext: forall is,\n  GT_ext cnil P Qnil ->\n  indexed_hyps_ext is ->\n  GT_ext (indexed_cases cnil genC genB is)\n     P\n     (indexed_post_ext is).\nProof.\n  induction is; intros.\n  - eapply cases_spec_base_GT_ext_specialized; eauto.\n  - simpl in *.\n    eapply cases_spec_step_GT_ext_specialized; iauto.\nQed.\n\nEnd IndexedCasesSpec_EXT.\n\nEnd GT_ext.\n\nLemma some_spec:\n  forall c P Q,\n    HT c P (fun m s => Q m ((Vint 1,handlerTag) ::: s)) ->\n    HT (some c) P Q.\nProof.\n  intros.\n  unfold some.\n  eapply HT_compose; eauto.\n  eapply push_spec.\nQed.\n\nDefinition none_spec     := push_spec.\nDefinition genTrue_spec  := push_spec.\nDefinition genFalse_spec := push_spec.\n\nDefinition ZtoBool (z:Z) :=  negb (z =? 0).\nDefinition valToBool (v : val) :=\n  match v with\n    | Vint 0 => false\n    | _ => true\n  end.\n\nLemma val_eq_int :\n  forall z1 z2,\n    val_eq (Vint z1) (Vint z2) = Vint (boolToZ (z1 =? z2)).\nProof.\n  unfold val_eq.\n  intros.\n  destruct (equiv_dec (Vint z1) (Vint z2)) as [E | E].\n  - inv E. rewrite Z.eqb_refl. reflexivity.\n  - assert (E' : z1 <> z2) by congruence.\n    rewrite <- Z.eqb_neq in E'.\n    rewrite E'. reflexivity.\nQed.\n\nDefinition andv (v1 v2 : val) : val :=\n  if valToBool v1 then v2 else Vint 0.\n\nLemma genAnd_spec: forall (Q:memory -> stack -> Prop),\n  HT genAnd\n     (fun m s => exists v1 t1 v2 t2 s0,\n                   s = (v1,t1):::(v2,t2):::s0 /\\\n                   forall t, Q m ((andv v1 v2,t):::s0))\n     Q.\nProof.\n  intros.\n  eapply HT_forall_exists.  intro v1.\n  eapply HT_forall_exists.  intro t1.\n  eapply HT_forall_exists.  intro v2.\n  eapply HT_forall_exists.  intro t2.\n  eapply HT_forall_exists.  intro s0.\n  unfold genAnd, andv.\n  destruct (valToBool v1) eqn:E.\n  - assert (v1 <> Vint 0). { intro. subst. unfold valToBool in E. congruence. }\n    eapply HT_strengthen_premise.\n    + eapply HT_compose; try eapply push_spec.\n      eapply HT_compose; try eapply genEq_spec.\n      eapply ifNZ_spec_Z with (v:=0); eauto.\n      apply nop_spec.\n    + split_vc.  subst. split_vc. split; eauto.\n      unfold val_eq. destruct (equiv_dec (Vint 0) v1).  congruence. eauto.\n  - assert (v1 = Vint 0). { unfold valToBool in E. destruct v1 as [[]|]; congruence. }\n    eapply HT_strengthen_premise.\n    + eapply HT_compose; try eapply push_spec.\n      eapply HT_compose; try eapply genEq_spec.\n      eapply ifNZ_spec_NZ with (v:=1); try lia.\n      eapply HT_compose; try eapply pop_spec.\n      eapply genFalse_spec.\n    + split_vc. subst. rewrite val_eq_int.\n      split; eauto. split_vc.\nQed.\n\nDefinition orv (v1 v2 : val) : val :=\n  if valToBool v1 then Vint 1 else v2.\n\nLemma genOr_spec : forall (Q:memory -> stack -> Prop),\n  HT genOr\n     (fun m s => exists v1 t1 v2 t2 s0,\n                   s = (v1,t1):::(v2,t2):::s0 /\\\n                   forall t, Q m ((orv v1 v2,t):::s0))\n     Q.\nProof.\n  intros.\n  eapply HT_forall_exists.  intro v1.\n  eapply HT_forall_exists.  intro t1.\n  eapply HT_forall_exists.  intro v2.\n  eapply HT_forall_exists.  intro t2.\n  eapply HT_forall_exists.  intro s0.\n  intros.\n  unfold genOr, orv.\n  destruct (valToBool v1) eqn:E.\n  - assert (v1 <> Vint 0). { intro. subst. unfold valToBool in E. congruence. }\n    eapply HT_strengthen_premise.\n    + eapply HT_compose; try eapply push_spec.\n      eapply HT_compose; try eapply genEq_spec.\n      eapply ifNZ_spec_Z with (v:=0); eauto.\n      eapply HT_compose; try eapply pop_spec.\n      eapply genTrue_spec.\n    + split_vc. subst. split_vc. split; eauto.\n      unfold val_eq. destruct (equiv_dec (Vint 0) v1).  congruence. eauto.\n  - assert (v1 = Vint 0). { unfold valToBool in E. destruct v1 as [[]|]; congruence. }\n    eapply HT_strengthen_premise.\n    + eapply HT_compose; try eapply push_spec.\n      eapply HT_compose; try eapply genEq_spec.\n      eapply ifNZ_spec_NZ with (v:=1); try lia.\n      eapply nop_spec.\n    + split_vc. subst. rewrite val_eq_int. split; eauto.\nQed.\n\nLemma genNot_spec : forall Q : _ -> _ -> Prop,\n  HT genNot\n     (fun m s => exists v t s0,\n                   s = (Vint v, t) ::: s0 /\\\n                   forall t', Q m ((Vint (boolToZ (v =? 0)),t') ::: s0))\n     Q.\nProof.\n  intros Q.\n  eapply HT_forall_exists. intros v.\n  eapply HT_forall_exists. intros t.\n  eapply HT_forall_exists. intros s0.\n  intros.\n  unfold genNot.\n  cases (0 =? v) as Heq.\n  - apply Z.eqb_eq in Heq. subst.\n    eapply HT_strengthen_premise.\n    + eapply HT_compose; try eapply push_spec.\n      eapply genEq_spec.\n    + split_vc. subst. split_vc. rewrite val_eq_int. simpl. auto.\n  - eapply HT_strengthen_premise.\n    + eapply HT_compose; try eapply push_spec.\n      eapply genEq_spec.\n    + split_vc. subst. split_vc. rewrite val_eq_int. rewrite Z.eqb_sym. eauto.\nQed.\n\nLemma genTestEqual_spec:\n  forall c1 c2 (P Q R : HProp),\n    HT c2 Q (fun m s => exists v1 t1 v2 t2 s0,\n                          s = (v1,t1) ::: (v2,t2) ::: s0 /\\\n                          forall t',\n                            R m ((val_eq v1 v2, t') ::: s0)) ->\n    HT c1 P Q ->\n    HT (genTestEqual c1 c2) P R.\nProof.\n  intros.\n  unfold genTestEqual.\n  eapply HT_compose; eauto.\n  eapply HT_compose; eauto.\n  eapply HT_strengthen_premise; try eapply genEq_spec.\n  intros m s (v1 & t1 & v2 & t2 & s0 & ? & ?). subst.\n  repeat eexists. eauto.\nQed.\n\n(* ********* Specifications for loops **************** *)\n\nLemma genLoop_spec: forall c I,\n(forall i, 0 < i ->\n  HT c\n     (fun m s => exists s' t, s = CData (Vint i,t) :: s' /\\ I m s)\n     (fun m s => exists i' s' t, s = CData (Vint i',t) :: s' /\\ I m (CData (Vint i',t) :: s') /\\ 0 <= i' < i)) ->\nHT (genLoop c)\n     (fun m s => exists i, 0 < i /\\ exists s' t, s = CData (Vint i,t) :: s' /\\ I m s)\n     (fun m s => exists s' t, s = CData (Vint 0,t) :: s' /\\ I m s).\nProof.\n  intros c I P.\n  eapply HT_forall_exists. intros i.\n  eapply HT_fold_constant_premise. intros H.\n  unfold genLoop, dup.\n  assert (0 <= i) by lia. generalize dependent H.\n  set (Q := fun i => 0 < i ->\n   HT (c ++ [Dup 0] ++ [BranchNZ (- Z.of_nat (length (c ++ [Dup 0])))])\n     (fun (m : memory) (s : stack) => exists s' t, s = (Vint i, t) ::: s' /\\ I m s)\n     (fun (m : memory) (s : stack) => exists s' t, s = (Vint 0, t) ::: s' /\\ I m s)).\n  generalize dependent i.\n  eapply (Zlt_0_ind Q); unfold Q; clear Q.\n  intros i.\n  unfold CodeTriples.HT in *. intros.\n  destruct H3 as [s' [t' [P1 P2]]].\n\n  edestruct P as [stk1 [cache1 [[i' [s'' [t'' [Q1 [Q2 Q3]]]]] Q4]]].\n  eauto.\n  eapply code_at_compose_1; eauto.\n  eexists. eexists. split. eauto. subst stk0.  eauto. eauto.\n  subst stk1.\n  replace (@nil CEvent) with (@nil CEvent ++ @nil CEvent) by auto.\n  pose proof (code_at_compose_2 _ _ _ _ H2).\n  pose proof (code_at_compose_1 _ _ _ _ H3).\n  pose proof (code_at_compose_2 _ _ _ _ H3).\n  clear H3.\n  unfold code_at in H5,H6. intuition.\n  rewrite app_length in H4, H5. simpl in H4, H5.\n\n  destruct (i =? 0) eqn:EQ.\n\n  (* impossible *)\n  apply Z.eqb_eq in EQ. subst i. inv H1.  clear EQ.\n\n  destruct (i' =? 0) eqn: EQ.\n\n  - (* no loop *)\n  apply Z.eqb_eq in EQ. subst i'.\n  eexists. eexists. split. eexists. eexists. split. eauto. eauto.\n  eapply runsToEnd_trans.\n  eapply Q4. clear Q4.\n\n  eapply runsToEnd_trans.\n  eapply rte_step; eauto.\n  eapply cstep_dup_p; eauto.  simpl. eauto.\n  subst.\n  eapply rte_step; eauto.\n  eapply cstep_branchnz_p'; eauto.\n  destruct (0 =? 0) eqn:E.\n     eapply rte_refl; eauto.\n     inv E.\n  replace (n + Z.of_nat (length c) + 1 + 1) with (n + Z.of_nat (length c + 2)) by (zify; lia). subst n'. eauto.\n\n  - (* loop *)\n  assert (i' <> 0).  eapply Z.eqb_neq;  eauto.\n  edestruct H as [stk3 [cache3 [[s''' [t''' [R1 R2]]] R3]]].\n  instantiate (1:= i').  lia.\n  zify; lia.\n  eauto.\n  exists s''.  eauto. eauto.\n  eexists.  eexists. split. eexists. eexists. split. eauto. eauto.\n  eapply runsToEnd_trans.\n  eapply Q4.  clear Q4.\n  repeat rewrite app_length in *. simpl in R3.\n  eapply runsToEnd_trans.\n  eapply rte_step.  eauto.\n  eapply cstep_dup_p; eauto.\n  simpl; eauto.\n  eapply rte_step; eauto.\n  eapply cstep_branchnz_p'; eauto.\n  rewrite EQ. zify ; lia.\n  subst.\n  eapply rte_refl; auto.\n\nQed.\n\nLemma genFor_spec :\n  forall I c (Q : HProp)\n         (HTc : forall i,\n                  i > 0 ->\n                  exists Pc,\n                    HT c Pc\n                       (fun m s => exists t s', s = (Vint i, t) ::: s' /\\ I Q m s' (Z.pred i)) /\\\n                    forall m s t, I Q m s i -> Pc m ((Vint i,t):::s))\n         (VC : forall m s t, I Q m s 0 -> Q m ((Vint 0,t):::s)),\n    HT (genFor c)\n       (fun m s => exists i t s',\n                     s = (Vint i,t) ::: s' /\\\n                     i >= 0 /\\\n                     I Q m s' i)\n       Q.\nProof.\n  intros.\n  unfold genFor.\n  eapply HT_strengthen_premise.\n  { eapply HT_compose; try eapply dup_spec.\n    eapply ifNZ_spec; try eapply nop_spec.\n    eapply HT_weaken_conclusion; try eapply genLoop_spec\n                                     with (I := fun m s =>\n                                                  exists i ti s',\n                                                    s = (Vint i, ti) ::: s' /\\\n                                                    I Q m s' i).\n    { intros.\n      assert (POS : i > 0) by lia.\n      specialize (HTc i POS). clear POS.\n      destruct HTc as (Pc & HTc & POST).\n      eapply HT_strengthen_premise.\n      { unfold push.\n        eapply HT_compose; try eapply HTc.\n        eapply HT_strengthen_premise.\n        { eapply HT_compose; try eapply push_spec.\n          eapply add_spec. }\n        intros m s (? & s' & ? & INV). subst.\n        do 6 eexists. split; eauto.\n        split; [reflexivity|].\n        replace (-1 + i) with (Z.pred i) by lia.\n        do 3 eexists. split; eauto.\n        split; eauto.\n        lia. }\n      intros m s (s' & t & ? & i' & ? & s'' & ? & ?). subst.\n      assert (i' = i) by congruence.\n      assert (s'' = s') by congruence. subst. eauto. }\n    intros m s (s' & t & ? & i & ? & s'' & ? & ?).\n    assert (i = 0) by congruence.\n    assert (s'' = s') by congruence. subst. eauto. }\n\n  intros m s (i & t & s' & ? & ? & ?). subst. simpl.\n  eexists. split; eauto.\n  do 3 eexists. split; eauto. split.\n  - intros. eexists. split; [|do 2 eexists; split; eauto]. lia.\n  - intros. subst. eauto.\nQed.\n\nLemma ret_specEscape: forall raddr (Q: memory -> stack -> Prop * Outcome),\n  HTEscape raddr [Ret]\n    (fun m s => exists s', s = (CRet raddr false false::s') /\\\n                           let (prop, outcome) := Q m s' in\n                           prop /\\ outcome = Success)\n    Q.\nProof.\n  intros. cases raddr; subst.\n  unfold CodeTriples.HTEscape.\n  intros imem stk0 mem0 fh n CODE (s' & ? & H). subst.\n  eexists s', mem0. destruct (Q mem0 s') as [prop outcome].\n  intuition. subst.\n  repeat eexists.\n  eauto.\n\n  (* Load an instruction *)\n  subst.\n  unfold code_at in *. intuition.\n\n  (* Run an instruction *)\n  eapply rte_success; auto.\n  eapply ruu_end; simpl; eauto.\n  eapply cstep_ret_p; eauto.\n  eapply cptr_done.\nQed.\n\nLemma jump_specEscape_Failure: forall raddr (Q: memory -> stack -> Prop * Outcome),\n  HTEscape raddr [Jump]\n           (fun m s => exists tag s0, (Vint (-1), tag) ::: s0 = s /\\\n                                      let (prop, outcome) := Q m s0 in\n                                      prop /\\ outcome = Failure)\n           Q.\nProof.\n  intros.\n  unfold CodeTriples.HTEscape.\n  intros imem stk0 mem0 fh n CODE (tag & s0 & ? & H). subst.\n  eexists s0, mem0.\n  destruct (Q mem0 s0) as [prop outcome]. destruct H; subst.\n  simpl.\n  repeat eexists.\n  eauto.\n\n  (* Load an instruction *)\n  subst.\n  unfold code_at in *. intuition.\n\n  (* Run an instruction *)\n  eapply rte_fail; auto.\n  eapply rte_step; eauto.\n  eapply cstep_jump_p; eauto.\n  simpl; eauto; lia.\nQed.\n\nLemma skipNZ_specEscape: forall r c1 c2 v P1 P2 Q,\n  (v =  0 -> HTEscape r c1 P1 Q) ->\n  (v <> 0 -> HTEscape r c2 P2 Q) ->\n  HTEscape r ((skipNZ (length c1) ++ c1) ++ c2)\n           (fun m s => exists s0 l, s = (Vint v, l) ::: s0 /\\\n                                    (v =  0 -> P1 m s0) /\\\n                                    (v <> 0 -> P2 m s0))\n           Q.\nProof.\n  intros.\n  unfold skipNZ.\n  destruct (dec_eq v 0); subst.\n  - eapply HTEscape_append.\n    eapply HTEscape_compose.\n    eapply skipNZ_spec_Z; auto.\n    eapply HTEscape_strengthen_premise; iauto.\n  - eapply HTEscape_compose.\n    eapply skipNZ_continuation_spec_NZ; auto.\n    eapply HTEscape_strengthen_premise; iauto.\nQed.\n\nLemma ifNZ_specEscape: forall r t f v Pt Pf Q,\n  (v <> 0 -> HTEscape r t Pt Q) ->\n  (v =  0 -> HTEscape r f Pf Q) ->\n  HTEscape r (ifNZ t f)\n           (fun m s => exists s0 t, s = (Vint v, t) ::: s0 /\\\n                                    (v <> 0 -> Pt m s0) /\\\n                                    (v =  0 -> Pf m s0))\n           Q.\nProof.\n  intros.\n  unfold ifNZ.\n  rewrite <- app_ass.\n  eapply HTEscape_strengthen_premise.\n  eapply skipNZ_specEscape with (v:=v).\n  - intros.\n    eapply HTEscape_append; eauto.\n  - intros.\n    eauto.\n  - jauto.\nQed.\n\nLemma genSysRet_specEscape_Some: forall raddr (Q: memory -> stack -> Prop * Outcome),\n  HTEscape raddr genSysRet\n           (fun m s =>\n              exists s0,\n              s = (Vint 1, handlerTag) ::: CRet raddr false false :: s0 /\\\n              let (prop, outcome) := Q m s0 in\n              prop /\\ outcome = Success)\n           Q.\nProof.\n  intros.\n  unfold genSysRet.\n  eapply HTEscape_strengthen_premise.\n  - eapply ifNZ_specEscape with (v:=1) (Pf:=fun m s => True); intros; try assumption.\n    eapply ret_specEscape; try assumption.\n    false.\n  - subst.\n    intuition. split_vc.\nQed.\n\nLemma genError_specEscape: forall raddr (P: memory -> stack -> Prop * Outcome),\n  HTEscape raddr genError\n           (fun m s => let (prop, outcome) := P m s in\n                       prop /\\ outcome = Failure)\n           P.\nProof.\n  intros.\n  unfold genError.\n  eapply HTEscape_strengthen_premise.\n  { eapply HTEscape_compose; try eapply push_spec.\n    eapply jump_specEscape_Failure. }\n  simpl.\n  intros m s H.\n  repeat eexists; eauto.\nQed.\n\nLemma genSysRet_specEscape_None: forall raddr s0 m0,\n HTEscape raddr genSysRet\n   (fun m s => (extends m0 m /\\ s = (Vint 0, handlerTag) ::: s0))\n   (fun m s => (extends m0 m /\\ s = s0, Failure)).\nProof.\n  intros.\n  unfold genSysRet.\n  eapply HTEscape_strengthen_premise.\n  - eapply ifNZ_specEscape with (v := 0) (Pt := fun m s => True); intros; try assumption.\n    + intuition.\n    + eapply genError_specEscape.\n  - intros.\n    subst.\n    intuition.\n    jauto_set_goal; eauto.\nQed.\n\nLemma genSysVRet_spec :\n  forall raddr (Q : memory -> stack -> Prop * Outcome),\n    HTEscape raddr genSysVRet\n             (fun m s =>  (exists t atom s0,\n                             s = (Vint 1, t) ::: atom ::: CRet raddr true false :: s0 /\\\n                             let (prop, outcome) := Q m (atom ::: s0) in\n                             prop /\\ outcome = Success) \\/\n                          (exists t s0, s = (Vint 0, t) ::: s0 /\\\n                                        let (prop, outcome) := Q m s0 in\n                                        prop /\\ outcome = Failure))\n             Q.\nProof.\n  intros.\n  unfold genSysVRet.\n  destruct raddr as [pcret pcrett].\n  intros code stk0 mem0 fh n code_at [H | H].\n  - destruct H as (t & [resv resl] & s0 & STK & POST).\n    simpl in *. destruct code_at as (H1 & H2 & H3 & H4 & H5 & H6 & _).\n    eexists ((resv, resl) ::: s0), mem0. repeat eexists.\n    destruct (Q mem0 ((resv, resl) ::: s0)) as [prop outcome]. destruct POST.\n    simpl in *. subst. simpl. repeat (split; auto).\n    eapply rte_success.\n    eapply ruu_step; eauto.\n    { eapply cstep_branchnz_p'; eauto. } simpl.\n    replace (n + 5) with (n + 1 + 1 + 1 + 1 + 1) by ring.\n    eapply ruu_end; eauto.\n    eapply cstep_vret_p; eauto.\n    eapply cptr_done.\n  - destruct H as (t & s0 & STK & POST).\n    simpl in *. destruct code_at as (H1 & H2 & H3 & H4 & H5 & H6 & _).\n    eexists s0, mem0. repeat eexists.\n    destruct (Q mem0 s0) as [prop outcome]. destruct POST.\n    simpl in *. subst. simpl. repeat (split; auto).\n    eapply rte_fail; simpl; try lia.\n    eapply rte_step; try reflexivity.\n    { eapply cstep_branchnz_p'; eauto. } simpl.\n    eapply rte_step; try reflexivity.\n    { clear H4. eapply cstep_push_p; eauto. }\n    eapply rte_step; try reflexivity.\n    { eapply cstep_jump_p; eauto. }\n    eauto.\nQed.\n\nEnd CodeSpecs.\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/CodeSpecs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.27003092000884216}}
{"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     SecureDNS.\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\nModule SecureDNSProtocolSecure <: AutomatedSafeProtocolSS.\n\n  Import SecureDNSProtocol.\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 realServerbrt_bodybrt :\n    forall t n (cmd : RealWorld.user_cmd t),\n      boundRunningTime cmd n\n      -> forall (tv : RealWorld.denote t) n__iter,\n        exists n__server, boundRunningTime (realServer n__iter tv cmd) n__server.\n  Proof.\n    induction n__iter; intros.\n    - rewrite realserver_done.\n      eexists; find_runtime.\n    - erewrite unroll_realserver_step; eauto.\n      split_ex.\n      eexists; find_runtime.\n      \n      Unshelve.\n      exact 0.\n  Qed.\n\n  Lemma finitelyRuns : exists n, runningTimeMeasure ru0 n.\n  Proof.\n    autounfold; simpl.\n    repeat \n      match goal with\n      | [ |- context [realServer _ _ ?cmd] ] =>\n        match goal with\n        | [ H : exists _, boundRunningTime cmd _ |- _ ] => fail 1\n        | _ => let BRT := fresh \"BRT\" in\n              assert (exists n, boundRunningTime cmd n) as BRT by (eexists; simpl; find_runtime)\n        end\n      end\n    ; split_ex\n    ; repeat\n        match goal with\n        | [ H : boundRunningTime ?cmd _ |- context [ realServer ?n ?dv ?cmd ] ] =>\n          pose proof (realServerbrt_bodybrt H dv n); clear H\n        end\n    ; split_ex.\n    \n    eexists; econstructor; simpl; find_runtime; eauto.\n\n    Unshelve.\n    all: exact 0.\n  Qed.\n\n  Lemma realServerss_bodyss :\n    forall t uid uids ctx (cmd : RealWorld.user_cmd (RealWorld.Base t)) cs (usrs : RealWorld.honest_users t) sty,\n      syntactically_safe uid uids ctx cmd sty\n      -> typingcontext_sound ctx usrs cs uid\n      -> forall tv n,\n          exists sty__s ctx__s,\n            List.Forall (fun styp => List.In styp ctx__s) ctx\n            /\\ syntactically_safe uid uids ctx__s (realServer n tv cmd) sty__s\n            /\\ typingcontext_sound ctx__s usrs cs uid.\n  Proof.\n    induct n; intros.\n    - rewrite realserver_done.\n      (do 2 eexists); eauto.\n    - erewrite unroll_realserver_step; eauto.\n      split_ex.\n      (do 2 eexists); repeat simple apply conj; eauto.\n      econstructor; intros; eauto using syntactically_safe_add_ctx.\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    match goal with\n    | [ |- exists _ _, syntactically_safe ?uid ?uids _ (realServer ?n ?tv ?cmd) _\n               /\\ typingcontext_sound _ ?usrs ?cs ?uid ] =>\n      assert (exists sty ctx, syntactically_safe uid uids ctx cmd sty\n                         /\\ typingcontext_sound ctx usrs cs uid)\n    end.\n\n    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    split_ex.\n\n    match goal with\n    | [ SS : syntactically_safe _ _ _ ?cmd _, TCS : typingcontext_sound _ _ _ _\n        |- context [ realServer ?n ?tv ?cmd ] \n      ] =>\n      pose proof ( realServerss_bodyss SS TCS tv n)\n      ; clear SS TCS\n      ; split_ex\n    end\n    ; (do 2 eexists); split; eauto.\n\n    Unshelve.\n    all: exact true.\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  (* Show Ltac Profile \"churn2\". *)\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; simpl in *; 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 SecureDNSProtocolSecure.\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/SecureDNSSecure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2699379075311945}}
{"text": "Require Import Semantics.\n(* type_remove *)\nRequire Import Semantics_Conv.\nRequire Import OptionMap2.\nRequire Import FMapFacts.\nRequire Import AccessRights.\nRequire Import AccessRightSets.\nRequire Import References.\nRequire Import RefSets.\nRequire Import Capabilities.\nRequire Import Indices.\nRequire Import Objects.\nRequire Import SystemState.\nRequire Import SemanticsDefinitions.\nRequire Import Semantics.\n\nModule MakeSemanticsConv (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) (Sem: SemanticsType Ref RefS Cap Ind Obj Sys SemDefns) : SemanticsConv Ref RefS Cap Ind Obj Sys SemDefns Sem.\n\nRequire Import SystemState_ConvImpl.\n\n  Module SC := SemDefns.SC.\n  Module OC := SC.OC.\n  Module CC := SC.CC.\n\n\n  Module CIL_Facts := SC.CIL_Facts.\n  (* type_remove *)\n  Module Sys_MapEquiv := SC.Sys_MapEquiv.\n\n  (* type_remove *)\n  Definition SysEQ := SC.SysEQ.\n  (* type_remove *)\n  Definition CapEQ := CC.CapEQ.\n  (* type_remove *)\n  Definition ObjEQ := OC.ObjEQ.\n  (* type_remove *)\n  Definition RefEQ := CC.RefEQ.\n  (* type_remove *)\n  Definition IndEQ := OC.IndEQ.\n  (* type_remove *)\n  Definition PEQ := SC.PEQ.\n\n  Hint Resolve SC.addCap_eq.\n  Hint Resolve ARSet.eq_refl.\n  Hint Resolve Cap.mkCap_eq.\n  Hint Immediate Sys.eq_sym.\n\n  Theorem do_store_eq : forall a a' t t' c c' i i' s s',\n    Sys.eq s s' ->\n    Ref.eq a a' ->\n    Ind.eq t t' ->\n    Ind.eq c c' ->\n    Ind.eq i i' ->\n    Sys.eq (Sem.do_store a t c i s) (Sem.do_store a' t' c' i' s').\n  Proof.\n    intros.\n    case (SemDefns.store_preReq_dec a t s); simpl; intros.\n    \n    (* case where preReq occurs *)\n    eapply Sys.eq_trans. eapply Sem.store_valid; auto.\n    eapply SemDefns.store_preReq_eq_iff in s0;\n      [\n      |apply Ref.eq_sym in H0; apply H0\n      |apply Ind.eq_sym in H1; apply H1\n      |apply Sys.eq_sym in H; apply H].\n    eapply Sys.eq_sym. eapply Sys.eq_trans. eapply Sem.store_valid; auto.\n\n    apply option_map1_Equiv with\n      (EqA := RefEQ)\n      (EqB := SysEQ); try apply SemDefns.option_target_eq; try apply Ref.eq_sym; eauto.\n    (* probably a new theorem here *)\n    unfold option_map1_compat_op.\n    intros.\n    unfold SC.copyCap.\n    eapply option_map1_Equiv with\n      (EqA := CapEQ)\n      (EqB := SysEQ); try apply SC.getCap_eq; try apply Ref.eq_sym; auto.\n    (* probably a new theorem here *)\n    unfold option_map1_compat_op.\n    intros.\n    unfold SC.addCap.\n    eapply option_map1_Equiv with\n      (EqA := ObjEQ)\n      (EqB := SysEQ); try apply SC.getObj_eq; auto.\n    (* probably a new theorem here *)\n    unfold option_map1_compat_op.\n    intros.\n    unfold SC.updateObj.\n    eapply option_map1_Equiv with\n      (EqA := PEQ)\n      (EqB := SysEQ); try apply SC.getObjTuple_eq; eauto.\n    (* probably a new theroem here *)\n    unfold option_map1_compat_op.\n    intros.\n    (* And here is the meat of the theorem *)\n    unfold SC.addObjTuple.\n    unfold SC.update_pair_object. \n    repeat progress (destruct a3; destruct a'3).\n    repeat progress (destruct p; destruct p0).\n    simpl in *.\n    repeat progress destruct H7.\n    apply SC.addObjTuple_eq; auto.\n    unfold Sys.P.eq. \n    simpl.\n    repeat progress (split; auto).\n    apply OC.addCap_eq; auto.\n    (* and the case where things are not equal *)\n    eapply Sys.eq_trans. eapply Sem.store_invalid; auto.    \n    eapply Sys.eq_sym. eapply Sys.eq_trans;[ eapply Sem.store_invalid; auto|auto].\n    intro n'. apply n.\n    eapply SemDefns.store_preReq_eq_iff in n'; eauto.\n  Qed.\n\n  Theorem do_send_eq : forall a a' t t' cil cil' op_i op_i' s s',\n    Sys.eq s s' ->\n    Ref.eq a a' ->\n    Ind.eq t t' ->\n    CIL_Facts.cil_eq cil cil' ->\n    option_map_eq Ind.eq op_i op_i' ->\n    Sys.eq (Sem.do_send a t cil op_i s) (Sem.do_send a' t' cil' op_i' s').\n  Proof.\n    intros.\n    case (SemDefns.send_preReq_dec a t s); simpl; intros.\n    eapply Sys.eq_trans. eapply Sem.send_valid; auto.\n    eapply SemDefns.send_preReq_eq_iff in s0;\n      [\n      |apply Ref.eq_sym in H0; apply H0\n      |apply Ind.eq_sym in H1; apply H1\n      |apply Sys.eq_sym in H; apply H].\n    eapply Sys.eq_sym. eapply Sys.eq_trans. eapply Sem.send_valid; auto.\n\n\n    Ltac apply_cil_sym := let cil_sym := fresh \"cil_sym\" in \n        destruct CIL_Facts.cil_Equiv as [_ cil_sym _]; unfold Symmetric in cil_sym; apply cil_sym.\n\n    Hint Extern 1 (CIL_Facts.cil_eq _ _) => apply_cil_sym.\n\n    eapply option_map1_Equiv with\n      (EqA := RefEQ)\n      (EqB := SysEQ); try apply SemDefns.option_target_eq; try apply Ref.eq_sym; auto.\n    (* probably a new theorem here *)\n    unfold option_map1_compat_op.\n    intros.\n    apply SC.copyCapList_eq; try apply Ref.eq_sym; eauto.\n    destruct op_i; destruct op_i'.\n    simpl in *.\n    unfold SC.addCap.\n    eapply option_map1_Equiv with\n      (EqA := ObjEQ)\n      (EqB := SysEQ); try apply SC.getObj_eq; auto.\n    unfold option_map1_compat_op; intros.\n    unfold SC.updateObj.\n    eapply option_map1_Equiv with\n      (EqA := PEQ)\n      (EqB := SysEQ); simpl in *;  try apply SC.getObjTuple_eq; auto.\n    (*case 1*)\n    unfold option_map1_compat_op; intros.\n    apply SC.addObjTuple_eq; auto.\n    repeat progress destruct a2; destruct a'2.\n    repeat progress destruct p0.\n    repeat progress destruct p.\n    repeat progress destruct H6.\n    unfold Sys.P.eq; simpl.\n    simpl in *.\n    repeat progress split; auto.\n    apply OC.addCap_eq; auto.\n    apply CC.mkCap_equiv; try apply Ref.eq_sym; auto.\n    \n    (* next 3 cases *)\n    unfold option_map_eq in H3; simpl in H3; contradiction.\n    unfold option_map_eq in H3; simpl in H3; contradiction.\n    simpl; auto.\n\n    (* and the case where things are not equal *)\n    eapply Sys.eq_trans. eapply Sem.send_invalid; auto.    \n    eapply Sys.eq_sym. eapply Sys.eq_trans;[ eapply Sem.send_invalid; auto|auto].\n    intro n'. apply n.\n    eapply SemDefns.send_preReq_eq_iff in n'; eauto.\n  Qed.\n\nTheorem do_revoke_eq : forall a a' t t' c c' s s',\n    Sys.eq s s' ->\n    Ref.eq a a' ->\n    Ind.eq t t' ->\n    Ind.eq c c' ->\n    Sys.eq (Sem.do_revoke a t c s) (Sem.do_revoke a' t' c' s').\n  Proof.\n    intros.\n    case (SemDefns.revoke_preReq_dec a t s); simpl; intros.\n    eapply Sys.eq_trans. eapply Sem.revoke_valid; auto.\n    eapply SemDefns.revoke_preReq_eq_iff in r;\n      [|apply Ref.eq_sym in H0; apply H0\n       |apply Ind.eq_sym in H1; apply H1\n       |apply Sys.eq_sym in H; apply H].\n    eapply Sys.eq_sym. eapply Sys.eq_trans. eapply Sem.revoke_valid; auto.\n\n    eapply option_map1_Equiv with\n      (EqA := RefEQ)\n      (EqB := SysEQ); try apply SemDefns.option_target_eq; try apply Ref.eq_sym; auto.\n    (* probably a new theorem here *)\n    unfold option_map1_compat_op.\n    intros.\n    unfold SC.rmCap.\n    eapply option_map1_Equiv with\n      (EqA := ObjEQ)\n      (EqB := SysEQ); try apply SC.getObj_eq; auto.\n    (* probably a new theorem here *)\n    unfold option_map1_compat_op.\n    intros.\n    unfold SC.updateObj.\n    eapply option_map1_Equiv with\n      (EqA := PEQ)\n      (EqB := SysEQ); simpl;  try apply SC.getObjTuple_eq; auto.\n    (* probably a new theorem here *)\n    unfold option_map1_compat_op.\n    intros.\n    (* And here is the meat of the theorem *)\n    apply SC.addObjTuple_eq; auto.\n    unfold SC.update_pair_object.\n    repeat progress destruct a2; destruct a'2.\n    repeat progress destruct p0.\n    repeat progress destruct p.\n    repeat progress destruct H5.\n    unfold Sys.P.eq.\n    simpl in *.\n    repeat progress split; auto.\n    apply OC.removeCap_eq; auto. \n    (* and the case where things are not equal *)\n    eapply Sys.eq_trans. eapply Sem.revoke_invalid; auto.    \n    eapply Sys.eq_sym. eapply Sys.eq_trans;[ eapply Sem.revoke_invalid; auto|auto].\n    intro n'. apply n.\n    eapply SemDefns.revoke_preReq_eq_iff in n'; eauto.\n  Qed.\n\n  Theorem do_destroy_eq : forall a a' t t' s s',\n    Sys.eq s s' ->\n    Ref.eq a a' ->\n    Ind.eq t t' ->\n    Sys.eq (Sem.do_destroy a t s) (Sem.do_destroy a' t' s').\n  Proof.\n    intros.\n    case (SemDefns.destroy_preReq_dec a t s); simpl; intros.\n    eapply Sys.eq_trans. eapply Sem.destroy_valid; auto.\n    eapply SemDefns.destroy_preReq_eq_iff in d;\n      [|apply Ref.eq_sym in H0; apply H0\n       |apply Ind.eq_sym in H1; apply H1\n       |apply Sys.eq_sym in H; apply H].\n    eapply Sys.eq_sym. eapply Sys.eq_trans. eapply Sem.destroy_valid; auto.\n    eapply option_map1_Equiv with\n      (EqA := RefEQ)\n      (EqB := SysEQ); try apply SemDefns.option_target_eq; try apply Ref.eq_sym; auto.\n    unfold option_map1_compat_op.\n    intros.\n    (* probably a new theorem here *)\n    unfold SC.set_dead.\n    unfold SC.set_label.\n    eapply option_map1_Equiv with\n      (EqA:=PEQ)\n      (EqB:=SysEQ); try apply SC.getObjTuple_eq; auto.\n    (* the meat of the theorem *)\n    unfold option_map1_compat_op.\n    intros.\n    apply SC.addObjTuple_eq; auto.\n    unfold SC.update_pair_label.\n    repeat progress destruct a1; destruct a'1.\n    repeat progress destruct p0.\n    repeat progress destruct p.\n    repeat progress destruct H3.\n    (* TODO: really want a remove and relabel eq *)\n    unfold Sys.P.eq.\n    simpl in *.\n    repeat progress split; auto.\n    (* and the case where things are not equal *)\n    eapply Sys.eq_trans. eapply Sem.destroy_invalid; auto.    \n    eapply Sys.eq_sym. eapply Sys.eq_trans;[ eapply Sem.destroy_invalid; auto|auto].\n    intro n'. apply n.\n    eapply SemDefns.destroy_preReq_eq_iff in n'; eauto.\n  Qed.\n\n  Theorem do_read_eq : forall a a' t t' s s',\n    Sys.eq s s' ->\n    Ref.eq a a' ->\n    Ind.eq t t' ->\n    Sys.eq (Sem.do_read a t s) (Sem.do_read a' t' s').\n  Proof.\n    intros.\n    eapply Sys.eq_trans. eapply Sem.read_spec; auto.\n    eapply Sys.eq_sym. eapply Sys.eq_trans. eapply Sem.read_spec; auto.\n    eapply Sys.eq_sym; auto.\n  Qed.\n\n  Theorem do_write_eq : forall a a' t t' s s',\n    Sys.eq s s' ->\n    Ref.eq a a' ->\n    Ind.eq t t' ->\n    Sys.eq (Sem.do_write a t s) (Sem.do_write a' t' s').\n  Proof.\n    intros.\n    eapply Sys.eq_trans. eapply Sem.write_spec; auto.\n    eapply Sys.eq_sym. eapply Sys.eq_trans. eapply Sem.write_spec; auto.\n    eapply Sys.eq_sym; auto.\n  Qed.\n\nTheorem do_fetch_eq : forall a a' t t' c c' i i' s s',\n    Sys.eq s s' ->\n    Ref.eq a a' ->\n    Ind.eq t t' ->\n    Ind.eq c c' ->\n    Ind.eq i i' ->\n    Sys.eq (Sem.do_fetch a t c i s) (Sem.do_fetch a' t' c' i' s').\n  Proof.\n    intros.\n    case (SemDefns.fetch_preReq_dec a t s); simpl; intros.\n    (* case where preReq occurs *)\n    generalize f; intros [Hf Hf'].\n    case (SemDefns.option_hasRight_dec (SC.getCap t a s) rd); intros Hread.\n    (* read case *)\n    eapply Sys.eq_trans. eapply Sem.fetch_read; auto.\n    eapply SemDefns.fetch_preReq_eq_iff in f;\n      [|apply Ref.eq_sym in H0; apply H0\n       |apply Ind.eq_sym in H1; apply H1\n       |apply Sys.eq_sym in H; apply H].\n    eapply Sys.eq_sym. eapply Sys.eq_trans. eapply Sem.fetch_read; auto.\n    eapply SemDefns.option_hasRight_eq;\n     [eapply Ind.eq_sym; eauto | apply Ref.eq_sym; eauto | apply Sys.eq_sym; eauto | apply AccessRight.eq_refl | eauto].\n    \n    \n    eapply option_map1_Equiv with\n      (EqA := RefEQ) \n      (EqB := SysEQ); try apply SemDefns.option_target_eq; try apply Ref.eq_sym; auto.\n    (* probably a new theorem here *)\n    unfold option_map1_compat_op.\n    intros.\n    unfold SC.copyCap.\n    eapply option_map1_Equiv with\n      (EqA := CapEQ)\n      (EqB := SysEQ); try apply SC.getCap_eq; auto.\n    (* probably a new theorem here *)\n    unfold option_map1_compat_op.\n    intros.\n    unfold SC.addCap.\n    eapply option_map1_Equiv with\n      (EqA := ObjEQ)\n      (EqB := SysEQ); try apply SC.getObj_eq; try apply Ref.eq_sym; auto.\n    (* probably a new theorem here *)\n    unfold option_map1_compat_op.\n    intros.\n    unfold SC.updateObj.\n    eapply option_map1_Equiv with\n      (EqA := PEQ)\n      (EqB := SysEQ); try apply SC.getObjTuple_eq; try apply Ref.eq_sym; auto.\n    (* probably a new theroem here *)\n    unfold option_map1_compat_op.\n    intros.\n    (* And here is the meat of the theorem *)\n    unfold SC.addObjTuple.\n    unfold SC.update_pair_object. \n    repeat progress destruct a3; destruct a'3.\n    repeat progress destruct p0.\n    repeat progress destruct p.\n    repeat progress destruct H7.\n    apply SC.addObjTuple_eq; try apply Ref.eq_sym; auto.\n    simpl in *.\n    unfold Sys.P.eq. \n    simpl.\n    repeat progress split; auto.\n    apply OC.addCap_eq; auto.\n    (* now the weak case *)\n    destruct Hf' as [Hf'|Hf']; try contradiction.\n\n    eapply Sys.eq_trans. eapply Sem.fetch_weak; auto.\n    eapply SemDefns.fetch_preReq_eq_iff in f;\n      [|apply Ref.eq_sym in H0; apply H0\n       |apply Ind.eq_sym in H1; apply H1\n       |apply Sys.eq_sym in H; apply H].\n    eapply Sys.eq_sym. eapply Sys.eq_trans. eapply Sem.fetch_weak; auto.\n    intro n; apply Hread.\n    eapply SemDefns.option_hasRight_eq; try apply AccessRight.eq_refl; eauto. \n    eapply SemDefns.option_hasRight_eq;\n      [eapply Ind.eq_sym; eauto | apply Ref.eq_sym; eauto | apply Sys.eq_sym; eauto | apply AccessRight.eq_refl | auto].\n\n    eapply option_map1_Equiv with\n      (EqA := RefEQ) \n      (EqB := SysEQ); try apply SemDefns.option_target_eq; try apply Ref.eq_sym; auto.\n    (* probably a new theorem here *)\n    unfold option_map1_compat_op.\n    intros.\n    unfold SC.copyCap.\n    eapply option_map1_Equiv with\n      (EqA := CapEQ)\n      (EqB := SysEQ); try apply SC.getCap_eq; try apply Ref.eq_sym; auto.\n    (* probably a new theorem here *)\n    unfold option_map1_compat_op.\n    intros.\n    unfold SC.addCap.\n    eapply option_map1_Equiv with\n      (EqA := ObjEQ)\n      (EqB := SysEQ); try apply SC.getObj_eq; try apply Ref.eq_sym; auto.\n    (* probably a new theorem here *)\n    unfold option_map1_compat_op.\n    intros.\n    unfold SC.updateObj.\n    eapply option_map1_Equiv with\n      (EqA := PEQ)\n      (EqB := SysEQ); try apply SC.getObjTuple_eq; try apply Ref.eq_sym; auto.\n    (* probably a new theroem here *)\n    unfold option_map1_compat_op.\n    intros.\n    (* And here is the meat of the theorem *)\n    unfold SC.addObjTuple.\n    unfold SC.update_pair_object. \n    repeat progress destruct a3; destruct a'3.\n    repeat progress destruct p0.\n    repeat progress destruct p.\n    repeat progress destruct H7.\n    apply SC.addObjTuple_eq; try apply Ref.eq_sym; auto.\n    unfold Sys.P.eq. \n    simpl in *.\n    repeat progress split; auto.\n    apply OC.addCap_eq; auto.\n    (* need a weaken_eq theorem *)\n    apply CC.weaken_equiv; auto.\n    (* and the case where things are not equal *)\n    eapply Sys.eq_trans. eapply Sem.fetch_invalid; auto.    \n    eapply Sys.eq_sym. eapply Sys.eq_trans;[ eapply Sem.fetch_invalid; auto|auto].\n    intro n'. apply n.\n    eapply SemDefns.fetch_preReq_eq_iff in n'; eauto.\n  Qed.\n\n  Theorem do_allocate_eq : forall a a' n n' i i' cil cil' s s',\n    Sys.eq s s' ->\n    Ref.eq a a' ->\n    Ref.eq n n' ->\n    Ind.eq i i' ->\n    CIL_Facts.cil_eq cil cil' ->\n    Sys.eq (Sem.do_allocate a n i cil s) (Sem.do_allocate a' n' i' cil' s').\n  Proof.\n    intros.\n    case (SemDefns.allocate_preReq_dec a n s); simpl; intros.\n\n    (* case where preReq occurrs *)\n    eapply Sys.eq_trans. eapply Sem.allocate_valid; auto.\n    eapply SemDefns.allocate_preReq_eq_iff in a0;\n      [|apply Ref.eq_sym in H0; apply H0\n       |apply Ref.eq_sym in H1; apply H1\n       |apply Sys.eq_sym in H; apply H].\n    eapply Sys.eq_sym.  eapply Sys.eq_trans.  eapply Sem.allocate_valid; auto.\n    unfold SC.set_alive.\n    unfold SC.set_label.\n    \n    Hint Resolve SC.addCap_eq.\n    Hint Resolve ARSet.eq_refl.\n    Hint Resolve Cap.mkCap_eq.\n\n    apply SC.addCap_eq; try apply Ref.eq_sym; auto.  eapply Cap.mkCap_eq; split. \n    eapply Ref.eq_trans. \n      eapply Ref.eq_trans. \n        eapply Ref.eq_sym; apply H1. \n        apply Ref.eq_sym; eapply CC.mkCap_target. \n      auto.\n    eapply ARSet.eq_trans.\n      eapply ARSet.eq_sym. eapply CC.mkCap_rights.\n      auto.\n    apply SC.copyCapList_eq; try apply Ref.eq_sym; auto. (* generalize CIL_Facts.cil_Equiv; intros [_ sym _].  apply sym. auto. *)\n\n    (* apply SC.copyCapList_eq; auto.\n       apply SC.addCap_eq; auto;  [eapply Cap.mkCap_eq; split; [rewrite CC.mkCap_target]| rewrite mkCap_rights]; eauto|]. *)\n\n    apply option_map1_Equiv with\n      (EqA:=PEQ)\n      (EqB:=SysEQ); try solve [apply SC.updateObj_eq; try apply Obj.eq_refl; eauto].\n\n    \n    (* option_map1_compat_op case *)\n    unfold option_map1_compat_op; intros.\n    apply SC.addObjTuple_eq; try apply SC.copyCapList_eq; try apply Ref.eq_sym; eauto.\n    unfold SC.update_pair_label.\n    repeat progress destruct a1; destruct a'0. \n    repeat progress destruct H4.\n    repeat progress destruct p0.\n    repeat progress destruct p.\n    unfold Sys.P.eq.\n    simpl in *.\n    repeat progress split; auto.\n    Hint Immediate Sys.eq_sym.\n    apply SC.updateObj_eq; try apply Obj.eq_refl; try apply SC.rmCapsByTarget_eq; try apply Ref.eq_sym; eauto.\n    apply SC.updateObj_eq; try apply Obj.eq_refl; try apply SC.rmCapsByTarget_eq; try apply Ref.eq_sym; eauto.\n\n(*    apply SC.updateObj_eq; try apply Obj.eq_refl; try apply SC.rmCapsByTarget_eq; eauto. *)\n    (* option_map_eq case *)\n    eapply Sys_MapEquiv.find_eq; eauto.\n    eapply SC.updateObj_eq; try apply Obj.eq_refl; try apply SC.rmCapsByTarget_eq; try apply Ref.eq_sym; eauto.\n\n    (* and the case where things are not equal *)\n    eapply Sys.eq_trans. eapply Sem.allocate_invalid; auto.\n    assert (~ SemDefns.allocate_preReq a' n' s'). intro. eapply n0.\n\n    eapply SemDefns.allocate_preReq_eq_iff in H4; eauto.\n    eapply Sys.eq_sym.  eapply Sys.eq_trans.  eapply Sem.allocate_invalid; auto. apply Sys.eq_sym; auto.\n  Qed.\n\n\n  Theorem do_op_eq : forall op s s',\n    Sys.eq s s' -> Sys.eq (Sem.do_op op s) (Sem.do_op op s').\n  Proof.\n    intros.\n    destruct op; auto;\n     first [apply do_read_eq | apply do_write_eq | apply do_fetch_eq | apply do_store_eq | apply do_revoke_eq | apply do_send_eq | apply do_allocate_eq | apply do_destroy_eq]; auto; try apply Ref.eq_refl;\n    try (destruct CIL_Facts.cil_Equiv as [refl _ _]; apply refl);\n      try (destruct (option_map_eq_Equiv Ind.eq IndEQ) as [refl _ _]; apply refl).\n  Qed.\n\n  Import RefS.\n\n  Theorem Proper_read_from_def: Proper (Sys.eq ==> eq ==> RefSet.eq ==> impl) Sem.read_from_def.\n  Proof.\n    unfold Proper; unfold respectful; unfold impl.\n    intros s s' Hs op op' Hop r r' Hr Hrf.\n\n    Require Import OptionSumbool.\n\n    (* Heq = H0 , HpreReq = H Hempty = H0 *)\n    (* The first two cases solve the branches of odd constructors, the last two for even *)\n    Ltac solve_occurrance op_preReq_eq_iff Hr Heq a t s s' Hs HpreReq Hempty:= solve\n      [ eapply op_preReq_eq_iff; eauto; try apply Ref.eq_refl\n        | eapply RefSet.eq_trans; [| apply Hr];\n          eapply RefSet.eq_trans; [| apply Heq];\n            try apply RefSet.eq_refl;\n              unfold Sem.add_option_target;\n                let Hcap := fresh \"Hcap\" in\n                  let Hcase := fresh \"Hcase\" in\n                    let Hcase' := fresh \"Hcase'\" in\n                      generalize (SC.getCap_eq _ _ _ _ _ _ Hs (Ind.eq_refl t) (Ref.eq_refl a)); intros Hcap;\n                        case (option_sumbool (SC.getCap t a s));intros Hcase; \n                          [|destruct Hcase as [cap Hcase]];rewrite Hcase in *;\n                            (case (option_sumbool (SC.getCap t a s'));intros Hcase'; \n                              [|destruct Hcase' as [cap' Hcase']];rewrite Hcase' in *); \n                            simpl in *; try solve \n                              [apply RefSet.eq_refl \n                                | contradiction\n                                | apply Cap.target_eq in Hcap; rewrite Hcap; apply RefSet.eq_refl]\n        | intros Hnot; apply HpreReq; eapply op_preReq_eq_iff; eauto; try apply Ref.eq_refl\n        | eapply RefSetFacts.Empty_m; [apply RefSet.eq_sym; apply Hr| apply Hempty] \n      ].\n    destruct Hrf; rewrite <- Hop in *;\n      [ constructor 1; solve_occurrance SemDefns.read_preReq_eq_iff Hr H0 a t s s' Hs H H0\n        | constructor 2; solve_occurrance SemDefns.read_preReq_eq_iff Hr H0 a t s s' Hs H H0\n        | constructor 3; solve_occurrance SemDefns.write_preReq_eq_iff Hr H0 a t s s' Hs H H0\n        | constructor 4; solve_occurrance SemDefns.write_preReq_eq_iff Hr H0 a t s s' Hs H H0\n        | constructor 5; solve_occurrance SemDefns.fetch_preReq_eq_iff Hr H0 a t s s' Hs H H0\n        | constructor 6; solve_occurrance SemDefns.fetch_preReq_eq_iff Hr H0 a t s s' Hs H H0\n        | constructor 7; solve_occurrance SemDefns.store_preReq_eq_iff Hr H0 a t s s' Hs H H0\n        | constructor 8; solve_occurrance SemDefns.store_preReq_eq_iff Hr H0 a t s s' Hs H H0\n        | constructor 9; solve_occurrance SemDefns.revoke_preReq_eq_iff Hr H0 a t s s' Hs H H0\n        | constructor 10; solve_occurrance SemDefns.revoke_preReq_eq_iff Hr H0 a t s s' Hs H H0\n        | constructor 11; solve_occurrance SemDefns.send_preReq_eq_iff Hr H0 a t s s' Hs H H0\n        | constructor 12; solve_occurrance SemDefns.send_preReq_eq_iff Hr H0 a t s s' Hs H H0\n        | constructor 13; solve_occurrance SemDefns.allocate_preReq_eq_iff Hr H0 a t s s' Hs H H0\n        | constructor 14; solve_occurrance SemDefns.allocate_preReq_eq_iff Hr H0 a t s s' Hs H H0\n        | constructor 15; solve_occurrance SemDefns.destroy_preReq_eq_iff Hr H0 a t s s' Hs H H0\n        | constructor 16; solve_occurrance SemDefns.destroy_preReq_eq_iff Hr H0 a t s s' Hs H H0\n      ].\n  Qed.\n\n  Theorem Proper_wrote_to_def: Proper (Sys.eq ==> eq ==> RefSet.eq ==> impl) Sem.wrote_to_def.\n  Proof.\n    unfold Proper; unfold respectful; unfold impl.\n    intros s s' Hs op op' Hop w w' Hw Hwt.\n    destruct Hwt; rewrite <- Hop in *;\n      [ constructor 1; solve_occurrance SemDefns.read_preReq_eq_iff Hw H0 a t s s' Hs H H0\n        | constructor 2; solve_occurrance SemDefns.read_preReq_eq_iff Hw H0 a t s s' Hs H H0\n        | constructor 3; solve_occurrance SemDefns.write_preReq_eq_iff Hw H0 a t s s' Hs H H0\n        | constructor 4; solve_occurrance SemDefns.write_preReq_eq_iff Hw H0 a t s s' Hs H H0\n        | constructor 5; solve_occurrance SemDefns.fetch_preReq_eq_iff Hw H0 a t s s' Hs H H0\n        | constructor 6; solve_occurrance SemDefns.fetch_preReq_eq_iff Hw H0 a t s s' Hs H H0\n        | constructor 7; solve_occurrance SemDefns.store_preReq_eq_iff Hw H0 a t s s' Hs H H0\n        | constructor 8; solve_occurrance SemDefns.store_preReq_eq_iff Hw H0 a t s s' Hs H H0\n        | constructor 9; solve_occurrance SemDefns.revoke_preReq_eq_iff Hw H0 a t s s' Hs H H0\n        | constructor 10; solve_occurrance SemDefns.revoke_preReq_eq_iff Hw H0 a t s s' Hs H H0\n        | constructor 11; solve_occurrance SemDefns.send_preReq_eq_iff Hw H0 a t s s' Hs H H0\n        | constructor 12; solve_occurrance SemDefns.send_preReq_eq_iff Hw H0 a t s s' Hs H H0\n        | constructor 13; solve_occurrance SemDefns.allocate_preReq_eq_iff Hw H0 a t s s' Hs H H0\n        | constructor 14; solve_occurrance SemDefns.allocate_preReq_eq_iff Hw H0 a t s s' Hs H H0\n        | constructor 15; solve_occurrance SemDefns.destroy_preReq_eq_iff Hw H0 a t s s' Hs H H0\n        | constructor 16; solve_occurrance SemDefns.destroy_preReq_eq_iff Hw H0 a t s s' Hs H H0\n      ].\n  Qed.\n\n\nEnd MakeSemanticsConv.\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/Semantics_ConvImpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.26993790220362607}}
{"text": "(**\nThis file is part of the Flocq formalization of floating-point\narithmetic in Coq: http://flocq.gforge.inria.fr/\n\nCopyright (C) 2011-2018 Sylvie Boldo\n#<br />#\nCopyright (C) 2011-2018 Guillaume Melquiond\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 3 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nCOPYING file for more details.\n*)\n\nFrom Coq Require Import ZArith Lia Zquot.\n\nRequire Import SpecFloatCompat.\n\nNotation cond_Zopp := cond_Zopp (only parsing).\nNotation iter_pos := iter_pos (only parsing).\n\nSection Zmissing.\n\n(** About Z *)\nTheorem Zopp_le_cancel :\n  forall x y : Z,\n  (-y <= -x)%Z -> Z.le x y.\nProof.\nintros x y Hxy.\napply Zplus_le_reg_r with (-x - y)%Z.\nnow ring_simplify.\nQed.\n\nTheorem Zgt_not_eq :\n  forall x y : Z,\n  (y < x)%Z -> (x <> y)%Z.\nProof.\nintros x y H Hn.\napply Z.lt_irrefl with x.\nnow rewrite Hn at 1.\nQed.\n\nEnd Zmissing.\n\nSection Proof_Irrelevance.\n\nScheme eq_dep_elim := Induction for eq Sort Type.\n\nDefinition eqbool_dep P (h1 : P true) b :=\n  match b return P b -> Prop with\n  | true => fun (h2 : P true) => h1 = h2\n  | false => fun (h2 : P false) => False\n  end.\n\nLemma eqbool_irrelevance : forall (b : bool) (h1 h2 : b = true), h1 = h2.\nProof.\nassert (forall (h : true = true), refl_equal true = h).\napply (eq_dep_elim bool true (eqbool_dep _ _) (refl_equal _)).\nintros b.\ncase b.\nintros h1 h2.\nnow rewrite <- (H h1).\nintros h.\ndiscriminate h.\nQed.\n\nEnd Proof_Irrelevance.\n\nSection Even_Odd.\n\nTheorem Zeven_ex :\n  forall x, exists p, x = (2 * p + if Z.even x then 0 else 1)%Z.\nProof.\nintros [|[n|n|]|[n|n|]].\nnow exists Z0.\nnow exists (Zpos n).\nnow exists (Zpos n).\nnow exists Z0.\nexists (Zneg n - 1)%Z.\nchange (2 * Zneg n - 1 = 2 * (Zneg n - 1) + 1)%Z.\nring.\nnow exists (Zneg n).\nnow exists (-1)%Z.\nQed.\n\nEnd Even_Odd.\n\nSection Zpower.\n\nTheorem Zpower_plus :\n  forall n k1 k2, (0 <= k1)%Z -> (0 <= k2)%Z ->\n  Zpower n (k1 + k2) = (Zpower n k1 * Zpower n k2)%Z.\nProof.\nintros n k1 k2 H1 H2.\nnow apply Zpower_exp ; apply Z.le_ge.\nQed.\n\nTheorem Zpower_Zpower_nat :\n  forall b e, (0 <= e)%Z ->\n  Zpower b e = Zpower_nat b (Z.abs_nat e).\nProof.\nintros b [|e|e] He.\napply refl_equal.\napply Zpower_pos_nat.\nelim He.\napply refl_equal.\nQed.\n\nTheorem Zpower_nat_S :\n  forall b e,\n  Zpower_nat b (S e) = (b * Zpower_nat b e)%Z.\nProof.\nintros b e.\nrewrite (Zpower_nat_is_exp 1 e).\napply (f_equal (fun x => x * _)%Z).\napply Zmult_1_r.\nQed.\n\nTheorem Zpower_pos_gt_0 :\n  forall b p, (0 < b)%Z ->\n  (0 < Zpower_pos b p)%Z.\nProof.\nintros b p Hb.\nrewrite Zpower_pos_nat.\ninduction (nat_of_P p).\neasy.\nrewrite Zpower_nat_S.\nnow apply Zmult_lt_0_compat.\nQed.\n\nTheorem Zeven_Zpower_odd :\n  forall b e, (0 <= e)%Z -> Z.even b = false ->\n  Z.even (Zpower b e) = false.\nProof.\nintros b e He Hb.\ndestruct (Z_le_lt_eq_dec _ _ He) as [He'|He'].\nrewrite <- Hb.\nnow apply Z.even_pow.\nnow rewrite <- He'.\nQed.\n\n(** The radix must be greater than 1 *)\nRecord radix := { radix_val :> Z ; radix_prop : Zle_bool 2 radix_val = true }.\n\nTheorem radix_val_inj :\n  forall r1 r2, radix_val r1 = radix_val r2 -> r1 = r2.\nProof.\nintros (r1, H1) (r2, H2) H.\nsimpl in H.\nrevert H1.\nrewrite H.\nintros H1.\napply f_equal.\napply eqbool_irrelevance.\nQed.\n\nDefinition radix2 := Build_radix 2 (refl_equal _).\n\nVariable r : radix.\n\nTheorem radix_gt_0 : (0 < r)%Z.\nProof.\napply Z.lt_le_trans with 2%Z.\neasy.\napply Zle_bool_imp_le.\napply r.\nQed.\n\nTheorem radix_gt_1 : (1 < r)%Z.\nProof.\ndestruct r as (v, Hr). simpl.\napply Z.lt_le_trans with 2%Z.\neasy.\nnow apply Zle_bool_imp_le.\nQed.\n\nTheorem Zpower_gt_1 :\n  forall p,\n  (0 < p)%Z ->\n  (1 < Zpower r p)%Z.\nProof.\nintros [|p|p] Hp ; try easy.\nsimpl.\nrewrite Zpower_pos_nat.\ngeneralize (lt_O_nat_of_P p).\ninduction (nat_of_P p).\neasy.\nintros _.\nrewrite Zpower_nat_S.\nassert (0 < Zpower_nat r n)%Z.\nclear.\ninduction n.\neasy.\nrewrite Zpower_nat_S.\napply Zmult_lt_0_compat with (2 := IHn).\napply radix_gt_0.\napply Z.le_lt_trans with (1 * Zpower_nat r n)%Z.\nrewrite Zmult_1_l.\nnow apply (Zlt_le_succ 0).\napply Zmult_lt_compat_r with (1 := H).\napply radix_gt_1.\nQed.\n\nTheorem Zpower_gt_0 :\n  forall p,\n  (0 <= p)%Z ->\n  (0 < Zpower r p)%Z.\nProof.\nintros p Hp.\nrewrite Zpower_Zpower_nat with (1 := Hp).\ninduction (Z.abs_nat p).\neasy.\nrewrite Zpower_nat_S.\napply Zmult_lt_0_compat with (2 := IHn).\napply radix_gt_0.\nQed.\n\nTheorem Zpower_ge_0 :\n  forall e,\n  (0 <= Zpower r e)%Z.\nProof.\nintros [|e|e] ; try easy.\napply Zlt_le_weak.\nnow apply Zpower_gt_0.\nQed.\n\nTheorem Zpower_le :\n  forall e1 e2, (e1 <= e2)%Z ->\n  (Zpower r e1 <= Zpower r e2)%Z.\nProof.\nintros e1 e2 He.\ndestruct (Zle_or_lt 0 e1)%Z as [H1|H1].\nreplace e2 with (e2 - e1 + e1)%Z by ring.\nrewrite Zpower_plus with (2 := H1).\nrewrite <- (Zmult_1_l (r ^ e1)) at 1.\napply Zmult_le_compat_r.\napply (Zlt_le_succ 0).\napply Zpower_gt_0.\nnow apply Zle_minus_le_0.\napply Zpower_ge_0.\nnow apply Zle_minus_le_0.\nclear He.\ndestruct e1 as [|e1|e1] ; try easy.\napply Zpower_ge_0.\nQed.\n\nTheorem Zpower_lt :\n  forall e1 e2, (0 <= e2)%Z -> (e1 < e2)%Z ->\n  (Zpower r e1 < Zpower r e2)%Z.\nProof.\nintros e1 e2 He2 He.\ndestruct (Zle_or_lt 0 e1)%Z as [H1|H1].\nreplace e2 with (e2 - e1 + e1)%Z by ring.\nrewrite Zpower_plus with (2 := H1).\nrewrite Zmult_comm.\nrewrite <- (Zmult_1_r (r ^ e1)) at 1.\napply Zmult_lt_compat2.\nsplit.\nnow apply Zpower_gt_0.\napply Z.le_refl.\nsplit.\neasy.\napply Zpower_gt_1.\nclear -He ; omega.\napply Zle_minus_le_0.\nnow apply Zlt_le_weak.\nrevert H1.\nclear -He2.\ndestruct e1 ; try easy.\nintros _.\nnow apply Zpower_gt_0.\nQed.\n\nTheorem Zpower_lt_Zpower :\n  forall e1 e2,\n  (Zpower r (e1 - 1) < Zpower r e2)%Z ->\n  (e1 <= e2)%Z.\nProof.\nintros e1 e2 He.\napply Znot_gt_le.\nintros H.\napply Zlt_not_le with (1 := He).\napply Zpower_le.\nclear -H ; omega.\nQed.\n\nTheorem Zpower_gt_id :\n  forall n, (n < Zpower r n)%Z.\nProof.\nintros [|n|n] ; try easy.\nsimpl.\nrewrite Zpower_pos_nat.\nrewrite Zpos_eq_Z_of_nat_o_nat_of_P.\ninduction (nat_of_P n).\neasy.\nrewrite inj_S.\nchange (Zpower_nat r (S n0)) with (r * Zpower_nat r n0)%Z.\nunfold Z.succ.\napply Z.lt_le_trans with (r * (Z_of_nat n0 + 1))%Z.\nclear.\napply Zlt_0_minus_lt.\nreplace (r * (Z_of_nat n0 + 1) - (Z_of_nat n0 + 1))%Z with ((r - 1) * (Z_of_nat n0 + 1))%Z by ring.\napply Zmult_lt_0_compat.\ncut (2 <= r)%Z. omega.\napply Zle_bool_imp_le.\napply r.\napply (Zle_lt_succ 0).\napply Zle_0_nat.\napply Zmult_le_compat_l.\nnow apply Zlt_le_succ.\napply Z.le_trans with 2%Z.\neasy.\napply Zle_bool_imp_le.\napply r.\nQed.\n\nEnd Zpower.\n\nSection Div_Mod.\n\nTheorem Zmod_mod_mult :\n  forall n a b, (0 < a)%Z -> (0 <= b)%Z ->\n  Zmod (Zmod n (a * b)) b = Zmod n b.\nProof.\nintros n a [|b|b] Ha Hb.\nnow rewrite 2!Zmod_0_r.\nrewrite (Zmod_eq n (a * Zpos b)).\nrewrite Zmult_assoc.\nunfold Zminus.\nrewrite Zopp_mult_distr_l.\napply Z_mod_plus.\neasy.\napply Zmult_gt_0_compat.\nnow apply Z.lt_gt.\neasy.\nnow elim Hb.\nQed.\n\nTheorem ZOmod_eq :\n  forall a b,\n  Z.rem a b = (a - Z.quot a b * b)%Z.\nProof.\nintros a b.\nrewrite (Z.quot_rem' a b) at 2.\nring.\nQed.\n\nTheorem ZOmod_mod_mult :\n  forall n a b,\n  Z.rem (Z.rem n (a * b)) b = Z.rem n b.\nProof.\nintros n a b.\nassert (Z.rem n (a * b) = n + - (Z.quot n (a * b) * a) * b)%Z.\nrewrite <- Zopp_mult_distr_l.\nrewrite <- Zmult_assoc.\napply ZOmod_eq.\nrewrite H.\napply Z_rem_plus.\nrewrite <- H.\napply Zrem_sgn2.\nQed.\n\nTheorem Zdiv_mod_mult :\n  forall n a b, (0 <= a)%Z -> (0 <= b)%Z ->\n  (Z.div (Zmod n (a * b)) a) = Zmod (Z.div n a) b.\nProof.\nintros n a b Ha Hb.\ndestruct (Zle_lt_or_eq _ _ Ha) as [Ha'|Ha'].\ndestruct (Zle_lt_or_eq _ _ Hb) as [Hb'|Hb'].\nrewrite (Zmod_eq n (a * b)).\nrewrite (Zmult_comm a b) at 2.\nrewrite Zmult_assoc.\nunfold Zminus.\nrewrite Zopp_mult_distr_l.\nrewrite Z_div_plus by now apply Z.lt_gt.\nrewrite <- Zdiv_Zdiv by easy.\napply sym_eq.\napply Zmod_eq.\nnow apply Z.lt_gt.\nnow apply Zmult_gt_0_compat ; apply Z.lt_gt.\nrewrite <- Hb'.\nrewrite Zmult_0_r, 2!Zmod_0_r.\napply Zdiv_0_l.\nrewrite <- Ha'.\nnow rewrite 2!Zdiv_0_r, Zmod_0_l.\nQed.\n\nTheorem ZOdiv_mod_mult :\n  forall n a b,\n  (Z.quot (Z.rem n (a * b)) a) = Z.rem (Z.quot n a) b.\nProof.\nintros n a b.\ndestruct (Z.eq_dec a 0) as [Za|Za].\nrewrite Za.\nnow rewrite 2!Zquot_0_r, Zrem_0_l.\nassert (Z.rem n (a * b) = n + - (Z.quot (Z.quot n a) b * b) * a)%Z.\nrewrite (ZOmod_eq n (a * b)) at 1.\nrewrite Zquot_Zquot.\nring.\nrewrite H.\nrewrite Z_quot_plus with (2 := Za).\napply sym_eq.\napply ZOmod_eq.\nrewrite <- H.\napply Zrem_sgn2.\nQed.\n\nTheorem ZOdiv_small_abs :\n  forall a b,\n  (Z.abs a < b)%Z -> Z.quot a b = Z0.\nProof.\nintros a b Ha.\ndestruct (Zle_or_lt 0 a) as [H|H].\napply Z.quot_small.\nsplit.\nexact H.\nnow rewrite Z.abs_eq in Ha.\napply Z.opp_inj.\nrewrite <- Zquot_opp_l, Z.opp_0.\napply Z.quot_small.\ngeneralize (Zabs_non_eq a).\nomega.\nQed.\n\nTheorem ZOmod_small_abs :\n  forall a b,\n  (Z.abs a < b)%Z -> Z.rem a b = a.\nProof.\nintros a b Ha.\ndestruct (Zle_or_lt 0 a) as [H|H].\napply Z.rem_small.\nsplit.\nexact H.\nnow rewrite Z.abs_eq in Ha.\napply Z.opp_inj.\nrewrite <- Zrem_opp_l.\napply Z.rem_small.\ngeneralize (Zabs_non_eq a).\nomega.\nQed.\n\nTheorem ZOdiv_plus :\n  forall a b c, (0 <= a * b)%Z ->\n  (Z.quot (a + b) c = Z.quot a c + Z.quot b c + Z.quot (Z.rem a c + Z.rem b c) c)%Z.\nProof.\nintros a b c Hab.\ndestruct (Z.eq_dec c 0) as [Zc|Zc].\nnow rewrite Zc, 4!Zquot_0_r.\napply Zmult_reg_r with (1 := Zc).\nrewrite 2!Zmult_plus_distr_l.\nassert (forall d, Z.quot d c * c = d - Z.rem d c)%Z.\nintros d.\nrewrite ZOmod_eq.\nring.\nrewrite 4!H.\nrewrite <- Zplus_rem with (1 := Hab).\nring.\nQed.\n\nEnd Div_Mod.\n\nSection Same_sign.\n\nTheorem Zsame_sign_trans :\n  forall v u w, v <> Z0 ->\n  (0 <= u * v)%Z -> (0 <= v * w)%Z -> (0 <= u * w)%Z.\nProof.\nintros [|v|v] [|u|u] [|w|w] Zv Huv Hvw ; try easy ; now elim Zv.\nQed.\n\nTheorem Zsame_sign_trans_weak :\n  forall v u w, (v = Z0 -> w = Z0) ->\n  (0 <= u * v)%Z -> (0 <= v * w)%Z -> (0 <= u * w)%Z.\nProof.\nintros [|v|v] [|u|u] [|w|w] Zv Huv Hvw ; try easy ; now discriminate Zv.\nQed.\n\nTheorem Zsame_sign_imp :\n  forall u v,\n  (0 < u -> 0 <= v)%Z ->\n  (0 < -u -> 0 <= -v)%Z ->\n  (0 <= u * v)%Z.\nProof.\nintros [|u|u] v Hp Hn.\neasy.\napply Zmult_le_0_compat.\neasy.\nnow apply Hp.\nreplace (Zneg u * v)%Z with (Zpos u * (-v))%Z.\napply Zmult_le_0_compat.\neasy.\nnow apply Hn.\nrewrite <- Zopp_mult_distr_r.\napply Zopp_mult_distr_l.\nQed.\n\nTheorem Zsame_sign_odiv :\n  forall u v, (0 <= v)%Z ->\n  (0 <= u * Z.quot u v)%Z.\nProof.\nintros u v Hv.\napply Zsame_sign_imp ; intros Hu.\napply Z_quot_pos with (2 := Hv).\nnow apply Zlt_le_weak.\nrewrite <- Zquot_opp_l.\napply Z_quot_pos with (2 := Hv).\nnow apply Zlt_le_weak.\nQed.\n\nEnd Same_sign.\n\n(** Boolean comparisons *)\n\nSection Zeq_bool.\n\nInductive Zeq_bool_prop (x y : Z) : bool -> Prop :=\n  | Zeq_bool_true_ : x = y -> Zeq_bool_prop x y true\n  | Zeq_bool_false_ : x <> y -> Zeq_bool_prop x y false.\n\nTheorem Zeq_bool_spec :\n  forall x y, Zeq_bool_prop x y (Zeq_bool x y).\nProof.\nintros x y.\ngeneralize (Zeq_is_eq_bool x y).\ncase (Zeq_bool x y) ; intros (H1, H2) ; constructor.\nnow apply H2.\nintros H.\nspecialize (H1 H).\ndiscriminate H1.\nQed.\n\nTheorem Zeq_bool_true :\n  forall x y, x = y -> Zeq_bool x y = true.\nProof.\nintros x y.\napply -> Zeq_is_eq_bool.\nQed.\n\nTheorem Zeq_bool_false :\n  forall x y, x <> y -> Zeq_bool x y = false.\nProof.\nintros x y.\ngeneralize (proj2 (Zeq_is_eq_bool x y)).\ncase Zeq_bool.\nintros He Hn.\nelim Hn.\nnow apply He.\nnow intros _ _.\nQed.\n\nEnd Zeq_bool.\n\nSection Zle_bool.\n\nInductive Zle_bool_prop (x y : Z) : bool -> Prop :=\n  | Zle_bool_true_ : (x <= y)%Z -> Zle_bool_prop x y true\n  | Zle_bool_false_ : (y < x)%Z -> Zle_bool_prop x y false.\n\nTheorem Zle_bool_spec :\n  forall x y, Zle_bool_prop x y (Zle_bool x y).\nProof.\nintros x y.\ngeneralize (Zle_is_le_bool x y).\ncase Zle_bool ; intros (H1, H2) ; constructor.\nnow apply H2.\ndestruct (Zle_or_lt x y) as [H|H].\nnow specialize (H1 H).\nexact H.\nQed.\n\nTheorem Zle_bool_true :\n  forall x y : Z,\n  (x <= y)%Z -> Zle_bool x y = true.\nProof.\nintros x y.\napply (proj1 (Zle_is_le_bool x y)).\nQed.\n\nTheorem Zle_bool_false :\n  forall x y : Z,\n  (y < x)%Z -> Zle_bool x y = false.\nProof.\nintros x y Hxy.\ngeneralize (Zle_cases x y).\ncase Zle_bool ; intros H.\nelim (Z.lt_irrefl x).\nnow apply Z.le_lt_trans with y.\napply refl_equal.\nQed.\n\nEnd Zle_bool.\n\nSection Zlt_bool.\n\nInductive Zlt_bool_prop (x y : Z) : bool -> Prop :=\n  | Zlt_bool_true_ : (x < y)%Z -> Zlt_bool_prop x y true\n  | Zlt_bool_false_ : (y <= x)%Z -> Zlt_bool_prop x y false.\n\nTheorem Zlt_bool_spec :\n  forall x y, Zlt_bool_prop x y (Zlt_bool x y).\nProof.\nintros x y.\ngeneralize (Zlt_is_lt_bool x y).\ncase Zlt_bool ; intros (H1, H2) ; constructor.\nnow apply H2.\ndestruct (Zle_or_lt y x) as [H|H].\nexact H.\nnow specialize (H1 H).\nQed.\n\nTheorem Zlt_bool_true :\n  forall x y : Z,\n  (x < y)%Z -> Zlt_bool x y = true.\nProof.\nintros x y.\napply (proj1 (Zlt_is_lt_bool x y)).\nQed.\n\nTheorem Zlt_bool_false :\n  forall x y : Z,\n  (y <= x)%Z -> Zlt_bool x y = false.\nProof.\nintros x y Hxy.\ngeneralize (Zlt_cases x y).\ncase Zlt_bool ; intros H.\nelim (Z.lt_irrefl x).\nnow apply Z.lt_le_trans with y.\napply refl_equal.\nQed.\n\nTheorem negb_Zle_bool :\n  forall x y : Z,\n  negb (Zle_bool x y) = Zlt_bool y x.\nProof.\nintros x y.\ncase Zle_bool_spec ; intros H.\nnow rewrite Zlt_bool_false.\nnow rewrite Zlt_bool_true.\nQed.\n\nTheorem negb_Zlt_bool :\n  forall x y : Z,\n  negb (Zlt_bool x y) = Zle_bool y x.\nProof.\nintros x y.\ncase Zlt_bool_spec ; intros H.\nnow rewrite Zle_bool_false.\nnow rewrite Zle_bool_true.\nQed.\n\nEnd Zlt_bool.\n\nSection Zcompare.\n\nInductive Zcompare_prop (x y : Z) : comparison -> Prop :=\n  | Zcompare_Lt_ : (x < y)%Z -> Zcompare_prop x y Lt\n  | Zcompare_Eq_ : x = y -> Zcompare_prop x y Eq\n  | Zcompare_Gt_ : (y < x)%Z -> Zcompare_prop x y Gt.\n\nTheorem Zcompare_spec :\n  forall x y, Zcompare_prop x y (Z.compare x y).\nProof.\nintros x y.\ndestruct (Z_dec x y) as [[H|H]|H].\ngeneralize (Zlt_compare _ _ H).\ncase (Z.compare x y) ; try easy.\nnow constructor.\ngeneralize (Zgt_compare _ _ H).\ncase (Z.compare x y) ; try easy.\nconstructor.\nnow apply Z.gt_lt.\ngeneralize (proj2 (Zcompare_Eq_iff_eq _ _) H).\ncase (Z.compare x y) ; try easy.\nnow constructor.\nQed.\n\nTheorem Zcompare_Lt :\n  forall x y,\n  (x < y)%Z -> Z.compare x y = Lt.\nProof.\neasy.\nQed.\n\nTheorem Zcompare_Eq :\n  forall x y,\n  (x = y)%Z -> Z.compare x y = Eq.\nProof.\nintros x y.\napply <- Zcompare_Eq_iff_eq.\nQed.\n\nTheorem Zcompare_Gt :\n  forall x y,\n  (y < x)%Z -> Z.compare x y = Gt.\nProof.\nintros x y.\napply Z.lt_gt.\nQed.\n\nEnd Zcompare.\n\nSection cond_Zopp.\n\nTheorem cond_Zopp_negb :\n  forall x y, cond_Zopp (negb x) y = Z.opp (cond_Zopp x y).\nProof.\nintros [|] y.\napply sym_eq, Z.opp_involutive.\neasy.\nQed.\n\nTheorem abs_cond_Zopp :\n  forall b m,\n  Z.abs (cond_Zopp b m) = Z.abs m.\nProof.\nintros [|] m.\napply Zabs_Zopp.\napply refl_equal.\nQed.\n\nTheorem cond_Zopp_Zlt_bool :\n  forall m,\n  cond_Zopp (Zlt_bool m 0) m = Z.abs m.\nProof.\nintros m.\napply sym_eq.\ncase Zlt_bool_spec ; intros Hm.\napply Zabs_non_eq.\nnow apply Zlt_le_weak.\nnow apply Z.abs_eq.\nQed.\n\nEnd cond_Zopp.\n\nSection fast_pow_pos.\n\nFixpoint Zfast_pow_pos (v : Z) (e : positive) : Z :=\n  match e with\n  | xH => v\n  | xO e' => Z.square (Zfast_pow_pos v e')\n  | xI e' => Zmult v (Z.square (Zfast_pow_pos v e'))\n  end.\n\nTheorem Zfast_pow_pos_correct :\n  forall v e, Zfast_pow_pos v e = Zpower_pos v e.\nProof.\nintros v e.\nrewrite <- (Zmult_1_r (Zfast_pow_pos v e)).\nunfold Z.pow_pos.\ngeneralize 1%Z.\nrevert v.\ninduction e ; intros v f ; simpl.\n- rewrite <- 2!IHe.\n  rewrite Z.square_spec.\n  ring.\n- rewrite <- 2!IHe.\n  rewrite Z.square_spec.\n  apply eq_sym, Zmult_assoc.\n- apply eq_refl.\nQed.\n\nEnd fast_pow_pos.\n\nSection faster_div.\n\nLemma Zdiv_eucl_unique :\n  forall a b,\n  Z.div_eucl a b = (Z.div a b, Zmod a b).\nProof.\nintros a b.\nunfold Z.div, Zmod.\nnow case Z.div_eucl.\nQed.\n\nFixpoint Zpos_div_eucl_aux1 (a b : positive) {struct b} :=\n  match b with\n  | xO b' =>\n    match a with\n    | xO a' => let (q, r) := Zpos_div_eucl_aux1 a' b' in (q, 2 * r)%Z\n    | xI a' => let (q, r) := Zpos_div_eucl_aux1 a' b' in (q, 2 * r + 1)%Z\n    | xH => (Z0, Zpos a)\n    end\n  | xH => (Zpos a, Z0)\n  | xI _ => Z.pos_div_eucl a (Zpos b)\n  end.\n\nLemma Zpos_div_eucl_aux1_correct :\n  forall a b,\n  Zpos_div_eucl_aux1 a b = Z.pos_div_eucl a (Zpos b).\nProof.\nintros a b.\nrevert a.\ninduction b ; intros a.\n- easy.\n- change (Z.pos_div_eucl a (Zpos b~0)) with (Z.div_eucl (Zpos a) (Zpos b~0)).\n  rewrite Zdiv_eucl_unique.\n  change (Zpos b~0) with (2 * Zpos b)%Z.\n  rewrite Z.rem_mul_r by easy.\n  rewrite <- Zdiv_Zdiv by easy.\n  destruct a as [a|a|].\n  + change (Zpos_div_eucl_aux1 a~1 b~0) with (let (q, r) := Zpos_div_eucl_aux1 a b in (q, 2 * r + 1)%Z).\n    rewrite IHb. clear IHb.\n    change (Z.pos_div_eucl a (Zpos b)) with (Z.div_eucl (Zpos a) (Zpos b)).\n    rewrite Zdiv_eucl_unique.\n    change (Zpos a~1) with (1 + 2 * Zpos a)%Z.\n    rewrite (Zmult_comm 2 (Zpos a)).\n    rewrite Z_div_plus_full by easy.\n    apply f_equal.\n    rewrite Z_mod_plus_full.\n    apply Zplus_comm.\n  + change (Zpos_div_eucl_aux1 a~0 b~0) with (let (q, r) := Zpos_div_eucl_aux1 a b in (q, 2 * r)%Z).\n    rewrite IHb. clear IHb.\n    change (Z.pos_div_eucl a (Zpos b)) with (Z.div_eucl (Zpos a) (Zpos b)).\n    rewrite Zdiv_eucl_unique.\n    change (Zpos a~0) with (2 * Zpos a)%Z.\n    rewrite (Zmult_comm 2 (Zpos a)).\n    rewrite Z_div_mult_full by easy.\n    apply f_equal.\n    now rewrite Z_mod_mult.\n  + easy.\n- change (Z.pos_div_eucl a 1) with (Z.div_eucl (Zpos a) 1).\n  rewrite Zdiv_eucl_unique.\n  now rewrite Zdiv_1_r, Zmod_1_r.\nQed.\n\nDefinition Zpos_div_eucl_aux (a b : positive) :=\n  match Pos.compare a b with\n  | Lt => (Z0, Zpos a)\n  | Eq => (1%Z, Z0)\n  | Gt => Zpos_div_eucl_aux1 a b\n  end.\n\nLemma Zpos_div_eucl_aux_correct :\n  forall a b,\n  Zpos_div_eucl_aux a b = Z.pos_div_eucl a (Zpos b).\nProof.\nintros a b.\nunfold Zpos_div_eucl_aux.\nchange (Z.pos_div_eucl a (Zpos b)) with (Z.div_eucl (Zpos a) (Zpos b)).\nrewrite Zdiv_eucl_unique.\ncase Pos.compare_spec ; intros H.\nnow rewrite H, Z_div_same, Z_mod_same.\nnow rewrite Zdiv_small, Zmod_small by (split ; easy).\nrewrite Zpos_div_eucl_aux1_correct.\nchange (Z.pos_div_eucl a (Zpos b)) with (Z.div_eucl (Zpos a) (Zpos b)).\napply Zdiv_eucl_unique.\nQed.\n\nDefinition Zfast_div_eucl (a b : Z) :=\n  match a with\n  | Z0 => (0, 0)%Z\n  | Zpos a' =>\n    match b with\n    | Z0 => (0, 0)%Z\n    | Zpos b' => Zpos_div_eucl_aux a' b'\n    | Zneg b' =>\n      let (q, r) := Zpos_div_eucl_aux a' b' in\n      match r with\n      | Z0 => (-q, 0)%Z\n      | Zpos _ => (-(q + 1), (b + r))%Z\n      | Zneg _ => (-(q + 1), (b + r))%Z\n      end\n    end\n  | Zneg a' =>\n    match b with\n    | Z0 => (0, 0)%Z\n    | Zpos b' =>\n      let (q, r) := Zpos_div_eucl_aux a' b' in\n      match r with\n      | Z0 => (-q, 0)%Z\n      | Zpos _ => (-(q + 1), (b - r))%Z\n      | Zneg _ => (-(q + 1), (b - r))%Z\n      end\n    | Zneg b' => let (q, r) := Zpos_div_eucl_aux a' b' in (q, (-r)%Z)\n    end\n  end.\n\nTheorem Zfast_div_eucl_correct :\n  forall a b : Z,\n  Zfast_div_eucl a b = Z.div_eucl a b.\nProof.\nunfold Zfast_div_eucl.\nintros [|a|a] [|b|b] ; try rewrite Zpos_div_eucl_aux_correct ; easy.\nQed.\n\nEnd faster_div.\n\nSection Iter.\n\nContext {A : Type}.\nVariable (f : A -> A).\n\nFixpoint iter_nat (n : nat) (x : A) {struct n} : A :=\n  match n with\n  | S n' => iter_nat n' (f x)\n  | O => x\n  end.\n\nLemma iter_nat_plus :\n  forall (p q : nat) (x : A),\n  iter_nat (p + q) x = iter_nat p (iter_nat q x).\nProof.\ninduction q.\nnow rewrite plus_0_r.\nintros x.\nrewrite <- plus_n_Sm.\napply IHq.\nQed.\n\nLemma iter_nat_S :\n  forall (p : nat) (x : A),\n  iter_nat (S p) x = f (iter_nat p x).\nProof.\ninduction p.\neasy.\nsimpl.\nintros x.\napply IHp.\nQed.\n\nLemma iter_pos_nat :\n  forall (p : positive) (x : A),\n  iter_pos f p x = iter_nat (Pos.to_nat p) x.\nProof.\ninduction p ; intros x.\nrewrite Pos2Nat.inj_xI.\nsimpl.\nrewrite plus_0_r.\nrewrite iter_nat_plus.\nrewrite (IHp (f x)).\napply IHp.\nrewrite Pos2Nat.inj_xO.\nsimpl.\nrewrite plus_0_r.\nrewrite iter_nat_plus.\nrewrite (IHp x).\napply IHp.\neasy.\nQed.\n\nEnd Iter.\n", "meta": {"author": "validsdp", "repo": "flocq", "sha": "2a937c04e65acebcdc283a89ab6c6959eec10bc7", "save_path": "github-repos/coq/validsdp-flocq", "path": "github-repos/coq/validsdp-flocq/flocq-2a937c04e65acebcdc283a89ab6c6959eec10bc7/src/Core/Zaux.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213368305398, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.2699024116925206}}
{"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 Coq.Logic.ConstructiveEpsilon.\n\nRequire Export cequiv_bind.\nRequire Export computation_dec1.\n(*Require Export computation_dec.*)\nRequire Export sequents_tacs.\nRequire Export per_props_cequiv.\nRequire Export per_props_uni.\n\n\nLemma hasvalue_likec_eq {o} :\n  forall lib (t : @CTerm o),\n    hasvalue_likec lib t\n    <=> (hasvaluec lib t [+] raises_exceptionc lib t).\nProof.\n  introv.\n  destruct_cterms.\n  unfold hasvalue_likec, hasvaluec, raises_exceptionc; simpl.\n  split; intro h; repnd.\n  - apply hasvalue_like_implies_or; eauto 3 with slow.\n  - repndors.\n    + apply hasvalue_like_if_hasvalue; auto.\n    + apply hasvalue_like_if_raises_exception; auto.\nQed.\n\nLemma cast_capprox_value {o} :\n  forall lib (a b : @NTerm o) c bs,\n    Cast (approx lib a b)\n    -> computes_to_value lib a (oterm (Can c) bs)\n    -> {k : nat\n        , {u : NTerm\n        , reduces_in_atmost_k_steps lib b u k\n        # isccan u}}.\nProof.\n  introv apr comp; spcast.\n  inversion apr as [cc].\n  unfold close_comput in cc; repnd.\n  apply cc2 in comp; exrepnd.\n  unfold computes_to_value, reduces_to in comp1; exrepnd.\n  exists k.\n  exists (oterm (Can c) tr_subterms); dands; auto.\nQed.\n\nLemma cast_capprox_seq {o} :\n  forall lib (a b : @NTerm o) f,\n    Cast (approx lib a b)\n    -> computes_to_seq lib a f\n    -> {k : nat\n        , {f' : ntseq\n        , reduces_in_atmost_k_steps lib b (sterm f') k }}.\nProof.\n  introv apr comp; spcast.\n  inversion apr as [cc].\n  unfold close_comput in cc; repnd.\n  apply cc4 in comp; exrepnd.\n  unfold computes_to_seq, reduces_to in comp1; exrepnd.\n  exists k f'; dands; auto.\nQed.\n\nLemma cast_capprox_value2 {o} :\n  forall lib (a b : @NTerm o) c bs,\n    Cast (approx lib a b)\n    -> computes_to_value lib a (oterm (Can c) bs)\n    -> {k : nat\n        , {bs' : list BTerm\n        , reduces_in_atmost_k_steps lib b (oterm (Can c) bs') k}}.\nProof.\n  introv apr comp; spcast.\n  inversion apr as [cc].\n  unfold close_comput in cc; repnd.\n  apply cc2 in comp; exrepnd.\n  unfold computes_to_value, reduces_to in comp1; exrepnd.\n  exists k.\n  exists tr_subterms; dands; auto.\nQed.\n\nLemma cast_capprox_exc {o} :\n  forall lib (a b : @NTerm o) n e,\n    Cast (approx lib a b)\n    -> computes_to_exception lib n a e\n    -> {k : nat\n        , {n' : NTerm\n        , {e' : NTerm\n        , reduces_in_atmost_k_steps lib b (mk_exception n' e') k}}}.\nProof.\n  introv apr comp; spcast.\n  inversion apr as [cc].\n  unfold close_comput in cc; repnd.\n  apply cc3 in comp; exrepnd.\n  unfold computes_to_exception, reduces_to in comp0; exrepnd.\n  exists k.\n  exists a' e'; dands; auto.\nQed.\n\nLemma dec_ex_reduces_in_atmost_k_steps {o} :\n  forall lib k (t : @NTerm o),\n    decidable {v : NTerm & reduces_in_atmost_k_steps lib t v k}.\nProof.\n  introv.\n  remember (compute_at_most_k_steps lib k t) as c; symmetry in Heqc.\n  destruct c.\n  - left.\n    exists n; auto.\n  - right; intro r; exrepnd; rw r0 in Heqc; ginv.\nQed.\n\nLemma dec_ex_reduces_in_atmost_k_steps_exc {o} :\n  forall lib k (t : @NTerm o),\n    decidable {n : NTerm & {e : NTerm & reduces_in_atmost_k_steps lib t (mk_exception n e) k}}.\nProof.\n  introv.\n  remember (compute_at_most_k_steps lib k t) as c; symmetry in Heqc.\n  destruct c.\n  - destruct n as [v|f|op bs].\n    + right.\n      intro r; exrepnd.\n      rw r1 in Heqc; ginv.\n    + right; introv r; exrepnd.\n      rw r1 in Heqc; ginv.\n    + dopid op as [can|ncan|exc|abs] Case;\n      try (complete (right; intro r; exrepnd; rw r1 in Heqc; ginv)).\n      repeat (destruct bs; try (complete (right; intro r; exrepnd; rw r1 in Heqc; ginv))).\n      destruct b as [l1 t1].\n      destruct b0 as [l2 t2].\n      destruct l1; try (complete (right; intro r; exrepnd; rw r1 in Heqc; ginv)).\n      destruct l2; try (complete (right; intro r; exrepnd; rw r1 in Heqc; ginv)).\n      fold_terms.\n      left; exists t1 t2; auto.\n  - right; intro r; exrepnd; rw r1 in Heqc; ginv.\nQed.\n\nLemma reduces_in_atmost_k_steps_eq {o} :\n  forall lib (k : nat) (t t1 t2 : @NTerm o),\n    reduces_in_atmost_k_steps lib t t1 k\n    -> reduces_in_atmost_k_steps lib t t2 k\n    -> t1 = t2.\nProof.\n  introv r1 r2.\n  pose proof (compute_at_most_k_steps_eq lib k t (csuccess t1) (csuccess t2)) as h.\n  repeat (autodimp h hyp); ginv; auto.\nQed.\n\nLemma dec_ex_reduces_in_atmost_k_steps_iscan {o} :\n  forall lib k (t : @NTerm o),\n    decidable {v : NTerm & reduces_in_atmost_k_steps lib t v k # iscan v}.\nProof.\n  introv.\n  destruct (dec_ex_reduces_in_atmost_k_steps lib k t) as [d|d].\n  - exrepnd.\n    destruct (dec_iscan v) as [p|p].\n    + left; exists v; sp.\n    + right; intro h; exrepnd.\n      eapply reduces_in_atmost_k_steps_eq in d0;[|exact h1]; subst; sp.\n  - right; introv h; destruct d; exrepnd.\n    exists v; auto.\nQed.\n\nLemma dec_isccan {o} :\n  forall (t : @NTerm o), decidable (isccan t).\nProof.\n  introv.\n  destruct t as [v|f|op bs]; simpl; tcsp; try (complete (right; sp)).\n  dopid op as [can|ncan|exc|abs] Case; tcsp; try (complete (right; sp)).\nQed.\n\nLemma dec_ex_reduces_in_atmost_k_steps_isccan {o} :\n  forall lib k (t : @NTerm o),\n    decidable {v : NTerm & reduces_in_atmost_k_steps lib t v k # isccan v}.\nProof.\n  introv.\n  destruct (dec_ex_reduces_in_atmost_k_steps lib k t) as [d|d].\n  - exrepnd.\n    destruct (dec_isccan v) as [p|p].\n    + left; exists v; sp.\n    + right; intro h; exrepnd.\n      eapply reduces_in_atmost_k_steps_eq in d0;[|exact h1]; subst; sp.\n  - right; introv h; destruct d; exrepnd.\n    exists v; auto.\nQed.\n\nLemma dec_ex_reduces_in_atmost_k_steps_iscan_prop {o} :\n  forall lib k (t : @NTerm o),\n    decidable {v : NTerm , reduces_in_atmost_k_steps lib t v k # iscan v}.\nProof.\n  introv.\n  destruct (dec_ex_reduces_in_atmost_k_steps_iscan lib k t) as [d|d].\n  - left; exrepnd; exists v; sp.\n  - right; intro h; exrepnd; destruct d; exists v; sp.\nQed.\n\nLemma dec_ex_reduces_in_atmost_k_steps_iscan_prop2 {o} :\n  forall lib k (t : @NTerm o),\n    {{v : NTerm , reduces_in_atmost_k_steps lib t v k # iscan v}}\n    + {!{v : NTerm , reduces_in_atmost_k_steps lib t v k # iscan v}}.\nProof.\n  introv.\n  destruct (dec_ex_reduces_in_atmost_k_steps_iscan_prop lib k t) as [d|d]; sp.\nQed.\n\nLemma dec_ex_reduces_in_atmost_k_steps_isccan_prop {o} :\n  forall lib k (t : @NTerm o),\n    decidable {v : NTerm , reduces_in_atmost_k_steps lib t v k # isccan v}.\nProof.\n  introv.\n  destruct (dec_ex_reduces_in_atmost_k_steps_isccan lib k t) as [d|d].\n  - left; exrepnd; exists v; sp.\n  - right; intro h; exrepnd; destruct d; exists v; sp.\nQed.\n\nLemma dec_ex_reduces_in_atmost_k_steps_isccan_prop2 {o} :\n  forall lib k (t : @NTerm o),\n    {{v : NTerm , reduces_in_atmost_k_steps lib t v k # isccan v}}\n    + {!{v : NTerm , reduces_in_atmost_k_steps lib t v k # isccan v}}.\nProof.\n  introv.\n  destruct (dec_ex_reduces_in_atmost_k_steps_isccan_prop lib k t) as [d|d]; sp.\nQed.\n\nLemma dec_ex_reduces_in_atmost_k_steps_exc_prop {o} :\n  forall lib k (t : @NTerm o),\n    decidable {n : NTerm , {e : NTerm , reduces_in_atmost_k_steps lib t (mk_exception n e) k}}.\nProof.\n  introv.\n  destruct (dec_ex_reduces_in_atmost_k_steps_exc lib k t) as [d|d].\n  - left; exrepnd; exists n e; sp.\n  - right; intro h; exrepnd; destruct d; exists n e; sp.\nQed.\n\nLemma dec_ex_reduces_in_atmost_k_steps_exc_prop2 {o} :\n  forall lib k (t : @NTerm o),\n    {{n : NTerm , {e : NTerm , reduces_in_atmost_k_steps lib t (mk_exception n e) k}}}\n    + {!{n : NTerm , {e : NTerm , reduces_in_atmost_k_steps lib t (mk_exception n e) k}}}.\nProof.\n  introv.\n  destruct (dec_ex_reduces_in_atmost_k_steps_exc_prop lib k t) as [d|d]; sp.\nQed.\n\nLemma dec_ex_reduces_in_atmost_k_steps_seq {o} :\n  forall lib k (t : @NTerm o),\n    decidable {f : ntseq & reduces_in_atmost_k_steps lib t (sterm f) k}.\nProof.\n  introv.\n  remember (compute_at_most_k_steps lib k t) as c; symmetry in Heqc.\n  destruct c.\n  - destruct n as [v|f|op bs].\n    + right.\n      intro r; exrepnd.\n      rw r0 in Heqc; ginv.\n    + left.\n      exists f; auto.\n    + right.\n      intro r; exrepnd.\n      rw r0 in Heqc; ginv.\n  - right; intro r; exrepnd; rw r0 in Heqc; ginv.\nQed.\n\nLemma dec_ex_reduces_in_atmost_k_steps_seq_prop {o} :\n  forall lib k (t : @NTerm o),\n    decidable {f : ntseq , reduces_in_atmost_k_steps lib t (sterm f) k}.\nProof.\n  introv.\n  destruct (dec_ex_reduces_in_atmost_k_steps_seq lib k t) as [d|d].\n  - left; exrepnd; exists f; sp.\n  - right; intro h; exrepnd; destruct d; exists f; sp.\nQed.\n\nLemma dec_ex_reduces_in_atmost_k_steps_seq_prop2 {o} :\n  forall lib k (t : @NTerm o),\n    {{f : ntseq , reduces_in_atmost_k_steps lib t (sterm f) k}}\n    + {!{f : ntseq , reduces_in_atmost_k_steps lib t (sterm f) k}}.\nProof.\n  introv.\n  destruct (dec_ex_reduces_in_atmost_k_steps_seq_prop lib k t) as [d|d]; sp.\nQed.\n\nLemma ex_reduces_in_atmost_k_steps_can {o} :\n  forall lib (t : @NTerm o) k,\n    {u : NTerm , reduces_in_atmost_k_steps lib t u k # iscan u}\n    -> {u : NTerm & reduces_in_atmost_k_steps lib t u k # iscan u}.\nProof.\n  introv comp.\n  destruct (dec_ex_reduces_in_atmost_k_steps lib k t) as [d|d].\n  - exrepnd.\n    destruct (dec_iscan v) as [p|p].\n    + exists v; sp.\n    + provefalse; exrepnd.\n      eapply reduces_in_atmost_k_steps_eq in comp1;[|exact d0]; subst; tcsp.\n  - provefalse; exrepnd; destruct d.\n    exists u; auto.\nQed.\n\nLemma ex_reduces_in_atmost_k_steps_ccan {o} :\n  forall lib (t : @NTerm o) k,\n    {u : NTerm , reduces_in_atmost_k_steps lib t u k # isccan u}\n    -> {u : NTerm & reduces_in_atmost_k_steps lib t u k # isccan u}.\nProof.\n  introv comp.\n  destruct (dec_ex_reduces_in_atmost_k_steps lib k t) as [d|d].\n  - exrepnd.\n    destruct (dec_isccan v) as [p|p].\n    + exists v; sp.\n    + provefalse; exrepnd.\n      eapply reduces_in_atmost_k_steps_eq in comp1;[|exact d0]; subst; tcsp.\n  - provefalse; exrepnd; destruct d.\n    exists u; auto.\nQed.\n\nLemma ex_reduces_in_atmost_k_steps_exc {o} :\n  forall lib (t : @NTerm o) k,\n    {n : NTerm , {e : NTerm , reduces_in_atmost_k_steps lib t (mk_exception n e) k}}\n    -> {n : NTerm & {e : NTerm & reduces_in_atmost_k_steps lib t (mk_exception n e) k}}.\nProof.\n  introv comp.\n  destruct (dec_ex_reduces_in_atmost_k_steps_exc lib k t) as [d|d].\n  - exrepnd.\n    exists n e; auto.\n  - provefalse; exrepnd; destruct d.\n    exists n e; auto.\nQed.\n\nLemma ex_reduces_in_atmost_k_steps_seq {o} :\n  forall lib (t : @NTerm o) k,\n    {f : ntseq , reduces_in_atmost_k_steps lib t (sterm f) k}\n    -> {f : ntseq & reduces_in_atmost_k_steps lib t (sterm f) k}.\nProof.\n  introv comp.\n  destruct (dec_ex_reduces_in_atmost_k_steps_seq lib k t) as [d|d].\n  - exrepnd.\n    exists f; auto.\n  - provefalse; exrepnd; destruct d.\n    exists f; auto.\nQed.\n\nLemma cast_capprox_value3 {o} :\n  forall lib (a b : @NTerm o) c bs1 bs2,\n    Cast (approx lib a b)\n    -> computes_to_value lib a (oterm (Can c) bs1)\n    -> computes_to_value lib b (oterm (Can c) bs2)\n    -> length bs1 = length bs2\n       # (forall n : nat,\n            n < length bs1\n            -> {lv : list NVar\n                , {nt1, nt2 : NTerm\n                , Cast (olift (approx_aux lib bot2 \\2/ bot2) nt1 nt2)\n                # Cast (alpha_eq_bterm (bs1 {[n]}) (bterm lv nt1))\n                # Cast (alpha_eq_bterm (bs2 {[n]}) (bterm lv nt2))}}).\nProof.\n  introv apr comp1 comp2.\n  unfold lblift; dands; spcast.\n\n  - inversion apr as [cl].\n    unfold close_comput in cl; repnd.\n    apply cl2 in comp1; exrepnd.\n    eapply computes_to_value_eq in comp1;[|exact comp2]; ginv.\n    unfold lblift in comp0; sp.\n\n  - introv ltn.\n    inversion apr as [cl].\n    unfold close_comput in cl; repnd.\n    apply cl2 in comp1; exrepnd.\n    eapply computes_to_value_eq in comp1;[|exact comp2]; ginv.\n    unfold lblift in comp0; sp.\n    apply comp0 in ltn.\n    unfold blift in ltn; exrepnd.\n    exists lv nt1 nt2; sp.\nQed.\n\nLemma cast_capprox_value4 {o} :\n  forall lib (a b : @NTerm o) c bs1 bs2,\n    Cast (approx lib a b)\n    -> computes_to_value lib a (oterm (Can c) bs1)\n    -> computes_to_value lib b (oterm (Can c) bs2)\n    -> length bs1 = length bs2\n       # (forall n : nat,\n            n < length bs1\n            -> Cast (blift (olift (approx_aux lib bot2 \\2/ bot2)) (bs1 {[n]}) (bs2 {[n]}))).\nProof.\n  introv apr comp1 comp2.\n  unfold lblift; dands; spcast.\n\n  - inversion apr as [cl].\n    unfold close_comput in cl; repnd.\n    apply cl2 in comp1; exrepnd.\n    eapply computes_to_value_eq in comp1;[|exact comp2]; ginv.\n    unfold lblift in comp0; sp.\n\n  - introv ltn.\n    inversion apr as [cl].\n    unfold close_comput in cl; repnd.\n    apply cl2 in comp1; exrepnd.\n    eapply computes_to_value_eq in comp1;[|exact comp2]; ginv.\n    unfold lblift in comp0; sp.\nQed.\n\nLemma isccan_implies {p} :\n  forall t : @NTerm p,\n    isccan t\n    -> {c : CanonicalOp\n        & {bterms : list BTerm\n        & t = oterm (Can c) bterms}}.\nProof.\n  introv isc.\n  destruct t as [v|f|op bs]; try (complete (inversion isc)).\n  destruct op; try (complete (inversion isc)).\n  exists c bs; sp.\nQed.\n\nLemma alpha_stable {o} :\n  forall (a b : @NTerm o), Cast (alpha_eq a b) -> alpha_eq a b.\nProof.\n  nterm_ind1s a as [v|f ind|op bs ind] Case; introv ca.\n\n  - Case \"vterm\".\n    destruct b as [v2|f2|op2 bs2];\n      try (complete (provefalse; spcast; inversion ca; subst; tcsp)).\n\n    destruct (deq_nvar v v2); subst; auto.\n    provefalse; spcast; inversion ca; subst; tcsp.\n\n  - Case \"sterm\".\n    destruct b as [v2|f2|op2 bs2];\n      try (complete (provefalse; spcast; inversion ca; subst; tcsp)).\n    constructor; introv.\n    apply ind; spcast.\n    inversion ca; auto.\n\n  - Case \"oterm\".\n    destruct b as [v2|f2|op2 bs2];\n      try (complete (provefalse; spcast; inversion ca; subst; tcsp)).\n\n    assert (op = op2) as eqop.\n    { spcast; inversion ca; subst; auto. }\n    subst.\n\n    assert (length bs = length bs2) as eqlbs.\n    { spcast; inversion ca; subst; auto. }\n\n    apply alpha_eq_oterm_combine2; dands; auto.\n    introv i.\n    destruct b1 as [l1 t1].\n    destruct b2 as [l2 t2].\n\n    applydup in_combine in i; repnd.\n\n    assert (length l1 = length l2) as eql.\n    { spcast.\n      apply alpha_eq_oterm_combine in ca; repnd.\n      apply ca in i.\n      inversion i; auto. }\n\n    pose proof (fresh_vars (length l1) (all_vars t1 ++ all_vars t2)) as fvs; exrepnd.\n    apply (al_bterm _ _ lvn); auto.\n    apply (ind t1 (lsubst t1 (var_ren l1 lvn)) l1); auto.\n    { rw @lsubst_allvars_preserves_osize2; eauto 3 with slow. }\n\n    spcast.\n    apply alpha_eq_oterm_combine in ca; repnd.\n    apply ca in i.\n    apply (alphabt_change_var _ _ _ _ lvn) in i; tcsp.\nQed.\n\nLemma approx_stable {o} :\n  forall lib (a b : @CTerm o), capproxc lib a b -> approxc lib a b.\nProof.\n  introv.\n  destruct_cterms.\n  unfold capproxc, approxc; simpl.\n\n  (* use approx_acc_resp instead? *)\n  revert x0 x i0 i.\n  cofix CIH.\n  intros t1 t2 ispt1 ispt2 h.\n  constructor; constructor; dands; try (complete sp); eauto 3 with slow.\n\n  - introv cp.\n    dup h as ca.\n    eapply cast_capprox_value in ca;[|exact cp].\n    apply (constructive_indefinite_ground_description nat (fun x => x) (fun x => x))\n      in ca; auto;\n    [|introv;apply dec_ex_reduces_in_atmost_k_steps_isccan_prop2].\n\n    exrepnd.\n    apply ex_reduces_in_atmost_k_steps_ccan in ca0; exrepnd.\n    apply isccan_implies in ca1; repndors; exrepnd; subst.\n\n    exists bterms.\n\n    dup h as ca.\n    eapply cast_capprox_value2 in ca;[|exact cp].\n    assert (c0 = c) as e.\n    { exrepnd.\n      allapply @reduces_in_atmost_k_steps_implies_reduces_to.\n      eapply reduces_to_eq_val_like in ca0;\n        [|exact ca2|eauto 2 with slow|eauto 2 with slow].\n      ginv; auto. }\n    subst.\n    clear ca.\n    unfold computes_to_value.\n    applydup @reduces_atmost_preserves_program in ca0; eauto 3 with slow.\n    dands; eauto 3 with slow.\n\n    dup h as ca.\n    eapply cast_capprox_value4 in ca;\n      [|exact cp\n       |unfold computes_to_value;dands;\n        [exists x;exact ca0|eauto 3 with slow]\n      ].\n    repnd.\n\n    unfold lblift; dands; auto.\n    introv ltn.\n\n    applydup ca in ltn; exrepnd; clear ca.\n\n    remember (selectbt tl_subterms n) as u1.\n    remember (selectbt bterms n) as u2.\n    destruct u1 as [l1 u1].\n    destruct u2 as [l2 u2].\n\n    assert (length l1 = length l2) as el.\n    { spcast.\n      unfold blift in ltn0; exrepnd.\n      allapply @alpha_eq_bterm_implies_eq_length; omega. }\n\n    pose proof (fresh_vars (length l1) (l1 ++ l2 ++ all_vars u1 ++ all_vars u2)) as fvs; exrepnd.\n    exists lvn (lsubst u1 (var_ren l1 lvn)) (lsubst u2 (var_ren l2 lvn)).\n    dands;\n      [|apply btchange_alpha_aux; auto;\n        allrw disjoint_app_r; allrw disjoint_app_l;\n        repnd; dands; eauto 3 with slow\n       |apply btchange_alpha_aux; auto; try omega;\n        allrw disjoint_app_r; allrw disjoint_app_l;\n        repnd; dands; eauto 3 with slow];[].\n\n    assert (Cast (blift (olift (approx_aux lib bot2 \\2/ bot2))\n                        (bterm lvn (lsubst u1 (var_ren l1 lvn)))\n                        (bterm lvn (lsubst u2 (var_ren l2 lvn))))) as cb.\n    { spcast.\n      pose proof (respects_blift_alphabt (olift (approx_aux lib bot2 \\2/ bot2))) as resp.\n      unfold respects2 in resp; repnd.\n      apply (resp _ (bterm l2 u2)).\n      { apply btchange_alpha_aux; auto; try omega;\n        allrw disjoint_app_r; allrw disjoint_app_l;\n        repnd; dands; eauto 3 with slow. }\n      apply (resp0 (bterm l1 u1)).\n      { apply btchange_alpha_aux; auto; try omega;\n        allrw disjoint_app_r; allrw disjoint_app_l;\n        repnd; dands; eauto 3 with slow. }\n      auto. }\n    clear ltn0.\n\n    unfold computes_to_value in cp; repnd.\n    allrw @isvalue_iff; repnd.\n    allrw @isprogram_ot_iff; repnd.\n    pose proof (cp (bterm l1 u1)) as h1.\n    autodimp h1 hyp.\n    { rw Hequ1; apply selectbt_in; auto. }\n    pose proof (ca1 (bterm l2 u2)) as h2.\n    autodimp h2 hyp.\n    { rw Hequ2; apply selectbt_in; auto; try omega. }\n    allrw <- @isprog_vars_iff_isprogram_bt.\n    dup h1 as q1; rw @isprog_vars_eq in q1; repnd.\n    dup h2 as q2; rw @isprog_vars_eq in q2; repnd.\n\n    unfold olift.\n    dands.\n    {apply @lsubst_wf_iff_vars; auto. }\n    {apply @lsubst_wf_iff_vars; auto. }\n    introv ws isp1 isp2.\n    left.\n    apply CIH; eauto 3 with slow;[].\n    exrepnd; spcast.\n\n    pose proof (respects_alpha_olift_l (approx_aux lib bot2 \\2/ bot2)) as rl.\n    autodimp rl hyp.\n    { apply respects_alpha_l_approx_aux_bot2_or_bot2. }\n\n    pose proof (respects_alpha_olift_r (approx_aux lib bot2 \\2/ bot2)) as rr.\n    autodimp rr hyp.\n    { apply respects_alpha_r_approx_aux_bot2_or_bot2. }\n\n    apply blift_selen_triv in cb;\n      [|split;\n         [apply respects_alpha_l_approx_aux_bot2_or_bot2\n         |apply respects_alpha_r_approx_aux_bot2_or_bot2\n         ]\n      ].\n\n    unfold olift in cb; repnd.\n    pose proof (cb sub) as q.\n    repeat (autodimp q hyp).\n    repndors; tcsp; try (complete (unfold bot2 in q; sp)).\n\n  - introv cp.\n    dup h as ca.\n    eapply cast_capprox_exc in ca;[|exact cp].\n    apply (constructive_indefinite_ground_description nat (fun x => x) (fun x => x))\n      in ca; auto;\n    [|introv;apply dec_ex_reduces_in_atmost_k_steps_exc_prop2].\n\n    exrepnd.\n    apply ex_reduces_in_atmost_k_steps_exc in ca0; exrepnd.\n    exists n e0.\n    applydup @reduces_to_preserves_program in cp; eauto 3 with slow.\n    applydup @reduces_atmost_preserves_program in ca0; eauto 3 with slow.\n    allrw @isprogram_exception_iff; repnd.\n    dands; auto.\n\n    { exists x; auto. }\n\n    { left.\n      apply CIH; eauto 3 with slow.\n      spcast.\n      inversion h as [cl].\n      unfold close_comput in cl; repnd.\n      apply cl3 in cp; exrepnd.\n      allapply @reduces_in_atmost_k_steps_implies_reduces_to.\n      eapply reduces_to_eq_val_like in ca0;\n        [|exact cp2|eauto 2 with slow|eauto 2 with slow].\n      ginv.\n      clear cp3; repndors; try (complete (unfold bot2 in cp4; sp)). }\n\n    { left.\n      apply CIH; eauto 3 with slow.\n      spcast.\n      inversion h as [cl].\n      unfold close_comput in cl; repnd.\n      apply cl3 in cp; exrepnd.\n      allapply @reduces_in_atmost_k_steps_implies_reduces_to.\n      eapply reduces_to_eq_val_like in ca0;\n        [|exact cp2|eauto 2 with slow|eauto 2 with slow].\n      ginv.\n      clear cp4; repndors; try (complete (unfold bot2 in cp3; sp)). }\n\n  - introv comp.\n    dup h as ca.\n    eapply cast_capprox_seq in ca;[|exact comp].\n    apply (constructive_indefinite_ground_description nat (fun x => x) (fun x => x))\n      in ca; auto;\n    [|introv;apply dec_ex_reduces_in_atmost_k_steps_seq_prop2].\n\n    exrepnd.\n    apply ex_reduces_in_atmost_k_steps_seq in ca0; exrepnd.\n    exists f0.\n    applydup @reduces_to_preserves_program in comp; eauto 3 with slow.\n    applydup @reduces_atmost_preserves_program in ca1; eauto 3 with slow.\n    dands; auto.\n\n    { exists x; auto. }\n\n    { introv.\n      left.\n      apply CIH; eauto 3 with slow.\n      spcast.\n      inversion h as [cl].\n      unfold close_comput in cl; repnd.\n      apply cl4 in comp; exrepnd.\n      allapply @reduces_in_atmost_k_steps_implies_reduces_to.\n      eapply reduces_to_eq_val_like in ca1;\n        [|exact comp2|eauto 2 with slow|eauto 2 with slow].\n      allunfold @mk_ntseq; ginv; auto.\n      pose proof (comp1 n) as q; repndors; tcsp.\n      inversion q. }\nQed.\n\nLemma cequiv_stable {o} :\n  forall lib (a b : @CTerm o), ccequivc lib a b -> cequivc lib a b.\nProof.\n  introv h.\n  apply cequivc_iff_approxc.\n  dands; apply approx_stable; spcast;\n  rw @cequivc_iff_approxc in h; sp.\nQed.\n\nLemma cast_hasvalue {o} :\n  forall lib (a : @NTerm o),\n    Cast (hasvalue lib a)\n    -> {k : nat\n        , {u : NTerm\n        , reduces_in_atmost_k_steps lib a u k\n        # isprog u\n        # iscan u}}.\nProof.\n  introv comp; spcast.\n  unfold hasvalue, computes_to_value, reduces_to in comp; exrepnd.\n  exists k t'; dands; eauto 2 with slow.\n  apply compute_max_steps_eauto2 in comp0; eauto 3 with slow.\nQed.\n\nLemma cast_hasvalue2 {o} :\n  forall lib (a : @NTerm o),\n    Cast (hasvalue lib a)\n    -> {k : nat\n        , {u : NTerm\n        , reduces_in_atmost_k_steps lib a u k\n        # iscan u}}.\nProof.\n  introv comp; spcast.\n  unfold hasvalue, computes_to_value, reduces_to in comp; exrepnd.\n  exists k t'; dands; eauto 2 with slow.\nQed.\n\n(*\nLemma dec_ex_reduces_in_atmost_k_steps_isprog_iscan {o} :\n  forall lib k (t : @NTerm o),\n    decidable {v : NTerm & reduces_in_atmost_k_steps lib t v k # isprog v # iscan v}.\nProof.\n  introv.\n  destruct (dec_ex_reduces_in_atmost_k_steps lib k t) as [d|d].\n  - exrepnd.\n    destruct (dec_iscan v) as [p|p].\n    + destruct (decidable_isprog v) as [q|q].\n      * left; exists v; sp.\n      * right; intro h; exrepnd.\n        eapply reduces_in_atmost_k_steps_eq in d0;[|exact h1]; subst; sp.\n    + right; intro h; exrepnd.\n      eapply reduces_in_atmost_k_steps_eq in d0;[|exact h1]; subst; sp.\n  - right; introv h; destruct d; exrepnd.\n    exists v; auto.\nQed.\n\nLemma dec_ex_reduces_in_atmost_k_steps_isprog_iscan_prop {o} :\n  forall lib k (t : @NTerm o),\n    decidable {v : NTerm , reduces_in_atmost_k_steps lib t v k # isprog v # iscan v}.\nProof.\n  introv.\n  destruct (dec_ex_reduces_in_atmost_k_steps_isprog_iscan lib k t) as [d|d].\n  - left; exrepnd; exists v; sp.\n  - right; intro h; exrepnd; destruct d; exists v; sp.\nQed.\n\nLemma dec_ex_reduces_in_atmost_k_steps_isprog_iscan_prop2 {o} :\n  forall lib k (t : @NTerm o),\n    {{v : NTerm , reduces_in_atmost_k_steps lib t v k # isprog v # iscan v}}\n    + {!{v : NTerm , reduces_in_atmost_k_steps lib t v k # isprog v # iscan v}}.\nProof.\n  introv.\n  destruct (dec_ex_reduces_in_atmost_k_steps_isprog_iscan_prop lib k t) as [d|d]; sp.\nQed.\n\nLemma ex_reduces_in_atmost_k_steps_isprog_iscan {o} :\n  forall lib (t : @NTerm o) k,\n    {u : NTerm , reduces_in_atmost_k_steps lib t u k # isprog u # iscan u}\n    -> {u : NTerm & reduces_in_atmost_k_steps lib t u k # isprog u # iscan u}.\nProof.\n  introv comp.\n  destruct (dec_ex_reduces_in_atmost_k_steps_isprog_iscan lib k t) as [d|d].\n  - exrepnd.\n    exists v; auto.\n  - provefalse; exrepnd; destruct d.\n    exists u; auto.\nQed.\n *)\n\nLemma ex_reduces_in_atmost_k_steps_iscan {o} :\n  forall lib (t : @NTerm o) k,\n    {u : NTerm , reduces_in_atmost_k_steps lib t u k # iscan u}\n    -> {u : NTerm & reduces_in_atmost_k_steps lib t u k # iscan u}.\nProof.\n  introv comp.\n  destruct (dec_ex_reduces_in_atmost_k_steps_iscan lib k t) as [d|d].\n  - exrepnd.\n    exists v; auto.\n  - provefalse; exrepnd; destruct d.\n    exists u; auto.\nQed.\n\nLemma hasvaluec_stable {o} :\n  forall lib (a : @CTerm o), chaltsc lib a -> hasvaluec lib a.\nProof.\n  introv.\n  destruct_cterms.\n  unfold chaltsc, hasvaluec; simpl.\n  intro h.\n  apply cast_hasvalue2 in h.\n  apply (constructive_indefinite_ground_description nat (fun x => x) (fun x => x))\n    in h; auto;\n  [|introv; apply dec_ex_reduces_in_atmost_k_steps_iscan_prop2].\n  exrepnd.\n  apply ex_reduces_in_atmost_k_steps_iscan in h0; exrepnd.\n  exists u.\n  unfold computes_to_value; dands; auto.\n  { exists x0; auto. }\n  { apply isvalue_iff; dands; eauto 3 with slow. }\nQed.\n\nLemma cequorsq_mkc_halts {p} :\n  forall lib i (a b : @CTerm p),\n    equorsq lib (mkc_halts a) (mkc_halts b) (mkc_uni i)\n    <=>\n    (hasvaluec lib a <=> hasvaluec lib b).\nProof.\n  unfold equorsq; introv; split; introv h.\n  - split; introv q; apply hasvaluec_stable; repndors;\n     allrw @equality_in_uni_mkc_halts.\n     + apply h; spcast; auto.\n     + spcast.\n       apply cequivc_decomp_halts in h; repnd.\n       apply h0; auto.\n     + apply h; spcast; auto.\n     + spcast.\n       apply cequivc_decomp_halts in h; repnd.\n       apply h0; auto.\n  - left.\n    apply equality_in_uni_mkc_halts.\n    split; intro q; spcast; apply h; auto.\nQed.\n\nLemma isexc_as_raises_exceptionc {o} :\n  forall lib (a : @CTerm o),\n    capproxc lib bot_excc a <=> raises_exceptionc lib a.\nProof.\n  introv.\n  split; introv h; spcast.\n\n  - apply approx_stable in h.\n    destruct_cterms.\n    unfold approxc in h; allsimpl.\n    unfold raises_exceptionc; simpl.\n    inversion h as [cl].\n    unfold close_comput in cl; repnd.\n    pose proof (cl3 mk_bot mk_bot) as q.\n    autodimp q hyp.\n    { apply reduces_to_symm. }\n    exrepnd.\n    exists a' e'; auto.\n\n  - destruct_cterms.\n    unfold raises_exceptionc, raises_exception in h; allsimpl; exrepnd.\n    unfold approxc; simpl.\n    constructor.\n    unfold close_comput; dands; eauto 3 with slow.\n\n    { introv comp.\n      apply computes_to_value_exception in comp; sp. }\n\n    { introv comp.\n      apply computes_to_exception_exception in comp; repnd; subst.\n      applydup @preserve_program_exc2 in h1; eauto 3 with slow; repnd.\n      exists a e; dands; auto; left;\n      unfold mk_bot; apply bottom_approx_any; eauto 3 with slow. }\n\n    { introv comp.\n      apply reduces_to_if_isvalue_like in comp; eauto 3 with slow; ginv. }\nQed.\n\nLemma tequality_mkc_isexc {o} :\n  forall lib (a b : @CTerm o),\n    tequality lib (mkc_isexc a) (mkc_isexc b)\n    <=> (raises_exceptionc lib a <=> raises_exceptionc lib b).\nProof.\n  introv.\n  allrw @mkc_isexc_eq.\n  rw @tequality_mkc_approx.\n  allrw @isexc_as_raises_exceptionc; sp.\nQed.\n\nLemma member_isexc_iff {p} :\n  forall lib (t : @CTerm p),\n    raises_exceptionc lib t\n    <=> member lib mkc_axiom (mkc_isexc t).\nProof.\n  introv.\n  rw @mkc_isexc_eq.\n  rw <- @member_approx_iff.\n  rw @isexc_as_raises_exceptionc; sp.\nQed.\n\nLemma raises_exceptionc_stable {o} :\n  forall lib (a : @CTerm o), Cast (raises_exceptionc lib a) -> raises_exceptionc lib a.\nProof.\n  introv h.\n  apply isexc_as_raises_exceptionc; inversion h.\n  apply isexc_as_raises_exceptionc; auto.\nQed.\n\nLemma cequivc_decomp_isexc {o} :\n  forall lib (a b : @CTerm o),\n    cequivc lib (mkc_isexc a) (mkc_isexc b)\n    <=> cequivc lib a b.\nProof.\n  introv.\n  allrw @mkc_isexc_eq.\n  rw @cequivc_decomp_approx.\n  split; introv h; repnd; dands; auto.\nQed.\n\nLemma raises_exceptionc_preserves_cequivc {o} :\n  forall lib (a b : @CTerm o),\n    cequivc lib a b\n    -> raises_exceptionc lib a\n    -> raises_exceptionc lib b.\nProof.\n  introv ceq r.\n  destruct_cterms.\n  allunfold @raises_exceptionc.\n  allunfold @cequivc; allsimpl.\n  allunfold @raises_exception; exrepnd.\n  destruct ceq as [c1 c2].\n  inversion c1 as [cl].\n  unfold close_comput in cl; repnd.\n  apply cl3 in r1; exrepnd.\n  exists a' e'; auto.\nQed.\n\nLemma equality_in_uni_mkc_isexc {p} :\n  forall lib i (a b : @CTerm p),\n    equality lib (mkc_isexc a) (mkc_isexc b) (mkc_uni i)\n    <=>\n    (raises_exceptionc lib a <=> raises_exceptionc lib b).\nProof.\n  introv.\n  allrw @mkc_isexc_eq.\n  allrw @mkc_approx_equality_in_uni.\n  allrw @isexc_as_raises_exceptionc; sp.\nQed.\n\nLemma cequorsq_mkc_isexc {p} :\n  forall lib i (a b : @CTerm p),\n    equorsq lib (mkc_isexc a) (mkc_isexc b) (mkc_uni i)\n    <=>\n    (raises_exceptionc lib a <=> raises_exceptionc lib b).\nProof.\n  unfold equorsq; introv; split; introv h.\n  - split; introv q; apply raises_exceptionc_stable; repndors;\n    allapply @equality_in_uni;\n    allrw @tequality_mkc_isexc; spcast;\n    try (complete (apply h; auto)).\n    + rw @cequivc_decomp_isexc in h.\n      apply raises_exceptionc_preserves_cequivc in h; auto.\n    + rw @cequivc_decomp_isexc in h.\n      apply cequivc_sym in h.\n      apply raises_exceptionc_preserves_cequivc in h; auto.\n  - left.\n    apply equality_in_uni_mkc_isexc; auto.\nQed.\n\nDefinition bot_exccv {o} (vs : list NVar) : @CVTerm o vs :=\n  mk_cv vs bot_excc.\n\nDefinition halts_likec {o} lib (t : @CTerm o) (v : NVar) :=\n  approxc lib bot_excc (mkc_cbv t v (bot_exccv [v])).\n\nLemma cbv_raises_exception_val {o} :\n  forall lib (a t v u e : @NTerm o) (x : NVar),\n    computes_to_value lib t v\n    -> computes_to_exception lib a (subst u x v) e\n    -> computes_to_exception lib a (mk_cbv t x u) e.\nProof.\n  introv comp1 comp2.\n  unfold computes_to_value in comp1; repnd.\n  eapply reduces_to_trans;\n    [apply reduces_to_prinarg; exact comp0\n    |]; fold_terms.\n  apply isvalue_iff in comp1; repnd.\n  apply iscan_implies in comp3; repndors; exrepnd; subst;\n  eapply reduces_to_if_split2; try csunf; simpl; try reflexivity;\n  unfold apply_bterm; simpl; rw @fold_subst; auto.\nQed.\n\nLemma hasvalue_likec_iff_or {o} :\n  forall lib (t : @CTerm o),\n    hasvalue_likec lib t\n    <=> (hasvaluec lib t [+] raises_exceptionc lib t).\nProof.\n  introv; destruct_cterms.\n  unfold hasvalue_likec, hasvaluec, raises_exceptionc; simpl.\n  split; introv h.\n  - apply hasvalue_like_implies_or; eauto 3 with slow.\n  - repndors.\n    + apply hasvalue_like_if_hasvalue; auto.\n    + apply hasvalue_like_if_raises_exception; auto.\nQed.\n\nLemma isvalue_like_bot_exc {o} : @isvalue_like o bot_exc.\nProof.\n  unfold bot_exc; eauto 3 with slow.\nQed.\nHint Resolve isvalue_like_bot_exc : slow.\n\nLemma halts_likec_as_hasvalue_likec {o} :\n  forall lib (a : @CTerm o) v,\n    halts_likec lib a v <=> hasvalue_likec lib a.\nProof.\n  introv.\n  rw @hasvalue_likec_iff_or.\n  split; introv h; spcast.\n\n  - destruct_cterms.\n    unfold halts_likec, approxc in h; allsimpl.\n    unfold raises_exceptionc, hasvaluec; simpl.\n    inversion h as [cl].\n    unfold close_comput in cl; repnd.\n    pose proof (cl3 mk_bot mk_bot) as q.\n    autodimp q hyp.\n    { apply reduces_to_symm. }\n    exrepnd.\n    fold (@bot_exc o) in *.\n    repndors; try (complete (allunfold @bot2; sp)).\n    apply if_computes_to_exception_cbv0 in q0; eauto 3 with slow.\n    repndors; exrepnd.\n\n    + right.\n      exists a' e'; auto.\n\n    + left.\n      exists x0; auto.\n\n  - destruct_cterms.\n    unfold halts_likec, approxc; simpl.\n    fold (@bot_exc o).\n    unfold raises_exceptionc, raises_exception, hasvaluec, hasvalue in h; allsimpl.\n\n    constructor.\n    unfold close_comput; dands; eauto 3 with slow.\n    { apply isprogram_cbv_iff2; dands; eauto 3 with slow. }\n\n    + introv comp.\n      apply computes_to_value_exception in comp; sp.\n\n    + introv comp.\n      apply computes_to_exception_exception in comp; repnd; subst.\n      repndors; exrepnd.\n\n      * applydup @preserve_program in h0; eauto 3 with slow.\n        exists (@mk_bot o) (@mk_bot o); dands; eauto 3 with slow;\n        try (complete (left; unfold mk_bot; apply bottom_approx_any; eauto 3 with slow)).\n        eapply cbv_raises_exception_val;[exact h0|].\n        rw @subst_trivial; eauto 3 with slow.\n        apply computes_to_exception_refl.\n\n      * applydup @preserve_program_exc2 in h1; eauto 3 with slow; repnd.\n        exists a e.\n        dands; eauto 3 with slow;\n        try (complete (left; unfold mk_bot; apply bottom_approx_any; eauto 3 with slow)).\n        apply cbv_raises_exception; eauto 3 with slow.\n\n    + introv comp.\n      apply reduces_to_if_isvalue_like in comp; ginv; eauto 3 with slow.\nQed.\n\nLemma cast_halts_likec_as_hasvalue_likec {o} :\n  forall lib (a : @CTerm o) v,\n    Cast (halts_likec lib a v) <=> hasvalue_likec lib a.\nProof.\n  introv; split; intro h; spcast.\n  - apply approx_stable in h.\n    apply halts_likec_as_hasvalue_likec in h; auto.\n  - apply halts_likec_as_hasvalue_likec; auto.\nQed.\n\nLemma mkc_halts_like_eq {o} :\n  forall (t : @CTerm o),\n    mkc_halts_like t\n    = mkc_approx bot_excc (mkc_cbv t nvarx (bot_exccv [nvarx])).\nProof.\n  introv.\n  destruct_cterms.\n  apply cterm_eq; simpl; auto.\nQed.\n\nLemma tequality_mkc_halts_like {o} :\n  forall lib (a b : @CTerm o),\n    tequality lib (mkc_halts_like a) (mkc_halts_like b)\n    <=> (hasvalue_likec lib a <=> hasvalue_likec lib b).\nProof.\n  introv.\n  allrw @mkc_halts_like_eq.\n  rw @tequality_mkc_approx.\n  allrw @cast_halts_likec_as_hasvalue_likec; sp.\nQed.\n\nLemma member_halts_like_iff {p} :\n  forall lib (t : @CTerm p),\n    member lib mkc_axiom (mkc_halts_like t)\n    <=> hasvalue_likec lib t.\nProof.\n  introv.\n  rw @mkc_halts_like_eq.\n  rw <- @member_approx_iff.\n  rw @cast_halts_likec_as_hasvalue_likec; sp.\nQed.\n\nDefinition computes_to_approx_exception_or_value {o} lib (a b : @NTerm o) :=\n  forall n e,\n    computes_to_exception lib n a e\n    -> ({n' : NTerm\n         & {e' : NTerm\n         & computes_to_exception lib n' b e'\n         # approx lib n n'\n         # approx lib e e'}}\n        [+] (hasvalue lib b\n             # approx lib n mk_bot\n             # approx lib e mk_bot)).\n\nLemma approx_decomp_halts_exc_as_cbv {o} :\n  forall lib (a b : @NTerm o) v,\n    isprogram a\n    -> isprogram b\n    -> (approx\n          lib\n          (mk_cbv a v bot_exc)\n          (mk_cbv b v bot_exc)\n          <=>\n          (computes_to_approx_exception_or_value lib a b\n           # (hasvalue lib a -> hasvalue_like lib b))).\nProof.\n  introv ispa ispb.\n  split; intro h; dands.\n\n  - introv comp.\n    inversion h as [c]; clear h.\n    unfold close_comput in c; repnd.\n    pose proof (c3 n e) as k.\n    autodimp k hyp.\n    { apply cbv_raises_exception; auto. }\n    exrepnd.\n    repndors; try (complete (allunfold @bot2; sp)).\n    apply if_computes_to_exception_cbv0 in k0; auto; repndors; exrepnd.\n\n    + left; exists a' e'; dands; auto.\n\n    + applydup @preserve_program in k0; auto.\n      rw @subst_trivial in k3; eauto 3 with slow.\n      apply computes_to_exception_exception in k3; repnd; subst.\n      right; dands; auto.\n      exists x; auto.\n\n  - introv hv.\n    inversion h as [c]; clear h.\n    unfold close_comput in c; repnd.\n    pose proof (c3 (@mk_bot o) (@mk_bot o)) as k.\n    autodimp k hyp.\n    { unfold hasvalue in hv; exrepnd.\n      eapply cbv_raises_exception_val;[exact hv0|].\n      applydup @preserve_program in hv0; auto.\n      rw @subst_trivial; eauto 3 with slow.\n      apply computes_to_exception_refl. }\n    exrepnd.\n    repndors; try (complete (allunfold @bot2; sp)).\n    apply if_computes_to_exception_cbv0 in k0; eauto 3 with slow.\n    repndors; exrepnd.\n\n    + exists (mk_exception a' e'); dands; eauto 2 with slow.\n\n    + unfold computes_to_value in k0; repnd.\n      exists x; dands; eauto 3 with slow.\n\n  - constructor.\n    unfold close_comput; dands; auto;\n    try (complete (apply isprogram_cbv_iff2; dands; eauto 3 with slow)).\n\n    + introv comp.\n      apply computes_to_value_hasvalue in comp.\n      apply if_hasvalue_cbv in comp; eauto 3 with slow.\n      exrepnd.\n      applydup @preserve_program in comp1; auto.\n      rw @subst_trivial in comp0; eauto 3 with slow.\n      unfold hasvalue in comp0; exrepnd.\n      apply computes_to_value_exception in comp3; sp.\n\n    + introv comp.\n      applydup @if_computes_to_exception_cbv0 in comp; auto.\n      repndors; exrepnd.\n\n      * apply h0 in comp0; clear h; repndors; exrepnd.\n\n        { exists n' e'.\n          dands; auto.\n          apply cbv_raises_exception; auto. }\n\n        { exists (@mk_bot o) (@mk_bot o); dands; auto.\n          unfold hasvalue in comp1; exrepnd.\n          applydup @preserve_program in comp3; auto.\n          eapply cbv_raises_exception_val;[exact comp3|].\n          rw @subst_trivial; eauto 3 with slow.\n          apply computes_to_exception_refl. }\n\n      * applydup @preserve_program in comp0; auto.\n        rw @subst_trivial in comp1; eauto 3 with slow.\n        apply computes_to_exception_exception in comp1; repnd; subst.\n        autodimp h hyp.\n        { exists x; auto. }\n        apply hasvalue_like_implies_or in h; auto.\n        repndors.\n\n        { unfold hasvalue in h; exrepnd.\n          exists (@mk_bot o) (@mk_bot o); dands; auto;\n          try (complete (left; unfold mk_bot; apply bottom_approx_any; eauto 3 with slow)).\n          eapply cbv_raises_exception_val;[exact h1|].\n          applydup @preserve_program in h1; auto.\n          rw @subst_trivial; eauto 3 with slow.\n          apply computes_to_exception_refl. }\n\n        { unfold raises_exception in h; exrepnd.\n          applydup @preserve_program_exc2 in h2; eauto 3 with slow; repnd.\n          exists a0 e; dands;\n          try (complete (left; unfold mk_bot; apply bottom_approx_any; eauto 3 with slow)).\n          apply cbv_raises_exception; auto. }\n\n    + introv comp; repnd.\n      apply computes_to_seq_implies_computes_to_value in comp;\n        [|apply isprogram_cbv_iff2;dands; eauto 3 with slow].\n      apply computes_to_value_hasvalue in comp.\n      apply if_hasvalue_cbv in comp; eauto 3 with slow.\n      exrepnd.\n      applydup @preserve_program in comp1; auto.\n      rw @subst_trivial in comp0; eauto 3 with slow.\n      unfold hasvalue in comp0; exrepnd.\n      apply computes_to_value_exception in comp3; sp.\nQed.\n\nLemma cequiv_decomp_halts_exc_as_cbv {o} :\n  forall lib (a b : @NTerm o) v,\n    isprogram a\n    -> isprogram b\n    -> (cequiv\n          lib\n          (mk_cbv a v bot_exc)\n          (mk_cbv b v bot_exc)\n          <=>\n          ((hasvalue lib a -> hasvalue_like lib b)\n           # (hasvalue lib b -> hasvalue_like lib a)\n           # computes_to_approx_exception_or_value lib a b\n           # computes_to_approx_exception_or_value lib b a)).\nProof.\n  introv ispa ispb.\n  unfold cequiv, compute_to_cequiv_exceptions.\n  pose proof (approx_decomp_halts_exc_as_cbv lib a b v) as h.\n  repeat (autodimp h hyp).\n  pose proof (approx_decomp_halts_exc_as_cbv lib b a v) as k.\n  repeat (autodimp k hyp).\n  rw h.\n  rw k.\n  clear h k.\n  split; intro h; repnd; dands; auto.\nQed.\n\nDefinition computes_to_approxc_exception_or_value {o} lib (a b : @CTerm o) :=\n  computes_to_approx_exception_or_value lib (get_cterm a) (get_cterm b).\n\nLemma cequivc_decomp_halts_exc_as_cbv {o} :\n  forall lib (a b : @CTerm o) v,\n    cequivc\n      lib\n      (mkc_cbv a v (bot_exccv [v]))\n      (mkc_cbv b v (bot_exccv [v]))\n    <=>\n    ((hasvaluec lib a -> hasvalue_likec lib b)\n     # (hasvaluec lib b -> hasvalue_likec lib a)\n     # computes_to_approxc_exception_or_value lib a b\n     # computes_to_approxc_exception_or_value lib b a).\nProof.\n  introv.\n  destruct_cterms.\n  apply cequiv_decomp_halts_exc_as_cbv; simpl; eauto 3 with slow.\nQed.\n\nLemma cequivc_decomp_halts_like {o} :\n  forall lib (a b : @CTerm o),\n    cequivc lib (mkc_halts_like a) (mkc_halts_like b)\n    <=>\n    ((hasvaluec lib a -> hasvalue_likec lib b)\n     # (hasvaluec lib b -> hasvalue_likec lib a)\n     # computes_to_approxc_exception_or_value lib a b\n     # computes_to_approxc_exception_or_value lib b a).\nProof.\n  introv.\n  allrw @mkc_halts_like_eq.\n  rw @cequivc_decomp_approx.\n  allrw @cequivc_decomp_halts_exc_as_cbv.\n  split; intro h; repnd; dands; eauto 3 with slow.\nQed.\n\nLemma equality_in_uni_mkc_halts_like {p} :\n  forall lib i (a b : @CTerm p),\n    equality lib (mkc_halts_like a) (mkc_halts_like b) (mkc_uni i)\n    <=>\n    (hasvalue_likec lib a <=> hasvalue_likec lib b).\nProof.\n  introv.\n  allrw @mkc_halts_like_eq.\n  allrw @mkc_approx_equality_in_uni.\n  allrw @cast_halts_likec_as_hasvalue_likec.\n  allrw @isexc_as_raises_exceptionc; sp.\nQed.\n\nLemma hasvalue_likec_stable {o} :\n  forall lib (a : @CTerm o), Cast (hasvalue_likec lib a) -> hasvalue_likec lib a.\nProof.\n  introv h.\n  rw <- @member_halts_like_iff.\n  spcast.\n  apply member_halts_like_iff; auto.\nQed.\n\nLemma cequivc_halts_like_preserves_hasvalue_likec {o} :\n  forall lib (a b : @CTerm o),\n    cequivc lib (mkc_halts_like a) (mkc_halts_like b)\n    -> hasvalue_likec lib a\n    -> hasvalue_likec lib b.\nProof.\n  introv ceq hv.\n  rw @cequivc_decomp_halts_like in ceq; repnd.\n  allrw @hasvalue_likec_iff_or; repndors; tcsp.\n  destruct_cterms.\n  allunfold @computes_to_approxc_exception_or_value; allsimpl.\n  allunfold @raises_exceptionc; allsimpl.\n  allunfold @hasvaluec; allsimpl.\n  allunfold @computes_to_approx_exception_or_value; allsimpl.\n  unfold raises_exception in hv; exrepnd.\n  apply ceq2 in hv1.\n  repndors; exrepnd; tcsp.\n  right; exists n' e'; sp.\nQed.\n\nLemma cequorsq_mkc_halts_like {p} :\n  forall lib i (a b : @CTerm p),\n    equorsq lib (mkc_halts_like a) (mkc_halts_like b) (mkc_uni i)\n    <=>\n    (hasvalue_likec lib a <=> hasvalue_likec lib b).\nProof.\n  unfold equorsq; introv; split; introv h.\n  - split; introv q; apply hasvalue_likec_stable; repndors;\n    allapply @equality_in_uni;\n    allrw @tequality_mkc_halts_like; spcast;\n    try (complete (apply h; auto)).\n    + eapply cequivc_halts_like_preserves_hasvalue_likec; eauto.\n    + apply cequivc_sym in h.\n      eapply cequivc_halts_like_preserves_hasvalue_likec; eauto.\n  - left.\n    apply equality_in_uni_mkc_halts_like; 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_can.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.2699024039628502}}
{"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.\nLocal Open Scope N_scope.\nLocal Open Scope vector_scope.\n\n(******************************************************************************)\n(* A generic description of all adder trees made from a syntheszable adder    *)\n(* by using the tree combinator.                                              *)\n(******************************************************************************)\n\nSection WithCava.\n  Context {signal} `{Cava signal}.\n\n  (* An adder-tree with no bit-growth. *)\n  Definition adderTree {sz: nat}\n             (n: nat)\n    : signal (Vec (Vec Bit sz) (2^n)) ->\n      cava (signal (Vec Bit sz)) :=\n    tree addN.\n\n  (* An adder tree with 2 inputs. *)\n  Definition adderTree2 {sz: nat}\n                        (v : signal (Vec (Vec Bit sz) 2))\n                        : cava (signal (Vec Bit sz))\n    := adderTree 1 v.\n\n  (* An adder tree with 4 inputs. *)\n  Definition adderTree4 {sz: nat}\n                        (v : signal (Vec (Vec Bit sz) 4))\n                        : cava (signal (Vec Bit sz))\n    := adderTree 2 v.\n\nEnd WithCava.\n\n(******************************************************************************)\n(* Some tests.                                                                *)\n(******************************************************************************)\n\nDefinition v0 := N2Bv_sized 8  4.\nDefinition v2 := N2Bv_sized 8  6.\nDefinition v1 := N2Bv_sized 8 17.\nDefinition v3 := N2Bv_sized 8  3.\n\nDefinition v0_v1 := [v0; v1].\nDefinition v0_plus_v1 : Bvector 8 := adderTree 1 v0_v1.\n\nExample sum_vo_v1 : adderTree2 v0_v1 = N2Bv_sized 8 21.\nProof. reflexivity. Qed.\n\nDefinition v0_3 := [v0; v1; v2; v3].\nDefinition sum_v0_3 : Bvector 8 := adderTree4 v0_3.\n\nExample sum_v0_v1_v2_v3 : adderTree4 v0_3 = N2Bv_sized 8 30.\nProof. reflexivity. Qed.\n\nDefinition adder_tree_Interface name nrInputs bitSize\n  := combinationalInterface name\n     [mkPort \"inputs\" (Vec (Vec Bit bitSize) nrInputs)]\n     [mkPort \"sum\" (Vec Bit bitSize)].\n\n(* Create netlist and test-bench for a 4-input adder tree. *)\n\nDefinition adder_tree4_8Interface := adder_tree_Interface \"adder_tree4_8\" 4 8.\n\nDefinition adder_tree4_8Netlist\n  := makeNetlist adder_tree4_8Interface adderTree4.\n\nDefinition adder_tree4_8_tb_inputs\n  := map (fun i => Vector.map (N2Bv_sized 8) i)\n     [[17;  42;  23;  95];\n      [ 4;  13; 200;  30];\n      [255; 74; 255; 200]\n     ].\n\nDefinition adder_tree4_8_tb_expected_outputs\n  := simulate (Comb adderTree4) adder_tree4_8_tb_inputs.\n\nDefinition adder_tree4_8_tb :=\n  testBench \"adder_tree4_8_tb\" adder_tree4_8Interface\n  adder_tree4_8_tb_inputs adder_tree4_8_tb_expected_outputs.\n\n(* Create netlist for a 32-input adder tree. *)\n\nDefinition adder_tree32_8Interface\n  := adder_tree_Interface \"adder_tree32_8\" 32 8.\n\nDefinition adder_tree32_8Netlist\n  := makeNetlist adder_tree32_8Interface (adderTree 5).\n\n(* Create netlist and test-bench for a 64-input adder tree. *)\n\nDefinition adder_tree64_8Interface\n  := adder_tree_Interface \"adder_tree64_8\" 64 8.\n\nDefinition adder_tree64_8Netlist\n  := makeNetlist adder_tree64_8Interface (adderTree 6).\n\nDefinition adder_tree64_8_tb_inputs\n  := map (Vector.map (N2Bv_sized 8))\n     (Vector.const 255 64 :: map (Vector.map N.of_nat)\n     [vseq 0 64; vseq 64 64; vseq 128 64]).\n\nDefinition adder_tree64_8_tb_expected_outputs\n  := simulate (Comb (adderTree 6)) adder_tree64_8_tb_inputs.\n\nDefinition adder_tree64_8_tb :=\n  testBench \"adder_tree64_8_tb\" adder_tree64_8Interface\n  adder_tree64_8_tb_inputs adder_tree64_8_tb_expected_outputs.\n\n(* Create netlist and test-bench for a 64-input adder tree adding 128-bit words. *)\n\nDefinition adder_tree64_128Interface := adder_tree_Interface \"adder_tree64_128\" 64 128.\n\nDefinition adder_tree64_128Netlist\n  := makeNetlist adder_tree64_128Interface (adderTree 6).\n\nDefinition adder_tree64_128_tb_inputs\n  := map (Vector.map (N2Bv_sized 128))\n     (Vector.const (2^128-1) 64 :: map (Vector.map N.of_nat)\n     [vseq 0 64; vseq 64 64; vseq 128 64]).\n\nDefinition adder_tree64_128_tb_expected_outputs\n  := simulate (Comb (adderTree 6)) adder_tree64_128_tb_inputs.\n\nDefinition adder_tree64_128_tb :=\n  testBench \"adder_tree64_128_tb\" adder_tree64_128Interface\n  adder_tree64_128_tb_inputs adder_tree64_128_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/examples/AdderTree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.2698859562062589}}
{"text": "Require Import FcEtt.sigs.\n\nRequire Import FcEtt.fc_dec_fuel.\nRequire Import FcEtt.fc_dec_aux.\n\nRequire Import FcEtt.imports.\nRequire Export FcEtt.ett_inf_cs.\nRequire Import FcEtt.ett_ind.\nRequire Export FcEtt.fc_invert.\n\nRequire Import FcEtt.dep_prog.\n\nRequire Import FcEtt.toplevel.\n\nRequire Import FcEtt.fc_get.\nRequire Import FcEtt.fc_context_fv.\n\n\nModule fc_dec_fun (wf : fc_wf_sig) (weak : fc_weak_sig) (subst : fc_subst_sig) (unique: fc_unique_sig).\n\nModule invert := fc_invert wf weak subst.\nModule fuel := fc_dec_fuel wf weak subst unique.\nModule aux := fc_dec_aux wf weak subst unique.\nModule get := fc_get wf weak subst unique.\n\nImport fuel aux unique wf subst invert get.\n\nUnset Implicit Arguments.\n\nLtac obtacpre :=\n  intros; simpl in *.\n\nLtac obtacsolve :=\n  intros; simpl in *; try solve [ok].\n\n\nLemma An_IsoConv': ∀ (G : context) (D : available_props)\n                     (a1 a2 A a1' a2' B : tm) phi1 phi2 (g : co),\n  phi1 =  (Eq a1 a2 A)  →\n  phi2 = (Eq a1' a2' B) →\n  AnnDefEq G D g A B  →\n  AnnPropWff G phi1 →\n  AnnPropWff G phi2 →\n  erase_tm a1 = erase_tm a1' →\n  erase_tm a2 = erase_tm a2' →\n  AnnIso G D (g_IsoConv phi1 phi2 g) phi1 phi2.\nProof.\n  intros.\n  subst phi1 phi2.\n  eauto.\nQed.\n\n\n\n(* More pratical version of these lemma (both forms are useful, though) *)\nLemma get_tpg_correct' : ∀ {G : context} {a A : tm},\n    AnnTyping G a A → A = get_tpg G a.\nProof.\n  move => G a A tpg.\n  by rewrite (@get_tpg_correct _ _ _(get_tpg G a) tpg _).\nDefined.\n\n\nLemma get_deq_correct' : ∀ {G : context} {D : available_props} {g : co} {A B},\n    AnnDefEq G D g A B → get_deq G g = (A, B).\nProof.\n  move => G ? g A B deq.\n  have eq: get_deq G g = (fst (get_deq G g), snd (get_deq G g)) by destruct (get_deq G g).\n  by move: (@get_deq_correct _ _ _ _ _ (fst (get_deq G g)) (snd (get_deq G g)) deq eq) => [-> ->].\nDefined.\n\nLemma get_iso_correct' : ∀ {G : context} {D : available_props} {g : co} {phi1 phi2 : constraint}, AnnIso G D g phi1 phi2 → get_iso G g = (phi1, phi2).\nProof.\n  move => G ? g phi1 phi2 iso.\n  have eq: get_iso G g = (fst (get_iso G g), snd (get_iso G g)) by destruct (get_iso G g).\n  by move: (@get_iso_correct _ _ _ _ _ (fst (get_iso G g)) (snd (get_iso G g)) iso eq) => [-> ->].\nDefined.\n\n\n\n(**** Tactics ****)\n(* TODO: reorganize the tactics, and move the ones which don't belong here *)\n\n\n(* FIXME: that may be defined in fc_dec_fun *)\nLtac clear_annoying :=\n  repeat match goal with\n    | [H: <<_>> = _ |- _ ] => clear H\n    | [H: <<_, _>> = _ |- _ ] => clear H\n    | [H: !! = _ |- _ ] => clear H\n    | [H: yeah = _ |- _ ] => clear H\n    | [H: nope = _ |- _ ] => clear H\n    | [ H :     !! = _     |- _ ] => clear H\n    | [ H :     _ + { _ } |- _ ] => clear H\n    | [ H : { _ } + { _ } |- _ ] => clear H\n    | [ H : { _ | _} + { _ } |- _ ] => clear H\n    | [ H : { _, _ | _} + { _ } |- _ ] => clear H\n  end.\n\n\n\nLtac intro_uniq_full H :=\n    match type of H with\n      | AnnTyping ?G ?a ?A =>\n        let x := fresh \"u\" in\n        move : (@AnnTyping_unique G a A H) => x;\n        (* Apply uniqueness to other hyps about the same term (and ctx) and discard them *)\n        repeat match goal with\n          | [H' : AnnTyping G a ?A' |- _ ] =>  move: (x _ H') => ?; wrap_hyp H'\n        end\n      | AnnDefEq ?G ?L ?g ?A1 ?A2 =>\n        let x := fresh \"u\" in\n        move : (@AnnDefEq_unique G L g A1 A2 H) => x;\n        (* Apply uniqueness to other hyps about the same term (and ctx) and discard them *)\n        repeat match goal with\n          | [H' : AnnDefEq G L g ?A1' ?A2' |- _ ] =>  move: (x _ _ H') => ?; wrap_hyp H'\n        end\n      | AnnIso ?G ?L ?g ?phi1 ?phi2 =>\n        let x := fresh \"u\" in\n        move : (@AnnIso_unique G L g phi1 phi2 H) => x;\n        (* Apply uniqueness to other hyps about the same term (and ctx) and discard them *)\n        repeat match goal with\n          | [H' : AnnIso G L g ?phi1' ?phi2' |- _ ] =>  move: (x _ _ H') => ?; wrap_hyp H'\n        end\n    end.\n\n\n(* Apply uniqueness of type to existing typing hyps *)\nLtac auto_uniq_full :=\n  revert_all_with intro_uniq_full; intros; pcess_hyps.\n\nLtac terminator := auto_uniq_full; subst_forall; subst; cbn; pcess_hyps;\n  (* FIXME: eauto db version: basic_nosolve_n 3 *)\n  (* FIXME: eauto doesn't (always, at least) use the typing constructors, while in theory it should... *)\n  try solve [try econstructor; intuition (subst; eauto 3) | intuition (subst; eauto 3 with smart_cons_exists)].\n\nLtac hacky :=\n  do 3 (\n    intros;\n    (*\n    repeat match goal with\n      | [ p : tm * tm |- _ ] => destruct p; cbn in *\n    end; *)\n  try(\n  try (multimatch goal with\n    | [ |- ¬ _ ] => let H := fresh in intro H; inversion H; terminator\n    | _ => idtac\n  end);\n  try (multimatch goal with\n    | [ H : ¬ _ |-  _ ] => solve [edestruct H; terminator]\n    | [ H : forall _, ¬ _ |-  _ ] => solve [edestruct H; terminator]\n    | [ H : forall _ _, ¬ _ |-  _ ] => solve [edestruct H; terminator]\n  end); terminator)).\n\n\n(* Cleanup tactics\n   TODO: do we want them here or elsewhere? *)\nLtac clearbodies :=\n  repeat match goal with\n    | [ H := _ : _ |- _] => clearbody H\n  end.\n(* TODO: should be in tactics.v *)\nLtac clearbodies' :=\n  repeat match goal with\n    | [ x := ?bdy : _ |- _] =>\n      move: (eq_refl x);\n      rewrite -{2}[x]/bdy;\n      clearbody x;\n      let eqname := fresh \"eq\" x in\n      move => eqname\n  end.\n\n\n\n\n(* Ugly to have to grab them by their types, but we can't refer to their names (even after the definitions) *)\nLtac clean_fun :=\n  match goal with\n    | [\n        AnnTyping_dec : Tactics.fix_proto (∀ (G : context) (t : tm), fuel_tpg t → AnnCtx G → {T : tm | AnnTyping G t T} + {(∀ T : tm, ¬ AnnTyping G t T)}),\n        AnnPropWff_dec : Tactics.fix_proto (∀ (G : context) (phi : constraint), fuel_pwf phi → AnnCtx G → {AnnPropWff G phi} + {¬ AnnPropWff G phi}),\n        AnnDefEq_dec : Tactics.fix_proto (∀ (G : context) (S : available_props) (g : co), fuel_deq g → AnnCtx G → {A, B | AnnDefEq G S g A B} + {(∀ A B : tm, ¬ AnnDefEq G S g A B)}),\n        AnnIso_dec : Tactics.fix_proto (∀ (G : context) (S : available_props) (g : co), fuel_iso g → AnnCtx G → {phi1, phi2 | AnnIso G S g phi1 phi2} + {(∀ phi1 phi2 : constraint, ¬ AnnIso G S g phi1 phi2)})\n      |- _ ] => clear AnnTyping_dec AnnPropWff_dec AnnDefEq_dec AnnIso_dec\n  end.\n\n\nLtac clear_sums :=\n  repeat match goal with\n    | [ H :     !! = _     |- _ ] => clear H\n    | [ H :     _ + { _ } |- _ ] => clear H\n    | [ H : { _ } + { _ } |- _ ] => clear H\n  end.\n\n\nLtac cleanup_param cbodies sbst:=\n  clear_annoying;\n  intros; simpl in *;\n  cbodies;\n  try solve [ok];\n  try clean_fun;\n  clear_sums;\n  sbst. (* FIXME: for some reason, that subst breaks clear_fun if placed before it *)\n\nLtac cleanup := cleanup_param clearbodies subst.\nLtac cleanup' := cleanup_param clearbodies' idtac.\n\n\n\n\nObligation Tactic := try solve [hacky].\n\n(* We need an unfueled version for AnnIso_dec - in that case, we have the subterms and a typing for them (by regularity), but no *fuel* *)\nProgram Definition AnnPropWff_dec' (G: context) (a b A : tm) (A' B': tm) (H : AnnCtx G)\n                                  (pA: AnnTyping G a A') (pB: AnnTyping G b B') : {AnnPropWff G (Eq a b A)} + {¬ AnnPropWff G (Eq a b A)} :=\n  tm_eq_dec A A' >-->\n  tm_eq_dec (erase A) (erase B') >-->\n  yeah.\n\nObligation Tactic := obtacpre; first [match goal with [|- tm] => idtac end | eassumption].\n\n(** A system FC development wouldn't be right without a good, Haskell-style code. So please, enjoy. **)\n\n(* Naming scheme: fX is the name of the fuel for X *)\nProgram Fixpoint AnnTyping_dec (G : context) (t : tm) (fuel : fuel_tpg t) (H : AnnCtx G) {struct fuel} : {T : tm | AnnTyping G t T } + {(forall T, ¬ AnnTyping G t T)}  :=\n  match fuel with\n    | FT_Star =>  << a_Star >>\n\n    | FT_Var_f x =>\n      A <- binds_dec_tm x G;\n      << A >>\n\n    | FT_Pi rho A B fB fA =>\n      let (x, p) := atom_fresh (dom G \\u fv_tm_tm_tm B) in\n      KA <- AnnTyping_dec G A fA _;\n      tm_eq_dec KA a_Star >--->\n      KB <- AnnTyping_dec ([(x, Tm A)] ++ G) (open_tm_wrt_tm B (a_Var_f x)) (fB x _) _;\n      tm_eq_dec KB a_Star >--->\n      << a_Star >>\n\n    | FT_Abs rho a A fa fA =>\n      (* (∀ x : atom, ¬ x `in` L → Typing ([(x, Tm A)] ++ G) (open_tm_wrt_tm a (a_Var_f x)) (open_tm_wrt_tm B (a_Var_f x))) *)\n      let (x, p) := atom_fresh (dom G \\u fv_tm_tm_tm a) in\n      KA <- AnnTyping_dec G A fA _;\n      tm_eq_dec KA a_Star >--->\n      B <- AnnTyping_dec ([(x, Tm A)] ++ G) (open_tm_wrt_tm a (a_Var_f x)) (fa x _) _;\n      RhoCheck_erase_dec rho x (open_tm_wrt_tm a (a_Var_f x)) _ >--->\n      << a_Pi rho A (close_tm_wrt_tm x B )>>\n\n\n    | FT_App rho b a fb fa =>\n      A <- AnnTyping_dec G a fa _;\n      Tf <- AnnTyping_dec G b fb _;\n      match Tf with\n        | a_Pi rho' A' B =>\n          tm_eq_dec A' A >--->\n          rho_eq_dec rho rho' >---> << open_tm_wrt_tm B a >>\n        | _ => !!\n      end\n\n    | FT_Conv a g fa fg =>\n      A <- AnnTyping_dec G a fa _;\n      A' & B <- AnnDefEq_dec G (dom G) g fg _;\n      let K := get_tpg G B in\n  (*  K <- AnnTyping_dec G B _ _;  *)\n      tm_eq_dec K a_Star >--->\n      tm_eq_dec A A' >--->\n      << B >>\n\n    | FT_CApp b g fb fg =>\n      TB <- AnnTyping_dec G b fb _ ;\n      A1' & A2' <- AnnDefEq_dec G (dom G) g fg _;\n      match TB with\n        | (a_CPi (Eq A1 A2 K) B) =>\n          tm_eq_dec A1 A1' >--->\n          tm_eq_dec A2 A2' >--->\n          << open_tm_wrt_co B g >>\n        | _ => !!\n      end\n\n    | FT_Const T =>\n      K <- binds_dec_cs T an_toplevel;\n      (@DataTy_Star_dec K) _ >--->\n      << K >>\n\n    | FT_CPi phi B fB fphi =>\n      AnnPropWff_dec G phi fphi _ >--->\n      let (c, p) := atom_fresh (dom G \\u fv_co_co_tm B) in\n      KB <- AnnTyping_dec ([(c, Co phi)] ++ G) (open_tm_wrt_co B (g_Var_f c)) (fB c _) _;\n      tm_eq_dec KB a_Star >--->\n      << a_Star >>\n\n    | FT_CAbs a phi fa fphi =>\n      AnnPropWff_dec G phi fphi _ >--->\n      let (c, p) := atom_fresh (dom G \\u fv_co_co_constraint phi \\u fv_co_co_tm a) in\n      Bc <- AnnTyping_dec ((c ~ Co  phi ) ++  G) (open_tm_wrt_co a (g_Var_f c)) (fa c _) _;\n      << a_CPi phi (close_tm_wrt_co c Bc) >>\n\n    (* Erased language side: not typable in the annotated *)\n    | FT_UAbs _ _ => !!\n    | FT_UCAbs _  => !!\n    | FT_Bullet   => !!\n\n\n    | FT_Var_b _ => !!\n  (*  | a_FamApp _ _ => !! *)\n    | FT_DataCon _ => !!\n    | FT_Case _ _ => !!\n\n    | FT_Fam F =>\n      a & A <- binds_dec_ax F an_toplevel;\n        << A >>\n  end\n\n\nwith AnnPropWff_dec (G: context) (phi : constraint) (fuel : fuel_pwf phi)\n                    (H : AnnCtx G) {struct fuel} : {AnnPropWff G phi} + {¬ AnnPropWff G phi} :=\n  match fuel with\n    | FP_fuel_pwf a b K fa fb =>\n      Ka <-- AnnTyping_dec G a fa _;\n      Kb <-- AnnTyping_dec G b fb _;\n      tm_eq_dec K Ka >-->\n      tm_eq_dec (erase K) (erase Kb) >--> yeah\n  end\n\n\nwith AnnDefEq_dec (G: context) (S : available_props) (g : co) (fuel : fuel_deq g)\n                  (H: AnnCtx G) {struct fuel} : {A, B | AnnDefEq G S g A B} + {(forall A B, ¬ AnnDefEq G S g A B)} :=\n  match fuel with\n    | FD_Assn c =>\n        in_dec c S >--->\n        AB & K <- binds_dec_co c G;\n        << fst AB, snd AB >>\n\n    | FD_Refl a fa =>\n        A <- AnnTyping_dec G a fa _;\n        <<a, a>>\n\n    | FD_Refl2 a b g fa fb fg =>\n        A <- AnnTyping_dec G a fa _;\n        B <- AnnTyping_dec G b fb _;\n        tm_eq_dec (erase_tm a) (erase_tm b) >--->\n        A' & B' <- AnnDefEq_dec G (dom G) g fg _;\n        tm_eq_dec A A' >--->\n        tm_eq_dec B B' >--->\n        << a, b >>\n\n    | FD_Sym g fg =>\n        b & a <- AnnDefEq_dec G S g fg _;\n        << a, b >>\n\n    | FD_Trans g1 g2 fg1 fg2 =>\n        a & c <- AnnDefEq_dec G S g1 fg1 _;\n        d & b <- AnnDefEq_dec G S g2 fg2 _;\n        tm_eq_dec c d >--->\n        << a, b >>\n\n\n    | FD_Beta a1 a2 fa1 fa2 =>\n        A1 <- AnnTyping_dec G a1 fa1 _;\n        A2 <- AnnTyping_dec G a2 fa2 _;\n        tm_eq_dec (erase_tm A1) (erase_tm A2) >--->\n        @beta_dec (erase_tm a1) (erase_tm a2) _ >--->\n        << a1, a2 >>\n\n\n    | FD_PiCong rho g1 g2 fg1 fg2 =>\n      A1 & A2 <- AnnDefEq_dec G S g1 fg1 _;\n      tm_eq_dec (get_tpg G A1) a_Star >--->\n      tm_eq_dec (get_tpg G A2) a_Star >--->\n      let (x, _) := atom_fresh (dom G \\u fv_tm_tm_co g1 \\u fv_tm_tm_co g2) in\n      B1x & B2x <- AnnDefEq_dec ([(x, Tm A1)] ++ G) S (open_co_wrt_tm g2 (a_Var_f x)) (fg2 x _) _;\n      let B1  := close_tm_wrt_tm x B1x in\n      let B2  := close_tm_wrt_tm x B2x in\n      let B3x := tm_subst_tm_tm (a_Conv (a_Var_f x) (g_Sym g1)) x B2x in\n      let B3  := close_tm_wrt_tm x B3x in\n      (* let B3 := close_tm_wrt_tm x (tm_subst_tm_tm (a_Conv (a_Var_f x) (g_Sym g1)) x B2x) in *)\n      tm_eq_dec (get_tpg ([(x, Tm A1)] ++ G) B1x) a_Star >--->\n      tm_eq_dec (get_tpg ([(x, Tm A1)] ++ G) B2x) a_Star >--->\n      tm_eq_dec (get_tpg ([(x, Tm A2)] ++ G) B3x) a_Star >--->\n      << a_Pi rho A1 B1, a_Pi rho A2 B3 >>\n\n\n    | FD_AbsCong rho g1 g2 fg1 fg2 =>\n      A1 & A2 <- AnnDefEq_dec G S g1 fg1 _;\n      tm_eq_dec (get_tpg G A1) a_Star >--->\n      tm_eq_dec (get_tpg G A2) a_Star >--->\n      let (x, p) := atom_fresh (dom G \\u fv_tm_tm_co g1 \\u fv_tm_tm_co g2) in\n      B1x & B2x <- AnnDefEq_dec ([(x, Tm A1)] ++ G) S (open_co_wrt_tm g2 (a_Var_f x)) (fg2 x _) _;\n      let B1 := close_tm_wrt_tm x B1x in\n      let B2 := close_tm_wrt_tm x B2x in\n      let B3x := tm_subst_tm_tm (a_Conv (a_Var_f x) (g_Sym g1)) x B2x in\n      let B3  := close_tm_wrt_tm x B3x in\n      (* let B3 := close_tm_wrt_tm x (open_tm_wrt_tm B2 (a_Conv (a_Var_f x) (g_Sym g1))) in *)\n      (* let B3 := close_tm_wrt_tm x (tm_subst_tm_tm (a_Conv (a_Var_f x) (g_Sym g1)) x B2x) in *)\n      RhoCheck_erase_dec rho x B1x _ >--->\n      RhoCheck_erase_dec rho x B3x _ >--->\n      (* B <- AnnTyping_dec G (a_Abs rho A1 B2) _ _; *)\n      << a_Abs rho A1 B1, a_Abs rho A2 B3 >>\n\n\n    | FD_AppCong g1 g2 rho fg1 fg2 =>\n      a1 & a2 <- AnnDefEq_dec G S g1 fg1 _;\n      b1 & b2 <- AnnDefEq_dec G S g2 fg2 _;\n      let Ta1 := get_tpg G a1 in\n      let Ta2 := get_tpg G a2 in\n      let Tb1 := get_tpg G b1 in\n      let Tb2 := get_tpg G b2 in\n      match Ta1, Ta2 with\n        | a_Pi rho1 A1 _, a_Pi rho2 A2 _ =>\n          tm_eq_dec A1 Tb1 >--->\n          tm_eq_dec A2 Tb2 >--->\n          rho_eq_dec rho rho1 >--->\n          rho_eq_dec rho rho2 >--->\n          << a_App a1 rho b1, a_App a2 rho b2 >>\n        | _, _ => !!\n      end\n\n\n    | FD_CPiCong g1 g3 fg1 fg3 =>\n        phi1 & phi2 <- AnnIso_dec G S g1 fg1 _;\n        let (c, _) := atom_fresh (S \\u dom G \\u fv_co_co_co g1 \\u fv_co_co_co g3) in\n        B1c & B2c <- AnnDefEq_dec ([(c, Co phi1)] ++ G) S (open_co_wrt_co g3 (g_Var_f c)) (fg3 c _) _;\n        let B1  := close_tm_wrt_co c B1c in\n        let B2  := close_tm_wrt_co c B2c in\n        let B3c := open_tm_wrt_co B2 (g_Cast (g_Var_f c) (g_Sym g1)) in\n        let B3  := close_tm_wrt_co c (B3c) in\n        tm_eq_dec (get_tpg ([(c,Co phi1)] ++ G) B1c) a_Star >--->\n        tm_eq_dec (get_tpg ([(c,Co phi2)] ++ G) B3c) a_Star >--->\n        tm_eq_dec (get_tpg ([(c,Co phi1)] ++ G) B2c) a_Star >--->\n        << a_CPi phi1 B1, a_CPi phi2 B3 >>\n\n\n    | FD_CAbsCong g1 g3 g4 fg1 fg3 fg4 =>\n        phi1 & phi2 <- AnnIso_dec G S g1 fg1 _;\n        let (c, _) := atom_fresh (S \\u dom G \\u fv_co_co_co g1 \\u fv_co_co_co g3) in\n        a1c & a2c <- AnnDefEq_dec ([(c, Co phi1)] ++ G) S (open_co_wrt_co g3 (g_Var_f c)) (fg3 c _) _;\n        let a1  := close_tm_wrt_co c a1c in\n        let a2  := close_tm_wrt_co c a2c in\n        let a3c := open_tm_wrt_co a2 (g_Cast (g_Var_f c) (g_Sym g1)) in\n        let a3  := close_tm_wrt_co c a3c in\n        let B1c := get_tpg ([(c, Co phi1)] ++ G) a1c in\n        let B3c := get_tpg ([(c, Co phi2)] ++ G) a3c in\n        CPi1 & CPi2 <- AnnDefEq_dec G (dom G) g4 fg4 _;\n        tm_eq_dec CPi1 (a_CPi phi1 (close_tm_wrt_co c B1c)) >--->\n        tm_eq_dec CPi2 (a_CPi phi2 (close_tm_wrt_co c B3c)) >--->\n        << a_CAbs phi1 a1, a_CAbs phi2 a3 >>\n\n\n    | FD_CAppCong g1 g2 g3 fg1 fg2 fg3 =>\n      a1 & a2 <- AnnDefEq_dec G S g1 fg1 _;\n      b1 & b2 <- AnnDefEq_dec G (dom G) g2 fg2 _;\n      c1 & c2 <- AnnDefEq_dec G (dom G) g3 fg3 _;\n      let Ta1 := get_tpg G a1 in\n      let Ta2 := get_tpg G a2 in\n      match Ta1, Ta2 with\n        | a_CPi (Eq Ta11 Ta12 _) _, a_CPi (Eq Ta21 Ta22 _) _ =>\n          (* TODO: in theory, one would want to do a cons_eq_dec - but DeqEq_dec doesn't return the type *)\n          tm_eq_dec Ta11 b1 >--->\n          tm_eq_dec Ta12 b2 >--->\n          tm_eq_dec Ta21 c1 >--->\n          tm_eq_dec Ta22 c2 >--->\n          << a_CApp a1 g2, a_CApp a2 g3 >>\n        | _, _ => !!\n      end\n\n    | FD_CPiSnd g1 g2 g3 fg1 fg2 fg3 =>\n      a1 & a2 <- AnnDefEq_dec G S g1 fg1 _;\n      a & a' <- AnnDefEq_dec G (dom G) g2 fg2 _;\n      b & b' <- AnnDefEq_dec G (dom G) g3 fg3 _;\n      match a1, a2 with\n        | a_CPi (Eq a_ a_' _) B1, a_CPi (Eq b_ b_' _) B2 =>\n          tm_eq_dec a  a_  >--->\n          tm_eq_dec a' a_' >--->\n          tm_eq_dec b  b_  >--->\n          tm_eq_dec b' b_' >--->\n          << open_tm_wrt_co B1 g2, open_tm_wrt_co B2 g3 >>\n        | _, _ => !!\n      end\n\n\n    | FD_Cast g1 g2 fg1 fg2 =>\n      a & a' <- AnnDefEq_dec G S g1 fg1 _;\n      phi1 & phi2 <- AnnIso_dec G S g2 fg2 _;\n      match phi1, phi2 with\n        | Eq a_ a'_ _, Eq b b' _ =>\n          tm_eq_dec a  a_  >--->\n          tm_eq_dec a' a'_ >--->\n          << b, b' >>\n      end\n\n    | FD_PiFst g fg =>\n      T1 & T2 <- AnnDefEq_dec G S g fg _;\n      match T1, T2 with\n        | a_Pi rho1 A1 B1, a_Pi rho2 A2 B2 => rho_eq_dec rho1 rho2 >---> << A1, A2 >>\n        | _, _ => !!\n      end\n\n\n\n    | FD_PiSnd g1 g2 fg1 fg2 =>\n        T1 & T2 <- AnnDefEq_dec G S g1 fg1 _;\n        a1 & a2 <- AnnDefEq_dec G S g2 fg2 _;\n     (* A1 <- AnnTyping_dec G a1 _ _;\n        A2 <- AnnTyping_dec G a2 _ _; *)\n        let A1 := get_tpg G a1 in\n        let A2 := get_tpg G a2 in\n        match T1 with\n          | a_Pi rho A1' B1 =>\n            tm_eq_dec A1 A1' >--->\n            match T2 with\n              | a_Pi rho' A2' B2 =>\n                tm_eq_dec A2 A2' >--->\n                rho_eq_dec rho rho' >--->\n                << open_tm_wrt_tm B1 a1, open_tm_wrt_tm B2 a2 >>\n              | _ => !!\n            end\n          | _ => !!\n        end\n\n\n    | FD_IsoSnd g fg =>\n      phi1 & phi2 <- AnnIso_dec G S g fg _;\n      match phi1, phi2 with\n        | (Eq _ _ A), (Eq _ _ B) => << A, B>>\n      end\n\n\n    | FD_Eta b fb =>\n      let (x, p) := atom_fresh (dom G \\u fv_tm_tm_tm b) in\n      T <- AnnTyping_dec G b fb _;\n      match T with\n      | a_Pi Rel A B =>\n        << a_Abs Rel A (close_tm_wrt_tm x (a_App b Rel (a_Var_f x))), b >>\n      | a_Pi Irrel A B =>\n        << a_Abs Irrel A (close_tm_wrt_tm x (a_App b Irrel (a_Var_f x))), b >>\n      | a_CPi phi B =>\n        << a_CAbs phi (close_tm_wrt_co x (a_CApp b (g_Var_f x))), b >>\n      | _ => !!\n      end\n\n    | FD_Left g1  g2 fg1 fg2  => !!\n    | FD_Right _ _ _ _ => !!\n(* Left/Right.   This doesn't work yet.\n    | FD_Left g1  g2 fg1 fg2  =>\n      s1 & s2 <- AnnDefEq_dec G S g1 fg1 _;\n      t1 & t2 <- AnnDefEq_dec G (dom G) g2 fg2 _ ;\n      match s1 with\n      | (a_App a1 Rel a2) =>\n        match s2 with\n        | (a_App a1' Rel a2') =>\n          match t1 with\n          | (a_Pi Rel A1 B1) =>\n            match t2 with\n            | (a_Pi Rel A2 B2) =>\n              path_dec a1 >--->\n              path_dec a1' >--->\n              let A := get_tpg G a1  in\n              let A' := get_tpg G a1' in\n              tm_eq_dec A (a_Pi Rel A1 B1) >--->\n              tm_eq_dec A' (a_Pi Rel A2 B2) >--->\n              << a1 , a1' >>\n            | _ => !!\n            end\n          | _ => !!\n          end\n        | _ => !!\n        end\n      | _ => !!\n      end\n        (*\n      | (a_App a1 Irrel a2, a_App a1' Irrel a2', a_Pi Irrel A1 B1, a_Pi Irrel A2 B2) =>\n          let A := get_tpg G a1  in\n          let A' := get_tpg G a1' in\n          tm_eq_dec A (a_Pi Irrel A1 B1) >--->\n          tm_eq_dec A' (a_Pi Irrel A2 B2) >--->\n          << a1 , a1' >>\n\n      | (a_CApp a1 a2, a_CApp a1' a2', a_CPi A1 B1, a_CPi A2 B2) =>\n          let A := get_tpg G a1  in\n          let A' := get_tpg G a1' in\n          tm_eq_dec A (a_CPi A1 B1) >--->\n          tm_eq_dec A' (a_CPi A2 B2) >--->\n          << a1 , a1' >>\n\n      | _ => !!\n      end *)\n\n    | FD_Right g1  g2 fg1 fg2  =>\n      s1 & s2 <- AnnDefEq_dec G S g1 fg1 _;\n      t1 & t2 <- AnnDefEq_dec G (dom G) g2 fg2 _ ;\n      match (s1, s2, t1, t2) with\n      | (a_App a1 r1 a2, a_App a1' r2 a2', a_Pi r3 A1 B1, a_Pi r4 A2 B2) =>\n          let A := get_tpg G a1  in\n          let A' := get_tpg G a1' in\n          tm_eq_dec A (a_Pi r3 A1 B1) >--->\n          tm_eq_dec A' (a_Pi r4 A2 B2) >--->\n          rho_eq_dec r1 r2 >--->\n          rho_eq_dec r1 r3 >--->\n          rho_eq_dec r1 r4 >--->\n          << a2 , a2' >>\n      | _ => !!\n      end\n*)\n    (* Trivial cases *)\n    | FD_Triv          => !!\n    | FD_Var_b _       => !!\n    | FD_CPiFst _      => !!\n    | FD_Cong _ _ _    => !!\n    | FD_IsoConv _ _ _ => !!\n\n  end\n\n\nwith AnnIso_dec (G: context) (S : available_props) (g : co) (fuel : fuel_iso g)\n                (H: AnnCtx G) {struct fuel} : {phi1, phi2 | AnnIso G S g phi1 phi2} + {(forall phi1 phi2, ¬ AnnIso G S g phi1 phi2)} :=\n  match fuel with\n    | FI_Cong g1 A g2 fg1 fg2 =>\n      A1 & A2 <- AnnDefEq_dec G S g1 fg1 _;\n      B1 & B2 <- AnnDefEq_dec G S g2 fg2 _;\n      AnnPropWff_dec' G A1 B1 A (get_tpg G A1) (get_tpg G B1) _ _ _ >--->\n      AnnPropWff_dec' G A2 B2 A (get_tpg G A2) (get_tpg G B2) _ _ _ >--->\n      << Eq A1 B1 A, Eq A2 B2 A >>\n\n    | FI_CPiFst g fg =>\n      pi1 & pi2 <- AnnDefEq_dec G S g fg _;\n      match pi1, pi2 with\n        | a_CPi phi1 _, a_CPi phi2 _ =>\n          << phi1, phi2 >>\n        | _, _ => !!\n      end\n\n    | FI_IsoSym g fg =>\n      phi2 & phi1 <- AnnIso_dec G S g fg _;\n      << phi1, phi2 >>\n\n\n    | FI_IsoConv g phi1 phi2 fg fpwf1 fpwf2  =>\n      A' & B' <- AnnDefEq_dec G S g fg _;\n      AnnPropWff_dec G phi1 fpwf1 _ >--->\n      AnnPropWff_dec G phi2 fpwf2 _ >--->\n      match phi1, phi2 with\n        | Eq a1 a2 A, Eq a1' a2' B =>\n          tm_eq_dec (erase_tm  a1) (erase_tm  a1') >--->\n          tm_eq_dec (erase_tm  a2) (erase_tm  a2') >--->\n          tm_eq_dec A A' >--->\n          tm_eq_dec B B' >--->\n          << phi1, phi2 >>\n      end\n\n\n\n    (* Non-iso coercions *)\n    | FI_Var_f c => !!\n    | FI_Var_b _ => !!\n    | FI_Refl a => !!\n    | FI_Refl2 a b g => !!\n    | FI_Trans g1 g2 =>  !!\n    | FI_Beta a1 a2 => !!\n    | FI_PiCong rho g1 g2 => !!\n    | FI_AbsCong _ _ _ => !!\n    | FI_AppCong g1 rho g2 => !!\n    | FI_CAbsCong _ _ _ => !!\n    | FI_CAppCong g1 g2 g3 => !!\n    | FI_PiFst g => !!\n    | FI_Cast g1 g2 => !!\n    | FI_PiSnd g1 g2 => !!\n    | FI_Triv => !!\n    | FI_CPiCong _ _ => !!\n    | FI_CPiSnd _ _ _ => !!\n    | FI_IsoSnd _ => !!\n    | FI_Eta _ => !!\n    | FI_Left _ _ => !!\n    | FI_Right _ _ => !!\n  end\n\n.\n\n\n\n\n(*\nSolve Obligations of AnnDefEq_dec with obtacpre; first [match goal with [|- tm] => idtac end | eassumption].\n*)\n\n\n\n\n\nObligation Tactic :=\n  obtacsolve.\n\n\n\n\n\n\n\n\n(******** AnnDefEq_dec ********)\n\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\n\n(* An_EraseEq *)\nNext Obligation.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\nDefined.\n\n(* An_Sym *)\nNext Obligation.\n  hacky.\nDefined.\n\nObligation Tactic := obtacpre.\n\n\nNext Obligation.\n  eauto using An_Sym2.\nDefined.\n\n(* An_Trans *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  subst.\n  eauto using An_Trans2.\nDefined.\n\n\n(* An_Beta *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  move: lc_erase => [h0 _].\n  eapply h0.\n  move: (AnnTyping_lc wildcard'0) => [h1 _].\n  auto.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  cleanup.\nDefined.\n\n\n(* FIXME: in the following hard cases (Abs/CAbs/Pi/CPi -Cong), the code likely contains a lot of junk\n    It could also be made more concise, by using more ssr magic *)\n\n(* TODO: this belongs in tactics *)\n  Ltac reg H :=\n  match type of H with\n    | AnnTyping _ ?a ?A =>\n      first\n        [ let tpgA := fresh \"tpg\" A in move: (AnnTyping_regularity H) => tpgA\n        | let tpgA := fresh \"tpg\"   in move: (AnnTyping_regularity H) => tpgA]\n    | AnnDefEq _ _ ?g ?A ?B =>\n      let KA := fresh \"K\" A in\n      let KB := fresh \"K\" B in\n      let g' := fresh \"g\" in\n      let tpgA := fresh \"tpg\" A in\n      let tpgB := fresh \"tpg\" B in\n      (* let deqg' := fresh \"deq\" g' in *)\n      move: (AnnDefEq_regularity H) => [KA [KB [g' [tpgA [tpgB (* deqg' *) _]]]]]\n    (* FIXME: this is the same case than above, with less informative fresh names.\n       This is needed because fresh can fail (like, seriously?)\n       TODO: failproof version of fresh *)\n    | AnnDefEq _ _ ?g ?A ?B =>\n      let KA := fresh \"K\" in\n      let KB := fresh \"K\" in\n      let g' := fresh \"g\" in\n      let tpgA := fresh \"tpg\" in\n      let tpgB := fresh \"tpg\" in\n      (* let deqg' := fresh \"deq\" g' in *)\n      move: (AnnDefEq_regularity H) => [KA [KB [g' [tpgA [tpgB (* deqg' *) _]]]]]\n\n    | AnnIso _ _ ?g ?phi1 ?phi2 =>\n      let pwfp1 := fresh \"pwf\" phi1 in\n      let pwfp2 := fresh \"pwf\" phi2 in\n      move: (AnnIso_regularity H) => [pwfp1 pwfp2]\n  end.\n\n\nLtac cleanup_getcor :=\n  repeat match goal with\n    | [ _: get_tpg _ _ = get_tpg _ _ |- _ ] => fail\n    | [ eq: _ = get_tpg _ _ |- _ ] => symmetry in eq\n  end.\n\n\n(* FIXME: same, should be elsewhere (fc_invert.v?) *)\nLtac getcor a :=\n  cleanup_getcor;\n  match goal with\n    | [ eq: get_tpg ?G a = _,\n        tpg : AnnTyping ?G a ?A |- _ ] =>\n          let t := fresh tpg in\n          move: (get_tpg_correct tpg eq) => t; subst A\n  end.\n\n\n(* TODO: location *)\n(* For now, this assumes that we only need regularity on defeq hyps *)\nLtac autoreg :=\n  repeat match goal with\n    | [ H: AnnDefEq _ _ _ _ _ |- _ ] =>\n      reg H; wrap_hyp H\n    | [ H: AnnIso _ _ _ _ _ |- _ ] =>\n      reg H; wrap_hyp H\n  end;\n  pcess_hyps.\n\nLtac clearget :=\n  cleanup_getcor;\n  repeat match goal with\n    | [ H: get_tpg _ _ = get_tpg _ _ |- _ ] => fail\n    | [ eqTa : get_tpg ?G ?a = ?Ta,\n        tpga : AnnTyping ?G ?a ?Ta' |- _ ] =>\n      let eq := fresh in\n      (* FIXME: in the following subst, we don't control which equation gets rewritten -> inconsistent results *)\n      move:(get_tpg_correct' tpga); move=> eq; rewrite <- eq in *; clear eq; subst Ta'\n  end.\n\n\n\n\n(* An_PiCong *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  cleanup.\n  inversion 1.\n  auto_uniq_full.\n  apply wildcard'.\n  have: A0 = A1 by done. move => <-.\n  inversion H9.\n  by move: (get_tpg_correct' H21) => <-.\nDefined.\nNext Obligation.\n  cleanup.\n  inversion 1.\n  auto_uniq_full.\n  apply wildcard'.\n  have: A3 = A2 by done. move => <-.\n  inversion H12.\n  by move: (get_tpg_correct' H21) => <-.\nDefined.\nNext Obligation. (* Fuel: aux obligation *)\n  fsetdec.\nDefined.\nNext Obligation. (* Ctx wf *)\n  econstructor; try eassumption.\n  - cleanup.\n    reg wildcard'0.\n    by getcor A1.\n  - fsetdec.\nDefined.\nNext Obligation.\n  cleanup.\n  move /An_PiCong_inversion.\n  move => [a1 [b1 [a2 [b2 [b3 [eqA [eqB [tpg1 [tpg2 [tpg3 [defeq h]]]]]]]]]]].\n  apply: wildcard'.\n  have xnotin: x `notin` dom G by fsetdec.\n  move: (h _ xnotin) => [h' _].\n  auto_uniq_full; subst.\n  by apply: h'.\nDefined.\nNext Obligation.\n  cleanup'.\n  move /An_PiCong_inversion.\n  move => [a1 [b1 [a2 [b2 [b3 [eqA [eqB [tpg1 [tpg2 [tpg3 [defeq h]]]]]]]]]]].\n  eapply wildcard'.\n  have xG: x `notin` dom G by fsetdec.\n  move: (h _ xG) => /= [h' _].\n  have: A1 = a1 by cleanup; auto_uniq_full. move => ?; subst A1.\n  auto_uniq_full.\n  move: (An_Pi_inversion tpg1) => [_ [_]] /(_ _ xG).\n  by move: (u3 _ _ wildcard'3) => [<- _] => /(get_tpg_correct') ->.\nDefined.\nNext Obligation.\n  cleanup'.\n  move /An_PiCong_inversion.\n  move => [a1 [b1 [a2 [b2 [b3 [eqA [eqB [tpg1 [tpg2 [tpg3 [defeq h]]]]]]]]]]].\n  eapply wildcard'.\n  have xG: x `notin` dom G by fsetdec.\n  move: (h _ xG) => /= [h' _].\n  have: A1 = a1 by cleanup; auto_uniq_full. move => ?; subst A1.\n  clearbodies'.\n  auto_uniq_full.\n  move: (An_Pi_inversion tpg3) => [_ [_]] /(_ _ xG).\n  by move: (u3 _ _ wildcard'3) => [_ <-] => /(get_tpg_correct') ->.\nDefined.\nNext Obligation.\n  cleanup'.\n  move /An_PiCong_inversion.\n  move => [a1 [b1 [a2 [b2 [b3 [eqA [eqB [tpg1 [tpg2 [tpg3 [defeq h]]]]]]]]]]].\n  eapply wildcard'.\n  have xG: x `notin` dom G by fsetdec.\n  move: (h _ xG) => /= [h' eqb3].\n  have: A1 = a1 by cleanup; auto_uniq_full. move => ?; subst A1.\n  have: A2 = a2 by cleanup; auto_uniq_full. move => ?; subst A2.\n  clearbodies'.\n  auto_uniq_full.\n  move: (An_Pi_inversion tpg2) => [_ [_]] /(_ _ xG).\n  have realeq : B3x = open_tm_wrt_tm B2 (a_Conv (a_Var_f x) (g_Sym g1)) by rewrite eqB3x eqB2 tm_subst_tm_tm_spec.\n  move: realeq eqb3 eqB2 H2 => -> -> -> <-. rewrite close_tm_wrt_tm_open_tm_wrt_tm.\n  - by move => /(get_tpg_correct') ->.\n  - (* Fv in context for tpg hyp *) (* TODO: tactic *)\n    move: ann_context_fv_mutual => [h'' [_ [_ [_ _] ] ] ]; move: h'' => /(_ _ _ _  tpg3) /= [htmco [hcoco [htmtm hcotm ] ] ].\n    by fsetdec.\nDefined.\nNext Obligation.\n  cleanup'.\n  rewrite eqB1 eqB3.\n  eapply An_PiCong_exists3 with (x := x); try eassumption.\n  fsetdec.\nDefined.\n\n\n\n(* An_AbsCong *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  cleanup.\n  move /An_AbsCong_inversion => [a1' [a2' [b1' [b2' [b3' [B' h]]]]]].\n  move: h => [eqA [eqB [tpga1' [tpga2' [defg1 [tpga1b2' h]]]]]].\n  apply: wildcard'.\n  have: A1 = a1' by auto_uniq_full.\n  move=> ->.\n  by rewrite (get_tpg_correct' tpga1').\nDefined.\nNext Obligation.\n  cleanup.\n  move /An_AbsCong_inversion => [a1' [a2' [b1' [b2' [b3' [B' h]]]]]].\n  move: h => [eqA [eqB [tpga1' [tpga2' [defg1 [tpga1b2' h]]]]]].\n  apply: wildcard'.\n  have: A2 = a2' by auto_uniq_full.\n  move=> ->.\n  by rewrite (get_tpg_correct' tpga2').\nDefined.\nNext Obligation. (* Fuel: aux obligation *)\n  fsetdec.\nDefined.\nNext Obligation. (* Ctx wf *)\n  econstructor; try eassumption.\n  - cleanup.\n    reg wildcard'0.\n    by getcor A1.\n  - fsetdec.\nDefined.\nNext Obligation.\n  cleanup.\n  move /An_AbsCong_inversion => [a1' [a2' [b1' [b2' [b3' [B' h]]]]]].\n  move: h => [eqA [eqB [tpga1' [tpga2' [defg1 [tpga1b2' h]]]]]].\n  apply: wildcard'.\n  auto_uniq_full.\n  have: A1 = a1' /\\ A2 = a2' by split; congruence.\n  move=> [? ?]. subst A1 A2.\n  have xG: x `notin` dom G by fsetdec.\n  move: (h x xG) => [tpgg2 [_ [h' _] ] ].\n  eassumption.\nDefined.\nNext Obligation.\n  by move: (wf.AnnDefEq_lc1 wildcard').\nDefined.\nNext Obligation.\n  cleanup.\n  move /An_AbsCong_inversion => [a1' [a2' [b1' [b2' [b3' [B' h]]]]]].\n  move: h => [eqA [eqB [tpga1' [tpga2' [defg1 [tpga1b2' h]]]]]].\n  have p': x `notin` dom G by fsetdec.\n  move: (h x p') => [tpgg2 [_ [h' _] ] ].\n  apply wildcard'.\n  suff eq: B1x = open_tm_wrt_tm b1' (a_Var_f x) by rewrite eq.\n  auto_uniq_full.\n  move: (u2 _ _ wildcard'0) => [eqA1 _].\n  rewrite eqA1 in tpgg2.\n  by move: (u _ _ tpgg2) => [->].\nDefined.\nNext Obligation.\n  cleanup'.\n  move: (wf.AnnDefEq_lc2 wildcard'3).\n  rewrite eqB3x => ?.\n  apply: tm_subst_tm_tm_lc_tm => /=.\n  + done.\n  + apply lc_a_Conv.\n    - done.\n    - move: (wf.AnnDefEq_lc3 wildcard'0) => ?.\n      econstructor; eassumption.\nDefined.\nNext Obligation.\n  clear dependent filtered_var.\n  cleanup'.\n  move=> tpgg1g2. move: (tpgg1g2).\n  move /An_AbsCong_inversion => [a1' [a2' [b1' [b2' [b3' [B' h]]]]]].\n  move: h => [eqA [eqB [tpga1' [tpga2' [defg1 [tpga1b2' h]]]]]].\n  apply wildcard'.\n  have p': x `notin` dom G by fsetdec.\n  move: (h x p') => [tpgg2 [eqb3' [_ h'] ] ].\n  suff eq: B3x = open_tm_wrt_tm b3' (a_Var_f x) by rewrite eq.\n  auto_uniq_full.\n  have: A1 = a1' /\\ A2 = a2' by split; congruence.\n  move=> [? ?]. subst A1 A2.\n  rewrite eqB3x.\n  move: (u5 _ _ wildcard'3) => [_ eqb2'].\n  rewrite -eqb2' eqb3' tm_subst_tm_tm_spec close_tm_wrt_tm_open_tm_wrt_tm.\n  - done.\n  - (* Fv in context for tpg hyp *)\n    move: ann_context_fv_mutual => [h''' [_ [_ [_ _] ] ] ]; move: h''' => /(_ _ _ _ tpga1b2') /= [htmco'' [hcoco'' [htmtm'' hcotm'' ] ] ].\n    by fsetdec.\nDefined.\nNext Obligation.\n  clear dependent filtered_var.\n  cleanup'.\n  rewrite eqB1 eqB3.\n  eapply An_AbsCong_exists3; try eassumption.\n  - fsetdec.\n  - reflexivity.\nDefined.\n\n\n\n\n(* An_AppCong *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  cleanup'.\n  inversion 1.\n  apply wildcard'.\n  reg wildcard'2.\n  reg wildcard'1.\n  getcor a1.\n  getcor b1.\n  subst Ta1 Tb1.\n  auto_uniq_full.\n  intro_uniq_full wildcard'2. (* FIXME: auto_uniq_full not working here *)\n  intro_uniq_full wildcard'1. (* FIXME: auto_uniq_full not working here *)\n  have: a0 = a1 by congruence => [-> _].\n  move=> ?.\n  subst a0. subst a3.\n  inversion H8.\n  intro_uniq_full H19. (* TODO: this proof is messy *)\n  have: A1 = A3 by congruence. move => ->.\n  by move: (get_tpg_correct' H21).\nDefined.\nNext Obligation.\n  cleanup'.\n  inversion 1.\n  apply wildcard'.\n  reg wildcard'2.\n  reg wildcard'1.\n  getcor a2.\n  getcor b2.\n  subst Ta2 Tb2.\n  auto_uniq_full.\n  intro_uniq_full wildcard'2. (* FIXME: auto_uniq_full not working here *)\n  intro_uniq_full wildcard'1. (* FIXME: auto_uniq_full not working here *)\n  have: a0 = a1 by congruence => [-> _].\n  move=> ?.\n  subst b0. subst b2.\n  inversion H11.\n  intro_uniq_full H20. (* TODO: this proof is messy *)\n  have: A2 = A3 by congruence. move => ->.\n  by move: (get_tpg_correct' H21).\nDefined.\nNext Obligation.\n  cleanup'.\n  cleanup_getcor.\n  autoreg.\n  clearget.\n  inversion 1. inversion H8.\n  apply: wildcard'.\n  auto_uniq_full. subst a0.\n  move: (u9 _ tpga1).\n  congruence.\nDefined.\nNext Obligation.\n  cleanup'.\n  cleanup_getcor.\n  autoreg.\n  clearget.\n  inversion 1. inversion H11.\n  apply: wildcard'.\n  auto_uniq_full. subst b0.\n  move: (u9 _ tpga2).\n  congruence.\nDefined.\nNext Obligation.\n  (* FIXME: cleanup' not working *)\n  clear dependent filtered_var.\n  clear dependent filtered_var1.\n  clear dependent filtered_var0.\n  clear dependent filtered_var2.\n  clear dependent filtered_var4.\n  clear dependent filtered_var3. subst. clear dependent fuel.\n  clean_fun. clearbodies'.\n\n  autoreg.\n  clearget.\n  auto_uniq_full.\n  eapply An_AppCong2; try eassumption.\n  all: econstructor;\n  eauto using An_AppCong2.\n  subst Ta1. eassumption.\n  subst Ta2. eassumption.\nDefined.\nNext Obligation.\n  cleanup'.\n  autoreg.\n  clearget.\n  hacky.\nDefined.\n\n\n(* The numerous cases for the pattern match have been inlined -> solving them automatically *)\nLtac discr_pat_match :=\n  solve [obtacpre; solve [ let eq1 := fresh in let eq2 := fresh in move=> [eq1 eq2]; try discriminate eq1; discriminate eq2\n                         | subst; inversion 1 ] ].\n\nSolve Obligations of AnnDefEq_dec with discr_pat_match.\n\n\n\n(* An_CPiCong *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation. (* Fuel: Aux *)\n  fsetdec.\nDefined.\nNext Obligation.\n  econstructor.\n  - eassumption.\n  - cleanup'. by autoreg.\n  - fsetdec.\nDefined.\nNext Obligation.\n  cleanup.\n  move /An_CPiCong_inversion.\n  move => [ph1 [ph2 [b1 [b2 [b3 [eqA [eqB [isoph1 [tpgp1 [tpgp2 [tpg3 h]]]]]]]]]]].\n  apply: wildcard'.\n  have cG: c `notin` dom G by ok.\n  move: (h _ cG) => /= [h' _].\n  auto_uniq_full; subst.\n  by apply: h'.\nDefined.\nNext Obligation.\n  cleanup'.\n  pcess_hyps.\n  move /An_CPiCong_inversion.\n  move => [ph1 [ph2 [b1 [b2 [b3 [eqA [eqB [isoph1 [tpgp1 [tpgp2 [tpg3 h]]]]]]]]]]].\n  apply: wildcard'.\n  auto_uniq_full.\n  have cG: c `notin` dom G by ok.\n  have: phi1 = ph1 by congruence. move=> eqphi. rewrite eqphi.\n  move: (An_CPi_inversion tpgp1). do 2 move=> [_]. move => /(_ c cG) h'.\n  move: (get_tpg_correct' h') => ->.\n  suff: B1c = (open_tm_wrt_co b1 (g_Var_f c)) by move=> ->.\n  move: (h _ cG) => /= [h'' _].\n  auto_uniq_full.\n  (* Fv in context for tpg hyp *)\n  move: ann_context_fv_mutual => [h''' [_ [_ [_ _] ] ] ]; move: h''' => /(_ _ _ _ tpgp1) /= [? [? [? ?]]].\n  rewrite eqphi in wildcard'1.\n  by move:  (u10 _ _ wildcard'1) => [<- _].\nDefined.\nNext Obligation.\n  cleanup'.\n  move /An_CPiCong_inversion.\n  move => [ph1 [ph2 [b1 [b2 [b3 [eqA [eqB [isoph1 [tpgp1 [tpgp2 [tpg3 h]]]]]]]]]]].\n  apply: wildcard'.\n  auto_uniq_full.\n  have cG: c `notin` dom G by ok.\n  have: phi1 = ph1 by congruence. move=> eqph1.\n  have: phi2 = ph2 by congruence. move=> eqph2. rewrite eqph2.\n  move: (An_CPi_inversion tpgp2). do 2 move=> [_]. move => /(_ c cG) h'.\n  move: (get_tpg_correct' h') => ->.\n  suff: B3c = (open_tm_wrt_co b3 (g_Var_f c)) by move=> ->.\n  move: (h _ cG) => /= [h'' eqb3].\n  auto_uniq_full.\n  (* Fv in context for tpg hyp *)\n  move: ann_context_fv_mutual => [h''' [_ [_ [_ _] ] ] ]; move: h''' => /(_ _ _ _ tpg3) /= [? [? [? ?]]].\n  rewrite eqph1 in wildcard'2.\n  rewrite eqB3c eqB2 eqb3.\n  subst phi1.\n  move:  (u10 _ _ wildcard'1) => [_ <-].\n  rewrite close_tm_wrt_co_open_tm_wrt_co; by [|fsetdec].\nDefined.\nNext Obligation.\n  cleanup'.\n  move /An_CPiCong_inversion.\n  move => [ph1 [ph2 [b1 [b2 [b3 [eqA [eqB [isoph1 [tpgp1 [tpgp2 [tpg3 h]]]]]]]]]]].\n  apply: wildcard'.\n  auto_uniq_full.\n  have cG: c `notin` dom G by ok.\n  have: phi1 = ph1 by congruence. move=> eqph1.\n  have: phi2 = ph2 by congruence. move=> eqph2. rewrite eqph1.\n  move: (An_CPi_inversion tpg3). do 2 move=> [_]. move => /(_ c cG) h'.\n  move: (get_tpg_correct' h') => ->.\n  suff: B2c = (open_tm_wrt_co b2 (g_Var_f c)) by move=> ->.\n  move: (h _ cG) => /= [h'' eqb3].\n  auto_uniq_full.\n  (* Fv in context for tpg hyp *)\n  move: ann_context_fv_mutual => [h''' [_ [_ [_ _] ] ] ]; move: h''' => /(_ _ _ _ tpg3) /= [? [? [? ?]]].\n  rewrite eqph1 in wildcard'2.\n  subst ph1.\n  by move:  (u10 _ _ wildcard'1) => [_ <-].\nDefined.\nNext Obligation.\n  cleanup'.\n  (* Fv in context for eqdec hyp *)\n  move: ann_context_fv_mutual => [_ [_ [_ [h''' _] ] ] ]; move: h''' => /(_ _ _ _  _ _ wildcard'1) /= [? [? [? ?]]].\n  autoreg.\n  rewrite eqB1 eqB3.\n  eapply An_CPiCong_exists_3 with (c := c) (B2 := B2c);\n    try eassumption.\n  - fsetdec.\n  - move: co_subst_co_tm_spec. congruence.\nDefined.\n\n\n\n(* An_CAbsCong *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation. (* Fuel: aux *)\n  fsetdec.\nDefined.\nNext Obligation. (* Ctx wf *)\n  cleanup'.\n  autoreg.\n  econstructor; try eassumption.\n  fsetdec.\nDefined.\nNext Obligation.\n  cleanup.\n  move /An_CAbsCong_inversion.\n  move => [ph1 [ph2 [a1' [a2' [a3' [B1' [B2' [B3' [eqA [eqB [isoph12 [tpg1 [tpg2 [tpg3 [defeq4 h]]]]]]]]]]]]]]].\n  have cG: c `notin` dom G by ok.\n  move: (h _ cG) => /= [defeq3 eq23].\n  apply: wildcard'.\n  auto_uniq_full; subst.\n  by apply: defeq3.\nDefined.\nNext Obligation.\n  eassumption.\nDefined.\nNext Obligation.\n  cleanup_param clearbodies' idtac.\n  move /An_CAbsCong_inversion.\n  move => [ph1 [ph2 [a1' [a2' [a3' [B1' [B2' [B3' [eqA [eqB [isoph12 [tpg1 [tpg2 [tpg3 [defeq4 h]]]]]]]]]]]]]]].\n  (* Fv in context for eqdec hyp *)\n  move: ann_context_fv_mutual => [h'' [_ [_ [_ _] ] ] ]; move: h'' => /(_ _ _ _ tpg1) /= [? [? [? ?] ] ].\n  have cG: c `notin` dom G by ok.\n  move: (h _ cG) => /= [defeq3 eq23].\n  apply: wildcard'.\n  auto_uniq_full. (* TODO: it needs to be smarter on the opened contexts/when things are just congruent *)\n  have eqphi1: phi1 = ph1 by move: (u0 _ _ wildcard'0) => [-> _].\n  suff: a1 = a1' by move: (eqphi1) => [-> ->]; eassumption.\n  rewrite eqphi1 in wildcard'1.\n  move: (eqa1) (u5 _ _ wildcard'1) close_tm_wrt_co_open_tm_wrt_co => -> [<- _] ->; ok.\nDefined.\nNext Obligation.\n  cleanup'.\n  move /An_CAbsCong_inversion.\n  move => [ph1 [ph2 [a1' [a2' [a3' [B1' [B2' [B3' [eqA [eqB [isoph12 [tpg1 [tpg2 [tpg3 [defeq4 h]]]]]]]]]]]]]]].\n  (* Fv in context for eqdec hyp *)\n  move: ann_context_fv_mutual => [h'' [_ [_ [_ _] ] ] ]; move: h'' => /(_ _ _ _ tpg1) /= [? [? [? ?] ] ].\n  move: ann_context_fv_mutual => [h'' [_ [_ [_ _] ] ] ]; move: h'' => /(_ _ _ _ tpg2) /= [? [? [? ?] ] ].\n  move: ann_context_fv_mutual => [h'' [_ [_ [_ _] ] ] ]; move: h'' => /(_ _ _ _ tpg3) /= [? [? [? ?] ] ].\n  have cG: c `notin` dom G by ok.\n  move: (h _ cG) => /= [defeq3 eq23].\n  apply: wildcard'.\n  auto_uniq_full. (* TODO: it needs to be smarter on the opened contexts/when things are just congruent *)\n  have [eqphi1 eqphi2] : phi1 = ph1 /\\ phi2 = ph2 by move: (u0 _ _ wildcard'0) => [-> ->]. subst ph1 ph2.\n\n  subst CPi1.\n  have: a1 = a1' by move: eqa1 (u _ _ defeq3) => -> [-> _]; autorewrite with lngen.\n  intros; subst a1'.\n  rewrite eqB1c.\n  move: (An_CAbs_inversion tpg1) => [B0 [tmp h'']]. injection tmp.\n  intros; subst B0.\n  move: (h'' c cG) => [_ tpga1].\n  move: (get_tpg_correct' tpga1).\n  rewrite eqa1. autorewrite with lngen.\n  move=> <-.\n  by autorewrite with lngen.\nDefined.\nNext Obligation.\n  cleanup'.\n  move /An_CAbsCong_inversion.\n  move => [ph1 [ph2 [a1' [a2' [a3' [B1' [B2' [B3' [eqA [eqB [isoph12 [tpg1 [tpg2 [tpg3 [defeq4 h]]]]]]]]]]]]]]].\n  (* Fv in context for eqdec hyp *)\n  move: ann_context_fv_mutual => [h'' [_ [_ [_ _] ] ] ]; move: h'' => /(_ _ _ _ tpg1) /= [? [? [? ?] ] ].\n  move: ann_context_fv_mutual => [h'' [_ [_ [_ _] ] ] ]; move: h'' => /(_ _ _ _ tpg2) /= [? [? [? ?] ] ].\n  move: ann_context_fv_mutual => [h'' [_ [_ [_ _] ] ] ]; move: h'' => /(_ _ _ _ tpg3) /= [? [? [? ?] ] ].\n  have cG: c `notin` dom G by ok.\n  move: (h _ cG) => /= [defeq3 eq23].\n  apply: wildcard'.\n  auto_uniq_full. (* TODO: it needs to be smarter on the opened contexts/when things are just congruent *)\n  have [eqphi1 eqphi2] : phi1 = ph1 /\\ phi2 = ph2 by move: (u0 _ _ wildcard'0) => [-> ->]. subst ph1 ph2.\n\n  subst CPi2.\n  have: a2 = a2' by move: eqa2 (u _ _ defeq3) => -> [_ ->]; autorewrite with lngen.\n  intros; subst a2'.\n  have: a3 = a3' by rewrite eqa3 eqa3c -eq23; autorewrite with lngen.\n  intros; subst a3'.\n  rewrite eqB3c.\n  move: (An_CAbs_inversion tpg2) => [B0 [tmp h'']]. injection tmp.\n  intros; subst B0.\n  move: (h'' c cG) => [_ tpga2].\n  move: (get_tpg_correct' tpga2).\n  rewrite eqa3. autorewrite with lngen.\n  move=> <-.\n  by autorewrite with lngen.\nDefined.\nNext Obligation.\n  cleanup'.\n  (* Fv in context for eqdec hyp *)\n  move: ann_context_fv_mutual => [_ [_ [_ [h''' _]]]]; move: h''' => /(_ _ _ _  _ _ wildcard'2) /= [? [? [? ?]]].\n  rewrite eqa1 eqa3.\n  autoreg.\n  (* FIXME: clearget not working here (losing an eq) *)\n  (* clearget. *)\n  eapply An_CAbsCong_exists3 with (c := c) (a2 := a2c) (B1 := B1c) (B3 := B3c); try eassumption; try congruence.\n  - fsetdec.\n  - rewrite co_subst_co_tm_spec.\n    congruence.\n  - by rewrite eqB1c.\n  - by rewrite eqB3c.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\n\n\n\n(* An_CAppCong *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  cleanup'.\n  autoreg.\n  clearget.\n  subst Ta1 Ta2.\n\n  (* Inversion and glueing *)\n  inversion 1.\n  have: a0 = a1 /\\ b0 = a2 by auto_uniq_full; split; congruence.\n  move=> [? ?]; subst a0 b0; clear H4.\n  have: a3 = b1 /\\ b3 = b2 by auto_uniq_full; split; congruence.\n  move=> [? ?]; subst a3 b3; clear H5.\n\n  (* Contra *)\n  apply wildcard'.\n  inversion H9.\n  have: Ta11 = a0 by auto_uniq_full; congruence.\n  move=> ?; subst a0.\n  by auto_uniq_full.\nDefined.\nNext Obligation.\n  cleanup'.\n  autoreg.\n  clearget.\n  subst Ta1 Ta2.\n\n  (* Inversion and glueing *)\n  inversion 1.\n  have: a0 = a1 /\\ b0 = a2 by auto_uniq_full; split; congruence.\n  move=> [? ?]; subst a0 b0; clear H4.\n  have: a3 = b1 /\\ b3 = b2 by auto_uniq_full; split; congruence.\n  move=> [? ?]; subst a3 b3; clear H5.\n\n  (* Contra *)\n  apply wildcard'.\n  inversion H9.\n  have: Ta12 = b2 by auto_uniq_full; congruence.\n  move=> ?; subst b2.\n  by auto_uniq_full.\nDefined.\nNext Obligation.\n  cleanup'.\n  autoreg.\n  clearget.\n  subst Ta1 Ta2.\n\n  (* Inversion and glueing *)\n  inversion 1.\n  have: a0 = a1 /\\ b0 = a2 by auto_uniq_full; split; congruence.\n  move=> [? ?]; subst a0 b0; clear H4.\n  have: a3 = b1 /\\ b3 = b2 by auto_uniq_full; split; congruence.\n  move=> [? ?]; subst a3 b3; clear H5.\n\n  (* Contra *)\n  apply wildcard'.\n  inversion H12.\n  have: Ta21 = c1 by auto_uniq_full; congruence.\n  move=> ?; subst c1.\n  by auto_uniq_full.\nDefined.\nNext Obligation.\n  cleanup'.\n  autoreg.\n  clearget.\n  subst Ta1 Ta2.\n\n  (* Inversion and glueing *)\n  inversion 1.\n  have: a0 = a1 /\\ b0 = a2 by auto_uniq_full; split; congruence.\n  move=> [? ?]; subst a0 b0; clear H4.\n  have: a3 = b1 /\\ b3 = b2 by auto_uniq_full; split; congruence.\n  move=> [? ?]; subst a3 b3; clear H5.\n\n  (* Contra *)\n  apply wildcard'.\n  inversion H12.\n  have: Ta22 = c2 by auto_uniq_full; congruence.\n  move=> ?; subst c2.\n  by auto_uniq_full.\nDefined.\nNext Obligation.\n  (* FIXME: cleanup' not working *)\n  clear dependent filtered_var.\n  clear dependent filtered_var2.\n  clear dependent filtered_var1.\n  clear dependent filtered_var0.\n  clear dependent filtered_var4.\n  clear dependent filtered_var3. subst. clear dependent fuel.\n  clean_fun. clearbodies'.\n\n  autoreg.\n  clearget.\n  subst.\n\n  apply: An_CAppCong2;\n    try econstructor; eassumption.\nDefined.\nNext Obligation.\n  cleanup'.\n  autoreg.\n  clearget.\n  hacky.\nDefined.\n\n\nSolve Obligations of AnnDefEq_dec with discr_pat_match.\n\n\n(* An_CPiSnd *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\n\nSolve Obligations of AnnDefEq_dec with discr_pat_match.\n\n\n\n(* FIXME FIXME FIXME FIXME FIXME\n   FIXME FIXME FIXME FIXME FIXME\n   FIXME FIXME FIXME FIXME FIXME\n   FIXME FIXME FIXME FIXME FIXME\n   FIXME FIXME FIXME FIXME FIXME\n   FIXME FIXME FIXME FIXME FIXME\n\n   Make the pattern-match inversion tactic check whether or not it is applied to a goal it can solve (too slow to run on everything)\n\n   FIXME FIXME FIXME FIXME FIXME\n   FIXME FIXME FIXME FIXME FIXME\n   FIXME FIXME FIXME FIXME FIXME\n   FIXME FIXME FIXME FIXME FIXME\n   FIXME FIXME FIXME FIXME FIXME\n   FIXME FIXME FIXME FIXME FIXME\n*)\n\n(* An_CastCo *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\n\n\n(* An_PiFst *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\n\nSolve Obligations of AnnDefEq_dec with discr_pat_match.\n\n\n(* An_PiSnd *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  cleanup'.\n  autoreg.\n  clearget.\n  hacky.\nDefined.\nNext Obligation.\n  cleanup'.\n  autoreg.\n  clearget.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  cleanup'.\n  autoreg.\n  clearget.\n  apply: An_PiSnd;\n    subst; eauto.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\n\nSolve Obligations of AnnDefEq_dec with discr_pat_match.\n\nNext Obligation.\n  hacky.\nDefined.\n\n\nSolve Obligations of AnnDefEq_dec with discr_pat_match.\n\n(* An_IsoSnd *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\n\n\n(* FIXME: old cases. Currently, DefEq_dec is done at that point *)\n(*\n(* g_triv (impossible) *)\nNext Obligation.\n  (* FIXME: discriminate doesn't work *)\n  inversion 1; ok.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  cleanup'. autoreg.\n\n  econstructor.\n      move: (AnnDefEq_regularity wildcard'6). => [KA [KB [g' [tpgA [tpgB (* deqg' *) _]]]]]\n  reg wildcard'6.\n  ok.\nDefined.\nNext Obligation.\n  ok.\nDefined.\nNext Obligation.\n  ok.\nDefined.\nNext Obligation.\n  ok.\nDefined.\n*)\n\n(* An_Eta *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  eapply An_Eta with (L := dom G)(B := B).\n  subst. auto.\n  intros.\n  rewrite -tm_subst_tm_tm_spec.\n  simpl. destruct eq_dec; try done.\n  rewrite tm_subst_tm_tm_fresh_eq. auto.\n  auto.\nDefined. \nNext Obligation.\n  eapply An_Eta with (L := dom G)(B := B).\n  subst. auto.\n  intros.\n  rewrite -tm_subst_tm_tm_spec.\n  simpl. edestruct eq_dec; try done.\n  rewrite tm_subst_tm_tm_fresh_eq. auto.\n  auto.\nDefined.\nNext Obligation. \n  eapply An_EtaC with (L := dom G).\n  subst. eapply wildcard'.\n  intros.\n  rewrite -co_subst_co_tm_spec.\n  simpl. edestruct eq_dec; try done.\n  rewrite co_subst_co_tm_fresh_eq. auto.\n  move: (AnnTyping_context_fv wildcard') => h0.\n  fsetdec.\nDefined. \nNext Obligation.\n  cleanup. inversion 1; subst;\n  inversion H0; clear H0;\n  inversion H4; clear H4.\n  destruct rho.\n  move: (H5 A0 B0) => h0.\n  destruct h0.\n  eapply AnnTyping_unique. eauto. eauto.\n  move: (H2 A0 B0) => h0.\n  destruct h0.\n  eapply AnnTyping_unique. eauto. eauto.\n  move: (H0 phi) => h0.\n  edestruct h0.\n  eapply AnnTyping_unique. eauto. eauto.\nDefined. \n\nNext Obligation.\n  unfold wildcard'.\n  repeat split; intros; discriminate.\nDefined.\nNext Obligation.\n  unfold wildcard'.\n  repeat split; intros; discriminate.\nDefined.\nNext Obligation.\n  unfold wildcard'.\n  repeat split; intros; discriminate.\nDefined.\nNext Obligation.\n  unfold wildcard'.\n  repeat split; intros; discriminate.\nDefined.\nNext Obligation.\n  unfold wildcard'.\n  repeat split; intros; discriminate.\nDefined.\nNext Obligation.\n  unfold wildcard'.\n  repeat split; intros; discriminate.\nDefined.\nNext Obligation.\n  unfold wildcard'.\n  repeat split; intros; discriminate.\nDefined.\nNext Obligation.\n  unfold wildcard'.\n  repeat split; intros; discriminate.\nDefined.\nNext Obligation.\n  unfold wildcard'.\n  repeat split; intros; discriminate.\nDefined.\nNext Obligation.\n  unfold wildcard'.\n  repeat split; intros; discriminate.\nDefined.\nNext Obligation.\n  unfold wildcard'.\n  repeat split; intros; discriminate.\nDefined.\nNext Obligation.\n  unfold wildcard'.\n  repeat split; intros; discriminate.\nDefined.\nNext Obligation.\n  unfold wildcard'.\n  repeat split; intros; discriminate.\nDefined.\nNext Obligation.\n  unfold wildcard'.\n  repeat split; intros; discriminate.\nDefined.\nNext Obligation.\n  unfold wildcard'.\n  repeat split; intros; discriminate.\nDefined.\n\n\n (* cleanup'.\n  subst.\n  move=> h0.\n  inversion h0. subst.\n  apply (H0 A0 B0).\n  auto_uniq_full.\n  apply u0.\n  auto. admit. admit. *)\n\n(*\n\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.    *)\n\n(*\n(* An_Left *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  cleanup'.\n  autoreg.\n  intro h0; inversion h0. subst.\n  eapply wildcard'.\n  erewrite <- get_tpg_correct'. eauto.\n  auto_uniq_full.\n  eauto.\n  subst. eapply wildcard'.\n  erewrite <- get_tpg_correct'. eauto.\n  auto_uniq_full.\n  try done.\nDefined.\nNext Obligation.\n  cleanup'.\n  autoreg.\n  intro h0; inversion h0. subst.\n  eapply wildcard'.\n  erewrite <- get_tpg_correct'. eauto.\n  auto_uniq_full.\n  try done.\n  subst.   eapply wildcard'.\n  erewrite <- get_tpg_correct'. eauto.\n  auto_uniq_full.\n  try done.\nDefined.\nNext Obligation.\n  eapply An_Left2; try eassumption.\n *)\n\n(******** AnnIso_dec ********)\n\n(* An_Cong *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  cleanup'.\n  autoreg.\n  erewrite <- get_tpg_correct'; eassumption.\nDefined.\nNext Obligation.\n  cleanup'.\n  autoreg.\n  erewrite <- get_tpg_correct'; eassumption.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  eassumption.\nDefined.\nNext Obligation.\n  cleanup'.\n  autoreg.\n  erewrite <- get_tpg_correct'; eassumption.\nDefined.\nNext Obligation.\n  cleanup'.\n  autoreg.\n  erewrite <- get_tpg_correct'; eassumption.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  eauto.\nDefined.\n\n\n(* An_CPiFst *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\n\nSolve Obligations of AnnIso_dec with discr_pat_match.\n\n\n(* An_IsoSym *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  eauto.\nDefined.\n\n\n(* An_IsoConv *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  rewrite Heq_phi1 Heq_phi2.\n  subst A' B'.\n  eapply An_IsoConv'.\n   rewrite -Heq_phi1. reflexivity.\n   rewrite -Heq_phi2. reflexivity.\n  all: try eassumption.\nDefined.\n\n\n\n(******** AnnPropWff_dec ********)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\n\n\n(******** AnnTyping_dec ********)\n(* An_Star *)\nNext Obligation.\n  hacky.\nDefined.\n\n(* An_Var *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\n\n\n(* An_Pi *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation. (* Fuel: aux *)\n  fsetdec.\nDefined.\nNext Obligation. (* Ctx Wf *)\n  cleanup'.\n  autoreg.\n  subst.\n  econstructor; eauto.\nDefined.\nNext Obligation.\n  move /An_Pi_inversion => [_ [_] ].\n  have xG: x `notin` dom G by fsetdec.\n  move /(_ x xG).\n  ok.\nDefined.\nNext Obligation.\n  move /An_Pi_inversion => [? ?].\n  cleanup.\n  apply: wildcard'.\n  auto_uniq_full.\n  ok.\nDefined.\nNext Obligation.\n  apply An_Pi_exists2 with (x := x); ok.\nDefined.\n\n\n(* An_Abs *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation. (* Fuel: aux *)\n  fsetdec.\nDefined.\nNext Obligation. (* Ctx Wf *)\n  cleanup'.\n  autoreg.\n  subst.\n  econstructor; eauto.\nDefined.\nNext Obligation.\n  cleanup.\n  move /An_Abs_inversion => [? [_ [_] ] ].\n  have xG: x `notin` dom G by fsetdec.\n  move /(_ x xG).\n  ok.\nDefined.\nNext Obligation.\n  by move: (wf.AnnTyping_lc1 wildcard').\nDefined.\nNext Obligation.\n  cleanup.\n  move /An_Abs_inversion => [? [_ [_] ] ].\n  have xG: x `notin` dom G by fsetdec.\n  move /(_ x xG) => [h _].\n  by apply wildcard'.\nDefined.\nNext Obligation.\n  move: ann_context_fv_mutual => [h'' [_ [_ [_ _] ] ] ]; move: h'' => /(_ _ _ _ wildcard'2) /= [? [? [? ?] ] ].\n  eapply An_Abs_exists with (x := x); try done.\n  - autorewrite with lngen. fsetdec.\n  - by subst.\n  - by autorewrite with lngen.\nDefined.\n\n\n(* An_App *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  subst.\n  apply: An_App; eassumption.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\n\nSolve All Obligations with discr_pat_match.\n\n\n(* An_Cast *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  cleanup'.\n  autoreg.\n  clearget.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\n  Unshelve.\n  all: apply a_Star.\nDefined.\nNext Obligation.\n  cleanup'.\n  autoreg.\n  clearget.\n  subst.\n  apply: An_Conv; eassumption.\nDefined.\n\n\n(* An_CApp *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  subst.\n  apply: An_CApp; eassumption.\nDefined.\nNext Obligation.\n  hacky.\nDefined.\n\nSolve All Obligations with discr_pat_match.\n\n\n(* An_Const *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  move: (an_toplevel_to_const wildcard') => AT.\n  move: (AnnTyping_lc AT) => [lc1 lc2].\n  eapply lc_set_tm_of_lc_tm. eauto.\nDefined.\nNext Obligation.\n  inversion 1.\n  (* TODO: uniq should be discharged via typeclasses/CS *)\n  move: (binds_unique _ _ _ _ _ H3 wildcard'0 uniq_an_toplevel).\n  intro h0. inversion h0. subst.\n  move: (binds_to_type _ _ AnnSig_an_toplevel H3) => h1. done.\nDefined.\nNext Obligation.\n  subst.\n  apply: An_Const; eauto.\n  eapply an_toplevel_to_const; eauto.\nDefined.\n\n\n(* An_CPi *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation. (* Fuel: aux *)\n  fsetdec.\nDefined.\nNext Obligation.\n  cleanup'.\n  econstructor; try eassumption.\n  fsetdec.\nDefined.\nNext Obligation.\n  move /An_CPi_inversion => [_ [_] ].\n  have cG: c `notin` dom G by fsetdec.\n  move /(_ c cG).\n  ok.\nDefined.\nNext Obligation.\n  move /An_CPi_inversion => [_ [_] ].\n  have cG: c `notin` dom G by fsetdec.\n  move /(_ c cG) => /= h.\n  apply wildcard'.\n  auto_uniq_full.\n  by move: (u0 _ wildcard'1) => ->.\nDefined.\nNext Obligation.\n  apply An_CPi_exists with (c := c);\n  ok.\nDefined.\n\n\n(* An_CAbs *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation. (* Fuel: aux *)\n  fsetdec.\nDefined.\nNext Obligation.\n  cleanup'.\n  econstructor; try eassumption.\n  fsetdec.\nDefined.\nNext Obligation.\n  move /An_CAbs_inversion => [? [? ] ].\n  have cG: c `notin` dom G by fsetdec.\n  move /(_ _ cG).\n  ok.\nDefined.\nNext Obligation.\n  move: ann_context_fv_mutual => [h'' [_ [_ [_ _] ] ] ]; move: h'' => /(_ _ _ _ wildcard') /= [? [? [? ?] ] ].\n  apply An_CAbs_exists with (c := c); try eassumption.\n  - autorewrite with lngen. fsetdec.\n  - autorewrite with lngen. eassumption.\nDefined.\n\n\n(* An_Fam *)\nNext Obligation.\n  hacky.\nDefined.\nNext Obligation.\n  clear_annoying.\n  subst.\n  move: (an_toplevel_closed wildcard') => tpg.\n  autoreg. (* TODO: autoreg should do this one too (only use case though...) *)\n  move: (AnnTyping_regularity tpg) => kdg.\n  econstructor; eassumption.\nDefined.\n\nEnd fc_dec_fun.\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_dec_fun.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.2698859562062588}}
{"text": "From Undecidability.L.Tactics Require Import LTactics.\nFrom Undecidability.L Require Import UpToC.\nFrom Undecidability.L.Datatypes Require Export List.List_enc LBool LNat.\nFrom Undecidability.Shared.Libs.PSL.Lists Require Export Filter.\n\nSet Default Proof Using \"Type\".\n\nDefinition c__app := 16.\n#[global]\nInstance termT_append X {intX : registered X} : computableTime' (@List.app X) (fun A _ => (5,fun B _ => (length A * c__app + c__app,tt))).\nProof.\n  extract.\n  solverec. all: now unfold c__app. \nQed.\n\nDefinition c__map := 12. \nFixpoint map_time {X} (fT:X -> nat) xs :=\n  match xs with\n    [] => c__map\n  | x :: xs => fT x + map_time fT xs + c__map\n  end.\n  \n#[global]\nInstance term_map (X Y:Type) (Hx : registered X) (Hy:registered Y): computableTime' (@map X Y) (fun _ fT => (1,fun l _ => (map_time (fun x => fst (fT x tt)) l,tt))).\nProof.\n  extract.\n  solverec. all: unfold c__map; solverec. \nDefined. (*because other extract*)\n\n\nLemma map_time_const {X} c (xs:list X):\n  map_time (fun _ => c) xs = length xs * (c + c__map) + c__map.\nProof.\n  induction xs;cbn. all:lia.\nQed.\n\nLemma mapTime_upTo X (t__f : X -> nat):\n  map_time t__f <=c (fun l => length l + sumn (map t__f l) + 1 ).\nProof.\n  unfold map_time. exists c__map; unfold c__map. \n  induction x; cbn - [plus mult]; nia.\nQed.\n\n#[global]\nInstance term_map_noTime (X Y:Type) (Hx : registered X) (Hy:registered Y): computable (@map X Y).\nProof.\n  extract.\nDefined. (*because other extract*)\n  \n#[global]\nInstance termT_rev_append X `{registered X}: computableTime' (@rev_append X) (fun l _ => (5,fun res _ => (length l*13+4,tt))).\nProof.\n  extract.\n  recRel_prettify.\n  solverec.\nQed.\n\nDefinition c__rev := 13. \n#[global]\nInstance termT_rev X `{registered X}: computableTime' (@rev X) (fun l _ => ((length l + 1) *c__rev,tt)).\nProof.\n  eapply computableTimeExt with (x:= fun l => rev_append l []).\n  {intro. rewrite rev_alt. reflexivity. }\n  extract. solverec. unfold c__rev; solverec. \nQed.\n\nSection Fix_X.\n  Variable (X:Type).\n  Context {intX : registered X}.\n\n  Global Instance term_filter: computableTime' (@filter X) (fun p pT => (1,fun l _ => (fold_right (fun x res => 16 + res + fst (pT x tt)) 8 l ,tt))).\n  Proof using intX.\n    change (filter (A:=X)) with ((fun (f : X -> bool) =>\n                                    fix filter (l : list X) : list X := match l with\n                                                                        | [] => []\n                                                                        | x :: l0 => (fun r => if f x then x :: r else r) (filter l0)\n                                                                        end)).\n    extract.\n    solverec. \n  Defined. (*because other extract*)\n\n  Global Instance term_filter_notime: computable (@filter X).\n  Proof using intX.\n  pose (t:= extT (@filter X)). hnf in t. \n    computable using t.\n  Defined. (*because other extract*)\n\n  Global Instance term_repeat: computable (@repeat X).\n  Proof using intX.\n    extract.\n  Qed.\n  \nEnd Fix_X.\n\n\nSection concat.\n  Context X `{registered X}.\n\n  Fixpoint rev_concat acc (xs : list (list X)) :=\n    match xs with\n      [] => acc\n    | x::xs => rev_concat (rev_append x acc) xs\n    end.\n\n  Lemma rev_concat_rev xs acc:\n    rev (rev_concat acc xs) = rev acc ++ concat xs.\n  Proof.\n    induction xs in acc|-*. all:cbn. 2:rewrite IHxs,rev_append_rev. all:autorewrite with list in *. all:easy.\n  Qed.\n\n  Lemma rev_concat_length xs acc:\n    length (rev_concat acc xs) = length acc + length (concat xs).\n  Proof.\n    specialize (rev_concat_rev xs acc) as H1%(f_equal (@length _)).\n    autorewrite with list in H1. nia.\n  Qed.\n\n  \n  Lemma _term_rev_concat :\n    { time : UpToC (fun l => sumn (map (@length _) l) + length l + 1) &\n             computableTime' (@rev_concat) (fun _ _ => (5,fun l _ => (time l,tt)))}.\n  Proof.      \n    evar (c1 : nat).\n    exists_UpToC (fun l => c1 * (sumn (map (@length _) l) + length l + 1) ).\n    { extract. recRel_prettify2.\n      all:cbn - [plus mult].\n      all:enough (c1>=20) by nia.\n      instantiate (c1:=20). all:subst c1;nia. \n    }\n    smpl_upToC_solve.\n  Qed.\n  Global Instance term_rev_concat : computableTime' rev_concat _ := projT2 _term_rev_concat.\n\n  \n  Lemma _term_concat :\n    { time : UpToC (fun l => sumn (map (@length _) l) + length l + 1) &\n             computableTime' (@concat X) (fun l _ => (time l,tt))}.\n  Proof.\n    eexists_UpToC time. [time]: intros x.\n    eapply computableTimeExt with (x := fun l => rev (rev_concat [] l)).\n    -intros l;hnf. rewrite rev_concat_rev. easy.\n    -extract. solverec. unfold time. reflexivity.\n    -unfold time. smpl_upToC; try smpl_upToC_solve.\n     setoid_rewrite rev_concat_length. setoid_rewrite length_concat. smpl_upToC_solve.\n  Qed.\n\n  Global Instance term_concat : computableTime' (@concat X) _ := projT2 _term_concat.\n\nEnd concat.\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/Datatypes/List/List_basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.2698859562062588}}
{"text": "(* Distributed under the terms of the MIT license. *)\nFrom MetaCoq.Utils Require Import utils.\nFrom MetaCoq.Common Require Import config.\nFrom MetaCoq.Erasure Require Import EAstUtils Extract EArities EWcbvEval.\nFrom MetaCoq.PCUIC Require Import PCUICTyping PCUICAst PCUICAstUtils\n     PCUICSubstitution PCUICLiftSubst PCUICClosedTyp\n     PCUICReduction PCUICWcbvEval PCUICSR PCUICInversion PCUICGeneration\n     PCUICContextConversion PCUICArities PCUICWellScopedCumulativity PCUICConversion\n     PCUICWeakeningEnvTyp PCUICCanonicity.\nFrom MetaCoq.SafeChecker Require Import PCUICErrors.\nFrom Coq Require Import Program ssreflect.\n\nLocal Existing Instance extraction_checker_flags.\n\nLtac inv H := inversion H; subst; clear H.\n\nLemma typing_spine_inv args arg a Σ x2 x3 :\n  nth_error args (arg) = Some a ->\n  typing_spine Σ [] x2 args x3 ->\n  {T & Σ;;; [] |- a : T}.\nProof.\n  intros. revert arg H.\n  dependent induction X; intros arg H17.\n  - rewrite nth_error_nil in H17. congruence.\n  - destruct (arg)%nat eqn:EAst.\n    + cbn in H17. invs H17. eauto.\n    + cbn in H17. eauto.\nQed.\n\nDefinition well_typed Σ Γ t := ∑ T, Σ ;;; Γ |- t : T.\n\nLemma typing_spine_wt args Σ x2 x3 :  wf Σ.1 ->\n  typing_spine Σ [] x2 args x3 ->\n  All (well_typed Σ []) args.\nProof.\n  intros wfΣ sp.\n  dependent induction sp; constructor; auto.\n  now exists A.\nQed.\n\nLemma typing_spine_eval:\n  forall (Σ : global_env_ext) (args args' : list PCUICAst.term)\n  (X : All2 (PCUICWcbvEval.eval Σ) args args') (bla : wf Σ)\n    (T x x0 : PCUICAst.term) (t0 : typing_spine Σ [] x args x0)\n    (c : Σ;;; [] ⊢ x0 ≤ T) (x1 : PCUICAst.term)\n    (c0 : Σ;;; [] ⊢ x1 ≤ x), isType Σ [] x1 -> isType Σ [] T -> typing_spine Σ [] x1 args' T.\nProof.\n  intros. eapply typing_spine_red; eauto.\n  eapply typing_spine_wt in t0; auto.\n  eapply All2_All_mix_left in X; eauto. simpl in X.\n  eapply All2_impl. eassumption. simpl. intros t u [ct et]. eapply wcbeval_red; eauto.\n  eapply (projT2 ct).\nQed.\n\nLemma cumul_Sort_Prod_discr {Σ Γ T s na A B} :\n  wf_ext Σ ->\n  Σ ;;; Γ ⊢ T ≤ tSort s ->\n  Σ ;;; Γ ⊢ T ≤ tProd na A B -> False.\nProof.\n  intros wfΣ hs hs'.\n  eapply ws_cumul_pb_Sort_r_inv in hs as [s' []].\n  eapply ws_cumul_pb_Prod_r_inv in hs' as [dom' [codom' [T' []]]].\n  destruct (closed_red_confluence c c1) as [nf []].\n  eapply invert_red_sort in c2; subst.\n  eapply invert_red_prod in c3 as [? [? []]]. discriminate.\nQed.\n\n(** ** on mkApps *)\n\nLemma emkApps_snoc a l b :\n  EAst.mkApps a (l ++ [b]) = EAst.tApp (EAst.mkApps a l) b.\nProof.\n  revert a; induction l; cbn; congruence.\nQed.\n\nLemma mkApps_snoc a l b :\n  PCUICAst.mkApps a (l ++ [b]) = PCUICAst.tApp (PCUICAst.mkApps a l) b.\nProof.\n  revert a; induction l; cbn; congruence.\nQed.\n\nLemma mkAppBox_repeat n a :\n  mkAppBox a n = EAst.mkApps a (repeat EAst.tBox n).\nProof.\n  revert a; induction n; cbn; firstorder congruence.\nQed.\n\nLemma decompose_app_rec_inv2 {t l' f l} :\n  decompose_app_rec t l' = (f, l) ->\n  isApp f = false.\nProof.\n  induction t in f, l', l |- *; try intros [= <- <-]; try reflexivity.\n  simpl. apply IHt1.\nQed.\n\nModule Ee := EWcbvEval.\n\nLemma fst_decompose_app_rec t l : fst (EAstUtils.decompose_app_rec t l) = fst (EAstUtils.decompose_app t).\nProof.\n  induction t in l |- *; simpl; auto. rewrite IHt1.\n  unfold decompose_app. simpl. now rewrite (IHt1 [t2]).\nQed.\n\n(** ** Prelim on fixpoints *)\n\nLemma fix_subst_nth mfix n :\n  n < #|mfix| ->\n  nth_error (fix_subst mfix) n = Some (tFix mfix (#|mfix| - n - 1)).\nProof.\n  unfold fix_subst. generalize (#|mfix|).\n  intros m. revert n. induction m; cbn; intros.\n  - destruct n; inv H.\n  - destruct n.\n    + cbn. now rewrite Nat.sub_0_r.\n    + cbn. rewrite IHm. lia. reflexivity.\nQed.\n\nLemma efix_subst_nth mfix n :\n  n < #|mfix| ->\n  nth_error (EGlobalEnv.fix_subst mfix) n = Some (EAst.tFix mfix (#|mfix| - n - 1)).\nProof.\n  unfold EGlobalEnv.fix_subst. generalize (#|mfix|).\n  intros m. revert n. induction m; cbn; intros.\n  - destruct n; inv H.\n  - destruct n.\n    + cbn. now rewrite Nat.sub_0_r.\n    + cbn. rewrite IHm. lia. reflexivity.\nQed.\n\nLemma subslet_fix_subst `{cf : checker_flags} Σ mfix1 T n :\n  wf Σ.1 ->\n  Σ ;;; [] |- tFix mfix1 n : T ->\n  subslet Σ [] (fix_subst mfix1) (fix_context mfix1).\nProof.\n  intro hΣ.\n  unfold fix_subst, fix_context.\n  assert (exists L, mfix1 = mfix1 ++ L) by (exists []; now simpl_list). revert H.\n  generalize mfix1 at 2 5 6.  intros.\n  induction mfix0 using rev_ind.\n  - econstructor.\n  - rewrite mapi_app. cbn in *. rewrite rev_app_distr. cbn in *.\n    rewrite app_length. cbn. rewrite Nat.add_comm /=; econstructor.\n    + eapply IHmfix0. destruct H as [L]. exists (x :: L). subst. now rewrite <- app_assoc.\n    + rewrite <- plus_n_O.\n      rewrite PCUICLiftSubst.simpl_subst_k. clear. induction l; cbn; try congruence.\n      eapply inversion_Fix in X as (? & ? & ? & ? & ? & ? & ?) ; auto.\n      econstructor; eauto. destruct H. subst.\n      rewrite <- app_assoc, nth_error_app_ge; try lia.\n      now rewrite Nat.sub_diag.\nQed.\n\nLemma cofix_subst_nth mfix n :\n  n < #|mfix| ->\n  nth_error (cofix_subst mfix) n = Some (tCoFix mfix (#|mfix| - n - 1)).\nProof.\n  unfold cofix_subst. generalize (#|mfix|).\n  intros m. revert n. induction m; cbn; intros.\n  - destruct n; inv H.\n  - destruct n.\n    + cbn. now rewrite Nat.sub_0_r.\n    + cbn. rewrite IHm; lia_f_equal.\nQed.\n\nLemma ecofix_subst_nth mfix n :\n  n < #|mfix| ->\n  nth_error (EGlobalEnv.cofix_subst mfix) n = Some (EAst.tCoFix mfix (#|mfix| - n - 1)).\nProof.\n  unfold EGlobalEnv.cofix_subst. generalize (#|mfix|).\n  intros m. revert n. induction m; cbn; intros.\n  - destruct n; inv H.\n  - destruct n.\n    + cbn. now rewrite Nat.sub_0_r.\n    + cbn. rewrite IHm. lia. reflexivity.\nQed.\n\nLemma subslet_cofix_subst `{cf : checker_flags} Σ mfix1 T n :\n  wf Σ.1 ->\n  Σ ;;; [] |- tCoFix mfix1 n : T ->\n  subslet Σ [] (cofix_subst mfix1) (fix_context mfix1).\nProof.\n  intro hΣ.\n  unfold cofix_subst, fix_context.\n  assert (exists L, mfix1 = mfix1 ++ L)%list by (exists []; now simpl_list). revert H.\n  generalize mfix1 at 2 5 6.  intros.\n  induction mfix0 using rev_ind.\n  - econstructor.\n  - rewrite mapi_app. cbn in *. rewrite rev_app_distr. cbn in *.\n    rewrite app_length /= Nat.add_comm /=. econstructor.\n    + eapply IHmfix0. destruct H as [L]. exists (x :: L). subst. now rewrite <- app_assoc.\n    + rewrite <- plus_n_O.\n      rewrite PCUICLiftSubst.simpl_subst_k. clear. induction l; cbn; try congruence.\n      eapply inversion_CoFix in X as (? & ? & ? & ? & ? & ? & ?) ; auto.\n      econstructor; eauto. destruct H. subst.\n      rewrite <- app_assoc. rewrite nth_error_app_ge. lia.\n      now rewrite Nat.sub_diag.\nQed.\n\nLemma unfold_cofix_type Σ mfix idx args narg fn ty :\n  wf Σ.1 ->\n  Σ ;;; [] |- mkApps (tCoFix mfix idx) args : ty ->\n  unfold_cofix mfix idx = Some (narg, fn) ->\n  Σ ;;; [] |- mkApps fn args : ty.\nProof.\n  intros wfΣ ht.\n  pose proof (typing_wf_local ht).\n  eapply PCUICValidity.inversion_mkApps in ht as (? & ? & ?); eauto.\n  eapply inversion_CoFix in t; auto.\n  destruct_sigma t.\n  rewrite /unfold_cofix e => [=] harg hfn.\n  subst fn.\n  eapply PCUICSpine.typing_spine_strengthen in t0; eauto.\n  eapply PCUICSpine.type_mkApps; eauto.\n  pose proof a0 as a0'.\n  eapply nth_error_all in a0'; eauto. simpl in a0'.\n  eapply (substitution (Δ := [])) in a0'; eauto.\n  2:{ eapply subslet_cofix_subst; pcuic. constructor; eauto. }\n  rewrite PCUICLiftSubst.simpl_subst_k in a0'. now autorewrite with len.\n  eapply a0'. now eapply nth_error_all in a; tea.\nQed.\n\n(** Assumption contexts: constructor arguments/case branches contexts contain only assumptions, no local definitions *)\n\nLemma is_assumption_context_spec Γ :\n  is_true (is_assumption_context Γ) <-> PCUICLiftSubst.assumption_context Γ.\nProof.\n induction Γ; cbn.\n - split; econstructor.\n - split; intros H.\n   + destruct a; cbn in *. destruct decl_body; inversion H. now econstructor.\n   + invs H. cbn. now eapply IHΓ.\nQed.\n\nLemma assumption_context_map2_binders nas Γ :\n  assumption_context Γ ->\n  assumption_context (map2 set_binder_name nas Γ).\nProof.\n  induction 1 in nas |- *; cbn. destruct nas; cbn; auto; constructor.\n  destruct nas; cbn; auto; constructor. auto.\nQed.\n\nLemma declared_constructor_assumption_context (wfl := default_wcbv_flags) {Σ c mdecl idecl cdecl} {wfΣ : wf_ext Σ} :\n  declared_constructor Σ c mdecl idecl cdecl ->\n  assumption_context (cstr_args cdecl).\nProof.\n  intros.\n  destruct (on_declared_constructor H) as [? [cu [_ onc]]].\n  destruct onc.\n  now eapply is_assumption_context_spec.\nQed.\n\nLemma assumption_context_cstr_branch_context (wfl := default_wcbv_flags) {Σ} {wfΣ : wf_ext Σ} {c mdecl idecl cdecl} :\n  declared_constructor Σ c mdecl idecl cdecl ->\n  assumption_context (cstr_branch_context c.1 mdecl cdecl).\nProof.\n  intros decl.\n  eapply declared_constructor_assumption_context in decl.\n  rewrite /cstr_branch_context. pcuic.\nQed.\n\nLemma expand_lets_erasure (wfl := default_wcbv_flags) {Σ mdecl idecl cdecl c brs p} {wfΣ : wf_ext Σ} :\n  declared_constructor Σ c mdecl idecl cdecl ->\n  wf_branches idecl brs ->\n  All2i (fun i cdecl br =>\n   All2 (PCUICEquality.compare_decls eq eq) (bcontext br)\n      (cstr_branch_context c.1 mdecl cdecl)) 0 idecl.(ind_ctors) brs ->\n  All (fun br =>\n    expand_lets (inst_case_branch_context p br) (bbody br) = bbody br) brs.\nProof.\n  intros decl wfbrs.\n  red in wfbrs.\n  eapply Forall2_All2 in wfbrs.\n  intros ai.\n  eapply All2i_nth_hyp in ai.\n  eapply All2i_All2_mix_left in ai; tea. clear wfbrs.\n  solve_all.\n  red in a. red in a.\n  erewrite <- PCUICCasesContexts.inst_case_branch_context_eq; tea.\n  rewrite PCUICSigmaCalculus.expand_lets_assumption_context //.\n  eapply assumption_context_map2_binders.\n  rewrite /pre_case_branch_context_gen /inst_case_context.\n  eapply PCUICInductiveInversion.assumption_context_subst_context.\n  eapply PCUICInductiveInversion.assumption_context_subst_instance.\n  destruct c. cbn.\n  eapply (assumption_context_cstr_branch_context (c:=(i0, i))). split. apply decl. tea.\nQed.\n\nLemma assumption_context_compare_decls Γ Δ :\n  PCUICEquality.eq_context_upto_names Γ Δ ->\n  assumption_context Γ ->\n  assumption_context Δ.\nProof.\n  induction 1; auto.\n  intros H; depelim H.\n  depelim r; econstructor; auto.\nQed.\n\nLemma smash_assumption_context Γ Δ : assumption_context Γ ->\n  smash_context Δ Γ = Γ ,,, Δ.\nProof.\n  intros ass; induction ass in Δ |- *; cbn; auto.\n  - now rewrite app_context_nil_l.\n  - rewrite PCUICSigmaCalculus.smash_context_acc /app_context.\n    rewrite IHass /=.\n    rewrite -(app_tip_assoc Δ _ Γ). f_equal.\n    rewrite -/(expand_lets_k_ctx Γ 0 _).\n    rewrite [expand_lets_k_ctx _ _ _]PCUICSigmaCalculus.expand_lets_ctx_assumption_context //.\nQed.\n\nImport PCUICGlobalEnv PCUICSpine.\nLemma subslet_cstr_branch_context {cf : checker_flags} {Σ : global_env_ext} {wfΣ : wf Σ}\n  {Γ pars parsubst parsubst' s' inst' ind n mdecl idecl cdecl u p br napp} :\n  declared_constructor Σ (ind, n) mdecl idecl cdecl ->\n  consistent_instance_ext Σ (ind_universes mdecl) u ->\n  consistent_instance_ext Σ (ind_universes mdecl) (puinst p) ->\n  PCUICEquality.R_global_instance Σ (eq_universe Σ) (leq_universe Σ) (IndRef ind) napp u (puinst p) ->\n  spine_subst Σ Γ pars parsubst (ind_params mdecl)@[u] ->\n  spine_subst Σ Γ (pparams p) parsubst' (ind_params mdecl)@[puinst p] ->\n  assumption_context cdecl.(cstr_args) ->\n  ws_cumul_pb_terms Σ Γ pars (pparams p) ->\n  wf_predicate mdecl idecl p ->\n  wf_branch cdecl br ->\n  PCUICSpine.spine_subst Σ Γ s' inst'\n    (subst_context parsubst 0 (subst_context (inds (inductive_mind ind) u (ind_bodies mdecl)) #|ind_params mdecl| (cstr_args cdecl)@[u])) ->\n  subslet Σ Γ (List.rev s') (case_branch_context ind mdecl p (forget_types (bcontext br)) cdecl).\nProof.\n  intros declc cu cu' hr sppars sppars' assargs eqp wfp wfbr spargs.\n  rewrite /case_branch_context /case_branch_context_gen.\n  eapply PCUICSpine.subslet_eq_context_alpha.\n  symmetry. eapply PCUICCasesContexts.eq_binder_annots_eq.\n  eapply PCUICInductiveInversion.wf_pre_case_branch_context_gen; tea.\n  rewrite /pre_case_branch_context_gen /inst_case_context.\n  rewrite /cstr_branch_context.\n  rewrite PCUICInductiveInversion.subst_instance_expand_lets_ctx PCUICUnivSubstitutionConv.subst_instance_subst_context.\n  rewrite PCUICInductives.instantiate_inds //. exact declc.\n  epose proof (PCUICInductiveInversion.constructor_cumulative_indices declc cu cu' hr _ _ _ _ _ sppars sppars' eqp) as [eqctx _].\n  cbn in eqctx.\n  epose proof (spine_subst_smash spargs).\n  eapply spine_subst_cumul in X. eapply X.\n  pcuic. pcuic. apply X.\n  { eapply substitution_wf_local. eapply (spine_subst_smash sppars').\n    eapply PCUICInductives.wf_local_expand_lets.\n    rewrite -app_context_assoc.\n    eapply PCUICWeakeningTyp.weaken_wf_local => //. eapply sppars.\n    eapply (PCUICSR.on_constructor_wf_args declc) => //. }\n  rewrite /=.\n  rewrite -(spine_subst_inst_subst sppars').\n  assert (smash_context [] (cstr_args cdecl)@[puinst p] = (cstr_args cdecl)@[puinst p]).\n  { rewrite smash_assumption_context //. pcuic. }\n  rewrite -H.\n  rewrite -PCUICClosed.smash_context_subst /= subst_context_nil.\n  rewrite -PCUICClosed.smash_context_subst /= subst_context_nil. apply eqctx.\nQed.\n\n\n(** ** Prelim on typing *)\n\nInductive red_decls Σ Γ Γ' : forall (x y : context_decl), Type :=\n| conv_vass na na' T T' : isType Σ Γ' T' -> red Σ Γ T T' ->\n  eq_binder_annot na na' ->\n  red_decls Σ Γ Γ' (vass na T) (vass na' T')\n\n| conv_vdef_type na na' b T T' : isType Σ Γ' T' -> red Σ Γ T T' ->\n  eq_binder_annot na na' ->\n  red_decls Σ Γ Γ' (vdef na b T) (vdef na' b T')\n\n| conv_vdef_body na na' b b' T : isType Σ Γ' T ->\n  eq_binder_annot na na' ->\n  Σ ;;; Γ' |- b' : T -> red Σ Γ b b' ->\n  red_decls Σ Γ Γ' (vdef na b T) (vdef na' b' T).\n\nNotation red_context Σ := (All2_fold (red_decls Σ)).\n\nLemma conv_context_app (Σ : global_env_ext) (Γ1 Γ2 Γ1' : context) :\n  wf Σ ->\n  wf_local Σ (Γ1 ,,, Γ2) ->\n  conv_context cumulSpec0 Σ Γ1 Γ1' -> conv_context cumulSpec0 Σ (Γ1 ,,, Γ2) (Γ1' ,,, Γ2).\nProof.\n  intros. induction Γ2.\n  - cbn; eauto.\n  - destruct a. destruct decl_body.\n    + cbn. econstructor. inv X0. apply IHΓ2. eauto.\n      depelim X0; econstructor; reflexivity.\n    + cbn. econstructor. inv X0. apply IHΓ2. eauto. now econstructor.\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/Prelim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.26983662855060897}}
{"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_Arbiter.v                             *)\n(****************************************************************************)\n\n\nRequire Export Tools_Inf.\nRequire Export Behaviour_Struct_lemmas.\n\n\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nSection Timing_Arbiter_Proof.\n\n  Variable Fs : Stream bool.\n  Variable Act : Stream (d_list bool 4).\n\n(** Hypothesis on the input signals fs and act **)\n\n  Hypothesis fs_0 : S_head Fs = false.\n\n  Hypothesis\n    fs_act_signals : EqS sig_false (S_map2 andb (S_tail Fs) (S_Ackor Act)).   \n  \n\n  Definition P_Timing (fs : bool) (st : label_t) :=\n    false = fs && Out_Timing st.\n\n\n CoInductive Inv_P_Timing : Stream bool -> Stream label_t -> Prop :=\n     C_Inv_t :\n       forall (i : Stream bool) (s : Stream label_t),\n       P_Timing (S_head i) (S_head s) ->\n       Inv_P_Timing (S_tail i) (S_tail s) -> Inv_P_Timing i s.\n\n\n Lemma eqS_Inv_P_Timing :\n  forall (i i' : Stream bool) (s s' : Stream label_t),\n  EqS i i' -> EqS s s' -> Inv_P_Timing i' s' -> Inv_P_Timing i s.\n  Proof.\n  cofix eqS_Inv_P_Timing.\n  intros i i' s s' H_i H_s H_P.\n  inversion_clear H_i.\n  inversion_clear H_s.\n  inversion_clear H_P.\n  apply C_Inv_t.\n  rewrite H; rewrite H1; try trivial.\n  apply eqS_Inv_P_Timing with (S_tail i') (S_tail s'); trivial.\n  Qed.\n\n\n(** P_Timing is an invariant property **)\n\n  Lemma eq_fs_and_RouteE_false :\n   forall (e : bool * d_list bool 4) (s : label_t),\n   P_Timing (fst e) (Trans_Timing e s).\n Proof.\n unfold P_Timing in |- *.\n intros e s; elim e; clear e; intros fs act.\n elim (Lib_Bool.bool_dec fs); intros H_fs.\n rewrite H_fs; simpl in |- *.\n case s; case (Ackor act); simpl in |- *; auto.\n rewrite H_fs; simpl in |- *; auto.\n Qed.\n\n\n Lemma Is_Inv_P_Timing :\n  forall s : label_t, Inv_P_Timing Fs (States_TIMING (Compact Fs Act) s).\n Proof.\n intro s.\n apply C_Inv_t.\n simpl in |- *; rewrite fs_0; unfold P_Timing in |- *; auto.\n generalize Fs Act s fs_act_signals.\n clear fs_act_signals fs_0 s Act Fs.\n cofix Is_Inv_P_Timing.\n intros fs act s H_sig.\n inversion_clear H_sig.\n apply C_Inv_t.\n simpl in |- *.\n generalize\n  (eq_fs_and_RouteE_false (S_head (S_tail fs), S_head (S_tail act))\n     (Trans_Timing (S_head fs, S_head act) s)); simpl in |- *; \n  auto.\n simpl in H.\n generalize H.\n case (S_head (S_tail fs)); simpl in |- *.\n intros h; elim h; simpl in |- *.\n intros h'; clear h'.\n case s; case (S_head fs); unfold P_Timing in |- *; simpl in |- *; auto.\n unfold P_Timing in |- *; auto.\n simpl in Is_Inv_P_Timing; simpl in |- *.\n apply Is_Inv_P_Timing.\n apply H0.\n\n Qed.\n\n\n\n(* Proof that the property P_a4 taken for the FOUR_ARBITERS proof holds *)\n(* for the output of TIMING : we exhibit an invariant Inv_t_a4 *)\n(* Proof that : sa=AT_LEAST_ONE_IS_ACTIVE_a4 \\/ sa=WAIT_a4 -> RouteE=false *)\n(* Avec RouteE=(Out_Timing st) *)\n\nDefinition Inv_t_a4 (s_a4 : STATE_a4) (st : label_t) :=\n  let (sa4, _) := s_a4 in\n  sa4 = START_a4 /\\ st = START_t \\/\n  sa4 = START_a4 /\\ st = WAIT_t \\/\n  sa4 = START_a4 /\\ st = ROUTE_t \\/\n  sa4 = AT_LEAST_ONE_IS_ACTIVE_a4 /\\ st = START_t \\/\n  sa4 = WAIT_a4 /\\ st = START_t.\n\n\n\n(** Inv_t_a4 is an invariant **)\n\nLemma Inv_Init_states_t_a4 :\n forall (g : d_list (bool * bool) 4) (o : d_list bool 4),\n Inv_t_a4 (WAIT_a4, (g, o)) START_t.\nProof.\nunfold Inv_t_a4 in |- *; intros g o; do 3 right; auto.\nQed.\n\n\nLemma Inv_t_a4_Ok :\n forall (sa4 : STATE_a4) (st : label_t) (fs : bool) \n   (act : d_list bool 4) (ltReq : d_list (d_list bool 4) 4),\n P_Timing fs st ->\n Inv_t_a4 sa4 st ->\n Inv_t_a4 (Trans_Four_Arbiters (fs, (Out_Timing st, ltReq)) sa4)\n   (Trans_Timing (fs, act) st).\nProof.\nunfold Inv_t_a4 at 1 in |- *.\nintros sa4 st fs' act' ltReq'; elim sa4; clear sa4.\nintros sa4 g P H.\nelim g; clear g; intros g o.\nelim H; clear H; intros H.\nelim H; clear H; intros H1 H2; rewrite H1; rewrite H2; simpl in |- *.\ncase fs'; simpl in |- *; auto.\n\nelim H; clear H; intros H.\nelim H; clear H; intros H1 H2; rewrite H1; rewrite H2; simpl in |- *.\ncase (Ackor act'); simpl in |- *; auto.\ncase fs'; simpl in |- *; auto.\n\nelim H; clear H; intros H.\ngeneralize P; clear P.\nelim H; clear H; intros H1 H2; rewrite H1; rewrite H2; simpl in |- *.\ncase fs'; simpl in |- *.\nunfold P_Timing in |- *; simpl in |- *; intros Abs.\nabsurd (false = true); auto.\n\nintro H0; clear H0.\ncase (Ackor (d_map (Ackor (n:=3)) ltReq')); simpl in |- *; auto.\nright; right; right; auto.\n\nelim H; clear H; intros H.\nelim H; clear H; intros H1 H2; rewrite H1; rewrite H2; simpl in |- *.\ncase fs'; simpl in |- *; auto.\nright; right; right; right; auto.\n\nelim H; clear H; intros H1 H2; rewrite H1; rewrite H2; simpl in |- *.\ncase fs'; simpl in |- *; auto.\nright; right; right; right; auto.\n\nQed.\n\n\nLemma P_a4_inv :\n forall (sa4 : STATE_a4) (st : label_t) (fs : bool)\n   (ltReq : d_list (d_list bool 4) 4)\n   (old_a4 : d_list bool 2 * bool * (d_list bool 2 * bool) *\n             (d_list bool 2 * bool * (d_list bool 2 * bool))),\n Inv_t_a4 sa4 st -> P_a4 (fs, (Out_Timing st, ltReq)) sa4 old_a4.\nProof.\nunfold Inv_t_a4 in |- *; unfold P_a4 in |- *.\nintros sa4 st fs' ltReq' old_a4; clear fs' ltReq' old_a4.\nelim sa4; clear sa4; simpl in |- *.\nintros sa4 g H.\nelim g; clear g; intros g o.\n\nelim H; clear H; intros H.\nelim H; clear H; intros H1 H2; rewrite H1; rewrite H2; simpl in |- *; auto.\n\nelim H; clear H; intros H.\nelim H; clear H; intros H1 H2; rewrite H1; rewrite H2; simpl in |- *; auto.\n\nelim H; clear H; intros H.\nelim H; clear H; intros H1 H2; rewrite H1; rewrite H2; simpl in |- *; auto.\nintro H; elim H; clear H; intro Abs.\nabsurd (START_a4 = AT_LEAST_ONE_IS_ACTIVE_a4); auto.\ndiscriminate.\nabsurd (START_a4 = WAIT_a4); auto.\ndiscriminate.\n\nelim H; clear H; intros H.\nelim H; clear H; intros H1 H2; rewrite H1; rewrite H2; simpl in |- *; auto.\n\nelim H; clear H; intros H1 H2; rewrite H1; rewrite H2; simpl in |- *; auto.\n\nQed.\n\n\n\n(* Proof that P_a4 is invariant *)\n\n\nLemma Inv_a4 :\n forall (sa4 : STATE_a4) (st : label_t)\n   (old_a4 : d_list bool 2 * bool * (d_list bool 2 * bool) *\n             (d_list bool 2 * bool * (d_list bool 2 * bool)))\n   (ltReq : Stream (d_list (d_list bool 4) 4)),\n Inv_t_a4 sa4 st ->\n Inv P_a4 (Compact Fs (Compact (Behaviour_TIMING (Compact Fs Act) st) ltReq))\n   (States_FOUR_ARBITERS\n      (Compact Fs (Compact (Behaviour_TIMING (Compact Fs Act) st) ltReq)) sa4)\n   (Structure_States_FOUR_ARBITERS\n      (Compact Fs (Compact (Behaviour_TIMING (Compact Fs Act) st) ltReq))\n      old_a4).\nProof.\nintros sa st old_a4 ltReq H_I.\ngeneralize (Is_Inv_P_Timing st).\ngeneralize sa st old_a4 Fs Act ltReq H_I.\ncofix Inv_a4.\nintros sa' st' old_a4' fs' act' ltReq' H_I' H_P'.\ninversion_clear H_P'.\napply C_Inv.\nsimpl in H.\nrewrite S_head_Compact.\nrewrite S_head_Compact.\nrewrite S_head_Behaviour_TIMING.\napply P_a4_inv; try trivial.\n\ngeneralize\n (Inv_a4\n    (Trans_Four_Arbiters\n       (S_head\n          (Compact fs'\n             (Compact (Behaviour_TIMING (Compact fs' act') st') ltReq'))) sa')\n    (Trans_Timing (S_head (Compact fs' act')) st')\n    (Trans_Struct_four_arbiters\n       (S_head\n          (Compact fs'\n             (Compact (Behaviour_TIMING (Compact fs' act') st') ltReq')))\n       old_a4') (S_tail fs') (S_tail act') (S_tail ltReq')).\nclear Inv_a4.\nintro a4_I; apply a4_I.\nrewrite S_head_Compact.\nrewrite S_head_Compact.\nrewrite S_head_Behaviour_TIMING.\nrewrite S_head_Compact.\napply Inv_t_a4_Ok; try trivial.\ntry trivial.\nQed.\n\n\nEnd Timing_Arbiter_Proof.\n\n\n\nRequire Import Arbitration_beh_sc.\n\n\nLemma S_tail_Behaviour_TIMINGPDECODE_ID :\n forall\n   (i : Stream\n          (bool *\n           (d_list bool 4 * (d_list bool 4 * d_list (d_list bool 2) 4))))\n   (s : state_id * (label_t * STATE_p)),\n S_tail (Behaviour_TIMINGPDECODE_ID i s) =\n Behaviour_TIMINGPDECODE_ID (S_tail i) (Trans_TimingPDecode_Id (S_head i) s).\nProof.\nauto.\nQed.\n\n\nLemma Equiv_Behaviour_TIMINGPDECODE_ID :\n forall\n   (i : Stream\n          (bool *\n           (d_list bool 4 * (d_list bool 4 * d_list (d_list bool 2) 4))))\n   (si : state_id) (st : label_t) (sp : STATE_p),\n EqS (Behaviour_TIMINGPDECODE_ID i (si, (st, sp)))\n   (Compact (S_map fstS i)\n      (Compact\n         (Behaviour_TIMING\n            (Compact (S_map fstS i)\n               (S_map fstS (S_map sndS i))) st)\n         (Behaviour_PRIORITY_DECODE\n            (Compact (S_map fstS (S_map sndS i))\n               (Compact\n                  (S_map fstS\n                     (S_map sndS (S_map sndS i)))\n                  (S_map sndS\n                     (S_map sndS (S_map sndS i))))) sp))).\nProof.\ncofix Equiv_Behaviour_TIMINGPDECODE_ID.\nintros i si st sp.\napply eqS.\nclear Equiv_Behaviour_TIMINGPDECODE_ID; simpl in |- *.\nunfold Out_id in |- *; unfold Out_Timing_Mealy in |- *;\n unfold Out_PriorityDecode_Mealy in |- *.\nelim (S_head i); simpl in |- *.\nintros y y0; elim y0; simpl in |- *.\nintros y1 y2; elim y2; simpl in |- *; auto.\n\nrewrite S_tail_Behaviour_TIMINGPDECODE_ID.\nunfold Trans_TimingPDecode_Id in |- *.\nunfold Trans_Timing_PDecode in |- *; unfold Trans_PC in |- *.\ndo 2 rewrite S_tail_Compact.\nrewrite S_tail_Behaviour_TIMING; rewrite S_tail_Behaviour_PDECODE.\nsimpl in |- *.\nelim (S_head i); intros y y0.\nelim y0; intros y1 y2.\nelim y2; intros y3 y4.\nsimpl in |- *.\n\ngeneralize\n (Equiv_Behaviour_TIMINGPDECODE_ID (S_tail i) (Trans_id y si)\n    (Trans_Timing (y, y1) st) (Trans_PriorityDecode (y1, (y3, y4)) sp)).\nclear Equiv_Behaviour_TIMINGPDECODE_ID. \nintro H; apply H.\n\nQed.\n\n\nSection Verif_hyp.\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  Variable i : Stream Input_type.\n\n  Let Fs := S_map fstS i.\n\n  Let Act := S_map fstS (S_map sndS i).\n\n  Let Pri := S_map fstS (S_map sndS (S_map sndS i)).\n\n  Let Route := S_map sndS (S_map sndS (S_map sndS i)).\n\n\n  (** Hypothesis on the input signals fs and act **)\n\n  Hypothesis fs_0 : S_head Fs = false.\n\n  Hypothesis\n    fs_act_signals : EqS sig_false (S_map2 andb (S_tail Fs) (S_Ackor Act)).   \n  \n\nLemma Inv_a4' :\n forall (si : state_id) (st : label_t) (sp : STATE_p) \n   (sa4 : STATE_a4)\n   (ra4 : d_list bool 2 * bool * (d_list bool 2 * bool) *\n          (d_list bool 2 * bool * (d_list bool 2 * bool))),\n Inv_t_a4 sa4 st ->\n Inv P_a4 (Behaviour_TIMINGPDECODE_ID i (si, (st, sp)))\n   (States_FOUR_ARBITERS (Behaviour_TIMINGPDECODE_ID i (si, (st, sp))) sa4)\n   (Structure_States_FOUR_ARBITERS\n      (Behaviour_TIMINGPDECODE_ID i (si, (st, sp))) ra4).\nProof.\nintros si st sp sa4 ra4 HI.\n\ngeneralize\n (Inv_a4 fs_0 fs_act_signals (sa4:=sa4) (st:=st) ra4\n    (Behaviour_PRIORITY_DECODE (Compact Act (Compact Pri Route)) sp)).\nintro P.\napply\n eqS_about_P\n  with\n    (i' := Compact Fs\n             (Compact (Behaviour_TIMING (Compact Fs Act) st)\n                (Behaviour_PRIORITY_DECODE (Compact Act (Compact Pri Route))\n                   sp)))\n    (s1' := States_FOUR_ARBITERS\n              (Compact Fs\n                 (Compact (Behaviour_TIMING (Compact Fs Act) st)\n                    (Behaviour_PRIORITY_DECODE\n                       (Compact Act (Compact Pri Route)) sp))) sa4)\n    (s2' := Structure_States_FOUR_ARBITERS\n              (Compact Fs\n                 (Compact (Behaviour_TIMING (Compact Fs Act) st)\n                    (Behaviour_PRIORITY_DECODE\n                       (Compact Act (Compact Pri Route)) sp))) ra4).\nunfold Fs in |- *; unfold Act in |- *; unfold Pri in |- *;\n unfold Route in |- *; apply Equiv_Behaviour_TIMINGPDECODE_ID.\nunfold States_FOUR_ARBITERS in |- *.\napply EqS_States_Mealy; auto.\nunfold Fs in |- *; unfold Act in |- *; unfold Pri in |- *;\n unfold Route in |- *; apply Equiv_Behaviour_TIMINGPDECODE_ID.\nunfold Structure_States_FOUR_ARBITERS in |- *; unfold States_PC in |- *.\napply EqS_States_Mealy; auto.\nunfold Fs in |- *; unfold Act in |- *; unfold Pri in |- *;\n unfold Route in |- *; apply Equiv_Behaviour_TIMINGPDECODE_ID.\napply P.\ntry trivial.\nQed.\n\n\nEnd Verif_hyp.\n\n\nSection From_init_states.\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  Variable i : Stream Input_type.\n\n  Let Fs := S_map fstS i.\n\n  Let Act := S_map fstS (S_map sndS i).\n\n  Let Pri := S_map fstS (S_map sndS (S_map sndS i)).\n\n  Let Route := S_map sndS (S_map sndS (S_map sndS i)).\n\n\n  (** Hypothesis on the input signals fs and act **)\n\n  Hypothesis fs_0 : S_head Fs = false.\n\n  Hypothesis\n    fs_act_signals : EqS sig_false (S_map2 andb (S_tail Fs) (S_Ackor Act)).   \n  \n\n (* P_a4 is an invariant (from the initial states) *)\n\n  Variable g11_0 g12_0 g21_0 g22_0 : bool * bool.      (* lasts *)\n  Variable p_0 : d_list (d_list bool 4) 4.    (* ltReq *)\n\nLemma P_a4_Ok :\n Inv P_a4\n   (Behaviour_TIMINGPDECODE_ID i (IDENTITY, (START_t, (START_p, p_0))))\n   (States_FOUR_ARBITERS\n      (Behaviour_TIMINGPDECODE_ID i (IDENTITY, (START_t, (START_p, p_0))))\n      (WAIT_a4, (List4 g11_0 g12_0 g21_0 g22_0, l4_ffff)))\n   (Structure_States_FOUR_ARBITERS\n      (Behaviour_TIMINGPDECODE_ID i (IDENTITY, (START_t, (START_p, p_0))))\n      (pdt_List2 g11_0, false, (pdt_List2 g12_0, false),\n      (pdt_List2 g21_0, false, (pdt_List2 g22_0, false)))).\n\nProof.\napply Inv_a4'; auto.\napply Inv_Init_states_t_a4.\nQed.\n\n\nEnd From_init_states.\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_Arbiter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.26983662855060897}}
{"text": "From Coq Require Export Morphisms Setoid Program.Equality.\nFrom ITree Require Export ITree ITreeFacts Eq.Rutt.\nFrom Paco Require Import paco.\nFrom Coq Require Export Eqdep EqdepFacts.\n\nFrom Equations Require Import Equations.\n\nRequire Export HeterogeneousEventRelations.\n\nLtac inj_existT := repeat match goal with | H : existT _ _ _ = _ |- _ => apply inj_pair2 in H end.\n\nLemma rutt_inv_Vis :   forall (E1 E2 : Type -> Type) (R1 R2 : Type) (REv : forall A B : Type, E1 A -> E2 B -> Prop)\n    (RAns : forall A B : Type, E1 A -> A -> E2 B -> B -> Prop) (RR : R1 -> R2 -> Prop) A B\n    (e1 : E1 A) (e2 : E2 B) k1 k2,\n    rutt REv RAns RR (Vis e1 k1) (Vis e2 k2) ->\n    REv A B e1 e2 /\\ (forall a b, RAns A B e1 a e2 b -> rutt REv RAns RR (k1 a) (k2 b)).\nProof.\n  intros. pinversion H. inj_existT. subst. pclearbot. split; auto.\n  intros. apply H7 in H0. pclearbot. auto.\nQed.\n\nDefinition extract {E1 E2 A B} (REAns : relationEAnsH E1 E2) \n           (e1 : E1 A) (e2 : E2 B) : relationH A B :=\n  fun a b => REAns A B e1 a e2 b.\n  \n\nSection Rutt6.\n\nContext (D1 D2 E1 E2 : Type -> Type).\nContext (REvE : relationEH E1 E2).\nContext (REvAns : forall A B : Type, E1 A -> A -> E2 B -> B -> Prop ).\n\nContext (REvInv : relationEH D1 D2).\nContext (REvAnsInv : forall A B : Type, D1 A -> A -> D2 B -> B -> Prop).\n\nInductive rutt6F (sim : forall (A B : Type), D1 A -> D2 B -> itree E1 A -> itree E2 B -> Prop) :\n   forall (A B : Type), D1 A -> D2 B -> itree' E1 A -> itree' E2 B -> Prop := \n  (* shows how the post condition of the itrees is reliant on d1 and d2*)\n  | rutt6RetF (A B : Type) (d1 : D1 A) (d2 : D2 B) a b : \n    REvAnsInv A B d1 a d2 b -> rutt6F sim A B d1 d2 (RetF a) (RetF b)\n  | rutt6TauF (A B : Type) (d1 : D1 A) (d2 : D2 B) t1 t2 :\n    sim A B d1 d2 t1 t2 -> rutt6F sim A B d1 d2 (TauF t1) (TauF t2)\n  | rutt6VisF (A B C D : Type) (d1 : D1 A) (d2 : D2 B) (e1 : E1 C) (e2 : E2 D) k1 k2 :\n    REvE C D e1 e2 ->\n    (forall c d, REvAns C D e1 c e2 d -> sim A B d1 d2 (k1 c) (k2 d) ) ->\n    rutt6F sim A B d1 d2 (VisF e1 k1) (VisF e2 k2)\n\n  | rutt5TauL (A B : Type) (d1 : D1 A) (d2 : D2 B) t1 ot2 : \n    rutt6F sim A B d1 d2 (observe t1) ot2 ->\n    rutt6F sim A B d1 d2 (TauF t1) ot2\n  | rutt5TauR (A B : Type) (d1 : D1 A) (d2 : D2 B) ot1 t2 : \n    rutt6F sim A B d1 d2 ot1 (observe t2) ->\n    rutt6F sim A B d1 d2 ot1 (TauF t2)\n.\n\nHint Constructors rutt6F : itree.\n\nDefinition rutt6_ sim A B d1 d2 t1 t2 := rutt6F sim A B d1 d2 (observe t1) (observe t2).\n\nHint Unfold rutt6_ : itree.\n\nLemma rutt6_monot : monotone6 rutt6_.\nProof.\n  repeat intro. red in IN. red.\n  induction IN; eauto with itree.\nQed.\n\n\n\nDefinition rutt6 : forall (A B : Type), D1 A -> D2 B -> itree E1 A -> itree E2 B -> Prop := paco6 rutt6_ bot6.\n\n#[local] Hint Resolve rutt6_monot : paco.\n\nLemma rutt6_to_rutt (A B : Type) (d1 : D1 A) (d2 : D2 B) :\n  forall (t1 : itree E1 A) (t2 : itree E2 B), \n    rutt6 A B d1 d2 t1 t2 ->\n    rutt REvE REvAns (extract REvAnsInv d1 d2) t1 t2.\nProof.\n  pcofix CIH. intros t1 t2 Ht12. punfold Ht12. red in Ht12. pstep. red.\n  hinduction Ht12 before r; intros; pclearbot; eauto with itree.\n  - constructor; auto.\n  - constructor. right. apply CIH; auto.\n  - constructor; auto. intros. apply H0 in H1. pclearbot. right.\n    apply CIH; auto.\n  - constructor. eauto.\n  - constructor; eauto.\nQed.\n\nLemma rutt_to_rutt6 (A B : Type) (d1 : D1 A) (d2 : D2 B) :\n  forall (t1 : itree E1 A) (t2 : itree E2 B), \n    rutt REvE REvAns (extract REvAnsInv d1 d2) t1 t2 ->\n    rutt6 A B d1 d2 t1 t2.\nProof.\n  pcofix CIH. intros t1 t2 Ht12. punfold Ht12. red in Ht12. pstep. red.\n  hinduction Ht12 before r; intros; pclearbot; eauto with itree.\n  constructor; auto. intros. apply H0 in H1. pclearbot. right. apply CIH; auto.\nQed.\n\nEnd Rutt6.\n\n#[global] Hint Resolve rutt6_monot : paco.\n\nLtac use_simpobs := repeat match goal with\n                           | H : RetF _ = observe ?t |- _ => apply simpobs in H \n                           | H : TauF _ = observe ?t |- _ => apply simpobs in H\n                           | H : VisF _ _ = observe ?t |- _ => apply simpobs in H\n                           end.\n\nInstance grutt_cong_eqit_eq {E1 E2 R1 R2 r rg} {RR : R1 -> R2 -> Prop} {REv RAns} :\n\n  Proper (@eq_itree E1 R1 R1 eq ==> @eq_itree E2 R2 R2 eq  ==> flip impl)\n         (gpaco2 (rutt_ REv RAns RR) (euttge_trans_clo RR) r rg  ).\nProof. eapply grutt_cong_eqit; intros; subst; auto. Qed.\n\nInstance grutt_cong_euttge_eq {E1 E2 R1 R2 r rg} {RR : R1 -> R2 -> Prop} {REv RAns} :\n\n  Proper (@euttge E1 R1 R1 eq ==> @euttge E2 R2 R2 eq  ==> flip impl)\n         (gpaco2 (rutt_ REv RAns RR) (euttge_trans_clo RR) r rg  ).\nProof. eapply grutt_cong_euttge; intros; subst; auto. Qed.\n\n(*move this to rutt theory*)\nLemma rutt_bind (E1 E2 : Type -> Type) (R1 R2 S1 S2 : Type) (REvE : relationEH E1 E2) (REvAns : relationEAnsH E1 E2) \n  (RR : R1 -> R2 -> Prop) (RS : S1 -> S2 -> Prop) k1 k2 :\n  (forall r1 r2, RR r1 r2 -> rutt REvE REvAns RS (k1 r1) (k2 r2) ) ->\n  forall t1 t2, rutt REvE REvAns RR t1 t2 -> rutt REvE REvAns RS (bind t1 k1) (bind t2 k2).\nProof.\n  intros Hk. ginit. gcofix CIH. intros. punfold H0. red in H0.\n  remember (observe t1) as x. remember (observe t2) as y.\n  hinduction H0 before r; intros; use_simpobs.\n  - rewrite Heqx, Heqy. setoid_rewrite bind_ret_l. gfinal. right.\n    eapply paco2_mon; [eapply Hk; eauto | intros; contradiction].\n  - rewrite Heqx, Heqy. setoid_rewrite bind_tau. gstep. constructor.\n    gfinal. pclearbot. left. apply CIH. auto.\n  - rewrite Heqx, Heqy. setoid_rewrite bind_vis. gstep. constructor. auto.\n    intros. apply H0 in H1. pclearbot. gfinal. left. eapply CIH. auto.\n  - rewrite Heqx. rewrite tau_euttge. eauto.\n  - rewrite Heqy. rewrite tau_euttge. eauto.\nQed.\n\n\nVariant EvEq {E : Type -> Type} : forall (A B : Type), E A -> E B -> Prop :=\n  | eveq (A : Type) (e : E A) : EvEq A A e e.\n\nVariant EvEqAns {E : Type -> Type} : forall A B, E A -> A -> E B -> B -> Prop :=\n  | eveqans A (e : E A) (a : A) : EvEqAns A A e a e a.\n\nLemma rutt_to_eutt (E : Type -> Type) R1 R2 RR : \n  forall (t1 : itree E R1) (t2 : itree E R2),\n    rutt EvEq EvEqAns RR t1 t2 -> eutt RR t1 t2.\nProof.\n  ginit. gcofix CIH. intros t1 t2 Ht12. punfold Ht12. red in Ht12.\n  remember (observe t1) as ot1. remember (observe t2) as ot2.\n  hinduction Ht12 before r; intros; use_simpobs.\n  - rewrite Heqot1, Heqot2. gstep. constructor. auto.\n  - rewrite Heqot1, Heqot2. gstep. constructor. gfinal. left. pclearbot. eauto.\n  - rewrite Heqot1, Heqot2. dependent destruction H. gstep. constructor. intros.\n    gfinal. left. apply CIH. assert (EvEqAns A A e v e v). constructor. apply H0 in H. pclearbot. auto.\n  - rewrite Heqot1, tau_euttge. auto.\n  - rewrite Heqot2, tau_euttge. auto.\nQed. \n\n(*this is working fine but very annoying finish it monday morning*)\nLemma rutt_cong_eqit_eql: forall (E1 E2 : Type -> Type) (R1 R2 : Type)\n                            (RR : R1 -> R2 -> Prop)\n                            (REv : forall A B : Type, E1 A -> E2 B -> Prop)\n                            (RAns : forall A B : Type, E1 A -> A -> E2 B -> B -> Prop)\n                            (b1 b2 : bool) (t1 t2 : itree E1 R1) (t4 : itree E2 R2),\n    eqit eq b1 b2 t1 t2 ->\n    rutt REv RAns RR t2 t4 -> rutt REv RAns RR t1 t4.\nProof.\n  intros E1 E2 R1 R2 RR REv RAns b1 b2. ginit. gcofix CIH. \n  intros t1 t2 t4 Ht12 Ht24. punfold Ht24. red in Ht24.\n  punfold Ht12. red in Ht12. remember (observe t1) as x.\n  remember (observe t2) as y. remember (observe t4) as z.\n  hinduction Ht24 before r; intros; use_simpobs.\n  - remember (RetF r1) as or. hinduction Ht12 before r; intros; inv Heqor; use_simpobs; eauto.\n    + rewrite Heqz. rewrite Heqx. gstep. constructor. auto.\n    + rewrite Heqx. rewrite tau_euttge. eauto.\n  - assert (DEC: (exists m3, x = TauF m3) \\/ (forall m3, x <> TauF m3)).\n     { destruct x; eauto; right; repeat intro; discriminate. }\n     destruct DEC as [ [m3 Hm3]  | Hx ].\n     + subst. symmetry in Hm3. use_simpobs. rewrite Hm3, Heqz. gstep. constructor.\n       gfinal. left. pclearbot. eapply CIH; eauto. apply eqit_inv_Tau. rewrite <- Hm3.\n       pstep. auto.\n     + destruct x; try (exfalso; eapply Hx; eauto; fail).\n       {\n         pclearbot. use_simpobs. rewrite Heqx. clear Heqx t1. rewrite Heqz, tau_euttge. clear Heqz t4 Hx.\n         inv Ht12. punfold H. red in H. remember (RetF r0) as x.\n         hinduction REL before r; intros; inv Heqx; use_simpobs.\n         - gfinal. right. eapply paco2_mon; [ pstep; apply H | intros; contradiction].\n         - eapply IHREL; eauto. pstep_reverse. apply rutt_inv_Tau_l. pstep. auto.\n       }\n       {\n         pclearbot. rewrite Heqz, tau_euttge. use_simpobs. rewrite Heqx. inv Ht12. \n         punfold H. red in H. remember (VisF e k) as x. hinduction REL before r; intros; inv Heqx0; inj_existT; subst.\n         - pclearbot. remember (VisF e0 k2) as x. remember (observe m2) as om2.\n           hinduction H before r; intros; inv Heqx0; inj_existT; subst.\n           + use_simpobs. rewrite Heqom2. gstep. constructor; auto. intros. apply H0 in H1.\n             pclearbot. gfinal. left. eapply CIH; eauto. apply REL.\n           + use_simpobs. rewrite Heqom2. rewrite tau_euttge. eauto.\n         - eapply IHREL; eauto. pstep_reverse. apply rutt_inv_Tau_l. pstep. auto.\n       }\n  - rewrite Heqz. remember (VisF e1 k1) as y. hinduction Ht12 before r; intros; inv Heqy0; inj_existT; subst; use_simpobs.\n    + rewrite Heqx. gstep. constructor; auto. intros. pclearbot. gfinal. left. eapply CIH; eauto.\n      apply REL. apply H0 in H1. pclearbot. auto.\n    + rewrite Heqx, tau_euttge; eauto.\n  - subst.\n    inv Ht12. pclearbot; use_simpobs.\n    + rewrite H0, tau_euttge. eapply IHHt24; eauto. pstep_reverse.\n    + use_simpobs. rewrite H0, tau_euttge. inv CHECK. eapply IHHt24; eauto. \n      pstep_reverse. apply eqit_inv_Tau_r. pstep. auto.\n    + eapply IHHt24; eauto.\n  - rewrite Heqz, tau_euttge. eauto.\nQed.\n\nLemma rutt_cong_eqit_eqr: forall (E1 E2 : Type -> Type) (R1 R2 : Type)\n                            (RR : R1 -> R2 -> Prop)\n                            (REv : forall A B : Type, E1 A -> E2 B -> Prop)\n                            (RAns : forall A B : Type, E1 A -> A -> E2 B -> B -> Prop)\n                            (b1 b2 : bool) (t1 : itree E1 R1) (t2 t4 : itree E2 R2),\n    eqit eq b1 b2 t2 t4 ->\n    rutt REv RAns RR t1 t2 -> rutt REv RAns RR t1 t4.\nProof.\n  intros E1 E2 R1 R2 RR REv RAns b1 b2. ginit. gcofix CIH. \n  intros t1 t2 t4 Ht12 Ht24. punfold Ht24. red in Ht24.\n  punfold Ht12. red in Ht12. remember (observe t1) as x.\n  remember (observe t2) as y. remember (observe t4) as z.\n  hinduction Ht24 before r; intros; use_simpobs.\n  - remember (RetF r2) as or. hinduction Ht12 before r; intros; inv Heqor; use_simpobs; eauto.\n    + rewrite Heqz. rewrite Heqx. gstep. constructor. auto.\n    + rewrite Heqz. rewrite tau_euttge. eauto.\n  - assert (DEC: (exists m3, z = TauF m3) \\/ (forall m3, z <> TauF m3)).\n     { destruct z; eauto; right; repeat intro; discriminate. }\n     destruct DEC as [ [m3 Hm3]  | Hz ].\n     + subst. symmetry in Hm3. use_simpobs. rewrite Hm3, Heqx. gstep. constructor.\n       gfinal. left. pclearbot. eapply CIH; eauto. apply eqit_inv_Tau. rewrite <- Hm3.\n       pstep. auto.\n     + destruct z; try (exfalso; eapply Hz; eauto; fail).\n       {\n         pclearbot. use_simpobs. rewrite Heqx. clear Heqx t1. rewrite Heqz, tau_euttge.\n         inv Ht12. punfold H. red in H. remember (RetF r0) as x.\n         hinduction REL before r; intros; inv Heqx; use_simpobs.\n         - gfinal. right. eapply paco2_mon; [ pstep; apply H | intros; contradiction].\n         - eapply IHREL; eauto. pstep_reverse. apply rutt_inv_Tau_r. pstep. auto.\n       }\n       {\n         pclearbot. use_simpobs. rewrite Heqz, Heqx, tau_euttge. inv Ht12. \n         punfold H. red in H. remember (VisF e k) as x. hinduction REL before r; intros; inv Heqx0; inj_existT; subst.\n         - pclearbot. remember (VisF e0 k1) as x. remember (observe m1) as om2.\n           hinduction H before r; intros; inv Heqx0; inj_existT; subst.\n           + use_simpobs. rewrite Heqom2. gstep. constructor; auto. intros. apply H0 in H1.\n             pclearbot. gfinal. left. eapply CIH; eauto. apply REL.\n           + use_simpobs. rewrite Heqom2. rewrite tau_euttge. eauto.\n         - eapply IHREL; eauto. pstep_reverse. apply rutt_inv_Tau_r. pstep. auto.\n       }\n  - rewrite Heqx. remember (VisF e2 k2) as y. hinduction Ht12 before r; intros; inv Heqy0; inj_existT; subst; use_simpobs.\n    + rewrite Heqz. gstep. constructor; auto. intros. pclearbot. gfinal. left. eapply CIH; eauto.\n      apply REL. apply H0 in H1. pclearbot. auto.\n    + rewrite Heqz, tau_euttge; eauto.\n  - rewrite Heqx, tau_euttge. eapply IHHt24; eauto.\n  - inv Ht12. pclearbot; use_simpobs.\n    + rewrite H1, tau_euttge. eapply IHHt24; eauto. pstep_reverse.\n    + eapply IHHt24; eauto.\n    + use_simpobs. rewrite H0, tau_euttge. eapply IHHt24; eauto. inv CHECK. pstep_reverse.\n      eapply eqit_inv_Tau_l. pstep. auto.\nQed.\n\nInstance rutt_cong_eqit_eq {E1 E2 R1 R2} {RR : R1 -> R2 -> Prop} {REv RAns} b1 b2 :\n  Proper (@eqit E1 R1 R1 eq b1 b2 ==> @eqit E2 R2 R2 eq b1 b2 ==> flip impl) (rutt REv RAns RR).\nProof.\n  intros t1 t2 Ht12 t3 t4 Ht34 H.\n  eapply rutt_cong_eqit_eql; eauto. eapply rutt_cong_eqit_eqr; eauto. apply eqit_flip in Ht34. \n  eapply eqit_mon; try apply Ht34; eauto.\nQed.\n\n      \n\nSection MRec.\n\nContext (D1 D2 E : Type -> Type).\nContext (bodies1 : D1 ~> itree (D1 +' E)).\nContext (bodies2 : D2 ~> itree (D2 +' E)).\n(*\nContext (A B :Type).\nContext (init1 : D1 A).\nContext (init2 : D2 B).\n*)\nContext (REvE : relationEH E E).\nContext (REvAns : forall A B : Type, E A -> A -> E B -> B -> Prop ).\n\nContext (REvInv : relationEH D1 D2).\nContext (REvAnsInv : forall A B : Type, D1 A -> A -> D2 B -> B -> Prop).\n\nContext (Hbodies : forall A B (d1 : D1 A) (d2 : D2 B), REvInv A B d1 d2 -> \n         rutt (sum_relE REvInv REvE) (sum_relAns REvAnsInv REvAns) (extract REvAnsInv d1 d2)\n            (bodies1 A d1) (bodies2 B d2) ).\n(*maybe rutt actually needs to be changed? the types seem a little too constrained here\n  if rutt took in a family of relations indexed by types? then there might be more hope *)\n\n\n\nInstance eq_itree_Proper {E1 E2 R1 R2} {R : itree E1 R1 -> itree E2 R2 -> Prop} :  Proper (@eq_itree E1 R1 R1 eq ==> @eq_itree E2 R2 R2 eq ==> flip impl) R.                                                           \nAdmitted. (* needs an axiom to prove this, can be more specific later, possibly even do some gpaco stuff, but for now I just\n             want to see how it works out *)\n\n\nLemma rutt_mrec_interp_mrec_aux:\n  forall (A : Type) (d1 : D1 A) (B : Type) \n    (d2 : D2 B)\n    (r : forall x x0 : Type, D1 x -> D2 x0 -> itree E x -> itree E x0 -> Prop),\n    (forall (A0 : Type) (init1 : D1 A0) (B0 : Type)\n       (init2 : D2 B0),\n        REvInv A0 B0 init1 init2 ->\n        r A0 B0 init1 init2 (mrec bodies1 init1) (mrec bodies2 init2)) ->\n    (forall (m1 : itree (D1 +' E) A) (m2 : itree (D2 +' E) B),\n        paco2\n          (rutt_ (sum_relE REvInv REvE) (sum_relAns REvAnsInv REvAns)\n                 (extract REvAnsInv d1 d2)) bot2 m1 m2 ->\n        r A B d1 d2 (interp_mrec bodies1 m1) (interp_mrec bodies2 m2)) ->\n    forall (m1 : itree (D1 +' E) A) (m2 : itree (D2 +' E) B),\n      paco2\n        (rutt_ (sum_relE REvInv REvE) (sum_relAns REvAnsInv REvAns)\n               (extract REvAnsInv d1 d2)) bot2 m1 m2 ->\n      paco6 (rutt6_ D1 D2 E E REvE REvAns REvAnsInv) r A B d1 d2\n            (interp_mrec bodies1 m1) (interp_mrec bodies2 m2).\nProof.\n  intros A d1 B d2 r. intros CIH1 CIH2 m1 m2 Hm.\n  punfold Hm. red in Hm. remember (observe m1) as x. remember (observe m2) as y.\n  hinduction Hm before r; intros; use_simpobs.\n  - rewrite Heqx, Heqy. setoid_rewrite unfold_iter. cbn. setoid_rewrite bind_ret_l.\n    pstep. constructor; auto.\n  - pclearbot. rewrite Heqx, Heqy. setoid_rewrite unfold_iter.\n    cbn. setoid_rewrite bind_ret_l. pstep. constructor. right.\n    eapply CIH2; eauto.\n  - rewrite Heqx, Heqy. inversion H; inj_existT; subst.\n    + setoid_rewrite unfold_iter. cbn.\n      setoid_rewrite bind_ret_l. pstep. constructor. right. eapply CIH2.\n      eapply rutt_bind; eauto.\n      intros. red in H1.\n      eapply sum_relEAns_inl in H1. apply H0 in H1. pclearbot. auto.\n    + setoid_rewrite unfold_iter. cbn.\n      setoid_rewrite bind_vis. setoid_rewrite bind_ret_l.\n      pstep. constructor; auto. intros. left. pstep. constructor.\n      right. eapply CIH2; eauto. \n      assert (sum_relAns REvAnsInv REvAns A0 B0 (inr1 f1) c (inr1 f2) d). constructor. auto.\n      apply H0 in H2. pclearbot. auto.\n  - rewrite Heqx. setoid_rewrite unfold_iter at 1. cbn. setoid_rewrite bind_ret_l.\n    pstep. constructor. pstep_reverse.\n  - rewrite Heqy. setoid_rewrite unfold_iter at 2. cbn. setoid_rewrite bind_ret_l.\n    pstep. constructor. pstep_reverse.\nQed.\n\nTheorem rutt_mrec : \n  forall A B (init1 : D1 A) (init2 : D2 B), \n    REvInv A B init1 init2 -> rutt REvE REvAns (extract REvAnsInv init1 init2)\n         (mrec bodies1 init1) (mrec bodies2 init2).\nProof.\n  intros. apply rutt6_to_rutt. generalize dependent B. generalize dependent A.\n  pcofix CIH. unfold mrec. intros A d1 B d2 Hd12.\n  specialize (Hbodies A B d1 d2 Hd12) as Hbodiesd.\n  punfold Hbodiesd. red in Hbodiesd. remember (observe (bodies1 A d1)) as x.\n  remember (observe (bodies2 B d2)) as y. hinduction Hbodiesd before r; intros; use_simpobs; pclearbot.\n  - rewrite Heqx, Heqy. unfold interp_mrec. setoid_rewrite unfold_iter. setoid_rewrite bind_ret_l. \n    pstep. constructor. auto.\n  - rewrite Heqx, Heqy. \n    unfold interp_mrec at 1. rewrite unfold_iter. cbn. rewrite bind_ret_l.\n    fold (interp_mrec bodies1 m1).\n    unfold interp_mrec at 2. rewrite unfold_iter. cbn. rewrite bind_ret_l.\n    fold (interp_mrec bodies2 m2). pstep. constructor. left. \n    clear Heqx Heqy. generalize dependent m2. revert m1.\n    pcofix CIH'. eapply rutt_mrec_interp_mrec_aux; eauto.\n  - (* this may be set up wrong*)\n    assert (Vis e1 k1 ≅ bind (trigger e1) k1 ). setoid_rewrite bind_trigger. reflexivity.\n    assert (Vis e2 k2 ≅ bind (trigger e2) k2 ). setoid_rewrite bind_trigger. reflexivity.\n    rewrite Heqx, Heqy. rewrite H1, H2. setoid_rewrite interp_mrec_bind. inversion H; inj_existT; subst; pclearbot.\n    + (*interp_mrec_trigger   : interp_mrec ctx (ITree.trigger a) ≳ mrecursive ctx U a *)\n      unfold interp_mrec at 1. rewrite unfold_iter. cbn. setoid_rewrite bind_ret_l. rewrite bind_tau.\n      fold (interp_mrec bodies1  (ITree.bind (bodies1 A0 e0) (fun x : A0 => Ret x))).\n      setoid_rewrite <- interp_mrec_bind.\n      unfold interp_mrec at 2. rewrite unfold_iter. cbn. rewrite bind_ret_l. setoid_rewrite bind_ret_l.\n      fold (interp_mrec bodies2  (ITree.bind (bodies2 _ e3) (fun x => k2 x))). setoid_rewrite bind_ret_r.\n      pstep. constructor. left. \n      assert (Hb12 : rutt (sum_relE REvInv REvE)\n               (sum_relAns REvAnsInv REvAns)\n               (extract REvAnsInv d1 d2) (ITree.bind (bodies1 A0 e0) k1) (ITree.bind (bodies2 B0 e3) k2)).\n      { \n        eapply rutt_bind; eauto.\n        intros. red in H3. eapply sum_relEAns_inl in H3. apply H0 in H3.\n        pclearbot. auto.\n      }\n      remember (ITree.bind (bodies1 A0 e0) k1) as t1.\n      remember (ITree.bind (bodies2 B0 e3) k2) as t2. clear Heqt1 Heqt2.\n      generalize dependent t2. generalize dependent t1. pcofix CIH'.\n      eapply rutt_mrec_interp_mrec_aux; eauto.\n    + unfold interp_mrec at 1. rewrite unfold_iter. cbn. rewrite bind_vis. setoid_rewrite bind_ret_l. \n      rewrite bind_vis. setoid_rewrite unfold_iter at 1. cbn. setoid_rewrite bind_ret_l.\n      setoid_rewrite bind_tau. setoid_rewrite bind_ret_l. \n      unfold interp_mrec at 2. rewrite unfold_iter. cbn. rewrite bind_vis. setoid_rewrite bind_ret_l. \n      rewrite bind_vis. setoid_rewrite unfold_iter at 2. cbn. setoid_rewrite bind_ret_l.\n      setoid_rewrite bind_tau. setoid_rewrite bind_ret_l. pstep. constructor; auto.\n      intros. left. pstep. constructor. left.\n      assert (Hcd : sum_relAns REvAnsInv REvAns _ _ (inr1 f1) c (inr1 f2) d). econstructor. auto.\n      apply H0 in Hcd. pclearbot. remember (k1 c) as kc. remember (k2 d) as kd.\n      clear Heqkc Heqkd. generalize dependent kd. revert kc. pcofix CIH.\n      eapply rutt_mrec_interp_mrec_aux; eauto.\n  - rewrite Heqx. \n    unfold interp_mrec at 1. rewrite unfold_iter. cbn. rewrite bind_ret_l.\n    fold (interp_mrec bodies1 t1). pstep. constructor. pstep_reverse. \n    assert (Htd2 : rutt (sum_relE REvInv REvE)\n               (sum_relAns REvAnsInv REvAns)\n               (extract REvAnsInv d1 d2) t1 (bodies2 B d2) ).\n    {\n      apply Hbodies in Hd12.\n      assert (bodies1 A d1 ≈ t1). rewrite Heqx, tau_eutt. reflexivity. rewrite <- H. auto.\n    }\n    remember (bodies2 B d2) as t2. clear Heqx Heqy Heqt2 IHHbodiesd Hbodiesd. generalize dependent t2. generalize dependent t1.\n    pcofix CIH. intros. eapply rutt_mrec_interp_mrec_aux; eauto.\n  - rewrite Heqy. \n    unfold interp_mrec at 2. rewrite unfold_iter. cbn. rewrite bind_ret_l.\n    fold (interp_mrec bodies2 t2). pstep. constructor. pstep_reverse. \n    assert (Htd2 : rutt (sum_relE REvInv REvE)\n               (sum_relAns REvAnsInv REvAns)\n               (extract REvAnsInv d1 d2) (bodies1 A d1) t2 ).\n    {\n      apply Hbodies in Hd12.\n      assert (bodies2 _ d2 ≈ t2). rewrite Heqy, tau_eutt. reflexivity. rewrite <- H. auto.\n    }\n    remember (bodies1 _ d1) as t1. clear Heqx Heqy Heqt1 IHHbodiesd Hbodiesd. generalize dependent t2. generalize dependent t1.\n    pcofix CIH. intros. eapply rutt_mrec_interp_mrec_aux; eauto.\nQed.\n\nEnd MRec.\n\nTheorem eutt_mrec (E D1 D2 : Type -> Type) \n        (REvInv : relationEH D1 D2)  (REvAnsInv : forall A B : Type, D1 A -> A -> D2 B -> B -> Prop)\n        (bodies1 : D1 ~> itree (D1 +' E) ) (bodies2 : D2 ~> itree (D2 +' E) ) :\n  ( forall A B (d1 : D1 A) (d2 : D2 B), REvInv A B d1 d2 -> \n                                   rutt (sum_relE REvInv EvEq) (sum_relAns REvAnsInv EvEqAns) (extract REvAnsInv d1 d2)\n                                        (bodies1 A d1) (bodies2 B d2) ) ->\n  forall A B (init1 : D1 A) (init2 : D2 B) , \n    REvInv A B init1 init2 -> eutt (extract REvAnsInv init1 init2)\n         (mrec bodies1 init1) (mrec bodies2 init2).\nProof.\n  intros.\n  apply rutt_to_eutt. eapply rutt_mrec; eauto.\nQed.\n\n\nSection MrecTauTest.\n\n  Variant BoolRec : Type -> Type :=\n    boolrec : BoolRec bool.\n\n  Definition bodies1 (A : Type) (b : BoolRec A) : itree (BoolRec +' BoolRec)  A.\n    destruct b. apply (Ret false).\n  Defined.\n\n  Definition bodies2 (A : Type) (b : BoolRec A) : itree (BoolRec +' BoolRec) A.\n    destruct b. apply (Vis (inr1 boolrec) (fun b => Ret b)).\n  Defined.\n  \n\n  Goal mrec bodies1 boolrec ≅ (Ret false).\n    Proof.\n      unfold mrec, interp_mrec. rewrite unfold_iter. cbn. rewrite bind_ret_l.\n      reflexivity.\n    Qed.\n\n  Goal mrec bodies2 boolrec ≅ ((Vis (boolrec) (fun b => Tau (Ret b)))).\n  Proof.\n    setoid_rewrite unfold_iter. cbn. rewrite bind_vis.\n    setoid_rewrite bind_ret_l. setoid_rewrite unfold_iter. cbn.\n    setoid_rewrite bind_ret_l. reflexivity.\n  Qed.\n\n  (*\n    Ret false <= Vis exists (fun b => Ret b)\n\n\n    ~ Ret false <= Vis exists (fun b => Tau (Ret b)) \n\n    ~ Ret false <= Tau (Ret false)\n\n   *)\n\n  (*this demonstrates that extra taus get in which is why I need a solution to the eutt \n    problem, the thing is that it is not clear what that problem would be\n    the saturated thing sounds like a good idea but I looked at the proof and don't see \n    where it helps, suggesting there may be other counter examples\n   *)\n\nEnd MrecTauTest.\n", "meta": {"author": "lag47", "repo": "mrec", "sha": "e657c074205e423c300e7222189435f4ccc6206b", "save_path": "github-repos/coq/lag47-mrec", "path": "github-repos/coq/lag47-mrec/mrec-e657c074205e423c300e7222189435f4ccc6206b/theories/RuttFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.26975442221551515}}
{"text": "Set Implicit Arguments.\n\nRequire Import Platform.Cito.FreeVars.\nRequire Import Bedrock.StringSet.\nImport StringSet.\nRequire Import Platform.Cito.StringSetFacts.\n\nDefinition get_local_vars stmt arg_vars ret_var :=\n  elements (diff (add ret_var (free_vars stmt)) (of_list arg_vars)).\n\nRequire Import Platform.Cito.SetoidListFacts.\nRequire Import Platform.Cito.GeneralTactics2.\n\nLemma ret_in_vars : forall arg_vars s r, List.In r (arg_vars ++ get_local_vars s arg_vars r).\n  intros; apply List.in_or_app.\n  destruct (List.In_dec String.string_dec r arg_vars); try solve [intuition]; intros.\n  right.\n  unfold get_local_vars; simpl.\n  eapply InA_eq_In_iff.\n  eapply elements_1.\n  eapply diff_iff.\n  split.\n  eapply add_iff; eauto.\n  not_not.\n  eapply of_list_spec; eauto.\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/Cito/GetLocalVars.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2697544222155151}}
{"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 of parallel moves into sequences of individual moves.\n\n  In this file, we adapt the generic \"parallel move\" algorithm\n  (developed and proved correct in module [Parmov]) to the idiosyncraties\n  of the [LTLin] and [Linear] intermediate languages.  While the generic\n  algorithm assumes that registers never overlap, the locations\n  used in [LTLin] and [Linear] can overlap, and assigning one location\n  can set the values of other, overlapping locations to [Vundef].\n  We address this issue in the remainder of this file.\n*)\n\nRequire Import Coqlib.\nRequire Parmov.\nRequire Import Values.\nRequire Import Events.\nRequire Import AST.\nRequire Import Locations.\nRequire Import Conventions.\n\n(** * Instantiating the generic parallel move algorithm *)\n\n(** The temporary location to use for a move is determined\n  by the type of the data being moved: register [IT2] for an\n  integer datum, and register [FT2] for a floating-point datum. *)\n\nDefinition temp_for (l: loc) : loc :=\n  match Loc.type l with Tint => R IT2 | Tfloat => R FT2 end.\n\nDefinition parmove (srcs dsts: list loc) :=\n  Parmov.parmove2 loc Loc.eq temp_for srcs dsts.\n\nDefinition moves := (list (loc * loc))%type.\n\n(** [exec_seq m] gives semantics to a sequence of elementary moves.\n  This semantics ignores the possibility of overlap: only the\n  target locations are updated, but the locations they\n  overlap with are not set to [Vundef].  See [effect_seqmove] below\n  for a semantics that accounts for overlaps. *)\n\nDefinition exec_seq (m: moves) (e: Locmap.t) : Locmap.t :=\n  Parmov.exec_seq loc Loc.eq val m e.\n  \nLemma temp_for_charact:\n  forall l, temp_for l = R IT2 \\/ temp_for l = R FT2.\nProof.\n  intro; unfold temp_for. destruct (Loc.type l); tauto.\nQed.\n\nLemma is_not_temp_charact:\n  forall l,\n  Parmov.is_not_temp loc temp_for l <-> l <> R IT2 /\\ l <> R FT2.\nProof.\n  intros. unfold Parmov.is_not_temp. \n  destruct (Loc.eq l (R IT2)). \n  subst l. intuition. apply (H (R IT2)). reflexivity. discriminate.\n  destruct (Loc.eq l (R FT2)).\n  subst l. intuition. apply (H (R FT2)). reflexivity. \n  assert (forall d, l <> temp_for d). \n    intro. elim (temp_for_charact d); congruence.\n  intuition. \nQed.\n\nLemma disjoint_temp_not_temp:\n  forall l, Loc.notin l temporaries -> Parmov.is_not_temp loc temp_for l.\nProof.\n  intros. rewrite is_not_temp_charact. \n  unfold temporaries in H; simpl in H. \n  split; apply Loc.diff_not_eq; tauto.\nQed.\n\nLemma loc_norepet_norepet:\n  forall l, Loc.norepet l -> list_norepet l.\nProof.\n  induction 1; constructor. \n  apply Loc.notin_not_in; auto. auto.\nQed.\n\n(** Instantiating the theorems proved in [Parmov], we obtain\n  the following properties of semantic correctness and well-typedness\n  of the generated sequence of moves.  Note that the semantic\n  correctness result is stated in terms of the [exec_seq] semantics,\n  and therefore does not account for overlap between locations. *)\n\nLemma parmove_prop_1:\n  forall srcs dsts,\n  List.length srcs = List.length dsts ->\n  Loc.norepet dsts ->\n  Loc.disjoint srcs temporaries ->\n  Loc.disjoint dsts temporaries ->\n  forall e,\n  let e' := exec_seq (parmove srcs dsts) e in\n  List.map e' dsts = List.map e srcs /\\\n  forall l, ~In l dsts -> l <> R IT2 -> l <> R FT2 -> e' l = e l.\nProof.\n  intros. \n  assert (NR: list_norepet dsts) by (apply loc_norepet_norepet; auto).\n  assert (NTS: forall r, In r srcs -> Parmov.is_not_temp loc temp_for r).\n    intros. apply disjoint_temp_not_temp. apply Loc.disjoint_notin with srcs; auto.\n  assert (NTD: forall r, In r dsts -> Parmov.is_not_temp loc temp_for r).\n    intros. apply disjoint_temp_not_temp. apply Loc.disjoint_notin with dsts; auto.\n  generalize (Parmov.parmove2_correctness loc Loc.eq temp_for val srcs dsts H NR NTS NTD e).\n  change (Parmov.exec_seq loc Loc.eq val (Parmov.parmove2 loc Loc.eq temp_for srcs dsts) e) with e'.\n  intros [A B].\n  split. auto. intros. apply B. auto. rewrite is_not_temp_charact; auto.\nQed.\n\nLemma parmove_prop_2:\n  forall srcs dsts s d,\n  In (s, d) (parmove srcs dsts) ->\n     (In s srcs \\/ s = R IT2 \\/ s = R FT2)\n  /\\ (In d dsts \\/ d = R IT2 \\/ d = R FT2).\nProof.\n  intros srcs dsts.\n  set (mu := List.combine srcs dsts).\n  assert (forall s d, Parmov.wf_move loc temp_for mu s d ->\n            (In s srcs \\/ s = R IT2 \\/ s = R FT2)\n         /\\ (In d dsts \\/ d = R IT2 \\/ d = R FT2)).\n  unfold mu; induction 1. \n  split. \n    left. eapply List.in_combine_l; eauto.\n    left. eapply List.in_combine_r; eauto.\n  split. \n    right. apply temp_for_charact. \n    tauto.\n  split.\n    tauto.\n    right. apply temp_for_charact.\n  intros. apply H. \n  apply (Parmov.parmove2_wf_moves loc Loc.eq temp_for srcs dsts s d H0). \nQed.\n\nLemma loc_type_temp_for:\n  forall l, Loc.type (temp_for l) = Loc.type l.\nProof.\n  intros; unfold temp_for. destruct (Loc.type l); reflexivity. \nQed.\n\nLemma loc_type_combine:\n  forall srcs dsts,\n  List.map Loc.type srcs = List.map Loc.type dsts ->\n  forall s d,\n  In (s, d) (List.combine srcs dsts) ->\n  Loc.type s = Loc.type d.\nProof.\n  induction srcs; destruct dsts; simpl; intros; try discriminate.\n  elim H0.\n  elim H0; intros. inversion H1; subst. congruence.\n  apply IHsrcs with dsts. congruence. auto.\nQed.\n\nLemma parmove_prop_3:\n  forall srcs dsts,\n  List.map Loc.type srcs = List.map Loc.type dsts ->\n  forall s d,\n  In (s, d) (parmove srcs dsts) -> Loc.type s = Loc.type d.\nProof.\n  intros srcs dsts TYP.\n  set (mu := List.combine srcs dsts).\n  assert (forall s d, Parmov.wf_move loc temp_for mu s d ->\n            Loc.type s = Loc.type d).\n  unfold mu; induction 1. \n  eapply loc_type_combine; eauto.\n  rewrite loc_type_temp_for; auto.\n  rewrite loc_type_temp_for; auto.\n  intros. apply H. \n  apply (Parmov.parmove2_wf_moves loc Loc.eq temp_for srcs dsts s d H0). \nQed.\n\n(** * Accounting for overlap between locations *)\n\nSection EQUIVALENCE.\n\n(** We now prove the correctness of the generated sequence of elementary\n  moves, accounting for possible overlap between locations.\n  The proof is conducted under the following hypotheses: there must\n  be no partial overlap between\n- two distinct destinations (hypothesis [NOREPET]);\n- a source location and a destination location (hypothesis [NO_OVERLAP]).\n*)\n\nVariables srcs dsts: list loc.\nHypothesis LENGTH: List.length srcs = List.length dsts.\nHypothesis NOREPET: Loc.norepet dsts.\nHypothesis NO_OVERLAP: Loc.no_overlap srcs dsts.\nHypothesis NO_SRCS_TEMP: Loc.disjoint srcs temporaries.\nHypothesis NO_DSTS_TEMP: Loc.disjoint dsts temporaries.\n\n(** [no_overlap_dests l] holds if location [l] does not partially overlap\n  a destination location: either it is identical to one of the\n  destinations, or it is disjoint from all destinations. *)\n\nDefinition no_overlap_dests (l: loc) : Prop :=\n  forall d, In d dsts -> l = d \\/ Loc.diff l d.\n\n(** We show that [no_overlap_dests] holds for any destination location\n  and for any source location. *)\n\nLemma dests_no_overlap_dests:\n  forall l, In l dsts -> no_overlap_dests l.\nProof.\n  assert (forall d, Loc.norepet d ->\n          forall l1 l2, In l1 d -> In l2 d -> l1 = l2 \\/ Loc.diff l1 l2).\n  induction 1; simpl; intros.\n  contradiction.\n  elim H1; intro; elim H2; intro.\n  left; congruence.\n  right. subst l1. eapply Loc.in_notin_diff; eauto.\n  right. subst l2. apply Loc.diff_sym. eapply Loc.in_notin_diff; eauto.\n  eauto.\n  intros; red; intros. eauto. \nQed.\n\nLemma notin_dests_no_overlap_dests:\n  forall l, Loc.notin l dsts -> no_overlap_dests l.\nProof.\n  intros; red; intros.\n  right. eapply Loc.in_notin_diff; eauto.\nQed.\n\nLemma source_no_overlap_dests:\n  forall s, In s srcs \\/ s = R IT2 \\/ s = R FT2 -> no_overlap_dests s.\nProof.\n  intros. elim H; intro. exact (NO_OVERLAP s H0). \n  elim H0; intro; subst s; red; intros;\n  right; apply Loc.diff_sym; apply NO_DSTS_TEMP; auto; simpl; tauto.\nQed.\n\nLemma source_not_temp1:\n  forall s, In s srcs \\/ s = R IT2 \\/ s = R FT2 -> \n  Loc.diff s (R IT1) /\\ Loc.diff s (R FT1) /\\ Loc.notin s destroyed_at_move.\nProof.\n  intros. destruct H.\n  exploit Loc.disjoint_notin. eexact NO_SRCS_TEMP. eauto. \n  simpl; tauto.\n  destruct H; subst s; simpl; intuition congruence.\nQed.\n\nLemma dest_noteq_diff:\n  forall d l, \n  In d dsts \\/ d = R IT2 \\/ d = R FT2 ->\n  l <> d ->\n  no_overlap_dests l ->\n  Loc.diff l d.\nProof.\n  intros. elim H; intro.\n  elim (H1 d H2); intro. congruence. auto.\n  assert (forall r, l <> R r -> Loc.diff l (R r)).\n    intros. destruct l; simpl. congruence. destruct s; auto.\n  elim H2; intro; subst d; auto.\nQed.\n\n(** [locmap_equiv e1 e2] holds if the location maps [e1] and [e2]\n  assign the same values to all locations except temporaries [IT1], [FT1]\n  and except locations that partially overlap a destination. *)\n\nDefinition locmap_equiv (e1 e2: Locmap.t): Prop :=\n  forall l,\n  no_overlap_dests l -> Loc.diff l (R IT1) -> Loc.diff l (R FT1) -> Loc.notin l destroyed_at_move -> e2 l = e1 l.\n\n(** The following predicates characterize the effect of one move\n  move ([effect_move]) and of a sequence of elementary moves\n  ([effect_seqmove]).  We allow the code generated for one move\n  to use the temporaries [IT1] and [FT1] and [destroyed_at_move] in any way it needs. *)\n\nDefinition effect_move (src dst: loc) (e e': Locmap.t): Prop :=\n  e' dst = e src /\\\n  forall l, Loc.diff l dst -> Loc.diff l (R IT1) -> Loc.diff l (R FT1) -> Loc.notin l destroyed_at_move -> e' l = e l.\n\nInductive effect_seqmove: list (loc * loc) -> Locmap.t -> Locmap.t -> Prop :=\n  | effect_seqmove_nil: forall e,\n      effect_seqmove nil e e\n  | effect_seqmove_cons: forall s d m e1 e2 e3,\n      effect_move s d e1 e2 ->\n      effect_seqmove m e2 e3 ->\n      effect_seqmove ((s, d) :: m) e1 e3.\n\n(** The following crucial lemma shows that [locmap_equiv] is preserved\n  by executing one move [d <- s], once using the [effect_move]\n  predicate that accounts for partial overlap and the use of\n  temporaries [IT1], [FT1], or via the [Parmov.update] function that\n  does not account for any of these. *)\n\nLemma effect_move_equiv:\n  forall s d e1 e2 e1',\n  (In s srcs \\/ s = R IT2 \\/ s = R FT2) ->\n  (In d dsts \\/ d = R IT2 \\/ d = R FT2) ->\n  locmap_equiv e1 e2 -> effect_move s d e1 e1' ->\n  locmap_equiv e1' (Parmov.update loc Loc.eq val d (e2 s) e2).\nProof.\n  intros. destruct H2. red; intros. \n  unfold Parmov.update. destruct (Loc.eq l d). \n  subst l. destruct (source_not_temp1 _ H) as [A [B C]]. \n  rewrite H2. apply H1; auto. apply source_no_overlap_dests; auto.\n  rewrite H3; auto. apply dest_noteq_diff; auto. \nQed.\n\n(** We then extend the previous lemma to a sequence [mu] of elementary moves.\n*)\n\nLemma effect_seqmove_equiv:\n  forall mu e1 e1',\n  effect_seqmove mu e1 e1' ->\n  forall e2,\n  (forall s d, In (s, d) mu ->\n     (In s srcs \\/ s = R IT2 \\/ s = R FT2) /\\\n     (In d dsts \\/ d = R IT2 \\/ d = R FT2)) ->\n  locmap_equiv e1 e2 ->\n  locmap_equiv e1' (exec_seq mu e2).\nProof.\n  induction 1; intros.\n  simpl. auto.\n  simpl. apply IHeffect_seqmove. \n  intros. apply H1. apply in_cons; auto. \n  destruct (H1 s d (in_eq _ _)).\n  eapply effect_move_equiv; eauto. \nQed.\n\n(** Here is the main result in this file: executing the sequence\n  of moves returned by the [parmove] function results in the\n  desired state for locations: the final values of destination locations\n  are the initial values of source locations, and all locations\n  that are disjoint from the temporaries and the destinations\n  keep their initial values. *)\n\nLemma effect_parmove:\n  forall e e',\n  effect_seqmove (parmove srcs dsts) e e' ->\n  List.map e' dsts = List.map e srcs /\\\n  forall l, Loc.notin l dsts -> Loc.notin l temporaries -> e' l = e l.\nProof.\n  set (mu := parmove srcs dsts). intros.\n  assert (locmap_equiv e e) by (red; auto).\n  generalize (effect_seqmove_equiv mu e e' H e (parmove_prop_2 srcs dsts) H0).\n  intro. \n  generalize (parmove_prop_1 srcs dsts LENGTH NOREPET NO_SRCS_TEMP NO_DSTS_TEMP e).\n  fold mu. intros [A B]. \n  (* e' dsts = e srcs *)\n  split. rewrite <- A. apply list_map_exten; intros.\n  exploit Loc.disjoint_notin. eexact NO_DSTS_TEMP. eauto. simpl; intros.\n  apply H1. apply dests_no_overlap_dests; auto.\n  tauto. tauto. simpl; tauto. \n  (* other locations *)\n  intros. transitivity (exec_seq mu e l). \n  symmetry. apply H1. apply notin_dests_no_overlap_dests; auto.\n  eapply Loc.in_notin_diff; eauto. simpl; tauto.\n  eapply Loc.in_notin_diff; eauto. simpl; tauto.\n  simpl in H3; simpl; tauto.\n  apply B. apply Loc.notin_not_in; auto.\n  apply Loc.diff_not_eq. eapply Loc.in_notin_diff; eauto. simpl; tauto.\n  apply Loc.diff_not_eq. eapply Loc.in_notin_diff; eauto. simpl; tauto.\nQed.\n\nEnd EQUIVALENCE.\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/backend/Parallelmove.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2697544222155151}}
{"text": "(**********************************************************************)\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 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(* 021101301 USA                                                     *)\n(**********************************************************************)\n\n(**********************************************************************)\n(*                        Case.v                                      *)\n(*                                                                    *)\n(*                     Barry Jay                                      *)\n(*                                                                    *)\n(**********************************************************************)\n\n\nRequire Import Omega Max Bool List.\nRequire Import IntensionalLib.SF_calculus.Test.  \nRequire Import IntensionalLib.SF_calculus.General.  \nRequire Import IntensionalLib.Tree_calculus.Tree_Terms.  \nRequire Import IntensionalLib.Tree_calculus.Tree_Tactics.  \nRequire Import IntensionalLib.Tree_calculus.Tree_reduction.  \nRequire Import IntensionalLib.Tree_calculus.Tree_Normal.  \nRequire Import IntensionalLib.Tree_calculus.Tree_Closed.  \nRequire Import IntensionalLib.Tree_calculus.Substitution.  \nRequire Import IntensionalLib.Tree_calculus.Tree_Eval.  \nRequire Import IntensionalLib.Tree_calculus.Star.  \nRequire Import IntensionalLib.Tree_calculus.Wait.  \nRequire Import IntensionalLib.Tree_calculus.Fixpoints.  \nRequire Import IntensionalLib.Tree_calculus.Wave_Factor.  \nRequire Import IntensionalLib.Tree_calculus.Wave_Factor2.  \nRequire Import IntensionalLib.Tree_calculus.Equal.  \n\nLemma aux1: forall p q, S(S(S(S(S p)))) <= q ->\n                        pred (pred (pred (q - S p))) = q - S (S (S (S p))). \n  intros.\n  replace (pred (q - S p)) with (q - (S (S p)))  by omega.\n  replace (pred (q - S(S p))) with (q - (S (S (S p))))  by omega.\nomega.\nQed.\n\nLemma aux3 : forall M, pred (max match maxvar (lift 1 M) with\n             | 0 => 1\n             | S m' => S m'\n             end 1) = maxvar M - 0. \nProof.\nintros. rewrite max_pred. simpl. rewrite max_zero. \n  replace (maxvar M - 0) with (maxvar M) by omega.\nassert(maxvar M = 0 \\/ maxvar M <> 0) by decide equality. \ninversion H. unfold lift; rewrite lift_rec_closed. rewrite H0; auto. auto. \nclear H. \nassert(maxvar (lift 1 M) = S(maxvar M)). \ninduction M; split_all. gen_case H0 n. \nsimpl in *. noway.  \nsimpl in *. \nassert (maxvar M1 = 0 -> maxvar (lift_rec M1 0 1) = 0) by (split_all; rewrite lift_rec_closed; auto).\n\ngen3_case H0 H IHM1  (maxvar M1) . rewrite H; auto. \nunfold lift in *; rewrite IHM1; auto. \nassert (maxvar M2 = 0 -> maxvar (lift_rec M2 0 1) = 0) by (split_all; rewrite lift_rec_closed; auto).\ngen3_case H0 H1 IHM2  (maxvar M2) . rewrite H1; auto. \nrewrite IHM2; auto. \nrewrite H. auto. \nQed. \n\nLemma max_aux: forall m n, max m n = m \\/ max m n = n . \nProof. \ninduction m; split_all. induction n; split_all. \nassert(max m n = m \\/ max m n = n) by eapply2 IHm. \ninversion H; rewrite H0; auto. \nQed. \n\nLemma maxvar_lift_rec_compare: \nforall M p  n k, p>= maxvar M  -> p+k >= maxvar (lift_rec M n k).\nProof.\ninduction M; split_all. \nunfold relocate. elim(test n0 n); split_all.  omega. omega. omega. \nelim(max_is_max (maxvar M1) (maxvar M2)). intros. \neapply2 max_max2. \neapply2 IHM1. omega. \neapply2 IHM2. omega. \nQed. \n\n\nLemma lift_rec_misses: \nforall M n k, n >= maxvar M  -> lift_rec M n k = M. \nProof.\ninduction M; split_all. relocate_lt. auto. \nassert(max (maxvar M1) (maxvar M2) >= maxvar M1 /\\ max (maxvar M1) (maxvar M2) >= maxvar M2)\nby eapply2 max_is_max. split_all. \nrewrite IHM1; try omega. rewrite IHM2; auto; omega. \nQed.\n \nLemma maxvar_lift_rec_compare2: \nforall M N n k, maxvar M >= maxvar N -> maxvar (lift_rec M n k) >= maxvar (lift_rec N n k). \nProof.\ninduction M; split_all. \ngen_case H N.\n(* 5 *)  \nunfold relocate. elim(test n0 n); split_all. elim(test n0 n1); split_all; try noway. \nomega. omega. elim(test n0 n1); split_all; try noway. \n(* 4 *) \nomega. \n(* 3 *) \nunfold relocate. elim(test n0 n); split_all. \nassert(max (maxvar t) (maxvar t0) >= maxvar t /\\ max (maxvar t) (maxvar t0) >= maxvar t0) by eapply2 max_is_max. \nsplit_all. \nreplace (S(k+n)) with (S n + k) by omega. \neapply2 max_max2; eapply2 maxvar_lift_rec_compare; omega. \nassert(max (maxvar t) (maxvar t0) >= maxvar t /\\ max (maxvar t) (maxvar t0) >= maxvar t0) by eapply2 max_is_max. \nsplit_all. \nrewrite ! lift_rec_misses; try omega. \n(* 2 *) \nrewrite lift_rec_closed; auto. omega. \n(* 1 *) \nassert(max (maxvar M1) (maxvar M2)  = maxvar M1 \\/ \nmax (maxvar M1) (maxvar M2) = maxvar M2) by eapply2 max_aux. \nassert(max (maxvar (lift_rec M1 n k)) (maxvar (lift_rec M2 n k)) >=(maxvar (lift_rec M1 n k)) /\\ \nmax (maxvar (lift_rec M1 n k)) (maxvar (lift_rec M2 n k)) >=(maxvar (lift_rec M2 n k)))\nby eapply2 max_is_max. \nsplit_all. inversion H0. \nassert(maxvar (lift_rec M1 n k) >= maxvar (lift_rec N n k)). eapply2 IHM1; omega.  omega. \nassert(maxvar (lift_rec M2 n k) >= maxvar (lift_rec N n k)). eapply2 IHM2; omega.  omega. \nQed. \n\nLemma aux4 : forall M p,\n     match\n       pred\n         (pred\n            (maxvar (lift_rec M p 3) - p))\n     with\n     | 0 => 0\n     | S m' => m'\n     end = maxvar M - p\n.\nProof.\ninduction M; split_all.\n(* 2 *) \n case p; split_all. relocate_lt. \nsimpl. auto. \nunfold relocate. \nelim(test (S n0) n); split_all. \n(* 3 *) \ngen_case a n0. omega. \ngen_case a n1. gen_case a n. omega. \ngen_case a n2. gen_case a n. gen_case a n3. omega. \nunfold minus at 2; fold minus. \nassert(forall m n, m - (S n) = pred (m-n)) by (intros; omega). \nrewrite ! H. unfold pred at 3;  auto.\ncase (pred(pred (n-n3))); auto.  \n(* 2 *) \nassert(pred(pred(n-n0)) = 0) by omega. \nrewrite H. omega. \n(* 1 *) \nassert(max (maxvar M1) (maxvar M2) = maxvar M1 \\/ max (maxvar M1) (maxvar M2) = maxvar M2) by \neapply2 max_aux. \ninversion H.  rewrite H0. \nassert( maxvar(lift_rec M1 p 3) >= max (maxvar (lift_rec M1 p 3)) (maxvar (lift_rec M2 p 3))).\neapply2 max_max2. eapply2 maxvar_lift_rec_compare2. \nassert(max (maxvar M1) (maxvar M2) >= maxvar M2) by eapply2 max_is_max. \nrewrite H0 in H1. auto. \nassert(max (maxvar (lift_rec M1 p 3)) (maxvar (lift_rec M2 p 3))>= maxvar(lift_rec M1 p 3))\nby eapply2 max_is_max. \nassert(max (maxvar (lift_rec M1 p 3)) (maxvar (lift_rec M2 p 3)) = maxvar(lift_rec M1 p 3))\nby omega. \nrewrite H3. eapply2 IHM1. \n(* 1 *) \nassert( maxvar(lift_rec M2 p 3) >= max (maxvar (lift_rec M1 p 3)) (maxvar (lift_rec M2 p 3))).\neapply2 max_max2. eapply2 maxvar_lift_rec_compare2. \nassert(max (maxvar M1) (maxvar M2) >= maxvar M1) by eapply2 max_is_max. \nrewrite H0 in H1. auto. \nassert(max (maxvar (lift_rec M1 p 3)) (maxvar (lift_rec M2 p 3))>= maxvar(lift_rec M2 p 3))\nby eapply2 max_is_max. \nassert(max (maxvar (lift_rec M1 p 3)) (maxvar (lift_rec M2 p 3)) = maxvar(lift_rec M2 p 3))\nby omega. \nrewrite H3. rewrite H0. eapply2 IHM2. \nQed. \n\n\n\nDefinition swap M := App (App (Op Node) (App (Op Node) (App k_op M))) i_op.\n\nLemma swap_check : forall M N, sf_red (App (swap M) N) (App N M). \nProof. \nunfold swap; split_all; eval_tac. eval_tac.\neapply succ_red. eapply app_sf_red. eapply2 k_red.  eval_tac.  \neapply2 preserves_app_sf_red;  eval_tac. \nQed. \n\n(* \nLemma star_opt_swap : \nstar_opt (swap (Ref 0)) = App (App s_op (App k_op  (App s_op i_op ))) k_op .\nProof. split_all. Qed. \n*)\n\nDefinition case_app case (P1 P2 M : Tree) := \n(star_opt (App (App (App (App Fop (Ref 0)) i_op) \n                               (lift 1 (star_opt (star_opt (App (App (App (App \n                               (lift 2 (case P1 (case P2 (App k_op (App k_op M)))))\n                               (Ref 1)) \n                                                       (App k_op (App k_op (App k_op i_op))))\n                                                  (Ref 0))\n                                             (App k_op i_op)))))) \n               (swap (Ref 0)))).\n\nLtac occurs_true_tac M := \nrewrite (star_opt_occurs_true M) at 1;\n[| rewrite ! occurs_app; replace (occurs 0 (Ref 0)) with true by split_all; \nrewrite ? orb_true_r; auto | discriminate]. \n\nLtac occurs_false_tac M := \nrewrite (star_opt_occurs_false M) at 1; [| split_all]. \n\n(* restore \n\nDefinition s_op := \nstar_opt (star_opt (star_opt (App (App (Ref 2) (Ref 0)) \n                                  (App (Ref 1) (Ref 0))))).\n\n\nDefinition case_app_nf case (P1 P2 M: Tree) := \n(App\n        (App s_op\n           (App\n              (App s_op\n                 (App (App s_op Fop) (App k_op  i_op )))\n              (App k_op \n                 (App\n                    (App s_op\n                       (App (App s_op (App k_op  s_op))\n                          (App\n                             (App s_op\n                                (case P1\n                                   (case P2 (App k_op  (App k_op  M)))))\n                             (App k_op \n                                (App k_op \n                                   (App k_op  (App k_op  i_op )))))))\n                    (App k_op  (App k_op  (App k_op  i_op )))))))\n        (App (App s_op (App k_op  (App s_op i_op ))) k_op )). \n\nLemma case_app_val : \nforall case P1 P2 M, sf_red (case_app case P1 P2 M) (case_app_nf case P1 P2 M).\nProof. \nintros; unfold case_app. \nunfold star_opt at 3;  unfold occurs; fold occurs 0. \nunfold lift; rewrite ! occurs_lift_rec_zero. simpl. \nrewrite subst_rec_lift_rec; try omega. \nrewrite ! occurs_lift_rec_zero. simpl. \nunfold subst; rewrite subst_rec_lift_rec; try omega. \nrewrite ! occurs_lift_rec_zero. simpl. \nrewrite subst_rec_lift_rec; try omega. \nrewrite ! lift_rec_null. \neapply2 preserves_app_sf_red. \neapply2 zero_red. \nQed. \n \n\n*) \n\nLemma program_app: forall M N, program (App M N) -> program M /\\ program N.\nProof. \nunfold program; intros. inversion H. \nsimpl in *; max_out; inversion H0; split; split; auto. \nQed. \n\nFixpoint is_program M := \nmatch M with \n| Ref _ => false \n| Op _ => true \n| App (Op _) M2 => is_program M2 \n| App (App (Op _) M1) M2 => is_program M1 && is_program M2\n| _ => false \nend. \n \n\n\nLemma program_is_program: forall M, program M <-> is_program M = true. \nProof.\ninduction M; intros; auto.  \n(* 3 *) \n  split. unfold program. simpl. intro c; inversion c; discriminate. \ndiscriminate.\n(* 2 *) \nsplit; intro; unfold program; split; auto. \n(* 1 *) \ngen_case IHM1 M1. \n(* 3 *) \n  split. unfold program. simpl. intro c; inversion c.  \ngen_case H0 (maxvar M2); discriminate. \nintro; discriminate. \n(* 2 *) \nsplit. unfold program.  intro. inversion H. \neapply2 IHM2. inversion H0; simpl in H1. \nassert(status (App (Op o) M2) = Passive). \neapply2 closed_implies_passive. \nrewrite H7 in H6; discriminate. \nsplit; auto. \nintro.\nassert(program M2) by eapply2 IHM2. \n split; auto. nf_out. inversion H0; auto.  \ncase o; auto. simpl; inversion H0; auto. \n(* 1 *) \ngen_case IHM1 t. \n(* 3 *) \n  split. unfold program. simpl. intro c; inversion c.  \ngen_case H0 (maxvar t0); gen_case H0 (maxvar M2); discriminate. \nintro; discriminate. \n(* 2 *) \nsplit. unfold program.  intro. inversion H.\nassert(is_program t0 = true). \neapply2 IHM1.  split; auto. nf_out. \ninversion H0. \nassert(status (App (App (Op o) t0) M2) = Passive). \neapply2 closed_implies_passive. \nrewrite H7 in H6; discriminate. inversion H4; auto. case o; auto. \nsimpl in *; max_out. \nrewrite H2; simpl. eapply2 IHM2.\neapply2 (program_app (App (Op o) t0) M2).\nintro. \napply eq_sym in H. \nassert(true = is_program t0 /\\ true = is_program M2) by eapply2 andb_true_eq.\ninversion H0. \nassert(program M2) by eapply2 IHM2. \nassert(program (App (Op o) t0)) by eapply2 IHM1. \ninversion H3; inversion H4. inversion H7. \nsplit. \nnf_out. case o; auto. case o; auto. simpl in *. \nrewrite H6; rewrite H8; auto.\n split; auto. nf_out. case o; auto. \nsimpl in *. rewrite H6; rewrite H8; auto.\n(* 1 *) \ngen_case IHM1 t1. \n(* 3 *) \n  split. unfold program. simpl. intro c; inversion c.  \ngen_case H0 (maxvar t2); gen_case H0 (maxvar t0);  gen_case H0 (maxvar M2);  discriminate. \nintro; discriminate. \n(* 2 *) \nsplit. unfold program.  intro. inversion H. inversion H0. \nassert(status (App (App (App (Op o) t2) t0) M2) = Passive). \neapply2 closed_implies_passive. \nrewrite H7 in H6; discriminate. inversion H6. \nintro.  discriminate. \nsplit; intro. \ninversion H.  inversion H0. \nassert(status (App (App (App (App t3 t4) t2) t0) M2) = Passive). \neapply2 closed_implies_passive. \nrewrite H7 in H6; discriminate. inversion H6. \ndiscriminate.\nQed. \n \nFixpoint case P M := \n(* case P M is applied to the argument and then the default function.\n   The default function is either discared or swapped to the left. \n   Indices in P are renumbered, with binding from left to right \n*)   \n match P with\n  | Ref _ => star_opt (App k_op M)               \n  | Op _ => star_opt (App (App (App Fop (Ref 0)) (App k_op (lift 1 M))) \n                            (App k_op (App k_op (swap (Ref 0)))))\n  | App P1 P2 => \nif is_program P \nthen star_opt (App (App (App (App equal_comb (Ref 0)) P) (App k_op (lift 1 M))) (swap (Ref 0)))\nelse case_app case P1 P2 M            \n                end\n.\n\n\nLemma case_leaf: forall M R, sf_red (App (App (case (Op Node)M) (Op Node)) R) M.\nProof. \nintros; unfold case.  \neapply transitive_red. eapply preserves_app_sf_red. \neapply2 star_opt_beta. auto.  unfold_op. \nunfold subst; rewrite ! subst_rec_app. rewrite ! subst_rec_ref. \ninsert_Ref_out.\nrewrite ! (subst_rec_closed Fop). 2: simpl; auto. \nunfold lift;  rewrite subst_rec_lift_rec; try omega.\n rewrite ! lift_rec_null.\nrewrite ! (subst_rec_closed (Op Node)). 2: simpl; auto.\neapply transitive_red. eapply preserves_app_sf_red.\neapply2 factor_leaf.  auto. eval_tac. \nQed.   \n\nFixpoint pattern_size P :=\n  match P with\n    | Ref _ => 1\n    | Op _ => 0\n    | App P1 P2 => pattern_size P1 + (pattern_size P2)\n  end.\n\n\n\nLemma pattern_size_ref: forall i, pattern_size (Ref i) = 1.\nProof. auto. Qed. \n\n\n\nLemma pattern_size_app: forall M N, pattern_size (App M N) = pattern_size M + pattern_size N.\nProof. auto. Qed. \n\nLemma pattern_size_op: forall o, pattern_size (Op o) = 0.\nProof. auto. Qed. \n\n \n\nLemma lift_rec_preserves_pattern_size: forall M n k, pattern_size (lift_rec M n k) = pattern_size M. \nProof. induction M; split_all. Qed. \n\nLemma pattern_size_closed: forall M, maxvar M = 0 -> pattern_size M = 0. \nProof. induction M; split_all.  noway. rewrite IHM1; max_out; rewrite IHM2; max_out. Qed. \n\n(* restore ? \nLemma pattern_size_A_k : forall k, pattern_size (A_k k) = 0. \nProof. unfold A_k. intro. rewrite pattern_size_closed. auto. rewrite A_k_closed. auto. Qed. \n\nLemma pattern_size_omega_k : forall k, pattern_size (omega_k k) = 0. \nProof. unfold omega_k. intro. rewrite pattern_size_closed. auto. \nrewrite ? maxvar_star_opt. unfold maxvar; fold maxvar. \nrewrite?  maxvar_app_comb.   unfold maxvar; fold maxvar. rewrite A_k_closed.\nrewrite?  maxvar_app_comb.   unfold maxvar; fold maxvar. auto. \nQed. \n*)\n\nLemma pattern_size_lt_maxvar: forall P, maxvar P = 0 -> pattern_size P = 0. \nProof. induction P; split_all. omega.  max_out. Qed. \n\n\nLemma aux_lift_rec: forall M p n k, \nlift_rec (lift_rec M (p + n) k) p 3 = lift_rec (lift_rec (lift_rec M (p + n) k) p 2) (p+2) 1. \nProof. \nintros. rewrite (lift_rec_lift_rec (lift_rec M (p + n) k)); try omega. auto. \nQed. \n\nLemma lift_rec_preserves_case:\n  forall P M n k, lift_rec (case P M) n k = case P (lift_rec M (pattern_size P +n) k).\nProof.\n  induction P; intros. \n  (* 3 *)\n  unfold case, maxvar. rewrite lift_rec_preserves_star_opt. unfold_op. \n  unfold lift_rec; fold lift_rec.  unfold pattern_size. auto.\n  (* 2 *)\n    unfold case, maxvar, pattern_size, swap, lift_rec; fold lift_rec.\n  case o; unfold_op. \n    rewrite lift_rec_preserves_star_opt. \nunfold lift; rewrite ! lift_rec_app.\nrewrite (lift_rec_closed Fop). \n2: eapply2 Fop_closed.\nunfold lift_rec; fold lift_rec. relocate_lt.  \nunfold plus; fold plus. \nrewrite ! lift_lift_rec; try omega. auto. \n    (* 1 *) \n    unfold case; fold case. \nassert(is_program (App P1 P2) = true \\/ is_program (App P1 P2) <> true) by decide equality. \ninversion H. rewrite H0. \n(* 2 *) \nassert(program (App P1 P2)) by eapply2 program_is_program.  inversion H1.   \nrewrite lift_rec_preserves_star_opt. \nunfold swap; unfold_op. rewrite ! lift_rec_app. \nrewrite lift_rec_closed.\n2: eapply2 equal_comb_closed.  \nunfold lift_rec; fold lift_rec. relocate_lt.\nrewrite 2? lift_rec_closed. 2: simpl in H3; max_out. 2: simpl in H3; max_out. \nrewrite pattern_size_closed. \nunfold lift; rewrite lift_lift_rec; try omega. \nunfold plus; congruence.  auto. \n(* 1 *) \nassert(is_program (App P1 P2) = false).\neapply2 not_true_iff_false. \nrewrite H1. \n(* 1 *) \n    unfold case_app, swap, lift. unfold_op.\nrewrite lift_rec_preserves_star_opt.\nrewrite ! lift_rec_app. \nrewrite lift_rec_closed.\n2: eapply2 Fop_closed. \n  unfold lift_rec; fold lift_rec. relocate_lt. \nrewrite ! lift_rec_preserves_star_opt.\nrewrite ! lift_rec_app.\n     rewrite ! IHP1. rewrite ! IHP2.  \nrewrite ! lift_rec_app. \nrewrite lift_rec_closed. 2: simpl; auto.  \nrewrite ! (lift_rec_closed (Op Node)). 2: simpl; auto. \n2: simpl; auto. 2: simpl; auto. \n  unfold lift_rec at 5 7. relocate_lt. \n    unfold lift_rec; fold lift_rec. relocate_lt. \nunfold pattern_size; fold pattern_size.\nunfold plus; fold plus.\nf_equal. f_equal. f_equal. f_equal. \nf_equal. f_equal. f_equal. f_equal. \nf_equal. f_equal. f_equal. f_equal. \nf_equal. \n                    \nreplace (pattern_size P1 + 0) with (pattern_size P1) by auto.\nclear.  \nrewrite (lift_rec_lift_rec M); try omega.\nreplace((pattern_size P2 +\n                                          (pattern_size P1 + S (S (S n)))))\nwith ((1+2) + (pattern_size P2 + pattern_size P1 + n)) by omega. \nrewrite (lift_lift_rec M) at 1; try omega.\nreplace(pattern_size P2 + (pattern_size P1 + 2))\nwith (2+ (pattern_size P2 + pattern_size P1)) by omega. \nrewrite (lift_lift_rec); try omega.\nrewrite (lift_rec_lift_rec (lift_rec M _ _)); try omega.\nf_equal.  f_equal. omega.  \nQed.\n\n\nLemma aux2 : forall M N p k, subst_rec (lift_rec M p (1 + 2)) N\n     (S (S (S k)) + p) =\n   lift_rec (subst_rec M N (k + p))\n     p (1 + 2). \nProof. \nintros. unfold plus; fold plus. replace (S(S(S (k+ p)))) with (3+ (k+p)) by omega. \nrewrite subst_rec_lift_rec1; try omega. auto. \nQed. \n   \nLemma subst_rec_preserves_case:\n  forall P M N k, subst_rec (case P M) N k = case P (subst_rec M N (k+ pattern_size P)).\nProof.\n  induction P; intros. \n  (* 3 *)\n  unfold case, maxvar, pattern_size. rewrite subst_rec_preserves_star_opt.\n  unfold_op; unfold subst_rec; fold subst_rec.  replace (k+1) with (S k) by omega; auto. \n  (* 2 *)\n  unfold case, maxvar, swap. case o; unfold_op.  \n rewrite subst_rec_preserves_star_opt. \nrewrite ! subst_rec_app.\nrewrite subst_rec_closed.\n 2: rewrite Fop_closed; omega.\nrewrite ! (subst_rec_closed (Op Node)). 2: simpl; omega.  \n  unfold subst_rec; fold subst_rec.\ninsert_Ref_out. \nunfold lift. rewrite (subst_rec_lift_rec1 M); try omega.\nunfold pattern_size; fold pattern_size.  \n  replace (k+0) with k by omega. auto.  \n  (* 1 *) \n  unfold case; fold case.\nassert(is_program (App P1 P2) = true \\/ is_program (App P1 P2) <> true) by decide equality. \ninversion H. rewrite H0. \n(* 2 *) \nassert(program (App P1 P2)) by eapply2 program_is_program.  inversion H1.   \nrewrite subst_rec_preserves_star_opt. \nunfold swap; unfold_op; rewrite ! subst_rec_app. \nrewrite subst_rec_closed. 2: rewrite equal_comb_closed; omega. \nunfold subst_rec; fold subst_rec. insert_Ref_out.  \nrewrite 2? subst_rec_closed. 2: simpl in H3; max_out. 2: simpl in H3; max_out. \nrewrite pattern_size_closed. 2: auto.  \nunfold lift; rewrite subst_rec_lift_rec1; try omega. \nreplace (k+0) with k by omega; congruence. \n(* 1 *) \nassert(is_program (App P1 P2) = false).\neapply2 not_true_iff_false. \nrewrite H1. \n(* 1 *) \n  unfold case_app. \nrewrite subst_rec_preserves_star_opt. \nrewrite ! subst_rec_app.\nrewrite subst_rec_closed.\n2: rewrite Fop_closed; omega. \nunfold lift; rewrite subst_rec_lift_rec1. 2: omega.   \n  unfold subst_rec; fold subst_rec. insert_Ref_out.\nrewrite ! subst_rec_preserves_star_opt. \nrewrite ! lift_rec_preserves_star_opt.\nrewrite ! subst_rec_app. \nrewrite ! lift_rec_preserves_case. \nrewrite ! (subst_rec_closed k_op). 2: simpl; omega.\nunfold subst_rec; fold subst_rec. \ninsert_Ref_out.   \nrewrite ! (subst_rec_closed i_op). 2: unfold_op; simpl; omega.\n2: unfold_op; simpl; omega.\n  rewrite IHP1. rewrite IHP2.  \n  unfold subst_rec; fold subst_rec. \nunfold pattern_size; fold pattern_size.\nrewrite ! lift_rec_app. \nrewrite ! lift_rec_preserves_case.\nrewrite ! (lift_rec_closed k_op). 2: simpl; omega.  2: simpl; omega. \nrewrite ! subst_rec_app.\nrewrite ! (subst_rec_closed k_op). 2: simpl; omega. \nrewrite ! lift_rec_app.\nrewrite ! (lift_rec_closed k_op). 2: simpl; omega.\nunfold swap, subst_rec; fold subst_rec. \nunfold lift_rec; fold lift_rec. relocate_lt.\ninsert_Ref_out. \nrewrite ! (subst_rec_closed i_op). 2: simpl; omega. \nrewrite ! (subst_rec_closed k_op). 2: simpl; omega. \nf_equal. f_equal. f_equal. f_equal. \nf_equal. f_equal. f_equal. f_equal. \nf_equal. f_equal. f_equal. f_equal. \nf_equal. \nrewrite (lift_rec_lift_rec); try omega.\nreplace (S (S k) + pattern_size P1 + pattern_size P2) with \n(2 + (pattern_size P2 + pattern_size P1 + k)) by omega. \nrewrite subst_rec_lift_rec1; try omega. \nrewrite lift_rec_lift_rec; try omega.     \nreplace  (k+ (pattern_size P1 + (pattern_size P2))) \n    with (pattern_size P2 + pattern_size P1 + k)\n      by omega. \nauto. \nQed.\n\n\nInductive pattern_normal : nat -> Tree -> Prop :=\n| pnf_normal : forall j M, normal M -> pattern_normal j M\n(*  pattern_normal j (Ref n)\n| pnFop : forall j o, pattern_normal j (Op o)\n| pnf_active : forall j M1 M2, normal M1 -> normal j M2 -> \n                              status (App M1 M2) = Active -> \n                              pattern_normal j (App M1 M2)  \n*) \n| pnf_compound : forall j M1 M2, pattern_normal j M1 -> pattern_normal j M2 -> \n                              compound (App M1 M2) -> pattern_normal j (App M1 M2)\n| pnf_active : forall j M1 M2, pattern_normal j M1 -> pattern_normal j M2 -> \n                              status (App M1 M2) = Active -> pattern_normal j (App M1 M2)\n| pnf_break : forall j M1 M2, pattern_normal j M1 -> pattern_normal j M2 -> \n                              0 < maxvar M2 -> maxvar M2 <= j -> \n                              pattern_normal j (App M1 M2) \n(* actually, it is enough that one of the pattern variables occurs in M2 *) \n.\n\n(* \nLemma pattern_normal_1_occurs : \nforall M, pattern_normal 1 M -> \nnormal M \\/ exists M1 M2, M = App M1 M2 /\\ occurt0 M2 = true. \nProof.\ninduction M; split_all; try discriminate.  inversion H; subst.  auto. \nright; exists M1; exist M2. split; auto. \nclear - H5 H6. \ninduction M2; split_all; simpl in *. \nassert(n= 0) by omega. subst. auto. noway. \nassert(0< maxvar M2_1 \\/ 0< maxvar M2_2). \n\ngen_case H5 (maxvar M2_1);  gen_case H5 (maxvar M2_2). \nleft; omega. inversion H. \nrewrite IHM2_1; auto. \ngen_case H6 (maxvar M2_1). gen_case H6 (maxvar M2_2).\ngen_case H6 n.  gen_case H6 n0. noway. \nrewrite IHM2_2; auto. apply orb_true_r.  \ngen_case H6 (maxvar M2_1). gen_case H6 (maxvar M2_2).\ngen_case H6 n.  gen_case H6 n0. noway. \nQed. \n*) \n\nLemma pattern_normal_closed: \nforall M, maxvar M = 0 -> forall j, pattern_normal j M -> normal M. \nProof. \ninduction M; split_all. max_out. inversion H0; subst; auto.\neapply2 nf_compound. \nassert(status (App M1 M2) = Passive). \neapply2 (closed_implies_passive).  simpl; rewrite H1; rewrite H2; auto. \nrewrite H in H7; discriminate. \n   noway. \nQed. \n\nLemma normal_star_opt_app: \nforall M1 M2, occurs 0 (App M1 M2)  >0\n-> normal (star_opt M1) -> normal (star_opt M2) -> \nnormal (star_opt (App M1 M2)).\nProof.\nintros.  unfold star_opt; fold star_opt. simpl in H. \nassert(occurs 0 M1 >0 \\/ occurs 0 M2 >0) by omega. \ninversion H2.\nreplace (occurs 0 M1) with (S (pred (occurs 0 M1))) by omega.\neapply2 nf_compound.\nassert(occurs 0 M1 >0 \\/ occurs 0 M1 = 0) by omega. \ninversion H4. \n(* 2 *)\nreplace (occurs 0 M1) with (S (pred (occurs 0 M1))) by omega.\neapply2 nf_compound.\n(* 1 *)  \nreplace (occurs 0 M2) with (S (pred (occurs 0 M2))) by omega.\nrewrite H5.\nassert(M2 = Ref 0 \\/ M2 <> Ref 0) by repeat decide equality.\ninversion H6. subst. \nassert(star_opt M1 = App k_op (subst M1 (Op Node))).\nrewrite star_opt_occurs_false. auto. auto. \nrewrite H7 in *. \ninversion H0; auto.\n(* 1 *)\nreplace(match M2 with\n    | Ref 0 => subst M1 (Op Node)\n    | _ => App (App (Op Node) (App (Op Node) (star_opt M2))) (star_opt M1)\n        end) with (App (App (Op Node) (App (Op Node) (star_opt M2))) (star_opt M1)).\nunfold_op; eapply2 nf_compound. \ngen_case H7 M2.\ngen_case H7 n. congruence.\nQed. \n\n(* delete \nLemma pattern_normal_subst_occurs_false: \nforall M j, occurs 0 M = false -> pattern_normal j M  -> \npattern_normal (pred j) (subst M s_op). \nProof. \ninduction M; split_all. \ngen2_case H H0 n; unfold subst, subst_rec; insert_Ref_out. \ndiscriminate. eapply2 pnf_normal. \nunfold subst, subst_rec; eapply2 pnf_normal. \nrewrite orb_false_iff in H. inversion H. \ninversion H0; subst. \neapply2 pnf_normal. \nunfold subst. eapply2 occurs_false_subst_normal. \nsimpl; rewrite H1; rewrite H2; auto.\neapply2 pnf_compound.  fold subst_rec.  \neapply2 occurs_false_subst_normal. fold subst_rec.\n assert(compound (subst_rec (App M1 M2) s_op 0)).  \n(eapply2 subst_rec_preserves_compounds).\nsimpl in H3. auto. \nunfold subst, subst_rec; fold subst_rec. \napply pnf_break; fold subst_rec.\neapply2 IHM1. eapply2 IHM2. \n  \n\nassert(maxvar M2noway. \n\n\n\n  inversion H1; subst; auto. \ne\n\nauto. \n\n*) \n\n\nLemma occurs_false_subst_pattern_normal: \nforall M j N, occurs 0 M = 0 -> pattern_normal j M -> pattern_normal (pred j) (subst_rec M N 0). \nProof.\ninduction M; split_all.\n(* 3 *) \ngen2_case H H0 n. discriminate.  insert_Ref_out. eapply2 pnf_normal.\n(* 2 *)  \neapply2 pnf_normal.\n(* 1 *)    \nassert(occurs 0 M1 = 0 /\\ occurs 0 M2 = 0) by omega. \ninversion H1. \ninversion H0.\n(* 4 *) \n eapply2 pnf_normal. \nassert(normal (subst_rec (App M1 M2) N 0)) by eapply2 occurs_false_subst_normal. \nsimpl in H7; auto.\n(* 3 *) \neapply2 pnf_compound. \nassert(compound (subst_rec (App M1 M2) N 0)) by eapply2 subst_rec_preserves_compounds. \nsimpl in H10; auto.\n(* 2 *)\neapply2 pnf_active. \nreplace (App (subst_rec M1 N 0) (subst_rec M2 N 0)) with (subst_rec (App M1 M2) N 0) by auto. \nrewrite occurs_false_subst_status.  auto. simpl; auto. \n(* 1 *) \n subst. \neapply pnf_break. eapply2 IHM1. eapply2 IHM2.\n(* 2 *)  \neapply2 occurs_false_subst_rec_maxvar_gt0.\neapply2 occurs_false_subst_rec_maxvar_lt. \nQed. \n\nLemma pattern_normal_star_opt: \nforall M j, pattern_normal j M -> pattern_normal (pred j) (star_opt M). \nProof. \ninduction M; intros. \n(* 3 *) \neapply2 pnf_normal. eapply2 star_opt_normal.  \n(* 2 *) \neapply2 pnf_normal. eapply2 star_opt_normal.  \n(* 1 *) \n subst; inversion H; subst. \n(* 4 *) \neapply2 pnf_normal. eapply2 star_opt_normal.\n(* 3 *)   \nunfold star_opt; fold star_opt. \nassert(occurs 0 M1 >0 \\/ occurs 0 M1 = 0) by omega. \ninversion H0. \n(* 4 *)\nreplace (occurs 0 M1) with (S (pred (occurs 0 M1))) by omega.\neapply2 pnf_compound. eapply2 pnf_compound.  eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_normal. \n(* 3 *)  \nassert(pattern_normal  (pred j) (star_opt M2)) by eapply2 IHM2. \nrewrite H1.\nassert(pattern_normal (pred j) (subst_rec M1 (Op Node) 0)) .\neapply2 occurs_false_subst_pattern_normal.\nassert(pattern_normal (pred j) (star_opt M1)) by eapply2 IHM1. \nclear IHM1 IHM2 H H0 H1 . \n(* 3 *)  \nunfold subst, subst_rec; fold subst_rec. \nassert(pattern_normal (pred j) (App (App (Op Node) (App (Op Node) (star_opt M2))) (star_opt M1))). \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_normal. \nassert(occurs 0 M2 = 0 -> \n  pattern_normal (pred j) (App k_op (App (subst_rec M1 (Op Node) 0) (subst_rec M2 (Op Node) 0)))). \nintro. \nassert(pattern_normal (pred j) (subst_rec M2 (Op Node) 0)).\nrewrite star_opt_occurs_false in H3.  2: auto. \ninversion H3; subst; auto.\neapply2 pnf_normal.  inversion H1; auto. \neapply2 pnf_compound. unfold_op;  eapply2 pnf_normal. \n2: unfold_op; auto. \neapply2 pnf_compound.  \nassert(compound (subst_rec (App M1 M2) (Op Node) 0)).  \n(eapply2 subst_rec_preserves_compounds).\nsimpl in H8.  auto. \n(* 3 *) \ngen3_case H H0 H7 M2. gen3_case H H0 H7 n. \ngen3_case H H0 H7 (occurs 0 t + occurs 0 t0). \n(* 2 *) \nunfold star_opt; fold star_opt. \nassert(occurs 0 M1 >0 \\/ occurs 0 M1 = 0) by omega. \ninversion H0. \n(* 3 *) \nreplace (occurs 0 M1) with (S (pred (occurs 0 M1))) by omega.\neapply2 pnf_compound. eapply2 pnf_compound.  eapply2 pnf_normal.\n eapply2 pnf_compound.  eapply2 pnf_normal.\n(* 2 *)  \n rewrite H1.\n assert(pattern_normal  (pred j) (star_opt M2)) by eapply2 IHM2. \nassert(pattern_normal (pred j) (subst_rec M1 (Op Node) 0)) .\neapply2 occurs_false_subst_pattern_normal.\nassert(pattern_normal (pred j) (star_opt M1)) by eapply2 IHM1. \nclear IHM1 IHM2 H H0 . \n(* 2 *)  \nunfold subst, subst_rec; fold subst_rec. \nassert(pattern_normal (pred j) (App (App (Op Node) (App (Op Node) (star_opt M2))) (star_opt M1))). \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. eapply2 pnf_compound. eapply2 pnf_normal. \nassert(occurs 0 M2 = 0 -> \n  pattern_normal (pred j) (App k_op (App (subst_rec M1 (Op Node) 0) (subst_rec M2 (Op Node) 0)))). \nintro. \nassert(pattern_normal (pred j) (subst_rec M2 (Op Node) 0)).\nrewrite star_opt_occurs_false in H3.  2: auto. \ninversion H3; subst; auto.\neapply2 pnf_normal.  inversion H8; auto. \neapply2 pnf_compound. unfold_op;  eapply2 pnf_normal. \n2: unfold_op; auto. \neapply2 pnf_active.\nreplace (App (subst_rec M1 (Op Node) 0) (subst_rec M2 (Op Node) 0)) with \n(subst_rec (App M1 M2) (Op Node) 0) by auto. \nrewrite occurs_false_subst_status. auto.  \nsimpl; omega. \n(* 2 *) \ngen3_case H H0 H7 M2. gen3_case H H0 H7 n. \ngen3_case H H0 H7 (occurs 0 t + occurs 0 t0). \n(* 1 *) \nSet Keep Proof Equalities.\nassert(M2 = Ref 0 \\/ M2 <> Ref 0) by repeat decide equality. \ninversion H0; subst.  \nassert(occurs 0 M1 >0 \\/ occurs 0 M1 =0) by omega. \ninversion H1; subst. \n(* 3 *) \nunfold star_opt; fold star_opt. replace (occurs 0 M1) with (S (pred (occurs 0 M1))) by omega.\neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_normal. \nunfold star_opt; fold star_opt. rewrite H4.\neapply2 occurs_false_subst_pattern_normal. \n(* 1 *)\nassert(occurs 0 M1 >0 \\/ occurs 0 M1 =0) by omega. \ninversion H4; subst. \n(* 2 *) \nunfold star_opt; fold star_opt. replace (occurs 0 M1) with (S (pred (occurs 0 M1))) by omega.\neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_normal. \nunfold star_opt; fold star_opt. rewrite H7.\n(* 1 *) \nassert(pattern_normal  (pred j) (star_opt M2)) by eapply2 IHM2. \nassert(pattern_normal (pred j) (subst_rec M1 (Op Node) 0)) .\neapply2 occurs_false_subst_pattern_normal.\nassert(pattern_normal (pred j) (star_opt M1)) by eapply2 IHM1. \n(* 1 *)  \nunfold subst, subst_rec; fold subst_rec. \nassert(pattern_normal (pred j) (App (App (Op Node) (App (Op Node) (star_opt M2))) (star_opt M1))). \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal.  eapply2 pnf_compound. eapply2 pnf_normal. \nassert(occurs 0 M2 = 0 -> \n  pattern_normal (pred j) (App k_op (App (subst_rec M1 (Op Node) 0) (subst_rec M2 (Op Node) 0)))). \nintro. \nassert(pattern_normal (pred j) (subst_rec M2 (Op Node) 0)).\nrewrite star_opt_occurs_false in H10.  2: auto. \neapply2 occurs_false_subst_pattern_normal. unfold_op. \neapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_break. \neapply2 occurs_false_subst_rec_maxvar_gt0. \neapply2 occurs_false_subst_rec_maxvar_lt. \n(* 1 *) \ngen3_case H11 H12 H1 M2. gen3_case H11 H12 H1 n. \ngen3_case H11 H12 H1 (occurs 0 t + occurs 0 t0). \nQed. \n\n\nLemma pattern_normal_zero: forall M, pattern_normal 0 M -> normal M. \nProof. \ninduction M; split_all. inversion H; subst. auto. \neapply2 nf_compound.  eapply2 nf_active. noway. \nQed. \n\n\nLemma pattern_normal_gt: \nforall j M, pattern_normal j M -> forall k, j <= k -> pattern_normal k M. \nProof.\nintros j M pn; induction pn; split_all. \neapply2 pnf_normal. eapply2 pnf_compound. eapply2 pnf_active. eapply2 pnf_break.  omega. \nQed. \n\n\nLemma pattern_normal_app_comb: forall M N j, pattern_normal j M -> pattern_normal j N -> \npattern_normal j (app_comb M N). \nProof. \nintros. replace (app_comb M N) with \n(App (App (Op Node) (App (Op Node) i_op)) (App (App (Op Node) (App (Op Node) (App k_op N))) (App k_op M))) by auto. \nunfold_op. eapply2 pnf_compound.  eapply2 pnf_compound. eapply2 pnf_normal.  \nunfold_op. eapply2 pnf_compound.  eapply2 pnf_normal.  \neapply2 pnf_compound.  eapply2 pnf_compound.  eapply2 pnf_normal.\neapply2 pnf_normal.  eapply2 pnf_normal. \neapply2 pnf_compound.  eapply2 pnf_compound.  eapply2 pnf_normal.\neapply2 pnf_compound.  eapply2 pnf_normal.\neapply2 pnf_compound.  eapply2 pnf_normal.\neapply2 pnf_compound.  eapply2 pnf_normal.\nQed. \n\n\n\nLemma pattern_size_app_comb: forall M N, pattern_size (app_comb M N) = pattern_size N + pattern_size M. \nProof. intros. unfold app_comb. simpl. auto. Qed. \n\n(* restore ? \n\nLemma case_normal: \nforall (P M : Tree), normal M -> normal (case P M).\nProof.\n  induction P; intros.\n  (* 3 *)\n  unfold case, maxvar.   eapply2 star_opt_normal. unfold_op; split_all. \n  (* 2 *) \nunfold case, swap; unfold_op; intros. case o; nf_out. \napply nf_active. nf_out. eapply2 nf_active; nf_out. \neapply2 nf_active; nf_out. \nunfold lift; apply lift_rec_preserves_normal; auto. \nnf_out. cbv; auto.  \napply nf_active. nf_out.\nrepeat (apply nf_active; nf_out). \nunfold lift; apply lift_rec_preserves_normal; auto. \nnf_out. cbv; auto.  \n  (* 1 *) \n  unfold case; fold case; unfold case_app_nf. \nassert(is_program (App P1 P2) = true \\/ is_program (App P1 P2) <> true) by decide equality. \ninversion H0. rewrite H1. \n(* 2 *) \nrewrite star_opt_occurs_true. 2: cbv; auto. 2: unfold swap; discriminate. \nrewrite star_opt_occurs_true. 2: cbv; auto. 2: unfold swap; discriminate. \nrewrite star_opt_occurs_true. 2: cbv; auto. 2: unfold swap; discriminate. \nrewrite star_opt_eta.\nnf_out.  \nunfold subst; rewrite subst_rec_closed. eapply2 equal_comb_normal. \nrewrite equal_comb_closed; omega. \nassert(program (App P1 P2)) by eapply2 program_is_program. inversion H2; auto. \nunfold lift; apply lift_rec_preserves_normal. auto. \nunfold swap; unfold_op; nf_out.  \neapply2 occurs_closed. \n(* 1 *) \nassert(is_program (App P1 P2) = false).\neapply2 not_true_iff_false. \nrewrite H2. \n(* 1 *) \n  unfold case_app_nf, swap. unfold_op; nf_out. \ninversion H; eapply2 IHP1;  eapply2 IHP2. \neapply2 nf_compound. eapply2 nf_compound. \nQed. \n\n\n*) \n (* \nLemma case_pattern_normal: \nforall (P M : Tree) j, pattern_normal j M -> \npattern_normal (j - (pattern_size P)) (case P M).\nProof.\n  induction P; intros. \n  (* 3 *)\n  unfold pattern_size. unfold case. \nreplace (j-1) with (pred j) by omega. \neapply pattern_normal_star_opt; auto. \nunfold_op. eapply2 pnf_compound. eapply2 pnf_normal. \n(* 2 *) \nunfold pattern_size, case; simpl. replace (j-0) with j by omega. \ncase o. \n(* 3 *) \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \nunfold subst, subst_rec; eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_normal. nf_out. \nunfold subst, subst_rec; eapply2 pnf_normal. unfold_op. nf_out. \nunfold_op; eapply2 pnf_compound. eapply2 pnf_normal. \nunfold subst, subst_rec; eapply2 pnf_normal. \nunfold_op; eapply2 pnf_compound. eapply2 pnf_normal. \nunfold subst, subst_rec; eapply2 pnf_normal. \n2:unfold_op; eapply2 pnf_compound. \n2: eapply2 pnf_normal. 2: nf_out.  \n2: unfold subst, subst_rec; nf_out. \n2:unfold subst, subst_rec; eapply2 pnf_normal. \n2: unfold_op; eapply2 pnf_compound. \n2: unfold subst, subst_rec; eapply2 pnf_normal. \n2: unfold subst, subst_rec; eapply2 pnf_normal. \n2: nf_out.  \n(* 3 *) \nunfold lift. rewrite ! occurs_lift_rec_zero. gen_case H M. gen_case H n. relocate_lt. \nunfold_op. eapply2 pnf_compound.  eapply2 pnf_normal. \neapply2 pnf_normal. unfold subst; nf_out.  insert_Ref_out; auto. \nrelocate_lt. eapply2 pnf_normal. unfold subst; nf_out.  insert_Ref_out; auto. \neapply2 pnf_normal. unfold subst; nf_out. \nunfold_op; eapply2 pnf_compound. eapply2 pnf_normal.\nunfold subst, subst_rec; fold subst_rec. \nrewrite ! subst_rec_lift_rec; try omega.  rewrite ! lift_rec_null. \neapply2 pnf_compound. eapply2 pnf_normal.\n(* 2 *) \nunfold subst, subst_rec; fold subst_rec. \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_normal. unfold_op; unfold subst_rec; nf_out. \neapply2 pnf_normal. unfold_op; unfold subst_rec; nf_out. \neapply2 pnf_normal. unfold_op; unfold subst_rec; nf_out. \neapply2 pnf_normal. unfold_op; unfold subst_rec; nf_out. \n2: eapply2 pnf_normal; unfold_op; unfold subst_rec; nf_out. \n(* 2 *) \nunfold lift. gen_case H M; unfold lift_rec; fold lift_rec. \ngen_case H n. relocate_lt. unfold plus. insert_Ref_out.\neapply2 pnf_normal; nf_out. \neapply2 pnf_normal; nf_out. \nrelocate_lt. unfold plus. insert_Ref_out. nf_out. \neapply2 pnf_normal; nf_out. \n(* 2 *) \nrewrite ! occurs_lift_rec_zero. simpl. \nrewrite ! subst_rec_lift_rec; try omega. rewrite ! lift_rec_null.\nunfold_op; eapply2 pnf_compound. eapply2 pnf_normal.  eapply2 pnf_compound. \neapply2 pnf_normal.\n(* 1 *) \nunfold pattern_size; fold pattern_size. \nunfold case; fold case.\nassert(is_program (App P1 P2) = true \\/ is_program (App P1 P2) <> true) by decide equality. \ninversion H0. rewrite H1. \n(* 2 *) \nrewrite star_opt_occurs_true. 2: cbv; auto. 2: unfold swap; discriminate. \nrewrite star_opt_occurs_true. 2: cbv; auto. 2: unfold swap; discriminate. \nrewrite star_opt_occurs_true. 2: cbv; auto. 2: unfold swap; discriminate. \nrewrite star_opt_eta.\neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal.  \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal.  \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal.  \neapply2 pnf_normal. unfold subst; rewrite subst_rec_closed. \neapply2 equal_comb_normal. rewrite equal_comb_closed; omega. \neapply2 pnf_normal. eapply2 star_opt_normal. \nassert(program (App P1 P2)) by eapply2 program_is_program. \ninversion H2; auto. \nunfold_op. rewrite star_opt_occurs_false.\nunfold lift, subst_rec; fold subst_rec.   \nrewrite subst_rec_lift_rec; try omega. rewrite lift_rec_null. \neapply2 pnf_compound. \nunfold_op; eapply2 pnf_normal.   \neapply2 pnf_compound. eapply2 pnf_normal. \nrewrite ! pattern_size_closed. \nreplace (j-(0+0)) with j by omega. auto. \nassert(program (App P1 P2)) by eapply2 program_is_program. \ninversion H2.  simpl in H4; max_out. \nassert(program (App P1 P2)) by eapply2 program_is_program. \ninversion H2.  simpl in H4; max_out. \nunfold_op; auto. \nunfold occurs; fold occurs 0. \nunfold lift; rewrite occurs_lift_rec_zero.  auto. \neapply2 pnf_normal. unfold swap; unfold_op; nf_out. \neapply2 occurs_closed. \n(* 1 *) \nassert(is_program (App P1 P2) = false).\neapply2 not_true_iff_false. \nrewrite H2. \n(* 1 *) \n  unfold case_app_nf, swap. unfold_op; nf_out. \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal.  \neapply2 pnf_compound. eapply2 pnf_normal.  nf_out. \neapply2 pnf_compound. eapply2 pnf_normal.  \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal.  \neapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_compound. eapply2 pnf_normal.\n2: eapply2 pnf_normal. 2: nf_out.   \n2: eapply2 pnf_normal. 2: nf_out.   \n2: unfold_op; auto. 2: eapply2 pnf_normal.  2: nf_out.\n(* 1 *) \nreplace (j - (pattern_size P1 + pattern_size P2)) with (j - pattern_size P2 - pattern_size P1)\nby omega. \neapply2 IHP1. eapply2 IHP2. \nunfold_op;  eapply2 pnf_compound. eapply2 pnf_normal. \neapply2 pnf_compound. eapply2 pnf_normal.\nQed. \n \n\n *) \n\n\n\n(* matching *) \n\nInductive matching : Tree -> Tree -> list Tree -> Prop :=\n| match_ref : forall i M, matching (Ref i) M (cons M nil)\n| match_op: forall o, matching (Op o) (Op o) nil\n| match_app: forall p1 p2 M1 M2 sigma1 sigma2,\n               (compound (App p1 p2) \\/ status (App p1 p2) = Active) -> compound (App M1 M2) ->\n               matching p1 M1 sigma1 -> matching p2 M2 sigma2 ->\n               matching (App p1 p2) (App M1 M2) ((map (lift (length sigma1)) sigma2) ++ sigma1)\n.\n\nHint Constructors matching.\n\nLemma matching_lift:\n  forall P M sigma, matching P M sigma -> forall k, matching P (lift k M) (map (lift k) sigma). \nProof.\n  induction P; split_all; inversion H; subst; unfold map; fold map; auto. \n(* 2 *) \nreplace (lift k (App M1 M2)) with (App (lift k M1) (lift k M2)) by (unfold lift; auto). \nreplace(fix map (l : list Tree) : list Tree :=\n            match l with\n            | nil => nil\n            | a :: t => lift (length sigma1) a :: map t\n            end) with (map (lift (length sigma1))) by auto.\nreplace (fix map (l : list Tree) : list Tree :=\n         match l with\n         | nil => nil\n         | a :: t => lift k a :: map t\n         end) with (map (lift k)) by auto. \nrewrite map_app.\nreplace (map (lift k) (map (lift (length sigma1)) sigma2)) with\n         (map (lift (length (map (lift k) sigma1))) (map (lift k) sigma2)).\neapply2 match_app. \nreplace (App (lift k M1) (lift k M2)) with  (lift k (App M1 M2)) by (unfold lift; auto). \nunfold lift. eapply2 lift_rec_preserves_compound. \nclear. induction sigma2; split_all. rewrite IHsigma2. rewrite map_length. \nunfold lift; repeat rewrite lift_rec_lift_rec; try omega. \nreplace (length sigma1 + k) with (k+ length sigma1) by omega. auto.\nQed.\n\n\nLemma max_pred: forall m n, pred (max m n) = max (pred m) (pred n). \nProof. double induction m n; intros; auto. case n; intros; auto. Qed. \n\n\nLemma program_matching: forall M, program M -> matching M M nil. \nProof.\n  induction M; split_all.\n  inversion H; split_all. simpl in *; noway. \n  inversion H; split_all. inversion H0.\n  assert(status (App M1 M2) = Passive) by eapply2 closed_implies_passive.\n  rewrite H6 in H7; discriminate.\n  replace (nil: list Tree)\n  with (List.map (lift (length (nil: list Tree))) (nil: list Tree) ++ (nil: list Tree))\n    by split_all.\n  eapply2 match_app. simpl in *. max_out. eapply2 IHM1. unfold program; auto.\n  simpl in *. max_out. eapply2 IHM2. unfold program; auto.\nQed. \n\nLemma program_matching2: forall M sigma, matching M M sigma -> maxvar M = 0 -> program M. \nProof.\n  induction M; split_all. noway. unfold program; auto. \n  inversion H; split_all; subst. unfold program; split; auto.  eapply2 nf_compound. \n  eapply2 IHM1. max_out.  eapply2 IHM2. max_out. \nQed. \n\n\n\n  \nLemma pattern_is_closed: \nforall P, maxvar P = 0 -> forall M sigma, matching P M sigma -> M = P /\\ sigma = nil. \nProof. \ninduction P; intros; inversion H; subst.  \n(* 2 *) \ninversion H0; auto. \n(* 1 *) \ninversion H0; subst; simpl in *; max_out. \nassert(M1 = P1 /\\ sigma1 = nil). eapply2 IHP1 . \nassert(M2 = P2 /\\ sigma2 = nil). eapply2 IHP2 . \nsplit_all; subst. inversion H2; inversion H7; subst; split; auto.  \nQed. \n\n\n\nLemma maxvar_case_app : \nforall P1 P2, \n(forall M : Tree, maxvar (case P1 M) = maxvar M - pattern_size P1) -> \n(forall M : Tree, maxvar (case P2 M) = maxvar M - pattern_size P2) -> \nforall M, maxvar (case_app case P1 P2 M) = maxvar M - pattern_size (App P1 P2). \nProof. \nintros. unfold case_app. \nrewrite maxvar_star_opt. \nunfold_op. unfold maxvar; fold maxvar.  unfold max; fold max. \nunfold lift; rewrite ! lift_rec_preserves_star_opt. \nunfold lift_rec; fold lift_rec. \nrewrite lift_rec_lift_rec; try omega. \nrewrite ! maxvar_star_opt. \nrelocate_lt. \nrewrite ! lift_rec_preserves_case. \nunfold lift_rec; fold lift_rec. \nunfold maxvar; fold maxvar. \nunfold max; fold max. \nrewrite H; rewrite H0. \nunfold maxvar; fold maxvar. \nunfold max; fold max. \nrewrite ! max_pred.\nrewrite Fop_closed.  simpl. rewrite ! max_zero. \nreplace (pattern_size P2 + (pattern_size P1 + 0)) \nwith (pattern_size P1 + pattern_size P2) by omega. \nreplace (maxvar (lift_rec M (pattern_size P1 + pattern_size P2) 3) -\n             pattern_size P2 - pattern_size P1)\nwith (maxvar (lift_rec M (pattern_size P1 + pattern_size P2) 3) -\n             (pattern_size P1 + pattern_size P2)) by omega.\nclear. induction M; split_all. \ncase (pattern_size P1 + pattern_size P2); split_all.\n(* 3 *) \nunfold relocate. elim(test 0 n); split_all.  noway.\n(* 2 *) \nunfold relocate. elim(test (S n0) n); split_all.\ngen_case a n0; try omega.\ngen_case a n1; try omega.\ngen_case a n2; try omega.\nomega. \n(* 1 *) \nrewrite max_minus.\nrewrite ! max_pred. \nrewrite IHM1.  rewrite IHM2. \nrewrite max_minus. auto. \nQed. \n\n\n\nLemma maxvar_lift: forall M k, pred (maxvar (lift (S k) M)) = maxvar (lift k M). \nProof.\ninduction M; split_all. relocate_lt. omega. \nrewrite max_pred. unfold lift in *. auto. \nQed. \n\n\nLemma maxvar_case : forall P M, maxvar (case P M) = maxvar M - (pattern_size P).\nProof.\n  induction P; intros; unfold case; fold case; unfold maxvar; fold maxvar.\n  (* 3 *)\n  rewrite maxvar_star_opt. split_all. omega. \n  (* 2 *)\ncase o; unfold_op; unfold pattern_size.  \n  rewrite maxvar_star_opt. simpl. \nreplace (maxvar M - 0) with (maxvar M) by omega.\nrewrite max_pred. simpl. \nrewrite max_zero.   \nassert(pred (maxvar (lift 1 M)) = maxvar (lift 0 M)) by eapply2 maxvar_lift. \ngen_case H (maxvar (lift 1 M)).\nunfold lift in H; rewrite lift_rec_null in H; auto.\nunfold lift in H; rewrite lift_rec_null in H; auto.\n(* 1 *)\nassert(is_program (App P1 P2) = true \\/ is_program(App P1 P2) <> true)\nby decide equality. \ninversion H. \nrewrite H0.\nrewrite maxvar_star_opt.   \nrewrite ! maxvar_app. \nrewrite equal_comb_closed. simpl.  \nassert(program (App P1 P2)) by eapply2 program_is_program. \ninversion H1. simpl in H3. max_out. rewrite H4. rewrite H5. simpl. \nrewrite max_pred. \nassert(pred (maxvar (lift 1 M)) = maxvar (lift 0 M)) by eapply2 maxvar_lift. \nreplace (lift 0 M) with M in H3 by (unfold lift; rewrite lift_rec_null; auto).\n(* 2 *)\ngen_case H3 (maxvar (lift 1 M)).\nrewrite <- H3. \nomega.\nrewrite ! H3. rewrite max_zero.\nrewrite ! pattern_size_closed; auto.\nomega.\n(* 1 *) \nassert(is_program (App P1 P2) = false) by \neapply2 not_true_iff_false. \nrewrite H1. \n(* 1 *) \nunfold case_app. \nrewrite maxvar_star_opt.\nrewrite ! maxvar_app.\nrewrite ! maxvar_ref.\nrewrite Fop_closed. \nreplace (maxvar i_op) with 0 by (cbv; auto).\nrewrite ! max_pred.\nrewrite maxvar_lift. \nunfold lift at 1; rewrite ! lift_rec_null.\nrewrite ! maxvar_star_opt. \nrewrite ! maxvar_app.\nrewrite ! max_pred. \nrewrite maxvar_lift. \nsimpl. rewrite ! maxvar_lift.\nunfold lift; rewrite ! lift_rec_null.\nrewrite ! max_zero.\nrewrite IHP1. rewrite IHP2. \nunfold_op; simpl. omega.\nQed. \n\n\nLemma program_matching3: \nforall P M sigma, matching P M sigma -> maxvar P = 0 -> M = P /\\ sigma = nil. \nProof.\n  induction P; split_all. noway. \n  inversion H; split_all; subst. \n  inversion H; split_all; subst. \n  simpl in H0; max_out. \n  assert(M1 = P1 /\\ sigma1 = nil) by eapply2 IHP1.  \n  assert(M2 = P2 /\\ sigma2 = nil) by eapply2 IHP2.   \n  inversion H0; inversion H6; subst; split; cbv; auto.  \nQed. \n\nLemma case_by_matching:\n  forall P N sigma,  matching P N sigma ->\n                     forall M, sf_red (App (case P M) N) (App k_op (fold_left subst sigma M)). \nProof.\n  induction P; intros.\n  (* 3 *)\n  inversion H; subst. unfold fold_left.  unfold case; unfold_op.  eapply2 star_opt_beta.\n  (* 2 *)\n  inversion H; subst. unfold fold_left.  unfold case; unfold_op. case o. \n  eapply transitive_red. eapply2 star_opt_beta. \n  unfold subst; rewrite ! subst_rec_app. \nrewrite subst_rec_closed. 2: rewrite Fop_closed; omega. \nunfold subst_rec; fold subst_rec. insert_Ref_out. unfold lift, lift_rec; fold lift_rec.\nrewrite subst_rec_lift_rec; try omega. rewrite lift_rec_null. \neapply transitive_red. eapply2 factor_leaf.  \n  eval_tac.   (* 1 *) \n  unfold case; fold case. \nassert(is_program (App P1 P2) = true \\/ is_program(App P1 P2) <> true)\nby decide equality. \ninversion H0. \nrewrite H1. \neapply transitive_red. \neapply2 star_opt_beta.\nunfold subst; rewrite ! subst_rec_app. \nrewrite subst_rec_closed. 2: rewrite equal_comb_closed; omega. \nunfold lift; rewrite subst_rec_lift_rec; try omega. \nunfold subst_rec; fold subst_rec.\ninsert_Ref_out. unfold lift; rewrite ! lift_rec_null.   \nunfold swap; unfold_op. unfold subst, subst_rec; fold subst_rec. insert_Ref_out. \nunfold lift; rewrite ! lift_rec_null.\nassert(program (App P1 P2)) by eapply2 program_is_program. \ninversion H2; subst. simpl in H4; max_out. \nrewrite ! subst_rec_closed; try omega.   \nassert(N = App P1 P2 /\\ sigma = nil). \neapply2 program_matching3. simpl; auto. rewrite H5; rewrite H6; auto. \ninversion H4; subst. \neapply transitive_red. eapply preserves_app_sf_red. \neapply preserves_app_sf_red. \neapply2 equal_programs. auto. auto. \nunfold_op; eval_tac.\n(* 1 *)  \nassert(is_program (App P1 P2) = false) by \neapply2 not_true_iff_false. \nrewrite H2. \n(* 1 *) \n  unfold case_app. \neapply transitive_red. eapply2 star_opt_beta. \nunfold subst; rewrite ! subst_rec_app. \nrewrite subst_rec_closed. 2: simpl; auto. \nunfold subst_rec; fold subst_rec. insert_Ref_out. unfold lift; rewrite lift_rec_null. \nrewrite subst_rec_lift_rec; try omega.\nrewrite subst_rec_closed. 2: simpl; auto. \ninversion H; subst. inversion H6; subst.\n(* 2 *)  \neapply transitive_red. eapply preserves_app_sf_red. eapply2 factor_stem.\nunfold swap; simpl. insert_Ref_out. unfold lift; rewrite lift_rec_null. auto. \nrewrite ! lift_rec_preserves_star_opt.    \n  eapply transitive_red. eapply preserves_app_sf_red. eapply2 star_opt_beta2. auto. \nunfold subst; simpl. insert_Ref_out.\nunfold lift; rewrite ! lift_rec_null.\nrewrite ! subst_rec_lift_rec; try omega.\nrewrite ! lift_rec_null. \neapply transitive_red. eapply preserves_app_sf_red. \n  eapply preserves_app_sf_red. eapply preserves_app_sf_red. \n  eapply preserves_app_sf_red.\neapply2 IHP1. all: auto. \neapply transitive_red. eapply preserves_app_sf_red. \n  eapply preserves_app_sf_red. eapply preserves_app_sf_red. \n   eapply succ_red. eapply2 k_red. all: auto.  \nrewrite fold_subst_list. rewrite fold_subst_list. rewrite fold_subst_list.\neapply transitive_red. eapply list_subst_preserves_sf_red. \neapply preserves_app_sf_red. eapply preserves_app_sf_red.\neapply IHP2. eapply2 matching_lift. \nunfold lift; simpl. auto. unfold lift; simpl. auto. \neapply transitive_red. eapply list_subst_preserves_sf_red. \nunfold_op.  eapply transitive_red. eapply preserves_app_sf_red. \neapply succ_red. eapply2 k_red.  auto. auto. auto. \nrepeat rewrite list_subst_preserves_app. repeat rewrite list_subst_preserves_op. \neval_tac.   repeat eapply2 preserves_app_sf_red.\nrewrite fold_left_app. auto.\n(* 1 *) \neapply transitive_red. eapply preserves_app_sf_red. eapply2 factor_fork.\nunfold swap; simpl. insert_Ref_out. unfold lift; rewrite lift_rec_null. auto. \nrewrite ! lift_rec_preserves_star_opt.    \n  eapply transitive_red. eapply preserves_app_sf_red. eapply2 star_opt_beta2. auto. \nunfold subst; simpl. insert_Ref_out.\nunfold lift; rewrite ! lift_rec_null.\nrewrite ! subst_rec_lift_rec; try omega.\nrewrite ! lift_rec_null. \neapply transitive_red. eapply preserves_app_sf_red. \n  eapply preserves_app_sf_red. eapply preserves_app_sf_red. \n  eapply preserves_app_sf_red.\neapply2 IHP1. all: auto. \neapply transitive_red. eapply preserves_app_sf_red. \n  eapply preserves_app_sf_red. eapply preserves_app_sf_red. \n   eapply succ_red. eapply2 k_red. all: auto.  \nrewrite fold_subst_list. rewrite fold_subst_list. rewrite fold_subst_list.\neapply transitive_red. eapply list_subst_preserves_sf_red. \neapply preserves_app_sf_red. eapply preserves_app_sf_red.\neapply IHP2. eapply2 matching_lift. \nunfold lift; simpl. auto. unfold lift; simpl. auto. \neapply transitive_red. eapply list_subst_preserves_sf_red. \nunfold_op.  eapply transitive_red. eapply preserves_app_sf_red. \neapply succ_red. eapply2 k_red.  auto. auto. auto. \nrepeat rewrite list_subst_preserves_app. repeat rewrite list_subst_preserves_op. \neval_tac.   repeat eapply2 preserves_app_sf_red.\nrewrite fold_left_app. auto.\n \nQed. \n\n\n\nLemma case_normal: \nforall P M, normal P -> normal M -> normal (case P M).\nProof.\ninduction P; intros; unfold case. \n(* 3 *) \neapply2 star_opt_normal. unfold_op; auto. \n(* 2 *) \nrewrite star_opt_occurs_true. \nunfold_op; eapply2 nf_compound. \neapply2 nf_compound. \neapply2 nf_compound. \neapply2 star_opt_normal.\nunfold swap. \nunfold_op; repeat eapply2 nf_compound.\nrewrite star_opt_occurs_true. \nunfold_op; eapply2 nf_compound. \neapply2 nf_compound. \neapply2 nf_compound. \neapply2 star_opt_normal.\nrepeat eapply2 nf_compound.\nunfold lift. eapply2 lift_rec_preserves_normal. \n(* 6 *) \nunfold star_opt. \nrewrite occurs_closed. \nunfold subst. rewrite subst_rec_closed. \neapply2 Fop_normal. \nrewrite Fop_closed; auto. \neapply2 Fop_closed. \n(* 5 *) \nunfold occurs; fold occurs. unfold eqnat. omega. congruence. \n(* 3 *) \nunfold swap, occurs; fold occurs. unfold eqnat. omega. congruence. \n(* 1 *) \ncase (is_program (App P1 P2)). \nrewrite star_opt_occurs_true. \nunfold star_opt at 1.  unfold occurs. unfold swap. unfold_op. unfold plus, eqnat. \nsubst_tac. eapply2 nf_compound. repeat eapply2 nf_compound.\n(* 4 *)\n2: unfold swap; unfold_op; rewrite ! occurs_app.\n2: replace (occurs 0 (Ref 0)) with 1 by auto. 2:omega. \n2: unfold swap; congruence.\n(* 2 *)\nrewrite star_opt_occurs_true.\nall: cycle 1.\nrewrite ! occurs_app. unfold occurs at 2. unfold eqnat. \nomega. congruence.\nfold case.\nall: cycle -1.\n(* 2 *)\neapply2 nf_compound. eapply2 nf_compound. eapply2 nf_compound. \neapply2 star_opt_normal. \neapply2 nf_compound. \nunfold lift; eapply2 lift_rec_preserves_normal. \nrewrite star_opt_occurs_true.\n2: rewrite ! occurs_app. 2: unfold occurs at 2; unfold eqnat; omega.\n2: congruence.  \napply nf_compound. \napply nf_compound. auto. \napply nf_compound.  auto. \neapply2 star_opt_normal. \nauto. auto. 2: auto.\nunfold star_opt, occurs. fold star_opt.\nrewrite occurs_closed.  2: apply equal_comb_closed. \nunfold subst; rewrite subst_rec_closed.\napply equal_comb_normal.\nrewrite equal_comb_closed. auto.\n(* 1 *)\nunfold case_app. \nrewrite star_opt_occurs_true. \n2: unfold swap, occurs; unfold_op; unfold eqnat; omega.\n2: unfold swap; congruence. \neapply2 nf_compound.\neapply2 nf_compound.\neapply2 nf_compound.\ncbv; auto. repeat eapply2 nf_compound.\nrewrite star_opt_occurs_true. \n2: unfold occurs; unfold_op; unfold eqnat; omega.\n2: case(star_opt\n      (star_opt\n         (App\n            (App\n               (App (App (lift 2 (case P1 (case P2 (App k_op (App k_op M))))) (Ref 1))\n                    (App k_op (App k_op (App k_op i_op)))) (Ref 0)) (App k_op i_op))));\n  unfold lift, lift_rec; try congruence. \n2: intro; case n; relocate_lt; simpl. 2: congruence.\n2: intro; relocate_lt; simpl. 2: congruence.\n(* 1 *)\neapply2 nf_compound.\neapply2 nf_compound.\neapply2 nf_compound.\nall: cycle 1.\nrewrite star_opt_occurs_true. \n2: unfold swap, occurs; unfold_op; unfold eqnat; omega.\n2: unfold_op; congruence. \neapply2 nf_compound.\nrewrite star_opt_closed; repeat eapply2 nf_compound. all: unfold node; auto. \nunfold_op; auto. rewrite star_opt_eta.\n2: apply occurs_closed. 2: apply Fop_closed.\nunfold subst; rewrite subst_rec_closed. apply Fop_normal. rewrite Fop_closed; auto.\n(* 1 *)\nrewrite star_opt_occurs_true.\n2: unfold occurs; fold occurs. 2: unfold eqnat; omega. 2: discriminate. \nrewrite (star_opt_closed (App k_op i_op)). \n2: unfold_op; auto.\napply star_opt_normal.\nunfold lift. apply lift_rec_preserves_normal.\nunfold star_opt at 2. fold star_opt. unfold_op. \nreplace (occurs 0\n        (App\n           (App\n              (lift_rec\n                 (case P1\n                    (case P2 (App (App (Op Node) (Op Node)) (App (App (Op Node) (Op Node)) M))))\n                 0 2) (Ref 1))\n           (App (App (Op Node) (Op Node))\n              (App (App (Op Node) (Op Node))\n                 (App (App (Op Node) (Op Node))\n                    (App (App (Op Node) (App (Op Node) (Op Node))) (App (Op Node) (Op Node)))))))\n        ) with 0.\nall: cycle 1.\nrewrite ! occurs_app. \nrewrite ! occurs_op. \nrewrite occurs_lift_rec_zero. \ncbv; auto.\n(* 1 *)\nsubst_tac. \nrewrite star_opt_occurs_true. \n2: unfold occurs, eqnat; omega. \n2: discriminate. \n(* 1 *)\neapply2 nf_compound. eapply2 nf_compound. eapply2 nf_compound.\n2: apply star_opt_normal. 2: repeat eapply2 nf_compound. \nrewrite star_opt_occurs_true. \n2: unfold occurs, eqnat; omega. \n2: discriminate. \n(* 1 *)\nrepeat eapply2 nf_compound.\nall: unfold node; auto.\nunfold_op; auto.\nrewrite star_opt_eta.\n2: rewrite occurs_lift_rec_zero; auto.\nsubst_tac.\ninversion H. \napply IHP1; auto. apply IHP1; auto.\nQed.\n\n\n\n", "meta": {"author": "Barry-Jay", "repo": "Intensional-computation", "sha": "de09d3e646c1ea50127c5033b46576d8b4773259", "save_path": "github-repos/coq/Barry-Jay-Intensional-computation", "path": "github-repos/coq/Barry-Jay-Intensional-computation/Intensional-computation-de09d3e646c1ea50127c5033b46576d8b4773259/Tree_calculus/Case.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.269752915999331}}
{"text": "\n(************************************************\n *          Row Subtyping - Soundness           *\n *                 Leo White                    *\n ************************************************)\n\nSet Implicit Arguments.\nRequire Import Coq.Arith.PeanoNat LibLN Utilities Cofinite\n        Disjoint Definitions Opening FreeVars Environments\n        Subst Wellformedness Weakening Substitution Kinding\n        Subtyping Inversion Coercible Typing.\n\n(* *************************************************************** *)\n(** * Values do not reduce *)\n\nLemma values_do_not_reduce : forall t t' V V',\n    value t ->\n    ~ red t V t' V'.\nProof.\n  introv Hv.\n  unfold not.\n  introv Hr.\n  generalize dependent t'.\n  generalize dependent V.\n  generalize dependent V'.\n  induction Hv; introv Hr;\n    inversion Hr; subst; eauto.\nQed.\n\n(* *************************************************************** *)\n(** * Preservation *)\n\nLemma preservation : preservation.\nProof.\n  unfold preservation.\n  introv He Hd Hp Hst Ht Hs Hr.\n  generalize dependent T.\n  generalize dependent P.\n  induction Hr; introv Hp Hs Ht.\n  - invert_typing Ht He Hd Hp.\n    + assert (value t1) as Hvl by assumption.\n      exfalso.\n      apply (values_do_not_reduce Hvl Hr).\n    + assert (typing v E D P t1 T1) as Ht2 by auto.\n      destruct (IHHr Hst _ Hp Hs _ Ht2)\n        as [P' [Hex [Hv' [Hst' [Ht' Hs']]]]].\n      exists P'.\n      splits; auto.\n      apply typing_let with (L := L \\u dom D \\u dom E) (T1 := T1);\n        eauto using output_typing.\n      introv Hn.\n      apply typing_extend_store_type with (P := P);\n        eauto using typing_coercible with wellformed.\n  - exists P.\n    splits; auto.\n    invert_typing Ht He Hd Hp.\n    + pick_fresh x.\n      rewrite trm_subst_single_intro with (x := x);\n        auto with wellformed.\n      apply typing_trm_subst_single_l with (M := M);\n        eauto using typing_coercible, typing_scheme_c'\n          with wellformed.\n    + assert (kinding E empty T1 knd_type)\n        by eauto using output_typing with wellformed.\n      pick_fresh x.\n      rewrite trm_subst_single_intro with (x := x);\n        auto with wellformed.\n      apply typing_trm_subst_empty_l with (T2 := T1);\n        eauto using typing_coercible with wellformed.\n  - invert_typing Ht He Hd Hp.\n    assert (typing v E D P t1 (typ_arrow T1 T2)) as Ht2 by auto.\n    destruct (IHHr Hst _ Hp Hs _ Ht2)\n      as [P' [Hex [Hv' [Hst' [Ht' Hs']]]]].\n    exists P'.\n    splits; auto.\n    eauto using typing_coercible, typing_extend_store_type\n      with wellformed.\n  - invert_typing Ht He Hd Hp.\n    assert (typing v E D P t2 T1) as Ht2 by auto.\n    destruct (IHHr Hst _ Hp Hs _ Ht2)\n      as [P' [Hex [Hv' [Hst' [Ht' Hs']]]]].\n    exists P'.\n    splits; auto.\n    eauto using typing_coercible, typing_extend_store_type\n      with wellformed.\n  - exists P.\n    splits; auto.\n    invert_typing Ht He Hd Hp.\n    assert (typing v E D P (trm_abs t1) (typ_arrow T1 T2))\n      as Ht2 by assumption.\n    invert_typing Ht2 He Hd Hp.\n    pick_fresh x.\n    rewrite trm_subst_single_intro with (x := x);\n      auto with wellformed.\n    assert (coercible v E T3 T2)\n      by eauto using invert_coercible_arrow_right.\n    assert (coercible v E T1 T0)\n      by eauto using invert_coercible_arrow_left.\n    apply typing_trm_subst_empty_l with (T2 := T0);\n      eauto using typing_coercible with wellformed.\n  - exists P.\n    splits; auto.\n    invert_typing Ht He Hd Hp.\n    assert (typing v E D P (trm_fix t1) (typ_arrow T1 T2))\n      as Ht2 by assumption.\n    invert_typing Ht2 He Hd Hp.\n    pick_fresh x.\n    pick_fresh y.\n    rewrite trm_subst_intro with (xs := cons y (x::nil));\n      auto with wellformed.\n    assert (coercible v E T3 T2)\n      by eauto using invert_coercible_arrow_right.\n    assert (coercible v E T1 T0)\n      by eauto using invert_coercible_arrow_left.\n    apply typing_trm_subst_empty2_l\n      with (T2 := typ_arrow T0 T3) (T3 := T0);\n      eauto using typing_coercible with wellformed.\n  - invert_typing Ht He Hd Hp.\n    assert (typing v E D P t T1) as Ht2 by auto.\n    destruct (IHHr Hst _ Hp Hs _ Ht2)\n      as [P' [Hex [Hv' [Hst' [Ht' Hs']]]]].\n    exists P'.\n    splits; auto.\n    eauto using typing_coercible.\n  - invert_typing Ht He Hd Hp.\n    assert (typing v E D P t1 (typ_variant T1)) as Ht2 by auto.\n    destruct (IHHr Hst _ Hp Hs _ Ht2)\n      as [P' [Hex [Hv' [Hst' [Ht' Hs']]]]].\n    exists P'.\n    splits; auto.\n    apply typing_coercible with T4; auto.\n    apply typing_match with (L := L \\u dom E \\u dom D)\n      (T1 := T1) (T2 := T2) (T3 := T3) (T4 := T4);\n      eauto using typing_extend_store_type with wellformed.\n  - subst.\n    exists P.\n    splits; auto.\n    invert_typing Ht He Hd Hp.\n    assert\n      (typing v E D P (trm_constructor c2 t1) (typ_variant T1))\n      as Ht2 by assumption.\n    invert_typing Ht2 He Hd Hp.\n    assert (valid_tenv_extension v E empty) by auto.\n    assert (kinding E empty T2 knd_row_all)\n      by auto with kinding.\n    pick_fresh x.\n    rewrite trm_subst_single_intro with (x := x);\n      auto with wellformed.\n    apply typing_trm_subst_empty_l with (T2 := typ_variant T2);\n      eauto using typing_coercible with wellformed.\n    apply typing_constructor with (T1 := T0); auto.\n    subst_subtype (typ_constructor c2 T0).\n    subst_subtype ((typ_proj CSet.universe (CSet.singleton c2) T2)).\n    assert (subtype v E empty nil nil T5 T1 knd_row_all) as Hs2\n      by (apply invert_coercible_variant; auto).\n    rewrite Hs2.\n    sreflexivity.\n  - exists P.\n    splits; auto.\n    invert_typing Ht He Hd Hp.\n    assert\n      (typing v E D P (trm_constructor c1 t1) (typ_variant T1))\n      as Ht2 by assumption.\n    invert_typing Ht2 He Hd Hp.\n    assert (valid_tenv_extension v E empty) by auto.\n    assert (kinding E empty T3 knd_row_all)\n      by auto with kinding.\n    pick_fresh x.\n    rewrite trm_subst_single_intro with (x := x);\n      auto with wellformed.\n    apply typing_trm_subst_empty_l with (T2 := typ_variant T3);\n      eauto using typing_coercible with wellformed.\n    apply typing_constructor with (T1 := T0); auto.\n    subst_subtype (typ_constructor c1 T0).\n    assert (subtype v E empty nil nil T5 T1 knd_row_all) as Hs2\n      by (apply invert_coercible_variant; auto).\n    rewrite Hs2.\n    apply subtype_proj_subset with (cs3 := CSet.cosingleton c2);\n      auto with csetdec.\n  - invert_typing Ht He Hd Hp.\n    assert (typing v E D P t1 (typ_variant T1)) as Ht2 by auto.\n    destruct (IHHr Hst _ Hp Hs _ Ht2)\n      as [P' [Hex [Hv' [Hst' [Ht' Hs']]]]].\n    exists P'.\n    splits; auto.\n    apply typing_coercible with T3; auto.\n    apply typing_destruct with (L := L \\u dom D)\n      (T1 := T1) (T2 := T2); auto.\n    eauto using typing_extend_store_type with wellformed.\n  - subst.\n    exists P.\n    splits; auto.\n    invert_typing Ht He Hd Hp.\n    assert\n      (typing v E D P (trm_constructor c2 t1) (typ_variant T1))\n      as Ht2 by assumption.\n    invert_typing Ht2 He Hd Hp.\n    pick_fresh x.\n    rewrite trm_subst_single_intro with (x := x);\n      auto with wellformed.\n    assert (coercible v E T0 T2)\n      by eauto using invert_coercible_variant_constructor.\n    apply typing_trm_subst_empty_l with (T2 := T2);\n      eauto using typing_coercible with wellformed.\n  - invert_typing Ht He Hd Hp.\n    assert (typing v E D P t (typ_variant T1)) as Ht2 by auto.\n    destruct (IHHr Hst _ Hp Hs _ Ht2)\n      as [P' [Hex [Hv' [Hst' [Ht' Hs']]]]].\n    exists P'.\n    splits; auto.\n    eauto using typing_coercible.\n  - invert_typing Ht He Hd Hp.\n    assert (typing v E D P t1 typ_unit) as Ht2 by auto.\n    destruct (IHHr Hst _ Hp Hs _ Ht2)\n      as [P' [Hex [Hv' [Hst' [Ht' Hs']]]]].\n    exists P'.\n    splits; auto.\n    eauto using typing_coercible, typing_extend_store_type\n      with wellformed.\n  - invert_typing Ht He Hd Hp.\n    exists P.\n    splits; auto.\n    eauto using typing_coercible.\n  - invert_typing Ht He Hd Hp.\n    assert (typing v E D P t1 T1) as Ht2 by auto.\n    destruct (IHHr Hst _ Hp Hs _ Ht2)\n      as [P' [Hex [Hv' [Hst' [Ht' Hs']]]]].\n    exists P'.\n    splits; auto.\n    eauto using typing_coercible, typing_extend_store_type\n      with wellformed.\n  - invert_typing Ht He Hd Hp.\n    assert (typing v E D P t2 T2) as Ht2 by auto.\n    destruct (IHHr Hst _ Hp Hs _ Ht2)\n      as [P' [Hex [Hv' [Hst' [Ht' Hs']]]]].\n    exists P'.\n    splits; auto.\n    eauto using typing_coercible, typing_extend_store_type\n      with wellformed.\n  - invert_typing Ht He Hd Hp.\n    assert (typing v E D P t (typ_prod T1 T2)) as Ht2 by auto.\n    destruct (IHHr Hst _ Hp Hs _ Ht2)\n      as [P' [Hex [Hv' [Hst' [Ht' Hs']]]]].\n    exists P'.\n    splits; auto.\n    eauto using typing_coercible.\n  - exists P.\n    splits; auto.\n    invert_typing Ht He Hd Hp.\n    assert\n      (typing v E D P (trm_prod t1 t2) (typ_prod T1 T2))\n      as Ht2 by assumption.\n    invert_typing Ht2 He Hd Hp.\n    assert (coercible v E T0 T1)\n      by eauto using invert_coercible_prod_left.\n    eauto using typing_coercible.\n  - invert_typing Ht He Hd Hp.\n    assert (typing v E D P t (typ_prod T1 T2)) as Ht2 by auto.\n    destruct (IHHr Hst _ Hp Hs _ Ht2)\n      as [P' [Hex [Hv' [Hst' [Ht' Hs']]]]].\n    exists P'.\n    splits; auto.\n    eauto using typing_coercible.\n  - exists P.\n    splits; auto.\n    invert_typing Ht He Hd Hp.\n    assert\n      (typing v E D P (trm_prod t1 t2) (typ_prod T1 T2))\n      as Ht2 by assumption.\n    invert_typing Ht2 He Hd Hp.\n    assert (coercible v E T3 T2)\n      by eauto using invert_coercible_prod_right.\n    eauto using typing_coercible.\n  - invert_typing Ht He Hd Hp.\n    assert (typing v E D P t T1) as Ht2 by auto.\n    destruct (IHHr Hst _ Hp Hs _ Ht2)\n      as [P' [Hex [Hv' [Hst' [Ht' Hs']]]]].\n    exists P'.\n    splits; auto.\n    eauto using typing_coercible.\n  - invert_typing Ht He Hd Hp.\n    exists (P & l ~ T1).\n    remember Hs as Hs'.\n    destruct Hs' as [? ? ? ? ? Hsl].\n    destruct (Hsl l).\n    + splits; eauto using typing_store_ref, typing_coercible,\n        output_typing with wellformed. \n    + exfalso. eauto using binds_fresh_inv.\n  - invert_typing Ht He Hd Hp.\n    assert (typing v E D P t (typ_ref T1)) as Ht2 by auto.\n    destruct (IHHr Hst _ Hp Hs _ Ht2)\n      as [P' [Hex [Hv' [Hst' [Ht' Hs']]]]].\n    exists P'.\n    splits; eauto using typing_coercible.\n  - exists P.\n    splits; auto.\n    invert_typing Ht He Hd Hp.\n    assert (typing v E D P (trm_loc l) (typ_ref T1)) as Ht2\n        by assumption.\n    invert_typing Ht2 He Hd Hp.\n    destruct Hs as [? ? ? ? ? Hsl].\n    destruct (Hsl l).\n    + exfalso. eauto using binds_fresh_inv.\n    + replace t0 with t in *\n        by eauto using binds_functional.\n      replace T0 with T2 in *\n        by eauto using binds_functional.\n      assert (coercible v E T2 T1)\n        by eauto using invert_coercible_ref_covariant.\n      eauto using typing_coercible.\n  - invert_typing Ht He Hd Hp.\n    assert (typing v E D P t1 (typ_ref T1)) as Ht2 by auto.\n    destruct (IHHr Hst _ Hp Hs _ Ht2)\n      as [P' [Hex [Hv' [Hst' [Ht' Hs']]]]].\n    exists P'.\n    splits; auto.\n    eauto using typing_coercible,\n      typing_extend_store_type with wellformed.\n  - invert_typing Ht He Hd Hp.\n    assert (typing v E D P t2 T1) as Ht2 by auto.\n    destruct (IHHr Hst _ Hp Hs _ Ht2)\n      as [P' [Hex [Hv' [Hst' [Ht' Hs']]]]].\n    exists P'.\n    splits; auto.\n    eauto using typing_coercible,\n      typing_extend_store_type with wellformed.\n  - exists P.\n    invert_typing Ht He Hd Hp.\n    assert (typing v E D P (trm_loc l) (typ_ref T1)) as Ht2\n        by assumption.\n    invert_typing Ht2 He Hd Hp.\n    splits; eauto using typing_coercible.\n    assert (coercible v E T1 T0) as Hc\n      by eauto using invert_coercible_ref_contravariant.\n    eauto using typing_store_set, typing_coercible\n      with wellformed kinding.\nQed.\n\n(* *************************************************************** *)\n(** * Progress *)\n\nLemma progress : progress.\nProof.\n  unfold progress.\n  introv He Hp Hv Ht Hs.\n  assert (valid_env v E empty) as Hd by auto.\n  remember empty as D.\n  assert (term t) as Htrm by auto with wellformed.\n  induction_with_envs Ht He Hd Hp; subst; auto.\n  - exfalso; eauto using binds_empty_inv.\n  - inversion Htrm; subst.\n    assert (value t1 \\/ (exists t1' V1', red t1 V t1' V1'))\n      as IH1 by auto.\n    assert (value t2 \\/ (exists t2' V2', red t2 V t2' V2'))\n      as IH2 by auto.\n    destruct IH1 as [Hv1|[t1' [V1' He1]]];\n      destruct IH2 as [Hv2|[t2' [V2' He2]]];\n        eauto.\n    eapply invert_value_arrow with (t := t1); try eassumption;\n      intros; subst; eauto.\n  - pick_freshes_gen L (sch_arity M) Xs.\n    assert (value t1 \\/ (exists t1' V1', red t1 V t1' V1'))\n      as IH1 by eauto.\n    destruct IH1 as [Hv1|[t1' [V1' He1]]]; eauto 6.\n  - inversion Htrm; subst.\n    assert (value t1 \\/ (exists t1' V1', red t1 V t1' V1'))\n      as IH1 by eauto.\n    destruct IH1 as [Hv1|[t1' [V1' He1]]]; eauto.\n  - inversion Htrm; subst.\n    assert (value t \\/ (exists t' V', red t V t' V'))\n      as IH by eauto.\n    destruct IH as [Hv1|[t' [V' He1]]]; eauto.\n  - inversion Htrm; subst.\n    assert (value t1 \\/ (exists t1' V1', red t1 V t1' V1'))\n      as IH1 by eauto.\n    destruct IH1 as [Hv1|[t1' [V1' He1]]]; eauto.\n    eapply invert_value_variant with (t := t1); try eassumption;\n      intros; subst.\n    destruct (Nat.eq_dec c c0); subst; eauto.\n  - inversion Htrm; subst.\n    assert (value t1 \\/ (exists t1' V1', red t1 V t1' V1'))\n      as IH1 by eauto.\n    destruct IH1 as [Hv1|[t1' [V1' He1]]]; eauto.\n    eapply invert_value_variant with (t := t1); try eassumption;\n      intros; subst.    \n    destruct (Nat.eq_dec c c0); subst; eauto.\n    exfalso.\n    eapply typing_constructor_inv\n      with (c := c0) (t1 := t0); try eassumption; intros.\n    apply invert_subtype_constructor_bot\n      with (v := v) (E1 := E) (E2 := empty) (c := c0)\n           (cs := CSet.singleton c0) (T1 := T0); auto.\n    assert (subtype v E empty nil nil (typ_constructor c0 T0)\n             (typ_proj CSet.universe (CSet.singleton c0) T4)\n             (knd_row (CSet.singleton c0)))\n      as Hs1 by assumption.\n    assert (subtype v E empty nil nil T4 T1 knd_row_all)\n      as Hs2 by auto using invert_coercible_variant.\n    assert (subtype v E empty nil nil\n              (typ_proj CSet.universe (CSet.cosingleton c) T1)\n              (typ_bot (knd_row (CSet.cosingleton c)))\n              (knd_row (CSet.cosingleton c)))\n      as Hs3 by assumption.\n    apply subtype_proj_subset_bottom\n      with (cs3 := CSet.singleton c0) in Hs3; auto with csetdec.\n    rewrite Hs1.\n    rewrite Hs2.\n    rewrite Hs3.\n    sreflexivity.\n  - inversion Htrm; subst.\n    assert (value t1 \\/ (exists t1' V1', red t1 V t1' V1'))\n      as IH1 by eauto.\n    destruct IH1 as [Hv1|[t1' [V1' He1]]]; eauto.\n    eapply invert_value_variant with (t := t1);\n      try eassumption; intros; subst.\n    exfalso.\n    eapply typing_constructor_inv\n      with (c := c) (t1 := t0); try eassumption; intros.\n    apply invert_subtype_constructor_bot\n      with (v := v) (E1 := E) (E2 := empty) (c := c)\n           (cs := CSet.singleton c) (T1 := T0); auto.\n    assert (subtype v E empty nil nil (typ_constructor c T0)\n             (typ_proj CSet.universe (CSet.singleton c) T3)\n             (knd_row (CSet.singleton c)))\n      as Hs1 by assumption.\n    assert (subtype v E empty nil nil T3 T1 knd_row_all)\n      as Hs2 by auto using invert_coercible_variant.\n    assert (subtype v E empty nil nil\n              T1 (typ_bot knd_row_all) knd_row_all)\n      as Hs3 by assumption.\n    rewrite Hs1.\n    rewrite Hs2.\n    rewrite Hs3.\n    rewrite type_equal_proj_bot; auto with csetdec.\n    sreflexivity.\n  - inversion Htrm; subst.\n    assert (value t1 \\/ (exists t1' V1', red t1 V t1' V1'))\n      as IH1 by auto.   \n    destruct IH1 as [Hv1|[t1' [V1' He1]]]; eauto.\n    eapply invert_value_unit; try eassumption;\n      intros; subst; eauto.\n  - inversion Htrm; subst.\n    assert (value t1 \\/ (exists t1' V1', red t1 V t1' V1'))\n      as IH1 by auto.\n    assert (value t2 \\/ (exists t2' V2', red t2 V t2' V2'))\n      as IH2 by auto.\n    destruct IH1 as [Hv1|[t1' [V1' He1]]];\n      destruct IH2 as [Hv2|[t2' [V2' He2]]];\n        eauto.\n  - inversion Htrm; subst.\n    assert (value t1 \\/ (exists t1' V1', red t1 V t1' V1'))\n      as IH1 by eauto.\n    destruct IH1 as [Hv1|[t1' [V1' He1]]]; eauto.\n    eapply invert_value_prod with (t := t1); try eassumption;\n      intros; subst; eauto.\n  - inversion Htrm; subst.\n    assert (value t1 \\/ (exists t1' V1', red t1 V t1' V1'))\n      as IH1 by eauto.\n    destruct IH1 as [Hv1|[t1' [V1' He1]]]; eauto.\n    eapply invert_value_prod with (t := t1); try eassumption;\n      intros; subst; eauto.\n  - inversion Htrm; subst.\n    assert (value t1 \\/ (exists t1' V1', red t1 V t1' V1'))\n      as IH1 by eauto.\n    destruct IH1 as [Hv1|[t1' [V1' He1]]]; eauto.\n    pick_fresh_gen (dom V) l; eauto.\n  - inversion Htrm; subst.\n    assert (value t1 \\/ (exists t1' V1', red t1 V t1' V1'))\n      as IH1 by eauto.\n    destruct IH1 as [Hv1|[t1' [V1' He1]]]; eauto.\n    eapply invert_value_ref with (t := t1); try eassumption;\n      intros; subst.\n    eapply typing_loc_inv with (l := l); try eassumption;\n      intros.\n    destruct Hs as [? ? ? ? ? Hsl].\n    destruct (Hsl l).\n    + exfalso; eauto using binds_fresh_inv.\n    + eauto.\n  - inversion Htrm; subst.\n    assert (value t1 \\/ (exists t1' V1', red t1 V t1' V1'))\n      as IH1 by eauto.\n    assert (value t2 \\/ (exists t2' V2', red t2 V t2' V2'))\n      as IH2 by auto.\n    destruct IH1 as [Hv1|[t1' [V1' He1]]];\n      destruct IH2 as [Hv2|[t2' [V2' He2]]]; eauto.\n    eapply invert_value_ref with (t := t1); try eassumption;\n      intros; subst.\n    eapply typing_loc_inv with (l := l); try eassumption;\n      intros.\n    destruct Hs as [? ? ? ? ? Hsl].\n    destruct (Hsl l).\n    + exfalso; eauto using binds_fresh_inv.\n    + eauto 6 using binds_in_dom.\nQed.\n", "meta": {"author": "lpw25", "repo": "row-subtyping", "sha": "b7e1d328387066600cf171fdd51c6eac5c06466e", "save_path": "github-repos/coq/lpw25-row-subtyping", "path": "github-repos/coq/lpw25-row-subtyping/row-subtyping-b7e1d328387066600cf171fdd51c6eac5c06466e/proof/Soundness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.269752915999331}}
{"text": "(* Cyclone Semantics using TLC/LN in Coq Version 4 *)\n(* \"SAFE PROGRAMMING AT THE C LEVEL OF ABSTRACTION\".   Daniel Grossman, August 2003 *)\n(* Lemmas for WFDG  *)\n(* Brian Milnes 2016 *)\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_Admit_Environment.\nClose Scope list_scope.\nImport LibEnvNotations.\nImport LVPE.LibVarPathEnvNotations.\n\nLemma WFDG_ok_delta:\n  forall d g,\n    WFDG d g ->\n    ok d.\nProof.\n  intros.\n  inversion* H.\nQed.\nLtac WFDG_ok_delta :=\n  match goal with\n    | H : WFDG ?d ?g' |- ok ?d => apply WFDG_ok_delta with (g:= g')\n  end.\nHint Extern 1 (ok _) => try WFDG_ok_delta.\n\nLemma WFDG_ok_gamma:\n  forall d g,\n    WFDG d g ->\n    ok g.\nProof.\n  intros.\n  inversion H; subst.\n  constructor.\n  constructor.\n  assumption.\n  apply* get_none_inv.\nQed.\nLtac WFDG_ok_gamma :=\n  match goal with\n    | H : WFDG ?d' ?g |- ok ?g => apply WFDG_ok_gamma with (d:=d')\n  end.\nHint Extern 1 (ok _) => try WFDG_ok_gamma.\n\nLemma WFDG_gamma_K:\n  forall d g, \n    WFDG d g ->\n    forall x tau, \n      get x g = Some tau ->\n      K d tau A.\nProof.\n  introv WFDGd.\n  induction WFDGd; intros.\n  apply binds_empty_inv in H0.\n  inversion H0.\n  specialize (IHWFDGd x0 tau0).\n  unfold binds in *.\n  destruct(classicT(x0 = x)); subst.\n  rewrite get_push in H3.\n  case_var.\n  inversion H3; subst; assumption.\n  rewrite get_push in H3.\n  case_var.\n  auto.\nQed.\nLtac WFDG_gamma_K :=\n  match goal with \n   | H:  WFDG ?d' ?g', \n     I: get ?x' ?g' = Some ?tau'\n   |- K ?d' ?tau' A =>\n    apply WFDG_gamma_K with (d:=d') (g:=g') (x:=x') (tau:=tau')\nend.\nHint Extern 1 (K _ _ A) => WFDG_gamma_K.\n\nLemma WFDG_gamma_weakening:\n  forall d g y tau, \n    y \\notin (fv_gamma g) ->\n    K d tau A ->\n    WFDG d g ->\n    WFDG d (g & (y ~ tau)).\nProof.\n  introv NI WFd.\n  auto.\nQed.\nLtac WFDG_gamma_weakening :=\n  match goal with\n    | H: K ?d' ?tau' A, \n      I: WFDG ?d' ?g' \n    |-  WFDG ?d' (?g' & (?y' ~ ?tau')) =>\n      apply WFDG_gamma_weakening with (tau:=tau');\n      notin_solve\n  end.\nHint Extern 1 (WFDG _ (_ & (_ ~ _))) => WFDG_gamma_weakening.\n\nLemma WFDG_delta_weakening:\n  forall alpha d g k, \n    alpha \\notin fv_delta d ->\n    WFDG d g ->\n    WFDG (d & alpha ~ k) g.\nProof.\n  lets: WFDG_gamma_weakening.\n  introv ANI WFDGd.\n  induction WFDGd; auto.\n  assert(alpha \\notin fv_delta d).\n  auto.\n  apply IHWFDGd in H4.\n  constructor; try assumption.\n  constructor; try assumption.\n  apply A_1_Context_Weakening_1 with (d:= d); try assumption.\n  auto.\n  auto.\nQed.\nLtac WFDG_delta_weakening :=\n  match goal with\n    | H: ?alpha \\notin _,\n      I: WFDG ?d' ?g'\n    |- WFDG (?d' & ?alpha ~ ?k) ?g' =>\n      apply WFDG_delta_weakening; notin_solve\n  end.\nHint Extern 1 (WFDG (_ & _ ~ _) _) => WFDG_delta_weakening.\n\nLemma WFDG_strength:\n  forall alpha d0 g0 tau,\n  alpha \\notin fv_delta d0 ->\n  alpha \\notin fv_gamma g0 ->\n  WFDG d0 (g0 & alpha ~ tau) ->\n  WFDG d0 g0.\nProof.\n  introv ad ag WFDGd.\n  inversions* WFDGd.\n  apply empty_not_constructed in H.\n  inversion H.\n  apply functional_inversion_env in H.\n  inversion H.\n  subst*.\nQed.\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_WFDG_Lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2697414496826923}}
{"text": "Require Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp Require Import all_ssreflect.\nFrom mathcomp Require Import all_algebra.\n\nRequire Import ProofIrrelevance.\nRequire Import String.\nRequire Import QArith.\nRequire Import Coq.FSets.FMapFacts.\nRequire Import Structures.Orders NArith.\n\nRequire Import OUVerT.strings compile combinators ccombinators\n        OUVerT.numerics OUVerT.dyadic OUVerT.orderedtypes.\n\nRequire Import OUVerT.listlemmas OUVerT.maplemmas.\n(* Boolability is important to our construction of affine games,\n      however, it is non-essential and problematic for more advanced\n      games (e.g. the routing games shown in routing.v)\n\n  It's not hard to preserve boolability with certain combinators,\n  however, it is hard to regain it.\n\n  To work around this we have two layers of modules here:\n    1.) MyOrderedType, used to preserve Boolablity through particular combinators.\n    2.) SimpleMyOrderedType, used to strip away Boolability\n          and its associated requirements\n*)\n\n(* Define the basic extension of OrderedType: MyOrderedType *)\nModule Type MyOrderedType.\n  Include MyOrderedType.\n  Parameter cost_instance : forall N, CCostClass N t.\n  Parameter cost_max : forall N, CCostMaxClass N t.\nEnd MyOrderedType.\n\n(* We extend MyOrderedType with boolability\n    which is preserved under some relation EQ\n    for the construction of affine games *)\nModule Type BoolableMyOrderedType.\n  Include MyOrderedType.\n  Declare Instance boolable : Boolable t.\n  Declare Instance boolableUnit : BoolableUnit boolable.\n  Declare Instance eq' : Eq t.\n  Declare Instance eq_dec' : Eq_Dec eq'.\n  Declare Instance eq_refl' : Eq_Refl eq'.\nEnd BoolableMyOrderedType.\n\n(* SimplifyBoolable strips boolability *)\nModule SimplifyBoolable (A : BoolableMyOrderedType) <: MyOrderedType.\n  Include A.\nEnd SimplifyBoolable.\n\n(* Module OrderedType_of_MyOrderedType (A : MyOrderedType) *)\n(*   <: OrderedType.OrderedType. *)\n(*       Definition t : Type := A.t. *)\n(*       Definition eq := A.eq. *)\n(*       Definition lt := A.lt. *)\n(*       Lemma eq_refl : forall x : t, eq x x. *)\n(*       Proof. by move => x; rewrite /eq -A.eqP. Qed. *)\n(*       Lemma eq_sym : forall x y : t, eq x y -> eq y x. *)\n(*       Proof. by move => x y; rewrite /eq -2!A.eqP. Qed. *)\n(*       Lemma eq_trans : forall x y z : t, eq x y -> eq y z -> eq x z. *)\n(*       Proof. by move => x y z; rewrite /eq -3!A.eqP => -> ->. Qed. *)\n(*       Definition lt_trans := A.lt_trans. *)\n(*       Definition lt_not_eq := A.lt_not_eq. *)\n(*       Definition compare := A.compare. *)\n(*       Definition eq_dec := A.eq_dec. *)\n(* End OrderedType_of_MyOrderedType. *)\n\nModule Type OrderedFinType.\n  Include MyOrderedType.\n  Parameter eq_mixin : Equality.mixin_of t.\n  Parameter choice_mixin : Choice.mixin_of (EqType t eq_mixin).\n  Parameter fin_mixin : Finite.mixin_of (ChoiceType (EqType t eq_mixin) choice_mixin).\nEnd OrderedFinType.\n\nModule MyOrderedType_of_OrderedFinType\n       (A : OrderedFinType) <: MyOrderedType.\n  Include A.                                \nEnd MyOrderedType_of_OrderedFinType.\n\n(**\n  The following provides OrderedType instances for the basic types \n    Unit and Resource\n**)\nModule OrderedUnit <: MyOrderedType.\n  Definition t := Unit.\n  Definition t0 := mkUnit.\n  Definition enumerable  : Enumerable t := _.\n  Definition cost_instance : forall N, CCostClass N t := _.\n  Definition cost_max : forall N, CCostMaxClass N t := _.\n  Definition showable := unitShowable.\n  Definition eq u1 u2 := Unit_eq u1 u2 = true.\n  Definition lt (u1 u2 : Unit) := False.\n  Lemma eq_refl : forall x, eq x x. by []. Qed.\n  Lemma eq_symm : forall x y, eq x y -> eq y x. by []. Qed.\n  Lemma eq_trans : forall x y z, eq x y -> eq y z -> eq x z. by []. Qed.\n  Lemma lt_trans : forall x y z, lt x y -> lt y z -> lt x z. by []. Qed.\n  Lemma lt_not_eq : forall x y, lt x y -> ~ eq x y. by []. Qed.\n  Lemma compare : forall x y, Compare lt eq x y.\n    move => x y; by apply EQ => //. Qed.\n  Definition eq_dec : forall x y, {eq x y} + {~ eq x y}. by left => //. Qed.\n  Lemma eqP : forall x y, x = y <-> eq x y.\n  Proof.\n    move => x y. split; first by [].\n    case: x => H. case y => //.\n  Qed.\nEnd OrderedUnit.\n\nModule BoolableOrderedUnit <: BoolableMyOrderedType.\n  Include OrderedUnit.\n    (* It looks like these aspects are missing from unit games\n      in compile.v.\n     (** ToDo: update unit games to match the construction\n          of the other combinators/games **)\n  *)\n  Definition boolable : Boolable t := fun _ => false.\n  Definition boolableUnit : BoolableUnit boolable := mkUnit.\n  Definition eq' : Eq t := fun x y => True.\n  Lemma eq_refl' : Eq_Refl eq'.\n    Proof. rewrite /Eq_Refl => x //. Qed.\n  Lemma eq_dec' : Eq_Dec eq'.\n    Proof. rewrite /Eq_Dec /eq'=> x y. left. by []. Qed.\nEnd BoolableOrderedUnit.\n\nModule OrderedResource <: MyOrderedType.\n  Definition t := resource.\n  Definition t0 := RYes.\n  Definition enumerable  : Enumerable t := _.\n  Definition cost_instance : forall N, CCostClass N t := _.\n  Definition cost_max : forall N, CCostMaxClass N t := _.\n  Definition showable : Showable t := _.\n  Definition eq r1 r2 := resource_eq r1 r2 = true.\n  Definition lt r1 r2 :=\n    match r1, r2 with\n    | RNo, RNo => False\n    | RNo, RYes => True\n    | RYes, RNo => False\n    | RYes, RYes => False\n    end.\n\n  Lemma eq_refl : forall x, eq x x.\n  Proof. by move => x; rewrite /eq; case: (@resource_eqP x x). Qed.\n\n  Lemma eq_sym : forall x y, eq x y -> eq y x.\n  Proof.\n    move => x y; rewrite /eq.\n    case: (@resource_eqP x y) => // -> _; apply: eq_refl.\n  Qed.\n\n  Lemma eq_trans : forall x y z, eq x y -> eq y z -> eq x z.\n  Proof. by move => x y z; rewrite /eq; case: (@resource_eqP x y) => // ->. Qed.\n\n  Lemma lt_trans : forall x y z, lt x y -> lt y z -> lt x z.\n  Proof. by move => x y z; case: x => //; case: y => //; case: z. Qed.\n\n  Lemma lt_not_eq : forall x y, lt x y -> ~eq x y.\n  Proof. by move => x y; case: x => //; case: y. Qed.\n\n  Lemma compare : forall x y, Compare lt eq x y.\n  Proof.\n    case => //; case => //.\n    { apply: EQ => //. }\n    { apply: GT => //. }\n    { apply: LT => //. }\n    apply: EQ => //.\n  Qed.\n\n  Lemma eq_dec : forall x y, {eq x y} + {~eq x y}.\n  Proof.\n    move => x y; rewrite /eq; case: (@resource_eqP x y).\n    { by move => _; left. }\n      by move => _; right.\n  Qed.\n\n  Lemma eqP : forall x y, x = y <-> eq x y.\n  Proof. by move => x y; rewrite /eq; case: (@resource_eqP x y). Qed.\nEnd OrderedResource.\n\nModule BoolableOrderedResource <: BoolableMyOrderedType.\n  Include OrderedResource.\n  Definition boolable : Boolable t := _.\n  Definition boolableUnit : BoolableUnit boolable := _.\n  Definition eq' : Eq t.\n  unfold Eq.\n  apply eq.\n  Defined.\n  Definition eq_refl' : Eq_Refl eq'.\n  Proof.\n    red; intros; case: x => //.   \n  Defined.\n  Definition eq_dec' : Eq_Dec eq'.\n    red; intros; case: x; case y => //;\n    intuition.\n  Defined.\nEnd BoolableOrderedResource.\n\nModule OrderedFinResource <: OrderedFinType.\n  Include OrderedResource.                              \n  Definition eq_mixin := resource_eqMixin.                              \n  Definition choice_mixin := resource_choiceMixin.\n  Definition fin_mixin := resource_finMixin.\nEnd OrderedFinResource.\n\n\n(* We now begin defining functors for constructing\n    OrderedTypes and BoolableOrderedTypes *)\n\n(** First, we set up those functors which work without boolability **)\n\n  (* Products and their extensions (boolable and fin) *)\nModule OrderedProd (A B : MyOrderedType) <: MyOrderedType.\n  Definition t := (A.t*B.t)%type.\n  Definition t0 := (A.t0, B.t0).\n  Existing Instance A.enumerable.\n  Existing Instance B.enumerable.\n  Existing Instance A.cost_instance.\n  Existing Instance B.cost_instance.\n  Definition enumerable  : Enumerable t := _.\n  Existing Instance A.cost_max.\n  Existing Instance B.cost_max.\n  Existing Instance A.showable.\n  Existing Instance B.showable.\n  Definition cost_instance : forall N, CCostClass N t := _.\n  Definition cost_max : forall N, CCostMaxClass N t := _.\n  Definition show_prod (p : A.t*B.t) : string :=\n    let s1 := to_string p.1 in\n    let s2 := to_string p.2 in\n    append s1 s2.\n  Instance showable : Showable t := mkShowable show_prod.\n  Definition eq p1 p2 : Prop :=\n    (eqProd A.eq B.eq) p1 p2.\n  Definition lt p1 p2 :=\n    match p1, p2 with\n    | (a1, b1), (a2, b2) =>\n      A.lt a1 a2 \\/\n      (A.eq a1 a2 /\\ B.lt b1 b2)\n    end.\n  \n  Lemma lt_trans : forall x y z, lt x y -> lt y z -> lt x z.\n  Proof.\n    case => a b; case => c d; case => e f; rewrite /lt.\n    case => H.\n    { case => H1.\n      { left; by apply: (A.lt_trans _ _ _ H H1). }\n      case: H1 => H2 H3.\n      by move: H2; rewrite -A.eqP => H4; subst e; left. }\n    case: H; rewrite -A.eqP => H1 H2; subst c.\n    case; first by move => H3; left.\n    case => H3 H4; right; split => //.\n    by apply: (B.lt_trans _ _ _ H2 H4).\n  Qed.      \n\n  Lemma lt_not_eq : forall x y, lt x y -> ~eq x y.\n  Proof.\n    case => a b; case => c d; rewrite /lt /eq /=.\n    case.\n    { move => H []H2 H3.\n        by apply: (A.lt_not_eq _ _ H). }\n    case => H H1 []H2 H3.\n    by apply: (B.lt_not_eq _ _ H1).\n  Qed.\n  \n  Lemma compare : forall x y, Compare lt eq x y.\n  Proof.\n    move => x y.\n    case H: (A.compare x.1 y.1) => [lt_pf|eq_pf|gt_pf].\n    { have H2: lt x y.\n      { clear - lt_pf.\n        move: lt_pf; case: x => a b; case: y => c d /= H.\n          by left. }\n      apply: LT H2. }\n    { case: (B.compare x.2 y.2) => [lt_pf'|eq_pf'|gt_pf'].\n      { have H2: lt x y.\n        { clear - eq_pf lt_pf'.\n          move: eq_pf lt_pf'; case: x => a b; case: y => c d /= H H2.\n          right; split => //. }\n        apply: LT H2. }\n      { have H2: eq x y.\n        { rewrite /eq /eqProd. destruct x, y; split => //. }\n        apply: EQ H2. }\n      have H2: lt y x.\n      { clear - eq_pf gt_pf'; move: eq_pf gt_pf'.\n        case: x => a b; case: y => c d /= H H2.\n        right; split => //.\n        by move: H; rewrite -2!A.eqP => ->. }\n      by apply: GT H2. }\n    have H2: lt y x.\n    { clear - gt_pf; move: gt_pf; case: x => a b; case: y => c d /= H.\n      by left. }\n    by apply: GT H2.    \n  Qed.        \n\n  Lemma eq_dec : forall x y, {eq x y} + {~eq x y}.\n  Proof.\n    case => a b; case => c d; rewrite /eq /=.\n    case H2: (A.eq_dec a c) => [pf|pf].\n    { case H3: (B.eq_dec b d) => [pf'|pf'].\n      { left.\n        split => //. }\n      right.\n      case => H4 H5.\n      clear H2 H3.\n        by apply: pf'. }\n    right; case => H3 H4.\n    by clear H2; apply: pf.\n  Qed.    \n\n  Lemma eqP : forall x y, x = y <-> eq x y.\n  Proof.\n    case => a b; case => c d; rewrite /eq /=; split.\n    { case => -> ->; split.\n        by rewrite -A.eqP.\n        by rewrite -B.eqP. }\n    by case; rewrite -A.eqP -B.eqP => -> ->.\n  Qed.\nEnd OrderedProd.\n\nModule OrderedFinProd (X Y : OrderedFinType) <: OrderedFinType.\n  Module A := OrderedProd X Y. \n  Include A.\n  \n  Definition xE := EqType X.t X.eq_mixin.\n  Definition xC := ChoiceType xE X.choice_mixin.\n  Definition xF := FinType xC X.fin_mixin.\n\n  Definition yE := EqType Y.t Y.eq_mixin.\n  Definition yC := ChoiceType yE Y.choice_mixin.\n  Definition yF := FinType yC Y.fin_mixin.\n  \n  Definition eq_mixin := prod_eqMixin xE yE.\n  Definition choice_mixin := prod_choiceMixin xC yC.\n  Definition fin_mixin := prod_finMixin xF yF.\nEnd OrderedFinProd.\n\nModule BoolableOrderedProd (X Y : BoolableMyOrderedType) <: BoolableMyOrderedType.\n  Module SimpX := SimplifyBoolable X.\n  Module SimpY := SimplifyBoolable Y.\n  Module A := OrderedProd SimpX SimpY.\n  Include A.\n  \n  Definition boolable : Boolable t := _.\n  Definition boolableUnit : BoolableUnit boolable := _.\n  Definition eq' : Eq t := _.\n  Definition eq_refl' : Eq_Refl eq' := _.\n  Definition eq_dec' : Eq_Dec eq' := _.\nEnd BoolableOrderedProd.\n\n  (* Sigma Games *)\nModule Type OrderedPredType.\n  Include MyOrderedType.\n  Declare Instance pred : PredClass t.\n  Parameter a0 : t.\n  Parameter a0_pred : pred a0.\nEnd OrderedPredType.\n\n  (** We don't want/need boolability to be preserved for every predicate.\n        For those where it's important to do so, we use the BoolableOrderedPredType **)\nModule Type BoolableOrderedPredType.\n  Include BoolableMyOrderedType.\n\n  Declare Instance pred : PredClass t.\n  Parameter a0 : t.\n  Parameter a0_pred : pred a0.\n  Declare Instance boolablePres :\n    PredClassPreservesBoolableUnit pred boolableUnit.\nEnd BoolableOrderedPredType.\n\nModule SimplifyBoolablePredType (A : BoolableOrderedPredType) <: OrderedPredType.\n  Include A.\nEnd SimplifyBoolablePredType.\n\nModule OrderedSigma (T : OrderedPredType) <: MyOrderedType.\n  Definition pred_instance : PredClass T.t := T.pred.\n\n  Definition t := {x : T.t | @the_pred _ pred_instance x}%type.\n  Definition t0 := exist the_pred T.a0 T.a0_pred.\n  Existing Instance T.enumerable.\n  Existing Instance T.cost_instance.\n  Existing Instance T.cost_max.\n  Existing Instance T.showable.\n  Definition enumerable  : Enumerable t := _.\n  Definition cost_instance : forall N, CCostClass N t := _.\n  Definition cost_max : forall N, CCostMaxClass N t := _.\n  Definition show_sigma (x : t) : string :=\n    to_string (projT1 x).\n  Instance showable : Showable t := mkShowable show_sigma.\n  Definition eq (x1 x2 : t) := T.eq (projT1 x1) (projT1 x2).\n  Definition lt (x1 x2 : t) := T.lt (projT1 x1) (projT1 x2).\n  \n  Lemma lt_trans : forall x y z, lt x y -> lt y z -> lt x z.\n  Proof.\n    case => a H; case => b H2; case => c H3; rewrite /lt /=.\n    apply: T.lt_trans.\n  Qed.    \n\n  Lemma lt_not_eq : forall x y, lt x y -> ~eq x y.\n  Proof.\n    case => a H; case => b H2; rewrite /lt /eq /=.\n    by move/T.lt_not_eq.\n  Qed.    \n  \n  Lemma compare : forall x y, Compare lt eq x y.\n  Proof.\n    case => a H; case => b H2; rewrite /lt /eq /=.\n    case H3: (T.compare a b).\n    { apply: LT => //. }\n    { apply: EQ => //. }\n    apply: GT => //. \n  Qed.    \n\n  Lemma eq_dec : forall x y, {eq x y} + {~eq x y}.\n  Proof.\n    case => a H; case => b H2; rewrite /eq /=.\n    case: (T.eq_dec a b); first by left.\n    by right.\n  Qed.    \n\n  Lemma eqP : forall x y, x = y <-> eq x y.\n  Proof.\n    case => a H; case => b H2; rewrite /eq /=; move: (T.eqP a b) => <-.\n    split; first by inversion 1.\n    move => H3; move: H H2; subst a => H H2; f_equal.\n    apply: proof_irrelevance.\n  Qed.\nEnd OrderedSigma.\n\nModule BoolableOrderedSigma (T : BoolableOrderedPredType) <: BoolableMyOrderedType.\n  Module SimplPred := SimplifyBoolablePredType T.\n  Module SimplSigma := OrderedSigma SimplPred.\n  Include SimplSigma.\n  Definition boolable : Boolable t := _.\n  Definition boolableUnit: BoolableUnit boolable := _.\n  Definition eq' : Eq t := eqSigma (A:=SimplPred.t) SimplPred.eq' (P:=SimplPred.pred).\n  Definition eq_refl' : Eq_Refl eq' :=\n    eqSigmaRefl SimplPred.t SimplPred.eq' SimplPred.eq_refl' SimplPred.pred.\n  Definition eq_dec' : Eq_Dec eq' :=\n    eqSigmaDec SimplPred.t SimplPred.eq' SimplPred.eq_dec' SimplPred.pred.\nEnd BoolableOrderedSigma.\n\nModule Type OrderedPredFinType.\n  Include OrderedFinType.\n  Declare Instance pred : PredClass t.\n  Parameter a0 : t.\n  Parameter a0_pred : pred a0.\nEnd OrderedPredFinType.\n\nModule OrderedPredType_of_OrderedPredFinType\n       (X : OrderedPredFinType) <: OrderedPredType.\n  Include X.\nEnd OrderedPredType_of_OrderedPredFinType.\n  \nModule OrderedFinSigma (X : OrderedPredFinType) <: OrderedFinType.\n  Module Y := OrderedPredType_of_OrderedPredFinType X.\n  Module A := OrderedSigma Y.\n\n  Include A.\n\n  Definition xE := EqType X.t X.eq_mixin.\n  Definition xC := ChoiceType xE X.choice_mixin.\n  Definition xF := FinType xC X.fin_mixin.\n\n  Definition eq_mixin := @sig_eqMixin xE X.pred.\n  Definition choice_mixin := @sig_choiceMixin xC X.pred.\n  Definition fin_mixin := @sig_finMixin xF X.pred.\nEnd OrderedFinSigma.\n\n\n(* Scalar Games *)\nModule Type OrderedScalarType.\n  Include MyOrderedType.\n  Parameter scal : dyadic_rat.\n  Instance scal_DyadicScalarInstance : DyadicScalarClass := scal.\n  Local Open Scope ring_scope.\n  Parameter scal_pos : 0 <= projT1 scal.\nEnd OrderedScalarType.\n\nModule Type BoolableOrderedScalarType.\n  Include OrderedScalarType.\n  Declare Instance boolable : Boolable t.\n  Declare Instance boolableUnit: BoolableUnit boolable. \n  Declare Instance eq' : Eq t.\n  Declare Instance eq_dec' : Eq_Dec eq'.\n  Declare Instance eq_refl' : Eq_Refl eq'.\nEnd BoolableOrderedScalarType.\n\nModule SimplifyBoolableScalarType (A: BoolableOrderedScalarType) <: OrderedScalarType.\n  Include A.\nEnd SimplifyBoolableScalarType.\n                      \nModule OrderedScalar (T : OrderedScalarType) <: MyOrderedType.\n  Definition t := scalar scalar_val T.t.\n  Definition t0 := Wrap (Scalar (rty:=rat_realFieldType) scalar_val) T.t0.\n  Existing Instance T.showable.\n  Definition enumerable : Enumerable t :=\n    scalarEnumerableInstance _ T.enumerable scalar_val.\n  Definition cost_instance (N : nat) :=\n    scalarCCostInstance T.enumerable (T.cost_instance N) (H1:=T.scal_DyadicScalarInstance).\n  Definition cost_max (N : nat) :=\n    scalarCCostMaxInstance (T.cost_max N) dyadic_scalar_val.\n  Definition show_scalar (x : t) : string :=\n    append \"Scalar\" (to_string (unwrap x)).\n  Instance showable : Showable t := mkShowable show_scalar.\n  Definition eq (x1 x2 : t) := T.eq (unwrap x1) (unwrap x2).\n  Definition lt (x1 x2 : t) := T.lt (unwrap x1) (unwrap x2).\n  Lemma lt_trans : forall x y z, lt x y -> lt y z -> lt x z.\n  Proof.\n    case => a; case => b; case => e.\n    apply: T.lt_trans.\n  Qed.\n  Lemma lt_not_eq : forall x y, lt x y -> ~eq x y.\n  Proof. case => a; case => b; apply: T.lt_not_eq. Qed.\n  Lemma compare : forall x y, Compare lt eq x y.\n  Proof.\n    case => a; case => b; rewrite /=.\n    case: (T.compare a b) => H.\n    { rewrite /lt; constructor => //. }\n    { by rewrite /lt /eq; apply: EQ. }\n    by rewrite /lt /eq; apply: GT.\n  Qed.\n  Lemma eq_dec : forall x y, {eq x y} + {~eq x y}.\n  Proof. case => a; case => b; apply: T.eq_dec. Qed.\n  Lemma eqP : forall x y, x = y <-> eq x y.\n  Proof.\n    case => a; case => b; split => H; rewrite /eq.\n    by rewrite -(T.eqP a b); inversion H.\n    rewrite /eq /= in H; f_equal.\n    by rewrite T.eqP.\n  Qed.\nEnd OrderedScalar.\n\nModule BoolableOrderedScalar (A : BoolableOrderedScalarType) <: BoolableMyOrderedType.\n  Module SimplScalarType := SimplifyBoolableScalarType A.\n  Module SimplScalar := OrderedScalar SimplScalarType.\n  Include SimplScalar.\n  \n  (* Need to remind the system of these for some reason... *)\n  Existing Instances eqScalarRefl eqScalarDec.\n\n  Definition boolable : Boolable t := _.\n  Definition boolableUnit : BoolableUnit boolable := _.\n  Definition eq' : Eq t := _.\n  Definition eq_refl' : Eq_Refl eq' := _.\n  Definition eq_dec' : Eq_Dec eq' := _. \nEnd BoolableOrderedScalar.     \n\n(** The following combinators require notions of boolability **)\nModule BoolableOrderedSingleton (A : BoolableMyOrderedType) <: BoolableMyOrderedType.\n  Definition t := singleton (A.t).\n  Definition t0 := Wrap Singleton A.t0.\n  Existing Instance A.enumerable.\n  Existing Instance A.showable.\n  Definition enumerable  : Enumerable t := _.\n  Definition cost_instance : forall N, CCostClass N t := _.\n  Definition cost_max : forall N, CCostMaxClass N t := _.\n  Definition show_sing (sA : singleton (A.t)) : string := \n      append \"Singleton\" (to_string (unwrap sA)).\n  Instance showable : Showable t := mkShowable show_sing.\n  Definition eq (p1 p2 : t) := A.eq (unwrap p1) (unwrap p2).\n  Definition lt (p1 p2 : t) := A.lt (unwrap p1) (unwrap p2).\n  Definition lt_trans : forall x y z, lt x y -> lt y z -> lt x z.\n  Proof.\n    rewrite /lt; move => x y z; apply A.lt_trans.\n  Qed.\n  Lemma lt_not_eq : forall x y, lt x y -> ~ eq x y.\n  Proof.\n    rewrite /eq /lt; move => x y; apply A.lt_not_eq.\n  Qed.\n  Lemma compare : forall x y, Compare lt eq x y.\n  Proof.\n    move => x y.\n    case H: (A.compare (unwrap x) (unwrap y)) => [lt_pf|eq_pf|gt_pf];\n    [apply LT | apply EQ | apply GT] => //.\n  Qed.\n  Lemma eq_dec : forall x y, {eq x y} + {~eq x y}.\n  Proof.\n    move => x y.\n    case H : (A.eq_dec (unwrap x) (unwrap y)); [left | right] => //.\n  Qed.\n  Lemma eqP : forall x y, x = y <-> eq x y.\n  Proof.\n    rewrite /t.\n    move => x y. destruct x. destruct y.\n    split => H. rewrite H /eq. apply A.eqP. auto.\n    rewrite /eq /= in H. apply A.eqP in H. rewrite H => //.\n  Qed.\n  Definition boolable : Boolable t := _.\n  Definition boolableUnit : BoolableUnit boolable := _.\n  Definition eq' : Eq t := _.\n  Definition eq_refl' : Eq_Refl eq' := _.\n  Definition eq_dec' : Eq_Dec eq' := _.\nEnd BoolableOrderedSingleton.\n  \n(* This bundles the scalar and bias terms of an affine game together *) \nModule Type BoolableOrderedAffineType.\n  Include BoolableMyOrderedType.\n  Parameter scalar : dyadic_rat.\n  Local Open Scope ring_scope.\n  Parameter scalar_pos : 0 <= projT1 scalar.\n  Parameter bias : dyadic_rat.\n  Parameter bias_pos : 0 <= projT1 bias. (*FIXME*)\nEnd BoolableOrderedAffineType.\n\nModule ScalarType_of_OrderedAffineType (A : BoolableOrderedAffineType)\n  <: BoolableOrderedScalarType.\n  Include A.\n  Definition scal := A.scalar.\n  Definition scal_pos := A.scalar_pos.\n  Instance scal_DyadicScalarInstance : DyadicScalarClass := scal.\nEnd ScalarType_of_OrderedAffineType.\n\nModule OffsetType_of_OrderedAffineType (A : BoolableOrderedAffineType)\n  <: BoolableOrderedScalarType.\n    Include A.\n    Definition scal := A.bias.\n    Definition scal_pos := A.bias_pos.\n    Instance scal_DyadicScalarInstance : DyadicScalarClass := scal.\n    (*FIXME: incorporate into module signature:*)\n    Instance scal_ScalarAxiomInstance :\n      ScalarAxiomClass\n        (DyadicScalarInstance scal_DyadicScalarInstance) := scal_pos.\nEnd OffsetType_of_OrderedAffineType.\n\nModule BiasType_of_OffsetType (A : BoolableOrderedScalarType)\n  <: BoolableOrderedScalarType.\n    Include BoolableOrderedSingleton A.\n    Definition scal := A.scal.\n    Definition scal_pos := A.scal_pos.  \n    Instance scal_DyadicScalarInstance : DyadicScalarClass := scal.\n    (*FIXME: incorporate into module signature:*)\n    Instance scal_ScalarAxiomInstance :\n      ScalarAxiomClass\n        (DyadicScalarInstance scal_DyadicScalarInstance) := scal_pos.\nEnd BiasType_of_OffsetType.\n\n(* Given a BoolableOrderedAffineType, toss everything together to build\n    affine games *)\n\nModule OrderedAffinePred (A : BoolableOrderedAffineType) <: OrderedPredType.\n    Module S := ScalarType_of_OrderedAffineType A.\n    Module Off := OffsetType_of_OrderedAffineType A.\n    Module Bias := BiasType_of_OffsetType Off.\n    Module Scaled := BoolableOrderedScalar S.\n    Module Offset := BoolableOrderedScalar Bias.\n    Module Prod := BoolableOrderedProd Scaled Offset.\n\n    Include Prod.\n    Instance pred : PredClass Prod.t :=\n      affinePredInstance A.eq_dec'.\n    Definition a0 : t := (Wrap _ A.t0, Wrap _ (Wrap _ A.t0)).\n    Lemma a0_pred : pred a0.\n    Proof.\n      rewrite /a0 /pred /affinePredInstance => /=.\n      case H: (A.eq_dec' A.t0 A.t0) => //=.\n      assert (A.eq' A.t0 A.t0) as  H0 by apply A.eq_refl'.\n      contradiction.\n    Qed.\n  \n    Instance boolablePres : PredClassPreservesBoolableUnit pred _ :=\n      affinePredPreservesBoolableUnit _ _ _ _ _.      \n    \nEnd OrderedAffinePred.\n  \nModule OrderedAffine (A : BoolableOrderedAffineType) <: BoolableMyOrderedType.\n  Module Pred := OrderedAffinePred A.\n  Include BoolableOrderedSigma Pred.\nEnd OrderedAffine.\n\n(** MyOrdNatDep: a computational analogue of 'I_B.n *)\n\nModule MyOrdNatDep (B : BOUND) <: MyOrderedType.\n  Module N := OrdNatDep B. Include N.\n\n  Program Definition t0 := @mk 0%N _.\n  Next Obligation. by apply: B.n_gt0. Qed.\n\n  (* FIXME: this definition should be fold_left, not fold_right *)\n  Program Fixpoint enumerate_rec (m : nat) (pf : (m < n)%nat) : list t :=\n    (match m as x return _ = x -> list t with\n     | O => fun _ => t0 :: nil\n     | S m' => fun pf => @mk (N.of_nat m) _ :: enumerate_rec m' _\n     end) erefl.\n  Next Obligation. by rewrite Nat2N.id. Qed.\n\n  Lemma lt_dec x y : ({x<y} + {x>=y})%nat.\n  Proof.\n    case H: (leq (S x) y); first by left.\n    case H2: (y <= x)%nat; first by right.\n    move: (leq_total y x); rewrite H2 /= => H3.\n    rewrite ltnNge in H.    \n    rewrite leqNgt in H2.\n    rewrite leqNgt in H3.\n    rewrite -ltnNge in H.\n    by rewrite H in H2.\n  Qed.\n\n  Lemma gt0_pred_lt n : (0 < n -> n.-1 < n)%nat.\n  Proof. elim: n => //. Qed.\n  \n  Definition enumerate_t : list t :=\n    match lt_dec 0 n with \n    | left pfn => enumerate_rec (Nat.pred n) (gt0_pred_lt _ pfn)\n    | right _ => nil\n    end.\n\n  Instance enumerable : Enumerable t := enumerate_t.\n\n  Instance showable : Showable t :=\n    mkShowable (fun x => to_string x.(val)).\n\n  Lemma eqP : forall x y : t, x = y <-> eq x y.\n  Proof.\n    move => x y; case: x => vx px; case y => vy py.\n    rewrite /eq /=; split.\n    { inversion 1; subst.\n      apply: M.E.eq_refl. }\n    rewrite /BinNat.N.eq => H; subst vy.\n    f_equal.\n    apply: proof_irrelevance.\n  Qed.\n  \n  (* FIXME: Bogus cost_instance -- perhaps cost_instance and cost_max should \n     be factored out of MyOrderedType. *)\n  Instance cost_instance (n : nat) : CCostClass n t := fun _ _ => 0%D.\n  Instance cost_max (n : nat) : CCostMaxClass n t := 0%D.\nEnd MyOrdNatDep.  \n  \nModule MyOrdNatDepProps (B : BOUND).\n  Module M := MyOrdNatDep B. Include M.\n\n  Fixpoint enumerate_rec_erased (m : nat) : list N :=\n    match m with\n    | O => N.of_nat O :: nil\n    | S m' => N.of_nat m :: enumerate_rec_erased m'\n    end.\n\n  Lemma enumerate_rec_map_erased m (pf : (m < n)%nat) :\n    map val (enumerate_rec m pf) = enumerate_rec_erased m.\n  Proof. by elim: m pf => // n IH pf /=; f_equal; rewrite IH. Qed.\n\n  Fixpoint enumerate_rec_erased_nat (m : nat) : list nat :=\n    match m with\n    | O => O :: nil\n    | S m' => m :: enumerate_rec_erased_nat m'\n    end.\n\n  Lemma enumerate_rec_erased_nat_iota n :\n    List.rev (enumerate_rec_erased_nat n) = iota 0 (n.+1).\n  Proof.\n    elim: n => // n /= ->.\n    have ->: (0::iota 1 n = [::0]++iota 1 n)%nat by [].\n    rewrite -app_assoc /=; f_equal.\n    have ->: (n.+1 = n+1)%nat by rewrite addnC.\n    move: 1%nat => nx; elim: n nx => //= n IH nx; f_equal.\n    have ->: (n.+1 +nx = n + nx.+1)%nat by rewrite addSn.\n    apply: IH.\n  Qed.    \n  \n  Lemma enumerate_rec_map_erased_nat m :\n    map N.to_nat (enumerate_rec_erased m) = enumerate_rec_erased_nat m.\n  Proof.\n    elim: m => // m IH /=; f_equal => //.\n    by rewrite SuccNat2Pos.id_succ.\n  Qed.      \n\n  Lemma notin_gtn m n :\n    (m > n)%nat -> \n    ~InA (fun x : nat => [eta Logic.eq x]) m (enumerate_rec_erased_nat n).\n  Proof.\n    elim: n m.\n    { move => m H H2; inversion H2; subst => //.\n      inversion H1. }\n    move => n IH m H H2; apply: IH.\n    { apply: ltn_trans; last by apply: H.\n      by []. }\n    inversion H2; subst => //.\n    move: (ltP H) => H3; omega.\n  Qed.    \n  \n  Lemma enumerate_rec_erased_nat_nodup m :\n    NoDupA (fun x : nat => [eta Logic.eq x]) (enumerate_rec_erased_nat m).\n  Proof.\n    elim: m.\n    { constructor; first by inversion 1.\n      constructor. }\n    move => n IH /=; constructor => //.\n    by apply: notin_gtn.\n  Qed.\n\n  Lemma enumerate_rec_erased_nat_total n m :\n    (n <= m)%nat ->\n    In n (enumerate_rec_erased_nat m).\n  Proof.\n    elim: m n; first by case => //= _; left.\n    move => m IH n H; case: (Nat.eq_dec n m.+1) => [pf|pf].\n    { by left; subst n. }\n    right; apply: IH.\n    apply/leP; move: (leP H) => H2; omega.\n  Qed.\n\n  Lemma enumerate_rec_erased_total n m :\n    (N.to_nat n <= N.to_nat m)%nat ->\n    In n (enumerate_rec_erased (N.to_nat m)).\n  Proof.\n    move => H.\n    suff: In (N.to_nat n) (map N.to_nat (enumerate_rec_erased (N.to_nat m))).\n    { clear H; elim: m n.\n      { move => n /=; case => // H; left.\n        destruct n => //.\n        simpl in H.\n        move: (PosN0 p); rewrite -H //. }\n      move => p n; rewrite in_map_iff; case => x []H H1.\n      by move: (N2Nat.inj _ _ H) => H2; subst n. }\n    rewrite enumerate_rec_map_erased_nat.\n    apply: (enumerate_rec_erased_nat_total _ _ H).\n  Qed.    \n\n  Lemma enumerate_rec_total m (pf : (m < n)%nat) (x : t) :\n    (m.+1 = n)%nat -> \n    In x (enumerate_rec _ pf).\n  Proof.\n    move => Hsucc.\n    suff: In (val x) (map val (enumerate_rec m pf)).\n    { clear Hsucc.\n      elim: m pf x => /=.\n      { move => H x; case => // H2; left.\n        rewrite /t0; f_equal; destruct x as [vx pfx].\n        simpl in H2; subst vx; f_equal.\n        apply: proof_irrelevance. }\n      move => n IH pf x; case.\n      { destruct x as [vx pfx]; simpl => H; subst vx; left.\n        f_equal.\n        apply: proof_irrelevance. }\n      rewrite in_map_iff; case => x0 [] H H2; right.\n      clear - H H2.\n      destruct x0 as [vx0 pfx0].\n      destruct x as [vx pfx].\n      simpl in H; subst vx0.\n      have ->: pfx = pfx0 by apply: proof_irrelevance.\n      by []. }\n    rewrite enumerate_rec_map_erased.\n    destruct x as [vx pfx].\n    rewrite /val.\n    have ->: m = N.to_nat (N.of_nat m) by rewrite Nat2N.id.\n    apply: enumerate_rec_erased_total.\n    rewrite Nat2N.id.\n    apply/leP; move: (ltP pfx) (ltP pf); move: (N.to_nat vx) => n0.\n    rewrite -Hsucc => X Y.\n    omega.\n  Qed.    \n  \n  Lemma InA_map A B (f : A -> B) (l : list A) x :\n    InA (fun x => [eta Logic.eq x]) x l -> \n    InA (fun x => [eta Logic.eq x]) (f x) (map f l).\n  Proof.\n    elim: l; first by inversion 1.\n    move => a l IH; inversion 1; subst; first by constructor.\n    by apply: InA_cons_tl; apply: IH.\n  Qed.\n  \n  Lemma enumerate_rec_erased_nodup m :\n    NoDupA (fun x => [eta Logic.eq x]) (enumerate_rec_erased m).\n  Proof.\n    suff: (NoDupA (fun x => [eta Logic.eq x]) (map N.to_nat (enumerate_rec_erased m))).\n    { elim: (enumerate_rec_erased m) => // a l IH; inversion 1; subst.\n      constructor.\n      { by move => H; apply: H1; apply: InA_map. }\n      apply: (IH H2). }\n    rewrite enumerate_rec_map_erased_nat.\n    apply: enumerate_rec_erased_nat_nodup.\n  Qed.      \n\n  Lemma enumerate_rec_nodup m pf :\n    NoDupA (fun x : t => [eta Logic.eq x]) (enumerate_rec m pf).\n  Proof.\n    suff: NoDupA (fun x => [eta Logic.eq x]) (map val (enumerate_rec m pf)).\n    { elim: (enumerate_rec m pf) => // a l IH; inversion 1; subst.\n      constructor.\n      { clear - H1 => H2; apply: H1.\n        elim: l H2; first by inversion 1.\n        move => b l H; inversion 1; subst; first by constructor.\n        by apply: InA_cons_tl; apply: H. }\n      by apply: IH. }\n    rewrite enumerate_rec_map_erased.\n    apply: enumerate_rec_erased_nodup.\n  Qed.\n\n  Lemma enumerate_t_nodup :\n    NoDupA (fun x : t => [eta Logic.eq x]) enumerate_t.\n  Proof.\n    rewrite /enumerate_t.\n    case H: (lt_dec 0 n) => [pf|pf]; last by constructor.\n    by apply: enumerate_rec_nodup.\n  Qed.\n\n  Lemma enumerate_t_total x : In x enumerate_t.\n  Proof.\n    rewrite /enumerate_t.\n    case: (lt_dec 0 n) => [pf|pf]; last first.\n    { destruct x as [vx pfx].\n      move: (ltP pfx) (leP pf) => X Y.\n      omega. }\n    have H: (n = n.-1.+1).\n    { rewrite (ltn_predK (m:=0)) => //. }\n    symmetry in H.\n    by apply: (enumerate_rec_total _ (gt0_pred_lt n pf) x H).\n  Qed.\n\n  Program Instance enum_ok : @Enum_ok t enumerable.\n  Next Obligation.\n    rewrite /enumerable_fun /enumerable.\n    apply: enumerate_t_nodup.\n  Qed.\n  Next Obligation.\n    rewrite /enumerable_fun /enumerable.\n    apply: enumerate_t_total.\n  Qed.\n\n  Definition Ordinal_of_t (x : t) :=\n    @Ordinal n (N.to_nat (val x)) (M.pf x).\n\n  Definition val_of_Ordinal (x : 'I_n) : N :=\n    match x with\n      Ordinal n _ => N.of_nat n\n    end.\n  \n  Lemma rev_enumerate_enum :\n    List.rev (List.map Ordinal_of_t enumerate_t) =\n    enum 'I_n.\n  Proof.\n    rewrite /enumerate_t; case: (lt_dec 0 n); last first.\n    { move => a; move: (leP a) => H; move: (ltP B.n_gt0) => Hx; omega. }\n    move => pf.\n    suff: (List.rev (map val (enumerate_rec n.-1 (gt0_pred_lt n pf))) =\n           List.map val_of_Ordinal (enum 'I_n)).\n    { move: (enumerate_rec _ _) => l1.\n      move: (enum 'I_n) => l2; elim: l1 l2; first by case.\n      move => a l1 /= IH l2 H2.\n      have [l2' H]:\n        exists l2',\n          map val_of_Ordinal l2 = map val_of_Ordinal l2' ++ [:: val a].\n      { clear - H2; move: H2; move: (rev _) => l1x.\n        elim: l2 l1x => //.\n        { move => l1x /=; case: l1x => //. }\n        move => ax l2x IH l1x /= H2; case: l1x H2.\n        { simpl; inversion 1; subst; exists nil => //. }\n        move => ay l1y /=; inversion 1; subst.\n        case: (IH _ H1) => ll H3; exists (ax :: ll); simpl.\n        by rewrite -H1 in H3; rewrite H3. }\n      rewrite H in H2; apply app_inj_tail in H2; case: H2 => H2 _.\n      rewrite (IH _ H2); clear - H; symmetry in H.\n      have H2:\n        map val_of_Ordinal l2' ++ [:: val a] =\n        map val_of_Ordinal (l2' ++ [:: Ordinal_of_t a]).\n      { by rewrite map_app /= N2Nat.id. }\n      rewrite H2 in H; clear H2.\n      apply: map_inj; last by apply: H.\n      move => x y; case: x => x pfx; case: y => y pfy; move/Nat2N.inj.\n      move => H2; subst; f_equal; apply: proof_irrelevance. }\n    rewrite enumerate_rec_map_erased.\n    suff:\n      rev (map N.to_nat (enumerate_rec_erased n.-1)) =\n      map N.to_nat (map val_of_Ordinal (enum 'I_n)).\n    { rewrite -map_rev; move/map_inj; apply; apply: N2Nat.inj. }\n    rewrite enumerate_rec_map_erased_nat.\n    rewrite enumerate_rec_erased_nat_iota.\n    have ->: (map N.to_nat (map val_of_Ordinal (enum 'I_n)) = iota 0 n).\n    { have ->:\n        map N.to_nat (map val_of_Ordinal (enum 'I_n)) =\n        map eqtype.val (enum 'I_n).\n      { elim: (enum 'I_n) => // a l /= IH; f_equal => //.\n        by case: a => // m i; rewrite /val_of_Ordinal Nat2N.id. }\n      rewrite -val_enum_ord //. }\n    have ->: (n.-1.+1 = n).\n    { move: (ltP pf) => Hx; omega. }\n    by [].\n  Qed.\nEnd MyOrdNatDepProps.\n", "meta": {"author": "gstew5", "repo": "cage", "sha": "402ed9a7ffb00a2cb64436ad99bd46e2e10047d7", "save_path": "github-repos/coq/gstew5-cage", "path": "github-repos/coq/gstew5-cage/cage-402ed9a7ffb00a2cb64436ad99bd46e2e10047d7/orderedtypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2697350667351386}}
{"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        {pL: PropositionalLanguage L}\n        {GammaP: Provable L}\n        {GammaD: Derivable L}\n        {SC: NormalSequentCalculus L GammaP GammaD}\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        {minAX: MinimumAxiomatization L GammaP}\n        {ipAX: IntuitionisticPropositionalLogic 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      {AX: NormalAxiomatization 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": "UnifySL", "sha": "cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d", "save_path": "github-repos/coq/QinxiangCao-UnifySL", "path": "github-repos/coq/QinxiangCao-UnifySL/UnifySL-cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d/PropositionalLogic/Complete/Lindenbaum_Trivial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.26972023437062825}}
{"text": "Require Import MirrorCore.Lambda.ExprCore.\nRequire Import MirrorCore.Lambda.Red.\nRequire Import MirrorCore.Lambda.ExprLift.\nRequire Import MirrorCore.Lambda.Expr.\nRequire Import MirrorCore.TypesI.\n\nRequire Import ExtLib.Core.RelDec.\n\nRequire Import Charge.SetoidRewrite.Base.\nRequire Import Charge.SetoidRewrite.AutoSetoidRewrite.\nRequire Import Charge.ModularFunc.ILogicFunc.\n\nRequire Import Charge.Logics.ILogic.\n\nSection ILPullConjunct.\n  Context {typ func : Type} {HIL : ILogicFunc typ func}.\n  Context {RType_typ : RType typ}.\n   Context {RelDec_func : RelDec (@eq (expr typ func))}.\n\n  Let Rbase := expr typ func.\n\n  Variable target : expr typ func -> bool.  \nPrint rewriter.\nCheck @rewriter.\n\n  Definition rw_under_and (l : typ) (P : expr typ func) (rw : rewriter _) : rewriter _ :=\n    fun e rvars rg => rg_fmap (typ := typ) (func := func) (mkAnd l P) (rw e rvars rg).\n\nDefinition il_pull_conjunct_l (rw : @rw_type typ func) (e : expr typ func) (rvars : list (RG (expr typ func))) (rg : RG Rbase) : m (expr typ func) :=\n  match e with\n    | App (App a P) (App (App b Q) R) =>\n      match ilogicS (typ := typ) (func := expr typ func) a, ilogicS b with\n      \t| Some (ilf_and l), Some (ilf_and _) =>\n      \t\tmatch target Q with\n      \t\t\t| true => rg_plus\n                   (rg_bind (unifyRG (@rel_dec (expr typ func) _ _) rg (RGflip (RGinj (fEntails l))))\n                      (fun _ => rw_under_and l Q rw (mkAnd l P R) rvars rg))\n\t\t\t\t   (rg_bind (unifyRG (@rel_dec (expr typ func) _ _) rg (RGinj (fEntails l)))\n\t\t\t\t      (fun _ => rw_under_and l Q rw (mkAnd l P R) rvars rg))      \t\t\t\n      \t\t    | _ => rg_fail\n      \t\tend\n      \t| _, _ => rg_fail\n      end\n    | _ => rg_fail\n  end.\n\nDefinition il_pull_conjunct_r (rw : @rw_type typ func) (e : expr typ func) (rvars : list (RG (expr typ func))) (rg : RG Rbase) : m (expr typ func) :=\n  match e with\n    | App (App a (App (App b P) Q)) R =>\n      match ilogicS (typ := typ) (func := expr typ func) a, ilogicS b with\n      \t| Some (ilf_and l), Some (ilf_and _) =>\n      \t\tmatch target P with\n      \t\t\t| true => rg_plus\n\t               (rg_bind (unifyRG (@rel_dec (expr typ func) _ _) rg (RGflip (RGinj (fEntails l))))\n\t                 (fun _ => rw_under_and l P rw (mkAnd l Q R) rvars rg))\n\t\t\t\t   (rg_bind (unifyRG (@rel_dec (expr typ func) _ _) rg (RGinj (fEntails l)))\n\t                 (fun _ => rw_under_and l P rw (mkAnd l Q R) rvars rg))\n      \t\t    | _ => rg_fail\n      \t\tend\n      \t| _, _ => rg_fail\n      end\n    | _ => rg_fail\n  end.\n\nVariable gs : logic_ops.\n\nDefinition il_pull_conjunct_sym (rw : @rw_type typ func) (e : expr typ func) (rvars : list (RG (expr typ func))) (rg : RG Rbase) : m (expr typ func) :=\n  match e with\n    | App (App a P) Q =>\n      match ilogicS (typ := typ) (func := expr typ func) a with\n      \t| Some (ilf_and l) =>\n      \t\tmatch target Q with\n      \t\t  | true => rg_plus\n\t\t                  (rg_bind (unifyRG (@rel_dec (expr typ func) _ _) rg (RGflip (RGinj (fEntails l))))\n\t\t                     (fun _ => rw_under_and l Q rw P rvars rg))\n\t\t\t\t \t\t  (rg_bind (unifyRG (@rel_dec (expr typ func) _ _) rg (RGinj (fEntails l)))\n\t\t                     (fun _ => rw_under_and l Q rw P rvars rg))\n      \t\t  | _ => rg_fail\n      \t\tend\n        | _ => rg_fail\n      end\n    | _ => rg_fail\n  end.  \n\nDefinition il_pull_conjunct := sr_combineK il_pull_conjunct_sym (sr_combineK il_pull_conjunct_l il_pull_conjunct_r).\n\nEnd ILPullConjunct.\n\nImplicit Arguments il_pull_conjunct [[typ] [func] [HIL] [RelDec_func]].\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/PullConjunct/ILPullConjunct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.26972022794302514}}
{"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 GlobSim.\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.\n\nRequire Import simPromiseCertified.\nRequire Import Mem_at_eq_lemmas.\nRequire Import ConsistentProp.\n\n(** * Compositionality Proof *)\n\n(** This file contains the proof of compositionality of our thread-local simulation.\n\n    The theorem [compositionality] in this file shows the compositionality 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 simulates the whole source program.\n\n    The theorem [compositionality] 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 compositionality_aux:\n      forall (index: Type) (index_order: index -> index -> Prop)\n        (I: Invariant) (lo: Ordering.LocOrdMap) (b b': bool) inj \n        (ths_tgt ths_src: Threads.t) (ctid: IdentMap.key)\n        (sc_tgt sc_src: TimeMap.t) (mem_tgt mem_src: Memory.t)\n        (WELL_FOUNDED_ORDER: well_founded index_order)\n        (WELL_FORMED_INV: wf_I I)\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             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\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 = true -> dset = dset_init) /\\\n             Local.promise_consistent lc_tgt)\n        (COMPLETE_THRDS_MAP: \n           forall tid\n             (IN_SRC_THRDS: IdentMap.mem tid ths_src = true),\n             IdentMap.mem tid ths_tgt = true)\n        (SAFE: ~(exists npc,\n                    rtc (NPConfiguration.all_step lo)\n                        (NPConfiguration.mk (Configuration.mk ths_src ctid sc_src mem_src) b') 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) b') 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        (WF_ATM_BIT: b = true -> b' = true)\n        (*(CTID_IN: IdentMap.mem ctid ths_tgt = true)*)\n        (INV_OUT_ATM: b = 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        glob_sim_state lo (NPConfiguration.mk (Configuration.mk ths_tgt ctid sc_tgt mem_tgt) b)\n                       (NPConfiguration.mk (Configuration.mk ths_src ctid sc_src mem_src) b').\nProof.\n  cofix Hcofix; ii.\n  econs; ss; ii.\n  + (* tau step *)\n    inv TGT_TAU; ss.\n    assert(T_STEPS: rtc (NPAuxThread.tau_step lang lo)\n                        (NPAuxThread.mk lang (Thread.mk lang st1 lc1 sc_tgt mem_tgt) b)\n                        (NPAuxThread.mk lang (Thread.mk lang st2 lc2 sc2 m2) b0)).\n    {\n      eapply rtc_n1; [eapply STEPS | eapply STEP].\n    }\n    exploit wf_config_rtc_NPThread_tau_steps_prsv; [ | | eapply T_STEPS | eauto..]; eauto.\n    introv T_CONFIG_WF'.\n    eapply rtc_rtcn in T_STEPS. des.\n    exploit CUR_THRD; [eapply TID1 | eauto..]. ii; des.\n    assert(TGT_PROM_CONS: Local.promise_consistent lc2).\n    {\n      eapply consistent_nprm_promise_consistent in CONSISTENT; eauto; ss.\n      eapply wf_config_to_local_wf; eauto. \n      instantiate (3 := ctid). rewrite IdentMap.gss; eauto.\n      inv T_CONFIG_WF'; eauto. inv T_CONFIG_WF'; eauto.\n    }\n    exploit sim_tau_steps; [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    ii; des.\n    {\n      (* not abort *)\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.\n        eexists. split. eauto.  \n        eapply Hcofix with (b' := b_src') (inj := inj'); eauto.\n        {\n          ii. \n          erewrite IdentMap.gso in READY_TGT_THD; eauto.\n          lets READY_SRC_THD: READY_TGT_THD.\n          eapply READY_THRDS in READY_SRC_THD; eauto. des.\n          do 2 eexists.\n          split; eauto.\n          split; eauto.\n          eapply local_sim_rely_condition with (n_tgt := n) (n_src := 0) (lang2 := lang0); eauto.\n          eapply wf_config_to_local_wf; eauto.\n          clear S_CONFIG_WF'. 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          clear S_CONFIG_WF'. eapply wf_config_to_local_wf; eauto.\n          instantiate (3 := tid). erewrite IdentMap.gso; eauto.\n          clear S_CONFIG_WF'. eapply wf_config_to_local_wf; 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          ii.\n          rewrite IdentMap.gss in CUR_TGT_THRD. inv CUR_TGT_THRD.\n          eapply inj_pair2 in H1. subst.\n          do 3 eexists. split. eauto. split; eauto.\n        }\n        {\n          ii. rewrite IdentMap.mem_find. \n          destruct (Loc.eq_dec tid ctid); subst.\n          rewrite IdentMap.gss; eauto.\n          rewrite IdentMap.gso; eauto.\n          eapply COMPLETE_THRDS_MAP in IN_SRC_THRDS.\n          rewrite IdentMap.mem_find in IN_SRC_THRDS. eauto.\n        }\n        {\n          inv LOCAL_SIM_PSV; ss.\n          contradiction SAFE. eexists. split. eauto. ss.\n          econs; ss.\n          eapply NPAuxThread_tau_steps_2_Thread_tau_steps in NP_STEPS; ss.\n          do 3 eexists. split. eauto.\n          split.\n          eapply NP_STEPS. eauto.\n          clear - STEP_INV RELY_STEP.\n          ii. exploit RELY_STEP; eauto. ii; des.\n          inv STEP_INV. 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        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          {\n            clear - SAFE S_STEPS x.\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 x.\n            split. eapply rtc_compose; [eapply S_STEPS | eapply S_STEPS_TO_ABORT].\n            eauto.\n          }\n          {\n            eapply aux_ww_race_to_thrd_ww_race; eauto; ss.\n            eapply rtcn_rtc in S_STEPS.\n            eapply NPAuxThread_tau_steps_2_Thread_tau_steps in S_STEPS; ss.\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            inv T_CONFIG_WF'; eauto.\n          }\n          {\n            inv S_CONFIG_WF'; eauto.\n          }\n          {\n            inv T_CONFIG_WF'; eauto.\n          }\n          {\n            inv S_CONFIG_WF'; eauto.\n          }\n        }\n        eexists. split.\n        {\n          eapply rtcn_rtc in S_STEPS_CONS.\n          eapply Operators_Properties.clos_rt1n_step.\n          eapply NPConfiguration.step_tau; ss; [ | eapply S_STEPS_CONS | eapply S_STEP | eauto..]; eauto.\n        }\n        eapply Hcofix; eauto.\n        {\n          ii.\n          rewrite IdentMap.gso in READY_TGT_THD; eauto.\n          rewrite IdentMap.gso; eauto.\n          lets READY_SRC_THD: READY_TGT_THD.\n          eapply READY_THRDS in READY_SRC_THD; eauto. des.\n          do 2 eexists.\n          split; eauto.\n          split; eauto.\n          eapply local_sim_rely_condition with (n_tgt := n) (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          ii. rewrite IdentMap.gss in CUR_TGT_THRD.\n          inv CUR_TGT_THRD.\n          eapply inj_pair2 in H1. subst.\n          do 3 eexists. split.\n          rewrite IdentMap.gss; eauto.\n          split; eauto. \n        }\n        {\n          ii. rewrite IdentMap.mem_find. \n          destruct (Loc.eq_dec tid ctid); subst.\n          rewrite IdentMap.gss; eauto.\n          rewrite IdentMap.gso; eauto.\n          rewrite IdentMap.mem_find in IN_SRC_THRDS.\n          rewrite IdentMap.gso in IN_SRC_THRDS; eauto.\n          rewrite <- IdentMap.mem_find in IN_SRC_THRDS.\n          eapply COMPLETE_THRDS_MAP in IN_SRC_THRDS.\n          rewrite IdentMap.mem_find in IN_SRC_THRDS. eauto.\n        }\n        {\n          clear - SAFE S_STEPS x CONSISTENT_S.\n          eapply rtcn_rtc in S_STEPS. ii. des.\n          contradiction SAFE.\n          eapply rtc_rtcn in S_STEPS. des.\n          destruct n.\n          inv S_STEPS. \n          erewrite IdentMap.gsident in H; eauto.\n          eapply Behavior.rtcn_tail in S_STEPS. des. destruct a2. destruct state0.\n          eapply rtcn_rtc in S_STEPS.\n          eexists. split.\n          eapply Relation_Operators.rt1n_trans.\n          econs; eauto.\n          eapply NPConfiguration.step_tau; ss; eauto.\n          eapply H. eauto.\n        }\n        {\n          ii; des. contradiction WWRF.\n          clear - S_STEPS H H0 CONSISTENT_S x.\n          eapply Behavior.rtcn_tail in S_STEPS. des. destruct a2. destruct state0.\n          eapply rtcn_rtc in S_STEPS.\n          eexists. split.\n          eapply Relation_Operators.rt1n_trans.\n          econs; eauto.\n          eapply NPConfiguration.step_tau; ss; eauto.\n          eapply H. eauto.\n        }\n        {\n          inv LOCAL_SIM_PSV; ss.\n          contradiction SAFE.\n          eapply rtcn_rtc in S_STEPS.\n          eexists. split. eauto. ss.\n          eapply NPAuxThread_tau_steps_2_Thread_tau_steps in S_STEPS; ss.\n          eapply NPAuxThread_tau_steps_2_Thread_tau_steps in NP_STEPS; ss.\n          econs; ss. do 3 eexists.\n          split. eauto. split.\n          eapply rtc_compose. eapply S_STEPS. eapply NP_STEPS. eauto.\n          clear - STEP_INV RELY_STEP.\n          ii. exploit RELY_STEP; eauto. ii; des.\n          inv STEP_INV. eauto.\n        }\n      }\n    }\n    {\n      (* abort *)\n      clear - x SAFE S_STEPS ABORT.\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  + (* output step *)\n    inv TGT_OUT; ss.\n    exploit CUR_THRD; [eapply TID1 | eauto..]. ii; des.\n    exploit sim_output_steps; [eapply STEP | eauto..]. ii; des.\n    {\n      (* not abort *)\n      assert(CONSISTENT_S': Local.promises (Thread.local e_src0) = Memory.bot /\\ \n                            Local.promises (Thread.local e_src') = Memory.bot).\n      {\n        clear - S_OUT. inv S_OUT; ss. inv H. inv OUT; ss.\n        inv LOCAL; ss. inv LOCAL0; ss. exploit PROMISES; eauto.\n      }\n      destruct CONSISTENT_S' as (CONSISTENT_S' & CONSISTENT_S'').\n      exploit wf_config_NPThread_out_step_prsv; [ | | eapply STEP | eauto..]; eauto.\n      introv WF_CONFIG_TGT'. \n      destruct e_src0, e_src'.\n      exploit wf_config_rtc_NPThread_tau_steps_prsv; [ | | eapply S_STEPS | eauto..]; eauto.\n      introv WF_CONFIG_SRC'.\n      exploit wf_config_NPThread_out_step_prsv; [ | | eapply S_OUT | eauto..]; eauto.\n      instantiate (1 := ctid). rewrite IdentMap.gss; eauto.\n      introv WF_CONFIG_SRC''.\n      erewrite IdentMap.add_add_eq in WF_CONFIG_SRC''; eauto.\n      assert (T_PROM_CONS: Local.promise_consistent lc2).\n      {\n        inv STEP; ss. inv H; ss. inv OUT; ss.\n        inv LOCAL; ss. inv LOCAL0; ss.\n        exploit PROMISES; eauto. introv T_BOT.\n        unfold Local.promise_consistent; ss.\n        rewrite T_BOT; ss. ii. rewrite Memory.bot_get in PROMISE; ss.\n      }\n      eapply rtc_rtcn in S_STEPS. des. destruct n.\n      {\n        inv S_STEPS; ss. \n        do 2 eexists. split. eauto.\n        split.\n        econs; ss. eapply x. eapply S_OUT.\n        ss. econs. split. eauto. ss.\n        eapply Hcofix with (inj := inj'); eauto. \n        {\n          ii.\n          rewrite IdentMap.gso in READY_TGT_THD; eauto.\n          rewrite IdentMap.gso; eauto. ss.\n          exploit READY_THRDS; [eapply READY_TID | eapply READY_TGT_THD | eauto..]. ii; des. \n          do 2 eexists. split. eauto.\n          split; eauto.\n          eapply local_sim_out_rely_condition in x4; eauto.\n          eapply wf_config_to_local_wf; eauto.\n          eapply wf_config_to_local_wf; eauto. instantiate (3 := ctid). erewrite IdentMap.gss; eauto.\n          inv WF_CONFIG_TGT; eauto.\n          inv WF_CONFIG_TGT; eauto.\n          ss. inv WF_CONFIG_SRC'.\n          ss. 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 WF_CONFIG_TGT'; eauto.\n          inv WF_CONFIG_SRC'; eauto.\n          inv WF_CONFIG_TGT'; eauto.\n          inv WF_CONFIG_SRC''; eauto.\n          inv WF_CONFIG_SRC''; eauto.\n        }\n        {\n          ii. rewrite IdentMap.gss in CUR_TGT_THRD; eauto.\n          inv CUR_TGT_THRD. eapply inj_pair2 in H1. subst.\n          do 3 eexists. split. rewrite IdentMap.gss; eauto.\n          split; eauto. \n        }\n        {\n          ii. rewrite IdentMap.mem_find. \n          destruct (Loc.eq_dec tid ctid); subst.\n          rewrite IdentMap.gss; eauto.\n          rewrite IdentMap.gso; eauto.\n          rewrite IdentMap.mem_find in IN_SRC_THRDS.\n          rewrite IdentMap.gso in IN_SRC_THRDS; eauto.\n          rewrite <- IdentMap.mem_find in IN_SRC_THRDS.\n          eapply COMPLETE_THRDS_MAP in IN_SRC_THRDS.\n          rewrite IdentMap.mem_find in IN_SRC_THRDS. eauto.\n        }\n        {\n          introv ABORT. destruct ABORT as (npc & TO_ABORT & ABORT).\n          contradiction SAFE. exists npc.\n          split. eapply Relation_Operators.rt1n_trans.\n          econs. eapply NPConfiguration.step_out; ss; eauto.\n          ss. unfold NPAuxThread.consistent. unfold Thread.consistent_nprm; ii; ss.\n          eexists. split; eauto.\n          eauto. eauto.\n        }\n        {\n          introv WW_RACE. destruct WW_RACE as (npc & TO_WW_RACE & WW_RACE).\n          contradiction WWRF. exists npc.\n          split. eapply Relation_Operators.rt1n_trans.\n          econs. eapply NPConfiguration.step_out; ss; eauto.\n          ss. unfold NPAuxThread.consistent. unfold Thread.consistent_nprm; ii; ss.\n          eexists. split; eauto.\n          eauto. eauto.\n        }\n        { \n          inv LOCAL_SIM_PSV; ss.\n          contradiction SAFE.\n          eexists. split.\n          eapply Relation_Operators.rt1n_trans.\n          econs. eapply NPConfiguration.step_out; eauto.\n          ss. unfold NPAuxThread.consistent. unfold Thread.consistent_nprm; ss. ii.\n          eexists. split. eauto. ss.\n          ss. eauto. ss.\n          eapply NPAuxThread_tau_steps_2_Thread_tau_steps in NP_STEPS; ss.\n          econs; ss. do 3 eexists.\n          erewrite IdentMap.gss; eauto.\n          clear - STEP_INV RELY_STEP.\n          ii. exploit RELY_STEP; eauto. ii; des.\n          inv STEP_INV. eauto.\n        }\n        {\n          inv LOCAL_SIM_PSV; ss.\n          contradiction SAFE.\n          eexists. split.\n          eapply Relation_Operators.rt1n_trans.\n          econs. eapply NPConfiguration.step_out; eauto.\n          ss. unfold NPAuxThread.consistent. unfold Thread.consistent_nprm; ss. ii.\n          eexists. split. eauto. ss.\n          ss. eauto. ss. \n          eapply NPAuxThread_tau_steps_2_Thread_tau_steps in NP_STEPS; ss.\n          econs; ss. do 3 eexists.\n          erewrite IdentMap.gss; eauto.\n          clear - WELL_FORMED_INV RELY_STEP.\n          exploit RELY_STEP; eauto. intros. des. clear x0 RELY_STEP.\n          unfold wf_I in WELL_FORMED_INV. eapply WELL_FORMED_INV in x; eauto; ss.\n          inv x; eauto.\n        }\n      }\n      {\n        ss.\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        eapply rtcn_rtc in S_STEPS_CONS.\n        do 2 eexists. split.\n        eapply Relation_Operators.rt1n_trans. 2: eauto.\n        eapply NPConfiguration.step_tau; ss.\n        2: eapply S_STEPS_CONS. 2: eapply S_STEP. eauto.\n        unfold NPAuxThread.consistent. unfold Thread.consistent_nprm; ii; ss.\n        eexists. split; eauto; ss.\n        split.\n        econs; ss; eauto. rewrite IdentMap.gss; eauto.\n        ss. unfold NPAuxThread.consistent. unfold Thread.consistent_nprm; ii; ss; eauto.\n        eapply Hcofix with (inj := inj'); eauto.\n        {\n          ii. rewrite IdentMap.gso in READY_TGT_THD; eauto.\n          rewrite IdentMap.add_add_eq; eauto.\n          rewrite IdentMap.gso; eauto.\n          exploit READY_THRDS; eauto. ii; des.\n          do 2 eexists. split; eauto.\n          split; eauto.\n          eapply local_sim_out_rely_condition with (n_src := S n) in x4; 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.\n          inv WF_CONFIG_TGT'; eauto.\n          inv WF_CONFIG_TGT'; eauto.\n          inv WF_CONFIG_SRC''; eauto.\n          inv WF_CONFIG_SRC''; eauto.\n        }\n        {\n          ii. rewrite IdentMap.add_add_eq; eauto.\n          try rewrite IdentMap.gss in *; eauto.\n          inv CUR_TGT_THRD. eapply inj_pair2 in H1. subst.\n          do 3 eexists. split; eauto.\n        }\n        {\n          rewrite IdentMap.add_add_eq; eauto.\n          ii. rewrite IdentMap.mem_find. \n          destruct (Loc.eq_dec tid ctid); subst.\n          rewrite IdentMap.gss; eauto.\n          rewrite IdentMap.gso; eauto.\n          rewrite IdentMap.mem_find in IN_SRC_THRDS.\n          rewrite IdentMap.gso in IN_SRC_THRDS; eauto.\n          rewrite <- IdentMap.mem_find in IN_SRC_THRDS.\n          eapply COMPLETE_THRDS_MAP in IN_SRC_THRDS.\n          rewrite IdentMap.mem_find in IN_SRC_THRDS. 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_tau; eauto.\n          unfold NPAuxThread.consistent. unfold Thread.consistent_nprm; ii; eauto.\n          ss. eapply Relation_Operators.rt1n_trans. 2: eauto.\n          econs. eapply NPConfiguration.step_out; ss; eauto; ss.\n          rewrite IdentMap.gss; eauto.\n          unfold NPAuxThread.consistent. unfold Thread.consistent_nprm; ii; eauto.\n          eauto.\n        }\n        {\n          introv WW_RACE. destruct WW_RACE as (npc' & TO_WW_RACE & WW_RACE).\n          contradiction WWRF.\n          exists npc'.\n          split.\n          eapply Relation_Operators.rt1n_trans.\n          econs. eapply NPConfiguration.step_tau; eauto.\n          unfold NPAuxThread.consistent. unfold Thread.consistent_nprm; ii; eauto.\n          ss. eapply Relation_Operators.rt1n_trans. 2: eauto.\n          econs. eapply NPConfiguration.step_out; ss; eauto; ss.\n          rewrite IdentMap.gss; eauto.\n          unfold NPAuxThread.consistent. unfold Thread.consistent_nprm; ii; eauto.\n          eauto.\n        }\n        {\n          rewrite IdentMap.add_add_eq; eauto.\n        }\n        {\n          inv LOCAL_SIM_PSV; ss.\n          contradiction SAFE.\n          eexists. split.\n          eapply Relation_Operators.rt1n_trans.\n          econs. eapply NPConfiguration.step_tau; eauto.\n          unfold NPAuxThread.consistent. unfold Thread.consistent_nprm; ss.\n          ii. eexists. split. eauto. ss.\n          ss. \n          eapply Relation_Operators.rt1n_trans.\n          econs. eapply NPConfiguration.step_out; eauto.\n          ss. rewrite IdentMap.gss; eauto.\n          ss. unfold NPAuxThread.consistent. unfold Thread.consistent_nprm; ss. ii.\n          eexists. split. eauto. ss.\n          ss. eauto. ss.\n          eapply NPAuxThread_tau_steps_2_Thread_tau_steps in NP_STEPS; ss.\n          econs; ss. do 3 eexists.\n          split. \n          erewrite IdentMap.gss; eauto.\n          split; eauto.\n          clear - STEP_INV RELY_STEP.\n          ii. exploit RELY_STEP; eauto. ii; des.\n          inv STEP_INV. eauto.\n        }\n        {\n          inv LOCAL_SIM_PSV; ss.\n          contradiction SAFE.\n          eexists. split.\n          eapply Relation_Operators.rt1n_trans.\n          econs. eapply NPConfiguration.step_tau; eauto.\n          unfold NPAuxThread.consistent. unfold Thread.consistent_nprm; ss.\n          ii. eexists. split. eauto. ss.\n          ss. \n          eapply Relation_Operators.rt1n_trans.\n          econs. eapply NPConfiguration.step_out; eauto.\n          ss. rewrite IdentMap.gss; eauto.\n          ss. unfold NPAuxThread.consistent. unfold Thread.consistent_nprm; ss. ii.\n          eexists. split. eauto. ss.\n          ss. eauto. ss.\n          eapply NPAuxThread_tau_steps_2_Thread_tau_steps in NP_STEPS; ss.\n          econs; ss. do 3 eexists.\n          split. \n          erewrite IdentMap.gss; eauto.\n          split; eauto.\n          clear - WELL_FORMED_INV RELY_STEP.\n          exploit RELY_STEP; eauto. intros; des. clear RELY_STEP x0.\n          unfold wf_I in WELL_FORMED_INV.\n          eapply WELL_FORMED_INV in x; ss. inv x; eauto.\n        }\n      }\n    }\n    {\n      (* abort *)\n      clear - x SAFE S_STEPS ABORT.\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  + (* switch *)\n    destruct npc_tgt'. destruct cfg.\n    destruct (Loc.eq_dec tid ctid).\n    {\n      (* switch to the same thread *)\n      subst.\n      inv TGT_SW; ss.\n      {\n        (* thread not term *)\n        inv NPC2; ss.\n        exploit CUR_THRD; eauto. ii; des.\n        do 2 eexists.\n        split. eauto.\n        split.\n        econs; ss; eauto.\n        eapply Hcofix; eauto.\n        {\n          introv ABORT.\n          destruct ABORT as (npc & TO_ABORT & ABORT).\n          contradiction SAFE.\n          eexists.\n          split.\n          eapply Relation_Operators.rt1n_trans.\n          econs. eapply NPConfiguration.step_sw; ss; eauto.\n          eauto. eauto.\n        }\n        {\n          introv WW_RACE.\n          destruct WW_RACE as (npc' & TO_WW_RACE & WW_RACE).\n          contradiction WWRF.\n          exists npc'.\n          split.\n          eapply Relation_Operators.rt1n_trans.\n          econs. eapply NPConfiguration.step_sw; ss; eauto.\n          eauto. eauto.\n        }\n      }\n      {\n        (* thread term: contradiction *)\n        inv NPC2.\n        rewrite IdentMap.grs in NEW_TID_OK. ss.\n      }\n    }\n    {\n      (* switch to another thread *)\n      inv TGT_SW; ss; subst. \n      {\n        (* thread not term *)\n        inv NPC2; ss.\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        do 2 eexists.\n        split. eauto.\n        split.\n        econs; eauto; ss.\n        ss.\n        eapply Hcofix; eauto. \n        { \n          ii.\n          destruct (Loc.eq_dec tid ctid); subst.\n          {\n            exploit CUR_THRD; [eapply READY_TGT_THD | eauto..].\n            ii; des. \n            do 2 eexists. split; eauto.\n            exploit x4; eauto. ii; subst.\n            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            exploit WF_ATM_BIT; eauto. ii; subst.\n            exists npc'.\n            split. eauto.\n            eapply NPConfig_abort_to_Config_abort; eauto.\n          }\n          {\n            exploit READY_THRDS; eauto.\n          }\n        }\n        {\n          ii.\n          exploit READY_THRDS; eauto. ii; des.\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          ii; des.\n          do 3 eexists.\n          split. eauto.\n          split. eauto.\n          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.\n          eapply NPConfiguration.step_sw; eauto.\n          ss. eauto.\n        }\n        {\n          introv WW_RACE. destruct WW_RACE as (npc & TO_WW_RACE & WW_RACE).\n          contradiction WWRF.\n          exists npc.\n          split.\n          eapply Relation_Operators.rt1n_trans.\n          econs.\n          eapply NPConfiguration.step_sw; eauto.\n          ss. eauto.\n        }\n        {\n          eapply wf_config_sw_prsv; eauto.\n        }\n        {\n          eapply wf_config_sw_prsv; eauto.\n        }\n      }\n      {\n        (* thread term *) \n        inv NPC2; ss.\n        exploit CUR_THRD; eauto. ii. des.\n        inv x0; ss.\n        {\n          (* source 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; ss.\n          do 3 eexists.\n          split. eauto.\n          split. eapply NP_STEPS. eauto.\n        }\n        {\n          (* source not abort *)\n          clear THRD_STEP RELY_STEP THRD_ABORT.\n          exploit THRD_DONE0; eauto. ii; des.\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'). 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            inv Hprefix_tau_steps; ss.\n            do 2 eexists.\n            split. eauto.\n            split. \n            eapply NPConfiguration.step_thread_term; eauto; ss.\n            instantiate (3 := tid2). rewrite IdentMap.gro; eauto.\n            ss.\n            eapply Hcofix with (inj := inj'); eauto.\n            {\n              ii.\n              destruct (Loc.eq_dec tid ctid); subst.\n              rewrite IdentMap.grs in READY_TGT_THD; ss.\n              rewrite IdentMap.gro in READY_TGT_THD; eauto.\n              rewrite IdentMap.gro; eauto.\n              exploit READY_THRDS; eauto. ii; des.\n              eapply local_sim_rely_condition with (n_tgt := 0) (n_src := 0) in x10; 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              try rewrite IdentMap.gro in *; eauto.\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 x10; eauto.\n              rewrite NEW_TID_OK in CUR_TGT_THRD.\n              inv CUR_TGT_THRD. eapply inj_pair2 in H1. subst. \n              eapply rely_local_sim_state_to_local_sim_state in x10; eauto.\n              do 3 eexists.\n              split. eauto.\n              split. eauto.\n              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              ii. rewrite IdentMap.mem_find in IN_SRC_THRDS.\n              destruct (Loc.eq_dec tid ctid); subst.\n              rewrite IdentMap.grs in IN_SRC_THRDS; ss.\n              rewrite IdentMap.mem_find.\n              try rewrite IdentMap.gro in *; eauto.\n              try rewrite <- IdentMap.mem_find in *.\n              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              introv WW_RACE. destruct WW_RACE as (npc & TO_WW_RACE & WW_RACE).\n              contradiction WWRF.\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              eapply wf_config_rm_prsv; eauto.\n            }\n            {\n              eapply wf_config_rm_prsv; eauto.\n            }\n            {\n              ii. split; eauto.\n              inv STEP_INV; eauto.\n            }\n            {\n              clear - WELL_FORMED_INV x5.\n              unfold wf_I in WELL_FORMED_INV.\n              eapply WELL_FORMED_INV in x5; ss. inv x5; eauto.\n            }\n          }\n          {\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 - x3. inv x3. eauto.\n            }\n            exploit rtcn_rtc; [eapply Hprefix_tau_steps | eauto..]. introv PROFIX_STEPS_TEMP.\n            destruct e_src.\n            exploit wf_config_rtc_NPThread_tau_steps_prsv; [ | | eapply PROFIX_STEPS_TEMP | eauto..]; eauto.\n            introv WF_CONFIG_SRC'.\n            do 2 eexists.\n            split. clear PROFIX_STEPS_TEMP.\n            eapply Relation_Operators.rt1n_trans.\n            eapply NPConfiguration.step_tau; eauto.\n            unfold NPAuxThread.consistent. unfold Thread.consistent_nprm; ss. ii.\n            eexists. split; eauto.\n            ss. eauto.\n            split.\n            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            eapply Hcofix with (inj := inj'); eauto.\n            {\n              ii.\n              destruct (Loc.eq_dec tid ctid); subst.\n              rewrite IdentMap.grs in READY_TGT_THD; ss.\n              try rewrite IdentMap.gro in *; eauto.\n              rewrite IdentMap.gso; eauto.\n              exploit READY_THRDS; eauto. ii; des.\n              clear PREFIX_STEPS PREFIX_STEP.\n              eapply local_sim_rely_condition with (n_tgt := 0) (n_src := (S n0)) in x10; 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              ss. clear PREFIX_STEPS PREFIX_STEP. ii.\n              destruct (Loc.eq_dec tid2 ctid); subst.\n              rewrite IdentMap.grs in CUR_TGT_THRD. ss.\n              try rewrite IdentMap.gro in *; eauto.\n              rewrite IdentMap.gso; eauto.\n              exploit READY_THRDS; eauto. ii; des.\n              eapply local_sim_rely_condition with (n_tgt := 0) (n_src := (S n0)) in x10; eauto.\n              eapply rely_local_sim_state_to_local_sim_state in x10; eauto.\n              do 3 eexists.\n              split. eauto.\n              split. eauto.\n              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              inv STEP_INV; ss; eauto.\n              clear - x0 ATOMIC_COVER.\n              eapply na_steps_dset_to_Thread_na_steps in x0.\n              eapply Mem_at_eq_na_steps_prsv with (m := mem_tgt) in x0; ss; eauto.\n              eapply Mem_at_eq_reflexive; eauto.\n              eapply Mem_at_eq_reflexive; 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 := 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            {\n              ii. try rewrite IdentMap.mem_find in *.\n              destruct (Loc.eq_dec tid ctid); subst. \n              rewrite IdentMap.grs in IN_SRC_THRDS; eauto.\n              try rewrite IdentMap.gro in *; eauto.\n              rewrite IdentMap.gso in IN_SRC_THRDS; eauto.\n              try rewrite <- IdentMap.mem_find in *.\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            {\n              introv WW_RACE. destruct WW_RACE as (npc' & TO_WW_RACE & WW_RACE).\n              contradiction WWRF. clear PROFIX_STEPS_TEMP.\n              exists 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              eapply wf_config_rm_prsv; eauto.\n            }\n            {\n              eapply wf_config_rm_prsv; eauto.\n            }\n            {\n              ss. ii.\n              split; eauto.\n              inv STEP_INV.\n              eapply na_steps_dset_to_Thread_na_steps in x0. \n              eapply Mem_at_eq_na_steps_prsv with (m := mem_tgt) in x0; eauto; ss.\n              eapply Mem_at_eq_reflexive; eauto.\n              eapply Mem_at_eq_reflexive; eauto.\n            }\n            { \n              clear - WELL_FORMED_INV x5; ss.\n              unfold wf_I in WELL_FORMED_INV.\n              eapply WELL_FORMED_INV in x5; ss. inv x5; eauto.\n            }\n          }\n        }\n      }\n    }\n  + (* program done *)\n    inv TGT_DONE; ss. des.\n    exploit CUR_THRD; eauto. ii. des.\n    inv x1; ss.\n    {\n      (* source 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; ss.\n      do 3 eexists.\n      split. eauto.\n      split. eapply NP_STEPS. eauto.\n    }\n    {\n      (* source not abort *)\n      clear THRD_STEP RELY_STEP THRD_ABORT.\n      exploit THRD_DONE; eauto. ii; des. clear THRD_DONE.\n      exploit na_steps_dset_to_NPThread_tau_steps; eauto.\n      instantiate (1 := b'). introv Hprefix_tau_steps. des. renames x to lang.\n      eapply rtc_rtcn in Hprefix_tau_steps.\n      destruct Hprefix_tau_steps as (n0 & Hprefix_tau_steps).\n      assert(TO_DONE_S: IdentMap.is_empty (IdentMap.remove ctid ths_src) = true).\n      {\n        eapply IdentMap.is_empty_1.\n        eapply IdentMap.is_empty_2 in H1.\n        unfold IdentMap.Empty in *. ii.\n        eapply IdentMap.find_1 in H2.\n        destruct (Loc.eq_dec a ctid); subst.\n        rewrite IdentMap.grs in H2; ss.\n        rewrite IdentMap.gro in H2; eauto.\n        assert(CONRT_SRC: IdentMap.mem a ths_src = true).\n        {\n          rewrite IdentMap.mem_find. rewrite H2; eauto.\n        }\n        exploit COMPLETE_THRDS_MAP; eauto. introv CONTR_TGT.\n        rewrite IdentMap.mem_find in CONTR_TGT.\n        destruct (IdentMap.find a ths_tgt) eqn: CONTR_TGT_TID; ss.\n        specialize (H1 a p).\n        contradiction H1.\n        eapply IdentMap.find_2. rewrite IdentMap.gro; eauto.\n      }\n      assert(CONSISTENT_S: Local.promises (Thread.local e_src) = Memory.bot).\n      {\n        clear - x4. inv x4. eauto.\n      }\n      destruct n0.\n      {\n        inv Hprefix_tau_steps; ss.\n        eexists. split. eauto.\n        econs; eauto.\n      }\n      {\n        exploit Behavior.rtcn_tail; eauto. ii; des.\n        destruct e_src.\n        eexists.\n        split.\n        eapply Relation_Operators.rt1n_trans.\n        eapply rtcn_rtc in x7.\n        eapply NPConfiguration.step_tau; eauto.\n        unfold NPAuxThread.consistent. unfold Thread.consistent_nprm; ss. ii.\n        eexists. split. eauto. ss.\n        ss. eauto.\n        econs; eauto.\n        ss.\n        rewrite IdentMap.gss.\n        do 2 eexists. split. eauto.\n        split; eauto.\n        eapply IdentMap.is_empty_2 in TO_DONE_S.\n        eapply IdentMap.is_empty_1; eauto.\n        unfold IdentMap.Empty in *. ii.\n        specialize (TO_DONE_S a e). contradiction TO_DONE_S.\n        eapply IdentMap.find_1 in H2.\n        eapply IdentMap.find_2.\n        destruct (Loc.eq_dec a ctid); subst.\n        rewrite IdentMap.grs in H2; ss.\n        rewrite IdentMap.gro in H2; eauto.\n        rewrite IdentMap.gso in H2; eauto.\n        rewrite IdentMap.gro; eauto. \n      }\n    }\n  + (* abort *) \n    inv TGT_ABORT; ss. des; subst; ss.\n    exploit CUR_THRD; eauto. ii; des.\n    eapply rtc_rtcn in H2; des.\n    exploit sim_tau_steps; eauto; ss.\n    eapply wf_config_to_local_wf; eauto.\n    inv WF_CONFIG_TGT; eauto. inv WF_CONFIG_TGT; eauto.\n    inv H3. des; eauto.\n    ii; des.\n    {\n      inv LOCAL_SIM_PSV; ss.\n      {\n        (* source thread abort *)\n        contradiction SAFE.\n        eapply NPAuxThread_tau_steps_2_Thread_tau_steps in S_STEPS; ss.\n        eapply NPAuxThread_tau_steps_2_Thread_tau_steps in NP_STEPS; ss.\n        eexists.\n        split. eauto. ss.\n        econs; ss.\n        do 3 eexists.\n        split. eapply x0.\n        split. eapply rtc_compose. eapply S_STEPS. eapply NP_STEPS.\n        eauto.\n      }\n      {\n        (* target not promise consistent *)\n        inv H3; ss.\n      }\n      {\n        (* source thread not abort *)\n        clear THRD_STEP RELY_STEP THRD_DONE.\n        exploit THRD_ABORT; eauto. ii; des.\n        eapply rtc_rtcn in x4. des.\n        eapply rtc_na_p_to_np with (b := b_src') in x4; eauto. des.\n        eapply np_na_steps_is_tau_steps in x4.\n        eexists. split. eauto.\n        econs; ss.\n        do 6 eexists.\n        split. eauto. ss.\n        split. eapply x0.\n        split. eauto.\n        split.\n        eapply rtc_compose. eapply S_STEPS. eapply x4.\n        eauto.\n      }\n    }\n    {\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. eauto.\n      split. eapply S_STEPS. eauto.\n    }\n    Unshelve.\n    exact state.\n    exact true.\n    exact lang.\n    exact st_src0.\n    exact true.\n    exact st_src0.\n    exact true.\n    exact lang.\n    exact st_src.\n    exact true.\n    exact st_src.\n    exact true.\n    exact st_src.\n    exact true.\n    exact st_src.\n    exact true.\nQed.\n\n(** ** Compositionality *)\n(** It depicts the following conclusion, if\n    - [LOCAL_SIM]: local simulation holds;\n    - [SAFE_NP_SRC]: source program is safe under the non-preemptive semantics;\n    - [WW_RF_NP_SRC]: source progra is write-write race freedom;\n    then the global simulation holds. *)\nTheorem compositionality\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  glob_sim lang lo fs ctid code_t code_s.\nProof.\n  intros.\n  inv LOCAL_SIM.\n  unfold glob_sim.\n  introv TGT_INIT.\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 TGT_INIT. \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  rewrite H_src_init.\n  eexists. split; eauto.\n\n  (* construct global simulation *)\n  destruct c_tgt, c_src; simpls.\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  eapply compositionality_aux with (I := I) (inj := inj_init); 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; eauto.\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; eauto. ss.\n    unfold Local.promise_consistent, Local.init; ii; ss.\n    rewrite Memory.bot_get in PROMISE; eauto. ss.\n  }\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 3 eexists.\n    split; eauto. split; eauto.\n    split; eauto.\n    unfold Local.promise_consistent, Local.init; ii; ss.\n    rewrite Memory.bot_get in PROMISE; eauto. ss.\n  }\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  {\n    (* write-write race free *)\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  { \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  {\n    (* well-formed source configuration 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  {\n    (* init Mem_at_eq I *)\n    ii. split; eauto.\n    eapply Mem_at_eq_init.\n  }\n  {\n    (* monotonic inj *)\n    unfold monotonic_inj. unfold inj_init; ss. ii.\n    des_ifH INJ1; ss; subst. inv INJ1.\n    des_ifH INJ2; ss; subst. inv INJ2.\n    auto_solve_time_rel.\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/Compositionality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.26972022794302514}}
{"text": "Require Import Crypto.Specific.Framework.RawCurveParameters.\nRequire Import Crypto.Util.LetIn.\n\n(***\nModulus : 2^256 - 4294968273\nBase: 25.6\n***)\n\nDefinition curve : CurveParameters :=\n  {|\n    sz := 10%nat;\n    base := 25 + 3/5;\n    bitwidth := 64;\n    s := 2^256;\n    c := [(1, 4294968273)];\n    carry_chains := Some [seq 0 (pred 10); [0; 1]]%nat;\n\n    a24 := None;\n    coef_div_modulus := Some 2%nat;\n\n    goldilocks := None;\n    karatsuba := None;\n    montgomery := false;\n    freeze := Some true;\n    ladderstep := false;\n\n    mul_code := None;\n\n    square_code := None;\n\n    upper_bound_of_exponent_loose := None;\n    upper_bound_of_exponent_tight := None;\n    allowable_bit_widths := None;\n    freeze_extra_allowable_bit_widths := None;\n    modinv_fuel := None\n  |}.\n\nLtac extra_prove_mul_eq _ := idtac.\nLtac extra_prove_square_eq _ := idtac.\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/Specific/solinas64_2e256m4294968273_10limbs/CurveParameters.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.26962329015498815}}
{"text": "Require Import VST.concurrency.common.core_semantics.\nRequire Import VST.concurrency.common.semantics.\nRequire Import VST.sepcomp.event_semantics.\n\n(*\n\n{ initial_core : nat -> M -> C -> Values.val -> list Values.val -> Prop;\n    at_external : C -> M -> option (AST.external_function * AST.signature * list Values.val);\n    after_external : option Values.val -> C -> M -> option C;\n    halted : C -> Integers.Int.int -> Prop;\n    corestep : G -> C -> M -> C -> M -> Prop;\n    corestep_not_at_external : forall (ge : G) (m : M) (q : C) (m' : M) (q' : C),\n                               corestep ge q m q' m' -> at_external q m = None }\n\n *)\n\nInductive state_sum (Cs Ct:Type): Type :=\n| SState (c:Cs)\n| TState (c:Ct).\n\nDefinition state_sum_options {Cs Ct:Type} (cso: option Cs): option (state_sum Cs Ct) :=\n  match cso with\n  | Some cs => Some (SState _ _ cs)\n  | _ => None\n  end.\nDefinition state_sum_optiont {Cs Ct:Type} (cto: option Ct): option (state_sum Cs Ct) :=\n  match cto with\n  | Some ct => Some (TState _ _ ct)\n  | _ => None\n  end.\n\nDefinition state_sum_optionms {Cs Ct M:Type} (cso: option (Cs * option M)): option (state_sum Cs Ct * option M) :=\n  match cso with\n  | Some (cs, m) => Some (SState _ _ cs, m)\n  | _ => None\n  end.\nDefinition state_sum_optionmt {Cs Ct M:Type} (cto: option (Ct * option M)): option (state_sum Cs Ct * option M) :=\n  match cto with\n  | Some (ct, m) => Some (TState _ _ ct, m)\n  | _ => None\n  end.\n\nDefinition lt_op (n: nat) (no:option nat): Prop :=\n  match no with\n    | None => False\n    | Some n' => n < n' \n  end.\n\nDefinition initial_core_sum (no:option nat) (Cs Ct:Type) (M: Type)\n           (sinitial_core : nat -> M -> Cs -> M -> Values.val -> list Values.val -> Prop)\n           (tinitial_core : nat -> M -> Ct -> M -> Values.val -> list Values.val -> Prop):\n  nat -> M -> state_sum Cs Ct -> M -> Values.val -> list Values.val -> Prop :=\n  fun (n:nat) m c m' val vals =>\n    match c with\n    | SState c => lt_op n no /\\ sinitial_core n m c m' val vals\n    | TState c => ~lt_op n no /\\ tinitial_core n m c m' val vals\n    end.\n\nDefinition sum_func {Cs Ct X:Type} (fs:Cs -> X) (ft:Ct-> X) s:=\n  match s with\n  | SState c => (fs c)\n  | TState c => (ft c)\n  end.\n\nDefinition sum_func_option {Cs Ct Cs' Ct':Type} \n           (fs: Cs -> option Cs') (ft: Ct-> option Ct') s:=\n  match s with\n  | SState c => state_sum_options (fs c) \n  | TState c => state_sum_optiont (ft c) \n  end.\n\nDefinition at_external_sum (Cs Ct M: Type)\n           (sat_external: Cs -> M -> option (AST.external_function * list Values.val))\n           (tat_external: Ct -> M -> option (AST.external_function * list Values.val))\n           :=\n  sum_func sat_external tat_external.\n\nDefinition after_external_sum (Cs Ct M: Type)\n           (safter_external: option Values.val -> Cs -> M -> option Cs)\n           (tafter_external: option Values.val -> Ct -> M -> option Ct)\n           :=\n  fun vals c m => sum_func_option (fun c => safter_external vals c m)\n                                  (fun c => tafter_external vals c m) c.\n\nDefinition halted_sum Cs Ct\n           (shalted: Cs -> Integers.Int.int -> Prop)\n           (thalted: Ct -> Integers.Int.int -> Prop) :=\n  sum_func shalted thalted.\n\nInductive corestep_sum {M Cs Ct}\n          (scorestep: Cs -> M -> Cs -> M -> Prop)\n          (tcorestep: Ct -> M -> Ct -> M -> Prop):\n  state_sum Cs Ct -> M -> state_sum Cs Ct -> M -> Prop:=\n| SCorestep: forall s m s' m',\n    scorestep s m s' m' ->\n    corestep_sum scorestep tcorestep (SState _ _ s) m (SState _ _ s') m'\n| TCorestep: forall s m s' m',\n    tcorestep s m s' m' ->\n    corestep_sum scorestep tcorestep (TState _ _ s) m (TState _ _ s') m'.\n\nLemma corestep_not_at_external_sum:\n  forall M Cs Ct\n    {scorestep: Cs -> M -> Cs -> M -> Prop} \n    {sat_external: Cs -> M -> option (AST.external_function * list Values.val)}\n    (scorestep_not_at_external: forall (m : M) (q : Cs) (m' : M) (q' : Cs),\n        scorestep q m q' m' -> sat_external q m = None)\n    {tcorestep: Ct -> M -> Ct -> M -> Prop}\n    {tat_external: Ct -> M -> option (AST.external_function * list Values.val)}\n    (tcorestep_not_at_external: forall (m : M) (q : Ct) (m' : M) (q' : Ct),\n        tcorestep q m q' m' -> tat_external q m = None),\n  forall (m : M) (q : state_sum Cs Ct) (m' : M) (q' : state_sum Cs Ct),\n    corestep_sum scorestep tcorestep q m q' m' ->\n    at_external_sum _ _ _ sat_external tat_external q m = None.\nProof.\n  intros.\n  inversion H; subst; simpl in *.\n  - eapply scorestep_not_at_external; eauto. \n  - eapply tcorestep_not_at_external; eauto.\nQed.\n\nLemma corestep_not_halted_sum:\n  forall  M Cs Ct\n    (scorestep: Cs -> M -> Cs -> M -> Prop) \n    (shalted : Cs -> Integers.Int.int -> Prop)\n    (scorestep_not_halted: forall (m : M) (q : Cs) (m' : M) (q' : Cs) n,\n        scorestep q m q' m' -> ~ shalted q n)\n    (tcorestep: Ct -> M -> Ct -> M -> Prop)\n    (thalted : Ct -> Integers.Int.int -> Prop)\n    (tcorestep_not_halted: forall (m : M) (q : Ct) (m' : M) (q' : Ct) n,\n        tcorestep q m q' m' -> ~ thalted q n),\n  forall (m : M) (q : state_sum Cs Ct) (m' : M) (q' : state_sum Cs Ct) n,\n    corestep_sum scorestep tcorestep q m q' m' ->\n    ~ halted_sum _ _ shalted thalted q n.\nProof.\n  intros.\n  inversion H; subst; simpl; eauto.\nQed.\n\n(*\nLemma at_external_halted_excl_sum:\n  forall M Cs Ct\n    (scorestep: Cs -> M -> Cs -> M -> Prop) \n    (shalted : Cs -> Integers.Int.int -> option Values.val)\n    (sat_external: Cs -> M -> option (AST.external_function * list Values.val))\n    (sat_external_halted_excl : forall ge (q : Cs) m, sat_external q m = None \\/ shalted q )\n    (tcorestep: Ct -> M -> Ct -> M -> Prop)\n    (thalted : Ct -> Integers.Int.int -> option Values.val)\n    (tat_external: Ct -> M -> option (AST.external_function * list Values.val))\n    (tat_external_halted_excl : forall ge (q : Ct) m, tat_external q m = None \\/ thalted q = None),\n  forall  (m : M) (q : state_sum Cs Ct),\n    at_external_sum _ _ _ sat_external tat_external q m = None \\/\n    halted_sum _ _ shalted thalted q = None.\nProof.\n  intros.\n  destruct q; simpl; auto.\nQed.*)\n\nProgram Definition CoreSemanticsSum hb M Cs Ct\n        (CSs: CoreSemantics Cs M )\n        (CSt: CoreSemantics Ct M ): CoreSemantics (state_sum Cs Ct) M:=\n  Build_CoreSemantics _ _\n    (initial_core_sum hb _ _ _ (initial_core CSs) (initial_core CSt))\n    (at_external_sum _ _ _ (at_external CSs) (at_external CSt))\n    (after_external_sum _ _ _ (after_external CSs) (after_external CSt))\n    (halted_sum _ _  (halted CSs) (halted CSt))\n    (corestep_sum (corestep CSs) (corestep CSt)) \n    _\n    _.\nNext Obligation.\n  eapply corestep_not_halted_sum; try eapply H.\n  - eapply CSs.\n  - eapply CSt.\nQed.\nNext Obligation.\n  intros; eapply corestep_not_at_external_sum; eauto; first [apply CSs|apply CSt].\nQed.\n\nProgram Definition MemSemanticsSum (hb:option nat) Cs Ct\n        (CSs: MemSem Cs )\n        (CSt: MemSem Ct ): MemSem (state_sum Cs Ct):=\n  Build_MemSem _ (CoreSemanticsSum hb Memory.Mem.mem Cs Ct CSs CSt) _.\nNext Obligation.\n  intros.\n  inversion CS; subst.\n  - eapply CSs; eassumption.\n  - eapply CSt; eassumption.\nDefined.\n\nInductive ev_step_sum {Cs Ct:Type}\n          (ESs: Cs -> Memory.Mem.mem -> list mem_event -> Cs -> Memory.Mem.mem -> Prop)\n          (ESt: Ct -> Memory.Mem.mem -> list mem_event -> Ct -> Memory.Mem.mem -> Prop):\n  (state_sum Cs Ct) -> Memory.Mem.mem -> list mem_event -> (state_sum Cs Ct) -> Memory.Mem.mem -> Prop\n  :=\n| SEvstep: forall s m t s' m',\n    ESs s m t s' m' ->\n    ev_step_sum ESs ESt (SState _ _ s) m t (SState _ _ s') m'\n| TEvstep: forall s m t s' m',\n    ESt s m t s' m' ->\n    ev_step_sum ESs ESt (TState _ _ s) m t (TState _ _ s') m'.\n  \n\nProgram Definition EvSemanticsSum (hb:option nat) Cs Ct\n        (CSs: @EvSem Cs )\n        (CSt: @EvSem Ct ): @EvSem (state_sum Cs Ct):=\n  Build_EvSem _ (MemSemanticsSum hb Cs Ct CSs CSt) (ev_step_sum (ev_step CSs) (ev_step CSt)) _ _ _ _.\nNext Obligation.\n  intros.\n  inversion H; subst.\n  - constructor; eapply CSs; eauto.\n  - constructor; eapply CSt; eauto.\nDefined.\nNext Obligation.\n  intros.\n  inversion H; subst.\n  - eapply CSs in H0; destruct H0 as [T ?]. \n    exists T; constructor; eauto.\n  - eapply CSt in H0; destruct H0 as [T ?]. \n    exists T; constructor; eauto.\nDefined.\nNext Obligation.\n  intros.\n  inversion H; subst;\n  inversion H0; subst.\n  - eapply CSs; eauto.\n  - eapply CSt; eauto.\nDefined.\nNext Obligation.\n  intros.\n  inversion STEP; subst.\n  -  eapply (ev_step_elim CSs) in H. (*destruct H as [HH1 HH2];\n       split; eauto; intros.\n     apply HH2 in H.\n     destruct H as [cc' HH].\n     eexists; constructor; eauto.*) trivial.\n  -  eapply (ev_step_elim CSt) in H. (*destruct H as [HH1 HH2];\n       split; eauto; intros.\n     apply HH2 in H.\n     destruct H as [cc' HH].\n     eexists; constructor; eauto.*) trivial.\nDefined.\n\nDefinition CoreSem_Sum (hb:option nat) (Sems Semt: Semantics): Semantics:=\n  Build_Semantics _ _\n                  (EvSemanticsSum hb _ _ (@semSem Sems) (@semSem Semt))\n                  (@the_ge Sems, @the_ge Semt) .\n(* they have different genv...*)\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/compiler/CoreSemantics_sum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.26962329015498815}}
{"text": "(** * Projection functors from comma categories *)\nRequire Import Category.Core Functor.Core.\nRequire Import Category.Prod Functor.Prod.Core.\nRequire Import Functor.Composition.Core Functor.Identity.\nRequire Import InitialTerminalCategory.Functors.\nRequire Comma.Core.\nRequire Import Types.Prod.\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\". (* work around bug #5567, https://coq.inria.fr/bugs/show_bug.cgi?id=5567, notation-overridden,parsing should not trigger for only printing notations *)\n\nSet Universe Polymorphism.\nSet Implicit Arguments.\nGeneralizable All Variables.\nSet Asymmetric Patterns.\n\nLocal Open Scope functor_scope.\nLocal Open Scope category_scope.\n\n(** ** First projection [(S / T) → A × B] (for [S : A → C ← B : T]) *)\nSection comma_category.\n  Variables A B C : PreCategory.\n  Variable S : Functor A C.\n  Variable T : Functor B C.\n\n  Definition comma_category_projection : Functor (S / T) (A * B)\n    := Build_Functor\n         (S / T) (A * B)\n         (fun abf => (CommaCategory.a abf, CommaCategory.b abf)%core)\n         (fun _ _ m => (CommaCategory.g m, CommaCategory.h m)%core)\n         (fun _ _ _ _ _ => idpath)\n         (fun _ => idpath).\nEnd comma_category.\n\n(** ** First projections [(S / a) → A] and [(a / S) → A] *)\nSection slice_category.\n  Variable A : PreCategory.\n\n  Local Arguments Functor.Composition.Core.compose / .\n  Local Arguments Functor.Composition.Core.compose_composition_of / .\n  Local Arguments Functor.Composition.Core.compose_identity_of / .\n  Local Arguments path_prod / .\n  Local Arguments path_prod' / .\n  Local Arguments path_prod_uncurried / .\n\n  Definition arrow_category_projection : Functor (arrow_category A) A\n    := Eval simpl in fst o comma_category_projection _ 1.\n\n  Definition slice_category_over_projection (a : A) : Functor (A / a) A\n    := Eval simpl in fst o comma_category_projection 1 _.\n\n  Definition coslice_category_over_projection (a : A) : Functor (a \\ A) A\n    := Eval simpl in snd o comma_category_projection _ 1.\n\n  Section slice_coslice.\n    Variable C : PreCategory.\n    Variable a : C.\n    Variable S : Functor A C.\n\n    Definition slice_category_projection : Functor (S / a) A\n      := Eval simpl in fst o comma_category_projection S !a.\n\n    Definition coslice_category_projection : Functor (a / S) A\n      := Eval simpl in snd o comma_category_projection !a S.\n  End slice_coslice.\nEnd slice_category.\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/Projection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5, "lm_q1q2_score": 0.26949161034384206}}
{"text": "Require Import Undecidability.SystemF.SysF Undecidability.SystemF.Autosubst.syntax Undecidability.SystemF.Autosubst.unscoped.\nImport UnscopedNotations.\nRequire Import Undecidability.SystemF.Util.typing_facts Undecidability.SystemF.Util.term_facts.\n\nInductive step : term -> term -> Prop :=\n| step_beta s P Q :\n    step (app (abs s P) Q) (subst_term poly_var (scons Q var) P)\n| step_ty_beta P s :\n    step (ty_app (ty_abs P) s) (subst_term (scons s poly_var) var P)\n| step_appL P P' Q :\n    step P P' -> step (app P Q) (app P' Q)\n| step_appR P P' Q :\n    step P P' -> step (app Q P) (app Q P')\n| step_ty_app P P' s :\n    step P P' -> step (ty_app P s) (ty_app P' s)\n| step_lam s P P' :\n    step P P' -> step (abs s P) (abs s P')\n| step_ty_lam P P' :\n    step P P' -> step (ty_abs P) (ty_abs P').\n\nInductive sn x : Prop :=\n| SNI : (forall y, step x y -> sn y) -> sn x.\n\nLocal Hint Constructors step normal_form head_form : core.\n\nRequire Import Coq.Relations.Relation_Operators.\n\nLtac inv_step :=\n  match goal with\n    [ H : step ?P ?Q |- _] => inversion H; subst; clear H; try now firstorder\n  end.\n\nLemma progress P :\n  (forall Q, ~ step P Q) \\/ exists Q, step P Q.\nProof.\n  induction P.\n  - firstorder inv_step.\n  - destruct IHP1 as [H1 | [Q1 H1]]; eauto.\n    destruct IHP2 as [H2 | [Q2 H2]]; eauto.\n    destruct P1. 3:eauto.\n    all: firstorder inv_step.\n  - destruct IHP as [H1 | [Q1 H1]]; eauto. firstorder inv_step.\n  - destruct IHP as [H1 | [Q1 H1]]; eauto.\n    destruct P. 5:eauto. \n    all: firstorder inv_step.\n  - destruct IHP as [H1 | [Q1 H1]]; eauto. firstorder inv_step.\nQed.\n\nLemma preservation P Q Γ s :\n  typing Γ P s -> step P Q -> typing Γ Q s.\nProof.\n  induction 1 in Q |- *.\n  - inversion 1.\n  - inversion 1; subst.\n    + inversion H; subst.\n      eapply typing_subst_term. eassumption.\n      intros [] ? [=]; subst; cbn;\n      eauto using typing.\n    + eauto using typing.\n    + eauto using typing.\n  - inversion 1; subst. eauto using typing.\n  - inversion 1; subst.\n    + inversion H; subst.\n      evar (Gamma' : environment).\n      replace Gamma with Gamma'. all: subst Gamma'.\n      eapply typing_subst_poly_type. eassumption.\n      erewrite List.map_map, List.map_ext, List.map_id.\n      reflexivity. intros. now asimpl.\n    + eauto using typing.\n  - inversion 1; subst. eauto using typing.\nQed.\n\nLemma preservation_star P Q Γ s :\n  typing Γ P s -> Relation_Operators.clos_refl_trans term step P Q -> typing Γ Q s.\nProof.\n  intros H. induction 1; eauto using preservation.\nQed.\n\nLemma step_ext_2 P Q1 Q2 :\n  step P Q1 -> Q1 = Q2 -> step P Q2.\nProof.\n  now intros ? ->.\nQed.\n\nLtac now_asimpl := asimpl; ( (reflexivity || eapply ext_term; now intros []; repeat asimpl) ||\n                   f_equal; (reflexivity || eapply ext_term; now intros []; repeat asimpl)).\n\nLemma step_subst P Q σ τ :\n  step P Q -> step (subst_term σ τ P) (subst_term σ τ Q).\nProof.\n  induction 1 in σ, τ |- *; cbn; asimpl; eauto using step.\n  - eapply step_ext_2. \n    econstructor. now_asimpl.\n  - eapply step_ext_2.\n    econstructor. now_asimpl.\nQed.\n\nRequire Import Coq.Program.Equality.\n\nLtac inv H := inversion H; subst; clear H.\n\nLemma step_subst_inv P Q σ τ :\n  step (subst_term σ (τ >> var) P) Q -> exists P', step P P' /\\ subst_term σ (τ >> var) P' = Q.\nProof with eexists; split; [eauto | now_asimpl].\n  intros H. dependent induction H; rename x into Eqn.\n  - destruct P; inv Eqn. destruct P1; inv H0...\n  - destruct P; inv Eqn. destruct P; inv H0... \n  - destruct P; inv Eqn. destruct (IHstep _ _ _ eq_refl) as (P1' & H1 & <-)...\n  - destruct P; inv Eqn. destruct (IHstep _ _ _ eq_refl) as (P1' & H1 & <-)...\n  - destruct P; inv Eqn. destruct (IHstep _ _ _ eq_refl) as (P1' & H1 & <-)...\n  - destruct P; inv Eqn.\n    edestruct (IHstep P (up_term_poly_type σ) (0 .: τ >> shift))  as (P1' & H1 & <-).\n    now_asimpl. exists (abs p P1'). split. eauto. now_asimpl. \n  - destruct P; inv Eqn.  destruct (IHstep _ _ _ eq_refl) as (P1' & H1 & <-)...\nQed.\n\nDefinition nf P := match P with abs s P => normal_form P\n                           | ty_abs P => normal_form P | P => head_form P end.\n\nLemma nf_normal_form P :\n  nf P -> normal_form P.\nProof.\n  destruct P; cbn; eauto.\nQed.\n\nLemma sn_normal_form Γ P s :\n  typing Γ P s -> (forall Q, ~ step P Q) -> nf P.\nProof.\n  intros H Hstep.\n  induction H; cbn in *.\n  - eauto.\n  - econstructor.\n    destruct P.\n    all: try now (eapply IHtyping1; intros ? ?; eapply Hstep; eauto).\n    + exfalso. eapply Hstep; eauto.\n    + inversion H. \n    + eapply nf_normal_form, IHtyping2. intros ? ?; eapply Hstep; eauto.\n  - eapply nf_normal_form, IHtyping. intros ? ?. eapply Hstep. eauto.\n  - econstructor.\n    destruct P.\n    all: try now (eapply IHtyping; intros ? ?; eapply Hstep; eauto).\n    + inversion H.\n    + exfalso. eapply Hstep. eauto.\n  - eapply nf_normal_form, IHtyping. intros ? ?. eapply Hstep. eauto.\nQed.\n\nLemma sn_normal Γ P s :\n  typing Γ P s ->\n  sn P -> exists Q, clos_refl_trans _ step P Q /\\ normal_form Q.\nProof.\n  intros H.\n  induction 1 as [P Hsn IH] in s, H |- *.\n  destruct (progress P) as [Hstep | [Q Hstep]].\n  - exists P. split. econstructor 2.\n    eauto using nf_normal_form, sn_normal_form.\n  - pose proof (Hstep' := Hstep).\n    eapply IH in Hstep as (Q' & H1 & H2).\n    + exists Q'. split. econstructor 3. econstructor 1. all: eauto.\n    + eauto using preservation.\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/SystemF/Util/step.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5, "lm_q1q2_score": 0.26949161034384206}}
{"text": "From iris.bi Require Export derived_connectives extensions updates internal_eq plainly.\nFrom iris.base_logic Require Export upred.\nFrom iris.prelude Require Import options.\nImport uPred_primitive.\n\n(** BI instances for [uPred], and re-stating the remaining primitive laws in\nterms of the BI interface. This file does *not* unseal. *)\n\nDefinition uPred_emp {M} : uPred M := uPred_pure True.\n\nLocal Existing Instance entails_po.\n\nLemma uPred_bi_mixin (M : ucmra) :\n  BiMixin\n    uPred_entails uPred_emp uPred_pure uPred_and uPred_or uPred_impl\n    (@uPred_forall M) (@uPred_exist M) uPred_sep uPred_wand\n    uPred_persistently.\nProof.\n  split.\n  - exact: entails_po.\n  - exact: equiv_entails.\n  - exact: pure_ne.\n  - exact: and_ne.\n  - exact: or_ne.\n  - exact: impl_ne.\n  - exact: forall_ne.\n  - exact: exist_ne.\n  - exact: sep_ne.\n  - exact: wand_ne.\n  - exact: persistently_ne.\n  - exact: pure_intro.\n  - exact: pure_elim'.\n  - exact: and_elim_l.\n  - exact: and_elim_r.\n  - exact: and_intro.\n  - exact: or_intro_l.\n  - exact: or_intro_r.\n  - exact: or_elim.\n  - exact: impl_intro_r.\n  - exact: impl_elim_l'.\n  - exact: @forall_intro.\n  - exact: @forall_elim.\n  - exact: @exist_intro.\n  - exact: @exist_elim.\n  - exact: sep_mono.\n  - exact: True_sep_1.\n  - exact: True_sep_2.\n  - exact: sep_comm'.\n  - exact: sep_assoc'.\n  - exact: wand_intro_r.\n  - exact: wand_elim_l'.\n  - exact: persistently_mono.\n  - exact: persistently_idemp_2.\n  - (* emp ⊢ <pers> emp (ADMISSIBLE) *)\n    trans (uPred_forall (M:=M) (λ _ : False, uPred_persistently uPred_emp)).\n    + apply forall_intro=>-[].\n    + etrans; first exact: persistently_forall_2.\n      apply persistently_mono. exact: pure_intro.\n  - (* ((<pers> P) ∧ (<pers> Q)) ⊢ <pers> (P ∧ Q) (ADMISSIBLE) *)\n    intros P Q.\n    trans (uPred_forall (M:=M) (λ b : bool, uPred_persistently (if b then P else Q))).\n    + apply forall_intro=>[[]].\n      * apply and_elim_l.\n      * apply and_elim_r.\n    + etrans; first exact: persistently_forall_2.\n      apply persistently_mono. apply and_intro.\n      * etrans; first apply (forall_elim true). done.\n      * etrans; first apply (forall_elim false). done.\n  - exact: @persistently_exist_1.\n  - (* <pers> P ∗ Q ⊢ <pers> P (ADMISSIBLE) *)\n    intros. etrans; first exact: sep_comm'.\n    etrans; last exact: True_sep_2.\n    apply sep_mono; last done.\n    exact: pure_intro.\n  - exact: persistently_and_sep_l_1.\nQed.\n\nLemma uPred_bi_later_mixin (M : ucmra) :\n  BiLaterMixin\n    uPred_entails uPred_pure uPred_or uPred_impl\n    (@uPred_forall M) (@uPred_exist M) uPred_sep uPred_persistently uPred_later.\nProof.\n  split.\n  - apply contractive_ne, later_contractive.\n  - exact: later_mono.\n  - exact: later_intro.\n  - exact: @later_forall_2.\n  - exact: @later_exist_false.\n  - exact: later_sep_1.\n  - exact: later_sep_2.\n  - exact: later_persistently_1.\n  - exact: later_persistently_2.\n  - exact: later_false_em.\nQed.\n\nCanonical Structure uPredI (M : ucmra) : bi :=\n  {| bi_ofe_mixin := ofe_mixin_of (uPred M);\n     bi_bi_mixin := uPred_bi_mixin M;\n     bi_bi_later_mixin := uPred_bi_later_mixin M |}.\n\nLemma uPred_internal_eq_mixin M : BiInternalEqMixin (uPredI M) (@uPred_internal_eq M).\nProof.\n  split.\n  - exact: internal_eq_ne.\n  - exact: @internal_eq_refl.\n  - exact: @internal_eq_rewrite.\n  - exact: @fun_ext.\n  - exact: @sig_eq.\n  - exact: @discrete_eq_1.\n  - exact: @later_eq_1.\n  - exact: @later_eq_2.\nQed.\nGlobal Instance uPred_internal_eq M : BiInternalEq (uPredI M) :=\n  {| bi_internal_eq_mixin := uPred_internal_eq_mixin M |}.\n\nLemma uPred_plainly_mixin M : BiPlainlyMixin (uPredI M) uPred_plainly.\nProof.\n  split.\n  - exact: plainly_ne.\n  - exact: plainly_mono.\n  - exact: plainly_elim_persistently.\n  - exact: plainly_idemp_2.\n  - exact: @plainly_forall_2.\n  - exact: plainly_impl_plainly.\n  - (* P ⊢ ■ emp (ADMISSIBLE) *)\n    intros P.\n    trans (uPred_forall (M:=M) (λ _ : False , uPred_plainly uPred_emp)).\n    + apply forall_intro=>[[]].\n    + etrans; first exact: plainly_forall_2.\n      apply plainly_mono. exact: pure_intro.\n  - (* ■ P ∗ Q ⊢ ■ P (ADMISSIBLE) *)\n    intros P Q. etrans; last exact: True_sep_2.\n    etrans; first exact: sep_comm'.\n    apply sep_mono; last done.\n    exact: pure_intro.\n  - exact: later_plainly_1.\n  - exact: later_plainly_2.\nQed.\nGlobal Instance uPred_plainly M : BiPlainly (uPredI M) :=\n  {| bi_plainly_mixin := uPred_plainly_mixin M |}.\n\nLemma uPred_bupd_mixin M : BiBUpdMixin (uPredI M) uPred_bupd.\nProof.\n  split.\n  - exact: bupd_ne.\n  - exact: bupd_intro.\n  - exact: bupd_mono.\n  - exact: bupd_trans.\n  - exact: bupd_frame_r.\nQed.\nGlobal Instance uPred_bi_bupd M : BiBUpd (uPredI M) := {| bi_bupd_mixin := uPred_bupd_mixin M |}.\n\n(** extra BI instances *)\n\nGlobal Instance uPred_affine M : BiAffine (uPredI M) | 0.\nProof. intros P. exact: pure_intro. Qed.\n(* Also add this to the global hint database, otherwise [eauto] won't work for\nmany lemmas that have [BiAffine] as a premise. *)\nGlobal Hint Immediate uPred_affine : core.\n\nGlobal Instance uPred_persistently_forall M : BiPersistentlyForall (uPredI M).\nProof. exact: @persistently_forall_2. Qed.\n\nGlobal Instance uPred_pure_forall M : BiPureForall (uPredI M).\nProof. exact: @pure_forall_2. Qed.\n\nGlobal Instance uPred_later_contractive {M} : BiLaterContractive (uPredI M).\nProof. apply later_contractive. Qed.\n\nGlobal Instance uPred_persistently_impl_plainly M : BiPersistentlyImplPlainly (uPredI M).\nProof. exact: persistently_impl_plainly. Qed.\n\nGlobal Instance uPred_plainly_exist_1 M : BiPlainlyExist (uPredI M).\nProof. exact: @plainly_exist_1. Qed.\n\nGlobal Instance uPred_prop_ext M : BiPropExt (uPredI M).\nProof. exact: prop_ext_2. Qed.\n\nGlobal Instance uPred_bi_bupd_plainly M : BiBUpdPlainly (uPredI M).\nProof. exact: bupd_plainly. Qed.\n\n(** Re-state/export lemmas about Iris-specific primitive connectives (own, valid) *)\n\nModule uPred.\n\nSection restate.\n  Context {M : ucmra}.\n  Implicit Types φ : Prop.\n  Implicit Types P Q : uPred M.\n  Implicit Types A : Type.\n\n  (* Force implicit argument M *)\n  Notation \"P ⊢ Q\" := (bi_entails (PROP:=uPredI M) P%I Q%I).\n  Notation \"P ⊣⊢ Q\" := (equiv (A:=uPredI M) P%I Q%I).\n\n  Global Instance ownM_ne : NonExpansive (@uPred_ownM M) := uPred_primitive.ownM_ne.\n  Global Instance cmra_valid_ne {A : cmra} : NonExpansive (@uPred_cmra_valid M A) :=\n    uPred_primitive.cmra_valid_ne.\n\n  (** Re-exporting primitive lemmas that are not in any interface *)\n  Lemma ownM_op (a1 a2 : M) :\n    uPred_ownM (a1 ⋅ a2) ⊣⊢ uPred_ownM a1 ∗ uPred_ownM a2.\n  Proof. exact: uPred_primitive.ownM_op. Qed.\n  Lemma persistently_ownM_core (a : M) : uPred_ownM a ⊢ <pers> uPred_ownM (core a).\n  Proof. exact: uPred_primitive.persistently_ownM_core. Qed.\n  Lemma ownM_unit P : P ⊢ (uPred_ownM ε).\n  Proof. exact: uPred_primitive.ownM_unit. Qed.\n  Lemma later_ownM a : ▷ uPred_ownM a ⊢ ∃ b, uPred_ownM b ∧ ▷ (a ≡ b).\n  Proof. exact: uPred_primitive.later_ownM. Qed.\n  Lemma bupd_ownM_updateP x (Φ : M → Prop) :\n    x ~~>: Φ → uPred_ownM x ⊢ |==> ∃ y, ⌜Φ y⌝ ∧ uPred_ownM y.\n  Proof. exact: uPred_primitive.bupd_ownM_updateP. Qed.\n\n  (** This is really just a special case of an entailment\n  between two [siProp], but we do not have the infrastructure\n  to express the more general case. This temporary proof rule will\n  be replaced by the proper one eventually. *)\n  Lemma internal_eq_entails {A B : ofe} (a1 a2 : A) (b1 b2 : B) :\n    (a1 ≡ a2 ⊢ b1 ≡ b2) ↔ (∀ n, a1 ≡{n}≡ a2 → b1 ≡{n}≡ b2).\n  Proof. exact: uPred_primitive.internal_eq_entails. Qed.\n\n  Lemma ownM_valid (a : M) : uPred_ownM a ⊢ ✓ a.\n  Proof. exact: uPred_primitive.ownM_valid. Qed.\n  Lemma cmra_valid_intro {A : cmra} P (a : A) : ✓ a → P ⊢ (✓ a).\n  Proof. exact: uPred_primitive.cmra_valid_intro. Qed.\n  Lemma cmra_valid_elim {A : cmra} (a : A) : ¬ ✓{0} a → ✓ a ⊢ False.\n  Proof. exact: uPred_primitive.cmra_valid_elim. Qed.\n  Lemma plainly_cmra_valid_1 {A : cmra} (a : A) : ✓ a ⊢ ■ ✓ a.\n  Proof. exact: uPred_primitive.plainly_cmra_valid_1. Qed.\n  Lemma cmra_valid_weaken {A : cmra} (a b : A) : ✓ (a ⋅ b) ⊢ ✓ a.\n  Proof. exact: uPred_primitive.cmra_valid_weaken. Qed.\n  Lemma discrete_valid {A : cmra} `{!CmraDiscrete A} (a : A) : ✓ a ⊣⊢ ⌜✓ a⌝.\n  Proof. exact: uPred_primitive.discrete_valid. Qed.\n\n  (** This is really just a special case of an entailment\n  between two [siProp], but we do not have the infrastructure\n  to express the more general case. This temporary proof rule will\n  be replaced by the proper one eventually. *)\n  Lemma valid_entails {A B : cmra} (a : A) (b : B) :\n    (∀ n, ✓{n} a → ✓{n} b) → ✓ a ⊢ ✓ b.\n  Proof. exact: uPred_primitive.valid_entails. Qed.\n\n  (** Consistency/soundness statement *)\n  Lemma pure_soundness φ : (⊢@{uPredI M} ⌜ φ ⌝) → φ.\n  Proof. apply pure_soundness. Qed.\n\n  Lemma internal_eq_soundness {A : ofe} (x y : A) : (⊢@{uPredI M} x ≡ y) → x ≡ y.\n  Proof. apply internal_eq_soundness. Qed.\n\n  Lemma later_soundness P : (⊢ ▷ P) → ⊢ P.\n  Proof. apply later_soundness. Qed.\n\n  (** We restate the unsealing lemmas for the BI layer. The sealing lemmas\n  are partially applied so that they also rewrite under binders. *)\n  Local Lemma uPred_emp_unseal : bi_emp = @upred.uPred_pure_def M True.\n  Proof. by rewrite -upred.uPred_pure_unseal. Qed.\n  Local Lemma uPred_pure_unseal : bi_pure = @upred.uPred_pure_def M.\n  Proof. by rewrite -upred.uPred_pure_unseal. Qed.\n  Local Lemma uPred_and_unseal : bi_and = @upred.uPred_and_def M.\n  Proof. by rewrite -upred.uPred_and_unseal. Qed.\n  Local Lemma uPred_or_unseal : bi_or = @upred.uPred_or_def M.\n  Proof. by rewrite -upred.uPred_or_unseal. Qed.\n  Local Lemma uPred_impl_unseal : bi_impl = @upred.uPred_impl_def M.\n  Proof. by rewrite -upred.uPred_impl_unseal. Qed.\n  Local Lemma uPred_forall_unseal : @bi_forall _ = @upred.uPred_forall_def M.\n  Proof. by rewrite -upred.uPred_forall_unseal. Qed.\n  Local Lemma uPred_exist_unseal : @bi_exist _ = @upred.uPred_exist_def M.\n  Proof. by rewrite -upred.uPred_exist_unseal. Qed.\n  Local Lemma uPred_internal_eq_unseal :\n    @internal_eq _ _ = @upred.uPred_internal_eq_def M.\n  Proof. by rewrite -upred.uPred_internal_eq_unseal. Qed.\n  Local Lemma uPred_sep_unseal : bi_sep = @upred.uPred_sep_def M.\n  Proof. by rewrite -upred.uPred_sep_unseal. Qed.\n  Local Lemma uPred_wand_unseal : bi_wand = @upred.uPred_wand_def M.\n  Proof. by rewrite -upred.uPred_wand_unseal. Qed.\n  Local Lemma uPred_plainly_unseal : plainly = @upred.uPred_plainly_def M.\n  Proof. by rewrite -upred.uPred_plainly_unseal. Qed.\n  Local Lemma uPred_persistently_unseal :\n    bi_persistently = @upred.uPred_persistently_def M.\n  Proof. by rewrite -upred.uPred_persistently_unseal. Qed.\n  Local Lemma uPred_later_unseal : bi_later = @upred.uPred_later_def M.\n  Proof. by rewrite -upred.uPred_later_unseal. Qed.\n  Local Lemma uPred_bupd_unseal : bupd = @upred.uPred_bupd_def M.\n  Proof. by rewrite -upred.uPred_bupd_unseal. Qed.\n\n  Local Definition uPred_unseal :=\n    (uPred_emp_unseal, uPred_pure_unseal, uPred_and_unseal, uPred_or_unseal,\n    uPred_impl_unseal, uPred_forall_unseal, uPred_exist_unseal,\n    uPred_internal_eq_unseal, uPred_sep_unseal, uPred_wand_unseal,\n    uPred_plainly_unseal, uPred_persistently_unseal, uPred_later_unseal,\n    upred.uPred_ownM_unseal, upred.uPred_cmra_valid_unseal, @uPred_bupd_unseal).\nEnd restate.\n\n(** A tactic for rewriting with the above lemmas. Unfolds [uPred] goals that use\nthe BI layer. This is used by [base_logic.algebra] and [base_logic.bupd_alt]. *)\nLtac unseal := rewrite !uPred_unseal /=.\nEnd uPred.\n", "meta": {"author": "amintimany", "repo": "iris", "sha": "03eaffa3b28bffc561b93f30a3ba40bab8ae1fd1", "save_path": "github-repos/coq/amintimany-iris", "path": "github-repos/coq/amintimany-iris/iris-03eaffa3b28bffc561b93f30a3ba40bab8ae1fd1/iris/base_logic/bi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.26935993243181544}}
{"text": "From Coq Require Import Arith Bool List Lia.\nFrom Giskard Require Import structures.\n\nImport ListNotations.\n\nSet Implicit Arguments.\n\n(** * Local state operations, properties, and transitions *)\n\n(** Local state transitions capture message sending, receiving and processing\nbehaviors of individual nodes. Local state transitions can be defined as a\nquaternary relation on:\n- pre-state, \n- incoming message, \n- post-state, and\n- outgoing message(s).\n\nValid Giskard local state transitions can be defined as a predicate on these relations. *)\n\n(** ** Local state operations *)\n\n(** The following section defines operations that transform the pre-state\nto post-state in local state transitions. *)\n\n(** Received messages are stored in the in buffer. *) \nDefinition received (s : NState) (m : message) : Prop :=\n  In m (in_messages s).\n\n(** Sent messages are stored in the out buffer, as history.  *) \nDefinition sent (s : NState) (m : message) : Prop :=\n  In m (out_messages s).\n\nDefinition record (s : NState) (m : message) : NState :=\n mkNState (node_view s) (node_id s)\n  (in_messages s) (counting_messages s)  (m :: out_messages s) (timeout s).\n\nDefinition record_plural (s : NState) (lm : list message) : NState :=\n mkNState (node_view s) (node_id s)\n  (in_messages s) (counting_messages s)  (lm ++ out_messages s) (timeout s).\n\n(** Broadcast messages are stored in the in buffer, awaiting processing. *) \nDefinition add (s : NState) (m : message) : NState :=\n mkNState (node_view s) (node_id s)\n  (m :: in_messages s) (counting_messages s)  (out_messages s) (timeout s).\n\nDefinition add_plural (s : NState) (lm : list message) : NState :=\n mkNState (node_view s) (node_id s)\n  (lm ++ in_messages s) (counting_messages s) (out_messages s)  (timeout s).\n\n(** Invalid messages are removed from the in buffer, and thus unable to be processed. *) \nDefinition discard (s : NState) (m : message) : NState :=\n mkNState (node_view s) (node_id s)\n  (remove message_eq_dec m (in_messages s)) (counting_messages s) (out_messages s)  (timeout s).\n\n(** Processed messages are removed from the in buffer and added to the counting buffer. *)\nDefinition process (s : NState) (msg : message) : NState :=\n mkNState (node_view s) (node_id s)\n  (remove message_eq_dec msg (in_messages s)) (msg :: counting_messages s) (out_messages s) (timeout s).\n\n(** During a normal or abnormal view change, the view is incremented,\nand the in message buffer and timeout flag reset. *)\nDefinition increment_view (s : NState) : NState :=\n  mkNState (S (node_view s)) (node_id s) [] (counting_messages s) (out_messages s) false.\n\n(** ** Local state properties *)\n\n(** The following section defines properties that constitute pre- and post- conditions\nfor local state transitions. *)\n\n(** A message has a valid view with respect to a local state when it is equal to the\nlocal state's current view. Nodes only process \"non-expired\" messages sent in its current view. *)\nDefinition view_valid (s : NState) (msg : message) : Prop :=\n  node_view s = get_view msg.\n\nDefinition view_validb (s : NState) (msg : message) : bool :=\n  Nat.eqb (node_view s) (get_view msg).\n\n(** *** Byzantine behavior *)\n\n(** The primary form of Byzantine behavior Giskard considers is double voting:\nsending two PrepareVote messages for two different blocks of the same height within the same view.\nWe call two messages equivocating if they evidence double voting behavior of their sender. *)\nDefinition equivocating_messages (s : NState) (msg1 msg2 : message) : Prop :=\n  In msg1 (out_messages s) /\\\n  In msg2 (out_messages s) /\\\n  get_view msg1 = get_view msg2 /\\\n  get_message_type msg1 = PrepareVote /\\\n  get_message_type msg2 = PrepareVote /\\\n  get_block msg1 <> get_block msg2 /\\\n  b_height (get_block msg1) = b_height (get_block msg2).\n\n(** Duplicate block checking for either:\n- a PrepareVote message in the processed message buffer for a different block of the same height, or\n- a PrepareVote or PrepareQC message in the sent message buffer for a different block of the same height. *)\nDefinition exists_same_height_block_old (s : NState) (b : block) : Prop :=\n  (* Either PrepareBlock has been processed, but no vote has been cast *) \n  (exists msg, In msg (counting_messages s) /\\\n          get_message_type msg = PrepareBlock /\\ \n          b_height b = b_height (get_block msg) /\\\n          b <> get_block msg)\n  (* Or a PrepareVote or PrepareQC has been sent *) \n  \\/\n  (exists msg, In msg (out_messages s) /\\\n          (get_message_type msg = PrepareVote \\/\n           get_message_type msg = PrepareQC) /\\ \n          b_height b = b_height (get_block msg) /\\\n          b <> get_block msg). \n\nDefinition exists_same_height_block (s : NState) (b : block) : Prop :=\n  exists msg, In msg (out_messages s) /\\\n         get_message_type msg = PrepareVote /\\\n         b_height b = b_height (get_block msg) /\\\n         b <> get_block msg. \n\nDefinition exists_same_height_PrepareBlock (s : NState) (b : block) : Prop :=\n  exists msg, In msg (counting_messages s) /\\\n         get_message_type msg = PrepareBlock /\\\n         b_height b = b_height (get_block msg) /\\\n         b <> get_block msg.\n\nDefinition same_height_block_msg (b : block) (msg : message) :=\n get_message_type msg = PrepareVote /\\\n b_height b = b_height (get_block msg) /\\\n b <> get_block msg.\n\nDefinition same_height_block_msg_dec (b : block) (msg : message) :\n  { same_height_block_msg b msg }+{ ~ same_height_block_msg b msg }.\nProof.\ndestruct (message_type_eq_dec (get_message_type msg) PrepareVote).\n- destruct (Nat.eq_dec (b_height b) (b_height (get_block msg))).\n  * destruct (block_eq_dec b (get_block msg)).\n    + right.\n      intro.\n      destruct H.\n      destruct H0.\n      congruence.\n    + left.\n      split; [assumption|].\n      split; [assumption|].\n      assumption.\n  * right.\n    unfold same_height_block_msg.\n    intro.\n    destruct H.\n    destruct H0.\n    congruence.\n- right.\n  unfold same_height_block_msg.\n  simpl.\n  intro.\n  destruct H.\n  congruence.\nDefined.\n\nProgram Definition exists_same_height_block_dec (s : NState) (b : block) :\n { exists_same_height_block s b }+{~ exists_same_height_block s b} :=\nmatch Exists_dec (same_height_block_msg b) (out_messages s) (same_height_block_msg_dec b) with\n| left H_dec => left _\n| right H_dec => right _\nend.\nNext Obligation.\nclear Heq_anonymous.\napply Exists_exists in H_dec.\ndestruct H_dec.\ndestruct H.\ndestruct H0.\ndestruct H1.\nexists x.\nsplit; [assumption|].\nsplit; [assumption|].\nsplit; [assumption|].\nassumption.\nDefined.\nNext Obligation.\nclear Heq_anonymous.\nintro.\ncontradict H_dec.\napply Exists_exists.\ndestruct H.\ndestruct H.\ndestruct H0.\ndestruct H1.\nexists x.\nsplit; [assumption|].\nsplit; [assumption|].\nsplit; [assumption|].\nassumption.\nDefined.\n\nDefinition exists_same_height_blockb : NState -> block -> bool :=\n fun s b => if exists_same_height_block_dec s b then true else false.\n\nLemma exists_same_height_block_correct : forall (s : NState) (b : block),\n exists_same_height_block s b <-> exists_same_height_blockb s b = true.\nProof.\nintros; split; unfold exists_same_height_blockb;\n  destruct (exists_same_height_block_dec _ _); congruence.\nQed.\n\n(** *** Prepare stage definitions *)\n\n(** Blocks in Giskard go through three stages: Prepare, Precommit and Commit.\nThe local definitions of these three stages are: \n- a block is in prepare stage in some local state s iff it has received quorum PrepareVote messages\n  or a PrepareQC message in the current view or some previous view, and\n- a block is in precommit stage in some local state s iff its child block is in prepare stage in s, and\n- a block is in commit stage in some local state s iff its child block is in precommit stage in s. *)\n\n(** We can parameterize the definition of a block being in prepare stage by some view. *)\n\n(** Processed PrepareVote messages in some view about some block: *) \nDefinition processed_PrepareVote_in_view_about_block (s : NState) (view : nat) (b : block) : list message :=\n  filter (fun msg => message_type_eqb (get_message_type msg) PrepareVote &&\n                  block_eqb (get_block msg) b &&\n                  Nat.eqb (get_view msg) view)\n         (counting_messages s).\n\nDefinition vote_quorum_in_view (s : NState) (view : nat) (b : block) : Prop :=\n  quorum (processed_PrepareVote_in_view_about_block s view b).\n\nDefinition PrepareQC_in_view (s : NState) (view : nat) (b : block) : Prop :=\n  exists msg : message,\n    In msg (counting_messages s) /\\ \n    get_view msg = view /\\\n    get_block msg = b /\\\n    get_message_type msg = PrepareQC.\n\nDefinition prepare_stage_in_view (s : NState) (view : nat) (b : block) : Prop :=\n  vote_quorum_in_view s view b\n  \\/\n  PrepareQC_in_view s view b. \n\nDefinition prepare_stage_in_viewb  (s : NState) (view : nat) (b : block) : bool :=\n  quorumb (processed_PrepareVote_in_view_about_block s view b) \n  ||\n  existsb (fun msg => message_type_eqb (get_message_type msg) PrepareQC\n                                    && Nat.eqb (get_view msg) view\n                                    && block_eqb (get_block msg) b)\n  (counting_messages s).\n\n(** We use this parameterized definition to define the general version of a block being\nin prepare stage: A block has reached prepare stage in some state iff it has reached prepare\nstage in some view that is less than or equal to the current view. *)\nDefinition prepare_stage (s : NState) (b : block) :=\n  exists v', v' <= node_view s /\\ prepare_stage_in_view s v' b.\n\n(** *** View change definitions *)\n\n(** Participating nodes in Giskard vote in units of time called views. Each view has the same\nfixed set of participating nodes, which consists oof one block proposer for the view, and\nvalidators. Participating nodes take turns to be the block proposer, and the identity of\nthe block proposer for any given view is known to all participating nodes. A view generally\nproceeds as follows: at the beginning of the view, the block proposer proposes a fixed\nnumber of blocks, which validators vote on. If all blocks receive quorum votes, the nodes\nincrement their local view and wait for new block proposals in the new view. Otherwise,\na timeout occurs, and nodes exchange messages to communicate their acknowledgement of the\ntimeout and determine the parent block for the first block of the new view. The end of a\nview for a participating node is marked by either: \n- the last block proposed by the block proposer reaching prepare stage in its local state, or \n- the receipt of a ViewChangeQC message following a timeout.\n\nWe call the former a normal view change, and the latter an abnormal view change.\nBecause we assume that all local clocks are synchronized, in the case of an abnormal\nview change, all nodes timeout at once. However, because nodes process messages at\ndifferent speeds, blocks reach prepare stage at different speeds, and consequently,\nin the case of a normal view change, nodes are not guaranteed to increment their\nlocal view at the same time. *)\n\n(** In the case of an abnormal view change, the timeout flag is simultaneously flipped\nfor all participating nodes, and each sends a ViewChange message containing their\nlocal highest block at prepare stage. Nodes then enter a liminal stage in which only\nthree kinds of messages can be processed: PrepareQC, ViewChange and ViewChangeQC. *)\n\n(** Nodes will ignore all block proposals and block votes during this stage. Upon\nreceiving quorum ViewChange messages, validator nodes increment their view and wait\nfor new blocks to be proposed. The new block proposer aggregates the max height\nblock from its received ViewChange messages, and uses it to produce new blocks\nfor the new view. *)\n\n(** The following section contains definitions required for abnormal view changes. *)\n\n(** Quorum ViewChange messages in some view: *)\nDefinition processed_ViewChange_in_view (s : NState) (view : nat) : list message :=\n  filter (fun msg => message_type_eqb ViewChange (get_message_type msg) &&\n                  Nat.eqb (get_view msg) view)\n         (counting_messages s).\n\nLemma processed_ViewChange_in_view_correct :\n  forall s view msg,\n    In msg (processed_ViewChange_in_view s view) ->\n    In msg (counting_messages s) /\\ \n    get_message_type msg = ViewChange /\\\n    get_view msg = view.\nProof. \n  intros s view msg H_in.\n  apply filter_In in H_in.\n  destruct H_in as [H_in H_typeview].\n  apply andb_prop in H_typeview.\n  destruct H_typeview as [H_type H_view].\n  repeat split; try tauto. symmetry; now apply message_type_eqb_correct.\n  apply Nat.eqb_eq. assumption.\nQed.\n\nDefinition view_change_quorum_in_view (s : NState) (view : nat) : Prop :=\n  quorum (processed_ViewChange_in_view s view).\n\n(** Maximum height block from all processed ViewChange messages in view: *) \nDefinition highest_ViewChange_block_in_view (s : NState) (view : nat) : block :=\n  fold_right higher_block\n             GenesisBlock\n             (map (get_block) (processed_ViewChange_in_view s view)).\n\nDefinition highest_ViewChange_block_height_in_view (s : NState) (view : nat) : nat :=\n  b_height (highest_ViewChange_block_in_view s view). \n\n(** The last block of each view is identifiable to each participating node:  *) \nDefinition last_block (b : block) : Prop :=\n  b_last b = true.\n\n(** Because not every view is guaranteed to have a block in prepare stage,\nthe definition of <<highest_prepare_block_in_view>> must be able to recursively\nsearch for the highest prepare block in all past views: *)\nFixpoint highest_prepare_block_in_view (s : NState) (view : nat) : block :=\n  match view with\n    | 0 => GenesisBlock\n    | S view' =>\n      fold_right higher_block\n       (highest_prepare_block_in_view s view')\n       (map get_block\n         (filter (fun msg => prepare_stage_in_viewb s view (get_block msg))\n          (counting_messages s)))\n    end.\n\n(** The following definition constructs the ViewChange message to be\nsent by each participating node upon a timeout. *)\nDefinition highest_prepare_block_message (s : NState) : message :=\n mkMessage PrepareQC (node_view s) (node_id s)\n  (highest_prepare_block_in_view s (node_view s)) GenesisBlock.\n\n\n(** ** Message construction *)\n\n(** In Giskard, some message types \"carry\" other messages: \n- PrepareBlock messages for the first block in a view carry the PrepareQC\n  message of its parent block, PrepareBlock messages for non-first blocks\n  carry the PrepareQC of the parent block of the first block, and\n- PrepareVote messages carry the PrepareQC message of its parent block, and\n- ViewChange messages carry the PrepareQC message of the highest local\n  prepare stage block. *)\n\n(** We do not model this at the type level (i.e., by having inductive message\ntype definitions), but rather simulate this behavior using pre- and post-conditions\nin our local transitions. For example, a node only processes a PrepareBlock message\nin the in message buffer if the PrepareQC message that is \"piggybacked\" onto has also\nbeen received, and the transition effectively processes both of these messages in one step. *)\n\n(** PrepareBlocks are computed from either: \n- the final PrepareVote/PrepareQC message of the previous round, or \n- the ViewChangeQC from the previous round. \n\nThe messages in both of these cases contain the parent block for the newly proposed blocks.\nNote that because blocks are proposed in sequence, only the first PrepareBlock message carries\nthe parent block's PrepareQC message - the remaining blocks cannot do so because their parent\nblocks have not reached prepare stage yet, and therefore their PrepareQC messages cannot exist.\nTherefore, all PrepareBlock messages in a view carry the same PrepareQC message: that of\nthe first block's parent. *)\n\n(** Note that although all PrepareBlock messages are produced and sent together in one\nsingle transition, this does not mean that:\n- they are processed at the same time, and\n- we falsely enforce the discipline that the second proposed block contains the first\n  block's PrepareQC when in fact it has not reached PrepareQC. *)\n\nDefinition make_PrepareBlocks (s : NState) (previous_msg : message) : list message :=\n  [(mkMessage PrepareBlock \n    (node_view s)\n    (node_id s) \n    (generate_new_block (get_block previous_msg)) (* New block produced *) \n    (get_block previous_msg) (* PrepareQC of highest block from previous round *)\n   )\n   ;\n   (mkMessage PrepareBlock\n    (node_view s)\n    (node_id s)\n    (generate_new_block\n      (generate_new_block (get_block previous_msg))) (* New block produced *) \n    (get_block previous_msg) (* PrepareQC of highest block from previous round *)\n   )\n   ;\n   (mkMessage PrepareBlock \n    (node_view s)\n    (node_id s)\n    (* In particular, here we produce a block that is labeled as last block for the view *)\n    (generate_last_block\n      (generate_new_block\n         (generate_new_block (get_block previous_msg)))) (* New block produced *) \n    (get_block previous_msg)\n   )]. (* PrepareQC of highest block from previous round *)\n\nLemma make_PrepareBlocks_message_type :\n  forall s msg0 msg, \n  In msg (make_PrepareBlocks s msg0) ->\n  get_message_type msg = PrepareBlock. \nProof.         \n  intros. unfold make_PrepareBlocks in H.\n  simpl in H;\n    destruct H as [H | [H | [H | H]]];\n    subst; try easy.\nQed.\n\n(** A <<PrepareVote>> carries the <<PrepareQC>> of its parent, and can only be sent\nafter parent block reaches prepare stage, which means one of its inputs must be\neither a <<PrepareVote>> or <<PrepareQC>>. *)\n\n(** <<PrepareVote>>s are also computed from <<PrepareBlock>> messages,\nwhich means another one of its inputs must be a <<PrepareBlock>> message. *)\nDefinition make_PrepareVote (s : NState) (quorum_msg prepareblock_msg : message) : message :=\n  mkMessage PrepareVote (* message type *)\n  (node_view s) (* view number *)\n  (node_id s) (* node id *) \n  (get_block prepareblock_msg) (* block to vote for *) \n  (get_block quorum_msg).\n\n(** Nodes create <<PrepareVote>> messages upon receiving <<PrepareBlock>> messages\nfor each block, and \"wait\" to send it until the parent block reaches prepare stage.\nThis is modeled by constructing <<PrepareVote>> messages on-demand given that:\n- the parent block has just reached prepare stage, and\n- a <<PrepareBlock>> message exists for the child block.\n*)\n\n(** Constructing pending PrepareVote messages for child messages with existing PrepareBlocks. *)\nDefinition pending_PrepareVote (s : NState) (quorum_msg : message) : list message :=\n  map (fun prepare_block_msg => make_PrepareVote s quorum_msg prepare_block_msg)\n      (filter (fun msg => Nat.eqb (get_view msg) (get_view quorum_msg) &&\n                       negb (exists_same_height_blockb s (get_block msg)) &&\n                       parent_ofb (get_block msg) (get_block quorum_msg) &&\n                       message_type_eqb (get_message_type msg) PrepareBlock)\n              (counting_messages s)). \n\nLemma pending_PrepareVote_correct :\n  forall s msg0 msg,\n    In msg (pending_PrepareVote s msg0) ->\n    get_message_type msg = PrepareVote /\\\n    get_sender msg = node_id s /\\\n    get_view msg = node_view s.\nProof.  \n  intros. \n  unfold pending_PrepareVote in H.\n  rewrite in_map_iff in H.\n  destruct H as [msg' [H_type' H]].\n  apply filter_In in H.\n  destruct H. \n  repeat (apply andb_prop in H0;\n          destruct H0). \n  rewrite Nat.eqb_eq in *.\n  rewrite message_type_eqb_correct in H1.\n  rewrite <- H_type'. unfold make_PrepareVote; repeat split; simpl; try tauto.\nQed.\n\n(** PrepareQC messages carry nothing, and can only be sent after a quorum number of PrepareVotes,\nwhich means its only input is a PrepareVote containing the relevant block. *)\nDefinition make_PrepareQC (s : NState) (msg : message) : message :=\n  mkMessage PrepareQC \n  (node_view s)\n  (node_id s)\n  (get_block msg)\n  GenesisBlock. \n\n(** ViewChange messages carry the <<PrepareQC>> message of the highest block to\nreach prepare stage, and since they are triggered by timeouts, no input\nmessage is required: *)\nDefinition make_ViewChange (s : NState) : message :=\n  mkMessage ViewChange\n  (node_view s)\n  (node_id s)\n  (highest_prepare_block_in_view s (node_view s))\n  GenesisBlock.\n\n(** Upon receiving quorum <<ViewChange>> messages, the block proposer for the new\nview aggregates the max height block from all the <<ViewChange>> messages and\nsends a <<ViewChangeQC>> containing this block, alongside a <<PrepareQC>> message\nevidencing its prepare stage. *)  \nDefinition make_ViewChangeQC (s : NState) (highest_msg : message) : message :=\n  mkMessage ViewChangeQC\n  (node_view s)\n  (node_id s) \n  (get_block highest_msg)\n  GenesisBlock.\n\n(** ** Local state transitions *)\n\n(** Nodes are responsible for processing messages and updating their local state;\nbroadcasting outgoing messages is handled by the network. *)\n\n(** In the following section, Giskard local state transitions are organized\naccording to the type of message being processed. *)\n\n(** *** Message type-agnostic actions *) \n\n(** Block proposal-related definitions: *)\nDefinition GenesisBlock_message (s : NState) : message :=\n  mkMessage ViewChangeQC\n  0\n  (node_id s)\n  GenesisBlock\n  GenesisBlock.    \n\nDefinition propose_block_init (s : NState) (msg : message) (s' : NState) (lm : list message) : Prop :=\n  s' = record_plural s (make_PrepareBlocks s (GenesisBlock_message s)) /\\\n  lm = (make_PrepareBlocks s (GenesisBlock_message s)) /\\ \n  s = NState_init (node_id s) /\\\n  honest_node (node_id s) /\\ \n  is_block_proposer (node_id s) 0 /\\\n  timeout s = false.\n\n(** When the timeout happens, nodes enter a liminal phase where they are only allowed\nto process the following kinds of messages: \n- ViewChange from other nodes\n- ViewChangeQC \n- PrepareQC *)\n\n(** Upon timeout, nodes send a ViewChange message containing the highest block to reach\nPrepare stage in its current view, and the PrepareQC message attesting to that block's Prepare stage. *)\n(* It does not increment the view yet *) \nDefinition process_timeout (s : NState) (msg : message) (s' : NState) (lm : list message) :=\n  s' = record_plural s [make_ViewChange s; highest_prepare_block_message s] /\\\n  lm = [make_ViewChange s; highest_prepare_block_message s] /\\\n  honest_node (node_id s) /\\ \n  timeout s = true.   \n\n(** An expired message - discard and do not process. *)\nDefinition discard_view_invalid (s : NState) (msg : message) (s' : NState) (lm : list message) : Prop :=\n  s' = discard s msg /\\\n  lm = [] /\\\n  received s msg /\\ \n  honest_node (node_id s) /\\ \n  ~ view_valid s msg.\n(* At this point it doesn't matter whether timeout has occurred or not *)\n\n(** *** PrepareBlock message-related actions *)\n\n(** If a same height block has been seen - discard the message: *)\nDefinition process_PrepareBlock_duplicate (s : NState) (msg : message) (s' : NState) (lm : list message) : Prop :=\n  s' = discard s msg /\\\n  lm = [] /\\\n  received s msg /\\ \n  honest_node (node_id s) /\\ \n  get_message_type msg = PrepareBlock /\\ \n  view_valid s msg /\\\n  timeout s = false /\\ \n  exists_same_height_PrepareBlock s (get_block msg).\n\n(** Parent block has not reached Prepare - \"add its PrepareVote to pending buffer\" by simply\nprocessing the PrepareBlock message and waiting for parent block to reach quorum: *)\nDefinition process_PrepareBlock_pending_vote (s : NState) (msg : message) (s' : NState) (lm : list message) : Prop :=\n  s' = process s msg /\\\n  lm = [] /\\\n  received s msg /\\\n  honest_node (node_id s) /\\ \n  get_message_type msg = PrepareBlock /\\ \n  view_valid s msg /\\\n  (* PrepareBlocks cannot be processed during timeout *) \n  timeout s = false /\\ \n  ~ exists_same_height_PrepareBlock s (get_block msg) /\\\n  (* Parent block has not reached Prepare *)\n  ~ prepare_stage s (parent_of (get_block msg)). \n\n(** Parent block has reached QC - send PrepareVote for the block in that message and record in out buffer: *) \nDefinition process_PrepareBlock_vote (s : NState) (msg : message) (s' : NState) (lm : list message) : Prop :=\n  s' = (* Record outgoing PrepareVote messages *)\n       record_plural\n         (process s msg)\n         (pending_PrepareVote s msg) /\\\n  lm = (pending_PrepareVote s msg) /\\\n  received s msg /\\\n  honest_node (node_id s) /\\ \n  get_message_type msg = PrepareBlock /\\ \n  view_valid s msg /\\\n  (* PrepareBlocks cannot be processed during timeout *) \n  timeout s = false /\\ \n  prepare_stage s (parent_of (get_block msg)). \n\n(** *** PrepareVote message-related actions *)\n\n(** Block has not reached prepare stage - wait to send PrepareVote messages for child: *) \nDefinition process_PrepareVote_wait (s : NState) (msg : message) (s' : NState) (lm : list message) : Prop :=\n  s' = process s msg /\\\n  lm = [] /\\\n  received s msg /\\\n  honest_node (node_id s) /\\ \n  get_message_type msg = PrepareVote /\\ \n  view_valid s msg /\\\n  (* PrepareVotes cannot be processed during timeout *) \n  timeout s = false /\\ \n  ~ prepare_stage (process s msg) (get_block msg). \n\n(** Block is about to reach QC - send PrepareVote messages for child block if it exists and send PrepareQC: *)\n(* vote_quorum means quorum PrepareVote messages *)\nDefinition process_PrepareVote_vote (s : NState) (msg : message) (s' : NState) (lm : list message) : Prop :=\n  s' = process\n         (record_plural\n            s\n            ((make_PrepareQC s msg) :: pending_PrepareVote s msg))\n         msg /\\\n  lm = (make_PrepareQC s msg) :: pending_PrepareVote s msg /\\\n  honest_node (node_id s) /\\ \n  received s msg /\\\n  get_message_type msg = PrepareVote /\\\n  view_valid s msg /\\\n  (* PrepareVotes cannot be processed during timeout *) \n  timeout s = false /\\\n  ~ exists_same_height_block s (get_block msg) /\\\n  vote_quorum_in_view (process s msg) (get_view msg) (get_block msg). \n\n(** *** PrepareQC message-related actions *)\n\n(** PrepareQC messages are considered equivalent to a quorum of PrepareVote messages. \nPrepareQC messages can be processed after timeout, so we do not require that timeout\nhas not occurred. *)\n\n(** The PrepareQC message suffices to directly quorum a block, even if it has not received\nenough PrepareVote messages, *)\n\n(** Last block in view for to-be block proposer undergoing normal view change process:\n- increment view, and\n- propose block at height <<(S n)>>. *)\n\nDefinition process_PrepareQC_last_block_new_proposer (s : NState) (msg : message) (s' : NState) (lm : list message) : Prop :=\n  (* Increment the view; propose next block *) \n  s' = record_plural\n         (* New state *)\n         (increment_view (process s msg))\n         (* All to-propose blocks *)\n         (* The block generating function starts at the input block height plus one *)\n         (make_PrepareBlocks (increment_view (process s msg)) msg) /\\ \n  lm = (* Send all block proposals for the new view *)\n  make_PrepareBlocks (increment_view (process s msg)) msg /\\ \n  received s msg /\\ \n  honest_node (node_id s) /\\ \n  get_message_type msg = PrepareQC /\\ \n  view_valid s msg /\\\n  (* Here we don't need for timeout to be false because apparently we can still\n    process PrepareQC messages in the timeout period *)\n  last_block (get_block msg) /\\\n  is_block_proposer (node_id s) (S (node_view s)).\n\n(** Last block in the view for to-be validator - increment view: *) \n(* No child blocks can exist, so we don't need to send anything *) \nDefinition process_PrepareQC_last_block (s : NState) (msg : message) (s' : NState) (lm : list message) : Prop :=\n  s' = increment_view (process s msg) /\\ \n  lm = [] /\\\n  received s msg /\\ \n  honest_node (node_id s) /\\ \n  get_message_type msg = PrepareQC /\\ \n  view_valid s msg /\\\n  (* Here we don't need for timeout to be false because apparently\n     we can still process PrepareQC messages in the timeout period *)\n  last_block (get_block msg) /\\\n  ~ is_block_proposer (node_id s) (S (node_view s)).\n\n(** Not-the-last block in the view - send PrepareVote messages for child block and wait: *)\nDefinition process_PrepareQC_non_last_block (s : NState) (msg : message) (s' : NState) (lm : list message) : Prop :=\n  s' = process (record_plural s (pending_PrepareVote s msg)) msg /\\\n  lm = pending_PrepareVote s msg /\\\n  received s msg /\\ \n  honest_node (node_id s) /\\ \n  get_message_type msg = PrepareQC /\\ \n  view_valid s msg /\\\n  timeout s = false /\\ \n  ~ last_block (get_block msg).\n\n(** *** ViewChange message-related actions *)\n\n(** ViewChange messages can be processed after timeout, so we do not require that timeout has not occurred. *) \n\n(** Process ViewChange at quorum for to-be block proposer:\n- send highest PrepareQC message,\n- send ViewChangeQC message,\n- increment view, and\n- propose new block according to highest block in all quorum ViewChange messages. *)\nDefinition higher_message (msg1 msg2 : message) : message :=\n  if (block_eqb (get_block msg1) (higher_block (get_block msg1) (get_block msg2)))\n  then msg1\n  else msg2.\n\nDefinition highest_message_in_list (n : node) (t : message_type) (lm : list message) : message := \n  fold_right higher_message\n             (mkMessage t\n                        0\n                        n\n                        GenesisBlock\n                        GenesisBlock)\n             lm.\n\nLemma about_highest_message_in_list :\n  forall n t lm msg,\n    In msg lm ->\n    b_height (get_block msg) <= b_height (get_block (highest_message_in_list n t lm)).\nProof.\ninduction lm; intros; [inversion H|].\ndestruct H.\n- simpl.\n  subst.\n  unfold higher_message.\n  case_eq (block_eqb (get_block msg) (higher_block (get_block msg) (get_block (highest_message_in_list n t lm)))); intros.\n  * auto with arith.\n  * unfold higher_block in H.\n    revert H.\n    case_eq (b_height (get_block msg) <? b_height (get_block (highest_message_in_list n t lm))).\n    + intros Hlt Heq.\n      apply Nat.ltb_lt in Hlt.\n      auto with arith.\n    + intros Hle.\n      case (block_eq_dec (get_block msg) (get_block msg)); [|congruence].\n      intro Heq.\n      apply block_eqb_correct in Heq.\n      congruence.\n- simpl.\n  unfold higher_message.\n  case_eq (block_eqb (get_block msg) (higher_block (get_block msg) (get_block (highest_message_in_list n t lm)))); intros.\n  * apply block_eqb_correct in H0.\n    case_eq (block_eqb (get_block a) (higher_block (get_block a) (get_block (highest_message_in_list n t lm)))); intros.\n    + apply block_eqb_correct in H1.\n      apply IHlm in H.\n      assert (b_height (get_block (highest_message_in_list n t lm)) <= b_height (get_block a)).\n      -- rewrite H1.\n         unfold higher_block.\n         case_eq (b_height (get_block a) <? b_height (get_block (highest_message_in_list n t lm))); [lia|].\n         intro Hlt.\n         apply Nat.ltb_ge in Hlt.\n         lia.\n      -- lia.\n    + apply IHlm.\n      assumption.\n  * case_eq (block_eqb (get_block a) (higher_block (get_block a) (get_block (highest_message_in_list n t lm)))); intros.\n    + apply block_eqb_correct in H1.\n      apply IHlm in H.\n      assert (b_height (get_block (highest_message_in_list n t lm)) <= b_height (get_block a)).\n      -- rewrite H1.\n         unfold higher_block.\n         case_eq ((b_height (get_block a) <? b_height (get_block (highest_message_in_list n t lm)))); [lia|].\n         intro Hlt.\n         apply Nat.ltb_ge in Hlt.\n         lia.\n      -- lia.\n    + apply IHlm.\n      assumption.\nQed.\n\nDefinition highest_ViewChange_message (s : NState) : message :=\n  highest_message_in_list (node_id s) ViewChange (processed_ViewChange_in_view s (node_view s)).\n\nLemma highest_ViewChange_message_type_eq_ViewChange :\n  forall s, get_message_type (highest_ViewChange_message s) = ViewChange.\nProof.\nintro s.\nunfold highest_ViewChange_message.\nassert (forall msg, In msg (processed_ViewChange_in_view s (node_view s)) -> get_message_type msg = ViewChange).\n  intros.\n  apply processed_ViewChange_in_view_correct in H.\n  destruct H.\n  destruct H0.\n  assumption.\nrevert H.\ngeneralize (processed_ViewChange_in_view s (node_view s)).\ngeneralize (node_id s).\ninduction l; [reflexivity|].\nsimpl.\nintro Ht.\nunfold higher_message.\ndestruct (block_eqb (get_block a) (higher_block (get_block a) (get_block (highest_message_in_list n ViewChange l)))).\n- apply Ht; left; reflexivity.\n- apply IHl.\n  intros.\n  apply Ht; right; assumption.\nQed.\n\nLemma get_view_highest_ViewChange_message_node_view :\n  forall s msg, get_message_type msg = ViewChange ->\n   get_view msg = node_view s ->\n   In msg (counting_messages s) ->\n   get_view (highest_ViewChange_message s) = node_view s.\nProof.\nintros.\nunfold highest_ViewChange_message.\nassert (forall msg, In msg (processed_ViewChange_in_view s (node_view s)) -> get_view msg = (node_view s)).\n  intros.\n  apply processed_ViewChange_in_view_correct in H2.\n  destruct H2.\n  destruct H3.\n  assumption.\nassert (processed_ViewChange_in_view s (node_view s) <> []).\n  clear H2.\n  unfold processed_ViewChange_in_view.\n  apply In_split in H1.\n  destruct H1.\n  destruct H1.\n  rewrite H1.\n  clear H1.\n  induction x.\n    simpl.\n    rewrite H0.\n    apply eq_sym in H.\n    apply message_type_eqb_correct in H.\n    rewrite H.\n    rewrite Nat.eqb_refl.\n    simpl.\n    auto with datatypes.\n  simpl.\n  case (message_type_eqb ViewChange (get_message_type a) && (get_view a =? node_view s)); auto with datatypes.\nclear H1 H0 H.\nrevert H2 H3.\ngeneralize (processed_ViewChange_in_view s (node_view s)).\ngeneralize (node_id s).\ninduction l; [congruence|].\nsimpl.\nintros.\nclear H3.\nunfold higher_message.\ncase_eq (block_eqb (get_block a) (higher_block (get_block a) (get_block (highest_message_in_list n ViewChange l)))).\n  intro.\n  apply H2.\n  left.\n  reflexivity.\nunfold higher_block.\ndestruct l.\n- simpl.\n  case_eq (b_height (get_block a) <? b_height GenesisBlock).\n  * rewrite Nat.ltb_lt.\n    intro Hlt.\n    contradict Hlt.\n    apply Nat.ltb_nlt.\n    apply Nat.ltb_ge.\n    apply GenesisBlock_height.\n  * intros.\n    case (block_eq_dec (get_block a) (get_block a)); [|congruence].\n    intros; apply block_eqb_correct in e; congruence.\n- simpl in *.\n  intros.\n  apply IHl; auto with datatypes.\nQed.\n\nLemma get_view_highest_ViewChange_message_in_counting_messages :\n  forall s msg, get_message_type msg = ViewChange ->\n   get_view msg = node_view s ->\n   In msg (counting_messages s) ->\n   In (highest_ViewChange_message s) (counting_messages s).\nProof.\nintros.\nunfold highest_ViewChange_message.\nassert (forall msg, In msg (processed_ViewChange_in_view s (node_view s)) -> In msg (counting_messages s)).\n  intros.\n  apply processed_ViewChange_in_view_correct in H2.\n  destruct H2.\n  destruct H3.\n  assumption.\nassert (processed_ViewChange_in_view s (node_view s) <> []).\n  clear H2.\n  unfold processed_ViewChange_in_view.\n  apply In_split in H1.\n  destruct H1.\n  destruct H1.\n  rewrite H1.\n  clear H1.\n  induction x.\n    simpl.\n    rewrite H0.\n    apply eq_sym in H.\n    apply message_type_eqb_correct in H.\n    rewrite H.\n    rewrite Nat.eqb_refl.\n    simpl.\n    auto with datatypes.\n  simpl.\n  case (message_type_eqb ViewChange (get_message_type a) && (get_view a =? node_view s)); auto with datatypes.\nclear H H0 H1.\nrevert H2 H3.\ngeneralize (processed_ViewChange_in_view s (node_view s)).\ngeneralize (node_id s).\ninduction l; [congruence|].\nsimpl.\nintros.\nclear H3.\nunfold higher_message.\ncase_eq (block_eqb (get_block a) (higher_block (get_block a) (get_block (highest_message_in_list n ViewChange l)))).\n  intro.\n  apply H2.\n  left.\n  reflexivity.\nunfold higher_block.\ndestruct l.\n- simpl.\n  case_eq (b_height (get_block a) <? b_height GenesisBlock).\n  * rewrite Nat.ltb_lt.\n    intro Hlt.\n    contradict Hlt.\n    apply Nat.ltb_nlt.\n    apply Nat.ltb_ge.\n    apply GenesisBlock_height.\n  * intros.\n    case (block_eq_dec (get_block a) (get_block a)); [|congruence].\n    intros; apply block_eqb_correct in e; congruence.\n- simpl in *.\n  intros.\n  apply IHl; auto with datatypes.\nQed.\n\nDefinition process_ViewChange_quorum_new_proposer\n (s : NState) (msg : message) (s' : NState) (lm : list message) : Prop :=\n  s' = (* Record new blocks after incrementing view *)\n  record_plural (increment_view (process (process s msg)\n   (mkMessage PrepareQC (get_view msg) (get_sender msg)\n    (get_block (highest_ViewChange_message (process s msg))) GenesisBlock)))\n    (* The input has to include the current ViewChange message, just in\n       case that is the one which contains the highest block *)\n      ((* PrepareQC of highest block *)\n        (mkMessage PrepareQC (node_view s) (node_id s)\n          (get_block (highest_ViewChange_message (process s msg))) GenesisBlock) :: \n       (* ViewChangeQC containing highest block *)\n       (make_ViewChangeQC s (highest_ViewChange_message (process s msg))) ::\n       (* New block proposals *)\n       (make_PrepareBlocks (increment_view s) (highest_ViewChange_message (process s msg)))) /\\\n  lm = (* Send ViewChangeQC message before incrementing view to ensure the others can process it *)\n  (mkMessage PrepareQC (node_view s) (node_id s)\n    (get_block (highest_ViewChange_message (process s msg))) GenesisBlock) ::\n  (make_ViewChangeQC s (highest_ViewChange_message (process s msg))) ::\n  (* Send PrepareBlock messages *) \n  (make_PrepareBlocks (increment_view s) (highest_ViewChange_message (process s msg))) /\\\n  received s msg /\\\n  (* This condition is necessary given ViewChange sending behavior *) \n  received s (mkMessage PrepareQC (get_view msg) (get_sender msg)\n   (get_block (highest_ViewChange_message (process s msg))) GenesisBlock) /\\ \n  honest_node (node_id s) /\\ \n  get_message_type msg = ViewChange /\\\n  view_valid s msg /\\\n  (* ViewChange messages can be processed during timeout *)\n  (* It is important that the parameter here is (process s msg) and not simply s *)\n  view_change_quorum_in_view (process s msg) (node_view s) /\\\n  is_block_proposer (node_id s) (S (node_view s)).\n\n(** Process ViewChange before quorum - keep and wait for QC: *)\nDefinition process_ViewChange_pre_quorum (s : NState) (msg : message) (s' : NState) (lm : list message) : Prop :=\n  s' = process s msg /\\\n  lm = [] /\\\n  received s msg /\\ \n  honest_node (node_id s) /\\ \n  get_message_type msg = ViewChange /\\ \n  view_valid s msg /\\\n  ~ view_change_quorum_in_view (process s msg) (node_view s).\n\n\n(** *** ViewChangeQC message-related actions *)\n\n(** Process highest PrepareQC message, process ViewChangeQC, then increment view. *)\n\n(** Critically, this is where we enforce that the PrepareQC of the max height block\nis processed before view change occurs, otherwise nodes can get stuck during view change. *)\nDefinition process_ViewChangeQC_single (s : NState) (msg : message) (s' : NState) (lm : list message) : Prop :=\n  s' = increment_view (process (process s\n    (mkMessage PrepareQC (node_view s) (get_sender msg) (get_block msg) GenesisBlock)) msg) /\\\n  lm = [] /\\\n  received s msg /\\\n  received s (mkMessage PrepareQC (node_view s) (get_sender msg) (get_block msg) GenesisBlock) /\\\n  honest_node (node_id s) /\\ \n  get_message_type msg = ViewChangeQC /\\ \n  view_valid s msg.\n\n(** *** Timeout **)\n\n(** When timeout is triggered, send ViewChange with the highest prepare stage block.\nGiven the new definition of prepare stage, this block might not be from the current view at all. *) \n\nDefinition flip_timeout (s : NState) : NState :=\n  mkNState (node_view s) (node_id s) (in_messages s) (counting_messages s) (out_messages s)  true.\n\n(** *** Malicious node actions *)\n\n(** Malicious nodes can ignore messages: *)\nDefinition malicious_ignore (s : NState) (msg : message) (s' : NState) (lm : list message) : Prop :=\n  s' = discard s msg /\\\n  lm = [] /\\\n  received s msg /\\\n  ~ honest_node (node_id s).\n\n(** Malicious nodes can double vote for two blocks of the same height: *)\nDefinition process_PrepareBlock_malicious_vote (s : NState) (msg : message) (s' : NState) (lm : list message) : Prop :=\n  s' = record_plural (process s msg) (pending_PrepareVote s msg) /\\\n  lm = pending_PrepareVote s msg /\\\n  received s msg /\\\n  ~ honest_node (node_id s) /\\ \n  get_message_type msg = PrepareBlock /\\ \n  view_valid s msg /\\\n  exists_same_height_block s (get_block msg).\n\n(** ** Protocol transition type definitions *)\n\n(** Valid Giskard transitions can be defined as a finite set/type of relations on pre-state,\npost-state, processed message and outgoing message(s), constrained by protocol rules. *)\nInductive NState_transition_type :=\n| propose_block_init_type\n| discard_view_invalid_type \n| process_PrepareBlock_duplicate_type\n| process_PrepareBlock_pending_vote_type \n| process_PrepareBlock_vote_type\n| process_PrepareVote_vote_type\n| process_PrepareVote_wait_type\n| process_PrepareQC_last_block_new_proposer_type\n| process_PrepareQC_last_block_type\n| process_PrepareQC_non_last_block_type\n| process_ViewChange_quorum_new_proposer_type\n| process_ViewChange_pre_quorum_type\n| process_ViewChangeQC_single_type\n| process_PrepareBlock_malicious_vote_type.\n\nDefinition get_transition (t : NState_transition_type) : (NState -> message -> NState -> list message -> Prop) :=\n  match t with\n  | propose_block_init_type => propose_block_init\n  | discard_view_invalid_type => discard_view_invalid\n  | process_PrepareBlock_duplicate_type => process_PrepareBlock_duplicate\n  | process_PrepareBlock_pending_vote_type => process_PrepareBlock_pending_vote\n  | process_PrepareBlock_vote_type => process_PrepareBlock_pending_vote\n  | process_PrepareQC_last_block_new_proposer_type => process_PrepareQC_last_block_new_proposer\n  | process_PrepareQC_last_block_type => process_PrepareQC_last_block\n  | process_PrepareQC_non_last_block_type => process_PrepareQC_non_last_block\n  | process_PrepareVote_vote_type => process_PrepareVote_vote\n  | process_PrepareVote_wait_type => process_PrepareVote_wait\n  | process_ViewChange_quorum_new_proposer_type => process_ViewChange_quorum_new_proposer\n  | process_ViewChange_pre_quorum_type => process_ViewChange_pre_quorum\n  | process_ViewChangeQC_single_type => process_ViewChangeQC_single\n  | process_PrepareBlock_malicious_vote_type => process_PrepareBlock_malicious_vote\n  end.\n\n(** ** Facts about local state transitions *)\n\nLemma out_messages_local_monotonic :\n  forall (s1 s2 : NState) (msg : message) (lm : list message) (t : NState_transition_type),\n    (get_transition t) s1 msg s2 lm ->\n    forall (msg0 : message),\n      In msg0 (out_messages s1) ->\n      In msg0 (out_messages s2). \nProof.     \n  intros s1 s2 msg lm t H_step msg0 H_in.\n  assert (H_step_copy := H_step). \n  destruct t; simpl in H_step;\n    destruct H_step as [H_subst _];\n    try (subst; assumption);\n    try (rewrite H_subst; simpl; rewrite in_app_iff; repeat right; assumption); \n    try (rewrite H_subst in *; simpl; right;\n         assert (H : In msg0 (pending_messages_about_block s1 (get_block msg)) \\/ In msg0 (out_messages s1)) by tauto;\n          apply in_app_iff in H; assumption);\n    try (destruct H_step_copy as [_ [_ [_ [H_init _]]]]; \n         rewrite H_init in H_in; inversion H_in);\n    try (rewrite H_subst; simpl; try rewrite in_app_iff; repeat right; \n         assumption).\nQed. \n\nLemma counting_messages_same_view_monotonic :\n  forall (s1 s2 : NState) (msg : message) (lm : list message) (t : NState_transition_type),\n    (get_transition t) s1 msg s2 lm ->\n    node_view s1 = node_view s2 -> \n    forall (msg0 : message),\n      In msg0 (counting_messages s1) ->\n      In msg0 (counting_messages s2). \nProof.     \n  intros s1 s2 msg lm t H_step H_view msg0 H_in.\n  destruct t; simpl in H_step;\n    destruct H_step as [H_subst _];\n    simpl in H_subst; \n    try (subst; assumption); \n    try rewrite H_subst in *; simpl;\n      try (simpl in H_view; lia);\n      try (right; assert (In msg0 (pending_messages_about_block s1 (get_block msg)) \\/ In msg0 (out_messages s1)) by tauto;\n           apply in_app_iff in H; assumption);\n      try tauto.\nQed.\n\nLemma counting_messages_local_monotonic :\n  forall (s1 s2 : NState) (msg : message) (lm : list message) (t : NState_transition_type),\n    (get_transition t) s1 msg s2 lm ->\n    forall (msg0 : message),\n      In msg0 (counting_messages s1) ->\n      In msg0 (counting_messages s2). \nProof.     \n  intros s1 s2 msg lm t H_step msg0 H_in.\n  assert (H_step_copy := H_step). \n  destruct t; simpl in H_step;\n    destruct H_step as [H_subst _];\n    try (subst; assumption);\n    try (rewrite H_subst; simpl; rewrite in_app_iff; repeat right; assumption); \n    try (rewrite H_subst in *; simpl; right;\n         assert (H : In msg0 (pending_messages_about_block s1 (get_block msg)) \\/ In msg0 (out_messages s1)) by tauto;\n         apply in_app_iff in H; assumption);\n    try (destruct H_step_copy as [_ [_ [_ [H_init _]]]]; \n         rewrite H_init in H_in; inversion H_in);\n    try (rewrite H_subst; simpl; try rewrite in_app_iff; repeat right; \n         assumption).\nQed.\n\nLemma about_local_out_messages :\n  forall (s1 s2 : NState) (msg : message) (lm : list message) (p : NState_transition_type),\n    get_transition p s1 msg s2 lm ->\n    forall (msg0 : message),\n      In msg0 lm ->\n      In msg0 (out_messages s2). \nProof. \n  intros s1 s2 msg lm p H_step msg0 H_in. \n  destruct p;\n    assert (H_step_copy := H_step);\n    destruct H_step as [H_update [H_out _]];\n    rewrite H_out in H_in;\n    (* In cases where lm = [] *) \n    try (now apply in_nil in H_in);\n    try (rewrite H_update; simpl;\n         rewrite in_app_iff; tauto);\n    try (rewrite H_update; simpl;\n         inversion H_in; subst; try tauto;\n         right; apply in_app_iff; tauto);\n    try (rewrite H_update; \n         simpl in *;\n         destruct H_in as [H_in | [H_in | [H_in | H_in]]];\n         tauto). \nQed.\n\nLemma not_prepare_stage :\n  forall (s : NState) (b : block),\n    ~ prepare_stage s b ->\n    ~ vote_quorum_in_view s (node_view s) b /\\\n    forall (msg : message),\n      In msg (counting_messages s) ->\n      get_block msg = b ->\n      get_view msg = (node_view s) -> \n      get_message_type msg = PrepareQC ->\n      False. \nProof.\n  intros s b H_not. split.\n  intros H_not2. apply H_not.\n  exists (node_view s). split. lia. left. assumption.\n  intros. \n  apply H_not. exists (node_view s); split; try lia. right. exists msg. tauto.\nQed. \n\nLemma prepare_stage_record_agnostic :\n  forall (s : NState) (b : block) (msg : message),\n    prepare_stage (record s msg) b -> \n    prepare_stage s b. \nProof.\n  intros s b msg H.\n  destruct H as [v' [H_past H_prepare]]. \n  exists v'. split. assumption.\n  assumption. \nQed.\n\nLemma prepare_stage_record_plural_agnostic :\n  forall (s : NState) (b : block) (lm : list message),\n    prepare_stage (record_plural s lm) b <-> \n    prepare_stage s b. \nProof.\n  intros s b msg; split; intro H.\n  destruct H as [v' [H_past H_prepare]]. \n  exists v'. split. assumption.\n  assumption.\n  easy. \nQed.\n\nLemma prepare_stage_process_record_plural_agnostic :\n  forall (s : NState) (b : block) (lm : list message) (msg : message),\n    prepare_stage (process (record_plural s lm) msg) b <-> \n    prepare_stage (process s msg) b. \nProof.\n  intros s b msg; split; intro H.\n  destruct H as [v' [H_past H_prepare]]. \n  exists v'. split. assumption.\n  assumption.\n  easy.\nQed.\n", "meta": {"author": "runtimeverification", "repo": "giskard-verification", "sha": "ca807a07ada37b0904577d5e7364f422a3494a22", "save_path": "github-repos/coq/runtimeverification-giskard-verification", "path": "github-repos/coq/runtimeverification-giskard-verification/giskard-verification-ca807a07ada37b0904577d5e7364f422a3494a22/theories/local.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4726834766204329, "lm_q1q2_score": 0.26935993243181544}}
{"text": "Require Export LibTactics.\nRequire Export Metalib.Metatheory.\nRequire Import Syntax_ott.\nRequire Import Row_inf.\nRequire Import Fii_inf.\nRequire Import Infrastructure.\n\nSet Implicit Arguments.\n\n\n\nFixpoint fv_Gtx (Gtx : GContext) {struct Gtx} : vars :=\n  match Gtx with\n  | nil            => {}\n  | cons (x, y) P' => fv_rtyp_in_rt y \\u fv_Gtx P'\n  end.\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 C3 := gather_atoms_with (fun x : stctx => dom x) in\n  let C4 := gather_atoms_with (fun x : sctx => dom x) in\n  let D4 := gather_atoms_with (fun x => fv_sty_in_sty x) in\n  let D5 := gather_atoms_with (fun x => fv_sty_in_sexp x) in\n  let D6 := gather_atoms_with (fun x => fv_sexp_in_sexp x) in\n  let D8 := gather_atoms_with (fun x => fv_rtyp_in_rtyp x) in\n  let D9 := gather_atoms_with (fun x => fv_rtyp_in_rlist x) in\n  let D10 := gather_atoms_with (fun x => fv_rtyp_in_rt x) in\n  let D11 := gather_atoms_with (fun x => fv_rexp_in_rexp x) in\n  let D12 := gather_atoms_with (fun x => fv_rtyp_in_rexp x) in\n  let D13 := gather_atoms_with (fun x : GContext => dom x) in\n  let D14 := gather_atoms_with (fun x : PContext => dom x) in\n  let D15 := gather_atoms_with (fun x => fv_rtyp_in_rt x) in\n  let D16 := gather_atoms_with (fun x : TContext => dom x) in\n  let D17 := gather_atoms_with (fun x : GContext => fv_Gtx x) in\n  let D18 := gather_atoms_with (fun x : PContext => fv_Ptx x) in\n  let D19 := gather_atoms_with (fun x : stctx => fv_stctx x) in\n  constr:(A \\u B \\u C3 \\u C4 \\u D4 \\u D5 \\u D6 \\u D8 \\u D9 \\u D10 \\u D11 \\u D12 \\u D13 \\u D14 \\u D15 \\u D16 \\u D17 \\u D18 \\u D19).\n\nLemma fv_notin_open_sty_wrt_sty_rec : forall B X i A,\n    X \\notin fv_sty_in_sty A  ->\n    X \\notin fv_sty_in_sty B  ->\n    X \\notin fv_sty_in_sty (open_sty_wrt_sty_rec i A B).\nProof with eauto.\n  intro B. inductions B; introv H1 H2; simpls...\n  destruct (lt_eq_lt_dec n i); simpls...\n  destruct s; simpls...\nQed.\n\n(* ********************************************************************** *)\n(** * Locally Closed *)\n\nLemma lc_rt_from_wfrt : forall Ttx rt,\n    wfrt Ttx rt ->\n    lc_rt rt\nwith lc_rtyp_from_wfr : forall Ttx r,\n    wfr Ttx r ->\n    lc_rtyp r\nwith lc_rlist_from_wfcl : forall Ttx R,\n    wfcl Ttx R ->\n    lc_rlist R.\nProof with eauto.\n  -\n  induction 1; constructor; auto.\n  + eapply lc_rlist_from_wfcl...\n  + introv.\n    pick_fresh X.\n    forwards ~ : H1 X.\n    rewrite subst_rtyp_in_rt_intro with (r1:=r_TyVar_f a) (a1:=X)...\n    apply subst_rtyp_in_rt_lc_rt...\n  + eapply lc_rtyp_from_wfr...\n\n  -\n    induction 1; constructor; auto.\n    eapply lc_rt_from_wfrt...\n\n  -\n    induction 1; constructor; auto.\n    eapply lc_rtyp_from_wfr...\nQed.\n\nLemma lc_sty_from_swft : forall DD B,\n    swft DD B ->\n    lc_sty B.\nProof with eauto.\n  induction 1...\nQed.\nHint Resolve lc_rt_from_wfrt lc_rt_from_wfrt lc_rlist_from_wfcl lc_sty_from_swft : lngen.\n\n\n(* ********************************************************************** *)\n(** * Wellformedness *)\n\nLemma wfrt_from_binds_wfc: forall Ttx Gtx x rt,\n    wfc Ttx Gtx ->\n    binds x rt Gtx ->\n    wfrt Ttx rt.\nProof.\n  introv H BD. induction H.\n  false.\n  apply binds_cons_1 in BD.\n  destruct BD as [ [I1 I2] | I3 ];\n  substs; auto.\nQed.\n\nLtac destruct_hypo :=\n  match goal with\n  | H: _ /\\ _ |- _ => destruct H\n  end.\n\nLtac invert_wfrt :=\n  match goal with\n  | H : wfrt _ (rt_Record _) |- _ => inverts H\n  end.\n\n\nLemma cmp_regular : forall Ttx r1 r2,\n    cmp Ttx r1 r2 ->\n    wfr Ttx r1 /\\ wfr Ttx r2\nwith teq_regular : forall Ttx rt1 rt2,\n    teq Ttx rt1 rt2 ->\n    wfrt Ttx rt1 /\\ wfrt Ttx rt2\nwith ceq_regular : forall Ttx R1 R2,\n    ceq Ttx R1 R2 ->\n    wfcl Ttx R1 /\\ wfcl Ttx R2.\nProof with eauto.\n  -\n  induction 1; repeat destruct_hypo; splits...\n  + apply teq_regular in H0. destruct_hypo. repeat invert_wfrt...\n  + apply teq_regular in H1. destruct_hypo. repeat invert_wfrt...\n  + inversions H1...\n  + inversions H1...\n\n  -\n  induction 1; repeat destruct_hypo; splits; try (solve[repeat invert_wfrt; eauto])...\n  + pick fresh X and apply wfrt_All.\n    apply ceq_regular in H. destruct_hypo...\n    forwards ~ [? ?] : H1 X.\n  + pick fresh X and apply wfrt_All.\n    apply ceq_regular in H. destruct_hypo...\n    forwards ~ : H3 X. destruct_hypo...\n  + lets: cmp_regular H. lets: cmp_regular H0.\n  repeat destruct_hypo...\n  + lets: cmp_regular H. lets: cmp_regular H0.\n  repeat destruct_hypo...\n  constructor...\n  constructor...\n  + lets: cmp_regular H. repeat destruct_hypo...\n  + lets: cmp_regular H. repeat destruct_hypo...\n\n  -\n  induction 1; repeat destruct_hypo; splits...\n  + lets: teq_regular H0. destruct_hypo... repeat invert_wfrt...\n  + lets: teq_regular H0. destruct_hypo... repeat invert_wfrt...\n  + inversions H...\nQed.\n\nLemma cmpList_wfr: forall Ttx r R,\n    cmpList Ttx r R ->\n    wfr Ttx r.\nProof with eauto.\n  induction 1...\nQed.\n\nLemma wftc_from_wfc : forall T G,\n    wfc T G ->\n    wftc T.\nProof with eauto.\n  introv WFC.\n  induction WFC; simpls...\nQed.\n\n\nLemma wftc_uniq : forall Ttx,\n    wftc Ttx ->\n    uniq Ttx.\nProof with eauto.\n  introv WFTC.\n  induction WFTC; simpls...\nQed.\n\nHint Resolve wftc_uniq.\n\n\n\nLemma empty_cmp : forall Ttx R,\n    wfcl Ttx R ->\n    cmpList Ttx r_Empty R.\nProof with eauto.\n  introv WFCL.\n  induction WFCL; simpls...\nQed.\n\n\nHint Resolve empty_cmp.\n\nLemma wftc_strength: forall E G,\n    wftc (E ++ G) ->\n    wftc G.\nProof with eauto.\n  intros E.\n  alist induction E; introv WFTC; simpls...\n  inverts WFTC.\n  eapply IHE...\nQed.\n\n\nLemma map_subst_rtyp_in_binding_id : forall G Z P,\n  Z `notin` fv_Gtx G ->\n  G = map (subst_rtyp_in_rt P Z) G.\nProof with eauto.\n  intros G.\n  induction G; intros...\n\n  destruct a.\n  rewrite map_cons.\n  simpls.\n  f_equal; simpls...\n\n  rewrite subst_rtyp_in_rt_fresh_eq; simpls...\nQed.\n\n\n\n\nHint Extern 1 (wfr ?E ?t) =>\n  match goal with\n  | H: cmpList E t _ |- _ => apply (cmpList_wfr H)\n  end.\n\nHint Extern 1 (wfr ?E ?t) =>\n  match goal with\n  | H: cmp E t _ |- _ => apply (proj1 (cmp_regular H))\n  | H: cmp E _ t |- _ => apply (proj2 (cmp_regular H))\n  end.\n\nHint Extern 1 (wfrt ?E ?t) =>\n  match goal with\n  | H: teq E t _ |- _ => apply (proj1 (teq_regular H))\n  | H: teq E _ t |- _ => apply (proj2 (teq_regular H))\n  end.\n\nHint Extern 1 (wfcl ?E ?t) =>\n  match goal with\n  | H: ceq E t _ |- _ => apply (proj1 (ceq_regular H))\n  | H: ceq E _ t |- _ => apply (proj2 (ceq_regular H))\n  end.\n\nLemma cmpList_wfcl: forall Ttx r R,\n    cmpList Ttx r R ->\n    wftc Ttx ->\n    wfcl Ttx R.\nProof with eauto.\n  introv H1 H2. inductions H1...\nQed.\n\n\nHint Extern 1 (wfcl ?E ?t) =>\n  match goal with\n  | H: cmpList E _ t |- _ => apply (cmpList_wfcl H)\n  end.\n\n(* ********************************************************************** *)\n(** * WEAKENING *)\n\nScheme wfcl_ind := Induction for wfcl Sort Prop\n  with wfrt_ind := Induction for wfrt Sort Prop\n  with wfr_ind  := Induction for wfr Sort Prop\n  with cmp_ind  := Induction for cmp Sort Prop\n  with ceq_ind  := Induction for ceq Sort Prop\n  with teq_ind  := Induction for teq Sort Prop.\n\nCombined Scheme wfrt_mutind from wfcl_ind, wfrt_ind, wfr_ind, cmp_ind, ceq_ind, teq_ind.\n\n\nInductive same_tctx : TContext -> TContext -> Prop :=\n| same_empty : same_tctx nil nil\n| same_cons : forall X A B s1 s2,\n    ceq s1 A B ->\n    wfcl s1 A ->\n    wfcl s2 B ->\n    same_tctx s1 s2 ->  same_tctx ([(X , A)] ++ s1) ([(X , B)] ++ s2).\n\nLemma same_tctx_dom : forall ctxa ctxb,\n    same_tctx ctxa ctxb ->\n    dom ctxa [=] dom ctxb.\nProof with eauto; try fsetdec.\n  induction 1; simpls...\nQed.\n\nLemma same_tctx_var : forall s1 s2 X A,\n    same_tctx s1 s2 ->\n    binds X A s1 ->\n    exists B, binds X B s2.\nProof with eauto.\n  introv Eq.\n  gen X A.\n  induction Eq; introv I.\n\n  analyze_binds I.\n\n  analyze_binds I...\n  lets (B0 & ?) : IHEq BindsTac.\n\n  exists B0...\nQed.\n\nHint Constructors same_tctx.\nLemma wf_general_weakening :\n  (forall T R,\n      wfcl T R ->\n        forall G E F,\n          T = G ++ E ->\n          wftc (G ++ F ++ E) ->\n          wfcl (G ++ F ++ E) R)\n  /\\ (\n    forall T R,\n      wfrt T R ->\n      forall G E F,\n        T = G ++ E ->\n        wftc (G ++ F ++ E) ->\n        wfrt (G ++ F ++ E) R)\n  /\\ (\n    forall T R,\n      wfr T R ->\n      forall G E F,\n          T = G ++ E ->\n          wftc (G ++ F ++ E) ->\n          wfr (G ++ F ++ E) R)\n  /\\ (\n    forall T R1 R2,\n      cmp T R1 R2 ->\n      wfr T R1 /\\ wfr T R2 /\\\n      forall G E F,\n          T = G ++ E ->\n          wftc (G ++ F ++ E) ->\n          cmp (G ++ F ++ E) R1 R2)\n  /\\ (\n    forall T R1 R2,\n      ceq T R1 R2 ->\n      wfcl T R1 /\\ wfcl T R2 /\\\n      forall G E F,\n          T = G ++ E ->\n          wftc (G ++ F ++ E) ->\n          ceq (G ++ F ++ E) R1 R2)\n  /\\(\n    forall T R1 R2,\n      teq T R1 R2 ->\n      wfrt T R1 /\\ wfrt T R2 /\\\n      forall G E F,\n          T = G ++ E ->\n          wftc (G ++ F ++ E) ->\n          teq (G ++ F ++ E) R1 R2)\n.\nProof with eauto.\n  apply wfrt_mutind; intros; repeat destruct_hypo; substs; try splits;\n    intros; substs;\n    repeat invert_wfrt...\n  -\n  pick fresh X and apply wfrt_All...\n  rewrite_env ((([(X, R)] ++ G) ++ F ++ E)).\n  apply H0...\n  simpl_env...\n  - inverts H0...\n  - inverts H0...\n  - inverts w...\n  - pick fresh X and apply wfrt_All...\n    forwards ~ : H0 X.\n    repeat destruct_hypo...\n  - pick fresh X and apply wfrt_All...\n    forwards ~ : H1 X.\n    repeat destruct_hypo...\n  - pick fresh X and apply teq_CongAll...\n    rewrite_env ((([(X, R)] ++ G) ++ F ++ E)).\n    apply H0... simpl. constructor...\n    forwards ~ : H3 G E F...\n    rewrite_env ((([(X, R')] ++ G) ++ F ++ E)).\n    apply H1... simpl. constructor...\n    forwards ~ : H3 G E F...\n  - intros. subst...\n    apply teq_CongMerge...\n  - apply wfrt_Rec.\n    constructor...\nQed.\n\nLemma wfcl_weakening : forall R G E F,\n    wfcl (G ++ E) R ->\n    wftc (G ++ F ++ E) ->\n    wfcl (G ++ F ++ E) R.\nProof.\n  intros.\n  pose (proj1 wf_general_weakening) as I.\n  eapply I; eauto.\nQed.\n\nLemma wfcl_weakening_head : forall R E F,\n    wfcl E R ->\n    wftc (F ++ E) ->\n    wfcl (F ++ E) R.\nProof.\n  intros.\n  rewrite_env (nil ++ F ++ E).\n  apply wfcl_weakening; eauto.\nQed.\n\nLemma wfcl_weakening_tail : forall R E G,\n    wfcl G R ->\n    wftc (G ++ E) ->\n    wfcl (G ++ E) R.\nProof with eauto.\n  intros.\n  rewrite_env (G ++ E ++ nil).\n  apply wfcl_weakening; simpl_env...\nQed.\n\n\nLemma wfcl_from_binds_wftc: forall Ttx a A,\n  wftc Ttx ->\n  binds a A Ttx ->\n  wfcl Ttx A.\nProof with eauto.\n  introv H BD. induction H.\n  false.\n  apply binds_cons_1 in BD.\n  destruct BD as [ [I1 I2] | I3 ];\n  substs;\n  apply wfcl_weakening_head...\nQed.\n\nLemma wfr_weakening : forall R G E F,\n    wfr (G ++ E) R ->\n    wftc (G ++ F ++ E) ->\n    wfr (G ++ F ++ E) R.\nProof.\n  intros.\n  pose (proj1 (proj2 (proj2 wf_general_weakening))) as I.\n  eapply I; eauto.\nQed.\n\nLemma wfr_weakening_head : forall R E F,\n    wfr E R ->\n    wftc (F ++ E) ->\n    wfr (F ++ E) R.\nProof.\n  intros.\n  rewrite_env (nil ++ F ++ E).\n  apply wfr_weakening; eauto.\nQed.\n\nLemma wfr_weakening_tail : forall R E G,\n    wfr G R ->\n    wftc (G ++ E) ->\n    wfr (G ++ E) R.\nProof with eauto.\n  intros.\n  rewrite_env (G ++ E ++ nil).\n  apply wfr_weakening; simpl_env...\nQed.\n\nLemma wfrt_weakening : forall R G E F,\n    wfrt (G ++ E) R ->\n    wftc (G ++ F ++ E) ->\n    wfrt (G ++ F ++ E) R.\nProof.\n  intros.\n  pose ((proj1 (proj2 wf_general_weakening))) as I.\n  eapply I; eauto.\nQed.\n\nLemma wfrt_weakening_head : forall R E F,\n    wfrt E R ->\n    wftc (F ++ E) ->\n    wfrt (F ++ E) R.\nProof.\n  intros.\n  rewrite_env (nil ++ F ++ E).\n  apply wfrt_weakening; eauto.\nQed.\n\nLemma wfrt_weakening_tail : forall R E G,\n    wfrt G R ->\n    wftc (G ++ E) ->\n    wfrt (G ++ E) R.\nProof with eauto.\n  intros.\n  rewrite_env (G ++ E ++ nil).\n  apply wfrt_weakening; simpl_env...\nQed.\n\nLemma cmp_weakening : forall G E F A B,\n    cmp (G ++ E) A B ->\n    wftc (G ++ F ++ E) ->\n    cmp (G ++ F ++ E) A B.\nProof.\n  intros.\n  pose (proj1 (proj2 (proj2 (proj2 wf_general_weakening))))  as I.\n  eapply I; eauto.\nQed.\n\nLemma cmp_weakening_head : forall E F A B,\n    cmp E A B ->\n    wftc (F ++ E) ->\n    cmp (F ++ E) A B.\nProof.\n  intros. rewrite_env (nil ++ F ++ E).\n  apply cmp_weakening; eauto.\nQed.\n\n(* ********************************************************************** *)\n(** * FV *)\n\nScheme rlist_ind := Induction for wfcl Sort Prop\n  with rt_ind    := Induction for wfrt Sort Prop\n  with rtyp_ind  := Induction for wfr  Sort Prop.\nCombined Scheme rlist_rt_mutind from rlist_ind, rt_ind, rtyp_ind.\n\nLemma notin_fv_rtyp_in_rt_open_rt_wrt_rtyp_rec: forall A a B n,\n    a `notin` fv_rtyp_in_rtyp B ->\n    a `notin` fv_rtyp_in_rt A ->\n    a `notin` fv_rtyp_in_rt (open_rt_wrt_rtyp_rec n B A)\nwith  notin_fv_rtyp_in_rlist_open_rlist_wrt_rtyp_rec: forall A a B n,\n    a `notin` fv_rtyp_in_rtyp B ->\n    a `notin` fv_rtyp_in_rlist A ->\n    a `notin` fv_rtyp_in_rlist (open_rlist_wrt_rtyp_rec n B A)\nwith  notin_fv_rtyp_in_rtyp_open_rtyp_wrt_rtyp_rec: forall A a B n,\n    a `notin` fv_rtyp_in_rtyp B ->\n    a `notin` fv_rtyp_in_rtyp A ->\n    a `notin` fv_rtyp_in_rtyp (open_rtyp_wrt_rtyp_rec n B A).\nProof.\n  -\n  intro A. induction A; introv NOT1 NOT2 ; simpls; auto.\n  -\n  intro A. induction A; introv NOT1 NOT2 ; simpls; auto.\n  -\n  intro A. induction A. introv I1; introv I2 . simpl.\n  destruct (lt_eq_lt_dec n n0). destruct s; simpl; auto...\n  simpl; auto.\n\n  introv I1; introv I2 . simpl; auto.\n  introv I1; introv I2 . simpl; auto.\n  introv I1; introv I2 . simpl; auto.\n  introv I1; introv I2 . simpl; auto.\n  simpl in I2.\n  apply notin_union.\n  apply IHA1; auto.\n  apply IHA2; auto.\nQed.\n\nLemma notin_fv_rtyp_in_rt_open_rt_wrt_rtyp: forall A a B,\n    a `notin` fv_rtyp_in_rtyp B ->\n    a `notin` fv_rtyp_in_rt A ->\n    a `notin` fv_rtyp_in_rt (open_rt_wrt_rtyp A B).\nProof.\n  introv I1 I2.\n  unfold open_rt_wrt_rtyp.\n  apply notin_fv_rtyp_in_rt_open_rt_wrt_rtyp_rec; eauto.\nQed.\n\nLemma notin_fv_rtyp_in_rlist_open_rlist_wrt_rtyp: forall A a B,\n    a `notin` fv_rtyp_in_rtyp B ->\n    a `notin` fv_rtyp_in_rlist A ->\n    a `notin` fv_rtyp_in_rlist (open_rlist_wrt_rtyp A B).\nProof.\n  introv I1 I2.\n  unfold open_rlist_wrt_rtyp.\n  apply notin_fv_rtyp_in_rlist_open_rlist_wrt_rtyp_rec; eauto.\nQed.\n\nLemma  notin_fv_rtyp_in_rtyp_open_rtyp_wrt_rtyp: forall A a B,\n    a `notin` fv_rtyp_in_rtyp B ->\n    a `notin` fv_rtyp_in_rtyp A ->\n    a `notin` fv_rtyp_in_rtyp (open_rtyp_wrt_rtyp A B).\nProof.\n  introv I1 I2.\n  unfold open_rlist_wrt_rtyp.\n  apply notin_fv_rtyp_in_rtyp_open_rtyp_wrt_rtyp_rec; eauto.\nQed.\n\nLemma notin_Fv_rtyp_in_rt_open_rt_wrt_rtyp_inverse: forall A B a n,\n    a `notin` fv_rtyp_in_rt (open_rt_wrt_rtyp_rec n B A) ->\n    a `notin` fv_rtyp_in_rt A\nwith notin_Fv_rtyp_in_rlist_open_rlist_wrt_rtyp_inverse: forall A B a n,\n    a `notin` fv_rtyp_in_rlist (open_rlist_wrt_rtyp_rec n B A) ->\n    a `notin` fv_rtyp_in_rlist A\nwith notin_Fv_rtyp_in_rtyp_open_rtyp_wrt_rtyp_inverse: forall A B a n,\n    a `notin` fv_rtyp_in_rtyp (open_rtyp_wrt_rtyp_rec n B A) ->\n    a `notin` fv_rtyp_in_rtyp A.\nProof with auto.\n  -\n    induction A; introv NOTIN; simpls...\n    forwards ~ : IHA1. forwards ~ : IHA2.\n    apply notin_union.\n    apply notin_Fv_rtyp_in_rlist_open_rlist_wrt_rtyp_inverse with B n...\n    apply IHA with B (S n)...\n    apply notin_Fv_rtyp_in_rtyp_open_rtyp_wrt_rtyp_inverse with B n...\n  -\n    induction A; introv NOTIN; simpls...\n    apply notin_union.\n    apply notin_Fv_rtyp_in_rtyp_open_rtyp_wrt_rtyp_inverse with B n...\n    apply IHA with B (n)...\n  -\n    induction A; introv NOTIN; simpls...\n    apply notin_Fv_rtyp_in_rt_open_rt_wrt_rtyp_inverse with B n...\n    apply notin_union.\n    apply IHA1 with B n... apply IHA2 with B n...\nQed.\n\nLemma wfr_fresh : forall F r a,\n    wfr F r ->\n    a `notin` dom F ->\n    a `notin` fv_rtyp_in_rtyp r\nwith wfrt_fresh : forall F r a,\n    wfrt F r ->\n    a `notin` dom F ->\n    a `notin` fv_rtyp_in_rt r\nwith wfcl_fresh : forall F r a,\n    wfcl F r ->\n    a `notin` dom F ->\n    a `notin` fv_rtyp_in_rlist r.\nProof.\n  -\n    induction 1; introv NOTIN; simpl; auto.\n    apply test_solve_notin_3. introv I. substs.\n    false binds_dom_contradiction; eauto.\n    apply wfrt_fresh with Ttx; auto...\n  -\n    induction 1; introv NOTIN; simpl; auto.\n    apply notin_union. apply wfcl_fresh with Ttx; auto.\n    pick_fresh X. forwards ~ : H1 X; auto.\n\n    eapply notin_Fv_rtyp_in_rt_open_rt_wrt_rtyp_inverse. eassumption.\n    apply wfr_fresh with Ttx; auto.\n  -\n    induction 1; introv NOTIN; simpl; auto.\n    apply notin_union. apply wfr_fresh with Ttx; auto.\n    apply IHwfcl; auto.\nQed.\n\n\n(* ********************************************************************** *)\n(** * CMP *)\n\nLemma cmp_from_cmpList : forall F B R r,\n    cmpList F B R ->\n    rtyp_in_rlist r R ->\n    cmp F B r.\nProof.\n  induction 1; introv Rin; simpls.\n  inverts Rin.\n  inverts Rin; auto.\nQed.\n\n(* ********************************************************************** *)\n(** * SUBSTITUTION *)\n\nLemma subst_rtyp_rtyp_in_rlist: forall r R a B,\n    rtyp_in_rlist r R ->\n    rtyp_in_rlist (subst_rtyp_in_rtyp B a r) (subst_rtyp_in_rlist B a R).\nProof.\n  induction 1; simpls.\n  apply ti_head...\n  apply ti_cons; auto...\nQed.\n\nScheme wftc_ind1 := Induction for wftc Sort Prop\n  with wfcl_ind1 := Induction for wfcl Sort Prop\n  with wfrt_ind1 := Induction for wfrt Sort Prop\n  with wfr_ind1 := Induction for wfr Sort Prop\n  with cmp_ind1 := Induction for cmp Sort Prop\n  with ceq_ind1 := Induction for ceq Sort Prop\n  with teq_ind1 := Induction for teq Sort Prop.\n\nCombined Scheme wfrt_mutind' from wftc_ind1, wfcl_ind1, wfrt_ind1, wfr_ind1, cmp_ind1, ceq_ind1, teq_ind1.\n\nLemma wf_general_subst :\n  ( forall T,\n      wftc T ->\n      forall E F B a R,\n        T = (E ++ [(a, R)] ++ F) ->\n        cmpList F B R ->\n        wfr F B ->\n        wftc (map (subst_rtyp_in_rlist B a) E ++ F)\n  ) /\\ (\n   forall T A,\n    wfcl T A ->\n    forall E F B a R,\n      wftc T ->\n      wftc (map ( subst_rtyp_in_rlist B a ) E ++ F) ->\n      T = (E ++ [(a, R)] ++ F) ->\n      cmpList F B R ->\n      wfr F B ->\n      wfcl (map (subst_rtyp_in_rlist B a) E ++ F)\n           (subst_rtyp_in_rlist B a A)\n  ) /\\ (\n    forall T A,\n    wfrt T A ->\n    forall E F B a R,\n      wftc T ->\n      wftc (map ( subst_rtyp_in_rlist B a ) E ++ F) ->\n      T = (E ++ [(a, R)] ++ F) ->\n      cmpList F B R ->\n      wfr F B ->\n      wfrt (map ( subst_rtyp_in_rlist B a ) E ++ F)\n           (subst_rtyp_in_rt B a A)\n  ) /\\ (\n    forall T A,\n    wfr T A ->\n    forall E F B a R,\n      wftc T ->\n      wftc (map ( subst_rtyp_in_rlist B a ) E ++ F) ->\n      T = (E ++ [(a, R)] ++ F) ->\n      cmpList F B R ->\n      wfr F B ->\n      wfr (map (subst_rtyp_in_rlist B a) E ++ F)\n          (subst_rtyp_in_rtyp B a A)\n  ) /\\ (\n    forall T A C,\n      cmp T A C ->\n      forall E F B a R,\n      wftc T ->\n      wftc (map ( subst_rtyp_in_rlist B a ) E ++ F) ->\n      T = (E ++ [(a, R)] ++ F) ->\n      cmpList F B R ->\n      wfr F B ->\n      cmp (map (subst_rtyp_in_rlist B a) E ++ F)\n          (subst_rtyp_in_rtyp B a A)\n          (subst_rtyp_in_rtyp B a C)\n  ) /\\ (\n    forall T A C,\n      ceq T A C ->\n      forall E F B a R,\n      wftc T ->\n      wftc (map ( subst_rtyp_in_rlist B a ) E ++ F) ->\n      T = (E ++ [(a, R)] ++ F) ->\n      cmpList F B R ->\n      wfr F B ->\n      ceq (map (subst_rtyp_in_rlist B a) E ++ F)\n          (subst_rtyp_in_rlist B a A)\n          (subst_rtyp_in_rlist B a C)\n  ) /\\ (\n    forall T A C,\n      teq T A C ->\n      forall E F B a R,\n      wftc T ->\n      wftc (map ( subst_rtyp_in_rlist B a ) E ++ F) ->\n      T = (E ++ [(a, R)] ++ F) ->\n      cmpList F B R ->\n      wfr F B ->\n      teq (map (subst_rtyp_in_rlist B a) E ++ F)\n          (subst_rtyp_in_rt B a A)\n          (subst_rtyp_in_rt B a C)\n  )\n.\nProof with eauto.\n  apply wfrt_mutind'; try solve [intros; substs; simpl; eauto].\n  - intros. false nil_neq_one_mid...\n  - introv WF IH1 WF2 IH2 NEQ EQ CMP WFR; substs.\n    analyze_binds EQ.\n    apply one_eq_app in EQ.\n    destruct EQ as [ (qs & [I1 I2]) | [I1 I2]]; substs.\n    simpl. constructor...\n    simpl. simpl in I2.\n    invert I2. intros. substs...\n  - introv WFCL IH1 IH2 IH3 WFTC1 WFTC2 EQ CMP WFR. substs.\n    simpl.\n    pick fresh X and apply wfrt_All...\n    forwards ~ : IH3 X ([(X, R)] ++ E) B a R0...\n    simpl. constructor...\n    simpl... simpl in H.\n    unfold open_rt_wrt_rtyp in H.\n    rewrite subst_rtyp_in_rt_open_rt_wrt_rtyp_rec in H...\n    rewrite subst_rtyp_in_rtyp_fresh_eq in H...\n    apply lc_rtyp_from_wfr with F...\n  - introv BD WFTC1 WFTC2 EQ CMP WFR. substs... simpl.\n    case_if...\n    eapply wfr_weakening_head...\n    analyze_binds BD...\n  - introv WFCL IH1 WFR IH2 BD RTY WFR1 WFR3 EQ CMP. introv WFR2. substs.\n    simpl. case_if; subst.\n    +\n    apply binds_mid_eq in BD; auto. substs.\n    apply cmp_weakening_head; auto.\n    forwards ~ : cmp_from_cmpList CMP RTY.\n    rewrite subst_rtyp_in_rtyp_fresh_eq; auto.\n    apply wfr_fresh with F...\n    apply fresh_mid_tail with R0 E...\n    +\n    analyze_binds BD.\n    apply subst_rtyp_rtyp_in_rlist with (a:=a0) (B:=B) in RTY.\n    apply binds_map_2 with(f:=subst_rtyp_in_rlist B a0) in BindsTac.\n    apply cmp_Tvar with (subst_rtyp_in_rlist B a0 R)...\n\n    apply subst_rtyp_rtyp_in_rlist with (a:=a0) (B:=B) in RTY.\n    apply cmp_Tvar with (subst_rtyp_in_rlist B a0 R)...\n    rewrite subst_rtyp_in_rlist_fresh_eq; auto.\n    apply wfcl_fresh with F...\n    eapply wfcl_from_binds_wftc...\n    apply wftc_strength with (E ++ [(a0, R0)]);\n    rewrite_env (E ++ [(a0, R0)] ++ F)...\n    apply fresh_mid_tail with R0 E...\n  - introv CMP IH1 WFRT IH2 WFTC WFTC2 EQ CMP2 WFR2. subst.\n    simpl.\n    apply cmp_Base with (subst_rtyp_in_rt B a rt5)...\n  - introv CMP IH1 WFTC WFTC2 EQ CMP2 WFR. subst.\n    apply cmp_MergeE1 with (subst_rtyp_in_rtyp B a s2)...\n  - introv CMP IH1 WFTC WFTC2 EQ CMP2 WFR. subst.\n    apply cmp_MergeE2 with (subst_rtyp_in_rtyp B a s1)...\n  - intros. simpls. substs.\n    pick fresh X and apply teq_CongAll...\n    specialize (H0 X).\n    forwards ~ : H0 ((X, R) :: E) F B a R0.\n    constructor...\n    simpls...\n    constructor... forwards ~ : H H2 H3 .\n    simpls...\n    unfold open_rt_wrt_rtyp in H4.\n    do 2 rewrite subst_rtyp_in_rt_open_rt_wrt_rtyp_rec in H4...\n    rewrite subst_rtyp_in_rtyp_fresh_eq in H4...\n    apply lc_rtyp_from_wfr with F...\n    apply lc_rtyp_from_wfr with F...\n    apply lc_rtyp_from_wfr with F...\n    specialize (H1 X).\n    forwards ~ : H1 ((X, R') :: E) F B a R0.\n    constructor...\n    simpls...\n    constructor... forwards ~ : H H2 H3 .\n    simpls...\n    constructor... forwards ~ : H H2 H3. \n    simpls...\n    unfold open_rt_wrt_rtyp in H4.\n    unfold open_rt_wrt_rtyp in H4.\n    do 2 rewrite subst_rtyp_in_rt_open_rt_wrt_rtyp_rec in H4...\n    rewrite subst_rtyp_in_rtyp_fresh_eq in H4...\n    apply lc_rtyp_from_wfr with F...\n    apply lc_rtyp_from_wfr with F...\n    apply lc_rtyp_from_wfr with F...\n  - intros. simpl... apply teq_CongMerge...\nQed.\n\nLemma wfrt_subst : forall A E F B a R,\n    wfrt (E ++ [(a, R)] ++ F) A ->\n    wftc (E ++ [(a, R)] ++ F) ->\n    cmpList F B R ->\n    wfr F B ->\n    wfrt (map ( subst_rtyp_in_rlist B a ) E ++ F)\n         (subst_rtyp_in_rt B a A).\nProof.\n  intros.\n  pose (proj1 (proj2 (proj2 wf_general_subst))) as I.\n  eapply I; eauto.\n  pose (proj1 wf_general_subst) as I2.\n  eapply I2; eauto.\nQed.\n\n\nLemma wfcl_subst : forall A E F B a R,\n    wfcl (E ++ [(a, R)] ++ F) A ->\n    wftc (E ++ [(a, R)] ++ F) ->\n    cmpList F B R ->\n    wfr F B ->\n    wfcl (map ( subst_rtyp_in_rlist B a ) E ++ F)\n         (subst_rtyp_in_rlist B a A).\nProof.\n  intros.\n  pose (proj1 (proj2 wf_general_subst)) as I.\n  eapply I; eauto.\n  pose (proj1 wf_general_subst) as I2.\n  eapply I2; eauto.\nQed.\n\n\nLemma wfc_subst_tb : forall F E Z P T B,\n  wfc (F ++ Z ~ B ++ E) T ->\n  wfr E P ->\n  cmpList E P B ->\n  wftc (map (subst_rtyp_in_rlist P Z) F ++ E) ->\n  wfc (map (subst_rtyp_in_rlist P Z) F ++ E) (map (subst_rtyp_in_rt P Z) T).\nProof with eauto using wftc_from_wfc.\n  introv WFC.\n  remember (F ++ Z ~ B ++ E) as G.\n  generalize dependent F.\n  induction WFC; introv EQ WFR CMP Ok; subst; simpls...\n\n  constructor...\n  simpl_env in *.\n  eapply wfrt_subst...\nQed.\n\nLemma wftc_subst_tb : forall Q Z P E F,\n  wftc (F ++ Z ~ Q ++ E) ->\n  wfr E P ->\n  cmpList E P Q ->\n  wftc (map (subst_rtyp_in_rlist P Z) F ++ E).\nProof with eauto.\n  introv WFTC.\n  alist induction F; introv WFR CMP; simpls...\n\n  inverts WFTC...\n\n  inverts WFTC...\n\n  constructor...\n  simpl_env in *.\n  eapply wfcl_subst...\nQed.\n\n\nLemma wfc_strengthen : forall X R Ttx Gtx,\n      wfc ([(X, R)] ++ Ttx) Gtx ->\n      wftc Ttx ->\n      wfcl Ttx R ->\n      X \\notin fv_Gtx Gtx ->\n      wfc Ttx Gtx.\nProof with eauto.\n  introv WFC WFTC WFCL NOTIN.\n\n  rewrite_env (nil ++ [(X, R)] ++ Ttx) in WFC.\n  forwards IMP : wfc_subst_tb WFC...\n  simpls.\n  rewrite <- map_subst_rtyp_in_binding_id in IMP...\nQed.\n\n\n(* ********************************************************************** *)\n(** * BINDING *)\n\nLemma wfp_binds : forall a R Ttx Ptx,\n  binds a R Ttx ->\n  wfp Ttx Ptx   ->\n  exists b, binds a b Ptx.\nProof with auto.\n  induction 2...\n  false.\n  apply binds_cons_1 in H.\n  destruct H as [[I1 I2]| I3].\n    subst. exists b...\n    forwards ~ (? & ?) : IHwfp I3.\n    exists x...\nQed.\n\nLemma binds_ptx_fv: forall a b Ptx,\n      binds a b Ptx ->\n      b `in` fv_Ptx Ptx.\nProof with eauto.\n  introv BD. inductions Ptx...\n  false. destruct a0. analyze_binds BD; simpl...\nQed.\n\nLemma wfp_binds_neq : forall Ttx Ptx a1 a2 b1 b2,\n    wfp Ttx Ptx ->\n    binds a1 b1 Ptx ->\n    binds a2 b2 Ptx ->\n    b1 <> a2.\nProof with eauto.\n  induction 1; introv BD1 BD2; eauto.\n  analyze_binds BD1; analyze_binds BD2.\n  forwards ~ : binds_In BindsTac...\n  introv I. subst. false H5...\n  forwards ~ : binds_ptx_fv BindsTac.\n  introv I. subst. false H3...\nQed.\n\nLemma wfp_binds_range_neq : forall Ttx Ptx a1 a2 b1 b2,\n    wfp Ttx Ptx ->\n    binds a1 b1 Ptx ->\n    binds a2 b2 Ptx ->\n    a1 <> a2 ->\n    b1 <> b2.\nProof with eauto.\n  induction 1; introv BD1 BD2 NEQ; eauto.\n  analyze_binds BD1; analyze_binds BD2.\n  forwards ~ : binds_ptx_fv BindsTac.\n  introv I. subst. false H6...\n  forwards ~ : binds_ptx_fv BindsTac.\n  introv I. subst. false H6...\nQed.\n\nLemma wfp_uniq : forall Ttx Ptx,\n  wfp Ttx Ptx ->\n  uniq Ptx.\nProof.\n  induction 1; eauto.\nQed.\nHint Resolve wfp_binds_neq wfp_uniq.\n\nLemma fv_Ptx_union : forall G P,\n    fv_Ptx (G ++ P) [=] fv_Ptx G \\u fv_Ptx P.\nProof with eauto.\n  intros G.\n  induction G; intros; simpls...\n\n  fsetdec.\n\n  destruct a.\n  specializes IHG P.\n  rewrite IHG.\n  fsetdec.\nQed.\n\n\nLemma wfp_mid_inv : forall Ptx1 Ptx2 a0 b0 Ttx,\n    wfp Ttx (Ptx1 ++ [(a0, b0)] ++ Ptx2) ->\n    b0 \\notin dom (Ptx1 ++ Ptx2) /\\ b0 \\notin fv_Ptx (Ptx1 ++ Ptx2 ).\nProof with eauto.\n  introv WFP. inductions WFP.\n  assert (binds a0 b0 nil).\n  rewrite x...\n  false.\n\n  apply one_eq_app in x.\n  destruct x as [ (P' & [I1 I2]) | [I1 I2]]; substs.\n  forwards ~ : IHWFP.\n  destruct_hypo. simpl_env in *.\n  repeat rewrite fv_Ptx_union in *.\n  simpls. splits...\n\n  simpl in I2. simpl_env.\n  inverts I2...\nQed.\n\n\n(* ********************************************************************** *)\n(** * TEQ *)\n\nLemma teq_record_r : forall Ttx rt r,\n    teq Ttx rt (rt_Record r) ->\n    exists r2, rt = rt_Record r2\nwith teq_record_l : forall Ttx rt r,\n    teq Ttx (rt_Record r) rt ->\n    exists r2, rt = rt_Record r2.\nProof with auto.\n  -\n    introv EQ. inductions EQ.\n    + exists r...\n    + forwards : teq_record_l EQ.\n      destruct_exists.\n      exists x...\n    + forwards ~ : IHEQ2. destruct_exists.\n      forwards : IHEQ1 H. destruct_exists.\n      exists x0...\n    + exists (r_SingleField l rt5)...\n    + exists (r_Merge r1 r2)...\n    + exists (r_Merge r r_Empty)...\n    + exists (r_Merge r1 (r_Merge r2 r3))...\n    + exists (r_Merge r1 r2)...\n  -\n    introv EQ. inductions EQ.\n    + exists r...\n    + forwards : teq_record_r EQ.\n      destruct_exists.\n      exists x...\n    + forwards ~ : IHEQ1. destruct_exists.\n      forwards : IHEQ2 H. destruct_exists.\n      exists x0...\n    + exists (r_SingleField l rt')...\n    + exists (r_Merge r1' r2')...\n    + exists (r0)...\n    + exists (r_Merge (r_Merge r1 r2) r3)...\n    + exists (r_Merge r2 r1)...\nQed.\n\n", "meta": {"author": "xnning", "repo": "Row-and-Bounded-via-Disjoint", "sha": "7ed92de6ca987b9840a5b0fe9ea3441eebf34b45", "save_path": "github-repos/coq/xnning-Row-and-Bounded-via-Disjoint", "path": "github-repos/coq/xnning-Row-and-Bounded-via-Disjoint/Row-and-Bounded-via-Disjoint-7ed92de6ca987b9840a5b0fe9ea3441eebf34b45/CoqProofs/elaborations/Row_Properties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2693599324318154}}
{"text": "(* Cut Elimination in Proof Nets *)(* TODO uacyclic pour tens trop long à compiler *)\n\nFrom Coq Require Import Bool Wf_nat.\nFrom OLlibs Require Import dectype.\nSet Warnings \"-notation-overridden\". (* to ignore warnings due to the import of ssreflect *)\nFrom mathcomp Require Import all_ssreflect zify.\nSet Warnings \"notation-overridden\".\nFrom GraphTheory Require Import preliminaries mgraph setoid_bigop structures bij.\n\nFrom Yalla Require Export graph_more mll_prelim mll_def mll_basic mll_correct.\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).\n\n\n(** * Axiom - cut reduction *)\nSection red_ax.\nVariables (G : proof_structure) (e : edge G) (Hcut : vlabel (target e) = cut)\n  (Hax : vlabel (source e) = ax).\n\n(* The label on the new edge is the one of the other arrow of the ax node, (dual (flabel e), ?) *)\nDefinition red_ax_graph_1 : base_graph :=\n  G ∔ [source (other_cut Hcut), elabel (other_ax Hax), target (other_ax Hax)].\n\nDefinition red_ax_graph : base_graph :=\n  induced ([set: red_ax_graph_1] :\\ (source e) :\\ (target e)).\n\n(* the degenerate case where the axiom and the cut form a loop *)\nLocal Notation non_degenerate := (None \\in edge_set ([set: red_ax_graph_1] :\\ source e :\\ target e)).\n\nLemma red_ax_degenerate_None :\n non_degenerate = (other_cut Hcut != other_ax Hax).\nProof.\n  rewrite !in_set !andb_true_r /=.\n  destruct (eq_comparable (other_cut Hcut) (other_ax Hax)) as [Heq | Hneq].\n  - rewrite Heq eq_refl other_ax_e. caseb.\n  - transitivity true; last by symmetry; apply /eqP.\n    splitb; apply /eqP.\n    + by apply no_source_cut.\n    + intro H. contradict Hneq. apply other_ax_eq.\n      rewrite H. splitb. apply other_cut_neq.\n    + intro H. contradict Hneq. symmetry; apply other_cut_eq.\n      rewrite H. splitb. apply other_ax_neq.\n    + by apply no_target_ax.\nQed.\n\nDefinition red_ax_order_1 : seq (edge red_ax_graph_1) :=\n  [seq if a == other_ax Hax then None else Some a | a <- order G].\n\nLemma red_ax_order_1_other_ax :\n  Some (other_ax Hax) \\notin red_ax_order_1.\nProof.\n  unfold red_ax_order_1. induction (order G); trivial.\n  rewrite /= in_cons. splitb. case_if.\n  by apply /eqP; apply nesym.\nQed.\n\nLemma red_ax_consistent_order :\n  all (pred_of_set (edge_set ([set: red_ax_graph_1] :\\ (source e) :\\ (target e)))) red_ax_order_1.\nProof.\n  apply /allP => a A.\n  assert (Hl : vlabel (target a) = c).\n  { revert A => /mapP[b B]. apply p_order in B.\n    case_if. }\n  destruct a as [a | ]; simpl in Hl.\n  - rewrite /edge_set. apply /setIdP. rewrite !in_set /=.\n    splitb; apply /eqP.\n    + by apply no_source_cut.\n    + intro Hc.\n      assert (a = other_ax Hax).\n      { apply other_ax_eq. splitb.\n        intros ?; subst a.\n        by rewrite Hcut in Hl. }\n      subst a.\n      contradict A; apply /negP.\n      apply red_ax_order_1_other_ax.\n    + intro Hc. by rewrite Hc Hcut in Hl.\n    + by apply no_target_ax.\n  - rewrite -in_set.\n    rewrite memKset red_ax_degenerate_None.\n    apply /eqP. intro Hc.\n    contradict Hl. by rewrite -Hc other_cut_e Hcut.\nQed.\n\nDefinition red_ax_order : seq (edge red_ax_graph) :=\n  sval (all_sigP red_ax_consistent_order).\n\nDefinition red_ax_graph_data : graph_data := {|\n  graph_of := red_ax_graph;\n  order := red_ax_order;\n  |}.\n\nDefinition red_ax_transport (b : bool) : edge red_ax_graph -> edge G :=\n  fun a => match val a with\n  | None => if b then other_ax Hax else other_cut Hcut\n  | Some a' => a'\n  end.\n\nLemma red_ax_transport_inj (b : bool) : injective (red_ax_transport b).\nProof.\n  intros [a A] [a' A'].\n  rewrite /red_ax_transport /=.\n  move => ?. apply /eqP. rewrite sub_val_eq /=.\n  assert (Some (if b then other_ax Hax else other_cut Hcut)\n    \\notin edge_set ([set: red_ax_graph_1] :\\ source e :\\ target e)).\n  { destruct b; rewrite !in_set /= ?other_ax_e ?other_cut_e; caseb. }\n  destruct a, a'; subst; trivial; [contradict A | contradict A']; by apply /negP.\nQed.\n\nLemma red_ax_transport_edges (b : bool) (v : G) Hv :\n  edges_at_outin b v = [set red_ax_transport b a | a in edges_at_outin b (Sub v Hv : red_ax_graph)].\nProof.\n  apply /setP => a.\n  rewrite Imset.imsetE !in_set.\n  symmetry; apply /imageP; case_if.\n  - assert (endpoint b a <> source e /\\ endpoint b a <> target e) as [Hvs Hvt]\n      by by (revert Hv; rewrite !in_set => /andP[/eqP-? /andP[/eqP-? _]]).\n    assert (a <> e) by by (intros ?; subst; destruct b; by rewrite_all eq_refl).\n    destruct (eq_comparable a (other_cut Hcut)) as [ | Hneqc];\n    [ | destruct (eq_comparable a (other_ax Hax)) as [ | Hneqa]]; subst.\n    + destruct b.\n      { contradict Hvt. apply other_cut_e. }\n      assert (Hn : non_degenerate).\n      { rewrite red_ax_degenerate_None. apply /eqP => Heq.\n        contradict Hv; apply /negP.\n        rewrite Heq other_ax_e !in_set. caseb. }\n      exists (Sub None Hn); trivial.\n      by rewrite !in_set; cbn.\n    + destruct b.\n      2:{ contradict Hvs. apply other_ax_e. }\n      apply nesym in Hneqc. revert Hneqc => /eqP. rewrite -red_ax_degenerate_None => Hn.\n      exists (Sub None Hn); trivial.\n      by rewrite !in_set; cbn.\n    + assert (Ha : Some a \\in edge_set ([set: red_ax_graph_1] :\\ source e :\\ target e)).\n      { rewrite !in_set /=.\n        splitb; apply /eqP.\n        - by apply no_source_cut.\n        - intros ?. contradict Hneqa. by apply other_ax_eq.\n        - intros ?. contradict Hneqc. by apply other_cut_eq.\n        - by apply no_target_ax. }\n      exists (Sub (Some a) Ha); trivial.\n      by rewrite !in_set; cbn.\n  - intros [[x ?] Hx Ha].\n    rewrite /red_ax_transport /= in Ha. subst.\n    contradict Hx; apply /negP.\n    rewrite in_set; cbn; simpl; apply /eqP.\n    by destruct x, b.\nQed.\n\nLemma red_ax_transport_flabel b (a : edge red_ax_graph) :\n  flabel a = flabel (red_ax_transport b a).\nProof.\n  destruct a as [[a | ] Ha], b; trivial; cbn.\n  destruct (p_ax_cut_bis G) as [Hpax Hpcut].\n  specialize (Hpcut _ Hcut _ (target_in_edges_at_in e)).\n  unfold is_dual_f, is_dual in Hpcut. revert Hpcut => /eqP-<-.\n  specialize (Hpax _ Hax _ (source_in_edges_at_out e)).\n  unfold is_dual_f, is_dual in Hpax. by revert Hpax => /eqP-->.\nQed.\n\nLemma red_ax_p_deg : proper_degree red_ax_graph.\nProof.\n  intros b [v Hv]; cbn.\n  rewrite -p_deg (red_ax_transport_edges _ Hv) card_imset //.\n  apply red_ax_transport_inj.\nQed.\n\n\nLemma red_ax_p_ax_cut : proper_ax_cut red_ax_graph.\nProof.\n  move => b [v Hv] /= Hl.\n  destruct (p_ax_cut Hl) as [el [er H]].\n  revert H; rewrite (red_ax_transport_edges _ Hv) Imset.imsetE 2!in_set.\n  move => [/imageP[El ? ?] [/imageP[Er ? ?] ?]]. subst el er.\n  exists El, Er. splitb.\n  by rewrite !(red_ax_transport_flabel b).\nQed.\n\nLemma red_ax_p_tens_parr : proper_tens_parr red_ax_graph.\nProof.\n  move => b [v Hv] /= Hl.\n  destruct (p_tens_parr Hl) as [el [er [ec [Lt [Ll [Rt [Rl [Ct Cl]]]]]]]].\n  revert Lt Rt Ct. rewrite !(red_ax_transport_edges _ Hv).\n  move => /imsetP[el' Lt' ?] /imsetP[er' Rt' ?] /imsetP[ec' Ct' ?]. subst el er ec.\n  rewrite -!(red_ax_transport_flabel) in Cl.\n  exists el', er', ec'. splitb.\n  - by destruct el' as [[? | ] ?].\n  - by destruct er' as [[? | ] ?].\nQed.\n\nLemma red_ax_p_noleft : proper_noleft red_ax_graph.\nProof. intros [[? | ] ?] ?; by apply p_noleft. Qed.\n\nLemma red_ax_p_order : proper_order red_ax_graph_data.\nProof.\n  rewrite /proper_order /red_ax_graph_data /red_ax_order /=.\n  destruct (all_sigP _) as [l L], (p_order G).\n  split.\n  - intros [a A]; cbn.\n    rewrite in_seq_sig !SubK -L /red_ax_order_1.\n    destruct a as [a | ].\n    + apply (@iff_stepl (a \\in order G)); [ | by apply iff_sym].\n      split.\n      * intro In. apply /mapP.\n        exists a; trivial.\n        case_if.\n        contradict A; apply /negP.\n        rewrite !in_set /= other_ax_e. caseb.\n      * move => /mapP[? ? /eqP]. case_if.\n    + apply (@iff_stepl (other_ax Hax \\in order G)); [ | by apply iff_sym].\n      split.\n      * intro In. apply /mapP.\n        exists (other_ax Hax); trivial. case_if.\n      * move => /mapP[? ? /eqP]. case_if.\n  - rewrite uniq_seq_sig -L /red_ax_order_1 map_inj_uniq //.\n    move => ? ? /eqP. case_if.\nQed.\n\nDefinition red_ax_ps : proof_structure := {|\n  graph_data_of := red_ax_graph_data;\n  p_deg := red_ax_p_deg;\n  p_ax_cut := red_ax_p_ax_cut;\n  p_tens_parr := red_ax_p_tens_parr;\n  p_noleft := red_ax_p_noleft;\n  p_order := red_ax_p_order;\n  |}.\n\n\n(** Sequent of an axiom - cut reduction *)\nLemma red_ax_sequent_eq : sequent red_ax_graph_data = [seq flabel e | e <- red_ax_order_1].\nProof.\n  rewrite /red_ax_graph_data /red_ax_order.\n  destruct (all_sigP _) as [l L].\n  by rewrite [in RHS]L -map_comp.\nQed.\n\nLemma red_ax_sequent : sequent red_ax_ps = sequent G.\nProof.\n  rewrite red_ax_sequent_eq /red_ax_order_1 /sequent -map_comp.\n  apply eq_map => a /=. case_if.\nQed.\n\n(** Decreasing number of vertices *)\nLemma red_ax_nb : #|G| = #|red_ax_graph| + 2.\nProof.\n  rewrite -(@card_imset _ _ val); [ | apply val_inj].\n  transitivity (#|setT :\\ (source e) :\\ (target e)| + 2).\n  - rewrite -cardsT [in LHS](cardsD1 (source e)) [in LHS](cardsD1 (target e)) !in_set.\n    enough (target e != source e) by lia.\n    apply /eqP => Hf. contradict Hcut.\n    by rewrite Hf Hax.\n  - f_equal. apply eq_card => v.\n    rewrite Imset.imsetE in_set.\n    symmetry; destruct (v \\in [set: G] :\\ source e :\\ target e) eqn:Hv; rewrite Hv.\n    + apply /imageP. by exists (Sub v Hv).\n    + apply /imageP; intros [[u U] _ ?]; subst v.\n      by rewrite U in Hv.\nQed.\n\n\n(** Correctness *)\n(* For this part, we assume that we are not in the degenerate case, i.e. the edge we added is still here *)\nDefinition red_ax_G (N : non_degenerate) :=\n  @invert_edge_graph _ _\n  (@extend_edge_graph _\n    (@extend_edge_graph _ red_ax_graph (Sub None N) cut (dual (flabel e)) (flabel e))\n    (Some (Sub None N)) ax (flabel e) (dual (flabel e)))\n  None.\n\nDefinition red_ax_iso_v_bij_fwd (N : non_degenerate) :\n  red_ax_G N -> G :=\n  fun v => match v with\n  | Some (Some (exist u _)) => u\n  | Some None               => target e\n  | None                    => source e\n  end.\n\nDefinition red_ax_iso_v_bij_bwd (N : non_degenerate) :\n  G -> red_ax_G N :=\n  fun v => if @boolP _ is AltTrue p then Some (Some (Sub v p))\n    else if v == source e then None else Some None.\n\nLemma red_ax_iso_v_bijK (N : non_degenerate) :\n  cancel (@red_ax_iso_v_bij_fwd N) (red_ax_iso_v_bij_bwd N).\nProof.\n  intros [[[v V] | ] | ]; cbn;\n  unfold red_ax_iso_v_bij_bwd; case: {-}_ /boolP => [Hc | /negP-?] //.\n  - cbnb.\n  - contradict Hc; apply /negP.\n    rewrite !in_set. caseb.\n  - case: ifP; trivial.\n    clear - Hcut Hax => /eqP H.\n    contradict Hcut. by rewrite H Hax.\n  - contradict Hc; apply /negP.\n    rewrite !in_set. caseb.\n  - case_if.\nQed.\n\nLemma red_ax_iso_v_bijK' (N : non_degenerate) :\n  cancel (red_ax_iso_v_bij_bwd N) (@red_ax_iso_v_bij_fwd N).\nProof.\n  intro v; unfold red_ax_iso_v_bij_bwd.\n  case: {-}_ /boolP => [// | ].\n  rewrite !in_set andb_true_r => /nandP[/negPn/eqP-? | /negPn/eqP-?]; subst; case_if.\nQed.\n\nDefinition red_ax_iso_v (N : non_degenerate) := {|\n  bij_fwd := _;\n  bij_bwd:= _;\n  bijK:= @red_ax_iso_v_bijK N;\n  bijK':= red_ax_iso_v_bijK' _;\n  |}.\n\nDefinition red_ax_iso_e_bij_fwd (N : non_degenerate) :\n  edge (red_ax_G N) -> edge G :=\n  fun a => match a with\n  | None                            => e\n  | Some None                       => other_cut Hcut\n  | Some (Some (exist None _))      => other_ax Hax\n  | Some (Some (exist (Some a) _))  => a\n  end.\n\nDefinition red_ax_iso_e_bij_bwd (N : non_degenerate) :\n  edge G -> edge (red_ax_G N) :=\n  fun a => if @boolP _ is AltTrue p then Some (Some (Sub (Some a) p))\n    else if a == e then None\n    else if a == other_ax Hax then Some (Some (Sub None N))\n    else Some None.\n\nLemma red_ax_iso_e_bijK (N : non_degenerate) :\n  cancel (@red_ax_iso_e_bij_fwd N) (@red_ax_iso_e_bij_bwd N).\nProof.\n  intros [[[[a | ] A] | ] | ]; cbn;\n  unfold red_ax_iso_e_bij_bwd; case: {-}_ /boolP => [Hc | /negP ?] //.\n  - cbnb.\n  - contradict Hc; apply /negP.\n    rewrite !in_set /= other_ax_e. caseb.\n  - case_if; cbnb.\n    by assert (other_ax Hax <> e) by apply other_ax_neq.\n  - contradict Hc; apply /negP.\n    rewrite !in_set /= other_cut_e. caseb.\n  - assert (other_cut Hcut == e = false) as -> by (apply /eqP; apply other_cut_neq).\n    case_if. contradict N; apply /negP.\n    rewrite red_ax_degenerate_None. by apply /negPn/eqP.\n  - contradict Hc; apply /negP.\n    rewrite !in_set. caseb.\n  - by rewrite eq_refl.\nQed.\n\nLemma red_ax_iso_e_bijK' (N : non_degenerate) :\n  cancel (red_ax_iso_e_bij_bwd N) (@red_ax_iso_e_bij_fwd N).\nProof.\n  intro a.\n  unfold red_ax_iso_e_bij_bwd. case: {-}_ /boolP => [ | Ha]; cbnb.\n  case_if.\n  revert Ha; rewrite !in_set !andb_true_r /=\n    => /nandP[/nandP[/negPn/eqP-Ha | /negPn/eqP-Ha] | /nandP[/negPn/eqP-Ha | /negPn/eqP-Ha]].\n  - contradict Ha. by apply no_source_cut.\n  - by assert (a = other_ax Hax) by by apply other_ax_eq.\n  - symmetry; by apply other_cut_eq.\n  - contradict Ha. by apply no_target_ax.\nQed.\n\nDefinition red_ax_iso_e (N : non_degenerate) := {|\n  bij_fwd := _;\n  bij_bwd:= _;\n  bijK:= @red_ax_iso_e_bijK N;\n  bijK':= red_ax_iso_e_bijK' _;\n  |}.\n\nLemma red_ax_iso_ihom (N : non_degenerate) :\n  is_ihom (red_ax_iso_v N) (red_ax_iso_e N) pred0.\nProof.\n  split.\n  - intros [[[[? | ] ?] | ] | ] []; cbnb.\n    + by apply other_ax_e.\n    + by apply other_cut_e.\n  - by intros [[[? ?] | ] | ].\n  - move => [[[[? | ] ?] | ] | ] /=;\n    apply /eqP; cbn; splitb; apply /eqP; trivial.\n    + destruct (p_ax_cut_bis G) as [Hpax _].\n      by revert Hpax => /(_ _ Hax _ (source_in_edges_at_out e)) /eqP-->.\n    + destruct (p_ax_cut_bis G) as [_ Hpcut].\n      by revert Hpcut => /(_ _ Hcut _ (target_in_edges_at_in e)) /eqP-->.\n    + apply p_noleft.\n      rewrite other_cut_e Hcut. caseb.\n    + apply p_noleft.\n      rewrite Hcut. caseb.\nQed.\n\nDefinition red_ax_iso (N : non_degenerate) :=\n  {| iso_v := _; iso_e := _; iso_d := _; iso_ihom := red_ax_iso_ihom N |}.\n\nLemma red_ax_correct_None :\n  uacyclic (@switching _ G) -> non_degenerate.\nProof.\n  intro A.\n  rewrite red_ax_degenerate_None. apply /eqP => N.\n  unfold uacyclic in A.\n  enough (P : supath switching (source e) (source e) (forward e :: backward (other_cut Hcut) :: nil))\n    by by specialize (A _ {| upval := _ ; upvalK := P |}).\n  rewrite /supath /= in_cons in_nil orb_false_r {2}N other_cut_e other_ax_e.\n  splitb. cbn.\n  rewrite other_cut_e Hcut /=.\n  apply /eqP; apply nesym, other_cut_neq.\nQed.\n\nLemma red_ax_correct : correct G -> correct red_ax_graph.\nProof.\n  intro C.\n  assert (N : non_degenerate)\n    by (destruct C; by apply red_ax_correct_None).\n  set C' := iso_correct (red_ax_iso N) C.\n  by apply invert_edge_correct, correct_to_weak, extend_edge_correct_from,\n                                correct_to_weak, extend_edge_correct_from in C'.\nQed.\n\nEnd red_ax.\n\nDefinition red_ax_pn (G : proof_net) (e : edge G) (Hcut : vlabel (target e) = cut)\n  (Hax : vlabel (source e) = ax) : proof_net := {|\n  ps_of := red_ax_ps Hcut Hax;\n  p_correct := @red_ax_correct _ _ _ _ (p_correct G);\n  |}.\n\n\n\n(** * Tensor - cut reduction *)\nDefinition red_tens_graph_1 (G : base_graph) (v : G) (et ep : edge G) : base_graph :=\n  induced (setT :\\ source et :\\ source ep :\\ v).\n\nSection red_tens_proof_structure.\nVariables (G : proof_structure) (v : G) (Hcut : vlabel v = cut) (et ep : edge G)\n  (Het : target et = v) (Hep : target ep = v) (Htens : vlabel (source et) = ⊗)\n  (Hparr : vlabel (source ep) = ⅋).\n\nLemma red_tens_ineq_in :\n  (forall a, source a != v) /\\\n  source (left_tens Htens) != source et /\\\n  source (right_tens Htens) != source et /\\\n  source (left_parr Hparr) != source ep /\\\n  source (right_parr Hparr) != source ep /\\\n  source (left_tens Htens) != source ep /\\\n  source (right_tens Htens) != source ep /\\\n  source (left_parr Hparr) != source et /\\\n  source (right_parr Hparr)!= source et.\nProof.\n  assert (forall a, source a != v).\n  { intro a; apply /eqP. by apply no_source_cut. }\n  splitb; apply /eqP => Hc;\n  [set a := Htens | set a := Htens | set a := Hparr | set a := Hparr\n  |set a := Htens | set a := Htens | set a := Hparr | set a := Hparr];\n  [set a' := et | set a' := et | set a' := ep | set a' := ep\n  |set a' := et | set a' := et | set a' := ep | set a' := ep];\n  [set b := Htens | set b := Htens | set b := Hparr | set b := Hparr\n  |set b := Hparr | set b := Hparr | set b := Htens | set b := Htens];\n  [set b' := et | set b' := et | set b' := ep | set b' := ep\n  |set b' := ep | set b' := ep | set b' := et | set b' := et];\n  [set f := left_tens (G := G) | set f := right_tens (G := G) | set f := left_parr (G := G) | set f := right_parr (G := G)\n  |set f := left_tens (G := G) | set f := right_tens (G := G) | set f := left_parr (G := G) | set f := right_parr (G := G)];\n  [set g := ccl_tens (G := G) | set g := ccl_tens (G := G) | set g := ccl_parr (G := G) | set g := ccl_parr (G := G)\n  |set g := ccl_parr (G := G) | set g := ccl_parr (G := G) | set g := ccl_tens (G := G) | set g := ccl_tens (G := G)].\n  all: assert (f _ a = g _ b /\\ b' = g _ b) as [Hc0 Hc1] by (split; apply ccl_eq; caseb).\n  all: assert (Hc2 : source a' = v) by\n    (replace v with (target b'); rewrite Hc1 -Hc0 ?left_e ?right_e; caseb).\n  all: contradict Hcut; by rewrite -Hc2 ?Htens ?Hparr.\nQed.\n\nLemma red_tens_ineq_if :\n  source et <> source ep /\\ source ep <> source et /\\\n  left_tens Htens <> right_tens Htens /\\ right_tens Htens <> left_tens Htens /\\\n  left_parr Hparr <> right_parr Hparr /\\ right_parr Hparr <> left_parr Hparr /\\\n  left_tens Htens <> left_parr Hparr /\\ left_parr Hparr <> left_tens Htens /\\\n  left_tens Htens <> right_parr Hparr /\\ right_parr Hparr <> left_tens Htens /\\\n  left_parr Hparr <> right_tens Htens /\\ right_tens Htens <> left_parr Hparr /\\\n  right_tens Htens <> right_parr Hparr /\\ right_parr Hparr <> right_tens Htens /\\\n  left_tens Htens <> ep /\\ left_tens Htens <> et /\\\n  right_tens Htens <> ep /\\ right_tens Htens <> et /\\\n  left_parr Hparr <> ep /\\ left_parr Hparr <> et /\\\n  right_parr Hparr <> ep /\\ right_parr Hparr <> et.\nProof.\n  assert (Hf : source et <> source ep) by\n    (intro Hf; clear - Htens Hparr Hf; contradict Htens; by rewrite Hf Hparr).\n  assert (right_tens Htens <> left_tens Htens /\\ right_parr Hparr <> left_parr Hparr) as [? ?]\n    by (split; apply nesym, left_neq_right).\n  assert (left_tens Htens <> left_parr Hparr /\\ left_tens Htens <> right_parr Hparr /\\\n    right_tens Htens <> left_parr Hparr /\\ right_tens Htens <> right_parr Hparr) as [? [? [? ?]]].\n  { splitb; intro Hc; contradict Hf.\n    - rewrite -(left_e (or_introl Htens)) -(left_e (or_intror Hparr)). by f_equal.\n    - rewrite -(left_e (or_introl Htens)) -(right_e (or_intror Hparr)). by f_equal.\n    - rewrite -(right_e (or_introl Htens)) -(left_e (or_intror Hparr)). by f_equal.\n    - rewrite -(right_e (or_introl Htens)) -(right_e (or_intror Hparr)). by f_equal. }\n  assert (left_tens Htens <> ep /\\ left_tens Htens <> et /\\\n    right_tens Htens <> ep /\\ right_tens Htens <> et /\\\n    left_parr Hparr <> ep /\\ left_parr Hparr <> et /\\\n    right_parr Hparr <> ep /\\ right_parr Hparr <> et) as [? [? [? [? [? [? [? ?]]]]]]].\n  { splitb => Hc; subst; contradict Hcut.\n    all: rewrite -1?Hc ?left_e ?right_e ?Htens ?Hparr; caseb.\n    all: rewrite -1?Hep -1?Hc ?left_e ?right_e ?Htens ?Hparr; caseb. }\n  splitb; by apply nesym.\nQed. (* TODO Tout mettre en double ? Rien ? *)\n\nLemma red_tens_in :\n  source (left_tens Htens) \\in setT :\\ source et :\\ source ep :\\ v /\\\n  source (right_tens Htens) \\in setT :\\ source et :\\ source ep :\\ v /\\\n  source (left_parr Hparr) \\in setT :\\ source et :\\ source ep :\\ v /\\\n  source (right_parr Hparr) \\in setT :\\ source et :\\ source ep :\\ v.\nProof.\n  destruct red_tens_ineq_in as [? [? [? [? [? [? [? [? ?]]]]]]]].\n  rewrite !in_set. splitb.\nQed.\nLemma red_tens_in_slt :\n  source (left_tens Htens) \\in setT :\\ source et :\\ source ep :\\ v.\nProof. by destruct red_tens_in as [? [? [? ?]]]. Qed.\nLemma red_tens_in_srt :\n  source (right_tens Htens) \\in setT :\\ source et :\\ source ep :\\ v.\nProof. by destruct red_tens_in as [? [? [? ?]]]. Qed.\nLemma red_tens_in_slp :\n  source (left_parr Hparr) \\in setT :\\ source et :\\ source ep :\\ v.\nProof. by destruct red_tens_in as [? [? [? ?]]]. Qed.\nLemma red_tens_in_srp :\n  source (right_parr Hparr) \\in setT :\\ source et :\\ source ep :\\ v.\nProof. by destruct red_tens_in as [? [? [? ?]]]. Qed.\n\nDefinition red_tens_graph :=\n  (red_tens_graph_1 v et ep) ∔ cut ∔ cut\n    ∔ [inl (inl (Sub (source (left_tens Htens)) red_tens_in_slt)) ,\n        (flabel (left_tens Htens), true) , inl (inr tt)]\n    ∔ [inl (inl (Sub (source (right_tens Htens)) red_tens_in_srt)) ,\n        (flabel (right_tens Htens), true) , inr tt]\n    ∔ [inl (inl (Sub (source (left_parr Hparr)) red_tens_in_slp)) ,\n        (flabel (left_parr Hparr), true) , inr tt]\n    ∔ [inl (inl (Sub (source (right_parr Hparr)) red_tens_in_srp)) ,\n        (flabel (right_parr Hparr), true) , inl (inr tt)].\n\nLemma red_tens_cut_set : edges_at_in v = [set et; ep].\nProof.\n  subst v.\n  rewrite other_cut_set.\n  replace (other_cut Hcut) with ep; trivial.\n  apply other_cut_eq. splitb.\n  intros ?; subst; contradict Hparr.\n  by rewrite Htens.\nQed.\n\nLemma red_tens_removed :\n  edge_set (setT :\\ source et :\\ source ep :\\ v) =\n  setT :\\ left_tens Htens :\\ left_parr Hparr :\\ right_tens Htens :\\ right_parr Hparr :\\ et :\\ ep.\nProof.\n  apply /setP => a.\n  rewrite !in_set !andb_true_r.\n  destruct red_tens_ineq_in as [-> _]. simpl.\n  destruct (eq_comparable a et) as [? | Aet];\n  [ | destruct (eq_comparable a ep) as [? | Aep]];\n  [ | | destruct (eq_comparable a (left_tens Htens))];\n  [ | | | destruct (eq_comparable a (right_tens Htens))];\n  [ | | | | destruct (eq_comparable a (left_parr Hparr))];\n  [ | | | | | destruct (eq_comparable a (right_parr Hparr))];\n  try by (subst a; rewrite ?left_e ?right_e !eq_refl ?andb_false_r).\n  assert (a != ep /\\ a != et /\\ a != left_tens Htens /\\ a != right_tens Htens /\\\n    a != left_parr Hparr /\\ a != right_parr Hparr) as [-> [-> [-> [-> [-> ->]]]]]\n    by by splitb; apply /eqP.\n  simpl.\n  assert (Hin := target_in_edges_at_in a).\n  splitb; apply /eqP => Hc.\n  - contradict Aep. by apply one_source_parr.\n  - contradict Aet. by apply one_source_tens.\n  - contradict Hin; apply /negP.\n    rewrite Hc red_tens_cut_set // !in_set.\n    splitb; by apply /eqP.\n  - contradict Hin; apply /negP.\n    rewrite Hc (right_set (or_intror Hparr)) ?in_set.\n    splitb; by apply /eqP.\n  - contradict Hin; apply /negP.\n    rewrite Hc (right_set (or_introl Htens)) ?in_set.\n    splitb; by apply /eqP.\nQed.\n\nLemma red_tens_c_stay e :\n  vlabel (target e) = c -> e \\in edge_set (setT :\\ source et :\\ source ep :\\ v).\nProof.\n  intro E.\n  rewrite red_tens_removed // !in_set.\n  splitb; apply /eqP => ?; subst e;\n  contradict E; by rewrite ?Het ?Hep ?Hcut ?left_e ?right_e ?Htens ?Hparr.\nQed.\n\nLemma red_tens_consistent_order :\n  all (pred_of_set (edge_set (setT :\\ source et :\\ source ep :\\ v))) (order G).\nProof. apply /allP => ? ?. by apply red_tens_c_stay, p_order. Qed.\n\nDefinition red_tens_order : seq (edge red_tens_graph) :=\n  [seq Some (Some (Some (Some (inl (inl u))))) | u <- sval (all_sigP red_tens_consistent_order)].\n\nDefinition red_tens_graph_data : graph_data := {|\n  graph_of := red_tens_graph;\n  order := red_tens_order;\n  |}.\n\nDefinition red_tens_transport : edge red_tens_graph -> edge G :=\n  fun a => match a with\n  | None                                              => right_parr Hparr\n  | Some None                                         => left_parr Hparr\n  | Some (Some None)                                  => right_tens Htens\n  | Some (Some (Some None))                           => left_tens Htens\n  | Some (Some (Some (Some (inr a))))                 => match a with end\n  | Some (Some (Some (Some (inl (inl (exist a _)))))) => a\n  | Some (Some (Some (Some (inl (inr a)))))           => match a with end\n  end.\n\nLemma red_tens_transport_inj : injective red_tens_transport.\nProof.\n  unfold red_tens_transport.\n  destruct red_tens_ineq_if as [? [? [? [? [? [? [? [? [? [? [? [? [? [? _]]]]]]]]]]]]]].\n  move => [[[[[[[a A] | []] | []] | ] | ] | ] | ] [[[[[[[b B] | []] | []] | ] | ] | ] | ]\n    /eqP; cbn => /eqP-?; try subst a; try subst b; cbnb.\n  all: (contradict A || contradict B); apply /negP.\n  all: rewrite red_tens_removed !in_set; caseb.\nQed.\n\nLemma red_tens_transport_edges (b : bool) (u : G) (Hu : u \\in (setT :\\ source et :\\ source ep :\\ v)) :\n  edges_at_outin b u = [set red_tens_transport a | a in edges_at_outin b (inl (inl (Sub u Hu)) : red_tens_graph)].\nProof.\n  apply /setP => a.\n  rewrite Imset.imsetE !in_set.\n  symmetry; apply /imageP; case_if.\n  - assert (a <> et /\\ a <> ep) as [? ?].\n    { split; intros ?; subst; contradict Hu; apply /negP.\n      all: rewrite !in_set.\n      all: destruct b; rewrite ?Hep; caseb. }\n    destruct (a \\in edge_set (setT :\\ source et :\\ source ep :\\ v)) eqn:Ina.\n    + exists (Some (Some (Some (Some (inl (inl (Sub a Ina))))))); rewrite // !in_set; cbnb.\n    + rewrite red_tens_removed // !in_set andb_true_r in Ina.\n      revert Ina; introb.\n      all: destruct b; first by (contradict Hu; apply /negP; rewrite !in_set ?left_e ?right_e; caseb).\n      * exists None; rewrite // !in_set; cbnb.\n      * exists (Some (Some None)); rewrite // !in_set; cbnb.\n      * exists (Some None); rewrite // !in_set; cbnb.\n      * exists (Some (Some (Some None))); rewrite // !in_set; cbnb.\n  - intros [[[[[[[[? ?] | []] | []] | ] | ] | ] | ] Hin Heq]; cbn in Heq; subst a.\n    all: contradict Hin; apply /negP.\n    all: rewrite !in_set.\n    all: by destruct b; cbnb; apply /eqP.\nQed.\n\nLemma red_tens_transport_flabel (a : edge red_tens_graph) :\n  flabel (red_tens_transport a) = flabel a.\nProof. by destruct a as [[[[[[[? ?] | []] | []] | ] | ] | ] | ]. Qed.\n\nLemma red_tens_transport_llabel (a : edge red_tens_graph) w W :\n  a \\in edges_at_in (inl (inl (Sub w W)) : red_tens_graph) ->\n  llabel (red_tens_transport a) = llabel a.\nProof. destruct a as [[[[[[[? ?] | []] | []] | ] | ] | ] | ]; by rewrite // in_set. Qed.\n\nLemma red_tens_edges_at_new :\n  edges_at_in (inl (inr tt) : red_tens_graph) = [set Some (Some (Some None)); None] /\\\n  edges_at_out (inl (inr tt) : red_tens_graph) = set0 /\\\n  edges_at_in (inr tt : red_tens_graph) = [set Some (Some None); Some None] /\\\n  edges_at_out (inr tt : red_tens_graph) = set0.\nProof. splitb; apply /setP; move => [[[[[[[? ?] | []] | []] | ] | ] | ] | ]; by rewrite !in_set. Qed.\n\n\nLemma red_tens_p_deg : proper_degree red_tens_graph.\nProof.\n  destruct red_tens_edges_at_new as [Lin [Lout [Rin Rout]]].\n  move => b [[[u Hu] | []] | []] /=.\n  - rewrite -(p_deg b u) (red_tens_transport_edges _ Hu) card_imset //.\n    apply red_tens_transport_inj.\n  - destruct b; by rewrite ?Lin ?Lout ?cards2 ?cards0.\n  - destruct b; by rewrite ?Rin ?Rout ?cards2 ?cards0.\nQed.\n\nLemma red_tens_forms :\n  flabel (right_tens Htens)^ = flabel (left_parr Hparr)  /\\\n  flabel (left_tens Htens)^ = flabel (right_parr Hparr).\nProof.\n  destruct (p_ax_cut_bis G) as [_ Hpcut]. (* Get information about the removed cut *)\n  assert (Hvet : et \\in edges_at_in v) by by rewrite in_set Het.\n  revert Hpcut => /(_ _ Hcut _ Hvet) /eqP-Hpcut.\n  assert (Ht := p_tens_bis Htens).\n  assert (Hp := p_parr_bis Hparr).\n  assert (et = ccl_tens Htens /\\ ep = ccl_parr Hparr) as [Hct Hcp] by (split; apply ccl_eq; caseb).\n  rewrite -Hct in Ht.\n  rewrite -Hcp in Hp.\n  assert (Hoep : ep = other (pre_proper_cut Hcut) Hvet).\n  { apply other_eq.\n    - by rewrite in_set Hep.\n    - intro Hc; clear - Hc Htens Hparr; contradict Hparr.\n      by rewrite Hc Htens. }\n  rewrite -Hoep Ht Hp {Hoep Hvet Hct Hcp Ht Hp} in Hpcut.\n  by inversion Hpcut.\nQed.\n\nLemma red_tens_p_ax_cut : proper_ax_cut red_tens_graph.\nProof.\n  unfold proper_ax_cut.\n  destruct red_tens_forms as [Hl Hr].\n  move => b [[[w W] | []] | []] /= R.\n  - destruct (p_ax_cut R) as [el [er H]].\n    revert H; rewrite (red_tens_transport_edges _ W) Imset.imsetE 2!in_set.\n    move => [/imageP[El ? ?] [/imageP[Er ? ?] Heq]]. subst el er.\n    rewrite !red_tens_transport_flabel in Heq.\n    by exists El, Er.\n  - destruct b; [ | by contradict R].\n    exists None, (Some (Some (Some None))).\n    by rewrite !in_set Hr.\n  - destruct b; [ | by contradict R].\n    exists (Some None), (Some (Some None)).\n    by rewrite !in_set Hl.\nQed.\n\nLemma red_tens_p_tens_parr : proper_tens_parr red_tens_graph.\nProof.\n  unfold proper_tens_parr.\n  intros b [[[w W] | []] | []] Hl; cbn in Hl.\n  all: try (destruct b; by contradict Hl).\n  destruct (p_tens_parr Hl) as [el [er [ec H]]].\n  revert H; rewrite !(red_tens_transport_edges _ W) Imset.imsetE !in_set.\n  move => [/imageP[El Elin ?] [Hll [/imageP[Er Erin ?] [Hrl [/imageP[Ec Ecin ?] Heq]]]]].\n  subst el er ec.\n  rewrite (red_tens_transport_llabel Elin) in Hll.\n  rewrite (red_tens_transport_llabel Erin) in Hrl.\n  rewrite !red_tens_transport_flabel in Heq.\n  by exists El, Er, Ec.\nQed.\n\nLemma red_tens_p_noleft : proper_noleft red_tens_graph.\nProof. move => [[[[[[? | []] | []] | ] | ] | ] | ] ? //. by apply p_noleft. Qed.\n\nLemma red_tens_p_order : proper_order red_tens_graph_data.\nProof.\n  unfold proper_order, red_tens_graph_data, red_tens_order; cbn.\n  destruct (all_sigP _) as [l L]. split.\n  - intros [[[[[[f | []] | []] | ] | ] | ] | ]; cbn.\n    { rewrite mem_map; [ | repeat (apply inj_comp; trivial)].\n      rewrite in_seq_sig -L.\n      apply p_order. }\n    all: split; move => H //.\n    all: contradict H; apply /negP; clear.\n    all: induction l as [ | ? ? IH]; first by trivial.\n    all: by rewrite map_cons in_cons IH.\n  - rewrite map_inj_uniq; [ | repeat (apply inj_comp; trivial)].\n    rewrite uniq_seq_sig -L.\n    apply p_order.\nQed.\n\nDefinition red_tens_ps : proof_structure := {|\n  graph_data_of := red_tens_graph_data;\n  p_deg := red_tens_p_deg;\n  p_ax_cut := red_tens_p_ax_cut;\n  p_tens_parr := red_tens_p_tens_parr;\n  p_noleft := red_tens_p_noleft;\n  p_order := red_tens_p_order;\n  |}.\n\n\n(** Sequent of an tensor - cut reduction *)\nLemma red_tens_sequent : sequent red_tens_graph_data = sequent G.\nProof.\n  transitivity [seq flabel (red_tens_transport u) | u <- red_tens_order].\n  { apply eq_map => ?. by rewrite red_tens_transport_flabel. }\n  rewrite /red_tens_order -map_comp.\n  destruct (all_sigP _) as [l L].\n  by rewrite /sequent [in RHS]L -map_comp.\nQed.\n\n(** Decreasing number of vertices *)\nLemma red_tens_nb : #|G| = #|red_tens_graph| + 1.\nProof.\n  rewrite !card_add_vertex -card_induced_all [in LHS](card_inducedD1 _ (source et))\n    [in LHS](card_inducedD1 _ (source ep)) [in LHS](card_inducedD1 _ v) !in_set.\n  elim red_tens_ineq_if => _ [/eqP--> _].\n  elim red_tens_ineq_in => V _.\n  rewrite eq_sym V eq_sym V /=. lia.\nQed.\n\n\n(** Correctness *)\nLemma red_tens_ineq_switching :\n  switching et <> switching ep /\\\n  switching (left_tens Htens) <> switching (right_tens Htens) /\\\n  switching (left_tens Htens) <> switching et /\\\n  switching (left_tens Htens) <> switching ep /\\\n  switching (left_tens Htens) <> switching (left_parr Hparr) /\\\n  switching (left_tens Htens) <> switching (right_parr Hparr) /\\\n  switching (right_tens Htens) <> switching et /\\\n  switching (right_tens Htens) <> switching ep /\\\n  switching (right_tens Htens) <> switching (left_parr Hparr) /\\\n  switching (right_tens Htens) <> switching (right_parr Hparr) /\\\n  switching et <> switching (left_parr Hparr) /\\\n  switching ep <> switching (left_parr Hparr) /\\\n  switching et <> switching (right_parr Hparr) /\\\n  switching ep <> switching (right_parr Hparr).\nProof.\n  split.\n  { cbnb. rewrite Het Hep Hcut /=. cbnb. intros ?; subst.\n    contradict Htens. by rewrite Hparr. }\n  split.\n  { cbnb. rewrite left_e ?right_e !Htens /=; caseb. cbnb.\n    apply left_neq_right. }\n  splitb => Hs.\n  all: apply switching_eq in Hs.\n  all: rewrite ?left_e ?right_e in Hs; caseb.\n  all: enough (vlabel v <> cut) by by [].\n  all: try (rewrite -Het Hs).\n  all: try (rewrite -Het -Hs).\n  all: try (rewrite -Hep Hs).\n  all: try (rewrite -Hep -Hs).\n  all: try rewrite ?Htens ?Hparr //.\n  all: contradict Htens; by rewrite Hs ?Het ?Hep ?Hcut ?Hparr.\nQed.\n\nLemma red_tens_switching a f A F :\n  switching a = switching f ->\n  switching (Some (Some (Some (Some (inl (inl (Sub a A)))))) : edge red_tens_graph) =\n  switching (Some (Some (Some (Some (inl (inl (Sub f F)))))) : edge red_tens_graph).\nProof. move => /eqP. unfold switching; case_if; cbnb. Qed.\n\nDefinition red_tens_upath_bwd (p : @upath _ _ red_tens_graph) : @upath _ _ G :=\n  map (fun a => (red_tens_transport a.1, a.2)) p.\n\nLemma red_tens_upath_bwd_in (p : @upath _ _ red_tens_graph) :\n  [forall b, (None, b) \\notin p] -> [forall b, (Some None, b) \\notin p] ->\n  [forall b, (Some (Some None), b) \\notin p] -> [forall b, (Some (Some (Some None)), b) \\notin p] ->\n  forall a b, (a, b) \\in red_tens_upath_bwd p ->\n  exists A, (Some (Some (Some (Some (inl (inl (Sub a A)))))), b) \\in p.\nProof.\n  induction p as [ | f p IH]; try by [].\n  rewrite !forall_notincons => /andP[n N] /andP[sn SN] /andP[ssn SSN] /andP[sssn SSSN] a b.\n  destruct f as ([[[[[[[f F] | []] | []] | ] | ] | ] | ], c);\n  [ | by exfalso; revert sssn => /forallP /(_ c) /eqP\n    | by exfalso; revert ssn => /forallP /(_ c) /eqP\n    | by exfalso; revert sn => /forallP /(_ c) /eqP\n    | by exfalso; revert n => /forallP /(_ c) /eqP].\n  rewrite /= !in_cons. cbnb. introb.\n  - exists F. caseb.\n  - elim: (IH N SN SSN SSSN a b _) => // A In.\n    exists A. rewrite in_cons In. caseb.\nQed.\n\nLemma red_tens_upath_bwd_nin_switching (p : @upath _ _ red_tens_graph) :\n  [forall b, (None, b) \\notin p] -> [forall b, (Some None, b) \\notin p] ->\n  [forall b, (Some (Some None), b) \\notin p] -> [forall b, (Some (Some (Some None)), b) \\notin p] ->\n  switching (left_tens Htens) \\notin [seq switching a.1 | a <- red_tens_upath_bwd p] /\\\n  switching (right_tens Htens) \\notin [seq switching a.1 | a <- red_tens_upath_bwd p] /\\\n  switching (left_parr Hparr) \\notin [seq switching a.1 | a <- red_tens_upath_bwd p] /\\\n  switching (right_parr Hparr) \\notin [seq switching a.1 | a <- red_tens_upath_bwd p] /\\\n  switching et \\notin [seq switching a.1 | a <- red_tens_upath_bwd p] /\\\n  switching ep \\notin [seq switching a.1 | a <- red_tens_upath_bwd p].\nProof.\n  intros. splitb.\n  all: apply /mapP; move => [[a b] In S].\n  all: apply red_tens_upath_bwd_in in In; trivial; destruct In as [A In].\n  all: apply switching_eq in S; rewrite ?left_e ?right_e /= in S.\n  all: clear - A S Het Hep; contradict A; apply /negP.\n  all: rewrite !in_set -S ?Hep ?Het; caseb.\nQed.\n\nLemma red_tens_upath_Some (p : @upath _ _ red_tens_graph) (u w : red_tens_graph) :\n  p <> nil -> supath switching u w p ->\n  [forall b, (None, b) \\notin p] -> [forall b, (Some None, b) \\notin p] ->\n  [forall b, (Some (Some None), b) \\notin p] -> [forall b, (Some (Some (Some None)), b) \\notin p] ->\n  exists u' U' w' W', u = inl (inl (Sub u' U')) /\\ w = inl (inl (Sub w' W')) /\\\n  supath switching u' w' (red_tens_upath_bwd p).\nProof.\n  revert u w. induction p as [ | a p IH] => // u w _ P.\n  rewrite !forall_notincons => /andP[n N] /andP[sn SN] /andP[ssn SSN] /andP[sssn SSSN].\n  destruct a as ([[[[[[[a A] | []] | []] | ] | ] | ] | ], b);\n  [ | by exfalso; revert sssn => /forallP /(_ b) /eqP\n    | by exfalso; revert ssn => /forallP /(_ b) /eqP\n    | by exfalso; revert sn => /forallP /(_ b) /eqP\n    | by exfalso; revert n => /forallP /(_ b) /eqP].\n  revert P; unfold supath at 1; cbn; rewrite in_cons\n    => /andP[/andP[/andP[/eqP ? W] /andP[U0 U1]] /norP[_ N']]; subst u.\n  rewrite SubK'. rewrite SubK' in W.\n  assert (P : supath switching (inl (inl (Sub (endpoint b a) (induced_proof b A))) :\n    red_tens_graph) w p) by splitb.\n  destruct p as [ | f p].\n  { exists (endpoint (~~ b) a), (induced_proof (~~ b) A),\n      (endpoint b a), (induced_proof b A).\n    revert W; cbn => /eqP ?; subst w.\n    splitb. }\n  assert (Hr : f :: p <> [::]) by by [].\n  destruct (IH _ _ Hr P N SN SSN SSSN) as [x [X [y [Y [Hx [Hy P']]]]]].\n  clear Hr IH.\n  revert Hx => /eqP Hx; cbn in Hx; simpl in Hx; revert Hx => /eqP ?. subst w x.\n  exists (endpoint (~~ b) a), (induced_proof (~~ b) A), y, Y.\n  revert P'.\n  remember (f :: p) as p'.\n  unfold supath; cbn => /andP[/andP[W' U'] N''].\n  splitb.\n  revert U0; apply contra => /mapP [[d db] In Seq]; apply /mapP.\n  destruct (red_tens_upath_bwd_in N SN SSN SSSN In) as [D ?].\n  exists (Some (Some (Some (Some (inl (inl (Sub d D)))))), db); trivial.\n  by apply red_tens_switching.\nQed.\n\nLemma red_tens_uacyclic_nocut :\n  uacyclic (@switching _ G) ->\n  forall (p : @upath _ _ red_tens_graph) (u : red_tens_graph),\n  supath switching u u p ->\n  [forall b, (None, b) \\notin p] -> [forall b, (Some None, b) \\notin p] ->\n  [forall b, (Some (Some None), b) \\notin p] -> [forall b, (Some (Some (Some None)), b) \\notin p] ->\n  p = [::].\nProof.\n  move => A p u P N SN SSN SSSN.\n  destruct p as [ | a p]; trivial.\n  assert (NN : a :: p <> [::]) by by [].\n  destruct (red_tens_upath_Some NN P N SN SSN SSSN) as [? [? [u' [? [? [Hu'' P']]]]]]. subst u.\n  revert Hu'' => /eqP; cbnb => /eqP ?. subst u'.\n  specialize (A _ {| upval := _ ; upvalK := P' |}).\n  contradict A; cbnb.\nQed.\n\nLemma red_tens_upath_fN p u U w W :\n  supath switching (inl (inl (Sub u U)) : red_tens_graph) (inl (inl (Sub w W))) p ->\n  (forward None \\in p -> exists l r, p = l ++ forward None :: backward (Some (Some (Some None))) :: r) /\\\n  (forward (Some None) \\in p -> exists l r, p = l ++ forward (Some None) :: backward (Some (Some None)) :: r) /\\\n  (forward (Some (Some None)) \\in p -> exists l r, p = l ++ forward (Some (Some None)) :: backward (Some None) :: r) /\\\n  (forward (Some (Some (Some None))) \\in p -> exists l r, p = l ++ forward (Some (Some (Some None))) :: backward None :: r).\nProof.\n  move => P; splitb => In.\n  all: destruct (in_elt_sub In) as [n N].\n  all: set l := take n p; set r := drop n.+1 p.\n  all: exists l, (behead r); f_equal; f_equal.\n  all: rewrite N -/l -/r; rewrite N -/l -/r in P.\n  all: destruct (supath_subKK P) as [_ R]; clear - R.\n  all: revert R; rewrite /supath /= in_cons => /andP[/andP[/andP[_ ?] /andP[? _]] _].\n  all: by destruct r as [ | ([[[[[[[? ?] | []] | []] | ] | ] | ] | ], []) ?].\nQed.\n\nLemma red_tens_upath_bN p u U w W :\n  supath switching (inl (inl (Sub u U)) : red_tens_graph) (inl (inl (Sub w W))) p ->\n  (backward None \\in p -> exists l r, p = l ++ forward (Some (Some (Some None))) :: backward None :: r) /\\\n  (backward (Some None) \\in p -> exists l r, p = l ++ forward (Some (Some None)) :: backward (Some None) :: r) /\\\n  (backward (Some (Some None)) \\in p -> exists l r, p = l ++ forward (Some None) :: backward (Some (Some None)) :: r) /\\\n  (backward (Some (Some (Some None))) \\in p -> exists l r, p = l ++ forward None :: backward (Some (Some (Some None))) :: r).\nProof.\n  move => P.\n  destruct (red_tens_upath_fN (supath_revK P)) as [N [SN [SSN SSSN]]].\n  splitb => In; [set H := N | set H := SN | set H := SSN | set H := SSSN].\n  1: assert (In' : forward None \\in upath_rev p) by by rewrite (upath_rev_in p).\n  2: assert (In' : forward (Some None) \\in upath_rev p) by by rewrite (upath_rev_in p).\n  3: assert (In' : forward (Some (Some None)) \\in upath_rev p) by by rewrite (upath_rev_in p).\n  4: assert (In' : forward (Some (Some (Some None))) \\in upath_rev p) by by rewrite (upath_rev_in p).\n  all: destruct (H In') as [l [r Hp]].\n  all: exists (upath_rev (r : @upath _ _ red_tens_graph)), (upath_rev (l : @upath _ _ red_tens_graph)).\n  all: by rewrite -(upath_rev_inv p) Hp upath_rev_cat /= -!cats1 -!catA.\nQed.\n\nLemma red_tens_NSSSN p u U w W :\n  supath switching (inl (inl (Sub u U)) : red_tens_graph) (inl (inl (Sub w W))) p ->\n  [forall b, (None, b) \\notin p] -> [forall b, (Some (Some (Some None)), b) \\notin p].\nProof.\n  intro P.\n  enough (Hd : forall b, (Some (Some (Some None)), b) \\in p -> (None, ~~b) \\in p).\n  { move => /forallP H; apply /forallP => b; revert H => /(_ (~~b)). apply contra, Hd. }\n  move => [] In.\n  - destruct (red_tens_upath_fN P) as [_ [_ [_ H]]]. specialize (H In).\n    destruct H as [l [r ?]]; subst p; clear.\n    rewrite mem_cat !in_cons. caseb.\n  - destruct (red_tens_upath_bN P) as [_ [_ [_ H]]]. specialize (H In).\n    destruct H as [l [r ?]]; subst p; clear.\n    rewrite mem_cat !in_cons. caseb.\nQed.\n\nLemma red_tens_SNSSN p u U w W :\n  supath switching (inl (inl (Sub u U)) : red_tens_graph) (inl (inl (Sub w W))) p ->\n  [forall b, (Some None, b) \\notin p] -> [forall b, (Some (Some None), b) \\notin p].\nProof.\n  intro P.\n  enough (Hd : forall b, (Some (Some None), b) \\in p -> (Some None, ~~b) \\in p).\n  { move => /forallP H; apply /forallP => b; revert H => /(_ (~~b)). apply contra, Hd. }\n  move => [] In.\n  - destruct (red_tens_upath_fN P) as [_ [_ [H _]]]. specialize (H In).\n    destruct H as [l [r ?]]; subst p; clear.\n    rewrite mem_cat !in_cons. caseb.\n  - destruct (red_tens_upath_bN P) as [_ [_ [H _]]]. specialize (H In).\n    destruct H as [l [r ?]]; subst p; clear.\n    rewrite mem_cat !in_cons. caseb.\nQed.\n\nLemma red_tens_upath_SomeNoneNot_ff :\n  uacyclic (@switching _ G) ->\n  forall p u U,\n  supath switching (inl (inl (Sub u U)) : red_tens_graph) (inl (inl (Sub u U))) p ->\n  forward (Some None) \\in p ->\n  forward None \\notin p.\nProof.\n  move => A p u U P SN; apply /negP => N.\n  destruct (red_tens_upath_fN P) as [_ [HSN [_ _]]]. specialize (HSN SN).\n  destruct HSN as [l [r ?]]; subst p.\n  clear SN.\n  revert N; rewrite mem_cat !in_cons /= => /orP N.\n  wlog : u U l r P N / forward None \\in r.\n  { destruct N as [N | N].\n    2:{ move => /(_ _ _ _ _ P) H. apply H; caseb. }\n    destruct (supath_subKK P) as [L _].\n    assert (Hr : upath_target (inl (inl (Sub u U)) : red_tens_graph) l =\n      source (Some None : edge red_tens_graph)).\n    { revert P => /andP[/andP[Wl _] _].\n      by rewrite (uwalk_sub_middle Wl). }\n    rewrite Hr {Hr} /= in L.\n    destruct (red_tens_upath_fN L) as [HN [_ [_ _]]]. specialize (HN N).\n    destruct HN as [g [m ?]]; subst l.\n    assert (P' := supath_turnsK P).\n    assert (Hr : [:: forward (Some None), backward (Some (Some None)) & r] ++ g ++\n      [:: forward None, backward (Some (Some (Some None))) & m] = [::] ++\n      [:: forward (Some None), backward (Some (Some None)) & r ++ g ++\n      [:: forward None, backward (Some (Some (Some None))) & m]]) by by [].\n    rewrite Hr {Hr} in P'.\n    move => /(_ _ _ _ _ P') H. apply H; rewrite !mem_cat !in_cons; caseb. }\n  clear N => N.\n  replace (l ++ [:: forward (Some None), backward (Some (Some None)) & r]) with\n    ((l ++ [:: forward (Some None); backward (Some (Some None))]) ++ r) in P by by rewrite -catA.\n  destruct (supath_subKK P) as [_ R].\n  assert (Hr : upath_source (inl (inl (Sub u U)) : red_tens_graph) r =\n    source (Some (Some None) : edge red_tens_graph)).\n  { revert P => /andP[/andP[W _] _].\n    by rewrite -(uwalk_sub_middle W) upath_target_cat. }\n  rewrite Hr {Hr} /= in R.\n  destruct (red_tens_upath_fN R) as [HN [_ [_ _]]]. specialize (HN N).\n  destruct HN as [m [d ?]]; subst r.\n  clear N R.\n  rewrite -catA in P.\n  assert (SN : [forall b, (Some None, b) \\notin m]).\n  { apply /forallP => b.\n    assert (M := supath_nin b P).\n    by revert M; repeat (rewrite ?mem_cat ?in_cons /=); introb. }\n  assert (N : [forall b, (None, b) \\notin m]).\n  { apply /forallP => b.\n    rewrite !catA in P.\n    assert (M := supath_nin b P).\n    by revert M; repeat (rewrite ?mem_cat ?in_cons /=); introb. }\n  rewrite catA in P.\n  assert (M := supath_subK P).\n  rewrite upath_target_cat /= in M.\n  assert (SSN := red_tens_SNSSN M SN).\n  assert (SSSN := red_tens_NSSSN M N).\n  destruct red_tens_ineq_switching as [? [_ [_ [_ [_ [_ [? [? [_ [? [_ [_ [? ?]]]]]]]]]]]]].\n  assert (NN : m <> nil).\n  { intros ?; subst m.\n    revert M; rewrite /supath; cbnb => /andP[/andP[/eqP-Hc _] _].\n    enough (Pc : supath switching (source (right_tens Htens)) (source (right_parr Hparr))\n      (forward (right_tens Htens) :: forward et :: backward ep :: backward (right_parr Hparr) :: nil)).\n    { rewrite Hc in Pc.\n      specialize (A _ {| upval := _ ; upvalK := Pc |}).\n      contradict A; cbnb. }\n    rewrite /supath /= !in_cons.\n    repeat (apply /andP; split); repeat (apply /norP; split); trivial; apply /eqP;\n    rewrite // ?right_e ?Het ?Hep; caseb. }\n  destruct (red_tens_upath_Some NN M N SN SSN SSSN) as [x [X [y [Y [Hx [Hy Pxy]]]]]].\n  revert Hx => /eqP; cbnb => /eqP ?; subst x.\n  revert Hy => /eqP; cbnb => /eqP ?; subst y.\n  enough (Pf : supath switching (source (right_parr Hparr)) (source (right_parr Hparr))\n    (forward (right_parr Hparr) :: forward ep :: backward et :: backward (right_tens Htens) ::\n    (red_tens_upath_bwd m))).\n  { specialize (A _ {| upval := _ ; upvalK := Pf |}).\n    contradict A; cbnb. }\n  revert Pxy => /andP[/andP[Wn Un] ?].\n  rewrite /supath /= !in_cons.\n  destruct (red_tens_upath_bwd_nin_switching N SN SSN SSSN) as [? [? [? [? [? ?]]]]].\n  splitb; simpl; try (by apply /eqP; apply nesym); rewrite ?right_e ?Het ?Hep; caseb.\nQed.\n\nLemma red_tens_upath_SomeNoneNot_fb  :\n  uacyclic (@switching _ G) ->\n  forall p u U,\n  supath switching (inl (inl (Sub u U)) : red_tens_graph) (inl (inl (Sub u U))) p ->\n  forward (Some None) \\in p ->\n  backward None \\notin p.\nProof.\n  move => A p u U P SN; apply /negP => N.\n  destruct (red_tens_upath_fN P) as [_ [HSN [_ _]]]. specialize (HSN SN).\n  destruct HSN as [l [r ?]]; subst p.\n  clear SN.\n  revert N; rewrite mem_cat !in_cons /= => /orP N.\n  wlog : u U l r P N / backward None \\in r.\n  { destruct N as [N | N].\n    2:{ move => /(_ _ _ _ _ P) H. apply H; caseb. }\n    destruct (supath_subKK P) as [L _].\n    assert (Hr : upath_target (inl (inl (Sub u U)) : red_tens_graph) l =\n      source (Some None : edge red_tens_graph)).\n    { revert P => /andP[/andP[Wl _] _].\n      by rewrite (uwalk_sub_middle Wl). }\n    rewrite Hr {Hr} /= in L.\n    destruct (red_tens_upath_bN L) as [HN [_ [_ _]]]. specialize (HN N).\n    destruct HN as [g [m ?]]; subst l.\n    assert (P' := supath_turnsK P).\n    assert (Hr : [:: forward (Some None), backward (Some (Some None)) & r] ++ g ++\n      [:: forward (Some (Some (Some None))), backward None & m] = [::] ++\n      [:: forward (Some None), backward (Some (Some None)) & r ++ g ++\n      [:: forward (Some (Some (Some None))), backward None & m]]) by by [].\n    rewrite Hr {Hr} in P'.\n    move => /(_ _ _ _ _ P') H. apply H; rewrite !mem_cat !in_cons; caseb. }\n  clear N => N.\n  replace (l ++ [:: forward (Some None), backward (Some (Some None)) & r]) with\n    ((l ++ [:: forward (Some None); backward (Some (Some None))]) ++ r) in P by by rewrite -catA.\n  destruct (supath_subKK P) as [_ R].\n  assert (Hr : upath_source (inl (inl (Sub u U)) : red_tens_graph) r =\n    source (Some (Some None) : edge red_tens_graph)).\n  { revert P => /andP[/andP[W _] _].\n    by rewrite -(uwalk_sub_middle W) upath_target_cat. }\n  rewrite Hr {Hr} /= in R.\n  destruct (red_tens_upath_bN R) as [HN [_ [_ _]]]. specialize (HN N).\n  destruct HN as [m [d ?]]; subst r.\n  clear N R.\n  rewrite -catA in P.\n  assert (SN : [forall b, (Some None, b) \\notin m]).\n  { apply /forallP => b.\n    assert (M := supath_nin b P).\n    by revert M; repeat (rewrite ?mem_cat ?in_cons /=); introb. }\n  assert (N : [forall b, (None, b) \\notin m]).\n  { apply /forallP => b.\n    rewrite !catA in P.\n    assert (Hr : (((l ++ [:: forward (Some None); backward (Some (Some None))]) ++ m) ++\n      [:: forward (Some (Some (Some None))), backward None & d]) = (((l ++\n      [:: forward (Some None); backward (Some (Some None))]) ++ m ++\n      [:: forward (Some (Some (Some None)))]) ++ backward None :: d)) by by rewrite -!catA.\n    rewrite Hr {Hr} in P.\n    assert (M := supath_nin b P).\n    by revert M; repeat (rewrite ?mem_cat ?in_cons /=); introb. }\n  rewrite catA in P.\n  assert (M := supath_subK P).\n  rewrite upath_target_cat /= in M.\n  assert (SSN := red_tens_SNSSN M SN).\n  assert (SSSN := red_tens_NSSSN M N).\n  destruct red_tens_ineq_switching as [_ [? _]].\n  assert (NN : m <> nil).\n  { intros ?; subst m.\n    revert M; rewrite /supath; cbnb => /andP[/andP[/eqP Hc _] _].\n    enough (Pc : supath switching (source (left_tens Htens)) (source (right_tens Htens))\n      [:: forward (left_tens Htens); backward (right_tens Htens)]).\n    { rewrite Hc in Pc.\n      specialize (A _ {| upval := _ ; upvalK := Pc |}).\n      contradict A; cbnb. }\n    rewrite /supath /= !in_cons.\n    repeat (apply /andP; split); repeat (apply /norP; split); trivial; apply /eqP;\n    rewrite // ?left_e ?right_e ?Het ?Hep; caseb. }\n  destruct (red_tens_upath_Some NN M N SN SSN SSSN) as [x [X [y [Y [Hx [Hy Pxy]]]]]].\n  revert Hx => /eqP; cbnb => /eqP ?; subst x.\n  revert Hy => /eqP; cbnb => /eqP ?; subst y.\n  enough (Pf : supath switching (source (left_tens Htens)) (source (left_tens Htens))\n    (forward (left_tens Htens) :: backward (right_tens Htens) ::\n    (red_tens_upath_bwd m))).\n  { specialize (A _ {| upval := _ ; upvalK := Pf |}).\n    contradict A; cbnb. }\n  revert Pxy => /andP[/andP[Wn Un] ?].\n  rewrite /supath /= !in_cons.\n  destruct (red_tens_upath_bwd_nin_switching N SN SSN SSSN) as [? [? [? [? [? ?]]]]].\n  splitb; simpl; try (by apply /eqP; apply nesym); apply /eqP; rewrite ?left_e ?right_e ?Het ?Hep; caseb.\nQed.\n\nLemma red_tens_upath_SomeNoneNot :\n  uacyclic (@switching _ G) ->\n  forall p u U b,\n  supath switching (inl (inl (Sub u U)) : red_tens_graph) (inl (inl (Sub u U))) p ->\n  (Some None, b) \\in p ->\n  [forall c, (None, c) \\notin p].\nProof.\n  move => A p u U b.\n  revert p u U.\n  wlog: b / b = true.\n  { move => /(_ true erefl) H p u U P SN. destruct b; [by apply (H _ _ _ P) | ].\n    enough (Hd : [forall b, (None, b) \\notin upath_rev p]).\n    { apply /forallP => b. revert Hd => /forallP /(_ (~~b)).\n      by rewrite (upath_rev_in p) negb_involutive. }\n    apply (H _ _ _ (supath_revK P)).\n    by rewrite (upath_rev_in p). }\n  move => -> {b} p u U P SN.\n  apply /forallPn. move => [[] /negPn N]; contradict N; apply /negP.\n  - by apply (red_tens_upath_SomeNoneNot_ff A P).\n  - by apply (red_tens_upath_SomeNoneNot_fb A P).\nQed.\n\nLemma red_tens_upath_NoneNot :\n  uacyclic (@switching _ G) ->\n  forall p u U b,\n  supath switching (inl (inl (Sub u U)) : red_tens_graph) (inl (inl (Sub u U))) p ->\n  (None, b) \\in p ->\n  [forall c, (Some None, c) \\notin p].\nProof.\n  move => A p u U b P In.\n  apply /forallPn; move => [c /negPn Hc].\n  assert (Nin := red_tens_upath_SomeNoneNot A P Hc).\n  revert Nin => /forallP /(_ b) Nin.\n  by contradict In; apply /negP.\nQed.\n\nLemma red_tens_uacyclic_notcut_None :\n  uacyclic (@switching _ G) -> forall u U b p,\n  supath switching (inl (inl (Sub u U)) : red_tens_graph) (inl (inl (Sub u U))) p ->\n  (None, b) \\in p ->\n  p = [::].\nProof.\n  move => A u U b.\n  wlog: b / b = true.\n  { move => /(_ true erefl) H p P N. destruct b; [by apply H | ].\n    enough (Hd : upath_rev p = [::]).\n    { destruct p as [ | [? ?] ?]; trivial. contradict Hd. apply rcons_nil. }\n    apply H.\n    - by apply supath_revK.\n    - by rewrite (upath_rev_in p). }\n  move => -> {b} p P N; cbn.\n  assert (SN := red_tens_upath_NoneNot A P N).\n  destruct (red_tens_upath_fN P) as [HN [_ [_ _]]]. specialize (HN N).\n  destruct HN as [l [r ?]]; subst p.\n  clear N.\n  assert (P' : supath switching (source (Some (Some (Some None)) : edge red_tens_graph))\n    (source (None : edge red_tens_graph)) (r ++ l)).\n  { clear - P.\n    assert (P' := supath_turnsK P).\n    change ([:: forward None, backward (Some (Some (Some None))) & r] ++ l) with\n      ([:: forward None; backward (Some (Some (Some None)))] ++ r ++ l) in P'.\n    destruct (supath_subKK P') as [_ P''].\n    revert P'; rewrite /supath => /andP[/andP[W _] _].\n    by rewrite -(uwalk_sub_middle W) in P''. }\n  assert (N' : [forall b, (None, b) \\notin r ++ l]).\n  { apply /forallP => b.\n    assert (M := supath_nin b P).\n    revert M; repeat (rewrite ?mem_cat ?in_cons /=); introb. splitb. }\n  assert (SN' : [forall b, (Some None, b) \\notin r ++ l]).\n  { clear - SN. apply /forallP => b. revert SN => /forallP /(_ b).\n    rewrite !mem_cat !in_cons. introb. splitb. }\n  assert (SSN' := red_tens_SNSSN P' SN').\n  assert (SSSN' := red_tens_NSSSN P' N').\n  assert (NN' : r ++ l <> nil).\n  { intros ?.\n    assert (r = nil /\\ l = nil) as [? ?] by by destruct r. subst r l.\n    revert P; rewrite /supath cat0s => /andP[/andP[W _] _].\n    revert W; cbn; rewrite !SubK => /andP[/eqP ? /eqP Hu]. subst u.\n    enough (P : supath switching (source (left_tens Htens)) (source (right_parr Hparr))\n      (forward (left_tens Htens) :: forward et :: backward ep :: backward (right_parr Hparr) :: nil)).\n    { rewrite Hu in P.\n      specialize (A _ {| upval := _ ; upvalK := P |}).\n      contradict A; cbnb. }\n    rewrite /supath /= !in_cons.\n    destruct red_tens_ineq_switching as [? [_ [? [? [_ [? [_ [_ [_ [_ [_ [_ [? ?]]]]]]]]]]]]].\n    repeat (apply /andP; split); repeat (apply /norP; split); trivial; apply /eqP;\n    rewrite // ?left_e ?right_e ?Het ?Hep; caseb. }\n  destruct (red_tens_upath_Some NN' P' N' SN' SSN' SSSN') as [x [X [y [Y [Hx [Hy Pxy]]]]]].\n  revert Hx => /eqP; cbnb => /eqP ?; subst x.\n  revert Hy => /eqP; cbnb => /eqP ?; subst y.\n  enough (Pf : supath switching (source (right_parr Hparr)) (source (right_parr Hparr))\n    (forward (right_parr Hparr) :: forward ep :: backward et :: backward (left_tens Htens) ::\n    (red_tens_upath_bwd (r ++ l)))).\n  { specialize (A _ {| upval := _ ; upvalK := Pf |}).\n    contradict A; cbnb. }\n  revert Pxy => /andP[/andP[W Un] ?].\n  rewrite /supath /= !in_cons.\n  destruct red_tens_ineq_switching as [? [_ [? [? [_ [? [_ [_ [_ [_ [_ [_ [? ?]]]]]]]]]]]]].\n  destruct (red_tens_upath_bwd_nin_switching N' SN' SSN' SSSN') as [? [? [? [? [? ?]]]]].\n  splitb; simpl; try (by apply /eqP; apply nesym); rewrite // ?left_e ?right_e ?Het ?Hep; caseb.\nQed.\n\nLemma red_tens_uacyclic_notcut_SomeNone :\n  uacyclic (@switching _ G) -> forall u U b p,\n  supath switching (inl (inl (Sub u U)) : red_tens_graph) (inl (inl (Sub u U))) p ->\n  (Some None, b) \\in p ->\n  p = [::].\nProof.\n  move => A u U b.\n  wlog: b / b = true.\n  { move => /(_ true erefl) H p P SN. destruct b; [by apply H | ].\n    enough (Hd : upath_rev p = [::]).\n    { destruct p as [ | [? ?] ?]; trivial. contradict Hd. apply rcons_nil. }\n    apply H.\n    - by apply supath_revK.\n    - by rewrite (upath_rev_in p). }\n  move => -> {b} p P SN; cbn.\n  assert (N := red_tens_upath_SomeNoneNot A P SN).\n  destruct (red_tens_upath_fN P) as [_ [HSN [_ _]]]. specialize (HSN SN).\n  destruct HSN as [l [r ?]]; subst p.\n  clear SN.\n  assert (P' : supath switching (source (Some (Some None) : edge red_tens_graph))\n    (source (Some None : edge red_tens_graph)) (r ++ l)).\n  { clear - P.\n    assert (P' := supath_turnsK P).\n    change ([:: forward (Some None), backward (Some (Some None)) & r] ++ l) with\n      ([:: forward (Some None); backward (Some (Some None))] ++ r ++ l) in P'.\n    destruct (supath_subKK P') as [_ P''].\n    revert P'; rewrite /supath => /andP[/andP[W _] _].\n    by rewrite -(uwalk_sub_middle W) in P''. }\n  assert (N' : [forall b, (None, b) \\notin r ++ l]).\n  { clear - N. apply /forallP => b. revert N => /forallP /(_ b).\n    rewrite !mem_cat !in_cons. introb. splitb. }\n  assert (SN' : [forall b, (Some None, b) \\notin r ++ l]).\n  { apply /forallP => b.\n    assert (M := supath_nin b P).\n    revert M; repeat (rewrite ?mem_cat ?in_cons /=); introb. splitb. }\n  assert (SSN' := red_tens_SNSSN P' SN').\n  assert (SSSN' := red_tens_NSSSN P' N').\n  destruct red_tens_ineq_switching as [? [? [? [? [? [? [? [? [? [? [? [? [? ?]]]]]]]]]]]]].\n  assert (NN' : r ++ l <> nil).\n  { intros ?.\n    assert (r = nil /\\ l = nil) as [? ?] by by destruct r. subst r l.\n    revert P; rewrite /supath cat0s => /andP[/andP[W _] _].\n    revert W; cbn; rewrite !SubK => /andP[/eqP ? /eqP Hu]. subst u.\n    enough (P : supath switching (source (right_tens Htens)) (source (left_parr Hparr))\n      (forward (right_tens Htens) :: forward et :: backward ep :: backward (left_parr Hparr) :: nil)).\n    { rewrite Hu in P.\n      specialize (A _ {| upval := _ ; upvalK := P |}).\n      contradict A; cbnb. }\n    rewrite /supath /= !in_cons.\n    repeat (apply /andP; split); repeat (apply /norP; split); trivial; apply /eqP;\n    rewrite // ?left_e ?right_e ?Het ?Hep; caseb. }\n  destruct (red_tens_upath_Some NN' P' N' SN' SSN' SSSN') as [x [X [y [Y [Hx [Hy Pxy]]]]]].\n  revert Hx => /eqP; cbnb => /eqP ?; subst x.\n  revert Hy => /eqP; cbnb => /eqP ?; subst y.\n  enough (Pf : supath switching (source (left_parr Hparr)) (source (left_parr Hparr))\n    (forward (left_parr Hparr) :: forward ep :: backward et :: backward (right_tens Htens) ::\n    (red_tens_upath_bwd (r ++ l)))).\n  { specialize (A _ {| upval := _ ; upvalK := Pf |}).\n    contradict A; cbnb. }\n  revert Pxy => /andP[/andP[W Un] ?].\n  rewrite /supath /= !in_cons.\n  destruct (red_tens_upath_bwd_nin_switching N' SN' SSN' SSSN') as [? [? [? [? [? ?]]]]].\n  splitb; simpl; try (by apply /eqP; apply nesym); rewrite // ?left_e ?right_e ?Het ?Hep; caseb.\nQed.\n\nLemma red_tens_uacyclic_notcut :\n  uacyclic (@switching _ G) -> forall u U p,\n  supath switching (inl (inl (Sub u U)) : red_tens_graph) (inl (inl (Sub u U))) p ->\n  p = [::].\nProof.\n  move => A u U p P.\n  remember [forall b, (None, b) \\notin p] as Hn eqn:N; symmetry in N. destruct Hn.\n  - remember [forall b, (Some None, b) \\notin p] as Hsn eqn:SN; symmetry in SN. destruct Hsn.\n    + apply (red_tens_uacyclic_nocut A P); trivial.\n      * by apply (red_tens_SNSSN P).\n      * by apply (red_tens_NSSSN P).\n    + revert SN => /negP/negP/forallPn[b /negPn-SN].\n      apply (red_tens_uacyclic_notcut_SomeNone A P SN).\n  - revert N => /negP/negP/forallPn[b /negPn-N].\n    apply (red_tens_uacyclic_notcut_None A P N).\nQed.\n\nLemma red_tens_uacyclic :\n  uacyclic (@switching _ G) -> uacyclic (@switching _ red_tens_ps).\nProof.\n  move => A [[[u U] | []] | []] [p P]; cbnb.\n  { apply (red_tens_uacyclic_notcut A P). }\n  all: destruct p as [ | (e, b) p]; trivial.\n  all: assert (P' := supath_turnK P).\n  all: revert P => /andP[/andP[/andP[? _] _] _].\n  all: destruct e as [[[[[[[? ?] | []] | []] | ] | ] | ] | ], b; try by [].\n  all: assert (N := red_tens_uacyclic_notcut A P').\n  all: contradict N; apply rcons_nil.\nQed.\n(* TODO voir si ce n'est pas plus simple de dire il existe ou pas tel chemin dans\nle graphe d'origine, en reportant sur le nouveau on en déduit acyclique *)\n\n\nDefinition red_tens_image : edge G -> edge red_tens_graph :=\n  fun e => if @boolP _ is AltTrue p then Some (Some (Some (Some (inl (inl (Sub e p))))))\n    else if e == left_tens Htens then Some (Some (Some None))\n    else if e == right_tens Htens then Some (Some None)\n    else if e == left_parr Hparr then Some None\n    else None.\n\nLemma red_tens_graph_1_card_edge :\n  #|edge G| = #|edge (red_tens_graph_1 v et ep)| + 6.\nProof.\n  rewrite /= red_tens_removed // card_set_subset cardsE.\n  rewrite -cardsE (cardsD1 (left_tens Htens)) (cardsD1 (left_parr Hparr)) (cardsD1 (right_tens Htens))\n    (cardsD1 (right_parr Hparr)) (cardsD1 et) (cardsD1 ep) !in_set /=.\n  destruct red_tens_ineq_if as\n    [_ [_ [_ [H1 [_ [H3 [_ [H5 [_ [H7 [_ [H9 [_ [H11 [H12 [H13 [H14 [H15 [H16 [H17 [H18 H19]]]]]]]]]]]]]]]]]]]]].\n  apply nesym in H12. apply nesym in H13. apply nesym in H14. apply nesym in H15.\n  apply nesym in H16. apply nesym in H17. apply nesym in H18. apply nesym in H19.\n  revert H1 H3 H5 H7 H9 H11 H12 H13 H14 H15 H16 H17 H18 H19 => /eqP--> /eqP--> /eqP--> /eqP-->\n    /eqP--> /eqP--> /eqP--> /eqP--> /eqP--> /eqP--> /eqP--> /eqP--> /eqP--> /eqP-->.\n  assert (ep != et) as ->.\n  { clear - Htens Hparr. apply /eqP => ?; subst. contradict Hparr. by rewrite Htens. }\n  rewrite /= cardsE. lia.\nQed. (* TODO voir comment gérer proprement ce red_tens_ineq_if *)\n\nLemma red_tens_nb_edges :\n  #|edge G| = #|edge red_tens_graph| + 2.\nProof. rewrite !card_edge_add_edge !card_edge_add_vertex red_tens_graph_1_card_edge. lia. Qed.\n\nLemma red_tens_nb_parr :\n  #|[set u : G | vlabel u == ⅋]| = #|[set u : red_tens_ps | vlabel u == ⅋]| + 1.\nProof.\n  enough (#|[set u : G | vlabel u == ⅋] :\\ (source ep)| =\n    #|[set u : red_tens_ps | vlabel u == ⅋]|) as <-.\n  { rewrite (cardsD1 (source ep)) !in_set Hparr /=. lia. }\n  rewrite -!card_set_subset.\n  assert (Hf : forall (u : {u : G | (u \\notin [set source ep]) && (u \\in [set w | vlabel w == ⅋])}),\n    val u \\in [set: G] :\\ (source et) :\\ (source ep) :\\ v).\n  { move => [u U] /=.\n    rewrite /= !in_set.\n    revert U; rewrite !in_set => /andP[/eqP ? /eqP U].\n    splitb; apply /eqP; trivial.\n    all: move => ?; subst u; contradict U; by rewrite ?Hcut ?Htens. }\n  assert (Hf' : forall (u : {u : G | (u \\notin [set source ep]) && (u \\in [set w | vlabel w == ⅋])}),\n    vlabel (inl (inl (Sub (val u) (Hf u))) : red_tens_graph) == ⅋).\n  { by move => [? /=]; rewrite !in_set => /andP[_ /eqP-->]. }\n  set f : {u : G | (u \\notin [set source ep]) && (u \\in [set w | vlabel w == ⅋])} ->\n    {u : red_tens_graph | vlabel u == ⅋} :=\n    fun u => Sub (inl (inl (Sub (val u) (Hf u)))) (Hf' u).\n  assert (Hg : forall (u : {u : red_tens_graph | vlabel u == ⅋}),\n    match val u with\n    | inl (inl u) => (val u \\notin [set source ep]) && (val u \\in [set w | vlabel w == ⅋])\n    | _ => false\n    end).\n  { move => [[[[u Uin] | []] | []] /= U] //.\n    revert Uin; rewrite !in_set => /andP[_ /andP[? _]]. splitb. }\n  apply (bij_card_eq (f := f)). eapply Bijective. Unshelve. 3:{\n    move => [[[u | []] | []] U] //. exact (Sub (val u) (Hg (Sub (inl (inl u)) U))). }\n  - move => ?; cbnb.\n  - move => [[[? | []] | []] ?]; cbnb.\nQed.\n\nLemma red_tens_uconnected_nb :\n  uacyclic (@switching _ G) ->\n  uconnected_nb (@switching_left _ red_tens_graph) = uconnected_nb (@switching_left _ G).\nProof.\n  move => A.\n  assert (N := switching_left_uconnected_nb A).\n  rewrite red_tens_nb_edges red_tens_nb_parr red_tens_nb in N.\n  assert (N' : uconnected_nb (@switching_left _ G) + #|edge red_tens_ps|\n    = #|red_tens_graph| + #|[set u : red_tens_ps | vlabel u == ⅋]|) by (simpl in *; lia).\n  rewrite -(switching_left_uconnected_nb (red_tens_uacyclic A)) in N'. simpl in *. lia.\nQed.\n\nLemma red_tens_correct :\n  correct G -> correct red_tens_graph.\nProof.\n  move => [A C]. split.\n  - by apply red_tens_uacyclic.\n  - by rewrite red_tens_uconnected_nb.\nQed.\n\nEnd red_tens_proof_structure.\n\nDefinition red_tens_pn (G : proof_net) (v : G) (Hcut : vlabel v = cut) (et ep : edge G)\n  (Het : target et = v) (Hep : target ep = v) (Htens : vlabel (source et) = ⊗)\n  (Hparr : vlabel (source ep) = ⅋) : proof_net := {|\n  ps_of := red_tens_ps Hcut Het Hep Htens Hparr;\n  p_correct := @red_tens_correct _ _ _ _ _ _ _ _ _ (p_correct G);\n  |}.\n\n\n(** * Cut reduction procedure *)\nLemma red_term (G : proof_structure) (v : G) (H : vlabel v = cut) :\n  [exists e, (target e == v) && (vlabel (source e) == ax)] || [exists et, exists ep,\n  (target et == v) && (target ep == v) && (vlabel (source et) == ⊗) && (vlabel (source ep) == ⅋)].\nProof.\n  enough (Hdone : (exists e, target e = v /\\ vlabel (source e) = ax) \\/\n    exists et ep, target et = v /\\ target ep = v /\\ vlabel (source et) = ⊗ /\\ vlabel (source ep) = ⅋).\n  { apply /orP. destruct Hdone as [[e [<- <-]] | [et [ep [Het [Hep [<- <-]]]]]].\n    - left. apply /existsP; exists e. splitb.\n    - right. apply /existsP; exists et. apply /existsP; exists ep. rewrite Het Hep. splitb. }\n  destruct (p_cut H) as [e [e' H']].\n  revert H'; rewrite !in_set; move => [/eqP-Hin [/eqP-Hin' Heq]].\n  rewrite -Hin in H.\n  assert (Hout := p_deg_out (source e)).\n  assert (Hout' := p_deg_out (source e')).\n  assert (#|edges_at_out (source e)| <> 0 /\\ #|edges_at_out (source e')| <> 0) as [? ?].\n  { split; intro Hc; [set f := e | set f := e'].\n    all: assert (Hf : f \\in set0) by by rewrite -(cards0_eq Hc) in_set.\n    all: contradict Hf; by rewrite in_set. }\n  destruct (vlabel (source e)) eqn:Hle; try done; try (by left; exists e);\n  destruct (vlabel (source e')) eqn:Hle'; try done; try (by left; exists e').\n  - contradict Heq.\n    enough (flabel e = tens (flabel (left_tens Hle)) (flabel (right_tens Hle))\n      /\\ flabel e' = tens (flabel (left_tens Hle')) (flabel (right_tens Hle'))) as [-> ->] by by [].\n    assert (e = ccl_tens Hle /\\ e' = ccl_tens Hle') as [He He'] by (split; apply ccl_eq; caseb).\n    by rewrite {1}He {1}He' !p_tens_bis.\n  - right; by exists e, e'.\n  - right; by exists e', e.\n  - contradict Heq.\n    enough (flabel e = parr (flabel (left_parr Hle)) (flabel (right_parr Hle)) /\\\n      flabel e' = parr (flabel (left_parr Hle')) (flabel (right_parr Hle'))) as [-> ->] by by [].\n    assert (e = ccl_parr Hle /\\ e' = ccl_parr Hle') as [He He'] by (split; apply ccl_eq; trivial).\n    by rewrite {1}He {1}He' !p_parr_bis.\nQed.\n\n(** One step *)\nDefinition red_one_ps (G : proof_structure) (v : G) (H : vlabel v = cut) : proof_structure.\nProof.\n  elim: (orb_sum (red_term H)).\n  - move => /existsP/sigW[? /andP[/eqP-? /eqP-?]]; subst.\n    by apply (red_ax_ps H).\n  - move => /existsP/sigW[? /existsP/sigW[? /andP[/andP[/andP[/eqP-Het /eqP-Hep] /eqP-?] /eqP-?]]].\n    by apply (red_tens_ps H Het Hep).\nDefined.\n\nLemma red_one_correct (G : proof_structure) (v : G) (H : vlabel v = cut) :\n  correct G -> correct (red_one_ps H).\nProof.\n  unfold red_one_ps.\n  elim: (orb_sum (red_term H)) => ? /=.\n  - elim: (sigW _) => ? /andP[He ?]. set Hr := elimTF _ He; destruct Hr.\n    apply red_ax_correct.\n  - elim: (sigW _) => ? ?; elim: (sigW _); introb.\n    by apply red_tens_correct.\nQed.\n\nDefinition red_one_pn (G : proof_net) (v : G) (H : vlabel v = cut) : proof_net := {|\n  ps_of := red_one_ps H;\n  p_correct := red_one_correct _ (p_correct G);\n  |}.\n\nLemma red_one_sequent (G : proof_structure) (v : G) (H : vlabel v = cut) :\n  sequent (red_one_ps H) = sequent G.\nProof.\n  unfold red_one_ps.\n  elim: (orb_sum (red_term H)) => ? /=.\n  - elim: (sigW _) => ? /andP[He ?]. set Hr := elimTF eqP He; destruct Hr.\n    apply red_ax_sequent.\n  - elim: (sigW _) => *; elim: (sigW _); introb.\n    apply red_tens_sequent.\nQed.\n\nLemma red_one_nb (G : proof_structure) (v : G) (H : vlabel v = cut) :\n  #|red_one_ps H| < #|G|.\nProof.\n  unfold red_one_ps.\n  elim: (orb_sum (red_term H)) => ? /=.\n  - elim: (sigW _) => e /andP[He Hax]. set Hr := elimTF eqP He; destruct Hr.\n    rewrite (red_ax_nb H (elimTF eqP Hax)) /=. lia.\n  - elim: (sigW _) => *. elim: (sigW _) => ? /andP[/andP[/andP[Het Hep] Htens] Hparr].\n    rewrite (red_tens_nb H (elimTF eqP Het) (elimTF eqP Hep) (elimTF eqP Htens)\n      (elimTF eqP Hparr)) /=. lia.\nQed.\n\n(** All steps *)\nLemma red_all (G : proof_structure) :\n  {P : proof_structure | correct G -> correct P & sequent P = sequent G /\\ ~(has_cut P)}.\nProof.\n  revert G.\n  enough (Hm : forall n (G : proof_structure), #|G| = n ->\n    {P : proof_structure | correct G -> correct P & sequent P = sequent G /\\ ~(has_cut P)})\n    by (intro G; by apply (Hm #|G|)).\n  intro n; induction n as [n IH] using lt_wf_rect; intros G Hc.\n  have [/has_cutP/existsP/sigW[v /eqP-Hcut] | /has_cutP-?] := altP (has_cutP G).\n  2:{ by exists G. }\n  assert (N : (#|red_one_ps Hcut| < n)%coq_nat) by (rewrite -Hc; apply /leP; apply red_one_nb).\n  specialize (IH _ N _ erefl). destruct IH as [P CC [S C]].\n  exists P; [ | split; trivial].\n  - move => ?. by apply CC, red_one_correct.\n  - rewrite S. apply red_one_sequent.\nQed.\n\nDefinition red (G : proof_structure) : proof_structure := proj1_sig (red_all G).\n\nLemma red_correct (G : proof_structure) : correct G -> correct (red G).\nProof. by destruct (proj2_sig (red_all G)) as [? _]. Qed.\n\nDefinition red_pn (G : proof_net) : proof_net := {|\n  ps_of := red G;\n  p_correct := red_correct (p_correct G);\n  |}.\n\nLemma red_sequent (G : proof_structure) : sequent (red G) = sequent G.\nProof. by destruct (proj2_sig (red_all G)) as [_ [? _]]. Qed.\n\nLemma red_has_cut (G : proof_structure) : ~ has_cut (red G).\nProof. by destruct (proj2_sig (red_all G)) as [_ [_ ?]]. Qed.\n\nEnd Atoms.\n\n(* TODO confluence, normalisation *)\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_cut.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.26932566072209807}}
{"text": "From VLSM.Lib Require Import Itauto.\nFrom stdpp Require Import prelude finite.\nFrom Coq Require Import FinFun RIneq.\nFrom VLSM.Lib Require Import Preamble FinSetExtras.\nFrom VLSM.Lib Require Import RealsExtras Measurable.\nFrom VLSM.Core Require Import VLSM VLSMProjections MessageDependencies Composition Equivocation.\nFrom VLSM.Core Require Import Equivocation.FixedSetEquivocation.\nFrom VLSM.Core Require Import Equivocation.TraceWiseEquivocation.\nFrom VLSM.Core Require Import Equivocation.WitnessedEquivocation.\n\n(** * VLSM Limited Message Equivocation\n\n  In this section we define the notion of limited (message-based) equivocation.\n\n  This notion is slightly harder to define than that of fixed-set equivocation,\n  because, while for the latter we fix a set and let only the nodes belonging to\n  that set to equivocate, in the case of limited equivocation, the set of nodes\n  equivocating can change dynamically, each node being virtually allowed to\n  equivocate as long as the weight of all nodes currently equivocating does\n  not pass a certain threshold.\n\n  As we need to be able to measure the amount of equivocation in a given state\n  to design a composition constraint preventing equivocation weight from passing\n  the threshold, we need an appropriate measure of equivocation.\n  We here choose [is_equivocating_tracewise] as this measure.\n\n  Moreover, to further limit the amount of equivocation allowed when producing\n  a message, we assume a full-node-like  condition to be satisfied by all nodes.\n  This  guarantees that whenever a message not-previously send is received in a\n  state, the amount of equivocation would only grow with the weight of the\n  sender of the message (if that wasn't already known as an equivocator).\n*)\n\nSection sec_limited_message_equivocation.\n\nContext\n  {message : Type}\n  `{EqDecision index}\n  (IM : index -> VLSM message)\n  (threshold : R)\n  `{ReachableThreshold validator Cv threshold}\n  (equivocating : composite_state IM -> validator -> Prop)\n  (Hno_initial_equivocation :\n    forall s, composite_initial_state_prop IM s ->\n    forall v, ~ equivocating s v)\n  .\n\nInductive LimitedEquivocationProp (s : composite_state IM) : Prop :=\n| limited_equivocation :\n    forall (vs : Cv)\n      (Heqv_vs : forall v, equivocating s v -> v ∈ vs)\n      (Hlimited : (sum_weights vs <= threshold)%R),\n      LimitedEquivocationProp s.\n\nDefinition limited_equivocation_constraint\n  (l : composite_label IM)\n  (som : composite_state IM * option message)\n  : Prop :=\n  LimitedEquivocationProp (composite_transition IM l som).1.\n\nDefinition limited_equivocation_composite_vlsm : VLSM message :=\n  composite_vlsm IM limited_equivocation_constraint.\n\nLemma limited_equivocation_valid_state s\n  : valid_state_prop limited_equivocation_composite_vlsm s ->\n    LimitedEquivocationProp s.\nProof.\n  intros Hs; apply valid_state_prop_iff in Hs\n    as [[[is His] ->] | (l & [s' om'] & om & [(_ & _ & _ & Hv) Ht])]; simpl.\n  - exists ∅.\n    + by intros v Hv; contradict Hv; apply Hno_initial_equivocation.\n    + rewrite sum_weights_empty; [| done].\n      by apply (rt_positive (H6 := H6)).\n  - by cbv in Hv, Ht; rewrite Ht in Hv.\nQed.\n\nEnd sec_limited_message_equivocation.\n\nSection sec_basic_limited_message_equivocation.\n\nContext\n  {message : Type}\n  `{EqDecision index}\n  `{EqDecision validator}\n  (IM : index -> VLSM message)\n  `{BasicEquivocation (composite_state IM) validator}\n  .\n\nDefinition basic_limited_equivocation_constraint :=\n  limited_equivocation_constraint IM threshold is_equivocating (Cv := Cv).\n\nDefinition basic_limited_equivocation_composite_vlsm : VLSM message :=\n  limited_equivocation_composite_vlsm IM threshold is_equivocating (Cv := Cv).\n\nLemma LimitedEquivocationProp_impl_not_heavy :\n  forall s, LimitedEquivocationProp (Cv := Cv) IM threshold is_equivocating s -> not_heavy s.\nProof.\n  intros s [].\n  apply Rle_trans with (sum_weights vs); [| done].\n  apply sum_weights_subseteq; intros v Hv.\n  apply elem_of_filter in Hv as [Hvsl Hvsr].\n  by apply Heqv_vs, Hvsl.\nQed.\n\nDefinition basic_equivocation_state_validators_comprehensive_prop : Prop :=\n  forall s v, is_equivocating s v -> v ∈ state_validators s.\n\nLemma not_heavy_impl_LimitedEquivocationProp\n  (Hcomprehensive : basic_equivocation_state_validators_comprehensive_prop)\n  : forall s, not_heavy s -> LimitedEquivocationProp (Cv := Cv) IM threshold is_equivocating s.\nProof.\n  intros s Hs.\n  exists (equivocating_validators s); [| done].\n  intros v Hv; apply elem_of_filter.\n  split; [done |].\n  by apply Hcomprehensive.\nQed.\n\nEnd sec_basic_limited_message_equivocation.\n\nSection sec_tracewise_limited_message_equivocation.\n\nContext\n  {message index : Type}\n  (IM : index -> VLSM message)\n  (threshold : R)\n  `{EqDecision index}\n  `{forall i, HasBeenSentCapability (IM i)}\n  `{forall i, HasBeenReceivedCapability (IM i)}\n  (Free := free_composite_vlsm IM)\n  `{finite.Finite validator}\n  `{ReachableThreshold validator Cv threshold}\n  (A : validator -> index)\n  (sender : message -> option validator)\n  `{RelDecision _ _ (is_equivocating_tracewise_no_has_been_sent IM A sender)}\n  (Htracewise_BasicEquivocation : BasicEquivocation (composite_state IM) validator Cv threshold\n    := equivocation_dec_tracewise IM threshold A sender)\n  .\n\nExisting Instance Htracewise_BasicEquivocation.\n\nLemma tracewise_basic_equivocation_state_validators_comprehensive_prop :\n  basic_equivocation_state_validators_comprehensive_prop IM.\nProof. by intros s v _; cbn; apply elem_of_list_to_set, elem_of_enum. Qed.\n\nDefinition tracewise_limited_equivocation_constraint :=\n  basic_limited_equivocation_constraint IM.\n\nDefinition tracewise_limited_equivocation_vlsm_composition : VLSM message :=\n  basic_limited_equivocation_composite_vlsm IM.\n\nLemma full_node_limited_equivocation_valid_state_weight s\n  : valid_state_prop tracewise_limited_equivocation_vlsm_composition s ->\n    LimitedEquivocationProp (Cv := Cv) IM threshold is_equivocating s.\nProof.\n  eapply limited_equivocation_valid_state; [done |].\n  by intros; apply initial_state_not_is_equivocating_tracewise.\nQed.\n\nLemma tracewise_not_heavy_LimitedEquivocationProp_iff :\n  forall s, not_heavy s <-> LimitedEquivocationProp (Cv := Cv) IM threshold is_equivocating s.\nProof.\n  intros; split.\n  - by apply not_heavy_impl_LimitedEquivocationProp,\n      tracewise_basic_equivocation_state_validators_comprehensive_prop.\n  - by apply LimitedEquivocationProp_impl_not_heavy.\nQed.\n\nEnd sec_tracewise_limited_message_equivocation.\n\nSection sec_fixed_limited_message_equivocation.\n\n(** ** Fixed Message Equivocation implies Limited Message Equivocation\n\n  In this section we show that if the set of allowed equivocators for a fixed\n  equivocation constraint is of weight smaller than the threshold accepted for\n  limited message equivocation, then any valid trace for the fixed equivocation\n  constraint is also a trace under the limited equivocation constraint.\n*)\n\nContext\n  {message index : Type}\n  (IM : index -> VLSM message)\n  (threshold : R)\n  `{FinSet index Ci}\n  `{!finite.Finite index}\n  `{forall i, HasBeenSentCapability (IM i)}\n  `{forall i, HasBeenReceivedCapability (IM i)}\n  (Free := free_composite_vlsm IM)\n  `{finite.Finite validator}\n  `{ReachableThreshold validator Cv threshold}\n  (A : validator -> index)\n  `{! Inj (=) (=) A}\n  (sender : message -> option validator)\n  (eqv_validators : Cv)\n  (equivocators := fin_sets.set_map A eqv_validators : Ci)\n  (Hlimited : (sum_weights eqv_validators <= threshold)%R )\n  (Hsender_safety : sender_safety_alt_prop IM A sender)\n  `{RelDecision _ _ (is_equivocating_tracewise_no_has_been_sent IM A sender)}\n  (Fixed := fixed_equivocation_vlsm_composition IM equivocators)\n  (StrongFixed := strong_fixed_equivocation_vlsm_composition IM equivocators)\n  (PreFree := pre_loaded_with_all_messages_vlsm Free)\n  (Limited : VLSM message := tracewise_limited_equivocation_vlsm_composition (Cv := Cv) IM threshold 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\nLemma StrongFixed_valid_state_not_heavy s\n  (Hs : valid_state_prop StrongFixed s)\n  : tracewise_not_heavy s.\nProof.\n  cut (tracewise_equivocating_validators s ⊆ eqv_validators).\n  {\n    intro Hincl; unfold tracewise_not_heavy, not_heavy.\n    by etransitivity; [apply sum_weights_subseteq |].\n  }\n  assert (StrongFixedinclPreFree : VLSM_incl StrongFixed PreFree).\n  {\n    apply VLSM_incl_trans with (machine Free).\n    - by apply (constraint_free_incl IM (strong_fixed_equivocation_constraint IM equivocators)).\n    - by apply vlsm_incl_pre_loaded_with_all_messages_vlsm.\n  }\n  apply valid_state_has_trace in Hs as [is [tr Htr]].\n  apply (VLSM_incl_finite_valid_trace_init_to StrongFixedinclPreFree) 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 [pre [item [suf [Heqtr [Hm0 Heqv]]]]]]].\n  rewrite Heqtr in Htr.\n  destruct Htr as [Htr Hinit].\n  change (pre ++ item :: suf) with (pre ++ [item] ++ suf) in Htr.\n  apply (finite_valid_trace_from_to_app_split StrongFixed) in Htr.\n  destruct Htr as [Hpre Hitem].\n  apply (VLSM_incl_finite_valid_trace_from_to StrongFixedinclPreFree) 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 StrongFixed), proj1 in Hitem.\n  inversion Hitem; subst; clear Htl Hitem. simpl in Hm0. subst.\n  destruct Ht as [(_ & _ & _ & Hc) _].\n  destruct Hc as [(i & Hi & Hsenti) | Hemit].\n  + assert (Hsent : composite_has_been_sent IM (finite_trace_last is pre) m0)\n      by (exists i; done).\n    apply (composite_proper_sent IM) in Hsent; [| done].\n    by specialize (Hsent _ _ (conj Hpre_pre Hinit)).\n  + apply (SubProjectionTraces.sub_can_emit_sender IM (elements equivocators)\n      A sender Hsender_safety _ _ v), elem_of_elements in Hemit; [| done].\n    by revert Hemit; apply elem_of_set_map_inj.\nQed.\n\nLemma StrongFixed_incl_Limited : VLSM_incl StrongFixed Limited.\nProof.\n  apply constraint_subsumption_incl.\n  intros [i li] [s om] Hpv.\n  unfold limited_equivocation_constraint.\n  destruct (composite_transition _ _ _) as [s' om'] eqn: Ht.\n  by eapply tracewise_not_heavy_LimitedEquivocationProp_iff,\n    StrongFixed_valid_state_not_heavy, input_valid_transition_destination.\nQed.\n\nLemma Fixed_incl_Limited : VLSM_incl Fixed Limited.\nProof.\n  destruct (Fixed_eq_StrongFixed IM equivocators) as [Heq _].\n  apply VLSM_incl_trans with (machine StrongFixed).\n  - by apply Heq.\n  - by apply StrongFixed_incl_Limited.\nQed.\n\nEnd sec_fixed_limited_message_equivocation.\n\nSection sec_has_limited_equivocation.\n\n(** ** Limited Equivocation derived from Fixed Equivocation\n\n  We say that a trace has the [fixed_limited_equivocation_prop]erty if it is\n  valid for the composition using a [generalized_fixed_equivocation_constraint]\n  induced by a subset of indices whose weight is less than the allowed\n  [ReachableThreshold].\n*)\n\nContext\n  {message}\n  `{FinSet index Ci}\n  `{!finite.Finite index}\n  (IM : index -> VLSM message)\n  (threshold : R)\n  `{finite.Finite validator}\n  `{ReachableThreshold validator Cv threshold}\n  (A : validator -> index)\n  `{!Inj (=) (=) A}\n  (sender : message -> option validator)\n  `{forall i, HasBeenSentCapability (IM i)}\n  `{forall i, HasBeenReceivedCapability (IM i)}\n  .\n\nDefinition fixed_limited_equivocation_prop\n  (s : composite_state IM)\n  (tr : list (composite_transition_item IM))\n  : Prop\n  :=\n    exists equivocators : Cv,\n      (sum_weights equivocators <= threshold)%R /\\\n      finite_valid_trace (fixed_equivocation_vlsm_composition (Ci := Ci) IM (fin_sets.set_map A equivocators)) s tr.\n\nContext\n  `{FinSet message Cm}\n  (message_dependencies : message -> Cm)\n  `{RelDecision _ _ (is_equivocating_tracewise_no_has_been_sent IM A sender)}\n  (Limited : VLSM message := tracewise_limited_equivocation_vlsm_composition (Cv := Cv) IM threshold A sender)\n  .\n\n(**\n  Traces with the [fixed_limited_equivocation_prop]erty are valid for the\n  composition using a [limited_equivocation_constraint].\n*)\nLemma traces_exhibiting_limited_equivocation_are_valid\n  (Hsender_safety : sender_safety_alt_prop IM A sender)\n  : forall s tr, fixed_limited_equivocation_prop s tr -> finite_valid_trace Limited s tr.\nProof.\n  intros s tr [equivocators [Hlimited Htr]].\n  eapply VLSM_incl_finite_valid_trace; [| done].\n  by eapply Fixed_incl_Limited.\nQed.\n\n(**\n  Traces having the [strong_trace_witnessing_equivocation_prop]erty, which\n  are valid for the free composition and whose final state is [not_heavy] have\n  the [fixed_limited_equivocation_prop]erty.\n*)\nLemma traces_exhibiting_limited_equivocation_are_valid_rev\n  (Hke : WitnessedEquivocationCapability IM threshold A sender (Cv := Cv))\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  (no_initial_messages_in_IM : no_initial_messages_in_IM_prop IM)\n  (can_emit_signed : channel_authentication_prop IM A sender)\n  (Htracewise_basic_equivocation : BasicEquivocation (composite_state IM) validator Cv threshold\n    := equivocation_dec_tracewise IM threshold A sender)\n  (tracewise_not_heavy := not_heavy (1 := Htracewise_basic_equivocation) (Cv := Cv))\n  : forall is s tr, strong_trace_witnessing_equivocation_prop IM threshold A sender is tr (Cv := Cv) ->\n    finite_valid_trace_init_to (free_composite_vlsm IM) is s tr ->\n    tracewise_not_heavy s ->\n    fixed_limited_equivocation_prop is tr.\nProof.\n  intros is s tr Hstrong Htr Hnot_heavy.\n  exists (equivocating_validators s).\n  split; cycle 1.\n  - by eapply valid_trace_forget_last, strong_witness_has_fixed_equivocation.\n  - by replace (sum_weights _) with (equivocation_fault s).\nQed.\n\n(**\n  Traces with the [strong_trace_witnessing_equivocation_prop]erty, which are\n  valid for the composition using a [limited_equivocation_constraint]\n  have the [fixed_limited_equivocation_prop]erty.\n*)\nLemma limited_traces_exhibiting_limited_equivocation_are_valid_rev\n  (Hke : WitnessedEquivocationCapability IM threshold A sender (Cv := Cv))\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  (no_initial_messages_in_IM : no_initial_messages_in_IM_prop IM)\n  (can_emit_signed : channel_authentication_prop IM A sender)\n  : forall s tr, strong_trace_witnessing_equivocation_prop IM threshold A sender s tr (Cv := Cv) ->\n    finite_valid_trace Limited s tr -> fixed_limited_equivocation_prop s tr.\nProof.\n  intros s tr Hstrong Htr.\n  eapply traces_exhibiting_limited_equivocation_are_valid_rev; [done.. | |].\n  - apply valid_trace_add_default_last.\n    eapply VLSM_incl_finite_valid_trace; [| done].\n    by apply constraint_free_incl.\n  - by apply tracewise_not_heavy_LimitedEquivocationProp_iff,\n      full_node_limited_equivocation_valid_state_weight,\n      finite_valid_trace_last_pstate with (X := Limited), Htr.\nQed.\n\n(**\n  Any state which is valid for limited equivocation can be produced by\n  a trace having the [fixed_limited_equivocation_prop]erty.\n*)\n\nLemma limited_valid_state_has_trace_exhibiting_limited_equivocation\n  (Hke : WitnessedEquivocationCapability IM threshold A sender (Cv := Cv))\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  (no_initial_messages_in_IM : no_initial_messages_in_IM_prop IM)\n  (can_emit_signed : channel_authentication_prop IM A sender)\n  : forall s, valid_state_prop Limited s ->\n    exists is tr, finite_trace_last is tr = s /\\ fixed_limited_equivocation_prop is tr.\nProof.\n  intros s Hs.\n  assert (Hfree_s : valid_state_prop (free_composite_vlsm IM) s)\n    by (revert Hs; apply VLSM_incl_valid_state, constraint_free_incl).\n  destruct\n    (free_has_strong_trace_witnessing_equivocation_prop IM threshold A sender _ s Hfree_s)\n    as (is & tr & Htr & Heqv).\n  exists is, tr.\n  apply valid_trace_get_last in Htr as Hlst.\n  split; [done |].\n  eapply traces_exhibiting_limited_equivocation_are_valid_rev; [done.. |].\n  by apply tracewise_not_heavy_LimitedEquivocationProp_iff,\n    full_node_limited_equivocation_valid_state_weight.\nQed.\n\nEnd sec_has_limited_equivocation.\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/Equivocation/LimitedMessageEquivocation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2693256547202471}}
{"text": "(* Cyclone Semantics using TLC/LN in Coq Version 4 *)\n(* \"SAFE PROGRAMMING AT THE C LEVEL OF ABSTRACTION\".   Daniel Grossman, August 2003 *)\n(* Lemmas for WFC  *)\n(* Brian Milnes 2016 *)\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.\nClose Scope list_scope.\nImport LibEnvNotations.\nImport LVPE.LibVarPathEnvNotations.\n\nLemma WFU_ok_upsilon:\n  forall u,\n    WFU u ->\n    LVPE.okp u.\nProof.\n  intros.\n  inversion H.\n  constructor.\n  constructor.\n  assumption.\n  apply LVPE.get_none_inv.\n  assumption.\nQed.\n\nLtac WFU_ok_upsilon :=\n  match goal with\n    | H : WFU ?u |- LVPE.okp ?u => apply WFU_ok_upsilon\n  end.\nHint Extern 1 (LVPE.okp _) => try WFU_ok_upsilon.\n\nLemma WFDG_ok_delta:\n  forall d g,\n    WFDG d g ->\n    ok d.\nProof.\n  intros.\n  inversion* H.\nQed.\n\nLtac WFDG_ok_delta :=\n  match goal with\n    | H : WFDG ?d ?g' |- ok ?d => apply WFDG_ok_delta with (g:= g')\n  end.\nHint Extern 1 (ok _) => try WFDG_ok_delta.\n\nLemma WFDG_ok_gamma:\n  forall d g,\n    WFDG d g ->\n    ok g.\nProof.\n  intros.\n  inversion H; subst.\n  constructor.\n  constructor.\n  assumption.\n  apply* get_none_inv.\nQed.\nLtac WFDG_ok_gamma :=\n  match goal with\n    | H : WFDG ?d' ?g |- ok ?g => apply WFDG_ok_gamma with (d:=d')\n  end.\nHint Extern 1 (ok _) => try WFDG_ok_gamma.\n\nLemma WFC_ok_delta:\n  forall d u g, \n    WFC d u g ->\n    ok d.\nProof.\n  intros.\n  inversion* H.\nQed.\nLtac WFC_ok_delta :=\n  match goal with\n    | H : WFC ?d ?u' ?g'|- ok ?d => apply WFC_ok_delta with (u:=u') (g:=g')\n  end.\nHint Extern 1 (ok _) => try WFC_ok_delta.\n\nLemma WFC_ok_gamma:\n  forall d u g, \n    WFC d u g ->\n    ok g.\nProof.\n  intros*.\n  inversion* H; subst.\nQed.\nLtac WFC_ok_gamma :=\n  match goal with\n    | H : WFC ?d' ?u' ?g|- ok ?g => apply WFC_ok_gamma with (d:= d') (u:=u')\n  end.\nHint Extern 1 (ok _) => try WFC_ok_gamma.\n\nLemma WFU_K:\n  forall u xp tau,\n   WFU (u &p xp ~p tau) ->\n    K empty tau A.\nProof.\n  introv WFUd.\n  induction u.\n  inversion WFUd.\n  apply LVPE.empty_push_inv in H0.\n  inversion H0.\n  rewrite <- LVPE.V.empty_def in H.\n  apply LVPE.eq_push_inv in H.\n  inversion H.\n  inversion H5.\n  subst.\n  assumption.\n  inversion WFUd.\n  apply LVPE.empty_push_inv in H0.\n  inversion H0.\n  apply LVPE.eq_push_inv in H.\n  inversion H.\n  inversion H5.\n  subst.\n  assumption.\nQed.\nLtac WFU_K := \n  match goal with\n    | H : WFU (?u' &p ?xp' ~p ?tau') |- K empty ?tau' A => \n    apply WFU_K with (u:= u') (xp:=xp') (tau:=tau')\n  end.\nHint Extern 1 (K empty _ A) => WFU_K.\n\nLemma WFDG_K:\n  forall d g,  \n    WFDG d g ->\n    forall x tau,\n      get x g = Some tau ->\n      K d tau A.\nProof.\n  intros.\n  induction H.\n  rewrite get_empty in H0.\n  inversion H0.\n  rewrite get_push in H0.\n  case_var.\n  inversion H0; subst.\n  assumption.\n  apply IHWFDG.\n  assumption.\nQed.\nLtac WFDG_K := \n  match goal with\n    | H : WFDG ?d' ?g', I: get ?x' ?g' = Some ?tau' |- K ?d' ?tau' A =>\n      apply WFDG_K with (d:=d') (g:=g') (x:= x') (tau:=tau')\n  end.\nHint Extern 1 (K _ _ A) => WFDG_K.\n\nLemma WFC_K:\n  forall d u g,\n    WFC d u g ->\n    forall x tau,\n      get x g = Some tau ->\n      K d tau A.\nProof.\n  intros.\n  inversion H; subst.\n  auto.\nQed.\nLtac WFC_K := \n  match goal with\n    | H : WFC ?d' ?u' ?g', I: get ?x' ?g' = Some ?tau' |- K ?d' ?tau' A =>\n      apply WFC_K with (d:=d') (g:=g') (x:= x') (tau:=tau')\n  end.\nHint Extern 1 (K _ _ A) => WFC_K.\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_Well_Formedness_Lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2693111250282043}}
{"text": "From iris.proofmode Require Import tactics environments.\nFrom Perennial.Helpers Require Import NamedProps.\n\n(** * Caching and re-using Iris proofs.\n\n    Tactics for saving an Iris proof using a collection of hypotheses.\n\n    Usage:\n\n    [iCache P with \"H1 H2...\"] asks the user to prove [P] using hypotheses H1\n    H2... from the context. It creates a cached proof in the persistent context.\n\n    Later, [iFromCache] attempts to prove the goal using a matching cache and\n    the exact same hypotheses (including names).\n *)\n\n(** Implementation details:\n\n    A cache [c] for a result [R] remembers an [env] ([c.(cache_prop)]) and a\n    list of names used, and the persistent statement in the context is:\n\n    □ ([∗] c -∗ R)\n\n    Constructing the proof just involves setting up this statement. It uses\n    [iNamed] to serialize/deserialize the hypotheses while retaining names. See\n    [cached_make] for where the naming comes from, and [iCache_go] for some\n    cleanup after iApplying that theorem.\n\n    To restore the cache, we just split the environment with [envs_split] using\n    the list of names in the cache and match exactly with the cache's\n    environment. This works well because it uses a canonical order specified in\n    the cache, so after splitting we can look for equality. See\n    [tac_cached_use].\n\n    Finally, we use a cute trick to make the caches look pleasant: a\n    printing-only notation in [cache_hide_scope] that doesn't print the\n    environment and only shows the goal and hypotheses. It's possible to hide\n    things using implicits instead, but this solution has some advantages:\n\n    - Caches are displayed as [cache_for!], which tells you something funny is\n      going on.\n    - We have a little more control over the display (for example, it says\n      [cache_for! ... with ...] as a hint for what the second argument means).\n    - Caches can be temporarily displayed with [Local Close Scope cache_hide_scope].\n\n *)\n\nSection bi.\n  Context {PROP: bi}.\n  Context `{!BiAffine PROP}.\n\n  Record cache (R: PROP) :=\n    Cache { cache_prop :> env PROP;\n            cache_names: list ident; }.\n\n  Arguments cache_names {R} c.\n  Arguments cache_prop {R} c.\n\n  Definition cached_def {R} (c: cache R): PROP :=\n    (□ ([∗] c -∗ R))%I.\n  Definition cached_aux : seal (@cached_def). by eexists. Qed.\n  Definition cached := unseal cached_aux.\n  Definition cached_eq : @cached = @cached_def := seal_eq cached_aux.\n  Arguments cached {R} c.\n\n  Ltac unseal := rewrite cached_eq /cached_def.\n\n  Global Instance cached_Persistent {R} c : Persistent (@cached R c).\n  Proof. unseal. apply _. Qed.\n\n  Lemma cached_elim R (c: cache R) Δs :\n    Δs.(env_spatial) = c.(cache_prop) →\n    cached c -∗\n    of_envs Δs -∗\n    R.\n  Proof.\n    unseal.\n    iIntros (Hsubenv) \"#Hcache HΔ\".\n    iDestruct (envs_clear_spatial_sound with \"HΔ\") as \"(HΔ'&HΔs)\".\n    iApply \"Hcache\".\n    rewrite -Hsubenv.\n    iAssumption.\n  Qed.\n\n  Local Theorem tac_cached_use {Δ: envs PROP} i {R} (c: cache R) :\n    envs_lookup i Δ = Some (true, cached c) →\n    match envs_split base.Left c.(cache_names) Δ with\n    | Some (Γs, _) => Γs.(env_spatial) = c.(cache_prop)\n    | None => False\n    end →\n    envs_entails Δ R.\n  Proof.\n    iIntros (Hlookup Hsubenv).\n    destruct_with_eqn (envs_split base.Left c.(cache_names) Δ); [ | contradiction ].\n    destruct p as [Γs Γ'].\n    rewrite envs_entails_unseal.\n    iIntros \"HΔ\".\n    iDestruct (envs_lookup_intuitionistic_sound _ _ _ Hlookup with \"HΔ\") as\n        \"[#Hcache HΔ]\".\n    iDestruct (envs_split_sound with \"HΔ\") as \"[HΔ1 HΔ2]\"; eauto.\n    iApply (cached_elim with \"Hcache HΔ1\"); auto.\n  Qed.\n\n  Local Theorem cached_make R (c: cache R) :\n    □ (env_to_named_prop c -∗ R) -∗\n    cached c.\n  Proof.\n    unseal.\n    iIntros \"#HR !>\".\n    rewrite env_to_named_prop_sound //.\n  Qed.\nEnd bi.\n\nArguments cached {PROP R} c.\nArguments cache_names {PROP R} c.\nArguments cache_prop {PROP R} c.\n\n(* following the pattern from proofmode/reduction.v *)\nDeclare Reduction cached_eval :=\n  cbv [ env_to_named_prop env_to_named_prop_go cache_prop ].\nLtac cached_eval t :=\n  eval cached_eval in t.\nLtac cached_reduce :=\n  match goal with |- ?u => let v := cached_eval u in change_no_check v end.\n\nLtac iCache_go P Hs pat :=\n  let Hs := words Hs in\n  let Hs := (eval vm_compute in (INamed <$> Hs)) in\n  let Δ := iGetCtx in\n  let js := reduction.pm_eval (envs_split base.Left Hs Δ) in\n  match js with\n  | Some (?Δ, _) => let Γs := (eval cbv [env_spatial] in Δ.(env_spatial)) in\n                    iAssert (cached (Cache P Γs Hs)) as pat;\n                    [ iApply cached_make; iModIntro;\n                      cached_reduce;\n                      iNamed 1\n                    | ]\n  | None => fail 1 \"hypotheses not found\"\n  end.\n\nTactic Notation \"iCache\" constr(P) \"with\" constr(Hs) :=\n  iCache_go P Hs \"#?\".\n\nLtac iFromCache :=\n  lazymatch goal with\n  | [ |- envs_entails (Envs ?Γp _ _) ?P ] =>\n    first [ match Γp with\n            | context[Esnoc _ ?i (@cached _ P ?c)] =>\n              apply (tac_cached_use i c);\n              [ reflexivity (* lookup should always succeed, found by context match *)\n              | reduction.pm_reduce;\n                reflexivity ]\n            end\n          | lazymatch Γp with\n            | context[Esnoc _ _ (@cached _ P _)] =>\n              fail 1 \"iFromCache: could not find hypotheses for any cache\"\n            | _ =>\n              fail 1 \"iFromCache: no matching caches\"\n            end\n          ]\n  end.\n\nDeclare Scope cache_hide_scope.\nNotation \"'cache_for!' P 'with' Hs\" := (cached (Cache P _ Hs))\n                                         (at level 29, only printing) : cache_hide_scope.\nOpen Scope cache_hide_scope.\n\nModule examples.\n  Section bi.\n    Context {PROP:bi} `{!BiAffine PROP}.\n    Context (P P1 P2 Q R: PROP).\n    Context (HP: P -∗ P1 ∗ P2).\n    Context (HQ: P1 -∗ Q).\n\n    Example make_and_use_cache :\n      P -∗\n      P1 ∗ (P -∗ P1).\n    Proof.\n      iIntros \"HP\".\n      iCache P1 with \"HP\".\n      { iDestruct (HP with \"HP\") as \"[$ _]\". }\n      iSplitL \"HP\".\n      - iFromCache.\n      - iIntros \"HP\".\n        iFromCache.\n    Qed.\n\n    Example multiple_caches_for_goal :\n      P ∗ Q -∗\n      Q ∗ Q.\n    Proof.\n      iIntros \"[HP HQ]\".\n      iCache Q with \"HP\".\n      { iDestruct (HP with \"HP\") as \"[HP1 _]\".\n        iDestruct (HQ with \"HP1\") as \"$\". }\n      iCache Q with \"HQ\".\n      { auto. }\n      iSplitL \"HP\".\n      (* these goals are identical, so one of them requires backtracking on\n      which cache to use *)\n      - iFromCache.\n      - iFromCache.\n    Qed.\n\n    Example reordered_hypotheses :\n      P ∗ Q -∗\n      Q ∗ P.\n    Proof.\n      iIntros \"[HP HQ]\".\n      iCache (Q ∗ P)%I with \"HQ HP\".\n      { iFrame. }\n      (* we need to grab the goals from the context in the opposite order that\n      they appear; the current implementation uses envs_split driven by a list\n      of hypotheses in the cache itself to guide the splitting and order *)\n      iFromCache.\n    Qed.\n\n    Example fail_no_hyps :\n      P -∗ P.\n    Proof.\n      iIntros \"HP\".\n      iCache P with \"HP\"; first by iFrame.\n      iRename \"HP\" into \"HP'\".\n      Fail iFromCache. (* this should report a useful error *)\n    Abort.\n\n    Example fail_wrong_hyps :\n      P ∗ Q -∗ P.\n    Proof.\n      iIntros \"[HP HQ]\".\n      iCache P with \"HP\"; first by iFrame.\n      iClear \"HP\". iRename \"HQ\" into \"HP\".\n      Fail iFromCache. (* this should report a useful error *)\n    Abort.\n\n    Example fail_no_cache :\n      P -∗ P.\n    Proof.\n      iIntros \"HP\".\n      Fail iFromCache. (* this should report a useful error *)\n    Abort.\n\n  End bi.\nEnd examples.\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/Helpers/ProofCaching.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2693111250282043}}
{"text": "(* vendored from https://github.com/tchajed/iris-named-props *)\nFrom iris.proofmode Require Import string_ident.\nFrom iris.proofmode Require Import tactics environments intro_patterns (*monpred*).\n\nSet Default Proof Using \"Type\".\n\n(* NamedProps implements [name ∷ P], which is equivalent to P but knows to\n   name itself [name] when destructed. The syntax is intended to be analogous\n   to in Gallina where you might write [forall (Hfoo: 3 < 4), ...] for a\n   hypothesis that would be introduced as [Hfoo] using automatic names.\n\n  To use this library, write your definitions with [name ∷ P] for each conjunct.\n  Then, use [iNamed \"H\"] to destruct an invariant \"H\" into its conjuncts, using\n  their specified names. [iNamed] also introduces existentials with the names\n  for the Coq binders.\n\n  The names in a named proposition are not actually names but full-blown Iris intro\n  patterns. This means you can write [#H] to automatically introduce to the\n  persistent context, [%H] to name a pure fact (using string_to_ident), or even\n  something crazy like [\"[<- H]\"] to destruct the hypothesis and rewrite by the\n  first conjunct.\n\n  There are a several top-level tactics provided to work with named\n  propositions:\n  - [iNamed \"H\"] names a single hypothesis. This is the most common usage.\n  - [iNamed 1] on a wand introduces and destructs the premise.\n  - [iNamed] names any anonymous hypotheses (without destructing them).\n  - [iNamedAccu] is like [iAccu] - it solves a goal which is an evar with the\n    conjunction of all the hypotheses - but produces a conjunction of named\n    hypotheses. This is especially useful when that evar ?Q shows up as a\n    premise in a wand, [?Q -∗ ...], at which point you can do [iNamed 1] to\n    restore the context, including all the names.\n  - [iFrameNamed] is a work-in-progress tactic to frame a goal with named\n    conjuncts with the hypotheses using the names. This is intended to be much\n    faster than framing the entire persistent and spatial contexts.\n\n  Note that this library provides general support for propositions and is not\n  specific to definitions. You can use named hypotheses in Hoare logic\n  preconditions (to make the first iIntros more stable), in the postcondition\n  (to make it easier for the caller to re-introduce hypotheses), or in loop\n  invariants (to serve both of these purposes). If they ever get in the way you\n  can always [rewrite /named] to get rid of the names.\n *)\n\n(* Named props are defined to be the underlying prop. We used to have this\nsealed, but it turns out that this inconveniently required many forwarding\ntypeclass instances (for things like [IntoPure], [Persistent], and framing) and\nwe didn't run into any issues making it completely transparent.\n\nFor efficiency reasons, we don't have [(PROP:bi) (P:PROP)], since this requires\na coercion to the carrier of [PROP]. *)\nDefinition named {A} (name: string) (P: A): A := P.\n\nSection named.\n  Context `{SI: indexT}.\n  Context {PROP:bi}.\n\n  Theorem to_named name (P: PROP) : P -∗ named name P.\n  Proof. auto. Qed.\n  Theorem from_named name (P: PROP) : named name P -∗ P.\n  Proof. auto. Qed.\n\n  (* Implementation of [iNamedAccu]; the soundness proof basically shows these\n  definitions are equivalent to the ones used in the [iAccu] implementation,\n  since we can simply unfold [named]. *)\n\n  Fixpoint env_to_named_prop_go (acc : PROP) (Γ : env PROP) : PROP :=\n    match Γ with\n    | Enil => acc\n    | Esnoc Γ (INamed name) P => env_to_named_prop_go (named name P ∗ acc)%I Γ\n    | Esnoc Γ _ P => env_to_named_prop_go (named \"?\" P ∗ acc)%I Γ\n    end.\n  Definition env_to_named_prop (Γ : env PROP) : PROP :=\n    match Γ with\n    | Enil => emp%I\n    | Esnoc Γ (INamed name) P => env_to_named_prop_go (named name P) Γ\n    | Esnoc Γ _ P => env_to_named_prop_go (named \"?\" P) Γ\n    end.\n\n  Theorem env_to_named_prop_go_unname (acc: PROP) Γ :\n    env_to_named_prop_go acc Γ = env_to_prop_go acc Γ.\n  Proof.\n    revert acc.\n    induction Γ; simpl; auto; intros.\n    rewrite IHΓ.\n    destruct i; simpl; auto.\n  Qed.\n\n  Theorem env_to_named_prop_unname (Γ: env PROP) :\n    env_to_named_prop Γ = env_to_prop Γ.\n  Proof.\n    destruct Γ; auto.\n    destruct i; simpl; rewrite env_to_named_prop_go_unname //.\n  Qed.\n\n  Theorem env_to_named_prop_sound (Γ: env PROP) :\n    env_to_named_prop Γ ≡ ([∗] Γ)%I.\n  Proof.\n    rewrite env_to_named_prop_unname env_to_prop_sound //.\n  Qed.\n\n  Lemma tac_named_accu Δ (P: PROP) :\n    env_to_named_prop (env_spatial Δ) = P →\n    envs_entails Δ P.\n  Proof.\n    rewrite env_to_named_prop_unname.\n    apply coq_tactics.tac_accu.\n  Qed.\n\n  Lemma tac_delay_split (R P Q: PROP) :\n    (P ∗ R) -∗ (R -∗ Q) -∗ P ∗ Q.\n  Proof.\n    iIntros \"[$ R] Hwand\".\n    iApply (\"Hwand\" with \"R\").\n  Qed.\n\nEnd named.\n\nLtac to_pm_ident H :=\n  lazymatch type of H with\n  | string => constr:(INamed H)\n  | ident => constr:(H)\n  end.\n\nLocal Ltac iDeex_as i x :=\n  let x' := fresh x in\n  iDestructHyp i as (x') i.\n\nLtac iDeex :=\n  repeat match goal with\n         | |- context[Esnoc _ ?i (bi_exist (fun x => _))] =>\n           iDeex_as i x\n         end.\n\n(** [IsExistential] identifies propositions that should be destructed as\nexistentials by [iDeex]. *)\nClass IsExistential `{SI: indexT} {PROP:bi} (P: PROP) := is_existential {}.\nGlobal Arguments is_existential {SI PROP P} : assert.\nGlobal Instance is_existential_exist `{SI: indexT} {PROP:bi} {A} (Φ: A → PROP) :\n  IsExistential (bi_exist Φ).\nProof. Qed.\n\n(** [IsSplittable] identifies separating conjunction-like propositions that\nshould be split by [iNamed] as it traverses a proposition for named conjuncts.\n*)\nClass IsSplittable `{SI: indexT} {PROP:bi} (P: PROP) := is_splittable {}.\nGlobal Arguments IsSplittable {_ _} _%I : assert.\nGlobal Arguments is_splittable {SI PROP P} : assert.\nGlobal Instance is_splittable_sep `{SI: indexT} {PROP:bi} (P Q: PROP) :\n  IsSplittable (P ∗ Q).\nProof. Qed.\n\n(*\nLemma make_monPred_at_named {I : biIndex} {PROP : bi} name (i : I) (P : monPred I PROP) (𝓟 : PROP) :\n  MakeMonPredAt i P 𝓟 →\n  MakeMonPredAt i (named name P) (named name 𝓟).\nProof. done. Qed.\n\n(* This is not an instance since Coq would try and apply the instance at every\nstep in the type class resolution since [named name P] unfolds to just [P].\nInstead we register a hint that only applies when the goal contains [named]. *)\nGlobal Hint Extern 0 (MakeMonPredAt _ (named _ _) _) => apply make_monPred_at_named : typeclass_instances.\n*)\n\n\n(** tc_is_inhabited succeeds if P is an inhabited typeclass and fails otherwise.\n*)\nLtac tc_is_inhabited P :=\n  first [ let _ := constr:(ltac:(tc_solve) : P) in idtac\n        | fail 1 \"could not satisfy\" P ].\n\nLtac iDeex_one H :=\n  lazymatch iTypeOf H with\n  | Some (_, ?P) => lazymatch P with\n                    | named _ _ => idtac\n                    | _ => tc_is_inhabited (IsExistential P);\n                           iDestruct H as (?) H\n                    end\n  | None => fail 1 \"iDeexHyp:\" H \"not found\"\n  end.\n\n(* iDeexHyp is like [iDestruct \"H\" as (?) \"H\"] except that it preserves the name\nof the binder and repeats while the goal is an existential *)\nLtac iDeexHyp H :=\n  iDeex_one H; repeat iDeex_one H.\n\nLemma tac_name_replace `{SI: indexT} {PROP:bi} (i: ident) Δ p (P: PROP) Q name :\n  envs_lookup i Δ = Some (p, named name P) →\n  match envs_simple_replace i p (Esnoc Enil (INamed name) P) Δ with\n  | Some Δ' => envs_entails Δ' Q\n  | None => False\n  end →\n  envs_entails Δ Q.\nProof. rewrite /named. apply coq_tactics.tac_rename. Qed.\n\nLocal Ltac iNameReplace i name :=\n  eapply (tac_name_replace i _ _ _ _ name);\n  [ first [ reduction.pm_reflexivity\n          | fail 1 \"iNamed: could not find\" i ]\n  | reduction.pm_reduce;\n    lazymatch goal with\n    | |- False => fail 1 \"iNamed: name in not fresh\" i\n    | _ => idtac\n    end\n  ].\n\nLemma tac_name_intuitionistic `{SI: indexT} {PROP:bi} Δ i i' p (P P' Q: PROP) name :\n  envs_lookup i Δ = Some (p, named name P) →\n  IntoPersistent p P P' →\n  (if p then TCTrue else TCOr (Affine P) (Absorbing Q)) →\n  match envs_replace i p true (Esnoc Enil i' P') Δ with\n  | Some Δ' => envs_entails Δ' Q\n  | None => False\n  end →\n  envs_entails Δ Q.\nProof.\n  rewrite /named.\n  rewrite ?envs_entails_eq ?envs_entails_unseal => ? HP' HPQ HQ.\n  destruct (envs_replace _ _ _ _ _) as [Δ'|] eqn:Hrep; last done.\n  rewrite envs_replace_singleton_sound //.\n  rewrite HQ.\n\n  destruct p; simpl.\n  - iIntros \"[#HP HQ]\".\n    iApply \"HQ\".\n    iApply \"HP\".\n  - iIntros \"[#HP HQ]\".\n    iApply \"HQ\"; iFrame \"#\".\nQed.\n\nLocal Ltac iNameIntuitionistic i i' :=\n  eapply (tac_name_intuitionistic _ i i' _ _ _ _ _);\n  [ reduction.pm_reflexivity\n  | tc_solve\n  | simpl; tc_solve\n  | reduction.pm_reduce\n  ].\n\nLocal Ltac iNamePure i name :=\n  let id := string_to_ident name in\n  let id := fresh id in\n  iPure i as id.\n\n(* iNameHyp implements naming a hypothesis of the form [H: name ∷ P].\n\n   The complete tactic is mutually recursive with iNamed_go for * patterns; this\n   self-contained version takes iNamed_go as a parameter *)\nLocal Ltac iNameHyp_go_rx H iNamed_go :=\n  let i := to_pm_ident H in\n  lazymatch goal with\n  | |- context[Esnoc _ i (named ?name ?P)] =>\n    (* we check for some simple special-cases: *)\n    let pat := intro_pat.parse_one name in\n    lazymatch pat with\n    | IIdent (INamed ?name) =>\n      (* just rename one hypothesis *)\n      iNameReplace i name\n    | IIntuitionistic (IIdent ?i') =>\n      iNameIntuitionistic i i'\n    (* pure intros need to be freshened (otherwise they block using iNamed) *)\n    | IPure (IGallinaNamed ?name) =>\n      iNamePure i name\n    (* the token \"*\" causes iNamed to recurse *)\n    | IForall => change (Esnoc ?Δ i (named name P)) with (Esnoc Δ i P); iNamed_go i\n    | _ =>\n       (* we now do this only for backwards compatibility, which is a completely\n       safe but inefficient sequence that handles persistent/non-persistent\n       things correctly (most likely few patterns not covered above should even\n       be supported) *)\n       let Htmp := iFresh in\n       iRename i into Htmp;\n       iDestruct (from_named with Htmp) as pat;\n       try iClear Htmp\n    end\n  | |- context[Esnoc _ i _] =>\n    fail \"iNameHyp: hypothesis\" H \"is not a named\"\n  | _ => fail 1 \"iNameHyp: hypothesis\" H \"not found\"\n  end.\n\n(* The core of iNamed is destructing a spine of separating conjuncts and naming\n  each conjunct with iNameHyp; the implementation currently just calls iDestruct\n  and then attempts to name the new anonymous hypotheses, but it would be better\n  to parametrize the splitting and naming into a typeclass. *)\nLtac iNamedDestruct_go_rx H iNameHyp :=\n  (* we track the original name H0 here so that at the very end we can name the\n  last conjunct if it isn't named (this is what PropRestore runs into - it can\n  be destructed until a final Restore hypothesis) *)\n  let rec go H0 H :=\n      first [ iNameHyp H\n            | lazymatch iTypeOf H with\n              | Some (_, ?P) => tc_is_inhabited (IsSplittable P)\n              | None => fail 1 \"iNamed: hypothesis\" H \"not found\"\n              end;\n              let Htmp1 := iFresh in\n              let Htmp2 := iFresh in\n              let pat := constr:(IList [[IIdent Htmp1; IIdent Htmp2]]) in\n              iDestruct H as pat;\n              iNameHyp Htmp1; go H0 Htmp2\n            | (* reaching here means the last conjunct could not be named with\n              iNameHyp; rather than leave it anonymous, restore the original\n              name (note this could fail if that name was used by one of the\n              inner names, which we don't handle here) *)\n              iRename H into H0 ] in\n  go H H.\n\n(* this declaration defines iNamed by tying together all the mutual recursion *)\nLocal Ltac iNamed_go H :=\n  lazymatch H with\n  | 1%Z => let i := iFresh in iIntros i; iNamed_go i\n  | 1%nat => let i := iFresh in iIntros i; iNamed_go i\n  | _ =>\n    (* first destruct the existentials, then split the conjuncts (but\n    importantly only these two levels; the user must explicitly opt-in to\n    destructing more existentials for conjuncts) *)\n    try iDeexHyp H;\n    iNamedDestruct_go H\n  end with\n  (* Ltac *) iNameHyp_go H :=\n  iNameHyp_go_rx H iNamed_go with\n  (* Ltac *) iNamedDestruct_go H := iNamedDestruct_go_rx H iNameHyp_go.\n\nTactic Notation \"iNamedDestruct\" constr(H) := iNamedDestruct_go H.\nTactic Notation \"iNamed\" constr(H) := iNamed_go H.\n\n(* iNamed names any hypotheses that are anonymous but have a name. This is\nprimarily useful when you for some reason need to introduce using ? and then\nseparately name (this can arise if [iNamed] isn't doing the right thing, or\nwouldn't work for all the conjuncts) *)\nTactic Notation \"iNamed\" :=\n  repeat match goal with\n         | |- context[Esnoc _ ?i (named ?name ?P)] =>\n           iNameHyp_go i\n         (* TODO: debug this for destructing anonymous composites *)\n         (* | |- context[Esnoc _ ?i ?P] =>\n           lazymatch P with\n           | context[named _ _] => progress iNamed i\n           end *)\n         end.\n\n(* iNameHyp only introduces names for a single hypothesis (and is usually not\nuseful on its own) *)\nLtac iNameHyp H := iNameHyp_go H.\n\nTactic Notation \"iNamedAccu\" :=\n  iStartProof; eapply tac_named_accu; [ (* only one goal should spawn *)\n    first [\n        cbv [ env_to_named_prop env_to_named_prop_go ];\n        reduction.pm_reflexivity\n      | fail 1 \"iNamedAccu: not an evar\"\n      ]\n  ].\n\nLtac iFrameNamed :=\n  lazymatch goal with\n  | [ |- envs_entails _ ?g ] =>\n    repeat match g with\n           | context[named ?p ?P] =>\n             let pat := intro_patterns.intro_pat.parse_one p in\n             lazymatch pat with\n             | IIdent ?name => iFrame name\n             | IIntuitionistic (IIdent ?name) => iFrame name\n             | IPure (IGallinaNamed ?name) =>\n               let name := string_to_ident name in\n               iFrame (name)\n             end\n           end\n  end.\n\n(* this is crucially placed just below level 80, which is where ∗ is, so that\nyou can change [P ∗ Q] to [\"HP\" ∷ P ∗ \"HQ\" ∷ Q] without adding parentheses to\nattach the names correctly *)\nNotation \"name ∷ P\" := (named name P%I) (at level 79).\n\n(* Enable eauto to solve goals where the top-level is [named] *)\nGlobal Hint Extern 0 (environments.envs_entails _ (named _ _)) => unfold named : core.\n\nLtac iSplitDelay :=\n  let PROP := iBiOfGoal in\n  let R := fresh \"remainder\" in\n  evar (R:PROP.(bi_car));\n  iApply (tac_delay_split R with \"[-] []\");\n  subst R.\n", "meta": {"author": "logsem", "repo": "melocoton", "sha": "b77eecc3381f53db0eb3c4cf1314e881a8dc41b3", "save_path": "github-repos/coq/logsem-melocoton", "path": "github-repos/coq/logsem-melocoton/melocoton-b77eecc3381f53db0eb3c4cf1314e881a8dc41b3/theories/named_props.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.26931112502820426}}
{"text": "Require Import list_examples.\n\nDefinition heap_fun' (R : Spec kcfg) (deps : list Defn) (d:Defn) (y : Exp) :\n  forall (args : list KResult) (init_heap : MapPattern k k)\n    (ret : Z -> MapPattern k k), Prop :=\n  match d with FunDef name formals body =>\n    fun args init_heap ret =>\n      forall krest store stack heap funs mark otherfuns,\n      funs ~= fundefs deps (name s|-> KDefn d) :* otherfuns ->\n      (mark > 0)%Z ->\n      forall frame,\n      heap |= (init_heap :* litP frame) ->\n      R (KCfg (kra (ECall name (map KResultToExp args) + y)%code krest)\n              store stack heap funs mark)\n        (fun _ => False)\n  end.\n\n\n(* Nonterminating program. Note loading the value \"x\" has the potential to get\n   stuck but the program will not reach that point *)\n\nDefinition inf_rec := FunDef \"sum_recursive_inf\" [\"x\"]\n (SIf (BCon false)\n   (SReturn 0)\n   (SReturn (ECall \"sum_recursive_inf\" [ECon 1] + arr_val \"x\"))).\n\nInductive inf_rec_spec : Spec kcfg :=\n  rec_claim : forall H x' x, heap_fun' inf_rec_spec nil inf_rec x' [Int x]\n    H\n    (fun r => constraint False).\n\nLemma inf_rec_proof : sound kstep inf_rec_spec.\nProof.\n  apply proved_sound. intros. inversion H. simpl in H4. subst. simpl.\n  eapply sstep. step_solver. \n  eapply dstep. step_solver. \n  eapply dstep. step_solver.\n  eapply dstep. step_solver.\n  eapply dtrans.\n  econstructor. trans_solver. assumption. eassumption. trans_solver.\nQed.\n\n\n(* Trivial nonterminating iterative program. Analogous iterative program as\n   above gets stuck loading array value and thus is terminating *)\n\nDefinition inf_it := FunDef \"sum_inf\" [\"x\"]\n {{Decl \"s\";\"s\"<-0\n  ;SWhile (BCon true) {{\"s\"<-\"s\"+1}}\n  ;SReturn \"s\"}}.\n\nInductive inf_it_spec : Spec kcfg :=\n  inf_claim : forall k H l x, heap_loop inf_it_spec\n  inf_it 0 (\"s\" s|-> KInt k :* \"x\" s|-> KInt x)\n    (asP H (rep_list l x))\n    (fun r => constraint False).\n\nLemma inf_it_proof : sound kstep inf_it_spec.\nProof. list_solver. Qed.\n", "meta": {"author": "Formal-Systems-Laboratory", "repo": "coinduction", "sha": "1031da11c4a4523ea9b7347036b6bdabc7620e1d", "save_path": "github-repos/coq/Formal-Systems-Laboratory-coinduction", "path": "github-repos/coq/Formal-Systems-Laboratory-coinduction/coinduction-1031da11c4a4523ea9b7347036b6bdabc7620e1d/coinduction-proofs/himp/examples/ex03_list/ex14_inf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.26931111769015703}}
{"text": "(********************************************************************)\n(*                                                                  *)\n(*  The Why3 Verification Platform   /   The Why3 Development Team  *)\n(*  Copyright 2010-2015   --   INRIA - CNRS - Paris-Sud University  *)\n(*                                                                  *)\n(*  This software is distributed under the terms of the GNU Lesser  *)\n(*  General Public License version 2.1, with the special exception  *)\n(*  on linking described in file LICENSE.                           *)\n(*                                                                  *)\n(********************************************************************)\n\n(* This file is generated by Why3's Coq-realize driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire BuiltIn.\nRequire list.List.\n\n(* Why3 goal *)\nDefinition hd: forall {a:Type} {a_WT:WhyType a}, (list a) -> a.\nintros a a_WT [|h _].\nexact why_inhabitant.\nexact h.\nDefined.\n\n(* Why3 goal *)\nLemma hd_cons : forall {a:Type} {a_WT:WhyType a}, forall (x:a) (r:(list a)),\n  ((hd (Init.Datatypes.cons x r)) = x).\nProof.\nnow intros a a_WT x r.\nQed.\n\n(* Why3 goal *)\nDefinition tl: forall {a:Type} {a_WT:WhyType a}, (list a) -> (list a).\nintros a a_WT [|_ t].\nexact nil.\nexact t.\nDefined.\n\n(* Why3 goal *)\nLemma tl_cons : forall {a:Type} {a_WT:WhyType a}, forall (x:a) (r:(list a)),\n  ((tl (Init.Datatypes.cons x r)) = r).\nProof.\nnow intros a a_WT x r.\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/lib/coq/list/HdTlNoOpt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808532, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.269311117690157}}
{"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 msl.Extensionality.\n\nRequire Import sepcomp.mem_lemmas.\nRequire Import sepcomp.semantics.\n\nRequire Import msl.Coqlib2.\n\n(********************* Lemmas and definitions related to mem_step ********)\n\nLemma mem_step_refl m: mem_step m m.\n  apply (mem_step_freelist _ _ nil); trivial.\nQed.\n\nLemma mem_step_free:\n      forall m b lo hi m', Mem.free m b lo hi = Some m' -> mem_step m m'.\nProof.\n intros. eapply (mem_step_freelist _ _ ((b,lo,hi)::nil)).\n simpl. rewrite H; reflexivity.\nQed.\n\nLemma mem_step_store:\n      forall m ch b a v m', Mem.store ch m b a v = Some m' -> mem_step m m'.\nProof.\n intros. eapply mem_step_storebytes. eapply Mem.store_storebytes; eassumption.\nQed.\n\nRecord memstep_preserve (P:mem -> mem -> Prop) :=\n  {\n    preserve_trans: forall m1 m2 m3, P m1 m2 -> P m2 m3 -> P m1 m3;\n    preserve_mem: forall m m', mem_step m m' -> P m m'\n  }.\n\nLemma preserve_refl {P} (HP: memstep_preserve P): forall m, P m m.\nProof. intros. eapply (preserve_mem _ HP). apply mem_step_refl. Qed.\n\nLemma preserve_free {P} (HP: memstep_preserve P):\n      forall m b lo hi m', Mem.free m b lo hi = Some m' -> P m m'.\nProof.\n intros. eapply (preserve_mem _ HP). eapply mem_step_free; eauto. Qed.\n\nTheorem preserve_conj {P Q} (HP:memstep_preserve P) (HQ: memstep_preserve Q):\n        memstep_preserve (fun m m' => P m m' /\\ Q m m').\nProof.\nintros. constructor.\n+ intros. destruct H; destruct H0. split. eapply HP; eauto. eapply HQ; eauto.\n+ intros; split. apply HP; trivial. apply HQ; trivial.\nQed.\n\n(*opposite direction appears not to hold*)\nTheorem preserve_impl {A} (P:A -> mem -> mem -> Prop) (Q:A->Prop):\n        (forall a, Q a -> memstep_preserve (P a)) -> memstep_preserve (fun m m' => forall a, Q a -> P a m m').\nProof.\nintros.\nconstructor; intros.\n+ eapply H; eauto.\n+ apply H; eauto.\nQed.\n\nLemma preserve_exensional {P Q} (HP:memstep_preserve P) (PQ:P=Q): memstep_preserve Q.\nsubst; trivial. Qed.\n\n(*opposite direction appears not to hold*)\nTheorem preserve_univ {A} (P:A -> mem -> mem -> Prop):\n        (forall a, memstep_preserve (P a)) -> memstep_preserve (fun m m' => forall a, P a m m').\nProof. intros.\neapply preserve_exensional.\neapply (@preserve_impl A (fun a m m'=> P a m m') (fun a=>True)).\nintros. apply H. extensionality m. extensionality m'. apply prop_ext. intuition.\nQed.\n\nTheorem mem_forward_preserve: memstep_preserve mem_forward.\nProof.\nconstructor.\n+ apply mem_forward_trans.\n+ intros. induction H.\n  eapply storebytes_forward; eassumption.\n  eapply alloc_forward; eassumption.\n  eapply freelist_forward; eassumption.\n  eapply mem_forward_trans; eassumption.\nQed.\n\nTheorem readonly_preserve b: memstep_preserve (fun m m' => mem_forward m m' /\\ (Mem.valid_block m b -> readonly m b m')).\nProof.\nconstructor.\n+ intros. destruct H; destruct H0.\n  split; intros. eapply mem_forward_trans; eassumption.\n  eapply readonly_trans; eauto. apply H2. apply H. eassumption.\n+ intros; induction H.\n  - split; intros. eapply storebytes_forward; eassumption.\n    eapply storebytes_readonly; eassumption.\n  - intros.\n    split; intros. eapply alloc_forward; eassumption.\n    eapply alloc_readonly; eassumption.\n  - intros.\n    split; intros. eapply freelist_forward; eassumption.\n    eapply freelist_readonly; eassumption.\n  - destruct IHmem_step1; destruct IHmem_step2.\n    split. eapply mem_forward_trans; eassumption.\n    intros. eapply readonly_trans. eauto. apply H4. apply H1; eassumption.\nQed.\n\nTheorem readonly_preserve':\n   memstep_preserve (fun m m' => mem_forward m m' /\\ (forall b, Mem.valid_block m b -> readonly m b m')).\nProof.\neapply preserve_exensional.\neapply preserve_univ; intros. apply (readonly_preserve a).\n  extensionality m. extensionality m'. apply prop_ext.\n  split; intros. split. eapply H. apply xH. intros. eapply (H b). trivial.\n  destruct H. split; eauto.\nQed.\n\nLemma storebytes_unch_loc_unwritable b ofs: forall l m m' (L: Mem.storebytes m b ofs l = Some m'),\n      Mem.unchanged_on (loc_not_writable m) m m'.\nProof.\nintros.\nsplit; intros.\n+ rewrite (Mem.nextblock_storebytes _ _ _ _ _ L); apply Ple_refl.\n+ split; intros.\n  eapply Mem.perm_storebytes_1; eassumption.\n  eapply Mem.perm_storebytes_2; eassumption.\n+ rewrite (Mem.storebytes_mem_contents _ _ _ _ _ L).\n  apply Mem.storebytes_range_perm in L.\n  destruct (eq_block b0 b); subst.\n  - destruct (zle ofs ofs0).\n      destruct (zlt ofs0 (ofs + Z.of_nat (length l))).\n        elim H. eapply Mem.perm_max. apply L. omega.\n      rewrite PMap.gss. apply Mem.setN_other. intros. omega.\n    rewrite PMap.gss. apply Mem.setN_other. intros. omega.\n  - rewrite PMap.gso; trivial.\nQed.\n\nLemma unch_on_loc_not_writable_trans m1 m2 m3\n        (Q : Mem.unchanged_on (loc_not_writable m1) m1 m2)\n        (W : Mem.unchanged_on (loc_not_writable m2) m2 m3)\n        (F:mem_forward m1 m2):\n     Mem.unchanged_on (loc_not_writable m1) m1 m3.\nProof.\n  destruct Q as [Q0 Q1 Q2]. destruct W as [W0 W1 W2].\n  split; intros.\n  - eapply Ple_trans; eassumption.\n  - cut (Mem.perm m2 b ofs k p <-> Mem.perm m3 b ofs k p).\n      specialize (Q1 _ _ k p H H0). intuition.\n    apply W1; clear W1. intros N. apply H. apply Q1; trivial. apply F; trivial.\n  -  rewrite W2; clear W2.\n       apply Q2; trivial.\n     intros N; apply H. apply F; trivial. eapply Mem.perm_valid_block; eassumption.\n     apply Q1; trivial. eapply Mem.perm_valid_block; eassumption.\nQed.\n\nTheorem loc_not_writable_preserve:\n   memstep_preserve (fun m m' => mem_forward m m' /\\ Mem.unchanged_on (loc_not_writable m) m m').\nProof.\nconstructor.\n+ intros. destruct H as [F1 Q]; destruct H0 as [F2 W].\n  split; intros. eapply mem_forward_trans; eassumption. clear F2.\n  eapply unch_on_loc_not_writable_trans; eassumption.\n+ intros; induction H.\n  - split; intros. eapply storebytes_forward; eassumption.\n    eapply storebytes_unch_loc_unwritable; eassumption.\n  - split; intros. eapply alloc_forward; eassumption.\n    eapply Mem.alloc_unchanged_on; eassumption.\n  - split; intros. eapply freelist_forward; eassumption.\n    generalize dependent m.\n    induction l; simpl; intros. inv H. apply Mem.unchanged_on_refl.\n    destruct a. destruct p.\n    remember (Mem.free m b z0 z) as w. destruct w; inv H. symmetry in Heqw.\n    eapply unch_on_loc_not_writable_trans.\n      eapply Mem.free_unchanged_on. eassumption.\n        intros i I N. elim N; clear N.\n        eapply Mem.perm_max. eapply Mem.perm_implies. eapply Mem.free_range_perm; eassumption. constructor.\n      apply IHl; eassumption.\n      eapply free_forward; eassumption.\n  - destruct IHmem_step1; destruct IHmem_step2.\n    split. eapply mem_forward_trans; eassumption.\n    intros. clear H H0 H3. eapply unch_on_loc_not_writable_trans; eassumption.\nQed.\n\nLemma freelist_perm: forall l m m' (L : Mem.free_list m l = Some m') b (B: Mem.valid_block m b)\n      ofs (P': Mem.perm m' b ofs Max Nonempty) k p,\n      Mem.perm m b ofs k p <-> Mem.perm m' b ofs k p.\nProof. induction l; simpl; intros.\n+ inv L; split; trivial.\n+ destruct a. destruct p0.\n  remember (Mem.free m b0 z0 z) as w. symmetry in Heqw.\n  destruct w; inv L.\n  specialize (IHl _ _  H0 _ (Mem.valid_block_free_1 _ _ _ _ _ Heqw _ B) _ P' k p).\n  assert (P: Mem.perm m b ofs k p <-> Mem.perm m0 b ofs k p).\n  { clear IHl. destruct (Mem.perm_free_list _ _ _ _ _ _ _ H0 P') as [P ?]; clear H0 P'.\n    destruct (eq_block b0 b); subst.\n    - destruct (zlt ofs z0).\n      * split; intros. apply (Mem.perm_free_1 _ _ _ _ _ Heqw) in H0; eauto.\n        eapply Mem.perm_free_3; eassumption.\n      * destruct (zle z ofs).\n        split; intros. apply (Mem.perm_free_1 _ _ _ _ _ Heqw) in H0; eauto.\n                       eapply Mem.perm_free_3; eassumption.\n        split; intros.\n          eelim (Mem.perm_free_2 _ _ _ _ _ Heqw ofs Max Nonempty); clear Heqw; trivial. omega.\n        eelim (Mem.perm_free_2 _ _ _ _ _ Heqw ofs Max Nonempty); clear Heqw. omega.\n          eapply Mem.perm_implies. eapply Mem.perm_max. eassumption. constructor.\n    - split; intros.\n      * eapply (Mem.perm_free_1 _ _ _ _ _ Heqw); trivial. intuition.\n      * eapply (Mem.perm_free_3 _ _ _ _ _ Heqw); trivial.\n  }\n  intuition.\nQed.\n\nTheorem perm_preserve:\n   memstep_preserve (fun m m' =>  mem_forward m m' /\\ forall b, Mem.valid_block m b -> forall ofs, Mem.perm m' b ofs Max Nonempty ->\n                                  forall k p, Mem.perm m b ofs k p <-> Mem.perm m' b ofs k p).\nProof.\nconstructor.\n+ intros; split. eapply mem_forward_trans. apply H. apply H0.\n  destruct H; destruct H0. intros.\n  assert (M: Mem.perm m1 b ofs k p <-> Mem.perm m2 b ofs k p).\n  - clear H2. apply H1; trivial. apply H0; trivial. apply H; trivial.\n  - clear H1.\n    assert (VB2: Mem.valid_block m2 b). apply H; trivial.\n    destruct (H2 _ VB2 _ H4 k p); destruct M. split; intros; eauto.\n+ intros; induction H.\n  - split; intros. eapply storebytes_forward; eassumption.\n    split; intros. eapply Mem.perm_storebytes_1; eassumption.\n    eapply Mem.perm_storebytes_2; eassumption.\n  - split; intros. eapply alloc_forward; eassumption.\n    split; intros. eapply Mem.perm_alloc_1; eassumption.\n    eapply Mem.perm_alloc_4; try eassumption.\n    intros N; subst b'. elim (Mem.fresh_block_alloc _ _ _ _ _ H H0).\n  - intros; split. eapply freelist_forward; eassumption.\n    apply (freelist_perm _ _ _ H).\n  - clear H H0. destruct IHmem_step1; destruct IHmem_step2.\n    split. eapply mem_forward_trans; eassumption.\n    intros.\n    assert (M: Mem.perm m b ofs k p <-> Mem.perm m'' b ofs k p).\n    * clear H2. apply H0; trivial. apply H1; trivial. apply H; trivial.\n    * clear H0.\n      assert (VB2: Mem.valid_block m'' b). apply H; trivial.\n      destruct (H2 _ VB2 _ H4 k p); destruct M. split; intros; eauto.\nQed.\n\nLemma mem_step_forward m m': mem_step m m' -> mem_forward m m'.\nintros. apply preserve_mem; trivial.\neapply mem_forward_preserve; trivial.\nQed.\n\nLemma freelist_perm_inv: forall l m m' (L : Mem.free_list m l = Some m') b (B: Mem.valid_block m b)\n      ofs k p (P: Mem.perm m b ofs k p),\n      Mem.perm m b ofs Max Freeable \\/ Mem.perm m' b ofs k p.\nProof. induction l; simpl; intros.\n+ inv L. right; trivial.\n+ destruct a. destruct p0.\n  remember (Mem.free m b0 z0 z) as w. symmetry in Heqw.\n  destruct w; inv L.\n  exploit Mem.perm_free_inv; eauto. intros [[HHx HH] | HH]; try subst b0.\n  - left. eapply Mem.perm_max.  eapply Mem.free_range_perm; eassumption.\n  - destruct (IHl _ _  H0 _ (Mem.valid_block_free_1 _ _ _ _ _ Heqw _ B) _ _ _ HH); clear IHl.\n    2: right; trivial.\n    left. eapply Mem.perm_free_3; eauto.\nQed.\n\nTheorem preserves_max_eq_or_free:\n   memstep_preserve (fun m m' =>  mem_forward m m' /\\\n                                  forall b (VB: Mem.valid_block m b) ofs,\n                                   (forall k p, Mem.perm m b ofs k p <-> Mem.perm m' b ofs k p) \\/\n                                   (Mem.perm m b ofs Max Freeable /\\\n                                    Mem.perm_order'' None ((Mem.mem_access m') !! b ofs Max))).\nProof.\nconstructor.\n+ intros; split. eapply mem_forward_trans. apply H. apply H0.\n  destruct H; destruct H0. intros.\n  assert (VB2: Mem.valid_block m2 b). { apply H; trivial. }\n  destruct (H1 _ VB ofs) as [K1 | [K1 L1]]; destruct (H2 _ VB2 ofs) as [K2 | [K2 L2]]; clear H1 H2.\n  - left; intros. specialize (K1 k p); specialize (K2 k p). intuition.\n  - right; split; trivial. apply K1; trivial.\n  - right; split; trivial. simpl in *. specialize (K2 Max).\n    unfold Mem.perm in *.\n    remember ((Mem.mem_access m3) !! b ofs Max) as w; destruct w; trivial.\n    destruct ((Mem.mem_access m2) !! b ofs Max); try contradiction.\n    destruct (K2 p); simpl in *. apply H2. apply perm_refl.\n  - right; split; trivial.\n+ intros; induction H.\n  - split; intros. eapply storebytes_forward; eassumption.\n    left; intros. split; intros.\n    * eapply Mem.perm_storebytes_1; eassumption.\n    * eapply Mem.perm_storebytes_2; eassumption.\n  - split; intros. eapply alloc_forward; eassumption.\n    left; intros. split; intros.\n    * eapply Mem.perm_alloc_1; eassumption.\n    * eapply Mem.perm_alloc_4; try eassumption.\n      intros N; subst. eapply Mem.fresh_block_alloc; eassumption.\n  - split; intros. eapply freelist_forward; eassumption.\n    destruct (Mem.perm_dec m' b ofs Max Nonempty).\n    * left; intros. eapply freelist_perm; eassumption.\n    * destruct (Mem.perm_dec m b ofs Max Freeable); trivial.\n       right; split; trivial. unfold Mem.perm in n; simpl in *.\n       destruct ((Mem.mem_access m') !! b ofs Max); trivial.\n       elim n; clear n. constructor.\n      left; intros.\n      split; intros. 2: eapply perm_freelist; eassumption.\n      exploit freelist_perm_inv; eauto. intros [X | X]; trivial; contradiction.\n  - clear H H0. destruct IHmem_step1; destruct IHmem_step2.\n    split. eapply mem_forward_trans; eassumption.\n    intros.\n    assert (VB2 : Mem.valid_block m'' b). { apply H; trivial. }\n    specialize (H0 _ VB ofs). specialize (H2 _ VB2 ofs).\n    destruct H0 as [K | [K1 K2]]; destruct H2 as [L | [L1 L2]].\n    * left; intros. split; intros. apply L. apply K; trivial.\n      apply K. apply L; trivial.\n    * right. split; trivial. apply K; trivial.\n    * right. split; trivial.\n      clear K1. unfold Mem.perm in *. simpl in *. specialize (L Max).\n      remember ((Mem.mem_access m') !! b ofs Max) as d; destruct d; trivial.\n      destruct ((Mem.mem_access m'') !! b ofs Max); try contradiction.\n      specialize (L p); simpl in *. apply L. apply perm_refl.\n    * right. split; trivial.\nQed.\n\nTheorem mem_step_max_eq_or_free m m' (STEP: mem_step m m') b (VB: Mem.valid_block m b) ofs:\n       (forall k p, Mem.perm m b ofs k p <-> Mem.perm m' b ofs k p) \\/\n       (Mem.perm m b ofs Max Freeable /\\ None = ((Mem.mem_access m') !! b ofs Max)).\nProof. intros.\nexploit preserve_mem. apply preserves_max_eq_or_free. eassumption.\nsimpl; intros [A B]. destruct (B _ VB ofs). left; trivial. right.\n  destruct H; split; trivial.\n  destruct ((Mem.mem_access m') !! b ofs Max); trivial; contradiction.\nQed.\n\nLemma memsem_preserves {G C} (s: @MemSem G C) P (HP:memstep_preserve P):\n      forall g c m c' m', corestep s g c m c' m'-> P m m'.\nProof. intros.\n  apply corestep_mem in H.\n  eapply preserve_mem; eassumption.\nQed.\n\nLemma corestep_fwd {C G} (s:@MemSem G C) g c m c' m'\n   (CS:corestep s g c m c' m' ): mem_forward m m'.\nProof.\neapply memsem_preserves; try eassumption. apply mem_forward_preserve.\nQed.\n\nLemma corestep_rdonly {C G} (s:@MemSem G C) g c m c' m'\n   (CS:corestep s g c m c' m') b (VB:Mem.valid_block m b): readonly m b m'.\nProof.\neapply (memsem_preserves s _ readonly_preserve'); eassumption.\nQed.\n\nLemma mem_step_nextblock:  memstep_preserve (fun m m' => Mem.nextblock m <= Mem.nextblock m')%positive.\nconstructor.\n+ intros. xomega.\n+ induction 1.\n - apply Mem.nextblock_storebytes in H;\n   rewrite H; xomega.\n - apply Mem.nextblock_alloc in H.\n   rewrite H. clear. xomega.\n - apply nextblock_freelist in H.\n   rewrite H; xomega.\n - xomega.\nQed.\n\nLemma mem_step_nextblock':\n  forall m m',\n     mem_step m m' ->\n   (Mem.nextblock m <= Mem.nextblock m')%positive.\nProof. apply mem_step_nextblock. Qed.\n\n(*E-step: Axiomatization of external steps - potentially useful when Memory interface is hardened\nInductive e_step m m' : Prop :=\n    mem_step_estep: mem_step m m' -> e_step m m'\n  | drop_perm_estep: forall b lo hi p,\n      Mem.drop_perm m b lo hi p = Some m' -> e_step m m'\n  | change_cur_estep:\n      (forall b ofs, (Mem.mem_access m) !! b ofs Max = (Mem.mem_access m') !! b ofs Max) ->\n      Mem.unchanged_on (loc_not_writable m) m m' ->\n      (Mem.mem_contents m = Mem.mem_contents m') ->\n      Mem.nextblock m = Mem.nextblock m' -> e_step m m'\n  | estep_trans: forall m'',\n       e_step m m'' -> e_step m'' m' -> e_step m m'.\n\nLemma e_step_refl m: e_step m m.\nProof. apply mem_step_estep. apply mem_step_refl. Qed.\n\nLemma estep_forward m m' (E:e_step m m'): mem_forward m m'.\nProof.\ninduction E.\napply mem_forward_preserve; eassumption.\n+ split; intros.\n    eapply Mem.drop_perm_valid_block_1; eassumption.\n    eapply Mem.perm_drop_4; eassumption.\n+ split; intros.\n  unfold Mem.valid_block in *. rewrite H2 in *; assumption.\n  unfold Mem.perm. rewrite H. apply H4.\n+ eapply mem_forward_trans; eassumption.\nQed.\n\nLemma estep_unch_on_loc_not_writable m m' (E:e_step m m'): Mem.unchanged_on (loc_not_writable m) m m'.\nProof.\ninduction E.\n+ apply loc_not_writable_preserve in H. apply H.\n+ unfold Mem.drop_perm in H.\n  destruct (Mem.range_perm_dec m b lo hi Cur Freeable); inv H; simpl in *.\n  split; simpl; trivial.\n  intros. red in H.\n  unfold Mem.perm; simpl. rewrite PMap.gsspec.\n  destruct (peq b0 b); subst; simpl. 2: intuition.\n  destruct (zle lo ofs); simpl. 2: intuition.\n  destruct (zlt ofs hi); simpl. 2: intuition.\n  elim H. eapply Mem.perm_max. eapply Mem.perm_implies. apply r. omega. constructor.\n+ trivial.\n+ eapply unch_on_loc_not_writable_trans; try eassumption. eapply estep_forward; eassumption.\nQed.\n*)\n(*\nTheorem loadbytes_drop m b lo hi p m' (D:Mem.drop_perm m b lo hi p = Some m'):\n  forall b' ofs,\n  b' <> b \\/ ofs < lo \\/ hi <= ofs \\/ perm_order p Readable ->\n  Mem.loadbytes m' b' ofs 1 = Mem.loadbytes m b' ofs 1.\nProof.\n  intros.\nTransparent Mem.loadbytes.\n  unfold Mem.loadbytes.\n  destruct (Mem.range_perm_dec m b' ofs (ofs + 1) Cur Readable).\n  rewrite pred_dec_true.\n  unfold Mem.drop_perm in D. destruct (Mem.range_perm_dec m b lo hi Cur Freeable); inv D. simpl. auto.\n  red; intros. specialize (Mem.perm_drop_1 _ _ _ _ _ _ D ofs0 Cur); intros.\n    destruct (eq_block b' b); subst.\n      destruct H. eapply Mem.perm_drop_3. eassumption. left; trivial. apply r. trivial.\n      destruct (zlt ofs lo). eapply Mem.perm_drop_3. eassumption. right. omega. apply r. trivial.\n      destruct H. omega.\n      destruct (zle hi ofs). eapply Mem.perm_drop_3. eassumption. right. omega. apply r. trivial.\n      destruct H. omega.\n      eapply Mem.perm_implies. apply H1. omega. trivial.\n   eapply Mem.perm_drop_3. eassumption. left; trivial. apply r. omega.\n\n  destruct (Mem.range_perm_dec m' b' ofs (ofs + 1) Cur Readable); trivial.\n  elim n; clear n. red; intros. eapply Mem.perm_drop_4. eassumption. apply r. trivial.\nQed.\n*)\n\nLemma mem_step_obeys_cur_write:\n  forall m b ofs m',\n    Mem.valid_block m b ->\n   ~ Mem.perm m b ofs Cur Writable ->\n   mem_step m m' ->\n ZMap.get ofs (PMap.get b (Mem.mem_contents m)) =\n ZMap.get ofs (PMap.get b (Mem.mem_contents m')).\nProof.\n intros.\n induction H1.\n* revert m ofs0 H H0 H1; induction bytes; intros.\n Transparent Mem.storebytes.\n unfold Mem.storebytes in H1.\n destruct (Mem.range_perm_dec m b0 ofs0\n         (ofs0 + Z.of_nat (length nil)) Cur Writable);\n  inv H1; simpl.\n destruct (peq b b0). subst b0.\n rewrite PMap.gss. auto.\n rewrite PMap.gso; auto.\n change (a::bytes) with ((a::nil)++bytes) in H1.\n apply Mem.storebytes_split in H1.\n destruct H1 as [m1 [? ?]].\n etransitivity.\n 2: eapply IHbytes; try apply H2.\n clear H2 IHbytes.\n unfold Mem.storebytes in H1.\nOpaque Mem.storebytes.\n destruct (Mem.range_perm_dec m b0 ofs0\n         (ofs0 + Z.of_nat (length (a :: nil))) Cur Writable);\n inv H1; simpl.\n destruct (peq b b0). subst b0.\n rewrite PMap.gss.\n destruct (zeq ofs0 ofs). subst.\n contradiction H0. apply r. simpl. omega.\n rewrite ZMap.gso; auto.\n rewrite PMap.gso; auto.\n clear - H H1.\n eapply Mem.storebytes_valid_block_1; eauto.\n contradict H0. clear - H1 H0.\n eapply Mem.perm_storebytes_2; eauto.\n*\n apply AllocContentsOther with (b':=b) in H1.\n rewrite H1. auto. intro; subst.\n apply Mem.alloc_result in H1; unfold Mem.valid_block in H.\n subst. apply Plt_strict in H; auto.\n*\n revert m H H0 H1; induction l; simpl; intros.\n inv H1; auto.\n destruct a. destruct p.\n destruct (Mem.free m b0 z0 z) eqn:?; inv H1.\n rewrite <- (IHl m0); auto.\n eapply free_contents; eauto.\n intros [? ?]. subst b0. apply H0.\n apply Mem.free_range_perm in Heqo.\n   specialize (Heqo ofs).\n   eapply Mem.perm_implies. apply Heqo. omega. constructor.\n clear - H Heqo.\n unfold Mem.valid_block in *.\n apply Mem.nextblock_free in Heqo. rewrite Heqo.\n auto.\n clear - H0 Heqo.\n contradict H0.\n eapply Mem.perm_free_3; eauto.\n*\n assert (Mem.valid_block m'' b). {\n   apply mem_step_nextblock in H1_.\n   unfold Mem.valid_block in *.\n   eapply Plt_le_trans; eauto.\n }\n erewrite IHmem_step1 by auto. apply IHmem_step2; auto.\n contradict H0.\n clear - H H1_ H0.\n revert H H0; induction H1_; intros.\n eapply Mem.perm_storebytes_2; eauto.\n pose proof (Mem.perm_alloc_inv _ _ _ _ _ H _ _ _ _ H1).\n destruct (eq_block b b'); subst; trivial.\n - pose proof (Mem.alloc_result _ _ _ _ _ H).\n   subst. apply Plt_strict in H0. contradiction.\n - eapply Mem.perm_free_list in H; try apply H1.\n   destruct H; auto.\n - eapply IHH1_1; auto. eapply IHH1_2; eauto.\n   apply mem_step_nextblock in H1_1.\n   unfold Mem.valid_block in *.\n   eapply Plt_le_trans; eauto.\nQed.\n\nLemma ple_load m ch a v\n            (LD: Mem.loadv ch m a = Some v)\n            m1 (PLE: perm_lesseq m m1):\n           Mem.loadv ch m1 a = Some v.\nProof.\nunfold Mem.loadv in *.\ndestruct a; auto.\nTransparent Mem.load.\nunfold Mem.load in *.\nOpaque Mem.load.\ndestruct PLE.\nif_tac in LD; [ | inv LD].\nrewrite if_true.\nrewrite <- LD; clear LD.\nf_equal. f_equal.\ndestruct H.\nrewrite size_chunk_conv in H.\nclear - H perm_le_cont.\nforget (size_chunk_nat ch) as n.\nforget (Int.unsigned i) as j.\nrevert j H; induction n; intros; simpl; f_equal.\napply perm_le_cont.\napply (H j).\nrewrite inj_S.\nomega.\napply IHn.\nrewrite inj_S in H.\nintros ofs ?; apply H. omega.\nclear - H perm_le_Cur.\ndestruct H; split; auto.\nintros ? ?. specialize (H ofs H1).\nhnf in H|-*.\nspecialize (perm_le_Cur b ofs).\ndestruct ((Mem.mem_access m) !! b ofs Cur); try contradiction.\ndestruct ((Mem.mem_access m1) !! b ofs Cur);\ninv perm_le_Cur; auto; try constructor; try inv H.\nQed.\n\nLemma ple_store:\n  forall ch m v1 v2 m' m1\n   (PLE: perm_lesseq m m1),\n   Mem.storev ch m v1 v2 = Some m' ->\n   exists m1', perm_lesseq m' m1' /\\ Mem.storev ch m1 v1 v2 = Some m1'.\nProof.\nintros.\nunfold Mem.storev in *.\ndestruct v1; try discriminate.\nTransparent Mem.store.\nunfold Mem.store in *.\nOpaque Mem.store.\ndestruct (Mem.valid_access_dec m ch b (Int.unsigned i)  Writable); inv H.\ndestruct (Mem.valid_access_dec m1 ch b (Int.unsigned i)\n      Writable).\n*\neexists; split; [ | reflexivity].\ndestruct PLE.\nconstructor; simpl; auto.\nintros. unfold Mem.perm in H. simpl in H.\nforget (Int.unsigned i) as z.\ndestruct (eq_block b0 b). subst.\nrewrite !PMap.gss.\nforget (encode_val ch v2) as vl.\nassert (z <= ofs < z + Z.of_nat (length vl) \\/ ~ (z <= ofs < z + Z.of_nat (length vl))) by omega.\ndestruct H0.\nclear - H0.\nforget ((Mem.mem_contents m1) !! b) as mA.\nforget ((Mem.mem_contents m) !! b) as mB.\nrevert z mA mB H0; induction vl; intros; simpl.\nsimpl in H0; omega.\nsimpl length in H0; rewrite inj_S in H0.\ndestruct (zeq z ofs).\nsubst ofs.\nrewrite !Mem.setN_outside by omega. rewrite !ZMap.gss; auto.\napply IHvl; omega.\nrewrite !Mem.setN_outside by omega.\napply perm_le_cont. auto.\nrewrite !PMap.gso by auto.\napply perm_le_cont. auto.\n*\ncontradiction n; clear n.\ndestruct PLE.\nunfold Mem.valid_access in *.\ndestruct v; split; auto.\nhnf in H|-*; intros.\nspecialize (H _ H1).\nclear - H perm_le_Cur.\nspecialize (perm_le_Cur b ofs).\nhnf in H|-*.\ndestruct ((Mem.mem_access m) !! b ofs Cur); try contradiction.\ninv H;\ndestruct ((Mem.mem_access m1) !! b ofs Cur);\ninv perm_le_Cur; auto; try constructor; try inv H.\nQed.\n\nLemma free_access_inv m b lo hi m' (FR: Mem.free m b lo hi = Some m') b' ofs k p\n  (P: (Mem.mem_access m') !! b' ofs k = Some p):  (Mem.mem_access m) !! b' ofs k = Some p.\nProof.\napply Mem.free_result in FR; subst. simpl in *.\nrewrite PMap.gsspec in P.\ndestruct (peq b' b); subst; trivial.\ndestruct (zle lo ofs && zlt ofs hi); inv P; trivial.\nQed.\n\nLemma free_access_inv_None m b lo hi m' (FR: Mem.free m b lo hi = Some m') b' ofs k\n  (P: (Mem.mem_access m') !! b' ofs k = None):\n  (b' = b /\\ Z.le lo ofs /\\ Z.lt ofs hi /\\  (Mem.mem_access m) !! b' ofs k = Some Freeable) \\/\n  ((b' <> b \\/ Z.lt ofs lo \\/ Z.le hi ofs) /\\ (Mem.mem_access m) !! b' ofs k = None).\nProof.\nspecialize (Mem.free_result _ _ _ _ _ FR). intros; subst. simpl in *.\nrewrite PMap.gsspec in P.\ndestruct (peq b' b); subst.\n+ remember (zle lo ofs && zlt ofs hi) as q.\n  destruct q; inv P.\n  - left. split; trivial. destruct (zle lo ofs); simpl in *; try discriminate.\n    split; trivial. destruct (zlt ofs hi); simpl in *; try discriminate.\n    split; trivial.\n    assert (RP: Mem.perm m b ofs Cur Freeable). apply (Mem.free_range_perm _ _ _ _ _ FR ofs); omega.\n    destruct k.\n    * eapply Mem.perm_max in RP.\n      unfold Mem.perm in RP. destruct ((Mem.mem_access m) !! b ofs Max); simpl in *; try discriminate.\n      destruct p; simpl in *; try inv RP; simpl; trivial. contradiction.\n    * unfold Mem.perm in RP. destruct ((Mem.mem_access m) !! b ofs Cur); simpl in *; try discriminate.\n      destruct p; simpl in *; try inv RP; simpl; trivial. contradiction.\n  - right; split; trivial. right.\n    destruct (zle lo ofs); destruct (zlt ofs hi); simpl in *; try discriminate; try omega.\n+ right; split; trivial. left; trivial.\nQed.\n\nLemma ple_free: forall m m' b lo hi (FL: Mem.free m b lo hi = Some m') m1 (PLE:perm_lesseq m m1),\n      exists m1', Mem.free m1 b lo hi = Some m1' /\\ perm_lesseq m' m1'.\nProof. intros.\n  specialize (Mem.free_range_perm _ _ _ _ _ FL). intros.\n  assert (RF: Mem.range_perm m1 b lo hi Cur Freeable).\n  { destruct PLE. red; intros.\n    specialize (perm_le_Cur b ofs). specialize (H _ H0). unfold Mem.perm in *.\n    destruct ((Mem.mem_access m) !! b ofs Cur); simpl in *; try contradiction.\n    destruct ((Mem.mem_access m1) !! b ofs Cur); simpl in *; try contradiction.\n    eapply perm_order_trans; eassumption.\n  }\n  destruct (Mem.range_perm_free m1 b lo hi RF) as [mm MM].\n  exists mm; split; trivial.\n  destruct PLE.\n  split; intros.\n  - specialize (perm_le_Cur b0 ofs); clear perm_le_Max perm_le_cont.\n    remember ((Mem.mem_access mm) !! b0 ofs Cur) as q; symmetry in Heqq.\n      destruct q; simpl in *.\n      * rewrite (free_access_inv _ _ _ _ _ MM _ _ _ _ Heqq) in *.\n        remember ((Mem.mem_access m') !! b0 ofs Cur) as w; symmetry in Heqw.\n         destruct w; trivial.\n         rewrite (free_access_inv _ _ _ _ _ FL _ _ _ _ Heqw) in *. simpl in *; trivial.\n      * remember ((Mem.mem_access m') !! b0 ofs Cur) as w; symmetry in Heqw.\n        destruct w; trivial.\n        rewrite (free_access_inv _ _ _ _ _ FL _ _ _ _ Heqw) in *.\n        destruct (free_access_inv_None _ _ _ _ _ MM _ _ _ Heqq).\n        ++ destruct H0 as [? [? [? ?]]]; subst.\n           rewrite (Mem.free_result _ _ _ _ _ FL) in *. simpl in *.\n           rewrite PMap.gss in Heqw.\n           remember (zle lo ofs&& zlt ofs hi ) as t; destruct t; simpl in *; try discriminate.\n           destruct (zle lo ofs); destruct (zlt ofs hi); simpl in *; try discriminate; omega.\n        ++ destruct H0 as [? ?]. rewrite H1 in *; simpl in *; contradiction.\n  - specialize (perm_le_Max b0 ofs); clear perm_le_Cur perm_le_cont.\n    remember ((Mem.mem_access mm) !! b0 ofs Max) as q; symmetry in Heqq.\n      destruct q; simpl in *.\n      * rewrite (free_access_inv _ _ _ _ _ MM _ _ _ _ Heqq) in *.\n        remember ((Mem.mem_access m') !! b0 ofs Max) as w; symmetry in Heqw.\n         destruct w; trivial.\n         rewrite (free_access_inv _ _ _ _ _ FL _ _ _ _ Heqw) in *. simpl in *; trivial.\n      * remember ((Mem.mem_access m') !! b0 ofs Max) as w; symmetry in Heqw.\n        destruct w; trivial.\n        rewrite (free_access_inv _ _ _ _ _ FL _ _ _ _ Heqw) in *.\n        destruct (free_access_inv_None _ _ _ _ _ MM _ _ _ Heqq).\n        ++ destruct H0 as [? [? [? ?]]]; subst.\n           rewrite (Mem.free_result _ _ _ _ _ FL) in *. simpl in *.\n           rewrite PMap.gss in Heqw.\n           remember (zle lo ofs&& zlt ofs hi ) as t; destruct t; simpl in *; try discriminate.\n           destruct (zle lo ofs); destruct (zlt ofs hi); simpl in *; try discriminate; omega.\n        ++ destruct H0 as [? ?]. rewrite H1 in *; simpl in *; contradiction.\n  - rewrite (Mem.free_result _ _ _ _ _ FL). rewrite (Mem.free_result _ _ _ _ _ MM).\n    simpl. apply perm_le_cont. eapply Mem.perm_free_3; eassumption.\n  - rewrite (Mem.free_result _ _ _ _ _ FL). rewrite (Mem.free_result _ _ _ _ _ MM).\n    simpl; trivial.\nQed.\n\nLemma ple_freelist: forall l m m' (FL: Mem.free_list m l = Some m') m1 (PLE:perm_lesseq m m1),\n      exists m1', Mem.free_list m1 l = Some m1' /\\ perm_lesseq m' m1'.\nProof. induction l; simpl; intros.\n+ inv FL;  exists m1; split; trivial.\n+ destruct a as [[b lo] hi]. remember (Mem.free m b lo hi) as q. destruct q; inv FL.\n  symmetry in Heqq.\n  destruct (ple_free _ _ _ _ _ Heqq _ PLE) as [mm [MMF MM]]. rewrite MMF. eauto.\nQed.\n\nLemma ple_storebytes:\n  forall m b ofs bytes m' m1\n   (PLE: perm_lesseq m m1),\n   Mem.storebytes m b ofs bytes = Some m' ->\n   exists m1', perm_lesseq m' m1' /\\ Mem.storebytes m1 b ofs bytes = Some m1'.\nProof.\nintros. Transparent Mem.storebytes. unfold Mem.storebytes in *. Opaque Mem.storebytes.\nremember (Mem.range_perm_dec m b ofs (ofs + Z.of_nat (length bytes)) Cur Writable ) as d.\ndestruct d; inv H.\ndestruct (Mem.range_perm_dec m1 b ofs (ofs + Z.of_nat (length bytes)) Cur Writable).\n+ clear Heqd.\n  eexists; split. 2: reflexivity.\n  destruct PLE.\n  split; intros; simpl.\n  - simpl. apply perm_le_Cur.\n  - simpl. apply perm_le_Max.\n  - simpl in *. rewrite PMap.gsspec. rewrite PMap.gsspec.\n    destruct (peq b0 b); subst.\n    * destruct (zlt ofs0 ofs).\n      ++ rewrite Mem.setN_outside. 2: left; trivial.  rewrite Mem.setN_outside. 2: left; trivial.  apply perm_le_cont. apply H.\n      ++ destruct (zle (ofs+Z.of_nat (length bytes)) ofs0).\n         rewrite Mem.setN_outside. 2: right; xomega.  rewrite Mem.setN_outside. 2: right; xomega.  apply perm_le_cont. apply H.\n         clear - g g0.\n         remember ((Mem.mem_contents m1) !! b) as mA. clear HeqmA.\n         remember ((Mem.mem_contents m) !! b) as mB. clear HeqmB.\n         revert ofs mA mB g g0; induction bytes; intros; simpl.\n         -- simpl in *; omega.\n         -- simpl length in g0; rewrite inj_S in g0.\n            destruct (zeq ofs ofs0).\n            ** subst ofs0. rewrite !Mem.setN_outside by omega. rewrite !ZMap.gss; auto.\n            ** apply IHbytes; omega.\n    * apply perm_le_cont. apply H.\n  - assumption .\n+ elim n; clear - PLE r. destruct PLE.\n  red; intros. specialize (r _ H). specialize (perm_le_Cur b ofs0).\n  unfold Mem.perm in *.\n  destruct ((Mem.mem_access m1) !! b ofs0 Cur).\n  destruct ((Mem.mem_access m) !! b ofs0 Cur). simpl in *. eapply perm_order_trans; eassumption.\n  inv r.\n  destruct ((Mem.mem_access m) !! b ofs0 Cur); inv perm_le_Cur. inv r.\nQed.\n\nLemma ple_loadbytes m b ofs n bytes\n            (LD: Mem.loadbytes m b ofs n = Some bytes)\n            m1 (PLE: perm_lesseq m m1) (N: 0 <= n):\n            Mem.loadbytes m1 b ofs n = Some bytes.\nProof.\nTransparent Mem.loadbytes.\nunfold Mem.loadbytes.\nOpaque Mem.loadbytes.\napply loadbytes_D in LD. destruct LD as [RP1 CONT].\ndestruct PLE.\ndestruct (Mem.range_perm_dec m1 b ofs (ofs + n) Cur Readable).\n+ rewrite CONT; f_equal. eapply Mem.getN_exten.\n  intros. apply perm_le_cont. apply RP1. rewrite nat_of_Z_eq in H; omega.\n+ elim n0; clear - RP1 perm_le_Cur.\n  red; intros. specialize (RP1 _ H). specialize (perm_le_Cur b ofs0).\n  unfold Mem.perm in *.\n  destruct ((Mem.mem_access m1) !! b ofs0 Cur).\n  destruct ((Mem.mem_access m) !! b ofs0 Cur). simpl in *. eapply perm_order_trans; eassumption.\n  inv RP1.\n  destruct ((Mem.mem_access m) !! b ofs0 Cur); inv perm_le_Cur. inv RP1.\nQed.\n\nLemma alloc_access_inv m b lo hi m' (ALLOC: Mem.alloc m lo hi = (m', b)) b' ofs k p\n  (P: (Mem.mem_access m') !! b' ofs k = Some p):\n  (b'=b /\\ Z.le lo ofs /\\ Z.lt ofs hi) \\/\n  (b' <> b /\\ (Mem.mem_access m) !! b' ofs k = Some p).\nProof.\nTransparent Mem.alloc. unfold Mem.alloc in ALLOC. Opaque Mem.alloc. inv ALLOC; simpl in *.\nrewrite PMap.gsspec in P.\ndestruct (peq b' (Mem.nextblock m)); subst; trivial.\n+ left; split; trivial.\n  remember (zle lo ofs && zlt ofs hi) as q. destruct q; inv P; trivial.\n  destruct (zle lo ofs); destruct (zlt ofs hi); simpl in *; try discriminate; omega.\n+ right; split; trivial.\nQed.\n\nLemma alloc_access_inv_None m b lo hi m' (ALLOC: Mem.alloc m lo hi = (m', b)) b' ofs k\n  (P: (Mem.mem_access m') !! b' ofs k = None): (Mem.mem_access m) !! b' ofs k = None.\nProof.\nTransparent Mem.alloc. unfold Mem.alloc in ALLOC. Opaque Mem.alloc. inv ALLOC; simpl in *.\nrewrite PMap.gsspec in P.\ndestruct (peq b' (Mem.nextblock m)); subst; trivial.\napply Mem.nextblock_noaccess. xomega.\nQed.\n\nLemma alloc_inc_perm: forall m lo hi m' b\n      (M: Mem.alloc m lo hi = (m',b)) m1 (PLE: perm_lesseq m m1),\n      exists m1' : mem, Mem.alloc m1 lo hi =(m1',b) /\\ perm_lesseq m' m1'.\nProof. intros.\n  remember (Mem.alloc m1 lo hi). destruct p; symmetry in Heqp.\n  assert (B: b0=b).\n     apply Mem.alloc_result  in M. apply Mem.alloc_result  in Heqp.\n     destruct PLE. rewrite perm_le_nb in *; subst. trivial.\n  subst b0.\n  eexists m0; split; trivial.\n  Transparent Mem.alloc. unfold Mem.alloc in *. Opaque Mem.alloc. inv M; inv Heqp. simpl in *.\n  destruct PLE.\n  split; simpl; intros.\n  + specialize (perm_le_Cur b ofs); clear perm_le_Max perm_le_cont.\n    rewrite perm_le_nb, PMap.gsspec.  rewrite PMap.gsspec.\n    destruct (peq b (Mem.nextblock m1)); subst; trivial.\n    destruct (if zle lo ofs && zlt ofs hi then Some Freeable else None); simpl; trivial. apply perm_refl.\n  + specialize (perm_le_Max b ofs); clear perm_le_Cur perm_le_cont.\n    rewrite perm_le_nb, PMap.gsspec.  rewrite PMap.gsspec.\n    destruct (peq b (Mem.nextblock m1)); subst; trivial.\n    destruct (if zle lo ofs && zlt ofs hi then Some Freeable else None); simpl; trivial. apply perm_refl.\n  + unfold Mem.perm in H; simpl in H.\n    rewrite PMap.gsspec in H.\n    destruct (peq b (Mem.nextblock m)); subst.\n    - rewrite perm_le_nb. do 2 rewrite PMap.gss. trivial.\n    - rewrite PMap.gso; try rewrite H1; trivial. rewrite PMap.gso; trivial. apply perm_le_cont. apply H.\n  + rewrite H1; trivial.\nQed.\n\nLemma perm_lesseq_refl:\n  forall m, perm_lesseq m m.\nProof.\nintros.\n constructor; intros; auto.\n match goal with |- Mem.perm_order'' ?A _ => destruct A; constructor end.\n match goal with |- Mem.perm_order'' ?A _ => destruct A; constructor end.\nQed.\n\n(*************************************************************************)\n\nDefinition corestep_fun {G C M : Type} (sem : @CoreSemantics G C M) :=\n  forall (m m' m'' : M) ge c c' c'',\n  corestep sem ge c m c' m' ->\n  corestep sem ge c m c'' m'' ->\n  c'=c'' /\\ m'=m''.\n\n(**  Multistepping *)\n\nSection corestepN.\n  Context {G C M E:Type} (Sem:@CoreSemantics G C M) (ge:G).\n\n  Fixpoint corestepN (n:nat) : C -> M -> C -> M -> Prop :=\n    match n with\n      | O => fun c m c' m' => (c,m) = (c',m')\n      | S k => fun c1 m1 c3 m3 => exists c2, exists m2,\n        corestep Sem ge c1 m1 c2 m2 /\\\n        corestepN k c2 m2 c3 m3\n    end.\n\n  Lemma corestepN_add : forall n m c1 m1 c3 m3,\n    corestepN (n+m) c1 m1 c3 m3 <->\n    exists c2, exists m2,\n      corestepN n c1 m1 c2 m2 /\\\n      corestepN m 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 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 x1 x2 c3 m3).\n    eauto.\n  Qed.\n\n  Definition corestep_plus c m c' m' :=\n    exists n, corestepN (S n) c m c' m'.\n\n  Definition corestep_star c m c' m' :=\n    exists n, corestepN n c m c' m'.\n\n  Lemma corestep_plus_star : forall c1 c2 m1 m2,\n    corestep_plus c1 m1 c2 m2 -> corestep_star c1 m1 c2 m2.\n  Proof. intros. destruct H as [n1 H1]. eexists. apply H1. Qed.\n\n  Lemma corestep_plus_trans : forall c1 c2 c3 m1 m2 m3,\n    corestep_plus c1 m1 c2 m2 -> corestep_plus c2 m2 c3 m3 ->\n    corestep_plus c1 m1 c3 m3.\n  Proof. intros. destruct H as [n1 H1]. destruct H0 as [n2 H2].\n    destruct (corestepN_add (S n1) (S n2) c1 m1 c3 m3) as [_ H].\n    eexists. apply H. exists c2. exists m2. split; assumption.\n  Qed.\n\n  Lemma corestep_star_plus_trans : forall c1 c2 c3 m1 m2 m3,\n    corestep_star c1 m1 c2 m2 -> corestep_plus c2 m2 c3 m3 ->\n    corestep_plus c1 m1 c3 m3.\n  Proof. intros. destruct H as [n1 H1]. destruct H0 as [n2 H2].\n    destruct (corestepN_add n1 (S n2) 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 corestep_plus_star_trans: forall c1 c2 c3 m1 m2 m3,\n    corestep_plus c1 m1 c2 m2 -> corestep_star c2 m2 c3 m3 ->\n    corestep_plus c1 m1 c3 m3.\n  Proof. intros. destruct H as [n1 H1]. destruct H0 as [n2 H2].\n    destruct (corestepN_add (S n1) n2 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 corestep_star_trans: forall c1 c2 c3 m1 m2 m3,\n    corestep_star c1 m1 c2 m2 -> corestep_star c2 m2 c3 m3 ->\n    corestep_star c1 m1 c3 m3.\n  Proof. intros. destruct H as [n1 H1]. destruct H0 as [n2 H2].\n    destruct (corestepN_add n1 n2 c1 m1 c3 m3) as [_ H].\n    eexists. apply H.  exists c2. exists m2.  split; assumption.\n  Qed.\n\n  Lemma corestep_plus_one: forall c m c' m',\n    corestep  Sem ge c m c' m' -> corestep_plus c m c' m'.\n  Proof. intros. unfold corestep_plus, corestepN. simpl.\n    exists O. exists c'. exists m'. eauto.\n  Qed.\n\n  Lemma corestep_plus_two: forall c m c' m' c'' m'',\n    corestep  Sem ge c m c' m' -> corestep  Sem ge c' m' c'' m'' ->\n    corestep_plus 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 corestep_star_zero: forall c m, corestep_star  c m c m.\n  Proof. intros. exists O. reflexivity. Qed.\n\n  Lemma corestep_star_one: forall c m c' m',\n    corestep  Sem ge c m c' m' -> corestep_star c m c' m'.\n  Proof. intros.\n    exists (S O). exists c'. exists m'. split; trivial. reflexivity.\n  Qed.\n\n  Lemma corestep_plus_split: forall c m c' m',\n    corestep_plus c m c' m' ->\n    exists c'', exists m'', corestep  Sem ge c m c'' m'' /\\\n      corestep_star 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 corestepN.\n\nSection memstepN.\n  Context {G C:Type} (M:@MemSem G C) (g:G).\n\nLemma corestepN_mem n: forall c m c' m', corestepN M g n c m c' m' -> mem_step m m'.\ninduction n; intros; inv H.\n  apply mem_step_refl.\n  destruct H0 as [m'' [CS CSN]]. eapply mem_step_trans.\n  eapply corestep_mem; eassumption.\n  eapply IHn; eassumption.\nQed.\n\nLemma corestep_plus_mem c m c' m' (H:corestep_plus M g c m c' m'): mem_step m m'.\ndestruct H as [n H]. eapply corestepN_mem; eassumption. Qed.\n\nLemma corestep_star_mem c m c' m' (H:corestep_star M g c m c' m'): mem_step m m'.\ndestruct H as [n H]. eapply corestepN_mem; eassumption. Qed.\n\nLemma memsem_preservesN P (HP: memstep_preserve P)\n      n c m c' m' (H: corestepN M g n c m c' m'): P m m'.\napply corestepN_mem in H. apply HP; trivial. Qed.\n\nLemma memsem_preserves_plus P (HP:memstep_preserve P)\n      c m c' m' (H: corestep_plus M g c m c' m'): P m m'.\ndestruct H. apply (memsem_preservesN _ HP) in H; trivial. Qed.\n\nLemma memsem_preserves_star P (HP:memstep_preserve P)\n      c m c' m' (H: corestep_star M g c m c' m'): P m m'.\ndestruct H. apply (memsem_preservesN _ HP) in H; trivial. Qed.\n\nLemma corestepN_fwd n  c m c' m'\n   (CS:corestepN M g n c m c' m'): mem_forward m m'.\nProof.\neapply memsem_preservesN; try eassumption. apply mem_forward_preserve.\nQed.\n\nLemma corestep_plus_fwd c m c' m'\n   (CS:corestep_plus M g c m c' m'): mem_forward m m'.\nProof.\ndestruct CS. eapply corestepN_fwd; eassumption.\nQed.\n\nLemma corestep_star_fwd c m c' m'\n   (CS:corestep_star M g c m c' m'): mem_forward m m'.\nProof.\ndestruct CS. eapply corestepN_fwd; eassumption.\nQed.\n\nLemma corestepN_rdonly n c m c' m'\n    (CS:corestepN M g n c m c' m') b (VB:Mem.valid_block m b): readonly m b m'.\nProof.\neapply (memsem_preservesN _ readonly_preserve'); eassumption.\nQed.\n\nLemma corestep_plus_rdonly c m c' m'\n   (CS:corestep_plus M g c m c' m') b (VB:Mem.valid_block m b): readonly m b m'.\nProof.\ndestruct CS. eapply corestepN_rdonly; eassumption.\nQed.\n\nLemma corestep_star_rdonly c m c' m'\n   (CS:corestep_star M g c m c' m')b (VB:Mem.valid_block m b): readonly m b m'.\nProof.\ndestruct CS. eapply corestepN_rdonly; eassumption.\nQed.\n\nEnd memstepN.\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/semantics_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2692999171646949}}
{"text": "From Hammer Require Import Hammer.\n\nSet Warnings \"-notation-overridden\".\n\nRequire Import Category.Lib.\nRequire Export Category.Structure.Bicartesian.\nRequire Export Category.Structure.Cartesian.Closed.\nRequire Export Category.Structure.Distributive.\n\nGeneralizable All Variables.\nSet Primitive Projections.\nSet Universe Polymorphism.\nUnset Transparent Obligations.\n\nSection BiCCC.\n\nContext {C : Category}.\nContext `{@Cartesian C}.\nContext `{@Cocartesian C}.\nContext `{@Closed C _}.\n\nGlobal Program Instance prod_coprod_l {x y z : C} :\n\n(y + z) × x ≅ y × x + z × x := {\nto   := uncurry (curry inl ▽ curry inr);\nfrom := first inl ▽ first inr\n}.\nNext Obligation.\nrewrite <- !merge_comp.\nrewrite <- eval_first.\nrewrite <- !comp_assoc.\nrewrite <- !first_comp; cat.\nQed.\nNext Obligation.\nrewrite uncurry_comp_r.\napply curry_inj.\nrewrite curry_uncurry.\nrewrite <- merge_comp.\nrewrite <- !curry_comp; cat.\nrewrite <- !curry_id.\nrewrite merge_comp; cat.\nQed.\n\nHint Rewrite @prod_coprod_l : isos.\n\nLemma uncurry_merge {x y z w : C} (f : x ~> y^z) (g : w ~> y^z) :\nuncurry (f ▽ g) ≈ uncurry f ▽ uncurry g ∘ to prod_coprod_l.\nProof. hammer_hook \"BiCCC\" \"BiCCC.uncurry_merge\".\nsimpl.\napply curry_inj; cat.\nrewrite curry_comp; cat.\nrewrite <- merge_comp.\napply merge_inv; split;\nrewrite <- curry_comp; cat.\nQed.\n\nCorollary unmerge_uncurry {x y z w : C} (f : x ~> y^z) (g : w ~> y^z) :\nuncurry f ▽ uncurry g ≈ uncurry (f ▽ g) ∘ from prod_coprod_l.\nProof. hammer_hook \"BiCCC\" \"BiCCC.unmerge_uncurry\".\nrewrite uncurry_merge.\nrewrite <- comp_assoc.\nrewrite iso_to_from; cat.\nQed.\n\nGlobal Program Instance prod_coprod_r {x y z : C} :\n\nx × (y + z) ≅ x × y + x × z := {\nto   := uncurry (curry (inl ∘ swap) ▽ curry (inr ∘ swap)) ∘ swap;\nfrom := second inl ▽ second inr\n}.\nNext Obligation.\nrewrite <- !comp_assoc.\nrewrite <- !merge_comp.\nrewrite <- eval_first.\nrewrite <- !comp_assoc.\nrewrite !swap_second.\nrewrite !(comp_assoc (first _)).\nrewrite <- !first_comp; cat.\nrewrite !(comp_assoc eval).\nrewrite !eval_first; cat.\nrewrite <- !comp_assoc; cat.\nQed.\nNext Obligation.\nrewrite uncurry_merge. simpl.\nrewrite !comp_assoc; cat.\nrewrite <- merge_comp.\nrewrite !comp_assoc; cat.\nrewrite <- !swap_first.\nrewrite merge_comp.\nrewrite <- !comp_assoc.\napply swap_inj_l, swap_inj_r.\nrewrite comp_assoc.\nrewrite swap_invol, id_left, id_right.\nrewrite <- !comp_assoc.\nrewrite swap_invol, id_right.\nrewrite uncurry_comp_r.\nrewrite <- merge_comp.\napply curry_inj.\nrewrite curry_uncurry.\nrewrite <- !curry_comp; cat.\nrewrite <- !curry_id.\nrewrite merge_comp; cat.\nQed.\n\nHint Rewrite @prod_coprod_r : isos.\n\nGlobal Program Instance exp_coprod {x y z : C} :\nx^(y + z) ≅ x^y × x^z := {\nto   := curry (eval ∘ second inl) △ curry (eval ∘ second inr);\nfrom := curry (uncurry exl ▽ uncurry exr ∘ to prod_coprod_r)\n}.\nNext Obligation.\nrewrite <- fork_comp.\nrewrite <- fork_exl_exr.\napply fork_inv; split;\nrewrite curry_comp_l;\nrewrite <- comp_assoc;\nrewrite <- first_second;\nrewrite comp_assoc;\nrewrite eval_first;\nrewrite uncurry_curry;\nrewrite <- !comp_assoc;\nrewrite swap_second;\nrewrite curry_comp;\nrewrite <- !eval_first;\nrewrite <- comp_assoc;\nrewrite (comp_assoc (first _));\nrewrite <- first_comp; cat;\nrewrite !eval_first;\nrewrite (comp_assoc eval);\nrewrite !eval_first; cat;\nrewrite <- comp_assoc; cat;\nrewrite <- curry_comp; cat.\nQed.\nNext Obligation.\nremember (_ △ _) as p.\nenough (∀ {w : C} (f g : w ~> x^(y + z)), p ∘ f ≈ p ∘ g -> f ≈ g) as HA.\napply HA.\nrewrite comp_assoc.\nrewrite Heqp.\nrewrite exp_coprod_obligation_1; cat.\nintros ??? e.\nrewrite Heqp in e.\nrewrite <- !fork_comp in e.\napply fork_inv in e.\ndestruct e as [HA HB].\nrewrite !curry_comp_l in HA.\nrewrite !curry_comp_l in HB.\napply curry_inj in HA.\napply curry_inj in HB.\nrewrite <- !comp_assoc in HA.\nrewrite <- !comp_assoc in HB.\nrewrite <- !first_second in HA.\nrewrite <- !first_second in HB.\nrewrite !comp_assoc in HA.\nrewrite !comp_assoc in HB.\napply uncurry_inj.\nrewrite <- !eval_first.\nenough (∀ {w : C} (f g : w × (y + z) ~> x),\nf ∘ second inl ≈ g ∘ second inl ->\nf ∘ second inr ≈ g ∘ second inr -> f ≈ g) as HC.\nexact (HC _ _ _ HA HB).\nintros ? h i HD HE.\nunfold second in HD, HE.\nrewrite <- id_right.\nrewrite <- (id_right i).\nrewrite <- (iso_from_to prod_coprod_r).\nsimpl.\nrewrite !comp_assoc.\nrewrite <- !merge_comp.\nrewrites.\nreflexivity.\nQed.\n\nHint Rewrite @exp_coprod : isos.\n\nContext `{@Initial C}.\n\nGlobal Program Instance prod_zero_l {x : C} :\n0 × x ≅ 0 := {\nto   := uncurry zero;\nfrom := zero\n}.\nNext Obligation. apply curry_inj; simpl; cat. Qed.\n\nHint Rewrite @prod_zero_l : isos.\n\nGlobal Program Instance prod_zero_r {x : C} :\nx × 0 ≅ 0 := {\nto   := uncurry zero ∘ swap;\nfrom := zero\n}.\nNext Obligation. apply swap_inj_r, curry_inj; simpl; cat. Qed.\n\nHint Rewrite @prod_zero_r : isos.\n\nContext `{@Terminal C}.\n\nGlobal Program Instance exp_zero {x : C} :\nx^0 ≅ 1 := {\nto   := one;\nfrom := curry (zero ∘ to prod_zero_r)\n}.\nNext Obligation.\napply uncurry_inj.\napply swap_inj_r.\napply curry_inj; simpl; cat.\nQed.\n\nEnd BiCCC.\n\nProgram Instance BiCCC_Distributive {C : Category}\n`{@Cartesian C} `{@Cocartesian C} `{@Closed C _} `{@Initial C} :\n@Distributive C _ _ _.\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/category-theory/BiCCC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891307678321, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.269202843814604}}
{"text": "Require Import Mtac2.Mtac2.\n\nGoal True.\nMProof.\n  (M.evar nat;; M.evar bool;; M.ret _)%MC. (* FIXME: why are all evars shelved when we do this in the tactic monad? *)\n  Unshelve.\n  M.ret _.\n  Unshelve.\n  M.ret _.\n  Unshelve.\n  M.ret true.\n  Unshelve.\n  M.ret I.\n  M.ret 0.\nQed.\n\nDefinition ThrowANat (n : nat) : Exception. exact exception. Qed.\nDefinition test n : M nat :=\n  mmatch n with\n  | [? n'] S n' => M.raise (ThrowANat n')\n  | _ => M.ret 0\n  end.\n\nGoal True.\nMProof.\n  M.mtry' (test 1;; M.ret I) (fun _=> M.ret I).\nQed.\n\nGoal {n:nat| n = n}.\nMProof.\n  (mtry test 1;; M.raise exception\n  with [? n'] ThrowANat n' => M.ret (exist _ n' _) end)%MC.\nAbort.\n\n\nGoal {n:nat| n = n}.\nMProof.\n  (mmatch 2 + 4 with\n  | [? n] n + n => M.ret (exist _ (n + n) eq_refl)\n  | [? n] n + n => M.ret (exist _ (n + n) eq_refl)\n  | [? n] n + n => M.ret (exist _ (n + n) eq_refl)\n  | [? n] n + n => M.ret (exist _ (n + n) eq_refl)\n  | [? n m] n + m => M.ret (exist (fun n=>n=n) (n + m) eq_refl)\n  end)%MC.\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/goal_reordering.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.26920284381460396}}
{"text": "Require Import Ctl.Paths.\nRequire Import Ctl.Definition.\nRequire Import Ctl.Basic.\nOpen Scope tprop_scope.\n\nRequire Import Setoid.\nRequire Import Glib.Glib.\n\nLtac tentails :=\n  match goal with \n  | |- ?R @?s ⊨ ⟨?P⟩ => change_no_check (P s)\n  end.\n\nTactic Notation \"tentails!\" :=\n  cbn;\n  repeat match goal with \n  | |- ?R @?s ⊨ ?P => unfold P\n  end;\n  change_no_check (?R @?s ⊨ ⟨?P⟩) with (P s);\n  cbn.\n\nTactic Notation \"tentails\" \"in\" hyp(H) :=\n  change (?R @?s ⊨ ⟨?P⟩) with (P s) in H.\n\nTactic Notation \"tentails!\" \"in\" hyp(H) :=\n  cbn in H;\n  repeat match type of H with \n  | ?R @?s ⊨ ?P => unfold P in H\n  end;\n  progress change (?R @?s ⊨ ⟨?P⟩) with (P s) in H;\n  cbn in H.\n\nTactic Notation \"tentails\" \"in\" \"*\" :=\n  tentails;\n  repeat match goal with \n  | H : _ |- _ => tentails in H\n  end.\n\nTactic Notation \"tentails!\" \"in\" \"*\" :=\n  tentails!;\n  repeat match goal with \n  | H : _ |- _ => tentails! in H\n  end.\n\n\n\n(*\nTactic Notation \"unfold_timpl\" :=\n  progress change_no_check (?R @?s ⊨ ?p ⟶ ?q) with (R @s ⊨ p -> R @s ⊨ q).\nTactic Notation \"unfold_timpl\" \"in\" hyp(H) :=\n  progress change_no_check (?R @?s ⊨ ?p ⟶ ?q) with (R @s ⊨ p -> R @s ⊨ q) in H.\n\nTactic Notation \"unfold_tnot\" := \n  progress change_no_check (?R @?s ⊨ ¬?P) with (R @s ⊭ P).\nTactic Notation \"unfold_tnot\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ ¬?P) with (R @s ⊭ P) in H.\n\nTactic Notation \"unfold_tconj\" := \n  progress change_no_check (?R @?s ⊨ ?P ∧ ?Q) with (R @s ⊨ P /\\ R @s ⊨ Q).\nTactic Notation \"unfold_tconj\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ ?P ∧ ?Q) with (R @s ⊨ P /\\ R @s ⊨ Q) in H.\n\nTactic Notation \"unfold_tbiimpl\" := \n  progress change_no_check (?R @?s ⊨ ?P ⟷ ?Q) with (R @s ⊨ P <-> R @s ⊨ Q).\nTactic Notation \"unfold_tbiimpl\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ ?P ⟷ ?Q) with (R @s ⊨ P <-> R @s ⊨ Q) in H.\n\nTactic Notation \"unfold_AX\" := \n  progress change_no_check (?R @?s ⊨ AX ?P) with (forall s', R s s' -> R @s' ⊨ P).\nTactic Notation \"unfold_AX\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ AX ?P) with (forall s', R s s' -> R @s' ⊨ P) in H.\n\nTactic Notation \"unfold_AG\" := \n  progress change_no_check (?R @?s ⊨ AG ?P) with \n    (forall n (p: path R n s) s', in_path s' p -> R @s' ⊨ P).\nTactic Notation \"unfold_AG\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ AG ?P) with \n    (forall n (p: path R n s) s', in_path s' p -> R @s' ⊨ P) in H.\n*)\n\nTactic Notation \"unfold_timpl\" :=\n  progress change_no_check (?R @?s ⊨ ?p ⟶ ?q) with (R @s ⊨ p -> R @s ⊨ q) +\n  rewrite rew_timpl +\n  setoid_rewrite rew_timpl.\nTactic Notation \"unfold_timpl\" \"in\" hyp(H) :=\n  progress change_no_check (?R @?s ⊨ ?p ⟶ ?q) with (R @s ⊨ p -> R @s ⊨ q) in H +\n  rewrite rew_timpl in H +\n  setoid_rewrite rew_timpl in H.\n\nTactic Notation \"unfold_tnot\" :=\n  progress change_no_check (?R @?s ⊨ ¬?P) with (R @s ⊭ P) +\n  rewrite rew_tnot +\n  setoid_rewrite rew_tnot.\nTactic Notation \"unfold_tnot\" \"in\" hyp(H) :=\n  progress change_no_check (?R @?s ⊨ ¬?P) with (R @s ⊭ P) in H +\n  rewrite rew_tnot in H +\n  setoid_rewrite rew_tnot in H.\n\nTactic Notation \"unfold_tconj\" := \n  progress change_no_check (?R @?s ⊨ ?P ∧ ?Q) with (R @s ⊨ P /\\ R @s ⊨ Q) +\n  rewrite rew_tconj +\n  setoid_rewrite rew_tconj.\nTactic Notation \"unfold_tconj\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ ?P ∧ ?Q) with (R @s ⊨ P /\\ R @s ⊨ Q) in H +\n  rewrite rew_tconj in H +\n  setoid_rewrite rew_tconj in H.\n\nTactic Notation \"unfold_tdisj\" := \n  progress change_no_check (?R @?s ⊨ ?P ∨ ?Q) with (R @s ⊨ P \\/ R @s ⊨ Q) +\n  rewrite rew_tdisj +\n  setoid_rewrite rew_tdisj.\nTactic Notation \"unfold_tdisj\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ ?P ∨ ?Q) with (R @s ⊨ P ∨ R @s ⊨ Q) in H +\n  rewrite rew_tdisj in H +\n  setoid_rewrite rew_tdisj in H.\n\nTactic Notation \"unfold_tbiimpl\" := \n  progress change_no_check (?R @?s ⊨ ?P ⟷ ?Q) with (R @s ⊨ P <-> R @s ⊨ Q) +\n  rewrite rew_tbiimpl +\n  setoid_rewrite rew_tbiimpl.\nTactic Notation \"unfold_tbiimpl\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ ?P ⟷ ?Q) with (R @s ⊨ P <-> R @s ⊨ Q) in H +\n  rewrite rew_tbiimpl in H +\n  setoid_rewrite rew_tbiimpl in H.\n\nTactic Notation \"unfold_tlift\" := \n  progress change_no_check (?R @?s ⊨ ⟨?P⟩) with (P s) +\n  rewrite rew_tlift +\n  setoid_rewrite rew_tlift.\nTactic Notation \"unfold_tlift\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ ⟨?P⟩) with (P s) in H +\n  rewrite rew_tlift in H +\n  setoid_rewrite rew_tlift in H.\n\nTactic Notation \"unfold_AX\" := \n  progress change_no_check (?R @?s ⊨ AX ?P) with (forall s', R s s' -> R @s' ⊨ P) +\n  rewrite rew_AX +\n  setoid_rewrite rew_AX.\nTactic Notation \"unfold_AX\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ AX ?P) with (forall s', R s s' -> R @s' ⊨ P) in H +\n  rewrite rew_AX in H +\n  setoid_rewrite rew_AX in H.\n\nTactic Notation \"unfold_EX\" := \n  progress change_no_check (?R @?s ⊨ EX ?P) with (exists s', R s s' /\\ R @s' ⊨ P) +\n  rewrite rew_EX +\n  setoid_rewrite rew_EX.\nTactic Notation \"unfold_EX\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ EX ?P) with (exists s', R s s' /\\ R @s' ⊨ P) in H +\n  rewrite rew_EX in H +\n  setoid_rewrite rew_EX in H.\n\nTactic Notation \"unfold_AG\" := \n  progress change_no_check (?R @?s ⊨ AG ?P) with \n    (forall (p: path R s) s', in_path s' p -> R @s' ⊨ P) +\n  rewrite rew_AG +\n  setoid_rewrite rew_AG.\nTactic Notation \"unfold_AG\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ AG ?P) with \n    (forall (p: path R s) s', in_path s' p -> R @s' ⊨ P) in H +\n  rewrite rew_AG in H +\n  setoid_rewrite rew_AG in H.\n\nTactic Notation \"unfold_EG\" := \n  progress change_no_check (?R @?s ⊨ EG ?P) with \n    (exists p: path R s, forall s', in_path s' p -> R @s' ⊨ P) +\n  rewrite rew_EG +\n  setoid_rewrite rew_EG.\nTactic Notation \"unfold_EG\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ EG ?P) with \n    (exists p: path R s, forall s', in_path s' p -> R @s' ⊨ P) in H +\n  rewrite rew_EG in H +\n  setoid_rewrite rew_EG in H.\n\nTactic Notation \"unfold_AF\" := \n  progress change_no_check (?R @?s ⊨ AF ?P) with \n    (forall p: path R s, exists s', in_path s' p /\\ R @s' ⊨ P) +\n  rewrite rew_AF +\n  setoid_rewrite rew_AF.\nTactic Notation \"unfold_AF\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ AF ?P) with \n    (forall p: path R s, exists s', in_path s' p /\\ R @s' ⊨ P) in H +\n  rewrite rew_AF in H +\n  setoid_rewrite rew_AF in H.\n\nTactic Notation \"unfold_EF\" := \n  progress change_no_check (?R @?s ⊨ EF ?P) with \n    (exists (p: path R s) s', in_path s' p /\\ R @s' ⊨ P) +\n  rewrite rew_EF +\n  setoid_rewrite rew_EF.\nTactic Notation \"unfold_EF\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ EF ?P) with \n    (exists (p: path R s) s', in_path s' p /\\ R @s' ⊨ P) in H +\n  rewrite rew_EF in H +\n  setoid_rewrite rew_EF in H.\n\nTactic Notation \"unfold_AU\" := \n  progress change_no_check (?R @?s ⊨ A[?P U ?Q]) with \n    (forall p: path R s, exists sQ i,\n      in_path_at sQ i p /\\ \n      (forall sP, in_path_before sP i p -> R @sP ⊨ P) /\\ \n      R @sQ ⊨ Q) +\n  rewrite rew_AU +\n  setoid_rewrite rew_AU.\nTactic Notation \"unfold_AU\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ A[?P U ?Q]) with \n    (forall p: path R s, exists sQ i,\n      in_path_at sQ i p /\\ \n      (forall sP, in_path_before sP i p -> R @sP ⊨ P) /\\ \n      R @sQ ⊨ Q) in H +\n  rewrite rew_AU in H +\n  setoid_rewrite rew_AU in H.\n\nTactic Notation \"unfold_EU\" := \n  progress change_no_check (?R @?s ⊨ E[?P U ?Q]) with \n    (exists (p: path R s) sQ i,\n      in_path_at sQ i p /\\ \n      (forall sP, in_path_before sP i p -> R @sP ⊨ P) /\\ \n      R @sQ ⊨ Q) +\n  rewrite rew_EU +\n  setoid_rewrite rew_EU.\nTactic Notation \"unfold_EU\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ E[?P U ?Q]) with \n    (exists (p: path R s) sQ i,\n      in_path_at sQ i p /\\ \n      (forall sP, in_path_before sP i p -> R @sP ⊨ P) /\\ \n      R @sQ ⊨ Q) in H +\n  rewrite rew_EU in H +\n  setoid_rewrite rew_EU in H.\n\nTactic Notation \"unfold_AW\" := \n  progress change_no_check (?R @?s ⊨ A[?P W ?Q]) with \n    (forall p: path R s,\n      (forall s', in_path s' p -> R @s' ⊨ P ∧ ¬Q) \\/\n      (exists sQ i,\n        in_path_at sQ i p /\\ \n        (forall sP, in_path_before sP i p -> R @sP ⊨ P) /\\ \n        R @sQ ⊨ Q)) +\n  rewrite rew_AW +\n  setoid_rewrite rew_AW.\nTactic Notation \"unfold_AW\" \"in\" hyp(H) := \n  progress change_no_check (?R @?s ⊨ A[?P W ?Q]) with \n    (forall p: path R s,\n      (forall s', in_path s' p -> R @s' ⊨ P ∧ ¬Q) \\/\n      (exists sQ i,\n        in_path_at sQ i p /\\ \n        (forall sP, in_path_before sP i p -> R @sP ⊨ P) /\\ \n        R @sQ ⊨ Q)) in H +\n  rewrite rew_AW in H +\n  setoid_rewrite rew_AW in H.\n \n\n(* tintro - intro a timpl *)\n\nTactic Notation \"tintro\" := \n  match goal with\n  | |- _ @_ ⊨ ¬_ => unfold_tnot; intro\n  | |- _ @_ ⊨ _ ⟶ _ => unfold_timpl; intro\n  end.\n\nTactic Notation \"tintro\" ident(x) := \n  match goal with\n  | |- _ @_ ⊨ ¬_ => unfold_tnot; intro x\n  | |- _ @_ ⊨ _ ⟶ _ => unfold_timpl; intro x\n  end.\n\nTactic Notation \"tintros\" :=\n  repeat tintro.\nTactic Notation \"tintros\" ident(x1) :=\n  tintro x1.\nTactic Notation \"tintros\" ident(x1) ident(x2) :=\n  tintro x1; tintros x2.\nTactic Notation \"tintros\" ident(x1) ident(x2) ident(x3) :=\n  tintro x1; tintros x2 x3.\nTactic Notation \"tintros\" ident(x1) ident(x2) ident(x3) ident(x4) :=\n  tintro x1; tintros x2 x3 x4.\nTactic Notation \"tintros\" ident(x1) ident(x2) ident(x3) ident(x4) ident(x5) :=\n  tintro x1; tintros x2 x3 x4 x5.\nTactic Notation \"tintros\" ident(x1) ident(x2) ident(x3) ident(x4) ident(x6) :=\n  tintro x1; tintros x2 x3 x4 x5 x6.\n\n\n(* tsimpl - simple a tprop *)\n\nTactic Notation \"tsimpl_step\" :=\n  unfold_timpl +\n  unfold_tbiimpl +\n  unfold_tnot +\n  unfold_AX +\n  unfold_EX +\n  unfold_AG +\n  unfold_EG +\n  unfold_AF +\n  unfold_EF +\n  unfold_AU + \n  unfold_EU +\n  unfold_AW.\n\nTactic Notation \"tsimpl_step\" \"in\" hyp(H) :=\n  unfold_timpl in H +\n  unfold_tbiimpl in H +\n  unfold_tnot in H +\n  unfold_AX in H +\n  unfold_EX in H +\n  unfold_AG in H +\n  unfold_EG in H +\n  unfold_AF in H +\n  unfold_EF in H +\n  unfold_AU in H +\n  unfold_EU in H + \n  unfold_AW in H.\n\nTactic Notation \"tsimpl\" := repeat tsimpl_step.\nTactic Notation \"tsimpl\" \"in\" hyp(H) := repeat tsimpl_step in H.\nTactic Notation \"tsimpl\" \"in\" \"*\" :=\n  try tsimpl;\n  repeat match goal with \n  | H: _ @_ ⊨ _ |- _ => tsimpl in H\n  end.\n\n(* tapply: carefully unfolds TProp hypothesis just enough to use apply *)\n\nLtac _tapply_unfold_step H :=\n  match type of H with \n  | _ @_ ⊨ _ ⟶ _ => \n      unfold_timpl in H\n  | _ @_ ⊨ ¬ _ =>\n      unfold_tnot in H\n  | _ @_ ⊨ _ ⟷ _ =>\n      unfold_tbiimpl in H\n  | _ @_ ⊨ AX _ =>\n      unfold_AX in H\n  | _ @_ ⊨ AG _ => \n      unfold_AG in H\n  end + \n  unfold_timpl in H +\n  unfold_tnot in H +\n  unfold_tbiimpl in H +\n  unfold_AX in H +\n  unfold_AG in H.\n\nLtac _tapply_aux H :=\n  apply H + (_tapply_unfold_step H; _tapply_aux H).\n\nLtac _tapply_aux_in H H2 :=\n  apply H in H2 + (_tapply_unfold_step H; _tapply_aux_in H H2).\n\nLtac _etapply_aux H :=\n  eapply H + (_tapply_unfold_step H; _etapply_aux H).\n\nLtac _etapply_aux_in H H2 :=\n  eapply H in H2 + (_tapply_unfold_step H; _etapply_aux_in H H2).\n\n\nTactic Notation \"tapply\" uconstr(c) :=\n  let Htemp := fresh in \n  eset (Htemp := c);\n  _tapply_aux Htemp;\n  clear Htemp.\n\nTactic Notation \"tapply\" uconstr(c) \"in\" hyp(H) :=\n  let Htemp := fresh in \n  eset (Htemp := c);\n  _tapply_aux_in Htemp H;\n  clear Htemp.\n\nTactic Notation \"etapply\" uconstr(c) :=\n  let Htemp := fresh in \n  eset (Htemp := c);\n  _etapply_aux Htemp;\n  clear Htemp.\n\nTactic Notation \"etapply\" uconstr(c) \"in\" hyp(H) :=\n  let Htemp := fresh in \n  eset (Htemp := c);\n  _etapply_aux_in Htemp H;\n  clear Htemp.\n\nTactic Notation \"tapplyc\" hyp(H) :=\n  tapply H; clear H.\nTactic Notation \"tapplyc\" hyp(H) \"in\" hyp(H2) :=\n  tapply H in H2; clear H.\nTactic Notation \"etapplyc\" hyp(H) :=\n  etapply H; clear H.\nTactic Notation \"etapplyc\" hyp(H) \"in\" hyp(H2) :=\n  etapply H in H2; clear H.\n\nClose Scope tprop_scope.", "meta": {"author": "gjurgensen", "repo": "thesis", "sha": "fee5e9e2ba728f3707eee7ad9d90837c25cf7764", "save_path": "github-repos/coq/gjurgensen-thesis", "path": "github-repos/coq/gjurgensen-thesis/thesis-fee5e9e2ba728f3707eee7ad9d90837c25cf7764/Ctl/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.26920284381460396}}
{"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 Equivalence.\nRequire Import Morphisms.\nRequire Import Setoid.\nRequire Import EquivDec.\nRequire Import Program.\nRequire Import String.\nRequire Import List.\nRequire Import Arith.\nRequire Import Utils.\nRequire Import DataRuntime.\nRequire Import DData.\nRequire Import DDataNorm.\nRequire Import DNNRCBase.\n\nSection DNNRCBaseEq.\n  Context {fruntime:foreign_runtime}.\n  Context {A plug_type:Set}.\n  Context {eqdec:EqDec A eq}.\n  Context {plug:AlgPlug plug_type}.\n\n  (** Equivalence between expressions in the \n      Distributed Nested Relational Calculus *)\n\n  Definition dnnrc_base_eq (e1 e2:@dnnrc_base _ A plug_type) : Prop :=\n    forall (h:brand_relation_t) (dcenv denv:dbindings),\n      Forall (ddata_normalized h) (map snd dcenv) ->\n      Forall (ddata_normalized h) (map snd denv) ->\n      dnnrc_base_eval h dcenv denv e1 = dnnrc_base_eval h dcenv denv e2.\n\n  Global Instance dnnrc_base_equiv : Equivalence dnnrc_base_eq.\n  Proof.\n    constructor.\n    - unfold Reflexive, dnnrc_base_eq.\n      intros; reflexivity.\n    - unfold Symmetric, dnnrc_base_eq.\n      intros; rewrite (H _ dcenv denv) by trivial; reflexivity.\n    - unfold Transitive, dnnrc_base_eq.\n      intros; rewrite (H _ dcenv denv) by trivial;\n      rewrite (H0 _ dcenv denv) by trivial; reflexivity.\n  Qed.\n\n  (* all the dnnrc_base constructors are proper wrt. equivalence *)\n\n  (* DNNRCGetConstant *)\n  Global Instance dgetconstant_proper : Proper (eq ==> eq ==> dnnrc_base_eq) DNNRCGetConstant.\n  Proof.\n    unfold Proper, respectful, dnnrc_base_eq.\n    intros; subst; reflexivity.\n  Qed.\n\n  (* DNNRCVar *)\n  Global Instance dvar_proper : Proper (eq ==> eq ==> dnnrc_base_eq) DNNRCVar.\n  Proof.\n    unfold Proper, respectful, dnnrc_base_eq.\n    intros; subst; reflexivity.\n  Qed.\n\n  (* DNNRCConst *)\n  \n  Global Instance dconst_proper : Proper (eq ==> eq ==> dnnrc_base_eq) DNNRCConst.\n  Proof.\n    unfold Proper, respectful, dnnrc_base_eq.\n    intros; subst; reflexivity.\n  Qed.\n\n  (* DNNRCBinop *)\n  \n  Global Instance dbinary_op_proper : Proper (eq ==> binary_op_eq ==> dnnrc_base_eq ==> dnnrc_base_eq ==> dnnrc_base_eq) DNNRCBinop.\n  Proof.\n    unfold Proper, respectful, dnnrc_base_eq.\n    intros; simpl. subst.\n    rewrite H1 by trivial.\n    rewrite H2 by trivial.\n    case_eq (dnnrc_base_eval h dcenv denv y1);\n      case_eq (dnnrc_base_eval h dcenv denv y2); intros; simpl; trivial.\n    destruct d0; destruct d; try reflexivity; simpl.\n    rewrite H0; [reflexivity| | ].\n    apply (dnnrc_base_eval_normalized_local h dcenv denv y1); try assumption.\n    apply (dnnrc_base_eval_normalized_local h dcenv denv y1); try assumption.\n  Qed.\n\n  (* DNNRCUnnop *)\n  \n  Global Instance dunary_op_proper : Proper (eq ==> unary_op_eq ==> dnnrc_base_eq ==> dnnrc_base_eq) DNNRCUnop.\n  Proof.\n    unfold Proper, respectful, dnnrc_base_eq.\n    intros; simpl. subst.\n    rewrite H1 by trivial.\n    case_eq (dnnrc_base_eval h dcenv denv y1); simpl; trivial; intros.\n    destruct d; try reflexivity; simpl.\n    rewrite H0; [reflexivity| ].\n    apply (dnnrc_base_eval_normalized_local h dcenv denv y1); try assumption.\n  Qed.\n    \n  (* DNNRCLet *)\n  \n  Global Instance dlet_proper : Proper (eq ==> eq ==> dnnrc_base_eq ==> dnnrc_base_eq ==> dnnrc_base_eq) DNNRCLet.\n  Proof.\n    unfold Proper, respectful, dnnrc_base_eq.\n    intros; simpl. rewrite H0; clear H0; rewrite H1 by trivial; clear H1.\n    case_eq (dnnrc_base_eval h dcenv denv y1); simpl; trivial; intros.\n    rewrite H2; eauto.\n    constructor; eauto.\n    simpl.\n    eapply (dnnrc_base_eval_normalized h dcenv denv y1); eauto.\n  Qed.\n\n  (* DNNRCFor *)\n\n  Hint Resolve data_normalized_dcoll_in : qcert.\n\n  Global Instance dfor_proper : Proper (eq ==> eq ==> dnnrc_base_eq ==> dnnrc_base_eq ==> dnnrc_base_eq) DNNRCFor.\n  Proof.\n    unfold Proper, respectful, dnnrc_base_eq.\n    intros; simpl. rewrite H1 by trivial; clear H1. subst.\n    case_eq (dnnrc_base_eval h dcenv denv y1); simpl; trivial; intros.\n    destruct d; try reflexivity; simpl.\n    { destruct d; try reflexivity; simpl.\n      f_equal.\n      apply lift_map_ext; intros.\n      rewrite H2; simpl; eauto.\n      constructor; [|assumption].\n      assert (ddata_normalized h (Dlocal (dcoll l))).\n      - eapply (dnnrc_base_eval_normalized _ dcenv denv); eauto.\n      - inversion H1; subst; clear H1.\n        econstructor.\n        inversion H6; subst; clear H6.\n        rewrite Forall_forall in H5.\n        auto. }\n    { f_equal.\n      apply lift_map_ext; intros.\n      rewrite H2; simpl; eauto.\n      constructor; [|assumption].\n      assert (ddata_normalized h (Ddistr l)).\n      - eapply (dnnrc_base_eval_normalized _ dcenv denv); eauto.\n      - inversion H1; subst; clear H1.\n        constructor.\n        rewrite Forall_forall in H6.\n        auto. }\n  Qed.\n\n  (* DNNRCIf *)\n  \n  Global Instance dif_proper : Proper (eq ==> dnnrc_base_eq ==> dnnrc_base_eq ==> dnnrc_base_eq ==> dnnrc_base_eq) DNNRCIf.\n  Proof.\n    unfold Proper, respectful, dnnrc_base_eq.\n    intros; simpl. subst. rewrite H0 by trivial; clear H0.\n    case_eq (dnnrc_base_eval h dcenv denv y0); simpl; trivial; intros.\n    destruct d; try reflexivity; simpl.\n    destruct d; try reflexivity; simpl.\n    destruct b; eauto.\n  Qed.\n\n  (* DNNRCEither *)\n  Global Instance deither_proper : Proper (eq ==> dnnrc_base_eq ==> eq ==> dnnrc_base_eq ==> eq ==> dnnrc_base_eq ==> dnnrc_base_eq) DNNRCEither.\n  Proof.\n    unfold Proper, respectful, dnnrc_base_eq.\n    intros; simpl. subst.\n    rewrite H0 by trivial.\n    match_case; intros ? eqq1. match_destr.\n    - apply H2; simpl; eauto.\n      rewrite Forall_forall; intros.\n      inversion H; subst.\n      unfold olift, checkLocal in eqq1.\n      case_eq (dnnrc_base_eval h dcenv denv y0); intros; rewrite H1 in eqq1; try congruence;\n      destruct d0; try congruence; inversion eqq1; subst.\n      assert (ddata_normalized h (Dlocal (dleft d))).\n      apply (@dnnrc_base_eval_normalized _ _ _ h dcenv _ denv y0); assumption.\n      inversion H3; subst; clear H3.\n      inversion H8; subst; clear H8.\n      constructor; assumption.\n      rewrite Forall_forall in H6. auto.\n    - apply H4; simpl; eauto.\n      rewrite Forall_forall; intros.\n      inversion H; subst.\n      unfold olift, checkLocal in eqq1.\n      case_eq (dnnrc_base_eval h dcenv denv y0); intros; rewrite H1 in eqq1; try congruence;\n      destruct d0; try congruence; inversion eqq1; subst.\n      assert (ddata_normalized h (Dlocal (dright d))).\n      apply (@dnnrc_base_eval_normalized _ _ _ h dcenv plug denv y0); assumption.\n      inversion H3; subst; clear H3.\n      inversion H8; subst; clear H8.\n      constructor; assumption.\n      rewrite Forall_forall in H6. auto.\n  Qed.\n\n  (* DNNRCGroupBy *)\n  Global Instance dgroupby_proper : Proper (eq ==> eq ==> eq ==> dnnrc_base_eq ==>dnnrc_base_eq) DNNRCGroupBy.\n  Proof.\n    unfold Proper, respectful, dnnrc_base_eq.\n    intros; simpl; subst.\n    trivial.\n  Qed.\n\n  (* DNNRCCollect *)\n  Global Instance dcollect_proper : Proper (eq ==> dnnrc_base_eq ==> dnnrc_base_eq) DNNRCCollect.\n  Proof.\n    unfold Proper, respectful, dnnrc_base_eq.\n    intros; simpl. subst.\n    rewrite H0 by trivial.\n    reflexivity.\n  Qed.\n    \n  (* DNNRCDispatch *)\n  Global Instance ddispatch_proper : Proper (eq ==> dnnrc_base_eq ==> dnnrc_base_eq) DNNRCDispatch.\n  Proof.\n    unfold Proper, respectful, dnnrc_base_eq.\n    intros; simpl. subst.\n    rewrite H0 by trivial.\n    reflexivity.\n  Qed.\n\n  Global Instance dalg_proper : Proper (eq ==> eq ==> Forall2 (fun n1 n2  => fst n1 = fst n2 /\\ dnnrc_base_eq (snd n1) (snd n2)) ==> dnnrc_base_eq) DNNRCAlg.\n  Proof.\n    unfold Proper, respectful, dnnrc_base_eq.\n    intros; simpl; subst.\n    cut ((map\n         (fun x : string * @dnnrc_base _ A plug_type =>\n          match dnnrc_base_eval h dcenv denv (snd x) with\n          | Some (Dlocal _) => None\n          | Some (Ddistr coll) => Some (fst x, coll)\n          | None => None\n          end) x1) = (map\n         (fun x : string * @dnnrc_base _ A plug_type =>\n          match dnnrc_base_eval h dcenv denv (snd x) with\n          | Some (Dlocal _) => None\n          | Some (Ddistr coll) => Some (fst x, coll)\n          | None => None\n          end) y1)); [intros eqq; rewrite eqq; trivial | ].\n    dependent induction H1; simpl; trivial.\n    rewrite IHForall2 by trivial.\n    destruct H as [eqq1 eqq2].\n    rewrite eqq1, eqq2 by trivial.\n    trivial.\n  Qed.\n\nEnd DNNRCBaseEq.\n\nNotation \"X ≡ᵈ Y\" := (dnnrc_base_eq X Y) (at level 90) : dnnrc_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/DNNRC/Lang/DNNRCBaseEq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376236, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2692028372180259}}
{"text": "Require Import AutoSep Wrap StringOps XmlLex SinglyLinkedList Malloc.\n\nSet Implicit Arguments.\n\n\n(** * Definition of XML search language *)\n\nInductive pat :=\n\n(* Match CDATA constant. *)\n| Cdata (const : string)\n\n(* Record CDATA at this position via two variables. *)\n| Var (start len : string)\n\n| TreeVar (start len : string)\n(* Like [Var], but grabs a whole XML tree *)\n\n(* Match a specific tag at this level in the XML tree, then continue into its children. *)\n| Tag (tag : string) (inner : pat)\n\n(* Match two different patterns at this level of the tree. *)\n| Both (p1 p2 : pat)\n\n(* Match one pattern and then another in the part of the XML tree right after the match of the first. *)\n| Ordered (p1 p2 : pat).\n\n(** Which program variables appear free in a pattern? *)\nFixpoint freeVar (p : pat) (x : string) : Prop :=\n  match p with\n    | Cdata _ => False\n    | Var start len => x = start \\/ x = len\n    | TreeVar start len => x = start \\/ x = len\n    | Tag _ inner => freeVar inner x\n    | Both p1 p2 => freeVar p1 x \\/ freeVar p2 x\n    | Ordered p1 p2 => freeVar p1 x \\/ freeVar p2 x\n  end.\n\n(** Does the pattern avoid:\n  * - double-binding a program variable?\n  * - mentioning a huge string constant as a tag name? *)\nFixpoint wf (p : pat) : Prop :=\n  match p with\n    | Cdata const => goodSize (String.length const)\n    | Var start len => start <> len\n    | TreeVar start len => start <> len\n    | Tag tag inner => goodSize (String.length tag) /\\ wf inner\n    | Both p1 p2 => wf p1 /\\ wf p2 /\\ (forall x, freeVar p1 x -> ~freeVar p2 x)\n    | Ordered p1 p2 => wf p1 /\\ wf p2 /\\ (forall x, freeVar p1 x -> ~freeVar p2 x)\n  end%type.\n\n(** All pairs of start-length variables in a pattern *)\nFixpoint allCdatas (p : pat) : list (string * string) :=\n  match p with\n    | Cdata _ => nil\n    | Var start len => (start, len) :: nil\n    | TreeVar start len => (start, len) :: nil\n    | Tag _ inner => allCdatas inner\n    | Both p1 p2 => allCdatas p2 ++ allCdatas p1\n    | Ordered p1 p2 => allCdatas p2 ++ allCdatas p1\n  end.\n\n\n(** * Compiling patterns into Bedrock chunks *)\n\nSection Pat.\n  Variable A : Type.\n  Variables invPre : A -> vals -> HProp.\n  Variables invPost : A -> vals -> W -> HProp.\n\n  (* Do all start-length pairs in a list denote valid spans in a string of length \"len\"? *)\n  Definition 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\n  (* Are all saved positions in a list valid pointers within a string of a given length? *)\n  Definition stackOk (ls : list W) (len : W) :=\n    List.Forall (fun x => x <= len) ls.\n\n  (* Precondition and postcondition of search *)\n  Definition invar :=\n    Al a : A, Al bs, Al ls,\n    PRE[V] array8 bs (V \"buf\") * xmlp (V \"len\") (V \"lex\") * sll ls (V \"stack\") * mallocHeap 0\n      * [| length bs = wordToNat (V \"len\") |] * [| stackOk ls (V \"len\") |] * invPre a V\n    POST[R] array8 bs (V \"buf\") * mallocHeap 0 * invPost a V R.\n\n  (* Primary invariant, recording that a set of CDATA positions is in bounds. *)\n  Definition inv cdatas :=\n    Al a : A, Al bs, Al ls,\n    PRE[V] array8 bs (V \"buf\") * xmlp (V \"len\") (V \"lex\") * sll ls (V \"stack\") * mallocHeap 0\n      * [| length bs = wordToNat (V \"len\") |] * [| inBounds cdatas V |]\n      * [| stackOk ls (V \"len\") |] * invPre a V\n    POST[R] array8 bs (V \"buf\") * mallocHeap 0 * invPost a V R.\n\n  (* Intermediate invariant, to use right after reading token position from the lexer. *)\n  Definition invP cdatas :=\n    Al a : A, Al bs, Al ls,\n    PRE[V, R] array8 bs (V \"buf\") * xmlp' (V \"len\") R (V \"lex\") * mallocHeap 0\n      * sll ls (V \"stack\")\n      * [| length bs = wordToNat (V \"len\") |] * [| inBounds cdatas V |]\n      * [| stackOk ls (V \"len\") |] * invPre a V\n    POST[R'] array8 bs (V \"buf\") * mallocHeap 0 * invPost a V R'.\n\n  (* Intermediater invariant, to use right after reading token length from the lexer. *)\n  Definition invL cdatas start :=\n    Al a : A, Al bs, Al ls,\n    PRE[V, R] array8 bs (V \"buf\") * xmlp (V \"len\") (V \"lex\") * sll ls (V \"stack\") * mallocHeap 0\n      * [| length bs = wordToNat (V \"len\") |] * [| inBounds cdatas V |]\n      * [| stackOk ls (V \"len\") |]\n      * [| wordToNat (V start) + wordToNat R <= wordToNat (V \"len\") |]%nat * invPre a V\n    POST[R'] array8 bs (V \"buf\") * mallocHeap 0 * invPost a V R'.\n\n  (* Alternate sequencing operator, which generates twistier code but simpler postconditions and VCs *)\n  Definition SimpleSeq (ch1 ch2 : chunk) : chunk := fun ns res =>\n    Structured nil (fun im mn H => Seq_ H (toCmd ch1 mn H ns res) (toCmd ch2 mn H ns res)).\n\n  Infix \";;\" := SimpleSeq : SP_scope.\n\n  (* Workhorse pattern compilation function, taking as input:\n   * p: an XML pattern to compile\n   * level: tree depth at which this pattern is applied (starts at 1 for top-level pattern)\n   * cdatas: list of start-length pairs denoting spans within the string we match against,\n   *         set by earlier successfull matches of subpatterns\n   * onSuccess: continuation code to run when the pattern matches fully\n   *)\n  Fixpoint Pat' (p : pat) (level : nat) (cdatas : list (string * string))\n    (onSuccess : chunk) : chunk :=\n    match p with\n      | Cdata const =>\n        (* Read next token. *)\n        \"res\" <-- Call \"xml_lex\"!\"next\"(\"buf\", \"lex\")\n        [inv cdatas];;\n\n        (* Now here's a gross hack to support XML-RPC, which has some positions where\n         * \"blah\" and \"<string>blah</string>\" are equivalent. *)\n        If (\"res\" = 1) {\n          \"level\" <- (level + 1)%nat;;\n          \"res\" <-- Call \"xml_lex\"!\"next\"(\"buf\", \"lex\")\n          [inv cdatas]\n        } else {\n          \"level\" <- level\n        };;\n\n        (* What type of token is it? *)\n        If (\"res\" = 2) {\n          (* We may have a match!  First, grab the boundaries of the matching string. *)\n          \"tagStart\" <-- Call \"xml_lex\"!\"tokenStart\"(\"lex\")\n          [invP cdatas];;\n\n          \"tagLen\" <-- Call \"xml_lex\"!\"tokenLength\"(\"lex\")\n          [invL cdatas \"tagStart\"];;\n\n          If (\"tagLen\" = String.length const) {\n            (* Now check if the CDATA content here matches the constant from the pattern. *)\n            StringEq \"buf\" \"len\" \"tagStart\" \"matched\" const\n            (fun a V => Ex ls, xmlp (V \"len\") (V \"lex\") * sll ls (V \"stack\") * mallocHeap 0\n              * [| inBounds cdatas V |] * [| stackOk ls (V \"len\") |] * invPre a V)%Sep\n            (fun bs a V R => array8 bs (V \"buf\") * mallocHeap 0 * invPost a V R)%Sep;;\n\n            If (\"matched\" = 0) {\n              (* Nope, not equal. *)\n              Skip\n            } else {\n              (* Equal! *)\n              If (\"level\" = level) {\n                Skip\n              } else {\n                \"level\" <- level;;\n                \"res\" <-- Call \"xml_lex\"!\"next\"(\"buf\", \"lex\")\n                [inv cdatas]\n              };;\n              onSuccess\n            }\n          } else {\n            (* Tag is wrong length to match. *)\n            Skip\n          }\n        } else {\n          (* It's not CDATA.  Pattern doesn't match. *)\n          Skip\n        }\n\n      | Var start len =>\n        (* Read next token. *)\n        \"res\" <-- Call \"xml_lex\"!\"next\"(\"buf\", \"lex\")\n        [inv cdatas];;\n\n        (* Now here's a gross hack to support XML-RPC, which has some positions where\n         * \"blah\" and \"<string>blah</string>\" are equivalent. *)\n        If (\"res\" = 1) {\n          \"level\" <- (level + 1)%nat;;\n          \"res\" <-- Call \"xml_lex\"!\"next\"(\"buf\", \"lex\")\n          [inv cdatas]\n        } else {\n          \"level\" <- level\n        };;\n\n        (* What type of token is it? *)\n        If (\"res\" = 2) {\n          (* This is indeed CDATA!  Save the position and signal success. *)\n          start <-- Call \"xml_lex\"!\"tokenStart\"(\"lex\")\n          [invP cdatas];;\n\n          len <-- Call \"xml_lex\"!\"tokenLength\"(\"lex\")\n          [invL cdatas start];;\n\n          If (\"level\" = level) {\n            Skip\n          } else {\n            \"level\" <- level;;\n            \"res\" <-- Call \"xml_lex\"!\"next\"(\"buf\", \"lex\")\n            [inv ((start, len) :: cdatas)]\n          };;\n\n          onSuccess\n        } else {\n          (* It's not CDATA.  Pattern doesn't match. *)\n          Skip\n        }\n\n      | TreeVar start len =>\n        start <-- Call \"xml_lex\"!\"position\"(\"lex\")\n        [inv cdatas];;\n\n        (* Read next token. *)\n        \"res\" <-- Call \"xml_lex\"!\"next\"(\"buf\", \"lex\")\n        [inv cdatas];;\n\n        (* What type of token is it? *)\n        If (\"res\" = 2) {\n          (* This is the easy case: just CDATA.  Do like for [Var]. *)\n          start <-- Call \"xml_lex\"!\"tokenStart\"(\"lex\")\n          [invP cdatas];;\n\n          len <-- Call \"xml_lex\"!\"tokenLength\"(\"lex\")\n          [invL cdatas start];;\n\n          onSuccess\n        } else {\n          If (\"res\" = 1) {\n            (* It's an open tag, so we should keep lexing until encountering the matching closer. *)\n\n            \"level\" <- level;;\n\n            [inv cdatas]\n            While (\"level\" >= level) {\n              \"res\" <-- Call \"xml_lex\"!\"next\"(\"buf\", \"lex\")\n              [inv cdatas];;\n\n              If (\"res\" = 1) {\n                (* Open tag *)\n                \"level\" <- \"level\" + 1\n              } else {\n                If (\"res\" = 3) {\n                  (* Close tag *)\n                  \"level\" <- \"level\" - 1\n                } else {\n                  Skip\n                }\n              }\n            };;\n\n            \"level\" <- level;;\n\n            \"res\" <-- Call \"xml_lex\"!\"position\"(\"lex\")\n            [inv cdatas];;\n\n            If (start > \"res\") {\n              (* Shouldn't be possible, but we can't prove it ATM. *)\n              Skip\n            } else {\n              len <- \"res\" - start;;\n\n              If (\"res\" > \"len\") {\n                (* Again, shouldn't be possible. *)\n                Skip\n              } else {\n                onSuccess\n              }\n            }\n          } else {\n            (* This is not going to be a valid tree. *)\n            Skip\n          }\n        }\n\n      | Tag tag inner =>\n        (* Initialize a variable storing the tree depth of our current position.\n         * We'll consult this variable to see when we're at the proper depth for matching\n         * the current pattern. *)\n        \"level\" <- level;;\n\n        (* Loop until level drops below the starting level (after which the pattern never applies again). *)\n        [inv cdatas]\n        While (\"level\" >= level) {\n          (* Lex next token. *)\n          \"res\" <-- Call \"xml_lex\"!\"next\"(\"buf\", \"lex\")\n          [inv cdatas];;\n\n          (* What type of token is it? *)\n          If (\"res\" = 1) {\n            (* Open tag -- does it match? *)\n\n            If (\"level\" > level) {\n              (* We've descended too deep, so this position doesn't qualify. *)\n              \"level\" <- \"level\" + 1;;\n              Skip\n            } else {\n              \"level\" <- \"level\" + 1;;\n\n              (* We may have a match!  First, grab the boundaries of the matching string. *)\n              \"tagStart\" <-- Call \"xml_lex\"!\"tokenStart\"(\"lex\")\n              [invP cdatas];;\n\n              \"tagLen\" <-- Call \"xml_lex\"!\"tokenLength\"(\"lex\")\n              [invL cdatas \"tagStart\"];;\n\n              If (\"tagLen\" = String.length tag) {\n                (* Now check if the tag name here matches the name from the pattern. *)\n                StringEq \"buf\" \"len\" \"tagStart\" \"matched\" tag\n                (fun a V => Ex ls, xmlp (V \"len\") (V \"lex\") * sll ls (V \"stack\") * mallocHeap 0\n                  * [| inBounds cdatas V |] * [| stackOk ls (V \"len\") |] * invPre a V)%Sep\n                (fun bs a V R => array8 bs (V \"buf\") * mallocHeap 0 * invPost a V R)%Sep;;\n\n                If (\"matched\" = 0) {\n                  (* Nope, not equal. *)\n                  Skip\n                } else {\n                  (* Equal!  Continue with the nested pattern. *)\n                  Pat' inner (S level) cdatas onSuccess\n                }\n              } else {\n                (* Tag is wrong length to match. *)\n                Skip\n              }\n            }\n          } else {\n            If (\"res\" = 3) {\n              (* Close tag *)\n              \"level\" <- \"level\" - 1\n            } else {\n              If (\"res\" = 0) {\n                (* Done parsing.  Force exit from the loop. *)\n                \"level\" <- 0\n              } else {\n                (* Ignore any other kind of token. *)\n                Skip\n              }\n            }\n          }\n        }\n\n      | Both p1 p2 =>\n        (* Warning: shameless reuse here of variables for new purposes *)\n\n        (* Get the current position, which we will save to return to later. *)\n        \"tagLen\" <-- Call \"xml_lex\"!\"position\"(\"lex\")\n        [Al a : A, Al bs, Al ls,\n          PRE[V, R] array8 bs (V \"buf\") * xmlp (V \"len\") (V \"lex\")\n            * sll ls (V \"stack\") * mallocHeap 0 * [| R <= V \"len\" |]%word\n            * [| length bs = wordToNat (V \"len\") |] * [| inBounds cdatas V |]\n            * [| stackOk ls (V \"len\") |] * invPre a V\n          POST[R'] array8 bs (V \"buf\") * mallocHeap 0 * invPost a V R'];;\n\n        (* Allocate a new entry for the position stack. *)\n        \"tagStart\" <-- Call \"malloc\"!\"malloc\"(0, 2)\n        [Al a : A, Al bs, Al ls,\n          PRE[V, R] array8 bs (V \"buf\") * xmlp (V \"len\") (V \"lex\")\n            * sll ls (V \"stack\") * mallocHeap 0 * [| V \"tagLen\" <= V \"len\" |]%word\n            * R =?> 2 * [| R <> 0 |] * [| freeable R 2 |]\n            * [| length bs = wordToNat (V \"len\") |] * [| inBounds cdatas V |]\n            * [| stackOk ls (V \"len\") |] * invPre a V\n          POST[R'] array8 bs (V \"buf\") * mallocHeap 0 * invPost a V R'];;\n\n        (* Save the current position in this entry, then push it onto the stack. *)\n        \"tagStart\" *<- \"tagLen\";;\n        \"tagStart\"+4 *<- \"stack\";;\n        \"stack\" <- \"tagStart\";;\n\n        (* Try matching the first pattern. *)\n        Pat' p1 level cdatas\n        ((* Make sure the stack is nonempty afterward.\n          * Only buggy code here could lead to that outcome, but we aren't verifying at that level\n          * of detail yet, so we use a run-time check. *)\n        If (\"stack\" = 0) {\n          (* We hope this case is impossible. *)\n          Call \"sys\"!\"abort\"()\n          [PREonly[_] [| False |]]\n        } else {\n          (* Stack nonempty!  Pop position off of stack (into \"tagLen\"). *)\n          \"tagLen\" <-* \"stack\";;\n          \"tagStart\" <- \"stack\";;\n          \"stack\" <-* \"stack\"+4;;\n\n          (* Free the popped stack entry. *)\n          Call \"malloc\"!\"free\"(0, \"tagStart\", 2)\n          [Al a : A, Al bs, Al ls,\n            PRE[V] array8 bs (V \"buf\") * xmlp (V \"len\") (V \"lex\")\n              * sll ls (V \"stack\") * mallocHeap 0 * [| V \"tagLen\" <= V \"len\" |]%word\n              * [| length bs = wordToNat (V \"len\") |] * [| inBounds (allCdatas p1 ++ cdatas) V |]\n              * [| stackOk ls (V \"len\") |] * invPre a V\n          POST[R'] array8 bs (V \"buf\") * mallocHeap 0 * invPost a V R'];;\n\n          (* Restore the position we popped. *)\n          Call \"xml_lex\"!\"setPosition\"(\"lex\", \"tagLen\")\n          [inv (allCdatas p1 ++ cdatas)];;\n\n          (* Now try matching the second pattern from the same initial position. *)\n          Pat' p2 level (allCdatas p1 ++ cdatas)\n          onSuccess\n        })\n\n      | Ordered p1 p2 =>\n        (* Try matching the first pattern. *)\n        Pat' p1 level cdatas (\n          (* Loop lexing tokens until we return to the appropriate tree level. *)\n          [inv (allCdatas p1 ++ cdatas)]\n          While (\"level\" > level) {\n            \"res\" <-- Call \"xml_lex\"!\"next\"(\"buf\", \"lex\")\n            [inv (allCdatas p1 ++ cdatas)];;\n\n            If (\"res\" = 1) {\n              (* Open tag *)\n              \"level\" <- \"level\" + 1\n            } else {\n              If (\"res\" = 3) {\n                (* Close tag *)\n                \"level\" <- \"level\" - 1\n              } else {\n                Skip\n              }\n            }\n          };;\n\n          (* Now try matching the second pattern from the same initial position. *)\n          Pat' p2 level (allCdatas p1 ++ cdatas)\n          onSuccess\n        )\n    end%SP.\n\n  Notation baseVars := (\"buf\" :: \"len\" :: \"lex\" :: \"res\"\n    :: \"tagStart\" :: \"tagLen\" :: \"matched\" :: \"stack\" :: \"level\" :: nil).\n\n  Definition noConflict pt := List.Forall (fun p => ~In (fst p) baseVars /\\ ~In (snd p) baseVars\n    /\\ ~freeVar pt (fst p) /\\ ~freeVar pt (snd p)).\n\n  Notation \"l ~~ im ~~> s\" := (LabelMap.find l%SP im = Some (Precondition s None)) (at level 0).\n\n  Lemma inBounds_sel : forall cdatas V, inBounds cdatas (sel V) = inBounds cdatas V.\n    auto.\n  Qed.\n\n  Lemma 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.\n  Qed.\n\n  Lemma incl_peel : forall A (x : A) ls ls',\n    incl (x :: ls) ls'\n    -> In x ls' /\\ incl ls ls'.\n    unfold incl; intuition.\n  Qed.\n\n  Ltac deDouble := simpl in *;\n    repeat match goal with\n             | [ H : incl nil _ |- _ ] => clear H\n             | [ H : incl _ _ |- _ ] => apply incl_peel in H; destruct H\n             | [ H : forall x, x = _ \\/ x = _ -> _ |- _ ] =>\n               generalize (H _ (or_introl _ eq_refl)); intro;\n                 specialize (H _ (or_intror _ eq_refl))\n             | [ H : forall x, freeVar _ _ \\/ freeVar _ _ -> _ |- _ ] =>\n               generalize (fun x H0 => H x (or_introl _ H0)); intro;\n                 specialize (fun x H0 => H x (or_intror _ H0))\n           end;\n    intuition idtac; repeat match goal with\n                              | [ H : False -> False |- _ ] => clear H\n                            end.\n\n  Lemma mult4_S : forall n,\n    4 * S n = S (S (S (S (4 * n)))).\n    simpl; intros; omega.\n  Qed.\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  Ltac evalu :=\n    match goal with\n      | [ ns : list string |- _ ] =>\n        repeat match goal with\n                 | [ H : In _ ns |- _ ] => clear H\n               end\n    end; try rewrite mult4_S in *; repeat rewrite inBounds_sel in *;\n    repeat rewrite invPre_sel in *; repeat rewrite invPost_sel in *;\n    match goal with\n      | [ _ : evalInstrs _ _ _ = _ |- _ ] => evaluate SinglyLinkedList.hints\n      | [ _ : evalCond _ _ _ _ _ = _ |- _ ] => evaluate SinglyLinkedList.hints\n      | _ => idtac\n    end;\n    repeat match goal with\n             | [ H : In _ _ |- _ ] => clear H\n             | [ H : evalInstrs _ _ _ = _ |- _ ] => clear H\n           end;\n    try match goal with\n          | [ st : (settings * state)%type |- _ ] => destruct st; simpl in *\n        end.\n\n  Ltac finish := descend; repeat (step SinglyLinkedList.hints; descend); auto.\n\n  Hint Extern 1 (@eq W _ _) => unfold natToW in *; words.\n\n  Opaque mult.\n\n  Lemma stackOk_cons : forall w len ws,\n    w <= len\n    -> stackOk ws len\n    -> stackOk (w :: ws) len.\n    constructor; auto.\n  Qed.\n\n  Hint Immediate stackOk_cons.\n\n  Ltac noConflict := unfold noConflict; intros; eapply Forall_impl; [ | eauto ]; (cbv beta; simpl; tauto).\n\n  Lemma noConflict_Both1 : forall p1 p2 cdatas,\n    noConflict (Both p1 p2) cdatas\n    -> noConflict p1 cdatas.\n    noConflict.\n  Qed.\n\n  Lemma noConflict_Both2' : forall p1 p2 cdatas,\n    noConflict (Both p1 p2) cdatas\n    -> noConflict p2 cdatas.\n    noConflict.\n  Qed.\n\n  Ltac allCdatas_freeVar := intros ? p;\n    induction p; simpl; intuition; subst; auto;\n      match goal with\n        | [ H : _ |- _ ] => apply in_app_or in H; tauto\n      end.\n\n  Lemma allCdatas_freeVar1 : forall xy p,\n    In xy (allCdatas p) -> freeVar p (fst xy).\n    allCdatas_freeVar.\n  Qed.\n\n  Lemma allCdatas_freeVar2 : forall xy p,\n    In xy (allCdatas p) -> freeVar p (snd xy).\n    allCdatas_freeVar.\n  Qed.\n\n  Lemma noConflict_Both2 : forall p1 p2 cdatas,\n    noConflict (Both p1 p2) cdatas\n    -> (forall x, freeVar p1 x -> freeVar p2 x -> False)\n    -> (forall x, freeVar p1 x -> ~In x baseVars)\n    -> noConflict p2 (allCdatas p1 ++ cdatas).\n    intros; apply Forall_app.\n    2: eapply noConflict_Both2'; eauto.\n    apply Forall_forall; intros.\n    generalize (allCdatas_freeVar1 _ _ H2); intro.\n    apply allCdatas_freeVar2 in H2.\n    intuition eauto.\n  Qed.\n\n  Hint Immediate noConflict_Both1.\n  Hint Extern 1 (noConflict _ (_ ++ _)) => eapply noConflict_Both2; [ eassumption | eassumption |\n    simpl; intros; match goal with\n                     | [ H : _, H' : freeVar _ _ |- _ ] => apply H in H'; tauto\n                   end ].\n\n  Hint Extern 1 (incl _ _) => hnf; simpl; intuition congruence.\n\n  Lemma Forall_app1 : forall A P (ls1 ls2 : list A),\n    List.Forall P (ls1 ++ ls2)\n    -> List.Forall P ls1.\n    induction ls1; inversion 1; eauto.\n  Qed.\n\n  Lemma Forall_app2 : forall A P (ls1 ls2 : list A),\n    List.Forall P (ls1 ++ ls2)\n    -> List.Forall P ls2.\n    induction ls1; inversion 1; eauto.\n  Qed.\n\n  Lemma inBounds_app1 : forall ls1 ls2 x,\n    inBounds (ls1 ++ ls2) x\n    -> inBounds ls1 x.\n    intros; eapply Forall_app1; eauto.\n  Qed.\n\n  Lemma inBounds_app2 : forall ls1 ls2 x,\n    inBounds (ls1 ++ ls2) x\n    -> inBounds ls2 x.\n    intros; eapply Forall_app2; eauto.\n  Qed.\n\n  Hint Immediate inBounds_app1 inBounds_app2.\n\n  Lemma inBounds_decons : forall x cdatas y,\n    inBounds (x :: cdatas) y\n    -> inBounds cdatas y.\n    inversion 1; auto.\n  Qed.\n\n  Hint Immediate inBounds_decons.\n\n  Lemma inBounds_assoc : forall ls1 ls2 ls3 x,\n    inBounds ((ls1 ++ ls2) ++ ls3) x\n    -> inBounds (ls1 ++ ls2 ++ ls3) x.\n    intros; rewrite app_assoc; assumption.\n  Qed.\n\n  Lemma inBounds_assoc' : forall ls1 ls2 ls3 x,\n    inBounds (ls1 ++ ls2 ++ ls3) x\n    -> inBounds ((ls1 ++ ls2) ++ ls3) x.\n    intros; rewrite <- app_assoc; assumption.\n  Qed.\n\n  Hint Immediate inBounds_assoc inBounds_assoc'.\n\n  Lemma wplus_wminus : forall u v : W,\n    u ^+ v ^- v = u.\n    intros; words.\n  Qed.\n\n  Hint Rewrite wplus_wminus mult4_S : sepFormula.\n\n  Ltac inBounds :=\n    rewrite <- inBounds_sel;\n      repeat match goal with\n               | [ H : inBounds _ ?X |- _ ] =>\n                 match X with\n                   | sel _ => fail 1\n                   | _ => rewrite <- inBounds_sel in H\n                 end\n             end;\n      try (constructor; [ descend | ]);\n        match goal with\n          | [ H : inBounds _ _, H' : noConflict _ _ |- _ ] =>\n            eapply Forall_impl2; [ apply H\n              | (eapply noConflict_Both2; [ eassumption | eassumption |\n                simpl; intros; match goal with\n                                 | [ H : _, H' : freeVar _ _ |- _ ] => apply H in H'; tauto\n                               end ]) || apply H'\n              | cbv beta; simpl; intuition descend;\n                repeat match goal with\n                         | [ H : forall x, _ |- _ ] => rewrite <- H by congruence\n                       end; assumption ]\n        end.\n\n  Ltac reger := repeat match goal with\n                         | [ H : Regs _ _ = _ |- _ ] => rewrite H\n                       end.\n\n  Ltac inver :=\n    match goal with\n      | [ H : forall a : A, _ |- himp _ ?P ?Q ] =>\n        match P with\n          | context[invPre _ ?vs] =>\n            match Q with\n              | context[invPre _ ?vs'] =>\n                match vs' with\n                  | vs => fail 1\n                  | _ => rewrite (H _ vs vs') by intuition descend\n                end\n            end\n          | context[invPost _ ?vs _] =>\n            match Q with\n              | context[invPost _ ?vs' _] =>\n                match vs' with\n                  | vs => fail 1\n                  | _ => rewrite (H _ vs vs') by intuition descend\n                end\n            end\n        end\n    end.\n\n  Ltac bash :=\n    unfold inv, invP, invL, localsInvariant; try rewrite mult4_S in *; reger; try inver; descend;\n      try rewrite inBounds_sel; try rewrite invPre_sel in *; try rewrite invPost_sel in *;\n        try match goal with\n              | [ _ : inBounds ?cdatas _ |- interp _ (![?pre] _ ---> ![?post] _)%PropX ] =>\n                match post with\n                  | context[locals ?ns _ _ _] =>\n                    match pre with\n                      | context[locals ns ?vs _ _] =>\n                        assert (inBounds cdatas vs) by inBounds\n                    end\n                end\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\n                    end\n                end;\n                match goal with\n                  | [ H : forall x : string, _ -> sel ?V _ = sel ?V' _ |- _ ] =>\n                    repeat match goal with\n                             | [ |- context[V ?x] ] => change (V x) with (sel V x)\n                             | [ |- context[V' ?x] ] => change (V' x) with (sel V' x)\n                           end;\n                    repeat rewrite H by intuition congruence\n                end; reflexivity\n            end;\n        try match goal with\n              | [ |- interp _ (![?pre] _ ---> ![?post] _)%PropX ] =>\n                match post with\n                  | context[locals ?ns _ _ _] =>\n                    match pre with\n                      | context[locals ns ?vs _ _] =>\n                        match pre with\n                          | context[invPre ?a ?vs'] =>\n                            assert (unit -> invPre a vs' = invPre a vs) by\n                              match goal with\n                                | [ H : _ |- _ ] => intro; apply H; intuition descend\n                              end\n                          | context[invPost ?a ?vs' ?r] =>\n                            assert (unit -> invPost a vs' r = invPost a vs r) by\n                              match goal with\n                                | [ H : _ |- _ ] => intro; apply H; intuition descend\n                              end\n                        end\n                    end\n                end;\n                try match goal with\n                      | [ _ : context[Var ?start ?len] |- _ ] =>\n                        match post with\n                          | context[locals ?ns _ _ _] =>\n                            match pre with\n                              | context[locals ns ?vs _ _] =>\n                                assert (wordToNat (sel vs start) + wordToNat (sel vs len)\n                                  <= wordToNat (sel vs \"len\"))%nat by descend\n                            end\n                        end\n                    end\n            end;\n        step SinglyLinkedList.hints;\n        try match goal with\n              | [ H : unit -> invPre _ _ = invPre _ _ |- _ ] => rewrite (H tt)\n              | [ H : unit -> invPost _ _ _ = invPost _ _ _ |- _ ] => rewrite (H tt)\n            end.\n\n  Ltac clear_fancier := match goal with\n                          | [ H : importsGlobal _ |- _ ] =>\n                            repeat match goal with\n                                     | [ H' : context[H] |- _ ] => clear H'\n                                   end; clear H\n                        end.\n\n  Ltac deSpec := simpl in *;\n    repeat match goal with\n             | [ H : LabelMap.find _ _ = _ |- _ ] => try rewrite H; clear H\n           end; clear_fancier;\n    try match goal with\n          | [ st : (settings * state)%type |- _ ] => destruct st; simpl in *\n        end.\n\n  Ltac prove_Himp :=\n    deSpec; apply Himp_ex; intro;\n      repeat match goal with\n               | [ V : vals |- _ ] =>\n                 match goal with\n                   | [ |- context[V ?x] ] => change (V x) with (sel V x)\n                 end\n             end;\n      match goal with\n        | [ H : context[invPre] |- ?P ===> ?Q ] =>\n          match P with\n            | context[invPre ?a ?V] =>\n              match Q with\n                | context[invPre a ?V'] =>\n                  rewrite (H a V V') by intuition\n              end\n          end\n      end;\n      match goal with\n        | [ H : forall x : string, _ |- _ ] =>\n          repeat rewrite H by congruence; cancel auto_ext; inBounds\n      end.\n\n  Ltac invoke1 :=\n    match goal with\n      | [ |- _ ===> _ ] => prove_Himp\n      | [ H : _ |- vcs _ ] => apply H; clear H\n      | [ H : forall x, _, H' : interp _ _ |- _ ] => apply H in H'; clear H\n      | [ |- vcs _ ] => wrap0\n    end; try eassumption; try (rewrite app_assoc; eassumption); eauto; propxFo;\n    try match goal with\n          | [ st : (settings * state)%type |- _ ] => destruct st; simpl in *\n        end.\n\n  Ltac set_env :=\n    match goal with\n      | [ _ : context[locals ?ns ?vs ?res ?sp] |- context[locals ?ns ?vs' ?res ?sp'] ] =>\n        match sp with\n          | sp' => idtac\n          | _ => let H := fresh in assert (H : sp = sp') by words; clear H\n        end; equate vs' vs; descend\n    end.\n\n  Ltac prep_call :=\n    match goal with\n      | [ H : context[locals ?ns ?vs ?avail ?p]\n        |- context[locals ?ns' _ ?avail' _] ] =>\n      match avail' with\n        | avail => fail 1\n        | _ =>\n          let offset := eval simpl in (4 * List.length ns) in\n            change (locals ns vs avail p) with (locals_call ns vs avail p ns' avail' offset) in H;\n              assert (ok_call ns ns' avail avail' offset)%nat\n                by (split; [ simpl; omega\n                  | split; [ simpl; omega\n                    | split; [ NoDup\n                      | reflexivity ] ] ])\n      end;\n      match goal with\n        | [ H : interp _ _ |- _ ] => autorewrite with sepFormula in H; simpl in H\n      end\n    end.\n\n  Ltac split_IH := match goal with\n                     | [ IH : forall level : nat, _ |- _ ] =>\n                       generalize (fun a b c d e f g h i j => proj1 (IH a b c d e f g h i j));\n                         generalize (fun a b c d e f g h i j => proj2 (IH a b c d e f g h i j));\n                           clear IH; intros\n                   end.\n\n  Ltac PatR := repeat split_IH; wrap0; deDouble; propxFo; repeat invoke1;\n    deSpec; simp; repeat invoke1; try prep_call;\n      evalu; try tauto; descend; try set_env; repeat bash; inBounds || eauto.\n\n  Hint Constructors unit.\n\n  Lemma StringMatch_ok : forall (x : W) n y,\n    (wordToNat x + n <= wordToNat y)%nat\n    -> x <= y.\n    intros; nomega.\n  Qed.\n\n  Hint Immediate StringMatch_ok.\n\n  Lemma stackOk_hd : forall w ws len,\n    stackOk (w :: ws) len\n    -> w <= len.\n    inversion 1; auto.\n  Qed.\n\n  Lemma stackOk_tl : forall w ws len,\n    stackOk (w :: ws) len\n    -> stackOk ws len.\n    inversion 1; auto.\n  Qed.\n\n  Hint Immediate stackOk_hd stackOk_tl.\n\n  Lemma inBounds_easy : forall start len cdatas V k,\n    inBounds ((start, len) :: cdatas) V\n    -> noConflict (Var start len) cdatas\n    -> \"res\" <> start\n    -> \"res\" <> len\n    -> inBounds ((start, len) :: cdatas) (upd V \"res\" k).\n    intros.\n    rewrite <- inBounds_sel in *.\n    inversion_clear H.\n    constructor.\n    descend; assumption.\n    eapply Forall_impl2.\n    apply H4.\n    apply H0.\n    simpl; intuition idtac.\n    descend.\n  Qed.\n\n  Hint Immediate inBounds_easy.\n\n  Lemma inBounds_easyTree : forall start len cdatas V k w q,\n    inBounds cdatas V\n    -> noConflict (TreeVar start len) cdatas\n    -> \"res\" <> start\n    -> \"res\" <> len\n    -> \"len\" <> len\n    -> start <> len\n    -> sel (upd (upd V \"res\" w) len q) \"res\" <= sel (upd (upd V \"res\" w) len q) \"len\"\n    -> sel (upd V \"res\" w) start <= w\n    -> inBounds ((start, len) :: cdatas) (upd (upd V \"res\" k) len (w ^- sel V start)).\n    intros.\n    autorewrite with sepFormula in *.\n    rewrite <- inBounds_sel in *.\n    constructor.\n    descend.\n    simpl in *.\n    nomega.\n    eapply Forall_impl2.\n    apply H.\n    apply H0.\n    simpl; intuition idtac.\n    descend.\n  Qed.\n\n  Hint Immediate inBounds_easyTree.\n\n  Theorem PatR_correct : forall im mn H ns res,\n    ~In \"rp\" ns\n    -> incl baseVars ns\n    -> (res >= 11)%nat\n    -> \"xml_lex\"!\"next\" ~~ im ~~> nextS\n    -> \"xml_lex\"!\"position\" ~~ im ~~> positionS\n    -> \"xml_lex\"!\"setPosition\" ~~ im ~~> setPositionS\n    -> \"xml_lex\"!\"tokenStart\" ~~ im ~~> tokenStartS\n    -> \"xml_lex\"!\"tokenLength\" ~~ im ~~> tokenLengthS\n    -> \"malloc\"!\"malloc\" ~~ im ~~> mallocS\n    -> \"malloc\"!\"free\" ~~ im ~~> freeS\n    -> \"sys\"!\"abort\" ~~ im ~~> abortS\n    -> forall p level cdatas onSuccess,\n      (forall x, freeVar p x -> In x ns /\\ ~In x baseVars /\\ x <> \"rp\")\n      -> wf p\n      -> noConflict p cdatas\n      -> (forall a V V', (forall x, ~In x baseVars -> ~freeVar p x -> sel V x = sel V' x)\n        -> invPre a V = invPre a V')\n      -> (forall a V V' R, (forall x, ~In x baseVars -> ~freeVar p x -> sel V x = sel V' x)\n        -> invPost a V R = invPost a V' R)\n      -> (forall specs pre st,\n        interp specs (Postcondition (toCmd onSuccess (im := im) mn H ns res pre) st)\n        -> interp specs (inv (allCdatas p ++ cdatas) true (fun w => w) ns res st))\n      -> (forall pre,\n        (forall specs st, interp specs (pre st)\n          -> interp specs (inv (allCdatas p ++ cdatas) true (fun w => w) ns res st))\n        -> vcs (VerifCond (toCmd onSuccess (im := im) mn H ns res pre)))\n      -> forall pre,\n        (forall specs st, interp specs (pre st) -> interp specs (inv cdatas true (fun x => x) ns res st))\n        -> (forall specs st, interp specs ((toCmd (Pat' p level cdatas onSuccess)\n          (im := im) mn H ns res pre).(Postcondition) st)\n          -> interp specs (inv cdatas true (fun x => x) ns res st))\n        /\\ vcs ((toCmd (Pat' p level cdatas onSuccess) (im := im) mn H ns res pre).(VerifCond)).\n    induction p; abstract PatR.\n  Qed.\n\n  Notation PatVcs p onSuccess := (fun im ns res =>\n    (~In \"rp\" ns) :: incl baseVars ns\n    :: (forall x, freeVar p x -> In x ns /\\ ~In x baseVars)\n    :: wf p\n    :: (forall specs mn H pre st,\n      interp specs (Postcondition (toCmd onSuccess (im := im) mn H ns res pre) st)\n      -> interp specs (inv (allCdatas p) true (fun w => w) ns res st))\n    :: (res >= 11)%nat\n    :: \"xml_lex\"!\"next\" ~~ im ~~> nextS\n    :: \"xml_lex\"!\"position\" ~~ im ~~> positionS\n    :: \"xml_lex\"!\"setPosition\" ~~ im ~~> setPositionS\n    :: \"xml_lex\"!\"tokenStart\" ~~ im ~~> tokenStartS\n    :: \"xml_lex\"!\"tokenLength\" ~~ im ~~> tokenLengthS\n    :: \"malloc\"!\"malloc\" ~~ im ~~> mallocS\n    :: \"malloc\"!\"free\" ~~ im ~~> freeS\n    :: \"sys\"!\"abort\" ~~ im ~~> abortS\n    :: (forall mn H pre,\n      (forall specs st, interp specs (pre st)\n        -> interp specs (inv (allCdatas p) true (fun w => w) ns res st))\n      -> vcs (VerifCond (toCmd onSuccess (im := im) mn H ns res pre)))\n    :: (forall a V V', (forall x, ~In x baseVars -> ~freeVar p x -> sel V x = sel V' x)\n      -> invPre a V = invPre a V')\n    ::  (forall a V V' R, (forall x, ~In x baseVars -> ~freeVar p x -> sel V x = sel V' x)\n      -> invPost a V R = invPost a V' R)\n    :: nil).\n\n  Hint Extern 1 (noConflict _ nil) => constructor.\n  Hint Extern 1 (inBounds nil _) => constructor.\n\n  Definition Pat (p : pat) (onSuccess : chunk) : chunk.\n    refine (WrapC (Pat' p 1 nil onSuccess)\n      invar\n      invar\n      (PatVcs p onSuccess)\n      _ _); abstract (wrap0;\n        match goal with\n          | [ H : wf _ |- _ ] => eapply PatR_correct in H;\n            match goal with\n              | [ |- Logic.ex _ ] => destruct H; PatR\n              | [ |- vcs _ ] => destruct H; PatR\n              | _ => try rewrite app_nil_r; eauto\n            end; (intros; app; simpl; intuition congruence) || PatR\n        end).\n  Defined.\n\nEnd Pat.\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/XmlSearch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2691484690102594}}
{"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.Blame.\nRequire Import Source.Language.\nRequire Import Source.GlobalEnv.\nRequire Import Lib.Tactics.\nRequire Import Lib.Monads.\nRequire Import Lib.Extra.\nRequire Import Source.CS.\nImport Source.CS.CS.\n\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype seq.\nFrom mathcomp Require ssrnat.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nImport Source.\n\nModule CS.\n\nInstance state_turn : HasTurn state := {\n  turn_of s iface := s_component s \\in domm iface\n}.\n\nCorollary kstep_deterministic:\n  forall G st t st1 st2,\n    kstep G st t st1 -> kstep G st t st2 -> st1 = st2.\nProof.\n  intros G st t st1 st2 Hkstep1 Hkstep2.\n  apply eval_kstep_correct in Hkstep1.\n  apply eval_kstep_correct in Hkstep2.\n  rewrite Hkstep1 in Hkstep2.\n  inversion Hkstep2.\n  reflexivity.\nQed.\n\nSection Semantics.\n\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 sem := sem p.\n\n  Lemma trace_wb t cs cs' :\n    Star sem cs t cs' ->\n    well_bracketed_trace (stack_state_of cs) t.\n  Proof.\n    elim: cs t cs' / => //= s1 t1 s2 t2 s3 t Hstep Hstar IH -> {t}.\n    case: s1 t1 s2 / Hstep Hstar IH=> //=.\n    - (* Internal Return *)\n      by move=> C stk mem k _ P v P_expr old <-; rewrite eqxx.\n    - (* External Return *)\n      move=> C stk mem k C' P v P_expr old.\n      by rewrite eq_sym eqxx=> /eqP/negbTE -> /=.\n    - (* Internal Call *)\n      by move=> C stk mem k v _ _ old <-; rewrite eqxx.\n    - (* External Call *)\n      by move=> C stk mem k v _ C' old /eqP/negbTE ->; rewrite !eqxx.\n  Qed.\n\n  Lemma events_wf st t st' :\n    Star sem st t st' ->\n    all (well_formed_event (prog_interface p)) t.\n  Proof.\n  elim: st t st' / => // st1 t1 st2 t2 st3 t /= Hstep Hstar IH -> {t}.\n  rewrite all_cat; case: st1 t1 st2 / Hstep {Hstar} => //=.\n  - by move=> ????????? /eqP -> /imported_procedure_iff ->.\n  - by move=> ????????  /eqP ->.\n  Qed.\n\n  Lemma trace_wf mainP t cs cs' :\n    Star sem cs t cs' ->\n    initial_state p cs ->\n    prog_main p = Some mainP ->\n    well_formed_program p ->\n    well_formed_trace (prog_interface p) t.\n  Proof.\n    move=> Hstar Hinitial Hmain Hwf; rewrite /well_formed_trace.\n    rewrite (events_wf Hstar) andbT.\n    suffices <- : stack_state_of cs = stack_state0 by apply: trace_wb; eauto.\n    by move: Hinitial; rewrite /initial_state /initial_machine_state Hmain => ->.\n  Qed.\n\n  (* Several alternative formulations are possible. One may include the ERet event\n     in the star, express the inclusion of ECall in the trace via In, etc. *)\n  Lemma eret_from_initial_star_goes_after_ecall_cs s0 t s1 s2 C' v C :\n    CS.initial_state p s0 ->\n    Star sem s0 t s1 ->\n    Step sem s1 [:: ERet C' v C] s2 ->\n    exists t1 s s' t2 P v',\n      Star sem s0 t1 s /\\\n      Step sem s [ECall C P v' C'] s' /\\\n      Star sem s' t2 s1 /\\\n      t = t1 ** [ECall C P v' C'] ** t2.\n  Proof.\n    move=> Hinitial Hstar Hstep.\n    have {Hstep} /trace_wb : Star sem s0 (t ++ [:: ERet C' v C]) s2.\n      apply: star_trans; eauto; exact: star_one.\n    have -> : stack_state_of s0 = stack_state0.\n      by rewrite Hinitial /= /CS.initial_machine_state /=; case: prog_main.\n    case/well_bracketed_trace_inv=> t1 [P [arg [t2 e]]].\n    move: Hstar; rewrite {}e -[seq.cat]/Eapp.\n    case/(star_middle1_inv (@singleton_traces p))=> s1' [s2' [Hstar1 [Hstep2 Hstar3]]].\n    by exists t1, s1', s2', t2, P, arg; repeat split=> //.\n  Qed.\n\nEnd Semantics.\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/Source/CSExtra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2691484573643935}}
{"text": "Require Import floyd.base.\nRequire Import floyd.assert_lemmas.\nRequire Import floyd.client_lemmas.\nRequire Import floyd.nested_field_lemmas.\nRequire Import floyd.type_induction.\nRequire Import floyd.aggregate_type.\nRequire Import floyd.reptype_lemmas.\nRequire Import floyd.proj_reptype_lemmas.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import floyd.sublist.\n\nSection SINGLE_HOLE.\n\nContext {cs: compspecs}.\n\nLemma gfield_dec: forall (gf0 gf1: gfield), {gf0 = gf1} + {gf0 <> gf1}.\nProof.\n  intros.\n  destruct gf0, gf1; try solve [right; congruence].\n  + destruct (zeq i i0); [left | right]; congruence.\n  + destruct (Pos.eq_dec i i0); [left | right]; congruence.\n  + destruct (Pos.eq_dec i i0); [left | right]; congruence.\nDefined.\n\nLemma rgfs_dec: forall rgfs0 rgfs1: list gfield, {rgfs0 = rgfs1} + {rgfs0 <> rgfs1}.\nProof.\n  apply list_eq_dec.\n  apply gfield_dec.\nDefined.\n\nDefinition upd_gfield_reptype t gf (v: reptype t) (v0: reptype (gfield_type t gf)) : reptype t :=\n  fold_reptype\n  (match t, gf return (REPTYPE t -> reptype (gfield_type t gf) -> REPTYPE t)\n  with\n  | Tarray t0 n a, ArraySubsc i => upd_Znth i\n(*zl_concat (zl_concat (zl_sublist 0 i v) (zl_singleton i v0)) (zl_sublist (i + 1) n v) *)\n  | Tstruct id _, StructField i =>\n      fun v v0 => upd_compact_prod _ v (i, field_type i (co_members (get_co id))) v0 member_dec\n  | Tunion id _, UnionField i =>\n      fun v v0 => upd_compact_sum _ v (i, field_type i (co_members (get_co id))) v0 member_dec\n  | _, _ => fun v _ => v\n  end (unfold_reptype v) v0).\n\nFixpoint upd_reptype (t: type) (gfs: list gfield) (v: reptype t) (v0: reptype (nested_field_type t gfs)): reptype t :=\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) -> reptype t\n  with\n  | nil => fun v0 => v0\n  | gf :: gfs0 => fun v0 => upd_reptype t gfs0 v (upd_gfield_reptype _ gf (proj_reptype t gfs0 v) v0)\n  end (eq_rect_r reptype v0 (eq_sym (nested_field_type_ind t gfs))).\n\nLemma upd_Znth_ints i xints v:\n      upd_Znth i (map Vint xints) (Vint v) =\n      map Vint ((sublist 0 i xints) ++\n                v :: (sublist (i + 1) (Zlength (map Vint xints)) xints)).\nProof. unfold upd_Znth; intros. rewrite map_app. simpl.\n  do 2 rewrite sublist_map; trivial.\nQed.\n\nRequire Import floyd.stronger.\n\nLemma upd_reptype_data_equal: forall t gfs v v0 v1, data_equal v0 v1 -> data_equal (upd_reptype t gfs v v0) (upd_reptype t gfs v v1).\nProof.\n  intros.\n  induction gfs as [| gf gfs].\n  + exact H.\n  + change (upd_reptype t (gf :: gfs) v v0) with\n      (upd_reptype t gfs v (upd_gfield_reptype _ gf (proj_reptype t gfs v)\n        (eq_rect_r reptype v0 (eq_sym (nested_field_type_ind t (gf :: gfs)))))).\n    change (upd_reptype t (gf :: gfs) v v1) with\n      (upd_reptype t gfs v (upd_gfield_reptype _ gf (proj_reptype t gfs v)\n        (eq_rect_r reptype v1 (eq_sym (nested_field_type_ind t (gf :: gfs)))))).\n    apply IHgfs.\n    assert (data_equal (eq_rect_r reptype v0 (eq_sym (nested_field_type_ind t (gf :: gfs))))\n              (eq_rect_r reptype v1 (eq_sym (nested_field_type_ind t (gf :: gfs)))))\n      by (apply eq_rect_r_data_equal; auto).\n    forget (eq_rect_r reptype v0 (eq_sym (nested_field_type_ind t (gf :: gfs)))) as V0.\n    forget (eq_rect_r reptype v1 (eq_sym (nested_field_type_ind t (gf :: gfs)))) as V1.\n    forget (proj_reptype t gfs v) as V.\n    clear - H0.\n    revert V0 V1 H0 V.\n    destruct (nested_field_type t gfs), gf; unfold upd_gfield_reptype; intros; try reflexivity.\n    - admit.\n    - admit.\n    - admit.\nAdmitted.\n\nEnd SINGLE_HOLE.\n\nModule zlist_hint_db.\n\nLemma Znth_sub_0_r: forall A i l (d: A), Znth (i - 0) l d = Znth i l d.\n  intros.\n  rewrite Z.sub_0_r by omega.\n  auto.\nQed.\n\nLemma Znth_map_Vint: forall (i : Z) (l : list int),\n  0 <= i < Zlength l -> Znth i (map Vint l) Vundef = Vint (Znth i l Int.zero).\nProof.\n  intros i l.\n  apply Znth_map.\nQed.\n\nEnd zlist_hint_db.\n\n(*Hint Rewrite @zl_constr_correct using solve [omega] : zl_nth_db.\nHint Rewrite zlist_hint_db.Znth_sub_0_r : zl_nth_db.\nHint Rewrite zlist_hint_db.Znth_map_Vint using solve [omega] : zl_nth_db.\nHint Rewrite (fun A d => @zl_sublist_correct A d _ (list_zlist_correct _ _)) using solve [omega] : zl_nth_db.\nHint Rewrite (fun A d => @zl_concat_correct_l A d _ (list_zlist_correct _ _)) using solve [omega] : zl_nth_db.\nHint Rewrite (fun A d => @zl_concat_correct_r A d _ (list_zlist_correct _ _)) using solve [omega] : zl_nth_db.\n\nHint Rewrite (fun A d => @zl_sub_concat_l A d _ (list_zlist_correct _ _)) using solve [omega] : zl_sub_db.\nHint Rewrite (fun A d => @zl_sub_concat_r A d _ (list_zlist_correct _ _)) using solve [omega] : zl_sub_db.\nHint Rewrite (fun A d => @zl_sub_concat_mid A d _ (list_zlist_correct _ _)) using solve [omega] : zl_sub_db.\nHint Rewrite (fun A d => @zl_sub_sub A d _ (list_zlist_correct _ _)) using solve [omega] : zl_sub_db.\nHint Rewrite (fun A d => @zl_sub_self A d _ (list_zlist_correct _ _)) using solve [omega] : zl_sub_db.\nHint Rewrite (fun A d => @zl_sub_empty A d _ (list_zlist_correct _ _)) using solve [omega] : zl_sub_db.\nHint Rewrite (fun A d => @zl_concat_empty_l A d _ (list_zlist_correct _ _)) using solve [omega] : zl_sub_db.\nHint Rewrite (fun A d => @zl_concat_empty_r A d _ (list_zlist_correct _ _)) using solve [omega] : zl_sub_db.\n*)\nSection POSE_TAC.\n\nContext {cs: compspecs}.\n\nDefinition eq_pose {A} x y := @eq A x y.\n\nDefinition abs_pose t (v: reptype t) : Prop := True.\n\nDefinition concr_pose t (v: reptype t) : Prop := True.\n\nEnd POSE_TAC.\n\nLtac abs_or_concr t v :=\n  let t' := eval compute in t in\n  match t' with\n  | Tarray _ _ _ =>\n    match v with\n    | @nil _ => assert (concr_pose t v) by exact I\n    | _ :: _ => assert (concr_pose t v) by exact I\n    | _ => assert (abs_pose t v) by exact I\n    end\n  | Tstruct ?id _ =>\n    let m := eval compute in (co_members (get_co id)) in\n    match m with\n    | @nil _ => assert (concr_pose t v) by exact I\n    | _ :: @nil _ => assert (concr_pose t v) by exact I\n    | _ => match v with\n           | (_, _) => assert (concr_pose t v) by exact I\n           | _ => assert (abs_pose t v) by exact I\n           end\n    end\n  | Tunion ?id _ =>\n    let m := eval compute in (co_members (get_co id)) in\n    match m with\n    | @nil _ => assert (concr_pose t v) by exact I\n    | _ :: @nil _ => assert (concr_pose t v) by exact I\n    | _ => match v with\n           | (_, _) => assert (concr_pose t v) by exact I\n           | _ => assert (abs_pose t v) by exact I\n           end\n    end\n  end.\n\nTransparent peq.\n\nLtac cbv_proj_struct H :=\n    cbv beta zeta iota delta\n    [proj_struct proj_compact_prod list_rect\n    member_dec field_type Ctypes.field_type\n     ident_eq peq Pos.eq_dec BinNums.positive_rec positive_rect\n    sumbool_rec sumbool_rect bool_dec bool_rec bool_rect option_rec option_rect\n    eq_rect_r eq_rect eq_rec_r eq_rec eq_sym eq_trans f_equal\n    type_eq type_rec type_rect typelist_eq typelist_rec typelist_rect\n    intsize_rec intsize_rect signedness_rec signedness_rect floatsize_rec floatsize_rect\n    tvoid tschar tuchar tshort tushort tint\n    tuint tbool tlong tulong tfloat tdouble tptr tarray noattr\n    ] in H; simpl in H.\n\nLtac pose_proj_reptype_1 CS t gf v H :=\n  assert (@proj_gfield_reptype CS t gf v = @proj_gfield_reptype CS t gf v) as H by reflexivity;\n  let H0 := fresh \"H\" in\n  let H1 := fresh \"H\" in\n  let V := fresh \"v\" in\n  let t' := eval compute in t in\n  remember v as V eqn:H0 in H at 2;\n  match type of V with\n  | ?t_temp => change t_temp with (@reptype CS t) in V\n  end;\n  change (@proj_gfield_reptype CS t gf V) with (@proj_gfield_reptype CS t' gf V) in H;\n  unfold proj_gfield_reptype in H at 2;\n  pose proof unfold_reptype_JMeq t' V as H1;\n  apply JMeq_eq in H1;\n  rewrite H1 in H; clear H1;\n  match type of H with\n  | _ = proj_struct ?i ?m V ?d =>\n    let v_res := fresh \"v\" in\n    let H_eq := fresh \"H\" in\n    remember (proj_struct i m V d) as v_res eqn:H_eq;\n    let d' := eval vm_compute in d in change d with d' in H_eq;\n    let m' := eval vm_compute in m in change m with m' in H_eq;\n    cbv_proj_struct H_eq;\n    subst v_res;\n    subst V\n(*  | _ = zl_nth ?i ?l =>\n    subst V;\n    autorewrite with zl_nth_db in H\n*)\n  | _ =>\n    subst V\n  end\n.\n\nLtac pose_proj_reptype CS t gfs v H :=\n  match gfs with\n  | nil =>\n      assert (eq_pose (@proj_reptype CS t gfs v) v) as H by reflexivity\n  | ?gf :: ?gfs0 =>\n     pose proof I as H;   (* *0* SEE LINE *1* *)\n     let H0 := fresh \"H\" in\n     pose_proj_reptype CS t gfs0 v H0;\n     match type of H0 with\n     | eq_pose (proj_reptype t gfs0 v) ?v0 =>\n         let H1 := fresh \"H\" in\n         match gfs0 with\n         | nil => pose_proj_reptype_1 CS t gf v0 H1\n         | _ => pose_proj_reptype_1 CS (nested_field_type t gfs0) gf v0 H1\n         end;\n         clear H;         (* *1* SEE LINE *0* *)\n         match gfs0 with\n         | nil => assert (eq_pose (@proj_reptype CS t gfs v) (@proj_gfield_reptype CS t gf v0)) as H\n         | _ => assert (eq_pose (@proj_reptype CS t gfs v)\n                   (@proj_gfield_reptype CS (nested_field_type t gfs0) gf v0)) as H\n         end;\n         [unfold eq_pose in *; rewrite <- H0; unfold proj_reptype, eq_rect_r; apply eq_sym, eq_rect_eq |];\n         rewrite H1 in H;\n         clear H1\n     end\n  end.\n\nLtac pose_upd_reptype_1 CS t gf v v0 H :=\n  let t' := eval compute in t in\n  assert (data_equal (@upd_gfield_reptype CS t gf v v0) (@upd_gfield_reptype CS t' gf v v0)) as H\n    by reflexivity;\n  unfold upd_gfield_reptype at 2 in H;\n  let H0 := fresh \"H\" in\n  pose proof unfold_reptype_JMeq t' v as H0;\n  apply JMeq_eq in H0;\n  rewrite H0 in H;\n  clear H0;\n  match t' with\n  | Tarray _ _ _ => autorewrite with zl_sub_db in H\n  | _ => idtac\n  end;\n  unfold upd_compact_prod, eq_rect_r in H; simpl in H;\n  match type of H with\n  | data_equal _ (fold_reptype ?v_res) =>\n    pose proof (JMeq_eq (fold_reptype_JMeq t' v_res)) as H0;\n    rewrite H0 in H;\n    clear H0\n  end.\n\nLtac pose_upd_reptype CS t gfs v v0 H :=\n  match gfs with\n  | nil =>\n      assert (data_equal (@upd_reptype CS t gfs v v0) v0) as H by reflexivity\n  | ?gf :: ?gfs0 =>\n      pose proof I as H;   (* *2* SEE LINE *3* *)\n      match goal with\n      | HH : eq_pose (proj_reptype t gfs0 v) ?v1 |- _ =>\n          let H_upd1 := fresh \"H_upd1\" in\n          pose_upd_reptype_1 CS (nested_field_type t gfs0) gf v1 v0 H_upd1;\n          match type of H_upd1 with\n          | data_equal _ ?v1' =>\n                  let H0 := fresh \"H\" in\n                  pose_upd_reptype CS t gfs0 v v1' H0;\n                  match type of H0 with\n                  | data_equal _ ?v_res =>\n                      clear H;         (* *3* SEE LINE *2* *)\n                      assert (H: data_equal (@upd_reptype CS t gfs v v0) v_res);\n                          [| clear H_upd1 H0]\n                  end;\n                 [change (@upd_reptype CS t gfs v v0) with\n                   (@upd_reptype CS t gfs0 v (upd_gfield_reptype _ gf (proj_reptype t gfs0 v) v0));\n                  unfold eq_pose in HH; rewrite HH;\n                  eapply Equivalence.equiv_transitive;\n                  [apply upd_reptype_data_equal; exact H_upd1 | exact H0]\n                 | clear HH]\n          end\n      end\n  end.\n\nModule Type TestType.\nEnd TestType.\nModule Test : TestType.\n\nDefinition _f1 := 1%positive.\nDefinition _f2 := 2%positive.\nDefinition _f3 := 3%positive.\nDefinition _f4 := 4%positive.\nDefinition _f5 := 5%positive.\nDefinition cd1 := Composite 101%positive Struct ((_f1, tint) :: (_f2%positive, tint) :: nil) noattr.\nDefinition cd2 := Composite 102%positive Struct ((_f3, Tstruct 101%positive noattr) ::\n                                 (_f4, Tstruct 101%positive noattr) ::\n                                 (_f5, Tpointer (Tstruct 101%positive noattr) noattr) :: nil) noattr.\nDefinition cenv := match build_composite_env (cd1 :: cd2 :: nil) with Errors.OK env => env | _ => PTree.empty _ end.\n\nInstance cs: compspecs.\n  apply (mkcompspecs cenv).\n+\n  apply build_composite_env_consistent with (defs := cd1 :: cd2 :: nil).\n  reflexivity.\n  + intros ? ? ?.\n    apply PTree.elements_correct in H.\n    revert H.\n    change co with (snd (id, co)) at 2.\n    forget (id, co) as ele.\n    revert ele.\n    apply Forall_forall.\n    assert (8 >= 8) by omega.\n    assert (4 >= 4) by omega.\n    repeat constructor; unfold composite_legal_alignas; assumption.\n  + intros ? ? ?.\n    apply PTree.elements_correct in H.\n    revert H.\n    change co with (snd (id, co)) at 2.\n    forget (id, co) as ele.\n    revert ele.\n    apply Forall_forall.\n    repeat constructor; unfold composite_legal_alignas; reflexivity.\nDefined.\n\nDefinition t1 := Tstruct 101%positive noattr.\nDefinition t2 := Tstruct 102%positive noattr.\nDefinition v1: reptype t1 := (Vint Int.zero, Vint Int.one).\nDefinition v2: reptype t2 := ((Vint Int.zero, Vint Int.one), ((Vint Int.zero, Vint Int.one), Vundef)).\n\n(*\nEval vm_compute in (reptype_gen t2).\nEval vm_compute in (proj_reptype t1 (StructField 1%positive :: nil) v1).\n*)\nGoal proj_reptype t1 (StructField _f1 :: nil) v1 = Vint Int.zero.\nreflexivity.\nQed.\n\nGoal proj_reptype t2 (StructField _f2 :: StructField _f3 :: nil) v2 = Vint Int.one.\nunfold v2.\npose_proj_reptype cs t2\n  (StructField _f2 :: StructField _f3 :: nil) ((Vint Int.zero, Vint Int.one, (Vint Int.zero, Vint Int.one, Vundef)): reptype (Tstruct 102%positive noattr)) HH.\neauto.\nTime Qed. (* Cut down from 10 seconds to 4 seconds, magically. *)\n\nGoal forall n l, 0 < n -> proj_reptype (tarray tint n) (ArraySubsc 0 :: nil) l = Znth 0 l Vundef.\nintros.\npose_proj_reptype cs (tarray tint n) (ArraySubsc 0 :: nil) l HH.\nexact HH.\nQed.\n\nGoal data_equal (upd_reptype t2 (StructField 3%positive :: nil) v2 (Vint Int.one, Vint Int.one))\n((Vint Int.one, Vint Int.one), ((Vint Int.zero, Vint Int.one), Vundef)).\nset (v0 := (Vint Int.one, Vint Int.one)).\nchange (val * val)%type with (reptype (Tstruct 101%positive noattr)) in v0.\npose_proj_reptype cs (Tstruct 102%positive noattr) (StructField 3%positive :: nil) v2 H.\npose_upd_reptype cs (Tstruct 102%positive noattr) (StructField 3%positive :: nil) v2 v0 H1.\nexact H1.\nQed.\n\nGoal forall n l, 0 < n -> data_equal\n    (upd_reptype (tarray tint n) (ArraySubsc 0 :: nil) l Vundef)\n    (Vundef :: sublist 1 (Zlength l) l).\nintros.\npose_proj_reptype cs (tarray tint n) (ArraySubsc 0 :: nil) l HH.\npose_upd_reptype cs (tarray tint n) (ArraySubsc 0 :: nil) l Vundef HHH.\nexact HHH.\nQed.\n\nEnd Test.\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/floyd/replace_refill_reptype_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.2690980317527401}}
{"text": "Add LoadPath \"..\".\nAdd LoadPath \"../Labeled\".\nAdd LoadPath \"../Hybrid\".\n\nRequire Import Shared.\nRequire Import Labeled.\nRequire Import Hybrid.\nRequire Import Arith.\n\nOpen Scope is5_scope.\nOpen Scope permut_scope.\nOpen Scope labeled_is5_scope.\nOpen Scope hybrid_is5_scope.\n\n(* Context conversion *)\n\nFixpoint annotate_worlds_Hyb (w: var) (L: ctx_LF) : ctx_L :=\nmatch L with\n  | nil => nil\n  | (x, T) :: L' => (w, (x, T)) :: annotate_worlds_Hyb w L'\nend.\n\nDefinition Hyb_to_L_ctx (G: bg_Hyb) (Ctx: ctx_Hyb) :\n  (list var) * ctx_L * var :=\n  let Omega := map fst_ (Ctx :: G) in\n  let Delta := flat_map (fun x => annotate_worlds_Hyb (fst_ x) (snd_ x))\n    (Ctx :: G) in\n  (Omega, Delta, fst Ctx).\n\nLemma annotate_worlds_Hyb_app:\nforall l1 l2 x,\n  annotate_worlds_Hyb x (l1++l2) =\n  annotate_worlds_Hyb x l1 ++ annotate_worlds_Hyb x l2.\ninduction l1; intros; rew_app; simpl; auto; destruct a; simpl;\nrewrite IHl1; rew_app; auto.\nQed.\n\nLemma permut_annotate_worlds_Hyb:\nforall l l' x,\n  l *=* l' -> annotate_worlds_Hyb x l *=* annotate_worlds_Hyb x l'.\ninduction l; intros.\napply permut_nil_eq in H; subst; auto.\nassert (a::l *=* l') by auto;\napply permut_split_head in H; destruct H as (hd, (tl, H)); subst;\ndestruct a; simpl; repeat rewrite annotate_worlds_Hyb_app; simpl;\npermut_simpl; replace (annotate_worlds_Hyb x hd ++ annotate_worlds_Hyb x tl)\nwith (annotate_worlds_Hyb x (hd++tl)) by (apply annotate_worlds_Hyb_app; auto).\napply IHl;\napply permut_cons_inv with (a:=(v,t)); rewrite H0; permut_simpl.\nQed.\n\nLemma PPermut_Hyb_flat_map_annotate_worlds_Hyb:\nforall G G',\n  G ~=~ G' ->\n  flat_map (fun x => annotate_worlds_Hyb (fst_ x) (snd_ x)) G *=*\n  flat_map (fun x => annotate_worlds_Hyb (fst_ x) (snd_ x)) G'.\ninduction G; intros.\nremember (fun x : var * list (var * ty) =>\n            annotate_worlds_Hyb (fst_ x) (snd_ x))\n  as g;\napply PPermut_Hyb_nil_impl in H; subst; auto.\nassert (a::G ~=~ G') by auto;\ndestruct a; apply PPermut_Hyb_split_head in H;\ndestruct H as (l', (hd, (tl, (Ha, Hb)))); subst;\nrew_flat_map; simpl;\nassert (l *=* l') by auto;\napply permut_annotate_worlds_Hyb with (x:=v) in Ha;\nrewrite Ha; permut_simpl;\nrewrite IHG with (G':=hd++tl); rew_flat_map; auto;\napply PPermut_Hyb_last_rev with (w:=v) (Gamma:=l) (Gamma':=l);\nauto; transitivity ((v,l)::G); [ | rewrite H0]; PPermut_Hyb_simpl.\nQed.\n\nLemma ok_Hyb_to_L_ctx_ok_Omega_L:\nforall G w Gamma Omega,\n  ok_Hyb ((w, Gamma)::G) nil ->\n  Omega *=* fst_ (fst_ (Hyb_to_L_ctx G (w, Gamma))) ->\n  ok_Omega_L Omega.\ninduction G; intros; inversion H; subst;\n[simpl in *; eauto | destruct a];\nrew_map in *; simpl in *.\napply ok_Omega_L_permut with (O1:=w::nil);\n  [symmetry | constructor]; auto; constructor.\nrew_map in *; simpl in *.\ninversion H6; subst;\nassert (v::w::map fst_ G *=* Omega) by (rewrite H0; permut_simpl).\napply permut_split_head in H1; destruct H1 as (hd, (tl, H1)); subst.\napply ok_Omega_L_permut with (O1:=v::hd++tl); [permut_simpl | constructor].\napply ok_Hyb_not_Mem_fst with (w:=v) in H8; [ | apply Mem_here].\nintro. apply Mem_permut with (l':=w::map fst_ G) in H1.\nrewrite Mem_cons_eq in H1; destruct H1;\n[ subst; elim H7; apply Mem_here | contradiction].\napply permut_cons_inv with (a:=v);\ntransitivity (hd & v ++ tl); [ | rewrite H0]; permut_simpl.\n  apply IHG with (w:=w) (Gamma:=Gamma).\n  inversion H6; subst; constructor; auto.\n  apply ok_Hyb_used_weakening in H10; auto.\n  apply permut_cons_inv with (a:=v);\n    transitivity (hd & v ++ tl); [ | rewrite H0]; permut_simpl.\nQed.\n\nLemma ok_Hyb_to_L_ctx_ok_Gamma_L:\nforall G Gamma w Delta U,\n  ok_Hyb (flat_map snd_ ((w, Gamma)::G)) U ->\n  Delta *=* snd_ (fst_ (Hyb_to_L_ctx G (w, Gamma))) ->\n  ok_Gamma_L Delta U.\ninduction G; induction Gamma; intros; simpl in *; rew_app in *.\nsymmetry in H0; apply permut_nil_eq in H0; subst; constructor.\ndestruct a; simpl in *; inversion H; subst;\napply ok_Gamma_L_permut with (G1:=(w, (v, t)) :: annotate_worlds_Hyb w Gamma);\n[symmetry | constructor]; auto; apply IHGamma with (w:=w); rew_app; auto.\ndestruct a; simpl in *;\napply ok_Gamma_L_permut with (G1:=annotate_worlds_Hyb v l ++ flat_map\n         (fun x : var * list (var * ty) =>\n            annotate_worlds_Hyb (fst_ x) (snd_ x))\n         G); [symmetry |]; auto;\napply IHG with (w:=v) (Gamma:=l); auto; permut_simpl.\ndestruct a0; destruct a; simpl in *; inversion H; subst;\napply ok_Gamma_L_permut with\n  (G1:=((w, (v, t)) :: annotate_worlds_Hyb w Gamma) ++\n       annotate_worlds_Hyb v0 l ++\n       flat_map\n         (fun x : var * list (var * ty) =>\n            annotate_worlds_Hyb (fst_ x) (snd_ x))\n         G); [symmetry |]; auto;\nrew_app; constructor; auto;\napply IHGamma with (w:=w); auto; permut_simpl.\nQed.\n\nLemma ok_Hyb_to_L_ctx_ok_L:\nforall G w Gamma Omega Delta,\n  ok_Bg_Hyb ((w, Gamma)::G) ->\n  Omega *=* fst_ (fst_ (Hyb_to_L_ctx G (w, Gamma))) ->\n  Delta *=* snd_ (fst_ (Hyb_to_L_ctx G (w, Gamma))) ->\n  ok_L Omega Delta.\nintros; destruct H; split;\n[eapply ok_Hyb_to_L_ctx_ok_Omega_L |\n eapply ok_Hyb_to_L_ctx_ok_Gamma_L]; eauto.\nQed.\n\nLemma Mem_preserved_world_L:\nforall G w Gamma Omega,\n  Omega *=* fst_ (fst_ (Hyb_to_L_ctx G (w, Gamma))) ->\n  forall w0 Gamma0,\n    Mem (w0, Gamma0) ((w, Gamma)::G) ->\n    Mem w0 Omega.\ninduction G; intros; simpl in *.\nrewrite Mem_cons_eq in H0; destruct H0;\n[ | rewrite Mem_nil_eq in H0; contradiction];\ninversion H0; subst; apply Mem_permut with (l:=map fst_ ((w, Gamma)::nil));\n[symmetry; auto | rew_map; simpl; apply Mem_here].\ndestruct a;\neapply Mem_permut with (l:=map fst_ ((w, Gamma) :: (v, l) :: G));\n[symmetry; auto | ]; rewrite Mem_cons_eq in H0; destruct H0.\ninversion H0; subst; rew_map; simpl; apply Mem_here.\ndestruct (eq_var_dec w0 v); subst.\nrew_map; simpl; repeat rewrite Mem_cons_eq; right; left; auto.\nrewrite Mem_cons_eq in H0; destruct H0.\ninversion H0; subst; repeat rewrite Mem_cons_eq; right; left; auto.\nrew_map; simpl. apply Mem_permut with (l:=v::w::map fst_ G);\n[permut_simpl | rewrite Mem_cons_eq; right];\napply IHG with (w:=w) (Gamma:=Gamma) (Gamma0:=Gamma0).\nrew_map; simpl; auto.\nrewrite Mem_cons_eq; right; auto.\nQed.\n\nLemma Mem_annotate_worlds_Hyb:\nforall Gamma w Delta x a,\n  Delta = annotate_worlds_Hyb w Gamma ->\n  (Mem (x, a) Gamma <-> Mem (w, (x, a)) Delta).\ninduction Gamma; intros; simpl in *; subst.\nrepeat rewrite Mem_nil_eq; tauto.\ndestruct a; repeat rewrite Mem_cons_eq; split; intros;\ndestruct H; try inversion H; subst; simpl in *.\nleft; auto.\nright; apply Mem_here.\ndestruct y; right; apply IHGamma; auto.\nleft; auto.\nright; eapply IHGamma; eauto; apply Mem_here.\nright; eapply IHGamma; eauto. rewrite H0; auto.\nQed.\n\nLemma Mem_preserved_term_L:\nforall G w Gamma Delta,\n  Delta *=* snd_ (fst_ (Hyb_to_L_ctx G (w, Gamma))) ->\n  forall w0 x0 a0 Gamma0,\n    Mem (w0, Gamma0) ((w, Gamma)::G) ->\n    Mem (x0, a0) Gamma0 ->\n    Mem  (w0, (x0, a0)) Delta.\ninduction G; intros; simpl in *.\nrewrite Mem_cons_eq in H0; destruct H0.\ninversion H0; subst;\napply Mem_permut with (l:=annotate_worlds_Hyb w Gamma);\n[symmetry; rew_app in *; auto | rew_map; simpl];\neapply Mem_annotate_worlds_Hyb; auto.\nrewrite Mem_nil_eq in H0; contradiction.\ndestruct a; simpl in *.\napply Mem_permut with (l:=annotate_worlds_Hyb w Gamma ++\n                          annotate_worlds_Hyb v l ++\n  flat_map\n        (fun x : var * list (var * ty) =>\n           annotate_worlds_Hyb (fst_ x) (snd_ x))\n        G);\n[symmetry; rew_app in *; auto | rew_map; simpl].\nrepeat rewrite Mem_cons_eq in H0; repeat rewrite Mem_app_or_eq; destruct H0.\ninversion H0; subst.\nleft; eapply Mem_annotate_worlds_Hyb; auto.\ndestruct H0.\ninversion H0; subst; right; left; eapply Mem_annotate_worlds_Hyb; auto.\nright; right; apply IHG with (w:=w) (Gamma:=nil) (Gamma0 := Gamma0);\nsimpl; auto; rewrite Mem_cons_eq; right; auto.\nQed.\n\n(* Term conversion *)\nFixpoint Hyb_to_L_term (M0: te_Hyb) :=\nmatch M0 with\n| hyp_Hyb v =>\n  hyp_L v\n| lam_Hyb A M =>\n  lam_L A (Hyb_to_L_term M)\n| appl_Hyb M N =>\n  appl_L (Hyb_to_L_term M) (Hyb_to_L_term N)\n| box_Hyb M =>\n  box_L (Hyb_to_L_term M)\n| unbox_fetch_Hyb w M =>\n  unbox_L (fetch_L w (Hyb_to_L_term M))\n| get_here_Hyb w M =>\n  get_L w (here_L (Hyb_to_L_term M))\n| letdia_get_Hyb w M N =>\n  letd_L (get_L w (Hyb_to_L_term M)) (Hyb_to_L_term N)\nend.\n\nLemma Hyb_to_L_term_subst_t:\nforall M N x,\n  subst_t_L (Hyb_to_L_term M) x (Hyb_to_L_term N) =\n  Hyb_to_L_term (subst_t_Hyb M x N).\ninduction N; intros; simpl in *;\ntry rewrite IHN || (rewrite IHN1; rewrite IHN2); auto;\ncase_if; simpl; auto.\nQed.\n\nLemma Hyb_to_L_term_subst_w:\nforall M w w',\n  subst_w_L (Hyb_to_L_term M) w w' =\n  Hyb_to_L_term (subst_w_Hyb w w' M).\ninduction M; intros; simpl in *;\ntry rewrite IHM || (rewrite IHM1; rewrite IHM2); auto;\ncase_if; simpl; auto.\nQed.\n\nLemma Hyb_to_L_typing:\nforall G w Gamma M A Omega Delta w' M'\n  (HT: G |= (w, Gamma) |- M ::: A)\n  (H_Omega: Omega *=* fst_ (fst_ (Hyb_to_L_ctx G (w, Gamma))))\n  (H_Delta: Delta *=* snd_ (fst_ (Hyb_to_L_ctx G (w, Gamma))))\n  (H_w: w' = snd_ (Hyb_to_L_ctx G (w, Gamma)))\n  (H_M: M' = Hyb_to_L_term M),\n  Omega; Delta |- M' ::: A @ w.\nintros;\nunfold Hyb_to_L_ctx in *; rew_flat_map in *; rew_map in *;\nsimpl in *; subst;\ngeneralize dependent Omega;\ngeneralize dependent Delta;\nremember (w, Gamma) as Ctx;\ngeneralize dependent w;\ngeneralize dependent Gamma.\ninduction HT;\nintros; inversion HeqCtx; subst; simpl in *.\n(* hyp *)\napply t_hyp_L.\n  eapply ok_Hyb_to_L_ctx_ok_L; simpl; eauto.\n  eapply Mem_preserved_world_L with (w:=w0) (Gamma:=Gamma0);\n    simpl; eauto; eapply Mem_here.\n  eapply Mem_preserved_term_L with (w:=w0) (Gamma:=Gamma0);\n    simpl; eauto; eapply Mem_here.\n(* lam *)\napply t_lam_L with (L:=L).\n  eapply ok_Hyb_to_L_ctx_ok_L; eauto.\n  intros. replace (hyp_L (fte x)) with (Hyb_to_L_term (hyp_Hyb (fte x))).\n  unfold open_t_L; rewrite Hyb_to_L_term_subst_t. eapply H; eauto.\n  simpl; permut_simpl; auto.\n  simpl; auto.\n(* appl *)\napply t_appl_L with (A:=A).\n  eapply ok_Hyb_to_L_ctx_ok_L; eauto.\n  eapply IHHT1; eauto.\n  eapply IHHT2; eauto.\n(* box *)\napply t_box_L with (L:=L).\n  apply ok_Hyb_to_L_ctx_ok_L with (G:=G) (w:=w0) (Gamma:=Gamma0); auto;\n    assert ((w0, Gamma0) :: G ~=~ G & (w0, Gamma0)) as H1 by PPermut_Hyb_simpl;\n    rewrite H1; auto.\n  eapply Mem_preserved_world_L with (w:=w0) (Gamma:=Gamma0);\n    simpl; eauto; eapply Mem_here.\n  intros; unfold open_w_L; rewrite Hyb_to_L_term_subst_w.\n  apply H with (Gamma:=nil); auto.\n  rewrite H_Delta; simpl; rew_app; rew_flat_map; simpl; permut_simpl.\n  rew_map; simpl; rewrite H_Omega; permut_simpl.\n(* unbox_fetch *)\napply t_unbox_L.\n  eapply ok_Hyb_to_L_ctx_ok_L; eauto.\n  apply t_fetch_L.\n    eapply ok_Hyb_to_L_ctx_ok_L; eauto.\n    eapply IHHT; eauto.\n    apply Mem_permut with (l:=w0::map fst_ G);\n    [ symmetry | apply Mem_here ]; auto.\napply t_unbox_L.\n  eapply ok_Hyb_to_L_ctx_ok_L; eauto.\n  simpl; rew_map; simpl; rewrite H_Omega; permut_simpl.\n  replace ((w::nil) ++ map fst_ G) with (map fst_ ((w, Gamma)::G))\n    by (rew_map; simpl; auto);\n  apply PPermut_Hyb_map_fst; rewrite <- H; PPermut_Hyb_simpl.\n  simpl; rewrite H_Delta; rew_flat_map; simpl; permut_simpl.\n  apply PPermut_Hyb_flat_map_annotate_worlds_Hyb in H; rew_map in *;\n    rewrite <- H; rew_flat_map; simpl; permut_simpl.\n  apply t_fetch_L.\n    eapply ok_Hyb_to_L_ctx_ok_L; eauto.\n    rewrite H_Omega; symmetry; simpl; rew_map; simpl; permut_simpl.\n    replace ((w::nil) ++ map fst_ G) with (map fst_ ((w, Gamma)::G))\n      by (rew_map; simpl; auto);\n    apply PPermut_Hyb_map_fst; rewrite <- H; PPermut_Hyb_simpl.\n    simpl; rewrite H_Delta; rew_flat_map; simpl; permut_simpl.\n    apply PPermut_Hyb_flat_map_annotate_worlds_Hyb in H; rew_map in *;\n      rewrite <- H; rew_flat_map; simpl; permut_simpl.\n    eapply IHHT; eauto.\n    simpl; rewrite H_Delta; rew_flat_map; simpl; permut_simpl.\n    apply PPermut_Hyb_flat_map_annotate_worlds_Hyb in H; rew_map in *;\n      rewrite <- H; rew_flat_map; simpl; permut_simpl.\n    rewrite H_Omega; rew_map; simpl; permut_simpl.\n    replace ((w::nil) ++ map fst_ G) with (map fst_ ((w, Gamma)::G))\n      by (rew_map; simpl; auto);\n    apply PPermut_Hyb_map_fst; rewrite <- H; PPermut_Hyb_simpl.\n    eapply Mem_preserved_world_L with (w:=w0) (Gamma:=Gamma0);\n    simpl; eauto; eapply Mem_here.\n(* get_here *)\napply t_get_L.\n  eapply ok_Hyb_to_L_ctx_ok_L; eauto.\n  apply t_here_L.\n    eapply ok_Hyb_to_L_ctx_ok_L; eauto.\n    eapply IHHT; eauto.\n    apply Mem_permut with (l:=w0::map fst_ G);\n    [ symmetry | apply Mem_here ]; auto.\napply t_get_L.\n  eapply ok_Hyb_to_L_ctx_ok_L; eauto.\n  simpl; rew_map; simpl; rewrite H_Omega; permut_simpl.\n  replace ((w::nil) ++ map fst_ G) with (map fst_ ((w, Gamma)::G))\n    by (rew_map; simpl; auto);\n  apply PPermut_Hyb_map_fst; rewrite <- H; PPermut_Hyb_simpl.\n  simpl; rewrite H_Delta; rew_flat_map; simpl; permut_simpl.\n  apply PPermut_Hyb_flat_map_annotate_worlds_Hyb in H; rew_map in *;\n    rewrite <- H; rew_flat_map; simpl; permut_simpl.\n  apply t_here_L.\n    eapply ok_Hyb_to_L_ctx_ok_L; eauto.\n    rewrite H_Omega; symmetry; simpl; rew_map; simpl; permut_simpl.\n    replace ((w::nil) ++ map fst_ G) with (map fst_ ((w, Gamma)::G))\n      by (rew_map; simpl; auto);\n    apply PPermut_Hyb_map_fst; rewrite <- H; PPermut_Hyb_simpl.\n    simpl; rewrite H_Delta; rew_flat_map; simpl; permut_simpl.\n    apply PPermut_Hyb_flat_map_annotate_worlds_Hyb in H; rew_map in *;\n      rewrite <- H; rew_flat_map; simpl; permut_simpl.\n    eapply IHHT; eauto.\n    simpl; rewrite H_Delta; rew_flat_map; simpl; permut_simpl.\n    apply PPermut_Hyb_flat_map_annotate_worlds_Hyb in H; rew_map in *;\n      rewrite <- H; rew_flat_map; simpl; permut_simpl.\n    rewrite H_Omega; rew_map; simpl; permut_simpl.\n    replace ((w::nil) ++ map fst_ G) with (map fst_ ((w, Gamma)::G))\n      by (rew_map; simpl; auto);\n    apply PPermut_Hyb_map_fst; rewrite <- H; PPermut_Hyb_simpl.\n    eapply Mem_preserved_world_L with (w:=w0) (Gamma:=Gamma0);\n    simpl; eauto; eapply Mem_here.\n(* letdia_get *)\napply t_letd_L with (A:=A) (Lt:=L_t) (Lw:=L_w).\n  eapply ok_Hyb_to_L_ctx_ok_L; eauto.\n  apply t_get_L.\n    eapply ok_Hyb_to_L_ctx_ok_L; eauto.\n    eapply IHHT; eauto.\n    eapply Mem_preserved_world_L with (w:=w0) (Gamma:=Gamma0);\n    simpl; eauto; eapply Mem_here.\n  intros; unfold open_t_Hyb in *; unfold open_w_Hyb in *;\n  unfold open_t_L in *; unfold open_w_L in *.\n    rewrite Hyb_to_L_term_subst_w.\n    replace (hyp_L (fte t)) with (Hyb_to_L_term (hyp_Hyb (fte t))).\n    rewrite Hyb_to_L_term_subst_t.\n    eapply H; eauto.\n    rewrite H_Delta; rew_map; simpl; permut_simpl.\n    rewrite H_Omega; rew_map; simpl; permut_simpl.\n    simpl; auto.\napply t_letd_L with (A:=A) (Lt:=L_t) (Lw:=L_w).\n  eapply ok_Hyb_to_L_ctx_ok_L; eauto.\n  rewrite H_Omega; simpl; rew_map; simpl; permut_simpl;\n  replace ((w::nil) ++ map fst_ G) with (map fst_ ((w, Gamma)::G))\n    by (rew_map; simpl; auto);\n  apply PPermut_Hyb_map_fst; rewrite <- H0; PPermut_Hyb_simpl.\n  simpl; rewrite H_Delta; rew_flat_map; simpl; permut_simpl;\n  apply PPermut_Hyb_flat_map_annotate_worlds_Hyb in H0; rew_map in *;\n  rewrite <- H0; rew_flat_map; simpl; permut_simpl.\n  apply t_get_L.\n    eapply ok_Hyb_to_L_ctx_ok_L; eauto.\n    rewrite H_Omega; simpl; rew_map; simpl; permut_simpl;\n    replace ((w::nil) ++ map fst_ G) with (map fst_ ((w, Gamma)::G))\n      by (rew_map; simpl; auto);\n    apply PPermut_Hyb_map_fst; rewrite <- H0; PPermut_Hyb_simpl.\n    simpl; rewrite H_Delta; rew_flat_map; simpl; permut_simpl;\n    apply PPermut_Hyb_flat_map_annotate_worlds_Hyb in H0; rew_map in *;\n    rewrite <- H0; rew_flat_map; simpl; permut_simpl.\n    eapply IHHT; eauto.\n    simpl; rewrite H_Delta; rew_flat_map; simpl; permut_simpl;\n    apply PPermut_Hyb_flat_map_annotate_worlds_Hyb in H0; rew_map in *;\n    rewrite <- H0; rew_flat_map; simpl; permut_simpl.\n    rewrite H_Omega; simpl; rew_map; simpl; permut_simpl;\n    replace ((w::nil) ++ map fst_ G) with (map fst_ ((w, Gamma)::G))\n      by (rew_map; simpl; auto);\n    apply PPermut_Hyb_map_fst; rewrite <- H0; PPermut_Hyb_simpl.\n    eapply Mem_preserved_world_L with (w:=w0) (Gamma:=Gamma0);\n    simpl; eauto; eapply Mem_here.\n    intros; unfold open_t_Hyb in *; unfold open_w_Hyb in *;\n    unfold open_t_L in *; unfold open_w_L in *.\n    rewrite Hyb_to_L_term_subst_w.\n    replace (hyp_L (fte t)) with (Hyb_to_L_term (hyp_Hyb (fte t))).\n    rewrite Hyb_to_L_term_subst_t.\n    eapply H; eauto.\n    simpl; rewrite H_Delta; rew_flat_map; simpl; permut_simpl;\n    apply PPermut_Hyb_flat_map_annotate_worlds_Hyb in H0; rew_map in *;\n    rewrite <- H0; rew_flat_map; simpl; permut_simpl.\n    rewrite H_Omega; simpl; rew_map; simpl; permut_simpl.\n    replace (map fst_ G & w) with (map fst_ (G & (w, Gamma)))\n      by (rew_map; simpl; auto);\n    apply PPermut_Hyb_map_fst; rewrite <- H0; PPermut_Hyb_simpl.\n    simpl; auto.\nQed.\n\nLemma Hyb_to_L_term_lc_w:\nforall M n,\n  lc_w_n_Hyb n M -> lc_w_n_L n (Hyb_to_L_term M).\ninduction M; intros; inversion H; subst; simpl in *;\ntry destruct v; repeat constructor; eauto.\nQed.\n\nLemma Hyb_to_L_term_lc_t:\nforall M n,\n  lc_t_n_Hyb n M -> lc_t_n_L n (Hyb_to_L_term M).\ninduction M; intros; inversion H; subst; simpl in *;\nrepeat constructor; eauto.\nQed.\n\nHint Resolve Hyb_to_L_term_lc_w Hyb_to_L_term_lc_t.\n\nLemma Hyb_to_L_value:\nforall M,\n  value_Hyb M -> value_L (Hyb_to_L_term M).\ninduction M; intros; simpl; inversion H; subst; constructor; auto.\nQed.\n\nLemma Hyb_to_L_steps:\nforall M N w,\n  lc_w_Hyb M -> lc_t_Hyb M ->\n  step_Hyb (M, fwo w) (N, fwo w) ->\n  steps_L (Hyb_to_L_term M) (Hyb_to_L_term N) (fwo w).\ninduction M; intros; inversion H1; subst;\nunfold open_w_Hyb in *; unfold open_t_Hyb in *;\nunfold open_w_L in *; unfold open_t_L in *;\nunfold lc_w_Hyb in *; unfold lc_t_Hyb in *;\nsimpl;\ntry rewrite <- Hyb_to_L_term_subst_t;\ntry rewrite <- Hyb_to_L_term_subst_w.\n(* appl_lam *)\nconstructor; constructor; unfold lc_w_L in *; unfold lc_t_L in *; auto;\nunfold open_t_L; apply lc_t_subst_L; auto.\n(* appl *)\napply steps_L_appl_L; unfold lc_w_L in *; unfold lc_t_L in *; eauto.\n(* unbox_box *)\napply stepm_L with (M':= unbox_L (box_L (Hyb_to_L_term M0))).\nrepeat constructor; unfold lc_w_L in *; unfold lc_t_L in *;\ninversion H; inversion H0; subst; auto;\nrepeat constructor; eauto.\nrepeat constructor; unfold lc_w_L in *; unfold lc_t_L in *;\nunfold open_w_L; auto.\napply lc_w_subst_L; auto.\n(* unbox_fetch *)\ndestruct v; inversion H; subst; try omega;\napply steps_L_unbox_L_fetch_L; unfold lc_w_L in *; unfold lc_t_L in *; auto.\n(* get_here *)\ndestruct v; inversion H; subst; try omega;\napply steps_L_get_L_here_L; unfold lc_w_L in *; unfold lc_t_L in *; auto;\ninversion H1; subst.\n(* letd_here*)\nclear IHM2;\ndestruct v; destruct ctx''; inversion H; inversion H12; subst; try omega;\napply stepm_L with\n  (M':=letd_L (get_L (fwo v0) (here_L (Hyb_to_L_term M)))\n              (Hyb_to_L_term M2)).\nrepeat constructor; auto; try (apply Hyb_to_L_value; auto);\nunfold open_t_L; unfold open_w_L;\nunfold open_w_L; unfold open_t_L;\n[ apply lc_t_subst_L | apply lc_w_subst_L]; auto; repeat constructor; auto.\nconstructor; constructor; auto;\nunfold lc_t_L in *; unfold lc_w_L in *; auto;\nunfold open_t_L; unfold open_w_L;\n[apply lc_t_subst_L | apply lc_w_subst_L | apply Hyb_to_L_value]; auto.\n(* letd_get *)\ndestruct v; inversion H; subst; try omega;\napply steps_L_letd_L_get_L; unfold lc_w_L in *; unfold lc_t_L in *; auto.\nQed.\n\nClose Scope labeled_is5_scope.\nClose Scope hybrid_is5_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/LanguagesEquivalence/Hyb_to_L.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.26909803175274005}}
{"text": "From Futhark Require Import FutharkExtract.\nFrom Futhark Require Import FutharkPretty.\nFrom ConCert.Extraction Require Import Common.\nFrom ConCert.Extraction Require Import Utils.\nFrom ConCert.Utils Require Import StringExtra.\n\nFrom Coq Require Import Datatypes.\nFrom Coq Require Import String.\nFrom Coq Require Import ZArith.\nFrom Coq Require Import List.\nFrom Coq Require Import Arith.\nFrom Coq Require Import Floats.\n\nFrom MetaCoq.Template Require Import All.\nFrom MetaCoq.Template Require Import monad_utils.\n\nImport MonadNotation.\nFrom stdpp Require  base.\n\nImport ListNotations.\n\n\nOpen Scope string.\nOpen Scope pair_scope.\n\n(** Extracts [program] to Futhark, adds a new definition [extracted_name]\n    with the extracted program and also prints the program.\n    The definition with the extracted program can be used later on\n    to redirect to a file, for example. *)\nDefinition extract_and_print {A}\n           (extracted_name : string)\n           (prelude : string)\n           (translate_constants : list (BasicAst.kername * string))\n           (translate_ctors : list (string * string))\n           (tests : option FutharkTest)\n           (program : A) :=\n  res <- futhark_extraction \"\" prelude translate_constants translate_ctors tests program;;\n  match res with\n  | inl s => tmDefinition extracted_name s;;\n             tmMsg s\n  | inr s => tmFail s\n  end.\n\nDefinition float_zero := S754_zero false.\n\nDefinition nat_to_float : nat -> spec_float :=\n    fun n => match n with\n          | O => float_zero\n          | S _ => S754_finite false (Pos.of_nat n) 0\n          end.\n\n(** We remap Coq's types to the corresponding Futhark types.\n All required operations should be remapped as well. *)\nDefinition TT :=\n  [\n   (* natural numbers *)\n    remap <%% nat %%> \"i64\"\n  ; remap <%% plus %%> \"addI64\"\n  ; remap <%% mult %%> \"multI64\"\n\n    (* integers *)\n  ; remap <%% Z %%> \"i64\"\n  ; remap <%% Z.add %%> \"addI64\"\n  ; remap <%% Z.mul %%> \"multI64\"\n\n   (* floats *)\n  ; remap <%% spec_float %%> \"f64\"\n  ; remap <%% float_zero %%> \"0.0\"\n  ; remap <%% SF64add %%> \"addF64\"\n  ; remap <%% SF64div %%> \"divF64\"\n  ; remap <%% nat_to_float %%> \"f64.i64\"\n\n  (* bools *)\n  ; remap <%% bool %%> \"bool\"\n    (* lists *)\n  ; remap <%% list %%> \"[]\"\n  ; remap <%% @List.length %%> \"length\"\n  ; remap <%% List.fold_right %%> \"reduce\"\n\n\n   (* subset types *)\n  ; remap <%% sig %%> \"sig_\"\n  ; remap <%% @proj1_sig %%> \"id\"\n].\n\nDefinition TT_ctors :=\n  [ (\"O\", \"0i64\")\n  ; (\"Z0\", \"0i64\")\n  ; (\"true\", \"true\")\n  ; (\"false\", \"false\")].\n\nOpen Scope string.\n\nModule PatternMatching.\n\n  Inductive Dec :=\n  | Yes (_ : Z)\n  | No (_ : Z).\n\n  Definition add_dec (d1 d2 : Dec) : Z :=\n    match d1,d2 with\n    | Yes i1, Yes i2\n    | Yes i1, No i2\n    | No i1, Yes i2\n    | No i1, No i2  => i1 + i2\n    end.\n\n  MetaCoq Run (extract_and_print\n                 \"add_dec_futhark\"\n                 i64_ops\n                 TT\n                 TT_ctors\n                 None\n                 add_dec).\nEnd PatternMatching.\n\n\nModule TupleMatch.\n  (** Example of how deconstructing tuples with match or let\n      expressions work. *)\n\n  Definition tmatch (x : Z * Z * Z * Z) :=\n    match x with\n    | (y, _, _, _) => y\n    end.\n\n  Definition tlet (x : Z * Z * Z * Z) :=\n    let '(y, _, _, _) := x in y.\n\n  Definition twiceFirst (x : Z * Z * Z * Z) := (tmatch x, tlet x).\n\n  MetaCoq Run (extract_and_print \"tuple_match_futhark\" \"\" TT []\n                                  None\n                                  twiceFirst).\n\nEnd TupleMatch.\n\n\nModule Sum.\n\n  (** A simple example of reduction *)\n\n  Definition sum (xs: list nat) := fold_right plus 0 xs.\n\n  Definition test_input := [4;3;2;1].\n  Definition test_output := 10.\n\n  Example sum_test : sum test_input = test_output. reflexivity. Qed.\n\n  Definition futhark_sum_test :=\n    {| FTname := \"Sum test\"\n     ; FTinput := string_of_list (fun n => string_of_nat n ++ \"i64\") test_input\n     ; FToutput := string_of_nat test_output ++ \"i64\" |}.\n\n  MetaCoq Run (extract_and_print \"sum_futhark\" i64_ops TT TT_ctors\n                                  (Some futhark_sum_test)\n                                  sum).\n\nEnd Sum.\n\nModule Average.\n\n  (** An example from the fronpage of https://futhark-lang.org/ *)\n\n  (** We use the [spec_float] type, which is a specification of IEEE754 floating-point numbers in Coq.\n   That allows for proving properties related to the precision of operations on floats.*)\n\n  Open Scope float.\n\n  Definition average (xs: list spec_float) : spec_float :=\n    SF64div (fold_right SF64add float_zero xs) (nat_to_float (length xs)).\n\n\n  Example average_test : average (map Prim2SF [10.5; 20.5]) = Prim2SF 15.5.\n  Proof. reflexivity. Qed.\n\n  Definition futhark_average_test :=\n    {| FTname := \"Average test\"\n     ; FTinput := \"[10.5f64,20.5f64]\" (* we can't print float literals currently *)\n     ; FToutput := \"15.5f64\" |}.\n\n  MetaCoq Run (extract_and_print \"average_futhark\" f64_ops TT TT_ctors\n                                  (Some futhark_average_test)\n                                  average).\n\nEnd Average.\n\nModule Monoid.\n  (** In this example, we provide a \"safe\" parallel reduction operation.\n   It is safe in the sense that it requires an operation and a neutral element of a carrier type to be a monoid *)\n\n  Class IsMonoid (M : Type) (op : M -> M -> M) (e : M) : Prop:=\n    { munit_left : forall m, op e m = m;\n      munit_right : forall m, op m e = m;\n      massoc : forall m1 m2 m3, op m1 (op m2 m3) = op (op m1 m2) m3\n    }.\n\n  Definition parallel_reduce {A : Type} (op : A -> A -> A) (e : A) `{IsMonoid A op e} (xs : list A) :=\n    fold_right op e xs.\n\n  (** We cannot define [sum], because Coq cannot find appropriate instance *)\n  Fail Definition sum (xs : list Z) := parallel_reduce Z.add 0%Z.\n\n  (** So, we define the required instance *)\n  #[refine]\n  Instance Z_add_monoid : IsMonoid Z Z.add 0%Z :=\n    {| munit_left := fun m => _;\n       munit_right := _;\n       massoc := _\n    |}.\n  * reflexivity.\n  * apply Z.add_0_r.\n  * intros;apply Z.add_assoc.\n  Defined.\n\n  (** Now, it works as expected *)\n  Definition sum (xs : list Z) := parallel_reduce Z.add 0%Z.\n\n  (** We tell our extraction that our parallel reduce is Futhark's reduce *)\n  Definition TT_extra :=\n    [ remap <%% @parallel_reduce %%> \"reduce\"].\n\n  (** The witness of the instance [Z_add_monoid] is erased, because it's a proposition.\n   So, we are left with an ordinary Futhark function *)\n  MetaCoq Run (extract_and_print \"sum_futhark\" i64_ops (TT ++ TT_extra) TT_ctors\n                                  None\n                                  sum).\n  (* Geneterates the following function: *)\n  (* let sum  = reduce addI32 0i32 *)\nEnd Monoid.\n\nModule DotProduct.\n\n  Open Scope Z.\n\n  Definition map2 {A B C : Type} (f : A -> B -> C) (xs : list A) (ys : list B)\n             (p : length xs = length ys) : list C :=\n    map (fun '(x,y) => f x y) (combine xs ys).\n\n  Definition TT_extra :=\n    [ remap <%% @map2 %%> \"map2\"\n    ; remap <%% List.split %%> \"unzip\"].\n\n  (** A function computing a dot product of two lists.\n   It also takes a proof that the two lists have the same length.\n   Eventually, we should be able to use vectors (sized lists) in such functions *)\n  Definition dotprod (xs: list Z) (ys: list Z) (p : length xs = length ys):=\n    fold_right Z.add 0%Z (map2 Z.mul xs ys p).\n\n  (** The input is a list of pairs, which is basically N x 2 matrix.\n   We take a dot product of the two vertical columns.\n   We can prove that the sizes of the arguments to [dotprod] are of the same size *)\n  Program Definition dotprod_list_of_pairs (xs : list (Z * Z)) :=\n    let pair_of_lists := List.split xs in\n    dotprod pair_of_lists.1 pair_of_lists.2 _.\n  Next Obligation.\n    intros. subst pair_of_lists.\n    now rewrite split_length_l, split_length_r.\n  Defined.\n\n  Definition test_input :=\n    [(1, 4)\n    ;(2,-5)\n    ;(3, 6)].\n\n  Definition test_output := 12.\n\n  Example dotprod_test : dotprod_list_of_pairs test_input = test_output. reflexivity. Qed.\n\n  Definition futhark_dotprod_test :=\n    {| FTname := \"Dotproduct test\"\n     ; FTinput := string_of_list\n                      (fun '(n,m) => parens false (string_of_Z n ++ \",\" ++ string_of_Z m)) test_input\n     ; FToutput := string_of_Z test_output |}.\n\n\n  (** Unfortunately, Futhark test syntax doesn't support tuples, so we don't generate the test *)\n  MetaCoq Run (extract_and_print \"dotprod_list_of_pairs_futhark\" i64_ops (TT ++ TT_extra) TT_ctors\n                                 None\n                                 dotprod_list_of_pairs).\n\nEnd DotProduct.\n\nNotation \"[| n |] A\" := ({ xs : list A | #|xs| = n }) (at level 100).\n\nModule RefinementTypes.\n\n  Import Lia.\n\n  Hint Resolve combine_length : core.\n\n  Program Definition zip {A B n} (xs : [|n|]A) (ys : [|n|]B) : [|n|](A*B) :=\n    combine xs ys.\n  Next Obligation.\n    intros;destruct xs,ys;cbn. rewrite combine_length;lia.\n  Qed.\n\n  Program Definition concat {A n m} (xs : [|n|]A) (ys : [|m|]A) : [|n+m|]A\n    := (xs ++ ys)%list.\n  Next Obligation.\n    intros;destruct xs,ys;cbn;subst;apply app_length; lia.\n  Qed.\n\n  (** In this example we use commutativity of addition to type check the definition *)\n  Program Definition zip_concat_swap {n m} (xs : [|n|]Z) (ys : [|m|]Z)\n    : [| m+n |] (Z * Z) :=\n    zip (concat xs ys) (concat ys xs).\n  Next Obligation.\n    cbn;intros. destruct xs,ys;cbn;subst. rewrite app_length; lia.\n  Qed.\n  Next Obligation.\n    intros. destruct xs,ys;cbn;subst.\n    rewrite combine_length; repeat rewrite app_length. lia.\n  Qed.\n\n  Program Definition zip_self {n} (xs : {l : list Z | length l = n}) : {l | length l = n } := zip xs xs.\n\n  Definition TT_extra :=\n    [ remap <%% @zip %%> \"zip\"\n    ; remap <%% @concat %%> \"concat\"\n    ].\n\n  (** The statement below produces \"almost compilable\" code :)\n     It requires some type coercions to be inserted in order to compile *)\n  MetaCoq Run (extract_and_print \"zip_concat_swap_futhark\" sig_defs\n                                 (TT ++ TT_extra)\n                                 TT_ctors\n                                 None\n                                 zip_concat_swap).\nEnd RefinementTypes.\n\nModule Indexing.\n\n  Import Lia.\n\n  Program Definition safe_index {A} : forall (l : list A), {n : nat | n < List.length l} -> A :=\n    fix go (l : list A) (n : nat | n < List.length l) : A :=\n      match l with\n      | nil => _\n      | hd :: tl =>\n        match n with\n        | 0 => hd\n        | S n => go tl n\n        end\n      end.\n  Next Obligation.\n  intros;subst;cbn in *. destruct n as [n Hn]. exfalso;inversion Hn.\n  Defined.\n  Next Obligation.\n    intros. subst;simpl in *. destruct n0 as [n1 Hn1].\n    subst filtered_var. cbn in *. subst. auto with arith.\n  Defined.\n\n  Fixpoint repl_iota_aux (i : nat) (xs : list nat) : list nat :=\n    match xs with\n    | [] => []\n    | x :: xs' => repeat i x ++ repl_iota_aux (1+i) xs'\n    end.\n\n  Definition repl_iota := repl_iota_aux 0.\n\n  Example repl_iota_1 : repl_iota [2;3;1] = [0;0;1;1;1;2].\n  Proof. reflexivity. Qed.\n\n  Example repl_iota_2 : repl_iota [1;2;3] = [0;1;1;2;2;2].\n  Proof. reflexivity. Qed.\n\n  Lemma repl_iota_aux_decompose n i a l :\n    In i (repeat n a ++ repl_iota_aux (1+n) l) ->\n    i = n \\/ In i (repl_iota_aux (1+n) l).\n  Proof.\n    intros H.\n    apply Erasure.In_app_inv in H.\n    destruct H.\n    - apply repeat_spec in H;auto.\n    - auto.\n  Qed.\n\n  Lemma repl_iota_aux_lt {n i xs} :\n    In i (repl_iota_aux n xs) ->\n    i < n + #|xs|.\n  Proof.\n    revert dependent i.\n    revert dependent n.\n    induction xs;intros n i H.\n    - inversion H.\n    - cbn in *.\n      apply repl_iota_aux_decompose in H.\n      destruct H.\n      * lia.\n      * replace (n + S #|xs|) with (S n + #|xs|) by lia.\n        apply IHxs;auto.\n  Qed.\n\n  Program Definition repl_iota_rt {n} (xs : [|n|]nat) :\n    {l : list nat | forall i, In i l -> i < n } :=\n    repl_iota xs.\n  Next Obligation.\n    cbn;intros n xs i H.\n    destruct xs as [l Hsize];cbn in *. subst.\n    apply @repl_iota_aux_lt with (n:=0);auto.\n  Qed.\n\n  (** The implementation is a bit tricky, because while we map through [idxs]\n      we need to know that each element is actually coming from [idxs].\n      If we use the standard [map], this information is lost.\n      For that reason we use [map_In], which takes a function of two arguments:\n      an element of a list and a proof that this element is in the list passed to [map_In] as an argument *)\n  Program Definition segm_replicate {n} (reps : [|n|]nat) (vs : [|n|]nat)\n    : list nat :=\n    let idxs := repl_iota_rt reps in\n    map_In idxs (fun i Hin => safe_index vs i).\n\n  Next Obligation.\n    intros. cbn.\n    destruct idxs as [l Hl];cbn in *.\n    destruct vs;cbn in *; subst;auto.\n  Qed.\n\n  Definition prelude_extra :=\n     \"import \"\"../lib/repl_iota\"\"\" ++ nl ++(* we treat [repl_iota] as a library function *)\n      \"\" ++ nl ++\n      \"let unsafe_index 'a (xs : []a) (i: i64) : a = #[unsafe] xs[i]\" ++ nl ++\n        (* we also need a wrapper around our [map_In] function, since it's signature differs from the Futhark's [map] *)\n      \"let map_wrapper 'a 'b (xs : []a) (f : a -> () -> b) : []b = map (\\x -> f x ()) xs\".\n\n  Definition TT_extra :=\n    [ remap <%% @Utils.map_In %%> \"map_wrapper\"\n    ; remap <%% @repl_iota_rt %%> \"repl_iota\"\n    ; remap <%% @safe_index %%> \"unsafe_index\"\n    ].\n\n  (* NOTE: Clearly, using [segm_replicate] as a \"library\" function is not safe,\n     because the invariant that the two arrays are of the same size is erased\n     and curretnly we don't generate explicit sizes for the array types.\n     However, it could be called from a wrapper that ensures the required\n     preconditions hold. *)\n  MetaCoq Run (extract_and_print \"segm_replicate_futhark\"\n                                     (prelude_extra ++ nl ++ sig_defs)\n                                     (TT ++ TT_extra)\n                                     TT_ctors\n                                     None\n                                     segm_replicate).\nEnd Indexing.\n\n(** Here, we redirect the previuosly extracted programs to files *)\n(** This part cannot be evaluated in the interactive mode, because one has to provide fixed paths. Therefore, we use path from the project's root, so it works when building the project using [makefile] *)\n\n(* NOTE: we use [MetaCoq Run (tmMsg ...)] instead of [Print], because\n   [Print] adds some extra stuff, which we don't need *)\n\nRedirect \"./extracted/auto-generated/pattern_matching.fut\"\n         MetaCoq Run (tmMsg PatternMatching.add_dec_futhark).\n\nRedirect \"./extracted/auto-generated/tuple_match.fut\"\n         MetaCoq Run (tmMsg TupleMatch.tuple_match_futhark).\n\nRedirect \"./extracted/auto-generated/average.fut\"\n         MetaCoq Run (tmMsg Average.average_futhark).\n\nRedirect \"./extracted/auto-generated/monoid.fut\"\n         MetaCoq Run (tmMsg Monoid.sum_futhark).\n\nRedirect \"./extracted/auto-generated/dot_product.fut\"\n         MetaCoq Run (tmMsg DotProduct.dotprod_list_of_pairs_futhark).\n\n(* NOTE: this example is currently does not compile without some manual editing.\n   It requres a type coercion, which we cannot insert automatically yet. *)\n(* Redirect \"./extracted/auto-generated/refinement_types.fut\" *)\n(*          MetaCoq Run (tmMsg RefinementTypes.zip_concat_swap_futhark). *)\n\nRedirect \"./extracted/auto-generated/segm_replicate.fut\"\n         MetaCoq Run (tmMsg Indexing.segm_replicate_futhark).\n", "meta": {"author": "annenkov", "repo": "futhark-extract", "sha": "a637d37382e602a707db398a30168664c0a73c42", "save_path": "github-repos/coq/annenkov-futhark-extract", "path": "github-repos/coq/annenkov-futhark-extract/futhark-extract-a637d37382e602a707db398a30168664c0a73c42/theories/FutharkExamples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.26909803175274005}}
{"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\n(** * Build a table for the next binop at a given level *)\nRequire Import Coq.Lists.List.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Fiat.Common.\nRequire Import Fiat.Common.List.Operations.\nRequire Import Fiat.Common.List.ListFacts.\nRequire Import Fiat.Common.SetoidInstances.\nRequire Import Fiat.Parsers.Reachable.ParenBalanced.Core.\nRequire Import Fiat.Parsers.StringLike.Core.\nRequire Import Fiat.Parsers.StringLike.Properties.\nRequire Import Fiat.Parsers.StringLike.FirstChar.\nRequire Import Fiat.Parsers.Refinement.BinOpBrackets.ParenBalanced.\n\nSet Implicit Arguments.\n\nSection make_table.\n  Context {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char}.\n  Context {pdata : paren_balanced_hiding_dataT Char}.\n\n  (** We build a version of paren-balanced-hiding to compute each cell\n      of the table. *)\n  (**\n<<\npb' ch n \"\" = (n == 0)\npb' ch n (ch :: s) = n > 0 && pb' ch n s\npb' ch n ('(' :: s) = pb' ch (n + 1) s\npb' ch n (')' :: s) = n > 0 && pb' ch (n - 1) s\npb' ch n (_ :: s) = pb' ch n s\n\npb = pb' '+' 0\n>>\n*)\n\n  Definition compute_next_bin_op'_step\n    := (fun ch next level\n        => if is_bin_op ch\n           then if Compare_dec.gt_dec level 0\n                then option_map S (next level)\n                else Some 0\n           else if is_open ch\n                then option_map S (next (S level))\n                else if is_close ch\n                     then if Compare_dec.gt_dec level 0\n                          then option_map S (next (pred level))\n                          else None\n                     else option_map S (next level)).\n\n  Definition compute_next_bin_op' (str : String) (level : nat)\n  : option nat\n    := fold\n         compute_next_bin_op'_step\n         (fun _ => None)\n         str\n         level.\n\n  Lemma compute_next_bin_op'_nil (str : String) (H : length str = 0)\n  : compute_next_bin_op' str = fun _ => None.\n  Proof.\n    apply fold_nil; assumption.\n  Qed.\n\n  Lemma compute_next_bin_op'_recr {HSLP : StringLikeProperties Char} (str : String)\n  : compute_next_bin_op' str\n    = match get 0 str with\n        | Some ch => compute_next_bin_op'_step ch (compute_next_bin_op' (drop 1 str))\n        | None => fun _ => None\n      end.\n  Proof.\n    apply fold_recr.\n  Qed.\n\n  Global Instance compute_next_bin_op'_step_Proper {HSLP : StringLikeProperties Char}\n  : Proper (eq ==> (eq ==> eq) ==> eq ==> eq) compute_next_bin_op'_step.\n  Proof.\n    repeat intro; subst.\n    unfold compute_next_bin_op'_step.\n    unfold respectful in *.\n    match goal with\n      | [ H : _ |- _ ] => erewrite !H by reflexivity\n    end.\n    reflexivity.\n  Qed.\n\n  Global Instance compute_next_bin_op'_Proper {HSLP : StringLikeProperties Char}\n  : Proper (beq ==> eq) compute_next_bin_op'.\n  Proof.\n    apply fold_Proper.\n  Qed.\n\n  Global Instance compute_next_bin_op'_Proper' {HSLP : StringLikeProperties Char}\n  : Proper (beq ==> eq ==> eq) compute_next_bin_op'.\n  Proof.\n    repeat intro; subst.\n    refine (f_equal (fun f => f _) _).\n    setoid_subst_rel beq.\n    reflexivity.\n  Qed.\n\n  Typeclasses Opaque compute_next_bin_op'.\n  Opaque compute_next_bin_op'.\n\n  (** We build a table to tell us where to split.\n      For each character, we store an [option nat], and keep a\n      transient [list nat].\n\n      We store where the next '+' at the current level of\n      parenthetization is.  The transient list stores where the\n      next '+' is for higher levels. *)\n\n  Definition list_of_next_bin_ops'_step'\n    := (fun ch table_higher_ops =>\n          let next_ops := map (option_map S) (nth 0 table_higher_ops nil) in\n          let '(cur_mark, new_higher_ops) := (nth 0 next_ops None, tl next_ops) in\n          ((if is_bin_op ch\n            then Some 0 :: new_higher_ops\n            else if is_open ch\n                 then new_higher_ops\n                 else if is_close ch\n                      then None :: next_ops\n                      else next_ops))).\n\n  Definition list_of_next_bin_ops'_step\n    := (fun ch table_higher_ops =>\n          list_of_next_bin_ops'_step' ch table_higher_ops :: table_higher_ops).\n\n  Definition list_of_next_bin_ops' (str : String)\n  : list (list (option nat))\n    := fold\n         list_of_next_bin_ops'_step\n         nil\n         str.\n\n  Definition list_of_next_bin_ops (str : String)\n    := map (fun ls => nth 0 ls None) (list_of_next_bin_ops' str).\n\n  Lemma list_of_next_bin_ops'_nil (str : String) (H : length str = 0)\n  : list_of_next_bin_ops' str = nil.\n  Proof.\n    apply fold_nil; assumption.\n  Qed.\n\n  Lemma list_of_next_bin_ops'_recr {HSLP : StringLikeProperties Char} (str : String)\n  : list_of_next_bin_ops' str\n    = match get 0 str with\n        | Some ch => list_of_next_bin_ops'_step ch (list_of_next_bin_ops' (drop 1 str))\n        | None => nil\n      end.\n  Proof.\n    apply fold_recr.\n  Qed.\n\n  Global Instance list_of_next_bin_ops'_Proper {HSLP : StringLikeProperties Char}\n  : Proper (beq ==> eq) list_of_next_bin_ops'.\n  Proof.\n    apply fold_Proper.\n  Qed.\n\n  Typeclasses Opaque list_of_next_bin_ops'.\n  Opaque list_of_next_bin_ops'.\n\n  Lemma list_of_next_bin_ops'_length' {HSLP : StringLikeProperties Char} str\n  : List.length (list_of_next_bin_ops' str) = length str.\n  Proof.\n    set (len := length str).\n    generalize (eq_refl : length str = len).\n    clearbody len.\n    revert str.\n    induction len; simpl; intros str H'.\n    { rewrite list_of_next_bin_ops'_nil by assumption; reflexivity. }\n    { specialize (IHlen (drop 1 str)).\n      rewrite drop_length, H' in IHlen.\n      simpl in IHlen.\n      specialize (IHlen (NPeano.Nat.sub_0_r _)).\n      rewrite list_of_next_bin_ops'_recr.\n      destruct (singleton_exists (take 1 str)) as [ch H''].\n      { rewrite take_length, H'; reflexivity. }\n      { erewrite (fun s H => proj1 (get_0 s H)) by eassumption.\n        unfold list_of_next_bin_ops'_step.\n        repeat match goal with\n                 | _ => reflexivity\n                 | _ => rewrite IHlen\n                 | _ => progress simpl\n                 | [ |- context[if ?f ch then _ else _] ] => destruct (f ch)\n               end. } }\n  Qed.\n\n  Lemma list_of_next_bin_ops'_drop {HSLP : StringLikeProperties Char} str n\n  : List.drop n (list_of_next_bin_ops' str) = list_of_next_bin_ops' (drop n str).\n  Proof.\n    revert str.\n    induction n as [|n]; simpl; intros.\n    { rewrite drop_0; reflexivity. }\n    { replace (S n) with (n + 1) by omega.\n      rewrite <- drop_drop, <- IHn; clear IHn.\n      set (len := length str).\n      generalize (eq_refl : length str = len).\n      clearbody len.\n      revert str n.\n      induction len; simpl; intros str n H'.\n      { rewrite !list_of_next_bin_ops'_nil by (rewrite ?drop_length; omega).\n        destruct n; reflexivity. }\n      { specialize (IHlen (drop 1 str)).\n        rewrite drop_length, H' in IHlen.\n        simpl in IHlen.\n        rewrite NPeano.Nat.sub_0_r in IHlen.\n        specialize (IHlen (pred n) eq_refl).\n        rewrite list_of_next_bin_ops'_recr.\n        destruct (singleton_exists (take 1 str)) as [ch H''].\n        { rewrite take_length, H'; reflexivity. }\n        { rewrite (proj1 (get_0 _ _) H'').\n          reflexivity. } } }\n  Qed.\n\n  Definition index_points_to_binop (offset index : nat) (str : String)\n    := for_first_char (drop (offset + index) str) is_bin_op.\n\n  Lemma index_points_to_binop_spec {HSLP : StringLikeProperties Char} offset index str ch\n        (H : (take 1 (drop (offset + index) str) ~= [ ch ])%string_like)\n  : index_points_to_binop offset index str <-> is_bin_op ch.\n  Proof.\n    unfold index_points_to_binop.\n    rewrite (for_first_char__take 0).\n    rewrite <- for_first_char_singleton; [ reflexivity | assumption ].\n  Qed.\n\n  Lemma index_points_to_binop_S1 {HSLP : StringLikeProperties Char} offset index str\n  : index_points_to_binop (S offset) index str <-> index_points_to_binop offset index (drop 1 str).\n  Proof.\n    unfold index_points_to_binop.\n    rewrite ?drop_drop, !NPeano.Nat.add_1_r; simpl.\n    reflexivity.\n  Qed.\n\n  Lemma index_points_to_binop_S2 {HSLP : StringLikeProperties Char} offset index str\n  : index_points_to_binop offset (S index) str <-> index_points_to_binop offset index (drop 1 str).\n  Proof.\n    rewrite <- index_points_to_binop_S1.\n    unfold index_points_to_binop.\n    replace (offset + S index) with (S offset + index) by omega.\n    reflexivity.\n  Qed.\n\n  Lemma index_points_to_binop_nil {HSLP : StringLikeProperties Char}\n        (offset index : nat) (str : String) (H : length str <= offset + index)\n  : index_points_to_binop offset index str.\n  Proof.\n    unfold index_points_to_binop.\n    apply for_first_char_nil.\n    rewrite drop_length; omega.\n  Qed.\n\n  Definition index_not_points_to_binop (offset index : nat) (str : String)\n    := for_first_char (drop (offset + index) str) (fun ch => is_bin_op ch = false).\n\n  Lemma index_not_points_to_binop_spec {HSLP : StringLikeProperties Char} offset index str ch\n        (H : (take 1 (drop (offset + index) str) ~= [ ch ])%string_like)\n  : index_not_points_to_binop offset index str <-> is_bin_op ch = false.\n  Proof.\n    unfold index_not_points_to_binop.\n    rewrite (for_first_char__take 0).\n    rewrite <- for_first_char_singleton; [ reflexivity | assumption ].\n  Qed.\n\n  Lemma index_not_points_to_binop_S1 {HSLP : StringLikeProperties Char} offset index str\n  : index_not_points_to_binop (S offset) index str <-> index_not_points_to_binop offset index (drop 1 str).\n  Proof.\n    unfold index_not_points_to_binop.\n    rewrite ?drop_drop, !NPeano.Nat.add_1_r; simpl.\n    reflexivity.\n  Qed.\n\n  Lemma index_not_points_to_binop_S2 {HSLP : StringLikeProperties Char} offset index str\n  : index_not_points_to_binop offset (S index) str <-> index_not_points_to_binop offset index (drop 1 str).\n  Proof.\n    rewrite <- index_not_points_to_binop_S1.\n    unfold index_not_points_to_binop.\n    replace (offset + S index) with (S offset + index) by omega.\n    reflexivity.\n  Qed.\n\n  Lemma index_not_points_to_binop_nil {HSLP : StringLikeProperties Char}\n        (offset index : nat) (str : String) (H : length str <= offset + index)\n  : index_not_points_to_binop offset index str.\n  Proof.\n    unfold index_not_points_to_binop.\n    apply for_first_char_nil.\n    rewrite drop_length; omega.\n  Qed.\n\n  Definition cell_of_next_bin_ops_spec'' (level : nat) (cell : option nat) (str : String) offset idx\n    := (cell = Some idx\n        -> index_points_to_binop offset idx str\n           /\\ paren_balanced_hiding' (take idx (drop offset str)) level)\n       /\\ (cell = None\n           -> paren_balanced' (take idx (drop offset str)) level\n           -> index_not_points_to_binop offset idx str).\n\n  Definition list_of_next_bin_ops_spec'' (level : nat) (table : list (option nat)) (str : String) offset idx\n    := cell_of_next_bin_ops_spec'' level (nth offset table None) str offset idx.\n\n  Definition list_of_next_bin_ops_spec' (level : nat) (table : list (option nat)) (str : String)\n    := forall offset idx, list_of_next_bin_ops_spec'' level table str offset idx.\n\n  Definition list_of_next_bin_ops_spec\n    := list_of_next_bin_ops_spec' 0.\n\n  Global Instance cell_of_next_bin_ops_spec''_Proper {HSLP : StringLikeProperties Char}\n  : Proper (eq ==> eq ==> beq ==> eq ==> eq ==> iff) cell_of_next_bin_ops_spec''.\n  Proof.\n    repeat intro; subst.\n    unfold cell_of_next_bin_ops_spec''.\n    repeat (split || intros || split_and);\n    specialize_by assumption;\n    unfold index_points_to_binop in *;\n    unfold index_not_points_to_binop in *;\n    try match goal with\n          | [ H : (_ =s _) |- _ ] => rewrite <- H; assumption\n          | [ H : (_ =s _) |- _ ] => rewrite H; assumption\n        end.\n    repeat match goal with\n             | [ H : (_ =s _) |- _ ] => rewrite <- H\n             | [ H : (_ =s ?x), H' : context[?x] |- _ ] => rewrite <- H in H'\n             | _ => progress specialize_by assumption\n             | _ => assumption\n           end.\n    repeat match goal with\n             | [ H : (_ =s _) |- _ ] => rewrite H\n             | [ H : (?x =s _), H' : context[?x] |- _ ] => rewrite H in H'\n             | _ => progress specialize_by assumption\n             | _ => assumption\n           end.\n  Qed.\n\n  Definition cell_of_next_bin_op_spec''_S_offset {HSLP : StringLikeProperties Char} {level cell str offset idx}\n             (H : cell_of_next_bin_ops_spec'' level cell (drop 1 str) offset idx)\n  : cell_of_next_bin_ops_spec'' level cell str (S offset) idx.\n  Proof.\n    unfold cell_of_next_bin_ops_spec'' in *; simpl in *.\n    rewrite !index_points_to_binop_S1.\n    rewrite !index_not_points_to_binop_S1.\n    rewrite drop_drop, NPeano.Nat.add_1_r in H.\n    assumption.\n  Qed.\n\n  Definition list_of_next_bin_ops_spec''_S_offset {HSLP : StringLikeProperties Char} {level table str offset t' idx}\n             (H : list_of_next_bin_ops_spec'' level table (drop 1 str) offset idx)\n  : list_of_next_bin_ops_spec'' level (t'::table) str (S offset) idx.\n  Proof.\n    unfold list_of_next_bin_ops_spec''; simpl.\n    apply cell_of_next_bin_op_spec''_S_offset.\n    assumption.\n  Qed.\n\n  Local Ltac t_eq :=\n    repeat match goal with\n             | _ => assumption\n             | _ => progress simpl in *\n             | _ => progress subst\n             | [ |- is_true true ] => reflexivity\n             | [ H : None = Some _ |- _ ] => solve [ inversion H ]\n             | [ H : Some _ = None |- _ ] => solve [ inversion H ]\n             | [ H : 0 = S _ |- _ ] => solve [ inversion H ]\n             | [ H : S _ = 0 |- _ ] => solve [ inversion H ]\n             | [ H : is_true false |- _ ] => solve [ inversion H ]\n             | [ H : false = true |- _ ] => solve [ inversion H ]\n             | [ H : true = false |- _ ] => solve [ inversion H ]\n             | [ H : ?x = ?x |- _ ] => clear H\n             | [ H : Some _ = Some _ |- _ ] => inversion H; clear H\n             | [ H : option_map _ ?x = Some _ |- _ ] => destruct x eqn:?; simpl in H\n             | [ H : option_map _ ?x = None |- _ ] => destruct x eqn:?; simpl in H\n             | _ => progress split_and\n             | [ H : is_true (?str ~= [ ?ch ])%string_like, H' : is_true (?str ~= [ ?ch' ])%string_like |- _ ]\n               => assert (ch = ch') by (eapply singleton_unique; eassumption);\n                 clear H'\n             | [ H : ?x = true |- context[?x] ] => rewrite H\n             | [ H : ?x = false |- context[?x] ] => rewrite H\n             | [ H : is_true ?x |- context[?x] ] => rewrite H\n             | [ H : ?x = true, H' : context[?x] |- _ ] => rewrite H in H'\n             | [ H : ?x = false, H' : context[?x] |- _ ] => rewrite H in H'\n             | [ H : is_true ?x, H' : context[?x] |- _ ] => rewrite H in H'\n             | [ H : ?x = S _, H' : context[?x] |- _ ] => rewrite H in H'\n             | [ H : ?x = Some _, H' : context[?x] |- _ ] => rewrite H in H'\n             | [ H : ?x = None, H' : context[?x] |- _ ] => rewrite H in H'\n             | [ H : option_map _ ?x = Some _ |- _ ] => destruct x eqn:?; simpl in H\n             | [ H : option_map _ ?x = None |- _ ] => destruct x eqn:?; simpl in H\n             | [ H : forall x, _ = _ -> @?T x |- _ ] => specialize (H _ eq_refl)\n             | [ H : _ = _ -> ?T |- _ ] => specialize (H eq_refl)\n             | [ H : context[_ - 0] |- _ ] => rewrite NPeano.Nat.sub_0_r in H\n             | [ |- context[_ - 0] ] => rewrite NPeano.Nat.sub_0_r\n             | [ H : context[(_ + 1)%nat] |- _ ] => rewrite NPeano.Nat.add_1_r in H || setoid_rewrite NPeano.Nat.add_1_r in H\n             | [ H : ?x > 0 |- _ ] => is_var x; destruct x; [ exfalso; clear -H; omega | clear dependent H ]\n             | [ H : ~ ?x > 0 |- _ ] => is_var x; destruct x; [ clear dependent H | exfalso; clear -H; omega ]\n             | [ H : 0 > 0 |- _ ] => exfalso; clear -H; omega\n             | [ |- and _ _ ] => split\n             | _ => progress intros\n           end.\n\n  Local Ltac t' :=\n    idtac;\n    match goal with\n      | _ => progress t_eq\n      | [ |- index_points_to_binop 0 0 _ ] => eapply index_points_to_binop_spec; [ simpl; rewrite ?drop_0; eassumption | ]\n      | _ => rewrite paren_balanced_hiding'_nil by (rewrite take_length; reflexivity)\n      | [ H : _ |- _ ] => progress rewrite ?nth_tl in H\n      | _ => progress rewrite ?drop_0, ?nth_tl\n      | [ |- context[drop _ (take _ _)] ] => rewrite drop_take\n      | [ H : context[drop _ (take _ _)] |- _ ] => rewrite drop_take in H\n      | [ |- context[get 0 (take _ _)] ] => rewrite get_take_lt by omega\n      | [ |- context[nth ?n (map ?f ?ls) _] ] => simpl rewrite (map_nth f ls None n)\n      | [ |- context[nth ?n (map ?f ?ls) _] ] => simpl rewrite (map_nth f ls nil n)\n      | [ H : context[nth ?n (map ?f ?ls) _] |- _ ] => revert H; simpl rewrite (map_nth f ls None n)\n      | [ H : context[nth ?n (map ?f ?ls) _] |- _ ] => revert H; simpl rewrite (map_nth f ls nil n)\n      | [ |- index_points_to_binop _ (S _) _ ] => rewrite index_points_to_binop_S2\n      | [ H : context[length (take _ _)] |- _ ] => rewrite take_length in H\n      | [ H : context[length (drop _ _)] |- _ ] => rewrite drop_length in H\n      | [ H : context[drop 0 _] |- _ ] => rewrite drop_0 in H || setoid_rewrite drop_0 in H\n      | [ H : context[drop _ (drop _ _)] |- _ ] => rewrite drop_drop in H || setoid_rewrite drop_drop in H\n      | [ H : context[take _ (take _ _)] |- _ ] => rewrite take_take in H || setoid_rewrite take_take in H\n      | [ H : context[get 0 ?str] |- _ ] => erewrite (proj1 (get_0 str _)) in H by eassumption\n      | [ H : context[get 0 (take 0 _)] |- _ ]\n        => rewrite has_first_char_nonempty in H by (rewrite take_length; reflexivity)\n      | [ |- context[get 0 ?str] ] => erewrite (proj1 (get_0 str _)) by eassumption\n      | [ |- context[get 0 (take 0 _)] ]\n        => rewrite has_first_char_nonempty by (rewrite take_length; reflexivity)\n      | [ H : get 0 _ = Some _ |- _ ] => apply get_0 in H\n      | [ H : get 0 _ = None |- _ ] => apply no_first_char_empty in H\n      | [ H : context[(take ?n ?str ~= [ _ ])%string_like] |- _ ]\n        => pose proof (length_singleton _ _ H);\n          progress apply take_n_1_singleton in H\n      | [ |- index_not_points_to_binop 0 0 _ ] => eapply index_not_points_to_binop_spec; [ simpl; rewrite ?drop_0; eassumption | ]\n      | [ |- index_points_to_binop 0 0 _ ] => eapply index_points_to_binop_spec; [ simpl; rewrite ?drop_0; eassumption | ]\n      | [ |- index_points_to_binop (S _) _ _ ] => rewrite index_points_to_binop_S1\n      | [ |- index_not_points_to_binop (S _) _ _ ] => rewrite index_not_points_to_binop_S1\n      | [ |- index_points_to_binop _ (S _) _ ] => rewrite index_points_to_binop_S2\n      | [ |- index_not_points_to_binop _ (S _) _ ] => rewrite index_not_points_to_binop_S2\n      | _ => solve [ eauto with nocore ]\n    end.\n\n  Local Ltac t := repeat t'.\n\n  Lemma tables_agree {HSLP : StringLikeProperties Char}\n        {level str offset}\n  : nth offset (map (fun ls => nth level ls None) (list_of_next_bin_ops' str)) None\n    = compute_next_bin_op' (drop offset str) level.\n  Proof.\n    revert level offset.\n    set (len := length str).\n    generalize (eq_refl : length str = len).\n    clearbody len.\n    revert str.\n    induction len; simpl; intros str Hlen level offset.\n    { hnf.\n      rewrite compute_next_bin_op'_nil, list_of_next_bin_ops'_nil by (rewrite ?drop_length; omega).\n      destruct offset; reflexivity. }\n    { specialize (IHlen (drop 1 str)).\n      specialize_by (rewrite drop_length; omega).\n      setoid_rewrite drop_drop in IHlen.\n      t_eq.\n      rewrite list_of_next_bin_ops'_recr.\n      destruct (get 0 str) eqn:H'; [ | solve [ t ] ].\n      destruct offset as [|offset].\n      { rewrite compute_next_bin_op'_recr.\n        rewrite drop_0, H'.\n        unfold list_of_next_bin_ops'_step; simpl.\n        rewrite drop_0.\n        unfold compute_next_bin_op'_step, list_of_next_bin_ops'_step'.\n        rewrite <- !IHlen; clear IHlen.\n        repeat match goal with\n                 | [ |- context[if ?e then _ else _] ] => destruct e eqn:?\n                 | _ => progress t\n                 | _ => reflexivity\n               end;\n          match goal with\n            | [ |- context[nth ?n (map ?f ?ls) _] ] => simpl rewrite <- (map_nth f ls nil n)\n          end;\n          destruct level; reflexivity. }\n      { rewrite <- IHlen; clear IHlen.\n        reflexivity. } }\n  Qed.\n\n  Definition list_of_next_bin_ops_spec''_0_0_bin_op {HSLP : StringLikeProperties Char} {table str idx ch}\n             (H_ch : (take 1 str ~= [ch])%string_like)\n             (H : is_bin_op ch)\n  : list_of_next_bin_ops_spec'' 0 (Some 0 :: table) str 0 idx.\n  Proof.\n    hnf; t.\n  Qed.\n\n  Lemma cell_of_next_bin_ops_spec''_compute_next_bin_op' {HSLP : StringLikeProperties Char}\n        {level str offset idx}\n  : cell_of_next_bin_ops_spec'' level (compute_next_bin_op' (drop offset str) level) str offset idx.\n  Proof.\n    revert level offset idx.\n    set (len := length str).\n    generalize (eq_refl : length str = len).\n    clearbody len.\n    revert str.\n    induction len; simpl; intros str Hlen level offset idx.\n    { hnf.\n      rewrite compute_next_bin_op'_nil by (rewrite drop_length; omega).\n      repeat split; intros.\n      { apply index_points_to_binop_nil; omega. }\n      { congruence. }\n      { apply index_not_points_to_binop_nil; omega. } }\n    { specialize (IHlen (drop 1 str)).\n      specialize_by (rewrite drop_length; omega).\n      setoid_rewrite drop_drop in IHlen; t_eq.\n      destruct offset as [|offset];\n        [\n        | solve [ eauto using cell_of_next_bin_op_spec''_S_offset with nocore ] ].\n      rewrite drop_0.\n      specialize (fun level => IHlen level 0).\n      split.\n      { specialize (fun level => IHlen level (pred idx)).\n        destruct idx as [|idx].\n        { clear IHlen.\n          rewrite compute_next_bin_op'_recr.\n          unfold compute_next_bin_op'_step.\n          repeat match goal with\n                   | [ |- context[match ?e with _ => _ end] ] => destruct e eqn:?\n                 end;\n          t. }\n        { rewrite compute_next_bin_op'_recr.\n          repeat match goal with\n                   | [ |- context[match ?e with _ => _ end] ] => destruct e eqn:?\n                 end;\n            [ | solve [ t ] ].\n          rewrite paren_balanced_hiding'_recr.\n          repeat match goal with\n                   | [ |- context[match ?e with _ => _ end] ] => destruct e eqn:?\n                 end;\n            [ | solve [ t ] ].\n          unfold compute_next_bin_op'_step, paren_balanced_hiding'_step, paren_balanced'_step, cell_of_next_bin_ops_spec'' in *.\n          repeat match goal with\n                   | _ => progress t\n                   | [ |- context[match ?e with _ => _ end] ] => destruct e eqn:?\n                   | [ H : context[match ?e with _ => _ end] |- _ ] => destruct e eqn:?\n                 end. } }\n      { specialize (fun level => IHlen level (pred idx)).\n        destruct idx as [|idx].\n        { clear IHlen.\n          rewrite compute_next_bin_op'_recr, paren_balanced'_recr.\n          unfold compute_next_bin_op'_step, paren_balanced'_step.\n          repeat match goal with\n                   | [ |- context[match ?e with _ => _ end] ] => destruct e eqn:?\n                 end;\n          t. }\n        { simpl in *.\n          rewrite compute_next_bin_op'_recr.\n          repeat match goal with\n                   | [ |- context[match ?e with _ => _ end] ] => destruct e eqn:?\n                 end;\n            [ | solve [ t ] ].\n          rewrite paren_balanced'_recr.\n          repeat match goal with\n                   | [ |- context[match ?e with _ => _ end] ] => destruct e eqn:?\n                 end;\n            [ | solve [ t ] ].\n          unfold compute_next_bin_op'_step, paren_balanced'_step, cell_of_next_bin_ops_spec'' in *.\n          repeat match goal with\n                   | _ => progress t\n                   | [ |- context[match ?e with _ => _ end] ] => destruct e eqn:?\n                   | [ H : context[match ?e with _ => _ end] |- _ ] => destruct e eqn:?\n                 end. } } }\n  Qed.\n\n  Lemma list_of_next_bin_ops'_satisfies_spec {HSLP : StringLikeProperties Char} (str : String)\n  : forall n,\n      list_of_next_bin_ops_spec' n (map (fun ls => nth n ls None) (list_of_next_bin_ops' str)) str.\n  Proof.\n    unfold list_of_next_bin_ops_spec'.\n    intros n offset idx.\n    unfold list_of_next_bin_ops_spec''.\n    rewrite tables_agree.\n    apply cell_of_next_bin_ops_spec''_compute_next_bin_op'.\n  Qed.\n\n  Lemma list_of_next_bin_ops_satisfies_spec {HSLP : StringLikeProperties Char} (str : String)\n  : list_of_next_bin_ops_spec (list_of_next_bin_ops str) str.\n  Proof.\n    apply list_of_next_bin_ops'_satisfies_spec.\n  Qed.\nEnd make_table.\n\nSection for_string.\n  Context {HSLM : StringLikeMin Ascii.ascii} {HSL : StringLike Ascii.ascii} {HSLP : StringLikeProperties Ascii.ascii}.\n  Context {pdata : paren_balanced_hiding_dataT Ascii.ascii}.\n\n  Definition list_of_next_bin_ops'_step'_opt\n    := (fun ch (table_higher_ops : option (list (option nat)) * list (option nat)) =>\n          let next_ops := map (option_map S) (match fst table_higher_ops with\n                                                | None => nil\n                                                | Some ls => ls\n                                              end) in\n          let '(cur_mark, new_higher_ops) := (nth 0 next_ops None, tl next_ops) in\n          (Some (if is_bin_op ch\n                 then Some 0 :: new_higher_ops\n                 else if is_open ch\n                      then new_higher_ops\n                      else if is_close ch\n                           then None :: next_ops\n                           else next_ops))).\n\n  Definition list_of_next_bin_ops'_step_opt\n    := (fun ch table_higher_ops =>\n          (list_of_next_bin_ops'_step'_opt ch table_higher_ops,\n           (match fst table_higher_ops with\n              | Some ls => nth 0 ls None :: snd table_higher_ops\n              | None => snd table_higher_ops\n            end))).\n\n  Definition list_of_next_bin_ops'_opt0 (str : String)\n  : option (list (option nat)) * list (option nat)\n    := fold\n         list_of_next_bin_ops'_step_opt\n         (None, nil)\n         str.\n\n  Section no_fold.\n    Local Arguments fold / _ _ _ _ _ _ _.\n    Local Arguments fold' / _ _ _ _ _ _ _ _.\n    Local Arguments list_of_next_bin_ops'_opt0 / _.\n    Local Arguments list_of_next_bin_ops'_step_opt / _ _.\n    Local Arguments list_of_next_bin_ops'_step'_opt / _ _.\n    Definition list_of_next_bin_ops'_opt (str : String)\n    : option (list (option nat)) * list (option nat)\n      := Eval simpl in list_of_next_bin_ops'_opt0 str.\n  End no_fold.\n\n  Definition list_of_next_bin_ops_opt (str : String)\n    := let ls' := list_of_next_bin_ops'_opt str in\n       match fst ls' with\n         | Some ls'' => nth 0 ls'' None :: snd ls'\n         | None => snd ls'\n       end.\n\n  Lemma list_of_next_bin_ops'_opt_correct (str : String)\n  : list_of_next_bin_ops'_opt str\n    = (nth 0 (map Some (list_of_next_bin_ops' str)) None,\n       tl (map (fun ls => nth 0 ls None) (list_of_next_bin_ops' str))).\n  Proof.\n    change list_of_next_bin_ops'_opt with list_of_next_bin_ops'_opt0.\n    unfold list_of_next_bin_ops', list_of_next_bin_ops'_opt0.\n    set (len := length str).\n    generalize (eq_refl : length str = len).\n    clearbody len.\n    revert str.\n    induction len; intros str H'.\n    { rewrite !fold_nil by assumption; reflexivity. }\n    { specialize (IHlen (drop 1 str)).\n      specialize_by (rewrite drop_length; omega).\n      rewrite !(fold_recr _ _ str).\n      destruct (get 0 str) eqn:H''.\n      { unfold list_of_next_bin_ops'_step_opt at 1.\n        rewrite !IHlen; clear IHlen.\n        unfold list_of_next_bin_ops'_step'_opt.\n        generalize (fold list_of_next_bin_ops'_step [] (drop 1 str)).\n        intros ls'.\n        unfold list_of_next_bin_ops'_step.\n        unfold list_of_next_bin_ops'_step'.\n        repeat match goal with\n                 | [ |- context[if ?e then _ else _] ] => destruct e eqn:?\n                 | _ => progress cbv beta\n                 | [ |- context[fst (?x, ?y)] ] =>\n                   change (fst (x, y)) with x\n                 | [ |- context[snd (?x, ?y)] ] =>\n                   change (snd (x, y)) with y\n                 | [ |- context[nth 0 (?x::?xs) ?v] ]\n                   => change (nth 0 (x::xs) v) with x\n                 | [ |- (_, _) = (_, _) ] => apply f_equal2\n                 | [ |- context[map ?f (?x::?xs)] ]\n                   => change (map f (x::xs)) with (f x :: map f xs)\n                 | [ |- Some _ = Some _ ] => apply f_equal\n                 | [ |- _::_ = _::_ ] => apply f_equal2\n                 | _ => reflexivity\n                 | [ |- context[nth 0 (map Some ?ls) None] ]\n                   => is_var ls; destruct ls\n               end. }\n      { reflexivity. } }\n  Qed.\n\n  Lemma list_of_next_bin_ops_opt_correct (str : String)\n  : list_of_next_bin_ops_opt str = list_of_next_bin_ops str.\n  Proof.\n    unfold list_of_next_bin_ops_opt, list_of_next_bin_ops.\n    rewrite !list_of_next_bin_ops'_opt_correct.\n    simpl.\n    generalize (list_of_next_bin_ops' str).\n    intro ls'.\n    destruct ls'; simpl; reflexivity.\n  Qed.\n\n  Lemma list_of_next_bin_ops_opt_satisfies_spec (str : String)\n  : list_of_next_bin_ops_spec (list_of_next_bin_ops_opt str) str.\n  Proof.\n    rewrite list_of_next_bin_ops_opt_correct.\n    apply list_of_next_bin_ops_satisfies_spec.\n  Qed.\nEnd for_string.\n\nSection no_records.\n  Section specialized.\n    Context {String : Type}.\n\n    Class list_of_next_bin_ops_opt_data :=\n      { is_open : Ascii.ascii -> bool;\n        is_close : Ascii.ascii -> bool;\n        is_bin_op : Ascii.ascii -> bool;\n        length : String -> nat;\n        get : nat -> String -> option Ascii.ascii;\n        unsafe_get : nat -> String -> Ascii.ascii }.\n    Context {ldata : list_of_next_bin_ops_opt_data}.\n\n    Section exploded.\n      Context (char_at_matches : nat -> String -> (Ascii.ascii -> bool) -> bool)\n              (is_char : String -> Ascii.ascii -> bool)\n              (take : nat -> String -> String)\n              (drop : nat -> String -> String)\n              (bool_eq : String -> String -> bool).\n\n      Local Instance temp_pbh : paren_balanced_hiding_dataT Ascii.ascii\n        := { is_open := is_open;\n             is_close := is_close;\n             is_bin_op := is_bin_op }.\n\n      Local Instance temp_hslm : StringLikeMin Ascii.ascii\n        := { length := length;\n             unsafe_get := unsafe_get;\n             char_at_matches := char_at_matches }.\n\n      Local Instance temp_hsl : StringLike Ascii.ascii\n        := { is_char := is_char;\n             drop := drop;\n             take := take;\n             get := get;\n             bool_eq := bool_eq }.\n\n      Local Arguments list_of_next_bin_ops'_opt / _ _ _ _.\n      Definition list_of_next_bin_ops'_opt_nor' (str : String)\n      : option (list (option nat)) * list (option nat)\n        := Eval simpl in list_of_next_bin_ops'_opt (str : @StringLike.String _ temp_hslm).\n    End exploded.\n\n    Definition list_of_next_bin_ops'_opt_nor (str : String)\n    : option (list (option nat)) * list (option nat)\n      := Eval unfold list_of_next_bin_ops'_opt_nor' in list_of_next_bin_ops'_opt_nor' str.\n\n    Definition list_of_next_bin_ops_opt_nor (str : String)\n      := let ls' := list_of_next_bin_ops'_opt_nor str in\n         match fst ls' with\n           | Some ls'' => nth 0 ls'' None :: snd ls'\n           | None => snd ls'\n         end.\n  End specialized.\n\n  Section correct.\n    Context {HSLM : StringLikeMin Ascii.ascii} {HSL : StringLike Ascii.ascii} {HSLP : StringLikeProperties Ascii.ascii}.\n    Context {pdata : paren_balanced_hiding_dataT Ascii.ascii}.\n\n    Global Instance default_list_of_next_bin_ops_opt_data : list_of_next_bin_ops_opt_data\n      := { is_open := ParenBalanced.Core.is_open;\n           is_close := ParenBalanced.Core.is_close;\n           is_bin_op := ParenBalanced.Core.is_bin_op;\n           length := StringLike.length;\n           get := StringLike.get;\n           unsafe_get := StringLike.unsafe_get }.\n\n    Lemma list_of_next_bin_ops'_opt_nor_correct (str : String)\n    : list_of_next_bin_ops'_opt_nor str\n      = (nth 0 (map Some (list_of_next_bin_ops' str)) None,\n         tl (map (fun ls => nth 0 ls None) (list_of_next_bin_ops' str))).\n    Proof.\n      exact (list_of_next_bin_ops'_opt_correct str).\n    Qed.\n\n    Lemma list_of_next_bin_ops_opt_nor_correct (str : String)\n    : list_of_next_bin_ops_opt_nor str = list_of_next_bin_ops str.\n    Proof.\n      exact (list_of_next_bin_ops_opt_correct str).\n    Qed.\n\n    Lemma list_of_next_bin_ops_opt_nor_satisfies_spec (str : String)\n    : list_of_next_bin_ops_spec (list_of_next_bin_ops_opt_nor str) str.\n    Proof.\n      exact (list_of_next_bin_ops_opt_satisfies_spec str).\n    Qed.\n  End correct.\nEnd no_records.\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/BinOpBrackets/MakeBinOpTable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.26909803175274005}}
{"text": "Require Import Coqlib.\nRequire Import ImpPrelude.\nRequire Import STS.\nRequire Import Behavior.\nRequire Import ModSem.\nRequire Import Skeleton.\nRequire Import PCM.\nRequire Import Mem1.\n\nSet Implicit Arguments.\n\n\n\n\n\nSection PROOF.\n\n  Context `{Σ: GRA.t}.\n  Context `{@GRA.inG memRA Σ}.\n\n  (* def new(): Ptr *)\n  (*   Ptr stk = alloc(1); *)\n  (*   return stk *)\n\n  Definition newF: list val -> itree Es val :=\n    fun args =>\n      _ <- (pargs [] args)?;;\n      `new_node: val  <- (ccallU \"alloc\" [Vint 1]);;\n      assume(wf_val new_node);;;\n      `_: val         <- (ccallU \"store\" [new_node; Vnullptr]);;\n      Ret new_node\n  .\n\n  (* def pop(Ptr stk): Int64 *)\n  (*   let hd := load(stk, 0); *)\n  (*   if(ptrcmp(hd, NULL) != 0) { *)\n  (*     let v    := load(hd, 0); *)\n  (*     let next := load(hd, 1); *)\n  (*     free(hd, 2); *)\n  (*     store(stk, 0, next); *)\n  (*     return v *)\n  (*   } *)\n  (*   return -1 *)\n\n  Definition popF: list val -> itree Es val :=\n    fun args =>\n      `stk: mblock <- (pargs [Tblk] args)?;;\n      `hd: val  <- (ccallU \"load\" [Vptr stk 0]);;\n      assume(wf_val hd);;;\n      `b: val   <- (ccallU \"cmp\"  [hd; Vnullptr]);;\n      assume((wf_val b) /\\ (match b with | Vint _ => True | _ => False end));;;\n      if dec (Vint 0) b\n      then (\n          let addr_val    := hd in\n          assume (match addr_val with | Vptr _ 0 => True | _ => False end);;;\n          `addr_next: val <- (vadd hd (Vint 8))?;;\n          `v: val         <- (ccallU \"load\"  [addr_val]);;\n          `next: val      <- (ccallU \"load\"  [addr_next]);;\n          `_: val         <- (ccallU \"free\"  [addr_val]);;\n          `_: val         <- (ccallU \"free\"  [addr_next]);;\n          `_: val         <- (ccallU \"store\" [Vptr stk 0; next]);;\n          Ret v\n        )\n      else Ret (Vint (- 1))\n  .\n\n  (* def push(Ptr stk, Int64 n): Unit *)\n  (*   let new_node := alloc(2); *)\n  (*   store(new_node, 0, n); *)\n  (*   let hd := load(stk, 0); *)\n  (*   store(new_node, 1, hd); *)\n  (*   store(stk, 0, new_node); *)\n  (*   return () *)\n\n  Definition pushF: list val -> itree Es val :=\n    fun args =>\n      '(stk, v)      <- (pargs [Tblk; Tuntyped] args)?;;\n      `new_node: val <- (ccallU \"alloc\" [Vint 2]);;\n      let addr_val   := new_node in\n      assume(match addr_val with | Vptr _ 0 => True | _ => False end);;;\n      addr_next      <- (vadd new_node (Vint 8))?;;\n      `hd: val       <- (ccallU \"load\"  [Vptr stk 0]);;\n      `_: val        <- (ccallU \"store\" [addr_val;   v]);;\n      `_: val        <- (ccallU \"store\" [addr_next; hd]);;\n      `_: val        <- (ccallU \"store\" [Vptr stk 0; new_node]);;\n      Ret Vundef\n  .\n\n  Definition StackSem: ModSem.t := {|\n    ModSem.fnsems := [(\"new\", cfunU newF); (\"pop\", cfunU popF); (\"push\", cfunU pushF)];\n    ModSem.mn := \"Stack\";\n    ModSem.initial_st := tt↑;\n  |}\n  .\n\n  Definition Stack: Mod.t := {|\n    Mod.get_modsem := fun _ => StackSem;\n    Mod.sk := [(\"new\", Sk.Gfun); (\"pop\", Sk.Gfun); (\"push\", Sk.Gfun)];\n  |}\n  .\nEnd PROOF.\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/Stack0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.26909802448265}}
{"text": "Require Import Common.Definitions.\nRequire Import Common.Values.\nRequire Import Source.Language.\nRequire Import Intermediate.CS.\nRequire Import Intermediate.GlobalEnv.\nRequire Import S2I.Compiler.\nRequire Export Extraction.Definitions.\n\nDefinition compile_and_run (p: Source.program) (fuel: nat) :=\n  match compile_program p with\n  | None => print_error ocaml_int_0\n  | Some compiled_p =>\n    let G := prepare_global_env compiled_p in\n    let st := CS.initial_machine_state compiled_p in\n    match CS.execN fuel G st with\n    | None => print_error ocaml_int_1\n    | Some n => print_ocaml_int (z2int n)\n    end\n  end.", "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/S2I/Examples/Helper.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.26906946907552276}}
{"text": "Require Export Util.\n\n(*-----  Abstract Data Type  -----*)\n\n(*  Heap Type  *)\n\nModule Type HEAP.\n\nParameter name : Set.\nParameter rtype : Set.\nParameter ref : Set.\nParameter alloc : Set.\nParameter super_env : Type.\nParameter field_type : Type.\nParameter type_env : Type.\n\nParameter heap : Type.\nParameter empty_heap : heap.\n\nParameter get : ref -> name -> heap -> option ref.\nParameter update : ref -> name -> ref -> heap -> heap.\nParameter new : ref -> field_type -> heap -> heap.\nParameter remove : ref -> name -> heap -> heap.\nParameter pin : ref -> name -> ref -> heap -> Prop.\n\nParameter pdisjoint : heap -> heap -> Prop.\nParameter union : heap -> heap -> heap. (* the two heaps should be disjoint *)\nParameter beq : heap -> heap -> bool.\nParameter eq : heap -> heap -> Prop.\nParameter subheap : heap -> heap -> Prop.\n\nParameter well_formed : super_env -> type_env -> heap -> Prop.\n\nInfix \"|=|\" := eq (at level 70) : heap_scope.\nInfix \"|+|\" := union (at level 60, right associativity) : heap_scope.\nInfix \"|*|\" := pdisjoint (at level 50) : heap_scope.\nInfix \"|<|\" := subheap (at level 70) : heap_scope.\nNotation \"{}\" := empty_heap : heap_scope.\n\nOpen Scope heap_scope.\n\nAxiom beq_refl : forall x : heap, beq x x = true.\nAxiom beq_sym : forall x y : heap, beq x y = true <-> beq y x = true.\nAxiom beq_trans : forall x y z : heap, beq x y = true -> beq y z = true -> beq x z = true.\n\nAxiom eq_refl : forall x : heap, x |=| x.\nAxiom eq_sym : forall x y : heap, x |=| y -> y |=| x.\nAxiom eq_trans : forall x y z : heap, x |=| y -> y |=| z -> x |=| z.\n\nAxiom subheap_refl : forall h : heap, h |<| h.\nAxiom subheap_asym : forall h1 h2 : heap, h1 |<| h2 -> h2 |<| h1 -> h1 |=| h2.\nAxiom subheap_trans : forall h1 h2 h3 : heap, h1 |<| h2 -> h2 |<| h3 -> h1 |<| h3.\nAxiom subheap_union : forall h1 h2 : heap, h1 |<| h2 |+| h1.\n\nAxiom update_update : forall r1 n r2 r3 h,\n    update r1 n r2 h = update r1 n r2 (update r1 n r3 h).\n\nAxiom in_update_1 : forall r1 n r2 h, pin r1 n r2 (update r1 n r2 h).\nAxiom in_update_2 : forall r1 r2 r3 r4 n1 n2 h,\n    (r1 <> r2 \\/ n1 <> n2) -> pin r1 n1 r3 h -> pin r1 n1 r3 (update r2 n2 r4 h).\nAxiom in_update_3 : forall r1 r2 r3 r4 n1 n2 h,\n    (r1 <> r2 \\/ n1 <> n2) -> pin r1 n1 r3 (update r2 n2 r4 h) -> pin r1 n1 r3 h.\nAxiom in_get : forall r1 r2 n h, pin r1 n r2 h <-> get r1 n h = Some r2.\nAxiom not_in_get : forall r1 n h, (forall r2, ~ pin r1 n r2 h) <-> get r1 n h = None.\n\nAxiom in_union_1 : forall r1 n r2 h1 h2,\n    pin r1 n r2 (h1 |+| h2) <-> pin r1 n r2 h1 \\/ pin r1 n r2 h2.\nAxiom in_union_2 : forall r1 n r2 h1 h2,\n    ~ pin r1 n r2 h1 -> (pin r1 n r2 h2 <-> pin r1 n r2 (h1 |+| h2)).\nAxiom not_in_empty_1 : forall r1 n r2, ~ pin r1 n r2 {}.\nAxiom in_equal : forall (r r1 r2 : ref) (n : name) (h : heap),\n    pin r n r1 h -> pin r n r2 h -> r1 = r2.\n\nAxiom pdisjoint_empty : forall x : heap, x |*| {}.\nAxiom pdisjoint_sym : forall x y : heap, x |*| y -> y |*| x.\nAxiom pdisjoint_union : forall h1 h2 h3 : heap,\n    h1 |*| (h2 |+| h3) <-> h1 |*| h2 /\\ h1 |*| h3.\nAxiom pdisjoint_self : forall h : heap, h |*| h -> h |=| {}.\n\nAxiom equal_1 : forall h1 h2 : heap, h1 |=| h2 -> beq h1 h2 = true.\nAxiom equal_2 : forall h1 h2 : heap, beq h1 h2 = true -> h1 |=| h2.\nAxiom equal_3 : forall h1 h2 : heap, h1 = h2 <-> h1 |=| h2.\nAxiom union_emp : forall h : heap, {} |+| h |=| h.\nAxiom union_comm : forall h1 h2 : heap, h1 |+| h2 |=| h2 |+| h1.\nAxiom union_asso : forall h1 h2 h3 : heap,\n    h1 |+| h2 |+| h3 |=| (h1 |+| h2) |+| h3.\n\nAxiom not_in_remove_1 : forall r1 n r2 h, ~ pin r1 n r2 (remove r1 n h).\nAxiom in_remove_2 : forall r1 r2 r3 n1 n2 h,\n    (r1 <> r2 \\/ n1 <> n2) -> pin r1 n1 r3 h -> pin r1 n1 r3 (remove r2 n2 h).\nAxiom in_remove_3 : forall r1 r2 r3 n1 n2 h,\n    pin r1 n1 r3 (remove r2 n2 h) -> pin r1 n1 r3 h.\nAxiom disjoint_remove : forall r1 n r2 h,\n    remove r1 n h |*| update r1 n r2 {}.\n\nClose Scope heap_scope.\n\nEnd HEAP.\n\n\n(*-----  Data  -----*)\n\n(*  Heap  *)\n\nModule Heap <: HEAP.\n\nDefinition name := Name.name.\nDefinition rtype := RType.rtype.\nDefinition ref := Ref.ref.\nDefinition alloc := Ref.alloc.\nDefinition super_env := RType.super_env.\nDefinition field_type := RType.field_type.\nDefinition type_env := RType.type_env.\n\nDefinition obj := Smap.t ref.\nDefinition heap := Rmap.t obj.\nDefinition empty_heap := Rmap.empty obj.\n\nDefinition get (r : ref) (n : name) (h : heap) : option ref :=\n    match Rmap.find r h with\n        | None => None\n        | Some o => Smap.find n o\n    end.\n\nDefinition update (r : ref) (n : name) (r1 : ref) (h : heap) : heap :=\n    match Rmap.find r h with\n        | None => Rmap.add r (Smap.add n r1 (Smap.empty ref)) h\n        | Some o => Rmap.add r (Smap.add n r1 o) h\n    end.\n\nDefinition remove (r : ref) (n : name) (h : heap) : heap :=\n    match Rmap.find r h with\n        | None => h\n        | Some o => Rmap.add r (Smap.remove n o) h\n    end.\n\nDefinition pin (r : ref) (n : name) (r1 : ref) (h : heap) : Prop :=\n    exists o, Rmap.MapsTo r o h /\\ Smap.MapsTo n r1 o.\n\nDefinition new (r : ref) (f : field_type) (h : heap) : heap :=\n    Rmap.add r (Smap.map (fun _ => Ref.rnull) f) h.\n\nDefinition pdisjoint (h1 h2 : heap) : Prop :=\n    forall (r1 r2 r3 : ref) (n : name), ~ (pin r1 n r2 h1 /\\ pin r1 n r3 h2).\n\nDefinition union1 (r : ref) (o : obj) (h : heap) : heap :=\n    match Rmap.find r h with\n        | None => Rmap.add r o h\n        | Some o1 => Rmap.add r (Smap.fold (Smap.add (elt:=ref)) o1 o) h\n    end.\nDefinition union (h1 h2 : heap) : heap :=\n    Rmap.fold union1 h1 h2.\n\nDefinition beq (h1 h2 : heap) : bool :=\n    Rmap.equal (Smap.equal Ref.beq) h1 h2.\n\n(* 如果 h1 与 h2 相差一个空对象，eq h1 h2 仍成立 *)\nDefinition eq (h1 h2 : heap) : Prop :=\n    forall (r1 r2 : ref) (n : name), pin r1 n r2 h1 <-> pin r1 n r2 h2.\n\nDefinition subheap (h1 h2 : heap) : Prop :=\n    forall (r1 r2 : ref) (n : name), pin r1 n r2 h1 -> pin r1 n r2 h2.\n\nBind Scope heap_scope with heap.\nDelimit Scope heap_scope with heap.\n\nInfix \"|=|\" := eq (at level 70) : heap_scope.\nInfix \"|+|\" := union (at level 60, right associativity) : heap_scope.\nInfix \"|*|\" := pdisjoint (at level 50) : heap_scope.\nInfix \"|<|\" := subheap (at level 70) : heap_scope.\nNotation \"{}\" := empty_heap : heap_scope.\n\nOpen Scope heap_scope.\n\nDefinition check_attr (s : super_env) (f : field_type) (n : name) (r : ref) (p : Prop) : Prop :=\n    match Smap.find n f with\n        | None => False\n        | Some t => \n            (RType.subtype (Ref.get_type r) t s) /\\ p\n    end.\nDefinition check_obj (s : super_env) (te : type_env) (r : ref) (o : obj) (p : Prop) : Prop :=\n    match Smap.find (Ref.get_type r) te with\n        | None => False\n        | Some f => \n            (o <> Smap.empty ref \\/ f = Smap.empty rtype) /\\\n            (Smap.fold (check_attr s f) o p)\n    end.\nDefinition well_formed (s : super_env) (te : type_env) (h : heap) : Prop :=\n    Rmap.fold (check_obj s te) h True.\n\nAxiom equal_1 : forall h1 h2 : heap, h1 |=| h2 -> beq h1 h2 = true.\nLemma equal_2 : forall h1 h2 : heap, beq h1 h2 = true -> h1 |=| h2.\nProof.\n  unfold beq; unfold eq. intros h1 h2 H r1 r2 n.\n  apply Rmap.equal_2 in H.\n  unfold Rmap.Equivb in H.\n  unfold Rmap.Raw.Equivb in H.\n  assert (forall r1 r2, Ref.beq r1 r2 = true <-> r1 = r2).\n  intros r0 r3. apply lr_trans with (b := Ref.peq r0 r3).\n  apply Ref.equal_1. apply Ref.equal_2.\n  destruct H. unfold pin. split. intro H2.\n  do 2 destruct H2. exists x. split.\n  assert (Rmap.Raw.PX.In r1 (Rmap.this h1)).\n  unfold Rmap.Raw.PX.In. exists x; apply H2.\n  apply H in H4. unfold Rmap.Raw.PX.In in H4.\n  destruct H4. apply H1 with (e' := x0) in H2.\n  apply smap_equal with (m1 := x) (m2 := x0) in H0.\n  apply H0 in H2. rewrite H2. assumption.\n  assumption. assumption. intro H2.\n  do 2 destruct H2. exists x. split.\n  assert (Rmap.Raw.PX.In r1 (Rmap.this h2)).\n  unfold Rmap.Raw.PX.In. exists x; apply H2.\n  apply H in H4. unfold Rmap.Raw.PX.In in H4.\n  destruct H4. assert (x0 = x).\n  apply H1 with (e' := x) in H4.\n  apply smap_equal with (m1 := x0) (m2 := x) in H0.\n  apply H0; assumption. assumption.\n  rewrite <- H5. assumption. assumption.\nQed.\nLemma equal_3 : forall h1 h2 : heap, h1 = h2 <-> h1 |=| h2.\nProof.\n  unfold eq. intros h1 h2. split.\n  intros H r1 r2 n. apply equal_2.\n  apply rmap_equal. intros e1 e2.\n  apply smap_equal. intros e0 e3.\n  apply lr_trans with (b := Ref.peq e0 e3).\n  apply Ref.equal_1. apply Ref.equal_2. assumption.\n  intro H. apply equal_1 in H. unfold beq in H.\n  assert (forall r1 r2, Ref.beq r1 r2 = true <-> r1 = r2).\n  intros r1 r2. apply lr_trans with (b := Ref.peq r1 r2).\n  apply Ref.equal_1. apply Ref.equal_2.\n  assert (forall o1 o2, (Smap.equal Ref.beq) o1 o2 = true <-> o1 = o2).\n  apply smap_equal. assumption.\n  apply rmap_equal with (m1 := h1) (m2 := h2) in H1.\n  apply H1; assumption.\nQed.\n\nLemma beq_refl : forall x : heap, beq x x = true.\nProof.\n  intro x. unfold beq.\n  apply rmap_refl_2. intro.\n  apply smap_refl_2. intro.\n  apply Ref.beq_refl.\nQed.\nLemma beq_sym : forall x y : heap, beq x y = true <-> beq y x = true.\nProof.\n  intros x y. unfold beq. split.\n  apply rmap_sym_2. intros.\n  apply smap_sym_2. intros.\n  apply Ref.beq_sym.\n  assumption. assumption.\n  apply rmap_sym_2. intros.\n  apply smap_sym_2. intros.\n  apply Ref.beq_sym.\n  assumption. assumption.\nQed.\nLemma beq_trans : forall x y z : heap, beq x y = true -> beq y z = true -> beq x z = true.\nProof.\n  unfold beq. intros x y z.\n  apply rmap_trans_2 with (e2 := y). intros.\n  apply smap_trans_2 with (e2 := t2). intros.\n  apply Ref.beq_trans with (y := t4).\n  assumption. assumption.\n  assumption. assumption.\nQed.\n\nLemma eq_refl : forall x : heap, x |=| x.\nProof.\n  unfold eq. intros. split.\n  intro; assumption.\n  intro; assumption.\nQed.\n\nLemma eq_sym : forall x y : heap, x |=| y -> y |=| x.\nProof.\n  unfold eq. intros; split.\n  apply H. apply H.\nQed.\n\nLemma eq_trans : forall x y z : heap, x |=| y -> y |=| z -> x |=| z.\nProof.\n  unfold eq. intros. split.\n  intro; apply H0; apply H; assumption.\n  intro; apply H; apply H0; assumption.\nQed.\n\nLemma subheap_refl : forall h : heap, h |<| h.\nProof.\n  unfold subheap.\n  intros h r1 r2 n H.\n  assumption.\nQed.\n\nLemma subheap_asym : forall h1 h2 : heap, h1 |<| h2 -> h2 |<| h1 -> h1 |=| h2.\nProof.\n  unfold subheap. unfold eq.\n  intros h1 h2 H H0 r1 r2 n.\n  split. apply H. apply H0.\nQed.\n\nLemma subheap_trans : forall h1 h2 h3 : heap, h1 |<| h2 -> h2 |<| h3 -> h1 |<| h3.\nProof.\n  unfold subheap.\n  intros h1 h2 h3 H H0 r1 r2 n H1.\n  apply H0. apply H. assumption.\nQed.\n\nLemma in_update_1 : forall r1 n r2 h, pin r1 n r2 (update r1 n r2 h).\nProof.\n  intros r1 n r2 h. unfold update.\n  case (Rmap.find r1 h).\n  intro o. unfold pin.\n  exists (Smap.add n r2 o). split.\n  apply Rmap.add_1; reflexivity.\n  apply Smap.add_1; reflexivity.\n  unfold pin.\n  exists (Smap.add n r2 (Smap.empty ref)).\n  split.\n  apply Rmap.add_1; reflexivity.\n  apply Smap.add_1; reflexivity.\nQed.\n\nLemma in_update_2 : forall r1 r2 r3 r4 n1 n2 h,\n    (r1 <> r2 \\/ n1 <> n2) -> pin r1 n1 r3 h -> pin r1 n1 r3 (update r2 n2 r4 h).\nProof.\n  intros r1 r2 r3 r4 n1 n2 h H H0.\n  unfold update. unfold pin in H0.\n  do 2 destruct H0.\n  case Ref.eq_dec with (x := r1) (y := r2).\n  intro H2.\n  destruct H. elim H; assumption.\n  rewrite <- H2. apply Rmap.find_1 in H0.\n  rewrite H0. exists (Smap.add n2 r4 x).\n  split. apply Rmap.add_1. reflexivity.\n  apply Smap.add_2. auto.\n  assumption. intro H2.\n  unfold pin. exists x.\n  split. case (Rmap.find r2 h).\n  intro o. apply Rmap.add_2. auto.\n  assumption. apply Rmap.add_2. auto.\n  assumption. assumption.\nQed.\n\nLemma in_update_3 : forall r1 r2 r3 r4 n1 n2 h,\n    (r1 <> r2 \\/ n1 <> n2) -> pin r1 n1 r3 (update r2 n2 r4 h) -> pin r1 n1 r3 h.\nProof.\n  intros r1 r2 r3 r4 n1 n2 h H H0.\n  unfold update in H0; unfold pin in H0.\n  do 2 destruct H0.\n  case Ref.eq_dec with (x := r1) (y := r2).\n  intro H2. destruct H. elim H; assumption.\n  rewrite <- H2 in H0.\n  inductS (Rmap.find r1 h); rewrite H3 in H0. unfold pin.\n  assert (x = Smap.add n2 r4 x0).\n  apply rmap_add in H0. assumption.\n  exists x0. split.\n  apply Rmap.find_2 in H3. assumption.\n  rewrite H4 in H1.\n  apply Smap.add_3 in H1. assumption. auto.\n  assert (x = Smap.add n2 r4 (Smap.empty ref)).\n  assert (Rmap.MapsTo r1 (Smap.add n2 r4 (Smap.empty ref))\n    (Rmap.add r1 (Smap.add n2 r4 (Smap.empty ref)) h)).\n  apply Rmap.add_1. reflexivity.\n  apply rmap_inject with (k := r1)\n    (m := (Rmap.add r1 (Smap.add n2 r4 (Smap.empty ref)) h));\n  assumption. rewrite H4 in H1.\n  apply Smap.add_3 in H1.\n  apply Smap.empty_1 in H1. elim H1. auto.\n  intro H2. inductS (Rmap.find r2 h); rewrite H3 in H0;\n  apply Rmap.add_3 in H0; unfold pin;\n  try (exists x; split; assumption); auto.\nQed.\n\nLemma in_get : forall r1 r2 n h, pin r1 n r2 h <-> get r1 n h = Some r2.\nProof.\n  intros r1 r2 n h.\n  split. intro H.\n  unfold pin in H.\n  do 2 destruct H.\n  unfold get.\n  apply Rmap.find_1 in H.\n  rewrite H.\n  apply Smap.find_1 in H0.\n  rewrite H0; reflexivity.\n  intro H. unfold get in H.\n  unfold pin.\n  inductS (Rmap.find r1 h); rewrite H0 in H.\n  apply Smap.find_2 in H.\n  apply Rmap.find_2 in H0.\n  exists x; split; assumption.\n  inversion H.\nQed.\n\nLemma not_in_get : forall r1 n h, (forall r2, ~ pin r1 n r2 h) <-> get r1 n h = None.\nProof.\n  intros r1 n h. split. intro H.\n  unfold pin in H. unfold get.\n  inductS (Rmap.find r1 h).\n  apply Rmap.find_2 in H0.\n  assert (forall r2, ~ Smap.MapsTo n r2 x).\n  intros r2 H1. elim H with (r2 := r2).\n  exists x; split; assumption.\n  inductS (Smap.find n x).\n  apply Smap.find_2 in H2.\n  elim H1 with (r2 := x0); assumption.\n  reflexivity. reflexivity.\n  intros H r2 H0. unfold get in H.\n  inductS (Rmap.find r1 h); rewrite H1 in H.\n  unfold pin in H0. do 2 destruct H0.\n  apply Rmap.find_1 in H0. rewrite H1 in H0.\n  inversion H0. rewrite <- H4 in H2.\n  apply Smap.find_1 in H2. rewrite H2 in H; inversion H.\n  do 2 destruct H0. apply Rmap.find_1 in H0.\n  rewrite H1 in H0; inversion H0.\nQed.\n\nLemma in_union_1 : forall r1 n r2 h1 h2,\n    pin r1 n r2 (h1 |+| h2) <-> pin r1 n r2 h1 \\/ pin r1 n r2 h2.\nProof.\n  unfold union.\n  intros r1 n r2 h1 h2.\n  split. intro H.\nAdmitted.\n\nLemma in_union_2 : forall r1 n r2 h1 h2, ~ pin r1 n r2 h1 ->\n    (pin r1 n r2 h2 <-> pin r1 n r2 (h1 |+| h2)).\nProof.\n  intros r1 n r2 h1 h2 H.\n  split. intro H0.\n  apply in_union_1.\n  right. assumption.\n  intro H0.\n  apply in_union_1 in H0.\n  case H0. intro H1.\n  elim H. assumption.\n  intro H1. assumption.\nQed.\n\n(* rnull/rtrue/rfalse has no field. *)\nAxiom not_in_null : forall n r h, ~ pin Ref.rnull n r h.\nAxiom not_in_true : forall n r h, ~ pin Ref.rtrue n r h.\nAxiom not_in_false : forall n r h, ~ pin Ref.rfalse n r h.\n\nLemma subheap_union : forall h1 h2 : heap, h1 |<| h2 |+| h1.\nProof.\n  unfold subheap. intros h1 h2 r1 r2 n H.\n  apply in_union_1. right; assumption.\nQed.\n\nLemma not_in_empty_1 : forall r1 n r2, ~ pin r1 n r2 {}.\nProof.\n  intros r1 n r2 H.\n  unfold pin in H.\n  destruct H; destruct H.\n  apply Rmap.empty_1 in H.\n  assumption.\nQed.\n\nLemma not_in_empty_2 : forall k, ~ Rmap.In k {}.\nProof.\n  intros k.\n  unfold Rmap.In.\n  unfold Rmap.Raw.PX.In.\n  intro H.\n  elim H.\n  intros x H0.\n  apply Rmap.empty_1 in H0.\n  assumption.\nQed.\n\nLemma pdisjoint_empty : forall x : heap, x |*| {}.\nProof.\n  unfold pdisjoint.\n  intros x r1 r2 r3 n H.\n  destruct H. unfold pin in H0.\n  destruct H0. destruct H0.\n  apply Rmap.empty_1 in H0.\n  elim H0.\nQed.\n\nLemma pdisjoint_sym : forall x y : heap, x |*| y -> y |*| x.\nProof.\n  unfold pdisjoint.\n  intros x y H r1 r2 r3 n H0.\n  elim H with (r1 := r1) (r2 := r3) (r3 := r2) (n := n).\n  destruct H0. split.\n  assumption. assumption.\nQed.\n\nLemma pdisjoint_union : forall h1 h2 h3 : heap,\n    h1 |*| (h2 |+| h3) <-> h1 |*| h2 /\\ h1 |*| h3.\nProof.\n  unfold pdisjoint.\n  intros h1 h2 h3.\n  split. intro H.\n  split. intros r1 r2 r3 n H0.\n  destruct H0.\n  elim H with (r1 := r1) (r2 := r2) (r3 := r3) (n := n).\n  split. assumption.\n  apply in_union_1.\n  left; assumption.\n  intros r1 r2 r3 n H0.\n  destruct H0.\n  elim H with (r1 := r1) (r2 := r2) (r3 := r3) (n := n).\n  split. assumption.\n  apply in_union_1.\n  right; assumption.\n  intros H r1 r2 r3 n H0.\n  destruct H. destruct H0.\n  apply in_union_1 in H2.\n  destruct H2.\n  elim H with (r1 := r1) (r2 := r2) (r3 := r3) (n := n).\n  split. assumption. assumption.\n  elim H1 with (r1 := r1) (r2 := r2) (r3 := r3) (n := n).\n  split. assumption. assumption.\nQed.\n\nLemma pdisjoint_self : forall h : heap, h |*| h -> h |=| {}.\nProof.\n  unfold eq; unfold pdisjoint.\n  intros h H r1 r2 n. split.\n  intro H0. \n  elim H with (r1 := r1) (r2 := r2) (r3 := r2) (n := n).\n  split. assumption. assumption.\n  intro H0. apply not_in_empty_1 in H0.\n  elim H0.\nQed.\n\nLemma exist_pdisjoint : forall h1 h2 : heap,\n    h1 |<| h2 -> exists h3 : heap, h3 |*| h1 /\\ h2 |=| h3 |+| h1.\nProof.\n(*\n  intros h1 h2 H. unfold subheap in H.\n  exists (diff_heap h1 h2). unfold diff_heap. split.\n  unfold pdisjoint. intros r1 r2 r3 n H0.\n  destruct H0. unfold pin in H1. do 2 destruct H1.\n  unfold pin in H0. do 2 destruct H0.\n  rewrite Rmap.fold_1 in H1.\n*)\nAdmitted.\n\nLemma in_equal : forall (r r1 r2 : ref) (n : name) (h : heap),\n    pin r n r1 h -> pin r n r2 h -> r1 = r2.\nProof.\n  unfold pin.\n  intros r r1 r2 n h H H0.\n  destruct H. destruct H0.\n  destruct H. destruct H0.\n  apply Rmap.find_1 in H.\n  apply Rmap.find_1 in H0.\n  rewrite H in H0.\n  inversion H0.\n  rewrite H4 in H1.\n  apply Smap.find_1 in H1.\n  apply Smap.find_1 in H2.\n  rewrite H1 in H2.\n  inversion H2.\n  reflexivity.\nQed.\n\nLemma update_update : forall r1 n r2 r3 h,\n    update r1 n r2 h = update r1 n r2 (update r1 n r3 h).\nProof.\n  intros r1 n r2 r3 h.\n  apply equal_3. unfold eq.\n  intros r0 r4 n0.\n  split. intro H.\n  case Ref.eq_dec with (x := r0) (y := r1).\n  case String.string_dec with (s1 := n0) (s2 := n).\n  intros H0 H1. rewrite H0. rewrite H1.\n  rewrite H0 in H. rewrite H1 in H.\n  assert (pin r1 n r2 (update r1 n r2 h)).\n  apply in_update_1.\n  assert (r2 = r4).\n  apply in_equal with (r := r1) (n := n) (h := update r1 n r2 h).\n  assumption. assumption.\n  rewrite H3. apply in_update_1.\n  intros H0 H1. apply in_update_3 in H.\n  apply in_update_2.\n  right; assumption.\n  apply in_update_2.\n  right; assumption. assumption.\n  right; assumption.\n  intro H0. apply in_update_3 in H.\n  apply in_update_2.\n  left; assumption.\n  apply in_update_2.\n  left; assumption. assumption.\n  left; assumption.\n  intro H.\n  case Ref.eq_dec with (x := r0) (y := r1).\n  case String.string_dec with (s1 := n0) (s2 := n).\n  intros H0 H1. rewrite H0. rewrite H1.\n  rewrite H0 in H. rewrite H1 in H.\n  assert (pin r1 n r2 (update r1 n r2 (update r1 n r3 h))).\n  apply in_update_1.\n  assert (r2 = r4).\n  apply in_equal with (r := r1) (n := n) (h := update r1 n r2 (update r1 n r3 h)).\n  assumption. assumption.\n  rewrite H3. apply in_update_1.\n  intros H0 H1. apply in_update_3 in H.\n  apply in_update_2.\n  right; assumption.\n  apply in_update_3 in H. assumption.\n  right; assumption.\n  right; assumption.\n  intro H0. apply in_update_3 in H.\n  apply in_update_2.\n  left; assumption.\n  apply in_update_3 in H. assumption.\n  left; assumption.\n  left; assumption.\nQed.\n\nLemma union_emp : forall h : heap, {} |+| h |=| h.\nProof.\n  unfold eq; unfold union.\n  intros h r1 r2 n.\n  split. intro H.\n  apply in_union_1 in H.\n  destruct H.\n  assert (~ pin r1 n r2 empty_heap).\n  apply not_in_empty_1 in H. elim H.\n  elim H0. assumption.\n  assumption.\n  intro H.\n  apply in_union_1.\n  right. assumption.\nQed.\n\nLemma union_comm : forall h1 h2 : heap, h1 |+| h2 |=| h2 |+| h1.\nProof.\n  unfold eq; unfold union.\n  assert (forall (h1 h2 : heap) (r1 r2 : ref) (n : name),\n    pin r1 n r2 (Rmap.fold union1 h1 h2) -> pin r1 n r2 (Rmap.fold union1 h2 h1)).\n  intros h1 h2 r1 r2 n H.\n  apply in_union_1 in H.\n  apply in_union_1.\n  destruct H.\n  right; assumption.\n  left; assumption.\n  split. apply H. apply H.\nQed.\n\nLemma union_asso : forall h1 h2 h3 : heap,\n    h1 |+| h2 |+| h3 |=| (h1 |+| h2) |+| h3.\nProof.\n  unfold eq; unfold union.\n  intros h1 h2 h3 r1 r2 n.\n  split. intro H.\n  apply in_union_1 in H.\n  apply in_union_1.\n  destruct H. left.\n  apply in_union_1.\n  left; assumption.\n  apply in_union_1 in H.\n  destruct H. left.\n  apply in_union_1.\n  right; assumption.\n  right; assumption.\n  intro H.\n  apply in_union_1 in H.\n  apply in_union_1.\n  destruct H.\n  apply in_union_1 in H.\n  destruct H.\n  left; assumption.\n  right; apply in_union_1.\n  left; assumption.\n  right; apply in_union_1.\n  right; assumption.\nQed.\n\nLemma not_in_remove_1 : forall r1 n r2 h, ~ pin r1 n r2 (remove r1 n h).\nProof.\n  intros r1 n r2 h H.\n  unfold remove in H.\n  inductS (Rmap.find r1 h); rewrite H0 in H.\n  unfold pin in H. do 2 destruct H.\n  assert (x0 = Smap.remove n x).\n  apply rmap_add in H. assumption.\n  rewrite H2 in H1.\n  assert (Smap.In n (Smap.remove n x)).\n  exists r2. assumption.\n  apply Smap.remove_1 in H3.\n  elim H3. reflexivity.\n  unfold pin in H. do 2 destruct H.\n  apply Rmap.find_1 in H.\n  rewrite H0 in H. inversion H.\nQed.\n\nLemma in_remove_2 : forall r1 r2 r3 n1 n2 h,\n    (r1 <> r2 \\/ n1 <> n2) -> pin r1 n1 r3 h -> pin r1 n1 r3 (remove r2 n2 h).\nProof.\n  intros r1 r2 r3 n1 n2 h H H0.\n  unfold remove.\n  inductS (Rmap.find r2 h).\n  do 2 destruct H0.\n  destruct H. exists x0. split.\n  apply Rmap.add_2. auto.\n  assumption. assumption.\n  case (Ref.eq_dec r1 r2).\n  intro H3. rewrite <- H3.\n  rewrite <- H3 in H1.\n  apply Rmap.find_2 in H1.\n  exists (Smap.remove (elt:=ref) n2 x).\n  split. apply Rmap.add_1. reflexivity.\n  apply Smap.remove_2. auto.\n  assert (x0 = x).\n  apply rmap_inject with (k := r1) (m := h).\n  assumption. assumption.\n  rewrite <- H4. assumption.\n  intro H3. exists x0. split.\n  apply Rmap.add_2. auto.\n  assumption. assumption. assumption.\nQed.\n\nLemma in_remove_3 : forall r1 r2 r3 n1 n2 h,\n    pin r1 n1 r3 (remove r2 n2 h) -> pin r1 n1 r3 h.\nProof.\n  intros r1 r2 r3 n1 n2 h H.\n  unfold remove in H.\n  inductS (Rmap.find r2 h); rewrite H0 in H.\n  do 2 destruct H.\n  case (Ref.eq_dec r1 r2).\n  intro H2. rewrite <- H2 in H.\n  assert (x0 = Smap.remove n2 x).\n  apply rmap_add in H. assumption.\n  exists x. split. rewrite <- H2 in H0.\n  apply Rmap.find_2 in H0. assumption.\n  rewrite H3 in H1.\n  apply Smap.remove_3 with (x := n2).\n  assumption.\n  intro H2. exists x0. split.\n  apply Rmap.add_3 in H. assumption.\n  auto. assumption. assumption.\nQed.\n\nLemma disjoint_remove : forall r1 n r2 h, remove r1 n h |*| update r1 n r2 {}.\nProof.\n  unfold pdisjoint.\n  intros r1 n r2 h r0 r3 r4 n0 H.\n  destruct H.\n  case Ref.eq_dec with (x := r0) (y := r1).\n  intro H1. rewrite H1 in H.\n  case String.string_dec with (s1 := n0) (s2 := n).\n  intro H2. rewrite H2 in H.\n  apply not_in_remove_1 in H. elim H.\n  intro H2.\n  apply in_update_3 in H0.\n  apply not_in_empty_1 in H0.\n  elim H0. right; assumption.\n  intro H1.\n  case String.string_dec with (s1 := n0) (s2 := n).\n  intro H2. apply in_update_3 in H0.\n  apply not_in_empty_1 in H0.\n  elim H0. left; assumption.\n  intro H2. apply in_update_3 in H0.\n  apply not_in_empty_1 in H0.\n  elim H0. left; assumption.\nQed.\n\nClose Scope heap_scope.\nEnd Heap.\n\nBind Scope heap_scope with Heap.heap.\nDelimit Scope heap_scope with heap.\n\nInfix \"|=|\" := Heap.eq (at level 70) : heap_scope.\nInfix \"|+|\" := Heap.union (at level 60, right associativity) : heap_scope.\nInfix \"|*|\" := Heap.pdisjoint (at level 50) : heap_scope.\nInfix \"|<|\" := Heap.subheap (at level 70) : heap_scope.\nNotation \"{}\" := Heap.empty_heap : heap_scope.\n", "meta": {"author": "fm-pku", "repo": "VeriJ-tool", "sha": "a31633f866c2668bbe403d3974d734e10f0e89c8", "save_path": "github-repos/coq/fm-pku-VeriJ-tool", "path": "github-repos/coq/fm-pku-VeriJ-tool/VeriJ-tool-a31633f866c2668bbe403d3974d734e10f0e89c8/Heap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2690694690755227}}
{"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 InvariantVoidnessPreservation.\n\nModule MyVoidnessPreservation :=\n  InvariantVoidnessPreservation.VoidnessPreservationBase\n    Dynamics.StrictDynamics.\nImport MyVoidnessPreservation.\n\n(* -------------------- Examples from email threads -------------------- *)\n\n(* A<Object> x = new A<void>(); // No *)\nGoal ~(VoidnessPreserves dt_A_void dt_A_Object).\n  intro H. inversion H; simpl in *.\n  - inversion H2. inversion H5.\n    + inversion H8. intuition H14.\n    + inversion H8; subst.\n      * inversion H14. inversion H4.\n      * inversion H8. inversion H4. inversion H14. inversion H3. inversion H10.\nQed.\n\n(* A<dynamic> x = new A<void>(); // No *)\nGoal ~(VoidnessPreserves dt_A_void dt_A_dynamic).\n  intro H. inversion H; simpl in *.\n  - inversion H2. inversion H5. \n    + inversion H8. intuition H14.\n    + inversion H8. \n      * inversion H14. inversion H20. exact H23.\n      * inversion H13. inversion H17.      \nQed.\n\n(* A<Object> x = new A<dynamic>(); // Yes *)\nGoal VoidnessPreserves dt_A_dynamic dt_A_Object.\n  unfold dt_A_dynamic, dt_A_Object, ct_A_dynamic, ct_A_Object.\n  apply vp_class. apply vctsp_cons.\n  - apply vctp_some. apply vctps_first. \n    + apply vpp_cons; auto.\n    + apply vpp_cons; auto. apply vp_class_dynamic.\n  - apply vctsp_cons; auto.\n    apply vctp_some. apply vctps_rest. apply vctps_first; auto.\nQed.\n\n(* A<void> x = new A<dynamic>(); // voidV = dynamicV, No *)\nGoal ~(VoidnessPreserves dt_A_dynamic dt_A_void).\n  intro H. inversion H; simpl in *.\n  - inversion H2. inversion H5.\n    + inversion H8. intuition H14.\n    + inversion H8.\n      * inversion H16. inversion H20. exact H23. \n      * inversion H13. inversion H17.\nQed.\n\n(* A<void> x = new A<Object>(); // voidV = objectV, No *)\nGoal ~(VoidnessPreserves dt_A_Object dt_A_void).\n  intro H. inversion H; simpl in *.\n  - inversion H2. inversion H5.\n    + inversion H8. intuition H14. \n    + inversion H8. \n      * inversion H16. inversion H20.\n      * inversion H13. inversion H17.\nQed.\n\n(* dynamic x = new A<void>(); // Yes *)\nGoal VoidnessPreserves dt_A_void dt_dynamic.\n  unfold dt_A_void, ct_A_void. auto.\nQed.\n\n(* Object x = new A<void>(); // Yes *)\nGoal VoidnessPreserves dt_A_void dt_Object.\n  unfold dt_A_void, dt_Object, ct_A_void, ct_Object.\n  apply vp_class. apply vctsp_cons; auto.\n  apply vctp_gone. apply vctg_cons; auto. discriminate.\nQed.\n\n(* Iterable<void> x = new List<void>(); // Yes *)\nGoal VoidnessPreserves dt_List_void dt_Iterable_void.\n  simpl.\n  - apply vp_class. apply vctsp_cons.\n    + apply vctp_gone; apply vctg_cons. discriminate.\n      apply vctg_cons; auto. discriminate.\n    + apply vctsp_cons.\n      * apply vctp_some; auto. apply vctps_first; auto. \n      * apply vctsp_cons; auto. \n        apply vctp_some. apply vctps_rest. apply vctps_first; auto.\nQed.\n\n(* List<void> x = new Iterable<void>(); // Yes *)\nGoal VoidnessPreserves dt_Iterable_void dt_List_void.\n  simpl.\n  - apply vp_class. apply vctsp_cons.\n    + apply vctp_some. apply vctps_rest. apply vctps_first.\n      * apply vpp_cons. apply vp_any_void. auto.\n      * apply vpp_cons. apply vp_any_void. auto.\n    + apply vctsp_cons.\n      * apply vctp_some. apply vctps_rest. apply vctps_rest.\n        apply vctps_first. auto. auto.\n      * apply vctsp_nil.\nQed.\n\n(* Iterable<Object> x = new List<void>(); // No *)\nGoal ~(VoidnessPreserves dt_List_void dt_Iterable_Object).\n  intro H. inversion H. \n  - inversion H2. inversion H7. inversion H10. \n    + inversion H13. intuition H19.\n    + inversion H13. \n      * inversion H19. inversion H25. \n      * inversion H18. inversion H22.\nQed.\n\n(* List<Object> x = new Iterable<void>(); // No *)\nGoal ~(VoidnessPreserves dt_Iterable_void dt_List_Object).\n  intro H. inversion H. \n  - inversion H2. inversion H5. \n    + inversion H8. inversion H17. intuition H21.\n    + inversion H8. inversion H13. \n      * inversion H18. inversion H24.\n      * inversion H17. inversion H21.\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/ClassInvariantStrictTest.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2690694690755227}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Import Tweetnacl_verif.init_tweetnacl.\nRequire Import Tweetnacl.Libs.Export.\nRequire Import Tweetnacl.ListsOp.Export.\nRequire Import Tweetnacl.Low.Car25519.\nRequire Import Tweetnacl.Low.Carry_n.\nRequire Import Tweetnacl.Low.BackCarry.\nRequire Import Tweetnacl.Mid.Car25519.\nRequire Import Tweetnacl.Mid.Reduce.\nLocal Open Scope Z.\n\nLemma car_low_level: forall contents_o,\n  Forall (fun x : ℤ => - 2 ^ 62 < x < 2 ^ 62) contents_o ->\n  Zlength contents_o = 16 -> forall i, 0 <= i < 15 -> 0 <= i < Zlength (map Int64.repr (Carrying_n 16 (nat_of_Z i) 0 contents_o)) ->\nmVI64 (Carrying_n 16 (nat_of_Z (i + 1)) 0 contents_o) =\nupd_Znth i\n  (upd_Znth (i + 1) (mVI64 (Carrying_n 16 (nat_of_Z i) 0 contents_o))\n     (Vlong\n        (Int64.add (Int64.repr (Znth (i + 1) (Carrying_n 16 (nat_of_Z i) 0 contents_o) 0))\n           (Int64.shr (Int64.repr (Znth i (Carrying_n 16 (nat_of_Z i) 0 contents_o) 0)) (Int64.repr 16)))))\n  (force_val\n     (sem_cast_l2l\n        (force_val\n           (sem_and tlg tint\n              (Znth i\n                 (upd_Znth (i + 1) (mVI64 (Carrying_n 16 (nat_of_Z i) 0 contents_o))\n                    (Vlong\n                       (Int64.add (Int64.repr (Znth (i + 1) (Carrying_n 16 (nat_of_Z i) 0 contents_o) 0))\n                          (Int64.shr (Int64.repr (Znth i (Carrying_n 16 (nat_of_Z i) 0 contents_o) 0)) (Int64.repr 16)))))\n                 Vundef) (Vint (Int.repr 65535)))))).\nProof.\n  intros contents_o Hcontents_o Hlengthcontents_o i Hi HiL.\n  assert(Hlength2: 0 <= i + 1 < Zlength (Carrying_n 16 (nat_of_Z i) 0 contents_o)).\n  {\n    assert(exists i', nat_of_Z i = i') by eauto.\n    destruct H as [i' Hi'].\n    assert(0 <= Z.of_nat i' < 15).\n    rewrite -Hi' /nat_of_Z Z2Nat.id ; omega.\n    rewrite Carrying_n_Zlength ; [ |rewrite Zlength_correct in Hlengthcontents_o] ; go.\n  }\n  rewrite upd_Znth_map.\n  repeat rewrite Int64.shr_div_two_p.\n  rewrite (Int64.unsigned_repr 16).\n  2: solve_bounds_by_values.\n  rewrite add64_repr.\n  rewrite upd_Znth_map.\n  rewrite (Znth_map Int64.zero).\n  2: rewrite Zlength_map upd_Znth_Zlength ; omega.\n  rewrite (Znth_map 0).\n  2: rewrite upd_Znth_Zlength ; omega.\n  rewrite (Int64.signed_repr (Znth i (Carrying_n 16 (nat_of_Z i) 0 contents_o) 0)).\n  2: {\n  apply Forall_Znth ; try omega.\n  eapply list.Forall_impl.\n  rewrite Zlength_correct in Hlengthcontents_o;\n  eapply Zcarry_n_bounds_length ; go.\n  intros ; simpl in H ; solve_bounds_by_values.\n  }\n  rewrite /sem_and /tint /sem_binarith /classify_binarith.\n  simpl sem_cast.\n  rewrite /sem_cast_i2l /sem_cast_l2l /both_long /force_val.\n  rewrite /cast_int_long.\n  rewrite and64_repr.\n  rewrite upd_Znth_map.\n  rewrite upd_Znth_map.\n  f_equal.\n  f_equal.\n  rewrite Int.signed_repr.\n  2: solve_bounds_by_values.\n  change 65535 with (Z.ones 16).\n  rewrite Z.land_comm.\n  repeat orewrite upd_Znth_upd_nth.\n  repeat orewrite Znth_nth.\n  unfold nat_of_Z.\n  assert(Hi': exists i', Z.to_nat i = i') by eauto.\n  destruct Hi' as [i' Hi'].\n  assert_gen_hyp_ Hid i 14 14.\n  omega.\n  rewrite Zlength_correct in Hlengthcontents_o.\n  assert(Ho' : (length contents_o = 16)%nat) by go.\n  repeat (destruct contents_o ; tryfalse).\n\n  repeat match goal with\n      | [H : _ \\/ _ |- _ ] => destruct H ; subst\n      | _ => idtac\n    end; Grind_add_Z; repeat change_Z_to_nat ; repeat rewrite Carry_n_step ; repeat rewrite Carry_n_step_0 ; unfold upd_nth ; unfold nth;\n  unfold getResidue ;\n  unfold getCarry ;\n  repeat orewrite Int64.Zshiftl_mul_two_p ; repeat orewrite Int64.Zshiftr_div_two_p ; reflexivity.\nQed.\n\nLemma car25519low_level: forall o, Forall (fun x : ℤ => - 2 ^ 62 < x < 2 ^ 62) o ->\nZlength o = 16 ->\nforall c, Vlong c = Vlong (Int64.repr (Znth 15 (Carrying_n 16 15 0 o) 0)) ->\nforall d, Vlong d = Vlong (Int64.repr (Znth 0 (Carrying_n 16 15 0 o) 0)) ->\nmVI64 (car25519 o) =\nupd_Znth 15\n  (upd_Znth 0 (mVI64 (Carrying_n 16 (Pos.to_nat 15) 0 o))\n     (Vlong (Int64.add d (Int64.mul (Int64.repr 38) (Int64.shr c (Int64.repr 16))))))\n  (force_val\n     (sem_cast_l2l\n        (force_val\n           (sem_and tlg tint\n              (Znth 15\n                 (upd_Znth 0 (mVI64 (Carrying_n 16 (Pos.to_nat 15) 0 o))\n                    (Vlong (Int64.add d (Int64.mul (Int64.repr 38) (Int64.shr c (Int64.repr 16)))))) Vundef)\n              (Vint (Int.repr 65535)))))).\nProof.\n  intros o Ho Hlengtho c Hc d Hd.\n  assert(HZl: Zlength (Carrying_n 16 15 0 o) = 16).\n    rewrite Carrying_n_Zlength ; [omega |rewrite Zlength_correct in Hlengtho] ; rewrite Hlengtho ; compute ; reflexivity.\n  change (Pos.to_nat 15) with (15%nat) in *.\n  change (nat_of_Z 15) with (15%nat) in *.\n  change (Z.to_nat 15) with (15%nat) in *.\n  assert(Hlength': Datatypes.length o = 16%nat).\n    rewrite Zlength_correct in Hlengtho ; omega.\n  assert(Hlength: 0 <= 15 < Zlength (Carrying_n 16 15 0 o)).\n    rewrite Carrying_n_Zlength; try omega ; rewrite Hlength'; reflexivity.\n  assert(H1516: 0 <= 15 < 16) by omega.\n  assert(H016: 0 <= 0 < 16) by omega.\n  assert(Hcorrolary15 := Zcarry_n_bounds_length o Hlength' Ho 15 H1516).\n  assert(Hcorrolary0 := Zcarry_n_bounds_length o Hlength' Ho 0 H016).\n  change (Z.to_nat 15) with 15%nat in Hcorrolary15.\n  change (Z.to_nat 0) with 0%nat in Hcorrolary0.\n  assert(Vlong_inv: forall a b, Vlong a = Vlong b -> a = b) by congruence.\n  apply Vlong_inv in Hc.\n  apply Vlong_inv in Hd.\n  subst c d.\n  repeat rewrite Int64.shr_div_two_p.\n  rewrite (Int64.unsigned_repr 16).\n  2: solve_bounds_by_values.\n  rewrite mul64_repr.\n  rewrite add64_repr.\n  rewrite upd_Znth_map.\n  rewrite (Znth_map Int64.zero).\n  2: rewrite upd_Znth_Zlength Zlength_map ; omega.\n  rewrite /sem_and /tint /sem_binarith /classify_binarith.\n  simpl sem_cast.\n  rewrite /sem_cast_i2l /sem_cast_l2l /both_long /force_val /cast_int_long.\n  rewrite upd_Znth_map.\n  rewrite upd_Znth_map.\n  rewrite (Znth_map 0).\n  2: rewrite upd_Znth_Zlength ; omega.\n  rewrite and64_repr.\n  rewrite upd_Znth_map.\n  f_equal.\n  f_equal.\n  unfold car25519.\n  remember (Carrying_n 16 15 0 o) as carr_list.\n  assert(Hlength_car: (length carr_list = 16)%nat).\n    subst ; rewrite Carrying_n_length ; rewrite Zlength_correct in Hlengtho ; omega.\n  rewrite Int.signed_repr.\n  2: solve_bounds_by_values.\n  rewrite Int64.signed_repr.\n  2:{\n    apply Forall_Znth.\n    omega.\n    eapply Forall_impl ; eauto;\n    let Hx := fresh in intros ? Hx ;\n    simpl in Hx;\n    solve_bounds_by_values.\n  }\n  repeat (destruct carr_list ; tryfalse).\n  simpl backCarry;\n  repeat orewrite upd_Znth_upd_nth;\n  repeat orewrite Znth_nth;\n  unfold nat_of_Z;\n  repeat change_Z_to_nat;\n  unfold nth;\n  unfold upd_nth;\n  unfold getResidue;\n  unfold getCarry.\n  change 65535 with (Z.ones 16).\n  rewrite Z.land_comm.\n  orewrite Int64.Zshiftr_div_two_p => //.\nQed.\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_car25519_compute.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.26906946272346455}}
{"text": "(* an abstract structured pools contract *)\n\nFrom PhD.Specifications.FA2Spec Require FA2Spec.\nFrom ConCert.Execution Require Import Blockchain.\nFrom ConCert.Execution Require Import BuildUtils.\nFrom ConCert.Execution Require Import Containers.\nFrom ConCert.Execution Require Import ContractCommon.\nFrom ConCert.Execution Require Import Monad.\nFrom ConCert.Execution Require Import ResultMonad.\nFrom ConCert.Execution Require Import Serializable.\nFrom ConCert.Utils Require Import RecordUpdate.\nFrom ConCert.Utils Require Import Extras.\nFrom Coq Require Import Ensembles.\nFrom Coq Require Import ZArith_base.\nFrom Coq Require Import QArith_base.\nFrom Coq Require Import String.\nFrom Coq Require Import List.\nFrom Coq Require Import Fin.\nFrom Coq.Init Require Import Byte.\n\nImport ListNotations.\nOpen Scope N_scope.\nOpen Scope string.\n\n(* =============================================================================\n * Defintions:\n      We begin with some type and auxiliary definitions which we use for the \n      contract specification.\n * ============================================================================= *)\n\nSection Definitions.\nContext {Base : ChainBase}.\n\n(* ConCert specific types *)\nDefinition error : Type := N.\n\n    Section ErrorCodes. \n\n    Definition error_PERMISSIONS_DENIED : error := 1.\n    Definition error_CONTRACT_NOT_FOUND : error := 2.\n    Definition error_TOKEN_NOT_FOUND : error := 3.\n    Definition error_INSUFFICIENT_BALANCE : error := 4.\n    Definition error_CALL_VIEW_FAILED : error := 5.\n    Definition error_FAILED_ASSERTION : error := 6.\n    Definition error_FAILED_DIVISION : error := 7.\n    Definition error_FAILED_TO_INITIALIZE : error := 8.\n\n    End ErrorCodes.\n\nDefinition token : Type := FA2Spec.token. (* token_address and token_id fields *)\nDefinition exchange_rate := N. (* always divided by 1_000_000n in the code  *)\n\nDefinition transfer_to := FA2Spec.transfer_to.\nDefinition transfer_data := FA2Spec.transfer_data.\n\nDefinition mint_data := FA2Spec.mint_data.\nDefinition mint := FA2Spec.mint.\n\nRecord pool_data := {\n    token_pooled : token ;\n    qty_pooled : N ; (* the qty of tokens to be pooled *)\n}.\n\nRecord unpool_data := {\n    token_unpooled : token ;\n    qty_unpooled : N ; (* the qty of pool tokens being turned in *)\n}.\n\nRecord trade_data := {\n    token_in_trade : token ; \n    token_out_trade : token ; \n    qty_trade : N ; (* the qty of token_in going in *)\n}.\n\nInductive entrypoint := \n(* pooling and trading *)\n| Pool : pool_data -> entrypoint \n| Unpool : unpool_data -> entrypoint \n| Trade : trade_data -> entrypoint.\n\nDefinition calc_delta_y (rate_in : N) (rate_out : N) (qty_trade : N) (k : N) (x : N) : N := \n    (* calculate ell *)\n    let l := N.sqrt (k * (1_000_000 * 1_000_000) / (rate_in * rate_out)) in \n    (* calculate the exchange rate *)\n    l * rate_in / 1_000_000 - k / ((l * rate_out) / 1_000_000 + qty_trade).\n\nDefinition calc_rate_in (rate_in : N) (rate_out : N) (qty_trade : N) (k : N) (x : N) : N :=\n    let delta_y := calc_delta_y rate_in rate_out qty_trade k x in \n    (rate_in * x / 1_000_000 + rate_out * delta_y / 1_000_000) / (x + qty_trade).\n\n(* a function to get a balance from an FMap *)\nDefinition get_bal (t : token) (tokens_held : FMap token N) := \n    match FMap.find t tokens_held with | Some b => b | None => 0 end.\n\n(* the same function, but named differently for the sake of clarity *)\nDefinition get_rate (t : token) (rates : FMap token N) : N :=\n    match FMap.find t rates with | Some r => r | None => 0 end.\n\nEnd Definitions.\n\n\n(* the abstract specification *)\nSection AbstractSpecification.\nContext {Base : ChainBase}\n\n(* =============================================================================\n * The Contract Specification:\n      We detail a list of propositions of a contract's behavior which can be \n      proven true of a given contract.\n * ============================================================================= *)\n\n    { Setup Msg State Error : Type }\n    `{Serializable Msg}  `{Serializable Setup}  `{Serializable State} `{Serializable Error}.\n\n(* Specification of the Msg type:\n  - A Pool entrypoint, whose interface is defined by the pool_data type\n  - An Unpool entrypoint, whose interface is defined by the unpool_data type\n  - A Trade entrypoint, whose interface is defined by the trade_data type\n*)\nClass Msg_Spec (T : Type) := \n  build_msg_spec {\n    pool : pool_data -> T ;\n    unpool : unpool_data -> T ;\n    trade : trade_data -> T ;\n}.\n\n(* specification of the State type:\n  - keeps track of:\n    - the exchange rates\n    - tokens held\n    - pool token address\n    - number of outstanding pool tokens\n*)\nClass State_Spec (T : Type) := \n  build_state_spec {\n    stor_rates : T -> FMap token exchange_rate ;\n    stor_tokens_held : T -> FMap token N ;\n    stor_pool_token : T -> token ; \n    stor_outstanding_tokens : T -> N ;\n}.\n\n(* specification of the Setup type \n  to initialize the contract, we need:\n    - the initial rates\n    - the pool token\n*)\nClass Setup_Spec (T : Type) := \n  build_setup_spec {\n    init_rates : T -> FMap token exchange_rate ;\n    init_pool_token : T -> token ; \n}.\n\n(* specification of the Error type *)\nClass Error_Spec (T : Type) := \n  build_error_type {\n    error_to_Error : error -> T ;\n}.\n\n(* we assume that our contract types satisfy the type specifications *)\nContext `{Msg_Spec Msg}  `{Setup_Spec Setup}  `{State_Spec State} `{Error_Spec Error}.\n\n(* Specification of the POOL entrypoint *)\n(* When the POOL entrypoint is called, the contract call fails if \n    the token to be pooled is not in the family of semi-fungible tokens. *)\nDefinition pool_entrypoint_check (contract : Contract Setup Msg State Error) : Prop :=\n    forall bstate caddr cstate chain ctx msg msg_payload,\n    (* reachable bstate *)\n    reachable bstate -> \n    (* the contract address is caddr with state cstate *)\n    env_contracts bstate caddr = Some (contract : WeakContract) -> \n    contract_state bstate caddr = Some cstate -> \n    (* forall calls to the Pool entrypoint *)\n    msg = pool (msg_payload) -> \n    (* the receive function returns an error if the token to be pooled is not in the \n       rates map held in the storage (=> is not in the semi-fungible family) *)\n    FMap.find msg_payload.(token_pooled) (stor_rates cstate) = None -> \n    receive contract chain ctx cstate (Some msg) = \n      Err(error_to_Error error_TOKEN_NOT_FOUND).\n\n\nDefinition pool_entrypoint_check_2 (contract : Contract Setup Msg State Error) : Prop :=\n    forall bstate caddr cstate cstate' chain ctx msg msg_payload acts,\n    (* reachable bstate *)\n    reachable bstate -> \n    (* the contract address is caddr with state cstate *)\n    env_contracts bstate caddr = Some (contract : WeakContract) -> \n    contract_state bstate caddr = Some cstate -> \n    (* forall calls to the Pool entrypoint *)\n    msg = pool (msg_payload) -> \n    (* the receive function returns an error if the token to be pooled is not in the \n       rates map held in the storage (=> is not in the semi-fungible family) *)\n    receive contract chain ctx cstate (Some msg) = Ok(cstate', acts) -> \n    exists r_x, \n    FMap.find msg_payload.(token_pooled) (stor_rates cstate) = Some r_x.\n\n\n(* When the POOL entrypoint is successfully called, it emits a TRANSFER call to the \n    token in storage, with q tokens in the payload of the call *)\nDefinition pool_emits_transfer (contract : Contract Setup Msg State Error) : Prop := \n    forall bstate caddr cstate chain ctx msg msg_payload cstate' acts,\n    (* reachable bstate *)\n    reachable bstate -> \n    (* the contract address is caddr with state cstate *)\n    env_contracts bstate caddr = Some (contract : WeakContract) -> \n    contract_state bstate caddr = Some cstate -> \n    (* the call to POOL was successful *)\n    msg = pool (msg_payload) -> \n    receive contract chain ctx cstate (Some msg) = Ok(cstate', acts) -> \n    (* in the acts list there is a transfer call with q tokens as the payload *)\n    exists transfer_to transfer_data transfer_payload,\n    (* there is a transfer call *)\n    In \n    (act_call \n        (msg_payload.(token_pooled).(FA2Spec.token_address)) (* call to the token address *)\n        0 (* with amount = 0 *)\n        (serialize (FA2Spec.Transfer transfer_payload)))\n    acts /\\ \n    (* with a transfer in it *)\n    In transfer_data transfer_payload /\\ \n    (* which itself has transfer data *)\n    In transfer_to transfer_data.(FA2Spec.txs) /\\\n    (* whose quantity is the quantity pooled *)\n    transfer_to.(FA2Spec.amount) = msg_payload.(qty_pooled).\n\n\n(* When the POOL entrypoint is successfully called, it emits a MINT call to the \n    pool_token, with q * r_x / 1_000_000 in the payload *)\nDefinition pool_emits_mint (contract : Contract Setup Msg State Error) : Prop := \n    forall bstate caddr cstate chain ctx msg msg_payload cstate' acts,\n    (* reachable bstate *)\n    reachable bstate -> \n    (* the contract address is caddr with state cstate *)\n    env_contracts bstate caddr = Some (contract : WeakContract) -> \n    contract_state bstate caddr = Some cstate -> \n    (* the call to POOL was successful *)\n    msg = pool msg_payload -> \n    receive contract chain ctx cstate (Some msg) = Ok(cstate', acts) -> \n    (* in the acts list there is a MINT call with q * r_x / 1_000_000 in the payload *)\n    exists mint_data mint_payload,\n    (* there is a mint call in acts *)\n    In \n    (act_call\n        (stor_pool_token cstate).(FA2Spec.token_address) (* calls the pool token address *)\n        0 (* with amount 0 *)\n        (serialize (FA2Spec.Mint mint_payload)))\n    acts /\\ \n    (* with has mint_data in the payload *)\n    In mint_data mint_payload /\\\n    (* and the mint data has these properties: *)\n    let r_x := get_rate msg_payload.(token_pooled) (stor_rates cstate) in \n    mint_data.(FA2Spec.qty) = msg_payload.(qty_pooled) * r_x / 1_000_000 /\\\n    (* TODO perhaps also specify that the minted tokens go to pooler *)\n    mint_data.(FA2Spec.mint_owner) = ctx.(ctx_from).\n\n(* When the POOL entrypoint is successfully called, the TRANSFER and MINT transactions\n    are the only transactions emitted by the contract *)\nDefinition pool_atomic (contract : Contract Setup Msg State Error) : Prop := \n    forall bstate caddr cstate chain ctx msg msg_payload cstate' acts, \n    (* reachable bstate *)\n    reachable bstate -> \n    (* the contract address is caddr with state cstate *)\n    env_contracts bstate caddr = Some (contract : WeakContract) -> \n    contract_state bstate caddr = Some cstate -> \n    (* the call to POOL was successful *)\n    msg = pool msg_payload -> \n    receive contract chain ctx cstate (Some msg) = Ok(cstate', acts) -> \n    (* we have a MINT call in acts and a TRANSFER call *)\n    length acts = 2%nat.\n\n\n(* When the POOL entrypoint is successfully called, tokens_held goes up appropriately *)\nDefinition pool_increases_tokens_held (contract : Contract Setup Msg State Error) : Prop := \n    forall bstate caddr cstate chain ctx msg msg_payload qty token cstate' acts,\n    (* reachable bstate *)\n    reachable bstate -> \n    (* the contract address is caddr with state cstate *)\n    env_contracts bstate caddr = Some (contract : WeakContract) -> \n    contract_state bstate caddr = Some cstate -> \n    (* the call to POOL was successful *)\n    msg = pool msg_payload -> \n    qty = msg_payload.(qty_pooled) -> \n    token = msg_payload.(token_pooled) ->\n    receive contract chain ctx cstate (Some msg) = Ok(cstate', acts) -> \n    (* in cstate', tokens_held has increased at token *)\n    let old_bal := get_bal token (stor_tokens_held cstate) in \n    let new_bal := get_bal token (stor_tokens_held cstate') in \n    new_bal = old_bal + qty.\n\n\n(* Specification of the UNPOOL entrypoint *)\n(* When the UNPOOL entrypoint is called, the contract call fails if \n    the token to be pooled is not in the family of semi-fungible tokens. *)\nDefinition unpool_entrypoint_check (contract : Contract Setup Msg State Error) : Prop :=\n    forall bstate caddr cstate chain ctx msg msg_payload,\n    (* reachable bstate *)\n    reachable bstate -> \n    (* the contract address is caddr with state cstate *)\n    env_contracts bstate caddr = Some (contract : WeakContract) -> \n    contract_state bstate caddr = Some cstate -> \n    (* forall calls to the Pool entrypoint *)\n    msg = unpool (msg_payload) -> \n    (* the receive function returns an error if the token to be pooled is not in the \n       rates map held in the storage (=> is not in the semi-fungible family) *)\n    FMap.find msg_payload.(token_unpooled) (stor_rates cstate) = None -> \n    receive contract chain ctx cstate (Some msg) = \n      Err(error_to_Error error_TOKEN_NOT_FOUND).\n\n\nDefinition unpool_entrypoint_check_2 (contract : Contract Setup Msg State Error) : Prop :=\n    forall bstate caddr cstate cstate' chain ctx msg msg_payload acts,\n    (* reachable bstate *)\n    reachable bstate -> \n    (* the contract address is caddr with state cstate *)\n    env_contracts bstate caddr = Some (contract : WeakContract) -> \n    contract_state bstate caddr = Some cstate -> \n    (* forall calls to the Pool entrypoint *)\n    msg = unpool (msg_payload) -> \n    (* the receive function returns an error if the token to be pooled is not in the \n       rates map held in the storage (=> is not in the semi-fungible family) *)\n    receive contract chain ctx cstate (Some msg) = Ok(cstate', acts) -> \n    exists r_x,\n    FMap.find msg_payload.(token_unpooled) (stor_rates cstate) = Some r_x.\n\n\n(* When the UNPOOL entrypoint is successfully called, it emits a BURN call to the \n    pool_token, with q in the payload *)\nDefinition unpool_emits_burn (contract : Contract Setup Msg State Error) : Prop :=\n    forall bstate caddr cstate chain ctx msg msg_payload cstate' acts,\n    (* reachable bstate *)\n    reachable bstate -> \n    (* the contract address is caddr with state cstate *)\n    env_contracts bstate caddr = Some (contract : WeakContract) -> \n    contract_state bstate caddr = Some cstate -> \n    (* the call to UNPOOL was successful *)\n    msg = unpool msg_payload -> \n    receive contract chain ctx cstate (Some msg) = Ok(cstate', acts) -> \n    (* in the acts list there is a BURN call with q in the payload *)\n    exists burn_data burn_payload,\n    (* there is a mint call in acts *)\n    In \n    (act_call\n        (stor_pool_token cstate).(FA2Spec.token_address) (* calls the pool token address *)\n        0 (* with amount 0 *)\n        (serialize (FA2Spec.Retire burn_payload)))\n    acts /\\ \n    (* with has burn_data in the payload *)\n    In burn_data burn_payload /\\\n    (* and burn_data has these properties: *)\n    burn_data.(FA2Spec.retire_amount) = msg_payload.(qty_unpooled) /\\\n    (* the burned tokens go from the unpooler *)\n    burn_data.(FA2Spec.retiring_party) = ctx.(ctx_from).\n\n\n(* When the UNPOOL entrypoint is successfully called, it emits a TRANSFER call to the \n    token in storage, with q * 1_000_000 / r_x tokens in the payload of the call *)\nDefinition unpool_emits_transfer (contract : Contract Setup Msg State Error) : Prop :=\n    forall bstate caddr cstate chain ctx msg msg_payload cstate' acts,\n    (* reachable bstate *)\n    reachable bstate -> \n    (* the contract address is caddr with state cstate *)\n    env_contracts bstate caddr = Some (contract : WeakContract) -> \n    contract_state bstate caddr = Some cstate -> \n    (* the call to UNPOOL was successful *)\n    msg = unpool (msg_payload) -> \n    receive contract chain ctx cstate (Some msg) = Ok(cstate', acts) -> \n    (* in the acts list there is a transfer call with q tokens as the payload *)\n    exists transfer_to transfer_data transfer_payload,\n    (* there is a transfer call *)\n    In \n    (act_call \n        (msg_payload.(token_unpooled).(FA2Spec.token_address)) (* call to the token address *)\n        0 (* with amount = 0 *)\n        (serialize (FA2Spec.Transfer transfer_payload)))\n    acts /\\ \n    (* with a transfer in it *)\n    In transfer_data transfer_payload /\\ \n    (* which itself has transfer data *)\n    In transfer_to transfer_data.(FA2Spec.txs) /\\\n    (* whose quantity is the quantity pooled *)\n    let r_x := get_rate msg_payload.(token_unpooled) (stor_rates cstate) in \n    transfer_to.(FA2Spec.amount) = msg_payload.(qty_unpooled) * 1_000_000 / r_x.\n\n\n(* When the UNPOOL entrypoint is successfully called, tokens_held goes down appropriately *)\nDefinition unpool_decreases_tokens_held (contract : Contract Setup Msg State Error) : Prop := \n    forall bstate caddr cstate chain ctx msg msg_payload qty token cstate' acts,\n    (* reachable bstate *)\n    reachable bstate -> \n    (* the contract address is caddr with state cstate *)\n    env_contracts bstate caddr = Some (contract : WeakContract) -> \n    contract_state bstate caddr = Some cstate -> \n    (* the call to UNPOOL was successful *)\n    msg = unpool msg_payload -> \n    qty = msg_payload.(qty_unpooled) -> \n    token = msg_payload.(token_unpooled) ->\n    receive contract chain ctx cstate (Some msg) = \n      Ok(cstate', acts) -> \n    (* in cstate', tokens_held has increased at token *)\n    let old_bal := get_bal token (stor_tokens_held cstate) in \n    let new_bal := get_bal token (stor_tokens_held cstate') in \n    new_bal = old_bal - qty.\n\n\n(* If the TRADE entrypoint is called, token_in_trade and token_out_trade must both be \n    part of the semi-fungible family for the trade to succeed. *)\nDefinition trade_entrypoint_check (contract : Contract Setup Msg State Error) : Prop :=\n    forall bstate caddr cstate chain ctx msg msg_payload,\n    (* reachable bstate *)\n    reachable bstate -> \n    (* the contract address is caddr with state cstate *)\n    env_contracts bstate caddr = Some (contract : WeakContract) -> \n    contract_state bstate caddr = Some cstate -> \n    (* forall calls to the Pool entrypoint *)\n    msg = trade (msg_payload) -> \n    (* the receive function returns an error if the token to be pooled is not in the \n       rates map held in the storage (=> is not in the semi-fungible family) *)\n    ((FMap.find msg_payload.(token_in_trade) (stor_rates cstate) = None) \\/\n    (FMap.find msg_payload.(token_out_trade) (stor_rates cstate) = None)) ->\n    receive contract chain ctx cstate (Some msg) = \n      Err(error_to_Error error_TOKEN_NOT_FOUND).\n\n\nDefinition trade_entrypoint_check_2 (contract : Contract Setup Msg State Error) : Prop :=\n    forall bstate caddr cstate chain ctx msg msg_payload cstate' acts,\n    (* reachable bstate *)\n    reachable bstate -> \n    (* the contract address is caddr with state cstate *)\n    env_contracts bstate caddr = Some (contract : WeakContract) -> \n    contract_state bstate caddr = Some cstate -> \n    (* forall calls to the Pool entrypoint *)\n    msg = trade (msg_payload) -> \n    (* the receive function returns an error if the token to be pooled is not in the \n       rates map held in the storage (=> is not in the semi-fungible family) *)\n    receive contract chain ctx cstate (Some msg) = Ok(cstate', acts) -> \n    exists x r_x r_y,\n    ((FMap.find msg_payload.(token_in_trade) (stor_tokens_held cstate) = Some x) /\\\n    (FMap.find msg_payload.(token_in_trade) (stor_rates cstate) = Some r_x) /\\\n    (FMap.find msg_payload.(token_out_trade) (stor_rates cstate) = Some r_y)).\n\n\n(* Specification of the TRADE entrypoint *)\n(* When TRADE is successfully called, the trade is priced using the correct formula \n    given by calculate_trade. The updated rate is also priced using the formula from\n    calculate_trade. *)\nDefinition trade_pricing_formula (contract : Contract Setup Msg State Error) : Prop := \n    forall bstate caddr cstate chain ctx msg msg_payload t_x t_y q cstate' acts,\n    (* reachable bstate *)\n    reachable bstate -> \n    (* the contract address is caddr with state cstate *)\n    env_contracts bstate caddr = Some (contract : WeakContract) -> \n    contract_state bstate caddr = Some cstate -> \n    (* the TRADE entrypoint was called succesfully *)\n    msg = trade msg_payload -> \n    t_x = msg_payload.(token_in_trade) -> \n    t_y = msg_payload.(token_out_trade) -> \n    t_x <> t_y -> \n    q = msg_payload.(qty_trade) ->\n    receive contract chain ctx cstate (Some msg) = \n      Ok(cstate', acts) -> \n    (* calculate the diffs delta_x and delta_y *)\n    let delta_x := \n        (get_bal t_x (stor_tokens_held cstate')) - (get_bal t_x (stor_tokens_held cstate)) in \n    let delta_y := \n        (get_bal t_y (stor_tokens_held cstate)) - (get_bal t_y (stor_tokens_held cstate')) in \n    let rate_in := (get_rate t_x (stor_rates cstate)) in \n    let rate_out := (get_rate t_y (stor_rates cstate)) in \n    let k := (stor_outstanding_tokens cstate) in \n    let x := get_bal t_x (stor_tokens_held cstate) in \n    (* the diff delta_x and delta_y are correct *)\n    delta_x = q /\\\n    delta_y = calc_delta_y rate_in rate_out q k x.\n\n\nDefinition trade_update_rates_formula (contract : Contract Setup Msg State Error) : Prop := \n    forall bstate caddr cstate chain ctx msg msg_payload t_x t_y q cstate' acts,\n    (* reachable bstate *)\n    reachable bstate -> \n    (* the contract address is caddr with state cstate *)\n    env_contracts bstate caddr = Some (contract : WeakContract) -> \n    contract_state bstate caddr = Some cstate -> \n    (* the TRADE entrypoint was called succesfully *)\n    msg = trade msg_payload -> \n    t_x = msg_payload.(token_in_trade) -> \n    t_y = msg_payload.(token_out_trade) -> \n    t_x <> t_y -> \n    q = msg_payload.(qty_trade) ->\n    receive contract chain ctx cstate (Some msg) = \n      Ok(cstate', acts) -> \n    (* calculate the diffs delta_x and delta_y *)\n    let rate_in := (get_rate t_x (stor_rates cstate)) in \n    let rate_out := (get_rate t_y (stor_rates cstate)) in \n    let k := (stor_outstanding_tokens cstate) in \n    let x := get_bal t_x (stor_tokens_held cstate) in \n    (* the new rate of t_x is correct *)\n    let r_x' := calc_rate_in rate_in rate_out q k x in \n    FMap.find t_x (stor_rates cstate') = Some r_x' /\\ \n    (forall t, t <> t_x -> \n        FMap.find t (stor_rates cstate') = \n        FMap.find t (stor_rates cstate)).\n\n\n(* When TRADE is successfully called, it emits a TRANSFER action of t_x in quantity q *)\nDefinition trade_emits_transfer_tx (contract : Contract Setup Msg State Error) : Prop :=\n    forall bstate caddr cstate cstate' chain ctx msg msg_payload acts,\n    (* reachable bstate *)\n    reachable bstate -> \n    (* the contract address is caddr with state cstate *)\n    env_contracts bstate caddr = Some (contract : WeakContract) -> \n    contract_state bstate caddr = Some cstate -> \n    (* the call to TRADE was successful *)\n    msg = trade (msg_payload) -> \n    receive contract chain ctx cstate (Some msg) = Ok(cstate', acts) -> \n    (* in the acts list there is a transfer call with q tokens as the payload *)\n    exists transfer_to transfer_data transfer_payload,\n    (* there is a transfer call *)\n    In \n    (act_call \n        (msg_payload.(token_in_trade).(FA2Spec.token_address)) (* call to the correct token address *)\n        0 (* with amount = 0 *)\n        (serialize (FA2Spec.Transfer transfer_payload)))\n    acts /\\ \n    (* with a transfer in it *)\n    In transfer_data transfer_payload /\\ \n    (* which itself has transfer data *)\n    In transfer_to transfer_data.(FA2Spec.txs) /\\\n    (* whose quantity is the quantity traded, transferred to the contract *)\n    transfer_to.(FA2Spec.amount) = msg_payload.(qty_trade) /\\\n    transfer_to.(FA2Spec.to_) = ctx.(ctx_contract_address).\n\n\n(* transfers with delta_y given by calculate_trade function *)\nDefinition trade_emits_transfer_ty (contract : Contract Setup Msg State Error) : Prop :=\n    forall bstate caddr cstate chain ctx msg msg_payload cstate' acts,\n    (* reachable bstate *)\n    reachable bstate -> \n    (* the contract address is caddr with state cstate *)\n    env_contracts bstate caddr = Some (contract : WeakContract) -> \n    contract_state bstate caddr = Some cstate -> \n    (* the call to TRADE was successful *)\n    msg = trade (msg_payload) -> \n    receive contract chain ctx cstate (Some msg) = \n      Ok(cstate', acts) -> \n    (* in the acts list there is a transfer call with q tokens as the payload *)\n    exists transfer_to transfer_data transfer_payload,\n    (* there is a transfer call *)\n    In \n    (act_call \n        (msg_payload.(token_out_trade).(FA2Spec.token_address)) (* call to the correct token address *)\n        0 (* with amount = 0 *)\n        (serialize (FA2Spec.Transfer transfer_payload)))\n    acts /\\ \n    (* with a transfer in it *)\n    In transfer_data transfer_payload /\\ \n    (* which itself has transfer data *)\n    In transfer_to transfer_data.(FA2Spec.txs) /\\\n    (* whose quantity is the quantity traded, transferred to the contract *)\n    let t_x := msg_payload.(token_in_trade) in \n    let t_y := msg_payload.(token_out_trade) in \n    let rate_in := (get_rate t_x (stor_rates cstate)) in \n    let rate_out := (get_rate t_y (stor_rates cstate)) in \n    let k := (stor_outstanding_tokens cstate) in \n    let x := get_bal t_x (stor_tokens_held cstate) in \n    let q := msg_payload.(qty_trade) in \n    transfer_to.(FA2Spec.amount) = calc_delta_y rate_in rate_out q k x  /\\\n    transfer_to.(FA2Spec.to_) = ctx.(ctx_from).\n\n\n(* Initialization specification *)\n(* TODO HOW IS THE CONTRACT INITIALIZED *)\nDefinition initialized_with_nonzero_rates (contract : Contract Setup Msg State Error) : Prop := \n    forall chain bstate ctx setup cstate,\n    (* bstate is reachable *)\n    reachable bstate -> \n    (* we call init successfully *)\n    init contract chain ctx setup = Ok cstate -> \n    (* then all rates are nonzero *)\n    forall t r,\n    FMap.find t (stor_rates cstate) = Some r -> \n    r > 0.\n\n(* we amalgamate each proposition in the specification into a single proposition *)\nDefinition is_structured_pool\n    (C : Contract Setup Msg State Error) : Prop := \n    pool_entrypoint_check C /\\\n    pool_entrypoint_check_2 C /\\\n    pool_emits_transfer C /\\\n    pool_emits_mint C /\\\n    pool_atomic C /\\\n    pool_increases_tokens_held C /\\\n    unpool_entrypoint_check C /\\\n    unpool_entrypoint_check_2 C /\\\n    unpool_emits_burn C /\\\n    unpool_emits_transfer C /\\\n    unpool_decreases_tokens_held C /\\\n    trade_entrypoint_check C /\\\n    trade_entrypoint_check_2 C /\\\n    trade_pricing_formula C /\\\n    trade_update_rates_formula C /\\\n    trade_emits_transfer_tx C /\\\n    trade_emits_transfer_ty C /\\\n    initialized_with_nonzero_rates C.\n\n(* A tactic to destruct is_sp if it's in the context of a proof *)\nTactic Notation \"is_sp_destruct\" := \nmatch goal with \n    | is_sp : is_structured_pool _ |- _ => \n        unfold is_structured_pool in is_sp;\n        destruct is_sp  as [pool_entrypoint_check_pf is_sp'];\n        destruct is_sp' as [pool_entrypoint_check_2_pf is_sp'];\n        destruct is_sp' as [pool_emits_transfer_pf is_sp'];\n        destruct is_sp' as [pool_emits_mint_pf is_sp'];\n        destruct is_sp' as [pool_atomic_pf is_sp'];\n        destruct is_sp' as [pool_increases_tokens_held_pf is_sp'];\n        destruct is_sp' as [unpool_entrypoint_check_pf is_sp'];\n        destruct is_sp' as [unpool_entrypoint_check_2_pf is_sp'];\n        destruct is_sp' as [unpool_emits_burn_pf is_sp'];\n        destruct is_sp' as [unpool_emits_transfer_pf is_sp'];\n        destruct is_sp' as [unpool_decreases_tokens_held_pf is_sp'];\n        destruct is_sp' as [trade_entrypoint_check_pf is_sp'];\n        destruct is_sp' as [trade_entrypoint_check_2_pf is_sp'];\n        destruct is_sp' as [trade_pricing_formula_pf is_sp'];\n        destruct is_sp' as [trade_update_rates_formula_pf is_sp'];\n        destruct is_sp' as [trade_emits_transfer_tx_pf is_sp'];\n        destruct is_sp' as [trade_emits_transfer_ty_pf initialized_with_nonzero_rates_pf]\nend.\n\n\n(* =============================================================================\n * The contract Metaspecification:\n      We reason about a contract which satisfies the properties of the specification \n      given here, showing that a contract which satisfies the specification also satisfies\n      the properties here.\n * ============================================================================= *)\n\n Context {contract : Contract Setup Msg State Error}\n { is_sp : is_structured_pool contract }.\n\n\n(* Demand Sensitivity :\n    A trade for a given token increases its price relative to other constituent tokens, \n    so that higher relative demand corresponds to a higher relative price. \n    Likewise, trading one token in for another decreases the first's relative price in \n    the pool, corresponding to slackened demand. This enforces the classical notion of \n    supply and demand \n\n    We prove that r_x' > r_x and forall t_z, r_z' = r_z.\n*)\nLemma rate_decrease : forall r_x r_y delta_x k x, \n    calc_rate_in r_x r_y delta_x k x < r_x.\nProof. Admitted.\n\nTheorem demand_sensitivity :\n    forall bstate caddr cstate t_x r_x,\n    (* state is reachable *)\n    reachable bstate -> \n    (* the contract address is caddr with state cstate *)\n    env_contracts bstate caddr = Some (contract : WeakContract) -> \n    contract_state bstate caddr = Some cstate -> \n    (* r_x is the rate of token t_x *)\n    0 < r_x ->\n    (FMap.find t_x (stor_rates cstate)) = Some r_x -> \n    (* a trade of t_x for some t_y happens *)\n    forall chain ctx msg msg_payload acts cstate',\n        receive contract chain ctx cstate (Some msg) = Ok(cstate', acts) ->\n        msg = trade msg_payload ->\n        msg_payload.(token_in_trade) = t_x ->\n        t_x <> msg_payload.(token_out_trade) ->\n    (* new cstate induced by *)\n    let r_x' := get_rate t_x (stor_rates cstate') in \n    (* r_x' goes down while all other rates stay constant *)\n    r_x' < r_x /\\\n    forall t,\n    t <> t_x ->\n    get_rate t (stor_rates cstate') = get_rate t (stor_rates cstate).\nProof.\n    intros. \n    is_sp_destruct.\n    pose proof (trade_entrypoint_check_2_pf bstate caddr cstate chain ctx msg msg_payload\n            cstate' acts H7 H8 H9 H13 H12).\n    do 4 destruct H16. destruct H17.\n    (* get the new rates *)  \n    pose proof (trade_update_rates_formula_pf bstate caddr cstate chain ctx msg msg_payload t_x (msg_payload.(token_out_trade)) (msg_payload.(qty_trade)) cstate' acts H7 H8 H9 H13 (eq_sym H14) (reflexivity (token_out_trade msg_payload)) H15 (reflexivity (qty_trade msg_payload)) H12). \n    destruct H19.\n    (*  *)\n    split.\n    -   unfold r_x'. unfold get_rate.\n        replace (FMap.find t_x (stor_rates cstate')) \n        with (Some\n            (calc_rate_in \n                (get_rate t_x (stor_rates cstate))\n                (get_rate (token_out_trade msg_payload) (stor_rates cstate)) \n                (qty_trade msg_payload)\n                (stor_outstanding_tokens cstate) \n                (get_bal t_x (stor_tokens_held cstate)))).\n        assert (r_x = (get_rate t_x (stor_rates cstate))).\n        +   unfold get_rate. \n            replace (FMap.find t_x (stor_rates cstate)) \n            with (Some r_x).\n            reflexivity.\n        +   rewrite H21.\n            exact (rate_decrease \n                (get_rate t_x (stor_rates cstate)) \n                (get_rate (token_out_trade msg_payload) (stor_rates cstate)) \n                (qty_trade msg_payload)\n                (stor_outstanding_tokens cstate) \n                (get_bal t_x (stor_tokens_held cstate))).\n    -   intros. unfold get_rate.\n        replace (FMap.find t (stor_rates cstate')) with (FMap.find t (stor_rates cstate));\n        try exact (eq_sym (H20 t H21)).\n        auto.\nQed.\n\n\n(* Nonpathological prices \n    As relative prices shift over time, a price that starts out nonzero never goes to \n    zero or to a negative value. \n\n    This is to avoid pathological behavior of zero or negative prices. \n\n    Note, however, that prices can still get arbitrarily close to zero, like in the case \n    of CPMMs.\n*) (*\nTheorem nonpathological_prices : \n    forall bstate caddr cstate n,\n    (* the state is reachable *)\n    reachable bstate -> \n    (* get the address *)\n    env_contracts bstate caddr = Some (contract : WeakContract) -> \n    contract_state bstate caddr = Some cstate -> \n    (* the statement *)\n    forall t,\n    (* token in the ledger => rate neq zero *)\n    FMap.find t (stor_rates cstate) = Some n /\\ n > 0 -> \n    (* any state reachable through cstate has the same property *)\n    forall bstate' cstate',\n    reachable_through bstate bstate' -> \n    contract_state bstate' caddr = Some cstate' ->\n    (* the token still has an exchange rate greater than zero in the new state cstate' *)\n    exists n', \n    FMap.find t (stor_rates cstate) = Some n' /\\ n' > 0.\nProof.\n    intros.\n    (* contract induction over the trace *)\n\n*)\n\n(* Functional non-depletion :\n    No trade can empty the entire pool of tokens. This mimics properties of CPMMs \n    currently, for which no trade can deplete any constituent token of any pool. The \n    difference here is that we are willing to let individual, constituent tokens deplete, \n    but do not allow the entire pool to deplete. \n\n    This is because tokenized carbon credits can be consumed by being retired as offsets, \n    so while we don't want the entire class of carbon credits to deplete from the pool by \n    trading, we should enable individual credits to deplete.\n*)\nTheorem functional_non_depletion :\n    forall bstate caddr cstate,\n    (* state is reachable *)\n    reachable bstate -> \n    (* the contract address is caddr with state cstate *)\n    env_contracts bstate caddr = Some (contract : WeakContract) -> \n    contract_state bstate caddr = Some cstate -> \n    (* there is liquidity *)\n    (stor_outstanding_tokens cstate) > 0 -> \n    (* a trade occurs *)\n    forall chain ctx msg msg_payload acts cstate',\n        receive contract chain ctx cstate (Some msg) = Ok(cstate', acts) -> \n        msg = trade msg_payload ->\n    (* there is liquidity *)\n    (stor_outstanding_tokens cstate') > 0.\nProof. (* \n    intros.\n    pose proof (trade_entrypoint_check_2_pf bstate caddr cstate chain ctx msg msg_payload\n            cstate' acts H7 H8 H9 H12 H11).\n    do 4 destruct H13. destruct H14.\n    rewrite H12 in H11. *)\n    (* open up the receive function \n    cbn in H7.\n    destruct \n        (FMap.find (token_in_trade msg_payload) (tokens_held cstate)),\n        (FMap.find (token_in_trade msg_payload) (rates cstate)),\n        (FMap.find (token_out_trade msg_payload) (rates cstate)) in H7; \n    cbn in H7; inversion H7. \n    destruct (RPMM.get_bal (token_out_trade msg_payload) (tokens_held cstate) <?\n           calc_delta_y e n0 (qty_trade msg_payload) (outstanding_tokens cstate) n)%N in H7;\n    cbn in H7; inversion H7.\n    clear H7 H13 H15.*)\n    (*  *)\n    Admitted.\n\n\n\n(* Swap rate consistency : \n    For tokens tau_x, tau_y and tau_z, the exchange rate from tau_x to tau_y, and then to \n    tau_z, must not be greater than the exchange rate from tau_x to token tau_z. \n\n    As we will see, structured pools always price trades consistently, but because of how \n    prices update over time it is nontrivial to show that this is true in practice.\n    \n    In particular, price consistency means that it is never profitable to trade in a loop, \n    e.g. tau_x to tau_y, and back to tau_x, which is important so that there are no \n    arbitrage oportunities internal to the pool.\n*)\nTheorem swap_rate_consistency : \n    forall bstate caddr cstate,\n    (* state is reachable *)\n    reachable bstate -> \n    (* the contract address is caddr with state cstate *)\n    env_contracts bstate caddr = Some (contract : WeakContract) -> \n    contract_state bstate caddr = Some cstate -> \n    (* a trade from t_x to t_z *)\n    forall t_x t_z qty_trade\n        chain ctx msg_xz msg_payload_xz acts_xz cstate_xz,\n        receive contract chain ctx cstate msg_xz = Ok (cstate_xz, acts_xz) ->\n        msg_xz = Some (trade msg_payload_xz) -> \n        msg_payload_xz = Build_trade_data t_x t_z qty_trade ->\n    (* a trade from t_x to t_y *)\n    forall t_y msg_xy msg_payload_xy acts_xy cstate_xy,\n        receive contract chain ctx cstate msg_xy = Ok (cstate_xy, acts_xy) ->\n        msg_xy = Some (trade msg_payload_xy) -> \n        msg_payload_xy = Build_trade_data t_x t_y qty_trade ->\n    (* which yields delta_y tokens in t_y *)\n    let delta_y := \n        (get_bal t_y (stor_tokens_held cstate)) - \n        (get_bal t_y (stor_tokens_held cstate_xy)) in \n    (* followed by a trade of delta_y from t_y to t_z *)\n    forall msg_yz msg_payload_yz acts_yz cstate_yz chain' ctx',\n        receive contract chain' ctx' cstate_xy msg_yz = Ok (cstate_yz, acts_yz) ->\n        msg_yz = Some (trade msg_payload_yz) -> \n        msg_payload_yz = Build_trade_data t_y t_z delta_y ->\n    (* the output delta_z *)\n    let delta_z_direct := \n        (get_bal t_z (stor_tokens_held cstate)) - \n        (get_bal t_z (stor_tokens_held cstate_xz)) in \n    let delta_z_indirect := \n        (get_bal t_z (stor_tokens_held cstate)) - \n        (get_bal t_z (stor_tokens_held cstate_yz)) in     \n    (* the direct trade yielded more t_z than the indirect trade *)\n    delta_z_direct > delta_z_indirect.\nProof. Admitted.\n\n\n(* Arbitrage sensitivity :\n    If an opportunity for arbitrage exists due to some external market pricing a \n    constituent token differently from the structured pool, the arbitrage loop can be \n    closed with one sufficiently large transaction.\n\n    In our case, this happens because prices adapt through trades due to demand \n    sensitivity or the pool depletes in that particular token.\n*)\nTheorem arbitrage_sensitivity : \n    forall bstate caddr cstate t_x, \n    (* state is reachable *)\n    reachable bstate -> \n    (* the contract address is caddr with state cstate *)\n    env_contracts bstate caddr = Some (contract : WeakContract) -> \n    contract_state bstate caddr = Some cstate -> \n    (*  *)\n    forall external_price \n    chain ctx msg msg_payload cstate' acts,\n    receive contract chain ctx cstate msg = Ok(cstate', acts) -> \n    msg = Some(trade msg_payload) -> \n    exists trade_qty, \n    msg_payload.(qty_trade) = trade_qty -> \n    (* price stabilizes or liquidity depletes *)\n    FMap.find t_x (stor_rates cstate') = Some(external_price) \\/\n    FMap.find t_x (stor_tokens_held cstate') = None.\nProof. Admitted.\n\n\n(* Pooled consistency \n    The sum of all the constituent, pooled tokens, multiplied by their value in terms of \n    pooled tokens, always equals the total number of outstanding pool tokens. That is, \n    pool tokens are never under- or over-collateralized. \n*)\nDefinition fold_fn (rates : FMap token exchange_rate) (tokens_held : FMap token N)\n    (n : N) (k : token) : N := \n    let rate := \n        match FMap.find k rates with \n        | Some r => r \n        | None => 0\n        end in \n    let qty_held := \n        match FMap.find k tokens_held with \n        | Some r => r \n        | None => 0 \n        end in \n    rate * qty_held / 1_000_000.\n\nDefinition sum_over_tokens \n    (rates : FMap token exchange_rate) (tokens_held : FMap token N) : N := \n    (* get the list of keys *)\n    let token_family := (FMap.keys rates) in \n    (* fold over the list *)\n    List.fold_left\n        (fold_fn rates tokens_held)\n        token_family \n        0.\n\nTheorem pooled_consistency : \n    forall bstate caddr cstate,\n    (* state is reachable *)\n    reachable bstate -> \n    (* the contract address is caddr *)\n    env_contracts bstate caddr = Some (contract : WeakContract) -> \n    (* the contract state is cstate *)\n    contract_state bstate caddr = Some cstate -> \n    (* The sum of all the constituent, pooled tokens, multiplied by their value in terms \n    of pooled tokens, always equals the total number of outstanding pool tokens. *)\n    sum_over_tokens (stor_rates cstate) (stor_tokens_held cstate) = \n        (stor_outstanding_tokens cstate).\nProof. Admitted.\n\n\nEnd AbstractSpecification.", "meta": {"author": "differentialderek", "repo": "FinCert", "sha": "77fa9f39bd6defd77adf8188818016f2d28feb69", "save_path": "github-repos/coq/differentialderek-FinCert", "path": "github-repos/coq/differentialderek-FinCert/FinCert-77fa9f39bd6defd77adf8188818016f2d28feb69/specifications/StructuredPoolsSpec/StructuredPoolsSpec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318194686359, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.2690694627234645}}
{"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\nLocal Hint Extern 10 (forall _ _, get (snd ⊝ computeParametersF ?DL ?ZL ?AP ?F ?als) _ _ -> ❬?LVb❭ = ❬_❭)\n=> eapply computeParametersF_length : len.\n\nLocal Hint Extern 1 =>\nmatch goal with\n  [ |- context [ ❬snd (computeParameters _ _ _ _ )❭ ] ] =>\n  rewrite computeParameters_length; eauto with len\nend : len.\n\n\nLemma computeParameters_trs b ZL Lv AP s lv\n: live_sound Imperative ZL Lv s lv\n  -> noUnreachableCode (isCalled b) s\n  -> poLe AP (Lv \\\\ ZL)\n  -> length Lv = length ZL\n  -> length ZL = length AP\n  -> trs (restr (getAnn lv) ⊝ (zip ominus' (Lv \\\\ ZL)\n                                  (snd (computeParameters (Lv \\\\ ZL) AP s lv))))\n        s lv\n        (fst (computeParameters (Lv \\\\ ZL) AP s lv)).\nProof.\n  intros LIVE NOUR P LEN1 LEN2.\n  revert_except LIVE.\n  induction LIVE; simpl in *; intros; repeat let_case_eq;\n    repeat let_pair_case_eq; inv NOUR; simpl in *.\n  - eapply trsExp, trs_monotone_DL.\n    + eapply IHLIVE; eauto 10 using addParam_Subset with len.\n    + rewrite restrict_comp_meet.\n      assert (SEQ:lv ∩ (getAnn al \\ singleton x) [=] getAnn al \\ singleton x) by\n          (clear - H0; cset_tac).\n      rewrite SEQ. eapply restrict_zip_ominus'; eauto with len.\n      eapply PIR2_not_in; [ eapply computeParameters_AP_LV; eauto with len\n                          | eauto with len].\n  - econstructor.\n    + eapply trs_monotone_DL; eauto.\n      eapply restrict_subset2; eauto.\n      eapply zip_ominus_contra; eauto using PIR2_zip_ounion with len.\n    + eapply trs_monotone_DL; eauto using PIR2_zip_ounion' with len.\n      eapply restrict_subset2; eauto with len.\n      eapply zip_ominus_contra; eauto using PIR2_zip_ounion' with len.\n  - inv_get.\n    econstructor.\n    + eapply restrict_get_Some.\n      eapply zip_get_eq. eapply zip_get; eauto.\n      eapply keep_Some; eauto. simpl. reflexivity.\n      rewrite <- H1. eauto with cset.\n  - econstructor.\n  - len_simpl.\n    assert (LenHelp1:❬(getAnn ⊝ als ++ Lv) \\\\ (fst ⊝ F ++ ZL)❭ =\n                     ❬snd\n                        (computeParameters ((getAnn ⊝ als ++ Lv) \\\\ (fst ⊝ F ++ ZL))\n                                           (tab {} ‖F‖ ++ AP) t alb)❭). {\n      rewrite computeParameters_length; eauto; revert LEN1 LEN2 H; clear_all;\n        eauto with len.\n    }\n    assert (LenHelp2:\n              forall (n : nat) (aa : 〔؟ ⦃var⦄〕),\n                get (snd ⊝ computeParametersF F als Lv ZL AP) n aa ->\n                ❬aa❭ =\n                ❬snd\n                   (computeParameters ((getAnn ⊝ als ++ Lv) \\\\ (fst ⊝ F ++ ZL))\n                                      (tab {} ‖F‖ ++ AP) t alb)❭). {\n      eapply computeParametersF_length; eauto.\n      rewrite <- LenHelp1. eauto with len. eauto with len.\n    }\n    lnorm. econstructor.\n    + eauto with len.\n    + eauto with len.\n    + rewrite map_length. rewrite take_length_le; eauto.\n      rewrite zip_length2; [eauto 20 with len|].\n      rewrite fold_zip_ounion_length; eauto.\n    + intros. inv_get. simpl.\n      eapply trs_monotone_DL.\n      * eapply H1; eauto using PIR2_Subset_tab_extend with len.\n      * { rewrite (take_eta (length F) (zip ominus' _ _)).\n          do 2 rewrite List.map_app.\n          eapply PIR2_app.\n          - rewrite restrict_disj.\n            + eapply restrict_subset2; eauto.\n              do 2 rewrite take_zip.\n              rewrite take_app_eq; [|eauto with len].\n              rewrite take_app_eq; [|eauto with len].\n              eapply ominus'_Some_oto_list.\n              eapply PIR2_take. eapply PIR2_addAdds3.\n              eauto with len.\n              eapply PIR2_combineParams_get;\n                [ eapply computeParametersF_length_pair; eauto with len\n                | eauto with len\n                | eapply zip_get; eauto\n                | reflexivity ].\n            + intros.\n              inv_get.\n              Opaque to_list.\n\n              pose proof (H10 _ H12).\n              edestruct computeParameters_isCalledFrom_get_Some; try eapply H6;\n                try eassumption;\n                [ intros; edestruct H2; eauto\n                | eauto with len\n                | dcr; subst ].\n              pose proof (H10 _ H15).\n              edestruct computeParameters_isCalledFrom_get_Some; try eapply H7;\n                try eassumption;\n                [ intros; edestruct H2; eauto\n                | eauto with len\n                | dcr; subst ].\n              simpl.\n              repeat rewrite of_list_app.\n              repeat rewrite of_list_3.\n              eapply disj_minus.\n              rewrite (meet_comm _ (getAnn lvs)) at 1.\n              rewrite union_meet_distr_r. rewrite union_meet_distr_r.\n              eapply union_incl_split.\n              eapply incl_union_incl_minus. eapply incl_union_left.\n              eapply incl_meet_split. eapply incl_union_right.\n              eapply incl_list_union; [ eapply map_get_1; try eapply H5 | ].\n              clear_all; cset_tac.\n              clear_all; cset_tac.\n              eapply incl_union_incl_minus. eapply incl_union_left.\n              assert (x0 ⊆ list_union (oget ⊝ take ❬F❭ (olu F als Lv ZL AP t alb))). {\n                eapply incl_list_union.\n                eapply map_get_1; eauto.\n                eapply get_take; try eapply H6; eauto. reflexivity.\n              }\n              clear - H17.\n              cset_tac.\n          - rewrite restrict_comp_meet.\n            pose proof (H10 _ H12).\n            edestruct computeParameters_isCalledFrom_get_Some; try eapply H6;\n              eauto with len; dcr; subst.\n            intros; edestruct H2; eauto.\n            simpl.\n\n            repeat rewrite of_list_app. repeat rewrite of_list_3.\n            set (XX:=(list_union (oget\n                                ⊝ take ❬F❭\n                                    (olist_union (snd ⊝ computeParametersF F als Lv ZL AP)\n                                     (snd\n                                        (computeParameters ((getAnn ⊝ als ++ Lv) \\\\ (fst ⊝ F ++ ZL))\n                                                           (tab {} ‖F‖ ++ AP) t alb))))\n                                 ∪ list_union (fst ∘ of_list ⊝ F))).\n\n            assert (lvsEQ:\n                      lv ∩ (getAnn lvs \\ (of_list (fst Zs) ∪\n                                                  (XX ∩ (getAnn lvs \\ of_list (fst Zs)) ∪ x)))\n                         [=]\n                         (getAnn lvs \\ (of_list (fst Zs) ∪\n                                                (XX ∩ (getAnn lvs \\ of_list (fst Zs)) ∪ x)))). {\n              rewrite meet_comm. symmetry. eapply incl_meet.\n              rewrite <- H3. subst XX.\n              rewrite <- H14.\n              clear_all; cset_tac.\n            }\n            rewrite lvsEQ.\n            rewrite restrict_disj.\n            + eapply restrict_subset2; eauto.\n              do 2 rewrite drop_zip.\n              repeat rewrite drop_length_ass; eauto with len.\n              eapply zip_ominus_contra; eauto with len.\n              eapply PIR2_drop; eauto.\n              eapply PIR2_addAdds3; eauto with len.\n              eapply PIR2_combineParams_get;\n                [ | eauto with len | eauto using zip_get_eq | reflexivity].\n              eapply computeParametersF_length_pair; eauto with len.\n            + intros. inv_get.\n              unfold ominus', lminus in H15.\n              destruct x3; invc H15. simpl in *.\n              subst XX.\n              revert H5 H6. clear_all.\n              intros; hnf; intros. cset_tac'.\n              * eapply H8; eauto.\n                eapply incl_list_union. eapply map_get_1; eauto. reflexivity.\n                eauto.\n              * eapply H0; eauto.\n                eapply incl_list_union.\n                eapply map_get_1.\n                eapply get_take; eauto using get_range. reflexivity.\n                eauto.\n        }\n    + eapply trs_monotone_DL.\n      eapply IHLIVE; eauto using PIR2_Subset_tab_extend with len.\n      * { rewrite (take_eta (length F) (zip ominus' _ _)).\n          rewrite List.map_app.\n          eapply PIR2_app.\n          - eapply PIR2_restrict.\n            do 2 rewrite take_zip.\n            rewrite take_app_eq; [|eauto with len].\n            rewrite take_app_eq; [|eauto with len].\n            eapply ominus'_Some_oto_list.\n            eapply PIR2_take. eapply PIR2_addAdds3.\n            eauto with len.\n            eapply PIR2_combineParams; [| reflexivity].\n            eapply computeParametersF_length_pair; eauto with len.\n          - eapply restrict_subset2; eauto.\n            do 2 rewrite drop_zip.\n            repeat (rewrite drop_length_ass; [| eauto with len]).\n            eapply zip_ominus_contra.\n            eapply PIR2_drop; eauto.\n            eapply PIR2_addAdds3. eauto with len.\n            eapply PIR2_combineParams; [| reflexivity].\n            eapply computeParametersF_length_pair; eauto with len.\n        }\nQed.\n\n\nLemma is_trs b s lv\n: live_sound Imperative nil nil s lv\n  -> noUnreachableCode (isCalled b) s\n  -> trs 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_trs; eauto; try reflexivity.\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/DelocationAlgoCorrect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2690010619547869}}
{"text": "From machine_program_logic.program_logic Require Import weakestpre.\nFrom HypVeri Require Import lifting rules.rules_base stdpp_extra.\nFrom HypVeri.algebra Require Import base reg mem pagetable trans mailbox base_extra.\nFrom HypVeri.lang Require Import lang_extra mem_extra reg_extra pagetable_extra trans_extra.\n\nSection mem_relinquish.\n\nContext `{hypparams: HypervisorParameters}.\nContext `{vmG: !gen_VMG Σ}.\n\nLemma p_relinquish_inv_consist σ h i j ps tt:\n  inv_trans_pgt_consistent σ ->\n  inv_trans_ps_disj σ ->\n  σ.2 !! h = Some (Some (j, i, ps, tt, true)) ->\n  j ≠ i ->\n  inv_trans_pgt_consistent (update_page_table_global revoke_access (update_transaction σ h (j, i, ps, tt, false)) i ps).\nProof.\n  intros Hinv_con Hinv_disj Hlk Hneq_i.\n  rewrite /inv_trans_pgt_consistent /inv_trans_pgt_consistent' /=.\n  rewrite map_Forall_lookup.\n  intros h' meta Hlookup'.\n  rewrite lookup_insert_Some in Hlookup'.\n  destruct Hlookup' as [[<- <-]|[Hneq Hlookup']].\n  {\n    intros p Hin.\n    specialize (Hinv_con h _ Hlk p Hin).\n    simpl in Hinv_con.\n    generalize dependent σ.1.1.1.2.\n    generalize dependent σ.2.\n    induction ps using set_ind_L .\n    - set_solver + Hin.\n    - intros tran Htran pgt Hpgt.\n      simpl.\n      rewrite set_fold_disj_union_strong.\n      {\n        rewrite set_fold_singleton.\n        destruct (decide (x = p)).\n        {\n          subst.\n          destruct tt;first done.\n          rewrite Hpgt.\n          apply p_upd_pgt_pgt_not_elem.\n          done.\n          rewrite lookup_insert_Some.\n          left. split;auto.\n          assert (Hrw: {[j;i]} ∖ {[i]} = ({[j]} : gset _)).\n          set_solver + Hneq_i.\n          rewrite /revoke_access Hrw //.\n          rewrite Hpgt.\n          apply p_upd_pgt_pgt_not_elem.\n          done.\n          rewrite lookup_insert_Some.\n          left. split;auto.\n          assert (Hrw: {[i]} ∖ {[i]} = (∅ : gset _)).\n          set_solver +.\n          rewrite /revoke_access Hrw //.\n        }\n        {\n          destruct (pgt !! x).\n          {\n            feed specialize IHps.\n            set_solver + Hin n.\n            apply (IHps (<[h := Some (j, i, X, tt, true)]>tran));eauto.\n            rewrite lookup_insert //.\n            rewrite lookup_insert_ne //.\n          }\n          {\n            feed specialize IHps.\n            set_solver + Hin n.\n            apply (IHps (<[h := Some (j, i, X, tt, true)]>tran));eauto.\n            rewrite lookup_insert //.\n          }\n        }\n      }\n      apply upd_is_strong_assoc_comm.\n      set_solver + H0.\n  }\n  {\n    rewrite /inv_trans_pgt_consistent /inv_trans_pgt_consistent' /= in Hinv_con.\n    specialize (Hinv_con h' meta Hlookup').\n    simpl in Hinv_con.\n    destruct meta as [[[[[sv rv] ps'] tt'] b]|];last done.\n    simpl in *.\n    intros p Hin.\n    specialize (Hinv_con p Hin).\n    assert (p ∉ ps).\n    {\n      intro.\n      specialize (Hinv_disj h' _ Hlookup').\n      simpl in Hinv_disj.\n      pose proof (elem_of_pages_in_trans' p (delete h' σ.2)) as [_ Hin'].\n      feed specialize Hin'.\n      exists h.\n      eexists.\n      split.\n      rewrite lookup_delete_ne //.\n      done.\n      set_solver + Hin H0 Hin' Hinv_disj.\n    }\n    destruct tt',b;auto;try apply p_upd_pgt_pgt_not_elem;auto.\n  }\nQed.\n\n\nLemma mem_relinquish {tt wi sacc i j q p_tx} {ps: gset PID}\n      ai r0 wh:\n  (* has access to the page which the instruction is in *)\n  tpa ai ≠ p_tx ->\n  tpa ai ∈ sacc ->\n  (* current instruction is hvc *)\n  decode_instruction wi = Some(Hvc) ->\n  (* the hvc call to invoke is relinquish *)\n  decode_hvc_func r0 = Some(Relinquish) ->\n  {SS{{(* the encoding of instruction wi is stored in location ai *)\n       ▷(PC @@ i ->r ai) ∗  ▷ ai ->a wi ∗\n       ▷ (R0 @@ i ->r r0) ∗\n       ▷ (R1 @@ i ->r wh) ∗\n       (* the pagetable, the owership ra is not required *)\n       ▷ i -@A> sacc ∗\n       (* the descriptor is ready in the tx page *)\n       ▷ TX@ i := p_tx ∗\n       (* is the receiver and the transaction has been retrieved *)\n       ▷ wh -{q}>t (j, i, ps, tt) ∗ ▷ wh ->re true }}}\n  ExecI @ i\n  {{{ RET (false, ExecI) ;\n      (* PC is incremented *)\n      PC @@ i ->r (ai ^+ 1)%f ∗ ai ->a wi ∗\n      (* donesn't have access to psd anymore *)\n      i -@A> (sacc ∖ ps) ∗\n      (* return Succ to R0 *)\n      R0 @@ i ->r (encode_hvc_ret_code Succ) ∗\n      R1 @@ i ->r wh ∗\n      (* the same tx *)\n      TX@ i := p_tx ∗\n      (* the transaction is marked as unretrieved *)\n      wh -{q}>t(j, i, ps, tt) ∗ wh ->re false\n      }}}.\nProof.\n  iIntros (Hneq_tx Hin_acc Hdecode_i Hdecode_f Φ) \"(>PC & >mem_ins & >R0 & >R1 & >acc & >tx & >tran & >re) HΦ\".\n  iApply (sswp_lift_atomic_step ExecI);[done|].\n  iIntros (n σ1) \"%Hsche state\".\n  rewrite /scheduled /= /scheduler in Hsche.\n  assert (σ1.1.1.2 = i) as Heq_cur. { case_bool_decide;last done. by apply fin_to_nat_inj. }\n  clear Hsche.\n  iModIntro.\n  iDestruct \"state\" as \"(Hnum & mem & regs & mb & rx_state & pgt_owned & pgt_acc & pgt_excl &\n                            trans & hpool & retri & %Hwf & %Hdisj & %Hconsis)\".\n  (* valid regs *)\n  iDestruct ((gen_reg_valid3 i PC ai R0 r0 R1 wh Heq_cur) with \"regs PC R0 R1\")\n    as \"(%Hlookup_PC & %Hlookup_R0 & %Hlookup_R1)\";eauto.\n  (* valid pt *)\n  iDestruct (access_agree_check_true (tpa ai) i with \"pgt_acc acc\") as %Hcheckpg_ai;eauto.\n  (* valid mem *)\n  iDestruct (gen_mem_valid ai wi with \"mem mem_ins\") as %Hlookup_ai.\n  (* valid tx rx *)\n  iDestruct (mb_valid_tx i p_tx with \"mb tx\") as %Heq_tx.\n  (* valid trans *)\n  iDestruct (trans_valid_Some with \"trans tran\") as %[re Hlookup_tran].\n  iDestruct (trans_valid_handle_Some with \"tran\") as %Hvalid_handle.\n  iDestruct (retri_valid_Some with \"retri re\") as %[meta Hlookup_tran'].\n  rewrite Hlookup_tran in Hlookup_tran'.\n  inversion Hlookup_tran'. subst re. clear meta Hlookup_tran' H1.\n  iSplit.\n  - (* reducible *)\n    iPureIntro.\n    apply (reducible_normal i Hvc ai wi);eauto.\n    rewrite Heq_tx //.\n  - iModIntro.\n    iIntros (m2 σ2) \"vmprop_auth %HstepP\".\n    iFrame \"vmprop_auth\".\n    apply (step_ExecI_normal i Hvc ai wi) in HstepP;eauto.\n    2: rewrite Heq_tx //.\n    remember (exec Hvc σ1) as c2 eqn:Heqc2.\n    rewrite /exec /hvc Hlookup_R0 /= Hdecode_f /relinquish Hlookup_R1 /get_transaction /= Hlookup_tran Heq_cur /= in Heqc2.\n    case_bool_decide;last done. clear H0. simpl in Heqc2.\n    case_bool_decide;last done. clear H0.\n    destruct HstepP;subst m2 σ2; subst c2; simpl.\n    rewrite /gen_vm_interp.\n    (* unchanged part *)\n    rewrite (preserve_get_rx_gmap σ1).\n    2: rewrite p_upd_pc_mb //.\n    rewrite (preserve_get_mb_gmap σ1).\n    2: rewrite p_upd_pc_mb //.\n    rewrite p_upd_pc_mem p_upd_reg_mem p_rvk_acc_mem p_upd_tran_mem.\n    iFrame \"Hnum mem mb rx_state\".\n    (* upd regs *)\n    rewrite (u_upd_pc_regs _ i ai). 2: done.\n    2: { rewrite u_upd_reg_regs p_rvk_acc_current_vm p_upd_tran_current_vm.\n         rewrite (preserve_get_reg_gmap σ1). rewrite lookup_insert_ne. solve_reg_lookup. done. f_equal.\n    }\n    rewrite u_upd_reg_regs p_rvk_acc_current_vm p_upd_tran_current_vm Heq_cur.\n    rewrite (preserve_get_reg_gmap σ1);last done.\n    iDestruct ((gen_reg_update2_global PC i _ (ai ^+ 1)%f R0 i _ (encode_hvc_ret_code Succ)) with \"regs PC R0\")\n      as \">[$ [PC R0]]\";eauto.\n    (* upd pgt *)\n    rewrite (preserve_get_own_gmap (update_page_table_global revoke_access (update_transaction σ1 wh (j, i, ps, tt, false)) i ps) (update_incr_PC _)).\n    2: rewrite p_upd_pc_pgt p_upd_reg_pgt //.\n    rewrite p_rvk_acc_own. rewrite (preserve_get_own_gmap σ1);last done.\n    iFrame \"pgt_owned\".\n    rewrite (preserve_get_access_gmap (update_page_table_global revoke_access (update_transaction σ1 wh (j, i, ps, tt, true)) i ps) (update_incr_PC _)).\n    2: rewrite p_upd_pc_pgt p_upd_reg_pgt //.\n    iDestruct (access_agree with \"pgt_acc acc\") as %Hlookup_pgt_acc.\n    rewrite (u_rvk_acc_acc _ _ _ sacc).\n    2: {\n      rewrite p_upd_tran_pgt.\n      intros p Hin_p.\n      specialize (Hconsis wh _ Hlookup_tran p Hin_p).\n      simpl in Hconsis.\n      destruct tt.\n      done.\n      eexists;eauto.\n      eexists;eauto.\n    }\n    2: rewrite (preserve_get_access_gmap σ1);done.\n    rewrite (preserve_get_access_gmap σ1);last done.\n    iDestruct (access_update (sacc∖ ps) with \"pgt_acc acc\") as \">[$ acc]\". done.\n    rewrite (preserve_get_excl_gmap (update_page_table_global revoke_access (update_transaction σ1 wh (j, i, ps, tt, false)) i ps) (update_incr_PC _)).\n    2: rewrite p_upd_pc_pgt p_upd_reg_pgt //.\n    rewrite (p_rvk_acc_excl _ _ j tt).\n    2: {\n      intros p Hin.\n      specialize (Hconsis wh _ Hlookup_tran p Hin).\n      destruct tt; simpl in Hconsis.\n      done.\n      rewrite p_upd_tran_pgt //.\n      rewrite p_upd_tran_pgt //.\n    }\n    rewrite (preserve_get_excl_gmap σ1);last done.\n    iFrame \"pgt_excl\".\n    (* upd tran *)\n    rewrite (preserve_get_trans_gmap (update_transaction σ1 wh (j, i, ps, tt, false)) (update_incr_PC _)).\n    2: rewrite p_upd_pc_trans p_upd_reg_trans //.\n    rewrite u_upd_tran_trans.\n    rewrite insert_id.\n    2: rewrite /get_trans_gmap /get_transactions_gmap lookup_fmap Hlookup_tran //=.\n    iFrame \"trans\".\n    (* upd hp *)\n    rewrite (preserve_get_hpool_gset (update_transaction σ1 wh (j, i, ps, tt, false)) (update_incr_PC _)).\n    2: rewrite p_upd_pc_trans p_upd_reg_trans //. rewrite p_upd_tran_hp.\n    iFrame \"hpool\".\n    (* upd retri *)\n    rewrite (preserve_get_retri_gmap (update_transaction σ1 wh (j, i, ps, tt, false)) (update_incr_PC _)).\n    2: rewrite p_upd_pc_trans p_upd_reg_trans //.\n    2: { exists (Some (j, i, ps, tt, true)). split;eauto. }\n    rewrite u_upd_tran_retri.\n    iDestruct (retri_update_flip with \"retri re\") as \">[$ re]\".\n    (* inv_trans_wellformed *)\n    rewrite (preserve_inv_trans_wellformed (update_transaction σ1 wh (j, i, ps, tt, false))).\n    2: rewrite p_upd_pc_trans p_upd_reg_trans //.\n    iAssert (⌜inv_trans_wellformed (update_transaction σ1 wh (j, i, ps, tt, false))⌝%I) as \"$\". iPureIntro.\n    apply (p_upd_tran_inv_wf σ1 wh);eauto.\n    (* inv_trans_pgt_consistent *)\n    rewrite (preserve_inv_trans_pgt_consistent (update_page_table_global revoke_access (update_transaction σ1 wh (j, i, ps, tt, false)) i ps) (update_incr_PC _)).\n    2: rewrite p_upd_pc_trans p_upd_reg_trans //.\n    2: rewrite p_upd_pc_pgt p_upd_reg_pgt //.\n    iAssert (⌜inv_trans_pgt_consistent (update_page_table_global revoke_access (update_transaction σ1 wh (j, i, ps, tt, false)) i ps)⌝%I) as \"$\". iPureIntro.\n    apply p_relinquish_inv_consist;auto.\n    { destruct Hwf as [_ [Hwf _]]. specialize (Hwf wh _ Hlookup_tran). done. }\n    (* inv_trans_ps_disj *)\n    rewrite (preserve_inv_trans_ps_disj (update_transaction σ1 wh (j, i, ps, tt, false))).\n    2: rewrite p_upd_pc_trans p_upd_reg_trans //.\n    iAssert (⌜inv_trans_ps_disj (update_transaction σ1 wh (j, i, ps, tt, false))⌝%I) as \"$\". iPureIntro.\n    eapply p_upd_tran_inv_disj.\n    apply Hdisj.\n    exact Hlookup_tran.\n    done.\n    (* just_scheduled *)\n    iModIntro.\n    rewrite /just_scheduled_vms /just_scheduled.\n    rewrite /scheduled /machine.scheduler /= /scheduler.\n    rewrite p_upd_pc_current_vm p_upd_reg_current_vm p_rvk_acc_current_vm p_upd_tran_current_vm.\n    rewrite Heq_cur.\n    iSplitL \"\".\n    set fl := (filter _ _).\n    assert (fl = []) as ->.\n    {\n      rewrite /fl.\n      induction n.\n      - simpl.\n        rewrite filter_nil //=.\n      - rewrite seq_S.\n        rewrite filter_app.\n        rewrite IHn.\n        simpl.\n        rewrite filter_cons_False /=. rewrite filter_nil //.\n        rewrite andb_negb_l //.\n    }\n    by iSimpl.\n    (* Φ *)\n    case_bool_decide;last contradiction.\n    simpl. iApply \"HΦ\".\n    rewrite /fresh_handles. iFrame.\nQed.\n\nLemma mem_relinquish_invalid_handle {E i wi sacc r0 r2 wh p_tx} ai:\n  tpa ai ≠ p_tx ->\n  (tpa ai) ∈ sacc ->\n  (* the current instruction is hvc *)\n  (* the decoding of wi is correct *)\n  decode_instruction wi = Some(Hvc) ->\n  (* the hvc call to invoke is retrieve *)\n  decode_hvc_func r0 = Some(Relinquish) ->\n  wh ∉ valid_handles ->\n  {SS{{(* the encoding of instruction wi is stored in location ai *)\n       ▷ (PC @@ i ->r ai) ∗ ▷ ai ->a wi ∗\n       (* registers *)\n       ▷ (R0 @@ i ->r r0) ∗\n       ▷ (R1 @@ i ->r wh) ∗\n       ▷ (R2 @@ i ->r r2) ∗\n       ▷ i -@A> sacc ∗\n       ▷ TX@ i := p_tx}}}\n   ExecI @ i; E\n   {{{ RET (false, ExecI) ;\n       (* PC is incremented *)\n       PC @@ i ->r (ai ^+ 1)%f ∗ ai ->a wi ∗\n       R0 @@ i ->r (encode_hvc_ret_code Error) ∗\n       R1 @@ i ->r wh ∗\n       R2 @@ i ->r (encode_hvc_error InvParam) ∗\n       i -@A> sacc ∗\n       TX@ i := p_tx\n   }}}.\nProof.\n  iIntros (Hneq_tx Hin_acc Hdecode_i Hdecode_f Hnin_wh Φ)\n          \"(>PC & >mem_ins & >R0 & >R1 & >R2 & >acc & >tx) HΦ\".\n  iApply (sswp_lift_atomic_step ExecI);[done|].\n  iIntros (n σ1) \"%Hsche state\".\n  rewrite /scheduled /= /scheduler in Hsche.\n  assert (σ1.1.1.2 = i) as Heq_cur. { case_bool_decide;last done. by apply fin_to_nat_inj. }\n  clear Hsche.\n  iModIntro.\n  iDestruct \"state\" as \"(Hnum & mem & regs & mb & rx_state & pgt_owned & pgt_acc & pgt_excl &\n                            trans & hpool & retri & %Hwf & %Hdisj & %Hconsis)\".\n  (* valid regs *)\n  iDestruct ((gen_reg_valid4 i PC ai R0 r0 R1 wh R2 r2 Heq_cur) with \"regs PC R0 R1 R2\")\n    as \"(%Hlookup_PC & %Hlookup_R0 & %Hlookup_R1 & %Hlookup_R2)\";eauto.\n  (* valid pt *)\n  iDestruct (access_agree_check_true (tpa ai) i with \"pgt_acc acc\") as %Hcheckpg_ai;eauto.\n  (* valid mem *)\n  iDestruct (gen_mem_valid ai wi with \"mem mem_ins\") as %Hlookup_ai.\n  (* valid tx *)\n  iDestruct (mb_valid_tx i p_tx with \"mb tx\") as %Heq_tx.\n  (* valid tran *)\n  iSplit.\n  - (* reducible *)\n    iPureIntro.\n    apply (reducible_normal i Hvc ai wi);auto.\n    rewrite Heq_tx //.\n  - iModIntro.\n    iIntros (m2 σ2) \"vmprop_auth %HstepP\".\n    iFrame \"vmprop_auth\".\n    apply (step_ExecI_normal i Hvc ai wi) in HstepP;eauto.\n    2: rewrite Heq_tx //.\n    remember (exec Hvc σ1) as c2 eqn:Heqc2.\n    rewrite /exec /hvc Hlookup_R0 /= Hdecode_f /relinquish Hlookup_R1 /= in Heqc2.\n    assert (Hwh_None: get_transaction σ1 wh = None).\n    {\n      destruct Hwf as [_ [_ Hwf]].\n      rewrite /inv_finite_handles in Hwf.\n      rewrite Hwf in Hnin_wh.\n      rewrite not_elem_of_dom in Hnin_wh.\n      rewrite /get_transaction Hnin_wh //.\n      case_bool_decide;done.\n    }\n    rewrite Hwh_None /= in Heqc2.\n    destruct HstepP;subst m2 σ2; subst c2; simpl.\n    iDestruct (hvc_error_update (E:= E) InvParam with \"PC R0 R2 [$Hnum $mem $regs $mb $rx_state $pgt_owned $pgt_acc $pgt_excl $ trans $hpool $retri]\")\n    as \">[[$ $] ?]\". 1-4: auto. iPureIntro. auto.\n    rewrite /scheduled /machine.scheduler /= /scheduler.\n    rewrite p_upd_pc_current_vm 2!p_upd_reg_current_vm Heq_cur.\n    case_bool_decide;last contradiction.\n    simpl. iApply \"HΦ\".\n    iFrame.\n    by iFrame.\nQed.\n\nLemma mem_relinquish_fresh_handle {E i wi sacc r0 r2 wh sh q p_tx} ai:\n  tpa ai ≠ p_tx ->\n  (tpa ai) ∈ sacc ->\n  decode_instruction wi = Some(Hvc) ->\n  decode_hvc_func r0 = Some(Relinquish) ->\n  wh ∈ sh ->\n  {SS{{▷ (PC @@ i ->r ai) ∗ ▷ ai ->a wi ∗\n       ▷ (R0 @@ i ->r r0) ∗\n       ▷ (R1 @@ i ->r wh) ∗\n       ▷ (R2 @@ i ->r r2) ∗\n       ▷ i -@A> sacc ∗\n       ▷ TX@ i := p_tx ∗\n       ▷ fresh_handles q sh}}}\n   ExecI @ i; E\n   {{{ RET (false, ExecI) ;\n       PC @@ i ->r (ai ^+ 1)%f ∗ ai ->a wi ∗\n       R0 @@ i ->r (encode_hvc_ret_code Error) ∗\n       R1 @@ i ->r wh ∗\n       R2 @@ i ->r (encode_hvc_error InvParam) ∗\n       i -@A> sacc ∗\n       TX@ i := p_tx ∗\n       fresh_handles q sh\n   }}}.\nProof.\n  iIntros (Hneq_tx Hin_acc Hdecode_i Hdecode_f Hin_wh Φ)\n          \"(>PC & >mem_ins & >R0 & >R1 & >R2 & >acc & >tx & >[hp handles]) HΦ\".\n  iApply (sswp_lift_atomic_step ExecI);[done|].\n  iIntros (n σ1) \"%Hsche state\".\n  rewrite /scheduled /= /scheduler in Hsche.\n  assert (σ1.1.1.2 = i) as Heq_cur. { case_bool_decide;last done. by apply fin_to_nat_inj. }\n  clear Hsche.\n  iModIntro.\n  iDestruct \"state\" as \"(Hnum & mem & regs & mb & rx_state & pgt_owned & pgt_acc & pgt_excl &\n                            trans & hpool & retri & %Hwf & %Hdisj & %Hconsis)\".\n  (* valid regs *)\n  iDestruct ((gen_reg_valid4 i PC ai R0 r0 R1 wh R2 r2 Heq_cur) with \"regs PC R0 R1 R2\")\n    as \"(%Hlookup_PC & %Hlookup_R0 & %Hlookup_R1 & %Hlookup_R2)\";eauto.\n  (* valid pt *)\n  iDestruct (access_agree_check_true (tpa ai) i with \"pgt_acc acc\") as %Hcheckpg_ai;eauto.\n  (* valid mem *)\n  iDestruct (gen_mem_valid ai wi with \"mem mem_ins\") as %Hlookup_ai.\n  (* valid tx *)\n  iDestruct (mb_valid_tx i p_tx with \"mb tx\") as %Heq_tx.\n  (* valid hpool *)\n  iDestruct (hpool_valid with \"hpool hp\") as %Heq_hp.\n  (* valid tran *)\n  iAssert (⌜get_transaction σ1 wh = None⌝%I) as %Hwh_None.\n  {\n    iDestruct (big_sepS_elem_of _ _ wh with \"handles\") as \"[tran _]\".\n    done.\n    iDestruct (trans_valid_None with \"trans tran\") as %Hlookup_tran.\n    iPureIntro.\n    rewrite /get_transaction Hlookup_tran //.\n    case_bool_decide;done.\n  }\n  iSplit.\n  - (* reducible *)\n    iPureIntro.\n    apply (reducible_normal i Hvc ai wi);auto.\n    rewrite Heq_tx //.\n  - iModIntro.\n    iIntros (m2 σ2) \"vmprop_auth %HstepP\".\n    iFrame \"vmprop_auth\".\n    apply (step_ExecI_normal i Hvc ai wi) in HstepP;eauto.\n    2: rewrite Heq_tx //.\n    remember (exec Hvc σ1) as c2 eqn:Heqc2.\n    rewrite /exec /hvc Hlookup_R0 /= Hdecode_f /relinquish Hlookup_R1 /= in Heqc2.\n    rewrite Hwh_None /= in Heqc2.\n    destruct HstepP;subst m2 σ2; subst c2; simpl.\n    iDestruct (hvc_error_update (E:= E) InvParam with \"PC R0 R2 [$Hnum $mem $regs $mb $rx_state $pgt_owned $pgt_acc $pgt_excl $ trans $hpool $retri]\")\n    as \">[[$ $] ?]\". 1-4: auto. iPureIntro. auto.\n    rewrite /scheduled /machine.scheduler /= /scheduler.\n    rewrite p_upd_pc_current_vm 2!p_upd_reg_current_vm Heq_cur.\n    case_bool_decide;last contradiction.\n    simpl. iApply \"HΦ\".\n    iFrame.\n    by iFrame.\nQed.\n\nLemma mem_relinquish_invalid_trans {E i wi sacc r0 r2 wh meta q p_tx} ai:\n  tpa ai ≠ p_tx ->\n  (tpa ai) ∈ sacc ->\n  decode_instruction wi = Some(Hvc) ->\n  decode_hvc_func r0 = Some(Relinquish) ->\n  meta.1.1.2 ≠ i ->\n  {SS{{▷ (PC @@ i ->r ai) ∗ ▷ ai ->a wi ∗\n       ▷ (R0 @@ i ->r r0) ∗\n       ▷ (R1 @@ i ->r wh) ∗\n       ▷ (R2 @@ i ->r r2) ∗\n       ▷ i -@A> sacc ∗\n       ▷ TX@ i := p_tx ∗\n       ▷ wh -{q}>t (meta)\n       }}}\n   ExecI @ i; E\n   {{{ RET (false, ExecI) ;\n       PC @@ i ->r (ai ^+ 1)%f ∗ ai ->a wi ∗\n       R0 @@ i ->r (encode_hvc_ret_code Error) ∗\n       R1 @@ i ->r wh ∗\n       R2 @@ i ->r (encode_hvc_error Denied) ∗\n       i -@A> sacc ∗\n       TX@ i := p_tx ∗\n       wh -{q}>t (meta)\n   }}}.\nProof.\n  iIntros (Hneq_tx Hin_acc Hdecode_i Hdecode_f Hin_wh Φ)\n          \"(>PC & >mem_ins & >R0 & >R1 & >R2 & >acc & >tx & >tran) HΦ\".\n  iApply (sswp_lift_atomic_step ExecI);[done|].\n  iIntros (n σ1) \"%Hsche state\".\n  rewrite /scheduled /= /scheduler in Hsche.\n  assert (σ1.1.1.2 = i) as Heq_cur. { case_bool_decide;last done. by apply fin_to_nat_inj. }\n  clear Hsche.\n  iModIntro.\n  iDestruct \"state\" as \"(Hnum & mem & regs & mb & rx_state & pgt_owned & pgt_acc & pgt_excl &\n                            trans & hpool & retri & %Hwf & %Hdisj & %Hconsis)\".\n  (* valid regs *)\n  iDestruct ((gen_reg_valid4 i PC ai R0 r0 R1 wh R2 r2 Heq_cur) with \"regs PC R0 R1 R2\")\n    as \"(%Hlookup_PC & %Hlookup_R0 & %Hlookup_R1 & %Hlookup_R2)\";eauto.\n  (* valid pt *)\n  iDestruct (access_agree_check_true (tpa ai) i with \"pgt_acc acc\") as %Hcheckpg_ai;eauto.\n  (* valid mem *)\n  iDestruct (gen_mem_valid ai wi with \"mem mem_ins\") as %Hlookup_ai.\n  (* valid tx *)\n  iDestruct (mb_valid_tx i p_tx with \"mb tx\") as %Heq_tx.\n  (* valid tran *)\n  iDestruct (trans_valid_Some with \"trans tran\") as %[? Hlookup_tran].\n  iDestruct (trans_valid_handle_Some with \"tran\") as %Hvalid_handle.\n  iSplit.\n  - (* reducible *)\n    iPureIntro.\n    apply (reducible_normal i Hvc ai wi);auto.\n    rewrite Heq_tx //.\n  - iModIntro.\n    iIntros (m2 σ2) \"vmprop_auth %HstepP\".\n    iFrame \"vmprop_auth\".\n    apply (step_ExecI_normal i Hvc ai wi) in HstepP;eauto.\n    2: rewrite Heq_tx //.\n    remember (exec Hvc σ1) as c2 eqn:Heqc2.\n    rewrite /exec /hvc Hlookup_R0 /= Hdecode_f /relinquish Hlookup_R1 /= in Heqc2.\n    rewrite /get_transaction Hlookup_tran /= in Heqc2.\n    destruct meta as [[[? ?] ?] ?].\n    case_bool_decide;last contradiction. clear H0. simpl in Heqc2.\n    case_bool_decide;rewrite Heq_cur // in H0.\n    rewrite andb_false_r /= in Heqc2.\n    destruct HstepP;subst m2 σ2; subst c2; simpl.\n    iDestruct (hvc_error_update (E:= E) Denied with \"PC R0 R2 [$Hnum $mem $regs $mb $rx_state $pgt_owned $pgt_acc $pgt_excl $ trans $hpool $retri]\")\n    as \">[[$ $] ?]\". 1-4: auto. iPureIntro. auto.\n    rewrite /scheduled /machine.scheduler /= /scheduler.\n    rewrite p_upd_pc_current_vm 2!p_upd_reg_current_vm Heq_cur.\n    case_bool_decide;last contradiction.\n    simpl. iApply \"HΦ\".\n    iFrame.\n    by iFrame.\nQed.\n\nLemma mem_relinquish_not_retrieved{E i wi sacc r0 r2 wh q p_tx} ai:\n  tpa ai ≠ p_tx ->\n  (tpa ai) ∈ sacc ->\n  decode_instruction wi = Some(Hvc) ->\n  decode_hvc_func r0 = Some(Relinquish) ->\n  {SS{{▷ (PC @@ i ->r ai) ∗ ▷ ai ->a wi ∗\n       ▷ (R0 @@ i ->r r0) ∗\n       ▷ (R1 @@ i ->r wh) ∗\n       ▷ (R2 @@ i ->r r2) ∗\n       ▷ i -@A> sacc ∗\n       ▷ TX@ i := p_tx ∗\n       ▷ wh -{q}>re false\n       }}}\n   ExecI @ i; E\n   {{{ RET (false, ExecI) ;\n       PC @@ i ->r (ai ^+ 1)%f ∗ ai ->a wi ∗\n       R0 @@ i ->r (encode_hvc_ret_code Error) ∗\n       R1 @@ i ->r wh ∗\n       R2 @@ i ->r (encode_hvc_error Denied) ∗\n       i -@A> sacc ∗\n       TX@ i := p_tx ∗\n       wh -{q}>re false\n   }}}.\nProof.\n  iIntros (Hneq_tx Hin_acc Hdecode_i Hdecode_f Φ)\n          \"(>PC & >mem_ins & >R0 & >R1 & >R2 & >acc & >tx & >re) HΦ\".\n  iApply (sswp_lift_atomic_step ExecI);[done|].\n  iIntros (n σ1) \"%Hsche state\".\n  rewrite /scheduled /= /scheduler in Hsche.\n  assert (σ1.1.1.2 = i) as Heq_cur. { case_bool_decide;last done. by apply fin_to_nat_inj. }\n  clear Hsche.\n  iModIntro.\n  iDestruct \"state\" as \"(Hnum & mem & regs & mb & rx_state & pgt_owned & pgt_acc & pgt_excl &\n                            trans & hpool & retri & %Hwf & %Hdisj & %Hconsis)\".\n  (* valid regs *)\n  iDestruct ((gen_reg_valid4 i PC ai R0 r0 R1 wh R2 r2 Heq_cur) with \"regs PC R0 R1 R2\")\n    as \"(%Hlookup_PC & %Hlookup_R0 & %Hlookup_R1 & %Hlookup_R2)\";eauto.\n  (* valid pt *)\n  iDestruct (access_agree_check_true (tpa ai) i with \"pgt_acc acc\") as %Hcheckpg_ai;eauto.\n  (* valid mem *)\n  iDestruct (gen_mem_valid ai wi with \"mem mem_ins\") as %Hlookup_ai.\n  (* valid tx *)\n  iDestruct (mb_valid_tx i p_tx with \"mb tx\") as %Heq_tx.\n  (* valid tran *)\n  iDestruct (retri_valid_Some with \"retri re\") as %[? Hlookup_re].\n  iDestruct (retri_valid_handle_Some with \"re\") as %Hvalid_handle.\n  iSplit.\n  - (* reducible *)\n    iPureIntro.\n    apply (reducible_normal i Hvc ai wi);auto.\n    rewrite Heq_tx //.\n  - iModIntro.\n    iIntros (m2 σ2) \"vmprop_auth %HstepP\".\n    iFrame \"vmprop_auth\".\n    apply (step_ExecI_normal i Hvc ai wi) in HstepP;eauto.\n    2: rewrite Heq_tx //.\n    remember (exec Hvc σ1) as c2 eqn:Heqc2.\n    rewrite /exec /hvc Hlookup_R0 /= Hdecode_f /relinquish Hlookup_R1 /= in Heqc2.\n    rewrite /get_transaction Hlookup_re /= in Heqc2.\n    destruct x as [[[? ?] ?] ?].\n    assert (Heq_c2 : (m2,σ2) = (ExecI, update_incr_PC (update_reg (update_reg σ1 R0 (encode_hvc_ret_code Error)) R2 (encode_hvc_error Denied)))).\n    {\n      case_bool_decide;last contradiction.\n      destruct HstepP;subst m2 σ2; subst c2; done.\n    }\n    inversion Heq_c2. clear H1 H2 Heq_c2 Heqc2.\n    iDestruct (hvc_error_update (E:= E) Denied with \"PC R0 R2 [$Hnum $mem $regs $mb $rx_state $pgt_owned $pgt_acc $pgt_excl $ trans $hpool $retri]\")\n    as \">[[$ $] ?]\". 1-4: auto. iPureIntro. auto.\n    rewrite /scheduled /machine.scheduler /= /scheduler.\n    rewrite p_upd_pc_current_vm 2!p_upd_reg_current_vm Heq_cur.\n    case_bool_decide;last contradiction.\n    simpl. iApply \"HΦ\".\n    iFrame.\n    by iFrame.\nQed.\n\nEnd mem_relinquish.\n", "meta": {"author": "logsem", "repo": "VMSL", "sha": "0a9b005b599a770e40c07abc9aa10a4ee9759315", "save_path": "github-repos/coq/logsem-VMSL", "path": "github-repos/coq/logsem-VMSL/VMSL-0a9b005b599a770e40c07abc9aa10a4ee9759315/theories/rules/mem_relinquish.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.2690010568108303}}
{"text": "Require Import Min.\n\nRequire Import msl.msl_standard.\nRequire Import Maps.\nRequire Import FuncListMachine.\nRequire Import lemmas.\n\nOpen Scope pred.\n\nProgram Definition guards (n:nat) (X:pred world) (stk:stack) : pred world :=\n  fun prt =>\n    match prt with (p,(r,t)) =>\n\n      forall p',\n        necR p p' ->\n        X (p',(r,t)) ->\n        safe t p' r stk /\\\n        (level p' >= n -> eventually_halts t p' r stk)\n  end.\nNext Obligation.\n  unfold hereditary; intros.\n  destruct a as [p [r' t]].\n  destruct a' as [p' [r'' t']].\n  hnf in H.\n  simpl in H.\n  unfold prog in *.\n  case_eq (age1 p); intros.\n  rewrite H1 in H.\n  inv H.\n  spec H0 p'0.\n  spec H0.\n  apply rt_trans with p'; auto.\n  apply rt_step; auto.\n  spec H0; auto.\n  rewrite H1 in H; discriminate.\nQed.\n\nProgram Definition term_guards (t:store -> option nat) (n:nat) (X:pred world) (stk:stack) : pred world :=\n  fun prt =>\n    match prt with (p,(r,t')) =>\n\n      forall p',\n        necR p p' ->\n        X (p',(r,t')) ->\n        exists n',\n          t r = Some n' /\\\n          safe t' p' r stk /\\\n          (level p' >= (n'+n) -> eventually_halts t' p' r stk)\n  end.\nNext Obligation.\n  unfold hereditary; intros.\n  destruct a as [? [? ?]].\n  destruct a' as [? [? ?]].\n  intros.\n  hnf in H.\n  unfold prog in *.\n  simpl in H.\n  case_eq (age1 p); intros; rewrite H3 in H; inv H.\n  spec H0 p'. spec H0.\n  apply rt_trans with p0; auto.\n  apply rt_step; auto.\n  spec H0; auto.\nQed.\n\nProgram Definition funptr (l:label) (A:Type) (P Q: A -> pred world) : pred world :=\n  fun prt =>\n    match prt with (p,(_,t)) =>\n      exists i,  prog_lookup p l = Some i /\\\n        (forall stk p' n t' (x:A),\n          termMeasure_incr t t' ->\n           laterR p p' ->\n           (forall r', guards n (Q x) stk (p',(r' ,t'))) ->\n           (forall r , term_guards (t l) n (P x) ((i;;instr_nil _)::stk) (p',(r,t'))))\n    end.\nNext Obligation.\n  unfold hereditary; intros.\n  destruct a as [p [r' t]].\n  destruct a' as [p' [r'' t']].\n  hnf in H; simpl in H.\n  case_eq (age1 p); intros.\n  unfold prog in *.\n  rewrite H1 in H.\n  inv H.\n  rename t' into t.\n  destruct H0 as [i [? ?]].\n  rewrite K.knot_age1 in H1.\n  case_eq (K.unsquash p); intros.\n  rewrite H2 in H1.\n  destruct n; try discriminate.\n  inv H1.\n  exists (fmap_instr (K.approx n) i).\n  split.\n  unfold prog_lookup.\n  rewrite K.unsquash_squash; simpl.\n  unfold KnotInput.fmap.\n  apply fmap_eqn.\n  unfold prog_lookup in H.\n  rewrite H2 in H.\n  auto.\n  intros.\n  spec H0 stk p' n0 t' x.\n  spec H0; auto.\n  spec H0.\n  apply t_trans with (K.squash (n,f)); auto.\n  apply t_step.\n  hnf. simpl.\n  rewrite K.knot_age1. rewrite H2. auto.\n  spec H0. auto.\n  hnf; intros.\n  spec H0 r p'0 H5 H6.\n  destruct H0 as [n' [? ?]].\n  exists n'; split; auto.\n  destruct H7; split.\n  revert H7; apply safe_approx with n; eauto.\n  replace n with (level (K.squash (n,f))).\n  apply later_level.\n  apply Rt_Rft_trans with p'; auto.\n  rewrite K.knot_level.\n  rewrite K.unsquash_squash; auto.\n  hnf; eauto.\n  hnf; auto.\n  constructor; auto.\n  apply (intro_instr_approx_rel _ _ (i;;instr_nil _)); auto.\n  apply stack_approx_rel_refl.\n  intros; spec H8; auto.\n  revert H8.\n  apply ev_halts_approx with n.\n  replace n with (level (K.squash (n,f))).\n  apply later_level.\n  apply Rt_Rft_trans with p'; auto.\n  rewrite K.knot_level.\n  rewrite K.unsquash_squash; auto.\n  hnf; eauto.\n  hnf; auto.\n  constructor; auto.\n  apply (intro_instr_approx_rel _ _ (i;;instr_nil _)); auto.\n  apply stack_approx_rel_refl.\n\n  unfold prog in *.\n  rewrite H1 in H.\n  discriminate.\nQed.\n\nLemma boxy_funptr : forall l A P Q,\n  boxy K.expandM (funptr l A P Q).\nProof.\n  intros. apply boxy_i; auto.\n  simpl; intros.\n  destruct w; destruct w'.\n  destruct o; destruct o0.\n  rewrite K.expandM_spec in H.\n  destruct H.\n  assert (k=k0).\n  hnf in H.\n  apply K.unsquash_inj.\n  destruct (K.unsquash k). destruct (K.unsquash k0).\n  destruct H; f_equal; auto.\n  subst k0.\n  destruct H1. simpl in *.\n  destruct H0 as [i [? ?]].\n  exists i; split; auto.\n  intros.\n  spec H3 stk p' n t' x. spec H3; auto.\n  do 2 intro. destruct (H2 l0 r0); auto.\n  rewrite H9; auto.\n  spec H3; auto.\n  spec H3; auto.\n  spec H3 r p'0 H7 H8.\n  destruct H3 as [n' [? ?]].\n  exists n'; split; auto.\n  destruct (H2 l r); auto.\n  rewrite H3 in H10; discriminate.\n  congruence.\nQed.\n\n(* Definition of the hoare relation and rules *)\n\nDefinition hoare (t:terminationMeasure) (n':nat) (G R P:pred world) (c:instruction) (Q:pred world) :=\n  forall t', termMeasure_incr t t' ->\n\n  forall p n k stk,\n    (forall s, G (p,(s,t'))) ->\n    (forall r', guards n R stk       (p,(r',t'))) ->\n    (forall r', guards n Q (k::stk)  (p,(r',t'))) ->\n    (forall r,  guards (n'+n) P ((c ;; k)::stk) (p,(r,t'))).\n\n\nLemma hoare_weaken : forall t t' x x' (G G' R R' P P' Q Q':pred world) i,\n  termMeasure_incr t t' ->\n  x <= x' ->\n  G' |-- G  ->\n  R  |-- R' ->\n  P' |-- P  ->\n  Q  |-- Q' ->\n  hoare t  x  G  R  P  i Q ->\n  hoare t' x' G' R' P' i Q'.\nProof.\n  intros until i; repeat intro.\n  hnf in H5.\n  spec H5 t'0.\n  spec H5; auto.\n  do 2 intro. destruct (H l r0); auto.\n  rewrite H12; auto.\n  spec H5 p n k stk.\n  spec H5; auto.\n  spec H5. repeat intro. eapply H8; eauto.\n  spec H5. repeat intro. eapply H9; eauto.\n  spec H5 r p' H10.\n  spec H5; auto.\n  destruct H5; split; auto.\n  intro. spec H12. omega.\n  auto.\nQed.\n\nLemma hoare_weaken_time : forall t x x' G R P i Q,\n  x <= x' ->\n  hoare t x G R P i Q ->\n  hoare t x' G R P i Q.\nProof.\n  intros until Q. intro. apply hoare_weaken; auto; hnf; auto.\nQed.\n\nLemma hoare_weaken_pre : forall t x G R P P' i Q,\n  P' |-- P ->\n  hoare t x G R P i Q ->\n  hoare t x G R P' i Q .\nProof.\n  intros until Q. intro.\n  apply hoare_weaken; auto; hnf; auto.\nQed.\n\nLemma hoare_weaken_post : forall t x G R P i Q Q',\n  Q |-- Q' ->\n  hoare t x G R P i Q ->\n  hoare t x G R P i Q'.\nProof.\n  intros until Q'. intro.\n  apply hoare_weaken; auto; hnf; auto.\nQed.\n\nLemma hoare_ex_pre : forall t x G R T P i Q,\n  (forall z:T, hoare t x G R (P z) i Q) ->\n  hoare t x G R (exp P) i Q.\nProof.\n  repeat intro.\n  destruct H5.\n  spec H x0.\n  eapply H; eauto.\nQed.\n\nLemma hoare_fact_pre : forall t x G R (X:Prop) P i Q,\n  (X -> hoare t x G R P i Q) ->\n  hoare t x G R (!!X && P) i Q.\nProof.\n  repeat intro.\n  destruct H5. hnf in H5.\n  spec H H5. eapply H; eauto.\nQed.\n\n\nLemma hoare_return : forall t (G R:pred world),\n  hoare t 0 G R R instr_return FF.\nProof.\n  repeat intro.\n  spec H1 r p' H3 H4.\n  destruct H1. split.\n  repeat intro.\n  inv H6. econstructor.\n  eapply step_return.\n  inv H7. apply H1; auto.\n  intro. spec H5. omega.\n  destruct H5 as [pz [rz ?]].\n  exists pz. exists rz.\n  econstructor. eapply step_return.\n  auto.\nQed.\n\nLemma hoare_getlabel : forall t l v (G R P:pred world),\n  hoare t 0 G R\n    (box (setM v (value_label l)) P)\n    (instr_getlabel l v)\n    P.\nProof.\n  repeat intro.\n  spec H2 (r#v <- (value_label l)).\n  spec H2 p' H3.\n  spec H2. apply H4. constructor; auto.\n  destruct H2. split.\n  repeat intro.\n  inv H6. econstructor. econstructor.\n  inv H7. apply H2; auto.\n  intro; spec H5. omega.\n  destruct H5 as [pz [rz ?]].\n  exists pz; exists rz.\n  econstructor. econstructor.\n  auto.\nQed.\n\nLemma hoare_step_fetch0 : forall t v1 v2 x1 x2 (G R P:pred world),\n  hoare t 0 G R\n    (store_op (fun r => r#v1 = Some (value_cons x1 x2)) && box (setM v2 x1) P)\n    (instr_fetch_field v1 0 v2)\n    P.\nProof.\n  repeat intro.\n  destruct H4.\n  destruct H4 as [_ [? _]].\n  spec H2 (r#v2 <- x1).\n  spec H2 p' H3.\n  spec H2. apply H5. constructor. auto.\n  destruct H2. split.\n  repeat intro.\n  inv H7.\n  econstructor. econstructor; eauto.\n  inv H8.\n  apply H2; auto.\n  replace x1 with a0 by congruence. auto.\n  intro. spec H6. omega.\n  destruct H6 as [pz [rz ?]].\n  exists pz; exists rz.\n  econstructor. econstructor. eauto.\n  auto.\nQed.\n\nLemma hoare_step_fetch1 : forall t v1 v2 x1 x2 (G R P:pred world),\n  hoare t 0 G R\n    (store_op (fun r => r#v1 = Some (value_cons x1 x2)) && box (setM v2 x2) P)\n    (instr_fetch_field v1 1 v2)\n    P.\nProof.\n  repeat intro.\n  destruct H4.\n  destruct H4 as [_ [? _]].\n  spec H2 (r#v2 <- x2).\n  spec H2 p' H3.\n  spec H2. apply H5. constructor. auto.\n  destruct H2. split.\n  repeat intro.\n  inv H7.\n  econstructor. econstructor; eauto.\n  inv H8.\n  apply H2; auto.\n  replace x2 with a1 by congruence. auto.\n  intro. spec H6. omega.\n  destruct H6 as [pz [rz ?]].\n  exists pz; exists rz.\n  econstructor. econstructor. eauto.\n  auto.\nQed.\n\nLemma hoare_cons : forall t v1 v2 v3 x1 x2 (G R P:pred world),\n  hoare t 0 G R\n     (store_op (fun r => r#v1 = Some x1 /\\ r#v2 = Some x2) &&\n        box (setM v3 (value_cons x1 x2)) P)\n     (instr_cons v1 v2 v3)\n     P.\nProof.\n  repeat intro.\n  destruct H4.\n  destruct H4 as [_ [[? ?] _]].\n  spec H2 (r#v3 <- (value_cons x1 x2)).\n  spec H2 p' H3.\n  spec H2.\n  apply H5. constructor. auto.\n  destruct H2. split.\n  repeat intro.\n  inv H8.\n  econstructor. econstructor; eauto.\n  inv H9.\n  apply H2.\n  replace x1 with a1 by congruence.\n  replace x2 with a2 by congruence.\n  auto.\n  intro. spec H7. omega.\n  destruct H7 as [pz [rz ?]].\n  exists pz; exists rz.\n  econstructor. econstructor; eauto.\n  auto.\nQed.\n\nLemma hoare_if : forall t x v s1 s2 G R P Q,\n  P |-- store_op (fun r => match r#v with\n                           | Some (value_label l) => l = L 0\n                           | Some (value_cons _ _) => True\n                           | _ => False\n                           end) ->\n  hoare t x G R (P && store_op (fun r => r#v = Some (value_label (L 0)))) s1 Q ->\n  hoare t x G R (P && store_op (fun r => exists x1, exists x2, r#v = Some (value_cons x1 x2))) s2 Q ->\n  hoare t x G R P (instr_if_nil v s1 s2) Q.\nProof.\n  repeat intro.\n  generalize H7; intros.\n  apply H in H8.\n  simpl in H8. destruct H8 as [_ [? _]].\n  case_eq (r#v); intros; rewrite H9 in H8;\n    try tauto.\n  destruct v0.\n\n  (* nil case *)\n  subst l.\n  spec H0 t' H2 p n k.\n  spec H0 stk.\n  do 3 (spec H0; auto).\n  spec H0 r p' H6.\n  spec H0.\n  split; auto.\n  simpl. intuition.\n  destruct H0; split.\n  repeat intro.\n  inv H10.\n  econstructor 1.\n  eapply step_if_nil1. auto.\n  inv H11.\n  eapply H0; eauto.\n  rewrite H22 in H9. discriminate.\n  intro; spec H8; auto.\n  destruct H8 as [pz [rz ?]].\n  exists pz; exists rz.\n  econstructor.\n  eapply step_if_nil1; auto.\n  auto.\n\n  (* cons case *)\n  spec H1 t' H2 p n k.\n  spec H1 stk.\n  do 3 (spec H1; auto).\n  spec H1 r p' H6.\n  spec H1. split. auto.\n  simpl; intuition. eauto.\n  destruct H1. split.\n  repeat intro.\n  inv H11.\n  econstructor 1. eapply step_if_nil2; eauto.\n  eapply H1; eauto.\n  inv H12. rewrite H23 in H9; discriminate.\n  rewrite H23 in H9. inv H9. auto.\n  intro; spec H10; auto.\n  destruct H10 as [pz [rz ?]].\n  exists pz; exists rz.\n  econstructor.\n  eapply step_if_nil2; eauto.\n  auto.\nQed.\n\nLemma hoare_call : forall t x G R v Q,\n  let wp :=\n    EX l:label, EX A:Type, EX lP:(A->pred world), EX lQ:(A -> pred world), EX n':nat, EX a:A,\n      store_op (fun r => r#v = Some (value_label l) /\\ t l r = Some n' /\\ n' < x) &&\n      (G --> funptr l A lP lQ) &&\n      lP a && (closed (lQ a --> Q))\n in\n  hoare t x G R wp (instr_call v) Q.\nProof.\n  repeat intro.\n  unfold wp in H4.\n  destruct H4 as [l [A [lP [lQ [n' [a ?]]]]]].\n  destruct H4 as [[[? ?] ?] ?].\n  destruct H4 as [_ [? _]].\n  destruct H4 as [? [? ?]].\n  destruct x. exfalso; omega.\n  assert (funptr l A lP lQ (p',(r,t'))).\n  apply H5. auto.\n  apply pred_nec_hereditary with (p,(r,t')); auto.\n  rewrite worldNec_unfold; intuition.\n  case_eq (age1 p'); intros.\n  destruct H10 as [i [? ?]].\n  spec H12 (k::stk) p0 n t' a.\n  spec H12. hnf; auto.\n  spec H12. apply t_step. auto.\n  spec H12.\n    intro r'. spec H2 r'.\n    repeat intro.\n    spec H2 p'0.\n    spec H2.\n    apply rt_trans with p'; auto.\n    apply rt_trans with p0; auto.\n    apply rt_step; auto.\n    spec H2; auto.\n    spec H7 (p',(r',t')).\n    spec H7. simpl; hnf; auto.\n    apply H7.\n    rewrite worldNec_unfold; intuition.\n    apply rt_trans with p0; auto.\n    apply rt_step; auto.\n    auto.\n\n  spec H12 r p0. spec H12; auto.\n  spec H12. apply pred_nec_hereditary with (p',(r,t')); auto.\n  rewrite worldNec_unfold; intuition.\n  destruct H12 as [n2 [? ?]].\n  destruct (H l r). congruence.\n  rewrite <- H14 in H12.\n  rewrite H8 in H12. inv H12. clear H14.\n\n  destruct H13. split.\n  repeat intro.\n  inv H14.\n  econstructor 1.\n  eapply step_call with (i':=i); eauto.\n  inv H15.\n  assert (p0 = p'1) by congruence. subst p'1.\n  assert (l = l0) by congruence. subst l0.\n  assert (i = i'0) by congruence. subst i'0.\n  apply H12; auto.\n  apply (af_level2 age_facts) in H11.\n  congruence.\n  intro. spec H13.\n  apply (af_level2 age_facts) in H11. omega.\n  destruct H13 as [pz [rz ?]].\n  exists pz; exists rz.\n  econstructor.\n  econstructor; eauto.\n  auto.\n\n  split.\n  clear -H11.\n  repeat intro.\n  apply stepstar_stepN in H. destruct H as [n H].\n  revert p' H11 p'0 s' k k' stk H.\n  induction n; simpl; intros.\n  inv H.\n  econstructor 1.\n  eapply step_call_apocalypse.\n  rewrite <- (af_level1 age_facts); auto.\n  inv H.\n  inv H1.\n  hnf in H12. rewrite H12 in H11. discriminate.\n  eapply IHn; eauto.\n  rewrite (af_level1 age_facts) in H11.\n  intro. exfalso. omega.\nQed.\n\n\nLemma hoare_assert : forall t (G R P:pred world) (Q:K.assert),\n  boxy K.expandM G ->\n  G && P |-- (proj1_sig Q) ->\n  hoare t 0 G R P (instr_assert Q) P.\nProof.\n  repeat intro.\n  split.\n  hnf; intros.\n  inv H7.\n  econstructor 1.\n  econstructor.\n  apply H0. split; auto.\n  eapply pred_nec_hereditary.\n  2: apply H2.\n  instantiate (1:=s').\n  rewrite worldNec_unfold. intuition.\n  inv H8.\n  destruct (H4 s'0 p'1); auto.\n  repeat intro.\n  destruct (H4 r p'); auto.\n  spec H9. omega.\n  destruct H9 as [p'' [r' ?]].\n  exists p''; exists r'.\n  econstructor 2.\n  econstructor.\n  apply H0.\n  split; auto.\n  eapply pred_nec_hereditary.\n  2: apply H2.\n  instantiate (1:=r).\n  rewrite worldNec_unfold; intuition.\n  auto.\nQed.\n\nLemma hoare_seq : forall t x y G R P Q S i1 i2,\n  hoare t x G R P i1 Q ->\n  hoare t y G R Q i2 S ->\n  hoare t (x+y) G R P (i1 ;; i2) S.\nProof.\n  intros. hnf; intros.\n  assert (guards (x+(y+n)) P ((i1;;i2;;k)::stk) (p,(r,t'))).\n  apply H; auto.\n  repeat intro.\n  spec H3 r' p' H5 H6.\n  intuition.\n  repeat intro.\n  spec H5 p' H6 H7.\n  destruct H5; split.\n  repeat intro.\n  inv H9.\n  econstructor 1. econstructor.\n  inv H10.\n  eapply H5; eauto.\n  intro.\n  spec H8. omega.\n  destruct H8 as [pz [rz ?]].\n  exists pz; exists rz.\n  econstructor. econstructor.\n  auto.\nQed.\n\n\n(* Verifying function bodies and entire programs *)\n\nDefinition verify_prog (t:terminationMeasure) (G:pred world) (psi:program K.assert) (G':pred world) :=\n  forall n r,\n     agedfrom (K.squash (n,psi),(r,t)) && |>(box K.expandM (closed G))\n       |-- box K.expandM (closed G').\n\nLemma verify_complete : forall G G' psi t,\n  G' |-- G ->\n  verify_prog t G psi G' ->\n  forall n r, G' (K.squash (n,psi),(r,t)).\nProof.\n  intros.\n  spec H0 n r.\n  cut (agedfrom (K.squash (n,psi),(r,t)) |-- (box K.expandM (closed G'))).\n  intros.\n  eapply H1.\n  hnf; apply rt_refl.\n  apply K.expandM_refl.\n  hnf; simpl; auto.\n  apply goedel_loeb.\n  apply derives_trans with\n    (agedfrom (K.squash (n,psi),(r,t)) && |>(box K.expandM (closed G))); auto.\n  intros a Ha; destruct Ha; split; auto.\n  clear H1.\n  revert a H2.\n  do 3 apply box_positive; auto.\nQed.\n\n\nLemma verify_func : forall psi l (G:pred world) (A:Type) (P Q:A -> pred world) i t,\n  psi#l = Some i ->\n\n  (forall a p r t', termMeasure_incr t t' -> proj1_sig (P a) (p,(r,t')) -> exists n, t l r = Some n) ->\n\n  (forall a n,\n    let Pr  := P a && store_op (fun r' => t l r' = Some n) in\n    let Pr' a' := P a' && store_op (fun r' => exists n', t l r' = Some n' /\\ n' < n) in\n    hoare t n (funptr l A Pr' Q && G) (Q a) Pr i FF) ->\n\n  verify_prog t  G psi G ->\n  verify_prog t (funptr l A P Q && G) psi (funptr l A P Q && G).\nProof.\n  repeat intro.\n  destruct H3.\n  unfold closed in H6.\n  do 3 rewrite box_and in H6.\n  destruct H6.\n  split. 2: eapply H2; eauto; split; eauto.\n  destruct a. destruct a'. destruct a'0.\n  destruct H5.\n  destruct p. destruct p1. destruct o.\n  simpl in H5, H8. subst p0 t1.\n  rewrite K.expandM_spec in H4.\n  assert (k = k0 /\\ r = s /\\ t = t0).\n  simpl in H3. rewrite worldNec_unfold in H3.\n  intuition.\n  hnf in H3.\n  apply K.unsquash_inj.\n  destruct (K.unsquash k). destruct (K.unsquash k0).\n  f_equal; intuition.\n  destruct H5 as [? [? ?]]; subst s t0 k0.\n  destruct H4 as [_ ?].\n  destruct H4. simpl in H4, H5.\n  assert (Hlookup :\n    prog_lookup k l =\n      Some (fmap_instr (K.approx (level k)) i)).\n  replace (fmap_instr (K.approx (level k)) i)\n    with (fmap_instr (K.approx (level k)) (fmap_instr (K.approx n) i)).\n  apply nec_prog_lookup with (K.squash (n,psi)); auto.\n  simpl in H3. rewrite worldNec_unfold in H3; intuition.\n  unfold prog_lookup. rewrite K.unsquash_squash.\n  simpl. unfold KnotInput.fmap.\n  apply fmap_eqn. auto.\n  rewrite collapse_instr_approx.\n  rewrite min_l; auto.\n  replace n with (level (K.squash (n,psi))).\n  apply nec_level. simpl in H3. rewrite worldNec_unfold in H3; intuition.\n  rewrite K.knot_level. rewrite K.unsquash_squash; auto.\n\n  simpl.\n  exists (fmap_instr (K.approx (level k)) i).\n  split. auto.\n\n  clear s0.\n  intros stk p' n0 t' x G1 G2 G3 r0.\n  revert stk p' n0 t' x G1 G2 G3.\n  set (R r1 r2 :=\n           match t l r1, t l r2 with\n           | Some n1, Some n2 => n1 < n2\n           | _, _ => False\n           end).\n  assert (well_founded R).\n  clear. hnf; intro a.\n  case_eq (t l a); intros.\n  revert a H.\n  induction n using (well_founded_induction lt_wf); intros.\n  constructor; intros.\n  hnf in H1.\n  case_eq (t l y); intros.\n  rewrite H2 in H1. rewrite H0 in H1.\n  apply H with n0; auto.\n  rewrite H2 in H1. elim H1.\n  constructor; intros.\n  hnf in H0. destruct (t l y).\n  rewrite H in H0. elim H0. elim H0.\n\n  move r0 after H8.\n  induction r0 using (well_founded_induction H8).\n  intros.\n  destruct (H0 x p'0 r0 t') as [n' ?]; auto.\n  eapply termMeasure_incr_trans; eauto.\n  exists n'; split; auto.\n  destruct (H5 l r0); congruence.\n\n  spec H1 x n' t'.\n  spec H1. eapply termMeasure_incr_trans; eauto.\n  spec H1 p' n0 (instr_nil K.assert) stk.\n  spec H1.\n\n    repeat intro.\n    split.\n    exists (fmap_instr (K.approx (level p')) i).\n    split.\n    replace (fmap_instr (K.approx (level p')) i)\n      with (fmap_instr (K.approx (level p')) (fmap_instr (K.approx (level k)) i)).\n    apply nec_prog_lookup with k; auto.\n    apply Rt_Rft; auto.\n    rewrite collapse_instr_approx.\n    rewrite min_l; auto.\n    apply later_level in G2.\n    unfold prog in *. omega.\n\n    clear H1.\n    repeat intro.\n    destruct H16.\n    simpl in H17.\n    destruct H17 as [_ [? _]].\n    destruct H17 as [n'' [? ?]].\n    exists n''. split.\n    destruct (H5 l r1). congruence.\n    destruct (G1 l r1); congruence.\n    spec H9 r1. spec H9.\n    hnf. rewrite H17. rewrite H12. auto.\n    spec H9 stk0 p'1 n1 t'0 x0.\n    spec H9.\n    eapply termMeasure_incr_trans; eauto.\n    spec H9. apply t_trans with p'; auto.\n    spec H9. auto.\n    spec H9 p'2. spec H9. auto.\n    spec H9. auto.\n    destruct H9 as [n2 [? ?]].\n    assert (n'' = n2).\n    destruct (H5 l r1); congruence.\n    subst n''.\n    destruct H19; split.\n    revert H19.\n    apply safe_approx with (level p').\n    apply later_level.\n    apply Rt_Rft_trans with p'1; auto.\n    hnf; auto.\n    hnf; auto.\n    constructor. hnf. simpl. f_equal.\n    rewrite collapse_instr_approx.\n    rewrite collapse_instr_approx_same.\n    rewrite min_l; auto.\n    apply later_level in G2.\n    unfold prog in *; omega.\n    apply stack_approx_rel_refl.\n    intro. spec H20. auto.\n    revert H20.\n    apply ev_halts_approx with (level p').\n    apply later_level. apply Rt_Rft_trans with p'1; auto.\n    hnf; auto.\n    hnf. auto.\n    constructor. hnf. simpl. f_equal.\n    rewrite collapse_instr_approx.\n    rewrite collapse_instr_approx_same.\n    rewrite min_l; auto.\n    apply later_level in G2.\n    unfold prog in *; omega.\n    apply stack_approx_rel_refl.\n    eapply H7.\n    instantiate (1:=(p',(r,t))).\n    simpl.\n    rewrite worldLater_unfold. intuition.\n    instantiate (1:= (p',(r,t'))).\n    rewrite K.expandM_spec.\n    split. hnf. destruct (K.unsquash p'); split; hnf; auto.\n    split; simpl; auto. hnf; auto.\n    eapply termMeasure_incr_trans; eauto.\n    split; simpl; auto.\n\n  spec H1. auto.\n  spec H1. repeat intro. elim H14.\n  spec H1 r0.\n  spec H1 p'0.\n  spec H1; auto.\n  spec H1. split; auto.\n  simpl. auto.\n  destruct H1; split.\n  revert H1.\n  apply safe_approx with (level k).\n  apply later_level. apply Rt_Rft_trans with p'; auto.\n  hnf; auto.\n  hnf; auto.\n  constructor.\n  hnf. simpl. f_equal.\n  rewrite collapse_instr_approx_same; auto.\n  apply stack_approx_rel_refl.\n  intro; spec H13; auto.\n  revert H13.\n  apply ev_halts_approx with (level k).\n  apply later_level. apply Rt_Rft_trans with p'; auto.\n  hnf; auto.\n  hnf; auto.\n  constructor.\n  hnf. simpl. f_equal.\n  rewrite collapse_instr_approx_same; auto.\n  apply stack_approx_rel_refl.\nQed.\n\n\nLemma end_assert_lemma : forall Q t n p p' r r' stk,\n    stepN n t p p' r (stk++(instr_assert Q ;; instr_return ;; instr_nil _) :: nil) r' nil ->\n    stepstar t p p' r (stk++(instr_return ;; instr_nil _) :: nil) r' nil /\\ proj1_sig Q (p',(r',t)).\nProof.\n  induction n; simpl; intros; inv H.\n  destruct stk; discriminate.\n  destruct stk. simpl in H1.\n  inv H1. simpl.\n  split; auto.\n  apply stepN_stepstar with n; auto.\n  inv H2. inv H.\n  inv H0. auto.\n  inv H.\n\n  simpl in H1.\n  inv H1.\n  apply IHn with (stk:= i0::stk) in H2.\n  intuition. econstructor. econstructor; auto. auto.\n  apply IHn with (stk:= i0::stk) in H2.\n  intuition. econstructor. econstructor; auto. auto.\n  apply IHn with (stk:= i0::stk) in H2.\n  intuition. econstructor. econstructor; eauto. auto.\n  apply IHn with (stk:= i0::stk) in H2.\n  intuition. econstructor. econstructor; eauto. auto.\n  apply IHn with (stk:= i0::stk) in H2.\n  intuition. econstructor. econstructor; eauto. auto.\n  apply IHn with (stk:= (i1;;i2;;i3)::stk) in H2.\n  intuition. econstructor. econstructor; eauto. auto.\n  apply IHn with (stk:= (i1;;i0)::stk) in H2.\n  intuition. econstructor. econstructor; eauto. auto.\n  apply IHn with (stk:= (i2;;i0)::stk) in H2.\n  intuition. econstructor. eapply step_if_nil2; eauto. auto.\n  apply IHn with (stk:= (i'0;;instr_nil _)::i0::stk) in H2.\n  intuition. econstructor. econstructor; eauto. auto.\n  apply IHn with (stk:= (instr_call v;;i0)::stk) in H2. intuition.\n  apply IHn with (stk:=stk) in H2.\n  intuition. econstructor. econstructor. auto.\nQed.\n\n(* Fundamental liveness theorem.  A verified function,\n   when started in a state satisfying its precondition,\n   will halt in a state satisfying its postcondition.\n *)\n\nLemma verify_totally_correct : forall t G A P Q psi l x\n  (HQ:forall x, boxy K.expandM (Q x)),\n  verify_prog t G psi G ->\n  G |-- funptr l A P Q ->\n  forall r,\n    (forall n, P x (K.squash (n,psi),(r#(L 0) <- (value_label l),t))) ->\n    exists n, exists p', exists r',\n      stepstar t (K.squash (n,psi)) p'\n        r ((instr_getlabel l (L 0) ;; instr_call (L 0) ;; instr_return ;; instr_nil _)::nil)\n        r' nil /\\\n      Q x (p',(r',t)).\nProof.\n  intros.\n  assert (forall n r, G (K.squash (n,psi),(r,t))).\n  apply verify_complete with G; auto.\n  hnf; auto.\n  set (r' :=(r#(L 0) <- (value_label l))).\n  assert (exists n, t l r' = Some n).\n  assert (funptr l A P Q (K.squash (1,psi),(r,t))) by auto.\n  destruct H3 as [i [? ?]].\n  spec H4 (nil : stack) (K.squash (0,psi)) 0 t x.\n  spec H4. hnf; auto.\n  spec H4. apply t_step. hnf.\n  rewrite K.knot_age1. rewrite K.unsquash_squash.\n  f_equal. apply K.unsquash_inj.\n  repeat rewrite K.unsquash_squash.\n  f_equal.\n  change ((KnotInput.fmap (K.approx 0) oo KnotInput.fmap (K.approx 1)) psi =\n    KnotInput.fmap (K.approx 0) psi).\n  rewrite KnotInput.fmap_comp.\n  replace 1 with (1+0) by omega.\n  rewrite <- (K.approx_approx1 1 0); auto.\n  spec H4.\n  repeat intro. split; repeat intro.\n  inv H7. constructor 2.\n  inv H8.\n  exists p'. exists r'0. apply stepstar_O.\n  spec H4 r' (K.squash (0,psi)).\n  spec H4. auto.\n  spec H4. auto.\n  destruct H4 as [n' [? ?]]. eauto.\n  destruct H3 as [n ?].\n  assert (funptr l A P Q (K.squash (S n,psi),(r,t))) by auto.\n  destruct H4 as [i [? ?]].\n  spec H5 ((instr_assert (exist _ (Q x) (HQ x)) ;; instr_return ;; instr_nil K.assert)::nil).\n  spec H5 (K.squash (n,psi)) 0 t x.\n  spec H5. hnf; auto.\n  spec H5.\n  apply t_step.\n  hnf. rewrite K.knot_age1.\n  rewrite K.unsquash_squash; simpl.\n  f_equal.\n  apply K.unsquash_inj.\n  repeat rewrite K.unsquash_squash.\n  f_equal.\n  transitivity (KnotInput.fmap (K.approx n oo K.approx (S n)) psi).\n  rewrite <- KnotInput.fmap_comp; auto.\n  replace (K.approx n oo K.approx (S n)) with (K.approx n); auto.\n  extensionality.\n  unfold compose.\n  change (K.approx n x0 = (K.approx n oo K.approx (1+n)) x0).\n  rewrite <- K.approx_approx1; auto.\n  hnf; auto.\n  spec H5.\n  repeat intro.\n  split.\n  hnf.\n  intros.\n  inv H8.\n  econstructor 1.\n  econstructor.\n  auto.\n  inv H9. simpl in *.\n  inv H10.\n  econstructor 1.\n  econstructor.\n  inv H8.\n  inv H9.\n  constructor.\n  inv H8.\n  intros.\n  econstructor.\n  econstructor.\n  econstructor 2.\n  econstructor.\n  simpl; auto.\n  econstructor. econstructor.\n  econstructor 1.\n  spec H5 r' (K.squash (n,psi)).\n  spec H5; auto.\n  spec H5. auto.\n  destruct H5 as [n' [? ?]].\n  assert (n = n') by congruence. subst n'.\n  destruct H6. spec H7; auto.\n  rewrite K.knot_level.\n  rewrite K.unsquash_squash; simpl. omega.\n  exists (S n).\n  destruct H7 as [pz [rz ?]].\n  exists pz; exists rz.\n  cut\n    (stepstar t (K.squash (n, psi)) pz r'\n         ((i;; instr_nil K.assert)\n          :: (instr_return;; instr_nil K.assert) :: nil) rz nil\n         /\\ Q x (pz,(rz,t))).\n  intros [? ?]; split; auto.\n  econstructor 2.\n  econstructor.\n  econstructor 2.\n  econstructor; eauto.\n  rewrite get_set_same; auto.\n  hnf; simpl.\n  rewrite K.knot_age1.\n  rewrite K.unsquash_squash.\n  reflexivity.\n  match goal with [ |- stepstar _ ?X _ _ _ _ _ ] =>\n    replace X with (K.squash (n,psi))\n  end.\n  auto.\n  apply K.unsquash_inj.\n  repeat rewrite K.unsquash_squash.\n  f_equal.\n  symmetry.\n  transitivity (KnotInput.fmap (K.approx n oo K.approx (S n)) psi).\n  rewrite <- KnotInput.fmap_comp; auto.\n  change (S n) with (1+n).\n  rewrite <- K.approx_approx1; auto.\n\n  apply stepstar_stepN in H7. destruct H7.\n  eapply end_assert_lemma with (Q:=exist _ (Q x) (HQ x))\n    (stk:=(i;;instr_nil _)::nil). eauto.\nQed.\n\n(* Weaker corallary: a program with a safe entry point\n   will eventually halt.\n *)\nCorollary verify_halts : forall t G psi l,\n  verify_prog t G psi G ->\n  G |-- funptr l unit (fun _ => TT) (fun _ => TT) ->\n  forall r, exists n,\n    eventually_halts t (K.squash (n,psi)) r\n        ((instr_getlabel l (L 0) ;; instr_call (L 0) ;; instr_return ;; instr_nil _)::nil).\nProof.\n  intros.\n  destruct (verify_totally_correct t G unit (fun _ => TT) (fun _ => TT) psi l tt) with (r:=r)\n    as [n [p' [r' [? ?]]]]; auto.\n  exists n. hnf. eauto.\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/funclistmach/hoare_total.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.26893506011160756}}
{"text": "Set Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\nFrom Coq Require Import Strings.String.\nFrom PLF Require Import Maps.\nFrom PLF Require Import Types.\nFrom PLF Require Import Smallstep.\n\nInductive ty : Type :=\n  | Ty_Top : ty\n  | Ty_Bool : ty\n  | Ty_Base : string -> ty\n  | Ty_Arrow : ty -> ty -> ty\n  | Ty_Unit : ty\n  | Ty_Prod : ty -> ty -> ty.\n\nInductive tm : Type :=\n  | tm_var : string -> tm\n  | tm_app : tm -> tm -> tm\n  | tm_abs : string -> ty -> tm -> tm\n  | tm_true : tm\n  | tm_false : tm\n  | tm_if : tm -> tm -> tm -> tm\n  | tm_unit : tm\n  | tm_pair : tm -> tm -> tm\n  | tm_fst : tm -> tm\n  | tm_snd : tm -> tm.\n\nDeclare Custom Entry stlc.\nNotation \"<{ e }>\" := e (e custom stlc at level 99).\nNotation \"( x )\" := x (in custom stlc, x at level 99).\nNotation \"x\" := x (in custom stlc at level 0, x constr at level 0).\nNotation \"S -> T\" := (Ty_Arrow S T) (in custom stlc at level 50, right associativity).\nNotation \"x y\" := (tm_app x y) (in custom stlc at level 1, left associativity).\nNotation \"\\ x : t , y\" :=\n  (tm_abs x t y) (in custom stlc at level 90, x at level 99,\n                     t custom stlc at level 99,\n                     y custom stlc at level 99,\n                     left associativity).\nCoercion tm_var : string >-> tm.\nNotation \"'Bool'\" := Ty_Bool (in custom stlc at level 0).\nNotation \"'if' x 'then' y 'else' z\" :=\n  (tm_if x y z) (in custom stlc at level 89,\n                    x custom stlc at level 99,\n                    y custom stlc at level 99,\n                    z custom stlc at level 99,\n                    left associativity).\nNotation \"'true'\" := true (at level 1).\nNotation \"'true'\" := tm_true (in custom stlc at level 0).\nNotation \"'false'\" := false (at level 1).\nNotation \"'false'\" := tm_false (in custom stlc at level 0).\nNotation \"'Unit'\" :=\n  (Ty_Unit) (in custom stlc at level 0).\nNotation \"'unit'\" := tm_unit (in custom stlc at level 0).\nNotation \"'Base' x\" := (Ty_Base x) (in custom stlc at level 0).\nNotation \"'Top'\" := (Ty_Top) (in custom stlc at level 0).\n\nNotation \"X * Y\" :=\n  (Ty_Prod X Y) (in custom stlc at level 2, X custom stlc, Y custom stlc at level 0).\nNotation \"( x ',' y )\" := (tm_pair x y) (in custom stlc at level 0,\n                                                x custom stlc at level 99,\n                                                y custom stlc at level 99).\nNotation \"t '.fst'\" := (tm_fst t) (in custom stlc at level 0).\nNotation \"t '.snd'\" := (tm_snd t) (in custom stlc at level 0).\n\n\nReserved Notation \"'[' x ':=' s ']' t\" (in custom stlc at level 20, x constr).\nFixpoint subst (x : string) (s : tm) (t : tm) : tm :=\n  match t with\n  | tm_var y =>\n      if eqb_string x y then s else t\n  | <{\\y:T, t1}> =>\n      if eqb_string x y then t else <{\\y:T, [x:=s] t1}>\n  | <{t1 t2}> =>\n      <{([x:=s] t1) ([x:=s] t2)}>\n  | <{true}> =>\n      <{true}>\n  | <{false}> =>\n      <{false}>\n  | <{if t1 then t2 else t3}> =>\n      <{if ([x:=s] t1) then ([x:=s] t2) else ([x:=s] t3)}>\n  | <{unit}> =>\n      <{unit}>\n  | <{ ( l , r ) }> => <{ ( [x:=s]l , [x:=s]r ) }>\n  | <{ t.fst }> => <{ ([x:=s]t).fst }>\n  | <{ t.snd }> => <{ ([x:=s]t).snd }>\n  end\nwhere \"'[' x ':=' s ']' t\" := (subst x s t) (in custom stlc).\n\n\nInductive value : tm -> Prop :=\n  | v_abs : forall x T2 t1,\n      value <{\\x:T2, t1}>\n  | v_true :\n      value <{true}>\n  | v_false :\n      value <{false}>\n  | v_unit :\n      value <{unit}>\n  | v_pair : forall v1 v2,\n      value v1 ->\n      value v2 ->\n      value <{(v1, v2)}>.\n\nHint Constructors value : core.\nReserved Notation \"t '-->' t'\" (at level 40).\nInductive step : tm -> tm -> Prop :=\n  | ST_AppAbs : forall x T2 t1 v2,\n         value v2 ->\n         <{(\\x:T2, t1) v2}> --> <{ [x:=v2]t1 }>\n  | ST_App1 : forall t1 t1' t2,\n         t1 --> t1' ->\n         <{t1 t2}> --> <{t1' t2}>\n  | ST_App2 : forall v1 t2 t2',\n         value v1 ->\n         t2 --> t2' ->\n         <{v1 t2}> --> <{v1 t2'}>\n  | ST_IfTrue : forall t1 t2,\n      <{if true then t1 else t2}> --> t1\n  | ST_IfFalse : forall t1 t2,\n      <{if false then t1 else t2}> --> t2\n  | ST_If : forall t1 t1' t2 t3,\n      t1 --> t1' ->\n      <{if t1 then t2 else t3}> --> <{if t1' then t2 else t3}>\n  | ST_Pair1 : forall t1 t1' t2,\n       t1 --> t1' ->\n       <{ (t1 , t2) }> --> <{ (t1' , t2) }>\n  | ST_Pair2 : forall v1 t2 t2',\n       value v1 ->\n       t2 --> t2' ->\n       <{ (v1 , t2) }> --> <{ (v1 , t2') }>\n  | ST_PairFstStep : forall t t',\n       t --> t' ->\n       <{ t.fst }> --> <{ t'.fst }>\n  | ST_PairFst : forall v1 v2,\n       <{ (v1 , v2).fst }> --> <{ v1 }>\n  | ST_PairSndStep : forall t t',\n       t --> t' ->\n       <{ t.snd }> --> <{ t'.snd }>\n  | ST_PairSnd : forall v1 v2,\n       <{ (v1 , v2).snd }> --> <{ v2 }>\nwhere \"t '-->' t'\" := (step t t').\nHint Constructors step : core.\n\n\nReserved Notation \"T '<:' U\" (at level 40).\nInductive subtype : ty -> ty -> Prop :=\n  | S_Refl : forall T,\n      T <: T\n  | S_Trans : forall S U T,\n      S <: U ->\n      U <: T ->\n      S <: T\n  | S_Top : forall S,\n      S <: <{Top}>\n  | S_Arrow : forall S1 S2 T1 T2,\n      T1 <: S1 ->\n      S2 <: T2 ->\n      <{S1->S2}> <: <{T1->T2}>\n  | S_Pair : forall S1 S2 T1 T2,\n      S1 <: T1 ->\n      S2 <: T2 ->\n      <{S1 * S2}> <: <{T1 * T2}>\nwhere \"T '<:' U\" := (subtype T U).\n\n\nHint Constructors subtype : core.\nModule Examples.\nOpen Scope string_scope.\nNotation x := \"x\".\nNotation y := \"y\".\nNotation z := \"z\".\nNotation A := <{Base \"A\"}>.\nNotation B := <{Base \"B\"}>.\nNotation C := <{Base \"C\"}>.\nNotation String := <{Base \"String\"}>.\nNotation Float := <{Base \"Float\"}>.\nNotation Integer := <{Base \"Integer\"}>.\n\nExample subtyping_example_0 :\n  <{C->Bool}> <: <{C->Top}>.\nProof. auto. Qed.\n\nDefinition Person : ty := <{ (String * Top)}>.\n\nDefinition Student : ty := <{ (String * Float)}>.\n\nDefinition Employee : ty := <{ (String * Integer)}>.\n\nExample sub_student_person :  Student <: Person.\nProof. apply S_Pair. apply S_Refl. apply S_Top. Qed.\n\nExample sub_employee_person :  Employee <: Person.\nProof. apply S_Pair. apply S_Refl. apply S_Top. Qed.\n\nExample subtyping_example_1 :\n  <{Top->Student}> <: <{(C->C)->Person}>.\nProof with eauto.\n  apply S_Arrow...\n  apply sub_student_person. Qed.\n\n\nExample subtyping_example_2 :\n  <{Top->Person}> <: <{Person->Top}>.\nProof with eauto.\n  apply S_Arrow... Qed.\n\nEnd Examples.\n\n\n\nDefinition context := partial_map ty.\nReserved Notation \"Gamma '|-' t '\\in' T\" (at level 40, t custom stlc, T custom stlc at level 0).\nInductive has_type : context -> tm -> ty -> Prop :=\n  (* Same as before: *)\n  (* pure STLC *)\n  | T_Var : forall Gamma x T1,\n      Gamma x = Some T1 ->\n      Gamma |- x \\in T1\n  | T_Abs : forall Gamma x T1 T2 t1,\n      (x |-> T2 ; Gamma) |- t1 \\in T1 ->\n      Gamma |- \\x:T2, t1 \\in (T2 -> T1)\n  | T_App : forall T1 T2 Gamma t1 t2,\n      Gamma |- t1 \\in (T2 -> T1) ->\n      Gamma |- t2 \\in T2 ->\n      Gamma |- t1 t2 \\in T1\n  | T_True : forall Gamma,\n       Gamma |- true \\in Bool\n  | T_False : forall Gamma,\n       Gamma |- false \\in Bool\n  | T_If : forall t1 t2 t3 T1 Gamma,\n       Gamma |- t1 \\in Bool ->\n       Gamma |- t2 \\in T1 ->\n       Gamma |- t3 \\in T1 ->\n       Gamma |- if t1 then t2 else t3 \\in T1\n  | T_Unit : forall Gamma,\n      Gamma |- unit \\in Unit\n  (* New rule of subsumption: *)\n  | T_Sub : forall Gamma t1 T1 T2,\n      Gamma |- t1 \\in T1 ->\n      T1 <: T2 ->\n      Gamma |- t1 \\in T2\n  (* Pair *)\n  | T_Pair : forall Gamma t1 t2 T1 T2,\n      Gamma |- t1 \\in T1 ->\n      Gamma |- t2 \\in T2 ->\n      Gamma |- (t1 , t2) \\in (T1 * T2)\n  | T_PairFst : forall Gamma t T1 T2,\n      Gamma |- t \\in (T1 * T2) ->\n      Gamma |- t.fst \\in T1\n  | T_PairSnd : forall Gamma t T1 T2,\n      Gamma |- t \\in (T1 * T2) ->\n      Gamma |- t.snd \\in T2\nwhere \"Gamma '|-' t '\\in' T\" := (has_type Gamma t T).\nHint Constructors has_type : core.\n\nModule Examples2.\nImport Examples.\n\n\nExample e21: forall A B, empty |- ((\\z:A, z) , (\\z:B, z)) \\in ((A->A) * (B->B)).\nProof. intros A B. eapply (T_Pair empty <{ \\z:A, z }> <{ \\z:B, z }> <{ A->A }> <{ B->B }>).\n  - apply T_Abs. apply T_Var. auto.\n  - apply T_Abs. apply T_Var. auto.\nQed.\n\nExample e22: forall A B, empty |- (\\x:(Top * (B->B)), x.snd) ((\\z:A, z), (\\z:B, z)) \\in (B -> B).\nProof. intros A B.\n  eapply T_App.\n  - apply T_Abs. eapply T_PairSnd. apply T_Var. unfold \"|->\". rewrite t_update_eq. reflexivity.\n  - apply T_Pair.\n    + apply T_Sub with <{ A -> A }>. (* Anything subtype of Top *)\n      * apply T_Abs. apply T_Var. unfold \"|->\". rewrite t_update_eq. reflexivity.\n      * apply S_Top.\n    + apply T_Abs. apply T_Var. unfold \"|->\". rewrite t_update_eq. reflexivity.\nQed.\n\nExample e23: forall A B C, empty |- (\\z:(C->C)->(Top * (B->B)), (z (\\x:C, x)).snd)\n              (\\z:C->C, ((\\z:A, z), (\\z:B, z)))\n         \\in (B->B).\nProof. intros A B C.\n  apply T_App with <{ (C -> C) -> Top * (B -> B) }>.\n  - apply T_Abs. eapply T_PairSnd. eapply T_App. \n    + apply T_Var. unfold \"|->\". rewrite t_update_eq. reflexivity.\n    + apply T_Abs. apply T_Var. unfold \"|->\". rewrite t_update_eq. reflexivity.\n  - apply T_Abs. apply T_Pair.\n    + apply T_Sub with <{ A -> A }>. \n      * apply T_Abs. apply T_Var. unfold \"|->\". rewrite t_update_eq. reflexivity.\n      * apply S_Top.\n    + apply T_Abs. apply T_Var. unfold \"|->\". rewrite t_update_eq. reflexivity.\nQed.\n\nEnd Examples2.\n\n\nLemma sub_inversion_Bool : forall U,\n     U <: <{Bool}> -> U = <{Bool}>.\nProof with auto.\n  intros U Hs.\n  remember <{Bool}> as V.\n  induction Hs; subst; try auto; try (inversion HeqV).\n  - rewrite -> IHHs1; apply IHHs2; reflexivity.\nQed.\n\n\nLemma sub_inversion_arrow : forall U V1 V2,\n     U <: <{ V1 -> V2 }> ->\n     exists U1 U2, U = <{ U1 -> U2 }> /\\ V1 <: U1 /\\ U2 <: V2.\nProof with eauto.\n  intros U V1 V2 Hs.\n  remember <{ V1 -> V2 }> as V.\n  generalize dependent V2. generalize dependent V1.\n  induction Hs; intros V1 V2 Ev; subst; try (inversion Ev).\n  - exists V1, V2. split; try reflexivity. split; apply S_Refl.\n  - destruct (IHHs2 V1 V2) as [ U1 [ U2  [Eu [ Hv1s Hu2s] ] ] ]. reflexivity.\n    subst.\n    destruct (IHHs1 U1 U2) as [ U1' [ U2'  [Eu' [ Hv1s' Hu2s'] ] ] ]. reflexivity.\n    subst.\n    exists U1', U2'.\n    split. reflexivity.\n    split.\n    + apply (S_Trans _ _ _ Hv1s Hv1s').\n    + apply (S_Trans _ _ _ Hu2s' Hu2s).\n  - exists S1, S2.\n    split. reflexivity.\n    split.\n    + rewrite <- H0. assumption.\n    + rewrite <- H1. assumption.\nQed.\n\n\nLemma bool_if_bottom_for_true: forall G T, G |- true \\in T -> <{ Bool }> <: T.\nProof.\n  intros G T H.\n  remember <{ true }> as t eqn:Et.\n  induction H; try (discriminate Et).\n  - constructor.\n  - subst. apply S_Trans with T1.\n    + apply IHhas_type. reflexivity.\n    + assumption.\nQed.\n\nLemma true_isnt_arrow: forall G T1 T2, ~(G |- true \\in (T1 -> T2)).\nProof.\n  intros G T1 T2 H.\n  inversion H; subst.\n  apply bool_if_bottom_for_true in H.\n  apply sub_inversion_arrow in H.\n  destruct H as [U1 [U2 [HT0 [HU1 HU2]]]]. \n  discriminate HT0.\nQed.\n\n\nLemma bool_if_bottom_for_false: forall G T, G |- false \\in T -> <{ Bool }> <: T.\nProof.\n  intros G T H.\n  remember <{ false }> as t eqn:Et.\n  induction H; try (discriminate Et).\n  - constructor.\n  - subst. apply S_Trans with T1.\n    + apply IHhas_type. reflexivity.\n    + assumption.\nQed.\n\nLemma false_isnt_arrow: forall G T1 T2, ~(G |- false \\in (T1 -> T2)).\nProof.\n  intros G T1 T2 H.\n  inversion H; subst.\n  apply bool_if_bottom_for_false in H.\n  apply sub_inversion_arrow in H.\n  destruct H as [U1 [U2 [HT0 [HU1 HU2]]]]. \n  discriminate HT0.\nQed.\n\nLemma unit_is_bottom_for_unit: forall G T, G |- unit \\in T -> <{ Unit }> <: T.\nProof.\n  intros G T H.\n  remember <{ unit }> as t eqn:Et.\n  induction H; try (discriminate Et).\n  - constructor.\n  - subst. apply S_Trans with T1.\n    + apply IHhas_type. reflexivity.\n    + assumption.\nQed.\n\nLemma unit_isnt_arrow: forall G T1 T2, ~(G |- unit \\in (T1 -> T2)).\nProof.\n  intros G T1 T2 H.\n  inversion H; subst.\n  apply unit_is_bottom_for_unit in H.\n  apply sub_inversion_arrow in H.\n  destruct H as [U1 [U2 [HT0 [HU1 HU2]]]]. \n  discriminate HT0.\nQed.\n\n\nLemma pair_is_bottom_for_pair: forall G v1 v2 T, G |- (v1, v2) \\in T -> exists T1 T2, <{ T1 * T2 }> <: T.\nProof.\n  intros G v1 v2 T H.\n  remember <{ (v1, v2) }> as t eqn:Et.\n  induction H; try (discriminate Et).\n  - subst. \n    destruct IHhas_type as [T2' [T3' H']]. reflexivity.\n    exists T2', T3'.\n    apply S_Trans with T1.\n    + apply H'.\n    + assumption.\n  - exists T1, T2. constructor.\nQed.\n\nLemma pair_isnt_arrow: forall G v1 v2 T1 T2, ~(G |- (v1, v2) \\in (T1 -> T2)).\nProof.\n  intros G v1 v2 T1 T2 H.\n  inversion H; subst.\n  apply pair_is_bottom_for_pair in H.\n  destruct H as [T' [T'' H']].\n  apply sub_inversion_arrow in H'.\n  destruct H' as [U1 [U2 [HT0 [HU1 HU2]]]]. \n  discriminate HT0.\nQed.\n\n\nLemma canonical_forms_of_arrow_types : forall Gamma s T1 T2,\n  Gamma |- s \\in (T1 -> T2) ->\n  value s ->\n  exists x S1 s2, s = <{ \\x:S1, s2 }>.\nProof with eauto.\n  intros G s T1 T2 Ht Hv.\n  generalize dependent G.\n  generalize dependent T1.\n  generalize dependent T2.\n  induction Hv. \n  - intros T1 T2' G Ht. exists x, T2, t1. reflexivity.\n  - intros T2 T1 G Ht. exfalso. apply (true_isnt_arrow G T1 T2 Ht).\n  - intros T2 T1 G Ht. exfalso. apply (false_isnt_arrow G T1 T2 Ht).\n  - intros T2 T1 G Ht. exfalso. apply (unit_isnt_arrow G T1 T2 Ht).\n  - intros T2 T1 G Ht. exfalso. apply (pair_isnt_arrow G v1 v2 T1 T2 Ht).\nQed.\n\n\nLemma abs_is_bottom_for_abs: forall G x xT b T, G |- (\\x:xT, b) \\in T -> exists T1 T2, <{ T1 -> T2 }> <: T.\nProof.\n  intros G x xT b T H.\n  remember <{ (\\x:xT, b) }> as f eqn:Ef.\n  induction H; try (discriminate Ef).\n  - subst.\n    injection Ef as Ex Et Eb. subst.\n    exists xT, T1. constructor.\n  - subst.\n    destruct IHhas_type as [T2' [T3' H']]. reflexivity.\n    exists T2', T3'.\n    apply S_Trans with T1.\n    + apply H'.\n    + assumption.\nQed.\n\nLemma typing_inversion_abs : forall Gamma x S1 t2 T,\n     Gamma |- (\\x:S1, t2) \\in T ->\n     exists S2, <{ S1 -> S2 }> <: T  /\\  (x |-> S1 ; Gamma) |- t2 \\in S2.\nProof.\n  intros G x S1 t2 T H.\n  remember <{ (\\x:S1, t2) }> as f eqn:Ef.\n  induction H; try (discriminate Ef).\n  - injection Ef as Ex Et Eb. subst.\n    exists T1. split. \n      constructor.\n      assumption.\n  - subst.\n    destruct IHhas_type as [T2' [T3' H']]. reflexivity.\n    exists T2'.\n    split.\n    * apply S_Trans with T1; assumption.\n    * assumption.\nQed.\n\nLemma sub_inversion_pair : forall U V1 V2,\n     U <: <{ V1 * V2 }> ->\n     exists U1 U2, U = <{ U1 * U2 }> /\\ U1 <: V1 /\\ U2 <: V2.\nProof with eauto.\n  intros U V1 V2 Hs.\n  remember <{ V1 * V2 }> as V.\n  generalize dependent V2. generalize dependent V1.\n  induction Hs; intros V1 V2 Ev; subst; try (inversion Ev).\n  - exists V1, V2. split; try reflexivity. split; apply S_Refl.\n  - destruct (IHHs2 V1 V2) as [ U1 [ U2  [Eu [ Hv1s Hu2s] ] ] ]. reflexivity.\n    subst.\n    destruct (IHHs1 U1 U2) as [ U1' [ U2'  [Eu' [ Hv1s' Hu2s'] ] ] ]. reflexivity.\n    subst.\n    exists U1', U2'.\n    split. reflexivity.\n    split.\n    + apply (S_Trans _ _ _ Hv1s' Hv1s).\n    + apply (S_Trans _ _ _ Hu2s' Hu2s).\n  - exists S1, S2.\n    split. reflexivity.\n    split.\n    + rewrite <- H0. assumption.\n    + rewrite <- H1. assumption.\nQed.\n\n\nLemma canonical_forms_of_pair_types : forall Gamma s T1 T2,\n  Gamma |- s \\in (T1 * T2) ->\n  value s ->\n  exists v1 v2, s = <{ (v1, v2) }>.\nProof with eauto.\n  intros G s T1 T2 Ht Hv.\n  generalize dependent G.\n  generalize dependent T1.\n  generalize dependent T2.\n  induction Hv. \n  - intros T1 T' G Ht. exfalso.\n    apply abs_is_bottom_for_abs in Ht.\n    destruct Ht as [T2' [T3' Ht]].\n    apply sub_inversion_pair in Ht.\n    destruct Ht as [U1' [U2' [Ht [Hu1 Hu2]]]].\n    discriminate Ht.\n  - intros T2 T1 G Ht. exfalso.\n    apply bool_if_bottom_for_true in Ht.\n    apply sub_inversion_pair in Ht.\n    destruct Ht as [U1' [U2' [Ht [Hu1 Hu2]]]].\n    discriminate Ht.\n  - intros T2 T1 G Ht. exfalso.\n    apply bool_if_bottom_for_false in Ht.\n    apply sub_inversion_pair in Ht.\n    destruct Ht as [U1' [U2' [Ht [Hu1 Hu2]]]].\n    discriminate Ht.\n  - intros T2 T1 G Ht. exfalso.\n    apply unit_is_bottom_for_unit in Ht.\n    apply sub_inversion_pair in Ht.\n    destruct Ht as [U1' [U2' [Ht [Hu1 Hu2]]]].\n    discriminate Ht.\n  - intros T2 T1 G Ht. exists v1, v2. reflexivity.\nQed.\n\n\nLemma abs_is_bottom_for_fun: forall G x T2 t1 T, G |- \\ x : T2, t1 \\in T -> exists T1, <{ T2 -> T1 }> <: T.\nProof.\n  intros G x T2 t1 T H.\n  remember <{ (\\x : T2, t1) }> as t eqn:Et.\n  induction H; try (discriminate Et).\n  - injection Et as Et1 Et2 Et3. subst. exists T1. constructor.\n  - subst. \n    destruct IHhas_type as [T3' H']. \n      reflexivity. \n    exists T3'. apply S_Trans with T1.\n    + apply H'.\n    + assumption.\nQed.\n\nLemma typing_inversion_var : forall Gamma (x:string) T,\n  Gamma |- x \\in T ->\n  exists S, Gamma x = Some S /\\ S <: T.\nProof with eauto.\n  intros G x T H.\n  remember (tm_var x) as t eqn:Et.\n  induction H; try (discriminate Et).\n  - exists T1. split.\n    + injection Et as Et. rewrite Et in H. assumption.\n    + constructor.\n  - destruct IHhas_type as [S' [Hl' Hr']]...\nQed.\n\n\nLemma typing_inversion_app : forall Gamma t1 t2 T2,\n  Gamma |- t1 t2 \\in T2 ->\n  exists T1,  Gamma |- t1 \\in (T1 -> T2) /\\ Gamma |- t2 \\in T1.\nProof with eauto.\n  intros G t1 t2 T2 H.\n  remember <{ t1 t2 }> as t eqn:Et.\n  induction H; try (discriminate Et).\n  - exists T2. \n    injection Et as Et1 Et2. subst.\n    split; assumption.\n  - destruct IHhas_type as [t2' [Hl' Hr']]...\nQed.\n\n\nLemma abs_arrow : forall x S1 s2 T1 T2,\n  empty |- (\\x:S1, s2) \\in (T1 -> T2) ->\n     T1 <: S1 /\\ (x |-> S1 ; empty) |- s2 \\in T2.\nProof with eauto.\n  intros x S1 s2 T1 T2 Hty.\n  apply typing_inversion_abs in Hty.\n  destruct Hty as [S2 [Hsub Hty1]].\n  apply sub_inversion_arrow in Hsub.\n  destruct Hsub as [U1 [U2 [Heq [Hsub1 Hsub2]]]].\n  injection Heq as Heq; subst... Qed.\n\n\nLemma canonical_forms_of_Bool : forall Gamma s,\n  Gamma |- s \\in Bool ->\n  value s ->\n  s = tm_true \\/ s = tm_false.\nProof. intros G s H.\n  inversion H; intro Hv; subst; try (inversion Hv; subst).\n  - left. reflexivity.\n  - right. reflexivity.\n  - exfalso. \n    apply abs_is_bottom_for_fun in H.\n    destruct H as [T' H].\n    apply sub_inversion_Bool in H.\n    discriminate H.\n  - left. reflexivity.\n  - right. reflexivity.\n  - exfalso. \n    apply unit_is_bottom_for_unit in H.\n    apply sub_inversion_Bool in H.\n    discriminate H.\n  - exfalso.\n    apply pair_is_bottom_for_pair in H.\n    destruct H as [T1' [T2' H]].\n    apply sub_inversion_Bool in H.\n    discriminate H.\nQed.\n\n\nTheorem progress : forall t T,\n     empty |- t \\in T   ->   value t \\/ (exists t', t --> t').\nProof with eauto.\n  intros t T Ht.\n  remember empty as Gamma.\n  induction Ht; subst Gamma; auto.\n  - (* T_Var *)\n    discriminate.\n  - (* T_App *)\n    right.\n    destruct IHHt1; subst...\n    + (* t1 is a value *)\n      destruct IHHt2; subst...\n      * (* t2 is a value *)\n        eapply canonical_forms_of_arrow_types in Ht1; [|assumption].\n        destruct Ht1 as [x [S1 [s2 H1]]]. subst.\n        exists (<{ [x:=t2]s2 }>)...\n      * (* t2 steps *)\n        destruct H0 as [t2' Hstp]. exists <{ t1 t2' }>...\n    + (* t1 steps *)\n      destruct H as [t1' Hstp]. exists <{ t1' t2 }>...\n  - (* T_Test *)\n    right.\n    destruct IHHt1.\n    + (* t1 is a value *) eauto.\n    + apply canonical_forms_of_Bool in Ht1; [|assumption].\n      destruct Ht1; subst...\n    + destruct H. rename x into t1'. eauto.\n  - (* T_Pair *)\n    destruct IHHt1; subst...\n    + (* t1 is a value *)\n      destruct IHHt2; subst...\n      * (* t2 steps *)\n        destruct H0 as [t2' Hstp]. right. exists <{ (t1 , t2') }>...\n    + (* t1 steps *)\n      destruct H as [t1' Hstp]. right. exists <{ (t1' , t2) }>...\n  - (* T_PairFst *)\n    destruct IHHt...\n    + (* value pair *)\n      destruct (canonical_forms_of_pair_types _ _ _ _ Ht) as [v1 [v2 Ht']]; auto.\n      right. subst. exists v1. constructor.\n    + destruct H as [t' H]. right. exists (tm_fst t')...\n  - (* T_PairSnd *)\n    destruct IHHt...\n    + (* value pair *)\n      destruct (canonical_forms_of_pair_types _ _ _ _ Ht) as [v1 [v2 Ht']]; auto.\n      right. subst. exists v2. constructor.\n    + destruct H as [t' H]. right. exists (tm_snd t')...\nQed.\n\nLemma weakening : forall Gamma Gamma' t T,\n     inclusion Gamma Gamma' ->\n     Gamma |- t \\in T ->\n     Gamma' |- t \\in T.\nProof.\n  intros Gamma Gamma' t T H Ht.\n  generalize dependent Gamma'.\n  induction Ht; eauto using inclusion_update.\nQed.\n\nLemma weakening_empty : forall Gamma t T,\n     empty |- t \\in T ->\n     Gamma |- t \\in T.\nProof.\n  intros Gamma t T.\n  eapply weakening.\n  discriminate.\nQed.\n\nLemma substitution_preserves_typing : forall Gamma x U t v T,\n   (x |-> U ; Gamma) |- t \\in T ->\n   empty |- v \\in U ->\n   Gamma |- [x:=v]t \\in T.\nProof.\nProof.\n  intros Gamma x U t v T Ht Hv.\n  remember (x |-> U; Gamma) as Gamma'.\n  generalize dependent Gamma.\n  induction Ht; intros Gamma' G; simpl; eauto.\n  - destruct (eqb_stringP x x0).\n    + subst. rewrite update_eq in H. injection H as H. subst. \n      apply weakening_empty. assumption.\n    + subst. rewrite update_neq in H. \n        constructor. assumption.\n        assumption.\n  - destruct (eqb_stringP x x0); subst.\n    + constructor.\n      rewrite update_shadow in Ht. \n      assumption.\n    + constructor.\n      apply IHHt.\n      rewrite update_permute.\n        reflexivity.\n        assumption.\nQed.\n\nLemma pair_destr: forall v1 v2 T1 T2, \n  empty |- (v1, v2) \\in (T1 * T2) -> \n  empty |- v1 \\in T1  /\\  empty |- v2 \\in T2.\nProof.\n  intros v1 v2 T1 T2 H.\n  remember <{(v1, v2)}> as p eqn:Ep.\n  remember <{(T1 * T2)}> as t eqn:Et.\n  generalize dependent T1.\n  generalize dependent T2.\n  induction H; try (discriminate Ep); subst.\n  - intros T2' T1' Hv. subst.\n    apply sub_inversion_pair in H0.\n    destruct H0 as [U1 [U2 [H' [Hu1 Hu2]]]]. subst.\n    assert (HG: Gamma |- v1 \\in U1 /\\ Gamma |- v2 \\in U2). {\n      apply IHhas_type.\n        reflexivity.\n        reflexivity.\n    }\n    clear IHhas_type.\n    destruct HG as [Hvu1 Hvu2].\n    split.\n    + eapply T_Sub. apply Hvu1. apply Hu1.\n    + eapply T_Sub. apply Hvu2. apply Hu2.\n  - intros T1' T2' Ets. injection Ets as Ets1 Ets2. subst.\n    injection Ep as tv1 tv2. subst.\n    split.\n      assumption.\n      assumption.\nQed.\n\nTheorem preservation : forall t t' T,\n     empty |- t \\in T ->\n     t --> t' ->\n     empty |- t' \\in T.\nProof with eauto.\n  intros t t' T HT. generalize dependent t'.\n  remember empty as Gamma.\n  induction HT;\n       intros t' HE; subst;\n       try solve [inversion HE; subst; eauto].\n  - (* T_App *)\n    inversion HE; subst...\n    (* Most of the cases are immediate by induction,\n       and eauto takes care of them *)\n    + (* ST_AppAbs *)\n      destruct (abs_arrow _ _ _ _ _ HT1) as [HA1 HA2].\n      apply substitution_preserves_typing with T0...\n  - (* T_PairFst *)\n    inversion HE; subst...\n    apply pair_destr in HT.\n    destruct HT as [Ht1 Ht2].\n    assumption.\n  - (* T_PairSnd *)\n  inversion HE; subst...\n  apply pair_destr in HT.\n  destruct HT as [Ht1 Ht2].\n  assumption.\nQed.\n", "meta": {"author": "cattingcat", "repo": "coq_lessons", "sha": "49ea5727398acddd5b347b234d6b4efcab305422", "save_path": "github-repos/coq/cattingcat-coq_lessons", "path": "github-repos/coq/cattingcat-coq_lessons/coq_lessons-49ea5727398acddd5b347b234d6b4efcab305422/softwarefoundations/vol2_plf/Sub.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.2688524339184419}}
{"text": "Require Import Coq.Reals.Rdefinitions.\nRequire Import Coq.Reals.RIneq.\nRequire Import Coq.micromega.Psatz.\nRequire Import SMTC.Tactic.\nRequire Import Logic.Syntax.\nRequire Import Logic.Semantics.\nRequire Import Logic.Lib.\nRequire Import Logic.ProofRules.\nRequire Import Logic.Automation.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Strings.String.\n\n(* Some useful tactics for our examples. *)\n\nLtac cut_setoid_rewrite_r X :=\n  let xx := fresh \"xx\" in\n  cut X; [ intro xx; rewrite xx; clear xx | ].\n\nLtac cut_setoid_rewrite_l X :=\n  let xx := fresh \"xx\" in\n  cut X; [ intro xx; rewrite <- xx; clear xx | ].\n\nLtac rewrite_rename_equiv F m :=\n  cut_setoid_rewrite_r (F -|- Rename m F);\n  [ | rewrite <- Rename_ok by eauto with rw_rename; reflexivity ].\n\nLtac decompose_hyps :=\n  repeat first [ rewrite Lemmas.land_lor_distr_R\n               | rewrite Lemmas.land_lor_distr_L ] ;\n  repeat apply lorL.\n\nLtac destruct_ite :=\n  match goal with\n  | [ |- context [ if ?e then _ else _ ] ]\n    => destruct e\n  end.\n\nFixpoint get_vars_term (t : Term) : list Var :=\n  match t with\n  | VarNextT t | VarNowT t => t :: nil\n  | NatT _ | RealT _ => nil\n  | PlusT a b | MinusT a b | MultT a b | MaxT a b\n  | Binop _ a b =>\n                             get_vars_term a ++\n                                           get_vars_term b\n  | InvT a | CosT a | SinT a | SqrtT a | ArctanT a\n  | ExpT a | Unop _ a =>\n                                         get_vars_term a\n  end.\n\nDefinition get_image_vars (m:list (Var*Term)) :=\n  List.flat_map (fun p => get_vars_term (snd p)) m.\n\nFixpoint get_witness (m : list (Var*Term)) : state -> state :=\n  match m with\n  | nil => fun st => st\n  | (x,VarNowT y) :: m =>\n    fun st z =>\n      if String.string_dec z y\n      then st x else get_witness m st z\n  | _ => fun st => st\n  end.\n\nFixpoint get_next_vars_term (t : Term) : list Var :=\n  match t with\n  | VarNextT t => t :: nil\n  | VarNowT _ | NatT _ | RealT _ => nil\n  | PlusT a b | MinusT a b | MultT a b | MaxT a b\n  | Binop _ a b =>\n                             get_next_vars_term a ++\n                             get_next_vars_term b\n  | InvT a | CosT a | SinT a | SqrtT a | ArctanT a\n  | ExpT a | Unop _ a => get_next_vars_term a\n  end.\n\nFixpoint get_next_vars_formula (f : Formula) : list Var :=\n  match f with\n  | Always a | Eventually a | Enabled a =>\n                              get_next_vars_formula a\n  | And a b | Or a b | Imp a b =>\n                       get_next_vars_formula a ++\n                       get_next_vars_formula b\n  | Rename _ a => get_next_vars_formula a\n  | Comp l r _ => get_next_vars_term l ++\n                                     get_next_vars_term r\n  | _ => nil\n  end.\n\nFixpoint remove_dup (ls : list Var) : list Var :=\n  match ls with\n  | nil => nil\n  | l :: ls => let ls' := remove_dup ls in\n               if in_dec string_dec l ls'\n               then ls' else l :: ls'\n  end.\n\nLtac enable_ex_st :=\n  match goal with\n  | |- lentails _ (Enabled ?X) =>\n    let vars := eval compute in\n    (remove_dup (get_next_vars_formula X)) in\n        let rec foreach ls :=\n            match ls with\n            | @cons _ ?l ?ls => eapply (ex_state l); simpl;\n                                foreach ls\n            | _ => idtac\n            end\n        in\n        eapply Enabled_action; simpl; intros;\n        foreach vars\n  end; try (eapply ex_state_any; (let st := fresh in\n                                  intro st; clear st)).\n\nLtac enable_ex_st' :=\n  match goal with\n  | |- _ |-- Enabled ?X =>\n        let vars := eval compute in (remove_dup (get_next_vars_formula X)) in\n        let rec foreach ls :=\n         (match ls with\n          | ?l :: ?ls => eapply (ex_state l); simpl; foreach ls\n          | _ => idtac\n          end) in\n        eapply Enabled_action'; [ tlaIntuition | ]; simpl; intros; foreach vars\n  end; try (eapply ex_state_any; (let st := fresh in\n                                  intro st; clear st)).\n\nLtac smart_repeat_eexists :=\n  repeat match goal with\n           |- exists x, _ => eexists\n         end.\n\n(* The old tactic, very slow. *)\n(*\nLtac enable_ex_st :=\n  eapply Enabled_action; intros; eapply ex_state_flow_any;\n  auto; simpl; intros;\n  repeat match goal with\n         | |- context [ ?X ] =>\n           match type of X with\n           | Var => idtac\n           | String.string => idtac\n           end ;\n             try match goal with\n                 | X := _ |- _ => unfold X\n                 end;\n             eapply (@ex_state X) ; simpl ;\n             match goal with\n             | |- exists x (y : _), (@?F x) => fail 1\n             | |- _ => idtac\n             end\n         end;\n  try (eapply ex_state_any ;\n       let st := fresh in intro st ; clear st).\n*)\n\nLemma reason_action : forall P Q,\n    (forall a b tr,\n        eval_formula\n          P\n          (Stream.Cons a\n                       (Stream.Cons b tr)) ->\n        eval_formula\n          Q (Stream.Cons a (Stream.Cons b tr))) ->\n    (P |-- Q).\nProof.\n  red. red. red. intros. destruct tr.\n  destruct tr. auto.\nQed.\n\nLtac reason_action_tac :=\n  eapply reason_action; simpl;\n  let pre := fresh \"pre\" in\n  let post := fresh \"post\" in\n  let tr := fresh \"tr\" in\n  intros pre post tr;\n    breakAbstraction; simpl; unfold eval_comp;\n    simpl; intros.\n\n(* This solves linear real arithmetic goals.\n   It should be complete. *)\nLtac solve_linear :=\n  breakAbstraction; intros; unfold eval_comp in *;\n  simpl in *; intuition; try psatzl R.\n\n(* This tries to solve nonlinear real\n   arithmetic goals. It is not complete\n   and can be incredibly inefficient. *)\nLtac solve_nonlinear :=\n  breakAbstraction; intros; unfold eval_comp in *;\n  simpl in *; intuition; try psatz R.\n\nLtac zero_deriv_tac v :=\n  eapply ContinuousProofRules.zero_deriv\n  with (x:=v); [ charge_tauto | solve_linear | ].\n\nLtac always_imp_tac :=\n  match goal with\n  | [ |- ?H |-- _ ]\n    => match H with\n       | context[ Always ?HH ] =>\n         tlaAssert (Always HH);\n           [ charge_tauto |\n             apply Lemmas.forget_prem; apply Always_imp ]\n       end\n  end.\n\nLtac specialize_arith_hyp H :=\n  repeat match type of H with\n         | ?G -> _ =>\n           let HH := fresh \"H\" in\n           assert G as HH by solve_linear;\n             specialize (H HH); clear HH\n         end.\n\nLtac specialize_arith :=\n  repeat match goal with\n         | [ H : ?G -> _ |- _ ] =>\n           specialize_arith_hyp H\n         end.\n\n(* This simplifies real arithmetic goals.\n   It sometimes is useful to run this before\n   sending things to solve_nonlinear. *)\nLtac R_simplify :=\n  unfold state, Value; field_simplify;\n  unfold Rdiv;\n  repeat rewrite RMicromega.Rinv_1;\n  repeat\n    match goal with\n    | H:_ |- _ =>\n      unfold state, Value in H; field_simplify in H;\n      unfold Rdiv in H;\n      repeat rewrite RMicromega.Rinv_1 in H;\n      revert H\n    end; intros.\n\n(* Doesn't change the goal but runs\n   z3 on real arithmetic goals. At the\n   moment, you have to look in the *coq*\n   buffer for the output. *)\nLtac z3_prepare :=\n  intros.\n\nLtac z3_solve :=\n  z3_prepare; smt solve.\n\nLtac z3_quick :=\n  z3_prepare; smt solve.\n\n(* rewrites the values of variables in the next\n   state into hypothesis and goals. *)\nLtac rewrite_next_st :=\n  repeat match goal with\n           | [ H : eq (Stream.hd (Stream.tl _) _)  _ |- _ ]\n             => rewrite H in *\n         end.\n\n(* Gets rid of arithmetic expressions of the\n   form 0+_, _+0, 0*_, and _*0, _-0, 0-_. *)\nLtac rewrite_real_zeros :=\n  repeat (first\n            [ rewrite Rmult_0_r in *\n            | rewrite Rmult_0_l in *\n            | rewrite Rplus_0_r in *\n            | rewrite Rplus_0_l in *\n            | rewrite Rminus_0_r in *\n            | rewrite Rminus_0_l in * ]).\n\nLtac simpl_Rmax :=\n  repeat first [rewrite Rbasic_fun.Rmax_left in * by solve_linear |\n                rewrite Rbasic_fun.Rmax_right in * by solve_linear ].\n\nLocal Open Scope HP_scope.\n\n(* I'm not sure what the following three\n   tactics do *)\n(*\nLtac find_zeros eqs :=\n  match eqs with\n    | nil => constr:(@nil Var)\n    | cons (DiffEqC ?y (ConstC (NatC O))) ?eqs =>\n      let rest := find_zeros eqs in\n      constr:(cons y rest)\n    | cons _ ?eqs =>\n      let rest := find_zeros eqs in\n      rest\n  end.\n*)\n\n(*\nLtac extract_unchanged eqs :=\n  let xs := find_zeros eqs in\n  let rec aux l :=\n      match l with\n        | nil => idtac\n        | cons ?y ?l => apply zero_deriv\n                        with (cp:=eqs) (x:=y);\n                        try (aux l)\n      end in\n  aux xs.\n*)\n\nLtac get_var_inv F x :=\n  match F with\n    | And ?F1 _ =>\n      get_var_inv F1 x\n    | And _ ?F2 =>\n      get_var_inv F2 x\n    | Comp (next_term x) (next_term ?e) Eq =>\n      constr:(Comp x e Eq)\n  end.\n\n(* Applies differential induction with\n   a known differential invariant *)\nLtac prove_diff_inv known :=\n  match goal with\n      |- context [ Continuous ?eqs ] =>\n      match goal with\n          |- (|-- _ -->> Comp (next_term ?t1)\n                   (next_term ?t2) ?op) =>\n          apply diff_ind with\n          (Hyps:=known) (G:=Comp t1 t2 op) (cp:=eqs)\n      end\n  end.\n\n(* Removes ! from variables in a Term *)\nFixpoint unnext_term (t:Term) : Term :=\n  match t with\n    | VarNowT x => VarNowT x\n    | VarNextT x => VarNowT x\n    | RealT r => RealT r\n    | NatT n => NatT n\n    | PlusT t1 t2 =>\n      PlusT (unnext_term t1) (unnext_term t2)\n    | MinusT t1 t2 =>\n      MinusT (unnext_term t1) (unnext_term t2)\n    | MultT t1 t2 =>\n      MultT (unnext_term t1) (unnext_term t2)\n    | InvT t => InvT (unnext_term t)\n    | CosT t => CosT (unnext_term t)\n    | SinT t => SinT (unnext_term t)\n    | SqrtT t => SqrtT (unnext_term t)\n    | ArctanT t => ArctanT (unnext_term t)\n    | ExpT t => ExpT (unnext_term t)\n    | MaxT t1 t2 => MaxT (unnext_term t1) (unnext_term t2)\n    | Unop f t => Unop f (unnext_term t)\n    | Binop f t1 t2 => Binop f (unnext_term t1)\n                             (unnext_term t2)\n  end.\n\n(* Removes ! from variables in a Formula *)\nFixpoint unnext (F:Formula) : Formula :=\n  match F with\n    | Comp t1 t2 op =>\n      Comp (unnext_term t1) (unnext_term t2) op\n    | And F1 F2 => And (unnext F1) (unnext F2)\n    | Or F1 F2 => Or (unnext F1) (unnext F2)\n    | Imp F1 F2 => Imp (unnext F1) (unnext F2)\n    | Syntax.Exists T f => Syntax.Exists T (fun t => unnext (f t))\n    | Syntax.Forall T f => Syntax.Forall T (fun t => unnext (f t))\n    | _ => F\n  end.\n\n(* Tries to prove (discrete) inductive goals in our examples.\n   Only works for linear arithmetic. Leaves unsolved subgoals\n   unchanged. *)\nLtac prove_inductive :=\n  repeat apply or_next; repeat apply and_right;\n  match goal with\n    | [ |- context [Continuous ?deqs] ] =>\n      match goal with\n(*        | [ |- (|-- _ -->> (?HH -->> ?GG))] =>\n          abstract (apply diff_ind_imp\n                    with (eqs:=deqs) (H:=unnext HH)\n                                     (G:=unnext GG);\n                    solve [reflexivity |\n                           simpl; intuition;\n                           solve_linear])*)\n(*        | [ |- _ ] =>\n          abstract\n            (apply unchanged_continuous with (eqs:=deqs);\n             solve_linear)*)\n        | [ |- (|-- _ -->> ?GG) ] =>\n          abstract (eapply diff_ind\n                    with (cp:=deqs) (G:=unnext GG)\n                                    (Hyps:=TRUE);\n                    try solve [reflexivity |\n                               simpl; intuition;\n                               solve_linear] )\n      end\n    | [ |- _ ] =>\n      try abstract (solve_linear)\n  end.\n\nLtac rewrite_projT2_L s :=\n  let H := fresh in\n  pose proof (projT2 s) as H;\n    cbv beta in H; rewrite <- H; clear H.\n\nLtac rewrite_projT2_R s :=\n  let H := fresh in\n  pose proof (projT2 s) as H;\n    cbv beta in H; rewrite H; clear H.\n", "meta": {"author": "dricketts", "repo": "quadcopter", "sha": "62bb21915612a141e1ffabc73df3dc2d931c54ce", "save_path": "github-repos/coq/dricketts-quadcopter", "path": "github-repos/coq/dricketts-quadcopter/quadcopter-62bb21915612a141e1ffabc73df3dc2d931c54ce/logic/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2688524339184419}}
{"text": "Set Implicit Arguments.\n\nRequire Import fcf.FCF.\nRequire Import fcf.CompFold.\nRequire Import fcf.PRF.\nRequire Import fcf.PRG_NA.\n\nLocal Open Scope list_scope.\nSection HMAC_DRBG_PRG_NA.\n\n(* HMAC-DRBG spec *)\n\n(* The security parameter eta determines the size of PRF keys *)\nVariable eta : nat.\nVariable eta_nz : eta <> O.\n(* The function f models HMAC *)\nVariable f : Bvector eta -> Blist -> Bvector eta.\n\nDefinition RndK : Comp (Bvector eta) := {0,1}^eta.\nDefinition RndV : Comp (Bvector eta) := {0,1}^eta.\nDefinition KV : Set := (Bvector eta * Bvector eta)%type.\n\n(* The Instantiate function *)\n(* NOTE: does not reflect NIST spec *)\nDefinition Instantiate : Comp KV :=\n  k <-$ RndK;\n  v <-$ RndV;\n  ret (k, v).\n\n(* The Generate function *)\nDefinition to_list (A : Type) (n : nat) (v : Vector.t A n) := Vector.to_list v.\n\nFixpoint Gen_loop (k : Bvector eta) (v : Bvector eta) (n : nat)\n  : list (Bvector eta) * Bvector eta :=\n  match n with\n  | O => (nil, v)\n  | S n' =>\n    let v' := f k (to_list v) in\n    let (bits, v'') := Gen_loop k v' n' in\n    (v' :: bits, v'')\n  end.\n\n(* Spec says \"V || 0x00\"; here we will use a list of 8 bits of 0 (a byte) *)\nFixpoint replicate {A} (n : nat) (a : A) : list A :=\n  match n with\n  | O => nil\n  | S n' => a :: replicate n' a\n  end.\n\nDefinition zeroes : list bool := replicate 8 false.\n\nDefinition Generate (state : KV) (n : nat) :\n  Comp (list (Bvector eta) * KV) :=\n  [k, v] <-2 state;\n  [bits, v'] <-2 Gen_loop k v n;\n  k' <- f k (to_list v' ++ zeroes);\n  v'' <- f k' (to_list v');\n  ret (bits, (k', v'')).\n\n\n(* The adversary against the PRG *)\nVariable blocksPerCall : nat.       (* blocks generated by GenLoop *)\nVariable blocksPerCall_gt_0 : blocksPerCall > O.\nVariable numCalls : nat.        (* number of calls to Generate *)\nVariable numCalls_gt_0: numCalls > O.\nDefinition requestList : list nat := replicate numCalls blocksPerCall.\nVariable A : list (list (Bvector eta)) -> Comp bool.\nVariable A_wf : forall ls, well_formed_comp (A ls).\n\n(* The constructed adversary against the PRF *)\nFixpoint oracleCompMap_inner {D R OracleIn OracleOut : Set} \n           (e1 : EqDec ((list R) * (nat * KV))) \n           (e2 : EqDec (list R))\n           (* this is an oracleComp, not an oracle *)\n           (* the oracle has type (D * R) -> D -> Comp (R, (D * R)) *)\n           (oracleComp : (nat * KV) -> D -> OracleComp OracleIn OracleOut (R * (nat * KV))) \n           (state : (nat * KV)) (* note this state type -- it is EXPLICITLY being passed around *)\n           (inputs : list D) : OracleComp OracleIn OracleOut (list R * (nat * KV)) :=\n  match inputs with\n  | nil => $ ret (nil, state)\n  | input :: inputs' => \n    [res, state'] <--$2 oracleComp state input;\n    [resList, state''] <--$2 oracleCompMap_inner _ _ oracleComp state' inputs';\n    $ ret (res :: resList, state'')\n  end.\n\nDefinition oracleCompMap_outer {D R OracleIn OracleOut : Set} \n           (e1 : EqDec ((list R) * (nat * KV))) \n           (e2 : EqDec (list R))\n           (oracleComp : (nat * KV) -> D -> OracleComp OracleIn OracleOut (R * (nat * KV)))\n           (inputs : list D) : OracleComp OracleIn OracleOut (list R) :=\n  [k, v] <--$2 $ Instantiate;   (* generate state inside, instead of being passed state *)\n  [bits, _] <--$2 oracleCompMap_inner _ _ oracleComp (O, (k, v)) inputs;\n  (* the \"_\" here has type (nat * KV) *)\n  $ ret bits.\n\nDefinition Generate_v_PRF_oc (state : KV) (n : nat) :\n  OracleComp (list bool) (Bvector eta) (list (Bvector eta) * KV) :=\n  [k, v] <-2 state;\n  v' <- f k (to_list v);\n  [bits, v''] <-2 Gen_loop k v' n;\n  k' <- f k (to_list v'' ++ zeroes);\n  $ ret (bits, (k', v'')).\n\nFixpoint Gen_loop_oc (v : Bvector eta) (n : nat)\n  : OracleComp (list bool) (Bvector eta) (list (Bvector eta) * Bvector eta) :=\n  match n with\n  | O => $ ret (nil, v)\n  | S n' =>\n    v' <--$ (OC_Query _ (to_list v)); (* ORACLE USE *)\n    [bits, v''] <--$2 Gen_loop_oc v' n';\n    $ ret (v' :: bits, v'')\n  end.\n\nDefinition Generate_v_oc (state : KV) (n : nat) :\n  OracleComp (list bool) (Bvector eta) (list (Bvector eta) * KV) :=\n  [k, v_0] <-2 state;\n  v <--$ (OC_Query _ (to_list v_0)); (* ORACLE USE *)\n  [bits, v'] <--$2 Gen_loop_oc v n;\n  (* TODO what's the state type here? and the global Generate_v_oc return type? *)\n  k' <--$ (OC_Query _ (to_list v' ++ zeroes)); (* ORACLE USE *)\n  $ ret (bits, (k', v')).\n\nDefinition Generate_noV_oc (state : KV) (n : nat) :\n  OracleComp (list bool) (Bvector eta)  (list (Bvector eta) * KV) :=\n  [k, v] <-2 state;\n  [bits, v'] <--$2 Gen_loop_oc v n;\n  (* TODO what's the state type here? and the global Generate_v_oc return type? *)\n  k' <--$ (OC_Query _ (to_list v' ++ zeroes)); (* ORACLE USE *)\n  $ ret (bits, (k', v')).\n\nFixpoint Gen_loop_rb_intermediate (k : Bvector eta) (v : Bvector eta) (n : nat)\n  : Comp (list (Bvector eta) * Bvector eta) :=\n  match n with\n  | O => ret (nil, v)\n  | S n' =>\n    v' <-$ {0,1}^eta;\n    [bits, v''] <-$2 Gen_loop_rb_intermediate k v' n';\n    ret (v' :: bits, v'')\n  end.\n\nDefinition Generate_rb_intermediate_oc (state : KV) (n : nat) \n  : OracleComp (list bool) (Bvector eta) (list (Bvector eta) * KV) :=\n  [k, v] <-2 state;\n  v' <--$ $ {0,1}^eta;\n  [bits, v''] <--$2 $ Gen_loop_rb_intermediate k v' n;    (* promote comp to oraclecomp, then remove from o.c. *)\n  $ ret (bits, (k, v'')).\n\nDefinition Oi_oc' (i : nat) (sn : nat * KV) (n : nat) \n  : OracleComp Blist (Bvector eta) (list (Bvector eta) * (nat * KV)) :=\n  [callsSoFar, state] <-2 sn;\n  let Generate_v_choose :=\n      (* this behavior (applied with f_oracle) needs to match that of choose_Generate's *)\n      if lt_dec callsSoFar i (* callsSoFar < i (override all else) *)\n           then Generate_rb_intermediate_oc (* this implicitly has no v to update *)\n      else if beq_nat callsSoFar O (* use oracle on 1st call w/o updating v *)\n           then Generate_noV_oc \n      else if beq_nat callsSoFar i (* callsSoFar = i *)\n           then Generate_v_oc    (* uses provided oracle (PRF or RF) *)\n      else Generate_v_PRF_oc in        (* uses PRF with (k,v) updating *)\n  [bits, state'] <--$2 Generate_v_choose state n;\n  $ ret (bits, (S callsSoFar, state')).\n\nDefinition PRF_Adversary (i : nat) : OracleComp Blist (Bvector eta) bool :=\n  bits <--$ oracleCompMap_outer _ _ (Oi_oc' i) requestList;\n  $ A bits.\n(* End constructed adversary definition *)\n\nDefinition Pr_collisions := (S blocksPerCall)^2 / 2^eta.\nDefinition PRF_Advantage_Game i : Rat := \n  PRF_Advantage RndK ({0,1}^eta) f _ _ (PRF_Adversary i).\nFixpoint argMax(f : nat -> Rat) (n : nat) :=\n  match n with\n    | O => O\n    | S n' => let p := (argMax f n') in\n              if (le_Rat_dec (f (S n')) (f p)) then p else (S n')\n                                                             end.\n\nDefinition PRF_Advantage_Max := PRF_Advantage_Game (argMax PRF_Advantage_Game numCalls).\nDefinition Gi_Gi_plus_1_bound := PRF_Advantage_Max + Pr_collisions.\n\n(* The desired security property: HMAC_DRBG is a non-adaptive PRG *)\nDefinition HMAC_DRBG_PRG_NA :=\n  PRG_Nonadaptive_Advantage _ _ ({0,1}^eta) Instantiate Generate \n  (ret requestList) A <= (numCalls / 1) * Gi_Gi_plus_1_bound.\n\n(* The proof of this property is imported and applied below *)\nRequire Import HMAC_DRBG_nonadaptive.\n\nTheorem Generate_rb_eq_ideal : \n  forall b x,\n  evalDist (Generate_ideal (Bvector_EqDec eta) ({ 0 , 1 }^ eta) b) x ==\n  evalDist (Generate_rb eta b) x.\n  \n  unfold Generate_rb, Generate_ideal in *.\n  Local Opaque evalDist.\n  induction b; intuition; simpl in *.\n  - fcf_simp.\n    reflexivity.\n\n  - fcf_inline_first.\n    fcf_skip.\n    fcf_inline_first.\n    fcf_skip.\n    rewrite IHb.\n    rewrite evalDist_right_ident.\n    reflexivity.\n    rewrite evalDist_right_ident.\n    reflexivity.\nQed.\n\nTheorem PRG_Advantage_eq : \n  PRG_Nonadaptive_Advantage _ _ ({0,1}^eta) HMAC_DRBG_PRG_NA.Instantiate HMAC_DRBG_PRG_NA.Generate \n  (ret HMAC_DRBG_PRG_NA.requestList) A == \n  | Pr [G_real f _ A blocksPerCall numCalls ] -\n       Pr [G_ideal A blocksPerCall numCalls ] |.\n\n  unfold PRG_Nonadaptive_Advantage.\n  apply ratDistance_eqRat_compat.\n  - unfold PRG_G1, G_real.\n    fcf_skip.\n    reflexivity.\n    fcf_simp.\n    reflexivity.\n\n  - unfold PRG_G2, G_ideal.\n    fcf_simp.\n    fcf_skip.\n    eapply compMap_eq; intuition.\n    apply list_pred_eq.\n    subst.\n    apply Generate_rb_eq_ideal.\nQed.\n\nTheorem HMAC_DRBG_PRG_NA_true : HMAC_DRBG_PRG_NA.\n\n  unfold HMAC_DRBG_PRG_NA, PRG_Nonadaptive_Advantage.\n  eapply leRat_trans.\n  apply eqRat_impl_leRat.\n  apply PRG_Advantage_eq.\n  apply G1_G2_close; intuition.\n\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/fcf/HMAC_DRBG_nonadaptive_result.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6723316991792861, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2688060397702447}}
{"text": "Require Import ssreflect.\nFrom mathcomp Require Import ssrnat zify.\nRequire Import BinNums.\n\nRequire Import UMLang.UrsusLib.\nRequire Import UrsusTVM.Cpp.tvmTypes.\nRequire Import UrsusTVM.Cpp.tvmFunc.\nRequire Import UrsusTVM.Cpp.tvmNotations.\nRequire Import FinProof.Common.\nRequire Import FinProof.CommonInstances.\nRequire Import FinProof.EpsilonMonad.\nRequire Import FinProof.StateMonad21.\nRequire Import FinProof.ProgrammingWith. \nRequire Import FinProof.MonadTransformers21. \nRequire Import FinProof.StateMonad21Instances.\nRequire Import UMLang.UrsusLib.\nRequire Import UrsusStdLib.Cpp.stdNotations.\nRequire Import UrsusStdLib.Cpp.stdFuncNotations.\nRequire Import UMLang.UrsusLib.\n\nRequire Import UrsusStdLib.Cpp.stdTypes.\nRequire Import UrsusStdLib.Cpp.stdNotations.\nRequire Import UrsusStdLib.Cpp.stdFuncNotations.\nRequire Import KWproject.Contracts.ProofsCommon.\n\nRequire Import SuperLedger GenTree.\n\nRequire Import List.\n\nRequire Import FinProof.Lib.BoolEq.\nRequire Import FinProof.Lib.GenTree.\n\nImport ListNotations.\n\nImport UrsusNotations.\nLocal Open Scope ursus_scope.\nLocal Open Scope ucpp_scope.\n(* Local Open Scope xlist_scope. *)\n\nSet Typeclasses Depth 100.\n\n\nSet Implicit Arguments.\n\nSection MessageTree.\n\nNotation LedgerClassT lT := \n  (LedgerClass \n    XBool\n    (Ledger                  lT)\n    (LedgerMainState         lT)\n    (LedgerLocalState        lT)\n    VMStateLRecord\n    (LedgerMessagesAndEvents lT)\n    GlobalParamsLRecord\n    OutgoingMessageParamsLRecord).\n\nContext (Interfaces Contracts : Type).\nContext `{ContractsUtils Interfaces Contracts}.\n\nNotation nodeType         := (@nodeType         Interfaces Contracts).\nNotation superLedger      := (@superLedger      Interfaces Contracts).\nNotation externalNodeType := (@externalNodeType Interfaces Contracts).\n\nDefinition messageTree := Tree nodeType.\n\nImplicit Type t : messageTree.\n\nRecord state := {\n  MessagesQueue : list nodeType;\n  SuperLedger   : superLedger;\n  RunOutOfFuel  : bool;\n}.\n\n(*  *)\n(* Notation StateT := (simpleState superLedger). *)\n\nCheck MonadState.\n\nContext (StateTG : Type -> Type -> Type).\nContext `{Mo : forall S, Monad (StateTG S)} `{forall S, @MonadState (StateTG S) S (Mo S)}.\n\nNotation StateT' := (StateTG state).\nNotation StateT  := (StateTG superLedger).\n\nDefinition putMessageQueue (n : list nodeType) : state -> state := \n  fun '(Build_state ms sl r) => Build_state n sl r.\n\nDefinition putSuperLedger (s : superLedger) : state -> state := \n  fun '(Build_state ms sl r) => Build_state ms s r.\n\nDefinition runOut : state -> state := \n  fun '(Build_state ms sl r) => Build_state ms sl true.\n\nLocal Obligation Tactic := idtac.\n\nLocal Open Scope bool_scope.\n\nContext `{nodeEqType: eqb_spec nodeType}.\n\nFixpoint takeheads {T} (l : list (list T)) := \n  match l with \n  | (h :: t) :: ls => h :: takeheads ls\n  | [ ] :: ls => takeheads ls\n  | [ ] => [ ]\n  end.\n\nFixpoint checkRoots (R : nodeType -> nodeType -> Prop) ts qss: Prop := \n  match ts, qss with \n  | [ ]    , [ ]             => True\n  | t :: ts, (q :: _) :: qss => R (Tree.root t) q /\\ checkRoots R ts qss\n  | _      , _               => False\n  end.\n\n#[global, program] \nInstance XBoolEquableList {T} `{XBoolEquable bool T} : XBoolEquable bool (list T).\nNext Obligation.\nintros ??.\nrefine (fix foo (l1 l2 : list _) :=\n  match l1, l2 with \n  | h1 :: t1, h2 :: t2 => eqb h1 h2 && foo t1 t2\n  | nil     , nil      => true\n  | _       , _        => false\n  end).\nDefined.\n\nFixpoint checkTreeT (mt : messageTree) (qss : list (list nodeType)) :\n  StateT bool :=\n  let fix Checks mts qss : StateT bool := \n    match mts, qss with \n    | [ ]    , [ ]               => $true\n    | t :: ts, (q :: qs) :: qss  =>\n      do sl ← get;\n      let sl'  := sl_of  (InterpretNode (Tree.root t) sl) in\n      let tss  := tss_of (InterpretNode (Tree.root t) sl) in\n      let err  := errTp_of (InterpretNode (Tree.root t) sl) in\n      let qss' := if qs is nil then tss else qs :: tss    in\n      (put sl' >>\n      do b  ← checkTreeT t qss';\n      do bs ← Checks ts qss;\n      $ (eqb (Tree.root t) (putError q err) && b && bs))\n    | _      , _                 => $ false\n    end in\n  Checks (Tree.nodes mt) qss.\n\nFixpoint checkTreesT mts qss : StateT bool := \n  match mts, qss with \n  | [ ]    , [ ]               => $true\n  | t :: ts, (q :: qs) :: qss  =>\n    do sl ← get;\n    let sl'  := sl_of  (InterpretNode (Tree.root t) sl) in\n    let tss  := tss_of (InterpretNode (Tree.root t) sl) in\n    let err  := errTp_of (InterpretNode (Tree.root t) sl) in\n    let qss' := if qs is nil then tss else qs :: tss    in\n   (put sl' >>\n    do b  ← checkTreeT t qss';\n    do bs ← checkTreesT ts qss;\n    $ (eqb (Tree.root t) (putError q err) && b && bs))\n  | _      , _                 => $ false\n  end.\n\nLemma checkTreeE (n : nodeType)  : \n  (forall t q qs qss ts, checkTreeT (Node n (t :: ts)) ((q :: qs) :: qss) = \n    do sl ← get;\n    let sl'  := sl_of  (InterpretNode (Tree.root t) sl) in\n    let tss  := tss_of (InterpretNode (Tree.root t) sl) in\n    let err  := errTp_of (InterpretNode (Tree.root t) sl) in\n    let qss' := if qs is nil then tss else qs :: tss    in\n    (put sl' >>\n    do b  ← checkTreeT t qss';\n    do bs ← checkTreeT (Node n ts) qss ;\n    $ (eqb (Tree.root t) (putError q err) && b && bs))) *\n  (checkTreeT (Node n nil) nil = $true).\nProof. by [ ].  Qed.\n\nLemma checkTreeE2 (n : nodeType) ts qss : \n  checkTreeT (Node n ts) qss = checkTreesT ts qss.\nProof. by [ ]. Qed.\n\nFixpoint checkForestT (l : list messageTree) : (StateT bool) :=\n  match l with\n  | [ ]     => $ true\n  | t :: ts => \n    modify (setTime (getTime (Tree.root t))) >>\n    do sl ← get;\n    let: mk_IN sl' qss err := InterpretNode (Tree.root t) sl in\n    put sl' >>\n    do b  ← checkTreeT   t qss;\n    do bs ← checkForestT ts;\n    $ (b && bs && eqb (getError (Tree.root t)) err)\n  end.\n\nLemma checkForestE t ts :\n  checkForestT (t :: ts) =\n    modify (setTime (getTime (Tree.root t))) >>\n    do sl ← get;\n    let: mk_IN sl' qss err := InterpretNode (Tree.root t) sl in\n    put sl' >>\n    do b  ← checkTreeT   t qss;\n    do bs ← checkForestT ts;\n    $ (b && bs && eqb (getError (Tree.root t)) err).\nProof. by [ ]. Qed.\n\nDefinition mapNode (l : list externalNodeType) : list nodeType := map inl l.\n\nDefinition checkForest (l : list messageTree) (ems : list externalNodeType) (sl : superLedger) := \n  eval_state (checkForestT l) sl && \n  eqb \n    (map (fun t => putError (Tree.root t) (Build_errorType None false)) l) \n    (map (fun m => putError m (Build_errorType None false)) (mapNode ems)).\n\nDefinition execForest (l : list messageTree) (sl : superLedger) := \n  exec_state (checkForestT l) sl.\n\n#[global] Arguments checkTreeT : simpl never.\n\n\nLemma checkTreesE t ts q qs qss: \n  checkTreesT (t :: ts) ((q :: qs) :: qss) = \n  do sl ← get;\n  let sl'  := sl_of  (InterpretNode (Tree.root t) sl) in\n  let tss  := tss_of (InterpretNode (Tree.root t) sl) in\n  let err  := errTp_of (InterpretNode (Tree.root t) sl) in\n  let qss' := if qs is nil then tss else qs :: tss    in\n  (put sl' >>\n  do b  ← checkTreeT t qss';\n  do bs ← checkTreesT ts qss;\n  $ (eqb (Tree.root t) (putError q err) && b && bs)).\nProof. by [ ]. Qed.\n\n(* \n  1) addrR parent = addrS children +\n  2) все кроме root -- internalNodeType +\n  3) bounce onBounce = false\n  4) messge queue is empty for intermediate ledgers +\n  .) balance = const \n  .) add new field option ErrorType +\n  .) if ↑ = Some error ==> exists message onBounce somewhere (come up with spec) \n  \n  \n  1) InterpretNode n sl = (sl', qss) -> \n  Forall (Forall (fun n' => addrS_of n' = addrR_of n)) qss.\n  2) InterpretNode n sl = (sl', qss) -> \n  sum_balance sl = sum_balance sl'.\n  3) InterpretNode n sl = (sl', qss) -> \n  Forall (Forall (fun n' => isOnBoune n' -> bouncce n' = false))) qss.\n *)\n\nFixpoint Builds (Build : nodeType -> StateT' messageTree) \n  (nss : list (list nodeType)) : StateT' (list messageTree) :=\n  match nss with\n  | (n :: ns) :: nss => \n    modify (putMessageQueue ns) >>\n    do mt  ← Build n;\n    do mts ← Builds Build nss;\n    $ (mt :: mts)\n  | _ :: nss => modify runOut >> $ nil\n  | _        => $ nil\n  end.\n\nFixpoint Build (fuel : nat) (n : nodeType) : StateT' messageTree :=\n  if fuel is S fuel then\n    do sl ← embed_fun SuperLedger;\n    do ms ← embed_fun MessagesQueue;\n    let Int := (InterpretNode n sl)                  in\n    let sl' := sl_of  Int                            in\n    let nss := tss_of Int                            in\n    let err := errTp_of Int                          in\n    let qss' := if ms is nil then nss else ms :: nss in\n    modify (putSuperLedger sl') >> \n    if qss' is nil then $ (Node (putError n err) nil) else\n    do mts ← Builds (Build fuel) qss';\n    $ (Node (putError n err) mts)\n  else modify runOut >> $ (Node n nil).\n\nFixpoint buildForestT fuel (l : list nodeType) : (StateT' (list messageTree)) :=\n  match l with\n  | [ ] => $ [ ]\n  | n :: tln => modify (fun '(Build_state ms sl r) => Build_state ms (setTime (getTime n) sl) r) >>\n                do tree ← Build fuel n;\n                do forest ← buildForestT (fuel - 1) tln;\n                $ (tree :: forest)\n  end.\n\nDefinition buildForest fuel (l : list externalNodeType) (sl : superLedger) := \n  eval_state (buildForestT fuel (mapNode l)) (Build_state nil sl false).\n\nDefinition buildSLedger fuel (l : list externalNodeType) (sl : superLedger) := \n  SuperLedger (exec_state (buildForestT fuel (mapNode l)) (Build_state nil sl false)).\n\nDefinition buildFinished fuel (l : list externalNodeType) (sl : superLedger) := \n  negb (RunOutOfFuel (exec_state (buildForestT fuel (mapNode l)) (Build_state nil sl false))).\n\n(* Context `{nodeEqType : eqb_spec nodeType}. *)\n\nArguments run : simpl never.\n\n\nLemma runmodify {M : Type -> Type} {S : Type} `{Monad M}\n  {MonadState : MonadState S} (f : S -> S) \n  (s : S) : run (modify f) s = (f s, f s)%xprod.\nProof. by rewrite /modify runbind runget /Basics.compose runput. Qed.\n\nLemma runmodifybind {M : Type -> Type} {S : Type} `{Monad M}\n  {MonadState : MonadState S} (f : S -> S) X (m : M X)\n  (s : S) : run (modify f >> m) s = run m (f s).\nProof. \n  rewrite runbind'.\n  case E: (run _); rewrite runmodify in E.\n  by case: E=>?->. \nQed.\n\nLemma runputbind {M : Type -> Type} {S : Type} `{Monad M}\n  {MonadState : MonadState S} (f : S) X (m : M X)\n  (s : S) : run (put f >> m) s = run m f.\nProof. \n  rewrite runbind'.\n  case E: (run _); rewrite runput in E.\n  by case: E=>?->. \nQed.\n\nFrom mathcomp Require Import ssreflect ssrbool zify.\n\nInductive run_chekTree_spec tr que stat stat' : Prop := \n  | Run_step t sl' tss st  q qs qss qss' sl ts x err\n    (trE   : tr   = Node x (t :: ts))\n    (queE  : que = (q :: qs) :: qss) \n    (statE : stat = sl)\n    (tE    : Tree.root t = putError q err)\n    (INt   : InterpretNode (Tree.root t) sl = mk_IN sl' tss err)\n    (qss'E : qss' = if qs is nil then tss else qs :: tss)\n    (runE1 : run (checkTreeT t qss') sl' = (true, st)%xprod)\n    (runE2 : run (checkTreeT (Node x ts) qss) st = (true, stat')%xprod)\n    (runE3 : \n      run \n        (checkTreeT (Node x (t :: ts)) ((q :: qs) :: qss)) \n        sl = \n        (true, stat')%xprod)  :\n      run_chekTree_spec tr que stat stat'\n  | Run_empty x sl\n    (runE : run (checkTreeT (Node x nil) nil) sl = \n      (true, sl)%xprod)\n    (trE    : tr    = Node x nil)\n    (queE   : que   = nil)\n    (statE  : stat  = sl)\n    (stat'E : stat' = sl) : \n      run_chekTree_spec tr que stat stat' .\n\nArguments eqb : simpl never. \n\nLemma run_checkTreeE x ts sl qss :  \n  run (checkTreeT (Node x ts) qss) sl = \n  match ts, qss with \n  | t :: ts, (q :: qs) :: qss =>\n    let: mk_IN sl' tss err      := InterpretNode (Tree.root t) sl in\n    let: (b , st)%xprod  := run \n      (checkTreeT t (if qs is nil then tss else qs :: tss))\n      sl' in \n    let: (b', st')%xprod := run (checkTreeT (Node x ts) qss) st in\n      (eqb (Tree.root t) (putError q err) && b && b', st')%xprod\n  | [ ]    , [ ]              => (true, sl)%xprod\n  | _      , _                => (false, sl)%xprod\n  end.\nProof. \ncase: ts qss=> [|t ts] [|[>|q qs qss] ].\n{ by rewrite checkTreeE rununit. }\n1-4: by rewrite /checkTreeT /= rununit.\nrewrite checkTreeE runbind runget /SuperLedger.\nrewrite runputbind /putSuperLedger.\ndestruct (InterpretNode (Tree.root t) sl) as [sl' tss err] eqn:E.\nset qss' := match qs with\n            | [ ] => snd (fst (sl', tss, err))\n            | _ :: _ => qs :: snd (fst (sl', tss, err))\n            end.\nrewrite runbind /fst.\ndestruct (run (checkTreeT t qss') _) as [b st] eqn:E1.\nrewrite runbind.\ndestruct (run (checkTreeT (Node x ts) qss) _) as [b1 st'] eqn:E2.\nby rewrite rununit.\nQed.\n\n(* Arguments Builds : simpl never. *)\n\nLemma run_BuildE n fuel ms sl r:\n  run (Build fuel n) (Build_state ms sl r) = \n  if fuel is fuel.+1 then \n    let: mk_IN sl' tss err := InterpretNode n sl in\n    let: qss               := if ms is nil then tss else ms :: tss in\n      match qss with \n      | nil      => ([putError n err | [ ] ], (Build_state ms sl' r))%xprod\n      | nil :: _ => ([putError n err | [ ] ], (Build_state ms sl' true))%xprod\n      | ((q :: qs) :: qss) =>\n        let: (trh, st)%xprod := \n          run (Build fuel q) (Build_state qs sl' r) in \n        let: (trt, st')%xprod :=\n          run (Builds (Build fuel) qss) st in \n          ([putError n err | trh :: trt], st')%xprod \n      end\n  else ([n | [ ] ], (Build_state ms sl true))%xprod.\nProof.\ncase: fuel=> [|fuel].\n{ by rewrite /= @runmodifybind rununit. }\ndo ? rewrite /= runbind runembed /=.\ncase E: (InterpretNode n sl)=> [sl' tss err] /=.\nset qss := if ms is nil then tss else ms :: tss.\ncase: qss=> [|[|q qs] qss].\n{ by rewrite runmodifybind rununit. }\n{ by rewrite runmodifybind /= runbind /Builds runmodifybind ?rununit. }\nrewrite runmodifybind /= runbind runmodifybind runbind.\ncase: (run _ _)=> [trh st].\nrewrite runbind.\ncase: (run _ _)=> [trt st'].\nby rewrite ?rununit.\nQed.\n\nArguments Builds : simpl nomatch.\n\nLemma run_BuildsE Build st nss:\n  run (Builds Build nss) st = \n  match nss with\n  | (n :: ns) :: nss => \n    let: (trh, st1)%xprod :=\n      run (Build n) (putMessageQueue ns st) in \n    let: (trt, st2)%xprod := \n      run (Builds (Build) nss) st1 in \n      (trh :: trt, st2)%xprod\n  | _ :: nss => (nil, runOut st)%xprod\n  | _        => (nil, st)%xprod\n  end.\nProof.\ncase: nss=> [|[|]>].\n1-2: by rewrite /= ?runmodifybind rununit.\nrewrite /= runbind runmodify runbind.\ncase: (run _ _)=>>.\nrewrite runbind.\ncase: (run _ _)=>>.\nby rewrite rununit.\nQed.\n\nInductive run_Build_spec n ms1 sl1 ms2 sl2 t : nat -> list (list nodeType) -> Prop := \n  | Runb_step err tss sl sl' q qs qss fuel trh trt ms'\n    (INt   : InterpretNode n sl1 = mk_IN sl tss err)\n    (qssE  : (q :: qs) :: qss = if ms1 is nil then tss else ms1 :: tss)\n    (runE1 : \n      run (Build fuel q) (Build_state qs sl false) = \n      (trh, Build_state ms' sl' false)%xprod)\n    (runE2 : \n      run (Builds (Build fuel) qss) (Build_state ms' sl' false) = \n      (trt, Build_state ms2 sl2 false)%xprod)\n    (runE4 : \n      run (Build fuel.+1 n) (Build_state ms1 sl1 false) = \n      ([putError n err | trh :: trt], Build_state ms2 sl2 false)%xprod)\n    (tE : [putError n err | trh :: trt] = t)\n    (* (nE : n = putError n err) *)\n      : run_Build_spec n ms1 sl1 ms2 sl2 t (fuel.+1) ((q :: qs) :: qss)\n  | Runb_empty err tss sl fuel\n    (INt  : InterpretNode n sl1 = mk_IN sl tss err)\n    (qssE : nil = if ms1 is nil then tss else ms1 :: tss)\n    (runE : run (Build fuel.+1 n) (Build_state ms1 sl1 false) = \n      ([putError n err | [ ] ], (Build_state ms1 sl false))%xprod)\n    (* (nE   : t = putError n err) *)\n    (msE  : ms1 = ms2)\n    (sl2E : sl2 = sl)\n    (tE : [putError n err | [ ] ] = t)\n      : run_Build_spec n ms1 sl1 ms2 sl2 t (fuel.+1) nil.\n\nLemma Build_RunOutOfFuel_aux ts nss n t sl sl' ms ms' fuel r: \n  (run (Build fuel n) (Build_state ms sl r) = (t, (Build_state ms' sl' false))%xprod ->\n  r = false) * \n  (run (Builds (Build fuel) nss) (Build_state ms sl r) = (ts, (Build_state ms' sl' false))%xprod ->\n  r = false).\nProof.\nelim: fuel nss n t sl sl' ms ms' r ts. \n{ move=> nss ? ? sl sl' ms ms' r ts; rewrite run_BuildE; split=> //.\n  elim: nss sl sl' r ms ms' ts=> [>|[|n ns] ? IHnss >]; rewrite run_BuildsE //.\n  { by case. }\n  case E1: (run _ _)=> [t1 st1].\n  case E2: (run _ _)=> [t2 [ ] ]; move: E2.\n  rewrite run_BuildE in E1.\n  move=> /[swap]=> -[???->].\n  by case: E1=> ? <- /IHnss. }\nmove=> fuel IHfuel.\nhave HB: forall n t sl sl' ms ms' r,\n  run (Build fuel.+1 n) (Build_state ms sl r) = (t, Build_state ms' sl' false)%xprod ->\n  r = false.\n{ move=> n t sl sl' ms ms' r.\n  rewrite run_BuildE.\n  case: (InterpretNode _ _)=> [? tss ?].\n  set (qss := if ms is nil then tss else ms :: tss).\n  case E: qss=> [|[|q qs] qss']=> //.\n  { by case. }\n  case E1: (run _ _)=> [t1 [ ] ].\n  case E2: (run _ _)=> [t2 [ ] ]; move: E2.\n  move=> /[swap] -[???->].\n  edestruct IHfuel as [_ IH2].\n  move: E1=> /[swap] /IH2 ->.\n  edestruct IHfuel as [IH1 _].\n  by move/IH1. }\nmove=> nss n t sl sl' ms ms' r ts; split.\n{ exact/HB. }\nelim: nss ms ms' sl sl' r ts=> [>|[|n' ns] nss IHnss >]; rewrite run_BuildsE //.\n{ by case. }\ncase E1: (run _ _)=> [t1 [ ] ].\ncase E2: (run _ _)=> [t2 [ ] ]; move: E2.\nmove=> /[swap] -[???->] /IHnss.\nby move: E1=> /[swap]-> /HB.\nUnshelve. all: done.\nQed.\n\nLemma Build_RunOutOfFuel n t sl sl' ms ms' fuel r: \n  run (Build fuel n) (Build_state ms sl r) = (t, (Build_state ms' sl' false))%xprod ->\n  r = false.\nProof.\nedestruct Build_RunOutOfFuel_aux as [IH1]; exact/IH1.\nUnshelve. all: exact/nil.\nQed.\n\nLemma Builds_RunOutOfFuel (n : nodeType) nss ts t sl sl' ms ms' fuel r: \n  run (Builds (Build fuel) nss) (Build_state ms sl r) = (ts, (Build_state ms' sl' false))%xprod ->\n  r = false.\nProof.\nedestruct Build_RunOutOfFuel_aux as [_ IH1]; exact/IH1.\nUnshelve. \n{ exact/n. }\nexact/[n | nil].\nQed.\n\n\nLemma run_BuildP n t sl sl' ms ms' fuel :\n  run (Build fuel n) (Build_state ms sl false) = (t, (Build_state ms' sl' false))%xprod ->\n  let: mk_IN _ tss _ := InterpretNode n sl in \n  run_Build_spec n ms sl ms' sl' t fuel (if ms is nil then tss else ms :: tss).\nProof.\nmove=> /[dup] rE.\nrewrite run_BuildE.\ncase E1: (InterpretNode _ _) => [s tss err].\ncase E2: fuel=> //.\nset qss := (if ms is nil then tss else ms :: tss).\ncase E3: qss=> [|[|q qs] qss']=> // [ [<-<-<-]|].\n{ econstructor=> //.\n  { exact/E1. }\n  { exact/eq_sym/E3. }\n  by rewrite -E2 run_BuildE /= E1 -/qss E3 E2. }\ncase E4: (run _ _)=> [trh [ ] ].\ncase E5: (run _ _)=> [trt st2].\ncase=> /[dup] tE <- st2E.\neconstructor=> //.\n{ exact/E1. }\n{ exact/eq_sym/E3. }\n{ move: st2E E5 E4=> {1}-> /Builds_RunOutOfFuel-/(_ n t)->; exact. }\n{ move: st2E E5 (E5)=> {1 2}-> /Builds_RunOutOfFuel-/(_ n t)->; exact. }\nby rewrite -E2 rE tE.\nQed.\n\nLemma run_checkTreeP x ts qss sl sl' :  \n    (run_chekTree_spec (Node x ts) qss sl sl') <->\n    (run (checkTreeT (Node x ts) qss) sl = (true, sl')%xprod).\nProof.\n  split.\n  { case=> [>[->->->->qE]*|?>? [->->->->->] ] //. }\n  case: ts qss=> [|t ts] [|[>|q qs qss] ].\n  2-5: by rewrite /checkTreeT /= rununit.\n  { rewrite /checkTreeT /= rununit=> -[->]. \n    apply/(@Run_empty _ _ _ _ x sl')=> //.\n    by rewrite /checkTreeT /= rununit. }\n  move=> /[dup] r.\n  rewrite run_checkTreeE.\n  destruct (InterpretNode (Tree.root t) sl) as [sl'' tss err] eqn:E.\n  set qss' := match qs with\n              | [ ] => snd (sl'', tss)\n              | _ :: _ => qs :: snd (sl'', tss)\n              end.\n  destruct (run (checkTreeT t qss') _) as [b st] eqn:E1.\n  destruct (run (checkTreeT (Node x ts) qss) st) as [b1 ?] eqn:E2.\n  move=> -[/andP ] [/andP ] [/eqb_spec_reflect] tE bE b1E sE.\n  rewrite bE in E1; rewrite b1E sE in E2.\n  exact/(Run_step _ _ _ _ E (eq_refl qss') E1 E2).\nQed.\n\n\nLemma eval_state_checkTreeP x ts qss st :\n  reflect \n    (run_chekTree_spec (Node x ts) qss st (xsnd (run (checkTreeT (Node x ts) qss) st)))\n    (eval_state (checkTreeT (Node x ts) qss) st).\nProof.\n  apply: (iffP idP); rewrite /eval_state.\n  { move=> RE; apply/run_checkTreeP; move: RE.\n    by case: (run _ _)=> /= ??->. }\n  by move/run_checkTreeP=>->.\nQed.\n\nLemma putError_internal q err : isInternal q = true -> isInternal (putError q err).\nProof.\n  intros.\n  unfold putError;\n  destruct q.\n  destruct e.\n  { simpl in H1; auto. }\n  destruct i; simpl in *; auto.\nQed. \n\nLemma checkTree_intrenalN (t : messageTree) (qss : list (list nodeType)) sl : \n  Forall (Forall (fun n => isInternal n = true)) qss ->\n  eval_state (checkTreeT t qss) sl = true -> \n  Forall (Tree.Forall (fun n => isInternal n = true)) (Tree.nodes t).\nProof.\n  revert qss sl.\n  induction t as [|t ts].\n  { intros; constructor. }\n  intros qss sl qsI; simpl.\n  move=> /eval_state_checkTreeP runC.\n  destruct runC; subst; try done.\n  injection (eq_sym trE); intros; subst.\n  destruct t as [n ts'].\n  do ? constructor.\n  { inversion qsI as [|?? X]; inversion X as [|?? Y].\n    apply putError_internal with (err:=err) in Y;\n    by rewrite <- tE in Y. }\n  { apply (f_equal xfst) in runE1.\n    eapply (IHt _ _ _ runE1); auto.\n    Unshelve.\n    apply IN_internal in INt.\n    inversion qsI as [|?? X]; inversion X.\n    by destruct qs; auto; constructor. }\n  apply (f_equal xfst) in runE2.\n  eapply IHt0 with (qss := qss0) (sl := st); auto.\n  by inversion qsI.\nQed.\n\nLemma checkTree_checkRoots t qss sl : \n  eval_state (checkTreeT t qss) sl = true -> \n  checkRoots (fun n1 n2 => getAddrS n1 = getAddrS n2) (Tree.nodes t) qss.\nProof.\nelim/Tree_ind: t qss sl=> [|t ts].\n{ move=> ? [? /eval_state_checkTreeP-[|] //|>].\n  by rewrite /eval_state /checkTreeT /= rununit. }\nmove=> n IHt1 IHt2 [>|[>|q qs qss] ].\n1-2: by rewrite /eval_state /checkTreeT /= rununit.\nmove=> ? /eval_state_checkTreeP-[ ]//.\nmove=> ??? > [<-<-<-] [<-<-<-] <- qE.\nmove=> ??? /(f_equal xfst) r /= *.\nsplit; last exact/IHt2/r.\nby rewrite qE errorE.\nQed. \n\nArguments InterpretNode : simpl never.\n\nInductive addr_spec : messageTree -> Prop := \n  | Addr_spec1 n (t : messageTree) ts\n    (addrRt       : getAddrS n = getAddrS (Tree.root t))\n    (addrSts      : Forall (fun n' => getAddrS (Tree.root n') = getAddrR n) ts)\n    (addr_spec_tr : Forall addr_spec (t :: ts)) :\n      addr_spec (Node n (t :: ts))\n  | Addr_spec2 n ts\n    (addrSts      : Forall (fun n' => getAddrS (Tree.root n') = getAddrR n) ts)\n    (addr_spec_tr : Forall addr_spec ts) :\n      addr_spec (Node n ts).\n\nDefinition addr_spec_nodes n qss := \n  match qss with \n  | q :: qs => \n    Forall (Forall (fun n' => getAddrS n' = getAddrR n)) qss \\/\n    Forall (Forall (fun n' => getAddrS n' = getAddrR n)) qs /\\ \n    Forall (fun n' => getAddrS n' = getAddrS n) q\n  | nil => True\n  end.\n\nLemma add_spec_nodesF n qss :\n  Forall (Forall (fun n' => getAddrS n' = getAddrR n)) qss ->\n  addr_spec_nodes n qss.\nProof. by case: qss=> //=; left. Qed.\n\nLemma checkRoots_Forall ts qss (P : nodeType -> Prop) \n  (R : nodeType -> nodeType -> Prop) :\n  (forall x y, P y -> R x y -> P x) ->\n  Forall (Forall P) qss ->\n  checkRoots R ts qss ->\n  Forall P (map (@Tree.root _) ts).\nProof.\n  elim: ts qss=> /=; first by constructor.\n  move=>> IHts -[ ] // [ ] //> RP X.\n  inversion X as [|?? Y]; inversion Y.\n  move=> [/RP] PP { }/IHts IHts.\n  constructor=> //; last exact/IHts.\n  exact/PP.\nQed.\n\nHint Resolve Tree.size_lt_cons Tree.size_lt_add_root : core.\n\nLemma checkTree_addr_spec t qss sl : \n  addr_spec_nodes (Tree.root t) qss ->\n  eval_state (checkTreeT t qss) sl = true ->\n  addr_spec t.\nProof.\nhave AH: (forall n x y,\n  getAddrS y = getAddrR n -> getAddrS x = getAddrS y -> getAddrS x = getAddrR n).\n{ by move=>> ->. }\nelim/Tree.ind_size: t qss sl=> -[n ts] IHt qss sl.\ncase: qss=> [|[|q qs] qss].\n1-2: case: (ts)=> [|>]; rewrite /checkTreeT /= /eval_state rununit //.\n{ by do ? constructor. }\ncase: ts IHt=> [|t ts] IHt.\n{ by rewrite /checkTreeT /= /eval_state rununit. }\nmove=> ads.\ncase/eval_state_checkTreeP=> // ?? tss > [<-<-<-] [<-<-<-] <-.\nmove=> qE IN qss'E r1 r2 r3.\nhave adsts: (addr_spec (Node n ts)).\n{ apply/IHt=> //; last exact/(f_equal xfst r2).\n  move: ads=> /= -[|[ ] ] X *; apply/add_spec_nodesF=> //.\n  by inversion X. }\nhave adstss: addr_spec_nodes (Tree.root t) tss.\n{ exact/add_spec_nodesF/IN_addrS/IN. }\nmove: ads.\nrewrite /addr_spec_nodes=> /[dup] ? -[ads|[ads1 ads2] ].\n{ constructor 2.\n  { move/(f_equal xfst)/checkTree_checkRoots: r3.\n    by move=> /checkRoots_Forall-/(_ _ (AH _) ads) /Forall_map. }\n  constructor.\n  { apply/IHt=> //; last exact/(f_equal xfst r1).\n    case: (qs) qss'E ads=> [|a l]-> // /Forall_forall f.\n    right; split.\n    { exact/IN_addrS/IN. }\n    rewrite qE; apply/Forall_forall=> x In.\n    move: (f (q :: a :: l))=> /(_ (or_introl eq_refl))/Forall_forall.\n    move=> /[dup]/(_ x)/(_ (or_intror In))->.\n    move=> /(_ q)/(_ (or_introl eq_refl)).\n    by rewrite errorE=>->. }\n  by inversion adsts. }\nconstructor 1.\n{ rewrite qE. \n  move/Forall_forall/(_ q (or_introl eq_refl)): ads2.\n  by rewrite errorE=>->. } \n{ move/(f_equal xfst)/checkTree_checkRoots: r2=> /=.\n  by move=> /checkRoots_Forall-/(_ _ (AH _) ads1) /Forall_map. }\nconstructor; last by inversion adsts.\napply/IHt=> //; last exact/(f_equal xfst r1).\ncase: (qs) qss'E ads2=> [|a l]-> // /Forall_forall f.\nright; split=> //.\n{ exact/IN_addrS/IN. }\nrewrite qE; apply/Forall_forall=> x In.\nmove: (f x)=> /(_ (or_intror In)).\nmove: (f q)=> /(_ (or_introl eq_refl)).\nby rewrite errorE=>->.\nQed.\n\nDefinition error_spec `{eqb_spec Interfaces} (t : messageTree) := \n  forall t', \n    let rt' := Tree.root t' in\n    Tree.sub t' t ->\n    isInternal rt' ->\n    isSome (err_of (getError rt'))  ->\n    has_money_for_on_bounce (getError rt') ->\n    getBounce (getMess rt') ->\n    exists2 n, \n      Tree.In n t' &\n      onBounce_spec (getAddrR rt') n.\n\nLemma checkTree_qss t sl qss : \n  eval_state (checkTreeT t qss) sl = true ->\n  forall x q, In q qss -> In x q -> exists err, Tree.In (putError x err) t.\nProof.\nelim/Tree.ind_size: t sl qss=> -[t [|tsh tst] ] IHt sl qss.\nall: case/eval_state_checkTreeP=> //.\n{ by move=>> ?? ->. }\nmove=> ??????????? err [<-<-<-].\ndestruct qss as [|[|q qs] qss]=> //.\ncase=><-<-<-<- qE IN qss'E /(f_equal xfst) r1 /(f_equal xfst) r2 r3.\nmove=> ?? /= [<-/=[<-|] |].\n{ by exists err; constructor 2; do ? constructor 1. }\n{ case: (qs) r1 qss'E=> // ?? /IHt/[swap]->/[apply]-[ ] //.\n  { by left. }\n  by move=> err'; exists err'; constructor 2; constructor 1. }\nmove: r2=> /IHt/[apply]/[apply]-[//|] err'.\nexists err'; exact/Tree.In_cons.\nQed.\n\nLemma checkTree_error_hyps {sl qs qss n tsh tst q qss'} :\n  eval_state (checkTreeT (Node n (tsh :: tst)) qss) sl = true -> \n  qss = (q :: qs) :: qss' ->\n  let IntN := InterpretNode (Tree.root tsh) sl in\n  [/\\ getError (Tree.root tsh) = errTp_of IntN                                    ,\n  incl (tss_of IntN) (if qs is nil then (tss_of IntN) else qs :: (tss_of IntN)) &\n  eval_state \n    (checkTreeT tsh (if qs is nil then (tss_of IntN) else qs :: (tss_of IntN))) \n    (sl_of IntN) = true].\nProof.\n  case/eval_state_checkTreeP=>> //.\n  case=> <-<-<--><- qE IN qss'E r1 r2 r3 [? qsE ?] IntN.\n  rewrite -qsE /IntN IN /= qE errorE -qss'E; split=>//.\n  { move: qss'E; rewrite qsE; case: (qs)=>[|??]-> //; by right. }\n  by move/(f_equal xfst): r1.\nQed.\n\n\nLemma checkTree_error_spec `{eqb_spec Interfaces} sl qss tr: \n  (let IntN := InterpretNode (Tree.root tr) sl in\n  getError (Tree.root tr) = errTp_of IntN ->\n  incl (tss_of IntN) qss -> \n  eval_state (checkTreeT tr qss) (sl_of IntN) = true -> \n    error_spec tr) /\\ \n  (eval_state (checkTreeT tr qss) sl = true ->\n    Forall error_spec (Tree.nodes tr)).\nProof.\nelim/Tree.ind_size: tr sl qss=> -[n ts] IHtr sl qss.\nsplit.\n{ move=> IntN err inc.\n  destruct ts as [|tsh tst]=> /eval_state_checkTreeP-[ ] //.\n  { move=> ? sl' ? [xE] qssE; move: inc err; rewrite /IntN qssE xE /Tree.root.\n    move=> inc err <- r; rewrite /error_spec=> ?. \n    rewrite Tree.subE=> -[ ]; last by move=> X; inversion X.\n    move->=> /=; by rewrite err=> /IN_error/[apply]/[apply]/[apply]-[?/inc]. }\n  move=> ? sl' ? sl'' ? qs qss1 qss'>; move: inc err => inc err.\n  case=> <-<-<- /[dup] qssE <-<- qE IN qss'E.\n  move=> r1 /(f_equal xfst) r2 /(f_equal xfst) r3.\n  move=> t' /=; rewrite Tree.subE=> -[->|].\n  { rewrite err => /IN_error/[apply]/[apply]/[apply]-[ ]; rewrite /Tree.root.\n    move/checkTree_qss: r3=> qss_sub.\n    move=> x /inc/qss_sub x_sub /Exists_exists .\n    case=> n' -[/x_sub-[err' ] ]; exists (putError n' err')=> //.\n    exact/onBounce_spec_putError. }\n  move=> /= /Exists_cons-[ ].\n    { have s: (Tree.size tsh < Tree.size (Node n (tsh :: tst)))%coq_nat by [ ].\n    case: (IHtr _ s (sl_of IntN) qss')=> +_.\n    case: (checkTree_error_hyps r3 qssE).\n    rewrite IN -qss'E=> ???; exact. }\n  have s: (Tree.size (Node n tst) < Tree.size (Node n (tsh :: tst)))%coq_nat by [ ].\n  case: (IHtr _ s sl'' qss1)=> _.\n  move: r2=> /[swap]/[apply] /=.\n  move=> /Forall_forall f /Exists_exists-[n' [/f] ]; exact. }\ndestruct ts as [|tsh tst].\n{ by constructor. }\ncase/eval_state_checkTreeP=> // ? sl' ? sl'' ? qs qss1 qss'>.\ncase=> <-<-<- /[dup] qssE <-<- qE IN qss'E.\nmove=> r1 /(f_equal xfst) r2 /(f_equal xfst) r3.\nconstructor.\n{ have s: (Tree.size tsh < Tree.size (Node n (tsh :: tst)))%coq_nat by [ ].\n  case: (IHtr _ s sl qss')=> +_.\n  case: (checkTree_error_hyps r3 qssE).\n  rewrite IN -qss'E=> ???; exact. }\nhave s: (Tree.size (Node n tst) < Tree.size (Node n (tsh :: tst)))%coq_nat by [ ].\ncase: (IHtr _ s sl'' qss1)=> _.\nby move: r2=> /[swap]/[apply] /=.\nQed.\n\nLemma checkForest_IN \n  (P : list (list nodeType) -> nodeType -> Prop) \n  (Q : messageTree -> Prop)\n  sl trs :\n  (forall n sl qss err sl', \n    InterpretNode n sl = mk_IN sl' qss err -> \n    P qss n) ->\n  (forall qss sl tr, \n    P qss (Tree.root tr) -> \n    eval_state (checkTreeT tr qss) sl = true -> Q tr) ->\n  eval_state (checkForestT trs) sl = true -> Forall Q trs.\nProof.\nmove=> PP QP.\nelim: trs sl; first by constructor.\nmove=> trh trt IHtrs sl.\nrewrite checkForestE /eval_state runmodifybind runbind runget.\ncase E1: (InterpretNode _ _).\nrewrite runputbind runbind.\ncase E2: (run _ _); move/(f_equal xfst): E2=> E2.\nrewrite runbind.\ncase E3: (run _ _); move/(f_equal xfst): E3=> E3.\nrewrite rununit /==> /andP-[/andP-[ ] ]; rewrite /is_true=>*; subst.\nconstructor.\n{ exact/QP/E2/PP/E1. }\nexact/IHtrs/E3.\nQed.\n\nArguments Tree.root {_}.\nArguments Tree.nodes {_}.\n\nTheorem checkForest_messages_type trs ems sl :\n  checkForest trs ems sl ->\n  (forall tr, In tr trs -> isExternal (Tree.root tr)) /\\ \n  (forall tr, In tr trs ->\n    Forall (Tree.Forall (fun x => isInternal x)) (Tree.nodes tr)).\nProof.\nmove=> /andP-[/checkForest_IN] IN Eq; split.\n{ elim: (trs) ems Eq=> // trh trt IHtrs [ ] // e ?.\n  rewrite /= /eqb /==> /andP-[/eqb_spec_intro] tE { }/IHtrs IHtrs.\n  move=> tr -[<-|/IHtrs] //.\n  rewrite (isExternal_putError _ (Build_errorType None false)) tE.\n  by case: (e). }\napply/Forall_forall/IN=>>.\n{ exact/IN_internal. }\nexact/checkTree_intrenalN.\nQed.\n\nTheorem checkForest_addr_spec trs ems sl :\n  checkForest trs ems sl ->\n  Forall addr_spec trs.\nProof.\nmove=> /andP-[/checkForest_IN] + _; apply=>>.\n{ apply IN_addrS. }\nby move=> ?; apply/checkTree_addr_spec/add_spec_nodesF.\nQed.\n\nTheorem checkForest_error_spec `{eqb_spec Interfaces} trs ems sl :\n  checkForest trs ems sl ->\n  Forall error_spec trs.\nProof.\nmove=> /andP-[+_].\nelim: trs sl; first by constructor.\nmove=> trh trt IHtrs sl.\nrewrite checkForestE /eval_state runmodifybind runbind runget.\ncase E1: (InterpretNode _ _)=> [sl' tss' err'].\nrewrite runputbind runbind.\ncase E2: (run _ _); move/(f_equal xfst): E2=> E2.\nrewrite runbind.\ncase E3: (run _ _); move/(f_equal xfst): E3=> E3.\nrewrite rununit /==> /andP-[/andP-[ ] ]; rewrite /is_true=>??; subst.\nmove/eqb_spec_intro=> ?.\nconstructor.\n{ case: (checkTree_error_spec (setTime (getTime (Tree.root trh)) sl) tss' trh)=> +_. \n  by apply; rewrite E1. }\nexact/IHtrs/E3.\nQed.\n\nArguments Tree.size : simpl never.\n\nLemma checkTreeT_inj t1 t2 tss sl :\n  Tree.root t1 = Tree.root t2 ->\n  eval_state (checkTreeT t1 tss) sl = true ->\n  eval_state (checkTreeT t2 tss) sl = true ->\n  ((t1 = t2) * \n  (run (checkTreeT t2 tss) sl = \n   run (checkTreeT t2 tss) sl))%type.\nProof.\nmove=> rE e1 e2; suff->: (t1 = t2) by [ ].\nmove: rE e1 e2.\nelim/Tree.ind_size: t1=> -[x ts] IHt1 in t2 tss sl *.\nmove=> /= rE /eval_state_checkTreeP rP.\ninversion rP; subst; destruct t2 as [x' ts']=> //=; first last.\nall: move=> /eval_state_checkTreeP rP'.\nall: inversion rP'; subst=> //.\nall: case: trE=> ??; subst.\nall: case: trE0=> ??; subst=> //.\ncase/(@eq_sym _ _ _): queE=> *; subst.\nmove: INt INt0 (tE) (tE0). \nrewrite {1}tE {1}tE0 ?errorE=> -> -[??->/[swap]<-].\nmove/IHt1=> /= IH; subst.\nmove: (f_equal xfst runE1) (f_equal xfst runE0).\nmove=> { }/IH/[apply]/(_ (@Tree.size_lt_add_root _ _ _ _)).\nmove=> ?; subst.\nmove: runE1 runE0=>-> [?]; subst.\nmove/IHt1: (f_equal xfst runE2) (f_equal xfst runE4)=> /[apply].\nby move/(_ (@Tree.size_lt_cons _ _ _ _))/(_ eq_refl)=> [->].\nQed.\n\nLemma MessagesQueue_run_BuildE {n fuel sl ms} :\n  RunOutOfFuel (exec_state (Build fuel n) (Build_state ms sl false)) = false ->\n  MessagesQueue (exec_state (Build fuel n) (Build_state ms sl false)) = [ ].\nProof.\nset eq := (@eq_refl _ (run (Build fuel n) (Build_state ms sl false))).\nmove: {2}(run _ _) eq=> -[t [ms' sl' ?] ]=> /[dup]+/[swap].\nrewrite /exec_state=>{1}->/=-> /[dup]{2}-> /=.\nelim: fuel=> [|fuel IHfuel] in t n ms ms' sl sl' *.\n{ by rewrite run_BuildE. }\nmove/run_BuildP.\ncase E: (InterpretNode _ _)=> [? tss ?].\nset qss := if ms is nil then tss else ms :: tss.\nmove=> rP.\ninversion rP; subst; first last.\n{ by case: (ms')=> [|??] in qssE *. }\nmove/IHfuel: runE1=> ?; subst.\nmove: IHfuel runE2; clear=> IHfuel.\nelim: qss0=> [|[|q qs] qss IHqss] in trt sl'0 ms' sl' *; rewrite run_BuildsE //=.\n{ by case. }\ncase E: (run _ _)=> [?[?? r] ].\ncase E1: (run _ _)=> [?[ ] ]; move: E1=> /[swap].\ncase=> ? ->->-> E1.\nhave rE: r = false by exact/Builds_RunOutOfFuel/E1.\nsubst.\nmove/IHfuel: E=> ?; subst.\nexact/IHqss/E1.\nQed.\n\nLemma run_Build_eq_root fuel n  ms sl ms1 sl1 t :\n  run (Build fuel n) (Build_state ms sl false) = \n  (t, Build_state ms1 sl1 false)%xprod -> \n    Tree.root t = putError n (InterpretNode (Tree.root t) sl).\nProof.\nmove/run_BuildP.\ncase E: (InterpretNode _ _)=> [>] rP.\nby inversion rP; rewrite -tE /= errorE INt.\nQed.\n\nLemma run_Build_eq_root2 fuel n  ms sl ms1 sl1 t :\n  run (Build fuel n) (Build_state ms sl false) = \n  (t, Build_state ms1 sl1 false)%xprod -> \n    Tree.root t = putError n (InterpretNode n sl).\nProof.\nmove/run_BuildP.\ncase E: (InterpretNode _ _)=> [>] rP.\nby inversion rP; rewrite -tE -E /= INt.\nQed.\n\nLemma checkTreeBuildE n t fuel sl sl' ms : \n  let: tss  := tss_of (InterpretNode n sl) in\n  let: sl'' := sl_of (InterpretNode n sl) in\n  let: qss  := (if ms is nil then tss else ms :: tss)  in\n  run (Build fuel n) (Build_state ms sl false) = \n  (t, (Build_state nil sl' false))%xprod ->\n  run (checkTreeT t qss) sl'' = (true, sl')%xprod.\nProof.\nelim: fuel t ms n sl sl'=>[>|].\n{ by rewrite run_BuildE. }\nmove=> fuel IHfuel [x ts] ms n sl sl'.\ncase E: (InterpretNode n sl)=> [sl'' tss err].\nrewrite /tss_of /sl_of.\nset qss  := (if ms is nil then tss else ms :: tss).\nmove/run_BuildP; rewrite {1}E -/qss=> rP.\ninversion rP=> //; have slE: sl'' = sl0 by rewrite INt in E; case: E=> slE.\nall: subst; rewrite -tE.\n2: { by rewrite run_checkTreeE. }\nrewrite run_checkTreeE.\ncase E6: (InterpretNode _ _)=> [sl'' tss'' err''].\ncase E7: (run _ _)=> [b1 s1].\ncase E8: (run _ _)=> [b2 s2].\nmove/run_Build_eq_root: (runE1) (E6)=> /[swap] -> /= /[dup] rE->.\nrewrite eqbxx /=.\nmove: (@MessagesQueue_run_BuildE q fuel sl0 qs) (runE1).\nrewrite /exec_state {1 2}runE1 /= => -> // /IHfuel.\nrewrite rE errorE in E6; rewrite E6 /=.\nrewrite E7=> -[-> sE] /=; subst.\nelim: (qss0) (ms') (sl') (sl'0) (b2) (s2) (trt) runE2 E8.\n{ clear=>>; rewrite run_BuildsE run_checkTreeE.\n  by case=><-?<- [->->]. }\nmove: IHfuel nodeEqType; clear=> IHfuel nodeEqType.\nmove=> [|q qs] qss IHqss ?? sl' >; rewrite run_BuildsE //=.\ncase E1: (run _ _)=> [trt [?? r] ].\ncase E2: (run _ _)=> [trt1 st1].\ncase=> <- st1E; subst.\nrewrite run_checkTreeE.\ncase E6: (InterpretNode _ _)=> [sl'' tss'' err''].\ncase E7: (run _ _)=> [b3 s3].\ncase E8: (run _ _)=> [b4 s4].\nhave rE: r = false by exact/Builds_RunOutOfFuel/E2.\nsubst.\nmove/run_Build_eq_root: (E1) (E6)=> /[swap] -> /= /[dup] rE->.\nrewrite eqbxx /= .\nmove: (@MessagesQueue_run_BuildE q fuel sl' qs) (E1).\nrewrite /exec_state {1 2}E1 /= => -> // /IHfuel.\nrewrite rE errorE in E6; rewrite E6 /=.\nrewrite E7=> -[-> sE] /=; subst.\nby move/IHqss: E2=> /(_ _ _ E8)=> -[->->][->->].\nQed.\n\nLemma checkTreeP n t fuel sl sl' ms : \n  let: tss  := tss_of (InterpretNode n sl) in\n  let: sl'' := sl_of (InterpretNode n sl) in\n  let: qss  := if ms is nil then tss else ms :: tss  in\n  RunOutOfFuel (exec_state (Build fuel n) (Build_state ms sl false)) = false ->\n  run (Build fuel n) (Build_state ms sl false) = \n  (t, (Build_state nil sl' false))%xprod <->\n  putError n (InterpretNode n sl) = Tree.root t /\\ \n  run (checkTreeT t qss) sl'' = (true, sl')%xprod.\nProof.\nmove=> rofE; split.\n{ by move=> /[dup] /run_Build_eq_root2-> /checkTreeBuildE->. }\ncase=> tE.\nset rb := run (Build fuel n) (Build_state ms sl false).\nset st := xsnd rb.\nmove: (@checkTreeBuildE n (xfst rb) fuel sl (SuperLedger st) ms).\nmove: (rofE) (MessagesQueue_run_BuildE rofE).\nrewrite /exec_state /st /rb; case E: (run _ _)=> [? [ ] ].\nmove=> /= ->-> /(_ eq_refl).\nrewrite /exec_state E /= in rofE; rewrite rofE in E.\nmove/run_Build_eq_root2: E=> rootE.\ndo 2? move=> /[dup] /(f_equal xsnd) /= {-1}<- /[swap].\nmove=> /(f_equal xfst)/[swap] /(f_equal xfst) /=.\nby move/checkTreeT_inj/[apply]; rewrite rootE -tE=> /(_ eq_refl)-[->].\nQed.\n\nLemma run_buildForestE fuel ls ms sl r : \n  run (buildForestT fuel ls) (Build_state ms sl r) = \n  match ls with \n  | [ ] => ([ ], Build_state ms sl r)%xprod\n  | n :: tln => \n    let: (tree, st)%xprod := \n      run \n        (Build fuel n) \n        (Build_state ms (setTime (getTime n) sl) r) in \n    let: (forest, st')%xprod := run (buildForestT (fuel - 1) tln) st in \n      (tree :: forest, st')%xprod\n  end.\nProof.\ncase: ls=> //= *; rewrite (rununit, runmodifybind) //.\ndo ? (rewrite runbind; case: (run _ _)=> * ).\nby rewrite rununit.\nQed.\n\nLemma eval_state_buildForest1E fuel l sl ms r : \n  eval_state (buildForestT fuel (l :: nil)) (Build_state ms sl r) = \n  [eval_state (Build fuel l) (Build_state ms (setTime (getTime l) sl) r)].\nProof.\nrewrite /eval_state run_buildForestE.\nby case: (run _ _)=> [?[ ] ] *; rewrite run_buildForestE.\nQed.\n\nLemma exec_state_buildForest1E fuel l sl ms r : \n  exec_state (buildForestT fuel (l :: nil)) (Build_state ms sl r) = \n  exec_state (Build fuel l) (Build_state ms (setTime (getTime l) sl) r).\nProof.\nrewrite /exec_state run_buildForestE.\nby case: (run _ _)=> [?[ ] ] *; rewrite run_buildForestE.\nQed.\n\nLemma buildForest_RunOutOfFuel ls sl fuel ms r: \n  RunOutOfFuel \n    (exec_state (buildForestT fuel ls) (Build_state ms sl r)) = false ->\n  r = false.\nProof.\nelim: ls=> [|l ls IHl] in fuel ms sl r *; rewrite /exec_state /=.\n{ by rewrite rununit. }\nrewrite runmodifybind runbind.\ncase E1: (run _ _)=> [? [ ] ]; rewrite runbind.\ncase E2: (run _ _)=> [? [ ] ]; rewrite rununit.\nmove: E2=> /[swap] /=-> /(f_equal xsnd)/(f_equal RunOutOfFuel)/IHl.\nmove=> ?; subst.\nexact/Build_RunOutOfFuel/E1.\nQed.\n\nLemma MessageQueue_run_buildForestE {ls fuel sl}: \n  RunOutOfFuel \n    (exec_state (buildForestT fuel ls) (Build_state nil sl false)) = false ->\n  MessagesQueue\n    (exec_state (buildForestT fuel ls) (Build_state nil sl false)) = nil.\nProof.\nelim: ls=> [|l ls IHl] in fuel sl *; rewrite /exec_state /=.\n{ by rewrite rununit. }\nrewrite runmodifybind runbind.\ncase E1: (run _ _)=> [? [ ] ]; rewrite runbind.\ncase E2: (run _ _)=> [? [ ] ]; rewrite rununit.\nmove: (E2)=> /[swap] /= ?; subst.\nmove/[dup]/(f_equal xsnd)/(f_equal RunOutOfFuel).\nmove/buildForest_RunOutOfFuel=> ?; subst.\nmove/[dup]/(f_equal xsnd)/(f_equal RunOutOfFuel).\nmove/(f_equal xsnd)/(f_equal RunOutOfFuel)/MessagesQueue_run_BuildE: (E1).\nrewrite /= /exec_state E1 /= => ?; subst=>/IHl.\nby rewrite /exec_state E2.\nQed.\n\n\nLemma rof_buildForest_cons {l ls fuel sl tr tr' ms1 sl1 ms2 sl2 r1 r2} : \n  let: st1 := Build_state ms1 sl1 r1 in \n  let: st2 := Build_state ms2 sl2 r2 in \n  RunOutOfFuel \n  (exec_state (buildForestT fuel (l :: ls)) (Build_state nil sl false)) = false ->\n  run (Build fuel l) (Build_state nil (setTime (getTime l) sl) false) =\n     (tr, st1)%xprod -> \n  run (buildForestT (fuel - 1) ls) st1 = (tr', st2)%xprod -> \n  (r1  = false) *\n  (r2  = false) *\n  (ms1 = nil)   *\n  (ms2 = nil).\nProof.\nrewrite /exec_state /= runmodifybind runbind.\ncase E1: (run _ _)=> [? [ ] ]; rewrite runbind.\ncase E2: (run _ _)=> [? [ ] ]; rewrite rununit.\nmove=> /= ?; subst.\nmove/(f_equal xsnd)/(f_equal RunOutOfFuel)/buildForest_RunOutOfFuel: (E2)=> /= ?.\nsubst.\nmove/(f_equal xsnd)/(f_equal RunOutOfFuel)/MessagesQueue_run_BuildE: (E1)=> /= E.\nrewrite /exec_state E1 /= in E; subst.\nmove/(f_equal xsnd)/(f_equal RunOutOfFuel)/MessageQueue_run_buildForestE: (E2).\nby rewrite /exec_state E2=> /= ?; subst=> -[? <-<-<-]; rewrite E2=> -[?<-?<-].\nQed.\n\n\nLemma checkForestTP fr ls fuel sl sl' : \n  RunOutOfFuel \n    (exec_state (buildForestT fuel ls) (Build_state nil sl false)) = false ->\n  (map (fun t => putError (Tree.root t) (Build_errorType None false)) fr) =\n  (map (fun m => putError m (Build_errorType None false)) ls) /\\\n  run (checkForestT fr) sl = (true, sl')%xprod <->\n  run (buildForestT fuel ls) (Build_state nil sl false) = \n  (fr, Build_state nil sl' false)%xprod.\nProof.\nelim: ls=> [/=|l ls IHl] in fr fuel sl sl' *.\n{ rewrite /exec_state ?rununit /==> ?.\n  case: fr=> [/=|]; last split=> [ [ ]|] //.\n  by rewrite rununit; split=> [ [? [ ] ]|[ ] ]->. }\nmove=> rofE /=.\nrewrite runmodifybind runbind.\ncase E1: (run (Build _ _) _)=> [a [? sl'' ?] ].\nrewrite runbind.\ncase E2: (run (buildForestT _ _) _)=> [b [? sl0 ?] ].\nrewrite rununit. \nhave runE1 := E1; have runE2 := E2.\nrewrite ?(rof_buildForest_cons rofE E1 E2) {E1 E2} in runE1 runE2 *.\nsplit.\n{ case=> lsE ct.\n  destruct fr as [|tr fr]=> //.\n  move: ct; rewrite /=.\n  rewrite runmodifybind runbind runget.\n  case E3: (InterpretNode _ _)=> [sl1 tss1 err1].\n  rewrite runputbind runbind.\n  case E4: (run _ _)=> [? sl'''].\n  rewrite runbind.\n  case E5: (run _ _)=> [ ].\n  rewrite rununit=> -[/andP-[/andP-[ ] ] ]; rewrite /is_true=> ??+?; subst.\n  move=> /eqb_spec_reflect.\n  move: (@checkTreeP l tr fuel (setTime (getTime l) sl) sl''' nil).\n  move: lsE=> /= [ ] /(f_equal (fun x => putError x (getError l))).\n  rewrite ?errorE=> {5 6 7 8 9 10 11}<- lsE.\n  rewrite ?errorE ?E3 /= => -[ ].\n  { by rewrite /exec_state runE1. }\n  move=> _ /[swap]<-; rewrite ?errorE E4=> /(_ (conj eq_refl eq_refl)).\n  rewrite runE1=> -[??]; subst.\n  case: (IHl fr (fuel - 1) sl''' sl').\n  { by rewrite /exec_state runE2. }\n  rewrite lsE E5=> /(_ (conj eq_refl eq_refl)).\n  by rewrite runE2=> -[->->]. }\ncase=> <-<- /=.\nrewrite runmodifybind runbind runget.\ncase E3: (InterpretNode _ _)=> [sl1 tss1 err1].\nrewrite runputbind runbind.\ncase E4: (run _ _)=> [? sl'''].\nrewrite runbind.\ncase E5: (run _ _)=> [ ].\nrewrite rununit.\nmove: (@checkTreeP l a fuel (setTime (getTime l) sl) sl'' nil).\ncase.\n{ by rewrite /exec_state runE1. }\nmove=> /(_ runE1) -[ ] ++ _.\nmove=> aE; move: E3; rewrite -aE ?errorE=>-> /=.\nrewrite ?errorE eqbxx E4=> -[??]; subst.\ncase: (IHl b (fuel - 1) sl'' sl0).\n{ by rewrite /exec_state runE2. }\nby move=> _ /(_ runE2) -[-> ]; rewrite E5=> -[->->].\nQed.\n\nLemma checkForestP fr scen fuel sl : \n  buildFinished fuel scen sl ->\n  reflect (fr = buildForest fuel scen sl) (checkForest fr scen sl).\nProof.\nrewrite /buildFinished=> /negbTE /[dup] rofE /checkForestTP cE.\nrewrite /checkForest /buildForest /eval_state.\napply/(iffP andP).\n{ case=> fE /eqb_spec_reflect ?.\n  rewrite (proj1 (cE fr (xsnd (run (checkForestT fr) sl)))); split=> //.\n  by case: (run _ _) fE=> //= ??->. }\nmove=> frE.\ndestruct \n  (cE \n    fr \n    (SuperLedger \n      (xsnd \n        (run \n          (buildForestT fuel (mapNode scen)) \n          (Build_state nil sl false))))) as [_ bE].\ncase: bE=> [|-> ->] //=; last by rewrite eqbxx.\nmove/MessageQueue_run_buildForestE: rofE (rofE).\nby rewrite frE /exec_state; case: (run _ _)=> /= ? [/=> ->->].\nQed.\n\nLemma execForestE fr scen fuel sl : \n  buildFinished fuel scen sl ->\n  checkForest fr scen sl ->\n  execForest fr sl = buildSLedger fuel scen sl.\nProof.\nmove=> /[dup] + /checkForestP/[apply]+->.\nrewrite /buildFinished=> /negbTE /[dup] rofE /checkForestTP cE.\nrewrite /execForest /buildSLedger /exec_state /=.\ncase: (cE (buildForest fuel scen sl) \n  (SuperLedger \n    (xsnd \n      (run \n        (buildForestT fuel (mapNode scen))\n        (Build_state nil sl false)))))=> _ [|?->] //.\nmove/MessageQueue_run_buildForestE: rofE (rofE).\nrewrite /exec_state; case E: (run _ _)=> [? [/=> ] ].\nby move=>->->; rewrite /buildForest /eval_state E.\nQed.\n\nArguments buildForestT : simpl never.\n\nLemma buildForest_cat fuel ems1 ems2 sl : \n  buildFinished fuel ems1 sl ->\n  buildForest fuel (ems1 ++ ems2) sl = \n  buildForest fuel ems1 sl ++\n  buildForest (fuel - length ems1) ems2 (buildSLedger fuel ems1 sl).\nProof.\nelim: ems1=> [/=|em ems1 IHems1 /=] in fuel ems2 sl *.\n{ rewrite /buildForest /eval_state rununit /= subn0.\n  by rewrite /buildSLedger /exec_state /= rununit. }\nrewrite /buildFinished=> /negbTE rofE.\nrewrite /buildForest /buildSLedger /eval_state /exec_state /=.\nrewrite 2?run_buildForestE.\ncase E1: (run (Build _ _) _)=> [a [? sl' ?] ].\ncase E2: (run (buildForestT _ _) _)=> [b [ ] ].\ncase E3: (run (buildForestT _ _) _)=> [c [ ] ].\ncase E4: (run (buildForestT _ _) _)=> [d [ ] ].\nmove=> /=; apply/f_equal.\nmove: (IHems1 (fuel - 1) ems2 sl').\nrewrite /buildForest /eval_state.\nhave runE1 := E1; have runE3 := E3.\nrewrite !(rof_buildForest_cons rofE E1 E3) {E1 E3} in runE1 runE3 E4 E2 *.\nhave->: fuel - 1 - length ems1 = fuel - (length ems1).+1 by lia.\nrewrite /buildFinished /buildSLedger /exec_state ?runE3 E2 /= E4.\nexact.\nQed.\n\nSection LedgerInvariants.\n\nVariable (P : superLedger -> Prop).\n\nHypothesis P_inv_IN : forall n sl sl', \n  P sl -> \n  sl' = sl_of (InterpretNode n sl) -> \n  P sl'.\n\n(* Lemma P_inv_CT tr qss st : \n  P st ->\n  P (exec_state (checkTreeT tr qss) st).\nProof.\n  rewrite /exec_state.\n  case: st qss; elim/Tree.ind: tr=> /=.\n  { move=> x ms sl qss ?; case: qss.\n    { by rewrite run_checkTreeE. }\n    by rewrite /checkTreeT /= rununit. }\n  move=> t ts x ++++ qss.\n  case: qss=> [*|[*|q qs qss IHtr1 IHtr2 ms sl Psl] ].\n  1-2: by rewrite /checkTreeT /= rununit.\n  rewrite run_checkTreeE.\n  case E1: (InterpretNode _ _)=> [sl' tss].\n  set qss' := if ms is nil then tss else ms :: tss.\n  case E2: (run (checkTreeT _ _) _)=> [b [ms1 sl1] ].\n  case E3: (run _ _) => [b' st' /=].\n  move/(f_equal xsnd): E3=> /=<-.\n  apply/IHtr2.\n  move/(f_equal xsnd)/(f_equal SuperLedger): E2=> /=<-.\n  apply/IHtr1/(P_inv_IN (Tree.root t) Psl).\n  by rewrite E1.\nQed. *)\n\nEnd LedgerInvariants.\n\nEnd MessageTree.\n\n", "meta": {"author": "fibletype", "repo": "scenarios", "sha": "9126a53892bcf1d1e8cb713c37d206700e48bfcb", "save_path": "github-repos/coq/fibletype-scenarios", "path": "github-repos/coq/fibletype-scenarios/scenarios-9126a53892bcf1d1e8cb713c37d206700e48bfcb/src/MessageTree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.39981164073979497, "lm_q1q2_score": 0.2688060397702446}}
{"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.\nRequire Import Race.\n\nRequire Import APF.\nRequire Import PF.\nRequire Import PFSingle.\nRequire Import DRF_PF.\n\nLemma sim_apf_pf_racefree c\n      (RACEFREE: pf_racefree PFSingle.step c)\n  :\n    pf_racefree PFConfiguration.step c.\nProof.\n  ii. ginduction STEPS; i.\n  - eapply RACEFREE; eauto.\n  - inv H. exploit PFSingle.step_sim; eauto. i. des.\n    eapply IHSTEPS; auto. ii. eapply RACEFREE; cycle 1; eauto. etrans.\n    + eapply rtc_implies; try apply STEPS0. i. inv H. econs; eauto.\n    + econs; eauto. econs; eauto.\nQed.\n\nTheorem drf_single_pf s\n        (RACEFREE: pf_racefree PFSingle.step (Configuration.init s))\n  :\n    behaviors Configuration.step (Configuration.init s) <1=\n    behaviors PFSingle.step (Configuration.init s).\nProof.\n  ii. eapply PFSingle.long_step_equiv.\n  eapply drf_pf; eauto.\n  eapply sim_apf_pf_racefree; 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/drf/SingleDRF_PF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.4148988457967689, "lm_q1q2_score": 0.26877073293753434}}
{"text": "Require Import Raft.\nRequire Import TraceUtil.\n\nSection InputBeforeOutputInterface.\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\n  Definition input_before_output (tr : list (name * (raft_input + list raft_output))) :=\n    before_func (is_input_with_key client id) (is_output_with_key client id) tr.\n  End inner.\n\n  Class input_before_output_interface : Prop :=\n    {\n      output_implies_input_before_output :\n        forall client id failed net tr,\n          step_f_star step_f_init (failed, net) tr ->\n          key_in_output_trace client id tr ->\n          input_before_output client id tr\n    }.\nEnd InputBeforeOutputInterface.", "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/InputBeforeOutputInterface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2687707329375343}}
{"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 A B C G Aprime Aprimeprime Bprime Cprime Bprimeprime Bprimeprimeprime : Universe, ((wd_ A B /\\ (wd_ B C /\\ (wd_ A C /\\ (wd_ Bprime A /\\ (wd_ Bprime C /\\ (wd_ Aprime B /\\ (wd_ Aprime C /\\ (wd_ Cprime A /\\ (wd_ Cprime B /\\ (wd_ Aprimeprime Bprimeprime /\\ (wd_ Aprime Bprimeprimeprime /\\ (wd_ Aprime Bprime /\\ (wd_ Bprime Bprimeprimeprime /\\ (wd_ G Aprime /\\ (wd_ G Aprimeprime /\\ (wd_ G Bprimeprime /\\ (wd_ Aprime Bprimeprime /\\ (wd_ Bprimeprime Bprimeprimeprime /\\ (wd_ G Bprimeprimeprime /\\ (wd_ Aprime Aprimeprime /\\ (wd_ B G /\\ (wd_ Bprimeprime B /\\ (wd_ A G /\\ (wd_ Aprimeprime A /\\ (wd_ A Aprime /\\ (col_ Aprime Bprime Bprimeprimeprime /\\ (col_ G Bprimeprime Bprimeprimeprime /\\ (col_ Bprimeprime B G /\\ (col_ Cprime A B /\\ (col_ Bprime A C /\\ (col_ G Aprime Aprimeprime /\\ (col_ Aprimeprime A G /\\ (col_ Aprime B C /\\ (col_ Aprime Bprimeprime Aprime /\\ (col_ A Aprimeprime Aprime /\\ col_ Aprime Bprimeprime A))))))))))))))))))))))))))))))))))) -> col_ A B G)).\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_1124.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.3738758297482025, "lm_q1q2_score": 0.2686650747748344}}
{"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(*          Refinement proof for PTIntro layer                         *)\n(*                                                                     *)\n(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)\n(*                                                                     *)\n(*          Yale Flint Group                                           *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** This file provide the contextual refinement proof between MAL layer and MPTIntro layer*)\nRequire Import PTIntroGenDef.\nRequire Export PTIntroGenAccessorDef.\n\n(** * Definition of the refinement relation*)\nSection Refinement.\n\n  Section WITHMEM.\n\n    Context `{Hstencil: Stencil}.\n    Context `{Hmem: Mem.MemoryModel}.\n    Context `{Hmwd: UseMemWithData mem}.\n\n    Require Import LoadStoreSem1.\n    Require Import XOmega.\n    Require Import HostAccess1.\n    Require Import GuestAccessIntel1.\n    Require Import HostAccess2.\n    Require Import LoadStoreGeneral.\n\n    Notation hStore := (fun F V => exec_storeex2 (flatmem_store := flatmem_store) (F:=F) (V:=V)).\n\n    Notation lStore := (fun F V => exec_storeex1 (flatmem_store := flatmem_store) (F:=F) (V:=V)).\n\n    Lemma store_correct:\n      store_accessor_sim_def HDATAOps LDATAOps (one_crel HDATA LDATA) hStore lStore.\n    Proof.\n      unfold store_accessor_sim_def. intros.\n      pose proof H2 as Hmatch.\n      inv H2. inv match_extcall_states.\n\n      unfold exec_storeex2 in *. \n      unfold exec_storeex1. \n      unfold exec_host_store1, exec_host_store2 in *.\n      inv H4.\n      exploit (eval_addrmode_correct ge1 ge2 a); eauto. intros HW.\n      Local Opaque Z.sub.\n      simpl in *. revert H1. inv match_related. subrewrite''. intros HLoad.\n      destruct (eval_addrmode ge1 a rs1) eqn: Hev; contra_inv.\n      - (* addr is Vint*)\n        inv HW. destruct (ihost d2) eqn:HPH; contra_inv.\n        destruct (pg d2) eqn:HPE; contra_inv.\n        destruct (ikern d2) eqn:HPK; contra_inv.\n        specialize (valid_PT refl_equal).\n        + (* host *)\n          generalize match_match; intros HM. inv match_match. \n          inv H1. inv relate_PT_re. \n          * (* PT = -1 *)\n            rewrite <- H7 in valid_PT; omega.  \n          * assert (HFB: Genv.find_symbol ge2 PTPool_LOC = Some b).\n            {\n              inv H0. congruence.\n            }\n            rewrite HFB. lift_trivial. rewrite H8.\n            assert (valid_PT': 0 <= PT d1 < 64) by omega.\n            specialize (H5 _ valid_PT').\n            set (pt := (ZMap.get (PT d1) (ptpool d1))) in *. inv H5.\n            assert (HI: 0<= PDX (Int.unsigned i) <= PDX Int.max_unsigned).\n            {\n              specialize (Int.unsigned_range_2 i).\n              clear. unfold PDX. Local Transparent Z.sub.\n              xomega. Local Opaque Z.sub.\n            }\n            specialize (H7 _ HI).\n            destruct H7 as [v[HLD [_ HP]]].    \n            assert (HI1: 0<= PTX (Int.unsigned i) <= PTX Int.max_unsigned).\n            {\n              unfold PTX; change ((Int.max_unsigned / 4096) mod 1024) with 1023.\n              specialize (Z_mod_lt (Int.unsigned i/PgSize) one_k).\n              omega.\n            }\n            inv HP; try rewrite <- H9 in HLoad; try rewrite <- H5 in HLoad; contra_inv.\n            pose proof relate_PMap_re as HPP.\n            inv HPP. specialize (H9 _ valid_PT' _ HI pi pdx).\n            rewrite H5 in H9. specialize (H9 refl_equal _ HI1).\n            destruct H9 as [v1[HLD1 HP]].\n            rewrite Int.unsigned_repr; [|rewrite_omega]. \n            rewrite HLD, H7.\n            rewrite Z_div_plus_full_l; [|omega].\n            rewrite (Zdiv_small PT_PERM_PTU); [|omega].\n            rewrite Z.add_0_r. rewrite HLD1. clear HLD1.\n            destruct (zle (Int.unsigned i mod 4096) (4096 - size_chunk chunk)); contra_inv.\n            destruct (Zdivide_dec (align_chunk chunk) (Int.unsigned i mod 4096)\n                                  (Memdata.align_chunk_pos chunk)); contra_inv.\n            inv HP; try rewrite <- H11 in HLoad; contra_inv. \n            {\n              change (Int.unsigned Int.zero mod 4096) with 0; simpl.\n              eapply pagefault_correct; eauto.\n            }\n            {\n              rewrite <- H9 in HLoad; contra_inv. rewrite H12.\n              assert (HW1: (padr * PgSize + v) mod PgSize = v mod PgSize).\n              {\n                rewrite Zplus_mod.\n                rewrite Z_mod_mult.\n                rewrite Z.add_0_l.\n                apply Zmod_mod.\n              }\n              assert (HW2: (padr * PgSize + v) / PgSize = padr).\n              {\n                rewrite Z_div_plus_full_l; [|omega].\n                rewrite (Zdiv_small v). omega.\n                functional inversion H11; subst; omega.\n              }\n              rewrite HW1, HW2.\n              functional inversion H11; rewrite <- H13 in HLoad; contra_inv;\n              (rewrite Zmod_small; trivial; [|omega]; simpl;\n               eapply exec_flatmem_store_correct; eauto).\n              apply PTADDR_mod_lt. assumption.\n              apply PTADDR_mod_lt. assumption.\n            }\n        + (* guest *)\n          eapply guest_intel_store_correct1; eauto.\n      - (* adr is (b,ofs) *)\n        inv HW; subdestruct; eapply storel_correct; eauto.\n    Qed.\n    \n  End WITHMEM.\n\nEnd Refinement.", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/mm/PTIntroGenAccessor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.2686650697615564}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import fastpile.\nRequire Import spec_stdlib.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\n\nDefinition tlist := Tstruct _list noattr.\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 [ _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 Pile_new_spec :=\n DECLARE _Pile_new\n WITH gv: globals\n PRE [ ] PROP() LOCAL(gvars 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 [ _p OF tptr tpile, _n OF tint  ]\n    PROP(0 <= n <= Int.max_signed)\n    LOCAL(temp _p p; temp _n (Vint (Int.repr n)); gvars 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 [ _p OF tptr tpile  ]\n    PROP(0 <= sumlist sigma <= Int.max_signed)\n    LOCAL(temp _p p)\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 [ _p OF tptr tpile  ]\n    PROP()\n    LOCAL(temp _p p; gvars 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": "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/fast/spec_fastpile.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.26863316487431166}}
{"text": "Require Import Prelude.\nRequire Import Infrastructure.\nRequire Import Regularity.\nRequire Import CanonicalForms.\nRequire Import Equations.\n\n#[export] Hint Resolve binds_empty_inv.\n\nLtac empty_binding :=\n  match goal with\n  | H: binds ?x ?v empty |- _ => apply binds_empty_inv in H; contradiction\n  | _ => fail \"no empty bindings found\"\n  end.\n\nLtac IHT e :=\n  match goal with\n  | Ht: {?Σ, ?D, ?E} ⊢(?TT) e ∈ ?T |- _ =>\n    match goal with\n    | IH: forall T, ?P0 -> {Σ, D, E} ⊢(?TT2) e ∈ T -> ?P |- _ =>\n      let H := fresh \"IHt\" in\n      assert P as H; eauto\n    end\n  end.\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    end\n  end.\n\n#[export] Hint Constructors value red.\nTheorem progress_thm : progress.\nProof.\n  unfold progress.\n  introv Typ.\n  assert (Hterm: term e).\n  1: {\n    eapply typing_implies_term; eauto.\n  }\n  apply Tgen_from_any in Typ. clear TT.\n\n  gen T Hterm.\n  induction e using trm_ind;\n    introv TypGen Hterm;\n    lets [T2 [TypReg EQ]]: inversion_typing_eq TypGen;\n    inversion TypReg;\n    inversion Hterm;\n    subst;\n    try solve [\n          left*\n        | repeat generalize_typings;\n          forwards* [Hv1 | [e1' Hred1]]: IHe1;\n          forwards* [Hv2 | [e2' Hred2]]: IHe2\n        ]; clear TypGen EQ T; try rename T2 into T.\n  - empty_binding.\n  - repeat generalize_typings.\n    forwards * [Hval | [? ?]]: IHe.\n  - generalize_typings.\n    forwards * [Hval | [? ?]]: IHe.\n    lets [T' [Typ2 EQ]]: inversion_typing_eq H0.\n    apply empty_eq_is_equivalent in EQ. subst.\n    lets* [v1 [v2 ?]]: CanonicalFormTuple Typ2; subst.\n    right*.\n  - generalize_typings.\n    forwards * [Hval | [? ?]]: IHe.\n    lets [T' [Typ2 EQ]]: inversion_typing_eq H0.\n    apply empty_eq_is_equivalent in EQ. subst.\n    lets* [v1 [v2 ?]]: CanonicalFormTuple Typ2; subst.\n    right*.\n  - repeat generalize_typings.\n    forwards * [Hval1 | [? ?]]: IHe1.\n    forwards * [Hval2 | [? ?]]: IHe2.\n    right.\n    lets [T' [Typ2 EQ]]: inversion_typing_eq H5.\n    apply empty_eq_is_equivalent in EQ. subst.\n    lets* [v1 ?]: CanonicalFormAbs Typ2; subst.\n    eexists.\n    apply* red_beta.\n  - repeat generalize_typings.\n    forwards * [Hval1 | [? ?]]: IHe.\n    right.\n    lets [T' [Typ2 EQ]]: inversion_typing_eq H1.\n    apply empty_eq_is_equivalent in EQ. subst.\n    lets* [v1 ?]: CanonicalFormTAbs Typ2; subst.\n    eexists.\n    apply* red_tbeta.\n  - repeat generalize_typings.\n    right.\n    eexists.\n    eauto.\n  - right.\n    rename l into branches.\n    repeat generalize_typings.\n    forwards * [Hval1 | [? ?]]: IHe.\n    lets [T' [Typ2 EQ]]: inversion_typing_eq H2.\n    apply empty_eq_is_equivalent in EQ; subst.\n    lets* [GCargs [cid [ctor_e ?]]]: CanonicalFormGadt Typ2; subst.\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    match goal with\n    | [ Hnth: List.nth_error ?As ?i = Some ?A |- _ ] =>\n      match goal with\n      | [ Hlen: length As = length ?Bs |- _ ] =>\n        lets* [[clA clT] [nth_cl inzip]]: nth_error_implies_zip Hnth Hlen\n      end\n    end.\n    assert (clA = length GCargs).\n    * match goal with\n      | [ H: forall def clause, List.In (def, clause) ?A -> clauseArity clause = Carity def |- _ ] =>\n        lets*: H inzip\n      end.\n    * subst.\n      eexists.\n      eauto.\nQed.\n\nCheck progress_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/Progress.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2686331648743116}}
{"text": "(* PREAMBLE *)\n\nFrom compcert.cfrontend           Require Csyntax Csem.\nFrom compcert.common              Require Values.\nFrom compcert.lib                 Require Coqlib.\n\nFrom trancert.lib                 Require All.\nFrom trancert.analysis            Require Appears ImmediatePointers.\nFrom trancert.simulations.memory  Require bijection.Def bijection.AST.\n\nImport bijection.Def common.Values Memdata Csyntax BinNums Coqlib lib.All\n       analysis.Appears analysis.ImmediatePointers bijection.AST.\n\nTheorem biject_appears:\n  forall f a b i,\n    biject_expr f a b ->\n    appears_expr i b ->\n    appears_expr i a\n  with biject_appears_exprlist:\n         forall f a b i,\n           biject_exprlist f a b ->\n           appears_exprlist i b ->\n           appears_exprlist i a.\nProof.\n  {\n    clear biject_appears.\n    intros f a b i H H0.\n    generalize dependent b.\n    induction a;intros;\n      try solve [\n            match goal with | [H: biject_expr _ _ _|-_] => inv H end; auto;\n            match goal with | [H: appears_expr _ _ |-_] => inv H end;\n            unfold ExprQuant.expr_is_var; decomp\n          |\n          match goal with | [H: biject_expr _ _ _|-_] => inv H end;\n          match goal with | [H: appears_expr _ _ |-_] => inv H end; eauto;\n          unfold ExprQuant.expr_is_var in *; decomp\n          |\n\n          match goal with | [H: biject_expr _ _ _|-_] => inv H end;\n          constructor;\n          match goal with | [H: appears_expr _ _ |-_] => inv H end; eauto; decomp;\n          [eapply IHa; eauto| unfold ExprQuant.expr_is_var in *; decomp]\n          |\n          constructor;\n          match goal with | [H: biject_expr _ _ _|-_] => inv H end;\n          match goal with | [H: appears_expr _ _ |-_] => inv H end; eauto; decomp;\n          [\n              exploit IHa1; eauto|\n              exploit IHa2; eauto|\n              unfold ExprQuant.expr_is_var in *; decomp]\n          ].\n    - inv H.\n      constructor.\n      inv H0; decomp;\n          [\n              exploit IHa1; eauto|\n              exploit IHa2; eauto|\n              exploit IHa3; eauto|\n              unfold ExprQuant.expr_is_var in *; decomp\n          ].\n    - inv H.\n      inv H0; decomp.\n      constructor; eauto.\n      + left. eapply IHa; eauto.\n      + constructor. right. eapply biject_appears_exprlist; eauto.\n      + unfold ExprQuant.expr_is_var in *; decomp.\n    - inv H. constructor. inv H0.\n      + eapply biject_appears_exprlist; eauto.\n      + unfold ExprQuant.expr_is_var in *; decomp.\n  }\n  {\n    clear biject_appears_exprlist.\n    induction a; intros; auto; inv H; auto.\n    constructor.\n    inv H0; decomp.\n    + eapply biject_appears in H1; eauto.\n    + eapply IHa in H1; eauto.\n  }\nQed.\n\n\nSection NoPointers.\n  Context (f: embedding).\n\n  Theorem biject_expr_idemp:\n    forall e, ~ expr_has_addr e -> biject_expr f e e\n    with biject_exprlist_idemp:\n           forall el, ~ exprlist_has_addr el -> biject_exprlist f el el.\n  Proof.\n    {\n      clear biject_expr_idemp.\n      induction e; intros; eauto; try solve [\n                                        by constructor\n                                      |\n                                      constructor;\n                                      [apply IHe1; contradict H; by constructor; eauto\n                                      | apply IHe2; contradict H; by constructor; eauto\n                                      ]\n                                      | constructor;\n                                        [ apply IHe1; contradict H; by constructor; eauto\n                                        | apply IHe2; contradict H; by constructor; eauto\n                                        | apply IHe3; contradict H; by constructor; eauto\n                                        ]\n                                      | constructor; eauto; eapply IHe; contradict H; by constructor\n                                      ].\n      - constructor.\n        destruct v; constructor.\n        contradict H. repeat constructor.\n      - constructor.\n        + eapply biject_exprlist_idemp; eauto.\n          contradict H; by constructor; eauto.\n        + eapply IHe.\n          contradict H; by constructor; eauto.\n      - constructor.\n        + eapply biject_exprlist_idemp; eauto.\n          contradict H; by constructor; eauto.\n      - constructor.\n        contradict H.\n        repeat constructor.\n    }\n    {\n      clear biject_exprlist_idemp.\n      induction el; constructor.\n      - eapply biject_expr_idemp; eauto.\n        contradict H; by constructor; auto.\n      - eapply IHel; eauto.\n        contradict H; by constructor; auto.\n    }\n  Qed.\n\n\n  Theorem biject_statement_idemp:\n    forall e, ~ stmt_has_addr e -> biject_statement f e e\n    with biject_labeled_statements_idemp:\n           forall el, ~ ls_has_addr el -> biject_labeled_statements f el el.\n  Proof.\n    {\n      clear biject_statement_idemp.\n      induction e; intros; eauto; try constructor;\n        try solve [ done |\n                    eapply biject_expr_idemp; by contradict H; constructor; auto|\n                    eapply IHe; contradict H; by constructor; eauto|\n                    eapply IHe1; contradict H; by constructor; eauto|\n                    eapply IHe2; contradict H; by constructor; eauto|\n                    eapply IHe3; contradict H; by constructor; eauto].\n      - destruct o.\n        econstructor.\n        + eapply biject_expr_idemp; by contradict H; constructor; auto.\n        + constructor.\n      -  eapply biject_labeled_statements_idemp.\n         contradict H.\n           by constructor; auto.\n    }\n    {\n      clear biject_labeled_statements_idemp.\n      induction el; constructor.\n      - apply biject_statement_idemp. contradict H. constructor; auto.\n      - apply IHel; contradict H. constructor; auto.\n    }\n  Qed.\n\nEnd NoPointers.\n", "meta": {"author": "sayon", "repo": "trancert", "sha": "eb5c94c75067782158522f61bdd7cc902bf74185", "save_path": "github-repos/coq/sayon-trancert", "path": "github-repos/coq/sayon-trancert/trancert-eb5c94c75067782158522f61bdd7cc902bf74185/simulations/memory/bijection/Appears.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2686331648743116}}
{"text": "Require Export DEX_ElemLemmas.\n\nImport DEX_BigStepWithTypes.DEX_BigStepWithTypes DEX_BigStep.DEX_Dom DEX_Prog.\n\nSection p.\n  Variable kobs : L.t.\n  Variable p : DEX_ExtendedProgram.\n\nLemma some_eq: forall (A:Type) (x y:A), Some x = Some y -> x = y.\nProof. intros; inversion H; auto. Qed.\n\nLemma leql_join_eq: forall (k k1 k2: L.t) , k2 = L.join k k1 -> L.leql k k2.\nProof. intros. subst; apply leql_join2; apply L.leql_refl; auto. Qed.\n\nLtac indist2_intra_normal_aux Hindistreg rn:=\n  specialize Hindistreg with rn;\n  inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist];\n  try (constructor 1 with (k:=lvl) (k':=lvl'); \n  try (rewrite MapList.get_update2; auto); auto);\n  try (constructor 2; rewrite ?DEX_Registers.get_update_old; auto).\n\nLemma indist2_intra_normal : \n forall se reg m sgn pc pc2 pc2' i r1 rt1 r1' rt1' r2 r2' rt2 rt2',\n   instructionAt m pc = Some i ->\n\n   NormalStep se reg m sgn i (pc,r1) rt1 (pc2,r2) rt2 ->\n   NormalStep se reg m sgn i (pc,r1') rt1' (pc2',r2') rt2' ->\n   st_in kobs rt1 rt1' (pc,r1) (pc,r1') ->\n\n   st_in kobs rt2 rt2' (pc2,r2) (pc2',r2').\nProof.\n  intros se reg m sgn pc pc2 pc2' i r1 rt1 r1' rt1' r2 r2' rt2 rt2'\n    Hins Hstep Hstep' Hindist.\n  destruct i; simpl in Hstep, Hstep';\n  inversion_clear Hstep in Hins Hstep' Hindist;\n  inversion_clear Hstep' in Hindist;\n  apply inv_st_in in Hindist;  \n  constructor; auto.\n  (* DEX_Move *)\n  subst.\n  inversion Hindist as [Heqset Hindistreg].\n  constructor; auto. \n  (* proving eq_set *)\n  rewrite MapList.domain_inv; auto. rewrite MapList.domain_inv; auto.\n  intros rn.\n  destruct Reg_eq_dec with (x:=rn) (y:=rt) as [Hreg | Hreg].\n    (* rn = rt *)\n    rewrite Hreg.\n    specialize Hindistreg with (rn:=rs).  \n    inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist]. \n    constructor 1 with (k:=L.join k0 (se pc)) (k':=L.join k1 (se pc)); \n      try (rewrite MapList.get_update1; auto); auto.\n    rewrite Hget in H7; inversion H7; subst; apply not_leql_join1; auto.\n    rewrite Hget' in H17; inversion H17; subst; apply not_leql_join1; auto.\n    constructor 2. rewrite <- H5 in Hvalueindist; rewrite <- H15 in Hvalueindist.\n    rewrite ?DEX_Registers.get_update_new; auto.\n    (* rn <> rt *) \n    indist2_intra_normal_aux Hindistreg rn.\n  (* DEX_Const *)\n  subst.\n  inversion Hindist as [Heqset Hindistreg].\n  constructor; auto.\n  (* proving eq_set *)\n  rewrite MapList.domain_inv; auto. rewrite MapList.domain_inv; auto.\n  intros rn. \n  destruct Reg_eq_dec with (x:=rn) (y:=rt) as [Hreg | Hreg].\n    (* rn = rt *)\n    rewrite Hreg.\n    constructor 2.\n    rewrite ?DEX_Registers.get_update_new.\n    constructor 1. constructor.\n    (* rn <> rt *) \n    indist2_intra_normal_aux Hindistreg rn.\n  (* DEX_Ineg *)\n  subst.\n  inversion Hindist as [Heqset Hindistreg].\n  constructor; auto.\n  (* proving eq_set *)\n  rewrite MapList.domain_inv; auto. rewrite MapList.domain_inv; auto.\n  intros rn. \n  destruct Reg_eq_dec with (x:=rn) (y:=rt) as [Hreg | Hreg].\n    (* rn = rt *)\n    rewrite Hreg.\n    specialize Hindistreg with (rn:=rs).  \n    inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist]. \n    constructor 1 with (k:=L.join k (se pc)) (k':=L.join k0 (se pc)); \n      try (rewrite MapList.get_update1; auto); auto.\n    rewrite Hget in H5; inversion H5; subst; apply not_leql_join1; auto.\n    rewrite Hget' in H14; inversion H14; subst; apply not_leql_join1; auto.\n    constructor 2. rewrite <- H4 in Hvalueindist; rewrite <- H13 in Hvalueindist.\n    rewrite ?DEX_Registers.get_update_new; auto.\n    inversion Hvalueindist. inversion H15. constructor 1; constructor.\n    (* rn <> rt *) \n    indist2_intra_normal_aux Hindistreg rn.\n  (* DEX_Inot *)\n  subst.\n  inversion Hindist as [Heqset Hindistreg].\n  constructor; auto.\n  (* proving eq_set *)\n  rewrite MapList.domain_inv; auto. rewrite MapList.domain_inv; auto.\n  intros rn. \n  destruct Reg_eq_dec with (x:=rn) (y:=rt) as [Hreg | Hreg].\n    (* rn = rt *)\n    rewrite Hreg.\n    specialize Hindistreg with (rn:=rs).  \n    inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist]. \n    constructor 1 with (k:=L.join k (se pc)) (k':=L.join k0 (se pc)); \n      try (rewrite MapList.get_update1; auto); auto.\n    rewrite Hget in H5; inversion H5; subst; apply not_leql_join1; auto.\n    rewrite Hget' in H14; inversion H14; subst; apply not_leql_join1; auto.\n    constructor 2. rewrite <- H4 in Hvalueindist; rewrite <- H13 in Hvalueindist.\n    rewrite ?DEX_Registers.get_update_new; auto.\n    inversion Hvalueindist. inversion H15. constructor 1; constructor.\n    (* rn <> rt *) \n    indist2_intra_normal_aux Hindistreg rn.\n  (* DEX I2b *)\n  subst.\n  inversion Hindist as [Heqset Hindistreg].\n  constructor; auto.\n  (* proving eq_set *)\n  rewrite MapList.domain_inv; auto. rewrite MapList.domain_inv; auto.\n  intros rn. \n  destruct Reg_eq_dec with (x:=rn) (y:=rt) as [Hreg | Hreg].\n    (* rn = rt *)\n    rewrite Hreg.\n    specialize Hindistreg with (rn:=rs).  \n    inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist]. \n    constructor 1 with (k:=L.join k (se pc)) (k':=L.join k0 (se pc)); \n      try (rewrite MapList.get_update1; auto); auto.\n    rewrite Hget in H5; inversion H5; subst; apply not_leql_join1; auto.\n    rewrite Hget' in H14; inversion H14; subst; apply not_leql_join1; auto.\n    constructor 2. rewrite <- H4 in Hvalueindist; rewrite <- H13 in Hvalueindist.\n    rewrite ?DEX_Registers.get_update_new; auto.\n    inversion Hvalueindist. inversion H15. constructor 1; constructor.\n    (* rn <> rt *) \n    indist2_intra_normal_aux Hindistreg rn.\n  (* DEX_I2s *)\n  subst.\n  inversion Hindist as [Heqset Hindistreg].\n  constructor; auto.\n  (* proving eq_set *)\n  rewrite MapList.domain_inv; auto. rewrite MapList.domain_inv; auto.\n  intros rn. \n  destruct Reg_eq_dec with (x:=rn) (y:=rt) as [Hreg | Hreg].\n    (* rn = rt *)\n    rewrite Hreg.\n    specialize Hindistreg with (rn:=rs).  \n    inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist]. \n    constructor 1 with (k:=L.join k (se pc)) (k':=L.join k0 (se pc)); \n      try (rewrite MapList.get_update1; auto); auto.\n    rewrite Hget in H5; inversion H5; subst; apply not_leql_join1; auto.\n    rewrite Hget' in H14; inversion H14; subst; apply not_leql_join1; auto.\n    constructor 2. rewrite <- H4 in Hvalueindist; rewrite <- H13 in Hvalueindist.\n    rewrite ?DEX_Registers.get_update_new; auto.\n    inversion Hvalueindist. inversion H15. constructor 1; constructor.\n    (* rn <> rt *) \n    indist2_intra_normal_aux Hindistreg rn.\n  (* DEX_IBinop *)\n  subst.\n  inversion Hindist as [Heqset Hindistreg].\n  constructor; auto.\n  (* proving eq_set *)\n  rewrite MapList.domain_inv; auto. rewrite MapList.domain_inv; auto.\n  intros rn. \n  destruct Reg_eq_dec with (x:=rn) (y:=rt) as [Hreg | Hreg].\n    (* rn = rt *)\n    rewrite Hreg.\n    assert (Hindistreg' := Hindistreg).\n    specialize Hindistreg with (rn:=ra).\n    specialize Hindistreg' with (rn:=rb).  \n    inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist]. \n    constructor 1 with (k:=L.join k1 (L.join k2 (se pc))) (k':=L.join k0 (L.join k3 (se pc))); \n      try (rewrite MapList.get_update1; auto); auto.\n    rewrite Hget in H8; inversion H8; subst; apply not_leql_join1; auto.\n    rewrite Hget' in H21; inversion H21; subst; apply not_leql_join1; auto.\n    (* case of register b *)\n    inversion Hindistreg' as [lvl2 lvl2' Hget2 Hget2' Hleq2 Hleq2' | Hvalueindist'].\n    constructor 1 with (k:=L.join k1 (L.join k2 (se pc))) (k':=L.join k0 (L.join k3 (se pc))); \n      try (rewrite MapList.get_update1; auto); auto.\n    rewrite Hget2 in H9; inversion H9; subst.\n    apply not_leql_join2; apply not_leql_join1; auto.\n    rewrite Hget2' in H22; inversion H22; subst.\n    apply not_leql_join2; apply not_leql_join1; auto.\n    constructor 2. \n    rewrite ?DEX_Registers.get_update_new.\n    rewrite <- H6 in Hvalueindist; rewrite <- H19 in Hvalueindist.\n    rewrite <- H7 in Hvalueindist'; rewrite <- H20 in Hvalueindist'.\n    inversion Hvalueindist as [v v' Hin | Hnone]; inversion Hvalueindist' as [v2 v2' Hin' | Hnone']; \n    inversion Hin; inversion Hin'. repeat (constructor); auto.\n    (* rn <> rt *) \n    indist2_intra_normal_aux Hindistreg rn.\n  (* DEX_IBinopConst *)\n  subst.\n  inversion Hindist as [Heqset Hindistreg].\n  constructor; auto.\n  (* proving eq_set *)\n  rewrite MapList.domain_inv; auto. rewrite MapList.domain_inv; auto.\n  intros rn. \n  destruct Reg_eq_dec with (x:=rn) (y:=rt) as [Hreg | Hreg].\n    (* rn = rt *)\n    rewrite Hreg.\n    specialize Hindistreg with (rn:=r).\n    inversion Hindistreg as [lvl lvl' Hget Hget' Hleq Hleq' | Hvalueindist]. \n    constructor 1 with (k:=L.join k (se pc)) (k':=L.join k0 (se pc)); \n      try (rewrite MapList.get_update1; auto); auto.\n    rewrite Hget in H5; inversion H5; subst; apply not_leql_join1; auto.\n    rewrite Hget' in H14; inversion H14; subst; apply not_leql_join1; auto.\n    constructor 2. \n    rewrite ?DEX_Registers.get_update_new.\n    rewrite <- H4 in Hvalueindist; rewrite <- H13 in Hvalueindist. \n    inversion Hvalueindist as [val val' Hin | Hnone]; inversion Hin;\n    repeat (constructor); auto.\n    (* rn <> rt *) \n    indist2_intra_normal_aux Hindistreg rn.\n\nQed.\n\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_I/DEX_ElemLemmaNormalIntra2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.26863315835217727}}
{"text": "Load loadpath.\nRequire Import ZArith Coq.Lists.List Permutation.\nRequire Import msl.Axioms.\nRequire Import msl.predicates_sa.\nRequire Import veric.Coqlib2.\nRequire Import veristar.variables veristar.datatypes veristar.clauses\n               veristar.list_denote veristar.model_type veristar.model\n               veristar.basic veristar.compare.\n\nModule Type SPRED_LEMMAS.\nDeclare Module VSM : VERISTAR_MODEL.\nImport VSM VeriStarLogic.\n\nEnd SPRED_LEMMAS.\n\nModule SPredLemmas (VSM : VERISTAR_MODEL) <: SPRED_LEMMAS\n  with Module VSM := VSM.\nModule VSM := VSM.\nImport VSM VeriStarLogic.\n\nImport sepalg.\n\n(* properties of spred operators *)\n\nModule spred. Section spred.\nVariables x y z : spred.\n\nLocal Open Scope pred.\n\nLemma andpN : x && TT = x.\nProof. apply andp_TT. Qed.\n\nLemma andpS : x && y = y && x.\nProof. apply andp_comm. Qed.\n\nLemma andpA : x && (y && z) = (x && y) && z.\nProof. rewrite andp_assoc; auto. Qed.\n\nLemma orpN : x || FF = x.\nProof.\nextensionality; apply prop_ext; split; [solve[intros [H|H]; [auto|case H]; auto]\n|solve[left; auto]].\nQed.\n\nLemma orpS : x || y = y || x.\nProof. apply union_com. Qed.\n\nLemma orpA : x || (y || z) = (x || y) || z.\nProof. rewrite union_assoc; auto. Qed.\n\nLemma sepconS : sepcon x y = sepcon y x.\nProof. apply sepcon_comm. Qed.\n\nLemma sepconA : x * (y * z) = (x * y) * z.\nProof. rewrite sepcon_assoc; auto. Qed.\n\nEnd spred. End spred.\n\nLemma emp_sep_emp h h1 h2 : join h h1 h2 -> emp h -> emp h1 -> emp h2.\nProof. intros; rewrite <-(emp_sepcon emp); exists h; exists h1; split; auto. Qed.\n\nLemma space_denote_permute l l' :\n  Permutation l l' -> space_denote l = space_denote l'.\nProof.\nintros;\napply (listd_perm space_atom_denote _ emp spred.sepconS spred.sepconA l l' H).\nQed.\n\nLemma space_insert sa l :\n  space_denote (insert (rev_cmp compare_space_atom) sa l) =\n  space_denote (sa :: l).\nProof.\nintros; eapply listd_perm;\n[apply spred.sepconS|apply spred.sepconA|apply perm_insert].\nQed.\n\nLemma eq_space_atomlist_sound (al bl : list space_atom) :\n  true = eq_space_atomlist al bl ->\n  space_denote al = space_denote bl.\nProof.\nintros H; unfold eq_space_atomlist, isEq in H.\nremember (compare_list compare_space_atom al bl) as j; destruct j; inversion H.\nsolve[apply comp_eq in Heqj; subst; auto].\nQed.\n\nLemma expr_eq_eq' : forall e1 e2, true = expr_eq e1 e2 -> e1=e2.\nProof.\nunfold expr_eq; intros; do_comp expr_cspec e1 e2; subst; auto; congruence.\nQed.\n\nLemma pure_atom_denote_order_eqv_pure_atom : forall a,\n  pure_atom_denote a = pure_atom_denote (order_eqv_pure_atom a).\nProof.\nintros; destruct a; unfold pure_atom_denote in *; simpl in *.\nremember (expr_cmp e e0) as b; destruct b; try reflexivity.\nsolve[apply var_eq_sym'].\nQed.\n\nLemma list_denote_normalize_pure_atoms:\n forall Q (B:spred) (l:list pure_atom)\n     (Qassoc: forall x y z , Q x (Q y z) = Q (Q x y) z)\n     (Qsymm: forall x y, Q x y = Q y x)\n     (Hcmp: forall x y, Eq = pure_atom_cmp x y ->\n                        (forall P, Q (pure_atom_denote x) (Q (pure_atom_denote y) P) = Q (pure_atom_denote y) P)),\nlist_denote pure_atom_denote Q B l =\nlist_denote pure_atom_denote Q B (normalize_atoms l).\nProof.\nintros.\nunfold normalize_atoms.\n  rewrite listd_sort_uniq.\n    rewrite listd_map.\n      reflexivity.\n      intros. rewrite <- pure_atom_denote_order_eqv_pure_atom. trivial.\n      apply Qsymm.\n      apply Qassoc.\n    apply Hcmp.\nQed.\n\nLemma union_contractive:\nforall {A} x, (@orp A) x x = x.\nProof.\nintros. unfold orp.\nextensionality a. apply prop_ext. split; intros.\n destruct H; assumption. left; assumption.\nQed.\n\nLemma list_denote_union_normalize_pure_atoms:\n forall(B:spred) (l:list pure_atom),\nlist_denote pure_atom_denote (@orp state) B l =\nlist_denote pure_atom_denote (@orp state) B (normalize_atoms l).\nProof.\nintros.\napply list_denote_normalize_pure_atoms.\n  intros. rewrite union_assoc; trivial.\n  intros. rewrite union_com; trivial.\n  intros. rewrite <- pure_atom_cmp_eq in H. rewrite H.\n      rewrite <- union_assoc.\n      rewrite union_contractive. reflexivity.\nQed.\n\nLemma intersection_contractive:\nforall {A} x, (@andp A) x x = x.\nProof.\nintros. unfold andp.\nextensionality a. apply prop_ext. split; intros. destruct H; assumption. split; assumption.\nQed.\n\nLemma list_denote_intersection_normalize_pure_atoms:\n forall(B:spred) (l:list pure_atom),\nlist_denote pure_atom_denote (@andp state) B l =\nlist_denote pure_atom_denote (@andp state) B (normalize_atoms l).\nProof.\nintros.\napply list_denote_normalize_pure_atoms.\n  intros. rewrite andp_assoc; trivial.\n  intros. rewrite andp_comm; trivial.\n  intros.\n  rewrite <- pure_atom_cmp_eq in H. rewrite H.\n      rewrite <- andp_assoc.\n      rewrite intersection_contractive. reflexivity.\nQed.\n\nLemma expr_cmp_eq: forall e e',\n  expr_cmp e e' = Eq -> (e === e') = TT.\nProof.\nintros.\nextensionality s; apply prop_ext.\nsplit; intros; trivial.\nclear H0.\ndestruct e; simpl.\n  destruct e'; simpl. reflexivity. inversion H.\n  destruct e'; simpl. inversion H.\n    inversion H.\nsymmetry in H. apply comp_eq in H; auto.\ninversion H; subst; reflexivity.\nQed.\n\nLemma expr_cmp_eq': forall e e' s,\n  expr_cmp e e' = Eq -> (e === e') s.\nProof.\nintros.\nrewrite (expr_cmp_eq _ _ H). trivial.\nQed.\n\nLemma list_denote_intersection_filter_nonreflex:\n forall(B:spred) (l:list pure_atom),\nlist_denote pure_atom_denote (@andp state) B l =\nlist_denote pure_atom_denote (@andp state) B (filter nonreflex_atom l).\nProof.\nintros.\ninduction l; simpl. reflexivity.\nrewrite IHl. clear IHl.\nremember (nonreflex_atom a) as b; destruct b; simpl.\n  reflexivity.\ndestruct a; simpl in *.\n  assert (expr_cmp e e0 = Eq).\n    remember (expr_cmp e e0) as b; destruct b; try reflexivity.\n    inversion Heqb. inversion Heqb.\n  clear Heqb.\nrewrite (expr_cmp_eq _ _ H). rewrite TT_and. reflexivity.\nQed.\n\nLemma list_denote_normalize_filter_nonreflex_atom:\nforall B l,\nlist_denote pure_atom_denote (@andp state) B\n            (normalize_atoms (filter nonreflex_atom l))\n= list_denote pure_atom_denote (@andp state) B l.\nProof.\nintros.\nrewrite <- list_denote_intersection_normalize_pure_atoms.\nrewrite <- list_denote_intersection_filter_nonreflex; reflexivity.\nQed.\n\nLemma list_denote_inter_app : forall {A} (f: A -> spred) cs1 cs2 s,\n  list_denote f (@andp state) TT (cs1 ++ cs2) s ->\n  (list_denote f (@andp state) TT cs1 s /\\\n   list_denote f (@andp state) TT cs2 s).\nProof.\nintros A f.\ninduction cs1; simpl; intros.\n  split. trivial. assumption.\ndestruct H as [H1 H2].\n destruct (IHcs1 _ _ H2) as [H3 H4].\n split. split; assumption. assumption.\nQed.\n\nLemma list_denote_assoc_sym_id : forall {A T} (E: A -> T) Q B C l\n  (CID : forall x, Q x C = x)\n  (QSYM : forall x y, Q x y = Q y x)\n  (QASSOC : forall x y z, Q x (Q y z) = Q (Q x y) z),\n  list_denote E Q B l = Q B (list_denote E Q C l).\nProof.\nintros.\ninduction l; simpl; intros; auto.\nrewrite IHl. rewrite QSYM. rewrite <- QASSOC.\npattern (Q (list_denote E Q C l) (E a)).\nrewrite QSYM. auto.\nQed.\n\nLemma list_denote_union_left : forall {A} (f: A -> spred) cs1 cs2 s,\n  list_denote f (@orp state) FF cs1 s ->\n  list_denote f (@orp state) FF (cs1 ++ cs2) s.\nProof.\nintros.\nrewrite listd_app.\nrewrite (@listd_unfold_un _ state).\nleft. assumption.\nQed.\n\nLemma list_denote_union_right : forall {A} (f: A -> spred) cs1 cs2 s,\n  list_denote f (@orp state) FF cs2 s ->\n  list_denote f (@orp state) FF (cs1 ++ cs2) s.\nProof.\nintros.\nrewrite listd_app.\nrewrite (@listd_unfold_un _ state).\nright. assumption.\nQed.\n\nLemma list_denote_sepcon_sort :\n  forall {A} (E:A -> spred) (B:spred) (l:list A) cmp s,\n    list_denote E sepcon B l s <->\n    list_denote E sepcon B (rsort cmp l) s.\nProof.\nintros.\nrewrite (listd_sort). split; trivial.\nintros; rewrite sepcon_comm; auto.\nintros; rewrite sepcon_assoc; auto.\nQed.\n\nLemma empty_not_singleton: forall c, M.empty <> M.singleton c.\n Proof. intros. intro.\n   contradiction (@M.empty_spec c).\n   rewrite H. rewrite M.singleton_spec. auto.\nQed.\n\nLemma singleton_inv:\n  forall x y, M.singleton x = M.singleton y -> x=y.\nProof.\nintros.\napply (M.singleton_spec y).\nrewrite <- H. apply M.singleton_spec. auto.\nQed.\n\nLemma elements_singleton: forall c, M.elements (M.singleton c) = [c].\nProof.\nintros.\nassert (X:= M.singleton_spec c).\nassert (ND := M.elements_spec2w (M.singleton c)).\ninversion ND; clear ND.\n  apply False_ind.\n  remember (M.elements (M.singleton c)) as l.\n  destruct l.\n    apply eq_sym in Heql.\n    apply empty_set_elems' in Heql.\n    unfold M.Empty in Heql. apply (Heql c). apply X. trivial.\n  inversion H0.\nassert (x = c).\n  apply X. rewrite <- elements_In. rewrite <- H. left. trivial.\nsubst.\ndestruct l. trivial.\nassert (c0 = c).\n  apply X. rewrite <- elements_In. rewrite <- H. right. left. trivial.\nsubst. exfalso. apply H0. left. trivial.\nQed.\n\nLemma var_eq_Next: forall e e' g g' s, (e === e') s -> (g === g') s ->\nspace_atom_denote (Next e g) s = space_atom_denote (Next e' g') s.\nProof.\nintros; simpl.\napply prop_ext; split; intros.\n  rewrite H in H1. rewrite H0 in H1. assumption.\n  rewrite H. rewrite H0. assumption.\nQed.\n\nLemma var_eq_Lseg1: forall e e' g s, (e === e') s ->\nspace_atom_denote (Lseg e g) s = space_atom_denote (Lseg e' g) s.\nProof.\nintros; simpl.\nrewrite H; auto.\nQed.\n\nLemma var_eq_Lseg2: forall g e e' s, (e === e') s ->\nspace_atom_denote (Lseg g e) s = space_atom_denote (Lseg g e') s.\nProof.\nintros; simpl.\nrewrite H; auto.\nQed.\n\nLemma var_eq_Lseg: forall e e' g g' s, (e === e') s -> (g === g') s ->\nspace_atom_denote (Lseg e g) s = space_atom_denote (Lseg e' g') s.\nProof.\nintros.\neapply eq_trans. apply var_eq_Lseg2. apply H0.\napply var_eq_Lseg1. apply H.\nQed.\n\nLemma join_stacks_eq : forall s0 s1 s : state,\n  join s0 s1 s -> stk s0=stk s1 /\\ stk s0=stk s.\nProof.\nintros.\ndestruct H. destruct H.\nsubst; split; auto.\ntransitivity (stk s1); auto.\nQed.\n\nLemma expr_denote_join: forall e s r t,\njoin s r t -> expr_denote e t = expr_denote e s.\nProof.\nintros.\ndestruct e; simpl in H; simpl; intros. trivial.\ndestruct (join_stacks_eq _ _ _ H) as [_ D].\nrewrite <- D. trivial.\nQed.\n\nLemma expr_denote_eq_dec_loc:\n   forall x y s,\n        nil_or_loc (expr_denote x s) ->\n        Decidable.decidable (expr_denote x s = expr_denote y s).\nProof.\nintros.\ndestruct H.\nrewrite H.\ndestruct (nil_dec (expr_denote y s)); [left | right]; auto.\ndestruct H as [l ?].\ncase_eq (val2loc (expr_denote y s)); intros.\ndestruct (loc_eq_dec l l0).\nleft; subst.\neapply val2loc_inj; eauto.\nright.\ncontradict H1. rewrite H1 in *. congruence.\nright.\nintro.\nrewrite H1 in *; congruence.\nQed.\n\nLemma expr_denote_heap_ind : forall x s h h',\n  expr_denote x (State s h)=expr_denote x (State s h').\nProof.\nintros. destruct x; auto.\nQed.\n\nLemma state_join_var_eq : forall (s0 s1 s : state) x y,\n  join s0 s1 s ->\n  (x === y) s0 ->\n  (x === y) s.\nProof.\nintros.\ndestruct s; destruct s0; destruct s1. destruct H. simpl in *. destruct H.\nunfold var_eq in *; subst; auto.\nQed.\n\nLemma state_join_var_eq' : forall (s0 s1 s : state) x y,\n  join s0 s1 s ->\n  (x === y) s ->\n  (x === y) s0.\nProof.\nintros.\ndestruct s; destruct s0; destruct s1. destruct H. simpl in *. destruct H.\nunfold var_eq in *; subst; auto.\nQed.\n\nLemma unXX {A:Type} (P: pred A) b : un P (un P b) = un P b.\nProof.\nextensionality a; apply prop_ext; split; firstorder.\nQed.\n\nLemma lseg_appN: forall x y s r t,\n lseg x y s -> lseg y nil_val r -> join s r t -> lseg x nil_val t.\nProof.\nintros.\nrevert r H0 t H1; induction H; intros.\napply join_unit1_e in H2; auto. subst; auto.\nspecialize (IHlseg _ H4).\ndestruct (join_assoc H3 H5) as [hf [? ?]].\nspecialize (IHlseg _ H6).\neconstructor 2; eauto.\nintro; subst. rewrite nil_not_loc in H0; inversion H0.\nQed.\n\nLemma pure_atom_denote_heap_ind: forall a s h h',\npure_atom_denote a (State s h) = pure_atom_denote a (State s h').\nProof.\nintros.\ndestruct a; simpl.\nunfold var_eq. simpl.\nrewrite (expr_denote_heap_ind e s h h').\nrewrite (expr_denote_heap_ind e0 s h h').\nreflexivity.\nQed.\n\nLemma pure_atoms_denote_intersection_heap_ind: forall Delta s h h',\nlist_denote pure_atom_denote (@andp state) TT Delta (State s h) =\nlist_denote pure_atom_denote (@andp state) TT Delta (State s h').\nProof.\nintros Delta.\ninduction Delta; simpl; intros.\n  reflexivity.\napply prop_ext.\nsplit; intros; destruct H.\n  split. rewrite <- (pure_atom_denote_heap_ind a s h h'). assumption.\n  rewrite <- (IHDelta s h h'). assumption.\nsplit. rewrite (pure_atom_denote_heap_ind a s h h'). assumption.\n  rewrite (IHDelta s h h'). assumption.\nQed.\n\nLemma pure_atoms_denote_union_heap_ind: forall Delta s h h',\nlist_denote pure_atom_denote (@orp state) FF Delta (State s h) =\nlist_denote pure_atom_denote (@orp state) FF Delta (State s h').\nProof.\nintros Delta.\ninduction Delta; simpl; intros.\n  reflexivity.\napply prop_ext.\nsplit; intros; destruct H.\n  left. rewrite <- (pure_atom_denote_heap_ind a s h h'). assumption.\n  right. rewrite <- (IHDelta s h h'). assumption.\nleft. rewrite (pure_atom_denote_heap_ind a s h h'). assumption.\n  right. rewrite (IHDelta s h h'). assumption.\nQed.\n\nLemma lseg_nil_or_loc:\n  forall x y h, lseg x y h -> nil_or_loc y.\nProof.\ninduction 1; auto.\nQed.\n\nLemma lseg_end: forall x y h,\n  lseg x y h -> (x = y /\\ emp h) \\/ y = nil_val \\/\n     (exists l, val2loc y = Some l /\\ emp_at l h).\nProof.\ninduction 1; intros; auto.\nright.\ndestruct IHlseg as [[? ?] | [?|[l [? ?]]]]; auto.\nsubst.\napply join_unit2_e in H3; auto. subst h0.\napply lseg_nil_or_loc in H2.\nclear H5.\ndestruct H2; auto; right.\ndestruct H2 as [l ?]; exists l.\nsplit; auto.\napply (rawnext_out H1 H2).\ncontradict H.\nsubst l.\napply val2loc_inj with x'; auto.\nright; exists l.\nsplit; auto.\napply emp_at_join with l in H3.\napply H3. split; auto.\nassert (l<>x') by (contradict H; subst; eapply val2loc_inj; eauto).\neapply rawnext_out; eauto.\nQed.\n\nLemma lseg_lseg_app: forall x y z h1 h2 h tz,\n  lseg x y h1 ->\n  lseg y z h2 ->\n  join h2 h1 h ->\n val2loc z = Some tz ->\n  emp_at tz h ->\n  lseg x z h.\nProof.\nintros.\nrevert z h2 H0 h H1 tz H2 H3; induction H; intros.\napply join_unit2_e in H2; auto; subst; auto.\nspecialize (IHlseg _ _ H4).\ndestruct (join_assoc H3 (join_comm H5)) as [hf [? ?]].\nspecialize (IHlseg _ (@join_comm _ _ Perm_heap _ _ _ H8) _ H6).\nassert (emp_at tz hf). apply emp_at_join with tz in H9. apply H9 in H7. destruct H7; auto.\nspecialize (IHlseg H10).\neapply lseg_cons; eauto.\nintro; subst z0.\nassert (x'=tz) by congruence. subst x'.\nclear H6.\napply emp_at_join with tz in H9.\napply H9 in H7. destruct H7.\nclear - H1 H6. eapply rawnext_not_emp; eauto.\neapply rawnext2rawnext'; eauto.\nQed.\n\nLemma Space_denote_cons: forall a L,\nspace_denote (a::L) = sepcon (space_atom_denote a) (space_denote L).\nProof.\nintros.\napply listd_cons.\nQed.\n\nLemma Space_denote_app: forall M L,\nspace_denote (M ++ L) = sepcon (space_denote M) (space_denote L).\nProof.\nintros M.\ninduction M; simpl.\n  intros. rewrite (emp_sepcon (space_denote L)). trivial.\nintros.\n  rewrite (IHM L). rewrite sepconA; auto with typeclass_instances.\nQed.\n\nLemma Space_denote_rev: forall L,\nspace_denote (rev L) = (space_denote L).\nProof.\nintros.\napply space_denote_permute. apply Permutation_sym.  apply Permutation_rev.\nQed.\n\nEnd SPredLemmas.\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/veristar/spred_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2686331583521772}}
{"text": "From mathcomp\nRequire Import ssreflect ssrbool ssrnat eqtype ssrfun seq.\nFrom fcsl\nRequire Import pred.\nFrom scilla\nRequire Import Automata2.\nFrom scilla\nRequire Import options.\n\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(* Parameters *)\nVariable init_owner : address.\nVariable init_max_block : nat.\nVariable init_goal : value.\n\n(* Initial state *)\nDefinition init_state := CS (init_owner, init_max_block, init_max_block) [::] false.\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\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\n   \nDefinition balance_backed (st: cstate crowdState) : Prop :=\n  (* If the campaign not funded... *)\n  ~~ (funded (state st)) ->\n  (* the contract has enough funds to reimburse everyone. *)\n  sumn (map snd (backers (state st))) <= balance st.\n\nLemma sufficient_funds_safe : safe crowd_prot balance_backed.\nProof.\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|].\n- by rewrite subn0; apply: (leq_trans Hi (leq_addr (val m) bal)).\ncase: ifP=>/=_; move=> {}/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]; last first.\n- by rewrite subn0; apply: (leq_trans Hi (leq_addr (val m) bal)).\ncase: ifP=>//=_; move=> {}/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|].\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.\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": "Zilliqa", "repo": "scilla-coq", "sha": "41f2166a91de19e79fefba45bff207b6fd2b941d", "save_path": "github-repos/coq/Zilliqa-scilla-coq", "path": "github-repos/coq/Zilliqa-scilla-coq/scilla-coq-41f2166a91de19e79fefba45bff207b6fd2b941d/Contracts/Crowdfunding.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.26863315835217716}}
{"text": "From Undecidability Require Import TM.Util.TM_facts TM.Util.Relations.\nFrom Undecidability.L Require Import LM_heap_def UnfoldClos Programs.\nFrom Undecidability.L Require Import LambdaDepth.\n\nSet Default Proof Using \"Type\".\nRequire Import FunInd.\n\nLemma lookup_el H alpha x c: lookup H alpha x = Some c -> exists beta, Some (c,beta) el H.\nProof.\n  induction x in alpha, c|-*.\n  all:cbn. all:destruct nth_error as [[[] | ]| ] eqn:eq.\n  all:intros [= eq'].\n  1:subst.\n  all:eauto using nth_error_In.\nQed.\n\nDefinition boundHeap (H:Heap) maxPro maxVar maxDepth:=\n  (forall a P beta, Some ((a,P),beta) el H ->\n    sizeP P <= maxPro /\\ a <= length H /\\ beta <= length H /\\ lambdaDepthP 1 P <= maxDepth/\\ largestVarP P <= maxVar ).\n\nDefinition unfoldTailRecStep_sizes (H:Heap) maxPro maxVar maxDepth: list (HClos * nat) -> Prop :=\n  fun stack =>\n    forall a P k, ((a,P),k) el stack\n      -> sizeP P <= maxPro\n      /\\ a <= length H\n      /\\ largestVarP P <= maxVar\n      /\\ lambdaDepthP k P <= maxDepth + 1.\n\nLemma unfoldTailRecStep_sizes_correct' H maxPro maxVar maxDepth a k s P s' stack stack' res fuel :\n  boundHeap H maxPro maxVar maxDepth\n  -> LM_heap_correct.unfolds H a k s s'\n  -> ARS.pow (fun a b => inl b = unfoldTailRecStep H a) fuel ((a,compile s++P,k)::stack,res) stack'\n  -> (sizeP (compile s++P) <= maxPro /\\ a <= length H /\\ largestVarP (compile s++P) <= maxVar /\\ lambdaDepthP k ((compile s++P)) <= maxDepth)\n  -> (unfoldTailRecStep_sizes H maxPro maxVar maxDepth stack)\n  -> (exists fuel', fuel' < fuel /\\ \n      ARS.pow (fun a b => inl b = unfoldTailRecStep H a) fuel' ((a,P,k)::stack,rev (compile s')++res) stack')\n     \\/ unfoldTailRecStep_sizes H maxPro maxVar maxDepth (fst stack').\nProof.\n  intros HH.\n  revert a k s P s' stack stack' res.\n  induction fuel as [fuel IH] using lt_wf_ind.\n  intros ? ? ? ? ? ? ? ? Hunf HR Hhd Htl.\n  destruct fuel as [|fuel].\n  {hnf in HR. subst stack'. cbn [fst]in *. right. intros ? ? ? [[= <- <- <-]|]. all:now eauto. }\n  change (S fuel) with (1+fuel) in *. eapply pow_add in HR as (stack''&Hstep%(rcomp_1)&HR).\n  symmetry in Hstep. \n  induction Hunf in P,stack,Hstep,Hhd,Htl|-*. 1-3:cbn in Hstep.\n  - destruct (Nat.leb_spec k n). now exfalso;nia.\n    injection Hstep as [= <-]. left. eauto.\n  - destruct (Nat.leb_spec k n). 2: now exfalso;nia.\n    rewrite H1 in Hstep. injection Hstep as [= <-]. inv H2. inv Hunf.\n    destruct (lookup_el H1) as (?&Hel). hnf in HH. specialize HH with (1:= Hel) as (?&?&?&?&?).\n    specialize IH with (2:= H5) (P:=[]) as IH'. rewrite app_nil_r in IH'. specialize IH' with (2:=HR) as [(fuel'&?&IH')|IH'].\n    + nia.\n    + specialize (lambdaDepthP_min 1 (compile s0)). repeat simple apply conj;try nia.\n    + hnf. intros ? ? ? [[= <- <- <-]|]. 2:now eauto. \n      specialize (lambdaDepthP_min k P).  \n      cbn - [max] in Hhd|-*. repeat simple apply conj;try nia.\n    + destruct fuel' as [|fuel'].\n      {\n        hnf in IH'. subst stack'. right. hnf;cbn. intros ? ? ? [[= <- <- <-] | [[= <- <- <-]| ]].\n        3:now eauto. { cbn. unfold sizeP in *. nia. }\n        cbn - [max] in Hhd|-*. unfold sizeP, largestVarP in *. specialize (lambdaDepthP_min k P). repeat simple apply conj;try nia.\n      }\n      change (S fuel') with (1+fuel') in *. eapply pow_add in IH' as (stack''&Hstep%(rcomp_1)&IH').\n      cbn in Hstep. injection Hstep as [=->].\n      destruct fuel' as [|fuel'].\n      {\n        hnf in IH'. subst stack'. right. hnf;cbn. intros ? ? ? [[= <- <- <-]| ].\n        2:now eauto.\n        cbn - [max] in Hhd|-*. unfold sizeP, largestVarP in *. specialize (lambdaDepthP_min k P). repeat simple apply conj;try nia.\n      }\n      change (S fuel') with (1+fuel') in *. eapply pow_add in IH' as (stack''&Hstep%(rcomp_1)&IH').\n      cbn in Hstep. injection Hstep as [=->].\n      cbn. autorewrite with list;cbn. left;eexists;split. 2:eassumption. nia.\n    +now right.\n  - injection Hstep as [= <-]. cbn in Hhd. rewrite <- app_assoc in HR,Hhd.\n    specialize IH with (2:=Hunf) (3:=HR) as [(fuel'&?&IH')|IH'].\n    + nia.\n    + cbn in Hhd|-*. unfold sizeP,largestVarP. nia.\n    + easy.\n    + cbn in Hhd|-*. autorewrite with list in Hhd|-*. rewrite lambdaDepthP_compile', maxl_app in Hhd. cbn - [max]in Hhd|-*.\n      destruct fuel' as [|fuel'].\n      {\n        hnf in IH'. subst stack'. right. hnf;cbn. intros ? ? ? [[= <- <- <-]| ].\n        2:now eauto.\n        cbn - [max] in Hhd|-*. unfold sizeP in *. repeat simple apply conj;try nia.\n      }\n      change (S fuel') with (1+fuel') in *. eapply pow_add in IH' as (stack''&Hstep%(rcomp_1)&IH').\n      cbn in Hstep. injection Hstep as [=->].\n      left;do 2 eexists. 2:eassumption. nia. \n    + easy.\n  - cbn [compile] in Hstep,Hhd. rewrite <- !app_assoc in Hstep,Hhd.\n    edestruct IHHunf1  as [(fuel'&?&IH')|IH']. 3:eassumption.\n    1,2,4:easy.\n    cbn in Hhd|-*. unfold sizeP,largestVarP in Hhd. autorewrite with list in Hhd|-*.  \n    rewrite !lambdaDepthP_compile', !maxl_app in Hhd. cbn - [max]in Hhd|-*.\n    specialize IH with (3:=IH') as [(fuel''&?&IH'')|IH'']. 2:eassumption.\n    + nia.\n    + cbn in Hhd|-*. unfold sizeP,largestVarP in Hhd|-*. autorewrite with list. rewrite !lambdaDepthP_compile', !maxl_app;cbn.\n      repeat simple apply conj;try nia.\n    + easy.\n    + destruct fuel'' as [|fuel''].\n      {\n        hnf in IH''. subst stack'. right. hnf;cbn. intros ? ? ? [[= <- <- <-]| ].\n        2:now eauto.\n        cbn - [max] in Hhd|-*. unfold sizeP in *. repeat simple apply conj;try nia.\n      }\n      change (S fuel'') with (1+fuel'') in *. eapply pow_add in IH'' as (stack'''&Hstep'%(rcomp_1)&IH''').\n      cbn in Hstep. injection Hstep' as [=->].\n      left;do 2 eexists. 2:eassumption. nia. \n    + easy.\nQed.\n\nLemma unfoldTailRecStep_sizes_correct H maxPro maxVar maxDepth a k s s' stack' res fuel :\n  boundHeap H maxPro maxVar maxDepth\n  -> LM_heap_correct.unfolds H a k s s'\n  -> ARS.pow (fun a b => inl b = unfoldTailRecStep H a) fuel ([(a,compile s,k)],res) stack'\n  -> sizeP (compile s) <= maxPro /\\ a <= length H /\\ LargestVar.largestVar s<= maxVar /\\ k + lambdaDepth s <= maxDepth\n  -> unfoldTailRecStep_sizes H maxPro maxVar maxDepth (fst stack').\nProof.\n  intros H1 H2 H3 ?.\n  edestruct unfoldTailRecStep_sizes_correct' with (P:=@nil Tok) (1:=H1) (2:=H2)as [(fuel'&?&H')|H'].\n  -rewrite app_nil_r. eassumption.\n  -rewrite app_nil_r. rewrite lambdaDepthP_compile, largestVar_compile. easy.\n  -easy.\n  -destruct fuel'.\n   { hnf in H'. subst stack';cbn. hnf. intros ? ? ? [[= <- <- <-]|[]];cbn. unfold sizeP in *. nia. }\n   change (S fuel') with (1+fuel') in *. eapply pow_add in H' as (stack''&Hstep%(rcomp_1)&H').\n   cbn in Hstep. injection Hstep as [=->].\n   destruct fuel'.\n   +hnf in H'. subst stack';cbn. hnf. easy.\n   +exfalso.  change (S fuel') with (1+fuel') in *. eapply pow_add in H' as (stack''&Hstep%(rcomp_1)&_). easy.\n  -easy.\nQed.\n\nFrom Undecidability.L.AbstractMachines Require Import SizeAnalysisStep SubtermProperty.\n\n\nLemma abstractMachine_boundHeap k s a s0 H :\n  ARS.pow step k (LM_heap_def.init s) ([], [(a, compile s0)], H) -> \n  boundHeap H (sizeP (compile s)) (LargestVar.largestVar s) (lambdaDepth s).\nProof.\n  intros H'. unfold boundHeap. intros ? ? ? HH.\n  specialize subterm_property with (1:=H') as (_&_&Hsub). specialize Hsub with (1:=HH) as (?&?&tmp);cbn in tmp;subst P.\n  specialize size_clos with (1:=H') as (_&Hlength). easy. specialize Hlength with (1:=HH) as (?&?&?&?).\n  repeat simple apply conj;try eassumption.\n  -apply lambdaDepth_subterm in H0 as <-. cbn. now rewrite lambdaDepthP_compile.\n  -now rewrite <- largestVar_compile.\nQed.\n\nLemma abstractMachine_boundRes k s a s0 H :\n  ARS.pow step k (LM_heap_def.init s) ([], [(a, compile s0)], H) -> \n  sizeP (compile s0) <= sizeP (compile s) /\\\n  a <= | H | /\\\n  LargestVar.largestVar s0 <= LargestVar.largestVar s /\\\n  1 + lambdaDepth s0 <= lambdaDepth s.\nProof.\n  intros H'. \n  specialize subterm_property with (1:=H') as (_&Hsub&_). specialize Hsub as (?&?&tmp). now left.\n  apply compile_inj in tmp as <-.\n  specialize size_clos with (1:=H') as (Hlength&_). easy. specialize Hlength as (?&?&?). now left.\n  repeat simple apply conj;try eassumption.\n  -now rewrite <- !largestVar_compile.\n  -apply lambdaDepth_subterm in H0 as <-. cbn. easy.\nQed.\n\n\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/AbstractMachines/FlatPro/SizeAnalysisUnfoldClos.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604274, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.26857445054663054}}
{"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 int.MinMax.\n\n(* Why3 assumption *)\nInductive list (a:Type) {a_WT:WhyType a} :=\n  | Nil : list a\n  | Cons : a -> (list a) -> list a.\nAxiom list_WhyType : forall (a:Type) {a_WT:WhyType a}, WhyType (list a).\nExisting Instance list_WhyType.\nImplicit Arguments Nil [[a] [a_WT]].\nImplicit Arguments Cons [[a] [a_WT]].\n\n(* Why3 assumption *)\nFixpoint infix_plpl {a:Type} {a_WT:WhyType a}(l1:(list a)) (l2:(list\n  a)) {struct l1}: (list a) :=\n  match l1 with\n  | Nil => l2\n  | (Cons x1 r1) => (Cons x1 (infix_plpl r1 l2))\n  end.\n\nAxiom Append_assoc : forall {a:Type} {a_WT:WhyType a}, forall (l1:(list a))\n  (l2:(list a)) (l3:(list a)), ((infix_plpl l1 (infix_plpl l2\n  l3)) = (infix_plpl (infix_plpl l1 l2) l3)).\n\nAxiom Append_l_nil : forall {a:Type} {a_WT:WhyType a}, forall (l:(list a)),\n  ((infix_plpl l (Nil :(list a))) = l).\n\n(* Why3 assumption *)\nFixpoint length {a:Type} {a_WT:WhyType a}(l:(list a)) {struct l}: Z :=\n  match l with\n  | Nil => 0%Z\n  | (Cons _ r) => (1%Z + (length r))%Z\n  end.\n\nAxiom Length_nonnegative : forall {a:Type} {a_WT:WhyType a}, forall (l:(list\n  a)), (0%Z <= (length l))%Z.\n\nAxiom Length_nil : forall {a:Type} {a_WT:WhyType a}, forall (l:(list a)),\n  ((length l) = 0%Z) <-> (l = (Nil :(list a))).\n\nAxiom Append_length : forall {a:Type} {a_WT:WhyType a}, forall (l1:(list a))\n  (l2:(list a)), ((length (infix_plpl l1\n  l2)) = ((length l1) + (length l2))%Z).\n\n(* Why3 assumption *)\nFixpoint mem {a:Type} {a_WT:WhyType a}(x:a) (l:(list a)) {struct l}: Prop :=\n  match l with\n  | Nil => False\n  | (Cons y r) => (x = y) \\/ (mem x r)\n  end.\n\nAxiom mem_append : forall {a:Type} {a_WT:WhyType a}, forall (x:a) (l1:(list\n  a)) (l2:(list a)), (mem x (infix_plpl l1 l2)) <-> ((mem x l1) \\/ (mem x\n  l2)).\n\nAxiom mem_decomp : forall {a:Type} {a_WT:WhyType a}, forall (x:a) (l:(list\n  a)), (mem x l) -> exists l1:(list a), exists l2:(list a),\n  (l = (infix_plpl l1 (Cons x l2))).\n\nAxiom map : forall (a:Type) {a_WT:WhyType a} (b:Type) {b_WT:WhyType b}, Type.\nParameter map_WhyType : forall (a:Type) {a_WT:WhyType a}\n  (b:Type) {b_WT:WhyType b}, WhyType (map a b).\nExisting Instance map_WhyType.\n\nParameter get: forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  (map a b) -> a -> b.\n\nParameter set: forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  (map a b) -> a -> b -> (map a b).\n\nAxiom Select_eq : forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  forall (m:(map a b)), forall (a1:a) (a2:a), forall (b1:b), (a1 = a2) ->\n  ((get (set m a1 b1) a2) = b1).\n\nAxiom Select_neq : forall {a:Type} {a_WT:WhyType a}\n  {b:Type} {b_WT:WhyType b}, forall (m:(map a b)), forall (a1:a) (a2:a),\n  forall (b1:b), (~ (a1 = a2)) -> ((get (set m a1 b1) a2) = (get m a2)).\n\nParameter const: forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  b -> (map a b).\n\nAxiom Const : forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  forall (b1:b) (a1:a), ((get (const b1:(map a b)) a1) = b1).\n\n(* Why3 assumption *)\nInductive datatype  :=\n  | TYunit : datatype \n  | TYint : datatype \n  | TYbool : datatype .\nAxiom datatype_WhyType : WhyType datatype.\nExisting Instance datatype_WhyType.\n\n(* Why3 assumption *)\nInductive value  :=\n  | Vvoid : value \n  | Vint : Z -> value \n  | Vbool : bool -> value .\nAxiom value_WhyType : WhyType value.\nExisting Instance value_WhyType.\n\n(* Why3 assumption *)\nInductive operator  :=\n  | Oplus : operator \n  | Ominus : operator \n  | Omult : operator \n  | Ole : operator .\nAxiom operator_WhyType : WhyType operator.\nExisting Instance operator_WhyType.\n\nAxiom mident : Type.\nParameter mident_WhyType : WhyType mident.\nExisting Instance mident_WhyType.\n\nAxiom mident_decide : forall (m1:mident) (m2:mident), (m1 = m2) \\/\n  ~ (m1 = m2).\n\n(* Why3 assumption *)\nInductive ident  :=\n  | mk_ident : Z -> ident .\nAxiom ident_WhyType : WhyType ident.\nExisting Instance ident_WhyType.\n\n(* Why3 assumption *)\nDefinition ident_index(v:ident): Z := match v with\n  | (mk_ident x) => x\n  end.\n\nParameter result: ident.\n\nAxiom ident_decide : forall (m1:ident) (m2:ident), (m1 = m2) \\/ ~ (m1 = m2).\n\n(* Why3 assumption *)\nInductive term  :=\n  | Tvalue : value -> term \n  | Tvar : ident -> term \n  | Tderef : mident -> term \n  | Tbin : term -> operator -> term -> term .\nAxiom term_WhyType : WhyType term.\nExisting Instance term_WhyType.\n\n(* Why3 assumption *)\nFixpoint var_occurs_in_term(x:ident) (t:term) {struct t}: Prop :=\n  match t with\n  | (Tvalue _) => False\n  | (Tvar i) => (x = i)\n  | (Tderef _) => False\n  | (Tbin t1 _ t2) => (var_occurs_in_term x t1) \\/ (var_occurs_in_term x t2)\n  end.\n\n(* Why3 assumption *)\nInductive fmla  :=\n  | Fterm : term -> fmla \n  | Fand : fmla -> fmla -> fmla \n  | Fnot : fmla -> fmla \n  | Fimplies : fmla -> fmla -> fmla \n  | Flet : ident -> term -> fmla -> fmla \n  | Fforall : ident -> datatype -> fmla -> fmla .\nAxiom fmla_WhyType : WhyType fmla.\nExisting Instance fmla_WhyType.\n\n(* Why3 assumption *)\nInductive expr  :=\n  | Evalue : value -> expr \n  | Ebin : expr -> operator -> expr -> expr \n  | Evar : ident -> expr \n  | Ederef : mident -> expr \n  | Eassign : mident -> expr -> expr \n  | Eseq : expr -> expr -> expr \n  | Elet : ident -> expr -> expr -> expr \n  | Eif : expr -> expr -> expr -> expr \n  | Eassert : fmla -> expr \n  | Ewhile : expr -> fmla -> expr -> expr .\nAxiom expr_WhyType : WhyType expr.\nExisting Instance expr_WhyType.\n\n(* Why3 assumption *)\nDefinition type_value(v:value): datatype :=\n  match v with\n  | Vvoid => TYunit\n  | (Vint int) => TYint\n  | (Vbool bool1) => TYbool\n  end.\n\n(* Why3 assumption *)\nInductive type_operator : operator -> datatype -> datatype\n  -> datatype -> Prop :=\n  | Type_plus : (type_operator Oplus TYint TYint TYint)\n  | Type_minus : (type_operator Ominus TYint TYint TYint)\n  | Type_mult : (type_operator Omult TYint TYint TYint)\n  | Type_le : (type_operator Ole TYint TYint TYbool).\n\n(* Why3 assumption *)\nDefinition type_stack  := (list (ident* datatype)%type).\n\nParameter get_vartype: ident -> (list (ident* datatype)%type) -> datatype.\n\nAxiom get_vartype_def : forall (i:ident) (pi:(list (ident* datatype)%type)),\n  match pi with\n  | Nil => ((get_vartype i pi) = TYunit)\n  | (Cons (x, ty) r) => ((x = i) -> ((get_vartype i pi) = ty)) /\\\n      ((~ (x = i)) -> ((get_vartype i pi) = (get_vartype i r)))\n  end.\n\n(* Why3 assumption *)\nDefinition type_env  := (map mident datatype).\n\n(* Why3 assumption *)\nInductive type_term : (map mident datatype) -> (list (ident* datatype)%type)\n  -> term -> datatype -> Prop :=\n  | Type_value : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (v:value), (type_term sigma pi (Tvalue v)\n      (type_value v))\n  | Type_var : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (v:ident) (ty:datatype), ((get_vartype v pi) = ty) ->\n      (type_term sigma pi (Tvar v) ty)\n  | Type_deref : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (v:mident) (ty:datatype), ((get sigma v) = ty) ->\n      (type_term sigma pi (Tderef v) ty)\n  | Type_bin : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (t1:term) (t2:term) (op:operator) (ty1:datatype)\n      (ty2:datatype) (ty:datatype), (type_term sigma pi t1 ty1) ->\n      ((type_term sigma pi t2 ty2) -> ((type_operator op ty1 ty2 ty) ->\n      (type_term sigma pi (Tbin t1 op t2) ty))).\n\n(* Why3 assumption *)\nInductive type_fmla : (map mident datatype) -> (list (ident* datatype)%type)\n  -> fmla -> Prop :=\n  | Type_term : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (t:term), (type_term sigma pi t TYbool) ->\n      (type_fmla sigma pi (Fterm t))\n  | Type_conj : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (f1:fmla) (f2:fmla), (type_fmla sigma pi f1) ->\n      ((type_fmla sigma pi f2) -> (type_fmla sigma pi (Fand f1 f2)))\n  | Type_neg : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (f:fmla), (type_fmla sigma pi f) -> (type_fmla sigma\n      pi (Fnot f))\n  | Type_implies : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (f1:fmla) (f2:fmla), (type_fmla sigma pi f1) ->\n      ((type_fmla sigma pi f2) -> (type_fmla sigma pi (Fimplies f1 f2)))\n  | Type_let : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (x:ident) (t:term) (f:fmla) (ty:datatype),\n      (type_term sigma pi t ty) -> ((type_fmla sigma (Cons (x, ty) pi) f) ->\n      (type_fmla sigma pi (Flet x t f)))\n  | Type_forall1 : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (x:ident) (f:fmla), (type_fmla sigma (Cons (x, TYint)\n      pi) f) -> (type_fmla sigma pi (Fforall x TYint f))\n  | Type_forall2 : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (x:ident) (f:fmla), (type_fmla sigma (Cons (x, TYbool)\n      pi) f) -> (type_fmla sigma pi (Fforall x TYbool f))\n  | Type_forall3 : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (x:ident) (f:fmla), (type_fmla sigma (Cons (x, TYunit)\n      pi) f) -> (type_fmla sigma pi (Fforall x TYunit f)).\n\n(* Why3 assumption *)\nInductive type_expr : (map mident datatype) -> (list (ident* datatype)%type)\n  -> expr -> datatype -> Prop :=\n  | Type_Evalue : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (v:value), (type_expr sigma pi (Evalue v)\n      (type_value v))\n  | Type_Evar : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (v:ident) (ty:datatype), ((get_vartype v pi) = ty) ->\n      (type_expr sigma pi (Evar v) ty)\n  | Type_Ederef : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (v:mident) (ty:datatype), ((get sigma v) = ty) ->\n      (type_expr sigma pi (Ederef v) ty)\n  | Type_Ebinop : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (e1:expr) (e2:expr) (op:operator) (ty1:datatype)\n      (ty2:datatype) (ty:datatype), (type_expr sigma pi e1 ty1) ->\n      ((type_expr sigma pi e2 ty2) -> ((type_operator op ty1 ty2 ty) ->\n      (type_expr sigma pi (Ebin e1 op e2) ty)))\n  | Type_seq : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (e1:expr) (e2:expr) (ty:datatype), (type_expr sigma pi\n      e1 TYunit) -> ((type_expr sigma pi e2 ty) -> (type_expr sigma pi\n      (Eseq e1 e2) ty))\n  | Type_assigns : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (x:mident) (e:expr) (ty:datatype), ((get sigma\n      x) = ty) -> ((type_expr sigma pi e ty) -> (type_expr sigma pi\n      (Eassign x e) TYunit))\n  | Type_if : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (t:expr) (e1:expr) (e2:expr) (ty:datatype),\n      (type_expr sigma pi t TYbool) -> ((type_expr sigma pi e1 ty) ->\n      ((type_expr sigma pi e2 ty) -> (type_expr sigma pi (Eif t e1 e2) ty)))\n  | Type_assert : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (p:fmla), (type_fmla sigma pi p) -> (type_expr sigma\n      pi (Eassert p) TYbool)\n  | Type_while : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (guard:expr) (body:expr) (inv:fmla) (ty:datatype),\n      (type_fmla sigma pi inv) -> ((type_expr sigma pi guard TYbool) ->\n      ((type_expr sigma pi body ty) -> (type_expr sigma pi (Ewhile guard inv\n      body) ty)))\n  | Type_Elet : forall (sigma:(map mident datatype)) (pi:(list (ident*\n      datatype)%type)) (x:ident) (e1:expr) (e2:expr) (ty1:datatype)\n      (ty2:datatype), (type_expr sigma pi e1 ty1) -> ((type_expr sigma\n      (Cons (x, ty1) pi) e2 ty2) -> (type_expr sigma pi (Elet x e1 e2) ty2)).\n\n(* Why3 assumption *)\nDefinition env  := (map mident value).\n\n(* Why3 assumption *)\nDefinition stack  := (list (ident* value)%type).\n\nParameter get_stack: ident -> (list (ident* value)%type) -> value.\n\nAxiom get_stack_def : forall (i:ident) (pi:(list (ident* value)%type)),\n  match pi with\n  | Nil => ((get_stack i pi) = Vvoid)\n  | (Cons (x, v) r) => ((x = i) -> ((get_stack i pi) = v)) /\\ ((~ (x = i)) ->\n      ((get_stack i pi) = (get_stack i r)))\n  end.\n\nAxiom get_stack_eq : forall (x:ident) (v:value) (r:(list (ident*\n  value)%type)), ((get_stack x (Cons (x, v) r)) = v).\n\nAxiom get_stack_neq : forall (x:ident) (i:ident) (v:value) (r:(list (ident*\n  value)%type)), (~ (x = i)) -> ((get_stack i (Cons (x, v) r)) = (get_stack i\n  r)).\n\nParameter eval_bin: value -> operator -> value -> value.\n\nAxiom eval_bin_def : forall (x:value) (op:operator) (y:value), match (x,\n  y) with\n  | ((Vint x1), (Vint y1)) =>\n      match op with\n      | Oplus => ((eval_bin x op y) = (Vint (x1 + y1)%Z))\n      | Ominus => ((eval_bin x op y) = (Vint (x1 - y1)%Z))\n      | Omult => ((eval_bin x op y) = (Vint (x1 * y1)%Z))\n      | Ole => ((x1 <= y1)%Z -> ((eval_bin x op y) = (Vbool true))) /\\\n          ((~ (x1 <= y1)%Z) -> ((eval_bin x op y) = (Vbool false)))\n      end\n  | (_, _) => ((eval_bin x op y) = Vvoid)\n  end.\n\n(* Why3 assumption *)\nFixpoint eval_term(sigma:(map mident value)) (pi:(list (ident* value)%type))\n  (t:term) {struct t}: value :=\n  match t with\n  | (Tvalue v) => v\n  | (Tvar id) => (get_stack id pi)\n  | (Tderef id) => (get sigma id)\n  | (Tbin t1 op t2) => (eval_bin (eval_term sigma pi t1) op (eval_term sigma\n      pi t2))\n  end.\n\nAxiom eval_bool_term : forall (sigma:(map mident value)) (pi:(list (ident*\n  value)%type)) (sigmat:(map mident datatype)) (pit:(list (ident*\n  datatype)%type)) (t:term), (type_term sigmat pit t TYbool) ->\n  exists b:bool, ((eval_term sigma pi t) = (Vbool b)).\n\n(* Why3 assumption *)\nFixpoint eval_fmla(sigma:(map mident value)) (pi:(list (ident* value)%type))\n  (f:fmla) {struct f}: Prop :=\n  match f with\n  | (Fterm t) => ((eval_term sigma pi t) = (Vbool true))\n  | (Fand f1 f2) => (eval_fmla sigma pi f1) /\\ (eval_fmla sigma pi f2)\n  | (Fnot f1) => ~ (eval_fmla sigma pi f1)\n  | (Fimplies f1 f2) => (eval_fmla sigma pi f1) -> (eval_fmla sigma pi f2)\n  | (Flet x t f1) => (eval_fmla sigma (Cons (x, (eval_term sigma pi t)) pi)\n      f1)\n  | (Fforall x TYint f1) => forall (n:Z), (eval_fmla sigma (Cons (x,\n      (Vint n)) pi) f1)\n  | (Fforall x TYbool f1) => forall (b:bool), (eval_fmla sigma (Cons (x,\n      (Vbool b)) pi) f1)\n  | (Fforall x TYunit f1) => (eval_fmla sigma (Cons (x, Vvoid) pi) f1)\n  end.\n\nParameter msubst_term: term -> mident -> ident -> term.\n\nAxiom msubst_term_def : forall (t:term) (r:mident) (v:ident),\n  match t with\n  | ((Tvalue _)|(Tvar _)) => ((msubst_term t r v) = t)\n  | (Tderef x) => ((r = x) -> ((msubst_term t r v) = (Tvar v))) /\\\n      ((~ (r = x)) -> ((msubst_term t r v) = t))\n  | (Tbin t1 op t2) => ((msubst_term t r v) = (Tbin (msubst_term t1 r v) op\n      (msubst_term t2 r v)))\n  end.\n\nParameter subst_term: term -> ident -> ident -> term.\n\nAxiom subst_term_def : forall (t:term) (r:ident) (v:ident),\n  match t with\n  | ((Tvalue _)|(Tderef _)) => ((subst_term t r v) = t)\n  | (Tvar x) => ((r = x) -> ((subst_term t r v) = (Tvar v))) /\\\n      ((~ (r = x)) -> ((subst_term t r v) = t))\n  | (Tbin t1 op t2) => ((subst_term t r v) = (Tbin (subst_term t1 r v) op\n      (subst_term t2 r v)))\n  end.\n\n(* Why3 assumption *)\nDefinition fresh_in_term(id:ident) (t:term): Prop := ~ (var_occurs_in_term id\n  t).\n\nAxiom fresh_in_binop : forall (t:term) (t':term) (op:operator) (v:ident),\n  (fresh_in_term v (Tbin t op t')) -> ((fresh_in_term v t) /\\\n  (fresh_in_term v t')).\n\n(* Why3 assumption *)\nFixpoint fresh_in_fmla(id:ident) (f:fmla) {struct f}: Prop :=\n  match f with\n  | (Fterm e) => (fresh_in_term id e)\n  | ((Fand f1 f2)|(Fimplies f1 f2)) => (fresh_in_fmla id f1) /\\\n      (fresh_in_fmla id f2)\n  | (Fnot f1) => (fresh_in_fmla id f1)\n  | (Flet y t f1) => (~ (id = y)) /\\ ((fresh_in_term id t) /\\\n      (fresh_in_fmla id f1))\n  | (Fforall y ty f1) => (~ (id = y)) /\\ (fresh_in_fmla id f1)\n  end.\n\n(* Why3 assumption *)\nFixpoint subst(f:fmla) (x:ident) (v:ident) {struct f}: fmla :=\n  match f with\n  | (Fterm e) => (Fterm (subst_term e x v))\n  | (Fand f1 f2) => (Fand (subst f1 x v) (subst f2 x v))\n  | (Fnot f1) => (Fnot (subst f1 x v))\n  | (Fimplies f1 f2) => (Fimplies (subst f1 x v) (subst f2 x v))\n  | (Flet y t f1) => (Flet y (subst_term t x v) (subst f1 x v))\n  | (Fforall y ty f1) => (Fforall y ty (subst f1 x v))\n  end.\n\n(* Why3 assumption *)\nFixpoint msubst(f:fmla) (x:mident) (v:ident) {struct f}: fmla :=\n  match f with\n  | (Fterm e) => (Fterm (msubst_term e x v))\n  | (Fand f1 f2) => (Fand (msubst f1 x v) (msubst f2 x v))\n  | (Fnot f1) => (Fnot (msubst f1 x v))\n  | (Fimplies f1 f2) => (Fimplies (msubst f1 x v) (msubst f2 x v))\n  | (Flet y t f1) => (Flet y (msubst_term t x v) (msubst f1 x v))\n  | (Fforall y ty f1) => (Fforall y ty (msubst f1 x v))\n  end.\n\nAxiom subst_fresh_term : forall (t:term) (x:ident) (v:ident),\n  (fresh_in_term x t) -> ((subst_term t x v) = t).\n\nAxiom subst_fresh : forall (f:fmla) (x:ident) (v:ident), (fresh_in_fmla x\n  f) -> ((subst f x v) = f).\n\nAxiom eval_msubst_term : forall (e:term) (sigma:(map mident value)) (pi:(list\n  (ident* value)%type)) (x:mident) (v:ident), (fresh_in_term v e) ->\n  ((eval_term sigma pi (msubst_term e x v)) = (eval_term (set sigma x\n  (get_stack v pi)) pi e)).\n\nAxiom eval_msubst : forall (f:fmla) (sigma:(map mident value)) (pi:(list\n  (ident* value)%type)) (x:mident) (v:ident), (fresh_in_fmla v f) ->\n  ((eval_fmla sigma pi (msubst f x v)) <-> (eval_fmla (set sigma x\n  (get_stack v pi)) pi f)).\n\nAxiom eval_swap_term : forall (t:term) (sigma:(map mident value)) (pi:(list\n  (ident* value)%type)) (l:(list (ident* value)%type)) (id1:ident)\n  (id2:ident) (v1:value) (v2:value), (~ (id1 = id2)) -> ((eval_term sigma\n  (infix_plpl l (Cons (id1, v1) (Cons (id2, v2) pi))) t) = (eval_term sigma\n  (infix_plpl l (Cons (id2, v2) (Cons (id1, v1) pi))) t)).\n\nAxiom eval_swap_term_2 : forall (t:term) (sigma:(map mident value)) (pi:(list\n  (ident* value)%type)) (id1:ident) (id2:ident) (v1:value) (v2:value),\n  (~ (id1 = id2)) -> ((eval_term sigma (Cons (id1, v1) (Cons (id2, v2) pi))\n  t) = (eval_term sigma (Cons (id2, v2) (Cons (id1, v1) pi)) t)).\n\nAxiom eval_swap : forall (f:fmla) (sigma:(map mident value)) (pi:(list\n  (ident* value)%type)) (l:(list (ident* value)%type)) (id1:ident)\n  (id2:ident) (v1:value) (v2:value), (~ (id1 = id2)) -> ((eval_fmla sigma\n  (infix_plpl l (Cons (id1, v1) (Cons (id2, v2) pi))) f) <-> (eval_fmla sigma\n  (infix_plpl l (Cons (id2, v2) (Cons (id1, v1) pi))) f)).\n\n(* Why3 goal *)\nTheorem eval_swap_2 : forall (f:fmla) (id1:ident) (id2:ident) (v1:value)\n  (v2:value), (~ (id1 = id2)) -> forall (sigma:(map mident value)) (pi:(list\n  (ident* value)%type)), (eval_fmla sigma (Cons (id1, v1) (Cons (id2, v2)\n  pi)) f) <-> (eval_fmla sigma (Cons (id2, v2) (Cons (id1, v1) pi)) f).\nintros f id1 id2 v1 v2 h1 sigma pi.\nassert (h: ((eval_fmla sigma\n  (infix_plpl Nil (Cons (id1, v1) (Cons (id2, v2) pi))) f) <-> (eval_fmla sigma\n  (infix_plpl Nil (Cons (id2, v2) (Cons (id1, v1) pi))) f))).\napply eval_swap; auto.\nsimpl in h; auto.\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/hoare_logic/draft/blocking_semantics4/blocking_semantics4_ImpExpr_eval_swap_2_4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4843800842769843, "lm_q1q2_score": 0.2685744505466304}}
{"text": "Set Implicit Arguments.\n\nRequire Import Platform.Cito.Syntax.\nRequire Import Coq.Strings.String.\n\nDefinition Optimizer := Stmt -> string -> Stmt.\n\nDefinition compose (f g : Optimizer) : Optimizer := fun s r => g (f s r) r.\n\nRequire Import Platform.Cito.ADT.\n\nModule Make (Import E : ADT).\n\n  Require Import Platform.Cito.Semantics.\n  Module Import SemanticsMake := Semantics.Make E.\n\n  Section TopSection.\n\n    Definition PreserveRunsTo (opt : Optimizer) :=  forall ret fs s v v', RunsTo fs (opt s ret) v v' -> exists vs', RunsTo fs s v (vs', snd v') /\\ Locals.sel vs' ret = Locals.sel (fst v') ret.\n\n    Definition PreserveSafe (opt : Optimizer) := forall fs s v, Safe fs s v -> forall ret, Safe fs (opt s ret) v.\n\n    Require Import Platform.Cito.GetLocalVars.\n    Require Import Platform.Cito.Depth.\n    Require Import Bedrock.IL.\n\n    Definition PreserveGoodSize (opt : Optimizer) :=\n      forall stmt argvars retvar,\n        let size s := List.length (get_local_vars s argvars retvar) + depth s in\n        goodSize (size stmt) ->\n        goodSize (size (opt stmt retvar)).\n\n    Require Import Platform.Cito.CompileStmtSpec.\n    Require Import Coq.Lists.List.\n\n    Definition PreserveSynReq (opt : Optimizer) :=\n      forall stmt argvars retvar,\n        let vars s := argvars ++ get_local_vars s argvars retvar in\n        let stmt' := opt stmt retvar in\n        syn_req (vars stmt) (depth stmt) stmt ->\n        syn_req (vars stmt') (depth stmt') stmt'.\n\n    Definition GoodOptimizer opt :=\n      PreserveRunsTo opt /\\\n      PreserveSafe opt /\\\n      PreserveGoodSize opt /\\\n      PreserveSynReq opt.\n\n    Require Import Platform.Cito.GoodFunc.\n    Require Import Platform.Cito.SyntaxFunc.\n    Definition PreserveGoodSize' (opt : Optimizer) :=\n      forall f,\n        GoodFunc f ->\n        let s := opt (Body f) (RetVar f) in\n        goodSize (length (get_local_vars s (ArgVars f) (RetVar f)) + depth s).\n\n    Definition PreserveSynReq' (opt : Optimizer) :=\n      forall f,\n        GoodFunc f ->\n        let s := opt (Body f) (RetVar f) in\n        syn_req (ArgVars f ++ get_local_vars s (ArgVars f) (RetVar f)) (depth s) s.\n\n    Lemma GoodOptimizer_Safe : forall opt, GoodOptimizer opt -> PreserveSafe opt.\n      unfold GoodOptimizer; intuition.\n    Qed.\n\n    Lemma GoodOptimizer_RunsTo : forall opt, GoodOptimizer opt -> PreserveRunsTo opt.\n      unfold GoodOptimizer; intuition.\n    Qed.\n\n    Require Import Platform.Cito.GeneralTactics.\n\n    Lemma GoodFunc_GoodOptimizer_goodSize : forall opt, GoodOptimizer opt -> PreserveGoodSize' opt.\n      unfold GoodOptimizer.\n      intros.\n      openhyp.\n      unfold PreserveGoodSize'.\n      unfold PreserveGoodSize in *.\n      intros.\n      simpl in *.\n      eapply H1; eauto.\n      destruct H3; openhyp; eauto.\n    Qed.\n\n    Lemma GoodFunc_GoodOptimizer_syn_req : forall opt, GoodOptimizer opt -> PreserveSynReq' opt.\n      unfold GoodOptimizer.\n      intros.\n      openhyp.\n      unfold PreserveSynReq'.\n      unfold PreserveSynReq in *.\n      intros.\n      simpl in *.\n      eapply H2; eauto.\n      eapply GoodFunc_syn_req; eauto.\n    Qed.\n\n    Lemma PreserveRunsTo_trans : forall a b, PreserveRunsTo a -> PreserveRunsTo b -> PreserveRunsTo (compose a b).\n      unfold PreserveRunsTo, compose; intros.\n      eapply H0 in H1; eauto; openhyp.\n      eapply H in H1; eauto; openhyp.\n      descend; intuition eauto.\n    Qed.\n\n    Lemma PreserveSafe_trans : forall a b, PreserveSafe a -> PreserveSafe b -> PreserveSafe (compose a b).\n      unfold PreserveSafe, compose; intros.\n      eauto.\n    Qed.\n\n    Lemma PreserveGoodSize_trans : forall a b, PreserveGoodSize a -> PreserveGoodSize b -> PreserveGoodSize (compose a b).\n      unfold PreserveGoodSize, compose; intros.\n      eauto.\n    Qed.\n\n    Lemma PreserveSynReq_trans : forall a b, PreserveSynReq a -> PreserveSynReq b -> PreserveSynReq (compose a b).\n      unfold PreserveSynReq, compose; intros.\n      eauto.\n    Qed.\n\n    Lemma GoodOptimizer_trans :\n      forall a b,\n        GoodOptimizer a ->\n        GoodOptimizer b ->\n        GoodOptimizer (compose a b).\n    Proof.\n      unfold GoodOptimizer; intros.\n      openhyp.\n      split.\n      eapply PreserveRunsTo_trans; eauto.\n      split.\n      eapply PreserveSafe_trans; eauto.\n      split.\n      eapply PreserveGoodSize_trans; eauto.\n      eapply PreserveSynReq_trans; eauto.\n    Qed.\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/GoodOptimizer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2685392451300189}}
{"text": "Require Import String.\nRequire Import Functors.\nRequire Import MonadLib.\nRequire Import Names.\nRequire Import EffPure.\nRequire Import EffState.\nRequire Import EffExcept.\nRequire Import Ref.\nRequire Import Exception.\nRequire Import ESoundES.\n\nOpen Scope string_scope.\n\nSection Test_Section.\n\n  Definition D := RefType :+: UnitType.\n\n  Definition E := RefE :+: (ExceptE D).\n\n  Definition V := StuckValue :+: 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_Unit D V _) ::+:: (WFValue_Loc D V _).\n\n  Instance DType_Env_CE : ConsExtensionC (list (DType D)). eauto with typeclass_instances. Defined.\n  Instance DType_Env_WFE : WF_EnvC V (list (DType D)). apply (DType_Env_WFE _ _ WFV). Defined.\n\n  Definition WFVM :=\n    (WFValueM_base D V MT ME (list (DType D)) WFV) ::+::\n    (WFValueM_State D V MT ME _) ::+::\n    (WFValueM_Except D V MT ME _).\n\n  Instance typeof_alg : forall T : Set, 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 150 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 250 with typeclass_instances.\n    eauto 250 with typeclass_instances.\n    intros; repeat apply @P2Algebra_Plus.\n    eapply Ref_eval_soundness'' with (WFV := WFV);\n      eauto 250 with typeclass_instances.\n    eapply Except_eval_soundness';\n      eauto 250 with typeclass_instances.\n    eauto 250 with typeclass_instances.\n    eauto 250 with typeclass_instances.\n  Qed.\n\n  Eval compute in (\"Soundness for '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_RE.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.2685376456357494}}
{"text": "Require Import AllInRel Util Map Envs Exp IL Annotation Coherence DecSolve.\nRequire Import Liveness.Liveness Restrict Delocation Indexwise.\n\nSet Implicit Arguments.\nUnset Printing Records.\n\nLocal Hint Extern 1 =>\nmatch goal with\n  [ H : annotation _ _ |- annotation _ _ ] => inv H; eassumption\nend.\n\nLemma trs_dec DL s ans_lv ans\n  : {trs DL s ans_lv ans} +\n    {~ trs DL s ans_lv ans}.\nProof.\n  revert DL ans_lv ans.\n  sind s.\n  time (destruct s; destruct ans; try solve [dec_right]; destruct ans_lv; try solve [dec_right]).\n  + destruct a; [ | dec_right];\n      destruct (IH s (ltac:(eauto))\n                   (restr (getAnn ans_lv \\ singleton x) ⊝  DL) ans_lv ans);\n      [| dec_right].\n    dec_solve.\n  + destruct a; [| dec_right];\n    destruct (IH s1 (ltac:(eauto)) DL ans_lv1 ans1); [| dec_right];\n    destruct (IH s2 (ltac:(eauto)) DL ans_lv2 ans2); [| dec_right].\n    dec_solve.\n  + destruct (get_dec DL (counted l)) as [[[G'|]]|];[| dec_right | dec_right];\n      destruct a; [| dec_right];\n        dec_solve.\n  + destruct a;[| dec_right].\n    dec_solve.\n  + ensure (length F = length a);\n    ensure (length F = length sa);\n    ensure(length F = length sa0).\n    destruct (IH s (ltac:(eauto)) (Some ⊝ (getAnn ⊝ sa0) \\\\ app (A:=var) ⊜ (fst ⊝ F) a ++ DL)\n                 ans_lv ans);[| dec_right].\n    edestruct (indexwise_R4_dec\n                 (R:=fun lvs Zs Za' ans' =>\n                       trs (restr (getAnn lvs \\ of_list (fst Zs ++ Za'))\n                                     ⊝ (Some ⊝ (getAnn ⊝ sa0) \\\\ app (A:=var) ⊜ (fst ⊝ F) a ++ DL))\n                           (snd Zs) lvs ans')\n                 (LA:=sa0)\n                 (LB:=F)\n                 (LC:=a)\n                 (LD:=sa)); intros; eauto.\n    hnf; intros. eapply IH; eauto.\n    dec_solve. dec_right.\nDefined.\n\nInstance trs_dec_inst DL s lv Y\n: Computable (trs DL s lv Y).\nProof.\n  hnf; eauto using trs_dec.\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/Coherence/DelocationValidator.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2684785094968909}}
{"text": "Require Import String.\nRequire Import List.\nRequire Import Sets.Ensembles.\n\nImport ListNotations.\n\nParameter bytes: Type.\n\n(* Agents *)\n\nInductive agent := \n    | Peer : nat -> agent \n    | Attacker : agent.\n\nDefinition eqb (A B: agent) :=\n    match A, B with\n        | Peer i, Peer j => Nat.eqb i j\n        | Attacker, Attacker => true \n        | _, _ => false \n    end.\n\nLemma refl_eqb:\n    forall A, eqb A A = true.\nAdmitted.\n\n(* Messages *)\n\nVariant public :=\n    | Literal : bytes -> public \n    | Agent : agent -> public\n    | PC : nat -> public \n    | TagSend : public\n    | TagAccept : public \n    | TagChallengeRequest : public \n    | TagChallengeReply : public.\n\nVariant private :=\n    | Nonce : nat -> private \n    | Index : string -> private.\n \nInductive msg :=\n    | Tuple : list msg -> msg \n    | MAC : msg -> msg\n    | Atom : public + private -> msg. \n\n(* Le prédicat inductif 'analz' permet de générer un ensemble de message à partir d'un ensemble de message de départ.\n    - tout message appartenant à l'ensemble de départ est analysé\n    - si un message analysé est un tuple, alors on peut analyser tout les sous messages de ce tuple\n    - il n'y a pas d'autres prédicat récursif donc ces deux règles suffisent\n    - les prédicats unitaires peuvent être analysé du moment qu'ils sont présent dans un Tuple grâce à la deuxième règle\n    - on ne peut pas analyser le contenu d'un MAC *)\n\nInductive analz (H: Ensemble msg) (X: msg): Prop :=\n    | analz_init: In msg H X -> analz H X\n    | analz_tuple Xs: analz H (Tuple Xs) -> List.In X Xs -> analz H X.\n\n(* Le prédicat inductif 'synth' permet de générer un ensemble de message synthétisables à partir de messages de départ.\n    - tout message de départ est synthétisable\n    - n'importe quel message de type Public est synthétisable\n    - un tuple est synthétisable lorsque tout les messages qui le compose le sont\n    - un mac d'un message synthétisable est synthétisable *)\n\nInductive synth (H: Ensemble msg): Ensemble msg :=\n    | synth_init X: In msg H X -> synth H X\n    | synth_public p: synth H (Atom (inl p))\n    | synth_tuple Xs: (forall X, List.In X Xs -> synth H X) -> synth H (Tuple Xs).\n\nLemma not_synth_MAC:\n    forall H X, ~ (H (MAC X)) -> ~ synth H (MAC X).\nProof.\n    intros H X. intros HnotMAC Hsynth.\n    inversion Hsynth. subst. apply HnotMAC. apply H0.\nQed.\n\nLemma can_send_MAC:\n    forall H X, synth H (MAC X) -> H (MAC X).\nProof.\n    intros H X. intro Hsynth.\n    inversion Hsynth. subst. auto.\nQed.\n    \n(* Events *)\n\nVariant visibility :=\n    | Publicly  : agent ->  agent -> visibility \n    | Privately :           agent -> visibility.\n\nRecord event := E { mode: visibility ; payload: msg }.\n\nDefinition publicly A B msg := E (Publicly A B) msg.\nDefinition privately A msg := E (Privately A) msg.\n\nDefinition format_index B index := Tuple [Atom (inl (Agent B)) ; Atom (inr (Index index))].\nDefinition format_Accept A B pkt index pc := Tuple [Atom (inl TagAccept) ; \n    Atom (inl (Agent A)) ; Atom (inl (Agent B)) ; Atom (inl (Literal pkt)) ; \n    Atom (inr (Index index)) ; Atom (inl (PC pc))].\nDefinition format_ChallengeAccept A B n0 index pc := Tuple [Atom (inl TagAccept) ; \n    Atom (inl (Agent A)) ; Atom (inl (Agent B)) ; Atom (inr (Nonce n0)) ; \n    Atom (inr (Index index)) ; Atom (inl (PC pc))].\n\nDefinition privately_reset A B index := privately A (format_index B index).\nDefinition privately_Accept A B pkt index pc := \n    privately A (format_Accept A B pkt index pc).\nDefinition privately_ChallengeAccept A B n0 index pc := \n    privately A (format_ChallengeAccept A B n0 index pc).\n\nDefinition format_Send pkt index pc := Tuple [Atom (inl TagSend) ; Atom (inl (Literal pkt)) ; \n    Atom (inr (Index index)) ; Atom (inl (PC pc))].\nDefinition format_ChallengeRequest n0 := Tuple [Atom (inl TagChallengeRequest) ; Atom (inr (Nonce n0))].\nDefinition format_ChallengeReply n0 index pc := Tuple [Atom (inl TagChallengeReply) ;\n    Atom (inr (Nonce n0)) ; Atom (inr (Index index)) ; Atom (inl (PC pc))].\n\nDefinition format_MAC src dest msg :=\n    Tuple [ msg ; MAC ( Tuple [ Atom (inl (Agent src)) ; Atom (inl (Agent dest)) ; msg ] ) ].\n\nDefinition format_MAC_Send src dest pkt index pc := \n    format_MAC src dest (format_Send pkt index pc).\nDefinition format_MAC_ChallengeRequest src dest n0 :=\n    format_MAC src dest (format_ChallengeRequest n0).\nDefinition format_MAC_ChallengeReply src dest n0 index pc :=\n    format_MAC src dest (format_ChallengeReply n0 index pc).\n\nDefinition publicly_Send A B pkt index pc := \n    publicly A B (format_MAC_Send A B pkt index pc).\nDefinition publicly_ChallengeRequest A B n0 := \n    publicly A B (format_MAC_ChallengeRequest A B n0).\nDefinition publicly_ChallengeReply A B n0 index pc := \n    publicly A B (format_MAC_ChallengeReply A B n0 index pc).\n\nDefinition capture := list event.\n\nParameter index_seed: agent -> string.\nInductive init_state: agent -> Ensemble msg :=\n    | init_state_index: forall A s, init_state A (format_index A s).\n\nInductive knows: agent -> capture -> Ensemble msg :=\n    | knows_init A m: init_state A m -> knows A [] m \n    | knows_attacker A B X evs: knows Attacker ( publicly A B X :: evs ) X\n    | knows_privately A X evs: knows A ( privately A X :: evs ) X\n    | knows_publicly A B X evs: knows A ( publicly A B X :: evs ) X\n    | knows_later A e evs m: knows A evs m -> knows A ( e :: evs ) m.\n\nDefinition fresh_index B evs index := not ( analz (knows B evs) (Atom (inr (Index index))) ).\nDefinition fresh_nonce A evs n0 := not ( analz (knows A evs) (Atom (inr (Nonce n0))) ).\n\nParameters A B: agent.\nDefinition evs_ex := [ publicly_ChallengeRequest A B 42].\nLemma f:\n    fresh_nonce A evs_ex 42 -> False.\nProof.\n    unfold fresh_nonce. intro H. apply H.\n    unfold evs_ex. unfold publicly_ChallengeRequest.\n    unfold format_ChallengeRequest. \n    apply analz_tuple with (Xs := [Atom (inl TagChallengeRequest) ; Atom (inr (Nonce 42))]) ; try firstorder.\n    apply analz_tuple with (Xs := [Tuple [Atom (inl TagChallengeRequest) ; Atom (inr (Nonce 42)) ] ; \n        MAC (Tuple [Atom (inl (Agent A)) ; Atom (inl (Agent B)) ; Tuple [ Atom (inl TagChallengeRequest) ; Atom (inr (Nonce 42))]])]) ; try firstorder.\n    apply analz_init. unfold In. apply knows_publicly.\nQed.\n\nLemma fB:\n    fresh_nonce B evs_ex 42.\nProof.\n    unfold fresh_nonce. unfold evs_ex.\n    intro H. inversion H.\n    (* premier lemme : analz Empty_set = Empty_set\n        deuxième lemme : knows B evs_ex = Empty_set *)\nAdmitted.\n\nDefinition unique (ev: event) evs :=\n    ~ List.In ev evs \\/ (exists pre suff, evs = pre ++ ev :: suff \n                        /\\ ~ List.In ev pre /\\ ~ List.In ev suff). \n\nRecord local_state := LS {\n        _PC: agent -> option nat ;\n        _index: agent -> option string ;\n        _nonce: agent -> nat -> bool\n    }.\nDefinition global_state := agent -> local_state.\n\nDefinition lookup_PC (sigma: global_state) A B := (sigma A).(_PC) B.\nDefinition lookup_index (sigma: global_state) A B := (sigma A).(_index) B.\n(* Definition test_nonce (sigma: global_state) A B n := (sigma A).(_nonce) B n. *)\n\nDefinition update_PC (sigma: global_state) A B new_pc :=\n    fun A' => \n        if eqb A' A then \n            let update_new_PC B' := if eqb B' B then Some new_pc \n                        else (sigma A).(_PC) B' \n            in\n            LS update_new_PC (sigma A).(_index) (sigma A).(_nonce)\n        else sigma A'.\n\nDefinition update_index (sigma: global_state) A B new_index :=\n    fun A' =>\n        if eqb A' A then \n            let update_new_index B' := if eqb B' B then Some new_index \n                        else (sigma A).(_index) B' \n            in\n            LS (sigma A).(_PC) update_new_index (sigma A).(_nonce)\n        else sigma A'.\n\nDefinition update_PC_index (sigma: global_state) A B new_pc new_index :=\n    update_index (update_PC sigma A B new_pc) A B new_index.\n    \nDefinition set_nonce (sigma: global_state) A B new_nonce b :=\n    fun A' =>\n        if eqb A' A then \n            let set_new_nonce B' := if eqb B' B then \n                            (fun n =>  if Nat.eqb n new_nonce then b else (sigma A).(_nonce) B n)\n                        else (sigma A).(_nonce) B'\n            in\n            LS (sigma A).(_PC) (sigma A).(_index) set_new_nonce\n        else sigma A'.\n\nDefinition init_global_state (seed: agent -> string): global_state := \n    fun A => LS \n        ( fun B => if eqb A B then Some 0 else None ) \n        ( fun B => (if eqb A B then Some (seed A) else None) ) \n        ( fun _ _ => false ).\n\n(* Definition saved_index sigma A B index := Some index = lookup_index sigma A B.\nDefinition saved_PC sigma A B pc := Some pc = lookup_PC sigma A B. *)\n\nDefinition is_privately_reset A B ev := exists ix, ev = privately_reset A B ix.\nDefinition is_publicly_Send A ev := exists B pkt ix pc, ev = publicly_Send A B pkt ix pc.\nDefinition is_publicly_ChallengeRequest A B ev := exists n0, ev = publicly_ChallengeRequest A B n0.\nDefinition is_privately_ChallengeAccept A B ev := exists n ix pc, ev = privately_ChallengeAccept A B n ix pc.\nDefinition is_privately_Accept A B ev := exists pkt ix pc, ev = privately_Accept A B pkt ix pc.\n\nInductive local_index (A B: agent) (ix: string): capture -> Prop :=\n    | local_index_init: \n        init_state A (format_index B ix) -> \n        local_index A B ix [] \n    | local_index_now_reset evs: \n        local_index A B ix ( privately_reset A B ix :: evs )\n    | local_index_now_ChallengeReply evs n0 pc:\n        local_index A B ix ( publicly_ChallengeReply A B n0 ix pc :: evs )\n    | local_index_later ev evs: \n        ~ is_privately_reset A B ev -> \n        ~ is_publicly_ChallengeRequest A B ev ->\n        local_index A B ix evs -> \n        local_index A B ix (ev :: evs).\n\nInductive saved_index (A B: agent) (ix: string): capture -> Prop :=\n    | saved_index_now evs n0 pc: \n        saved_index A B ix ( privately_ChallengeAccept A B n0 ix pc :: evs )\n    | saved_index_later ev evs: \n        ~ is_privately_ChallengeAccept A B ev -> \n        saved_index A B ix evs -> \n        saved_index A B ix (ev :: evs).\n\nInductive local_PC (A B: agent): nat -> capture -> Prop :=\n    | local_PC_init:\n        local_PC A B 0 []\n    | local_PC_now_reset evs ix:\n        local_PC A B 0 ( privately_reset A B ix :: evs )\n    | local_PC_now_Send evs pc pkt ix pc':\n        local_PC A B pc evs ->\n        local_PC A B (pc + 1) ( publicly_Send A B pkt ix pc' :: evs )\n    | local_PC_later ev evs pc: \n        ~ is_privately_reset A A ev -> \n        ~ is_publicly_Send A ev ->\n        local_PC A B pc evs -> \n        local_PC A B pc (ev :: evs).\n\nInductive saved_PC (A B: agent): nat -> capture -> Prop :=\n    | saved_PC_now_ChallengeAccept evs n0 ix pc:\n        saved_PC A B pc ( privately_ChallengeAccept A B n0 ix pc :: evs )\n    | saved_PC_now_Accept evs pkt ix pc:\n        saved_PC A B (pc + 1) ( privately_Accept A B pkt ix pc :: evs )\n    | saved_PC_later ev evs pc:\n        ~ is_privately_ChallengeAccept A B ev ->\n        ~ is_privately_Accept A B ev ->\n        saved_PC A B pc evs ->\n        saved_PC A B pc (ev :: evs).\n\nInductive nonce_inflight (A B: agent) (n0: nat): capture -> Prop :=\n    | nonce_inflight_now evs:\n        nonce_inflight A B n0 ( publicly_ChallengeRequest A B n0 :: evs )\n    | nonce_inflight_later_ChallengeAccept evs n1 ix pc:\n        n0 <> n1 ->\n        nonce_inflight A B n0 evs ->\n        nonce_inflight A B n0 ( privately_ChallengeAccept A B n1 ix pc :: evs )\n    | nonce_inflight_later ev evs:\n        ~ is_publicly_ChallengeRequest A B ev ->\n        ~ is_privately_ChallengeAccept A B ev ->\n        nonce_inflight A B n0 evs ->\n        nonce_inflight A B n0 (ev :: evs).\n\nInductive Network: (*global_state ->*) capture -> Prop :=\n    | Network_Attack: forall (* sigma *) evs X B,\n        Network (* sigma *) evs ->\n        synth (analz (knows Attacker evs)) X ->\n        Network (* sigma *) ( publicly Attacker B X :: evs )\n    \n    | Network_init: (*forall sigma,\n        sigma = init_global_state index_seed ->*)\n        Network (* sigma *) []\n\n    | Network_local_reset: forall (* sigma *) evs A B index_B (* sigma1 sigma2 *),\n        Network (* sigma *) evs -> \n        fresh_index B evs index_B ->\n        (* sigma1 = update_index sigma B B index_B ->\n        sigma2 = update_PC sigma1 B B 0 -> *)\n        Network (* sigma2 *) ( privately_reset B A index_B :: evs )\n\n    (* Fix me: miss Network_saved_reset*)\n\n    | Network_Send: forall (* sigma *) evs A B pkt index_B pc_B (* sigma1 *),\n        Network (* sigma *) evs -> \n        local_index B A index_B evs -> \n        local_PC B A pc_B evs ->\n        (* sigma1 = update_PC sigma B B (pc_B + 1) ->*)\n        Network (* sigma1 *) ( publicly_Send B A pkt index_B pc_B :: evs )\n    \n    | Network_Accept: forall (* sigma *) evs A B B' index_B pc_B pkt pc (* sigma1 *),\n        Network (* sigma *) evs -> \n        List.In (publicly B' A (format_MAC_Send B A pkt index_B pc_B)) evs ->\n        saved_index A B index_B evs ->\n        saved_PC A B pc evs -> pc < pc_B -> \n        (* sigma1 = update_PC sigma A B pc_B -> *)\n        Network (* sigma1 *) ( privately_Accept A B pkt index_B pc_B :: evs )\n        \n    | Network_ChallengeRequest: forall (* sigma *) evs A B n0 (* sigma1 *),\n        Network (* sigma *) evs -> \n        fresh_nonce A evs n0 ->\n        (* sigma1 = set_nonce sigma A B n0 true -> *)\n        Network (* sigma1 *)\n            ( publicly_ChallengeRequest A B n0 :: evs ) \n        \n    | Network_ChallengeReply: forall (* sigma *) evs A A' B n0 index_B (* sigma1 sigma2 *),\n        Network (* sigma *) evs -> \n        List.In (publicly A' B (format_MAC_ChallengeRequest A B n0)) evs ->\n        (* test_nonce sigma B A n0 = false ->*)\n        fresh_index B evs index_B ->\n        (*sigma1 = update_index sigma B B index_B ->\n        sigma2 = update_PC sigma1 B B 0 -> *)\n        Network (* sigma2 *)\n            ( publicly_ChallengeReply B A n0 index_B 0 :: evs )\n                \n    | Network_ChallengeAccept: forall (* sigma *) evs A B B' n0 index_B pc_B (* sigma1 sigma2 sigma3 *),\n        Network (* sigma *) evs ->\n        List.In (publicly_ChallengeRequest A B n0) evs ->\n        List.In (publicly B' A (format_MAC_ChallengeReply B A n0 index_B pc_B)) evs ->\n        nonce_inflight A B n0 evs ->\n        (* sigma1 = update_index sigma A B index_B ->\n        sigma2 = update_PC sigma1 A B pc_B ->\n        sigma3 = set_nonce sigma2 A B n0 false -> *)\n        Network (* sigma3 *)\n            ( privately_ChallengeAccept A B n0 index_B pc_B :: evs ).\n\nAxiom R: capture -> capture -> Prop.\nDefinition leq_capture (evs evs': capture) := exists pre, evs' = pre ++ evs.\n\nLemma R_cons:\n    forall ev evs,\n        Network (ev :: evs) ->\n        R evs (ev :: evs).\nAdmitted.\n\nLemma R_leq:\n    forall evs evs',\n        leq_capture evs evs' ->\n        Network evs' ->\n        R evs evs'.\nAdmitted.\n\nLemma R_proj:\n    forall A B evs evs' ix ix' pc pc',\n        R evs evs' ->\n        saved_index A B ix evs ->\n        saved_PC A B pc evs ->\n        saved_index A B ix' evs' ->\n        saved_PC A B pc' evs' ->\n        ix = ix' ->\n        pc <= pc'.\nAdmitted.\n\n(*Lemma invariant_init:\n    forall sigma sigma' evs,\n        Network sigma evs ->\n        Network sigma' evs ->\n        R_sigma sigma sigma'.\nProof.\n    (*\n        On procède par induction sur evs :\n        - soit on bump par 1 le pc dans sigma et sigma' donc ok\n        - soit on change l'indice, si les nouveaux indices sont égaux, alors les pc sont aussi égaux, \n                sinon on a bien la relation R\n        - soit on ne touche à rien\n    *)\nAdmitted.*)\n\n(*Lemma invariant:\n    forall sigma sigma' evs evs',\n        Network sigma evs ->\n        leq_capture evs evs' ->\n        Network sigma' evs' ->\n        R_sigma sigma sigma'.\nProof.\n    (*\n        On procède par induction sur le prefixe pre.\n        - Dans le cas de la liste vide, on s'attend à sigma = sigma'\n    *)\nAdmitted.*)\n\nLemma stability:\n    forall ev evs,\n        Network evs ->\n        List.In ev evs ->\n        exists evs',\n            leq_capture (ev :: evs') evs \n            /\\ Network (ev :: evs').\nAdmitted.\n\nLemma Accept_Inversion:\nforall evs A B pkt index pc,\n    Network evs ->\n    List.In (privately_Accept A B pkt index pc) evs ->\n    exists pc',\n        List.In (publicly_Send B A pkt index pc) evs \n        /\\ saved_index A B index evs\n        /\\ saved_PC A B pc' evs /\\ pc' < pc.\nAdmitted.\n\nLemma Accept_unicity:\n    forall evs A B pkt index_B pc_B, \n        Network ( privately_Accept A B pkt index_B pc_B :: evs ) ->\n        ~ (List.In ( privately_Accept A B pkt index_B pc_B ) evs).\nProof.\n    intros evs A B pkt index_B pc_B. intros Hnetwork HIn.\n    assert ( exists pc',\n        List.In (publicly_Send B A pkt index_B pc_B) evs \n        /\\ saved_index A B index_B evs\n        /\\ saved_PC A B pc' evs /\\ pc' < pc_B ) as (pc1 & ? & ? & ? & ?). admit.\n    assert ( exists pc' evs',\n        leq_capture (privately_Accept A B pkt index_B pc_B :: evs') evs \n        /\\ List.In (publicly_Send B A pkt index_B pc_B) evs' \n        /\\ saved_index A B index_B evs'\n        /\\ saved_PC A B pc' evs' /\\ pc' < pc_B ) as (pc' & evs' & ? & ? & ? & ? & ?). admit.\n    assert ( saved_index A B index_B (privately_Accept A B pkt index_B pc_B :: evs') ). admit.\n    assert ( saved_PC A B pc_B (privately_Accept A B pkt index_B pc_B :: evs') ). admit.\n    assert ( R (privately_Accept A B pkt index_B pc_B :: evs') evs ).\n    apply R_leq. auto. admit.\n    assert ( pc_B <= pc1 ). eapply R_proj ; eauto. SearchAbout ( ?x < ?y ) .\n    eapply Lt.le_not_lt ; eauto.\nAdmitted.\n\n\n(* Théorèmes montrant que les prédicats Network_Send, Network_reset et Network_ChallengeRequest peuvent toujours se faire *)\n\nLemma Send_always_possible:\n    forall evs A B, \n        Network evs -> \n        (exists index, local_index A B index evs) \n        /\\ (exists pc, local_PC A B pc evs).\nProof.\n    (*intros sigma evs B. intro Hnetwork. induction Hnetwork.\n    - assumption.\n    - unfold init_global_state in H. split. \n        * unfold saved_index. unfold lookup_index. subst. \n            exists (index_seed B). simpl. rewrite refl_eqb. reflexivity.\n        * unfold saved_PC. unfold lookup_PC. subst.\n            exists 0. simpl. rewrite refl_eqb. reflexivity.\n    -*)\nAdmitted.\n\nTheorem can_Send:\n    forall evs A B pkt, \n        Network evs -> \n        exists evs' index pc, \n            Network evs' \n            /\\ List.In (publicly_Send B A pkt index pc) evs'\n            /\\ (exists pre, evs' = pre ++ evs).\nProof.\n    intros evs A B pkt. intro Hnetwork.\n    pose proof (Send_always_possible evs B A Hnetwork) as ([index Hindex] & [pc Hpc]).\n    eexists. exists index. exists pc. split.\n    - eapply Network_Send ; eauto.\n    - split ; try firstorder.\n        exists [publicly_Send B A pkt index pc]. auto.\nQed.\n\n(* Network_reset est peut être redondant, on commente donc le théorème et le lemme associé\nLemma reset_always_possible:\n    forall sigma evs B, Network sigma evs -> (exists index, fresh_index B evs index).\nAdmitted.\n\nTheorem can_reset:\n    forall sigma evs B, Network sigma evs -> \n        exists sigma1 evs' index, \n            Network sigma1 evs' \n            /\\ List.In (privately_reset B index) evs' \n            /\\ (exists pre, evs' = pre ++ evs).\nAdmitted.\n*)\n\nLemma ChallengeRequest_always_possible:\n    forall evs A, \n        Network evs ->\n        exists n0, fresh_nonce A evs n0.\nAdmitted.\n\nTheorem can_Challenge:\n    forall evs A B, \n        Network evs -> \n        exists evs' n0, \n            Network evs' \n            /\\ List.In (publicly_ChallengeRequest A B n0) evs'\n            /\\ (exists pre, evs' = pre ++ evs).\nProof.\n    intros evs A B. intro Hnetwork.\n    pose proof (ChallengeRequest_always_possible evs A Hnetwork) as [n0 Hn0].\n    eexists. exists n0. split.\n    - eapply Network_ChallengeRequest ; eauto.\n    - split ; try firstorder.\n        exists [publicly_ChallengeRequest A B n0]. auto.\nQed.\n\nTheorem liveness:\n    forall evs A B pkt,\n        Network evs ->\n        exists evs' index pc,\n            Network evs'\n            /\\ List.In (publicly_Send B A pkt index pc) evs' \n            /\\ List.In (privately_Accept A B pkt index pc) evs'\n            /\\ (exists pre, evs' = pre ++ evs).\nProof.\n    intros evs A B pkt. intro Hnetwork.\n    (*assert ( HsavedIndex : (exists index, saved_index sigma A B index) \n        \\/ lookup_index sigma A B = None ). apply saved_index_dec.\n    destruct HsavedIndex as [(index, HsavedIndex) | HnotIndex].\n    - assert ( HsavedPC : (exists pc, saved_PC sigma A B pc)\n            \\/ lookup_PC sigma A B = None ). apply saved_PC_dec.\n        destruct HsavedPC as [(pc, HsavedPC) | HnotPC].\n        + assert ( HcanSend : exists sigma' evs' index' pc',\n                        Network sigma' evs' \n                        /\\ List.In (publicly_Send B A pkt index' pc') evs' \n                        /\\ exists pre, evs' = pre ++ evs ).\n            eapply can_Send ; eauto.\n    *)\n    (* Pour démontrer ce théorème il y a 2 cas possibles :\n        cas 1 : les conditions sont réunies pour accepter une requête\n            alors pre = [ privately_Accept ... ; publicly_Send ... ]\n        cas 2 : au moins une des conditions n'est pas valide \n            alors pre = [ privately_Accept ... ; publicly_Send ... ;\n                            privately_reset ... ; publicly_ChallengeReply ... ;\n                            privately_nonce ... ; publicly_ChallengeRequest ... ]\n    Dans le cas 2, il faut montrer que la procédure de Challenge / Reply permet de réunir les conditions \n        pour accepter la requête.\n    Ces deux cas sont les seuls à montrer car ChallengeRequest et Send peuvent toujours se faire :\n        il s'agit des theoremes can_ChallengeRequest et can_Send *)\nAdmitted.\n\n(* Théorèmes de spoofing *)\n\n(* Fix me: this is not actually spoofing\nTheorem spoofing_Accept:\n    forall evs A B pkt index pc,\n        Network evs ->\n        List.In (privately_Accept A B pkt index pc) evs ->\n        exists evs', \n            Network evs'\n            /\\ List.In (privately_Accept A B pkt index pc) evs' \n            /\\ List.In (publicly Attacker A (format_MAC_Send B A pkt index pc)) evs'.\nProof.\n    intros evs A B pkt index pc. intros Hnetwork HIn.\n    assert (exists pc', \n                List.In ( publicly_Send B A pkt index pc ) evs\n                /\\ saved_index A B index evs \n                /\\ saved_PC A B pc' evs /\\ pc' < pc ) \n            as \n            [pc' (HinSend & (HsavedIndex & (HsavedPC & HorderPC)))]. \n    + eapply Accept_Inversion ; eauto.\n    + eexists. split.\n        - eapply Network_Accept ; eauto.\n        - split. \n            * eapply in_eq. \n            * apply in_cons. eapply insert_attack ; eauto.\nQed.*)\n\n(* Théorèmes d'unicité des événements *)\n\nLemma compatibiliy_knows_in: forall evs A B X,\n    List.In (publicly A B X) evs -> knows Attacker evs X.\nProof.\n    intros evs A B X. intro HIn.\n    apply in_split in HIn as [l1 [l2 HIn]]. subst.\n    induction l1.\n    - simpl. apply knows_attacker.\n    - rewrite <- app_comm_cons. apply knows_later. assumption.\nQed.\n\nTheorem replay: forall evs A B X, \n    Network evs -> \n    List.In (publicly A B X) evs ->\n    forall C, Network ( publicly Attacker C X :: evs ).\nProof.\n    intros evs A B X. intros Hnetwork HIn. intro C.\n    apply Network_Attack ; try auto.\n    apply synth_init. unfold In. apply analz_init. unfold In.\n    eapply compatibiliy_knows_in. eauto.\nQed.\n\nLemma distinct_index_PC_dec: \n    forall (index index': string) (pc pc': nat),\n        (index = index' /\\ pc = pc') \\/ (index <> index' \\/ pc <> pc').\nAdmitted.\n\nTheorem safety:\n    forall evs index pc A B pkt,\n        Network evs ->\n        unique ( privately_Accept A B pkt index pc ) evs.\nProof.\n    intros evs index pc A B pkt. intro Hnetwork.\n    unfold unique. induction Hnetwork.\n    - destruct IHHnetwork as [HnotIn | [pre [suff (Hevs & (HnotInPre & HnotInSuff))]]].\n        * left. apply not_in_cons. split ; easy.\n        * right. exists (publicly Attacker B0 X :: pre). exists suff. split.\n            + rewrite <- app_comm_cons. apply f_equal. assumption.\n            + split ; try easy. apply not_in_cons. split ; easy.\n    - auto.\n    - destruct IHHnetwork as [HnotIn | [pre [suff (Hevs & (HnotInPre & HnotInSuff))]]].\n        * left. apply not_in_cons. split ; easy.\n        * right. exists (privately_reset B0 A0 index_B :: pre). exists suff. split.\n            + rewrite <- app_comm_cons. apply f_equal. assumption.\n            + split ; try easy. apply not_in_cons. split ; easy.\n    - destruct IHHnetwork as [HnotIn | [pre [suff (Hevs & (HnotInPre & HnotInSuff))]]].\n        * left. apply not_in_cons. split ; easy.\n        * right. exists (publicly_Send B0 A0 pkt0 index_B pc_B :: pre). exists suff. split.\n            + rewrite <- app_comm_cons. apply f_equal. assumption.\n            + split ; try easy. apply not_in_cons. split ; easy.\n    - assert ( Hdiscriminate : (index = index_B /\\ pc = pc_B) \\/ (index <> index_B \\/ pc <> pc_B) ).\n        apply distinct_index_PC_dec. destruct Hdiscriminate as [(HindexEq & HpcEq) | Hdistinct].\n        * assert ( HeqAccept : privately_Accept A0 B0 pkt0 index_B pc_B = \n                                privately_Accept A B pkt index pc). admit.\n            right. exists []. exists evs. simpl. split.\n            + f_equal. subst. assumption.\n            + split ; try easy. rewrite <- HeqAccept. eapply Accept_unicity. eapply Network_Accept ; eauto.\n        * assert ( HdistinctAccept : privately_Accept A B pkt index pc <> \n                                    privately_Accept A0 B0 pkt0 index_B pc_B ). admit.\n            destruct IHHnetwork as [HnotIn | [pre [suff (Hin & HnotInPre & HnotInSuff)]]].            \n            + left. apply not_in_cons. split ; assumption.\n            + right. exists (privately_Accept A0 B0 pkt0 index_B pc_B :: pre). exists suff. split.\n                ++ rewrite <- app_comm_cons. apply f_equal. assumption.\n                ++ split ; try easy. apply not_in_cons. split ; assumption.\n    - destruct IHHnetwork as [HnotIn | [pre [suff (Hevs & (HnotInPre & HnotInSuff))]]].\n        * left. apply not_in_cons. split ; try easy.\n            apply not_in_cons. split ; easy.\n        * right. exists (privately_nonce A0 n0 :: publicly_ChallengeRequest A0 B0 n0 :: pre). \n            exists suff. split.\n            + rewrite <- app_comm_cons. rewrite <- app_comm_cons. apply f_equal. apply f_equal. assumption.\n            + split ; try easy. apply not_in_cons. split ; try easy.\n                apply not_in_cons. split ; easy.\n    - destruct IHHnetwork as [HnotIn | [pre [suff (Hevs & (HnotInPre & HnotInSuff))]]].\n        * left. apply not_in_cons. split ; try easy.\n            apply not_in_cons. split ; easy.\n        * right. exists (privately_reset B0 A0 index_B :: publicly_ChallengeReply B0 A0 n0 index_B 0 :: pre). \n            exists suff. split.\n            + rewrite <- app_comm_cons. rewrite <- app_comm_cons. apply f_equal. apply f_equal. assumption.\n            + split ; try easy. apply not_in_cons. split ; try easy.\n                apply not_in_cons. split ; easy.\nAdmitted.\n\n(* Théorèmes d'authenticité *)\n\nLemma in_inv:\n    forall {A} (a b: A) (l: list A), List.In a (b :: l) -> a <> b -> List.In a l.\nAdmitted.\n\nTheorem Send_authenticity:\n    forall evs A A' B B' pkt index pc,\n        Network evs ->\n        List.In (publicly A' B' (format_MAC_Send A B pkt index pc)) evs ->\n        List.In (publicly_Send A B pkt index pc) evs.\nProof.\n    intros evs A A' B B' pkt index pc. intros Hnetwork HIn.\n    induction Hnetwork ; try easy.\n    - (* Dans le cas de Network_Attack, on doit discriminer sur X,\n            - si X = format_MAC_Send A B pkt index pc alors, comme on a \n                synth (analz (knows Attacker evs)) X, on a, par définition de knows_attacker\n                    List.In (publicly A B X) evs.\n                Ainsi, on a List.In (publicly A B (format_MAC_Send A B pkt index pc)) evs.\n                D'où le résultat pour ce cas.\n            - sinon, on a alors \n                    publicly A' B' (format_MAC_Send A B pkt index pc) <> publicly Attacker B0 X\n                et donc on applique l'hypothèse de récurrence\n        *)\n        admit.\n    - apply in_cons. apply IHHnetwork. apply in_inv in HIn ; easy.\n    - (* Dans le cas de Network_Send, on doit discriminer sur l'égalité des couples (index, index_B)\n        et (pc, pc_B). En effet, il peut très bien y avoir d'autres messages échangés sur le réseau.\n        Dans le cas où les deux couples sont égaux, on est dans le cas où le message que l'on souhaite ajouter\n        avec Network_Send est celui qui nous intéresse.\n        Dans le cas où au moins l'un des deux couples est différent, on est dans le cas d'un autre message,\n        on applique alors l'hypothèse de récurrence *)\n        assert ( Hdiscriminate : (index = index_B /\\ pc = pc_B) \\/ (index <> index_B \\/ pc <> pc_B) ).\n        apply distinct_index_PC_dec. destruct Hdiscriminate as [(HindexEq & HpcEq) | Hdistinct].\n        * assert ( HeqSend : publicly_Send A B pkt index pc = \n                                publicly_Send B0 A0 pkt0 index_B pc_B). admit.\n            rewrite <- HeqSend. apply in_eq.\n        * assert ( HdistinctSend : publicly_Send A B pkt index pc <> \n                                publicly_Send B0 A0 pkt0 index_B pc_B). admit.\n            apply in_cons. apply IHHnetwork. apply in_inv in HIn ; try easy. admit.\n    - apply in_cons. apply IHHnetwork. apply in_inv in HIn ; easy.\n    - apply in_cons. apply in_cons. apply IHHnetwork. apply in_inv in HIn ; try easy. \n        apply in_inv in HIn ; easy.\n    - apply in_cons. apply in_cons. apply IHHnetwork. apply in_inv in HIn ; try easy. \n        apply in_inv in HIn ; easy.\nAdmitted.\n\nTheorem ChallengeRequest_authenticity:\n    forall evs A A' B B' n0,\n        Network evs ->\n        List.In (publicly A' B' (format_MAC_ChallengeRequest A B n0)) evs ->\n        List.In (publicly_ChallengeRequest A B n0) evs.\nProof.\n    intros evs A A' B B' n0. intros Hnetwork HIn.\n    induction Hnetwork ; try easy.\n    - admit.\n    - apply in_cons. apply IHHnetwork. apply in_inv in HIn ; easy.\n    - apply in_cons. apply IHHnetwork. apply in_inv in HIn ; easy.\n    - apply in_cons. apply IHHnetwork. apply in_inv in HIn ; easy.\n    - apply in_cons. assert ( Hdiscriminate : (n0 = n1) \\/ (n0 <> n1) ). admit. \n        destruct Hdiscriminate as [HeqNonce | HdistinctNonce].\n        * rewrite <- HeqNonce. assert ( HeqChallRequest : publicly_ChallengeRequest A B n0 =\n                                    publicly_ChallengeRequest A0 B0 n0 ). admit.\n            rewrite <- HeqChallRequest. apply in_eq.\n        * assert ( HdistinctChallReq : publicly_ChallengeRequest A B n0 <>\n                                        publicly_ChallengeRequest A0 B0 n1 ). admit.\n            apply in_cons. apply IHHnetwork. apply in_inv in HIn ; try easy.\n            apply in_inv in HIn ; try easy. admit.\n    - apply in_cons. apply in_cons. apply IHHnetwork. apply in_inv in HIn ; try easy.\n        apply in_inv in HIn ; easy.\nAdmitted.\n\nTheorem ChallengeReply_authenticity:\n    forall evs A A' B B' n0 index pc,\n        Network evs ->\n        List.In (publicly A' B' (format_MAC_ChallengeReply A B n0 index pc)) evs ->\n        List.In (publicly_ChallengeReply A B n0 index pc) evs.\nProof.\n    intros evs A A' B B' n0 index pc. intros Hnetwork HIn.\n    induction Hnetwork ; try easy.\n    - admit.\n    - apply in_cons. apply IHHnetwork. apply in_inv in HIn ; easy.\n    - apply in_cons. apply IHHnetwork. apply in_inv in HIn ; easy.\n    - apply in_cons. apply IHHnetwork. apply in_inv in HIn ; easy.\n    - apply in_cons.  apply IHHnetwork. apply in_inv in HIn ; try easy.\n    - apply in_cons. assert ( Hdiscriminate : (n0 = n1) \\/ (n0 <> n1) ). admit.\n        destruct Hdiscriminate as [HeqNonce | HdistinctNonce].\n        * rewrite <- HeqNonce. assert ( HeqChallReply : publicly_ChallengeReply A B n0 index pc =\n                                                        publicly_ChallengeReply B0 A0 n0 index_B 0 ). admit.\n            rewrite <- HeqChallReply. apply in_eq.\n        * assert ( HdistinctChallRep : publicly_ChallengeReply A B n0 index pc <>\n                                        publicly_ChallengeReply B0 A0 n1 index_B 0 ). admit.\n            apply in_cons. apply IHHnetwork. apply in_inv in HIn ; try easy.\n            apply in_inv in HIn ; try easy. admit.\nAdmitted.", "meta": {"author": "BtheCat", "repo": "babel-MAC", "sha": "295ffd0adcb1338ce49f1e25da54a3c47543a055", "save_path": "github-repos/coq/BtheCat-babel-MAC", "path": "github-repos/coq/BtheCat-babel-MAC/babel-MAC-295ffd0adcb1338ce49f1e25da54a3c47543a055/babel_bella.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.26847850273573276}}
{"text": "Set Implicit Arguments.\n\nRequire Import Coq.Structures.DecidableTypeEx.\nRequire Import Coq.FSets.FMapInterface.\nRequire Bedrock.Platform.Cito.ListFacts1.\nRequire Bedrock.Platform.Cito.FMapFacts1.\nRequire Bedrock.Platform.Cito.GeneralTactics.\nRequire Bedrock.Platform.Cito.GeneralTactics2.\nRequire Bedrock.Platform.Cito.Option.\nRequire Bedrock.Platform.Cito.GeneralTactics4.\nRequire Bedrock.Platform.Cito.ListFacts4.\nRequire Bedrock.Platform.Cito.SetoidListFacts.\n\nModule UWFacts_fun (E : UsualDecidableType) (Import M : WSfun E).\n\n  Import Bedrock.Platform.Cito.ListFacts1.\n\n  Import Bedrock.Platform.Cito.FMapFacts1.\n  Module Import UWFacts := UWFacts_fun E M.\n  Import WFacts.\n  Import P.\n  Import F.\n\n  Definition Submap {elt} m1 m2 := forall {k v}, @find elt k m1 = Some v -> find k m2 = Some v.\n  Definition direct_sum elt (h1 h2 h12 : t elt) := (Equal (update h1 h2) h12 /\\ Disjoint h1 h2).\n\n  Module FMapNotations.\n    Infix \"==\" := (@Equal _) (at level 70) : fmap_scope.\n    Notation \"{}\" := (@empty _) : fmap_scope.\n    Infix \"-\" := (@diff _) : fmap_scope.\n    Infix \"+\" := (@update _) : fmap_scope.\n    Infix \"<=\" := Submap : fmap_scope.\n    Notation \"h1 * h2 === h12\" := (direct_sum h1 h2 h12) (at level 100) : fmap_scope.\n    Delimit Scope fmap_scope with fmap.\n  End FMapNotations.\n\n  Section TopSection.\n\n    Import Bedrock.Platform.Cito.GeneralTactics.\n    Import Bedrock.Platform.Cito.GeneralTactics2.\n    Import Bedrock.Platform.Cito.Option.\n    Import ListNotations.\n    Import FMapNotations.\n    Open Scope fmap_scope.\n\n    Hint Extern 1 => reflexivity.\n\n    Section Elt.\n\n      Variable elt:Type.\n\n      Implicit Types m : t elt.\n      Implicit Types x y z k : key.\n      Implicit Types e v : elt.\n      Implicit Types ls : list (key * elt).\n\n      Notation eqke := (@eq_key_elt elt).\n      Notation eqk := (@eq_key elt).\n\n      Lemma In_MapsTo : forall k m, In k m -> exists v, MapsTo k v m.\n        unfold In; eauto.\n      Qed.\n\n      Lemma not_in_find : forall k m, ~ In k m -> find k m = None.\n        intros; eapply not_find_in_iff; eauto.\n      Qed.\n\n      Lemma of_list_empty : of_list [] == @empty elt.\n        eauto.\n      Qed.\n\n      (* update *)\n\n      Lemma update_o_1 : forall k m1 m2, ~ In k m2 -> find k (m1 + m2) = find k m1.\n        intros.\n        eapply option_univalence; split; intros.\n        eapply find_2 in H0; eapply update_mapsto_iff in H0; openhyp.\n        eapply MapsTo_In in H0; intuition.\n        eapply find_1; eauto.\n        eapply find_2 in H0.\n        eapply find_1; eapply update_mapsto_iff; eauto.\n      Qed.\n\n      Lemma update_o_2 : forall k m1 m2, In k m2 -> find k (m1 + m2) = find k m2.\n        intros.\n        eapply option_univalence; split; intros.\n        eapply find_2 in H0; eapply update_mapsto_iff in H0; openhyp.\n        eapply find_1; eauto.\n        intuition.\n        eapply find_2 in H0.\n        eapply find_1; eapply update_mapsto_iff; eauto.\n      Qed.\n\n      Lemma update_empty_1 : forall m, {} + m == m.\n        unfold Equal; intros.\n        eapply option_univalence; split; intros.\n        eapply find_2 in H.\n        eapply update_mapsto_iff in H; openhyp.\n        eapply find_1; eauto.\n        eapply empty_mapsto_iff in H; intuition.\n        eapply find_2 in H.\n        eapply find_1; eapply update_mapsto_iff; eauto.\n      Qed.\n\n      Lemma update_empty_2 : forall m, m + {} == m.\n        unfold Equal; intros.\n        eapply option_univalence; split; intros.\n        eapply find_2 in H.\n        eapply update_mapsto_iff in H; openhyp.\n        eapply empty_mapsto_iff in H; intuition.\n        eapply find_1; eauto.\n        eapply find_2 in H.\n        eapply find_1; eapply update_mapsto_iff.\n        right; split; eauto.\n        intuition.\n        eapply empty_in_iff; eauto.\n      Qed.\n\n      Lemma update_assoc : forall m1 m2 m3, m1 + m2 + m3 == m1 + (m2 + m3).\n        intros.\n        unfold Equal.\n        intros.\n        eapply option_univalence.\n        split; intros.\n        eapply find_2 in H.\n        eapply update_mapsto_iff in H.\n        openhyp.\n        eapply find_1.\n        eapply update_mapsto_iff.\n        left.\n        eapply update_mapsto_iff.\n        eauto.\n        eapply update_mapsto_iff in H.\n        openhyp.\n        eapply find_1.\n        eapply update_mapsto_iff.\n        left.\n        eapply update_mapsto_iff.\n        eauto.\n        eapply find_1.\n        eapply update_mapsto_iff.\n        right.\n        split; eauto.\n        not_not.\n        eapply update_in_iff in H2.\n        intuition.\n\n        eapply find_2 in H.\n        eapply update_mapsto_iff in H.\n        openhyp.\n        eapply update_mapsto_iff in H.\n        openhyp.\n        eapply find_1.\n        eapply update_mapsto_iff.\n        eauto.\n        eapply find_1.\n        eapply update_mapsto_iff.\n        right.\n        split; eauto.\n        eapply update_mapsto_iff.\n        eauto.\n        eapply find_1.\n        eapply update_mapsto_iff.\n        right.\n        split.\n        eapply update_mapsto_iff.\n        right.\n        split; eauto.\n        not_not.\n        eapply update_in_iff.\n        eauto.\n        not_not.\n        eapply update_in_iff.\n        eauto.\n      Qed.\n\n      Lemma update_self : forall m, m + m == m.\n        unfold Equal; intros.\n        eapply option_univalence; split; intros.\n        eapply find_2 in H; eapply update_mapsto_iff in H; openhyp.\n        eapply find_1; eauto.\n        eapply MapsTo_In in H; intuition.\n        eapply find_2 in H.\n        eapply find_1; eapply update_mapsto_iff; eauto.\n      Qed.\n\n      Lemma update_same : forall m1 m2, m1 == m2 -> m1 + m2 == m1.\n        intros.\n        rewrite H.\n        eapply update_self.\n      Qed.\n\n      Lemma update_diff_same : forall m1 m2 m3, m1 - m3 + (m2 - m3) == m1 + m2 - m3.\n        intros.\n        unfold Equal.\n        intros.\n        eapply option_univalence.\n        split; intros.\n        eapply find_2 in H.\n        eapply update_mapsto_iff in H.\n        openhyp.\n        eapply diff_mapsto_iff in H.\n        openhyp.\n        eapply find_1.\n        eapply diff_mapsto_iff.\n        split; eauto.\n        eapply update_mapsto_iff.\n        eauto.\n        eapply diff_mapsto_iff in H.\n        openhyp.\n        eapply find_1.\n        eapply diff_mapsto_iff.\n        split; eauto.\n        eapply update_mapsto_iff.\n        right.\n        split; eauto.\n        not_not.\n        eapply diff_in_iff; eauto.\n\n        eapply find_2 in H.\n        eapply diff_mapsto_iff in H.\n        openhyp.\n        eapply update_mapsto_iff in H.\n        openhyp.\n        eapply find_1.\n        eapply update_mapsto_iff.\n        left.\n        eapply diff_mapsto_iff; eauto.\n        eapply find_1.\n        eapply update_mapsto_iff.\n        right.\n        split.\n        eapply diff_mapsto_iff; eauto.\n        not_not.\n        eapply diff_in_iff in H2.\n        intuition.\n      Qed.\n\n      Lemma Disjoint_diff_update_comm : forall m1 m2 m3, Disjoint m2 m3 -> m1 - m2 + m3 == m1 + m3 - m2.\n        intros.\n        unfold Equal.\n        intros.\n        eapply option_univalence.\n        split; intros.\n        eapply find_2 in H0.\n        eapply update_mapsto_iff in H0.\n        openhyp.\n        eapply find_1.\n        eapply diff_mapsto_iff.\n        split.\n        eapply update_mapsto_iff.\n        eauto.\n        unfold Disjoint in *.\n        intuition.\n        eapply H.\n        split; eauto.\n        eapply MapsTo_In; eauto.\n        eapply diff_mapsto_iff in H0.\n        openhyp.\n        eapply find_1.\n        eapply diff_mapsto_iff.\n        split; eauto.\n        eapply update_mapsto_iff.\n        eauto.\n\n        eapply find_2 in H0.\n        eapply diff_mapsto_iff in H0.\n        openhyp.\n        eapply update_mapsto_iff in H0.\n        openhyp.\n        eapply find_1.\n        eapply update_mapsto_iff.\n        eauto.\n        eapply find_1.\n        eapply update_mapsto_iff.\n        right.\n        split; eauto.\n        eapply diff_mapsto_iff.\n        eauto.\n      Qed.\n\n      (* update_all *)\n\n      Definition update_all ms := List.fold_left (fun acc m => update acc m) ms (@empty elt).\n\n      Lemma update_all_nil : update_all [] == {}.\n        eauto.\n      Qed.\n\n      Lemma update_all_single : forall m, update_all [m] == m.\n        intros.\n        unfold update_all; simpl.\n        eapply update_empty_1.\n      Qed.\n\n      Definition update_all' m ms := fold_left (fun acc m0 : t elt => acc + m0) ms m.\n\n      Lemma update_all'_m' : forall ms m1 m2, m1 == m2 -> update_all' m1 ms == update_all' m2 ms.\n        unfold update_all'.\n        induction ms; simpl; intros.\n        eauto.\n        erewrite IHms.\n        eauto.\n        rewrite H.\n        eauto.\n      Qed.\n\n      Global Add Morphism update_all'\n          with signature Equal ==> Logic.eq ==> Equal as update_all'_m.\n        intros; eapply update_all'_m'; eauto.\n      Qed.\n\n      Lemma update_all_cons : forall ms m, update_all (m :: ms) == m + (update_all ms).\n        induction ms; simpl; intros.\n        rewrite update_all_nil.\n        rewrite update_all_single.\n        rewrite update_empty_2.\n        eauto.\n        unfold update_all in *.\n        simpl in *.\n        rewrite IHms.\n        replace (fold_left (fun acc m0 : t elt => acc + m0) ms ({} + m + a)) with (update_all' ({} + m + a) ms) by reflexivity.\n        rewrite update_assoc.\n        unfold update_all'.\n        rewrite IHms.\n        rewrite update_assoc.\n        eauto.\n      Qed.\n\n      Lemma update_all_Equal : forall ms1 ms2, List.Forall2 (@Equal elt) ms1 ms2 -> update_all ms1 == update_all ms2.\n        induction 1; simpl; intros.\n        eauto.\n        repeat rewrite update_all_cons.\n        rewrite H.\n        rewrite IHForall2.\n        eauto.\n      Qed.\n\n      Lemma app_all_update_all : forall lsls, @NoDupKey elt (app_all lsls) -> of_list (app_all lsls) == update_all (List.map (@of_list _) lsls).\n        induction lsls; simpl; intros.\n        eauto.\n        rewrite update_all_cons.\n        rewrite of_list_app; eauto.\n        rewrite IHlsls; eauto.\n        eapply NoDupKey_unapp2; eauto.\n      Qed.\n\n      Lemma update_all_elim : forall ms k v, MapsTo k v (update_all ms) -> exists m, List.In m ms /\\ MapsTo k v m.\n        induction ms; simpl; intros.\n        rewrite update_all_nil in H.\n        eapply empty_mapsto_iff in H; intuition.\n        rewrite update_all_cons in H.\n        eapply update_mapsto_iff in H; openhyp.\n        eapply IHms in H; openhyp.\n        eexists; split; eauto.\n        eexists; split; eauto.\n      Qed.\n\n      (* diff *)\n\n      Lemma diff_empty : forall m, diff m {} == m.\n        unfold Equal; intros.\n        eapply option_univalence; split; intros.\n        eapply find_2 in H; eapply diff_mapsto_iff in H; openhyp.\n        eapply find_1; eauto.\n        eapply find_2 in H.\n        eapply find_1.\n        eapply diff_mapsto_iff; split; eauto.\n        intuition; eapply empty_in_iff; eauto.\n      Qed.\n\n      Lemma empty_diff : forall m, {} - m == {}.\n        unfold Equal; intros.\n        eapply option_univalence; split; intros.\n        eapply find_2 in H; eapply diff_mapsto_iff in H; openhyp.\n        eapply empty_mapsto_iff in H; intuition.\n        eapply find_2 in H; eapply empty_mapsto_iff in H; intuition.\n      Qed.\n\n      Lemma diff_same : forall m, m - m == {}.\n        unfold Equal; intros.\n        eapply option_univalence; split; intros.\n        eapply find_2 in H; eapply diff_mapsto_iff in H; openhyp.\n        eapply MapsTo_In in H; intuition.\n        eapply find_2 in H; eapply empty_mapsto_iff in H; intuition.\n      Qed.\n\n      Lemma diff_update : forall m1 m2 m3, m1 - (m2 + m3) == m1 - m2 - m3.\n        unfold Equal; intros.\n        eapply option_univalence; split; intros.\n        eapply find_2 in H; eapply diff_mapsto_iff in H; openhyp.\n        eapply find_1.\n        eapply diff_mapsto_iff; split.\n        eapply diff_mapsto_iff; split; eauto.\n        not_not; eapply update_in_iff; eauto.\n        not_not; eapply update_in_iff; eauto.\n        eapply find_2 in H; eapply diff_mapsto_iff in H; openhyp.\n        eapply diff_mapsto_iff in H; openhyp.\n        eapply find_1.\n        eapply diff_mapsto_iff; split; eauto.\n        not_not; eapply update_in_iff in H2; intuition.\n      Qed.\n\n      Lemma diff_diff_sym : forall m1 m2 m3, m1 - m2 - m3 == m1 - m3 - m2.\n        unfold Equal; intros.\n        eapply option_univalence; split; intros.\n        eapply find_2 in H; eapply diff_mapsto_iff in H; openhyp.\n        eapply diff_mapsto_iff in H; openhyp.\n        eapply find_1.\n        eapply diff_mapsto_iff; split; eauto.\n        eapply diff_mapsto_iff; split; eauto.\n        eapply find_2 in H; eapply diff_mapsto_iff in H; openhyp.\n        eapply diff_mapsto_iff in H; openhyp.\n        eapply find_1.\n        eapply diff_mapsto_iff; split; eauto.\n        eapply diff_mapsto_iff; split; eauto.\n      Qed.\n\n      Lemma diff_o : forall k m1 m2, ~ In k m2 -> find k (m1 - m2) = find k m1.\n        intros.\n        eapply option_univalence; split; intros.\n        eapply find_2 in H0; eapply diff_mapsto_iff in H0; openhyp.\n        eapply find_1; eauto.\n        eapply find_2 in H0.\n        eapply find_1; eapply diff_mapsto_iff; split; eauto.\n      Qed.\n\n      Lemma diff_o_none : forall k m1 m2, In k m2 -> find k (m1 - m2) = None.\n        intros.\n        eapply not_in_find.\n        intuition.\n        eapply diff_in_iff in H0.\n        intuition.\n      Qed.\n\n      (* Compat *)\n\n      Definition Compat m1 m2 := forall k, In k m1 -> In k m2 -> find k m1 = find k m2.\n\n      Lemma Compat_sym : forall m1 m2, Compat m1 m2 -> Compat m2 m1.\n        unfold Compat; intros; symmetry; eauto.\n      Qed.\n\n      Lemma Compat_refl : forall m, Compat m m.\n        unfold Compat; intros; eauto.\n      Qed.\n\n      Global Add Parametric Relation : (t elt) Compat\n          reflexivity proved by Compat_refl\n          symmetry proved by Compat_sym\n            as Compat_rel.\n\n      Global Add Morphism Compat\n          with signature Equal ==> Equal ==> iff as Compat_m.\n        unfold Compat; intros.\n        intuition.\n        rewrite <- H in *.\n        rewrite <- H0 in *.\n        eauto.\n        rewrite H in *.\n        rewrite H0 in *.\n        eauto.\n      Qed.\n\n      Lemma Compat_diff : forall m1 m2 m, Compat m1 m2 -> Compat (m1 - m) m2.\n        unfold Compat; intros.\n        rewrite <- H; eauto.\n        rewrite diff_o; eauto.\n        eapply diff_in_iff in H0; intuition.\n        eapply diff_in_iff in H0; intuition.\n      Qed.\n\n      Lemma Compat_empty : forall m, Compat m {}.\n        unfold Compat; intros.\n        eapply empty_in_iff in H0; intuition.\n      Qed.\n\n      Lemma Compat_update : forall m1 m2 m3, Compat m1 m2 -> Compat m1 m3 -> Compat m1 (m2 + m3).\n        unfold Compat; intros.\n        destruct (In_dec m3 k).\n        rewrite update_o_2; eauto.\n        rewrite update_o_1; eauto.\n        eapply H; eauto.\n        eapply update_in_iff in H2; intuition.\n      Qed.\n\n      Lemma Compat_update_sym : forall m1 m2, Compat m1 m2 -> m1 + m2 == m2 + m1.\n        unfold Compat; intros.\n        unfold Equal; intros.\n        destruct (In_dec m1 y); destruct (In_dec m2 y).\n        rewrite update_o_2 by eauto.\n        rewrite update_o_2 by eauto.\n        symmetry; eauto.\n        rewrite update_o_1 by eauto.\n        rewrite update_o_2 by eauto.\n        eauto.\n        rewrite update_o_2 by eauto.\n        rewrite update_o_1 by eauto.\n        eauto.\n        rewrite update_o_1 by eauto.\n        rewrite update_o_1 by eauto.\n        repeat rewrite not_in_find; eauto.\n      Qed.\n\n      Lemma Compat_update_all : forall ms m, List.Forall (Compat m) ms -> Compat m (update_all ms).\n        induction ms; simpl; intros.\n        unfold update_all; simpl.\n        eapply Compat_empty.\n        rewrite update_all_cons.\n        inversion H; subst.\n        eapply Compat_update; eauto.\n      Qed.\n\n      Lemma Compat_add_not_In : forall k v m1 m2, Compat (add k v m1) m2 -> ~ In k m1 -> Compat m1 m2.\n        intros.\n        unfold Compat in *.\n        intros.\n        erewrite <- H; eauto.\n        rewrite add_neq_o; eauto.\n        not_not.\n        subst; eauto.\n        eapply add_in_iff; eauto.\n      Qed.\n\n      Lemma Compat_eq : forall k v1 v2 m1 m2, Compat m1 m2 -> find k m1 = Some v1 -> find k m2 = Some v2 -> v1 = v2.\n        intros.\n        unfold Compat in *.\n        erewrite H in H0.\n        congruence.\n        eapply find_2 in H0.\n        eapply MapsTo_In; eauto.\n        eapply find_2 in H1.\n        eapply MapsTo_In; eauto.\n      Qed.\n\n      Lemma Compat_MapsTo : forall m1 m2, Compat m1 m2 -> forall k v1 v2, MapsTo k v1 m1 -> MapsTo k v2 m2 -> v1 = v2.\n        intros.\n        generalize H0; intro.\n        generalize H1; intro.\n        eapply find_1 in H0.\n        eapply find_1 in H1.\n        rewrite H in H0.\n        rewrite H0 in H1.\n        injection H1; intros; eauto.\n        eapply MapsTo_In; eauto.\n        eapply MapsTo_In; eauto.\n      Qed.\n\n      Definition AllCompat := ForallOrdPairs Compat.\n\n      Lemma update_all_intro : forall ms, AllCompat ms -> forall k v m, List.In m ms -> MapsTo k v m -> MapsTo k v (update_all ms).\n        induction 1; simpl; intros.\n        intuition.\n        openhyp.\n        subst.\n        rewrite update_all_cons.\n        destruct (In_dec (update_all l) k).\n        eapply In_MapsTo in i.\n        openhyp.\n        eapply Compat_update_all in H.\n        eapply Compat_MapsTo in H; eauto.\n        subst.\n        eapply update_mapsto_iff; eauto.\n        eapply update_mapsto_iff; eauto.\n        rewrite update_all_cons.\n        eapply update_mapsto_iff; eauto.\n      Qed.\n\n      (* Disjoint *)\n\n      Global Add Parametric Relation : (t elt) (@Disjoint elt)\n          symmetry proved by (@Disjoint_sym elt)\n            as Disjoint_rel.\n\n      Lemma Disjoint_Compat : forall m1 m2, Disjoint m1 m2 -> Compat m1 m2.\n        unfold Disjoint, Compat; intros; firstorder.\n      Qed.\n\n      Lemma Disjoint_empty : forall m, Disjoint m {}.\n        unfold Disjoint; intros.\n        intuition.\n        eapply empty_in_iff in H1; intuition.\n      Qed.\n\n      Lemma Disjoint_update : forall m1 m2 m3, Disjoint m1 m2 -> Disjoint m1 m3 -> Disjoint m1 (m2 + m3).\n        unfold Disjoint; intros.\n        intuition.\n        eapply update_in_iff in H3; firstorder.\n      Qed.\n\n      Lemma Disjoint_update_sym : forall m1 m2, Disjoint m1 m2 -> update m1 m2 == update m2 m1.\n        intros.\n        eapply Compat_update_sym.\n        eapply Disjoint_Compat; eauto.\n      Qed.\n\n      Lemma Disjoint_diff : forall m1 m2 m3, Disjoint m1 m2 -> Disjoint m1 (m2 - m3).\n        unfold Disjoint; intros.\n        intuition.\n        eapply diff_in_iff in H2; firstorder.\n      Qed.\n\n      Lemma Disjoint_after_diff : forall m1 m2, Disjoint (m1 - m2) m2.\n        unfold Disjoint; intros.\n        intuition.\n        eapply diff_in_iff in H0; firstorder.\n      Qed.\n\n      Lemma Disjoint_diff_no_effect : forall m1 m2, Disjoint m1 m2 -> m1 - m2 == m1.\n        unfold Equal; intros.\n        eapply option_univalence; split; intros.\n        eapply find_2 in H0; eapply diff_mapsto_iff in H0; openhyp.\n        eapply find_1; eauto.\n        eapply find_2 in H0.\n        eapply find_1; eapply diff_mapsto_iff; split; eauto.\n        intuition; eapply H; split; eauto.\n        eapply MapsTo_In; eauto.\n      Qed.\n\n      Lemma Disjoint_update_all : forall ms m, List.Forall (Disjoint m) ms -> Disjoint m (update_all ms).\n        induction ms; simpl; intros.\n        unfold update_all; simpl.\n        eapply Disjoint_empty.\n        rewrite update_all_cons.\n        inversion H; subst.\n        eapply Disjoint_update; eauto.\n      Qed.\n\n      (* map *)\n\n      Lemma map_empty : forall B (f : elt -> B), map f {} == {}.\n        unfold Equal; intros.\n        rewrite map_o.\n        repeat rewrite empty_o.\n        eauto.\n      Qed.\n\n      Lemma map_add : forall B (f : _ -> B) k v m, map f (add k v m) == add k (f v) (map f m).\n        unfold Equal; intros.\n        rewrite map_o.\n        repeat rewrite add_o.\n        destruct (eq_dec k y).\n        eauto.\n        rewrite map_o.\n        eauto.\n      Qed.\n\n      Lemma map_update : forall B (f : _ -> B) m1 m2, map f (m1 + m2) == map f m1 + map f m2.\n        unfold Equal; intros.\n        eapply option_univalence.\n        split; intros.\n        eapply find_2 in H.\n        eapply map_mapsto_iff in H.\n        openhyp.\n        subst.\n        eapply update_mapsto_iff in H0.\n        openhyp.\n        eapply find_1.\n        eapply update_mapsto_iff.\n        left.\n        eapply map_mapsto_iff.\n        eexists; eauto.\n        eapply find_1.\n        eapply update_mapsto_iff.\n        right.\n        split.\n        eapply map_mapsto_iff.\n        eexists; eauto.\n        not_not.\n        eapply map_in_iff; eauto.\n\n        eapply find_2 in H.\n        eapply update_mapsto_iff in H.\n        openhyp.\n        eapply map_mapsto_iff in H.\n        openhyp.\n        subst.\n        eapply find_1.\n        eapply map_mapsto_iff.\n        eexists; split; eauto.\n        eapply update_mapsto_iff.\n        eauto.\n        eapply map_mapsto_iff in H.\n        openhyp.\n        subst.\n        eapply find_1.\n        eapply map_mapsto_iff.\n        eexists; split; eauto.\n        eapply update_mapsto_iff.\n        right.\n        split; eauto.\n        not_not.\n        eapply map_in_iff; eauto.\n      Qed.\n\n      Lemma map_of_list : forall B (f : elt -> B) ls, map f (of_list ls) == of_list (List.map (fun p => (fst p, f (snd p))) ls).\n        induction ls; simpl; intros.\n        eapply map_empty.\n        unfold uncurry; simpl in *.\n        rewrite <- IHls.\n        destruct a; simpl in *.\n        eapply map_add.\n      Qed.\n\n      (* mapi *)\n\n      Global Add Parametric Morphism elt' : (@mapi elt elt')\n          with signature Logic.eq ==> Equal ==> Equal as mapi_m.\n        intros; subst; eauto.\n        unfold Equal; intros.\n        repeat rewrite mapi_o.\n        rewrite H; eauto.\n        intros; subst; eauto.\n        intros; subst; eauto.\n      Qed.\n\n      Lemma find_mapi :\n        forall B (f : _ -> _ -> B) k v m,\n          find k m = Some v ->\n          find k (mapi f m) = Some (f k v).\n        intros.\n        rewrite mapi_o.\n        rewrite H.\n        eauto.\n        intros; subst; eauto.\n      Qed.\n\n      Lemma mapi_empty : forall B (f : _ -> elt -> B), mapi f {} == {}.\n        unfold Equal; intros.\n        rewrite mapi_o.\n        repeat rewrite empty_o.\n        eauto.\n        intros.\n        subst.\n        eauto.\n      Qed.\n\n      Lemma mapi_add : forall B (f : _ -> _ -> B) k v m, mapi f (add k v m) == add k (f k v) (mapi f m).\n        unfold Equal; intros.\n        rewrite mapi_o.\n        repeat rewrite add_o.\n        destruct (eq_dec k y).\n        subst.\n        eauto.\n        rewrite mapi_o.\n        eauto.\n        intros; subst; eauto.\n        intros; subst; eauto.\n      Qed.\n\n      Lemma mapi_of_list : forall B (f : _ -> _ -> B) ls, mapi f (of_list ls) == of_list (List.map (fun p => (fst p, f (fst p) (snd p))) ls).\n        induction ls; simpl; intros.\n        eapply mapi_empty.\n        unfold uncurry; simpl in *.\n        rewrite <- IHls.\n        destruct a; simpl in *.\n        eapply mapi_add.\n      Qed.\n\n      Lemma mapi_update : forall B (f : _ -> _ -> B) m1 m2, mapi f (m1 + m2) == mapi f m1 + mapi f m2.\n        unfold Equal; intros.\n        eapply option_univalence.\n        split; intros.\n        eapply find_2 in H.\n        eapply mapi_mapsto_iff in H.\n        openhyp.\n        subst.\n        eapply update_mapsto_iff in H0.\n        openhyp.\n        eapply find_1.\n        eapply update_mapsto_iff.\n        left.\n        eapply mapi_mapsto_iff.\n        intros; subst; eauto.\n        eexists; eauto.\n        eapply find_1.\n        eapply update_mapsto_iff.\n        right.\n        split.\n        eapply mapi_mapsto_iff.\n        intros; subst; eauto.\n        eexists; eauto.\n        not_not.\n        eapply mapi_in_iff; eauto.\n        intros; subst; eauto.\n\n        eapply find_2 in H.\n        eapply update_mapsto_iff in H.\n        openhyp.\n        eapply mapi_mapsto_iff in H.\n        openhyp.\n        subst.\n        eapply find_1.\n        eapply mapi_mapsto_iff.\n        intros; subst; eauto.\n        eexists; split; eauto.\n        eapply update_mapsto_iff.\n        eauto.\n        intros; subst; eauto.\n        eapply mapi_mapsto_iff in H.\n        openhyp.\n        subst.\n        eapply find_1.\n        eapply mapi_mapsto_iff.\n        intros; subst; eauto.\n        eexists; split; eauto.\n        eapply update_mapsto_iff.\n        right.\n        split; eauto.\n        not_not.\n        eapply mapi_in_iff; eauto.\n        intros; subst; eauto.\n      Qed.\n\n      Lemma NoDupKey_app_all_elim : forall lsls, NoDupKey (app_all lsls) -> forall ls, List.In ls lsls -> NoDupKey ls.\n        induction lsls; simpl; intuition.\n        subst.\n        eapply NoDupKey_unapp1; eauto.\n        eapply IHlsls; eauto.\n        eapply NoDupKey_unapp2; eauto.\n      Qed.\n\n      Lemma NoDupKey_app_all_AllCompat : forall lsls, NoDupKey (app_all lsls) -> AllCompat (List.map (@of_list _) lsls).\n        induction lsls; simpl; intuition.\n        econstructor.\n        econstructor.\n        eapply Forall_forall.\n        intros.\n        eapply in_map_iff in H0; openhyp; subst.\n        eapply Disjoint_Compat.\n        unfold Disjoint.\n        intros.\n        nintro.\n        openhyp.\n        eapply In_of_list in H0.\n        eapply In_of_list in H2.\n        generalize H; intros.\n        eapply NoDupKey_app_DisjointKey in H.\n        eapply H.\n        split; eauto.\n        unfold InKey in *.\n        rewrite map_app_all.\n        eapply In_app_all_intro; eauto.\n        eapply in_map; eauto.\n        eapply NoDupKey_unapp2 in H.\n        eapply NoDupKey_app_all_elim; eauto.\n        eapply NoDupKey_unapp1; eauto.\n        eapply IHlsls.\n        eapply NoDupKey_unapp2; eauto.\n      Qed.\n\n    End Elt.\n\n    Lemma map_update_all_comm : forall elt B (f : elt -> B) ms, map f (update_all ms) == update_all (List.map (map f) ms).\n      induction ms; simpl; intros.\n      repeat rewrite update_all_nil.\n      rewrite map_empty.\n      eauto.\n      repeat rewrite update_all_cons.\n      rewrite map_update.\n      rewrite IHms.\n      eauto.\n    Qed.\n\n\n    Lemma mapi_update_all_comm : forall elt B (f : _ -> elt -> B) ms, mapi f (update_all ms) == update_all (List.map (mapi f) ms).\n      induction ms; simpl; intros.\n      repeat rewrite update_all_nil.\n      rewrite mapi_empty; eauto.\n      eauto.\n      repeat rewrite update_all_cons.\n      rewrite mapi_update.\n      rewrite IHms.\n      eauto.\n    Qed.\n\n    (* newly added from Facade *)\n\n    Lemma find_Some_in : forall elt k m (v : elt), find k m = Some v -> In k m.\n      intros; eapply MapsTo_In; eapply find_mapsto_iff; eauto.\n    Qed.\n\n    Lemma in_find_Some elt k m : In k m -> exists v : elt, find k m = Some v.\n      intros H.\n      eapply In_MapsTo in H.\n      destruct H as [v H].\n      eapply find_mapsto_iff in H.\n      eauto.\n    Qed.\n\n    Lemma diff_disjoint elt m1 m2 : @Disjoint elt (m1 - m2) m2.\n    Proof.\n      unfold Disjoint.\n      intros k.\n      nintro.\n      openhyp.\n      eapply diff_in_iff in H.\n      openhyp; intuition.\n    Qed.\n\n    Lemma Disjoint_in_not elt h1 h2 x : @Disjoint elt h1 h2 -> In x h1 -> ~ In x h2.\n    Proof.\n      intros Hdisj Hin1 Hin2.\n      eapply Hdisj; eauto.\n    Qed.\n\n    Lemma diff_find_Some_iff : forall elt k (v : elt) m m', find k (m - m') = Some v <-> find k m = Some v /\\ ~ In k m'.\n      split; intros.\n      eapply find_mapsto_iff in H.\n      eapply diff_mapsto_iff in H; openhyp.\n      eapply find_mapsto_iff in H.\n      eauto.\n      openhyp.\n      eapply find_mapsto_iff.\n      eapply diff_mapsto_iff.\n      eapply find_mapsto_iff in H.\n      eauto.\n    Qed.\n\n    Lemma diff_swap_find elt k (v : elt) h h1 h2 : find k (h - h1 - h2) = Some v -> find k (h - h2 - h1) = Some v.\n    Proof.\n      intros Hf.\n      eapply diff_find_Some_iff in Hf.\n      destruct Hf as [Hf Hni2].\n      eapply diff_find_Some_iff in Hf.\n      destruct Hf as [Hf Hni1].\n      eapply diff_find_Some_iff.\n      split.\n      eapply diff_find_Some_iff.\n      eauto.\n      eauto.\n    Qed.\n\n    Lemma diff_swap elt (h h1 h2 : t elt) : h - h1 - h2 == h - h2 - h1.\n    Proof.\n      unfold Equal.\n      intros k.\n      eapply option_univalence.\n      intros v; split; intros Hf; eapply diff_swap_find; eauto.\n    Qed.\n\n    Global Add Parametric Morphism elt : (@Submap elt)\n        with signature Equal ==> Equal ==> iff as Submap_m.\n    Proof.\n      intros x y Hxy x' y' Hx'y'.\n      unfold Submap.\n      split; intros H.\n      intros k v Hf.\n      rewrite <- Hx'y' in *.\n      rewrite <- Hxy in *.\n      eauto.\n      intros k v Hf.\n      rewrite Hx'y' in *.\n      rewrite Hxy in *.\n      eauto.\n    Qed.\n\n    Lemma submap_trans elt (a b c : t elt) : a <= b -> b <= c -> a <= c.\n    Proof.\n      intros Hab Hbc; unfold Submap; intros k v Hf; eapply Hbc; eauto.\n    Qed.\n\n    Lemma submap_find : forall elt k (v : elt) m1 m2, m1 <= m2 -> find k m1 = Some v -> find k m2 = Some v.\n      unfold Submap; eauto.\n    Qed.\n\n    Lemma submap_in elt h1 h2 : h1 <= h2 -> forall k, @In elt k h1 -> In k h2.\n    Proof.\n      intros Hsm k Hi.\n      eapply in_find_Some in Hi.\n      destruct Hi as [v Hf].\n      eapply find_Some_in; eauto.\n    Qed.\n\n    Lemma diff_submap elt (m1 m2 : t elt) : m1 - m2 <= m1.\n    Proof.\n      unfold Submap.\n      intros k v Hf.\n      eapply diff_find_Some_iff in Hf; openhyp; eauto.\n    Qed.\n\n    Lemma submap_not_in : forall elt h1 h2, h1 <= h2 -> forall k, ~ @In elt k h2 -> ~ In k h1.\n      intros; not_not; eapply submap_in; eauto.\n    Qed.\n    Lemma submap_diff elt (a b c : t elt) : c <= b -> b <= a -> a - b <= a - c.\n    Proof.\n      intros Hcb Hba.\n      unfold Submap.\n      intros k v Hf.\n      eapply diff_find_Some_iff in Hf.\n      destruct Hf as [Hf Hni].\n      eapply diff_find_Some_iff.\n      split.\n      solve [eauto].\n      solve [eapply submap_not_in; eauto].\n    Qed.\n\n    Lemma submap_restrict elt (h1 h2 h : t elt) : h1 <= h2 -> h1 - h <= h2 - h.\n    Proof.\n      unfold Submap; intros Hsml k v Hf.\n      eapply diff_find_Some_iff in Hf; openhyp; rewrite diff_o; eauto.\n    Qed.\n\n    Import Bedrock.Platform.Cito.GeneralTactics4.\n\n    Lemma submap_diff_diff elt (h1 h2 h3 : t elt) : h1 <= h2 -> h2 <= h3 -> h2 - h1 == (h3 - h1) - (h3 - h2).\n    Proof.\n      intros H12 H23.\n      unfold Equal.\n      intros k.\n      eapply option_univalence.\n      intros v; split; intros Hf.\n      eapply diff_find_Some_iff in Hf.\n      destruct Hf as [Hf Hni].\n      eapply diff_find_Some_iff.\n      split.\n      eapply diff_find_Some_iff.\n      split.\n      eapply submap_find; eauto.\n      eauto.\n      not_not.\n      eapply diff_in_iff in H.\n      destruct H as [Hi3 Hni2].\n      eapply find_Some_in in Hf; contradiction.\n      eapply diff_find_Some_iff in Hf.\n      destruct Hf as [Hf Hni].\n      eapply diff_find_Some_iff in Hf.\n      destruct Hf as [Hf Hni1].\n      eapply diff_find_Some_iff.\n      split.\n      destruct (option_dec (find k h2)) as [[v' Hs] | Hn].\n      copy Hs; eapply H23 in Hs; unif v'; eauto.\n      eapply not_find_in_iff in Hn.\n      contradict Hni.\n      eapply diff_in_iff.\n      split.\n      eapply find_Some_in; eauto.\n      eauto.\n      eauto.\n    Qed.\n\n    Lemma submap_case elt h2 h12 : h2 <= h12 -> forall k (v : elt), find k h12 = Some v <-> find k (h12 - h2) = Some v \\/ find k h2 = Some v.\n    Proof.\n      intros Hsm k v; split.\n      intros Hf12.\n      destruct (In_dec h2 k) as [Hin | Hni].\n      right.\n      eapply in_find_Some in Hin.\n      destruct Hin as [v' Hf2].\n      copy_as Hf2 Hf2'; eapply Hsm in Hf2'.\n      unif v'.\n      eauto.\n      left.\n      eapply diff_find_Some_iff; eauto.\n\n      intros [Hfd | Hf2].\n      eapply diff_find_Some_iff in Hfd; eauto.\n      destruct Hfd as [Hf12 Hni].\n      eauto.\n      eapply Hsm; eauto.\n    Qed.\n\n    Lemma submap_disjoint_1 elt (h1 h2 h1' : t elt) : Disjoint h1 h2 -> h1' <= h1 -> Disjoint h1' h2.\n    Proof.\n      intros Hdisj Hsm.\n      unfold Disjoint.\n      intros k [Hin1 Hin2].\n      eapply submap_in in Hin1; eauto.\n      eapply Hdisj; eauto.\n    Qed.\n\n    Arguments submap_disjoint_1 [_] _ _ _ _ _ _ _.\n\n    Lemma diff_submap_cancel elt (h1 h12 : t elt) : h1 <= h12 -> h12 - (h12 - h1) == h1.\n    Proof.\n      intros Hsm.\n      unfold Equal.\n      intros k.\n      eapply option_univalence.\n      intros v; split; intros Hf.\n      eapply diff_find_Some_iff in Hf.\n      destruct Hf as [Hf12 Hni].\n      eapply submap_case in Hf12; eauto.\n      openhyp.\n      contradict Hni; eapply find_Some_in; eauto.\n      eauto.\n      eapply diff_find_Some_iff.\n      split.\n      eapply Hsm; eauto.\n      intros Hin.\n      eapply diff_in_iff in Hin.\n      destruct Hin as [? Hni].\n      contradict Hni; eapply find_Some_in; eauto.\n    Qed.\n\n    Global Add Parametric Morphism elt : (@direct_sum elt)\n        with signature Equal ==> Equal ==> Equal ==> iff as direct_sum_m.\n    Proof.\n      intros.\n      unfold direct_sum.\n      rewrite H.\n      rewrite H0.\n      rewrite H1.\n      intuition.\n    Qed.\n\n    Lemma direct_sum_disjoint elt h1 h2 h12 : direct_sum h1 h2 h12 -> @Disjoint elt h1 h2.\n    Proof.\n      intros H; destruct H; eauto.\n    Qed.\n\n    Lemma direct_sum_in_not elt h1 h2 h12 x : @direct_sum elt h1 h2 h12 -> In x h1 -> ~ In x h2.\n    Proof.\n      intros; eapply Disjoint_in_not; eauto.\n      eapply direct_sum_disjoint; eauto.\n    Qed.\n    Arguments direct_sum_in_not [_] _ _ _ _ _ _ _.\n\n    Lemma disjoint_update_iff elt h1 h2 : Disjoint h1 h2 -> forall k (v : elt), find k (h1 + h2) = Some v <-> find k h1 = Some v \\/ find k h2 = Some v.\n    Proof.\n      intros Hdisj k v.\n      split; intros Hf12.\n      eapply find_mapsto_iff in Hf12.\n      eapply update_mapsto_iff in Hf12.\n      destruct Hf12 as [Hf2 | [Hf1 Hni2]].\n      eapply find_mapsto_iff in Hf2.\n      eauto.\n      eapply find_mapsto_iff in Hf1.\n      eauto.\n      eapply find_mapsto_iff.\n      eapply update_mapsto_iff.\n      destruct Hf12 as [Hf1 | Hf2].\n      right.\n      split.\n      eapply find_mapsto_iff; eauto.\n      eapply Disjoint_in_not; eauto.\n      eapply find_Some_in; eauto.\n      left.\n      eapply find_mapsto_iff; eauto.\n    Qed.\n\n    Lemma direct_sum_intro elt h1 h2 h12 : @Disjoint elt h1 h2 -> (forall k v, find k h12 = Some v <-> find k h1 = Some v \\/ find k h2 = Some v) -> direct_sum h1 h2 h12.\n    Proof.\n      intros Hdisj Hiff.\n      unfold direct_sum.\n      split.\n      unfold Equal.\n      intros k.\n      eapply option_univalence.\n      intros v.\n      etransitivity.\n      2 : symmetry; eauto.\n      eapply disjoint_update_iff; eauto.\n      eauto.\n    Qed.\n\n    Lemma find_Some_direct_sum elt h1 h2 h12 : direct_sum h1 h2 h12 -> forall k (v : elt), find k h12 = Some v <-> find k h1 = Some v \\/ find k h2 = Some v.\n    Proof.\n      intros Hds k v.\n      destruct Hds as [Hheq Hdisj].\n      rewrite <- Hheq.\n      eapply disjoint_update_iff; eauto.\n    Qed.\n\n    Lemma diff_direct_sum elt (h2 h12 : t elt) : h2 <= h12 -> direct_sum (h12 - h2) h2 h12.\n    Proof.\n      intros Hsm.\n      eapply direct_sum_intro.\n      eapply diff_disjoint.\n      eapply submap_case; eauto.\n    Qed.\n\n    Lemma direct_sum_submap elt (h1 h2 h12 : t elt) : direct_sum h1 h2 h12 -> h1 <= h12 /\\ h2 <= h12.\n      intros Hds.\n      specialize (find_Some_direct_sum Hds).\n      intros Hiff.\n      unfold Submap.\n      split; intros k v Hf; eapply Hiff; eauto.\n    Qed.\n\n    Arguments direct_sum_submap [_] _ _ _ _.\n\n    Lemma direct_sum_sym elt (h1 h2 h12 : t elt) : direct_sum h1 h2 h12 -> direct_sum h2 h1 h12.\n    Proof.\n      intros Hds.\n      specialize (find_Some_direct_sum Hds).\n      intros Hiff.\n      eapply direct_sum_intro.\n      eapply Disjoint_sym; eapply direct_sum_disjoint; eauto.\n      intros k v.\n      etransitivity.\n      eauto.\n      intuition.\n    Qed.\n\n    Lemma direct_sum_submap_submap elt (h1 h12 h123 h2 : t elt) : h1 <= h12 -> h12 <= h123 -> h2 == h12 - h1 -> direct_sum h2 (h123 - h12) (h123 - h1).\n    Proof.\n      intros Hsm1 Hsm12 Heq2.\n      eapply direct_sum_intro.\n      rewrite Heq2.\n      eapply submap_disjoint_1; eauto.\n      2 : solve [eapply diff_submap; eauto].\n      eapply Disjoint_sym; eapply diff_disjoint; eauto.\n      intros k v; split.\n      intros Hfd.\n      eapply diff_find_Some_iff in Hfd; eauto.\n      destruct Hfd as [Hf123 Hni1].\n      eapply submap_case in Hf123; eauto.\n      destruct Hf123 as [Hfd | Hf12].\n      eauto.\n      left.\n      rewrite Heq2.\n      eapply submap_case in Hf12; eauto.\n      destruct Hf12 as [Hfd | Hf1].\n      eauto.\n      contradict Hni1; eapply find_Some_in; eauto.\n\n      intros Hor.\n      eapply diff_find_Some_iff.\n      rewrite Heq2 in Hor.\n      destruct Hor as [Hf2 | Hfd].\n      eapply diff_find_Some_iff in Hf2.\n      openhyp.\n      split.\n      eapply Hsm12; eauto.\n      eauto.\n      eapply diff_find_Some_iff in Hfd.\n      openhyp.\n      split.\n      eauto.\n      not_not.\n      eapply submap_in; eauto.\n    Qed.\n\n    Fixpoint make_map {elt} keys values :=\n      match keys, values with\n        | k :: keys', v :: values' => add k v (make_map keys' values')\n        | _, _ => @empty elt\n      end.\n\n    Lemma make_map_in elt ks : forall (vs : list elt) k, In k (make_map ks vs) -> List.In k ks.\n    Proof.\n      induction ks; destruct vs; simpl; intros k' Hi.\n      eapply empty_in_iff in Hi; contradiction.\n      eapply empty_in_iff in Hi; contradiction.\n      eapply empty_in_iff in Hi; contradiction.\n      rename a into k.\n      eapply add_in_iff in Hi.\n      destruct Hi as [He | Hi].\n      subst; eauto.\n      right; eauto.\n    Qed.\n\n    Lemma make_map_not_in elt k ks (vs : list elt) : ~ List.In k ks -> ~ In k (make_map ks vs).\n    Proof.\n      intros; not_not.\n      rename H0 into H.\n      eapply make_map_in; eauto.\n    Qed.\n\n    Lemma make_map_find_None A k ks (vs : list A) :\n      ~ List.In k ks ->\n      find k (make_map ks vs) = None.\n    Proof.\n      intros H.\n      eapply make_map_not_in in H.\n      eapply not_find_in_iff; eauto.\n    Qed.\n\n    Lemma make_map_Equal_elim A :\n      forall ks (vs vs' : list A),\n        NoDup ks ->\n        length vs = length ks ->\n        length vs' = length ks ->\n        make_map ks vs == make_map ks vs' ->\n        vs = vs'.\n    Proof.\n      induction ks; destruct vs; destruct vs'; simpl; try solve [intros; intuition; try discriminate].\n      intros Hnd Hlen Hlen' Heqv.\n      inversion Hnd; subst.\n      inject Hlen.\n      inject Hlen'.\n      rename a into k.\n      f_equal.\n      {\n        unfold Equal in *.\n        specialize (Heqv k).\n        repeat rewrite add_eq_o in * by eauto.\n        inject Heqv.\n        eauto.\n      }\n      eapply IHks; eauto.\n      unfold Equal in *.\n      intros k'.\n      destruct (eq_dec k' k) as [? | Hne]; subst.\n      {\n        repeat rewrite make_map_find_None by eauto.\n        eauto.\n      }\n      specialize (Heqv k').\n      repeat rewrite add_neq_o in * by eauto.\n      eauto.\n    Qed.\n\n    Fixpoint make_mapM {elt} keys values :=\n      match keys, values with\n        | k :: keys', v :: values' =>\n          match v with\n            | Some a => add k a (make_mapM keys' values')\n            | None => make_mapM keys' values'\n          end\n        | _, _ => @empty elt\n      end.\n\n    Import Bedrock.Platform.Cito.ListFacts4.\n\n    Lemma in_make_mapM_iff elt ks : forall vs k, length ks = length vs -> (In k (make_mapM ks vs) <-> exists i (a : elt), nth_error ks i = Some k /\\ nth_error vs i = Some (Some a)).\n    Proof.\n      induction ks; try (rename a into k'); destruct vs as [|v' vs]; simpl; intros k Hl; (split; [intros Hi | intros Hex]); try discriminate.\n      eapply empty_in_iff in Hi; contradiction.\n      destruct Hex as [i [a [Hk Hv]]]; rewrite nth_error_nil in *; discriminate.\n\n      inject Hl.\n      destruct v' as [a' | ].\n      eapply add_in_iff in Hi.\n      destruct Hi as [Heq | Hi].\n      subst.\n      solve [exists 0, a'; eauto].\n      solve [eapply IHks in Hi; eauto; destruct Hi as [i [a [Hk Hv]]]; exists (S i), a; eauto].\n      solve [eapply IHks in Hi; eauto; destruct Hi as [i [a [Hk Hv]]]; exists (S i), a; eauto].\n\n      inject Hl.\n      destruct Hex as [i [a [Hk Hv]]].\n      destruct i as [ | i]; simpl in *.\n      inject Hk.\n      inject Hv.\n      eapply add_in_iff; eauto.\n      destruct v' as [a' |].\n      eapply add_in_iff.\n      right.\n      eapply IHks; eauto.\n      eapply IHks; eauto.\n    Qed.\n\n    Definition no_dupM elt ks vs := forall i j (k : key) (ai aj : elt), nth_error ks i = Some k -> nth_error vs i = Some (Some ai) -> nth_error ks j = Some k -> nth_error vs j = Some (Some aj) -> i = j.\n\n    Lemma no_dupM_cons_elim elt ks vs k (v : option elt) : no_dupM (k :: ks) (v :: vs) -> no_dupM ks vs.\n    Proof.\n      unfold no_dupM.\n      intros Hnd i j k' ai aj Hik Hiv Hjk Hjv.\n      assert (S i = S j).\n      eapply Hnd; eauto; simpl; eauto.\n      inject H; eauto.\n    Qed.\n\n    Lemma find_Some_make_mapM_iff elt ks : forall vs k (a : elt), length ks = length vs -> no_dupM ks vs -> (find k (make_mapM ks vs) = Some a <-> exists i, nth_error ks i = Some k /\\ nth_error vs i = Some (Some a)).\n    Proof.\n      induction ks; try (rename a into k'); destruct vs as [ | v' vs]; simpl in *; intros k a Hl Hnd; (split; [intros Hi | intros Hex]); try rewrite empty_o in *; try discriminate.\n      destruct Hex as [i [Hk Hv]]; rewrite nth_error_nil in *; discriminate.\n\n      inject Hl.\n      destruct v' as [a' | ].\n      destruct (eq_dec k k') as [Heq | Hne].\n      subst.\n      rewrite add_eq_o in * by eauto.\n      inject Hi.\n      solve [exists 0; eauto].\n      rewrite add_neq_o in * by eauto.\n      eapply IHks in Hi; eauto.\n      solve [destruct Hi as [i [Hk Hv]]; exists (S i); eauto].\n      solve [eapply no_dupM_cons_elim; eauto].\n      eapply IHks in Hi; eauto.\n      solve [destruct Hi as [i [Hk Hv]]; exists (S i); eauto].\n      solve [eapply no_dupM_cons_elim; eauto].\n\n      inject Hl.\n      destruct Hex as [i [Hk Hv]].\n      destruct i as [ | i]; simpl in *.\n      inject Hk.\n      inject Hv.\n      rewrite add_eq_o in * by eauto.\n      solve [eauto].\n      destruct v' as [a' |].\n      destruct (eq_dec k k') as [Heq | Hne].\n      subst.\n      assert (0 = S i).\n      eapply Hnd; eauto; simpl; eauto.\n      discriminate.\n      rewrite add_neq_o in * by eauto.\n      eapply IHks; eauto.\n      solve [eapply no_dupM_cons_elim; eauto].\n      eapply IHks; eauto.\n      solve [eapply no_dupM_cons_elim; eauto].\n    Qed.\n\n    Lemma add_new_submap elt k m : ~ In k m -> forall (v : elt), m <= add k v m.\n    Proof.\n      intros Hni v.\n      unfold Submap.\n      intros k' v' Hf.\n      destruct (eq_dec k' k).\n      subst.\n      contradict Hni.\n      eapply find_Some_in; eauto.\n      rewrite add_neq_o by eauto; eauto.\n    Qed.\n\n    Lemma NoDup_elements elt (m : t elt) : NoDup (List.map fst (elements m)).\n    Proof.\n      eapply NoDupKey_NoDup_fst.\n      eapply elements_3w.\n    Qed.\n\n    Lemma add_eq_elim elt k (v1 v2 : elt) m1 m2 : add k v1 m1 == add k v2 m2 -> v1 = v2 /\\ remove k m1 == remove k m2.\n    Proof.\n      intros Heq.\n      unfold Equal in *.\n      split.\n      - specialize (Heq k).\n        rewrite add_eq_o in * by eauto.\n        rewrite add_eq_o in * by eauto.\n        inject Heq; eauto.\n      - intros k'.\n        destruct (eq_dec k' k).\n        + subst.\n          repeat rewrite remove_eq_o by eauto.\n          eauto.\n        + repeat rewrite remove_neq_o by eauto.\n          specialize (Heq k').\n          rewrite add_neq_o in * by eauto.\n          rewrite add_neq_o in * by eauto.\n          eauto.\n    Qed.\n\n    Lemma add_add_comm elt k k' (v v' : elt) m : k <> k' -> add k v (add k' v' m) == add k' v' (add k v m).\n    Proof.\n      intros Hne.\n      unfold Equal.\n      intros k''.\n      destruct (eq_dec k'' k).\n      - subst.\n        rewrite add_eq_o by eauto.\n        destruct (eq_dec k k').\n        + subst.\n          intuition.\n        + rewrite add_neq_o by eauto.\n          rewrite add_eq_o by eauto.\n          eauto.\n      - rewrite add_neq_o by eauto.\n        destruct (eq_dec k'' k').\n        + subst.\n          rewrite add_eq_o by eauto.\n          rewrite add_eq_o by eauto.\n          eauto.\n        + rewrite add_neq_o by eauto.\n          rewrite add_neq_o by eauto.\n          rewrite add_neq_o by eauto.\n          eauto.\n    Qed.\n\n    Global Arguments add_add_comm [elt] k k' _ _ _ _ _.\n\n    Lemma remove_add_comm elt k k' (v' : elt) m : k <> k' -> remove k (add k' v' m) == add k' v' (remove k m).\n    Proof.\n      intros Hne.\n      unfold Equal.\n      intros k''.\n      destruct (eq_dec k'' k).\n      - subst.\n        rewrite remove_eq_o by eauto.\n        destruct (eq_dec k k').\n        + subst.\n          intuition.\n        + rewrite add_neq_o by eauto.\n          rewrite remove_eq_o by eauto.\n          eauto.\n      - rewrite remove_neq_o by eauto.\n        destruct (eq_dec k'' k').\n        + subst.\n          rewrite add_eq_o by eauto.\n          rewrite add_eq_o by eauto.\n          eauto.\n        + rewrite add_neq_o by eauto.\n          rewrite add_neq_o by eauto.\n          rewrite remove_neq_o by eauto.\n          eauto.\n    Qed.\n\n    Lemma add_remove_comm elt k k' (v : elt) m : k <> k' -> add k v (remove k' m) == remove k' (add k v m).\n    Proof.\n      intros Hne.\n      unfold Equal.\n      intros k''.\n      destruct (eq_dec k'' k).\n      - subst.\n        rewrite add_eq_o by eauto.\n        destruct (eq_dec k k').\n        + subst.\n          intuition.\n        + rewrite remove_neq_o by eauto.\n          rewrite add_eq_o by eauto.\n          eauto.\n      - rewrite add_neq_o by eauto.\n        destruct (eq_dec k'' k').\n        + subst.\n          rewrite remove_eq_o by eauto.\n          rewrite remove_eq_o by eauto.\n          eauto.\n        + rewrite remove_neq_o by eauto.\n          rewrite remove_neq_o by eauto.\n          rewrite add_neq_o by eauto.\n          eauto.\n    Qed.\n\n    Lemma remove_remove_comm elt k k' (m : t elt) : k <> k' -> remove k (remove k' m) == remove k' (remove k m).\n    Proof.\n      intros Hne.\n      unfold Equal.\n      intros k''.\n      destruct (eq_dec k'' k).\n      - subst.\n        rewrite remove_eq_o by eauto.\n        destruct (eq_dec k k').\n        + subst.\n          intuition.\n        + rewrite remove_neq_o by eauto.\n          rewrite remove_eq_o by eauto.\n          eauto.\n      - rewrite remove_neq_o by eauto.\n        destruct (eq_dec k'' k').\n        + subst.\n          rewrite remove_eq_o by eauto.\n          rewrite remove_eq_o by eauto.\n          eauto.\n        + rewrite remove_neq_o by eauto.\n          rewrite remove_neq_o by eauto.\n          rewrite remove_neq_o by eauto.\n          eauto.\n    Qed.\n    Global Arguments remove_remove_comm [elt] k k' _ _ _.\n\n    Lemma add_remove_eq_false elt k (v : elt) m1 m2 : ~ add k v m1 == remove k m2.\n    Proof.\n      intro H.\n      unfold Equal in *.\n      specialize (H k).\n      rewrite add_eq_o in * by eauto.\n      rewrite remove_eq_o in * by eauto.\n      discriminate.\n    Qed.\n\n    Section EqualOn.\n\n      Variable Domain : key -> Prop.\n\n      Variable elt : Type.\n\n      Definition EqualOn (m1 m2 : t elt) := forall k, Domain k -> find k m1 = find k m2.\n\n      Lemma EqualOn_refl a : EqualOn a a.\n      Proof.\n        unfold EqualOn.\n        eauto.\n      Qed.\n\n      Lemma EqualOn_sym a b : EqualOn a b -> EqualOn b a.\n      Proof.\n        intros H.\n        unfold EqualOn in *; intros.\n        symmetry; eauto.\n      Qed.\n\n      Lemma EqualOn_trans a b c : EqualOn a b -> EqualOn b c -> EqualOn a c.\n      Proof.\n        intros H1 H2.\n        unfold EqualOn in *; intros.\n        etransitivity.\n        - eapply H1; eauto.\n        - eauto.\n      Qed.\n\n      Global Add Relation (t elt) EqualOn\n          reflexivity proved by EqualOn_refl\n          symmetry proved by EqualOn_sym\n          transitivity proved by EqualOn_trans\n            as EqualOn_rel.\n\n      Lemma Equal_EqualOn a a' b b' : a == a' -> b == b' -> (EqualOn a b <-> EqualOn a' b').\n      Proof.\n        intros Ha Hb.\n        split; intros H.\n        - unfold EqualOn in *.\n          intros k Hk.\n          rewrite <- Ha.\n          rewrite <- Hb.\n          eapply H; eauto.\n        - unfold EqualOn in *.\n          intros k Hk.\n          rewrite Ha.\n          rewrite Hb.\n          eapply H; eauto.\n      Qed.\n\n      Global Add Morphism EqualOn\n          with signature Equal ==> Equal ==> iff as Equal_EqualOn_m.\n      Proof.\n        intros; eapply Equal_EqualOn; eauto.\n      Qed.\n\n      Lemma add_EqualOn k v m1 m2 : EqualOn m1 m2 -> EqualOn (add k v m1) (add k v m2).\n      Proof.\n        intros Heq.\n        unfold EqualOn in *.\n        intros k' Hk'.\n        destruct (eq_dec k' k) as [Heqk | Hnek].\n        - subst.\n          repeat rewrite add_eq_o by eauto.\n          eauto.\n        - repeat rewrite add_neq_o by eauto.\n          eauto.\n      Qed.\n\n      Lemma remove_EqualOn k m1 m2 : EqualOn m1 m2 -> EqualOn (remove k m1) (remove k m2).\n      Proof.\n        intros Heq.\n        unfold EqualOn in *.\n        intros k' Hk'.\n        destruct (eq_dec k' k) as [Heqk | Hnek].\n        - subst.\n          repeat rewrite remove_eq_o by eauto.\n          eauto.\n        - repeat rewrite remove_neq_o by eauto.\n          eauto.\n      Qed.\n\n      Global Add Morphism (@add elt) with signature eq ==> eq ==> EqualOn ==> EqualOn as add_EqualOn_m.\n      Proof.\n        intros; eapply add_EqualOn; eauto.\n      Qed.\n\n      Global Add Morphism (@remove elt) with signature eq ==> EqualOn ==> EqualOn as remove_EqualOn_m.\n      Proof.\n        intros; eapply remove_EqualOn; eauto.\n      Qed.\n\n      Lemma out_add_EqualOn a b k v : EqualOn a b -> ~ Domain k -> EqualOn (add k v a) b.\n      Proof.\n        intros Heq Hk.\n        unfold EqualOn in *.\n        intros k' Hk'.\n        destruct (eq_dec k' k) as [? | Hne].\n        - subst.\n          contradiction.\n        - rewrite add_neq_o by eauto.\n          eapply Heq; eauto.\n      Qed.\n\n    End EqualOn.\n\n    Lemma empty_submap elt m : @empty elt <= m.\n    Proof.\n      intros k v Hin.\n      rewrite empty_o in Hin.\n      discriminate.\n    Qed.\n\n    Definition sub_domain elt1 elt2 (m1 : t elt1) (m2 : t elt2) := forall k, In k m1 -> In k m2.\n\n    Definition equal_domain elt1 elt2 (m1 : t elt1) (m2 : t elt2) := sub_domain m1 m2 /\\ sub_domain m2 m1.\n\n    Definition is_sub_domain elt1 elt2 (m1 : t elt1) (m2 : t elt2) := forallb (fun k => mem k m2) (keys m1).\n\n    Import Bedrock.Platform.Cito.SetoidListFacts.\n\n    Lemma is_sub_domain_sound : forall elt1 elt2 (m1 : t elt1) (m2 : t elt2), is_sub_domain m1 m2 = true -> sub_domain m1 m2.\n      intros.\n      unfold is_sub_domain, sub_domain in *.\n      intros.\n      eapply forallb_forall in H.\n      eapply mem_in_iff; eauto.\n      eapply InA_In.\n      eapply In_In_keys; eauto.\n    Qed.\n\n    Lemma is_sub_domain_complete : forall elt1 elt2 (m1 : t elt1) (m2 : t elt2), sub_domain m1 m2 -> is_sub_domain m1 m2 = true.\n    Proof.\n      intros.\n      unfold is_sub_domain, sub_domain in *.\n      eapply forallb_forall.\n      intros k Hin.\n      eapply mem_in_iff; eauto.\n      eapply H.\n      Require Import SetoidListFacts.\n      eapply In_InA in Hin.\n      eapply In_In_keys; eauto.     \n    Qed.\n\n    Definition equal_domain_dec elt1 elt2 (m1 : t elt1) (m2 : t elt2) := (is_sub_domain m1 m2 && is_sub_domain m2 m1)%bool.\n\n    Lemma equal_domain_dec_sound : forall elt1 elt2 (m1 : t elt1) (m2 : t elt2), equal_domain_dec m1 m2 = true -> equal_domain m1 m2.\n      unfold equal_domain_dec, equal_domain; intros.\n      eapply Bool.andb_true_iff in H; openhyp.\n      eapply is_sub_domain_sound in H.\n      eapply is_sub_domain_sound in H0.\n      eauto.\n    Qed.\n\n    Lemma in_elements_find elt k (v : elt) d : List.In (k, v) (elements d) -> find k d = Some v.\n    Proof.\n      intros H.\n      eapply InA_eqke_In in H.\n      eapply elements_2 in H.\n      eapply find_mapsto_iff; eauto.\n    Qed.\n\n    Lemma find_in_elements elt k (v : elt) d : find k d = Some v -> List.In (k, v) (elements d).\n    Proof.\n      intros H.\n      eapply InA_eqke_In.\n      eapply elements_1.\n      eapply find_mapsto_iff; eauto.\n    Qed.\n\n    Lemma submap_diff_empty_equal elt a b : a <= b -> b - a == empty elt -> b == a.\n    Proof.\n      intros Hsm Hdiff.\n      intros k.\n      destruct (option_dec (find k a)) as [ [v Hv] | Hnone].\n      {\n        rewrite Hv.\n        eapply Hsm; eauto.\n      }\n      rewrite Hnone.\n      destruct (option_dec (find k b)) as [ [v Hv] | Hnone'].\n      {\n        assert (MapsTo k v (b - a)).\n        {\n          eapply diff_mapsto_iff.\n          split.\n          - eapply find_mapsto_iff; eauto.\n          - eapply not_find_in_iff; eauto.\n        }\n        rewrite Hdiff in H.\n        eapply empty_mapsto_iff in H.\n        intuition.\n      }\n      eauto.\n    Qed.\n\n    Lemma submap_refl elt (m : t elt) : m <= m.\n    Proof.\n      intros k.\n      intros; eauto.\n    Qed.\n\n    Lemma sub_domain_refl A a : @sub_domain A A a a.\n    Proof.\n      intros k; eauto.\n    Qed.\n\n    Lemma sub_domain_update_1 A B a b c : @sub_domain A B a b -> sub_domain a (b + c).\n    Proof.\n      intros Hsd.\n      intros k H.\n      eapply update_in_iff.\n      left; eauto.\n    Qed.\n\n    Lemma sub_domain_update_2 A B a b c : @sub_domain A B a c -> sub_domain a (b + c).\n    Proof.\n      intros Hsd.\n      intros k H.\n      eapply update_in_iff.\n      right; eauto.\n    Qed.\n\n    Lemma sub_domain_map_1 A B C (f : A -> C) a b : @sub_domain A B a b -> sub_domain (map f a) b.\n    Proof.\n      intros Hsd.\n      intros k H.\n      eapply map_4 in H; eauto.\n    Qed.\n\n    Lemma sub_domain_map_2 A B C (f : B -> C) a b : @sub_domain A B a b -> sub_domain a (map f b).\n    Proof.\n      intros Hsd.\n      intros k H.\n      eapply map_3; eauto.\n    Qed.\n\n    Lemma sub_domain_update_sub_domain A a b : @sub_domain A A b a -> sub_domain (a + b) a.\n    Proof.\n      intros Hsd.\n      intros k H.\n      eapply update_in_iff in H.\n      intuition.\n    Qed.\n\n    Arguments empty {elt}.\n\n    Definition filterM_f {A B} (f : key -> A -> option B) k v acc := match f k v with | Some v' => add k v' acc | None => acc end.\n\n    Definition filterM A B (f : key -> A -> option B) d :=  fold (filterM_f f) d empty.\n\n    Lemma filterM_elim A B f k (b : B) d : find k (filterM f d) = Some b -> exists a : A, find k d = Some a /\\ f k a = Some b.\n    Proof.\n      unfold filterM.\n      eapply fold_rec_bis.\n      {\n        intros m1 m2 a Heq H1 H.\n        rewrite <- Heq.\n        eauto.\n      }\n      {\n        intros H.\n        rewrite empty_o in H.\n        discriminate.\n      }\n      {\n        intros k' e a d'.\n        intros Hk' Hnin H1 H.\n        unfold filterM_f in *.\n        destruct (option_dec (f k' e)) as [ [v Heq] | Heq ]; rewrite Heq in *.\n        {\n          destruct (eq_dec k k') as [? | Hneq].\n          {\n            subst.\n            rewrite add_eq_o in H by eauto.\n            inject H.\n            exists e.\n            split; eauto.\n            rewrite add_eq_o by eauto.\n            eauto.\n          }\n          {\n            rewrite add_neq_o in H by eauto.\n            eapply H1 in H.\n            destruct H as [v' [H Heq'] ].\n            exists v'; split; eauto.\n            rewrite add_neq_o by eauto.\n            eauto.\n          }\n        }\n        {\n          eapply H1 in H.\n          destruct H as [v [H Heq'] ].\n          destruct (eq_dec k k') as [? | Hneq].\n          {\n            subst.\n            contradict Hnin.\n            eapply find_Some_in; eauto.\n          }\n          {\n            exists v; split; eauto.\n            rewrite add_neq_o by eauto; eauto.\n          }\n        }\n      }\n    Qed.\n\n    Definition inter elt1 elt2 (d1 : t elt1) (d2 : t elt2) := filterM (fun k v1 => match find k d2 with | Some v2 => Some (v1, v2) | None => None end ) d1.\n\n    Lemma find_inter_elim A B k d1 d2 (v1 : A) (v2 : B) : find k (inter d1 d2) = Some (v1, v2) -> find k d1 = Some v1 /\\ find k d2 = Some v2.\n    Proof.\n      intros H.\n      unfold inter in *.\n      eapply filterM_elim in H.\n      destruct H as [v1' [H1 H2] ].\n      destruct (option_dec (find k d2)) as [ [v2' Heq] | Heq ]; rewrite Heq in *.\n      {\n        inject H2.\n        eauto.\n      }\n      discriminate.\n    Qed.\n\n    Lemma singleton_in_iff elt k' k (v : elt) : In k' (add k v empty) <-> k = k'.\n    Proof.\n      split; intros H.\n      {\n        eapply add_in_iff in H.\n        destruct H as [? | H]; trivial.\n        eapply empty_in_iff in H; intuition.\n      }\n      subst.\n      eapply add_in_iff; eauto.\n    Qed.\n\n    Lemma add_diff_singleton elt k (v : elt) d : ~ In k d -> add k v d - add k v empty == d.\n    Proof.\n      intros Hnin.\n      intros k'.\n      destruct (eq_dec k' k) as [? | Heq].\n      {\n        subst.\n        rewrite diff_o_none.\n        - eapply not_find_in_iff in Hnin; eauto.\n        - eapply add_in_iff; eauto.\n      }\n      {\n        rewrite diff_o.\n        - rewrite add_neq_o by eauto; eauto.\n        - intros Hin.\n          eapply singleton_in_iff in Hin.\n          subst; intuition.\n      }\n    Qed.\n\n    Definition Disjoint2 {A B} (m1 : t A) (m2 : t B) := forall k, In k m1 -> ~ In k m2.\n\n  End TopSection.\n\nEnd UWFacts_fun.\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/FMapFacts2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2684785027357327}}
{"text": "\nRequire Import Metalib.Metatheory.\nRequire Import Infrastructure.\nRequire Import Disjoint.\nRequire Import Syntax_ott.\nRequire Import Row_Intuitive_Syntax.\nRequire Import Row_Intuitive_Inf.\n\n(* ********************************************************************** *)\n(** * Auxiliary definitions *)\n(* ********************************************************************** *)\n\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 C3 := gather_atoms_with (fun x : stctx => dom x) in\n  let C4 := gather_atoms_with (fun x : sctx => dom x) in\n  let D4 := gather_atoms_with (fun x => fv_sty_in_sty x) in\n  let D5 := gather_atoms_with (fun x => fv_sty_in_sexp x) in\n  let D6 := gather_atoms_with (fun x => fv_sexp_in_sexp x) in\n  let E1 := gather_atoms_with (fun x : TContext => dom x) in\n  let E2 := gather_atoms_with (fun x : GContext => dom x) in\n  let E3 := gather_atoms_with (fun x  => fv_rexp_in_rexp x) in\n  let E4 := gather_atoms_with (fun x  => fv_rtyp_in_rexp x) in\n  let E5 := gather_atoms_with (fun x  => fv_rtyp_in_rtyp x) in\n  let E6 := gather_atoms_with (fun x  => fv_rtyp_in_rt x) in\n  let E7 := gather_atoms_with (fun x  => fv_rtyp_in_rlist x) in\n  constr:(A \\u B \\u C3 \\u C4 \\u D4 \\u D5 \\u D6 \\u E1 \\u E2 \\u E3 \\u E4 \\u E5 \\u E6 \\u E7).\n\n\nDefinition trans_Ttx T := map trans_rlist  T.\n\nDefinition trans_Gtx G := map trans_rt G.\n\nLemma trans_open_rt_wrt_rtyp_rec : forall A B n,\n    trans_rt ( open_rt_wrt_rtyp_rec n B A ) = open_sty_wrt_sty_rec n (trans_rtyp B ) (trans_rt A )\n\nwith\n\ntrans_open_rlist_wrt_rtyp_rec : forall R A n,\n    trans_rlist (open_rlist_wrt_rtyp_rec n A R) =  open_sty_wrt_sty_rec n (trans_rtyp A) (trans_rlist R)\n\nwith\n\ntrans_open_rtyp_wrt_rtyp_rec : forall A B m,\n    trans_rtyp ( open_rtyp_wrt_rtyp_rec m B A ) = open_sty_wrt_sty_rec m (trans_rtyp B ) (trans_rtyp A ).\n\n\nProof with eauto.\n  - Case \"rt\".\n    intros A.\n    induction A; intros B n; simpls...\n\n    rewrite IHA1...\n    rewrite IHA2...\n\n    rewrite trans_open_rlist_wrt_rtyp_rec...\n    rewrite IHA...\n\n  - Case \"rlist\".\n\n    intros R.\n    induction R; intros A n; simpls...\n\n    rewrite trans_open_rtyp_wrt_rtyp_rec...\n    rewrite IHR...\n\n  - Case \"rtyp\".\n\n    intros A.\n    induction A; intros B m; simpls...\n\n\n    destruct (lt_eq_lt_dec n m)...\n    destruct s...\n\n    rewrite trans_open_rt_wrt_rtyp_rec...\n    rewrite trans_open_rtyp_wrt_rtyp_rec...\n    rewrite trans_open_rtyp_wrt_rtyp_rec...\nQed.\n\n\nLemma trans_open_rt_wrt_rtyp : forall t1 t2,\n    trans_rt (open_rt_wrt_rtyp t1 t2) = open_sty_wrt_sty (trans_rt t1) (trans_rtyp t2).\nProof.\n  intros.\n  unfold open_rt_wrt_rtyp.\n  unfold open_sty_wrt_sty.\n  rewrite trans_open_rt_wrt_rtyp_rec.\n  reflexivity.\nQed.\n\n\nLemma wfr_lc : forall T r,\n    wfr T r ->\n    lc_rtyp r\n\nwith\n\nwfrt_lc : forall T t,\n    wfrt T t ->\n    lc_rt t\n\nwith\n\nwfcl_lc : forall T R,\n    wfcl T R ->\n    lc_rlist R.\nProof with eauto.\n  - Case \"wft\".\n    introv WFR.\n    induction WFR.\n\n    constructor.\n    constructor...\n    constructor.\n    constructor...\n\n  - Case \"wfrt\".\n    introv WFT.\n    induction WFT.\n    constructor.\n    constructor...\n    pick fresh a.\n    specializes H1; auto.\n    eapply lc_rt_ConQuan_exists...\n    constructor...\n\n  - Case \"wfcl\".\n    introv WFCL.\n    induction WFCL.\n    constructor.\n    constructor...\nQed.\n\n\n\nLemma wftc_uniq : forall T,\n    wftc T ->\n    uniq T.\nProof with eauto.\n  intros T.\n  alist induction T; intros; simpls...\n  inverts H...\nQed.\n\n\n\nLemma trans_lc_typ : forall t,\n    lc_rt t ->\n    lc_sty (trans_rt t)\n\nwith\n\ntrans_lc_rlist : forall R,\n    lc_rlist R ->\n    lc_sty (trans_rlist R)\n\nwith\n\ntrans_lc_rty : forall r,\n    lc_rtyp r ->\n    lc_sty (trans_rtyp r).\n\nProof with eauto.\n  - Case \"typ\".\n    introv LC.\n    induction LC; simpls...\n\n    pick fresh X.\n    apply lc_sty_all_exists with X...\n    replace (sty_var_f X) with (trans_rtyp (r_TyVar_f X))...\n    rewrite <- trans_open_rt_wrt_rtyp...\n\n  - Case \"rtyp\".\n    introv LC.\n    induction LC; simpls...\n\n  - Case \"rlist\".\n    introv LC.\n    induction LC; simpls...\nQed.\n\n\nHint Resolve wfr_lc wfrt_lc wftc_uniq.\n\n\nHint Constructors has_type.\n\n\nLemma notin_rtyp_sty : forall A X,\n    X `notin` fv_rtyp_in_rt A ->\n    X `notin` fv_sty_in_sty (trans_rt A )\n\nwith\n\nnotin_rtyp_rlist : forall R X,\n    X `notin` fv_rtyp_in_rlist R ->\n    X `notin` fv_sty_in_sty (trans_rlist R)\n\nwith\n\nnotin_rtyp_rtyp : forall r X,\n    X `notin` fv_rtyp_in_rtyp r ->\n    X `notin` fv_sty_in_sty (trans_rtyp r).\n\nProof with eauto.\n\n  - Case \"typ\".\n\n    intros A.\n    induction A; introv Notin; simpls...\n\n  - Case \"rlist\".\n\n    intros R.\n    induction R; introv Notin; simpls...\n\n  - Case \"rtyp\".\n\n    intros r.\n    induction r; introv Notin; simpls...\n\nQed.\n\n\n\n(* ********************************************************************** *)\n(** * Type safety lemmas *)\n(* ********************************************************************** *)\n\nInductive wtt : TContext -> GContext -> rexp -> rt -> sexp -> Prop :=    (* defn wtt *)\n | wtt_Eq : forall (Ttx:TContext) (Gtx:GContext) (re:rexp) (rt':rt) (ee:sexp) (rt5:rt),\n     wtt Ttx Gtx re rt5 ee ->\n     teq Ttx rt5 rt' ->\n     wtt Ttx Gtx re rt' (sexp_anno ee (trans_rt rt'))\n | wtt_Var : forall (Ttx:TContext) (Gtx:GContext) (x:expvar) (rt5:rt),\n     wftc Ttx ->\n     wfc Ttx Gtx ->\n     binds  x   rt5   Gtx  ->\n     wtt Ttx Gtx (re_Var_f x) rt5 (sexp_var_f x)\n | wtt_Lit : forall (Ttx:TContext) (Gtx:GContext) (x:nat),\n     wftc Ttx ->\n     wfc Ttx Gtx ->\n     wtt Ttx Gtx (re_Lit x) rt_Base (sexp_lit x)\n | wtt_ArrowI : forall (L:vars) (Ttx:TContext) (Gtx:GContext) (rt5:rt) (re:rexp) (rt':rt) (ee:sexp),\n     wfrt Ttx rt5 ->\n      ( forall x , x \\notin  L  -> wtt Ttx  (( x ~ rt5 )++ Gtx )   ( open_rexp_wrt_rexp re (re_Var_f x) )  rt'  ( open_sexp_wrt_sexp ee (sexp_var_f x) )  )  ->\n      wtt Ttx Gtx (re_Abs rt5 re) (rt_Fun rt5 rt')\n          (sexp_anno  ( (sexp_abs ee) )  (sty_arrow  (trans_rt rt5) (trans_rt rt') ))\n | wtt_ArrowE : forall (Ttx:TContext) (Gtx:GContext) (re1 re2:rexp) (rt':rt) (ee1 ee2:sexp) (rt5:rt),\n     wtt Ttx Gtx re1 (rt_Fun rt5 rt') ee1 ->\n     wtt Ttx Gtx re2 rt5 ee2 ->\n     wtt Ttx Gtx (re_App re1 re2) rt' (sexp_app ee1 ee2)\n | wtt_Base : forall (Ttx:TContext) (Gtx:GContext) (l:i) (re:rexp) (rt5:rt) (ee:sexp),\n     wtt Ttx Gtx re rt5 ee ->\n     wtt Ttx Gtx (re_SingleField l re) (rt_Record (r_SingleField l rt5)) (sexp_rcd l ee)\n | wtt_Empty : forall (Ttx:TContext) (Gtx:GContext),\n     wftc Ttx ->\n     wfc Ttx Gtx ->\n     wtt Ttx Gtx re_Empty (rt_Record r_Empty) sexp_top\n | wtt_Merge : forall (Ttx:TContext) (Gtx:GContext) (re1 re2:rexp) (r1 r2:rtyp) (ee1 ee2:sexp),\n     wtt Ttx Gtx re1 (rt_Record r1) ee1 ->\n     wtt Ttx Gtx re2 (rt_Record r2) ee2 ->\n     cmp Ttx r1 r2 ->\n     wtt Ttx Gtx (re_Merge re1 re2) (rt_Record (r_Merge r1 r2)) (sexp_merge ee1 ee2)\n | wtt_Restr : forall (Ttx:TContext) (Gtx:GContext) (re:rexp) (l:i) (r:rtyp) (ee:sexp) (rt5:rt),\n     wtt Ttx Gtx re (rt_Record (r_Merge (r_SingleField l rt5) r)) ee ->\n     wtt Ttx Gtx (re_Res re l) (rt_Record r) (sexp_anno ee  (trans_rtyp r) )\n | wtt_Select : forall (Ttx:TContext) (Gtx:GContext) (re:rexp) (l:i) (rt5:rt) (ee:sexp) (r:rtyp),\n     wtt Ttx Gtx re (rt_Record (r_Merge (r_SingleField l rt5) r)) ee ->\n     wtt Ttx Gtx (re_Selection re l) rt5 (sexp_proj  ( (sexp_anno ee (sty_rcd l  (trans_rt rt5) )) )  l)\n\n | wtt_AllI : forall (L:vars) (Ttx:TContext) (Gtx:GContext) (R:rlist) (re:rexp) (rt5:rt) (ee:sexp),\n     wfc Ttx Gtx ->\n     wfcl Ttx R ->\n     ( forall a , a \\notin  L  ->\n             wtt  (( a ~ R )++ Ttx )  Gtx\n                  ( open_rexp_wrt_rtyp re (r_TyVar_f a) )\n                  ( open_rt_wrt_rtyp rt5 (r_TyVar_f a) )\n                  (open_sexp_wrt_sty ee (sty_var_f a))  ) ->\n     wtt Ttx Gtx (re_ConTyAbs R re) (rt_ConQuan R rt5) (sexp_tabs (trans_rlist R)  ee)\n\n | wtt_AllE : forall (Ttx:TContext) (Gtx:GContext) (re:rexp) (r:rtyp) (rt5:rt) (ee:sexp) (R:rlist),\n     wtt Ttx Gtx re (rt_ConQuan R rt5) ee ->\n     cmpList Ttx r R ->\n     wtt Ttx Gtx (re_ConTyApp re r)  (open_rt_wrt_rtyp  rt5   r )  (sexp_tapp ee (trans_rtyp r)) .\n\n\nSection type_safe_trans.\n\n  (* These are internal properties of Harper's system *)\n  Variable cmp_regular : forall T r r',\n    cmp T r r' ->\n    wfr T r /\\ wfr T r'.\n\n  Variable wtt_regular : forall T G e1 t E,\n    wtt T G e1 t E ->\n    wfrt T t /\\ wftc T.\n\n\n  Lemma cmp_list_regular : forall T r R,\n      cmpList T r R ->\n      wftc T ->\n      wfr T r /\\ wfcl T R.\n    Proof with eauto.\n      introv CMP.\n      induction CMP; introv WFTC; splits; simpls...\n      forwards (? & ?) : cmp_regular H...\n      forwards (? & ?) : cmp_regular H...\n      forwards (? & ?) : IHCMP WFTC...\n    Qed.\n\n  Lemma wfcl_to_swft : forall T R,\n      wfcl T R ->\n      swft (trans_Ttx T) (trans_rlist R)\n  with\n\n  wfr_to_swft : forall T r,\n      wfr T r ->\n      swft (trans_Ttx T) (trans_rtyp r)\n\n  with\n\n  wft_to_swft :forall T t,\n      wfrt T t ->\n      swft (trans_Ttx T) (trans_rt t).\n\n\n  Proof with eauto.\n    - Case \"wfcl_to_swft\".\n\n      introv WFCL.\n\n      induction WFCL.\n\n      + SCase \"empty\".\n        clear wfr_to_swft wft_to_swft wfcl_to_swft.\n        simpls...\n\n      + SCase \"rl_rtyp\".\n        forwards : wfr_to_swft H.\n        clear wfr_to_swft wft_to_swft wfcl_to_swft.\n        simpls...\n\n    - Case \"wfr_to_swft\".\n\n      introv WFR.\n\n      induction WFR.\n\n      + SCase \"var\".\n        clear wfr_to_swft wft_to_swft wfcl_to_swft.\n        simpls.\n        econstructor.\n        eapply binds_map_2...\n\n\n      + SCase \"record\".\n        forwards : wft_to_swft H.\n        clear wfr_to_swft wft_to_swft wfcl_to_swft.\n        simpls...\n\n      + SCase \"empty\".\n        clear wfr_to_swft wft_to_swft wfcl_to_swft.\n        simpls...\n\n      + SCase \"restrict\".\n        clear wfr_to_swft wft_to_swft wfcl_to_swft.\n        simpls...\n\n\n    - Case \"wft_to_swft\".\n\n      introv WFT.\n\n      induction WFT.\n\n      + SCase \"base\".\n        clear wfr_to_swft wft_to_swft wfcl_to_swft.\n        simpls...\n\n      + SCase \"arrow\".\n        clear wfr_to_swft wft_to_swft wfcl_to_swft.\n        simpls...\n\n      + SCase \"forall\".\n        forwards : wfcl_to_swft H.\n        clear wfr_to_swft wft_to_swft wfcl_to_swft.\n        simpls.\n        pick fresh X and apply swft_all...\n        replace (sty_var_f X) with (trans_rtyp (r_TyVar_f X))...\n        rewrite <- trans_open_rt_wrt_rtyp...\n\n      + SCase \"record\".\n        forwards : wfr_to_swft H.\n        clear wfr_to_swft wft_to_swft wfcl_to_swft.\n        simpls...\n  Qed.\n\n\n  Lemma wftc_to_swfte : forall T,\n      wftc T ->\n      swfte (trans_Ttx T).\n  Proof with eauto.\n    introv WFTC.\n\n    induction WFTC; simpls...\n\n    forwards : wfcl_to_swft H.\n\n    econstructor...\n    unfold trans_Ttx...\n  Qed.\n\n\n  Lemma wfc_to_swfe : forall T G,\n      wfc T G ->\n      swfe (trans_Ttx T) (trans_Gtx G).\n  Proof with eauto using wft_to_swft.\n    introv H.\n    induction H; simpls...\n    constructor...\n    unfold trans_Gtx...\n    unfold trans_Ttx...\n  Qed.\n\n\n  Lemma teq_csub : forall T t t',\n      teq T t t' ->\n      uniq T ->\n      sub (trans_Ttx T) (trans_rt t) (trans_rt t') /\\\n      sub (trans_Ttx T) (trans_rt t') (trans_rt t)\n\n  with\n\n  ceq_csub: forall T R R',\n      ceq T R R' ->\n      uniq T ->\n      sub (trans_Ttx T) (trans_rlist R) (trans_rlist R') /\\\n      sub (trans_Ttx T) (trans_rlist R') (trans_rlist R).\n\n  Proof with eauto using wft_to_swft, wfr_to_swft, wfcl_to_swft, notin_rtyp_sty.\n\n    - Case \"teq\".\n      introv Eq.\n      induction Eq; introv Uniq.\n\n      + SCase \"refl\".\n        clear teq_csub ceq_csub.\n        splits...\n\n      + SCase \"sym\".\n        clear teq_csub ceq_csub.\n        destruct IHEq...\n\n      + SCase \"trans\".\n        clear teq_csub ceq_csub.\n\n        destruct (IHEq1 Uniq) as (Sub1 & Sub2).\n        destruct (IHEq2 Uniq) as (Sub3 & Sub4).\n\n        splits...\n\n      + SCase \"arrow\".\n        clear teq_csub ceq_csub.\n\n        simpls.\n\n        destruct (IHEq1 Uniq) as (Sub1 & Sub2).\n        destruct (IHEq2 Uniq) as (Sub3 & Sub4).\n\n        splits...\n\n      + SCase \"typ_all\".\n        simpls.\n        splits.\n\n        pick fresh a.\n        forwards ( Sub1 & Sub2) : H1 a; auto.\n        forwards (? & ?) : ceq_csub H; auto.\n        rewrite trans_open_rt_wrt_rtyp in *.\n        rewrite trans_open_rt_wrt_rtyp in *.\n        pick fresh b and apply S_forall; eauto.\n        apply sub_renaming with (X := a)...\n        unfold trans_Ttx; eauto.\n        unfold trans_Ttx; eauto.\n        rewrite_env (nil ++ [(a, trans_rlist R')] ++ trans_Ttx Ttx).\n        apply sub_narrow with (Q := trans_rlist R); auto.\n        simpls...\n        unfold trans_Ttx; eauto.\n\n\n        pick fresh a.\n        forwards (Sub1 & Sub2) : H1 a; auto.\n        forwards (? & ?) : ceq_csub H; auto.\n        rewrite trans_open_rt_wrt_rtyp in *.\n        rewrite trans_open_rt_wrt_rtyp in *.\n        pick fresh b and apply S_forall; eauto.\n        apply sub_renaming with (X := a)...\n        unfold trans_Ttx; eauto.\n        unfold trans_Ttx; eauto.\n\n\n      + SCase \"base\".\n        forwards (? & ?) : teq_csub Eq; try assumption.\n        clear teq_csub ceq_csub.\n\n        simpls; splits...\n\n      + SCase \"merge\".\n        clear teq_csub ceq_csub.\n        destruct (IHEq1 Uniq).\n        destruct (IHEq2 Uniq).\n\n        simpls; splits.\n\n        eapply S_and.\n        apply S_trans with (trans_rtyp r1)...\n        apply S_trans with (trans_rtyp r2)...\n\n        eapply S_and.\n        apply S_trans with (trans_rtyp r1')...\n        apply S_trans with (trans_rtyp r2')...\n\n\n      + SCase \"merge_unit\".\n        clear teq_csub ceq_csub.\n\n        simpls; splits...\n\n        eapply S_and...\n\n      + SCase \"merge_assoc\".\n        clear teq_csub ceq_csub.\n        forwards (? & ?): cmp_regular H.\n        forwards (? & ?): cmp_regular H0.\n        simpls; splits.\n\n        eapply S_and.\n        eapply S_and.\n        eapply S_andl...\n        apply S_trans with ((sty_and (trans_rtyp r2) (trans_rtyp r3)))...\n        eapply S_andr...\n        apply S_trans with ((sty_and (trans_rtyp r2) (trans_rtyp r3)))...\n        eapply S_andr...\n\n        eapply S_and.\n        apply S_trans with ((sty_and (trans_rtyp r1) (trans_rtyp r2)))...\n        eapply S_andl...\n        eapply S_and.\n        apply S_trans with ((sty_and (trans_rtyp r1) (trans_rtyp r2)))...\n        eapply S_andl...\n        eapply S_andr...\n\n      + SCase \"merge_comm\".\n        clear teq_csub ceq_csub.\n        forwards (? & ?): cmp_regular H.\n\n        simpls; splits.\n\n        eapply S_and...\n        eapply S_and...\n\n    - Case \"ceq\".\n\n      introv Eq.\n      induction Eq; introv Uniq.\n\n      + SCase \"refl\".\n\n        clear teq_csub ceq_csub.\n\n        splits...\n\n\n      + SCase \"sym\".\n        clear teq_csub ceq_csub.\n\n        destruct (IHEq Uniq).\n        splits...\n\n      + SCase \"trans\".\n        clear teq_csub ceq_csub.\n\n        destruct (IHEq1 Uniq) as (Sub1 & Sub2).\n        destruct (IHEq2 Uniq) as (Sub3 & Sub4).\n\n        splits...\n\n\n      + SCase \"inner\".\n\n        lets (? & ?) : teq_csub H; try assumption.\n        clear teq_csub ceq_csub.\n\n        destruct (IHEq Uniq) as (Sub1 & Sub2).\n        simpls.\n        splits.\n\n        eapply S_and.\n        apply S_trans with ((trans_rtyp r))...\n        apply S_trans with ((trans_rlist R))...\n\n        eapply S_and.\n        apply S_trans with ((trans_rtyp r))...\n        apply S_trans with ((trans_rlist R))...\n\n\n      + SCase \"swap\".\n        clear teq_csub ceq_csub.\n\n        simpls.\n        splits.\n\n\n        eapply S_and.\n        apply S_trans with ((sty_and (trans_rtyp r') (trans_rlist R)))...\n        eapply S_andr...\n        eapply S_and.\n        eapply S_andl...\n        apply S_trans with ((sty_and (trans_rtyp r') (trans_rlist R)))...\n        eapply S_andr...\n\n        eapply S_and.\n        apply S_trans with ((sty_and (trans_rtyp r) (trans_rlist R)))...\n        eapply S_andr...\n        eapply S_and.\n        eapply S_andl...\n        apply S_trans with ((sty_and (trans_rtyp r) (trans_rlist R)))...\n        eapply S_andr...\n\n\n      + SCase \"empty\".\n        clear teq_csub ceq_csub.\n        simpls.\n        splits...\n\n        eapply S_and...\n\n      + SCase \"merge\".\n        clear teq_csub ceq_csub.\n\n        simpls.\n        inverts H.\n        splits.\n\n        eapply S_and.\n        apply S_trans with ((sty_and (trans_rtyp r1) (trans_rtyp r2)))...\n        eapply S_andl...\n        eapply S_and.\n        apply S_trans with ((sty_and (trans_rtyp r1) (trans_rtyp r2)))...\n        eapply S_andl...\n        eapply S_andr...\n\n\n        eapply S_and.\n        eapply S_and.\n        eapply S_andl...\n        apply S_trans with ((sty_and (trans_rtyp r2) (trans_rlist R)))...\n        eapply S_andr...\n        apply S_trans with ((sty_and (trans_rtyp r2) (trans_rlist R)))...\n        eapply S_andr...\n\n      + SCase \"dupl\".\n        clear teq_csub ceq_csub.\n\n        simpls; splits.\n\n\n        eapply S_and.\n        eapply S_andl...\n        apply S_trans with ((sty_and (trans_rtyp r) (trans_rlist R)))...\n        eapply S_andr...\n\n        eapply S_and.\n        eapply S_andl...\n        apply S_trans with ((sty_and (trans_rtyp r) (trans_rlist R)))...\n\n\n      + SCase \"base\".\n        forwards (? & ?) : teq_csub H2; try assumption.\n        clear teq_csub ceq_csub.\n\n        simpls; splits.\n\n        eapply S_and.\n        eapply S_trans with ((sty_rcd l (trans_rt rt5)))...\n        eapply S_andr...\n\n\n        eapply S_and.\n        apply S_trans with ((sty_rcd l (trans_rt rt')))...\n        eapply S_andr...\n\n\n  Qed.\n\n\n  Lemma rtyp_in_rlist_sub: forall T r R,\n      rtyp_in_rlist r R ->\n      wfcl T R ->\n      wfr T r ->\n      sub (trans_Ttx T) (trans_rlist R) (trans_rtyp r).\n  Proof with eauto using wfcl_to_swft, wfr_to_swft, wfr_to_swft.\n    introv Rlst.\n    induction Rlst; introv WFCL WFT; simpls...\n\n    inverts WFCL.\n\n    eapply S_andl...\n\n    inverts WFCL.\n    specializes IHRlst...\n  Qed.\n\n\n  Lemma cmp_disjoint : forall T r r',\n      cmp T r r' ->\n      wftc T ->\n      disjoint (trans_Ttx T) (trans_rtyp r) (trans_rtyp r').\n  Proof with eauto using wft_to_swft, wfr_to_swft, wftc_to_swfte.\n    introv CMP.\n\n    induction CMP; introv Uniq; simpls...\n\n    - Case \"eq\".\n      assert (uniq (trans_Ttx Ttx)).\n      unfold trans_Ttx...\n      lets (? & ?) : teq_csub H...\n      lets (? & ?) : teq_csub H0...\n      specializes IHCMP Uniq.\n      eapply disjoint_symmetric in IHCMP...\n      forwards HH3 : disjoint_sub IHCMP...\n      eapply disjoint_symmetric in HH3...\n      eapply disjoint_sub...\n\n    - Case \"symm\".\n      specializes IHCMP Uniq.\n      eapply disjoint_symmetric...\n      unfold trans_Ttx...\n\n    - Case \"tvar\".\n      forwards ? : rtyp_in_rlist_sub H0...\n      unfolds trans_Ttx...\n\n    - Case \"mergeE1\".\n      specializes IHCMP Uniq.\n      eapply disjoint_and in IHCMP...\n      destruct IHCMP...\n      forwards (? & ?): cmp_regular CMP...\n\n    - Case \"mergeE2\".\n      specializes IHCMP Uniq.\n      eapply disjoint_and in IHCMP...\n      destruct IHCMP...\n      forwards (? & ?): cmp_regular CMP...\n\n  Qed.\n\n\n  Lemma cmp_list_disjoint : forall T r R,\n      cmpList T r R ->\n      wftc T ->\n      disjoint (trans_Ttx T) (trans_rtyp r) (trans_rlist R).\n  Proof with eauto using wfr_to_swft, cmp_disjoint.\n    introv CMP.\n    induction CMP; introv Uniq; simpls...\n  Qed.\n\n\n  Theorem type_safe : forall T G e t E,\n      wtt T G e t E ->\n      has_type (trans_Ttx T) (trans_Gtx G) E Inf (trans_rt t).\n  Proof with eauto using wft_to_swft, wfc_to_swfe, wftc_to_swfte, cmp_disjoint, wfcl_to_swft, wfr_to_swft, cmp_list_disjoint.\n\n    introv WTT.\n\n    induction WTT; simpls...\n\n\n    - Case \"wtt_eq\".\n      lets (? & ?) : teq_csub...\n      forwards (? & ?) : wtt_regular WTT...\n\n    - Case \"wtt_var\".\n      econstructor...\n      eapply binds_map_2...\n\n    - Case \"wtt_abs\".\n      econstructor...\n\n      pick fresh x and apply T_abs...\n      forwards WTT : H0 x...\n      forwards (? & ?) : wtt_regular WTT...\n      forwards : H1 x...\n\n    - Case \"wtt_app\".\n      forwards (WFTC & ?) : wtt_regular WTT1...\n      inverts WFTC...\n\n      econstructor...\n\n\n    - Case \"wtt_merge\".\n      forwards (W & ?) : wtt_regular WTT1.\n      inverts W.\n      forwards (W & ?) : wtt_regular WTT2.\n      inverts W.\n\n      econstructor...\n\n    - Case \"wtt_restr\".\n      forwards (W & ?) : wtt_regular WTT.\n      inverts W as W.\n      inverts W as W.\n      inverts W as W.\n\n      econstructor.\n      eapply T_sub...\n\n    - Case \"wtt_select\".\n      forwards (W & ?) : wtt_regular WTT.\n      inverts W as W.\n      inverts W as W.\n      inverts W as W.\n      econstructor...\n      econstructor...\n      eapply T_sub...\n\n    - Case \"wtt_tabs\".\n      pick fresh a and apply T_tabs...\n      forwards : H1 a...\n      replace (sty_var_f a) with (trans_rtyp (r_TyVar_f a))...\n      rewrite <- trans_open_rt_wrt_rtyp...\n      eapply H2...\n\n    - Case \"wtt_tapp\".\n      forwards (? & ?) : wtt_regular WTT.\n      forwards (? & ?) : cmp_list_regular H...\n      rewrite trans_open_rt_wrt_rtyp...\n  Qed.\n\nEnd type_safe_trans.", "meta": {"author": "xnning", "repo": "Row-and-Bounded-via-Disjoint", "sha": "7ed92de6ca987b9840a5b0fe9ea3441eebf34b45", "save_path": "github-repos/coq/xnning-Row-and-Bounded-via-Disjoint", "path": "github-repos/coq/xnning-Row-and-Bounded-via-Disjoint/Row-and-Bounded-via-Disjoint-7ed92de6ca987b9840a5b0fe9ea3441eebf34b45/CoqProofs/elaborations/Row_Intuitive_Elaboration.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.26847850273573265}}
{"text": "(** * Representing Erros.\n\n    We use the sumor type to represent constructs in the verse\nlanguage that might be erroneous. This module developes the monadic\nnotation for it for ease of use in the rest of the program.\n\n*)\n\nRequire Export Verse.Monad.\nGlobal Notation \"{- A -}\" := (inleft A).\nGlobal Notation \"'error' A\" := (inright A) (at level 40).\n\nSection Error.\n  Variable A   : Type.\n  Variable Err : Prop.\n\n  Definition TypeE := Type + {Err}.\n\n  Definition inject (A : TypeE) : Type :=\n    match A with\n    | {- T -} => T\n    | _       => Empty_set + {Err}\n    end.\n\n  Definition lift (fam : A -> Type) : A + {Err} -> Type\n    := fun ae => inject (fam <$> ae).\n\n  Section DependentApply.\n\n    Variable fam : A -> Type.\n\n    Definition apD (f : forall a, fam a) : forall y, lift fam y\n      := fun y =>\n           match y as y0 return lift fam y0 with\n           | {- a -} => f a\n           |  error e => error e\n           end.\n\n\n  End DependentApply.\n\n  Definition recover (x : A + {Err}) : if x then A else Err\n    := match x with\n       | {- a -} => a\n       | inright b => b\n       end.\n\n  Definition noErrorIsNotError {e : Err} {a : A}  : error e <> inleft a.\n    intro pf.\n    refine (match pf with\n            |eq_refl => _\n            end); exact idProp.\n  Defined.\n\n  Definition recover' (ae : A + {Err}) : (exists a, ae = inleft a) -> { a : A | ae = inleft a}\n    := match ae as ae0 return (exists a, ae0 = {- a -}) -> {a | ae0 = {- a -} } with\n       | inleft a  => fun _  => exist _ a eq_refl\n       | inright _ =>\n         let absurdity pf :=  match pf with\n                              | ex_intro _ _ pf0 => noErrorIsNotError pf0\n                              end in\n         fun pf => False_rect _ (absurdity pf)\n       end.\n\n\nEnd Error.\nArguments recover' [A Err].\n\n(* Type to capture translation error *)\nInductive TranslationError : Prop :=\n| UpdatesNeedHostEndian\n| UpdatesNotForRotatesInC\n| ExplicitClobberNotInC\n| CouldNotTranslate : forall A : Type, A -> TranslationError\n| CouldNotTranslateBecause : forall A : Type, A -> TranslationError -> TranslationError.\n\nArguments  CouldNotTranslate [A].\nArguments  CouldNotTranslateBecause [A].\n\n\nNotation \"'updates' 'need' 'host' 'endian' 'lhs'\"\n  := UpdatesNeedHostEndian  (only printing).\nNotation \"'updates' 'with' 'rotates' 'not' 'supported' 'in' 'C'\"\n  := UpdatesNotForRotatesInC (only printing).\nNotation \"'explicit' 'clobber' 'not' 'supported' 'in' 'C'\"\n  := ExplicitClobberNotInC (only printing).\nNotation \"'could' 'not' 'translate' X\"\n  := (CouldNotTranslate  X) (at level 100, only printing).\nNotation \"'unable' 'to' 'translate' X 'because,' E\"\n  := (CouldNotTranslateBecause X E)\n       ( at level 101, right associativity, only printing,\n         format \"'[v   ' 'unable'  'to'  'translate'  X  'because,' '/' E ']'\"\n       ).\n\n\nClass Castable (E1 E2 : Prop) := { cast : E1 -> E2 }.\n\nInstance idCast E : Castable E E := { cast := @id _ }.\n\nSection Lifts.\n\n  Variable T    : Type.\n  Variable E E1 E2 : Prop.\n\n  Variable E1toE : Castable E1 E.\n  Variable E2toE : Castable E2 E.\n\n  Definition liftErr (t : T + {E1}) : T + {E} :=\n    match t with\n    | {- t' -} => {- t' -}\n    | error e  => error (cast e)\n    end.\n\n  Definition collectErr (t : T + {E1} + {E2}) : T + {E} :=\n    match t with\n    | error e2       => error (cast e2)\n    | {- error e1 -} => error (cast e1)\n    | {- {- t' -} -} => {- t' -}\n    end.\n\nEnd Lifts.\n\nArguments liftErr [T E E1 _] _.\nArguments collectErr [T E E1 E2 _ _] _.\n\nSection Conditionals.\n\n  (** Some type *)\n  Variable A : Type.\n\n  (** A decidable predicate on A *)\n  Variable P : A -> Prop.\n\n  (** The decision procedure for P *)\n  Variable decP : forall a : A, {P a} + {~ P a}.\n\n  (** Emit the value only whe the predicate is satisfied\n   *)\n  Definition when (a : A) : A + {~ P a} :=\n    match decP a with\n    | left _  => {- a -}\n    | right err => error err\n    end.\n\n  (** Emit the value unless the predicate is true. *)\n  Definition unless (a : A ) : A + {P a} :=\n    match decP a with\n    | left err => error err\n    | right _ => {- a -}\n    end.\n\nEnd Conditionals.\n\nArguments when [A P] _ _.\nArguments unless [A P] _ _.\nArguments apD [A Err fam].\nArguments recover [A Err] _.\n\nRequire Import List.\nImport ListNotations.\n\nRequire Import Vector.\nImport VectorNotations.\n\nSection PullOut.\n\n  Variable A : Type.\n  Variable Err : Prop.\n\n  Fixpoint pullOutVector {n} (verr : Vector.t (A + {Err}) n) : Vector.t A n + {Err} :=\n  match verr with\n  | []                            => {- [] -}\n  | inright err :: _              => inright err\n  | Vector.cons _ {- x -} m xs => Vector.cons _ x m  <$> (pullOutVector xs)\n  end.\n\n  Fixpoint pullOutList (lerr : list (A + {Err})) : list A + {Err} :=\n    match lerr with\n    | [] => {- [] -}\n    | error err :: _  => inright err\n    | {- x -}   :: xs => do res <- pullOutList xs;; {- x :: res -}\n    end%list.\n\n  Definition pullOutSigT {P : A -> Type} (serr : sigT (fun A => P A + {Err})) : sigT P + {Err}\n    := let 'existT _ a pae := serr in\n       match pae with\n       | error err => inright err\n       | {- pa -}  => {- existT _ _ pa -}\n       end.\n\nEnd PullOut.\n\nArguments pullOutVector [A Err n].\nArguments pullOutList [A Err].\nArguments pullOutSigT {A Err P}.  (* Using [] instead of {} does not allow this to be mapped! *)\n\nSection PartialFunctions.\n  Variable A B : Type.\n  Variable E   : Prop.\n  Variable partial : A -> B + {E}.\n\n\n  Definition InDomain a := exists b, partial a = inleft b.\n  Definition InRange  b := exists a, partial a = inleft b.\n\n  Definition domain := {a | InDomain a}.\n  Definition range  := {b | InRange b}.\n\n  Definition totalise (aD : domain) : B :=\n    match aD with\n    | exist _ a pf\n      => match recover' (partial a) pf with\n         | exist _ b _ => b\n         end\n    end.\n\n  (* Get the total core of the partial function *)\n  Definition totalCore (aD : domain) : range :=\n    match aD with\n    | exist _ a pf =>\n      match recover' (partial a) pf with\n      | exist _ b pf0 => exist _ b (ex_intro _ a pf0)\n      end\n    end.\n\n\nEnd PartialFunctions.\nArguments InDomain [A B E].\nArguments InRange  [A B E].\nArguments totalCore [A B E].\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/src/Verse/Error.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.46490157137338856, "lm_q1q2_score": 0.2684784959745745}}
{"text": "From Coq Require Import String Arith Psatz Bool List Program.Equality Lists.ListSet .\nFrom DanTrick Require Import DanTrickLanguage DanLogProp DanLogicHelpers \n  StackLanguage StackLangEval EnvToStack StackLogicGrammar LogicProp TranslationPure FunctionWellFormed ImpVarMap ImpVarMapTheorems StackLangTheorems.\n\nFrom DanTrick Require Export LogicTranslationBase ParamsWellFormed FunctionWellFormed.\n\nLemma compile_bool_args_sound_pos :  \n  forall (vals: list bool) (sargs: list bexp_stack) (dargs: list bexp_Dan) (num_args: nat) (idents: list ident),\n    compile_bool_args num_args idents dargs sargs -> \n    forall fenv_d fenv_s func_list,\n    forall (FENV_WF: fenv_well_formed' func_list fenv_d),\n      fenv_s = compile_fenv fenv_d -> \n      (forall aD aS,\n          aS = compile_aexp aD (fun x => one_index_opt x idents) (List.length idents) ->\n          forall (FUN_APP_AEXP: fun_app_well_formed fenv_d func_list aD),\n          forall (MAP_WF_AEXP: var_map_wf_wrt_aexp idents aD),\n          forall nenv dbenv stk n rho, \n            List.length dbenv = num_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 bD (fun x => one_index_opt x idents) (List.length idents) ->\n          forall (FUN_APP_BEXP: fun_app_bexp_well_formed fenv_d func_list bD),\n          forall (MAP_WF_BEXP: var_map_wf_wrt_bexp idents bD),\n          forall nenv dbenv stk bl rho, \n            List.length dbenv = num_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)) -> \n      forall nenv dbenv,\n        List.length dbenv = num_args -> \n        (eval_prop_args_rel\n           (fun (b : bexp_Dan) (v : bool) =>\n              b_Dan b dbenv fenv_d nenv v) dargs vals) ->\n        forall (ARGS_FUN_APP: prop_args_rel (V := bool) (fun_app_bexp_well_formed fenv_d func_list) dargs),\n        forall (ARGS_MAP_WF: prop_args_rel (V := bool) (var_map_wf_wrt_bexp idents) dargs),\n        forall stk,\n          state_to_stack idents nenv dbenv stk -> \n          forall rho, \n            eval_prop_args_rel\n              (fun (boolexpr : bexp_stack) (boolval : bool) =>\n                 bexp_stack_sem boolexpr (compile_fenv fenv_d) \n                                (stk ++ rho) (stk ++ rho, boolval)) sargs vals. \nProof.\n  induction vals. \n  - intros. inversion H4. subst. inversion H. subst.\n    inversion H0. subst. apply RelArgsNil.\n  - intros. inversion H4. subst. inversion H. subst. inversion H0. subst.\n    inversion ARGS_FUN_APP. inversion ARGS_MAP_WF. subst.\n    apply RelArgsCons.\n    + pose proof (BEXP := H2 arg (comp_bool idents arg)). \n      eapply BEXP.\n      -- unfold comp_bool. auto.\n      -- eauto.\n      -- eauto.\n      -- eapply eq_refl.\n      -- apply H5.\n      -- auto. \n    + pose proof (IHvals args' args (Datatypes.length dbenv) idents) as int.\n      pose proof (CompiledBoolArgs idents (Datatypes.length dbenv) args args' H9).\n      pose proof (int H3 fenv_d (compile_fenv fenv_d)) as int2.\n      pose proof (eq_refl (compile_fenv fenv_d)) as eq.\n      pose proof (int2 func_list FENV_WF eq H1 H2 nenv dbenv) as int3.\n      pose proof (eq_refl (Datatypes.length dbenv)) as eq2.\n      pose proof (int3 eq2 H11 H12 H17 stk H5 rho) as conc.\n      apply conc.\nQed.  \n\nLemma compile_arith_args_sound_pos :  \nforall vals sargs dargs num_args idents,\n  compile_arith_args num_args idents dargs sargs -> \n  forall fenv_d fenv_s func_list,\n    forall (FENV_WF: fenv_well_formed' func_list fenv_d),\n    fenv_s = compile_fenv fenv_d -> \n    (forall aD aS,\n          aS = compile_aexp aD (fun x => one_index_opt x idents) (List.length idents) ->\n          forall (FUN_APP_AEXP: fun_app_well_formed fenv_d func_list aD),\n          forall (MAP_WF_AEXP: var_map_wf_wrt_aexp idents aD),\n          forall nenv dbenv stk n rho, \n            List.length dbenv = num_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 bD (fun x => one_index_opt x idents) (List.length idents) ->\n          forall (FUN_APP_BEXP: fun_app_bexp_well_formed fenv_d func_list bD),\n          forall (MAP_WF_BEXP: var_map_wf_wrt_bexp idents bD),\n          forall nenv dbenv stk bl rho, \n            List.length dbenv = num_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)) -> \n    forall nenv dbenv,\n      List.length dbenv = num_args -> \n      (eval_prop_args_rel\n      (fun (b : aexp_Dan) (v : nat) =>\n         a_Dan b dbenv fenv_d nenv v) dargs vals) ->\n      forall (ARGS_FUN_APP: prop_args_rel (V := nat) (fun_app_well_formed fenv_d func_list) dargs),\n      forall (ARGS_MAP_WF: prop_args_rel (V := nat) (var_map_wf_wrt_aexp idents) dargs),\n      forall stk,\n        state_to_stack idents nenv dbenv stk -> \n        forall rho, \n          eval_prop_args_rel\n          (fun (boolexpr : aexp_stack) (boolval : nat) =>\n          aexp_stack_sem boolexpr (compile_fenv fenv_d) \n            (stk ++ rho) (stk ++ rho, boolval)) sargs vals. \nProof.\n  induction vals. \n  - intros. inversion H4. subst. inversion H. subst.\n    inversion H0. subst. apply RelArgsNil.\n  - intros. inversion H4. subst. inversion H. subst. inversion H0. subst.\n    inversion ARGS_FUN_APP. inversion ARGS_MAP_WF. subst.\n    apply RelArgsCons.\n    + pose proof (AEXP := H1 arg (comp_arith idents arg)). \n      eapply AEXP.\n      -- auto.\n      -- auto.\n      -- auto.\n      -- reflexivity.\n      -- eauto.\n      -- eauto.\n    + pose proof (IHvals args' args (Datatypes.length dbenv) idents) as int.\n      pose proof (CompiledArithArgs idents (Datatypes.length dbenv) args args' H9).\n      pose proof (int H3 fenv_d (compile_fenv fenv_d)) as int2.\n      pose proof (eq_refl (compile_fenv fenv_d)) as eq.\n      pose proof (int2 func_list FENV_WF eq H1 H2 nenv dbenv) as int3.\n      pose proof (eq_refl (Datatypes.length dbenv)) as eq2.\n      pose proof (int3 eq2 H11 H12 H17 stk H5 rho) as conc.\n      apply conc.\nQed.\n\nLemma trans_sound_pos_assume_comp_basestate_lp_aexp (idents : list DanTrickLanguage.ident)\n      (dbenv : list nat)\n      (fenv_d : fun_env)\n      (func_list : list fun_Dan)\n      (FENV_WF : fenv_well_formed' func_list fenv_d)\n      (H1 : forall (aD : aexp_Dan) (aS : aexp_stack),\n          aS =\n            compile_aexp aD (fun x : ident => one_index_opt x idents)\n                         (Datatypes.length idents) ->\n          fun_app_well_formed fenv_d func_list aD ->\n          var_map_wf_wrt_aexp idents aD ->\n          forall (nenv : nat_env) (dbenv0 stk : list nat)\n            (n : nat) (rho : list nat),\n            Datatypes.length dbenv0 = Datatypes.length dbenv ->\n            state_to_stack idents nenv dbenv0 stk ->\n            a_Dan aD dbenv0 fenv_d nenv n ->\n            aexp_stack_sem aS (compile_fenv fenv_d) (stk ++ rho)\n                           (stk ++ rho, n))\n      (H2 : forall (bD : bexp_Dan) (bS : bexp_stack),\n          bS =\n            compile_bexp bD (fun x : ident => one_index_opt x idents)\n                         (Datatypes.length idents) ->\n          fun_app_bexp_well_formed fenv_d func_list bD ->\n          var_map_wf_wrt_bexp idents bD ->\n          forall (nenv : nat_env) (dbenv0 stk : list nat)\n            (bl : bool) (rho : list nat),\n            Datatypes.length dbenv0 = Datatypes.length dbenv ->\n            state_to_stack idents nenv dbenv0 stk ->\n            b_Dan bD dbenv0 fenv_d nenv bl ->\n            bexp_stack_sem bS (compile_fenv fenv_d) (stk ++ rho)\n                           (stk ++ rho, bl))\n      (OKfuncs: funcs_okay_too func_list (compile_fenv fenv_d))\n      (OKparams : Forall (fun func => all_params_ok (DanTrickLanguage.Args func) (DanTrickLanguage.Body func)) func_list)\n      (nenv : nat_env)\n      (l : LogicProp nat aexp_Dan)\n      (stk : list nat)\n      (H5 : state_to_stack idents nenv dbenv stk)\n      (rho : list nat)\n      (FUN_APP : Dan_lp_prop_rel (fun_app_well_formed fenv_d func_list)\n                                 (fun_app_bexp_well_formed fenv_d func_list)\n                                 (Dan_lp_arith l))\n      (MAP_WF : Dan_lp_prop_rel (var_map_wf_wrt_aexp idents)\n                                (var_map_wf_wrt_bexp idents) (Dan_lp_arith l))\n      (H0 : Dan_lp_rel (Dan_lp_arith l) fenv_d dbenv nenv)\n      (s : LogicProp nat aexp_stack)\n      (TRANSLATE : lp_transrelation (Datatypes.length dbenv) idents\n                              (Dan_lp_arith l) (MetaNat s)):\n  meta_match_rel (MetaNat s) (compile_fenv fenv_d) (stk ++ rho).\nProof.\n  invc FUN_APP. invc MAP_WF. invc TRANSLATE. invc H9. invc H0.\n  constructor.\n  - Tactics.revert_until s.\n    revert l.\n    induction s; intros; invc H.\n    + constructor.\n    + invs H4.\n    + invs H4. econstructor.\n      * eapply H1; try eauto.\n        reflexivity. invs H6. assumption. invs H7. assumption.\n      * assumption.\n    + invs H4. invs H7. invs H6. econstructor.\n      * eapply H1; [reflexivity | | | reflexivity | .. ]; eassumption.\n      * eapply H1; [reflexivity | | | reflexivity | .. ]; eassumption.\n      * assumption.\n    + invs H4. invs H6. invs H7. econstructor.\n      * eapply IHs1. eapply H12. eassumption. assumption. assumption.\n      * eapply IHs2; [ eapply H13 | eassumption .. ].\n    + invs H6. invs H7. invs H4; [eapply RelOrPropLeft | eapply RelOrPropRight].\n      * eapply IHs1; [ eapply H8 | eassumption .. ].\n      * eapply IHs2; [ eapply H9 | eassumption .. ].\n    + invs H4. invs H6. invs H7. econstructor; [ eapply H1; try reflexivity .. |]; eassumption.\n    + invs H4. invs H6. invs H7. econstructor; [ | eassumption ].\n      eapply compile_arith_args_sound_pos; try eassumption.\n      econstructor. assumption. reflexivity. reflexivity.\n  - Tactics.revert_until s. revert l.\n    induction s; intros; invs H.\n    + constructor.\n    + invs H4.\n    + invs H4. eapply arith_compile_prop_rel_implies_pure'; eauto.\n    + invs H4. invs H6. invs H7.\n      eapply arith_compile_prop_rel_implies_pure'; eauto.\n    + invs H4. invs H6. invs H7.\n      econstructor; [ eapply IHs1; [ eapply H13 | ..] | eapply IHs2; [ eapply H14 | .. ]]; eauto.\n    + invs H6.\n      eapply arith_compile_prop_rel_implies_pure'; eauto.\n    + invs H6. eapply arith_compile_prop_rel_implies_pure'; eauto.\n    + invs H6. invs H7. constructor. eapply arith_compile_prop_args_rel_implies_pure'; eauto.\nQed.\n    \nLemma trans_sound_pos_assume_comp_basestate_lp_bexp (idents : list DanTrickLanguage.ident)\n      (dbenv : list nat)\n      (fenv_d : fun_env)\n      (func_list : list fun_Dan)\n      (FENV_WF : fenv_well_formed' func_list fenv_d)\n      (H1 : forall (aD : aexp_Dan) (aS : aexp_stack),\n          aS =\n            compile_aexp aD (fun x : ident => one_index_opt x idents)\n                         (Datatypes.length idents) ->\n          fun_app_well_formed fenv_d func_list aD ->\n          var_map_wf_wrt_aexp idents aD ->\n          forall (nenv : nat_env) (dbenv0 stk : list nat)\n            (n : nat) (rho : list nat),\n            Datatypes.length dbenv0 = Datatypes.length dbenv ->\n            state_to_stack idents nenv dbenv0 stk ->\n            a_Dan aD dbenv0 fenv_d nenv n ->\n            aexp_stack_sem aS (compile_fenv fenv_d) (stk ++ rho)\n                           (stk ++ rho, n))\n      (H2 : forall (bD : bexp_Dan) (bS : bexp_stack),\n          bS =\n            compile_bexp bD (fun x : ident => one_index_opt x idents)\n                         (Datatypes.length idents) ->\n          fun_app_bexp_well_formed fenv_d func_list bD ->\n          var_map_wf_wrt_bexp idents bD ->\n          forall (nenv : nat_env) (dbenv0 stk : list nat)\n            (bl : bool) (rho : list nat),\n            Datatypes.length dbenv0 = Datatypes.length dbenv ->\n            state_to_stack idents nenv dbenv0 stk ->\n            b_Dan bD dbenv0 fenv_d nenv bl ->\n            bexp_stack_sem bS (compile_fenv fenv_d) (stk ++ rho)\n                           (stk ++ rho, bl))\n      (OKfuncs: funcs_okay_too func_list (compile_fenv fenv_d))\n      (OKparams : Forall (fun func => all_params_ok (DanTrickLanguage.Args func) (DanTrickLanguage.Body func)) func_list)\n      (nenv : nat_env)\n      (s : LogicProp bool bexp_stack)\n      (l : LogicProp bool bexp_Dan)\n      (H4 : AbsEnv_rel (AbsEnvLP (Dan_lp_bool l)) fenv_d dbenv nenv)\n      (stk : list nat)\n      (H5 : state_to_stack idents nenv dbenv stk)\n      (rho : list nat)\n      (FUN_APP : Dan_lp_prop_rel (fun_app_well_formed fenv_d func_list)\n                                 (fun_app_bexp_well_formed fenv_d func_list)\n                                 (Dan_lp_bool l))\n      (MAP_WF : Dan_lp_prop_rel (var_map_wf_wrt_aexp idents)\n                                (var_map_wf_wrt_bexp idents) (Dan_lp_bool l))\n      (H : prop_rel (var_map_wf_wrt_bexp idents) l)\n      (TRANSLATE : compile_prop_rel (comp_bool idents) l s):\n  meta_match_rel (MetaBool s) (compile_fenv fenv_d) (stk ++ rho).\nProof.\n  invc FUN_APP. invc MAP_WF. invc H4. invc H3.\n  constructor.\n  - Tactics.revert_until s.\n    induction s; intros; invs TRANSLATE.\n    + constructor.\n    + invs H4.\n    + invs H4. invs H7. invs H8. econstructor; [ | eassumption ].\n      eapply H2; try reflexivity; try eassumption.\n    + invs H4. invs H7. invs H8. econstructor; [ .. | eassumption ].\n      all: eapply H2; try reflexivity; try eassumption.\n    + invs H4. invs H7. invs H8. econstructor; [ eapply IHs1; [ | eapply H15 | .. ] | eapply IHs2; [ | eapply H16 | .. ]]; eassumption.\n    + invs H7. invs H8. invs H4.\n      * eapply RelOrPropLeft. eapply IHs1; [ | eapply H13 | .. ]; eassumption.\n      * eapply RelOrPropRight. eapply IHs2; [ | eapply H14 | .. ]; eassumption.\n    + invs H4. invs H7. invs H8.\n      econstructor; [ .. | eassumption ].\n      all: eapply H2; try reflexivity; try eassumption.\n    + invs H4. invs H7. invs H8. econstructor; [ | eassumption ].\n      eapply compile_bool_args_sound_pos; try reflexivity;\n        try eassumption.\n      constructor. assumption.\n  - Tactics.revert_until s.\n    induction s; intros; invs TRANSLATE.\n    + constructor.\n    + constructor.\n    + invs H7. invs H8. eapply bool_compile_prop_rel_implies_pure'; try eassumption.\n      reflexivity. reflexivity.\n    + invs H7. invs H8. eapply bool_compile_prop_rel_implies_pure'; eauto.\n    + invs H7. invs H8. eapply bool_compile_prop_rel_implies_pure'; eauto.\n    + invs H7. invs H8. eapply bool_compile_prop_rel_implies_pure'; eauto.\n    + invs H7. invs H8. eapply bool_compile_prop_rel_implies_pure'; eauto.\n    + invs H7. invs H8. constructor.  eapply bool_compile_prop_args_rel_implies_pure'; eauto.\nQed.\n\n          \n\nLemma trans_sound_pos_assume_comp_basestate (m : MetavarPred)\n      (idents : list DanTrickLanguage.ident)\n      (dbenv : list nat)\n      (d : Dan_lp)\n      (fenv_d : fun_env)\n      (func_list : list fun_Dan)\n      (FENV_WF : fenv_well_formed' func_list fenv_d)\n      (H1 : forall (aD : aexp_Dan) (aS : aexp_stack),\n          aS =\n            compile_aexp aD (fun x : ident => one_index_opt x idents)\n                         (Datatypes.length idents) ->\n          fun_app_well_formed fenv_d func_list aD ->\n          var_map_wf_wrt_aexp idents aD ->\n          forall (nenv : nat_env) (dbenv0 stk : list nat)\n            (n : nat) (rho : list nat),\n            Datatypes.length dbenv0 = Datatypes.length dbenv ->\n            state_to_stack idents nenv dbenv0 stk ->\n            a_Dan aD dbenv0 fenv_d nenv n ->\n            aexp_stack_sem aS (compile_fenv fenv_d) (stk ++ rho)\n                           (stk ++ rho, n))\n      (H2 : forall (bD : bexp_Dan) (bS : bexp_stack),\n          bS =\n            compile_bexp bD (fun x : ident => one_index_opt x idents)\n                         (Datatypes.length idents) ->\n          fun_app_bexp_well_formed fenv_d func_list bD ->\n          var_map_wf_wrt_bexp idents bD ->\n          forall (nenv : nat_env) (dbenv0 stk : list nat)\n            (bl : bool) (rho : list nat),\n            Datatypes.length dbenv0 = Datatypes.length dbenv ->\n            state_to_stack idents nenv dbenv0 stk ->\n            b_Dan bD dbenv0 fenv_d nenv bl ->\n            bexp_stack_sem bS (compile_fenv fenv_d) (stk ++ rho)\n                           (stk ++ rho, bl))\n      (OKfuncs: funcs_okay_too func_list (compile_fenv fenv_d))\n      (OKparams : Forall (fun func => all_params_ok (DanTrickLanguage.Args func) (DanTrickLanguage.Body func)) func_list)\n      (nenv : nat_env)\n      (H4 : AbsEnv_rel (AbsEnvLP d) fenv_d dbenv nenv)\n      (stk : list nat)\n      (H5 : state_to_stack idents nenv dbenv stk)\n      (rho : list nat)\n      (H10 : lp_transrelation (Datatypes.length dbenv) idents d m)\n      (H0 : Dan_lp_rel d fenv_d dbenv nenv)\n      (MAP_WF : Dan_lp_prop_rel (var_map_wf_wrt_aexp idents)\n                             (var_map_wf_wrt_bexp idents) d)\n      (FUN_APP : Dan_lp_prop_rel (fun_app_well_formed fenv_d func_list)\n                             (fun_app_bexp_well_formed fenv_d func_list) d):\n  absstate_match_rel\n    (BaseState\n       (AbsStkSize (Datatypes.length idents + Datatypes.length dbenv)) m)\n    (compile_fenv fenv_d) (stk ++ rho).\nProof.\n  constructor.\n  - constructor.\n    inversion H5. simpl. rewrite app_length. rewrite app_length. rewrite map_length. lia.\n  - inversion MAP_WF. subst. invs FUN_APP. invs H10. invs H9.\n    clear H9. eapply trans_sound_pos_assume_comp_basestate_lp_aexp; eauto.\n    subst. invc H10. invc H8; eauto.\n    eapply trans_sound_pos_assume_comp_basestate_lp_bexp; eauto.\nQed.\n\n\n\n\n\nLemma trans_sound_pos_assume_comp : \n  forall state dan_log num_args idents, \n    logic_transrelation num_args idents dan_log state -> \n    forall fenv_d fenv_s func_list,\n    forall (FENV_WF: fenv_well_formed' func_list fenv_d)\n      (OKfuncs: funcs_okay_too func_list (compile_fenv fenv_d))\n      (OKparams : Forall (fun func => all_params_ok (DanTrickLanguage.Args func) (DanTrickLanguage.Body func)) func_list),\n      fenv_s = compile_fenv fenv_d -> \n      (forall aD aS,\n          aS = compile_aexp aD (fun x => one_index_opt x idents) (List.length idents) ->\n          forall (FUN_APP_AEXP: fun_app_well_formed fenv_d func_list aD),\n          forall (MAP_WF_AEXP: var_map_wf_wrt_aexp idents aD),\n          forall nenv dbenv stk n rho, \n            List.length dbenv = num_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 bD (fun x => one_index_opt x idents) (List.length idents) ->\n          forall (FUN_APP_BEXP: fun_app_bexp_well_formed fenv_d func_list bD),\n          forall (MAP_WF_BEXP: var_map_wf_wrt_bexp idents bD),\n          forall nenv dbenv stk bl rho, \n            List.length dbenv = num_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)) -> \n      forall nenv dbenv,\n        List.length dbenv = num_args ->\n        forall (FUN_APP: AbsEnv_prop_rel (fun_app_well_formed fenv_d func_list)\n                                     (fun_app_bexp_well_formed fenv_d func_list)\n                                     dan_log)\n          (MAP_WF: AbsEnv_prop_rel (var_map_wf_wrt_aexp idents)\n                                    (var_map_wf_wrt_bexp idents)\n                                    dan_log),\n        AbsEnv_rel dan_log fenv_d dbenv nenv -> \n        forall stk,\n          state_to_stack idents nenv dbenv stk -> \n          forall rho, \n            absstate_match_rel state fenv_s (stk ++ rho). \nProof.\n  induction state; intros.\n  - inversion H. subst. clear H. inversion H4. inversion MAP_WF. inversion FUN_APP. subst.\n    eapply trans_sound_pos_assume_comp_basestate; eauto.\n    \n  - invs H. invs H4. invs MAP_WF. invs FUN_APP.\n    constructor.\n    + eapply IHstate1; try eassumption; try reflexivity.\n    + eapply IHstate2; try eassumption; try reflexivity.\n  - invs H. invs MAP_WF. invs FUN_APP. invs H4.\n    + eapply RelAbsOrLeft. eapply IHstate1; try eassumption; try reflexivity.\n    + eapply RelAbsOrRight. eapply IHstate2; try eassumption; try reflexivity.\nQed.\n", "meta": {"author": "uwplse", "repo": "potpie", "sha": "d4814d315ff9d450a8d91ed77b22340b0ff35690", "save_path": "github-repos/coq/uwplse-potpie", "path": "github-repos/coq/uwplse-potpie/potpie-d4814d315ff9d450a8d91ed77b22340b0ff35690/LogicTrans.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.26838842492807635}}
{"text": "Require Import Verdi.GhostSimulations.\n\nRequire Import VerdiRaft.Raft.\nRequire Import VerdiRaft.RaftRefinementInterface.\n\nRequire Import VerdiRaft.SortedInterface.\nRequire Import VerdiRaft.AppendEntriesRequestTermSanityInterface.\n\nSection AppendEntriesRequestTermSanity.\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  Context {si : sorted_interface}.\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  Lemma 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 logs_sorted_aerts :\n    forall net,\n      logs_sorted (deghost net) ->\n      append_entries_request_term_sanity net.\n  Proof using. \n    unfold logs_sorted, append_entries_request_term_sanity. intuition.\n    unfold packets_ge_prevTerm in *. find_apply_lem_hyp ghost_packet.\n    eauto.\n  Qed.\n\n  Instance aertsi : append_entries_request_term_sanity_interface.\n  Proof.\n    split. intros. find_apply_lem_hyp lift_sorted.\n    eauto using logs_sorted_aerts.\n  Qed.\nEnd AppendEntriesRequestTermSanity.\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/AppendEntriesRequestTermSanityProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2683884186517871}}
{"text": "From Coq Require Import FunctionalExtensionality List Bool Program.Basics.\nFrom Coq Require Import Arith Arith.Peano_dec Arith.Compare_dec.\nFrom Chapar Require Import Predefs extralib KVStore.\n\nImport ListNotations.\n\nModule KVSAlg3 <: AlgDef.\n\n  Import SysPredefs.\n\n  Definition Clock := nat.\n\n  Record Entry {Val: Type} := {\n    entry_val: Val;\n    entry_node: NId;\n    entry_clock: Clock\n  }.\n  Definition entry {Val: Type} := @Build_Entry Val.\n\n  Record StateRec {Val: Type} := {\n    store: Key -> @Entry Val;\n    rec: NId -> Clock;\n    dep: NId -> Clock\n  }.\n  Definition state {Val: Type} := @Build_StateRec Val.\n  Definition State {Val: Type} := @StateRec Val.\n\n  Record UpdateRec {Val: Type} := {\n    sender_node: NId;\n    sender_dep: NId -> Clock\n  }.\n  Definition update {Val: Type} := @Build_UpdateRec Val.\n  Definition Update {Val: Type} := @UpdateRec Val.\n\n  Definition dummy_update {Val: Type} := @update Val 0 (fun n => 0).\n\n  Section ValParam.\n  Variable Val: Type.\n  \n  Definition init_method (init_val: Val): State :=\n    state (fun (k: Key) => entry init_val 0 0)\n          (fun (n: NId) => 0)\n          (fun (n: NId) => 0).\n\n  Definition get_method (n: NId)(this: State)(k: Key): (Val * State) :=\n    let s := store this in\n    let r := rec this in\n    let d := dep this in\n    let e := s k in\n    let v := entry_val e in\n    let n' := entry_node e in\n    let c' := entry_clock e in\n    let d' := override d n' (max (d n') c') in\n    (v, (state s r d')).\n\n  Definition put_method (n: NId)(this: State)(k: Key)(v: Val): (State * Update) :=\n    let s := store this in\n    let r := rec this in\n    let d := dep this in\n    let d' := override d n ((r n) + 1) in\n    let r' := override r n ((r n) + 1) in\n    let s' := override s k (entry v n (d' n)) in\n    ((state s' r' d'), (@update Val n d')).\n\n  Definition guard_method (n: NId)(this: @State Val)(k: Key)(v: Val)(u: @Update Val): bool :=\n    let s := store this in\n    let r := rec this in\n    let d := dep this in\n    let n' := sender_node u in\n    let d' := sender_dep u in\n    (fold_left \n       (fun b n => b && ((d' n) <=? (r n)))\n       nids\n       true)\n     && ((d' n') =? ((r n') + 1)).\n\n  Definition update_method (n: NId)(this: State)(k: Key)(v: Val)(u: @Update Val): State :=\n    let s := store this in\n    let r := rec this in\n    let d := dep this in\n    let n' := sender_node u in\n    let d' := sender_dep u in\n    let r' := override r n' (d' n') in\n    let d'' := fun n => max (d n) (d' n) in\n    let s' := override s k (entry v n' (d' n')) in\n    (state s' r' d'').\n\n  End ValParam.\n\nEnd KVSAlg3.\n\nModule KVSAlg3CauseObl (SyntaxArg: SyntaxPar) <: CauseObl KVSAlg3 SyntaxArg.\n\n  (* Module Type InstExecToAbsExecPar (AlgDef: AlgDef)(SyntaxArg: SyntaxPar). *)\n\n  Export SysPredefs.\n\n  Module CExec := ConcExec SyntaxArg KVSAlg3.\n  Import CExec.\n  Module SExec := SeqExec SyntaxArg.\n  Import SExec.\n  Module ICExec := InstConcExec SyntaxArg KVSAlg3.\n  Import ICExec.\n\n  Lemma inst_clock_leq_rec:\n    forall (p: ICExec.Syntax.PProg)(h: list Label)(s: State)(n: NId),\n      let as1 := alg_state ((node_states (init p)) n) in\n      let as2 := alg_state ((node_states s) n) in\n      step_star (init p) h s\n      -> forall k, entry_clock (store as2 k) <= rec as2 (entry_node (store as2 k)).\n\n    Proof.\n      intros.\n      \n      remember (init p) as s0 eqn: Hs.\n      induction H.\n\n      subst as1.\n      subst as2.\n      subst s.\n      simpl.\n      apply Nat.le_refl.      \n\n      rename as2 into as3.\n      pose (as2 := alg_state (node_states s2 n)).\n      depremise IHstep_star. assumption.\n      subst as3.\n      inversion H0; clear H0;\n      simpl in *.\n\n      destruct (eq_nat_dec n n0).\n        (* -- *)\n        simpl_override.\n        simpl.\n        simpl_override.\n        simpl.\n        destruct (eq_nat_dec k0 k).\n          (* -- *)\n          simpl_override.\n          simpl.\n          simpl_override.\n          simpl.\n          apply Nat.le_refl.\n          (* -- *)\n          simpl_override.\n          rewrite <- H2 in IHstep_star.\n          simpl in IHstep_star.\n          subst n.\n          simpl_override_in IHstep_star.\n          simpl in IHstep_star.\n          destruct (eq_nat_dec n0 (entry_node (store s k))).\n          simpl_override.\n          rewrite e0.\n          rewrite Nat.add_comm.\n          simpl.\n          apply le_S.\n          assumption.\n          simpl_override.\n          assumption.\n       (* -- *)\n       simpl_override.\n       rewrite <- H2 in IHstep_star.\n       simpl in IHstep_star.\n       simpl_override_in IHstep_star.\n       assumption.\n\n      destruct (eq_nat_dec n n0).\n        (* -- *)\n        simpl_override.\n        simpl.\n        rewrite <- H2 in IHstep_star.\n        simpl in IHstep_star.\n        subst n.\n        simpl_override_in IHstep_star.\n        simpl in IHstep_star.\n        assumption.\n        (* -- *)\n        simpl_override.\n        simpl.\n        rewrite <- H2 in IHstep_star.\n        simpl in IHstep_star.\n        simpl_override_in IHstep_star.\n        simpl in IHstep_star.\n        assumption.\n\n      destruct (eq_nat_dec n n0).\n        (* -- *)\n        simpl_override.\n        simpl.\n        simpl_override.\n        simpl.\n        destruct (eq_nat_dec k0 k).\n          (* -- *)\n          simpl_override.\n          simpl.\n          simpl_override.\n          simpl.\n          apply Nat.le_refl.\n          (* -- *)\n          simpl_override.\n          rewrite <- H3 in IHstep_star.\n          simpl in IHstep_star.\n          subst n.\n          simpl_override_in IHstep_star.\n          simpl in IHstep_star.\n          destruct (eq_nat_dec (sender_node u) (entry_node (store s k))).\n          simpl_override.\n          rewrite <- e0 in *.\n          unfold guard_method in H2.\n          bool_to_prop_in H2.\n          destruct H2.\n          bool_to_prop_in H2.\n          rewrite H2.\n          rewrite Nat.add_comm.\n          simpl.\n          apply le_S.\n          assumption.\n         (* -- *)\n         simpl_override.\n         assumption.\n       (* -- *)\n       simpl_override.\n       rewrite <- H3 in IHstep_star.\n       simpl in IHstep_star.\n       simpl_override_in IHstep_star.\n       simpl in IHstep_star.\n       assumption.\n\n      destruct (eq_nat_dec n n0).\n        (* -- *)\n        simpl_override.\n        simpl.\n        rewrite <- H2 in IHstep_star.\n        simpl in IHstep_star.\n        subst n.\n        simpl_override_in IHstep_star.\n        simpl in IHstep_star.\n        assumption.\n        (* -- *)\n        simpl_override.\n        simpl.\n        rewrite <- H2 in IHstep_star.\n        simpl in IHstep_star.\n        simpl_override_in IHstep_star.\n        simpl in IHstep_star.\n        assumption.\n       \n    Qed.\n\n  Lemma dep_leq_rec:\n    forall (p: ICExec.Syntax.PProg)(h: list Label)(s: State)(n: NId),\n        let as2 := alg_state ((node_states s) n) in\n        step_star (init p) h s\n        -> forall n', In n' nids -> dep as2 n' <= rec as2 n'.\n\n    Proof.\n      intros p h s n as2 H n' Hi.\n      remember (init p) as s0 eqn: Hs.\n      induction H.\n\n      subst as2.\n      subst s.\n      simpl.\n      apply Nat.le_refl.\n\n      rename as2 into as3.\n      pose (as2 := alg_state (node_states s2 n)).\n      simpl in IHstep_star. depremise IHstep_star. assumption.\n\n      subst as3.\n      inversion H0; clear H0;\n      simpl in *.\n\n\n      (* put *)\n      rewrite <- H2 in IHstep_star.\n      simpl in IHstep_star.\n\n      destruct (eq_nat_dec n n0).\n        (* --- *)\n        simpl_override.\n        simpl.\n        destruct (eq_nat_dec n' n0).\n          (* --- *)\n          simpl_override.\n          simpl.\n          simpl_override.\n          subst n'.\n          apply Nat.le_refl.\n          (* --- *)\n          simpl_override.\n          simpl.\n          simpl_override.\n          subst n.\n          simpl_override_in IHstep_star.\n          simpl in IHstep_star.          \n          assumption.\n        (* --- *)\n        simpl_override.\n        simpl_override_in IHstep_star.\n        assumption.\n\n      (* get *)\n      unfold override.\n      destruct (eq_nat_dec n n0).\n        (* --- *)\n        simpl.\n        subst n.\n        destruct (eq_nat_dec (entry_node (store s k)) n').\n          (* -- *)\n          subst n'.\n          simpl_override.\n          apply Nat.max_lub.\n          rewrite <- H2 in IHstep_star.\n          simpl in IHstep_star.\n          simpl_override_in IHstep_star.\n          simpl in IHstep_star.\n          assumption.\n          assert (A := inst_clock_leq_rec p ls s2 n0).\n          simpl in A.\n          depremise A. subst s1. assumption.\n          specialize (A k).\n          rewrite <- H2 in A.\n          simpl in A.\n          simpl_override_in A.\n          simpl in A.\n          assumption.\n          (* -- *)\n          simpl_override.\n          rewrite <- H2 in IHstep_star.\n          simpl in IHstep_star.\n          simpl_override_in IHstep_star.\n          simpl in IHstep_star.\n          assumption.\n        (* --- *)\n        rewrite <- H2 in IHstep_star.\n        simpl in IHstep_star.\n        simpl_override_in IHstep_star.\n        assumption.\n        \n\n      (* update *)\n      destruct (n =_? n0).       \n\n        (* --- *)\n        subst n.\n        simpl_override.\n        simpl.\n        destruct (sender_node u =_? n').\n        \n          (* -- *)\n          rewrite e0 in *.\n          simpl_override.\n\n          rewrite <- H3 in IHstep_star.\n          simpl in IHstep_star.\n          simpl_override_in IHstep_star.\n          simpl in IHstep_star.\n\n          unfold guard_method in H2.\n          bool_to_prop_in H2.\n          destruct H2.\n          bool_to_prop_in H2.\n          rewrite e0 in H2.\n          rewrite H2.\n          apply Nat.max_lub.\n          rewrite Nat.add_comm.\n          simpl.\n          apply le_S.\n          assumption.\n          apply Nat.le_refl.\n\n          (* -- *)\n          simpl_override.\n          rewrite <- H3 in IHstep_star.\n          simpl in IHstep_star.\n          simpl_override_in IHstep_star.\n          simpl in IHstep_star.\n          apply Nat.max_lub.\n          assumption.\n          unfold guard_method in H2.\n          bool_to_prop_in H2.\n          destruct H2.\n          assert (A:= fold_left_and NId nids n'\n                 (fun n => sender_dep u n <=? rec s n)).\n            depremise A. split. assumption. assumption.\n            simpl in A.\n            bool_to_prop_in A.\n          assumption.\n\n        (* --- *)\n        simpl_override.\n        rewrite <- H3 in IHstep_star.\n        simpl in IHstep_star.\n        simpl_override_in IHstep_star.\n        simpl in IHstep_star.\n        assumption.\n\n      (* fault *)\n      destruct (eq_nat_dec n n0).\n        (* --- *)\n        subst n.\n        simpl_override.\n        subv_in s2 IHstep_star.\n        simpl_override_in IHstep_star.\n        assumption.\n        (* --- *)\n        simpl_override.\n        subv_in s2 IHstep_star.\n        simpl_override_in IHstep_star.\n        assumption.\n\n    Qed.\n\n  Lemma entry_clock_leq_dep:\n    forall (p: ICExec.Syntax.PProg)(h: list Label)(s: State)(n n': NId)(k: Key),\n        let as2 := alg_state ((node_states s) n) in\n        (step_star (init p) h s\n         /\\ entry_node (store as2 k) = n')\n        -> entry_clock (store as2 k) <= dep as2 n'.\n\n    Proof.\n      intros.\n      remember (init p) as s0 eqn: Hs.\n      open_conjs.\n      induction H.\n\n      subst as2.\n      subst s.\n      simpl.\n      apply Nat.le_refl.\n\n      rename as2 into as3.\n      pose (as2 := alg_state (node_states s2 n)).\n      simpl in IHstep_star. depremise IHstep_star. assumption.\n\n      subst as3.\n      inversion H1;\n      simpl in *.\n\n      (* put *)\n      rewrite <- H3 in IHstep_star.\n      simpl in IHstep_star.\n\n      destruct (eq_nat_dec n n0).\n      subst n.\n\n        (* --- *)\n        destruct (eq_nat_dec n' n0).\n\n          (* --- *)\n          subst n'.\n          simpl_override.\n          simpl.\n          simpl_override.\n          simpl.\n          destruct (eq_nat_dec k0 k).\n            simpl_override.\n            simpl.\n            simpl_override.\n            reflexivity.\n\n            simpl_override.\n            rewrite <- H5 in IHstep_star. simpl in IHstep_star. simpl_override_in IHstep_star. simpl in IHstep_star. simpl_override_in IHstep_star. simpl in IHstep_star. simpl_override_in IHstep_star.\n            depremise IHstep_star. reflexivity.\n            assert (A := dep_leq_rec p ls s2 n0).\n              simpl in A. depremise A. subst s1. assumption.\n              specialize (A n0). depremise A. assumption.\n              rewrite <- H3 in A. simpl in A. simpl_override_in A. simpl in A.\n            rewrite <- H5 in e0. simpl in e0. simpl_override_in e0. simpl in e0. simpl_override_in e0.\n            rewrite e0 in IHstep_star.\n            rewrite Nat.add_comm.\n            simpl.\n            apply le_S.\n            eapply Nat.le_trans; eassumption.          \n\n          (* --- *)\n          simpl_override.\n          simpl.\n          simpl_override.\n          simpl.\n          simpl_override_in IHstep_star.\n          simpl in IHstep_star.\n          rewrite <- H5 in H0. simpl in H0. simpl_override_in H0. simpl in H0. simpl_override_in H0. simpl in H0.\n          destruct (eq_nat_dec k k0).\n\n            (* -- *)\n            subst k.\n            simpl_override_in H0.\n            simpl in H0.\n            symmetry in H0. contradiction.\n\n            (* -- *)\n            simpl_override.\n            simpl_override.\n            simpl_override_in H0.\n            depremise IHstep_star. assumption.\n            assumption.\n\n        (* --- *)      \n        simpl_override.      \n        simpl_override_in IHstep_star.\n        simpl in IHstep_star.\n        rewrite <- H5 in H0. simpl in H0. simpl_override_in H0.\n        depremise IHstep_star. assumption.\n        assumption.\n\n      (* get *)\n      destruct (eq_nat_dec n n0).\n        subst n.\n        simpl_override.\n        simpl.\n        destruct (eq_nat_dec (entry_node (store s k0)) n').\n\n          (* --- *)\n          subst n'.\n          simpl_override.\n          simpl.\n\n          rewrite <- H3 in IHstep_star.\n          simpl in IHstep_star.\n          simpl_override_in IHstep_star.\n          simpl in IHstep_star.\n          simpl_override_in IHstep_star.\n          simpl in IHstep_star.\n          simpl_override_in IHstep_star.\n          simpl in IHstep_star.\n          rewrite <- H5 in IHstep_star.\n          simpl in IHstep_star.\n          simpl_override_in IHstep_star.        \n          simpl in IHstep_star.\n\n          rewrite <- H5 in e0.\n          simpl in e0.\n          simpl_override_in e0.\n          simpl in e0.\n          \n          depremise IHstep_star. reflexivity.\n          \n          apply PeanoNat.Nat.max_le_iff.\n          left. rewrite e0. assumption.\n          \n          (* --- *)\n          simpl_override.\n          rewrite <- H3 in IHstep_star.\n          simpl in IHstep_star.\n          simpl_override_in IHstep_star.\n          simpl in IHstep_star.\n          rewrite <- H5 in H0. simpl in H0. simpl_override_in H0. simpl in H0.\n          depremise IHstep_star. assumption.\n          assumption.\n\n        (* --- *)\n        simpl_override.\n        rewrite <- H3 in IHstep_star.\n        simpl in IHstep_star.\n        simpl_override_in IHstep_star.\n        simpl in IHstep_star.\n        rewrite <- H5 in H0. simpl in H0. simpl_override_in H0. simpl in H0.\n        depremise IHstep_star. assumption.\n        assumption.\n\n      (* update *)\n      destruct (eq_nat_dec n n0).\n        (* --- *)\n        subst n.\n        simpl_override.\n        simpl.\n\n        destruct (eq_nat_dec k k0).\n\n          (* -- *)\n          simpl_override.\n          simpl.\n\n          rewrite <- H6 in H0. simpl in H0. simpl_override_in H0. simpl in H0. rewrite e0 in H0. simpl_override_in H0. simpl in H0.\n          rewrite H0.\n          apply Nat.le_max_r.\n\n          (* -- *)\n          simpl_override.\n          simpl.\n\n          rewrite <- H4 in IHstep_star.\n          simpl in IHstep_star.\n          simpl_override_in IHstep_star.\n          simpl in IHstep_star.\n          depremise IHstep_star. rewrite <- H6 in H0. simpl in H0. simpl_override_in H0. simpl in H0. simpl_override_in H0. assumption.\n\n          eapply Nat.le_trans. eassumption.\n          apply Nat.le_max_l.\n\n        (* --- *)\n        simpl_override.\n        rewrite <- H4 in IHstep_star.\n        simpl in IHstep_star.\n        simpl_override_in IHstep_star.\n        simpl in IHstep_star.\n        depremise IHstep_star. rewrite <- H6 in H0. simpl in H0. simpl_override_in H0. assumption.\n        assumption.      \n\n      (* fault *)\n      subv_in s2 IHstep_star.\n      destruct (eq_nat_dec n n0).\n        (* -- *)\n        subst n.\n        simpl_override.\n        simpl_override_in IHstep_star.\n        depremise IHstep_star.\n        subv_in s3 H0.\n        simpl_override_in H0.\n        assumption.\n        assumption.\n        (* -- *)\n        simpl_override.\n        simpl_override_in IHstep_star.\n        depremise IHstep_star.\n        subv_in s3 H0.\n        simpl_override_in H0.\n        assumption.\n        assumption.\n\n    Qed.\n\n\n  Lemma update_sender_eq_msg_sender:\n    forall p h s m,\n      step_star (init p) h s\n      /\\ In m (messages s)\n      -> sender_node (msg_update m) = msg_sender m.\n\n    Proof.\n      intros.\n      open_conjs.\n      remember (init p) as s0 eqn: Hi.\n      induction H.\n\n      subst s.\n      simpl in H0.\n      contradiction.\n\n      depremise IHstep_star.\n      assumption.\n      inversion H1.\n\n      rewrite <- H5 in H0.\n      simpl in H0.\n      apply in_app_iff in H0.\n      destruct H0 as [H0 | H0].\n      \n      depremise IHstep_star.\n      rewrite <- H3.\n      simpl.\n      assumption.\n      assumption.\n      \n      apply in_map_iff in H0.\n      destruct H0 as [n' [N1 N2]].\n      subst m.\n      simpl in *.\n      reflexivity.\n\n      rewrite <- H3 in IHstep_star.\n      simpl in IHstep_star.\n      depremise IHstep_star.\n      rewrite <- H5 in H0.\n      assumption.\n      assumption.\n\n      rewrite <- H4 in IHstep_star.\n      simpl in IHstep_star.\n      depremise IHstep_star.\n      rewrite <- H6 in H0.\n      simpl in H0.\n      apply in_app_iff in H0.\n      destruct H0 as [H0 | H0].\n      apply in_app_iff.\n      left. assumption.\n      apply in_app_iff.\n      right. apply in_cons. assumption.\n      assumption.\n\n      depremise IHstep_star.\n      subv s2.\n      subv_in s3 H0.\n      assumption.\n      assumption.\n\n    Qed.\n\n\n  Lemma update_no_self_message:\n    forall p h s m,\n      step_star (init p) h s\n      /\\ In m (messages s)\n      -> not (sender_node (msg_update m) = msg_receiver m).\n    \n    Proof.\n      intros.\n      destruct H as [H1 H2].\n      assert (A1 := update_sender_eq_msg_sender p h s m). \n        depremise A1. split; assumption.\n      assert (A2 := no_self_message p h s m).\n        depremise A2. split; assumption.\n      rewrite <- A1 in A2.\n      assumption.\n\n    Qed.\n\n\n  Lemma step_star_clock_nondec:\n    forall (p: ICExec.Syntax.PProg)(h0 h: list Label)(s s': State)(n: NId),\n        let sc := dep (alg_state ((node_states s) n)) in\n        let sc' := dep (alg_state ((node_states s') n)) in\n        (step_star (init p) h0 s\n         /\\ step_star s h s')\n        -> forall n', sc n' <= sc' n'.\n\n    Proof.\n      intros.\n      destruct H as [HI H].\n\n      induction H.\n\n      apply Nat.le_refl.\n      rename sc' into sc''.\n      pose (sc' := dep (alg_state (node_states s2 n))).\n      assert (sc' n' <= sc'' n').\n      clear IHstep_star.\n\n      inversion H0;\n      subst sc;\n      subst sc';\n      subst sc'';\n      simpl in *.\n\n      (* put *)\n      rewrite <- H2.\n      rewrite <- H4.\n      simpl.\n      destruct (eq_nat_dec n n0).\n\n        (* --- *)\n        simpl_override.\n        destruct (eq_nat_dec n' n0).\n\n          (* --- *)\n          simpl_override.\n          simpl.\n          simpl_override.\n          subst n'. \n          rewrite Nat.add_comm.\n          simpl.\n          apply le_S.\n          assert (A:= dep_leq_rec p (h0 ++ ls) s2 n0). \n            simpl in A.\n            depremise A.\n            eapply step_star_app. exists s1. split; assumption.\n            specialize (A n0). depremise A. \n              assert (B := label_node_in_nids p (h0++ls++[l]) s3 l). depremise B.\n                split. apply step_star_app. exists s1. split. assumption. apply step_star_app_one. exists s2. split; assumption.\n                apply in_app_iff. right. apply in_app_iff. right. apply in_eq.\n              subst l0. rewrite <- H3 in B. simpl in B.\n            assumption.\n          \n          rewrite <- H2 in A.\n          simpl in A.\n          simpl_override_in A.\n          simpl in A.\n          assumption.\n\n          (* --- *)\n          simpl_override.\n          simpl.\n          simpl_override.\n          apply Nat.le_refl.\n\n        (* --- *)\n        simpl_override.\n        simpl_override.\n        apply Nat.le_refl.\n\n      (* get *)\n      rewrite <- H2.\n      rewrite <- H4.\n      simpl.\n      destruct (eq_nat_dec n n0).\n\n        (* --- *)\n        subst n.\n        simpl_override.\n        simpl_override.\n        simpl.\n        destruct (eq_nat_dec (entry_node (store s k)) n').\n\n          (* -- *)\n          subst n'.\n          simpl_override.\n          rewrite <- Nat.le_max_l.\n          apply Nat.le_refl.\n\n          (* -- *)\n          simpl_override.\n          apply Nat.le_refl.\n\n        (* --- *)\n        simpl_override.\n        simpl_override.\n        apply Nat.le_refl.\n        \n\n      (* update *)\n      rewrite <- H3.\n      rewrite <- H5.\n      simpl.\n      destruct (eq_nat_dec n n0).\n      \n        (* --- *)\n        subst n.\n        simpl_override.\n        simpl_override.\n        simpl.\n        apply Nat.le_max_l.\n\n        (* --- *)\n        simpl_override.\n        simpl_override.\n        apply Nat.le_refl.\n\n\n      (* fault *)\n      subv s2.\n      subv s3.\n      destruct (eq_nat_dec n n0).\n\n        (* --- *)\n        subst n.\n        simpl_override.\n        simpl_override.\n        apply Nat.le_refl.\n\n        (* --- *)\n        simpl_override.\n        simpl_override.\n        apply Nat.le_refl.\n\n\n      simpl in IHstep_star.\n      depremise IHstep_star.\n      assumption.\n      subst sc'.\n      subst sc''.\n\n      eapply Nat.le_trans;\n      eassumption.\n\n\n    Qed.\n\n  Lemma step_star_rec_nondec:\n    forall (p: ICExec.Syntax.PProg)(h0 h: list Label)(s s': State)(n: NId),\n        let sc := rec (alg_state ((node_states s) n)) in\n        let sc' := rec (alg_state ((node_states s') n)) in\n        (step_star (init p) h0 s\n         /\\ step_star s h s')\n        -> forall n', sc n' <= sc' n'.\n\n    Proof.\n      intros.\n      destruct H as [HI H].\n\n      induction H.\n\n      apply Nat.le_refl.\n\n      rename sc' into sc''.\n      pose (sc' := rec (alg_state (node_states s2 n))).\n      assert (sc' n' <= sc'' n').\n      clear IHstep_star.\n\n      inversion H0; clear H0;\n      subst sc;\n      subst sc';\n      subst sc'';\n      simpl in *.\n\n      (* put *)\n      rewrite <- H2.\n      rewrite <- H4.\n      simpl.\n      destruct (eq_nat_dec n n0).\n\n        (* --- *)\n        simpl_override.\n        destruct (eq_nat_dec n' n0).\n\n          (* --- *)\n          simpl_override.\n          simpl.\n          simpl_override.\n          subst n'. \n          rewrite Nat.add_comm.\n          simpl.\n          apply le_S.\n          apply Nat.le_refl.\n\n          (* --- *)\n          simpl_override.\n          simpl.\n          simpl_override.\n          apply Nat.le_refl.\n\n        (* --- *)\n        simpl_override.\n        simpl_override.\n        apply Nat.le_refl.\n\n      (* get *)\n      rewrite <- H2.\n      rewrite <- H4.\n      simpl.\n      destruct (eq_nat_dec n n0).\n\n        (* --- *)\n        subst n.\n        simpl_override.\n        simpl_override.\n        simpl.\n        apply Nat.le_refl.\n\n        (* --- *)\n        simpl_override.\n        simpl_override.\n        apply Nat.le_refl.\n        \n      (* update *)\n      rewrite <- H3.\n      rewrite <- H5.\n      simpl.\n      destruct (eq_nat_dec n n0).\n      \n        (* --- *)\n        subst n.\n        simpl_override.\n        simpl_override.\n        simpl.\n        destruct (eq_nat_dec (sender_node u) n').\n        \n          (* -- *)\n          simpl_override.\n          unfold guard_method in H2.\n          bool_to_prop_in H2.\n          destruct H2.\n          bool_to_prop_in H2.\n          rewrite e0 in *.\n          rewrite H2.\n          rewrite Nat.add_comm.\n          simpl.\n          apply le_S.\n          apply Nat.le_refl.\n\n          (* -- *)\n          simpl_override.\n          apply Nat.le_refl.\n\n        (* --- *)\n        simpl_override.\n        simpl_override.\n        apply Nat.le_refl.\n\n      (* fault *)\n      subv s2.\n      subv s3.\n      destruct (eq_nat_dec n n0).\n\n        (* --- *)\n        subst n.\n        simpl_override.\n        simpl_override.\n        apply Nat.le_refl.\n\n        (* --- *)\n        simpl_override.\n        simpl_override.\n        apply Nat.le_refl.\n\n      simpl in IHstep_star.\n      depremise IHstep_star.\n      assumption.\n      subst sc'.\n      subst sc''.\n\n      eapply Nat.le_trans;\n      eassumption.\n\n    Qed.\n\n  Lemma step_star_dep_rec_nondec:\n    forall (p: ICExec.Syntax.PProg)(h0 h: list Label)(s s': State)(n: NId),\n        let sc := dep (alg_state ((node_states s) n)) in\n        let sc' := rec (alg_state ((node_states s') n)) in\n        (step_star (init p) h0 s\n         /\\ step_star s h s')\n        -> forall n', In n' nids -> sc n' <= sc' n'.\n\n    Proof.\n      intros.\n      subst sc.\n      subst sc'.\n\n      assert (A1 := step_star_clock_nondec p h0 h s s' n H n').\n      \n      open_conjs.\n      assert (A2 := dep_leq_rec p (h0 ++ h) s' n).\n       simpl in A2. depremise A2.\n       apply step_star_app. exists s. split; assumption.\n       specialize (A2 n').\n       depremise A2. assumption.\n      eapply Nat.le_trans;  eassumption.      \n    Qed.\n\n  Lemma proc_order_clock:\n    forall (p: ICExec.Syntax.PProg)(h: list Label)(s: State)(l l': Label)(n: NId),\n      (step_star (init p) h s\n       /\\ prec h l l'\n       /\\ label_node l = label_node l')\n      -> (let c := dep (label_post_state l) n in\n          let c' := dep (label_post_state l') n in\n          c <= c'\n          /\\ ((label_node l' = n /\\ label_is_put l') -> c < c')).\n\n      Proof.\n        intros.\n        destruct H as [H1 [H2 H3]].\n        assert (L := prec_exec p h s l l').\n        depremise L. split; assumption.\n        destruct L as [h1 L].\n        destruct L as [s1 L].\n        destruct L as [s' L].\n        destruct L as [h2 L].\n        destruct L as [s'' L].\n        destruct L as [s2 L].\n        destruct L as [h3 [L1 [L3 [L4 [L5 L2]]]]].        \n        assert (M1 := step_star_clock_nondec p (h1 ++ [l]) h2 s' s'' (label_node l)).\n          simpl in M1. depremise M1. split. apply step_star_app_one. exists s1. split; assumption. assumption. specialize (M1 n).\n        subst c. subst c'.\n        assert (N1 := label_poststate_state s1 s' l L3).\n        assert (N2 := label_poststate_state s'' s2 l' L5).\n        rewrite N1; clear N1.\n        rewrite N2; clear N2.\n\n        assert (L: dep (alg_state (node_states s'' (label_node l))) n\n                       <= dep (alg_state (node_states s2 (label_node l'))) n\n                       /\\ (label_node l' = n /\\ label_is_put l'\n                          ->  dep (alg_state (node_states s'' (label_node l))) n <\n                             dep (alg_state (node_states s2 (label_node l'))) n)).\n\n        clear M1.\n        rewrite H3 in *.\n\n        inversion L5.\n\n        (* put *)\n        simpl.\n        simpl_override.\n        simpl.\n        simpl_override.\n        simpl.\n        destruct (eq_nat_dec n n0).\n          (* -- *)\n          simpl_override.\n          assert (A:= dep_leq_rec p (h1 ++ l :: h2) s'' n0). \n            simpl in A. depremise A. apply step_star_app. exists s1. split. assumption. apply step_star_end. exists s'. split; assumption.\n            specialize (A n0).\n            rewrite <- H0 in A. simpl in A. simpl_override_in A. \n          simpl in A.\n            depremise A. assert (B := label_node_in_nids p (h1 ++ [l] ++ h2 ++ [l']) s2 l'). depremise B. split. apply step_star_app. exists s1. split. assumption. apply step_star_app. exists s'. split. apply step_star_one. assumption. apply step_star_app_one. exists s''. split; assumption.\n            apply in_app_iff. right. apply in_app_iff. right. apply in_app_iff. right. apply in_eq.\n            simpl in B. subst l'. subst l0. simpl in B. assumption.\n\n          split.\n          rewrite Nat.add_comm.\n          simpl.\n          subst n.\n          apply le_S.          \n          assumption.\n          intro.\n          rewrite Nat.add_comm.\n          simpl.\n          subst n.\n          apply Nat.lt_succ_r.\n          assumption.\n          (* -- *)\n          simpl_override.\n          split.\n          apply Nat.le_refl.\n          intros.\n          destruct H6.\n          exfalso.\n          apply n1.\n          symmetry; assumption.\n\n        (* get *)\n          simpl.\n          simpl_override.\n          simpl.\n          simpl_override.\n          simpl.\n          split.\n          destruct (eq_nat_dec (entry_node (store s0 k)) n).\n          simpl_override.\n          rewrite e0.\n          apply Nat.le_max_l.\n          simpl_override.\n          apply Nat.le_refl.\n          intros.\n          destruct H6.\n          contradiction.\n          \n        \n        (* update *)\n          simpl.\n          split.\n          simpl_override.\n          simpl.\n          simpl_override.\n          simpl.\n          apply Nat.le_max_l.\n          intro.\n          open_conjs.\n          contradiction.\n\n        \n        (* fault *)\n          simpl.\n          simpl_override.\n          simpl_override.\n          split.\n          apply Nat.le_refl.\n          intros.\n          open_conjs. contradiction.\n\n      destruct L as [N1 N2].\n      split.\n        (* -- *)\n        rewrite <- H3 in *; clear H3.\n        eapply Nat.le_trans; eassumption.\n        (* -- *)\n        clear N1.\n        intros.\n        depremise N2.\n        assumption.\n        clear H.\n          \n        eapply Nat.le_lt_trans; eassumption.\n      Qed.\n\n  Lemma proc_order_dep_rec:\n    forall (p: ICExec.Syntax.PProg)(h: list Label)(s: State)(l l': Label)(n: NId),\n      (step_star (init p) h s\n       /\\ prec h l l'\n       /\\ label_node l = label_node l'\n       /\\ In n nids)\n      -> (let c := dep (label_post_state l) n in\n          let c' := rec (label_post_state l') n in\n          c <= c'\n          /\\ ((label_node l' = n /\\ label_is_put l') -> c < c')).\n\n    Proof.\n      intros.\n      subst c.\n      subst c'.\n      open_conjs.\n\n      assert (A1 := proc_order_clock p h s l l' n).\n        depremise A1. split_all; assumption. simpl in A1.\n\n      open_conjs.\n      assert (L := prec_exec p h s l l').\n        depremise L. split; assumption.\n      destruct L as [h1 L].\n      destruct L as [s1' L].\n      destruct L as [s1 L].\n      destruct L as [h2 L].\n      destruct L as [s2' L].\n      destruct L as [s2 L].\n      destruct L as [h3 [L1 [L2 [L3 [L4 L5]]]]].\n\n      assert (A2 := dep_leq_rec p (h1 ++ l :: h2 ++ [l']) s2 (label_node l')).\n        simpl in A2. depremise A2.\n        apply step_star_app. exists s1'.\n        split. assumption. apply step_star_end. exists s1.\n        split. assumption. apply step_star_app_one. exists s2'.\n        split; assumption.\n        specialize (A2 n).\n        depremise A2. assumption.\n\n      assert (N2 := label_poststate_state s2' s2 l' L4).\n      rewrite <- N2 in A2; clear N2.\n\n      split.\n        eapply Nat.le_trans; eassumption.\n        intro. depremise H4. assumption. eapply Nat.lt_le_trans; eassumption.\n    Qed.\n\n\n  Lemma get_from_map:\n    forall (s s': State)(l: Label),\n      (label_is_get l\n       /\\ step s l s')\n      -> let k := label_key l in\n         let n' := label_orig_node l in\n         let c' := label_clock l in\n         let n := label_node l in\n         let m := store (alg_state ((node_states s) n)) in\n         let iv := m k in\n         let ivn := inst_val_nid (entry_val iv) in\n         let ivc := inst_val_clock (entry_val iv) in\n         (n' = ivn /\\ c' = ivc).\n\n    Proof.\n      intros.\n      open_conjs.\n      \n      inversion H0.\n\n      (* put *)\n        simpl in *.\n        rewrite <- H3 in H.\n        unfold label_is_get in H.\n        contradiction.\n\n      (* get *)\n        simpl in *.\n        subst n'.\n        subst c'.\n        subst ivn.\n        subst ivc.\n        rewrite <- H3.\n        simpl.\n        subst n'0.\n        subst c'0.\n        subst u.\n        subst iv.\n        subst m.\n        subst s.\n        subst k.\n        subst n.\n        rewrite <- H3.        \n        simpl.\n        simpl_override.\n        simpl.\n        split; reflexivity.\n\n      (* update *)\n        simpl in *.\n        rewrite <- H4 in H.\n        unfold label_is_get in H.\n        contradiction.\n\n      (* fault *)\n        simpl in *.\n        subv_in l H.\n        contradiction.\n\n    Qed.\n\n  Lemma put_change:\n    forall (s s': State)(l: Label),\n      let n := label_node l in\n      let c := label_clock l in\n      let k := label_key l in\n      let m' := store (alg_state (node_states s' n)) in\n      let iv := m' k in\n      (step s l s'\n       /\\ label_is_put l)\n      -> (inst_val_nid (entry_val iv) = n\n          /\\ inst_val_clock (entry_val iv) = c).\n\n    Proof.\n      intros.\n      destruct H as [H1 H2].\n      inversion H1.\n\n      clear H2.\n      subst iv.\n      subst m'.\n      subst s'.\n      simpl.\n      subst n.\n      subst c.\n      subst k.\n      subst l.\n      simpl.\n      simpl_override.\n      simpl.\n      simpl_override.\n      simpl.\n      split; reflexivity.\n\n      rewrite <- H3 in H2; unfold label_is_put in H2; inversion H2.\n      rewrite <- H4 in H2; unfold label_is_put in H2; inversion H2.\n      rewrite <- H3 in H2; unfold label_is_put in H2; inversion H2.\n\n    Qed.\n\n\n  Lemma update_change:\n    forall (s s': State)(l: Label),\n      let n' := label_orig_node l in\n      let c' := label_clock l in\n      let n := label_node l in\n      let k := label_key l in\n      let m' := store (alg_state (node_states s' n)) in\n      let iv := m' k in\n      (step s l s'\n       /\\ label_is_update l)\n      -> (inst_val_nid (entry_val iv) = n'\n          /\\ inst_val_clock (entry_val iv) = c').\n\n    Proof.\n      intros.\n      destruct H as [H1 H2].\n      inversion H1.\n\n      rewrite <- H3 in H2; unfold label_is_update in H2; inversion H2.\n      rewrite <- H3 in H2; unfold label_is_get in H2; inversion H2.\n\n      clear H2.\n      subst iv.\n      subst m'.\n      subst s'.\n      simpl.\n      subst n'.\n      subst c'.\n      subst k.\n      subst n.\n      subst l.\n      simpl.\n      simpl_override.\n      simpl.\n      simpl_override.\n      simpl.\n      split; reflexivity.\n\n      rewrite <- H3 in H2; unfold label_is_update in H2; inversion H2.\n      \n    Qed.\n\n\n\n  Lemma put_nochange:\n    forall (s s': State)(l: Label),\n      let n := label_node l in\n      let k := label_key l in\n      let m := store (alg_state (node_states s n)) in\n      let m' := store (alg_state (node_states s' n)) in\n      (step s l s'\n       /\\ label_is_put l)\n      -> (forall k', \n            (not (k = k'))\n            -> m k' = m' k').\n\n    Proof.\n      intros.\n      open_conjs.\n\n      inversion H.\n      subst m.\n      subst m'.\n      subst s.\n      subst s'.\n      simpl.\n      unfold override.\n      destruct (eq_nat_dec n n0).\n        simpl.        \n        subst k.\n        rewrite <- H4 in H0. simpl in H0.\n        simpl_override.\n        reflexivity.\n      reflexivity.\n\n      rewrite <- H4 in H1; unfold label_is_put in H1; inversion H1.\n      rewrite <- H5 in H1; unfold label_is_put in H1; inversion H1.\n      rewrite <- H4 in H1; unfold label_is_put in H1; inversion H1.\n      \n    Qed.\n\n  Lemma get_nochange:\n    forall (s s': State)(l: Label)(n: NId),\n      let m := store (alg_state (node_states s n)) in\n      let m' := store (alg_state (node_states s' n)) in\n      (step s l s'\n       /\\ label_is_get l)\n      -> m = m'.\n\n    Proof.\n      intros.\n      open_conjs.\n      inversion H.\n\n      rewrite <- H3 in H0; unfold label_is_put in H0; inversion H0.\n\n      subst m.\n      subst m'.\n      subst s.\n      subst s'.\n      simpl.\n      unfold override.\n      destruct (eq_nat_dec n n0).\n        simpl. reflexivity.\n        reflexivity.\n\n      rewrite <- H4 in H0; unfold label_is_put in H0; inversion H0.\n      rewrite <- H3 in H0; unfold label_is_put in H0; inversion H0.\n      \n    Qed.\n\n  Lemma update_nochange:\n    forall (s s': State)(l: Label),\n      let n := label_node l in\n      let k := label_key l in\n      let m := store (alg_state (node_states s n)) in\n      let m' := store (alg_state (node_states s' n)) in\n      (step s l s'\n       /\\ label_is_update l)\n      -> (forall k', \n            (not (k = k'))\n            -> m k' = m' k').\n\n    Proof.\n      intros.\n      open_conjs.\n      inversion H.\n\n      rewrite <- H4 in H1; unfold label_is_put in H1; inversion H1.\n      rewrite <- H4 in H1; unfold label_is_put in H1; inversion H1.\n\n      subst m.\n      subst m'.\n      subst s.\n      subst s'.\n      simpl.\n      unfold override.\n      destruct (eq_nat_dec n n0).\n        simpl.\n        subst k. rewrite <- H5 in H0. simpl in H0.\n        simpl_override.\n        reflexivity.\n      reflexivity.      \n\n      rewrite <- H4 in H1; unfold label_is_put in H1; inversion H1.\n\n    Qed.\n\n  Lemma node_nochange:\n    forall (s s': State)(l: Label)(n': NId),\n      let n := label_node l in\n      let m := store (alg_state (node_states s n')) in\n      let m' := store (alg_state (node_states s' n')) in\n      (step s l s'\n      /\\ not (n = n'))\n      -> m = m'.\n\n    Proof.\n      intros.\n      open_conjs.\n\n      inversion H;\n\n      subst m;\n      subst m';\n      subst s;\n      subst s';\n      simpl;\n      subst n;\n      subst l;\n      simpl in *;\n      simpl_override;\n      simpl_override;\n      reflexivity.\n    Qed.\n\n  Lemma in_map_from_put_update:\n    forall (p: ICExec.Syntax.PProg)(h: list Label)(s: State)(k: Key)(n: NId),\n      step_star (init p) h s\n      -> let m := store (alg_state ((node_states s) n)) in\n         let iv := m k in\n         let ivn := inst_val_nid (entry_val iv) in\n         let ivc := inst_val_clock (entry_val iv) in\n         (ivn = init_nid /\\ ivc = 0)\n         \\/ (exists (l: Label),\n               (In l h\n                /\\ label_is_put l\n                /\\ label_node l = ivn\n                /\\ label_clock l = ivc\n                /\\ label_node l = n)\n               \\/ (In l h\n                   /\\ label_is_update l\n                   /\\ label_orig_node l = ivn\n                   /\\ label_clock l = ivc\n                   /\\ label_node l = n)).\n\n    Proof.\n      intros.\n      remember (init p) as s0 eqn: H1.\n      induction H.\n\n      left.\n      subst ivn. subst ivc.\n      subst iv.\n      subst m.\n      subst s.\n      unfold init.\n      simpl. split; reflexivity.\n\n      depremise IHstep_star. assumption.\n      pose (n' := label_node l).\n      destruct (eq_nat_dec n n') eqn: N.\n      subst n'.\n      \n      (* The same node *)\n      assert (E := H0).\n      inversion H0.\n      \n      (* put *)\n        destruct (eq_nat_dec k k0) eqn: K.\n\n          clear IHstep_star.\n          right.\n          exists l.\n          left.\n          split.\n            (* --- *)\n            subst l.\n            apply in_or_app.\n            right.\n            unfold In.\n            left. reflexivity.\n            (* --- *)\n            split.\n            subst l.\n            unfold label_is_put. apply I.\n            rewrite <- H4.\n            simpl.\n            assert (L := put_change s2 s3 l). \n            simpl in L. depremise L.\n            split. assumption. rewrite <- H4. simpl. apply I.\n            rewrite <- H4 in L.\n            simpl in L.\n            open_conjs.\n            subst ivn. subst ivc. subst iv. subst m. subst k. subst n.  subst l.\n            simpl. split_all.\n            symmetry; assumption.\n            symmetry; assumption.\n            reflexivity.\n\n          clear H2 H5.\n          assert (L := put_nochange s2 s3 l).\n          simpl in L. depremise L. split. assumption. subst l. simpl. apply I.\n          rewrite <- H4 in L. simpl in L.\n          specialize (L k). depremise L. apply not_eq_sym. assumption.\n          simpl in IHstep_star. rewrite e in IHstep_star. rewrite <- H4 in IHstep_star. simpl in IHstep_star.\n          rewrite L in *; clear L.\n          destruct IHstep_star. \n          (* --- *)\n            left.\n            subst ivn.\n            subst ivc.\n            subst iv.\n            subst m.\n            subst n.\n            subst l.\n            simpl.\n            assumption.\n            right.\n            destruct H2 as [l' H2].\n            destruct H2; open_conjs; exists l'.\n            left.\n            split_all.\n            apply in_or_app. left. assumption.\n            assumption.\n            subst ivn. subst iv. subst m. subst n. subst l. simpl. assumption.\n            subst ivc. subst iv. subst m. subst n. subst l. simpl. assumption.\n            rewrite e. rewrite <- H4. simpl. assumption.\n            right.\n            split_all.\n            apply in_or_app. left. assumption.\n            assumption.\n            subst ivn. subst iv. subst m. subst n. subst l. simpl. assumption.\n            subst ivc. subst iv. subst m. subst n. subst l. simpl. assumption.\n            rewrite e. rewrite <- H4. simpl. assumption.\n\n      (* get *)\n        assert (L := get_nochange s2 s3 l n).\n        simpl in L. depremise L.\n        split. assumption. subst l. unfold label_is_get. apply I.\n        rewrite L in *.\n        destruct IHstep_star.\n        (* --- *)\n          left. subst ivn. subst ivc. subst iv. subst m. assumption.\n        (* --- *)\n          right.\n          destruct H6 as [l' H6].\n          exists l'.\n          destruct H6; open_conjs.\n          left. \n            split. apply in_or_app. left. assumption.\n            split. assumption. subst ivn. subst  ivc. subst iv. subst m. split_all; assumption.\n          right.\n            split. apply in_or_app. left. assumption.\n            split. assumption. subst ivn. subst  ivc. subst iv. subst m. \n            split_all; assumption.\n\n      (* update *)\n        clear N.\n        rewrite <- H5 in e. simpl in e.\n        destruct (eq_nat_dec k k0) eqn: K.\n\n          clear IHstep_star.\n          right.\n          exists l.\n          right.\n          split.\n            (* --- *)\n            subst l.\n            apply in_or_app.\n            right.\n            unfold In.\n            left. reflexivity.\n            (* --- *)\n            split.\n            subst l.\n            unfold label_is_update. apply I.\n            rewrite <- H5.\n            simpl.\n            assert (L := update_change s2 s3 l). \n            simpl in L. depremise L.\n            split. assumption. rewrite <- H5. simpl. apply I.\n            rewrite <- H5 in L.\n            simpl in L.\n            open_conjs.\n            subst ivn. subst ivc. subst iv. subst m. subst k. subst n.  subst l.\n            simpl. split_all; try reflexivity; symmetry; assumption.\n\n          clear H2 H3 H6.\n          assert (L := update_nochange s2 s3 l).\n          simpl in L. depremise L. split. assumption. subst l. simpl. apply I.\n          rewrite <- H5 in L. simpl in L.\n          specialize (L k). depremise L. apply not_eq_sym. assumption.\n          simpl in IHstep_star. rewrite e in IHstep_star. (* rewrite <- H4 in IHstep_star. *) simpl in IHstep_star.\n          rewrite L in *; clear L.\n          destruct IHstep_star. \n          (* --- *)\n            left.\n            subst ivn.\n            subst ivc.\n            subst iv.\n            subst m.\n            subst n.\n            subst l.\n            simpl.\n            assumption.\n            right.\n            destruct H2 as [l' H2].\n            destruct H2; open_conjs; exists l'.\n            left.\n            split_all.\n            apply in_or_app. left. assumption.\n            assumption.\n            subst ivn. subst iv. subst m. subst n. subst l. simpl. assumption.\n            subst ivc. subst iv. subst m. subst n. subst l. simpl. assumption.\n            rewrite e. assumption.\n\n            right.\n            split_all.\n            apply in_or_app. left. assumption.\n            assumption.\n            subst ivn. subst iv. subst m. subst n. subst l. simpl. assumption.\n            subst ivc. subst iv. subst m. subst n. subst l. simpl. assumption.\n            rewrite e. assumption.\n\n\n      (* fault *)\n        subst ivn. subst  ivc. subst iv. subst m.\n        subv s3.\n        subv_in s2 IHstep_star.\n        destruct (eq_nat_dec n0 n).\n        \n          (* --- *)\n          subst n0.\n          simpl_override.\n          simpl_override_in IHstep_star.\n\n          destruct IHstep_star.\n          (* --- *)\n          left. assumption.\n          (* --- *)\n          right.\n          destruct H6 as [l' H6].\n          exists l'.\n          destruct H6; open_conjs.\n          left. \n            split. apply in_or_app. left. assumption.\n            split. assumption. split_all; assumption.\n          right.\n            split. apply in_or_app. left. assumption.\n            split. assumption. split_all; assumption.\n\n          (* --- *)\n          simpl_override.\n          simpl_override_in IHstep_star.\n\n          destruct IHstep_star.\n          (* --- *)\n          left. assumption.\n          (* --- *)\n          right.\n          destruct H6 as [l' H6].\n          exists l'.\n          destruct H6; open_conjs.\n          left. \n            split. apply in_or_app. left. assumption.\n            split. assumption. split_all; assumption.\n          right.\n            split. apply in_or_app. left. assumption.\n            split. assumption. split_all; assumption.\n\n\n      (* A different node *)     \n      assert (L := node_nochange s2 s3 l n). \n      simpl in L; depremise L. split. assumption. subst n'. apply not_eq_sym. assumption.\n      rewrite L in *. clear L.\n      destruct IHstep_star.\n      left. subst ivn. subst ivc. subst iv. subst m. assumption.\n      right. destruct H2 as [l' H2]. exists l'.\n      destruct H2; open_conjs.\n      left. split_all.\n      apply in_or_app. left. assumption.\n      assumption.\n      subst ivn. subst iv. subst m. assumption.\n      subst ivc. subst iv. subst m. assumption.\n      assumption.\n      right. split_all.\n      apply in_or_app. left. assumption.\n      assumption.\n      subst ivn. subst iv. subst m. assumption.\n      subst ivc. subst iv. subst m. assumption.\n      assumption.\n\n    Qed.\n\n\n  Lemma sem_clock_alg_state_clock:\n    forall p h s,\n      step_star (init p) h s\n      -> forall n,\n           let sc := clock_state (node_states s n) in\n           let ac := rec (alg_state (node_states s n)) n in\n           sc = ac.           \n    \n    Proof.\n      intros.\n      remember (init p) as s0 eqn: Hi.\n      induction H.\n\n      subst sc.\n      subst ac.\n      subst s.\n      simpl.\n      reflexivity.\n\n      \n      depremise IHstep_star.\n      assumption.\n      simpl in IHstep_star.\n      subst sc.\n      subst ac.\n      inversion H0.\n      \n      simpl.\n      destruct (eq_nat_dec n n0).\n        subst n.\n        simpl_override.\n        simpl.\n        simpl_override.\n        rewrite <- H2 in IHstep_star.\n        simpl in IHstep_star.\n        simpl_override_in IHstep_star.\n        simpl in IHstep_star.\n        rewrite IHstep_star.      \n        reflexivity.\n\n        simpl_override.\n        rewrite <- H2 in IHstep_star.\n        simpl in IHstep_star.\n        simpl_override_in IHstep_star.        \n        assumption.\n\n\n      simpl.\n      destruct (eq_nat_dec n n0).\n        subst n.\n        simpl_override.\n        simpl.\n        rewrite <- H2 in IHstep_star.\n        simpl in IHstep_star.\n        simpl_override_in IHstep_star.\n        simpl in IHstep_star.\n        assumption.\n\n        simpl_override.\n        rewrite <- H2 in IHstep_star.\n        simpl in IHstep_star.\n        simpl_override_in IHstep_star.\n        assumption.\n\n      simpl.\n      destruct (eq_nat_dec n n0).\n        subst n.\n        simpl_override.\n        simpl.\n        rewrite <- H3 in IHstep_star.\n        simpl in IHstep_star.\n        simpl_override_in IHstep_star.\n        simpl in IHstep_star.\n\n        assert (L := update_no_self_message p ls s2 (message n' c' k v u n0 lp)). \n          depremise L.\n          split_all.\n          subst s1.\n          assumption.\n          rewrite <- H3.\n          simpl.\n          apply in_app_iff.\n          right.\n          apply in_eq.\n        simpl in L.\n        simpl_override.\n        assumption.\n\n        simpl_override.\n        rewrite <- H3 in IHstep_star.\n        simpl in IHstep_star.\n        simpl_override_in IHstep_star.\n        assumption.\n\n      simpl.\n      subv_in s2 IHstep_star.\n      destruct (eq_nat_dec n n0).\n        subst n.\n        simpl_override.\n        simpl_override_in IHstep_star.\n        assumption.\n\n        simpl_override.\n        simpl_override_in IHstep_star.\n        assumption.\n\n    Qed.\n\n  Lemma update_dep_eq_msg_clock:\n    forall p h s m,\n      step_star (init p) h s\n      /\\ In m (messages s)\n      -> sender_dep (msg_update m) (sender_node (msg_update m))= msg_clock m.\n\n    Proof.\n      intros.\n      open_conjs.\n      remember (init p) as s0 eqn: Hi.\n      induction H.\n\n      subst s.\n      simpl in H0.\n      contradiction.\n\n      depremise IHstep_star.\n      assumption.\n      inversion H1.\n\n      rewrite <- H5 in H0.\n      simpl in H0.\n      apply in_app_iff in H0.\n      destruct H0 as [H0 | H0].\n      \n      depremise IHstep_star.\n      rewrite <- H3.\n      simpl.\n      assumption.\n      assumption.\n      \n      apply in_map_iff in H0.\n      destruct H0 as [n' [N1 N2]].\n      subst m.\n      simpl in *.\n      simpl_override.\n      assert (A := sem_clock_alg_state_clock).\n      specex_deprem A. subst s1. eassumption.\n      specialize (A n). simpl in A. subv_in s2 A. simpl_override_in A.\n      rewrite A.\n      reflexivity.\n\n      rewrite <- H3 in IHstep_star.\n      simpl in IHstep_star.\n      depremise IHstep_star.\n      rewrite <- H5 in H0.\n      assumption.\n      assumption.\n\n      rewrite <- H4 in IHstep_star.\n      simpl in IHstep_star.\n      depremise IHstep_star.\n      rewrite <- H6 in H0.\n      simpl in H0.\n      apply in_app_iff in H0.\n      destruct H0 as [H0 | H0].\n      apply in_app_iff.\n      left. assumption.\n      apply in_app_iff.\n      right. apply in_cons. assumption.\n      assumption.\n\n      depremise IHstep_star.\n      subv s2.\n      subv_in s3 H0.\n      assumption.\n      assumption.\n\n    Qed.\n\n\n  Lemma msg_update_label:\n    forall p h s m,\n      step_star (init p) h s\n      /\\ In m (messages s)\n      -> (let lp := msg_label m in\n          let u := msg_update m in\n          label_is_put lp\n          /\\ sender_node u = label_node lp\n          /\\ sender_dep u = dep (label_post_state lp)\n          /\\ sender_dep u (sender_node u) = label_clock lp).\n\n    Proof.\n      intros.\n      remember (init p) as s0 eqn: Hs.\n      open_conjs.\n      induction H.\n\n      subst s.\n      simpl in H0.\n      contradiction.\n\n      depremise IHstep_star. assumption.\n      inversion H1.\n\n      subst l0.\n      subst u.\n      simpl.\n      rewrite <- H5 in H0.\n      simpl in H0.\n      apply in_app_iff in H0.\n      destruct H0.\n      depremise IHstep_star.\n      rewrite <- H3.\n      simpl.\n      assumption.\n      assumption.\n      apply in_map_iff in H0.\n      destruct H0 as [n' [N1 N2]].\n      rewrite <- N1.\n      simpl.\n      subst lp.\n      rewrite <- N1.\n      simpl.\n      split.\n      reflexivity.\n      simpl_override.\n      assert (A:= sem_clock_alg_state_clock p ls s2).\n        depremise A.\n        subst s1. assumption.\n        specialize (A n).\n        simpl in A.\n        rewrite <- H3 in A.\n        simpl in A.\n        simpl_override_in A.\n        simpl in A.\n      rewrite A.\n      split_all; reflexivity.\n\n      subst u.\n      rewrite <- H5 in H0.\n      simpl in H0.\n      depremise IHstep_star.\n      rewrite <- H3.\n      simpl.\n      assumption.\n      assumption.\n\n      subst u.\n      rewrite <- H6 in H0.\n      simpl in H0.\n      apply in_app_iff in H0.\n      destruct H0 as [H0 | H0].\n      depremise IHstep_star.\n      rewrite <- H4.\n      simpl.\n      apply in_app_iff.\n      left.\n      assumption.\n      assumption.\n      depremise IHstep_star.\n      rewrite <- H4.\n      simpl.\n      apply in_app_iff.\n      right.\n      apply in_cons.\n      assumption.\n      assumption.\n\n      depremise IHstep_star.\n      subv s2.\n      subv_in s3 H0.\n      assumption.\n      assumption.\n\n    Qed.\n\n\n  Lemma label_clock_label_post_state_clock:\n    forall p h s l s',\n      (step_star (init p) h s\n       /\\ step s l s'\n       /\\ label_is_put l)\n      -> (let n := label_node l in\n          let lc := label_clock l in\n          let ls := (label_post_state l) in\n          let sc := dep ls n in\n          lc = sc).\n    \n    Proof.\n      intros.\n      destruct H as [H1 [H2 H3]].\n\n      assert (L := sem_clock_alg_state_clock p h s H1 n).\n      simpl in L.\n      inversion H2.\n\n      subst lc. rewrite <- H4.\n      simpl.\n      subst sc.\n      subst n.\n      subst ls.\n      rewrite <- H4.\n      simpl.\n      simpl_override.\n      \n      rewrite <- H4 in L.\n      simpl in L.\n      rewrite <- H0 in L.\n      simpl in L.\n      simpl_override_in L.      \n      simpl in L.      \n      rewrite <- L.\n      reflexivity.\n\n      rewrite <- H4 in H3. simpl in H3. contradiction.\n      rewrite <- H5 in H3. simpl in H3. contradiction.\n      rewrite <- H4 in H3. simpl in H3. contradiction.\n\n    Qed.\n\n\n  Lemma label_clock_alg_state_clock:\n    forall p h s l s',\n      (step_star (init p) h s\n       /\\ step s l s'\n       /\\ label_is_put l)\n      -> (let n := label_node l in\n          let lc := label_clock l in\n          let ac := dep (alg_state (node_states s' n)) n in\n          lc = ac).\n\n    Proof.\n      intros.\n      destruct H as [H1 [H2 H3]].\n\n      assert (L := sem_clock_alg_state_clock p h s H1 n).\n      inversion H2.\n\n      subst lc. rewrite <- H4.\n      simpl.\n      subst ac.\n      simpl in L.\n      rewrite <- H0 in L.\n      simpl in L.\n      subst n.\n      rewrite <- H4 in L.\n      rewrite <- H4.\n      simpl in *.\n      simpl_override_in L.\n      rewrite <- H5.\n      simpl.\n      simpl in L.      \n      simpl_override.\n      subst s'0.\n      simpl in *.\n      simpl_override.\n      rewrite L.\n      reflexivity.\n\n      rewrite <- H4 in H3. simpl in H3. contradiction.\n      rewrite <- H5 in H3. simpl in H3. contradiction.      \n      rewrite <- H4 in H3. simpl in H3. contradiction.\n\n    Qed.\n\n\n  Lemma label_clock_leq_alg_state_clock:\n    forall p h1 s l s' h2 s'',\n      (step_star (init p) h1 s\n       /\\ step s l s'\n       /\\ label_is_put l\n       /\\ step_star s' h2 s'')\n      -> (let n := label_node l in\n          let lc := label_clock l in\n          let c'' := dep (alg_state (node_states s'' n)) n in\n          lc <= c'').\n\n    Proof.\n      intros.\n      open_conjs.\n\n      assert (L := label_clock_alg_state_clock p h1 s l s').\n      depremise L.\n      split_all.\n      assumption.\n      assumption.\n      assumption.\n            \n      assert (M := step_star_clock_nondec p (h1++[l]) h2 s' s'' n).\n        simpl in M.\n        depremise M.\n        split. apply step_star_app_one. exists s. split; assumption.\n        assumption.\n        specialize (M n).\n\n      subst lc.\n      subst c''.\n      simpl in L.\n      simpl in M.\n\n      subst n.\n      rewrite L.\n      assumption.\n    Qed.\n\n  Lemma label_clock_leq_alg_state_rec:\n    forall p h1 s l s' h2 s'',\n      (step_star (init p) h1 s\n       /\\ step s l s'\n       /\\ label_is_put l\n       /\\ step_star s' h2 s'')\n      -> (let n := label_node l in\n          let lc := label_clock l in\n          let c'' := rec (alg_state (node_states s'' n)) n in\n          lc <= c'').\n\n    Proof.\n      intros.\n      open_conjs.\n\n      subst lc.\n      subst c''.\n      subst n.\n\n      assert (A1 := label_clock_leq_alg_state_clock p h1 s l s' h2 s'').\n        depremise A1. split_all; assumption.\n        simpl in A1.\n\n      assert (A2 := dep_leq_rec p (h1++l::h2) s'' (label_node l)).\n        simpl in A2. depremise A2. apply step_star_app. exists s. split. assumption. apply step_star_end. exists s'. split; assumption.\n        specialize (A2 (label_node l)). depremise A2.\n        assert (B1 := label_node_in_nids p (h1++[l]) s' l). depremise B1. split. apply step_star_app_one. exists s. split; assumption.\n        apply in_app_iff. right. apply in_eq. simpl in B1. assumption.\n        \n      eapply Nat.le_trans; eassumption.\n\n    Qed.\n    \n\n  Lemma update_clock:\n    forall s s' l,\n    (step s l s'\n     /\\ label_is_update l)\n    -> let n' := label_orig_node l in\n       let c' := label_clock l in\n       let n := label_node l in\n       let ls := label_post_state l in\n       let co := dep ls in\n       let ms := messages s in\n       exists m,\n         let mn' := msg_sender m in\n         let mc' := msg_clock m in\n         let mn := msg_receiver m in\n         let u := msg_update m in\n         let mco := sender_dep u in\n         In m ms\n         /\\ n' = mn'\n         /\\ c' = mc'\n         /\\ n = mn\n         /\\ forall n'', In n'' nids -> mco n'' <= co n''.\n\n    Proof.\n      intros.\n      open_conjs.\n      inversion H.\n\n      rewrite <- H3 in H0. unfold label_is_update in H0. contradiction.\n      rewrite <- H3 in H0. unfold label_is_update in H0. contradiction.\n\n      exists (message n'0 c'0 k v u n0 lp).\n      simpl.\n      split_all.\n\n      subst ms.\n      subst s.\n      simpl.\n      apply in_app_iff.\n      right.\n      apply in_eq.\n\n      subst n'.\n      rewrite <- H4. \n      simpl.\n      reflexivity.\n\n      subst c'.\n      rewrite <- H4. \n      simpl.\n      reflexivity.\n\n      subst n.\n      rewrite <- H4. \n      simpl.\n      reflexivity.\n\n      intros.\n      subst co.\n      subst ls.\n      rewrite <- H4.\n      simpl in *.\n      apply Nat.le_max_r.\n\n      rewrite <- H3 in H0. unfold label_is_update in H0. contradiction.\n\n    Qed.\n\n  Lemma message_pre_put:\n    forall p h s m,\n      let ms := messages s in\n      (step_star (init p) h s\n       /\\ In m ms)\n      -> let mn := msg_sender m in\n         let mc := msg_clock m in\n         let u := msg_update m in\n         let mco := sender_dep u in\n         exists l,\n           let n := label_node l in\n           let c := label_clock l in\n           let ls := label_post_state l in\n           let co := dep ls in\n           In l h\n           /\\ label_is_put l\n           /\\ mn = n\n           /\\ mc = c\n           /\\ mco = co.\n\n    Proof.\n      intros.\n      open_conjs.\n      remember (init p) as p0 eqn: Hp.\n      induction H.\n\n      subst ms. subst s.\n      unfold init in H0.\n      simpl in H0.\n      contradiction.\n\n      simpl in IHstep_star. depremise IHstep_star. assumption.\n      inversion H1.\n\n      (* put *)\n        subst ms. rewrite <- H5 in H0.\n        simpl in H0.\n        apply in_app_iff in H0.\n        destruct H0.\n          \n          (* IH *)\n            depremise IHstep_star.\n            rewrite <- H3.\n            simpl.\n            assumption.\n            destruct IHstep_star as [l' [L1 [L2 [L3 [L4 L5]]]]].\n            \n            exists l'.\n            simpl.\n            split_all.\n            apply in_app_iff.\n            left.\n            assumption.\n            assumption.\n            assumption.\n            assumption.\n            assumption.\n\n          (* This step *)\n            apply in_map_iff in H0.\n            destruct H0 as [n' H0].\n            open_conjs.\n\n            exists l.\n            simpl.\n            split_all.\n            apply in_app_iff.\n            right.\n            subst l.\n            apply in_eq.\n\n            subst l.\n            unfold label_is_put.\n            apply I.\n\n            subst mn.\n            rewrite <- H4.\n            rewrite <- H0.\n            simpl.\n            reflexivity.\n\n            subst mc.\n            rewrite <- H4.\n            rewrite <- H0.\n            simpl.\n            reflexivity.\n\n            subst mco.\n            rewrite <- H4.\n            simpl.\n            apply functional_extensionality.\n            intro n''.\n\n            unfold override.\n            destruct (eq_nat_dec n'' n).\n            subst n''.\n            subst u.\n            rewrite <- H0.            \n            simpl.\n            simpl_override.\n            reflexivity.\n            subst u. rewrite <- H0. simpl.\n            simpl_override.\n            reflexivity.\n\n      (* get *)\n        depremise IHstep_star.\n        rewrite <- H3.\n        simpl.\n        subst ms.\n        rewrite <- H5 in H0.\n        simpl in H0.\n        assumption.\n        destruct IHstep_star as [l' [L1 [L2 [L3 [L4 L5]]]]].\n\n        exists l'.\n        simpl; split_all.\n        apply in_app_iff.\n        left. assumption.\n        assumption.\n        assumption.\n        assumption.\n        assumption.\n\n      (* update *)\n        depremise IHstep_star.\n        rewrite <- H4.\n        simpl.\n        subst ms.\n        rewrite <- H6 in H0.\n        simpl in H0.\n        apply in_app_iff in H0.\n        destruct H0.\n        apply in_app_iff.\n        left. assumption.\n        apply in_app_iff.\n        right.\n        apply in_cons.\n        assumption.\n        destruct IHstep_star as [l' [L1 [L2 [L3 [L4 L5]]]]].\n\n        exists l'.\n        simpl; split_all.\n        apply in_app_iff.\n        left. assumption.\n        assumption.\n        assumption.\n        assumption.\n        assumption.\n\n      (* get *)\n        depremise IHstep_star.\n        subv s2.\n        subv_in ms H0.\n        subv_in s3 H0.\n        assumption.\n        destruct IHstep_star as [l' [L1 [L2 [L3 [L4 L5]]]]].\n        exists l'.\n        simpl; split_all.\n        apply in_app_iff.\n        left. assumption.\n        assumption.\n        assumption.\n        assumption.\n        assumption.\n\n    Qed.\n\n\n\n\n  Lemma reads_from_clock:\n    forall (p: ICExec.Syntax.PProg)(h: list Label)(s: State)(l l': Label)(n: NId),\n      (step_star (init p) h s\n       /\\ prec h l l'\n       /\\ label_is_put l /\\ label_is_get l'\n       /\\ label_node l = label_orig_node l'\n       /\\ label_clock l = label_clock l'\n       /\\ In n nids)\n      -> (let c := dep (label_post_state l) n in\n          let c' := dep (label_post_state l') n in\n          c <= c').\n\n      Proof.\n        intros p h s l l' n.\n        intros.\n        destruct H as [H [H0 [H2 [H3 [H4 [H5 Hi]]]]]].\n        apply prec_in in H0.\n        destruct H0 as [H0 H1].\n\n        assert (L := in_exec h (init p) s l' (conj H H1)).\n        destruct L as [h1 [s1 [s2 [h2 L]]]].\n        open_conjs.\n\n        assert (L := get_from_map s1 s2 l' (conj H3 H8)). (* simpl in L. *)\n\n        pose (k := label_key l').\n        pose (n' := label_node l').\n        assert (M := in_map_from_put_update p h1 s1 k n' H7).\n        destruct M as [M | M].\n\n          (* Reads the initial value. *)\n            simpl in L.\n            subst k. remember (label_key l') as k eqn: Hk .\n            subst n'. remember (label_node l') as n' eqn: Hn.\n            open_conjs.\n            clear H12 H10.\n            rewrite H11 in H13.\n            clear H11.\n            rewrite <- H5 in H13.\n            assert (L := put_clock_gtz p h s l). \n            depremise L.\n            split_all; assumption.\n            rewrite H13 in L. inversion L.\n\n          (* --- *)\n          destruct M as [lw [M | M]]; open_conjs.\n          \n          (* There is a put. *)\n          simpl in L.\n          open_conjs.\n          subst k. remember (label_key l') as k eqn: Hk.\n          subst n'. remember (label_node l') as n' eqn: Hn.\n          remember (alg_state (node_states s1 n')) as as1 eqn: A.\n          rewrite <- H12 in *. clear H12.\n          rewrite <- H13 in *. clear H13.\n          rewrite <- H4 in *. (* clear H4. *)\n          rewrite <- H5 in *. (* clear H5. *)\n          assert (L := put_unique p h s l lw).\n          depremise L.\n          split_all. assumption. assumption.\n          rewrite H6. apply in_app_iff. left. assumption.\n          assumption. assumption. assumption. \n          assumption.\n          subst lw.\n          clear H11 H15 H16.\n          subst c. subst c'.\n          apply in_split in H10.\n          destruct H10 as [h11 [h12 H10]].\n          assert (Hs := H7).\n          rewrite H10 in H7.\n          apply step_star_app in H7.\n          destruct H7 as [s0 [H71 H72]].\n          apply step_star_end in H72.\n          destruct H72 as [s0' [H72 H73]].\n\n          assert (N1 := label_poststate_state s0 s0' l H72).\n          assert (N2 := label_poststate_state s1 s2 l' H8).\n          rewrite N1; clear N1.\n          rewrite N2; clear N2.\n\n          rewrite H14 in *; rewrite <- Hn in *.\n\n          assert (L := step_star_clock_nondec p (h11 ++ [l]) (h12 ++ [l']) s0' s2 n').\n            simpl in L.\n            depremise L. split. \n            apply step_star_app. exists s0. split. assumption. apply step_star_one. assumption.\n            apply step_star_app_one.\n            exists s1. split; assumption.\n            specialize (L n).\n          assumption.\n\n          (* There is an update. *)\n          simpl in L.\n          open_conjs.\n          subst k. remember (label_key l') as k eqn: Hk.\n          subst n'. remember (label_node l') as n' eqn: Hn.\n          remember (alg_state (node_states s1 n)) as as1 eqn: A.\n          rewrite <- H12 in *. clear H12.\n          rewrite <- H13 in *. clear H13.\n\n          assert (L := in_exec h1 (init p) s1 lw (conj H7 H10)).\n          destruct L as [h2' [s2' [s3' [h3' [L1 [L2 [L3 L4]]]]]]].\n\n          assert (M := update_clock s2' s3' lw (conj L3 H11)).\n          simpl in M.\n          destruct M as [m [M1 [M2 [M3 [M4 M5]]]]].\n\n          assert (N := message_pre_put p h2' s2' m). \n          simpl in N. depremise N. split; assumption.\n          destruct N as [lp [N1 [N2 [N3 [N4 N5]]]]].\n          \n          assert (P := put_unique p h s l lp).\n          depremise P.\n          split_all.\n          assumption.\n          assumption.\n          rewrite H6. apply in_app_iff. left. rewrite L1. apply in_app_iff. left. assumption.\n          assumption.          \n          assumption.\n          rewrite H4. rewrite H15. rewrite M2. rewrite N3. reflexivity.\n          rewrite H5. rewrite H16. rewrite M3. rewrite N4. reflexivity.\n          rewrite <- P in *.\n          subst c. subst c'.\n\n          specialize (M5 n). depremise M5. assumption.\n\n          assert (E: dep (label_post_state lw) n <= dep (label_post_state l') n).\n            assert (R := label_poststate_state s2' s3' lw L3); rewrite R; clear R.\n            assert (R := label_poststate_state s1 s2 l' H8); rewrite R; clear R.\n            rewrite H14. rewrite <- Hn.\n            eapply step_star_clock_nondec.\n              split.\n              econstructor. apply L2. apply L3. econstructor; eassumption.          \n\n          rewrite <- N5.\n\n          eapply Nat.le_trans;  eassumption.\n\n    Qed.\n\n\n  \n  Lemma cause_step_clock:\n    forall (p: ICExec.Syntax.PProg)(h: list Label)(s: State)(l l': Label)(n: NId),\n      (step_star (init p) h s\n      /\\ cause_step h l l'\n      /\\ In n nids)\n      -> (let c := dep (label_post_state l) n in\n          let c' := dep (label_post_state l') n in\n          c <= c'\n          /\\ ((label_node l' = n /\\ label_is_put l') -> c < c')).\n\n    Proof.\n      intros.\n      destruct H as [H' [H1 H2]].\n      inversion H1; clear H1.\n\n      (* Case: Process order *)\n        open_conjs.\n        apply proc_order_clock with (p := p)(h := h)(s := s).\n        split_all; assumption.\n\n      (* Case: Reads from *)\n        open_conjs.\n        split.\n          (* -- *)\n          apply reads_from_clock with (p := p)(h := h)(s := s).        \n          split_all; assumption.\n          (* -- *)\n          intros.\n          open_conjs.\n          destruct l';\n          simpl in *; contradiction.\n    Qed.\n\n\n  Lemma cause_clock:\n    forall (p: ICExec.Syntax.PProg)(h: list Label)(s: State)(l l': Label)(n: NId),\n      (step_star (init p) h s\n      /\\ cause h l l'\n      /\\ In n nids)\n      -> (let c := dep (label_post_state l) n in\n          let c' := dep (label_post_state l') n in\n          c <= c'\n          /\\ ((label_node l' = n /\\ label_is_put l') -> c < c')).\n\n  Proof.\n    intros.\n    destruct H as [H' [H1 H2]].\n    induction H1.\n\n    eapply cause_step_clock.\n    split_all; eassumption.\n\n    rename c' into c''.\n    pose (c' := dep (label_post_state l') n).\n    assert (c <= c').\n    apply IHcause.\n    assumption.\n    split.\n      (* -- *)\n      assert (c' <= c'').\n      apply cause_step_clock with (p := p)(h := h)(s := s).\n      split_all; assumption. \n      eapply Nat.le_trans; eassumption.\n      (* -- *)\n      intros.\n      assert (c' < c'').\n      apply cause_step_clock with (p := p)(h := h)(s := s).\n      split_all; assumption. \n      assumption.\n      eapply Nat.le_lt_trans; eassumption.\n  Qed.\n\n\n  (* Obligations *)\n\n  Lemma ExecToSeqExec':\n    forall p h s,\n      CExec.StepStar.step_star (CExec.init p) h s\n      -> exists h' s',\n           SExec.StepStar.step_star (SExec.init) h' s'\n           /\\ h' = CExec.eff_hist h\n           /\\ forall n k, entry_val (store (CExec.alg_state (CExec.node_states s n)) k) = s' n k.\n\n    Proof.\n      intros.\n      remember (CExec.init p) as s0.\n      induction H.\n      \n      exists nil.\n      eexists.\n      split_all.\n      constructor.\n      reflexivity.\n      intros.\n      subst s.\n      reflexivity.\n\n      depremise IHstep_star. assumption.\n      destruct IHstep_star as [h' [s' [N1 [N2 N3]]]].\n      exists (h' ++ [CExec.eff l]).\n      inversion H0.\n\n      (* put *)\n      exists (override s' n (override (s' n) k v)).\n      split_all.\n\n      apply SExec.StepStar.step_star_app_one.\n      eexists.\n      split_all.\n      eassumption.\n      simpl.\n      unfold SExec.StepStarArgs.step.\n      assert (A: s' = override s' n (s' n)).\n        apply functional_extensionality. intro n'.\n        destruct (eq_nat_dec n n'). \n        subst n'. simpl_override. reflexivity.\n        simpl_override. reflexivity.\n      rewrite A at 1.\n      apply SExec.put_step.\n\n      simpl.\n      subv h'.\n      rewrite exec_eff_app.\n      f_equal.\n\n      intros.\n      simpl.\n      destruct (eq_nat_dec n n0).\n        subst n0.\n        simpl_override.\n        simpl_override.\n\n        destruct (eq_nat_dec k k0).\n        subst k0.\n        simpl_override.\n        simpl_override.\n        simpl_override.\n        reflexivity.\n\n        simpl_override.\n        simpl_override.\n        specialize (N3 n k0).\n        subv_in s2 N3.\n        simpl_override_in N3.\n        assumption.\n        \n      simpl_override.\n      simpl_override.\n      specialize (N3 n0 k0).\n      subv_in s2 N3.\n      simpl_override_in N3.\n      assumption.\n\n      (* get *)\n      exists (override s' n (s' n)).\n      split_all.\n\n      apply SExec.StepStar.step_star_app_one.\n      eexists.\n      split_all.\n      eassumption.\n      simpl.\n      unfold SExec.StepStarArgs.step.\n      assert (A: s' = override s' n (s' n)).\n        apply functional_extensionality. intro n'.\n        destruct (eq_nat_dec n n'). \n        subst n'. simpl_override. reflexivity.\n        simpl_override. reflexivity.\n      rewrite A at 1.\n      subv v'.      \n      specialize (N3 n k).\n        subv_in s2 N3.\n        simpl_override_in N3.\n      rewrite N3.\n      apply SExec.get_step.\n\n      simpl.\n      subv h'.\n      rewrite exec_eff_app.\n      f_equal.\n\n      intros.\n      simpl.\n      destruct (eq_nat_dec n n0).\n        subst n0.\n        simpl_override.\n        simpl_override.\n        specialize (N3 n k0).\n        subv_in s2 N3.\n        simpl_override_in N3.\n        assumption.\n        \n        simpl_override.\n        simpl_override.\n        specialize (N3 n0 k0).\n        subv_in s2 N3.\n        simpl_override_in N3.\n        assumption.\n\n      (* update *)\n      simpl.\n      exists (override s' n (override (s' n) k v)).\n      split_all.\n\n      apply SExec.StepStar.step_star_app_one.\n      eexists.\n      split_all.\n      eassumption.\n      unfold SExec.StepStarArgs.step.\n      assert (A: s' = override s' n (s' n)).\n        apply functional_extensionality. intro n'.\n        destruct (eq_nat_dec n n'). \n        subst n'. simpl_override. reflexivity.\n        simpl_override. reflexivity.\n      rewrite A at 1.\n      apply SExec.put_step.\n\n      simpl.\n      subv h'.\n      rewrite exec_eff_app.\n      f_equal.\n\n      intros.\n      destruct (eq_nat_dec n n0).\n        subst n0.\n        simpl_override.\n        simpl_override.\n\n        destruct (eq_nat_dec k k0).\n        subst k0.\n        simpl_override.\n        simpl_override.\n        reflexivity.\n\n        simpl_override.\n        simpl_override.\n        specialize (N3 n k0).\n        subv_in s2 N3.\n        simpl_override_in N3.\n        assumption.\n        \n      simpl_override.\n      simpl_override.\n      specialize (N3 n0 k0).\n      subv_in s2 N3.\n      simpl_override_in N3.\n      assumption.\n\n      (* fault *)\n      exists (override s' n (s' n)).\n      split_all.\n\n      apply SExec.StepStar.step_star_app_one.\n      eexists.\n      split_all.\n      eassumption.\n      simpl.\n      unfold SExec.StepStarArgs.step.\n      assert (A: s' = override s' n (s' n)).\n        apply functional_extensionality. intro n'.\n        destruct (eq_nat_dec n n'). \n        subst n'. simpl_override. reflexivity.\n        simpl_override. reflexivity.\n      rewrite A at 1.\n      apply SExec.fault_step.\n\n      simpl.\n      subv h'.\n      rewrite exec_eff_app.\n      f_equal.\n\n      intros.\n      simpl.\n      destruct (eq_nat_dec n n0).\n        subst n0.\n        simpl_override.\n        simpl_override.\n        specialize (N3 n k0).\n        subv_in s2 N3.\n        simpl_override_in N3.\n        assumption.\n        \n        simpl_override.\n        simpl_override.\n        specialize (N3 n0 k0).\n        subv_in s2 N3.\n        simpl_override_in N3.\n        assumption.\n\n\n    Qed.\n\n  Lemma ExecToSeqExec:\n    forall p h s,\n      CExec.StepStar.step_star (CExec.init p) h s\n      -> exists h' s',\n           SExec.StepStar.step_star (SExec.init) h' s'\n           /\\ h' = CExec.eff_hist h.\n\n    Proof.\n      intros.\n      assert (A := ExecToSeqExec').\n      specex_deprem A. eassumption.\n      destruct A as [h' [s' [A1 [A2 _]]]].\n      exists h'. exists s'. split_all; assumption.\n    Qed.\n\n\n  Definition algrec: ICExec.AlgState -> NId -> Clock :=\n    rec.\n    \n\n  Lemma algrec_init:\n    forall p n n',\n      algrec (alg_state (node_states (init p) n)) n' = 0.\n\n    Proof.\n      intros;\n      reflexivity.      \n    Qed.\n\n\n  Lemma algrec_step:\n    forall p h s l s',\n      (ICExec.StepStar.step_star (ICExec.init p) h s\n       /\\ ICExec.step s l s')\n      -> (((ICExec.label_is_get l ->\n            let n := ICExec.label_node l in\n            forall n',\n              algrec (ICExec.alg_state (ICExec.node_states s n)) n' = \n              algrec (ICExec.alg_state (ICExec.node_states s' n)) n'))\n          /\\ (ICExec.label_is_put l ->\n              let n := ICExec.label_node l in\n              algrec (ICExec.alg_state (ICExec.node_states s' n)) n = \n              S (algrec (ICExec.alg_state (ICExec.node_states s n)) n)\n              /\\ forall n', (not (n' = n) ->\n                             algrec (ICExec.alg_state (ICExec.node_states s n)) n' = \n                             algrec (ICExec.alg_state (ICExec.node_states s' n)) n'))\n          /\\ (ICExec.label_is_update l ->\n              (let n := ICExec.label_node l in\n               let n' := ICExec.label_orig_node l in\n               let c' := ICExec.label_clock l in\n               S (algrec (ICExec.alg_state (ICExec.node_states s n)) n') = c'\n               /\\ algrec (ICExec.alg_state (ICExec.node_states s' n)) n' = c'\n               /\\ (forall n'', not (n'' = label_orig_node l) ->\n                               algrec (ICExec.alg_state (ICExec.node_states s n)) n'' = \n                               algrec (ICExec.alg_state (ICExec.node_states s' n)) n'')))).\n\n    Proof.\n      intros.\n      destruct H as [H0 H1].\n      split_all.\n\n      (* get *)\n      intros.\n      unfold algrec.\n      destruct l; try contradiction.\n      simpl in *. clear H. subst n.\n      inversion H1.      \n      simpl.\n      simpl_override.\n      simpl_override.\n      subst a.\n      reflexivity.\n\n      (* put *)\n      intros.\n      unfold algrec.\n      destruct l; try contradiction.\n      simpl in *. clear H. subst n.\n      inversion H1.\n      simpl.\n      simpl_override.\n      simpl_override.\n      split.      \n      subst a.\n      rewrite Nat.add_comm.\n      simpl.\n      f_equal.\n      subv n.\n      reflexivity.\n\n      intros.\n      subst a.\n      rewrite <- H4 in *.\n      simpl_override.\n      reflexivity.\n\n      (* update *)\n      intros.\n      unfold algrec.\n      destruct l; try contradiction.\n      simpl in *. clear H. subst n. subst n'. subst c'.\n      inversion H1.\n      simpl.\n      simpl_override.\n      simpl_override.\n      subst a.\n      subst c.\n\n      unfold guard_method in H13.\n      bool_to_prop_in H13.\n      destruct H13 as [_ N].\n      bool_to_prop_in N.\n\n      assert (A1 := update_sender_eq_msg_sender).\n        specex_deprem A1. split_all.\n        eassumption. subv s. apply in_app_iff. right. apply in_eq.\n        simpl in A1.\n\n      assert (A2 := update_dep_eq_msg_clock).\n        specex_deprem A2. split_all.\n        eassumption. subv s. apply in_app_iff. right. apply in_eq.\n        simpl in A2.\n      rewrite A2 in N.\n      rewrite A2.\n      rewrite A1 in N.\n      rewrite A1.\n      rewrite Nat.add_comm in N.\n      simpl in N.\n      subst n'.\n      clear A1 A2.\n\n      split_all.\n\n      symmetry.\n      assumption.\n\n      simpl_override.\n      reflexivity.\n\n      intros.\n      simpl_override.\n      reflexivity.\n      \n    Qed.\n\n\n  Lemma cause_rec:\n    forall p h s1 l s2 l',\n      let n := label_node l in\n      let c := label_clock l in\n      let n' := label_node l' in\n      let lp := msg_label (label_message l') in\n      (step_star (init p) h s1\n       /\\ step s1 l' s2\n       /\\ label_is_put l\n       /\\ label_is_update l'\n       /\\ cause h l lp)\n      -> c <= algrec (alg_state (node_states s1 n')) n.\n\n    Proof.\n      intros.\n      destruct H as [N1 [N2 [N3 [N4 N5]]]].\n      unfold algrec.\n      destruct l'; try contradiction.\n      remember (update_label n0 n1 c0 n2 k v a m a0) as l' eqn: Hu.\n\n      assert (A1: c = dep (label_post_state l) n).\n        subv c. subv n.\n        apply cause_in in N5. destruct N5 as [N5 _].\n        assert (B1 := in_exec). \n          specex_deprem B1. split; eassumption.\n          destruct B1 as [h1 [sm1 [sm2 [h2 [B11 [B12 [B13 B14]]]]]]].\n        assert (B2 := label_clock_label_post_state_clock).\n          specex_deprem B2.\n          split_all. apply B12. eassumption. eassumption.\n          simpl in B2.\n        assumption.\n\n      rewrite A1. clear A1.\n            \n      assert (A2 := cause_clock).\n        specex_deprem A2. split_all.\n        eassumption.\n        eassumption.\n        eapply label_node_in_nids.\n        split. eassumption. apply cause_in in N5. destruct N5 as [N5 _]. eassumption.\n        simpl in A2.\n        subst n. remember (label_node l) as n eqn: Hn.\n        destruct A2 as [A21 A22].\n\n\n      assert (A3: \n                (dep (label_post_state lp) (label_node lp) = rec (alg_state (node_states s1 n')) (label_node lp) + 1)\n                /\\ (forall n, In n nids ->\n                              dep (label_post_state lp) n <= rec (alg_state (node_states s1 n')) n)).\n        subv_in l' N2.\n        inversion N2; simpl in *; try contradiction.\n        subst s'0. subst a. subst s'5. subst s'4. subst s'3. subst s'2. subst v0. subst k0. subst n3. subst c0. subst n'0. subst s'1.\n        subv n'. subv l'.\n        simpl_override.\n        subv lp. subv l'. subv m.\n\n        unfold guard_method in H11.\n        bool_to_prop_in H11.\n        destruct H11 as [U1 U2].\n\n        bool_to_prop_in U2.\n        assert (B1 := msg_update_label).\n          specex_deprem B1. split_all. eassumption. subv s1. apply in_app_iff. right. apply in_eq. simpl in B1.\n          destruct B1 as [B11 [B12 [B13 B14]]].\n\n        split.\n\n        rewrite B13 in U2.\n        rewrite B12 in U2.\n        assumption.\n\n        intros.\n        assert (B2 := fold_left_and NId nids n3 (fun n => sender_dep u n <=? rec s n)).\n          depremise B2. split. \n          rewrite <- U1 at 2.\n          f_equal.\n          assumption.\n        simpl in B2.\n        bool_to_prop_in B2.\n        rewrite B13 in B2.\n        assumption.\n\n      destruct A3 as [A31 A32].\n\n      destruct (eq_nat_dec n (label_node lp)).\n\n        clear A21 A32.\n        subv n.\n        depremise A22. split. symmetry. assumption. \n          assert (B := msg_update_label).\n            subv_in l' N2. inversion N2.\n            specex_deprem B. split_all. eassumption.  subv s1. apply in_app_iff. right. apply in_eq. simpl in B.\n            destruct B as [B _].\n          subv lp. subv l'. subv m.\n          assumption.  \n        rewrite e in A22.\n        rewrite A31 in A22.\n        clear A31.\n        rewrite Nat.add_comm in A22.\n        simpl in A22.\n        apply (proj1 (Nat.lt_succ_r _ _)) in A22.\n        assumption.\n\n        \n        clear A22 A31.\n        specialize (A32 n).\n        depremise A32.\n        assert (B := label_node_in_nids).\n          specex_deprem B. split.\n          eassumption.\n          apply cause_in in N5.\n          destruct N5 as [N5 _].\n          eassumption.\n          simpl in B.\n        subv n.\n        assumption.\n        eapply Nat.le_trans; eassumption.\n\n    Qed.\n\n\nEnd KVSAlg3CauseObl.\n\n\n\nModule KVSAlg1Parametric <: Parametric KVSAlg3.\n\n  Import SysPredefs.\n  Import KVSAlg3.\n\n\n  Section ParallelWorlds.\n\n    Definition RState (Val1: Type)(Val2: Type)(R: Val1 -> Val2 -> Prop)(s1: @State Val1)(s2: @State Val2): Prop := \n      (forall k, \n         ((R (entry_val (store s1 k)) (entry_val (store s2 k)))\n         /\\ (entry_node (store s1 k)) = entry_node (store s2 k))\n         /\\ (entry_clock (store s1 k) = entry_clock (store s2 k)))\n      /\\ rec s1 = rec s2\n      /\\ dep s1 = dep s2.\n\n\n    Definition RUpdate (Val1: Type)(Val2: Type)(R: Val1 -> Val2 -> Prop)(u1: @Update Val1)(u2: @Update Val2): Prop := \n      sender_node u1 = sender_node u2 /\\\n      sender_dep u1 = sender_dep u2.\n\n    Variables Val1 Val2 : Type.\n    Variable R : Val1 -> Val2 -> Prop.\n\n    Lemma init_method_R: \n      forall v1 v2, R v1 v2 -> RState _ _ R (init_method _ v1) (init_method _ v2).\n      Proof using.\n        intros.\n        unfold RState.\n        unfold init_method.\n        simpl.\n        split.\n        intros.\n        split_all.\n        assumption.\n        reflexivity.\n        reflexivity.\n        split_all; reflexivity.\n      Qed.\n\n    Lemma get_method_R:\n      forall n s1 s2 k,\n        RState _ _ R s1 s2\n        -> let (v1', s1') := get_method _ n s1 k in\n           let (v2', s2') := get_method _ n s2 k in\n           R v1' v2' /\\ RState _ _ R s1' s2'.\n      Proof using.\n        intros.\n        unfold get_method.\n        unfold RState in H.\n        split.\n        open_conjs.\n        specialize (H k).\n        open_conjs.\n        assumption.\n        unfold RState.\n        intros.\n        simpl.\n        open_conjs.\n        split_all.\n        assumption.\n        assumption.\n        rewrite H1.\n        specialize (H k).\n        open_conjs.\n        rewrite H2.\n        rewrite H3.\n        reflexivity.\n      Qed.\n\n\n    Lemma put_method_R:\n      forall n s1 s2 k v1 v2,\n        RState _ _ R s1 s2\n        -> R v1 v2\n        -> let (s1', u1) := put_method _ n s1 k v1 in\n           let (s2', u2) := put_method _ n s2 k v2 in\n           RState _ _ R s1' s2' /\\ RUpdate _ _ R u1 u2.\n      Proof using.\n        intros.\n        simpl.\n        split.\n\n          (* --- *)\n          unfold RState.\n          split_all.\n          intros.\n          destruct (eq_nat_dec k k0).          \n\n            subst k.\n            simpl_override.\n            simpl_override.\n            simpl_override.\n            unfold RState in H.\n            open_conjs.\n            split_all.\n            assumption.\n            reflexivity.\n            simpl_override.\n            rewrite H1.\n            reflexivity.\n\n            simpl_override.\n            simpl_override.\n            simpl_override.\n            unfold RState in H.\n            open_conjs.\n            specialize (H k0).\n            assumption.\n\n            simpl_override.\n            unfold RState in H.\n            open_conjs.\n            rewrite H1.\n            reflexivity.\n\n            simpl_override.\n            unfold RState in H.\n            open_conjs.\n            rewrite H1.\n            rewrite H2.\n            reflexivity.\n\n          (* --- *)\n          unfold RUpdate.\n          unfold RState in H.\n          open_conjs.\n          rewrite H1.\n          rewrite H2.\n          split; reflexivity.\n\n      Qed.\n\n    Lemma guard_method_R:\n      forall n s1 s2 k v1 v2 u1 u2,\n        RState _ _ R s1 s2\n        -> R v1 v2\n        -> RUpdate _ _ R u1 u2\n        -> guard_method _ n s1 k v1 u1 = guard_method _ n s2 k v2 u2.\n      Proof using.\n        intros.\n        unfold guard_method.\n        unfold RState in H.\n        unfold RUpdate in H1.\n        open_conjs.\n        rewrite H1.\n        rewrite H2.\n        rewrite H3.\n        reflexivity.\n      Qed.\n\n    Lemma update_method_R:\n      forall n s1 s2 k v1 v2 u1 u2,\n        RState _ _ R s1 s2\n        -> R v1 v2\n        -> RUpdate _ _ R u1 u2\n        -> RState _ _ R (update_method _ n s1 k v1 u1) (update_method _ n s2 k v2 u2).\n      Proof using.\n        intros.\n        unfold RState.\n        split_all.\n\n          intros.\n          unfold update_method.          \n          destruct (eq_nat_dec k k0).\n            \n            subst k.\n            simpl_override.\n            simpl_override.\n            simpl_override.\n            split_all.\n            assumption.\n            unfold RUpdate in H1.\n            open_conjs.\n            assumption.\n            unfold RUpdate in H1.\n            open_conjs.\n            rewrite H1.\n            rewrite H2.\n            reflexivity.\n\n            simpl_override.\n            simpl_override.\n            simpl_override.\n            split_all.\n            unfold RState in H.\n            open_conjs.\n            specialize (H k0).\n            open_conjs.\n            assumption.\n            unfold RState in H.\n            open_conjs.\n            specialize (H k0).\n            open_conjs.\n            assumption.\n            unfold RState in H.\n            open_conjs.\n            specialize (H k0).\n            open_conjs.\n            assumption.\n          \n          unfold update_method.\n          simpl.\n          unfold RState in H.\n          open_conjs.\n          unfold RUpdate in H1.\n          open_conjs.\n          rewrite H2.\n          rewrite H1.\n          rewrite H4.\n          reflexivity.\n\n          unfold update_method.\n          simpl.\n          unfold RState in H.\n          open_conjs.\n          unfold RUpdate in H1.\n          open_conjs.\n          rewrite H3.\n          rewrite H4.\n          reflexivity.\n      Qed.\n\n  End ParallelWorlds.\n\nEnd KVSAlg1Parametric.\nModule KVSAlg1ExecToAbstExec (SyntaxArg: SyntaxPar).\n  \n  Module ExecToAbstExec := ExecToAbstExec KVSAlg3 KVSAlg1Parametric KVSAlg3CauseObl SyntaxArg.\n  Import ExecToAbstExec.\n\n  Lemma CausallyConsistent: \n    forall (p: Syntax.PProg)(h: list N.CExec.Label),\n      N.CExec.history (N.CExec.init p) h \n      -> exists (h': list AExec.Label),\n           AExec.history (AExec.init p) h'\n           /\\ N.CExec.ext_hist h = AExec.ext_hist h'.\n      \n    Proof.\n      apply ExecToAbstExec.CausallyConsistent.\n    Qed.\n\nEnd KVSAlg1ExecToAbstExec.\n\n", "meta": {"author": "coq-community", "repo": "chapar", "sha": "1355a8dd3a9cd6d07daf8f8ea64f07187d84c7ec", "save_path": "github-repos/coq/coq-community-chapar", "path": "github-repos/coq/coq-community-chapar/chapar-1355a8dd3a9cd6d07daf8f8ea64f07187d84c7ec/coq/Algorithms/KVSAlg3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.26838841865178703}}
{"text": "Require Export ComponentSM3.\nRequire Export ComponentSM4.\n\n\nSection ComponentSM6.\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  Context { base_fun_io       : baseFunIO }.\n  Context { base_state_fun    : baseStateFun }.\n  Context { trusted_state_fun : trustedStateFun }.\n\n\n  Fixpoint sm2update_p {n} {cn}\n    : forall (sm : n_proc n cn), M_Update (pred n) 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 => fun s i => M_on_pred (sm2update_p q s i)\n               end\n    end.\n\n  (* [k] is meant to be <= than [n] *)\n  Definition M_to {n} k {O} (m : M_n n O) : M_n k O :=\n    fun (ps : n_procs k) =>\n      let (ps', o') := m (raise_to_n_procs _ ps)\n      in (select_n_procs _ ps', o').\n\n  (* [n] is meant to be <= than [k] *)\n  Definition M_from {n} k {O} (m : M_n n O) : M_n k O :=\n    fun (ps : n_procs k) =>\n      let (ps', o') := m (select_n_procs _ ps)\n      in (raise_to_n_procs _ ps', o').\n\n  Lemma M_to_same :\n    forall {n} {O} (m : M_n n O),\n      M_to n m = m.\n  Proof.\n    introv.\n    apply functional_extensionality; introv; simpl.\n    unfold M_to; autorewrite with comp.\n    dest_cases w; autorewrite with comp; auto.\n  Qed.\n  Hint Rewrite @M_to_same : comp.\n\n  Lemma M_from_same :\n    forall {n} {O} (m : M_n n O),\n      M_from n m = m.\n  Proof.\n    introv.\n    apply functional_extensionality; introv; simpl.\n    unfold M_from; autorewrite with comp.\n    dest_cases w; autorewrite with comp; auto.\n  Qed.\n  Hint Rewrite @M_from_same : comp.\n\n  Lemma select_n_proc_incr_pred_n_proc :\n    forall {cn} {k} n (sm : n_proc (pred k) cn),\n      n <= pred k\n      -> select_n_proc n (incr_pred_n_proc sm)\n         = select_n_proc n sm.\n  Proof.\n    induction k; introv lek; simpl in *; tcsp;[].\n    destruct n; auto;[].\n    destruct (deq_nat k n); subst; auto;[].\n    simpl; try omega.\n  Qed.\n\n  Lemma select_n_procs_incr_pred_n_procs :\n    forall n k (l : n_procs (pred k)),\n      n <= pred k\n      -> select_n_procs n (incr_pred_n_procs l)\n         = select_n_procs n l.\n  Proof.\n    induction l; introv len; simpl; tcsp;[].\n    repeat (autodimp IHl hyp).\n    unfold select_n_procs in *; simpl in *.\n    destruct a as [cn p]; simpl.\n    rewrite select_n_proc_incr_pred_n_proc; auto;[].\n    remember (select_n_proc n p) as w; symmetry in Heqw.\n    rewrite IHl; auto.\n  Qed.\n\n  Lemma M_to_M_on_pred :\n    forall {n} {O} k (m : M_n (pred n) O),\n      k <= pred n\n      -> M_to k (M_on_pred m) = M_to k m.\n  Proof.\n    introv le.\n    apply functional_extensionality; introv; simpl.\n    unfold M_to, M_on_pred; simpl.\n    autorewrite with comp.\n    rewrite decr_n_procs_as_select_n_procs_pred.\n    rewrite raise_to_n_procs_select_n_procs; try omega;[].\n    remember (m (raise_to_n_procs (Init.Nat.pred n) x)) as p; repnd.\n    rewrite select_n_procs_incr_pred_n_procs; auto.\n  Qed.\n\n  Lemma sm2update_as_sm2update_p :\n    forall {n} {cn}\n           (sm : n_proc n cn) s i,\n      sm2update sm s i = M_to (sm2level sm) (sm2update_p sm s i).\n  Proof.\n    induction n; introv; simpl in *; tcsp.\n    destruct sm as [sm|sm]; simpl in *; auto; autorewrite with comp; auto;[].\n    rewrite IHn.\n    pose proof (sm2level_le_pred _ _ sm) as q.\n    rewrite M_to_M_on_pred; auto.\n  Qed.\n\n  Lemma sm2update_p_as_sm2update :\n    forall {n} {cn}\n           (sm : n_proc n cn) s i,\n      sm2update_p sm s i = M_from (pred n) (sm2update sm s i).\n  Proof.\n    induction n; introv; simpl in *; tcsp.\n    destruct sm as [sm|sm]; simpl in *; auto; autorewrite with comp; auto;[].\n    rewrite IHn.\n    pose proof (sm2level_le_pred _ _ sm) as q.\n\n    apply functional_extensionality; introv; simpl.\n    unfold M_on_pred, M_from.\n    rewrite select_n_procs_decr_n_procs; auto.\n    remember (sm2update sm s i (select_n_procs (sm2level sm) x)) as w; repnd; f_equal.\n    rewrite incr_pred_n_procs_raise_to_n_procs; auto.\n  Qed.\n\n(*  Lemma app_m_proc_as_sm2update :\n    forall {n} {cn}\n           (sm : n_proc n cn)\n           (i  : cio_I (fio cn)),\n      app_m_proc sm i\n      = ((sm2update_p sm (sm2state sm) i)\n           >>>= fun s o => ret _ (update_state_or_halt_m sm s, o)).\n  Proof.\n    induction n; introv; simpl in *; tcsp.\n    destruct sm as [sm|sm].\n\n    { f_equal.\n      apply functional_extensionality; introv; simpl.\n      unfold lift_M_O, app_n_proc_at, bind_pair, bind; simpl.\n      fold M_StateMachine in *.\n      fold n_proc in *.\n      remember (sm_update sm (sm_state sm) i x) as q; symmetry in Heqq; simpl in *; repnd; simpl.\n      destruct q1; simpl; auto. }\n\n    { rewrite IHn; simpl.\n      f_equal.\n      apply functional_extensionality; introv; simpl.\n      unfold lift_M_O2, M_on_pred, bind_pair, bind; simpl.\n      fold M_StateMachine in *.\n      fold n_proc in *.\n      remember (sm2update_p sm (sm2state sm) i (decr_n_procs x)) as q; repnd; simpl; auto.\n      unfold update_state_or_halt_m; destruct q1; simpl; auto. }\n  Qed.*)\n\n  Lemma select_n_proc_raise :\n    forall {n} {cn} i j (a : n_proc n cn) b,\n      j <= i <= n\n      -> select_n_proc j a = Some b\n      -> select_n_proc i a = raise_to_n_proc i b.\n  Proof.\n    induction n; introv len sel; simpl in *; tcsp;[].\n    destruct j; simpl in *; tcsp;[].\n    destruct (deq_nat n j); subst; ginv.\n\n    { assert (i = S j) by omega; subst.\n      destruct (deq_nat j j); subst; simpl in *; tcsp.\n      destruct (deq_nat j j); subst; simpl in *; tcsp.\n      pose proof (UIP_refl_nat _ e) as z; subst; simpl in *.\n      pose proof (UIP_refl_nat _ e0) as z; subst; simpl in *; auto. }\n\n    destruct i; auto; simpl in *; auto; try omega;[].\n\n    destruct (deq_nat n i); subst; simpl in *; try omega.\n\n    { destruct (deq_nat j i); subst; simpl in *; auto;\n        destruct a as [a|a]; ginv;[].\n\n      pose proof (raise_to_n_proc_as_select_n_proc _ (S j) i a b) as q.\n      autodimp q hyp; try omega.\n      apply q in sel; clear q.\n      rewrite sel; simpl; auto. }\n\n    destruct (deq_nat j i); subst; try omega;\n      destruct a as [a|a]; ginv;[].\n\n    pose proof (IHn _ (S i) (S j) a b) as IHn.\n    repeat (autodimp IHn hyp); try omega;[].\n    rewrite IHn; simpl.\n    destruct (deq_nat j i); subst; try omega; auto.\n  Qed.\n\n  Lemma select_n_nproc_raise :\n    forall {n} i j (a : n_nproc n) b,\n      j <= i <= n\n      -> select_n_nproc j a = Some b\n      -> select_n_nproc i a = raise_to_n_nproc i b.\n  Proof.\n    introv len sel.\n    destruct a; simpl in *.\n    apply option_map_Some in sel; exrepnd; subst; simpl in *.\n    apply (select_n_proc_raise i) in sel1; auto.\n    rewrite sel1; auto.\n  Qed.\n\n(*  Definition M_run_smat_on_inputs {n} {cn}\n             (sm : n_proc_at n cn)\n             (l  : list (cio_I (fio cn)))\n             (i  : cio_I (fio cn))\n    : M_n n (op_st_o cn) :=\n    M_run_update_on_inputs (sm_state sm) (sm_update sm) l i.*)\n\n(*  Definition halt_main_ls {L S} (ls : LocalSystem L S) : LocalSystem L S :=\n    LocalSystem\n      (halt_machine (ls_main ls))\n      (ls_subs ls).*)\n\n(*  Definition upd_ls_main_op_state_and_subs\n             {L} {S}\n             (ls : LocalSystem L S)\n             (o  : option (sf _))\n             (ss : n_procs _) : LocalSystem _ _ :=\n    match o with\n    | Some s => upd_ls_main_state_and_subs ls s ss\n    | None => halt_main_ls (upd_ls_subs ls ss)\n    end.*)\n\n(*  Definition M_output_ls_on_input\n             {Lv cn}\n             (ls : LocalSystem Lv cn)\n             (i  : cio_I (fio cn)) : LocalSystem _ _ * cio_O (fio cn) :=\n    M_break\n      (M_run_smat_on_inputs (ls_main ls) [] i)\n      (ls_subs ls)\n      (fun subs op =>\n         match op with\n         | Some (ops, o) => (upd_ls_main_op_state_and_subs ls ops subs, o)\n         | None => (halt_main_ls (upd_ls_subs ls subs), cio_default_O (fio cn))\n         end).*)\n\n  Definition raise_to_n_proc_def {n} {cn} m (p : n_proc n cn) (d : n_proc m cn) : n_proc m cn :=\n    opt_val (raise_to_n_proc m p) d.\n\n  Lemma at2sm_update_state :\n    forall n cn (p : n_proc_at n cn) s,\n      at2sm (update_state p s)\n      = update_state_m (at2sm p) s.\n  Proof.\n    tcsp.\n  Qed.\n\n(*  Lemma at2sm_halt_machine :\n    forall n cn (p : n_proc_at n cn),\n      at2sm (halt_machine p)\n      = halt_machine_m (at2sm p).\n  Proof.\n    tcsp.\n  Qed.*)\n\n  Lemma raise_to_n_proc_update_state_m :\n    forall m n cn (p : n_proc n cn) s,\n      raise_to_n_proc m (update_state_m p s)\n      = option_map\n          (fun q => update_state_m q s)\n          (raise_to_n_proc m p).\n  Proof.\n    induction m; introv; simpl in *; tcsp.\n\n    { destruct (deq_nat n 0); subst; simpl in *; tcsp. }\n\n    destruct (deq_nat n (S m)); subst; simpl in *; tcsp.\n    rewrite IHm; clear IHm.\n    repeat (rewrite option_map_option_map; unfold compose; simpl); auto.\n  Qed.\n\n(*  Lemma raise_to_n_proc_halt_machine_m :\n    forall m n cn (p : n_proc n cn),\n      raise_to_n_proc m (halt_machine_m p)\n      = option_map halt_machine_m (raise_to_n_proc m p).\n  Proof.\n    induction m; introv; simpl in *; tcsp.\n\n    { destruct (deq_nat n 0); subst; simpl in *; tcsp. }\n\n    destruct (deq_nat n (S m)); subst; simpl in *; tcsp.\n    rewrite IHm; clear IHm.\n    repeat (rewrite option_map_option_map; unfold compose; simpl); auto.\n  Qed.*)\n\n  Lemma at2sm_sm2at :\n    forall n cn (p : n_proc n cn),\n      raise_to_n_proc n (at2sm (sm2at p)) = Some p.\n  Proof.\n    induction n; introv; simpl in *; tcsp;[].\n    destruct p as [p|p]; simpl in *.\n\n    { destruct (deq_nat n n); tcsp.\n      pose proof (UIP_refl_nat _ e) as q; subst; simpl in *; auto. }\n\n    destruct (deq_nat (sm2level p) n); subst; simpl in *; tcsp.\n\n    { pose proof (sm2level_le_pred _ _ p) as q.\n      rewrite e in q.\n      destruct n; simpl in *; try omega. }\n\n    rewrite IHn; simpl; auto.\n  Qed.\n  Hint Rewrite at2sm_sm2at : comp.\n\n(*  Definition update_subs_with_sub_ls\n             {n} {L} {cn}\n             (subs : n_procs n)\n             (sm   : n_proc n cn)\n             (ls   : LocalSystem L cn) : n_procs n :=\n    replace_subs\n      (replace_name (raise_to_n_proc_def _ (at2sm (ls_main ls)) sm) subs)\n      (raise_to_n_procs (pred n) (ls_subs ls)).*)\n\n(*  Lemma M_break_call_comp :\n    forall (cn : CompName) n O\n           (i    : cio_I (fio cn))\n           (subs : n_procs n)\n           (F    : n_procs n -> cio_O (fio cn) -> O),\n      M_break (call_proc cn i) subs F\n      = match find_name cn subs with\n        | Some sm =>\n\n          let ls1 := MkLocalSystem (sm2at sm) (select_n_procs _ subs) in\n          let (ls2, o) := M_output_ls_on_input ls1 i in\n          F (update_subs_with_sub_ls subs sm ls2) o\n\n        | None => F subs (cio_default_O (fio cn))\n        end.\n  Proof.\n    introv.\n    unfold M_break, call_proc, M_output_ls_on_input, M_output_sm_on_inputs; simpl.\n    unfold update_subs_with_sub_ls.\n    unfold M_run_smat_on_inputs, M_run_update_on_inputs; simpl.\n    remember (find_name cn subs) as find; symmetry in Heqfind; destruct find; auto;[].\n    rename n0 into p.\n\n    autorewrite with comp.\n    unfold M_break; simpl.\n    rewrite app_m_proc_as_sm2update.\n    rewrite sm2update_p_as_sm2update.\n    unfold M_from, bind_pair, bind; simpl.\n    rewrite select_n_procs_decr_n_procs; eauto 3 with comp;[].\n\n    remember (sm2update p (sm2state p) i (select_n_procs (sm2level p) subs)) as w; repnd; simpl in *.\n    f_equal.\n\n    destruct w1; simpl; f_equal; f_equal.\n\n    { rewrite at2sm_update_state.\n      unfold raise_to_n_proc_def.\n      rewrite raise_to_n_proc_update_state_m.\n      autorewrite with comp; simpl; auto. }\n\n    { rewrite at2sm_halt_machine.\n      unfold raise_to_n_proc_def.\n      rewrite raise_to_n_proc_halt_machine_m.\n      autorewrite with comp; simpl; auto. }\n  Qed.*)\n\n(*  Lemma ls_subs_upd_ls_main_op_state_and_subs :\n    forall {L S} (ls : LocalSystem L S) ops subs,\n      ls_subs (upd_ls_main_op_state_and_subs ls ops subs) = subs.\n  Proof.\n    introv.\n    destruct ops; simpl; auto.\n  Qed.\n  Hint Rewrite @ls_subs_upd_ls_main_op_state_and_subs : comp.*)\n\n(*  Lemma is_proc_n_proc_at_upd_ls_main_op_state_and_subs :\n    forall {L S} (ls : LocalSystem L S) ops subs,\n      is_proc_n_proc_at (ls_main ls)\n      -> is_proc_n_proc_at (upd_ls_main_op_state_and_subs ls ops subs).\n  Proof.\n    introv; destruct ops; simpl; auto.\n  Qed.\n  Hint Resolve is_proc_n_proc_at_upd_ls_main_op_state_and_subs : comp.*)\n\n  Lemma is_proc_n_proc_at_update_implies_some :\n    forall cn n (p : n_proc_at n cn) s i subs1 subs2 sop out,\n      is_proc_n_proc_at p\n      -> sm_update p s i subs1 = (subs2, (sop, out))\n      -> exists s, sop = Some s.\n  Proof.\n    introv isp e.\n    unfold is_proc_n_proc_at in isp; exrepnd.\n    rewrite isp0 in e; clear isp0.\n    unfold proc2upd in *; simpl in *.\n    unfold interp_s_proc, to_proc_some_state in *; simpl in *.\n    unfold bind_pair, bind in *; simpl in *.\n    remember (interp_proc (p0 s i) subs1) as w; repnd; simpl in *; ginv; eauto.\n    inversion e; subst; eauto.\n  Qed.\n\n(*  Lemma M_output_ls_on_input_preserves :\n    forall {L S} (ls1 ls2 : LocalSystem L S) i o,\n      wf_ls ls1\n      -> are_procs_ls ls1\n      -> M_output_ls_on_input ls1 i = (ls2, o)\n      -> wf_ls ls2\n         /\\ are_procs_ls ls2\n         /\\ similar_sms_at (ls_main ls1) (ls_main ls2)\n         /\\ similar_subs (ls_subs ls1) (ls_subs ls2).\n  Proof.\n    introv wf aps out.\n    unfold M_output_ls_on_input, M_break in out; simpl in *.\n    dest_cases w; symmetry in Heqw.\n    unfold M_run_smat_on_inputs in Heqw; simpl in *.\n    unfold M_run_update_on_inputs, bind_some, bind in Heqw; simpl in *.\n    unfold bind in Heqw; simpl in *.\n    repeat (dest_cases w; repnd); ginv.\n    inversion Heqw; subst; simpl in *; GC.\n    clear Heqw.\n    symmetry in Heqw1.\n    destruct aps as [aps1 aps2].\n    destruct wf as [wf1 wf2].\n    pose proof (are_procs_implies_preserves_sub\n                  (ls_main ls1)\n                  (sm_state (ls_main ls1))\n                  i\n                  (ls_subs ls1)) as q.\n    repeat (autodimp q hyp).\n    unfold M_break in q.\n    rewrite Heqw1 in q; simpl in *.\n    repnd.\n    unfold wf_ls, are_procs_ls; simpl.\n    autorewrite with comp.\n    applydup is_proc_n_proc_at_update_implies_some in Heqw1; auto;[].\n    exrepd; subst; simpl in *.\n    dands; eauto 3 with comp;[].\n    apply similar_subs_preserves_procs_names in q0.\n    rewrite <- q0; auto.\n  Qed.*)\n\n  Lemma M_break_snd_eq :\n    forall {n} {A} {B}\n           (m : M_n n (A * B))\n           (subs : n_procs n),\n      M_break m subs (fun _ out => snd out)\n      = snd (M_break m subs (fun _ out => out)).\n  Proof.\n    introv.\n    unfold M_break.\n    destruct (m subs); auto.\n  Qed.\n\n  Lemma M_break_fst_eq :\n    forall {n} {A} {B}\n           (m : M_n n (A * B))\n           (subs : n_procs n),\n      M_break m subs (fun _ out => fst out)\n      = fst (M_break m subs (fun _ out => out)).\n  Proof.\n    introv.\n    unfold M_break.\n    destruct (m subs); auto.\n  Qed.\n\n  Lemma M_break_fst_eq2 :\n    forall {n} {A} {B}\n           (m : M_n n (A * B))\n           (subs : n_procs n),\n      M_break m subs (fun _ out => fst out)\n      = fst (snd (M_break m subs (fun subs out => (subs, out)))).\n  Proof.\n    introv.\n    unfold M_break.\n    destruct (m subs); auto.\n  Qed.\n\n  Lemma M_break_snd_eq2 :\n    forall {n} {A} {B}\n           (m : M_n n (A * B))\n           (subs : n_procs n),\n      M_break m subs (fun _ out => snd out)\n      = snd (snd (M_break m subs (fun subs out => (subs, out)))).\n  Proof.\n    introv.\n    unfold M_break.\n    destruct (m subs); auto.\n  Qed.\n\n  Lemma M_break_option_map_fst_eq :\n    forall {n} {A} {B} {O}\n           (m : M_n n (option A * B))\n           (subs : n_procs n) (F : n_procs n -> A -> O),\n      M_break m subs (fun subs' out => option_map (F subs') (fst out))\n      = let (subs',out) := M_break m subs (fun subs' out => (subs', out)) in\n        option_map (F subs') (fst out).\n  Proof.\n    introv.\n    unfold M_break.\n    destruct (m subs); auto.\n  Qed.\n\n  Lemma similar_subs_nil_l :\n    forall {n} (subs : n_procs n),\n      similar_subs ([] : n_procs n) subs <-> subs = [].\n  Proof.\n    introv; split; intro q; subst; auto.\n    inversion q; auto.\n  Qed.\n  Hint Rewrite @similar_subs_nil_l : comp.\n\n  Definition sm2p0 {cn} (sm : MP_StateMachine (fun _ => False) cn) : n_proc_at 0 cn := sm.\n\n  Lemma fold_build_m_sm :\n    forall {n} {nm} (upd : M_Update n nm (sf nm)) (s : sf nm),\n      at2sm (build_mp_sm upd s) = build_m_sm upd s.\n  Proof.\n    tcsp.\n  Qed.\n  Hint Rewrite @fold_build_m_sm : comp.\n\n  Lemma update_state_m_sm_or_at_build_mp_sm :\n    forall {cn} (upd : M_Update 0 cn (sf cn)) (s s' : sf cn),\n      @update_state_m _ _ _ _ _ _ _ _ 1 cn (@sm_or_at _ False (build_mp_sm upd s)) s'\n      = build_m_sm upd s'.\n  Proof.\n    tcsp.\n  Qed.\n  Hint Rewrite @update_state_m_sm_or_at_build_mp_sm : comp.\n\n  Lemma lower_head_incr_n_procs :\n    forall i {n} (l : n_procs n),\n      lower_head i (incr_n_procs l)\n      = lower_head i l.\n  Proof.\n    destruct l; simpl; auto.\n    destruct n0; simpl in *; tcsp.\n  Qed.\n  Hint Rewrite lower_head_incr_n_procs : comp.\n\n  Lemma ordered_subs_incr_n_procs :\n    forall {n} (l : n_procs n),\n      ordered_subs (incr_n_procs l)\n      = ordered_subs l.\n  Proof.\n    unfold incr_n_procs; induction l; introv; simpl in *; tcsp.\n    rewrite IHl; f_equal.\n    destruct a; simpl.\n    fold (incr_n_procs l); autorewrite with comp; auto.\n  Qed.\n  Hint Rewrite @ordered_subs_incr_n_procs : comp.\n\n  Lemma get_names_incr_n_procs :\n    forall {n} (l : n_procs n),\n      get_names (incr_n_procs l)\n      = get_names l.\n  Proof.\n    induction l; introv; simpl in *; tcsp.\n    rewrite IHl.\n    destruct a; simpl in *; tcsp.\n  Qed.\n  Hint Rewrite @get_names_incr_n_procs : comp.\n\n  Lemma are_procs_n_procs_incr_n_procs :\n    forall {n} (l : n_procs n),\n      are_procs_n_procs l\n      -> are_procs_n_procs (incr_n_procs l).\n  Proof.\n    introv aps i; apply in_map_iff in i; exrepnd; subst; simpl in *.\n    apply aps in i0.\n    destruct x; simpl in *; tcsp.\n  Qed.\n  Hint Resolve are_procs_n_procs_incr_n_procs : comp.\n\n  Lemma similar_procs_incr_n_nproc_left_implies :\n    forall {n} (p : n_nproc n) (k : n_nproc (S n)),\n      similar_procs (incr_n_nproc p) k\n      -> exists j, k = incr_n_nproc j /\\ similar_procs p j.\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 h2; subst; eauto 3 with comp.\n    simpl in *.\n    destruct p, p1, p2; simpl in *; tcsp; inversion h1; subst; simpl in *.\n    match goal with\n    | [ H : context[b] |- _ ] => rename H into h3\n    end.\n    apply Eqdep.EqdepTheory.inj_pair2 in h3; subst; eauto 3 with comp.\n    exists (MkPProc pp_name b0); simpl; tcsp.\n  Qed.\n\n  Lemma similar_subs_incr_n_procs_left_implies :\n    forall {n} (l : n_procs n) (k : n_procs (S n)),\n      similar_subs (incr_n_procs l) k\n      -> exists j, k = incr_n_procs j /\\ similar_subs l j.\n  Proof.\n    induction l; destruct k; introv sim; simpl in *; tcsp;\n      inversion sim; subst; clear sim.\n    { exists ([] : n_procs n); simpl; tcsp. }\n    apply IHl in sims; clear IHl; exrepnd; subst; simpl in *.\n    apply similar_procs_incr_n_nproc_left_implies in simp; exrepnd; subst.\n    exists (j0 :: j); simpl; tcsp.\n  Qed.\n\nEnd ComponentSM6.\n\n\nHint Rewrite @M_to_same : comp.\nHint Rewrite @M_from_same : comp.\nHint Rewrite @at2sm_sm2at : comp.\n(*Hint Rewrite @ls_subs_upd_ls_main_op_state_and_subs : comp.*)\nHint Rewrite @similar_subs_nil_l : comp.\nHint Rewrite @fold_build_m_sm : comp.\nHint Rewrite @update_state_m_sm_or_at_build_mp_sm : comp.\nHint Rewrite @lower_head_incr_n_procs : comp.\nHint Rewrite @ordered_subs_incr_n_procs : comp.\nHint Rewrite @get_names_incr_n_procs : comp.\n\nHint Resolve are_procs_n_procs_incr_n_procs : comp.\n\n\n(*Hint Resolve is_proc_n_proc_at_upd_ls_main_op_state_and_subs : comp.*)\n\n\nLtac prove_wf :=\n  match goal with\n  | [ |- wf_procs _ ] =>\n    repeat constructor; simpl; tcsp\n  end.\n\nLtac prove_are_procs :=\n  match goal with\n  | [ |- are_procs_n_procs _ ] =>\n    repeat constructor;\n    [unfold is_proc_n_proc_at; eexists; introv; reflexivity\n    |introv xx; simpl in *; tcsp]\n  end.\n\n(*Ltac m_output_ls_on_input_preserves H out :=\n  match type of H with\n  | M_output_ls_on_input ?ls1 ?i = (?ls2, ?o) =>\n    let wf   := fresh \"wf\"   in\n    let wf1  := fresh \"wf1\"  in\n    let wf2  := fresh \"wf2\"  in\n    let wf3  := fresh \"wf3\"  in\n    let wf4  := fresh \"wf4\"  in\n    let main := fresh \"main\" in\n    let subs := fresh \"subs\" in\n    autorewrite with comp minbft in H;\n    applydup @M_output_ls_on_input_preserves in H as wf;\n    try prove_wf;\n    try prove_are_procs;\n    destruct ls2 as [main subs]; simpl in *;\n    simpl in wf;\n    autorewrite with comp minbft in wf;\n    destruct wf as [wf1 [wf2 [wf3 wf4]]];\n    exrepnd; subst; simpl in *;\n    rename o into out\n  end.*)\n\n(*Ltac abstract_m_output_ls_on_input H out :=\n  match type of H with\n  | context[M_output_ls_on_input ?ls ?i] =>\n    let o := fresh \"out\" in\n    remember (M_output_ls_on_input ls i) as o;\n    repnd;\n    match goal with\n    | [ G : (_,_) = M_output_ls_on_input _ _ |- _ ] =>\n      symmetry in G;\n      simpl in H;\n      m_output_ls_on_input_preserves G out\n    end\n  end.*)\n\n(*Ltac use_m_break_call_comp out :=\n  match goal with\n  | [ H : context[call_proc ?n ?i] |- _ ] =>\n    let h  := fresh \"h\" in\n    let xx := fresh \"xx\" in\n    pose proof (M_break_call_comp n) as h;\n    rewrite h in H; clear h;\n    remember @M_output_ls_on_input as xx;\n    simpl in H; subst xx;\n    abstract_m_output_ls_on_input H out\n  end.*)\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/ComponentSM6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.26838841865178703}}
{"text": "From Perennial.program_proof Require Import grove_prelude.\nFrom Goose.github_com.mit_pdos.gokv Require Import memkv.\n\nFrom Perennial.program_proof.memkv Require Export memkv_shard_definitions memkv_coord_definitions common_proof.\nFrom Perennial.program_proof.memkv Require Import memkv_shard_clerk_proof.\n\n(* Needed for ShardClerkSet GetClerk *)\nFrom Perennial.program_proof.memkv Require Import memkv_coord_clerk_proof.\n\nSection memkv_coord_start_proof.\n\nContext `{!heapGS Σ, erpcG Σ, urpcregG Σ, kvMapG Σ}.\n\nLemma wp_encodeShardMap s (shardMap_sl : Slice.t) (shardMapping : list u64) :\n  length shardMapping = int.nat uNSHARD →\n  {{{ \"Hs_ptr\" ∷ s ↦[slice.T HostName] (slice_val shardMap_sl) ∗\n      \"HshardMap_sl\" ∷ typed_slice.is_slice_small (V:=u64) shardMap_sl HostName 1 shardMapping\n  }}}\n    encodeShardMap #s\n  {{{ (sl: Slice.t) (data: list u8), RET (slice_val sl);\n      \"%Henc\" ∷ ⌜ has_encoding_shardMapping data shardMapping ⌝ ∗\n      \"Hdata\" ∷  typed_slice.is_slice sl byteT 1 data ∗\n      \"Hs_ptr\" ∷ s ↦[slice.T HostName] (slice_val shardMap_sl) ∗\n      \"HshardMap_sl\" ∷ typed_slice.is_slice_small (V:=u64) shardMap_sl HostName 1 shardMapping\n  }}}.\nProof.\n  wp_pures. iIntros (Hshards Φ) \"H HΦ\".\n  iNamed \"H\".\n  wp_lam.\n\n  wp_pures.\n  wp_apply (wp_new_enc).\n  iIntros (enc) \"Henc\".\n  wp_pures.\n  change (int.Z (word.mul 8 65536)) with (8 * 65536).\n\n  wp_load.\n  wp_apply (wp_Enc__PutInts with \"[$Henc $HshardMap_sl]\").\n  { rewrite /uNSHARD in Hshards. rewrite Hshards. word. }\n  iIntros \"[Henc HshardMap_sl]\".\n\n  wp_apply (wp_Enc__Finish with \"Henc\").\n  iIntros (rep_sl repData).\n  iIntros \"(%Henc & %Hlen & Hrep_sl)\".\n  iApply \"HΦ\". rewrite /named. iFrame. iPureIntro.\n  rewrite /has_encoding_shardMapping. done.\nQed.\n\nLemma wp_KVCoord__AddServerRPC s x γ γsh :\n  {{{ \"#His_memkv\" ∷ is_KVCoordServer s γ ∗\n      \"#His_shard\" ∷ is_shard_server x γsh ∗\n      \"%Heq_kv_gn\" ∷ ⌜γsh.(kv_gn) = γ.(coord_kv_gn)⌝\n  }}}\n    KVCoord__AddServerRPC #s #x\n  {{{ RET #(); True%I }}}.\nProof.\n  iIntros (Φ) \"H HΦ\".\n  iNamed \"H\".\n  wp_lam.\n  wp_pures.\n  iNamed \"His_memkv\".\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_apply (wp_MapInsert with \"[$]\").\n  { eauto. }\n  iIntros \"Hmap\".\n  wp_pures.\n  wp_loadField.\n  wp_apply (wp_MapLen (V:=u64) with \"[$Hmap]\").\n  remember (size (typed_map.map_insert hostShards x 0)) as num_shards eqn:Heq_num_shards.\n  iIntros \"(%Hmap_size&Hmap)\".\n  wp_pures.\n  wp_apply (wp_ref_of_zero _ _ (uint64T)).\n  { econstructor. }\n  iIntros (nf_left_ptr) \"Hnf_left\".\n  wp_pures.\n  wp_apply (wp_StoreAt with \"[$]\").\n  { naive_solver. }\n  iIntros \"Hnf_left\".\n  wp_pures.\n  wp_loadField.\n  iDestruct (typed_slice.is_slice_small_acc with \"HshardMap_sl\") as \"(HshardMap_sl&HshardMap_clo)\".\n  wp_bind (forSlice _ _ _).\n  rewrite /forSlice.\n  wp_pures.\n  wp_apply (wp_slice_len).\n  (* wp_pures would reduce too far *)\n  wp_pure (goose_lang.Rec _ _ _).\n  wp_pure (goose_lang.App _ _).\n  wp_pure (goose_lang.Rec _ _ _).\n\n  (* We want to generalize over the loop argument, which is 0, but there are many occurrences of 0.\n     This is a hack to only eplace that one occurence. *)\n  pose (k' := U64 0).\n  assert (k' = 0) as Heqk by auto.\n  iEval (rewrite -{-1}Heqk).\n  clear Heqk. remember k' as k eqn:Heqk. clear Heqk.\n\n  remember ((word.sub (word.sub num_shards 65536)\n                                          (word.divu (word.mul num_shards 65536) num_shards)))\n           as nf_left eqn:Hnf_left.\n  clear Hnf_left.\n\n  remember ((typed_map.map_insert hostShards x 0)) as hostShards'.\n  clear HeqhostShards'.\n  clear Heq_num_shards.\n  iLöb as \"IH\" forall (k hostShards' nf_left shardMapping Hlen_shardMapping HshardMapping_dom) \"HshardServers\".\n  wp_pures.\n  iFreeze \"IH\".\n  wp_if_destruct; last first.\n  { iClear \"IH\". wp_pures. wp_loadField. wp_apply (release_spec with \"[-HΦ]\").\n    { iFrame \"Hlocked HmuInv\". iNext. iExists _, _, _, _, _.\n      iDestruct (\"HshardMap_clo\" with \"[$]\") as \"$\".\n      iFrame. iSplit; eauto. }\n    wp_pures. iApply \"HΦ\". eauto. }\n  iDestruct (typed_slice.is_slice_small_sz (V:=u64) with \"[$]\") as %Hsz.\n  edestruct (list_lookup_lt _ (shardMapping) (int.nat k)) as (v&Heq).\n  { word_cleanup. }\n  wp_apply (typed_slice.wp_SliceGet (V:=u64) with \"[HshardMap_sl]\").\n  { rewrite /HostName. iFrame \"HshardMap_sl\". iPureIntro. eauto. }\n  iIntros \"HshardMap_sl\". wp_pures.\n  wp_loadField. wp_apply (wp_MapGet with \"[$]\").\n  iIntros (v' ok) \"(%Hget&Hmap)\".\n  wp_pures.\n  wp_if_destruct; last first.\n  { wp_pure (goose_lang.Rec _ _ _).\n    wp_pure (goose_lang.App _ _).\n    iThaw \"IH\".\n    wp_pure (_ + _)%E.\n    iApply (\"IH\" $! _ with \"[//] [//] [$] [$] [$] [$] [$] [$] [$] [$] [$] [$] [$]\").\n  }\n  wp_pures.\n  wp_if_destruct.\n  {\n    wp_apply (wp_LoadAt with \"[$]\").\n    iIntros \"Hnf_left_ptr\". wp_pures.\n    wp_if_destruct.\n    {\n      wp_apply (wp_LoadAt with \"[$]\").\n      iIntros \"Hnf_left_ptr\". wp_pures.\n      wp_apply (wp_StoreAt with \"[$]\").\n      { naive_solver. }\n      iIntros \"Hnf_left_ptr\". wp_pures.\n      wp_loadField.\n      rewrite /all_are_shard_servers.\n      iDestruct (\"HshardServers\" $! _ _ with \"[//]\") as (γh) \"(His_shard_host&Heq)\".\n      wp_apply (wp_ShardClerkSet__GetClerk with \"[$]\").\n      iIntros (ck_ptr) \"(Hclerk&Hclerk_clo)\".\n      wp_bind (KVShardClerk__MoveShard #ck_ptr #_ #x).\n      wp_apply (wp_KVShardClerk__MoveShard with \"[$Hclerk]\").\n      { iFrame \"#His_shard\". iPureIntro.\n        eapply lookup_lt_Some in Heq. lia. }\n      iIntros \"Hclerk\".\n      wp_pures.\n      wp_loadField.\n      wp_apply (wp_MapInsert with \"[$]\").\n      { naive_solver. }\n      iIntros \"Hmap\".\n      wp_pures.\n      wp_loadField.\n      wp_apply (wp_MapGet with \"[$]\").\n      iIntros (v' ok') \"(%Hget'&Hmap)\".\n      wp_pures. wp_loadField.\n      wp_apply (wp_MapInsert with \"[$]\").\n      { naive_solver. }\n      iIntros \"Hmap\".\n      wp_pures.\n      wp_loadField.\n      wp_apply (typed_slice.wp_SliceSet (V:=u64) with \"[$HshardMap_sl]\").\n      { eauto. }\n      iIntros \"HshardMap_sl\".\n      wp_pure (goose_lang.Rec _ _ _).\n      wp_pure (goose_lang.App _ _).\n      iThaw \"IH\".\n      wp_pure (_ + _)%E.\n      iDestruct (\"Hclerk_clo\" with \"[$]\") as \"Hclerk\".\n      iApply (\"IH\" $! _ (typed_map.map_insert\n                  (typed_map.map_insert hostShards' v (word.sub (word.add (word.divu 65536 _) 1) 1))\n                  x (word.add v' 1)) with \"[] [] [$] [$] [$] [$] [$] [$] [$] [$] [$] [$]\").\n      { iPureIntro. rewrite insert_length. eauto. }\n      { iPureIntro. intros i Hlt.\n        destruct (decide (i = k)).\n        { subst. rewrite list_lookup_insert; eauto.\n          word. }\n        { rewrite list_lookup_insert_ne; eauto.\n          intros Heq'.\n          apply Z2Nat.inj in Heq'; try word.\n          eapply (int_Z_inj) in Heq'; eauto. apply _.\n        }\n      }\n      iModIntro. iIntros (? Hin Hlookup').\n      destruct (decide (sid = int.nat k)).\n      {\n        subst. rewrite list_lookup_insert in Hlookup'; last by word.\n        iExists _. inversion Hlookup'; subst. iFrame \"His_shard\".\n        eauto.\n      }\n      iClear \"IH\".\n      rewrite list_lookup_insert_ne in Hlookup'; last by word.\n      iApply \"HshardServers\"; eauto.\n    }\n    wp_pure (goose_lang.Rec _ _ _).\n    wp_pure (goose_lang.App _ _).\n    wp_pure (_ + _)%E.\n    iThaw \"IH\".\n    iApply (\"IH\" $! _ _ with \"[//] [//] [$] [$] [$] [$] [$] [$] [$] [$] [$] [$] [$]\").\n  }\n  {\n    wp_loadField.\n      rewrite /all_are_shard_servers.\n      iDestruct (\"HshardServers\" $! _ _ with \"[//]\") as (γh) \"(His_shard_host&Heq)\".\n      wp_apply (wp_ShardClerkSet__GetClerk with \"[$]\").\n      iIntros (ck_ptr) \"(Hclerk&Hclerk_clo)\".\n      wp_bind (KVShardClerk__MoveShard #ck_ptr #_ #x).\n      wp_apply (wp_KVShardClerk__MoveShard with \"[$Hclerk]\").\n      { iFrame \"#His_shard\". iPureIntro.\n        eapply lookup_lt_Some in Heq. lia. }\n      iIntros \"Hclerk\".\n      wp_pures.\n      wp_loadField.\n      wp_apply (wp_MapInsert with \"[$]\").\n      { naive_solver. }\n      iIntros \"Hmap\".\n      wp_pures.\n      wp_loadField.\n      wp_apply (wp_MapGet with \"[$]\").\n      iIntros (v'' ok'') \"(%Hget'&Hmap)\".\n      wp_pures. wp_loadField.\n      wp_apply (wp_MapInsert with \"[$]\").\n      { naive_solver. }\n      iIntros \"Hmap\".\n      wp_pures.\n      wp_loadField.\n      wp_apply (typed_slice.wp_SliceSet (V:=u64) with \"[$HshardMap_sl]\").\n      { eauto. }\n      iIntros \"HshardMap_sl\".\n      wp_pure (goose_lang.Rec _ _ _).\n      wp_pure (goose_lang.App _ _).\n      iThaw \"IH\".\n      wp_pure (_ + _)%E.\n      iDestruct (\"Hclerk_clo\" with \"[$]\") as \"Hclerk\".\n      iApply (\"IH\" $! _ _ with \"[] [] [$] [$] [$] [$] [$] [$] [$] [$] [$] [$]\").\n      { iPureIntro. rewrite insert_length. eauto. }\n      { iPureIntro. intros i Hlt.\n        destruct (decide (i = k)).\n        { subst. rewrite list_lookup_insert; eauto.\n          word. }\n        { rewrite list_lookup_insert_ne; eauto.\n          intros Heq'.\n          apply Z2Nat.inj in Heq'; try word.\n          eapply (int_Z_inj) in Heq'; eauto. apply _.\n        }\n      }\n      iModIntro. iIntros (? Hin Hlookup').\n      destruct (decide (sid = int.nat k)).\n      {\n        subst. rewrite list_lookup_insert in Hlookup'; last by word.\n        iExists _. inversion Hlookup'; subst. iFrame \"His_shard\".\n        eauto.\n      }\n      iClear \"IH\".\n      rewrite list_lookup_insert_ne in Hlookup'; last by word.\n      iApply \"HshardServers\"; eauto.\n    }\nQed.\n\nLemma wp_KVCoordServer__Start (s:loc) (host : u64) γ :\nhandlers_dom γ.(coord_urpc_gn) {[ U64 1; U64 2 ]} -∗\nis_coord_server host γ -∗\nis_KVCoordServer s γ -∗\n  {{{\n       True\n  }}}\n    KVCoord__Start #s #host\n  {{{\n       RET #(); True\n  }}}.\nProof.\n  iIntros \"#Hdom #His_coord #His_memkv !#\" (Φ) \"_ HΦ\".\n  wp_lam.\n  wp_pures.\n  wp_apply map.wp_NewMap.\n  iIntros (handlers_ptr) \"Hmap\".\n  wp_pures.\n\n  wp_apply (map.wp_MapInsert with \"Hmap\").\n  iIntros \"Hmap\".\n  wp_pures.\n  rewrite /KVCoord__GetShardMapRPC.\n\n  wp_apply (map.wp_MapInsert with \"Hmap\").\n  iIntros \"Hmap\".\n  wp_pures.\n\n  wp_apply (wp_MakeServer with \"[$Hmap]\").\n  iIntros (rs) \"Hsown\".\n  wp_pures.\n\n  iNamed \"His_coord\".\n  wp_apply (wp_StartServer with \"[$Hsown]\").\n  { rewrite ?dom_insert_L; set_solver. }\n  {\n    iSplitL \"\".\n    { rewrite /handlers_complete.\n      rewrite ?dom_insert_L dom_empty_L. iExactEq \"Hdom\". f_equal. set_solver. }\n    iApply (big_sepM_insert_2 with \"\").\n    { (* GetShardMapping RPC handler_is *)\n      iExists _.\n      iFrame \"#HgetSpec\".\n\n      clear Φ.\n      rewrite /impl_handler_spec.\n      iIntros (??????) \"!#\".\n      iIntros (Φ) \"Hpre HΦ\".\n      wp_pures.\n      iDestruct \"Hpre\" as \"(Hreq_sl & Hrep & _ & Hpre)\".\n      simpl.\n      iDestruct \"Hpre\" as (_) \"[_ Hpost]\".\n      iNamed \"His_memkv\".\n      wp_loadField.\n      wp_apply (acquire_spec with \"[$HmuInv]\").\n      iIntros \"[Hlocked Hown]\".\n      iNamed \"Hown\".\n      wp_pures.\n      wp_apply (wp_struct_fieldRef_mapsto with \"[$shardMap]\").\n      { eauto. }\n      iIntros (fl) \"(H1&H2)\".\n      iDestruct (typed_slice.is_slice_small_acc with \"HshardMap_sl\") as \"[HshardMap_sl HshardMap_close]\".\n      wp_apply (wp_encodeShardMap with \"[$]\").\n      { word_cleanup. rewrite wrap_small; last (rewrite /uNSHARD; lia).\n        rewrite -Hlen_shardMapping. lia. }\n      iIntros (sl data) \"(%Henc&H)\".\n      wp_apply (wp_StoreAt with \"[$]\").\n      { apply slice_val_ty. }\n      iIntros \"Hrep\".\n      iNamed \"H\".\n      iDestruct (\"HshardMap_close\" with \"HshardMap_sl\") as \"HshardMap_sl\".\n      iDestruct (is_slice_to_small with \"Hdata\") as \"Hdata\".\n      wp_pures.\n      wp_loadField.\n      wp_apply (release_spec with \"[-HΦ Hpost Hrep Hdata]\").\n      { iFrame \"Hlocked HmuInv\".\n        iNext. iExists _, _, _, _, _. iFrame. iFrame \"#\". iFrame \"%\".\n        iDestruct \"H1\" as %Hequiv. iApply Hequiv. iFrame. }\n      wp_pures. iApply \"HΦ\". iFrame. iApply \"Hpost\". iModIntro. iExists _. iFrame \"% #\".\n    }\n    iApply (big_sepM_insert_2 with \"\").\n    { (* AddServerRPC *)\n      iExists _.\n      iFrame \"#HaddSpec\".\n\n      clear Φ.\n      rewrite /impl_handler_spec.\n      iIntros (??????) \"!#\".\n      iIntros (Φ) \"Hpre HΦ\".\n      wp_pures.\n      iDestruct \"Hpre\" as \"(Hreq_sl & Hrep & Hrep_sl & Hpre)\".\n      iDestruct (is_slice_to_small with \"Hrep_sl\") as \"Hrep_sl\".\n      simpl.\n      iDestruct \"Hpre\" as (x) \"[Hpre Hpost]\".\n      iDestruct \"Hpre\" as \"(%Henc&Hshard)\".\n      iDestruct \"Hshard\" as (γsh Heq) \"#His_shard\".\n      wp_apply (wp_DecodeUint64' with \"[$Hreq_sl]\"); first by eauto.\n      wp_pures.\n      simpl in x.\n      wp_apply (wp_KVCoord__AddServerRPC with \"[]\").\n      { iSplitL \"\".\n        { rewrite /named. iExactEq \"His_memkv\". eauto. }\n        iFrame \"His_shard\". eauto.\n      }\n      wp_pures. iApply \"HΦ\". iFrame. iApply \"Hpost\". eauto.\n    }\n    rewrite big_sepM_empty. eauto.\n  }\n  wp_pures. iApply \"HΦ\".\n  auto.\nQed.\n\nEnd memkv_coord_start_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/memkv/memkv_coord_start_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.26838841237549765}}
{"text": "Set Implicit Arguments.\nRequire Import Metalib.Metatheory.\nRequire Import Program.Equality.\nRequire Export Antisymmetry.\n\n\nLemma label_transform3: forall (X X0:atom) T D,\n    X \\notin fl_tt T \\u {{X0}} ->\n    type D ->\n    open_tt (subst_label X (subst_tt X (typ_label X D) T))\n             (typ_label X0 (open_tt (subst_label X (subst_tt X (typ_label X D) T)) X0))\n      = subst_label X (subst_tt X (typ_label X D) (open_tt T (typ_label X0 (open_tt T X0)))).\nProof with auto.\n  intros.\n  rewrite  subst_tt_open_tt ...\n  rewrite subst_label_open_tt ...\n  f_equal...\n  rewrite drop_label_reverse_type...  \n  rewrite drop_label_reverse_type...\n  solve_notin.\nQed.\n\nLemma label_transform4 : forall (X X0:atom) T D,\n    X \\notin fl_tt T \\u {{X0}} ->\n    type D ->\n    (open_tt (subst_label X (subst_tt X (typ_label X D) T)) X0) = (subst_label X (subst_tt X (typ_label X D) (open_tt T X0))).\nProof with auto.\n  intros.\n  rewrite <- subst_label_open_tt_var...\n  f_equal...\n  rewrite subst_tt_open_tt_var...\nQed.  \n\n\nLemma binds_subst_label_existial : forall E X Y T U,\n    binds X (bind_sub U) (map (drop_label Y) (map (subst_tb Y (typ_label Y T)) E)) ->\n    exists Q,\n      binds X (bind_sub Q) E.\nProof with auto.\n  induction E;intros;simpl in *...\n  analyze_binds H...\n  destruct a.\n  analyze_binds H...\n  2: {\n    destruct IHE with (X:=X) (Y:=Y) (U:=U) (T:=T)...\n    exists x...\n  }  \n  destruct b;simpl in *.\n  dependent destruction BindsTacVal.\n  exists t...\n  inversion BindsTacVal.\nQed.\n\nLemma WF_narrowing_env_subst_inv: forall E1 E2 (X:atom) Y S,\n    WF (map (subst_tb Y S) E1 ++ Y ~ bind_sub typ_top ++ E2) X ->\n    WF (E1 ++ Y ~ bind_sub typ_top ++ E2) X.\nProof with auto.\n  induction E1;intros...\n  simpl in *.\n  destruct a.\n  dependent destruction H...\n  analyze_binds H...\n  -\n    destruct b.\n    apply WF_var with (U:=t)...\n    simpl in *.\n    inversion BindsTacVal...\n  -\n    rewrite_env (nil ++ (a~ b) ++ E1 ++ (Y, bind_sub typ_top) :: E2).\n    apply WF_weakening...\n    apply IHE1  with (S:=S)...\n    apply WF_var with (U:=U)...\n  -\n    apply WF_var with (U:=typ_top)...\n  -\n    apply WF_var with (U:=U)...\nQed.   \n\nLemma binds_subst_extensial: forall E S T X0 X U,\n    binds X0 (bind_sub U) (map (subst_tb X S) E) ->\n    exists A,\n      binds X0 (bind_sub A) (map (subst_tb X T) E).\nProof with auto.\n  induction E;intros...\n  simpl in *.\n  analyze_binds H.\n  simpl in *.\n  destruct a.\n  analyze_binds H.\n  -\n    destruct b;simpl in *; inversion BindsTacVal.\n    exists (subst_tt X T t)...\n  -\n    apply IHE with (T:=T) in BindsTac...\n    destruct_hypos.\n    exists x...\nQed.\n\nLemma WF_narrowing_env: forall E1 E E2 A S T X,\n    WF (E1 ++ map (subst_tb X S) E ++ E2) A ->\n    WF (E1 ++ map (subst_tb X T) E ++ E2) A.\nProof with auto.\n  intros.\n  dependent induction H;try solve [analyze_binds H;eauto]...\n  -\n    analyze_binds H; try solve [apply WF_var with (U:=U);auto].\n    apply binds_subst_extensial with (T:=T) in BindsTac0.\n    destruct_hypos.\n    apply WF_var with (U:=x)...\n  -\n    apply WF_all with (L:=L )...\n    apply IHWF with (S0:=S)...\n    intros.\n    rewrite_env ((X0 ~ bind_sub T1 ++ E1) ++ map (subst_tb X T) E ++ E2). \n    eapply H1 with (S0:=S)...\n  -\n    apply WF_rec with (L:=L );intros...\n    rewrite_env ((X0 ~ bind_sub typ_top ++ E1) ++ map (subst_tb X T) E ++ E2). \n    eapply H0 with (S0:=S)...\n    rewrite_env ((X0 ~ bind_sub typ_top ++ E1) ++ map (subst_tb X T) E ++ E2). \n    eapply H2 with (S0:=S)...\nQed.\n\nLemma sub_map_inv_var: forall X Y X0 C E1 E2, \n    X <> Y -> X0 <> Y ->\n  sub (map (subst_tb Y C) E1 ++ (Y, bind_sub typ_top) :: E2) X X0 ->\n  sub (map (subst_tb Y C) E1 ++ (Y, bind_sub typ_top) :: E2) X0 X ->\n  wf_env (E1 ++ (Y, bind_sub typ_top) :: E2) ->\n  sub (E1 ++ (Y, bind_sub typ_top) :: E2) X X0.\nProof with auto.\n  intros.\n  pose proof suba_sub_tvar_chain H1.\n  pose proof suba_sub_tvar_chain H2.\n  destruct H4 as [W1 ?].\n  destruct H5 as [W2 ?].\n  pose proof sub_tvar_chain_antisym H4 H5.\n  subst.\n  apply sa_fvar...\n  get_well_form.\n  apply WF_narrowing_env_subst_inv in H6...\nQed.\n\n\nLemma subst_label_collect3': forall T i X,\n    rt_type T -> type T ->\n    i `in` collectLabel T ->\n    i `in` collectLabel (subst_label X T).\nProof with auto.\n  intros.\n  induction H0;try solve [inversion H]...\n  simpl in *.\n  apply union_iff in H1. apply union_iff.\n  destruct H1...\nQed.  \n\n\nLemma subst_tt_collect2': forall T i X A,\n    i `in` collectLabel T ->\n    rt_type T ->\n    type T ->\n    i `in` collectLabel (subst_tt X A T).\nProof with auto.\n  intros.\n  induction H1;try solve [inversion H0]...\n  simpl in *.\n  apply union_iff in H. apply union_iff.\n  destruct H...\nQed.  \n\n\nLemma drop_label_reverse_wf: forall E1 E2 C D A X,\n    WF (map (drop_label X) (map (subst_tb X (typ_label X C)) E1) ++\n            (X, bind_sub typ_top) :: E2)\n       (subst_label X (subst_tt X (typ_label X D) A)) ->\n    X \\notin fl_tt A -> type D ->\n    WF (E1 ++ (X, bind_sub typ_top) :: E2) A.\nProof with auto.\n  intros.\n  assert (type A) as HA.\n  get_type...\n  rewrite drop_label_reverse_type in H... \n  apply type_to_rec in HA.\n  generalize dependent E1.\n  generalize dependent E2.\n  generalize dependent C.\n  generalize dependent D.\n  generalize dependent X.\n  induction HA;intros;simpl in *;try solve [dependent destruction H;auto]...\n  -\n    destruct (X==X0);subst...\n    +\n      apply WF_var with (U:=typ_top)...\n    +\n      simpl in H...\n      dependent destruction H...\n      analyze_binds H...\n      apply binds_subst_label_existial in BindsTac.\n      destruct_hypos.\n      apply WF_var with (U:=x)...\n      apply WF_var with (U:=U)...\n  -\n    dependent destruction H.\n    constructor...\n    apply IHHA1 with (C:=C) (D:=D)...\n    apply IHHA2 with (C:=C) (D:=D)...\n  -\n    dependent destruction H5.\n    apply WF_rec with (L:=L \\u L0 \\u {{X}});intros...\n    +\n      rewrite_env ((X0 ~ bind_sub typ_top ++ E1) ++ (X, bind_sub typ_top) :: E2).\n      apply H2 with (C:=C) (D:=D)...\n      solve_notin.\n      rewrite <- subst_tt_open_tt_var...\n      rewrite  subst_label_open_tt_var...\n      apply H5...\n    +\n      rewrite_env ((X0 ~ bind_sub typ_top ++ E1) ++ (X, bind_sub typ_top) :: E2).\n      apply H0 with (C:=C) (D:=D)...\n      solve_notin.\n      rewrite <- label_transform3...\n      apply H6...\n  -\n    dependent destruction H3.\n    apply WF_all with (L:=L \\u L0 \\u {{X}});intros...\n    +\n      apply IHHA with (C:=C) (D:=D)...\n    +\n      rewrite_env ((X0 ~ bind_sub T1 ++ E1) ++ (X, bind_sub typ_top) :: E2).\n      apply H0 with (C:=C) (D:=D)...\n      solve_notin.\n      rewrite <- label_transform4...\n      simpl.\n      rewrite drop_label_reverse_type...\n      assert (T1 = subst_label X (subst_tt X (typ_label X D) T1)).\n      rewrite drop_label_reverse_type ...\n      rewrite H6.\n      apply H4...\n  -\n    destruct (l==X);subst...\n    +\n      apply notin_union  in H0.\n      destruct_hypos.\n      apply test_solve_notin_7 in H0.\n      destruct H0.\n    +\n      dependent destruction H.\n      constructor...\n      apply IHHA with (C:=C) (D:=D)...\n  -\n    dependent destruction H2... \n    apply WF_rcd_cons...\n    + apply IHHA1 with (D:=D) (C:=C)...\n    + apply IHHA2 with (D:=D) (C:=C)...\n    + intros Hc.\n      apply H3.\n      apply subst_label_collect3' with (X:=X)...\n      { apply Infrastructure.subst_tt_rt_type... }\n      { apply subst_tt_type... apply type4rec_to_type... }\n      apply subst_tt_collect2'...\n      apply type4rec_to_type...\nQed.\n\n    \nLemma WF_nominal_inversion: forall E1 E2 X A (X0:atom) D C,\n    WF (X0 ~ bind_sub typ_top ++\n           map (subst_tb X (typ_label X (open_tt C X))) E1 ++ (X, bind_sub typ_top) :: E2)\n          (open_tt (subst_tt X (typ_label X (open_tt D X)) A) X0)->\n    X \\notin {{X0}} \\u fl_tt A  ->\n    wf_env (X0 ~ bind_sub typ_top ++\n           map (subst_tb X (typ_label X (open_tt C X))) E1 ++ (X, bind_sub typ_top) :: E2) ->\n    type (open_tt D X) ->\n    WF (X0 ~ bind_sub typ_top ++ E1 ++ (X, bind_sub typ_top) :: E2) (open_tt A X0) .\nProof with auto.\n  intros.\n  rewrite subst_tt_open_tt_var in H...\n  rewrite_env ((X0 ~ bind_sub typ_top ++\n           map (subst_tb X (typ_label X (open_tt C X))) E1) ++ (X, bind_sub typ_top) :: E2) in H.\n  apply WF_drop_label in H...\n  simpl in H...\n  rewrite_env ((X0 ~ bind_sub typ_top ++ E1) ++ (X, bind_sub typ_top) :: E2).\n  apply drop_label_reverse_wf with (C:=open_tt C X) (D:=open_tt D X)...\n  solve_notin.\nQed.\n\nLtac inv_rt :=\n  try solve [\n    repeat match goal with\n    | [ H : rt_type ?T |- _ ] => inversion H;clear H\n    end\n      ].\n\nLemma Tlookup_first_element: forall i T1 T2,\n    Tlookup i (typ_rcd_cons i T1 T2) = Some T1.\nProof with auto.\n  intros.\n  simpl.\n  destruct (i==i);subst...\n  destruct n...\nQed.\n\nLemma dropLable_notin: forall T2 i E,\n    WF E T2 ->\n    rt_type T2 ->\n    i `notin` collectLabel T2 ->\n    dropLabel i T2 = T2.\nProof with eauto.\n  intros.\n  induction H;try solve [inversion H0]...\n  simpl in *.\n  destruct (i0==i);subst...\n  apply notin_union in H1.\n  destruct_hypos.\n  apply test_solve_notin_7 in H1...\n  destruct H1.\n  f_equal...\nQed.\n\nLemma dropLabel_first_element: forall E i T1 T2,\n    WF E (typ_rcd_cons i T1 T2) ->\n    dropLabel i (typ_rcd_cons i T1 T2) = T2.\nProof with auto.\n  intros.\n  dependent destruction H...\n  simpl...\n  destruct (i==i)...\n  apply dropLable_notin with (E:=E)...\n  destruct n...\nQed.\n\nLemma dom_add_subset: forall a E T,\n    a \\notin E \\u T ->\n    add a E [<=] add a T ->\n    E [<=] T.\nProof with auto.\n  intros.\n  unfold \"[<=]\" in *.\n  intros.\n  specialize (H0 a0).\n  assert (a0 \\in add a E).\n  apply AtomSetImpl.add_2...\n  apply H0 in H2.\n  apply KeySetProperties.FM.add_iff in H2...\n  destruct H2...\n  subst...\n  assert (False).\n  apply H...\n  destruct H2.\nQed.\n\nLemma dom_notin_in: forall (X Y:atom) E,\n    X \\notin E ->\n    Y \\in E ->\n          X <> Y.\nProof with auto.\n  intros...\n  unfold \"\\notin\" in *...\n  intros.\n  apply H...\n  subst...\nQed.\n\nLemma union_swap_assoc: forall A B C,\n    A \\u B \\u C [=] B \\u A \\u C.\nProof with auto.\n  intros.\n  rewrite <- AtomSetProperties.union_assoc...\n  rewrite <- AtomSetProperties.union_assoc...\n  assert (union A B [=] union B A).\n  apply AtomSetProperties.union_sym...\n  rewrite H...\n  apply AtomSetProperties.equal_refl...\nQed.\n\n\nLemma drop_collect_flip: forall E A i,\n    WF E A ->\n    rt_type A ->\n    i \\in collectLabel A ->\n    {{i}} \\u collectLabel (dropLabel i A) [=] collectLabel A.\nProof with auto.\n  intros.\n  induction H;try solve [inversion H0]...\n  -\n    simpl in *.\n    apply empty_iff in H1.\n    destruct H1.\n  -\n    simpl in *...\n    destruct (i0==i);subst.\n    +\n      apply KeySetProperties.union_equal_2...\n      rewrite <- notin_drop_collect_self...\n      apply AtomSetProperties.equal_refl...\n    +\n      simpl in *.\n      rewrite union_swap_assoc...\n      apply KeySetProperties.union_equal_2...\n      apply IHWF2...\n      apply AtomSetImpl.union_1 in H1.\n      destruct H1...\n      apply AtomSetImpl.singleton_1 in H1...\n      destruct n...\nQed.\n    \nLemma record_permutation: forall S2 T2 E i j T1 S1,\n    equiv E (typ_rcd_cons i T1 T2) (typ_rcd_cons j S1 S2) ->\n    j \\in collectLabel (typ_rcd_cons i T1 T2) /\\\n          (exists T0, Tlookup j (typ_rcd_cons i T1 T2) = Some T0 /\\ equiv E T0 S1) /\\\n          equiv E (dropLabel j (typ_rcd_cons i T1 T2)) S2.\nProof with auto.\n  unfold equiv.\n  intros.\n  destruct_hypos.\n  dependent destruction H.\n  dependent destruction H6.\n  destruct (j==i);subst...\n  -\n    repeat split...\n    +\n      apply label_belong with (B:=T1)...\n      apply Tlookup_first_element...\n    +\n      exists T1.\n      repeat split...\n      apply Tlookup_first_element...\n      apply H5 with (i0:=i)...\n      apply Tlookup_first_element...\n      apply Tlookup_first_element...\n      apply H12 with (i0:=i)...\n      apply Tlookup_first_element...\n      apply Tlookup_first_element...\n    +\n      rewrite dropLabel_first_element with (E:=E)...\n      dependent destruction H3.\n      dependent destruction H6.\n      dependent destruction H3;dependent destruction H6.\n      *\n        apply Reflexivity...\n      *\n        simpl in H2...\n        simpl in H7.\n        rewrite <- KeySetProperties.add_union_singleton in H2.\n        rewrite <- KeySetProperties.add_union_singleton in H2.\n        rewrite <- KeySetProperties.add_union_singleton in H2.\n        apply dom_add_subset in H2...\n        rewrite KeySetProperties.add_union_singleton in H2.\n        apply union_empty in H2...\n        destruct H2.\n      *\n        simpl in H12...\n        simpl in H4.\n        rewrite <- KeySetProperties.add_union_singleton in H12.\n        rewrite <- KeySetProperties.add_union_singleton in H12.\n        rewrite <- KeySetProperties.add_union_singleton in H12.\n        apply dom_add_subset in H12...\n        rewrite KeySetProperties.add_union_singleton in H12.\n        apply union_empty in H12...\n        destruct H12.\n      *\n        constructor...\n        --\n          simpl in *...\n          rewrite <- KeySetProperties.add_union_singleton in H2.\n          rewrite <- KeySetProperties.add_union_singleton in H2.\n          rewrite <- KeySetProperties.add_union_singleton in H2.\n          rewrite <- KeySetProperties.add_union_singleton in H2.\n          apply dom_add_subset in H2...\n          rewrite <- KeySetProperties.add_union_singleton.\n          rewrite <- KeySetProperties.add_union_singleton...\n        --\n          intros.\n          apply H5 with (i2:=i2)...\n          ++\n            assert (Hq1:=H3).\n            assert (Hq2:=H6).\n            apply label_belong in Hq1.\n            apply label_belong in Hq2.\n            apply dom_notin_in with (X:=i) in Hq1...\n            apply dom_notin_in with (X:=i) in Hq2...\n            simpl...\n            destruct (i==i2);subst...\n            destruct Hq1...\n          ++\n            assert (Hq1:=H3).\n            assert (Hq2:=H6).\n            apply label_belong in Hq1.\n            apply label_belong in Hq2.\n            apply dom_notin_in with (X:=i) in Hq1...\n            apply dom_notin_in with (X:=i) in Hq2...\n            simpl...\n            destruct (i==i2);subst...\n            destruct Hq1...\n    +\n      rewrite dropLabel_first_element with (E:=E)...\n      dependent destruction H3.\n      dependent destruction H6.\n      dependent destruction H3;dependent destruction H6.\n      *\n        apply Reflexivity...\n      *\n        simpl in H2...\n        simpl in H7.\n        rewrite <- KeySetProperties.add_union_singleton in H2.\n        rewrite <- KeySetProperties.add_union_singleton in H2.\n        rewrite <- KeySetProperties.add_union_singleton in H2.\n        apply dom_add_subset in H2...\n        rewrite KeySetProperties.add_union_singleton in H2.\n        apply union_empty in H2...\n        destruct H2.\n      *\n        simpl in H12...\n        simpl in H4.\n        rewrite <- KeySetProperties.add_union_singleton in H12.\n        rewrite <- KeySetProperties.add_union_singleton in H12.\n        rewrite <- KeySetProperties.add_union_singleton in H12.\n        apply dom_add_subset in H12...\n        rewrite KeySetProperties.add_union_singleton in H12.\n        apply union_empty in H12...\n        destruct H12.\n      *\n        constructor...\n        --\n          simpl in *...\n          rewrite <- KeySetProperties.add_union_singleton in H12.\n          rewrite <- KeySetProperties.add_union_singleton in H12.\n          rewrite <- KeySetProperties.add_union_singleton in H12.\n          rewrite <- KeySetProperties.add_union_singleton in H12.\n          apply dom_add_subset in H12...\n          rewrite <- KeySetProperties.add_union_singleton.\n          rewrite <- KeySetProperties.add_union_singleton...\n        --\n          intros.\n          apply H14 with (i2:=i2)...\n          ++\n            assert (Hq1:=H3).\n            assert (Hq2:=H6).\n            apply label_belong in Hq1.\n            apply label_belong in Hq2.\n            apply dom_notin_in with (X:=i) in Hq1...\n            apply dom_notin_in with (X:=i) in Hq2...\n            simpl...\n            destruct (i==i2);subst...\n            destruct Hq1...\n          ++\n            assert (Hq1:=H3).\n            assert (Hq2:=H6).\n            apply label_belong in Hq1.\n            apply label_belong in Hq2.\n            apply dom_notin_in with (X:=i) in Hq1...\n            apply dom_notin_in with (X:=i) in Hq2...\n            simpl...\n            destruct (i==i2);subst...\n            destruct Hq1...\n  -\n    simpl in H2...\n    assert (j \\in collectLabel T2) as Hj.\n    {\n      assert (j `in` collectLabel (typ_rcd_cons i T1 T2)) as HH.\n      auto.\n      simpl in HH.\n      apply AtomSetImpl.union_1 in HH...\n      destruct HH...\n      apply AtomSetImpl.singleton_1 in H13.\n      destruct n...\n    }    \n    repeat split...\n    +\n      apply lookup_some in Hj...\n      destruct Hj.\n      exists x...\n      repeat split...\n      *\n        simpl...\n        destruct (i==j);subst...\n        destruct n...\n      *\n        apply H5 with (i0:=j)...\n        simpl...\n        destruct (i==j);subst...\n        destruct n...\n        simpl...\n        destruct (j==j);subst...\n        destruct n0...\n      *\n        apply H12 with (i0:=j)...\n        simpl...\n        destruct (j==j);subst...\n        destruct n0...\n        simpl...\n        destruct (i==j);subst...\n        destruct n...        \n    +\n      dependent destruction H3.\n      dependent destruction H5.\n      constructor...\n      *\n        apply rt_type_drop with (E:=E)...\n      *\n        simpl in *.\n        destruct (i==j);subst...\n        destruct n...\n        clear H7 H14.\n        simpl.\n        apply dom_add_subset with (a:=j)...\n        solve_notin.\n        apply notin_drop_self...\n        rewrite  KeySetProperties.add_union_singleton.\n        rewrite  KeySetProperties.add_union_singleton...\n        rewrite union_swap_assoc...\n        rewrite drop_collect_flip with (E:=E)...\n      *\n        apply WF_drop...\n      *\n        intros.\n        apply H7 with (i0:=i0)...\n        --\n          apply Tlookup_drop in H15...\n        --\n          assert (Ht:=H16).\n          apply label_belong in Ht.\n          apply dom_notin_in with (Y:=i0) in H6...\n          simpl...\n          destruct (j==i0);subst...\n          destruct H6...\n    +\n      dependent destruction H3.\n      dependent destruction H5.\n      constructor...\n      *\n        apply rt_type_drop with (E:=E)...\n      *\n        simpl in *.\n        destruct (i==j);subst...\n        destruct n...\n        clear H7 H14.\n        simpl.\n        apply dom_add_subset with (a:=j)...\n        solve_notin.\n        apply notin_drop_self...\n        rewrite  KeySetProperties.add_union_singleton.\n        rewrite  KeySetProperties.add_union_singleton...\n        rewrite union_swap_assoc...\n        rewrite drop_collect_flip with (E:=E)...\n      *\n        apply WF_drop...\n      *\n        intros.\n        apply H14 with (i0:=i0)...\n        --\n          assert (Ht:=H15).\n          apply label_belong in Ht.\n          apply dom_notin_in with (Y:=i0) in H6...\n          simpl...\n          destruct (j==i0);subst...\n          destruct H6...       \n        --\n          apply Tlookup_drop in H16...\nQed.      \n\n\nLemma lookup_some_in_fl_tt : forall i A x E,\n    WF E A -> rt_type A ->\n    Tlookup i A = Some x->\n    fl_tt x [<=] fl_tt A.\nProof with auto.\n  intros.\n  induction H;try solve [inversion H0]...\n  inversion H1...\n  simpl in *.\n  destruct (i0==i);subst...\n  inversion H1;subst...\n  rewrite union_swap_assoc...\n  apply KeySetProperties.union_subset_1...\n  apply IHWF2 in H1...\n  rewrite KeySetProperties.union_sym...\n  apply union_subset_6...\n  rewrite KeySetProperties.union_sym...\n  apply union_subset_6...\nQed.\n\nLemma lookup_some_subst: forall i A T E X B,\n    WF E A -> rt_type A ->\n    Tlookup i A = Some T->\n    Tlookup i (subst_tt X B A) = Some (subst_tt X B T).\nProof with auto.\n  intros.\n  induction H;try solve [inversion H0]...\n  inversion H1...\n  simpl in *.\n  destruct (i0==i);subst...\n  inversion H1...\nQed.\n\nLemma fl_tt_dropLabel : forall E i T,\n    WF E T -> rt_type T ->\n    fl_tt (dropLabel i T) [<=] fl_tt T.\nProof with auto.\n  intros.\n  induction H;try solve [inversion H0]...\n  simpl in *...\n  apply AtomSetProperties.FM.Subset_refl...\n  simpl in *...\n  destruct (i0==i);subst...\n  -\n    apply IHWF2 in H2...\n    rewrite KeySetProperties.union_sym...\n    apply union_subset_6...\n    rewrite KeySetProperties.union_sym...\n    apply union_subset_6...\n  -\n    simpl in *.\n    apply union_subset_x...\n    apply union_subset_x...\nQed.\n\nLemma subst_tt_rcd_cons: forall i X B A D,\n    typ_rcd_cons i (subst_tt X D A) (subst_tt X D B) = subst_tt X D (typ_rcd_cons i A B).\nProof with auto.\n  intros...\nQed.\n\nLemma subst_tt_collectLabel_in: forall E T X i D,\n    WF E T -> rt_type T ->\n    i \\in  collectLabel T ->\n           i `in` collectLabel (subst_tt X D T).\nProof with auto.\n  intros.\n  induction H;try solve [inversion H0]...\n  simpl in *...\n  apply AtomSetImpl.union_1 in H1.\n  destruct H1...\nQed.\n\nLemma subst_tt_dropLabel: forall i T X A E,\n    WF E T -> rt_type T ->\n    subst_tt X A (dropLabel i T) = dropLabel i (subst_tt X A T).\nProof with auto.\n  intros.\n  induction H;try solve [inversion H0]...\n  simpl in *...\n  destruct (i0==i);subst...\n  simpl...\n  f_equal...\nQed.  \n\nLemma dropLabel_fv_tt : forall E T A i,\n    WF E T -> rt_type T ->\n    Tlookup i T = Some A ->\n    fv_tt T [=] union (fv_tt A) (fv_tt (dropLabel i T)).\nProof with auto.\n  intros.\n  induction H;try solve [inversion H0]...\n  simpl in *...\n  inversion H1...\n  simpl in *.\n  destruct (i0==i);subst...\n  -\n    rewrite dropLable_notin with (E:=E)...\n    inversion H1;subst...\n    apply KeySetProperties.equal_refl...\n  -\n    simpl...\n    apply IHWF2 in H1...\n    rewrite H1.\n    rewrite union_swap_assoc...\n    apply KeySetProperties.equal_refl...\nQed.    \n      \nLemma subst_reverse_equiv: forall A,\n    type4rec A -> forall B, type4rec B ->\n    forall X C D E1 E2 S,\n    X \\notin fl_tt A \\u fl_tt B \\u fv_tt S \\u fv_tt C \\u fv_tt D->\n    equiv (map (subst_tb X (typ_label X (open_tt S X))) E1 ++ (X, bind_sub typ_top) :: E2 ) (subst_tt X (typ_label X (open_tt C X)) A) (subst_tt X (typ_label X (open_tt D X)) B) ->\n    equiv (E1 ++ (X, bind_sub typ_top) :: E2) A B ->\n    WF ((X, bind_sub typ_top) :: E2) (open_tt C X) ->\n    WF ((X, bind_sub typ_top) :: E2) (open_tt D X) ->\n    WF ((X, bind_sub typ_top) :: E2) (open_tt S X) ->\n    wf_env (E1 ++ (X, bind_sub typ_top) :: E2) ->\n    (equiv ((X, bind_sub typ_top) ::E2) (open_tt C X)  (open_tt D X) \\/ (X \\notin fv_tt A \\u fv_tt B )) .\nProof with auto.\n  unfold equiv.\n  intros A HA;induction HA;\n    intros B HB;induction HB;intros;destruct_hypos;simpl in *;try solve [\n      inversion H0;inv_rt|\n      inversion H1;inv_rt|\n      inversion H2;inv_rt|\n      inversion H3;inv_rt|\n      inversion H4;inv_rt|\n      inversion H5;inv_rt|\n      inversion H6;inv_rt|\n      inversion H7;inv_rt|\n      inversion H8;inv_rt|\n      inversion H9;inv_rt|\n      inversion H10;inv_rt|\n      destruct (X==X0);subst;auto;inversion H0;inv_rt]...\n  - destruct (X==X1);destruct (X0==X1);subst...\n    +\n      dependent destruction H0;inv_rt.\n      dependent destruction H7;inv_rt.\n      left.\n      apply wf_env_cons in H5...\n      apply sub_strengthening_env in H0...\n      apply sub_strengthening_env in H7...\n    +\n      inversion H0;inv_rt...\n    +\n      inversion H7;inv_rt...\n  -\n    dependent destruction H0;inv_rt.\n    dependent destruction H7;inv_rt.\n    dependent destruction H1;inv_rt.\n    dependent destruction H6;inv_rt.\n    clear IHHB1 IHHB2.\n    destruct IHHA1 with (B:=T0) (X:=X) (C:=C) (D:=D) (E1:=E1) (E2:=E2) (S:=S)...\n    destruct IHHA2 with (B:=T3) (X:=X) (C:=C) (D:=D) (E1:=E1) (E2:=E2) (S:=S)...\n  -\n    clear H4 H6.\n    dependent destruction H8;inv_rt.\n    dependent destruction H15;inv_rt.\n    dependent destruction H12;inv_rt.\n    dependent destruction H15;inv_rt.\n    pick fresh Y.\n    assert (type (open_tt C X)) by (get_type;auto).\n    assert (type (open_tt D X)) by (get_type;auto).\n    destruct H0 with (X:=Y) (X0:=X) (B:=open_tt T0 (typ_label Y (open_tt T0 Y))) (C:=C) (D:=D) (E1:=Y~bind_sub typ_top ++E1) (E2:=E2) (S:=S)...\n    +\n      solve_notin.\n    +\n      split.\n      *\n        rewrite_env (Y ~ bind_sub typ_top ++\n                     map (subst_tb X (typ_label X (open_tt S X))) E1 ++ (X, bind_sub typ_top) :: E2).\n      rewrite subst_tt_open_tt_twice...\n      rewrite subst_tt_open_tt_twice...\n      *\n        rewrite_env (Y ~ bind_sub typ_top ++\n                     map (subst_tb X (typ_label X (open_tt S X))) E1 ++ (X, bind_sub typ_top) :: E2).\n      rewrite subst_tt_open_tt_twice...\n      rewrite subst_tt_open_tt_twice...\n    +\n      split.\n      *\n        apply H14...\n      *\n        apply H17...\n    +      \n      rewrite_env (Y ~ bind_sub typ_top ++ E1 ++ (X, bind_sub typ_top) :: E2)...\n    +\n      right.\n      apply notin_union in H24.\n      destruct_hypos.\n      apply notin_fv_open_inv in H24.\n      apply notin_fv_open_inv in H25...\n  -    \n    clear H2 IHHB.\n    dependent destruction H4;inv_rt.\n    dependent destruction H11;inv_rt.\n    dependent destruction H5;inv_rt.\n    dependent destruction H10;inv_rt.\n    destruct IHHA with (B:=T0) (X:=X) (C:=C) (D:=D) (E1:=E1) (E2:= E2) (S:=S)...\n    clear IHHA.\n    pick fresh Y.\n    destruct H0 with (B:=open_tt T3 Y) (X:=Y) (X0:=X) (C:=C) (D:=D) (E1:=Y ~ bind_sub T1 ++E1) (E2:=E2) (S:=S);clear H0...\n    +\n      solve_notin.\n    +\n      split.\n      *\n        rewrite <- subst_tt_open_tt_var...\n        rewrite <- subst_tt_open_tt_var...\n        rewrite_env (nil ++ Y ~ bind_sub (subst_tt X (typ_label X (open_tt S X)) T1) ++ map (subst_tb X (typ_label X (open_tt S X))) E1 ++ (X, bind_sub typ_top) :: E2).\n        apply sub_narrowing with (Q:=subst_tt X (typ_label X (open_tt D X)) T0)...\n        --\n          clear Fr.\n          assert (subst_tt X (typ_label X (open_tt D X)) T0 = subst_tt X (typ_label X (open_tt S X)) T0).\n          {\n            rewrite <- subst_tt_fresh...\n            rewrite <- subst_tt_fresh...\n          }\n          rewrite H0.\n          assert (equiv (X ~ bind_sub typ_top ++ E2) (typ_label X (open_tt S X)) (typ_label X (open_tt S X))).\n          {\n            apply wf_env_cons in H10.\n            unfold equiv;split;constructor;\n            apply Reflexivity...\n          }\n          apply equiv_sub_subst...\n        --\n          apply H2...\n        --\n          get_type...\n        --\n          get_type...\n      *\n        rewrite <- subst_tt_open_tt_var...\n        rewrite <- subst_tt_open_tt_var...\n        rewrite_env (nil ++ Y ~ bind_sub (subst_tt X (typ_label X (open_tt S X)) T1) ++ map (subst_tb X (typ_label X (open_tt S X))) E1 ++ (X, bind_sub typ_top) :: E2).\n        apply sub_narrowing with (Q:=subst_tt X (typ_label X (open_tt C X)) T1)...\n        --\n          clear Fr.\n          assert (subst_tt X (typ_label X (open_tt C X)) T1 = subst_tt X (typ_label X (open_tt S X)) T1).\n          {\n            rewrite <- subst_tt_fresh...\n            rewrite <- subst_tt_fresh...\n          }\n          rewrite H0.\n          assert (equiv (X ~ bind_sub typ_top ++ E2) (typ_label X (open_tt S X)) (typ_label X (open_tt S X))).\n          {\n            apply wf_env_cons in H10.\n            unfold equiv;split;constructor;\n            apply Reflexivity...\n          }\n          apply equiv_sub_subst_refl...\n          get_well_form...\n        --\n          apply H4...\n        --\n          get_type...\n        --\n          get_type...\n    +\n      split.\n      *\n        rewrite_env (nil ++ Y ~ bind_sub T1 ++ E1 ++ (X, bind_sub typ_top) :: E2).\n        apply sub_narrowing with (Q:=T0)...\n        apply H5...\n      *\n        rewrite_env (Y ~ bind_sub T1 ++ E1 ++ (X, bind_sub typ_top) :: E2).\n        apply H6...        \n    +\n      rewrite_env (Y ~ bind_sub T1 ++ E1 ++ (X, bind_sub typ_top) :: E2)...\n      constructor...\n      get_well_form...\n    +\n      right.\n      apply notin_union in H12.\n      destruct_hypos.\n      apply notin_fv_open_inv in H0.\n      apply notin_fv_open_inv in H12.\n      solve_notin.\n  -\n    dependent destruction H0;inv_rt...\n    dependent destruction H7;inv_rt...\n    dependent destruction H1;inv_rt.\n    dependent destruction H6;inv_rt.\n    clear IHHB.\n    destruct IHHA with (B:=A0) (X:=X) (C:=C) (D:=D) (E1:=E1) (E2:=E2) (S:=S)...\n  -\n    dependent destruction H2...\n    collect_nil H5.\n  -\n    dependent destruction H7...\n    collect_nil H6.\n  -\n    clear IHHB1 IHHB2.\n    assert (equiv (E1 ++ (X, bind_sub typ_top) :: E2) (typ_rcd_cons i0 T0 T3)  (typ_rcd_cons i T1 T2)) as HE.\n    { unfold equiv;split... }\n    apply record_permutation in HE...\n    unfold equiv in *.\n    destruct_hypos.\n    destruct IHHA1 with (B:=x) (X:=X) (E1:=E1) (E2:=E2) (C:=C) (D:=D) (S:=S)...\n    +\n      apply type_to_rec.\n      get_type...\n    +\n      solve_notin.\n      apply lookup_some_in_fl_tt with (E:=(E1 ++ (X, bind_sub typ_top) :: E2)) in H11...\n      simpl in *.\n      apply notin_partial with (E2:=union (singleton i0) (union (fl_tt T0) (fl_tt T3)))...\n      get_well_form...\n    +\n      split.\n      *\n        clear IHHA1 IHHA2 H9.\n        dependent destruction H2.\n        apply H8 with (i1:=i)...\n        --\n          simpl...\n          destruct (i==i);subst...\n          destruct n...\n        --\n          rewrite subst_tt_rcd_cons...\n          apply lookup_some_subst with (E:=(E1 ++ (X, bind_sub typ_top) :: E2))...\n          get_well_form...\n      *\n        clear IHHA1 IHHA2 H2.\n        dependent destruction H9.\n        apply H8 with (i1:=i)...\n        --\n          rewrite subst_tt_rcd_cons...\n          apply lookup_some_subst with (E:=(E1 ++ (X, bind_sub typ_top) :: E2))...\n          get_well_form...\n        --\n          simpl...\n          destruct (i==i);subst...\n          destruct n...\n    +\n      destruct IHHA2 with (B:=dropLabel i (typ_rcd_cons i0 T0 T3)) (X:=X) (E1:=E1) (E2:=E2) (C:=C) (D:=D) (S:=S)...\n      *\n        apply type_to_rec.\n        get_type...\n      *\n        solve_notin.\n        destruct (i0==i);subst...\n        --\n          apply notin_partial with (E2:=fl_tt T3)...\n          apply fl_tt_dropLabel with (E:=(E1 ++ (X, bind_sub typ_top) :: E2))...\n          get_well_form...\n          dependent destruction H30...\n        --\n          simpl.\n          solve_notin.\n          apply notin_partial with (E2:=fl_tt T3)...\n          apply fl_tt_dropLabel with (E:=(E1 ++ (X, bind_sub typ_top) :: E2))...\n          get_well_form...\n          dependent destruction H25...\n      *\n        clear IHHA1 IHHA2.\n        split.\n        --\n          clear H9.\n          dependent destruction H2.\n          constructor...\n          ++\n            apply subst_tt_rt_type with (E:=E1 ++ (X, bind_sub typ_top) :: E2)...\n            rewrite_env (nil ++ E1 ++ (X, bind_sub typ_top) :: E2).\n            apply WF_weakening...\n            get_well_form...\n          ++\n            apply subst_tt_rt_type with (E:=E1 ++ (X, bind_sub typ_top) :: E2)...\n            rewrite_env (nil ++ E1 ++ (X, bind_sub typ_top) :: E2).\n            apply WF_weakening...\n            apply rt_type_drop with (E:=E1 ++ (X, bind_sub typ_top) :: E2)...\n            get_well_form...\n            apply WF_drop...\n            get_well_form...\n          ++\n            simpl in *...\n            destruct (i0==i);subst...\n            **\n              apply union_subset_x2 in H5...\n              apply KeySetFacts.Subset_trans with (s':=collectLabel (subst_tt X (typ_label X (open_tt D X)) T3))...\n              rewrite subst_tt_dropLabel with (E:= E1 ++ (X, bind_sub typ_top) :: E2)...\n              simpl...\n              apply drop_coolect_less...\n              get_well_form.\n              dependent destruction H31...\n              dependent destruction H7...\n            **\n              assert ( WF (E1 ++ (X, bind_sub typ_top) :: E2) T3).\n              {\n                get_well_form.\n                dependent destruction H33...\n              }              \n              simpl in *...\n              rewrite subst_tt_dropLabel with (E:= E1 ++ (X, bind_sub typ_top) :: E2)...\n              apply union_subset_x2 with (a:=i).\n              rewrite union_swap_assoc...\n              rewrite drop_collect_flip with (E:=E1 ++ (X, bind_sub typ_top) :: E2) ...\n              apply subst_tt_wf...\n              rewrite_env (nil ++ E1 ++ (X, bind_sub typ_top) :: E2).\n              apply WF_weakening...\n              apply subst_tt_rt_type with (E:=E1 ++ (X, bind_sub typ_top) :: E2)...\n              rewrite_env (nil ++ E1 ++ (X, bind_sub typ_top) :: E2).\n              apply WF_weakening...\n              apply subst_tt_collectLabel_in with (E:=E1 ++ (X, bind_sub typ_top) :: E2)...\n              apply  union_iff in H15.\n              destruct H15...\n              apply F.singleton_iff in H15...\n              destruct n...\n              solve_notin.\n              apply notin_drop_self...\n          ++\n            rewrite_env (nil ++ map (subst_tb X (typ_label X (open_tt S X))) E1 ++ (X, bind_sub typ_top) :: E2).\n            apply WF_narrowing_env with (S:=typ_label X (open_tt C X)).\n            simpl.\n            apply subst_tb_wf2 with (Q:=bind_sub typ_top)...\n            get_well_form...\n          ++\n            rewrite_env (nil ++ map (subst_tb X (typ_label X (open_tt S X))) E1 ++ (X, bind_sub typ_top) :: E2).\n            apply WF_narrowing_env with (S:=typ_label X (open_tt D X)).\n            apply subst_tb_wf2 with (Q:=bind_sub typ_top)...\n            get_well_form...\n          ++\n            intros.\n            assert (Ht:=H23).\n            apply label_belong in Ht.\n            simpl...\n            apply H8 with (i1:=i1)...\n            **\n              rewrite subst_tt_dropLabel with (E:=E1 ++ (X, bind_sub typ_top) :: E2) in Ht...\n              apply dom_notin_in with (X:=i) in Ht...\n              simpl...\n              destruct (i==i1);subst...\n              destruct Ht...\n              apply notin_drop_self...\n              get_well_form...\n            **\n              rewrite subst_tt_dropLabel with (E:=E1 ++ (X, bind_sub typ_top) :: E2) in H23...\n              apply Tlookup_drop in H23...\n              get_well_form...\n        --\n          clear H2.\n          dependent destruction H9.\n          constructor...\n          ++\n            apply subst_tt_rt_type with (E:=E1 ++ (X, bind_sub typ_top) :: E2)...\n            rewrite_env (nil ++ E1 ++ (X, bind_sub typ_top) :: E2).\n            apply WF_weakening...\n            apply rt_type_drop with (E:=E1 ++ (X, bind_sub typ_top) :: E2)...\n            get_well_form...\n            apply WF_drop...\n            get_well_form...\n          ++\n            apply subst_tt_rt_type with (E:=E1 ++ (X, bind_sub typ_top) :: E2)...\n            rewrite_env (nil ++ E1 ++ (X, bind_sub typ_top) :: E2).\n            apply WF_weakening...\n            get_well_form...\n          ++\n            simpl in *...\n            destruct (i0==i);subst...\n            **\n              get_well_form.\n              dependent destruction H30.\n              dependent destruction H32.\n              apply union_subset_x2 in H5...\n              rewrite subst_tt_dropLabel with (E:= E1 ++ (X, bind_sub typ_top) :: E2)...\n              rewrite dropLable_notin with (E:= E1 ++ (X, bind_sub typ_top) :: E2)...\n              apply subst_tt_wf...\n              rewrite_env (nil ++ E1 ++ (X, bind_sub typ_top) :: E2).\n              apply WF_weakening...\n              apply subst_tt_rt_type with (E:= E1 ++ (X, bind_sub typ_top) :: E2)...\n              rewrite_env (nil ++ E1 ++ (X, bind_sub typ_top) :: E2).\n              apply WF_weakening...\n              apply subst_tt_collect with (E:= E1 ++ (X, bind_sub typ_top) :: E2)...\n              apply subst_tt_collect with (E:= E1 ++ (X, bind_sub typ_top) :: E2)...\n            **\n              assert ( WF (E1 ++ (X, bind_sub typ_top) :: E2) T3).\n              {\n                get_well_form.\n                dependent destruction H33...\n              }              \n              simpl in *...\n              rewrite subst_tt_dropLabel with (E:= E1 ++ (X, bind_sub typ_top) :: E2)...\n              apply union_subset_x2 with (a:=i).\n              rewrite union_swap_assoc...\n              rewrite drop_collect_flip with (E:=E1 ++ (X, bind_sub typ_top) :: E2) ...\n              apply subst_tt_wf...\n              rewrite_env (nil ++ E1 ++ (X, bind_sub typ_top) :: E2).\n              apply WF_weakening...\n              apply subst_tt_rt_type with (E:=E1 ++ (X, bind_sub typ_top) :: E2)...\n              rewrite_env (nil ++ E1 ++ (X, bind_sub typ_top) :: E2).\n              apply WF_weakening...\n              apply subst_tt_collectLabel_in with (E:=E1 ++ (X, bind_sub typ_top) :: E2)...\n              apply  union_iff in H15.\n              destruct H15...\n              apply F.singleton_iff in H15...\n              destruct n...\n              solve_notin.\n              get_well_form.\n              dependent destruction H32.\n              apply subst_tt_collect with (E:= E1 ++ (X, bind_sub typ_top) :: E2)...\n          ++\n            rewrite_env (nil ++ map (subst_tb X (typ_label X (open_tt S X))) E1 ++ (X, bind_sub typ_top) :: E2).\n            apply WF_narrowing_env with (S:=typ_label X (open_tt D X)).\n            simpl.\n            apply subst_tb_wf2 with (Q:=bind_sub typ_top)...\n            get_well_form...\n          ++\n            rewrite_env (nil ++ map (subst_tb X (typ_label X (open_tt S X))) E1 ++ (X, bind_sub typ_top) :: E2).\n            apply WF_narrowing_env with (S:=typ_label X (open_tt C X)).\n            apply subst_tb_wf2 with (Q:=bind_sub typ_top)...\n            get_well_form...\n          ++\n            intros.\n            assert (Ht:=H22).\n            apply label_belong in Ht.\n            apply H8 with (i1:=i1)...\n            **\n              rewrite subst_tt_dropLabel with (E:=E1 ++ (X, bind_sub typ_top) :: E2) in H22...\n              apply Tlookup_drop in H22...\n              get_well_form...\n            **\n              rewrite subst_tt_dropLabel with (E:=E1 ++ (X, bind_sub typ_top) :: E2) in Ht...\n              apply dom_notin_in with (X:=i) in Ht...\n              simpl...\n              destruct (i==i1);subst...\n              destruct Ht...\n              apply notin_drop_self...\n              get_well_form...\n      *\n        clear IHHA1 IHHA2.\n        right.\n        simpl in *.\n        destruct (i0==i);subst.\n        --\n          inversion H11;subst.\n          get_well_form.\n          dependent destruction H26.\n          rewrite dropLable_notin  with (E:=E1 ++ (X, bind_sub typ_top) :: E2) in H34...\n        --\n          simpl in *.\n          assert (fv_tt T3 [=] fv_tt x \\u fv_tt (dropLabel i T3)).\n          {\n            rewrite <- dropLabel_fv_tt with (E:=E1 ++ (X, bind_sub typ_top) :: E2)...\n            apply  KeySetProperties.equal_refl...\n            get_well_form.\n            dependent destruction H26...\n          }\n          rewrite H18...\nQed.        \n", "meta": {"author": "juda", "repo": "dissertation-artifacts", "sha": "924adb42dac97d5fae9c288bf26808d3037d3aa0", "save_path": "github-repos/coq/juda-dissertation-artifacts", "path": "github-repos/coq/juda-dissertation-artifacts/dissertation-artifacts-924adb42dac97d5fae9c288bf26808d3037d3aa0/coq_fsub/coq_fsub_main/Reverse.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583270090337582, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.268264223218982}}
{"text": "From DeepWeb Require Export\n     Observe.\n\nCoFixpoint match_event {T R} (e0 : observeE R) (r : R) (m : itree oE T)\n  : itree oE T :=\n  match observe m with\n  | RetF x  => Ret x\n  | TauF m' => Tau (match_event e0 r m')\n  | VisF e k =>\n    match e with\n    | (||||oe) =>\n      match oe in observeE Y, e0 in observeE R return (Y -> _) -> R -> _ with\n      | Observe__Send c0, Observe__Send c =>\n        if (c0 =? c)%nat\n        then\n          fun k pkt =>\n            (* embed Log (\"Match Send \" ++ to_string pkt);; *)\n            k pkt\n        else fun _ _ =>\n               (* embed Log (\"Mismatch Send: expect to \" ++ to_string c *)\n               (*         ++ \", but observed to \" ++ to_string c0);; *)\n               throw \"Sent from different connection\"\n      | Observe__Select, Observe__Select =>\n        fun k cs =>\n          k cs\n      | Observe__Recv, Observe__Recv =>\n        fun k pkt =>\n          (* embed Log (\"Match Recv \" ++ to_string pkt);; *)\n          k pkt\n      | _, _ => fun _ _ => throw \"Unexpected event\"\n      end k r\n    | _ => vis e (match_event e0 r ∘ k)\n    end\n  end.\n\nDefinition match_observe {T R} (e : observeE T) (r : T) (l : list (itree oE R))\n  : list (itree oE R) := map (match_event e r) l.\n\nVariant genE : Type -> Set :=\n  Gen : connT -> genE packetT.\n\nClass Is__tE E `{genE -< E} `{nondetE -< E}\n      `{failureE -< E} `{logE -< E} `{netE -< E}.\nNotation tE := (genE +' nondetE +' failureE +' logE +' netE).\nInstance tE_Is__tE : Is__tE tE. Defined.\n\nCoFixpoint tester' {E R} `{Is__tE E} (others : list (itree oE R)) (m : itree oE R)\n  : itree E R :=\n  match observe m with\n  | RetF r  => ret r\n  | TauF m' => Tau (tester' others m')\n  | VisF e k =>\n    let catch (err : string) : itree E R :=\n      embed Log (\"Catch \" ++ err ++ \" with \" ++ to_string (List.length others)\n                          ++ \" other branches\");;\n      match others with\n      | [] => throw err\n      | other :: others' =>\n        Tau (tester' others' other)\n      end in\n    match e with\n    | (Throw err|) => catch err\n    | (|ne|) =>\n      match ne in nondetE Y return (Y -> _) -> _ with\n      | Or => fun k => b <- trigger Or;;\n                   Tau (tester' others (k b))\n      end k\n    | (||de|) =>\n      match de in decideE Y return (Y -> _) -> _ with\n      | Decide =>\n        fun k => b <- trigger Or;;\n              Tau (tester' (others ++ [k (negb b)]) (k b))\n      end k\n    | (|||le|) =>\n      match le in logE Y return (Y -> _) -> _ with\n      | Log str => fun k => embed Log (\"Observer: \" ++ str);;\n                        Tau (tester' others (k tt))\n      end k\n    | (||||oe) =>\n      match oe in observeE Y return (Y -> _) -> _ with\n      | Observe__Select =>\n        fun k =>\n          cs <- fst <$> sublist conns;;\n          Tau (tester' (match_observe Observe__Select cs others) (k cs))\n      | Observe__Send c =>\n        fun k =>\n          pkt <- embed Gen c;;\n          embed Net__Send pkt;;\n          (* embed Log (\"Sent \" ++ to_string pkt);; *)\n          Tau (tester' (match_observe (Observe__Send c) pkt others) (k pkt))\n      | Observe__Recv =>\n        fun k =>\n          conns <- trigger Net__Select;;\n          match conns with\n          | [] =>\n            match others with\n            | [] => Tau (tester' [] m)\n            | other :: others' =>\n              (* embed Log (\"Not ready to receive, try other \" *)\n              (*         ++ to_string (List.length others') ++ \" branches\");; *)\n              Tau (tester' (others' ++ [m]) other)\n            end\n          | c :: _ =>\n            pkt <- embed Net__Recv c;;\n            (* embed Log (\"Recv \" ++ to_string pkt);; *)\n            Tau (tester' (match_observe Observe__Recv pkt others) (k pkt))\n          end\n      end k\n    end\n  end.\n\nDefinition tester {E R} `{Is__tE E} : itree oE R -> itree E R := tester' [].\n", "meta": {"author": "liyishuai", "repo": "DeepWebTest", "sha": "1f026df620ccf658a683a1b927b90fc6b2703afd", "save_path": "github-repos/coq/liyishuai-DeepWebTest", "path": "github-repos/coq/liyishuai-DeepWebTest/DeepWebTest-1f026df620ccf658a683a1b927b90fc6b2703afd/echo/Test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6406358685621721, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2682322581893774}}
{"text": "From iris.algebra Require Import frac.\nFrom iris.proofmode Require Import tactics.\nRequire Import Eqdep_dec List.\nFrom cap_machine Require Import rules.\nFrom cap_machine Require Export iris_extra addr_reg_sample region_macros contiguous stack_macros_helpers.\n\nSection stack_macros.\n  Context {Σ:gFunctors} {memg:memG Σ} {regg:regG Σ}\n          `{MP: MachineParameters}.\n\n\n  (* --------------------------------------------------------------------------------- *)\n  (* ------------------------------------- FETCH ------------------------------------- *)\n  (* --------------------------------------------------------------------------------- *)\n\n  Definition fetch_instrs (f : Z) :=\n    [move_r r_t1 PC;\n    getb r_t2 r_t1;\n    geta r_t3 r_t1;\n    sub_r_r r_t2 r_t2 r_t3;\n    lea_r r_t1 r_t2;\n    load_r r_t1 r_t1;\n    lea_z r_t1 f;\n    move_z r_t2 0;\n    move_z r_t3 0;\n    load_r r_t1 r_t1]. \n\n  Definition fetch f a : iProp Σ :=\n    ([∗ list] a_i;w_i ∈ a;(fetch_instrs f), a_i ↦ₐ w_i)%I. \n\n  (* fetch spec *)\n  Lemma fetch_spec f a pc_p pc_g pc_b pc_e a_first a_last b_link e_link a_link entry_a wentry φ w1 w2 w3:\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, entry_a) = true ->\n    (a_link + f)%a = Some entry_a ->\n\n      ▷ fetch f a\n    ∗ ▷ PC ↦ᵣ inr (pc_p,pc_g,pc_b,pc_e,a_first)\n    ∗ ▷ pc_b ↦ₐ inr (RO,Global,b_link,e_link,a_link)\n    ∗ ▷ entry_a ↦ₐ wentry\n    ∗ ▷ r_t1 ↦ᵣ w1\n    ∗ ▷ r_t2 ↦ᵣ w2\n    ∗ ▷ r_t3 ↦ᵣ w3\n    (* if the capability is global, we want to be able to continue *)\n    (* if w is not a global capability, we will fail, and must now show that Phi holds at failV *)\n    ∗ ▷ (PC ↦ᵣ inr (pc_p,pc_g,pc_b,pc_e,a_last) ∗ fetch f a\n            (* the newly allocated region *)\n            ∗ r_t1 ↦ᵣ wentry ∗ r_t2 ↦ᵣ inl 0%Z ∗ r_t3 ↦ᵣ inl 0%Z\n            ∗ pc_b ↦ₐ inr (RO,Global,b_link,e_link,a_link)\n            ∗ entry_a ↦ₐ wentry\n            -∗ WP Seq (Instr Executable) {{ φ }})\n    ⊢\n      WP Seq (Instr Executable) {{ φ }}.\n  Proof.\n    iIntros (Hvpc Hcont Hwb Hentry) \"(>Hprog & >HPC & >Hpc_b & >Ha_entry & >Hr_t1 & >Hr_t2 & >Hr_t3 & Hφ)\".\n    iDestruct (big_sepL2_length with \"Hprog\") as %Hlength.\n    destruct a as [|a l];[inversion Hlength|].\n    apply contiguous_between_cons_inv_first in Hcont as Heq. subst.\n    (* move r_t1 PC *)\n    destruct l;[inversion Hlength|].\n    iPrologue \"Hprog\".\n    iApply (wp_move_success_reg_fromPC with \"[$HPC $Hi $Hr_t1]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|iContiguous_next Hcont 0|auto|..].\n    iEpilogue \"(HPC & Hprog_done & Hr_t1)\".\n    (* getb r_t2 r_t1 *)\n    destruct l;[inversion Hlength|]. \n    iPrologue \"Hprog\".\n    iApply (wp_Get_success with \"[$HPC $Hi $Hr_t2 $Hr_t1]\");\n      [apply decode_encode_instrW_inv|auto|iCorrectPC a_first a_last|iContiguous_next Hcont 1|auto..].\n    iEpilogue \"(HPC & Hi & Hr_t1 & Hr_t2) /=\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\". \n    (* geta r_t3 r_t1 *)\n    destruct l;[inversion Hlength|]. \n    iPrologue \"Hprog\".\n    iApply (wp_Get_success with \"[$HPC $Hi $Hr_t3 $Hr_t1]\");\n      [apply decode_encode_instrW_inv|auto|iCorrectPC a_first a_last|iContiguous_next Hcont 2|auto..].\n    iEpilogue \"(HPC & Hi & Hr_t1 & Hr_t3) /=\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\". \n    (* sub r_t2 r_t2 r_t3 *)\n    destruct l;[inversion Hlength|]. \n    iPrologue \"Hprog\".\n    iApply (wp_add_sub_lt_success_dst_r with \"[$HPC $Hi $Hr_t3 $Hr_t2]\");\n      [apply decode_encode_instrW_inv|auto|iContiguous_next Hcont 3|iCorrectPC a_first a_last|..].\n    iEpilogue \"(HPC & Hi & Hr_t3 & Hr_t2) /=\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\". \n    (* lea r_t1 r_t2 *)\n    destruct l;[inversion Hlength|]. \n    iPrologue \"Hprog\".\n    assert ((a_first + (pc_b - a_first))%a = Some pc_b) as Hlea;[solve_addr|]. \n    iApply (wp_lea_success_reg with \"[$HPC $Hi $Hr_t1 $Hr_t2]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|iContiguous_next Hcont 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      assert (a_first < a_last)%Z as Hlt;[simpl in Hcont;solve_addr|].\n      apply isCorrectPC_inrange with (a:=a_first) in Hvpc;[|lia].\n      destruct pc_p;auto;inversion Hvpc;solve_addr. }\n    iEpilogue \"(HPC & Hi & Hr_t2 & Hr_t1) /=\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\". \n    (* load r_t1 r_t1 *)\n    destruct l;[inversion Hlength|].\n    assert (readAllowed pc_p = true) as Hra.\n    { eapply pc_range_readA;eauto. }\n    iPrologue \"Hprog\".\n    iAssert (⌜(pc_b ≠ a3)%Z⌝)%I as %Hneq.\n    { iIntros (Hcontr);subst.\n      iDestruct (addr_dupl_false with \"Hi Hpc_b\") as %Hne; auto. }\n    iApply (wp_load_success_same with \"[$HPC $Hi $Hr_t1 Hpc_b]\");\n      [|apply decode_encode_instrW_inv|iCorrectPC a_first a_last|auto| |iContiguous_next Hcont 5|..].\n    { exact (inr (RW, Global, b_link, e_link, a_link)). }\n    { apply contiguous_between_length in Hcont as Hlen.\n      assert (pc_b < pc_e)%Z as Hle.\n      { eapply isCorrectPC_contiguous_range in Hvpc as Hwb';[|eauto|apply elem_of_cons;left;eauto].\n        inversion Hwb'. solve_addr. }\n      apply isCorrectPC_range_perm in Hvpc as Heq; [|revert Hlen; clear; solve_addr].\n      apply andb_true_intro. split;[apply Z.leb_le;solve_addr|apply Z.ltb_lt;auto].\n    }\n    { destruct (pc_b =? a3)%a; [done|iFrame]. }\n    destruct ((pc_b =? a3)%a) eqn:Hcontr;[apply Z.eqb_eq in Hcontr;apply z_of_eq in Hcontr;congruence|clear Hcontr]. \n    iEpilogue \"(HPC & Hr_t1 & Hi & Hpc_b)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* lea r_t1 f *)\n    destruct l;[inversion Hlength|]. \n    iPrologue \"Hprog\".\n    iApply (wp_lea_success_z with \"[$HPC $Hi $Hr_t1]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|iContiguous_next Hcont 6|apply Hentry|simpl;auto..].\n    iEpilogue \"(HPC & Hi & Hr_t1)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* move r_t2 0 *)\n    destruct l;[inversion Hlength|]. \n    iPrologue \"Hprog\".\n    iApply (wp_move_success_z with \"[$HPC $Hi $Hr_t2]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|iContiguous_next Hcont 7|auto|..].\n    iEpilogue \"(HPC & Hi & Hr_t2)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* move r_t3 0 *)\n    destruct l;[inversion Hlength|]. \n    iPrologue \"Hprog\".\n    iApply (wp_move_success_z with \"[$HPC $Hi $Hr_t3]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|iContiguous_next Hcont 8|auto|..].\n    iEpilogue \"(HPC & Hi & Hr_t3)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* load r_t1 r_t1 *)\n    destruct l;[|inversion Hlength].\n    apply contiguous_between_last with (ai:=a7) in Hcont as Hlink;[|auto]. \n    iPrologue \"Hprog\".\n    iAssert (⌜(entry_a ≠ a7)%Z⌝)%I as %Hneq'.\n    { iIntros (Hcontr);subst.\n      iDestruct (addr_dupl_false with \"Hi Ha_entry\") as %Hne; auto. }\n    iApply (wp_load_success_same with \"[$HPC $Hi $Hr_t1 Ha_entry]\");\n      [exact wentry|apply decode_encode_instrW_inv|iCorrectPC a_first a_last|auto|auto|apply Hlink|..].\n    { destruct (entry_a =? a7)%a; auto. }\n    destruct ((entry_a =? a7)%a) eqn:Hcontr;[apply Z.eqb_eq in Hcontr;apply z_of_eq in Hcontr;congruence|clear Hcontr]. \n    iEpilogue \"(HPC & Hr_t1 & Hi & Hentry_a)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* continuation *)\n    iApply \"Hφ\".\n    iFrame. \n    iDestruct \"Hprog_done\" as \"($&$&$&$&$&$&$&$&$&$)\".\n  Qed.\n\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/fetch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2682322466984298}}
{"text": "From st.prelude Require Import autosubst.\nFrom st.STLCmuVS Require Import lang typing tactics.\nFrom st.STLCmu Require Import types.\nFrom st.STLCmuVS.lib Require Import fixarrow omega.\nFrom st.backtranslations.un_syn Require Import universe.base.\n\nInductive direction :=\n  | Embed\n  | Project.\n\nDefinition FstSnd (ep : direction) : expr → expr :=\n  match ep with\n  | Embed => Fst\n  | Project => Snd\n  end.\n\nDefinition opp_direction (ep : direction) :=\n  match ep with\n  | Embed => Project\n  | Project => Embed\n  end.\n\nDefinition fixgenTRec (eb pb : val) : val :=\n  (LamV (* 1 → ((τ → U) × (U → τ)) *) (\n       LamV (* 1 *) (\n           ( LamV (inject TCRec (Fold (eb.{ren (+2)} (Unfold %0)))) , (* τ → U *)\n             LamV (Fold (pb.{ren (+2)} (Unfold (extract TCRec %0)))) (* U → τ *)\n           )\n         )\n     )\n  )%Eₙₒ.\n\nLemma fixgenTRec_subst (eb pb : val) (σ : var → expr) : (fixgenTRec eb pb).{σ} = fixgenTRec eb.{up σ} pb.{up σ}.\nProof. rewrite /fixgenTRec. simpl. rewrite inject_Closed extract_Closed. repeat rewrite -val_subst_valid. by asimpl. Qed.\n\nLemma fixgenTRec_typed (eb pb : val) Γ τb\n      (peb : (TUnit ⟶ ((TRec τb ⟶ TUniverse) × (TUniverse ⟶ TRec τb)))%Tₙₒ :: Γ ⊢ₙₒ eb : τb.[TRec τb/] ⟶ TUniverse)\n      (ppb : (TUnit ⟶ ((TRec τb ⟶ TUniverse) × (TUniverse ⟶ TRec τb)))%Tₙₒ :: Γ ⊢ₙₒ pb : TUniverse ⟶ τb.[TRec τb/]) :\n  Γ ⊢ₙₒ fixgenTRec eb pb :\n    (TUnit ⟶ ((TRec τb ⟶ TUniverse) × (TUniverse ⟶ TRec τb))) ⟶ (TUnit ⟶ ((TRec τb ⟶ TUniverse) × (TUniverse ⟶ TRec τb))).\nProof.\n  assert (TUniverse = TUniverse.[TRec TUniverse/]) as eq; first by asimpl.\n  constructor. constructor. constructor. constructor. apply App_typed with (τ1 := TRec TUniverse). apply inject_typed.\n  constructor. apply App_typed with (τ1 := τb.[TRec τb/]).\n  change (TRec τb :: TUnit :: (TUnit ⟶ (TRec τb ⟶ TUniverse) × (TUniverse ⟶ TRec τb))%Tₙₒ :: Γ) with\n      ([TRec τb ; TUnit] ++ ((TUnit ⟶ (TRec τb ⟶ TUniverse) × (TUniverse ⟶ TRec τb))%Tₙₒ :: Γ)).\n  rewrite -val_subst_valid. apply context_weakening. rewrite -eq. apply peb.\n  constructor. by constructor.\n  constructor. constructor. apply App_typed with (τ1 := TUniverse).\n  change (TUniverse :: TUnit :: (TUnit ⟶ (TRec τb ⟶ TUniverse) × (TUniverse ⟶ TRec τb))%Tₙₒ :: Γ) with\n      ([TUniverse ; TUnit] ++ ((TUnit ⟶ (TRec τb ⟶ TUniverse) × (TUniverse ⟶ TRec τb))%Tₙₒ :: Γ)).\n  rewrite -val_subst_valid. apply context_weakening. apply ppb.\n  rewrite eq. constructor. apply App_typed with (τ1 := TUniverse).\n  apply extract_typed. rewrite -eq. by constructor.\nQed.\n\nGlobal Opaque fixgenTRec.\n\nFixpoint ep_pair (dir : direction) (τ : type) : val :=\n  (match τ with\n   | TUnit => match dir with\n             | Embed => inject TCUnit\n             | Project => extract TCUnit\n             end\n   | TBool => match dir with\n             | Embed => inject TCBool\n             | downward => extract TCBool\n             end\n   | TInt => match dir with\n            | Embed => inject TCInt\n            | Project => extract TCInt\n            end\n   | TProd τ1 τ2 => match dir with\n                   | Embed => LamV (LetIn (Fst %0)\n                                        (LetIn (Snd %1)\n                                               (inject TCProd ((ep_pair Embed τ1).{ren (+3)} %1, (ep_pair Embed τ2).{ren (+3)} %0))))\n                   | Project => LamV (LetIn (extract TCProd %0)\n                                          (LetIn (Fst %0)\n                                                 (LetIn (Snd %1)\n                                                        ((ep_pair Project τ1).{ren (+4)} %1 , (ep_pair Project τ2).{ren (+4)} %0))))\n     end\n   | TSum τ1 τ2 => match dir with\n                  | Embed => LamV (Case %0\n                                      (inject TCSum (InjL ((ep_pair Embed τ1).{ren (+2)} %0)))\n                                      (inject TCSum (InjR ((ep_pair Embed τ2).{ren (+2)} %0))))\n                  | Project => LamV (Case (extract TCSum %0)\n                                        (InjL ((ep_pair Project τ1).{ren (+2)} %0))\n                                        (InjR ((ep_pair Project τ2).{ren (+2)} %0)))\n                  end\n   | TArrow τ1 τ2 => match dir with\n                    | Embed => LamV (inject TCArrow (Lam ((ep_pair Embed τ2).{ren (+2)} (%1 ((ep_pair Project τ1).{ren (+2)} %0)))))\n                    | Project => LamV (Lam ((ep_pair Project τ2).{ren (+2)} (extract TCArrow %1 ((ep_pair Embed τ1).{ren (+2)} %0))))\n                    end\n   | TRec τb => let β := fixgenTRec (ep_pair Embed τb) (ep_pair Project τb) in\n               LamV (FstSnd dir (LamV (FixArrow β.{ren (+2)} %0(*_*)) ()) %0)\n   | TVar X => LamV (FstSnd dir (Var (S X) ()) %0)\n  end)%Eₙₒ.\n\nDefinition direction_type dir τ :=\n  match dir with\n  | Embed => TArrow τ TUniverse\n  | Project => TArrow TUniverse τ\n  end.\n\nLemma ep_pair_typed_gen (τ : type) (τs : list type) (pτn : Closed_n (length τs) τ) (dir : direction) :\n  map (fun τ => (TUnit ⟶ (τ ⟶ TUniverse) × (TUniverse ⟶ τ))%Tₙₒ) τs ⊢ₙₒ (ep_pair dir τ) : (direction_type dir τ.[subst_list τs]).\nProof.\n  generalize dependent dir.\n  generalize dependent τs.\n  induction τ as [ | | | τ1 IHτ1 τ2 IHτ2 | τ1 IHτ1 τ2 IHτ2 | τ1 IHτ1 τ2 IHτ2 | τb IHτb | X ];\n    intros τs Cnτ dir; try by (destruct dir; (apply inject_typed || apply extract_typed)).\n  - (* TProd *) destruct dir.\n    + repeat ((rewrite -val_subst_valid; apply context_weakening3) || apply IHτ1 with (dir := Embed) || apply IHτ2 with (dir := Embed) || closed_solver || apply inject_typed || econstructor).\n    + repeat ((rewrite -val_subst_valid; apply context_weakening4) || apply IHτ1 with (dir := Project) || apply IHτ2 with (dir := Project) || closed_solver || apply extract_typed || econstructor).\n  - (* TSum *) destruct dir.\n    + repeat ((rewrite -val_subst_valid; apply context_weakening2) || apply IHτ1 with (dir := Embed) || apply IHτ2 with (dir := Embed) || closed_solver || apply inject_typed || econstructor).\n    + repeat ((rewrite -val_subst_valid; apply context_weakening2) || apply IHτ1 with (dir := Project) || apply IHτ2 with (dir := Project) || closed_solver || apply (extract_typed TCSum) || econstructor).\n  - (* TArrow *) destruct dir.\n    + repeat ((rewrite -val_subst_valid; apply context_weakening2) || apply IHτ1 with (dir := Project) || apply IHτ2 with (dir := Embed) || closed_solver || apply inject_typed || econstructor).\n    + repeat ((rewrite -val_subst_valid; apply context_weakening2) || apply IHτ1 with (dir := Embed) || apply IHτ2 with (dir := Project) || closed_solver || apply (extract_typed TCArrow) || econstructor).\n  - (* TRec *) destruct dir.\n    + constructor. fold ep_pair.\n      apply App_typed with (τ1 := (TRec τb).[subst_list τs]). 2: by constructor.\n      apply Fst_typed with (τ2 := (TUniverse ⟶ (TRec τb).[subst_list τs])%Tₙₒ).\n      apply App_typed with (τ1 := TUnit). 2: by constructor. apply Lam_typed.\n      apply App_typed with (τ1 := TUnit). 2: by constructor.\n      apply FixArrow_typed.\n      rewrite -val_subst_valid. apply context_weakening2.\n      apply fixgenTRec_typed.\n      * asimpl. change (TRec τb.[up (subst_list τs)] .: subst_list τs) with (subst_list (TRec τb.[up (subst_list τs)] :: τs)).\n        rewrite -map_cons. apply IHτb with (dir := Embed). closed_solver.\n      * asimpl. change (TRec τb.[up (subst_list τs)] .: subst_list τs) with (subst_list (TRec τb.[up (subst_list τs)] :: τs)).\n        rewrite -map_cons. apply IHτb with (dir := Project). closed_solver.\n    + constructor. fold ep_pair.\n      apply App_typed with (τ1 := TUniverse). 2: by constructor.\n      apply Snd_typed with (τ1 := ((TRec τb).[subst_list τs] ⟶ TUniverse)%Tₙₒ).\n      apply App_typed with (τ1 := TUnit). 2: by constructor. apply Lam_typed.\n      apply App_typed with (τ1 := TUnit). 2: by constructor.\n      apply FixArrow_typed.\n      rewrite -val_subst_valid. apply context_weakening2.\n      apply fixgenTRec_typed.\n      * asimpl. change (TRec τb.[up (subst_list τs)] .: subst_list τs) with (subst_list (TRec τb.[up (subst_list τs)] :: τs)).\n        rewrite -map_cons. apply IHτb with (dir := Embed). closed_solver.\n      * asimpl. change (TRec τb.[up (subst_list τs)] .: subst_list τs) with (subst_list (TRec τb.[up (subst_list τs)] :: τs)).\n        rewrite -map_cons. apply IHτb with (dir := Project). closed_solver.\n  - (* TVar *)\n    destruct (TVar_subst_list_closed_n_length _ _ Cnτ) as [τ [eq ->]].\n    destruct dir; repeat econstructor; simpl; by rewrite list_lookup_fmap eq /=.\nQed.\n\nLemma ep_pair_typed (τ : type) (pτ : Closed τ) dir :\n  [] ⊢ₙₒ (ep_pair dir τ) : (direction_type dir τ).\nProof. cut (fmap (fun τ => (TUnit ⟶ (τ ⟶ TUniverse) × (TUniverse ⟶ τ))%Tₙₒ) [] ⊢ₙₒ ep_pair dir τ : direction_type dir τ.[subst_list []]). by asimpl. by apply ep_pair_typed_gen. Qed.\n\nLemma ep_pair_Closed (τ : type) (pτ : Closed τ) dir :\n  Closed (of_val $ ep_pair dir τ).\nProof.\n  intro σ. replace (of_val $ ep_pair dir τ) with (of_val $ ep_pair dir τ).[ids] at 2 by by asimpl.\n  erewrite (typed_subst_invariant [] _ _ σ ids). auto. apply ep_pair_typed.\n  auto. simpl. lia.\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/backtranslations/sem_syn/embed_project.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2680326628819653}}
{"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(** * MSetRBT : Implementation of MSetInterface via Red-Black trees *)\n\n(** Initial author: Andrew W. Appel, 2011.\n    Extra modifications by: Pierre Letouzey\n\nThe design decisions behind this implementation are described here:\n\n - Efficient Verified Red-Black Trees, by Andrew W. Appel, September 2011.\n   http://www.cs.princeton.edu/~appel/papers/redblack.pdf\n\nAdditional suggested reading:\n\n - Red-Black Trees in a Functional Setting by Chris Okasaki.\n   Journal of Functional Programming, 9(4):471-477, July 1999.\n   http://www.eecs.usma.edu/webs/people/okasaki/jfp99redblack.pdf\n\n - Red-black trees with types, by Stefan Kahrs.\n   Journal of Functional Programming, 11(4), 425-432, 2001.\n\n - Functors for Proofs and Programs, by J.-C. Filliatre and P. Letouzey.\n   ESOP'04: European Symposium on Programming, pp. 370-384, 2004.\n   http://www.lri.fr/~filliatr/ftp/publis/fpp.ps.gz\n*)\n\n\nRequire MSetGenTree.\nRequire Import Bool List BinPos Pnat Setoid SetoidList PeanoNat.\nLocal Open Scope list_scope.\n\n(* For nicer extraction, we create induction principles\n   only when needed *)\nLocal Unset Elimination Schemes.\n\n(** An extra function not (yet?) in MSetInterface.S *)\n\nModule Type MSetRemoveMin (Import M:MSetInterface.S).\n\n Parameter remove_min : t -> option (elt * t).\n\n Axiom remove_min_spec1 : forall s k s',\n  remove_min s = Some (k,s') ->\n   min_elt s = Some k /\\ remove k s [=] s'.\n\n Axiom remove_min_spec2 : forall s, remove_min s = None -> Empty s.\n\nEnd MSetRemoveMin.\n\n(** The type of color annotation. *)\n\nInductive color := Red | Black.\n\nModule Color.\n Definition t := color.\nEnd Color.\n\n(** * Ops : the pure functions *)\n\nModule Ops (X:Orders.OrderedType) <: MSetInterface.Ops X.\n\n(** ** Generic trees instantiated with color *)\n\n(** We reuse a generic definition of trees where the information\n    parameter is a color. Functions like mem or fold are also\n    provided by this generic functor. *)\n\nInclude MSetGenTree.Ops X Color.\n\nDefinition t := tree.\nLocal Notation Rd := (Node Red).\nLocal Notation Bk := (Node Black).\n\n(** ** Basic tree *)\n\nInductive Intree (x : elt) : tree -> Prop :=\n  | IsRoottree : forall c l r y, x = y -> Intree x (Node c l y r)\n  | InLefttree : forall c l r y, Intree x l -> Intree x (Node c l y r)\n  | InRighttree : forall c l r y, Intree x r -> Intree x (Node c l y r).\n\nDefinition Intr := Intree.\n\n\nDefinition singleton (k: elt) : tree := Bk Leaf k Leaf.\n\n(** ** Changing root color *)\n\nDefinition makeBlack t :=\n match t with\n | Leaf => Leaf\n | Node _ a x b => Bk a x b\n end.\n\nDefinition makeRed t :=\n match t with\n | Leaf => Leaf\n | Node _ a x b => Rd a x b\n end.\n\n(** ** Balancing *)\n\n(** We adapt when one side is not a true red-black tree.\n    Both sides have the same black depth. *)\n\nDefinition lbal l k r :=\n match l with\n | Rd (Rd a x b) y c => Rd (Bk a x b) y (Bk c k r)\n | Rd a x (Rd b y c) => Rd (Bk a x b) y (Bk c k r)\n | _ => Bk l k r\n end.\n\nDefinition rbal l k r :=\n match r with\n | Rd (Rd b y c) z d => Rd (Bk l k b) y (Bk c z d)\n | Rd b y (Rd c z d) => Rd (Bk l k b) y (Bk c z d)\n | _ => Bk l k r\n end.\n\n(** A variant of [rbal], with reverse pattern order.\n    Is it really useful ? Should we always use it ? *)\n\nDefinition rbal' l k r :=\n match r with\n | Rd b y (Rd c z d) => Rd (Bk l k b) y (Bk c z d)\n | Rd (Rd b y c) z d => Rd (Bk l k b) y (Bk c z d)\n | _ => Bk l k r\n end.\n\n(** Balancing with different black depth.\n    One side is almost a red-black tree, while the other is\n    a true red-black tree, but with black depth + 1.\n    Used in deletion. *)\n\nDefinition lbalS l k r :=\n match l with\n | Rd a x b => Rd (Bk a x b) k r\n | _ =>\n   match r with\n   | Bk a y b => rbal' l k (Rd a y b)\n   | Rd (Bk a y b) z c => Rd (Bk l k a) y (rbal' b z (makeRed c))\n   | _ => Rd l k r (* impossible *)\n   end\n end.\n\nDefinition rbalS l k r :=\n match r with\n | Rd b y c => Rd l k (Bk b y c)\n | _ =>\n   match l with\n   | Bk a x b => lbal (Rd a x b) k r\n   | Rd a x (Bk b y c) => Rd (lbal (makeRed a) x b) y (Bk c k r)\n   | _ => Rd l k r (* impossible *)\n   end\n end.\n\n(** ** Insertion *)\n \nFixpoint ins x s :=\n match s with\n | Leaf => Rd Leaf x Leaf\n | Node c l y r =>\n   match X.compare x y with\n   | Eq => s\n   | Lt =>\n     match c with\n     | Red => Rd (ins x l) y r\n     | Black => lbal (ins x l) y r\n     end\n   | Gt =>\n     match c with\n     | Red => Rd l y (ins x r)\n     | Black => rbal l y (ins x r)\n     end\n   end\n end.\n\nDefinition add x s := makeBlack (ins x s).\n\n\nFixpoint ins_tree x s :=\n match s with\n | Leaf => Rd Leaf x Leaf\n | Node c l y r =>\n   match X.compare x y with\n   | Eq => Node c l x r \n   | Lt =>\n     match c with\n     | Red => Rd (ins_tree x l) y r\n     | Black => lbal (ins_tree x l) y r\n     end\n   | Gt =>\n     match c with\n     | Red => Rd l y (ins_tree x r)\n     | Black => rbal l y (ins_tree x r)\n     end\n   end\n end.\n\nDefinition add_tree x s := makeBlack (ins_tree x s).\n(** ** Deletion *)\n\nFixpoint append (l:tree) : tree -> tree :=\n match l with\n | Leaf => fun r => r\n | Node lc ll lx lr =>\n   fix append_l (r:tree) : tree :=\n   match r with\n   | Leaf => l\n   | Node rc rl rx rr =>\n     match lc, rc with\n     | Red, Red =>\n       let lrl := append lr rl in\n       match lrl with\n       | Rd lr' x rl' => Rd (Rd ll lx lr') x (Rd rl' rx rr)\n       | _ => Rd ll lx (Rd lrl rx rr)\n       end\n     | Black, Black =>\n       let lrl := append lr rl in\n       match lrl with\n       | Rd lr' x rl' => Rd (Bk ll lx lr') x (Bk rl' rx rr)\n       | _ => lbalS ll lx (Bk lrl rx rr)\n       end\n     | Black, Red => Rd (append_l rl) rx rr\n     | Red, Black => Rd ll lx (append lr r)\n     end\n   end\n end.\n\nFixpoint del x t :=\n match t with\n | Leaf => Leaf\n | Node _ a y b =>\n   match X.compare x y with\n   | Eq => append a b\n   | Lt =>\n     match a with\n     | Bk _ _ _ => lbalS (del x a) y b\n     | _ => Rd (del x a) y b\n     end\n   | Gt =>\n     match b with\n     | Bk _ _ _ => rbalS a y (del x b)\n     | _ => Rd a y (del x b)\n     end\n   end\n end.\n\nDefinition remove x t := makeBlack (del x t).\n\n(** ** Removing minimal element *)\n\nFixpoint delmin l x r : (elt * tree) :=\n match l with\n | Leaf => (x,r)\n | Node lc ll lx lr =>\n   let (k,l') := delmin ll lx lr in\n   match lc with\n   | Black => (k, lbalS l' x r)\n   | Red => (k, Rd l' x r)\n   end\n end.\n\nDefinition remove_min t : option (elt * tree) :=\n match t with\n | Leaf => None\n | Node _ l x r =>\n   let (k,t) := delmin l x r in\n   Some (k, makeBlack t)\n end.\n\n(** ** Tree-ification\n\n    We rebuild a tree of size [if pred then n-1 else n] as soon\n    as the list [l] has enough elements *)\n\nDefinition bogus : tree * list elt := (Leaf, nil).\n\nNotation treeify_t := (list elt -> tree * list elt).\n\nDefinition treeify_zero : treeify_t :=\n fun acc => (Leaf,acc).\n\nDefinition treeify_one : treeify_t :=\n fun acc => match acc with\n | x::acc => (Rd Leaf x Leaf, acc)\n | _ => bogus\n end.\n\nDefinition treeify_cont (f g : treeify_t) : treeify_t :=\n fun acc =>\n match f acc with\n | (l, x::acc) =>\n   match g acc with\n   | (r, acc) => (Bk l x r, acc)\n   end\n | _ => bogus\n end.\n\nFixpoint treeify_aux (pred:bool)(n: positive) : treeify_t :=\n match n with\n | xH => if pred then treeify_zero else treeify_one\n | xO n => treeify_cont (treeify_aux pred n) (treeify_aux true n)\n | xI n => treeify_cont (treeify_aux false n) (treeify_aux pred n)\n end.\n\nFixpoint plength_aux (l:list elt)(p:positive) := match l with\n | nil => p\n | _::l => plength_aux l (Pos.succ p)\nend.\n\nDefinition plength l := plength_aux l 1.\n\nDefinition treeify (l:list elt) :=\n fst (treeify_aux true (plength l) l).\n\n(** ** Filtering *)\n\nFixpoint filter_aux (f: elt -> bool) s acc :=\n match s with\n | Leaf => acc\n | Node _ l k r =>\n   let acc := filter_aux f r acc in\n   if f k then filter_aux f l (k::acc)\n   else filter_aux f l acc\n end.\n\nDefinition filter (f: elt -> bool) (s: t) : t :=\n treeify (filter_aux f s nil).\n\nFixpoint partition_aux (f: elt -> bool) s acc1 acc2 :=\n match s with\n | Leaf => (acc1,acc2)\n | Node _ sl k sr =>\n   let (acc1, acc2) := partition_aux f sr acc1 acc2 in\n   if f k then partition_aux f sl (k::acc1) acc2\n   else partition_aux f sl acc1 (k::acc2)\n end.\n\nDefinition partition (f: elt -> bool) (s:t) : t*t :=\n  let (ok,ko) := partition_aux f s nil nil in\n  (treeify ok, treeify ko).\n\n(** ** Union, intersection, difference *)\n\n(** union of the elements of [l1] and [l2] into a third [acc] list. *)\n\nFixpoint union_list l1 : list elt -> list elt -> list elt :=\n match l1 with\n | nil => @rev_append _\n | x::l1' =>\n    fix union_l1 l2 acc :=\n    match l2 with\n    | nil => rev_append l1 acc\n    | y::l2' =>\n       match X.compare x y with\n       | Eq => union_list l1' l2' (x::acc)\n       | Lt => union_l1 l2' (y::acc)\n       | Gt => union_list l1' l2 (x::acc)\n       end\n    end\n end.\n\nDefinition linear_union s1 s2 :=\n  treeify (union_list (rev_elements s1) (rev_elements s2) nil).\n\nFixpoint inter_list l1 : list elt -> list elt -> list elt :=\n match l1 with\n | nil => fun _ acc => acc\n | x::l1' =>\n    fix inter_l1 l2 acc :=\n    match l2 with\n    | nil => acc\n    | y::l2' =>\n       match X.compare x y with\n       | Eq => inter_list l1' l2' (x::acc)\n       | Lt => inter_l1 l2' acc\n       | Gt => inter_list l1' l2 acc\n       end\n    end\n end.\n\nDefinition linear_inter s1 s2 :=\n  treeify (inter_list (rev_elements s1) (rev_elements s2) nil).\n\nFixpoint diff_list l1 : list elt -> list elt -> list elt :=\n match l1 with\n | nil => fun _ acc => acc\n | x::l1' =>\n    fix diff_l1 l2 acc :=\n    match l2 with\n    | nil => rev_append l1 acc\n    | y::l2' =>\n       match X.compare x y with\n       | Eq => diff_list l1' l2' acc\n       | Lt => diff_l1 l2' acc\n       | Gt => diff_list l1' l2 (x::acc)\n       end\n    end\n end.\n\nDefinition linear_diff s1 s2 :=\n  treeify (diff_list (rev_elements s1) (rev_elements s2) nil).\n\n(** [compare_height] returns:\n  - [Lt] if [height s2] is at least twice [height s1];\n  - [Gt] if [height s1] is at least twice [height s2];\n  - [Eq] if heights are approximately equal.\n  Warning: this is not an equivalence relation! but who cares.... *)\n\nDefinition skip_red t :=\n match t with\n | Rd t' _ _ => t'\n | _ => t\n end.\n\nDefinition skip_black t :=\n match skip_red t with\n | Bk t' _ _ => t'\n | t' => t'\n end.\n\nFixpoint compare_height (s1x s1 s2 s2x: tree) : comparison :=\n match skip_red s1x, skip_red s1, skip_red s2, skip_red s2x with\n | Node _ s1x' _ _, Node _ s1' _ _, Node _ s2' _ _, Node _ s2x' _ _ =>\n   compare_height (skip_black s1x') s1' s2' (skip_black s2x')\n | _, Leaf, _, Node _ _ _ _ => Lt\n | Node _ _ _ _, _, Leaf, _ => Gt\n | Node _ s1x' _ _, Node _ s1' _ _, Node _ s2' _ _, Leaf =>\n   compare_height (skip_black s1x') s1' s2' Leaf\n | Leaf, Node _ s1' _ _, Node _ s2' _ _, Node _ s2x' _ _ =>\n   compare_height Leaf s1'  s2'  (skip_black s2x')\n | _, _, _, _ => Eq\n end.\n\n(** When one tree is quite smaller than the other, we simply\n    adds repeatively all its elements in the big one.\n    For trees of comparable height, we rather use [linear_union]. *)\n\nDefinition union (t1 t2: t) : t :=\n match compare_height t1 t1 t2 t2 with\n | Lt => fold add t1 t2\n | Gt => fold add t2 t1\n | Eq => linear_union t1 t2\n end.\n\nDefinition diff (t1 t2: t) : t :=\n match compare_height t1 t1 t2 t2 with\n | Lt => filter (fun k => negb (mem k t2)) t1\n | Gt => fold remove t2 t1\n | Eq => linear_diff t1 t2\n end.\n\nDefinition inter (t1 t2: t) : t :=\n match compare_height t1 t1 t2 t2 with\n | Lt => filter (fun k => mem k t2) t1\n | Gt => filter (fun k => mem k t1) t2\n | Eq => linear_inter t1 t2\n end.\n\nEnd Ops.\n\n(** * MakeRaw : the pure functions and their specifications *)\n\nModule Type MakeRaw (X:Orders.OrderedType) <: MSetInterface.RawSets X.\nInclude Ops X.\n\n(** Generic definition of binary-search-trees and proofs of\n    specifications for generic functions such as mem or fold. *)\n\nInclude MSetGenTree.Props X Color.\n\nLocal Notation Rd := (Node Red).\nLocal Notation Bk := (Node Black).\n\nLocal Hint Immediate MX.eq_sym : core.\nLocal Hint Unfold In lt_tree gt_tree Ok : core.\nLocal Hint Constructors InT bst : core.\nLocal Hint Resolve MX.eq_refl MX.eq_trans MX.lt_trans ok : core.\nLocal Hint Resolve lt_leaf gt_leaf lt_tree_node gt_tree_node : core.\nLocal Hint Resolve lt_tree_not_in lt_tree_trans gt_tree_not_in gt_tree_trans : core.\nLocal Hint Resolve elements_spec2 : core.\n\n\n(** This is new added part**)\n\n\n(*Ltac clear_inversion H := inversion H; clear H; subst.\n\nLtac inv_ok := match goal with\n | H:Ok (Node _ _ _ _) |- _ => clear_inversion H; inv_ok\n | H:Ok Leaf |- _ => clear H; inv_ok\n | H:bst ?x |- _ => change (Ok x) in H; inv_ok\n | _ => idtac\nend.\n\n(** A tactic to repeat [inversion_clear] on all hyps of the\n    form [(f (Node _ _ _ _))] *)\n\nLtac is_tree_constr c :=\n  match c with\n   | Leaf => idtac\n   | Node _ _ _ _ => idtac\n   | _ => fail\n  end.\n\nLtac invtree f :=\n  match goal with\n     | H:f ?s |- _ => is_tree_constr s; clear_inversion H; invtree f\n     | H:f _ ?s |- _ => is_tree_constr s; clear_inversion H; invtree f\n     | H:f _ _ ?s |- _ => is_tree_constr s; clear_inversion H; invtree f\n     | _ => idtac\n  end.\n*)\nLtac inv_tree := inv_ok; invtree Intree.\n\nLtac intuition_in_tree := repeat progress (intuition; inv_tree).\n\n(** End new part **)\n\n\n(** ** Singleton set *)\n\nLemma singleton_spec x y : InT y (singleton x) <-> X.eq y x.\nProof.\n unfold singleton; intuition_in.\nQed.\n\n#[global]\nInstance singleton_ok x : Ok (singleton x).\nProof.\n unfold singleton; auto.\nQed.\n\n(** ** makeBlack, MakeRed *)\n\nLemma makeBlack_spec s x : InT x (makeBlack s) <-> InT x s.\nProof.\n destruct s; simpl; intuition_in.\nQed.\n\nLemma makeBlack_spec_tree s x : Intree x (makeBlack s) <-> Intree x s.\nProof. \n destruct s. simpl. intuition_in_tree. simpl.  intuition_in. inversion H.\n subst. constructor. auto. subst. apply InLefttree. auto. subst.\n apply InRighttree. auto. inversion H. subst. constructor. auto. subst.\n apply InLefttree. auto. subst.  apply InRighttree. auto.\nQed.\n\nLemma makeRed_spec s x : InT x (makeRed s) <-> InT x s.\nProof.\n destruct s. simpl. intuition_in. unfold makeRed. intuition eauto. intuition_in.\nintuition_in.\nQed.\n\nLemma makeRed_spec_tree s x : Intree x (makeRed s) <-> Intree x s.\nProof.\n destruct s. simpl. intuition_in. simpl.  intuition_in. inversion H.\n subst. constructor. auto. subst. apply InLefttree. auto. subst.\n apply InRighttree. auto. inversion H. subst. constructor. auto. subst.\n apply InLefttree. auto. subst.  apply InRighttree. auto.\nQed.\n\n\nLemma Bk_Rd l x r y:\nIntree y (Bk l x r) <-> Intree y (Rd l x r).\nProof. split. intros. inversion H. subst. constructor. auto. subst. apply InLefttree.\nauto. subst. apply InRighttree. auto. \nintros. inversion H. subst. constructor. auto. subst. apply InLefttree.\nauto. subst. apply InRighttree. auto.  Qed. \n\n#[global]\nInstance makeBlack_ok s `{Ok s} : Ok (makeBlack s).\nProof.\n destruct s; simpl; ok.\nQed.\n\n#[global]\nInstance makeRed_ok s `{Ok s} : Ok (makeRed s).\nProof.\n destruct s; simpl; ok.\nQed.\n\n(** ** Generic handling for red-matching and red-red-matching *)\n\nDefinition isblack t :=\n match t with Bk _ _ _ => True | _ => False end.\n\nDefinition notblack t :=\n match t with Bk _ _ _ => False | _ => True end.\n\nDefinition notred t :=\n match t with Rd _ _ _ => False | _ => True end.\n\nDefinition rcase {A} f g t : A :=\n match t with\n | Rd a x b => f a x b\n | _ => g t\n end.\n\nInductive rspec {A} f g : tree -> A -> Prop :=\n | rred a x b : rspec f g (Rd a x b) (f a x b)\n | relse t : notred t -> rspec f g t (g t).\n\nFact rmatch {A} f g t : rspec (A:=A) f g t (rcase f g t).\nProof.\ndestruct t as [|[|] l x r]; simpl; now constructor.\nQed.\n\nDefinition rrcase {A} f g t : A :=\n match t with\n | Rd (Rd a x b) y c => f a x b y c\n | Rd a x (Rd b y c) => f a x b y c\n | _ => g t\n end.\n\nNotation notredred := (rrcase (fun _ _ _ _ _ => False) (fun _ => True)).\n\nInductive rrspec {A} f g : tree -> A -> Prop :=\n | rrleft a x b y c : rrspec f g (Rd (Rd a x b) y c) (f a x b y c)\n | rrright a x b y c : rrspec f g (Rd a x (Rd b y c)) (f a x b y c)\n | rrelse t : notredred t -> rrspec f g t (g t).\n\nFact rrmatch {A} f g t : rrspec (A:=A) f g t (rrcase f g t).\nProof.\ndestruct t as [|[|] l x r]; simpl; try now constructor.\ndestruct l as [|[|] ll lx lr], r as [|[|] rl rx rr]; now constructor.\nQed.\n\nDefinition rrcase' {A} f g t : A :=\n match t with\n | Rd a x (Rd b y c) => f a x b y c\n | Rd (Rd a x b) y c => f a x b y c\n | _ => g t\n end.\n\nFact rrmatch' {A} f g t : rrspec (A:=A) f g t (rrcase' f g t).\nProof.\ndestruct t as [|[|] l x r]; simpl; try now constructor.\ndestruct l as [|[|] ll lx lr], r as [|[|] rl rx rr]; now constructor.\nQed.\n\n(** Balancing operations are instances of generic match *)\n\nFact lbal_match l k r :\n rrspec\n   (fun a x b y c => Rd (Bk a x b) y (Bk c k r))\n   (fun l => Bk l k r)\n   l\n   (lbal l k r).\nProof.\n exact (rrmatch _ _ _).\nQed.\n\nFact rbal_match l k r :\n rrspec\n   (fun a x b y c => Rd (Bk l k a) x (Bk b y c))\n   (fun r => Bk l k r)\n   r\n   (rbal l k r).\nProof.\n exact (rrmatch _ _ _).\nQed.\n\nFact rbal'_match l k r :\n rrspec\n   (fun a x b y c => Rd (Bk l k a) x (Bk b y c))\n   (fun r => Bk l k r)\n   r\n   (rbal' l k r).\nProof.\n exact (rrmatch' _ _ _).\nQed.\n\nFact lbalS_match l x r :\n rspec\n  (fun a y b => Rd (Bk a y b) x r)\n  (fun l =>\n    match r with\n    | Bk a y b => rbal' l x (Rd a y b)\n    | Rd (Bk a y b) z c => Rd (Bk l x a) y (rbal' b z (makeRed c))\n    | _ => Rd l x r\n    end)\n  l\n  (lbalS l x r).\nProof.\n exact (rmatch _ _ _).\nQed.\n\nFact rbalS_match l x r :\n rspec\n  (fun a y b => Rd l x (Bk a y b))\n  (fun r =>\n    match l with\n    | Bk a y b => lbal (Rd a y b) x r\n    | Rd a y (Bk b z c) => Rd (lbal (makeRed a) y b) z (Bk c x r)\n    | _ => Rd l x r\n    end)\n  r\n  (rbalS l x r).\nProof.\n exact (rmatch _ _ _).\nQed.\n\n(** ** Balancing for insertion *)\n\nLemma lbal_spec l x r y :\n   InT y (lbal l x r) <-> X.eq y x \\/ InT y l \\/ InT y r.\nProof.\n case lbal_match; intuition_in.\nQed.\n\nLemma lbal_spec_tree l x r y :\n   Intree y (lbal l x r) <-> y = x \\/ Intree y l \\/ Intree y r.\nProof.\n case lbal_match; intuition_in.\n - inversion H. \n    * subst;right;left;constructor;auto.\n    * subst;right;left;apply InLefttree;apply Bk_Rd;auto.\n    * subst; inversion H1; subst;  auto; subst; \n      right; left; apply InRighttree; auto; subst; auto. \n - apply InRighttree. constructor. auto. \n - inversion H. \n    * subst. constructor. auto. \n    * subst. apply InLefttree. apply Bk_Rd. auto.\n    * subst. apply InRighttree.  apply InLefttree. auto.\n - apply InRighttree. apply InRighttree.  auto.\n - inversion H. \n    * subst. right. left. apply InRighttree. constructor. auto.\n    * subst. right. left. inversion H1. subst. constructor. auto. subst. \n      apply InLefttree. auto. subst.  apply InRighttree. apply InLefttree. auto. \n    * subst. inversion H1. subst.  auto. subst. \n      right. left. apply InRighttree.  apply InRighttree. auto. subst. auto.\n - apply InRighttree. constructor. auto.\n - inversion H. \n    * subst. apply InLefttree. constructor. auto. \n    * subst; apply InLefttree; apply InLefttree; auto.\n    * subst. inversion H1. subst. constructor. auto. subst. \n      apply InLefttree. apply InRighttree.  auto. subst.\n      apply InRighttree. apply InLefttree. auto.\n - apply InRighttree. apply InRighttree.  auto. \n - inversion H0. subst. auto. subst. right. left. auto. subst. right. right. auto.\n - constructor. auto.\n - apply InLefttree.  auto.\n - apply InRighttree. auto.\nQed.\n\n#[global]\nInstance lbal_ok l x r `(Ok l, Ok r, lt_tree x l, gt_tree x r) :\n Ok (lbal l x r).\nProof.\n destruct (lbal_match l x r); ok.\nQed.\n\nLemma rbal_spec l x r y :\n   InT y (rbal l x r) <-> X.eq y x \\/ InT y l \\/ InT y r.\nProof.\n case rbal_match; intuition_in.\nQed.\n\nLemma rbal_spec_tree l x r y :\n   Intree y (rbal l x r) <-> y = x \\/ Intree y l \\/ Intree y r.\nProof.\n case rbal_match; intuition_in_tree.\n - right. right. apply InLefttree;constructor;auto.\n - right. right. apply InLefttree;apply InLefttree;auto.\n - right;right;constructor;auto.\n - right;right;apply InLefttree;apply InRighttree;auto.\n - right;right;apply InRighttree;auto.\n - apply InLefttree;constructor;auto.\n - apply InLefttree;apply InLefttree;auto.\n - apply InRighttree;constructor;auto.\n - constructor;auto.\n - apply InLefttree;apply InRighttree;auto.\n - apply InRighttree;apply InLefttree;auto.\n - apply InRighttree;apply InRighttree;auto.\n - right;right;constructor;auto.\n - right;right;apply InLefttree;auto.\n - right;right;apply InRighttree;constructor;auto.\n - right;right;apply InRighttree;apply InLefttree;auto.\n - right;right;apply InRighttree;apply InRighttree;auto.\n - apply InLefttree;constructor;auto.\n - apply InLefttree;apply InLefttree;auto.\n - constructor;auto.\n - apply InLefttree;apply InRighttree;auto.\n - apply InRighttree;constructor;auto.\n - apply InRighttree;apply InLefttree;auto.\n - apply InRighttree;apply InRighttree;auto.\n - constructor;auto.\n - apply InLefttree;auto.\n - apply InRighttree;auto.\n Qed.\n \n\n\n#[global]\nInstance rbal_ok l x r `(Ok l, Ok r, lt_tree x l, gt_tree x r) :\n Ok (rbal l x r).\nProof.\n destruct (rbal_match l x r); ok.\nQed.\n\nLemma rbal'_spec l x r y :\n   InT y (rbal' l x r) <-> X.eq y x \\/ InT y l \\/ InT y r.\nProof.\n case rbal'_match; intuition_in.\nQed.\n\nLemma rbal'_spec_tree l x r y :\n   Intree y (rbal' l x r) <-> y = x \\/ Intree y l \\/ Intree y r.\nProof.\ncase rbal'_match; intuition_in_tree.\n - right. right. apply InLefttree;constructor;auto.\n - right. right. apply InLefttree;apply InLefttree;auto.\n - right;right;constructor;auto.\n - right;right;apply InLefttree;apply InRighttree;auto.\n - right;right;apply InRighttree;auto.\n - apply InLefttree;constructor;auto.\n - apply InLefttree;apply InLefttree;auto.\n - apply InRighttree;constructor;auto.\n - constructor;auto.\n - apply InLefttree;apply InRighttree;auto.\n - apply InRighttree;apply InLefttree;auto.\n - apply InRighttree;apply InRighttree;auto.\n - right;right;constructor;auto.\n - right;right;apply InLefttree;auto.\n - right;right;apply InRighttree;constructor;auto.\n - right;right;apply InRighttree;apply InLefttree;auto.\n - right;right;apply InRighttree;apply InRighttree;auto.\n - apply InLefttree;constructor;auto.\n - apply InLefttree;apply InLefttree;auto.\n - constructor;auto.\n - apply InLefttree;apply InRighttree;auto.\n - apply InRighttree;constructor;auto.\n - apply InRighttree;apply InLefttree;auto.\n - apply InRighttree;apply InRighttree;auto.\n - constructor;auto.\n - apply InLefttree;auto.\n - apply InRighttree;auto.\nQed.\n\n#[global]\nInstance rbal'_ok l x r `(Ok l, Ok r, lt_tree x l, gt_tree x r) :\n Ok (rbal' l x r).\nProof.\n destruct (rbal'_match l x r); ok.\nQed.\n\n Hint Rewrite In_node_iff In_leaf_iff\n makeRed_spec makeBlack_spec lbal_spec rbal_spec rbal'_spec : rb.\n \nHint Rewrite In_node_iff In_leaf_iff\n makeRed_spec_tree makeBlack_spec_tree lbal_spec_tree rbal_spec_tree : rbtree.\n\nLtac descolor := destruct_all Color.t.\nLtac destree t := destruct t as [|[|] ? ? ?].\nLtac autorew := autorewrite with rb.\nLtac autorew_tree := autorewrite with rbtree.\nTactic Notation \"autorew\" \"in\" ident(H) := autorewrite with rb in H.\nTactic Notation \"autorew_tree\" \"in\" ident(H) := autorewrite with rbtree in H.\n(** ** Insertion *)\n\nLemma ins_spec : forall s x y,\n InT y (ins x s) <-> X.eq y x \\/ InT y s.\nProof.\n induct s x.\n - intuition_in.\n - intuition_in. setoid_replace y with x; eauto.\n - descolor; autorew; rewrite IHl; intuition_in.\n - descolor; autorew; rewrite IHr; intuition_in.\nQed.\n\nLemma ins_tree_spec_tree1 : forall s x y,\n~X.eq x y /\\ Intree y (ins_tree x s) -> Intree y s.\nProof.\n induct s x.\n - intuition_in_tree. destruct H0. auto. \n - intuition_in_tree.\n   * destruct H1. auto.\n   * apply InLefttree;auto.\n   * apply InRighttree;auto.\n - destruct i.\n    +  intuition_in_tree.\n      -- constructor. auto.\n      -- apply InLefttree. apply (IHl x). auto.\n      -- apply InRighttree. auto.\n    + destruct H. apply lbal_spec_tree in H1. destruct H1.\n        ** constructor. auto. \n        ** destruct H1.  apply InLefttree. apply (IHl x). auto. auto. \n            apply InRighttree. auto.\n - destruct i.\n    +  intuition_in_tree.\n      -- constructor. auto.\n      -- apply InLefttree. auto. \n      -- apply InRighttree. apply (IHr x). auto.\n    + destruct H. apply rbal_spec_tree in H1. destruct H1.\n        ** constructor. auto. \n        ** destruct H1.  apply InLefttree. auto. \n            apply InRighttree. apply (IHr x). auto. \nQed.\n\n\n\nLemma ins_tree_spec_tree2 : forall s x y,\nIntree y s/\\~X.eq x y  -> Intree y (ins_tree x s).\nProof.\n induct s x.\n - intuition_in_tree. \n - intuition_in_tree.  \n  * apply InLefttree;auto.\n  * apply InRighttree;auto.\n -  destruct H. destruct i. intuition_in_tree. \n  * constructor. auto.\n  * apply InLefttree;auto.\n  * apply InRighttree;auto.\n  * apply lbal_spec_tree. intuition_in_tree. \n - destruct H. destruct i. intuition_in_tree. \n  * constructor. auto.\n  * apply InLefttree;auto.\n  * apply InRighttree;auto.\n  * apply rbal_spec_tree. intuition_in_tree.\nQed.   \n\n\nLemma ins_spec0_tree : forall s x y,\n~Intree y s -> Intree y (ins x s) -> x = y .\nProof. \n induct s x.\n - intuition_in_tree. \n - intuition_in_tree. \n - descolor. intuition_in_tree. \n  * assert(Intree x' (Rd l x' r)). constructor;auto. intuition_in_tree.\n  * apply IHl. intro. assert(Intree y (Rd l x' r)). apply InLefttree;auto. intuition_in_tree.\n    auto.\n  * assert(Intree y (Rd l x' r)). apply InRighttree;auto.  intuition_in_tree.\n  * apply lbal_spec_tree in H0. intuition_in_tree.  \n      + assert(Intree y (Bk l x' r)). constructor. auto. intuition_in_tree.\n      + apply IHl. intro. assert(Intree y (Bk l x' r)). apply InLefttree;auto. intuition_in_tree. auto.\n      + assert(Intree y (Bk l x' r)). apply InRighttree;auto.  intuition_in_tree.\n - destruct i. intuition_in_tree. \n   * assert(Intree x' (Rd l x' r)). constructor;auto. intuition_in_tree.\n   * assert(Intree y (Rd l x' r)). apply InLefttree;auto. intuition_in_tree.\n   * apply IHr. intro. assert(Intree y (Rd l x' r)). apply InRighttree;auto.  intuition_in_tree. auto.\n   * apply rbal_spec_tree in H0. intuition_in_tree.\n     + assert(Intree y (Bk l x' r)). constructor. auto.  intuition_in_tree.\n     +assert(Intree y (Bk l x' r)). apply InLefttree;auto. intuition_in_tree.\n     + apply IHr. intro. assert(Intree y (Bk l x' r)). apply InRighttree;auto.  intuition_in_tree. auto.\nQed.\n\n\nLemma ins_spec1_tree : forall s x y,\nIntree y s -> Intree y (ins x s).\nProof. \n induct s x.\n - intuition_in_tree. \n - intuition_in_tree. \n - descolor. intuition_in_tree. \n  * constructor;auto.\n  * apply InLefttree;apply IHl;auto.\n  * apply InRighttree;auto.\n  * apply lbal_spec_tree. intuition_in_tree. \n - descolor. intuition_in_tree.\n  * constructor;auto.\n  * apply InLefttree;auto.\n  * apply InRighttree;auto.\n  * apply rbal_spec_tree. intuition_in_tree. \nQed.\n\n\nLemma ins_spec2_tree : forall s x y,\n~X.eq x y -> Intree y (ins x s) -> Intree y s.\nProof. \n induct s x.\n - intuition_in_tree. destruct H. auto.\n - intuition_in_tree. \n - descolor. intuition_in_tree. \n  *  constructor;auto.\n  * apply IHl in H3. destruct H3.\n    ** apply InLefttree;auto. constructor. auto.\n    ** apply InLefttree;auto. apply InLefttree. auto.\n   ** apply InLefttree;auto. apply InRighttree. auto.\n   ** auto.\n  *  apply InRighttree;auto.\n  * apply lbal_spec_tree in H0. intuition_in_tree.\n    + constructor. auto.\n    + apply IHl in H. destruct H.\n        *** apply InLefttree;auto. constructor. auto.\n        *** apply InLefttree;auto. apply InLefttree;auto.\n        *** apply InLefttree;auto. apply InRighttree;auto.\n        *** auto.\n     +  apply InRighttree;auto.\n - destruct i.  intuition_in_tree. \n      + constructor. auto.\n      +apply InLefttree;auto.\n      + apply InRighttree;auto. apply (IHr x). auto. auto.\n      + apply rbal_spec_tree in H0. intuition_in_tree.\n         ***  constructor. auto.\n         ***  apply InLefttree;auto.\n         *** apply IHr in H0. apply InRighttree;auto. auto.\nQed.\n\nLemma ins_spec_tree : forall s x y,\nnot (InT x s) -> Intree y (ins x s) <-> x = y \\/ Intree y s.\nProof.\n induct s x.\n - intuition_in_tree. constructor. auto. \n - assert(Hr:~ InT x r). intro. destruct H. apply InRight. auto.\n   assert(Hl:~ InT x l). intro. destruct H. apply InLeft. auto. \n   split.\n    * intro H1. intuition_in_tree.\n    * intro H1. destruct H1.\n       + subst. destruct H. constructor. auto. \n       + destruct H. constructor. auto. \n - assert(Hr:~ InT x r). intro. destruct H. apply InRight. auto.\n   assert(Hl:~ InT x l). intro. destruct H. apply InLeft. auto. \n    * destruct i. \n       + split. \n          ++ intro. inversion H1. \n              -- subst. right. constructor. auto. \n              -- subst. apply IHl in H3. destruct H3. auto. \n                 right. apply InLefttree. auto. auto.\n              -- subst. right. apply InRighttree. auto.\n         ++ intro. destruct H1. apply InLefttree. apply IHl. auto. auto.\n            inversion H1. \n            -- subst. constructor. auto.\n            -- subst. apply InLefttree. apply IHl.  auto. auto.\n            -- subst. apply InRighttree. auto.\n       + split. \n          ++ intro. apply lbal_spec_tree in H1. destruct H1.\n             -- right. constructor. auto.\n             -- destruct H1. apply IHl in H1. destruct H1. auto. right.\n                apply InLefttree. auto. auto. right. apply InRighttree. auto.\n          ++ intros. apply lbal_spec_tree. destruct H1. \n             -- right. left. apply IHl.  auto. auto.\n             -- inversion H1.\n                +++ subst. auto. \n                +++ subst. right. left. apply IHl. auto. auto.\n                +++ subst. auto.\n - assert(Hr:~ InT x r). intro. destruct H. apply InRight. auto.\n   assert(Hl:~ InT x l). intro. destruct H. apply InLeft. auto. \n   split. \n     * destruct i. \n       + intro. inversion H1.\n          -- subst. right. constructor. auto. \n          -- subst. right. apply InLefttree. auto.\n          -- subst. apply IHr in H3. destruct H3. auto. right. \n             apply InRighttree. auto. auto.\n       + intro. apply rbal_spec_tree in H1. destruct H1.\n          -- right. constructor. auto. \n          -- destruct H1. right. apply InLefttree. auto. apply IHr in H1.\n             destruct H1. auto. right. apply InRighttree;auto. auto.\n    * destruct i. \n       + intro. destruct H1. apply InRighttree;auto. apply IHr. auto. \n         auto. inversion H1.\n          -- subst. constructor. auto. \n          -- subst.  apply InLefttree. auto.\n          -- subst. apply InRighttree. apply IHr. auto. auto.\n       + intro. apply rbal_spec_tree. destruct H1. \n          -- right. right. apply IHr. auto. auto.\n          -- inversion H1. \n              ++ subst.  auto. \n              ++ subst.  auto.\n              ++ subst. right. right. apply IHr. auto. auto.\nQed.\n\n\nHint Rewrite ins_spec : rb.\nHint Rewrite ins_spec1_tree ins_spec2_tree : rbtree.\n\n#[global]\nInstance ins_ok s x `{Ok s} : Ok (ins x s).\nProof.\n induct s x; auto; descolor;\n (apply lbal_ok || apply rbal_ok || ok); auto;\n intros y; autorew; intuition; order.\nQed.\n\nLemma add_spec' s x y :\n InT y (add x s) <-> X.eq y x \\/ InT y s.\nProof.\n unfold add. now autorew.\nQed.\n\nLemma add_tree_spec'_tree s x y :\n~X.eq x y  -> Intree y (add_tree x s) <-> Intree y s.\nProof. unfold add_tree. rewrite makeBlack_spec_tree.\nsplit. intros. apply ins_tree_spec_tree1 with (x:=x). auto.\nintros. apply ins_tree_spec_tree2 with (x:=x). auto. \nQed.\n\nLemma add_spec'0_tree s x y :\n~Intree y s -> Intree y (add x s) -> x = y.\nProof. unfold add. rewrite makeBlack_spec_tree.\napply ins_spec0_tree. \nQed.\n\nLemma add_spec'1_tree s x y :\nIntree y s -> Intree y (add x s).\nProof. unfold add. rewrite makeBlack_spec_tree.\napply ins_spec1_tree. \nQed.\n\nLemma add_spec'2_tree s x y :\n~X.eq x y -> Intree y (add x s) -> Intree y s.\nProof. unfold add. rewrite makeBlack_spec_tree.\napply ins_spec2_tree. \nQed.\n\n\nLemma add_spec'_tree s x y :\nnot (InT x s) -> Intree y (add x s) <-> x = y \\/ Intree y s.\nProof. unfold add. rewrite makeBlack_spec_tree.\napply ins_spec_tree. \nQed.\n\nHint Rewrite add_spec' : rb.\nHint Rewrite add_spec'2_tree add_spec'1_tree: rbtree.\n\nLemma add_spec s x y `{Ok s} :\n InT y (add x s) <-> X.eq y x \\/ InT y s.\nProof.\n apply add_spec'.\nQed.\n\nLemma add_spec_tree s x y `{Ok s} :\nnot (InT x s) -> Intree y (add x s) <-> x = y \\/ Intree y s.\nProof.\n apply add_spec'_tree.\nQed.\n\nLemma add_spec0_tree s x y `{Ok s} :\n~Intree y s -> Intree y (add x s) -> x = y .\nProof.\n apply add_spec'0_tree.\nQed.\n\nLemma add_spec1_tree s x y `{Ok s} :\nIntree y s -> Intree y (add x s).\nProof.\n apply add_spec'1_tree.\nQed.\n\nLemma add_spec2_tree s x y `{Ok s} :\n~ X.eq x y -> Intree y (add x s) -> Intree y s.\nProof.\n apply add_spec'2_tree.\nQed.\n\nLemma add_tree_spec_tree s x y `{Ok s} :\n~ X.eq x y -> Intree y (add_tree x s) <-> Intree y s.\nProof.\n apply add_tree_spec'_tree.\nQed.\n\n\n#[global]\nInstance add_ok s x `{Ok s} : Ok (add x s).\nProof.\n unfold add; auto_tc.\nQed.\n\n(** ** Balancing for deletion *)\n\nLemma lbalS_spec l x r y :\n  InT y (lbalS l x r) <-> X.eq y x \\/ InT y l \\/ InT y r.\nProof.\n case lbalS_match.\n - intros; autorew; intuition_in.\n - clear l. intros l _.\n   destruct r as [|[|] rl rx rr].\n   * autorew. intuition_in.\n   * destree rl; autorew; intuition_in.\n   * autorew. intuition_in.\nQed.\n\nLemma lbalS_spec_tree l x r y :\n  Intree y (lbalS l x r) <-> y = x \\/ Intree y l \\/ Intree y r.\nProof.\ncase lbalS_match.\n - intuition_in_tree.\n   * right;left;constructor;auto.\n   * right;left;apply InLefttree;auto.\n   * right;left;apply InRighttree;auto.\n   * constructor;auto. \n   * apply InLefttree;constructor;auto.\n   * apply InLefttree;apply InLefttree;auto.\n   * apply InLefttree; apply InRighttree;auto.\n   * apply InRighttree;auto.\n - intros t _. \n   destruct l as [|[|] ll lx lr]. \n   * intuition_in_tree. \n      + destruct r.\n         { inversion H. subst. auto. subst. auto. subst. inversion H1. }\n         { destruct t0. \n              { destruct r1. \n                 { inversion H. subst. auto. subst. auto. subst. auto. }\n                 { destruct t0. inversion H. subst. auto. subst. auto. subst. auto. \n                   inversion H. subst. \n                   inversion H. subst. right;right;apply InLefttree;constructor;auto.\n                   subst. right;right;apply InLefttree;constructor;auto.\n                   subst. right;right;apply InLefttree;constructor;auto.\n                   subst. inversion H1. subst. auto. subst. auto. subst. \n                   right;right;apply InLefttree;apply InLefttree;auto.\n                   subst. apply rbal'_spec_tree in H1.\n                   destruct H1. right;right;constructor;auto.\n                   destruct H0. right;right;apply InLefttree;apply InRighttree;auto.\n                   right;right;apply InRighttree;apply makeRed_spec_tree;auto. }\n              }\n              { apply rbal'_spec_tree in H. destruct H. auto.\n                destruct H. auto. apply Bk_Rd in H. auto.\n              }\n       }\n    + destruct r. constructor;auto. destruct t0.\n        destruct r1. constructor;auto. destruct t0.\n        constructor;auto.  apply InLefttree;constructor;auto.\n        apply rbal'_spec_tree. auto.\n    + destruct r. apply InLefttree;auto. destruct t0.\n        destruct r1. apply InLefttree;auto. destruct t0.\n        apply InLefttree;auto. apply InLefttree;apply InLefttree;auto.\n        apply rbal'_spec_tree. auto.\n    + destruct r. inversion H. destruct t0.\n        destruct r1. apply InRighttree;auto. destruct t0.\n        apply InRighttree;auto. inversion H. \n        { subst.  apply InRighttree. \n        apply rbal'_spec_tree. auto. }\n        { subst. inversion H1.  subst. constructor. auto. \n          subst. apply InLefttree;apply InRighttree;auto.\n          subst.  apply InRighttree.\n        apply rbal'_spec_tree. auto.\n        } \n        { subst. apply InRighttree.\n        apply rbal'_spec_tree. apply makeRed_spec_tree in H1. auto. }\n        { apply rbal'_spec_tree. apply Bk_Rd in H.  auto. }\n  *  intuition_in_tree. \n      + destruct r.\n         { inversion H. subst. auto. subst. auto. subst. inversion H1. }\n         { destruct t0. \n              { destruct r1. \n                 { inversion H. subst. auto. subst. auto. subst. auto. }\n                 { destruct t0. inversion H. subst. auto. subst. auto. subst. auto. \n                   inversion H. subst. \n                   inversion H. subst. right;right;apply InLefttree;constructor;auto.\n                   subst. right;right;apply InLefttree;constructor;auto.\n                   subst. right;right;apply InLefttree;constructor;auto.\n                   subst. inversion H1. subst. auto. subst. auto. subst. \n                   right;right;apply InLefttree;apply InLefttree;auto.\n                   subst. apply rbal'_spec_tree in H1.\n                   destruct H1. right;right;constructor;auto.\n                   destruct H0. right;right;apply InLefttree;apply InRighttree;auto.\n                   right;right;apply InRighttree;apply makeRed_spec_tree;auto. }\n              }\n              { apply rbal'_spec_tree in H. destruct H. auto.\n                destruct H. auto. apply Bk_Rd in H. auto.\n              }\n       }\n    + destruct r. constructor;auto. destruct t0.\n        destruct r1. constructor;auto. destruct t0.\n        constructor;auto.  apply InLefttree;constructor;auto.\n        apply rbal'_spec_tree. auto.\n    + destruct r. apply InLefttree;auto. destruct t0.\n        destruct r1. apply InLefttree;auto. destruct t0.\n        apply InLefttree;auto. apply InLefttree;apply InLefttree;auto.\n        apply rbal'_spec_tree. auto.\n    + destruct r. inversion H. destruct t0.\n        destruct r1. apply InRighttree;auto. destruct t0.\n        apply InRighttree;auto. inversion H. \n        { subst.  apply InRighttree. \n        apply rbal'_spec_tree. auto. }\n        { subst. inversion H1.  subst. constructor. auto. \n          subst. apply InLefttree;apply InRighttree;auto.\n          subst.  apply InRighttree.\n        apply rbal'_spec_tree. auto.\n        } \n        { subst. apply InRighttree.\n        apply rbal'_spec_tree. apply makeRed_spec_tree in H1. auto. }\n        { apply rbal'_spec_tree. apply Bk_Rd in H.  auto. }\n   * intuition_in_tree. \n      + destruct r.\n         { inversion H. subst. auto. subst. auto. subst. inversion H1. }\n         { destruct t0. \n              { destruct r1. \n                 { inversion H. subst. auto. subst. auto. subst. auto. }\n                 { destruct t0. inversion H. subst. auto. subst. auto. subst. auto. \n                   inversion H. subst. \n                   inversion H. subst. right;right;apply InLefttree;constructor;auto.\n                   subst. right;right;apply InLefttree;constructor;auto.\n                   subst. right;right;apply InLefttree;constructor;auto.\n                   subst. inversion H1. subst. auto. subst. auto. subst. \n                   right;right;apply InLefttree;apply InLefttree;auto.\n                   subst. apply rbal'_spec_tree in H1.\n                   destruct H1. right;right;constructor;auto.\n                   destruct H0. right;right;apply InLefttree;apply InRighttree;auto.\n                   right;right;apply InRighttree;apply makeRed_spec_tree;auto. }\n              }\n              { apply rbal'_spec_tree in H. destruct H. auto.\n                destruct H. auto. apply Bk_Rd in H. auto.\n              }\n       }\n    + destruct r. constructor;auto. destruct t0.\n        destruct r1. constructor;auto. destruct t0.\n        constructor;auto.  apply InLefttree;constructor;auto.\n        apply rbal'_spec_tree. auto.\n    + destruct r. apply InLefttree;auto. destruct t0.\n        destruct r1. apply InLefttree;auto. destruct t0.\n        apply InLefttree;auto. apply InLefttree;apply InLefttree;auto.\n        apply rbal'_spec_tree. auto.\n    + destruct r. inversion H. destruct t0.\n        destruct r1. apply InRighttree;auto. destruct t0.\n        apply InRighttree;auto. inversion H. \n        { subst.  apply InRighttree. \n        apply rbal'_spec_tree. auto. }\n        { subst. inversion H1.  subst. constructor. auto. \n          subst. apply InLefttree;apply InRighttree;auto.\n          subst.  apply InRighttree.\n        apply rbal'_spec_tree. auto.\n        } \n        { subst. apply InRighttree.\n        apply rbal'_spec_tree. apply makeRed_spec_tree in H1. auto. }\n        { apply rbal'_spec_tree. apply Bk_Rd in H.  auto. }\nQed.\n\n\n#[global]\nInstance lbalS_ok l x r :\n forall `(Ok l, Ok r, lt_tree x l, gt_tree x r), Ok (lbalS l x r).\nProof.\n case lbalS_match; intros.\n - ok.\n - destruct r as [|[|] rl rx rr].\n   * ok.\n   * destruct rl as [|[|] rll rlx rlr]; intros; ok.\n     + apply rbal'_ok; ok.\n       intros w; autorew; auto.\n     + intros w; autorew.\n       destruct 1 as [Hw|[Hw|Hw]]; try rewrite Hw; eauto.\n   * autorew. apply rbal'_ok; ok.\nQed.\n\nLemma rbalS_spec l x r y :\n  InT y (rbalS l x r) <-> X.eq y x \\/ InT y l \\/ InT y r.\nProof.\n case rbalS_match.\n - intros; autorew; intuition_in.\n - intros t _.\n   destruct l as [|[|] ll lx lr].\n   * autorew. intuition_in.\n   * destruct lr as [|[|] lrl lrx lrr]; autorew; intuition_in.\n   * autorew. intuition_in.\nQed.\n\n\nLemma rbalS_spec_tree l x r y :\n  Intree y (rbalS l x r) <-> y = x \\/ Intree y l \\/ Intree y r.\nProof. split. {\n case rbalS_match.\n - intuition_in. inversion H. subst. auto. subst. right. left. auto.\n   subst. right. right. apply Bk_Rd.  auto. \n - intros t _.\n   destruct l as [|[|] ll lx lr].\n   * intuition_in. inversion H. subst. auto. subst. right. left. auto.\n   subst. right. right. auto.\n   * destruct lr as [|[|] lrl lrx lrr]; intuition_in. \n    -- inversion H. subst. auto. subst. right. left. auto. subst. right. right. auto.\n    -- inversion H. subst. auto. subst. right. left. auto. subst. right. right. auto.\n    -- inversion H. subst. right. left. apply InRighttree. constructor. auto. subst.\n       right. left. apply lbal_spec_tree in H1.  destruct H1. \n       constructor.  auto. destruct H0. apply InLefttree. apply makeRed_spec_tree.\n       auto. apply InRighttree. apply InLefttree. auto. subst. \n       inversion H1. subst. auto. subst. right. left. apply InRighttree. \n       apply InRighttree. auto. subst. right. right. auto.\n   * intuition_in. apply lbal_spec_tree in H. destruct H. auto.\n      destruct H. right. left. apply Bk_Rd.  auto. right. right. auto.\n}\n{ case rbalS_match.\n - intuition_in_tree. apply Bk_Rd. constructor. auto.\n   apply Bk_Rd. apply InLefttree. auto.\n   apply Bk_Rd. apply InRighttree. constructor. auto.\n   apply Bk_Rd. apply InRighttree. apply InLefttree. auto.\n   apply Bk_Rd. apply InRighttree. apply InRighttree. auto.\n - intros t _.\n   destruct l as [|[|] ll lx lr].\n   * intuition_in_tree. constructor. auto. apply InRighttree. auto. \n   * destruct lr as [|[|] lrl lrx lrr]; intuition_in_tree.\n      + constructor. auto.\n      + apply InLefttree. constructor;auto.\n      + apply InLefttree. apply InLefttree. auto.\n      + apply InRighttree. auto.\n      + constructor. auto.\n      + apply InLefttree. constructor;auto.\n      + apply InLefttree. apply InLefttree. auto.\n      + apply InLefttree. apply InRighttree. constructor;auto.\n      + apply InLefttree. apply InRighttree. apply InLefttree. auto.\n      + apply InLefttree. apply InRighttree. apply InRighttree. auto.\n      + apply InRighttree. auto.\n      + apply InRighttree. constructor. auto.\n      + apply InLefttree. apply lbal_spec_tree. auto.\n      + apply InLefttree. apply lbal_spec_tree. right. left. \n         apply makeRed_spec_tree. auto.\n      + constructor. auto.\n      + apply InLefttree. apply lbal_spec_tree.  auto.\n      + apply InRighttree. apply InLefttree. auto.\n      + apply InRighttree. apply InRighttree. auto.\n   * intuition_in_tree. \n      + apply lbal_spec_tree. auto.\n      + apply lbal_spec_tree. right. left. constructor;auto.\n      + apply lbal_spec_tree. right. left. apply InLefttree. auto.\n      + apply lbal_spec_tree. right. left. apply InRighttree. auto.\n      + apply lbal_spec_tree. right. right. auto.\n} Qed.\n\n\n#[global]\nInstance rbalS_ok l x r :\n forall `(Ok l, Ok r, lt_tree x l, gt_tree x r), Ok (rbalS l x r).\nProof.\n case rbalS_match; intros.\n - ok.\n - destruct l as [|[|] ll lx lr].\n   * ok.\n   * destruct lr as [|[|] lrl lrx lrr]; intros; ok.\n     + apply lbal_ok; ok.\n       intros w; autorew; auto.\n     + intros w; autorew.\n       destruct 1 as [Hw|[Hw|Hw]]; try rewrite Hw; eauto.\n   * apply lbal_ok; ok.\nQed.\n\nHint Rewrite lbalS_spec rbalS_spec : rb.\nHint Rewrite lbalS_spec_tree rbalS_spec_tree : rbtree.\n\n(** ** Append for deletion *)\n\nLtac append_tac l r :=\n induction l as [| lc ll _ lx lr IHlr];\n [intro r; simpl\n |induction r as [| rc rl IHrl rx rr _];\n   [simpl\n   |destruct lc, rc;\n     [specialize (IHlr rl); clear IHrl\n     |simpl;\n      assert (Hr:notred (Bk rl rx rr)) by (simpl; trivial);\n      set (r:=Bk rl rx rr) in *; clearbody r; clear IHrl rl rx rr;\n      specialize (IHlr r)\n     |change (append _ _) with (Rd (append (Bk ll lx lr) rl) rx rr);\n      assert (Hl:notred (Bk ll lx lr)) by (simpl; trivial);\n      set (l:=Bk ll lx lr) in *; clearbody l; clear IHlr ll lx lr\n     |specialize (IHlr rl); clear IHrl]]].\n\nFact append_rr_match ll lx lr rl rx rr :\n rspec\n  (fun a x b => Rd (Rd ll lx a) x (Rd b rx rr))\n  (fun t => Rd ll lx (Rd t rx rr))\n  (append lr rl)\n  (append (Rd ll lx lr) (Rd rl rx rr)).\nProof.\n exact (rmatch _ _ _).\nQed.\n\nFact append_bb_match ll lx lr rl rx rr :\n rspec\n  (fun a x b => Rd (Bk ll lx a) x (Bk b rx rr))\n  (fun t => lbalS ll lx (Bk t rx rr))\n  (append lr rl)\n  (append (Bk ll lx lr) (Bk rl rx rr)).\nProof.\n exact (rmatch _ _ _).\nQed.\n\nLemma append_spec l r x :\n InT x (append l r) <-> InT x l \\/ InT x r.\nProof.\n revert r.\n append_tac l r; autorew; try tauto.\n - (* Red / Red *)\n   revert IHlr; case append_rr_match;\n    [intros a y b | intros t Ht]; autorew; tauto.\n - (* Black / Black *)\n   revert IHlr; case append_bb_match;\n    [intros a y b | intros t Ht]; autorew; tauto.\nQed.\n\nLemma append_spec_tree l r x :\n Intree x (append l r) <-> Intree x l \\/ Intree x r.\nProof.\n revert r.\n append_tac l r; try tauto. \n - intuition_in_tree. \n - intuition_in_tree. \n - (* Red / Red *)\n   revert IHlr; case append_rr_match;\n    [intros | intros t Ht]. \n    +  intuition_in_tree. \n      * assert(Intree x0 (Rd a x0 b)). constructor. auto. \n        apply H in H0. destruct H0. left. apply InRighttree. auto.\n        right. apply InLefttree. auto.\n      * left. constructor. auto.\n      * left. apply InLefttree. auto.\n      * assert(Intree x (Rd a x0 b)).  apply InLefttree. auto.\n        apply H in H0. destruct H0. left. apply InRighttree. auto.\n        right.  apply InLefttree. auto.\n      * right. constructor. auto.\n      * assert(Intree x (Rd a x0 b)).  apply InRighttree. auto.\n        apply H in H0. destruct H0. left. apply InRighttree. auto.\n        right.  apply InLefttree. auto.\n      * right. apply InRighttree. auto.\n      * apply InLefttree. constructor. auto.\n      * apply InLefttree. apply InLefttree.  auto.\n      * constructor. auto.\n      * apply InLefttree. apply InRighttree.  auto.\n      * apply InRighttree. apply InLefttree. auto.\n      * constructor. auto.\n      * apply InLefttree. apply InRighttree.  auto.\n      * constructor. auto.\n      * apply InLefttree. apply InRighttree.  auto.\n      * apply InLefttree. apply InRighttree.  auto.\n      * apply InLefttree. apply InRighttree.  auto.\n      * apply InRighttree. apply InLefttree. auto.\n      * apply InRighttree. apply InLefttree. auto.\n      * apply InRighttree. apply InLefttree. auto.\n      * apply InRighttree. constructor. auto.\n      * constructor. auto.\n      * constructor. auto.\n      * constructor. auto.\n      * constructor. auto.\n      * apply InLefttree. apply InRighttree.  auto.\n      * apply InLefttree. apply InRighttree.  auto.\n      * constructor. auto.\n      * apply InLefttree. apply InRighttree.  auto.\n      * apply InRighttree. apply InLefttree. auto.\n      * constructor. auto.\n      * apply InLefttree. apply InRighttree.  auto.\n      * apply InRighttree. apply InLefttree. auto.\n      * apply InRighttree. apply InRighttree.  auto.\n    + intuition_in_tree.\n      * left. constructor. auto.\n      * left. apply InLefttree. auto.\n      * right. constructor. auto.\n      * left. apply InRighttree.  auto.\n      * right. apply InLefttree. auto.\n      * right. apply InRighttree.  auto.\n      * constructor. auto.\n      * apply InLefttree. auto.\n      * apply InRighttree. apply InLefttree. auto.\n      * apply InRighttree. apply InLefttree. auto.\n      * apply InRighttree. constructor. auto.\n      * apply InRighttree. apply InLefttree. auto.\n      * apply InRighttree. apply InLefttree. auto.\n      * apply InRighttree. apply InRighttree. auto.\n - intuition_in_tree.\n      + left. constructor. auto.\n      + left. apply InLefttree. auto.\n      + left. apply InRighttree.  auto.\n      + constructor. auto.\n      + apply InLefttree. auto.\n      + apply InRighttree.  auto.\n      + apply InRighttree.  auto.\n      + apply InRighttree.  auto.\n      + apply InRighttree.  auto.\n - intuition_in_tree.\n      + right. constructor. auto.\n      + right. apply InLefttree. auto.\n      + right. apply InRighttree.  auto.\n      + apply InLefttree. auto.\n      + apply InLefttree. auto.\n      + constructor. auto.\n      + apply InLefttree. auto.\n      + apply InLefttree. auto.\n      + apply InRighttree.  auto.\n -    revert IHlr; case append_bb_match;\n    [intros | intros t Ht].\n    + intuition_in_tree.\n      * assert(Intree x0 (Rd a x0 b)). constructor. auto. \n        apply H in H0. destruct H0. left. apply InRighttree. auto.\n        right. apply InLefttree. auto.\n      * left. constructor. auto.\n      * left. apply InLefttree. auto.\n      * assert(Intree x (Rd a x0 b)).  apply InLefttree. auto.\n        apply H in H0. destruct H0. left. apply InRighttree. auto.\n        right.  apply InLefttree. auto.\n      * right. constructor. auto.\n      * assert(Intree x (Rd a x0 b)).  apply InRighttree. auto.\n        apply H in H0. destruct H0. left. apply InRighttree. auto.\n        right.  apply InLefttree. auto.\n      * right. apply InRighttree. auto.\n      * apply InLefttree. constructor. auto.\n      * apply InLefttree. apply InLefttree.  auto.\n      * constructor. auto.\n      * apply InLefttree. apply InRighttree.  auto.\n      * apply InRighttree. apply InLefttree. auto.\n      * constructor. auto.\n      * apply InLefttree. apply InRighttree.  auto.\n      * constructor. auto.\n      * apply InLefttree. apply InRighttree.  auto.\n      * apply InLefttree. apply InRighttree.  auto.\n      * apply InLefttree. apply InRighttree.  auto.\n      * apply InRighttree. apply InLefttree. auto.\n      * apply InRighttree. apply InLefttree. auto.\n      * apply InRighttree. apply InLefttree. auto.\n      * apply InRighttree. constructor. auto.\n      * constructor. auto.\n      * constructor. auto.\n      * constructor. auto.\n      * constructor. auto.\n      * apply InLefttree. apply InRighttree.  auto.\n      * apply InLefttree. apply InRighttree.  auto.\n      * constructor. auto.\n      * apply InLefttree. apply InRighttree.  auto.\n      * apply InRighttree. apply InLefttree. auto.\n      * constructor. auto.\n      * apply InLefttree. apply InRighttree.  auto.\n      * apply InRighttree. apply InLefttree. auto.\n      * apply InRighttree. apply InRighttree.  auto.\n    + intuition_in_tree.\n        * apply lbalS_spec_tree in H0. destruct H0 as [H0 | H0 ]. left. constructor.\n          auto. destruct H0 as [H0 | H0 ]. left. apply InLefttree. auto.\n          intuition_in_tree. right. constructor. auto. left. apply InRighttree.  auto.\n          right. apply InLefttree. auto. right. apply InRighttree.  auto.\n        * apply lbalS_spec_tree. auto.\n        * apply lbalS_spec_tree. auto.\n        * apply lbalS_spec_tree. right. right. apply InLefttree. auto.\n        * apply lbalS_spec_tree. right. right. apply InLefttree. auto.\n        * apply lbalS_spec_tree. right. right. constructor. auto.\n        * apply lbalS_spec_tree. right. right. apply InLefttree. auto.\n        * apply lbalS_spec_tree. right. right. apply InLefttree. auto.\n        * apply lbalS_spec_tree. right. right. apply InRighttree. auto.\nQed.\n\nHint Rewrite append_spec : rb.\nHint Rewrite append_spec_tree : rbtree.\n\nLemma append_ok : forall x l r `{Ok l, Ok r},\n lt_tree x l -> gt_tree x r -> Ok (append l r).\nProof.\n append_tac l r.\n - (* Leaf / _ *)\n   trivial.\n - (* _ / Leaf *)\n   trivial.\n - (* Red / Red *)\n   intros; inv.\n   assert (IH : Ok (append lr rl)) by (apply IHlr; eauto). clear IHlr.\n   assert (X.lt lx rx) by (transitivity x; eauto).\n   assert (G : gt_tree lx (append lr rl)).\n    { intros w. autorew. destruct 1; [|transitivity x]; eauto. }\n   assert (L : lt_tree rx (append lr rl)).\n    { intros w. autorew. destruct 1; [transitivity x|]; eauto. }\n   revert IH G L; case append_rr_match; intros; ok.\n - (* Red / Black *)\n   intros; ok.\n   intros w; autorew; destruct 1; eauto.\n - (* Black / Red *)\n   intros; ok.\n   intros w; autorew; destruct 1; eauto.\n - (* Black / Black *)\n   intros; inv.\n   assert (IH : Ok (append lr rl)) by (apply IHlr; eauto). clear IHlr.\n   assert (X.lt lx rx) by (transitivity x; eauto).\n   assert (G : gt_tree lx (append lr rl)).\n    { intros w. autorew. destruct 1; [|transitivity x]; eauto. }\n   assert (L : lt_tree rx (append lr rl)).\n    { intros w. autorew. destruct 1; [transitivity x|]; eauto. }\n   revert IH G L; case append_bb_match; intros; ok.\n    apply lbalS_ok; ok.\nQed.\n\n(** ** Deletion *)\n\nLemma del_spec : forall s x y `{Ok s},\n InT y (del x s) <-> InT y s /\\ ~X.eq y x.\nProof.\ninduct s x. \n- intuition_in.\n- autorew; intuition_in.\n  + assert (X.lt y x') by eauto. order.\n  + assert (X.lt x' y) by eauto. order.\n  + order.\n- destruct l as [|[|] ll lx lr]; autorew;\n  rewrite ?IHl by trivial; intuition_in; order.\n- destruct r as [|[|] rl rx rr]; autorew;\n  rewrite ?IHr by trivial; intuition_in; order.\nQed.\n\n\n\nLemma Intree_InT  s y :\n   Intree y s -> InT y s.\nProof. \n   induction s as [ | c l Hl x r Hr ]; simpl; auto.\n - intuition. inversion H. \n - intuition_in_tree. \n Qed.\n\n\n\n\nLemma del_spec_tree : forall s x y `{Ok s},\nIntree y (del x s) <-> Intree y s/\\~X.eq x y.\nProof. split. \n{\ninduction s.\n- intuition_in_tree. inversion H0. \n- intros. intuition_in_tree. simpl in H0.\n        destruct (X.compare x t1).\n        -- apply append_spec_tree in H0.\n        destruct H0.\n          +++ apply InLefttree. auto.\n          +++ apply InRighttree. auto.\n        -- destruct s1.\n          +++ inversion H0. \n              --- subst. constructor. auto.\n              --- subst. inversion H3.\n              --- subst. apply InRighttree. auto.\n          +++ destruct t2. \n              --- inversion H0. subst. constructor. auto. \n                  subst. apply InLefttree. apply H.  auto. \n                  subst. apply InRighttree. auto.\n              --- intuition_in. apply lbalS_spec_tree in H0. destruct H0. constructor. auto.\n                  destruct H0. apply InLefttree. apply H. auto.  \n                  apply InRighttree. auto.\n          -- destruct s2.\n          +++ inversion H0. \n              --- subst. constructor. auto.\n              --- subst. apply InLefttree. auto.\n              --- subst. inversion H3.\n          +++ destruct t2. \n              --- intuition_in_tree. constructor. auto. \n                  apply InLefttree. auto. \n                  apply InRighttree. constructor. auto. apply InRighttree.\n                  apply InLefttree. auto.  apply InRighttree.  apply InRighttree. auto.\n              --- intuition_in_tree. \n                  apply rbalS_spec_tree in H0. destruct H0. constructor. auto.\n                  destruct H0. apply InLefttree. auto. apply InRighttree. apply H1.\n                  auto. \n          -- apply Intree_InT in H0. apply del_spec in H0. \n  destruct H0. destruct H3. intuition_in_tree. auto.\n}\n{ induction s.\n- intuition_in_tree. \n- intros. intuition_in_tree. simpl. \n        destruct (X.compare x t1) eqn:Hc.\n         * destruct (X.compare_spec x t1). intuition_in_tree.\n            inversion Hc. inversion Hc.\n         * destruct s1. \n            + simpl. constructor. auto.\n            + destruct t2. \n                ++ intuition_in_tree. constructor. auto.\n                ++ apply lbalS_spec_tree. auto.\n          * destruct s2. \n            + simpl. constructor. auto.\n            + destruct t2. \n                ++  constructor. auto.\n                ++ intuition_in_tree. apply rbalS_spec_tree. auto.\n          * simpl. destruct (X.compare x t1) eqn:Hc. \n             + destruct (X.compare_spec x t1). apply append_spec_tree. \n                auto. inversion Hc. inversion Hc.\n             + destruct s1.\n                ++ intuition_in_tree.\n                ++ destruct t2.\n                    +++ intuition_in_tree.\n                        ---- apply InLefttree. apply H3. \n                        ---- apply InLefttree. apply H3. \n                       ---- apply InLefttree. apply H3. \n                    +++ apply lbalS_spec_tree. auto.\n             + destruct s2. \n                ++  apply InLefttree. auto.\n                ++  destruct t2.\n                     +++  apply InLefttree. auto.\n                     +++ apply rbalS_spec_tree. auto.\n         * simpl. destruct (X.compare x t1) eqn:Hc.\n                ++ apply append_spec_tree. auto.\n                ++ destruct s1. \n                      +++ apply InRighttree. auto.\n                      +++ destruct t2.\n                            ---- apply InRighttree. auto.\n                            ---- apply lbalS_spec_tree. auto.\n                ++ destruct s2. \n                       +++ inversion H0.\n                       +++ destruct t2.\n                            ---- apply InRighttree. auto.\n                            ---- apply rbalS_spec_tree. auto.\n} Qed.\n\nHint Rewrite del_spec : rb.\n\n#[global]\nInstance del_ok s x `{Ok s} : Ok (del x s).\nProof.\ninduct s x.\n- trivial.\n- eapply append_ok; eauto.\n- assert (lt_tree x' (del x l)).\n  { intro w. autorew; trivial. destruct 1. eauto. }\n  destruct l as [|[|] ll lx lr]; auto_tc.\n- assert (gt_tree x' (del x r)).\n  { intro w. autorew; trivial. destruct 1. eauto. }\n  destruct r as [|[|] rl rx rr]; auto_tc.\nQed.\n\nLemma remove_spec s x y `{Ok s} :\n InT y (remove x s) <-> InT y s /\\ ~X.eq y x.\nProof.\nunfold remove.  rewrite makeBlack_spec. rewrite del_spec.  split. auto. auto. auto.\nQed.\n\nLemma remove_spec_tree s x y `{Ok s} :\nIntree y (remove x s) <-> Intree y s/\\ ~X.eq x y.\nProof.\nunfold remove. rewrite makeBlack_spec_tree. apply del_spec_tree. auto.\nQed.\n\n\nHint Rewrite remove_spec : rb.\n\n#[global]\nInstance remove_ok s x `{Ok s} : Ok (remove x s).\nProof.\nunfold remove; auto_tc.\nQed.\n\n\n(** Elements_tree **)\n\n \nLemma elements_spec1'_tree : forall s acc x,\n List.In x (elements_aux acc s) <-> Intree x s \\/ List.In x acc.\nProof.\n induction s as [ | c l Hl x r Hr ]; simpl; auto.\n - intuition.\n   inversion H0.\n - intros.\n   rewrite Hl.\n   destruct (Hr acc x0); clear Hl Hr.\n   intuition_in; inversion_clear H3; intuition_in. \n    * subst. left. apply InLefttree. constructor. auto.\n    * left. apply InLefttree. apply InLefttree. auto.\n    * left. apply InLefttree. apply InRighttree. auto.\n    * subst. left. constructor. auto.\n    * left. apply InRighttree. auto.\n    * subst. simpl. auto.\nQed.\n\nLemma elements_spec_tree : forall s x, List.In x (elements s) <-> Intree x s.\nProof.\n intros; generalize (elements_spec1'_tree s nil x); intuition.\n inversion_clear H0.\nQed.\n\n\n\n(** ** Removing the minimal element *)\n\nLemma delmin_spec l y r c x s' `{O : Ok (Node c l y r)} :\n delmin l y r = (x,s') ->\n  min_elt (Node c l y r) = Some x /\\ del x (Node c l y r) = s'.\nProof.\n revert y r c x s' O.\n induction l as [|lc ll IH ly lr _].\n - simpl. intros y r _ x s' _. injection 1; intros; subst.\n   now rewrite MX.compare_refl.\n - intros y r c x s' O.\n   simpl delmin.\n   specialize (IH ly lr). destruct delmin as (x0,s0).\n   destruct (IH lc x0 s0); clear IH; [ok|trivial|].\n   remember (Node lc ll ly lr) as l.\n   simpl min_elt in *.\n   intros E.\n   replace x0 with x in * by (destruct lc; now injection E).\n   split.\n   * subst l; intuition.\n   * assert (X.lt x y).\n     { inversion_clear O.\n       assert (InT x l) by now apply min_elt_spec1. auto. }\n     simpl. case X.compare_spec; try order.\n     destruct lc; injection E; subst l s0; auto.\nQed.\n\nLemma remove_min_spec1 s x s' `{Ok s}:\n remove_min s = Some (x,s') ->\n  min_elt s = Some x /\\ remove x s = s'.\nProof.\n unfold remove_min.\n destruct s as [|c l y r]; try easy.\n generalize (delmin_spec l y r c).\n destruct delmin as (x0,s0). intros D.\n destruct (D x0 s0) as (->,<-); auto.\n fold (remove x0 (Node c l y r)).\n inversion_clear 1; auto.\nQed.\n\nLemma remove_min_spec2 s : remove_min s = None -> Empty s.\nProof.\n unfold remove_min.\n destruct s as [|c l y r].\n - easy.\n - now destruct delmin.\nQed.\n\nLemma remove_min_ok (s:t) `{Ok s}:\n match remove_min s with\n | Some (_,s') => Ok s'\n | None => True\n end.\nProof.\n generalize (remove_min_spec1 s).\n destruct remove_min as [(x0,s0)|]; auto.\n intros R. destruct (R x0 s0); auto. subst s0. auto_tc.\nQed.\n\n(** ** Treeify *)\n\nNotation ifpred p n := (if p then pred n else n%nat).\n\nDefinition treeify_invariant size (f:treeify_t) :=\n forall acc,\n size <= length acc ->\n let (t,acc') := f acc in\n cardinal t = size /\\ acc = elements t ++ acc'.\n\nLemma treeify_zero_spec : treeify_invariant 0 treeify_zero.\nProof.\n intro. simpl. auto.\nQed.\n\nLemma treeify_one_spec : treeify_invariant 1 treeify_one.\nProof.\n intros [|x acc]; simpl; auto; inversion 1.\nQed.\n\nLemma treeify_cont_spec f g size1 size2 size :\n treeify_invariant size1 f ->\n treeify_invariant size2 g ->\n size = S (size1 + size2) ->\n treeify_invariant size (treeify_cont f g).\nProof.\n intros Hf Hg EQ acc LE. unfold treeify_cont.\n specialize (Hf acc).\n destruct (f acc) as (t1,acc1).\n destruct Hf as (Hf1,Hf2).\n  { transitivity size; trivial. subst. rewrite <- Nat.add_succ_r. apply Nat.le_add_r. }\n destruct acc1 as [|x acc1].\n  { exfalso. revert LE. apply Nat.lt_nge. subst.\n    rewrite app_nil_r, <- elements_cardinal.\n    apply (Nat.succ_le_mono (cardinal t1)), Nat.le_add_r. }\n specialize (Hg acc1).\n destruct (g acc1) as (t2,acc2).\n destruct Hg as (Hg1,Hg2).\n  { revert LE. subst.\n    rewrite app_length, <- elements_cardinal. simpl.\n    rewrite Nat.add_succ_r, <- Nat.succ_le_mono.\n    apply Nat.add_le_mono_l. }\n rewrite elements_node, app_ass. now subst.\nQed.\n\nLemma treeify_aux_spec n (p:bool) :\n treeify_invariant (ifpred p (Pos.to_nat n)) (treeify_aux p n).\nProof.\n revert p.\n induction n as [n|n|]; intros p; simpl treeify_aux.\n - eapply treeify_cont_spec; [ apply (IHn false) | apply (IHn p) | ].\n   rewrite Pos2Nat.inj_xI.\n   assert (H := Pos2Nat.is_pos n). apply Nat.neq_0_lt_0 in H.\n   destruct p; simpl; intros; rewrite Nat.add_0_r; trivial.\n   now rewrite <- Nat.add_succ_r, Nat.succ_pred; trivial.\n - eapply treeify_cont_spec; [ apply (IHn p) | apply (IHn true) | ].\n   rewrite Pos2Nat.inj_xO.\n   assert (H := Pos2Nat.is_pos n). apply Nat.neq_0_lt_0 in H.\n   rewrite <- Nat.add_succ_r, Nat.succ_pred by trivial.\n   destruct p; simpl; intros; rewrite Nat.add_0_r; trivial.\n   symmetry. now apply Nat.add_pred_l.\n - destruct p; [ apply treeify_zero_spec | apply treeify_one_spec ].\nQed.\n\nLemma plength_aux_spec l p :\n  Pos.to_nat (plength_aux l p) = length l + Pos.to_nat p.\nProof.\n revert p. induction l; trivial. simpl plength_aux.\n intros. now rewrite IHl, Pos2Nat.inj_succ, Nat.add_succ_r.\nQed.\n\nLemma plength_spec l : Pos.to_nat (plength l) = S (length l).\nProof.\n unfold plength. rewrite plength_aux_spec. apply Nat.add_1_r.\nQed.\n\nLemma treeify_elements l : elements (treeify l) = l.\nProof.\n assert (H := treeify_aux_spec (plength l) true l).\n unfold treeify. destruct treeify_aux as (t,acc); simpl in *.\n destruct H as (H,H'). { now rewrite plength_spec. }\n subst l. rewrite plength_spec, app_length, <- elements_cardinal in *.\n destruct acc.\n * now rewrite app_nil_r.\n * exfalso. revert H. simpl.\n   rewrite Nat.add_succ_r, Nat.add_comm.\n   apply Nat.succ_add_discr.\nQed.\n\nLemma treeify_spec x l : InT x (treeify l) <-> InA X.eq x l.\nProof.\n intros. now rewrite <- elements_spec1, treeify_elements.\nQed.\n\n\n\nLemma treeify_ok l : sort X.lt l -> Ok (treeify l).\nProof.\n intros. apply elements_sort_ok. rewrite treeify_elements; auto.\nQed.\n\n\n(** ** Filter *)\n\n#[deprecated(since=\"8.11\",note=\"Lemma filter_app has been moved to module List.\")]\nNotation filter_app := List.filter_app.\n\nLemma filter_aux_elements s f acc :\n filter_aux f s acc = List.filter f (elements s) ++ acc.\nProof.\n revert acc.\n induction s as [|c l IHl x r IHr]; trivial.\n intros acc.\n rewrite elements_node, List.filter_app. simpl.\n destruct (f x); now rewrite IHl, IHr, app_ass.\nQed.\n\nLemma filter_elements s f :\n elements (filter f s) = List.filter f (elements s).\nProof.\n unfold filter.\n now rewrite treeify_elements, filter_aux_elements, app_nil_r.\nQed.\n\nLemma filter_spec s x f :\n Proper (X.eq==>Logic.eq) f ->\n (InT x (filter f s) <-> InT x s /\\ f x = true).\nProof.\n intros Hf.\n rewrite <- elements_spec1, filter_elements, filter_InA, elements_spec1;\n  now auto_tc.\nQed.\n\n#[global]\nInstance filter_ok s f `(Ok s) : Ok (filter f s).\nProof.\n apply elements_sort_ok.\n rewrite filter_elements.\n apply filter_sort with X.eq; auto_tc.\nQed.\n\n(** ** Partition *)\n\nLemma partition_aux_spec s f acc1 acc2 :\n partition_aux f s acc1 acc2 =\n  (filter_aux f s acc1, filter_aux (fun x => negb (f x)) s acc2).\nProof.\n revert acc1 acc2.\n induction s as [ | c l Hl x r Hr ]; simpl.\n - trivial.\n - intros acc1 acc2.\n   destruct (f x); simpl; now rewrite Hr, Hl.\nQed.\n\nLemma partition_spec s f :\n partition f s = (filter f s, filter (fun x => negb (f x)) s).\nProof.\n unfold partition, filter. now rewrite partition_aux_spec.\nQed.\n\nLemma partition_spec1 s f :\n Proper (X.eq==>Logic.eq) f ->\n Equal (fst (partition f s)) (filter f s).\nProof. now rewrite partition_spec. Qed.\n\nLemma partition_spec2 s f :\n Proper (X.eq==>Logic.eq) f ->\n Equal (snd (partition f s)) (filter (fun x => negb (f x)) s).\nProof. now rewrite partition_spec. Qed.\n\n#[global]\nInstance partition_ok1 s f `(Ok s) : Ok (fst (partition f s)).\nProof. rewrite partition_spec; now apply filter_ok. Qed.\n\n#[global]\nInstance partition_ok2 s f `(Ok s) : Ok (snd (partition f s)).\nProof. rewrite partition_spec; now apply filter_ok. Qed.\n\n\n(** ** An invariant for binary list functions with accumulator. *)\n\nLtac inA :=\n rewrite ?InA_app_iff, ?InA_cons, ?InA_nil, ?InA_rev in *; auto_tc.\n\nRecord INV l1 l2 acc : Prop := {\n l1_sorted : sort X.lt (rev l1);\n l2_sorted : sort X.lt (rev l2);\n acc_sorted : sort X.lt acc;\n l1_lt_acc x y : InA X.eq x l1 -> InA X.eq y acc -> X.lt x y;\n l2_lt_acc x y : InA X.eq x l2 -> InA X.eq y acc -> X.lt x y}.\nLocal Hint Resolve l1_sorted l2_sorted acc_sorted : core.\n\nLemma INV_init s1 s2 `(Ok s1, Ok s2) :\n INV (rev_elements s1) (rev_elements s2) nil.\nProof.\n rewrite !rev_elements_rev.\n split; rewrite ?rev_involutive; auto; intros; now inA.\nQed.\n\nLemma INV_sym l1 l2 acc : INV l1 l2 acc -> INV l2 l1 acc.\nProof.\n destruct 1; now split.\nQed.\n\nLemma INV_drop x1 l1 l2 acc :\n  INV (x1 :: l1) l2 acc -> INV l1 l2 acc.\nProof.\n intros (l1s,l2s,accs,l1a,l2a). simpl in *.\n destruct (sorted_app_inv _ _ l1s) as (U & V & W); auto.\n split; auto.\nQed.\n\nLemma INV_eq x1 x2 l1 l2 acc :\n  INV (x1 :: l1) (x2 :: l2) acc -> X.eq x1 x2 ->\n  INV l1 l2 (x1 :: acc).\nProof.\n intros (U,V,W,X,Y) EQ. simpl in *.\n destruct (sorted_app_inv _ _ U) as (U1 & U2 & U3); auto.\n destruct (sorted_app_inv _ _ V) as (V1 & V2 & V3); auto.\n split; auto.\n - constructor; auto. apply InA_InfA with X.eq; auto_tc.\n - intros x y; inA; intros Hx [Hy|Hy].\n   + apply U3; inA.\n   + apply X; inA.\n - intros x y; inA; intros Hx [Hy|Hy].\n   + rewrite Hy, EQ; apply V3; inA.\n   + apply Y; inA.\nQed.\n\nLemma INV_lt x1 x2 l1 l2 acc :\n  INV (x1 :: l1) (x2 :: l2) acc -> X.lt x1 x2 ->\n  INV (x1 :: l1) l2 (x2 :: acc).\nProof.\n intros (U,V,W,X,Y) EQ. simpl in *.\n destruct (sorted_app_inv _ _ U) as (U1 & U2 & U3); auto.\n destruct (sorted_app_inv _ _ V) as (V1 & V2 & V3); auto.\n split; auto.\n - constructor; auto. apply InA_InfA with X.eq; auto_tc.\n - intros x y; inA; intros Hx [Hy|Hy].\n   + rewrite Hy; clear Hy. destruct Hx; [order|].\n     transitivity x1; auto. apply U3; inA.\n   + apply X; inA.\n - intros x y; inA; intros Hx [Hy|Hy].\n   + rewrite Hy. apply V3; inA.\n   + apply Y; inA.\nQed.\n\nLemma INV_rev l1 l2 acc :\n INV l1 l2 acc -> Sorted X.lt (rev_append l1 acc).\nProof.\n intros. rewrite rev_append_rev.\n apply SortA_app with X.eq; eauto with *.\n intros x y. inA. eapply @l1_lt_acc; eauto.\nQed.\n\n(** ** union *)\n\nLemma union_list_ok l1 l2 acc :\n INV l1 l2 acc -> sort X.lt (union_list l1 l2 acc).\nProof.\n revert l2 acc.\n induction l1 as [|x1 l1 IH1];\n  [intro l2|induction l2 as [|x2 l2 IH2]];\n   intros acc inv.\n - eapply INV_rev, INV_sym; eauto.\n - eapply INV_rev; eauto.\n - simpl. case X.compare_spec; intro C.\n   * apply IH1. eapply INV_eq; eauto.\n   * apply (IH2 (x2::acc)). eapply INV_lt; eauto.\n   * apply IH1. eapply INV_sym, INV_lt; eauto. now apply INV_sym.\nQed.\n\n#[global]\nInstance linear_union_ok s1 s2 `(Ok s1, Ok s2) :\n Ok (linear_union s1 s2).\nProof.\n unfold linear_union. now apply treeify_ok, union_list_ok, INV_init.\nQed.\n\n#[global]\nInstance fold_add_ok s1 s2 `(Ok s1, Ok s2) :\n Ok (fold add s1 s2).\nProof.\n rewrite fold_spec, <- fold_left_rev_right.\n unfold elt in *.\n induction (rev (elements s1)); simpl; unfold flip in *; auto_tc.\nQed.\n\n#[global]\nInstance union_ok s1 s2 `(Ok s1, Ok s2) : Ok (union s1 s2).\nProof.\n unfold union. destruct compare_height; auto_tc.\nQed.\n\nLemma union_list_spec x l1 l2 acc :\n InA X.eq x (union_list l1 l2 acc) <->\n  InA X.eq x l1 \\/ InA X.eq x l2 \\/ InA X.eq x acc.\nProof.\n revert l2 acc.\n induction l1 as [|x1 l1 IH1].\n - intros l2 acc; simpl. rewrite rev_append_rev. inA. tauto.\n - induction l2 as [|x2 l2 IH2]; intros acc; simpl.\n   * rewrite rev_append_rev. inA. tauto.\n   * case X.compare_spec; intro C.\n     + rewrite IH1, !InA_cons, C; tauto.\n     + rewrite (IH2 (x2::acc)), !InA_cons. tauto.\n     + rewrite IH1, !InA_cons; tauto.\nQed.\n\nLemma linear_union_spec s1 s2 x :\n InT x (linear_union s1 s2) <-> InT x s1 \\/ InT x s2.\nProof.\n unfold linear_union.\n rewrite treeify_spec, union_list_spec, !rev_elements_rev.\n rewrite !InA_rev, InA_nil, !elements_spec1 by auto_tc.\n tauto.\nQed.\n\nLemma fold_add_spec s1 s2 x :\n InT x (fold add s1 s2) <-> InT x s1 \\/ InT x s2.\nProof.\n rewrite fold_spec, <- fold_left_rev_right.\n rewrite <- (elements_spec1 s1), <- InA_rev by auto_tc.\n unfold elt in *.\n induction (rev (elements s1)); simpl.\n - rewrite InA_nil. tauto.\n - unfold flip. rewrite add_spec', IHl, InA_cons. tauto.\nQed.\n\nLemma union_spec' s1 s2 x :\n InT x (union s1 s2) <-> InT x s1 \\/ InT x s2.\nProof.\n unfold union. destruct compare_height.\n - apply linear_union_spec.\n - apply fold_add_spec.\n - rewrite fold_add_spec. tauto.\nQed.\n\nLemma union_spec : forall s1 s2 y `{Ok s1, Ok s2},\n (InT y (union s1 s2) <-> InT y s1 \\/ InT y s2).\nProof.\n intros; apply union_spec'.\nQed.\n\n(** ** inter *)\n\nLemma inter_list_ok l1 l2 acc :\n INV l1 l2 acc -> sort X.lt (inter_list l1 l2 acc).\nProof.\n revert l2 acc.\n induction l1 as [|x1 l1 IH1]; [|induction l2 as [|x2 l2 IH2]]; simpl.\n - eauto.\n - eauto.\n - intros acc inv.\n   case X.compare_spec; intro C.\n   * apply IH1. eapply INV_eq; eauto.\n   * apply (IH2 acc). eapply INV_sym, INV_drop, INV_sym; eauto.\n   * apply IH1. eapply INV_drop; eauto.\nQed.\n\n#[global]\nInstance linear_inter_ok s1 s2 `(Ok s1, Ok s2) :\n Ok (linear_inter s1 s2).\nProof.\n unfold linear_inter. now apply treeify_ok, inter_list_ok, INV_init.\nQed.\n\n#[global]\nInstance inter_ok s1 s2 `(Ok s1, Ok s2) : Ok (inter s1 s2).\nProof.\n unfold inter. destruct compare_height; auto_tc.\nQed.\n\nLemma inter_list_spec x l1 l2 acc :\n sort X.lt (rev l1) ->\n sort X.lt (rev l2) ->\n (InA X.eq x (inter_list l1 l2 acc) <->\n   (InA X.eq x l1 /\\ InA X.eq x l2) \\/ InA X.eq x acc).\nProof.\n revert l2 acc.\n induction l1 as [|x1 l1 IH1].\n - intros l2 acc; simpl. inA. tauto.\n - induction l2 as [|x2 l2 IH2]; intros acc.\n   * simpl. inA. tauto.\n   * simpl. intros U V.\n     destruct (sorted_app_inv _ _ U) as (U1 & U2 & U3); auto.\n     destruct (sorted_app_inv _ _ V) as (V1 & V2 & V3); auto.\n     case X.compare_spec; intro C.\n     + rewrite IH1, !InA_cons, C; tauto.\n     + rewrite (IH2 acc); auto. inA. intuition; try order.\n       assert (X.lt x x1) by (apply U3; inA). order.\n     + rewrite IH1; auto. inA. intuition; try order.\n       assert (X.lt x x2) by (apply V3; inA). order.\nQed.\n\nLemma linear_inter_spec s1 s2 x `(Ok s1, Ok s2) :\n InT x (linear_inter s1 s2) <-> InT x s1 /\\ InT x s2.\nProof.\n unfold linear_inter.\n rewrite !rev_elements_rev, treeify_spec, inter_list_spec\n  by (rewrite rev_involutive; auto_tc).\n rewrite !InA_rev, InA_nil, !elements_spec1 by auto_tc. tauto.\nQed.\n\nLocal Instance mem_proper s `(Ok s) :\n Proper (X.eq ==> Logic.eq) (fun k => mem k s).\nProof.\n intros x y EQ. apply Bool.eq_iff_eq_true; rewrite !mem_spec; auto.\n now rewrite EQ.\nQed.\n\nLemma inter_spec s1 s2 y `{Ok s1, Ok s2} :\n InT y (inter s1 s2) <-> InT y s1 /\\ InT y s2.\nProof.\n unfold inter. destruct compare_height.\n - now apply linear_inter_spec.\n - rewrite filter_spec, mem_spec by auto_tc; tauto.\n - rewrite filter_spec, mem_spec by auto_tc; tauto.\nQed.\n\n(** ** difference *)\n\nLemma diff_list_ok l1 l2 acc :\n INV l1 l2 acc -> sort X.lt (diff_list l1 l2 acc).\nProof.\n revert l2 acc.\n induction l1 as [|x1 l1 IH1];\n  [intro l2|induction l2 as [|x2 l2 IH2]];\n    intros acc inv.\n - eauto.\n - unfold diff_list. eapply INV_rev; eauto.\n - simpl. case X.compare_spec; intro C.\n   * apply IH1. eapply INV_drop, INV_sym, INV_drop, INV_sym; eauto.\n   * apply (IH2 acc). eapply INV_sym, INV_drop, INV_sym; eauto.\n   * apply IH1. eapply INV_sym, INV_lt; eauto. now apply INV_sym.\nQed.\n\n#[global]\nInstance diff_inter_ok s1 s2 `(Ok s1, Ok s2) :\n Ok (linear_diff s1 s2).\nProof.\n unfold linear_inter. now apply treeify_ok, diff_list_ok, INV_init.\nQed.\n\n#[global]\nInstance fold_remove_ok s1 s2 `(Ok s2) :\n Ok (fold remove s1 s2).\nProof.\n rewrite fold_spec, <- fold_left_rev_right.\n unfold elt in *.\n induction (rev (elements s1)); simpl; unfold flip in *; auto_tc.\nQed.\n\n#[global]\nInstance diff_ok s1 s2 `(Ok s1, Ok s2) : Ok (diff s1 s2).\nProof.\n unfold diff. destruct compare_height; auto_tc.\nQed.\n\nLemma diff_list_spec x l1 l2 acc :\n sort X.lt (rev l1) ->\n sort X.lt (rev l2) ->\n (InA X.eq x (diff_list l1 l2 acc) <->\n   (InA X.eq x l1 /\\ ~InA X.eq x l2) \\/ InA X.eq x acc).\nProof.\n revert l2 acc.\n induction l1 as [|x1 l1 IH1].\n - intros l2 acc; simpl. inA. tauto.\n - induction l2 as [|x2 l2 IH2]; intros acc.\n   + intros; simpl. rewrite rev_append_rev. inA. tauto.\n   + simpl. intros U V.\n     destruct (sorted_app_inv _ _ U) as (U1 & U2 & U3); auto.\n     destruct (sorted_app_inv _ _ V) as (V1 & V2 & V3); auto.\n     case X.compare_spec; intro C.\n     * rewrite IH1; auto. f_equiv. inA. intuition; try order.\n       assert (X.lt x x1) by (apply U3; inA). order.\n     * rewrite (IH2 acc); auto. f_equiv. inA. intuition; try order.\n       assert (X.lt x x1) by (apply U3; inA). order.\n     * rewrite IH1; auto. inA. intuition; try order.\n       left; split; auto. destruct 1.\n       -- order.\n       -- assert (X.lt x x2) by (apply V3; inA). order.\nQed.\n\nLemma linear_diff_spec s1 s2 x `(Ok s1, Ok s2) :\n InT x (linear_diff s1 s2) <-> InT x s1 /\\ ~InT x s2.\nProof.\n unfold linear_diff.\n rewrite !rev_elements_rev, treeify_spec, diff_list_spec\n  by (rewrite rev_involutive; auto_tc).\n rewrite !InA_rev, InA_nil, !elements_spec1 by auto_tc. tauto.\nQed.\n\nLemma fold_remove_spec s1 s2 x `(Ok s2) :\n  InT x (fold remove s1 s2) <-> InT x s2 /\\ ~InT x s1.\nProof.\n rewrite fold_spec, <- fold_left_rev_right.\n rewrite <- (elements_spec1 s1), <- InA_rev by auto_tc.\n unfold elt in *.\n induction (rev (elements s1)); simpl; intros.\n - rewrite InA_nil. intuition.\n - unfold flip in *. rewrite remove_spec, IHl, InA_cons.\n   + tauto.\n   + clear IHl. induction l; simpl; auto_tc.\nQed.\n\nLemma diff_spec s1 s2 y `{Ok s1, Ok s2} :\n InT y (diff s1 s2) <-> InT y s1 /\\ ~InT y s2.\nProof.\n unfold diff. destruct compare_height.\n - now apply linear_diff_spec.\n - rewrite filter_spec, Bool.negb_true_iff,\n     <- Bool.not_true_iff_false, mem_spec;\n    intuition.\n    intros x1 x2 EQ. f_equal. now apply mem_proper.\n - now apply fold_remove_spec.\nQed.\n\nEnd MakeRaw.\n\n(** * Balancing properties\n\n    We now prove that all operations preserve a red-black invariant,\n    and that trees have hence a logarithmic depth.\n*)\n\nModule BalanceProps(X:Orders.OrderedType)(Import M : MakeRaw X).\n\nLocal Notation Rd := (Node Red).\nLocal Notation Bk := (Node Black).\nImport M.MX.\n\n(** ** Red-Black invariants *)\n\n(** In a red-black tree :\n    - a red node has no red children\n    - the black depth at each node is the same along all paths.\n    The black depth is here an argument of the predicate. *)\n\nInductive rbt : nat -> tree -> Prop :=\n | RB_Leaf : rbt 0 Leaf\n | RB_Rd n l k r :\n   notred l -> notred r -> rbt n l -> rbt n r -> rbt n (Rd l k r)\n | RB_Bk n l k r : rbt n l -> rbt n r -> rbt (S n) (Bk l k r).\n\n(** A red-red tree is almost a red-black tree, except that it has\n    a _red_ root node which _may_ have red children. Note that a\n    red-red tree is hence non-empty, and all its strict subtrees\n    are red-black. *)\n\nInductive rrt (n:nat) : tree -> Prop :=\n | RR_Rd l k r : rbt n l -> rbt n r -> rrt n (Rd l k r).\n\n(** An almost-red-black tree is almost a red-black tree, except that\n    it's permitted to have two red nodes in a row at the very root (only).\n    We implement this notion by saying that a quasi-red-black tree\n    is either a red-black tree or a red-red tree. *)\n\nInductive arbt (n:nat)(t:tree) : Prop :=\n | ARB_RB : rbt n t -> arbt n t\n | ARB_RR : rrt n t -> arbt n t.\n\n(** The main exported invariant : being a red-black tree for some\n    black depth. *)\n\nClass Rbt (t:tree) :=  RBT : exists d, rbt d t.\n\n(** ** Basic tactics and results about red-black *)\n\nScheme rbt_ind := Induction for rbt Sort Prop.\nLocal Hint Constructors rbt rrt arbt : core.\nLocal Hint Extern 0 (notred _) => (exact I) : core.\nLtac invrb := intros; invtree rrt; invtree rbt; try contradiction.\nLtac desarb := match goal with H:arbt _ _ |- _ => destruct H end.\nLtac nonzero n := destruct n as [|n]; [try split; invrb|].\n\nLemma rr_nrr_rb n t :\n rrt n t -> notredred t -> rbt n t.\nProof.\n destruct 1 as [l x r Hl Hr].\n destruct l, r; descolor; invrb; auto.\nQed.\n\nLocal Hint Resolve rr_nrr_rb : core.\n\nLemma arb_nrr_rb n t :\n arbt n t -> notredred t -> rbt n t.\nProof.\n destruct 1; auto.\nQed.\n\nLemma arb_nr_rb n t :\n arbt n t -> notred t -> rbt n t.\nProof.\n destruct 1; destruct t; descolor; invrb; auto.\nQed.\n\nLocal Hint Resolve arb_nrr_rb arb_nr_rb : core.\n\n(** ** A Red-Black tree has indeed a logarithmic depth *)\n\nDefinition redcarac s := rcase (fun _ _ _ => 1) (fun _ => 0) s.\n\nLemma rb_maxdepth s n : rbt n s -> maxdepth s <= 2*n + redcarac s.\nProof.\n induction 1.\n - simpl; auto.\n - replace (redcarac l) with 0 in * by now destree l.\n   replace (redcarac r) with 0 in * by now destree r.\n   simpl maxdepth. simpl redcarac.\n   rewrite Nat.add_succ_r, <- Nat.succ_le_mono.\n   now apply Nat.max_lub.\n - simpl. rewrite <- Nat.succ_le_mono.\n   apply Nat.max_lub; eapply Nat.le_trans; eauto;\n   [destree l | destree r]; simpl;\n   rewrite !Nat.add_0_r, ?Nat.add_1_r, ?Nat.add_succ_r; auto.\nQed.\n\nLemma rb_mindepth s n : rbt n s -> n + redcarac s <= mindepth s.\nProof.\n induction 1; simpl.\n - trivial.\n - rewrite Nat.add_succ_r.\n   apply -> Nat.succ_le_mono.\n   replace (redcarac l) with 0 in * by now destree l.\n   replace (redcarac r) with 0 in * by now destree r.\n   now apply Nat.min_glb.\n - apply -> Nat.succ_le_mono. rewrite Nat.add_0_r.\n   apply Nat.min_glb.\n   + refine (Nat.le_trans _ _ _ _ IHrbt1).\n     apply Nat.le_add_r.\n   + refine (Nat.le_trans _ _ _ _ IHrbt2).\n     apply Nat.le_add_r.\nQed.\n\nLemma maxdepth_upperbound s : Rbt s ->\n maxdepth s <= 2 * Nat.log2 (S (cardinal s)).\nProof.\n intros (n,H).\n eapply Nat.le_trans; [eapply rb_maxdepth; eauto|].\n transitivity (2*(n+redcarac s)).\n - rewrite Nat.mul_add_distr_l. apply Nat.add_le_mono_l.\n   rewrite <- Nat.mul_1_l at 1. apply Nat.mul_le_mono_r.\n   auto.\n - apply Nat.mul_le_mono_l.\n   transitivity (mindepth s).\n   + now apply rb_mindepth.\n   + apply mindepth_log_cardinal.\nQed.\n\nLemma maxdepth_lowerbound s : s<>Leaf ->\n Nat.log2 (cardinal s) < maxdepth s.\nProof.\n apply maxdepth_log_cardinal.\nQed.\n\n\n(** ** Singleton *)\n\nLemma singleton_rb x : Rbt (singleton x).\nProof.\n unfold singleton. exists 1; auto.\nQed.\n\n(** ** [makeBlack] and [makeRed] *)\n\nLemma makeBlack_rb n t : arbt n t -> Rbt (makeBlack t).\nProof.\n destruct t as [|[|] l x r].\n - exists 0; auto.\n - destruct 1; invrb; exists (S n); simpl; auto.\n - exists n; auto.\nQed.\n\nLemma makeRed_rr t n :\n rbt (S n) t -> notred t -> rrt n (makeRed t).\nProof.\n destruct t as [|[|] l x r]; invrb; simpl; auto.\nQed.\n\n(** ** Balancing *)\n\nLemma lbal_rb n l k r :\n arbt n l -> rbt n r -> rbt (S n) (lbal l k r).\nProof.\ncase lbal_match; intros; desarb; invrb; auto.\nQed.\n\nLemma rbal_rb n l k r :\n rbt n l -> arbt n r -> rbt (S n) (rbal l k r).\nProof.\ncase rbal_match; intros; desarb; invrb; auto.\nQed.\n\nLemma rbal'_rb n l k r :\n rbt n l -> arbt n r -> rbt (S n) (rbal' l k r).\nProof.\ncase rbal'_match; intros; desarb; invrb; auto.\nQed.\n\nLemma lbalS_rb n l x r :\n arbt n l -> rbt (S n) r -> notred r -> rbt (S n) (lbalS l x r).\nProof.\n intros Hl Hr Hr'.\n destruct r as [|[|] rl rx rr]; invrb. clear Hr'.\n revert Hl.\n case lbalS_match.\n - destruct 1; invrb; auto.\n - intros. apply rbal'_rb; auto.\nQed.\n\nLemma lbalS_arb n l x r :\n arbt n l -> rbt (S n) r -> arbt (S n) (lbalS l x r).\nProof.\n case lbalS_match.\n - destruct 1; invrb; auto.\n - clear l. intros l Hl Hl' Hr.\n   destruct r as [|[|] rl rx rr]; invrb.\n   * destruct rl as [|[|] rll rlx rlr]; invrb.\n     right; auto using rbal'_rb, makeRed_rr.\n   * left; apply rbal'_rb; auto.\nQed.\n\nLemma rbalS_rb n l x r :\n rbt (S n) l -> notred l -> arbt n r -> rbt (S n) (rbalS l x r).\nProof.\n intros Hl Hl' Hr.\n destruct l as [|[|] ll lx lr]; invrb. clear Hl'.\n revert Hr.\n case rbalS_match.\n - destruct 1; invrb; auto.\n - intros. apply lbal_rb; auto.\nQed.\n\nLemma rbalS_arb n l x r :\n rbt (S n) l -> arbt n r -> arbt (S n) (rbalS l x r).\nProof.\n case rbalS_match.\n - destruct 2; invrb; auto.\n - clear r. intros r Hr Hr' Hl.\n   destruct l as [|[|] ll lx lr]; invrb.\n   * destruct lr as [|[|] lrl lrx lrr]; invrb.\n     right; auto using lbal_rb, makeRed_rr.\n   * left; apply lbal_rb; auto.\nQed.\n\n\n(** ** Insertion *)\n\n(** The next lemmas combine simultaneous results about rbt and arbt.\n    A first solution here: statement with [if ... then ... else] *)\n\nDefinition ifred s (A B:Prop) := rcase (fun _ _ _ => A) (fun _ => B) s.\n\nLemma ifred_notred s A B : notred s -> (ifred s A B <-> B).\nProof.\n destruct s; descolor; simpl; intuition.\nQed.\n\nLemma ifred_or s A B : ifred s A B -> A\\/B.\nProof.\n destruct s; descolor; simpl; intuition.\nQed.\n\nLemma ins_rr_rb x s n : rbt n s ->\n ifred s (rrt n (ins x s)) (rbt n (ins x s)).\nProof.\ninduction 1 as [ | n l k r | n l k r Hl IHl Hr IHr ].\n- simpl; auto.\n- simpl. rewrite ifred_notred in * by trivial.\n  elim_compare x k; auto.\n- rewrite ifred_notred by trivial.\n  unfold ins; fold ins. (* simpl is too much here ... *)\n  elim_compare x k.\n  * auto.\n  * apply lbal_rb; trivial. apply ifred_or in IHl; intuition.\n  * apply rbal_rb; trivial. apply ifred_or in IHr; intuition.\nQed.\n\nLemma ins_arb x s n : rbt n s -> arbt n (ins x s).\nProof.\n intros H. apply (ins_rr_rb x), ifred_or in H. intuition.\nQed.\n\n#[global]\nInstance add_rb x s : Rbt s -> Rbt (add x s).\nProof.\n intros (n,H). unfold add. now apply (makeBlack_rb n), ins_arb.\nQed.\n\n(** ** Deletion *)\n\n(** A second approach here: statement with ... /\\ ... *)\n\nLemma append_arb_rb n l r : rbt n l -> rbt n r ->\n (arbt n (append l r)) /\\\n (notred l -> notred r -> rbt n (append l r)).\nProof.\nrevert r n.\nappend_tac l r.\n- split; auto.\n- split; auto.\n- (* Red / Red *)\n  intros n. invrb.\n  case (IHlr n); auto; clear IHlr.\n  case append_rr_match.\n  + intros a x b _ H; split; invrb.\n    assert (rbt n (Rd a x b)) by auto. invrb. auto.\n  + split; invrb; auto.\n- (* Red / Black *)\n  split; invrb. destruct (IHlr n) as (_,IH); auto.\n- (* Black / Red *)\n  split; invrb. destruct (IHrl n) as (_,IH); auto.\n- (* Black / Black *)\n  nonzero n.\n  invrb.\n  destruct (IHlr n) as (IH,_); auto; clear IHlr.\n  revert IH.\n  case append_bb_match.\n  + intros a x b IH; split; destruct IH; invrb; auto.\n  + split; [left | invrb]; auto using lbalS_rb.\nQed.\n\n(** A third approach : Lemma ... with ... *)\n\nLemma del_arb s x n : rbt (S n) s -> isblack s -> arbt n (del x s)\nwith del_rb s x n : rbt n s -> notblack s -> rbt n (del x s).\nProof.\n{ revert n.\n  induct s x; try destruct c; try contradiction; invrb.\n  - apply append_arb_rb; assumption.\n  - assert (IHl' := del_rb l x). clear IHr del_arb del_rb.\n    destruct l as [|[|] ll lx lr]; auto.\n    nonzero n. apply lbalS_arb; auto.\n  - assert (IHr' := del_rb r x). clear IHl del_arb del_rb.\n    destruct r as [|[|] rl rx rr]; auto.\n    nonzero n. apply rbalS_arb; auto. }\n{ revert n.\n  induct s x; try assumption; try destruct c; try contradiction; invrb.\n  - apply append_arb_rb; assumption.\n  - assert (IHl' := del_arb l x). clear IHr del_arb del_rb.\n    destruct l as [|[|] ll lx lr]; auto.\n    nonzero n. destruct n as [|n]; [invrb|]; apply lbalS_rb; auto.\n  - assert (IHr' := del_arb r x). clear IHl del_arb del_rb.\n    destruct r as [|[|] rl rx rr]; auto.\n    nonzero n. apply rbalS_rb; auto. }\nQed.\n\n#[global]\nInstance remove_rb s x : Rbt s -> Rbt (remove x s).\nProof.\n intros (n,H). unfold remove.\n destruct s as [|[|] l y r].\n - apply (makeBlack_rb n). auto.\n - apply (makeBlack_rb n). left. apply del_rb; simpl; auto.\n - nonzero n. apply (makeBlack_rb n). apply del_arb; simpl; auto.\nQed.\n\n(** ** Treeify *)\n\nDefinition treeify_rb_invariant size depth (f:treeify_t) :=\n forall acc,\n size <= length acc ->\n  rbt depth (fst (f acc)) /\\\n  size + length (snd (f acc)) = length acc.\n\nLemma treeify_zero_rb : treeify_rb_invariant 0 0 treeify_zero.\nProof.\n intros acc _; simpl; auto.\nQed.\n\nLemma treeify_one_rb : treeify_rb_invariant 1 0 treeify_one.\nProof.\n intros [|x acc]; simpl; auto; inversion 1.\nQed.\n\nLemma treeify_cont_rb f g size1 size2 size d :\n treeify_rb_invariant size1 d f ->\n treeify_rb_invariant size2 d g ->\n size = S (size1 + size2) ->\n treeify_rb_invariant size (S d) (treeify_cont f g).\nProof.\n intros Hf Hg H acc Hacc.\n unfold treeify_cont.\n specialize (Hf acc).\n destruct (f acc) as (l, acc1). simpl in *.\n destruct Hf as (Hf1, Hf2).\n { subst. refine (Nat.le_trans _ _ _ _ Hacc).\n   rewrite <- Nat.add_succ_r. apply Nat.le_add_r. }\n destruct acc1 as [|x acc2]; simpl in *.\n - exfalso. revert Hacc. apply Nat.lt_nge. rewrite H, <- Hf2.\n   rewrite Nat.add_0_r. apply (Nat.succ_le_mono size1), Nat.le_add_r.\n - specialize (Hg acc2).\n   destruct (g acc2) as (r, acc3). simpl in *.\n   destruct Hg as (Hg1, Hg2).\n   { revert Hacc.\n     rewrite H, <- Hf2, Nat.add_succ_r, <- Nat.succ_le_mono.\n     apply Nat.add_le_mono_l. }\n   split; auto.\n   now rewrite H, <- Hf2, <- Hg2, Nat.add_succ_r, Nat.add_assoc.\nQed.\n\nLemma treeify_aux_rb n :\n exists d, forall (b:bool),\n  treeify_rb_invariant (ifpred b (Pos.to_nat n)) d (treeify_aux b n).\nProof.\n induction n as [n (d,IHn)|n (d,IHn)| ].\n - exists (S d). intros b.\n   eapply treeify_cont_rb; [ apply (IHn false) | apply (IHn b) | ].\n   rewrite Pos2Nat.inj_xI.\n   assert (H := Pos2Nat.is_pos n). apply Nat.neq_0_lt_0 in H.\n   destruct b; simpl; intros; rewrite Nat.add_0_r; trivial.\n   now rewrite <- Nat.add_succ_r, Nat.succ_pred; trivial.\n - exists (S d). intros b.\n   eapply treeify_cont_rb; [ apply (IHn b) | apply (IHn true) | ].\n   rewrite Pos2Nat.inj_xO.\n   assert (H := Pos2Nat.is_pos n). apply Nat.neq_0_lt_0 in H.\n   rewrite <- Nat.add_succ_r, Nat.succ_pred by trivial.\n   destruct b; simpl; intros; rewrite Nat.add_0_r; trivial.\n   symmetry. now apply Nat.add_pred_l.\n - exists 0; destruct b;\n    [ apply treeify_zero_rb | apply treeify_one_rb ].\nQed.\n\n(** The black depth of [treeify l] is actually a log2, but\n    we don't need to mention that. *)\n\n#[global]\nInstance treeify_rb l : Rbt (treeify l).\nProof.\n unfold treeify.\n destruct (treeify_aux_rb (plength l)) as (d,H).\n exists d.\n apply H.\n now rewrite plength_spec.\nQed.\n\n(** ** Filtering *)\n\n#[global]\nInstance filter_rb f s : Rbt (filter f s).\nProof.\n unfold filter; auto_tc.\nQed.\n\n#[global]\nInstance partition_rb1 f s : Rbt (fst (partition f s)).\nProof.\n unfold partition. destruct partition_aux. simpl. auto_tc.\nQed.\n\n#[global]\nInstance partition_rb2 f s : Rbt (snd (partition f s)).\nProof.\n unfold partition. destruct partition_aux. simpl. auto_tc.\nQed.\n\n(** ** Union, intersection, difference *)\n\n#[global]\nInstance fold_add_rb s1 s2 : Rbt s2 -> Rbt (fold add s1 s2).\nProof.\n intros. rewrite fold_spec, <- fold_left_rev_right. unfold elt in *.\n induction (rev (elements s1)); simpl; unfold flip in *; auto_tc.\nQed.\n\n#[global]\nInstance fold_remove_rb s1 s2 : Rbt s2 -> Rbt (fold remove s1 s2).\nProof.\n intros. rewrite fold_spec, <- fold_left_rev_right. unfold elt in *.\n induction (rev (elements s1)); simpl; unfold flip in *; auto_tc.\nQed.\n\nLemma union_rb s1 s2 : Rbt s1 -> Rbt s2 -> Rbt (union s1 s2).\nProof.\n intros. unfold union, linear_union. destruct compare_height; auto_tc.\nQed.\n\nLemma inter_rb s1 s2 : Rbt s1 -> Rbt s2 -> Rbt (inter s1 s2).\nProof.\n intros. unfold inter, linear_inter. destruct compare_height; auto_tc.\nQed.\n\nLemma diff_rb s1 s2 : Rbt s1 -> Rbt s2 -> Rbt (diff s1 s2).\nProof.\n intros. unfold diff, linear_diff. destruct compare_height; auto_tc.\nQed.\n\nEnd BalanceProps.\n\n(** * Final Encapsulation\n\n   Now, in order to really provide a functor implementing [S], we\n   need to encapsulate everything into a type of binary search trees.\n   They also happen to be well-balanced, but this has no influence\n   on the correctness of operations, so we won't state this here,\n   see [BalanceProps] if you need more than just the MSet interface.\n*)\n\nModule Type MSetInterface_S_Ext := MSetInterface.S <+ MSetRemoveMin.\n\nModule Make (X: Orders.OrderedType) <:\n MSetInterface_S_Ext with Module E := X.\n Module Raw. Include MakeRaw X. End Raw.\n Include MSetInterface.Raw2Sets X Raw.\n\n Definition opt_ok (x:option (elt * Raw.t)) :=\n  match x with Some (_,s) => Raw.Ok s | None => True end.\n\n Definition mk_opt_t (x: option (elt * Raw.t))(P: opt_ok x) :\n   option (elt * t) :=\n match x as o return opt_ok o -> option (elt * t) with\n | Some (k,s') => fun P : Raw.Ok s' => Some (k, Mkt s')\n | None => fun _ => None\n end P.\n\n Definition remove_min s : option (elt * t) :=\n  mk_opt_t (Raw.remove_min (this s)) (Raw.remove_min_ok s).\n\n Lemma remove_min_spec1 s x s' :\n  remove_min s = Some (x,s') ->\n   min_elt s = Some x /\\ Equal (remove x s) s'.\n Proof.\n destruct s as (s,Hs).\n unfold remove_min, mk_opt_t, min_elt, remove, Equal, In; simpl.\n generalize (fun x s' => @Raw.remove_min_spec1 s x s' Hs).\n set (P := Raw.remove_min_ok s). clearbody P.\n destruct (Raw.remove_min s) as [(x0,s0)|]; try easy.\n intros H [= -> <-]. simpl.\n destruct (H x s0); auto. subst; intuition.\n Qed.\n\n Lemma remove_min_spec2 s : remove_min s = None -> Empty s.\n Proof.\n destruct s as (s,Hs).\n unfold remove_min, mk_opt_t, Empty, In; simpl.\n generalize (Raw.remove_min_spec2 s).\n set (P := Raw.remove_min_ok s). clearbody P.\n destruct (Raw.remove_min s) as [(x0,s0)|]; now intuition.\n Qed.\n\nEnd Make.\n\n\n", "meta": {"author": "ganitsutra", "repo": "ecda", "sha": "0ba91a66769e5588255c25e2d847e118cfd65813", "save_path": "github-repos/coq/ganitsutra-ecda", "path": "github-repos/coq/ganitsutra-ecda/ecda-0ba91a66769e5588255c25e2d847e118cfd65813/formalization/RBT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2680326628819653}}
{"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 Import trajectory_const.\nRequire Import trajectory_def.\nRequire Import constants.\nRequire Import ycngftys.\nRequire Import ycngstys.\nRequire Import tau.\nRequire Import ails.\nRequire Import trajectory.\nRequire Import measure2state.\n\nLemma d_distance :\n forall (intr : Trajectory) (evad : EvaderTrajectory),\n distance (measure2state (tr evad) 0) (measure2state intr 0) = d intr evad.\nProof with trivial.\nunfold distance, d in |- *; unfold Die in |- *; simpl in |- *;\n unfold xi, yi in |- *...\nQed.\n\nLemma R_T :\n forall (intr : Trajectory) (evad : EvaderTrajectory) (T : TimeT),\n h (tr evad) = V ->\n Rsqr (RR (measure2state intr 0) (measure2state (tr evad) 0) T) =\n (Rsqr (l intr evad T * cos (beta intr evad T + thetat intr 0) - V * T) +\n  Rsqr (l intr evad T * sin (beta intr evad T + thetat intr 0)))%R.\nProof with trivial.\nintros intr evad T hyp_evad; rewrite Rsqr_minus...\nunfold Rminus in |- *...\nrepeat rewrite Rplus_assoc...\nset (z := 250%R)...\nrewrite\n (Rplus_comm (Rsqr (l intr evad T * cos (beta intr evad T + thetat intr 0))))\n ...\nrepeat rewrite Rplus_assoc...\nreplace\n (Rsqr (l intr evad T * sin (beta intr evad T + thetat intr 0)) +\n  Rsqr (l intr evad T * cos (beta intr evad T + thetat intr 0)))%R with\n (Rsqr (l intr evad T))...\nrewrite <- (Rplus_comm (Rsqr (l intr evad T)))...\nrepeat rewrite <- Rplus_assoc...\nreplace\n (2 * (l intr evad T * cos (beta intr evad T + thetat intr 0)) * (V * T))%R\n with\n (2 * (l intr evad T * (V * T) * cos (beta intr evad T + thetat intr 0)))%R...\ncut\n (l intr evad T =\n  dist_euc (x (tr evad) T) (y (tr evad) T) (x intr 0%R) (y intr 0%R))...\nintro...\nrewrite H...\ncut\n ((V * T)%R =\n  dist_euc (x (tr evad) 0%R + T * z - T * z * cos (thetat intr 0))\n    (y (tr evad) 0%R - T * z * sin (thetat intr 0)) \n    (x (tr evad) T) (y (tr evad) T))...\nintro...\nrewrite H0...\ncut\n (RR (measure2state intr 0) (measure2state (tr evad) 0) T =\n  dist_euc (x (tr evad) 0%R + T * z - T * z * cos (thetat intr 0))\n    (y (tr evad) 0%R - T * z * sin (thetat intr 0)) \n    (x intr 0%R) (y intr 0%R))...\nintro; rewrite H1...\nreplace\n (Rsqr\n    (dist_euc (x (tr evad) 0 + T * z - T * z * cos (thetat intr 0))\n       (y (tr evad) 0 - T * z * sin (thetat intr 0)) \n       (x (tr evad) T) (y (tr evad) T)) +\n  Rsqr (dist_euc (x (tr evad) T) (y (tr evad) T) (x intr 0) (y intr 0)) +\n  -\n  (2 *\n   (dist_euc (x (tr evad) T) (y (tr evad) T) (x intr 0) (y intr 0) *\n    dist_euc (x (tr evad) 0 + T * z - T * z * cos (thetat intr 0))\n      (y (tr evad) 0 - T * z * sin (thetat intr 0)) \n      (x (tr evad) T) (y (tr evad) T) *\n    cos (beta intr evad T + thetat intr 0))))%R with\n (Rsqr\n    (dist_euc (x (tr evad) 0 + T * z - T * z * cos (thetat intr 0))\n       (y (tr evad) 0 - T * z * sin (thetat intr 0)) \n       (x (tr evad) T) (y (tr evad) T)) +\n  Rsqr (dist_euc (x (tr evad) T) (y (tr evad) T) (x intr 0) (y intr 0)) -\n  2 *\n  (dist_euc (x (tr evad) T) (y (tr evad) T) (x intr 0) (y intr 0) *\n   dist_euc (x (tr evad) 0 + T * z - T * z * cos (thetat intr 0))\n     (y (tr evad) 0 - T * z * sin (thetat intr 0)) \n     (x (tr evad) T) (y (tr evad) T) * cos (beta intr evad T + thetat intr 0)))%R...\napply law_cosines...\nunfold dist_euc in |- *...\nreplace\n (sqrt\n    (Rsqr (x (tr evad) T - x intr 0%R) + Rsqr (y (tr evad) T - y intr 0%R)))\n with (l intr evad T)...\ngeneralize (tr_cond1 evad (val T))...\nintro; rewrite H2...\ngeneralize (tr_cond2 evad (val T)); intro...\nrewrite H3...\nreplace\n (x (tr evad) 0 + T * z - T * z * cos (thetat intr 0) -\n  (x (tr evad) 0 + h (tr evad) * T))%R with (- T * z * cos (thetat intr 0))%R...\nreplace (y (tr evad) 0 - T * z * sin (thetat intr 0) - y (tr evad) 0)%R with\n (- T * z * sin (thetat intr 0))%R...\nreplace\n (Rsqr (- T * z * cos (thetat intr 0)) + Rsqr (- T * z * sin (thetat intr 0)))%R\n with (Rsqr (T * z))...\nrewrite sqrt_Rsqr...\nrewrite <- H2...\nrewrite <- H3...\ngeneralize xe_0; intro...\nunfold xe, xi in H4...\nrewrite (H4 intr evad T)...\ngeneralize ye_0; intro...\nunfold ye, yi in H5...\nrewrite (H5 intr evad T)...\nreplace (x intr 0 - (l intr evad T * cos (beta intr evad T) + x intr 0))%R\n with (- (l intr evad T * cos (beta intr evad T)))%R...\nunfold Rminus in |- *...\nreplace\n (y intr 0 + - (y intr 0 + - (l intr evad T * sin (beta intr evad T))))%R\n with (l intr evad T * sin (beta intr evad T))%R...\nrewrite cos_plus...\nunfold Rminus in |- *...\nrewrite Rmult_plus_distr_l...\nreplace\n (- (l intr evad T * cos (beta intr evad T)) *\n  (- T * z * cos (thetat intr 0)) +\n  l intr evad T * sin (beta intr evad T) * (- T * z * sin (thetat intr 0)))%R\n with\n (l intr evad T * cos (beta intr evad T) * T * z * cos (thetat intr 0) +\n  l intr evad T * - sin (beta intr evad T) * T * z * sin (thetat intr 0))%R...\nreplace (- (sin (beta intr evad T) * sin (thetat intr 0)))%R with\n (- sin (beta intr evad T) * sin (thetat intr 0))%R...\nrepeat rewrite <- Rmult_assoc...\nrepeat rewrite Rmult_assoc...\npattern (cos (beta intr evad T)) at 1 in |- *;\n rewrite (Rmult_comm (cos (beta intr evad T)))...\nrepeat rewrite <- Rmult_assoc...\nreplace\n (l intr evad T * T * z * cos (beta intr evad T) * cos (thetat intr 0))%R\n with\n (l intr evad T * T * z * cos (thetat intr 0) * cos (beta intr evad T))%R...\napply Rplus_eq_compat_l...\nrepeat rewrite Rmult_assoc...\napply Rmult_eq_compat_l...\nrepeat rewrite <- Rmult_assoc...\nrepeat rewrite <- (Rmult_comm (sin (thetat intr 0)))...\nrepeat rewrite Rmult_assoc...\napply Rmult_eq_compat_l...\nrewrite (Rmult_comm (- sin (beta intr evad T)))...\nrepeat rewrite Rmult_assoc...\nrepeat rewrite Rmult_assoc...\nrepeat apply Rmult_eq_compat_l...\nring...\nrewrite Ropp_mult_distr_l_reverse...\nrewrite <- Ropp_mult_distr_l_reverse...\nreplace\n (- l intr evad T * cos (beta intr evad T) * (- T * z * cos (thetat intr 0)))%R\n with\n (l intr evad T * cos (beta intr evad T) * T * z * cos (thetat intr 0))%R...\napply Rplus_eq_compat_l...\nrepeat rewrite Rmult_assoc...\napply Rmult_eq_compat_l...\nrepeat rewrite <- Rmult_assoc...\nrepeat rewrite <- (Rmult_comm (sin (thetat intr 0)))...\napply Rmult_eq_compat_l...\nrepeat rewrite <- (Rmult_comm z)...\napply Rmult_eq_compat_l...\nring...\nrepeat rewrite <- Rmult_assoc...\nrepeat rewrite <- (Rmult_comm (cos (thetat intr 0)))...\napply Rmult_eq_compat_l...\nrepeat rewrite <- (Rmult_comm z)...\napply Rmult_eq_compat_l...\nring...\nring...\nring...\nleft; apply Rmult_lt_0_compat...\napply Rlt_le_trans with MinT...\napply MinT_is_pos...\napply (cond_1 T)...\nunfold z in |- *; prove_sup...\nreplace (- T * z * cos (thetat intr 0))%R with\n (- T * (z * cos (thetat intr 0)))%R...\nreplace (- T * z * sin (thetat intr 0))%R with\n (- T * (z * sin (thetat intr 0)))%R...\nrepeat rewrite Rsqr_mult...\nrepeat rewrite <- Rsqr_neg...\nrewrite cos2...\nunfold Rminus in |- *; rewrite Rmult_plus_distr_l...\nrewrite Rmult_1_r...\nring...\nrepeat rewrite Rmult_assoc...\nrepeat rewrite Rmult_assoc...\nunfold Rminus in |- *...\nrewrite (Rplus_comm (y (tr evad) 0%R))...\nrepeat rewrite Rplus_assoc...\nrewrite Rplus_opp_r; rewrite Rplus_0_r...\nrepeat rewrite <- Ropp_mult_distr_l_reverse...\nrewrite hyp_evad...\nreplace (v V) with z...\nunfold Rminus in |- *...\nring...\nunfold Rminus in |- *; unfold RR, dist_euc in |- *...\nreplace\n (sqrt\n    (Rsqr (dx (measure2state intr 0) (measure2state (tr evad) 0) T) +\n     Rsqr (dy (measure2state intr 0) (measure2state (tr evad) 0) T))) with\n (sqrt\n    (Rsqr\n       (x intr 0%R + T * z * cosd (toDeg (theta intr 0%R)) -\n        (x (tr evad) 0%R + T * z)) +\n     Rsqr\n       (y intr 0%R + T * z * sind (toDeg (theta intr 0%R)) - y (tr evad) 0%R)))...\nunfold cosd, sind, thetat in |- *...\nrewrite rad_deg...\nrewrite\n (Rsqr_neg\n    (x intr 0%R + T * z * cos (theta intr 0%R) - (x (tr evad) 0%R + T * z)))\n ...\nrewrite\n (Rsqr_neg (y intr 0%R + T * z * sin (theta intr 0%R) - y (tr evad) 0%R))\n ...\nreplace\n (- (x intr 0 + T * z * cos (theta intr 0) - (x (tr evad) 0 + T * z)))%R with\n (x (tr evad) 0 + T * z - T * z * cos (theta intr 0) - x intr 0)%R...\nreplace (- (y intr 0 + T * z * sin (theta intr 0) - y (tr evad) 0))%R with\n (y (tr evad) 0 - T * z * sin (theta intr 0) - y intr 0)%R...\nunfold Rminus in |- *...\nrepeat rewrite Ropp_plus_distr...\nrewrite Ropp_involutive...\nrewrite <- (Rplus_comm (y (tr evad) 0%R))...\nrepeat rewrite Rplus_assoc...\napply Rplus_eq_compat_l...\nrewrite (Rplus_comm (- y intr 0%R))...\nunfold Rminus in |- *...\nrepeat rewrite Ropp_plus_distr...\nrepeat rewrite Ropp_involutive...\nrewrite <- (Rplus_comm (x (tr evad) 0%R + T * z))...\nrepeat rewrite Rplus_assoc...\nrepeat apply Rplus_eq_compat_l...\nrewrite (Rplus_comm (- x intr 0%R))...\ncut (v V = z)...\nintro...\nrewrite H0...\nunfold dist_euc in |- *...\ngeneralize (tr_cond1 evad (val T)); intro...\ngeneralize (tr_cond2 evad (val T)); intro...\nrewrite H1...\nrewrite H2...\nrewrite hyp_evad...\nrewrite H0...\nreplace\n (x (tr evad) 0 + T * z - T * z * cos (thetat intr 0) -\n  (x (tr evad) 0 + z * T))%R with (- (T * z * cos (thetat intr 0)))%R...\nreplace (y (tr evad) 0 - T * z * sin (thetat intr 0) - y (tr evad) 0)%R with\n (- (T * z * sin (thetat intr 0)))%R...\nrepeat rewrite <- Rsqr_neg...\nrepeat rewrite Rsqr_mult...\nrewrite cos2...\nreplace\n (Rsqr T * Rsqr z * (1 - Rsqr (sin (thetat intr 0))) +\n  Rsqr T * Rsqr z * Rsqr (sin (thetat intr 0)))%R with \n (Rsqr T * Rsqr z)%R...\nrewrite <- Rsqr_mult...\nrewrite sqrt_Rsqr...\napply Rmult_comm...\nleft; apply Rmult_lt_0_compat...\napply Rlt_le_trans with MinT...\napply MinT_is_pos...\napply (cond_1 T)...\nunfold z in |- *; prove_sup...\nunfold Rminus in |- *...\nrewrite Rmult_plus_distr_l...\nrewrite Rmult_1_r...\nring...\nunfold Rminus in |- *...\nrewrite (Rplus_comm (y (tr evad) 0%R))...\nrewrite Rplus_assoc...\nrewrite Rplus_opp_r...\nsymmetry  in |- *; apply Rplus_0_r...\nunfold Rminus in |- *...\nrewrite Ropp_plus_distr...\nrewrite (Rplus_comm (- x (tr evad) 0%R))...\nrepeat rewrite Rplus_assoc...\nrewrite (Rplus_comm (x (tr evad) 0%R))...\nrepeat rewrite Rplus_assoc...\nrewrite Rplus_opp_l; rewrite Rplus_0_r...\nring...\nunfold l, dist_euc in |- *...\nunfold Die in |- *...\nunfold xi, yi in |- *...\nrewrite (Rsqr_neg (x intr 0%R - x (tr evad) T))...\nrewrite (Rsqr_neg (y intr 0%R - y (tr evad) T))...\nunfold Rminus in |- *...\nrepeat rewrite Ropp_plus_distr...\nrepeat rewrite Ropp_involutive...\nrewrite <- (Rplus_comm (x (tr evad) T))...\nrewrite <- (Rplus_comm (y (tr evad) T))...\nrepeat rewrite Rmult_assoc...\nrepeat apply Rmult_eq_compat_l...\nrewrite <- (Rmult_comm (V * T))...\nrepeat rewrite Rmult_assoc...\nrepeat rewrite Rsqr_mult...\nrewrite sin2...\nunfold Rminus in |- *...\nrewrite Rmult_plus_distr_l...\nrewrite Rmult_1_r...\nring...\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/ails_trajectory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2679904786531365}}
{"text": "Require Export Program.Basics. Open Scope program_scope.\nFrom Paco Require Import paconotation_internal paco_internal pacotac_internal.\nFrom Paco Require Export paconotation.\nSet Implicit Arguments.\n\nSection PACO5.\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.\n\n(** ** Predicates of Arity 5\n*)\n\nDefinition paco5(gf : rel5 T0 T1 T2 T3 T4 -> rel5 T0 T1 T2 T3 T4)(r: rel5 T0 T1 T2 T3 T4) : rel5 T0 T1 T2 T3 T4 :=\n  @curry5 T0 T1 T2 T3 T4 (paco (fun R0 => @uncurry5 T0 T1 T2 T3 T4 (gf (@curry5 T0 T1 T2 T3 T4 R0))) (@uncurry5 T0 T1 T2 T3 T4 r)).\n\nDefinition upaco5(gf : rel5 T0 T1 T2 T3 T4 -> rel5 T0 T1 T2 T3 T4)(r: rel5 T0 T1 T2 T3 T4) := paco5 gf r \\5/ r.\nArguments paco5 : clear implicits.\nArguments upaco5 : clear implicits.\n#[local] Hint Unfold upaco5 : core.\n\nDefinition monotone5 (gf: rel5 T0 T1 T2 T3 T4 -> rel5 T0 T1 T2 T3 T4) :=\n  forall x0 x1 x2 x3 x4 r r' (IN: gf r x0 x1 x2 x3 x4) (LE: r <5= r'), gf r' x0 x1 x2 x3 x4.\n\nDefinition _monotone5 (gf: rel5 T0 T1 T2 T3 T4 -> rel5 T0 T1 T2 T3 T4) :=\n  forall r r'(LE: r <5= r'), gf r <5== gf r'.\n\nLemma monotone5_eq (gf: rel5 T0 T1 T2 T3 T4 -> rel5 T0 T1 T2 T3 T4) :\n  monotone5 gf <-> _monotone5 gf.\nProof. unfold monotone5, _monotone5, le5. split; intros; eapply H; eassumption. Qed.\n\nLemma monotone5_map (gf: rel5 T0 T1 T2 T3 T4 -> rel5 T0 T1 T2 T3 T4)\n      (MON: _monotone5 gf) :\n  _monotone (fun R0 => @uncurry5 T0 T1 T2 T3 T4 (gf (@curry5 T0 T1 T2 T3 T4 R0))).\nProof.\n  red; intros. apply uncurry_map5. apply MON; apply curry_map5; assumption.\nQed.\n\nLemma monotone5_compose (gf gf': rel5 T0 T1 T2 T3 T4 -> rel5 T0 T1 T2 T3 T4)\n      (MON1: monotone5 gf)\n      (MON2: monotone5 gf'):\n  monotone5 (compose gf gf').\nProof.\n  red; intros. eapply MON1. apply IN.\n  intros. eapply MON2. apply PR. apply LE.\nQed.\n\nLemma monotone5_union (gf gf': rel5 T0 T1 T2 T3 T4 -> rel5 T0 T1 T2 T3 T4)\n      (MON1: monotone5 gf)\n      (MON2: monotone5 gf'):\n  monotone5 (gf \\6/ gf').\nProof.\n  red; intros. destruct IN.\n  - left. eapply MON1. apply H. apply LE.\n  - right. eapply MON2. apply H. apply LE.\nQed.\n\nLemma _paco5_mon_gen (gf gf': rel5 T0 T1 T2 T3 T4 -> rel5 T0 T1 T2 T3 T4) r r'\n    (LEgf: gf <6= gf')\n    (LEr: r <5= r'):\n  paco5 gf r <5== paco5 gf' r'.\nProof.\n  apply curry_map5. red; intros. eapply paco_mon_gen. apply PR.\n  - intros. apply LEgf, PR0.\n  - intros. apply LEr, PR0.\nQed.\n\nLemma paco5_mon_gen (gf gf': rel5 T0 T1 T2 T3 T4 -> rel5 T0 T1 T2 T3 T4) r r' x0 x1 x2 x3 x4\n    (REL: paco5 gf r x0 x1 x2 x3 x4)\n    (LEgf: gf <6= gf')\n    (LEr: r <5= r'):\n  paco5 gf' r' x0 x1 x2 x3 x4.\nProof.\n  eapply _paco5_mon_gen; [apply LEgf | apply LEr | apply REL].\nQed.\n\nLemma paco5_mon_bot (gf gf': rel5 T0 T1 T2 T3 T4 -> rel5 T0 T1 T2 T3 T4) r' x0 x1 x2 x3 x4\n    (REL: paco5 gf bot5 x0 x1 x2 x3 x4)\n    (LEgf: gf <6= gf'):\n  paco5 gf' r' x0 x1 x2 x3 x4.\nProof.\n  eapply paco5_mon_gen; [apply REL | apply LEgf | intros; contradiction PR].\nQed.\n\nLemma upaco5_mon_gen (gf gf': rel5 T0 T1 T2 T3 T4 -> rel5 T0 T1 T2 T3 T4) r r' x0 x1 x2 x3 x4\n    (REL: upaco5 gf r x0 x1 x2 x3 x4)\n    (LEgf: gf <6= gf')\n    (LEr: r <5= r'):\n  upaco5 gf' r' x0 x1 x2 x3 x4.\nProof.\n  destruct REL.\n  - left. eapply paco5_mon_gen; [apply H | apply LEgf | apply LEr].\n  - right. apply LEr, H.\nQed.\n\nLemma upaco5_mon_bot (gf gf': rel5 T0 T1 T2 T3 T4 -> rel5 T0 T1 T2 T3 T4) r' x0 x1 x2 x3 x4\n    (REL: upaco5 gf bot5 x0 x1 x2 x3 x4)\n    (LEgf: gf <6= gf'):\n  upaco5 gf' r' x0 x1 x2 x3 x4.\nProof.\n  eapply upaco5_mon_gen; [apply REL | apply LEgf | intros; contradiction PR].\nQed.\n\nSection Arg5.\n\nVariable gf : rel5 T0 T1 T2 T3 T4 -> rel5 T0 T1 T2 T3 T4.\nArguments gf : clear implicits.\n\nTheorem _paco5_mon: _monotone5 (paco5 gf).\nProof.\n  red; intros. eapply curry_map5, _paco_mon; apply uncurry_map5; assumption.\nQed.\n\nTheorem _paco5_acc: forall\n  l r (OBG: forall rr (INC: r <5== rr) (CIH: l <5== rr), l <5== paco5 gf rr),\n  l <5== paco5 gf r.\nProof.\n  intros. apply uncurry_adjoint1_5.\n  eapply _paco_acc. intros.\n  apply uncurry_adjoint1_5 in INC. apply uncurry_adjoint1_5 in CIH.\n  apply uncurry_adjoint2_5.\n  eapply le5_trans. eapply (OBG _ INC CIH).\n  apply curry_map5.\n  apply _paco_mon; try apply le1_refl; apply curry_bij1_5.\nQed.\n\nTheorem _paco5_mult_strong: forall r,\n  paco5 gf (upaco5 gf r) <5== paco5 gf r.\nProof.\n  intros. apply curry_map5.\n  eapply le1_trans; [| eapply _paco_mult_strong].\n  apply _paco_mon; intros [] H; apply H.\nQed.\n\nTheorem _paco5_fold: forall r,\n  gf (upaco5 gf r) <5== paco5 gf r.\nProof.\n  intros. apply uncurry_adjoint1_5.\n  eapply le1_trans; [| apply _paco_fold]. apply le1_refl.\nQed.\n\nTheorem _paco5_unfold: forall (MON: _monotone5 gf) r,\n  paco5 gf r <5== gf (upaco5 gf r).\nProof.\n  intros. apply curry_adjoint2_5.\n  eapply _paco_unfold; apply monotone5_map; assumption.\nQed.\n\nTheorem paco5_acc: forall\n  l r (OBG: forall rr (INC: forall _x_0 _x_1 _x_2 _x_3 _x_4 (PR: r _x_0 _x_1 _x_2 _x_3 _x_4 : Prop), rr _x_0 _x_1 _x_2 _x_3 _x_4 : Prop) (CIH: forall _x_0 _x_1 _x_2 _x_3 _x_4 (PR: l _x_0 _x_1 _x_2 _x_3 _x_4 : Prop), rr _x_0 _x_1 _x_2 _x_3 _x_4 : Prop), forall _x_0 _x_1 _x_2 _x_3 _x_4 (PR: l _x_0 _x_1 _x_2 _x_3 _x_4 : Prop), paco5 gf rr _x_0 _x_1 _x_2 _x_3 _x_4 : Prop),\n  l <5= paco5 gf r.\nProof.\n  apply _paco5_acc.\nQed.\n\nTheorem paco5_mon: monotone5 (paco5 gf).\nProof.\n  apply monotone5_eq.\n  apply _paco5_mon.\nQed.\n\nTheorem upaco5_mon: monotone5 (upaco5 gf).\nProof.\n  red; intros.\n  destruct IN.\n  - left. eapply paco5_mon. apply H. apply LE.\n  - right. apply LE, H.\nQed.\n\nTheorem paco5_mult_strong: forall r,\n  paco5 gf (upaco5 gf r) <5= paco5 gf r.\nProof.\n  apply _paco5_mult_strong.\nQed.\n\nCorollary paco5_mult: forall r,\n  paco5 gf (paco5 gf r) <5= paco5 gf r.\nProof. intros; eapply paco5_mult_strong, paco5_mon; [apply PR|..]; intros; left; assumption. Qed.\n\nTheorem paco5_fold: forall r,\n  gf (upaco5 gf r) <5= paco5 gf r.\nProof.\n  apply _paco5_fold.\nQed.\n\nTheorem paco5_unfold: forall (MON: monotone5 gf) r,\n  paco5 gf r <5= gf (upaco5 gf r).\nProof.\n  intro. eapply _paco5_unfold; apply monotone5_eq; assumption.\nQed.\n\nEnd Arg5.\n\nArguments paco5_acc : clear implicits.\nArguments paco5_mon : clear implicits.\nArguments upaco5_mon : clear implicits.\nArguments paco5_mult_strong : clear implicits.\nArguments paco5_mult : clear implicits.\nArguments paco5_fold : clear implicits.\nArguments paco5_unfold : clear implicits.\n\nGlobal Instance paco5_inst  (gf : rel5 T0 T1 T2 T3 T4->_) r x0 x1 x2 x3 x4 : paco_class (paco5 gf r x0 x1 x2 x3 x4) :=\n{ pacoacc    := paco5_acc gf;\n  pacomult   := paco5_mult gf;\n  pacofold   := paco5_fold gf;\n  pacounfold := paco5_unfold gf }.\n\nEnd PACO5.\n\nGlobal Opaque paco5.\n\n#[export] Hint Unfold upaco5 : core.\n#[export] Hint Resolve paco5_fold : core.\n#[export] Hint Unfold monotone5 : core.\n\n", "meta": {"author": "snu-sf", "repo": "paco", "sha": "5c5693f46c8957f36a2349a0d906e911366136de", "save_path": "github-repos/coq/snu-sf-paco", "path": "github-repos/coq/snu-sf-paco/paco-5c5693f46c8957f36a2349a0d906e911366136de/src/paco5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2679904786531365}}
{"text": "(* NOTE: This program is NOT open-source, and is NOT licensed for\n * redistribution.  It is copyright by the authors.  Permission is\n * granted only to the CertiCoq project for the use of this program\n * as a benchmark in measuring CertiCoq performance. *)\n\n(************************************************************************************)\n(**                                                                                  *)\n(**                              The DataCert Library                                *)\n(**                                                                                  *)\n(**                           LRI, CNRS & Université Paris-Sud                       *)\n(**                                                                                  *)\n(**                 Copyright 2016 : Véronique Benzaken & Évelyne Contejean          *)\n(**                                                                                  *)\n(************************************************************************************)\n\nSet Implicit Arguments.\n\n(** printing inS? $\\in_?$ #∈<SUB>?</SUB># *)\n(** printing inS $\\in$ #∈# *)\n(** printing subS? $\\subseteq_?$ #⊆<SUB>?</SUB># *)\n(** printing subS $\\subseteq$ #⊆# *)\n(** printing unionS $\\cup$ #⋃# *)\n(** printing interS $\\cap$ #⋂# *)\n(** printing inI $\\in_I$ #∈<SUB><I>I</I></SUB># *)\n(** printing theta $\\theta$ #θ# *)\n(** printing nu1 $\\nu_1$ #ν<SUB><I>1</I></SUB># *)\n(** printing nu $\\nu$ #ν# *)\n(** printing mu $\\mu$ #μ# *)\n(** printing sigma $\\sigma$ #σ# *)\n(** printing -> #⟶# *)\n(** printing <-> #⟷# *)\n(** printing => #⟹# *)\n(** printing (emptysetS) $\\emptyset$ #Ø# *)\n(** printing emptysetS $\\emptyset$ #Ø# *)\n(** printing {{ $\\{$ #{# *)\n(** printing }} $\\}$ #}# *)\n\nRequire Import Relations SetoidList List String Ascii Bool ZArith NArith.\n\nRequire Import FlatData ListFacts OrderedSet FiniteSet Tree Formula Sql.\n\n\nSection Try.\nImport Tuple Expression.\nRequire Import Values Relnames SortedAttributes SortedTuples. \n\n(** Defining functions and aggregates, and giving their interpretation *)\n\nInductive symbol : Type := \n  | Symbol : string -> symbol\n  | CstVal : value -> symbol.\n\nInductive predicate : Type := Predicate : string -> predicate.\n\nDefinition OP : Oset.Rcd predicate.\nsplit with (fun x y => match x, y with Predicate s1, Predicate s2 => string_compare s1 s2 end).\n- intros [s1] [s2]; generalize (Oset.eq_bool_ok Ostring s1 s2); simpl.\n  case (string_compare s1 s2).\n  + apply f_equal.\n  + intros H1 H2; apply H1; injection H2; exact (fun h => h).\n  + intros H1 H2; apply H1; injection H2; exact (fun h => h).\n- intros [s1] [s2] [s3]; apply (Oset.compare_lt_trans Ostring s1 s2 s3).\n- intros [s1] [s2]; apply (Oset.compare_lt_gt Ostring s1 s2).\nDefined.\n\nDefinition symbol_compare (s1 s2 : symbol) := \n  match s1, s2 with\n    | Symbol s1, Symbol s2 => string_compare s1 s2\n    | Symbol _, CstVal _ => Lt\n    | CstVal _, Symbol _ => Gt\n    | CstVal v1, CstVal v2 => value_compare v1 v2\n  end.\n\nDefinition OSymbol : Oset.Rcd symbol.\nsplit with symbol_compare.\n- intros [s1 | s1] [s2 | s2]; simpl; try discriminate.\n  + generalize (Oset.eq_bool_ok Ostring s1 s2); simpl.\n    case (string_compare s1 s2).\n    * apply f_equal.\n    * intros H1 H2; apply H1; injection H2; exact (fun h => h).\n    * intros H1 H2; apply H1; injection H2; exact (fun h => h).\n  + generalize (Oset.eq_bool_ok OVal s1 s2); simpl.\n    case (value_compare s1 s2).\n    * apply f_equal.\n    * intros H1 H2; apply H1; injection H2; exact (fun h => h).\n    * intros H1 H2; apply H1; injection H2; exact (fun h => h).\n- intros [s1 | s1] [s2 | s2] [s3 | s3]; simpl;\n  try (apply (Oset.compare_lt_trans Ostring) || \n             apply (Oset.compare_lt_trans OVal) || \n             trivial || discriminate).\n- intros [s1 | s1] [s2 | s2]; simpl;\n  try (apply (Oset.compare_lt_gt Ostring) || \n             apply (Oset.compare_lt_gt OVal) || \n             trivial || discriminate).\nDefined.\n\nDefinition interp_symbol f := \n  match f with\n    | Symbol \"plus\" => \n      fun l => \n        match l with \n          | Value_N a1 :: Value_N a2 :: nil => Value_N (Nplus a1 a2) \n          | _ => Value_N 0 end\n    | Symbol \"mult\" => \n      fun l => \n        match l with \n          | Value_N a1 :: Value_N a2 :: nil => Value_N (Nmult a1 a2) \n          | _ => Value_N 0 end\n    | Symbol \"minus\" => \n      fun l => \n        match l with \n          | Value_N a1 :: Value_N a2 :: nil => Value_N (Nminus a1 a2) \n          | _ => Value_N 0 end\n    | Symbol \"opp\" => \n      fun l => \n        match l with \n          | Value_N a1 :: nil => Value_N (Nopp a1) \n          | _ => Value_N 0 end\n    | CstVal v => \n      fun l => \n        match l with \n          | nil => v\n          | _ => default_value (type_of_value v)\n        end\n    | _ => fun _ => Value_N 0 \n  end.\n\nDefinition interp_predicate p := \n  match p with\n    | Predicate \"<\" =>\n      fun l =>\n        match l with\n          | Value_N a1 :: Value_N a2 :: nil => \n            match Ncompare a1 a2 with Lt => true | _ => false end\n          | _ => false\n        end\n    | Predicate \"<=\" =>\n      fun l =>\n        match l with\n          | Value_N a1 :: Value_N a2 :: nil => \n            match Ncompare a1 a2 with Gt => false | _ => true end\n          | _ => false\n        end\n    | Predicate \">\" =>\n      fun l =>\n        match l with\n          | Value_N a1 :: Value_N a2 :: nil => \n            match Ncompare a1 a2 with Gt => true | _ => false end\n          | _ => false\n        end\n    | Predicate \">=\" =>\n      fun l =>\n        match l with\n          | Value_N a1 :: Value_N a2 :: nil => \n            match Ncompare a1 a2 with Lt => false | _ => true end\n          | _ => false\n        end\n    | Predicate \"=\" =>\n      fun l =>\n        match l with\n          | Value_N a1 :: Value_N a2 :: nil => \n            match Ncompare a1 a2 with Eq => true | _ => false end\n          | Value_string s1 :: Value_string s2 :: nil =>\n            match string_compare s1 s2 with Eq => true | _ => false end\n          | _ => false\n        end\n   | _ => fun _ => false\n  end.\n\nInductive aggregate : Type := \n  | Aggregate : string -> aggregate.\n\nDefinition OAgg : Oset.Rcd aggregate.\nsplit with (fun x y => match x, y with Aggregate s1, Aggregate s2 => string_compare s1 s2 end).\n- intros [s1] [s2]; generalize (Oset.eq_bool_ok Ostring s1 s2); simpl.\n  case (string_compare s1 s2).\n  + apply f_equal.\n  + intros H1 H2; apply H1; injection H2; exact (fun h => h).\n  + intros H1 H2; apply H1; injection H2; exact (fun h => h).\n- intros [s1] [s2] [s3]; apply (Oset.compare_lt_trans Ostring s1 s2 s3).\n- intros [s1] [s2]; apply (Oset.compare_lt_gt Ostring s1 s2).\nDefined.\n\nDefinition interp_aggregate a :=\n  match a with\n    | Aggregate \"count\" => \n      fun (l : list (Tuple.value T)) => Value_N (N_of_nat (List.length l))\n    | Aggregate \"sum\" =>\n      fun (l : list (Tuple.value T)) =>\n           Value_N (fold_left (fun acc x => match x with Value_N x => (acc + x)%N | _ => acc end) l 0%N)\n    | Aggregate \"avg\" =>\n      fun (l : list (Tuple.value T)) =>\n           Value_N (let sum := fold_left (fun acc x => match x with Value_N x => (acc + x)%N | _ => acc end) l 0%N in Ndiv sum (N_of_nat (List.length l)))\n    | Aggregate _ => fun _ => Value_N 0\n  end.\n\n(** Building a database instance, and updating it  *)\nDefinition mk_tuple la f := mk_tuple T (mk_set FAN la) f.\n\nDefinition show_tuple t :=\n  List.map\n    (fun a => (a, dot T t a))\n    (Fset.elements _ (support _ t)).\n\nDefinition show_tuples x :=\n  List.map show_tuple (Feset.elements (FTuple T) x).\n\nRecord db_state : Type :=\n  mk_state\n    {\n      _relnames : list relname;\n      _basesort : relname -> Fset.set FAN;\n      _instance : relname -> Feset.set (FTuple T)\n    }.\n\nDefinition show_state (db : db_state) :=\n  (_relnames db,\n   List.map (fun r => (r, Fset.elements _ (_basesort db r))) (_relnames db),\n   List.map (fun r => (r, show_tuples (_instance db r))) (_relnames db)).\n\nDefinition init_db :=\n  mk_state\n    nil\n    (fun _ => Fset.empty FAN)\n    (fun _ => Feset.empty (FTuple T)).\n\nDefinition create_table \n           (* old state *) db \n           (* new table name *) t \n           (* new table sort *) st \n            :=\n  mk_state\n    (t :: _relnames db)\n    (fun x =>\n       match Oset.compare ORN x t with\n         | Eq => mk_set FAN st\n         |_ => _basesort db x\n       end)\n    (_instance db).\n\nDefinition insert_tuple_into  \n           (* old state *) db \n           (* new tuple *) tpl \n           (* table *) tbl\n            :=\n  if Fset.equal FAN (support T tpl) (_basesort db tbl)\n  then \n    mk_state \n      (_relnames db)\n      (_basesort db)\n      (fun x =>\n         match Oset.compare ORN x tbl with\n           | Eq => Feset.add (FTuple T) tpl (_instance db tbl)\n           |_ => _instance db x\n         end)\n   else (* no NULL values by default *) db.\n\nFixpoint insert_tuples_into\n           (* old state *) db \n           (* new tuple list *) ltpl \n           (* table *) tbl :=\n  match ltpl with\n    | nil => db\n    | t :: l => insert_tuple_into (insert_tuples_into db l tbl) t tbl\n  end.\n\nDefinition MyDBS db := DatabaseSchema.mk_R (Tuple.A T) ORN (_basesort db).\n\n(** Evaluation of SQL-COQ queries *)\n\nDefinition eval_sql_query_in_state (db : db_state) q := \n  eval_sql_query \n    (DBS := MyDBS db) interp_predicate interp_symbol interp_aggregate (_instance db) q.\n\n(** Some notations, to ease the readability *)\nNotation aa := (Attr_N 0 \"a\").\nNotation bb := (Attr_N 0 \"b\").\nNotation cc := (Attr_N 0 \"c\").\nNotation ac := (Attr_N 0 \"ac\").\nNotation cb := (Attr_N 0 \"cb\").\nNotation b_plus_c := (Attr_N 0 \"b_plus_c\").\nNotation a := (Attr_N 0 \"a\").\nNotation b := (Attr_N 0 \"b\").\nNotation c := (Attr_N 0 \"c\").\nNotation a1 := (Attr_N 0 \"a1\").\nNotation b1 := (Attr_N 0 \"b1\").\nNotation c1 := (Attr_N 0 \"c1\").\nNotation a0 := (Attr_N 0 \"a0\").\nNotation b0 := (Attr_N 0 \"b0\").\nNotation c0 := (Attr_N 0 \"c0\").\nNotation a2 := (Attr_N 0 \"a2\").\nNotation b2 := (Attr_N 0 \"b2\").\nNotation c2 := (Attr_N 0 \"c2\").\nNotation a3 := (Attr_N 0 \"a3\").\nNotation b3 := (Attr_N 0 \"b3\").\nNotation c3 := (Attr_N 0 \"c3\").\nNotation a4 := (Attr_N 0 \"a4\").\nNotation b4 := (Attr_N 0 \"b4\").\nNotation c4 := (Attr_N 0 \"c4\").\n\nNotation table0 :=  (Rel \"table0\").\nNotation t0 :=  (Rel \"t0\").\nNotation table1 :=  (Rel \"table1\").\nNotation t1 :=  (Rel \"t1\").\nNotation table2 :=  (Rel \"table2\").\nNotation t2 :=  (Rel \"t2\").\nNotation table3 :=  (Rel \"table3\").\nNotation t3 :=  (Rel \"t3\").\n\n(** Again, for the constructs of the SQL framework *)\nDefinition _Select_Star := (@Select_Star symbol aggregate T).\n\nDefinition _Select_List := (@Select_List symbol aggregate T).\n\nDefinition _Select_As := (@Select_As symbol aggregate T).\n\nDefinition _Att_Ren_Star := (@Att_Ren_Star T).\n\nDefinition _Att_Ren_List := (@Att_Ren_List T).\n\nDefinition _Att_As := (@Att_As T).\n\nDefinition _Sql_Table db := (@Sql_Table predicate symbol aggregate T (MyDBS db)).\n\nDefinition _Sql_Select db := @Sql_Select predicate symbol aggregate T (MyDBS db).\n\nDefinition _From_Item db := (@From_Item predicate symbol aggregate T (MyDBS db)).\n\nDefinition _Sql_Atom db := (@Sql_Atom predicate symbol aggregate T (MyDBS db)).\n\nDefinition _Sql_True db := (@Sql_True predicate symbol aggregate T (MyDBS db)).\n\nDefinition _Sql_Not db := (@Sql_Not predicate symbol aggregate T (MyDBS db)).\n\nDefinition _Sql_Conj db := (@Sql_Conj predicate symbol aggregate T (MyDBS db)).\n\nDefinition _Group_Fine := (@Group_Fine symbol T).\n\nDefinition __Sql_Dot a := (@F_Dot T symbol a).\n\nDefinition _Sql_Dot a := (@A_Expr T _ aggregate (@F_Dot T symbol a)).\n\nDefinition _Sql_Pred db := (@Sql_Pred predicate symbol aggregate T (MyDBS db)).\n\nDefinition _Sql_In db := (@Sql_In predicate symbol aggregate T (MyDBS db)).\n\nDefinition _Sql_Quant db := (@Sql_Quant predicate symbol aggregate T (MyDBS db)).\n\nDefinition _A_Expr := (@A_Expr T symbol aggregate).\n\nDefinition _F_Expr := (@F_Expr T symbol).\n\nDefinition _CstN n := (F_Constant T symbol (Value_N n)). \n\nDefinition CstN n := (_A_Expr (F_Constant T symbol (Value_N n))). \n\nDefinition t123 := \n  mk_tuple \n    (aa :: bb :: cc :: nil)\n    (fun x => match x with \n                | aa => Value_N 1 \n                | bb => Value_N 2 \n                | cc => Value_N 3 \n                | _ => Value_N 0 end).\n\nDefinition t456 := mk_tuple \n        (aa :: bb :: cc :: nil)\n        (fun x => match x with \n                    | aa => Value_N 4 \n                    | bb => Value_N 5 \n                    | cc => Value_N 6 \n                    | _ => Value_N 0 end).\n\nDefinition t778 := mk_tuple \n        (aa :: bb :: cc :: nil)\n        (fun x => match x with \n                    | aa => Value_N 7\n                    | bb => Value_N 7 \n                    | cc => Value_N 8 \n                    | _ => Value_N 0 end).\n\nDefinition t779 := mk_tuple \n        (aa :: bb :: cc :: nil)\n        (fun x => match x with \n                    | aa => Value_N 7\n                    | bb => Value_N 7 \n                    | cc => Value_N 9 \n                    | _ => Value_N 0 end).\n\nDefinition db0 := init_db.\n\n(** \ncreate table table1(a integer, b integer, c integer);\n*)\n\nDefinition db1 := \n  create_table \n    (create_table db0 table0 (aa :: bb :: cc :: nil))\n    table1 (aa :: bb :: cc :: nil).\n\n(**\ninsert into table1 values (1,2,3);\ninsert into table1 values (4,5,6);\n*)\nDefinition db2 := insert_tuples_into db1 (t123 :: t456 :: nil) table1.\n\nDefinition db3 := insert_tuples_into db2 (t778 :: t779 :: nil) table1.\n\n(**\ninsert into table1 values (4,5);\n*)\n\nDefinition db4 := \n  insert_tuple_into \n    db3 \n    (mk_tuple \n        (aa :: bb :: nil)\n        (fun x => match x with \n                    | aa => Value_N 4\n                    | bb => Value_N 5 \n                    | _ => Value_N 0 end))\n    table1.\n\n(** select t5.a2 as a3 from table5 as t5(a2) *)\n\nDefinition eval_sql0 :=\n  let a1 := Attr_N 0 \"a1\" in\n  let a2 := Attr_N 0 \"a2\" in\n  let a3 := Attr_N 0 \"a3\" in\n  let table5 := Rel \"table5\" in\n  let tpl n := \n      mk_tuple \n        (a1 :: nil) \n        (fun x => match x with a1 => Value_N n | _ => Value_N 0 end) in\n  let db1 := \n      insert_tuples_into \n        (create_table db0 table5 (a1 :: nil))\n        (tpl 1 :: tpl 2 :: tpl 3 :: nil)\n        table5 in\n  let sql0 db :=\n  _Sql_Select \n        (* select *) (_Select_List ((_Select_As (_Sql_Dot a2) a3) :: nil))\n        (* from *) ((_From_Item \n                       (_Sql_Table table5) \n                       (Att_Ren_List ((Att_As T a1 a2) :: nil))) :: nil)\n        (* where *) (_Sql_Atom (_Sql_True db))\n        (* groupby *) (_Group_Fine)\n        (* having *) (_Sql_Atom (_Sql_True db)) in\n\n  eval_sql_query_in_state (sql0 db1).\n\nEval compute in (show_tuples eval_sql0).\n\n(** select * from table1; *)\n\nDefinition sql1 db :=\n  _Sql_Select \n    (* select *) _Select_Star \n    (* from *) ((_From_Item (_Sql_Table table1) _Att_Ren_Star) :: nil)\n    (* where *) (_Sql_Atom (_Sql_True db))\n    (* groupby *) _Group_Fine\n    (* having *) (_Sql_Atom (_Sql_True db)).\n\nDefinition eval_sql1 := eval_sql_query_in_state (sql1 db2).\n\nEval compute in (show_tuples eval_sql1).\n\n(** select * from table1 where aa = bb *)\nDefinition sql2 db :=\n  _Sql_Select \n    (* select *) _Select_Star \n    (* from *) ((_From_Item (_Sql_Table table1) _Att_Ren_Star) :: nil)\n    (* where *) (_Sql_Atom (_Sql_Pred db (Predicate \"=\") (_Sql_Dot aa :: _Sql_Dot bb :: nil)))\n    (* groupby *) _Group_Fine\n    (* having *) (_Sql_Atom (_Sql_True db)).\n\nDefinition eval_sql2 := eval_sql_query_in_state (sql2 db2).\nEval compute in (show_tuples eval_sql2).\n\n(** Evalution of the same query in different states (that is instances) of the database *)\nDefinition eval_sql2' := eval_sql_query_in_state (sql2 db3).\nEval compute in (show_tuples eval_sql2').\n\nDefinition eval_sql1' := eval_sql_query_in_state (sql1 db3).\nEval compute in (show_tuples eval_sql1').\n\nDefinition eval_sql1'' := eval_sql_query_in_state (sql1 db4).\nEval compute in (show_tuples eval_sql1'').\n\n(** (4,5) has not been inserted in db4, as specified by insert_tuple.\n We COULD have made another choice, and null values in that case would correspond \n to an attribute which occurs in the sort of the query, but not in the support\n of the tuple.*)\n\n(** SELECT a, b FROM table1; *)\n\nDefinition sql5 db :=\n  _Sql_Select \n    (* select *) (_Select_List \n                    ((_Select_As (_Sql_Dot aa) aa) :: \n                     (_Select_As (_Sql_Dot bb) bb ) :: nil))\n    (* from *) ((_From_Item (_Sql_Table table1) _Att_Ren_Star) :: nil)\n    (* where *) (_Sql_Atom (_Sql_True db))\n    (* groupby *) _Group_Fine\n    (* having *) (_Sql_Atom (_Sql_True db)).\n\nDefinition eval_sql5 := eval_sql_query_in_state (sql5 db4).\nEval vm_compute in (show_tuples eval_sql5).\n\n(** SELECT a, b + c FROM table1; actully, we use\n   SELECT a, b + c AS bplusc FROM table1; *)\nDefinition sql6 db :=\n  _Sql_Select \n    (* select *) (_Select_List \n                    ((_Select_As (_Sql_Dot aa) aa) :: \n                     (_Select_As \n                        (_A_Expr ((_F_Expr (Symbol \"plus\")) ((__Sql_Dot bb) :: (__Sql_Dot cc) :: nil)))\n                          b_plus_c ) :: nil))\n    (* from *) ((_From_Item (_Sql_Table table1) _Att_Ren_Star) :: nil)\n    (* where *) (_Sql_Atom (_Sql_True db))\n    (* groupby *) _Group_Fine\n    (* having *) (_Sql_Atom (_Sql_True db)).\n\nDefinition eval_sql6 := eval_sql_query_in_state (sql6 db4).\nEval compute in (show_tuples eval_sql6).\n\n(** explicit renaming of attributes\n      select * from table1 as t1(a1 , b1 , c1 ); *)\n\nDefinition sql7 db :=\n  _Sql_Select \n    (* select *) _Select_Star\n    (* from *) ((_From_Item \n                   (_Sql_Table table1) \n                   (_Att_Ren_List \n                      (_Att_As aa a1 :: \n                       _Att_As bb b1 :: \n                       _Att_As cc c1 :: nil))) :: nil)\n    (* where *) (_Sql_Atom (_Sql_True db))\n    (* groupby *) _Group_Fine\n    (* having *) (_Sql_Atom (_Sql_True db)).\n\nDefinition eval_sql7 := eval_sql_query_in_state (sql7 db4).\nEval vm_compute in (show_tuples eval_sql7).\n\n(** select * from table1 as t1 where t1.a < 4*)\nDefinition sql8 db :=\n  _Sql_Select \n    (* select *) _Select_Star\n    (* from *) ((_From_Item (_Sql_Table table1) _Att_Ren_Star) :: nil)\n    (* where *) (_Sql_Atom \n                   (_Sql_Pred db (Predicate \"<\") \n                              (_Sql_Dot aa :: CstN 4 :: nil)))\n    (* groupby *) _Group_Fine\n    (* having *) (_Sql_Atom (_Sql_True db)).\n\nDefinition eval_sql8 := eval_sql_query_in_state (sql8 db4).\nEval vm_compute in (show_tuples eval_sql8).\n\n(** select * from table1 as t1 where t1.a > 4*)\n\nDefinition sql9 db :=\n  _Sql_Select \n    (* select *) _Select_Star\n    (* from *) ((_From_Item (_Sql_Table table1) _Att_Ren_Star) :: nil)\n    (* where *) (_Sql_Atom \n                   (_Sql_Pred db (Predicate \">\") \n                              (_Sql_Dot aa :: CstN 4 :: nil)))\n    (* groupby *) _Group_Fine\n    (* having *) (_Sql_Atom (_Sql_True db)).\n\nDefinition eval_sql9 := eval_sql_query_in_state (sql9 db4).\nEval vm_compute in (show_tuples eval_sql9).\n\n(** select * from table1 as t1 where t1.a = 4*)\nDefinition sql10 db :=\n  _Sql_Select \n    (* select *) _Select_Star\n    (* from *) ((_From_Item (_Sql_Table table1) _Att_Ren_Star) :: nil)\n    (* where *) (_Sql_Atom \n                   (_Sql_Pred db (Predicate \"=\") \n                              (_Sql_Dot aa :: CstN 4 :: nil)))\n    (* groupby *) _Group_Fine\n    (* having *) (_Sql_Atom (_Sql_True db)).\n\nDefinition eval_sql10 := eval_sql_query_in_state (sql10 db4).\nEval vm_compute in (show_tuples eval_sql10).\n\n(** select * from table1 as t1 where t1.a <> 4*)\n\nDefinition sql11 db :=\n  _Sql_Select \n    (* select *) _Select_Star\n    (* from *) ((_From_Item (_Sql_Table table1) _Att_Ren_Star) :: nil)\n    (* where *) (_Sql_Not \n                   (_Sql_Atom \n                   (_Sql_Pred db (Predicate \"=\") \n                              (_Sql_Dot aa :: CstN 4 :: nil))))\n    (* groupby *) _Group_Fine\n    (* having *) (_Sql_Atom (_Sql_True db)).\n\nDefinition eval_sql11 := eval_sql_query_in_state (sql11 db4).\nEval vm_compute in (show_tuples eval_sql11).\n\n\n(** select * from table1 as t1 where t1.a < 4 or t1.a >= 7*)\nDefinition sql12 db :=\n  _Sql_Select \n    (* select *) _Select_Star\n    (* from *) ((_From_Item (_Sql_Table table1) _Att_Ren_Star) :: nil)\n    (* where *) (_Sql_Conj Or_F \n                   (_Sql_Atom \n                   (_Sql_Pred db (Predicate \"<\") \n                              (_Sql_Dot aa :: CstN 4 :: nil)))\n                   (_Sql_Atom \n                   (_Sql_Pred db (Predicate \">=\") \n                              (_Sql_Dot aa :: CstN 7 :: nil))))\n    (* groupby *) _Group_Fine\n    (* having *) (_Sql_Atom (_Sql_True db)).\n\nDefinition eval_sql12 := eval_sql_query_in_state (sql12 db4).\nEval vm_compute in (show_tuples eval_sql12).\n\n(** select * from table1 where 2 * a < 12 *)\nDefinition sql13 db :=\n  _Sql_Select \n    (* select *) _Select_Star\n    (* from *) ((_From_Item (_Sql_Table table1) _Att_Ren_Star) :: nil)\n    (* where *) (_Sql_Atom \n                   (_Sql_Pred db (Predicate \"<\") \n                              (_A_Expr (((_F_Expr (Symbol \"mult\")) \n                                     (_CstN 2 :: __Sql_Dot aa :: nil))) :: \n                              (CstN 12) :: nil)))\n    (* groupby *) _Group_Fine\n    (* having *) (_Sql_Atom (_Sql_True db)).\n\nDefinition eval_sql13 := eval_sql_query_in_state (sql13 db4).\n\nEval vm_compute in (show_tuples eval_sql13).\n\nNotation a_plus_b := \n  (_A_Expr ((_F_Expr (Symbol \"plus\")) ((__Sql_Dot a) :: (__Sql_Dot b) :: nil))). \n\nNotation a0_plus_c1 :=\n  (_A_Expr ((_F_Expr (Symbol \"plus\")) ((__Sql_Dot a0) :: (__Sql_Dot c1) :: nil))).\n\nNotation rho0 := (Att_Ren_List ((Att_As T a a0) :: (Att_As T b b0) ::  (Att_As T c c0) ::  nil)).\nNotation rho1 := (Att_Ren_List ((Att_As T a a1) :: (Att_As T b b1) ::  (Att_As T c c1) ::  nil)).\n\n(** select * from from tbl1[[*]] where (a+b) >= all (select (a0 + c1) as a0_plus_c1 from tbl0[[rho0]], tbl1[[rho1]]) *)\nDefinition sql17 db :=\n  _Sql_Select\n    (* select *) _Select_Star\n    (* from *) ((_From_Item (_Sql_Table table1) _Att_Ren_Star) :: nil)\n    (* where *) (_Sql_Atom \n                   (_Sql_Quant \n                      Forall_F (db := db)\n                      (Predicate \">=\") (a_plus_b :: nil)\n                      (_Sql_Select \n                         (_Select_List (_Select_As a0_plus_c1 (Attr_N 0 \"a0_plus_c1\") :: nil))\n                         (_From_Item (_Sql_Table table0) rho0 :: \n                                     _From_Item  (_Sql_Table table1) rho1 :: nil)\n                         (_Sql_Atom (_Sql_True db))\n                         _Group_Fine  \n                         (_Sql_Atom (_Sql_True db)))))\n    (* groupby *) _Group_Fine\n    (* having *) (_Sql_Atom (_Sql_True db)).\n\n\nEnd Try.\n\n", "meta": {"author": "CertiCoq", "repo": "certicoq", "sha": "2405e1012e9c0a58e49002d9779bb65527d6c323", "save_path": "github-repos/coq/CertiCoq-certicoq", "path": "github-repos/coq/CertiCoq-certicoq/certicoq-2405e1012e9c0a58e49002d9779bb65527d6c323/benchmarks/lib/SqlQueries3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2679904786531365}}
{"text": "Require Import compcert.lib.Axioms.\nRequire Import compcert.lib.Maps.\n(* Require Export compcert.lib.Coqlib. *)\n\nRequire Import concurrency.sepcomp. Import SepComp.\n\nRequire Import concurrency.pos.\nRequire Import concurrency.scheduler.\nRequire Import concurrency.TheSchedule.\nRequire Import concurrency.konig.\nRequire Import concurrency.addressFiniteMap. (*The finite maps*)\nRequire Import concurrency.pos.\nRequire Import concurrency.lksize.\nRequire Import concurrency.permjoin_def.\nRequire Import Coq.Program.Program.\nFrom mathcomp.ssreflect Require Import ssreflect ssrbool ssrnat ssrfun eqtype seq fintype finfun.\nSet Implicit Arguments.\n\nRequire Import concurrency.ssromega. (*omega in ssrnat *)\n\nRequire Import Coq.ZArith.ZArith.\n\nRequire Import concurrency.permissions.\nRequire Import concurrency.threadPool.\n\nRequire Import compcert.common.Memory. (*for Mem.perm_order'' *)\nSet Bullet Behavior \"Strict Subproofs\".\n\n\nDefinition map_leq {A B} (m1: PTree.t A)(m2: PTree.t B): Prop :=\n  forall p, m1 ! p -> m2 ! p.\n\nLemma map_leq_apply:\n  forall {A B} (m1: PTree.t A)(m2: PTree.t B) p f1,\n    map_leq m1 m2 ->\n    m1 ! p = Some f1 -> exists f2, m2 ! p = Some f2.\nProof.\n  move => A B m1 m2 p f1.\n  rewrite /map_leq => /(_ p) Mle AA.\n  rewrite AA in Mle. specialize (Mle ltac:(auto)).\n  destruct (m2 ! p) as [f2|]; try solve[inversion Mle].\n  exists f2; auto.\nQed.\n\nLemma treemap_sub_map: forall {A B} (f: positive -> B -> A) m2,\n    map_leq (PTree.map f m2) m2.\nProof.\n  move => A B f m2 p.\n  rewrite PTree.gmap.\n  destruct (m2 ! p) eqn:m2p; auto; intros HH; inversion HH.\nQed.\n\nDefinition map_empty_def {A} (m1: PMap.t (Z -> option A)):=\n  m1.1 = fun _ => None.\n\nDefinition fun_leq' {A B} (f1: Z -> option A) (f2: Z -> option B): Prop :=\n  forall p, f1 p -> f2 p.\n\nDefinition fun_leq {A B} (o1: option (Z -> option A)) (o2: option (Z -> option B)): Prop :=\n  match o1, o2 with\n  | Some f1, Some f2 => fun_leq' f1 f2\n  | None, None => True\n  | _, _ => False\n  end.\n\nDefinition option_eq {A B} (a:option A) (b: option B): Prop :=\n  match a, b with\n  | Some _ , Some _ => True\n  | None, None => True\n  | _, _ => False\n  end.\n\nDefinition bounded_nat_func_aux {A} (f: nat -> option A) hi: Prop :=\n  (forall p, (p >= hi )%nat -> f p = None).\n\nDefinition bounded_nat_func' {A} (f: nat -> option A) hi: Prop :=\n  (forall p, (p > hi )%nat -> f p = None).\n\nDefinition bounded_func' {A} (f: Z -> option A) hi lo: Prop :=\n  (forall p, (p > hi )%Z -> f p = None) /\\\n  (forall p, (p < lo)%Z -> f p = None).\n\nDefinition bounded_func_op {A} (f: option (Z -> option A)) hi lo: Prop :=\n  match f with\n  | Some f' => bounded_func' f' hi lo\n  | None => True\n  end.\n\nDefinition bounded_func {A} (f: Z -> option A): Prop :=\n  exists hi lo,\n  bounded_func' f hi lo.\n\nDefinition bounded_map {A} (m: PTree.t (Z -> option A)):=\n  forall p f, m ! p = Some f -> bounded_func f.\n\nFixpoint strong_tree_leq {A B}\n         (t1: PTree.t A) (t2: PTree.t B)\n         (leq: option A -> option B -> Prop):=\n  match t1, t2 with\n  | PTree.Leaf, PTree.Leaf => True\n  | PTree.Node l1 o1 r1, PTree.Node l2 o2 r2 =>\n    leq o1 o2 /\\\n    strong_tree_leq l1 l2 leq /\\\n    strong_tree_leq r1 r2 leq\n  | _, _ => False\n  end.\n\nDefinition same_shape {A B} (m1: PTree.t (Z -> option A))(m2: PTree.t (Z -> option B)):=\n  strong_tree_leq m1 m2 option_eq.\n\nDefinition sub_map' {A B} (m1: PTree.t (Z -> option A))(m2: PTree.t (Z -> option B)):=\n  forall p f1, m1 ! p = Some f1 ->\n          exists f2, m2 ! p = Some f2 /\\ fun_leq' f1 f2.\n\nDefinition sub_map {A B} (m1: PTree.t (Z -> option A))(m2: PTree.t (Z -> option B)):=\n  strong_tree_leq m1 m2 fun_leq.\n\nLemma sub_map_and_shape:\n  forall { A B} m1 m2,\n  @same_shape A B m1 m2 ->\n  sub_map' m1 m2 ->\n  sub_map m1 m2.\nProof.\n  induction m1.\n  - intros.\n    destruct m2; inversion H.\n    auto.\n  - intros.\n    rewrite /sub_map /=.\n    destruct m2; try inversion H.\n    split; [|split].\n    + destruct o as [o|].\n      2: destruct o0; inversion H1; auto.\n      specialize (H0 1%positive o ltac:(auto)).\n      destruct o0; try solve [inversion H1].\n      destruct H0 as [f [ISo LEQ]].\n      inversion ISo.\n      auto.\n    + destruct H as [AA [BB CC]].\n      eapply IHm1_1; eauto.\n      move => b f HH.\n      move: H0 => /(_  (b~0)%positive f HH) //.\n    + destruct H as [AA [BB CC]].\n      eapply IHm1_2; eauto.\n      move => b f HH.\n      move: H0 => /(_  (b~1)%positive f HH) //.\nQed.\n\nDefinition nat_to_perm (i:nat) :=\n  (match i with\n  | 0 => Some None\n  | 1 => Some (Some Nonempty)\n  | 2 => Some (Some Readable)\n  | 3 => Some (Some Writable)\n  | 4 => Some (Some Freeable)\n  | _ => None\n  end)%nat.\n\nDefinition perm_to_nat (p: option (option permission)) :=\n  match p with\n  | Some (None) => 0\n  | Some (Some Nonempty) => 1\n  | Some (Some Readable) => 2\n  | Some (Some Writable) => 3\n  | Some (Some Freeable) => 4\n  | None => 5\n  end.\n\nDefinition nat_to_perm_simpl (i:nat) :=\n  (match i with\n  | 0 => None\n  | 1 => Some Nonempty\n  | 2 => Some Readable\n  | 3 => Some Writable\n  | 4 => Some Freeable\n  | _ => None\n  end)%nat.\n\nDefinition perm_to_nat_simpl (p: option permission) :=\n  match p with\n  | None => 0\n  | Some Nonempty => 1\n  | Some Readable => 2\n  | Some Writable => 3\n  | Some Freeable => 4\n  end.\nLemma perm_to_nat_bound:\n  forall p,\n    perm_to_nat p < 6.\nProof.\n  intros p.\n  destruct p as [p|];\n    try destruct p as [p|]; try destruct p; compute; auto.\nQed.\n\nLemma perm_to_nat_bound_simpl:\n  forall p,\n    perm_to_nat_simpl p < 5.\nProof.\n  intros p.\n  destruct p as [p|];\n    try destruct p; compute; auto.\nQed.\n\nLemma nat_to_perm_perm_to_nat:\n  forall p,\n    nat_to_perm (perm_to_nat p) = p.\nProof.\n  intros p.\n  destruct p as [p|];\n    try destruct p as [p|];\n    try destruct p;\n    reflexivity.\nQed.\n\nLemma nat_to_perm_perm_to_nat_simpl:\n  forall p,\n    nat_to_perm_simpl (perm_to_nat_simpl p) = p.\nProof.\n  intros p.\n  destruct p as [p|];\n    try destruct p;\n    reflexivity.\nQed.\n\nLemma finite_bounded_nat_aux_func:\n  forall hi ,\n    konig.finite\n      ( fun f:nat -> option (option permission) => bounded_nat_func_aux f hi).\nProof.\n\n   intros hi.\n   pose (K:= perm_to_nat).\n   induction hi.\n   - exists 1%nat.\n     exists (fun x _ => None).\n     intros.\n     exists 0%nat.\n     split; auto.\n\n     extensionality b.\n     symmetry.\n     apply H.\n     apply /leP. omega.\n\n   - destruct IHhi as [N [FN H]].\n     exists (6*N)%nat.\n     exists (fun x i => if (Nat.eq_dec i hi) then\n                       nat_to_perm (Nat.modulo x 6)\n                else FN (Nat.div x 6) i).\n     move=> f HH.\n     specialize (H (fun n => if (Nat.eq_dec n hi) then\n                            None\n                          else f n) ).\n     destruct H as [i [ineq f_spec]].\n     + intros pp pphi.\n       destruct (Nat.eq_dec pp hi).\n       * auto.\n       * simpl; eapply HH.\n         move: pphi=> /leP pphi.\n         apply /ltP.\n         omega.\n\n     + exists ((6 * i) + (perm_to_nat (f hi))).\n       split.\n       * replace (6 * N) with\n         (6 * (N - 1) + 6 ).\n         { eapply (NPeano.Nat.lt_le_trans _ (6 * i  + 6)).\n           - apply /leP.\n             rewrite ltn_add2l.\n             destruct (f hi) as [p|];\n               [destruct p; try destruct p|]; simpl; apply /leP; try omega.\n           - apply /leP.\n             rewrite leq_add2r.\n             rewrite leq_pmul2l.\n             + apply / leP. clear -ineq.\n               replace N with (S (N - 1)) in ineq.\n               apply /leP.\n               by rewrite - ltnS; apply /leP.\n               rewrite -addn1.\n               apply subnK.\n               destruct N; apply /ltP; try omega.\n             + compute; auto.\n         }\n         rewrite - mulnSr.\n         replace (N -1).+1 with N; auto.\n         rewrite -addn1.\n         symmetry; apply subnK.\n         destruct N; apply /ltP; try omega.\n       * { extensionality i0.\n           destruct (Nat.eq_dec i0 hi).\n           - subst.\n             rewrite addnC.\n             rewrite mulnC.\n             rewrite NPeano.Nat.mod_add; try omega.\n             rewrite NPeano.Nat.mod_small;\n               try (apply /ltP; eapply perm_to_nat_bound).\n             rewrite nat_to_perm_perm_to_nat.\n             reflexivity.\n\n           - replace ((6 * i + perm_to_nat (f hi)) / 6) with i.\n             + rewrite f_spec.\n               simpl.\n               destruct (Nat.eq_dec i0 hi);\n                 try solve [exfalso; apply n; auto].\n               reflexivity.\n             + eapply NPeano.Nat.div_unique;\n               try (apply /ltP; eapply perm_to_nat_bound).\n               reflexivity.\n         }\nQed.\n\n\nLemma finite_bounded_nat_aux_func_simpl:\n  forall hi ,\n    konig.finite\n      ( fun f:nat -> option permission => bounded_nat_func_aux f hi).\nProof.\n\n   intros hi.\n   pose (K:= perm_to_nat_simpl).\n   induction hi.\n   - exists 1%nat.\n     exists (fun x _ => None).\n     intros.\n     exists 0%nat.\n     split; auto.\n\n     extensionality b.\n     symmetry.\n     apply H.\n     apply /leP. omega.\n\n   - destruct IHhi as [N [FN H]].\n     exists (5*N)%nat.\n     exists (fun x i => if (Nat.eq_dec i hi) then\n                       nat_to_perm_simpl (Nat.modulo x 5)\n                else FN (Nat.div x 5) i).\n     move=> f HH.\n     specialize (H (fun n => if (Nat.eq_dec n hi) then\n                            None\n                          else f n) ).\n     destruct H as [i [ineq f_spec]].\n     + intros pp pphi.\n       destruct (Nat.eq_dec pp hi).\n       * auto.\n       * simpl; eapply HH.\n         move: pphi=> /leP pphi.\n         apply /ltP.\n         omega.\n\n     + exists ((5 * i) + (perm_to_nat_simpl (f hi))).\n       split.\n       * replace (5 * N) with\n         (5 * (N - 1) + 5 ).\n         { eapply (NPeano.Nat.lt_le_trans _ (5 * i  + 5)).\n           - apply /leP.\n             rewrite ltn_add2l.\n             destruct (f hi) as [p|]; [destruct p|]; simpl; apply /leP; try omega.\n           - apply /leP.\n             rewrite leq_add2r.\n             rewrite leq_pmul2l.\n             + apply / leP. clear -ineq.\n               replace N with (S (N - 1)) in ineq.\n               apply /leP.\n               by rewrite - ltnS; apply /leP.\n               rewrite -addn1.\n               apply subnK.\n               destruct N; apply /ltP; try omega.\n             + compute; auto.\n         }\n         rewrite - mulnSr.\n         replace (N -1).+1 with N; auto.\n         rewrite -addn1.\n         symmetry; apply subnK.\n         destruct N; apply /ltP; try omega.\n       * { extensionality i0.\n           destruct (Nat.eq_dec i0 hi).\n           - subst.\n             rewrite addnC.\n             rewrite mulnC.\n             rewrite NPeano.Nat.mod_add; try omega.\n             rewrite NPeano.Nat.mod_small;\n               try (apply /ltP; eapply perm_to_nat_bound_simpl).\n             rewrite nat_to_perm_perm_to_nat_simpl.\n             reflexivity.\n\n           - replace ((5 * i + perm_to_nat_simpl (f hi)) / 5) with i.\n             + rewrite f_spec.\n               simpl.\n               destruct (Nat.eq_dec i0 hi);\n                 try solve [exfalso; apply n; auto].\n               reflexivity.\n             + eapply NPeano.Nat.div_unique;\n               try (apply /ltP; eapply perm_to_nat_bound_simpl).\n               reflexivity.\n         }\nQed.\n\nLemma finite_bounded_nat_func:\n  forall hi ,\n    konig.finite\n      ( fun f:nat -> option (option permission) => bounded_nat_func' f hi).\nProof.\n  intros.\n  destruct (finite_bounded_nat_aux_func (S hi)) as [x [f HH]].\n  exists x, f.\n  move=> x0 BND.\n  cut (bounded_nat_func_aux x0 hi.+1).\n  Focus 2. { intros b ineq; eapply BND; auto. } Unfocus.\n  move=> /HH [] i [] A B.\n  exists i; split; eauto.\nQed.\n\n\nLemma finite_bounded_nat_func_simpl:\n  forall hi ,\n    konig.finite\n      ( fun f:nat -> option permission => bounded_nat_func' f hi).\nProof.\n  intros.\n  destruct (finite_bounded_nat_aux_func_simpl (S hi)) as [x [f HH]].\n  exists x, f.\n  move=> x0 BND.\n  cut (bounded_nat_func_aux x0 hi.+1).\n  Focus 2. { intros b ineq; eapply BND; auto. } Unfocus.\n  move=> /HH [] i [] A B.\n  exists i; split; eauto.\nQed.\n\nLemma finite_bounded_func:\n  forall hi lo,\n    konig.finite\n      ( fun f:Z -> option (option permission) => bounded_func' f hi lo).\nProof.\n  intros hi lo.\n  destruct (Coqlib.zlt hi lo).\n  - exists 1%N.\n    exists (fun _ _ => None).\n    intros.\n    exists 0%nat; split; auto.\n    extensionality b.\n    destruct H as[H1 H2].\n    symmetry.\n    destruct (Coqlib.zle b hi).\n    + eapply H2.\n      eapply Z.le_lt_trans; eauto.\n    + eapply H1; assumption.\n  - assert (0 <= hi - lo)%Z by omega.\n    pose (n:= Z.to_nat (hi - lo)).\n    destruct (finite_bounded_nat_func n) as [N [FN HN]].\n    exists N.\n    exists (fun n z => (if (Z_lt_ge_dec z lo)\n                then None\n                else FN n (Z.to_nat (z-lo)))).\n    intros f [BOUND1 BOUND2].\n    pose (f':= fun n => f (Z.of_nat n + lo)%Z).\n    assert (bounded_nat_func' f' n).\n    { intros b ineq.\n      unfold f'.\n      eapply BOUND1.\n      unfold n in ineq.\n      cut (Z.of_nat b > hi - lo)%Z.\n      omega.\n      move: ineq => /ltP /inj_lt /Z.gt_lt_iff.\n      rewrite Z2Nat.id => //.\n    }\n    apply HN in H0.\n    destruct H0 as [i [ineq FN_spec]].\n    exists i; split; auto.\n    extensionality z.\n    rewrite FN_spec.\n    unfold f'.\n    destruct (Z_lt_ge_dec z lo).\n    + simpl.\n      symmetry.\n        by apply BOUND2.\n    + simpl.\n      rewrite Z2Nat.id.\n      * f_equal; omega.\n      * omega.\nQed.\n\n\nLemma finite_bounded_func_simpl:\n  forall hi lo,\n    konig.finite\n      ( fun f:Z -> option permission => bounded_func' f hi lo).\nProof.\n  intros hi lo.\n  destruct (Coqlib.zlt hi lo).\n  - exists 1%N.\n    exists (fun _ _ => None).\n    intros.\n    exists 0%nat; split; auto.\n    extensionality b.\n    destruct H as[H1 H2].\n    symmetry.\n    destruct (Coqlib.zle b hi).\n    + eapply H2.\n      eapply Z.le_lt_trans; eauto.\n    + eapply H1; assumption.\n  - assert (0 <= hi - lo)%Z by omega.\n    pose (n:= Z.to_nat (hi - lo)).\n    destruct (finite_bounded_nat_func_simpl n) as [N [FN HN]].\n    exists N.\n    exists (fun n z => (if (Z_lt_ge_dec z lo)\n                then None\n                else FN n (Z.to_nat (z-lo)))).\n    intros f [BOUND1 BOUND2].\n    pose (f':= fun n => f (Z.of_nat n + lo)%Z).\n    assert (bounded_nat_func' f' n).\n    { intros b ineq.\n      unfold f'.\n      eapply BOUND1.\n      unfold n in ineq.\n      cut (Z.of_nat b > hi - lo)%Z.\n      omega.\n      move: ineq => /ltP /inj_lt /Z.gt_lt_iff.\n      rewrite Z2Nat.id => //.\n    }\n    apply HN in H0.\n    destruct H0 as [i [ineq FN_spec]].\n    exists i; split; auto.\n    extensionality z.\n    rewrite FN_spec.\n    unfold f'.\n    destruct (Z_lt_ge_dec z lo).\n    + simpl.\n      symmetry.\n        by apply BOUND2.\n    + simpl.\n      rewrite Z2Nat.id.\n      * f_equal; omega.\n      * omega.\nQed.\n\nLemma finite_bounded_op_func_simpl:\n  forall hi lo,\n    konig.finite\n      ( fun f: option (Z -> option permission) => bounded_func_op f hi lo).\nProof.\n  move => hi lo.\n  move: (finite_bounded_func_simpl hi lo) => [] N [] FN FN_spec.\n\n  exists (S N).\n  exists (fun n => if n == 0 then None\n           else Some (FN (n -1)) ).\n  move => f H.\n  destruct f.\n  - move: FN_spec => /(_ _ H) [] i [] ineqi speci.\n    exists (S i); split.\n    + omega.\n    + rewrite - speci.\n      simpl; repeat f_equal.\n      rewrite - addn1 - addnBA=> //.\n  - exists 0; split; auto.\n    + omega.\nQed.\n\nLemma finite_bounded_op_func:\n  forall hi lo,\n    konig.finite\n      ( fun f: option (Z -> option (option permission)) => bounded_func_op f hi lo).\nProof.\n  move => hi lo.\n  move: (finite_bounded_func hi lo) => [] N [] FN FN_spec.\n\n  exists (S N).\n  exists (fun n => if n == 0 then None\n           else Some (FN (n -1)) ).\n  move => f H.\n  destruct f.\n  - move: FN_spec => /(_ _ H) [] i [] ineqi speci.\n    exists (S i); split.\n    + omega.\n    + rewrite - speci.\n      simpl; repeat f_equal.\n      rewrite - addn1 - addnBA=> //.\n  - exists 0; split; auto.\n    + omega.\nQed.\n\nLemma finite_sub_maps:\n  forall m2,\n    @bounded_map permission m2 ->\n    konig.finite\n      (fun m1 => @sub_map (option permission) permission m1 m2).\nProof.\n  induction m2.\n  - move => _.\n    exists 1%nat.\n    exists (fun _ => PTree.Leaf).\n    intros .\n    exists 0%nat.\n    split; auto.\n    destruct x; auto.\n    unfold strong_tree_leq in H;\n      simpl in H.\n    destruct o; inversion H.\n  - move => H.\n    assert (HH1:\n              forall (p : positive) (f : Z -> option permission),\n                m2_1 ! p = Some f ->\n                exists hi lo : Z,\n                  (forall p0 : Z, (p0 > hi)%Z -> f p0 = None) /\\\n                  (forall p0 : Z, (p0 < lo)%Z -> f p0 = None)).\n    { clear - H.\n      move=> p f Hget.\n      move : H => /(_ (p~0)%positive f ltac:(simpl;auto)) [] hi [] lo BOUND.\n      exists hi, lo; assumption.\n    }\n    move: IHm2_1=> /(_ HH1) [] N1 [] F1 spec_F1.\n    assert (HH2:\n              forall (p : positive) (f : Z -> option permission),\n                m2_2 ! p = Some f ->\n                exists hi lo : Z,\n                  (forall p0 : Z, (p0 > hi)%Z -> f p0 = None) /\\\n                  (forall p0 : Z, (p0 < lo)%Z -> f p0 = None)).\n    { clear - H.\n      move=> p f Hget.\n      move : H => /(_ (p~1)%positive f ltac:(simpl;auto)) [] hi [] lo BOUND.\n      exists hi, lo; assumption.\n    }\n    move: IHm2_2=> /(_ HH2) [] N2 [] F2 spec_F2.\n    destruct o as [f1|].\n    + move : H => /(_ 1%positive f1 ltac:(reflexivity)) [] hi [] lo BNDD.\n      move : (finite_bounded_op_func hi lo) => [] N [] F F_spec.\n      exists (S( N * N1 * N2)).\n      exists (fun n => if n == 0\n               then PTree.Leaf\n               else\n                 PTree.Node\n                   (F1 ( (n-1) mod N1))\n                   (F ((n-1) / (N1 * N2)))\n                   (F2 (((n-1) / N1 ) mod N2))).\n      intros x spec.\n      destruct x.\n      * exists 0%nat; split; auto.\n        omega.\n      * move: spec .\n        rewrite /sub_map /= => [] [] FUN_lq [] tree1 tree2.\n        assert (bounded_func_op o hi lo).\n        { Lemma fun_le_bounded_func_op:\n            forall {A} o f hi lo,\n              @bounded_func' A f hi lo ->\n              fun_leq o (Some f) ->\n              @bounded_func_op (option A) o hi lo.\n          Proof.\n            intros.\n            destruct o; [|constructor].\n            simpl.\n            simpl in H0.\n            split; intros p.\n            - intros HH. apply H in HH.\n              unfold fun_leq' in H0.\n              specialize (H0 p).\n              destruct (o p); try solve [auto].\n              specialize (H0 ltac:(auto)).\n              rewrite HH in H0; inversion H0.\n            - intros HH. apply H in HH.\n              unfold fun_leq' in H0.\n              specialize (H0 p).\n              destruct (o p); try solve [auto].\n              specialize (H0 ltac:(auto)).\n              rewrite HH in H0; inversion H0.\n          Qed.\n          eapply fun_le_bounded_func_op ; eauto.\n          }\n        move: F_spec => /(_ _ H) []i [] ineq fi.\n        move : spec_F1 => /(_ _ tree1) [] i1 [] ineq1 fi1.\n        move : spec_F2 => /(_ _ tree2) [] i2 [] ineq2 fi2.\n        exists (S(i1 + (i2 * N1) + (i * N1 * N2))); split.\n        { apply lt_n_S.\n          replace (N * N1 * N2) with\n          (N1 + N1 * (N2 * N -1)).\n          - eapply (NPeano.Nat.lt_le_trans).\n            + instantiate (1:= (N1 + i2 * N1 + i * N1 * N2)).\n              apply /ltP.\n              rewrite ltn_add2r;\n                rewrite ltn_add2r;\n                apply /ltP; auto.\n            + apply /leP.\n              rewrite -addnA.\n              rewrite leq_add2l.\n              apply /leP.\n              replace (i * N1 * N2) with\n              ((i * N2) * N1).\n              *\n                rewrite -mulnDl.\n                rewrite mulnC.\n                apply /leP.\n                rewrite leq_pmul2l; try (apply /ltP; omega).\n                apply /leP.\n                eapply lt_n_Sm_le.\n                rewrite - addn1.\n                rewrite subnK.\n                2:\n                  rewrite muln_gt0;\n                  apply /andP; split;\n                  try (apply /ltP; omega).\n                eapply (NPeano.Nat.lt_le_trans).\n                -- instantiate (1:= N2 + i * N2).\n                   apply /ltP.\n                   rewrite ltn_add2r.\n                   apply /leP; auto.\n                -- replace (N2 + i * N2) with\n                   (N2 * (1 + i)).\n                   apply /leP.\n                   rewrite leq_pmul2l.\n                   rewrite add1n.\n                   apply /ltP; auto.\n                   apply /ltP; omega.\n                   rewrite mulnDr.\n                   rewrite mulnC.\n                   f_equal.\n                   compute; auto.\n                   rewrite mulnC; auto.\n              * do 2 rewrite - mulnA.\n                f_equal. rewrite mulnC; auto.\n          - replace (N1 + N1 * (N2 * N - 1))\n            with (N1 * 1 + N1 * (N2 * N - 1)).\n            + rewrite -mulnDr.\n              rewrite addnC.\n              rewrite subnK.\n\n              2:\n                rewrite muln_gt0;\n                apply /andP; split;\n                try (apply /ltP; omega).\n              rewrite -mulnA.\n              rewrite mulnA.\n              rewrite mulnC; auto.\n            + f_equal.\n              rewrite mulnC.\n              compute; auto. }\n      -- simpl; f_equal.\n         ++ rewrite - fi1.\n            f_equal.\n            rewrite -addn1.\n            rewrite -addnBA. 2: ssromega.\n            replace (i1 + i2 * N1 + i * N1 * N2 + (1 - 1)) with\n            (i1 + i2 * N1 + i * N1 * N2) by ssromega.\n            replace (i1 + i2 * N1 + i * N1 * N2) with\n            (i1 + (i2  + i *  N2) * N1).\n            2:\n            rewrite mulnDl addnA; f_equal;\n            do 2 rewrite -mulnA; f_equal; rewrite mulnC; auto.\n            rewrite NPeano.Nat.mod_add.\n            apply NPeano.Nat.mod_small; auto.\n            destruct N1; omega.\n         ++ rewrite - fi.\n            f_equal.\n            rewrite -addn1.\n            rewrite -addnBA. 2: ssromega.\n            replace (i1 + i2 * N1 + i * N1 * N2 + (1 - 1)) with\n            (i1 + i2 * N1 + i * N1 * N2) by ssromega.\n            assert (i1 + i2 * N1 + i * N1 * N2 =\n                    ((N1 * N2) * i) + (i1 + i2 * N1)).\n            { rewrite addnC. f_equal.\n              rewrite - mulnA mulnC; auto. }\n            eapply NPeano.Nat.div_unique in H0; auto.\n            eapply (NPeano.Nat.lt_le_trans).\n            ** instantiate (1:= N1 + i2 * N1).\n               apply /ltP; rewrite ltn_add2r.\n               apply /ltP; auto.\n            ** replace (N1 + i2 * N1) with ( (1 + i2) * N1).\n               rewrite add1n.\n               rewrite mulnC.\n               apply /leP; rewrite leq_pmul2l.\n               apply /ltP; auto.\n               destruct N1; ssromega.\n               rewrite mulnDl; f_equal.\n               ssromega.\n\n         ++ rewrite - fi2.\n            f_equal.\n            rewrite -addn1.\n            rewrite -addnBA. 2: ssromega.\n            replace (i1 + i2 * N1 + i * N1 * N2 + (1 - 1)) with\n            (i1 + i2 * N1 + i * N1 * N2) by ssromega.\n            assert (i1 + i2 * N1 + i * N1 * N2 =\n                    (N1 * (i2 + i * N2)) + i1).\n            { rewrite -addnA.\n              replace (i * N1 * N2) with\n              (i  * N2 * N1).\n              rewrite - mulnDl.\n              rewrite mulnC addnC; auto.\n              do 2 rewrite -mulnA; f_equal.\n              rewrite mulnC. auto. }\n            eapply NPeano.Nat.div_unique in H0; auto.\n            rewrite - H0.\n            rewrite NPeano.Nat.mod_add.\n            apply NPeano.Nat.mod_small; auto.\n            destruct N2; omega.\n    + exists (S( N1 * N2)).\n      exists (fun n => if n == 0\n               then PTree.Leaf\n               else\n                 PTree.Node\n                   (F1 ( (n-1) mod N1))\n                   (None )\n                   (F2 (((n-1) / N1 ) mod N2))).\n      intros x spec.\n      destruct x.\n      * exists 0%nat; split; auto.\n        omega.\n      * move: spec .\n        rewrite /sub_map /= => [] [] FUN_lq [] tree1 tree2.\n        move : spec_F1 => /(_ _ tree1) [] i1 [] ineq1 fi1.\n        move : spec_F2 => /(_ _ tree2) [] i2 [] ineq2 fi2.\n        exists (S(i1 + (i2 * N1))); split.\n        { apply lt_n_S.\n          replace (N1 * N2) with\n          (N1 + N1 * (N2 -1)).\n          - eapply (NPeano.Nat.lt_le_trans).\n            + instantiate (1:= (N1 + i2 * N1)).\n              apply /ltP.\n              rewrite ltn_add2r;\n                apply /ltP; auto.\n            + apply /leP.\n              rewrite leq_add2l.\n              apply /leP.\n              rewrite mulnC.\n              apply /leP.\n              rewrite leq_pmul2l; try (apply /ltP; omega).\n              apply /leP.\n              eapply lt_n_Sm_le.\n              rewrite - addn1.\n              rewrite subnK; auto.\n              destruct N2; ssromega.\n\n          - replace (N1 + N1 * (N2 - 1))\n            with (N1 * 1 + N1 * (N2 - 1)).\n            + rewrite -mulnDr.\n              rewrite addnC.\n              rewrite subnK.\n              2: ssromega.\n              rewrite mulnC; auto.\n            + f_equal.\n              rewrite mulnC.\n              compute; auto. }\n      -- simpl; f_equal.\n         ++ rewrite - fi1.\n            f_equal.\n            rewrite -addn1.\n            rewrite -addnBA. 2: ssromega.\n            replace (i1 + i2 * N1 + (1 - 1)) with\n            (i1 + i2 * N1) by ssromega.\n            rewrite NPeano.Nat.mod_add.\n            apply NPeano.Nat.mod_small; auto.\n            destruct N1; omega.\n         ++ destruct o; auto; inversion FUN_lq.\n         ++ rewrite - fi2.\n            f_equal.\n            rewrite -addn1.\n            rewrite -addnBA. 2: ssromega.\n            replace (i1 + i2 * N1 + (1 - 1)) with\n            (i1 + i2 * N1 ) by ssromega.\n            assert (i1 + i2 * N1 =\n                    (N1 * (i2) + i1)).\n            { rewrite mulnC addnC; auto. }\n            eapply NPeano.Nat.div_unique in H0; auto.\n            rewrite - H0.\n            apply NPeano.Nat.mod_small; auto.\nQed.\n\nLemma finite_sub_maps_simpl:\n  forall m2,\n    @bounded_map permission m2 ->\n    konig.finite\n      (fun m1 => @sub_map permission permission m1 m2).\nProof.\n\n  induction m2.\n  - move => _.\n    exists 1%nat.\n    exists (fun _ => PTree.Leaf).\n    intros .\n    exists 0%nat.\n    split; auto.\n    destruct x; auto.\n    unfold strong_tree_leq in H;\n      simpl in H.\n    destruct o; inversion H.\n  - move => H.\n    assert (HH1:\n              forall (p : positive) (f : Z -> option permission),\n                m2_1 ! p = Some f ->\n                exists hi lo : Z,\n                  (forall p0 : Z, (p0 > hi)%Z -> f p0 = None) /\\\n                  (forall p0 : Z, (p0 < lo)%Z -> f p0 = None)).\n    { clear - H.\n      move=> p f Hget.\n      move : H => /(_ (p~0)%positive f ltac:(simpl;auto)) [] hi [] lo BOUND.\n      exists hi, lo; assumption.\n    }\n    move: IHm2_1=> /(_ HH1) [] N1 [] F1 spec_F1.\n    assert (HH2:\n              forall (p : positive) (f : Z -> option permission),\n                m2_2 ! p = Some f ->\n                exists hi lo : Z,\n                  (forall p0 : Z, (p0 > hi)%Z -> f p0 = None) /\\\n                  (forall p0 : Z, (p0 < lo)%Z -> f p0 = None)).\n    { clear - H.\n      move=> p f Hget.\n      move : H => /(_ (p~1)%positive f ltac:(simpl;auto)) [] hi [] lo BOUND.\n      exists hi, lo; assumption.\n    }\n    move: IHm2_2=> /(_ HH2) [] N2 [] F2 spec_F2.\n    destruct o as [f1|].\n    + move : H => /(_ 1%positive f1 ltac:(reflexivity)) [] hi [] lo BNDD.\n      move : (finite_bounded_op_func_simpl hi lo) => [] N [] F F_spec.\n      exists (S( N * N1 * N2)).\n      exists (fun n => if n == 0\n               then PTree.Leaf\n               else\n                 PTree.Node\n                   (F1 ( (n-1) mod N1))\n                   (F ((n-1) / (N1 * N2)))\n                   (F2 (((n-1) / N1 ) mod N2))).\n      intros x spec.\n      destruct x.\n      * exists 0%nat; split; auto.\n        omega.\n      * move: spec .\n        rewrite /sub_map /= => [] [] FUN_lq [] tree1 tree2.\n        assert (bounded_func_op o hi lo).\n        { Lemma fun_le_bounded_func_op_simpl:\n            forall {A} o f hi lo,\n              @bounded_func' A f hi lo ->\n              fun_leq o (Some f) ->\n              @bounded_func_op A o hi lo.\n          Proof.\n            intros.\n            destruct o; [|constructor].\n            simpl.\n            simpl in H0.\n            split; intros p.\n            - intros HH. apply H in HH.\n              unfold fun_leq' in H0.\n              specialize (H0 p).\n              destruct (o p); try solve [auto].\n              specialize (H0 ltac:(auto)).\n              rewrite HH in H0; inversion H0.\n            - intros HH. apply H in HH.\n              unfold fun_leq' in H0.\n              specialize (H0 p).\n              destruct (o p); try solve [auto].\n              specialize (H0 ltac:(auto)).\n              rewrite HH in H0; inversion H0.\n          Qed.\n          eapply fun_le_bounded_func_op_simpl ; eauto.\n          }\n        move: F_spec => /(_ _ H) []i [] ineq fi.\n        move : spec_F1 => /(_ _ tree1) [] i1 [] ineq1 fi1.\n        move : spec_F2 => /(_ _ tree2) [] i2 [] ineq2 fi2.\n        exists (S(i1 + (i2 * N1) + (i * N1 * N2))); split.\n        { apply lt_n_S.\n          replace (N * N1 * N2) with\n          (N1 + N1 * (N2 * N -1)).\n          - eapply (NPeano.Nat.lt_le_trans).\n            + instantiate (1:= (N1 + i2 * N1 + i * N1 * N2)).\n              apply /ltP.\n              rewrite ltn_add2r;\n                rewrite ltn_add2r;\n                apply /ltP; auto.\n            + apply /leP.\n              rewrite -addnA.\n              rewrite leq_add2l.\n              apply /leP.\n              replace (i * N1 * N2) with\n              ((i * N2) * N1).\n              *\n                rewrite -mulnDl.\n                rewrite mulnC.\n                apply /leP.\n                rewrite leq_pmul2l; try (apply /ltP; omega).\n                apply /leP.\n                eapply lt_n_Sm_le.\n                rewrite - addn1.\n                rewrite subnK.\n                2:\n                  rewrite muln_gt0;\n                  apply /andP; split;\n                  try (apply /ltP; omega).\n                eapply (NPeano.Nat.lt_le_trans).\n                -- instantiate (1:= N2 + i * N2).\n                   apply /ltP.\n                   rewrite ltn_add2r.\n                   apply /leP; auto.\n                -- replace (N2 + i * N2) with\n                   (N2 * (1 + i)).\n                   apply /leP.\n                   rewrite leq_pmul2l.\n                   rewrite add1n.\n                   apply /ltP; auto.\n                   apply /ltP; omega.\n                   rewrite mulnDr.\n                   rewrite mulnC.\n                   f_equal.\n                   compute; auto.\n                   rewrite mulnC; auto.\n              * do 2 rewrite - mulnA.\n                f_equal. rewrite mulnC; auto.\n          - replace (N1 + N1 * (N2 * N - 1))\n            with (N1 * 1 + N1 * (N2 * N - 1)).\n            + rewrite -mulnDr.\n              rewrite addnC.\n              rewrite subnK.\n\n              2:\n                rewrite muln_gt0;\n                apply /andP; split;\n                try (apply /ltP; omega).\n              rewrite -mulnA.\n              rewrite mulnA.\n              rewrite mulnC; auto.\n            + f_equal.\n              rewrite mulnC.\n              compute; auto. }\n      -- simpl; f_equal.\n         ++ rewrite - fi1.\n            f_equal.\n            rewrite -addn1.\n            rewrite -addnBA. 2: ssromega.\n            replace (i1 + i2 * N1 + i * N1 * N2 + (1 - 1)) with\n            (i1 + i2 * N1 + i * N1 * N2) by ssromega.\n            replace (i1 + i2 * N1 + i * N1 * N2) with\n            (i1 + (i2  + i *  N2) * N1).\n            2:\n            rewrite mulnDl addnA; f_equal;\n            do 2 rewrite -mulnA; f_equal; rewrite mulnC; auto.\n            rewrite NPeano.Nat.mod_add.\n            apply NPeano.Nat.mod_small; auto.\n            destruct N1; omega.\n         ++ rewrite - fi.\n            f_equal.\n            rewrite -addn1.\n            rewrite -addnBA. 2: ssromega.\n            replace (i1 + i2 * N1 + i * N1 * N2 + (1 - 1)) with\n            (i1 + i2 * N1 + i * N1 * N2) by ssromega.\n            assert (i1 + i2 * N1 + i * N1 * N2 =\n                    ((N1 * N2) * i) + (i1 + i2 * N1)).\n            { rewrite addnC. f_equal.\n              rewrite - mulnA mulnC; auto. }\n            eapply NPeano.Nat.div_unique in H0; auto.\n            eapply (NPeano.Nat.lt_le_trans).\n            ** instantiate (1:= N1 + i2 * N1).\n               apply /ltP; rewrite ltn_add2r.\n               apply /ltP; auto.\n            ** replace (N1 + i2 * N1) with ( (1 + i2) * N1).\n               rewrite add1n.\n               rewrite mulnC.\n               apply /leP; rewrite leq_pmul2l.\n               apply /ltP; auto.\n               destruct N1; ssromega.\n               rewrite mulnDl; f_equal.\n               ssromega.\n\n         ++ rewrite - fi2.\n            f_equal.\n            rewrite -addn1.\n            rewrite -addnBA. 2: ssromega.\n            replace (i1 + i2 * N1 + i * N1 * N2 + (1 - 1)) with\n            (i1 + i2 * N1 + i * N1 * N2) by ssromega.\n            assert (i1 + i2 * N1 + i * N1 * N2 =\n                    (N1 * (i2 + i * N2)) + i1).\n            { rewrite -addnA.\n              replace (i * N1 * N2) with\n              (i  * N2 * N1).\n              rewrite - mulnDl.\n              rewrite mulnC addnC; auto.\n              do 2 rewrite -mulnA; f_equal.\n              rewrite mulnC. auto. }\n            eapply NPeano.Nat.div_unique in H0; auto.\n            rewrite - H0.\n            rewrite NPeano.Nat.mod_add.\n            apply NPeano.Nat.mod_small; auto.\n            destruct N2; omega.\n    + exists (S( N1 * N2)).\n      exists (fun n => if n == 0\n               then PTree.Leaf\n               else\n                 PTree.Node\n                   (F1 ( (n-1) mod N1))\n                   (None )\n                   (F2 (((n-1) / N1 ) mod N2))).\n      intros x spec.\n      destruct x.\n      * exists 0%nat; split; auto.\n        omega.\n      * move: spec .\n        rewrite /sub_map /= => [] [] FUN_lq [] tree1 tree2.\n        move : spec_F1 => /(_ _ tree1) [] i1 [] ineq1 fi1.\n        move : spec_F2 => /(_ _ tree2) [] i2 [] ineq2 fi2.\n        exists (S(i1 + (i2 * N1))); split.\n        { apply lt_n_S.\n          replace (N1 * N2) with\n          (N1 + N1 * (N2 -1)).\n          - eapply (NPeano.Nat.lt_le_trans).\n            + instantiate (1:= (N1 + i2 * N1)).\n              apply /ltP.\n              rewrite ltn_add2r;\n                apply /ltP; auto.\n            + apply /leP.\n              rewrite leq_add2l.\n              apply /leP.\n              rewrite mulnC.\n              apply /leP.\n              rewrite leq_pmul2l; try (apply /ltP; omega).\n              apply /leP.\n              eapply lt_n_Sm_le.\n              rewrite - addn1.\n              rewrite subnK; auto.\n              destruct N2; ssromega.\n\n          - replace (N1 + N1 * (N2 - 1))\n            with (N1 * 1 + N1 * (N2 - 1)).\n            + rewrite -mulnDr.\n              rewrite addnC.\n              rewrite subnK.\n              2: ssromega.\n              rewrite mulnC; auto.\n            + f_equal.\n              rewrite mulnC.\n              compute; auto. }\n      -- simpl; f_equal.\n         ++ rewrite - fi1.\n            f_equal.\n            rewrite -addn1.\n            rewrite -addnBA. 2: ssromega.\n            replace (i1 + i2 * N1 + (1 - 1)) with\n            (i1 + i2 * N1) by ssromega.\n            rewrite NPeano.Nat.mod_add.\n            apply NPeano.Nat.mod_small; auto.\n            destruct N1; omega.\n         ++ destruct o; auto; inversion FUN_lq.\n         ++ rewrite - fi2.\n            f_equal.\n            rewrite -addn1.\n            rewrite -addnBA. 2: ssromega.\n            replace (i1 + i2 * N1 + (1 - 1)) with\n            (i1 + i2 * N1 ) by ssromega.\n            assert (i1 + i2 * N1 =\n                    (N1 * (i2) + i1)).\n            { rewrite mulnC addnC; auto. }\n            eapply NPeano.Nat.div_unique in H0; auto.\n            rewrite - H0.\n            apply NPeano.Nat.mod_small; 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/concurrency/bounded_maps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.26799047196509096}}
{"text": "(* Sequent calculus with upper bounds on proof size.\n   Useful for doing induction on.\n\n   The main purpose this file is to provide the inversion lemmas (see the bottom part of the file).\n *)\nFrom Coq Require Import ssreflect.\nFrom stdpp Require Import prelude.\nFrom bunched.algebra Require Import bi.\nFrom bunched Require Import seqcalc bunch_decomp prelude.lists.\n\nReserved Notation \"P ⊢ᴮ{ n } Q\" (at level 99, n, Q at level 200, right associativity).\nReserved Notation \"Δ =?{ n } Δ'\" (at level 99, n at level 200).\n\nModule SeqcalcHeight(R : ANALYTIC_STRUCT_EXT).\n  Import R.\n  Module S := Seqcalc(R).\n  Import S.\n\n  Implicit Type Δ : bunch.\n  Implicit Type ψ ϕ : formula.\n\n  (** ** Alternative formulation of bunch equivalences *)\n  Inductive bunch_equiv : bunch → bunch → Prop :=\n  | BE_cong C Δ1 Δ2 :\n      Δ1 =? Δ2 →\n      fill C Δ1 =? fill C Δ2\n  | BE_comma_unit_l Δ :\n      (empty ,, Δ)%B =? Δ\n  | BE_comma_comm Δ1 Δ2 :\n      (Δ1 ,, Δ2)%B =? (Δ2 ,, Δ1)%B\n  | BE_comma_assoc Δ1 Δ2 Δ3 : (Δ1 ,, (Δ2 ,, Δ3))%B =? ((Δ1 ,, Δ2) ,, Δ3)%B\n  | BE_semic_unit_l Δ : (top ;, Δ)%B =? Δ\n  | BE_semic_comm Δ1 Δ2  : (Δ1 ;, Δ2)%B =? (Δ2 ;, Δ1)%B\n  | BE_semic_assoc Δ1 Δ2 Δ3  : (Δ1 ;, (Δ2 ;, Δ3))%B =? ((Δ1 ;, Δ2) ;, Δ3)%B\n  where \"Δ =? Γ\" := (bunch_equiv Δ%B Γ%B).\n\n  Definition bunch_equiv_h := rtsc (bunch_equiv).\n\n  Lemma bunch_equiv_1 Δ Δ' :\n    (Δ =? Δ') → (Δ ≡ Δ').\n  Proof. induction 1; by econstructor; eauto. Qed.\n\n  Lemma bunch_equiv_2 Δ Δ' :\n    (Δ ≡ Δ') → (bunch_equiv_h Δ Δ').\n  Proof.\n    induction 1.\n    all: try by (eapply rtsc_lr; econstructor).\n    - unfold bunch_equiv_h. reflexivity.\n    - by symmetry.\n    - etrans; eauto.\n    - eapply rtc_congruence; eauto.\n      intros X Y. apply sc_congruence. clear X Y.\n      intros X Y ?. by econstructor.\n  Qed.\n\n  Local Lemma bunch_equiv_fill_1 Δ C ϕ :\n    fill C (frml ϕ) =? Δ →\n    ∃ C', Δ = fill C' (frml ϕ) ∧ (∀ Δ, fill C' Δ ≡ fill C Δ).\n  Proof.\n    intros Heq.\n    remember (fill C (frml ϕ)) as Y.\n    revert C HeqY.\n    induction Heq=>C' heqY; symmetry in heqY.\n    + apply bunch_decomp_complete in heqY.\n      apply bunch_decomp_ctx in heqY.\n      destruct heqY as [H1 | H2].\n      * destruct H1 as [C1 [HC0%bunch_decomp_correct HC]].\n        destruct (IHHeq C1 HC0) as [C2 [HΔ1 HC2]].\n        simplify_eq/=.\n        exists (C2 ++ C). rewrite fill_app. split; first done.\n        intros Δ. rewrite !fill_app HC2 //.\n      * destruct H2 as (C1 & C2 & HC1 & HC2 & Hdec0).\n        specialize (Hdec0 Δ2). apply bunch_decomp_correct in Hdec0.\n        exists (C1 Δ2). split ; eauto.\n        intros Δ. rewrite HC1.\n        assert (Δ1 ≡ Δ2) as <-.\n        { by apply bunch_equiv_1. }\n        by rewrite HC2.\n    + apply bunch_decomp_complete in heqY.\n      inversion heqY; simplify_eq/=.\n      { inversion H3. }\n      apply bunch_decomp_correct in H3.\n      exists Π. split; eauto.\n      intros X. rewrite fill_app /= left_id //.\n    + apply bunch_decomp_complete in heqY.\n      inversion heqY; simplify_eq/=.\n      * exists (Π ++ [CtxCommaR Δ2]). split.\n        { rewrite fill_app/=.\n          apply bunch_decomp_correct in H3.\n          by rewrite H3. }\n        intros Δ. rewrite !fill_app/=.\n        by rewrite comm.\n      * exists (Π ++ [CtxCommaL Δ1]). split.\n        { rewrite fill_app/=.\n          apply bunch_decomp_correct in H3.\n          by rewrite H3. }\n        intros Δ. rewrite !fill_app/=.\n        by rewrite comm.\n    + apply bunch_decomp_complete in heqY.\n      inversion heqY; simplify_eq/=.\n      * exists (Π ++ [CtxCommaL Δ2;CtxCommaL Δ3])%B. split.\n        { rewrite fill_app/=.\n          apply bunch_decomp_correct in H3.\n          by rewrite H3. }\n        intros Δ. rewrite !fill_app/=.\n        by rewrite assoc.\n      * inversion H3; simplify_eq/=.\n        ** exists (Π0 ++ [CtxCommaR Δ1;CtxCommaL Δ3])%B. split.\n           { rewrite fill_app/=.\n             apply bunch_decomp_correct in H4.\n               by rewrite H4. }\n           intros Δ. rewrite !fill_app/=.\n           by rewrite assoc.\n        ** exists (Π0 ++ [CtxCommaR (Δ1,,Δ2)])%B. split.\n           { simpl. rewrite fill_app/=.\n             apply bunch_decomp_correct in H4.\n             by rewrite H4. }\n           intros Δ. rewrite !fill_app/=.\n           by rewrite assoc.\n    + apply bunch_decomp_complete in heqY.\n      inversion heqY; simplify_eq/=.\n      { inversion H3. }\n      apply bunch_decomp_correct in H3.\n      exists Π. split; eauto.\n      intros X. rewrite fill_app /= left_id //.\n    + apply bunch_decomp_complete in heqY.\n      inversion heqY; simplify_eq/=.\n      * exists (Π ++ [CtxSemicR Δ2]). split.\n        { rewrite fill_app/=.\n          apply bunch_decomp_correct in H3.\n          by rewrite H3. }\n        intros Δ. rewrite !fill_app/=.\n        by rewrite comm.\n      * exists (Π ++ [CtxSemicL Δ1]). split.\n        { rewrite fill_app/=.\n          apply bunch_decomp_correct in H3.\n          by rewrite H3. }\n        intros Δ. rewrite !fill_app/=.\n        by rewrite comm.\n    + apply bunch_decomp_complete in heqY.\n      inversion heqY; simplify_eq/=.\n      * exists (Π ++ [CtxSemicL Δ2;CtxSemicL Δ3])%B. split.\n        { rewrite fill_app/=.\n          apply bunch_decomp_correct in H3.\n          by rewrite H3. }\n        intros Δ. rewrite !fill_app/=.\n        by rewrite assoc.\n      * inversion H3; simplify_eq/=.\n        ** exists (Π0 ++ [CtxSemicR Δ1;CtxSemicL Δ3])%B. split.\n           { rewrite fill_app/=.\n             apply bunch_decomp_correct in H4.\n               by rewrite H4. }\n           intros Δ. rewrite !fill_app/=.\n           by rewrite assoc.\n        ** exists (Π0 ++ [CtxSemicR (Δ1;,Δ2)])%B. split.\n           { simpl. rewrite fill_app/=.\n             apply bunch_decomp_correct in H4.\n             by rewrite H4. }\n           intros Δ. rewrite !fill_app/=.\n           by rewrite assoc.\n  Qed.\n\n  Local Lemma bunch_equiv_fill_2 Δ C ϕ :\n    Δ =? fill C (frml ϕ) →\n    ∃ C', Δ = fill C' (frml ϕ) ∧ (∀ Δ, fill C' Δ ≡ fill C Δ).\n  Proof.\n    intros Heq.\n    remember (fill C (frml ϕ)) as Y.\n    revert C HeqY.\n    induction Heq=>C' heqY; symmetry in heqY.\n    + apply bunch_decomp_complete in heqY.\n      apply bunch_decomp_ctx in heqY.\n      destruct heqY as [H1 | H2].\n      * destruct H1 as [C1 [HC0%bunch_decomp_correct HC]].\n        destruct (IHHeq C1 HC0) as [C2 [HΔ1 HC2]].\n        simplify_eq/=.\n        exists (C2 ++ C). rewrite fill_app. split; first done.\n        intros Δ. rewrite !fill_app HC2 //.\n      * destruct H2 as (C1 & C2 & HC1 & HC2 & Hdec0).\n        specialize (Hdec0 Δ1). apply bunch_decomp_correct in Hdec0.\n        exists (C1 Δ1). split ; eauto.\n        intros Δ. rewrite HC1.\n        assert (Δ1 ≡ Δ2) as ->.\n        { by apply bunch_equiv_1. }\n        by rewrite HC2.\n    + exists (C' ++ [CtxCommaR empty]). simpl; split.\n      { rewrite fill_app /=. by rewrite heqY. }\n      intros X; rewrite fill_app/=.\n      by rewrite left_id.\n    + apply bunch_decomp_complete in heqY.\n      inversion heqY; simplify_eq/=.\n      * exists (Π ++ [CtxCommaR Δ1]). split.\n        { rewrite fill_app/=.\n          apply bunch_decomp_correct in H3.\n          by rewrite H3. }\n        intros Δ. rewrite !fill_app/=.\n        by rewrite comm.\n      * exists (Π ++ [CtxCommaL Δ2]). split.\n        { rewrite fill_app/=.\n          apply bunch_decomp_correct in H3.\n          by rewrite H3. }\n        intros Δ. rewrite !fill_app/=.\n        by rewrite comm.\n    + apply bunch_decomp_complete in heqY.\n      inversion heqY; simplify_eq/=.\n      * inversion H3; simplify_eq/=.\n        ** exists (Π0 ++ [CtxCommaL (Δ2 ,, Δ3)])%B. split.\n           { rewrite fill_app/=.\n             apply bunch_decomp_correct in H4.\n               by rewrite H4. }\n           intros Δ. rewrite !fill_app/=.\n           by rewrite assoc.\n        ** exists (Π0 ++ [CtxCommaL Δ3;CtxCommaR Δ1])%B. split.\n           { simpl. rewrite fill_app/=.\n             apply bunch_decomp_correct in H4.\n             by rewrite H4. }\n           intros Δ. rewrite !fill_app/=.\n           by rewrite assoc.\n      * exists (Π ++ [CtxCommaR Δ2;CtxCommaR Δ1])%B. split.\n        { rewrite fill_app/=.\n          apply bunch_decomp_correct in H3.\n            by rewrite H3. }\n           intros Δ. rewrite !fill_app/=.\n           by rewrite assoc.\n    + exists (C' ++ [CtxSemicR top]). simpl; split.\n      { rewrite fill_app /=. by rewrite heqY. }\n      intros X; rewrite fill_app/=.\n      by rewrite left_id.\n    + apply bunch_decomp_complete in heqY.\n      inversion heqY; simplify_eq/=.\n      * exists (Π ++ [CtxSemicR Δ1]). split.\n        { rewrite fill_app/=.\n          apply bunch_decomp_correct in H3.\n          by rewrite H3. }\n        intros Δ. rewrite !fill_app/=.\n        by rewrite comm.\n      * exists (Π ++ [CtxSemicL Δ2]). split.\n        { rewrite fill_app/=.\n          apply bunch_decomp_correct in H3.\n          by rewrite H3. }\n        intros Δ. rewrite !fill_app/=.\n        by rewrite comm.\n    + apply bunch_decomp_complete in heqY.\n      inversion heqY; simplify_eq/=.\n      * inversion H3; simplify_eq/=.\n        ** exists (Π0 ++ [CtxSemicL (Δ2 ;, Δ3)])%B. split.\n           { rewrite fill_app/=.\n             apply bunch_decomp_correct in H4.\n             by rewrite H4. }\n           intros Δ. rewrite !fill_app/=.\n           by rewrite assoc.\n        ** exists (Π0 ++ [CtxSemicL Δ3;CtxSemicR Δ1])%B. split.\n           { simpl. rewrite fill_app/=.\n             apply bunch_decomp_correct in H4.\n             by rewrite H4. }\n           intros Δ. rewrite !fill_app/=.\n           by rewrite assoc.\n      * exists (Π ++ [CtxSemicR Δ2;CtxSemicR Δ1])%B. split.\n        { rewrite fill_app/=.\n          apply bunch_decomp_correct in H3.\n            by rewrite H3. }\n           intros Δ. rewrite !fill_app/=.\n           by rewrite assoc.\n  Qed.\n\n  Lemma bunch_equiv_fill Δ C ϕ :\n    Δ ≡ (fill C (frml ϕ)) →\n    ∃ C', Δ = fill C' (frml ϕ) ∧ (∀ Δ, fill C' Δ ≡ fill C Δ).\n  Proof.\n    intros H%bunch_equiv_2.\n    revert Δ H. eapply rtc_ind_l.\n    { exists C. eauto. }\n    intros X Y HXY HY. clear HY.\n    intros (C0 & -> & HC0).\n    destruct HXY as [HXY|HXY].\n    - apply bunch_equiv_fill_2 in HXY.\n      destruct HXY as (C' & -> & HC').\n      eexists; split; eauto.\n      intros ?. by rewrite HC' HC0.\n    - apply bunch_equiv_fill_1 in HXY.\n      destruct HXY as (C' & -> & HC').\n      eexists; split; eauto.\n      intros ?. by rewrite HC' HC0.\n  Qed.\n\n  (** * SEQUENT CALCULUS *)\n  Polymorphic Inductive proves : bunch → formula → nat → Prop :=\n    (* structural *)\n  | BI_Higher Δ ϕ n : (Δ ⊢ᴮ{n} ϕ) → (Δ ⊢ᴮ{S n} ϕ)\n  | BI_Axiom (a : atom) : frml (ATOM a) ⊢ᴮ{0} ATOM a\n  | BI_Equiv Δ Δ' ϕ n :\n      (Δ ≡ Δ') → (Δ ⊢ᴮ{n} ϕ) →\n      Δ' ⊢ᴮ{S n} ϕ\n  | BI_Weaken C Δ Δ' ϕ n : (fill C Δ ⊢ᴮ{n} ϕ) →\n                         fill C (Δ ;, Δ') ⊢ᴮ{S n} ϕ\n  | BI_Contr C Δ ϕ n : (fill C (Δ ;, Δ) ⊢ᴮ{n} ϕ) →\n                     fill C Δ ⊢ᴮ{S n} ϕ\n  | BI_Simple_Ext Π (Δs : nat → bunch) n\n    (Ts : list bterm) (T : bterm) ϕ :\n    (Ts, T) ∈ rules →\n    (∀ Ti, Ti ∈ Ts → fill Π (bterm_ctx_act Ti Δs) ⊢ᴮ{n} ϕ) →\n    fill Π (bterm_ctx_act T Δs) ⊢ᴮ{S n} ϕ\n  (* multiplicatives *)\n  | BI_Emp_R :\n      empty ⊢ᴮ{0} EMP\n  | BI_Emp_L C ϕ n :\n      (fill C empty ⊢ᴮ{n} ϕ) →\n      fill C (frml EMP) ⊢ᴮ{S n} ϕ\n  | BI_Sep_R Δ Δ' ϕ ψ n m :\n      (Δ ⊢ᴮ{n} ϕ) →\n      (Δ' ⊢ᴮ{m} ψ) →\n      Δ ,, Δ' ⊢ᴮ{S (n `max` m)} SEP ϕ ψ\n  | BI_Sep_L C ϕ ψ χ n :\n      (fill C (frml ϕ ,, frml ψ) ⊢ᴮ{n} χ) →\n      fill C (frml (SEP ϕ ψ)) ⊢ᴮ{S n} χ\n  | BI_Wand_R Δ ϕ ψ n :\n      (Δ ,, frml ϕ ⊢ᴮ{n} ψ) →\n      Δ  ⊢ᴮ{S n} WAND ϕ ψ\n  | BI_Wand_L C Δ ϕ ψ χ n m :\n      (Δ ⊢ᴮ{n} ϕ) →\n      (fill C (frml ψ) ⊢ᴮ{m} χ) →\n      fill C (Δ ,, frml (WAND ϕ ψ)) ⊢ᴮ{S (n `max` m)} χ\n    (* additives *)\n  | BI_False_L C ϕ :\n      fill C (frml BOT) ⊢ᴮ{0} ϕ\n  | BI_True_R Δ :\n      Δ ⊢ᴮ{0} TOP\n  | BI_True_L C ϕ n :\n      (fill C top ⊢ᴮ{n} ϕ) →\n      fill C (frml TOP) ⊢ᴮ{S n} ϕ\n  | BI_Conj_R Δ Δ' ϕ ψ n m :\n      (Δ ⊢ᴮ{n} ϕ) →\n      (Δ' ⊢ᴮ{m} ψ) →\n      Δ ;, Δ' ⊢ᴮ{S (n `max` m)} CONJ ϕ ψ\n  | BI_Conj_L C ϕ ψ χ n :\n      (fill C (frml ϕ ;, frml ψ) ⊢ᴮ{n} χ) →\n      fill C (frml (CONJ ϕ ψ)) ⊢ᴮ{S n} χ\n  | BI_Disj_R1 Δ ϕ ψ n :\n      (Δ ⊢ᴮ{n} ϕ) →\n      Δ ⊢ᴮ{S n} DISJ ϕ ψ\n  | BI_Disj_R2 Δ ϕ ψ n :\n      (Δ ⊢ᴮ{n} ψ) →\n      Δ ⊢ᴮ{S n} DISJ ϕ ψ\n  | BI_Disj_L Π ϕ ψ χ n m :\n      (fill Π (frml ϕ) ⊢ᴮ{n} χ) →\n      (fill Π (frml ψ) ⊢ᴮ{m} χ) →\n      fill Π (frml (DISJ ϕ ψ)) ⊢ᴮ{S (n `max` m)} χ\n  | BI_Impl_R Δ ϕ ψ n :\n      (Δ ;, frml ϕ ⊢ᴮ{n} ψ) →\n      Δ  ⊢ᴮ{S n} IMPL ϕ ψ\n  | BI_Impl_L C Δ ϕ ψ χ n m:\n      (Δ ⊢ᴮ{n} ϕ) →\n      (fill C (frml ψ) ⊢ᴮ{m} χ) →\n      fill C (Δ ;, frml (IMPL ϕ ψ)) ⊢ᴮ{S (n `max` m)} χ\n  where \"Δ ⊢ᴮ{ n } ϕ\" := (proves Δ%B ϕ%B n).\n\n  Lemma provesN_proves n Δ ϕ :\n    (Δ ⊢ᴮ{ n } ϕ) → Δ ⊢ᴮ ϕ.\n  Proof.\n    induction 1; try by econstructor; eauto.\n    (* XXX: somehow, [try] is really needed here ^ *)\n  Qed.\n\n  Lemma proves_le n m Δ ϕ :\n    n ≤ m → (Δ ⊢ᴮ{n} ϕ) → Δ ⊢ᴮ{m} ϕ.\n  Proof.\n    induction 1; auto.\n    intros H1. eapply BI_Higher. eauto.\n  Qed.\n\n  Lemma proves_provesN Δ ϕ :\n    (Δ ⊢ᴮ ϕ) → ∃ n, Δ ⊢ᴮ{n} ϕ.\n  Proof.\n    induction 1.\n    all: try destruct IHproves as [n IH].\n    all: try (destruct IHproves1 as [n1 IH1];\n              destruct IHproves2 as [n2 IH2]).\n    all: try by eexists; econstructor; eauto.\n    (* The worst case: simple structural rules *)\n    apply (Forall_forall (λ Ti, ∃ n : nat, fill Π (bterm_ctx_act Ti Δs) ⊢ᴮ{ n} ϕ)) in H1.\n    apply Forall_exists_Forall2 in H1.\n    destruct H1 as (ns & Hns).\n    exists (S (max_list ns)).\n    eapply BI_Simple_Ext; eauto.\n    intros Ti HTi.\n    destruct (elem_of_list_lookup_1 _ _ HTi) as [i Hi].\n    destruct (ns !! i) as [n|] eqn:Hn; last first.\n    { eapply Forall2_lookup_r in Hns; eauto.\n      naive_solver. }\n    eapply (proves_le n). {\n      eapply max_list_elem_of_le.\n      by eapply elem_of_list_lookup_2.\n    }\n    eapply Forall2_lookup_lr in Hns; eauto.\n  Qed.\n\n  (** * Inversion lemmas *)\n  Local Ltac bind_ctx :=\n    match goal with\n    | [ |- fill ?C ?Δ,, ?Δ' ⊢ᴮ{_} _ ] =>\n      replace (fill C Δ,, Δ')%B\n      with (fill (C ++ [CtxCommaL Δ']) Δ)%B\n      by rewrite fill_app//\n    | [ |- fill ?C ?Δ;, ?Δ' ⊢ᴮ{_} _ ] =>\n      replace (fill C Δ;, Δ')%B\n      with (fill (C ++ [CtxSemicL Δ']) Δ)%B\n      by rewrite fill_app//\n    end.\n\n  Local Ltac commute_left_rule IH :=\n    intros ->; bind_ctx;\n    econstructor; eauto; rewrite fill_app; by eapply IH.\n\n  Lemma wand_r_inv' Δ ϕ ψ n :\n    (Δ ⊢ᴮ{n} WAND ϕ ψ) →\n    (Δ ,, frml ϕ ⊢ᴮ{n} ψ)%B.\n  Proof.\n    remember (WAND ϕ ψ) as A.\n    intros H. revert ϕ ψ HeqA.\n    induction H; intros A B; try by inversion 1.\n    all: try by (commute_left_rule IHproves).\n    - intros ->. by constructor; apply IHproves.\n    - intros ->. eapply BI_Equiv.\n      { rewrite -H. reflexivity. }\n      by apply IHproves.\n    - intros ->. bind_ctx.\n      eapply BI_Simple_Ext; eauto.\n      intros Ti HTi. rewrite fill_app. simpl.\n      eapply H1; eauto.\n    - intros ?; simplify_eq/=. by apply BI_Higher.\n    - commute_left_rule IHproves2.\n    - intros ?; simplify_eq/=.\n      bind_ctx. eapply BI_Disj_L.\n      + rewrite fill_app/=. by eapply IHproves1.\n      + rewrite fill_app/=. by eapply IHproves2.\n    - commute_left_rule IHproves2.\n  Qed.\n\n  Lemma impl_r_inv' Δ ϕ ψ n :\n    (Δ ⊢ᴮ{n} IMPL ϕ ψ) →\n    (Δ ;, frml ϕ ⊢ᴮ{n} ψ)%B.\n  Proof.\n    remember (IMPL ϕ ψ) as A.\n    intros H. revert ϕ ψ HeqA.\n    induction H; intros A B; try by inversion 1.\n    all: try by (commute_left_rule IHproves).\n    - intros ->. by constructor; apply IHproves.\n    - intros ->. eapply BI_Equiv.\n      { rewrite -H. reflexivity. }\n      by apply IHproves.\n    - intros ->. bind_ctx.\n      eapply BI_Simple_Ext; eauto.\n      intros Ti HTi. rewrite fill_app. simpl.\n      eapply H1; eauto.\n    - commute_left_rule IHproves2.\n    - intros ?; simplify_eq/=.\n      bind_ctx. eapply BI_Disj_L.\n      + rewrite fill_app/=. by eapply IHproves1.\n      + rewrite fill_app/=. by eapply IHproves2.\n    - intros ?; simplify_eq/=. by apply BI_Higher.\n    - commute_left_rule IHproves2.\n  Qed.\n\n  Lemma sep_l_inv' Δ C ϕ ψ χ n :\n    (Δ ⊢ᴮ{n} χ) →\n    Δ = fill C (frml (SEP ϕ ψ)) →\n    (fill C (frml ϕ,, frml ψ) ⊢ᴮ{n} χ).\n  Proof.\n    revert C Δ χ.\n    induction n using lt_wf_ind. rename H into IHproves.\n    intros C Δ χ PROOF Heq. symmetry in Heq. revert Heq.\n    inversion PROOF; simplify_eq/= => Heq.\n    (* induction H => C' Heq; symmetry in Heq. *)\n    - (* raising the pf height *)\n      apply BI_Higher.\n      eapply IHproves; eauto.\n    - (* axiom *)\n      apply fill_is_frml in Heq. destruct_and!; simplify_eq/=.\n      (* eapply BI_Sep_R; by econstructor. *)\n    - (* equivalence of bunches *)\n      simplify_eq/=.\n      destruct (bunch_equiv_fill _ _ _ H) as [C2 [-> HC2]].\n      eapply BI_Equiv.\n      { apply HC2. }\n      eapply IHproves; eauto.\n    - (* weakening *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          apply BI_Weaken.\n          rewrite -fill_app.\n          eapply IHproves; eauto.\n          by apply bunch_decomp_correct, bunch_decomp_app.\n        * rewrite !fill_app/=.\n          by apply BI_Weaken.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Weaken.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* contraction *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2]; last first.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Contr.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n      + rename C0 into C'.\n        destruct H1 as [C0 [HC0 ->]].\n        apply bunch_decomp_correct in HC0.\n        simplify_eq/=.\n        assert (fill C' (fill C0 (frml ϕ,, frml ψ);, fill C0 (frml (SEP ϕ ψ))) ⊢ᴮ{ n0} χ) as IH1.\n        { specialize (IHproves n0 (lt_n_Sn _)).\n          set (C2 := (C0 ++ [CtxSemicL (fill C0 (frml (SEP ϕ ψ)))] ++ C')%B).\n          specialize (IHproves C2 _ _ H).\n          revert IHproves. rewrite /C2 !fill_app /=.\n          eauto. }\n        rewrite fill_app.\n        apply BI_Contr.\n        set (C2 := (C0 ++ [CtxSemicR (fill C0 (frml ϕ,, frml ψ))] ++ C')%B).\n        replace (fill C' (fill C0 (frml ϕ,, frml ψ);, fill C0 (frml ϕ,, frml ψ)))%B\n                   with (fill C2 (frml ϕ,, frml ψ))%B by rewrite fill_app//.\n        eapply IHproves; eauto.\n        rewrite /C2 fill_app//.\n    - (* ext *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2]; last first.\n      + destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        eapply BI_Simple_Ext; eauto.\n        intros Ti Hi.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n      + destruct H1 as [C0 [HC0 ->]].\n        apply bunch_decomp_correct in HC0.\n        simplify_eq/=.\n        apply bterm_ctx_act_decomp in HC0; last first.\n        { by eapply (rules_good (Ts,T)). }\n        destruct HC0 as (j & Π₀ & Hjfv & Hj & HC0).\n        rewrite fill_app -HC0.\n        eapply BI_Simple_Ext; eauto.\n        revert Hj Hjfv IHproves H0.\n        clear.\n        intros Hj Hjfv IHproves Hpfs.\n        intros Ti HTi. specialize (Hpfs Ti HTi).\n        revert Π Hpfs. clear HTi.\n        induction Ti=>Π Hpfs.\n        { simpl.\n          destruct (decide (j = x)) as [->|?].\n          - rewrite functions.fn_lookup_insert.\n            rewrite -fill_app.\n            eapply IHproves; eauto.\n            by rewrite fill_app -Hj.\n          - rewrite functions.fn_lookup_insert_ne; auto. }\n        { simpl.\n          assert (fill ([CtxCommaL (bterm_ctx_act Ti2 Δs)]++Π) (bterm_ctx_act Ti1 (<[j:=fill Π₀ (frml ϕ,, frml ψ)]> Δs)) ⊢ᴮ{ n0} χ) as HH1.\n          { eapply IHTi1. rewrite fill_app /=. eauto. }\n          rewrite fill_app in HH1.\n          simpl in HH1.\n          replace\n          (fill Π (bterm_ctx_act Ti1\n             (<[j:=fill Π₀ (frml ϕ,, frml ψ)]> Δs),,bterm_ctx_act Ti2 (<[j:=fill Π₀ (frml ϕ,, frml ψ)]> Δs)))%B\n            with\n          (fill ([CtxCommaR (bterm_ctx_act Ti1 (<[j:=fill Π₀ (frml ϕ,, frml ψ)]> Δs))]++Π)\n                (bterm_ctx_act Ti2 (<[j:=fill Π₀ (frml ϕ,, frml ψ)]> Δs)))%B\n            by rewrite fill_app//.\n          eapply IHTi2.\n          rewrite fill_app/=//. }\n        { simpl.\n          assert (fill ([CtxSemicL (bterm_ctx_act Ti2 Δs)]++Π) (bterm_ctx_act Ti1 (<[j:=fill Π₀ (frml ϕ,, frml ψ)]> Δs)) ⊢ᴮ{ n0} χ) as HH1.\n          { eapply IHTi1. rewrite fill_app /=. eauto. }\n          rewrite fill_app in HH1.\n          simpl in HH1.\n          replace\n          (fill Π (bterm_ctx_act Ti1\n             (<[j:=fill Π₀ (frml ϕ,, frml ψ)]> Δs);,bterm_ctx_act Ti2 (<[j:=fill Π₀ (frml ϕ,, frml ψ)]> Δs)))%B\n            with\n          (fill ([CtxSemicR (bterm_ctx_act Ti1 (<[j:=fill Π₀ (frml ϕ,, frml ψ)]> Δs))]++Π)\n                (bterm_ctx_act Ti2 (<[j:=fill Π₀ (frml ϕ,, frml ψ)]> Δs)))%B\n            by rewrite fill_app//.\n          eapply IHTi2.\n          rewrite fill_app/=//. }\n    - (* emp R *)\n      exfalso.\n      apply bunch_decomp_complete in Heq.\n      inversion Heq.\n    - (* emp L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Emp_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* sep R *)\n      apply bunch_decomp_complete in Heq.\n      inversion Heq; simplify_eq/=.\n      + rewrite fill_app /=.\n        eapply BI_Sep_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n      + rewrite fill_app /=.\n        eapply BI_Sep_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n    - (* sep L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        by apply BI_Higher.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Sep_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* wand R *)\n      apply BI_Wand_R.\n      assert ((fill C (frml ϕ,, frml ψ),, frml ϕ0) =\n                   fill (C ++ [CtxCommaL (frml ϕ0)]) (frml ϕ,, frml ψ))%B as ->.\n      { rewrite fill_app//. }\n      eapply IHproves; eauto. rewrite -Heq fill_app /= //.\n    - (* wand L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          eapply BI_Wand_L; eauto.\n          eapply IHproves; eauto; first lia.\n          by apply bunch_decomp_correct.\n        * exfalso. inversion H5.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Wand_L; eauto.\n        rewrite -HC0.\n        eapply IHproves; eauto; first lia.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* bot L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_False_L.\n    - (* top R *) apply BI_True_R.\n    - (* top L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_True_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* conjR *)\n      apply bunch_decomp_complete in Heq.\n      inversion Heq; simplify_eq/=.\n      + rewrite fill_app /=.\n        eapply BI_Conj_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n      + rewrite fill_app /=.\n        eapply BI_Conj_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n    - (* conjL *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Conj_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* disj R 1 *)\n      eapply BI_Disj_R1.\n      eapply IHproves; eauto.\n    - (* disj R 2 *)\n      eapply BI_Disj_R2.\n      eapply IHproves; eauto.\n    - (* disj L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Disj_L.\n        * rewrite -HC0.\n          eapply IHproves; eauto; first lia.\n          apply bunch_decomp_correct. apply Hdec0.\n        * rewrite -HC0.\n          eapply IHproves; eauto; first lia.\n          apply bunch_decomp_correct. apply Hdec0.\n    - (* impl R *)\n      apply BI_Impl_R.\n      assert ((fill C (frml ϕ,, frml ψ);, frml ϕ0) =\n                   fill (C ++ [CtxSemicL (frml ϕ0)]) (frml ϕ,, frml ψ))%B as ->.\n      { rewrite fill_app//. }\n      eapply IHproves; eauto. rewrite -Heq fill_app /= //.\n    -       apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          eapply BI_Impl_L; eauto.\n          eapply IHproves; eauto; first lia.\n          by apply bunch_decomp_correct.\n        * exfalso. inversion H5.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Impl_L; eauto.\n        rewrite -HC0.\n        eapply IHproves; eauto; first lia.\n        apply bunch_decomp_correct. apply Hdec0.\n  Qed.\n\n  Lemma conj_l_inv' Δ C ϕ ψ χ n :\n    (Δ ⊢ᴮ{n} χ) →\n    Δ = fill C (frml (CONJ ϕ ψ)) →\n    (fill C (frml ϕ;, frml ψ) ⊢ᴮ{n} χ).\n  Proof.\n    revert C Δ χ.\n    induction n using lt_wf_ind. rename H into IHproves.\n    intros C Δ χ PROOF Heq. symmetry in Heq. revert Heq.\n    inversion PROOF; simplify_eq/= => Heq.\n    (* induction H => C' Heq; symmetry in Heq. *)\n    - (* raising the pf height *)\n      apply BI_Higher.\n      eapply IHproves; eauto.\n    - (* axiom *)\n      apply fill_is_frml in Heq. destruct_and!; simplify_eq/=.\n      (* eapply BI_Sep_R; by econstructor. *)\n    - (* equivalence of bunches *)\n      simplify_eq/=.\n      destruct (bunch_equiv_fill _ _ _ H) as [C2 [-> HC2]].\n      eapply BI_Equiv.\n      { apply HC2. }\n      eapply IHproves; eauto.\n    - (* weakening *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          apply BI_Weaken.\n          rewrite -fill_app.\n          eapply IHproves; eauto.\n          by apply bunch_decomp_correct, bunch_decomp_app.\n        * rewrite !fill_app/=.\n          by apply BI_Weaken.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Weaken.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* contraction *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2]; last first.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Contr.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n      + rename C0 into C'.\n        destruct H1 as [C0 [HC0 ->]].\n        apply bunch_decomp_correct in HC0.\n        simplify_eq/=.\n        assert (fill C' (fill C0 (frml ϕ;, frml ψ);, fill C0 (frml (CONJ ϕ ψ))) ⊢ᴮ{ n0} χ) as IH1.\n        { specialize (IHproves n0 (lt_n_Sn _)).\n          set (C2 := (C0 ++ [CtxSemicL (fill C0 (frml (CONJ ϕ ψ)))] ++ C')%B).\n          specialize (IHproves C2 _ _ H).\n          revert IHproves. rewrite /C2 !fill_app /=.\n          eauto. }\n        rewrite fill_app.\n        apply BI_Contr.\n        set (C2 := (C0 ++ [CtxSemicR (fill C0 (frml ϕ;, frml ψ))] ++ C')%B).\n        replace (fill C' (fill C0 (frml ϕ;, frml ψ);, fill C0 (frml ϕ;, frml ψ)))%B\n                   with (fill C2 (frml ϕ;, frml ψ))%B by rewrite fill_app//.\n        eapply IHproves; eauto.\n        rewrite /C2 fill_app//.\n    - (* ext *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2]; last first.\n      + destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        eapply BI_Simple_Ext; eauto.\n        intros Ti Hi.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n      + destruct H1 as [C0 [HC0 ->]].\n        apply bunch_decomp_correct in HC0.\n        simplify_eq/=.\n        apply bterm_ctx_act_decomp in HC0; last first.\n        { by eapply (rules_good (Ts,T)). }\n        destruct HC0 as (j & Π₀ & Hjfv & Hj & HC0).\n        rewrite fill_app -HC0.\n        eapply BI_Simple_Ext; eauto.\n        revert Hj Hjfv IHproves H0.\n        clear.\n        intros Hj Hjfv IHproves Hpfs.\n        intros Ti HTi. specialize (Hpfs Ti HTi).\n        revert Π Hpfs. clear HTi.\n        induction Ti=>Π Hpfs.\n        { simpl.\n          destruct (decide (j = x)) as [->|?].\n          - rewrite functions.fn_lookup_insert.\n            rewrite -fill_app.\n            eapply IHproves; eauto.\n            by rewrite fill_app -Hj.\n          - rewrite functions.fn_lookup_insert_ne; auto. }\n        { simpl.\n          assert (fill ([CtxCommaL (bterm_ctx_act Ti2 Δs)]++Π) (bterm_ctx_act Ti1 (<[j:=fill Π₀ (frml ϕ;, frml ψ)]> Δs)) ⊢ᴮ{ n0} χ) as HH1.\n          { eapply IHTi1. rewrite fill_app /=. eauto. }\n          rewrite fill_app in HH1.\n          simpl in HH1.\n          replace\n          (fill Π (bterm_ctx_act Ti1\n             (<[j:=fill Π₀ (frml ϕ;, frml ψ)]> Δs),,bterm_ctx_act Ti2 (<[j:=fill Π₀ (frml ϕ;, frml ψ)]> Δs)))%B\n            with\n          (fill ([CtxCommaR (bterm_ctx_act Ti1 (<[j:=fill Π₀ (frml ϕ;, frml ψ)]> Δs))]++Π)\n                (bterm_ctx_act Ti2 (<[j:=fill Π₀ (frml ϕ;, frml ψ)]> Δs)))%B\n            by rewrite fill_app//.\n          eapply IHTi2.\n          rewrite fill_app/=//. }\n        { simpl.\n          assert (fill ([CtxSemicL (bterm_ctx_act Ti2 Δs)]++Π) (bterm_ctx_act Ti1 (<[j:=fill Π₀ (frml ϕ;, frml ψ)]> Δs)) ⊢ᴮ{ n0} χ) as HH1.\n          { eapply IHTi1. rewrite fill_app /=. eauto. }\n          rewrite fill_app in HH1.\n          simpl in HH1.\n          replace\n          (fill Π (bterm_ctx_act Ti1\n             (<[j:=fill Π₀ (frml ϕ;, frml ψ)]> Δs);,bterm_ctx_act Ti2 (<[j:=fill Π₀ (frml ϕ;, frml ψ)]> Δs)))%B\n            with\n          (fill ([CtxSemicR (bterm_ctx_act Ti1 (<[j:=fill Π₀ (frml ϕ;, frml ψ)]> Δs))]++Π)\n                (bterm_ctx_act Ti2 (<[j:=fill Π₀ (frml ϕ;, frml ψ)]> Δs)))%B\n            by rewrite fill_app//.\n          eapply IHTi2.\n          rewrite fill_app/=//. }\n    - (* emp R *)\n      exfalso.\n      apply bunch_decomp_complete in Heq.\n      inversion Heq.\n    - (* emp L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Emp_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* sep R *)\n      apply bunch_decomp_complete in Heq.\n      inversion Heq; simplify_eq/=.\n      + rewrite fill_app /=.\n        eapply BI_Sep_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n      + rewrite fill_app /=.\n        eapply BI_Sep_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n    - (* sep L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Sep_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* wand R *)\n      apply BI_Wand_R.\n      assert ((fill C (frml ϕ;, frml ψ),, frml ϕ0) =\n                   fill (C ++ [CtxCommaL (frml ϕ0)]) (frml ϕ;, frml ψ))%B as ->.\n      { rewrite fill_app//. }\n      eapply IHproves; eauto. rewrite -Heq fill_app /= //.\n    - (* wand L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          eapply BI_Wand_L; eauto.\n          eapply IHproves; eauto; first lia.\n          by apply bunch_decomp_correct.\n        * exfalso. inversion H5.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Wand_L; eauto.\n        rewrite -HC0.\n        eapply IHproves; eauto; first lia.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* bot L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_False_L.\n    - (* top R *) apply BI_True_R.\n    - (* top L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_True_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* conjR *)\n      apply bunch_decomp_complete in Heq.\n      inversion Heq; simplify_eq/=.\n      + rewrite fill_app /=.\n        eapply BI_Conj_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n      + rewrite fill_app /=.\n        eapply BI_Conj_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n    - (* conjL *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        by apply BI_Higher.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Conj_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* disj R 1 *)\n      eapply BI_Disj_R1.\n      eapply IHproves; eauto.\n    - (* disj R 2 *)\n      eapply BI_Disj_R2.\n      eapply IHproves; eauto.\n    - (* disj L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Disj_L.\n        * rewrite -HC0.\n          eapply IHproves; eauto; first lia.\n          apply bunch_decomp_correct. apply Hdec0.\n        * rewrite -HC0.\n          eapply IHproves; eauto; first lia.\n          apply bunch_decomp_correct. apply Hdec0.\n    - (* impl R *)\n      apply BI_Impl_R.\n      assert ((fill C (frml ϕ;, frml ψ);, frml ϕ0) =\n                   fill (C ++ [CtxSemicL (frml ϕ0)]) (frml ϕ;, frml ψ))%B as ->.\n      { rewrite fill_app//. }\n      eapply IHproves; eauto. rewrite -Heq fill_app /= //.\n    -       apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          eapply BI_Impl_L; eauto.\n          eapply IHproves; eauto; first lia.\n          by apply bunch_decomp_correct.\n        * exfalso. inversion H5.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Impl_L; eauto.\n        rewrite -HC0.\n        eapply IHproves; eauto; first lia.\n        apply bunch_decomp_correct. apply Hdec0.\n  Qed.\n\n  Lemma top_l_inv' Δ C ϕ ψ χ n :\n    (Δ ⊢ᴮ{n} χ) →\n    Δ = fill C (frml TOP) →\n    (fill C top ⊢ᴮ{n} χ).\n  Proof.\n    revert C Δ χ.\n    induction n using lt_wf_ind. rename H into IHproves.\n    intros C Δ χ PROOF Heq. symmetry in Heq. revert Heq.\n    inversion PROOF; simplify_eq/= => Heq.\n    (* induction H => C' Heq; symmetry in Heq. *)\n    - (* raising the pf height *)\n      apply BI_Higher.\n      eapply IHproves; eauto.\n    - (* axiom *)\n      apply fill_is_frml in Heq. destruct_and!; simplify_eq/=.\n    - (* equivalence of bunches *)\n      simplify_eq/=.\n      destruct (bunch_equiv_fill _ _ _ H) as [C2 [-> HC2]].\n      eapply BI_Equiv.\n      { apply HC2. }\n      eapply IHproves; eauto.\n    - (* weakening *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          apply BI_Weaken.\n          rewrite -fill_app.\n          eapply IHproves; eauto.\n          by apply bunch_decomp_correct, bunch_decomp_app.\n        * rewrite !fill_app/=.\n          by apply BI_Weaken.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Weaken.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* contraction *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2]; last first.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Contr.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n      + rename C0 into C'.\n        destruct H1 as [C0 [HC0 ->]].\n        apply bunch_decomp_correct in HC0.\n        simplify_eq/=.\n        assert (fill C' (fill C0 top;, fill C0 (frml TOP)) ⊢ᴮ{ n0} χ) as IH1.\n        { specialize (IHproves n0 (lt_n_Sn _)).\n          set (C2 := (C0 ++ [CtxSemicL (fill C0 (frml TOP))] ++ C')%B).\n          specialize (IHproves C2 _ _ H).\n          revert IHproves. rewrite /C2 !fill_app /=.\n          eauto. }\n        rewrite fill_app.\n        apply BI_Contr.\n        set (C2 := (C0 ++ [CtxSemicR (fill C0 top)] ++ C')%B).\n        replace (fill C' (fill C0 top;, fill C0 top))%B\n                   with (fill C2 top)%B by rewrite fill_app//.\n        eapply IHproves; eauto.\n        rewrite /C2 fill_app//.\n    - (* ext *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2]; last first.\n      + destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        eapply BI_Simple_Ext; eauto.\n        intros Ti Hi.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n      + destruct H1 as [C0 [HC0 ->]].\n        apply bunch_decomp_correct in HC0.\n        simplify_eq/=.\n        apply bterm_ctx_act_decomp in HC0; last first.\n        { by eapply (rules_good (Ts, T)). }\n        destruct HC0 as (j & Π₀ & Hjfv & Hj & HC0).\n        rewrite fill_app -HC0.\n        eapply BI_Simple_Ext; eauto.\n        revert Hj Hjfv IHproves H0.\n        clear.\n        intros Hj Hjfv IHproves Hpfs.\n        intros Ti HTi. specialize (Hpfs Ti HTi).\n        revert Π Hpfs. clear HTi.\n        induction Ti=>Π Hpfs.\n        { simpl.\n          destruct (decide (j = x)) as [->|?].\n          - rewrite functions.fn_lookup_insert.\n            rewrite -fill_app.\n            eapply IHproves; eauto.\n            by rewrite fill_app -Hj.\n          - rewrite functions.fn_lookup_insert_ne; auto. }\n        { simpl.\n          assert (fill ([CtxCommaL (bterm_ctx_act Ti2 Δs)]++Π) (bterm_ctx_act Ti1 (<[j:=fill Π₀ top]> Δs)) ⊢ᴮ{ n0} χ) as HH1.\n          { eapply IHTi1. rewrite fill_app /=. eauto. }\n          rewrite fill_app in HH1.\n          simpl in HH1.\n          replace\n          (fill Π (bterm_ctx_act Ti1\n             (<[j:=fill Π₀ top]> Δs),,bterm_ctx_act Ti2 (<[j:=fill Π₀ top]> Δs)))%B\n            with\n          (fill ([CtxCommaR (bterm_ctx_act Ti1 (<[j:=fill Π₀ top]> Δs))]++Π)\n                (bterm_ctx_act Ti2 (<[j:=fill Π₀ top]> Δs)))%B\n            by rewrite fill_app//.\n          eapply IHTi2.\n          rewrite fill_app/=//. }\n        { simpl.\n          assert (fill ([CtxSemicL (bterm_ctx_act Ti2 Δs)]++Π) (bterm_ctx_act Ti1 (<[j:=fill Π₀ top]> Δs)) ⊢ᴮ{ n0} χ) as HH1.\n          { eapply IHTi1. rewrite fill_app /=. eauto. }\n          rewrite fill_app in HH1.\n          simpl in HH1.\n          replace\n          (fill Π (bterm_ctx_act Ti1\n             (<[j:=fill Π₀ top]> Δs);,bterm_ctx_act Ti2 (<[j:=fill Π₀ top]> Δs)))%B\n            with\n          (fill ([CtxSemicR (bterm_ctx_act Ti1 (<[j:=fill Π₀ top]> Δs))]++Π)\n                (bterm_ctx_act Ti2 (<[j:=fill Π₀ top]> Δs)))%B\n            by rewrite fill_app//.\n          eapply IHTi2.\n          rewrite fill_app/=//. }\n    - (* emp R *)\n      exfalso.\n      apply bunch_decomp_complete in Heq.\n      inversion Heq.\n    - (* emp L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Emp_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* sep R *)\n      apply bunch_decomp_complete in Heq.\n      inversion Heq; simplify_eq/=.\n      + rewrite fill_app /=.\n        eapply BI_Sep_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n      + rewrite fill_app /=.\n        eapply BI_Sep_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n    - (* sep L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Sep_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* wand R *)\n      apply BI_Wand_R.\n      assert ((fill C top,, frml ϕ0) =\n                   fill (C ++ [CtxCommaL (frml ϕ0)]) top)%B as ->.\n      { rewrite fill_app//. }\n      eapply IHproves; eauto. rewrite -Heq fill_app /= //.\n    - (* wand L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          eapply BI_Wand_L; eauto.\n          eapply IHproves; eauto; first lia.\n          by apply bunch_decomp_correct.\n        * exfalso. inversion H5.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Wand_L; eauto.\n        rewrite -HC0.\n        eapply IHproves; eauto; first lia.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* bot L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_False_L.\n    - (* top R *) apply BI_True_R.\n    - (* top L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        by eapply BI_Higher.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_True_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* conjR *)\n      apply bunch_decomp_complete in Heq.\n      inversion Heq; simplify_eq/=.\n      + rewrite fill_app /=.\n        eapply BI_Conj_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n      + rewrite fill_app /=.\n        eapply BI_Conj_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n    - (* conjL *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Conj_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* disj R 1 *)\n      eapply BI_Disj_R1.\n      eapply IHproves; eauto.\n    - (* disj R 2 *)\n      eapply BI_Disj_R2.\n      eapply IHproves; eauto.\n    - (* disj L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Disj_L.\n        * rewrite -HC0.\n          eapply IHproves; eauto; first lia.\n          apply bunch_decomp_correct. apply Hdec0.\n        * rewrite -HC0.\n          eapply IHproves; eauto; first lia.\n          apply bunch_decomp_correct. apply Hdec0.\n    - (* impl R *)\n      apply BI_Impl_R.\n      assert ((fill C top;, frml ϕ0) =\n                   fill (C ++ [CtxSemicL (frml ϕ0)]) top)%B as ->.\n      { rewrite fill_app//. }\n      eapply IHproves; eauto. rewrite -Heq fill_app /= //.\n    -       apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          eapply BI_Impl_L; eauto.\n          eapply IHproves; eauto; first lia.\n          by apply bunch_decomp_correct.\n        * exfalso. inversion H5.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Impl_L; eauto.\n        rewrite -HC0.\n        eapply IHproves; eauto; first lia.\n        apply bunch_decomp_correct. apply Hdec0.\n  Qed.\n\n  Lemma emp_l_inv' Δ C ϕ ψ χ n :\n    (Δ ⊢ᴮ{n} χ) →\n    Δ = fill C (frml EMP) →\n    (fill C empty ⊢ᴮ{n} χ).\n  Proof.\n    revert C Δ χ.\n    induction n using lt_wf_ind. rename H into IHproves.\n    intros C Δ χ PROOF Heq. symmetry in Heq. revert Heq.\n    inversion PROOF; simplify_eq/= => Heq.\n    (* induction H => C' Heq; symmetry in Heq. *)\n    - (* raising the pf height *)\n      apply BI_Higher.\n      eapply IHproves; eauto.\n    - (* axiom *)\n      apply fill_is_frml in Heq. destruct_and!; simplify_eq/=.\n    - (* equivalence of bunches *)\n      simplify_eq/=.\n      destruct (bunch_equiv_fill _ _ _ H) as [C2 [-> HC2]].\n      eapply BI_Equiv.\n      { apply HC2. }\n      eapply IHproves; eauto.\n    - (* weakening *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          apply BI_Weaken.\n          rewrite -fill_app.\n          eapply IHproves; eauto.\n          by apply bunch_decomp_correct, bunch_decomp_app.\n        * rewrite !fill_app/=.\n          by apply BI_Weaken.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Weaken.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* contraction *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2]; last first.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Contr.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n      + rename C0 into C'.\n        destruct H1 as [C0 [HC0 ->]].\n        apply bunch_decomp_correct in HC0.\n        simplify_eq/=.\n        assert (fill C' (fill C0 empty;, fill C0 (frml EMP)) ⊢ᴮ{ n0} χ) as IH1.\n        { specialize (IHproves n0 (lt_n_Sn _)).\n          set (C2 := (C0 ++ [CtxSemicL (fill C0 (frml EMP))] ++ C')%B).\n          specialize (IHproves C2 _ _ H).\n          revert IHproves. rewrite /C2 !fill_app /=.\n          eauto. }\n        rewrite fill_app.\n        apply BI_Contr.\n        set (C2 := (C0 ++ [CtxSemicR (fill C0 empty)] ++ C')%B).\n        replace (fill C' (fill C0 empty;, fill C0 empty))%B\n                   with (fill C2 empty)%B by rewrite fill_app//.\n        eapply IHproves; eauto.\n        rewrite /C2 fill_app//.\n    - (* ext *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2]; last first.\n      + destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        eapply BI_Simple_Ext; eauto.\n        intros Ti Hi.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n      + destruct H1 as [C0 [HC0 ->]].\n        apply bunch_decomp_correct in HC0.\n        simplify_eq/=.\n        apply bterm_ctx_act_decomp in HC0; last first.\n        { by eapply (rules_good (Ts,T)). }\n        destruct HC0 as (j & Π₀ & Hjfv & Hj & HC0).\n        rewrite fill_app -HC0.\n        eapply BI_Simple_Ext; eauto.\n        revert Hj Hjfv IHproves H0.\n        clear.\n        intros Hj Hjfv IHproves Hpfs.\n        intros Ti HTi. specialize (Hpfs Ti HTi).\n        revert Π Hpfs. clear HTi.\n        induction Ti=>Π Hpfs.\n        { simpl.\n          destruct (decide (j = x)) as [->|?].\n          - rewrite functions.fn_lookup_insert.\n            rewrite -fill_app.\n            eapply IHproves; eauto.\n            by rewrite fill_app -Hj.\n          - rewrite functions.fn_lookup_insert_ne; auto. }\n        { simpl.\n          assert (fill ([CtxCommaL (bterm_ctx_act Ti2 Δs)]++Π) (bterm_ctx_act Ti1 (<[j:=fill Π₀ empty]> Δs)) ⊢ᴮ{ n0} χ) as HH1.\n          { eapply IHTi1. rewrite fill_app /=. eauto. }\n          rewrite fill_app in HH1.\n          simpl in HH1.\n          replace\n          (fill Π (bterm_ctx_act Ti1\n             (<[j:=fill Π₀ empty]> Δs),,bterm_ctx_act Ti2 (<[j:=fill Π₀ empty]> Δs)))%B\n            with\n          (fill ([CtxCommaR (bterm_ctx_act Ti1 (<[j:=fill Π₀ empty]> Δs))]++Π)\n                (bterm_ctx_act Ti2 (<[j:=fill Π₀ empty]> Δs)))%B\n            by rewrite fill_app//.\n          eapply IHTi2.\n          rewrite fill_app/=//. }\n        { simpl.\n          assert (fill ([CtxSemicL (bterm_ctx_act Ti2 Δs)]++Π) (bterm_ctx_act Ti1 (<[j:=fill Π₀ empty]> Δs)) ⊢ᴮ{ n0} χ) as HH1.\n          { eapply IHTi1. rewrite fill_app /=. eauto. }\n          rewrite fill_app in HH1.\n          simpl in HH1.\n          replace\n          (fill Π (bterm_ctx_act Ti1\n             (<[j:=fill Π₀ empty]> Δs);,bterm_ctx_act Ti2 (<[j:=fill Π₀ empty]> Δs)))%B\n            with\n          (fill ([CtxSemicR (bterm_ctx_act Ti1 (<[j:=fill Π₀ empty]> Δs))]++Π)\n                (bterm_ctx_act Ti2 (<[j:=fill Π₀ empty]> Δs)))%B\n            by rewrite fill_app//.\n          eapply IHTi2.\n          rewrite fill_app/=//. }\n    - (* emp R *)\n      exfalso.\n      apply bunch_decomp_complete in Heq.\n      inversion Heq.\n    - (* emp L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        by eapply BI_Higher.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Emp_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* sep R *)\n      apply bunch_decomp_complete in Heq.\n      inversion Heq; simplify_eq/=.\n      + rewrite fill_app /=.\n        eapply BI_Sep_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n      + rewrite fill_app /=.\n        eapply BI_Sep_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n    - (* sep L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Sep_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* wand R *)\n      apply BI_Wand_R.\n      assert ((fill C empty,, frml ϕ0) =\n                   fill (C ++ [CtxCommaL (frml ϕ0)]) empty)%B as ->.\n      { rewrite fill_app//. }\n      eapply IHproves; eauto. rewrite -Heq fill_app /= //.\n    - (* wand L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          eapply BI_Wand_L; eauto.\n          eapply IHproves; eauto; first lia.\n          by apply bunch_decomp_correct.\n        * exfalso. inversion H5.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Wand_L; eauto.\n        rewrite -HC0.\n        eapply IHproves; eauto; first lia.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* bot L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_False_L.\n    - (* true R *) apply BI_True_R.\n    - (* true L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_True_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* conjR *)\n      apply bunch_decomp_complete in Heq.\n      inversion Heq; simplify_eq/=.\n      + rewrite fill_app /=.\n        eapply BI_Conj_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n      + rewrite fill_app /=.\n        eapply BI_Conj_R; eauto.\n        eapply IHproves; eauto; first lia.\n        by apply bunch_decomp_correct.\n    - (* conjL *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Conj_L.\n        rewrite -HC0.\n        eapply IHproves; eauto.\n        apply bunch_decomp_correct. apply Hdec0.\n    - (* disj R 1 *)\n      eapply BI_Disj_R1.\n      eapply IHproves; eauto.\n    - (* disj R 2 *)\n      eapply BI_Disj_R2.\n      eapply IHproves; eauto.\n    - (* disj L *)\n      apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n      + destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Disj_L.\n        * rewrite -HC0.\n          eapply IHproves; eauto; first lia.\n          apply bunch_decomp_correct. apply Hdec0.\n        * rewrite -HC0.\n          eapply IHproves; eauto; first lia.\n          apply bunch_decomp_correct. apply Hdec0.\n    - (* impl R *)\n      apply BI_Impl_R.\n      assert ((fill C empty;, frml ϕ0) =\n                   fill (C ++ [CtxSemicL (frml ϕ0)]) empty)%B as ->.\n      { rewrite fill_app//. }\n      eapply IHproves; eauto. rewrite -Heq fill_app /= //.\n    -       apply bunch_decomp_complete in Heq.\n      apply bunch_decomp_ctx in Heq.\n      destruct Heq as [H1 | H2].\n      + destruct H1 as [C1 [HC0 HC]].\n        inversion HC0; simplify_eq/=.\n        * rewrite !fill_app/=.\n          eapply BI_Impl_L; eauto.\n          eapply IHproves; eauto; first lia.\n          by apply bunch_decomp_correct.\n        * exfalso. inversion H5.\n      + rename C0 into C'.\n        destruct H2 as (C0 & C1 & HC0 & HC1 & Hdec0).\n        rewrite -HC1.\n        apply BI_Impl_L; eauto.\n        rewrite -HC0.\n        eapply IHproves; eauto; first lia.\n        apply bunch_decomp_correct. apply Hdec0.\n  Qed.\n\n  (** Derivable rules / inversion lemmas *)\n  Lemma impl_r_inv Δ ϕ ψ :\n    (Δ ⊢ᴮ IMPL ϕ ψ) →\n    (Δ ;, frml ϕ ⊢ᴮ ψ)%B.\n  Proof.\n    intros [n H]%proves_provesN.\n    eapply provesN_proves.\n    by apply impl_r_inv'.\n  Qed.\n  Lemma wand_r_inv Δ ϕ ψ :\n    (Δ ⊢ᴮ WAND ϕ ψ) →\n    (Δ ,, frml ϕ ⊢ᴮ ψ)%B.\n  Proof.\n    intros [n H]%proves_provesN.\n    eapply provesN_proves.\n    by apply wand_r_inv'.\n  Qed.\n  Lemma sep_l_inv C ϕ ψ χ :\n    (fill C (frml (SEP ϕ ψ)) ⊢ᴮ χ) →\n    (fill C (frml ϕ,, frml ψ) ⊢ᴮ χ).\n  Proof.\n    intros [n H]%proves_provesN.\n    eapply provesN_proves.\n    eapply sep_l_inv'; eauto.\n  Qed.\n  Lemma conj_l_inv C ϕ ψ χ :\n    (fill C (frml (CONJ ϕ ψ)) ⊢ᴮ χ) →\n    (fill C (frml ϕ;, frml ψ) ⊢ᴮ χ).\n  Proof.\n    intros [n H]%proves_provesN.\n    eapply provesN_proves.\n    eapply conj_l_inv'; eauto.\n  Qed.\n  Lemma collapse_l_inv C Δ ϕ :\n    (fill C (frml (collapse Δ)) ⊢ᴮ ϕ) →\n    (fill C Δ ⊢ᴮ ϕ).\n  Proof.\n    revert C. induction Δ; simpl; first done.\n    - intros C [n H]%proves_provesN.\n      eapply provesN_proves.\n      eapply top_l_inv'; eauto.\n    - intros C [n H]%proves_provesN.\n      eapply provesN_proves.\n      eapply emp_l_inv'; eauto.\n    - intros C H1.\n      replace (fill C (Δ1,, Δ2))%B\n        with (fill (CtxCommaR Δ1::C) Δ2) by reflexivity.\n      apply IHΔ2. simpl.\n      replace (fill C (Δ1,, frml (collapse Δ2)))%B\n        with (fill (CtxCommaL (frml (collapse Δ2))::C) Δ1) by reflexivity.\n      apply IHΔ1. simpl.\n      by apply sep_l_inv.\n    - intros C H1.\n      replace (fill C (Δ1;, Δ2))%B\n        with (fill (CtxSemicR Δ1::C) Δ2) by reflexivity.\n      apply IHΔ2. simpl.\n      replace (fill C (Δ1;, frml (collapse Δ2)))%B\n        with (fill (CtxSemicL (frml (collapse Δ2))::C) Δ1) by reflexivity.\n      apply IHΔ1. simpl.\n      by apply conj_l_inv.\n  Qed.\nEnd SeqcalcHeight.\n", "meta": {"author": "co-dan", "repo": "BI-cutelim", "sha": "cfbabc61a7a4b4c7e5bc7bb873fea4257949a76f", "save_path": "github-repos/coq/co-dan-BI-cutelim", "path": "github-repos/coq/co-dan-BI-cutelim/BI-cutelim-cfbabc61a7a4b4c7e5bc7bb873fea4257949a76f/theories/seqcalc_height.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765155565327, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.2679218876201256}}
{"text": "Require Import Min.\n\nRequire Import msl.msl_standard.\nRequire Import Maps.\nRequire Import FuncListMachine.\nRequire Import lemmas.\nRequire Import hoare_total.\n\nOpen Scope pred.\n\nSection estep.\n  Variable X:Type.\n  Variable x:X.\n\n  Inductive estep : program X -> store -> list (instr X) -> store -> list (instr X) -> Prop :=\n\n  | estep_assert : forall p r i stk (P:X),\n    (*----------------------------------------------------*)\n      estep p r ((instr_assert P ;; i) :: stk) r (i :: stk)\n\n  | estep_getlabel: forall p r l v i stk,\n    (*----------------------------------------------------*)\n      estep p r ((instr_getlabel l v ;; i) :: stk) (r#v <- (value_label l)) (i :: stk)\n\n  | estep_fetch_field_0: forall p r v1 v2 i a0 a1 stk,\n      r#v1 = Some (value_cons a0 a1) ->\n    (*----------------------------------------------------*)\n      estep p r ((instr_fetch_field v1 0 v2 ;; i) :: stk) (r#v2 <- a0) (i :: stk)\n\n  | estep_fetch_field_1: forall p r v1 v2 i a0 a1 stk,\n      r#v1 = Some (value_cons a0 a1) ->\n    (*----------------------------------------------------*)\n      estep p r ((instr_fetch_field v1 1 v2 ;; i) :: stk) (r#v2 <- a1) (i :: stk)\n\n  | estep_cons: forall p r v1 v2 v3 i a1 a2 stk,\n      r#v1 = Some a1 ->\n      r#v2 = Some a2 ->\n    (*----------------------------------------------------*)\n      estep p r ((instr_cons v1 v2 v3 ;; i) :: stk) (r#v3 <- (value_cons a1 a2)) (i :: stk)\n\n  | estep_seq: forall p r i1 i2 i3 stk,\n    (*----------------------------------------------------*)\n      estep p r (((i1 ;; i2) ;; i3) :: stk) r ((i1 ;; i2 ;; i3) :: stk)\n\n  | estep_if_nil1 : forall p r v i1 i2 i stk,\n      r#v = Some (value_label (L 0)) ->\n    (*----------------------------------------------------*)\n      estep p r ((instr_if_nil v i1 i2 ;; i) :: stk) r ((i1 ;; i) :: stk)\n\n  | estep_if_nil2 : forall p r v i1 i2 i a1 a2 stk,\n      r#v = Some (value_cons a1 a2) ->\n    (*----------------------------------------------------*)\n      estep p r ((instr_if_nil v i1 i2 ;; i) :: stk) r ((i2 ;; i) :: stk)\n\n  | estep_call : forall p r v l i i' stk,\n      r#v = Some (value_label l) ->\n      p#l = Some i' ->\n    (*----------------------------------------------------*)\n      estep p r ((instr_call v ;; i) :: stk) r ((i' ;; instr_assert x) :: i :: stk)\n\n  | estep_return : forall p r stk i,\n    (*----------------------------------------------------*)\n      estep p r ((instr_return ;; i) :: stk) r stk.\n\n\n  Inductive estepstar : program X -> store -> list (instr X) -> store -> list (instr X) ->  Prop :=\n  | estepstar_O: forall p s i, estepstar p s i s i\n  | estepstar_S: forall p s i s' i' s'' i'',\n              estep p s i s' i' ->\n              estepstar p s' i' s'' i'' ->\n              estepstar p s i s'' i''.\n\n  Definition eventually_ehalts (p:program X) (r:store) (s:list (instr X)) : Prop :=\n    exists r', estepstar p r s r' nil.\n\n  Definition erase_instr : instruction -> instr X :=\n    fmap_instr (fun _ => x).\n\n  Definition erase_prog := map_fmap _ _ erase_instr.\n\n  Theorem erase_step : forall p p' n r r' s s',\n    step (K.squash (n,p)) p' r s r' s' ->\n    estep (erase_prog p) r (List.map erase_instr s) r' (List.map erase_instr s') /\\\n    exists n', p' = K.squash (n',p).\n  Proof.\n    intros.\n    inv H; unfold erase_instr; simpl in *;\n      try (split; econstructor; eauto; fail).\n    split.\n    eapply estep_call; eauto.\n    unfold prog_lookup in H1.\n    rewrite K.unsquash_squash in H1.\n    simpl in H1.\n    unfold KnotInput.fmap in H1.\n    eapply fmap_eqn2 in H1.\n    destruct H1 as [i'' [? ?]].\n    unfold erase_prog.\n    erewrite fmap_eqn.\n    2: eauto.\n    f_equal.\n    subst i'.\n    clear.\n    unfold erase_instr.\n    induction i''; simpl; congruence.\n    hnf in H2.\n    rewrite K.knot_age1 in H2.\n    rewrite K.unsquash_squash in H2.\n    destruct n; try discriminate.\n    inv H2.\n    exists n.\n    apply K.unsquash_inj.\n    repeat rewrite K.unsquash_squash.\n    f_equal.\n    rewrite K.fmap_fmap.\n    change (S n) with (1 +n).\n    rewrite <- K.approx_approx1.\n    auto.\n  Qed.\n\n  Lemma erase_halt' : forall n p p' r r' s,\n    stepstar (K.squash (n,p)) p' r s r' nil ->\n    estepstar (erase_prog p) r (List.map erase_instr s) r' nil.\n  Proof.\n    intros.\n    remember (K.squash (n,p)) as phat.\n    remember (@nil instruction) as s'.\n    revert Heqphat Heqs'.\n    revert n.\n    induction H; intros.\n    subst i.\n    simpl.\n    econstructor.\n    subst.\n    apply erase_step in H.\n    destruct H.\n    destruct H1.\n    subst p'.\n    spec IHstepstar x0.\n    spec IHstepstar; auto.\n    spec IHstepstar; auto.\n    eapply estepstar_S; eauto.\n  Qed.\n\n  Theorem erase_halt : forall p n r s,\n    eventually_halts (K.squash (n,p)) r s ->\n    eventually_ehalts (erase_prog p) r (List.map erase_instr s).\n  Proof.\n    intros. hnf in H. hnf.\n    destruct H as [p' [r' ?]].\n    exists r'.\n    eapply erase_halt'; eauto.\n  Qed.\n\n  Theorem total_correctness_full_erasure : forall G psi l t c r n,\n    verify_prog psi G ->\n    G |-- funptr l unit t (fun _ => TT) (fun _ => TT) ->\n    proj1_sig t r n ->\n    psi#l = Some c ->\n    eventually_ehalts (erase_prog psi) r ((erase_instr c ;; instr_assert x) :: nil).\n  Proof.\n    intros.\n    generalize (verify_halts t G psi l H H0 r n c H1 H2).\n    apply erase_halt.\n  Qed.\n\nEnd estep.\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/erase.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765155565327, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.26792188762012553}}
{"text": "From iris.algebra Require Import proofmode_classes.\nFrom iris.base_logic Require Export derived.\nFrom iris Require Import options.\n\nImport base_logic.bi.uPred.\n\n(* Setup of the proof mode *)\nSection class_instances.\nContext {M : ucmraT}.\nImplicit Types P Q R : uPred M.\n\nGlobal Instance into_pure_cmra_valid `{!CmraDiscrete A} (a : A) :\n  @IntoPure (uPredI M) (✓ a) (✓ a).\nProof. by rewrite /IntoPure discrete_valid. Qed.\n\nGlobal Instance from_pure_cmra_valid {A : cmraT} (a : A) :\n  @FromPure (uPredI M) false (✓ a) (✓ a).\nProof.\n  rewrite /FromPure /=. eapply bi.pure_elim=> // ?.\n  rewrite -uPred.cmra_valid_intro //.\nQed.\n\nGlobal Instance from_sep_ownM (a b1 b2 : M) :\n  IsOp a b1 b2 →\n  FromSep (uPred_ownM a) (uPred_ownM b1) (uPred_ownM b2).\nProof. intros. by rewrite /FromSep -ownM_op -is_op. Qed.\nGlobal Instance from_sep_ownM_core_id (a b1 b2 : M) :\n  IsOp a b1 b2 → TCOr (CoreId b1) (CoreId b2) →\n  FromAnd (uPred_ownM a) (uPred_ownM b1) (uPred_ownM b2).\nProof.\n  intros ? H. rewrite /FromAnd (is_op a) ownM_op.\n  destruct H; by rewrite bi.persistent_and_sep.\nQed.\n\nGlobal Instance into_and_ownM p (a b1 b2 : M) :\n  IsOp a b1 b2 → IntoAnd p (uPred_ownM a) (uPred_ownM b1) (uPred_ownM b2).\nProof.\n  intros. apply bi.intuitionistically_if_mono. by rewrite (is_op a) ownM_op bi.sep_and.\nQed.\n\nGlobal Instance into_sep_ownM (a b1 b2 : M) :\n  IsOp a b1 b2 → IntoSep (uPred_ownM a) (uPred_ownM b1) (uPred_ownM b2).\nProof. intros. by rewrite /IntoSep (is_op a) ownM_op. Qed.\nEnd class_instances.\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/proofmode.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2679218876201255}}
{"text": "(*\n * Vericert: Verified high-level synthesis.\n * Copyright (C) 2020 Yann Herklotz <yann@yannherklotz.com>\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 <https://www.gnu.org/licenses/>.\n *)\n\n(* begin hide *)\nFrom Coq Require Import ZArith.ZArith FSets.FMapPositive Lia.\nFrom compcert Require Import lib.Integers common.Values.\nFrom vericert Require Import Vericertlib.\n(* end hide *)\n\n(*|\n=====\nValue\n=====\n\nA ``value`` is a bitvector with a specific size. We are using the implementation\nof the bitvector by mit-plv/bbv, because it has many theorems that we can reuse.\nHowever, we need to wrap it with an ``Inductive`` so that we can specify and\nmatch on the size of the ``value``. This is necessary so that we can easily\nstore ``value`` of different sizes in a list or in a map.\n\nUsing the default ``word``, this would not be possible, as the size is part of\nthe type.\n|*)\n\nDefinition value : Type := int.\n\n(*|\nValue conversions\n=================\n\nVarious conversions to different number types such as ``N``, ``Z``, ``positive``\nand ``int``, where the last one is a theory of integers of powers of 2 in\nCompCert.\n|*)\n\nDefinition valueToNat (v : value) : nat :=\n  Z.to_nat (Int.unsigned v).\n\nDefinition natToValue (n : nat) : value :=\n  Int.repr (Z.of_nat n).\n\nDefinition valueToN (v : value) : N :=\n  Z.to_N (Int.unsigned v).\n\nDefinition NToValue (n : N) : value :=\n  Int.repr (Z.of_N n).\n\nDefinition ZToValue (z : Z) : value :=\n  Int.repr z.\n\nDefinition valueToZ (v : value) : Z :=\n  Int.signed v.\n\nDefinition uvalueToZ (v : value) : Z :=\n  Int.unsigned v.\n\nDefinition posToValue (p : positive) : value :=\n  Int.repr (Z.pos p).\n\nDefinition valueToPos (v : value) : positive :=\n  Z.to_pos (Int.unsigned v).\n\nDefinition intToValue (i : Integers.int) : value := i.\n\nDefinition valueToInt (i : value) : Integers.int := i.\n\nDefinition ptrToValue (i : ptrofs) : value := Ptrofs.to_int i.\n\nDefinition valueToPtr (i : value) : Integers.ptrofs :=\n  Ptrofs.of_int i.\n\nDefinition valToValue (v : Values.val) : option value :=\n  match v with\n  | Values.Vint i => Some (intToValue i)\n  | Values.Vptr b off => Some (ptrToValue off)\n  | Values.Vundef => Some (ZToValue 0%Z)\n  | _ => None\n  end.\n\n(*|\nConvert a ``value`` to a ``bool``, so that choices can be made based on the\nresult. This is also because comparison operators will give back ``value``\ninstead of ``bool``, so if they are in a condition, they will have to be\nconverted before they can be used.\n|*)\n\nDefinition valueToBool (v : value) : bool :=\n  if Z.eqb (uvalueToZ v) 0 then false else true.\n\nDefinition boolToValue (b : bool) : value :=\n  natToValue (if b then 1 else 0).\n\n(*|\nArithmetic operations\n---------------------\n|*)\n\nInductive val_value_lessdef: val -> value -> Prop :=\n| val_value_lessdef_int:\n    forall i v',\n    i = valueToInt v' ->\n    val_value_lessdef (Vint i) v'\n| val_value_lessdef_ptr:\n    forall b off v',\n    off = valueToPtr v' ->\n    val_value_lessdef (Vptr b off) v'\n| lessdef_undef: forall v, val_value_lessdef Vundef v.\n\nInductive opt_val_value_lessdef: option val -> value -> Prop :=\n| opt_lessdef_some:\n    forall v v', val_value_lessdef v v' -> opt_val_value_lessdef (Some v) v'\n| opt_lessdef_none: forall v, opt_val_value_lessdef None v.\n\nLemma valueToZ_ZToValue :\n  forall z,\n  (Int.min_signed <= z <= Int.max_signed)%Z ->\n  valueToZ (ZToValue z) = z.\nProof. auto using Int.signed_repr. Qed.\n\nLemma uvalueToZ_ZToValue :\n  forall z,\n  (0 <= z <= Int.max_unsigned)%Z ->\n  uvalueToZ (ZToValue z) = z.\nProof. auto using Int.unsigned_repr. Qed.\n\nLemma valueToPos_posToValue :\n  forall v,\n  0 <= Z.pos v <= Int.max_unsigned ->\n  valueToPos (posToValue v) = v.\nProof.\n  unfold valueToPos, posToValue.\n  intros. rewrite Int.unsigned_repr.\n  apply Pos2Z.id. assumption.\nQed.\n\nLemma valueToInt_intToValue :\n  forall v,\n  valueToInt (intToValue v) = v.\nProof. auto. Qed.\n\nLemma valToValue_lessdef :\n  forall v v',\n    valToValue v = Some v' ->\n    val_value_lessdef v v'.\nProof.\n  intros.\n  destruct v; try discriminate; constructor.\n  unfold valToValue in H. inversion H.\n  unfold valueToInt. unfold intToValue in H1. auto.\n  inv H. symmetry. unfold valueToPtr, ptrToValue. apply Ptrofs.of_int_to_int. trivial.\nQed.\n\nLtac simplify_val := repeat (simplify; unfold uvalueToZ, valueToPtr, Ptrofs.of_int, valueToInt, intToValue,\n                                       ptrToValue in *).\n\nLtac crush_val := simplify_val; try discriminate; try congruence; try lia; liapp; try assumption.\n", "meta": {"author": "ymherklotz", "repo": "vericert", "sha": "c3de945fa463aa9a2ad0804eb8f67e40f585eb3a", "save_path": "github-repos/coq/ymherklotz-vericert", "path": "github-repos/coq/ymherklotz-vericert/vericert-c3de945fa463aa9a2ad0804eb8f67e40f585eb3a/src/hls/ValueInt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.267921880628352}}
{"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 AST.\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 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": "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/Renumber.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.4765796510636759, "lm_q1q2_score": 0.2679218806283519}}
{"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\nRequire Export cequiv.\n\nLemma bcequiv_refl {o} :\n  forall lib (b : @BTerm o),\n    wf_bterm b\n    -> bcequiv lib b b.\nProof.\n  introv wf.\n  destruct b as [l t].\n  allrw @wf_bterm_iff.\n  apply blift_approx_cequiv.\n  - unfold approx_open_bterm, blift.\n    exists l t t; dands; eauto 3 with slow.\n  - unfold approx_open_bterm, blift.\n    exists l t t; dands; eauto 3 with slow.\nQed.\n\nLemma bcequiv_nobnd {o} :\n  forall lib (t u : @NTerm o),\n    wf_term t\n    -> wf_term u\n    -> cequiv lib t u\n    -> bcequiv lib (nobnd t) (nobnd u).\nProof.\n  introv wft wfu ceq.\n  applydup @cequiv_sym in ceq.\n  apply cequiv_le_approx in ceq.\n  apply cequiv_le_approx in ceq0.\n  apply blift_approx_cequiv.\n  - unfold approx_open_bterm, blift.\n    exists ([] : list NVar) t u; dands; eauto 3 with slow.\n    apply approx_implies_approx_open; auto.\n  - unfold approx_open_bterm, blift.\n    exists ([] : list NVar) u t; dands; eauto 3 with slow.\n    apply approx_implies_approx_open; auto.\nQed.\n\n\n(*\n*** Local Variables:\n*** coq-load-path: (\".\" \"../util/\")\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/cequiv_props4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.2679218736365784}}
{"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 O E Eprime P A B C D A1 B1 C1 D1 C1prime M D1prime N : Universe, ((wd_ O E /\\ (wd_ P B /\\ (wd_ A B /\\ (wd_ O M /\\ (wd_ M C1 /\\ (wd_ O C1 /\\ (wd_ C1 C1prime /\\ (wd_ O C1prime /\\ (wd_ E Eprime /\\ (wd_ O Eprime /\\ (wd_ P A /\\ (wd_ A C /\\ (wd_ P C /\\ (wd_ C D /\\ (wd_ C1prime A1 /\\ (wd_ O A1 /\\ (wd_ O B1 /\\ (wd_ M C1prime /\\ (wd_ N O /\\ (wd_ D1 N /\\ (wd_ D1 D1prime /\\ (wd_ N D1prime /\\ (wd_ D1prime O /\\ (wd_ O D1 /\\ (wd_ P D /\\ (wd_ A1 Eprime /\\ (col_ P A B /\\ (col_ P C D /\\ (col_ O E A1 /\\ (col_ O E B1 /\\ (col_ O E C1 /\\ (col_ O E D1 /\\ (col_ O M N /\\ (col_ C A B /\\ (col_ N D1 D1prime /\\ (col_ M C1 C1prime /\\ (col_ O C1prime D1prime /\\ (col_ O A1 C1 /\\ col_ O C1 D1)))))))))))))))))))))))))))))))))))))) -> col_ P A 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_1416.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.26788281621472426}}
{"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 Bool.\nRequire Import String.\nRequire Import List.\nRequire Import Compare_dec.\nRequire Import Eqdep_dec.\nRequire Import Program.\nRequire Import Utils.\nRequire Import DataSystem.\nRequire Import cNRAEnv.\nRequire Import cNRAEnvEq.\nRequire Import NRASystem.\n\nImport ListNotations.\nLocal Open Scope list_scope.\n\nSection TcNRAEnv.\n  Local Open Scope nraenv_core_scope.\n  \n  (** Typing for NRA *)\n  Section typ.\n    Context {m:basic_model}.\n    Context (τconstants:tbindings).\n  \n  Inductive nraenv_core_type : nraenv_core -> rtype -> rtype -> rtype -> Prop :=\n  | type_cNRAEnvGetConstant {τenv τin τout} s :\n      tdot τconstants s = Some τout ->\n      nraenv_core_type (cNRAEnvGetConstant s) τenv τin τout\n  | type_cNRAEnvID {τenv τ} :\n      nraenv_core_type cNRAEnvID τenv τ τ\n  | type_cNRAEnvConst {τenv τin τout} c :\n      data_type (normalize_data brand_relation_brands c) τout -> nraenv_core_type (cNRAEnvConst c) τenv τin τout\n  | type_cNRAEnvBinop {τenv τin τ₁ τ₂ τout} b op1 op2 :\n      binary_op_type b τ₁ τ₂ τout ->\n      nraenv_core_type op1 τenv τin τ₁ ->\n      nraenv_core_type op2 τenv τin τ₂ ->\n      nraenv_core_type (cNRAEnvBinop b op1 op2) τenv τin τout\n  | type_cNRAEnvUnop {τenv τin τ τout} u op :\n      unary_op_type u τ τout ->\n      nraenv_core_type op τenv τin τ ->\n      nraenv_core_type (cNRAEnvUnop u op) τenv τin τout\n  | type_cNRAEnvMap {τenv τin τ₁ τ₂} op1 op2 :\n      nraenv_core_type op1 τenv τ₁ τ₂ ->\n      nraenv_core_type op2 τenv τin (Coll τ₁) ->\n      nraenv_core_type (cNRAEnvMap op1 op2) τenv τin (Coll τ₂)\n  | type_cNRAEnvMapProduct {τenv τin τ₁ τ₂ τ₃} op1 op2 pf1 pf2 pf3 :\n      nraenv_core_type op1 τenv (Rec Closed τ₁ pf1) (Coll (Rec Closed τ₂ pf2)) ->\n      nraenv_core_type op2 τenv τin (Coll (Rec Closed τ₁ pf1)) ->\n      rec_concat_sort τ₁ τ₂ = τ₃ ->\n      nraenv_core_type (cNRAEnvMapProduct op1 op2) τenv τin (Coll (Rec Closed τ₃ pf3))\n  | type_cNRAEnvProduct {τenv τin τ₁ τ₂ τ₃} op1 op2 pf1 pf2 pf3 :\n      nraenv_core_type op1 τenv τin (Coll (Rec Closed τ₁ pf1)) ->\n      nraenv_core_type op2 τenv τin (Coll (Rec Closed τ₂ pf2)) ->\n      rec_concat_sort τ₁ τ₂ = τ₃ ->\n      nraenv_core_type (cNRAEnvProduct op1 op2) τenv τin (Coll (Rec Closed τ₃ pf3))\n  | type_cNRAEnvSelect {τenv τin τ} op1 op2 :\n      nraenv_core_type op1 τenv τ Bool ->\n      nraenv_core_type op2 τenv τin (Coll τ) ->\n      nraenv_core_type (cNRAEnvSelect op1 op2) τenv τin (Coll τ)\n  | type_cNRAEnvDefault {τenv τin τ} op1 op2 :\n      nraenv_core_type op1 τenv τin (Coll τ) ->\n      nraenv_core_type op2 τenv τin (Coll τ) ->\n      nraenv_core_type (cNRAEnvDefault op1 op2) τenv τin (Coll τ)\n  | type_cNRAEnvEither {τenv τl τr τout} opl opr :\n      nraenv_core_type opl τenv τl τout ->\n      nraenv_core_type opr τenv τr τout ->\n      nraenv_core_type (cNRAEnvEither opl opr) τenv (Either τl τr) τout\n  | type_cNRAEnvEitherConcat {τenv τin rll pfl rlr pfr rlo pfo lo ro} op1 op2 pflo pfro :\n      nraenv_core_type op1 τenv τin (Either (Rec Closed rll pfl) (Rec Closed rlr pfr)) ->\n      nraenv_core_type op2 τenv τin (Rec Closed rlo pfo) ->\n      rec_concat_sort rll rlo = lo ->\n      rec_concat_sort rlr rlo = ro ->\n      nraenv_core_type (cNRAEnvEitherConcat op1 op2) τenv  τin (Either (Rec Closed lo pflo) (Rec Closed ro pfro))                  \n  | type_cNRAEnvApp {τenv τin τ1 τ2} op2 op1 :\n      nraenv_core_type op1 τenv τin τ1 ->\n      nraenv_core_type op2 τenv τ1 τ2 ->\n      nraenv_core_type (cNRAEnvApp op2 op1) τenv τin τ2\n  | type_cNRAEnvEnv {τenv τin} :\n      nraenv_core_type cNRAEnvEnv τenv τin τenv\n  | type_cNRAEnvAppEnv {τenv τenv' τin τ2} op2 op1 :\n      nraenv_core_type op1 τenv τin τenv' ->\n      nraenv_core_type op2 τenv' τin τ2 ->\n      nraenv_core_type (cNRAEnvAppEnv op2 op1) τenv τin τ2\n  | type_cNRAEnvMapEnv {τenv τin τ₂} op1 :\n      nraenv_core_type op1 τenv τin τ₂ ->\n      nraenv_core_type (cNRAEnvMapEnv op1) (Coll τenv) τin (Coll τ₂).\n  End typ.\n\n  Notation \"Op ▷ A >=> B ⊣ C ; E\" := (nraenv_core_type C Op E A B) (at level 70).\n\n  (** Type lemmas for individual algebraic expressions *)\n\n  Context {m:basic_model}.\n  \n  Lemma lift_map_typed {τc} {τenv τ₁ τ₂ : rtype} c (op1 : nraenv_core) (env:data) (dl : list data) :\n    (bindings_type c τc) ->\n    (env ▹ τenv) ->\n    (Forall (fun d : data => data_type d τ₁) dl) ->\n    (op1 ▷ τ₁ >=> τ₂ ⊣ τc; τenv) ->\n    (forall d : data,\n       data_type d τ₁ -> exists x : data, brand_relation_brands ⊢ₑ op1 @ₑ d ⊣ c; env = Some x /\\ x ▹ τ₂) ->\n    exists x : list data, (lift_map (nraenv_core_eval brand_relation_brands c op1 env) dl = Some x) /\\ data_type (dcoll x) (Coll τ₂).\n  Proof.\n    intros dt_c; intros.\n    induction dl; simpl; intros.\n    - exists (@nil data); split; [reflexivity|apply dtcoll;apply Forall_nil].\n    - inversion H0; clear H0.\n      elim (H2 a); intros; try assumption.\n      elim H0; intros; clear H0.\n      rewrite H7; clear H7.\n      specialize (IHdl H6); clear H6.\n      elim IHdl; intros; clear IHdl.\n      elim H0; intros; clear H0.\n      dependent induction H7.\n      rewrite H6.\n      exists (x0 :: x1).\n      split; try reflexivity.\n      apply dtcoll.\n      apply Forall_cons; try assumption.\n      assert (r = τ₂) by (apply rtype_fequal; assumption).\n      rewrite <- H3; assumption.\n  Qed.\n\n  Lemma lift_map_env_typed {τc} {τenv τ₁ τ₂ : rtype} c (op1 : nraenv_core) (x0:data) (dl : list data) :\n    bindings_type c τc ->\n    (x0 ▹ τ₁) ->\n    (Forall (fun d : data => data_type d τenv) dl) ->\n    (op1 ▷ τ₁ >=> τ₂ ⊣ τc;τenv) ->\n    (forall env : data,\n       data_type env τenv ->\n       forall d : data,\n         data_type d τ₁ ->\n         exists x : data, brand_relation_brands ⊢ₑ op1 @ₑ d ⊣ c;env = Some x /\\ data_type x τ₂) ->\n    exists x : list data, (lift_map (fun env' => (nraenv_core_eval brand_relation_brands c op1 env' x0)) dl = Some x) /\\ data_type (dcoll x) (Coll τ₂).\n  Proof.\n    intros dt_c.\n    induction dl; simpl; intros.\n    - exists (@nil data); split; [reflexivity|apply dtcoll;apply Forall_nil].\n    - inversion H0; clear H0 H4 l H3 x.\n      elim (H2 a H5 x0); intros; try assumption.\n      elim H0; intros; clear H0.\n      rewrite H3; clear H3; simpl in *.\n      specialize (IHdl H H6); clear H6.\n      elim IHdl; intros; clear IHdl; trivial.\n      elim H0; intros; clear H0.\n      dependent induction H6.\n      rewrite H3; clear H3; simpl.\n      exists (x2 :: x1).\n      split; try reflexivity.\n      apply dtcoll.\n      apply Forall_cons; try assumption.\n      assert (r = τ₂) by (apply rtype_fequal; assumption).\n      rewrite <- H3; assumption.\n      eauto.\n  Qed.\n\n  Lemma recover_rec k d r τ pf:\n    data_type d r ->\n    ` r =\n    Rec₀ k\n      (map\n         (fun x : string * {τ₀ : rtype₀ | wf_rtype₀ τ₀ = true} =>\n            (fst x, ` (snd x))) τ) ->\n    data_type d (Rec k τ pf).\n  Proof.\n    intros.\n    assert (Rec k τ pf = r).\n    unfold Rec.\n    apply rtype_fequal.\n    rewrite H0.\n    reflexivity.\n    rewrite H1; assumption.\n  Qed.\n\n  Lemma recover_rec_forall k l r τ pf:\n    Forall (fun d : data => data_type d r) l ->\n    ` r =\n    Rec₀ k\n      (map\n         (fun x : string * {τ₀ : rtype₀ | wf_rtype₀ τ₀ = true} =>\n            (fst x, ` (snd x))) τ) ->\n    Forall (fun d : data => data_type d (Rec k τ pf)) l.\n  Proof.\n    intros; rewrite Forall_forall in *; intros.\n    specialize (H x H1).\n    apply (recover_rec k x r τ pf); assumption.\n  Qed.\n\n  Lemma omap_concat_typed_env\n        (τenv:rtype) (τ₁ τ₂ τ₃: list (string * rtype)) (env:data) (dl2: list data)\n        (x : list (string * data)) pf1 pf2 pf3:\n    (data_type env τenv) ->\n    (forall x : data, In x dl2 -> data_type x (Rec Closed τ₂ pf2)) ->\n    rec_concat_sort τ₁ τ₂ = τ₃ ->\n    data_type (drec x) (Rec Closed τ₁ pf1) ->\n    (exists y : list data,\n       lift_map (fun x1 : data => orecconcat (drec x) x1) dl2\n       = Some y /\\ data_type (dcoll y) (Coll (Rec Closed τ₃ pf3))).\n  Proof.\n    intro Henv.\n    intros; induction dl2; simpl.\n    exists (@nil data); split; [reflexivity|apply dtcoll; apply Forall_nil].\n    simpl in H.\n    assert (data_type a (Rec Closed τ₂ pf2))\n      by (apply (H a); left; reflexivity).\n    destruct (data_type_Rec_inv H2); subst.\n    apply dtrec_closed_inv in H2.\n    assert (H':forall x : data, In x dl2 -> data_type x (Rec Closed τ₂ pf2)) by\n        (eapply forall_in_weaken; eassumption).\n    specialize (IHdl2 H'); clear H'.\n    destruct IHdl2 as [? [??]].\n    revert H0; elim (lift_map (fun x2 : data => orecconcat (drec x) x2) dl2); intros; try discriminate.\n    inversion H0; subst; clear H0.\n    unfold lift.\n    induction dl2.\n    - simpl.\n      exists (drec (rec_concat_sort x x0) :: nil); split; try reflexivity.\n      apply dtcoll. rewrite Forall_forall in *; intros.\n      simpl in H0. intuition.\n      destruct x2; try congruence. inversion H4; subst; clear H4.\n      apply dtrec_full.\n      apply rec_concat_with_drec_concat_well_typed; try assumption.\n      apply dtrec_closed_inv in H1. trivial.\n    - simpl in *.\n      generalize (H a). intuition.\n      destruct (data_type_Rec_inv H5); subst.\n      apply dtrec_closed_inv in H5.\n      destruct IHdl2; [intuition | ].\n      unfold lift.\n      destruct H0 as [eq1 dt1].\n      case_option_in eq1; try discriminate.\n      eexists; split; [reflexivity | ].\n      constructor.\n      inversion eq1; subst; clear eq1.\n      inversion dt1; subst.\n      generalize (recover_rec_forall _ _ _ _ pf3 H8 H7).\n      inversion 1; simpl; subst.\n      constructor; simpl; trivial.\n      constructor; trivial.\n      apply dtrec_full.\n      apply dtrec_closed_inv in H1.\n      apply rec_sort_Forall2.\n      + repeat rewrite domain_app.\n        rewrite (sorted_forall_same_domain H1).\n        rewrite (sorted_forall_same_domain H5). trivial.\n      + apply Forall2_app; trivial.\n  Qed.\n\n  Lemma oproduct_typed_env {τ₁ τ₂ τ₃: list (string * rtype)} (dl dl0: list data) pf1 pf2 pf3:\n    Forall (fun d : data => data_type d (Rec Closed τ₂ pf2)) dl0 ->\n    Forall (fun d : data => data_type d (Rec Closed τ₁ pf1)) dl ->\n    rec_concat_sort τ₁ τ₂ = τ₃ ->\n    exists x : list data, (oproduct dl dl0 = Some x) /\\ data_type (dcoll x) (Coll (Rec Closed τ₃ pf3)).\n  Proof.\n    intros; rewrite Forall_forall in *.\n    induction dl; simpl in *.\n    - exists (@nil data); split; [reflexivity| apply dtcoll; apply Forall_nil].\n    - assert (exists r, a = drec r /\\ data_type (drec r) (Rec Closed τ₁ pf1)).\n      + clear IHdl H; assert (data_type a (Rec Closed τ₁ pf1))\n                    by (specialize (H0 a); apply H0; left; reflexivity).\n         destruct (data_type_Rec_inv H); subst.\n         apply dtrec_closed_inv in H.\n         eexists; split; [reflexivity | ].\n         apply dtrec_full; trivial.\n      + destruct H2 as [? [??]]; subst.\n      assert (forall x : data, In x dl -> data_type x (Rec Closed τ₁ pf1))\n        by (apply forall_in_weaken with (P := (fun x0 => (drec x) = x0)); assumption).\n      specialize (IHdl H1).\n      destruct IHdl as [? [??]].\n      unfold oproduct.\n      simpl.\n      assert (exists y, (omap_concat (drec x) dl0) = Some y /\\ (data_type  (dcoll y) (Coll (Rec Closed  (rec_concat_sort τ₁ τ₂) pf3))))\n        by (eapply omap_concat_typed_env; eauto).\n      destruct H5 as [? [??]].\n      generalize (oproduct_cons _ _ _ _ _ H2 H5).\n      unfold oproduct; simpl.\n      rewrite H5. intros eqq.\n      exists (x1 ++ x0).\n      split; trivial.\n      inversion H6; subst.\n      inversion H4; subst.\n      generalize (recover_rec_forall _ _ _ _ pf3 H9 H8); intros.\n      generalize (recover_rec_forall _ _ _ _ pf3 H11 H10); intros.\n      constructor. apply Forall_app; trivial.\n  Qed.\n  \n  Lemma data_type_concat l1 l2 τ:\n    data_type (dcoll l1) (Coll τ) ->\n    data_type (dcoll l2) (Coll τ) ->\n    data_type (dcoll (l1 ++ l2)) (Coll τ).\n  Proof.\n    intros.\n    dependent induction H.\n    dependent induction H0.\n    apply dtcoll.\n    apply Forall_app; rewrite Forall_forall in *;\n    assert (r = τ) by (apply rtype_fequal; assumption);\n    assert (r0 = τ) by (apply rtype_fequal; assumption);\n    rewrite H1 in H; rewrite H2 in H0; assumption.\n  Qed.\n\n  Lemma omap_product_typed_env {τc} {τenv:rtype} {τ₁ τ₂ τ₃ : list (string * rtype)} (op1 : nraenv_core) c (env:data) (dl: list data) pf1 pf2 pf3:\n    bindings_type c τc ->\n    env ▹ τenv ->\n    rec_concat_sort τ₁ τ₂ = τ₃ ->\n    Forall (fun d : data => data_type d (Rec Closed τ₁ pf1)) dl ->\n    (op1 ▷ Rec Closed τ₁ pf1 >=> Coll (Rec Closed τ₂ pf2) ⊣ τc;τenv) ->\n    (forall d : data,\n                data_type d (Rec Closed τ₁ pf1) ->\n                exists x : data,\n                   brand_relation_brands ⊢ₑ op1 @ₑ d ⊣ c;env = Some x /\\ data_type x (Coll (Rec Closed τ₂ pf2))) ->\n    exists x : list data, (omap_product (nraenv_core_eval brand_relation_brands c op1 env) dl = Some x) /\\ data_type (dcoll x) (Coll (Rec Closed τ₃ pf3)).\n  Proof.\n    intros dt_c Henv.\n    intros; rewrite Forall_forall in *.\n    induction dl; simpl in *; unfold omap_product in *; simpl.\n    exists (@nil data); split; [reflexivity|apply dtcoll; apply Forall_nil].\n    assert (forall x : data, In x dl -> data_type x (Rec Closed τ₁ pf1))\n      by (apply forall_in_weaken with (P := (fun x => a = x)); assumption).\n    elim (IHdl H3); intros; elim H4; intros; clear IHdl H4.\n    assert (data_type a (Rec Closed τ₁ pf1))\n      by (apply (H0 a); left; reflexivity).\n    rewrite H5; clear H5.\n    destruct (data_type_Rec_inv H4); subst.\n    apply dtrec_closed_inv in H4.\n    assert (data_type (drec x0) (Rec Closed τ₁ pf1))\n      by (apply (H0 (drec x0)); left; reflexivity).\n    unfold oncoll_map_concat.\n    elim (H2 (drec x0) H); intros; clear H2.\n    elim H5; intros; clear H5.\n    rewrite H2; clear H2.\n    dtype_inverter.\n    apply Col_inv in H7.\n    rename x1 into dl0.\n    assert (exists y, (omap_concat (drec x0) dl0) = Some y /\\ (data_type (dcoll y) (Coll (Rec Closed (rec_concat_sort τ₁ τ₂) pf3)))).\n    unfold omap_concat.\n    eapply (omap_concat_typed_env τenv τ₁ τ₂ (rec_concat_sort τ₁ τ₂)); eauto.\n    apply Forall_forall; eauto.\n    destruct H2 as [?[eqq ?]].\n    rewrite eqq; clear eqq.\n    simpl.\n    exists (x1++x).\n    split. reflexivity.\n    apply data_type_concat; assumption.\n  Qed.\n\n  Lemma omap_product_typed2_env {τc} {τenv:rtype} {τ₁ τ₂ τ₃ : list (string * rtype)} τin c (op1 : nraenv_core) (env:data) y (dl: list data) pf1 pf2 pf3:\n    bindings_type c τc ->\n    env▹ τenv ->\n    rec_concat_sort τ₁ τ₂ = τ₃ ->\n    Forall (fun d : data => data_type d (Rec Closed τ₁ pf1)) dl ->\n    (op1 ▷ τin >=> Coll (Rec Closed τ₂ pf2) ⊣ τc;τenv) ->\n    (forall d : data,\n                data_type d (Rec Closed τ₁ pf1) ->\n                exists x : data,\n                   brand_relation_brands ⊢ₑ op1 @ₑ y ⊣ c;env = Some x /\\ data_type x (Coll (Rec Closed τ₂ pf2))) ->\n    exists x : list data, (omap_product (fun z =>  brand_relation_brands ⊢ₑ op1@ₑ y ⊣ c;env) dl = Some x) /\\ data_type (dcoll x) (Coll (Rec Closed τ₃ pf3)).\n  Proof.\n    intros dt_c Henv.\n    intros; rewrite Forall_forall in *.\n    induction dl; simpl in *; unfold omap_product in *; simpl.\n    exists (@nil data); split; [reflexivity|apply dtcoll; apply Forall_nil].\n    assert (forall x : data, In x dl -> data_type x (Rec Closed τ₁ pf1))\n      by (apply forall_in_weaken with (P := (fun x => a = x)); assumption).\n    elim (IHdl H3); intros; elim H4; intros; clear IHdl H4.\n    assert (data_type a (Rec Closed τ₁ pf1))\n      by (apply (H0 a); left; reflexivity).\n    rewrite H5; clear H5.\n    destruct (data_type_Rec_inv H4); subst.\n    apply dtrec_closed_inv in H4.\n    rename x0 into dl0.\n    assert (data_type (drec dl0) (Rec Closed τ₁ pf1))\n      by (apply (H0 (drec dl0)); left; reflexivity).\n    unfold oncoll_map_concat.\n    elim (H2 (drec dl0) H); intros; clear H2.\n    elim H5; intros; clear H5.\n    rewrite H2; clear H2.\n    dtype_inverter.\n    apply Col_inv in H7.\n    rename x0 into dl1.\n    assert (exists y, (omap_concat (drec dl0) dl1) = Some y /\\ (data_type  (dcoll y) (Coll (Rec Closed (rec_concat_sort τ₁ τ₂) pf3)))).\n    unfold omap_concat.\n    apply (omap_concat_typed_env τenv τ₁ τ₂ (rec_concat_sort τ₁ τ₂) env dl1 dl0 pf1 pf2 pf3); trivial.\n    intros.\n    rewrite Forall_forall in H7; specialize (H7 _ H2); trivial.\n    destruct H2 as [? [eqq ?]].\n    rewrite eqq; clear eqq.\n    exists (x0++x).\n    split. reflexivity.\n    apply data_type_concat; assumption.\n  Qed.\n\n  (** Main typing soundness theorem for NRAEnv *)\n\n  Theorem typed_nraenv_core_yields_typed_data {τc} {τenv τin τout} c (env:data) (d:data) (op:nraenv_core):\n    bindings_type c τc ->\n    (env ▹ τenv) -> (d ▹ τin) -> (op ▷ τin >=> τout ⊣ τc;τenv) ->\n    (exists x, (brand_relation_brands ⊢ₑ op @ₑ d ⊣ c;env = Some x /\\ (x ▹ τout))).\n  Proof.\n    intros dt_c Henv.\n    intros.\n    revert env Henv d H.\n    dependent induction H0; simpl; intros.\n    (* type_cNRAEnvGetConstant *)\n    - unfold tdot in *.\n      unfold edot in *.\n      destruct (Forall2_lookupr_some dt_c H) as [? [eqq1 eqq2]].\n      rewrite eqq1.\n      eauto.\n    (* type_cNRAEnvID *)\n    - exists d; split; [reflexivity|assumption].\n    (* type_cNRAEnvConst *)\n    - exists (normalize_data brand_relation_brands c0); split; try reflexivity.\n      assumption.\n    (* type_cNRAEnvBinop *)\n    - elim (IHnraenv_core_type1 env Henv d H0); elim (IHnraenv_core_type2 env Henv d H0); intros.\n      elim H1; elim H2; intros; clear H1 H2.\n      rewrite H3; simpl.\n      rewrite H5; simpl.\n      apply (typed_binary_op_yields_typed_data x0 x b H4 H6); assumption.\n    (* type_cNRAEnvUnop *)\n    - elim (IHnraenv_core_type env Henv d H1); intros.\n      elim H2; intros; clear H2.\n      rewrite H3.\n      apply (typed_unary_op_yields_typed_data x u H4); assumption.\n    (* type_cNRAEnvMap *)\n    - elim (IHnraenv_core_type2 env Henv d H); intros; clear H IHnraenv_core_type2.\n      elim H0; intros; clear H0.\n      rewrite H; clear H.\n      invcs H1.\n      rtype_equalizer.\n      subst.\n      assert (EE : exists x : list data, (lift_map (nraenv_core_eval brand_relation_brands c op1 env) dl = Some x)\n                                    /\\ data_type (dcoll x) (Coll τ₂)).\n      + apply (@lift_map_typed τc τenv τ₁ τ₂ c op1 env dl dt_c Henv); trivial.\n        apply IHnraenv_core_type1; trivial.\n      + destruct EE as [? [eqq dt]].\n        simpl.\n        rewrite eqq; simpl.\n        eexists; split; try reflexivity.\n        trivial.\n    (* type_cNRAEnvMapProduct *)\n    - elim (IHnraenv_core_type2 env Henv d H0); intros; clear IHnraenv_core_type2 H0.\n      elim H1; intros; clear H1.\n      rewrite H0; clear H0.\n      invcs H2.\n      assert (EE : exists x : list data, (omap_product (nraenv_core_eval brand_relation_brands c op1 env) dl = Some x) /\\ data_type (dcoll x) (Coll (Rec Closed (rec_concat_sort τ₁ τ₂) pf3))).\n      + apply (omap_product_typed_env op1 c env dl pf1 pf2 pf3 dt_c Henv); try assumption; try reflexivity.\n        apply recover_rec_forall with (r:= r); assumption.\n        apply IHnraenv_core_type1; assumption.\n      + destruct EE as [? [eqq typ]].\n        simpl; rewrite eqq; simpl.\n        eexists; split; try reflexivity.\n        trivial.\n    (* type_cNRAEnvProduct *)\n    - elim (IHnraenv_core_type1 env Henv d H0); intros; clear IHnraenv_core_type1.\n      elim H1; intros; clear H1.\n      rewrite H2; clear H2; invcs H3.\n      assert (EE : exists x : list data, (omap_product (fun _ : data => brand_relation_brands ⊢ₑ op2 @ₑ d ⊣ c;env) dl = Some x) /\\ data_type (dcoll x) (Coll (Rec Closed (rec_concat_sort τ₁ τ₂) pf3))).\n      + apply (@omap_product_typed2_env τc τenv τ₁ τ₂ (rec_concat_sort τ₁ τ₂) τin c op2 env d dl pf1 pf2 pf3); try assumption; try reflexivity.\n        apply recover_rec_forall with (r:= r); assumption.\n        destruct (IHnraenv_core_type2 env Henv d H0) as [? [eqq dt]].\n        rewrite eqq.\n        intros.\n        eexists; split; try reflexivity.\n        trivial.\n      + destruct EE as [? [eqq typ]].\n        simpl; rewrite eqq; simpl.\n        eexists; split; try reflexivity.\n        trivial.\n    (* type_cNRAEnvSelect *)\n    - elim (IHnraenv_core_type2 env Henv d H); intros; clear IHnraenv_core_type2.\n      elim H0; intros; clear H0.\n      rewrite H1; clear H1 H0_0.\n      invcs H2.\n      rtype_equalizer.\n      subst.\n      assert (exists c2, \n          (lift_filter\n             (fun x' : data =>\n              match brand_relation_brands ⊢ₑ op1 @ₑ x' ⊣ c;env with\n              | Some (dbool b) => Some b\n              | _ => None\n              end) dl) = Some c2 /\\ Forall (fun d : data => data_type d τ) c2).\n      + induction dl.\n        * exists (@nil data). split. reflexivity. apply Forall_nil.\n        * rewrite Forall_forall in *; intros.\n          assert (forall x : data, In x dl -> data_type x τ)\n                 by intuition.\n          assert (data_type a τ)\n            by (simpl in *; intuition).\n          destruct (IHnraenv_core_type1 env Henv a H1) as [? [eqq dt]].\n          simpl; rewrite eqq; simpl.\n          dtype_inverter.\n          destruct (IHdl H0) as [? [eqq1 dt1]].\n          rewrite eqq1; simpl.\n          assert (data_type a τ)\n            by (simpl in *; intuition).\n          destruct x0; simpl; eexists; split; try reflexivity; trivial.\n          constructor; trivial.\n      + destruct H0 as [? [eqq dt]].\n        simpl; rewrite eqq; simpl.\n        eexists; split; try reflexivity; trivial.\n        constructor; trivial.\n    (* type_cNRAEnvDefault *)\n    - elim (IHnraenv_core_type1 env Henv d H); elim (IHnraenv_core_type2 env Henv d H); intros.\n      elim H0; elim H1; intros; clear H0 H1 H.\n      rewrite H2. rewrite H4. clear H2 H4.\n      simpl.\n      invcs H3; invcs H5; rtype_equalizer.\n      subst.\n      destruct dl.\n      + eexists; split; try reflexivity; trivial.\n        constructor; trivial.\n      + eexists; split; try reflexivity; trivial.\n        constructor; trivial.\n    (* type_cNRAEnvEither *)\n    - destruct (data_type_Either_inv H) as [[dd[? ddtyp]]|[dd[? ddtyp]]]; subst; eauto.\n    (* type_cNRAEnvEitherConcat *)\n    - destruct (IHnraenv_core_type2 env Henv d H1) as [? [??]].\n      rewrite H2.\n      destruct (IHnraenv_core_type1 env Henv d H1) as [? [??]].\n      rewrite H4.\n      destruct (data_type_Rec_inv H3); subst.\n      destruct (data_type_Either_inv H5) as [[dd[? ddtyp]]|[dd[? ddtyp]]]; subst; eauto;\n      destruct (data_type_Rec_inv ddtyp); subst;\n      (eexists;split;[reflexivity| ];\n      econstructor;\n      eapply dtrec_rec_concat_sort; eauto).\n    (* type_cNRAEnvApp *)\n    - elim (IHnraenv_core_type1 env Henv d H); intros.\n      elim H0; intros; clear H0 H.\n      rewrite H1; simpl.\n      elim (IHnraenv_core_type2 env Henv x H2); intros.\n      elim H; intros; clear H.\n      rewrite H0; simpl.\n      exists x0;split;[reflexivity|assumption].\n    (* type_cNRAEnvEnv *)\n    - exists env; split; [reflexivity|assumption].\n    (* type_cNRAEnvAppEnv *)\n    - elim (IHnraenv_core_type1 env Henv d H); intros.\n      elim H0; intros; clear H0.\n      rewrite H1; simpl.\n      elim (IHnraenv_core_type2 x H2 d H); intros.\n      elim H0; intros; clear H0.\n      rewrite H3; simpl.\n      exists x0;split;[reflexivity|assumption].\n    (* type_cNRAEnvMapEnv *)\n    - intros.\n      invcs Henv; rtype_equalizer.\n      subst; simpl.\n      assert (exists x : list data, (lift_map (fun env' : data => (nraenv_core_eval brand_relation_brands c op1 env' d)) dl = Some x) /\\ data_type (dcoll x) (Coll τ₂)).\n      * apply (@lift_map_env_typed τc τenv τin τ₂); try assumption.\n      * destruct H1 as [? [eqq dt]].\n        rewrite eqq; simpl.\n        eexists; split; try reflexivity; trivial.\n  Qed.\n\n  (* Evaluation into single value for typed core NRAe *)\n\n  Hint Constructors nra_type unary_op_type binary_op_type : qcert.\n  Hint Resolve ATdot ATnra_data : qcert.\n  (** Corrolaries of the main type soudness theorem *)\n\n  Definition typed_nraenv_core_total {τc} {τenv τin τout} (op:nraenv_core) (HOpT: op ▷ τin >=> τout ⊣ τc;τenv) c (env:data) (d:data)\n    (dt_c: bindings_type c τc) :\n    (env ▹ τenv) ->\n    (d ▹ τin) ->\n    { x:data | x ▹ τout }.\n  Proof.\n    intro Henv.\n    intros HdT.\n    generalize (typed_nraenv_core_yields_typed_data c env d op dt_c Henv HdT HOpT).\n    intros.\n    destruct (brand_relation_brands ⊢ₑ op @ₑ d ⊣ c;env).\n    assert (data_type d0 τout).\n    - inversion H. inversion H0. inversion H1. trivial.\n    - exists d0. trivial.\n    - cut False. intuition. inversion H.\n      destruct H0. inversion H0.\n  Defined.\n\n  Definition tnraenv_core_eval {τc} {τenv τin τout} (op:nraenv_core) (HOpT: op ▷ τin >=> τout ⊣ τc;τenv) c (env:data) (d:data)\n             (dt_c: bindings_type c τc) : \n    (env ▹ τenv) -> (d ▹ τin) -> data.\n  Proof.\n    intros Henv.\n    intros HdT.\n    destruct (typed_nraenv_core_total op HOpT c env d dt_c Henv HdT).\n    exact x.\n  Defined.\n\n  Theorem typed_nraenv_core_to_typed_nra {τc} {τenv τin τout} (op:nraenv_core):\n    (nraenv_core_type τc op τenv τin τout) -> (nra_type τc (nra_of_nraenv_core op) (nra_context_type τenv τin) τout).\n  Proof.\n    intros.\n    dependent induction H; simpl; intros.\n    (* cNRAEnvGetConstant *)\n    - unfold nra_bind, nra_context_type.\n      econstructor; eauto.\n    (* cNRAEnvID *)\n    - qeauto.\n    (* cNRAEnvConst *)\n    - qeauto.\n    (* cNRAEnvBinop *)\n    - qeauto.\n    (* cNRAEnvUnop *)\n    - qeauto.\n    (* cNRAEnvMap *)\n    - apply (@type_NRAMap m τc (nra_context_type τenv τin) (nra_context_type τenv τ₁) τ₂); try assumption.\n      eapply ATunnest_two.\n      eapply (type_NRAUnop). qeauto.\n      unfold nra_wrap_a1, nra_double.\n      eapply type_NRABinop. qeauto.\n      eapply (type_NRAUnop). qeauto.\n      eapply type_NRAUnop; qeauto.\n      eapply type_OpDot. unfold tdot, edot; simpl. qauto.\n      eapply (type_NRAUnop). qeauto.\n      eauto.\n      unfold tdot, edot; auto.\n      reflexivity.\n      reflexivity.\n    (* cNRAEnvMapProduct *)\n    - apply (@type_NRAMap m τc (nra_context_type τenv τin) (Rec Closed ((\"PBIND\"%string, τenv) :: (\"PDATA\"%string, (Rec Closed τ₁ pf1)) :: (\"PDATA2\"%string, (Rec Closed τ₂ pf2)) :: nil) (eq_refl _))).\n      econstructor; qeauto.\n      econstructor; qeauto.\n      econstructor; qeauto.\n      reflexivity.\n      econstructor; qeauto.\n      econstructor; qeauto.\n      reflexivity.\n      apply (@type_NRAMapProduct m τc (nra_context_type τenv τin)\n                          [(\"PBIND\"%string, τenv); (\"PDATA\"%string, Rec Closed τ₁ pf1)]\n                          [(\"PDATA2\"%string, (Rec Closed τ₂ pf2))]\n                          [(\"PBIND\"%string, τenv); (\"PDATA\"%string, Rec Closed τ₁ pf1); (\"PDATA2\"%string, Rec Closed τ₂ pf2)]\n                          (NRAMap (NRAUnop (OpRec \"PDATA2\") NRAID) (nra_of_nraenv_core op1))\n                          (unnest_two \"a1\" \"PDATA\" (NRAUnop OpBag (nra_wrap_a1 (nra_of_nraenv_core op2))))\n                          eq_refl eq_refl\n            ); try reflexivity.\n      qeauto.\n      unfold nra_wrap_a1.\n      apply (ATunnest_two \"a1\" \"PDATA\" (NRAUnop OpBag (nra_double \"PBIND\" \"a1\" nra_bind (nra_of_nraenv_core op2))) τc (nra_context_type τenv τin) [(\"PBIND\"%string, τenv); (\"a1\"%string, Coll (Rec Closed τ₁ pf1))] eq_refl (Rec Closed τ₁ pf1)); try reflexivity.\n      apply (@type_NRAUnop m τc (nra_context_type τenv τin) (Rec Closed [(\"PBIND\"%string, τenv); (\"a1\"%string, Coll (Rec Closed τ₁ pf1))] eq_refl)).\n      econstructor; eauto.\n      unfold nra_double, nra_bind.\n      apply (@type_NRABinop m τc (nra_context_type  τenv τin) (Rec Closed [(\"PBIND\"%string, τenv)] eq_refl) (Rec Closed [(\"a1\"%string, Coll (Rec Closed τ₁ pf1))] eq_refl)); try eauto.\n        econstructor; qeauto.\n\n        econstructor; qeauto.\n        econstructor; qeauto.\n    (* cNRAEnvProduct *)\n    - qeauto.\n    (* cNRAEnvSelect *)\n    - econstructor; eauto.\n      2: { econstructor; eauto.\n           eapply ATunnest_two.\n           + econstructor; qeauto.\n             unfold nra_wrap_a1, nra_double.\n             eapply type_NRABinop.\n             * econstructor; reflexivity.\n             * econstructor; qeauto.\n               econstructor; qeauto.\n               eapply type_OpDot; unfold tdot, edot; simpl; eauto.\n             * econstructor; qeauto.\n           + unfold tdot, edot; simpl; eauto.\n           + econstructor; eauto. }\n        * econstructor; qeauto.\n          eapply type_OpDot; unfold tdot, edot; simpl; eauto.\n    (* cNRAEnvDefault *)\n    - qeauto.\n    (* type_cNRAEnvEither *)\n    - econstructor.\n      + econstructor; try reflexivity.\n        * { econstructor.\n            - econstructor; qeauto.\n              econstructor; qeauto.\n              reflexivity.\n            - econstructor; qeauto.\n          }\n        * { econstructor; qeauto.\n            - econstructor; qeauto.\n              econstructor; qeauto.\n              econstructor; qeauto.\n            \n          } \n      + econstructor; qeauto.\n    (* cNRAEnvEitherConcat *)\n    - qeauto.\n    (* cNRAEnvApp *)\n    - apply (@type_NRAApp m τc (nra_context_type τenv τin) (nra_context_type τenv τ1) τ2).\n      + unfold nra_context, nra_bind, nra_context_type, nra_double; simpl.\n        unfold nra_wrap.\n        apply (@type_NRABinop m τc (Rec Closed [(\"PBIND\"%string, τenv); (\"PDATA\"%string, τin)] eq_refl) (Rec Closed ((\"PBIND\"%string, τenv)::nil) (eq_refl _)) (Rec Closed ((\"PDATA\"%string, τ1)::nil) (eq_refl _))); repeat (econstructor; qeauto).\n      + trivial.\n    (* cNRAEnvEnv *)\n    - unfold nra_bind, nra_context_type. qeauto.\n    (* cNRAEnvAppEnv *)\n    - apply (@type_NRAApp m τc (nra_context_type τenv τin) (nra_context_type τenv' τin) τ2).\n      + unfold nra_context, nra_bind, nra_context_type, nra_double; simpl.\n        apply (@type_NRABinop m τc (Rec Closed [(\"PBIND\"%string, τenv); (\"PDATA\"%string, τin)] eq_refl) (Rec Closed ((\"PBIND\"%string, τenv')::nil) (eq_refl _)) (Rec Closed ((\"PDATA\"%string, τin)::nil) (eq_refl _))).\n        econstructor; qeauto.\n        do 3 (econstructor; qeauto).\n        do 3 (econstructor; qeauto).\n      + trivial.\n    (* cNRAEnvMapEnv *)\n    - econstructor; qeauto.\n      eapply ATunnest_two.\n      + econstructor; qeauto.\n        unfold nra_wrap_bind_a1, nra_double.\n        eapply type_NRABinop; qeauto.\n        * do 3 (econstructor; qeauto).\n          reflexivity.\n      + reflexivity.\n      + simpl; trivial.\n      Unshelve.\n      qeauto. qeauto. qeauto. qeauto. qeauto. \n      qeauto. qeauto. qeauto. qeauto. qeauto.\n      qeauto. qeauto.\n  Qed.\n\n  Lemma fold_nra_context_type (env d: {τ₀ : rtype₀ | wf_rtype₀ τ₀ = true}) pf :\n    Rec Closed [(\"PBIND\"%string, env); (\"PDATA\"%string, d)] pf\n    = nra_context_type env d.\n  Proof.\n    unfold nra_context_type.\n    erewrite Rec_pr_irrel; eauto.\n  Qed.\n\n  Ltac defst l\n    := match l with\n       | @nil (string*rtype₀) => constr:(@nil (string*rtype))\n       | cons (?x,proj1_sig ?y) ?l' =>\n         let l'' := defst l' in\n         constr:(cons (x,y) l'')\n       end.\n  \n  Ltac rec_proj_simpler\n    := repeat\n         match goal with\n         | [H: Rec₀ ?k ?l = proj1_sig ?τ |- _ ] => symmetry in H\n         | [H: proj1_sig ?τ = Rec₀ ?k ?l |- _ ] =>\n           let ll := defst l in\n           let HH:=fresh \"eqq\" in\n           generalize (@Rec₀_eq_proj1_Rec _ _ τ k ll); intros HH;\n           simpl in HH; specialize (HH H); clear H; destruct HH;\n           try subst τ\n         end.\n  \n  Lemma UIP_bool {a b:bool} (pf1 pf2:a = b) : pf1 = pf2.\n  Proof.\n    apply UIP_dec. apply bool_dec.\n  Qed.\n\n  Ltac nra_inverter_ext\n    :=\n      simpl in *; match goal with\n                  | [H:@nra_type _ _ (unnest_two _ _ _) _ (Coll _) |- _ ] => apply ATunnest_two_inv in H;\n                                                                           destruct H as [? [? [? [? [? [? [?[??]]]]]]]]\n                  | [H: prod _ _ |- _ ] => destruct H; simpl in *; try subst\n                  | [H: context [Rec Closed [(\"PBIND\"%string, ?env); (\"PDATA\"%string, ?d)] ?pf ] |- _ ] => unfold rtype in H; rewrite (fold_nra_context_type env d pf) in H\n                  | [H: Rec₀ ?k ?l = proj1_sig ?τ |- _ ] => symmetry in H\n                  | [H: proj1_sig ?τ = Rec₀ ?k ?l |- _ ] =>\n                    let ll := defst l in\n                    let HH:=fresh \"eqq\" in\n                    generalize (@Rec₀_eq_proj1_Rec _ _ τ k ll); intros HH;\n                    simpl in HH; specialize (HH H); clear H; destruct HH;\n                    try subst τ\n                  | [H:proj1_sig _ =\n                       Rec₀ Closed\n                            (map\n                               (fun x : string * {τ₀ : rtype₀ | wf_rtype₀ τ₀ = true} =>\n                                  (fst x, ` (snd x))) _) |- _ ]\n                    => let Hpf := fresh \"spf\" in\n                       apply Rec₀_eq_proj1_Rec in H; destruct H as [? Hpf]\n                  | [H1:@eq bool ?a ?b,\n                        H2:@eq bool ?a ?b |- _] => destruct (UIP_bool H1 H2)\n                  end.\n\n  Ltac nra_inverter2 :=\n    repeat (try unfold nra_wrap, nra_wrap_a1, nra_wrap_bind_a1, nra_context, nra_double, nra_bind, nra_wrap in *; (nra_inverter_ext || nra_inverter); try subst).\n\n  Ltac tdot_inverter :=\n    repeat\n      match goal with\n        | [H: tdot _ _ = Some _ |- _ ] =>\n          let HH:= fresh \"eqq\" in\n          inversion H as [HH];\n            match type of HH with\n              | ?x1 = ?x2 => try (subst x2 || subst x1); clear H\n              | _ => fail 1\n            end\n      end.\n\n  Lemma typed_nraenv_core_to_typed_nra_inv' {k τc τenv τin τout pf} (op:nraenv_core):\n    nra_type τc (nra_of_nraenv_core op) (Rec k [(\"PBIND\"%string, τenv); (\"PDATA\"%string, τin)] pf) τout ->\n    nraenv_core_type τc op τenv τin τout.\n  Proof.\n    Hint Constructors nraenv_core_type : qcert.\n    revert k τenv τin τout pf.\n    induction op; simpl; intros.\n    - inversion H; clear H; subst.\n      econstructor; trivial.\n    - nra_inverter2; try tdot_inverter; qeauto.\n    - nra_inverter2; try tdot_inverter; qeauto.\n    - nra_inverter2; try tdot_inverter; qeauto.\n    - nra_inverter2; try tdot_inverter; qeauto.\n    - nra_inverter2; try tdot_inverter; qeauto.\n    - nra_inverter2; try tdot_inverter; qeauto.\n    - nra_inverter2; try tdot_inverter; qeauto.\n    - nra_inverter2; try tdot_inverter; qeauto.\n    - nra_inverter2; try tdot_inverter; qeauto.\n    - nra_inverter2; try tdot_inverter; qeauto.\n    - nra_inverter2; try tdot_inverter; qeauto.\n    - nra_inverter2; try tdot_inverter; qeauto.\n    - nra_inverter2; try tdot_inverter; qeauto.\n    - nra_inverter2; try tdot_inverter; qeauto.\n    - nra_inverter2; try tdot_inverter; qeauto.\n  Qed.\n  \n  Theorem typed_nraenv_core_to_typed_nra_inv {τc} {τenv τin τout} (op:nraenv_core):\n    nra_type τc (nra_of_nraenv_core op) (nra_context_type τenv τin) τout ->\n    nraenv_core_type τc op τenv τin τout.\n  Proof.\n    unfold nra_context_type.\n    apply typed_nraenv_core_to_typed_nra_inv'.\n  Qed.\n\n  Lemma typed_nraenv_core_const_sort_f {τc op τenv τin τout} :\n    nraenv_core_type (rec_sort τc) op τenv τin τout ->\n    nraenv_core_type τc op τenv τin τout.\n  Proof.\n    revert τc op τenv τin τout.\n    induction op; simpl; inversion 1; rtype_equalizer; subst; qeauto.\n    unfold tdot, edot in *.\n    rewrite (assoc_lookupr_drec_sort (odt:=ODT_string)) in H1.\n    econstructor. apply H1.\n  Qed.\n\n  Lemma typed_nraenv_core_const_sort_b {τc op τenv τin τout} :\n      nraenv_core_type τc op τenv τin τout ->\n      nraenv_core_type (rec_sort τc) op τenv τin τout.\n  Proof.\n    revert τc op τenv τin τout.\n    induction op; simpl; inversion 1; rtype_equalizer; subst; qeauto.\n    econstructor.\n    unfold tdot, edot.\n    rewrite (assoc_lookupr_drec_sort (odt:=ODT_string)).\n    apply H1.\n  Qed.\n\n  Lemma typed_nraenv_core_const_sort τc op τenv τin τout :\n    nraenv_core_type (rec_sort τc) op τenv τin τout <->\n    nraenv_core_type τc op τenv τin τout.\n  Proof.\n    split; intros.\n    - apply typed_nraenv_core_const_sort_f; trivial.\n    - apply typed_nraenv_core_const_sort_b; trivial.\n  Qed.\n\nEnd TcNRAEnv.\n\n(* Typed algebraic plan *)\n\nNotation \"Op ▷ A >=> B ⊣ C ; E\" := (nraenv_core_type C Op E A B) (at level 70).\nNotation \"Op @▷ d ⊣ C ; e\" := (tnraenv_core_eval C Op e d) (at level 70).\n\n(* Used to prove type portion of typed directed rewrites *)\n  \nGlobal Hint Constructors nraenv_core_type : qcert.\nGlobal Hint Constructors unary_op_type : qcert.\nGlobal Hint Constructors binary_op_type : qcert.\n\nLtac nraenv_core_inverter := \n  match goal with\n    | [H:Coll _ = Coll _ |- _] => inversion H; clear H\n    | [H: `?τ₁ = Coll₀ (`?τ₂) |- _] => rewrite (Coll_right_inv τ₁ τ₂) in H; subst\n    | [H:  Coll₀ (`?τ₂) = `?τ₁ |- _] => symmetry in H\n    (* Note: do not generalize too hastily on unary_op/binary_op constructors *)\n    | [H:cNRAEnvID ▷ _ >=> _ ⊣ _ ; _ |- _ ] => inversion H; clear H\n    | [H:cNRAEnvEnv ▷ _ >=> _ ⊣  _ ;_ |- _ ] => inversion H; clear H\n    | [H:cNRAEnvMap _ _ ▷ _ >=> _ ⊣  _ ;_ |- _ ] => inversion H; clear H\n    | [H:cNRAEnvMapProduct _ _ ▷ _ >=> _ ⊣  _ ;_ |- _ ] => inversion H; clear H\n    | [H:cNRAEnvMapEnv _ ▷ _ >=> _ ⊣  _ ;_ |- _ ] => inversion H; clear H\n    | [H:cNRAEnvDefault _ _ ▷ _ >=> _ ⊣  _ ;_ |- _ ] => inversion H; clear H\n    | [H:cNRAEnvApp _ _ ▷ _ >=> _ ⊣  _ ;_ |- _ ] => inversion H; clear H\n    | [H:cNRAEnvAppEnv _ _ ▷ _ >=> _ ⊣  _ ;_ |- _ ] => inversion H; clear H\n    | [H:cNRAEnvEither _ _ ▷ _ >=> _ ⊣  _ ;_ |- _ ] => inversion H; clear H\n    | [H:cNRAEnvEitherConcat _ _ ▷ _ >=> _ ⊣  _ ;_ |- _ ] => inversion H; clear H\n    | [H:cNRAEnvProduct _ _ ▷ _ >=> _ ⊣  _ ;_ |- _ ] => inversion H; clear H\n    | [H:cNRAEnvSelect _ _ ▷ _ >=> _ ⊣  _ ;_ |- _ ] => inversion H; clear H\n    | [H:cNRAEnvUnop _ _ ▷ _ >=> _ ⊣  _ ;_ |- _ ] => inversion H; clear H\n    | [H:cNRAEnvBinop _ _ _ ▷ _ >=> _ ⊣  _ ;_ |- _ ] => inversion H; clear H\n    | [H:cNRAEnvConst _ ▷ _ >=> _ ⊣  _ ;_ |- _ ] => inversion H; clear H\n    | [H: (_,_)  = (_,_) |- _ ] => inversion H; clear H\n    | [H: map (fun x2 : string * {τ₀ : rtype₀ | wf_rtype₀ τ₀ = true} =>\n                 (fst x2, ` (snd x2))) ?x0 = [] |- _] => apply (map_rtype_nil x0) in H; simpl in H; subst\n    | [H: (map\n             (fun x : string * {τ₀ : rtype₀ | wf_rtype₀ τ₀ = true} =>\n                (fst x, proj1_sig (snd x))) _)\n          = \n          (map\n             (fun x' : string * {τ₀' : rtype₀ | wf_rtype₀ τ₀' = true} =>\n                (fst x', proj1_sig (snd x'))) _) |- _ ] =>\n      apply map_rtype_fequal in H; trivial\n    | [H:Rec _ _ _ = Rec _ _ _ |- _ ] => generalize (Rec_inv H); clear H; intro H; try subst\n    | [H: context [(_::nil) = map \n                                (fun x : string * {τ₀ : rtype₀ | wf_rtype₀ τ₀ = true} =>\n                                   (fst x, proj1_sig (snd x))) _] |- _] => symmetry in H\n                                                                                         \n    | [H: context [map \n                     (fun x : string * {τ₀ : rtype₀ | wf_rtype₀ τ₀ = true} =>\n                        (fst x, proj1_sig (snd x))) _ = (_::nil) ] |- _] => apply map_eq_cons in H;\n        destruct H as [? [? [? [??]]]]\n    | [H: Coll₀ _ = Coll₀ _ |- _ ] => inversion H; clear H\n    | [H: Rec₀ _ _ = Rec₀ _ _ |- _ ] => inversion H; clear H\n    | [H: _ ▷ _ >=> snd ?x ⊣  _ ;_ |- _] => destruct x; simpl in *; subst\n    | [H:unary_op_type OpBag _ _ |- _ ] => inversion H; clear H; subst\n    | [H:unary_op_type OpFlatten _ _ |- _ ] => inversion H; clear H; subst\n    | [H:unary_op_type (OpRec _) _ _ |- _ ] => inversion H; clear H; subst\n    | [H:unary_op_type (OpDot _) _ _ |- _ ] => inversion H; clear H; subst\n    | [H:unary_op_type (OpRecProject _) _ _ |- _ ] => inversion H; clear H; subst\n    | [H:unary_op_type (OpRecRemove _) _ _ |- _ ] => inversion H; clear H; subst\n    | [H:unary_op_type OpLeft _ _ |- _ ] => inversion H; clear H; subst\n    | [H:unary_op_type OpRight _ _ |- _ ] => inversion H; clear H; subst\n    | [H:binary_op_type OpRecConcat _ _ _ |- _ ] => inversion H; clear H\n    | [H:binary_op_type OpAnd _ _ _ |- _ ] => inversion H; clear H\n    | [H:binary_op_type OpRecMerge _ _ _ |- _ ] => inversion H; clear H\n  end; try rtype_equalizer; try assumption; try subst; simpl in *; try nraenv_core_inverter.\n\n(* inverts, then tries and solve *)\nLtac nraenv_core_inferer := try nraenv_core_inverter; subst; try qeauto.\n\n(* simplifies when a goal evaluates an expression over well-typed data *)\n\nLtac input_well_typed :=\n  repeat progress\n         match goal with\n           | [HO:?op ▷ ?τin >=> ?τout ⊣  ?τc ; ?τenv,\n              HI:?x ▹ ?τin,\n              HC:bindings_type ?c ?τc,\n              HE:?env ▹ ?τenv\n              |- context [(nraenv_core_eval ?h ?c ?op ?env ?x)]] =>\n             let xout := fresh \"dout\" in\n             let xtype := fresh \"τout\" in\n             let xeval := fresh \"eout\" in\n             destruct (typed_nraenv_core_yields_typed_data c _ _ op HC HE HI HO)\n               as [xout [xeval xtype]]; rewrite xeval in *; simpl\n         end.\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/cNRAEnv/Typing/TcNRAEnv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.2678755402412479}}
{"text": "(* QuickChick Prelude *)\nSet Warnings \"-extraction-opaque-accessed,-extraction\".\nSet Warnings \"-notation-overridden,-parsing\".\n\nRequire Import String List. Open Scope string.\n\nFrom QuickChick Require Import QuickChick Tactics.\nFrom mathcomp Require Import ssreflect ssrfun ssrbool ssrnat eqtype seq.\nImport QcDefaultNotation. Open Scope qc_scope.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\n(* End prelude *)\n\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.lia.Lia.\nRequire Import Imp.\nRequire Import Maps.\n\n\nDefinition Assertion := state -> Prop.\n\nDefinition assert_implies (P Q : Assertion) : Prop :=\n  forall st, P st -> Q st.\n\nNotation \"P ->> Q\" := (assert_implies P Q)\n                      (at level 80) : hoare_spec_scope.\nOpen Scope hoare_spec_scope.\n\nNotation \"P <<->> Q\" :=\n  (P ->> Q /\\ Q ->> P) (at level 80) : hoare_spec_scope.\n\nDefinition hoare_triple\n           (P:Assertion) (c:com) (Q:Assertion) : Prop :=\n  forall st st',\n     c / st \\\\ st'  ->\n     P st  ->\n     Q st'.\n\nNotation \"{{ P }}  c  {{ Q }}\" :=\n  (hoare_triple P c Q) (at level 90, c at next level)\n  : hoare_spec_scope.\n\nTheorem hoare_post_true : forall (P Q : Assertion) c,\n  (forall st, Q st) ->\n  {{P}} c {{Q}}.\nAdmitted. (* Higher Order *)\n\nTheorem hoare_pre_false : forall (P Q : Assertion) c,\n  (forall st, ~(P st)) ->\n  {{P}} c {{Q}}.\nAdmitted. (* Higher Order *)\n\nDefinition assn_sub X a P : Assertion :=\n  fun (st : state) =>\n    P (t_update st X (aeval st a)).\n\nNotation \"P [ X |-> a ]\" := (assn_sub X a P) (at level 10).\n\nTheorem hoare_asgn : forall Q X a,\n  {{assn_sub X a Q }} (X ::= a) {{Q}}.\nAdmitted. (* Higher Order *)\n\nTheorem hoare_asgn_fwd :\n  (forall {X Y: Type} {f g : X -> Y},\n     (forall (x: X), f x = g x) ->  f = g) ->\n  forall m a P,\n  {{fun st => P st /\\ t_lookup st X = m}}\n    X ::= a\n  {{fun st => P (t_update st X m) \n            /\\ t_lookup st X = aeval (t_update st X m) a }}.\nAdmitted. (* Higher Order *)\n\nTheorem hoare_asgn_fwd_exists :\n  (forall {X Y: Type} {f g : X -> Y},\n     (forall (x: X), f x = g x) ->  f = g) ->\n  forall a P,\n  {{fun st => P st}}\n    X ::= a\n  {{fun st => exists m, P (t_update st X m) /\\\n                t_lookup st X = aeval (t_update st X m) a }}.\nAdmitted. (* So Higher Order it is not even funny *)\n\nTheorem hoare_consequence_pre : forall (P P' Q : Assertion) c,\n  {{P'}} c {{Q}} ->\n  P ->> P' ->\n  {{P}} c {{Q}}.\nAdmitted. (* Higher Order *)\n\nTheorem hoare_consequence_post : forall (P Q Q' : Assertion) c,\n  {{P}} c {{Q'}} ->\n  Q' ->> Q ->\n  {{P}} c {{Q}}.\nAdmitted. (* Higher Order *)\n\nTheorem hoare_consequence : forall (P P' Q Q' : Assertion) c,\n  {{P'}} c {{Q'}} ->\n  P ->> P' ->\n  Q' ->> Q ->\n  {{P}} c {{Q}}.\nAdmitted. (* Higher Order *)\n\nLemma silly1 : forall (P : nat -> nat -> Prop) (Q : nat -> Prop),\n  (forall x y : nat, P x y) ->\n  (forall x y : nat, P x y -> Q x) ->\n  Q 42.\nAdmitted. (* Higher Order *)\n\nLemma silly2 :\n  forall (P : nat -> nat -> Prop) (Q : nat -> Prop),\n  (exists y, P 42 y) ->\n  (forall x y : nat, P x y -> Q x) ->\n  Q 42.\nAdmitted. (* Higher Order *)\n\nTheorem hoare_skip : forall P,\n     {{P}} SKIP {{P}}.\nAdmitted. (* Higher Order *)\n\nTheorem hoare_seq : forall P Q R c1 c2,\n     {{Q}} c2 {{R}} ->\n     {{P}} c1 {{Q}} ->\n     {{P}} c1;;c2 {{R}}.\nAdmitted. (* Higher Order *)\n\nDefinition bassn b : Assertion :=\n  fun st => (beval st b = true).\n\nLemma bexp_eval_true : forall b st,\n  beval st b = true -> (bassn b) st.\nAdmitted. (* QuickChick bexp_eval_true. *)\n\nLemma bexp_eval_false : forall b st,\n  beval st b = false -> ~ ((bassn b) st).\nAdmitted. (* QuickChick bexp_eval_false. *)\n\nTheorem hoare_if : forall P Q b c1 c2,\n  {{fun st => P st /\\ bassn b st}} c1 {{Q}} ->\n  {{fun st => P st /\\ ~(bassn b st)}} c2 {{Q}} ->\n  {{P}} (IFB b THEN c1 ELSE c2 FI) {{Q}}.\nAdmitted. (* QuickChick hoare_if *)\n\nLemma hoare_while : forall P b c,\n  {{fun st => P st /\\ bassn b st}} c {{P}} ->\n  {{P}} WHILE b DO c END {{fun st => P st /\\ ~ (bassn b st)}}.\nAdmitted. (* Higher Order *)\n\nTheorem always_loop_hoare : forall P Q,\n  {{P}} WHILE BTrue DO SKIP END {{Q}}.\nAdmitted. (* Higher Order *)\n\n", "meta": {"author": "mpstepan", "repo": "QC-631-Final", "sha": "4cbf25da5bd57252767e13c43cb20acb324178ee", "save_path": "github-repos/coq/mpstepan-QC-631-Final", "path": "github-repos/coq/mpstepan-QC-631-Final/QC-631-Final-4cbf25da5bd57252767e13c43cb20acb324178ee/examples/sf/Hoare.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.2678755402412478}}
{"text": "(** Some derived lemmas for ectx-based languages *)\nFrom iris.program_logic Require Export ectx_language.\nFrom iris.program_logic Require Export total_weakestpre total_lifting.\nFrom iris.proofmode Require Import tactics.\nSet Default Proof Using \"Type\".\n\nSection wp.\nContext {Λ : ectxLanguage} `{irisG Λ Σ} {Hinh : Inhabited (state Λ)}.\nImplicit Types P : iProp Σ.\nImplicit Types Φ : val Λ → iProp Σ.\nImplicit Types v : val Λ.\nImplicit Types e : expr Λ.\nHint Resolve head_prim_reducible head_reducible_prim_step.\n\nLemma twp_lift_head_step {s E Φ} e1 :\n  to_val e1 = None →\n  (∀ σ1, state_interp σ1 ={E,∅}=∗\n    ⌜head_reducible e1 σ1⌝ ∗\n    ∀ e2 σ2 efs, ⌜head_step e1 σ1 e2 σ2 efs⌝ ={∅,E}=∗\n      state_interp σ2 ∗ WP e2 @ s; E [{ Φ }] ∗ [∗ list] ef ∈ efs, WP ef @ s; ⊤ [{ _, True }])\n  ⊢ WP e1 @ s; E [{ Φ }].\nProof.\n  iIntros (?) \"H\". iApply (twp_lift_step _ E)=>//. iIntros (σ1) \"Hσ\".\n  iMod (\"H\" $! σ1 with \"Hσ\") as \"[% H]\"; iModIntro.\n  iSplit; [destruct s; auto|]. iIntros (e2 σ2 efs) \"%\".\n  iApply \"H\". by eauto.\nQed.\n\nLemma twp_lift_pure_head_step {s E Φ} e1 :\n  (∀ σ1, head_reducible e1 σ1) →\n  (∀ σ1 e2 σ2 efs, head_step e1 σ1 e2 σ2 efs → σ1 = σ2) →\n  (|={E}=> ∀ e2 efs σ, ⌜head_step e1 σ e2 σ efs⌝ →\n    WP e2 @ s; E [{ Φ }] ∗ [∗ list] ef ∈ efs, WP ef @ s; ⊤ [{ _, True }])\n  ⊢ WP e1 @ s; E [{ Φ }].\nProof using Hinh.\n  iIntros (??) \">H\". iApply twp_lift_pure_step; eauto.\n  iIntros \"!>\" (????). iApply \"H\"; eauto.\nQed.\n\nLemma twp_lift_atomic_head_step {s E Φ} e1 :\n  to_val e1 = None →\n  (∀ σ1, state_interp σ1 ={E}=∗\n    ⌜head_reducible e1 σ1⌝ ∗\n    ∀ e2 σ2 efs, ⌜head_step e1 σ1 e2 σ2 efs⌝ ={E}=∗\n      state_interp σ2 ∗\n      from_option Φ False (to_val e2) ∗ [∗ list] ef ∈ efs, WP ef @ s; ⊤ [{ _, True }])\n  ⊢ WP e1 @ s; E [{ Φ }].\nProof.\n  iIntros (?) \"H\". iApply twp_lift_atomic_step; eauto.\n  iIntros (σ1) \"Hσ1\". iMod (\"H\" $! σ1 with \"Hσ1\") as \"[% H]\"; iModIntro.\n  iSplit; first by destruct s; auto. iIntros (e2 σ2 efs) \"%\". iApply \"H\"; auto.\nQed.\n\nLemma twp_lift_atomic_head_step_no_fork {s E Φ} e1 :\n  to_val e1 = None →\n  (∀ σ1, state_interp σ1 ={E}=∗\n    ⌜head_reducible e1 σ1⌝ ∗\n    ∀ e2 σ2 efs, ⌜head_step e1 σ1 e2 σ2 efs⌝ ={E}=∗\n      ⌜efs = []⌝ ∗ state_interp σ2 ∗ from_option Φ False (to_val e2))\n  ⊢ WP e1 @ s; E [{ Φ }].\nProof.\n  iIntros (?) \"H\". iApply twp_lift_atomic_head_step; eauto.\n  iIntros (σ1) \"Hσ1\". iMod (\"H\" $! σ1 with \"Hσ1\") as \"[$ H]\"; iModIntro.\n  iIntros (v2 σ2 efs) \"%\".\n  iMod (\"H\" $! v2 σ2 efs with \"[# //]\") as \"(% & $ & $)\"; subst; auto.\nQed.\n\nLemma twp_lift_pure_det_head_step {s E Φ} e1 e2 efs :\n  (∀ σ1, head_reducible e1 σ1) →\n  (∀ σ1 e2' σ2 efs',\n    head_step e1 σ1 e2' σ2 efs' → σ1 = σ2 ∧ e2 = e2' ∧ efs = efs') →\n  (|={E}=> WP e2 @ s; E [{ Φ }] ∗ [∗ list] ef ∈ efs, WP ef @ s; ⊤ [{ _, True }])\n  ⊢ WP e1 @ s; E [{ Φ }].\nProof using Hinh. eauto using twp_lift_pure_det_step. Qed.\n\nLemma twp_lift_pure_det_head_step_no_fork {s E Φ} e1 e2 :\n  to_val e1 = None →\n  (∀ σ1, head_reducible e1 σ1) →\n  (∀ σ1 e2' σ2 efs',\n    head_step e1 σ1 e2' σ2 efs' → σ1 = σ2 ∧ e2 = e2' ∧ [] = efs') →\n  WP e2 @ s; E [{ Φ }] ⊢ WP e1 @ s; E [{ Φ }].\nProof using Hinh.\n  intros. rewrite -(twp_lift_pure_det_step e1 e2 []) /= ?right_id; eauto.\nQed.\nEnd wp.\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/total_ectx_lifting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.26784288379076515}}
{"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.\nRequire Import Utf8.\n\nModule Ir.\n\nModule GVN4.\n\n(**************************************************************\n  This file proves validity of the fourth GVN optimization case:\n 4. Either p or q is computed by a series of gep inbounds with\n     positive offsets, based on the same base pointer.\n\n  High-level structure of proof is as follows:\n  (1) We define the notion of `gepinbs p q p0`, meaning\n      that p and q have same base pointer p0, and have gep inbounds\n      with positive offsets.\n  (2) We show that if p0 is a logical pointer, p and q are the same.\n  (3) We show that if p0 is a physical pointer,\n      after calculation, given p=Phy(o1, I1, cid1) and\n      q=Phy(o2, I2, cid2), min(I1) = min(I2) /\\ max(I2) = max(I2)\n      /\\ o1 = o2 /\\ cid1 = cid2. This relation is defined as\n      `phys_minmaxI p q`.\n      (2) and (3) are shown in `gepinbs_after_icmpeq_true`.\n  (4) We show that if `phy_minmaxI p q` holds, then refinement\n      holds for all instructions that has operand p replaced\n      with q.\n **************************************************************)\n\nDefinition posofs (ofs:nat) (t:Ir.ty) :=\n  ofs * Ir.ty_bytesz t < Nat.shiftl 1 (Ir.PTRSZ - 1).\n\nInductive gepinbs: Ir.Memory.t -> Ir.val -> Ir.val -> Ir.ptrval -> Prop :=\n| gi_one: (* should have at least one GEP *)\n    forall m p0 p q ofs1 ofs2 t1 t2\n           (HGEP1:p = Ir.SmallStep.gep p0 ofs1 t1 m true)\n           (HGEP2:q = Ir.SmallStep.gep p0 ofs2 t2 m true)\n           (HPOS1:posofs ofs1 t1)\n           (HPOS2:posofs ofs2 t2),\n      gepinbs m p q p0\n| gi_succ_l:\n    forall m p q p0 ofs p' t\n           (HBASE:gepinbs m (Ir.ptr p) (Ir.ptr q) p0)\n           (HGEP1:p' = Ir.SmallStep.gep p ofs t m true)\n           (HPOS:posofs ofs t),\n      gepinbs m p' (Ir.ptr q) p0\n| gi_succ_r:\n    forall m p q p0 ofs q' t\n           (HBASE:gepinbs m (Ir.ptr p) (Ir.ptr q) p0)\n           (HGEP1:q' = Ir.SmallStep.gep q ofs t m true)\n           (HPOS:posofs ofs t),\n      gepinbs m (Ir.ptr p) q' p0.\n\nDefinition phys_minmaxI (p q:Ir.ptrval): Prop :=\n  exists o I1 I2 cid ofsmin ofsmax,\n    (p = Ir.pphy o I1 cid /\\ q = Ir.pphy o I2 cid /\\\n     list_min ofsmin I1 /\\ list_min ofsmin I2 /\\\n     list_max ofsmax I1 /\\ list_max ofsmax I2).\n\n\n(*********************************************************\n Important property of gepinbs:\n  If gepinbs p q holds, and `icmp eq p, q` evaluates\n    to true, then either p = q or phys_minmaxI holds.\n *********************************************************)\n\nLemma gepinbs_log_neverphy:\n  forall m v1 l o v2 p0\n         (HP1:Ir.ptr (Ir.plog l o) = v1)\n         (HGEPINBS:gepinbs m v1 v2 p0),\n    ~ exists o2 I2 cid2, v2 = Ir.ptr (Ir.pphy o2 I2 cid2).\nProof.\n  intros.\n  generalize dependent l.\n  generalize dependent o.\n  induction HGEPINBS.\n  { intros. inv HP1. intros HH. inv HH. inv H0. inv H1.\n    unfold Ir.SmallStep.gep in *.\n    des_ifs.\n  }\n  { unfold Ir.SmallStep.gep in HGEP1.\n    des_ifs. intros. inv HP1.\n    intros HH. inv HH. inv H. inv H0. inv H.\n    exploit IHHGEPINBS. ss. eexists. eexists. eexists. ss.\n    eauto. }\n  { intros. intros HH. inv HH. inv H. inv H0.\n    unfold Ir.SmallStep.gep in H.\n    des_ifs.\n    exploit IHHGEPINBS. ss. do 3 eexists. ss. eauto.\n    exploit IHHGEPINBS. ss. do 3 eexists. ss. eauto.\n  }\nQed.\n\nLemma gepinbs_phy_neverlog:\n  forall m v1 o I cid v2 p0\n         (HP1:Ir.ptr (Ir.pphy o I cid) = v1)\n         (HGEPINBS:gepinbs m v1 v2 p0),\n    ~ exists l2 o2, v2 = Ir.ptr (Ir.plog l2 o2).\nProof.\n  intros.\n  generalize dependent o.\n  generalize dependent I.\n  generalize dependent cid.\n  induction HGEPINBS.\n  { intros. inv HP1. intros HH. inv HH. inv H0. inv H1.\n    unfold Ir.SmallStep.gep in *. des_ifs.\n  }\n  { intros. intros HH. inv HH. inv H. inv H0.\n    unfold Ir.SmallStep.gep in HP1.\n    des_ifs.\n    exploit IHHGEPINBS. ss. do 3 eexists. ss. eauto.\n    exploit IHHGEPINBS. ss. do 3 eexists. ss.\n  }\n  { intros. intros HH. inv HH. inv H.\n    unfold Ir.SmallStep.gep in H0.\n    des_ifs.\n    exploit IHHGEPINBS. ss. eexists. eexists. eexists. ss.\n  }\nQed.\n\nLemma gepinbs_phy_samecid:\n  forall m v1 v2 o1 o2 I1 I2 cid1 cid2 p0\n         (HP1:Ir.ptr (Ir.pphy o1 I1 cid1) = v1)\n         (HP1:Ir.ptr (Ir.pphy o2 I2 cid2) = v2)\n         (HGEPINBS:gepinbs m v1 v2 p0),\n    cid1 = cid2.\nProof.\n  intros.\n  generalize dependent o1.\n  generalize dependent o2.\n  generalize dependent I1.\n  generalize dependent I2.\n  generalize dependent cid1.\n  generalize dependent cid2.\n  induction HGEPINBS.\n  { intros. inv HP1.\n    unfold Ir.SmallStep.gep in *. des_ifs.\n  }\n  { intros. inv HP0.\n    unfold Ir.SmallStep.gep in HP1.\n    des_ifs.\n    exploit IHHGEPINBS. ss. ss. eauto.\n    exploit IHHGEPINBS. ss. ss. eauto.\n  }\n  { intros. inv HP0.\n    unfold Ir.SmallStep.gep in *. des_ifs.\n    exploit IHHGEPINBS. ss. ss. eauto.\n    exploit IHHGEPINBS. ss. ss. eauto.\n  }\nQed.\n\nLemma gep_phy_Ilb:\n  forall o1 o2 I1 I2 cid1 cid2 ofs t m\n         (HMIN:exists n, list_min n I1)\n         (HGEP:(Ir.ptr (Ir.pphy o2 I2 cid2)) =\n               Ir.SmallStep.gep (Ir.pphy o1 I1 cid1) ofs t m true)\n         (HPOS:posofs ofs t),\n  exists n, (list_min n (o1::I1) /\\ list_min n I2).\nProof.\n  intros.\n  unfold Ir.SmallStep.gep in HGEP.\n  unfold posofs in HPOS.\n  rewrite <- Nat.ltb_lt in HPOS.\n  rewrite HPOS in HGEP.\n  des_ifs.\n  rewrite Nat.ltb_lt in *.\n  unfold Ir.SmallStep.twos_compl_add.\n  unfold Ir.SmallStep.twos_compl.\n  rewrite Nat.mod_small.\n  unfold list_min.\n  simpl.\n  inv HMIN. inv H.\n  destruct (x <=? o1) eqn:HEQ.\n  { rewrite Nat.leb_le in HEQ.\n    exists x.\n    split. split. eauto.\n    simpl. constructor. ss. ss.\n    split. do 2 right. ss.\n    constructor. ss. constructor. lia. ss.\n  }\n  { rewrite Nat.leb_gt in HEQ.\n    exists o1. split. split. eauto. constructor. ss.\n    rewrite List.Forall_forall in *. intros. eapply H1 in H. lia.\n    split. eauto.\n    constructor. ss. constructor. lia.\n    rewrite List.Forall_forall in *. intros. eapply H1 in H. lia.\n  }\n  rewrite Ir.PTRSZ_MEMSZ.\n  ss.\nQed.\n\nLemma gep_phy_Iub:\n  forall o1 o2 I1 I2 cid1 cid2 ofs t m\n         (HMAX:list_max o1 I1)\n         (HGEP:(Ir.ptr (Ir.pphy o2 I2 cid2)) =\n               Ir.SmallStep.gep (Ir.pphy o1 I1 cid1) ofs t m true)\n         (HPOS:posofs ofs t),\n  list_max o2 I2.\nProof.\n  intros.\n  unfold Ir.SmallStep.gep in HGEP.\n  unfold posofs in HPOS.\n  rewrite <- Nat.ltb_lt in HPOS.\n  rewrite HPOS in HGEP.\n  des_ifs.\n  rewrite Nat.ltb_lt in *.\n  unfold Ir.SmallStep.twos_compl_add.\n  unfold Ir.SmallStep.twos_compl.\n  rewrite Nat.mod_small.\n  unfold list_max.\n  simpl.\n  inv HMAX.\n  split.\n  right. left. ss.\n  constructor. lia. constructor. ss.\n  rewrite List.Forall_forall in *. intros. apply H0 in H1. lia.\n  rewrite Ir.PTRSZ_MEMSZ.\n  ss.\nQed.\n\nLemma gepinbs_log_sameblk:\n  forall m v1 l1 o1 l2 o2 v2 p0\n         (HP1:Ir.ptr (Ir.plog l1 o1) = v1)\n         (HP2:Ir.ptr (Ir.plog l2 o2) = v2)\n         (HGEPINBS:gepinbs m v1 v2 p0),\n    l1 = l2.\nProof.\n  intros.\n  generalize dependent l1.\n  generalize dependent l2.\n  generalize dependent o1.\n  generalize dependent o2.\n  induction HGEPINBS.\n  { intros. inv HP2. unfold Ir.SmallStep.gep in *. des_ifs. }\n  { intros.\n    unfold Ir.SmallStep.gep in HGEP1.\n    des_ifs. exploit IHHGEPINBS. ss. eexists. eauto.\n  }\n  { intros. unfold Ir.SmallStep.gep in HGEP1.\n    des_ifs.\n    exploit IHHGEPINBS. ss. do 3 eexists. ss.\n  }\nQed.\n\nLemma gepinbs_notnum:\n  forall m v1 v2 p0\n         (HGEPINBS:gepinbs m v1 v2 p0),\n    (~ (exists n1, v1 = Ir.num n1)) /\\\n    (~ (exists n2, v2 = Ir.num n2)).\nProof.\n  intros.\n  induction HGEPINBS.\n  { split. intros HH. inv HH. unfold Ir.SmallStep.gep in *. des_ifs.\n    intros HH. inv HH. unfold Ir.SmallStep.gep in *.  des_ifs. }\n  { inv IHHGEPINBS.\n    split; try ss.\n    intros HH.\n    inv HH.\n    unfold Ir.SmallStep.gep in H1. des_ifs. }\n  { inv IHHGEPINBS.\n    split; try ss.\n    intros HH. inv HH.\n    unfold Ir.SmallStep.gep in H1. des_ifs. }\nQed.\n\nLemma gepinbs_icmp_det:\n  forall m v1 v2 p1 p2 p0\n         (HP1:Ir.ptr p1 = v1)\n         (HP2:Ir.ptr p2 = v2)\n         (HGEPINBS:gepinbs m v1 v2 p0),\n    Ir.SmallStep.icmp_eq_ptr_nondet_cond p1 p2 m = false.\nProof.\n  intros.\n  unfold Ir.SmallStep.icmp_eq_ptr_nondet_cond.\n  destruct v1; try congruence.\n  destruct p; try (inv HP1; reflexivity).\n  inv HP1.\n  destruct p2; try reflexivity.\n  eapply gepinbs_log_sameblk in HGEPINBS; try reflexivity.\n  subst b.\n  rewrite Nat.eqb_refl. simpl. des_ifs.\nQed.\n\nLemma phys_minmaxI_cons:\n  forall o I1 I2 cid i\n    (HPMM:phys_minmaxI (Ir.pphy o I1 cid) (Ir.pphy o I2 cid)),\n    phys_minmaxI (Ir.pphy o (i::I1) cid) (Ir.pphy o (i::I2) cid).\nProof.\n  intros.\n  unfold phys_minmaxI in *.\n  inv HPMM. inv H. inv H0. inv H. inv H0. inv H.\n  inv H0. inv H1. inv H2. inv H3. inv H4.\n  inv H. inv H0.\n  exploit list_minmax_le.\n  eapply H1. eapply H3. intros HH.\n  do 4 eexists.\n  destruct (x3 <=? i) eqn:HMIN.\n  { rewrite Nat.leb_le in HMIN.\n    destruct (i <? x4) eqn:HMAX.\n    { rewrite Nat.ltb_lt in HMAX.\n      exists x3. exists x4.\n      split. ss. split. ss.\n      split. eapply list_min_cons; ss.\n      split. eapply list_min_cons; ss.\n      split. eapply list_max_cons. ss. omega.\n      eapply list_max_cons. ss. omega.\n    }\n    { rewrite Nat.ltb_ge in HMAX.\n      exists x3. exists i.\n      split. ss. split. ss.\n      split. eapply list_min_cons; ss.\n      split. eapply list_min_cons; ss.\n      split. eapply list_max_cons2. eassumption. ss.\n      eapply list_max_cons2. eassumption. omega.\n    }\n  }\n  { rewrite Nat.leb_gt in HMIN.\n    destruct (i <? x4) eqn:HMAX.\n    { rewrite Nat.ltb_lt in HMAX.\n      exists i. exists x4.\n      split. ss. split. ss.\n      split. eapply list_min_cons2. eassumption. omega.\n      split. eapply list_min_cons2. eassumption. omega.\n      split. eapply list_max_cons. ss. omega.\n      eapply list_max_cons. ss. omega.\n    }\n    { rewrite Nat.ltb_ge in HMAX.\n      omega.\n    }\n  }\nQed.\n\nLemma phys_minmaxI_refl:\n  forall o I s i\n    (HIN:List.In i I),\n    phys_minmaxI (Ir.pphy o I s) (Ir.pphy o I s).\nProof.\n  unfold phys_minmaxI.\n  intros.\n  destruct I. inv HIN.\n  assert (HH1 := list_min_exists n I).\n  assert (HH2 := list_max_exists n I).\n  inv HH1. inv HH2.\n  do 6 eexists.\n  split. ss.\n  split. ss.\n  do 4 (split; try eassumption).\nQed.\n\nLemma twos_compl_add_PTRSZ:\n  forall o i\n         (HLE:o + i < Ir.MEMSZ),\n  Ir.SmallStep.twos_compl_add o i Ir.PTRSZ = o + i.\nProof.\n  intros.\n  unfold Ir.SmallStep.twos_compl_add.\n  unfold Ir.SmallStep.twos_compl.\n  rewrite Ir.PTRSZ_MEMSZ.\n  rewrite Nat.mod_small. ss.\n  ss.\nQed.\n\nLemma twos_compl_add_PTRSZ':\n  forall o i\n         (HLE:o + i <? Ir.MEMSZ = true),\n  Ir.SmallStep.twos_compl_add o i Ir.PTRSZ = o + i.\nProof.\n  intros.\n  apply twos_compl_add_PTRSZ.\n  rewrite <- Nat.ltb_lt. ss.\nQed.\n\nLemma gepinbs_phy_Imax:\n  forall m o I1 cid p1 p2 p0 o0 I0 cid0\n         (HP1:p1 = (Ir.ptr (Ir.pphy o I1 cid)))\n         (HP0:p0 = Ir.pphy o0 I0 cid0)\n         (HGEP:gepinbs m p1 p2 p0),\n    (exists n, list_max n I1 /\\ list_max n I0 /\\ o < n) \\/\n    (list_max o I1 /\\ (forall n, list_max n I0 -> n <= o)).\nProof.\n  intros.\n  generalize dependent o.\n  generalize dependent I1.\n  generalize dependent I0.\n  generalize dependent cid.\n  induction HGEP.\n  { intros. inv HP1.\n    destruct I0.\n    { right.\n      unfold Ir.SmallStep.gep in *.\n      unfold posofs in *. rewrite <- Nat.ltb_lt in HPOS1, HPOS2.\n      des_ifs.\n      split.\n      {\n        split.\n        {\n          apply list_max_cons. apply list_max_one.\n          rewrite twos_compl_add_PTRSZ. lia.\n          rewrite Nat.ltb_lt in Heq. ss.\n        }\n        {\n          apply list_max_cons. apply list_max_one.\n          rewrite twos_compl_add_PTRSZ. lia.\n          rewrite Nat.ltb_lt in Heq. ss.\n        }\n      }\n      { intros. inv H. inv H0. }\n    }\n    assert (HMAX := list_max_exists n I0).\n    inv HMAX.\n    destruct (x <=? o) eqn:HLE.\n    { right.\n      split.\n      {\n        unfold posofs in *. rewrite <- Nat.ltb_lt in *.\n        unfold Ir.SmallStep.gep in *.\n        des_ifs.\n        split.\n        apply list_max_cons. eapply list_max_cons2. eapply H0.\n        rewrite Nat.leb_le in HLE. lia.\n        rewrite twos_compl_add_PTRSZ. lia.\n        rewrite Nat.ltb_lt in *. ss.\n        apply list_max_cons. eapply list_max_cons2. eapply H0.\n        rewrite Nat.leb_le in HLE. lia.\n        rewrite twos_compl_add_PTRSZ. lia.\n        rewrite Nat.ltb_lt in *. ss.\n      }\n      { intros. eapply list_max_inj_l with (n := x) in H1; try ss.\n        rewrite Nat.leb_le in HLE. omega. }\n    }\n    { left. exists x.\n      unfold posofs in *. rewrite <- Nat.ltb_lt in *.\n      unfold Ir.SmallStep.gep in *.\n      des_ifs.\n      split.\n      {\n        apply list_max_cons. apply list_max_cons. ss.\n        rewrite Nat.leb_gt in HLE.\n        omega.\n        rewrite Nat.leb_gt in HLE.\n        rewrite twos_compl_add_PTRSZ in HLE. eapply le_trans.\n        instantiate (1 := o0 + ofs1 * Ir.ty_bytesz t1).\n        eapply Nat.le_add_r.\n        rewrite Nat.ltb_lt in Heq. omega.\n        rewrite Nat.ltb_lt in Heq. ss.\n      }\n      { split. ss.\n        apply Nat.leb_gt in HLE.\n        apply Nat.ltb_lt. ss.\n      }\n    }\n  }\n  { intros.\n    inv HP0.\n    unfold posofs in HPOS.\n    rewrite <- Nat.ltb_lt in HPOS.\n    unfold Ir.SmallStep.gep in HP1.\n    des_ifs.\n    exploit IHHGEP.\n    ss. ss. intros HH. inv HH.\n    { inv H. inv H0. inv H1. clear IHHGEP.\n      remember (Ir.SmallStep.twos_compl_add n (ofs * Ir.ty_bytesz t)\n                                            Ir.PTRSZ) as n'.\n      destruct (x <=? n') eqn:HLE.\n      { rewrite Nat.leb_le in HLE.\n        right. split.\n        apply list_max_cons. eapply list_max_cons2. eapply H. ss.\n        subst n'.\n        rewrite twos_compl_add_PTRSZ.\n        apply Nat.le_add_r. rewrite Nat.ltb_lt in Heq. ss.\n        intros. apply list_max_inj_l with (n := x) in H1. omega. ss.\n      }\n      { left.\n        exists x.\n        split.\n        {  apply list_max_cons. apply list_max_cons. ss.\n          subst n'.\n          rewrite Nat.leb_gt in HLE. rewrite twos_compl_add_PTRSZ in *. omega.\n          rewrite Nat.ltb_lt in Heq. omega.\n          rewrite Nat.ltb_lt in Heq. omega.\n          subst n'.\n          rewrite Nat.leb_gt in HLE. rewrite twos_compl_add_PTRSZ in *.\n          lia. rewrite Nat.ltb_lt in Heq. ss.\n        }\n        { split. ss. rewrite Nat.leb_gt in HLE. omega. }\n      }\n    }\n    { inv H. right.\n      split.\n      { apply list_max_cons. eapply list_max_cons2. eassumption.\n        rewrite twos_compl_add_PTRSZ.\n        apply Nat.le_add_r. rewrite Nat.ltb_lt in Heq. ss.\n        rewrite twos_compl_add_PTRSZ.\n        apply Nat.le_add_r. rewrite Nat.ltb_lt in Heq. ss.\n      }\n      { intros. apply H1 in H.\n        rewrite twos_compl_add_PTRSZ'. lia.\n        ss.\n      }\n    }\n  }\n  { intros. inv HP1. eapply IHHGEP. ss. ss. }\nQed.\n\nLemma gepinbs_sym:\n  forall m p1 p2 p0\n         (HGEP:gepinbs m p1 p2 p0),\n    gepinbs m p2 p1 p0.\nProof.\n  intros.\n  induction HGEP.\n  { eapply gi_one. eassumption. eassumption. ss. ss. }\n  { eapply gi_succ_r. eassumption. eassumption. ss. }\n  { eapply gi_succ_l. eassumption. eassumption. ss. }\nQed.\n\nLemma gepinbs_phy_I_In:\n  forall m p1 p2 p0 o I cid\n         (HP1:p1 = Ir.ptr (Ir.pphy o I cid))\n         (HGEP:gepinbs m p1 p2 p0),\n    List.In o I.\nProof.\n  intros.\n  generalize dependent o.\n  generalize dependent I.\n  generalize dependent cid.\n  induction HGEP.\n  { intros. inv HP1. unfold Ir.SmallStep.gep in *.\n    des_ifs. right. left. ss. right. left. ss. }\n  { intros. inv HP1. unfold Ir.SmallStep.gep in *.\n    des_ifs. right. left. ss. right. left. ss. }\n  { intros. eapply IHHGEP. eassumption. }\nQed.\n\nLemma gepinbs_phy_Imin:\n  forall m o I1 cid p1 p2 p0 o0 I0\n         (HP1:p1 = (Ir.ptr (Ir.pphy o I1 cid)))\n         (HP0:p0 = Ir.pphy o0 I0 cid)\n         (HGEP:gepinbs m p1 p2 p0),\n    (exists n, list_min n I1 /\\ list_min n I0) \\/\n     list_min o0 I1.\nProof.\n  intros.\n  generalize dependent o.\n  generalize dependent o0.\n  generalize dependent I1.\n  generalize dependent I0.\n  generalize dependent cid.\n  induction HGEP.\n  { intros. inv HP1. unfold Ir.SmallStep.gep in H.\n    unfold posofs in *. rewrite <- Nat.ltb_lt in HPOS1, HPOS2. des_ifs.\n    { destruct I0.\n      { right. eapply list_min_cons2.\n        apply list_min_one.\n        rewrite twos_compl_add_PTRSZ'. apply Nat.le_add_r.\n        ss.\n      }\n      { assert (HH := list_min_exists n I0).\n        inv HH.\n        destruct (x <? o0) eqn:HLE.\n        { left. exists x.\n          split; try ss.\n          apply list_min_cons.\n          apply list_min_cons.\n          ss.\n          rewrite twos_compl_add_PTRSZ'. rewrite Nat.ltb_lt in HLE.\n          lia. ss.\n          rewrite Nat.ltb_lt in HLE. omega.\n        }\n        { destruct (x <=? Ir.SmallStep.twos_compl_add o0 (ofs1 * Ir.ty_bytesz t1)\n                          Ir.PTRSZ)\n                   eqn:HLE2.\n          { right. rewrite Nat.ltb_ge in HLE.\n            eapply list_min_cons2.\n            apply list_min_cons.\n            eassumption.\n            rewrite Nat.leb_le in HLE2. ss. ss. }\n          { rewrite Nat.ltb_ge in HLE. rewrite Nat.leb_gt in HLE2.\n            right. eapply list_min_cons2.\n            eapply list_min_cons2.\n            eassumption.\n            omega.\n            rewrite twos_compl_add_PTRSZ'. lia.\n            ss.\n          }\n        }\n      }\n    }\n  }\n  { intros. inv HP0. dup HP1.\n    unfold Ir.SmallStep.gep in HP1. dup HPOS. unfold posofs in HPOS.\n    rewrite <- Nat.ltb_lt in HPOS.\n    des_ifs.\n    exploit IHHGEP. ss. ss. intros HH.\n    inv HH.\n    { inv H. inv H0. left.\n      symmetry in HP0.\n      dup HP0.\n      apply gep_phy_Ilb in HP0.\n      inv HP0. inv H0. \n      apply list_min_In in H2.\n      exists x0.\n      assert (x = x0).\n      { eapply list_min_inj_l. eapply H.  eapply H2. }\n      subst x.\n      split.\n      ss. ss. eapply gepinbs_phy_I_In. ss. eassumption.\n      eexists. eassumption. assumption.\n    }\n    { symmetry in HP0.\n      apply gep_phy_Ilb in HP0.\n      inv HP0. inv H0.\n      apply list_min_In in H1.\n      assert (x = o0).\n      { eapply list_min_inj_l. eapply H1. eassumption. }\n      subst x.\n      right. ss.\n      eapply gepinbs_phy_I_In. ss. eassumption.\n      eexists. eapply H.\n      ss.\n    }\n  }\n  { intros. inv HP0. inv HP1.\n    exploit IHHGEP. ss. ss. eauto. }\nQed.\n\nLemma gepinbs_phy_Imin2:\n  forall m o I1 cid p1 p2 p0 o0 I0 n\n         (HP1:p1 = (Ir.ptr (Ir.pphy o I1 cid)))\n         (HP0:p0 = Ir.pphy o0 I0 cid)\n         (HGEP:gepinbs m p1 p2 p0)\n         (HMIN:list_min n I1),\n    n <= o.\nProof.\n  intros.\n  generalize dependent o.\n  generalize dependent o0.\n  generalize dependent I1.\n  generalize dependent I0.\n  generalize dependent cid.\n  induction HGEP.\n  { intros. inv HP1. unfold Ir.SmallStep.gep in H.\n    unfold posofs in *. rewrite <- Nat.ltb_lt in HPOS1, HPOS2. des_ifs.\n    inv HMIN. rewrite List.Forall_forall in H0.\n        exploit H0. right. ss. left. ss.\n        intros. ss.\n  }\n  { intros. inv HP0.\n    unfold Ir.SmallStep.gep in HP1. unfold posofs in HPOS.\n    rewrite <- Nat.ltb_lt in HPOS.\n    des_ifs.\n    inv HMIN. rewrite List.Forall_forall in H0.\n    exploit H0. right. left. ss. intros. omega.\n  }\n  { ss. }\nQed.\n\nLemma gepinbs_phy_base:\n  forall m o1 I1 cid p1 p2 p0\n         (HP1:p1 = (Ir.ptr (Ir.pphy o1 I1 cid)))\n         (HGEP:gepinbs m p1 p2 p0),\n    exists o2 I2, p0 = Ir.pphy o2 I2 cid.\nProof.\n  intros.\n  generalize dependent o1.\n  generalize dependent I1.\n  generalize dependent cid.\n  induction HGEP.\n  { intros. inv HP1. unfold Ir.SmallStep.gep in H.\n    des_ifs; do 3 eexists; ss.\n  }\n  { intros. inv HP1. unfold Ir.SmallStep.gep in H.\n    des_ifs.\n    exploit IHHGEP. ss. eauto.\n    exploit IHHGEP. ss. eauto.\n  }\n  { ss. }\nQed.\n\nLemma gepinbs_phy_Imin3:\n  forall m o1 o2 I1 cid p1 p2 p0 I2\n         (HP1:p1 = (Ir.ptr (Ir.pphy o1 I1 cid)))\n         (HP2:p2 = (Ir.ptr (Ir.pphy o2 I2 cid)))\n         (HGEP:gepinbs m p1 p2 p0),\n    exists n, list_min n I1 /\\ list_min n I2.\nProof.\n  intros.\n  generalize dependent o1.\n  generalize dependent o2.\n  generalize dependent I1.\n  generalize dependent I2.\n  generalize dependent cid.\n  induction HGEP.\n  { intros. inv HP1. inv HP2. unfold Ir.SmallStep.gep in *.\n    unfold posofs in HPOS1, HPOS2. rewrite <- Nat.ltb_lt in HPOS1, HPOS2. des_ifs.\n    assert (HH2 := list_min_exists n l).\n    inv HH2.\n    exists x. split.\n    apply list_min_swap.\n    apply list_min_cons. ss. rewrite twos_compl_add_PTRSZ'.\n    apply list_min_hd in H. lia.\n    ss.\n    apply list_min_swap.\n    apply list_min_cons.  ss.\n    rewrite twos_compl_add_PTRSZ'. apply list_min_hd in H. lia. ss.\n  }\n  { intros. inv HP1. inv HP2. dup H. dup HPOS.\n    unfold Ir.SmallStep.gep in H. unfold posofs in HPOS.\n    rewrite <- Nat.ltb_lt in HPOS.\n    des_ifs.\n    exploit IHHGEP. ss. ss. intros HH.\n    inv HH. inv H.\n    exists x. split; try assumption.\n    dup HGEP. eapply gepinbs_phy_base in HGEP0; try reflexivity.\n    inv HGEP0. inv H.\n    assert (x <= n).\n    { eapply gepinbs_phy_Imin2. ss. ss. eassumption. ss. }\n    apply list_min_cons; try omega.\n    apply list_min_cons.\n    ss.\n    rewrite twos_compl_add_PTRSZ'. lia. ss.\n  }\n  { intros.\n    inv HP2. inv HP1.\n    unfold Ir.SmallStep.gep in H. unfold posofs in HPOS. rewrite <- Nat.ltb_lt in HPOS.\n    des_ifs.\n    exploit IHHGEP. ss. ss. intros HH.\n    inv HH. inv H.\n    exists x. split; try assumption.\n    dup HGEP. eapply gepinbs_phy_base in HGEP; try reflexivity.\n    inv HGEP. inv H.\n    assert (x <= n).\n    { eapply gepinbs_phy_Imin2. ss. ss. apply gepinbs_sym in HGEP0.\n      eassumption. ss. }\n    apply list_min_cons; try omega.\n    apply list_min_cons. ss.\n    rewrite twos_compl_add_PTRSZ'. lia. ss.\n  }\nQed.\n\nLemma gep_phy_Iub2:\n  forall o I cid o' I' cid' ofs t m\n         (HGEP:Ir.SmallStep.gep (Ir.pphy o I cid) ofs t m true = Ir.ptr (Ir.pphy o' I' cid'))\n         (HPOS:posofs ofs t),\n    list_max o' I' \\/ (exists n, list_max n I /\\ list_max n I').\nProof.\n  intros.\n  destruct I.\n  { left.\n    unfold Ir.SmallStep.gep in HGEP.\n    unfold posofs in HPOS.\n    des_ifs.\n    { unfold Ir.SmallStep.twos_compl_add.\n      unfold Ir.SmallStep.twos_compl.\n      unfold list_max. split.\n      right. constructor. ss.\n      constructor. rewrite Nat.mod_small. lia.\n      rewrite Ir.PTRSZ_MEMSZ. rewrite Nat.ltb_lt in Heq0. ss.\n      constructor. ss.\n      constructor.\n    }\n    { rewrite Nat.ltb_ge in Heq. omega. }\n  }\n  { assert (HH := list_max_exists n I).\n    inv HH.\n    unfold Ir.SmallStep.gep in HGEP.\n    des_ifs.\n    { destruct (x <=? Ir.SmallStep.twos_compl_add o (ofs * Ir.ty_bytesz t) Ir.PTRSZ)\n               eqn:HLE.\n      { left.\n        constructor.\n        right. left. ss.\n        constructor. rewrite twos_compl_add_PTRSZ. lia.\n          rewrite Nat.ltb_lt in Heq0. ss.\n        constructor. ss.\n        inv H.\n        rewrite List.Forall_forall in *.\n        intros. apply H1 in H. rewrite Nat.leb_le in HLE.\n          rewrite twos_compl_add_PTRSZ. eapply Nat.le_trans. eapply H.\n          rewrite twos_compl_add_PTRSZ in HLE. ss.\n          rewrite Nat.ltb_lt in Heq0. ss. rewrite Nat.ltb_lt in Heq0. ss.\n      }\n\n      { right. exists x.\n        split. ss.\n        rewrite Nat.leb_gt in HLE.\n        rewrite twos_compl_add_PTRSZ in HLE.\n        constructor. right. right. inv H. ss.\n        constructor. \n        lia.\n        constructor. rewrite twos_compl_add_PTRSZ. lia.\n        rewrite Nat.ltb_lt in Heq0. lia.\n        inv H. rewrite List.Forall_forall in *.\n        intros. apply H1 in H. ss.\n        rewrite Nat.ltb_lt in Heq0. ss.\n      }\n    }\n    { unfold posofs in HPOS. rewrite Nat.ltb_ge in Heq. omega. }\n  }\nQed.\n\nTheorem gepinbs_after_icmpeq_true:\n  forall md st st' r ptrty op1 op2 v1 v2 e pbase\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    (* gepinbs holds *)\n    (HEQPROP:gepinbs (Ir.Config.m st) v1 v2 pbase)\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 \\/\n    (exists p1 p2, Ir.ptr p1 = v1 /\\ Ir.ptr p2 = v2 /\\ phys_minmaxI p1 p2).\nProof.\n  intros.\n  inv HSTEP; try congruence.\n  { inv HISTEP;try congruence.\n    { unfold Ir.SmallStep.inst_det_step in HNEXT. rewrite <- HINST in HNEXT.\n      rewrite <- HOP1, <- HOP2 in HNEXT.\n      dup HEQPROP. apply gepinbs_notnum in HEQPROP0.\n      inv HEQPROP0.\n      destruct v1.\n      { exfalso. eapply H. eexists. ss. }\n      destruct v2.\n      { exfalso. eapply H0. eexists. ss. }\n      des_ifs.\n      clear H H0.\n      destruct p.\n      { (* log *)\n        destruct p0.\n        { dup HEQPROP.\n          eapply gepinbs_log_sameblk in HEQPROP; try reflexivity.\n          subst b0.\n          unfold Ir.SmallStep.icmp_eq_ptr in Heq. rewrite Nat.eqb_refl in Heq.\n          inv Heq.\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          unfold Ir.SmallStep.to_num in HTRUE.\n          des_ifs. rewrite Nat.eqb_eq in Heq. subst n.\n          left. ss.\n          { unfold Ir.Config.cur_inst in HINST.\n            unfold Ir.Config.cur_fdef_pc in HINST.\n            des_ifs. }\n        }\n        { (* cannot be phy *)\n          eapply gepinbs_log_neverphy in HEQPROP; try reflexivity.\n          exfalso. apply HEQPROP. do 3 eexists. ss.\n        }\n      }\n      { (* phy *)\n        destruct p0.\n        { (* cannot be log *)\n          eapply gepinbs_phy_neverlog in HEQPROP; try reflexivity.\n          exfalso. apply HEQPROP. do 3 eexists.\n        }\n        { right.\n          unfold Ir.SmallStep.icmp_eq_ptr in Heq.\n          unfold Ir.SmallStep.p2N in Heq.\n          rewrite Nat.min_id in Heq.\n          unfold Ir.SmallStep.twos_compl in Heq.\n          rewrite Ir.PTRSZ_MEMSZ in Heq.\n          rewrite Nat.mod_small in Heq.\n          inv Heq.\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          unfold Ir.SmallStep.to_num in HTRUE.\n          inv HTRUE.\n          des_ifs.\n          rewrite Nat.eqb_eq in Heq. subst n.\n          dup HEQPROP.\n          eapply gepinbs_phy_samecid in HEQPROP0; try reflexivity.\n          subst o.\n          dup HEQPROP. eapply gepinbs_phy_base in HEQPROP0; try reflexivity.\n          inv HEQPROP0. inv H.\n          eexists. eexists. split. ss. split. ss.\n          unfold phys_minmaxI.\n          dup HEQPROP.\n          eapply gepinbs_phy_Imin3 in HEQPROP0; try reflexivity.\n          dup HEQPROP.\n          eapply gepinbs_phy_Imax in HEQPROP1.\n          2: ss. 2: ss.\n          apply gepinbs_sym in HEQPROP.\n          eapply gepinbs_phy_Imax in HEQPROP.\n          2:ss. 2:ss.\n          inv HEQPROP0. inv H.\n          inv HEQPROP.\n          { inv H. inv H3. inv H4.\n            inv HEQPROP1.\n            { inv H4. inv H6. inv H7.\n              assert (x2 = x3).\n              { eapply list_max_inj_l. eapply H3. ss. }\n              subst x2.\n              do 6 eexists.\n              split. ss. split. ss.\n              split. eassumption.\n              split. ss.\n              split. eassumption.\n              ss.\n            }\n            { inv H4. apply H7 in H3.\n              omega. }\n          }\n          { inv H.\n            inv HEQPROP1.\n            { inv H. inv H5. inv H6. apply H4 in H5. omega. }\n            { inv H. \n              do 6 eexists.\n              split. ss. split. ss.\n              split. eassumption. split. ss.\n              split. eassumption. ss.\n            }\n          }\n          { unfold Ir.Config.cur_inst in HINST. unfold Ir.Config.cur_fdef_pc in HINST.\n            des_ifs.\n          }\n          { inv HWF.\n            exploit wf_ptr. rewrite <- HOP2. reflexivity.\n            intros HH.\n            unfold Ir.Config.ptr_wf in HH.\n            inv HH. eapply H0. reflexivity.\n          }\n        }\n      }\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.\n        unfold Ir.Config.cur_inst in HINST. unfold Ir.Config.cur_fdef_pc in HINST.\n            des_ifs.\n      }\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.\n        unfold Ir.Config.cur_inst in HINST. unfold Ir.Config.cur_fdef_pc in HINST.\n            des_ifs.\n      }\n    }\n    { eapply gepinbs_icmp_det in HEQPROP.\n      rewrite HNONDET in HEQPROP. inv HEQPROP.\n      congruence. congruence.\n    }\n  }\n  { unfold Ir.SmallStep.t_step in HTSTEP.\n    apply Ir.Config.cur_inst_not_cur_terminator in HINST.\n    des_ifs.\n  }\nQed.\n\n\n\n\nLemma inbounds_abs_minmax:\n  forall ofsmin ofsmax mb ofss\n         (HMIN:list_min ofsmin ofss)\n         (HMAX:list_max ofsmax ofss)\n         (HINB:Ir.MemBlock.inbounds_abs ofsmin mb = true)\n         (HINB:Ir.MemBlock.inbounds_abs ofsmax mb = true),\n    List.forallb (fun i : nat => Ir.MemBlock.inbounds_abs i mb)\n                 ofss = true.\nProof.\n  intros.\n  unfold Ir.MemBlock.inbounds_abs in *.\n  unfold in_range in *.\n  rewrite List.forallb_forall.\n  intros.\n  repeat (rewrite andb_true_iff in *). repeat (rewrite Nat.leb_le in *).\n  unfold list_min in HMIN.\n  unfold list_max in HMAX.\n  inv HMIN. inv HMAX.\n  rewrite List.Forall_forall in *.\n  dup H.\n  apply H1 in H4. apply H3 in H. omega.\nQed.\n\nLemma inbounds_blocks2_minmax:\n  forall m ofss ofsmin ofsmax\n         (HWF:Ir.Memory.wf m)\n         (HMIN:list_min ofsmin ofss)\n         (HMAX:list_max ofsmax ofss)\n         (HDIFF:ofsmin <> ofsmax),\n    Ir.Memory.inbounds_blocks2 m ofss =\n    Ir.Memory.inbounds_blocks2 m (ofsmin::ofsmax::nil).\nProof.\n  intros.\n  assert (lsubseq ofss (ofsmin::ofsmax::nil) \\/\n          lsubseq ofss (ofsmax::ofsmin::nil)).\n  { unfold list_min in HMIN.\n    unfold list_max in HMAX.\n    inv HMIN. inv HMAX.\n    exploit (@In_split2 nat).\n    eassumption. eassumption. eassumption.\n    intros HH. inv HH. inv H3. inv H4.\n    inv H3.\n    { left. eapply lsubseq_append2. constructor.\n      eapply lsubseq_append2. constructor. constructor.\n    }\n    { right. eapply lsubseq_append2. constructor.\n      eapply lsubseq_append2. constructor. constructor.\n    }\n  }\n  remember (Ir.Memory.inbounds_blocks2 m ofss) as blks1.\n  remember (Ir.Memory.inbounds_blocks2 m [ofsmin; ofsmax]) as blks2.\n  symmetry in Heqblks1.\n  symmetry in Heqblks2.\n  dup Heqblks2.\n  eapply Ir.Memory.inbounds_blocks2_singleton2 in Heqblks2.\n  destruct H.\n  { dup Heqblks0.\n    eapply Ir.Memory.inbounds_blocks2_lsubseq2 in Heqblks0.\n    2: eapply Heqblks1.\n    destruct blks2.\n    { destruct blks1. ss. inv Heqblks0. }\n    destruct blks2.\n    { assert (HPERM:exists ofss', Permutation (ofsmin::ofsmax::ofss') ofss ).\n      { apply lsubseq_split_len2 in H.\n        inv H. inv H0. inv H.\n        exists (x ++ x0 ++ x1).\n        replace (ofsmax::x++x0++x1) with ((ofsmax::x)++(x0++x1)) by ss.\n        eapply perm_trans with (l' := (ofsmax::x) ++ ofsmin:: x0 ++ x1).\n        eapply Permutation_middle.\n        simpl.\n        replace (x++ofsmin::x0++x1) with ((x++ofsmin::x0)++x1).\n        replace (x++ofsmin::x0++ofsmax::x1) with\n                ((x++ofsmin::x0)++ofsmax::x1).\n        eapply Permutation_middle.\n        rewrite <- List.app_assoc. ss.\n        rewrite <- List.app_assoc. ss.\n      }\n      destruct HPERM as [ofss' HPERM].\n\n      assert (HEQ:Ir.Memory.inbounds_blocks2 m ofss =\n                  Ir.Memory.inbounds_blocks2 m (ofsmin::ofsmax::ofss')).\n      { eapply Ir.Memory.inbounds_blocks2_Permutation. eapply HPERM. ss. }\n\n      rewrite HEQ in Heqblks1.\n      destruct p.\n      assert (List.forallb (fun i : nat => Ir.MemBlock.inbounds_abs i t)\n                           (ofsmin :: ofsmax :: ofss') = true).\n      { eapply inbounds_abs_minmax with (ofsmin := ofsmin) (ofsmax := ofsmax).\n        { eapply list_min_Permutation.\n          eassumption. apply Permutation_sym. eassumption.\n        }\n        { eapply list_max_Permutation.\n          eassumption. apply Permutation_sym. eassumption.\n        }\n        { eapply Ir.Memory.inbounds_blocks2_forallb in Heqblks3.\n          simpl in Heqblks3. rewrite andb_true_r in Heqblks3. ss. }\n        { eapply Ir.Memory.inbounds_blocks2_forallb2 in Heqblks3.\n          simpl in Heqblks3. repeat (rewrite andb_true_r in Heqblks3).\n          rewrite andb_true_iff in Heqblks3. inv Heqblks3. ss. }\n      }\n      eapply Ir.Memory.inbounds_blocks2_singleton4 with (m := m) (bid := b) in H0.\n      rewrite Heqblks1 in H0.  ss.\n      ss.\n      { eapply Ir.Memory.In_get. ss.\n        eapply Ir.Memory.inbounds_blocks2_In2.\n        rewrite Heqblks3. ss.\n      }\n      { eapply Ir.Memory.inbounds_blocks2_alive in Heqblks3.\n        simpl in Heqblks3. rewrite andb_true_r in Heqblks3. ss.\n      }\n      ss.\n    }\n    { simpl in Heqblks2. omega. }\n    ss.\n  }\n  { assert (Ir.Memory.inbounds_blocks2 m [ofsmax; ofsmin] = blks2).\n    { eapply Ir.Memory.inbounds_blocks2_Permutation with (I := [ofsmin; ofsmax]).\n      eapply perm_swap. ss. }\n    clear Heqblks0. rename H0 into Heqblks0.\n    dup Heqblks0.\n    eapply Ir.Memory.inbounds_blocks2_lsubseq2 in Heqblks0.\n    2: eapply Heqblks1.\n    destruct blks2.\n    { destruct blks1. ss. inv Heqblks0. }\n    destruct blks2.\n    { assert (HPERM:exists ofss', Permutation (ofsmax::ofsmin::ofss') ofss ).\n      { apply lsubseq_split_len2 in H.\n        inv H. inv H0. inv H.\n        exists (x ++ x0 ++ x1).\n        replace (ofsmin::x++x0++x1) with ((ofsmin::x)++(x0++x1)) by ss.\n        eapply perm_trans with (l' := (ofsmin::x) ++ ofsmax:: x0 ++ x1).\n        eapply Permutation_middle.\n        simpl.\n        replace (x++ofsmax::x0++x1) with ((x++ofsmax::x0)++x1).\n        replace (x++ofsmax::x0++ofsmin::x1) with\n                ((x++ofsmax::x0)++ofsmin::x1).\n        eapply Permutation_middle.\n        rewrite <- List.app_assoc. ss.\n        rewrite <- List.app_assoc. ss.\n      }\n      destruct HPERM as [ofss' HPERM].\n\n      assert (HEQ:Ir.Memory.inbounds_blocks2 m ofss =\n                  Ir.Memory.inbounds_blocks2 m (ofsmax::ofsmin::ofss')).\n      { eapply Ir.Memory.inbounds_blocks2_Permutation. eapply HPERM. ss. }\n\n      rewrite HEQ in Heqblks1.\n      destruct p.\n      assert (List.forallb (fun i : nat => Ir.MemBlock.inbounds_abs i t)\n                           (ofsmax :: ofsmin :: ofss') = true).\n      { eapply inbounds_abs_minmax with (ofsmin := ofsmin) (ofsmax := ofsmax).\n        { eapply list_min_Permutation.\n          eassumption. apply Permutation_sym.\n          eassumption.\n        }\n        { eapply list_max_Permutation.\n          eassumption. apply Permutation_sym. eassumption.\n        }\n        { eapply Ir.Memory.inbounds_blocks2_forallb2 in Heqblks3.\n          simpl in Heqblks3. repeat (rewrite andb_true_r in Heqblks3).\n          rewrite andb_true_iff in Heqblks3. inv Heqblks3. ss. }\n        { eapply Ir.Memory.inbounds_blocks2_forallb in Heqblks3.\n          simpl in Heqblks3. rewrite andb_true_r in Heqblks3. ss.\n        }\n      }\n      eapply Ir.Memory.inbounds_blocks2_singleton4 with (m := m) (bid := b) in H0.\n      rewrite Heqblks1 in H0.  ss.\n      ss.\n      { eapply Ir.Memory.In_get. ss.\n        eapply Ir.Memory.inbounds_blocks2_In2.\n        rewrite Heqblks3. ss.\n      }\n      { eapply Ir.Memory.inbounds_blocks2_alive in Heqblks3.\n        simpl in Heqblks3. rewrite andb_true_r in Heqblks3. ss.\n      }\n      omega.\n    }\n    { simpl in Heqblks2. omega. }\n    ss.\n  }\n  ss.\n  ss.\nQed.\n\nLemma phys_minmaxI_get_deref:\n  forall m p q sz\n         (HWF:Ir.Memory.wf m)\n         (HPMM:phys_minmaxI p q)\n         (HSZ:sz > 0),\n    Ir.get_deref m p sz = Ir.get_deref m q sz.\nProof.\n  intros.\n  unfold Ir.get_deref.\n  inv HPMM.\n  repeat (match goal with\n  | [H:exists _, _ |- _] => destruct H\n  | [H:_ /\\ _ |- _] => destruct H\n  end).\n  rewrite H, H0.\n  unfold Ir.get_deref_blks_phyptr.\n  assert (HE1:exists xm, list_min xm (x :: (x+sz) :: x0) /\\\n                         list_min xm (x :: (x+sz) :: x1)).\n  { destruct (x <=? x3) eqn:HLE.\n    { exists x.\n      split.\n      { unfold list_min in *. split. left. ss.\n        rewrite List.Forall_forall. intros.\n        inv H1. rewrite Nat.leb_le in HLE. inv H5.\n        { omega. }\n        inv H.\n        { omega. }\n        rewrite List.Forall_forall in H7.\n        apply H7 in H0. omega.\n      }\n      { unfold list_min in *. split. left. ss.\n        rewrite List.Forall_forall. intros.\n        inv H2. rewrite Nat.leb_le in HLE. inv H5.\n        { omega. }\n        inv H.\n        { omega. }\n        rewrite List.Forall_forall in H7.\n        apply H7 in H0. omega.\n      }\n    }\n    { rewrite Nat.leb_gt in HLE.\n      exists x3.\n      unfold list_min in *.\n      inv H1. inv H2.\n      repeat (rewrite List.Forall_forall in *).\n      split.\n      { split. right. right. ss.\n        intros. inv H1. omega. inv H2. omega. apply H6. ss.\n      }\n      { split. right. right. ss.\n        intros. inv H1. omega. inv H2. omega. apply H0. ss.\n      }\n    }\n  }\n  assert (HE2:exists xm, list_max xm (x :: (x+sz) :: x0) /\\\n                         list_max xm (x :: (x+sz) :: x1)).\n  { destruct (x4 <=? x + sz) eqn:HLE.\n    { exists (x + sz).\n      split.\n      { unfold list_max in *. split. right. left. ss.\n        rewrite List.Forall_forall. intros.\n        inv H3. rewrite Nat.leb_le in HLE. inv H5.\n        { omega. }\n        inv H.\n        { omega. }\n        rewrite List.Forall_forall in H7.\n        apply H7 in H0. omega.\n      }\n      { unfold list_max in *. split. right. left. ss.\n        rewrite List.Forall_forall. intros.\n        inv H5.\n        { omega. }\n        inv H6.\n        { omega. }\n        rewrite Nat.leb_le in HLE.\n        rewrite List.Forall_forall in H4.\n        inv H4.\n        apply H5 in H. omega.\n      }\n    }\n    { rewrite Nat.leb_gt in HLE.\n      exists x4.\n      unfold list_max in *.\n      inv H3. inv H4.\n      repeat (rewrite List.Forall_forall in *).\n      split.\n      { split. right. right. ss.\n        intros. inv H3. omega. inv H4. omega. apply H6. ss.\n      }\n      { split. right. right. ss.\n        intros. inv H3. omega. inv H4. omega. apply H0. ss.\n      }\n    }\n  }\n  clear H1 H2 H3 H4.\n  inv HE1. inv H1. inv HE2. inv H1.\n\n  assert (HINB1:\n            Ir.Memory.inbounds_blocks2 m (x :: x + sz :: x0) =\n            Ir.Memory.inbounds_blocks2 m [x5;x6]).\n  { eapply inbounds_blocks2_minmax. ss. ss. ss. ss.\n    exploit list_minmax_lt. eapply H. eapply H2.\n    left. ss. right. left. ss. omega.\n    intros. omega. }\n  assert (HINB2:\n            Ir.Memory.inbounds_blocks2 m (x :: x + sz :: x1) =\n            Ir.Memory.inbounds_blocks2 m [x5;x6]).\n  { eapply inbounds_blocks2_minmax. ss. ss. ss. ss.\n    exploit list_minmax_lt. eapply H. eapply H2.\n    left. ss. right. left. ss. omega.\n    intros. omega. }\n  rewrite HINB1, HINB2.\n  reflexivity.\nQed.\n\n\n\n\n(* ends with refinement with common update_reg_and_incrpc calls *)\nLtac thats_it :=\n          eapply Ir.SSRefinement.refines_update_reg_and_incrpc;\n          [ eassumption | eassumption\n          | apply Ir.Refinement.refines_state_eq;\n            apply Ir.Config.eq_refl\n          | try apply Ir.Refinement.refines_value_refl; try constructor; fail ].\n\nLtac cc_thats_it := constructor; constructor; thats_it.\n\n\n(* ends with refinement with common incrpc calls *)\nLtac thats_it2 :=\n          eapply Ir.SSRefinement.refines_incrpc;\n          [ eassumption | eassumption\n          | apply Ir.Refinement.refines_state_eq;\n            apply Ir.Config.eq_refl ].\n\nLtac cc_thats_it2 := constructor; constructor; thats_it2.\n\nLtac hey_terminator HINST2 :=\n  apply Ir.Config.cur_inst_not_cur_terminator in HINST2;\n       congruence.\n\nLtac hey_terminator2 HINST2 HTSTEP :=\n  apply Ir.Config.cur_inst_not_cur_terminator in HINST2;\n       unfold Ir.SmallStep.t_step in HTSTEP;\n       des_ifs.\n\nLtac unfold_phys_minmaxI H :=\n  unfold phys_minmaxI in H;\n  destruct H as [o H];\n  destruct H as [I1 H];\n  destruct H as [I2 H];\n  destruct H as [cid H];\n  destruct H as [ofsmin H];\n  destruct H as [ofsmax H];\n  destruct H as [H1 [H2 [H3 [H4 [H5 H6]]]]].\n\n\n\n\n(*****\n      Refinement on load instruction.\n *****)\n\nTheorem load_refines:\n  forall md1 md2 (* md2 is an optimized program *)\n         st r retty opptr1 opptr2 v1 v2 sr1 sr2\n         (HWF1:Ir.Config.wf md1 st)\n         (HWF2:Ir.Config.wf md2 st) (* State st is wellformed on two modules *)\n         (* Two loads on a same state(including same PC) *)\n         (HINST1:Some (Ir.Inst.iload r retty opptr1) = Ir.Config.cur_inst md1 st)\n         (HINST2:Some (Ir.Inst.iload r retty opptr2) = Ir.Config.cur_inst md2 st)\n         (* Has a good relation between pointer operands *)\n         (HOP1:Ir.Config.get_val st opptr1 = Some v1)\n         (HOP2:Ir.Config.get_val st opptr2 = Some v2)\n         (HPMM:exists p1 p2, Ir.ptr p1 = v1 /\\ Ir.ptr p2 = v2 /\\ phys_minmaxI p1 p2)\n         (* And.. have a step. *)\n         (HSTEP1:Ir.SmallStep.sstep md1 st sr1)\n         (HSTEP2:Ir.SmallStep.sstep md2 st sr2),\n\n    Ir.Refinement.refines_step_res sr2 sr1. (* target refines source *)\nProof.\n  intros.\n  inv HSTEP1.\n  { inv HSTEP2.\n    { inv HISTEP; try congruence.\n      unfold Ir.SmallStep.inst_det_step in HNEXT.\n      rewrite <- HINST1 in HNEXT.\n      rewrite HOP1 in HNEXT.\n      inv HISTEP0; try congruence.\n      unfold Ir.SmallStep.inst_det_step in HNEXT0.\n      rewrite <- HINST2 in HNEXT0.\n      rewrite HOP2 in HNEXT0.\n      inv HWF1.\n\n      clear wf_cid_to_f.\n      clear wf_cid_to_f2.\n      clear wf_stack.\n      clear wf_ptr.\n      clear wf_ptr_mem.\n\n      inv HPMM. inv H. inv H0. inv H1.\n      unfold Ir.deref in *.\n      unfold Ir.load_val in *.\n      unfold Ir.load_bytes in *.\n      rewrite phys_minmaxI_get_deref with (q := x0) in HNEXT.\n      des_ifs; try (cc_thats_it).\n      inv HWF2. ss. ss.\n      apply Ir.ty_bytesz_pos.\n    }\n    hey_terminator HINST2.\n    hey_terminator2 HINST2 HTSTEP.\n  }\n  constructor.\n  hey_terminator2 HINST1 HTSTEP.\nQed.\n\n\n\n(*****\n      Refinement on store instruction.\n *****)\n\nTheorem store_refines:\n  forall md1 md2 (* md2 is an optimized program *)\n         st valty opptr1 opptr2 opval v1 v2 sr1 sr2\n         (HWF1:Ir.Config.wf md1 st)\n         (HWF2:Ir.Config.wf md2 st) (* State st is wellformed on two modules *)\n         (* Two stores on a same state(including same PC) *)\n         (HINST1:Some (Ir.Inst.istore valty opptr1 opval) = Ir.Config.cur_inst md1 st)\n         (HINST2:Some (Ir.Inst.istore valty opptr2 opval) = Ir.Config.cur_inst md2 st)\n         (* Has a good relation between pointer operands *)\n         (HOP1:Ir.Config.get_val st opptr1 = Some v1)\n         (HOP2:Ir.Config.get_val st opptr2 = Some v2)\n         (HPMM:exists p1 p2, Ir.ptr p1 = v1 /\\ Ir.ptr p2 = v2 /\\ phys_minmaxI p1 p2)\n         (* And.. have a step. *)\n         (HSTEP1:Ir.SmallStep.sstep md1 st sr1)\n         (HSTEP2:Ir.SmallStep.sstep md2 st sr2),\n    Ir.Refinement.refines_step_res sr2 sr1. (* target refines source *)\nProof.\n    intros.\n  inv HSTEP1.\n  { inv HSTEP2.\n    { inv HISTEP; try congruence.\n      unfold Ir.SmallStep.inst_det_step in HNEXT.\n      rewrite <- HINST1 in HNEXT.\n      rewrite HOP1 in HNEXT.\n      inv HISTEP0; try congruence.\n      unfold Ir.SmallStep.inst_det_step in HNEXT0.\n      rewrite <- HINST2 in HNEXT0.\n      rewrite HOP2 in HNEXT0.\n      inv HWF1.\n\n      clear wf_cid_to_f.\n      clear wf_cid_to_f2.\n      clear wf_stack.\n      clear wf_ptr.\n      clear wf_ptr_mem.\n\n      inv HPMM. inv H. inv H0. inv H1.\n      unfold Ir.deref in *.\n      rewrite phys_minmaxI_get_deref with (q := x0) in HNEXT.\n      des_ifs.\n      unfold Ir.store_val.\n      unfold Ir.store_bytes.\n      des_ifs; try (cc_thats_it2; fail);\n      try (rewrite phys_minmaxI_get_deref with (q := x0) in *;\n           [ congruence\n           | inv HWF2; ss | ss\n           | rewrite Nat.eqb_eq in Heq2; rewrite <- Heq2;  apply Ir.ty_bytesz_pos ]).\n      { rewrite phys_minmaxI_get_deref with (q := x0) in *. rewrite Heq3 in Heq5.\n        inv Heq5. cc_thats_it2.\n        inv HWF2. ss.\n        ss.\n        rewrite Nat.eqb_eq in Heq2. rewrite <- Heq2.\n        apply Ir.ty_bytesz_pos. }\n      { rewrite phys_minmaxI_get_deref with (q := x0) in *. rewrite Heq3 in Heq5.\n        inv Heq5. cc_thats_it2.\n        inv HWF2. ss.\n        ss.\n        rewrite Nat.eqb_eq in Heq2. rewrite <- Heq2.\n        apply Ir.ty_bytesz_pos. }\n      constructor.\n      cc_thats_it2.\n      ss.\n      ss.\n      apply Ir.ty_bytesz_pos.\n    }\n    hey_terminator HINST2.\n    hey_terminator2 HINST2 HTSTEP.\n  }\n  constructor.\n  hey_terminator2 HINST1 HTSTEP.\nQed.\n\n\n\n(*****\n      Refinement on free instruction.\n *****)\n\nTheorem free_refines:\n  forall md1 md2 (* md2 is an optimized program *)\n         st opptr1 opptr2 v1 v2 sr1 sr2\n         (HWF1:Ir.Config.wf md1 st)\n         (HWF2:Ir.Config.wf md2 st) (* State st is wellformed on two modules *)\n         (* Two frees on a same state(including same PC) *)\n         (HINST1:Some (Ir.Inst.ifree opptr1) = Ir.Config.cur_inst md1 st)\n         (HINST2:Some (Ir.Inst.ifree opptr2) = Ir.Config.cur_inst md2 st)\n         (* Has a good relation between pointer operands *)\n         (HOP1:Ir.Config.get_val st opptr1 = Some v1)\n         (HOP2:Ir.Config.get_val st opptr2 = Some v2)\n         (HPMM:exists p1 p2, Ir.ptr p1 = v1 /\\ Ir.ptr p2 = v2 /\\ phys_minmaxI p1 p2)\n         (* And.. have a step. *)\n         (HSTEP1:Ir.SmallStep.sstep md1 st sr1)\n         (HSTEP2:Ir.SmallStep.sstep md2 st sr2),\n    Ir.Refinement.refines_step_res sr2 sr1. (* target refines source *)\nProof.\n  intros.\n  inv HSTEP1.\n  { inv HSTEP2.\n    { inv HISTEP; try congruence.\n      unfold Ir.SmallStep.inst_det_step in HNEXT.\n      rewrite <- HINST1 in HNEXT.\n      rewrite HOP1 in HNEXT.\n      inv HISTEP0; try congruence.\n      unfold Ir.SmallStep.inst_det_step in HNEXT0.\n      rewrite <- HINST2 in HNEXT0.\n      rewrite HOP2 in HNEXT0.\n      inv HWF1.\n\n      clear wf_cid_to_f.\n      clear wf_cid_to_f2.\n      clear wf_stack.\n      clear wf_ptr.\n      clear wf_ptr_mem.\n\n      inv HPMM. inv H. inv H0. inv H1.\n      unfold Ir.SmallStep.free in *.\n      dup H0.\n      unfold_phys_minmaxI H1.\n      subst x. subst x0.\n      unfold Ir.deref in HNEXT, HNEXT0.\n      rewrite phys_minmaxI_get_deref with (q := Ir.pphy o I2 cid) in HNEXT.\n      des_ifs.\n      cc_thats_it2. constructor. constructor. constructor.\n      ss. ss. ss.\n    }\n    hey_terminator HINST2.\n    hey_terminator2 HINST2 HTSTEP.\n  }\n  constructor.\n  hey_terminator2 HINST1 HTSTEP.\nQed.\n\n\n\n(*****\n      Refinement on ptrtoint instruction.\n *****)\n\nTheorem ptrtoint_refines:\n  forall md1 md2 (* md2 is an optimized program *)\n         st r opptr1 opptr2 retty v1 v2 sr1 sr2\n         (HWF1:Ir.Config.wf md1 st)\n         (HWF2:Ir.Config.wf md2 st) (* State st is wellformed on two modules *)\n         (* Two ptrtoins on a same state(including same PC) *)\n         (HINST1:Some (Ir.Inst.iptrtoint r opptr1 retty) = Ir.Config.cur_inst md1 st)\n         (HINST2:Some (Ir.Inst.iptrtoint r opptr2 retty) = Ir.Config.cur_inst md2 st)\n         (* Has a good relation between pointer operands *)\n         (HOP1:Ir.Config.get_val st opptr1 = Some v1)\n         (HOP2:Ir.Config.get_val st opptr2 = Some v2)\n         (HPMM:exists p1 p2, Ir.ptr p1 = v1 /\\ Ir.ptr p2 = v2 /\\ phys_minmaxI p1 p2)\n         (* And.. have a step. *)\n         (HSTEP1:Ir.SmallStep.sstep md1 st sr1)\n         (HSTEP2:Ir.SmallStep.sstep md2 st sr2),\n    Ir.Refinement.refines_step_res sr2 sr1. (* target refines source *)\nProof.\n  intros.\n  inv HSTEP1.\n  { inv HSTEP2.\n    { inv HISTEP; try congruence.\n      unfold Ir.SmallStep.inst_det_step in HNEXT.\n      rewrite <- HINST1 in HNEXT.\n      rewrite HOP1 in HNEXT.\n      inv HISTEP0; try congruence.\n      unfold Ir.SmallStep.inst_det_step in HNEXT0.\n      rewrite <- HINST2 in HNEXT0.\n      rewrite HOP2 in HNEXT0.\n      inv HWF1.\n\n      clear wf_cid_to_f.\n      clear wf_cid_to_f2.\n      clear wf_stack.\n      clear wf_ptr.\n      clear wf_ptr_mem.\n\n      inv HPMM. inv H. inv H0. inv H1.\n      unfold_phys_minmaxI H0.\n      subst x. subst x0.\n      des_ifs; try (cc_thats_it; fail).\n    }\n    hey_terminator HINST2.\n    hey_terminator2 HINST2 HTSTEP.\n  }\n  constructor.\n  hey_terminator2 HINST1 HTSTEP.\nQed.\n\n\n\n(*****\n      Refinement on psub instruction.\n *****)\nTheorem psub_refines_l:\n  forall md1 md2 (* md2 is an optimized program *)\n         st r opptr11 opptr12 opptr2 retty ptrty v1 v2 sr1 sr2\n         (HWF1:Ir.Config.wf md1 st)\n         (HWF2:Ir.Config.wf md2 st) (* State st is wellformed on two modules *)\n         (* Two psubs on a same state(including same PC) *)\n         (HINST1:Some (Ir.Inst.ipsub r retty ptrty opptr11 opptr2) =\n                 Ir.Config.cur_inst md1 st)\n         (HINST2:Some (Ir.Inst.ipsub r retty ptrty opptr12 opptr2) =\n                 Ir.Config.cur_inst md2 st)\n         (* Has a good relation between the first pointer operands *)\n         (HOP1:Ir.Config.get_val st opptr11 = Some v1)\n         (HOP2:Ir.Config.get_val st opptr12 = Some v2)\n         (HPMM:exists p1 p2, Ir.ptr p1 = v1 /\\ Ir.ptr p2 = v2 /\\ phys_minmaxI p1 p2)\n         (* And.. have a step. *)\n         (HSTEP1:Ir.SmallStep.sstep md1 st sr1)\n         (HSTEP2:Ir.SmallStep.sstep md2 st sr2),\n    Ir.Refinement.refines_step_res sr2 sr1. (* target refines source *)\nProof.\n  intros.\n  inv HSTEP1.\n  { inv HSTEP2.\n    { inv HISTEP; try congruence.\n      unfold Ir.SmallStep.inst_det_step in HNEXT.\n      rewrite <- HINST1 in HNEXT.\n      rewrite HOP1 in HNEXT.\n      inv HISTEP0; try congruence.\n      unfold Ir.SmallStep.inst_det_step in HNEXT0.\n      rewrite <- HINST2 in HNEXT0.\n      rewrite HOP2 in HNEXT0.\n      inv HWF1.\n      inv HPMM. inv H. inv H0. inv H1.\n      unfold_phys_minmaxI H0.\n      subst x. subst x0.\n      unfold Ir.SmallStep.psub in *.\n      des_ifs; try (cc_thats_it; fail).\n    }\n    hey_terminator HINST2.\n    hey_terminator2 HINST2 HTSTEP.\n  }\n  constructor.\n  hey_terminator2 HINST1 HTSTEP.\nQed.\n\nTheorem psub_refines_r:\n  forall md1 md2 (* md2 is an optimized program *)\n         st r opptr1 opptr21 opptr22 retty ptrty v1 v2 sr1 sr2\n         (HWF1:Ir.Config.wf md1 st)\n         (HWF2:Ir.Config.wf md2 st) (* State st is wellformed on two modules *)\n         (* Two psubs on a same state(including same PC) *)\n         (HINST1:Some (Ir.Inst.ipsub r retty ptrty opptr1 opptr21) =\n                 Ir.Config.cur_inst md1 st)\n         (HINST2:Some (Ir.Inst.ipsub r retty ptrty opptr1 opptr22) =\n                 Ir.Config.cur_inst md2 st)\n         (* Has a good relation between the first pointer operands *)\n         (HOP1:Ir.Config.get_val st opptr21 = Some v1)\n         (HOP2:Ir.Config.get_val st opptr22 = Some v2)\n         (HPMM:exists p1 p2, Ir.ptr p1 = v1 /\\ Ir.ptr p2 = v2 /\\ phys_minmaxI p1 p2)\n         (* And.. have a step. *)\n         (HSTEP1:Ir.SmallStep.sstep md1 st sr1)\n         (HSTEP2:Ir.SmallStep.sstep md2 st sr2),\n    Ir.Refinement.refines_step_res sr2 sr1. (* target refines source *)\nProof.\n  intros.\n  inv HSTEP1.\n  { inv HSTEP2.\n    { inv HISTEP; try congruence.\n      unfold Ir.SmallStep.inst_det_step in HNEXT.\n      rewrite <- HINST1 in HNEXT.\n      rewrite HOP1 in HNEXT.\n      inv HISTEP0; try congruence.\n      unfold Ir.SmallStep.inst_det_step in HNEXT0.\n      rewrite <- HINST2 in HNEXT0.\n      rewrite HOP2 in HNEXT0.\n      inv HWF1.\n      inv HPMM. inv H. inv H0. inv H1.\n      unfold_phys_minmaxI H0.\n      subst x. subst x0.\n      unfold Ir.SmallStep.psub in *.\n      des_ifs; try (cc_thats_it; fail).\n    }\n    hey_terminator HINST2.\n    hey_terminator2 HINST2 HTSTEP.\n  }\n  constructor.\n  hey_terminator2 HINST1 HTSTEP.\nQed.\n\n\n\n(*****\n      Refinement on icmp eq instruction.\n *****)\n\nTheorem icmp_eq_refines_l:\n  forall md1 md2 (* md2 is an optimized program *)\n         st r opptr11 opptr12 opptr2 ptrty v1 v2 sr1 sr2\n         (HWF1:Ir.Config.wf md1 st)\n         (HWF2:Ir.Config.wf md2 st) (* State st is wellformed on two modules *)\n         (* Two icmps on a same state(including same PC) *)\n         (HINST1:Some (Ir.Inst.iicmp_eq r ptrty opptr11 opptr2) =\n                 Ir.Config.cur_inst md1 st)\n         (HINST2:Some (Ir.Inst.iicmp_eq r ptrty opptr12 opptr2) =\n                 Ir.Config.cur_inst md2 st)\n         (* Has a good relation between the first pointer operands *)\n         (HOP1:Ir.Config.get_val st opptr11 = Some v1)\n         (HOP2:Ir.Config.get_val st opptr12 = Some v2)\n         (HPMM:exists p1 p2, Ir.ptr p1 = v1 /\\ Ir.ptr p2 = v2 /\\ phys_minmaxI p1 p2)\n         (* And.. have a step. *)\n         (HSTEP2:Ir.SmallStep.sstep md2 st sr2)\n         (HSTEP1:Ir.SmallStep.sstep md1 st sr1),\n    Ir.Refinement.refines_step_res sr2 sr1. (* target refines source *)\nProof.\n  intros.\n  inv HSTEP1.\n  { inv HSTEP2.\n    { inv HISTEP; try congruence.\n      unfold Ir.SmallStep.inst_det_step in HNEXT.\n      rewrite <- HINST1 in HNEXT.\n      rewrite HOP1 in HNEXT.\n      inv HISTEP0; try congruence.\n      unfold Ir.SmallStep.inst_det_step in HNEXT0.\n      rewrite <- HINST2 in HNEXT0.\n      rewrite HOP2 in HNEXT0.\n      inv HWF1.\n      inv HPMM. inv H. inv H0. inv H1.\n      unfold_phys_minmaxI H0.\n      subst x. subst x0.\n      unfold Ir.SmallStep.icmp_eq_ptr in *.\n      des_ifs; try (cc_thats_it; fail).\n\n      inv HPMM. inv H. inv H0. inv H1.\n      unfold_phys_minmaxI H0.\n      subst x. subst x0.\n      rewrite <- HINST2 in HCUR. inv HCUR.\n      rewrite HOP2 in HOP0. inv HOP0.\n      unfold Ir.SmallStep.icmp_eq_ptr_nondet_cond in HNONDET. congruence.\n\n      inv HPMM. inv H. inv H0. inv H1.\n      unfold_phys_minmaxI H0.\n      subst x. subst x0.\n      rewrite <- HINST1 in HCUR. inv HCUR.\n      rewrite HOP1 in HOP0. inv HOP0.\n      unfold Ir.SmallStep.icmp_eq_ptr_nondet_cond in HNONDET. congruence.\n    }\n    hey_terminator HINST2.\n    hey_terminator2 HINST2 HTSTEP.\n  }\n  constructor.\n  hey_terminator2 HINST1 HTSTEP.\nQed.\n\nTheorem icmp_eq_refines_r:\n  forall md1 md2 (* md2 is an optimized program *)\n         st r opptr1 opptr21 opptr22 ptrty v1 v2 sr1 sr2\n         (HWF1:Ir.Config.wf md1 st)\n         (HWF2:Ir.Config.wf md2 st) (* State st is wellformed on two modules *)\n         (* Two icmps on a same state(including same PC) *)\n         (HINST1:Some (Ir.Inst.iicmp_eq r ptrty opptr1 opptr21) =\n                 Ir.Config.cur_inst md1 st)\n         (HINST2:Some (Ir.Inst.iicmp_eq r ptrty opptr1 opptr22) =\n                 Ir.Config.cur_inst md2 st)\n         (* Has a good relation between the first pointer operands *)\n         (HOP1:Ir.Config.get_val st opptr21 = Some v1)\n         (HOP2:Ir.Config.get_val st opptr22 = Some v2)\n         (HPMM:exists p1 p2, Ir.ptr p1 = v1 /\\ Ir.ptr p2 = v2 /\\ phys_minmaxI p1 p2)\n         (* And.. have a step. *)\n         (HSTEP1:Ir.SmallStep.sstep md1 st sr1)\n         (HSTEP2:Ir.SmallStep.sstep md2 st sr2),\n      Ir.Refinement.refines_step_res sr2 sr1. (* target refines source *)\nProof.\n  intros.\n  inv HSTEP1.\n  { inv HSTEP2.\n    { inv HISTEP; try congruence.\n      unfold Ir.SmallStep.inst_det_step in HNEXT.\n      rewrite <- HINST1 in HNEXT.\n      rewrite HOP1 in HNEXT.\n      inv HISTEP0; try congruence.\n      unfold Ir.SmallStep.inst_det_step in HNEXT0.\n      rewrite <- HINST2 in HNEXT0.\n      rewrite HOP2 in HNEXT0.\n      inv HWF1.\n      inv HPMM. inv H. inv H0. inv H1.\n      unfold_phys_minmaxI H0.\n      subst x. subst x0.\n      unfold Ir.SmallStep.icmp_eq_ptr in *.\n      des_ifs; try (cc_thats_it; fail).\n\n      inv HPMM. inv H. inv H0. inv H1.\n      unfold_phys_minmaxI H0.\n      subst x. subst x0.\n      rewrite <- HINST2 in HCUR. inv HCUR.\n      rewrite HOP2 in HOP3. inv HOP3.\n      unfold Ir.SmallStep.icmp_eq_ptr_nondet_cond in HNONDET. des_ifs.\n\n      inv HPMM. inv H. inv H0. inv H1.\n      unfold_phys_minmaxI H0.\n      subst x. subst x0.\n      rewrite <- HINST1 in HCUR. inv HCUR.\n      rewrite HOP1 in HOP3. inv HOP3.\n      unfold Ir.SmallStep.icmp_eq_ptr_nondet_cond in HNONDET. des_ifs.\n    }\n    hey_terminator HINST2.\n    hey_terminator2 HINST2 HTSTEP.\n  }\n  constructor.\n  hey_terminator2 HINST1 HTSTEP.\nQed.\n\n\n\n(*****\n      Refinement on icmp ule instruction.\n *****)\n\nTheorem icmp_ule_refines_l:\n  forall md1 md2 (* md2 is an optimized program *)\n         st r opptr11 opptr12 opptr2 ptrty v1 v2 sr1 sr2\n         (HWF1:Ir.Config.wf md1 st)\n         (HWF2:Ir.Config.wf md2 st) (* State st is wellformed on two modules *)\n         (* Two icmps on a same state(including same PC) *)\n         (HINST1:Some (Ir.Inst.iicmp_ule r ptrty opptr11 opptr2) =\n                 Ir.Config.cur_inst md1 st)\n         (HINST2:Some (Ir.Inst.iicmp_ule r ptrty opptr12 opptr2) =\n                 Ir.Config.cur_inst md2 st)\n         (* Has a good relation between the first pointer operands *)\n         (HOP1:Ir.Config.get_val st opptr11 = Some v1)\n         (HOP2:Ir.Config.get_val st opptr12 = Some v2)\n         (HPMM:exists p1 p2, Ir.ptr p1 = v1 /\\ Ir.ptr p2 = v2 /\\ phys_minmaxI p1 p2)\n         (* And.. have a step. *)\n         (HSTEP1:Ir.SmallStep.sstep md1 st sr1)\n         (HSTEP2:Ir.SmallStep.sstep md2 st sr2),\n    Ir.Refinement.refines_step_res sr2 sr1. (* target refines source *)\nProof.\n  intros.\n  inv HSTEP1.\n  { inv HSTEP2.\n    { inv HISTEP; try congruence.\n      unfold Ir.SmallStep.inst_det_step in HNEXT.\n      rewrite <- HINST1 in HNEXT.\n      rewrite HOP1 in HNEXT.\n      inv HISTEP0; try congruence.\n      unfold Ir.SmallStep.inst_det_step in HNEXT0.\n      rewrite <- HINST2 in HNEXT0.\n      rewrite HOP2 in HNEXT0.\n      inv HWF1.\n      inv HPMM. inv H. inv H0. inv H1.\n      unfold_phys_minmaxI H0.\n      subst x. subst x0.\n      unfold Ir.SmallStep.icmp_ule_ptr in *.\n      des_ifs; try (cc_thats_it; fail).\n\n      inv HPMM. inv H. inv H0. inv H1.\n      unfold_phys_minmaxI H0.\n      subst x. subst x0.\n      rewrite <- HINST2 in HCUR. inv HCUR.\n      rewrite HOP2 in HOP0. inv HOP0.\n      unfold Ir.SmallStep.icmp_ule_ptr_nondet_cond in HNONDET. congruence.\n\n      inv HPMM. inv H. inv H0. inv H1.\n      unfold_phys_minmaxI H0.\n      subst x. subst x0.\n      rewrite <- HINST1 in HCUR. inv HCUR.\n      rewrite HOP1 in HOP0. inv HOP0.\n      unfold Ir.SmallStep.icmp_ule_ptr_nondet_cond in HNONDET. congruence.\n    }\n    hey_terminator HINST2.\n    hey_terminator2 HINST2 HTSTEP.\n  }\n  constructor.\n  hey_terminator2 HINST1 HTSTEP.\nQed.\n\nTheorem icmp_ule_refines_r:\n  forall md1 md2 (* md2 is an optimized program *)\n         st r opptr1 opptr21 opptr22 ptrty v1 v2 sr1 sr2\n         (HWF1:Ir.Config.wf md1 st)\n         (HWF2:Ir.Config.wf md2 st) (* State st is wellformed on two modules *)\n         (* Two icmps on a same state(including same PC) *)\n         (HINST1:Some (Ir.Inst.iicmp_ule r ptrty opptr1 opptr21) =\n                 Ir.Config.cur_inst md1 st)\n         (HINST2:Some (Ir.Inst.iicmp_ule r ptrty opptr1 opptr22) =\n                 Ir.Config.cur_inst md2 st)\n         (* Has a good relation between the first pointer operands *)\n         (HOP1:Ir.Config.get_val st opptr21 = Some v1)\n         (HOP2:Ir.Config.get_val st opptr22 = Some v2)\n         (HPMM:exists p1 p2, Ir.ptr p1 = v1 /\\ Ir.ptr p2 = v2 /\\ phys_minmaxI p1 p2)\n         (* And.. have a step. *)\n         (HSTEP1:Ir.SmallStep.sstep md1 st sr1)\n         (HSTEP2:Ir.SmallStep.sstep md2 st sr2),\n    Ir.Refinement.refines_step_res sr2 sr1. (* target refines source *)\nProof.\n  intros.\n  inv HSTEP1.\n  { inv HSTEP2.\n    { inv HISTEP; try congruence.\n      unfold Ir.SmallStep.inst_det_step in HNEXT.\n      rewrite <- HINST1 in HNEXT.\n      rewrite HOP1 in HNEXT.\n      inv HISTEP0; try congruence.\n      unfold Ir.SmallStep.inst_det_step in HNEXT0.\n      rewrite <- HINST2 in HNEXT0.\n      rewrite HOP2 in HNEXT0.\n      inv HWF1.\n      inv HPMM. inv H. inv H0. inv H1.\n      unfold_phys_minmaxI H0.\n      subst x. subst x0.\n      unfold Ir.SmallStep.icmp_ule_ptr in *.\n      unfold Ir.SmallStep.icmp_ule_ptr_nondet_cond in *.\n      des_ifs; try (cc_thats_it; fail).\n\n      inv HPMM. inv H. inv H0. inv H1.\n      unfold_phys_minmaxI H0.\n      subst x. subst x0.\n      rewrite <- HINST2 in HCUR. inv HCUR.\n      rewrite HOP2 in HOP3. inv HOP3.\n      unfold Ir.SmallStep.icmp_ule_ptr_nondet_cond in HNONDET. des_ifs.\n\n      inv HPMM. inv H. inv H0. inv H1.\n      unfold_phys_minmaxI H0.\n      subst x. subst x0.\n      rewrite <- HINST1 in HCUR. inv HCUR.\n      rewrite HOP1 in HOP3. inv HOP3.\n      unfold Ir.SmallStep.icmp_ule_ptr_nondet_cond in HNONDET. des_ifs.\n    }\n    hey_terminator HINST2.\n    hey_terminator2 HINST2 HTSTEP.\n  }\n  constructor.\n  hey_terminator2 HINST1 HTSTEP.\nQed.\n\n(*****\n      Refinement on getelementptr is not needed because\n      physicalized_ptr already contains it. :)\n      In the same context refinement on bitcast is also not\n      needed because it returns identical value if\n      the input is a pointer value.\n *****)\n\nEnd GVN4.\n\nEnd Ir.\n", "meta": {"author": "aqjune", "repo": "twinsem", "sha": "c9cc45994bbc7545d32cad0a918492666e6bb69f", "save_path": "github-repos/coq/aqjune-twinsem", "path": "github-repos/coq/aqjune-twinsem/twinsem-c9cc45994bbc7545d32cad0a918492666e6bb69f/GVN4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.2678181990135334}}
{"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 Language.\nFrom PromisingLib Require Import Loc.\n\nRequire Import Event.\nRequire Import Time.\n\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\n\nRequire Import Cover.\nRequire Import Mapping.\nRequire Import Pred.\nRequire Import Trace.\nRequire Import MemoryProps.\nRequire Import PFConsistent.\nRequire Import PFConsistentStrong.\n\nSet Implicit Arguments.\n\nModule FutureCertify.\n  Section FutureCertify.\n    Variable (lang: language).\n\n    Lemma cap_steps_current_steps\n          th0 th1 mem1 sc1\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          (CAP: Memory.cap (Thread.memory th0) mem1)\n          (SC_MAX: Memory.max_concrete_timemap mem1 sc1)\n          (STEPS: rtc (@Thread.tau_step lang)\n                      (Thread.mk lang (Thread.state th0) (Thread.local th0) sc1 mem1)\n                      th1)\n          (CONSISTENT: Local.promise_consistent (Thread.local th1))\n      :\n        exists lc' sc' mem',\n          (<<STEPS: rtc (@Thread.tau_step lang)\n                        th0\n                        (Thread.mk lang (Thread.state th1) lc' sc' mem')>>) /\\\n          (<<CONSISTENT: Local.promise_consistent lc'>>)\n    .\n    Proof.\n      eapply pred_steps_thread_steps in STEPS.\n      destruct th0, th1. ss.\n      hexploit steps_map.\n      { eapply ident_map_le. }\n      { eapply ident_map_bot. }\n      { eapply ident_map_eq. }\n      { i. eapply ident_map_mappable_evt. }\n      { eapply STEPS. }\n      { ss. }\n      { ss. }\n      { ss. }\n      { eapply Local.cap_wf; eauto. }\n      { eapply LOCAL. }\n      { eauto. }\n      { eapply Memory.cap_closed; eauto. }\n      { eauto. }\n      { eapply Memory.max_concrete_timemap_closed; eauto. }\n      { eapply map_ident_in_memory_local; eauto; ss.\n        eapply ident_map_lt.\n      }\n      { econs.\n        { i. destruct msg as [val released|]; auto. right.\n          exists to, from, (Message.concrete val released), (Message.concrete val released).\n          eapply Memory.cap_inv in GET; eauto. des; ss. esplits; eauto.\n          { refl. }\n          { eapply ident_map_message. }\n          { refl. }\n        }\n        { i. eapply CAP in GET. left. exists fto, ffrom, fto, ffrom. splits; ss.\n          { refl. }\n          { refl. }\n          { i. econs; eauto. }\n        }\n      }\n      { eapply mapping_map_lt_collapsable_unwritable. eapply ident_map_lt. }\n      { eapply ident_map_timemap. }\n      { eapply Memory.max_concrete_timemap_spec; eauto.\n        eapply Memory.cap_closed_timemap; eauto. }\n      { instantiate (1:=fun _ => True). ss. }\n      i. des. esplits.\n      { eapply rtc_implies; try apply STEP. i. inv H. inv TSTEP. econs; eauto. }\n      { inv LOCAL0. eapply promise_consistent_mon; cycle 1; eauto.\n        { refl. }\n        eapply promise_consistent_map; eauto.\n        { eapply ident_map_le; eauto. }\n        { eapply ident_map_eq; eauto. }\n      }\n    Qed.\n\n    Definition future_certify lang (e:Thread.t lang): Prop :=\n      forall sc1 mem1\n        (FUTURE: Memory.future_weak (Thread.memory e) mem1)\n        (FUTURE: TimeMap.le (Thread.sc e) sc1)\n        (WF: Local.wf (Thread.local e) mem1)\n        (SC: Memory.closed_timemap sc1 mem1)\n        (MEM: Memory.closed mem1),\n        (<<FAILURE: Thread.steps_failure (Thread.mk lang (Thread.state e) (Thread.local e) sc1 mem1)>>) \\/\n        exists e2,\n          (<<STEPS: rtc (@Thread.tau_step lang) (Thread.mk lang (Thread.state e) (Thread.local e) sc1 mem1) e2>>) /\\\n          (<<PROMISES: (Local.promises (Thread.local e2)) = Memory.bot>>).\n\n    Lemma future_certify_exists\n          e\n          (LOCAL: Local.wf (Thread.local e) (Thread.memory e))\n          (MEMORY: Memory.closed (Thread.memory e))\n          (SC: Memory.closed_timemap (Thread.sc e) (Thread.memory e))\n          (CONSISTENT: @Thread.consistent lang e):\n      future_certify e.\n    Proof.\n      eapply consistent_pf_consistent_super_strong in CONSISTENT; eauto. des.\n      exploit (@concrete_promise_max_timemap_exists (Thread.memory e) (Local.promises (Thread.local e))).\n      { eapply MEMORY. } i. des.\n      ii. exploit (CONSISTENT0 mem1 TimeMap.bot sc1); eauto. i. des.\n      eapply Trace.silent_steps_tau_steps in STEPS; cycle 1.\n      { eapply List.Forall_impl; eauto. i. ss. des. auto. }\n      unguard. des.\n      { left. unfold Thread.steps_failure. destruct e1. ss. esplits; eauto. }\n      { right. esplits; eauto. }\n    Qed.\n\n    Lemma future_consistent\n          e sc' mem'\n          (LOCAL: Local.wf (Thread.local e) (Thread.memory e))\n          (MEMORY: Memory.closed (Thread.memory e))\n          (SC: Memory.closed_timemap (Thread.sc e) (Thread.memory e))\n          (CONSISTENT: @Thread.consistent lang e)\n          (SC_FUTURE: TimeMap.le (Thread.sc e) sc')\n          (MEM_FUTURE: Memory.future_weak (Thread.memory e) mem')\n          (LOCAL': Local.wf (Thread.local e) mem')\n          (MEMORY': Memory.closed mem')\n          (SC': Memory.closed_timemap sc' mem'):\n      Thread.consistent (Thread.mk lang (Thread.state e) (Thread.local e) sc' mem').\n    Proof.\n      ii. ss.\n      eapply future_certify_exists; try exact CONSISTENT; eauto.\n      - etrans; eauto. eapply Memory.cap_future_weak; eauto.\n      - etrans; eauto.\n        hexploit Memory.cap_closed_timemap; try exact SC'; eauto. i.\n        hexploit Memory.max_concrete_timemap_spec; eauto.\n      - eapply Local.cap_wf; eauto.\n      - eapply Memory.max_concrete_timemap_closed; eauto.\n      - eapply Memory.cap_closed; eauto.\n    Qed.\n  End FutureCertify.\nEnd FutureCertify.\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/FutureCertify.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2678181990135334}}
{"text": "(** * Common Subexpression Elimination for PHOAS Syntax *)\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.Sorting.Mergesort.\nRequire Import Coq.Structures.Orders.\nRequire Import Crypto.Compilers.Syntax.\nRequire Import Crypto.Compilers.Z.Syntax.\nRequire Import Crypto.Compilers.Z.Syntax.Util.\nRequire Import Crypto.Compilers.CommonSubexpressionElimination.\nRequire Import Crypto.Compilers.CommonSubexpressionEliminationProperties.\n\nLocal Set Decidable Equality Schemes.\nLocal Set Boolean Equality Schemes.\nInductive symbolic_op :=\n| SOpConst (z : Z)\n| SAdd\n| SSub\n| SMul\n| SShl\n| SShr\n| SLand\n| SLor\n| SOpp\n| SIdWithAlt\n| SZselect\n| SMulSplit (bitwidth : Z)\n| SAddWithCarry\n| SAddWithGetCarry (bitwidth : Z)\n| SSubWithBorrow\n| SSubWithGetBorrow (bitwidth : Z)\n.\n\nDefinition symbolic_op_leb (x y : symbolic_op) : bool\n  := match x, y with\n     | SOpConst z1, SOpConst z2 => Z.leb z1 z2\n     | SAddWithGetCarry bw1, SAddWithGetCarry bw2 => Z.leb bw1 bw2\n     | SSubWithGetBorrow bw1, SSubWithGetBorrow bw2 => Z.leb bw1 bw2\n     | SOpConst _, _ => true\n     | _, SOpConst _ => false\n     | SAdd, _ => true\n     | _, SAdd => false\n     | SSub, _ => true\n     | _, SSub => false\n     | SMul, _ => true\n     | _, SMul => false\n     | SShl, _ => true\n     | _, SShl => false\n     | SShr, _ => true\n     | _, SShr => false\n     | SLand, _ => true\n     | _, SLand => false\n     | SLor, _ => true\n     | _, SLor => false\n     | SOpp, _ => true\n     | _, SOpp => false\n     | SIdWithAlt, _ => true\n     | _, SIdWithAlt => false\n     | SZselect, _ => true\n     | _, SZselect => false\n     | SMulSplit _, _ => true\n     | _, SMulSplit _ => false\n     | SAddWithCarry, _ => true\n     | _, SAddWithCarry => false\n     | SAddWithGetCarry _, _ => true\n     | _, SAddWithGetCarry _ => false\n     | SSubWithBorrow, _ => true\n     | _, SSubWithBorrow => false\n     (*| SSubWithGetBorrow _, _ => true\n     | _, SSubWithGetBorrow _ => false*)\n     end.\n\nLocal Notation symbolic_expr := (@symbolic_expr base_type symbolic_op).\nLocal Notation symbolic_expr_beq := (@symbolic_expr_beq base_type symbolic_op base_type_beq symbolic_op_beq).\nLocal Notation symbolic_expr_leb := (@symbolic_expr_leb base_type symbolic_op base_type_beq symbolic_op_beq symbolic_op_leb base_type_leb).\n\nDefinition symbolize_op s d (opc : op s d) : symbolic_op\n  := match opc with\n     | OpConst T z => SOpConst z\n     | Add T1 T2 Tout => SAdd\n     | Sub T1 T2 Tout => SSub\n     | Mul T1 T2 Tout => SMul\n     | Shl T1 T2 Tout => SShl\n     | Shr T1 T2 Tout => SShr\n     | Land T1 T2 Tout => SLand\n     | Lor T1 T2 Tout => SLor\n     | Opp T Tout => SOpp\n     | IdWithAlt T1 T2 Tout => SIdWithAlt\n     | Zselect T1 T2 T3 Tout => SZselect\n     | MulSplit bitwidth T1 T2 Tout1 Tout2 => SMulSplit bitwidth\n     | AddWithCarry T1 T2 T3 Tout => SAddWithCarry\n     | AddWithGetCarry bitwidth T1 T2 T3 Tout1 Tout2 => SAddWithGetCarry bitwidth\n     | SubWithBorrow T1 T2 T3 Tout => SSubWithBorrow\n     | SubWithGetBorrow bitwidth T1 T2 T3 Tout1 Tout2 => SSubWithGetBorrow bitwidth\n     end.\n\nDefinition denote_symbolic_op s d (opc : symbolic_op) : option (op s d)\n  := match opc, s, d with\n     | SOpConst z, Unit, Tbase T => Some (OpConst z)\n     | SAdd, Prod (Tbase _) (Tbase _), Tbase _ => Some (Add _ _ _)\n     | SSub, Prod (Tbase _) (Tbase _), Tbase _ => Some (Sub _ _ _)\n     | SMul, Prod (Tbase _) (Tbase _), Tbase _ => Some (Mul _ _ _)\n     | SShl, Prod (Tbase _) (Tbase _), Tbase _ => Some (Shl _ _ _)\n     | SShr, Prod (Tbase _) (Tbase _), Tbase _ => Some (Shr _ _ _)\n     | SLand, Prod (Tbase _) (Tbase _), Tbase _ => Some (Land _ _ _)\n     | SLor, Prod (Tbase _) (Tbase _), Tbase _ => Some (Lor _ _ _)\n     | SOpp, Tbase _, Tbase _ => Some (Opp _ _)\n     | SIdWithAlt, Prod (Tbase _) (Tbase _), Tbase _ => Some (IdWithAlt _ _ _)\n     | SZselect, Prod (Prod (Tbase _) (Tbase _)) (Tbase _), Tbase _ => Some (Zselect _ _ _ _)\n     | SMulSplit bitwidth, Prod (Tbase _) (Tbase _), Prod (Tbase _) (Tbase _)\n       => Some (MulSplit bitwidth _ _ _ _)\n     | SAddWithCarry, Prod (Prod (Tbase _) (Tbase _)) (Tbase _), Tbase _ => Some (AddWithCarry _ _ _ _)\n     | SAddWithGetCarry bitwidth, Prod (Prod (Tbase _) (Tbase _)) (Tbase _), Prod (Tbase _) (Tbase _)\n       => Some (AddWithGetCarry bitwidth _ _ _ _ _)\n     | SSubWithBorrow, Prod (Prod (Tbase _) (Tbase _)) (Tbase _), Tbase _ => Some (SubWithBorrow _ _ _ _)\n     | SSubWithGetBorrow bitwidth, Prod (Prod (Tbase _) (Tbase _)) (Tbase _), Prod (Tbase _) (Tbase _)\n       => Some (SubWithGetBorrow bitwidth _ _ _ _ _)\n     | SAdd, _, _\n     | SSub, _, _\n     | SMul, _, _\n     | SShl, _, _\n     | SShr, _, _\n     | SLand, _, _\n     | SLor, _, _\n     | SOpp, _, _\n     | SOpConst _, _, _\n     | SIdWithAlt, _, _\n     | SZselect, _, _\n     | SMulSplit _, _, _\n     | SAddWithCarry, _, _\n     | SAddWithGetCarry _, _, _\n     | SSubWithBorrow, _, _\n     | SSubWithGetBorrow _, _, _\n       => None\n     end.\n\nLemma symbolic_op_leb_total\n  : forall a1 a2, symbolic_op_leb a1 a2 = true \\/ symbolic_op_leb a2 a1 = true.\nProof.\n  induction a1, a2; simpl; auto;\n    rewrite !Z.leb_le; omega.\nQed.\n\nModule SymbolicExprOrder <: TotalLeBool.\n  Definition t := (flat_type base_type * symbolic_expr)%type.\n  Definition leb (x y : t) : bool := symbolic_expr_leb (snd x) (snd y).\n  Theorem leb_total : forall a1 a2, leb a1 a2 = true \\/ leb a2 a1 = true.\n  Proof.\n    intros; apply symbolic_expr_leb_total;\n      auto using internal_base_type_dec_bl, internal_base_type_dec_lb, internal_symbolic_op_dec_bl, internal_symbolic_op_dec_lb, base_type_leb_total, symbolic_op_leb_total.\n  Qed.\nEnd SymbolicExprOrder.\n\nModule Import SymbolicExprSort := Sort SymbolicExprOrder.\n\nFixpoint symbolic_op_args_to_list (t : flat_type base_type)\n         (opc : symbolic_op) (args : symbolic_expr)\n  : list (flat_type base_type * symbolic_expr)\n  := match args, t with\n     | SOp argT opc' args', _\n       => if symbolic_op_beq opc opc'\n          then symbolic_op_args_to_list argT opc args'\n          else (t, args)::nil\n     | SPair x y, Prod A B\n       => symbolic_op_args_to_list A opc x ++ symbolic_op_args_to_list B opc y\n     | SPair x y, Unit\n       => symbolic_op_args_to_list Unit opc x ++ symbolic_op_args_to_list Unit opc y\n     | STT, _\n     | SVar _, _\n     | SPair _ _, _\n     | SFst _ _ _, _\n     | SSnd _ _ _, _\n     | SInvalid, _\n       => (t, args)::nil\n     end%list.\n\nFixpoint symbolic_op_list_to_args (args : list (flat_type base_type * symbolic_expr)) : symbolic_expr\n  := match args with\n     | nil => SInvalid\n     | (t, arg)::nil => arg\n     | (t1, arg1)::(t2, arg2)::nil\n       => SPair arg1 arg2\n     | (t1, arg1)::(((t2, arg2)::args'') as args')\n       => SPair arg1 (SOp t2 SAdd (symbolic_op_list_to_args args'))\n     end%list.\n\nDefinition normalize_symbolic_expr_mod_c (opc : symbolic_op) (args : symbolic_expr) : symbolic_expr\n  := match opc with\n     | SAdd\n     | SMul\n     | SLand\n     | SLor\n       => let ls := symbolic_op_args_to_list Unit opc args in\n          let ls := sort ls in\n          symbolic_op_list_to_args ls\n     | SOpConst _\n     | SSub\n     | SShl\n     | SShr\n     | SOpp\n     | SIdWithAlt\n     | SZselect\n     | SMulSplit _\n     | SAddWithCarry\n     | SAddWithGetCarry _\n     | SSubWithBorrow\n     | SSubWithGetBorrow _\n       => args\n     end.\n\nDefinition csef inline_symbolic_expr_in_lookup {var t} (v : exprf _ _ t) xs\n  := @csef base_type symbolic_op base_type_beq symbolic_op_beq\n           internal_base_type_dec_bl op symbolize_op\n           normalize_symbolic_expr_mod_c\n           var inline_symbolic_expr_in_lookup t v xs.\n\nDefinition cse inline_symbolic_expr_in_lookup {var} (prefix : list _) {t} (v : expr _ _ t) xs\n  := @cse base_type symbolic_op base_type_beq symbolic_op_beq\n          internal_base_type_dec_bl op symbolize_op\n          normalize_symbolic_expr_mod_c\n          inline_symbolic_expr_in_lookup var prefix t v xs.\n\nDefinition CSE_gen inline_symbolic_expr_in_lookup {t} (e : Expr t) (prefix : forall var, list { t : flat_type base_type & exprf _ _ t })\n  : Expr t\n  := @CSE base_type symbolic_op base_type_beq symbolic_op_beq\n          internal_base_type_dec_bl op symbolize_op\n          normalize_symbolic_expr_mod_c\n          inline_symbolic_expr_in_lookup t e prefix.\n\nDefinition CSE inline_symbolic_expr_in_lookup {t} (e : Expr t)\n  : Expr t\n  := @CSE_gen inline_symbolic_expr_in_lookup t e (fun _ => nil).\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/CommonSubexpressionElimination.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.26777906459146267}}
{"text": "Require Import VerdiRaft.Raft.\nRequire Import VerdiRaft.RaftRefinementInterface.\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nRequire Import VerdiRaft.SpecLemmas.\nRequire Import VerdiRaft.RefinementSpecLemmas.\n\nRequire Import VerdiRaft.VotesReceivedMoreUpToDateInterface.\nRequire Import VerdiRaft.RequestVoteReplyMoreUpToDateInterface.\n\nRequire Import VerdiRaft.LeaderLogsVotesWithLogInterface.\n\nSection LeaderLogsVotesWithLog.\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 {vrmutdi : votesReceived_moreUpToDate_interface}.\n  Context {rvrmutdi : requestVoteReply_moreUpToDate_interface}.\n\n  Lemma quorum_preserved:\n    forall (st st' : name -> electionsData * raft_data)\n      (t0 : term) (ll : list entry) (leader : name),\n      (forall h t leader log,\n         In (t, leader, log) (votesWithLog (fst (st h))) ->\n         In (t, leader, log) (votesWithLog (fst (st' h)))) ->\n      (exists quorum : list name,\n         NoDup quorum /\\\n         length quorum > div2 (length nodes) /\\\n         (forall h : name,\n            In h quorum ->\n            exists log : list entry,\n              moreUpToDate (maxTerm ll) (maxIndex ll) (maxTerm log) (maxIndex log) =\n              true /\\ In (t0, leader, log) (votesWithLog (fst (st h))))) ->\n      exists quorum : list name,\n        NoDup quorum /\\\n        length quorum > div2 (length nodes) /\\\n        (forall h : name,\n           In h quorum ->\n           exists log : list entry,\n             moreUpToDate (maxTerm ll) (maxIndex ll) (maxTerm log) (maxIndex log) =\n             true /\\ In (t0, leader, log) (votesWithLog (fst (st' h)))).\n  Proof using. \n    intros.\n    break_exists_exists. intuition.\n    find_apply_hyp_hyp. break_exists_exists. intuition eauto.\n  Qed.\n  \n  Lemma leaderLogs_votesWithLog_append_entries :\n    refined_raft_net_invariant_append_entries leaderLogs_votesWithLog.\n  Proof using. \n    red. unfold leaderLogs_votesWithLog. intros. simpl in *.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    - find_rewrite_lem update_elections_data_appendEntries_leaderLogs.\n      eapply quorum_preserved; [|eauto].\n      intros.\n      find_higher_order_rewrite; destruct_update; simpl in *; eauto.\n      rewrite votesWithLog_same_append_entries. auto.\n    - eapply quorum_preserved; [|eauto].\n      intros.\n      find_higher_order_rewrite; destruct_update; simpl in *; eauto.\n      rewrite votesWithLog_same_append_entries. auto.\n  Qed.\n\n  Lemma leaderLogs_votesWithLog_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply leaderLogs_votesWithLog.\n  Proof using. \n    red. unfold leaderLogs_votesWithLog. intros. simpl in *.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    - eapply quorum_preserved; [|eauto].\n      intros.\n      find_higher_order_rewrite; destruct_update; simpl in *; eauto.\n    - eapply quorum_preserved; [|eauto].\n      intros.\n      find_higher_order_rewrite; destruct_update; simpl in *; eauto.\n  Qed.\n\n  Lemma update_elections_data_request_vote_votesWithLog_old :\n    forall (h : name)\n      (st : electionsData *\n            RaftState.raft_data term name entry logIndex serverType data clientId output)\n      (t : nat) (src : fin N) (lli llt : nat)\n      (t' : term) (h' : name) (l' : list entry),\n      In (t', h', l') (votesWithLog (fst st)) ->\n      In (t', h', l')\n         (votesWithLog (update_elections_data_requestVote h src t src lli llt st)).\n  Proof using. \n    intros.\n    unfold update_elections_data_requestVote in *.\n    repeat break_match; simpl in *; intuition.\n  Qed.\n\n  Lemma leaderLogs_votesWithLog_request_vote :\n    refined_raft_net_invariant_request_vote leaderLogs_votesWithLog.\n  Proof using. \n    red. unfold leaderLogs_votesWithLog. intros. simpl in *.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    - find_rewrite_lem leaderLogs_update_elections_data_requestVote.\n      eapply quorum_preserved; [|eauto].\n      intros.\n      find_higher_order_rewrite; destruct_update; simpl in *;\n      eauto using update_elections_data_request_vote_votesWithLog_old.\n    - eapply quorum_preserved; [|eauto].\n      intros.\n      find_higher_order_rewrite; destruct_update; simpl in *;\n      eauto using update_elections_data_request_vote_votesWithLog_old.\n  Qed.\n\n\n  Lemma wonElection_dedup_spec :\n    forall l,\n      wonElection (dedup name_eq_dec l) = true ->\n      exists quorum,\n        NoDup quorum /\\\n        length quorum > div2 (length nodes) /\\\n        (forall h, In h quorum -> In h l).\n  Proof using. \n    intros.\n    exists (dedup name_eq_dec l). intuition; eauto using NoDup_dedup, in_dedup_was_in.\n    unfold wonElection in *.\n    do_bool. lia.\n  Qed.\n        \n  Lemma leaderLogs_votesWithLog_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply leaderLogs_votesWithLog.\n  Proof using rvrmutdi vrmutdi. \n    red. unfold leaderLogs_votesWithLog. intros. simpl in *.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto;\n    [|eapply quorum_preserved; [|eauto];\n      intros;\n      find_higher_order_rewrite; destruct_update; simpl in *; eauto;\n      rewrite update_elections_data_request_vote_reply_votesWithLog;\n      auto].\n    find_eapply_lem_hyp leaderLogs_update_elections_data_RVR; eauto.\n    intuition;\n      [eapply quorum_preserved; [|eauto];\n       intros;\n       find_higher_order_rewrite; destruct_update; simpl in *; eauto;\n       rewrite update_elections_data_request_vote_reply_votesWithLog;\n       auto|].\n    subst.\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_eapply_lem_hyp handleRequestVoteReply_spec'.\n    intuition.\n    conclude_using \n      ltac:(repeat find_rewrite; congruence).\n    concludes.\n    intuition.\n    repeat find_rewrite.\n    find_apply_lem_hyp wonElection_dedup_spec.\n    break_exists_exists. intuition.\n    find_apply_hyp_hyp.\n    simpl in *. intuition.\n    - subst.\n      find_eapply_lem_hyp requestVoteReply_moreUpToDate_invariant; eauto.\n      repeat find_rewrite.\n      repeat conclude_using eauto.\n      break_exists_exists. intuition.\n      find_higher_order_rewrite.\n      simpl in *.\n      destruct_update; subst; simpl in *; eauto.\n      repeat find_rewrite.\n      rewrite update_elections_data_request_vote_reply_votesWithLog. auto.\n    - find_eapply_lem_hyp votesReceived_moreUpToDate_invariant; eauto.\n      break_exists_exists. intuition.\n      find_higher_order_rewrite.\n      destruct_update; simpl in *; eauto.\n      rewrite update_elections_data_request_vote_reply_votesWithLog. auto.\n  Qed.\n\n  Lemma update_elections_data_timeout_votesWithLog_old :\n    forall h st t h' l,\n      In (t, h', l) (votesWithLog (fst st)) ->\n      In (t, h', l) (votesWithLog (update_elections_data_timeout h st)).\n  Proof using. \n    intros.\n    unfold update_elections_data_timeout.\n    repeat break_match; simpl in *; auto.\n  Qed.\n\n  Lemma leaderLogs_votesWithLog_timeout :\n    refined_raft_net_invariant_timeout leaderLogs_votesWithLog.\n  Proof using. \n    red. unfold leaderLogs_votesWithLog. intros. simpl in *.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto;\n    [|eapply quorum_preserved; [|eauto];\n      intros;\n      find_higher_order_rewrite; destruct_update; simpl in *; eauto;\n      apply update_elections_data_timeout_votesWithLog_old;\n      auto].\n    find_rewrite_lem update_elections_data_timeout_leaderLogs.\n    eapply quorum_preserved; [|eauto];\n      intros;\n      find_higher_order_rewrite; destruct_update; simpl in *; eauto;\n      apply update_elections_data_timeout_votesWithLog_old;\n      auto.\n  Qed.\n\n  Lemma leaderLogs_votesWithLog_client_request :\n    refined_raft_net_invariant_client_request leaderLogs_votesWithLog.\n  Proof using. \n    red. unfold leaderLogs_votesWithLog. intros. simpl in *.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto;\n    [|eapply quorum_preserved; [|eauto];\n      intros;\n      find_higher_order_rewrite; destruct_update; simpl in *; eauto;\n      rewrite votesWithLog_same_client_request;\n      auto].\n    find_rewrite_lem update_elections_data_client_request_leaderLogs.\n    eapply quorum_preserved; [|eauto];\n      intros;\n      find_higher_order_rewrite; destruct_update; simpl in *; eauto;\n      rewrite votesWithLog_same_client_request;\n      auto.\n  Qed.\n\n  Lemma leaderLogs_votesWithLog_do_leader :\n    refined_raft_net_invariant_do_leader leaderLogs_votesWithLog.\n  Proof using. \n    red. unfold leaderLogs_votesWithLog. 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;\n    solve [eapply quorum_preserved; [|eauto];\n           intros;\n           find_higher_order_rewrite; destruct_update; simpl in *; eauto;\n           auto].\n  Qed.\n\n  Lemma leaderLogs_votesWithLog_do_generic_server :\n    refined_raft_net_invariant_do_generic_server leaderLogs_votesWithLog.\n  Proof using. \n    red. unfold leaderLogs_votesWithLog. 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;\n    solve [eapply quorum_preserved; [|eauto];\n           intros;\n           find_higher_order_rewrite; destruct_update; simpl in *; eauto;\n           auto].\n  Qed.\n\n  Lemma leaderLogs_votesWithLog_reboot :\n    refined_raft_net_invariant_reboot leaderLogs_votesWithLog.\n  Proof using. \n    red. unfold leaderLogs_votesWithLog. 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;\n    solve [eapply quorum_preserved; [|eauto];\n           intros;\n           find_higher_order_rewrite; destruct_update; simpl in *; eauto;\n           auto].\n  Qed.\n\n  Lemma leaderLogs_votesWithLog_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset leaderLogs_votesWithLog.\n  Proof using. \n    red. unfold leaderLogs_votesWithLog. intros. simpl in *.\n    subst. repeat find_reverse_higher_order_rewrite.\n    eapply quorum_preserved; [|eauto];\n    intros;\n    find_higher_order_rewrite; destruct_update; simpl in *; eauto;\n    auto.\n  Qed.\n\n  Lemma leaderLogs_votesWithLog_init :\n    refined_raft_net_invariant_init leaderLogs_votesWithLog.\n  Proof using. \n    red. unfold leaderLogs_votesWithLog. intros. simpl in *.\n    intuition.\n  Qed.\n  \n  Instance llvwli : leaderLogs_votesWithLog_interface.\n  split.\n  intros.\n  apply refined_raft_net_invariant; auto.\n  - apply leaderLogs_votesWithLog_init.\n  - apply leaderLogs_votesWithLog_client_request.\n  - apply leaderLogs_votesWithLog_timeout.\n  - apply leaderLogs_votesWithLog_append_entries.\n  - apply leaderLogs_votesWithLog_append_entries_reply.\n  - apply leaderLogs_votesWithLog_request_vote.\n  - apply leaderLogs_votesWithLog_request_vote_reply.\n  - apply leaderLogs_votesWithLog_do_leader.\n  - apply leaderLogs_votesWithLog_do_generic_server.\n  - apply leaderLogs_votesWithLog_state_same_packet_subset.\n  - apply leaderLogs_votesWithLog_reboot.\n  Qed.\n  \nEnd LeaderLogsVotesWithLog.\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/LeaderLogsVotesWithLogProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.26777906459146267}}
{"text": "Require Import JaSyntax.\nRequire Import String.\nRequire Import Lists.List.\nImport ListNotations.\nOpen Scope list_scope.\nRequire Import NPeano.\nRequire Import PeanoNat.\nRequire Export Arith.\nOpen Scope nat_scope.\nRequire Import JaTactics.\n\nFrom Hammer Require Import Reconstr.\n\n\n\n(* Require Import Arith_base.\nRequire Import BinPos.\nRequire Import BinInt.\nRequire Import Zorder. *)\n\n\n(** The boolean function that returns [true] when [cname] is the name of the class declared as [cdecl]. *)\nDefinition is_class_name cn cd :=\n  match cd with\n    | JFCDecl dn _ _ _ => if JFClassName_dec dn cn then true else false\n  end.\n\nLemma is_class_name_name:\n  forall cn ex fields methods,\n    is_class_name cn (JFCDecl cn ex fields methods) = true.\nProof.\n  intros.\n  unfold is_class_name.\n  destruct (JFClassName_dec cn cn).\n  auto.\n  tauto.\nQed.\n\nLemma is_class_name_name_cd:\n  forall cd,\n    is_class_name (name_of_cd cd) cd = true.\nProof.\n  intros.\n  destruct cd.\n  unfold name_of_cd.\n  unfold is_class_name.\n  destruct (JFClassName_dec cn cn); try contradiction;auto.\nQed.\n\n\nLemma is_class_name_neq:\n  forall cn dn ex fields methods,\n    cn<>dn ->\n    is_class_name cn (JFCDecl dn ex fields methods) = false.\nProof.\n  intros.\n  unfold is_class_name.\n  destruct (JFClassName_dec dn cn).\n  auto.\n  rewrite e in *.\n  tauto.\n  auto.\nQed.\n\n\nLemma is_class_name_equal:\n  forall cn dn ex fields methods,\n    is_class_name cn (JFCDecl dn ex fields methods) = true ->\n    cn = dn.\nProof.\n  intros.\n  unfold is_class_name in H.\n  destruct (JFClassName_dec dn cn).\n  auto.\n  discriminate H.\nQed.\n\nLemma is_class_name_nequal:\n  forall cn dn ex fields methods,\n    is_class_name cn (JFCDecl dn ex fields methods) = false ->\n    cn <> dn.\nProof.\n  intros.\n  unfold is_class_name in H.\n  destruct (JFClassName_dec dn cn).\n  discriminate H.\n  auto.\nQed.\n\nLemma program_contains_counts_occ:\n  forall CC cn, \n    program_contains CC cn = true ->\n    (count_occ Bool.bool_dec (map (is_class_name cn) CC) true > 0)%nat.\nProof.\n  induction CC.\n  * intros.\n    simpl in H.\n    discriminate H.\n  * intros.\n    destruct a.\n    destruct (JFClassName_dec cn0 cn).\n    ** subst.\n       rewrite map_cons.\n       unfold is_class_name.\n       destruct (JFClassName_dec cn cn); try contradiction.\n       rewrite count_occ_cons_eq; auto. \n       auto with zarith.\n    ** rewrite map_cons.\n       unfold is_class_name.\n       destruct (JFClassName_dec cn0 cn); subst; try contradiction.\n       rewrite count_occ_cons_neq; auto.\n       fold (is_class_name cn0).\n       apply IHCC;eauto 2.\n       eapply program_contains_further_neq;eauto.\nQed.\n\n(** The property to check that class name [cname] occurs only once in the program [P]. *)\nDefinition name_once (CC:JFProgram) (cn:JFClassName) :=\n count_occ Bool.bool_dec (map (is_class_name cn) CC) true = 1%nat.\n\nLemma in_head_not_in_tail:\n  forall (CC:JFProgram) (cn:JFClassName) (cd:JFClassDeclaration),\n    (is_class_name cn cd) = true ->\n    name_once (cd :: CC) cn -> ~ name_once CC cn.\nProof.\n  induction CC.\n  * intros.\n    compute.\n    intro.\n    discriminate H1.\n  * intros.\n    unfold name_once in H0.\n    rewrite map_cons in H0.\n    rewrite H in H0.\n    rewrite count_occ_cons_eq in H0.\n    set (XX := (count_occ Bool.bool_dec (map (is_class_name cn) (a :: CC)) true)) in H0.\n    injection H0.\n    intros.\n    unfold XX in *.\n    intro.\n    unfold name_once in H2.\n    rewrite H1 in H2.\n    discriminate H2.\n    auto.\nQed.\n\nLemma name_once_further:\n  forall cn dn CC ex fields methods,\n  cn<>dn ->\n  name_once (JFCDecl cn ex fields methods :: CC) dn -> name_once CC dn.\nProof.\n  intros.\n  unfold name_once in H0.\n  rewrite map_cons in H0.\n  rewrite is_class_name_neq in H0.\n  rewrite count_occ_cons_neq in H0.\n  auto.\n  auto.\n  auto.\nQed.\n\nLemma name_once_further_neq:\n  forall cn dn CC ex ms fs,\n    cn <> dn ->\n    name_once CC dn ->\n    name_once (JFCDecl cn ex ms fs :: CC) dn.\nProof.\n  intros.\n  unfold name_once in *.\n  rewrite map_cons.\n  rewrite is_class_name_neq; auto.\nQed.\n\nLemma name_once_further_eq:\n  forall cn CC ex fields methods,\n    count_occ Bool.bool_dec (map (is_class_name cn) CC) true = 0%nat ->\n    name_once (JFCDecl cn ex fields methods :: CC) cn.\nProof.\n  unfold name_once.\n  intros.\n  rewrite map_cons.\n  rewrite is_class_name_name.\n  rewrite count_occ_cons_eq; auto.\nQed.\n\nLemma count_occ_zero_is_class_name_false:\n  forall CC cn cd,\n    count_occ Bool.bool_dec (map (is_class_name cn) CC) true = 0%nat ->\n    In cd CC ->\n    is_class_name cn cd = false.\nProof.\n  induction CC.\n  * intros.\n    unfold In in H0.\n    tauto.\n  * intros.\n    apply in_inv in H0.\n    destruct H0.\n    - rewrite H0 in *.\n      rewrite map_cons in H.\n      apply <- count_occ_not_In in H.\n      apply not_in_cons in H.\n      destruct H.\n      destruct (is_class_name cn cd).\n      + tauto.\n      + auto.\n    - apply IHCC.\n      rewrite map_cons in H.\n      assert (is_class_name cn a <> true).\n      apply <- count_occ_not_In in H.\n      apply not_in_cons in H.\n      intuition.\n      rewrite <- (count_occ_cons_neq  Bool.bool_dec (map (is_class_name cn) CC) H1).\n      auto.\n      trivial.\nQed.\n\n\n\n(** The property to check that declaraion [cdecl] occurs only once in the program [P]. *)\nDefinition decl_once (CC:JFProgram) (cd:JFClassDeclaration) :=\n  match cd with\n    | JFCDecl cn _ _ _ => name_once CC cn\n  end.\n\nLemma count_occ_zero_decl_once:\n  forall CC cn ex ms fs ex1 ms1 fs1,\n    count_occ Bool.bool_dec (map (is_class_name cn) CC) true = 0%nat ->                                                         \n    decl_once (JFCDecl cn ex ms fs :: CC) (JFCDecl cn ex1 ms1 fs1).\nProof.\n  intros.\n  unfold decl_once.\n  apply name_once_further_eq.\n  auto.\nQed.\n\nLemma decl_in_head_not_in_tail:\n  forall (CC:JFProgram) (cn:JFClassName) (cd:JFClassDeclaration),\n    (is_class_name cn cd) = true ->\n    (decl_once (cd :: CC) cd) ->\n    ~ (decl_once CC cd).\nProof.\n  intros.\n  unfold decl_once in *.\n  destruct cd.\n  unfold is_class_name in H.\n  destruct (JFClassName_dec cn0 cn).\n  rewrite e in *.\n  apply (in_head_not_in_tail CC cn (JFCDecl cn ex fields methods)).\n  apply is_class_name_name.\n  auto.\n  discriminate H.\nQed.\n\n\n\nLemma decl_in_head_false_in_tail:\n  forall (CC:JFProgram) (cn:JFClassName) (cd:JFClassDeclaration),\n    (is_class_name cn cd) = true ->\n    (decl_once (cd :: CC) cd) ->\n    Forall (fun x0 => is_class_name cn x0 = false) CC.\nProof.\n  intros.\n  unfold decl_once in *.\n  destruct cd.\n  apply is_class_name_equal in H.\n  rewrite H in *.\n  unfold name_once in H0.\n  rewrite map_cons in H0.\n  rewrite is_class_name_name in H0.\n  rewrite count_occ_cons_eq in H0; auto.\n  injection H0; intros.\n  apply Forall_forall.\n  intros.\n  eapply count_occ_zero_is_class_name_false; try apply H1; auto.\nQed.\n\nLemma decs_once_monotone:\n  forall (CC:JFProgram) (cd:JFClassDeclaration)\n         (dd:JFClassDeclaration) (cn:JFClassName),\n    decl_once (cd :: CC) dd ->\n    is_class_name cn cd = true ->\n    is_class_name cn dd = false ->\n    decl_once CC dd.\nProof.\n  intros.\n  unfold decl_once.\n  destruct dd.\n  unfold decl_once in H.\n  destruct cd.\n  apply is_class_name_equal in H0.\n  rewrite H0 in *.\n  eapply name_once_further.\n  apply is_class_name_nequal in H1.\n  eapply H1.\n  apply H.\nQed.\n  \n(** The property that all class names occur in the program uniquely. *)\nDefinition names_unique (CC:JFProgram) :=\n  Forall (decl_once CC) CC.\n\nLemma names_unique_zero:\n  forall CC cn ex fields methods,\n    names_unique (JFCDecl cn ex fields methods :: CC) ->\n    count_occ Bool.bool_dec (map (is_class_name cn) CC) true = 0%nat.\nProof.\n  intros.\n  unfold names_unique in H.\n  apply Forall_inv in H.\n  unfold decl_once in H.\n  unfold name_once in H.\n  rewrite map_cons in H.\n  rewrite is_class_name_name in H.\n  rewrite count_occ_cons_eq in H; auto.\nQed.\n\nLemma names_unique_cons:\n  forall CC cn ex ms fs,\n    count_occ Bool.bool_dec (map (is_class_name cn) CC) true = 0%nat ->\n    names_unique CC ->\n    names_unique (JFCDecl cn ex ms fs :: CC).\nProof.\n  intros.\n  unfold names_unique.\n  apply Forall_cons.\n  + apply count_occ_zero_decl_once.\n    auto.\n  + apply Forall_forall.\n    intros.\n    unfold names_unique in H0.\n    assert (forall y, In y CC -> (decl_once CC) y).\n    apply (Forall_forall (decl_once CC) CC).\n    auto.\n    destruct x.\n    assert (is_class_name cn (JFCDecl cn0 ex0 fields methods) = false). {\n      eapply count_occ_zero_is_class_name_false.\n      apply H.\n      auto.\n    }\n    apply (is_class_name_nequal) in H3.\n    unfold decl_once.\n    apply name_once_further_neq; auto.\n    assert (decl_once CC (JFCDecl cn0 ex0 fields methods)).\n    apply H2; auto.\n    unfold decl_once in H4; auto.\nQed.\n\nLemma names_unique_further:\n  forall (CC:JFProgram) (cd:JFClassDeclaration),\n    names_unique (cd :: CC) ->\n    names_unique CC.\nProof.\n  intros.\n  unfold names_unique in H.\n  inversion H.\n  unfold names_unique.\n  assert (forall x, In x CC -> (decl_once CC) x).\n  intros.\n  assert (forall x, In x CC -> (decl_once (cd :: CC)) x).\n  apply -> (Forall_forall (decl_once (cd :: CC)) CC).\n  auto.\n  assert (decl_once (cd :: CC) x0).\n  apply H5.\n  auto.\n  destruct cd.\n  apply (decs_once_monotone CC (JFCDecl cn ex fields methods) x0 cn).\n  auto.\n  unfold is_class_name.\n  destruct (JFClassName_dec cn cn).\n  auto.\n  tauto.\n  assert (Forall (fun x0 => is_class_name cn x0 = false) CC).\n  apply (decl_in_head_false_in_tail CC cn (JFCDecl cn ex fields methods)).\n  unfold is_class_name.\n  destruct (JFClassName_dec cn cn);auto.\n  auto.\n  assert (forall x, In x CC -> (is_class_name cn x = false)).\n  apply Forall_forall.\n  auto.\n  apply H8.\n  auto.\n  apply Forall_forall.\n  auto.\nQed.\n\nLemma names_unique_decompose_program:\n  forall (CC1 CC2:JFProgram),\n    names_unique (CC1 ++ CC2) ->\n    names_unique CC2.\nProof.\n  induction CC1.\n  + intros.\n    simpl in *.\n    auto.\n  + intros.\n    simpl in H.\n    unfold names_unique in H.\n    apply IHCC1.\n    unfold names_unique.\n    assert (forall x, In x (a :: CC1 ++ CC2) -> (decl_once (a :: CC1 ++ CC2)) x)\n      by (apply -> Forall_forall;auto).\n    apply <- Forall_forall.\n    intros.\n    destruct (JFClassName_dec (name_of_cd a) (name_of_cd x)).\n    ++ subst.\n       assert (decl_once (a :: CC1 ++ CC2) a) by eauto using in_eq.\n       assert (decl_once (a :: CC1 ++ CC2) x).\n       {\n         unfold decl_once.\n         unfold decl_once in H2.\n         destruct x.\n         destruct a.\n         simpl in e.\n         rewrite <- e.\n         auto.\n       }\n       assert (decl_once (x :: CC1 ++ CC2) x).\n       {\n         unfold decl_once.\n         unfold decl_once in H3.\n         destruct x.\n         destruct a.\n         simpl in e.\n         rewrite e in H3.\n         unfold name_once.\n         unfold name_once in H3.\n         simpl in H3.\n         simpl.\n         auto.\n       }\n       assert (~ decl_once (CC1 ++ CC2) x).\n       {\n         apply (decl_in_head_not_in_tail (CC1 ++ CC2) (name_of_cd x)).\n         apply is_class_name_name_cd; auto.\n         auto.\n       } \n       destruct x.\n       assert (In (is_class_name cn (JFCDecl cn ex fields methods))\n                  (map (is_class_name cn) (CC1 ++ CC2))) by eauto using in_map.\n       assert (count_occ Bool.bool_dec (map (is_class_name cn) (CC1 ++ CC2))\n                         (is_class_name cn (JFCDecl cn ex fields methods)) > 0)\n         by (apply count_occ_In; eauto).\n       unfold decl_once in H4.\n       unfold name_once in H4.\n       simpl in H4.\n       simpl in H7.\n       destruct (JFClassName_dec cn cn);try contradiction.\n       destruct (Bool.bool_dec true true);try contradiction.\n       injection H4;intros.\n       rewrite H8 in H7.\n       apply gt_irrefl in H7.\n       contradiction.\n    ++ eapply decs_once_monotone.\n       apply H0.\n       apply in_cons;auto.\n       apply is_class_name_name_cd.\n       unfold is_class_name.\n       destruct x.\n       destruct (JFClassName_dec cn (name_of_cd a)).\n       +++ rewrite <-  e in n.\n           simpl in n.\n           contradiction.\n       +++ trivial.\nQed.\n\nLemma names_unique_further_further:\n  forall (CC:JFProgram) (cd dd:JFClassDeclaration),\n    names_unique (cd::dd::CC) ->\n    names_unique (cd::CC).\nProof.\n  intros.\n  destruct cd.\n  apply  names_unique_cons.\n  - apply (names_unique_zero CC cn ex fields methods).\n    apply (names_unique_cons).\n    assert (count_occ Bool.bool_dec (map (is_class_name cn)\n                                         (dd :: CC)) true = 0). {\n      apply (names_unique_zero (dd :: CC) cn ex fields methods).\n      auto.\n    }\n    rewrite map_cons in H0.\n    destruct (is_class_name cn dd).\n    rewrite count_occ_cons_eq in H0; discriminate H0; auto.\n    rewrite count_occ_cons_neq in H0; auto.\n    eauto using names_unique_further.\n  - eauto using names_unique_further.\nQed.\n\nLemma count_zero_count_nzero:\n  forall CC cn ex fields methods,\n         count_occ JFClassDeclaration_dec CC\n         (JFCDecl cn ex fields methods) > 0 ->\n         count_occ Bool.bool_dec (map (is_class_name cn) CC) true = 0 ->\n         False.\nProof.\n  induction CC; intros.\n  - rewrite count_occ_nil in H.\n    assert (0<>0).\n    apply Lt.lt_0_neq.\n    auto.\n    tauto.\n  - destruct a.\n    destruct (JFClassName_dec cn0 cn).\n    + rewrite e in *.\n      rewrite map_cons in H0.\n      rewrite is_class_name_name in H0.\n      rewrite count_occ_cons_eq in H0.\n      discriminate H0.\n      auto.\n    + rewrite map_cons in H0.\n      rewrite is_class_name_neq in H0.\n      rewrite count_occ_cons_neq in H0.\n      rewrite count_occ_cons_neq in H.\n      eauto using IHCC.\n      congruence.\n      congruence.\n      auto.\nQed.\n\nLemma names_unique_find_class_unique:\n  forall CC cn cd cd',\n         names_unique CC ->\n         find_class CC cn = Some cd ->\n         find_class CC cn = Some cd' ->\n         cd = cd'.\nProof.\n  induction CC.\n  + intros.\n    simpl in H0.\n    discriminate H0.\n  + intros.\n    destruct a.\n    destruct (JFClassName_dec cn cn0).\n    ++ subst.\n       simpl in H1.\n       simpl in H0.\n       destruct (JFClassName_dec cn0 cn0); try contradiction.\n       rewrite H0 in *.\n       injection H1.\n       tauto.\n    ++ apply find_class_further_neq in H0; auto.\n       apply find_class_further_neq in H1; auto.\n       eapply IHCC;eauto using names_unique_further.\nQed.\n  \nHint Resolve names_unique_zero names_unique_cons names_unique_further names_unique_further_further names_unique_decompose_program count_zero_count_nzero is_class_name_name is_class_name_name_cd names_unique_find_class_unique.\n     \nLemma in_names_unique_eq:\n  forall CC cn ex fields methods ex0 fields0 methods0,\n    In (JFCDecl cn ex fields methods)\n       (JFCDecl cn ex0 fields0 methods0 :: CC) ->\n    names_unique  (JFCDecl cn ex0 fields0 methods0 :: CC) ->\n    (ex = ex0 /\\ fields = fields0 /\\ methods = methods0).\nProof.\n  intros.\n  simpl in H.\n  destruct H.\n  - injection H; auto.\n  - apply -> (count_occ_In JFClassDeclaration_dec) in H.\n    apply names_unique_zero in H0.\n    clear -H H0.\n    auto with zarith.\n    assert False by eauto.\n    tauto.\nQed.\n\nHint Resolve  in_names_unique_eq.\n\nLemma is_class_and_occ_zero:\n  forall CC cn dn cd, names_unique CC ->\n            find_class CC cn = Some cd ->\n            count_occ Bool.bool_dec (map (is_class_name dn) CC) true = 0 ->\n            cn <> dn.\nProof.\n  induction CC.\n  + sauto.\n  + intros.\n    destruct a.\n    assert ({cn=dn} + {cn<>dn}) by apply JFClassName_dec.\n    destruct H2.\n    * rewrite e in *.\n      rewrite map_cons in H1.\n      unfold is_class_name in H1.\n      destruct (JFClassName_dec cn0 dn).\n      - pose count_occ_cons_eq; scrush.\n      - pose count_occ_cons_neq; pose names_unique_further;\n          pose find_class_further_neq; scrush.\n    * auto.\nQed.\n\nLemma names_unique_count_class_name:\n  forall CC cn ex flds mthds,\n    names_unique CC ->\n    count_occ Bool.bool_dec (map (is_class_name cn) CC)\n              true = 0 ->\n    count_occ JFClassDeclaration_dec CC (JFCDecl cn ex flds mthds) = 0.\nProof.\n  induction CC.\n  - intros; simpl; auto.\n  - intros.\n    rewrite map_cons in H0.\n    destruct (Bool.bool_dec (is_class_name cn a) true).\n    + rewrite count_occ_cons_eq in H0; auto.\n      discriminate H0.\n    + rewrite count_occ_cons_neq.\n      eapply IHCC.\n      eauto using names_unique_further.\n      rewrite count_occ_cons_neq in H0; auto.\n      destruct a.\n      assert (is_class_name cn (JFCDecl cn0 ex fields methods) = false).\n      simpl in n.\n      destruct (JFClassName_dec cn0 cn).\n      tauto.\n      simpl. destruct (JFClassName_dec cn0 cn); tauto.\n      apply is_class_name_nequal in H1.\n      congruence.\nQed.      \n\nLemma in_find_class_raw:\n  forall CC cn ex fields methods,\n    In (JFCDecl cn ex fields methods) CC ->\n    exists ex1 fields1 methods1,\n    find_class CC cn = Some (JFCDecl cn ex1 fields1 methods1).\nProof.\n  induction CC.\n  * intros.\n    inversion H.\n  *  intros.\n     destruct (JFClassDeclaration_dec (JFCDecl cn ex fields methods) a).\n     ** rewrite <- e.\n        simpl.\n        destruct (JFClassName_dec cn cn); try contradiction.\n        clear.\n        do 3 eexists.\n        auto.\n     ** simpl.\n        destruct a.\n        destruct (JFClassName_dec cn0 cn).\n        *** subst.\n            clear. do 3 eexists. auto.\n        *** eapply IHCC.\n            eapply in_inv in H.\n            destruct H.\n            + injection H;intros;clear H.\n              contradiction.\n            + eauto.\nQed.    \n\nLemma in_find_class:\n  forall CC cn ex fields methods,\n    names_unique CC ->\n    In (JFCDecl cn ex fields methods) CC ->\n    find_class CC cn = Some (JFCDecl cn ex fields methods).\nProof.\n  induction CC;intros.\n  - assert (~ In (JFCDecl cn ex fields methods) []) by  auto using in_nil.\n    tauto.\n  - destruct (JFClassDeclaration_dec (JFCDecl cn ex fields methods) a).\n    + rewrite <- e. simpl.\n      destruct (JFClassName_dec cn cn); eauto.\n      tauto.\n    + destruct a.\n      simpl.\n      destruct (JFClassName_dec cn0 cn).\n      rewrite e in *.\n      assert (ex = ex0 /\\ fields = fields0 /\\ methods = methods0)\n        by eauto.\n      decompose [and] H1; clear H1.\n      congruence.\n      apply in_inv in H0.\n      destruct H0.\n      injection H0;intros.\n      tauto.\n      eapply IHCC; eauto.\nQed.\n\nHint Resolve in_find_class.\n\n\nLemma names_unique_in_neq:\n  forall CC cn dn ex fields methods ex1 fields1 methods1,\n    names_unique (JFCDecl cn ex fields methods :: CC) ->\n    In (JFCDecl dn ex1 fields1 methods1) CC ->\n    cn <> dn.\nProof.\n  intros.\n  assert (dn<>cn).\n  assert (count_occ Bool.bool_dec (map (is_class_name cn) CC) true = 0) by eauto.\n  assert (find_class CC dn = Some (JFCDecl dn ex1 fields1 methods1)) by eauto.\n  eapply is_class_and_occ_zero.\n  eapply names_unique_further; eauto.\n  eauto.\n  eauto.\n  auto.\nQed.\n\n\n\nHint Resolve names_unique_in_neq : myhints.\n\nLemma names_unique_count_zero:\n  forall CC cn ex fields methods,\n    names_unique (JFCDecl cn ex fields methods :: CC) ->\n    count_occ Bool.bool_dec (map (is_class_name cn) CC) true = 0.\nProof.\n  scrush.\nQed.\n\n\n\n\nLemma names_unique_neq_but_in:\n  forall CC cd dd,\n         In cd (cd :: CC) ->\n         dd <> cd ->\n         names_unique (cd :: CC) ->\n         In dd CC -> name_of_cd dd <> name_of_cd cd.\nProof.\n  intros.\n  destruct cd.\n  destruct dd.\n  simpl.\n  assert (count_occ Bool.bool_dec (map (is_class_name cn) CC) true = 0) by eauto.\n  assert (count_occ Bool.bool_dec (map (is_class_name cn0) CC) true > 0).\n  apply count_occ_In.\n  assert (names_unique CC) by eauto using names_unique_further.\n  unfold names_unique in H4.\n  assert (forall x,In x CC -> decl_once CC x) by (apply Forall_forall; auto).\n  assert (decl_once CC (JFCDecl cn0 ex0 fields0 methods0)) by auto.\n  unfold decl_once in H6.\n  unfold name_once in H6.\n  assert (count_occ Bool.bool_dec (map (is_class_name cn0) CC) true >0) by\n      try (rewrite H6; apply Gt.gt_Sn_O).\n  apply <- count_occ_In; eauto.\n  intro.\n  rewrite H5 in *.\n  rewrite H3 in H4.\n  apply (Gt.gt_irrefl 0 H4).\nQed.\n  \n\nLemma in_find_class_eq:\n  forall CC cd cd',\n    names_unique CC ->\n    In cd CC ->\n    find_class CC (name_of_cd cd) = Some cd' -> cd = cd'.\nProof.\n  induction CC;intros.\n  - assert (~ In cd []) by  auto using in_nil.\n    tauto.\n  - destruct (JFClassDeclaration_dec cd a).\n    + simpl in H1. rewrite e in *.\n      destruct a.\n      simpl in H1.\n      destruct (JFClassName_dec cn cn);\n      try injection H1;\n      tauto.\n    + assert (names_unique CC) by eauto using names_unique_further.\n      assert (a = cd \\/ In cd CC) by eauto.\n      destruct H3. symmetry in H3. contradiction.\n      assert (name_of_cd cd <> name_of_cd a).\n      apply (names_unique_neq_but_in CC a cd); auto.\n      auto using in_eq.\n      assert (find_class CC (name_of_cd cd) = Some cd').\n      destruct a.\n      eapply find_class_further_neq.\n      simpl in H4.\n      assert (cn <> name_of_cd cd) by auto.\n      eauto.\n      eauto.\n      apply IHCC; auto.\nQed.\n\n\n\n(**\n   Calculates the list of fields in an object of the given class name\n   [cname] traversing recursively its subtyping hierarchy up to _Object_.\n   The parameter [n] is added to ensure the correcntess of\n   structural recursion. The parameter [res] contains the triples\n   of fields collected so far in possibly earlier computation.\n\n   The function returns [Some] value in case its calculation is\n   correct. In case the calculation is not correct (when\n   - the structural induction parameter is too small,\n   - there is a non _Object_ class, which is not extended,\n   - there is no class of the given name in the program),\n   the function returns [None].\n *)\nFixpoint flds_aux (CC:JFProgram) cn n res {struct n} : option (list JFFieldDeclaration) := \n  match find_class CC cn with\n  | None => None\n  | Some cd => \n    let fr := flds_of_cd cd in\n    match cd with\n    | JFCDecl _ None _ _ => Some (res ++ fr)\n    | JFCDecl _ (Some ex) _ _ => \n      match n with\n      | 0 => None\n      | S k => flds_aux CC ex k (res ++ fr)\n      end\n    end\n  end.\n\n\n    \n\n\nLemma flds_aux_not_object_not_find_class:\n  forall CC cn n fds,\n    find_class CC cn = None ->\n    cn <> JFObjectName ->\n    flds_aux CC cn n fds = None.\nProof.\n  destruct n.\n  * intros. simpl.\n    rewrite H.\n    auto.\n  * intros. simpl.\n    rewrite H.\n    auto.\nQed.\n\nLemma flds_aux_not_object_find_class_ex_zero:\n  forall CC cn dn fields methods fds,\n    find_class CC cn = Some (JFCDecl cn (Some dn) fields methods) ->\n    flds_aux CC cn 0 fds = None.\nProof.\n  intros.\n  simpl.\n  rewrite H.\n  auto.\nQed.\n\nLemma flds_aux_not_object_in_first_none:\n  forall CC n cn fields methods fds,\n    exists flds',\n    flds_aux ((JFCDecl cn None fields methods) :: CC) cn n fds = Some flds'.\nProof.\n  intros.\n  destruct n.\n  + simpl.\n    destruct_eq.\n    eexists.\n    auto.\n  + simpl.\n    destruct_eq.\n    eexists.\n    auto.\nQed.\n\n\nLemma flds_aux_nil:\n    forall n CC cn fds, \n      flds_aux CC cn n fds = Some [] ->\n      fds = [].\nProof.\n  induction n.\n  * intros.\n    simpl in H.\n    destruct (find_class CC cn).\n    ** destruct j.\n       destruct ex.\n       *** discriminate H.\n       *** injection H;intros Hnil.\n           apply app_eq_nil in Hnil.\n           intuition.\n    ** discriminate H.\n  * intros.\n    simpl in H.\n    destruct (find_class CC cn).\n    ** destruct j.\n       destruct ex.\n       + assert (fds ++ (flds_of_cd (JFCDecl cn0 (Some j) fields methods))\n                 = []) as Hnil by (eapply IHn; eassumption).\n         apply app_eq_nil in Hnil.\n         intuition.\n       + injection H;intros Hnil.\n         eapply app_eq_nil in Hnil.\n         intuition.\n    ** discriminate H.\nQed.\n\nLemma flds_monotone_n_Sn:\n  forall CC n cn fd fds,\n         flds_aux CC cn n fd = Some fds ->\n         flds_aux CC cn (S n) fd = Some fds.\nProof.\n  induction n.\n  + intros.\n    simpl in H.\n    simpl.\n    destruct (find_class CC cn); try discriminate H.\n    destruct j.\n    destruct ex; try discriminate H.\n    auto.\n  + intros.\n    unfold flds_aux.\n    fold flds_aux.\n    simpl in H.\n    destruct (find_class CC cn); try discriminate H.\n    destruct j.\n    destruct ex; try discriminate H.\n    assert (flds_aux CC j (S n) (fd ++ flds_of_cd (JFCDecl cn0 (Some j) fields methods)) = Some fds).\n    auto.\n    Opaque flds_of_cd.\n    simpl in H0.\n    auto.\n    auto.\nQed.  \n\nLemma flds_monotone_n:\n  forall CC n m cn fd fds,\n    flds_aux CC cn n fd = Some fds ->\n    m > n ->\n    flds_aux CC cn m fd = Some fds.\nProof.\n  induction m.\n  + intros.\n    assert (n >=0) by auto with zarith.\n    assert (0 > 0) by auto with zarith.\n    assert (0<>0) by auto with zarith.\n    contradiction.\n  + intros.\n    apply flds_monotone_n_Sn.\n    assert (m > n \\/ n=m) by auto using gt_S.\n    destruct H1.\n    ++ apply IHm; auto.\n    ++ rewrite <- H1.\n       auto.\nQed.\n\n\n\nLemma flds_aux_decompose_acc:\n  forall n fds fd CC cn, \n    flds_aux CC cn n fd = Some fds ->\n    exists fds',\n      fds = fd ++ fds'.\nProof.\n  induction n.\n  * intros.\n    simpl in H.\n    destruct (find_class CC cn).\n    ** destruct j.\n       destruct ex.\n       *** discriminate H.\n       *** injection H;intros.\n           rewrite <- H0.\n           eexists;auto.\n    ** discriminate H.\n  * intros.\n    simpl in H.\n    destruct (find_class CC cn).\n    ** destruct j.\n       destruct ex.\n       *** assert ( exists fds', fds =\n                            (fd ++ flds_of_cd (JFCDecl cn0 (Some j) fields methods)) ++ fds').\n           {\n             eapply IHn.\n             apply H. }\n           destruct H0.\n           rewrite H0.\n           eexists.\n           auto using app_assoc.\n       *** injection H;intros.\n           rewrite <- H0.\n           eexists. auto.\n    ** discriminate H.\nQed.\n\nLemma flds_aux_decompose_second_same:\n  forall n fd1 fd2 fd1' fd' CC cn, \n    flds_aux CC cn n (fd1 ++ fd1') = Some (fd1 ++ fd1' ++ fd') ->\n    flds_aux CC cn n (fd2 ++ fd1') = Some (fd2 ++ fd1' ++ fd').\nProof.\n  induction n.\n  * simpl.\n    intros.\n    destruct (find_class CC cn); try discriminate H.\n    destruct j.\n    destruct ex;try discriminate H.\n    injection H;intros.\n    rewrite app_assoc in H0.\n    apply app_inv_head in H0.\n    rewrite H0.\n    rewrite app_assoc.\n    auto.\n  * simpl.\n    intros.\n    destruct (find_class CC cn); try discriminate H.\n    destruct j.\n    destruct ex;try discriminate H.\n    **  rewrite <- 1 app_assoc in H.\n        assert (exists ff, fd1 ++ fd1' ++ fd' = (fd1 ++ fd1' ++ (flds_of_cd (JFCDecl cn0 (Some j) fields methods))) ++ ff)\n          by eauto 2 using flds_aux_decompose_acc.\n        destruct H0.\n        rewrite <- 2 app_assoc in H0.\n        apply app_inv_head in H0.\n        apply app_inv_head in H0.\n        rewrite <- app_assoc.\n        assert (flds_aux CC j n (fd2 ++ fd1' ++ flds_of_cd (JFCDecl cn0 (Some j) fields methods)) =\n               Some (fd2 ++ (fd1'  ++ flds_of_cd (JFCDecl cn0 (Some j) fields methods)) ++ x)). {\n         eapply IHn.\n         rewrite H.\n         rewrite H0.\n         repeat rewrite app_assoc.\n         auto 1.\n        }\n        rewrite H1.\n        rewrite H0.\n        repeat rewrite app_assoc.\n        auto 1.\n    ** injection H. intros.\n       rewrite <- app_assoc in H0.\n       apply app_inv_head in H0.\n       apply app_inv_head in H0.\n       rewrite H0.\n       rewrite app_assoc.\n       congruence.\nQed.\n\nLemma flds_aux_decompose_first_same:\n  forall (n : nat) (fd1 fd1' fd2' fd' : list JFFieldDeclaration) (CC : JFProgram) (cn : JFClassName),\n    flds_aux CC cn n (fd1 ++ fd1') = Some (fd1 ++ fd1' ++ fd') ->\n    flds_aux CC cn n (fd1 ++ fd2') = Some (fd1 ++ fd2' ++ fd').\nProof.\n  intros.\n  rewrite app_assoc in H.\n  replace (fd1 ++ fd1') with ((fd1 ++ fd1') ++ []) in H by\n      (rewrite <- app_assoc;rewrite app_nil_r;auto).\n  replace (((fd1 ++ fd1') ++ []) ++ fd') with ((fd1 ++ fd1') ++ [] ++ fd') in H\n    by (rewrite app_assoc;rewrite app_nil_r;auto).\n  eapply flds_aux_decompose_second_same in H.\n  rewrite app_nil_r in H.\n  rewrite H.\n  repeat rewrite app_assoc.\n  rewrite app_nil_r.\n  auto 1.\nQed.\n    \nLemma flds_aux_flds_aux:\n  forall n CC cn fds x7 x7',\n    flds_aux CC cn n x7 = Some fds ->\n    (exists fds',\n        flds_aux CC cn n x7' = Some fds').\nProof.\n  induction n.\n  * intros.\n    simpl.\n    simpl in H.\n    destruct (find_class CC cn).\n    ** destruct j.\n       destruct ex.\n       *** discriminate H.\n       *** eexists. auto 1.\n    ** discriminate H.\n  * intros.\n    simpl.\n    simpl in H.\n    destruct (find_class CC cn).\n    ** destruct j.\n       destruct ex.\n       *** eapply IHn.\n           apply H.\n       *** eexists. auto 1.\n    ** discriminate H.\nQed.\n    \n(** How many extends steps there are to reach Object. *)\nFixpoint get_class_height (CC:JFProgram) (cn:JFClassName) : nat :=\n  match CC with\n  | [] => 0\n  | (JFCDecl name (Some name') _ _) :: CC' =>\n    if (JFClassName_dec name cn)\n    then S (get_class_height CC' name')\n    else get_class_height CC' cn\n  | (JFCDecl name None _ _) :: CC' =>\n    if (JFClassName_dec name cn)\n    then 1\n    else get_class_height CC' cn\n  end.\n\nLemma get_class_height_non_zero:\n  forall CC cn ex fields methods,\n  In (JFCDecl cn ex fields methods) CC ->\n         get_class_height CC cn <> 0.\nProof.\n  induction CC.\n  + intros.\n    auto 2 using in_nil.\n  + intros.\n    simpl.\n    destruct a.\n    destruct ex0.\n    ++ destruct (JFClassName_dec cn0 cn).\n       +++ auto 1.\n       +++ apply in_inv in H.\n           destruct H.\n           ++++ injection H;intros;contradiction.\n           ++++ eauto 2.\n    ++ destruct (JFClassName_dec cn0 cn).\n       +++ auto 1.\n       +++ apply in_inv in H.\n           destruct H.\n           ++++ injection H;intros;contradiction.\n           ++++ eauto 2.\nQed.\n\n\nLemma find_class_get_class_height:\n  forall CC cn cd,\n    find_class CC cn = Some cd ->\n    get_class_height CC cn <> 0.\nProof.\n  induction CC.\n  + intros.\n    discriminate H.\n  + intros.\n    destruct a.\n    simpl.\n    simpl in H.\n    intro.\n    destruct (JFClassName_dec cn0 cn).\n    +++ destruct ex;discriminate H0.\n    +++ destruct ex;eapply IHCC;eauto.\nQed.\n\n\n(** Calculates the list of field declarations in an object of the given\n    class identifier [C]. In case [C] is the bottom class\n    the function returns [None]. Otherwise it traverses the\n    object hierarchy and collects filelds.\n\n    Defined in Figure {fig:auxiliary-notation} as the function flds with overline bar. *)\nDefinition flds_overline (CC:JFProgram) (C:JFCId)\n: option (list JFFieldDeclaration) :=\n  match C with\n    | JFClass cn =>\n      flds_aux CC cn (get_class_height CC cn) []\n    | JFBotClass => None\n  end.\n\nLemma flds_overline_find_class :\n  forall CC C flds,\n    flds_overline CC (JFClass C) = Some flds ->\n    exists cdecl, find_class CC C = Some cdecl.\nProof.\n  intros ? ? ? Htmp.\n  simpl in Htmp.\n  destruct get_class_height in Htmp.\n  + simpl in Htmp.\n    destruct find_class; eauto 2.\n    discriminate Htmp.\n  + simpl in Htmp.\n    destruct find_class; eauto 2.\n    discriminate Htmp.\nQed.\n\nHint Resolve flds_overline_find_class.\n\n\n(** Calculates the list of field identifiers in an object of the given\n    class identifier [C]. In case [C] is the bottom class\n    the function returns [None]. Otherwise it traverses the\n    object hierarchy and collects filelds.\n\n    Defined in Figure {fig:syntax} as the function flds. *)\nDefinition flds (CC:JFProgram) (C:JFCId) :=\n  match flds_overline CC C with\n  | Some fields => Some (map name_of_fd fields)\n  | None => None\n  end.\n\n\n(** Calculates the type of the parameter [n] in the method [md] in\n    the class [C]. In case [C] is the bottom class the function\n    returns [None]. Otherwise it looks up the method [md] in the class\n    declaration of [C] in [CC]. If it succeeds it returns the type\n    of the paramter. Otherwise it returns None. We use here the\n    operation (.)^rwr in case method has no annotations. The value\n    n=0 is for the type of this.\n\n    Defined in Figure {fig:auxiliary-notation} as the function parTypM.\n  *)\nDefinition parTypM_of_md (C:JFCId) (md: JFMethodDeclaration) (n:nat) : JFACId :=\n  match md with\n  | JFMDecl D mu mn vs excs E =>\n    match n with\n    | 0 => (C, mu)\n    | _ => nth (n-1) (map snd vs) (JFObject, JFrwr)\n    end\n  | JFMDecl0 D mn vs excs E =>\n    match n with\n    | 0 => (C, JFrwr)\n    | _ => (nth (n-1) (map snd vs) JFObject, JFrwr)\n    end\n  end.\n\n\nDefinition parTypM (CC:JFProgram) (C:JFCId) (m:JFMId) (n:nat)\n  : option JFACId :=\n  match C with\n    | JFClass cn =>\n      let mdo := methodLookup CC cn m in\n      match mdo with\n      | Some md => Some (parTypM_of_md C md n)\n      | None => None\n      end\n    | JFBotClass => None\n  end.\n\n\nDefinition retTypM (CC:JFProgram) (C:JFCId) (m:JFMId)\n  : option JFACId :=\n  match C with\n    | JFClass cn =>\n      let mdo := methodLookup CC cn m in\n      match mdo with\n        | Some md => Some (rettyp_of_md md)\n        | None => None\n      end\n    | JFBotClass => None\n  end.\n\n\nDefinition thrs (CC:JFProgram) (C:JFCId) (m:JFMId)\n  : option (list JFACId) :=\n  match C with\n    | JFClass cn =>\n      let mdo := methodLookup CC cn m in\n      match mdo with\n        | Some md => Some (thrs_of_md md)\n        | None => None\n      end\n    | JFBotClass => None\n  end.\n\n\nLemma thrs_thrs_of_md:\n  forall CC cn md,\n    methodLookup CC cn (name_of_md md) = Some md ->\n    thrs CC (JFClass cn) (name_of_md md) =\n    Some (thrs_of_md md).\nProof.\n  intros.\n  simpl.\n  rewrite H.\n  auto.\nQed.\n\nDefinition body (CC:JFProgram) (C:JFCId) (m:JFMId)\n  : option JFExpr :=\n  match C with\n    | JFClass cname =>\n      let mdo := methodLookup CC cname m in\n      match mdo with\n        | Some md =>\n          Some (body_of_md md)\n        | None => None\n      end\n    | JFBotClass => None\n  end.\n", "meta": {"author": "jbujak", "repo": "jafun", "sha": "4b9b2d21ba06e6a98c885c8bf2cc202f52595058", "save_path": "github-repos/coq/jbujak-jafun", "path": "github-repos/coq/jbujak-jafun/jafun-4b9b2d21ba06e6a98c885c8bf2cc202f52595058/JaProgram.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.26777906459146267}}
{"text": "(** Camera definitions and proofs for the keyset RA. *)\n\nFrom iris.algebra Require Import gset.\nFrom iris.proofmode Require Import tactics.\nFrom iris.base_logic.lib Require Export iprop.\nFrom iris.base_logic.lib Require Export invariants.\n\nSet Default Proof Using \"All\".\nRequire Export search_str flows auth_ext.\n\nSection keyset_ra.\n\n(* The set of keys. *)\nContext `{Countable K}.\n\n(* The keyspace is some arbitrary finite subset of K. *)\nParameter KS : gset K.\n\nInductive prodT :=\n  prod : gset K*gset K → prodT\n| prodTop : prodT\n| prodBot : prodT.\n\nCanonical Structure prodRAC := leibnizO prodT.\n\nGlobal Instance prodOp : Op prodT :=\n  λ p1 p2,\n  match p1, p2 with\n  | prod (K1, C1), prod (K2, C2) =>\n    if (decide(C1 ⊆ K1)) then\n      (if (decide(C2 ⊆ K2)) then\n         (if (decide (K1 ## K2)) then\n            (if (decide (C1 ## C2)) then (prod (K1 ∪ K2, C1 ∪ C2))\n             else prodTop)\n          else prodTop)\n       else prodTop)\n    else prodTop\n  | prodTop, _ => prodTop\n  | _, prodTop => prodTop\n  | p1, prodBot => p1\n  | prodBot, p2 => p2 end.\n  \nGlobal Instance prodValid : Valid prodT :=\nλ p, match p with\n       | prod (K, C) => C ⊆ K\n       | prodTop => False\n       | prodBot => True end.\n\nGlobal Instance prodCore : PCore prodT :=\n  λ p, Some prodBot.\n\nGlobal Instance prodUnit : Unit prodT := prodBot.\n\nDefinition prodRA_mixin : RAMixin prodT.\nProof.\n  split; try apply _; try done.\n  - (* Core is unique? *)\n    intros ? ? cx -> ?. exists cx. done.\n  - unfold op, prodOp. intros [] [] []; try (simpl; done).\n    case_eq p. intros g g0 Hp. case_eq p0. intros g1 g2 Hp0. case_eq p1. intros g3 g4 Hp1.\n    destruct (decide (g2 ⊆ g1)). destruct (decide (g4 ⊆ g3)). destruct (decide (g1 ## g3)).\n    destruct (decide (g2 ## g4)). destruct (decide (g0 ⊆ g)). destruct (decide (g2 ∪ g4 ⊆ g1 ∪ g3)).\n    destruct (decide (g ## g1 ∪ g3)). destruct (decide (g0 ## g2 ∪ g4)).\n    destruct (decide (g ## g1)). destruct (decide (g0 ## g2)). destruct (decide (g0 ∪ g2 ⊆ g ∪ g1)).\n    destruct (decide (g ∪ g1 ## g3)). destruct (decide (g0 ∪ g2 ## g4)). apply leibniz_equiv_iff.\n    assert (g ∪ (g1 ∪ g3) = g ∪ g1 ∪ g3). { set_solver. }\n    assert (g0 ∪ (g2 ∪ g4) = g0 ∪ g2 ∪ g4). { set_solver. }\n    rewrite H0. rewrite H1. reflexivity.\n    unfold not in n. exfalso. apply n. set_solver.\n    unfold not in n. exfalso. apply n. set_solver.\n    unfold not in n. exfalso. apply n. set_solver.\n    unfold not in n. exfalso. apply n. set_solver.\n    unfold not in n. exfalso. apply n. set_solver.\n    destruct (decide (g ## g1)). destruct (decide (g0 ## g2)). destruct (decide (g ∪ g1 ## g3)).\n    destruct (decide (g0 ∪ g2 ## g4)).\n    unfold not in n. exfalso. apply n. set_solver.\n    unfold not in n. exfalso. apply n. set_solver.\n    destruct (decide (g0 ∪ g2 ⊆ g ∪ g1)); try done. done. done.\n    destruct (decide (g ## g1)). destruct (decide (g0 ## g2)). destruct (decide (g0 ∪ g2 ⊆ g ∪ g1)).\n    destruct (decide (g ∪ g1 ## g3)). destruct (decide (g0 ∪ g2 ## g4)).\n    unfold not in n. exfalso. apply n. set_solver. done. done. done. done. done.\n    unfold not in n. exfalso. apply n. set_solver. done.\n    unfold not in n. exfalso. apply n. set_solver.\n    destruct (decide (g0 ⊆ g)). destruct (decide (g ## g1)); try done.\n    destruct (decide (g0 ## g2)). destruct (decide (g0 ∪ g2 ⊆ g ∪ g1)).\n    destruct (decide (g ∪ g1 ## g3)). unfold not in n. exfalso. apply n. set_solver.\n    done. done. done. done. destruct (decide (g0 ⊆ g)).\n    destruct (decide (g ## g1)). destruct (decide (g0 ## g2)).\n    destruct (decide (g0 ∪ g2 ⊆ g ∪ g1)). done. done. done. done. done.\n    destruct (decide (g0 ⊆ g)). done. done.\n    case_eq p. intros g g0 Hp. case_eq p0. intros g1 g2 Hp0. destruct (decide (g0 ⊆ g)).\n    destruct (decide (g2 ⊆ g1)). destruct (decide (g ## g1)).\n    destruct (decide (g0 ## g2)). done. done. done. done. done.\n    case_eq p. intros g g0 Hp. case_eq p0. intros g1 g2 Hp0. destruct (decide (g0 ⊆ g)).\n    destruct (decide (g2 ⊆ g1)). destruct (decide (g ## g1)).\n    destruct (decide (g0 ## g2)). done. done. done. done. done.\n    case_eq p; try done. case_eq p; try done. case_eq p; try done. case_eq p; try done.\n    case_eq p; try done. case_eq p; try done. case_eq p. intros g g0 Hp. case_eq p0. intros g1 g2 Hp0.\n    destruct (decide (g0 ⊆ g)). destruct (decide (g2 ⊆ g1)). destruct (decide (g ## g1)).\n    destruct (decide (g0 ## g2)). done. done. done. done. done.\n    case_eq p; try done. case_eq p; try done.\n  - unfold op, prodOp. intros [] []. case_eq p. intros g g0 Hp. case_eq p0. intros g1 g2 Hp0.\n    destruct (decide (g0 ⊆ g)); try done. destruct (decide (g2 ⊆ g1)); try done.\n    destruct (decide (g ## g1)). destruct (decide (g0 ## g2)). destruct (decide (g1 ## g)).\n    destruct (decide (g2 ## g0)). assert (g1 ∪ g = g ∪ g1 ∧ g2 ∪ g0 = g0 ∪ g2) as [H1 H2]. { set_solver. }\n    rewrite H1; rewrite H2. done. unfold not in n. exfalso. apply n. done.\n    unfold not in n. exfalso. apply n. done. destruct (decide (g1 ## g)). destruct (decide (g2 ## g0)).\n    unfold not in n. exfalso. apply n. done. done. done. destruct (decide (g1 ## g)).\n    unfold not in n. exfalso. apply n. done. done. destruct (decide (g2 ⊆ g1)); try done.\n    case_eq p; try done. case_eq p; try done. case_eq p; try done. done. done.\n    case_eq p; try done. done. done.\n  - unfold pcore, prodCore. intros x cx. intros Hx. inversion Hx.\n    unfold op, prodOp. destruct x; try done.\n  - unfold pcore, prodCore. intros x cx Hx. inversion Hx. done.\n  - intros x y cx Hxy HS. inversion HS. exists prodBot. split; try done. exists prodBot; done.\n  - unfold valid, prodValid. intros x y. destruct x. destruct p.\n    destruct y. destruct p. unfold op, prodOp. destruct (decide (g0 ⊆ g)).\n    destruct (decide (g2 ⊆ g1)). destruct (decide (g ## g1)). destruct (decide (g0 ## g2)).\n    intros. done. intros; done. intros; done. intros; done. intros; done.\n    unfold op, prodOp. intros; done. unfold op, prodOp. done. unfold op, prodOp. done.\n    destruct y. destruct p. unfold op, prodOp. done. unfold op, prodOp. done. unfold op, prodOp. done.\nQed.\n\nCanonical Structure KsetRA := discreteR prodT prodRA_mixin.\n\nGlobal Instance prodRA_cmra_discrete : CmraDiscrete KsetRA.\nProof. apply discrete_cmra_discrete. Qed.\n\nLemma prod_ucmra_mixin : UcmraMixin prodT.\nProof.\n  split; try apply _; try done. unfold LeftId. intros x. unfold ε, prodUnit.\n  unfold op, prodOp. destruct x; try done.\nQed.\n\nCanonical Structure keysetUR : ucmra := Ucmra prodT prod_ucmra_mixin.\n\nLemma auth_ks_included (a1 a2 b1 b2: gset K) :\n  ✓ prod (a1, b1) → ✓ prod (a2, b2) → prod (a1, b1) ≼ prod (a2, b2)\n  → (a1 = a2 ∧ b1 = b2) ∨\n    (∃ a0 b0, a2 = a1 ∪ a0 ∧ b2 = b1 ∪ b0 ∧ a1 ## a0 ∧ b1 ## b0 ∧ b1 ⊆ a1 ∧ b2 ⊆ a2 ∧ b0 ⊆ a0).\nProof.\n  intros H1 H2 H0. destruct H0 as [z H0]. assert (✓ z). { apply (cmra_valid_op_r (prod (a1, b1))).\n  rewrite <- H0. done. } rewrite /(✓ prod (a1, b1)) /= in H1. rewrite /(✓ prod (a2, b2)) /= in H2.\n  destruct z.\n  - destruct p. rewrite /(✓ prod (g, g0)) /= in H3. rewrite /(⋅) /= in H0.\n    destruct (decide (b1 ⊆ a1)). destruct (decide (g0 ⊆ g)). destruct (decide (a1 ## g)).\n    destruct (decide (b1 ## g0)). right. exists g, g0. set_solver. inversion H0. inversion H0.\n    inversion H0. inversion H0.\n  - rewrite /(✓ prodTop) /= in H0. exfalso. done.\n  - rewrite /(⋅) /= in H0. inversion H0. left. done.\nQed.\n\nLemma auth_ks_local_update_insert K1 C Cn k:\n  ✓ prod (KS, C) ∧ ✓ prod (K1, Cn) ∧ k ∈ K1 ∧ k ∉ Cn ∧ k ∈ KS →\n  (prod (KS, C), prod (K1, Cn)) ~l~> (prod (KS, C ∪ {[k]}), prod (K1, Cn ∪ {[k]})).\nProof.\n  intros [H1 [H2 [H3 [H4 HKS]]]]. apply local_update_discrete. intros z.\n  intros _. intros. split. rewrite /(✓ prod (KS, C ∪ {[k]})) /=.\n  rewrite /(cmra_valid KsetRA) /=. rewrite /(✓ prod (KS, C)) /= in H1.\n  set_solver. rewrite /(opM) /= in H0.\n  destruct z. rewrite /(opM) /=. destruct c. destruct p. rewrite /(op) /= in H0.\n  rewrite /(cmra_op KsetRA) /= in H0. destruct (decide (Cn ⊆ K1)).\n  destruct (decide (g0 ⊆ g)). destruct (decide (K1 ## g)). destruct (decide (Cn ## g0)).\n  inversion H0. rewrite /(op) /=. rewrite /(cmra_op KsetRA) /=. destruct (decide (Cn ∪ {[k]} ⊆ K1)).\n  destruct (decide (g0 ⊆ g)). destruct (decide (K1 ## g)). destruct (decide (Cn ∪ {[k]} ## g0)).\n  assert (Cn ∪ g0 ∪ {[k]} = Cn ∪ {[k]} ∪ g0). { set_solver. } rewrite H6. rewrite H5. done.\n  unfold not in n. exfalso. apply n. set_solver. unfold not in n. exfalso. apply n. set_solver.\n  unfold not in n. exfalso. apply n. set_solver. unfold not in n. exfalso. apply n. set_solver.\n  unfold not in n. exfalso. apply n. set_solver. unfold not in n. exfalso. apply n. set_solver.\n  unfold not in n. exfalso. apply n. set_solver. unfold not in n. exfalso. apply n. set_solver.\n  rewrite /(op) /= in H0. rewrite /(cmra_op KsetRA) /= in H0. inversion H0.\n  rewrite /(op) /= in H0. rewrite /(cmra_op KsetRA) /= in H0. inversion H0.\n  rewrite /(op) /=. rewrite /(cmra_op KsetRA) /=. done.\n  rewrite /(opM) /=. inversion H0. done.\nQed.\n\nLemma auth_ks_local_update_delete K1 C Cn k:\n            ✓ prod (KS, C) ∧ ✓ prod (K1, Cn) ∧ k ∈ K1 ∧ k ∈ Cn →\n           (prod (KS, C), prod (K1, Cn)) ~l~> (prod (KS, C ∖ {[k]}), prod (K1, Cn ∖ {[k]})).\nProof.\n  intros [H1 [H2 [H3 H4]]]. apply local_update_discrete. intros z.\n  intros _. intros. split. rewrite /(✓ prod (KS, C ∖ {[k]})) /=.\n  rewrite /(cmra_valid KsetRA) /=. rewrite /(✓ prod (KS, C)) /= in H1.\n  set_solver. rewrite /(opM) /= in H0.\n  destruct z. rewrite /(opM) /=. destruct c. destruct p. rewrite /(op) /= in H0.\n  rewrite /(cmra_op KsetRA) /= in H0. destruct (decide (Cn ⊆ K1)).\n  destruct (decide (g0 ⊆ g)). destruct (decide (K1 ## g)). destruct (decide (Cn ## g0)).\n  inversion H. rewrite /(op) /=. rewrite /(cmra_op KsetRA) /=. destruct (decide (Cn ∖ {[k]} ⊆ K1)).\n  destruct (decide (g0 ⊆ g)). destruct (decide (K1 ## g)). destruct (decide (Cn ∖ {[k]} ## g0)).\n  assert (k ∉ g0). { set_solver. }\n  assert ((Cn ∪ g0) ∖ {[k]} = Cn ∖ {[k]} ∪ g0). { set_solver. } rewrite <- H6. inversion H0. done.\n  unfold not in n. exfalso. apply n. set_solver. unfold not in n. exfalso. apply n. set_solver.\n  unfold not in n. exfalso. apply n. set_solver. unfold not in n. exfalso. apply n. set_solver.\n  unfold not in n. exfalso. apply n. set_solver. unfold not in n. exfalso. apply n. set_solver.\n  unfold not in n. exfalso. apply n. set_solver. unfold not in n. exfalso. apply n. set_solver.\n  rewrite /(op) /= in H0. rewrite /(cmra_op KsetRA) /= in H0. inversion H0.\n  rewrite /(op) /= in H0. rewrite /(cmra_op KsetRA) /= in H0. inversion H0.\n  rewrite /(op) /=. rewrite /(cmra_op KsetRA) /=. done.\n  rewrite /(opM) /=. inversion H0. done.\nQed.\n\nEnd keyset_ra.\n\nArguments keysetUR _ {_ _}.\n\nSection keyset_updates.\n  Context `{Countable K}.\n\n  (** RA for pairs of keysets and contents *)\n\n  Class keysetG Σ := KeysetG { keyset_inG :> inG Σ (authUR (keysetUR K)) }.\n  Definition keysetΣ : gFunctors := #[GFunctor (authUR (keysetUR K))].\n\n  Global Instance subG_keysetΣ {Σ} : subG keysetΣ Σ → keysetG Σ.\n  Proof. solve_inG. Qed.\n\n  Context `{!keysetG Σ}.\n\n  (** Some useful lemmas  *)\n\n  Lemma keyset_valid γ_k Ks C:\n    own γ_k (◯ prod (Ks, C)) -∗ ⌜C ⊆ Ks⌝.\n  Proof.\n    iIntros \"Hks\".\n    iPoseProof (own_valid with \"Hks\") as \"HvldCn\".\n    iDestruct \"HvldCn\" as %HvldCn.\n    rewrite auth_frag_valid in HvldCn *; intros HvldCn.\n    unfold valid, cmra_valid in HvldCn.\n    simpl in HvldCn. unfold ucmra_valid in HvldCn. simpl in HvldCn.\n      by iPureIntro.\n  Qed.\n\n  (** Ghost update of abstract search structure state *)\n      \n  Lemma ghost_update_keyset γ_k dop (k: K) Cn Cn' res K1 C:\n    ⊢ ⌜Ψ dop k Cn Cn' res⌝ ∗ own γ_k (● prod (KS, C)) ∗ own γ_k (◯ prod (K1, Cn))\n    ∗ ⌜Cn' ⊆ K1⌝ ∗ ⌜k ∈ K1⌝ ∗ ⌜k ∈ KS⌝\n    ==∗ ∃ C', ⌜Ψ dop k C C' res⌝ ∗ own γ_k (● prod (KS, C'))\n      ∗ own γ_k (◯ prod (K1, Cn')).\n  Proof.\n    iIntros \"(#HΨ & Ha & Hf & % & % & HKS)\". iPoseProof (auth_own_incl γ_k (prod (KS, C)) (prod (K1, Cn))\n                with \"[$Ha $Hf]\") as \"%\". iDestruct \"HKS\" as %HKS.\n    iPoseProof ((own_valid γ_k (● prod (KS, C))) with \"Ha\") as \"%\".\n    iPoseProof ((own_valid γ_k (◯ prod (K1, Cn))) with \"Hf\") as \"%\".\n    assert ((K1 = KS ∧ Cn = C) ∨\n            (∃ a0 b0, KS = K1 ∪ a0 ∧ C = Cn ∪ b0 ∧ K1 ## a0 ∧ Cn ## b0 ∧ Cn ⊆ K1 ∧ C ⊆ KS ∧ b0 ⊆ a0)) as Hs.\n    { apply (auth_ks_included K1 KS Cn C); try done. rewrite <- auth_frag_valid. done. apply auth_auth_valid. done. }\n    destruct Hs.\n    - iEval (unfold Ψ) in \"HΨ\". destruct H5. destruct dop.\n      + iDestruct \"HΨ\" as \"%\". destruct H7.\n        iModIntro. iExists C. iEval (rewrite <-H7) in \"Hf\". iFrame. unfold Ψ.\n        iPureIntro. split; try done. rewrite <-H6. done.\n      + iDestruct \"HΨ\" as \"%\". destruct H7. destruct res.\n        * iMod (own_update_2 γ_k (● prod (KS, C)) (◯ prod (K1, Cn))\n          (● prod (KS, C ∪ {[k]}) ⋅ ◯ prod (K1, Cn ∪ {[k]})) with \"[Ha] [Hf]\") as \"(Ha & Hf)\"; try done.\n          { apply auth_update. apply auth_ks_local_update_insert.\n            repeat split; try done. apply auth_auth_valid.  done. apply auth_frag_valid. done.  }\n          iModIntro. iExists (C ∪ {[k]}). iEval (rewrite H7). iFrame.\n          unfold Ψ. iPureIntro. split; try done. rewrite <-H6. done.\n        * assert (Cn' = Cn). { set_solver. } iModIntro. iExists C. iEval (rewrite <-H9) in \"Hf\".\n          iFrame. unfold Ψ. iPureIntro. rewrite <- H6. split; try done. rewrite H9 in H7. done.\n      + iDestruct \"HΨ\" as \"%\". destruct H7. destruct res.\n        * iMod (own_update_2 γ_k (● prod (KS, C)) (◯ prod (K1, Cn))\n          (● prod (KS, C ∖ {[k]}) ⋅ ◯ prod (K1, Cn ∖ {[k]})) with \"[Ha] [Hf]\") as \"(Ha & Hf)\"; try done.\n          { apply auth_update. apply auth_ks_local_update_delete. repeat split; try done. apply auth_auth_valid. done. apply auth_frag_valid. done. }\n          iModIntro. iExists (C ∖ {[k]}). iEval (rewrite H7). iFrame.\n          unfold Ψ. iPureIntro. split; try done. rewrite <-H6. done.\n        * assert (Cn' = Cn). { set_solver. } iModIntro. iExists C. iEval (rewrite <-H9) in \"Hf\".\n          iFrame. unfold Ψ. iPureIntro. rewrite <- H6. split; try done. rewrite H9 in H7. done.\n    - destruct H5 as [Ko [Co [H5 [H6 [H7 [H8 [H9 [H10 H11]]]]]]]]. destruct dop.\n      + iDestruct \"HΨ\" as \"%\". destruct H12.\n        iModIntro. iExists C. iEval (rewrite <-H12) in \"Hf\". iFrame. unfold Ψ.\n        iPureIntro. split; try done. destruct res; set_solver.\n      + iDestruct \"HΨ\" as \"%\". destruct H12. destruct res.\n        * iMod (own_update_2 γ_k (● prod (KS, C)) (◯ prod (K1, Cn))\n          (● prod (KS, C ∪ {[k]}) ⋅ ◯ prod (K1, Cn ∪ {[k]})) with \"[Ha] [Hf]\") as \"(Ha & Hf)\"; try done.\n          { apply auth_update. apply auth_ks_local_update_insert. split; try done. }\n          iModIntro. iExists (C ∪ {[k]}). iEval (rewrite H12). iFrame.\n          unfold Ψ. iPureIntro. split; try done. set_solver.\n        * assert (Cn' = Cn). { set_solver. } iModIntro. iExists C. iEval (rewrite <-H14) in \"Hf\".\n          iFrame. unfold Ψ. iPureIntro. set_solver.\n      + iDestruct \"HΨ\" as \"%\". destruct H12. destruct res.\n        * iMod (own_update_2 γ_k (● prod (KS, C)) (◯ prod (K1, Cn))\n          (● prod (KS, C ∖ {[k]}) ⋅ ◯ prod (K1, Cn ∖ {[k]})) with \"[Ha] [Hf]\") as \"(Ha & Hf)\"; try done.\n          { apply auth_update. apply auth_ks_local_update_delete. repeat split; try done. }\n          iModIntro. iExists (C ∖ {[k]}). iEval (rewrite H12). iFrame.\n          unfold Ψ. iPureIntro. split; try done. set_solver.\n        * assert (Cn' = Cn). { set_solver. } iModIntro. iExists C. iEval (rewrite <-H14) in \"Hf\".\n          iFrame. unfold Ψ. iPureIntro. set_solver.\n  Qed.\n\nEnd keyset_updates.\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/keyset_ra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548511303336, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.26777905902678084}}
{"text": "Require Import MSets.MSetFacts.\nRequire Import MSets.MSetProperties.\nRequire Import MSets.MSetDecide.\nRequire Import FSets.FMapFacts.\nRequire Export Solvers.\nRequire Import RLDi.\nRequire Import Utf8.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nModule SolverRLD (Sys : CSysJoinSemiLat)\n                 (VSet : SetsTypeOn (Sys.V))\n                 (VMap : MapsTypeOn (Sys.V)).\n\nModule Var := Sys.V.\nModule D <: JoinSemiLattice := Sys.D.\n\nModule UtilD := UtilJoin (D).\n\nModule Import VSetFacts := WFactsOn (Var) (VSet).\nModule Import VSetProps := WPropertiesOn (Var) (VSet).\nModule Import VSetDecide := WDecideOn (Var) (VSet).\nModule Import VMapFacts := WFacts_fun (Var) (VMap).\n\nModule VS := VSet.\nModule Sigma := VMap.\nModule Infl := VMap.\n\nDefinition F := Sys.F.\n\nModule Import Defs := Solvers.Defs (Sys).\n\nModule SI := SolverRLDInstr (Sys) (VSet) (VMap).\n\n(*****************************************************************)\n(*********** Non-instrumented algorithm specification ************)\n(*****************************************************************)\n\nDefinition state :=\n  (Sigma.t D.t * Infl.t (list Var.t) * VS.t)%type.\n\nLtac destruct_state s :=\n  let sig := fresh \"sigma\" in\n  let inf := fresh \"infl\" in\n  let sta := fresh \"stable\" in\n    destruct s as [ [sig inf] sta].\n\nLtac destruct_pose_state s :=\n  let sig := fresh \"sigma\" in\n  let inf := fresh \"infl\" in\n  let sta := fresh \"stable\" in\n    destruct s as [ [sig inf] sta];\n    pose (s := (sig, inf, sta));\n    fold s.\n\nDefinition setval (x : Var.t) d (s : state) : state :=\n  let '(sigma, infl, stable) := s in\n    (Sigma.add x d sigma, infl, stable).\n\nDefinition getval (s : state) x :=\n  let '(sigma, _, _) := s in\n    match Sigma.find x sigma with\n      | Some d => d\n      | None => D.bot\n    end.\n\nLemma getval_eq (s1 s2 : state) :\n  let '(sigma1, _, _) := s1 in\n  let '(sigma2, _, _) := s2 in\n    VMap.Equal sigma1 sigma2 ->\n    getval s1 = getval s2.\nProof.\ndestruct_state s1. destruct_state s2. intro e.\nextensionality x; simpl. now rewrite e.\nQed.\n\nDefinition get_infl (s : state) x : list (Var.t) :=\n  let '(_, infl, _) := s in\n    match Infl.find x infl with\n      | Some l => l\n      | None => []\n    end.\n\nLemma get_infl_eq s1 s2 :\n  let '(_, infl1, _) := s1 in\n  let '(_, infl2, _) := s2 in\n    VMap.Equal infl1 infl2 ->\n    get_infl s1 = get_infl s2.\nProof.\ndestruct_state s1. destruct_state s2. intro e.\nextensionality x; simpl. now rewrite e.\nQed.\n\nDefinition add_infl y x (s : state) : state :=\n  let '(sigma, infl, stable) := s in\n    let xs := get_infl s y in\n    (sigma, Infl.add y (x :: xs) infl, stable).\n\nDefinition rem_infl x (s : state) : state :=\n  let '(sigma, infl, stable) := s in\n    (sigma, Infl.remove x infl, stable).\n\nDefinition is_stable x (s : state) :=\n  let '(_, _, stable) := s in VS.In x stable.\n\nLemma is_stable_dec x s : {is_stable x s} + {~ is_stable x s}.\ndestruct_state s. simpl. now apply VSetProps.In_dec.\nQed.\n\nDefinition get_stable (s : state) :=\n  let '(_, _, stable) := s in stable.\n\nDefinition add_stable x (s : state) : state :=\n  let '(sigma, infl, stable) := s in\n    (sigma, infl, VS.add x stable).\n\nDefinition rem_stable x (s : state) : state :=\n  let '(sigma, infl, stable) := s in\n    (sigma, infl, VS.remove x stable).\n\nDefinition prepare x s := add_stable x s.\n\nDefinition handle_work (w : list Var.t) (s : state) :=\n    let f s x := rem_stable x s in\n    List.fold_left f w s.\n\nDefinition extract_work (x : Var.t) (s : state) : (list Var.t * state)\n  := let w := get_infl s x in\n     let s := rem_infl x s in\n     let s := handle_work w s in\n       (w, s).\n\nLemma handle_work_spec s w s' :\n  s' = handle_work w s ->\n  let '(sigma, infl, stable) := s in\n  let '(sigma', infl', stable') := s' in\n    sigma' = sigma /\\\n    infl' = infl /\\\n    VS.Equal stable' (VS.diff stable (of_list w)).\nProof.\nrevert s s'.\ninduction w as [| x w IHw ].\n- intros s s' H1. destruct_state s. destruct_state s'. simpl.\n  inversion H1. now intuition; fsetdec.\n- intros s s' H.\n  remember (rem_stable x s) as s1.\n  assert (H1 : s' = handle_work w s1) by (subst; auto).\n  assert (H2 := IHw _ _ H1). clear IHw H1.\n  destruct_state s. destruct_state s1. destruct_state s'.\n  inversion Heqs1; subst; simpl.\n  now intuition; fsetdec.\nQed.\n\nLemma extract_work_spec x s w s' :\n  (w, s') = extract_work x s ->\n  let '(sigma, infl, stable) := s in\n  let '(sigma', infl', stable') := s' in\n    w = get_infl s x /\\\n    sigma' = sigma /\\\n    infl' = Infl.remove x infl /\\\n    VS.Equal stable' (VS.diff stable (of_list w)).\nProof.\nintro H. injection H as H1 Ew; clear H.\nassert (H := handle_work_spec H1).\nsubst w. destruct_state s. destruct_state s'.\nnow simpl in *; intuition.\nQed.\n\nDefinition s_init : state\n  := (Sigma.empty D.t,\n      Infl.empty (list Var.t),\n      VS.empty).\n\nSection algorithm.\n\nVariable Hpure : forall x, is_pure (F x).\nDefinition rhs x : Tree Var.t D.t D.t := proj1_sig (Hpure x).\n\nLemma rhs_spec x : F x = [[rhs x]].\nProof. now rewrite (proj2_sig (Hpure x)). Qed.\n\nInductive EvalGet :\n  Var.t -> Var.t -> state -> D.t * state -> Prop :=\n  | EvalGet0 :\n      forall x y s s0,\n        Solve y s s0 ->\n        let s1 := add_infl y x s0 in\n        let d := getval s0 y in\n        EvalGet x y s (d, s1)\n\nwith EvalGet_x :\n  Var.t -> (Var.t -> state -> D.t * state -> Prop) -> Prop :=\n  | EvalGet_x0 :\n      forall x (f : Var.t -> state -> D.t * state -> Prop),\n        (forall y s0 ds1,\n           f y s0 ds1 -> EvalGet x y s0 ds1) ->\n        EvalGet_x x f\n\nwith Wrap_Eval_x :\n  Var.t -> (Var.t -> state -> D.t * state -> Prop) ->\n  @Tree Var.t D.t D.t ->\n  state -> D.t * state -> Prop :=\n  | Wrap_Eval_x0 :\n    forall x f t s0 ds1,\n      EvalGet_x x f ->\n      [[t]]# f s0 ds1 ->\n      Wrap_Eval_x x f t s0 ds1\n\nwith Eval_rhs :\n  Var.t ->\n  state -> D.t * state -> Prop :=\n  | Eval_rhs0 :\n    forall x f s0 ds1,\n      EvalGet_x x f ->\n      Wrap_Eval_x x f (rhs x) s0 ds1 ->\n      Eval_rhs x s0 ds1\n\nwith Solve :\n  Var.t -> state -> state -> Prop :=\n  | Solve0 :\n      forall x s, is_stable x s -> Solve x s s\n  | Solve1 :\n      forall x d s s2,\n      ~ is_stable x s ->\n      let s1 := prepare x s in\n      Eval_rhs x s1 (d, s2) ->\n      let cur := getval s2 x in\n      let new := D.join cur d in\n      D.Leq new cur ->\n      Solve x s s2\n  | Solve2 :\n      forall x d s s2 s5 s6 work,\n      ~ is_stable x s ->\n      let s1 := prepare x s in\n      Eval_rhs x s1 (d, s2) ->\n      let cur := getval s2 x in\n      let new := D.join cur d in\n      ~ D.Leq new cur ->\n      let s4 := setval x new s2 in\n      (work, s5) = extract_work x s4 ->\n      SolveAll work s5 s6 ->\n      Solve x s s6\n\nwith SolveAll :\n  list Var.t -> state -> state -> Prop :=\n  | SolveAll0 :\n      forall s, SolveAll [] s s\n  | SolveAll2 :\n      forall x xs s s1 s2,\n        Solve x s s1 ->\n        SolveAll xs s1 s2 ->\n        SolveAll (x :: xs) s s2.\n\n(* generate a mutual induction scheme *)\nScheme evalget_min   := Minimality for EvalGet Sort Prop\n  with evalgetx_min  := Minimality for EvalGet_x Sort Prop\n  with wrapevalx_min := Minimality for Wrap_Eval_x Sort Prop\n  with evalrhs_min   := Minimality for Eval_rhs Sort Prop\n  with solve_min     := Minimality for Solve Sort Prop\n  with solveall_min  := Minimality for SolveAll Sort Prop.\n\nCombined Scheme solve_mut_min from\n  evalget_min,\n  evalgetx_min,\n  wrapevalx_min,\n  evalrhs_min,\n  solve_min,\n  solveall_min.\n\nDefinition EvalGet_fun x y s ds1\n  := forall ds1', EvalGet x y s ds1' -> ds1 = ds1'.\n\nDefinition EvalGet_x_fun x (f : Var.t -> state -> D.t * state -> Prop)\n  := forall f',\n       EvalGet_x x f' ->\n       forall y s ds0 ds0',\n         f y s ds0 -> f' y s ds0' -> ds0 = ds0'.\n\nDefinition Wrap_Eval_x_fun x (f : Var.t -> state -> D.t * state -> Prop) t s ds1\n  := forall f' ds1',\n       Wrap_Eval_x x f' t s ds1' ->\n       (forall y s ds0 ds0',\n          f y s ds0 -> f' y s ds0' -> ds0 = ds0') ->\n       ds1 = ds1'.\n\nDefinition Eval_rhs_fun x s ds1\n  := forall ds1', Eval_rhs x s ds1' -> ds1 = ds1'.\n\nDefinition Solve_fun x s s1\n  := forall s1', Solve x s s1' -> s1 = s1'.\n\nDefinition SolveAll_fun (l : list Var.t) s s1\n  := forall s1', SolveAll l s s1' -> s1 = s1'.\n\nLemma partial_functions_invar :\n  (forall x y s1 ds2,\n     EvalGet x y s1 ds2 -> EvalGet_fun x y s1 ds2) /\\\n  (forall x f,\n    EvalGet_x x f -> EvalGet_x_fun x f) /\\\n  (forall x f t s1 ds2,\n    Wrap_Eval_x x f t s1 ds2 ->\n    Wrap_Eval_x_fun x f t s1 ds2) /\\\n  (forall x s1 ds2,\n    Eval_rhs x s1 ds2 -> Eval_rhs_fun x s1 ds2) /\\\n  (forall x s1 s2,\n    Solve x s1 s2 -> Solve_fun x s1 s2) /\\\n  (forall w s1 s2,\n    SolveAll w s1 s2 -> SolveAll_fun w s1 s2).\nProof.\napply solve_mut_min.\n\n(* EvalGet *)\n- idtac. intros x y s s0 Hsol Isol s1 d.\n  red. red in Isol.\n  intros [d' s1'] Heval'.\n  subst.\n  inversion Heval' as [? ? ? ? Hsol']; subst; clear Heval'.\n  assert (Htmp := Isol _ Hsol').\n  unfold d, s1. now subst.\n\n(* EvalGet_x *)\n- idtac. intros x f Heval Ieval.\n  red in Ieval. red.\n  intros f' Heval'.\n  intros y s ds0 ds0' Hf Hf'.\n  inversion Heval'; subst. now firstorder.\n\n(* Wrap_Eval_x *)\n- idtac. intros x f.\n  induction t as [c | a k IH].\n  + intros s [d s0] Hevalx Ievalx Hf.\n    red. intros f' [d' s0'] Hwrap Hfun.\n    inversion Hwrap; subst; clear Hwrap.\n    now eapply wrap_rel_State_fun; eauto.\n  + intros s [d1 s1] Hevalx Ievalx HfQue.\n    red.\n    intros f' [d' s1'] Hf'Que Hff'.\n    inversion Hf'Que; subst.\n    now eapply wrap_rel_State_fun; eauto.\n\n(* Eval_rhs *)\n- idtac. intros x f s ds0 Hevalx Ievalx Hwrap Iwrap.\n  red. intros ds0' Heval.\n  red in Iwrap.\n  inversion Heval; subst; clear Heval.\n  now eapply Iwrap; eauto.\n\n(* Solve 0 *)\n- idtac. intros x s Hstaxs.\n  red. intros s0' Hsol'.\n  now inversion Hsol'.\n\n(* Solve 1 *)\n- idtac.\n  intros x d1 s s1 Hnstaxs s0 Heval Ieval cur new Hleq.\n  red. intros s1' Hsol'.\n  red in Ieval.\n  inversion Hsol' as [| ? ? ? ? ? s0' Heval' | ? ? ? ? ? ? ? ? s0' Heval' ].\n  + now subst s1'.\n  + unfold s0' in Heval'.\n    assert (Htmp := Ieval _ Heval').\n    now inversion Htmp.\n  + subst s2 s6.\n    assert (Htmp := Ieval _ Heval').\n    inversion Htmp.\n    unfold new0, cur1, cur0 in H0.\n    unfold new, cur in Hleq.\n    subst d1.\n    now rewrite H3, <- H6 in H0.\n\n(* Solve 2 *)\n- idtac.\n  intros x d1 s s1 s3 s4 w.\n  intros Hnstaxs s0 Heval Ieval.\n  intros cur new Hnleq s2 Hwork Hsolall Isolall.\n  red. intros s4' Hsol'.\n  inversion Hsol' as [| ? ? ? ? ? s0' Heval' | ? ? ? ? ? ? ? ? s0' Heval' ].\n  + now subst s4'.\n  + unfold s0' in Heval'.\n    assert (Htmp := Ieval _ Heval').\n    subst s4' s5.\n    inversion Htmp; clear Htmp.\n    unfold new, cur in Hnleq.\n    unfold new0, cur0, cur1 in H0.\n    subst d.\n    now rewrite H1, <- H4 in H0.\n  + clear H Hnstaxs.\n    assert (Htmp := Ieval _ Heval'); clear Heval Ieval.\n    subst s4' s5.\n    inversion Htmp; clear Htmp.\n    unfold new, cur in Hnleq.\n    unfold new0, cur0, cur1 in H0.\n    rewrite H3, <- H5 in H0.\n    assert (Hw : (w,s3) = (work,s7)).\n    { rewrite Hwork, H1.\n      subst s9.\n      unfold s2, new, cur.\n      unfold new0, cur0.\n      now rewrite H3, H4, <- H5. }\n    inversion Hw; subst s7 work; clear Hw.\n    now eapply Isolall; eauto.\n\n(* SolveAll 0 *)\n- idtac.\n  intros s. red. intros s0' Hsolall'.\n  now inversion Hsolall'; subst.\n\n(* SolveAll 1 *)\n- idtac.\n  intros x xs s s0 s1 Hsol Isol Hsolall Isolall.\n  red. intros s1' Hsolall'.\n  inversion Hsolall' as [| ? ? ? s1'' ? Hsol'' Hsolall''];\n    subst; auto.\n  red in Isol. assert (e := Isol _ Hsol''); subst s1''.\n  red in Isolall. now apply Isolall; auto.\nQed.\n\n(* a nicer reformulation of partial_functions_invar: *)\nLemma partial_functions :\n  (forall x y s1 ds2 ds2',\n     EvalGet x y s1 ds2 ->\n     EvalGet x y s1 ds2' -> ds2 = ds2') /\\\n  (forall x y f f' s ds ds',\n    EvalGet_x x f ->\n    EvalGet_x x f' ->\n    f y s ds -> f' y s ds' -> ds = ds') /\\\n  (forall x f f' t s1 ds2 ds2',\n    Wrap_Eval_x x f t s1 ds2 ->\n    Wrap_Eval_x x f' t s1 ds2' ->\n    (forall y s ds ds',\n       f y s ds -> f' y s ds' -> ds = ds') ->\n    ds2 = ds2') /\\\n  (forall x s1 ds2 ds2',\n    Eval_rhs x s1 ds2 -> Eval_rhs x s1 ds2' -> ds2 = ds2') /\\\n  (forall x s1 s2 s2',\n    Solve x s1 s2 -> Solve x s1 s2' -> s2 = s2') /\\\n  (forall w s1 s2 s2',\n    SolveAll w s1 s2 -> SolveAll w s1 s2' -> s2 = s2').\nProof.\npose proof partial_functions_invar as H.\nunfold EvalGet_fun, EvalGet_x_fun, Wrap_Eval_x_fun,\n  Eval_rhs_fun, Solve_fun, SolveAll_fun in H.\ndestruct H as [Hevalget [Hevalgetx [Hwrap [Heval [Hsol Hsolall] ] ] ] ].\nsplit; [| split; [| split; [| split; [| split] ] ] ].\n- intros; now eapply Hevalget; eauto.\n- intros; now eapply Hevalgetx; [refine H | refine H0 | |]; eauto.\n- intros; now eapply Hwrap; eauto.\n- intros; now eapply Heval; eauto.\n- intros; now eapply Hsol; eauto.\n- intros; now eapply Hsolall; eauto.\nQed.\n\nSection instrumentation.\n\n(*Definition state := S.state.*)\nDefinition state' := SI.state'.\n\nDefinition projI (si : state') : state :=\n  let '(sigma, infl, stable, _, _) := si in\n    (sigma, infl, stable).\n\nDefinition sim (s : state) (si : state') := projI si = s.\n\n(* lifted simulation relation *)\nDefinition simT\n  (f : Var.t -> State state D.t)\n  (f' : Var.t -> State state' D.t)\n  := forall x s s1 s' s1' d d',\n       sim s s' ->\n       f x s = (d, s1) ->\n       f' x s' = (d', s1') ->\n       d = d' /\\ sim s1 s1'.\n\n(* lifted simulation relation *)\n(*Definition simTrel\n  (f : Var.t -> state -> D.t * state -> Prop)\n  (f' : Var.t -> state' -> D.t * state' -> Prop)\n  := forall x s s1 s' s1' d d',\n       sim s s' ->\n       f x s (d, s1) ->\n       f' x s'(d', s1') ->\n       d = d' /\\ sim s1 s1'.*)\n\nDefinition simTrel\n  (f : Var.t -> state -> D.t * state -> Prop)\n  (f' : Var.t -> state' -> D.t * state' -> Prop)\n  := forall x s s1 s' d,\n       sim s s' ->\n       f x s (d, s1) ->\n       exists ds1',\n       f' x s' ds1' /\\\n       let (d',s1') := ds1' in\n       d = d' /\\ sim s1 s1'.\n\nLemma sim_init : sim s_init SI.s_init.\neasy.\nQed.\n\nLtac destruct_state s :=\n  let sig := fresh \"sigma\" in\n  let inf := fresh \"infl\" in\n  let sta := fresh \"stable\" in\n    destruct s as [ [sig inf] sta].\n\nLtac destruct_state' s :=\n  let sig := fresh \"sigma'\" in\n  let inf := fresh \"infl'\" in\n  let sta := fresh \"stable'\" in\n  let cal := fresh \"called'\" in\n  let que := fresh \"queued'\" in\n    destruct s as [ [ [ [sig inf] sta] cal] que].\n\nLemma sim_projI s' : sim (projI s') s'.\nnow destruct_state' s'.\nQed.\nHint Resolve sim_projI.\n\nLemma sim_prepare x s s' (H : sim s s') :\n  sim (prepare x s) (SI.prepare x s').\nProof.\ndestruct_state s.\ndestruct_state' s'.\nnow inversion H; subst.\nQed.\nHint Resolve sim_prepare.\n\nLemma sim_getval s s' (H : sim s s') :\n  getval s = SI.getval s'.\nProof.\ndestruct_state s.\ndestruct_state' s'.\nnow inversion H; subst.\nQed.\nHint Resolve sim_getval.\n\nLemma sim_setval x d s s' (H : sim s s') :\n  sim (setval x d s) (SI.setval x d s').\nProof.\ndestruct_state s.\ndestruct_state' s'.\nnow inversion H; subst.\nQed.\nHint Resolve sim_setval.\n\nLemma sim_add_infl x y s s' (H : sim s s') :\n  sim (add_infl x y s) (SI.add_infl x y s').\nProof.\ndestruct_state s.\ndestruct_state' s'.\nnow inversion H; subst.\nQed.\nHint Resolve sim_add_infl.\n\nLemma sim_is_stable x s s' (H : sim s s') :\n  is_stable x s <-> SI.is_stable x s'.\nProof.\ndestruct_state s.\ndestruct_state' s'.\nnow inversion H; subst.\nQed.\nHint Resolve sim_is_stable.\n\nLemma sim_add_stable x s s' (H : sim s s') :\n  sim (add_stable x s) (SI.add_stable x s').\nProof.\ndestruct_state s.\ndestruct_state' s'.\nnow inversion H; subst.\nQed.\nHint Resolve sim_add_stable.\n\nLemma sim_rem_called x s s' (H : sim s s') :\n  sim s (SI.rem_called x s').\nProof.\ndestruct_state s.\ndestruct_state' s'.\nnow inversion H; subst.\nQed.\nHint Resolve sim_rem_called.\n\nLemma sim_rem_queued x s s' (H : sim s s') :\n  sim s (SI.rem_queued x s').\nProof.\ndestruct_state s.\ndestruct_state' s'.\nnow inversion H; subst.\nQed.\nHint Resolve sim_rem_queued.\n\nLemma sim_handle_work s s' w (H : sim s s') :\n  sim (handle_work w s) (SI.handle_work w s').\nProof.\nrevert s s' H. induction w as [| x xs IH].\n- now firstorder.\n- intros s s' Hsims. simpl.\n  destruct_state s.\n  destruct_state' s'.\n  apply IH. now inversion Hsims.\nQed.\nHint Resolve sim_handle_work.\n\nLemma sim_extract_work x s s' w w' s0 s0' (H : sim s s') :\n  (w, s0) = extract_work x s ->\n  (w', s0') = SI.extract_work x s' ->\n  w = w' /\\ sim s0 s0'.\nProof.\ndestruct_state s.\ndestruct_state' s'.\nintros Hw Hw'.\nassert (Ew : w = w')\n  by (inversion Hw; inversion Hw'; now inversion H; subst).\nsplit; auto.\n- subst w'. inversion H; subst.\n  inversion Hw. inversion Hw'. now apply sim_handle_work.\nQed.\n\n(* simulation 'invariants' *)\nDefinition EvalGet_sim x y s ds1\n  := forall s',\n       sim s s' ->\n       exists ds1',\n         let '(d,s1) := ds1 in\n         let '(d',s1') := ds1' in\n       SI.EvalGet Hpure x y s' (d',s1') /\\\n       d = d' /\\ sim s1 s1'.\n\nDefinition EvalGet_x_sim (x : Var.t)\n                         (f : Var.t -> state -> D.t * state -> Prop)\n  := exists f', SI.EvalGet_x Hpure x f' /\\ simTrel f f'.\n\nDefinition Wrap_Eval_x_sim x f t s ds1\n  := forall f' s' l',\n       sim s s' ->\n       simTrel f f' ->\n       SI.EvalGet_x Hpure x f' ->\n       exists ds1' l1',\n         let '(d,s1) := ds1 in\n         let '(d',s1') := ds1' in\n       SI.Wrap_Eval_x Hpure x f' t (s',l') (d',(s1',l1')) /\\\n       d = d' /\\ sim s1 s1'.\n\nDefinition Eval_rhs_sim x s ds1\n  := forall s',\n       sim s s' ->\n       exists ds1' l',\n         let '(d,s1) := ds1 in\n         let '(d',s1') := ds1' in\n       SI.Eval_rhs Hpure x s' (d',(s1',l')) /\\\n       d = d' /\\ sim s1 s1'.\n\nDefinition Solve_sim x s s1\n  := forall s',\n       sim s s' ->\n       exists s1',\n         SI.Solve Hpure x s' s1' /\\ sim s1 s1'.\n\nDefinition SolveAll_sim (l : list Var.t) s s1\n  := forall s',\n       sim s s' ->\n       exists s1',\n         SI.SolveAll Hpure l s' s1' /\\ sim s1 s1'.\n\nRequire Import Classical.\nRequire Import Epsilon.\nRequire Import ChoiceFacts.\n\nTheorem simulation :\n  (forall x y s1 ds2,\n     EvalGet x y s1 ds2 -> EvalGet_sim x y s1 ds2) /\\\n  (forall x f,\n    EvalGet_x x f -> EvalGet_x_sim x f) /\\\n  (forall x f t s1 ds2,\n    Wrap_Eval_x x f t s1 ds2 ->\n    Wrap_Eval_x_sim x f t s1 ds2) /\\\n  (forall x s1 ds2,\n    Eval_rhs x s1 ds2 -> Eval_rhs_sim x s1 ds2) /\\\n  (forall x s1 s2,\n    Solve x s1 s2 -> Solve_sim x s1 s2) /\\\n  (forall w s1 s2,\n    SolveAll w s1 s2 -> SolveAll_sim w s1 s2).\nProof.\napply solve_mut_min.\n\n(* EvalGet *)\n- idtac.\n  intros x y s s0 Hsol Hsolsim s1 d.\n  red. intros s' Hsims.\n  red in Hsolsim.\n  elim (Hsolsim _ Hsims); intros s0' [Hsol' Hsims0].\n  pose (d' := SI.getval s0' y).\n  assert (e : d = d')\n    by (subst d; unfold d'; now erewrite sim_getval).\n  pose (s1' := SI.add_infl y x s0').\n  assert (Hsims1 : sim s1 s1')\n    by (subst s1; apply sim_add_infl; auto).\n  exists (d',s1').\n  split; [| split]; try apply SI.EvalGet0; easy.\n\n(* Eval_x *)\n- idtac.\n  intros x f H H0.\n  red. red in H0.\n  pose (f' := fun y s' ds1' =>\n          let '(d',s1') := ds1' in\n          match (constructive_definite_descr_excluded_middle\n                   constructive_definite_description\n                   classic)\n                  (f y (projI s') (d',(projI s1'))) with\n            | right _ => False\n            | left e =>\n                let ds1'' :=\n                    proj1_sig\n                      (constructive_indefinite_description\n                         _\n                         (H0 y (projI s') (d',(projI s1'))\n                             e s' (sim_projI s'))\n                      ) in\n                ds1'' = ds1'\n          end).\n  exists f'.\n  split.\n  + apply SI.EvalGet_x0.\n    intros y s' [d' s0'] Hf'.\n    unfold f' in Hf'.\n    simpl in Hf'.\n    destruct\n      (constructive_definite_descr_excluded_middle\n         constructive_definite_description classic\n         (f y (projI s') (d', projI s0'))); try easy.\n    assert (Hf'0 :=\n            proj2_sig\n              (constructive_indefinite_description\n                 _\n                 (H0 y (projI s') (d', projI s0') f0 s' (sim_projI s')))).\n    now rewrite Hf' in Hf'0.\n  + red. intros y s s0 s' d Hsims Hf.\n    destruct (H0 _ _ _ Hf _ Hsims)\n             as [ [d' s0'] [Heval' [? Hsims0] ] ]; subst d'.\n    exists (d,s0').\n    split; [| now auto].\n    unfold f'.\n    change (\n        match\n          constructive_definite_descr_excluded_middle\n            constructive_definite_description classic\n            (f y (projI s') (d, projI s0'))\n        with\n          | left e =>\n              proj1_sig\n                (constructive_indefinite_description\n                   _\n                   (H0 y (projI s') (d, projI s0')\n                       e s' (sim_projI s'))) =\n            (d, s0')\n          | right _ => False\n        end\n      ).\n    assert (Hfproj : f y (projI s') (d, projI s0')).\n    { rewrite Hsims. red in Hsims0; now rewrite Hsims0. }\n    destruct\n      (constructive_definite_descr_excluded_middle\n         constructive_definite_description classic\n         (f y (projI s') (d, projI s0'))) as [p | n]; auto.\n    assert (eHf : p = Hfproj) by (apply proof_irrelevance).\n    subst p.\n    set (p' :=\n         proj1_sig\n           (constructive_indefinite_description\n              _\n              (H0 y (projI s') (d, projI s0')\n                  Hfproj s' (sim_projI s')))).\n    assert (Hp' :=\n            proj2_sig\n              (constructive_indefinite_description\n                 _\n                 (H0 y (projI s') (d, projI s0') Hfproj s' (sim_projI s')))).\n    simpl in Hp'. fold p' in Hp'.\n    destruct p' as [pd' ps'].\n    destruct Hp' as [Hp' _].\n    now rewrite <- (proj1 (SI.partial_functions Hpure)\n                     _ _ _ _ _ Heval' Hp').\n\n(* Wrap_Eval_x *)\n- idtac.\n  intros x f.\n  induction t as [a | q k IH].\n  + idtac.\n    intros s [d s0] Hevalx Hevalxsim Ht.\n    destruct (wrap_rel_State_Ans_inv Ht); subst; clear Ht.\n    red. intros f' s' l' Hsims Hsimf Hevalx'.\n    exists (a,s'), l'.\n    split; auto.\n    apply SI.Wrap_Eval_x0; auto.\n    now apply wrapAns.\n  + intros s [d1 s1] Hevalx Hevalxsim Ht.\n    destruct (wrap_rel_State_Que_inv Ht)\n      as [d0 [s0 [Hf Hwrapf] ] ]; clear Ht.\n    assert (Hwrapeval : Wrap_Eval_x_sim x f (k d0) s0 (d1, s1))\n      by (apply IH; auto). clear IH.\n    red. intros f' s' l' Hsims Hsimf Hevalx'.\n    red in Hwrapeval.\n    red in Hevalxsim.\n    assert (Htmp := Hsimf _ _ _ _ _ Hsims Hf).\n    destruct Htmp as [ [d' s0'] [Hf' [? Hsims0 ] ] ].\n    subst d'.\n    assert (Htmp := Hwrapeval f' s0' (l' ++ [(q,d0)]) Hsims0 Hsimf Hevalx').\n    destruct Htmp as [ [d1' s1'] [l1' [Hwrapeval' [? Hsims1] ] ] ];\n      clear Hwrapeval.\n    subst d1'.\n    exists (d1,s1'), l1'. split; auto.\n    apply SI.Wrap_Eval_x0; auto.\n    apply wrapQue with (d0:=d0) (s0:= (s0', l' ++ [(q,d0)])).\n    * now apply SI.instrR0.\n    * now inversion Hwrapeval'; subst.\n\n(* Eval_rhs *)\n- idtac.\n  intros x f s [d s0] Hevalx Ievalx Hwrapx Iwrapx.\n  red. intros s' Hsims.\n  red in Ievalx. destruct Ievalx as [f' [Hevalx' Hsimff'] ].\n  red in Iwrapx.\n  destruct (Iwrapx f' _ [] Hsims) as [ [d' s0'] H]; auto.\n  destruct H as [l1' [Hwrapeval' [e Hsims0] ] ].\n  exists (d',s0'), l1'.\n  split; [| split]; try apply (SI.Eval_rhs0 (f:=f')); easy.\n\n(* Solve0 *)\n- idtac.\n  intros x s Hsta.\n  red. intros s' Hsims.\n  exists s'. split; auto.\n  apply SI.Solve0. now eapply sim_is_stable; eauto.\n\n(* Solve1 *)\n- idtac.\n  intros x d s s1 Hxnsta s0 Hevalrhs Hevalrhssim cur new Hleq.\n  red. intros s' Hsims.\n  assert (Hxnsta' : ~ SI.is_stable x s')\n    by (contradict Hxnsta; now eapply sim_is_stable; eauto).\n  red in Hevalrhssim.\n  pose (s0' := SI.prepare x s').\n  assert (Hsims0 : sim s0 s0') by (apply sim_prepare; auto).\n  destruct (Hevalrhssim _ Hsims0) as [ [d' s1'] [l1' [Hevalrhs' [e Hsims1] ] ] ].\n  clear Hevalrhssim. subst d'.\n  pose (s1'' := SI.rem_called x s1').\n  pose (cur' := SI.getval s1'' x).\n  pose (new' := D.join cur' d).\n  assert (Hsims1' : sim s1 s1'') by (apply sim_rem_called; auto).\n  assert (Hle' : SI.D.Leq new' cur')\n    by (unfold new',cur'; now erewrite <- sim_getval; eauto).\n  exists s1''. split; auto.\n  eapply (SI.Solve1); eauto.\n\n(* Solve2 *)\n- idtac.\n  intros x d s s1 s4 s5 w.\n  intros Hxnsta s0 Hevalrhs Hevalrhssim cur new Hleq s3 Hw Hsolall Hsolallsim.\n  red. intros s' Hsims.\n  assert (Hxnsta' : ~ SI.is_stable x s')\n    by (contradict Hxnsta; now eapply sim_is_stable; eauto).\n  red in Hevalrhssim.\n  pose (s0' := SI.prepare x s').\n  assert (Hsims0 : sim s0 s0') by (apply sim_prepare; auto).\n  destruct (Hevalrhssim _ Hsims0) as [ [d' s1'] [l1' [Hevalrhs' [e Hsims1] ] ] ].\n  clear Hevalrhssim. subst d'.\n  pose (s2' := SI.rem_called x s1').\n  pose (cur' := SI.getval s2' x).\n  pose (new' := SI.D.join cur' d).\n  assert (Hsims1' : sim s1 s2') by (apply sim_rem_called; auto).\n  assert (Hnle' : ~ SI.D.Leq new' cur')\n    by (unfold new',cur'; now erewrite <- sim_getval; eauto).\n  pose (s3' := SI.setval x new' s2').\n  assert (Hsims3 : sim s3 s3').\n  { unfold s3, s3', new, new', cur, cur'.\n    rewrite <- (sim_getval Hsims1'). now apply sim_setval. }\n  destruct (SI.extract_work x s3') as (w', s4') eqn:Hw'.\n  assert (Htmp1 : w = w' /\\ sim s4 s4')\n    by (eapply sim_extract_work; eauto).\n  destruct Htmp1 as [? Hsims4]; subst w'.\n  destruct (Hsolallsim _ Hsims4) as [s5' [Hsolall' Hsims5] ].\n  exists s5'. split; auto.\n  now eapply (SI.Solve2); eauto.\n\n(* SolveAll0 *)\n- idtac.\n  intros s.\n  red. intros s' Hsims.\n  exists s'. split; auto.\n  now eapply (SI.SolveAll0); eauto.\n\n(* SolveAll1 *)\n- idtac.\n  intros x xs s s0 s1 Hsols Hsolsim Hsolall Hsolallsim.\n  red. intros s' Hsims.\n  destruct (Hsolsim _ Hsims) as [s0' [Hsols'  Hsims0] ].\n  destruct (Hsolallsim _ Hsims0) as [s1' [Hsolall'  Hsims1] ].\n  exists s1'. split; auto.\n  now eapply (SI.SolveAll2); eauto.\nQed.\n\nEnd instrumentation.\n\nTheorem correctness s w :\n  SolveAll w s_init s ->\n  (forall z, In z w -> is_stable z s) /\\\n  (forall z v d,\n     is_stable z s ->\n     In (v,d) (deps (rhs z) (getval s)) ->\n     is_stable v s) /\\\n  (forall z,\n     is_stable z s -> D.Leq ([[rhs z]]* (getval s)) (getval s z)).\nProof.\nintros Hsolall.\napply simulation in Hsolall.\nassert (Htmp := Hsolall _ sim_init).\ndestruct Htmp as [s' [Hsolall' Hsims] ].\napply SI.correctness in Hsolall'.\ndestruct Hsolall' as [H0 [H1 H2] ].\nsplit; [| split].\n- clear - Hsims H0.\n  intros. now eapply sim_is_stable; eauto.\n- clear - Hsims H1.\n  rewrite <- (sim_getval Hsims) in H1.\n  intros z v d Hsta Hin. apply <- (sim_is_stable v Hsims).\n  eapply H1; [| refine Hin].\n  now apply (sim_is_stable z Hsims).\n- clear - H2 Hsims.\n  intros z Hsta.\n  rewrite <- (sim_getval Hsims) in H2.\n  now apply -> (sim_is_stable z Hsims) in Hsta; auto.\nQed.\n\nTheorem exactness :\n  has_uniq_lookup rhs ->\n  is_monotone rhs ->\n  forall mu w s,\n    is_solution rhs mu ->\n    SolveAll w s_init s ->\n    leqF (getval s) mu.\nProof.\nintros Huniq Hmon mu w s Hsolmu Hsolall.\napply simulation in Hsolall.\nassert (Htmp := Hsolall _ sim_init).\ndestruct Htmp as [s' [Hsolall' Hsims] ].\napply SI.exactness with (mu:=mu) in Hsolall'; try rewrite <- rhs_same; auto.\nnow rewrite (sim_getval Hsims).\nQed.\n\nSection termination.\n\nRequire Import Rels.\nRequire Import Arith.\nRequire Import Omega.\n\n(* We prove termination of RLD on the two assumptions: *)\nVariable Hasc : ascending_chain D.Leq.\n\nVariable varSet : {s : VS.t | forall x, VS.In x s}.\nLet V := proj1_sig varSet.\nLet cardV := VS.cardinal V.\n\nDefinition varVec :\n  {n : nat &\n    {v : vector Var.t n &\n       forall x, {i : {k : nat | k < n} | nth v i = x}}}.\nProof.\npose (l := VS.elements V).\ndestruct (vector_of l) as [n v] eqn:Hl.\nexists n, v.\nintros x.\nassert (Hx : has v x).\n{ assert (Htmp:= InA_has).\n  specialize Htmp with (l:=l) (a:=x).\n  rewrite Hl in Htmp.\n  apply Htmp; clear Htmp.\n  apply elements_1.\n  now apply (proj2_sig varSet). }\nexists (find Var.eq_dec Hx).\nnow apply nth_find.\nDefined.\n\nDefinition phi (f : Var.t -> D.t) : vector D.t _ :=\n  let v := projT1 (projT2 varVec) in map v f.\n\nDefinition psi (dv : vector D.t (projT1 varVec)) : Var.t -> D.t :=\n  fun x =>\n    let v := projT1 (projT2 varVec) in\n    let H := projT2 (projT2 varVec) in\n    let i := proj1_sig (H x) in\n      nth dv i.\n\nLemma psi_phi f : psi (phi f) = f.\nextensionality x.\nunfold phi, psi.\nrewrite nth_map.\nf_equal.\nnow apply (proj2_sig (projT2 (projT2 varVec) x)).\nQed.\n\nLemma phi_inj f g : phi f = phi g -> f = g.\nProof.\nintros H.\nrewrite <- (psi_phi f).\nrewrite <- (psi_phi g).\nnow f_equal.\nQed.\n\n(* TODO : rename lemmas *)\nLet R_phi (R : relation D.t) : relation (Var.t -> D.t)\n  := fun f g => lp_vector R (phi f) (phi g).\n\nLemma leqF_sub_inverse_lp_vector f g :\n  leqF f g -> R_phi D.Leq f g. \nProof.\nintros H.\nunfold R_phi.\napply lp_vector_nth.\nintros i.\nunfold phi.\nnow rewrite !nth_map.\nQed.\n\nLemma lem4 f g :\n  strict (inv (leqF (X:=Var.t))) f g ->\n  strict (inv (lp_vector D.Leq (n:=projT1 varVec)))\n         (phi f) (phi g).\nProof.\nintros [H ne].\nunfold inv, strict.\nunfold inv, strict in H.\nsplit; [now apply leqF_sub_inverse_lp_vector |\n        intros e; now apply phi_inj in e].\nQed.\n\nLemma lem4_bis :\n  inclusion\n    _\n    (strict (inv (leqF (X:=Var.t))))\n    (fun f g =>\n       (strict (inv (lp_vector D.Leq (n:=projT1 varVec))))\n         (phi f)\n         (phi g)).\nProof.\nunfold inclusion. intros f g.\nnow apply lem4.\nQed.\n\nLemma prec_1_wf :\n  well_founded (strict (inv (leqF (X:=Var.t)))).\nProof.\npose (H := fun n => asc_lp_vector (D.eq_dec) (n:=n) Hasc).\nunfold ascending_chain in H.\nspecialize H with (projT1 varVec).\napply wf_inverse_image with (f:=phi) in H.\nnow apply (wf_incl _ _ _ lem4_bis).\nQed.\n\nLemma subset_V s : VS.Subset s V.\nProof.\nintros x _.\nnow apply (proj2_sig varSet).\nQed.\nHint Resolve subset_V.\n\nLemma le_cardVar s : VS.cardinal s <= cardV.\nProof.\nnow apply VSetProps.subset_cardinal; auto.\nQed.\nHint Resolve le_cardVar.\n\nLemma cardVar_equal_V s :\n  VS.cardinal s = cardV ->\n  VS.Equal s V.\nProof.\nintros H.\napply subset_antisym; [now apply subset_V |].\nintros x Hx.\ndestruct (VSetProps.In_dec x s) as [e | n]; auto.\nassert (Hcard : VSet.cardinal s < VSet.cardinal V)\n  by (apply VSetProps.subset_cardinal_lt with x; auto).\nrewrite H in Hcard.\nnow apply Lt.lt_irrefl in Hcard.\nQed.\n\nDefinition strictS (R : relation VS.t) : relation VS.t :=\n  fun s t => R s t /\\ ~ VS.Equal s t.\n\nLemma card_Acc n :\n  forall s,\n    n + VS.cardinal s = cardV ->\n    Acc (strictS (inv (VS.Subset))) s.\nProof.\napply (lt_wf_ind n); clear n.\nintros n IH.\nintros s H.\nconstructor.\nintros t Ht.\nunfold strictS, inv in Ht.\npose (d := VS.diff t s).\nassert (Hd : ~ VS.Empty d).\n{ clear - Ht.\n  destruct Ht as [Hst Hne].\n  contradict Hne. now fsetdec. }\nassert (Hdcard : VS.cardinal d <> 0).\n{ contradict Hd. now apply VSetProps.cardinal_inv_1. }\nassert (Hdcardpos : VS.cardinal d > 0).\n{ unfold gt. now apply neq_0_lt; auto. }\nassert (Et : VS.Equal t (VS.union s d)) by fsetdec.\nassert (Hs' : VS.cardinal t = VS.cardinal s + VS.cardinal d)\n  by (rewrite Et; apply VSetProps.union_cardinal; now fsetdec).\npose (m := n - VS.cardinal d).\nassert (Hdn : VS.cardinal d <= n).\n{ apply plus_le_reg_l with (VS.cardinal s).\n  rewrite (plus_comm _ n), H, <- Hs'.\n  now auto. }\nassert (Hm : m < n) by (apply lt_minus; auto).\nassert (Hm1 : m + VS.cardinal t = cardV)\n  by (unfold m; rewrite Hs', <- H; omega).\nnow apply IH with m.\nQed.\n\nLemma prec_2_wf : well_founded (strictS (inv VS.Subset)).\nProof.\nunfold well_founded.\nintros s.\npose (n := cardV - VS.cardinal s).\nassert (Hcard : VS.cardinal s <= cardV) by auto.\nassert (H : n + VS.cardinal s = cardV) by (unfold n; omega).\nnow apply card_Acc with n.\nQed.\n\nDefinition sigma_fun (sigma : Sigma.t D.t) : Var.t -> D.t :=\n  fun x =>\n    match Sigma.find x sigma with\n      | Some d => d\n      | None => D.bot\n    end.\n\nLemma getval_sigma sigma infl stable :\n  getval (sigma, infl, stable) = sigma_fun sigma.\nProof.\neasy.\nQed.\n\nDefinition prec_sigma : relation (Sigma.t D.t) :=\n  fun sigma1 sigma2 =>\n    strict (inv (leqF (X:=Var.t))) (sigma_fun sigma1) (sigma_fun sigma2).\n\nLemma prec_sigma_irrefl s : ~ prec_sigma s s.\nProof.\nnow firstorder.\nQed.\nHint Resolve prec_sigma_irrefl.\n\nLemma prec_sigma_trans : transitive _ prec_sigma.\nProof.\nintros s1 s2 s3.\nunfold prec_sigma, strict, inv.\nintros [H10 H11].\nintros [H20 H21].\nsplit.\n- now eapply leqF_trans; eauto.\n- contradict H11. rewrite <- H11 in H20.\n  now apply leqF_antisym.\nQed.\n\nLemma prec_sigma_wf : well_founded prec_sigma.\nProof.\nunfold prec_sigma.\napply wf_inverse_image with (f:=sigma_fun).\nnow apply prec_1_wf.\nQed.\n\nDefinition prec_stable : relation VS.t :=\n  fun s1 s2 => strictS (inv VS.Subset) s1 s2.\n\nLemma prec_stable_irrefl s : ~ prec_stable s s.\nProof.\nnow firstorder.\nQed.\nHint Resolve prec_stable_irrefl.\n\nLemma prec_stable_trans : transitive _ prec_stable.\nProof.\nintros s1 s2 s3.\nunfold prec_stable, strict, inv.\nintros [H10 H11].\nintros [H20 H21].\nsplit.\n- now fsetdec.\n- contradict H11. now fsetdec.\nQed.\n\nLemma prec_stable_wf : well_founded prec_stable.\nProof.\nrefine prec_2_wf.\nQed.\n\nDefinition prec_ss := lexprod prec_sigma prec_stable.\n\nLemma prec_ss_wf : well_founded prec_ss.\nProof.\napply lexprod_wf;\n  [now apply prec_sigma_wf | now apply prec_stable_wf].\nQed.\n\nDefinition forget_infl (s : state) :=\n  let '(sigma, _, stable) := s in (sigma, stable).\n\nDefinition prec_state : relation state :=\n  fun s1 s2 => prec_ss (forget_infl s1) (forget_infl s2).\n\nLemma prec_state_wf : well_founded prec_state.\nProof.\nunfold prec_state.\napply wf_inverse_image with (f:=forget_infl).\nnow apply prec_ss_wf.\nQed.\n\nLocal Infix \"<\" := prec_state (at level 70).\n\nLemma prec_state_irrefl s : ~ s < s.\nProof.\nunfold prec_state, prec_ss.\ndestruct_state s. simpl.\nintros H. inversion H; subst; now firstorder.\nQed.\nHint Resolve prec_state_irrefl.\n\nLemma prec_state_trans : transitive _ prec_state.\nProof.\nintros s1 s2 s3.\nunfold prec_state, prec_ss.\ndestruct_state s1.\ndestruct_state s2.\ndestruct_state s3.\nsimpl.\nintros H1 H2.\ninversion H1 as [? ? ? ? H10 | ? ? ? H10]; subst; clear H1.\n- inversion H2 as [? ? ? ? H20 | ? ? ? H20]; subst; clear H2.\n  + left. now eapply prec_sigma_trans; eauto.\n  + now left.\n- inversion H2 as [? ? ? ? H20 | ? ? ? H20]; subst; clear H2.\n  + now left.\n  + right. now eapply prec_stable_trans; eauto.\nQed.\n\nDefinition eq_state : relation state :=\n  fun s1 s2 =>\n    let '(sigma1, _, stable1) := s1 in\n    let '(sigma2, _, stable2) := s2 in\n      sigma1 = sigma2 /\\ stable1 = stable2.\n\nLemma eq_state_refl : reflexive _ eq_state.\nProof.\nintros s; now destruct_state s.\nQed.\nHint Resolve eq_state_refl.\n\nLemma eq_state_sym : symmetric _ eq_state.\nProof.\nintros s1 s2.\ndestruct_state s1.\ndestruct_state s2.\nintros [? ?].\nnow subst.\nQed.\nHint Resolve eq_state_sym.\n\nLemma eq_state_trans : transitive _ eq_state.\nProof.\nintros s1 s2 s3.\ndestruct_pose_state s1.\ndestruct_pose_state s2.\ndestruct_pose_state s3.\nintros H1 H2.\ndestruct H1 as [H10 H11]; destruct H2 as [H20 H21].\nred. split; congruence.\nQed.\n\nDefinition precEq_state : relation state\n  := fun s1 s2 => prec_state s1 s2 \\/ eq_state s1 s2.\n\nLocal Infix \"<=\" := precEq_state (at level 70).\n\nLemma precEq_state_refl : reflexive _ precEq_state.\nProof.\nnow right; auto.\nQed.\nHint Resolve precEq_state_refl.\n\nLemma prec_eq_state s1 s2 s3 :\n  s1 < s2 -> eq_state s2 s3 -> s1 < s3.\nProof.\ndestruct_state s1.\ndestruct_state s2.\ndestruct_state s3.\nintros H1 H2. destruct H2.\ninversion H1; subst; clear H1.\n- now left.\n- now right.\nQed.\n\nLemma eq_prec_state s1 s2 s3 :\n  eq_state s1 s2 -> s2 < s3 -> s1 < s3.\nProof.\ndestruct_state s1.\ndestruct_state s2.\ndestruct_state s3.\nintros H1 H2. destruct H1.\ninversion H2; subst; clear H2.\n- now left.\n- now right.\nQed.\n\nLemma prec_precEq_state s1 s2 s3 :\n  s1 < s2 -> s2 <= s3 -> s1 < s3.\nProof.\nintros H1 H2. destruct H2 as [H2 | H2].\n- now eapply prec_state_trans; eauto.\n- now eapply prec_eq_state; eauto.\nQed.\n\nLemma precEq_prec_state s1 s2 s3 :\n  s1 <= s2 -> s2 < s3 -> s1 < s3.\nProof.\nintros H1 H2. destruct H1 as [H1 | H1].\n- now eapply prec_state_trans; eauto.\n- now eapply eq_prec_state; eauto.\nQed.\n\nLemma precEq_state_trans : transitive _ precEq_state.\nProof.\nintros s1 s2 s3.\nintros H1 H2.\ndestruct H1 as [H1 | H1]. \n- left. now eapply prec_precEq_state; eauto.\n- destruct H2 as [H2 | H2].\n  + left. now eapply eq_prec_state; eauto.\n  + right. now eapply eq_state_trans; eauto.\nQed.\n\nLemma eq_precEq_state s1 s2 s3 :\n  eq_state s1 s2 -> s2 <= s3 -> s1 <= s3.\nProof.\nintros H1 H2. destruct H2 as [H2 | H2].\n- left. now eapply eq_prec_state; eauto.\n- right. now eapply eq_state_trans; eauto.\nQed.\n\nLemma precEq_eq_state s1 s2 s3 :\n  s1 <= s2 -> eq_state s2 s3 -> s1 <= s3.\nProof.\nintros H1 H2. destruct H1 as [H1 | H1].\n- left. now eapply prec_eq_state; eauto.\n- right. now eapply eq_state_trans; eauto.\nQed.\n\nLemma eq_state_add_infl x y s :\n  eq_state (add_infl x y s) s.\nProof.\nnow destruct_state s.\nQed.\nLocal Hint Resolve eq_state_add_infl.\n\nLemma prec_prepare x s :\n  ~ is_stable x s -> prepare x s < s.\nProof.\ndestruct_state s.\nintros H. simpl in *.\nunfold prec_state, prec_ss.\nright.\nunfold prec_stable, strictS, inv; simpl.\nsplit; now fsetdec.\nQed.\n\nLemma precEq_invariant :\n  (forall x y s1 ds2,\n     EvalGet x y s1 ds2 ->\n     let (d,s2) := ds2 in s2 <= s1) /\\\n  (forall x f,\n     EvalGet_x x f ->\n     forall y s1 ds2,\n       f y s1 ds2 ->\n       let (d,s2) := ds2 in s2 <= s1) /\\\n  (forall x f t s1 ds2,\n     Wrap_Eval_x x f t s1 ds2 ->\n     let (d,s2) := ds2 in s2 <= s1) /\\\n  (forall x s1 ds2,\n     Eval_rhs x s1 ds2 ->\n     let (d,s2) := ds2 in s2 <= s1) /\\\n  (forall x s1 s2,\n     Solve x s1 s2 -> s2 <= s1) /\\\n  (forall w s1 s2,\n     SolveAll w s1 s2 -> s2 <= s1).\nProof.\napply solve_mut_min.\n\n(* EvalGet *)\n- idtac. intros x y s s0 _ Isol s1 d.\n  subst s1.\n  now apply eq_precEq_state with (s2:=s0); auto.\n\n(* EvalGet_x *)\n- idtac. easy.\n\n(* Wrap_Eval_x *)\n- idtac. intros x f.\n  induction t as [c | a k IH].\n  + intros s [d s0] _ Ievalx Ht.\n    now destruct (wrap_rel_State_Ans_inv Ht); subst.\n  + intros s [d1 s1] Hevalx Ievalx Ht.\n    destruct (wrap_rel_State_Que_inv Ht)\n      as [d0 [s0 [Hf Hwrapf] ] ]; clear Ht.\n    assert (H := Ievalx _ _ _ Hf).\n    simpl in H.\n    assert (H1 : s1 <= s0)\n      by (eapply (@IH _ _ (d1,s1)); eauto).\n    now eapply precEq_state_trans; eauto.\n\n(* Eval_rhs *)\n- idtac. now firstorder.\n\n(* Solve 0 *)\n- idtac. now auto.\n\n(* Solve 1 *)\n- idtac.\n  intros x d s s1 Hnstaxs s0 _ Ievalrhs cur Hleq.\n  assert (H : s0 < s) by (apply prec_prepare; auto).\n  left. now eapply precEq_prec_state; eauto.\n\n(* Solve 2 *)\n- idtac.\n  intros x d s s1 s3 s4 w.\n  intros Hnstaxs s0 _ Ievalrhs cur new Hnleq s2 Hw _ Isolveall.\n  assert (H : s0 < s) by (apply prec_prepare; auto).\n  clear Hnstaxs.\n  apply (precEq_state_trans Isolveall); clear Isolveall.\n  left.\n  apply (precEq_prec_state (s2:=s0)); auto.\n  apply (@precEq_state_trans s3 s1 s0); auto.\n  clear - Hnleq Hw.\n  assert (Hwspec := extract_work_spec Hw); clear Hw.\n  assert (Hvals1 : forall z, x <> z -> getval s3 z = getval s1 z).\n  { clear - Hwspec. intros z ne.\n    destruct_state s1; destruct_state s3.\n    destruct Hwspec as [_ [H _ ] ].\n    simpl in *; subst. now rewrite add_neq_o. }\n  assert (Hvals1x : getval s3 x = D.join cur d).\n  { clear - Hwspec.\n    destruct_state s1; destruct_state s3.\n    destruct Hwspec as [_ [H _ ] ].\n    simpl in *; subst. now rewrite add_eq_o. }\n  left. unfold prec_state, prec_ss.\n  destruct_state s1.\n  destruct_state s3.\n  left. unfold prec_sigma, strict, inv.\n  rewrite !getval_sigma in Hvals1.\n  rewrite getval_sigma in Hvals1x.\n  split.\n  + intros u. destruct (Var.eq_dec x u) as [e | n].\n    * subst u. now rewrite Hvals1x.\n    * now rewrite Hvals1; auto.\n  + contradict Hnleq. unfold cur.\n    now rewrite getval_sigma, <- Hnleq, Hvals1x.\n\n(* SolveAll 0 *)\n- idtac. now auto.\n\n(* SolveAll 1 *)\n- idtac. intros x xs s s0 s1 _ Isolve _ Isolveall.\n  now eapply precEq_state_trans; eauto.\nQed.\n\nLemma prec_call_SolveAll x s d s1 s3 w :\n  ~ is_stable x s ->\n  let s0 := prepare x s in\n  Eval_rhs x s0 (d, s1) ->\n  let cur := getval s1 x in\n  let new := D.join cur d in\n  ~ D.Leq new cur ->\n  let s2 := setval x new s1 in\n  (w, s3) = extract_work x s2 ->\n  s3 < s.\nProof.\nintros Hnstaxs s0 Evalrhs cur new Hnleq s2 Hw.\nassert (H : s0 < s) by (apply prec_prepare; auto).\nclear Hnstaxs.\napply precEq_invariant in Evalrhs.\napply (@prec_state_trans s3 s0 s); auto. clear H.\napply (prec_precEq_state (s2:=s1)); auto. clear Evalrhs.\nassert (Hwspec := extract_work_spec Hw); clear Hw.\nassert (Hvals1 : forall z, x <> z -> getval s3 z = getval s1 z).\n{ clear - Hwspec. intros z ne.\n  destruct_state s1; destruct_state s3.\n  destruct Hwspec as [_ [H _ ] ].\n  simpl in *; subst. now rewrite add_neq_o. }\nassert (Hvals1x : getval s3 x = D.join cur d).\n{ clear - Hwspec.\n  destruct_state s1; destruct_state s3.\n  destruct Hwspec as [_ [H _ ] ].\n  simpl in *; subst. now rewrite add_eq_o. }\nunfold prec_state, prec_ss.\ndestruct_state s1.\ndestruct_state s3.\nleft. unfold prec_sigma, strict, inv.\nrewrite !getval_sigma in Hvals1.\nrewrite getval_sigma in Hvals1x.\nsplit.\n+ intros u. destruct (Var.eq_dec x u) as [e | n].\n  * subst u. now rewrite Hvals1x.\n  * now rewrite Hvals1; auto.\n+ contradict Hnleq. unfold cur.\n  now rewrite getval_sigma, <- Hnleq, Hvals1x.\nQed.\n\nTheorem termination :\n  forall x s1, exists s2, Solve x s1 s2.\nProof.\nintros x s; revert s x.\napply (@well_founded_ind _ _ prec_state_wf\n        (fun s => forall x, exists s2, Solve x s s2)); auto.\nintros s IH x.\ndestruct (is_stable_dec x s) as [Hstaxs | Hnstaxs];\n  [exists s; now apply Solve0 |].\npose (s0 := prepare x s).\nassert (Hprecs0 : s0 < s) by (apply prec_prepare; auto).\nassert (Heval: forall y s1,\n                 s1 < s -> exists ds2, EvalGet x y s1 ds2).\n{ intros y s1 Hprecs1.\n  destruct (IH _ Hprecs1 y) as [s2 Hs2].\n  pose (s3 := add_infl y x s2).\n  pose (d := getval s2 y).\n  exists (d, s3). now apply EvalGet0 with (s0:=s2). }\npose (f := (fun y s' ds1' => EvalGet x y s' ds1')\n           : Var.t -> state -> D.t * state -> Prop).\nassert (Hevalxf : EvalGet_x x f).\n{ apply EvalGet_x0.\n  intros y q0 [d q2] Hf. now firstorder. }\nassert (H : forall t q,\n              q < s -> exists ds1, Wrap_Eval_x x f t q ds1).\n{ induction t as [c | a k IHt].\n  - intros q _. exists (c,q).\n    apply Wrap_Eval_x0; auto.\n    now apply wrapAns.\n  - intros q Hprecq.\n    destruct (Heval a _ Hprecq) as [ [d0' s0'] Heval0'].\n    assert (Hf : f a q (d0',s0')) by (unfold f; auto).\n    assert (Hprecs0' : s0' < s).\n    { apply precEq_prec_state with (s2:=q); auto.\n      unfold f in Hf. now apply precEq_invariant in Hf. }\n    destruct (IHt d0' _ Hprecs0') as [ [d1 s1] Hwrap']; clear IHt.\n    exists (d1,s1). apply Wrap_Eval_x0; auto.\n    eapply wrapQue; eauto. now inversion Hwrap'; subst. }\n destruct (H (rhs x) _ Hprecs0) as [ [d s1] Hwrapx]; clear H.\nassert (Hevalrhs : Eval_rhs x s0 (d,s1))\n  by (apply Eval_rhs0 with (f:=f); auto).\npose (cur := getval s1 x).\npose (new := D.join cur d).\ndestruct (D.eq_dec new cur) as [e | n].\n- assert (Hleq : D.Leq new cur) by now rewrite <- e.\n  exists s1. now apply Solve1 with (d:=d); auto.\n- assert (Hnleq : ~ D.Leq new cur).\n  { contradict n. unfold new. now apply D.LeqAntisym. }\n  pose (s2 := setval x new s1).\n  destruct (extract_work x s2) as [w s3] eqn: Hwork.\n  symmetry in Hwork.\n  assert (Hprecs3 : s3 < s)\n    by (eapply prec_call_SolveAll; eauto).\n  assert (H : forall l q, q < s -> exists s4, SolveAll l q s4).\n  { induction l as [| y ys IHl].\n    - intros q _. exists q. now apply SolveAll0.\n    - intros q Hprecq.\n      destruct (IH _ Hprecq y) as [s3' Hsol'].\n      assert (Hprecs3' : s3' < s).\n      { apply precEq_prec_state with (s2:=q); auto.\n        now apply precEq_invariant in Hsol'. }\n      destruct (IHl _ Hprecs3') as [s4 Hsolall']; clear IHl.\n      exists s4. now eapply SolveAll2; eauto. }\n  destruct (H w _ Hprecs3) as [s4 Hsolall].\n  exists s4. now eapply Solve2; eauto.\nQed.\n\nEnd termination.\n\nEnd algorithm.\n\nEnd SolverRLD.\n\n(* TODO this should go elsewhere actually *)\nModule SolverRLDcomplete (Sys : CSys)\n                         (VSet : SetsTypeOn (Sys.V))\n                         (VMap : MapsTypeOn (Sys.V)).\n\nInclude SolverRLD (Sys)(VSet)(VMap).\n\nSection exactness.\n\nVariable Hpure : forall x, is_pure (F x).\n(*Definition rhs x : Tree Var.t D.t D.t := proj1_sig (Hpure x).*)\n\nDefinition is_local_solution\n             (X X' : VS.t) (sigma : Var.t -> Sys.D.t)\n  := (forall z, VS.In z X -> VS.In z X') /\\\n     (forall z v d,\n        VS.In z X' ->\n        In (v,d) (deps (rhs Hpure z) sigma) ->\n        VS.In v X') /\\\n     (forall z,\n        VS.In z X' ->\n        D.Leq ([[rhs Hpure z]]* sigma) (sigma z)).\n\nDefinition sol_ext X X' sigma (H : is_local_solution X X' sigma)\n  : Var.t -> Sys.D.t\n  := fun z =>\n       match VSetProps.In_dec z X' with\n           | left _ => sigma z\n           | right _ => Sys.D.top\n       end.\n\nImport Defs.\n\nLemma sol_ext_is_solution\n        X X' sigma (H : @is_local_solution X X' sigma) :\n  is_solution (rhs Hpure) (@sol_ext X X' sigma H).\nProof.\ndestruct H as [H [H0 H1] ].\nintros x.\nunfold sol_ext at 2.\ncase (VSetProps.In_dec x X') as [e | n]; auto.\n- rewrite <- (@deps_val_compat _ _ _ _ _ sigma _ eq_refl).\n  + now apply H1.\n  + intros [v d] i.\n    unfold sol_ext; simpl.\n    now case (VSetProps.In_dec v X'); firstorder.\nQed.\n\nEnd exactness.\nEnd SolverRLDcomplete.\n", "meta": {"author": "karbyshev", "repo": "solvers", "sha": "db663eb55f7b75b72801058ad37be9e76220de41", "save_path": "github-repos/coq/karbyshev-solvers", "path": "github-repos/coq/karbyshev-solvers/solvers-db663eb55f7b75b72801058ad37be9e76220de41/RLD.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.26777758680260666}}
{"text": "(*\n  This file showcases the use of packages.\n *)\n\n\nFrom Coq Require Import Utf8.\nSet Warnings \"-ambiguous-paths,-notation-overridden,-notation-incompatible-format\".\nFrom mathcomp Require Import ssrnat ssreflect ssrfun ssrbool ssrnum eqtype choice seq.\nSet Warnings \"ambiguous-paths,notation-overridden,notation-incompatible-format\".\nFrom extructures Require Import ord fset fmap.\nFrom Crypt Require Import RulesStateProb Package Prelude.\nImport PackageNotation.\n\nFrom Equations Require Import Equations.\nRequire Equations.Prop.DepElim.\n\n\nSet Bullet Behavior \"Strict Subproofs\".\nSet Default Goal Selector \"!\".\nSet Primitive Projections.\n\n#[local] Open Scope package_scope.\n\nDefinition I0 : Interface :=\n  [interface val #[3] : 'nat → 'nat].\n\nDefinition I1 : Interface :=\n  [interface\n    val #[0] : 'bool → 'bool ;\n    val #[1] : 'nat → 'unit ;\n    val #[2] : 'unit → 'bool\n  ].\n\nDefinition I2 : Interface :=\n  [interface\n    val #[4] : 'bool × 'bool → 'bool\n  ].\n\nDefinition pempty : package fset0 [interface] [interface] :=\n  [package].\n\nDefinition p0 : package fset0 [interface] I0 :=\n  [package\n    def #[3] (x : 'nat) : 'nat {\n      ret x\n    }\n  ].\n\nDefinition p1 : package fset0 [interface] I1 :=\n  [package\n    def #[0] (z : 'bool) : 'bool {\n      ret z\n    } ;\n    def #[1] (y : 'nat) : 'unit {\n      ret Datatypes.tt\n    } ;\n    def #[2] (u : 'unit) : 'bool {\n      ret false\n    }\n  ].\n\nDefinition foo (x : bool) : code fset0 [interface] bool_choiceType :=\n  {code let u := x in ret u}.\n\nDefinition bar (b : bool) : code fset0 [interface] nat_choiceType :=\n  {code if b then ret 0 else ret 1}.\n\nDefinition p2 : package fset0 [interface] I2 :=\n  [package\n    def #[4] (x : 'bool × 'bool) : 'bool {\n      let '(u,v) := x in ret v\n    }\n  ].\n\nDefinition test₁ :\n  package\n    [fset (chNat; 0)]\n    [interface val #[0] : 'nat → 'nat]\n    [interface\n      val #[1] : 'nat → 'nat ;\n      val #[2] : 'unit → 'unit\n    ]\n  :=\n  [package\n    def #[1] (x : 'nat) : 'nat {\n      getr ('nat; 0) (λ n : nat,\n        opr (0, ('nat, 'nat)) n (λ m,\n          putr ('nat; 0) m (ret m)\n        )\n      )\n    } ;\n    def #[2] (_ : 'unit) : 'unit {\n      putr ('nat; 0) 0 (ret Datatypes.tt)\n    }\n  ].\n\nDefinition sig := {sig #[0] : 'nat → 'nat }.\n\n#[program] Definition test₂ :\n  package\n    [fset ('nat; 0)]\n    [interface val #[0] : 'nat → 'nat ]\n    [interface\n      val #[1] : 'nat → 'nat ;\n      val #[2] : 'unit → 'option ('fin 2) ;\n      val #[3] : {map 'nat → 'nat} → 'option 'nat\n    ]\n  :=\n  [package\n    def #[1] (x : 'nat) : 'nat {\n      n ← get ('nat ; 0) ;;\n      m ← op sig ⋅ n ;;\n      n ← get ('nat ; 0) ;;\n      m ← op sig ⋅ n ;;\n      put ('nat ; 0) := m ;;\n      ret m\n    } ;\n    def #[2] (_ : 'unit) : 'option ('fin 2) {\n      put ('nat ; 0) := 0 ;;\n      ret (Some (gfin 1))\n    } ;\n    def #[3] (m : {map 'nat → 'nat}) : 'option 'nat {\n      ret (getm m 0)\n    }\n  ].\n\n(* Testing the #import notation *)\nDefinition test₃ :\n  package\n    fset0\n    [interface\n      val #[0] : 'nat → 'bool ;\n      val #[1] : 'bool → 'unit\n    ]\n    [interface\n      val #[2] : 'nat → 'nat ;\n      val #[3] : 'bool × 'bool → 'bool\n    ]\n  :=\n  [package\n    def #[2] (n : 'nat) : 'nat {\n      #import {sig #[0] : 'nat → 'bool } as f ;;\n      #import {sig #[1] : 'bool → 'unit } as g ;;\n      b ← f n ;;\n      if b then\n        g false ;;\n        ret 0\n      else ret n\n    } ;\n    def #[3] ('(b₀,b₁) : 'bool × 'bool) : 'bool {\n      ret b₀\n    }\n  ].\n\n(** Information is redundant between the export interface and the package\n    definition, so it can safely be skipped.\n*)\nDefinition test₄ : package fset0 [interface] _ :=\n  [package\n    def #[ 0 ] (n : 'nat) : 'nat {\n      ret (n + n)%N\n    } ;\n    def #[ 1 ] (b : 'bool) : 'nat {\n      if b then ret 0 else ret 13\n    }\n  ].\n\nDefinition ℓ : Location := ('nat ; 0).\n\n#[tactic=notac] Equations? foo : code fset0 [interface] 'nat :=\n  foo := {code\n    n ← get ℓ ;;\n    ret n\n  }.\nProof.\n  ssprove_valid.\nAbort.\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/examples/package_usage_example.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.26777758680260666}}
{"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 invalidate_block_spec0 (addr: Z64) (adt: RData) : option RData :=\n    match addr with\n    | VZ64 _addr =>\n      when adt == barrier_spec  adt;\n      rely is_int64 _addr;\n      when adt == stage2_tlbi_ipa_spec (VZ64 _addr) (VZ64 4096) 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/TableAux/LowSpecs/invalidate_block.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.26774922489378633}}
{"text": "Require 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.\nLocal Open Scope Z. \nFrom tweetnacl20140427\n Require Import tweetNaclBase Salsa20 verif_salsa_base \n      tweetnaclVerifiableC Snuffle spec_salsa \n     verif_crypto_stream_salsa20_xor1. \nOpaque Snuffle.Snuffle.\n\nDefinition Inv cInit mInit bInit k nonce x z Nonce K mcont zcont gv:=\n(EX rounds:nat, EX m:_, EX zbytesR:list byte, EX srbytes:list byte,\n let r64 := (Z.of_nat rounds * 64)%Z in\n let c := offset_val r64 cInit in\n let b := Int64.sub bInit (Int64.repr r64) in\n  (PROP  (0 <= r64 <= Int64.unsigned bInit /\\ null_or_offset mInit r64 m\n          /\\ CONTENT SIGMA K mInit mcont zcont rounds zbytesR srbytes)\n   LOCAL  (lvar _x (Tarray tuchar 64 noattr) x;\n           lvar _z (Tarray tuchar 16 noattr) z; temp _c c; temp _m m;\n           temp _b (Vlong b); temp _k k; gvars gv)\n   SEP (data_at Tsh (Tarray tuchar 16 noattr) (Bl2VL zbytesR) z;\n     data_at_ Tsh (Tarray tuchar 64 noattr) x; Sigma_vector (gv _sigma);\n     data_at Tsh (Tarray tuchar 16 noattr) (SixteenByte2ValList Nonce) nonce;\n     ThirtyTwoByte K k; \n     data_at Tsh (Tarray tuchar  (Z.of_nat rounds * 64) noattr) (Bl2VL srbytes) cInit;\n     data_at_ Tsh (Tarray tuchar (Int64.unsigned bInit - Z.of_nat rounds * 64) noattr) c;\n     message_at mcont mInit))).\n\nDefinition IfPost z x b Nonce K mCont cLen nonce c k m zbytes gv :=\n  PROP ()\n  LOCAL (lvar _x (Tarray tuchar 64 noattr) x;\n   lvar _z (Tarray tuchar 16 noattr) z;\n   temp _k k; gvars gv)\n  SEP (data_at_ Tsh (Tarray tuchar 16 noattr) z;\n      data_at_ Tsh (Tarray tuchar 64 noattr) x; Sigma_vector (gv _sigma);\n      SByte Nonce nonce; ThirtyTwoByte K k; message_at mCont m;\n      (if Int64.eq b Int64.zero \n       then data_at_ Tsh (Tarray tuchar cLen noattr) c\n       else EX COUT:_, !!ContSpec b SIGMA K m mCont zbytes COUT && \n            data_at Tsh (Tarray tuchar cLen noattr) (Bl2VL COUT) c)).\n\nLemma crypto_stream_salsa20_xor_ok: semax_body SalsaVarSpecs SalsaFunSpecs\n      f_crypto_stream_salsa20_tweet_xor\n      crypto_stream_salsa20_xor_spec.\nProof. \nstart_function.\nrename H into MLEN.\n(*assert_PROP (isptr v_z) as isptrZ by entailer!.*)\n\nforward_if (b <> Int64.zero).\n{ forward.\n  change (Int64.unsigned _) with 0.\n  unfold crypto_stream_xor_postsep. \n  rewrite Int64.eq_true. cancel.\n }\n{ forward. entailer!!. }\nIntros. rename H into B.\nassert_PROP (field_compatible (Tarray tuchar (Int64.unsigned b) noattr) [] c) as FC by entailer!.\nfreeze FR1 := - (data_at_ _ _ v_z).\nforward_for_simple_bound 16 (EX i:Z, \n  (PROP  ()\n   LOCAL  (lvar _x (tarray tuchar 64) v_x; lvar _z (tarray tuchar 16) v_z;\n   temp _c c; temp _m m; temp _b (Vlong b); temp _n nonce; temp _k k; gvars gv)\n   SEP  (FRZL FR1; EX l:_, !!(Zlength l + i = 16) && data_at Tsh (tarray tuchar 16) \n          ((Zrepeat (Vint Int.zero) i) ++ l) v_z))).\n{Exists  (default_val (tarray tuchar 16)). simpl app. entailer!!. }\n{ rename H into I. Intros l. rename H into LI16.\n  forward. Exists (sublist 1 (Zlength l) l). entailer!!. list_solve. list_simplify.\n}\nIntros l. destruct l; [clear H | list_solve].\nrewrite app_nil_r.\nthaw FR1.\nfreeze FR2 := - (SByte Nonce _) (data_at _ _ _ v_z).\nunfold SByte.\nforward_for_simple_bound 8 (EX i:Z, \n  (PROP  ()\n   LOCAL  (lvar _x (Tarray tuchar 64 noattr) v_x;\n   lvar _z (Tarray tuchar 16 noattr) v_z; temp _c c; temp _m m;\n   temp _b (Vlong b); temp _n nonce; temp _k k; gvars gv)\n   SEP \n   (FRZL FR2; data_at Tsh (Tarray tuchar 16 noattr)\n        (sublist 0 i (SixteenByte2ValList Nonce) ++\n         (Zrepeat (Vint Int.zero) (16-i))) v_z;\n   data_at Tsh (Tarray tuchar 16 noattr) (SixteenByte2ValList Nonce) nonce))).\n{ entailer!!. }\n{ rename H into I.\n  assert (ZWS: Int.zwordsize = 32) by reflexivity.\n  destruct (SixteenByte2ValList_bytes Nonce) as [NBytes [NBytesL NB]]; rewrite NB.\n  assert (NBytesZL: Zlength NBytes = 16). apply Zlength_length; simpl; lia.\n  destruct (Znth_mapVint (map Int.repr (map Byte.unsigned NBytes)) i) as [v V]. \n    repeat rewrite Zlength_map. rewrite NBytesZL. lia. \n  assert (v = Int.repr (Byte.unsigned (Znth i NBytes))). {\n    rewrite Znth_map in V by list_solve. inv V. list_simplify. \n  }\n  subst v.\n  destruct (Byte.unsigned_range_2 (Znth i NBytes)) as [VBmin VBmax]. \n  specialize Byte_max_unsigned_Int_max_unsigned; intros ByteIntMaxUnsigned.\n  simpl.\n  forward. \n  change (@Znth val Vundef) with (@Znth val _); rewrite V.\n  entailer!!.\n  forward.\n  rewrite NB.\n  entailer!!. \n  list_simplify. subst i0. simpl.\n  rewrite zero_ext8_byte; auto.\n}\ndeadvars!.\n\n(*Verification of loop while (b >=64) ...*)\nrename c into cInit. rename m into mInit. rename b into bInit. thaw FR2.\nset (ZeroQuadByte := (Byte.zero, Byte.zero, Byte.zero, Byte.zero):QuadByte).\ndestruct Nonce as [[[N0 N1] N2] N3].\n  assert (sublist 0 8 (SixteenByte2ValList (N0, N1, N2, N3)) ++\n       Zrepeat (Vint Int.zero) (16 - 8)\n     = (SixteenByte2ValList (((N0, N1), ZeroQuadByte), ZeroQuadByte))).\n  { do 2 rewrite SixteenByte2ValList_char.\n   assert (Zlength (QuadByte2ValList N0) = 4) \n      by (rewrite Zlength_correct, QuadByteValList_length; reflexivity).\n   assert (Zlength (QuadByte2ValList N1) = 4) \n      by (rewrite Zlength_correct, QuadByteValList_length; reflexivity).\n   assert (Zlength (QuadByte2ValList ZeroQuadByte) = 4) \n      by (rewrite Zlength_correct, QuadByteValList_length; reflexivity).\n  rewrite app_assoc.\n  rewrite sublist_app1 by list_solve.\n  rewrite app_assoc.\n  f_equal. list_solve.\n }\n  rewrite H; clear H.\n  assert (I64MAX: Int64.max_unsigned = ltac:(let x := eval compute in Int64.max_unsigned in exact x))\n     by reflexivity.\n  destruct (SixteenByte2ValList_bytes (N0, N1, ZeroQuadByte, ZeroQuadByte)) as [zbytes [Lzbytes ZBytes]].\n  rewrite ZBytes.\nforward_while (Inv cInit mInit bInit k nonce v_x v_z (N0, N1,N2,N3) K mCont zbytes gv).\n{ (*precondition*)\n  Exists O mInit zbytes (@nil byte).\n  unfold Bl2VL, tarray.\n  rewrite Tarray_0_emp_iff \n   by (pose proof (Int64.unsigned_range bInit); auto with field_compatible).\n  entailer!. \n  2:cancel. (* why didn't the entailer! do this? *)\n  split; [split|].\n  + destruct mInit; simpl in *; try contradiction. subst i; auto.\n           rewrite Ptrofs.add_zero; trivial. \n  + constructor.\n  + simpl. rewrite Int64.sub_zero_l; auto.\n}\n{ entailer!!. }\n{ remember (Z.of_nat rounds * 64)%Z as r64.\n  destruct (zle (r64 + 64) (Int64.unsigned bInit)).\n  2:{ exfalso. assert (X: 64 > Int64.unsigned bInit - r64) by lia. clear g.\n           pose proof (Int64.unsigned_range_2 bInit).\n           unfold Int64.sub in HRE. rewrite (Int64.unsigned_repr r64) in HRE by lia.\n           rewrite Int64.unsigned_repr in HRE; lia.\n  }\n  destruct H as [R64old [M CONT]]. rename l into R64next.\n   \n  destruct (SixteenByte2ValList_exists zbytesR) as [d D].\n  { apply CONTCONT in CONT. rewrite <- CONT.\n    eapply Zlength_ZCont. rewrite Zlength_correct, Lzbytes. reflexivity. }\n\n  forward_call (gv _sigma, k, v_z, v_x, (d, SIGMA, K)). \n  { unfold CoreInSEP, SByte, Sigma_vector, tarray.\n    rewrite D; unfold Bl2VL. cancel. }\nIntros snuff. rename H into Snuff.\n\ndestruct (QuadChunks2ValList_bytes (map littleendian_invert snuff)) as [sr_bytes [SRBL SNR]].\nassert (SRL: Zlength sr_bytes = 64). {\n  rewrite map_length, (Snuffle20_length _ _ Snuff) in SRBL.\n  rewrite Zlength_correct, SRBL. reflexivity.\n  apply prepare_data_length.\n}\nfreeze [0;2;3] FR3.\nremember (offset_val r64 cInit) as c.\n\nassert(INT64SUB: Int64.sub bInit (Int64.repr (r64 + 64)) =\n           Int64.sub (Int64.sub bInit (Int64.repr r64)) (Int64.repr 64)).\n{ clear - R64next R64old HRE Heqr64 I64MAX.\n  destruct (Int64.unsigned_range_2 bInit).\n  unfold Int64.sub.\n  repeat rewrite Int64.unsigned_repr; try lia. f_equal; lia.\n} \n\nrewrite SNR.\nforward_seq. \napply (loop1 Espec (FRZL FR3) v_x v_z c mInit (Vlong (Int64.sub bInit (Int64.repr r64))) k m sr_bytes mCont).\n    eassumption.\n    clear - SRL R64next R64old HRE Heqr64 MLEN; lia. lia.\n\n(*continuation after the FOR(i,64) loop*)\nOpaque prepare_data.\ndeadvars!.\nIntros xorlist. rename H into XOR.\nrewrite sublist_same in XOR; try lia.\nforward.\nthaw FR3. unfold CoreInSEP. repeat flatten_sepcon_in_SEP.\nfreeze [1;2;3;4;5;6;7] FR4.\nunfold SByte. \nforward_seq. rewrite D.\n  apply (For_i_8_16_loop Espec (FRZL FR4) v_x v_z c m \n           (Vlong (Int64.sub bInit (Int64.repr r64))) k zbytesR gv).\nfreeze [0;1] FR5.\nforward.\nforward.\nrewrite Heqc. simpl.\n\nforward_if (EX m:_,\n  (PROP  (null_or_offset mInit (r64+64) m)\n   LOCAL \n   (temp _c\n      (force_val\n         (sem_add_ptr_int tuchar Signed (offset_val r64 cInit)\n            (Vint (Int.repr 64))));\n   temp _b\n     (Vlong\n        (Int64.sub (Int64.sub bInit (Int64.repr r64))\n           (Int64.repr (Int.signed (Int.repr 64)))));\n   lvar _x (Tarray tuchar 64 noattr) v_x; lvar _z (Tarray tuchar 16 noattr) v_z;\n   temp _m m; temp _k k; gvars gv)  SEP  (FRZL FR5))).\n{  clear H v. apply denote_tc_test_eq_split; auto with valid_pointer.\n   destruct mInit; simpl in M; try contradiction.\n   destruct M as [II M]; rewrite M in *; auto with valid_pointer.\n   rewrite M in *.\n     thaw FR5; thaw FR4.\n  assert (message_at mCont (Vptr b i)\n      |-- valid_pointer\n            (Vptr b (Ptrofs.add i (Ptrofs.repr (Z.of_nat rounds * 64))))). {\n        unfold message_at. eapply derives_trans. apply data_at_memory_block.\n        eapply derives_trans. apply memory_block_valid_pointer. simpl.\n        3: apply derives_refl'. 3: reflexivity. rep_lia.\n        apply top_share_nonidentity.\n   }\n  auto 50 with valid_pointer.\n}\n{ forward.\n  Exists (force_val (sem_add_ptr_int tuchar Signed m (Vint (Int.repr 64)))).\n  entailer!!.\n  destruct mInit; simpl in M; try contradiction.\n  destruct M as [II M]; rewrite M in *. contradiction. \n  rewrite M in *.  simpl. rewrite Ptrofs.add_assoc, ptrofs_add_repr. trivial. }\n{ forward. Exists m. entailer!!. destruct mInit; simpl in M; try contradiction.\n  simpl. apply M. inv M. }\nintros.\nthaw FR5. thaw FR4.\nIntros x.\ndestruct cInit; try solve [destruct FC as [? _]; contradiction].\nExists (S rounds, x, snd (ZZ (ZCont rounds zbytes) 8), srbytes ++ xorlist).\nunfold fst, snd.\nrewrite  Nat2Z.inj_succ, <- Zmult_succ_l_reverse.\nassert_PROP (field_compatible0\n     (Tarray tuchar (Int64.unsigned bInit - r64) noattr) \n      (SUB 64) (Vptr b (Ptrofs.add i (Ptrofs.repr r64))))\n   as FC2 by (entailer!; auto with field_compatible).\nentailer!!.\nrewrite INT64SUB.\nsplit; auto.\nspecialize (CONTCONT _ _ _ _ _ _ _ _ CONT); intros; subst zbytesR.\n assert (Hx := CONT_succ SIGMA K mInit mCont zbytes rounds _ _ CONT _ D\n    _ _ _ Snuff SNR XOR).\n unfold snd in Hx; exact Hx. (* why is this necessary? *)\n rewrite (CONTCONT _ _ _ _ _ _ _ _ CONT). \n  unfold SByte, Sigma_vector.\n  cancel.\n\n  assert (Zlength xorlist = 64). {\n     unfold bxorlist in XOR; destruct (combinelist_Zlength _ _ _ _ _ XOR).\n     rewrite H0. unfold bytes_at. \n    destruct mInit; list_solve.\n  }\n  assert (Zlength (Bl2VL xorlist) = 64) by (rewrite Zlength_Bl2VL; lia).\n  remember (Z.of_nat rounds * 64)%Z as r64.\n  apply CONT_Zlength in CONT.\n\n  assert (field_compatible (Tarray tuchar (Z.of_nat rounds * 64 + 64) noattr) [] (Vptr b i)).\n  { eapply field_compatible_array_smaller0. apply FC. lia. }\n\n  erewrite (split2_data_at_Tarray_tuchar _ (Int64.unsigned bInit - r64) (Zlength (Bl2VL xorlist)))\n    by list_solve.\n  autorewrite with sublist. rewrite H1.\n  rewrite field_address0_clarify by (unfold field_address0; simpl; rewrite if_true; simpl; trivial).\n  simpl.\n  assert (II:Int64.unsigned bInit - (Z.of_nat rounds * 64 + 64) = Int64.unsigned bInit - (Z.of_nat rounds * 64) - 64) by  lia.\n  rewrite Heqr64.\n  rewrite II, Ptrofs.add_assoc, ptrofs_add_repr. cancel.\n\n  unfold Bl2VL. repeat rewrite map_app.\n  erewrite (split2_data_at_Tarray_tuchar Tsh (Z.of_nat rounds * 64 + 64) (Z.of_nat rounds * 64))\n      by list_solve.\n  rewrite sublist_app1       by list_solve.\n  rewrite sublist_same by list_solve.\n  replace (Z.of_nat rounds * 64 + 64 - Z.of_nat rounds * 64) with 64 by lia.\n  rewrite sublist_app2       by list_solve.\n  rewrite sublist_same by list_solve.\n  rewrite field_address0_clarify; simpl. rewrite Zplus_0_l, Z.mul_1_l; trivial.\n  unfold field_address0; simpl. rewrite if_true; simpl; trivial.\n  auto with field_compatible.\n}\n\n(*continuation if (b) {...} *)\nremember (Z.of_nat rounds * 64)%Z as r64.\n assert (R64b: r64+64 > Int64.unsigned bInit).\n           destruct (Int64.unsigned_range_2 bInit) as [X1 X2].\n           unfold Int64.sub in HRE. rewrite (Int64.unsigned_repr r64) in HRE by lia.\n           rewrite Int64.unsigned_repr in HRE; lia.\ndestruct H as [R64a [M CONT]]. \n  assert (RR: Int64.unsigned (Int64.sub bInit (Int64.repr r64)) = Int64.unsigned bInit - r64).\n  { destruct (Int64.unsigned_range_2 bInit).\n    unfold Int64.sub.\n    repeat rewrite Int64.unsigned_repr; try lia. }\nforward_if (IfPost v_z v_x bInit (N0, N1, N2, N3) K mCont (Int64.unsigned bInit) nonce cInit k mInit zbytes gv).\n{ rename H into BR.\n  destruct (SixteenByte2ValList_exists zbytesR) as [d D].\n  { apply CONTCONT in CONT. rewrite <- CONT.\n    eapply Zlength_ZCont. rewrite Zlength_correct, Lzbytes. reflexivity. }\n  forward_call (gv _sigma, k, v_z, v_x, (d, SIGMA, K)). \n  { unfold CoreInSEP, SByte, Sigma_vector, tarray.\n    unfold Bl2VL; rewrite D. cancel. }\n  Intros snuff. rename H into Snuff.\n  destruct (QuadChunks2ValList_bytes (map littleendian_invert snuff)) as [sr_bytes [SRBL SNR]].\n  assert (Zlength sr_bytes = 64).\n    rewrite map_length, (Snuffle20_length _ _ Snuff) in SRBL.\n    rewrite Zlength_correct, SRBL. reflexivity.\n    apply prepare_data_length.\n  rename H into SRL.\n  freeze [0;2;3] FR1.\n  remember (offset_val r64 cInit) as c.\n  assert (BB: Int64.unsigned (Int64.sub bInit (Int64.repr r64)) < Int.max_unsigned).\n     rep_lia. \n  rewrite SNR, <- RR.\n  eapply semax_post_flipped'.\n  eapply (loop2 Espec (FRZL FR1) v_x v_z c mInit); try eassumption; try lia.\n  unfold IfPost.\n  Intros l.\n  unfold typed_true in BR. inversion BR; clear BR.\n  entailer!!.\n   rename H1 into H8.\n  rewrite RR in *. eapply negb_true_iff in H8. \n  unfold Int64.eq in H8. rewrite RR in H8. unfold Int64.zero in H8.\n  rewrite Int64.unsigned_repr in H8. 2: lia.\n  if_tac in H8. inv H8. clear H8. thaw FR1.\n  unfold CoreInSEP.\n  rewrite Int64.eq_false. 2: assumption.\n  Exists (srbytes ++ l). unfold SByte.\n  specialize (CONT_Zlength _ _ _ _ _ _ _ _ CONT); intros CZ.\n  entailer!. \n  + red.\n    assert (R: rounds = Z.to_nat (Int64.unsigned bInit / 64)).\n    { remember (Int64.unsigned bInit) as p.\n      erewrite <- Z.div_unique with (q:= Z.of_nat rounds).\n       rewrite Nat2Z.id. trivial.\n      instantiate (1:= p- 64 * Z.of_nat rounds). 2: lia.\n      left. lia. } \n    rewrite <- R.\n    assert (Arith1: (Int64.unsigned bInit / 64 * 64 = Z.of_nat rounds * 64)%Z).\n        rewrite R; rewrite Z2Nat.id; trivial. \n        apply Z_div_pos; lia.\n    assert (Arith2: Int64.unsigned bInit mod 64 = Int64.unsigned bInit - Z.of_nat rounds * 64).\n    { symmetry; eapply Zmod_unique. lia. instantiate (1:=Z.of_nat rounds); lia. }\n    rewrite Arith1, Arith2, (CONTCONT _ _ _ _ _ _ _ _ CONT).\n    rewrite if_false.\n    - exists zbytesR, srbytes, d, snuff, sr_bytes, l. \n      intuition.\n    - trivial.\n  + erewrite (split2_data_at_Tarray_tuchar _ (Int64.unsigned bInit) (Z.of_nat rounds * 64)).\n    2: lia. \n    2: rewrite Zlength_Bl2VL in *; rewrite Zlength_app. 2: lia. \n    rewrite Zlength_Bl2VL in *; unfold Bl2VL in *.\n    repeat rewrite map_app. autorewrite with sublist.\n    unfold Sigma_vector. cancel. \n    rewrite field_address0_clarify; simpl.\n    rewrite Zplus_0_l, Z.mul_1_l; trivial.\n    unfold field_address0; simpl.\n    rewrite Zplus_0_l, Z.mul_1_l, if_true; trivial. \n    apply field_compatible_isptr in H13. \n    destruct cInit; simpl in *; try contradiction; trivial.\n    auto with field_compatible.\n}\n{ forward.\n  hnf in H. inversion H; clear H. rewrite RR in *. eapply negb_false_iff in H1. \n  unfold Int64.eq in H1. rewrite RR in H1. unfold Int64.zero in H1.\n  rewrite Int64.unsigned_repr in H1 by lia.\n  if_tac in H1. 2: inv H1. clear H1. \n  assert (XX: Int64.unsigned bInit = r64) by lia.\n  rewrite XX in *. clear H RR.\n  unfold IfPost, CoreInSEP.\n  entailer!.\n  rewrite Zminus_diag in *; rewrite Tarray_0_emp_iff_; try assumption.\n  rewrite Int64.eq_false. 2: assumption.\n  unfold SByte. simpl. cancel.\n  Exists srbytes. apply andp_right; trivial.\n  apply prop_right. red. rewrite XX, Heqr64. \n  rewrite if_true. \n  + exists zbytesR. rewrite Z_div_mult_full, Nat2Z.id. assumption. lia.\n  + symmetry. eapply Zdiv.Zmod_unique. lia.\n    rewrite Z.mul_comm, Zplus_0_r. reflexivity.\n}\nunfold IfPost. \nforward.\nunfold crypto_stream_xor_postsep.\nunfold tarray; entailer!!.\ndestruct (Int64.eq bInit Int64.zero). trivial.\nIntros l. Exists l. entailer!!.\nexists zbytes. split; assumption.\nall: fail.  (* make sure we're really done *)\nAdmitted.  (* Qed blows up *)\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/tweetnacl20140427/verif_crypto_stream_salsa20_xor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.26774922489378633}}
{"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 Hoare.\nRequire Import STB KnotHeader.\nRequire Import KnotMainImp KnotMain0 KnotMain1 KnotImp Knot0 Knot1 Mem0 Mem1.\nRequire Import KnotMainImp0proof KnotImp0proof KnotMain01proof Knot01proof Mem01proof.\nRequire Import ProofMode.\n\nRequire Import Invariant Weakening.\n\nSet Implicit Arguments.\n\n\n\n\nSection PROOF.\n\n  Let Σ: GRA.t := GRA.of_list [invRA; knotRA; memRA].\n  Local Existing Instance Σ.\n\n  Let invRA_inG: @GRA.inG invRA Σ.\n  Proof. exists 0. ss. Defined.\n  Local Existing Instance invRA_inG.\n\n  Let knotRA_inG: @GRA.inG knotRA Σ.\n  Proof. exists 1. ss. Defined.\n  Local Existing Instance knotRA_inG.\n\n  Let memRA_inG: @GRA.inG memRA Σ.\n  Proof. exists 2. ss. Defined.\n  Local Existing Instance memRA_inG.\n\n  Let RecStb: Sk.t -> gname -> option fspec :=\n    fun sk => to_stb KnotRecStb.\n  Hint Unfold RecStb: stb.\n\n  Let FunStb: Sk.t -> gname -> option fspec :=\n    fun sk => to_stb (MainFunStb RecStb sk).\n  Hint Unfold FunStb: stb.\n\n  Let smds := [SMain RecStb; SKnot RecStb FunStb; SMem (fun _ => true)].\n  Let GlobalStb := fun sk => to_stb (SMod.get_stb smds sk).\n  Hint Unfold GlobalStb: stb.\n\n  Definition KnotAllImp: list Mod.t := [KnotMainImp.KnotMain; KnotImp.Knot; Mem0.Mem (fun _ => false)].\n  Definition KnotAll0: list Mod.t := [KnotMain0.Main; Knot0.Knot; Mem0.Mem (fun _ => false)].\n  Definition KnotAll1: list Mod.t := List.map (SMod.to_tgt GlobalStb) smds.\n  Definition KnotAll2: list Mod.t := List.map SMod.to_src smds.\n\n  Lemma KnotAll01_correct:\n    refines2 KnotAll0 KnotAll1.\n  Proof.\n    eapply refines2_cons.\n    { eapply KnotMain01proof.correct with (RecStb:=RecStb) (FunStb:=FunStb) (GlobalStb:=GlobalStb).\n      { stb_incl_tac. }\n      { ii. econs; ss. refl. }\n      { ii. econs; ss. refl. }\n    }\n    eapply refines2_cons.\n    { eapply Knot01proof.correct with (RecStb:=RecStb) (FunStb:=FunStb) (GlobalStb:=GlobalStb).\n      + stb_incl_tac.\n      + stb_incl_tac.\n      + stb_incl_tac; ors_tac.\n    }\n    etrans.\n    { eapply Mem01proof.correct. }\n    { eapply Weakening.adequacy_weaken. ss. }\n  Qed.\n\n  Lemma KnotAll12_correct:\n    refines_closed (Mod.add_list KnotAll1) (Mod.add_list KnotAll2).\n  Proof.\n    eapply adequacy_type.\n    { instantiate (1:=GRA.embed inv_token ⋅ GRA.embed (Auth.white (Some None: Excl.t (option (nat -> nat))): knotRA)).\n      g_wf_tac.\n      { Local Transparent Sk.load_skenv _points_to string_dec.\n        ur. unfold var_points_to, initial_mem_mr. ss. uo. split.\n        2: { ur. i. ur. i. ur. des_ifs. }\n        { repeat rewrite URA.unit_id. ur. eexists ε.\n          repeat rewrite URA.unit_id. extensionality k. extensionality n.\n          unfold sumbool_to_bool, andb. des_ifs.\n          { ss. clarify. }\n          { ss. clarify. exfalso. lia. }\n          { repeat (destruct k; ss). }\n        }\n      }\n      { unfold knot_full. ur. splits; auto.\n        { rewrite URA.unit_id. refl. }\n        { ur. ss. }\n      }\n      { ur. ss. }\n    }\n    { i. ss. clarify. ss. exists id. splits; auto.\n      { iIntros \"[H0 H1]\". iFrame. iSplits; ss. }\n      { i. iPureIntro. i. des; auto. }\n    }\n  Qed.\n\n  Theorem Knot_correct:\n    refines_closed (Mod.add_list KnotAllImp) (Mod.add_list KnotAll2).\n  Proof.\n    transitivity (Mod.add_list KnotAll0).\n    { eapply refines_close. eapply refines2_pairwise. econs; simpl.\n      { eapply KnotMainImp0proof.correct. }\n      econs; simpl.\n      { eapply KnotImp0proof.correct. }\n      econs; ss.\n    }\n    etrans.\n    { eapply refines_close. eapply KnotAll01_correct. }\n    { eapply KnotAll12_correct. }\n  Qed.\n\nEnd PROOF.\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/KnotAll.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2677492248937863}}
{"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(** * algoTrace\n\nPierre Letouzey & Laurent Thery\n*)\n\nFrom Stalmarck Require Export trace.\nFrom Stalmarck Require Export algoDotriplet.\nFrom Stalmarck Require Export interImplement2.\nFrom Stalmarck Require Import makeTriplet.\n\n(** Append inside a triplet *)\nDefinition appL (L : list rZ) (d : mbD) : mbD :=\n  match d with\n  | triple a b l => triple _ _ _ a b (appendRz L l)\n  end.\n\n(** To make Coq run faster *)\nOpaque addEqMem.\nOpaque doTripletF.\nOpaque interMem.\n\n(** Evaluation of a dotriplet trace *)\nFixpoint evalTraceF (T : Trace) : rArray vM -> mbD :=\n  fun Ar =>\n  match T with\n  | emptyTrace => triple _ _ _ Ar false nil\n  | tripletTrace t =>\n      match doTripletF Ar t with\n      | None => triple _ _ _ Ar false nil\n      | Some T => T\n      end\n  | seqTrace T1 T2 =>\n      match evalTraceF T1 Ar with\n      | triple Ar' true L' => triple _ _ _ Ar' true L'\n      | triple Ar' false L' => appL L' (evalTraceF T2 Ar')\n      end\n  | dilemmaTrace a b T1 T2 =>\n      match addEqMem Ar a b with\n      | triple Ar1 true L1 =>\n          match addEqMem Ar a (rZComp b) with\n          | triple Ar2 true L2 => triple _ _ _ Ar true nil\n          | triple Ar2 false L2 => appL L2 (evalTraceF T2 Ar2)\n          end\n      | triple Ar1 false L1 =>\n          match addEqMem Ar a (rZComp b) with\n          | triple Ar2 true L2 => appL L1 (evalTraceF T1 Ar1)\n          | triple Ar2 false L2 =>\n              match evalTraceF T1 Ar1 with\n              | triple Ar1' true L1' => appL L2 (evalTraceF T2 Ar2)\n              | triple Ar1' false L1' =>\n                  match evalTraceF T2 Ar2 with\n                  | triple Ar2' true L2' =>\n                      triple _ _ _ Ar1' false (appendRz L1 L1')\n                  | triple Ar2' false L2' =>\n                      match\n                        interMem Ar1' Ar2' Ar (appendRz L1 L1')\n                          (appendRz L2 L2')\n                      with\n                      | (Ar', L') => triple _ _ _ Ar' false L'\n                      end\n                  end\n              end\n          end\n      end\n  end.\n\nTheorem TraceCorrect :\n forall (Ar : rArray vM) (T : Trace) (LL : list triplet),\n TraceInList T LL ->\n forall S : State,\n wellFormedArray Ar ->\n rArrayState Ar S ->\n match evalTraceF T Ar with\n | triple Ar' false L =>\n     wellFormedArray Ar' /\\\n     (exists S' : State, stalmarckP S LL S' /\\ rArrayState Ar' S') /\\\n     OlistRz L /\\\n     (forall e : rNat,\n      ~ InRz (rZPlus e) L -> rArrayGet _ Ar' e = rArrayGet _ Ar e)\n | triple Ar' true L =>\n     exists S' : State, stalmarckP S LL S' /\\ contradictory S'\n end.\nProof.\nintros Ar T; generalize Ar; clear Ar; elim T; simpl in |- *.\nintros Ar LL H' S H'0 H'1; repeat (split; auto with stalmarck).\nexists S; split; auto with stalmarck.\nred in |- *; apply OlistNil; auto with stalmarck.\nintros t Ar LL H' S H'0 H'1.\ngeneralize (doTripletFCorrect Ar t S H'0 H'1).\ncase (doTripletF Ar t).\nintros x; case x; auto with stalmarck.\nintros Ar' b' L'; case b'.\nintros H'3; Elimc H'3; intros S' E; Elimc E; intros H'3 H'4.\nexists S'; split; auto with stalmarck.\napply stalmarckPref; auto with stalmarck.\napply doTripletsTrans with (S2 := S') (t := t); auto with stalmarck.\nintros H'3; Elimc H'3; intros H'3 H'4; Elimc H'4; intros H'4 H'5; Elimc H'5;\n intros H'5 H'6.\nElimc H'4; intros S' E; Elimc E; intros H'4 H'7.\nrepeat (split; auto with stalmarck).\nexists S'; split; auto with stalmarck.\napply stalmarckTrans with (S2 := S'); auto with stalmarck.\napply stalmarckPref; auto with stalmarck.\napply doTripletsTrans with (S2 := S') (t := t); auto with stalmarck.\nintros H'2; repeat (split; auto with stalmarck).\nexists S; split; auto with stalmarck.\nred in |- *; apply OlistNil; auto with stalmarck.\nintros t H' t0 H'0 Ar LL H'1 S H'2 H'3.\nelim H'1; intros H'4 H'5; clear H'1.\ngeneralize (H' Ar LL H'4 S H'2 H'3).\ncase (evalTraceF t Ar).\nintros Ar'' b'' L''; case b''; simpl in |- *; auto with stalmarck.\nintros H'1; elim H'1; intros H'6 H'7; elim H'7; intros H'8 H'9; elim H'9;\n intros H'10 H'11; clear H'9 H'7 H'1.\nelim H'8; intros S' E; elim E; intros H'1 H'7; clear E H'8.\ngeneralize (H'0 Ar'' LL H'5 S' H'6 H'7).\ncase (evalTraceF t0 Ar''); auto with stalmarck.\nintros Ar''' b''' L'''; case b'''; simpl in |- *; auto with stalmarck.\nintros H'8; elim H'8; intros S'0 E; elim E; intros H'9 H'12; clear E H'8.\nexists S'0; split; auto with stalmarck.\napply stalmarckTrans with (S2 := S'); auto with stalmarck.\nintros H'8; elim H'8; intros H'9 H'12; elim H'12; intros H'13 H'14; elim H'14;\n intros H'15 H'16; clear H'14 H'12 H'8.\nrepeat (split; auto with stalmarck).\nelim H'13; intros S'0 E; elim E; intros H'8 H'12; clear E H'13.\nexists S'0; split; auto with stalmarck.\napply stalmarckTrans with (S2 := S'); auto with stalmarck.\nunfold appendRz in |- *; red in |- *; apply appendfOlist; auto with stalmarck.\ntry exact rZltEqComp.\nintros e H'14.\nrewrite H'16.\napply H'11; auto with stalmarck.\nContradict H'14; auto with stalmarck.\ncut (InclEq _ eqRz L'' (appendf _ rZlt eqRz rZltEDec L'' L''')).\nintros H'8; inversion H'8; red in |- *; auto with stalmarck.\napply appendfInclEq1; auto with stalmarck.\nContradict H'14; auto with stalmarck.\ncut (InclEq _ eqRz L''' (appendf _ rZlt eqRz rZltEDec L'' L''')).\nintros H'8; inversion H'8; red in |- *; auto with stalmarck.\napply appendfInclEq2; auto with stalmarck.\nintros a b t H' t0 H'0 Ar LL H'1 S H'2 H'3.\ngeneralize (addEqMemCorrect Ar a b S H'2 H'3).\ncase (addEqMem Ar a b).\nintros Ar1 b1 L1; case b1.\nintros H'4.\ngeneralize (addEqMemCorrect Ar a (rZComp b) S H'2 H'3); auto with stalmarck.\ncase (addEqMem Ar a (rZComp b)); auto with stalmarck.\nintros Ar2 b2 L2; case b2.\nintros H'5; exists S; split; auto with stalmarck.\nred in |- *.\nexists a.\napply eqStateRzTrans with (b := rZComp (rZComp b)); auto with stalmarck.\napply eqStateRzInv; auto with stalmarck.\napply eqStateRzSym; auto with stalmarck.\nintros H'5; Elimc H'5; intros H'5 H'6; Elimc H'6; intros H'6 H'7; Elimc H'7;\n intros H'7 H'8.\nElimc H'1; intros H'1 H'9.\ngeneralize (H'0 Ar2 LL H'9 _ H'5 H'6).\ncase (evalTraceF t0 Ar2); auto with stalmarck.\nintros Ar2' b2' L2'; case b2'; simpl in |- *; auto with stalmarck.\nintros H'10; Elimc H'10; intros S' E; Elimc E; intros H'10 H'11.\nexists S'; split; auto with stalmarck.\napply stalmarckTrans with (S2 := S'); auto with stalmarck.\napply\n stalmarckPSplit with (a := a) (b := b) (S2 := addEq (a, b) S) (S3 := S');\n auto with stalmarck.\nred in |- *; split; auto with stalmarck.\nred in |- *.\nintros i j H'12.\napply interMemEqStateRz; auto with stalmarck.\ncase H'4.\nintros x H'13.\napply eqStateRzContr with (a := x); auto with stalmarck.\nintros H'10; Elimc H'10; intros H'10 H'11; Elimc H'11; intros H'11 H'12;\n Elimc H'12; intros H'12 H'13.\nElimc H'11; intros S' E; Elimc E; intros H'11 H'14.\nrepeat (split; auto with stalmarck).\nexists S'; split; auto with stalmarck.\napply\n stalmarckPSplit with (a := a) (b := b) (S2 := addEq (a, b) S) (S3 := S');\n auto with stalmarck.\nred in |- *; split; auto with stalmarck.\nred in |- *.\nintros i j H'15.\napply interMemEqStateRz; auto with stalmarck.\ncase H'4.\nintros x H'16.\napply eqStateRzContr with (a := x); auto with stalmarck.\nunfold appendRz in |- *; red in |- *; apply appendfOlist; auto with stalmarck.\ntry exact rZltEqComp.\nintros e H'15.\nrewrite H'13.\napply H'8; auto with stalmarck.\nContradict H'15; auto with stalmarck.\ncut (InclEq _ eqRz L2 (appendf _ rZlt eqRz rZltEDec L2 L2')).\nintros H'16; inversion H'16; red in |- *; auto with stalmarck.\napply appendfInclEq1; auto with stalmarck.\nContradict H'15; auto with stalmarck.\ncut (InclEq _ eqRz L2' (appendf _ rZlt eqRz rZltEDec L2 L2')).\nintros H'16; inversion H'16; red in |- *; auto with stalmarck.\napply appendfInclEq2; auto with stalmarck.\nintros H'4; Elimc H'4; intros H'4 H'5; Elimc H'5; intros H'5 H'6; Elimc H'6;\n intros H'6 H'7.\nElimc H'1; intros H'1 H'8.\ngeneralize (addEqMemCorrect Ar a (rZComp b) S H'2 H'3); auto with stalmarck.\ncase (addEqMem Ar a (rZComp b)); auto with stalmarck.\nintros Ar2 b2 L2; case b2.\nintros H'9.\ngeneralize (H' Ar1 LL H'1 _ H'4 H'5).\ncase (evalTraceF t Ar1).\nintros Ar1' b1' L1'; case b1'; simpl in |- *; auto with stalmarck.\nintros H'10; Elimc H'10; intros S' E; Elimc E; intros H'10 H'11.\nexists S'; split; auto with stalmarck.\napply\n stalmarckPSplit\n  with (a := a) (b := b) (S2 := S') (S3 := addEq (a, rZComp b) S); \n auto with stalmarck.\nred in |- *; split; auto with stalmarck; auto with stalmarck.\nred in |- *.\nintros i j H'12.\napply interMemEqStateRz; auto with stalmarck.\ncase H'9.\nintros x H'13.\napply eqStateRzContr with (a := x); auto with stalmarck.\nintros H'10; Elimc H'10; intros H'10 H'11; Elimc H'11; intros H'11 H'12;\n Elimc H'12; intros H'12 H'13.\nrepeat (split; auto with stalmarck).\nElimc H'11; intros S' E; Elimc E; intros H'11 H'14.\nexists S'; split; auto with stalmarck.\napply\n stalmarckPSplit\n  with (a := a) (b := b) (S2 := S') (S3 := addEq (a, rZComp b) S); \n auto with stalmarck.\nred in |- *; split; auto with stalmarck; auto with stalmarck.\nred in |- *.\nintros i j H'15.\napply interMemEqStateRz; auto with stalmarck.\ncase H'9.\nintros x H'16.\napply eqStateRzContr with (a := x); auto with stalmarck.\nunfold appendRz in |- *; red in |- *; apply appendfOlist; auto with stalmarck.\ntry exact rZltEqComp.\nintros e H'14.\nrewrite H'13.\napply H'7; auto with stalmarck.\nContradict H'14; auto with stalmarck.\ncut (InclEq _ eqRz L1 (appendf _ rZlt eqRz rZltEDec L1 L1')).\nintros H'15; inversion H'15; red in |- *; auto with stalmarck.\napply appendfInclEq1; auto with stalmarck.\nContradict H'14; auto with stalmarck.\ncut (InclEq _ eqRz L1' (appendf _ rZlt eqRz rZltEDec L1 L1')).\nintros H'15; inversion H'15; red in |- *; auto with stalmarck.\napply appendfInclEq2; auto with stalmarck.\nintros H'9; Elimc H'9; intros H'9 H'10; Elimc H'10; intros H'10 H'11;\n Elimc H'11; intros H'11 H'12.\ngeneralize (H' Ar1 LL H'1 _ H'4 H'5).\ncase (evalTraceF t Ar1).\nintros Ar1' b1' L1'; case b1'; simpl in |- *; auto with stalmarck.\nintros H'13; Elimc H'13; intros S' E; Elimc E; intros H'13 H'14.\ngeneralize (H'0 Ar2 LL H'8 _ H'9 H'10).\ncase (evalTraceF t0 Ar2).\nintros Ar2' b2' L2'; case b2'; simpl in |- *; auto with stalmarck.\nintros H'15; Elimc H'15; intros S'0 E; Elimc E; intros H'15 H'16.\nexists S'; split; auto with stalmarck.\napply stalmarckPSplit with (a := a) (b := b) (S2 := S') (S3 := S'0); auto with stalmarck.\nsplit; auto with stalmarck.\nred in |- *.\nintros i j H'17.\napply interMemEqStateRz; auto with stalmarck.\ncase H'16.\nintros x H'18.\napply eqStateRzContr with (a := x); auto with stalmarck.\nintros H'15; Elimc H'15; intros H'15 H'16; Elimc H'16; intros H'16 H'17;\n Elimc H'17; intros H'17 H'18.\nElimc H'16; intros S'0 E; Elimc E; intros H'16 H'19.\nrepeat (split; auto with stalmarck).\nexists S'0; split; auto with stalmarck.\napply stalmarckPSplit with (a := a) (b := b) (S2 := S') (S3 := S'0); auto with stalmarck.\nsplit; auto with stalmarck.\nred in |- *.\nintros i j H'20.\napply interMemEqStateRz; auto with stalmarck.\ncase H'14.\nintros x H'21.\napply eqStateRzContr with (a := x); auto with stalmarck.\nunfold appendRz in |- *; red in |- *; apply appendfOlist; auto with stalmarck.\ntry exact rZltEqComp.\nintros e H'20.\nrewrite H'18.\napply H'12; auto with stalmarck.\nContradict H'20; auto with stalmarck.\ncut (InclEq _ eqRz L2 (appendf _ rZlt eqRz rZltEDec L2 L2')).\nintros H'21; inversion H'21; red in |- *; auto with stalmarck.\napply appendfInclEq1; auto with stalmarck.\nContradict H'20; auto with stalmarck.\ncut (InclEq _ eqRz L2' (appendf _ rZlt eqRz rZltEDec L2 L2')).\nintros H'21; inversion H'21; red in |- *; auto with stalmarck.\napply appendfInclEq2; auto with stalmarck.\nintros H'13; Elimc H'13; intros H'13 H'14; Elimc H'14; intros H'14 H'15;\n Elimc H'15; intros H'15 H'16.\ncut (OlistRz (appendRz L1 L1')); [ intros O1 | idtac ].\n2: unfold appendRz in |- *; red in |- *; apply appendfOlist; auto with stalmarck.\n2: try exact rZltEqComp.\ncut\n (forall e : rNat,\n  ~ InRz (rZPlus e) (appendRz L1 L1') ->\n  rArrayGet vM Ar1' e = rArrayGet vM Ar e); [ intros E1 | idtac ].\n2: intros e H'17.\n2: rewrite H'16; auto with stalmarck.\n2: apply H'7; auto with stalmarck.\n2: Contradict H'17; auto with stalmarck.\n2: cut (InclEq _ eqRz L1 (appendf _ rZlt eqRz rZltEDec L1 L1')).\n2: intros H'18; inversion H'18; red in |- *; auto with stalmarck.\n2: apply appendfInclEq1; auto with stalmarck.\n2: Contradict H'17; auto with stalmarck.\n2: cut (InclEq _ eqRz L1' (appendf _ rZlt eqRz rZltEDec L1 L1')).\n2: intros H'18; inversion H'18; red in |- *; auto with stalmarck.\n2: apply appendfInclEq2; auto with stalmarck.\ngeneralize (H'0 Ar2 LL H'8 _ H'9 H'10).\ncase (evalTraceF t0 Ar2).\nintros Ar2' b2' L2'; case b2'; simpl in |- *; auto with stalmarck.\nintros H'17; Elimc H'17; intros S' E; Elimc E; intros H'17 H'18.\nrepeat (split; auto with stalmarck).\nElimc H'14; intros S'0 E; Elimc E; intros H'14 H'19.\nexists S'0; split; auto with stalmarck.\napply stalmarckPSplit with (a := a) (b := b) (S2 := S'0) (S3 := S'); auto with stalmarck.\nsplit; auto with stalmarck.\nred in |- *.\nintros i j H'20.\napply interMemEqStateRz; auto with stalmarck.\ncase H'18.\nintros x H'21.\napply eqStateRzContr with (a := x); auto with stalmarck.\nintros H'17; Elimc H'17; intros H'17 H'18; Elimc H'18; intros H'18 H'19;\n Elimc H'19; intros H'19 H'20.\ncut (OlistRz (appendRz L2 L2')); [ intros O2 | idtac ].\n2: unfold appendRz in |- *; red in |- *; apply appendfOlist; auto with stalmarck.\n2: try exact rZltEqComp.\ncut\n (forall e : rNat,\n  ~ InRz (rZPlus e) (appendRz L2 L2') ->\n  rArrayGet vM Ar2' e = rArrayGet vM Ar e); [ intros E2 | idtac ].\n2: intros e H'21.\n2: rewrite H'20; auto with stalmarck.\n2: apply H'12; auto with stalmarck.\n2: Contradict H'21; auto with stalmarck.\n2: cut (InclEq _ eqRz L2 (appendf _ rZlt eqRz rZltEDec L2 L2')).\n2: intros H'22; inversion H'22; red in |- *; auto with stalmarck.\n2: apply appendfInclEq1; auto with stalmarck.\n2: Contradict H'21; auto with stalmarck.\n2: cut (InclEq _ eqRz L2' (appendf _ rZlt eqRz rZltEDec L2 L2')).\n2: intros H'22; inversion H'22; red in |- *; auto with stalmarck.\n2: apply appendfInclEq2; auto with stalmarck.\nElimc H'18; intros S'0 E; Elimc E; intros H'18 H'21.\nElimc H'14; intros S' E; Elimc E; intros H'14 H'22.\ncut (inclState S S'); [ intros I1 | idtac ].\ncut (inclState S S'0); [ intros I2 | idtac ].\ngeneralize\n (interMemProp Ar1' Ar2' Ar H'13 H'17 H'2 (appendRz L1 L1') \n    (appendRz L2 L2') O1 O2 _ _ _ H'22 H'21 H'3 I1 I2 E1 E2).\ncase (interMem Ar1' Ar2' Ar (appendRz L1 L1') (appendRz L2 L2')).\nintros Ar' L' H'23; Elimc H'23; intros H'23 H'24; Elimc H'24;\n intros H'24 H'25; Elimc H'25; intros H'25 H'26.\nrepeat (split; auto with stalmarck).\nexists (interState S' S'0); split; auto with stalmarck.\napply stalmarckPSplit with (a := a) (b := b) (S2 := S') (S3 := S'0); auto with stalmarck.\napply inclStateTrans with (addEq (a, rZComp b) S); auto with stalmarck.\napply stalmarckIncl with (L := LL); auto with stalmarck.\napply inclStateTrans with (addEq (a, b) S); auto with stalmarck.\napply stalmarckIncl with (L := LL); auto with stalmarck.\nQed.\n\n(** A computable InDec *)\nDefinition InDec :\n  forall A : Type,\n  (forall x y : A, {x = y :>A} + {x <> y :>A}) ->\n  forall (a : A) (l : list A), {In a l} + {~ In a l}.\nfix InDec 4.\nintros A H' a l; case l.\nright; red in |- *; intros H'0; inversion H'0.\nintros a0 l0; case (H' a a0).\nintros H'0; left; rewrite H'0; auto with datatypes stalmarck.\nintros H'0; case (InDec A H' a l0).\nintros H'1; left; auto with datatypes stalmarck.\nintros H'1; right; simpl in |- *; red in |- *; intros H'2; case H'2; auto with stalmarck.\nDefined.\n\n(** the function f returns given a signed variable the triplets that contains this variable\n    fIn just check if all triplets in the trace are in the image of f *)\nFixpoint fInT (f : rZ -> list triplet) (T : Trace) {struct T} : bool :=\n  match T with\n  | emptyTrace => true\n  | tripletTrace (Triplet b p q r) =>\n      match InDec _ tripletDec (Triplet b p q r) (f p) with\n      | left _ => true\n      | right _ => false\n      end\n  | seqTrace T1 T2 =>\n      match fInT f T1 with\n      | true => fInT f T2\n      | false => false\n      end\n  | dilemmaTrace _ _ T1 T2 =>\n      match fInT f T1 with\n      | true => fInT f T2\n      | false => false\n      end\n  end.\n\nTheorem fInTCorrect :\n forall (LL : list triplet) (f : rZ -> _) (T : Trace),\n (forall n : rZ, incl (f n) LL) -> fInT f T = true -> TraceInList T LL.\nProof.\nintros LL f T H'; elim T; simpl in |- *; auto with stalmarck.\nintros t; case t; auto with stalmarck.\nintros r r0 r1 r2; case (InDec _ tripletDec (Triplet r r0 r1 r2) (f r0));\n auto with stalmarck.\nintros H'0 H'1; apply (H' r0); auto with stalmarck.\nintros; discriminate.\nintros t; case (fInT f t); auto with stalmarck.\nintros; discriminate.\nintros a b t; case (fInT f t); auto with stalmarck.\nintros; discriminate.\nQed.\n\n(** Build the hashtable *)\nFixpoint buildL (L : list triplet) : rArray (list triplet) :=\n  match L with\n  | nil => rArrayMake _ (rEmpty _) (fun r => nil)\n  | t :: L1 =>\n      match t with\n      | Triplet _ p q r =>\n          letP _ _\n            (letP _ _\n               (letP _ _ (buildL L1)\n                  (fun Ar1 =>\n                   rArraySet _ Ar1 (valRz p) (t :: rArrayGet _ Ar1 (valRz p))))\n               (fun Ar2 =>\n                rArraySet _ Ar2 (valRz q) (t :: rArrayGet _ Ar2 (valRz q))))\n            (fun Ar3 =>\n             rArraySet _ Ar3 (valRz r) (t :: rArrayGet _ Ar3 (valRz r)))\n      end\n  end.\n\nDefinition getT (Ar : rArray (list triplet)) (r : rZ) :=\n  rArrayGet _ Ar (valRz r).\n\nTheorem getTCorrect :\n forall (L : list triplet) (a : rZ), incl (getT (buildL L) a) L.\nProof.\nunfold getT in |- *; intros L; elim L; simpl in |- *.\nintros a; elim a; simpl in |- *.\nintros r; case r; simpl in |- *; auto with datatypes stalmarck.\nintros r; case r; simpl in |- *; auto with datatypes stalmarck.\nintros t; case t; auto with stalmarck.\nintros r r0 r1 r2 l H' a; unfold letP, getT in |- *; simpl in |- *.\ncase (rNatDec (valRz r2) (valRz a)); intros Eq1.\nrepeat rewrite Eq1.\nrepeat rewrite rArrayDef1 with (m := valRz a).\ncase (rNatDec (valRz r1) (valRz a)); intros Eq2.\nrepeat rewrite Eq2.\nrepeat rewrite rArrayDef1 with (m := valRz a).\ncase (rNatDec (valRz r0) (valRz a)); intros Eq3.\nrepeat rewrite Eq3.\nrepeat rewrite rArrayDef1 with (m := valRz a); auto with datatypes stalmarck.\nrepeat rewrite rArrayDef2 with (m2 := valRz a); auto with datatypes stalmarck.\nrewrite rArrayDef2 with (m2 := valRz a); auto with stalmarck.\ncase (rNatDec (valRz r0) (valRz a)); intros Eq3.\nrepeat rewrite Eq3.\nrepeat rewrite rArrayDef1 with (m := valRz a); auto with datatypes stalmarck.\nrewrite rArrayDef2 with (m2 := valRz a); auto with datatypes stalmarck.\nrewrite rArrayDef2 with (m2 := valRz a); auto with datatypes stalmarck.\ncase (rNatDec (valRz r1) (valRz a)); intros Eq2.\nrepeat rewrite Eq2.\nrepeat rewrite rArrayDef1 with (m := valRz a).\ncase (rNatDec (valRz r0) (valRz a)); intros Eq3.\nrepeat rewrite Eq3.\nrepeat rewrite rArrayDef1 with (m := valRz a); auto with datatypes stalmarck.\nrepeat rewrite rArrayDef2 with (m2 := valRz a); auto with datatypes stalmarck.\nrewrite rArrayDef2 with (m2 := valRz a); auto with stalmarck.\ncase (rNatDec (valRz r0) (valRz a)); intros Eq3.\nrepeat rewrite Eq3.\nrepeat rewrite rArrayDef1 with (m := valRz a); auto with datatypes stalmarck.\nrewrite rArrayDef2 with (m2 := valRz a); auto with datatypes stalmarck.\nQed.\n\n(** The initial array is well-formed *)\nTheorem rIwF : wellFormedArray (rArrayInit vM (fun _ : rNat => class nil)).\nProof.\napply wellFormedArrayDef; auto with stalmarck.\napply pointerDecreaseDef; simpl in |- *; auto with stalmarck.\nintros r; case r; simpl in |- *; intros; discriminate.\napply pointToClassRefDef; simpl in |- *; auto with stalmarck.\nintros r; case r; simpl in |- *; intros; discriminate.\napply pointToClassClassRef; simpl in |- *; auto with stalmarck.\nintros r; case r; simpl in |- *.\nintros p s Lr H'; inversion H'.\nintros H'0; inversion H'0.\nintros p s Lr H'; inversion H'.\nintros H'0; inversion H'0.\nintros s Lr H'; inversion H'.\nintros H'0; inversion H'0.\nintros r; case r; simpl in |- *; intros; discriminate.\napply OlistArrayDef; simpl in |- *; auto with stalmarck.\nintros r; case r; simpl in |- *.\nintros H' Lr H'0; inversion H'0; red in |- *; apply OlistNil; auto with stalmarck.\nintros H' Lr H'0; inversion H'0; red in |- *; apply OlistNil; auto with stalmarck.\nintros Lr H'; inversion H'; red in |- *; apply OlistNil; auto with stalmarck.\nQed.\n\n(** The correction of our checker *)\nTheorem checkTrace :\n forall (e : Expr) (T : Trace),\n match makeTriplets (norm e) with\n | tRC L r n =>\n     match fInT (getT (buildL L)) T with\n     | true =>\n         match addEqMem (rArrayInit _ (fun r => class nil)) r rZFalse with\n         | triple Ar1 true L1 => Tautology e\n         | triple Ar1 false L1 =>\n             match evalTraceF T Ar1 with\n             | triple Ar' false L => True\n             | triple Ar' true L => Tautology e\n             end\n         end\n     | false => True\n     end\n end.\nProof.\nintros e T; CaseEq (makeTriplets (norm e)).\nintros l r r0.\nCaseEq (fInT (getT (buildL l)) T); auto with stalmarck.\nCaseEq (addEqMem (rArrayInit vM (fun _ : rNat => class nil)) r rZFalse).\nintros r1 b; case b; auto with stalmarck.\nintros l0 H' H'0 H'1.\ncase (TautoRTauto e).\nintros H'3 H'4; apply H'4; auto with stalmarck.\ncase (rTautotTauto (norm e)).\nintros H'5 H'6; apply H'6; auto with stalmarck.\nred in |- *; rewrite H'1.\napply stalmarckGivesValidEquation with (S := addEq (r, rZFalse) nil); auto with stalmarck.\ngeneralize\n (addEqMemCorrect (rArrayInit vM (fun _ : rNat => class nil)) r rZFalse nil).\nrewrite H'; auto with stalmarck.\nintros H'2; apply H'2; auto with stalmarck.\napply rIwF; auto with stalmarck.\nexact initCorrect; auto with stalmarck.\nCaseEq (evalTraceF T r1).\nintros r2 b0; case b0; auto with stalmarck.\nintros l0 H' l1 H'0 H'1 H'2.\ncase (TautoRTauto e).\nintros H'3 H'4; apply H'4; auto with stalmarck.\ncase (rTautotTauto (norm e)).\nintros H'5 H'6; apply H'6; auto with stalmarck.\nred in |- *; rewrite H'2.\ngeneralize (TraceCorrect r1 T l).\nrewrite H'; auto with stalmarck.\ngeneralize\n (addEqMemCorrect (rArrayInit vM (fun _ : rNat => class nil)) r rZFalse nil).\nrewrite H'0; auto with stalmarck.\nintros H'7; Elimc H'7;\n [ intros H'7 H'8; Elimc H'8; intros H'8 H'9; Elimc H'9; intros H'9 H'10\n | idtac\n | idtac ]; auto with stalmarck.\nintros H'11; lapply H'11;\n [ intros H'12; elim (H'12 (addEq (r, rZFalse) nil));\n    [ intros S' E; Elimc E; intros H'13 H'14; clear H'11\n    | clear H'11\n    | clear H'11 ]\n | clear H'11 ]; auto with stalmarck.\napply stalmarckGivesValidEquation with (S := S'); auto with stalmarck.\napply fInTCorrect with (f := getT (buildL l)); auto with stalmarck.\nintros n; apply getTCorrect; auto with stalmarck.\napply rIwF; auto with stalmarck.\nexact initCorrect; auto with stalmarck.\nQed.\n\nTransparent addEqMem.\nTransparent doTripletF.\nTransparent interMem.\n\n(** How to prove a\\/ ~a *)\n#[local] Definition t1 :\n  Tautology (Node Or (V (rnext zero)) (normalize.N (V (rnext zero)))) :=\n  checkTrace (Node Or (V (rnext zero)) (normalize.N (V (rnext zero))))\n    (seqTrace\n       (tripletTrace\n          (Triplet rAnd (rZPlus (rnext (rnext zero))) \n             (rZMinus (rnext zero)) (rZPlus (rnext zero)))) emptyTrace).\n\n\n(** A function to check trace *)\nDefinition checkTracef (e : Expr) (T : Trace) :=\n  match makeTriplets (norm e) with\n  | tRC L r n =>\n      match fInT (getT (buildL L)) T with\n      | true =>\n          match addEqMem (rArrayInit _ (fun r => class nil)) r rZFalse with\n          | triple Ar1 true L1 => true\n          | triple Ar1 false L1 =>\n              match evalTraceF T Ar1 with\n              | triple Ar' false L => false\n              | triple Ar' true L => true\n              end\n          end\n      | false => false\n      end\n  end.\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/algoTrace.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5039061705290806, "lm_q1q2_score": 0.2676796810859221}}
{"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 nat.\nLocal Open Scope logic.\n\nDefinition update_inner_if_then :=\n  (Ssequence\n      (Scall None\n           (Evar _memcpy\n              (Tfunction\n                 (Tcons (tptr tvoid) (Tcons (tptr tvoid) (Tcons tuint Tnil)))\n                 (tptr tvoid) cc_default))\n           [Ebinop Oadd (Etempvar _p (tptr tuchar)) (Etempvar _n tuint)\n              (tptr tuchar), Etempvar _data (tptr tuchar),\n           Etempvar _fragment tuint])\n     (Ssequence\n        (Scall None\n           (Evar _sha256_block_data_order\n              (Tfunction\n                 (Tcons (tptr t_struct_SHA256state_st)\n                    (Tcons (tptr tvoid) Tnil)) tvoid cc_default))\n           [Etempvar _c (tptr t_struct_SHA256state_st),\n           Etempvar _p (tptr tuchar)])\n        (Ssequence\n           (Sset _data\n              (Ebinop Oadd (Etempvar _data (tptr tuchar))\n                 (Etempvar _fragment tuint) (tptr tuchar)))\n           (Ssequence\n              (Sset _len\n                 (Ebinop Osub (Etempvar _len tuint)\n                    (Etempvar _fragment tuint) tuint))\n                 (Scall None\n                    (Evar _memset\n                       (Tfunction\n                          (Tcons (tptr tvoid) (Tcons tint (Tcons tuint Tnil)))\n                          (tptr tvoid) cc_default))\n                    [Etempvar _p (tptr tuchar), Econst_int (Int.repr 0) tint,\n                    Ebinop Omul (Econst_int (Int.repr 16) tint)\n                      (Econst_int (Int.repr 4) tint) tint]))))).\n\nDefinition  update_inner_if_else :=\n                (Ssequence\n                    (Scall None\n                      (Evar _memcpy (Tfunction\n                                      (Tcons (tptr tvoid)\n                                        (Tcons (tptr tvoid)\n                                          (Tcons tuint Tnil))) (tptr tvoid) cc_default))\n                      ((Ebinop Oadd (Etempvar _p (tptr tuchar))\n                         (Etempvar _n tuint) (tptr tuchar)) ::\n                       (Etempvar _data (tptr tuchar)) ::\n                       (Etempvar _len tuint) :: nil))\n                  (Ssequence\n                    (Sassign\n                      (Efield\n                        (Ederef (Etempvar _c (tptr t_struct_SHA256state_st))\n                          t_struct_SHA256state_st) _num tuint)\n                      (Ebinop Oadd (Etempvar _n tuint)\n                        (Ecast (Etempvar _len tuint) tuint) tuint))\n                    (Sreturn None))).\n\nDefinition update_inner_if :=\n        Sifthenelse (Ebinop Oge (Etempvar _len tuint)\n                             (Etempvar _fragment tuint) tint)\n         update_inner_if_then\n         update_inner_if_else.\n\nDefinition inv_at_inner_if sh hashed len c d dd data kv hi lo:=\n (PROP ()\n   (LOCAL \n   (`(eq (Vint (Int.repr (64- Zlength dd)))) (eval_id _fragment);\n   `(eq  (offset_val (Int.repr 40) c)) (eval_id _p);\n   `(eq (Vint (Int.repr (Zlength dd)))) (eval_id _n);\n   `(eq c) (eval_id _c); `(eq d) (eval_id _data);\n   `(eq (Vint (Int.repr (Z.of_nat len)))) (eval_id _len);\n   `(eq kv) (eval_var _K256 (tarray tuint CBLOCKz)))\n   SEP  (`(array_at tuint Tsh (tuints (hash_blocks init_registers hashed)) 0 8 c);\n    `(sha256_length (hilo hi lo + (Z.of_nat len)*8) c);\n   `(array_at tuchar Tsh (ZnthV tuchar (map Vint (map Int.repr dd))) 0 64 (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   `(data_block sh data d)))).\n\nDefinition sha_update_inv sh hashed len c d (frag: list Z) (data: list Z) kv r_Nh r_Nl (done: bool) :=\n   (EX blocks:list int,\n   PROP  (len >= length blocks*4 - length frag /\\\n              (LBLOCKz | Zlength blocks) /\\ \n              intlist_to_Zlist blocks = frag ++ firstn (length blocks * 4 - length frag) data /\\\n             if done then len-(length blocks*4 - length frag) < CBLOCK else True)\n   LOCAL  (`(eq (offset_val (Int.repr 40) c)) (eval_id _p);\n   `(eq c) (eval_id _c); `(eq (offset_val (Int.repr (Z.of_nat (length blocks*4-length frag))) d)) (eval_id _data);\n   `(eq (Vint (Int.repr (Z.of_nat (len- (length blocks*4 - length frag)))))) (eval_id _len);\n   `(eq kv) (eval_var _K256 (tarray tuint CBLOCKz)))\n   SEP  (`(K_vector kv);\n    `(array_at tuint Tsh (tuints (hash_blocks init_registers (hashed ++ blocks))) 0 8 c);\n    `(sha256_length (hilo r_Nh r_Nl + (Z.of_nat len)*8) c);\n   `(array_at_ tuchar Tsh 0 64 (offset_val (Int.repr 40) c));\n   `(field_at_ Tsh t_struct_SHA256state_st [_num] c);\n   `(data_block sh data d))).\n\nLemma closed_make_args:\n  forall (Q: environ -> mpred) funsig el,\n     closed_wrt_vars (fun _ => True) Q ->\n  `Q (make_args' funsig el) = Q.\nProof.\nintros.\nextensionality rho.\nunfold_lift.\nhnf in H.\nunfold make_args'.\nspecialize (H rho (te_of (make_args (map fst (fst funsig)) (el rho) rho))).\nrewrite H.\nf_equal.\ndestruct rho; simpl.\nforget (el (mkEnviron ge ve te)) as vl.\nforget (map fst (fst funsig)) as il.\ninduction il; destruct vl; simpl.\nunfold globals_only. simpl.\nAbort.  (* need to be closed for addressable locals, too *)\n\nDefinition Delta_update_inner_if : tycontext.\nsimplify_Delta_from\n  (initialized _fragment\n     (initialized _p\n        (initialized _n\n           (initialized _data (func_tycontext f_SHA256_Update Vprog Gtot))))).\nDefined.\n\nLemma update_inner_if_then_proof:\n forall (Espec : OracleKind) (hashed : list int)\n          (dd data : list Z) (c d: val) (sh: share) (len: nat) kv\n          (hi lo: int) \n   (H : (Z.of_nat len <= Zlength data)%Z)\n   (H7 : ((Zlength hashed * 4 + Zlength dd) * 8)%Z = hilo hi lo)\n   (H3 : (Zlength dd < CBLOCKz)%Z)\n   (H3' : Forall isbyteZ dd)\n   (H4 : (LBLOCKz | Zlength hashed))\n   (Hlen : (Z.of_nat len <= Int.max_unsigned)%Z)\n   (c' : name _c) (data_ : name _data) (len' : name _len) \n   (data' : name _data) (p : name _p) (n : name _n)\n   (fragment_ : name _fragment),\n  let j := (40 + Zlength dd)%Z in\n  let k := (64 - Zlength dd)%Z in\n  forall (H0: (0 < k <= 64)%Z)\n       (H1: (64 < Int.max_unsigned)%Z)\n       (DBYTES: Forall isbyteZ data),\nsemax Delta_update_inner_if\n  (PROP  ()\n   LOCAL \n   (`(typed_true tint)\n      (eval_expr\n         (Ebinop Oge (Etempvar _len tuint) (Etempvar _fragment tuint) tint));\n   `(eq (Vint (Int.repr k))) (eval_id _fragment);\n   `(eq (offset_val (Int.repr 40) c)) (eval_id _p);\n   `(eq (Vint (Int.repr (Zlength dd)))) (eval_id _n); `(eq c) (eval_id _c);\n   `(eq d) (eval_id _data);\n   `(eq (Vint (Int.repr (Z.of_nat len)))) (eval_id _len);\n   `(eq kv) (eval_var _K256 (tarray tuint CBLOCKz)))\n   SEP \n   (`(array_at tuint Tsh (tuints (hash_blocks init_registers hashed)) 0 8 c);\n   `(sha256_length (hilo hi lo + Z.of_nat len * 8) 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] (Vint (Int.repr (Zlength dd)))\n       c); `(K_vector kv);\n   `(array_at tuchar sh (tuchars (map Int.repr data)) 0 (Zlength data) d)))\n  update_inner_if_then\n  (overridePost (sha_update_inv sh hashed len c d dd data kv hi lo false)\n     (function_body_ret_assert tvoid\n        (EX  a' : s256abs,\n         PROP  (update_abs (firstn len data) (S256abs hashed dd) a')\n         LOCAL ()\n         SEP  (`(K_vector kv); `(sha256state_ a' c); `(data_block sh data d))))).\nProof.\n intros.\n simplify_Delta; abbreviate_semax.\n  unfold update_inner_if_then.\n  apply (remember_value (eval_id _fragment)); intro fragment.\n  forward_call (* memcpy (p+n,data,fragment); *)\n   ((sh,Tsh), \n    offset_val (Int.repr (Zlength dd)) (offset_val (Int.repr 40) c),\n    d, \n    Int.unsigned (force_int fragment),\n    Basics.compose force_int (ZnthV tuchar (map Vint (map Int.repr data)))).\n fold j; fold k.\n entailer!.\n clear fragment H5.\n rewrite negb_true_iff in H6. \n apply ltu_repr_false in H6; [ | repable_signed | omega].\n clear TC.\n unfold j,k in *; clear j k.\nrewrite cVint_force_int_ZnthV\n by (rewrite initial_world.Zlength_map; omega).\n rewrite memory_block_array_tuchar by omega.\n rewrite split_offset_array_at with (contents :=ZnthV tuchar (map Vint (map Int.repr dd))) (lo := Zlength dd); [| omega | simpl; omega | reflexivity].\n rewrite (split_array_at (64-Zlength dd) _ _ (tuchars (map Int.repr data)))\n    by omega.\n\n replace (offset_val (Int.repr (40 + Zlength dd)) c)\n          with (offset_val (Int.repr (sizeof tuchar * Zlength dd)) (offset_val (Int.repr 40) c))\n  by (change (sizeof tuchar) with 1%Z; rewrite Z.mul_1_l; rewrite offset_offset_val, add_repr; auto).\n cancel.\n \n after_call.\n fold j k.\n rename H5 into H2'.\n gather_SEP 4%Z 1%Z.\n replace_SEP 0%Z (`(array_at tuchar Tsh (ZnthV tuchar (map Vint (map Int.repr (dd ++ data) ))) 0\n        64 (offset_val (Int.repr 40) c))).\n entailer!.\n rewrite negb_true_iff in H8; \n apply ltu_repr_false in H8; [ | omega..].\n unfold j,k in *.\n rename c' into c.\n rewrite cVint_force_int_ZnthV\n by (rewrite initial_world.Zlength_map; omega).\n replace (offset_val (Int.repr (40 + Zlength dd)) c)\n          with (offset_val (Int.repr (sizeof tuchar * Zlength dd)) (offset_val (Int.repr 40) c))\n  by (change (sizeof tuchar) with 1%Z; rewrite Z.mul_1_l; rewrite offset_offset_val, add_repr; auto).\n rewrite split_offset_array_at with (lo := Zlength dd) (contents := (ZnthV tuchar (map Vint (map Int.repr (dd ++ data))))); [| omega | simpl; omega | reflexivity].\n  normalize.\n apply sepcon_derives; apply derives_refl'; apply equal_f; apply array_at_ext; intros.\n unfold ZnthV. repeat rewrite if_false by omega.\n repeat rewrite map_app.\n rewrite app_nth1; auto. repeat rewrite map_length. apply Nat2Z.inj_lt.\n rewrite Z2Nat.id by omega. rewrite <- Zlength_correct; omega.\n repeat rewrite map_app.\n unfold ZnthV. repeat rewrite if_false by omega.\n rewrite app_nth2; auto. f_equal.\n rewrite !map_length. rewrite Zlength_correct. \n rewrite Z2Nat.inj_add by omega.\n rewrite Nat2Z.id. omega.\n rewrite map_length; auto.\n repeat rewrite map_length. apply Nat2Z.inj_ge.\n rewrite Z2Nat.id by omega. rewrite <- Zlength_correct; omega.\n\n forward_call (* sha256_block_data_order (c,p); *)\n   (hashed, Zlist_to_intlist (dd++(firstn (Z.to_nat k) data)), c, (offset_val (Int.repr 40) c), Tsh, kv).\n entailer.\n unfold j,k in *|-.\n rewrite negb_true_iff in H9; apply ltu_repr_false in H9; [ | omega..].\n assert (length (dd ++ firstn (Z.to_nat k) data) = 64). {\n  unfold k.\n  rewrite app_length.\n  rewrite firstn_length, min_l.\n  apply Nat2Z.inj. rewrite Nat2Z.inj_add.\n  rewrite Z2Nat.id.\n  change (Z.of_nat 64) with 64%Z.\n  rewrite <- Zlength_correct; omega.\n  omega.\n  apply Nat2Z.inj_le.  rewrite Z2Nat.id.  rewrite <- Zlength_correct; omega.\n  omega.\n}\n assert (length (Zlist_to_intlist (dd ++ firstn (Z.to_nat k) data)) = LBLOCK). {\n  apply length_Zlist_to_intlist. assumption.\n}\n apply andp_right; [apply prop_right |].\n rewrite Zlength_correct, H12. reflexivity.\n replace (data_block Tsh\n      (intlist_to_Zlist (Zlist_to_intlist (dd ++ firstn (Z.to_nat k) data)))\n      (offset_val (Int.repr 40) c))\n    with (array_at tuchar Tsh (ZnthV tuchar (map Vint (map Int.repr (dd ++ data)))) 0\n  64 (offset_val (Int.repr 40) c)).\n cancel.\n unfold data_block.\n rewrite prop_true_andp.\n replace (Zlength\n     (intlist_to_Zlist (Zlist_to_intlist (dd ++ firstn (Z.to_nat k) data))))\n  with 64%Z\n by (rewrite Zlength_correct;\n      change 64%Z with (Z.of_nat 64); symmetry; f_equal;\n       rewrite length_intlist_to_Zlist, H12; reflexivity).\n  apply equal_f; apply array_at_ext; intros.\n unfold tuchars, ZnthV. repeat rewrite if_false by omega.\n rewrite Zlist_to_intlist_to_Zlist.\n  repeat rewrite map_map. \n  repeat rewrite (@nth_map' Z val _ _ 0%Z).\n  f_equal. f_equal.\n destruct (zlt i (Zlength dd)).\n assert (Z.to_nat i < length dd)\n  by (apply Nat2Z.inj_lt; rewrite Z2Nat.id by omega; rewrite <- Zlength_correct; auto).\n  repeat rewrite app_nth1 by auto; auto.\n assert (Z.to_nat i >= length dd)\n  by (apply Nat2Z.inj_ge; rewrite Z2Nat.id by omega; rewrite <- Zlength_correct; auto).\n  repeat rewrite app_nth2 by auto; auto.\n  symmetry; apply nth_firstn_low.\n  unfold k.\n  split. apply Nat2Z.inj_lt. rewrite Nat2Z.inj_sub by omega. \n  repeat rewrite Z2Nat.id by omega. rewrite <- Zlength_correct;omega.\n apply Nat2Z.inj_ge.  \n  repeat rewrite Z2Nat.id by omega. rewrite <- Zlength_correct;omega.\n  rewrite app_length. rewrite firstn_length. rewrite min_l.\n  unfold k; apply Nat2Z.inj_lt.\n rewrite Z2Nat.id by omega; rewrite Nat2Z.inj_add; \n rewrite Z2Nat.id by omega; rewrite <- Zlength_correct.\n omega.\n unfold k.\n apply Nat2Z.inj_le; rewrite Z2Nat.id by omega.\n  rewrite <- Zlength_correct; omega.\n  apply Nat2Z.inj_lt; rewrite  Z2Nat.id by omega.\n  rewrite app_length, Nat2Z.inj_add.\n repeat rewrite <- Zlength_correct.\n  omega.\n rewrite H11; exists LBLOCK; reflexivity.\n rewrite Forall_app; split; auto.\n apply Forall_firstn; auto.\n apply isbyte_intlist_to_Zlist.\n after_call.\n forward. (* data  += fragment; *)\nentailer!.\n forward. (* len -= fragment; *)\n      normalize_postcondition.\n forward_call (* memset (p,0,SHA_CBLOCK); *)\n    (Tsh, offset_val (Int.repr 40) c, 64%Z, Int.zero). {\n fold k. fold j.\n unfold data_block.\n entailer!.\n simpl.\n rewrite <- H12 in H8, H10; clear len'0 H12.\n simpl in H8.\n inversion H8; clear H8; subst len'.\n simpl in H10.\n rewrite memory_block_array_tuchar by omega.\n replace  (Zlength\n     (intlist_to_Zlist (Zlist_to_intlist (dd ++ firstn (Z.to_nat k) data))))\n    with 64%Z.\n cancel.\n rewrite Zlength_intlist_to_Zlist.\n rewrite Zlength_correct.\n change 64%Z with (4*16)%Z; f_equal.\n rewrite length_Zlist_to_intlist with (n:=16).\n reflexivity.\n simpl.\n rewrite app_length, firstn_length.\n rewrite min_l.\n unfold k in *. \n apply Nat2Z.inj.\n rewrite Nat2Z.inj_add.\n rewrite Z2Nat.id by omega.\n rewrite <- Zlength_correct.\n change (Z.of_nat 64) with 64%Z; omega.\n unfold k in *.\n apply Nat2Z.inj_le; rewrite Z2Nat.id by omega.\n rewrite <- Zlength_correct.\n fold k in H10;  simpl in H10.\n unfold Int.ltu in H10; if_tac in H10; try inv H10.\n unfold k in H8; repeat rewrite Int.unsigned_repr in H8 by omega.\n omega.\n}\n\n after_call.\n unfold sha_update_inv.\n entailer.\n rewrite negb_true_iff in H9.\n apply ltu_repr_false in H9; [ | omega..].\n clear TC  TC1.\n apply exp_right with (Zlist_to_intlist (dd ++ firstn (Z.to_nat k) data)).\n assert (LL: length (dd ++ firstn (Z.to_nat k) data) = CBLOCK). {\n rewrite app_length. rewrite firstn_length. rewrite min_l.\n unfold k in *; \n apply Nat2Z.inj. rewrite Nat2Z.inj_add.\n rewrite Z2Nat.id by omega.\n rewrite <- Zlength_correct. change (Z.of_nat (CBLOCK)) with 64%Z.\n omega.\n apply Nat2Z.inj_le;  rewrite Z2Nat.id by omega; rewrite <- Zlength_correct; omega.\n}\nassert (length (Zlist_to_intlist (dd ++ firstn (Z.to_nat k) data)) = LBLOCK). {\n apply length_Zlist_to_intlist. change (4*LBLOCK)%nat with CBLOCK.\n apply LL.\n}\n assert (KK: k = Z.of_nat (LBLOCK * 4 - length dd)). {\n unfold k.\n rewrite Nat2Z.inj_sub. rewrite Zlength_correct; reflexivity.\n unfold k in H0. clear - H0.\n apply Nat2Z.inj_le.\n change (Z.of_nat (LBLOCK*4)) with 64%Z.\n rewrite <- Zlength_correct.\n omega.\n}\n entailer!.\n *\n  rewrite H6. \n  apply Nat2Z.inj_ge.\n  rewrite Nat2Z.inj_sub.\n  change (Z.of_nat (LBLOCK*4)) with 64%Z.\n  rewrite <- Zlength_correct; omega.\n  clear - H3. apply Nat2Z.inj_le. rewrite <- Zlength_correct.\n  change (Z.of_nat (LBLOCK*4)%nat) with CBLOCKz; clear - H3; omega.\n * \n  apply Zlength_length in H6; auto.\n  rewrite H6. exists 1%Z; reflexivity.\n *\n  rewrite H6. rewrite Zlist_to_intlist_to_Zlist.\n  f_equal. f_equal. clear - H0.\n  rewrite Z2Nat.inj_sub by omega.\n  rewrite Zlength_correct, Nat2Z.id.\n  reflexivity.\n  rewrite LL. exists 16; reflexivity.\n  rewrite Forall_app; split; auto.\n  apply Forall_firstn; auto.\n *\n  rewrite H6. f_equal.\n  f_equal.\n  auto.\n *\n  rewrite H6. do 2 f_equal.\n  rewrite Nat2Z.inj_sub. f_equal; auto.\n  apply Nat2Z.inj_le.\n  rewrite <- KK. omega.\n *\n  unfold data_block.\n  rewrite prop_true_andp by auto. \n  rewrite cVint_force_int_ZnthV.\n  rewrite <- split_array_at.\n auto.\n omega. rewrite initial_world.Zlength_map. omega.\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_update2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.26767968108592205}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.progs.logical_compare.\n\nInstance CompSpecs : compspecs. Proof. 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 [ tbool, tbool ]\n        PROP () PARAMS (Vint a; Vint b) SEP ()\n  POST [ tbool ]\n        PROP() RETURN (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 [ tbool, tbool ]\n        PROP () PARAMS (Vint a; Vint b) SEP ()\n  POST [ tbool ]\n        PROP() RETURN (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 tt gv\n  POST [ tint ] main_post prog 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 tt 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": "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_logical_compare.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2676773948429908}}
{"text": "(* bad *)\nFrom Coq Require Import\n  Lists.List Logic.ProofIrrelevance ZArith.ZArith.\nFrom DEZ.Has Require Export\n  OneSortedEnumeration OneSortedCardinality.\nFrom DEZ.Is Require Export\n  OneSortedFinite Isomorphic TwoSortedBimodule\n  Ring TwoSortedUnitalAssociativeAlgebra.\nFrom DEZ.Justifies Require Export\n  OneSortedPositiveOperations OneSortedNaturalOperations\n  OneSortedIntegerOperations.\nFrom DEZ.Justifies Require Export\n  ZTheorems.\nFrom DEZ.Supports Require Import\n  OneSortedArithmeticNotations.\nFrom DEZ.Supports Require Import\n  OneSortedMultiplicativeOperationNotations.\n\nImport ListNotations.\n\nImport Addition.Subclass Zero.Subclass Negation.Subclass\n  Multiplication.Subclass One.Subclass.\n\nDefinition Nseq (start len : N) : list N :=\n  map N.of_nat (seq (N.to_nat start) (N.to_nat len)).\n\n(* From Coq Require Import\n  FSets.FMapAVL Structures.OrderedTypeEx.\nModule Import Map := FMapAVL.Make Positive_as_OT. *)\n\nFrom Coq Require Import\n  FSets.FMapList Structures.OrderedTypeEx.\nModule Import Map := FMapList.Make Positive_as_OT.\n\nFrom Coq Require Import\n  FSets.FMapFacts.\n\nModule Props := WProperties_fun Positive_as_OT Map.\nModule Mapper := Props.F.\n\nDefinition Map_max_key {A : Type} (xs : Map.t A) : option key :=\n  Map.fold (fun (n : key) (x : A) (ms : option key) =>\n    match ms with\n    | Some m => Some (Pos.max n m)\n    | None => Some n\n    end) xs None.\n\nDefinition Map_max_key_def {A : Type} (d : key) (xs : Map.t A) : key :=\n  Map.fold (fun (n : key) (x : A) (m : key) => Pos.max n m) xs d.\n\nSection Context.\n\nContext (A B : Type) `{IsTwoBimod A B}.\n\nRecord tensor : Type := {\n  ht : A;\n  tt : Map.t (list B);\n}.\n\nDefinition proper (p : tensor) : Prop :=\n  forall (k : key) (x : list B),\n  MapsTo k x (tt p) -> length x = Pos.to_nat k.\n\nDefinition Add (p q : tensor) : tensor := {|\n  ht := Addition.add (ht p) (ht q);\n  tt := Map.map2 (fun (as' bs : option (list B)) => match as', bs with\n    | Some a, Some b => Some (List.map (prod_uncurry Addition.add) (combine a b))\n    | Some a, None => Some a\n    | None, Some b => Some b\n    | None, None => None\n    end) (tt p) (tt q)\n|}.\n\nDefinition Zero : tensor := {|\n  ht := zero;\n  tt := Map.empty (list B);\n|}.\n\nDefinition Neg (p : tensor) : tensor :={|\n  ht := neg (ht p);\n  tt := Map.map (List.map neg) (tt p);\n|}.\n\nDefinition ActL (a : A) (p : tensor) : tensor :=\n  {| ht := ht p; tt := Map.map (List.map (act_l a)) (tt p) |}.\n\nDefinition ActR (p : tensor) (a : A) : tensor :=\n  {| ht := ht p; tt := Map.map (List.map (flip act_r a)) (tt p) |}.\n\nGlobal Instance N_has_bin_op : HasBinOp N := N.add.\n\nGlobal Instance N_has_null_op : HasNullOp N := N.zero.\n\n(** Instant tensor algebra; just add water. *)\n\nEnd Context.\n\n(* Section Tests.\n\nLocal Open Scope Z_scope.\n\nInstance positive_has_one : HasOne positive := xH.\n\nInstance Z3_has_add : HasAdd (Z * Z * Z) :=\n  fun x y : Z * Z * Z =>\n  match x, y with\n  | (x0, x1, x2), (y0, y1, y2) => (x0 + y0, x1 + y1, x2 + y2)\n  end.\n\nInstance Z3_has_neg : HasNeg (Z * Z * Z) :=\n  fun x : Z * Z * Z =>\n  match x with\n  | (x0, x1, x2) => (- x0, - x1, - x2)\n  end.\n\nInstance Z3_has_act_l : HasActL Z (Z * Z * Z) :=\n  fun (a : Z) (x : Z * Z * Z) =>\n  match x with\n  | (x0, x1, x2) => (a * x0, a * x1, a * x2)\n  end.\n\nInstance Z3_has_act_r : HasActR Z (Z * Z * Z) :=\n  fun (x : Z * Z * Z) (a : Z) =>\n  match x with\n  | (x0, x1, x2) => (x0 * a, x1 * a, x2 * a)\n  end.\n\nLet p : tensor := {|\n  ht := Z.zero;\n  tt := Props.of_list [\n    (1%positive, [(0, 0, 0)]);\n    (2%positive, [(1, 0, 0); (1, 0, 0)]);\n    (3%positive, [(0, 0, 7); (0, 1, 0); (1, 0, 0)])];\n|}.\n\nLet q : tensor := {|\n  ht := Z.zero;\n  tt := Props.of_list [\n    (1%positive, [(2, 1, 0)]);\n    (2%positive, [(1, 0, 0); (1, 0, 0)]);\n    (3%positive, [(0, 1, 0); (0, 1, 0); (0, 0, 1)])];\n|}.\n\nLet r : tensor := {|\n  ht := Z.zero;\n  tt := Props.of_list [\n    (1%positive, [(0, 0, 0)]);\n    (2%positive, [(0, 0, 0); (0, 0, 0)]);\n    (3%positive, [(1, 0, 0); (1, 0, 0); (2, 1, 0)]);\n    (4%positive, [(0, 0, 7); (0, 1, 0); (1, 0, 0); (2, 1, 0)]);\n    (5%positive, [(1, 0, 0); (1, 0, 0); (0, 1, 0); (0, 1, 0); (0, 0, 1)]);\n    (6%positive, [(0, 0, 7); (0, 1, 0); (1, 0, 0); (0, 1, 0); (0, 1, 0); (0, 0, 1)])];\n|}.\n\nCompute GrdMul p q.\nCompute r.\n\nEnd Tests. *)\n", "meta": {"author": "Tuplanolla", "repo": "dez", "sha": "c2eadc2e032094c3504ec3803c000dba4feb547e", "save_path": "github-repos/coq/Tuplanolla-dez", "path": "github-repos/coq/Tuplanolla-dez/dez-c2eadc2e032094c3504ec3803c000dba4feb547e/fowl/Justifies/TensorTheorems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2676773886426616}}
{"text": "Load \"Pi4.v\".\n\n\n\n(**************************************************************************************************)\n\n\n\nTheorem DDH_two_RRS1 : phi11 ~ phi31.\n\nProof.  try (unfold phi11, phi21, phi10, phi20, t10, t20, t11,t12, t21,t22). unfold qa0000, qb0000, mphi10, mphi20, phi10. try (unfold phi11, phi21, phi10, phi20, t10, t20, t11,t12, t21,t22). simpl.  try unfold grn21, grn21, msgt10, msgt11, msgt20, msgt21. simpl. reflexivity. Qed.\n\nTheorem DDH_two_RRS2 : phi12 ~ phi22.\nProof. repeat (try (unfold phi12, phi22 ,phi11, phi21, phi10, phi20, t10, t20, t11,t12, t21,t22, t13, t23)). simpl. unfold qa0000, qb0000, qa1000, qa0010, qa0001, qa0100,qb1000, qb0010, qb0001, qb0100, mphi10, mphi20, phi10. simpl. try (unfold phi11, phi21, phi10, phi20, t10, t20, t11,t12, t21,t22, t13). simpl.  try unfold  grn2, grn22, grn21, grn21, msgt10, msgt11, msgt20, msgt21, mphi21, mphi11. simpl. reflexivity. Qed.\n\nTheorem DDH_two_RRS3: phi13~ phi23.\nProof.  reflexivity. Qed.\n\nTheorem DDH_two_RRS4: (Fresh [0; 1;2; 3] [] = true) -> phi14 ~ phi24.\nProof .  intros; pose proof (DDH); apply DDH in H;  repeat try unfold phi15, phi25, phi14, phi24, phi13, phi23, phi12, phi22 ,phi11, phi21, phi10, phi20 . repeat try unfold t10, t20, t11,t12, t21,t22, t13, t23, t14, t24, t15, t25, t16, t26.  try unfold mphi15 , mphi14 , mphi13 , mphi12. try unfold mphi11, mphi10. try simpl.  try unfold mphi25,mphi24,  mphi23,mphi22 . try unfold mphi21,  mphi20. simpl.\nrepeat try unfold msgt10, msgt20, msgt11, msgt12, msgt21, msgt22, msgt13, msgt23, msgt14, msgt24, msgt15, msgt25, msgt16, msgt26;\n repeat try unfold grn21, grn2, grn3, grn4, grn21, grn22, grn23, grn24; repeat try unfold mf1ph10rn1,  mf2ph110rn1,   mf2ph11rn1,  mf2ph11rn2,  mf3ph12rn1, mf3ph12rn2,  mf1ph20rn1,  mf2ph20rn1,   mf2ps1rn1,  mf2ps1rn2,  mf3ps2rn1, mf3ps2rn2; repeat try simpl;\nrepeat try unfold q0000, q1000 , q0010,q0100,q0001 ,q2000,q1100 ,q1001 ,q0110,q0200,q1000_s,q0010_s,q0100_s,q0001_s,q2100,q1200,q2001,q0210,\n q0120,q2000_s, q1100_s, q1001_s, q0110_s,q0200_s,q1000_ss,q0010_ss, q0100_ss,q0001_ss,q2200,q2100_s,q1200_s,q2001_s,q0210_s,q0120_s,q2000_ss,q1100_ss ,q1001_ss,q0110_ss,q0200_ss,\n q1000_sss,q0010_sss,q0100_sss,q0001_sss;\nrepeat try unfold qb0000, qb1000 , qb0010,qb0100,qb0001 ,qb2000,qb1100 ,qb1001 ,qb0110,qb0200,qb1000_s,qb0010_s,qb0100_s,qb0001_s,qb2100,qb1200,qb2001,qb0210,\n qb0120,qb2000_s, qb1100_s, qb1001_s, qb0110_s,qb0200_s,qb1000_ss,qb0010_ss, qb0100_ss,qb0001_ss,qb2200,qb2100_s,qb1200_s,qb2001_s,qb0210_s,qb0120_s,qb2000_ss,qb1100_ss ,qb1001_ss,qb0110_ss,qb0200_ss,\n qb1000_sss,qb0010_sss,qb0100_sss,qb0001_sss.\n\n repeat try unfold phi15, phi25, phi14, phi24, phi13, phi23, phi12, phi22 ,phi11, phi21, phi10, phi20 ;  repeat try unfold t10, t20, t11,t12, t21,t22, t13, t23, t14, t24, t15, t25, t16, t26. repeat try unfold mphi15, mphi25, mphi14, mphi24, mphi13, mphi23, mphi12, mphi22 ,mphi11, mphi21, mphi10, mphi20. \n try unfold mphi15 , mphi14 , mphi13 , mphi12. try unfold mphi11, mphi10. try simpl.  try unfold mphi25,mphi24,  mphi23,mphi22 . try unfold mphi21,  mphi20. simpl.\nrepeat try unfold msgt10, msgt20, msgt11, msgt12, msgt21, msgt22, msgt13, msgt23, msgt14, msgt24, msgt15, msgt25, msgt16, msgt26;\n repeat try unfold grn1, grn2, grn3, grn4, grn21, grn22, grn23, grn24; repeat try unfold mf1ph10rn1,  mf2ph10rn1,   mf2ph11rn1,  mf2ph11rn2,  mf3ph12rn1, mf3ph12rn2, mf3ph11rn2,  mf1ph20rn1,  mf2ph20rn1,   mf2ps1rn1,  mf2ps1rn2,  mf3ps2rn1, mf3ps2rn2, mf3ps1rn2; repeat try simpl;\nrepeat try unfold q0000, q1000 , q0010,q0100,q0001 ,q2000,q1100 ,q1001 ,q0110,q0200,q1000_s,q0010_s,q0100_s,q0001_s,q2100,q1200,q2001,q0210,\n q0120,q2000_s, q1100_s, q1001_s, q0110_s,q0200_s,q1000_ss,q0010_ss, q0100_ss,q0001_ss,q2200,q2100_s,q1200_s,q2001_s,q0210_s,q0120_s,q2000_ss,q1100_ss ,q1001_ss,q0110_ss,q0200_ss,\n q1000_sss,q0010_sss,q0100_sss,q0001_sss;\nrepeat try unfold qb0000, qb1000 , qb0010,qb0100,qb0001 ,qb2000,qb1100 ,qb1001 ,qb0110,qb0200,qb1000_s,qb0010_s,qb0100_s,qb0001_s,qb2100,qb1200,qb2001,qb0210,\n qb0120,qb2000_s, qb1100_s, qb1001_s, qb0110_s,qb0200_s,qb1000_ss,qb0010_ss, qb0100_ss,qb0001_ss,qb2200,qb2100_s,qb1200_s,qb2001_s,qb0210_s,qb0120_s,qb2000_ss,qb1100_ss ,qb1001_ss,qb0110_ss,qb0200_ss,\n qb1000_sss,qb0010_sss,qb0100_sss,qb0001_sss.\n \n try unfold mphi15 , mphi14 , mphi13 , mphi12. try unfold mphi11, mphi10. try simpl.  try unfold mphi25,mphi24,  mphi23,mphi22 . try unfold mphi21,  mphi20. simpl.\n\nAdmitted.\n\nTheorem DDH_two_RRS5: [t15] ~ [t25].\n\nProof.    repeat try unfold phi15, phi25, phi14, phi24, phi13, phi23, phi12, phi22 ,phi11, phi21, phi10, phi20 . repeat try unfold t10, t20, t11,t12, t21,t22, t13, t23, t14, t24, t15, t25, t16, t26.  try unfold mphi15 , mphi14 , mphi13 , mphi12. try unfold mphi11, mphi10. try simpl.  try unfold mphi25,mphi24,  mphi23,mphi22 . try unfold mphi21,  mphi20. simpl.\nrepeat try unfold msgt10, msgt20, msgt11, msgt12, msgt21, msgt22, msgt13, msgt23, msgt14, msgt24, msgt15, msgt25, msgt16, msgt26;\n repeat try unfold grn1, grn2, grn3, grn4, grn21, grn22, grn23, grn24; repeat try unfold mf1ph10rn1,  mf2ph10rn1,   mf2ph11rn1,  mf2ph11rn2,  mf3ph12rn1, mf3ph12rn2,  mf1ph20rn1,  mf2ph20rn1,   mf2ps1rn1,  mf2ps1rn2,  mf3ps2rn1, mf3ps2rn2; repeat try simpl;\nrepeat try unfold q0000, q1000 , q0010,q0100,q0001 ,q2000,q1100 ,q1001 ,q0110,q0200,q1000_s,q0010_s,q0100_s,q0001_s,q2100,q1200,q2001,q0210,\n q0120,q2000_s, q1100_s, q1001_s, q0110_s,q0200_s,q1000_ss,q0010_ss, q0100_ss,q0001_ss,q2200,q2100_s,q1200_s,q2001_s,q0210_s,q0120_s,q2000_ss,q1100_ss ,q1001_ss,q0110_ss,q0200_ss,\n q1000_sss,q0010_sss,q0100_sss,q0001_sss;\nrepeat try unfold qb0000, qb1000 , qb0010,qb0100,qb0001 ,qb2000,qb1100 ,qb1001 ,qb0110,qb0200,qb1000_s,qb0010_s,qb0100_s,qb0001_s,qb2100,qb1200,qb2001,qb0210,\n qb0120,qb2000_s, qb1100_s, qb1001_s, qb0110_s,qb0200_s,qb1000_ss,qb0010_ss, qb0100_ss,qb0001_ss,qb2200,qb2100_s,qb1200_s,qb2001_s,qb0210_s,qb0120_s,qb2000_ss,qb1100_ss ,qb1001_ss,qb0110_ss,qb0200_ss,\n qb1000_sss,qb0010_sss,qb0100_sss,qb0001_sss.\n\n\nrepeat try unfold phi15, phi25, phi14, phi24, phi13, phi23, phi12, phi22 ,phi11, phi21, phi10, phi20 ;  repeat try unfold t10, t20, t11,t12, t21,t22, t13, t23, t14, t24, t15, t25, t16, t26. repeat try unfold mphi15, mphi25, mphi14, mphi24, mphi13, mphi23, mphi12, mphi22 ,mphi11, mphi21, mphi10, mphi20. \n try unfold mphi15 , mphi14 , mphi13 , mphi12. try unfold mphi11, mphi10. try simpl.  try unfold mphi25,mphi24,  mphi23,mphi22 . try unfold mphi21,  mphi20. simpl.\nrepeat try unfold msgt10, msgt20, msgt11, msgt12, msgt21, msgt22, msgt13, msgt23, msgt14, msgt24, msgt15, msgt25, msgt16, msgt26;\n repeat try unfold grn1, grn2, grn3, grn4, grn21, grn22, grn23, grn24; repeat try unfold mf1ph10rn1,  mf2ph10rn1,   mf2ph11rn1,  mf2ph11rn2,  mf3ph12rn1, mf3ph12rn2, mf3ph11rn2,  mf1ph20rn1,  mf2ph20rn1,   mf2ps1rn1,  mf2ps1rn2,  mf3ps2rn1, mf3ps2rn2, mf3ps1rn2; repeat try simpl;\nrepeat try unfold q0000, q1000 , q0010,q0100,q0001 ,q2000,q1100 ,q1001 ,q0110,q0200,q1000_s,q0010_s,q0100_s,q0001_s,q2100,q1200,q2001,q0210,\n q0120,q2000_s, q1100_s, q1001_s, q0110_s,q0200_s,q1000_ss,q0010_ss, q0100_ss,q0001_ss,q2200,q2100_s,q1200_s,q2001_s,q0210_s,q0120_s,q2000_ss,q1100_ss ,q1001_ss,q0110_ss,q0200_ss,\n q1000_sss,q0010_sss,q0100_sss,q0001_sss;\nrepeat try unfold qb0000, qb1000 , qb0010,qb0100,qb0001 ,qb2000,qb1100 ,qb1001 ,qb0110,qb0200,qb1000_s,qb0010_s,qb0100_s,qb0001_s,qb2100,qb1200,qb2001,qb0210,\n qb0120,qb2000_s, qb1100_s, qb1001_s, qb0110_s,qb0200_s,qb1000_ss,qb0010_ss, qb0100_ss,qb0001_ss,qb2200,qb2100_s,qb1200_s,qb2001_s,qb0210_s,qb0120_s,qb2000_ss,qb1100_ss ,qb1001_ss,qb0110_ss,qb0200_ss,\n qb1000_sss,qb0010_sss,qb0100_sss,qb0001_sss.\n\nrepeat try unfold phi15, phi25, phi14, phi24, phi13, phi23, phi12, phi22 ,phi11, phi21, phi10, phi20 ;  repeat try unfold t10, t20, t11,t12, t21,t22, t13, t23, t14, t24, t15, t25, t16, t26. repeat try unfold mphi15, mphi25, mphi14, mphi24, mphi13, mphi23, mphi12, mphi22 ,mphi11, mphi21, mphi10, mphi20. \n try unfold mphi15 , mphi14 , mphi13 , mphi12. try unfold mphi11, mphi10. try simpl.  try unfold mphi25,mphi24,  mphi23,mphi22 . try unfold mphi21,  mphi20. simpl.\nrepeat try unfold msgt10, msgt20, msgt11, msgt12, msgt21, msgt22, msgt13, msgt23, msgt14, msgt24, msgt15, msgt25, msgt16, msgt26;\n repeat try unfold grn1, grn2, grn3, grn4, grn21, grn22, grn23, grn24; repeat try unfold mf1ph10rn1,  mf2ph10rn1,   mf2ph11rn1,  mf2ph11rn2,  mf3ph12rn1, mf3ph12rn2, mf3ph11rn2,  mf1ph20rn1,  mf2ph20rn1,   mf2ph21rn1,  mf2ph21rn2,  mf3ps2rn1, mf3ps2rn2, mf3ph21rn2; repeat try simpl;\nrepeat try unfold q0000, q1000 , q0010,q0100,q0001 ,q2000,q1100 ,q1001 ,q0110,q0200,q1000_s,q0010_s,q0100_s,q0001_s,q2100,q1200,q2001,q0210,\n q0120,q2000_s, q1100_s, q1001_s, q0110_s,q0200_s,q1000_ss,q0010_ss, q0100_ss,q0001_ss,q2200,q2100_s,q1200_s,q2001_s,q0210_s,q0120_s,q2000_ss,q1100_ss ,q1001_ss,q0110_ss,q0200_ss,\n q1000_sss,q0010_sss,q0100_sss,q0001_sss;\nrepeat try unfold qb0000, qb1000 , qb0010,qb0100,qb0001 ,qb2000,qb1100 ,qb1001 ,qb0110,qb0200,qb1000_s,qb0010_s,qb0100_s,qb0001_s,qb2100,qb1200,qb2001,qb0210,\n qb0120,qb2000_s, qb1100_s, qb1001_s, qb0110_s,qb0200_s,qb1000_ss,qb0010_ss, qb0100_ss,qb0001_ss,qb2200,qb2100_s,qb1200_s,qb2001_s,qb0210_s,qb0120_s,qb2000_ss,qb1100_ss ,qb1001_ss,qb0110_ss,qb0200_ss,\n qb1000_sss,qb0010_sss,qb0100_sss,qb0001_sss. \n\nAdmitted.\n\n\n", "meta": {"author": "ajayeeralla", "repo": "compSoundProofsWOracleMoves", "sha": "8480855887a9092d16dc183ce6ed19315a3ffa96", "save_path": "github-repos/coq/ajayeeralla-compSoundProofsWOracleMoves", "path": "github-repos/coq/ajayeeralla-compSoundProofsWOracleMoves/compSoundProofsWOracleMoves-8480855887a9092d16dc183ce6ed19315a3ffa96/RRS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2676488515310879}}
{"text": "Require Import Miscy.\nRequire Import BGPSpec.\nRequire Import EvolutionLemmas.\nRequire Import Environment.\nRequire Import Claims.\nRequire Import DominantConvergence.\nRequire Import Fairness.\nRequire Import Sugar.\nImport RTC.\n\nOpaque export'.\nOpaque import'.\nOpaque eqDecide.\nOpaque enumerate.\nOpaque argMax.\n\nSection AllASTypesConverge.\n  Context `{PR:@PrefixClass}.\n  Context `{IT:@InternetTopologyClass}.\n  Context `{AT:@AttributesClass IT}.\n  Context `{IP:@InitialPrefixClass PR IT AT}.\n  Context `{OD:@OrderingClass IT AT}.\n  Context `{RU:@RuleClass IT AT PR IP OD}.\n  Context `{FA:@Convergence FairNetworkState}.\n  Context `{SP:@SinglePrefixClass PR}.\n  Context `{B:@BGPConvergence PR IT AT IP OD RU FA SP}.\n\n  Definition ASConverges x := forall r, exists i a, converges (StableRouter x r i a).\n\n  Definition ASConvergesWithRoute x := forall r, exists i a, import' (x;r) i p a <> notAvailable /\\ \n                                                   converges (StableRouter x r i a).\n\n  Global Instance convergenceDefinitions : ConvergenceDefinitions. \n    refine {|\n      ConvergentLink x r x' r' c := converges (StableLink x r x' r' c);\n      ConvergentAS := ASConverges;\n      ConvergentASWithRoute := ASConvergesWithRoute\n    |}.\n    - (* convergentASLinkConverges *)\n      intros x r x' r' c h.\n      unfold ASConverges in h.\n      specialize (h r).\n      destruct h as [i [a h]].\n      unfold const in *.\n      eapply stableRIBsOutEmptyLink.\n      refine (impliedConverges _ _ (combineConverges _ h adjRIBsOutConvergence)).\n      intros s [[iStable aStable] outEq].\n      rewrite outEq.\n      unfold StableRouter in *.\n      unfold imports.\n      rewrite iStable.\n      rewrite aStable.\n      reflexivity.\n    - (* convergentASWithRouteConverges *)\n      intros x h r.\n      destruct (h r) as [i [a [_ h']]].\n      exists i. exists a. exact h'.\n  Defined.\n  \n  Context `{@LinkConvergenceLemmas _ _ _ _ _ convergenceDefinitions}.\n\n  Section ASWithStableIncomingLinksConverges.\n    Variable x : AS.\n    Variable neqX0 : x <> x0.\n    Variable stableIn : forall r x' r' c, ConvergentLink x' r' x r (external c).\n\n    Definition ExternalAnnouncementConverges r x' r' c : {a |\n      let i := mkReceived x r x' r' (external c) in\n      converges (fun s  => a = adjRIBsIn (ribs s x r) (i, p))}.\n    Proof.\n      destruct (emptyLinkConvergence x' r' x r (external c) (stableIn _ _ _ _ )) as [a h].\n      exists a.\n      refine (impliedConverges _ _ h).\n      intuition.\n    Defined.\n\n    Definition ExternalAnnouncementsConverge :\n      {exA | converges (fun s => forall r x' r' c,\n        let i := mkReceived x r x' r' (external c) in\n        exA r x' r' c = adjRIBsIn (ribs s x r) (i, p))}.\n    Proof.\n      specialize ExternalAnnouncementConverges.\n      intros h.\n      unfold const in *; cbn in h.\n      refine ((fun h' => _) (fun r x' r' => _)); revgoals. {\n        exact (swap_ex_forall (h r x' r')). \n      } clear h; rename h' into h.\n      refine ((fun h' => _) (fun r x' => _)); revgoals. {\n        exact (swap_ex_forall (h r x')). \n      } clear h; rename h' into h.\n      refine ((fun h' => _) (fun r => _)); revgoals. {\n        exact (swap_ex_forall (h r)). \n      } clear h; rename h' into h.\n      apply swap_ex_forall in h.\n      cbn in h.\n      destruct h as [exA h].\n      exists exA.\n      apply (distributeForallConverges FairNetworkState); intros r.\n      apply (distributeForallConverges FairNetworkState); intros x'.\n      apply (distributeForallConverges FairNetworkState); intros r'.\n      apply (distributeForallConverges FairNetworkState); intros c.\n      apply h.\n    Defined.\n\n    Definition InjectedAnnouncementsConverge :\n      {injA | converges (fun s => forall r, adjRIBsIn (ribs s x r) (injected, p) = injA r)}.\n    Proof.\n      unfold const; cbn.\n      exists (const notAvailable).\n      refine (impliedConverges _ _ injectedConvergence).\n      intros s h r.\n      specialize (h x r).\n      break_match; [congruence|].\n      apply h.\n    Defined.\n\n    Definition aNonInternal {r} (nii:@nonInternalIncoming _ x r) : RoutingInformation.\n      refine (match nii with\n      | Some (x';(r';c)) => (proj1_sig ExternalAnnouncementsConverge) r x' r' c\n      | None => (proj1_sig InjectedAnnouncementsConverge) r\n      end).\n    Defined.\n\n    Lemma aNonInternalConverges : \n      converges (fun s => forall r (nii:nonInternalIncoming r), \n        adjRIBsIn (ribs s x r) (nii2i nii, p) = aNonInternal nii).\n    Proof.\n      unfold aNonInternal.\n      refine (impliedConverges _ _ (combineConverges _\n                                    (proj2_sig ExternalAnnouncementsConverge)\n                                    (proj2_sig InjectedAnnouncementsConverge))).\n      intros s [exCon injCon].\n      destruct nii as [[x' [r' c]]|].\n      - (* nii is external *) \n        rewrite exCon.\n        reflexivity.\n      - (* nii is internal *) \n        rewrite injCon.\n        reflexivity.\n    Qed.\n    Opaque aNonInternal.\n\n    Definition aNonInternalImp {r} nii := import' (x;r) (nii2i nii) p (aNonInternal nii).\n\n    Instance enumerableNii x (r:router x) : enumerable (nonInternalIncoming r).\n      unfold nonInternalIncoming.\n      eapply enumerableOption.\n    Unshelve.\n      eapply enumerableSigT.\n    Unshelve.\n      - intros x'; apply eqDecAll.\n      - intros x'. \n        eapply enumerableSigT.\n    Unshelve.\n      intros r'; apply eqDecAll.\n    Qed.\n\n    Definition niiBest (r:router x) : nonInternalIncoming r.\n      refine (proj1_sig (argMax (fun nii => (nii2i nii, @aNonInternalImp r nii)) None)). \n    Defined.\n\n    Definition localDominance r niiBest s := \n      adjRIBsIn (ribs s x r) (nii2i niiBest, p) = aNonInternal niiBest /\\\n      forall nii, (nii2i niiBest, aNonInternalImp niiBest) >= (nii2i nii, imports x r (nii2i nii) s).\n\n    Lemma niiBestConverges r : converges (localDominance r (niiBest r)).\n      refine (impliedConverges _ _ aNonInternalConverges).\n      intros s con.\n      unfold niiBest.\n      match goal with \n      |- context[argMax ?F ?D] => destruct (argMax F D) as [niiBest niiBestBeatsEveryone] \n      end.\n      constructor; cbn.\n      - apply con.\n      - intro nii.\n        unfold imports.\n        rewrite con.\n        apply niiBestBeatsEveryone. \n    Qed.\n\n    Definition aNiiBestImp r := aNonInternalImp (niiBest r).\n\n    Definition globalDominance r := forall r', aNiiBestImp r >= aNiiBestImp r'.\n\n    Instance stableIncomingDominanceSet : DominanceSet x.\n      refine {|\n        dominant := globalDominance;\n        nonInternalBest r dom := niiBest r;\n        aBest r dom := aNonInternal (niiBest r);\n        designatedDominantRouter := argMax aNiiBestImp (designatedRouter x)\n      |}.\n      intros.\n      apply decidableAll.\n    Defined.\n\n    Instance stableIncomingDominanceLemmas : DominanceLemmas x. \n      constructor.\n      - (* dominantDominatesDominants *)\n        intros r dom r' dom'.\n        cbn in dom.\n        unfold globalDominance in dom.\n        apply (dom r').\n      - (* globalDominanceInj *)\n        apply (distributeForallConverges FairNetworkState); intros r.\n        apply (distributeForallConverges FairNetworkState); intros r'.\n        refine (impliedConverges _ _ (niiBestConverges r')).\n        intros s [_ better] dom noDom' h.\n        cbn in dom, noDom'; unfold globalDominance in dom, noDom'.\n        apply noDom'; clear noDom'.\n        intros r''.\n        eapply prefTransitive; [apply dom|]. \n        eapply prefTransitive; [apply h|]; clear h.\n        eapply preferenceRelationship.\n        apply (better None).\n      - (* globalDominanceExt *)\n        apply (distributeForallConverges _); intros r.\n        apply (distributeForallConverges _); intros r'.\n        apply (distributeForallConverges _); intros xe.\n        apply (distributeForallConverges _); intros re.\n        apply (distributeForallConverges _); intros c.\n        refine (impliedConverges _ _ (niiBestConverges r')).\n        intros s [_ better] dom noDom' h.\n        cbn in dom, noDom'; unfold globalDominance in dom, noDom'.\n        apply noDom'; clear noDom'.\n        intros r''.\n        eapply prefTransitive; [apply dom|]. \n        eapply prefTransitive; [apply h|]; clear h.\n        eapply preferenceRelationship.\n        apply (better (Some (xe;(re;c)))).\n      - (* bestInstalled *)\n        apply (distributeForallConverges _); intros r.\n        refine (impliedConverges _ _ (niiBestConverges r)).\n        intros s [h _] dom.\n        apply h.\n      - (* localDominanceInj *)\n        apply (distributeForallConverges _); intros r.\n        refine (impliedConverges _ _ (niiBestConverges r)).\n        intros s [_ h] dom.\n        apply (h None).\n      - (* localDominanceExt *)\n        apply (distributeForallConverges _); intros r.\n        refine (impliedConverges _ _ (niiBestConverges r)).\n        intros s [_ h] dom.\n        intros xe re c.\n        apply (h (Some (xe;(re;c)))).\n    Qed.\n\n    Lemma ASWithStableIncomingLinksConverges : ASConverges x.\n      intros r.\n      specialize (ASWithDominantRoutersConverges x r); intros h.\n      break_match; eexists; eexists; apply h.\n    Qed.\n  End ASWithStableIncomingLinksConverges.\n\n  Lemma internalImportNotNa x r r' h a : a <> notAvailable -> \n    import' (x; r) (mkReceived x r x r' (internal h)) p a <> notAvailable.\n  Proof.\n    Transparent import'.\n    unfold import', bindRoutingInformation.\n    Opaque import'.\n    break_match; [|congruence].\n    rename p into a'.\n    intros _ h'.\n    cbn in *.\n    apply (availableGtNa a').\n    specialize (internalImportRuleEq p x r r' h a').\n    rewrite h'; unfold prefEq.\n    intuition.\n  Qed.\n\n  Lemma internalExportNotNa x r r' nii h a : a <> notAvailable -> \n    export' (x; r) (nii2i nii) (mkOutgoing x r x r' (internal h)) p a <> notAvailable.\n  Proof.\n    Transparent export'.\n    unfold export', bindRoutingInformation.\n    Opaque export'.\n    unfold nii2i.\n    destruct nii as [[? [? c]]|].\n    - (* external *)\n      cbn.\n      break_match. \n      + (* customer isn't from internal *)\n        exfalso.\n        break_match; [|crush].\n        break_match; [|crush].\n        subst_max.\n        cbn in *.\n        inversion c.\n        * eapply customerIrreflexive; eauto.\n        * eapply customerIrreflexive; eauto.\n        * eapply peerToPeerIrreflexive; eauto.\n      + (* <copy of code D> *)\n        break_match; [|congruence].\n        (* announcement is available *)\n        rename p into a'.\n        intros _ h'.\n        cbn in *.\n        apply (availableGtNa a').\n        match goal with (* match h' *)\n        | _:exportRule _ ?I _ _ _ = notAvailable |- _ => \n          specialize (internalExportRuleEq p x r r' I h a')\n        end.\n        rewrite h'; unfold prefEq.\n        intuition.\n        (* </copy of code D> *)\n    - (* injected *)\n      (* <copy of code D> *)\n      break_match; [|congruence].\n      (* announcement is available *)\n      rename p into a'.\n      intros _ h'.\n      cbn in *.\n      apply (availableGtNa a').\n      match goal with (* match h' *)\n      | _:exportRule _ ?I _ _ _ = notAvailable |- _ => \n        specialize (internalExportRuleEq p x r r' I h a')\n      end.\n      rewrite h'; unfold prefEq.\n      intuition.\n      (* </copy of code D> *)\n  Qed.\n\n  Section ASWithStableCustomersConverges.\n    Variable x : AS.\n    Variable customerAS : AS.\n    Variable neqX0 : x <> x0.\n    Variable customerASIsCustomer : x >> customerAS.\n    Variable customerASRoute : ConvergentASWithRoute customerAS.\n    Variable allCustomersConverged : forall r x' r' (cust:x >> x') c, \n                                       ConvergentLink x' r' x r (external (c2pLink cust c)).\n\n    Definition CustomerAnnouncementConverges r (cust:customer x r) :\n      {a | converges (fun s => a = adjRIBsIn (ribs s x r) (c2i cust, p))}.\n    Proof.\n      destruct cust as [x' [r' [cust c]]].\n      destruct (emptyLinkConvergence x' r' x r (external (c2pLink cust c)) (allCustomersConverged _ _ _ _ _)) as [a h].\n      exists a.\n      refine (impliedConverges _ _ h).\n      intuition.\n    Defined.\n \n    Definition CustomerAnnouncementsConverge :\n      {a | converges (fun s => forall r cust, a r cust = adjRIBsIn (ribs s x r) (c2i cust, p))}.\n    Proof.\n      specialize CustomerAnnouncementConverges.\n      intros h.\n      unfold const in *; cbn in h.\n      refine ((fun h' => _) (fun r => _)); revgoals. {\n        exact (swap_ex_forall (h r)). \n      } clear h; rename h' into h.\n      apply swap_ex_forall in h.\n      cbn in h.\n      destruct h as [exA h].\n      exists exA.\n      apply (distributeForallConverges _); intros r.\n      apply (distributeForallConverges _); intros cust.\n      apply h.\n    Qed.\n\n    Definition aCustomer {r} (cust:customer x r) : RoutingInformation :=\n      (proj1_sig CustomerAnnouncementsConverge) r cust.\n\n    Definition aCustomerConverges : \n      converges (fun s => forall r cust, aCustomer cust = adjRIBsIn (ribs s x r) (c2i cust, p)) :=\n        proj2_sig CustomerAnnouncementsConverge.\n\n    Definition aCustomerImp {r} cust := import' (x;r) (c2i cust) p (aCustomer cust).\n\n    Definition designatedCustomer : ∑ r, customer x r.\n      destruct (designatedLink customerAS x customerASIsCustomer) as [r' [r c]].\n      unfold customer.\n      exact (r; (customerAS;(r';(customerASIsCustomer;c)))).\n    Defined.\n\n    Definition bestCustomer r (cust:customer x r) : customer x r.\n      refine (proj1_sig (argMax (fun cust => (c2i cust, aCustomerImp cust)) cust)).\n    Defined.\n\n    Definition isBestCustomer r cust := forall r' cust',\n      @aCustomerImp r cust >= @aCustomerImp r' cust'.\n\n    Definition hasBestCustomer r := exists cust, isBestCustomer r cust.\n\n    Definition getCustomer r (dom:hasBestCustomer r) := proj1_sig (indefinite_description dom).\n    \n    Definition aCustomerAvailable {r} cust : isBestCustomer r cust -> aCustomer cust <> notAvailable.\n      intros custIsBest.\n      unfold ConvergentASWithRoute in *.\n      cbn in *.\n      unfold ASConvergesWithRoute in *.\n      destruct (designatedLink customerAS x customerASIsCustomer) as [rCust [r' c]].\n      specialize (emptyLinkConvergence _ _ _ _ _ (allCustomersConverged _ _ _ _ c)). \n      intros [aLink inOutRIBs] notNaCust.\n      cbn in *.\n      (* if aCustomer cust were notAvailable, the AS would converge to false! *)\n      eapply falseConvergence.\n      cbn.\n      destruct (customerASRoute rCust) as [i [a [notNa stableRouter]]].\n      refine (impliedConverges _ _ (combineConverges _ inOutRIBs\n                                   (combineConverges _ adjRIBsOutConvergence\n                                   (combineConverges _ stableRouter\n                                                       aCustomerConverges)))).\n      clear inOutRIBs stableRouter customerASRoute.\n      unfold StableRouter in *.\n      intros s [[aOutEq aInEq] [outEq [[iStable aStable] aCustIn]]].\n      rewrite outEq in aOutEq; clear outEq.\n      unfold imports in aOutEq.\n      rewrite iStable in aOutEq; clear iStable.\n      rewrite aStable in aOutEq; clear aStable.\n      revert notNa aOutEq.\n      match goal with |- ?A <> notAvailable -> _ => generalize A end. \n      intros aImp notNaImp aOutEq.\n      assert (aLink <> notAvailable) as notNaLink. {\n        rewrite aOutEq; clear aOutEq.\n        Transparent export'.\n        unfold export', bindRoutingInformation.\n        Opaque export'.\n        break_match.\n        - break_match; [|congruence].\n          apply exportToProviderAvailable.\n        - unfold mkOutgoing.\n          break_match.\n          cbn in *.\n          break_match. {\n            exfalso.\n            break_match; [|intuition; congruence].\n            break_match; [|intuition; congruence].\n            apply (customerIrreflexive (x:=x)).\n            rewrite <- e0 at 1.\n            assumption.\n          }\n          break_match; [|congruence].\n          apply exportToProviderAvailable.\n      }\n      clear aOutEq notNaImp.\n      refine (let cust' : customer x r' := _ in _). {\n        unfold customer.\n        refine (customerAS; (rCust; (_; c))).\n      }\n      assert (aCustomer cust' <> notAvailable) as notNaCust'. {\n        rewrite aCustIn.\n        subst cust'.\n        cbn in *.\n        rewrite <- aInEq.\n        assumption.\n      }\n      clear notNaLink aCustIn aInEq aImp.\n      (* cust isn't na because its better than cust', and cust' isn't na *)\n      unfold isBestCustomer in *.\n      specialize (custIsBest r' cust').\n      apply notNaCust'; clear notNaCust'.\n      unfold aCustomerImp in *.\n      rewrite notNaCust in custIsBest.\n      Transparent import'.\n      unfold import', bindRoutingInformation in custIsBest.\n      Opaque import'.\n      break_match; [|reflexivity].\n      exfalso.\n      eapply importFromCustomerAvailable.\n      eapply ltNaIsNa.\n      exact custIsBest.\n    Qed.\n\n    Instance stableCustomersDominanceSet : DominanceSet x.\n      refine {|\n        dominant := hasBestCustomer;\n        nonInternalBest r dom := _;\n        aBest r dom := _;\n        designatedDominantRouter := _\n      |}.\n      - (* nonInternalBest *)\n        exact (c2nii (bestCustomer r (getCustomer r dom))).\n      - (* a Best *)\n        exact (aCustomer (bestCustomer r (getCustomer r dom))).\n      - intros. \n        apply decidableAll.\n      - (* designatedDominantRouter *)\n        refine (_ (argMax (fun rCust => @aCustomerImp rCust.1 rCust.2) designatedCustomer)); revgoals. {\n          eapply enumerableSigT.\n          Unshelve.\n          intros r'. \n          apply eqDecAll.\n        }\n        intros [[r cust] h].\n        exists r, cust.\n        intros r' cust'.\n        specialize (h (r';cust')).\n        eauto.\n    Defined.\n\n    Instance enumerableHasBestCustomer r : enumerable (hasBestCustomer r).\n      eapply enumerableDecidable.\n    Unshelve.\n      apply decidableAll.\n    Qed.\n\n    Lemma dominantRoutersBestCustomerIsBest r\n      (dom: hasBestCustomer r) (bestCust : customer x r) :\n      (forall cust : customer x r, (c2i bestCust, aCustomerImp bestCust) >= (c2i cust, aCustomerImp cust)) ->\n      isBestCustomer r bestCust.\n    Proof.\n      intros locallyBest.\n      destruct dom as [bestCust' dom].\n      specialize (locallyBest bestCust').\n      unfold isBestCustomer in *.\n      intros r' cust'.\n      specialize (dom r' cust').\n      cbn in *.\n      eapply preferenceRelationship in locallyBest.\n      eapply prefTransitive; eauto.\n    Qed.\n   \n    Lemma customerImportNotNa r dom : \n      let cust := bestCustomer r (getCustomer r dom)\n      in  import' (x; r) (c2i cust) p (aCustomer cust) <> notAvailable.\n    Proof.\n      Transparent import'.\n      unfold import', bindRoutingInformation.\n      Opaque import'.\n      break_match. \n      - (* aCustomer is available *)\n        eapply importFromCustomerAvailable.\n      - (* aCustomer is unavailable *)\n        exfalso.\n        revert Heqr0.\n        generalize (getCustomer r dom).\n        unfold bestCustomer.\n        intros cust.\n        cbn.\n        match goal with \n        | |- context[argMax ?F ?D] => destruct (argMax F D) as [bestCust bestCustIseBest]\n        end.\n        cbn.\n        eapply aCustomerAvailable. \n        apply dominantRoutersBestCustomerIsBest; eauto.\n    Qed.\n\n    Instance stableCustomersDominanceLemmas : DominanceLemmas x. \n      constructor.\n      - (* dominantDominatesDominants *)\n        intros r dom r' dom'.\n        unfold aBestImp, iBest; cbn; unfold bestCustomer, getCustomer.\n        destruct (indefinite_description dom ) as [cust  best ].\n        destruct (indefinite_description dom') as [cust' best'].\n        cbn.\n        match goal with |- context[argMax ?F ?C] => destruct (argMax F cust ) as [bestCust  locallyBest ] end.\n        match goal with |- context[argMax ?F ?C] => destruct (argMax F cust') as [bestCust' locallyBest'] end.\n        cbn; unfold aCustomerImp in *.\n        eapply prefTransitive; [apply best|].\n        eapply preferenceRelationship.\n        apply (locallyBest cust).\n      - (* globalDominanceInj *)\n        refine (impliedConverges _ _ (combineConverges _ injectedConvergence\n                                                         aCustomerConverges)).\n        intros s [injConv aConv] r r' dom noDom'.\n        specialize (injConv x r').\n        break_match; [congruence|].\n        unfold imports.\n        rewrite injConv.\n        Transparent import'.\n        unfold import', bindRoutingInformation.\n        Opaque import'.\n        unfold aBestImp, iBest.\n        apply notNaGtNa.\n        apply customerImportNotNa.\n      - (* globalDominanceExt *)\n        apply (distributeForallConverges _); intros r.\n        apply (distributeForallConverges _); intros r'.\n        apply (distributeForallConverges _); intros xe.\n        apply (distributeForallConverges _); intros re.\n        apply (distributeForallConverges _); intros c.\n        refine (impliedConverges _ _ aCustomerConverges).\n        intros s stable dom noDom'.\n        unfold dominant in *; cbn in *.\n        unfold hasBestCustomer in *.\n        cbn in *.\n        destruct c as [cust custC| | ].\n        + (* external customer *)\n          (* there exists some router rBetter whose customer is > that the one of r' *)\n          specialize (not_ex_all_not _ _ noDom'); clear noDom'; intros noDom'.\n          refine (let custR' : customer x r' := (xe;(re;(cust;custC))) in _).\n          specialize (noDom' custR').\n          specialize (not_all_ex_not _ _ noDom'); clear noDom'; intros [rBetter noDom'].\n          specialize (not_all_ex_not _ _ noDom'); clear noDom'; intros [rBetterCust rBetterCustIsBetter].\n          specialize (stable r' custR'). \n          unfold imports.\n          unfold c2i, nii2i, c2nii in stable.\n          cbn in stable.\n          rewrite <- stable.\n          eapply prefTransitiveGtR; [|apply rBetterCustIsBetter]; clear rBetterCustIsBetter.\n          (* there exist a customer of r that is equal or better than rBetter's customer *)\n          inversion dom as [bestCust bestCustIsBest].\n          specialize (bestCustIsBest rBetter rBetterCust).\n          eapply prefTransitive; [apply bestCustIsBest|]. \n          (* the best announcement of r is even better than that customer *)\n          unfold aBestImp.\n          unfold iBest.\n          unfold nonInternalBest.\n          cbn.\n          unfold bestCustomer.\n          cbn.\n          match goal with \n          | |- context[argMax ?F ?D] => destruct (argMax F D) as [theBestCustomer theBestCustomerIsTheBest] \n          end.\n          cbn.\n          eapply preferenceRelationship.\n          apply theBestCustomerIsTheBest.\n        + (* external provider *)\n          (* <copy of A> *)\n          unfold aBestImp, iBest, nii2i, c2nii, nonInternalBest.\n          cbn.\n          unfold c2nii, bestCustomer.\n          cbn.\n          match goal with \n          | |- context[argMax ?F ?D] => destruct (argMax F D) as [bestCust bestCustIsTheBest] \n          end.\n          cbn.\n          unfold imports.\n          match goal with\n          | |- context[adjRIBsIn ?R ?I] => generalize (adjRIBsIn R I); intros a\n          end.\n          refine (_ (aCustomerAvailable bestCust _)); revgoals. {\n            apply dominantRoutersBestCustomerIsBest; eauto.\n          }\n          intros bestCustAvailable.\n          (* </copy of A> *)\n          specialize (customerGtProvider p x r bestCust); intros customerGtProvider.\n          (* <copy of B> *)\n          destruct bestCust as [? [? [? ?]]].\n          Transparent import'.\n          unfold import', bindRoutingInformation.\n          unfold isBestCustomer in *.\n          match goal with\n          | |- context[match aCustomer ?C with _ => _ end] => destruct (aCustomer C) eqn:h'\n          end; [|congruence].\n          intros.\n          (* </copy of B> *)\n          (* <copy of C> *)\n          break_match; revgoals. {\n            (* na is worse than available *)\n            cbn in *.\n            eapply gtAnythingGtNA.\n            eauto.\n          Unshelve.\n            all: first [exact xe | auto].\n          }\n          apply customerGtProvider.\n          Opaque import'.\n          (* </copy of C> *)\n        + (* external peer *)\n          (* <copy of A> *)\n          unfold aBestImp, iBest, nii2i, c2nii, nonInternalBest.\n          cbn.\n          unfold c2nii, bestCustomer.\n          cbn.\n          match goal with \n          | |- context[argMax ?F ?D] => destruct (argMax F D) as [bestCust bestCustIsTheBest] \n          end.\n          cbn.\n          unfold imports.\n          match goal with\n          | |- context[adjRIBsIn ?R ?I] => generalize (adjRIBsIn R I); intros a\n          end.\n          refine (_ (aCustomerAvailable bestCust _)); revgoals. {\n            apply dominantRoutersBestCustomerIsBest; eauto.\n          }\n          intros bestCustAvailable.\n          (* </copy of A> *)\n          specialize (customerGtPeer p x r bestCust); intros customerGt.\n          (* <copy of B> *)\n          destruct bestCust as [? [? [? ?]]].\n          Transparent import'.\n          unfold import', bindRoutingInformation.\n          unfold isBestCustomer in *.\n          match goal with\n          | |- context[match aCustomer ?C with _ => _ end] => destruct (aCustomer C) eqn:h'\n          end; [|congruence].\n          (* </copy of B> *)\n          (* <copy of C> *)\n          intros.\n          break_match; revgoals. {\n            (* na is worse than available *)\n            cbn in *.\n            eapply gtAnythingGtNA.\n            eauto.\n          Unshelve.\n            all: first [exact xe | auto].\n          }\n          apply customerGt.\n          Opaque import'.\n          (* </copy of C> *)\n      - (* bestInstalled *)\n        apply (distributeForallConverges _); intros r.\n        apply (distributeForallConverges _); intros dom.\n        refine (impliedConverges _ _ aCustomerConverges).\n        intros s stable.\n        symmetry.\n        apply stable.\n      - (* localDominanceInj *)\n        refine (impliedConverges _ _ (combineConverges _ injectedConvergence\n                                                         aCustomerConverges)).\n        intros s [injConv aConv] r dom.\n        specialize (injConv x r).\n        break_match; [congruence|].\n        unfold imports.\n        rewrite injConv.\n        Transparent import'.\n        unfold import', bindRoutingInformation.\n        Opaque import'.\n        apply GtImpliesGe.\n        apply preferenceRelationshipGt.\n        unfold aBestImp, iBest.\n        apply notNaGtNa.\n        apply customerImportNotNa.\n      - (* localDominanceExt *)\n        apply (distributeForallConverges _); intros r.\n        apply (distributeForallConverges _); intros dom.\n        refine (impliedConverges _ _ aCustomerConverges).\n        intros s stable xe re c.\n        cbn.\n        destruct c.\n        + (* customer *)\n          unfold aBestImp.\n          unfold iBest.\n          unfold nonInternalBest.\n          cbn.\n          unfold bestCustomer.\n          cbn.\n          match goal with \n          | |- context[argMax ?F ?D] => destruct (argMax F D) as [theBestCustomer theBestCustomerIsTheBest] \n          end.\n          cbn.\n          unfold aCustomerImp in *.\n          refine (let cust : customer x r := (xe;(re;(h;c))) in _).\n          specialize (theBestCustomerIsTheBest cust).\n          cbn in *.\n          eapply prefTransitive; [|apply theBestCustomerIsTheBest].\n          unfold imports.\n          rewrite stable.\n          subst cust.\n          cbn.\n          unfold aCustomer.\n          apply prefReflexive.\n        + (* provider *)\n          (* <copy of A> *)\n          unfold aBestImp, iBest, nii2i, c2nii, nonInternalBest.\n          cbn.\n          unfold c2nii, bestCustomer.\n          cbn.\n          match goal with \n          | |- context[argMax ?F ?D] => destruct (argMax F D) as [bestCust bestCustIsTheBest] \n          end.\n          cbn.\n          unfold imports.\n          match goal with\n          | |- context[adjRIBsIn ?R ?I] => generalize (adjRIBsIn R I); intros a\n          end.\n          refine (_ (aCustomerAvailable bestCust _)); revgoals. {\n            apply dominantRoutersBestCustomerIsBest; eauto.\n          }\n          intros bestCustAvailable.\n          (* </copy of A> *)\n          specialize (customerGtProvider p x r bestCust); intros customerGt.\n          (* <copy of B> *)\n          destruct bestCust as [? [? [? ?]]].\n          Transparent import'.\n          unfold import', bindRoutingInformation.\n          unfold isBestCustomer in *.\n          match goal with\n          | |- context[match aCustomer ?C with _ => _ end] => destruct (aCustomer C) eqn:h'\n          end; [|congruence].\n          intros.\n          (* </copy of B> *)\n          apply GtImpliesGe.\n          apply preferenceRelationshipGt.\n          (* <copy of C> *)\n          break_match; revgoals. {\n            (* na is worse than available *)\n            cbn in *.\n            eapply gtAnythingGtNA.\n            eauto.\n          Unshelve.\n            all: first [exact xe | auto].\n          }\n          apply customerGt.\n          Opaque import'.\n          (* </copy of C> *)\n        + (* peer *)\n          (* <copy of A> *)\n          unfold aBestImp, iBest, nii2i, c2nii, nonInternalBest.\n          cbn.\n          unfold c2nii, bestCustomer.\n          cbn.\n          match goal with \n          | |- context[argMax ?F ?D] => destruct (argMax F D) as [bestCust bestCustIsTheBest] \n          end.\n          cbn.\n          unfold imports.\n          match goal with\n          | |- context[adjRIBsIn ?R ?I] => generalize (adjRIBsIn R I); intros a\n          end.\n          refine (_ (aCustomerAvailable bestCust _)); revgoals. {\n            apply dominantRoutersBestCustomerIsBest; eauto.\n          }\n          intros bestCustAvailable.\n          (* </copy of A> *)\n          specialize (customerGtPeer p x r bestCust); intros customerGt.\n          (* <copy of B> *)\n          destruct bestCust as [? [? [? ?]]].\n          Transparent import'.\n          unfold import', bindRoutingInformation.\n          unfold isBestCustomer in *.\n          match goal with\n          | |- context[match aCustomer ?C with _ => _ end] => destruct (aCustomer C) eqn:h'\n          end; [|congruence].\n          intros.\n          (* </copy of B> *)\n          apply GtImpliesGe.\n          apply preferenceRelationshipGt.\n          (* <copy of C> *)\n          break_match; revgoals. {\n            (* na is worse than available *)\n            cbn in *.\n            eapply gtAnythingGtNA.\n            eauto.\n          Unshelve.\n            all: first [exact xe | auto].\n          }\n          apply customerGt.\n          Opaque import'.\n          (* </copy of C> *)\n    Qed.\n\n    Lemma ASWithStableCustomersConverges : ConvergentASWithRoute x.\n      intros r.\n      specialize (ASWithDominantRoutersConverges x r); intros h.\n      break_match.\n      - (* r is dominant *)\n        eexists.\n        eexists.\n        constructor; [|apply h].\n        unfold iBest; cbn.\n        apply customerImportNotNa.\n      - (* r not dominant *)\n        eexists.\n        eexists.\n        constructor; [|apply h].\n        unfold aBestImpExp, aBestImp, iBest; cbn.\n        apply internalImportNotNa.\n        apply internalExportNotNa.\n        apply customerImportNotNa.\n    Qed.\n  End ASWithStableCustomersConverges.\n\n  Section ASWithInitialAnnouncementConverges.\n    Instance initialASDominanceSet : DominanceSet x0.\n      refine {|\n        dominant r := r = r0;\n        nonInternalBest r dom := None;\n        aBest r dom := available a0;\n        designatedDominantRouter := exist _ r0 _\n      |}.\n      - intros r.\n        constructor.\n        destruct (r =? r0); eauto.\n      - reflexivity.\n    Defined.\n\n    Lemma injectedGtExternal' : forall r xe re ce a,\n      ~(@le RoutingInformation _ \n        (import' (x0;r0) injected p (available a0))\n        (import' (x0;r) (mkReceived x0 r xe re (external ce)) p a)).\n    Proof.\n      intros.\n      Transparent import'. \n      unfold import', bindRoutingInformation; cbn.\n      break_match.\n      - apply injectedGtExternal.\n      - specialize importFromInjectedAvailable; intros h.\n        match goal with | |- _ < ?A => destruct A eqn:? end.\n        + eapply availableGtNa.\n        + unfold x0, a0, r0 in *.\n          congruence. \n    Qed.\n\n    Instance initialASDominanceLemmas : DominanceLemmas x0.\n      constructor.\n      - (* dominantDominatesDominants *)\n        intros.\n        cbn in *.\n        subst_max.\n        apply prefReflexive.\n      - (* globalDominanceInj *)\n        refine (impliedConverges _ _ injectedConvergence).\n        intros s h r r' dom noDom.\n        unfold aBestImp, imports.\n        cbn in *.\n        subst_max.\n        rewrite h; clear h.\n        break_match. {\n          assert (r' = r0) by crush.\n          congruence.\n        }\n        Transparent import'. \n        cbn.\n        specialize importFromInjectedAvailable; intros h.\n        match goal with | |- _ < ?A => destruct A eqn:? end.\n        + eapply availableGtNa.\n        + unfold x0, a0, r0 in *.\n          congruence. \n        Opaque import'. \n      - (* globalDominanceExt *)\n        refine (impliedConverges _ _ injectedConvergence).\n        intros s h r r' xe re ce dom noDom.\n        cbn in *.\n        unfold aBestImp, imports.\n        subst_max.\n        eapply injectedGtExternal'.\n      - (* bestInstalled *)\n        refine (impliedConverges _ _ injectedConvergence).\n        intros s h r dom.\n        cbn in *.\n        rewrite h; clear h.\n        subst_max.\n        break_match; [|congruence].\n        reflexivity.\n      - (* localDominanceInj *)\n        refine (impliedConverges _ _ injectedConvergence).\n        intros s h r dom.\n        unfold aBestImp, imports.\n        cbn in *.\n        rewrite h; clear h.\n        subst_max.\n        break_match; [|congruence].\n        apply prefReflexive.\n      - (* localDominanceExt *)\n        refine (impliedConverges _ _ injectedConvergence).\n        intros s x r dom x' r' c.\n        cbn in *.\n        apply GtImpliesGe.\n        apply preferenceRelationshipGt.\n        unfold imports, aBestImp.\n        cbn in *.\n        subst_max.\n        eapply injectedGtExternal'.\n    Qed.\n\n    Lemma ASWithInitialAnnouncementConverges : ConvergentASWithRoute x0.\n      intros r.\n      specialize (ASWithDominantRoutersConverges x0 r); intros h.\n      break_match.\n      - (* r is dominant *)\n        eexists.\n        eexists.\n        constructor; [|apply h].\n        unfold iBest; cbn.\n        cbn in *.\n        break_match; [|congruence].\n        subst_max.\n        unfold x0, a0, r0 in *.\n        Transparent import'.\n        apply importFromInjectedAvailable.\n        Opaque import'.\n      - (* r not dominant *)\n        eexists.\n        eexists.\n        constructor; [|apply h].\n        unfold aBestImpExp, aBestImp, iBest; cbn.\n        apply internalImportNotNa.\n        refine (_ : export' _ (nii2i None) _ _ _ <> _).\n        apply internalExportNotNa.\n        specialize (dominatorDom x0 r n); intros h'.\n        cbn in h'.\n        rewrite h'.\n        Transparent import'.\n        apply importFromInjectedAvailable.\n        Opaque import'.\n    Qed.\n  End ASWithInitialAnnouncementConverges.\n\n  Instance asConvergenceLemmas : ASConvergenceLemmas := {|\n    InitialASConverges := ASWithInitialAnnouncementConverges;\n    ASWithConvergentCustomersIsConvergent := ASWithStableCustomersConverges;\n    ASWithConvergentNeighborsIsConvergent := ASWithStableIncomingLinksConverges \n  |}.\nEnd AllASTypesConverge.\n", "meta": {"author": "uwplse", "repo": "bagpipe", "sha": "67a38c4c6def7fb270a045b4afa668d22e293be7", "save_path": "github-repos/coq/uwplse-bagpipe", "path": "github-repos/coq/uwplse-bagpipe/bagpipe-67a38c4c6def7fb270a045b4afa668d22e293be7/src/bagpipe/coq/GaoRexford/Proof/InternalConvergence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2676187721427645}}
{"text": "Require Import Coq.Logic.Classical.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Sets.Ensembles.\nRequire 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.Relation_ext.\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_computable.\nRequire Import CertiGraph.msl_application.Graph.\nRequire Import CertiGraph.msl_application.UnionFindGraph.\nRequire Import CertiGraph.msl_application.GList.\n\nLocal Open Scope logic.\n\nSection GList_UnionFind.\n\n  Context {pSGG: pPointwiseGraph_GList}.\n  Context {sSGG: sPointwiseGraph_GList nat unit}.\n\n  Definition SGraph := (PointwiseGraph addr (addr * unit) (nat * addr) unit).\n\n  Definition LGraph := (@LGraph addr (addr * unit) _ _ nat unit unit).\n  Definition UFGraph := (@UFGraph addr (addr * unit) _ _ is_null_SGBA (fun x => (x, tt)) nat unit unit).\n  \n  Definition UFGraph_LGraph (G: UFGraph): LGraph := lg_gg G.\n  Definition LGraph_SGraph (G: LGraph): SGraph := Graph_PointwiseGraph G.\n\n  Local Coercion UFGraph_LGraph: UFGraph >-> LGraph.\n  Local Coercion LGraph_SGraph: LGraph >-> SGraph.\n  \n  Local Identity Coercion ULGraph_LGraph: LGraph >-> UnionFindGraph.LGraph.\n  Local Identity Coercion LGraph_LabeledGraph: UnionFindGraph.LGraph >-> LabeledGraph.\n  Local Coercion pg_lg: LabeledGraph >-> PreGraph.\n  Local Identity Coercion SGraph_SpatialGraph: SGraph >-> PointwiseGraph.\n\n  Global Existing Instance fml.\n\n  #[export] Instance maGraph(G: UFGraph): MathGraph G is_null_SGBA := maGraph G.\n  #[export] Instance finGraph (G: UFGraph): FiniteGraph G := finGraph G.\n  #[export] Instance liGraph (G: UFGraph):  LstGraph G (fun x => (x, tt)) := liGraph G.\n\n  Definition vgamma := (@vgamma addr (addr * unit) SGBA_VE SGBA_EE is_null_SGBA (fun x => (x, tt)) nat unit unit).\n\n  Definition Graph_gen_redirect_parent (g: UFGraph) (x: addr) (pa: addr) (H: weak_valid g pa) (Hv: vvalid g x) (Hn: ~ reachable g pa x): UFGraph :=\n    Graph_gen_redirect_parent g x pa H Hv Hn.\n\n  Lemma graph_gen_redirect_parent_ramify: forall (g: UFGraph) x r pa root (H: weak_valid g root) (Hv: vvalid g x) (Hn: ~ reachable g root x),\n      vgamma g x = (r, pa) -> root <> null -> \n      (vertices_at (vvalid g) g: pred) \n        |-- vertex_at x (r, pa) * (vertex_at x (r, root) -* vertices_at (vvalid g) (Graph_gen_redirect_parent g x root H Hv Hn)).\n  Proof.\n    intros. assert (vgamma (Graph_gen_redirect_parent g x root H Hv Hn) x = (r, root)). {\n      simpl in *. remember (updateEdgeFunc (dst (lg_gg g)) (x, tt) root (x, tt)).\n      inversion H0. unfold vgamma, UnionFindGraph.vgamma. simpl. f_equal. unfold updateEdgeFunc in *. destruct (equiv_dec (x, tt) (x, tt)).\n      2: compute in c; exfalso; apply c; auto. subst a. destruct (SGBA_VE root null); [exfalso| ]; auto.\n    } apply vertices_at_ramif_1; auto. eexists. split; [|split].\n    - apply Ensemble_join_Intersection_Complement.\n      + unfold Included, In; intro y. intros. subst. auto.\n      + intros; destruct_eq_dec x x0; auto.\n    - apply Ensemble_join_Intersection_Complement.\n      + unfold Included, In; intro y. intros. subst. auto.\n      + intros; destruct_eq_dec x x0; auto.\n    - rewrite vertices_identical_spec. simpl. intros. change (lg_gg g) with (g: LGraph).\n      rewrite Intersection_spec in H3. destruct H3. unfold Complement, In in H4. unfold vgamma, UnionFindGraph.vgamma. simpl. unfold updateEdgeFunc.\n      destruct (equiv_dec (x, tt) (x0, tt)); auto. compute in e. exfalso. inversion e. auto.\n  Qed.\n\n  Definition ggrp_rel (g : UFGraph) (x root : addr) (g' : UFGraph) : Prop :=\n    exists H1 H2 H3, g' = Graph_gen_redirect_parent g x root H1 H2 H3.\n\n  Lemma graph_gen_redirect_parent_ramify_rel: forall (g: UFGraph) x r pa root g',\n      ggrp_rel g x root g' ->\n      vgamma g x = (r, pa) -> root <> null -> \n      (vertices_at (vvalid g) g: pred) \n        |-- vertex_at x (r, pa) * (vertex_at x (r, root) -* vertices_at (vvalid g) g').\n  Proof. intros g x r pa root g' [Ha [Hb [Hc Heq]]] ? ?. subst g'. apply graph_gen_redirect_parent_ramify; auto. Qed. \n\n  Definition Graph_vgen (G: UFGraph) (x: addr) (d: nat) : UFGraph := Graph_vgen G x d.\n\n  Lemma graph_vgen_ramify: forall (g: UFGraph) x r1 r2 pa,\n      vvalid g x -> vgamma g x = (r1, pa) -> (vertices_at (vvalid g) g: pred) |-- vertex_at x (r1, pa) * (vertex_at x (r2, pa) -* vertices_at (vvalid g) (Graph_vgen g x r2)).\n  Proof.\n    intros. assert (vgamma (Graph_vgen g x r2) x = (r2, pa)). {\n      simpl in *. inversion H0. unfold vgamma, UnionFindGraph.vgamma. simpl. f_equal. unfold update_vlabel. destruct (equiv_dec x x); auto. compute in c. exfalso; auto.\n    } apply vertices_at_ramif_1; auto. eexists. split; [|split].\n    - apply Ensemble_join_Intersection_Complement.\n      + unfold Included, In; intro y. intros. subst. auto.\n      + intros; destruct_eq_dec x x0; auto.\n    - apply Ensemble_join_Intersection_Complement.\n      + unfold Included, In; intro y. intros. subst. auto.\n      + intros; destruct_eq_dec x x0; auto.\n    - rewrite vertices_identical_spec. simpl. intros. change (lg_gg g) with (g: LGraph).\n      rewrite Intersection_spec in H2. destruct H2. unfold Complement, In in H3. unfold vgamma, UnionFindGraph.vgamma. simpl.\n      unfold update_vlabel. f_equal. destruct (equiv_dec x x0); auto. hnf in e. exfalso; auto.\n  Qed.\n\n  Lemma uf_under_bound_redirect_parent: forall (g: UFGraph) root x (Hw : weak_valid g root) (Hv : vvalid g x) (Hr: ~ reachable g root x),\n      uf_root g x root -> uf_under_bound id g -> uf_under_bound id (Graph_gen_redirect_parent g x root Hw Hv Hr).\n  Proof.\n    intros. hnf in H0 |-* . simpl. unfold uf_bound, id in *. intros. destruct p as [p l]. destruct H. destruct (redirect_to_root g (liGraph g) _ _ _ _ _ Hv Hr H4 H2 H3).\n    - destruct H5. apply H0; auto.\n    - destruct H5 as [? [l1 [? ?]]]. subst l. subst v. simpl. destruct H as [l2 ?]. destruct l2 as [? l2]. assert (a = x) by (destruct H as [[? _] ?]; simpl in H; auto).\n      subst a. destruct l2. 1: destruct H as [[_ ?] ?]; simpl in H; subst root; exfalso; apply Hr; apply reachable_refl; auto.\n      pose proof (reachable_by_path_merge _ _ _ _ _ _ _ H7 H). unfold path_glue in H3. simpl in H3. destruct H3 as [[_ ?] [? _]].\n      rewrite <- H5 in H3. pose proof (H0 _ H1 _ H6 H3). simpl in H8.\n      clear -H8. rewrite app_length in *. simpl in *. intuition.\n  Qed.\n\n  Lemma uf_under_bound_redirect_parent_lt: forall (g: UFGraph) root x (Hw : weak_valid g root) (Hv : vvalid g x) (Hr: ~ reachable g root x),\n      vlabel g x < vlabel g root -> (forall y, reachable g root y -> root = y) -> uf_under_bound id g -> uf_under_bound id (Graph_gen_redirect_parent g x root Hw Hv Hr).\n  Proof.\n    intros. hnf in H1 |-* . simpl. unfold uf_bound, id in *. intros. destruct p as [p l]. destruct (redirect_to_root g (liGraph g) _ _ _ _ _ Hv Hr H0 H3 H4).\n    - destruct H5; apply H1; auto.\n    - destruct H5 as [? [l1 [? ?]]]. subst l. clear H4. subst v. simpl. destruct H7 as [[_ ?] [? _]]. specialize (H1 _ Hv _ H5 H4). simpl in H1. rewrite app_length. simpl length.\n      clear - H H1. unfold UFGraph_LGraph in H. assert (vlabel (lg_gg g) x < vlabel (lg_gg g) root) by intuition. intuition.\n  Qed.\n\n  Lemma uf_under_bound_redirect_parent_eq: forall (g: UFGraph) root x (Hw : weak_valid g root) (Hv : vvalid g x) (Hr: ~ reachable g root x),\n      vlabel g x = vlabel g root -> (forall y, reachable g root y -> root = y) -> uf_under_bound id g ->\n      uf_under_bound id (Graph_vgen (Graph_gen_redirect_parent g x root Hw Hv Hr) root (vlabel g root + 1)).\n  Proof.\n    intros. hnf in H1 |-* . simpl. unfold uf_bound, id, update_vlabel in *. intros. destruct p as [p l]. destruct (redirect_to_root g (liGraph g) _ _ _ _ _ Hv Hr H0 H3 H4).\n    - destruct H5. specialize (H1 _ H2 _ H5 H6). simpl in H1 |-* . clear -H1. destruct (equiv_dec root v); [hnf in e; subst v |]; intuition.\n    - destruct H5 as [? [l1 [? ?]]]. subst l. clear H4. subst v. destruct (equiv_dec root root). 2: compute in c; exfalso; apply c; auto. simpl. destruct H7 as [[_ ?] [? _]].\n      specialize (H1 _ Hv _ H5 H4). simpl in H1. rewrite app_length. simpl. clear -H H1. unfold UFGraph_LGraph in *. assert (vlabel (lg_gg g) x = vlabel g root) by intuition. intuition.\n  Qed.\n\n  Definition make_set_Graph (default_dv: nat) (default_de: unit) (default_dg: unit) (v: addr) (g: UFGraph) (Hn: v <> null) (Hi: ~ vvalid g v) : UFGraph := make_set_Graph default_dv default_de default_dg v g Hn Hi.\nEnd GList_UnionFind.\n", "meta": {"author": "CertiGraph", "repo": "CertiGraph", "sha": "1be51414c139f8bc16b3e22f72989e454c37ce3c", "save_path": "github-repos/coq/CertiGraph-CertiGraph", "path": "github-repos/coq/CertiGraph-CertiGraph/CertiGraph-1be51414c139f8bc16b3e22f72989e454c37ce3c/msl_application/GList_UnionFind.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2676187721427645}}
{"text": "Require Import Coq.Lists.List\n        Coq.Strings.String\n        Coq.Arith.Arith\n        Coq.omega.Omega\n        Fiat.Common.ilist2\n        Fiat.Common.StringBound\n        Fiat.ADT\n        Fiat.ADT.ComputationalADT\n        Fiat.ADTNotation\n        Fiat.ADTRefinement\n        Fiat.ADTRefinement.BuildADTRefinements\n        Fiat.QueryStructure.Specification.Representation.Heading\n        Fiat.QueryStructure.Specification.Representation.Tuple.\n\n(* Computational ADT definitions for Tuples. *)\nSection TupleADT.\n\n  Open Scope string_scope.\n  Open Scope methSig_scope.\n  Open Scope consSig_scope.\n  Open Scope cMethDef_scope.\n  Open Scope cMethDefParsing_scope.\n  Open Scope cConsDef_scope.\n\n  Variable heading : Heading.   (* The heading of the tuple. *)\n\n  (* Tuple Initialization *)\n  Definition Tuple_Init := \"Init\".\n\n  Definition InitTupleDom := @Tuple heading.\n\n  Definition InitTupleSig : consSig :=\n    {| consID := Tuple_Init;\n       consDom := Vector.to_list (AttrList (HeadingRaw heading)) |}.\n\n  (*Fixpoint InitTuple heading' :\n    constructorType (@Tuple heading') (Vector.to_list (AttrList (HeadingRaw heading'))).\n      refine (match heading' return\n                    constructorType (@Tuple heading') (Vector.to_list (AttrList (HeadingRaw heading'))) with\n              |\n              |\n\n  Definition InitTupleDef :=\n    Def Constructor Tuple_Init (inits : InitTupleDom) : rep :=\n      InitTuple inits. *)\n\n  (* Getters and Setters for Tuples *)\n\n  Definition GetTupleSig id aType :=\n    Method (\"Get\" ++ id) : rep -> rep * aType.\n\n  Definition SetTupleSig id aType :=\n    Method (\"Set\" ++ id) : rep * aType -> rep.\n\n  Definition TupleSigs'\n             {n'}\n             (HeadingTypes : Vector.t Type n')\n             (HeadingNames : Vector.t string n')\n    : Vector.t methSig (n' * 2) :=\n    Vector.rect2\n      (fun (n : nat) (_ : Vector.t Type n) (_ : Vector.t string n) =>\n         Vector.t methSig (n * 2)) (Vector.nil methSig)\n      (fun (n : nat) (_ : Vector.t Type n) (_ : Vector.t string n)\n           (TupleSigs' : Vector.t methSig (n * 2)) (aType : Type)\n           (id : string) =>\n         Vector.cons methSig (GetTupleSig id aType) (S (n * 2))\n                     (Vector.cons methSig (SetTupleSig id aType) (n * 2) TupleSigs'))\n      HeadingTypes HeadingNames.\n\n  Definition TupleSigs :=\n    TupleSigs' (AttrList heading)\n               (HeadingNames heading).\n\n  Definition GetTupleDef\n             (attr : Fin.t (NumAttr heading)) :\n    cMethDef (Rep := @Tuple heading) (GetTupleSig (Vector.nth (HeadingNames heading) attr)\n                                                  (Vector.nth (AttrList heading) attr)) :=\n    Def Method _ (msg : rep) \n    : rep * (Vector.nth (AttrList heading) attr) :=\n      (msg, ith2 msg attr).\n  \n  Definition SetTupleDef\n             (attr : Fin.t (NumAttr heading)) :\n    cMethDef (Rep := @Tuple heading) (SetTupleSig (Vector.nth (HeadingNames heading) attr)\n                                                  (Vector.nth (AttrList heading) attr)) :=\n    (Def Method1 _ (msg : @Tuple heading) (val : Vector.nth (AttrList heading) attr) : rep :=\n      replace_Index2 _ msg attr val)%cMethDefParsing.\n\n  Definition TupleDefs'\n           {n'}\n           (HeadingTypes : Vector.t Type n')\n           (HeadingNames : Vector.t string n')\n    : (forall (attr : Fin.t n'),\n          cMethDef (Rep := @Tuple heading) (GetTupleSig (Vector.nth HeadingNames attr)\n                                                        (Vector.nth HeadingTypes attr)))\n      -> (forall (attr : Fin.t n'),\n             cMethDef (Rep := @Tuple heading) (SetTupleSig (Vector.nth HeadingNames attr)\n                                                           (Vector.nth HeadingTypes attr)))\n      -> ilist (B := cMethDef (Rep := @Tuple heading))\n            (TupleSigs' HeadingTypes HeadingNames) :=\n    Vector.rect2\n      (fun n HeadingTypes HeadingNames =>\n         (forall (attr : Fin.t n),\n             cMethDef (Rep := @Tuple heading) (GetTupleSig (Vector.nth HeadingNames attr)\n                                                           (Vector.nth HeadingTypes attr)))\n         -> (forall (attr : Fin.t n),\n                cMethDef (Rep := @Tuple heading) (SetTupleSig (Vector.nth HeadingNames attr)\n                                                              (Vector.nth HeadingTypes attr)))\n         -> ilist (n := n * 2) (B := cMethDef (Rep := @Tuple heading))\n                  (TupleSigs' HeadingTypes HeadingNames)) (fun _ _ => ())\n      (fun n HeadingTypes HeadingNames\n           TupleDefs' aType id\n           GetTupleDef' SetTupleDef' =>\n         icons (GetTupleDef' Fin.F1)\n               (icons (SetTupleDef' Fin.F1)\n                      (TupleDefs' (fun n => GetTupleDef' (Fin.FS n))\n                                  (fun n => SetTupleDef' (Fin.FS n)))))\n      HeadingTypes HeadingNames.\n\n    Definition TupleDefs :=\n      TupleDefs' (AttrList heading) (HeadingNames heading)\n                 GetTupleDef SetTupleDef.\n\n    (* Tuple ADT Definitions *)\n    Definition TupleADTSig : ADTSig :=\n      BuildADTSig (Vector.cons _ InitTupleSig _ (Vector.nil _))\n                  TupleSigs.\n\n    (*Definition TupleADT : cADT TupleADTSig :=\n      BuildcADT (icons InitTupleDef inil) TupleDefs. *)\n\n    (* Support for building messages. *)\n\n    (*Definition ConstructTuple subtopics :=\n      CallConstructor TupleADT Tuple_Init subtopics. *)\n\n    (* Support for calling message getters. *)\n    Lemma BuildGetTupleMethodID_ibound'\n          {n'}\n          (HeadingTypes : Vector.t Type n')\n          (HeadingNames : Vector.t string n')\n      : forall (idx : Fin.t n'),\n        Vector.nth (Vector.map methID (TupleSigs' HeadingTypes HeadingNames))\n                   (Fin.depair idx Fin.F1) =\n        (\"Get\" ++ Vector.nth HeadingNames idx)%string.\n    Proof.\n      pattern n', HeadingTypes, HeadingNames.\n      eapply Vector.rect2.\n      - intro; inversion idx.\n      - intros; generalize dependent idx; intro; revert v1 v2 H.\n        pattern n, idx.\n        eapply Fin.rectS; simpl; intros; eauto.\n    Qed.\n\n    Definition BuildGetTupleMethodID\n               (idx : Fin.t (NumAttr heading))\n    : BoundedString (Vector.map methID TupleSigs) :=\n      {| bindex := (\"Get\" ++ (Vector.nth (HeadingNames heading) idx))%string;\n         indexb := {| ibound := Fin.depair idx (@Fin.F1 1);\n                      boundi := BuildGetTupleMethodID_ibound' _ _ idx |}\n      |}.\n\n    (*Definition CallTupleGetMethod\n               (r : Tuple)\n               idx\n      := cMethods TupleADT (ibound (indexb (BuildGetTupleMethodID idx))) r. *)\n\n    (* Support for calling message setters. *)\n    Lemma BuildSetTupleMethodID_ibound\n          {n'}\n          (HeadingTypes : Vector.t Type n')\n          (HeadingNames : Vector.t string n')\n      : forall (idx : Fin.t n'),\n        Vector.nth (Vector.map methID (TupleSigs' HeadingTypes HeadingNames))\n                   (Fin.depair idx (Fin.FS Fin.F1)) =\n        (\"Set\" ++ Vector.nth HeadingNames idx)%string.\n    Proof.\n      pattern n', HeadingTypes, HeadingNames.\n      eapply Vector.rect2.\n      - intro; inversion idx.\n      - intros; generalize dependent idx; intro; revert v1 v2 H.\n        pattern n, idx.\n        eapply Fin.rectS; simpl; intros; eauto.\n    Qed.\n\n    Definition BuildSetTupleMethodID\n               (idx : Fin.t (NumAttr heading))\n    : BoundedString (Vector.map methID TupleSigs) :=\n      {| bindex := (\"Set\" ++ (Vector.nth (HeadingNames heading) idx))%string;\n         indexb := {| ibound := Fin.depair idx (Fin.FS Fin.F1);\n                      boundi := BuildSetTupleMethodID_ibound _ _ idx |}\n      |}.\n\n    (*Definition CallTupleSetMethod\n               (r : Tuple)\n               idx\n      := cMethods TupleADT (ibound (indexb (BuildSetTupleMethodID idx))) r. *)\n\nEnd TupleADT.\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/TupleADT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2675492143133058}}
{"text": "Require Import BagsInterface.\nRequire Import AdditionalLemmas.\nRequire Import EnsembleListEquivalence.\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    | appcontext [ ?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\nRequire Import String Arith.\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\nRequire Import QueryStructureNotations.\nRequire Import ListImplementation.\nRequire Import BagsOfTuples.\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. *)\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\nTactic 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        |- appcontext [ 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 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 : BoundedString) 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    | [ |- appcontext [\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", "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/Bags/BagsTactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2675492143133058}}
{"text": "From stdpp Require Export coPset.\nFrom iris.algebra Require Import gmap auth agree gset coPset.\nFrom iris.proofmode Require Import tactics.\nFrom iris.base_logic.lib Require Export own.\nFrom iris.base_logic.lib Require Import wsat.\nFrom iris.prelude Require Import options.\nExport invG.\nImport uPred.\n\n(** * Suffix subsets *)\nFixpoint coPset_suffixes_of_raw (p : positive) (E: coPset_raw) : coPset_raw :=\n  match p with\n  | 1 => E\n  | p~0 => coPNode' false (coPset_suffixes_of_raw p E) (coPLeaf false)\n  | p~1 => coPNode' false (coPLeaf false) (coPset_suffixes_of_raw p E)\n  end%positive.\nLemma coPset_suffixes_of_wf p E : coPset_wf E → coPset_wf (coPset_suffixes_of_raw p E).\nProof. induction p; simpl; eauto. Qed.\nDefinition coPset_suffixes_of (p : positive) (E : coPset) : coPset :=\n  coPset_suffixes_of_raw p (`E) ↾ coPset_suffixes_of_wf _ _ (proj2_sig E).\nLemma elem_coPset_suffixes_of p q E : p ∈ coPset_suffixes_of q E ↔ ∃ q', (p = Papp q' q) ∧ q' ∈ E.\nProof.\n  unfold elem_of, coPset_elem_of; simpl; split.\n  - revert p; induction q; intros [?|?|]; simpl;\n      rewrite ?coPset_elem_of_node; naive_solver.\n  - by intros [q' (->&Helem)]; induction q; simpl; rewrite ?coPset_elem_of_node.\nQed.\nLemma coPset_suffixes_of_top p :\n  coPset_suffixes_of p ⊤ = coPset_suffixes p.\nProof.\n  rewrite -leibniz_equiv_iff => x.\n  rewrite elem_coPset_suffixes_of elem_coPset_suffixes. naive_solver set_solver.\nQed.\n\nDefinition coPset_inl (E: coPset) : coPset := coPset_suffixes_of (positives_flatten (1::nil))%positive E.\nDefinition coPset_inr (E: coPset) : coPset := coPset_suffixes_of (positives_flatten (2::nil))%positive E.\n\nLemma coPset_suffixes_of_infinite p E:\n  (¬ set_finite E) → (¬ set_finite (coPset_suffixes_of p E)).\nProof.\n  rewrite ?coPset_finite_spec; simpl. intros Hsuff.\n  induction p; simpl; rewrite ?coPset_finite_node; rewrite ?andb_True //=; naive_solver.\nQed.\n\nLemma coPset_inl_inr_disj E1 E2 :\n  coPset_inl E1 ## coPset_inr E2.\nProof.\n  intros q. rewrite ?elem_coPset_suffixes_of.\n  intros (q1'&Heq1&Hin1) (q2'&Heq2&Hin2).\n  rewrite Heq1 in Heq2.\n  apply positives_flatten_suffix_eq in Heq2 => //=.\nQed.\n\nDefinition AlwaysEn := coPset_inl ⊤.\nDefinition MaybeEn := coPset_inr.\n\nLocal Hint Extern 0 (AlwaysEn ## MaybeEn _) => apply coPset_inl_inr_disj : core.\n\nDefinition uPred_fupd_def `{!invG Σ} (E1 E2 : coPset) (P : iProp Σ) : iProp Σ :=\n  wsat_all ∗ ownE (AlwaysEn ∪ MaybeEn E1) ==∗ ◇ (wsat_all ∗ ownE (AlwaysEn ∪ MaybeEn E2) ∗ P).\nDefinition uPred_fupd_aux : seal (@uPred_fupd_def). Proof. by eexists. Qed.\nDefinition uPred_fupd := uPred_fupd_aux.(unseal).\nGlobal Arguments uPred_fupd {Σ _}.\nLemma uPred_fupd_eq `{!invG Σ} : @fupd _ uPred_fupd = uPred_fupd_def.\nProof. rewrite -uPred_fupd_aux.(seal_eq) //. Qed.\n\nLemma coPset_suffixes_of_union p E1 E2 :\n  coPset_suffixes_of p (E1 ∪ E2) = coPset_suffixes_of p E1 ∪ coPset_suffixes_of p E2.\nProof.\n  rewrite -leibniz_equiv_iff.\n  intros x. set_unfold. rewrite ?elem_coPset_suffixes_of. set_unfold. naive_solver.\nQed.\n\nLemma coPset_suffixes_of_disj p E1 E2 :\n  E1 ## E2 ↔ coPset_suffixes_of p E1 ## coPset_suffixes_of p E2.\nProof.\n  set_unfold. split => Hin x.\n  - rewrite ?elem_coPset_suffixes_of.\n    intros (q1'&Heq1&Hin1) (q2'&Heq2&Hin2).\n    rewrite Heq1 in Heq2.\n    apply Papp_inj in Heq2; naive_solver.\n  - intros. apply (Hin (Papp x p)); apply elem_coPset_suffixes_of; eauto.\nQed.\n\nLemma MaybeEn_union E1 E2 : MaybeEn (E1 ∪ E2) = MaybeEn E1 ∪ MaybeEn E2.\nProof. apply coPset_suffixes_of_union. Qed.\nLemma MaybeEn_disj E1 E2 : E1 ## E2 ↔ MaybeEn E1 ## MaybeEn E2.\nProof. apply coPset_suffixes_of_disj. Qed.\nLemma MaybeEn_infinite E:\n  (¬ set_finite E) → (¬ set_finite (MaybeEn E)).\nProof. apply coPset_suffixes_of_infinite. Qed.\n\nLemma ownE_op_MaybeEn `{!invG Σ} E1 E2 :\n  E1 ## E2 → ownE (MaybeEn (E1 ∪ E2)) ⊣⊢ ownE (MaybeEn E1) ∗ ownE (MaybeEn E2).\nProof. intros Hdisj. rewrite MaybeEn_union ownE_op //=. by apply coPset_suffixes_of_disj. Qed.\n\nLemma ownE_op_MaybeEn' `{!invG Σ} E1 E2 :\n  ⌜ E1 ## E2 ⌝ ∧ ownE (MaybeEn (E1 ∪ E2)) ⊣⊢ ownE (MaybeEn E1) ∗ ownE (MaybeEn E2).\nProof. rewrite MaybeEn_union MaybeEn_disj ownE_op' //=. Qed.\n\nLemma uPred_fupd_mixin `{!invG Σ} : BiFUpdMixin (uPredI (iResUR Σ)) uPred_fupd.\nProof.\n  split.\n  - rewrite uPred_fupd_eq. solve_proper.\n  - intros E1 E2 (E1''&->&?)%subseteq_disjoint_union_L.\n    rewrite uPred_fupd_eq /uPred_fupd_def ?ownE_op // ?ownE_op_MaybeEn //.\n    by iIntros \"($ & $ & ($ & HE)) !> !> [$ [$ $]] !> !>\" .\n  - rewrite uPred_fupd_eq. iIntros (E1 E2 P) \">H [Hw HE]\". iApply \"H\"; by iFrame.\n  - rewrite uPred_fupd_eq. iIntros (E1 E2 P Q HPQ) \"HP HwE\". rewrite -HPQ. by iApply \"HP\".\n  - rewrite uPred_fupd_eq. iIntros (E1 E2 E3 P) \"HP HwE\".\n    iMod (\"HP\" with \"HwE\") as \">(Hw & HE & HP)\". iApply \"HP\"; by iFrame.\n  - intros E1 E2 Ef P HE1Ef. rewrite uPred_fupd_eq /uPred_fupd_def ?ownE_op // ownE_op_MaybeEn //.\n    iIntros \"Hvs (Hw & HAE & HE1 & HEf)\".\n    iMod (\"Hvs\" with \"[Hw HAE HE1]\") as \">($ & (HAE & HE2) & HP)\"; first by iFrame.\n    iDestruct (ownE_op_MaybeEn' with \"[HE2 HEf]\") as \"[? $]\"; first by iFrame.\n    iIntros \"!> !>\". iFrame. by iApply \"HP\".\n  - rewrite uPred_fupd_eq /uPred_fupd_def. by iIntros (????) \"[HwP $]\".\nQed.\nGlobal Instance uPred_bi_fupd `{!invG Σ} : BiFUpd (uPredI (iResUR Σ)) :=\n  {| bi_fupd_mixin := uPred_fupd_mixin |}.\n\nGlobal Instance uPred_bi_bupd_fupd `{!invG Σ} : BiBUpdFUpd (uPredI (iResUR Σ)).\nProof. rewrite /BiBUpdFUpd uPred_fupd_eq. by iIntros (E P) \">? [$ $] !> !>\". Qed.\n\nGlobal Instance uPred_bi_fupd_plainly `{!invG Σ} : BiFUpdPlainly (uPredI (iResUR Σ)).\nProof.\n  split.\n  - rewrite uPred_fupd_eq /uPred_fupd_def. iIntros (E P) \"H [Hw HE]\".\n    iAssert (◇ ■ P)%I as \"#>HP\".\n    { by iMod (\"H\" with \"[$]\") as \"(_ & _ & HP)\". }\n    by iFrame.\n  - rewrite uPred_fupd_eq /uPred_fupd_def. iIntros (E P Q) \"[H HQ] [Hw HE]\".\n    iAssert (◇ ■ P)%I as \"#>HP\".\n    { by iMod (\"H\" with \"HQ [$]\") as \"(_ & _ & HP)\". }\n    by iFrame.\n  - rewrite uPred_fupd_eq /uPred_fupd_def. iIntros (E P) \"H [Hw HE]\".\n    iAssert (▷ ◇ ■ P)%I as \"#HP\".\n    { iNext. by iMod (\"H\" with \"[$]\") as \"(_ & _ & HP)\". }\n    iFrame. iIntros \"!> !> !>\". by iMod \"HP\".\n  - rewrite uPred_fupd_eq /uPred_fupd_def. iIntros (E A Φ) \"HΦ [Hw HE]\".\n    iAssert (◇ ■ ∀ x : A, Φ x)%I as \"#>HP\".\n    { iIntros (x). by iMod (\"HΦ\" with \"[$Hw $HE]\") as \"(_&_&?)\". }\n    by iFrame.\nQed.\n\nLemma ownE_mono_le_acc `{!invG Σ} E1 E2:\n  E1 ⊆ E2 →\n  ownE E2 -∗ ownE E1 ∗ (ownE E1 -∗ ownE E2).\nProof.\n  iIntros (?). replace E2 with (E2 ∖ E1 ∪ E1).\n  { rewrite ownE_op; last by set_solver. iIntros \"(Hrest&$) H\". iFrame. }\n  { rewrite difference_union_L. set_solver. }\nQed.\n\nLemma ownE_weaken `{!invG Σ} E1 E2 : E2 ⊆ E1 → ownE E1 -∗ ownE E2.\nProof.\n  iIntros (?) \"H\". by iDestruct (ownE_mono_le_acc with \"H\") as \"($&_)\".\nQed.\n\nLemma fupd_plain_soundness `{!invPreG Σ} E1 E2 (P: iProp Σ) `{!Plain P} :\n  (∀ `{Hinv: !invG Σ}, ⊢ |={E1,E2}=> P) → ⊢ P.\nProof.\n  iIntros (Hfupd). apply later_soundness. iMod wsat_alloc' as (Hinv) \"[Hw HE]\".\n  iAssert (|={⊤,E2}=> P)%I as \"H\".\n  { iMod (fupd_mask_subseteq E1) as \"_\"; first done. iApply Hfupd. }\n  rewrite uPred_fupd_eq /uPred_fupd_def.\n  iMod (\"H\" with \"[$Hw HE]\") as \"[Hw [HE >H']]\"; iFrame.\n  iApply (ownE_weaken with \"HE\"). set_solver.\nQed.\n\nLemma step_fupdN_soundness `{!invPreG Σ} φ n :\n  (∀ `{Hinv: !invG Σ}, ⊢@{iPropI Σ} |={⊤,∅}=> |={∅}▷=>^n ⌜ φ ⌝) →\n  φ.\nProof.\n  intros Hiter.\n  apply (soundness (M:=iResUR Σ) _  (S n)); simpl.\n  apply (fupd_plain_soundness ⊤ ⊤ _)=> Hinv.\n  iPoseProof (Hiter Hinv) as \"H\". clear Hiter.\n  iApply fupd_plainly_mask_empty. iMod \"H\".\n  iMod (step_fupdN_plain with \"H\") as \"H\". iModIntro.\n  rewrite -later_plainly -laterN_plainly -later_laterN laterN_later.\n  iNext. iMod \"H\" as %Hφ. auto.\nQed.\n\nLemma step_fupdN_soundness' `{!invPreG Σ} φ n :\n  (∀ `{Hinv: !invG Σ}, ⊢@{iPropI Σ} |={⊤}[∅]▷=>^n ⌜ φ ⌝) →\n  φ.\nProof.\n  iIntros (Hiter). eapply (step_fupdN_soundness _ n)=>Hinv. destruct n as [|n].\n  { by iApply fupd_mask_intro_discard; [|iApply (Hiter Hinv)]. }\n   simpl in Hiter |- *. iMod Hiter as \"H\". iIntros \"!>!>!>\".\n  iMod \"H\". clear. iInduction n as [|n] \"IH\"; [by iApply fupd_mask_intro_discard|].\n  simpl. iMod \"H\". iIntros \"!>!>!>\". iMod \"H\". by iApply \"IH\".\nQed.\n", "meta": {"author": "jtassarotti", "repo": "iris-inv-hierarchy", "sha": "b25fe890d72ecb5bafa9db422ece3939d99882ab", "save_path": "github-repos/coq/jtassarotti-iris-inv-hierarchy", "path": "github-repos/coq/jtassarotti-iris-inv-hierarchy/iris-inv-hierarchy-b25fe890d72ecb5bafa9db422ece3939d99882ab/iris/base_logic/lib/fancy_updates.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2675492143133058}}
{"text": "Require Import Lang.Syntax Lang.Bindings FinFun.\nSet Implicit Arguments.\n\nImplicit Types EV HV V L : Set.\n\nSection section_L_bind_inj.\n\nLocal Fact disjoint_same_inv A (x : A) : disjoint \\{x} \\{x} → False.\nProof.\nunfold disjoint ; rewrite inter_same ; intro H.\nerewrite <- in_empty.\nrewrite <- H.\nrewrite in_singleton ; reflexivity.\nQed.\n\nLemma L_bind_lid_inj\nL L' (f : L → lid L')\n(Inj : Injective f)\n(i1 i2 : lid L)\n(Q1 : ∀ α, disjoint (Xs_lid (f α)) (Xs_lid i1))\n(Q2 : ∀ α, disjoint (Xs_lid (f α)) (Xs_lid i2))\n(H : L_bind_lid f i1 = L_bind_lid f i2) :\ni1 = i2.\nProof.\ndestruct i1 as [ α1 | X1 ], i2 as [ α2 | X2 ] ; simpl in *.\n+ specialize (Inj α1 α2 H) ; congruence.\n+ exfalso.\n  specialize (Q2 α1) ; rewrite H in Q2 ; simpl in Q2.\n  apply disjoint_same_inv in Q2 ; auto.\n+ exfalso.\n  specialize (Q1 α2) ; rewrite <- H in Q1 ; simpl in Q1.\n  apply disjoint_same_inv in Q1 ; auto.\n+ crush.\nQed.\n\nLemma L_bind_lbl_inj\nHV L L' (f : L → lid L')\n(Inj : Injective f)\n(l1 l2 : lbl HV L)\n(Q1 : ∀ α, disjoint (Xs_lid (f α)) (Xs_lbl l1))\n(Q2 : ∀ α, disjoint (Xs_lid (f α)) (Xs_lbl l2))\n(H : L_bind_lbl f l1 = L_bind_lbl f l2) :\nl1 = l2.\nProof.\ndestruct l1, l2 ; simpl in * ; try inversion H ; clear H ;\nrepeat match goal with\n| [ H : L_bind_lid ?f _ = L_bind_lid ?f _ |- _ ] =>\n  apply L_bind_lid_inj in H ; subst ; clear H\nend ;\ncrush.\nQed.\n\nLemma L_bind_ef_inj\nEV HV L L' (f : L → lid L')\n(Inj : Injective f)\n(ε1 ε2 : ef EV HV L)\n(Q1 : ∀ α, disjoint (Xs_lid (f α)) (Xs_ef ε1))\n(Q2 : ∀ α, disjoint (Xs_lid (f α)) (Xs_ef ε2))\n(H : L_bind_ef f ε1 = L_bind_ef f ε2) :\nε1 = ε2.\nProof.\ndestruct ε1, ε2 ; simpl in * ; try inversion H ; clear H ;\nrepeat match goal with\n| [ H : L_bind_lbl ?f _ = L_bind_lbl ?f _ |- _ ] =>\n  apply L_bind_lbl_inj in H ; subst ; clear H\nend ;\ncrush.\nQed.\n\nEnd section_L_bind_inj.\n\nLemma lbl_EV_bind_hd\nEV EV' HV V L (f : EV → eff EV' HV L)\n(h : hd EV HV V L) :\nlbl_hd (EV_bind_hd f h) = lbl_hd h.\nProof.\ninduction h ; crush.\nQed.\n\nLemma lbl_L_bind_hd EV HV V L L'\n  (f : L → lid L') (h : hd EV HV V L) :\n  lbl_hd (L_bind_hd f h) = L_bind_lbl f (lbl_hd h).\nProof.\n  induction h ; crush.\nQed.\n\nLemma lbl_V_bind_hd EV HV V V' L\n  (f : V → val EV HV V' L) (h : hd EV HV V L) :\n  lbl_hd (V_bind_hd f h) = lbl_hd h.\nProof.\n  induction h ; crush.\nQed.\n\nLemma lbl_HV_bind_hd EV EV' HV HV' V V' L\n  (f : HV → hd EV HV' V L) (g : HV → hd EV' HV' V' L)\n  (Q : ∀ p, lbl_hd (f p) = lbl_hd (g p))\n  (h : hd EV' HV V' L) :\n  lbl_hd (HV_bind_hd g h) = HV_bind_lbl f (lbl_hd h).\nProof.\n  induction h ; crush.\nQed.\n\nLemma EV_bind_XEnv_empty\nEV EV' HV (f : EV → eff EV' HV ∅) :\nEV_bind_XEnv f empty = empty.\nProof.\napply map_empty.\nQed.\n\nLemma EV_bind_XEnv_single\nEV EV' HV (f : EV → eff EV' HV ∅) X (T : ty EV HV ∅) (𝓔 : eff EV HV ∅) :\nEV_bind_XEnv f (X ~ (T, 𝓔)) = X ~ (EV_bind_ty f T, EV_bind_eff f 𝓔).\nProof.\napply map_single.\nQed.\n\nLemma EV_bind_XEnv_concat\nEV EV' HV (f : EV → eff EV' HV ∅) (Ξ Ξ' : XEnv EV HV) :\nEV_bind_XEnv f (Ξ & Ξ') =\n(EV_bind_XEnv f Ξ) & (EV_bind_XEnv f Ξ').\nProof.\napply map_concat.\nQed.\n\nLemma EV_bind_XEnv_dom\nEV EV' HV (f : EV → eff EV' HV ∅) (Ξ : XEnv EV HV) :\ndom (EV_bind_XEnv f Ξ) = dom Ξ.\nProof.\ninduction Ξ as [ | ? ? [? ?] IHΞ ] using env_ind.\n+ rewrite EV_bind_XEnv_empty.\n  repeat rewrite dom_empty.\n  reflexivity.\n+ rewrite EV_bind_XEnv_concat, EV_bind_XEnv_single.\n  repeat rewrite dom_concat, dom_single.\n  rewrite IHΞ.\n  reflexivity.\nQed.\n\nLemma HV_bind_XEnv_empty\nEV HV HV' V (f : HV → hd EV HV' V ∅) :\nHV_bind_XEnv f (empty : XEnv EV HV) = empty.\nProof.\napply map_empty.\nQed.\n\nLemma HV_bind_XEnv_single\nEV HV HV' V (f : HV → hd EV HV' V ∅) X (T : ty EV HV ∅) (𝓔 : eff EV HV ∅) :\nHV_bind_XEnv f (X ~ (T, 𝓔)) = X ~ (HV_bind_ty f T, HV_bind_eff f 𝓔).\nProof.\napply map_single.\nQed.\n\nLemma HV_bind_XEnv_concat\nEV HV HV' V (f : HV → hd EV HV' V ∅) (Ξ Ξ' : XEnv EV HV) :\nHV_bind_XEnv f (Ξ & Ξ') =\n(HV_bind_XEnv f Ξ) & (HV_bind_XEnv f Ξ').\nProof.\napply map_concat.\nQed.\n\nLemma HV_bind_XEnv_dom\nEV HV HV' V (f : HV → hd EV HV' V ∅) (Ξ : XEnv EV HV) :\ndom (HV_bind_XEnv f Ξ) = dom Ξ.\nProof.\ninduction Ξ as [ | ? ? [? ?] IHΞ ] using env_ind.\n+ rewrite HV_bind_XEnv_empty.\n  repeat rewrite dom_empty.\n  reflexivity.\n+ rewrite HV_bind_XEnv_concat, HV_bind_XEnv_single.\n  repeat rewrite dom_concat, dom_single.\n  rewrite IHΞ.\n  reflexivity.\nQed.\n\n\nSection section_binds_EV_bind.\nContext (EV EV' HV : Set).\nContext (f : EV → eff EV' HV ∅).\nContext (X : var).\n\nLemma binds_EV_bind T 𝓔 (Ξ : XEnv EV HV) :\nbinds X (T, 𝓔) Ξ →\nbinds X (EV_bind_ty f T, EV_bind_eff f 𝓔) (EV_bind_XEnv f Ξ).\nProof.\nintro Hbinds.\ninduction Ξ as [ | Ξ' X' [ T' 𝓔' ] IHΞ' ] using env_ind.\n+ apply binds_empty_inv in Hbinds ; crush.\n+ apply binds_concat_inv in Hbinds.\n  rewrite EV_bind_XEnv_concat, EV_bind_XEnv_single.\n  destruct Hbinds as [ Hbinds | Hbinds ].\n  - apply binds_single_inv in Hbinds ; crush.\n  - destruct Hbinds as [ FrX Hbinds ] ; auto.\nQed.\n\nLemma binds_EV_bind_inv\n(T' : ty EV' HV ∅) (𝓔' : eff EV' HV ∅) (Ξ : XEnv EV HV) :\nbinds X (T', 𝓔') (EV_bind_XEnv f Ξ) →\n∃ T 𝓔,\nT' = EV_bind_ty f T ∧ 𝓔' = EV_bind_eff f 𝓔 ∧ binds X (T, 𝓔) Ξ.\nProof.\nintro Hbinds'.\ninduction Ξ as [ | Ξ Y [ T 𝓔 ] IHΞ ] using env_ind.\n+ rewrite EV_bind_XEnv_empty in Hbinds'.\n  apply binds_empty_inv in Hbinds' ; crush.\n+ rewrite EV_bind_XEnv_concat, EV_bind_XEnv_single in Hbinds'.\n  apply binds_concat_inv in Hbinds'.\n  destruct Hbinds' as [ Hbinds' | Hbinds' ].\n  - apply binds_single_inv in Hbinds'.\n    destruct Hbinds' as [ [] Heq ].\n    inversion Heq ; subst.\n    eauto.\n  - destruct Hbinds' as [ FrX Hbinds' ].\n    specialize (IHΞ Hbinds').\n    destruct IHΞ as [T'' [𝓔'' [? [? ?]]]].\n    repeat eexists ; eauto.\nQed.\n\nEnd section_binds_EV_bind.\n\n\nSection section_binds_HV_bind.\nContext (EV HV HV' V : Set).\nContext (f : HV → hd EV HV' V ∅).\nContext (X : var).\n\nLemma binds_HV_bind T 𝓔 (Ξ : XEnv EV HV) :\nbinds X (T, 𝓔) Ξ →\nbinds X (HV_bind_ty f T, HV_bind_eff f 𝓔) (HV_bind_XEnv f Ξ).\nProof.\nintro Hbinds.\ninduction Ξ as [ | Ξ' X' [ T' 𝓔' ] IHΞ' ] using env_ind.\n+ apply binds_empty_inv in Hbinds ; crush.\n+ apply binds_concat_inv in Hbinds.\n  rewrite HV_bind_XEnv_concat, HV_bind_XEnv_single.\n  destruct Hbinds as [ Hbinds | Hbinds ].\n  - apply binds_single_inv in Hbinds ; crush.\n  - destruct Hbinds as [ FrX Hbinds ] ; auto.\nQed.\n\nLemma binds_HV_bind_inv\n(T' : ty EV HV' ∅) (𝓔' : eff EV HV' ∅) (Ξ : XEnv EV HV) :\nbinds X (T', 𝓔') (HV_bind_XEnv f Ξ) →\n∃ T 𝓔,\nT' = HV_bind_ty f T ∧ 𝓔' = HV_bind_eff f 𝓔 ∧ binds X (T, 𝓔) Ξ.\nProof.\nintro Hbinds'.\ninduction Ξ as [ | Ξ Y [ T 𝓔 ] IHΞ ] using env_ind.\n+ rewrite HV_bind_XEnv_empty in Hbinds'.\n  apply binds_empty_inv in Hbinds' ; crush.\n+ rewrite HV_bind_XEnv_concat, HV_bind_XEnv_single in Hbinds'.\n  apply binds_concat_inv in Hbinds'.\n  destruct Hbinds' as [ Hbinds' | Hbinds' ].\n  - apply binds_single_inv in Hbinds'.\n    destruct Hbinds' as [ [] Heq ].\n    inversion Heq ; subst.\n    eauto.\n  - destruct Hbinds' as [ FrX Hbinds' ].\n    specialize (IHΞ Hbinds').\n    destruct IHΞ as [T'' [𝓔'' [? [? ?]]]].\n    repeat eexists ; eauto.\nQed.\n\nEnd section_binds_HV_bind.\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/Lang/BindingsFacts_bind_0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5, "lm_q1q2_score": 0.26754921431330575}}
{"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  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 pc_p' w dst src regs :\n    decodeInstrW w = Jnz dst src ->\n\n    PermFlows pc_p pc_p' →\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 ↦ₐ[pc_p'] 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 ↦ₐ[pc_p'] w ∗\n        [∗ map] k↦y ∈ regs', k ↦ᵣ y }}}.\n  Proof.\n    iIntros (Hinstr Hfl 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; simpl.\n    iDestruct \"Hσ1\" as \"[Hr 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_inclSepM with \"Hr Hmap\") as %Hregs.\n    have HPC' := regs_lookup_eq _ _ _ HPC.\n    have ? := lookup_weaken _ _ _ _ HPC Hregs.\n    iDestruct (@gen_heap_valid_cap 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 pc_p' :\n    decodeInstrW w = Jnz r1 r2 →\n    PermFlows pc_p pc_p' → 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 ↦ₐ[pc_p'] w\n        ∗ ▷ r1 ↦ᵣ w1\n        ∗ ▷ r2 ↦ᵣ w2 }}}\n      Instr Executable @ E\n      {{{ RET NextIV;\n          PC ↦ᵣ updatePcPerm w1\n          ∗ pc_a ↦ₐ[pc_p'] w\n          ∗ r1 ↦ᵣ w1\n          ∗ r2 ↦ᵣ w2 }}}.\n  Proof.\n    iIntros (Hinstr Hfl 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 pc_p' :\n    decodeInstrW w = Jnz r2 r2 →\n    PermFlows pc_p pc_p' → 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 ↦ₐ[pc_p'] w\n        ∗ ▷ r2 ↦ᵣ w2 }}}\n      Instr Executable @ E\n      {{{ RET NextIV;\n          PC ↦ᵣ updatePcPerm w2\n          ∗ pc_a ↦ₐ[pc_p'] w\n          ∗ r2 ↦ᵣ w2 }}}.\n  Proof.\n    iIntros (Hinstr Hfl 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 pc_p' :\n    decodeInstrW w = Jnz PC PC →\n    PermFlows pc_p pc_p' → 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    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 pc_p' :\n    decodeInstrW w = Jnz PC r2 →\n    PermFlows pc_p pc_p' → 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 ↦ₐ[pc_p'] 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 ↦ₐ[pc_p'] w\n          ∗ r2 ↦ᵣ w2 }}}.\n  Proof.\n    iIntros (Hinstr Hfl 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 pc_p' :\n    decodeInstrW w = Jnz r1 PC →\n    PermFlows pc_p pc_p' → 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        ∗ ▷ r1 ↦ᵣ w1 }}}\n      Instr Executable @ E\n      {{{ RET NextIV;\n          PC ↦ᵣ updatePcPerm w1\n          ∗ pc_a ↦ₐ[pc_p'] w\n          ∗ r1 ↦ᵣ w1 }}}.\n  Proof.\n    iIntros (Hinstr Hfl 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 pc_p' :\n    decodeInstrW w = Jnz r1 r2 →\n    PermFlows pc_p pc_p' → 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 ↦ₐ[pc_p'] 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 ↦ₐ[pc_p'] w\n          ∗ r1 ↦ᵣ w1\n          ∗ r2 ↦ᵣ inl 0%Z }}}.\n  Proof.\n    iIntros (Hinstr Hfl 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   { congruence. }\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", "sha": "f68111362730aff998798d63c7d6a0a7176eff44", "save_path": "github-repos/coq/logsem-cerise-stack", "path": "github-repos/coq/logsem-cerise-stack/cerise-stack-f68111362730aff998798d63c7d6a0a7176eff44/theories/rules/rules_Jnz.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.26754761596883525}}
{"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(**)\nProposition prop26_formula16_isinkc_TRue: forall s,\n  (fun c0 c1 =>\n     isinkc kc0 kc1 (＜ π2 (π1 (FGO1 c0 c1 ⫠ ⫠)), π2 (π1 (FGO2 c0 c1 ⫠ ⫠)), π2 (π1 (FGO3 c0 c1 ⫠ ⫠)) ＞) = TRue) (c0 s) (c1 s).\nProof.\n  intros.\n  unfold isinkc.\n  assert (isin kc0 (＜ π2 (π1 FGO1 (c0 s) (c1 s) ⫠ ⫠), π2 (π1 FGO2 (c0 s) (c1 s) ⫠ ⫠), π2 (π1 FGO3 (c0 s) (c1 s) ⫠ ⫠) ＞) = FAlse).\n    unfold isin.\n    rewrite Tau1Tri, Tau2Tri, Tau3Tri.\n    rewrite Freshkc0FGO1_16, Freshkc0FGO2_16, Freshkc0FGO3_16.\n    repeat rewrite If_false.\n    reflexivity.\n  assert (isin kc1 (＜ π2 (π1 FGO1 (c0 s) (c1 s) ⫠ ⫠), π2 (π1 FGO2 (c0 s) (c1 s) ⫠ ⫠), π2 (π1 FGO3 (c0 s) (c1 s) ⫠ ⫠) ＞) = FAlse).\n    unfold isin.\n    rewrite Tau1Tri, Tau2Tri, Tau3Tri.\n    rewrite Freshkc1FGO1_16, Freshkc1FGO2_16, Freshkc1FGO3_16.\n    repeat rewrite If_false.\n    reflexivity.\n  rewrite H. clear H.\n  rewrite H0. clear H0.\n  repeat rewrite If_false.\n  reflexivity.\nQed.\n\n\n(* When both encryptions are bot, neither isinkc0 nor isinkc1 will success,\n   so using prop11, we can get rid of those process checks to reduce Do to FDO *)\n\nProposition prop26_formula16_Do_FDO : forall s,\n  (fun c0 c1 =>\n     [b0 c0; b1 c1; acc0 c0 c1 & acc1 c0 c1;\n     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     ＜ ⫠, ⫠, Do (FGO1 c0 c1 ⫠ ⫠) (FGO2 c0 c1 ⫠ ⫠) (FGO3 c0 c1 ⫠ ⫠) ＞ ＞]) (c0 s) (c1 s)\n ~\n   (fun c0 c1 =>\n      [b0 c0; b1 c1; acc0 c0 c1 & acc1 c0 c1;\n      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     ＜ ⫠, ⫠, FDO (FGO1 c0 c1 ⫠ ⫠) (FGO2 c0 c1 ⫠ ⫠) (FGO3 c0 c1 ⫠ ⫠) ＞ ＞]) (c0 s) (c1 s).\nProof.\n  intros.\n  simpl.\n  unfold Do.\n  rewrite (prop26_formula16_isinkc_TRue s).\n  repeat rewrite <- If_tf.\n  reflexivity.\n  unfold pchko. Provebool.\nQed.\n\n\n(* formula 16 on page 40  *)\nProposition prop26_formula16 :\n  (fun c0 c1 =>\n     [b0 c0; b1 c1; acc0 c0 c1 & acc1 c0 c1;\n     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     ＜ ⫠, ⫠, Do (FGO1 c0 c1 ⫠ ⫠) (FGO2 c0 c1 ⫠ ⫠) (FGO3 c0 c1 ⫠ ⫠) ＞ ＞]) (c0 lhs) (c1 lhs)\n ~\n   (fun c0 c1 =>\n      [b0 c0; b1 c1; acc0 c0 c1 & acc1 c0 c1;\n      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     ＜ ⫠, ⫠, Do (FGO1 c0 c1 ⫠ ⫠) (FGO2 c0 c1 ⫠ ⫠) (FGO3 c0 c1 ⫠ ⫠) ＞ ＞]) (c0 rhs) (c1 rhs).\nProof.\n  intros. simpl.\n\n(* First we need to get rid of the \"isinkc\" check in Do, namely change Do to FDO*)\n  rewrite (prop26_formula16_Do_FDO lhs).\n  rewrite (prop26_formula16_Do_FDO rhs).\n\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             ＜ ⫠, ⫠, FDO (FGO1 c0 c1 ⫠ ⫠) (FGO2 c0 c1 ⫠ ⫠) (FGO3 c0 c1 ⫠ ⫠) ＞ ＞])\n                     vot0 vot1 0 1).\n  apply voteLen. lia.\n  1, 3: ProveFresh.\n  apply Freshc_kc0_Lemma26_16.\n  apply Freshc_kc1_Lemma26_16.\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_16.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.26754761596883525}}
{"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.  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 terms5.\nRequire Export computation7.\nRequire Export computation_exc.\nRequire Export computation_dec1.\n\n\nLemma decidable_isprog {o} :\n  forall (t : @NTerm o),\n    decidable (isprog t).\nProof.\n  introv.\n  apply decidable_eq_bool.\nQed.\n\nLemma decidable_isprogram {o} :\n  forall (t : @NTerm o),\n    decidable (isprogram t).\nProof.\n  introv.\n  destruct (decidable_isprog t) as [d|d];[left|right]; eauto 3 with slow.\n  intro xx; destruct d; eauto 3 with slow.\nQed.\n\nLemma decidable_wf_term {o} :\n  forall (t : @NTerm o),\n    decidable (wf_term t).\nProof.\n  introv.\n  apply decidable_eq_bool.\nQed.\n\nLemma decidable_isvalue {o} :\n  forall (t : @NTerm o),\n    decidable (isvalue t).\nProof.\n  introv.\n  destruct t as [v|op bs]; try (complete (right; allsimpl; intro xx; inversion xx)).\n  dopid op as [c|nc|e|a] Case; try (complete (right; allsimpl; intro xx; inversion xx)).\n  destruct (decidable_isprogram (oterm (Can c) bs)) as [d|d];[left|right]; auto.\n  introv xx; destruct d.\n  inversion xx; auto.\nQed.\n\nLemma decidable_iscvalue {o} :\n  forall (t : @CTerm o),\n    decidable (iscvalue t).\nProof.\n  introv.\n  destruct_cterms.\n  unfold iscvalue; simpl.\n  apply decidable_isvalue.\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/computation_dec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.26754760904809805}}
{"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 A B C G Aprime Aprimeprime Bprime Cprime Bprimeprime Bprimeprimeprime : Universe, ((wd_ Aprime Bprimeprime /\\ (wd_ A B /\\ (wd_ B C /\\ (wd_ A C /\\ (wd_ Bprime A /\\ (wd_ Bprime C /\\ (wd_ Aprime B /\\ (wd_ Aprime C /\\ (wd_ Cprime A /\\ (wd_ Cprime B /\\ (wd_ Aprimeprime Bprimeprime /\\ (wd_ Aprime Bprimeprimeprime /\\ (wd_ Aprime Bprime /\\ (wd_ Bprime Bprimeprimeprime /\\ (wd_ G Aprime /\\ (wd_ G Aprimeprime /\\ (wd_ G Bprimeprime /\\ (wd_ Bprimeprime Bprimeprimeprime /\\ (wd_ G Bprimeprimeprime /\\ (wd_ Aprime Aprimeprime /\\ (wd_ B G /\\ (wd_ Bprimeprime B /\\ (wd_ A G /\\ (wd_ Aprimeprime A /\\ (col_ Aprime Bprime Bprimeprimeprime /\\ (col_ Aprime Bprimeprime Aprime /\\ (col_ G Aprimeprime Aprime /\\ (col_ G Bprimeprime Bprimeprimeprime /\\ (col_ Bprimeprime B G /\\ (col_ Cprime A B /\\ (col_ Bprime A C /\\ (col_ Aprimeprime A G /\\ (col_ Aprime B C /\\ col_ Aprime Bprimeprime G))))))))))))))))))))))))))))))))) -> col_ A B G)).\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_1104.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.37387582974820255, "lm_q1q2_score": 0.2674797400453206}}
{"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 (N.eqb 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 (N.eqb 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 (N.eqb 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 (N.eqb 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 (N.eqb 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": "coq-contribs", "repo": "bdds", "sha": "2a66529afca7c780fa18d21ecd4f6c8d55182a6d", "save_path": "github-repos/coq/coq-contribs-bdds", "path": "github-repos/coq/coq-contribs-bdds/bdds-2a66529afca7c780fa18d21ecd4f6c8d55182a6d/bdd5_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.26747122064444284}}
{"text": "Require Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nRequire Export Parser.NetworkConstruction.\n\nOpaque set_cell.\nOpaque io_types.\n\nLemma same_inputs_make_network':\n  forall A G (s: Syntax A) (descr: Description G) k N,\n    forall k', k' < k -> inputs (make_network' s descr k N) k' = inputs N k'.\nProof.\n  induction s;\n    repeat light || destruct_match || invert_constructor_equalities ||\n           match goal with\n           | H: context[make_network' ?s _ _ _] |- context[make_network' ?s ?descr ?k ?N] =>\n               unshelve epose proof (H descr k N ); clear H\n           | H: forall k, _ -> inputs _ _ = inputs _ _ |- _ => rewrite H in * by lia\n           end;\n    try lia.\nQed.\n\nLemma same_inputs_make_network2':\n  forall A G (s: Syntax A) (descr: Description G) k N,\n    forall k', k' >= k + syntax_size s -> inputs (make_network' s descr k N) k' = inputs N k'.\nProof.\n  induction s;\n    repeat light || destruct_match || invert_constructor_equalities ||\n           match goal with\n           | H: context[make_network' ?s _ _ _] |- context[make_network' ?s ?descr ?k ?N] =>\n               unshelve epose proof (H descr k N ); clear H\n           | H: forall k, _ -> inputs _ _ = inputs _ _ |- _ => rewrite H in * by lia\n           end;\n    try lia.\nQed.\n\nLemma cell_make_network':\n  forall A (s: Syntax A) G (descr: Description G) k N,\n    cells (make_network' s descr k N) k = make_cell_with_state s descr None.\nProof.\n  destruct s;\n    repeat light || destruct_match || invert_constructor_equalities.\nQed.\n\nLemma cell_make_network:\n  forall A (s : Syntax A) G (descr : Description G),\n    cells (make_network s descr) (sum_sizes vars) = make_cell_with_state s descr None.\nProof.\n  unfold make_network;\n    repeat light || rewrite cell_make_network'.\nQed.\n\nLemma same_cells_make_network':\n  forall A (s: Syntax A) G (descr: Description G) k N,\n    forall k', k' < k -> cells (make_network' s descr k N) k' = cells N k'.\nProof.\n  induction s;\n    repeat light || destruct_match || invert_constructor_equalities ||\n           match goal with\n           | H: context[make_network' ?s _ _ _] |- context[make_network' ?s ?descr ?k ?N] =>\n               unshelve epose proof (H _ descr k N); clear H\n           | H: forall k, _ -> cells _ _ = cells _ _ |- _ => rewrite H in * by lia\n           end;\n    try lia.\nQed.\n\nLemma same_cells_make_network2':\n  forall A (s: Syntax A) G (descr: Description G) k N,\n    forall k', k' >= k + syntax_size s -> cells (make_network' s descr k N) k' = cells N k'.\nProof.\n  induction s;\n    repeat light || destruct_match || invert_constructor_equalities ||\n           match goal with\n           | H: context[make_network' ?s _ _ _] |- context[make_network' ?s ?descr ?k ?N] =>\n               unshelve epose proof (H _ descr k N); clear H\n           | H: forall k, _ -> cells _ _ = cells _ _ |- _ => rewrite H in * by lia\n           end;\n    try lia.\nQed.\n", "meta": {"author": "epfl-lara", "repo": "scallion-proofs", "sha": "3f048aabee5c961446d9993a70355eff510a2ddb", "save_path": "github-repos/coq/epfl-lara-scallion-proofs", "path": "github-repos/coq/epfl-lara-scallion-proofs/scallion-proofs-3f048aabee5c961446d9993a70355eff510a2ddb/NetworkSimpleLemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.26747122064444284}}
{"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\nRequire Export DistributedReferenceCounting.machine1.invariant0.\nRequire Export DistributedReferenceCounting.machine1.invariant1.\nRequire Export DistributedReferenceCounting.machine1.invariant2.\nRequire Export DistributedReferenceCounting.machine1.invariant3.\n\nUnset Standard Proposition Elimination Names.\n\n(* Where send_table on the owner is defined in terms of the other components *)\n\nSection INVARIANT4.\n\nDefinition new_inc_count (m : Message) :=\n  match m with\n  | inc_dec s => 1%Z\n  | _ => 0%Z\n  end.\n\n\n(* Below five remarks aux1, aux2, aux3, aux4, aux5 ... followed by\n  the real meat the invariant 4. *)\n\nRemark aux1 :\n forall c : Config,\n legal c ->\n st c owner =\n (sigma_receive_table (rt c) + sigma_weight (bm c) -\n  sigma_table_but_owner Z (fun (_ : Site) (x : Z) => x) (st c))%Z.\nProof.\n  intros.\n  unfold sigma_send_table in |- *.\n  generalize (invariant1 c H).\n  unfold sigma_send_table in |- *.\n  rewrite sigma_sigma_but_owner.\n  generalize (sigma_table_but_owner Z (fun (_ : Site) (x : Z) => x) (st c)).\n  intros.\n  omega.\nQed.\n\nRemark aux2 :\n forall c : Config,\n legal c ->\n sigma_table_but_owner Z (fun (_ : Site) (x : Z) => x) (st c) =\n sigma_but Site owner eq_site_dec LS (fun s : Site => sigma_rooted s (bm c)).\nProof.\n  intros.\n  unfold sigma_table_but_owner in |- *.\n  apply sigma_but_simpl.\n  intros.\n  rewrite (invariant2 c s).\n  auto.\n  auto.\n  auto.\nQed.\n\nRemark aux3 :\n forall (s1 s2 : Site) (q : queue Message),\n (cardinal q -\n  sigma_but Site owner eq_site_dec LS (fun s : Site => rooted s s1 s2 q))%Z =\n reduce Message\n   (fun a : Message =>\n    (cardinal_count a -\n     sigma_but Site owner eq_site_dec LS\n       (fun s : Site => rooted_fun s s1 s2 a))%Z) q.\nProof.\n  intros.\n  unfold rooted in |- *.\n  unfold cardinal in |- *.\n  rewrite permute_sigma_but_reduce.\n  rewrite <- disjoint_reduce3.\n  unfold fun_minus in |- *.\n  auto.\nQed.\n\nRemark aux4 :\n forall t : Site -> Site -> queue Message,\n sigma2_table Site LS LS (queue Message)\n   (fun (s1 s2 : Site) (q : queue Message) =>\n    (cardinal q -\n     sigma_but Site owner eq_site_dec LS (fun s : Site => rooted s s1 s2 q))%Z)\n   t =\n sigma2_table Site LS LS (queue Message)\n   (fun (s1 s2 : Site) (q : queue Message) =>\n    reduce Message\n      (fun a : Message =>\n       (cardinal_count a -\n        sigma_but Site owner eq_site_dec LS\n          (fun s : Site => rooted_fun s s1 s2 a))%Z) q) t.\nProof.\n  intros.\n  unfold sigma2_table in |- *.\n  apply sigma_table_simpl.\n  apply funct_eq.\n  intros.\n  apply sigma_table_simpl2.\n  intros.\n  apply aux3.\nQed.\n\n\n\n\nRemark aux5 :\n forall c : Config,\n legal c ->\n sigma2_table Site LS LS (queue Message)\n   (fun (s1 s2 : Site) (q : queue Message) =>\n    reduce Message\n      (fun a : Message =>\n       (cardinal_count a -\n        sigma_but Site owner eq_site_dec LS\n          (fun s : Site => rooted_fun s s1 s2 a))%Z) q) \n   (bm c) =\n (sigma2_table Site LS LS (queue Message)\n    (fun (s1 s2 : Site) (q : queue Message) =>\n     if eq_site_dec s2 owner\n     then reduce Message dec_count q\n     else 0) (bm c) +\n  sigma2_table Site LS LS (queue Message)\n    (fun (s1 s2 : Site) (q : queue Message) =>\n     if eq_site_dec s1 owner\n     then reduce Message copy_count q\n     else 0) (bm c) -\n  sigma2_table Site LS LS (queue Message)\n    (fun (s1 s2 : Site) (q : queue Message) => reduce Message new_inc_count q)\n    (bm c))%Z.\n\n\nProof.\n  intros.\n  rewrite <- sigma2_disjoint.\n  rewrite <- sigma2_disjoint2.\n  apply sigma2_table_simpl_partial.\n  unfold fun_minus_site2 in |- *.\n  unfold fun_minus_site in |- *.\n  unfold fun_sum_site2 in |- *.\n  unfold fun_sum_site in |- *.\n  intros.\n  generalize (not_owner_inc4 c s1 s2 H).\n  generalize (inc_dec_owner4 c s1 s2 H).\n  generalize (inc_dec_owner2 c s1 s2 H).\n  generalize (empty_queue2 c H s1 s2 owner).\n  rewrite H0.\n  clear H0.\n  elim d.\n  intros; simpl in |- *.\n  case (eq_site_dec s2 owner).\n  case (eq_site_dec s1 owner).\n  intros; omega.\n  \n  intros; omega.\n  \n  case (eq_site_dec s1 owner).\n  intros; omega.\n  \n  intros; omega.\n  \n  intros.\n  simpl in |- *.\n  rewrite H0.\n  case (eq_site_dec s2 owner).\n  intro.\n  case (eq_site_dec s1 owner).\n  intro.\n  generalize (H1 e0 e).\n  intro.\n  discriminate.\n  \n  intro.\n  rewrite e.\n  unfold cardinal_count in |- *.\n  unfold fun_sum in |- *.\n  generalize (H4 d0).\n  elim d0.\n  intros.\n  rewrite sigma_rooted_fun3.\n  simpl in |- *.\n  omega.\n  \n  intros.\n  rewrite sigma_rooted_fun5.\n  simpl in |- *.\n  omega.\n  \n  apply finite_site.\n  \n  apply H5.\n  auto.\n  \n  simpl in |- *.\n  left; auto.\n  \n  intros.\n  rewrite sigma_rooted_fun7.\n  simpl in |- *.\n  omega.\n  \n  apply finite_site.\n  \n  auto.\n  \n  intros.\n  case (eq_site_dec s1 owner).\n  intro.\n  rewrite e.\n  simpl in |- *.\n  replace\n   (cardinal_count d0 -\n    sigma_but Site owner eq_site_dec LS\n      (fun s : Site => rooted_fun s owner s2 d0))%Z with\n   (copy_count d0 - new_inc_count d0)%Z.\n  omega.\n  \n  unfold cardinal_count in |- *.\n  unfold fun_sum in |- *.\n  generalize H3.\n  elim d0.\n  intros.\n  rewrite sigma_rooted_fun9.\n  simpl in |- *.\n  auto.\n  \n  apply finite_site.\n  \n  auto.\n  \n  intros.\n  generalize (H5 e s).\n  simpl in |- *.\n  intro.\n  elim H6.\n  left; auto.\n  \n  rewrite sigma_rooted_fun10.\n  simpl in |- *.\n  auto.\n  \n  intro.\n  replace\n   (cardinal_count d0 -\n    sigma_but Site owner eq_site_dec LS\n      (fun s : Site => rooted_fun s s1 s2 d0))%Z with \n   (- new_inc_count d0)%Z.\n  omega.\n  \n  simpl in |- *.\n  generalize (H2 n0 n).\n  elim d0.\n  intros.\n  rewrite sigma_rooted_fun12.\n  simpl in |- *.\n  auto.\n  \n  auto.\n  \n  auto.\n  \n  apply finite_site.\n  \n  intros.\n  generalize (H5 s).\n  simpl in |- *.\n  intro.\n  elim H6.\n  left; auto.\n  \n  intros.\n  rewrite sigma_rooted_fun14.\n  simpl in |- *.\n  auto.\n  \n  auto.\n  \n  auto.\n  \n  apply finite_site.\n  \n  intros.\n  generalize (H1 H5 H6).\n  intro; discriminate.\n  \n  intros.\n  generalize (H2 H5 H6 s0).\n  simpl in |- *.\n  intuition.\n  \n  intros.\n  generalize (H3 H5 s0).\n  simpl in |- *.\n  intuition.\n  \n  intros.\n  generalize (H4 m s0 H5).\n  simpl in |- *.\n  intro.\n  apply H7.\n  right; auto.\nQed.\n\nLemma simpl_dec_sum :\n forall c : Config,\n legal c ->\n sigma2_table Site LS LS (queue Message)\n   (fun (s1 s2 : Site) (q : queue Message) =>\n    if eq_site_dec s2 owner\n    then reduce Message dec_count q\n    else 0%Z) (bm c) =\n sigma_table Site LS Z (Z_id Site)\n   (fun s1 : Site => reduce Message dec_count (bm c s1 owner)).\n\nProof.\n  intros.\n  unfold sigma2_table in |- *.\n  apply sigma_table_simpl.\n  apply funct_eq.\n  intros.\n  unfold sigma_table in |- *.\n  rewrite\n   (sigma_sigma_but Site owner eq_site_dec\n      (fun s : Site =>\n       match eq_site_dec s owner with\n       | left _ => reduce Message dec_count (bm c e s)\n       | right _ => 0%Z\n       end)).\n  replace\n   (sigma_but Site owner eq_site_dec LS\n      (fun s : Site =>\n       match eq_site_dec s owner with\n       | left _ => reduce Message dec_count (bm c e s)\n       | right _ => 0%Z\n       end)) with 0%Z.\n  case (eq_site_dec owner owner).\n  intro; auto.\n  intuition.\n  rewrite sigma_but_null.\n  auto.\n  intros.\n  rewrite case_ineq.\n  auto.\n  auto.\n  apply finite_site.\nQed.    \n\nLemma simpl_copy_sum :\n forall c : Config,\n legal c ->\n sigma2_table Site LS LS (queue Message)\n   (fun (s1 _ : Site) (q : queue Message) =>\n    match eq_site_dec s1 owner with\n    | left _ => reduce Message copy_count q\n    | right _ => 0%Z\n    end) (bm c) =\n sigma_table Site LS Z (Z_id Site)\n   (fun s2 : Site => reduce Message copy_count (bm c owner s2)).\nProof.\n  intros.\n  unfold sigma2_table in |- *.\n  unfold sigma in |- *.\n  unfold sigma_table in |- *.\n  rewrite\n   (sigma_sigma_but Site owner eq_site_dec\n      (fun s : Site =>\n       Z_id Site s\n         (sigma Site LS\n            (fun s0 : Site =>\n             match eq_site_dec s owner with\n             | left _ => reduce Message copy_count (bm c s s0)\n             | right _ => 0%Z\n             end)))).\n  rewrite Z_id_reduce.\n  replace\n   (sigma_but Site owner eq_site_dec LS\n      (fun s : Site =>\n       Z_id Site s\n         (sigma Site LS\n            (fun s0 : Site =>\n             match eq_site_dec s owner with\n             | left _ => reduce Message copy_count (bm c s s0)\n             | right _ => 0%Z\n             end)))) with 0%Z.\n  simpl in |- *.\n  apply sigma_simpl.\n  intros.\n  rewrite case_eq.\n  rewrite Z_id_reduce.\n  auto.\n  \n  rewrite sigma_but_null.\n  auto.\n  \n  intros.\n  rewrite Z_id_reduce.\n  case (eq_site_dec s owner).\n  intro; elim H0; auto.\n  \n  intro.\n  apply sigma_null.\n  \n  apply finite_site.\nQed.\n\n\nLemma no_inc_dec :\n forall q : queue Message,\n (forall s0 : Site, ~ In_queue Message (inc_dec s0) q) ->\n reduce Message new_inc_count q = 0%Z.\nProof.\n  simple induction q.\n  simpl in |- *.\n  auto.\n  \n  simpl in |- *.\n  intros d q0 H.\n  elim d.\n  simpl in |- *.\n  intro.\n  rewrite H.\n  auto.\n  \n  intro.\n  generalize (H0 s0).\n  intuition.\n  \n  simpl in |- *.\n  intro.\n  intro.\n  generalize (H0 s).\n  intro.\n  elim H1; left; auto.\n  \n  simpl in |- *.\n  intro.\n  rewrite H.\n  auto.\n  \n  intro.\n  generalize (H0 s0).\n  intuition.\nQed.\n\n\n\nLemma simpl_inc_sum :\n forall c : Config,\n legal c ->\n sigma2_table Site LS LS (queue Message)\n   (fun (_ _ : Site) (q : queue Message) => reduce Message new_inc_count q)\n   (bm c) =\n sigma_table Site LS Z (Z_id Site)\n   (fun s1 : Site => reduce Message new_inc_count (bm c s1 owner)).\n\nProof.\n  intros.\n  unfold sigma2_table in |- *.\n  generalize (inc_dec_owner2 c).\n  generalize (inc_dec_owner3 c).\n  generalize (bm c).\n  intros.\n  apply sigma_table_simpl.\n  apply funct_eq.\n  intros.\n  unfold sigma_table in |- *.\n  case (eq_site_dec e owner).\n  intro.\n  rewrite\n   (sigma_sigma_but Site owner eq_site_dec\n      (fun s : Site => reduce Message new_inc_count (b e s)))\n   .\n  replace\n   (sigma_but Site owner eq_site_dec LS\n      (fun s : Site => reduce Message new_inc_count (b e s))) with 0%Z.\n  omega.\n  \n  rewrite sigma_but_null.\n  auto.\n  \n  intros.\n  generalize (H0 e s H H2).\n  intro.\n  apply no_inc_dec.\n  auto.\n  \n  apply finite_site.\n  \n  intro.\n  rewrite\n   (sigma_sigma_but Site owner eq_site_dec\n      (fun s : Site => reduce Message new_inc_count (b e s)))\n   .\n  replace\n   (sigma_but Site owner eq_site_dec LS\n      (fun s : Site => reduce Message new_inc_count (b e s))) with 0%Z.\n  auto.\n  \n  rewrite sigma_but_null.\n  auto.\n  \n  intros.\n  generalize (H1 e s H n H2).\n  intro.\n  apply no_inc_dec.\n  auto.\n  \n  apply finite_site.\nQed.\n\n\nRemark add_reduce :\n forall x y a u w z : Z,\n (y - a)%Z = (z + w - u)%Z -> (x + y - a)%Z = (x + z + w - u)%Z.\nProof.\nintros; omega.\nQed.\n\n\nLemma invariant4 :\n forall c : Config,\n legal c ->\n st c owner =\n (sigma_receive_table (rt c) +\n  sigma_table Site LS Z (Z_id Site)\n    (fun s1 : Site => reduce Message dec_count (bm c s1 owner)) +\n  sigma_table Site LS Z (Z_id Site)\n    (fun s2 : Site => reduce Message copy_count (bm c owner s2)) -\n  sigma_table Site LS Z (Z_id Site)\n    (fun s1 : Site => reduce Message new_inc_count (bm c s1 owner)))%Z.\nProof.\n  intros.\n  rewrite (aux1 c H).\n  rewrite aux2.\n  unfold sigma_weight in |- *.\n  unfold sigma_rooted in |- *.\n  rewrite sigma2_sigma_but.\n  apply add_reduce.\n  rewrite <- sigma2_disjoint2.\n  unfold fun_minus_site2 in |- *.\n  unfold fun_minus_site in |- *.\n  rewrite aux4.\n  rewrite aux5.\n  rewrite simpl_dec_sum.\n  rewrite simpl_copy_sum.\n  rewrite simpl_inc_sum.\n  auto.\n  auto.\n  auto.\n  auto.\n  auto.\n  auto.\nQed.\n\n\n\n\n\n\nEnd INVARIANT4.\n\n\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/machine1/invariant4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.26747122064444284}}
{"text": "Require Import Bool String List Arith.Peano_dec.\nRequire Import Lib.FMap Lib.Struct Lib.CommonTactics Lib.Concat Lib.Indexer Lib.StringEq.\nRequire Import Kami.Syntax Kami.Semantics Kami.SemFacts Kami.RefinementFacts.\nRequire Import Kami.Specialize Kami.Duplicate Kami.Notations.\n\nImport ListNotations.\n\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\nSection ModuleBound.\n  Variable m: Modules.\n  Variable n: nat. (* Assume that all indexed names in \"m\" is parametrized by \"n\" *)\n\n  Record NameBound :=\n    { originals : list string;\n      prefixes : list string\n    }.\n\n  Definition emptyNameBound := Build_NameBound nil nil.\n  Definition addOriginal s nb := Build_NameBound (s :: originals nb) (prefixes nb).\n  Definition addPrefix p nb := Build_NameBound (originals nb) (p :: prefixes nb).\n\n  Definition appendNameBound (nb1 nb2: NameBound) :=\n    Build_NameBound (originals nb1 ++ originals nb2)\n                    (prefixes nb1 ++ prefixes nb2).\n\n  Declare Scope namebound_scope.\n  Notation \"nb1 ++ nb2\" := (appendNameBound nb1 nb2) : namebound_scope.\n  Delimit Scope namebound_scope with nb.\n\n  Definition intersectNameBound (nb1 nb2: NameBound) :=\n    Build_NameBound (filter (fun o => string_in o (originals nb2)) (originals nb1))\n                    (filter (fun p => string_in p (prefixes nb2)) (prefixes nb1)).\n    \n  Definition subtractNameBound (nb1 nb2: NameBound) :=\n    Build_NameBound (filter (fun o => negb (string_in o (originals nb2))) (originals nb1))\n                    (filter (fun p => negb (string_in p (prefixes nb2))) (prefixes nb1)).\n\n  Definition unfoldNameBound (nb: NameBound) :=\n    (originals nb) ++ (concat (map (fun p => duplicateElt p n) (prefixes nb))).\n\n  Definition Abstracted (nb: NameBound) (ls: list string) :=\n    EquivList (unfoldNameBound nb) ls.\n\n  Lemma abstracted_nil: Abstracted (Build_NameBound nil nil) nil.\n  Proof. compute; auto. Qed.\n\n  Lemma abstracted_originals_refl: forall l, Abstracted (Build_NameBound l nil) l.\n  Proof.\n    unfold Abstracted, unfoldNameBound; simpl; intros.\n    rewrite app_nil_r; apply EquivList_refl.\n  Qed.\n\n  Lemma abstracted_EquivList:\n    forall nb l1 l2, Abstracted nb l1 -> EquivList l1 l2 -> Abstracted nb l2.\n  Proof.\n    unfold Abstracted; intros.\n    eapply EquivList_trans; eauto.\n  Qed.\n\n  Lemma abstracted_app_1:\n    forall a1 a2 l1 l2,\n      Abstracted a1 l1 -> Abstracted a2 l2 ->\n      Abstracted (a1 ++ a2)%nb (l1 ++ l2).\n  Proof.\n    unfold Abstracted, unfoldNameBound; intros.\n    destruct a1 as [o1 p1], a2 as [o2 p2]; simpl in *.\n    rewrite map_app, concat_app.\n    inv H; inv H0; split.\n    - subList_app_tac.\n    - repeat apply SubList_app_3.\n      + eapply SubList_trans; eauto; subList_app_tac.\n      + eapply SubList_trans; eauto; subList_app_tac.\n  Qed.\n\n  Lemma abstracted_app_2:\n    forall a l1 l2,\n      Abstracted a l1 -> Abstracted a l2 ->\n      Abstracted a (l1 ++ l2).\n  Proof.\n    unfold Abstracted, unfoldNameBound; intros.\n    destruct a as [o p]; simpl in *.\n    inv H; inv H0; split.\n    - subList_app_tac.\n    - apply SubList_app_3; auto.\n  Qed.\n\n  Lemma EquivList_filter:\n    forall l1 l2 l3 l4,\n      EquivList l1 l2 -> EquivList l3 l4 ->\n      EquivList (filter (fun d => string_in d l3) l1)\n                (filter (fun d => string_in d l4) l2).\n  Proof.\n    unfold EquivList, SubList; intros; dest; split; intros.\n    - specializeAll e.\n      apply filter_In; apply filter_In in H3; dest; split; auto.\n      apply eq_sym, string_in_dec_in in H4.\n      remember (string_in e l4) as ein; destruct ein; auto.\n      exfalso; apply string_in_dec_not_in in Heqein; auto.\n    - specializeAll e.\n      apply filter_In; apply filter_In in H3; dest; split; auto.\n      apply eq_sym, string_in_dec_in in H4.\n      remember (string_in e l3) as ein; destruct ein; auto.\n      exfalso; apply string_in_dec_not_in in Heqein; auto.\n  Qed.\n\n  Lemma EquivList_filter_neg:\n    forall l1 l2 l3 l4,\n      EquivList l1 l2 -> EquivList l3 l4 ->\n      EquivList (filter (fun d => negb (string_in d l3)) l1)\n                (filter (fun d => negb (string_in d l4)) l2).\n  Proof.\n    unfold EquivList, SubList; intros; dest; split; intros.\n    - specializeAll e.\n      apply filter_In; apply filter_In in H3; dest; split; auto.\n      rewrite negb_true_iff in *.\n      apply eq_sym, string_in_dec_not_in in H4.\n      remember (string_in e l4) as ein; destruct ein; auto.\n      exfalso; apply string_in_dec_in in Heqein; auto.\n    - specializeAll e.\n      apply filter_In; apply filter_In in H3; dest; split; auto.\n      rewrite negb_true_iff in *.\n      apply eq_sym, string_in_dec_not_in in H4.\n      remember (string_in e l3) as ein; destruct ein; auto.\n      exfalso; apply string_in_dec_in in Heqein; auto.\n  Qed.\n\n  Lemma filter_app:\n    forall {A} (l1 l2: list A) f,\n      filter f (l1 ++ l2) = filter f l1 ++ filter f l2.\n  Proof.\n    induction l1; simpl; intros; [reflexivity|].\n    destruct (f a); auto.\n    simpl; f_equal; auto.\n  Qed.\n\n  Lemma filter_Forall_true:\n    forall {A} (l: list A) f,\n      Forall (fun a => f a = true) l ->\n      filter f l = l.\n  Proof.\n    induction l; simpl; intros; [reflexivity|].\n    inv H; rewrite H2, IHl; auto.\n  Qed.\n\n  Lemma filter_DisjList_app_1:\n    forall l1 l2 l3,\n      DisjList l1 l3 ->\n      filter (fun d => string_in d (l2 ++ l3)) l1 =\n      filter (fun d => string_in d l2) l1.\n  Proof.\n    induction l1; simpl; intros; auto.\n    remember (string_in a l2) as ain; destruct ain; simpl.\n    - apply string_in_dec_in in Heqain.\n      remember (string_in _ _) as aain; destruct aain; simpl.\n      + rewrite IHl1; [reflexivity|].\n        eapply DisjList_cons; eauto.\n      + exfalso; apply string_in_dec_not_in in Heqaain; elim Heqaain.\n        apply in_or_app; auto.\n    - apply string_in_dec_not_in in Heqain.\n      remember (string_in _ _) as aain; destruct aain; simpl.\n      + exfalso; apply string_in_dec_in in Heqaain.\n        apply in_app_or in Heqaain; destruct Heqaain; auto.\n        specialize (H a); destruct H; auto.\n        elim H; left; auto.\n      + apply IHl1; eapply DisjList_cons; eauto.\n  Qed.\n\n  Lemma filter_DisjList_app_2:\n    forall l1 l2 l3,\n      DisjList l1 l2 ->\n      filter (fun d => string_in d (l2 ++ l3)) l1 =\n      filter (fun d => string_in d l3) l1.\n  Proof.\n    induction l1; simpl; intros; auto.\n    remember (string_in a l3) as ain; destruct ain; simpl.\n    - apply string_in_dec_in in Heqain.\n      remember (string_in _ _) as aain; destruct aain; simpl.\n      + rewrite IHl1; [reflexivity|].\n        eapply DisjList_cons; eauto.\n      + exfalso; apply string_in_dec_not_in in Heqaain; elim Heqaain.\n        apply in_or_app; auto.\n    - apply string_in_dec_not_in in Heqain.\n      remember (string_in _ _) as aain; destruct aain; simpl.\n      + exfalso; apply string_in_dec_in in Heqaain.\n        apply in_app_or in Heqaain; destruct Heqaain; auto.\n        specialize (H a); destruct H; auto.\n        elim H; left; auto.\n      + apply IHl1; eapply DisjList_cons; eauto.\n  Qed.\n\n  Lemma filter_DisjList_app_neg_1:\n    forall l1 l2 l3,\n      DisjList l1 l3 ->\n      filter (fun d => negb (string_in d (l2 ++ l3))) l1 =\n      filter (fun d => negb (string_in d l2)) l1.\n  Proof.\n    induction l1; simpl; intros; auto.\n    remember (string_in a l2) as ain; destruct ain; simpl.\n    - apply string_in_dec_in in Heqain.\n      remember (string_in _ _) as aain; destruct aain; simpl.\n      + apply IHl1; eapply DisjList_cons; eauto.\n      + exfalso; apply string_in_dec_not_in in Heqaain; elim Heqaain.\n        apply in_or_app; auto.\n    - apply string_in_dec_not_in in Heqain.\n      remember (string_in _ _) as aain; destruct aain; simpl.\n      + apply string_in_dec_in in Heqaain.\n        exfalso; apply in_app_or in Heqaain; destruct Heqaain; auto.\n        specialize (H a); destruct H; auto.\n        elim H; left; auto.\n      + f_equal; apply IHl1; eapply DisjList_cons; eauto.\n  Qed.\n\n  Lemma filter_DisjList_app_neg_2:\n    forall l1 l2 l3,\n      DisjList l1 l2 ->\n      filter (fun d => negb (string_in d (l2 ++ l3))) l1 =\n      filter (fun d => negb (string_in d l3)) l1.\n  Proof.\n    induction l1; simpl; intros; auto.\n    remember (string_in a l3) as ain; destruct ain; simpl.\n    - apply string_in_dec_in in Heqain.\n      remember (string_in _ _) as aain; destruct aain; simpl.\n      + apply IHl1; eapply DisjList_cons; eauto.\n      + exfalso; apply string_in_dec_not_in in Heqaain; elim Heqaain.\n        apply in_or_app; auto.\n    - apply string_in_dec_not_in in Heqain.\n      remember (string_in _ _) as aain; destruct aain; simpl.\n      + apply string_in_dec_in in Heqaain.\n        exfalso; apply in_app_or in Heqaain; destruct Heqaain; auto.\n        specialize (H a); destruct H; auto.\n        elim H; left; auto.\n      + f_equal; apply IHl1; eapply DisjList_cons; eauto.\n  Qed.\n\n  Lemma duplicateElt_in_DisjList:\n    forall p n l,\n      ~ In p l ->\n      DisjList (duplicateElt p n) (concat (map (fun t => duplicateElt t n) l)).\n  Proof.\n    induction l; simpl; intros; [apply DisjList_nil_2|].\n    apply DisjList_comm, DisjList_app_4.\n    - apply duplicateElt_DisjList; intuition.\n    - apply DisjList_comm; auto.\n  Qed.\n\n  Lemma duplicateElt_in_filter:\n    forall p n l,\n      In p l ->\n      duplicateElt p n =\n      filter (fun d => string_in d (concat (map (fun p => duplicateElt p n) l)))\n             (duplicateElt p n).\n  Proof.\n    intros.\n    rewrite filter_Forall_true; [reflexivity|].\n    apply Forall_forall; intros pn ?.\n    destruct (string_in _ _) eqn:Hin; [reflexivity|].\n    exfalso.\n    apply eq_sym, string_in_dec_not_in in Hin; elim Hin; clear Hin.\n    induction l; simpl; intros; [dest_in|].\n    inv H.\n    - apply in_or_app; left; assumption.\n    - apply in_or_app; right; auto.\n  Qed.\n\n  Lemma duplicateElt_concat_DisjList:\n    forall n l1 l2,\n      DisjList l1 l2 ->\n      DisjList (concat (map (fun t => duplicateElt t n) l1))\n               (concat (map (fun t => duplicateElt t n) l2)).\n  Proof.\n    induction l1; simpl; intros; [apply DisjList_nil_1|].\n    apply DisjList_app_4.\n    - apply duplicateElt_in_DisjList.\n      specialize (H a); destruct H; auto.\n      elim H; left; auto.\n    - apply IHl1; eapply DisjList_cons; eauto.\n  Qed.\n\n  Lemma concat_filter_comm:\n    forall p1 p2 n,\n      concat\n        (map (fun p => duplicateElt p n)\n             (filter (fun p => string_in p p2) p1)) =\n      filter\n        (fun d => string_in d (concat (map (fun p => duplicateElt p n) p2)))\n        (concat (map (fun p => duplicateElt p n) p1)).\n  Proof.\n    induction p1; simpl; intros; auto.\n    remember (string_in a p2) as ain; destruct ain; simpl.\n    - rewrite IHp1.\n      generalize (concat (map (fun p : string => duplicateElt p n0) p1)); intros.\n      rewrite filter_app; f_equal.\n      apply string_in_dec_in in Heqain.\n      apply duplicateElt_in_filter; assumption.\n    - rewrite IHp1; clear -Heqain.\n      generalize (concat (map (fun p : string => duplicateElt p n0) p1)); intros.\n      rewrite filter_app.\n      replace (filter (fun d => string_in d (concat (map (fun p => duplicateElt p n0) p2)))\n                      (duplicateElt a n0)) with (@nil string); [reflexivity|].\n      apply eq_sym.\n      apply string_in_dec_not_in in Heqain.\n      rewrite <-app_nil_l with (l:= (concat (map (fun p : string => duplicateElt p n0) p2))).\n      rewrite filter_DisjList_app_1.\n      + induction (duplicateElt a n0); auto.\n      + apply duplicateElt_in_DisjList; auto.\n  Qed.\n\n  Lemma concat_filter_comm_neg:\n    forall p1 p2 n,\n      concat\n        (map (fun p => duplicateElt p n)\n             (filter (fun p => negb (string_in p p2)) p1)) =\n      filter\n        (fun d => negb (string_in d (concat (map (fun p => duplicateElt p n) p2))))\n        (concat (map (fun p => duplicateElt p n) p1)).\n  Proof.\n    induction p1; simpl; intros; auto.\n    remember (string_in a p2) as ain; destruct ain; simpl.\n    - rewrite filter_app.\n      replace (filter\n                (fun d => negb (string_in d (concat (map (fun p => duplicateElt p n0) p2))))\n                (duplicateElt a n0)) with (nil (A:= string)).\n      + rewrite app_nil_l; auto.\n      + apply string_in_dec_in in Heqain; clear -Heqain.\n        induction n0; simpl.\n        * remember (string_in _ _) as iin; destruct iin; auto.\n          exfalso; apply string_in_dec_not_in in Heqiin; elim Heqiin; clear Heqiin.\n          induction p2; [inv Heqain|].\n          inv Heqain; simpl; auto.\n        * remember (string_in _ _) as iin; destruct iin; simpl.\n          { clear -IHn0; induction (duplicateElt a n0); simpl in *; auto.\n            remember (string_in a0 (concat (map (fun p => duplicateElt p n0) p2)))\n              as allin; destruct allin; simpl in IHn0; [|inv IHn0].\n            remember (string_in a0 (concat (map (fun p => (p) __ (S n0) :: duplicateElt p n0) p2)))\n              as cllin; destruct cllin; simpl; auto.\n            exfalso; apply string_in_dec_not_in in Heqcllin; elim Heqcllin.\n            apply string_in_dec_in in Heqallin; clear -Heqallin.\n            apply in_concat_iff in Heqallin; dest.\n            apply in_map_iff in H; dest; subst.\n            apply in_concat_iff; eexists; split.\n            { apply in_map_iff; eexists; split; eauto. }\n            { right; auto. }\n          }\n          { exfalso; apply string_in_dec_not_in in Heqiin; elim Heqiin; clear Heqiin.\n            apply in_concat_iff; eexists; split.\n            { apply in_map_iff; eexists; split; eauto. }\n            { left; auto. }\n          }\n    - rewrite IHp1; clear -Heqain.\n      generalize (concat (map (fun p : string => duplicateElt p n0) p1)); intros.\n      rewrite filter_app; f_equal.\n      apply string_in_dec_not_in in Heqain.\n      rewrite <-app_nil_l with (l:= (concat (map (fun p : string => duplicateElt p n0) p2))).\n      rewrite filter_DisjList_app_neg_1.\n      + induction (duplicateElt a n0); auto.\n        simpl; f_equal; auto.\n      + apply duplicateElt_in_DisjList; auto.\n  Qed.\n\n  Lemma hasNoIndex_duplicateElt_DisjList:\n    forall l p n,\n      hasNoIndex l = true ->\n      DisjList l (duplicateElt p n).\n  Proof.\n    induction n0; simpl; intros.\n    - unfold DisjList; intros.\n      destruct (in_dec string_dec e [p __ 0]); auto.\n      destruct (in_dec string_dec e l); auto.\n      exfalso; inv i; [|inv H0].\n      pose proof (hasNoIndex_in _ H _ i0).\n      clear -H0.\n      Transparent withIndex.\n      unfold withIndex in H0; generalize H0; apply badIndex.\n      Opaque withIndex.\n    - apply DisjList_comm, DisjList_string_cons; [|apply DisjList_comm; auto].\n      intro Hx; pose proof (hasNoIndex_in _ H _ Hx).\n      Transparent withIndex.\n      unfold withIndex in H0; generalize H0; apply badIndex.\n      Opaque withIndex.\n  Qed.\n\n  Lemma subtractNameBound_filter_abstracted:\n    forall nb1 nb2 l1 l2,\n      hasNoIndex (originals nb1) = true ->\n      hasNoIndex (originals nb2) = true ->\n      Abstracted nb1 l1 -> Abstracted nb2 l2 ->\n      Abstracted (subtractNameBound nb1 nb2) \n                 (filter (fun d => negb (string_in d l2)) l1).\n  Proof.\n    unfold Abstracted, unfoldNameBound; intros.\n    destruct nb1 as [o1 p1], nb2 as [o2 p2]; simpl in *.\n    eapply EquivList_trans; [|eapply EquivList_filter_neg; eauto].\n    rewrite filter_app; apply EquivList_app.\n    - rewrite filter_DisjList_app_neg_1; [apply EquivList_refl|].\n      clear -H; induction p2; [apply DisjList_nil_2|].\n      simpl; apply DisjList_comm, DisjList_app_4.\n      + apply DisjList_comm.\n        apply hasNoIndex_duplicateElt_DisjList; auto.\n      + apply DisjList_comm; auto.\n    - rewrite filter_DisjList_app_neg_2.\n      + rewrite concat_filter_comm_neg; apply EquivList_refl.\n      + clear -H0; apply DisjList_comm.\n        induction p1; [apply DisjList_nil_2|].\n        simpl; apply DisjList_comm, DisjList_app_4.\n        * apply DisjList_comm, hasNoIndex_duplicateElt_DisjList; auto.\n        * apply DisjList_comm; auto.\n  Qed.\n\n  Lemma intersectNameBound_filter_abstracted:\n    forall nb1 nb2 l1 l2,\n      hasNoIndex (originals nb1) = true ->\n      hasNoIndex (originals nb2) = true ->\n      Abstracted nb1 l1 -> Abstracted nb2 l2 ->\n      Abstracted (intersectNameBound nb1 nb2) \n                 (filter (fun d => string_in d l2) l1).\n  Proof.\n    unfold Abstracted, unfoldNameBound; intros.\n    destruct nb1 as [o1 p1], nb2 as [o2 p2]; simpl in *.\n    eapply EquivList_trans; [|eapply EquivList_filter; eauto].\n    rewrite filter_app; apply EquivList_app.\n    - rewrite filter_DisjList_app_1; [apply EquivList_refl|].\n      clear -H; induction p2; [apply DisjList_nil_2|].\n      simpl; apply DisjList_comm, DisjList_app_4.\n      + apply DisjList_comm.\n        apply hasNoIndex_duplicateElt_DisjList; auto.\n      + apply DisjList_comm; auto.\n    - rewrite filter_DisjList_app_2.\n      + rewrite concat_filter_comm; apply EquivList_refl.\n      + clear -H0; apply DisjList_comm.\n        induction p1; [apply DisjList_nil_2|].\n        simpl; apply DisjList_comm, DisjList_app_4.\n        * apply DisjList_comm, hasNoIndex_duplicateElt_DisjList; auto.\n        * apply DisjList_comm; auto.\n  Qed.\n\n  Definition RegsBound (regnb: NameBound) := Abstracted regnb (namesOf (getRegInits m)).\n  Definition DmsBound (dmnb: NameBound) := Abstracted dmnb (getDefs m).\n  Definition CmsBound (cmnb: NameBound) := Abstracted cmnb (getCalls m).\n\n  Definition DisjPrefixes (ss1 ss2: list string) :=\n    forall p1,\n      In p1 ss1 ->\n      forall p2,\n        In p2 ss2 ->\n        prefix p1 p2 = false /\\ prefix p2 p1 = false.\n\n  Definition DisjNameBound (nb1 nb2: NameBound) :=\n    hasNoIndex (originals nb1) = true /\\\n    hasNoIndex (originals nb2) = true /\\\n    DisjList (originals nb1) (originals nb2) /\\\n    DisjList (prefixes nb1) (prefixes nb2).\n\n  Fixpoint disjListStr (l1 l2: list string) :=\n    match l1 with\n    | nil => true\n    | h1 :: t1 => if string_in h1 l2 then false else disjListStr t1 l2\n    end.\n\n  Lemma disjListStr_DisjList:\n    forall l1 l2, disjListStr l1 l2 = true -> DisjList l1 l2.\n  Proof.\n    induction l1; simpl; intros; [apply DisjList_nil_1|].\n    remember (string_in a l2) as ain; destruct ain; [inv H|].\n    apply DisjList_string_cons; auto.\n    apply string_in_dec_not_in in Heqain; auto.\n  Qed.\n\n  Definition disjNameBound (nb1 nb2: NameBound) :=\n    (hasNoIndex (originals nb1))\n      && (hasNoIndex (originals nb2))\n      && (disjListStr (originals nb1) (originals nb2))\n      && (disjListStr (prefixes nb1) (prefixes nb2)).\n\n  Lemma disjNameBound_DisjNameBound:\n    forall nb1 nb2, disjNameBound nb1 nb2 = true -> DisjNameBound nb1 nb2.\n  Proof.\n    unfold disjNameBound, DisjNameBound; intros.\n    repeat (apply andb_true_iff in H; dest).\n    Opaque DisjPrefixes. repeat split; auto. Transparent DisjPrefixes.\n    - apply disjListStr_DisjList; auto.\n    - apply disjListStr_DisjList; auto.\n  Qed.\n\nEnd ModuleBound.\n\nSection Bounds.\n  Declare Scope namebound_scope.\n  Notation \"nb1 ++ nb2\" := (appendNameBound nb1 nb2) : namebound_scope.\n  Delimit Scope namebound_scope with nb.\n\n  Lemma concatMod_regsBound_1:\n    forall m1 m2 n rb1 rb2,\n      RegsBound m1 n rb1 ->\n      RegsBound m2 n rb2 ->\n      RegsBound (m1 ++ m2)%kami n (rb1 ++ rb2)%nb.\n  Proof.\n    unfold RegsBound; simpl; intros.\n    unfold RegInitT; rewrite namesOf_app.\n    apply abstracted_app_1; auto.\n  Qed.\n\n  Lemma concatMod_regsBound_2:\n    forall m1 m2 n rb,\n      RegsBound m1 n rb ->\n      RegsBound m2 n rb ->\n      RegsBound (m1 ++ m2)%kami n rb.\n  Proof.\n    unfold RegsBound; simpl; intros.\n    unfold RegInitT; rewrite namesOf_app.\n    apply abstracted_app_2; auto.\n  Qed.\n\n  Lemma concatMod_dmsBound_1:\n    forall m1 m2 n db1 db2,\n      DmsBound m1 n db1 ->\n      DmsBound m2 n db2 ->\n      DmsBound (m1 ++ m2)%kami n (db1 ++ db2)%nb.\n  Proof.\n    unfold DmsBound; simpl; intros.\n    rewrite getDefs_app.\n    apply abstracted_app_1; auto.\n  Qed.\n\n  Lemma concatMod_dmsBound_2:\n    forall m1 m2 n db,\n      DmsBound m1 n db ->\n      DmsBound m2 n db ->\n      DmsBound (m1 ++ m2)%kami n db.\n  Proof.\n    unfold DmsBound; simpl; intros.\n    rewrite getDefs_app.\n    apply abstracted_app_2; auto.\n  Qed.\n\n  Lemma concatMod_cmsBound_1:\n    forall m1 m2 n cb1 cb2,\n      CmsBound m1 n cb1 ->\n      CmsBound m2 n cb2 ->\n      CmsBound (m1 ++ m2)%kami n (cb1 ++ cb2)%nb.\n  Proof.\n    unfold CmsBound in *; simpl; intros.\n    apply EquivList_trans with (l2:= getCalls m1 ++ getCalls m2).\n    - apply abstracted_app_1; auto.\n    - split; [apply getCalls_subList_1|apply getCalls_subList_2].\n  Qed.\n\n  Lemma concatMod_cmsBound_2:\n    forall m1 m2 n cb,\n      CmsBound m1 n cb ->\n      CmsBound m2 n cb ->\n      CmsBound (m1 ++ m2)%kami n cb.\n  Proof.\n    unfold CmsBound in *; simpl; intros.\n    apply EquivList_trans with (l2:= getCalls m1 ++ getCalls m2).\n    - apply abstracted_app_2; auto.\n    - split; [apply getCalls_subList_1|apply getCalls_subList_2].\n  Qed.\n\n  (** normal boundaries *)\n  \n  Definition getRegsBound (m: Modules) := Build_NameBound (namesOf (getRegInits m)) nil.\n  Definition getDmsBound (m: Modules) := Build_NameBound (getDefs m) nil.\n  Definition getCmsBound (m: Modules) := Build_NameBound (getCalls m) nil.\n\n  Lemma getRegsBound_bounded:\n    forall m n, RegsBound m n (getRegsBound m).\n  Proof. intros; apply abstracted_originals_refl. Qed.\n\n  Lemma getDmsBound_bounded:\n    forall m n, DmsBound m n (getDmsBound m).\n  Proof. intros; apply abstracted_originals_refl. Qed.\n  \n  Lemma getCmsBound_bounded:\n    forall m n, CmsBound m n (getCmsBound m).\n  Proof. intros; apply abstracted_originals_refl. Qed.\n\n  Lemma getRegsBound_modular:\n    forall m1 m2 n,\n      RegsBound m1 n (getRegsBound m1) ->\n      RegsBound m2 n (getRegsBound m2) ->\n      RegsBound (m1 ++ m2)%kami n (getRegsBound (m1 ++ m2)%kami).\n  Proof.\n    intros.\n    replace (getRegsBound (m1 ++ m2)%kami) with (getRegsBound m1 ++ getRegsBound m2)%nb.\n    - apply concatMod_regsBound_1; auto.\n    - unfold getRegsBound, appendNameBound; simpl.\n      unfold RegInitT; rewrite namesOf_app; reflexivity.\n  Qed.\n  \n  Lemma getDmsBound_modular:\n    forall m1 m2 n,\n      DmsBound m1 n (getDmsBound m1) ->\n      DmsBound m2 n (getDmsBound m2) ->\n      DmsBound (m1 ++ m2)%kami n (getDmsBound (m1 ++ m2)%kami).\n  Proof.\n    intros.\n    replace (getDmsBound (m1 ++ m2)%kami) with (getDmsBound m1 ++ getDmsBound m2)%nb.\n    - apply concatMod_dmsBound_1; auto.\n    - unfold getDmsBound; rewrite getDefs_app; reflexivity.\n  Qed.\n\n  Lemma getCmsBound_modular:\n    forall m1 m2 n,\n      CmsBound m1 n (getCmsBound m1) ->\n      CmsBound m2 n (getCmsBound m2) ->\n      CmsBound (m1 ++ m2)%kami n (getCmsBound (m1 ++ m2)%kami).\n  Proof.\n    intros; pose proof (concatMod_cmsBound_1 H H0); clear H H0.\n    eapply EquivList_trans; eauto.\n    unfold unfoldNameBound.\n    apply EquivList_app; [|apply EquivList_refl].\n    split; [apply getCalls_subList_2|apply getCalls_subList_1].\n  Qed.\n\n  (** duplicate boundaries *)\n\n  Definition getDupRegsBound m :=\n    Build_NameBound nil (namesOf (getRegInits m)).\n  Definition getDupDmsBound m :=\n    Build_NameBound nil (getDefs m).\n  Definition getDupCmsBound m :=\n    Build_NameBound nil (getCalls m).\n\n  Lemma getDupNameBound_concat_vertical:\n    forall names n,\n      EquivList\n        (concat (map (fun p => (p) __ (S n) :: duplicateElt p n) names))\n        ((map (spf (S n)) names)\n           ++ (concat (map (fun p : string => duplicateElt p n) names))).\n  Proof.\n    induction names; simpl; intros; [apply EquivList_nil|].\n    apply EquivList_cons; auto.\n    eapply EquivList_trans.\n    - apply EquivList_app.\n      + apply EquivList_refl.\n      + apply IHnames.\n    - clear; equivList_app_tac.\n  Qed.\n\n  Lemma getDupRegsBound_bounded:\n    forall m n,\n      (forall i, Specializable (m i)) ->\n      (forall i j, getDupRegsBound (m i) = getDupRegsBound (m j)) ->\n      RegsBound (duplicate m n) n (getDupRegsBound (m 0)).\n  Proof.\n    unfold RegsBound, Abstracted, unfoldNameBound; simpl; intros.\n    induction n; simpl; intros.\n    - rewrite specializeMod_regs by auto.\n      generalize (namesOf (getRegInits (m 0))) as regs; clear.\n      induction regs; simpl; intros; [apply EquivList_nil|].\n      apply EquivList_cons; auto.\n    - unfold RegInitT; rewrite namesOf_app.\n      rewrite specializeMod_regs by auto.\n      match goal with\n      | [H: EquivList ?ilhs _ |- EquivList ?lhs (?nl ++ _) ] =>\n        apply EquivList_trans with (l2:= (nl ++ ilhs))\n      end.\n      + specialize (H0 0 (S n)); inv H0.\n        apply getDupNameBound_concat_vertical.\n      + apply EquivList_app; [apply EquivList_refl|auto].\n  Qed.\n\n  Lemma getDupDmsBound_bounded:\n    forall m n,\n      (forall i, Specializable (m i)) ->\n      (forall i j, getDupDmsBound (m i) = getDupDmsBound (m j)) ->\n      DmsBound (duplicate m n) n (getDupDmsBound (m 0)).\n  Proof.\n    unfold DmsBound, Abstracted, unfoldNameBound; simpl; intros.\n    induction n; simpl; intros.\n    - rewrite specializeMod_defs by auto.\n      generalize (getDefs (m 0)) as dms; clear.\n      induction dms; simpl; intros; [apply EquivList_nil|].\n      apply EquivList_cons; auto.\n    - rewrite getDefs_app.\n      rewrite specializeMod_defs by auto.\n      match goal with\n      | [H: EquivList ?ilhs _ |- EquivList ?lhs (?nl ++ _) ] =>\n        apply EquivList_trans with (l2:= (nl ++ ilhs))\n      end.\n      + specialize (H0 0 (S n)); inv H0.\n        apply getDupNameBound_concat_vertical.\n      + apply EquivList_app; [apply EquivList_refl|auto].\n  Qed.\n\n  Lemma getDupCmsBound_bounded:\n    forall m n,\n      (forall i, Specializable (m i)) ->\n      (forall i j, getDupCmsBound (m i) = getDupCmsBound (m j)) ->\n      CmsBound (duplicate m n) n (getDupCmsBound (m 0)).\n  Proof.\n    unfold CmsBound, Abstracted, unfoldNameBound; simpl; intros.\n    induction n; simpl; intros.\n    - rewrite specializeMod_calls by auto.\n      generalize (getCalls (m 0)) as cms; clear.\n      induction cms; simpl; intros; [apply EquivList_nil|].\n      apply EquivList_cons; auto.\n    - apply EquivList_trans with\n      (l2:= getCalls (specializeMod (m (S n)) (S n)) ++ getCalls (duplicate m n));\n        [|split; [apply getCalls_subList_1|apply getCalls_subList_2]].\n      rewrite specializeMod_calls by auto.\n      match goal with\n      | [H: EquivList ?ilhs _ |- EquivList ?lhs (?nl ++ _) ] =>\n        apply EquivList_trans with (l2:= (nl ++ ilhs))\n      end.\n      + specialize (H0 0 (S n)); inv H0.\n        apply getDupNameBound_concat_vertical.\n      + apply EquivList_app; [apply EquivList_refl|auto].\n  Qed.\n\nEnd Bounds.\n\nSection Correctness.\n\n  Lemma disjNameBound_DisjList:\n    forall ss1 ss2,\n      DisjNameBound ss1 ss2 ->\n      forall n l1 l2,\n        Abstracted n ss1 l1 -> Abstracted n ss2 l2 ->\n        DisjList l1 l2.\n  Proof.\n    unfold DisjNameBound, Abstracted, DisjList; intros.\n    destruct (in_dec string_dec e l1); [|left; auto].\n    destruct (in_dec string_dec e l2); [|right; auto].\n\n    exfalso; dest.\n    inv H0; inv H1; clear H0 H5.\n    specialize (H6 _ i); specialize (H7 _ i0); clear i i0.\n    unfold unfoldNameBound in H6, H7.\n    apply in_app_or in H6; apply in_app_or in H7.\n    destruct H6, H7.\n    - destruct (H3 e); auto.\n    - clear -H H0 H1 H2; apply in_concat_iff in H1; destruct H1 as [l ?]; dest.\n      apply in_map_iff in H1; destruct H1 as [s ?]; dest; subst; simpl in *.\n      pose proof (hasNoIndex_duplicateElt_DisjList _ s n H e) as Hd.\n      destruct Hd; auto.\n    - clear -H0 H1 H2.\n      induction (prefixes ss1); [inv H0|].\n      simpl in H0; apply in_app_or in H0; destruct H0; auto.\n      pose proof (hasNoIndex_duplicateElt_DisjList _ a n H2 e) as Hd.\n      destruct Hd; auto.\n    - clear -H0 H1 H4.\n      pose proof (duplicateElt_concat_DisjList n H4 e); destruct H; auto.\n  Qed.\n\n  Lemma regsBound_disj_regs:\n    forall mb1 mb2,\n      DisjNameBound mb1 mb2 ->\n      forall n m1 m2,\n        RegsBound m1 n mb1 -> RegsBound m2 n mb2 ->\n        DisjList (namesOf (getRegInits m1)) (namesOf (getRegInits m2)).\n  Proof.\n    intros; eapply disjNameBound_DisjList; eauto.\n  Qed.\n\n  Lemma dmsBound_disj_dms:\n    forall mb1 mb2,\n      DisjNameBound mb1 mb2 ->\n      forall n m1 m2,\n        DmsBound m1 n mb1 -> DmsBound m2 n mb2 ->\n        DisjList (getDefs m1) (getDefs m2).\n  Proof.\n    intros; eapply disjNameBound_DisjList; eauto.\n  Qed.\n\n  Lemma cmsBound_disj_calls:\n    forall mb1 mb2,\n      DisjNameBound mb1 mb2 ->\n      forall n m1 m2,\n        CmsBound m1 n mb1 -> CmsBound m2 n mb2 ->\n        DisjList (getCalls m1) (getCalls m2).\n  Proof.\n    intros; eapply disjNameBound_DisjList; eauto.\n  Qed.\n\n  Lemma bound_disj_dms_calls:\n    forall mb1 mb2,\n      DisjNameBound mb1 mb2 ->\n      forall n m1 m2,\n        DmsBound m1 n mb1 -> CmsBound m2 n mb2 ->\n        DisjList (getDefs m1) (getCalls m2).\n  Proof.\n    intros; eapply disjNameBound_DisjList; eauto.\n  Qed.\n\n  Lemma bound_disj_calls_dms:\n    forall mb1 mb2,\n      DisjNameBound mb1 mb2 ->\n      forall n m1 m2,\n        CmsBound m1 n mb1 -> DmsBound m2 n mb2 ->\n        DisjList (getCalls m1) (getDefs m2).\n  Proof.\n    intros; eapply disjNameBound_DisjList; eauto.\n  Qed.\n\n  Lemma bound_disj_extDefs_calls:\n    forall dnb1 cnb1 cnb2,\n      hasNoIndex (originals dnb1) = true ->\n      hasNoIndex (originals cnb1) = true ->\n      DisjNameBound (subtractNameBound dnb1 cnb1) cnb2 ->\n      forall n m1 m2,\n        DmsBound m1 n dnb1 -> CmsBound m1 n cnb1 -> CmsBound m2 n cnb2 ->\n        DisjList (getExtDefs m1) (getCalls m2).\n  Proof.\n    intros.\n    eapply disjNameBound_DisjList; eauto.\n    apply subtractNameBound_filter_abstracted; auto.\n  Qed.\n\n  Lemma bound_disj_extCalls_defs:\n    forall dnb1 cnb1 dnb2,\n      hasNoIndex (originals dnb1) = true ->\n      hasNoIndex (originals cnb1) = true ->\n      DisjNameBound (subtractNameBound cnb1 dnb1) dnb2 ->\n      forall n m1 m2,\n        DmsBound m1 n dnb1 -> CmsBound m1 n cnb1 -> DmsBound m2 n dnb2 ->\n        DisjList (getExtCalls m1) (getDefs m2).\n  Proof.\n    intros.\n    eapply disjNameBound_DisjList; eauto.\n    apply subtractNameBound_filter_abstracted; auto.\n  Qed.\n\n  Lemma bound_disj_intCalls_calls:\n    forall dnb1 cnb1 cnb2,\n      hasNoIndex (originals dnb1) = true ->\n      hasNoIndex (originals cnb1) = true ->\n      DisjNameBound (intersectNameBound cnb1 dnb1) cnb2 ->\n      forall n m1 m2,\n        DmsBound m1 n dnb1 -> CmsBound m1 n cnb1 -> CmsBound m2 n cnb2 ->\n        DisjList (getIntCalls m1) (getCalls m2).\n  Proof.\n    intros.\n    eapply disjNameBound_DisjList; eauto.\n    apply intersectNameBound_filter_abstracted; auto.\n  Qed.\n\n  Lemma bound_disj_calls_intCalls:\n    forall cnb1 dnb2 cnb2,\n      hasNoIndex (originals dnb2) = true ->\n      hasNoIndex (originals cnb2) = true ->\n      DisjNameBound cnb1 (intersectNameBound cnb2 dnb2) ->\n      forall n m1 m2,\n        CmsBound m1 n cnb1 -> DmsBound m2 n dnb2 -> CmsBound m2 n cnb2 -> \n        DisjList (getCalls m1) (getIntCalls m2).\n  Proof.\n    intros.\n    eapply disjNameBound_DisjList; eauto.\n    apply intersectNameBound_filter_abstracted; auto.\n  Qed.\n\nEnd Correctness.\n\n(** Tactics *)\n\nLtac get_regs_bound_ex m :=\n  lazymatch m with\n  | ConcatMod ?m1 ?m2 =>\n    let nb1 := get_regs_bound_ex m1 in\n    let nb2 := get_regs_bound_ex m2 in\n    constr:(appendNameBound nb1 nb2)\n  | duplicate ?sm _ => constr:(getDupRegsBound (sm 0))\n  | makeModule _ => constr:(getRegsBound m)\n  | PrimMod _ => constr:(getRegsBound m)\n  | Mod _ _ _ => constr:(getRegsBound m)\n  | _ => let m' := eval red in m in get_regs_bound_ex m'\n  end.\n\nLtac get_dms_bound_ex m :=\n  lazymatch m with\n  | ConcatMod ?m1 ?m2 =>\n    let nb1 := get_dms_bound_ex m1 in\n    let nb2 := get_dms_bound_ex m2 in\n    constr:(appendNameBound nb1 nb2)\n  | duplicate ?sm _ => constr:(getDupDmsBound (sm 0))\n  | makeModule _ => constr:(getDmsBound m)\n  | PrimMod _ => constr:(getDmsBound m)\n  | Mod _ _ _ => constr:(getDmsBound m)\n  | _ => let m' := eval red in m in get_dms_bound_ex m'\n  end.\n\nLtac get_cms_bound_ex m :=\n  lazymatch m with\n  | ConcatMod ?m1 ?m2 =>\n    let nb1 := get_cms_bound_ex m1 in\n    let nb2 := get_cms_bound_ex m2 in\n    constr:(appendNameBound nb1 nb2)\n  | duplicate ?sm _ => constr:(getDupCmsBound (sm 0))\n  | makeModule _ => constr:(getCmsBound m)\n  | PrimMod _ => constr:(getCmsBound m)\n  | Mod _ _ _ => constr:(getCmsBound m)\n  | _ => let m' := eval red in m in get_cms_bound_ex m'\n  end.\n\nLtac red_to_regs_bound_ex rn :=\n  match goal with\n  | [ |- DisjList (namesOf (getRegInits ?m1))\n                  (namesOf (getRegInits ?m2)) ] =>\n    let mb1' := get_regs_bound_ex m1 in\n    let mb2' := get_regs_bound_ex m2 in\n    apply regsBound_disj_regs with (n:= rn) (mb1 := mb1') (mb2 := mb2')\n  | [ |- DisjList (map _ (getRegInits ?m1))\n                  (map _ (getRegInits ?m2)) ] =>\n    let mb1' := get_regs_bound_ex m1 in\n    let mb2' := get_regs_bound_ex m2 in\n    apply regsBound_disj_regs with (n:= rn) (mb1 := mb1') (mb2 := mb2')\n  end.\n\nLtac red_to_dms_bound_ex dn :=\n  match goal with\n  | [ |- DisjList (getDefs ?m1) (getDefs ?m2) ] =>\n    let mb1' := get_dms_bound_ex m1 in\n    let mb2' := get_dms_bound_ex m2 in\n    apply dmsBound_disj_dms with (n:= dn) (mb1 := mb1') (mb2 := mb2')\n  | [ |- DisjList (namesOf (getDefsBodies ?m1)) (namesOf (getDefsBodies ?m2)) ] =>\n    let mb1' := get_dms_bound_ex m1 in\n    let mb2' := get_dms_bound_ex m2 in\n    apply dmsBound_disj_dms with (n:= dn) (mb1 := mb1') (mb2 := mb2')\n  end.\n\nLtac red_to_cms_bound_ex cn :=\n  match goal with\n  | [ |- DisjList (getCalls ?m1) (getCalls ?m2) ] =>\n    let mb1' := get_cms_bound_ex m1 in\n    let mb2' := get_cms_bound_ex m2 in\n    apply cmsBound_disj_calls with (n:= cn) (mb1 := mb1') (mb2 := mb2')\n  end.\n\nLtac red_to_dc_bound_ex cn :=\n  match goal with\n  | [ |- DisjList (getDefs ?m1) (getCalls ?m2) ] =>\n    let mb1' := get_dms_bound_ex m1 in\n    let mb2' := get_cms_bound_ex m2 in\n    apply bound_disj_dms_calls with (n:= cn) (mb1 := mb1') (mb2 := mb2')\n  end.\n\nLtac red_to_cd_bound_ex cn :=\n  match goal with\n  | [ |- DisjList (getCalls ?m1) (getDefs ?m2) ] =>\n    let mb1' := get_cms_bound_ex m1 in\n    let mb2' := get_dms_bound_ex m2 in\n    apply bound_disj_calls_dms with (n:= cn) (mb1 := mb1') (mb2 := mb2')\n  end.\n\nLtac red_to_edc_bound_ex cn :=\n  match goal with\n  | [ |- DisjList (getExtDefs ?m1) (getCalls ?m2) ] =>\n    let dnb1' := get_dms_bound_ex m1 in\n    let cnb1' := get_cms_bound_ex m1 in\n    let cnb2' := get_cms_bound_ex m2 in\n    apply bound_disj_extDefs_calls with (n:= cn) (dnb1:= dnb1') (cnb1:= cnb1') (cnb2:= cnb2')\n  end.\n\nLtac red_to_ecd_bound_ex cn :=\n  match goal with\n  | [ |- DisjList (getExtCalls ?m1) (getDefs ?m2) ] =>\n    let dnb1' := get_dms_bound_ex m1 in\n    let cnb1' := get_cms_bound_ex m1 in\n    let dnb2' := get_dms_bound_ex m2 in\n    apply bound_disj_extCalls_defs with (n:= cn) (dnb1:= dnb1') (cnb1:= cnb1') (dnb2:= dnb2')\n  end.\n\nLtac red_to_icc_bound_ex cn :=\n  match goal with\n  | [ |- DisjList (getIntCalls ?m1) (getCalls ?m2) ] =>\n    let dnb1' := get_dms_bound_ex m1 in\n    let cnb1' := get_cms_bound_ex m1 in\n    let cnb2' := get_cms_bound_ex m2 in\n    apply bound_disj_intCalls_calls with (n:= cn) (dnb1:= dnb1') (cnb1:= cnb1') (cnb2:= cnb2')\n  end.\n\nLtac red_to_cic_bound_ex cn :=\n  match goal with\n  | [ |- DisjList (getCalls ?m1) (getIntCalls ?m2) ] =>\n    let cnb1' := get_cms_bound_ex m1 in\n    let dnb2' := get_dms_bound_ex m2 in\n    let cnb2' := get_cms_bound_ex m2 in\n    apply bound_disj_calls_intCalls with (n:= cn) (cnb1:= cnb1') (dnb2:= dnb2') (cnb2:= cnb2')\n  end.\n\nLtac regs_bound_tac_unit_ex :=\n  match goal with\n  | [ |- RegsBound (ConcatMod _ _) _ (appendNameBound _ _) ] =>\n    apply concatMod_regsBound_1\n  | [ |- RegsBound (ConcatMod _ _) _ _ ] =>\n    apply getRegsBound_modular\n  | [ |- RegsBound (duplicate _ _) _ _ ] =>\n    apply getDupRegsBound_bounded; auto\n  | [ |- RegsBound ?m _ _ ] => unfold_head m\n  | _ => apply getRegsBound_bounded\n  end.\nLtac regs_bound_tac_ex := repeat regs_bound_tac_unit_ex.\n\nLtac dms_bound_tac_unit_ex :=\n  match goal with\n  | [ |- DmsBound (ConcatMod _ _) _ (appendNameBound _ _) ] =>\n    apply concatMod_dmsBound_1\n  | [ |- DmsBound (ConcatMod _ _) _ _ ] =>\n    apply getDmsBound_modular\n  | [ |- DmsBound (duplicate _ _) _ _ ] =>\n    apply getDupDmsBound_bounded; auto\n  | [ |- DmsBound ?m _ _ ] => unfold_head m\n  | _ => apply getDmsBound_bounded\n  end.\nLtac dms_bound_tac_ex := repeat dms_bound_tac_unit_ex.\n\nLtac cms_bound_tac_unit_ex :=\n  match goal with\n  | [ |- CmsBound (ConcatMod _ _) _ (appendNameBound _ _) ] =>\n    apply concatMod_cmsBound_1\n  | [ |- CmsBound (ConcatMod _ _) _ _ ] =>\n    apply getCmsBound_modular\n  | [ |- CmsBound (duplicate _ _) _ _ ] =>\n    apply getDupCmsBound_bounded; auto\n  | [ |- CmsBound ?m _ _ ] => unfold_head m\n  | _ => apply getCmsBound_bounded\n  end.\nLtac cms_bound_tac_ex := repeat cms_bound_tac_unit_ex.\n\nLtac kdisj_regs_ex n :=\n  red_to_regs_bound_ex n;\n  [apply disjNameBound_DisjNameBound; reflexivity\n  |regs_bound_tac_ex\n  |regs_bound_tac_ex].\n\nLtac kdisj_dms_ex n :=\n  red_to_dms_bound_ex n;\n  [apply disjNameBound_DisjNameBound; reflexivity\n  |dms_bound_tac_ex\n  |dms_bound_tac_ex].\n\nLtac kdisj_cms_ex n :=\n  red_to_cms_bound_ex n;\n  [apply disjNameBound_DisjNameBound; reflexivity\n  |cms_bound_tac_ex\n  |cms_bound_tac_ex].\n\nLtac kdisj_dms_cms_ex n :=\n  red_to_dc_bound_ex n;\n  [apply disjNameBound_DisjNameBound; reflexivity\n  |dms_bound_tac_ex\n  |cms_bound_tac_ex].\n\nLtac kdisj_cms_dms_ex n :=\n  red_to_cd_bound_ex n;\n  [apply disjNameBound_DisjNameBound; reflexivity\n  |cms_bound_tac_ex\n  |dms_bound_tac_ex].\n\nLtac kdisj_edms_cms_ex n :=\n  red_to_edc_bound_ex n;\n  [reflexivity|reflexivity\n   |apply disjNameBound_DisjNameBound; reflexivity\n   |dms_bound_tac_ex\n   |cms_bound_tac_ex\n   |cms_bound_tac_ex].\n\nLtac kdisj_ecms_dms_ex n :=\n  red_to_ecd_bound_ex n;\n  [reflexivity|reflexivity\n   |apply disjNameBound_DisjNameBound; reflexivity\n   |dms_bound_tac_ex\n   |cms_bound_tac_ex\n   |dms_bound_tac_ex].\n\nLtac kdisj_icms_cms_ex n :=\n  red_to_icc_bound_ex n;\n  [reflexivity|reflexivity\n   |apply disjNameBound_DisjNameBound; reflexivity\n   |dms_bound_tac_ex\n   |cms_bound_tac_ex\n   |cms_bound_tac_ex].\n\nLtac kdisj_cms_icms_ex n :=\n  red_to_cic_bound_ex n;\n  [reflexivity|reflexivity\n   |apply disjNameBound_DisjNameBound; reflexivity\n   |cms_bound_tac_ex\n   |dms_bound_tac_ex\n   |cms_bound_tac_ex].\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/ModuleBoundEx.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.26747121402990676}}
{"text": "(*******************************************************************************)\n(*  © Université de Lille, The Pip Development Team (2015-2021)                *)\n(*                                                                             *)\n(*  This software is x computer program whose purpose is to run x minimal,     *)\n(*  hypervisor relying on proven properties such as memory isolation.          *)\n(*                                                                             *)\n(*  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 x 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(** * Summary\n    This module defines operations (both pure and monadic) on pip data types *)\n\nRequire Import Pip.Model.ADT Pip.Model.Hardware Pip.Model.Lib.\nRequire Import List Arith Lia.\n\nDefinition idxEq (x y : index) : bool := x =? y.\nDefinition idxGe (x y : index) : bool := y <=? x.\nDefinition idxGt (x y : index) : bool := y <? x.\nDefinition idxLe (x y : index) : bool := x <=? y.\nDefinition idxLt (x y : index) : bool := x <? y.\n\nDefinition idxEqM (x y : index) := ret (idxEq x y).\nDefinition idxGeM (x y : index) := ret (idxGe x y).\nDefinition idxGtM (x y : index) := ret (idxGt x y).\nDefinition idxLeM (x y : index) := ret (idxLe x y).\nDefinition idxLtM (x y : index) := ret (idxLt x y).\n\nProgram Definition idxPredM (n : index) : LLI index :=\n  let (i,P) := n in\n  if gt_dec i 0\n  then let ipred := i-1 in\n       ret (Build_index ipred _)\n  else undefined 27.\nNext Obligation. lia. Qed.\n\nProgram Definition idxSuccM (n : index) : LLI index :=\n  let isucc := n+1 in\n  if lt_dec isucc tableSize\n  then ret (Build_index isucc _)\n  else undefined 28.\n\nDefinition vaddrEq (x y : vaddr) : bool := eqList x y idxEq.\nDefinition vaddrEqM (x y : vaddr) := ret (vaddrEq x y).\n\nDefinition pageEq (x y : page) : bool := x =? y.\nDefinition pageEqM (x y : page) := ret (pageEq x y).\n\nDefinition levelEq (x y : level) : bool := x =? y.\nDefinition levelGt (x y : level) : bool := y <? x.\n\nDefinition levelEqM (x y : level) := ret (levelEq x y).\nDefinition levelGtM (x y : level) := ret (levelGt x y).\n\nProgram Definition levelPredM (n : level) : LLI level :=\n  if gt_dec n 0\n  then let ipred := n-1 in\n       ret (Build_level ipred _)\n  else undefined 30.\nNext Obligation.\ndestruct n; simpl; lia.\nQed.\n\nProgram Definition levelSuccM (n : level) : LLI level :=\n  let isucc := n+1 in\n  if lt_dec isucc nbLevel\n  then ret (Build_level isucc _)\n  else undefined 31.\n\nDefinition countEq (x y : count) : bool := x =? y.\nDefinition countGe (x y : count) : bool := y <=? x.\n\nDefinition countEqM (x y : count) := ret (countEq x y).\nDefinition countGeM (x y : count) := ret (countGe x y).\n\nProgram Definition countSuccM (n : count) : LLI count :=\n  let isucc := n+1 in\n  if le_dec isucc (3 * nbLevel + 1)\n  then ret (Build_count isucc _)\n  else undefined 34.\n\nProgram Definition countFromLevelM (x : level) : LLI count :=\n  ret (Build_count (x * 3) _).\nNext Obligation.\n  destruct x; simpl.\n  (* BEGIN SIMULATION\n    unfold nbLevel in Hl.\n     END SIMULATION *)\n  lia.\nQed.\n", "meta": {"author": "2xs", "repo": "pipcore", "sha": "436a5995dd0d60d8bd8866c1ed5cecabe031727f", "save_path": "github-repos/coq/2xs-pipcore", "path": "github-repos/coq/2xs-pipcore/pipcore-436a5995dd0d60d8bd8866c1ed5cecabe031727f/src/model/Ops.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.26740164700971286}}
{"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.  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 continuity.\nRequire Export stronger_continuity_defs1.\nRequire Export stronger_continuity_defs3.\nRequire Export list.  (* WTF!! *)\n\n\n\nLemma cequiv_bound_nat_bound {o} :\n  forall lib (a : get_patom_set o) (x e z : NVar) (k : nat) (f : @NTerm o),\n    (forall t n,\n       n < k\n       -> computes_to_value lib t (mk_nat n)\n       -> {j : nat & computes_to_value lib (mk_apply f t) (mk_nat j)})\n    -> cequiv\n         lib\n         (bound_nat a x e z (bound x (mk_utoken a) (mk_nat k) f))\n         (mk_lam x (mk_less (mk_var x) mk_zero (mk_vbot z)\n                            (mk_less (mk_var x) (mk_nat k)\n                                     (mk_apply f (mk_var x))\n                                     (spexc a)))).\nProof.\n  introv imp.\n\nAbort.\n\nLemma cequiv_sp_bound_nat_c_bound_c {o} :\n  forall lib v z (e n f : @CTerm o),\n    cequivc\n      lib\n      (sp_bound_nat_c v z (bound_c e n f v))\n      (bound2_c v z n f e).\nProof.\n  introv.\n\n  apply cequivc_lam; introv.\n  allrw @mkcv_less_substc.\n  allrw @mkcv_apply_substc.\n  allrw @substc_mkcv_zero.\n  allrw @mkc_var_substc.\n  allrw @csubst_mk_cv.\n  allrw @mkcv_vbot_substc.\n\n  eapply cequivc_trans;\n    [apply cequivc_mkc_less;\n      [apply cequivc_refl\n      |apply cequivc_refl\n      |apply cequivc_refl\n      |apply cequivc_apply_bound_c]\n    |].\n  rw @boundl_c_eq; auto.\nQed.\n\nLemma substc_mkcv_axiom {o} :\n  forall v (t : @CTerm o),\n    substc t v (mkcv_axiom v) = mkc_axiom.\nProof.\n  introv; destruct_cterms.\n  apply cterm_eq; simpl.\n  unfsubst.\nQed.\n\nLemma spM_in_modulus_fun_type_u {o} :\n  forall lib (F : @CTerm o),\n    member lib F (mkc_fun nat2nat mkc_tnat)\n    -> member lib (spM_c F) modulus_fun_type_u.\nProof.\n  introv mF.\n\n  unfold modulus_fun_type_u.\n  apply equality_in_function2.\n  fold (@modulus_fun_type_u o).\n  dands; try (apply type_modulus_fun_type_u).\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      apply type_tnat.\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\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 (@natk2nat o (mkc_nat k)) 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_natk2nat_implies_equality_bound lib f g k 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    pose proof (apply_nat2natE_aux2\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) as ee.\n    repeat (autodimp ee hyp); try (complete (intro xx; ginv));[].\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\nDefinition get_ints_from_computes_to_value {o}\n           (lib : @library o)\n           (t u : @NTerm o)\n           (comp : computes_to_value lib t u) : list Z :=\n  match comp with\n    | (c,_) => get_ints_from_computation lib t u c\n  end.\n\nDefinition get_ints_from_computes_to_valc {o}\n           (lib : @library o)\n           (t u : @CTerm o)\n           (comp : computes_to_valc lib t u) : list Z :=\n  get_ints_from_computes_to_value lib (get_cterm t) (get_cterm u) comp.\n\nLemma cequivc_nat {o} :\n  forall lib (t t' : @CTerm o) (n : nat),\n    computes_to_valc lib t (mkc_nat n)\n    -> cequivc lib t t'\n    -> computes_to_valc lib t' (mkc_nat n).\nProof.\n  introv comp ceq; destruct_cterms;\n  allunfold @computes_to_valc; allunfold @cequivc; allsimpl.\n  eapply cequiv_nat; eauto.\nQed.\n\nDefinition force_nat {o} (arg : @NTerm o) x z (f : @NTerm o) :=\n  mk_cbv arg x (mk_less (mk_var x)\n                        mk_zero\n                        (mk_vbot z)\n                        (mk_apply f (mk_var x))).\n\nDefinition force_nat_c {o} (arg : @CTerm o) x z (f : @CTerm o) : CTerm :=\n  mkc_cbv\n    arg\n    x\n    (mkcv_less\n       [x]\n       (mkc_var x)\n       (mkcv_zero [x])\n       (mkcv_vbot [x] z)\n       (mkcv_apply [x] (mk_cv [x] f) (mkc_var x))).\n\nLemma get_cterm_force_nat_c {o} :\n  forall (arg : @CTerm o) x z f,\n    get_cterm (force_nat_c arg x z f)\n    = force_nat (get_cterm arg) x z (get_cterm f).\nProof.\n  introv; destruct_cterms; simpl; auto.\nQed.\n\nDefinition lam_force_nat_c {o} x z (f : @CTerm o) : CTerm :=\n  mkc_lam\n    x\n    (mkcv_cbv\n       [x]\n       (mkc_var x)\n       x\n       (mkcv_dup1\n          x\n          (mkcv_less\n             [x]\n             (mkc_var x)\n             (mkcv_zero [x])\n             (mkcv_vbot [x] z)\n             (mkcv_apply [x] (mk_cv [x] f) (mkc_var x))))).\n\nLemma cequivc_mkc_apply_lam_force_nat_c {o} :\n  forall lib x z (f arg : @CTerm o),\n    cequivc\n      lib\n      (mkc_apply (lam_force_nat_c x z f) arg)\n      (force_nat_c arg x z f).\nProof.\n  introv.\n  eapply cequivc_trans;[unfold lam_force_nat_c;apply cequivc_beta|].\n  rw @mkcv_cbv_substc_same.\n  rw @mkc_var_substc.\n  rw @mkcv_cont1_dup1; eauto 3 with slow.\nQed.\n\nLemma equality_lam_force_nat_c_in_nat2nat {o} :\n  forall lib x z (f : @CTerm o),\n    member lib f nat2nat\n    -> equality lib f (lam_force_nat_c x z f) nat2nat.\nProof.\n  introv mem.\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 eq_mkc_nat_implies {o} :\n  forall k1 k2, @mkc_nat o k1 = mkc_nat k2 -> k1 = k2.\nProof.\n  introv e.\n  inversion e as [q].\n  allapply Znat.Nat2Z.inj; auto.\nQed.\n\nDefinition bound2_cbv_c {o} x z (n f e : @CTerm o) :=\n  mkc_lam\n    x\n    (mkcv_cbv\n       [x]\n       (mkc_var x)\n       x\n       (mkcv_dup1\n          x\n          (mkcv_less\n             [x]\n             (mkc_var x)\n             (mkcv_zero [x])\n             (mkcv_vbot [x] z)\n             (mkcv_less\n                [x]\n                (mkc_var x)\n                (mk_cv [x] n)\n                (mkcv_apply [x] (mk_cv [x] f) (mkc_var x))\n                (mk_cv [x] (mkc_exception e mkc_axiom)))))).\n\nLemma cequiv_bound2_c_cbv {o} :\n  forall lib x z (n f e : @CTerm o),\n    cequivc\n      lib\n      (bound2_c x z n f e)\n      (bound2_cbv_c x z n f e).\nProof.\n  introv.\n  apply cequivc_lam; introv.\n  allrw @mkcv_less_substc.\n  allrw @mkcv_cbv_substc_same.\n  allrw @mkcv_cont1_dup1.\n  allrw @mkcv_apply_substc.\n  allrw @substc_mkcv_zero.\n  allrw @mkc_var_substc.\n  allrw @csubst_mk_cv.\n  allrw @mkcv_vbot_substc.\n\n  apply approxc_implies_cequivc; apply approxc_assume_hasvalue; intro hv.\n\n  - apply hasvalue_likec_less in hv.\n    repndors; exrepnd.\n\n    + clear hv1 hv3 hv2.\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_mkc_less;\n          [apply reduces_toc_implies_cequivc;exact hv0\n          |apply cequivc_refl\n          |apply implies_cequivc_apply;\n            [apply cequivc_refl\n            |apply reduces_toc_implies_cequivc;exact hv0]\n          |apply cequivc_refl]\n        ]\n      |].\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\n      clear dependent u.\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      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      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      boolvar; eauto 3 with slow; try (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.\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_mkc_less;\n             [apply cequivc_sym\n             |apply cequivc_refl\n             |apply implies_cequivc_apply;\n               [apply cequivc_refl\n               |apply cequivc_sym]\n             |apply cequivc_refl]\n           ];\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      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      apply approxc_refl.\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.\nQed.\n\nDefinition sp_force_nat {o} (arg : @NTerm o) x z (f : @NTerm o) :=\n  mk_cbv arg x (mk_less (mk_var x) mk_zero (mk_vbot z) (mk_apply f (mk_var x))).\n\nDefinition bound2_cbv {o} arg x z (n : nat) (f : @NTerm o) a : NTerm :=\n  mk_cbv\n    arg\n    x\n    (mk_less\n       (mk_var x)\n       mk_zero\n       (mk_vbot z)\n       (mk_less (mk_var x) (mk_nat n) (mk_apply f (mk_var x)) (spexc a))).\n\nLemma alpha_eq_sp_force_nat {o} :\n  forall (arg1 arg2 : @NTerm o) x1 x2 z1 z2 f1 f2,\n    isprog f1\n    -> alpha_eq f1 f2\n    -> alpha_eq arg1 arg2\n    -> alpha_eq (sp_force_nat arg1 x1 z1 f1) (sp_force_nat arg2 x2 z2 f2).\nProof.\n  introv ispf aeq1 aeq2.\n  applydup @alpha_eq_preserves_isprog in aeq1; auto.\n  unfold sp_force_nat, mk_cbv, mk_less, mk_apply, mk_vbot, mk_lam, mk_fix, mk_zero, nobnd.\n\n  prove_alpha_eq4.\n  introv ln.\n  repeat (destruct n; tcsp); eauto 3 with slow;[].\n  clear ln.\n\n  pose proof (ex_fresh_var (x1 :: x2\n                               :: z1\n                               :: z2\n                               :: free_vars f1\n                               ++ bound_vars f1\n                               ++ free_vars f2\n                               ++ bound_vars f2)) as h;\n    exrepnd.\n  allsimpl; allrw in_app_iff; allrw not_over_or; repnd; GC.\n\n  apply (al_bterm_aux [v]); simpl; auto.\n\n  { unfold all_vars; simpl.\n    allrw remove_nvars_nil_l; allrw app_nil_r.\n    allrw @remove_nvars_eq; allsimpl.\n    allrw disjoint_singleton_l; allsimpl.\n    repeat (allrw in_app_iff; simpl).\n    tcsp. }\n\n  allrw <- beq_var_refl.\n  allrw memvar_singleton.\n  repeat (rw (lsubst_aux_trivial_cl_term2 f1); eauto 2 with slow).\n  repeat (rw (lsubst_aux_trivial_cl_term2 f2); eauto 2 with slow).\n\n  prove_alpha_eq4.\n  introv ln.\n\n  repeat (destruct n; tcsp; try omega); eauto 3 with slow;\n  clear ln;\n  apply alphaeqbt_nilv2;\n  prove_alpha_eq4;\n  introv ln;\n  repeat (destruct n; tcsp; try omega); eauto 3 with slow;[].\n  clear ln.\n\n  apply alphaeqbt_nilv2.\n  prove_alpha_eq4.\n  introv ln.\n  repeat (destruct n; tcsp; try omega); eauto 3 with slow;[].\n  clear ln.\n\n  pose proof (ex_fresh_var (x1 :: x2\n                               :: z1\n                               :: z2\n                               :: [])) as h;\n    exrepnd.\n  allsimpl; allrw in_app_iff; allrw not_over_or; repnd; GC.\n\n  apply (al_bterm_aux [v0]); simpl; auto.\n\n  { unfold all_vars; simpl; repeat (boolvar; allsimpl);\n    allrw disjoint_singleton_l; allsimpl; tcsp. }\n\n  repeat (boolvar; simpl); tcsp; eauto 2 with slow.\nQed.\n\nLemma alpha_eq_bound2_cbv {o} :\n  forall (arg1 arg2 : @NTerm o) x1 x2 z1 z2 b f1 f2 a,\n    isprog f1\n    -> alpha_eq f1 f2\n    -> alpha_eq arg1 arg2\n    -> alpha_eq (bound2_cbv arg1 x1 z1 b f1 a) (bound2_cbv arg2 x2 z2 b f2 a).\nProof.\n  introv ispf aeq1 aeq2.\n  applydup @alpha_eq_preserves_isprog in aeq1; auto.\n  unfold bound2_cbv, mk_cbv, mk_less, mk_apply, mk_vbot, mk_lam, mk_fix, mk_zero, nobnd.\n\n  prove_alpha_eq4.\n  introv ln.\n  repeat (destruct n; tcsp); eauto 3 with slow;[].\n  clear ln.\n\n  pose proof (ex_fresh_var (x1 :: x2\n                               :: z1\n                               :: z2\n                               :: free_vars f1\n                               ++ bound_vars f1\n                               ++ free_vars f2\n                               ++ bound_vars f2)) as h;\n    exrepnd.\n  allsimpl; allrw in_app_iff; allrw not_over_or; repnd; GC.\n\n  apply (al_bterm_aux [v]); simpl; auto.\n\n  { unfold all_vars; simpl.\n    allrw remove_nvars_nil_l; allrw app_nil_r.\n    allrw @remove_nvars_eq; allsimpl.\n    allrw disjoint_singleton_l; allsimpl.\n    repeat (allrw in_app_iff; simpl).\n    tcsp. }\n\n  allrw <- beq_var_refl.\n  allrw memvar_singleton.\n  repeat (rw (lsubst_aux_trivial_cl_term2 f1); eauto 2 with slow).\n  repeat (rw (lsubst_aux_trivial_cl_term2 f2); eauto 2 with slow).\n\n  prove_alpha_eq4.\n  introv ln.\n  repeat (destruct n; tcsp; try omega); eauto 3 with slow;\n  clear ln;\n  apply alphaeqbt_nilv2;\n  prove_alpha_eq4;\n  introv ln;\n  repeat (destruct n; tcsp; try omega); eauto 3 with slow;\n  clear ln;\n  apply alphaeqbt_nilv2;\n  prove_alpha_eq4;\n  introv ln;\n  repeat (destruct n; tcsp; try omega); eauto 3 with slow;[].\n  clear ln.\n\n  pose proof (ex_fresh_var (x1 :: x2\n                               :: z1\n                               :: z2\n                               :: [])) as h;\n    exrepnd.\n  allsimpl; allrw in_app_iff; allrw not_over_or; repnd; GC.\n\n  apply (al_bterm_aux [v0]); simpl; auto.\n\n  { unfold all_vars; simpl; repeat (boolvar; allsimpl);\n    allrw disjoint_singleton_l; allsimpl; tcsp. }\n\n  repeat (boolvar; simpl); tcsp; eauto 2 with slow.\nQed.\n\nLemma so_alphaeq_preserves_no_utokens {o} :\n  forall (t1 t2 : @SOTerm o),\n    so_alphaeq t1 t2\n    -> no_utokens t1\n    -> no_utokens t2.\nProof.\n  introv aeq nout.\n  apply get_utokens_so_soalphaeq in aeq.\n  allunfold @no_utokens.\n  rw aeq in nout; auto.\nQed.\nHint Resolve so_alphaeq_preserves_no_utokens : slow.\n\nDefinition computation_fails {o} lib (t : @NTerm o) :=\n  {s : String.string\n   & {u : NTerm\n   & {k : nat\n   & compute_at_most_k_steps lib k t = cfailure s u}}}.\n\nLemma alpha_eq_subst_sp_force_nat_alpha_eq {o} :\n  forall v z (f : @NTerm o) t,\n    isprog f\n    -> alpha_eq\n         (subst (mk_less (mk_var v) mk_zero (mk_vbot z) (mk_apply f (mk_var v))) v t)\n         (mk_less t mk_zero (mk_vbot z) (mk_apply f t)).\nProof.\n  introv isp.\n  pose proof (unfold_lsubst\n                [(v,t)]\n                (mk_less (mk_var v) mk_zero (mk_vbot z) (mk_apply f (mk_var v))))\n    as unf; exrepnd.\n  unfold subst.\n  rw unf0; clear unf0.\n  allapply @alpha_eq_mk_less; exrepnd; subst.\n  allapply @alpha_eq_mk_var; subst.\n  allapply @alpha_eq_mk_vbot; exrepnd; subst.\n  allapply @alpha_eq_mk_zero; subst.\n  allapply @alpha_eq_mk_apply; exrepnd; subst.\n  allapply @alpha_eq_mk_var; subst.\n\n  allsimpl; cpx; ginv.\n\n  allrw app_nil_r.\n  allrw disjoint_cons_l.\n  repnd.\n  rename a' into f'.\n\n  allrw memvar_singleton.\n  allrw <- @beq_var_refl.\n  rw (@lsubst_aux_trivial_cl_term2 o f'); eauto 3 with slow.\n\n  unfold mk_less, mk_apply, mk_vbot, mk_zero, mk_nat, mk_integer, mk_fix, mk_lam, mk_var, nobnd.\n  repeat (prove_alpha_eq4; eauto 2 with slow).\n\n  { pose proof (ex_fresh_var (v' :: z :: [])) as fv.\n    exrepnd; allsimpl; allrw not_over_or; repnd; GC.\n    apply (al_bterm_aux [v0]); simpl; auto;\n    repeat (boolvar; simpl); tcsp;\n    allrw disjoint_singleton_l; allsimpl; tcsp. }\nQed.\n\nLemma wf_bound2_cbv {o} :\n  forall (arg : @NTerm o) x z b f a,\n    wf_term (bound2_cbv arg x z b f a) <=> (wf_term arg # wf_term f).\nProof.\n  introv.\n  unfold bound2_cbv.\n  rw <- @wf_cbv_iff.\n  repeat (rw <- @wf_less_iff).\n  rw <- @wf_apply_iff.\n  split; intro h; repnd; dands; eauto 3 with slow.\nQed.\n\nLemma wf_sp_force_nat {o} :\n  forall (arg : @NTerm o) x z f,\n    wf_term (sp_force_nat arg x z f) <=> (wf_term arg # wf_term f).\nProof.\n  introv.\n  rw <- @wf_cbv_iff.\n  repeat (rw <- @wf_less_iff).\n  rw <- @wf_apply_iff.\n  split; intro h; repnd; dands; eauto 3 with slow.\nQed.\n\nLemma hasvalue_like_vbot {o} :\n  forall (lib : @library o) z,\n    !hasvalue_like lib (mk_vbot z).\nProof.\n  introv hv.\n  unfold hasvalue_like in hv; exrepnd.\n  apply reduces_to_vbot_if_isvalue_like in hv1; sp.\nQed.\n\nLemma not_hasvalue_like_fresh {o} :\n  forall lib (v : NVar), !@hasvalue_like o lib (mk_fresh v (mk_var v)).\nProof.\n  introv hv.\n  unfold hasvalue_like in hv; exrepnd.\n  apply reduces_in_atmost_k_step_fresh_id in hv1; sp.\nQed.\n\nLemma hasvalue_like_subst_less_seq {o} :\n  forall lib (f : @ntseq o) v a b c,\n    hasvalue_like\n      lib\n      (subst (mk_less (mk_var v) a b c) v (sterm f))\n    -> False.\nProof.\n  introv comp.\n  unfold subst, lsubst in comp; allsimpl; boolvar;\n  repndors; try (subst v'); tcsp;\n  allrw not_over_or; repnd; GC;\n  try (complete (match goal with\n                   | [ H : context[fresh_var ?l] |- _ ] =>\n                     let h := fresh \"h\" in\n                     pose proof (fresh_var_not_in l) as h;\n                   unfold all_vars in h;\n                   simpl in h;\n                   repeat (rw in_app_iff in h);\n                   repeat (rw not_over_or in h);\n                   repnd; allsimpl; tcsp\n                 end));\n  allsimpl; boolvar; tcsp; fold_terms; allrw app_nil_r.\n\n  unfold hasvalue_like, reduces_to in comp; exrepnd.\n\n  destruct k.\n\n  - allrw @reduces_in_atmost_k_steps_0; repnd; subst.\n    unfold isvalue_like in comp0; allsimpl; tcsp.\n\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    csunf comp2; allsimpl; ginv.\nQed.\n\n\n\n(*\n*** Local Variables:\n*** coq-load-path: (\".\" \"./close/\")\n*** End:\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_defs4_aux.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.26740164700971286}}
{"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 CtxtSwitchAux.Specs.save_ns_state_sysreg_state.\nRequire Import CtxtSwitchAux.LowSpecs.save_ns_state_sysreg_state.\nRequire Import CtxtSwitchAux.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_sysregs_spec\n       sysreg_write_spec\n    .\n\n  Lemma save_ns_state_sysreg_state_spec_exists:\n    forall habd habd'  labd\n           (Hspec: save_ns_state_sysreg_state_spec  habd = Some habd')\n            (Hrel: relate_RData habd labd),\n    exists labd', save_ns_state_sysreg_state_spec0  labd = Some labd' /\\ relate_RData habd' labd'.\n    Proof.\n      Local Opaque ptr_eq get_reg set_reg.\n      intros. destruct Hrel.\n      unfold save_ns_state_sysreg_state_spec, save_ns_state_sysreg_state_spec0 in *.\n      unfold sysreg_read_spec, set_ns_state_spec.\n      autounfold in Hspec.\n      hsimpl_hyp Hspec; inv Hspec; simpl_query_oracle; extract_prop_dec.\n      destruct regs_is_int64_dec in C; [|inversion C].\n      unfold Assertion.\n      repeat (unfold bind64 at 1; rewrite e; repeat simpl_update_reg; repeat (simpl priv; simpl cpu_regs; simpl_field);\n              unfold bind at 1; simpl ns_regs_el2).\n      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/CtxtSwitchAux/RefProof/restore_sysreg_state.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.26740164063736316}}
{"text": "From iris.base_logic.lib Require Export invariants.\nFrom iris.algebra Require Import auth gmap agree.\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_boxΣ Σ : 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; by auto.\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')) ∗ 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γ _]\".\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  iModIntro. iSplitL \"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γ _]\".\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  iModIntro. iSplitL \"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]\".\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  iModIntro. iSplitL \"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  iEval (rewrite internal_eq_iff later_iff big_sepM_later) in \"HeqP\".\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γ _]\".\n  iMod (box_own_auth_update γ with \"[Hγ Hγ']\") as \"[Hγ $]\"; first by iFrame.\n  iModIntro. iSplitL; last done. iNext; iExists true. 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Φ]\".\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    iModIntro. iSplitL \"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_sepM_later. 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 γ', (Q' ∗ P')%I. 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 _ _ (λ P, _) with \"[Heq] 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 _ _ (λ P, _) with \"[Heq] 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 _ _ (λ P, _) with \"[Heq1 Heq2] 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 _ _ (λ P, _) with \"[Heq1 Heq2] Hbox\").\n    iNext. iRewrite \"Heq1\". iRewrite \"Heq2\". by rewrite assoc.\nQed.\nEnd box.\n\nTypeclasses Opaque slice box.\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/boxes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.26740164063736316}}
{"text": "Require Import Common.Definitions.\nRequire Import Common.Memory.\nRequire Import Intermediate.Machine.\nRequire Import Lib.Monads.\nRequire Import Intermediate.GlobalEnv.\nRequire Import Old.Intermediate.MachineExtra.\n\nImport Intermediate.\nImport Machine.Intermediate.\nImport MachineExtra.Intermediate.\n\nFrom mathcomp Require Import ssreflect ssrfun.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nDefinition empty_global_env := {|\n  genv_interface := emptym;\n  genv_procedures := emptym;\n  genv_entrypoints := emptym\n|}.\n\nLemma prepare_global_env_empty_prog:\n  prepare_global_env empty_prog = empty_global_env.\nProof.\n  unfold prepare_global_env.\n  rewrite prepare_procedures_initial_memory_empty_program.\n  reflexivity.\nQed.\n\nLemma genv_procedures_program_link_left_in :\n  forall {p Cid},\n    Cid \\in domm (prog_interface p) ->\n  forall {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    (genv_procedures (prepare_global_env (program_link p c))) Cid =\n    (genv_procedures (prepare_global_env p)) Cid.\nProof.\n  intros p Cid Hin c Hwfp Hwfc Hlinkable Hmains.\n  rewrite (prepare_global_env_link Hwfp Hwfc Hlinkable Hmains).\n  unfold global_env_union; simpl.\n  rewrite unionmE.\n  assert\n    (exists procs, (genv_procedures (prepare_global_env p)) Cid = Some procs)\n    as [procs Hprocs]\n    by (apply /dommP; rewrite domm_genv_procedures; assumption).\n  setoid_rewrite Hprocs.\n  assumption.\nQed.\n\nLemma find_label_in_procedure_2:\n  forall G pc pc' l,\n    find_label_in_procedure G pc l = Some pc' ->\n    Pointer.block pc = Pointer.block pc'.\nProof.\n  eapply find_label_in_procedure_guarantees.\nQed.\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/GlobalEnvExtra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.26740164063736316}}
{"text": "(**\nCoLoR, a Coq library on rewriting and termination.\n\nSee the COPYRIGHTS and LICENSE files.\n\n- Frederic Blanqui, 2013-07-30\n\n* Interpretation of positive inductive data type systems\n\nas computability predicates so that the accessible arguments (that\nmust satisfy some positivity condition) of a computable constructor\nterm are computable.\n*)\n\nSet Implicit Arguments.\n\nFrom Coq Require Import IndefiniteDescription Structures.OrderedType.\nFrom CoLoR Require Import LogicUtil SN LCompSimple Tarski VecUtil SetUtil\n     RelUtil.\nFrom CoLoR Require Union SetUtil RelUtil AccUtil.\n\n\n(****************************************************************************)\n(** * Accessible supterm relation. *)\n\nModule Export Def.\n\n  Section supterm_acc.\n\n    Variables F X : Type.\n    Notation Fun := (@Fun F X).\n    Notation Te := (@Te F X).\n\n    Variable So : Type.\n    Notation Ty := (@Ty So).\n\n    Variable typ : F -> Ty.\n    Notation TypArgs := (@TypArgs F X So typ).\n\n    Variables (Acc : F -> set nat)\n      (Acc_arity : forall f i, Acc f i -> i < arity (typ f)).\n\n    Inductive supterm_acc : relation Te :=\n    | stacc_intro : forall f (ts : TypArgs f) i (hi : Acc f i),\n      supterm_acc (apps (Fun f) ts) (Vnth ts (Acc_arity hi)).\n\n    Lemma stacc_intro' f (ts : TypArgs f) i (hi : Acc f i) t u :\n      t = apps (Fun f) ts -> u = Vnth ts (Acc_arity hi) -> supterm_acc t u.\n\n    Proof. intros e1 e2. subst. apply stacc_intro. Qed.\n\n  End supterm_acc.\n\nEnd Def.\n\n(****************************************************************************)\n(** * Structure on base types for defining their interpretation as computability predicates. *)\n\nModule Type BI_Struct.\n\n  (** We assume given an ST structure. *)\n\n  Declare Module Export ST : ST_Struct.\n\n  (** We assume given a decidable total ordering structure on base\n  types. *)\n\n  Declare Module Export BOrd : OrderedType\n  with Definition t := So\n  with Definition eq := @Logic.eq So.\n\n  Infix \"<B\" := lt (at level 70).\n  Notation gtB := (transp lt) (only parsing).\n  Infix \">B\" := gtB (at level 70).\n\n  (** We assume that [ltB] is well-founded (in Coq sense). *)\n\n  Parameter ltB_wf : well_founded lt.\n\n  (** For each symbol [f : T_0 ~~> .. ~~> T_{n-1} -> A], we assume\n     given a set [Acc f] of accessible argument positions [i] between\n     [0] and [n-1] such that, for every base type [B] occurring in\n     [T_i], either [B] is smaller than [A], or [B] is equivalent to\n     [A] and occurs only positively in [T_i]. *)\n\n  Parameter Acc : F -> set nat.\n  Parameter Acc_arity : forall f i, Acc f i -> i < arity (typ f).\n  Parameter Acc_ok : forall f i (hi : Acc f i) a,\n    occurs a (Vnth (inputs (typ f)) (Acc_arity hi)) ->\n    a <B output_base (typ f)\n    \\/ (a = output_base (typ f)\n      /\\ pos a (Vnth (inputs (typ f)) (Acc_arity hi))).\n\n  Arguments Acc_ok [f i hi a] _.\n\n  (** Notations. *)\n\n  Notation aeq := (@aeq F X FOrd.eq_dec XOrd.eq_dec ens_X var_notin).\n  Notation vaeq := (Vforall2 aeq).\n  Notation supterm_acc := (@supterm_acc F X So typ Acc Acc_arity).\n\nEnd BI_Struct.\n\n(****************************************************************************)\n(** * Definition of the interpretation of base types\n\ngiven an ST structure for terms, a CP structure for the rewrite\nrelation, and a BI structure. *)\n\nModule Make (Export ST : ST_Struct)\n  (Export CP : CP_Struct with Module L := ST.L)\n  (Export BI : BI_Struct with Module ST := ST).\n\n  Module Import P := OrderedTypeFacts BOrd.\n  Module Export CS := LCompSimple.Make ST CP.\n\n  (*COQ: why is it needed?*)\n  Infix \"=>R\" := (clos_aeq (clos_mon Rh)).\n  Infix \"=>R*\" := (R_aeq*).\n\n(****************************************************************************)\n(** ** Properties of [supterm_acc]. *)\n\n  Lemma supterm_acc_supterm : supterm_acc << supterm!.\n\n  Proof. intros t u [f ts i hi]. apply supterm_nth. Qed.\n\n  Lemma supterm_acc_wf : WF supterm_acc.\n\n  Proof.\n    eapply WF_incl. apply supterm_acc_supterm. apply WF_tc. apply supterm_wf.\n  Qed.\n\n  Global Instance size_subpterm_acc : Proper (supterm_acc --> Peano.lt) size.\n\n  Proof. intros t u tu. inversion tu; subst. apply size_apps_r_nth. Qed.\n\n  Lemma supterm_acc_size : supterm_acc << transp (ltof size).\n\n  Proof. intros t u tu. apply size_subpterm_acc. hyp. Qed.\n\n  Lemma aeq_supterm_acc_commut : aeq @ supterm_acc << supterm_acc @ aeq.\n\n  Proof.\n    intros t u [t' [tt' t'u]]. inversion t'u; clear t'u; subst.\n    inv_aeq tt'; subst. exists (Vnth us (Acc_arity hi)). split.\n    apply stacc_intro. apply Vforall2_elim_nth. hyp.\n  Qed.\n\n  Lemma aeq_tc_supterm_acc_commut :\n    aeq @ (supterm_acc!) << (supterm_acc!) @ aeq.\n\n  Proof. apply commut_tc_inv. apply aeq_supterm_acc_commut. Qed.\n\n  Lemma supterm_acc_subs : forall s t u,\n    supterm_acc t u -> supterm_acc (subs s t) (subs s u).\n\n  Proof.\n    intros s t u tu. inversion tu; clear tu; subst.\n    rewrite subs_apps, <- Vnth_map. apply stacc_intro.\n  Qed.\n\n  Lemma tc_supterm_acc_subs : forall s t u,\n    supterm_acc! t u -> supterm_acc! (subs s t) (subs s u).\n\n  Proof.\n    intros s t u tu. revert t u tu; induction 1.\n    apply t_step. apply supterm_acc_subs. hyp.\n    trans (subs s y); fo.\n  Qed.\n\n  Section tc_supterm_acc_R_mon_wf.\n\n    Variables (R : relation Te) (R_mon : Monotone R).\n\n    Lemma supterm_acc_R_mon_commut : supterm_acc @ R << R @ supterm_acc.\n\n    Proof.\n      intros t v [u [tu uv]]. inversion tu; clear tu; subst.\n      exists (apps (Fun f) (Vreplace ts (Acc_arity hi) v)).\n      split. (*COQ:rewrite <- (Vreplace_nth_eq ts (Acc_arity hi)) at 1.*)\n      set (ts' := Vreplace ts (Acc_arity hi) v).\n      rewrite <- (Vreplace_nth_eq ts (Acc_arity hi)). unfold ts'. mon.\n      rewrite <- (Vnth_replace (Acc_arity hi) (Acc_arity hi) ts v) at 2.\n      apply stacc_intro.\n    Qed.\n\n    Lemma tc_supterm_acc_R_mon_commut : supterm_acc! @ R << R @ supterm_acc!.\n\n    Proof. apply commut_tc. apply supterm_acc_R_mon_commut. Qed.\n\n    Lemma tc_supterm_acc_R_mon_wf : WF R -> WF (supterm_acc! U R).\n\n    Proof.\n      intro R_wf. apply Union.WF_union_commut.\n      apply WF_tc. apply supterm_acc_wf. hyp.\n      apply tc_supterm_acc_R_mon_commut.\n    Qed.\n\n    Import RelUtil.\n\n    Section restrict.\n\n      Variables (P : set Te) (P_R : Proper (R ==> impl) P).\n\n      Lemma restrict_tc_supterm_acc_R_mon_wf :\n        WF (restrict P R) -> WF (restrict P (supterm_acc! U R)).\n\n      Proof.\n        intro R_wf. rewrite restrict_union. apply Union.WF_union_commut.\n        apply wf_restrict_sn. intros t ht. apply WF_tc. apply supterm_acc_wf.\n        hyp. intros t v [u [[ht tu] [hu uv]]].\n        assert (a : (supterm_acc! @ R) t v). exists u. fo.\n        destruct (tc_supterm_acc_R_mon_commut a) as [u' [tu' u'v]]. exists u'.\n        split; split; auto. eapply P_R. apply tu'. hyp.\n      Qed.\n\n    End restrict.\n\n    Lemma restrict_SN_tc_supterm_acc_R_mon_wf :\n      WF (restrict (SN R) (supterm_acc! U R)).\n\n    Proof.\n      apply restrict_tc_supterm_acc_R_mon_wf. class.\n      apply wf_restrict_sn. refl.\n    Qed.\n\n  End tc_supterm_acc_R_mon_wf.\n\n(****************************************************************************)\n(** ** Properties of [clos_aeq supterm_acc]. *)\n\n  Lemma clos_aeq_supterm_acc_wf : WF (clos_aeq supterm_acc).\n\n  Proof. apply clos_aeq_wf_size. apply supterm_acc_size. Qed.\n\n  Global Instance clos_aeq_tc_supterm_cc_trans : Transitive (clos_aeq (supterm_acc!)).\n\n  Proof.\n    rewrite <- trans_intro. rewrite clos_aeq_eq, !comp_assoc.\n    rewrite (commut_comp (tc_supterm_acc_R_mon_commut (R:=aeq) _)), !comp_assoc.\n    rewrite (commut_comp (tc_supterm_acc_R_mon_commut (R:=aeq) _)), !comp_assoc.\n    rewrite !(comp_incl_assoc (trans_comp_incl _)). refl.\n  Qed.\n\n  Lemma clos_aeq_tc_supterm_acc_eq :\n    clos_aeq (supterm_acc!) == (clos_aeq supterm_acc)!.\n\n  Proof.\n    split.\n    (* << *)\n    intros t u tu. inversion tu; clear tu; subst.\n    revert u' v' H1 t H u H0; induction 1; intros t tt' u uu'.\n    apply t_step. eapply clos_aeq_intro. apply tt'. apply uu'. hyp.\n    trans y; firstorder auto with crelations.\n    (* >> *)\n    apply tc_min. 2: class. apply clos_aeq_incl. apply incl_tc. refl.\n  Qed.\n\n  Lemma clos_aeq_tc_supterm_acc_wf : WF (clos_aeq (supterm_acc!)).\n\n  Proof.\n    apply clos_aeq_wf_size. apply tc_incl_trans. apply transp_trans. class.\n    apply supterm_acc_size.\n  Qed.\n\n  Lemma clos_aeq_tc_supterm_acc_subs : forall s t u,\n    clos_aeq (supterm_acc!) t u ->\n    clos_aeq (supterm_acc!) (subs s t) (subs s u).\n\n  Proof.\n    intros s t u tu.\n    destruct (clos_aeq_inv tu) as [t' [u' [tt' [uu' t'u']]]]; clear tu.\n    rewrite tt', uu'. apply clos_aeq_intro_refl.\n    apply tc_supterm_acc_subs. hyp.\n  Qed.\n\n  Section clos_aeq_tc_supterm_acc_R_mon_wf.\n\n    Variables (R : relation Te) (R_mon : Monotone R)\n      (R_aeq : Proper (aeq ==> aeq ==> impl) R).\n\n    Lemma clos_aeq_supterm_acc_R_mon_commut :\n      clos_aeq supterm_acc @ R << R @ clos_aeq supterm_acc.\n\n    Proof.\n      intros t v [u [tu uv]].\n      inversion tu; clear tu; subst; rename u' into t'; rename v' into u'.\n      assert (a : (supterm_acc @ R) t' v). exists u'. rewrite H0 in uv. fo.\n      destruct (supterm_acc_R_mon_commut R_mon a) as [w [t'w wv]].\n      exists w. split. rewrite H. hyp. apply clos_aeq_intro_refl. hyp.\n    Qed.\n\n    Lemma clos_aeq_tc_supterm_acc_R_mon_commut :\n      clos_aeq (supterm_acc!) @ R << R @ clos_aeq (supterm_acc!).\n\n    Proof.\n      rewrite clos_aeq_tc_supterm_acc_eq. apply commut_tc.\n      apply clos_aeq_supterm_acc_R_mon_commut.\n    Qed.\n\n    Lemma clos_aeq_tc_supterm_acc_R_mon_wf :\n      WF R -> WF (clos_aeq (supterm_acc!) U R).\n\n    Proof.\n      intro R_wf. apply Union.WF_union_commut.\n      apply clos_aeq_tc_supterm_acc_wf. hyp.\n      apply clos_aeq_tc_supterm_acc_R_mon_commut.\n    Qed.\n\n    Import SetUtil RelUtil.\n\n    Section restrict.\n\n      Variables (P : set Te) (P_R : Proper (R ==> impl) P).\n\n      Lemma restrict_clos_aeq_tc_supterm_acc_R_mon_wf :\n        WF (restrict P R) -> WF (restrict P (clos_aeq (supterm_acc!) U R)).\n\n      Proof.\n        intro R_wf. rewrite restrict_union. apply Union.WF_union_commut.\n        apply wf_restrict_sn. intros t ht. apply clos_aeq_tc_supterm_acc_wf.\n        hyp. intros t v [u [[ht tu] [hu uv]]].\n        assert (a : (clos_aeq (supterm_acc!) @ R) t v). exists u. fo.\n        destruct (clos_aeq_tc_supterm_acc_R_mon_commut a) as [u' [tu' u'v]].\n        exists u'. split; split; auto. eapply P_R. apply tu'. hyp.\n      Qed.\n\n    End restrict.\n\n    Lemma restrict_SN_clos_aeq_tc_supterm_acc_R_mon_wf :\n      WF (restrict (SN R) (clos_aeq (supterm_acc!) U R)).\n\n    Proof.\n      apply restrict_clos_aeq_tc_supterm_acc_R_mon_wf. class.\n      apply wf_restrict_sn. refl.\n    Qed.\n\n  End clos_aeq_tc_supterm_acc_R_mon_wf.\n\n(****************************************************************************)\n(** ** Interpretation of types\n\nThe interpretation [I] will be defined by well-founded induction\non [ltB] using Coq's corresponding combinator [Wf.Fix], which requires\na function [F] computing the interpretation of a base type [a] from\nthe interpretation [I_lt_a] for each base type strictly smaller than\n[a]. The interpretation of [a] itself is defined as the least fixpoint\nof some variant of the following monotone function [G]. *)\n\n  Import SetUtil AccUtil.\n\n  Section fixpoint.\n\n    Variable a : So.\n\n    Definition G I : set Te := fun t =>\n      SN R_aeq t /\\ forall f, output_base (typ f) = a ->\n        forall ts : Tes (arity (typ f)), R_aeq* t (apps (Fun f) ts) ->\n          forall i (hi : Acc f i),\n            int I (Vnth (inputs (typ f)) (Acc_arity hi))\n                  (Vnth ts (Acc_arity hi)).\n\n    Variable I_lt_a : forall b, b <B a -> set Te.\n\n    Definition update (X : set Te) b :=\n      match BOrd.compare b a with\n        | LT h => I_lt_a h\n        | EQ _ => X\n        | GT _ => SN R_aeq\n      end.\n\n    Definition G' X := G (update X).\n\n    Definition F := lfp subset set_glb G'.\n\n  End fixpoint.\n\n  Definition I : So -> set Te := Fix ltB_wf F.\n\n(** We now check that [G] is monotone. *)\n\n  Section G'_props.\n\n    Variables (a : So) (I_lt_a : forall b, b <B a -> set Te).\n\n    Global Instance G'_mon : Proper (subset ==> subset) (G' I_lt_a).\n\n    Proof.\n      intros X Y XY t [snt ht]. split. hyp. intros f hf ts h i hi.\n      apply int_pos with (I:=update I_lt_a X) (a:=a). apply BOrd.eq_dec.\n      (* [update X a [= update Y a] *)\n      unfold update. destruct (BOrd.compare a a). refl. hyp. refl.\n      intros b n. unfold update. destruct (BOrd.compare b a). refl. fo. refl.\n      (* [pos a Ti] *)\n      set (Ti := Vnth (inputs (typ f)) (Acc_arity hi)).\n      destruct (occurs_dec BOrd.eq_dec a Ti).\n      destruct (Acc_ok o) as [l|[_ l]].\n      rewrite hf in l. apply BOrd.lt_not_eq in l. unfold BOrd.eq in l. cong.\n      hyp.\n      apply not_occurs_pos. hyp.\n      (* [int (update X) ti Ti] *)\n      apply ht; hyp.\n    Qed.\n\n    Global Instance G'_equiv : Proper (equiv ==> equiv) (G' I_lt_a).\n\n    Proof.\n      intros X Y. rewrite 2!equiv_elim. intros [XY YX]. split.\n      rewrite XY. refl. rewrite YX. refl.\n    Qed.\n\n  End G'_props.\n\n(** We also check that [G] and [F] are compatible with [equiv]. *)\n\n  Section G_ext.\n\n    Variables (a : So) (I J : So -> set Te)\n      (e : forall b, ~b >B a -> I b [=] J b).\n\n    Lemma G_ext : G a I [=] G a J.\n\n    Proof.\n      intro t. apply iff_and. split. refl.\n      cut (forall f, output_base (typ f) = a ->\n        forall ts : Tes (arity (typ f)), t =>R* apps (Fun f) ts ->\n          forall i (hi : Acc f i),\n            int I (Vnth (inputs (typ f)) (Acc_arity hi))\n                  (Vnth ts (Acc_arity hi))\n        <-> int J (Vnth (inputs (typ f)) (Acc_arity hi))\n                  (Vnth ts (Acc_arity hi))).\n      intro h1. split.\n      intros h2 f hf ts r i hi. rewrite <- h1; auto.\n      intros h2 f hf ts r i hi. rewrite h1; auto.\n      intros f hf ts r i hi. apply int_equiv. intros b h. apply e.\n      destruct (Acc_ok h) as [j|[j1 j2]]. rewrite hf in j. intro k.\n      absurd (b <B b). apply lt_antirefl. trans a; hyp.\n      subst. apply lt_antirefl.\n    Qed.\n\n  End G_ext.\n\n  Section F_ext.\n\n    Variables (a : So) (I_lt_a J_lt_a : forall b, b <B a -> set Te)\n      (e : forall b (h : b <B a), I_lt_a h [=] J_lt_a h).\n\n    Lemma G'_ext : forall X Y, X [=] Y -> G' I_lt_a X [=] G' J_lt_a Y.\n\n    Proof.\n      intros X Y XY t. unfold G'. apply G_ext. intro b. unfold update.\n      destruct (BOrd.compare b a); fo.\n    Qed.\n\n    Lemma F_ext : F I_lt_a [=] F J_lt_a.\n\n    Proof.\n      unfold F. apply lfp_ext. fo. fo. fo. intro X. apply G'_ext. refl.\n    Qed.\n\n  End F_ext.\n\n(** Fixpoint equation satisfied by [I]. *)\n\n  Definition I' a b (_ : b <B a) := I b.\n\n  Arguments I' _ [_] _ _.\n\n  Lemma I_eq_F : forall a, I a [=] F (I' a).\n\n  Proof. intro a. unfold I. rewrite Fix_eq. refl. apply F_ext. Qed.\n\n  Lemma I_eq_G' : forall a, I a [=] G' (I' a) (I a).\n\n  Proof.\n    intro a. rewrite I_eq_F at 1. unfold F. rewrite set_lfp_eq. 2: apply G'_mon.\n    apply G'_ext. refl. rewrite I_eq_F. refl.\n  Qed.\n\n  Lemma I_eq : forall a, I a [=] G a I.\n\n  Proof.\n    intro a. rewrite I_eq_G'. unfold G'. apply G_ext. intros b h.\n    unfold update. destruct (BOrd.compare b a). refl. rewrite e. refl. fo.\n  Qed.\n\n(** We now check that base types are interpreted by computability\npredicates. *)\n\n  Section cp.\n\n    Variables (a : So) (I_lt_a : forall b, b <B a -> set Te)\n      (I_lt_a_cp_aeq : forall b (h : b<B a), cp_aeq (I_lt_a h))\n      (I_lt_a_cp_sn : forall b (h : b<B a), cp_sn (I_lt_a h))\n      (I_lt_a_cp_red : forall b (h : b<B a), cp_red (I_lt_a h))\n      (I_lt_a_cp_neutral : forall b (h : b<B a), cp_neutral (I_lt_a h))\n      (X : set Te) (X_cp_aeq : cp_aeq X) (X_cp_sn : cp_sn X)\n      (X_cp_red : cp_red X) (X_cp_neutral : cp_neutral X).\n\n    Lemma G'_cp_aeq : cp_aeq (G' I_lt_a X).\n\n    Proof.\n      intros t u tu [ht1 ht2]. split. rewrite <- tu. hyp.\n      intros f hf ts. rewrite <- tu. fo.\n    Qed.\n\n    Lemma G'_cp_sn : cp_sn (G' I_lt_a X).\n\n    Proof. fo. Qed.\n\n    Lemma G'_cp_red : cp_red (G' I_lt_a X).\n\n    Proof.\n      intros t u tu [ht1 ht2]. split. eapply SN_inv. apply tu. hyp.\n      intros f hf ts hu. assert (ht : t =>R* apps (Fun f) ts).\n      trans u. apply at_step. hyp. hyp. apply ht2; hyp.\n    Qed.\n\n    Lemma  G'_cp_neutral :\n      (forall f n (ts : Tes n), ~neutral (apps (Fun f) ts)) ->\n      cp_neutral (G' I_lt_a X).\n\n    Proof.\n      intros hn t ht1 ht2. split.\n      apply SN_intro. intros u tu. destruct (ht2 _ tu) as [h _]. hyp.\n      intros f hf ts r. destruct (clos_aeq_trans_inv _ r) as [h|[u [h1 h2]]].\n      rewrite h in ht1. fo.\n      eapply ht2. apply h1. hyp. hyp.\n    Qed.\n\n  End cp.\n\n  Lemma I_cp : (forall f n (ts : Tes n), ~neutral (apps (Fun f) ts)) ->\n    forall a, cp (I a).\n\n  Proof.\n    intros hn a. induction (ltB_wf a) as [a _ IH]. rewrite I_eq_G'.\n    constructor. apply G'_cp_aeq. apply G'_cp_sn. apply G'_cp_red.\n    apply G'_cp_neutral. hyp.\n  Qed.\n\n(** Computability of accessible arguments. *)\n\n  Lemma comp_acc : forall f (ts : Tes (arity (typ f))),\n    I (output_base (typ f)) (apps (Fun f) ts) -> forall i (hi : Acc f i),\n      int I (Vnth (inputs (typ f)) (Acc_arity hi)) (Vnth ts (Acc_arity hi)).\n\n  Proof.\n    intros f ts. set (a := output_base (typ f)).\n    (*COQ: rewrite I_eq. does not work here! *)\n    gen (I_eq a); unfold equiv, pointwise_relation; intro e; rewrite e; clear e.\n    intros [h1 h2] i hi. apply h2; refl.\n  Qed.\n\n(** Computability of function symbols. *)\n\n  Lemma comp_fun : (forall f n (ts : Tes n), ~neutral (apps (Fun f) ts)) ->\n    forall f (ts : Tes (arity (typ f))), vint I (inputs (typ f)) ts ->\n      (forall u, apps (Fun f) ts =>R u -> I (output_base (typ f)) u) ->\n      I (output_base (typ f)) (apps (Fun f) ts).\n\n  Proof.\n    intros hn f ts hts h. set (a := output_base (typ f)).\n    gen (I_cp hn a). intros [a1 a2 a3 a4].\n    (*COQ: rewrite I_eq. does not work here! *)\n    gen (I_eq a); unfold equiv, pointwise_relation; intro e; rewrite e; clear e.\n    split.\n    apply SN_intro. fo.\n    intros g hg us r i hi. destruct (clos_aeq_trans_inv _ r) as [j|[v [h1 h2]]].\n    inv_aeq j; subst. gen (eq_apps_fun_head i0). intro e. subst g.\n    apply eq_apps_nb_args_args in i0. subst us0. apply vint_elim_nth.\n    (*COQ:rewrite i2.*) eapply vint_vaeq. apply I_cp. hyp. sym. apply i2. hyp.\n    gen (h _ h1). fold a. (*COQ: rewrite I_eq.*)\n    gen (I_eq a); unfold equiv, pointwise_relation; intro e; rewrite e; clear e.\n    intros [i1 i2]. apply i2; hyp.\n  Qed.\n\nEnd Make.\n", "meta": {"author": "fblanqui", "repo": "color", "sha": "f2ef98f7d13c5d71dd2a614ed2e6721703a34532", "save_path": "github-repos/coq/fblanqui-color", "path": "github-repos/coq/fblanqui-color/color-f2ef98f7d13c5d71dd2a614ed2e6721703a34532/Term/Lambda/LCompInt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.26740163426501334}}
{"text": "Require Import Arith.\nRequire Import ZArith.\nRequire Import List.\nImport ListNotations.\nRequire Import Sorted.\nRequire Import Omega.\nRequire Import Psatz.\n\nRequire Import v1.NeutronTactics.\nRequire Import v1.Util.\nRequire Import v1.Multi.\nRequire Import v1.MForall.\nRequire Import v1.FloatAux.\n\nRequire Import epics.SpecTypes.\nRequire Import expr.Expr.\nRequire Import floatabs.Records.\nRequire Import floatabs.RecordData.\nRequire Import util.ListLemmas.\n\nRequire expr.Dbl.\nRequire floatabs.AbsExpr.\n\n\nSet Default Timeout 10.\n\nLocal Open Scope Z.\n\nModule Dbl := expr.Dbl.\nModule Abs := floatabs.AbsExpr.\n\n\n\nDefinition D := Dbl.dbl_eval_bits.\nDefinition A := Abs.abs_eval_bits.\n\nInductive ty_rel : Dbl.dbl_tydesc -> Abs.abs_tydesc -> Prop :=\n| TrNil : ty_rel Dbl.Nil Abs.Nil\n| TrDbl : ty_rel Dbl.Dbl Abs.Abs\n.\nHint Constructors ty_rel.\n\n\nDefinition lift (fd : tydesc D -> Type) (fa : tydesc A -> Type) :\n    (forall dty aty, fd dty -> fa aty -> Prop) ->\n    ({ ty : tydesc D & fd ty } -> { ty : tydesc A & fa ty } -> Prop).\nintro P.\nintros dsig asig.\ndestruct dsig as [d d'], asig as [a a'].\neapply P; eassumption.\nDefined.\n\n\nInductive refine_dbl : e_double -> abs_value -> Prop :=\n| RdNone : forall d, refine_dbl d None\n| RdSome : forall d z min max,\n        fwhole_eq d z ->\n        (min <= z <= max)%Z ->\n        refine_dbl d (Some (min, max)).\n\nInductive refine_value : forall dty aty, ty_denote D dty -> ty_denote A aty -> Prop :=\n| RvNil : refine_value Dbl.Nil Abs.Nil tt tt\n| RvDbl : forall d a,\n        refine_dbl d a ->\n        refine_value Dbl.Dbl Abs.Abs d a.\nDefinition refine_value' :\n    ({ ty : tydesc D & ty_denote D ty } -> { ty : tydesc A & ty_denote A ty } -> Prop) :=\n    lift _ _ refine_value.\n\nInductive refine_unop dty1 aty1 :\n    forall dtyR atyR\n        (df : unop_impl _ dty1 dtyR)\n        (af : unop_impl _ aty1 atyR),\n        Prop :=\n| RefineUnop : forall dtyR atyR df af,\n    ty_rel dty1 aty1 ->\n    ty_rel dtyR atyR ->\n    (forall dx1 ax1,\n        refine_value dty1 aty1 dx1 ax1 ->\n        refine_value dtyR atyR (df dx1) (af ax1)) ->\n    refine_unop dty1 aty1 dtyR atyR df af.\nDefinition refine_unop' dty1 aty1 :=\n    lift _ _ (refine_unop dty1 aty1).\n\nInductive refine_binop dty1 aty1 dty2 aty2 :\n    forall dtyR atyR\n        (df : binop_impl _ dty1 dty2 dtyR)\n        (af : binop_impl _ aty1 aty2 atyR),\n        Prop :=\n| RefineBinop : forall dtyR atyR df af,\n    ty_rel dty1 aty1 ->\n    ty_rel dty2 aty2 ->\n    ty_rel dtyR atyR ->\n    (forall dx1 ax1 dx2 ax2,\n        refine_value dty1 aty1 dx1 ax1 ->\n        refine_value dty2 aty2 dx2 ax2 ->\n        refine_value dtyR atyR (df dx1 dx2) (af ax1 ax2)) ->\n    refine_binop dty1 aty1 dty2 aty2 dtyR atyR df af.\nDefinition refine_binop' dty1 aty1 dty2 aty2 :=\n    lift _ _ (refine_binop dty1 aty1 dty2 aty2).\n\nInductive refine_ternop dty1 aty1 dty2 aty2 dty3 aty3 :\n    forall dtyR atyR\n        (df : ternop_impl _ dty1 dty2 dty3 dtyR)\n        (af : ternop_impl _ aty1 aty2 aty3 atyR),\n        Prop :=\n| RefineTernop : forall dtyR atyR df af,\n    ty_rel dty1 aty1 ->\n    ty_rel dty2 aty2 ->\n    ty_rel dty3 aty3 ->\n    ty_rel dtyR atyR ->\n    (forall dx1 ax1 dx2 ax2 dx3 ax3,\n        refine_value dty1 aty1 dx1 ax1 ->\n        refine_value dty2 aty2 dx2 ax2 ->\n        refine_value dty3 aty3 dx3 ax3 ->\n        refine_value dtyR atyR (df dx1 dx2 dx3) (af ax1 ax2 ax3)) ->\n    refine_ternop dty1 aty1 dty2 aty2 dty3 aty3 dtyR atyR df af.\nDefinition refine_ternop' dty1 aty1 dty2 aty2 dty3 aty3 :=\n    lift _ _ (refine_ternop dty1 aty1 dty2 aty2 dty3 aty3).\n\nInductive refine_varop dty1 aty1 :\n    forall dtyR atyR\n        (df : varop_impl _ dty1 dtyR)\n        (af : varop_impl _ aty1 atyR),\n        Prop :=\n| RefineVarop : forall dtyR atyR df af,\n    ty_rel dty1 aty1 ->\n    ty_rel dtyR atyR ->\n    (forall dx1 ax1,\n        Forall2 (refine_value dty1 aty1) dx1 ax1 ->\n        refine_value dtyR atyR (df dx1) (af ax1)) ->\n    refine_varop dty1 aty1 dtyR atyR df af.\nDefinition refine_varop' dty1 aty1 :=\n    lift _ _ (refine_varop dty1 aty1).\n\nInductive refine_state_fn :\n    forall dtyR atyR\n        (df : state_fn D 12 (ty_denote D dtyR))\n        (af : state_fn A 12 (ty_denote A atyR)),\n        Prop :=\n| RefineStateFn : forall dtyR atyR df af,\n    ty_rel dtyR atyR ->\n    (forall dsv dsx asv asx dsv' dsx' dr asv' asx' ar,\n        MForall2 (refine_value _ _) dsv asv ->\n        MForall2 (refine_value _ _) dsx asx ->\n        df dsv dsx = (dsv', dsx', dr) ->\n        af asv asx = (asv', asx', ar) ->\n        MForall2 (refine_value _ _) dsv' asv' /\\\n        MForall2 (refine_value _ _) dsx' asx' /\\\n        refine_value _ _ dr ar) ->\n    refine_state_fn dtyR atyR df af.\nDefinition refine_state_fn' :=\n    lift _ _ (refine_state_fn).\n\nInductive refine_state_fn_list :\n    forall dtyR atyR\n        (df : state_fn D 12 (list (ty_denote D dtyR)))\n        (af : state_fn A 12 (list (ty_denote A atyR))),\n        Prop :=\n| RefineStateFnList : forall dtyR atyR df af,\n    ty_rel dtyR atyR ->\n    (forall dsv dsx asv asx dsv' dsx' drs asv' asx' ars,\n        MForall2 (refine_value _ _) dsv asv ->\n        MForall2 (refine_value _ _) dsx asx ->\n        df dsv dsx = (dsv', dsx', drs) ->\n        af asv asx = (asv', asx', ars) ->\n        MForall2 (refine_value _ _) dsv' asv' /\\\n        MForall2 (refine_value _ _) dsx' asx' /\\\n        Forall2 (refine_value _ _) drs ars) ->\n    refine_state_fn_list dtyR atyR df af.\nDefinition refine_state_fn_list' :=\n    lift _ _ (refine_state_fn_list).\n\nInductive refine_state_fn_noxvar :\n    forall dtyR atyR\n        (df : state_fn_noxvar D 12 (ty_denote D dtyR))\n        (af : state_fn_noxvar A 12 (ty_denote A atyR)),\n        Prop :=\n| RefineStateFnNoXVar : forall dtyR atyR df af,\n    ty_rel dtyR atyR ->\n    (forall dsv asv dsv' dr asv' ar,\n        MForall2 (refine_value _ _) dsv asv ->\n        df dsv = (dsv', dr) ->\n        af asv = (asv', ar) ->\n        MForall2 (refine_value _ _) dsv' asv' /\\\n        refine_value _ _ dr ar) ->\n    refine_state_fn_noxvar dtyR atyR df af.\nDefinition refine_state_fn_noxvar' :=\n    lift _ _ (refine_state_fn_noxvar).\n\n\nLemma double_abs_refine : forall d,\n    refine_dbl d (Abs.double_abs d).\nintros. unfold Abs.double_abs. break_match.\n- econstructor.\n  + eapply B2Z_safe_correct. eassumption.\n  + omega.\n- constructor.\nQed.\n\nLemma convert_lit_refine : forall x,\n    refine_value' (convert_lit D x) (convert_lit A x).\nintros. simpl.  constructor. eauto using double_abs_refine.\nQed.\n\nLocal Hint Resolve (tydesc_eq_dec D) : eq_dec.\nLocal Hint Resolve (tydesc_eq_dec A) : eq_dec.\n\n\n\nLemma abs_bool_refine : forall d,\n    (d = d_zero \\/ d = d_one) ->\n    refine_dbl d Abs.abs_bool.\nintros0 Hor. destruct Hor.\n- econstructor.\n  + subst. eapply fwhole_eq_Z2B.\n    eapply Z.pow_pos_nonneg; omega.\n  + omega.\n\n- econstructor.\n  + subst. eapply fwhole_eq_Z2B.\n    rewrite Z.abs_eq by omega.\n    replace 1 with (1 ^ (53 - 1)) at 1 by (eapply Z.pow_1_l; omega).\n    eapply Z.pow_lt_mono_l; omega.\n  + omega.\nQed.\n\nLemma unop_denote_refine : forall op dty1 aty1 dden,\n    ty_rel dty1 aty1 ->\n    unop_denote D op dty1 = Some dden ->\n    exists aden,\n        unop_denote A op aty1 = Some aden /\\\n        refine_unop' _ _ dden aden.\ndestruct op, dty1; inversion 1; intros0 Dop;\nsimpl in *; try discriminate.\nall: eexists; split; [ reflexivity | ].\nall: inject_some; unfold refine_unop', lift.\nall: constructor; eauto.\nall: inversion 1; constructor.\nall: fix_existT; subst.\n\n- on >refine_dbl, invc; [ solve [constructor] | ].\n  simpl. unfold Abs.check_overflow. do 2 (break_if; try solve [constructor]).\n  econstructor.\n  + eapply fwhole_eq_Bopp; eauto.\n  + omega.\n\n- eapply abs_bool_refine.  break_if; eauto.\n\nQed.\n\n\nLemma Z_mult_range_max_l : forall x y0 y1 y,\n    y0 <= y <= y1 ->\n    x * y <= Z.max (x * y0) (x * y1).\nintros. destruct (Z_le_gt_dec 0 x).\n- eapply Z.le_trans with (m := x * y1).\n  + eapply Z.mul_le_mono_nonneg_l; omega.\n  + eapply Z.le_max_r.\n- eapply Z.le_trans with (m := x * y0).\n  + eapply Z.mul_le_mono_nonpos_l; omega.\n  + eapply Z.le_max_l.\nQed.\n\nLemma Z_mult_range_max_r : forall x0 x1 x y,\n    x0 <= x <= x1 ->\n    x * y <= Z.max (x0 * y) (x1 * y).\nintros. destruct (Z_le_gt_dec 0 y).\n- eapply Z.le_trans with (m := x1 * y).\n  + eapply Z.mul_le_mono_nonneg_r; omega.\n  + eapply Z.le_max_r.\n- eapply Z.le_trans with (m := x0 * y).\n  + eapply Z.mul_le_mono_nonpos_r; omega.\n  + eapply Z.le_max_l.\nQed.\n\nLemma Z_mult_range_max : forall x0 x1 y0 y1 x y,\n    x0 <= x <= x1 ->\n    y0 <= y <= y1 ->\n    let z1 := Z.max (Z.max (x0 * y0) (x0 * y1)) (Z.max (x1 * y0) (x1 * y1)) in\n    x * y <= z1.\nintros.\neapply Z.le_trans with (m := Z.max (x0 * y) (x1 * y)).\n- eapply Z_mult_range_max_r. eauto.\n- eapply Z.max_le_compat; eapply Z_mult_range_max_l; eauto.\nQed.\n\n\nLemma Z_mult_range_min_l : forall x y0 y1 y,\n    y0 <= y <= y1 ->\n    Z.min (x * y0) (x * y1) <= x * y.\nintros. destruct (Z_le_gt_dec 0 x).\n- eapply Z.le_trans with (m := x * y0).\n  + eapply Z.le_min_l.\n  + eapply Z.mul_le_mono_nonneg_l; omega.\n- eapply Z.le_trans with (m := x * y1).\n  + eapply Z.le_min_r.\n  + eapply Z.mul_le_mono_nonpos_l; omega.\nQed.\n\nLemma Z_mult_range_min_r : forall x0 x1 x y,\n    x0 <= x <= x1 ->\n    Z.min (x0 * y) (x1 * y) <= x * y.\nintros. destruct (Z_le_gt_dec 0 y).\n- eapply Z.le_trans with (m := x0 * y).\n  + eapply Z.le_min_l.\n  + eapply Z.mul_le_mono_nonneg_r; omega.\n- eapply Z.le_trans with (m := x1 * y).\n  + eapply Z.le_min_r.\n  + eapply Z.mul_le_mono_nonpos_r; omega.\nQed.\n\nLemma Z_mult_range_min : forall x0 x1 y0 y1 x y,\n    x0 <= x <= x1 ->\n    y0 <= y <= y1 ->\n    let z0 := Z.min (Z.min (x0 * y0) (x0 * y1)) (Z.min (x1 * y0) (x1 * y1)) in\n    z0 <= x * y.\nintros.\neapply Z.le_trans with (m := Z.min (x0 * y) (x1 * y)).\n- eapply Z.min_le_compat; eapply Z_mult_range_min_l; eauto.\n- eapply Z_mult_range_min_r. eauto.\nQed.\n\n\nLemma Z_mult_range : forall x0 x1 y0 y1 x y,\n    x0 <= x <= x1 ->\n    y0 <= y <= y1 ->\n    let z0 := Z.min (Z.min (x0 * y0) (x0 * y1)) (Z.min (x1 * y0) (x1 * y1)) in\n    let z1 := Z.max (Z.max (x0 * y0) (x0 * y1)) (Z.max (x1 * y0) (x1 * y1)) in\n    z0 <= x * y <= z1.\nintros. split; eauto using Z_mult_range_min, Z_mult_range_max.\nQed.\n\n\nLemma binop_denote_refine : forall op dty1 aty1 dty2 aty2 dden,\n    ty_rel dty1 aty1 ->\n    ty_rel dty2 aty2 ->\n    binop_denote D op dty1 dty2 = Some dden ->\n    exists aden,\n        binop_denote A op aty1 aty2 = Some aden /\\\n        refine_binop' _ _ _ _ dden aden.\ndestruct op, dty1, dty2; do 2 inversion 1; intros0 Dop;\nsimpl in *; try discriminate.\nall: eexists; split; [ reflexivity | ].\nall: inject_some; unfold refine_unop', lift.\nall: constructor; eauto.\nall: do 2 inversion 1; constructor.\nall: fix_existT; subst.\n\n- do 2 (on >refine_dbl, invc; [ solve [constructor] | ]).\n  simpl. unfold Abs.check_overflow. do 2 (break_if; try solve [constructor]).\n  econstructor.\n  + eapply fwhole_eq_Bplus; eauto.\n    rewrite Z_abs_range. change (53 - 1) with 52. omega.\n  + omega.\n\n- do 2 (on >refine_dbl, invc; [ solve [constructor] | ]).\n  simpl. unfold Abs.check_overflow. do 2 (break_if; try solve [constructor]).\n  econstructor.\n  + eapply fwhole_eq_Bminus; eauto.\n    rewrite Z_abs_range. change (53 - 1) with 52. omega.\n  + omega.\n\n- do 2 (on >refine_dbl, invc; [ solve [constructor] | ]).\n  simpl. unfold Abs.check_overflow. do 2 (break_if; try solve [constructor]).\n  econstructor.\n  + eapply fwhole_eq_Bmult; eauto.\n    rewrite Z_abs_range. change (53 - 1) with 52.\n    forward eapply Z_mult_range with (x := z) (y := z0); eauto.\n    cbv zeta in *. omega.\n  + eapply Z_mult_range; eauto.\n\n- constructor.\n\n- eapply abs_bool_refine.  unfold Dbl.b64_ge. do 2 (break_match; eauto).\n- eapply abs_bool_refine.  unfold Dbl.b64_gt. do 2 (break_match; eauto).\n- eapply abs_bool_refine.  unfold Dbl.b64_le. do 2 (break_match; eauto).\n- eapply abs_bool_refine.  unfold Dbl.b64_lt. do 2 (break_match; eauto).\n- eapply abs_bool_refine.  unfold Dbl.b64_ne. do 2 (break_match; eauto).\n- eapply abs_bool_refine.  unfold Dbl.b64_eq. do 2 (break_match; eauto).\n\n- eapply abs_bool_refine.  unfold Dbl.b64_and. do 2 (break_if; eauto).\n- eapply abs_bool_refine.  unfold Dbl.b64_or. do 2 (break_if; eauto).\n\nQed.\n\n\nLemma ternop_denote_refine : forall op dty1 aty1 dty2 aty2 dty3 aty3 dden,\n    ty_rel dty1 aty1 ->\n    ty_rel dty2 aty2 ->\n    ty_rel dty3 aty3 ->\n    ternop_denote D op dty1 dty2 dty3 = Some dden ->\n    exists aden,\n        ternop_denote A op aty1 aty2 aty3 = Some aden /\\\n        refine_ternop' _ _ _ _ _ _ dden aden.\ndestruct op, dty1, dty2, dty3; do 3 inversion 1; intros0 Dop;\nsimpl in *; try discriminate.\nall: eexists; split; [ reflexivity | ].\nall: inject_some; unfold refine_unop', lift.\nall: constructor; eauto.\nall: do 3 inversion 1; constructor.\nall: fix_existT; subst.\n\n- on (refine_dbl dx2 _), invc; [ solve [constructor] | ].\n  on (refine_dbl dx3 _), invc; [ solve [constructor] | ].\n  simpl. unfold Abs.check_overflow. do 3 (break_if; try solve [constructor]).\n  + econstructor; eauto. lia.\n  + econstructor; eauto. lia.\n\nQed.\n\n\n\nLemma min_fwhole_eq : forall dx dy zx zy,\n    fwhole_eq dx zx ->\n    fwhole_eq dy zy ->\n    fwhole_eq (Dbl.b64_min dx dy) (Z.min zx zy).\nintros0 Hx Hy.\nunfold Dbl.b64_min, Z.min. break_match; [ break_match | ].\nall: erewrite fwhole_eq_Bcompare in * by eauto.\n4: discriminate.\nall: inject_some; find_rewrite.\nall: eauto.\n\n(* Eq case needs a bit more. *)\nrewrite Z.compare_eq_iff in *. subst. auto.\nQed.\n\nLemma max_fwhole_eq : forall dx dy zx zy,\n    fwhole_eq dx zx ->\n    fwhole_eq dy zy ->\n    fwhole_eq (Dbl.b64_max dx dy) (Z.max zx zy).\nintros0 Hx Hy.\nunfold Dbl.b64_max, Z.max. break_match; [ break_match | ].\nall: erewrite fwhole_eq_Bcompare in * by eauto.\n4: discriminate.\nall: inject_some; find_rewrite.\nall: eauto.\nQed.\n\nLemma min_refine : forall dx dy ax ay,\n    refine_dbl dx ax ->\n    refine_dbl dy ay ->\n    refine_dbl (Dbl.b64_min dx dy) (Abs.abs_min ax ay).\nintros0 Hx Hy.\ninvc Hx; invc Hy; simpl; try solve [constructor].\nunfold Abs.check_overflow. do 2 (break_if; try solve [constructor]).\neapply RdSome with (z := Z.min z z0).\n- eapply min_fwhole_eq; eauto.\n- lia.\nQed.\n\nLemma max_refine : forall dx dy ax ay,\n    refine_dbl dx ax ->\n    refine_dbl dy ay ->\n    refine_dbl (Dbl.b64_max dx dy) (Abs.abs_max ax ay).\nintros0 Hx Hy.\ninvc Hx; invc Hy; simpl; try solve [constructor].\nunfold Abs.check_overflow. do 2 (break_if; try solve [constructor]).\neapply RdSome with (z := Z.max z z0).\n- eapply max_fwhole_eq; eauto.\n- lia.\nQed.\n\nLemma minimum_refine : forall dxs axs,\n    Forall2 refine_dbl dxs axs ->\n    refine_dbl (Dbl.b64_minimum dxs) (Abs.abs_minimum axs).\ninduction dxs; intros0 Hfa; invc Hfa; simpl.\n- eapply RdSome with (z := 0).\n  + unfold d_zero. eapply fwhole_eq_Z2B. eapply Z.pow_pos_nonneg; lia.\n  + lia.\n- eapply min_refine; eauto.\nQed.\n\nLemma maximum_refine : forall dxs axs,\n    Forall2 refine_dbl dxs axs ->\n    refine_dbl (Dbl.b64_maximum dxs) (Abs.abs_maximum axs).\ninduction dxs; intros0 Hfa; invc Hfa; simpl.\n2: on >Forall2, invc.\n- eapply RdSome with (z := 0).\n  + unfold d_zero. eapply fwhole_eq_Z2B. eapply Z.pow_pos_nonneg; lia.\n  + lia.\n- auto.\n- eapply max_refine; eauto.\nQed.\n\n\nLemma refine_value_dbl : forall dx ax,\n    refine_value Dbl.Dbl Abs.Abs dx ax <->\n    refine_dbl dx ax.\nintros. split; intro Hr.\n- inversion Hr. fix_existT. subst. auto.\n- constructor. auto.\nQed.\n\nLemma refine_value_dbl_list : forall dx ax,\n    Forall2 (refine_value Dbl.Dbl Abs.Abs) dx ax <->\n    Forall2 refine_dbl dx ax.\ninduction dx; intros; split; intro Hr; invc Hr; eauto.\n- rewrite refine_value_dbl in *. rewrite IHdx in *. eauto.\n- rewrite <- refine_value_dbl in *. rewrite <- IHdx in *. eauto.\nQed.\n\nLemma varop_denote_refine : forall op dty1 aty1 dden,\n    ty_rel dty1 aty1 ->\n    varop_denote D op dty1 = Some dden ->\n    exists aden,\n        varop_denote A op aty1 = Some aden /\\\n        refine_varop' _ _ dden aden.\n\ndestruct op, dty1; inversion 1; intros0 Dop;\nsimpl in *; try discriminate.\nall: eexists; split; [ reflexivity | ].\nall: inject_some; unfold refine_varop', lift.\nall: constructor; eauto.\nall: constructor.\n\n- rewrite refine_value_dbl_list in *.\n  eapply minimum_refine; eauto.\n\n- rewrite refine_value_dbl_list in *.\n  eapply maximum_refine; eauto.\nQed.\n\n\nLtac specialize_refinement :=\n    repeat match goal with\n    (* First, try to destruct some applications.  This will fail if the arguments\n       used in the LHS have not been filled in yet, and we will fall through to the\n       spec_evar case below. *)\n    | [ H : forall x, _ |- _ ] =>\n            match type of H with\n            | context [ ?x = (_, _, _) ] =>\n                    match x with\n                    | (_, _, _) => fail 1\n                    | _ => destruct x as [[? ?] ?] eqn:?\n                    end\n            end\n    (* Main case: try to fill in arguments using evar or eassumption *)\n    | [ H : forall x : ?T, _ |- _ ] =>\n            match type of T with\n            | Set => spec_evar H\n            | Prop => \n                    match goal with\n                    | [ H' : _ |- _ ] => specialize (H H'); clear H'\n                    end\n            end\n    (* Also handle @eq premises with reflexivity *)\n    | [ H : _ = _ -> _ |- _ ] => spec H by reflexivity\n    (* Final cleanup: break `exists` and `and`. *)\n    | [ H : exists _, _ |- _ ] => destruct H\n    | [ H : _ /\\ _ |- _ ] => destruct H\n    end.\n\nLemma var_ty_rel : ty_rel (var_ty D) (var_ty A).\nconstructor.\nQed.\n\nLemma xvar_ty_rel : ty_rel (xvar_ty D) (xvar_ty A).\nconstructor.\nQed.\n\nLemma nil_ty_rel : ty_rel (nil_ty D) (nil_ty A).\nconstructor.\nQed.\n\nLemma ty_rel_inj : forall dty aty1 aty2,\n    ty_rel dty aty1 ->\n    ty_rel dty aty2 ->\n    aty1 = aty2.\ndo 2 inversion 1; eauto.\nQed.\n\nLemma ty_rel_nil_sur : forall dty1 dty2,\n    ty_rel dty1 (nil_ty A) ->\n    ty_rel dty2 (nil_ty A) ->\n    dty1 = dty2.\ndo 2 inversion 1; eauto.\nQed.\n\nLemma nil_rel_fwd : forall aty,\n    ty_rel (nil_ty D) aty ->\n    aty = nil_ty A.\nintros. eapply ty_rel_inj; eauto using nil_ty_rel.\nQed.\n\nLemma nil_rel_rev : forall dty,\n    ty_rel dty (nil_ty A) ->\n    dty = nil_ty D.\nintros. eapply ty_rel_nil_sur; eauto using nil_ty_rel.\nQed.\n\n\nLemma unpack_opt_helper1\n    DI DP DR dopt (didx : DI) dval df drhs\n    AI AP AR aopt (aidx : AI) aval af\n        (P : AR -> Prop):\n    unpack_opt (R := DR) dopt df = Some drhs ->\n    dopt = Some (existT DP didx dval) ->\n    aopt = Some (existT AP aidx aval) ->\n    (df didx dval = Some drhs ->\n        exists arhs, af aidx aval = Some arhs /\\ P arhs) ->\n    exists arhs, unpack_opt (R := AR) aopt af = Some arhs /\\ P arhs.\nintros0 Hunpack Hdden Haden Hinner.\nsubst dopt aopt. simpl in *.\neauto.\nQed.\n\nLemma unpack_opt_some_inv : forall I P R (opt : option { x : I & P x }) f rhs\n        (Q : Prop),\n    (forall idx val,\n        opt = Some (existT P idx val) ->\n        f idx val = Some rhs ->\n        Q) ->\n    unpack_opt (R := R) opt f = Some rhs -> Q.\nintros.\ndestruct opt as [ s | ]; try discriminate.\ndestruct s. eauto.\nQed.\n\nLemma unpack_opt_some_inv' : forall I P R (opt : option { x : I & P x }) f rhs\n        (Q : Prop),\n    (forall idx val,\n        opt = Some (existT P idx val) ->\n        Q) ->\n    unpack_opt (R := R) opt f = Some rhs -> Q.\ninversion 2 using unpack_opt_some_inv. eauto.\nQed.\n\nLemma unpack_opt_some_ex\n    I P R opt (idx : I) val f (Q : R -> Prop):\n    opt = Some (existT P idx val) ->\n    (exists rhs, f idx val = Some rhs /\\ Q rhs) ->\n    (exists rhs, unpack_opt (R := R) opt f = Some rhs /\\ Q rhs).\nintros0 Hopt Hinner.\nsubst opt. simpl in *. eauto.\nQed.\n\nLtac handle_unpack_opt :=\n    let dden' := fresh \"dden'\" in\n    let aden' := fresh \"aden'\" in\n    let Hdden := fresh \"Hdden\" in\n    let Haden := fresh \"Haden\" in\n    let dty := fresh \"dty\" in\n    let aty := fresh \"aty\" in\n    let Hex := fresh \"Hex\" in\n    let Hrefine := fresh \"Hrefine\" in\n\n    match goal with\n    | [ H : unpack_opt ?dden ?df = Some _ |-\n        exists aden', unpack_opt ?aden ?af = Some _ /\\ _ ] =>\n\n            eapply unpack_opt_some_inv with (2 := H); clear H;\n            intros dty dden' Hdden H;\n\n            simple refine (let Hex : exists aden', aden = Some aden' /\\ _ aden' := _ in _);\n            [ shelve\n            | eauto (* or defer to caller *)\n            | clearbody Hex;\n              destruct Hex as (aden' & Haden & Hrefine);\n              destruct aden' as [aty aden'];\n              eapply unpack_opt_some_ex; simpl in *; eauto\n            ]\n    end.\n\n\nLemma if_tydesc_eq_dec_inv : forall\n    (T : Set) (A : eval_bits T)\n    (P : tydesc A -> tydesc A -> Type)\n    (ty xty : tydesc A)\n    (x : forall ty xty, P ty xty)\n    (y : forall ty xty, P ty xty)\n    (z : forall ty xty, P ty xty)\n    (Q : tydesc A -> Prop),\n    (x xty xty = z xty xty -> Q xty) ->\n    (ty <> xty ->\n        y ty xty = z ty xty ->\n        Q ty) ->\n    ((if tydesc_eq_dec A ty xty then x ty xty else y ty xty) = z ty xty) -> Q ty.\nintros.\ndestruct (tydesc_eq_dec _ _ _).\n- subst. eauto.\n- eauto.\nQed.\n\nLemma if_tydesc_eq_dec_eq_ex : forall\n    (T : Set) (A : eval_bits T)\n    (ty xty : tydesc A)\n    (R : Type) (f g : tydesc A -> tydesc A -> option R)\n    (Q : R -> Prop),\n    ty = xty ->\n    (exists rhs, f xty xty = Some rhs /\\ Q rhs) ->\n    (exists rhs, (if tydesc_eq_dec A ty xty then f ty xty else g ty xty) = Some rhs /\\ Q rhs).\nintros.\ndestruct (tydesc_eq_dec _ _ _); [ | exfalso; congruence ].\nsubst. auto.\nQed.\n\nLemma if_tydesc_eq_dec_ne_ex : forall\n    (T : Set) (A : eval_bits T)\n    (ty xty : tydesc A)\n    (R : Type) (f g : tydesc A -> tydesc A -> option R)\n    (Q : R -> Prop),\n    ty <> xty ->\n    (exists rhs, g ty xty = Some rhs /\\ Q rhs) ->\n    (exists rhs, (if tydesc_eq_dec A ty xty then f ty xty else g ty xty) = Some rhs /\\ Q rhs).\nintros.\ndestruct (tydesc_eq_dec _ _ _); [ exfalso; congruence | ].\nauto.\nQed.\n\n\nLemma unpack_ty_helper1\n    (DT : Set) (D : eval_bits DT) (DP : forall ty : tydesc D, Type) DR\n        dden dty dden' (df : DP dty -> option DR) drhs\n    (AT : Set) (A : eval_bits AT) (AP : forall ty : tydesc A, Type) AR\n        aden aty aden' (af : AP aty -> option AR)\n        (P : AR -> Prop) :\n    unpack_ty (R := DR) D dty dden df = Some drhs ->\n    dden = Some (existT DP dty dden') ->\n    aden = Some (existT AP aty aden') ->\n    (df dden' = Some drhs ->\n        exists arhs, af aden' = Some arhs /\\ P arhs) ->\n    exists arhs, unpack_ty (R := AR) A aty aden af = Some arhs /\\ P arhs.\nintros0 Hunpack Hdden Haden Hinner.\nsubst dden aden. simpl in *.\ndestruct (tydesc_eq_dec _ dty dty); [ | exfalso; congruence ].\ndestruct (tydesc_eq_dec _ aty aty); [ | exfalso; congruence ].\nfix_eq_rect; eauto using tydesc_eq_dec.\nQed.\n\nLemma unpack_ty_some_ex\n    (T : Set) (A : eval_bits T) (P : forall ty : tydesc A, Type) R\n        den ty den' (f : P ty -> option R)\n        (Q : R -> Prop) :\n    den = Some (existT P ty den') ->\n    (exists rhs, f den' = Some rhs /\\ Q rhs) ->\n    (exists rhs, unpack_ty (R := R) A ty den f = Some rhs /\\ Q rhs).\nintros0 Hden Hinner.\nsubst den. simpl in *.\ndestruct (tydesc_eq_dec _ ty ty); [ | exfalso; congruence ].\nfix_eq_rect; eauto using tydesc_eq_dec.\nQed.\n\nLemma unpack_ty_some_inv : forall\n    (T : Set) (D : eval_bits T) (P : forall ty : tydesc D, Type) R\n        xty den f rhs\n        (Q : Prop),\n    (forall val,\n        den = Some (existT P xty val) ->\n        f val = Some rhs ->\n        Q) ->\n    unpack_ty (R := R) D xty den f = Some rhs -> Q.\nintros0 HQ Hunpack.\ndestruct den as [ s | ]; try discriminate.\ndestruct s. simpl in Hunpack.\ndestruct (tydesc_eq_dec _ _ _); try discriminate.\nsubst xty. fix_eq_rect; eauto using tydesc_eq_dec.\nQed.\n\n\n\nLemma denote'_refine : forall e dden,\n    denote' D e = Some dden ->\n    exists aden,\n        denote' A e = Some aden /\\\n        refine_state_fn' dden aden.\ninduction e using expr_rect_mut with\n    (Pl := fun es => forall ddens,\n        denote'_list D es = Some ddens ->\n        exists adens,\n            denote'_list A es = Some adens /\\\n            refine_state_fn_list' ddens adens);\n[ .. | eauto | eauto ];\nintros0 Hden.\n\nLocal Opaque multi.\nLocal Opaque multi_get.\nLocal Opaque multi_set.\nLocal Opaque A.\nLocal Opaque D.\n\nall: simpl in *; unfold pack_denot in *; inject_some.\nall: try (eexists; split; [reflexivity|]; unfold refine_state_fn', lift).\n\n- constructor.  { constructor. }\n  intros. inject_pair.\n  split; [|split]; auto.\n  + eapply MForall2_get. assumption.\n\n- constructor.  { constructor. }\n  intros. inject_pair.\n  split; [|split]; auto.\n  + eapply MForall2_get. assumption.\n\n- constructor.  { constructor. }\n  intros. inject_pair.\n  split; [|split]; auto.\n  + eapply convert_lit_refine.\n\n- (* Unary *)\n  handle_unpack_opt.\n  handle_unpack_opt.\n    { on >refine_state_fn, invc. eapply unop_denote_refine; eauto. }\n    simpl in *.\n\n  eexists. split; [reflexivity|]. inject_some. simpl.\n\n  constructor.  { on >refine_unop, invc. auto. }\n  intros.  clear IHe.\n\n  on >refine_state_fn, invc.  specialize_refinement.\n    repeat find_rewrite. inject_pair.\n  on >refine_unop, invc.  specialize_refinement.\n\n  eauto.\n\n- (* Binary *)\n  handle_unpack_opt.\n  handle_unpack_opt.\n  handle_unpack_opt.\n    { inv Hrefine. inv Hrefine0. eapply binop_denote_refine; eauto. }\n    simpl in *.\n\n  eexists. split; [reflexivity|]. inject_some. simpl.\n\n  constructor.  { on >refine_binop, invc. auto. }\n  intros.  clear IHe1 IHe2.\n\n  on >(refine_state_fn dty), invc.  specialize_refinement.\n    repeat find_rewrite. inject_pair.\n  on >(refine_state_fn dty0), invc.  specialize_refinement.\n    repeat find_rewrite. inject_pair.\n  on >refine_binop, invc.  specialize_refinement.\n\n  eauto.\n\n- (* Varary *)\n  fold (denote'_list D xs) in *.\n  fold (denote'_list A xs) in *.\n  handle_unpack_opt.\n  handle_unpack_opt.\n    { inv Hrefine. eapply varop_denote_refine; eauto. }\n    simpl in *.\n\n  eexists. split; [reflexivity|]. inject_some. simpl.\n\n  constructor.  { on >refine_varop, invc. auto. }\n  intros.  clear IHe.\n\n  on >refine_state_fn_list, invc.  specialize_refinement.\n    repeat find_rewrite. inject_pair.\n  on >refine_varop, invc.  specialize_refinement.\n\n  eauto.\n\n- (* Assign *)\n\n  (* TODO - put unpack_ty stuff into the handle_unpack_opt tactic *)\n  on _, invc_using unpack_ty_some_inv.\n    destruct (IHe _ **) as ([? ?] & HH & ?). simpl in *.\n    on >refine_state_fn, invc.\n    assert (x = var_ty A) by eauto using ty_rel_inj, var_ty_rel. subst x.\n    eapply unpack_ty_some_ex; eauto.  clear HH.\n\n  eexists. split; [reflexivity|]. inject_some. simpl.\n\n  constructor.  { eauto using nil_ty_rel. }\n  intros.  clear IHe.\n\n  specialize_refinement.\n    repeat find_rewrite. inject_pair.\n\n  split; [|split]; eauto using set_MForall2.\n  + econstructor.\n\n- (* XAssign *)\n\n  on _, invc_using unpack_ty_some_inv.\n    destruct (IHe _ **) as ([? ?] & HH & ?). simpl in *.\n    on >refine_state_fn, invc.\n    assert (x = xvar_ty A) by eauto using ty_rel_inj, xvar_ty_rel. subst x.\n    eapply unpack_ty_some_ex; eauto.  clear HH.\n\n  eexists. split; [reflexivity|]. inject_some. simpl.\n\n  constructor.  { eauto using nil_ty_rel. }\n  intros.  clear IHe.\n\n  specialize_refinement.\n    repeat find_rewrite. inject_pair.\n\n  split; [|split]; eauto using set_MForall2.\n  + econstructor.\n\n- (* Cond *)\n  handle_unpack_opt.\n  handle_unpack_opt.\n  handle_unpack_opt.\n  handle_unpack_opt.\n    { do 3 on >refine_state_fn, invc. eapply ternop_denote_refine; eauto. }\n    simpl in *.\n\n  eexists. split; [reflexivity|]. inject_some. simpl.\n\n  constructor.  { on >refine_ternop, invc. auto. }\n  intros.  clear IHe1 IHe2 IHe3.\n\n  on >(refine_state_fn dty), invc.  specialize_refinement.\n    repeat find_rewrite. inject_pair.\n  on >(refine_state_fn dty0), invc.  specialize_refinement.\n    repeat find_rewrite. inject_pair.\n  on >(refine_state_fn dty1), invc.  specialize_refinement.\n    repeat find_rewrite. inject_pair.\n  on >refine_ternop, invc.  specialize_refinement.\n\n  eauto.\n\n- (* Seq *)\n  handle_unpack_opt.\n  handle_unpack_opt.\n  destruct (tydesc_eq_dec D _ _); [ | destruct (tydesc_eq_dec D _ _); [ | discriminate Hden ] ].\n\n  + assert (aty = nil_ty A). { eapply nil_rel_fwd. invc Hrefine. auto. }\n    subst aty. destruct (tydesc_eq_dec A _ _); [ | exfalso; congruence ].\n    eexists. split; [ reflexivity | ]. inject_some. simpl.\n    constructor. { invc Hrefine0. auto. } intros.\n\n    on >(refine_state_fn (nil_ty D)), invc.  specialize_refinement.\n      repeat find_rewrite. inject_pair.\n    on >(refine_state_fn dty0), invc.  specialize_refinement.\n      repeat find_rewrite. inject_pair.\n    auto.\n\n  + assert (aty <> nil_ty A).\n      { on (dty <> _), contradict. eapply nil_rel_rev. invc Hrefine. auto. }\n    destruct (tydesc_eq_dec A _ _); [ exfalso; congruence | ].\n    assert (aty0 = nil_ty A). { eapply nil_rel_fwd. invc Hrefine0. auto. }\n    subst aty0. destruct (tydesc_eq_dec A _ _); [ | exfalso; congruence ].\n    eexists. split; [ reflexivity | ]. inject_some. simpl.\n    constructor. { invc Hrefine. auto. } intros.\n\n    on >(refine_state_fn dty), invc.  specialize_refinement.\n      repeat find_rewrite. inject_pair.\n    on >(refine_state_fn (nil_ty D)), invc.  specialize_refinement.\n      repeat find_rewrite. inject_pair.\n    auto.\n\n- (* nil *) discriminate.\n\n- destruct es as [| e' es ].\n\n  + (* singleton list *)\n    handle_unpack_opt.\n\n    eexists. split; [reflexivity|]. inject_some. simpl.\n\n    constructor.  { on >refine_state_fn, invc. auto. }\n    intros.  clear IHe IHe0.\n\n    on >(refine_state_fn dty), invc.  specialize_refinement.\n      repeat find_rewrite. inject_pair.\n    auto.\n\n  + (* singleton list *)\n    remember (e' :: es) as e'_es.\n    handle_unpack_opt.\n    handle_unpack_opt.\n    destruct (tydesc_eq_dec _ _ _); try discriminate.\n      subst dty0.\n\n    destruct (tydesc_eq_dec _ _ _); cycle 1.\n      { on (aty <> _), contradict.\n        invc Hrefine. invc Hrefine0.\n        eapply ty_rel_inj; eauto. }\n      subst aty0.\n\n    eexists. split; [reflexivity|]. inject_some. simpl.\n\n    constructor.  { on >refine_state_fn, invc. auto. }\n    intros.  clear IHe IHe0.\n\n    on >(refine_state_fn dty), invc.  specialize_refinement.\n      repeat find_rewrite. inject_pair.\n    on >(refine_state_fn_list dty), invc.  specialize_refinement.\n      repeat find_rewrite. inject_pair.\n    auto.\n\nQed.\n\nLocal Transparent A.\nLocal Transparent D.\n\nLemma denote_refine : forall e dden,\n    Dbl.denote e = Some dden ->\n    exists aden,\n        Abs.denote e = Some aden /\\\n        refine_state_fn_noxvar Dbl.Dbl Abs.Abs dden aden.\nintros. unfold Dbl.denote in *.\n\non _, invc_using unpack_ty_some_inv.\nforward eapply denote'_refine as HH; eauto.  destruct HH as (aden & Haden & Hrefine).\n  simpl in Hrefine. destruct aden as [aty aden].\n  change e_double with (ty_denote D Dbl.Dbl) in val.\n  assert (aty = Abs.Abs).  { inv Hrefine. on >ty_rel, invc. auto. }  subst aty.\nunfold Abs.denote.\neapply unpack_ty_some_ex; eauto.\n\neexists. split; [ reflexivity | ]. inject_some.\nconstructor. { invc Hrefine. auto. }  intros.\nchange (tt, tt, tt, tt, tt, tt, tt, tt, tt, tt, tt, tt) with (multi_rep 12 tt) in *.\n\nassert (MForall2 (refine_value (xvar_ty D) (xvar_ty A)) (multi_rep 12 tt) (multi_rep 12 tt)).\n  { eapply rep_MForall2. constructor. }\n\non >refine_state_fn, invc.  specialize_refinement.\n  repeat find_rewrite. inject_pair.\nauto.\nQed.\n\n\nLemma refine_state_fn_noxvar_dbl_abs_inv : forall df af,\n    refine_state_fn_noxvar Dbl.Dbl Abs.Abs df af ->\n    (forall dsv asv dsv' dr asv' ar,\n        MForall2 (refine_value _ _) dsv asv ->\n        df dsv = (dsv', dr) ->\n        af asv = (asv', ar) ->\n        MForall2 (refine_value _ _) dsv' asv' /\\\n        refine_value _ _ dr ar).\ninversion 1. auto.\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/floatabs/AbsExprProofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2674016342650133}}
{"text": "(*===========================================================================\n    I/O actions\n  ===========================================================================*)\nRequire Import Ssreflect.ssreflect Ssreflect.ssrbool Ssreflect.ssrfun Ssreflect.eqtype Ssreflect.tuple Ssreflect.seq.\nRequire Import x86proved.bitsrep x86proved.bitsops x86proved.bitsprops.\n\nDefinition Chan := WORD.\nDefinition Data := BYTE.\n\nInductive Action :=\n| Out (c:Chan) (d:Data)\n| In (c:Chan) (d:Data).\n\nDefinition actionEq a1 a2 :=\n  match a1, a2 with\n  | Out c1 d1, Out c2 d2 => (c1 == c2) && (d1 == d2)\n  | In c1 d1, In c2 d2 => (c1 == c2) && (d1 == d2)\n  | _, _ => false\n  end.\n\nLemma action_eqP: Equality.axiom actionEq.\nProof. case => c1 d1.  case => c2 d2. simpl.\n+ case E1: (c1 == c2).\n  case E2: (d1 == d2).\n  simpl. rewrite (eqP E1) (eqP E2). by apply ReflectT.\n  apply ReflectF => H.  inversion H.\n  rewrite H2 in E2. by rewrite eq_refl in E2.\n  apply ReflectF => H. inversion H.\n  rewrite H1 in E1. by rewrite eq_refl in E1.\n  by apply ReflectF => H.\n  case => c2 d2.\n  by apply ReflectF => H.\nsimpl.\ncase E1: (c1 == c2).\ncase E2: (d1 == d2).\n  simpl. rewrite (eqP E1) (eqP E2). by apply ReflectT.\n  apply ReflectF => H.  inversion H.\n  rewrite H2 in E2. by rewrite eq_refl in E2.\n  apply ReflectF => H. inversion H.\n  rewrite H1 in E1. by rewrite eq_refl in E1.\nQed.\n\nCanonical action_eqMixin := EqMixin action_eqP.\nCanonical action_eqType := Eval hnf in EqType _ action_eqMixin.\n\nDefinition Actions := seq Action.\n\nDefinition preActions (a1 a2: Actions) := exists a', a2 = a1 ++ a'.\nDefinition preActionsOp a1 a2 := preActions a2 a1.\nDefinition strictPreActions (a1 a2: Actions) :=\n  exists o a', a2 = a1 ++ o::a'.\n\nDefinition postActions (a1 a2: Actions) := exists a', a2 = a'++a1.\nDefinition postActionsOp a1 a2 := postActions a2 a1.\nDefinition strictPostActions (a1 a2: Actions) :=\n  exists o a', a2 = a'++o::a1.\n\nRequire Import Coq.Classes.RelationClasses Coq.Program.Basics.\n\nInstance preActions_Pre: PreOrder preActions.\nProof. repeat constructor; hnf.\nmove => a. exists nil. by rewrite cats0.\nmove => x y z [a1 ->] [a2 ->]. exists (a1++a2). by rewrite catA.\nQed.\n\n\nInstance preActionsOp_Pre: PreOrder preActionsOp.\nProof. repeat constructor; hnf.\nmove => a. exists nil. by rewrite cats0.\nmove => x y z [a1 ->] [a2 ->]. exists (a2++a1). by rewrite catA.\nQed.\n\nInstance postActionsOp_Pre: PreOrder postActionsOp.\nProof. repeat constructor; hnf.\nmove => a. by exists nil.\nmove => x y z [a1 ->] [a2 ->]. exists (a1++a2). by rewrite catA.\nQed.\n\nLemma cat_preActions a : forall a1 a2, preActions a1 a2 -> preActions (a++a1) (a++a2).\nProof. induction a => // a1 a2 [a' ->]. exists a'. by rewrite catA. Qed.\n\nRequire Import Coq.Setoids.Setoid x86proved.charge.csetoid Coq.Classes.RelationClasses Coq.Classes.Morphisms.\n\nInstance ActionsEquiv : Equiv Actions := {\n   equiv a1 a2 := a1 = a2\n}.\n\nInstance ActionsType : type Actions.\nProof.\n  split.\n  move => x; by reflexivity.\n  move => x y H; by symmetry.\n  move => x y z H1 H2; by rewrite H1 H2.\nQed.\n\nDefinition outputToActions o : Actions := map (fun p => Out p.1 p.2) o.\n\nLemma preActionsOp_strictPre x t t':\n  preActionsOp t t' -> strictPreActions x t' -> strictPreActions x t.\nProof. move => PRE [a [b H]]. destruct t'. destruct x => //.\n+ destruct x. destruct PRE as [d ->]. simpl. by exists a0, (t'++d).\n+ inversion H. subst. destruct PRE as [d ->]. simpl.\nexists a, (b++d). by rewrite /= -!catA. Qed.\n\nLemma strictPre_implies_preActionsOp x y :\n  strictPreActions x y -> preActionsOp y x.\nProof. move => [a [b ->]]. by exists (a::b).  Qed.\n\nLemma preActionsOpDef o o' : preActions o o' <-> preActionsOp o' o.\nProof. by unfold preActionsOp. Qed.\n\nLemma strictPost_implies_postActionsOp x y :\n  strictPostActions x y -> postActionsOp y x.\nProof. move => [a [b ->]]. unfold postActionsOp. exists (b++[::a]). by rewrite -catA/=. Qed.\n\nLemma postActionsOpDef o o' : postActions o o' <-> postActionsOp o' o.\nProof. by unfold postActionsOp. 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/ioaction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.26738624997152294}}
{"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 continuity_type.\nRequire Export per_props_set.\nRequire Export per_props_union.\nRequire Export per_props_nat.\nRequire Export alphaeq3.\n\n\n(* n:Nat -> (Nat_n -> Nat) -> (Nat + Unit) *)\nDefinition modulus_fun_type {o} : @CTerm o :=\n  mkc_function\n    mkc_tnat\n    nvarx\n    (mkcv_fun\n       [nvarx]\n       (mkcv_fun [nvarx] (mkcv_natk [nvarx] (mkc_var nvarx)) (mkcv_tnat [nvarx]))\n       (mk_cv [nvarx] (mkc_union mkc_tnat mkc_unit))).\n\nDefinition strong_continuous {o} lib (F : @CTerm o) :=\n  {M : CTerm\n    & member lib M modulus_fun_type\n    # forall (f : CTerm),\n        member lib f nat2nat\n        -> {n : nat\n            & equality lib\n                       (mkc_apply2 M (mkc_nat n) f)\n                       (mkc_inl (mkc_apply F f))\n                       (mkc_union mkc_tnat mkc_unit)\n            # (forall (m : nat),\n                 inhabited_type lib (mkc_assert (mkc_isl (mkc_apply2 M (mkc_nat m) f)))\n                 -> m = n)}}.\n\n(**\n\n  [strong_continuous] should be derivable from [simple_strong_continuous]\n  using [M' n f = primrec(n, M n f, \\i.\\r.if isl(M i f) then inr() else r)]\n  to instantiate [strong_continuous] and\n  where [M] comes from [simple_strong_continuous].\n\n*)\nDefinition simple_strong_continuous {o} lib (F : @CTerm o) :=\n  {M : CTerm\n    & member lib M modulus_fun_type\n    # forall (f : CTerm),\n        member lib f nat2nat\n        -> {n : nat\n            & equality lib\n                       (mkc_apply2 M (mkc_nat n) f)\n                       (mkc_inl (mkc_apply F f))\n                       (mkc_union mkc_tnat mkc_unit) }}.\n\nDefinition agree_upto_red_bc_nat {o} lib b (f g : @CTerm o) :=\n  forall (t1 t2 : CTerm) (i : nat),\n    reduces_toc lib t1 (mkc_nat i)\n    -> reduces_toc lib t2 (mkc_nat i)\n    -> i < b\n    -> equality_of_int_tt lib (mkc_apply f t1) (mkc_apply g t2).\n\nLemma agree_upto_red_bc_nat_implies_equal_in_natk2nat {o} :\n  forall lib b (f g : @CTerm o),\n    member lib f nat2nat\n    -> member lib g nat2nat\n    -> agree_upto_red_bc_nat lib b f g\n    -> equality lib f g (natk2nat (mkc_nat b)).\nProof.\n  introv mf mg agree.\n  unfold natk2nat.\n  apply equality_in_fun; dands.\n  - apply type_mkc_natk.\n    exists (Z.of_nat b); spcast.\n    rw @mkc_nat_eq.\n    apply computes_to_valc_refl; eauto with slow.\n  - intro inh; apply type_tnat.\n  - introv e.\n    apply equality_in_natk in e; exrepnd; spcast.\n    apply computes_to_valc_isvalue_eq in e3; eauto with slow.\n    rw @mkc_nat_eq in e3; ginv.\n    assert (m < b) as l by omega; clear e1.\n    apply equality_in_tnat.\n    unfold equality_of_nat.\n\n    unfold agree_upto_red_bc_nat in agree.\n    pose proof (agree a a' m) as h; repeat (autodimp h hyp); eauto 3 with slow.\n    unfold equality_of_int_tt in h; exrepnd.\n\n    allrw @equality_in_fun; repnd; GC.\n    pose proof (mf a a) as k1; autodimp k1 hyp.\n    { apply equality_in_tnat; unfold equality_of_nat.\n      exists m; dands; spcast; auto. }\n    pose proof (mg a' a') as k2; autodimp k2 hyp.\n    { apply equality_in_tnat; unfold equality_of_nat.\n      exists m; dands; spcast; auto. }\n    allrw @equality_in_tnat; allunfold @equality_of_nat; exrepnd; GC; spcast.\n    allrw @mkc_nat_eq.\n    computes_to_eqval.\n\n    exists k0.\n    allrw @mkc_nat_eq; dands; spcast; auto.\nQed.\n\nDefinition continuous_nat {o} lib (F : @CTerm o) :=\n  forall f,\n    member lib f nat2nat\n    -> {b : nat\n        & forall g,\n            member lib g nat2nat\n            -> agree_upto_red_bc_nat lib b f g\n            -> equality_of_int_tt lib (mkc_apply F f) (mkc_apply F g)}.\n\nLemma strong_continuous_implies_continuous {o} :\n  forall lib (F : @CTerm o),\n    strong_continuous lib F -> continuous_nat lib F.\nProof.\n  introv cont.\n  unfold strong_continuous in cont.\n  unfold continuous_nat.\n  destruct cont as [M cont]; destruct cont as [mM cont].\n  introv mf.\n  applydup cont in mf; exrepnd.\n\n  exists n.\n  introv mg agree.\n\n  applydup cont in mg; exrepnd.\n  clear cont.\n\n  pose proof (agree_upto_red_bc_nat_implies_equal_in_natk2nat lib n f g) as e.\n  repeat (autodimp e hyp).\n  unfold modulus_fun_type in mM.\n  apply equality_in_function2 in mM; repnd; clear mM0.\n\n  pose proof (mM (mkc_nat n) (mkc_nat n)) as ap.\n  autodimp ap hyp.\n  { apply equality_in_tnat; unfold equality_of_nat.\n    exists n; dands; spcast; apply computes_to_valc_refl; eauto with slow. }\n  eapply alphaeqc_preserving_equality in ap;[|apply mkcv_fun_substc].\n  allrw @csubst_mk_cv.\n  eapply alphaeqc_preserving_equality in ap;\n    [|apply alphaeqc_mkc_fun;[|apply alphaeqc_refl];\n      apply mkcv_fun_substc].\n  allrw @mkcv_tnat_substc.\n  eapply alphaeqc_preserving_equality in ap;\n    [|apply alphaeqc_mkc_fun;[|apply alphaeqc_refl];\n      apply alphaeqc_mkc_fun;[|apply alphaeqc_refl];\n      apply mkcv_natk_substc].\n  allrw @mkc_var_substc.\n  fold (@natk2nat o (mkc_nat n)) in ap.\n\n  apply equality_in_fun in ap; repnd.\n  clear ap0 ap1.\n  pose proof (ap f g e) as equn.\n\n  allrw <- @mkc_apply2_eq.\n  assert (equality\n            lib\n            (mkc_apply2 M (mkc_nat n) g)\n            (mkc_inl (mkc_apply F f))\n            (mkc_union mkc_tnat mkc_unit)) as e2.\n  { eapply equality_trans;[apply equality_sym;exact equn|auto]. }\n\n  apply implies_isl_in_bool in e2.\n  eapply equality_respects_cequivc_right in e2;\n    [|eapply computes_to_valc_inl_implies_cequivc_isl_tt;\n       apply computes_to_valc_refl;\n       apply iscvalue_mkc_inl].\n\n  apply equality_tt_in_bool_implies_cequiv in e2; spcast.\n\n  pose proof (mg1 n) as k.\n  autodimp k hyp.\n  { spcast.\n    eapply inhabited_type_cequivc;\n      [apply cequivc_mkc_assert;apply cequivc_sym; exact e2|].\n    eapply inhabited_type_cequivc;\n      [apply cequivc_sym;apply mkc_assert_tt|].\n    apply inhabited_type_mkc_unit. }\n  subst n0.\n\n  assert (equality\n            lib\n            (mkc_inl (mkc_apply F f))\n            (mkc_inl (mkc_apply F g))\n            (mkc_union mkc_tnat mkc_unit)) as eap.\n  { eapply equality_trans;[apply equality_sym; exact mf0|].\n    eapply equality_trans;[exact equn|]; auto. }\n\n  apply equality_mkc_inl_implies in eap.\n  apply equality_in_tnat in eap.\n  apply equality_of_nat_implies_equality_of_int in eap.\n  apply equality_of_int_imp_tt in eap; auto.\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_defs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.26738624997152294}}
{"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\n(** * HElGamal.v : Semantic security of the Hashed ElGamal encryption scheme \n   in the Random Oracle Model *)\n\nSet Implicit Arguments.\n\nRequire Import SemHElGamal.\n\n\n(** TODO: Move this somewhere else *)\nLemma CGK_eqb_refl : forall k v, (@CGK.eqb k v v) = true.\nProof.\n intros k v; generalize (CGK.eqb_spec v v); case (CGK.eqb v v).\n trivial.\n intro H; elim H; trivial.\nQed.\n\nLemma CGK_eqb_sym : forall k v1 v2, \n @CGK.eqb k v1 v2 <-> @CGK.eqb k v2 v1.\nProof.\n intros k v1 v2.\n split;\n  generalize (CGK.eqb_spec v1 v2); generalize (CGK.eqb_spec v2 v1);\n  case (CGK.eqb v1 v2); case (CGK.eqb v2 v1);\n  intros H1 H2; trivial.\n elim H1; symmetry; trivial.\n elim H2; symmetry; trivial.\nQed.\n\nLemma is_true_CGK_eqb : forall k v1 v2, \n @CGK.eqb k v1 v2 <-> v1 = v2.\nProof.\n split; intros.\n generalize (CGK.eqb_spec v1 v2); rewrite H; trivial.\n rewrite H; apply CGK_eqb_refl.\nQed.\n\nLemma modus_ponens : forall k (m:Mem.t k) e1 e2,\n E.eval_expr (e1 ==> e2) m ->\n E.eval_expr e1 m ->\n E.eval_expr e2 m.\nProof.\n intros.\n unfold E.eval_expr, O.eval_op in H, H0; simpl in H, H0.\n rewrite H0 in H; trivial.\nQed.\n(* TODO : This lemma is eval_expr_eq *)\nLemma eval_eq : forall k (m:Mem.t k) (t:T.type) e1 e2,\n @E.eval_expr k t e1 m = E.eval_expr e2 m <-> \n E.eval_expr (e1 =?= e2) m.\nProof.\n intros; unfold E.eval_expr, O.eval_op; simpl.\n split.\n intro H; rewrite H.\n apply Ti_eqb_refl.\n intros H.\n rewrite is_true_Ti_eqb in H.\n apply H.\nQed.\n\n\nSection PR_RANDOM_DOM.\n \n Variable c : cmd.\n Variable t1 : T.type.\n Variable t2 : T.type.\n\n Variable e : E.expr t1.\n Variable n : nat -> nat.\n\n Variable i : Var.var T.Nat.\n Variable x : Var.var t1.\n Variable L : Var.var (T.List (T.Pair t1 t2)).\n \n Variable E : env.\n \n Hypothesis fv_x : ~Vset.mem x (fv_expr e).\n Hypothesis fv_i : ~Vset.mem i (fv_expr e).\n\n Let c' := c ++ [ i <$- [0..Elen L]; x <- Efst (Enth {i, L}) ].\n\n Close Scope nat_scope.\n\n Lemma Pr_random_dom : forall k (m:Mem.t k),\n  ([1/]1+pred (n k)) * Pr E c m (EP k (Elen L <! (n k)) [&&] EP k (e in_dom L)) <=\n  Pr E c' m (EP k (x =?= e)).\n Proof.\n  intros; unfold Pr, c'.\n  rewrite <- (mu_stable_mult _ _ _), deno_app_elim.\n  apply mu_monotonic; intro m'.\n  rewrite deno_cons_elim, Mlet_simpl, deno_random_elim.\n  unfold charfun, restr, EP, andP, andb, fone, fmult.\n  case_eq (@E.eval_expr _ T.Bool (Elen L <! n k) m');\n   case_eq (@E.eval_expr _ T.Bool (e in_dom L) m'); Usimpl; trivial.\n  simpl E.eval_expr; unfold O.eval_op; simpl T.app_op.\n  intros Hin Hlen.\n  apply leb_complete in Hlen; simpl in Hlen.\n  apply is_true_existsb in Hin; destruct Hin as [a [Hin Heq] ].\n  simpl in Hin.\n  destruct (In_nth_inv _ (T.default k (T.Pair t1 t2)) _ Hin) as [j [Hlt Hnth] ].  \n  rewrite <- (@sum_support_in _ _ j).\n  simpl; rewrite seq_length; unfold O.eval_op; simpl.\n  apply Unth_anti_mon; omega.  \n  apply le_In_seq; simpl; unfold O.eval_op; simpl in Hlt |- *; auto with arith.\n \n  rewrite deno_assign_elim.\n  rewrite Mem.get_upd_same.\n  simpl; unfold O.eval_op; simpl; mem_upd_simpl.\n  rewrite (@depend_only_fv_expr _ _ _ _ m').\n  apply is_true_Ti_eqb in Heq; rewrite Heq, Hnth, Ti_eqb_refl; trivial.\n\n  intros ? y Hy.\n  repeat rewrite Mem.get_upd_diff; trivial.\n  intro H; rewrite H in fv_i; tauto.\n  intro H; rewrite H in fv_x; tauto.\n Qed.\n\nEnd PR_RANDOM_DOM.\n\n\n(** ** CDH assumption *) \nSection CDH_ASSUMPTION.\n\n (** The CDH assumption says that any efficient adversary [C] has a\n    negligible chance of outputting [g^xy] given [g^x] and [g^y],\n    where [x] and [y] are uniformly sampled.\n *)\n\n Variables x y : Var.var T.Nat.\n Variable L : Var.var (T.List (T.Pair (T.User Group) (T.User Bitstring))).\n Variable z : Var.var (T.User Group).\n\n Variable Cname : positive.\n\n Notation Local C := (Proc.mkP Cname \n   (T.User Group :: T.User Group :: nil) \n   (T.User Group)).\n\n Definition CDH :=\n  [\n   x <$- [0..q-!1];\n   y <$- [0..q-!1];\n   z <c- C with {g^x, g^y}\n  ].\n\n Definition CDH_advantage E k (m:Mem.t k) := \n  Pr E CDH m (EP k (z =?= g^(x *! y))).\n \n Axiom CDH_assumption : forall (m:forall k, Mem.t k) E,\n  x <> y ->\n  Var.is_local x ->\n  Var.is_local y ->\n  lossless E (proc_body E C) ->\n  PPT_proc E C ->\n  negligible (fun k => CDH_advantage E (m k)).\n\nEnd CDH_ASSUMPTION.\n\n\nOpen Scope positive_scope.\n\n(** ** Global Variables *)\n\nNotation L   := (Var.Gvar (T.List (T.Pair (T.User Group) (T.User Bitstring))) 1).\nNotation Lam := (Var.Gvar (T.User Group) 2).\nNotation hp  := (Var.Gvar (T.User Bitstring) 3).\nNotation bad := (Var.Gvar T.Bool 4).\nNotation L'   := (Var.Gvar (T.List (T.Pair (T.User Group) (T.User Bitstring))) 5).\n\n(** *** Global variables shared between the adversary, the oracles and \n  the game *)\nDefinition Gcomm := Vset.empty.\n\n(** Global variable shared between [A] and [A'] *)\nNotation g_a := (Var.Gvar T.Nat 5).\n\nDefinition Gadv := Vset.singleton g_a.\n\n\n(** ** Local variables *)\n\n(** Integer variables *)\nNotation x := (Var.Lvar T.Nat 11).\nNotation y := (Var.Lvar T.Nat 12).\n\n(** Bitstrings *)\nNotation h := (Var.Lvar (T.User Bitstring) 21).\nNotation r := (Var.Lvar (T.User Bitstring) 22).\nNotation v := (Var.Lvar (T.User Bitstring) 23).\n\n(** Group elements *)\nNotation alpha  := (Var.Lvar (T.User Group) 31).\nNotation beta   := (Var.Lvar (T.User Group) 32).\nNotation lambda := (Var.Lvar (T.User Group) 33).\n\n(** Messages *)\nNotation mm := (Var.Lvar (T.Pair (T.User Bitstring) (T.User Bitstring)) 41).\nNotation mb := (Var.Lvar (T.User Bitstring) 42).\n\n(** Bits *)\nNotation b  := (Var.Gvar T.Bool 51).\nNotation b' := (Var.Lvar T.Bool 52).\n\n(** ** Procedures *)\nNotation Hash := (Proc.mkP 1 \n (T.User Group :: nil) \n (T.User Bitstring)).\n\nNotation A    := (Proc.mkP 2 \n (T.User Group :: nil) \n (T.Pair (T.User Bitstring) (T.User Bitstring))).\n\nNotation A'   := (Proc.mkP 3 \n (T.User Group :: T.User Group :: T.User Bitstring :: nil) \n T.Bool).\n\nNotation B    := (Proc.mkP 4 \n (T.User Group :: T.User Group :: nil) \n (T.User Group)).\n\nClose Scope positive_scope.\n\n\n(** ** Adversary and proof *)\nSection ADVERSARY_AND_PROOF.\n \n Variable env_adv : env.\n \n (** *** Specification of the adversary *)\n Definition A_params : var_decl (Proc.targs A) := dcons _ alpha (dnil _).\n\n Variable A_body : cmd.\n \n (** [A] returns a pair of messages *)\n Variable A_ret : E.expr (T.Pair (T.User Bitstring) (T.User Bitstring)).\n  \n Definition A'_params : var_decl (Proc.targs A') :=\n  dcons _ alpha (dcons _ beta (dcons _ v (dnil _))).\n\n Variable A'_body : cmd.\n\n (** [A'] returns a guess for [b], a boolean *)\n Variable A'_ret : E.expr T.Bool.\n \n Definition Hash_params : var_decl (Proc.targs Hash) := dcons _ lambda (dnil _).\n\n Definition Hash_ret := r.\n\n Definition makeEnv (Hash_body:cmd) :=  \n  let EHash := add_decl env_adv Hash Hash_params (refl_equal true) \n   Hash_body Hash_ret in \n  let EA    := add_decl EHash A A_params (refl_equal true) A_body A_ret in\n   add_decl EA A' A'_params (refl_equal true) A'_body A'_ret. \n\n\n (** Initial game *)\n Definition G0 :=\n  [\n   L <- Nil _;\n   x <$- [0..q-!1];\n   y <$- [0..q-!1];\n   mm <c- A with {g^x};\n   b <$- {0,1};\n   If b then [ mb <- Efst mm ] else [ mb <- Esnd mm ];  \n   h <c- Hash with {g^(x *! y)};\n   v <- h |x| mb;\n   b' <c- A' with {g^x, g^y, v}\n  ].\n\n Definition Hash0_body :=\n  [ \n   If !(lambda in_dom L) then \n    [ \n     r <$- {0,1}^k; \n     L <- (lambda | r) |::| L\n    ]\n   else \n    [\n     r <- L[{lambda}]\n    ]\n  ].\n\n Definition E0 := makeEnv Hash0_body.\n\n (** The set of oracles that can be called by [A] and [A'] *)\n Definition PrOrcl := PrSet.singleton (BProc.mkP Hash).\n\n (** Private procedures, not accessible to the adversary *)\n Definition PrPriv := PrSet.singleton (BProc.mkP B).\n\n (** The adversary is well-formed in [E0], i.e. it only reads or writes \n    variables it has access to, and only calls oracles and its own procedures *)\n Hypothesis A_wf  : WFAdv PrOrcl PrPriv Gadv Gcomm E0 A.\n Hypothesis A'_wf : WFAdv PrOrcl PrPriv Gadv Gcomm E0 A'.\n\n (** The adversary runs in PPT provided the hash oracle does *)\n Hypothesis A_PPT : forall E,\n  Eq_adv_decl PrOrcl PrPriv E0 E ->\n  (forall O, PrSet.mem O PrOrcl -> PPT_proc E (BProc.p_name O)) ->\n  PPT_proc E A.\n \n Hypothesis A'_PPT : forall E,\n  Eq_adv_decl PrOrcl PrPriv E0 E ->\n  (forall O, PrSet.mem O PrOrcl -> PPT_proc E (BProc.p_name O)) ->\n  PPT_proc E A'.\n \n (** The adversary is lossless (i.e. it always terminates) provided \n    the hash oracle is lossless *)\n Hypothesis A_lossless : forall E,\n  Eq_adv_decl PrOrcl PrPriv E0 E ->\n  (forall O, PrSet.mem O PrOrcl -> lossless E (proc_body E (BProc.p_name O))) ->\n  lossless E A_body.\n\n Hypothesis A'_lossless : forall E,\n  Eq_adv_decl PrOrcl PrPriv E0 E ->\n  (forall O, PrSet.mem O PrOrcl -> lossless E (proc_body E (BProc.p_name O))) ->\n  lossless E A'_body.\n \n Lemma EqAD : forall H_body1 H_body2, \n  Eq_adv_decl PrOrcl PrPriv (makeEnv H_body1) (makeEnv H_body2).\n Proof.\n  unfold Eq_adv_decl, proc_params, proc_body, proc_res, makeEnv; intros.\n  generalize (BProc.eqb_spec (BProc.mkP A) (BProc.mkP f)).\n  destruct (BProc.eqb (BProc.mkP A) (BProc.mkP f)); intros.\n  inversion H1; simpl; auto.\n  generalize (BProc.eqb_spec (BProc.mkP A') (BProc.mkP f)).\n  destruct (BProc.eqb (BProc.mkP A') (BProc.mkP f)); intros.\n  inversion H2; simpl; auto.\n  repeat rewrite add_decl_other_mk; try tauto; intro Heq;\n   apply H; rewrite <- Heq; vm_compute; trivial.\n Qed.\n\n Lemma EqOP : forall H_body1 H_body2, \n  Eq_orcl_params PrOrcl (makeEnv H_body1) (makeEnv H_body2).\n Proof.\n  unfold Eq_orcl_params,makeEnv; intros.\n  unfold PrOrcl in H.\n  apply PrSet.singleton_complete in H; inversion H; simpl.\n  vm_compute; trivial.\n Qed.\n\n Lemma A_wf_E : forall H_body, \n  WFAdv PrOrcl PrPriv Gadv Gcomm (makeEnv H_body) A.\n Proof.\n  intros; apply WFAdv_trans with (5:=A_wf); unfold E0; try discriminate.\n  apply EqOP.\n  apply EqAD.\n Qed.\n\n Lemma A'_wf_E : forall H_body,\n  WFAdv PrOrcl PrPriv Gadv Gcomm (makeEnv H_body) A'.\n Proof.\n  intros; apply WFAdv_trans with (5:=A'_wf); try discriminate.\n  apply EqOP.\n  apply EqAD.\n Qed.\n\n (** Helper functions to construct the information used by tactics *)\n Definition iEiEi Hbody Hr Hr' :=\n  let E := makeEnv Hbody in\n  let Aloss := @A_lossless E (EqAD _ _) in\n  let A'loss := @A'_lossless E (EqAD _ _) in\n  let piH := add_refl_info_rm Hash Hr Hr' (empty_info E E) in\n  let piA := add_adv_info_lossless (EqAD _ _) (A_wf_E _) Aloss Aloss piH in\n   add_adv_info_lossless (EqAD _ _) (A'_wf_E _) A'loss A'loss piA.\n\n Definition iEiEj Hbody Hbody' I O\n  (Hequiv:EqObsInv trueR I (makeEnv Hbody) Hbody (makeEnv Hbody') Hbody' O) :=\n  let E := makeEnv Hbody in    \n  let E' := makeEnv Hbody' in\n  let Aloss := @A_lossless E (EqAD _ _) in\n  let A'loss := @A'_lossless E (EqAD _ _)  in\n  let Aloss' := @A_lossless E' (EqAD _ _)  in\n  let A'loss' := @A'_lossless E' (EqAD _ _)  in\n  let piH := add_info Hash Vset.empty Vset.empty (empty_info E E') Hequiv in\n  let piA := add_adv_info_lossless (EqAD _ _) (A_wf_E _) Aloss Aloss' piH in\n   add_adv_info_lossless (EqAD _ _) (A'_wf_E _) A'loss A'loss' piA.\n \n\n (** Game one *)\n Definition G1 :=\n  [\n   hp <$- {0,1}^k;\n   L <- Nil _;\n   x <$- [0..q-!1];\n   y <$- [0..q-!1];\n   Lam <- g^(x *! y);\n   mm <c- A with {g^x};\n   b <$- {0,1};\n   If b then [ mb <- Efst mm ] else [ mb <- Esnd mm ];\n   h <c- Hash with {Lam};\n   v <- h |x| mb;\n   b' <c- A' with {g^x, g^y, v}\n  ].\n\n  Definition G1' :=\n  [\n   x <$- [0..q-!1];\n   y <$- [0..q-!1];\n   Lam <- g^(x *! y);\n   L <- Nil _;\n   hp <$- {0,1}^k;\n   mm <c- A with {g^x};\n   b <$- {0,1};\n   If b then [ mb <- Efst mm ] else [ mb <- Esnd mm ];\n   h <c- Hash with {Lam};\n   v <- h |x| mb;\n   b' <c- A' with {g^x, g^y, v}\n  ].\n\n Definition Hash1'_body :=\n  [ \n   If !(lambda in_dom L) then \n   [\n    If Lam =?= lambda then\n     [\n      r <- hp\n     ]\n    else\n     [\n      r <$- {0,1}^k\n     ];\n    L <- (lambda | r) |::| L\n   ]\n   else [\n    r <- L[{lambda}]\n   ]\n  ].\n\n Definition Hash1_body :=\n  [ \n   If !(lambda in_dom L) then \n   [\n    If Lam =?= lambda then\n     [\n      bad <- true; r <- hp\n     ]\n    else\n     [\n      r <$- {0,1}^k\n     ];\n    L <- (lambda | r) |::| L\n   ]\n   else [\n    r <- L[{lambda}]\n   ]\n  ].\n\n Definition E1'  := makeEnv Hash1'_body.\n Definition E1  := makeEnv Hash1_body.\n\n Definition iE0E0   := iEiEi Hash0_body Vset.empty Vset.empty.\n Definition iE1E1   := iEiEi Hash1_body Vset.empty Vset.empty.\n\n Definition I_H := Vset.add lambda (Vset.add Lam (Vset.singleton L)).\n Definition O_H := Vset.add r (Vset.singleton L).\n \n Lemma Hash1'_Hash1 :\n  EqObsInv trueR (Vset.add hp I_H)\n  E1' Hash1'_body\n  E1  Hash1_body\n  (Vset.add hp O_H).\n Proof.\n  deadcode;eqobs_in.\n Qed.\n\n Definition iE1'E1  := iEiEj Hash1'_Hash1.\n Definition iE1'E1' := iEiEi Hash1'_body Vset.empty Vset.empty.\n (* On doit pouvoir le faire automatiquement i.e sans la preuve Hash1'_Hash1*)\n\n Definition S:=\n  [ If !(Lam in_dom L) then [hp <$- {0,1}^k] else [hp <- L[{Lam}] ] ].\n\n Definition XS:= Vset.add hp (Vset.add Lam (Vset.singleton L)).\n\n Lemma Modify_S : forall E, Modify E XS S.\n Proof.\n  intros E;compute_assertion X t (modify (refl1_info (empty_info E E)) (Vset.add Lam (Vset.singleton L)) S).\n  refine (modify_correct _ _ _ X).\n Qed.\n\n Lemma EqObs_S : EqObs XS E0 S E1' S XS.\n Proof. eqobs_in. Qed.\n\n Lemma XS_global : forall x : VarP.Edec.t, Vset.mem x XS -> Var.is_global x.\n Proof.\n  unfold XS;intros x;repeat rewrite VsetP.add_spec;intros [H0 | [H0 | H0 ] ];\n  try (rewrite <- H0;trivial).\n  apply Vset.singleton_complete in H0;rewrite <- H0;trivial.\n Qed.\n\n Lemma swap_equiv : equiv Meq E0 (proc_body E0 Hash ++ S) E1' (S ++ proc_body E1' Hash) Meq.\n Proof.\n  union_mod;auto with *.\n  apply equiv_strengthen with (kreq_mem (Vset.add lambda (Vset.add L (Vset.singleton Lam)))).\n  intros k m1 m2 Heq;rewrite Heq;apply req_mem_refl.\n  apply EqObs_trans with (E2 := E0) (c2:= (L' <- L)::(proc_body E0 Hash ++ S));\n   [deadcode;eqobs_in | ].\n  apply EqObs_trans with (E2 := E1') (c2:= (L' <- L)::(S ++ proc_body E1' Hash));\n   [ | deadcode;eqobs_in].\n  apply equiv_cons with (req_mem_rel (Vset.add L' (Vset.add lambda (Vset.add L (Vset.singleton Lam))))\n                            (EP1 (L =?= L'))).\n  eqobsrel_tail;unfold implMR;simpl;unfold O.eval_op;simpl;intros.\n  change (E.eval_expr (L =?= L) m1);rewrite <- eval_eq;trivial.\n  ep_eq L L'.\n  unfold EP1;intros k m1 m2 (Heq, H1);rewrite <- (eval_eq m1 L L') in H1.\n  split;[trivial | transitivity (E.eval_expr L m1)].\n  apply depend_only_fv_expr;apply req_mem_sym;apply req_mem_weaken with (2:= Heq);vm_compute;trivial.\n  transitivity (E.eval_expr L' m1);[trivial | ].\n  apply depend_only_fv_expr;apply req_mem_weaken with (2:= Heq);vm_compute;trivial.\n  cp_test (lambda in_dom L').\n  ep_eq_l L L';[unfold EP1;intros k m1 m2 ((_,H),_);rewrite eval_eq;trivial | ].\n  swap;eqobs_in.\n  cp_test (Lam in_dom L').\n  ep_eq (Lam =?= lambda) false.\n  unfold req_mem_rel, andR, EP1, EP2, notR; intros k m1 m2 H;decompose [and] H;clear H.\n  split;refine (not_true_is_false _ _).\n  rewrite <- (eval_eq m1 Lam lambda);intros Heq;apply H2.\n  generalize H3 Heq;clear H3 Heq;simpl;unfold O.eval_op;simpl; intros H3 Heq;rewrite <- Heq;trivial.\n  rewrite <- (eval_eq m2 Lam lambda);intros Heq;apply H5.\n  generalize H6 Heq;clear H6 Heq;simpl;unfold O.eval_op;simpl; intros H6 Heq;rewrite <- Heq;trivial.\n  swap;eqobs_in.\n  cp_test (Lam =?=lambda).\n  alloc_l r hp;ep;eqobs_in.\n  swap;eqobs_in.\n Qed.\n \n Definition swi_H := \n  add_sw_info S XS Vset.empty E0 E1' (Modify_S E0) (Modify_S E1') EqObs_S \n  XS_global (fun t f => None) _ Hash swap_equiv.\n\n Definition swi : forall (tg : SemHElGamal.T.type) (g_ : Proc.proc tg),\n  option (sw_info S XS Vset.empty E0 E1' tg g_).\n  assert (swi_A : forall (tg : SemHElGamal.T.type) (g_ : Proc.proc tg), option (sw_info S XS Vset.empty E0 E1' tg g_)).\n    refine (add_sw_info_Adv S XS Vset.empty E0 E1' (Modify_S E0) (Modify_S E1') \n           EqObs_S XS_global swi_H _ A PrOrcl PrPriv Gadv Gcomm _ _);[ apply EqAD | trivial].\n  refine (add_sw_info_Adv S XS Vset.empty E0 E1' (Modify_S E0) (Modify_S E1') \n           EqObs_S XS_global swi_A _ A' PrOrcl PrPriv Gadv Gcomm _ _);[ apply EqAD | trivial].\n Defined.\n\n Lemma EqObs_G0_G1 : EqObs Gadv E0 G0 E1 G1 (fv_expr (b =?= b')).\n Proof.\n  unfold G0, G1;match goal with \n  |- EqObs _ _ (?i1::?i2::?i3::?c) _ (?ihp::_::_::_::?iLam::_) _ => \n     apply EqObs_trans with E0 ([i2;i3;iLam;i1]++(c++S));\n     [deadcode iE0E0;swap iE0E0;eqobs_in iE0E0 |\n      apply EqObs_trans with E1' ([i2;i3;iLam;i1]++(S++c));\n      [ | ep iE1'E1;swap iE1'E1;eqobs_in iE1'E1]\n     ]\n  end.\n  apply equiv_app with (kreq_mem (Vset.add x (Vset.add y (Vset.add Lam (Vset.add L Gadv))))).\n  eqobs_in.\n  match goal with \n  |- equiv _ _ _ _ ?c _ => apply equiv_trans_eq_mem_l with (E1':= E1') (c1':= c) (P1:=trueR) end.\n  apply equiv_strengthen with Meq;[intros k0 m1 m2 (H, _);trivial | ].\n  apply check_swap_c_correct with (pi:= swi) (I:=Vset.empty).\n   apply Modify_S. \n   apply Modify_S. \n   apply EqObs_S.\n   vm_compute; trivial.\n  eqobs_in iE1'E1'.\n  red;intros;red;trivial.\n Qed.\n\n (** Game two *)\n Definition G2 :=\n  [\n   bad <- false;\n   hp <$- {0,1}^k;\n   L <- Nil _;\n   x <$- [0..q-!1];\n   y <$- [0..q-!1];\n   Lam <- g^(x *! y);\n   mm <c- A with {g^x};\n   b <$- {0,1};\n   If b then [ mb <- Efst mm ] else [ mb <- Esnd mm ];\n   h <- hp;\n   v <- h |x| mb;\n   b' <c- A' with {g^x, g^y, v}\n  ].\n\n Definition Hash2_body :=\n  [ \n   If Lam =?= lambda then \n    [ \n     r <- hp\n    ] \n   else \n    [\n     If !(lambda in_dom L) then\n      [\n       r <$- {0,1}^k;\n       L <- (lambda | r) |::| L\n      ]\n     else \n      [\n       r <- L[{lambda}]\n      ]\n    ]\n  ].\n\n Definition E2 := makeEnv Hash2_body.\n\n Definition I2 := \n  EP1 ((Lam in_dom L) ==> (L[{Lam}] =?= hp)) /-\\\n  eq_assoc_except Lam L.\n \n Lemma dec_I2 : decMR I2.\n Proof.\n  unfold I2; auto.\n Qed.\n \n Lemma dep_I2 : depend_only_rel I2\n  (Vset.union (fv_expr ((Lam in_dom L) ==> (L[{Lam}] =?= hp)))\n    (Vset.add Lam (Vset.singleton L)))\n  (Vset.union Vset.empty (Vset.singleton L)).\n Proof.\n  unfold I2; auto.\n Qed.\n \n Definition eE1E2 : eq_inv_info I2 E1 E2.\n  refine (@empty_inv_info _ _ _ dep_I2 _ dec_I2 _ _).\n  vm_compute; trivial.\n Defined.\n\n Lemma Hash1_Hash2 :\n  EqObsInv I2\n  (Vset.add hp (Vset.add Lam (Vset.singleton lambda)))\n  E1 Hash1_body \n  E2 Hash2_body\n  (Vset.add r (Vset.singleton hp)).\n Proof.\n  unfold Hash2_body, Hash1_body.\n  cp_test (Lam =?= lambda).\n  ep_eq lambda Lam.\n  intros k m1 m2 (_,(H1,H2));split;symmetry;repeat rewrite eval_eq;trivial.\n  cp_test_l (Lam in_dom L).\n\n  ep_eq_l (L[{Lam}]) hp.\n  unfold I2, req_mem_rel, andR, EP1, EP2; intros.\n  decompose [and] H; clear H.\n  rewrite eval_eq; apply modus_ponens with (e1:=Lam in_dom L); auto.\n  eqobs_in eE1E2;unfold implMR, andR; tauto.\n\n  rewrite proj1_MR, proj1_MR.\n  unfold I2;eqobsrel_tail;\n   unfold implMR, andR; simpl; unfold O.eval_op; simpl; unfold O.assoc; simpl.\n  intros; rewrite CGK_eqb_refl; simpl.\n  split;[rewrite Veqb_refl; trivial | intros r Hdiff].\n  decompose [and] H;clear H.\n  destruct (H3 _ Hdiff);clear H3.\n  rewrite <- is_true_CGK_eqb in Hdiff;apply not_true_is_false in Hdiff;rewrite Hdiff.\n  simpl;split;trivial.\n\n  cp_test (lambda in_dom L).\n  unfold I2;intros k m1 m2 ((H0,(W1,W2)), (H2, H3)).\n  unfold notR, EP1 in H2; rewrite <- (eval_eq m1 Lam lambda) in H2; apply sym_not_eq in H2.\n  destruct (W2 _ H2) as (W3,_);clear W2 H2.\n  assert (E.eval_expr lambda m1 = E.eval_expr lambda m2).\n    apply depend_only_fv_expr;apply req_mem_weaken with (2:= H0);vm_compute;trivial.\n  generalize W3;rewrite H at 2;trivial.\n \n  eapply equiv_strengthen; [ | apply equiv_assign].\n  unfold req_mem_rel, upd_para, andR; intros.\n  decompose [and] H; clear H; split.\n  unfold kreq_mem;match goal with\n  |- _{! _ <-- ?x1!} =={_} _{! _ <-- ?x2!} => replace x2 with x1 \n  end.\n  apply req_mem_update.\n  apply req_mem_weaken with (2:=H0); vm_compute; trivial.\n  unfold notR, EP1 in H2;rewrite <- (eval_eq m1 Lam lambda) in H2;apply sym_not_eq in H2.\n  destruct H4 as (W1, W2);destruct (W2 _ H2).\n  assert (E.eval_expr lambda m1 = E.eval_expr lambda m2).\n    apply depend_only_fv_expr;apply req_mem_weaken with (2:= H0);vm_compute;trivial.\n  generalize H1;rewrite H4 at 2;trivial.\n  apply (@dep_I2 k m1 m2);trivial.\n  apply req_mem_upd_disjoint;vm_compute;trivial.\n  apply req_mem_upd_disjoint;vm_compute;trivial.\n  \n  unfold I2;eqobsrel_tail;\n    unfold implMR, andR; simpl; unfold O.eval_op; simpl; unfold O.assoc; simpl.\n  intros k m1 m2 H v _;decompose [and] H;clear H.\n  unfold notR, EP1 in H3;generalize H3;simpl;unfold O.eval_op;simpl;intros W.\n  apply not_true_is_false in W;rewrite W;split;[exact H1 | ].\n  intros r Hdiff;generalize (H4 _ Hdiff);simpl;unfold O.eval_op, O.assoc;simpl;intros (W1,W2).\n  replace (m2 lambda) with (m1 lambda);\n   [ | apply H0;trivial].\n  split;[rewrite W1;trivial| ].\n  destruct (CGK.eqb r (m1 lambda));trivial.\n Qed.\n\n Definition hE1E2 := add_info Hash Vset.empty Vset.empty eE1E2 Hash1_Hash2.\n\n Definition iE1E2inv :=\n  add_adv_info_lossless (EqAD _ _) (A'_wf_E _)\n  (@A'_lossless _ (EqAD _ _))\n  (@A'_lossless _ (EqAD _ _))\n  (add_adv_info_lossless (EqAD _ _) (A_wf_E _)\n   (@A_lossless _ (EqAD _ _))\n   (@A_lossless _ (EqAD _ _))\n   hE1E2).\n\n Definition iE2E2 := iEiEi Hash2_body Vset.empty Vset.empty.\n\n Lemma EqObs_G1_G2 : EqObs Gadv E1 G1 E1 G2 (fv_expr (b =?= b')).\n Proof.\n  unfold G1, G2.\n  match goal with\n  |- EqObs ?I ?E1 (?i1::?i2::?i3::?i4::?i5::?c1) \n              ?E2 (?i0::?i1::?i2::?i3::?i4::?i5::?c2) ?Q =>\n     change (EqObs I E1 ((i1::i2::i3::i4::i5::nil) ++ c1)\n                     E2 ((i0::i1::i2::i3::i4::i5::nil) ++ c2) Q)\n  end.\n  set (I:= (Vset.add L (Vset.add hp (Vset.add x (Vset.add y (Vset.add Lam Gadv)))))).\n  set (O:= fv_expr (b =?= b')).\n  apply equiv_app with (req_mem_rel I (EP1 (L =?= Nil _))).\n  unfold I2; eqobsrel_tail; \n   simpl; unfold O.eval_op; simpl; unfold implMR; simpl; intuition.\n  match goal with\n  |- equiv _ _ ?c _ _ _ => \n     apply equiv_trans with (P1:=req_mem_rel I I2) (Q1:= kreq_mem O) (Q2:= kreq_mem O)\n     (E2:= E2) (c2:=c) end.\n  auto using dec_I2.\n  intros k m1 m2 (H1, H2);split.\n  apply req_mem_trans with m2;[ | apply req_mem_sym];trivial.\n  generalize H2;unfold EP1.\n  rewrite <- (eval_eq m1 L (Nil _)).\n  unfold I2, eq_assoc_except, EP1, EP2, andR;simpl;unfold O.eval_op;simpl;intros Heq;rewrite Heq;auto.\n  apply req_mem_trans.\n  eqobs_in iE1E2inv.\n  match goal with\n  |- equiv _ _ _ _ ?c _ => \n     apply equiv_trans with (P1:=kreq_mem I) (Q1:= kreq_mem O) (Q2:= kreq_mem O)\n     (E2:= E2) (c2:=c) end.\n  auto using dec_I2.\n  intros k m1 m2 _;apply req_mem_refl.\n  apply req_mem_trans.\n  sinline_l iE2E2 Hash;eqobs_in iE2E2.\n  apply equiv_sym_transp.\n  apply equiv_strengthen with (req_mem_rel I I2).\n  intros k m1 m2 (H1, H2);split;[apply req_mem_sym;trivial | ].\n  generalize H2;unfold EP1.\n  rewrite <- (eval_eq m2 L (Nil _)).\n  unfold I2, eq_assoc_except, EP1, EP2, andR;simpl;unfold O.eval_op;simpl;intros Heq.\n  rewrite <- (H1 _ L), Heq;auto.\n  apply equiv_weaken with (kreq_mem O);[exact (@req_mem_sym O) | ].\n  eqobs_in iE1E2inv.\n Qed.\n\n\n\n (** Game three *)\n Definition G3 := G2.\n\n Definition Hash3_body :=\n  [ \n   If !(lambda in_dom L) then \n   [\n    If Lam =?= lambda then\n     [\n      bad <- true; r <$- {0,1}^k\n     ]\n    else\n     [\n      r <$- {0,1}^k\n     ];\n    L <- (lambda | r) |::| L\n   ]\n   else [\n    r <- L[{lambda}]\n   ]\n  ].\n\n Definition E3 := makeEnv Hash3_body.\n\n Definition iE3E3 := iEiEi Hash3_body Vset.empty Vset.empty.\n\n Definition upto_info : upto_info bad E1 E3 :=\n  add_adv_upto_info\n   (add_adv_upto_info\n    (add_upto_info (empty_upto_info bad _ _) Hash)\n    (EqAD _ _) (EqOP _ _) (A_wf_E _))\n   (EqAD _ _) (EqOP _ _) (A'_wf_E _). \n\n Lemma Pr_G2_G3 : forall k (m:Mem.t k),\n  Uabs_diff (Pr E1 G2 m (EP k (b =?= b'))) (Pr E3 G3 m (EP k (b =?= b'))) <= \n  Pr E3 G3 m (EP k bad).\n Proof.\n  intros.\n  unfold G3, G2, Pr.  \n  setoid_rewrite deno_cons_elim.\n  setoid_rewrite Mlet_simpl.\n  setoid_rewrite deno_assign_elim.\n  apply upto_bad_Uabs_diff with upto_info;\n   [ | | apply is_lossless_correct with (refl1_info iE3E3)];\n  vm_compute; trivial.\n Qed.\n\n Definition I3 := EP1 (bad ==> (Lam in_dom L)).\n\n Lemma dec_I3 : decMR I3.\n Proof.\n  unfold I3; auto.\n Qed.\n \n Lemma dep_I3 : depend_only_rel I3\n  (fv_expr (bad ==> (Lam in_dom L)))\n  Vset.empty.\n Proof.\n  unfold I3; auto.\n Qed.\n  \n Definition eE3E3 : eq_inv_info I3 E3 E3.\n  refine (@empty_inv_info _ _ _ dep_I3 _ dec_I3 _ _).\n  vm_compute; trivial.\n Defined.\n\n Lemma Hash3_inv :\n  EqObsInv I3\n  (Vset.add hp (Vset.add bad (Vset.add L (Vset.add Lam (Vset.singleton lambda)))))\n  E3 Hash3_body \n  E3 Hash3_body\n  (Vset.add r (Vset.add bad (Vset.add L (Vset.singleton hp)))).\n Proof.\n  unfold Hash3_body.\n  cp_test (lambda in_dom L).\n  eqobs_in eE3E3; unfold implMR, andR; tauto.\n  cp_test (Lam =?= lambda).\n  ep_eq lambda Lam.\n  intros k m1 m2 (_, (H1,H2));split;symmetry;rewrite eval_eq;trivial.\n  unfold I3; eqobsrel_tail; unfold implMR, EP1, andR; \n   simpl; unfold O.eval_op; simpl.\n  intros k m1 m2 [ _ [_ [ [H _] _] ] ].\n  rewrite CGK_eqb_refl; trivial.\n\n  unfold I3; eqobsrel_tail; unfold implMR, andR, EP1, notR; \n   simpl; unfold O.eval_op; simpl;intros k m1 m2 H;decompose [and] H;clear H;intros.\n  rewrite not_is_true_false in H1;rewrite H1;trivial.\n Qed.\n\n Definition hE3E3 := add_info Hash Vset.empty Vset.empty eE3E3 Hash3_inv.\n\n Definition iE3E3inv :=\n  add_adv_info_lossless (EqAD _ _) (A'_wf_E _)\n  (@A'_lossless _ (EqAD _ _))\n  (@A'_lossless _ (EqAD _ _))\n  (add_adv_info_lossless (EqAD _ _) (A_wf_E _)\n   (@A_lossless _ (EqAD _ _))\n   (@A_lossless _ (EqAD _ _))\n   hE3E3).\n\n Lemma Pr_G3_bad : forall k (m:Mem.t k),\n  Pr E3 G3 m (EP k bad) <= Pr E3 G3 m (EP k (Lam in_dom L)).\n Proof.\n  intros; unfold G3, G2, Pr.\n  eapply equiv_deno_le with (req_mem_rel Gadv trueR) (req_mem_rel (Vset.add Lam (Vset.add bad (Vset.singleton L))) I3).  \n  eqobs_tl iE3E3inv.\n  unfold I3; eqobsrel_tail; unfold implMR, andR; \n   simpl; unfold O.eval_op; trivial.\n  intros m1 m2 [H Hin]; unfold charfun, restr, EP, fone.\n  rewrite <- depend_only_fv_expr_subset with (2:=H);\n   unfold Vset.subset; trivial.\n  case_eq (E.eval_expr bad m1); intro;[ | trivial].\n  rewrite modus_ponens with (e1:=bad); trivial.\n  unfold req_mem_rel, andR, trueR; auto.\n Qed.\n\n\n (** Game four *)\n Definition G4 :=\n  [\n   L <- Nil _;\n   x <$- [0..q-!1];\n   y <$- [0..q-!1];\n   Lam <- g^(x *! y);\n   mm <c- A with {g^x};\n   b <$- {0,1};\n   If b then [mb <- Efst (mm)] else [mb <- Esnd (mm)];   \n   v <$- {0,1}^k;\n   hp <- v |x| mb;\n   b' <c- A' with {g^x, g^y, v}\n  ].\n\n Definition Hash4_body := Hash0_body.\n\n Definition E4 := makeEnv Hash4_body.\n\n Definition iE4E4 := iEiEi Hash4_body Vset.empty Vset.empty.\n\n Lemma Pr_G4 : forall k (m:Mem.t k),\n  Pr E4 G4 m (EP k (b =?= b')) == [1/2].\n Proof.\n  intros.\n  transitivity (Pr E4 (G4 ++ [b <$- {0,1}]) m (EP k (b =?= b'))).\n  apply EqObs_Pr with Gadv.\n  swap iE4E4; deadcode iE4E4; eqobs_in iE4E4.\n  apply Pr_sample_bool; [discriminate | ].\n  apply is_lossless_correct with (refl1_info iE4E4); vm_compute; trivial.  \n Qed.\n\n Lemma Hash3_Hash4 :\n  EqObsInv trueR (Vset.add lambda (Vset.singleton L))\n  E3 Hash3_body\n  E4 Hash4_body\n  (Vset.add r (Vset.add lambda (Vset.singleton L))).\n Proof.\n  unfold Hash3_body, Hash4_body, Hash0_body.\n  cp_test (lambda in_dom L);[eqobs_in | ].\n  cp_test_l (Lam =?= lambda);[ | eqobs_in].\n  ep_eq_l Lam lambda.\n  intros k m1 m2 [_ H]; rewrite eval_eq; trivial.\n  deadcode; eqobs_in.  \n Qed.\n\n Definition iE3E4 := iEiEj Hash3_Hash4.\n  \n Lemma EqObs_G3_G4 : EqObs Gadv E3 G3 E4 G4 (Vset.add L (Vset.add Lam (fv_expr (b =?=b')))).\n Proof.\n  unfold G4, G3, G2.\n  apply EqObs_trans with E4\n   [\n     L <- E.Cnil (T.Pair (T.User Group) (T.User Bitstring));\n     x <$- [0..q -! 1];\n     y <$- [0..q -! 1];\n     Lam <- g ^ (x *! y);\n     mm <c- A with {g ^ x};\n     b <$- {0,1};\n     If b then [mb <- Efst (mm)] else [mb <- Esnd (mm)];\n     hp <$- {0,1}^k;\n     v <- hp |x| mb;\n     b' <c- A' with {g ^ x, g ^ y, v}\n   ].\n  ep; swap iE3E4.\n  eqobs_tl iE3E4.\n  deadcode; eqobs_in.\n\n  eqobs_ctxt iE4E4.\n  union_mod.\n  eapply equiv_sub; [ | | apply opt_sampling; discriminate].\n  simpl; intros; apply req_mem_weaken with (2:=H); red; trivial. \n  simpl; intros; apply req_mem_weaken with (2:=H); red; trivial. \n Qed.\n\n (** Game five *)\n Notation i := (Var.Lvar T.Nat 20).\n Notation z := (Var.Lvar (T.User Group) 40).\n Notation gamma := (Var.Lvar (T.User Group) 50).\n\n Definition G5 := CDH x y z 4.\n\n (** The adversary against list CDH *)\n\n Definition B_body :=\n  [\n   L <- Nil _;   \n   mm <c- A with {alpha};\n   v <$- {0,1}^k;\n   b' <c- A' with {alpha, beta, v} \n ] ++\n [ i <$- [0..Elen L]; gamma <- Efst (Enth {i, L}) ].\n\n Definition B_params : var_decl (Proc.targs B) := \n  dcons _ alpha (dcons _ beta (dnil _)).\n\n Definition B_ret := gamma.\n\n Definition E5 := add_decl E4 B B_params (refl_equal true) B_body B_ret.\n \n Lemma EqAD_5 : Eq_adv_decl PrOrcl PrPriv E5 E5.\n Proof.  \n  unfold Eq_adv_decl; auto.\n Qed.\n\n Lemma EqAD_05 : Eq_adv_decl PrOrcl PrPriv E0 E5.\n Proof.\n  unfold Eq_adv_decl, E0, E5, E4, makeEnv, proc_params, proc_body, proc_res.\n  intros.\n  generalize (BProc.eqb_spec (BProc.mkP A') (BProc.mkP f)).\n  destruct (BProc.eqb (BProc.mkP A') (BProc.mkP f)); intros.\n  inversion H1; simpl; auto.\n  generalize (BProc.eqb_spec (BProc.mkP A) (BProc.mkP f)).\n  destruct (BProc.eqb (BProc.mkP A) (BProc.mkP f)); intros.\n  inversion H2; simpl; auto.  \n  repeat rewrite add_decl_other_mk; try tauto.\n  intro Heq; apply H; rewrite <- Heq; vm_compute; trivial.\n  intro Heq; apply H0; rewrite <- Heq; vm_compute; trivial.\n  intro Heq; apply H; rewrite <- Heq; vm_compute; trivial.\n Qed.\n\n Definition iE4E5 := \n  let Aloss := @A_lossless E4 (EqAD _ _) in    \n  let A'loss := @A'_lossless E4 (EqAD _ _) in\n  let Aloss' := @A_lossless E5 EqAD_05 in    \n  let A'loss' := @A'_lossless E5 EqAD_05 in\n  let piH := add_refl_info Hash (empty_info E4 E5) in\n  let piA := add_adv_info_lossless EqAD_05 (A_wf_E _) Aloss Aloss' piH in\n   add_adv_info_lossless EqAD_05 (A'_wf_E _) A'loss A'loss' piA.\n\n Definition B_advantage := CDH_advantage x y z 4 E5.\n\n\n (** The adversary makes at most qH queries to the hash oracle *)\n Variable qH : nat -> nat.\n \n Hypothesis range_G4 : forall k (m:Mem.t k),\n  range (EP k (Elen L <! qH k)) ([[G4]] E4 m).\n\n Close Scope bool_scope.\n\n Lemma EP_and : forall k e1 e2,\n  (EP k e1) [&&] (EP k e2) == EP k (e1 && e2).\n Proof.\n  trivial.\n Qed.\n\n Lemma security_bound : forall k (m:Mem.t k),\n  [1/]1+pred (qH k) *  Uabs_diff (Pr E0 G0 m (EP k (b =?= b'))) [1/2] <=\n  B_advantage m.\n Proof.\n  intros.\n  set (G4':=\n   [\n    L <- Nil _;  \n    x <$- [0..q -! 1];\n    y <$- [0..q -! 1];\n    mm <c- A with {g^x};\n    v <$- {0,1}^k;\n    b' <c- A' with {g^x, g^y, v}\n    ]).\n  assert (Uabs_diff (Pr E0 G0 m (EP k (b =?= b'))) [1/2] <=\n   Pr E4 G4' m ((EP k ((Elen L <! qH k) && (g^(x *! y) in_dom L))))).\n  eapply Ole_trans; [apply Oeq_le | eapply Ole_trans; [apply (Pr_G2_G3 m) | ] ].\n  apply Uabs_diff_morphism.\n  apply EqObs_Pr with Gadv.\n  apply EqObs_trans with (1:=EqObs_G0_G1); apply EqObs_G1_G2.\n  rewrite <- (Pr_G4 m); symmetry.\n  apply EqObs_Pr with Gadv; apply equiv_weaken with (2:=EqObs_G3_G4).\n  intros k0 m1 m2 H; apply req_mem_weaken with (2:=H); vm_compute; trivial.\n  eapply Ole_trans; [apply Pr_G3_bad | ].\n  apply Ole_trans with (Pr E4 G4 m (EP k (Lam in_dom L))).\n  apply EqObs_Pr with Gadv.\n  apply EqObs_sym.\n  apply equiv_weaken with (2:=EqObs_G3_G4).\n  intros k0 m1 m2 H; apply req_mem_weaken with (2:=H); vm_compute; trivial.\n  rewrite (Pr_range _ _ (range_G4 m)).\n  \n  rewrite EP_and.\n  apply Oeq_le.\n  rewrite (Pr_d_eq _ _ _ b); symmetry; rewrite (Pr_d_eq _ _ _ b).\n  apply EqObs_Pr with Gadv.\n  ep iE4E4; deadcode iE4E4; eqobs_in iE4E4.\n \n  rewrite H.\n  eapply Ole_trans.\n  apply (Pr_random_dom G4' (g^(x *! y)) qH i z L E4); \n   apply not_is_true_false; trivial.\n  apply EqObs_Pr with Gadv.\n  apply EqObs_sym.\n  sinline_r iE4E5 B; swap iE4E5; eqobs_in iE4E5.\n Qed.  \n\n Definition pi : PPT_info E5 :=\n  PPT_add_adv_infob EqAD_05 A'_PPT\n   (PPT_add_adv_infob EqAD_05 A_PPT\n    (PPT_add_info (PPT_empty_info E5) Hash)).\n   \n Lemma semantic_security : forall m,\n  negligible (fun k => [1/]1+pred (qH k) * Uabs_diff (Pr E0 G0 (m k) (EP k (b =?= b'))) [1/2]).\n Proof.\n  intro m.\n  apply negligible_le_stable with \n   (fun k => CDH_advantage x y z 4%positive E5 (m k)).\n  intro; apply security_bound.\n  apply CDH_assumption.\n  discriminate.\n  trivial.\n  trivial. \n  apply is_lossless_correct with (refl2_info iE4E5); vm_compute; trivial.\n  PPT_proc_tac pi.\n Qed.\n\nEnd ADVERSARY_AND_PROOF.\n", "meta": {"author": "EasyCrypt", "repo": "certicrypt", "sha": "7b3cd2fe4a317aec38dfff9eec902b265c575587", "save_path": "github-repos/coq/EasyCrypt-certicrypt", "path": "github-repos/coq/EasyCrypt-certicrypt/certicrypt-7b3cd2fe4a317aec38dfff9eec902b265c575587/Examples/HElGamal_ROM/HElGamal_CDH.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.2673862499715229}}
{"text": "Require Import\n        Coq.Strings.Ascii\n        Coq.Strings.String\n        Coq.Numbers.BinNums\n        Fiat.Common\n        Fiat.Computation.Notations\n        Fiat.BinEncoders.Env.Common.Specs\n        Fiat.BinEncoders.Env.Common.WordFacts.\n\nInductive ASN1_Simple : Set :=\n| ASN_Boolean : ASN1_Simple (* Universal 1 *)\n| ASN_Null : ASN1_Simple (* Universal 5 *)\n| ASN_Integer : ASN1_Simple (* Universal 2 *)\n| ASN_Enum : (* Universal 10 *)\n    list nat (* Codes *)\n    -> ASN1_Simple\n| ASN_BitString : ASN1_Simple (* Universal 3 *)\n| ASN_OctetString : ASN1_Simple (* Universal 4 *)\n| ASN_NumericString : ASN1_Simple (* Universal 18*)\n| ASN_PrintableString : ASN1_Simple (* Universal 19 *)\n| ASN_IA5String : ASN1_Simple. (* Universal 22 *)\n\nInductive ASN1_Simple_Modifier : Set :=\n| ASN_Size_Fixed : nat -> ASN1_Simple_Modifier\n| ASN_Size_Range : nat -> nat -> ASN1_Simple_Modifier\n| ASN_None : ASN1_Simple_Modifier.\n\nDefinition ASN1_Simple_denote (desc : ASN1_Simple) : Set :=\n  match desc with\n  | ASN_Boolean => bool\n  | ASN_Null => unit\n  | ASN_Integer => Z\n  | ASN_Enum n => Fin.t (length n)\n  | ASN_BitString => list bool\n  | ASN_OctetString => list (word 8)\n  | ASN_NumericString => string\n  | ASN_PrintableString => string\n  | ASN_IA5String => string\n  end.\n\nInductive ASN1_Structured : Set :=\n| ASN_Sequence : list ASN1_Sequence_Element -> ASN1_Structured\n| ASN_Choice : list ASN1_Type -> ASN1_Structured\n| ASN_Sequence_Of : ASN1_Type -> ASN1_Structured\n\nwith ASN1_Sequence_Element : Set :=\n     | Normal_Sequence_Element :\n         ASN1_Type -> ASN1_Sequence_Element\n     | Optional_Sequence_Element :\n         ASN1_Type -> ASN1_Sequence_Element\n     | Default_Sequence_Element :\n         forall (desc : ASN1_Simple),\n           ASN1_Simple_Modifier\n           -> ASN1_Simple_denote desc\n           -> ASN1_Sequence_Element\n\nwith ASN1_Type : Set :=\n     | ASN_Simple : ASN1_Simple -> ASN1_Simple_Modifier -> ASN1_Type\n     | ASN_Structured : ASN1_Structured -> ASN1_Type.\n\nCoercion ASN_Structured : ASN1_Structured >-> ASN1_Type.\n\nDefinition ASN_Simple_UnModified (desc : ASN1_Simple) : ASN1_Type :=\n  ASN_Simple desc ASN_None.\nCoercion ASN_Simple_UnModified : ASN1_Simple >-> ASN1_Type.\n\nFixpoint ASN1_Structured_denote (desc : ASN1_Structured) : Set :=\n  match desc with\n  | ASN_Sequence l =>\n    (fix ASN1_Sequence_denote (descs : list ASN1_Sequence_Element) {struct descs} : Set :=\n       match descs with\n       | Normal_Sequence_Element desc :: descs' =>\n         (ASN1_Type_denote desc) * (ASN1_Sequence_denote descs')\n       | Optional_Sequence_Element desc :: descs' =>\n         option (ASN1_Type_denote desc) * (ASN1_Sequence_denote descs')\n       | Default_Sequence_Element desc _ _ :: descs' =>\n         (ASN1_Simple_denote desc) * (ASN1_Sequence_denote descs')\n       | [ ] => unit\n       end)%type l\n  | ASN_Choice l =>\n    (fix ASN1_Choice_denote (descs : list ASN1_Type) {struct descs} : Set :=\n       match descs with\n       | desc :: descs' => (ASN1_Type_denote desc) + (ASN1_Choice_denote descs')\n       | [ ] => unit\n       end)%type l\n  | ASN_Sequence_Of desc' => list (ASN1_Type_denote desc')\n  end\n\nwith ASN1_Type_denote (desc : ASN1_Type) : Set :=\n       match desc with\n       | ASN_Simple desc' mod => ASN1_Simple_denote desc'\n       | ASN_Structured desc' => ASN1_Structured_denote desc'\n       end.\n\nSection ASN1_Format.\n\n  Require Import\n          Bedrock.Word.\n  \n  Require Import\n          Fiat.Common.EnumType\n          Fiat.BinEncoders.Env.Lib2.WordOpt\n          Fiat.BinEncoders.Env.Lib2.EnumOpt\n          Fiat.BinEncoders.Env.Lib2.Bool\n          Fiat.BinEncoders.Env.Lib2.NatOpt\n          Fiat.BinEncoders.Env.Lib2.FixStringOpt\n          Fiat.BinEncoders.Env.Common.ComposeOpt.\n  \n  Context {B : Type}.\n  Context {cache : Cache}.\n  Context {cacheAddNat : CacheAdd cache nat}.\n  Context {transformer : Transformer B}.\n  Context {transformerUnit : QueueTransformerOpt transformer bool}.\n\n  Import Coq.Vectors.VectorDef.VectorNotations.\n  \n  Definition Tag_Classes :=\n    [\"Universal\"; \"Application\"; \"Context-Specific\"; \"Private\"]%string.\n  \n  Definition Tag_Class_Codes :=\n    [WO~0~0; WO~0~1; WO~1~0; WO~1~1].\n\n  Definition Tag_Class := EnumType Tag_Classes.\n  \n  Definition ASN1_Format_Tag\n           (tag : Tag_Class)\n           (primitive : bool)\n           (identifier : nat)\n    : CacheEncode -> Comp (B * CacheEncode) :=\n          encode_enum_Spec Tag_Class_Codes tag\n    ThenC encode_word_Spec (WS primitive WO) \n    ThenC (If (NPeano.ltb identifier 31) Then\n              encode_nat_Spec 5 identifier\n              Else (encode_nat_Spec 31 identifier\n              ThenC (* TODO: Put actual high-tag formating rule here. *)\n              encode_nat_Spec 5 identifier))\n    DoneC. \n  \n  Definition ASN1_Format_Definite_Length\n             (length : nat)\n    : CacheEncode -> Comp (B * CacheEncode) :=\n    If (NPeano.ltb length 127) Then\n       encode_nat_Spec 8 length\n    Else\n       (encode_word_Spec WO~1 (* Set highest bit to 1 *)\n       ThenC encode_nat_Spec (S (NPeano.div (NPeano.log2 length) 8)) 7\n       ThenC encode_nat_Spec length (S (NPeano.div (NPeano.log2 length) 8) * 8))\n       DoneC.\n  \n  Fixpoint ASN1_Format_Simple_DER\n         (desc : ASN1_Simple)\n  : ASN1_Simple_denote desc -> CacheEncode -> Comp (B * CacheEncode) :=\n  match desc return\n        ASN1_Simple_denote desc\n        -> CacheEncode\n        -> Comp (B * CacheEncode) with\n  | ASN_Boolean =>\n    fun data =>\n      ASN1_Format_Tag Fin.F1 false 1\n    ThenC ASN1_Format_Definite_Length 1\n    ThenC encode_word_Spec (if data then natToWord 8 255 else natToWord 8 0)\n    DoneC\n\n  | ASN_Null =>\n    fun data =>\n      ASN1_Format_Tag Fin.F1 false 5\n    ThenC ASN1_Format_Definite_Length 0\n    DoneC\n    \n  | ASN_Integer => fun data => encode_word_Spec (natToWord 1 10) (* TODO *)\n  | ASN_Enum n => fun data => encode_word_Spec (natToWord 1 10) (* TODO *)\n  | ASN_BitString => fun data => encode_word_Spec (natToWord 1 10) (* TODO *)\n  | ASN_OctetString => fun data => encode_word_Spec (natToWord 1 10) (* TODO *)\n  | ASN_NumericString => fun data => encode_word_Spec (natToWord 1 10) (* TODO *)\n  | ASN_PrintableString => fun data => encode_word_Spec (natToWord 1 10) (* TODO *)\n  | ASN_IA5String =>\n    fun data => \n      ASN1_Format_Tag Fin.F1 false 22\n    ThenC ASN1_Format_Definite_Length (String.length data)\n    ThenC encode_string_Spec data                   \n    DoneC\n  end.\n\nEnd ASN1_Format.\n\nArguments ASN1_Format_Definite_Length _ _ / . (* Always simplify this format*)\nArguments ASN1_Format_Tag _ _ / . (* Always simplify this format*)\n\nSection ASN1_Decoder_Example.\n\n  Require Import\n          Fiat.BinEncoders.Env.Lib2.NoCache\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  \n  Instance ByteStringQueueTransformer : Transformer ByteString :=\n    ByteStringQueueTransformer.\n  \n  Example Simple_Format : ASN1_Simple :=\n    ASN_IA5String.\n\n  Ltac normalize_Compose Transformer :=\n    eapply SetoidMorphisms.refine_refineEquiv_Proper;\n    [ unfold flip;\n      repeat first\n             [ etransitivity; [ apply refineEquiv_compose_compose with (transformer := Transformer) | idtac ]\n             | etransitivity; [ apply refineEquiv_compose_Done with (transformer := Transformer) | idtac ]\n             | apply refineEquiv_under_compose with (transformer := Transformer) ];\n      intros; first [reflexivity | higher_order_reflexivity]\n    | reflexivity | ].\n  \n  Add Parametric Morphism\n      (E B : Type) (transformer : Transformer B)\n    : (@compose E B transformer)\n      with signature\n      (pointwise_relation _ (@refine (B * E)))\n        ==> (pointwise_relation _ (@refine (B * E)))\n        ==> (@eq E)\n        ==> (@refine (B * E))\n        as refine_compose.\n  Proof.\n    unfold pointwise_relation, compose, Bind2; intros.\n    setoid_rewrite H; setoid_rewrite H0; reflexivity.\n  Qed.\n\n  Lemma refine_compose_compose\n     : forall (E B : Type) (transformer : Transformer B) (encode1 encode2 encode3 : E -> Comp (B * E)) (ctx : E),\n      refine (((encode1 ThenC encode2) ThenC encode3) ctx) ((encode1 ThenC encode2 ThenC encode3) ctx).\n  Proof.\n    unfold pointwise_relation; intros.\n    apply refineEquiv_compose_compose.\n  Qed.\n\n  Lemma refine_ThenC_beta_reduce\n    : forall (E B : Type) (transformer : Transformer B) (encode1 encode2 : E -> Comp (B * E)) (ctx : E),\n      refine ((encode1 ThenC (fun ctx' => encode2 ctx')) ctx)\n             ((encode1 ThenC encode2) ctx).\n  Proof.\n    intros; reflexivity.\n  Qed.\n\n  Lemma refine_If_Then_Else_beta_reduce\n    : forall (E B : Type) (transformer : Transformer B) (encode1 encode2 : E -> Comp (B * E)) (ctx : E) b,\n      refine ((If b Then encode1 Else encode2) ctx)\n             (If b Then encode1 ctx Else encode2 ctx).\n  Proof.\n    intros; destruct b; reflexivity.\n  Qed.\n\n  Lemma refine_If_Then_Else_ThenC\n    : forall (E B : Type) (transformer : Transformer B) (encode1 encode2 encode3 : E -> Comp (B * E)) (ctx : E) b,\n      refine (((If b Then encode1 Else encode2) ThenC encode3) ctx)\n             (If b Then ((encode1 ThenC encode3) ctx) Else ((encode2 ThenC encode3) ctx)).\n  Proof.\n    intros; destruct b; reflexivity.\n  Qed.\n\n  Corollary AlignedEncodeNat\n            {numBytes}\n    : forall (n : nat) ce ce' (c : _ -> Comp _) (v : Vector.t _ numBytes),\n      refine (c (addE ce 8)) (ret (build_aligned_ByteString v, ce'))\n      -> refine (((encode_nat_Spec 8 (transformerUnit := ByteString_QueueTransformerOpt) n)\n                    ThenC c) ce)\n                (ret (build_aligned_ByteString (Vector.cons _ (natToWord 8 n) _ v), ce')).\n  Proof.\n    unfold encode_nat_Spec; cbv beta; intros.\n    rewrite <- AlignedEncodeChar; eauto.\n    reflexivity.\n  Qed.\n\n  Definition Variational_Vector\n             {numBytesT numBytesE}\n             (b : bool)\n             (vT : Vector.t Core.char numBytesT)\n             (vE : Vector.t Core.char numBytesE)\n    : Vector.t Core.char (If b Then numBytesT Else numBytesE) :=\n    match b return\n          Vector.t Core.char (If b Then numBytesT Else numBytesE)\n    with \n    | true => vT\n    | false => vE\n    end.\n      \n  Lemma AlignedEncode_If_Then_Else\n            {numBytesT numBytesE}\n    : forall (b : bool) ctx ctxT ctxE\n             (vT : Vector.t Core.char numBytesT)\n             (vE : Vector.t Core.char numBytesE)\n             (encode1 encode2 : CacheEncode -> Comp (_ * CacheEncode)),\n      (b = true\n       -> refine (encode1 ctx) (ret (build_aligned_ByteString vT, ctxT)))\n      -> (b = false\n          -> refine (encode2 ctx) (ret (build_aligned_ByteString vE, ctxE)))\n      -> refine (If b Then (encode1 ctx) Else (encode2 ctx))\n                (ret (build_aligned_ByteString (Variational_Vector b vT vE)\n                        \n                      , If b Then ctxT Else ctxE)).\n  Proof.\n    destruct b; simpl; intros; eauto.\n  Qed.\n\n  Lemma build_aligned_ByteString_id {B}\n    : forall ctx : B,\n      refine (ret (ByteString_id, ctx))\n             (ret (build_aligned_ByteString (Vector.nil _), ctx)).\n  Proof.\n    intros; replace ByteString_id\n             with (build_aligned_ByteString (Vector.nil _)).\n    reflexivity.\n    eapply ByteString_f_equal;\n      instantiate (1 := eq_refl _); reflexivity.\n  Qed.\n  \n  Definition Correct_simple_encoder\n    : { simple_encoder : _ &\n                         forall (t : ASN1_Simple_denote Simple_Format),\n                           NPeano.Nat.ltb (String.length t) 127 = true\n                           -> refine (ASN1_Format_Simple_DER Simple_Format t ())\n                     (ret (simple_encoder t)) }.\n  Proof.\n    simpl; eexists; intros.\n    unfold encode_nat_Spec at 1, encode_enum_Spec; simpl.\n    eapply SetoidMorphisms.refine_refineEquiv_Proper;\n      [ unfold flip;\n        repeat first\n               [ etransitivity; [ apply refineEquiv_compose_compose with (transformer := ByteStringQueueTransformer) | idtac ]\n               | etransitivity; [ apply refineEquiv_compose_Done with (transformer := ByteStringQueueTransformer) | idtac ]\n               | apply refineEquiv_under_compose with (transformer := ByteStringQueueTransformer) ];\n        intros; higher_order_reflexivity\n      | reflexivity | ];\n      rewrite refine_ThenC_beta_reduce.\n    rewrite (@CollapseEncodeWord _ test_cache); simpl; eauto.\n    rewrite !refine_ThenC_beta_reduce.\n    rewrite (@CollapseEncodeWord _ test_cache); simpl; eauto.\n    rewrite !refine_ThenC_beta_reduce.\n    eapply (@AlignedEncodeChar test_cache); eauto.\n    rewrite refine_If_Then_Else_ThenC.\n    eapply AlignedEncode_If_Then_Else; intros.\n    eapply (@AlignedEncodeNat _).\n    eapply (@encode_string_aligned_ByteString test_cache); eauto.\n    apply build_aligned_ByteString_id.\n    congruence.\n    Grab Existential Variables.\n    exact ().\n    apply Vector.nil.\n  Defined.\n\n  Arguments natToWord : simpl never.\n  \n  Definition byte_aligned_simple_encoder\n             (t :  ASN1_Simple_denote Simple_Format)\n    := Eval simpl in (projT1 Correct_simple_encoder t).\n\n  Print byte_aligned_simple_encoder.\n\nEnd ASN1_Decoder_Example.\n  \nSection ASN1_Example.\n  (* Suppose a company owns several sales outlets linked to a central *)\n  (* warehouse where stocks are maintained and deliveries start from. The *)\n  (* company requires that its protocol have the following features: *)\n  (* 1) the orders are collected locally at the sales outlets ; *)\n  (* 2) they are transmitted to the warehouse, where the delivery *)\n  (*    procedure should be managed ; *)\n  (* 3) an account of the delivery must be sent back to the sales outlets *)\n  (*    for following through the client's order. *)\n  (* Example taken from: http://www.itu.int/en/ITU-T/asn1/Pages/introduction.aspx. *)\n\n\n  (* Item-code ::= NumericString(SIZE (7)) *)\n  Definition ItemCode : ASN1_Type :=\n    ASN_Simple ASN_NumericString (ASN_Size_Fixed 7).\n\n  (* Label ::= PrintableString(SIZE (1..30)) *)\n  Definition Label : ASN1_Type :=\n    ASN_Simple ASN_PrintableString (ASN_Size_Range 1 30).\n\n  (* Quantity ::= CHOICE {\n   unites        INTEGER,\n   millimetres   INTEGER,\n   milligrammes  INTEGER\n} *)\n\n  Definition Quantity : ASN1_Type :=\n    ASN_Choice [ASN_Simple_UnModified ASN_Integer;\n                  ASN_Simple_UnModified ASN_Integer;\n                  ASN_Simple_UnModified ASN_Integer].\n\n  (* Cents ::= INTEGER *)\n  Definition Cents : ASN1_Type := ASN_Integer.\n\n  (* Order-number ::= NumericString(SIZE (12)) *)\n  Definition Order_Number : ASN1_Type :=\n    ASN_Simple ASN_NumericString (ASN_Size_Fixed 12).\n\n  (* Delivery-line ::= SEQUENCE {item      Item-code,\n                            quantity  Quantity *)\n  Definition Delivery_Line : ASN1_Type :=\n    ASN_Sequence [Normal_Sequence_Element ItemCode;\n                    Normal_Sequence_Element Quantity].\n\n  (*Delivery-report ::= SEQUENCE {\n  order-code  Order-number,\n  delivery    SEQUENCE OF Delivery-line\n} *)\n\n  Definition Delivery_Report : ASN1_Type :=\n    ASN_Sequence [Normal_Sequence_Element Order_Number;\n                    Normal_Sequence_Element (ASN_Structured (ASN_Sequence_Of Delivery_Line))].\n\n  (* Date ::= NumericString(SIZE (8)) -- MMDDYYYY *)\n  Definition Date : ASN1_Type  :=\n    ASN_Simple ASN_NumericString (ASN_Size_Fixed 8).\n\n  (* default-country PrintableString ::= \"France\" *)\n  Definition Default_Country : ASN1_Type_denote ASN_PrintableString := \"France\"%string.\n\n\n  (* Client ::= SEQUENCE {\n  name      PrintableString(SIZE (1..20)),\n  street    PrintableString(SIZE (1..50)) OPTIONAL,\n  postcode  NumericString(SIZE (5)),\n  town      PrintableString(SIZE (1..30)),\n  country   PrintableString(SIZE (1..20)) DEFAULT default-country\n  } *)\n  Definition Client : ASN1_Type :=\n    ASN_Sequence [Normal_Sequence_Element (ASN_Simple ASN_PrintableString (ASN_Size_Range 1 20));\n                    Optional_Sequence_Element (ASN_Simple ASN_PrintableString (ASN_Size_Range 1 50));\n                    Normal_Sequence_Element (ASN_Simple ASN_NumericString (ASN_Size_Fixed 5));\n                    Normal_Sequence_Element (ASN_Simple ASN_PrintableString (ASN_Size_Range 1 30));\n                    Default_Sequence_Element ASN_PrintableString (ASN_Size_Range 1 20) Default_Country].\n\n  (* Card-type ::= ENUMERATED {\n  cb(0), visa(1), eurocard(2), diners(3), american-express(4)} *)\n  Definition Card_Type : ASN1_Type :=\n    ASN_Enum [ 0; 1; 2; 3; 4].\n\n  (* Credit-card ::= SEQUENCE {\n  type         Card-type,\n  number       NumericString(SIZE (20)),\n  expiry-date  NumericString(SIZE (6))-- MMYYYY --\n  }*)\n  Definition Credit_Card : ASN1_Type :=\n    ASN_Sequence [Normal_Sequence_Element Card_Type;\n                    Normal_Sequence_Element (ASN_Simple ASN_NumericString (ASN_Size_Fixed 20));\n                    Normal_Sequence_Element (ASN_Simple ASN_NumericString (ASN_Size_Fixed 6))\n                 ].\n\n  (* Payment-method ::= CHOICE {\n  check        NumericString(SIZE (15)),\n  credit-card Credit-card,\n  cash         NULL\n} *)\n  Definition Payment_Method : ASN1_Type :=\n    ASN_Choice [ASN_Simple ASN_NumericString (ASN_Size_Fixed 8);\n                  Credit_Card;\n                  ASN_Simple ASN_Null ASN_None].\n\n  (* Order-header ::= SEQUENCE {\n  number   Order-number,\n  date     Date,\n  client   Client,\n  payment  Payment-method\n} *)\n  Definition Order_Header : ASN1_Type :=\n    ASN_Sequence [Normal_Sequence_Element Order_Number;\n                    Normal_Sequence_Element Date;\n                    Normal_Sequence_Element Client;\n                    Normal_Sequence_Element Payment_Method].\n\n  (* Item-code ::= NumericString(SIZE (7)) *)\n  Definition Item_Code : ASN1_Type  :=\n    ASN_Simple ASN_NumericString (ASN_Size_Fixed 7).\n\n  (* Order-line ::= SEQUENCE {\n  item-code  Item-code,\n  label      Label,\n  quantity   Quantity,\n  price      Cents\n} *)\n  Definition Order_Line : ASN1_Type :=\n    ASN_Sequence [Normal_Sequence_Element Item_Code;\n                    Normal_Sequence_Element Label;\n                    Normal_Sequence_Element Quantity;\n                    Normal_Sequence_Element Cents].\n\n\n  (* Order ::= SEQUENCE {header  Order-header,\n                    items   SEQUENCE OF Order-line\n} *)\n  Definition Order : ASN1_Type :=\n    ASN_Sequence [Normal_Sequence_Element Order_Header;\n                    Normal_Sequence_Element (ASN_Sequence_Of Order_Line)].\n\n  (*\nPDU ::= CHOICE {\n  question\n    CHOICE {question1  Order,\n            question2  Item-code,\n            question3  Order-number,\n            ...},\n  answer\n    CHOICE {answer1  Delivery-report,\n            answer2  Quantity,\n            answer3  Delivery-report,\n            ...}\n} *)\n\n  Definition PDU : ASN1_Type :=\n    ASN_Choice [ASN_Structured (ASN_Choice [Order; Item_Code; Order_Number]);\n                  ASN_Structured (ASN_Choice [Delivery_Report; Quantity; Delivery_Report])\n               ].\n\nEnd ASN1_Example.\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/Lib2/ASN1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.26738624262408534}}
{"text": "From cap_machine Require Export rules_StoreU 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 iFailStep_alt fail_type :=\n    iMod (exprspec_mapsto_update _ _ (fill _ (Instr Failed)) with \"Hown Hj\") as \"[Hown Hj]\";\n    iMod (\"Hclose\" with \"[Hown]\") as \"_\";\n    [iNext;iExists _,_;iFrame;iPureIntro;eapply rtc_r;eauto;prim_step_from_exec|];\n    try (iExists (FailedV),_,_; iFrame;iModIntro;iFailCore fail_type).\n\n  Lemma step_storeU Ep K\n     pc_p pc_g pc_b pc_e pc_a\n     rdst rsrc offs w wsrc mem regs :\n   decodeInstrW w = StoreU rdst offs rsrc →\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 (StoreU rdst offs rsrc) ⊆ dom _ regs →\n   mem !! pc_a = Some w →\n   word_of_argument regs rsrc = Some wsrc ->\n   match regs !! rdst with\n   | None => True\n   | Some (inl _) => True\n   | Some (inr (p, g, b, e, a)) =>\n     match z_of_argument regs offs with\n       | None => True\n       | Some zoffs => match verify_access (StoreU_access b e a zoffs) with\n                      | None => True\n                      | Some a' => if isU p && canStoreU p a' wsrc then\n                                    match mem !! a' with\n                                    | None => False\n                                    | Some w => True\n                                    end\n                                  else True\n                      end\n       end\n   end ->\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' mem', ⤇ fill K (of_val retv) ∗ ⌜ StoreU_spec regs rdst offs rsrc regs' mem mem' retv ⌝ ∗ ([∗ map] a↦w ∈ mem', a ↣ₐ w)∗ ([∗ map] k↦y ∈ regs', k ↣ᵣ y).\n  Proof.\n    iIntros (Hinstr Hvpc HPC Dregs Hmem_pc Hwsrc HaStore 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 rdst) as [rdstv [Hrdst' Hrdst'']]. by set_solver+.\n    pose proof (regs_lookup_eq _ _ _ Hrdst') as Hrdst'''.\n    (* Derive the PC in memory *)\n    iDestruct (memspec_heap_valid_inSepM _ _ _ _ pc_a with \"Hown Hmem\") as %Hma; eauto.\n    specialize (normal_always_step (σr,σm)) as [c [ σ2 Hstep]].\n    eapply step_exec_inv in Hstep; eauto.\n\n    simpl in Hrdst'', Hma. option_locate_mr σm σr.\n    assert (Hstep':=Hstep). rewrite /exec /reg in Hstep.\n    assert ((σr, σm).1 = σr) as Heq;auto. rewrite Heq in Hstep. clear Heq.\n    rewrite Hσrrdst in Hstep.\n\n    destruct rdstv as [zdst| [[[[p g] b] e] a] ].\n    { inv Hstep. iFailStep_alt StoreU_fail_const. }\n\n     (* destruct (isU p) eqn:HisU; cycle 1. *)\n     (* { simpl in Hstep. inv Hstep. iFailWP \"Hφ\" StoreU_fail_perm1. } *)\n\n     assert (Hwsrc': match rsrc with\n                     | inl n => inl n\n                     | inr rsrc =>\n                       match reg (σr, σm) !! rsrc with\n                       | Some w => w\n                       | None => inl 0%Z\n                       end\n                     end = wsrc).\n     { destruct rsrc; simpl in Hwsrc; inv Hwsrc; auto.\n       simpl. feed destruct (Hri r) as [aa [HA HB]]. by set_solver+.\n       rewrite HB; congruence. }\n     rewrite Hwsrc' in Hstep.\n\n     (* destruct (canStoreU p a wsrc) eqn:HcanStoreU; cycle 1. *)\n     (* { simpl in Hstep. inversion Hstep. *)\n     (*   iFailWP \"Hφ\" StoreU_fail_perm2. } *)\n\n     assert (Hzofargeq: z_of_argument σr offs = z_of_argument regs offs).\n     { rewrite /z_of_argument; destruct offs; auto.\n       feed destruct (Hri r) as [? [?]]. by set_solver+.\n       rewrite H4 H5; auto. }\n     rewrite Hzofargeq in Hstep.\n\n     Local Opaque verify_access.\n     Local Opaque exec.\n     simpl in Hstep. destruct (z_of_argument regs offs) as [zoffs|] eqn:Hoffs; cycle 1.\n     { inv Hstep. iFailStep_alt StoreU_fail_offs_arg. }\n\n     destruct (verify_access (StoreU_access b e a zoffs)) as [a'|] eqn:Hverify; cycle 1.\n     { inv Hstep. iFailStep_alt StoreU_fail_verify_access. }\n\n     destruct (isU p) eqn:HisU; cycle 1.\n     { simpl in Hstep. inv Hstep. iFailStep_alt StoreU_fail_perm1. }\n\n     destruct (canStoreU p a' wsrc) eqn:HcanStoreU; cycle 1.\n     { simpl in Hstep. inv Hstep. iFailStep_alt StoreU_fail_perm2. }\n\n     rewrite Hrdst' HisU Hverify HcanStoreU /= in HaStore.\n     destruct (mem !! a') as [wa|]eqn:Ha; try (inv HaStore; fail).\n\n     destruct (addr_eq_dec a a').\n     { subst a'. destruct (a + 1)%a as [a'|] eqn:Hap1; cycle 1.\n       { inv Hstep. iFailStep_alt StoreU_fail_incrPC1. }\n\n       iMod ((memspec_heap_update_inSepM _ _ _ a) with \"Hown Hmem\") as \"[Hown Hmem]\"; eauto.\n\n       destruct (incrementPC (<[rdst:=inr (p, g, b, e, a')]> regs)) eqn:Hincr; cycle 1.\n       { assert _ as Hincr' by (eapply (incrementPC_overflow_mono (<[rdst:=_]> regs) (<[rdst:=_]> σr) Hincr _ _)).\n         rewrite incrementPC_fail_updatePC in Hstep; eauto.\n         inv Hstep. simpl.\n         iMod (exprspec_mapsto_update _ _ (fill K (Instr Failed)) with \"Hown Hj\") as \"[Hown Hj]\".\n         iMod ((regspec_heap_update_inSepM _ _ _ rdst) with \"Hown Hmap\") as \"[Hown Hmap]\"; eauto.\n         iFailStep_alt StoreU_fail_incrPC2. }\n\n       destruct (incrementPC_success_updatePC _ σm _ Hincr) 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       instantiate (1 := <[a:=wsrc]> σm) in HuPC.\n       rewrite HuPC in Hstep. inversion Hstep; clear Hstep; subst c σ2. cbn.\n       iMod (exprspec_mapsto_update _ _ (fill K (Instr NextI)) with \"Hown Hj\") as \"[Hown Hj]\".\n       iMod ((regspec_heap_update_inSepM _ _ _ rdst) with \"Hown Hmap\") as \"[Hown Hmap]\"; eauto.\n       iMod ((regspec_heap_update_inSepM _ _ _ PC) with \"Hown Hmap\") as \"[Hown Hmap]\"; eauto.\n       rewrite <- Hwsrc'. iExists (NextIV),_,_. iFrame.\n       iMod (\"Hclose\" with \"[Hown]\") as \"_\".\n       { iNext. iExists _,_;iFrame. iPureIntro. eapply rtc_r;eauto.\n         apply verify_access_spec in Hverify as (? & ? & ? & ?). simpl. rewrite Hwsrc'.\n         prim_step_from_exec. }\n       iModIntro. iPureIntro. apply verify_access_spec in Hverify as (? & ? & ? & ?). econstructor; eauto.\n       - repeat split;eauto.\n       - rewrite Hwsrc'. auto.\n       - destruct (addr_eq_dec a a); try congruence.\n         rewrite Hap1. auto. }\n\n     iMod ((memspec_heap_update_inSepM _ _ _ a') with \"Hown Hmem\") as \"[Hown Hmem]\"; eauto.\n\n     destruct (incrementPC regs) eqn:Hincr; cycle 1.\n     { assert _ as Hincr' by (eapply (incrementPC_overflow_mono regs σr Hincr _ _)).\n       rewrite incrementPC_fail_updatePC in Hstep; eauto.\n       inv Hstep. simpl.\n       iFailStep_alt StoreU_fail_incrPC3. }\n\n     destruct (incrementPC_success_updatePC regs (<[a':=wsrc]> σm) _ Hincr) as (p1 & g1 & b1 & e1 & a1 & a_pc1 & HPC'' & Ha_pc' & HuPC & -> & ?).\n     eapply updatePC_success_incl in HuPC; eauto.\n     instantiate (1 := <[a':=wsrc]> σm) in HuPC.\n     rewrite HuPC in Hstep.\n     inversion Hstep; clear Hstep; subst c σ2. cbn.\n     iMod ((regspec_heap_update_inSepM _ _ _ PC) with \"Hown Hmap\") as \"[Hown Hmap]\"; eauto.\n     iMod (exprspec_mapsto_update _ _ (fill K (Instr NextI)) with \"Hown Hj\") as \"[Hown Hj]\".\n     rewrite <- Hwsrc'. iExists (NextIV),_,_. iFrame.\n     iMod (\"Hclose\" with \"[Hown]\") as \"_\".\n     { iNext. iExists _,_;iFrame. iPureIntro. eapply rtc_r;eauto.\n       apply verify_access_spec in Hverify as (? & ? & ? & ?). simpl. rewrite Hwsrc'.\n       prim_step_from_exec. }\n     iPureIntro. apply verify_access_spec in Hverify as (? & ? & ? & ?). econstructor; eauto.\n     { repeat split;eauto. }\n     { rewrite Hwsrc'. reflexivity. }\n     { destruct (addr_eq_dec a a'); try congruence; auto. }\n\n     Unshelve. all: eauto.\n     { destruct (reg_eq_dec PC rdst).\n       - subst rdst. rewrite lookup_insert. eauto.\n       - rewrite lookup_insert_ne; eauto. }\n     { eapply insert_mono; eauto. }\n   Qed.\n\n\n  Lemma step_storeU_alt Ep K\n     pc_p pc_g pc_b pc_e pc_a\n     rdst rsrc offs w mem regs :\n   decodeInstrW w = StoreU rdst offs rsrc →\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 (StoreU rdst offs rsrc) ⊆ dom _ regs →\n   mem !! pc_a = Some w →\n   allow_storeU_map_or_true rdst rsrc offs 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' mem', ⤇ fill K (of_val retv) ∗ ⌜ StoreU_spec regs rdst offs rsrc regs' mem mem' retv ⌝ ∗ ([∗ map] a↦w ∈ mem', a ↣ₐ w)∗ ([∗ map] k↦y ∈ regs', k ↣ᵣ y).\n  Proof.\n    iIntros (Hinstr Hvpc HPC Dregs Hmem_pc HaStore Hnclose) \"(#Hinv & Hj & >Hmem & >Hmap)\".\n    apply allow_storeU_map_or_true_match in HaStore as (wsrc & Hwsrc & HaStore).\n    iApply (step_storeU with \"[$Hmem $Hmap $Hj]\");eauto.\n  Qed.\n\nEnd cap_lang_spec_rules.\n\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_StoreU.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.4148988457967689, "lm_q1q2_score": 0.2672882531144953}}
{"text": "Require Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.ContextFreeGrammar.PreNotations.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Fix.FromAbstractInterpretationDefinitions.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Fix.Fix.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Fix.FromAbstractInterpretation.\n\nModule DataflowInput.\n  Section input_data.\n    Context {Char : Type}.\n\n    Record t :=\n      { T : Type;\n        fpdata : grammar_fixedpoint_lattice_data T;\n        aidata : AbstractInterpretation (Char:=Char) }.\n  End input_data.\n  Global Arguments t : clear implicits.\nEnd DataflowInput.\n\nModule DataflowOutput.\n  Definition t {Char} d G\n    := @fold_grammar_data Char (DataflowInput.T d) (DataflowInput.fpdata d) (DataflowInput.aidata d) G.\n\n  Section output_data.\n    Context {Char : Type}\n            {d : DataflowInput.t Char}\n            {G : pregrammar' Char}\n            (v : t d G).\n\n    Definition t_data := Eval hnf in @fgd_fold_grammar _ _ _ _ _ v.\n    Definition t_correct : Morphisms.pointwise_relation _ eq (lookup_state t_data) (lookup_state (fold_grammar G _))\n      := fgd_fold_grammar_correct.\n  End output_data.\n  Coercion t_data : t >-> aggregate_state.\nEnd DataflowOutput.\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/PreInterface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.4148988457967689, "lm_q1q2_score": 0.2672882531144953}}
{"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 ssrfun 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_seplog C_pp.\n\nLocal Open Scope C_types_scope.\nLocal Open Scope string_scope.\n\nModule pointer_test.\n\nModule C_Env <: CENV.\nDefinition g := \\wfctxt{ \\O \\}.\nDefinition sigma : g.-env := (\"i\", ityp: uint) :: (\"p\" , :* (ityp: uint)) :: \n  (\"q\" , :* (ityp: uchar)) :: nil. \nDefinition uniq_vars : uniq (unzip1 sigma) := Logic.eq_refl.\nEnd C_Env.\n\nModule Import C_m := C_Seplog_f C_Env.\nLocal Open Scope C_cmd_scope.\n\nCheck (\"i\" <-* %\"p\").\n\nEnd pointer_test.\n\nModule struct_test.\n\nDefinition tg := mkTag \"a\".\nDefinition flds : Ctxt.v :=\n  (\"f\", ityp uchar) :: (\"g\", ityp ulong) :: (\"h\", ptyp (ptyp (styp tg))) :: nil.\nDefinition g := \\wfctxt{ \"a\" |> flds \\, \\O \\}.\nDefinition a := g.-typ: styp tg.\nDefinition an_array_type := g.-typ: atyp 42 Logic.eq_refl tg.\n\nEval compute in (sizeof a).\nEval compute in (sizeof an_array_type).\n\nDefinition sigma : g.-env := @get_fields g tg.\nEval compute in (field_address 0 \"f\" (ityp: uchar) sigma Logic.eq_refl).\nEval compute in (field_address 0 \"g\" (ityp: ulong) sigma Logic.eq_refl).\nEval compute in (field_address 0 \"h\" (:* (:* (g.-typ: styp tg))) sigma Logic.eq_refl).\n\n(* *)\n\nEnd struct_test.\n\nModule array_in_struct.\n\nDefinition tg := mkTag \"a\".\nDefinition bad_flds := (\"f\", atyp 5 (refl_equal _) tg) :: nil.\n(*Definition g := \\wfctxt \\{ \"a\" |> bad_flds \\, \\O \\}.*)\n\nDefinition boxed_int_tg := mkTag \"bint\".\nDefinition boxed_int_fld := (\"bint_\", ityp sint) :: nil.\nDefinition flds := (\"f\", atyp 5 Logic.eq_refl boxed_int_tg) :: nil.\nDefinition g := \\wfctxt{ \"a\" |> flds \\, \"bint\" |> boxed_int_fld \\, \\O \\}.\nDefinition astruct := g.-typ: styp tg.\n\nEval compute in (sizeof astruct).\n\nEnd array_in_struct.\n\nModule two_self_referential_structs.\n\n(**\n\nexample p.151 from \"C A Reference Manual\" 5th Edition, Samuel P. Harbison III, Guy L. Steele Jr. 2002\n\n{ struct cell ;\n  struct header { struct cell   *first; ...};\n  struct cell   { struct header *head;  ...};\n}\n\n*)\n\nDefinition cell_tg := mkTag \"cell\".\nDefinition header_tg := mkTag \"header\".\nDefinition cell_flds := (\"data\", ityp uchar) :: (\"head\", ptyp (styp header_tg)) :: nil.\nDefinition header_flds := (\"first\", ptyp (styp cell_tg)) :: nil.\nDefinition g := \\wfctxt{ \"cell\" |> cell_flds \\, \"header\" |> header_flds \\, \\O \\}.\n(* NB: \\wfctxt will fail without pointers *)\nDefinition cell := g.-typ: styp cell_tg.\nDefinition header := g.-typ: styp header_tg.\n\nTime Eval compute in sizeof cell.\nTime Eval compute in sizeof header.\n\nGoal (sizeof cell = 1 + 3 + 4)%nat. by []. Qed.\nGoal (sizeof header = 4)%nat. by []. Qed.\n\nEval compute in (typ_to_string (styp cell_tg) \"\" \"\").\nEval compute in (typ_to_string_rec g cell \"\" \"\").\n\nEnd two_self_referential_structs.\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_examples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.2671908600156701}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import Core.Core Core.Notations Core.Tactics.\nRequire Import Exec.Ber_tlv_tag_serialize\n        Exec.Ber_tlv_length_serialize.\n\nOpen Scope Z.\n\nDefinition der_write_TL tag len size constructed := \n  let (tl, t) := tag_serialize tag (Int.repr size) in\n  let (ll, l) := length_serialize len (Int.repr (if eq_dec size 0 then size else size - t)) in\n  let ls := if eq_dec constructed 0%int \n            then tl ++ ll \n            else (upd_Znth 0 tl (Znth 0 tl or (Int.repr 32))%int) ++ ll in\n  if ((t =? -1) || (32 <? t))%bool \n  then ([], -1)\n  else if l =? -1 \n       then ([], -1) \n       else let s := l + t in\n            if 32 <? s \n            then ([], -1)\n            else (ls, s).\n\nLemma tag_serialize_bounds : forall t l, -1 <= snd (tag_serialize t l) <= 6.\n  { unfold tag_serialize.\n    intros.\n    cbn.\n    repeat break_if; autorewrite with norm; try nia. } \nQed.\n\nLemma length_serialize_bounds : \n  forall t l, -1 <= snd (length_serialize t l) <= 6.\n  { unfold length_serialize.\n    intros.\n    cbn.\n    repeat break_if; autorewrite with norm; try nia. } \nQed.\n\nLemma der_write_TL_serialize_sum : \n  forall t l s c, \n    let (tls, tl) := tag_serialize t (Int.repr s)  in\n    let (lls, ll) := length_serialize l (Int.repr (if eq_dec s 0 then s else s - tl)) in\n    tl <> -1 ->\n    ll <> -1 ->\n    tl <= 32 ->\n    tl + ll <= 32 ->\n    c = 0%int ->\n    der_write_TL t l s c = (tls ++ lls, tl + ll).\nProof.\n  intros.\n  repeat break_let.\n  unfold der_write_TL.\n  intros Z Z0 Z32 Zplus C.\n  erewrite Heqp.\n  erewrite Heqp0.\n  repeat break_if; try destruct_orb_hyp;\n  repeat Zbool_to_Prop; try nia.\n  intuition.\n  intuition.\n  congruence.\n  congruence.\nQed.\n\nLemma der_write_TL_serialize_sum_c : \n  forall t l s c, \n     let (tls, tl) := tag_serialize t (Int.repr s)  in\n    let (lls, ll) := length_serialize l (Int.repr (if eq_dec s 0 then s else s - tl)) in\n    tl <> -1 ->\n    ll <> -1 ->\n    tl <= 32 ->\n    tl + ll <= 32 ->\n    c <> 0%int ->\n    der_write_TL t l s c = ((upd_Znth 0 tls (Znth 0 tls or (Int.repr 32))%int) ++ lls, tl + ll).\nProof.\n  intros.\n  repeat break_let.\n  unfold der_write_TL.\n  intros Z Z0 Z32 Zplus C.\n  erewrite Heqp.\n  erewrite Heqp0.\n  repeat break_if; try destruct_orb_hyp;\n  repeat Zbool_to_Prop; try rep_omega;\n  try erewrite e in C;\n  try congruence;\n  intuition.\nQed.\n\nDefinition Z_of_val v := \n  match v with\n  | Vptr b i => Ptrofs.unsigned i \n  | _ => 0\n  end.\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/Exec/Der_write_TL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.26714158154106915}}
{"text": "Require Import FP.Classes.\nRequire Import FP.CoreClasses.\nRequire Import FP.DerivingMonad.Core.\n\nClass DM_IdxFunctorI (T:Type -> Type -> Type) (U:Type -> Type -> Type) :=\n  { DM_Idx_T_F_Eqv :> forall {I} `{! Eqv I }, F_Eqv (T I)\n  ; DM_Idx_T_F_PER_WF :> forall {I} `{! Eqv I ,! PER_WF I }, F_PER_WF (T I)\n  ; DM_Idx_U_F_Eqv :> forall {I} `{! Eqv I }, F_Eqv (U I)\n  ; DM_Idx_U_F_PER_WF :> forall {I} `{! Eqv I ,! PER_WF I }, F_PER_WF (U I)\n  ; DM_Idx_U_Monad :> forall {I}, Monad (U I)\n  ; DM_Idx_U_MonadWF :> forall {I} `{! Eqv I ,! PER_WF I }, MonadWF (U I)\n  }.\n\nClass DM_IdxFunctorI' T U := { dm_idx_functor_i : DM_IdxFunctorI T U }.\n\nModule Type DM_IdxFunctor_Arg.\n  Local Existing Instance dm_idx_functor_i.\n\n  Parameter T : Type -> Type -> Type.\n  Parameter U : Type -> Type -> Type.\n  Parameter to : forall {I A}, T I A -> U I A.\n  Parameter from : forall {I A}, U I A -> T I A.\n  Parameter _DM_IdxFunctorI : DM_IdxFunctorI' T U.\n  Parameter IR_from_eqv :\n    forall {I A} `{! Eqv I ,! PER_WF I ,! Eqv A ,! PER_WF A },\n    InjectionRespect (U I A) (T I A) from eqv eqv.\n  Parameter II_to_from_eqv :\n    forall {I A} `{! Eqv I ,! PER_WF I ,! Eqv A ,! PER_WF A },\n    InjectionInverse (T I A) (U I A) to from eqv.\n  Parameter II_from_from_eqv :\n    forall {I A} `{! Eqv I ,! PER_WF I ,! Eqv A ,! PER_WF A },\n    InjectionInverse (U I A) (T I A) from to eqv.\n  Parameter Proper_to_eqv :\n    forall {I A} `{! Eqv I ,! PER_WF I ,! Eqv A ,! PER_WF A },\n    Proper eqv (@to I A).\n  Parameter Proper_from_eqv :\n    forall {I A} `{! Eqv I ,! PER_WF I ,! Eqv A ,! PER_WF A },\n    Proper eqv (@from I A).\nEnd DM_IdxFunctor_Arg.\n\nModule DM_IdxFunctor (M:DM_IdxFunctor_Arg).\n  Local Existing Instance dm_idx_functor_i.\n\n  Import M.\n  Arguments T / _ _ .\n  Arguments U / _ _ .\n  Arguments to {I A} / _ .\n  Arguments from {I A} / _ .\n\n  Section I.\n    Context {I:Type}.\n\n    Section Monad.\n      Global Instance _Monad : Monad (T I) := Deriving_Monad_Bijection (@to I) (@from I).\n\n      Context `{! Eqv I ,! PER_WF I }.\n\n      Global Instance _MonadWF : MonadWF (T I) := Deriving_MonadWF_Bijection (@to I) (@from I).\n    End Monad.\n\n    Section Applicative.\n      Global Instance _Applicative : Applicative (T I) := Deriving_Applicative_Monad.\n\n      Context `{! Eqv I ,! PER_WF I }.\n\n      Global Instance _ApplicativeWF : ApplicativeWF (T I).\n      Proof.\n        apply Deriving_ApplicativeWF_MonadWF ; intros.\n        - unfold fret ; simpl ; logical_eqv.\n        - unfold fapply ; simpl ; logical_eqv.\n      Qed.\n    End Applicative.\n\n    Section Functor.\n      Global Instance _Functor : Functor (T I) := Deriving_Functor_Applicative.\n\n      Context `{! Eqv I ,! PER_WF I }.\n\n      Global Instance _FunctorWF : FunctorWF (T I).\n      Proof.\n        apply Deriving_FunctorWF_ApplicativeWF ; intros.\n        unfold fmap ; simpl ; logical_eqv.\n      Qed.\n    End Functor.\n\n    Section Pointed.\n      Global Instance _Pointed : Pointed (T I) := Deriving_Pointed_Applicative.\n\n      Context `{! Eqv I ,! PER_WF I }.\n\n      Global Instance _PointedWF : PointedWF (T I).\n      Proof.\n        apply Deriving_PointedWF_ApplicativeWF ; intros.\n        unfold point ; simpl ; logical_eqv.\n      Qed.\n    End Pointed.\n\n  End I.\nEnd DM_IdxFunctor.\n\nClass DMError_IdxFunctorI\n    (T:Type -> Type -> Type) (U:Type -> Type -> Type)\n    `{! forall {I} `{! Eqv I }, F_Eqv (U I)\n     ,! forall {I} `{! Eqv I ,! PER_WF I }, F_PER_WF (U I)\n     ,! forall {I}, Monad (U I)\n     } :=\n  { DMError_Idx_U_MonadCatch : forall {I}, MonadCatch I (U I)\n  ; DMError_Idx_U_MonadCatchWF : forall {I} `{! Eqv I ,! PER_WF I}, MonadCatchWF I (U I)\n  }.\n\nModule Type DMError_IdxFunctor_Arg.\n  Local Existing Instance dm_idx_functor_i.\n\n  Include DM_IdxFunctor_Arg.\n  Parameter _DMError_IdxFunctorI : DMError_IdxFunctorI T U.\nEnd DMError_IdxFunctor_Arg.\n\nModule DMError_IdxFunctor (M:DMError_IdxFunctor_Arg).\n  Local Existing Instance dm_idx_functor_i.\n  Local Existing Instance DMError_Idx_U_MonadCatch.\n  Local Existing Instance DMError_Idx_U_MonadCatchWF.\n\n  Import M.\n  Module DM := DM_IdxFunctor M.\n  Import DM.\n\n  Arguments T / _ _ .\n  Arguments U / _ _ .\n  Arguments to {I A} / _ .\n  Arguments from {I A} / _ .\n\n  Section MonadError.\n    Context {I:Type} `{! Eqv I ,! PER_WF I }.\n\n    Global Instance _MonadCatch : MonadCatch I (T I) := deriving_MonadCatch_Bijection (@to I) (@from I).\n    Global Instance _MonadCatchWF : MonadCatchWF I (T I).\n    Proof.\n      apply (deriving_MonadCatchWF_Bijection (@to I) (@from I)) ; intros.\n      - unfold mret at 1 ; simpl ; logical_eqv.\n      - unfold mbind at 1 ; simpl ; logical_eqv.\n    Qed.\n  End MonadError.\nEnd DMError_IdxFunctor.", "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/DerivingMonad/IdxFunctor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.26714158154106915}}
{"text": "Require Export SystemFR.StrictPositivity.\nRequire Export SystemFR.StrictPositivityLemmas.\nRequire Export SystemFR.Trees.\nRequire Export SystemFR.Syntax.\nRequire Export SystemFR.Tactics.\nRequire Export SystemFR.SizeLemmas.\nRequire Export SystemFR.NoTypeFVar.\n\nRequire Export SystemFR.SubstitutionLemmas.\nRequire Export SystemFR.ErasedTermLemmas.\nRequire Export SystemFR.FVLemmas.\nRequire Export SystemFR.FVLemmasLists.\n\n\n\nRequire Export SystemFR.AssocList.\n\nRequire Import Coq.Lists.List.\n\nRequire Import Psatz.\n\nOpaque strictly_positive.\n\nLemma strictly_positive_subst_aux:\n  forall n T lterms vars,\n    type_nodes T < n ->\n    pclosed_mapping lterms type_var ->\n    twfs lterms 0 ->\n    is_erased_type T ->\n    strictly_positive T vars ->\n    strictly_positive (psubstitute T lterms term_var) vars.\nProof.\n  induction n; destruct T; repeat step || destruct_tag || simp_spos; try lia;\n    eauto using no_type_fvar_subst;\n    eauto with lia.\n  right; exists X; steps; eauto using pfv_in_subst.\n  rewrite substitute_topen2; steps.\n  apply_any; repeat step || autorewrite with bsize in * || apply is_erased_type_topen;\n    eauto with lia.\nQed.\n\nLemma strictly_positive_subst:\n  forall T lterms vars,\n    pclosed_mapping lterms type_var ->\n    twfs lterms 0 ->\n    is_erased_type T ->\n    strictly_positive T vars ->\n    strictly_positive (psubstitute T lterms term_var) vars.\nProof.\n  eauto using strictly_positive_subst_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/StrictPositivitySubst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2671301378051835}}
{"text": "Require Export assetmapping_spl_int.\nRequire Export maps_proofs.\nRequire Export maps_inst.\nRequire Export maps_int.\nRequire Export maps_def.\nRequire Export assetmapping_spl_def.\nRequire Import Coq.Lists.ListSet.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Init.Specif.\nRequire Export Coq.Lists.List.\nImport Maps.\nImport AssetMappingSPL.  \n\n\nProgram Instance Ins_AssetMapping: AssetMapping Asset AssetName AM :=\n{\n  assetRef      := assetRef_func;\n  wfProduct     := wfProduct_ind;\n  aMR           := aMR_func;\n  my_set_union  := my_set_union_func;\n}.\nNext Obligation.\n  {(*assetRefinementReflexivity*)\n   apply assetRefinementReflexivity_axiom.\n} Qed.\nNext Obligation.\n { (*assetRefinementTranstivity*)\n  generalize H H0. apply assetRefinementTranstivity_axiom.\n} Qed.\nNext Obligation.\n { (*asRefCompositional*)\nassert (H3: assetRef_func S1 S2 /\\ wfProduct_ind (my_set_union_func S1 aSet)).\n split.\n + apply H.\n + apply H0.\n + generalize H3.\n  apply asRefCompositional_axiom.\n} Qed.\nNext Obligation. { (*assetMappingRefinement*)\n  generalize H0. apply assetMappingRefinement_axiom. split.\n    + apply H. \n    + apply H1.\n} Qed.\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/Instances/assetmapping_spl_inst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.4035668537353745, "lm_q1q2_score": 0.26713013242225303}}
{"text": "(*-----------------------------------------------------*)\n(* semantics_CDLPattern_V1_0.v   *)\n(* Author : Housseim Hachmaoui, Philippe Dhaussy *)\n(* ENSTA Bretagne, Lab-STICC / MOCS *)\n(* philippe.dhaussy@ensta-bretagne.fr *)\n(* May 2015 *)\n(*-----------------------------------------------------*)\n\n\n\nRequire Import List EqNat.\nExport ListNotations.\n\n(*###########*)\n(*# Horloge #*)\n(*###########*)\n\n(* Nous definissons l'horloge comme parametre car celle-ci est geree \npar le systeme *)\n\nParameter clock:nat.\n\n(* Types des operations a effectuer sur l'horloge *)\nInductive opHorloge : Type :=\n|NoOp (* Rien *)\n|ReInit (* Reinitialisation de l'horloge *)\n.\n(* Nous attribuons cette notation a la reinitialisation de l'horloge *)\nNotation \"clock:=-1\" := ReInit.\n\n(* Posons ce type pour les conditions relatives a l'horloge *)\nInductive condHorloge : Type :=\n|NoCond (* Absence de condition *)\n|cond : Prop -> condHorloge.\n\n(* Nous attribuons cette notation a une condition *)\nNotation \"[| x |]\"  := (cond x).\n\n(* Format des contrainte temporelle *)\nDefinition inCond (x y:nat):= ((clock > y) /\\ (clock < x)).\nDefinition outCond (x y:nat) := ((clock <= y) /\\ (clock >= x)).\n\n\n(*#######*)\n(*# LTS #*)\n(*#######*)\n\n(*########### Les etats ##############################################*)\n\n(* Nous avons certains etats fixes, d'autres intermediaires *)\nInductive state := Init|Inter|Reject|Success|state_: nat -> state.\n\n(* Cette fonction retourne true si deux etats sont egaux, false sinon *)\nFixpoint beq_state (s1 s2 : state): bool:= match s1 , s2 with\n|Init , Init => true\n|Inter , Inter => true\n|Reject , Reject => true\n|Success, Success => true\n|state_ id1 , state_ id2 => beq_nat id1 id2\n|_,_ => false\nend.\n\n(* Notation infixee de la fonction beq_state *)\nInfix \"s=s\" := beq_state (at level 50).\n\n(* Exemples pour tester si la fonction est fonctionne correctement *)\nExample test_beq_state_1: Inter s=s Inter = true.\ntrivial.\nQed.\n\nExample test_beq_state_2: Inter s=s Reject = false.\ntrivial.\nQed.\nExample test_beq_state_3: state_ 1 s=s state_ 2 = false.\ntrivial.\nQed.\nExample test_beq_state_4: state_ 1 s=s state_ 1 = true.\ntrivial.\nQed.\n(*####################################################################*)\n\n\n(*########### Les evenements #########################################*)\n\n(* Nous avons l'evenement nul, l'evenement de type signal gamma ou un evenement \nqu'on identifiera avec un id naturel *)\nInductive event := NoEvent|Gamma|e: nat -> event.\n\n(* Cette fonction retourne true si deux evenements sont egaux, false sinon *)\nFixpoint beq_event (e1 e2 : event): bool:= match e1 , e2 with\n|NoEvent,NoEvent => true\n|Gamma , Gamma => true\n|e id1 , e id2 => beq_nat id1 id2\n|_, _ => false\nend.\n\n(* Notation infixee de la fonction beq_event *)\nInfix \"e=e\" := beq_event (at level 50).\n\n\n(* Exemples pour tester si la fonction est fonctionne correctement *)\nExample test_beq_event_1: e 1 e=e Gamma = false.\ntrivial.\nQed.\n\nExample test_beq_event_2: e 2 e=e e 2 = true.\ntrivial.\nQed.\n\nExample test_beq_event_3: NoEvent e=e NoEvent = true.\ntrivial.\nQed.\n\n(*####################################################################*)\n\n\n(*########### Les etiquettes #########################################*)\n\n(* Format general d'un label *)\nInductive label :Type := lab (condition:condHorloge) (ev:event) (op:opHorloge).\n\n(* Attribution de plusieurs notations selon la presence ou l'absence d'un element\ndu label *)\n\n\nNotation \"( x // y / clock:=-1 )\" := (lab x y ReInit) (at level 0). (* Condition, evenement et operation *)\nNotation \"( x  // y /)\"  := (lab x y NoOp) (at level 0). (* Condition et evenement *)\nNotation \"( x /// clock:=-1)\"  := (lab x NoEvent ReInit) (at level 0). (* Condition et operation *)\nNotation \"(// x / clock:=-1)\"  := (lab NoCond x ReInit) (at level 0). (* Evenement et operation *)\nNotation \"(// x /)\"  := (lab NoCond x NoOp) (at level 0). (* Evenement uniquement *)\nNotation \"( x ///)\"  := (lab x NoEvent NoOp) (at level 0). (* Condition uniquement *)\nNotation \"(/// clock:=-1)\"  := (lab NoCond NoEvent ReInit) (at level 0). (* Operation uniquement *)\nNotation \"(///)\" := (lab NoCond NoEvent NoOp) (at level 0). (* Label vide *)\n(*Notation \"(// Gamma / clock:=-1)\"  := (lab NoCond Gamma ReInit) (at level 0). (* Evt Gamma et operation *)*)\n\n\n\n(* Quelques tests *)\nCompute lab NoCond NoEvent NoOp.\nCompute lab [|inCond 2 3|] NoEvent NoOp.\nCompute lab NoCond (e 1) NoOp.\nCompute lab NoCond NoEvent ReInit.\nCompute lab [|2=2|] (e 1) NoOp.\nCompute lab NoCond (e 1) ReInit.\nCompute lab [|2=2|] NoEvent ReInit.\nCompute lab [|2=2|] (e 1) ReInit.\nCompute (// e 0 /).\n\n(* Fonctions permettant de recuperer les elements de la structure label *)\nDefinition getLabCond (l:label):condHorloge := match l with\n|lab x y z => x\nend.\n\nDefinition getLabEvent (l:label):event := match l with\n|lab x y z => y\nend.\n\nDefinition getLabOp (l:label) := match l with\n|lab x y z => z\nend.\n\n(* Cette fonction retourne true si deux operations sont egales, false sinon *)\nFixpoint beq_op (o1 o2 : opHorloge): bool:= match o1 , o2 with\n|NoOp , NoOp => true\n|ReInit,ReInit => true\n|_, _ => false\nend.\n\n(* Notation infixee de la fonction beq_op *)\nInfix \"op=op\" := beq_op (at level 50).\n\n(* Cette fonction retourne true si deux conditions sont egales, false sinon *)\nFixpoint beq_cond (c1 c2 : condHorloge): bool:= match c1 , c2 with\n|NoCond , NoCond => true\n(*Ajouter d'autres egalites*)\n|_, _ => false\nend.\n(* Traiter cette fonction *)\n\n(* Notation infixee de la fonction beq_cond *)\nInfix \"c=c\" := beq_cond (at level 50).\n\n\n(* Cette fonction retourne true si deux labels sont egaux, false sinon *)\nDefinition beq_lab (a b:label):bool := match getLabCond(a) c=c getLabCond(b),\ngetLabEvent(a) e=e getLabEvent(b), getLabOp(a) op=op getLabOp(b) with\n|true,true,true =>true\n|_,_,_ => false\nend.\n\n(* Notation infixee de la fonction beq_lab *)\nInfix \"l=l\" := beq_lab (at level 50).\n\n\n(*####################################################################*)\n\n\n(*########### Les transitions #########################################*)\n\n(* Format general d'une transition *)\nInductive transition:Type := trans (src:state) (e:label) (trg:state).\n\n(* Attribution d'une notation aux transtions *)\nNotation \"( x , y , z )\"  := (trans x y z) .\n\n(* Test des transitions *)\nCompute trans Init ([|inCond 0 5|]///) Inter.\n\nCompute trans Init ([| 0 = 5 |] ///) Inter.\n\nCompute ( Init ,(//e 1/), Inter).\nEval compute in  (Init, (//e 1/) , Inter) .\nCheck trans Init (//e 3/)Inter.\n\n(* Fonctions permettant de recuperer les elements de la structure transition *)\nDefinition getTransSrc (t:transition):state := match t with\n|trans x y z => x\nend.\n\nDefinition getTransTrg (t:transition):state := match t with\n|trans x y z => z\nend.\n\nDefinition getTransLab (t:transition):label := match t with\n|trans x y z => y\nend.\n\n(* Cette fonction retourne true si deux transitions sont egales, false sinon *)\nDefinition beq_trans (t1 t2:transition):bool := match getTransSrc(t1) s=s getTransSrc(t2),\ngetTransTrg(t1) s=s getTransTrg(t2), getTransLab(t1) l=l getTransLab(t2) with\n|true,true,true =>true\n|_,_,_ => false\nend.\n\n\n(* Petite preuve sur la bonne définition des gets de transitions *)\nLemma sem_trans: forall (s1 s2: state) (l:label) (t:transition) , t = trans (s1) (l) (s2) -> getTransSrc(t)= s1 /\\ \ngetTransLab (t) = l /\\ getTransTrg(t)= s2 .\nintros.\nrewrite H.\nsplit; now repeat constructor.\nQed.\n\n(*=========================================================*)\n(*=  Definitions des elements syntaxiques des patrons CDL =*)\n(*=========================================================*)\n\n\nInductive occurrence : Type :=\n|Exactly_one: event -> occurrence\n|One_or_more: event -> occurrence\n.\n\nDefinition getEvtOfOccu (oc:occurrence) : event:=\nmatch oc with\n| Exactly_one x => x\n| One_or_more x => x\nend.\n\nFixpoint beq_occurrence (e1 e2 : occurrence): bool:= match e1 , e2 with\n|Exactly_one x1 , Exactly_one x2 => beq_event x1 x2\n|One_or_more x1 , One_or_more x2 => beq_event x1 x2\n|_,_ => false\nend.\n\n\nCheck Exactly_one (e 1).\nCheck One_or_more (e 2).\nCheck [(Exactly_one (e 1));(One_or_more (e 2))].\n\n\nInductive occurrence_expression :Type:=\nan: list occurrence -> occurrence_expression\n|all_ordered:list occurrence -> occurrence_expression\n|all_combined:list occurrence -> occurrence_expression\n.\n\nInductive repeatability :Type :=\n|trueRep\n|falseRep\n.\n\nInductive immediacy :Type :=\n|immediately\n|eventually\n.\nDefinition immediately_sem (x:list transition) := (Inter,(lab NoCond Gamma ReInit),Reject)::x.\nDefinition eventually_sem (x:list transition) := x.\n\n\n(* Définition de la contrainte de temps leads_to et de son sens *)\nDefinition leads_to (x y :nat):list transition := (trans Inter (lab [|inCond x y|] NoEvent ReInit) Reject)::nil.\n\n\n(* Défintion des éléments de Precedency et de leur sens *)\n\nInductive precedency :Type :=\n|Cannot_occur\n|May_occur.\n\n\n\n(*Cannot occur before*)\nFixpoint Cannot_sem (l: list event) (e: event) : list transition := match l with\n|nil => nil\n|x::l' =>  (Init,(lab NoCond x ReInit),Reject)::(Cannot_sem(l') (e))\nend.\n(*Notation pour Cannot occur before*)\nInfix \"Cannot_occur_before\" := Cannot_sem (at level 50).\n(*Test de Cannot occur before*)\nCompute ((e 2)::(e 3)::nil)  Cannot_occur_before (e 1).\n\n(*May occur before*)\nDefinition May_sem (l:list event) (e:event) : list transition := nil.\n(*Notation pour May occur before*)\nInfix \"May_occur_before\" := May_sem (at level 50).\n(*-----*)\n\n\n\n(* Fonctions permettant de résoudre le problème des transitions en doublon\ngénérées par différentes options *)\n\nFixpoint atLeastOne {X : Type} (f : X -> bool) (l : list X) : bool :=\n  match l with\n  | nil => false\n  | h::t => if f h then true else atLeastOne f t\n  end.\n\nDefinition atLeastOneElement {X : Type}\n  (eqb : X -> X -> bool) (e : X) (l : list X) : bool :=\n     atLeastOne (eqb e) l.\n\nDefinition clearDoublons {X : Type}\n  (eqb : X -> X -> bool) (l : list X) : list X :=\n    let fix intern (input : list X) (output : list X) : list X :=\n                    match input with\n                    | nil => output\n                    | h::t => if (atLeastOneElement eqb h output)\n                              then intern t output\n                              else intern t (output++(h::nil))\n                    end\n    in intern l nil.\n\n\n(*-----*)\n\n\n(* Absence pattern *)\n\n(* Définition de la contrainte de temps occurs et de son sens *)\nDefinition occurs_never:list transition := nil.\n\n\nFixpoint An_absence (lo:list occurrence) : list transition :=\nmatch lo with\n|nil => nil\n|(Exactly_one ev)::l' => (Init,(//ev/),Reject)::An_absence(l')\n|(One_or_more ev)::l' => (Init,(//ev/),Reject)::(Reject,(//ev/),Reject)::An_absence(l')\nend.\n\n\n\nDefinition All_ordered_absence (num: nat) (l : list occurrence) : list transition :=\n  let nextState := fun (s : state) => match s with\n                               | Init => state_ num\n                               | state_ n => state_ (S n)\n                               | _ => s\n                               end\n  in let endState := Reject\n  in let fix intern (s : state) (l : list occurrence) : list transition :=\n               match l with\n               | [] => []\n               | o::[] => match o with \n                         |(Exactly_one ev) => [(s, (//getEvtOfOccu o/), endState)]\n                         |(One_or_more ev) => [(s, (//getEvtOfOccu o/), endState);(endState, (//getEvtOfOccu o/), endState)]\n                         end\n               | (Exactly_one ev)::t =>\n                   let next := nextState s\n                   in (s, (//ev/), next)::(intern next t)\n               | (One_or_more ev)::t =>\n                   let next := nextState s\n                   in (s, (//ev/), next)::(next,(//ev/),next)::(intern next t)\n               end\n  in intern Init l.\n\n\n\n(*===============================All_combined==================================*)\n\n\nFixpoint getSubLists {X : Type} (l : list X) : list (list X) :=\n  match l with\n  |  [] => [nil]\n  |  h::t =>\n       let rest : list (list X) := getSubLists t\n       in (map (app [h]) rest) ++ rest \n  end.\n\nDefinition stateAndListAbsence (l': list occurrence)  :list (state*(list occurrence)):=\n(Init,l')::(let fix intern0 (l: list (list occurrence)):list (state*(list occurrence)):=\nmatch l with\n|[] => []\n|h::t =>  let endState:=Reject in let nextState := fun (s : state) => match s with\n                               | Init => state_ 1\n                               | state_ n => state_ (S n)\n                               | _ => s\n                               end\n                        in \n                           let fix intern1 (l2: list (list occurrence)) (ss:state) :\n                             list (state*(list occurrence)):=\n                            match l2 with\n                              | nil => nil\n                              |[nil] => [(endState,[])]\n                              | h2::t2 => \n                                      match t2 with \n                                     |nil => [(ss,h2)]\n                                     |_ => [(ss,h2)]++(intern1 t2 (nextState ss))\n                                     end\n                              end\n                            in intern1 t (state_ 1)\n  end  \nin intern0 (getSubLists l')).\n\n\nFixpoint isIn {X : Type} (eq_X : X -> X -> bool)\n  (x : X) (e : list X) : bool :=\n    match e with\n    | [] => false\n    | h::t => if eq_X h x then true else isIn eq_X x t\n    end.\n\nFixpoint minusList {X : Type} (eq_X : X -> X -> bool)\n  (e e' : list X) : list X :=\n    match e with\n    | [] => []\n    | h::t => let rest := minusList eq_X t e' \n              in if isIn eq_X h e' then rest else h::rest\n    end.\n\n\nDefinition absCombTrans (a b : state*(list occurrence)): list transition :=\nmatch a , b with\n|(x1,y1) , (x2,y2) => let occu := minusList (beq_occurrence) (y1) (y2) \n                      in match occu with\n                      |[Exactly_one e1] =>  if beq_nat (length y1) (S(length y2))\n                              then [(x1,(//e1/),x2)] else nil\n                      |[One_or_more e1] => if beq_nat (length y1) (S(length y2))\n                              then [(x1,(//e1/),x2);(x2,(//e1/),x2)] else nil\n                      | _ => nil\n                         end\nend.\n\n\nDefinition All_combined_absence (l:list occurrence):list transition:=\nlet fix intern (l':list (state*(list occurrence))):list transition :=\nmatch l' with\n  |  [] => []\n  |  h::t =>  \n       (let rest := intern t\n       in (flat_map (absCombTrans h) t) ++ rest)\n  end\nin intern (stateAndListAbsence l).\n\n(*==============================================================================*)\nFixpoint property_absence (arity_type:occurrence_expression) (occur:list transition): list transition :=\nmatch arity_type with\n|an lo => clearDoublons beq_trans (An_absence(lo)++occur)\n|all_ordered lo => clearDoublons beq_trans (All_ordered_absence 1(lo)++occur)\n|all_combined lo =>  clearDoublons beq_trans (All_combined_absence (lo)++occur)\nend.\n\n\n\n(*Existence pattern*)\n\n\n\n(* Définition de la contrainte de temps occurs et de son sens *)\nDefinition occurs (x y :nat):list transition := (trans Inter ([|clock>y|]///clock:=-1) Reject)(*::(Tt Inter (notConst x y) Success)*)::nil.\n\n\n\nFixpoint An_existence (lo:list occurrence) (occurF:nat-> nat-> list transition) (x:nat) (y:nat) : list transition :=\nmatch lo,occurF with\n|nil, occurs => nil\n|(Exactly_one ev)::l', occurs => ( Inter ,(lab [|clock>= x|] ev ReInit) , Success )::An_existence(l')(occurF)(x)(y)\n|(One_or_more ev)::l', occurs => (Inter,(lab [|clock>= x|] ev ReInit),Success)::(Success,(lab [|clock>= x|] ev ReInit),Success)::An_existence(l')(occurF)(x)(y)\nend.\n\nDefinition All_ordered_existence(num: nat) (l : list occurrence) (occurF:nat-> nat-> list transition) (x:nat) (y:nat) : list transition :=\n  let nextState := fun (s : state) => match s with\n                               | Inter => state_ num\n                               | state_ n => state_ (S n)\n                               | _ => s\n                               end\n  in let endState := Success\n  in let fix intern (s : state) (l : list occurrence) : list transition :=\n               match l,occurF with\n               | [],occurs => []\n               | o::[],occurs => match o with \n                         |(Exactly_one ev) => [(s, (lab [|clock>=x|] (getEvtOfOccu o) ReInit), endState)]\n                         |(One_or_more ev) => [(s, (lab [|clock>=x|] (getEvtOfOccu o) ReInit), endState);(endState,  (lab [|clock>=x|] (getEvtOfOccu o) ReInit), endState)]\n                         end\n               | (Exactly_one ev)::t,occurs =>\n                   let next := nextState s\n                   in (s, (//ev/), next)::(next,([|clock>y|]///clock:=-1),Reject)::(intern next t)\n               | (One_or_more ev)::t,occurs =>\n                   let next := nextState s\n                   in (s, (//ev/), next)::(next,([|clock>y|]///clock:=-1),Reject)::(next,(//ev/),next)::(intern next t)\n               end\n  in intern Inter l.\n\n\n\n\n\n\n(*===============================All_combined==================================*)\n\n\n\n\nDefinition stateAndListExistence (l': list occurrence)  :list (state*(list occurrence)):=\n(Inter,l')::(let fix intern0 (l: list (list occurrence)):list (state*(list occurrence)):=\nmatch l with\n|[] => []\n|h::t =>  let endState:=Success in let nextState := fun (s : state) => match s with\n                               | Inter => state_ 1\n                               | state_ n => state_ (S n)\n                               | _ => s\n                               end\n                        in \n                           let fix intern1 (l2: list (list occurrence)) (ss:state) :\n                             list (state*(list occurrence)):=\n                            match l2 with\n                              | nil => nil\n                              |[nil] => [(endState,[])]\n                              | h2::t2 => \n                                      match t2 with \n                                     |nil => [(ss,h2)]\n                                     |_ => [(ss,h2)]++(intern1 t2 (nextState ss))\n                                     end\n                              end\n                            in intern1 t (state_ 1)\n  end  \nin intern0 (getSubLists l')).\n\n\n\n\nDefinition existCombTrans (occurF:nat-> nat-> list transition) (x:nat) (y:nat) (a b : state*(list occurrence)): list transition :=\nmatch a , b with\n|(x1,y1) , (Success,y2) => let occu := minusList (beq_occurrence) (y1) (y2) \n                      in match occu with\n                      |[Exactly_one e1] =>  if beq_nat (length y1) (S(length y2))\n                              then [(x1,(lab [|clock>= x|] e1 ReInit),Success)] else nil\n                      |[One_or_more e1] => if beq_nat (length y1) (S(length y2))\n                              then [(x1,(lab [|clock>= x|] e1 ReInit),Success);(Success,(lab [|clock>= x|] e1 ReInit),Success)] else nil\n                      | _ => nil\n                         end\n|(x1,y1) , (x2,y2) => let occu := minusList (beq_occurrence) (y1) (y2) \n                      in match occu with\n                      |[Exactly_one e1] =>  if beq_nat (length y1) (S(length y2))\n                              then [(x1,(//e1/),x2);(x2,(lab [|clock< y|] NoEvent ReInit),Reject)] else nil\n                      |[One_or_more e1] => if beq_nat (length y1) (S(length y2))\n                              then [(x1,(//e1/),x2);(x2,(//e1/),x2);(x2,(lab [|clock< y|] NoEvent ReInit),Reject)] else nil\n                      | _ => nil\n                         end\n\nend.\n\n\nDefinition All_combined_existence (l:list occurrence) (occurF:nat-> nat-> list transition) (x:nat) (y:nat):list transition:=\n[(Init, (///clock:=-1),Inter)]++(let fix intern (l':list (state*(list occurrence))):list transition :=\nmatch l' with\n  |  [] => []\n  |  h::t =>  \n       (let rest := intern t\n       in (flat_map (existCombTrans occurF x y h) t ) ++ rest)\n  end\nin intern (stateAndListExistence l)).\n\n\n(*==============================================================================*)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nFixpoint property_existence (arity_type:occurrence_expression) (occur:nat->nat->list transition) (x: nat) (y: nat): list transition :=\nmatch arity_type with\n|an lo => clearDoublons beq_trans ([(trans Init (///clock:=-1) Inter)]++(An_existence lo occur x y) ++(occur x y))\n|all_ordered lo => clearDoublons beq_trans ([(trans Init (///clock:=-1) Inter)]++(All_ordered_existence 1 lo occur x y)++(occur x y))\n|all_combined lo => clearDoublons beq_trans ((All_combined_existence lo occur x y)++(occur x y))\nend.\n\n\n\n\n\nFixpoint An_pre (lo:list occurrence) : list transition :=\nmatch lo with\n|nil => nil\n|(Exactly_one ev)::l' => (Init,(//ev/),Inter)::(Inter, (lab NoCond ev  ReInit),Reject)::An_pre(l')\n|(One_or_more ev)::l' => (Init,(//ev/),Inter)::(Inter,(//ev/),Inter)::An_pre(l')\nend.\n\nFixpoint An_post (lo:list occurrence) : list transition :=\nmatch lo with\n|nil => nil\n|x::l' => (Inter,(//getEvtOfOccu(x)/),Init)::An_post(l')\nend.\n\nDefinition All_ordered_pre (num: nat) (l : list occurrence) : list transition :=\n  let nextState := fun (s : state) => match s with\n                               | Init => state_ num\n                               | state_ n => state_ (S n)\n                               | _ => s\n                               end\n  in let endState := Inter\n  in let fix intern (s : state) (l : list occurrence) : list transition :=\n               match l with\n               | [] => []\n               | o::[] => match o with \n                         |(Exactly_one ev) => [(s, (//getEvtOfOccu o/), endState)]\n                         |(One_or_more ev) => [(s, (//getEvtOfOccu o/), endState);(endState, (//getEvtOfOccu o/), endState)]\n                         end\n               | (Exactly_one ev)::t =>\n                   let next := nextState s\n                   in (s, (//ev/), next)::(intern next t)\n               | (One_or_more ev)::t =>\n                   let next := nextState s\n                   in (s, (//ev/), next)::(next,(//ev/),next)::(intern next t)\n               end\n  in intern Init l.\n\n\nDefinition All_ordered_post  (num: nat) (l : list occurrence) : list transition :=\n  let nextState := fun (s : state) => match s with\n                               | Inter => state_ num\n                               | state_ n => state_ (S n)\n                               | _ => s\n                               end\n  in let endState := Init\n  in let fix intern (s : state) (l : list occurrence) : list transition :=\n               match l with\n               | [] => []\n               | o::[] => match o with \n                         |(Exactly_one ev) => [(s, (//getEvtOfOccu o/), endState)]\n                         |(One_or_more ev) => [(s, (//getEvtOfOccu o/), endState);(endState, (//getEvtOfOccu o/), endState)]\n                         end\n               | (Exactly_one ev)::t =>\n                   let next := nextState s\n                   in (s, (//ev/), next)::(intern next t)\n               | (One_or_more ev)::t =>\n                   let next := nextState s\n                   in (s, (//ev/), next)::(next,(//ev/),next)::(intern next t)\n               end\n  in intern Inter l.\n\n\n(*===============================All_combined==================================*)\n\nDefinition stateAndListPre (l': list occurrence)  :list (state*(list occurrence)):=\n(Init,l')::(let fix intern0 (l: list (list occurrence)):list (state*(list occurrence)):=\nmatch l with\n|[] => []\n|h::t =>  let endState:=Inter in let nextState := fun (s : state) => match s with\n                               | Init => state_ 1\n                               | state_ n => state_ (S n)\n                               | _ => s\n                               end\n                        in \n                           let fix intern1 (l2: list (list occurrence)) (ss:state) :\n                             list (state*(list occurrence)):=\n                            match l2 with\n                              | nil => nil\n                              |[nil] => [(endState,[])]\n                              | h2::t2 => \n                                      match t2 with \n                                     |nil => [(ss,h2)]\n                                     |_ => [(ss,h2)]++(intern1 t2 (nextState ss))\n                                     end\n                              end\n                            in intern1 t (state_ 1)\n  end  \nin intern0 (getSubLists l')).\n\nDefinition stateAndListPost (num: nat) (l': list occurrence)  :list (state*(list occurrence)):=\n(Inter,l')::(let fix intern0 (l: list (list occurrence)):list (state*(list occurrence)):=\nmatch l with\n|[] => []\n|h::t =>  let endState:=Init in let nextState := fun (s : state) => match s with\n                               | Inter => state_ num\n                               | state_ n => state_ (S n)\n                               | _ => s\n                               end\n                        in \n                           let fix intern1 (l2: list (list occurrence)) (ss:state) :\n                             list (state*(list occurrence)):=\n                            match l2 with\n                              | nil => nil\n                              |[nil] => [(endState,[])]\n                              | h2::t2 => [(ss,h2)]++(intern1 t2) (nextState ss)\n                              end\n                            in intern1 t (state_ num)\n  end  \nin intern0 (getSubLists l')).\n\nDefinition preCombTrans (a b : state*(list occurrence)): list transition :=\nmatch a , b with\n|(x1,y1) , (x2,y2) => let occu := minusList (beq_occurrence) (y1) (y2) \n                      in match occu with\n                      |[Exactly_one e1] =>  if beq_nat (length y1) (S(length y2))\n                              then [(x1,(//e1/),x2)] else nil\n                      |[One_or_more e1] => if beq_nat (length y1) (S(length y2))\n                              then [(x1,(//e1/),x2);(x2,(//e1/),x2)] else nil\n                      | _ => nil\n                         end\nend.\n\nDefinition postCombTrans (a b : state*(list occurrence)): list transition :=\nmatch a , b with\n|(x1,y1) , (Init,y2) => let occu := minusList (beq_occurrence) (y1) (y2) \n                      in match occu with\n                      |[Exactly_one e1] =>  if beq_nat (length y1) (S(length y2))\n                              then [(x1,lab ([|clock>=0|]) (e1) (ReInit),Init)] else nil\n                      |[One_or_more e1] => if beq_nat (length y1) (S(length y2))\n                              then [(x1,lab ([|clock>=0|]) (e1) (ReInit),Init);(Init,lab ([|clock>=0|]) (e1) (ReInit),Init)] else nil\n                      | _ => nil\n                         end\n|(x1,y1) , (x2,y2) => let occu := minusList(beq_occurrence)(y1) (y2)\n                      in match occu with\n                      |[Exactly_one e1] => if beq_nat (length y1) (S(length y2)) \n                       then [(x1,(//e1/),x2)] else nil\n                      |[One_or_more e1] => if beq_nat (length y1) (S(length y2))\n                       then [(x1,(//e1/),x2);(x2,(//e1/),x2)] else nil\n                      | _ => nil\n                         end\nend.\n\nDefinition All_combined_pre (l:list occurrence):list transition:=\nlet fix intern (l':list (state*(list occurrence))):list transition :=\nmatch l' with\n  |  [] => []\n  |  h::t =>  \n       (let rest := intern t\n       in (flat_map (preCombTrans h) t) ++ rest)\n  end\nin intern (stateAndListPre l).\n\nDefinition All_combined_post  (num: nat) (l:list occurrence):list transition:=\nlet fix intern (l:list (state*(list occurrence))):list transition :=\n match l with\n  |  [] => []\n  |  h::t =>  \n       (let rest := intern t\n       in (flat_map (postCombTrans h) t) ++ rest)\n  end\nin intern (stateAndListPost num l).\n\n\n(*==============================================================================*)\n\n\n\nFixpoint property_response (pre:occurrence_expression) (Imm:immediacy) (tps:list transition) (post:occurrence_expression) (l_ev: list event) (preced:precedency) (ev: event): list transition :=\nmatch pre, post with\n|an lo1 ,an lo2 => (match Imm,preced with \n                   |immediately,May_occur =>  clearDoublons beq_trans (An_pre(lo1)++immediately_sem(tps)++An_post(lo2))\n                   |eventually,May_occur =>  clearDoublons beq_trans (An_pre(lo1)++eventually_sem(tps)++An_post(lo2))\n                   |immediately,Cannot_occur => clearDoublons beq_trans (An_pre(lo1)++immediately_sem(tps)++An_post(lo2)++Cannot_sem (l_ev) (ev))\n                   |eventually,Cannot_occur => clearDoublons beq_trans (An_pre(lo1)++eventually_sem(tps)++An_post(lo2)++Cannot_sem (l_ev) (ev))\n                   end)\n|all_ordered lo1 ,an lo2 => (match Imm,preced with \n                   |immediately,May_occur =>  clearDoublons beq_trans ((All_ordered_pre 1 lo1)++immediately_sem(tps)++An_post(lo2))\n                   |eventually,May_occur =>  clearDoublons beq_trans ((All_ordered_pre 1 lo1)++eventually_sem(tps)++An_post(lo2))\n                   |immediately,Cannot_occur => clearDoublons beq_trans ((All_ordered_pre 1 lo1)++immediately_sem(tps)++An_post(lo2)++Cannot_sem (l_ev) (ev))\n                   |eventually,Cannot_occur => clearDoublons beq_trans ((All_ordered_pre 1 lo1)++eventually_sem(tps)++An_post(lo2)++Cannot_sem (l_ev) (ev))\n                   end)\n|an lo1 ,all_ordered lo2 => (match Imm,preced with \n                   |immediately,May_occur =>  clearDoublons beq_trans (An_pre(lo1)++immediately_sem(tps)++(All_ordered_post 1 lo2))\n                   |eventually,May_occur =>  clearDoublons beq_trans (An_pre(lo1)++eventually_sem(tps)++(All_ordered_post 1 lo2))\n                   |immediately,Cannot_occur => clearDoublons beq_trans (An_pre(lo1)++immediately_sem(tps)++(All_ordered_post 1 lo2)++Cannot_sem (l_ev) (ev))\n                   |eventually,Cannot_occur => clearDoublons beq_trans (An_pre(lo1)++eventually_sem(tps)++(All_ordered_post 1 lo2)++Cannot_sem (l_ev) (ev))\n                   end)\n|all_ordered lo1 ,all_ordered lo2 => (match Imm,preced with \n                   |immediately,May_occur =>  clearDoublons beq_trans ((All_ordered_pre 1 lo1)++immediately_sem(tps)++(All_ordered_post (length lo1) lo2))\n                   |eventually,May_occur =>  clearDoublons beq_trans ((All_ordered_pre 1 lo1)++eventually_sem(tps)++(All_ordered_post (length lo1) lo2))\n                   |immediately,Cannot_occur => clearDoublons beq_trans ((All_ordered_pre 1 lo1)++immediately_sem(tps)++(All_ordered_post (length lo1) lo2)++Cannot_sem (l_ev) (ev))\n                   |eventually,Cannot_occur => clearDoublons beq_trans ((All_ordered_pre 1 lo1)++eventually_sem(tps)++(All_ordered_post (length lo1) lo2)++Cannot_sem (l_ev) (ev))\n                   end)\n|all_combined lo1 ,an lo2=> (match Imm,preced with \n                   |immediately,May_occur =>  clearDoublons beq_trans ((All_combined_pre lo1)++immediately_sem(tps)++An_post(lo2))\n                   |eventually,May_occur =>  clearDoublons beq_trans ((All_combined_pre lo1)++eventually_sem(tps)++An_post(lo2))\n                   |immediately,Cannot_occur => clearDoublons beq_trans ((All_combined_pre lo1)++immediately_sem(tps)++An_post(lo2)++Cannot_sem (l_ev) (ev))\n                   |eventually,Cannot_occur => clearDoublons beq_trans ((All_combined_pre lo1)++eventually_sem(tps)++An_post(lo2)++Cannot_sem (l_ev) (ev))\n                   end)\n\n\n\n\n\n|all_combined lo1 ,all_ordered lo2=> (match Imm,preced with \n                   |immediately,May_occur =>  clearDoublons beq_trans ((All_combined_pre lo1)++immediately_sem(tps)++(All_ordered_post (S (length lo1)) lo2))\n                   |eventually,May_occur =>  clearDoublons beq_trans ((All_combined_pre lo1)++eventually_sem(tps)++(All_ordered_post (S (length lo1)) lo2))\n                   |immediately,Cannot_occur => clearDoublons beq_trans ((All_combined_pre lo1)++immediately_sem(tps)++(All_ordered_post (S (length lo1)) lo2)++Cannot_sem (l_ev) (ev))\n                   |eventually,Cannot_occur => clearDoublons beq_trans ((All_combined_pre lo1)++eventually_sem(tps)++(All_ordered_post (S (length lo1)) lo2)++Cannot_sem (l_ev) (ev))\n                   end)\n\n|an lo1 ,all_combined lo2=> (match Imm,preced with \n                   |immediately,May_occur =>  clearDoublons beq_trans (An_pre(lo1)++immediately_sem(tps)++(All_combined_post 1 lo2))\n                   |eventually,May_occur =>  clearDoublons beq_trans (An_pre(lo1)++eventually_sem(tps)++(All_combined_post 1 lo2))\n                   |immediately,Cannot_occur => clearDoublons beq_trans (An_pre(lo1)++immediately_sem(tps)++(All_combined_post 1 lo2)++Cannot_sem (l_ev) (ev))\n                   |eventually,Cannot_occur => clearDoublons beq_trans (An_pre(lo1)++eventually_sem(tps)++(All_combined_post 1 lo2)++Cannot_sem (l_ev) (ev))\n                   end)\n\n\n|all_ordered lo1 ,all_combined lo2=>  (match Imm,preced with \n                   |immediately,May_occur =>  clearDoublons beq_trans ((All_ordered_pre 1 lo1)++immediately_sem(tps)++(All_combined_post (length lo1) lo2))\n                   |eventually,May_occur =>  clearDoublons beq_trans ((All_ordered_pre 1 lo1)++eventually_sem(tps)++(All_combined_post (length lo1) lo2))\n                   |immediately,Cannot_occur => clearDoublons beq_trans ((All_ordered_pre 1 lo1)++immediately_sem(tps)++(All_combined_post (length lo1) lo2)++Cannot_sem (l_ev) (ev))\n                   |eventually,Cannot_occur => clearDoublons beq_trans ((All_ordered_pre 1 lo1)++eventually_sem(tps)++(All_combined_post (length lo1) lo2)++Cannot_sem (l_ev) (ev))\n                   end)\n\n\n|all_combined lo1 ,all_combined lo2=>  (match Imm,preced with \n                   |immediately,May_occur =>  clearDoublons beq_trans ((All_combined_pre lo1)++immediately_sem(tps)++(All_combined_post (S(length lo1)) lo2))\n                   |eventually,May_occur =>  clearDoublons beq_trans ((All_combined_pre lo1)++eventually_sem(tps)++(All_combined_post (S(length lo1)) lo2))\n                   |immediately,Cannot_occur => clearDoublons beq_trans ((All_combined_pre lo1)++immediately_sem(tps)++(All_combined_post (S(length lo1)) lo2)++Cannot_sem (l_ev) (ev))\n                   |eventually,Cannot_occur => clearDoublons beq_trans ((All_combined_pre lo1)++eventually_sem(tps)++(All_combined_post (S(length lo1)) lo2)++Cannot_sem (l_ev) (ev))\n                   end)\nend.\n\n\n\n(*============*)\n(*= Exemples =*)\n(*============*)\n\n\n\n(*=====Absence=====*)\n\n\nCompute property_absence\n(an \n    [Exactly_one (e 1)]\n) \noccurs_never.\n\nCompute property_absence\n(an \n    [Exactly_one (e 1);\n    Exactly_one (e 2)]\n) \noccurs_never.\n\nCompute property_absence\n(an \n    [One_or_more (e 1)]\n) \noccurs_never.\n\nCompute property_absence\n(an \n    [One_or_more (e 1);\n    One_or_more (e 2)]\n) \noccurs_never.\n\nCompute property_absence\n(all_ordered \n    [Exactly_one (e 1);\n    Exactly_one (e 2)]\n) \noccurs_never.\n\nCompute property_absence\n(all_ordered \n    [One_or_more (e 1);\n     One_or_more (e 2)]\n) \noccurs_never.\n\nCompute property_absence (\nall_combined \n   [Exactly_one (e 1);\n    Exactly_one (e 2)])\noccurs_never.\n\nCompute property_absence (\nall_combined \n   [One_or_more (e 1);\n    One_or_more (e 2)])\noccurs_never.\n\n\n(*=====Existence=====*)\n\n\n\n\nCompute property_existence\n(an \n    [Exactly_one (e 1)]\n) \noccurs 1 5.\n\nCompute property_existence\n(an \n    [Exactly_one (e 1);\n     Exactly_one (e 2)]\n) \noccurs 1 5.\n\n\nCompute property_existence\n(an \n    [One_or_more (e 1)]\n) \noccurs 1 5.\n\nCompute property_existence\n(an \n    [One_or_more (e 1);\n    One_or_more (e 2)]\n) \noccurs 1 5.\n\nCompute property_existence\n(all_ordered \n    [Exactly_one (e 1);\n    Exactly_one (e 2)]\n)\noccurs 1 5.\n\nCompute property_existence\n(all_ordered \n    [One_or_more (e 1);\n     One_or_more (e 2)]\n) \noccurs 1 5.\n\n\nCompute property_existence\n(all_combined\n    [Exactly_one (e 1);\n    Exactly_one (e 2)]\n)\noccurs 1 5.\n\nCompute property_existence\n(all_combined \n    [One_or_more (e 1);\n     One_or_more (e 2)]\n) \noccurs 1 5.\n\n\n\n\n\n\n\n(*=====Response=====*)\n\n\n\n\nCompute property_response \n(an \n    [Exactly_one (e 1)]\n) \nimmediately (leads_to 0 5) \n(an\n    [Exactly_one (e 2)]\n) \n[e 2] Cannot_occur (e 1) .\n\n\n\nCompute property_response \n(an \n    [One_or_more (e 1)]\n) \nimmediately (leads_to 0 5) \n(an\n    [One_or_more (e 2)]\n) \n[e 2] Cannot_occur (e 1) .\n\n\nCompute property_response \n(an \n    [Exactly_one (e 1);\n    Exactly_one (e 2)]\n) \nimmediately (leads_to 0 5) \n(an\n    [Exactly_one (e 3);\n    Exactly_one (e 4)]\n) \n[e 3] Cannot_occur (e 1) .\n\n\n\nCompute property_response \n(an \n    [One_or_more (e 1);\n    One_or_more (e 2)]\n) \nimmediately (leads_to 0 5) \n(an\n    [One_or_more (e 3);\n    One_or_more (e 4)]\n) \n[e 3] Cannot_occur (e 1) .\n\n\nCompute property_response \n(all_combined \n    [Exactly_one (e 1);\n    Exactly_one (e 2)]\n) \nimmediately (leads_to 0 5) \n(an\n    [Exactly_one (e 3);\n    Exactly_one (e 4)]\n) \n[e 3] Cannot_occur (e 1) .\n\n\nCompute property_response \n(all_combined \n    [One_or_more (e 1);\n    One_or_more (e 2)]\n) \nimmediately (leads_to 0 5) \n(an\n    [One_or_more (e 3);\n    One_or_more (e 4)]\n) \n[e 3] Cannot_occur (e 1) .\n\n\nCompute property_response \n(all_ordered\n    [Exactly_one (e 1);\n    Exactly_one (e 2)]\n) \nimmediately (leads_to 0 5) \n(an\n    [Exactly_one (e 3);\n    Exactly_one (e 4)]\n) \n[e 3] Cannot_occur (e 1) .\n\n\nCompute property_response \n(all_ordered \n    [One_or_more (e 1);\n    One_or_more (e 2)]\n) \nimmediately (leads_to 0 5) \n(an\n    [One_or_more (e 3);\n    One_or_more (e 4)]\n) \n[e 3] Cannot_occur (e 1) .\n\n\n\nCompute property_response \n(an\n    [Exactly_one (e 1);\n    Exactly_one (e 2)]\n) \nimmediately (leads_to 0 5) \n(all_combined\n    [Exactly_one (e 3);\n    Exactly_one (e 4)]\n) \n[e 3] Cannot_occur (e 1) .\n\n\nCompute property_response \n(an \n    [One_or_more (e 1);\n    One_or_more (e 2)]\n) \nimmediately (leads_to 0 5) \n(all_combined\n    [One_or_more (e 3);\n    One_or_more (e 4)]\n) \n[e 3] Cannot_occur (e 1) .\n\n\nCompute property_response \n(an\n    [Exactly_one (e 1);\n    Exactly_one (e 2)]\n) \nimmediately (leads_to 0 5) \n(all_ordered\n    [Exactly_one (e 3);\n    Exactly_one (e 4)]\n) \n[e 3] Cannot_occur (e 1) .\n\n\nCompute property_response \n(an \n    [One_or_more (e 1);\n    One_or_more (e 2)]\n) \nimmediately (leads_to 0 5) \n(all_ordered\n    [One_or_more (e 3);\n    One_or_more (e 4)]\n) \n[e 3] Cannot_occur (e 1) .\n\n\nCompute property_response \n(all_combined\n    [Exactly_one (e 1);\n    Exactly_one (e 2)]\n) \nimmediately (leads_to 0 5) \n(all_combined\n    [Exactly_one (e 3);\n    Exactly_one (e 4)]\n) \n[e 3] Cannot_occur (e 1) .\n\nCompute property_response \n(all_combined \n    [One_or_more (e 1);\n    One_or_more (e 2)]\n) \nimmediately (leads_to 0 5) \n(all_combined\n    [One_or_more (e 3);\n    One_or_more (e 4)]\n) \n[e 3] Cannot_occur (e 1) .\n\n\nCompute property_response \n(all_ordered\n    [Exactly_one (e 1);\n    Exactly_one (e 2)]\n) \nimmediately (leads_to 0 5) \n(all_ordered\n    [Exactly_one (e 3);\n    Exactly_one (e 4)]\n) \n[e 3] Cannot_occur (e 1) .\n\nCompute property_response \n(all_ordered \n    [One_or_more (e 1);\n    One_or_more (e 2)]\n) \nimmediately (leads_to 0 5) \n(all_ordered\n    [One_or_more (e 3);\n    One_or_more (e 4)]\n) \n[e 3] Cannot_occur (e 1) .\n\n\nCompute property_response \n(all_combined\n    [Exactly_one (e 1);\n    Exactly_one (e 2)]\n) \nimmediately (leads_to 0 5) \n(all_ordered\n    [Exactly_one (e 3);\n    Exactly_one (e 4)]\n) \n[e 3] Cannot_occur (e 1) .\n\nCompute property_response \n(all_combined \n    [One_or_more (e 1);\n    One_or_more (e 2)]\n) \nimmediately (leads_to 0 5) \n(all_ordered\n    [One_or_more (e 3);\n    One_or_more (e 4)]\n) \n[e 3] Cannot_occur (e 1) .\n\n\n\nCompute property_response \n(all_ordered\n    [Exactly_one (e 1);\n    Exactly_one (e 2)]\n) \nimmediately (leads_to 0 5) \n(all_combined\n    [Exactly_one (e 3);\n    Exactly_one (e 4)]\n) \n[e 3] Cannot_occur (e 1) .\n\nCompute property_response \n(all_ordered \n    [One_or_more (e 1);\n    One_or_more (e 2)]\n) \nimmediately (leads_to 0 5) \n(all_combined\n    [One_or_more (e 3);\n    One_or_more (e 4)]\n) \n[e 3] Cannot_occur (e 1) .\n\n(*========================================================================*)\n\n\n\n\n\n\n\nCompute property_response \n(an \n    [Exactly_one (e 1);\n    One_or_more (e 2);\n    Exactly_one (e 3);\n    One_or_more (e 4)]\n) \nimmediately (leads_to 0 5) \n(an\n    [Exactly_one (e 5);\n    One_or_more (e 6);\n    Exactly_one (e 7);\n    One_or_more (e 8)]\n) \n[e 2] Cannot_occur (e 1) .\n\n\nCompute property_response \n(all_ordered \n    [Exactly_one (e 1);\n    One_or_more (e 2);\n    Exactly_one (e 3);\n    One_or_more (e 4)]\n) \nimmediately (leads_to 0 5) \n(an\n    [Exactly_one (e 5);\n    One_or_more (e 6);\n    Exactly_one (e 7);\n    One_or_more (e 8)]\n) \n[e 2] Cannot_occur (e 1) .\n\nCompute property_response\n(an \n    [Exactly_one (e 1);\n    One_or_more (e 2);\n    Exactly_one (e 3);\n    One_or_more (e 4)]\n) \nimmediately (leads_to 0 5) \n(all_ordered\n    [Exactly_one (e 5);\n    One_or_more (e 6);\n    Exactly_one (e 7);\n    One_or_more (e 8)]\n) \n[e 2] Cannot_occur (e 1) .\n\nCompute property_response \n(all_ordered\n    [Exactly_one (e 1);\n    One_or_more (e 2);\n    Exactly_one (e 3);\n    One_or_more (e 4)]\n) \nimmediately (leads_to 0 5) \n(all_ordered\n    [Exactly_one (e 5);\n    One_or_more (e 6);\n    Exactly_one (e 7);\n    One_or_more (e 8)]\n) \n[e 2] Cannot_occur (e 1) .\n\nCompute property_response \n(all_ordered\n    [One_or_more (e 1);\n     One_or_more (e 2);\n     One_or_more (e 3);\n     One_or_more (e 4)]\n) \nimmediately (leads_to 0 5) \n(all_ordered\n    [One_or_more (e 5);\n    One_or_more (e 6);\n    One_or_more (e 7);\n    One_or_more (e 8)]\n) \n[e 2] Cannot_occur (e 1) .", "meta": {"author": "plug-obp", "repo": "plug-obp.github.io", "sha": "260cf6e311d759b71c1b3244e419be43afa24caa", "save_path": "github-repos/coq/plug-obp-plug-obp.github.io", "path": "github-repos/coq/plug-obp-plug-obp.github.io/plug-obp.github.io-260cf6e311d759b71c1b3244e419be43afa24caa/lib/semantics_cdlpattern_v1_0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2671301270393226}}
{"text": "(** * Contract examples  *)\n\n(** We develop some blockchain infrastructure relevant for the contract execution (a fragment of the standard library and an execution context). With that, we develop a deep embedding of a crowdfunding contract and prove some of its properties using the corresponding shallow embedding *)\n\nRequire Import String.\nRequire Import Polymorphic.Ast Lib.CustomTactics.\nRequire Import List.\nRequire Import PeanoNat.\nRequire Import Coq.ssr.ssrbool.\nImport ListNotations.\nFrom Template Require Import All.\n\nImport MonadNotation.\nImport BaseTypes.\nImport StdLib.\nOpen Scope list.\n\n(** Our approximation for finite maps. Eventually, will be replaced with the Oak's standard library implementation. We assume that the standard library is available for a contract developer. *)\n\nSection Maps.\n  Open Scope nat.\n\n  Inductive addr_map : Set :=\n  | mnil | mcons : nat -> nat -> addr_map -> addr_map.\n\n  Inductive Maybe_map :=\n  | Just_map : nat -> Maybe_map | Nothing_map.\n\n  Definition Maybe := \"Maybe_map\".\n\n  Fixpoint lookup_map (m : addr_map) (key : nat) : Maybe_map :=\n    match m with\n    | mnil => Nothing_map\n    | mcons k v m' =>\n      if (Nat.eqb key k) then Just_map v else lookup_map m' key\n    end.\n\n  (* Ported from FMapWeaklist of StdLib *)\n  Function add_map (k : nat) (x : nat) (s : addr_map) : addr_map :=\n  match s with\n   | mnil => mcons k x mnil\n   | mcons k' y l => if Nat.eqb k k' then mcons k x l else mcons k' y (add_map k x l)\n  end.\n\n  Definition inmap_map k m := match lookup_map m k with\n                              | Just_map _ => true\n                              | Nothing => false\n                              end.\n\n  Lemma lookup_map_add k v m : lookup_map (add_map k v m) k = Just_map v.\n  Proof.\n    induction m.\n    + simpl. now rewrite PeanoNat.Nat.eqb_refl.\n    + simpl. destruct (k =? n) eqn:Heq.\n      * simpl. now rewrite PeanoNat.Nat.eqb_refl.\n      * simpl. now rewrite Heq.\n  Qed.\n\nEnd Maps.\n\nNotation \"a ∈ m\" := (inmap_map a m = true) (at level 50).\nNotation \"a ∉ m\" := (inmap_map a m = false) (at level 50).\n\n(** Generation of string constants using MetaCoq *)\nFixpoint mkNames (ns : list string) (postfix : string) :=\n  match ns with\n  | [] => tmPrint \"Done.\"\n  | n :: ns' => n' <- tmEval all (n ++ postfix)%string ;;\n                  str <- tmQuote n';;\n                  tmMkDefinition n str;;\n                  mkNames ns' postfix\n  end.\n\n(** Notations for functions on finite maps *)\n\nDefinition Map := \"addr_map\".\n\nNotation \"'mfind' a b\" :=  [| {eConst \"lookup_map\"} {a} {b} |]\n        (in custom expr at level 0,\n            a custom expr at level 1,\n            b custom expr at level 1).\n\nNotation \"'madd' a b c\" :=  [| {eConst \"add_map\"} {a} {b} {c} |]\n        (in custom expr at level 0,\n            a custom expr at level 1,\n            b custom expr at level 1,\n            c custom expr at level 1).\n\nNotation \"'mem' a b\" :=  [| {eConst \"inmap_map\"} {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(** * Contract execution context  *)\n\n(** The contract execution context is a part of the blockchain infrastructure, not specific to this particular example. We assume that these structures reflect the actual implementation.  *)\n\nRecord ctx := mkctx { _ctx_from : nat;\n                      _ctx_contract_address : nat ;\n                      _amount : nat;\n                      _cur_time : nat}.\n\nDefinition ctx_from_name := \"ExampleContracts._ctx_from\".\nDefinition Ctx := \"ExampleContracts.ctx\".\nNotation \"'ctx_from' a\" := [| {eConst ctx_from_name} {a} |]\n                             (in custom expr at level 0).\nNotation \"'ctx_contract_address' a\" :=\n  [| {eConst \"ExampleContracts._ctx_contract_address\"} {a} |]\n    (in custom expr at level 0).\nNotation \"'amount' a\" := [| {eConst \"_amount\"} {a} |]\n                             (in custom expr at level 0).\nNotation \"'cur_time' a\" := [| {eConst \"_cur_time\"} {a} |]\n                             (in custom expr at level 0).\n\n(** ** The crowdfunding contract *)\n\nModule CrowdfundingContract.\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. The idea is that the corresponding ASTs will be produced from the real Oak programs by means of printing the fully annotated abstract syntax trees build from constructors of the inductive type [Ast.expr] *)\n\n   (** Brackets like [[\\ \\]] delimit the scope of global definitions and like [[| |]] the scope of programs *)\n\n  (** We model types of addresses and currency by [nat] type of Coq *)\n  Notation Address := Nat.\n  Definition Money := Nat.\n\n  (** Generating names for the data structures  *)\n  Run TemplateProgram\n      (mkNames [\"State\" ; \"balance\" ; \"donations\" ; \"owner\"; \"deadline\"; \"goal\"; \"done\";\n                \"Result\" ; \"Res\" ; \"Error\";\n                \"Msg\"; \"Donate\"; \"GetFunds\"; \"Claim\";\n                \"Action\"; \"Transfer\"; \"Empty\" ] \"_coq\").\n\n  Import ListNotations.\n\n  (** *** Definitions of data structures for the contract *)\n\n  (** The internal state of the contract *)\n  Definition state_syn : global_dec :=\n    [\\ record State :=\n       { balance : Money ;\n         donations : Map;\n         owner : Money;\n         deadline : Nat;\n         done : Bool;\n         goal : Money } \\].\n\n  (** We can print actual AST by switching off the notations *)\n\n  Unset Printing Notations.\n\n  Print 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\n  Set Printing Notations.\n\n  (** Unquoting the definition of a record *)\n  Make Inductive (trans_global_dec state_syn).\n\n  (** As a result, we get a new Coq record [State_coq] *)\n  Print State_coq.\n\n  (** AST of action that our contract can produce *)\n  Definition action_syn :=\n    [\\ data Action :=\n         Transfer : Address -> Money -> Action\n    | Empty : Action; \\].\n\n  Make Inductive (trans_global_dec action_syn).\n\n  (** AST for the type of results *)\n  Definition result_syn :=\n    [\\ data Result :=\n         Res : State -> Action -> Result\n       | Error : Result; \\].\n\n  Make Inductive (trans_global_dec result_syn).\n\n  Definition msg_syn :=\n    [\\ data Msg :=\n       Donate : Msg\n       | GetFunds : Msg\n       | Claim : Msg; \\].\n\n  Make Inductive (trans_global_dec msg_syn).\n\n  (** Custom notations for patterns, projections and constructors *)\n  Module Notations.\n\n    (** Patterns *)\n    Notation \"'Donate'\" :=\n      (pConstr Donate []) (in custom pat at level 0).\n    Notation \"'GetFunds'\" :=\n      (pConstr GetFunds []) ( in custom pat at level 0).\n\n    Notation \"'Claim'\" :=\n      (pConstr Claim []) ( in custom pat at level 0).\n\n    Notation \"'Just' x\" :=\n      (pConstr \"Just\" [x]) (in custom pat at level 0,\n                               x constr at level 4).\n    Notation \"'Nothing'\" := (pConstr \"Nothing\" [])\n                              (in custom pat at level 0).\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    (** Constructors *)\n    Notation \"'Res' a b\" :=\n      [| {eConstr Result Res} {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 \"'Error'\" := (eConstr Result Error)\n                        (in custom expr at level 0).\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 Action Transfer} {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 \"'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\n    Definition Σ' :=\n      Σ ++ [gdInd Ctx 0 [(\"ExampleContracts.mkctx\",\n                        [(nAnon,tyInd Address); (nAnon,tyInd Address)])] false;\n              gdInd Maybe 0 [(\"Just\", [(nAnon,tyInd Nat)]);\n                             (\"Nothing\", [])] false;\n            state_syn;\n            result_syn;\n            msg_syn;\n            action_syn].\n\n\n    End Notations.\n\n  Import Notations.\n\n\n  (** Generating string constants for variable names *)\n\n  Run TemplateProgram (mkNames [\"c\";\"s\";\"e\";\"m\";\"v\";\n                                \"tx_amount\"; \"bal\"; \"sender\"; \"own\"; \"isdone\" ;\n                                \"accs\"; \"now\";\n                                 \"newstate\"; \"newmap\"; \"cond\"] \"\").\n  (** A shortcut for [if .. then .. else ..]  *)\n  Notation \"'if' cond 'then' b1 'else' b2 : ty\" :=\n    (eCase (tyInd Bool,0) (tyInd ty) cond\n           [(pConstr true_name [],b1);(pConstr false_name [],b2)])\n      (in custom expr at level 2,\n          cond custom expr at level 4,\n          ty constr at level 4,\n          b1 custom expr at level 4,\n          b2 custom expr at level 4).\n\n  (** *** The AST of a crowdfunding contract *)\n  Definition crowdfunding : expr :=\n    [| \\c : Ctx => \\m : Msg => \\s : State =>\n         let bal : Money := balance s in\n         let now : Nat := cur_time c in\n         let tx_amount : Money := amount c in\n         let sender : Address := ctx_from c in\n         let own : Address := owner s in\n         let accs : Map := donations s in\n         case m : Msg return Result of\n            | GetFunds ->\n             if (own == sender) && (deadline s < now) && (goal s <= bal)  then\n               Res (mkState 0 accs own (deadline s) True (goal s))\n                   (Transfer bal sender)\n             else Error : Result\n           | Donate -> if now <= deadline s then\n             (case (mfind accs sender) : Maybe return Result of\n               | Just v ->\n                 let newmap : Map := madd sender (v + tx_amount) accs in\n                 Res (mkState (tx_amount + bal) newmap own (deadline s) (done s) (goal s)) Empty\n               | Nothing ->\n                 let newmap : Map := madd sender tx_amount accs in\n                 Res (mkState (tx_amount + bal) newmap own (deadline s) (done s) (goal s)) Empty)\n               else Error : Result\n           | Claim ->\n             if (deadline s < now) && (bal < goal s) && (~ done s) then\n             (case (mfind accs sender) : Maybe return Result of\n              | Just v -> let newmap : Map := madd sender 0 accs in\n                  Res (mkState (bal-v) newmap own (deadline s) (done s) (goal s))\n                      (Transfer v sender)\n               | Nothing -> Error)\n              else Error : Result\n    |].\n\n  Make Definition entry :=\n    Eval compute in (expr_to_term Σ' (indexify nil crowdfunding)).\n\n  Ltac inv_andb H := apply Bool.andb_true_iff in H;destruct H.\n  Ltac split_andb := apply Bool.andb_true_iff;split.\n\n\n  Open Scope nat.\n  Open Scope bool.\n\n  Import Lia.\n\n  Definition deadline_passed now (s : State_coq) := s.(deadline_coq) <? now.\n\n  Definition goal_reached (s : State_coq) := s.(goal_coq) <=? s.(balance_coq).\n\n  Definition funded now (s : State_coq) :=\n    deadline_passed now s && goal_reached s.\n\n  Lemma not_leb n m : ~~ (n <=? m) -> m <? n.\n  Proof.\n   intros.\n   unfold Nat.ltb in *.\n   unfold is_true in *. rewrite Bool.negb_true_iff in *.\n   rewrite Nat.leb_gt in *. rewrite Nat.leb_le in *. lia.\n  Qed.\n\n  Lemma not_ltb n m : ~~ (n <? m) -> m <=? n.\n  Proof.\n   intros.\n   unfold Nat.ltb in *.\n   unfold is_true in *. rewrite Bool.negb_true_iff in *.\n   rewrite Nat.leb_gt in *. rewrite Nat.leb_le in *. lia.\n  Qed.\n\n  (** ** Properties of the crowdfunding contract *)\n\n  (** This function is a simplistic execution environment that performs one step of execution *)\n  Definition run (entry : State_coq -> Result_coq ) (init : State_coq)\n    : State_coq * Action_coq :=\n    match entry init with\n    | Res_coq fin out => (fin, out)\n    | Error_coq => (init, Empty_coq) (* if an error occurs, the state remains the same *)\n    end.\n\n  (** A wrapper for the assertions about the contract execution *)\n  Definition assertion (pre : State_coq -> Prop)\n             (entry : State_coq -> Result_coq )\n             (post : State_coq -> Action_coq -> Prop) :=\n    forall init, pre init -> exists fin out, run entry init = (fin, out) /\\ post fin out.\n\n  Notation \"{{ P }} c {{ Q }}\" := (assertion P c Q)( at level 50).\n\n\n  (** The donations can be paid back to the backers if the goal is not\nreached within a deadline *)\n\n  Lemma get_money_back_guarantee CallCtx (sender := CallCtx.(_ctx_from)) v :\n      (* pre-condition *)\n      {{ fun init =>\n         deadline_passed CallCtx.(_cur_time) init\n       /\\ ~~ (goal_reached init)\n       /\\ ~~ init.(done_coq)\n       /\\ lookup_map init.(donations_coq) sender = Just_map v }}\n\n        (* contract call *)\n       entry CallCtx Claim_coq\n\n       (* post-condition *)\n       {{fun fin out => lookup_map fin.(donations_coq) sender = Just_map 0\n         /\\ out = Transfer_coq v sender}}.\n  Proof.\n    unfold assertion. intros init H. simpl.\n    destruct H as [Hdl [Hgoal [Hndone Hlook]]].\n    unfold deadline_passed,goal_reached in *;simpl in *.\n    repeat eexists. unfold run. simpl.\n    assert (balance_coq init <? goal_coq init = true) by now apply not_leb.\n    repeat destruct (_ <? _);tryfalse.\n    destruct (~~ done_coq _)%bool;tryfalse.\n    destruct (lookup_map _ _);tryfalse;inversion Hlook;subst;clear Hlook.\n    repeat split;cbn. apply lookup_map_add.\n  Qed.\n\n  (** New donations are recorded correctly in the contract's state *)\n\n  Lemma new_donation_correct CallCtx (sender := CallCtx.(_ctx_from))\n        (donation := CallCtx.(_amount)) :\n\n    {{ fun init =>\n          sender ∉ init.(donations_coq) (* the sender have not donated before *)\n       /\\ ~~ deadline_passed CallCtx.(_cur_time) init }}\n\n      (* contract call *)\n    entry CallCtx Donate_coq\n\n    {{ fun fin out =>\n         (* nothing gets transferred *)\n         out = Empty_coq\n         (* donation has been accepted *)\n         /\\ lookup_map fin.(donations_coq) sender = Just_map donation  }}.\n  Proof.\n    unfold assertion. intros init H. simpl.\n    destruct H as [Hnew_sender Hdl].\n    unfold deadline_passed in *;simpl in *.\n    unfold run.\n    repeat eexists.\n    simpl in *. apply not_ltb in Hdl.\n    destruct (_ <=? _);tryfalse.\n    unfold inmap_map in *.\n    destruct (lookup_map _ _);tryfalse.\n    repeat split;eauto. simpl. now rewrite lookup_map_add.\n  Qed.\n\n\n  (** Existing donations are updated correctly in the contract's state *)\n\n  Lemma existing_donation_correct CallCtx (sender := CallCtx.(_ctx_from))\n        (new_don := CallCtx.(_amount)) old_don :\n    {{ fun init =>\n         (* the sender has already donated before *)\n         lookup_map init.(donations_coq) sender = Just_map old_don\n\n       /\\ ~~ deadline_passed CallCtx.(_cur_time) init }}\n\n     entry CallCtx Donate_coq\n\n    {{ fun fin out =>\n         (* nothing gets transferred *)\n         out = Empty_coq\n         (* donation has been added *)\n       /\\ lookup_map fin.(donations_coq) sender = Just_map (new_don + old_don) }}.\n  Proof.\n    unfold assertion. intros init H. simpl.\n    destruct H as [Hsender Hdl].\n    unfold deadline_passed in *;simpl in *.\n    subst;simpl in *.\n    eexists. eexists.\n    unfold run. simpl in *. apply not_ltb in Hdl.\n    destruct (_ <=? _);tryfalse.\n    destruct (lookup_map _ _);tryfalse.\n    inversion Hsender;subst.\n    repeat split;simpl;eauto. now rewrite lookup_map_add.\n  Qed.\n\n  Fixpoint sum_map  (m : addr_map) :=\n    match m with\n    | mnil => 0\n    | mcons _ v m' => v + sum_map m'\n    end.\n\n  Lemma sum_map_add_in m : forall n0 v' v k,\n      lookup_map m k = Just_map n0 ->\n      sum_map m = v ->\n      sum_map (add_map k (n0+v') m) = v' + v.\n  Proof.\n    intros;subst.\n    revert dependent n0. revert v' k.\n    induction m;intros;subst.\n    + inversion H.\n    + simpl in *. destruct (k =? n) eqn:Hkn.\n      * simpl in *. inversion H. subst. lia.\n      * simpl in *. rewrite IHm;auto. lia.\n  Qed.\n\n  Lemma sum_map_add_not_in m : forall v' v k,\n      lookup_map m k = Nothing_map ->\n      sum_map m = v ->\n      sum_map (add_map k v' m) = v' + v.\n  Proof.\n    intros;subst.\n    revert dependent k. revert v'.\n    induction m;intros;subst.\n    + reflexivity.\n    + simpl in *. destruct (k =? n) eqn:Hkn.\n      * inversion H.\n      * simpl in *. rewrite IHm;auto. lia.\n  Qed.\n\n  (** The contract does no leak funds: the overall balance before the deadline is always equal to the sum of individual donations *)\n\n  Definition consistent_balance ctx state :=\n    ~~ deadline_passed ctx.(_cur_time) state /\\\n    sum_map state.(donations_coq) = state.(balance_coq).\n\n  (** This lemma holds for any message  *)\n  Lemma contract_backed CallCtx msg :\n\n    {{ consistent_balance CallCtx }}\n\n      entry CallCtx msg\n\n    {{ fun fin _ => consistent_balance CallCtx fin }}.\n  Proof.\n    intros init H.\n    destruct H as [Hdl Hsum].\n    destruct msg.\n    + (* Donate *)\n      simpl in *.\n      specialize Hdl as Hdl'.\n      unfold deadline_passed in Hdl. unfold run,consistent_balance.\n      apply not_ltb in Hdl.  simpl.\n      destruct (_ <=? _);tryfalse.\n      destruct (lookup_map _ _) eqn:Hlook.\n      * repeat eexists;eauto. now apply sum_map_add_in.\n      * repeat eexists;eauto. now apply sum_map_add_not_in.\n    + (* GetFunds - it is not possible to get funds before the deadline, so the state is not modified *)\n      unfold consistent_balance in *.\n      unfold deadline_passed in *.\n      exists init. exists Empty_coq. unfold run. simpl.\n      destruct (_ <? _);tryfalse. rewrite Bool.andb_false_r. simpl.\n      split;eauto.\n    + (* Claim - it is not possible to claim a donation back before the deadline, so the state is not modified *)\n      unfold consistent_balance in *.\n      unfold deadline_passed in *.\n      exists init. exists Empty_coq. unfold run. simpl.\n      destruct (_ <? _);tryfalse. simpl.\n      split;eauto.\n  Qed.\n\n  (** The owner gets the money after the deadline, if the goal is reached *)\n\n  Lemma GetFunds_correct CallCtx (OwnerAddr := CallCtx.(_ctx_from)) funds :\n    {{ fun init => funded CallCtx.(_cur_time) init\n       /\\ init.(owner_coq) =? OwnerAddr\n       /\\ balance_coq init = funds }}\n\n    entry CallCtx GetFunds_coq\n\n    {{ fun fin out =>\n       (* the money are sent back *)\n       out = Transfer_coq funds OwnerAddr\n       (* set balance to 0 after withdrawing by the owner *)\n       /\\  fin.(balance_coq) = 0\n       (* set the \"done\" flag *)\n       /\\ fin.(done_coq) = true}}.\n  Proof.\n    unfold assertion. intros init H. simpl.\n    destruct H as [Hfunded [Hown Hbalance]]. unfold funded,goal_reached,deadline_passed in *.\n    subst. simpl in *.\n    unfold run. simpl in *. subst OwnerAddr. eexists. eexists.\n    destruct (_ <? _);tryfalse. destruct ( _ =? _);tryfalse. simpl in *.\n    destruct (_ <=? _);tryfalse. split;eauto.\n  Qed.\n\n  (** Backers cannot claim their money if the campaign have succeed (but owner haven't claimed the money yet, so the \"done\" flag is not set to [true]) *)\n  Lemma no_claim_if_succeeded CallCtx the_state:\n    {{ fun init =>\n         funded CallCtx.(_cur_time) init\n         /\\ ~~ init.(done_coq)\n         /\\ init = the_state }}\n\n      entry CallCtx Claim_coq\n\n    (* Nothing happens - the stated stays the same and no outgoing transfers *)\n    {{ fun fin out => fin = the_state /\\ out = Empty_coq }}.\n  Proof.\n    unfold assertion. intros init H. simpl.\n    unfold funded,deadline_passed,goal_reached in *. subst. simpl in *.\n    destruct H as [Hdl [Hgoal Hst]].\n    inv_andb Hdl. subst. unfold run. simpl.\n    exists the_state. eexists.\n    destruct the_state as [i_balance i_dons i_own i_dl i_done i_goal].\n    destruct CallCtx as [from c_addr am now]. simpl in *.\n\n    destruct (_ <? _);tryfalse. destruct (_ <=? _) eqn:Hleb;tryfalse.\n    replace (i_balance <? i_goal) with false by\n        (symmetry;rewrite Nat.ltb_ge in *; rewrite Nat.leb_le in *;lia).\n    now simpl.\n  Qed.\n\n  (** Backers cannot claim their money if the contract is marked as \"done\" *)\n  Lemma no_claim_after_done CallCtx the_state :\n    {{ fun init => init.(done_coq) /\\ init = the_state }}\n\n     entry CallCtx Claim_coq\n    (* Nothing happens - the stated stays the same and no outgoing transfers *)\n    {{ fun fin out => fin = the_state /\\ out = Empty_coq }}.\n  Proof.\n    unfold assertion. intros init H. simpl. destruct H. subst.\n    unfold funded,deadline_passed,goal_reached in *. subst. simpl in *.\n    exists the_state. eexists.\n    unfold run. simpl in *. destruct (done_coq _);tryfalse. simpl in *.\n    now rewrite Bool.andb_false_r.\n  Qed.\nEnd CrowdfundingContract.\n", "meta": {"author": "annenkov", "repo": "FMBC19-artefact", "sha": "3218074bc5f9b87a2761352e7c0a06be67cbf5b6", "save_path": "github-repos/coq/annenkov-FMBC19-artefact", "path": "github-repos/coq/annenkov-FMBC19-artefact/FMBC19-artefact-3218074bc5f9b87a2761352e7c0a06be67cbf5b6/theories/Examples/ExampleContracts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2669631611888173}}
{"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(*                 The Calculus of Inductive Constructions                  *)\n(*                                                                          *)\n(*                                Projet Coq                                *)\n(*                                                                          *)\n(*                     INRIA                        ENS-CNRS                *)\n(*              Rocquencourt                        Lyon                    *)\n(*                                                                          *)\n(*                                Coq V6.3                                  *)\n(*                               Dec 24 1996                                *)\n(*                                                                          *)\n(****************************************************************************)\n(*              Firing Squad Synchronization Problem                        *)\n(*                                                                          *)\n(*              Jean Duprat                                                 *)\n(*                                                                          *)\n(*              Developped in V5.10  July 1997                              *)\n(****************************************************************************)\n\nRequire Export basic.\n\nSection reflect.\n\nSection UZ.\n\nInductive UA (t x cote : nat) : Prop :=\n    make_UA : un < cote -> Diag t x cote G_Etat A_Etat G_Etat -> UA t x cote.\nInductive UAB (t x cote : nat) : Prop :=\n    make_UAB :\n      deux < cote ->\n      Diag' t x cote G_Etat G_Etat B_Etat G_Etat ->\n      Diag (S t) x cote G_Etat A_Etat G_Etat -> UAB t x cote.\nInductive ZCB (t x cote : nat) : Prop :=\n    make_ZCB :\n      un < cote ->\n      Diag t x cote G_Etat C_Etat G_Etat ->\n      Diag (S t) x cote G_Etat B_Etat G_Etat -> ZCB t x cote.\n\nEnd UZ.\n\nSection construction.\n\nNotation rec3 := (Rec3 _ _ _ _) (only parsing).\n\nVariable t x cote : nat.\n\nLemma B_UA :\n B_basic t x cote -> G_Etat (S t) (S x + cote) -> UA (S t) (S x) cote.\nintros H; elim H; clear H; intros; apply make_UA; auto with arith.\napply\n D'D_D\n  with\n    (P := L_Etat)\n    (Q := B_Etat)\n    (R := G_Etat)\n    (P' := L_Etat)\n    (Q' := B_Etat); auto with arith.\nunfold loi, L_Etat, A_Etat, B_Etat, G_Etat; intros; simpl;\n rewrite H3; rewrite H4; rewrite H5; auto with arith.\n\nunfold loi, L_Etat, A_Etat, B_Etat, G_Etat; intros; simpl;\n rewrite H3; rewrite H4; rewrite H5; auto with arith.\n\nunfold loi, L_Etat, A_Etat, B_Etat, G_Etat; intros; simpl;\n rewrite H3; rewrite H4; rewrite H5; auto with arith.\nQed.\n\nLemma C_UAB :\n deux < cote ->\n C_basic t x cote ->\n G_Etat (S t) (S x + cote) ->\n G_Etat (S (S t)) (S x + cote) -> UAB (S t) (S x) cote.\nintros Hlt H; elim H; clear H; intros;\n apply (Rec3 _ _ _ _ (make_UAB (S t) (S x) cote)); \n auto with arith.\napply DD_D' with (P := L_Etat) (Q := C_Etat) (P' := L_Etat) (Q' := C_Etat);\n auto with arith.\nunfold loi, L_Etat, B_Etat, C_Etat, G_Etat; intros; simpl;\n rewrite H4; rewrite H5; rewrite H6; auto with arith.\n\nunfold loi, L_Etat, B_Etat, C_Etat, G_Etat; intros; simpl;\n rewrite H4; rewrite H5; rewrite H6; auto with arith.\n\nunfold loi, L_Etat, B_Etat, C_Etat, G_Etat; intros; simpl;\n rewrite H4; rewrite H5; rewrite H6; auto with arith.\n\nunfold loi, L_Etat, B_Etat, C_Etat, G_Etat; intros; simpl;\n rewrite H4; rewrite H5; rewrite H6; auto with arith.\n\nclear H0; intros H0;\n apply\n  D_D'D\n   with\n     (P := L_Etat)\n     (Q := C_Etat)\n     (P' := G_Etat)\n     (Q' := B_Etat)\n     (R' := G_Etat); auto with arith.\nunfold loi, L_Etat, A_Etat, B_Etat, C_Etat, G_Etat; intros;\n simpl; rewrite H4; rewrite H5; rewrite H6; \n auto with arith.\n\nunfold loi, L_Etat, A_Etat, B_Etat, C_Etat, G_Etat; intros;\n simpl; rewrite H4; rewrite H5; rewrite H6; \n auto with arith.\n\nunfold loi, L_Etat, A_Etat, B_Etat, C_Etat, G_Etat; intros;\n simpl; rewrite H4; rewrite H5; rewrite H6; \n auto with arith.\nQed.\n\nLemma A_ZCB :\n A_basic t x cote ->\n G_Etat (S t) (S x + cote) ->\n G_Etat (S (S t)) (S x + cote) -> ZCB (S t) (S x) cote.\nintros H; elim H; clear H; intros;\n apply (Rec3 _ _ _ _ (make_ZCB (S t) (S x) cote)); \n auto with arith.\napply DD_D with (P := L_Etat) (Q := A_Etat) (P' := L_Etat) (Q' := A_Etat);\n auto with arith.\nunfold loi, L_Etat, A_Etat, C_Etat, G_Etat; intros; simpl;\n rewrite H4; rewrite H5; rewrite H6; auto with arith.\n\nunfold loi, L_Etat, A_Etat, C_Etat, G_Etat; intros; simpl;\n rewrite H4; rewrite H5; rewrite H6; auto with arith.\n\nunfold loi, L_Etat, A_Etat, C_Etat, G_Etat; intros; simpl;\n rewrite H4; rewrite H5; rewrite H6; auto with arith.\n\nclear H0; intros H0;\n apply D_DD with (P := L_Etat) (Q := A_Etat) (P' := G_Etat) (Q' := C_Etat);\n auto with arith.\nunfold loi, L_Etat, A_Etat, B_Etat, C_Etat, G_Etat; intros;\n simpl; rewrite H4; rewrite H5; rewrite H6; \n auto with arith.\n\nunfold loi, L_Etat, A_Etat, B_Etat, C_Etat, G_Etat; intros;\n simpl; rewrite H4; rewrite H5; rewrite H6; \n auto with arith.\n\nunfold loi, L_Etat, A_Etat, B_Etat, C_Etat, G_Etat; intros;\n simpl; rewrite H4; rewrite H5; rewrite H6; \n auto with arith.\nQed.\n\nLemma B_ZCB :\n B_basic t x cote ->\n G_Etat (S t) (S x + cote) ->\n G_Etat (S (S t)) (S x + cote) ->\n G_Etat (S (S (S t))) (S x + cote) -> ZCB (S (S t)) (S x) cote.\nintros Hb; elim Hb; intros; elim B_UA; auto with arith; clear H0; intros Hlt H0;\n clear Hb Hlt; apply (Rec3 _ _ _ _ (make_ZCB (S (S t)) (S x) cote));\n auto with arith.\napply D_DD with (P := L_Etat) (Q := B_Etat) (P' := G_Etat) (Q' := A_Etat);\n auto with arith.\nunfold loi, L_Etat, A_Etat, B_Etat, C_Etat, G_Etat; intros;\n simpl; rewrite H5; rewrite H6; rewrite H7; \n auto with arith.\n\nunfold loi, L_Etat, A_Etat, B_Etat, C_Etat, G_Etat; intros;\n simpl; rewrite H5; rewrite H6; rewrite H7; \n auto with arith.\n\nunfold loi, L_Etat, A_Etat, B_Etat, C_Etat, G_Etat; intros;\n simpl; rewrite H5; rewrite H6; rewrite H7; \n auto with arith.\n\nclear H1; intros H1;\n apply DDD with (P := G_Etat) (Q := A_Etat) (P' := G_Etat) (Q' := C_Etat);\n auto with arith.\nunfold loi, L_Etat, A_Etat, B_Etat, C_Etat, G_Etat; intros;\n simpl; rewrite H5; rewrite H6; rewrite H7; \n auto with arith.\n\nunfold loi, L_Etat, A_Etat, B_Etat, C_Etat, G_Etat; intros;\n simpl; rewrite H5; rewrite H6; rewrite H7; \n auto with arith.\n\nunfold loi_droite, B_Etat, G_Etat; intros t0 x0; case x0; intros;\n simpl; rewrite H5; rewrite H6; auto with arith.\n\nunfold loi, L_Etat, A_Etat, B_Etat, C_Etat, G_Etat; intros;\n simpl; rewrite H5; rewrite H6; rewrite H7; \n auto with arith.\n\nunfold loi, L_Etat, A_Etat, B_Etat, C_Etat, G_Etat; intros;\n simpl; rewrite H5; rewrite H6; rewrite H7; \n auto with arith.\nQed.\n\nLemma C_ZCB :\n deux < cote ->\n C_basic t x cote ->\n G_Etat (S t) (S x + cote) ->\n G_Etat (S (S t)) (S x + cote) ->\n G_Etat (S (S (S t))) (S x + cote) ->\n G_Etat (S (S (S (S t)))) (S x + cote) -> ZCB (S (S (S t))) (S x) cote.\nintros; elim C_UAB; auto with arith; clear H H0 H1; intros;\n apply (Rec3 _ _ _ _ (make_ZCB (S (S (S t))) (S x) cote)); \n auto with arith.\napply\n D'DD\n  with\n    (P := G_Etat)\n    (Q := B_Etat)\n    (R := G_Etat)\n    (P' := G_Etat)\n    (Q' := A_Etat); auto with arith.\nunfold loi, A_Etat, B_Etat, C_Etat, G_Etat; intros; simpl;\n rewrite H5; rewrite H6; rewrite H7; auto with arith.\n\nunfold loi, A_Etat, B_Etat, C_Etat, G_Etat; intros; simpl;\n rewrite H5; rewrite H6; rewrite H7; auto with arith.\n\nunfold loi_droite, C_Etat, G_Etat; intros t0 x0; case x0; intros;\n simpl; rewrite H5; rewrite H6; auto with arith.\n\nunfold loi, A_Etat, B_Etat, C_Etat, G_Etat; intros; simpl;\n rewrite H5; rewrite H6; rewrite H7; auto with arith.\n\nunfold loi, A_Etat, B_Etat, C_Etat, G_Etat; intros; simpl;\n rewrite H5; rewrite H6; rewrite H7; auto with arith.\n\nclear H0; intros H0;\n apply DDD with (P := G_Etat) (Q := A_Etat) (P' := G_Etat) (Q' := C_Etat);\n auto with arith.\nunfold loi, A_Etat, B_Etat, C_Etat, G_Etat; intros; simpl;\n rewrite H5; rewrite H6; rewrite H7; auto with arith.\n\nunfold loi, A_Etat, B_Etat, C_Etat, G_Etat; intros; simpl;\n rewrite H5; rewrite H6; rewrite H7; auto with arith.\n\nunfold loi_droite, B_Etat, G_Etat; intros t0 x0; case x0; intros;\n simpl; rewrite H5; rewrite H6; auto with arith.\n\nunfold loi, A_Etat, B_Etat, C_Etat, G_Etat; intros; simpl;\n rewrite H5; rewrite H6; rewrite H7; auto with arith.\n\nunfold loi, A_Etat, B_Etat, C_Etat, G_Etat; intros; simpl;\n rewrite H5; rewrite H6; rewrite H7; auto with arith.\nQed.\n\nEnd construction.\n\nSection triangle_sup.\n\nVariable t x cote : nat.\n\nLemma ZCB_GLC :\n deux < cote ->\n ZCB t x cote ->\n Verticale (S (S t)) (x + cote) cote G_Etat ->\n Diag (S t + un) (x + un) (cote - un) G_Etat L_Etat C_Etat.\nintros Hlt Hz Hv; elim Hz; clear Hz; elim Hv; clear Hv; intros.\ndo 2 rewrite plus_un;\n apply\n  DDdollar_D with (P := G_Etat) (Q := C_Etat) (P' := G_Etat) (Q' := B_Etat);\n auto with arith.\nunfold loi, B_Etat, C_Etat, G_Etat, L_Etat; intros; simpl;\n rewrite H3; rewrite H4; rewrite H5; auto with arith.\n\nunfold loi, B_Etat, C_Etat, G_Etat, L_Etat; intros; simpl;\n rewrite H3; rewrite H4; rewrite H5; auto with arith.\n\nunfold loi, B_Etat, C_Etat, G_Etat, L_Etat; intros; simpl;\n rewrite H3; rewrite H4; rewrite H5; auto with arith.\n\napply lt_S_n; rewrite Sminus_un; auto with arith.\n\nrewrite Sminus_un; auto with arith.\n\nrewrite Sminus_un; auto with arith.\n\nrewrite <- (plus_zero (S (S t))); rewrite (plus_n_Sm x); rewrite Sminus_un;\n auto with arith.\nQed.\n\nLemma ZCB_l :\n deux < cote ->\n ZCB t x cote ->\n Verticale (S (S t)) (x + cote) cote G_Etat ->\n Semi_Diag (S t + deux) (x + deux) (cote - deux) G_Etat L_Etat.\nintros Hlt Hz Hv; elim Hz; elim Hv; intros.\ndo 2 rewrite plus_deux;\n apply\n  DD_d\n   with\n     (P := G_Etat)\n     (Q := B_Etat)\n     (R := G_Etat)\n     (P' := G_Etat)\n     (Q' := L_Etat)\n     (R' := C_Etat).\nunfold loi, B_Etat, G_Etat, L_Etat; intros; simpl; rewrite H3;\n rewrite H4; rewrite H5; auto with arith.\n\nunfold loi, B_Etat, G_Etat, L_Etat; intros; simpl; rewrite H3;\n rewrite H4; rewrite H5; auto with arith.\n\ndo 2 apply lt_S_n; rewrite SSminus_deux; auto with arith.\n\nrewrite SSminus_deux; auto with arith.\n\nrewrite <- (plus_un (S t)); rewrite <- (plus_un x); unfold deux;\n rewrite Sminus_aSb; auto with arith.\napply ZCB_GLC; auto with arith.\n\nrewrite <- (plus_un (S (S t))); do 2 rewrite plus_n_Sm; rewrite SSminus_deux;\n auto with arith.\nQed.\n\nLemma ZCB_ll :\n trois < cote ->\n ZCB t x cote ->\n Verticale (S (S t)) (x + cote) cote G_Etat ->\n Semi_Diag (S t + trois) (x + trois) (cote - trois) G_Etat L_Etat.\nintros Hlt Hz Hv; elim Hv; intros.\ndo 2 rewrite plus_trois;\n apply\n  Dd_d\n   with\n     (P := G_Etat)\n     (Q := L_Etat)\n     (R := C_Etat)\n     (P' := G_Etat)\n     (Q' := L_Etat).\nunfold loi, G_Etat, L_Etat; intros; simpl; rewrite H0;\n rewrite H1; rewrite H2; auto with arith.\n\nunfold loi, G_Etat, L_Etat; intros; simpl; rewrite H0;\n rewrite H1; rewrite H2; auto with arith.\n\ndo 3 apply lt_S_n; rewrite SSSminus_trois; auto with arith.\n\nrewrite <- (plus_un (S t)); rewrite <- (plus_un x); unfold trois;\n do 2 (rewrite Sminus_aSb; auto with arith).\napply ZCB_GLC; auto with arith.\n\napply lt_trans with (m := trois); auto with arith.\n\nrewrite <- (plus_deux (S t)); rewrite <- (plus_deux x); unfold trois;\n rewrite Sminus_aSb; auto with arith.\napply ZCB_l; auto with arith.\n\ndo 2 rewrite plus_n_Sm; rewrite plus_Snm_nSm;\n rewrite <- (plus_deux (S (S t))); rewrite SSSminus_trois; \n auto with arith.\napply H; auto with arith.\napply le_trans with (m := trois); auto with arith.\nQed.\n\nLemma ZCB_lll :\n forall dcote : nat,\n deux <= dcote ->\n dcote < cote ->\n ZCB t x cote ->\n Verticale (S (S t)) (x + cote) cote G_Etat ->\n Semi_Diag (S t + dcote) (x + dcote) (cote - dcote) G_Etat L_Etat.\nintros; elim H2; intros.\ngeneralize H0;\n apply\n  recur_nSn\n   with\n     (P := fun dcote : nat =>\n           dcote < cote ->\n           Semi_Diag (S t + dcote) (x + dcote) (cote - dcote) G_Etat L_Etat)\n     (n := deux).\nintros; apply ZCB_l; auto with arith.\n\nintros; apply ZCB_ll; auto with arith.\n\nintros; repeat rewrite <- plus_n_Sm;\n apply dd_d with (P := G_Etat) (Q := L_Etat) (P' := G_Etat) (Q' := L_Etat).\nunfold loi, G_Etat, L_Etat; intros; simpl; rewrite H7;\n rewrite H8; rewrite H9; auto with arith.\n\nunfold loi, G_Etat, L_Etat; intros; simpl; rewrite H7;\n rewrite H8; rewrite H9; auto with arith.\n\napply lt_O_minus; auto with arith.\n\ndo 2 (rewrite Sminus_aSb; auto with arith).\napply H4; apply lt_trans with (m := S (S p)); auto with arith.\n\napply lt_trans with (m := S (S p)); auto with arith.\n\ndo 2 rewrite plus_n_Sm; rewrite Sminus_aSb; auto with arith.\n\nrewrite plus_n_Sm; do 3 rewrite <- plus_S; do 2 rewrite plus_n_Sm;\n rewrite plus_assoc_reverse; rewrite le_plus_minus_r; \n auto with arith.\napply H3; apply le_trans with (m := S (S p)); auto with arith.\n\nauto with arith.\nQed.\n\nLemma ZCB_Ht1 :\n deux < cote ->\n ZCB t x cote ->\n Verticale (S (S t)) (x + cote) cote G_Etat ->\n Horizontale_t1 (t + S cote) x (cote - trois) G_Etat C_Etat L_Etat.\nintros; apply make_horizontale_t1.\nrewrite <- plus_Snm_nSm; elim H0; intros; elim H4; auto with arith.\n\nelim ZCB_GLC; auto with arith; intros H2 H3 H4; clear H2 H3 H4.\nrewrite plus_assoc_reverse; rewrite (plus_un x); rewrite plus_Snm_nSm;\n rewrite <- le_plus_minus; auto with arith.\napply le_trans with (m := deux); auto with arith.\n\napply make_horizontale; intros; elim ZCB_lll with (dcote := S (S dx));\n auto with arith; intros.\ngeneralize (H5 (cote - S (S dx)) 0); clear H4 H5; repeat rewrite plus_zero.\nrewrite plus_assoc_reverse; rewrite le_plus_minus_r;\n repeat rewrite plus_Snm_nSm; auto with arith.\nrewrite <- (SSSminus_trois cote); auto with arith.\n\nunfold deux; auto with arith.\n\nrewrite <- (SSSminus_trois cote); auto with arith.\nQed.\n\nEnd triangle_sup.\n\nSection Z_verticale.\n\nVariable t x cote : nat.\n\nLemma A_Vg :\n A_basic t x cote ->\n G_Etat (S t) (S x + cote) ->\n G_Etat (S (S t)) (S x + cote) -> Verticale (S t + cote) (S x) un G_Etat.\nintros; elim (A_ZCB t x cote); auto with arith.\nintros; apply vert_un.\nelim H3; auto with arith.\n\nelim H4; auto with arith.\nQed.\n\nLemma B_Vg :\n B_basic t x cote ->\n G_Etat (S t) (S x + cote) ->\n G_Etat (S (S t)) (S x + cote) ->\n G_Etat (S (S (S t))) (S x + cote) ->\n Verticale (S t + cote) (S x) deux G_Etat.\nintros; elim (B_ZCB t x cote); auto with arith.\nintros; elim (B_UA t x cote); auto with arith.\nintros; apply vert_deux.\nelim H7; auto with arith.\n\nelim H4; auto with arith.\n\nelim H5; auto with arith.\nQed.\n\nLemma C_Vg :\n deux < cote ->\n C_basic t x cote ->\n G_Etat (S t) (S x + cote) ->\n G_Etat (S (S t)) (S x + cote) ->\n G_Etat (S (S (S t))) (S x + cote) ->\n G_Etat (S (S (S (S t)))) (S x + cote) ->\n Verticale (S t + cote) (S x) trois G_Etat.\nintros; elim (C_ZCB t x cote); auto with arith.\nintros; elim (C_UAB t x cote); auto with arith.\nintros; apply vert_trois.\nelim H9; auto with arith.\n\nelim H10; auto with arith.\n\nelim H6; auto with arith.\n\nelim H7; auto with arith.\nQed.\n\nEnd Z_verticale.\n\nEnd reflect.", "meta": {"author": "coq-contribs", "repo": "firing-squad", "sha": "821676dce0353798b0651d058ffb22b65fb09097", "save_path": "github-repos/coq/coq-contribs-firing-squad", "path": "github-repos/coq/coq-contribs-firing-squad/firing-squad-821676dce0353798b0651d058ffb22b65fb09097/reflection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2669631611888173}}
{"text": "Require Import ssreflect ssrnat ssrbool seq eqtype Ring Group ident3.\nImport Ring.ideal.\n\nSection Aux1. Import ZC_tactic.\n\nContext (i j k l m n : nat) (a1 a2 b c d : R)\n        {ij : i != j} {ji : j != i} \n        {ik : i != k} {jk : j != k} {ki : k != i} {kj : k != j} \n        {kl : k != l} {il : i != l} {jl : j != l} {lk : l != k} {li : l != i} {lj : l != j}.\n\nLemma ZC1_I_01:\nZ' ij a1 b ^^ X ij c .* X' il d = \n  X' il ((1 + (c * b + 1) * a1 * b) * d) .*\n  X' jl (- (b * a1 * b * d)) .*\n  Z' ij a1 b ^^ X ij c.\nProof.\nremember (Z' ij a1 b ^^ X ij c) as RHS.\nrewrite {1}HeqRHS.\nrewrite (ZC1 _ _ k) //. ZCR. rewrite -?GA.\nrewrite (Z3_swap' k i l) //.\nrewrite (Z3_swap' j i l) //; simplify0.\nrewrite (X5_swap' j i k l) //. rexpand. rsimpl.\nrewrite (X5_swap' j k i l) //.\nrewrite (X4'_swap' j k l) //.\nrewrite (Z3_swap' j k l) //; simplify0.\nrewrite (X4_swap' k l j) // -X0'.\nrewrite -(Z5' k j i l) // X'def.\nrewrite (Z3_swap' k j l) //; simplify0.\n\nrexpand. rsimpl. rewrite -?plus_assoc.\n\nremember (b * a1 * b) as A0.\nremember (A0 * c * b * a1 * b) as A1.\nremember (A0 * a1 * b) as A2.\nremember (A1 * c * b * a1 * b * d) as A3.\nremember (A1 * a1 * b * d) as A4.\nremember (A2 * c * b * a1 * b * d) as A5.\nremember (A2 * a1 * b * d) as A6.\n\ncancm (A1 * d). cancm (A2 * d). cancm A3. cancm A4. cancm A5. \n\nremember (a1 * b) as B0.\nremember (B0 * c * b * a1 * b) as B1.\nremember (B0 * a1 * b) as B2.\nremember (B1 * c * b * a1 * b * d) as B3.\nremember (B2 * c * b * a1 * b * d) as B4.\nremember (B1 * a1 * b * d) as B5.\nremember (B2 * a1 * b * d) as B6.\n\ncancm B3. cancm B4. cancm B5.\n\nrewrite (Z4'_swap' k j l) // -X0'. simplify0.\nrewrite (X4_swap' k l j) // -X0'.\nrewrite (X4'_swap' i j l) //.\nrewrite (Z3_swap' i j l) //; simplify0.\nrewrite (X4_swap' j l i) // -X0'.\nrewrite (X5_swap' i j k l) //.\nrewrite (X4'_swap' i k l) //.\nrewrite (X5_swap' i k j l) //.\nrewrite (Z3_swap' i k l) //; simplify0.\nrewrite (X4_swap' k l i) //.\nrewrite (X4_swap' j l i) // -X0'.\nrewrite (X5_swap' k j i l) //.\nrewrite (Z3_swap' k j l) //; simplify0.\nrewrite (X4'_swap' k j l) // -X0'.\nrewrite (Z3_swap _ _ _ k i l) //; simplify0.\nrewrite (X5_swap' k i j l) //.\nrewrite (X4'_swap' k i l) //.\nrewrite (X4_swap' j l k) // -X0'.\n\nsubst. simplify0. rexpand. rsimpl. rewrite -?plus_assoc -?mul_assoc.\n\nremember (c * b * a1 * b) as C0.\nremember (a1 * b * a1 * b) as C1.\nremember (a1 * b * c * b * a1 * b) as C2.\nremember (C2 * a1 * b) as C3.\nremember (C2 * c * b * a1 * b) as C4.\nremember (C1 * a1 * b) as C5.\nremember (C1 * c * b * a1 * b) as C6.\nremember (C3 * a1 * b) as C7.\nremember (C3 * c * b * a1 * b) as C8.\nremember (C6 * a1 * b) as C9.\nremember (C6 * c * b * a1 * b) as C10.\nremember (C4 * a1 * b) as C11.\nremember (C4 * c * b * a1 * b) as C12.\nremember (C5 * a1 * b) as C13.\nremember (C5 * c * b * a1 * b) as C14.\n\ncancm (C1 * d). cancm (C2 * d). cancm (C3 * d). cancm (C4 * d).\ncancm (C5 * d). cancm (C6 * d). cancm (C7 * d). cancm (C8 * d).\ncancm (C9 * d). cancm (C10 * d). cancm (C11 * d). cancm (C12 * d).\ncancm (C13 * d). rewrite inv_r X'zero GId. subst.\n\nremember (c * b * a1 * b) as D1.\nremember (D1 * c * b) as D2.\nremember (D1 * a1 * b) as D3.\nremember (D2 * a1 * b) as D4.\nremember (D3 * a1 * b) as D5.\nremember (D3 * c * b) as D6.\nremember (D4 * a1 * b) as D7.\nremember (D4 * c * b) as D8.\nremember (D6 * a1 * b) as D9.\nremember (D8 * a1 * b) as D10.\n\ncancm (D4 * d). cancm (D3 * d). cancm (D10 * d). cancm (D9 * d).\ncancm (D5 * d). subst.\n\nremember (b * a1 * b) as E1.\nremember (E1 * c * b) as E2.\nremember (E1 * a1 * b) as E3.\nremember (E2 * a1 * b) as E4.\n\ncancm (E4 * d). subst.\n\nrewrite (ZC1 _ _ k) //. ZCR. \nrewrite -?GA. rexpand. rsimpl. by rewrite -?plus_assoc. Qed.\n\n\nEnd Aux1.", "meta": {"author": "sxhya", "repo": "cgt", "sha": "68bf6f901068e9ec3c56284c2883513c524b0981", "save_path": "github-repos/coq/sxhya-cgt", "path": "github-repos/coq/sxhya-cgt/cgt-68bf6f901068e9ec3c56284c2883513c524b0981/ident4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2669367346441609}}
{"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 Tools.Matches.\nFrom Pyrosome.Lang Require Import SimpleVSubst SimpleVCPS SimpleUnit.\nImport Core.Notations.\n(*TODO: repackage this in compilers*)\nImport CompilerDefs.Notations.\n\nRequire Coq.derive.Derive.\n\n\nNotation compiler := (compiler string).\n\nDefinition prod_cc_def : lang :=\n  {[l/subst\n  [:| \"G\" : #\"env\", \"A\" : #\"ty\", \"B\" : #\"ty\",\n      \"v\" : #\"val\" \"G\" (#\"prod\" \"A\" \"B\")\n       -----------------------------------------------\n       #\".1\" \"v\" : #\"val\" \"G\" \"A\"\n  ];\n  [:| \"G\" : #\"env\", \"A\" : #\"ty\", \"B\" : #\"ty\",\n      \"v\" : #\"val\" \"G\" (#\"prod\" \"A\" \"B\")\n       -----------------------------------------------\n       #\".2\" \"v\" : #\"val\" \"G\" \"B\"\n  ];\n   [:= \"G\" : #\"env\", \"A\" : #\"ty\",\n      \"g\" : #\"val\" \"G\" \"A\",\n      \"B\" : #\"ty\",\n      \"v\" : #\"val\" \"G\" \"B\"\n      ----------------------------------------------- (\"proj 1\")\n      #\".1\" (#\"pair\" \"g\" \"v\") = \"g\" : #\"val\" \"G\" \"A\"\n  ];\n  [:= \"G\" : #\"env\", \"A\" : #\"ty\",\n      \"g\" : #\"val\" \"G\" \"A\",\n      \"B\" : #\"ty\",\n      \"v\" : #\"val\" \"G\" \"B\"\n      ----------------------------------------------- (\"proj 2\")\n      #\".2\" (#\"pair\" \"g\" \"v\") = \"v\" : #\"val\" \"G\" \"B\"\n  ];\n  [:= \"G\" : #\"env\", \"A\" : #\"ty\",\n      \"B\" : #\"ty\",\n      \"v\" : #\"val\" \"G\" (#\"prod\" \"A\" \"B\")\n      ----------------------------------------------- (\"negative pair eta\")\n      #\"pair\" (#\".1\" \"v\") (#\".2\" \"v\") = \"v\" : #\"val\" \"G\" (#\"prod\" \"A\" \"B\")\n  ]]}.\n\n\nDerive prod_cc\n       SuchThat (elab_lang_ext (cps_prod_lang ++ block_subst ++value_subst) prod_cc_def prod_cc)\n       As prod_cc_wf.\nProof. auto_elab. Qed.\n#[export] Hint Resolve prod_cc_wf : elab_pfs.\n\nDefinition cc_lang_def : lang :=\n  {[l/subst\n      [:| \"A\" : #\"ty\"\n          -----------------------------------------------\n          #\"neg\" \"A\" : #\"ty\"\n      ];\n  [:| \"G\" : #\"env\",\n      \"A\" : #\"ty\",\n      \"B\" : #\"ty\",\n      \"e\" : #\"blk\" (#\"ext\" #\"emp\" (#\"prod\" \"A\" \"B\")),\n      \"v\" : #\"val\" \"G\" \"A\"\n      -----------------------------------------------\n      #\"closure\" \"B\" \"e\" \"v\" : #\"val\" \"G\" (#\"neg\" \"B\")\n   ];\n   [:| \"G\" : #\"env\",\n       \"A\" : #\"ty\",\n       \"v1\" : #\"val\" \"G\" (#\"neg\" \"A\"),\n       \"v2\" : #\"val\" \"G\" \"A\"\n      -----------------------------------------------\n      #\"jmp\" \"v1\" \"v2\" : #\"blk\" \"G\"\n   ];\n  [:= \"G\" : #\"env\",\n      \"A\" : #\"ty\",\n      \"B\" : #\"ty\",\n      \"e\" : #\"blk\" (#\"ext\" #\"emp\" (#\"prod\" \"A\" \"B\")),\n      \"v\" : #\"val\" \"G\" \"A\",\n      \"v'\" : #\"val\" \"G\" \"B\"\n      ----------------------------------------------- (\"jmp_beta\")\n      #\"jmp\" (#\"closure\" \"B\" \"e\" \"v\") \"v'\"\n      = #\"blk_subst\" (#\"snoc\" #\"forget\" (#\"pair\" \"v\" \"v'\")) \"e\"\n      : #\"blk\" \"G\"\n  ];\n  [:= \"A\" : #\"ty\",\n      \"B\" : #\"ty\",\n      \"v\" : #\"val\" (#\"ext\" #\"emp\" \"A\") (#\"neg\" \"B\")\n      ----------------------------------------------- (\"clo_eta\")\n      #\"closure\" \"B\"\n        (#\"jmp\" (#\"val_subst\" (#\"snoc\" #\"wkn\" (#\".1\" #\"hd\")) \"v\") (#\".2\" #\"hd\"))\n        #\"hd\"\n      = \"v\"\n      : #\"val\" (#\"ext\" #\"emp\" \"A\") (#\"neg\" \"B\")\n  ]]}.\n\n\nDerive cc_lang\n       SuchThat (elab_lang_ext (prod_cc ++ cps_prod_lang ++ block_subst ++value_subst)\n                               cc_lang_def\n                               cc_lang)\n       As cc_lang_wf.\nProof. auto_elab. Qed.\n#[export] Hint Resolve cc_lang_wf : elab_pfs.\n\n\nDefinition subst_cc_def : compiler :=\n  match # from (block_subst ++ value_subst) with\n  | {{s #\"env\" }} => {{s #\"ty\"}}\n  | {{s #\"val\" \"G\" \"B\"}} => {{s #\"val\" (#\"ext\" #\"emp\" \"G\") \"B\"}}\n  | {{s #\"blk\" \"G\"}} => {{s #\"blk\" (#\"ext\" #\"emp\" \"G\")}}\n  | {{s #\"sub\" \"G\" \"G'\"}} => {{s #\"val\" (#\"ext\" #\"emp\" \"G\") \"G'\"}}\n  | {{e #\"cmp\" \"G\" \"G'\" \"A\" \"g\" \"g'\"}} =>\n    {{e #\"val_subst\" (#\"snoc\" #\"wkn\" \"g\") \"g'\"}}\n  | {{e #\"emp\"}} => {{e#\"unit\"}}\n  | {{e #\"forget\"}} => {{e# \"tt\"}}\n  | {{e #\"ext\" \"A\" \"B\" }} => {{e #\"prod\" \"A\" \"B\"}}\n  | {{e #\"snoc\" \"G\" \"G'\"\"g\" \"A\" \"v\"}} =>\n    {{e #\"pair\" \"g\" \"v\"}}\n  | {{e #\"id\" \"G\"}} => {{e #\"hd\"}}\n  | {{e #\"hd\" \"G\" \"A\"}} => {{e #\".2\" #\"hd\"}}\n  | {{e #\"wkn\" \"G\" \"A\"}} => {{e #\".1\" #\"hd\"}}\n  | {{e #\"val_subst\" \"G\" \"G'\" \"g\" \"A\" \"v\"}} =>\n    {{e #\"val_subst\" (#\"snoc\" #\"wkn\" \"g\") \"v\"}}\n  | {{e #\"blk_subst\" \"G\" \"G'\" \"g\" \"e\"}} =>\n    {{e #\"blk_subst\" (#\"snoc\" #\"wkn\" \"g\") \"e\"}}\n  end.\n\nDerive subst_cc\n       SuchThat (elab_preserving_compiler []\n                                          (unit_eta\n                                             ++ unit_lang\n                                             ++ prod_cc\n                                             ++ cps_prod_lang\n                                             ++ block_subst\n                                             ++value_subst)\n                                          subst_cc_def\n                                          subst_cc\n                                          (block_subst++value_subst))\n       As subst_cc_preserving.\nProof.\n  auto_elab_compiler.\n  cleanup_elab_after\n    (reduce; eredex_steps_with unit_eta \"unit eta\").\nQed.\n#[export] Hint Resolve subst_cc_preserving : elab_pfs.\n\n\n(*TODO: redo for positive products *)\nDefinition prod_cc_compile_def : compiler :=\n  match # from cps_prod_lang with\n  | {{e #\"pm_pair\" \"G\" \"A\" \"B\" \"v\" \"e\"}} =>\n    {{e #\"blk_subst\"\n        (#\"snoc\" #\"wkn\" (#\"pair\" (#\"pair\" {ovar 0} (#\".1\" \"v\")) (#\".2\" \"v\")))\n        \"e\"}}\n  end.\n\n\n(*TODO: move to value_subst? could conflict w/ cmp_forget\n  not currently used\n*)\n(*TODO: generalize? reverse for tactics?*)\nDefinition forget_eq_wkn_def : lang :=\n  {[l\n      [:= \"A\" : #\"ty\"\n         ----------------------------------------------- (\"wkn_emp_forget\")\n         #\"forget\" = #\"wkn\"\n         : #\"sub\" (#\"ext\" #\"emp\" \"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\n\nDerive prod_cc_compile\n       SuchThat (elab_preserving_compiler subst_cc\n                                          ( unit_eta\n                                             ++ unit_lang\n                                             ++ prod_cc\n                                             ++ cps_prod_lang\n                                             ++ block_subst\n                                             ++value_subst)\n                                          prod_cc_compile_def\n                                          prod_cc_compile\n                                          cps_prod_lang)\n       As prod_cc_preserving.\nProof. auto_elab_compiler. Qed.\n#[export] Hint Resolve prod_cc_preserving : elab_pfs.\n\n\nDefinition cc_def : compiler :=\n  match # from (cps_lang) with\n  | {{e #\"neg\" \"A\" }} => {{e #\"neg\" \"A\"}}\n  | {{e #\"cont\" \"G\" \"A\" \"e\"}} =>\n    {{e #\"closure\" \"A\" \"e\" #\"hd\"}}\n  | {{e #\"jmp\" \"G\" \"A\" \"v1\" \"v2\"}} =>\n    {{e #\"jmp\" \"v1\" \"v2\" }}\n  end.\n\n \nDerive cc\n       SuchThat (elab_preserving_compiler (prod_cc_compile++subst_cc)\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                                          cc_def\n                                          cc\n                                          cps_lang)\n       As cc_preserving.\nProof.\n  auto_elab_compiler.\n  cleanup_elab_after\n  (reduce;\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 cc_preserving : elab_pfs.\n\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/SimpleVCC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.26693672851995126}}
{"text": "Require Import Coq.Program.Syntax.\nRequire Export ZArith.\nRequire Import Coq.Program.Basics.\nRequire Import SetoidTactics.\nRequire Import SetoidClass.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Strings.Ascii.\nRequire Import Coq.Lists.List.\n\nRequire Import HDI.Util.\nRequire Import HDI.Syntax.\nRequire Import HDI.Heap.\nRequire Import HDI.OpSem.\nRequire Import HDI.Bisimulation.\nRequire HDI.HoareDoubles.\nRequire HDI.HoareDoublesI.\n\nLocal Open Scope Z.\nLocal Open Scope stmt.\nLocal Open Scope char.\nLocal Open Scope bool.\n\nSection Implementation.\n\n  CoFixpoint parseWS a : stmt:=\n    x <- read a;\n    if x =? zero then\n      ret 1 (* Title Case *)\n    else if x =? \" \" then\n      parseWS (1+a)\n    else if (negb (is_letterZ x)) || (is_upperZ x) then\n      parseLetters (1+a)\n    else\n      ret 0 (* not type case *)\n  with parseLetters (a:Z) :=\n    x <- read a;\n    if x =? zero then\n      ret 1 (* Title Case *)\n    else if x =? \" \" then\n      parseWS (1+a)\n    else if negb (is_letterZ x) || is_lowerZ x then\n        parseLetters (1+a)\n      else\n        ret 0 (* cAps in woRd *).\n\n  Definition isTitleCase := parseWS.\n\n  Lemma unfold_parseWS: forall a,\n    parseWS a =\n    x <- read a;\n    if x =? zero then\n      ret 1 (* Title Case *)\n    else if x =? \" \" then\n      parseWS (1+a)\n    else if (negb (is_letterZ x)) || (is_upperZ x) then\n      parseLetters (1+a)\n    else\n      ret 0 (* not type case *).\n  Proof. intros; rewrite (unfold_stmt_eq (parseWS a)); reflexivity. Qed.\n\n  Lemma unfold_parseLetters: forall a,\n    parseLetters a =\n    x <- read a;\n    if x =? zero then\n      ret 1 (* Title Case *)\n    else if x =? \" \" then\n      parseWS (1+a)\n    else if negb (is_letterZ x) || is_lowerZ x then\n        parseLetters (1+a)\n      else\n        ret 0 (* cAps in woRd *).\n  Proof. intros; rewrite (unfold_stmt_eq (parseLetters a)); reflexivity. Qed.\n\nEnd Implementation.\n\n\n\nSection Verification.\n\n  Fixpoint is_title_case_ (in_word: bool) (s: string) {struct s} : bool :=\n    match s with\n    | String x s' =>\n      if ascii_dec x zero then\n        true (* Title Case *)\n      else if ascii_dec x \" \" then\n        is_title_case_ false s'\n      else if in_word then\n        if negb (is_letter x) || is_lower x then\n          is_title_case_ true s'\n        else\n          false  (* cAps in woRd *)\n      else\n        let check_word x s :=\n          if (negb (is_letter x)) || (is_upper x) then\n            is_title_case_ true s'\n          else\n            false (* not type case *)\n        in\n        check_word x s'\n    | empty => true (* Title Case *)\n    end.\n  Definition is_title_case s := is_title_case_ false s.\n\n  Goal is_title_case \"\" = true. reflexivity. Abort.\n  Goal is_title_case \"  \" = true. reflexivity. Abort.\n  Goal is_title_case \"67\" = true. reflexivity. Abort.\n  Goal is_title_case \"A\" = true. reflexivity. Abort.\n  Goal is_title_case \"z\" = false. reflexivity. Abort.\n  Goal is_title_case \"Hello World\" = true. reflexivity. Abort.\n  Goal is_title_case \"Hello world\" = false. reflexivity. Abort.\n  Goal is_title_case \"hello World\" = false. reflexivity. Abort.\n  Goal is_title_case \"HeLlo World\" = false. reflexivity. Abort.\n  Goal is_title_case \"  Hello     World  \" = true. reflexivity. Abort.\n  Goal is_title_case \"8ello World\" = true. reflexivity. Abort.\n  Goal is_title_case \"8ellO World\" = false. reflexivity. Abort.\n\n  Lemma is_title_case_in_word: forall s,\n    is_title_case_ true s = is_title_case (String \"A\" s).\n  Proof. intros; reflexivity. Qed.\n\n  Section HD.\n    Import HoareDoubles.\n\n    Lemma isTitleCase_ok: forall a s F k,\n      |-{{a |->0 s && F}}  k (if is_title_case s then 1 else 0) ->\n      |-{{a |->0 s && F}}  isTitleCase a >>= k.\n    Proof.\n    Abort.\n\n  End HD.\n\n  Import HoareDoublesI.\n  Require Import CoInduction.\n\n  Definition tc_ret s := if is_title_case s then 1 else 0.\n\n  Lemma parseLetters_ind_ok: forall (I: predicate heap -> stmt -> Prop) a s F k,\n    I ||= {{a |->0 s && F}}  k (tc_ret (\"A\"++s)%string) ->\n    (forall a s0 s' F,\n      append s0 s' = s ->\n      I ||= {{a |->0 s' && F}}  k (tc_ret s') ->\n      I ||- {{a |->0 s' && F}} (parseWS a >>= k)) ->\n    I ||- {{a |->0 s && F}}  parseLetters a >>= k.\n  Proof.\n    intros I a s F k.\n    intros Hsafe_k Hsafe_sws.\n    unfold tc_ret in Hsafe_k; simpl in Hsafe_k.\n    rewrite <-is_title_case_in_word in Hsafe_k.\n    revert a F Hsafe_k.\n    induction s; simpl; intros.\n    * rewrite unfold_parseLetters.\n    step.\n    mcase_eq.\n    step; auto.\n    *\n    (* x <- parseLetters a; k x *)\n    rewrite unfold_parseLetters.\n    (* x <- act (read a); *)\n    step.\n    (* (if x =? Z_of_ascii zero *)\n    mcase_eq.\n    (*  then ret 1 *)\n    { apply Z_of_ascii_inv in H; subst a.\n      step; auto.\n    }\n    (*  else if x =? Z_of_ascii \" \" *)\n    destruct (ascii_dec a zero); subst.\n    congruence.\n    destruct (ascii_dec a \" \"); subst.\n    (*   then parseWS (1 + a) *)\n    { rewrite Z.eqb_refl.\n      rewrite str0_cons, (inter_comm ((1+a0) |->0 _)), <-!inter_assoc in Hsafe_k |- *.\n      apply hd'_safe.\n      eapply (Hsafe_sws (1+a0) \" \"%string s); auto.\n    }\n    rewrite (proj2 (Z.eqb_neq _ _)); [ | apply Z_of_ascii_neq; auto ].\n    (*   else if negb (is_letterZ x) || is_lowerZ x *)\n    rewrite is_letterZ_of_ascii, is_lowerZ_of_ascii.\n    rewrite is_letter_eq in Hsafe_k |- *.\n    rewrite Bool.negb_orb, Bool.orb_andb_distrib_l, negb_orb_cancel_l in Hsafe_k |- *.\n    rewrite Bool.andb_true_r in Hsafe_k |- *.\n    mcase_eq.\n    (*     then parseLetters (1 + a) *)\n    { rewrite str0_cons, (inter_comm ((1+a0) |->0 _)), <-!inter_assoc in Hsafe_k |- *.\n      apply hd'_safe.\n      apply IHs; intros; auto.\n      eapply Hsafe_sws with (s0:=String a s0); auto.\n      subst s.\n      reflexivity.\n    }\n    (*     else ret 0 >>= k *)\n    step; assumption.\n  Qed.\n\n  Lemma parseWS_ind_ok: forall I a s F k,\n    I ||= {{a |->0 s && F}}  k (tc_ret s) ->\n    I ||- {{a |->0 s && F}}  parseWS a >>= k.\n  Proof.\n    intros I a s F k Hsafe_k.\n    unfold tc_ret, is_title_case in Hsafe_k.\n    revert Hsafe_k.\n    remember (append EmptyString s) as s1.\n    revert Heqs1.\n    generalize EmptyString as s0.\n    revert a s F.\n    induction s1; simpl; intros; subst.\n    * rewrite unfold_parseWS.\n    destruct s0, s; try solve [inversion Heqs1].\n    step.\n    mcase_eq.\n    step; auto.\n    *\n    (* x <- parseWS a; k x *)\n    rewrite unfold_parseWS.\n    (* x <- read a *)\n    step.\n    (* if x =? Z_of_ascii zero *)\n    mcase_eq.\n    (* then ret 1 *)\n    { step; auto.\n      repeat mcase_eq in *.\n      destruct s0; inversion Heqs1; subst; eauto.\n      apply Z_of_ascii_inv in H; subst; auto.\n      apply Z_of_ascii_inv in H; subst; auto.\n      simpl in H0; discriminate.\n    }\n    (* else if x =? \" \" *)\n    destruct s.\n    compute in H; exfalso; eauto.\n    rewrite str0_cons, (inter_comm ((1+a0) |->0 _)), <-!inter_assoc in Hsafe_k |- *.\n    rewrite is_letterZ_of_ascii, is_upperZ_of_ascii.\n    unfold is_title_case_ in Hsafe_k.\n    fold is_title_case_ in Hsafe_k.\n    destruct (ascii_dec a1 zero); subst.\n    congruence.\n    destruct (ascii_dec a1 \" \"); subst.\n    (* then parseWS (1+a) *)\n    { rewrite Z.eqb_refl.\n      apply hd'_safe; eauto.\n      destruct s0; inversion Heqs1; subst; eauto.\n      eapply IHs1 with (s1:=\"\"%string); auto.\n      eapply IHs1 with (s2:= (s0++\" \")%string); auto.\n      clear.\n      induction s0; simpl in *; congruence.\n    }\n    (* else if (negb (is_letterZ x)) || (is_upperZ x) *)\n    rewrite (proj2 (Z.eqb_neq _ _)); [ | apply Z_of_ascii_neq; auto ].\n    repeat mcase_eq.\n    (* then parseLetters (1+a) *)\n    apply hd'_safe, parseLetters_ind_ok; intros; subst; eauto.\n    destruct s0; inversion Heqs1; subst; eauto.\n    eapply IHs1 with (s1:=(s0++String a1 s2)%string); eauto.\n    clear; induction s0; simpl in *; congruence.\n    (* else ret 0 (* not type case *) *)\n    step; auto.\n  Qed.\n\n\n\n\n  Lemma parseLetters_ok: forall (I0 I: predicate heap -> stmt -> Prop) a s F k,\n    I0 ||= {{a |->0 s && F}}  k (tc_ret (\"A\"++s)%string) ->\n    incl_inv I0 I ->\n    (forall a s F,\n      I0 ||= {{a |->0 s && F}}  k (tc_ret s) ->\n      I ||= {{a |->0 s && F}} parseWS a >>= k) ->\n    I ||- {{a |->0 s && F}}  parseLetters a >>= k.\n  Proof.\n    intros I0 I a s F k.\n    intros Hsafe_k HI0 Hsafe_sws.\n    unfold tc_ret in Hsafe_k; simpl in Hsafe_k.\n    rewrite <-is_title_case_in_word in Hsafe_k.\n    revert a s F Hsafe_k.\n    hd_coind.\n    (* x <- parseLetters a; k x *)\n    rewrite unfold_parseLetters.\n    (* x <- act (read a); *)\n    step.\n    (* if x =? Z_of_ascii zero *)\n    mcase_eq.\n    (*   then ret 1 *)\n    { rewrite HI0, H0 in Hsafe_k.\n      destruct s; simpl in *.\n      step; auto.\n      apply Z_of_ascii_inv in H1; subst.\n      simpl in *.\n      step; auto.\n    }\n    destruct s.\n    compute in H1; congruence.\n    (*   else if x =? Z_of_ascii \" \" *)\n    unfold is_title_case in Hsafe_k.\n    simpl in Hsafe_k.\n    destruct (ascii_dec a0 zero); subst.\n    congruence.\n    destruct (ascii_dec a0 \" \"); subst.\n    (*   then parseWS (1 + a) *)\n    { rewrite Z.eqb_refl.\n      rewrite str0_cons, (inter_comm ((1+a) |->0 _)), <-!inter_assoc in Hsafe_k |- *.\n      rewrite <-H0.\n      apply Hsafe_sws; assumption.\n    }\n    rewrite (proj2 (Z.eqb_neq _ _)); [ | apply Z_of_ascii_neq; auto ].\n    (*   else if negb (is_letterZ x) || is_lowerZ x *)\n    rewrite is_letterZ_of_ascii, is_lowerZ_of_ascii.\n    rewrite is_letter_eq in Hsafe_k |- *.\n    rewrite Bool.negb_orb, Bool.orb_andb_distrib_l, negb_orb_cancel_l in Hsafe_k |- *.\n    rewrite Bool.andb_true_r in Hsafe_k |- *.\n    mcase_eq.\n    (*     then parseLetters (1 + a) *)\n    rewrite str0_cons, (inter_comm ((1+a) |->0 _)), <-!inter_assoc in Hsafe_k |- *.\n    eauto.\n    (*   else ret 0 >>= k *)\n    rewrite <-H0, <-HI0.\n    step; assumption.\n  Qed.\n\n  Lemma parseWS_ok: forall I a s F k,\n    I ||= {{a |->0 s && F}}  k (tc_ret s) ->\n    I ||- {{a |->0 s && F}}  parseWS a >>= k.\n  Proof.\n    intros I a s F k Hsafe_k.\n    unfold tc_ret, is_title_case in Hsafe_k.\n    revert a s F Hsafe_k.\n    hd_coind.\n    (* x <- parseWS a; k x *)\n    rewrite unfold_parseWS.\n    (* x <- read a *)\n    step.\n    (* if x =? Z_of_ascii zero *)\n    mcase_eq.\n    (* then ret 1 *)\n    { rewrite H0 in Hsafe_k.\n      destruct s; simpl in *.\n      step; auto.\n      apply Z_of_ascii_inv in H1; subst.\n      simpl in *.\n      step; auto.\n    }\n    destruct s.\n    compute in H1; congruence.\n    (* else if x =? \" \" *)\n    rewrite str0_cons, (inter_comm ((1+a) |->0 _)), <-!inter_assoc in Hsafe_k |- *.\n    simpl (is_title_case_ _ _) in Hsafe_k.\n    rewrite is_letterZ_of_ascii, is_upperZ_of_ascii.\n    destruct (ascii_dec a0 zero); subst.\n    congruence.\n    destruct (ascii_dec a0 \" \"); subst.\n    (* then parseWS (1+a) *)\n    rewrite Z.eqb_refl; auto.\n    (* else if (negb (is_letterZ x)) || (is_upperZ x) *)\n    rewrite (proj2 (Z.eqb_neq _ _)); [ | apply Z_of_ascii_neq; auto ].\n    repeat mcase_eq.\n    (* then parseLetters (1+a) *)\n    apply hd'_safe, parseLetters_ok with (I0:=I); auto.\n    (* else ret 0 (* not type case *) *)\n    rewrite <-H0; step; assumption.\n  Qed.\n\n\n\n  Lemma isTitleCase_ok: forall I a s F k,\n    I ||= {{a |->0 s && F}}  k (if is_title_case s then 1 else 0) ->\n    I ||- {{a |->0 s && F}}  isTitleCase a >>= k.\n  Proof.\n    intros I a s F k Hsafe_k.\n    unfold isTitleCase.\n    apply parseWS_ok; assumption.\n  Qed.\n\n\nEnd Verification.\n", "meta": {"author": "siegebell", "repo": "hdcoind", "sha": "572e66a00767ee1e2c0677befe9d2db2271df0a7", "save_path": "github-repos/coq/siegebell-hdcoind", "path": "github-repos/coq/siegebell-hdcoind/hdcoind-572e66a00767ee1e2c0677befe9d2db2271df0a7/TitleCaseExample.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.26693672851995126}}
{"text": "Require Export Iron.Language.SystemF2Effect.Value.\nRequire Export Iron.Language.SystemF2Effect.Store.\nRequire Export Iron.Language.SystemF2Effect.Step.Frame.\nRequire Export Iron.Language.SystemF2Effect.Step.TypeF.\n\n(********************************************************************)\n(* Type of an expression in a frame context. *)\nInductive TypeC\n   :  kienv -> tyenv\n   -> stenv -> stprops\n   -> stack -> exp\n   -> ty    -> ty -> Prop :=\n | TcExp\n   :  forall ke te se sp fs x1 t1 e1 t2 e2 e3\n   ,  EquivT ke sp (TSum e1 e2) e3 KEffect\n   -> TypeX  ke te se sp x1 t1 e1\n   -> TypeF  ke te se sp fs t1 t2 e2\n   -> TypeC  ke te se sp fs x1 t2 e3.\n\nHint Constructors TypeC.\n\n\nLtac inverts_typec :=\n repeat\n  (try (match goal with\n        | [H: TypeC _ _ _ _ _ _ _ _ |- _ ] => inverts H\n        end);\n   try inverts_typef).\n\n\n(********************************************************************)\nLemma typeC_kindT_effect\n :  forall ke te se sp fs x t e\n ,  TypeC  ke te se sp fs x t e\n -> KindT  ke sp e KEffect.\nProof.\n intros.\n induction H; eauto.\nQed.\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/Step/TypeC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878414043814, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2669367223957415}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.NArith.NArith.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\nRequire Import Coq.derive.Derive.\nRequire Import Crypto.Util.Option.\nRequire Crypto.Util.Tuple.\nRequire Crypto.Util.OptionList.\nImport ListNotations.\n\nLocal Open Scope list_scope.\n\nLocal Set Implicit Arguments.\nLocal Set Boolean Equality Schemes.\nLocal Set Decidable Equality Schemes.\nLocal Set Primitive Projections.\n\nInductive REG :=\n|     rax |     rcx |     rdx |     rbx | rsp  | rbp  | rsi  | rdi  | r8  | r9  | r10  | r11  | r12  | r13  | r14  | r15\n|     eax |     ecx |     edx |     ebx | esp  | ebp  | esi  | edi  | r8d | r9d | r10d | r11d | r12d | r13d | r14d | r15d\n|      ax |      cx |      dx |      bx |  sp  |  bp  |  si  |  di  | r8w | r9w | r10w | r11w | r12w | r13w | r14w | r15w\n| ah | al | ch | cl | dh | dl | bh | bl |  spl |  bpl |  sil |  dil | r8b | r9b | r10b | r11b | r12b | r13b | r14b | r15b\n.\n\nDefinition CONST := Z.\nCoercion CONST_of_Z (x : Z) : CONST := x.\n\nInductive AccessSize := byte | word | dword | qword.\nCoercion bits_of_AccessSize (x : AccessSize) : N\n  := match x with\n     | byte => 8\n     | word => 16\n     | dword => 32\n     | qword => 64\n     end.\n\nRecord MEM := { mem_bits_access_size : option AccessSize ; mem_base_reg : option REG ; mem_scale_reg : option (Z * REG) ; mem_base_label : option string ; mem_offset : option Z }.\n\nDefinition mem_of_reg (r : REG) : MEM :=\n  {| mem_base_reg := Some r ; mem_offset := None ; mem_scale_reg := None ; mem_bits_access_size := None ; mem_base_label := None |}.\n\nInductive FLAG := CF | PF | AF | ZF | SF | OF.\n\nInductive OpPrefix :=\n| rep\n| repz\n| repnz\n.\n\nInductive OpCode :=\n| adc\n| adcx\n| add\n| adox\n| and\n| bzhi\n| call\n| clc\n| cmovb\n| cmovc\n| cmovnz\n| cmp\n| db\n| dd\n| dec\n| dq\n| dw\n| imul\n| inc\n| je\n| jmp\n| lea\n| mov\n| movzx\n| mul\n| mulx\n| pop\n| push\n| rcr\n| ret\n| sar\n| sbb\n| setc\n| seto\n| shl\n| shlx\n| shr\n| shrx\n| shrd\n| sub\n| test\n| xchg\n| xor\n.\n\nRecord JUMP_LABEL := { jump_near : bool ; label_name : string }.\n\nInductive ARG := reg (r : REG) | mem (m : MEM) | const (c : CONST) | label (l : JUMP_LABEL).\nCoercion reg : REG >-> ARG.\nCoercion mem : MEM >-> ARG.\nCoercion const : CONST >-> ARG.\n\nRecord NormalInstruction := { prefix : option OpPrefix ; op : OpCode ; args : list ARG }.\n\nInductive RawLine :=\n| SECTION (name : string)\n| GLOBAL (name : string)\n| LABEL (name : string)\n| ALIGN (amount : string)\n| DEFAULT_REL\n| EMPTY\n| INSTR (instr : NormalInstruction)\n.\nCoercion INSTR : NormalInstruction >-> RawLine.\nRecord Line := { indent : string ; rawline :> RawLine ; pre_comment_whitespace : string ; comment : option string }.\nDefinition Lines := list Line.\n\nDefinition reg_size (r : REG) : N :=\n      match r with\n      |(    rax |     rcx |     rdx |     rbx | rsp  | rbp  | rsi  | rdi  | r8  | r9  | r10  | r11  | r12  | r13  | r14  | r15 )\n       => 64\n      |(    eax |     ecx |     edx |     ebx | esp  | ebp  | esi  | edi  | r8d | r9d | r10d | r11d | r12d | r13d | r14d | r15d)\n       => 32\n      |(     ax |      cx |      dx |      bx |  sp  |  bp  |  si  |  di  | r8w | r9w | r10w | r11w | r12w | r13w | r14w | r15w)\n       => 16\n      |(ah | al | ch | cl | dh | dl | bh | bl |  spl |  bpl |  sil |  dil | r8b | r9b | r10b | r11b | r12b | r13b | r14b | r15b)\n       => 8\n      end.\n\nDefinition standalone_operand_size (x : ARG) : option N :=\n  match x with\n  | reg r => Some (reg_size r)\n  | mem m => option_map bits_of_AccessSize m.(mem_bits_access_size)\n  | const c => None\n  | label _ => None\n  end%N.\n\nDefinition opcode_size (op : OpCode) :=\n  match op with\n  | seto | setc => Some 8\n  | ret => Some 64 (* irrelevant? *)\n  | clc => Some 1 (* irrelevant? *)\n  | _ => None\n  end%N.\n\nDefinition operation_size instr :=\n  match opcode_size instr.(op) with\n  | Some s => Some s | None =>\n  let argsizes := List.map standalone_operand_size instr.(args) in\n  match OptionList.Option.List.lift argsizes with\n  | Some szs => match szs with\n                | nil => None (* unspecified *)\n                | _ => Some (List.fold_right N.max 0%N szs) (* fully specified *)\n                end\n  | _ => match OptionList.Option.List.map id argsizes with\n         | nil => None (* unspecified *)\n         | szs =>\n             let m := List.fold_right N.max 0%N szs in\n             let n := List.fold_right N.min m szs in\n             if N.eqb m n (* uniquely inferred from annotations *)\n             then Some n\n             else None (* inference needed but ambiguous *)\n         end\n  end\n  end.\n\nDefinition operand_size (x : ARG) (operation_size : N) : N :=\n  match standalone_operand_size x with\n  | Some s => s\n  | None => operation_size\n  end.\n\n\nDefinition reg_index (r : REG) : nat\n  :=  match r with\n      |     rax\n      |     eax\n      |      ax\n      |(ah | al)\n       => 0\n      |     rcx\n      |     ecx\n      |      cx\n      |(ch | cl)\n       => 1\n      |     rdx\n      |     edx\n      |      dx\n      |(dh | dl)\n       => 2\n      |     rbx\n      |     ebx\n      |      bx\n      |(bh | bl)\n       => 3\n      | rsp\n      | esp\n      |  sp\n      |( spl)\n       => 4\n      | rbp\n      | ebp\n      |  bp\n      |( bpl)\n       => 5\n      | rsi\n      | esi\n      |  si\n      |( sil)\n       => 6\n      | rdi\n      | edi\n      |  di\n      |( dil)\n       => 7\n      | r8\n      | r8d\n      | r8w\n      | r8b\n        => 8\n      | r9\n      | r9d\n      | r9w\n      | r9b\n        => 9\n      | r10\n      | r10d\n      | r10w\n      | r10b\n        => 10\n      | r11\n      | r11d\n      | r11w\n      | r11b\n        => 11\n      | r12\n      | r12d\n      | r12w\n      | r12b\n        => 12\n      | r13\n      | r13d\n      | r13w\n      | r13b\n        => 13\n      | r14\n      | r14d\n      | r14w\n      | r14b\n        => 14\n      | r15\n      | r15d\n      | r15w\n      | r15b\n        => 15\n      end.\nDefinition reg_offset (r : REG) : N :=\n      match r with\n      |(    rax |     rcx |     rdx |     rbx | rsp  | rbp  | rsi  | rdi  | r8  | r9  | r10  | r11  | r12  | r13  | r14  | r15 )\n      |(    eax |     ecx |     edx |     ebx | esp  | ebp  | esi  | edi  | r8d | r9d | r10d | r11d | r12d | r13d | r14d | r15d)\n      |(     ax |      cx |      dx |      bx |  sp  |  bp  |  si  |  di  | r8w | r9w | r10w | r11w | r12w | r13w | r14w | r15w)\n      |(     al |      cl |      dl |      bl |  spl |  bpl |  sil |  dil | r8b | r9b | r10b | r11b | r12b | r13b | r14b | r15b)\n       => 0\n      |(ah      | ch      | dh      | bh      )\n       => 8\n      end.\nDefinition index_and_shift_and_bitcount_of_reg (r : REG) :=\n  (reg_index r, reg_offset r, reg_size r).\n\nDefinition regs_of_index (index : nat) : list (list REG) :=\n  match index with\n  |  0 => [ [  al ; ah] ; [  ax] ; [ eax] ; [rax] ]\n  |  1 => [ [  cl ; ch] ; [  cx] ; [ ecx] ; [rcx] ]\n  |  2 => [ [  dl ; dh] ; [  dx] ; [ edx] ; [rdx] ]\n  |  3 => [ [  bl ; bh] ; [  bx] ; [ ebx] ; [rbx] ]\n  |  4 => [ [ spl     ] ; [  sp] ; [ esp] ; [rsp] ]\n  |  5 => [ [ bpl     ] ; [  bp] ; [ ebp] ; [rbp] ]\n  |  6 => [ [ sil     ] ; [  si] ; [ esi] ; [rsi] ]\n  |  7 => [ [ dil     ] ; [  di] ; [ edi] ; [rdi] ]\n  |  8 => [ [ r8b     ] ; [ r8w] ; [ r8d] ; [r8 ] ]\n  |  9 => [ [ r9b     ] ; [ r9w] ; [ r9d] ; [r9 ] ]\n  | 10 => [ [r10b     ] ; [r10w] ; [r10d] ; [r10] ]\n  | 11 => [ [r11b     ] ; [r11w] ; [r11d] ; [r11] ]\n  | 12 => [ [r12b     ] ; [r12w] ; [r12d] ; [r12] ]\n  | 13 => [ [r13b     ] ; [r13w] ; [r13d] ; [r13] ]\n  | 14 => [ [r14b     ] ; [r14w] ; [r14d] ; [r14] ]\n  | 15 => [ [r15b     ] ; [r15w] ; [r15d] ; [r15] ]\n  | _  => []\n  end.\n\n(** convenience printing function *)\nDefinition widest_register_of_index (n : nat) : REG\n  := match n with\n     | 0 => rax\n     | 1 => rcx\n     | 2 => rdx\n     | 3 => rbx\n     | 4 => rsp\n     | 5 => rbp\n     | 6 => rsi\n     | 7 => rdi\n     | 8 => r8\n     | 9 => r9\n     | 10 => r10\n     | 11 => r11\n     | 12 => r12\n     | 13 => r13\n     | 14 => r14\n     | 15 => r15\n     | _ => rax\n     end%nat.\n\nDefinition reg_of_index_and_shift_and_bitcount_opt :=\n  fun '(index, offset, size) =>\n    let sz := N.log2 (size / 8) in\n    let offset_n := (offset / 8)%N in\n    if ((8 * 2^sz =? size) && (offset =? offset_n * 8))%N%bool\n    then (rs <- nth_error (regs_of_index index) (N.to_nat sz);\n          nth_error rs (N.to_nat offset_n))%option\n    else None.\nDefinition reg_of_index_and_shift_and_bitcount :=\n  fun '(index, offset, size) =>\n    match reg_of_index_and_shift_and_bitcount_opt (index, offset, size) with\n    | Some r => r\n    | None => widest_register_of_index index\n    end.\n\nLemma widest_register_of_index_correct\n  : forall n,\n    (~exists r, reg_index r = n)\n    \\/ (let r := widest_register_of_index n in reg_index r = n\n       /\\ forall r', reg_index r' = n -> r = r' \\/ (reg_size r' < reg_size r)%N).\nProof.\n  intro n; set (r := widest_register_of_index n).\n  cbv in r.\n  repeat match goal with r := context[match ?n with _ => _ end] |- _ => destruct n; [ right | ] end;\n    [ .. | left; intros [ [] H]; cbv in H; congruence ].\n  all: subst r; split; [ reflexivity | ].\n  all: intros [] H; cbv in H; try (exfalso; congruence).\n  all: try (left; reflexivity).\n  all: try (right; vm_compute; reflexivity).\nQed.\n\nLemma reg_of_index_and_shift_and_bitcount_opt_correct v r\n  : reg_of_index_and_shift_and_bitcount_opt v = Some r <-> index_and_shift_and_bitcount_of_reg r = v.\nProof.\n  split; [ | intro; subst; destruct r; vm_compute; reflexivity ].\n  cbv [index_and_shift_and_bitcount_of_reg]; destruct v as [ [index shift] bitcount ].\n  cbv [reg_of_index_and_shift_and_bitcount_opt].\n  generalize (shift / 8)%N (N.log2 (bitcount / 8)); intros *.\n  repeat first [ congruence\n               | progress subst\n               | match goal with\n                 | [ H : _ /\\ _ |- _ ] => destruct H\n                 | [ H : N.to_nat _ = _ |- _ ] => apply (f_equal N.of_nat) in H; rewrite N2Nat.id in H; subst\n                 | [ |- Some _ = Some _ -> _ ] => inversion 1; subst\n                 | [ |- context[match ?x with _ => _ end] ] => destruct x eqn:?; subst\n                 end\n               | progress cbv [regs_of_index]\n               | match goal with\n                 | [ |- context[nth_error _ ?n] ] => destruct n eqn:?; cbn [nth_error Option.bind]\n                 end\n               | rewrite Bool.andb_true_iff, ?N.eqb_eq in * |- ].\n  all: vm_compute; reflexivity.\nQed.\n\nLemma reg_of_index_and_shift_and_bitcount_of_reg r\n  : reg_of_index_and_shift_and_bitcount (index_and_shift_and_bitcount_of_reg r) = r.\nProof. destruct r; vm_compute; reflexivity. Qed.\n\nLemma reg_of_index_and_shift_and_bitcount_eq v r\n  : reg_of_index_and_shift_and_bitcount v = r\n    -> (index_and_shift_and_bitcount_of_reg r = v\n        \\/ ((~exists r, index_and_shift_and_bitcount_of_reg r = v)\n            /\\ r = widest_register_of_index (fst (fst v)))).\nProof.\n  cbv [reg_of_index_and_shift_and_bitcount].\n  destruct v as [ [index offset] size ].\n  destruct reg_of_index_and_shift_and_bitcount_opt eqn:H;\n    [ left | right; split; [ intros [r' H'] | ] ]; subst; try reflexivity.\n  { rewrite reg_of_index_and_shift_and_bitcount_opt_correct in H; assumption. }\n  { rewrite <- reg_of_index_and_shift_and_bitcount_opt_correct in H'; congruence. }\nQed.\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/Assembly/Syntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283035, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.26693025636845746}}
{"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 Language.\nFrom PromisingLib Require Import Loc.\n\nFrom PromisingLib Require Import Event.\nRequire Import Time.\n\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Mapping.\nRequire Import Pred.\nRequire Import Trace.\nRequire Import MemoryProps.\n\nSet Implicit Arguments.\n\n\nModule CompressSteps.\n  Section CompressSteps.\n    Variable (lang: language).\n\n    Inductive spatial_mem (mem_src mem_tgt: Memory.t): Prop :=\n    | spatial_mem_intro\n        loc from to\n        (SPACE: Time.lt (Memory.max_ts loc mem_tgt) from)\n        (ADD: Memory.add mem_tgt loc from to Message.reserve mem_src)\n    .\n\n    Inductive spatial_thread (e_src e_tgt: Thread.t lang): Prop :=\n    | spatial_thread_intro\n        (STATE: (Thread.state e_src) = (Thread.state e_tgt))\n        (LOCAL: (Thread.local e_src) = (Thread.local e_tgt))\n        (SC: (Thread.sc e_src) = (Thread.sc e_tgt))\n        (MEMORY: spatial_mem (Thread.memory e_src) (Thread.memory e_tgt))\n    .\n\n    Lemma spatial_memory_map mem_src mem_tgt times\n          (SPATIAL: spatial_mem mem_src mem_tgt)\n          (CLOSED: Memory.closed mem_tgt)\n      :\n        exists (f: Loc.t -> Time.t -> Time.t -> Prop),\n          (<<IDENT: map_ident_in_memory f mem_tgt>>) /\\\n          (<<MAPLT: mapping_map_lt_iff f>>) /\\\n          (<<MEMORY: memory_map f mem_tgt mem_src>>) /\\\n          (<<COMPLETE: forall loc to (IN: List.In to (times loc)),\n              exists fto, (<<MAPPED: f loc to fto>>)>>).\n    Proof.\n      inv SPATIAL.\n      hexploit shift_map_exists.\n      { refl. }\n      { eapply SPACE. }\n      i. des.\n      exists (fun loc' => if (Loc.eq_dec loc loc') then f else eq).\n      assert (IDENT: map_ident_in_memory (fun loc' => if LocSet.Facts.eq_dec loc loc' then f else eq) mem_tgt).\n      { ii. des_ifs. eapply SAME; eauto. } splits; ss.\n      - ii. des_ifs. eapply MAPLT; eauto.\n      - econs.\n        + i. right. exists to0, from0, msg, msg. splits; auto.\n          * des_ifs. eapply SAME.\n            eapply Memory.max_ts_spec in GET. des. eauto.\n          * eapply map_ident_in_memory_closed_message; eauto.\n            inv CLOSED. eapply CLOSED0 in GET. des. auto.\n          * refl.\n          * eapply Memory.add_get1; eauto.\n        + i. erewrite Memory.add_o in GET; eauto.\n          destruct (loc_ts_eq_dec (loc0, fto) (loc, to)).\n          { ss. des; clarify. right. ii. des_ifs.\n            destruct (Time.le_lt_dec ts (Memory.max_ts loc mem_tgt)).\n            - dup l. eapply SAME in l. replace fts with ts in *.\n              + eapply TimeFacts.le_lt_lt; eauto.\n              + destruct (Time.le_lt_dec ts fts).\n                * destruct l1; auto.\n                  eapply MAPLT in H; eauto.\n                  exfalso. eapply Time.lt_strorder; eauto.\n                * eapply MAPLT in l1; eauto.\n                  exfalso. eapply Time.lt_strorder; eauto.\n            - eapply BOUND in MAP; eauto. des. auto. }\n          { guardH o. left. exists fto, ffrom, fto, ffrom. splits.\n            - eapply IDENT. eapply Memory.max_ts_spec in GET. des; auto.\n            - refl.\n            - refl.\n            - eapply IDENT. dup GET. eapply Memory.max_ts_spec in GET. des; auto.\n              eapply Memory.get_ts in GET0. des; clarify.\n              etrans; eauto. left. auto.\n            - i. econs; eauto. }\n      - i. des_ifs.\n        + eapply COMPLETE in IN; eauto.\n        + eauto.\n    Qed.\n\n    Lemma compress_steps_failure\n          e1_src e1_tgt\n          (THREAD1: spatial_thread 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          (MEM1_SRC: Memory.closed (Thread.memory e1_src))\n          (MEM1_TGT: Memory.closed (Thread.memory e1_tgt))\n          (STEPS_TGT: @Thread.steps_failure lang e1_tgt):\n      Thread.steps_failure e1_src.\n    Proof.\n      inv THREAD1. destruct e1_src, e1_tgt. ss. clarify.\n      unfold Thread.steps_failure in *. des.\n      eapply pred_steps_thread_steps in STEPS.\n      eapply pred_steps_trace_steps in STEPS. des.\n      hexploit (trace_times_list_exists tr). i. des.\n      hexploit (spatial_memory_map times MEMORY); eauto. i. des.\n      destruct e2. hexploit trace_steps_map; try apply STEPS0; try apply MEMORY0; eauto.\n      { eapply mapping_map_lt_iff_map_le; eauto. }\n      { eapply map_ident_in_memory_bot; eauto. }\n      { eapply mapping_map_lt_iff_map_eq; eauto. }\n      { eapply mapping_map_lt_iff_map_lt; eauto. }\n      { eapply wf_time_mapped_mappable; eauto. }\n      { eapply map_ident_in_memory_local; eauto. }\n      { eapply mapping_map_lt_iff_collapsable_unwritable; eauto. }\n      { eapply map_ident_in_memory_closed_timemap; eauto. }\n      { refl. }\n      i. des.\n      inv STEP_FAILURE; inv STEP; ss. inv LOCAL0; ss.\n      { esplits.\n        - eapply thread_steps_pred_steps.\n          eapply pred_steps_trace_steps2.\n          + eapply STEPS.\n          + instantiate (1:=fun _ => True). eapply List.Forall_forall. ii.\n            eapply list_Forall2_in in H; eauto. des.\n            eapply List.Forall_forall in EVENTS; try apply IN. destruct a, x.\n            ss. des. split; auto. rewrite <- TAU.\n            eapply tevent_map_same_machine_event; eauto.\n        - econs 2. econs; [|econs 7]; eauto.\n          eapply failure_step_map; eauto.\n          + eapply mapping_map_lt_iff_map_le; eauto.\n          + eapply mapping_map_lt_iff_map_eq; eauto.\n        - ss.\n      }\n      { exploit racy_write_step_map; eauto.\n        { eapply mapping_map_lt_iff_map_le; eauto. }\n        { eapply mapping_map_lt_iff_map_eq; eauto. }\n        { eapply mapping_map_lt_iff_map_lt; eauto. }\n        { exploit Trace.steps_future; try exact STEPS0; eauto. s. i. des. ss. }\n        { eapply mapping_map_lt_iff_collapsable_unwritable; eauto. }\n        i. des. esplits.\n        - eapply thread_steps_pred_steps.\n          eapply pred_steps_trace_steps2.\n          + eapply STEPS.\n          + instantiate (1:=fun _ => True). eapply List.Forall_forall. ii.\n            eapply list_Forall2_in in H; eauto. des.\n            eapply List.Forall_forall in EVENTS; try apply IN. destruct a, x.\n            ss. des. split; auto. rewrite <- TAU.\n            eapply tevent_map_same_machine_event; eauto.\n        - econs 2. econs; [|econs 10]; eauto.\n        - ss.\n      }\n      { exploit racy_update_step_map; eauto.\n        { eapply mapping_map_lt_iff_map_le; eauto. }\n        { eapply map_ident_in_memory_bot; eauto. }\n        { eapply mapping_map_lt_iff_map_eq; eauto. }\n        { eapply mapping_map_lt_iff_map_lt; eauto. }\n        { exploit Trace.steps_future; try exact STEPS0; eauto. s. i. des. ss. }\n        { eapply mapping_map_lt_iff_collapsable_unwritable; eauto. }\n        i. des. esplits.\n        - eapply thread_steps_pred_steps.\n          eapply pred_steps_trace_steps2.\n          + eapply STEPS.\n          + instantiate (1:=fun _ => True). eapply List.Forall_forall. ii.\n            eapply list_Forall2_in in H; eauto. des.\n            eapply List.Forall_forall in EVENTS; try apply IN. destruct a, x.\n            ss. des. split; auto. rewrite <- TAU.\n            eapply tevent_map_same_machine_event; eauto.\n        - econs 2. econs; [|econs 11]; eauto.\n        - ss.\n      }\n    Qed.\n\n    Lemma compress_steps_fulfill\n          e1_src e1_tgt\n          e2_tgt\n          (THREAD1: spatial_thread 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          (MEM1_SRC: Memory.closed (Thread.memory e1_src))\n          (MEM1_TGT: Memory.closed (Thread.memory e1_tgt))\n          (STEPS_TGT: rtc (@Thread.tau_step lang) e1_tgt e2_tgt)\n          (PROMISES_TGT: (Local.promises (Thread.local e2_tgt)) = Memory.bot):\n      exists e2_src,\n        <<STEPS_SRC: rtc (@Thread.tau_step lang) e1_src e2_src>> /\\\n                     <<PROMISES_SRC: (Local.promises (Thread.local e2_src)) = Memory.bot>>.\n    Proof.\n      inv THREAD1. destruct e1_src, e1_tgt. ss. clarify.\n      unfold Thread.steps_failure in *. des.\n      eapply pred_steps_thread_steps in STEPS_TGT.\n      eapply pred_steps_trace_steps in STEPS_TGT. des.\n      hexploit (trace_times_list_exists tr). i. des.\n      hexploit (spatial_memory_map times MEMORY); eauto. i. des.\n      destruct e2_tgt. hexploit trace_steps_map; try apply STEPS; try apply MEMORY0; eauto.\n      { eapply mapping_map_lt_iff_map_le; eauto. }\n      { eapply map_ident_in_memory_bot; eauto. }\n      { eapply mapping_map_lt_iff_map_eq; eauto. }\n      { eapply mapping_map_lt_iff_map_lt; eauto. }\n      { eapply wf_time_mapped_mappable; eauto. }\n      { eapply map_ident_in_memory_local; eauto. }\n      { eapply mapping_map_lt_iff_collapsable_unwritable; eauto. }\n      { eapply map_ident_in_memory_closed_timemap; eauto. }\n      { refl. }\n      i. des. esplits.\n      - eapply thread_steps_pred_steps.\n        eapply pred_steps_trace_steps2.\n        + eapply STEPS0.\n        + instantiate (1:=fun _ => True). eapply List.Forall_forall. ii.\n          eapply list_Forall2_in in H; eauto. des.\n          eapply List.Forall_forall in EVENTS; try apply IN. destruct a, x.\n          ss. des. split; auto. inv EVENT; ss.\n      - ss. inv LOCAL. rewrite PROMISES_TGT in *.\n        eapply bot_promises_map; eauto.\n    Qed.\n  End CompressSteps.\nEnd CompressSteps.\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/CompressSteps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.26693025636845735}}
{"text": "Require Import ZArith.\n\nDefinition zeq := Z_eq_dec.\n\nDefinition update (A: Set) (x: Z) (v: A) (s: Z -> A) : Z -> A :=\n fun y => if zeq x y then v else s y.\n\nImplicit Arguments update [A].\n\nDefinition ident := Z.\nParameter operator: Set.\nParameter value: Set.\nParameter is_true: value -> Prop.\nDefinition label := Z.\n\nInductive expr : Set :=\n | Evar: ident -> expr\n | Econst: value -> expr\n | Eop: operator -> expr -> expr -> expr.\n\nInductive stmt : Set :=\n | Sskip: stmt\n | Sassign: ident -> expr -> stmt\n | Scall: ident -> ident -> expr -> stmt (* x := f(e) *)\n | Sreturn: expr -> stmt\n | Sseq: stmt -> stmt -> stmt\n | Sifthenelse: expr -> stmt -> stmt -> stmt\n | Sloop: stmt -> stmt\n | Sblock: stmt -> stmt\n | Sexit: nat -> stmt\n | Slabel: label -> stmt -> stmt\n | Sgoto: label -> stmt.\n\nRecord function : Set := mkfunction {\n fn_param: ident;\n fn_body: stmt\n}.\n\nParameter program: ident -> option function.\n\nParameter main_function: ident.\n\nDefinition store := ident -> value.\n\nParameter empty_store : store.\n\nParameter eval_op: operator -> value -> value -> option value.\n\nFixpoint eval_expr (st: store) (e: expr) {struct e} : option value :=\n match e with\n | Evar v => Some (st v)\n | Econst v => Some v\n | Eop op e1 e2 =>\n     match eval_expr st e1, eval_expr st e2 with\n     | Some v1, Some v2 => eval_op op v1 v2\n     | _, _ => None\n     end\n end.\n\nInductive outcome: Set :=\n | Onormal: outcome\n | Oexit: nat -> outcome\n | Ogoto: label -> outcome\n | Oreturn: value -> outcome.\n\nDefinition outcome_block (out: outcome) : outcome :=\n match out with\n | Onormal => Onormal\n | Oexit O => Onormal\n | Oexit (S m) => Oexit m\n | Ogoto lbl => Ogoto lbl\n | Oreturn v => Oreturn v\n end.\n\nFixpoint label_defined (lbl: label) (s: stmt) {struct s}: Prop :=\n match s with\n | Sskip => False\n | Sassign id e => False\n | Scall id fn e => False\n | Sreturn e => False\n | Sseq s1 s2 => label_defined lbl s1 \\/ label_defined lbl s2\n | Sifthenelse e s1 s2 => label_defined lbl s1 \\/ label_defined lbl s2\n | Sloop s1 => label_defined lbl s1\n | Sblock s1 => label_defined lbl s1\n | Sexit n => False\n | Slabel lbl1 s1 => lbl1 = lbl \\/ label_defined lbl s1\n | Sgoto lbl => False\n end.\n\nInductive exec : stmt -> store -> outcome -> store -> Prop :=\n | exec_skip: forall st,\n     exec Sskip st Onormal st\n | exec_assign: forall id e st v,\n     eval_expr st e = Some v ->\n     exec (Sassign id e) st Onormal (update id v st)\n | exec_call: forall id fn e st v1 f v2 st',\n     eval_expr st e = Some v1 ->\n     program fn = Some f ->\n     exec_function f (update f.(fn_param) v1 empty_store) v2 st' ->\n     exec (Scall id fn e) st Onormal (update id v2 st)\n | exec_return: forall e st v,\n     eval_expr st e = Some v ->\n     exec (Sreturn e) st (Oreturn v) st\n | exec_seq_2: forall s1 s2 st st1 out' st',\n     exec s1 st Onormal st1 -> exec s2 st1 out' st' ->\n     exec (Sseq s1 s2) st out' st'\n | exec_seq_1: forall s1 s2 st out st',\n     exec s1 st out st' -> out <> Onormal ->\n     exec (Sseq s1 s2) st out st'\n | exec_ifthenelse_true: forall e s1 s2 st out st' v,\n     eval_expr st e = Some v -> is_true v -> exec s1 st out st' ->\n     exec (Sifthenelse e s1 s2) st out st'\n | exec_ifthenelse_false: forall e s1 s2 st out st' v,\n     eval_expr st e = Some v -> ~is_true v -> exec s2 st out st' ->\n     exec (Sifthenelse e s1 s2) st out st'\n | exec_loop_loop: forall s st st1 out' st',\n     exec s st Onormal st1 ->\n     exec (Sloop s) st1 out' st' ->\n     exec (Sloop s) st out' st'\n | exec_loop_stop: forall s st st' out,\n     exec s st out st' -> out <> Onormal ->\n     exec (Sloop s) st out st'\n | exec_block: forall s st out st',\n     exec s st out st' ->\n     exec (Sblock s) st (outcome_block out) st'\n | exec_exit: forall n st,\n     exec (Sexit n) st (Oexit n) st\n | exec_label: forall s lbl st st' out,\n     exec s st out st' ->\n     exec (Slabel lbl s) st out st'\n | exec_goto: forall st lbl,\n     exec (Sgoto lbl) st (Ogoto lbl) st\n\n(** [execg lbl stmt st out st'] starts executing at label [lbl] within [s],\n   in initial store [st].  The result of the execution is the outcome\n   [out] with final store [st']. *)\n\nwith execg: label -> stmt -> store -> outcome -> store -> Prop :=\n | execg_left_seq_2: forall lbl s1 s2 st st1 out' st',\n     execg lbl s1 st Onormal st1 -> exec s2 st1 out' st' ->\n     execg lbl (Sseq s1 s2) st out' st'\n | execg_left_seq_1: forall lbl s1 s2 st out st',\n     execg lbl s1 st out st' -> out <> Onormal ->\n     execg lbl (Sseq s1 s2) st out st'\n | execg_right_seq: forall lbl s1 s2 st out st',\n     ~(label_defined lbl s1) ->\n     execg lbl s2 st out st' ->\n     execg lbl (Sseq s1 s2) st out st'\n | execg_ifthenelse_left: forall lbl e s1 s2 st out st',\n     execg lbl s1 st out st' ->\n     execg lbl (Sifthenelse e s1 s2) st out st'\n | execg_ifthenelse_right: forall lbl e s1 s2 st out st',\n     ~(label_defined lbl s1) ->\n     execg lbl s2 st out st' ->\n     execg lbl (Sifthenelse e s1 s2) st out st'\n | execg_loop_loop: forall lbl s st st1 out' st',\n     execg lbl s st Onormal st1 ->\n     exec (Sloop s) st1 out' st' ->\n     execg lbl (Sloop s) st out' st'\n | execg_loop_stop: forall lbl s st st' out,\n     execg lbl s st out st' -> out <> Onormal ->\n     execg lbl (Sloop s) st out st'\n | execg_block: forall lbl s st out st',\n     execg lbl s st out st' ->\n     execg lbl (Sblock s) st (outcome_block out) st'\n | execg_label_found: forall lbl s st st' out,\n     exec s st out st' ->\n     execg lbl (Slabel lbl s) st out st'\n | execg_label_notfound: forall lbl s lbl' st st' out,\n     lbl' <> lbl ->\n     execg lbl s st out st' ->\n     execg lbl (Slabel lbl' s) st out st'\n\n(** [exec_finish out st st'] takes the outcome [out] and the store [st]\n at the end of the evaluation of the program.  If [out] is a [goto],\n execute again the program starting at the corresponding label.\n Iterate this way until [out] is [Onormal]. *)\n\nwith exec_finish: function -> outcome -> store -> value -> store -> Prop :=\n | exec_finish_normal: forall f st v,\n     exec_finish f (Oreturn v) st v st\n | exec_finish_goto: forall f lbl st out v st1 st',\n     execg lbl f.(fn_body) st out st1 ->\n     exec_finish f out st1 v st' ->\n     exec_finish f (Ogoto lbl) st v st'\n\n(** Execution of a function *)\n\nwith exec_function: function -> store -> value -> store -> Prop :=\n | exec_function_intro: forall f st out st1 v st',\n     exec f.(fn_body) st out st1 ->\n     exec_finish f out st1 v st' ->\n     exec_function f st v st'.\n\nScheme exec_ind4:= Minimality for exec Sort Prop\n with execg_ind4:= Minimality for execg Sort Prop\n with exec_finish_ind4 := Minimality for exec_finish Sort Prop\n with exec_function_ind4 := Minimality for exec_function Sort Prop.\n\nScheme exec_dind4:= Induction for exec Sort Prop\n with execg_dind4:= Minimality for execg Sort Prop\n with exec_finish_dind4 := Induction for exec_finish Sort Prop\n with exec_function_dind4 := Induction for exec_function Sort Prop.\n\nCombined Scheme exec_inductiond from exec_dind4, execg_dind4, exec_finish_dind4,\n  exec_function_dind4.\n\nScheme exec_dind4' := Induction for exec Sort Prop\n with execg_dind4' := Induction for execg Sort Prop\n with exec_finish_dind4' := Induction for exec_finish Sort Prop\n with exec_function_dind4' := Induction for exec_function Sort Prop.\n\nCombined Scheme exec_induction from exec_ind4, execg_ind4, exec_finish_ind4,\n  exec_function_ind4.\n\nCombined Scheme exec_inductiond' from exec_dind4', execg_dind4', exec_finish_dind4',\n  exec_function_dind4'.\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/test-suite/bugs/closed/shouldsucceed/1844.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.26692097568800194}}
{"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 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": "Ninijura", "repo": "bachelorproject", "sha": "dcfd46c08f0a0c5ad1f606b5114702c8e3e0c867", "save_path": "github-repos/coq/Ninijura-bachelorproject", "path": "github-repos/coq/Ninijura-bachelorproject/bachelorproject-dcfd46c08f0a0c5ad1f606b5114702c8e3e0c867/domains/cont_adj.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.26692097568800194}}
{"text": "Set Implicit Arguments.\n\nSection ADTValue.\n\n  Variable ADTValue : Type.\n\n  Require Import Platform.Cito.Transit.\n  Require Import Platform.Cito.Semantics.\n\n  Require Import Platform.Cito.Syntax.\n  Require Import Platform.Cito.GLabel.\n  Require Import Platform.Cito.GLabelMap.\n  Import GLabelMap.\n  Require Import Platform.Cito.SemanticsExpr.\n  Require Import Platform.Cito.GeneralTactics Platform.Cito.GeneralTactics2 Platform.Cito.GeneralTactics3.\n\n  Notation Callee := (@Callee ADTValue).\n\n  Definition Specs := GLabelMap.t Callee.\n\n  Definition f_var := \"_f\".\n\n  Notation State := (@State ADTValue).\n\n  Definition RunsToDCall specs retvar f args (v v' : State) :=\n    match find f specs with\n      | Some (Semantics.Foreign spec) =>\n        exists inputs outputs ret_w ret_a f_w,\n          let vs := upd (fst v) f_var f_w in\n          TransitTo spec (List.map (eval vs) args) inputs outputs ret_w ret_a (snd v) (snd v') /\\\n          fst v' = upd_option vs retvar ret_w\n      | _ => True\n    end.\n\n  Definition SafeDCall specs f args (v : State) :=\n    match find f specs with\n      | Some (Semantics.Foreign spec) =>\n        forall f_w,\n          let vs := upd (fst v) f_var f_w in\n          exists inputs, TransitSafe spec (List.map (eval vs) args) inputs (snd v)\n      | _ => False\n    end.\n\n  (* shallow embedding *)\n  Definition assert := Specs -> State -> State -> Prop.\n  Definition entailment := Specs -> Prop.\n\n  Inductive StmtEx := \n  | SkipEx : StmtEx\n  | SeqEx : StmtEx -> StmtEx -> StmtEx\n  | IfEx : Expr -> StmtEx -> StmtEx -> StmtEx\n  | WhileEx : assert -> Expr -> StmtEx -> StmtEx\n  | AssignEx : string -> Expr -> StmtEx\n  | AssertEx : assert -> StmtEx\n  | DCallEx : option string -> glabel -> list Expr -> StmtEx.\n\n  Definition and_lift (a b : assert) : assert := fun specs v v' => a specs v v' /\\ b specs v v'.\n  Definition or_lift (a b : assert) : assert := fun specs v v' => a specs v v' \\/ b specs v v'.\n  Definition imply_close (a b : assert) : entailment := fun specs => forall v v', a specs v v' -> b specs v v'.\n\n  Infix \"/\\\" := and_lift : assert_scope.\n  Infix \"\\/\" := or_lift : assert_scope.\n  Infix \"-->\" := imply_close (at level 90) : assert_scope.\n\n  Close Scope equiv_scope.\n\n  Definition is_true e : assert := fun _ _ v => eval (fst v) e <> $0.\n  Definition is_false e : assert := fun _ _ v => eval (fst v) e = $0.\n\n  Open Scope assert_scope.\n  \n  Fixpoint to_stmt s :=\n    match s with\n      | SkipEx => Syntax.Skip\n      | SeqEx a b => Syntax.Seq (to_stmt a) (to_stmt b)\n      | IfEx e t f => Syntax.If e (to_stmt t) (to_stmt f)\n      | WhileEx _ e b => Syntax.While e (to_stmt b)\n      | AssignEx x e => Syntax.Assign x e\n      | AssertEx _ => Syntax.Skip\n      | DCallEx x f args => Syntax.Seq (Syntax.Label f_var f) (Syntax.Call x (Var f_var) args)\n    end.\n\n  Coercion to_stmt : StmtEx >-> Stmt.\n\n  Fixpoint sp (stmt : StmtEx) (p : assert) : assert :=\n    match stmt with\n      | SeqEx a b => sp b (sp a p)\n      | IfEx e t f => sp t (p /\\ is_true e) \\/ sp f (p /\\ is_false e)\n      | WhileEx inv e _ => inv /\\ is_false e\n      | AssertEx a => a\n      | SkipEx => p\n      | AssignEx x e =>\n        (fun specs v0 v' =>\n           exists v,\n             p specs v0 v /\\\n             v' = (upd (fst v) x (eval (fst v) e), snd v))%type\n      | DCallEx x f args =>\n        (fun specs v0 v' =>\n           exists v,\n             p specs v0 v /\\\n             RunsToDCall specs x f args v v')%type\n    end.\n\n  Fixpoint vc stmt (p : assert) : list entailment :=\n    match stmt with\n      | SeqEx a b => vc a p ++ vc b (sp a p)\n      | IfEx e t f => vc t (p /\\ is_true e) ++ vc f (p /\\ is_false e)\n      | WhileEx inv e body => \n        (p --> inv) :: (sp body (inv /\\ is_true e) --> inv) :: vc body (inv /\\ is_true e)\n      | AssertEx a => (p --> a) :: nil\n      | SkipEx => nil\n      | AssignEx _ _ => nil\n      | DCallEx x f args => (p --> (fun specs _ v => SafeDCall specs f args v)) :: nil\n    end.\n  \n  Definition and_all : list entailment -> entailment := fold_right (fun a b specs => a specs /\\ b specs)%type (fun _ => True).\n\n  Lemma and_all_app : forall ls1 ls2 specs, and_all (ls1 ++ ls2) specs -> and_all ls1 specs /\\ and_all ls2 specs.\n    induction ls1; simpl; intuition.\n    eapply IHls1 in H1; openhyp; eauto.\n    eapply IHls1 in H1; openhyp; eauto.\n  Qed.\n\n  Lemma is_true_intro : forall e specs v v', wneb (eval (fst v') e) $0 = true -> (is_true e) specs v v'.\n    intros.\n    unfold is_true.\n    unfold wneb in *.\n    destruct (weq _ _) in *; intuition.\n  Qed.\n\n  Hint Resolve is_true_intro.\n\n  Lemma is_false_intro : forall e specs v v', wneb (eval (fst v') e) $0 = false -> (is_false e) specs v v'.\n    intros.\n    unfold is_false.\n    unfold wneb in *.\n    destruct (weq _ _) in *; intuition.\n  Qed.\n\n  Hint Resolve is_false_intro.\n\n  Hint Constructors Semantics.RunsTo.\n  Hint Constructors Semantics.Safe.\n\n  Ltac inject :=\n    match goal with\n      | H : _ = _ |- _ => unfold_all; injection H; intros; subst\n    end.\n\n  Definition Env := ((glabel -> option W) * (W -> option Callee))%type.\n\n  Open Scope type.\n\n  Definition specs_fs_agree (specs : Specs) (env : Env) :=\n    let labels := fst env in\n    let fs := snd env in\n    forall p spec, \n      fs p = Some spec <-> \n      exists (lbl : glabel),\n        labels lbl = Some p /\\\n        find lbl specs = Some spec.\n\n  Definition labels_in_scope (specs : Specs) (labels : glabel -> option W) :=\n    forall lbl, In lbl specs -> labels lbl <> None.\n\n  Definition specs_stn_injective (specs : Specs) stn := forall lbl1 lbl2 (w : W), In lbl1 specs -> In lbl2 specs -> stn lbl1 = Some w -> stn lbl2 = Some w -> lbl1 = lbl2.\n\n  Definition specs_env_agree (specs : Specs) (env : Env) :=\n    labels_in_scope specs (fst env) /\\\n    specs_stn_injective specs (fst env) /\\\n    specs_fs_agree specs env.\n\n  Require Import Platform.Cito.GLabelMapFacts.\n  Require Import Platform.Cito.Option.\n\n  Require Import Platform.Cito.BedrockTactics.\n\n  Lemma RunsTo_RunsToDCall : \n    forall specs env r f args v v', \n      specs_env_agree specs env -> \n      RunsTo env (DCallEx r f args) v v' ->\n      RunsToDCall specs r f args v v'.\n  Proof.\n    intros.\n    simpl in *.\n    unfold RunsToDCall.\n    inv_clear H0.\n    inv_clear H3.\n    destruct (option_dec(find f specs)).\n    destruct s; rewrite e; simpl in *.\n    destruct x; simpl in *.\n    destruct H; simpl in *.\n    destruct env; simpl in *.\n    rename a into f0.\n    assert (o0 w = Some (Foreign f0)).\n    eapply H0.\n    descend; eauto.\n    generalize H6; intro HH.\n    inv_clear H6; simpl in *.\n    sel_upd_simpl; rewrite H7 in H1; discriminate.\n    sel_upd_simpl; rewrite H7 in H1; injection H1; intros; subst.\n    eapply RunsTo_TransitTo in HH.\n    Focus 2.\n    simpl; sel_upd_simpl; eauto.\n    openhyp.\n    destruct r; simpl in *.\n    subst; simpl in *.\n    descend.\n    eauto.\n    sel_upd_simpl; eauto.\n    descend.\n    eauto.\n    eauto.\n    eauto.\n    rewrite e; eauto.\n  Qed.\n\n  Lemma SafeDCall_Safe : \n    forall specs env r f args v, \n      specs_env_agree specs env -> \n      SafeDCall specs f args v ->\n      Safe env (DCallEx r f args) v.\n  Proof.\n    intros.\n    destruct H.\n    destruct env; simpl in *.\n    unfold SafeDCall in *.\n    destruct (option_dec(find f specs)).\n    destruct s; rewrite e in *; simpl in *.\n    destruct x.\n    econstructor.\n    econstructor.\n    eapply H.\n    eapply MapsTo_In; eapply find_mapsto_iff; eauto.\n    intros.\n    inv_clear H2.\n    specialize (H0 w); clear H.\n    destruct H0 as [inputs Htsf].\n    eapply TransitSafe_Safe; eauto.\n    sel_upd_simpl.\n    eapply H1.\n    descend; eauto.\n    intuition.\n    rewrite e in *; eauto.\n    intuition.\n  Qed.\n\n  Lemma sound_runsto' : forall env (s : Stmt) v v', RunsTo env s v v' -> forall s' : StmtEx, s = s' -> forall specs, specs_env_agree specs env -> forall p, and_all (vc s' p) specs -> forall v0, p specs v0 v -> (sp s' p) specs v0 v'.\n    induction 1; simpl; intros; destruct s'; try discriminate; simpl in *; try inject.\n\n    (* skip *)\n    eauto.\n\n    openhyp.\n    eauto.\n\n    (* seq *)\n    eapply_in_any and_all_app; openhyp.\n    eauto.\n\n    (* call *)\n    openhyp.\n    descend.\n    eauto.\n    eapply RunsTo_RunsToDCall; simpl; eauto.\n\n    (* if *)\n    eapply_in_any and_all_app; openhyp.\n    left.\n    eapply IHRunsTo; eauto.\n    split; eauto.\n\n    eapply_in_any and_all_app; openhyp.\n    right.\n    eapply IHRunsTo; eauto.\n    split; eauto.\n\n    (* while *)\n    openhyp.\n    eapply (IHRunsTo2 (WhileEx _ e s')); simpl in *; eauto.\n    eapply IHRunsTo1; simpl in *; eauto.\n    split; eauto.\n\n    openhyp.\n    split; eauto.\n\n    (* assign *)\n    descend; eauto.\n  Qed.\n\n  Theorem sound_runsto : forall env (s : StmtEx) v v' specs p, RunsTo env s v v' -> specs_env_agree specs env -> and_all (vc s p) specs -> p specs v v -> (sp s p) specs v v'.\n    intros.\n    eapply sound_runsto'; eauto.\n  Qed.\n\n  Close Scope assert_scope.\n\n  Theorem sound_safe : forall specs env (s : Stmt) (s' : StmtEx) v p v0, s = s' -> specs_env_agree specs env -> and_all (vc s' p) specs -> p specs v0 v -> Safe env s v.\n    intros.\n    eapply (Safe_coind (fun s v => Safe env s v \\/ exists (s' : StmtEx) p v0, s = s' /\\ and_all (vc s' p) specs /\\ p specs v0 v)); [ .. | right; descend; eauto]; generalize H0; clear; intros; openhyp.\n\n    (* seq *)\n    inversion H; subst.\n    descend; left; eauto.\n\n    destruct x; try discriminate; simpl in *; try inject.\n    eapply_in_any and_all_app; openhyp.\n    descend.\n    right; descend; eauto.\n    intros.\n    eapply sound_runsto' with (p := x0) in H4; eauto.\n    right; descend; eauto.\n\n    (* dcall *)\n\n    openhyp.\n    eapply H1 in H2.\n    eapply SafeDCall_Safe in H2; eauto.\n    simpl in *.\n    inv_clear H2.\n    split.\n    eauto.\n    intros.\n    eauto.\n\n    (* if *)\n    inversion H; subst.\n    openhyp; subst.\n    left; descend.\n    eauto.\n    left; eauto.\n    right; descend.\n    eauto.\n    left; eauto.\n\n    destruct x; try discriminate; simpl in *; try inject.\n    eapply_in_any and_all_app; openhyp.\n    unfold wneb.\n    destruct (weq (eval (fst v) e) $0) in *.\n    right.\n    descend; eauto.\n    right; descend; eauto.\n    split; eauto.\n    left.\n    descend; eauto.\n    right; descend; eauto.\n    split; eauto.\n\n    (* while *)\n    inversion H; unfold_all; subst.\n    left; descend.\n    eauto.\n    left; eauto.\n    left; eauto.\n    right; eauto.\n\n    destruct x; try discriminate; simpl in *; try inject.\n    openhyp.\n    unfold wneb.\n    destruct (weq (eval (fst v) e) $0) in *.\n    right.\n    eauto.\n    left.\n    descend; eauto.\n    right.\n    descend; eauto.\n    split; eauto.\n    right.\n    eapply sound_runsto' with (p := and_lift a (is_true e)) in H5; eauto.\n    descend.\n    instantiate (1 := WhileEx _ e x).\n    eauto.\n    2 : eauto.\n    simpl.\n    descend; eauto.\n    split; eauto.\n\n    (* call *)\n    inversion H; unfold_all; subst.\n    left; descend; eauto.\n    right; descend; eauto.\n\n    destruct x; try discriminate; simpl in *; try inject.\n\n    (* label *)\n    inversion H; unfold_all; subst.\n    eauto.\n\n    destruct x0; try discriminate; simpl in *; try inject.\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/ProgramLogic2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.26692097568800194}}
{"text": "Set Universe Polymorphism.\nRequire Import Showable String List DepEquivAnti DepEquiv HoTT.\n\nNotation \"{ x : A & P }\" := (sigT_HSet A (fun x => P)) : type_scope.\n\n(** * Higher-order dependent equivalences *)\n\n(** \n\nWe enrich the dependent equivalence class with instances matching\nhigher-order types.\n\n *)\n\n(** Triggers for lifting and unlifing search: *)\n\n(* =lift= *)\nDefinition lift {A: HSet} {B_1 B_2: A ->HSet}{C_1 C_2: HSet}\n    `{(forall a, B_1 a ⇀ B_2 a)  ≲ (C_1 ⇀ C_2)} :\n    (forall a, B_1 a -> B_2 a) -> C_1 ⇀ C_2  := \n  fun f => c_fun (fun a b => creturn (f a b)).\n(* =end= *)\n\nDefinition liftA {A: HSet} {B_1 B_2: A ->HSet}{C_1 C_2: HSet}\n    `{(forall a, B_1 a ⇀ B_2 a)  ≈ (C_1 ⇀ C_2)} :\n    (forall a, B_1 a -> B_2 a) -> C_1 ⇀ C_2  := \n  fun f => ac_fun (fun a b => creturn (f a b)).\n\n(* =unlift= *)\nDefinition unlift {A: HSet}{B_1 B_2: A -> HSet}{C_1 C_2: HSet}\n  `{(forall a, B_1 a ⇀ B_2 a) ≲ (C_1 ⇀ C_2)} :\n   (C_1 -> C_2) -> forall a, B_1 a ⇀ B_2 a\n(* =end= *)\n  := fun ff => c_inv _ (IsConnection := c_isconn (Connection := H)) (clift ff).\n\nDefinition unliftA {A:HSet} {B: A -> HSet} {C : A -> HSet} {B_ C_:HSet}\n           {H :(forall a, B a ⇀ (C a)) ≈ (B_ ⇀ C_)} :\n  (B_ -> C_) -> forall a, B a ⇀ (C a)\n  := fun ff => ac_inv _  (clift ff).\n\nDefinition lift2 {A A': HSet} \n           {B: A -> A' -> HSet} {C: A -> A' -> HSet} {D : A -> A' -> HSet}\n           {B_ C_ D_:Type}\n           {HB_: IsHSet B_}\n           {HC_: IsHSet C_}\n           {HD_: IsHSet D_}\n           `{(forall a a', B a a' -> C a a' ⇀ D a a') ≲ (hset B_ -> hset C_ ⇀ hset D_)} :\n  (forall a a', B a a' -> C a a' -> D a a') -> B_ -> C_ ⇀ D_.\n  intros ff. pose (c := fun a a' b c => creturn (ff a a' b c)).\n  refine (c_fun c).\n  exact H.\nDefined. \n\nDefinition lift2A {A A': HSet} \n           {B: A -> A' -> HSet} {C: A -> A' -> HSet} {D : A -> A' -> HSet}\n           {B_ C_ D_:Type}\n           {HB_: IsHSet B_}\n           {HC_: IsHSet C_}\n           {HD_: IsHSet D_}\n           `{(forall a a', B a a' -> C a a' ⇀ D a a') ≈ (hset B_ -> hset C_ ⇀ hset D_)} :\n  (forall a a', B a a' -> C a a' -> D a a') -> B_ -> C_ ⇀ D_.\n  intros ff. pose (c := fun a a' b c => creturn (ff a a' b c)).\n  refine (ac_fun c).\n  exact H.\nDefined. \n\n(** ** Domain transformation: *)\n\nInstance HOAnticonnection_easy (A:HSet) (B: A -> HSet) (C:HSet)(C': HSet)         \n         (H: B ≈K□ C) \n  : (* ------------------------------------*)\n         (forall a, B a ⇀ C') ≈ (C ⇀ C')  \n  | 0\n  := {| ac_fun := Build_Mon (to_simpl_dom : (∀ a : A, B a ⇀ C') -> C ⇀ C') _ _;\n        ac_isconn := {| ac_inv := Build_Mon to_dep_dom _ _ |}|}. \nProof.\n  + intros f g Hfg c. cbn in *. unfold to_simpl_dom.\n    destruct (a_c_to_a c) as [a|]; simpl; eauto.\n    destruct (to_dep a c) as [b|]; simpl; eauto.\n    specialize (Hfg a b). revert Hfg. destruct (f a b); simpl; eauto.\n  + cbn. unfold to_simpl_dom. intro x.\n    destruct (a_c_to_a x) as [a|]; simpl; eauto; try apply irr_Fail.\n    destruct (to_dep a x); simpl; eauto; apply irr_Fail.\n  + intros f g Hfg a b. cbn in *. unfold to_dep_dom, kleisliComp.\n    destruct (to_simpl b) as [c | c]; simpl; eauto. \n    specialize (Hfg c). revert Hfg. simpl. destruct (f c) as [c' | c']; simpl; eauto.\n  + cbn. unfold to_dep_dom, kleisliComp. intros a b. \n    destruct (to_simpl b) as [c | c]; simpl; eauto; try apply irr_Fail.\n  + intros f a b. simpl. \n    unfold compose, to_dep_dom, to_simpl_dom in *; simpl in *.\n    assert (H'1'1: (a_c_to_a °° (apc_fun (a_partial_equiv a))) (e_fun (a_total_equiv a) b) = Some a)\n      by apply a_prop_c_to_a.\n    unfold kleisliComp in H'1'1. unfold to_simpl, b_to_c.\n    unfold to_dep, to_rich. simpl. \n    pose (r:=apc_sect (IsAnticonnectionK := apc_isconn (a := DepAnticonnection_ConnectionK _ _ _ _ ))  _ b).\n    generalize dependent r. unfold kleisliComp, to_simpl. cbn in *.  simpl. \n    unfold to_simpl, to_dep, b_to_c, compose.\n    revert H'1'1. \n    Set Printing All. simpl. \n    destruct ((@apc_fun (sigT_HSet C (fun c : _typeS C => @a_P A B C H a c)) C\n                 (@a_partial_equiv A B C H a)\n                 (@e_fun (_typeS (B a))\n                    (@sigT (_typeS C) (fun x : _typeS C => _typeP (@a_P A B C H a x)))\n                    (@a_total_equiv A B C H a) b))) as [c|c]; simpl ; eauto. \n    simpl; intro e. rewrite e. clear e. simpl in *.\n    Unset Printing All. \n    destruct (apc_inv _ c) as [c0|]; simpl; eauto.\n    intro e. inversion e.  rewrite H1. \n    destruct (f a b) as [c''|]; simpl; eauto. \n  + intros f c.\n    unfold compose, to_dep_dom, to_simpl_dom, to_dep, to_rich, to_simpl in *; simpl in *.\n    destruct (a_c_to_a c) as [a|]; simpl; eauto.\n    pose (r:= apc_retr (IsAnticonnectionK := apc_isconn (a := DepAnticonnection_ConnectionK _ _ _ a)) _ c). unfold kleisliComp in *.\n    generalize dependent r. cbn in *. unfold to_dep, to_rich, to_simpl,compose. \n    destruct (apc_inv _ c) as [s|]; simpl ; eauto.\n    destruct ( @apc_fun (sigT_HSet C (fun c0 : _typeS C => @a_P A B C H a c0)) C\n            (@a_partial_equiv A B C H a)\n            (@e_fun (_typeS (B a))\n               (@sigT (_typeS C) (fun x : _typeS C => _typeP (@a_P A B C H a x)))\n               (@a_total_equiv A B C H a)\n               (@e_inv (_typeS (B a))\n                  (@sigT (_typeS C) (fun x : _typeS C => _typeP (@a_P A B C H a x)))\n                  (@e_fun (_typeS (B a))\n                     (@sigT (_typeS C) (fun x : _typeS C => _typeP (@a_P A B C H a x)))\n                     (@a_total_equiv A B C H a))\n                  (@e_isequiv (_typeS (B a))\n                     (@sigT (_typeS C) (fun x : _typeS C => _typeP (@a_P A B C H a x)))\n                     (@a_total_equiv A B C H a)) s))) as [s'|]; simpl; eauto. \n    intro e. inversion e. clear e.   \n     destruct (f c); simpl ; eauto.\nDefined.\n\nInstance HOConnection_easy (A:HSet) (B: A -> HSet) (C:HSet)(C': HSet)         \n         (H: B ≲K□ C) \n  : (* ------------------------------------*)\n         (forall a, B a ⇀ C') ≲ (C ⇀ C')  \n| 0.\nProof.\n  unshelve eapply Connection_Anticonnection_K. cbn.\n  intros f a b. simpl. \n  unfold compose, to_dep_dom, to_simpl_dom in *; simpl in *.\n  assert (H'1'1: (c_to_a °° (pc_fun (partial_equiv a))) (e_fun (total_equiv a) b) = Some a)\n    by apply prop_c_to_a.\n  unfold kleisliComp in H'1'1. unfold to_simpl, b_to_c.\n  unfold to_dep, to_rich. simpl. \n  pose (r:=pc_sect (IsConnectionK := pc_isconn (c := DepConnection_ConnectionK _ _ _ _ ))  _ b).\n  generalize dependent r. unfold kleisliComp, to_simpl. cbn in *.  simpl. \n  unfold to_simpl, to_dep, b_to_c, compose.\n  revert H'1'1. \n  Set Printing All. simpl. \n  destruct ((@pc_fun (sigT_HSet C (fun c : _typeS C => @P A B C H a c)) C\n                 (@partial_equiv A B C H a)\n                 (@e_fun (_typeS (B a))\n                    (@sigT (_typeS C) (fun x : _typeS C => _typeP (@P A B C H a x)))\n                    (@total_equiv A B C H a) b))) as [c|c]; simpl ; eauto. \n    simpl; intro e. rewrite e. clear e. simpl in *.\n    Unset Printing All. \n    destruct (pc_inv _ c) as [c0|]; simpl; eauto.\n    intro e. inversion e. rewrite <- H1. \n    destruct (f a b) as [c''|]; simpl; eauto. \n    intro e; inversion e.\n    intro e; inversion e.\nDefined. \n\n\n(** ** Domain & co-domain transformation: *)\n\n(* =HODepEquiv= *)\nInstance HOConnectionAnti {A: HSet} {B_1 B_2: A -> HSet} {C_1 C_2: HSet}: \n  (B_1 ≈K□ C_1) -> (B_2 ≈K□ C_2) -> (forall a, B_1 a ⇀ B_2 a) ≈ (C_1 ⇀ C_2)\n  := fun _ _ =>\n       {| ac_fun := Build_Mon\n                    (fun f => to_simpl_dom (fun a b => x <- f a b; to_simpl x)) _ _ ; \n          ac_isconn := {| ac_inv := Build_Mon \n                    (fun f a b => x <- to_dep_dom f a b; to_dep _ x) _ _ |}|}.\n(* =end= *)\nProof.\n+ intros f g Hfg c. cbn in *. unfold to_simpl_dom.\n  destruct (a_c_to_a c) as [a|]; simpl; eauto.\n  destruct (to_dep a c) as [b|]; simpl; eauto.\n  specialize (Hfg a b). revert Hfg. destruct (f a b); simpl; eauto.\n  destruct (g a b) as [b1|]; simpl; intro e; inversion e; try reflexivity.\n  destruct (to_simpl b1); simpl; eauto.\n+ cbn. unfold to_simpl_dom. intro x.\n  destruct (a_c_to_a x) as [a|]; simpl; eauto; try apply irr_Fail.\n  destruct (to_dep a x); simpl; eauto; apply irr_Fail.\n+ intros f g Hfg a b. cbn in *. unfold to_dep_dom, to_dep_dom, kleisliComp.\n  destruct (to_simpl b) as [c | c]; simpl; eauto. \n  specialize (Hfg c). revert Hfg. destruct (f c); simpl; eauto.\n  destruct (g c) as [c1 | c1]; simpl; intro e; inversion e.\n  subst. destruct (to_dep a c1); simpl; eauto.\n+ cbn. unfold to_dep_dom, kleisliComp. intros a b. \n  destruct (to_simpl b); simpl; eauto; try apply irr_Fail.\n+ intros f a b.  unfold compose in *. cbn in *. \n  unfold to_dep_dom, to_dep_dom, to_simpl_dom in *.\n\n    assert (H'1'1: (a_c_to_a °° (apc_fun (a_partial_equiv a))) (e_fun (a_total_equiv a) b) = Some a)\n    by apply a_prop_c_to_a.\n  unfold kleisliComp in H'1'1. unfold to_simpl, b_to_c.\n\n   unfold to_dep, to_rich. simpl. \n   pose (r := apc_sect (IsAnticonnectionK := apc_isconn (a := DepAnticonnection_ConnectionK _ _ _ a )) _ b).\n   generalize dependent r. unfold kleisliComp, to_simpl. cbn in *.  simpl. \n  unfold to_simpl, to_dep, b_to_c,compose.\n  revert H'1'1.\n  Set Printing All. simpl. \n  destruct (@apc_fun (sigT_HSet C_1 (fun c : _typeS C_1 => @a_P A B_1 C_1 _ a c)) C_1\n                 (@a_partial_equiv A B_1 C_1 _ a)\n                 (@e_fun (_typeS (B_1 a))\n                    (@sigT (_typeS C_1)\n                       (fun x : _typeS C_1 => _typeP (@a_P A B_1 C_1 _ a x)))\n                    (@a_total_equiv A B_1 C_1 _ a) b)) as [c | c]; simpl; eauto.\n  Unset Printing All. \n  intro e; rewrite e. clear e. simpl in *. unfold to_rich. \n  destruct (apc_inv _ c) as [s | ]; simpl; eauto.\n  intro e; inversion e.\n  destruct (f a\n      (@e_inv (_typeS (B_1 a))\n         (@sigT (_typeS C_1) (fun x : _typeS C_1 => _typeP (@a_P A B_1 C_1 _ a x)))\n         (@e_fun (_typeS (B_1 a))\n            (@sigT (_typeS C_1) (fun x : _typeS C_1 => _typeP (@a_P A B_1 C_1 _ a x)))\n            (@a_total_equiv A B_1 C_1 _ a))\n         (@e_isequiv (_typeS (B_1 a))\n            (@sigT (_typeS C_1) (fun x : _typeS C_1 => _typeP (@a_P A B_1 C_1 _ a x)))\n            (@a_total_equiv A B_1 C_1 _ a)) s) ) as [b0 |]; simpl; eauto. \n  pose (r := apc_sect (IsAnticonnectionK := apc_isconn (a := DepAnticonnection_ConnectionK _ _ _ _ )) _ b0). simpl in r.\n  generalize dependent r. unfold kleisliComp, to_simpl, to_dep, b_to_c, c_to_b,compose. \n  Set Printing All. simpl. \n  destruct (@apc_fun (sigT_HSet C_2 (fun c0 : _typeS C_2 => @a_P A B_2 C_2 _ a c0)) C_2\n                (@a_partial_equiv A B_2 C_2 _ a)\n                (@e_fun (_typeS (B_2 a))\n                   (_typeS (sigT_HSet C_2 (fun c0 : _typeS C_2 => @a_P A B_2 C_2 _ a c0)))\n                   (@a_total_equiv A B_2 C_2 _ a) b0)) as [c' | ]; simpl; eauto.\n  Unset Printing All. \n+ intros f x. cbn in *. \n  unfold compose,  to_dep_dom, to_dep_dom, to_simpl_dom, to_simpl, clift, to_dep, to_rich in *;\n    simpl in *.\n  destruct (a_c_to_a x) as [a|]; simpl ; eauto. \n  pose (r := apc_retr (IsAnticonnectionK := apc_isconn (a := DepAnticonnection_ConnectionK _ _ _  a)) _ x). unfold kleisliComp in *.\n  generalize dependent r. cbn in *. unfold to_dep, to_rich, to_simpl,compose. \n  destruct (apc_inv _ x) as [s|]; simpl ; eauto.\n  destruct (@apc_fun (sigT_HSet C_1 (fun c : _typeS C_1 => @a_P A B_1 C_1 _ a c)) C_1\n            (@a_partial_equiv A B_1 C_1 _ a)\n            (@e_fun (_typeS (B_1 a))\n               (@sigT (_typeS C_1) (fun x0 : _typeS C_1 => _typeP (@a_P A B_1 C_1 _ a x0)))\n               (@a_total_equiv A B_1 C_1 _ a)\n               (@e_inv (_typeS (B_1 a))\n                  (@sigT (_typeS C_1)\n                     (fun x0 : _typeS C_1 => _typeP (@a_P A B_1 C_1 _ a x0)))\n                  (@e_fun (_typeS (B_1 a))\n                     (@sigT (_typeS C_1)\n                        (fun x0 : _typeS C_1 => _typeP (@a_P A B_1 C_1 _ a x0)))\n                     (@a_total_equiv A B_1 C_1 _ a))\n                  (@e_isequiv (_typeS (B_1 a))\n                     (@sigT (_typeS C_1)\n                        (fun x0 : _typeS C_1 => _typeP (@a_P A B_1 C_1 _ a x0)))\n                     (@a_total_equiv A B_1 C_1 _ a)) s))) as [c | c]; simpl; eauto.\n  intro e. inversion e. simpl. \n  destruct (f x) as [c0 | c0]; simpl; eauto. \n  pose (r := apc_retr (IsAnticonnectionK := apc_isconn (a := DepAnticonnection_ConnectionK _ _ _ a)) _ c0). unfold kleisliComp in *.\n  generalize dependent r. cbn in *. unfold to_dep, to_rich, to_simpl. \n  destruct (apc_inv _ c0); simpl ; eauto.\nDefined.\n\nInstance HOConnection \n  {A: HSet} {B_1 B_2: A -> HSet} {C_1 C_2: HSet}: \n  (B_1 ≲K□ C_1) -> (B_2 ≲K□ C_2) -> (forall a, B_1 a ⇀ B_2 a)  ≲ (C_1 ⇀ C_2).\nProof.\n  intros H1 H2. unshelve eapply Connection_Anticonnection_K. cbn.\n  + intros f a b.  unfold compose in *. cbn in *. \n  unfold to_dep_dom, to_dep_dom, to_simpl_dom in *.\n\n    assert (H'1'1: (c_to_a °° (pc_fun (partial_equiv a))) (e_fun (total_equiv a) b) = Some a)\n    by apply prop_c_to_a.\n  unfold kleisliComp in H'1'1. unfold to_simpl, b_to_c.\n\n\n    unfold to_dep, to_rich. simpl. \n    pose (r := pc_sect (IsConnectionK := pc_isconn (c := DepConnection_ConnectionK _ _ _ a )) _ b).\n    generalize dependent r. unfold kleisliComp, to_simpl. cbn in *.  simpl. \n  unfold to_simpl, to_dep, b_to_c,compose.\n  revert H'1'1.\n  Set Printing All. simpl. \n  destruct (@pc_fun (sigT_HSet C_1 (fun c : _typeS C_1 => @P A B_1 C_1 _ a c)) C_1\n                 (@partial_equiv A B_1 C_1 _ a)\n                 (@e_fun (_typeS (B_1 a))\n                    (@sigT (_typeS C_1)\n                       (fun x : _typeS C_1 => _typeP (@P A B_1 C_1 _ a x)))\n                    (@total_equiv A B_1 C_1 _ a) b)) as [c | c]; simpl; eauto.\n  Unset Printing All. \n  intro e; rewrite e. clear e. simpl in *. unfold to_rich. \n  destruct (pc_inv _ c) as [s | ]; simpl; eauto.\n  intro e; inversion e. \n  destruct (f a\n      (@e_inv (_typeS (B_1 a))\n         (@sigT (_typeS C_1) (fun x : _typeS C_1 => _typeP (@P A B_1 C_1 _ a x)))\n         (@e_fun (_typeS (B_1 a))\n            (@sigT (_typeS C_1) (fun x : _typeS C_1 => _typeP (@P A B_1 C_1 _ a x)))\n            (@total_equiv A B_1 C_1 _ a))\n         (@e_isequiv (_typeS (B_1 a))\n            (@sigT (_typeS C_1) (fun x : _typeS C_1 => _typeP (@P A B_1 C_1 _ a x)))\n            (@total_equiv A B_1 C_1 _ a)) s) ) as [b0 |]; simpl; eauto. \n  pose (r := pc_sect (IsConnectionK := pc_isconn (c := DepConnection_ConnectionK _ _ _ _ )) _ b0). simpl in r.\n  generalize dependent r. unfold kleisliComp, to_simpl, to_dep, b_to_c, c_to_b,compose. \n  Set Printing All. simpl. \n  destruct (@pc_fun (sigT_HSet C_2 (fun c0 : _typeS C_2 => @P A B_2 C_2 H2 a c0)) C_2\n          (@partial_equiv A B_2 C_2 H2 a)\n          (@e_fun (_typeS (B_2 a)) (@sigT (_typeS C_2) (fun x : _typeS C_2 => _typeP (@P A B_2 C_2 H2 a x)))\n             (@total_equiv A B_2 C_2 H2 a) b0)) as [c' | ]; simpl; eauto.\n  Unset Printing All. \n  intro e. inversion e. \n  intro e; inversion e. \nDefined.\n  \n\n(** ** Argument reordering: *)\n\n(* =HODepEquiv_2_sym= *)\nInstance HOConnection_2_sym\n   (A A': HSet) (B_1 B_2 B_3: A -> A' -> HSet) {C_1 C_2 C_3: HSet}\n  `{ (forall a a', B_2 a a' -> B_1 a a' ⇀ B_3 a a') ≲ (C_2 -> C_1 ⇀ C_3) }:\n    (forall a a', B_1 a a' -> B_2 a a' ⇀ B_3 a a') ≲ (C_1 -> C_2 ⇀ C_3) \n(* =end= *)\n  | 100\n  := {| c_fun := Build_Mon (fun ff b_ c_ => c_fun (fun a a' c b => ff a a' b c) c_ b_) _ _; \n        c_isconn :=\n          {|c_inv := Build_Mon (fun ff a a' b c => (c_inv _ (IsConnection := c_isconn (Connection := H))) (fun c b => ff b c) _ _ c b) _ _ |}|}.\nProof.\n  - intros x y H0 b c.\n    pose (x' := fun a a' c b => x a a' b c).\n    pose (y' := fun a a' c b => y a a' b c).\n    assert (e : x' ≼ y'). intros x1 x2 x3 x4. apply H0. \n    apply ((c_fun (Connection := H)).(mon) e).\n  - intros b c.\n    exact ((c_fun (Connection := H)).(p_mon _ _) c b).\n  - intros x y H0 a a' b c.\n    pose (x' := fun c b => x b c).\n    pose (y' := fun c b => y b c).\n    assert (e : x' ≼ y'). intros x1 x2. apply H0. \n    apply ((c_inv _ (IsConnection := c_isconn (Connection := H))).(mon) e).\n  - intros a a' b c. \n    exact ((c_inv _ (IsConnection := c_isconn (Connection := H))).(p_mon _ _) a a' c b).\n  - intros f a a' b c. \n    exact (c_sect _ (IsConnection := c_isconn (Connection := H)) (fun a a' c b => f a a' b c) a a' c b).\n  - intros f b c.\n    exact (c_retr _ (IsConnection := c_isconn (Connection := H)) (fun c b => f b c) _ _).\n  (* - simpl. intros f. apply funext. intro b. *)\n  (*   apply funext; intro c. apply is_hprop. *)\nDefined.\n\n\n\n(** ** Arity 2 types: *)\n\nHint Extern 1 (IsConnection ?f) => apply (c_isconn (Connection := _)) :\n             typeclass_instances.\n\n\n(* =HOCoercion_2_fun= *)\nDefinition HOConnection_2_fun \n  {A A': HSet} {B_1: A -> HSet} {B_2 B_3: A -> A' -> HSet} {C_1 C_2 C_3: HSet} :\n  (B_1 ≈K□ C_1) -> (forall a, ((forall a': A', B_2 a a' ⇀ B_3 a a') ≲ (C_2 ⇀ C_3))) -> \n  (forall a a', B_1 a → B_2 a a' ⇀ B_3 a a') -> C_1 -> C_2 ⇀ C_3 :=\n  fun _ _ f c_1 c_2 => to_simpl_dom (fun a b_1 => c_fun (fun a' => f a a' b_1) c_2) c_1. \n(* =end= *)\n\n(* =to_dep_dom2= *)\nDefinition HOConnection_2_inv  {A A': HSet} {B_1: A -> HSet} {B_2 B_3: A -> A' -> HSet} {C_1 C_2 C_3: HSet} :\n  (B_1 ≈K□ C_1) -> (forall a, ((forall a': A', B_2 a a' ⇀ B_3 a a') ≲ (C_2 ⇀ C_3))) ->\n  (C_1 → C_2 ⇀ C_3) -> ∀ a a', B_1 a → B_2 a a' ⇀ B_3 a a' :=\n  fun _ H f a a' b_1 b_2 => \n    c_inv (c_fun (Connection := H a)) (fun x => c_1 <- to_simpl b_1; f c_1 x) _ b_2.\n(* =end= *)\n\n(* =HODepEquiv2= *)\nInstance HOConnection_2 \n  (A A': HSet) (B_1: A -> HSet) (B_2 B_3: A -> A' -> HSet) (C_1 C_2 C_3: HSet) :\n  (B_1 ≲K□ C_1) -> (forall a, ((forall a': A', B_2 a a' ⇀ B_3 a a') ≲ (C_2 ⇀ C_3))) ->\n  (forall a a', B_1 a -> B_2 a a' ⇀ B_3 a a') ≲ (C_1 -> C_2 ⇀ C_3).\n(* =end= *)\nProof.\n    unshelve refine (fun H H' => \n  {| c_fun := Build_Mon (HOConnection_2_fun (DepConnection_DepAnticonnection _ _ _ H) H') _ _ ; \n     c_isconn := {| c_inv := Build_Mon (HOConnection_2_inv (DepConnection_DepAnticonnection _ _ _ H) H') _ _ |}|}).\n  + intros f g e b c. simpl. unfold HOConnection_2_fun, to_simpl_dom.\n    destruct (a_c_to_a b) as [a|] ;simpl; eauto. \n    destruct (to_dep a b) ;simpl; eauto.\n    refine ((c_fun (Connection := H' a)).(mon) _ _).\n    intros x1 x2. apply e.\n  + cbn. unfold HOConnection_2_fun, to_simpl_dom. intros b c.\n    destruct (a_c_to_a b) as [a|]; simpl; eauto; try apply fail_contr.\n    destruct (to_dep a b); simpl; eauto; try apply fail_contr.\n    apply (c_fun (Connection := H' a) .(p_mon _ _) c).\n  + intros f g e a a' b c. simpl. unfold to_dep_dom2. unfold HOConnection_2_inv.\n    refine ((c_inv _ (IsConnection := c_isconn (Connection := H' a))).(mon) _ _ _).\n    intros x1. destruct (to_simpl b) as [c'| c']; simpl ; eauto. apply e.\n  + cbn. unfold HOConnection_2_inv, to_simpl_dom. intros a a' b c.\n    destruct (to_simpl b) as[s | s]; simpl; try apply fail_contr; auto.\n    apply (c_inv _ (IsConnection := c_isconn (Connection := H' a)) .(p_mon _ _) a' c).\n    assert ((λ _ : C_2, @Fail C_3 _ s) = (λ _ : C_2, @Fail C_3 _ (_with \"bot\"))).\n    apply funext. intro. apply ap. apply is_hprop.\n    rewrite H0. apply (c_inv _ (IsConnection := c_isconn (Connection := H' a)) .(p_mon _ _) a' c).\n  + intros ff a a' b c.\n     unfold compose, HOConnection_2_inv, HOConnection_2_fun, to_simpl_dom in *; simpl in *.\n  assert (H'1'1: (a_c_to_a °° (apc_fun (a_partial_equiv a))) (e_fun (a_total_equiv a) b) = Some a)\n    by apply a_prop_c_to_a.\n  unfold kleisliComp in H'1'1. unfold to_simpl, b_to_c.\n  unfold to_dep, to_rich. simpl. \n  pose (r := pc_sect (IsConnectionK := pc_isconn (c := DepConnection_ConnectionK _ _ _ _ )) _ b).\n  generalize dependent r. unfold kleisliComp, to_simpl. cbn in *.  simpl. \n  unfold to_simpl, to_dep, b_to_c,compose.\n  revert H'1'1. cbn.\n  Set Printing All. simpl. \n  destruct (@pc_fun (sigT_HSet C_1 (fun c0 : _typeS C_1 => @P A B_1 C_1 H a c0)) C_1\n                 (@partial_equiv A B_1 C_1 H a)\n                 (@e_fun (_typeS (B_1 a))\n                    (@sigT (_typeS C_1)\n                       (fun x : _typeS C_1 => _typeP (@P A B_1 C_1 H a x)))\n                    (@total_equiv A B_1 C_1 H a) b)) as [c0 | c0]; simpl; eauto.\n  intro e; rewrite e. clear e. simpl in *. unfold to_rich.\n  Unset Printing All. \n  destruct (pc_inv _ c0); simpl; eauto.\n  intro e. inversion e. rewrite <- H1.\n  exact (c_sect (IsConnection := c_isconn (Connection := _)) _ (fun a' c => ff a a' b c) a' c).\n  intro e; inversion e. \n  intro e; inversion e. \n  + intros ff b c. \n    unfold compose, HOConnection_2_fun, to_simpl_dom, HOConnection_2_inv in *; simpl in *.\n    destruct (c_to_a b) as [a|];simpl; [ |eauto].\n    unfold to_dep, to_rich.\n    pose (r := pc_retr (IsConnectionK := pc_isconn (c := DepConnection_ConnectionK _ _ _ a)) _ b). unfold kleisliComp in *.\n  generalize dependent r. cbn in *. unfold to_dep, to_rich, to_simpl,compose. cbn. \n  destruct (pc_inv _ b) as [s|]; simpl ; eauto.\n  pose (e_retr (IsEquiv := e_isequiv (e := total_equiv a)) _ s).\n  pose (r := c_retr (IsConnection := c_isconn (Connection := H' a)) _ (to_dep_dom2 ff a (c_to_b s)) c).\n  generalize dependent r.\n  unfold to_dep_dom2; cbn. unfold to_simpl. simpl. \n  unfold compose, b_to_c, c_to_b in *.\n  Set Printing All. simpl in *. rewrite e. clear e. Unset Printing All. \n  destruct (pc_fun (partial_equiv a) s) as [c'|i]; simpl; eauto.  \n  intros e' e. inversion e. rewrite <- H1 in *. clear e H1. revert e'. \n  exact (fun x => x). \n  intros e _. revert e. \n  pose (F := c_fun (c_inv _ (IsConnection := c_isconn (Connection := H' a)) (λ _ : C_2, @Fail C_3 _ i))).\n  simpl in *.\n  change (F c ≼ @Fail _ info_str i -> F c ≼ ff b c).\n  destruct (F c); simpl; eauto. \n  intro e; inversion e. \n  (* + intro f. apply funext. intro. simpl. apply funext. intro. *)\n  (*   apply is_hprop. *)\nDefined.\n\n(* This instance must be here because before, it would break some\n   type class inferences, I don't understand why ?*)\n\n(* =DepEquivInj= *)\nInstance Connection_Inj (A A': HSet)(B: A -> HSet)(C: HSet) \n  (f: A' -> A) `{IsInjective _ _ f} \n  `{B ≲K□ C}: (fun a => B (f a)) ≲K□ C \n(* =end= *)                       \n  := Build_DepConnection A' (fun a => B (f a)) C (fun a c => P (f a) c)\n                    (fun a' => total_equiv (f a'))\n                    (λ a : A', partial_equiv (f a))\n                    (fun c => a <- c_to_a c; f^?-1 a) _. \nProof.\n  intros a' b. simpl. \n  pose (prop_c_to_a (f a') b). generalize dependent e. unfold kleisliComp, b_to_c.\n  Set Printing All. simpl. \n  destruct (@pc_fun (sigT_HSet C (fun c : _typeS C => @P A B C H0 (f a') c)) C\n                (@partial_equiv A B C H0 (f a'))\n                (@e_fun (_typeS (B (f a')))\n                   (@sigT (_typeS C) (fun x : _typeS C => _typeP (@P A B C H0 (f a') x)))\n                   (@total_equiv A B C H0 (f a')) b)) as [c|]; simpl; intro e;inversion e. \n  rewrite e. simpl.\n  Unset Printing All. \n  apply (i_sect a').\nDefined.", "meta": {"author": "CoqHott", "repo": "DICoq", "sha": "6abf83fbf3a78f45885760afa700c26a804f7ccc", "save_path": "github-repos/coq/CoqHott-DICoq", "path": "github-repos/coq/CoqHott-DICoq/DICoq-6abf83fbf3a78f45885760afa700c26a804f7ccc/HODepEquiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.26692097568800194}}
{"text": "(************************************************************\n* Lambda-calculus with exceptions                           *\n* Definition of an interpreter                              *\n*************************************************************)\n\nSet Implicit Arguments.\nRequire Export LambdaExn_Syntax.\nImport AssumeDeterministic.\nImport BehaviorsWithErrors.\n\nImplicit Types v : val.\nImplicit Types t : trm.\nImplicit Types b : beh.\n\n\n(*==========================================================*)\n(* * Definitions *)\n\n(************************************************************)\n(* ** Results *)\n\n(** Grammar of results of the interpreter *)\n\nInductive res :=\n  | res_return : beh -> res\n  | res_bottom : res.\n\nCoercion res_return : beh >-> res.\nImplicit Types r : res.\n\n\n(************************************************************)\n(* ** Monadic operators *)\n\n(** Bind-style operators *)\n\nDefinition if_success (r:res) (k:val->res) : res :=\n  match r with\n  | res_return (beh_ret v) => k v\n  | _ => r\n  end.\n\nDefinition if_fault (r:res) (k:val->res) : res :=\n  match r with\n  | res_return (beh_exn v) => k v\n  | _ => r\n  end.\n\nDefinition if_isclo (v:val) (k:var->trm->res) : res :=\n  match v with\n  | val_clo x t => k x t\n  | _ => beh_err\n  end.\n\n\n(************************************************************)\n(* ** Interpreter *)\n\n(** Definition of the interpreter *)\n\nFixpoint run (n:nat) (t:trm) : res :=\n  match n with \n  | O => res_bottom\n  | S m => \n    match t with\n    | trm_val v => v\n    | trm_abs x t1 => val_clo x t1\n    | trm_var x => beh_err\n    | trm_app t1 t2 => \n       if_success (run m t1) (fun v1 =>\n         if_success (run m t2) (fun v2 =>\n            if_isclo v1 (fun x t3 =>\n              run m (subst x v2 t3))))\n    | trm_try t1 t2 =>\n       if_fault (run m t1) (fun v => run m (trm_app t2 v))\n    | trm_raise t1 => \n       if_success (run m t1) (fun v1 => beh_exn v1)\n    | trm_rand => val_int 0\n    end\n  end.\n\n\n", "meta": {"author": "charguer", "repo": "formalmetacoq", "sha": "0f24ffe7416352c1a275671d8d857f8aa6a5bb39", "save_path": "github-repos/coq/charguer-formalmetacoq", "path": "github-repos/coq/charguer-formalmetacoq/formalmetacoq-0f24ffe7416352c1a275671d8d857f8aa6a5bb39/pretty/LambdaExn_Interp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2669209756880019}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect ssrbool ssrfun eqtype ssrnat seq div.\nRequire Import prime fintype finfun bigops ssralg finset.\nRequire Import groups morphisms perm automorphism normal commutators.\nRequire Import action zmodp cyclic center gprod pgroups nilpotent sylow.\nRequire Import abelian gseries maximal hall mxrepresentation.\nRequire Import BGsection1 BGsection2.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nImport GroupScope.\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 cardG_gt0 /= => 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 -coprime_commGid //; 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  by rewrite -coprime_quotient_cent ?morphim_Zgroup ?(solvableS sHG).\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  by rewrite -defV cent_sub_Fitting ?(solvableS sHG).\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_dvdG.\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 pV); first by rewrite coprime_sym.\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 coprime_morphl // (pnat_coprime pV).\n  case/andP: nWH => sWH nWH.\n  rewrite subsetI andbC commg_subl cycle_subG; apply/andP; split.\n    by apply: subsetP Wx; apply: subset_trans (subset_trans sWH _) nVG.\n  move: nWH; rewrite -commg_subr; 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/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_id ?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 ?muln_gt0 ?cardG_gt0 //=.\n  have: V \\subset V <*> P by rewrite -defVP mulG_subl.\n  move/LaGrange <-; rewrite part_pnat_id // 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 (cent_sub_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: coprime_abelian_cent_dprod; last by case/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)](im_invm 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 (cent_sub_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 := Aut_cyclic_abelian cycK.\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) ?cardG_gt0 //.\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_dvdn; apply/eqP.\n    have:= cycle_id x; rewrite -defC setIC; case/setIP=> _.\n    by case/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_exp.\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_dvdG.\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/coprime_cent_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_id ?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 ?cardG_gt0 // 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 /= -coprime_commGid //.\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' := (K)^`(1); have nK'K: K' <| K := der_normal 1 K.\nhave nK'PR: P <*> R \\subset 'N(K').\n  exact: char_norm_trans (der_char 1 K) 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 1 K)) //.\n  suffices abPR: abelian (P <*> R / K').\n    by apply: subset_trans (subset_trans abPR (centS _));\n      rewrite quotientS ?mulgen_subl ?mulgen_subr.\n  have nKqPR: P <*> R / K' \\subset 'N(K / K') by rewrite quotient_norms.\n  case cycK: (cyclic (K / K')).\n    have inj_autPR: 'injm (restrm nKqPR (conj_aut (K / K'))).\n      by rewrite ker_restrm ker_conj_aut trCK'.\n    rewrite -(im_invm inj_autPR) morphim_abelian //.\n    apply: abelianS (Aut_cyclic_abelian cycK).\n    by apply/subsetP=> pK'x; case/morphimP=> K'x _ _ /= ->; exact: Aut_aut.\n  have{cycK} [k2 abelK]: k = 2 /\\ q.-abelem (K / K').\n    case: k lek2 oK => [|[|[|//]]] _ oK.\n    - by rewrite (card1_trivg oK) cyclic1 in cycK.\n    - by rewrite prime_cyclic ?oK in cycK.\n    split=> //; apply/abelemP=> //=; split=> [|K'x KK'x].\n      suff ->: K / K' = 'Z(K / _) by exact: center_abelian.\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 (prime_cyclic _).\n        rewrite card_quotient ?char_norm ?center_char //=.\n        by rewrite -divgS ?subsetIl // oZ oK mulnK // prime_gt0.\n      by apply/eqP; rewrite eq_sym eqEcard oK oZ subsetIl leqnn.\n    apply/eqP; have:= order_dvdG KK'x; rewrite -order_dvdn oK.\n    case/dvdn_pfactor=> // k le_k2 ox; rewrite ox pfactor_dvdn ?prime_gt0 //.\n    rewrite logn_prime // eqxx leqNgt leq_eqVlt ltnNge le_k2 orbF eq_sym /=.\n    apply/eqP=> k2; case/cyclicP: cycK; exists K'x; apply/eqP.\n    by rewrite eq_sym eqEcard cycle_subG KK'x oK -k2 -ox leqnn.\n  have ntK: K / K' != 1.\n    by rewrite trivg_card1 oK k2 (eqn_sqr _ 1) neq_ltn orbC prime_gt1.\n  pose rPR := abelem_repr abelK ntK nKqPR.\n  have: mx_repr_faithful rPR by rewrite /mx_repr_faithful rker_abelem trCK'.\n  move: rPR; rewrite (dim_abelemE abelK ntK) oK pfactorK // k2 => rPR ffPR.\n  apply: charf'_GL2_abelian ffPR _.\n    by rewrite quotient_odd ?(oddSg _ oddG) // mulgen_subG (subset_trans sPH).\n  rewrite quotient_pgroup //; apply: sub_in_pnat coK_PR => q' _.\n  apply: contra; rewrite /= (GRing.charf_eq (char_Fp q_pr)); move/eqnP->.\n  by rewrite mem_primes q_pr cardG_gt0.\ncase abelK: (abelian K); last first.\n  have [||[dPhiK sK'] dCKP] := abelian_charsimple_special qK _ (esym defKP) _.\n  - by rewrite coprime_sym (pnat_coprime pP).\n  - apply/bigcupsP=> L; case/andP=> chL.\n    case/IHK: (char_sub chL) abelK => // [|-> -> //].\n    by rewrite (char_norm_trans chL).\n  have xKq: exponent K %| q.\n    have oddq: odd q.\n      move: oddG; rewrite !odd_2'nat; apply: pnat_dvd.\n      by apply: dvdn_trans qKdv (cardSg _); exact: subset_trans sHG.\n    have ntK: K :!=: 1 by apply/eqP=> K1; rewrite K1 comm1G eqxx in ntKP.\n    have{oddq ntK} [Q [chQ _ _ xQq qCKQ]] := critical_odd oddq qK ntK.\n    have: P <*> R \\subset 'N(Q) by exact: char_norm_trans nKPR.\n    have sQK := char_sub chQ.\n    case/IHK=> // [<- | cQP]; first by rewrite xQq.\n    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 /= astab_ract 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 nZK := normal_norm (center_normal K).\n  have trCPR_K': 'C_(P <*> R / 'Z(K))(K / 'Z(K)) = 1.\n    rewrite -quotient_astabQ -quotientIG /=; last first.\n      by rewrite sub_astabQ normG trivg_quotient sub1G.\n    apply/trivgP; rewrite -quotient1 quotientS // -trCPR_K subsetI subsetIl /=.\n    rewrite (coprime_cent_Phi qK) ?(coprimegS (subsetIl _ _)) //=.\n      rewrite norm_mulgenEr // coprime_cardMg ?(coprimeSg sPH) //.\n      by rewrite coprime_mulr coprime_sym (pnat_coprime pP) ?(coprimeSg sKH).\n    rewrite dPhiK (subset_trans (commgS _ (subsetIr _ _))) //.\n    by rewrite astabQ -quotient_cents2 ?subsetIl // cosetpreK centsC /=.\n  have nZP := char_norm_trans (center_char _) nKP.\n  have nZR := char_norm_trans (center_char _) nKR.\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    by rewrite coprime_quotient_cent ?center_sub ?(coprimeSg sKH).\n  have abK': q.-abelem (K / 'Z(K)).\n    by rewrite -dPhiK -trivg_Phi ?morphim_pgroup // Phi_quotient_id.\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 setICA coprime_abel_cent_TI ?subsetIr ?morphim_norms //.\n      by rewrite coprime_morphl // coprime_morphr // (coprimeSg sKH).\n    by rewrite sub_der1_abelian //= -sK'.\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    rewrite (coprime_cent_Phi qK) ?(coprimeSg sKH) // dPhiK.\n    by rewrite commGC -quotient_cents2.\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}(coprime_cent_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 (cardG_gt0 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  by rewrite defKP coprime_abel_cent_TI // coprime_sym (pnat_coprime pP).\nhave abelemK: q.-abelem K.\n  apply/abelem_Ohm1P => //.\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 expg_order.\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  apply/eqP; rewrite eqEsubset gen_subG; apply/andP; split.\n    apply/bigcupsP=> Ki _; exact: subsetIl.\n  rewrite (coprime_abelian_gen_cent abelK nVK) ?(pnat_coprime pV) //.\n  rewrite bigprodGE gen_subG; apply/bigcupsP=> Kj; case/and3P=> cycKj sKjK nKjK.\n  case: (eqsVneq (Vi Kj) 1) => [/= -> | ntVKj]; first by rewrite sub1G.\n  rewrite sub_gen // (bigD1 Kj) ?subsetUl //= inE p_index_maximal //.\n  have abelKj: q.-abelem (K / Kj).\n    apply/abelemP; rewrite ?quotient_abelian //; split=> // Kjx.\n    case/morphimP=> x NKjx Kx ->; rewrite -morphX //.\n    by case/abelemP: abelemK => // _; move/(_ x Kx)->; rewrite morph1.\n  rewrite -card_quotient //; case/cyclicP: cycKj => Kjx /= defKj.\n  case: (eqVneq Kjx 1) => [Kjx1 | ntKjx].\n    case/eqP: ntVKj; rewrite /= (index1g sKjK) // -card_quotient // defKj.\n    by rewrite Kjx1 [#|_|]order1.\n  rewrite defKj -/#[_]; case: (abelem_order_p abelKj _ ntKjx) => [|_ -> //].\n  by rewrite /= defKj cycle_id.\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/and3P: abV => _ 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, on mxK | 'JG].\n  apply/subsetP=> x PRx; rewrite 3!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, on Vi @: mxK | 'JG].\n  apply/subsetP=> x PRx; rewrite 3!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, on Vi @: mxK | 'JG].\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/and3P: abV.\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_sub_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 -afixJG; 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 astab1JG /= 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/and3P: abV=> _; 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 ?prime_gt0 // 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_gt0 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_dvdn ox /dvdn modn_small ?eqn0Ngt ?i_gt0.\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: prime_gt0.\n    rewrite /f -r1 {1}big_nat_recr big_nat_recl /= conjMg -conjgM -expgSr.\n    rewrite r1 -{2}ox expg_order 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    case: (eqsVneq (Vi Ki) 1) => [Vi1 | ntVKi].\n      by rewrite inE Vi1 eqxx andbF in mxKi.\n    have: p.-group (Vi Ki) by apply: pgroupS pV; exact: subsetIl.\n    by case/pgroup_pdiv=> // _ pVKi _; rewrite dvdn_leq.\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_sub_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 prime_cyclic // oVi.\n      case/cyclicP=> v; move/group_inj=> -> a.\n      case/imsetP=> y _ -> b; case/imsetP=> z _ ->{a b}.\n      apply: (centsP (Aut_cycle_abelian v)); exact: Aut_aut.\n    apply/eqP; rewrite -val_eqE eq_sym eqEcard sKRVj.\n    rewrite -(leq_pmul2r (prime_gt0 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      by rewrite coprime_abelian_cent_dprod ?(coprimeSg sKH).\n    case/dprodP=> _ defKR _ trKR_C.\n    rewrite -{1}defKR (TI_cardMg trKR_C) leq_pmul2l ?cardG_gt0 //=.\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_id ?eqxx //.\n      apply: pgroupS qK; exact: subsetIl.\n    case/cyclicP=> z defC; rewrite defC dvdn_leq ?prime_gt0 // order_dvdn.\n    case/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 (atrans_dvd transPR)).\n  rewrite defmxV cardsU1 (negPf V1Rj) oV1R -oR.\n  rewrite -odd_2'nat /= odd_2'nat; case/negP; exact: pgroupS oddG.\nhave:= sub0set 'Fix_(Vi @: mxK | 'JG)(P); 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 (prime_gt0 _)).\ncase/andP=> _; case/subsetPn=> Vj; case/setIP; case/imsetP=> Kj mxKj ->{Vj}.\nrewrite afixJG => 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 prime_cyclic ?oVi.\ncase/cyclicP=> v; move/group_inj->.\napply: (centsP (Aut_cycle_abelian 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/ssreflect12_trunk/theories/theorem3_6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2669209756880019}}
{"text": "(* General construction of a partial DM *)\n\nFrom Coq Require Import Utf8 RelationClasses.\nFrom PDM Require Import util structures PURE.\n\nSet Default Goal Selector \"!\".\nSet Printing Projections.\nSet Universe Polymorphism.\nUnset Universe Minimization ToSet.\n\nSection PDM.\n\n  (* Computational monad with assert/req *)\n\n  Context {M} `{ReqMonad M}.\n\n  (* Specification monad *)\n\n  Context {W} `{ReqMonad W} {Word : Order W} (hmono : MonoSpec W).\n\n  (* Effect observation *)\n\n  Context {θ : observation M W} (θ_lax : LaxMorphism θ) (hlax : ReqLaxMorphism Word θ).\n\n  Arguments θ [_].\n\n  (* Partial Dijkstra monad *)\n\n  Definition D A w :=\n    { c : M A | θ c ≤ᵂ w }.\n\n  #[export] Instance DijkstraMonad_D : DijkstraMonad D.\n  Proof.\n    constructor.\n    - intros A x.\n      exists (ret x).\n      apply θ_ret.\n    - intros A B w wf c f.\n      exists (bind (val c) (λ x, val (f x))).\n      etransitivity. 1: apply θ_bind.\n      apply bind_mono.\n      + destruct c. assumption.\n      + intro x. destruct (f x). assumption.\n    - intros A w w' c h.\n      exists (val c).\n      etransitivity. 2: exact h.\n      destruct c. assumption.\n  Defined.\n\n  Definition reqᴰ (p : Prop) : D p (req p).\n  Proof.\n    exists (req p).\n    apply θ_req.\n  Defined.\n\n  (* Lift from PURE *)\n\n  (* Would be nice to have a special case when W comes from pre and post + mono *)\n  Context {liftᵂ : spec_lift_pure W} (hlift : PureSpec W Word liftᵂ).\n\n  Arguments liftᵂ [_].\n\n  Definition liftᴾ [A w] (f : PURE A w) : D A (liftᵂ w).\n  Proof.\n    refine (subcompᴰ (bindᴰ (reqᴰ (val w (λ _, True))) (λ h, retᴰ (val (f h))))).\n    apply req_lift.\n  Defined.\n\n  (* Laws preservation *)\n\n  Context {hr : ∀ A, Reflexive (wle (A := A))}.\n  Context {hMl : MonadLaws M} {hWl : MonadLaws W}.\n\n  Lemma left_id_w :\n    ∀ {A B} (x : A) (w : A → W B),\n      w x ≤ᵂ bind (ret x) w.\n  Proof.\n    intros A B x w.\n    rewrite left_id. reflexivity.\n  Qed.\n\n  Lemma left_id :\n    ∀ A w (x : A) (f : ∀ (x : A), D A (w x)),\n      bindᴰ (retᴰ x) f = subcompᴰ (h := left_id_w x w) (f x).\n  Proof.\n    intros A w x f.\n    apply sig_ext. simpl.\n    apply left_id.\n  Qed.\n\n  Lemma right_id_w :\n    ∀ {A} (w : W A),\n      w ≤ᵂ bind w (ret (A:=A)).\n  Proof.\n    intros A w.\n    rewrite right_id. reflexivity.\n  Qed.\n\n  Lemma right_id :\n    ∀ A w (c : D A w),\n      bindᴰ c (λ x, retᴰ x) = subcompᴰ (h := right_id_w w) c.\n  Proof.\n    intros A w c.\n    apply sig_ext. simpl.\n    apply right_id.\n  Qed.\n\n  Lemma assoc_w :\n    ∀ {A B C} (w : W A) (wf : A → W B) (wg : B → W C),\n      bind w (λ x, bind (wf x) wg) ≤ᵂ bind (bind w wf) wg.\n  Proof.\n    intros A B C w wf wg.\n    rewrite assoc. reflexivity.\n  Qed.\n\n  Lemma assoc :\n    ∀ A B C w wf wg (c : D A w) (f : ∀ x, D B (wf x)) (g : ∀ y, D C (wg y)),\n      bindᴰ (bindᴰ c f) g =\n      subcompᴰ (h := assoc_w _ _ _) (bindᴰ c (λ x, bindᴰ (f x) g)).\n  Proof.\n    intros A B C w wf wg c f g.\n    apply sig_ext. simpl.\n    apply assoc.\n  Qed.\n\nEnd PDM.", "meta": {"author": "TheoWinterhalter", "repo": "pdm4all", "sha": "570868f2e395bada6e3dc0462d7e9af065289461", "save_path": "github-repos/coq/TheoWinterhalter-pdm4all", "path": "github-repos/coq/TheoWinterhalter-pdm4all/pdm4all-570868f2e395bada6e3dc0462d7e9af065289461/theories/PDM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.3665897363221598, "lm_q1q2_score": 0.26686833219043166}}
{"text": "Require Import String.\nRequire Import NPeano.\nRequire Import PeanoNat.\nRequire Import Coq.Strings.Ascii.\nRequire FMapWeakList.\nRequire Export Coq.Structures.OrderedTypeEx.\nRequire Import Coq.Program.Equality.\n\nRequire Import Lists.List.\nImport ListNotations.\nRequire Import JaUtils.\nRequire Import JaSyntax.\nRequire Import JaProgram.\nRequire Import JaSubtype.\nRequire Import JaProgramWf.\nRequire Import Jafun.\nRequire Import JaTactics.\nRequire Import JaUnique.\nRequire Import JaEnvs.\nRequire Import JaTypes.\nOpen Scope list_scope.\nOpen Scope nat_scope.\n\nFrom Hammer Require Import Reconstr.\n\n\nSection RedInvariants.\n\n  Variable P : JFProgram.\n\n\nLemma internal_fields_unique :\n  Well_formed_program P ->\n  JFprogTypes P ->\n  forall n,\n  forall cdecl C ex flds mthds,\n    get_class_height P C = n ->\n    cdecl = JFCDecl C ex flds mthds ->\n    In cdecl P ->\n    exists fields, flds_overline P (JFClass C) = Some fields /\\\n      Flds.names_unique fields.\nProof.\n  intros Hwp Hpt; induction n.\n  + intros until 0.\n    intros Hch Hcd HIn.\n    eapply get_class_height_non_zero in Hch; try contradiction.\n    sauto.\n  + intros until 0.\n    intros Hch Hcd HIn.\n    inversion Hpt as [_ Hta].\n    rewrite Forall_forall in Hta.\n    assert (Ht:=Hta cdecl HIn).\n    inversion Ht as [? ? ? ? Hcd' _ Hfr ? | ? ? Hcd' _ ?].\n    ++ \n      rewrite Hcd in Hcd'.\n      symmetry in Hcd'; injection Hcd'; clear Hcd'; intros; subst.\n      generalize HIn; intros HfndC.\n      apply in_find_class in HfndC; auto.\n      destruct ex as [D |]; swap 1 2. \n      *\n        simpl.\n        rewrite Hch.\n        simpl.\n        rewrite HfndC.\n        simpl.\n        eauto.\n      * generalize HfndC; intros HfndD.\n        eapply find_class_get_class_height_find_class in HfndD; eauto 2.\n        destruct HfndD as (ddecl, HfndD).\n        assert (C<>D) as Hneq by (eapply ex_not_circular; eauto 2).\n        generalize Hneq; intros Hext.\n        eapply find_class_extends in Hext; eauto 2.\n        generalize Hext; intro Hdh.\n        eapply extends_get_class_height in Hdh; eauto 2.\n        rewrite Hch in Hdh.\n        injection Hdh; clear Hdh; intro Hdh; symmetry in Hdh.\n        destruct ddecl as [D' Dex Dfld Dmthds].\n        eapply IHn in Hdh; eauto 2 using find_class_in.\n        decompose_ex Hdh.\n        destruct Hdh as [HDo Hfu]. \n        eapply flds_overline_decl_extends_decompose in HIn; eauto 2.\n        eexists.\n        split; eauto 1.\n        apply Flds.names_unique_app; eauto 1.\n        red in Hfr.\n        apply Flds.name_noocc_recip.\n        eapply Hfr; swap 1 3; eauto 1; try congruence; eauto 2.\n    ++ \n      rewrite Hcd in Hcd'.\n      symmetry in Hcd'; injection Hcd'; clear Hcd'; intros; subst.\n      apply in_find_class in HIn; auto.\n      simpl.\n      rewrite Hch.\n      simpl.\n      rewrite HIn.\n      simpl.\n      eauto 3.\nQed.      \n\n\n\nLemma exists_fields_unique :\n  Well_formed_program P ->\n  JFprogTypes P ->\n  forall C cdecl ex flds mthds,\n    cdecl = JFCDecl C ex flds mthds ->\n    In cdecl P ->\n    exists fields,\n      flds_overline P (JFClass C) = Some fields /\\\n      Flds.names_unique fields.\nProof.\n  intros.\n  eapply internal_fields_unique; eauto 1.\nQed.\n\nLemma fields_unique :\n  Well_formed_program P ->\n  JFprogTypes P ->\n  forall C fields,\n    flds_overline P (JFClass C) = Some fields ->\n    Flds.names_unique fields.\nProof.\n  intros Hwp Htp ? ? HC.\n  generalize HC; intro Htmp.\n  unfold flds_overline in Htmp.\n  assert (exists cdecl, find_class P C = Some cdecl) as HfndC.\n  - destruct get_class_height in Htmp.\n    + simpl in Htmp.\n      destruct find_class as [cdecl|]; try discriminate.\n      eauto 2.\n    + simpl in Htmp.\n      destruct find_class as [cdecl|]; try discriminate.\n      eauto 2.\n  - destruct HfndC as [ cdecl HfndC ].\n    destruct cdecl.\n    eapply find_class_in in HfndC.\n    edestruct exists_fields_unique as (fields1 & HC1 & ?); eauto 1.\n    intuition.\n    replace fields with fields1; trivial.\n    congruence.\nQed.\n\nHint Resolve fields_unique.\n\nLemma subtype_flds_overline_decompose :\n  Well_formed_program P ->\n  JFprogTypes  P ->\n  forall C D,\n    subtyping P C D ->\n    forall Cfields Dfields,\n    flds_overline P C = Some Cfields ->\n    flds_overline P D = Some Dfields ->\n    exists flds, Cfields = flds ++ Dfields.\nProof.\n  intros Hwp Htp ? ? Hsub.\n  induction Hsub as [?|?|?|? ? ? ? ? ? ? Hext].\n  * intros.\n    exists [].\n    simpl.\n    congruence.\n  * intros ? Ofields HC HO.\n    destruct C as [Cname|]; [idtac | unfold flds_overline in HC; discriminate].\n    edestruct flds_overline_find_class as [cdecl HfndC].\n    eapply HC.\n    unfold flds_overline in HO.\n    unfold JFObject in HO.\n    rewrite <- (app_nil_l Ofields) in HO.\n    rewrite <- (app_nil_l Cfields) in HC.\n    generalize Hwp; intros (_ & Hpo & _).\n    generalize Hpo; intro Hfo.\n    eapply program_contains_find_class in Hfo.\n    destruct Hfo.\n    edestruct flds_aux_decompose_object as [flds Heq]; swap 1 3; [apply HfndC | eauto 3 ..].\n    * intros ? ? HB ?.\n      unfold flds_overline in HB; discriminate.\n    * intros ? Efields HC HE.\n      subst C D.\n      edestruct extends_in_second as (Dex & Dflds & Dmthds & HDIn); eauto 2.\n      edestruct exists_fields_unique as (Dfields & HD & HDu); eauto 2.\n      edestruct IHHsub as (flds', Heq); eauto 2.\n      \n      eapply flds_overline_extends_decompose in Hext; eauto 2.\n      destruct Hext as (Cflds & HC').\n      exists (Cflds ++ flds').\n      rewrite <- app_assoc.\n      congruence.\nQed.  \n  \n(** Field exists in subtype and its definition is the same *)\nLemma subtype_fields_same :\n  Well_formed_program P ->\n  JFprogTypes P ->\n  forall C D,\n    subtyping P C D ->\n    forall Cfields Dfields,\n    flds_overline P C = Some Cfields ->\n    flds_overline P D = Some Dfields ->\n    forall x,\n    In x (map Flds.name_of_decl Dfields) ->\n    Flds.find Cfields x = Flds.find Dfields x.\nProof.\n  intros Hwp Htp ? ? Hsub ? ? HC HD.\n  destruct C as [Cname|]; [idtac | unfold flds_overline in HC; discriminate].\n  destruct D as [Dname|]; [idtac | unfold flds_overline in HD; discriminate].\n  generalize HC; intro HCfu.\n  eapply fields_unique in HCfu; eauto 1.\n  edestruct subtype_flds_overline_decompose as (flds, Heq); eauto 1.\n  subst.\n  intros.\n  edestruct Flds.in_map_find; eauto 2.\n  erewrite Flds.find_app_r_unique; eauto 1.\nQed.\n  \n      \n(* TODO *)\n    (* Podtypowanie z Objectem powinno \"naturalnie\" zachodzić, nie powinno być konstruktora \n       subtyping P E Object, tylko lemat...\n       forall P, In C P -> subtyping C Object\n       przy założeniach:\n       object_not_extends\n       all_extend_but_object\n       program_contains_object\n       well_formed_program (ze jeśli JFDecl (Some D) ... \\in P to D też)\n     *)\n    (* Zresztą chyba dowód lematu \n       flds_aux_decompose_object\n       zawiera takie wyprowadzenie...\n     *)\n    \nRecord TypedFrame :=\n  TFR\n  { TFRcdecl : JFClassDeclaration;\n    TFRmdecl : JFMethodDeclaration;\n    TFRXi : JFExEnv;\n    TFRGamma : JFEnv;\n    TFRfr : Frame;\n    TFRAcid : JFACId\n  }.\n\n\nDefinition replace_fr_in_tfr fr tfr : TypedFrame :=\n  {| TFRcdecl := TFRcdecl tfr;\n     TFRmdecl := TFRmdecl tfr;\n     TFRXi := TFRXi tfr;\n     TFRGamma := TFRGamma tfr;\n     TFRfr := fr;\n     TFRAcid := TFRAcid tfr\n  |}.\n\nLemma TFRfr_replace_fr_in_tfr:\n  forall fr tfr,\n    TFRfr (replace_fr_in_tfr fr tfr) = fr.\nProof.\n  intros.\n  simpl;auto.\nQed.\n\n(*\n\nDefinition replace_fr_in_tfr (fr: Frame) (tfr: TypedFrame) : TypedFrame.\ndestruct tfr; clear TFRfr0; now constructor.\nDefined.\nPrint replace_fr_in_tfr.\n\n(* more direct definition, more eager to reduce - but breaks some existing proofs  :( *)\n\n  match tfr with\n| {| TFRcdecl := TFRcdecl0; TFRmdecl := TFRmdecl0; TFRXi := TFRXi0; TFRGamma := TFRGamma0; TFRAcid\n  := TFRAcid0 |} =>\n    {|\n    TFRcdecl := TFRcdecl0;\n    TFRmdecl := TFRmdecl0;\n    TFRXi := TFRXi0;\n    TFRGamma := TFRGamma0;\n    TFRfr := fr;\n    TFRAcid := TFRAcid0 |}\nend.\n*)\n\n\n\n\n\n\nDefinition update_env_in_fr tfr l0 acid : TypedFrame :=\n  {| TFRcdecl := TFRcdecl tfr;\n     TFRmdecl := TFRmdecl tfr;\n     TFRXi := TFRXi tfr;\n     TFRGamma := oPlus P (TFRGamma tfr) l0 acid;\n     TFRfr := TFRfr tfr;\n     TFRAcid := TFRAcid tfr\n  |}.\n\nLemma update_env_null : forall e acid,\n    update_env_in_fr e null acid = e.\nProof.\n  intros.\n  unfold update_env_in_fr.\n  destruct e.\n  simpl.\n  f_equal.\n  destruct TFRGamma0; trivial.\nQed.\n\n\n  \n(** The definition of \"derivable extended context expression\" from\n    the paper. *)\nDefinition DerivableTFR (tfr : TypedFrame) :=\n  match tfr with\n    TFR cdecl mdecl Xi Gamma fr Acid =>\n    find_class P (name_of_cd cdecl) = Some cdecl /\\\n    methodLookup P (name_of_cd cdecl) (name_of_md mdecl) = Some mdecl /\\\n    (match fr with\n     | Ctx [[E ]]_ Some _ =>\n       exists v, E=JFVal1 v /\\ typesCtx P cdecl mdecl Xi Gamma (JFThrow v) Ctx Acid\n     | Ctx [[E ]]_ None => typesCtx P cdecl mdecl Xi Gamma E Ctx Acid\n     end)\n  end.\n\nDefinition TypedFrameStack := list TypedFrame.\n\n\nDefinition FSofTFS (tfs:TypedFrameStack) : FrameStack := map TFRfr tfs.\n\n\nDefinition HeapAgreesLocDecl (h:Heap) (ValAcid : JFVal * JFACId) :=\n  let (v, acid) := ValAcid in\n  let (cid, _) := acid in\n  match v with\n  | JFnull => False\n  | JFVLoc (JFLoc n) =>\n    exists (ro : RawObj) (cn : JFClassName),\n      Heap.find (*elt:=Obj*) n h = Some (ro, cn) /\\ subtyping P (JFClass cn) cid\n  | JFSyn _ => False\n  end.\n\n\nDefinition HeapAgreesEnv (h:Heap) (Gamma:JFEnv) : Prop :=\n  Forall (HeapAgreesLocDecl h) Gamma.\n\n\n\n\nLemma heap_find_HeapAgreesEnv:\n  forall n h o Cn Did mu Gamma,\n    names_unique P ->\n    subtype_well_founded P ->\n    Heap.find (elt:=Obj) n h = Some (o, Cn) ->\n    subtyping P (JFClass Cn) Did -> \n    HeapAgreesEnv h Gamma ->\n    HeapAgreesEnv h (oPlus P Gamma (JFLoc n) (Did,mu)).\nProof.\n  intros until 0.\n  intros Nuq Swf Hf HsubCD.\n  induction 1 as [ | (x1,(Cid1,mu1)) Gamma Hhal ?].\n  + simpl.\n    repeat constructor.\n    red.\n    do 2 eexists.\n    split; eauto 1.\n  + unfold oPlus; fold oPlus.\n    destruct (JFVal_dec x1 (JFVLoc (JFLoc n))); swap 1 2.\n    { now constructor. }\n    subst x1.\n    constructor; try assumption.\n    simpl.\n    do 2 eexists.\n    split; eauto 1.\n    inversion Hhal as (x,(cn,[Hf' Hsub])).\n    rewrite Hf in Hf'.\n    injection Hf'; clear Hf'; intros; subst x cn.\n    eapply infClass_inf; swap 1 5; eauto 1.\nQed.\n\nLemma HeapAgreesEnv_subtyping:\n  forall n C mu (Gamma:JFEnv) h obj D,\n    In (JFVLoc (JFLoc n), (C, mu)) Gamma ->\n    HeapAgreesEnv h Gamma ->\n    Heap.find (elt:=Obj) n h = Some (obj, D) ->\n    subtyping P (JFClass D) C.\nProof.\n  intros * InG HAE Hfnd.\n  unfold HeapAgreesEnv in HAE.\n  eapply Forall_forall in HAE; try eapply InG.\n  simpl in HAE.\n  decompose_ex HAE.\n  decompose_and HAE as [Fnd Sub].\n  congruence.\nQed.\n\n(** Properties that must be satisfied by all [TypedFrame]s \n    in a dynamic typing assertion. *) \n\nDefinition ConsistentTFR (h:Heap) (* W, R *) (tfr : TypedFrame) :=\n  Forall (fun '(v, _) => isNonNullLoc v) (TFRGamma tfr)\n  /\\\n  Env.names_unique (TFRGamma tfr)\n  /\\\n  (* NPE loc has some type <: JFNPE and rwr mode *)\n  (exists Cnpe, In (NPE_val, (Cnpe, JFrwr)) (TFRGamma tfr) /\\ subtyping P Cnpe JFNPE)\n  /\\\n  HeapAgreesEnv h (TFRGamma tfr)\n  (* /\\ something about W and R B.3.(1)c *)\n.\n\nLemma ConsistentTFR_isNonNullLoc:\n  forall h tfr,\n    ConsistentTFR h tfr ->\n    Forall (fun '(v, _) => isNonNullLoc v) (TFRGamma tfr).\nProof.\n  intros.\n  unfold ConsistentTFR in H;decompose [and] H;eauto.\nQed.\n  \nLemma ConsistentTFR_names_unique:\n  forall h tfr,\n    ConsistentTFR h tfr ->\n    Env.names_unique (TFRGamma tfr).\nProof.\n  intros.\n  unfold ConsistentTFR in H;decompose [and] H;eauto.\nQed.\n\nLemma ConsistentTFR_HeapAgreesEnv:\n  forall h tfr,\n    ConsistentTFR h tfr ->\n    HeapAgreesEnv h (TFRGamma tfr).\nProof.\n  intros.\n  unfold ConsistentTFR in H;decompose [and] H;eauto.\nQed.\n\n\nLemma ConsistentTFR_subtyping:\n  forall h tfr n oo C C' mu',\n    ConsistentTFR h tfr ->\n    Heap.find (elt:=Obj) n h = Some (oo, C) ->\n    In (JFVLoc (JFLoc n), (C', mu')) (TFRGamma tfr) ->\n    subtyping P (JFClass C) C'.\nProof.\n  intros.\n  unfold ConsistentTFR in H.\n  destruct H as (H2 & _ & Hnpe & H3).\n  unfold HeapAgreesEnv in H3.\n  eapply Forall_forall in H1; try eapply H3.\n  simpl in H1.\n  decompose_ex H1.\n  destruct H1.\n  eqf.\n  now intros _ [= ->].\nQed.\n\nInductive ConsistentTFSind (h:Heap) : TypedFrameStack -> Prop :=\n| ConsistentTFSind1 : forall tfr, ConsistentTFR h tfr -> ConsistentTFSind h [tfr]\n| ConsistentTFSind2 : forall tfri1 tfri tfstail n m vs Ctx robj cn,\n    ConsistentTFSind h (tfri :: tfstail) ->\n    ConsistentTFR h tfri1 -> \n    (* C i,expr = C[[l.m(ll)]]_∅ , with l ̸= null *)\n    TFRfr tfri = Ctx [[JFInvoke (JFVLoc (JFLoc n)) m vs ]]_ None ->\n    Forall isLoc vs ->\n    (* class(h, l) = C1 and C i+1,class = C1 and *)\n    Heap.find n h = Some (robj,cn) ->\n    name_of_cd (TFRcdecl tfri1) = cn ->\n    (* C i+1,meth = m *) \n    name_of_md (TFRmdecl tfri1) = m ->\n    (* and C i+1,exc = thrs(C1 , m) *)    (* we will check that mdecl really comes from cdecl later *)\n    TFRXi tfri1 = thrs_of_md (TFRmdecl tfri1) ->\n    (* ⟨C i+1,type , C i+1,mod ⟩ = retTypM(C1 , m) *)\n    TFRAcid tfri1 = rettyp_of_md (TFRmdecl tfri1) ->\n\n    (* if isLS(C i,meth ) then isLS(C i+1,meth ) *)\n    (isLS (TFRmdecl tfri) -> isLS (TFRmdecl tfri1)) -> \n    \n    ConsistentTFSind h (tfri1 :: tfri :: tfstail).\n\nLemma ConsistentTFSind_TFR:\n  forall h tfr tl,\n  ConsistentTFSind h (tfr :: tl) ->\n  ConsistentTFR h tfr.\nProof.\n  intros.\n  inversion H;auto.\nQed.\n\nLemma ConsistentTFSind_wfs:\n  forall h tfs,\n    ConsistentTFSind h tfs ->\n    well_formed_framestack (FSofTFS tfs).\nProof.\n  induction 1.\n  - simpl; trivial.\n  - simpl in *.\n    rewrite H1.\n    trivial.\nQed.\nHint Resolve ConsistentTFSind_wfs.\n\n(*\nLemma ConsistentTFSind_update_env_in_fr:\n  forall h e tl v o Cn Did mu,\n    ConsistentTFSind h (e :: tl) ->\n    Heap.find (elt:=Obj) v h = Some (o, Cn) ->\n    subtyping P (JFClass Cn) Did -> \n    ConsistentTFSind h ((update_env_in_fr e  (JFLoc v) (Did,mu)) :: tl).\nProof.\n  intros until 0.\n  intros IsTFS Hpfnd Hsub.\n  destruct tl.\n  + apply ConsistentTFSind1.\n    inversion IsTFS.\n    subst.\n    unfold ConsistentTFR in *.\n    decompose [and] H0; clear H0.\n    repeat split.\n    ++ destruct e.\n       simpl in *.\n       eauto using oPlus_non_null.\n    ++ simpl.\n       eapply heap_find_HeapAgreesEnv; eauto 1.\n  + inversion IsTFS.\n    eapply ConsistentTFSind2;eauto 1.\n    subst.\n    unfold ConsistentTFR in *.\n    decompose [and] H3; clear H3.\n    repeat split.\n    ++ destruct e.\n       simpl in *.\n       eauto using oPlus_non_null.\n    ++ simpl.\n       eapply heap_find_HeapAgreesEnv; eauto 1.\nQed.\n\n*)\n(** The property that a derivable extended context expression\n    support is a dynamic typing assertion.\n\n   Definition {def:dta} in Appendix B.\n*)\nInductive ConsistentTFS (h:Heap) : TypedFrameStack -> Prop :=\n| ConsistentTFSnone :\n    forall tfrn tfs Ctx E,\n      ConsistentTFSind h (tfrn::tfs) ->\n      TFRfr tfrn = Ctx [[E]]_ None ->\n      ConsistentTFS h (tfrn::tfs)\n| ConsistentTFSexc :\n    forall tfrn tfs Ctx n D robj,\n      ConsistentTFSind h (tfrn::tfs) ->\n      TFRfr tfrn = Ctx [[JFVal1 (JFVLoc (JFLoc n))]]_ (Some D) ->\n      Heap.find n h = Some (robj, D) ->\n      ConsistentTFS h (tfrn::tfs).\n\n\nLemma ConsistentTFS_wfs:\n  forall h tfs,\n    ConsistentTFS h tfs ->\n    well_formed_framestack (FSofTFS tfs).\nProof.\n  destruct 1; eauto 2.\nQed.\nHint Resolve ConsistentTFS_wfs.\n\n\nLemma ConsistentTFS_further:\n  forall h tfrn1 tfrn2 tfs,\n    ConsistentTFS h (tfrn1::tfrn2::tfs) -> ConsistentTFS h (tfrn2::tfs).\nProof.\n  induction tfs.\n  * intros. \n    inversion H; (\n      subst;\n       inversion H2;\n       subst;\n       try inversion H5;\n       try inversion H6;\n       subst;\n       eapply ConsistentTFSnone;eauto 1\n    ).\n  * intros.\n    inversion H.\n    ** subst.\n       inversion H2.\n       subst.\n       eapply ConsistentTFSnone;eauto 1.\n    ** subst.\n       inversion H2.\n       subst.\n       eapply ConsistentTFSnone;eauto 1.\nQed.\n\nDefinition DerivableTFS (h:Heap) (tfs:TypedFrameStack) : Prop :=\n  ConsistentTFS h tfs /\\ Forall DerivableTFR tfs.\n\nLemma DerivableTFS_wfs:\n  forall h tfs,\n    DerivableTFS h tfs ->\n    well_formed_framestack (FSofTFS tfs).\nProof.\n  destruct 1; eauto 2.\nQed.\nHint Resolve DerivableTFS_wfs.\n\nLemma DerivableTFS_further:\n  forall h e e0 tfs,\n    DerivableTFS h (e :: e0 ::tfs) ->\n    DerivableTFS h (e0 :: tfs).\nProof.\n  intros.\n  unfold DerivableTFS in H.\n  decompose_and H.\n  split.\n  + eauto using ConsistentTFS_further.\n  + eapply Forall_forall.\n    intros.\n    eapply Forall_forall in H1.\n    apply H1.\n    simpl.\n    right.\n    auto.\nQed.\n\nLemma ConsistentTFS_DTFR_DerivableTFS:\n  forall h tfs,\n    ConsistentTFS h tfs ->\n    Forall DerivableTFR tfs ->\n    DerivableTFS h tfs.\nProof.\n  unfold DerivableTFS;eauto 2.\nQed.\n\nLemma ConsistentTFS_one : forall h tfs,\n    ConsistentTFS h tfs -> Forall (ConsistentTFR h) tfs.\nProof.\n  destruct 1; induction H; auto.\nQed. \n\nLemma DerivableTFS_ConsistentTFR:\n  forall h tfr tfs,\n    DerivableTFS h (tfr::tfs) -> ConsistentTFR h tfr.\nProof.\n  intros.\n  unfold DerivableTFS in H.\n  destruct H.\n  eapply ConsistentTFS_one in H.\n  eapply Forall_inv in H.\n  assumption.\nQed.\n\nHint Resolve DerivableTFS_ConsistentTFR ConsistentTFSind_TFR HeapAgreesEnv_subtyping.\nHint Resolve ConsistentTFS_one ConsistentTFS_DTFR_DerivableTFS.\n\n\n\n\n\n\n\nLemma DerNU_first :\n  forall h tfr frs, DerivableTFS h (tfr :: frs) -> Env.names_unique (TFRGamma tfr).\nProof.\n  intros * H.\n  apply DerivableTFS_ConsistentTFR in H.\n  red in H.\n  tauto.\nQed.\n\nHint Resolve DerNU_first.\n\nLemma DerNU_first' :\n  forall h TFRcdecl0 TFRmdecl0 TFRXi0 TFRGamma0 TFRfr0 TFRAcid0 frs, DerivableTFS h\n    ({|\n     TFRcdecl := TFRcdecl0;\n     TFRmdecl := TFRmdecl0;\n     TFRXi := TFRXi0;\n     TFRGamma := TFRGamma0;\n     TFRfr := TFRfr0;\n     TFRAcid := TFRAcid0 |} :: frs) -> Env.names_unique TFRGamma0.\nProof.\n  intros * H.\n  apply DerivableTFS_ConsistentTFR in H.\n  red in H.\n  tauto.\nQed.\n\nHint Immediate DerNU_first'.\n\nLemma DerNU_second' :\n  forall h tfr' TFRcdecl0 TFRmdecl0 TFRXi0 TFRGamma0 TFRfr0 TFRAcid0 frs, DerivableTFS h\n    (tfr' :: {|\n     TFRcdecl := TFRcdecl0;\n     TFRmdecl := TFRmdecl0;\n     TFRXi := TFRXi0;\n     TFRGamma := TFRGamma0;\n     TFRfr := TFRfr0;\n     TFRAcid := TFRAcid0 |} :: frs) -> Env.names_unique TFRGamma0.\nProof.\n  intros * [H _].\n  apply ConsistentTFS_further in H.\n  apply ConsistentTFS_one in H.\n  sauto.\nQed.\n\nHint Immediate DerNU_second'.\n\nLemma DerNU_second :\n  forall h tfr' tfr fr, DerivableTFS h (tfr' :: tfr :: fr) -> Env.names_unique (TFRGamma tfr).\nProof.\n  intros * [H _].\n  apply ConsistentTFS_further in H.\n  apply ConsistentTFS_one in H.\n  sauto.\nQed.\n\nHint Resolve DerNU_second.\n\nLemma findAssoc_forDTFS_Invoke:\n  forall h fm1 fm2 tfs Ctx n m vs,\n    Well_formed_program P ->\n    DerivableTFS h (fm1 :: fm2 :: tfs) ->\n    TFRfr fm2 = Ctx [[JFInvoke (JFVLoc (JFLoc n)) m vs ]]_ None ->\n    exists D mu,\n      Env.find (TFRGamma fm2) (JFVLoc (JFLoc n)) = Some (JFVLoc (JFLoc n), (D, mu)).\nProof.\n  intros h fm1 fm2 tfs Ctx n m vs Wfp Dtfs FrOfFm2.\n  inversion Dtfs as [IsTFS DTFRs].\n  inversion DTFRs as [|tfrfst tfrtl DTFRfst DTFRtl tfrfsteq].\n  subst.\n  inversion DTFRtl as [|tfrsnd tfrtltl DTFRsnd DerDte].\n  subst.\n  unfold DerivableTFR in DTFRsnd.\n  destruct fm2.\n  simpl in *.\n  rewrite FrOfFm2 in DTFRsnd.\n  destruct DTFRsnd as (Fcls & MthdLkp & TpsCtx).\n  apply typesCtx_typesCtxExt in TpsCtx; try assumption.\n  destruct TpsCtx as [X11 [Acid1 TpsCtx]].\n  apply typesCtxExt_types in TpsCtx.\n  destruct Acid1 as (C,mu).\n  eapply inversion_JFInvoke in TpsCtx; eauto 2.\n\n  destruct TpsCtx as [D0 [dname [mu0 [D' [mu' [mthrs [rettyp info]]]]]]].\n  destruct info as [H1 [HtypesVal info]].\n  decompose [and] info.\n  clear info.\n  eapply inversion_JFVal1_nonnull in HtypesVal; eauto 2; try congruence.\n\n  decompose_ex HtypesVal.  \n  destruct HtypesVal as [? [HIn ?]].\n  eapply Env.In_find_exists in HIn; eauto 2.\n  decompose_ex HIn.\n  destruct d' as (?, (D, mu1)).\n  destruct HIn as [HIn [= ->]].\n  eauto 3.\nQed.\n\n\nLemma findAssoc_forDTFS_Val1:\n  forall (h : Heap) (fm : TypedFrame) (tfs : list TypedFrame) \n         (Ctx : JFContext) (n : nat) (md : JFEvMode),\n    Well_formed_program P ->\n    DerivableTFS h (fm :: tfs) ->\n    TFRfr fm = Ctx [[JFVal1 (JFVLoc (JFLoc n)) ]]_ md ->\n    exists (D : JFCId) (mu : JFAMod),\n      Env.find (TFRGamma fm) (JFVLoc (JFLoc n)) = Some (JFVLoc (JFLoc n),(D, mu)).\nProof.\n  intros h fm tfs Ctx n md Wfp Dtfs FrOfFm2.\n  inversion Dtfs as [IsTFS DTFRs].\n  inversion DTFRs as [|tfrfst tfrtl DTFRfst DTFRtl tfrfsteq].\n  subst.\n  unfold DerivableTFR in DTFRfst.\n  destruct fm.\n  simpl in *.\n  rewrite FrOfFm2 in DTFRfst.\n  destruct DTFRfst as (Fcls & MthdLkp & TpsCtx).\n  destruct md.\n  + destruct TpsCtx as [v [ValV TpsCtx]].\n    apply typesCtx_typesCtxExt in TpsCtx; try assumption.\n    destruct TpsCtx as [X11 [Acid1 TpsCtx]].\n    apply typesCtxExt_types in TpsCtx.\n    destruct Acid1 as (C,mu).\n    eapply inversion_Throw in TpsCtx; eauto 2.\n\n    destruct TpsCtx as [m [C1 [D [mu' [mis [Cis [TpsV [IsLeqIncluded TpsThr]]]]]]]].\n    injection ValV;intros.\n    subst.\n    eapply inversion_JFVal1_nonnull in TpsV; eauto 2; try discriminate.\n    destruct TpsV as [C'' [mu'' [LeqIsLS [Inn TpsV]]]].\n    eapply Env.In_find in Inn; eauto 1.\n    eauto.\n  + apply typesCtx_typesCtxExt in TpsCtx; try assumption.\n    decompose_ex TpsCtx.\n    apply typesCtxExt_types in TpsCtx.\n    destruct Acid1.\n    eapply inversion_JFVal1_nonnull in TpsCtx; eauto 2; try discriminate.\n    destruct TpsCtx as [? [? [? [HIn ?]]]].\n    eapply Env.In_find in HIn; eauto 1.\n    decompose_ex HIn.\n    eauto 3.\nQed.\n\n\n\n\nLemma getClassName_forDTFS:\n  forall h fm2 tfs Ctx n m vs,\n    Well_formed_program P ->\n    DerivableTFS h (fm2 :: tfs) ->\n    TFRfr fm2 = Ctx [[JFInvoke (JFVLoc (JFLoc n)) m vs ]]_ None ->\n    exists dname,\n    getClassName h n = Some dname.\nProof.\n  intros h fm2 tfs Ctx n m vs Wfp Dtfs FrOfFm2.\n  inversion Dtfs as [IsTFS DTFRs].\n  eapply Forall_inv in DTFRs.\n  unfold DerivableTFR in DTFRs.\n  destruct fm2.\n  simpl in *.\n  rewrite FrOfFm2 in DTFRs.\n  destruct DTFRs as (Fcls & MthdLkp & TpsCtx).\n  eapply typesCtx_typesCtxExt1 in TpsCtx; eauto 2.\n  destruct TpsCtx as [Xi1 [Acid1 TpsCtxExt]].\n  eapply typesCtxExt_types in TpsCtxExt;eauto 1.\n  destruct Acid1.\n  eapply inversion_JFInvoke in TpsCtxExt;eauto 2.\n  destruct TpsCtxExt as [D [dname [mu [D' [mu' [mthrs [retyp TpsCtxExt]]]]]]].\n  destruct TpsCtxExt as [Dname [TpsVal1 TpsCtxExt]].\n  eapply inversion_JFVal1_nonnull in TpsVal1;eauto 2;try congruence.\n  inversion IsTFS as [tfrn tfs0 Ctx0 E IsTFSindFm12 TFRfrfm1|\n                      tfrn tfs0 Ctx0 n0 D0 robj IsTFSindFm12\n                           TFRfrfm1 Hpfnd].\n  * simpl in *. subst.\n    clear TFRfrfm1 E Ctx0.\n    inversion IsTFSindFm12 as [|tfri1 tfri tfstail \n                                     n0 m0 vs0 Ctx1 robj cn\n                                     IsTFSindfm2 AuxTFSonefm1\n                                     TFRfrfm2 FaIsLoc\n                                     Hpfnd cneq m0eq TFRXieq\n                                     TFRAcideq IsLSimpl].\n    ** subst.\n       unfold ConsistentTFR in H.\n       simpl in H.\n       destruct H as (_ & _ & _ & H1).\n       unfold HeapAgreesEnv in H1.\n       destruct TpsVal1 as [C'' [mu'' [Leq [InTFRGamma0 TpsVal1]]]].\n       eapply Forall_forall in InTFRGamma0; try apply H1.\n       unfold HeapAgreesLocDecl in InTFRGamma0.\n       decompose_ex InTFRGamma0. \n       destruct InTFRGamma0 as [Hpfnd _].\n       unfold getClassName.\n       rewrite Hpfnd.\n       eexists;eauto 1.\n    ** subst.\n       simpl in *.\n       unfold ConsistentTFR in AuxTFSonefm1.\n       simpl in AuxTFSonefm1.\n       destruct AuxTFSonefm1 as (_ & _ & _ & H0).\n       unfold HeapAgreesEnv in H0.\n       destruct TpsVal1 as [C'' [mu'' [Leq [InTFRGamma0 TpsVal1]]]].\n       eapply Forall_forall in InTFRGamma0; try apply H0.\n       unfold HeapAgreesLocDecl in InTFRGamma0.\n       destruct InTFRGamma0 as [ro [cn [Hpfnd1 sbt]]].\n       unfold getClassName.\n       rewrite Hpfnd1.\n       eexists;eauto 1.\n  * subst.\n    inversion IsTFSindFm12 as [|tfri1 tfri tfstail \n                                     n0' m0' vs0' Ctx1 robj' cn\n                                     IsTFSindfm2 AuxTFSonefm1\n                                     TFRfrfm2 FaIsLoc\n                                     Hpfndn0' cneq m0eq TFRXieq\n                                     TFRAcideq IsLSimpl].\n    ** subst.\n       unfold ConsistentTFR in H.\n       simpl in H.\n       destruct H as (_ & _ & _ & H1).\n       unfold HeapAgreesEnv in H1.\n       destruct TpsVal1 as [C'' [mu'' [Leq [InTFRGamma0 TpsVal1]]]].\n       eapply Forall_forall in InTFRGamma0; try apply H1.\n       unfold HeapAgreesLocDecl in InTFRGamma0.\n       destruct InTFRGamma0 as [ro [cn [Hpfnd1 sbt]]].\n       unfold getClassName.\n       rewrite Hpfnd1.\n       eexists;eauto 1.\n    ** subst.\n       simpl in *.\n       unfold ConsistentTFR in AuxTFSonefm1.\n       simpl in AuxTFSonefm1.\n       destruct AuxTFSonefm1 as (_ & _ & _ & H0).\n       unfold HeapAgreesEnv in H0.\n       destruct TpsVal1 as [C'' [mu'' [Leq [InTFRGamma0 TpsVal1]]]].\n       eapply Forall_forall in InTFRGamma0; try apply H0.\n       unfold HeapAgreesLocDecl in InTFRGamma0.\n       destruct InTFRGamma0 as [ro [cn [Hpfnd1 sbt]]].\n       unfold getClassName.\n       rewrite Hpfnd1.\n       eexists;eauto 1.\nQed.\n\nLemma methodLookup_forDTFS:\n  forall h fm1 fm2 tfs Ctx n m vs dname,\n    Well_formed_program P ->\n    DerivableTFS h (fm1 :: fm2 :: tfs) ->\n    TFRfr fm2 = Ctx [[JFInvoke (JFVLoc (JFLoc n)) m vs ]]_ None ->\n    getClassName h n = Some dname ->\n    exists md,\n      methodLookup P dname m = Some md.\nProof.\n  intros h fm1 fm2 tfs Ctx n m vs dname Wfp Dtfs FrOfFm2 GetClNm.\n  inversion Dtfs as [IsTFS DTFRs].\n  inversion DTFRs as [|tfrn tfrtl Dtfrfm1 DTFRs1].\n  subst.\n  inversion DTFRs1 as [|tfrn1 tfrtl1 Dtfrfm2 DTFRs2].\n  subst.\n  unfold DerivableTFR in Dtfrfm2.\n  destruct fm2.\n  destruct Dtfrfm2 as (Fcls & MthdLkp & TpsCtxInvk).\n  simpl in *.\n  inversion IsTFS as [fm1' tfs' Ctx0 E IsTFSind TFRfrfm1|\n                      tfrn tfs0 Ctx0 n0 D robj IsTFSind TFRfrfm1 HpFnd].\n  * (* non-exception *) subst.\n    inversion IsTFSind as [|tfri1 tfri tfstail n0 m0 vs0 Ctx1 robj cn\n                                 IsTFSindfm2 AuxTFSonefm1 TFRfreq IsLocAll HpFnd\n                                 NameCd NameMd TFRXieq TFRAcideq IsLSimpl].\n    simpl in *.\n    injection TFRfreq;intros;clear TFRfreq.\n    subst.\n    apply typesCtx_typesCtxExt in TpsCtxInvk; try assumption.\n    destruct TpsCtxInvk as [Xi1 [Acid1 TpsCtxInvk]].\n    apply typesCtxExt_types in TpsCtxInvk.\n    destruct Acid1 as (C,mu).\n    eapply inversion_JFInvoke in TpsCtxInvk; eauto 2.\n    destruct TpsCtxInvk as [D0 [dname' [mu0 [D' [mu' [mthrs [rettyp info]]]]]]].\n    destruct info as [nameq [TpsVal [ParTypM info]]].\n    destruct D0;try discriminate nameq.\n    injection nameq;intros;clear nameq;subst.\n    unfold parTypM in ParTypM.\n    destruct (methodLookup P dname' (name_of_md (TFRmdecl fm1))) eqn:mthdLkp;\n      try discriminate ParTypM.\n    eapply inversion_JFVal1_nonnull in TpsVal;\n      try apply Fcls;try trivial;try discriminate;eauto 2.\n    destruct TpsVal as [dname'' [mu'' [LeqIsLS [Inn0 TpsVal]]]].\n    assert (ConsistentTFR h\n                {|\n                TFRcdecl := TFRcdecl0;\n                TFRmdecl := TFRmdecl0;\n                TFRXi := TFRXi0;\n                TFRGamma := TFRGamma0;\n                TFRfr := Ctx1\n                         [[JFInvoke (JFVLoc (JFLoc n0))\n                             (name_of_md (TFRmdecl fm1)) vs0 ]]_ None;\n                TFRAcid := TFRAcid0 |})\n      as AuxTFSone by (inversion IsTFSindfm2;auto).\n    inversion AuxTFSone as (NonNull & _ & _ & HpAgreesEnv).\n    simpl in *.\n    unfold HeapAgreesEnv in HpAgreesEnv.\n    assert (forall x : JFVal * JFACId,\n               In x TFRGamma0 -> HeapAgreesLocDecl h x)\n      as HpAgreesEnv' by\n          (apply (Forall_forall (HeapAgreesLocDecl h) TFRGamma0);\n           auto).\n    apply HpAgreesEnv' in Inn0.\n    simpl in Inn0.\n    destruct Inn0 as [ro [cn [Hfnd subt]]].\n    rewrite HpFnd in Hfnd.\n    injection Hfnd;intros;clear Hfnd;subst.\n    unfold getClassName in GetClNm.\n    rewrite HpFnd in GetClNm.\n    injection GetClNm;intros;clear GetClNm;subst.\n    assert (subtyping P (JFClass (name_of_cd (TFRcdecl fm1)))\n                      (JFClass dname')) as Sbtp.\n    { inversion LeqIsLS.\n      + injection H1;intros;clear H1.\n        injection H2;intros;clear H2.\n        subst.\n        eapply subtrans;eauto 2.\n      + injection H1;intros;clear H1.\n        injection H2;intros;clear H2.\n        subst.\n        eapply subtrans;eauto 2.\n    }\n    unfold DerivableTFR in Dtfrfm1.\n    destruct fm1.\n    simpl in *.\n    decompose [and] Dtfrfm1.\n    eapply lookup_in_supertype_subtype;\n      try apply Sbtp; try apply mthdLkp; eauto 2.\n  * (* exception *)\n    subst.\n    inversion IsTFSind as [|tfri1 tfri tfstail n1 m1 vs1 Ctx1 robj1 cn\n                                  IsTFSindfm2 AuxTFSonefm1 TFRfreq IsLocAll\n                                  HpFnd1\n                                  NameCd NameMd TFRXieq TFRAcideq IsLSimpl].\n    simpl in *.\n    injection TFRfreq;intros;clear TFRfreq.\n    subst.\n    apply typesCtx_typesCtxExt in TpsCtxInvk; try assumption.\n    destruct TpsCtxInvk as [Xi1 [Acid1 TpsCtxInvk]].\n    apply typesCtxExt_types in TpsCtxInvk.\n    destruct Acid1 as (C,mu).\n    eapply inversion_JFInvoke in TpsCtxInvk; eauto 2.\n    destruct TpsCtxInvk as [D0 [dname' [mu0 [D' [mu' [mthrs [rettyp info]]]]]]].\n    destruct info as [nameq [TpsVal [ParTypM info]]].\n    destruct D0;try discriminate nameq.\n    injection nameq;intros;clear nameq;subst.\n    unfold parTypM in ParTypM.\n    destruct (methodLookup P dname' (name_of_md (TFRmdecl fm1))) eqn:mthdLkp;\n      try discriminate ParTypM.\n    eapply inversion_JFVal1_nonnull in TpsVal;\n      try apply Fcls;try trivial;try discriminate;eauto 2.\n    destruct TpsVal as [dname'' [mu'' [LeqIsLS [Inn0 TpsVal]]]].\n    assert (ConsistentTFR h\n                {|\n                TFRcdecl := TFRcdecl0;\n                TFRmdecl := TFRmdecl0;\n                TFRXi := TFRXi0;\n                TFRGamma := TFRGamma0;\n                TFRfr := Ctx1\n                         [[JFInvoke (JFVLoc (JFLoc n0))\n                             (name_of_md (TFRmdecl fm1)) vs1 ]]_ None;\n                TFRAcid := TFRAcid0 |})\n      as AuxTFSone by (inversion IsTFSindfm2;auto).\n    inversion AuxTFSone as (NonNull & _ & _ & HpAgreesEnv).\n    simpl in *.\n    unfold HeapAgreesEnv in HpAgreesEnv.\n    assert (forall x : JFVal * JFACId,\n               In x TFRGamma0 -> HeapAgreesLocDecl h x)\n      as HpAgreesEnv' by\n          (apply (Forall_forall (HeapAgreesLocDecl h) TFRGamma0);\n           auto).\n    apply HpAgreesEnv' in Inn0.\n    simpl in Inn0.\n    destruct Inn0 as [ro [cn [Hfnd subt]]].\n    rewrite HpFnd1 in Hfnd.\n    injection Hfnd;intros;clear Hfnd;subst.\n    unfold getClassName in GetClNm.\n    rewrite HpFnd1 in GetClNm.\n    injection GetClNm;intros;clear GetClNm;subst.\n    assert (subtyping P (JFClass (name_of_cd (TFRcdecl fm1)))\n                      (JFClass dname')) as Sbtp.\n    { inversion LeqIsLS.\n      + injection H1;intros;clear H1.\n        injection H2;intros;clear H2.\n        subst.\n        eapply subtrans;eauto 2.\n      + injection H1;intros;clear H1.\n        injection H2;intros;clear H2.\n        subst.\n        eapply subtrans;eauto 2.\n    }\n    unfold DerivableTFR in Dtfrfm1.\n    destruct fm1.\n    simpl in *.\n    decompose [and] Dtfrfm1.\n    eapply lookup_in_supertype_subtype;\n      try apply Sbtp; try apply mthdLkp; eauto 2.\nQed.\n\n\nLemma ConsistentTFStoIsTFSe:\n  forall tfri tfri' h tfstail Ctx n A robj,\n    TFRfr tfri' = Ctx [[JFVal1 (JFVLoc (JFLoc n)) ]]_ Some A ->\n    TFRcdecl tfri' = TFRcdecl tfri ->\n    TFRmdecl tfri' = TFRmdecl tfri ->\n    TFRXi tfri' = TFRXi tfri ->\n    TFRGamma tfri' = TFRGamma tfri ->\n    TFRAcid tfri' = TFRAcid tfri ->\n    Heap.find (elt:=Obj) n h = Some (robj, A) ->\n    ConsistentTFSind h (tfri :: tfstail) ->\n    ConsistentTFS h (tfri' :: tfstail).\nProof.\n  intros tfri tfri' h tfstail Ctx n A robj eqfr eqcdecl eqmdecl\n         eqxi eqgamma eqacid hfind IsTFSind.\n  inversion IsTFSind as [tfri'' Aux eq1|tfri'' tfri''' tfrtl].\n  * eapply ConsistentTFSexc; eauto 1.\n    eapply ConsistentTFSind1.\n    unfold ConsistentTFR.\n    rewrite eqgamma.\n    unfold ConsistentTFR in Aux.\n    auto.\n  * eapply ConsistentTFSexc;try rewrite eqfr; eauto 1.\n    eapply ConsistentTFSind2;\n      try unfold ConsistentTFR; try rewrite eqgamma;try rewrite eqcdecl;\n        try rewrite eqxi; try rewrite eqmdecl; try rewrite eqacid;\n          try rewrite eqfr; eauto 2.\nQed.\n\n\n(* Lemma isDtfs_isNtfs : forall h e fr tfs, ConsistentTFS h (e::tfs) -> ConsistentTFS h (replace_fr_in_tfr fr e::tfs).\n*)\nLemma isDtfs_isNtfs : forall h e Ctx E tfs,\n    ConsistentTFS h (e::tfs) -> ConsistentTFS h (replace_fr_in_tfr (Ctx [[E]]_None) e::tfs).\nProof.\n  unfold replace_fr_in_tfr.\n  inversion_clear 1.\n  + inversion_clear H0.\n    ++\n      econstructor; simpl; trivial.\n      econstructor.\n      destruct H.\n      now constructor. \n    ++\n      econstructor; simpl; trivial.\n      econstructor; eauto 1.\n  + inversion_clear H0.\n    ++\n      econstructor; simpl; trivial.\n      econstructor.\n      destruct H.\n      now constructor. \n    ++\n      econstructor; simpl; trivial.\n    econstructor; eauto 1.\nQed.\n\nHint Resolve isDtfs_isNtfs.\n  \n\nLemma isDtfs_isNtfs_ex : forall h e Ctx n robj D tfs,\n    ConsistentTFS h (e::tfs) ->\n    Heap.find n h = Some (robj,D) ->\n    ConsistentTFS h (replace_fr_in_tfr (Ctx [[ JFVal1 (JFVLoc (JFLoc n)) ]]_Some D) e::tfs).\nunfold replace_fr_in_tfr.\ninversion_clear 1.\n+ inversion_clear H0.\n  ++\n    econstructor 2; simpl; eauto 1.\n    econstructor.\n    destruct H.\n    now constructor. \n  ++\n    econstructor 2; simpl; eauto 1.\n    econstructor; eauto 1.\n+ inversion_clear H0.\n  ++\n    econstructor 2; simpl; eauto 1.\n    econstructor.\n    destruct H.\n    now constructor. \n  ++\n    econstructor 2; simpl; eauto 1.\n    econstructor; eauto 1.\nQed.\n\nHint Resolve isDtfs_isNtfs_ex.\n\n\n\nLemma ConsistentTFR_update_env : forall h e n o Cn Did mu,\n    Well_formed_program P ->\n    Heap.find (elt:=Obj) n h = Some (o, Cn) ->\n    subtyping P (JFClass Cn) Did ->\n    ConsistentTFR h e ->  ConsistentTFR h (update_env_in_fr e (JFLoc n) (Did,mu)).  \nProof.\n  destruct 4 as (? & ? & Hnpe & ?).\n  repeat split; simpl; eauto 4 using heap_find_HeapAgreesEnv, names_unique_env_oPlus, oPlus_non_null.\n  destruct e; simpl in *.\n  destruct (JFVal_dec NPE_val (JFVLoc (JFLoc n))) as [ Heq | ?].\n  + rewrite Heq in *.\n    decompose_ex Hnpe.\n    destruct Hnpe.\n    edestruct In_in_oPlus as (Cnpe' & mu' & HIn_oPlus & Hleq1 & Hleq2); eauto 2.\n    eexists.\n    split.\n    ++ evar (mrwr : JFAMod).\n       enough (mrwr = mu') as HeqMod.\n       +++ rewrite <- HeqMod in HIn_oPlus.\n           unfold mrwr in *.\n           apply HIn_oPlus.\n       +++\n           destruct Hleq1 as [_ Hrwr].\n           rewrite rwr_eq; eauto 1.\n    ++\n      destruct Hleq1.\n      eapply subtrans; eauto 2.\n  + destruct Hnpe as (Cnpe & HIn & Hsub); eauto 4 using In_oPlus_other.\nQed.\n  \n\nLemma ConsistentTFSind_update_env : forall h e tfs n o Cn Did mu,\n    Well_formed_program P ->\n    Heap.find (elt:=Obj) n h = Some (o, Cn) ->\n    subtyping P (JFClass Cn) Did ->\n    ConsistentTFSind h (e :: tfs) ->  ConsistentTFSind h (update_env_in_fr e (JFLoc n) (Did,mu)::tfs).\nProof.\n  intros until 3.\n  inversion_clear 1.\n  + constructor.\n    eapply ConsistentTFR_update_env; eauto 1.  \n  + econstructor; simpl; eauto 1.\n    eapply ConsistentTFR_update_env; eauto 1.\nQed.\n\nLemma isDtfs_isNtfs_env : forall h e tfs n o Cn Did mu,\n    Well_formed_program P ->\n    Heap.find (elt:=Obj) n h = Some (o, Cn) ->\n    subtyping P (JFClass Cn) Did ->\n      ConsistentTFS h (e::tfs) -> ConsistentTFS h (update_env_in_fr e (JFLoc n) (Did,mu)::tfs).\nProof.\n  unfold update_env_in_fr.\n  intros until 3.\n  inversion_clear 1.\n  + econstructor; simpl; eauto 1.\n    eapply ConsistentTFSind_update_env; eauto 1.\n  + econstructor 2; simpl; eauto 1.\n    eapply ConsistentTFSind_update_env; eauto 1.\nQed.\n\n\nHint Resolve isDtfs_isNtfs_env.\n\n\nLemma DerivableTFS_update_env : forall h e tfs n o Cn Did mu,\n    Well_formed_program P ->\n    Heap.find (elt:=Obj) n h = Some (o, Cn) ->\n    subtyping P (JFClass Cn) Did ->\n    DerivableTFS h (e::tfs) ->\n    names_unique P ->\n    subtype_well_founded P ->\n    DerivableTFS h (update_env_in_fr e (JFLoc n) (Did,mu) :: tfs).                \nProof.\n  destruct 4 as [? Hder].\n  constructor; eauto 3.\n  inversion_clear Hder as [|? ? Hder' ?].\n  econstructor; trivial.\n  destruct e  as [? ? ? ? TFRfr0 ?].\n  red in Hder' |- *.\n  simpl.\n  decompose_and Hder' as (? & ? & Hder).\n  destruct TFRfr0 as [Ctx E A].\n  destruct A.\n  + (* case A=Some *)\n    decompose_ex Hder.\n    intuition.\n    eexists.\n    ssplit; eauto 1.\n    eapply typesCtx_subenv; eauto 2.\n    apply subenv_oPlus; eauto 2.\n  + (* case A=None *)\n    intuition.\n    eapply typesCtx_subenv; eauto 1.\n    apply subenv_oPlus; eauto 1.\nQed.\n\n\nLemma DerivableTFR_replace_fr : forall cdecl mdecl Xi Gamma E1 Ctx1 E2 Ctx2 Acid,\n    typesCtx P cdecl mdecl Xi Gamma E2 Ctx2 Acid ->\n\n    DerivableTFR (TFR cdecl mdecl Xi Gamma (Ctx1[[E1]]_ None) Acid) ->\n    DerivableTFR (replace_fr_in_tfr ( Ctx2[[E2]]_ None) (TFR cdecl mdecl Xi Gamma (Ctx1[[E1]]_ None) Acid)).\nProof.\n  intros until 0.\n  simpl.\n  intuition.\nQed.  \n\nLemma DerivableTFS_replace_fr : forall h cdecl mdecl Xi Gamma E1 Ctx1 E2 Ctx2 Acid tfs,\n    typesCtx P cdecl mdecl Xi Gamma E2 Ctx2 Acid ->\n\n    DerivableTFS h ((TFR cdecl mdecl Xi Gamma (Ctx1[[E1]]_ None) Acid)::tfs) ->\n    DerivableTFS h ((replace_fr_in_tfr ( Ctx2[[E2]]_ None) (TFR cdecl mdecl Xi Gamma (Ctx1[[E1]]_ None) Acid))::tfs).\nProof.\n  intros until 0.\n  intros Htyp.\n  destruct 1 as [Htfs Hder].\n  constructor; eauto 2.\n  inversion_clear Hder.\n  constructor; trivial.\n  apply DerivableTFR_replace_fr; trivial.\nQed.        \n\nLemma DerivableTFR_replace_fr2 : forall e E2 Ctx2,\n    typesCtx P (TFRcdecl e) (TFRmdecl e) (TFRXi e) (TFRGamma e) E2 Ctx2 (TFRAcid e) ->\n    DerivableTFR e ->\n    DerivableTFR (replace_fr_in_tfr ( Ctx2[[E2]]_ None) e).\nProof.\n  intros until 0.\n  destruct e.\n  simpl.\n  intuition.\nQed.\n\n\nEnd RedInvariants.\n\nHint Resolve fields_unique.\nHint Resolve DerivableTFS_wfs.\nHint Resolve DerivableTFS_ConsistentTFR.\nHint Resolve DerivableTFS_further.\nHint Resolve ConsistentTFS_one ConsistentTFS_DTFR_DerivableTFS.\nHint Resolve DerNU_first.\nHint Immediate DerNU_first'.\nHint Immediate DerNU_second'.\nHint Resolve DerNU_second.\nHint Resolve isDtfs_isNtfs.\nHint Resolve isDtfs_isNtfs_ex.\nHint Resolve isDtfs_isNtfs_env.\nHint Resolve isDtfs_isNtfs.\nHint Resolve fields_unique.\nHint Resolve ConsistentTFR_isNonNullLoc.\nHint Resolve ConsistentTFR_names_unique.\nHint Resolve ConsistentTFR_HeapAgreesEnv.\nHint Resolve ConsistentTFR_update_env.\n", "meta": {"author": "jbujak", "repo": "jafun", "sha": "4b9b2d21ba06e6a98c885c8bf2cc202f52595058", "save_path": "github-repos/coq/jbujak-jafun", "path": "github-repos/coq/jbujak-jafun/jafun-4b9b2d21ba06e6a98c885c8bf2cc202f52595058/JaRedInvariants.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947155710234, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2667604911656574}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Export Coq.Program.Basics.\nRequire Import Coq.micromega.Lia.\nRequire Import compcert.lib.Integers.\nRequire Import compcert.common.Values.\nRequire Import VST.veric.base.\nRequire Import VST.veric.Clight_lemmas.\nRequire Import VST.veric.val_lemmas.\nRequire Import VST.veric.shares.\nRequire Import VST.msl.seplog.\nRequire Import VST.msl.shares.\nRequire Import VST.zlist.sublist.\nRequire Import VST.floyd.coqlib3.\nRequire Import VST.floyd.functional_base.\nRequire Import VST.floyd.data_at_rec_lemmas.\nRequire Import VST.zlist.list_solver.\nRequire Import CertiGraph.lib.EquivDec_ext.\nRequire Import CertiGraph.lib.List_ext.\nRequire Import CertiGraph.graph.graph_model.\nRequire Export CertiGraph.graph.graph_gen.\nImport ListNotations.\n\nLocal Open Scope Z_scope.\n\nDefinition MAX_SPACES: Z := 12.\nLemma MAX_SPACES_eq: MAX_SPACES = 12. Proof. reflexivity. Qed.\n#[export] Hint Rewrite MAX_SPACES_eq: rep_lia.\nGlobal Opaque MAX_SPACES.\n\nDefinition NURSERY_SIZE: Z := Z.shiftl 1 16.\nLemma NURSERY_SIZE_eq: NURSERY_SIZE = Z.shiftl 1 16. Proof. reflexivity. Qed.\n#[export] Hint Rewrite NURSERY_SIZE_eq: rep_lia.\nGlobal Opaque NURSERY_SIZE.\n\nDefinition MAX_ARGS: Z := 1024.\nLemma MAX_ARGS_eq: MAX_ARGS = 1024. Proof. reflexivity. Qed.\n#[export] Hint Rewrite MAX_ARGS_eq: rep_lia.\nGlobal Opaque MAX_ARGS.\n\nDefinition WORD_SIZE: Z := Eval cbv [Archi.ptr64] in if Archi.ptr64 then 8 else 4.\n\nDefinition MAX_UINT: Z := Eval cbv [Archi.ptr64] in\n      if Archi.ptr64 then Int64.max_unsigned else Int.max_unsigned.\n\nDefinition MAX_SPACE_SIZE: Z := Eval cbv [Archi.ptr64] in\n      if Archi.ptr64 then Z.shiftl 1 40 else Z.shiftl 1 29.\n\nDefinition NO_SCAN_TAG: Z := 251.\nLemma NO_SCAN_TAG_eq: NO_SCAN_TAG = 251. Proof. reflexivity. Qed.\n#[export] Hint Rewrite NO_SCAN_TAG_eq: rep_lia.\nGlobal Opaque NO_SCAN_TAG.\n\nDefinition SPACE_STRUCT_SIZE: Z :=\n  Eval cbv [Archi.ptr64] in if Archi.ptr64 then 24 else 12.\n\nLemma four_div_WORD_SIZE: (4 | WORD_SIZE).\nProof. first [now exists 1 | now exists 2]. Qed.\n\nLemma MSS_eq_unsigned:\n  Int.unsigned (Int.shl (Int.repr 1) (Int.repr 29)) = Z.shiftl 1 29.\nProof.\n  rewrite Int.shl_mul_two_p.\n  rewrite (Int.unsigned_repr 29) by (compute; split; discriminate).\n  rewrite mul_repr. rewrite Zbits.Zshiftl_mul_two_p by lia.\n  rewrite !Z.mul_1_l, Int.unsigned_repr;\n    [lia | compute; split; intro S; discriminate].\nQed.\n\nLemma MSS_max_unsigned_range: forall n,\n    0 <= n < MAX_SPACE_SIZE ->\n    0 <= n <= if Archi.ptr64 then Int64.max_unsigned else Int.max_unsigned.\nProof.\n  intros. cbv [Archi.ptr64]. destruct H. split. 1: assumption.\n  rewrite Z.lt_eq_cases. left.\n  transitivity MAX_SPACE_SIZE. 1: assumption. unfold MAX_SPACE_SIZE.\n  vm_compute; reflexivity.\nQed.\n\nLemma MSS_max_wordsize_unsigned_range: forall n,\n    0 <= n < MAX_SPACE_SIZE ->\n    0 <= WORD_SIZE * n <= if Archi.ptr64 then Int64.max_unsigned else Int.max_unsigned.\nProof.\n  intros. cbv [Archi.ptr64]. destruct H. split. 1: unfold WORD_SIZE; lia.\n  rewrite Z.lt_eq_cases. left.\n  transitivity (WORD_SIZE * MAX_SPACE_SIZE); unfold WORD_SIZE. 1: lia.\n  unfold MAX_SPACE_SIZE. vm_compute; reflexivity.\nQed.\n\nLemma MSS_max_wordsize_signed_range: forall n,\n    0 <= n < MAX_SPACE_SIZE -> Ptrofs.min_signed <= WORD_SIZE * n <= Ptrofs.max_signed.\nProof.\n  intros. destruct H. split.\n  - unfold WORD_SIZE. transitivity 0. 2: lia. rewrite Z.le_lteq. left.\n    apply Ptrofs.min_signed_neg.\n  - rewrite Z.lt_le_pred in H0. rewrite Z.le_lteq. left.\n    apply Z.le_lt_trans with (WORD_SIZE * Z.pred MAX_SPACE_SIZE).\n    unfold WORD_SIZE. 1: lia.\n    unfold MAX_SPACE_SIZE. rewrite Z.mul_pred_r.\n    unfold Ptrofs.max_signed, Ptrofs.half_modulus, Ptrofs.modulus, Ptrofs.wordsize,\n    Wordsize_Ptrofs.wordsize.\n    destruct Archi.ptr64 eqn:?; first [now inversion Heqb | simpl; lia].\nQed.\n\nDefinition VType: Type := nat * nat.\nDefinition EType: Type := VType * nat.\nDefinition vgeneration: VType -> nat := fst.\nDefinition vindex: VType -> nat := snd.\n\n#[export] Instance V_EqDec: EqDec VType eq.\nProof.\n  hnf. intros [x] [y]. destruct (Nat.eq_dec x y).\n  - destruct (Nat.eq_dec n n0); subst.\n    + left. reflexivity.\n    + right. intro. apply n1. inversion H. reflexivity.\n  - right. intro. apply n1. inversion H. reflexivity.\nDefined.\n\n#[export] Instance E_EqDec: EqDec EType eq.\nProof.\n  hnf. intros [x] [y]. destruct (equiv_dec x y).\n  - hnf in e. destruct (Nat.eq_dec n n0); subst.\n    + left; reflexivity.\n    + right; intro; apply n1; inversion H; reflexivity.\n  - right; intro; apply c; inversion H; reflexivity.\nDefined.\n\nInductive GC_Pointer := | GCPtr: block -> ptrofs -> GC_Pointer.\n\nDefinition raw_field: Type := option (Z + GC_Pointer).\n\n#[export] Instance raw_field_inhabitant: Inhabitant raw_field := None.\n\nDefinition odd_Z2val (x: Z) : val :=\n  Eval cbv delta [Archi.ptr64] match\n         in (if Archi.ptr64 then Vlong (Int64.repr (2 * x + 1)%Z)\n              else Vint (Int.repr (2 * x + 1)%Z)).\n\nDefinition Z2val (x: Z) : val :=\n  Eval cbv delta [Archi.ptr64] match\n         in if Archi.ptr64 then Vlong (Int64.repr x) else Vint (Int.repr x).\n\nDefinition GC_Pointer2val (x: GC_Pointer) : val :=\n  match x with | GCPtr b z => Vptr b z end.\n\nRecord raw_vertex_block : Type :=\n  {\n    raw_mark: bool;\n    copied_vertex: VType;\n    raw_fields: list raw_field;\n    raw_color: Z;\n    raw_tag: Z;\n    raw_tag_range: 0 <= raw_tag < 256;\n    raw_color_range: 0 <= raw_color < 4;\n    raw_fields_range: 0 < Zlength raw_fields < two_p (WORD_SIZE * 8 - 10);\n    tag_no_scan: NO_SCAN_TAG <= raw_tag -> ~ In None raw_fields;\n    (* what's up with this? why can raw_f be None at all? *)\n  }.\n\nLocal Close Scope Z_scope.\n\nLemma raw_fields_not_nil: forall rvb, raw_fields rvb <> nil.\nProof.\n  intros. pose proof (raw_fields_range rvb). destruct (raw_fields rvb).\n  - simpl in H. rewrite Zlength_nil in H. exfalso; lia.\n  - intro. inversion H0.\nQed.\n\nDefinition raw_fields_head (rvb: raw_vertex_block): raw_field :=\n  match rvb.(raw_fields) as l return (raw_fields rvb = l -> raw_field) with\n  | nil => fun m => False_rect _ (raw_fields_not_nil _ m)\n  | r :: _ => fun _ => r\n  end eq_refl.\n\nLemma raw_fields_head_cons:\n  forall rvb, exists r l, raw_fields rvb = r :: l /\\ raw_fields_head rvb = r.\nProof.\n  intros. destruct rvb eqn:? . simpl. unfold raw_fields_head; simpl.\n  destruct raw_fields0.\n  - exfalso. clear Heqr. rewrite Zlength_nil in raw_fields_range0. lia.\n  - exists r, raw_fields0. split; reflexivity.\nQed.\n\nLocal Open Scope Z_scope.\n\nRecord generation_info: Type :=\n  {\n    start_address: val;\n    number_of_vertices: nat;\n    generation_sh: share;\n    start_isptr: isptr start_address;\n    generation_share_writable: writable_share generation_sh;\n  }.\n\nDefinition IMPOSSIBLE_VAL := Vptr xH Ptrofs.zero.\nLemma IMPOSSIBLE_ISPTR: isptr IMPOSSIBLE_VAL. Proof. exact I. Qed.\nGlobal Opaque IMPOSSIBLE_VAL.\n\nDefinition null_info: generation_info :=\n  Build_generation_info IMPOSSIBLE_VAL O Tsh IMPOSSIBLE_ISPTR writable_share_top.\n\n#[export] Instance gen_info_inhabitant: Inhabitant generation_info := null_info.\n\nRecord graph_info : Type :=\n  {\n    g_gen: list generation_info;\n    g_gen_not_nil: g_gen <> nil;\n  }.\n\nDefinition graph_info_head (gi: graph_info): generation_info :=\n  match gi.(g_gen) as l return (g_gen gi = l -> generation_info) with\n  | nil => fun m => False_rect _ (g_gen_not_nil _ m)\n  | s :: _ => fun _ => s\n  end eq_refl.\n\nLemma graph_info_head_cons:\n  forall gi, exists s l, g_gen gi = s :: l /\\ graph_info_head gi = s.\nProof.\n  intros. destruct gi eqn:? . simpl. unfold graph_info_head. simpl. destruct g_gen0.\n  1: contradiction. exists g, g_gen0. split; reflexivity.\nQed.\n\nDefinition LGraph := LabeledGraph VType EType raw_vertex_block unit graph_info.\n\nLocal Coercion pg_lg: LabeledGraph >-> PreGraph.\n\nRecord space: Type :=\n  {\n    space_start: val;\n    used_space: Z;\n    total_space: Z;\n    space_sh: share;\n    space_order: 0 <= used_space <= total_space;\n    space_upper_bound: total_space < MAX_SPACE_SIZE;\n  }.\n\nDefinition null_space: space.\nProof.\n  refine (Build_space nullval 0 0 emptyshare _ _).\n  - split; apply Z.le_refl.\n  - unfold MAX_SPACE_SIZE. vm_compute; reflexivity.\nDefined.\n\n#[export] Instance space_inhabitant: Inhabitant space := null_space.\n\nLemma total_space_tight_range: forall sp, 0 <= total_space sp < MAX_SPACE_SIZE.\nProof.\n  intros. split.\n  - destruct (space_order sp). transitivity (used_space sp); assumption.\n  - apply space_upper_bound.\nQed.\n\nLemma total_space_range: forall sp, 0 <= total_space sp <= (if Archi.ptr64 then Int64.max_unsigned else Int.max_unsigned).\nProof. intros. apply MSS_max_unsigned_range, total_space_tight_range. Qed.\n\nLemma total_space_signed_range: forall sp,\n    Ptrofs.min_signed <= WORD_SIZE * total_space sp <= Ptrofs.max_signed.\nProof. intros. apply MSS_max_wordsize_signed_range, total_space_tight_range. Qed.\n\nLemma used_space_signed_range: forall sp,\n    Ptrofs.min_signed <= WORD_SIZE * used_space sp <= Ptrofs.max_signed.\nProof.\n  intros. apply MSS_max_wordsize_signed_range. destruct (space_order sp). split.\n  1: assumption. apply Z.le_lt_trans with (total_space sp). 1: assumption.\n  apply (proj2 (total_space_tight_range sp)).\nQed.\n\nLemma rest_space_signed_range: forall sp,\n    Ptrofs.min_signed <=\n    WORD_SIZE * total_space sp - WORD_SIZE * used_space sp <=\n    Ptrofs.max_signed.\nProof.\n  intros. rewrite <- Z.mul_sub_distr_l. apply MSS_max_wordsize_signed_range.\n  destruct (space_order sp). pose proof (total_space_tight_range sp). lia.\nQed.\n\nDefinition range_signed (z: Z) :=\n  (if Archi.ptr64 then Int64.min_signed else Int.min_signed) <= z <=\n  (if Archi.ptr64 then Int64.max_signed else Int.max_signed).\n\nLemma signed_range_repable_signed: forall z,\n    Ptrofs.min_signed <= z <= Ptrofs.max_signed <-> range_signed z.\nProof.\n  intros. unfold range_signed.\n  replace Ptrofs.max_signed with\n      (if Archi.ptr64 then Int64.max_signed else Int.max_signed) by\n      (vm_compute; reflexivity).\n  replace Ptrofs.min_signed with\n      (if Archi.ptr64 then Int64.min_signed else Int.min_signed) by\n      (vm_compute; reflexivity).\n  reflexivity.\nQed.\n\nLemma used_space_repable_signed: forall sp, range_signed (used_space sp).\nProof.\n  intros. rewrite <- signed_range_repable_signed.\n  pose proof (used_space_signed_range sp). unfold WORD_SIZE in H. rep_lia.\nQed.\n\nLemma total_space_repable_signed: forall sp, range_signed (total_space sp).\nProof.\n  intros. rewrite <- signed_range_repable_signed.\n  pose proof (total_space_signed_range sp). unfold WORD_SIZE in H. rep_lia.\nQed.\n\nLemma rest_space_repable_signed: forall sp,\n    range_signed (total_space sp - used_space sp).\nProof.\n  intros. rewrite <- signed_range_repable_signed.\n  pose proof (rest_space_signed_range sp). unfold WORD_SIZE in H. rep_lia.\nQed.\n\nDefinition repable64_signed (z: Z) :=\n  Int64.min_signed <= z <= Int64.max_signed.\n\nLemma lt64_repr: forall i j,\n    repable64_signed i -> repable64_signed j ->\n    Int64.lt (Int64.repr i) (Int64.repr j) = true -> i < j.\nProof.\n  intros. unfold Int64.lt in H1. if_tac in H1. 2: inversion H1.\n  rewrite !Int64.signed_repr in H2; auto.\nQed.\n\nLemma lt64_repr_false: forall i j,\n    repable64_signed i -> repable64_signed j ->\n    Int64.lt (Int64.repr i) (Int64.repr j) = false -> i >= j.\nProof.\n  intros. unfold Int64.lt in H1. if_tac in H1. 1: inversion H1.\n  rewrite !Int64.signed_repr in H2; auto.\nQed.\n\nRecord heap: Type :=\n  {\n    spaces: list space;\n    spaces_size: Zlength spaces = MAX_SPACES;\n  }.\n\nLemma heap_spaces_nil: forall h: heap, nil = spaces h -> False.\nProof.\n  intros. pose proof (spaces_size h). rewrite <- H, Zlength_nil in H0. discriminate.\nQed.\n\nDefinition heap_head (h: heap) : space :=\n  match h.(spaces) as l return (l = spaces h -> space) with\n  | nil => fun m => False_rect space (heap_spaces_nil h m)\n  | s :: _ => fun _ => s\n  end eq_refl.\n\nLemma heap_head_cons: forall h, exists s l, spaces h = s :: l /\\ heap_head h = s.\nProof.\n  intros. destruct h eqn:? . simpl. unfold heap_head. simpl. destruct spaces0.\n  1: inversion spaces_size0. exists s, spaces0. split; reflexivity.\nQed.\n\nRecord thread_info: Type :=\n  {\n    ti_heap_p: val;\n    ti_heap: heap;\n    ti_args: list val;\n    arg_size: Zlength ti_args = MAX_ARGS;\n  }.\n\nDefinition vertex_size (g: LGraph) (v: VType): Z :=\n  Zlength (vlabel g v).(raw_fields) + 1.\n\nLemma svs_gt_one: forall g v, 1 < vertex_size g v.\nProof.\n  intros. unfold vertex_size. pose proof (raw_fields_range (vlabel g v)). lia.\nQed.\n\nFixpoint nat_seq (s: nat) (total: nat): list nat :=\n  match total with\n  | O => nil\n  | S n => s :: nat_seq (S s) n\n  end.\n\nLemma nat_seq_length: forall s n, length (nat_seq s n) = n.\nProof. intros. revert s. induction n; intros; simpl; [|rewrite IHn]; reflexivity. Qed.\n\nLemma nat_seq_S: forall i num, nat_seq i (S num) = nat_seq i num ++ [(num + i)%nat].\nProof.\n  intros. revert i. induction num; intros. 1: simpl; reflexivity.\n  remember (S num). simpl. rewrite (IHnum (S i)). subst. simpl. repeat f_equal. lia.\nQed.\n\nLemma nat_seq_In_iff: forall s n i, In i (nat_seq s n) <-> (s <= i < s + n)%nat.\nProof. intros. revert s. induction n; intros; simpl; [|rewrite IHn]; lia. Qed.\n\nLemma nat_seq_NoDup: forall s n, NoDup (nat_seq s n).\nProof.\n  intros. revert s. induction n; intros; simpl; constructor. 2: apply IHn.\n  intro. rewrite nat_seq_In_iff in H. lia.\nQed.\n\nLocal Close Scope Z_scope.\n\nLemma nat_seq_nth: forall s num n a, n < num -> nth n (nat_seq s num) a = s + n.\nProof.\n  intros. revert s n H. induction num; intros. 1: exfalso; lia. simpl. destruct n.\n  1: lia. specialize (IHnum (S s) n). replace (s + S n) with (S s + n) by lia.\n  rewrite IHnum; [reflexivity | lia].\nQed.\n\nLemma nat_seq_app: forall s n m, nat_seq s (n + m) = nat_seq s n ++ nat_seq (s + n) m.\nProof.\n  intros. revert s; induction n; simpl; intros.\n  - rewrite Nat.add_0_r. reflexivity.\n  - f_equal. rewrite IHn. replace (S s + n) with (s + S n) by lia. reflexivity.\nQed.\n\nLemma nat_seq_Permutation_cons: forall s i n,\n    i < n -> exists l, Permutation (nat_seq s n) (s + i :: l).\nProof.\n  intros. induction n. 1: lia. replace (S n) with (n + 1) by lia.\n  rewrite nat_seq_app. simpl. destruct (Nat.eq_dec i n).\n  - subst i. exists (nat_seq s n). symmetry. apply Permutation_cons_append.\n  - assert (i < n) by lia. apply IHn in H0. destruct H0 as [l ?].\n    exists (l +:: (s + n)). rewrite app_comm_cons. apply Permutation_app_tail.\n    assumption.\nQed.\n\nDefinition nat_inc_list (n: nat) : list nat := nat_seq O n.\n\nLemma nat_inc_list_length: forall num, length (nat_inc_list num) = num.\nProof. intros. unfold nat_inc_list. rewrite nat_seq_length. reflexivity. Qed.\n\nLemma nat_inc_list_S: forall num, nat_inc_list (S num) = nat_inc_list num ++ [num].\nProof. intros. unfold nat_inc_list. rewrite nat_seq_S. repeat f_equal. lia. Qed.\n\nLemma nat_inc_list_In_iff: forall i n, In i (nat_inc_list n) <-> i < n.\nProof. intros. unfold nat_inc_list. rewrite nat_seq_In_iff. intuition. Qed.\n\nLemma nat_inc_list_nth: forall i n a, i < n -> nth i (nat_inc_list n) a = i.\nProof. intros. unfold nat_inc_list. rewrite nat_seq_nth; [lia | assumption]. Qed.\n\nLemma nat_inc_list_app: forall n m,\n    nat_inc_list (n + m) = nat_inc_list n ++ nat_seq n m.\nProof. intros. unfold nat_inc_list. rewrite nat_seq_app. reflexivity. Qed.\n\nLemma nat_inc_list_NoDup: forall n, NoDup (nat_inc_list n).\nProof. intros. unfold nat_inc_list. apply nat_seq_NoDup. Qed.\n\nLemma nat_inc_list_Permutation_cons: forall i n,\n    i < n -> exists l, Permutation (nat_inc_list n) (i :: l).\nProof.\n  intros. unfold nat_inc_list. replace i with (O + i) by lia.\n  apply nat_seq_Permutation_cons. assumption.\nQed.\n\nLocal Open Scope Z_scope.\n\nDefinition vertex_size_accum g gen (s: Z) (n: nat) := s + vertex_size g (gen, n).\n\nDefinition previous_vertices_size (g: LGraph) (gen i: nat): Z :=\n  fold_left (vertex_size_accum g gen) (nat_inc_list i) 0.\n\nLemma vsa_mono: forall g gen s n, s < vertex_size_accum g gen s n.\nProof.\n  intros. unfold vertex_size_accum. pose proof (svs_gt_one g (gen, n)). lia.\nQed.\n\nLemma vsa_comm: forall g gen s n1 n2,\n    vertex_size_accum g gen (vertex_size_accum g gen s n1) n2 =\n    vertex_size_accum g gen (vertex_size_accum g gen s n2) n1.\nProof. intros. unfold vertex_size_accum. lia. Qed.\n\nLemma vs_accum_list_lt: forall g gen s l,\n    l <> nil -> s < fold_left (vertex_size_accum g gen) l s.\nProof.\n  intros; apply (fold_left_Z_mono_strict (vertex_size_accum g gen) nil l l);\n    [apply vsa_mono | apply vsa_comm | assumption | apply Permutation_refl].\nQed.\n\nLemma vs_accum_list_le: forall g gen s l, s <= fold_left (vertex_size_accum g gen) l s.\nProof.\n  intros. destruct l. 1: simpl; lia. rename l into l1. remember (n :: l1).\n  assert (l <> nil) by (subst; intro S; inversion S). rewrite Z.le_lteq. left.\n  apply vs_accum_list_lt. assumption.\nQed.\n\nLemma pvs_S: forall g gen i,\n    previous_vertices_size g gen (S i) =\n    previous_vertices_size g gen i + vertex_size g (gen, i).\nProof.\n  intros. unfold previous_vertices_size at 1. rewrite nat_inc_list_S, fold_left_app.\n  fold (previous_vertices_size g gen i). simpl. reflexivity.\nQed.\n\nLemma pvs_ge_zero: forall g gen i, 0 <= previous_vertices_size g gen i.\nProof. intros. unfold previous_vertices_size. apply vs_accum_list_le. Qed.\n\nDefinition generation_space_compatible (g: LGraph)\n           (tri: nat * generation_info * space) : Prop :=\n  match tri with\n  | (gen, gi, sp) =>\n    gi.(start_address) = sp.(space_start) /\\\n    gi.(generation_sh) = sp.(space_sh) /\\\n    previous_vertices_size g gen gi.(number_of_vertices) = sp.(used_space)\n  end.\n\nLocal Close Scope Z_scope.\n\nDefinition graph_thread_info_compatible (g: LGraph) (ti: thread_info): Prop :=\n  Forall (generation_space_compatible g)\n         (combine (combine (nat_inc_list (length g.(glabel).(g_gen)))\n                           g.(glabel).(g_gen)) ti.(ti_heap).(spaces)) /\\\n  Forall (eq nullval)\n         (skipn (length g.(glabel).(g_gen)) (map space_start ti.(ti_heap).(spaces))) /\\\n  length g.(glabel).(g_gen) <= length ti.(ti_heap).(spaces).\n\nRecord fun_info : Type :=\n  {\n    fun_word_size: Z;\n    live_roots_indices: list Z;\n    fi_index_range: forall i, In i live_roots_indices -> (0 <= i < MAX_ARGS)%Z;\n    lri_range: (Zlength (live_roots_indices) <= MAX_UINT - 2)%Z;\n    word_size_range: (0 <= fun_word_size <= MAX_UINT)%Z;\n  }.\n\nDefinition vertex_offset (g: LGraph) (v: VType): Z :=\n  previous_vertices_size g (vgeneration v) (vindex v) + 1.\n\nDefinition nth_gen (g: LGraph) (gen: nat): generation_info :=\n  nth gen g.(glabel).(g_gen) null_info.\n\nDefinition graph_gen_size g gen :=\n  previous_vertices_size g gen (number_of_vertices (nth_gen g gen)).\n\nDefinition graph_has_gen (g: LGraph) (n: nat): Prop := n < length g.(glabel).(g_gen).\n\nDefinition gen_has_index (g: LGraph) (gen index: nat): Prop :=\n  index < number_of_vertices (nth_gen g gen).\n\nDefinition graph_has_v (g: LGraph) (v: VType): Prop :=\n  graph_has_gen g (vgeneration v) /\\ gen_has_index g (vgeneration v) (vindex v).\n\nLemma graph_has_gen_O: forall g, graph_has_gen g O.\nProof.\n  intros. hnf. destruct (g_gen (glabel g)) eqn:? ; simpl; try lia.\n  pose proof (g_gen_not_nil (glabel g)). contradiction.\nQed.\n\nDefinition graph_has_gen_dec g n: {graph_has_gen g n} + {~ graph_has_gen g n} :=\n  lt_dec n (length (g_gen (glabel g))).\n\nDefinition gen_start (g: LGraph) (gen: nat): val :=\n  if graph_has_gen_dec g gen then start_address (nth_gen g gen) else Vundef.\n\nLemma graph_has_gen_start_isptr: forall g n,\n    graph_has_gen g n -> isptr (gen_start g n).\nProof. intros. unfold gen_start. if_tac; [apply start_isptr | contradiction]. Qed.\n\nDefinition vertex_address (g: LGraph) (v: VType): val :=\n  offset_val (WORD_SIZE * vertex_offset g v) (gen_start g (vgeneration v)).\n\nDefinition root_t: Type := Z + GC_Pointer + VType.\n\n#[export] Instance root_t_inhabitant: Inhabitant root_t := inl (inl Z.zero).\n\nDefinition root2val (g: LGraph) (fd: root_t) : val :=\n  match fd with\n  | inl (inl z) => odd_Z2val z\n  | inl (inr p) => GC_Pointer2val p\n  | inr v => vertex_address g v\n  end.\n\nDefinition roots_t: Type := list root_t.\n\nDefinition outlier_t: Type := list GC_Pointer.\n\nDefinition fun_thread_arg_compatible\n           (g: LGraph) (ti: thread_info) (fi: fun_info) (roots: roots_t) : Prop :=\n  map (root2val g) roots = map ((flip Znth) ti.(ti_args)) fi.(live_roots_indices).\n\nDefinition roots_outlier_compatible (roots: roots_t) (outlier: outlier_t): Prop :=\n  incl (filter_sum_right (filter_sum_left roots)) outlier.\n\nDefinition roots_graph_compatible (roots: roots_t) (g: LGraph): Prop :=\n  Forall (graph_has_v g) (filter_sum_right roots).\n\nDefinition roots_compatible (g: LGraph) (outlier: outlier_t) (roots: roots_t): Prop :=\n  roots_outlier_compatible roots outlier /\\ roots_graph_compatible roots g.\n\nDefinition outlier_compatible (g: LGraph) (outlier: outlier_t): Prop :=\n  forall v,\n    graph_has_v g v ->\n    incl (filter_sum_right (filter_option (vlabel g v).(raw_fields))) outlier.\n\nDefinition copy_compatible (g: LGraph): Prop :=\n  forall v, graph_has_v g v -> (vlabel g v).(raw_mark) = true ->\n            graph_has_v g (vlabel g v).(copied_vertex) /\\\n            vgeneration v <> vgeneration (vlabel g v).(copied_vertex).\nDefinition\n  super_compatible\n  (g_ti_r: LGraph * thread_info * roots_t) (fi: fun_info) (out: outlier_t) : Prop :=\n  let (g_ti, r) := g_ti_r in\n  let (g, ti) := g_ti in\n  graph_thread_info_compatible g ti /\\\n  fun_thread_arg_compatible g ti fi r /\\\n  roots_compatible g out r /\\\n  outlier_compatible g out.\n\nDefinition reset_gen_info (gi: generation_info) : generation_info :=\n  Build_generation_info (start_address gi) O (generation_sh gi) (start_isptr gi)\n                        (generation_share_writable gi).\n\nFixpoint reset_nth_gen_info\n         (n: nat) (gi: list generation_info) : list generation_info :=\n  match n with\n  | O => match gi with\n         | nil => nil\n         | g :: l => reset_gen_info g :: l\n         end\n  | S m => match gi with\n           | nil => nil\n           | g :: l => g :: reset_nth_gen_info m l\n           end\n  end.\n\nLemma reset_nth_gen_info_length: forall n gl,\n    length (reset_nth_gen_info n gl) = length gl.\nProof.\n  intros. revert n. induction gl; simpl; intros; destruct n; simpl;\n                      [| | | rewrite IHgl]; reflexivity.\nQed.\n\nLemma reset_nth_gen_info_not_nil: forall n g, reset_nth_gen_info n (g_gen g) <> nil.\nProof.\n  intros. pose proof (g_gen_not_nil g). destruct (g_gen g).\n  - contradiction.\n  - destruct n; simpl; discriminate.\nQed.\n\nLemma reset_nth_gen_info_diff: forall gl i j a,\n    i <> j -> nth i (reset_nth_gen_info j gl) a = nth i gl a.\nProof.\n  intros ? ? ?. revert gl i. induction j; intros; simpl; destruct gl; try reflexivity.\n  - destruct i. 1: contradiction. simpl. reflexivity.\n  - destruct i. 1: reflexivity. simpl. apply IHj. lia.\nQed.\n\nLemma reset_nth_gen_info_same: forall gl i,\n    nth i (reset_nth_gen_info i gl) null_info = reset_gen_info (nth i gl null_info).\nProof.\n  intros. revert gl. induction i; intros; destruct gl; simpl in *; try reflexivity.\n  apply IHi.\nQed.\n\nLemma reset_nth_gen_info_overflow: forall gl i,\n    length gl <= i -> reset_nth_gen_info i gl = gl.\nProof.\n  intros ? ?. revert gl. induction i; intros; destruct gl; simpl in *; try reflexivity.\n  1: lia. rewrite IHi; [reflexivity | lia].\nQed.\n\nLemma sublist_pos_cons: forall {A: Type} (lo hi: Z) (al: list A) v,\n    (0 < lo)%Z -> sublist lo hi (v :: al) = sublist (lo - 1) (hi - 1) al.\nProof.\n  intros. unfold_sublist_old. f_equal. 1: f_equal; lia.\n  replace (Z.to_nat lo) with (S (Z.to_nat (lo - 1))) by lia.\n  simpl. reflexivity.\nQed.\n\nLemma upd_Znth_pos_cons: forall {A: Type} (i: Z) (l: list A) v x,\n    (0 < i <= Zlength l)%Z -> upd_Znth i (v :: l) x = v :: upd_Znth (i - 1) l x.\nProof.\n  intros. unfold_upd_Znth_old.\n  rewrite (sublist_split 0 1 i); [| |rewrite Zlength_cons]; [| lia..].\n  unfold sublist at 1. simpl. rewrite !sublist_pos_cons by lia. do 4 f_equal.\n  1: lia. rewrite Zlength_cons; lia.\nQed.\n\nDefinition reset_nth_graph_info (n: nat) (g: graph_info) : graph_info :=\n  Build_graph_info (reset_nth_gen_info n g.(g_gen)) (reset_nth_gen_info_not_nil n g).\n\nLemma reset_space_order: forall sp, (0 <= 0 <= total_space sp)%Z.\nProof. intros. pose proof (space_order sp). lia. Qed.\n\nDefinition reset_space (sp: space) : space :=\n  Build_space (space_start sp) 0 (total_space sp) (space_sh sp) (reset_space_order sp)\n              (space_upper_bound sp).\n\nFixpoint reset_nth_space (n: nat) (s: list space): list space :=\n  match n with\n  | O => match s with\n         | nil => nil\n         | sp :: l => reset_space sp :: l\n         end\n  | S m => match s with\n           | nil => nil\n           | sp :: l => sp :: reset_nth_space m l\n           end\n  end.\n\nLemma reset_nth_space_length: forall n s, length (reset_nth_space n s) = length s.\nProof.\n  induction n; intros; simpl.\n  - destruct s; simpl; reflexivity.\n  - destruct s; [|simpl; rewrite (IHn s0)]; reflexivity.\nQed.\n\nLemma reset_nth_space_Zlength: forall n s, Zlength s = Zlength (reset_nth_space n s).\nProof. intros. rewrite !Zlength_correct, reset_nth_space_length. reflexivity. Qed.\n\nLemma reset_nth_heap_Zlength: forall n h,\n    Zlength (reset_nth_space n (spaces h)) = MAX_SPACES.\nProof. intros. rewrite <- reset_nth_space_Zlength. apply spaces_size. Qed.\n\nLemma reset_nth_space_Permutation: forall n s,\n    n < length s -> exists l, Permutation (reset_nth_space n s)\n                                          (reset_space (nth n s null_space) :: l) /\\\n                              Permutation s (nth n s null_space :: l).\nProof.\n  induction n; intros; destruct s; simpl in *; try lia.\n  - exists s0. split; constructor; reflexivity.\n  - assert (n < length s0) by lia. destruct (IHn _ H0) as [ll [? ?]].\n    exists (s :: ll). split.\n    + transitivity (s :: reset_space (nth n s0 null_space) :: ll).\n      1: constructor; assumption. apply perm_swap.\n    + transitivity (s :: nth n s0 null_space :: ll).\n      1: constructor; assumption. apply perm_swap.\nQed.\n\nLemma reset_nth_space_Znth: forall s i,\n    i < length s ->\n    reset_nth_space i s = upd_Znth (Z.of_nat i) s (reset_space (Znth (Z.of_nat i) s)).\nProof.\n  intros ? ?. revert s. induction i; intros; destruct s; simpl in H; try lia.\n  - simpl.\n    rewrite upd_Znth0_old, Znth_0_cons, sublist_1_cons, sublist_same;\n      try reflexivity; rewrite Zlength_cons. lia.\n    pose proof (Zlength_nonneg s0). lia.\n  - replace (Z.of_nat (S i)) with (Z.of_nat i + 1)%Z by (zify; lia).\n    rewrite Znth_pos_cons by lia.\n    replace (Z.of_nat i + 1 - 1)%Z with (Z.of_nat i) by lia. simpl.\n    rewrite upd_Znth_pos_cons.\n    + replace (Z.of_nat i + 1 - 1)%Z with (Z.of_nat i) by lia.\n      rewrite <- IHi; [reflexivity | lia].\n    + rewrite Zlength_correct. lia.\nQed.\n\nLemma reset_nth_space_overflow: forall s i, length s <= i -> reset_nth_space i s = s.\nProof.\n  intros ? ?. revert s.\n  induction i; intros; destruct s; simpl in *; try lia; try reflexivity.\n  rewrite IHi; [reflexivity | lia].\nQed.\n\nLemma reset_nth_space_diff: forall gl i j a,\n    i <> j -> nth i (reset_nth_space j gl) a = nth i gl a.\nProof.\n  intros ? ? ?. revert gl i. induction j; intros; simpl; destruct gl; try reflexivity.\n  - destruct i. 1: contradiction. simpl. reflexivity.\n  - destruct i. 1: reflexivity. simpl. apply IHj. lia.\nQed.\n\nLemma reset_nth_space_same: forall gl i a,\n    i < length gl -> nth i (reset_nth_space i gl) a = reset_space (nth i gl a).\nProof.\n  intros. revert gl H. induction i; intros; destruct gl; simpl in *; try lia.\n  - reflexivity.\n  - apply IHi. lia.\nQed.\n\nDefinition reset_nth_heap (n: nat) (h: heap) : heap :=\n  Build_heap (reset_nth_space n (spaces h)) (reset_nth_heap_Zlength n h).\n\nDefinition reset_nth_heap_thread_info (n: nat) (ti: thread_info) :=\n  Build_thread_info (ti_heap_p ti) (reset_nth_heap n (ti_heap ti))\n                    (ti_args ti) (arg_size ti).\n\nLemma reset_thread_info_overflow: forall n ti,\n    length (spaces (ti_heap ti)) <= n -> reset_nth_heap_thread_info n ti = ti.\nProof.\n  intros. unfold reset_nth_heap_thread_info. destruct ti. f_equal.\n  simpl. unfold reset_nth_heap. destruct ti_heap0. simpl in *.\n  assert (spaces0 = reset_nth_space n spaces0) by\n      (rewrite reset_nth_space_overflow; [reflexivity | assumption]).\n  apply EqdepFacts.f_eq_dep_non_dep, EqdepFacts.eq_dep1_dep.\n  apply (EqdepFacts.eq_dep1_intro _ _ _ _ _ _ H0). apply proof_irr.\nQed.\n\nDefinition make_header (g: LGraph) (v: VType): Z:=\n  let vb := vlabel g v in if vb.(raw_mark)\n                          then 0 else\n                            vb.(raw_tag) + (Z.shiftl vb.(raw_color) 8) +\n                            (Z.shiftl (Zlength vb.(raw_fields)) 10).\n\nLocal Open Scope Z_scope.\n\nLemma make_header_mark_iff: forall g v,\n    make_header g v = 0 <-> raw_mark (vlabel g v) = true.\nProof.\n  intros. unfold make_header. destruct (raw_mark (vlabel g v)). 1: intuition.\n  split; intros. 2: inversion H. exfalso.\n  destruct (raw_tag_range (vlabel g v)) as [? _].\n  assert (0 <= Z.shiftl (raw_color (vlabel g v)) 8). {\n    rewrite Z.shiftl_nonneg. apply (proj1 (raw_color_range (vlabel g v))).\n  } assert (Z.shiftl (Zlength (raw_fields (vlabel g v))) 10 <= 0) by lia.\n  clear -H2. assert (0 <= Z.shiftl (Zlength (raw_fields (vlabel g v))) 10) by\n      (rewrite Z.shiftl_nonneg; apply Zlength_nonneg).\n  assert (Z.shiftl (Zlength (raw_fields (vlabel g v))) 10 = 0) by lia. clear -H0.\n  rewrite Z.shiftl_eq_0_iff in H0 by lia.\n  pose proof (proj1 (raw_fields_range (vlabel g v))). lia.\nQed.\n\nLemma make_header_range: forall g v, 0 <= make_header g v < two_p (WORD_SIZE * 8).\nProof.\n  intros. unfold make_header. destruct (raw_mark (vlabel g v)).\n  - pose proof (two_p_gt_ZERO (WORD_SIZE * 8)). unfold WORD_SIZE in *; lia.\n  - pose proof (raw_tag_range (vlabel g v)). pose proof (raw_color_range (vlabel g v)).\n    pose proof (raw_fields_range (vlabel g v)). remember (raw_tag (vlabel g v)) as z1.\n    clear Heqz1. remember (raw_color (vlabel g v)) as z2. clear Heqz2.\n    remember (Zlength (raw_fields (vlabel g v))) as z3. clear Heqz3.\n    assert (0 <= 8) by lia. apply (Zbits.Zshiftl_mul_two_p z2) in H2. rewrite H2.\n    clear H2. assert (0 <= 10) by lia. apply (Zbits.Zshiftl_mul_two_p z3) in H2.\n    rewrite H2. clear H2. assert (two_p 10 > 0) by (apply two_p_gt_ZERO; lia).\n    assert (two_p 8 > 0) by (apply two_p_gt_ZERO; lia). split.\n    + assert (0 <= z2 * two_p 8) by (apply Z.mul_nonneg_nonneg; lia).\n      assert (0 <= z3 * two_p 10) by (apply Z.mul_nonneg_nonneg; lia). lia.\n    + destruct H as [_ ?]. destruct H0 as [_ ?]. destruct H1 as [_ ?].\n      change 256 with (two_p 8) in H. change 4 with (two_p 2) in H0.\n      assert (z1 <= two_p 8 - 1) by lia. clear H.\n      assert (z2 <= two_p 2 - 1) by lia. clear H0.\n      assert (z3 <= two_p (WORD_SIZE * 8 - 10) - 1) by lia. clear H1.\n      apply Z.mul_le_mono_nonneg_r with (p := two_p 8) in H. 2: lia.\n      apply Z.mul_le_mono_nonneg_r with (p := two_p 10) in H0. 2: lia.\n      rewrite Z.mul_sub_distr_r in H, H0. rewrite Z.mul_1_l in H, H0.\n      assert (0 <= WORD_SIZE * 8 - 10) by (unfold WORD_SIZE; lia).\n      rewrite <- two_p_is_exp in H, H0 by lia. simpl Z.add in H, H0. clear H1.\n      Opaque two_p. simpl. Transparent two_p. lia.\nQed.\n\nLemma make_header_int_rep_mark_iff: forall g v,\n    (if Archi.ptr64 then Int64.repr (make_header g v) = Int64.repr 0\n     else Int.repr (make_header g v) = Int.repr 0) <->\n    raw_mark (vlabel g v) = true.\nProof.\n  intros. rewrite <- make_header_mark_iff. split; intros; [|rewrite H; reflexivity].\n  cbv delta [Archi.ptr64] in H. simpl in H. Transparent Int.repr Int64.repr.\n  inversion H. Opaque Int64.repr Int.repr. clear H. rewrite H1.\n  match goal with\n  | H : Int64.Z_mod_modulus _ = _ |- _ => rewrite Int64.Z_mod_modulus_eq in H\n  | H : Int.Z_mod_modulus _ = _ |- _ => rewrite Int.Z_mod_modulus_eq in H\n  end.\n  rewrite Z.mod_small in H1; auto. apply make_header_range.\nQed.\n\nLemma make_header_Wosize: forall g v,\n    raw_mark (vlabel g v) = false ->\n    if Archi.ptr64 then\n      Int64.shru (Int64.repr (make_header g v)) (Int64.repr 10) =\n      Int64.repr (Zlength (raw_fields (vlabel g v)))\n    else\n      Int.shru (Int.repr (make_header g v)) (Int.repr 10) =\n      Int.repr (Zlength (raw_fields (vlabel g v))).\nProof.\n  intros. cbv delta [Archi.ptr64]. simpl.\n  match goal with\n  | |- Int64.shru _ _ = Int64.repr _ =>\n    rewrite Int64.shru_div_two_p, !Int64.unsigned_repr\n  | |- Int.shru _ _ = Int.repr _ => rewrite Int.shru_div_two_p, !Int.unsigned_repr\n  end.\n  - f_equal. unfold make_header.\n    remember (vlabel g v). clear Heqr.\n    rewrite H, !Zbits.Zshiftl_mul_two_p by lia. rewrite Z.div_add. 2: compute; lia.\n    pose proof (raw_tag_range r). pose proof (raw_color_range r).\n    cut ((raw_tag r + raw_color r * two_p 8) / two_p 10 = 0). 1: intros; lia.\n    apply Z.div_small. change 256 with (two_p 8) in H0. change 4 with (two_p 2) in H1.\n    assert (0 <= raw_tag r <= two_p 8 - 1) by lia. clear H0. destruct H2.\n    assert (0 <= raw_color r <= two_p 2 - 1) by lia. clear H1. destruct H3.\n    assert (two_p 8 > 0) by (apply two_p_gt_ZERO; lia). split.\n    + assert (0 <= raw_color r * two_p 8) by (apply Z.mul_nonneg_nonneg; lia). lia.\n    + apply Z.mul_le_mono_nonneg_r with (p := two_p 8) in H3. 2: lia.\n      rewrite Z.mul_sub_distr_r, <- two_p_is_exp in H3 by lia. simpl Z.add in H3. lia.\n  - rep_lia.\n  - pose proof (make_header_range g v). unfold WORD_SIZE in *.\n    match goal with\n    | |- context [Int64.max_unsigned] =>\n      unfold Int64.max_unsigned, Int64.modulus, Int64.wordsize, Wordsize_64.wordsize\n    | |- context [Int.max_unsigned] =>\n      unfold Int.max_unsigned, Int.modulus, Int.wordsize, Wordsize_32.wordsize\n    end. simpl Z.mul in H0. rewrite two_power_nat_two_p. simpl Z.of_nat. lia.\nQed.\n\nDefinition field_t: Type := Z + GC_Pointer + EType.\n\n#[export] Instance field_t_inhabitant: Inhabitant field_t := inl (inl Z.zero).\n\nDefinition field2val (g: LGraph) (fd: field_t) : val :=\n  match fd with\n  | inl (inl z) => odd_Z2val z\n  | inl (inr p) => GC_Pointer2val p\n  | inr e => vertex_address g (dst g e)\n  end.\n\nFixpoint make_fields' (l_raw: list raw_field) (v: VType) (n: nat): list field_t :=\n  match l_raw with\n  | nil => nil\n  | Some (inl z) :: l => inl (inl z) :: make_fields' l v (n + 1)\n  | Some (inr ptr) :: l => inl (inr ptr) :: make_fields' l v (n + 1)\n  | None :: l => inr (v, n) :: make_fields' l v (n + 1)\n  end.\n\nLemma make_fields'_eq_length: forall l v n, length (make_fields' l v n) = length l.\nProof.\n  intros. revert n. induction l; intros; simpl. 1: reflexivity.\n  destruct a; [destruct s|]; simpl; rewrite IHl; reflexivity.\nQed.\n\nLemma make_fields'_eq_Zlength: forall l v n, Zlength (make_fields' l v n) = Zlength l.\nProof.\n  intros. rewrite !Zlength_correct. rewrite make_fields'_eq_length. reflexivity.\nQed.\n\nLemma make_fields'_edge_depends_on_index:\n  forall n l_raw i v e,\n    0 <= Z.of_nat n < Zlength l_raw ->\n    nth n (make_fields' l_raw v i) field_t_inhabitant = inr e ->\n    e = (v, n+i)%nat.\nProof.\n  induction n as [|n' IHn'].\n  - intros. destruct l_raw; try inversion H0.\n    destruct r; [destruct s|]; simpl in H0; inversion H0;\n      reflexivity.\n  - intro. destruct l_raw; try inversion 2.\n    replace (S n' + i)%nat with (n' + S i)%nat by lia.\n    specialize (IHn' l_raw (S i) v e).\n    assert (0 <= Z.of_nat n' < Zlength l_raw) by\n          (rewrite Zlength_cons, Nat2Z.inj_succ in H; lia).\n      assert (nth n' (make_fields' l_raw v (S i)) field_t_inhabitant = inr e) by\n        (destruct r; [destruct s|]; simpl in H2;\n        replace (i + 1)%nat with (S i) in H2 by lia; assumption).\n      destruct r; [destruct s|]; simpl; apply IHn'; assumption.\nQed.\n\nDefinition make_fields (g: LGraph) (v: VType): list field_t :=\n  make_fields' (vlabel g v).(raw_fields) v O.\n\nDefinition get_edges (g: LGraph) (v: VType): list EType :=\n  filter_sum_right (make_fields g v).\n\nDefinition pregraph_remove_vertex_and_edges\n           (g: LGraph) (v: VType): PreGraph VType EType :=\n  fold_left pregraph_remove_edge (get_edges g v) (pregraph_remove_vertex g v).\n\nDefinition lgraph_remove_vertex_and_edges (g: LGraph) (v: VType): LGraph :=\n  Build_LabeledGraph _ _ _ (pregraph_remove_vertex_and_edges g v)\n                     (vlabel g) (elabel g) (glabel g).\n\nDefinition remove_nth_gen_ve (g: LGraph) (gen: nat): LGraph :=\n  let all_nv := map (fun idx => (gen, idx))\n                    (nat_inc_list (number_of_vertices (nth_gen g gen))) in\n  fold_left lgraph_remove_vertex_and_edges all_nv g.\n\nLemma remove_ve_glabel_unchanged: forall g gen,\n    glabel (remove_nth_gen_ve g gen) = glabel g.\nProof.\n  intros. unfold remove_nth_gen_ve.\n  remember (map (fun idx : nat => (gen, idx))\n                (nat_inc_list (number_of_vertices (nth_gen g gen)))). clear Heql.\n  revert g. induction l; intros; simpl. 1: reflexivity. rewrite IHl. reflexivity.\nQed.\n\nLemma remove_ve_vlabel_unchanged: forall g gen v,\n    vlabel (remove_nth_gen_ve g gen) v = vlabel g v.\nProof.\n  intros. unfold remove_nth_gen_ve.\n  remember (map (fun idx : nat => (gen, idx))\n                (nat_inc_list (number_of_vertices (nth_gen g gen)))). clear Heql.\n  revert g v. induction l; intros; simpl. 1: reflexivity. rewrite IHl. reflexivity.\nQed.\n\nLemma remove_ve_dst_unchanged: forall g gen e,\n    dst (remove_nth_gen_ve g gen) e = dst g e.\nProof.\n  intros. unfold remove_nth_gen_ve.\n  remember (map (fun idx : nat => (gen, idx))\n                (nat_inc_list (number_of_vertices (nth_gen g gen)))). clear Heql.\n  revert g e. induction l; intros; simpl. 1: reflexivity. rewrite IHl.\n  clear. simpl. unfold pregraph_remove_vertex_and_edges.\n  transitivity (dst (pregraph_remove_vertex g a) e). 2: reflexivity.\n  remember (pregraph_remove_vertex g a) as g'. remember (get_edges g a) as l.\n  clear a g Heqg' Heql. rename g' into g. revert g e. induction l; intros; simpl.\n  1: reflexivity. rewrite IHl. reflexivity.\nQed.\n\nDefinition reset_nth_glabel (n: nat) (g: LGraph) : LGraph :=\n  Build_LabeledGraph _ _ _ (pg_lg g) (vlabel g) (elabel g)\n                     (reset_nth_graph_info n (glabel g)).\n\nDefinition reset_graph (n: nat) (g: LGraph) : LGraph :=\n  reset_nth_glabel n (remove_nth_gen_ve g n).\n\nLemma graph_has_gen_reset: forall (g: LGraph) gen1 gen2,\n    graph_has_gen (reset_graph gen1 g) gen2 <-> graph_has_gen g gen2.\nProof.\n  intros. unfold graph_has_gen. simpl. rewrite reset_nth_gen_info_length.\n  rewrite remove_ve_glabel_unchanged. reflexivity.\nQed.\n\nLemma reset_nth_gen_diff: forall g i j,\n    i <> j -> nth_gen (reset_graph j g) i = nth_gen g i.\nProof.\n  intros. unfold nth_gen, reset_graph. simpl.\n  rewrite remove_ve_glabel_unchanged.\n  apply reset_nth_gen_info_diff. assumption.\nQed.\n\nDefinition make_fields_vals (g: LGraph) (v: VType): list val :=\n  let vb := vlabel g v in\n  let original_fields_val := map (field2val g) (make_fields g v) in\n  if vb.(raw_mark)\n  then vertex_address g vb.(copied_vertex) :: tl original_fields_val\n  else original_fields_val.\n\nLemma fields_eq_length: forall g v,\n    Zlength (make_fields_vals g v) = Zlength (raw_fields (vlabel g v)).\nProof.\n  intros. rewrite !Zlength_correct. f_equal. unfold make_fields_vals, make_fields.\n  destruct (raw_mark (vlabel g v)).\n  - destruct (raw_fields_head_cons (vlabel g v)) as [r [l [? ?]]].\n    rewrite H; simpl; destruct r; [destruct s|]; simpl;\n      rewrite map_length, make_fields'_eq_length; reflexivity.\n  - rewrite map_length, make_fields'_eq_length. reflexivity.\nQed.\n\nLemma make_fields_eq_length: forall g v,\n    Zlength (make_fields g v) = Zlength (raw_fields (vlabel g v)).\nProof.\n  unfold make_fields. intros.\n  rewrite !Zlength_correct, make_fields'_eq_length. reflexivity.\nQed.\n\nLemma make_fields_Znth_edge: forall g v n e,\n    0 <= n < Zlength (raw_fields (vlabel g v)) ->\n    Znth n (make_fields g v) = inr e -> e = (v, Z.to_nat n).\nProof.\n  intros. rewrite <- nth_Znth in H0. 2: rewrite make_fields_eq_length; assumption.\n  apply make_fields'_edge_depends_on_index in H0.\n  - rewrite Nat.add_0_r in H0; assumption.\n  - rewrite Z2Nat.id; [assumption | lia].\nQed.\n\nLemma Znth_skip_hd_same: forall A (d: Inhabitant A) (l: list A) a n,\n    n > 0 ->\n    Zlength l > 0 ->\n    Znth n (a :: tl l) = Znth n l.\nProof.\n  intros. destruct l.\n  - rewrite Zlength_nil in H0; inversion H0.\n  - repeat rewrite Znth_pos_cons by lia. reflexivity.\nQed.\n\nLemma make_fields'_n_doesnt_matter: forall i l v n m gcptr,\n    nth i (make_fields' l v n) field_t_inhabitant = inl (inr gcptr) ->\n    nth i (make_fields' l v m) field_t_inhabitant = inl (inr gcptr).\nProof.\n  intros.\n  unfold make_fields' in *.\n  generalize dependent i.\n  generalize dependent n.\n  generalize dependent m.\n  induction l.\n  + intros; assumption.\n  + induction i.\n    - destruct a; [destruct s|]; simpl; intros; try assumption; try inversion H.\n    - destruct a; [destruct s|]; simpl; intro;\n        apply IHl with (m:=(m+1)%nat) in H; assumption.\nQed.\n\nLemma make_fields'_item_was_in_list: forall l v n gcptr,\n    0 <= n < Zlength l ->\n    Znth n (make_fields' l v 0) = inl (inr gcptr) ->\n    Znth n l = Some (inr gcptr).\nProof.\n  intros.\n  rewrite <- nth_Znth; rewrite <- nth_Znth in H0; [| rewrite Zlength_correct in *..];\n    try rewrite make_fields'_eq_length; [|assumption..].\n  generalize dependent n.\n  induction l.\n  - intros. rewrite nth_Znth in H0; try assumption.\n    unfold make_fields' in H0; rewrite Znth_nil in H0; inversion H0.\n  - intro n. induction (Z.to_nat n) eqn:?.\n    + intros. destruct a; [destruct s|]; simpl in *; try inversion H0; try reflexivity.\n    + intros. simpl in *. clear IHn0.\n      replace n0 with (Z.to_nat (Z.of_nat n0)) by apply Nat2Z.id.\n      assert (0 <= Z.of_nat n0 < Zlength l). {\n        split; try lia.\n        destruct H; rewrite Zlength_cons in H1.\n        apply Zsucc_lt_reg; rewrite <- Nat2Z.inj_succ.\n        rewrite <- Heqn0; rewrite Z2Nat.id; assumption.\n      }\n      destruct a; [destruct s|]; simpl in H0; apply IHl;\n        try assumption; apply make_fields'_n_doesnt_matter with (n:=1%nat);\n        rewrite Nat2Z.id; assumption.\nQed.\n\nLemma make_fields_edge_unique: forall g e v1 v2 n m,\n    0 <= n < Zlength (make_fields g v1) ->\n    0 <= m < Zlength (make_fields g v2) ->\n    Znth n (make_fields g v1) = inr e ->\n    Znth m (make_fields g v2) = inr e ->\n    n = m /\\ v1 = v2.\nProof.\n  intros. unfold make_fields in *.\n  rewrite make_fields'_eq_Zlength in *.\n  assert (0 <= Z.of_nat (Z.to_nat n) < Zlength (raw_fields (vlabel g v1))) by\n      (destruct H; split; rewrite Z2Nat.id; assumption).\n  rewrite <- nth_Znth in H1 by\n      (rewrite make_fields'_eq_Zlength; assumption).\n  assert (0 <= Z.of_nat (Z.to_nat m) < Zlength (raw_fields (vlabel g v2))) by\n       (destruct H0; split; rewrite Z2Nat.id; assumption).\n  rewrite <- nth_Znth in H2 by\n      (rewrite make_fields'_eq_Zlength; assumption).\n  pose proof (make_fields'_edge_depends_on_index\n                (Z.to_nat n) (raw_fields (vlabel g v1)) 0 v1 e H3 H1).\n  pose proof (make_fields'_edge_depends_on_index\n                (Z.to_nat m) (raw_fields (vlabel g v2)) 0 v2 e H4 H2).\n  rewrite H5 in H6. inversion H6.\n  rewrite Nat.add_cancel_r, Z2Nat.inj_iff in H9 by lia.\n  split; [assumption | reflexivity].\nQed.\n\nLemma in_gcptr_outlier: forall g gcptr outlier n v,\n    graph_has_v g v ->\n    outlier_compatible g outlier ->\n    0 <= n < Zlength (raw_fields (vlabel g v)) ->\n    Znth n (make_fields g v) = inl (inr gcptr) ->\n    In gcptr outlier.\nProof.\n  intros.\n  apply H0 in H; apply H; clear H; clear H0.\n  unfold make_fields in H2.\n  apply make_fields'_item_was_in_list in H2; try assumption.\n  rewrite <- filter_sum_right_In_iff, <- filter_option_In_iff.\n  rewrite <- H2; apply Znth_In; assumption.\nQed.\n\nLemma vertex_address_the_same: forall (g1 g2: LGraph) v,\n    (forall v, g1.(vlabel) v = g2.(vlabel) v) ->\n    map start_address g1.(glabel).(g_gen) = map start_address g2.(glabel).(g_gen) ->\n    vertex_address g1 v = vertex_address g2 v.\nProof.\n  intros. unfold vertex_address. f_equal.\n  - f_equal. unfold vertex_offset. f_equal. remember (vindex v). clear Heqn.\n    induction n; simpl; auto. rewrite !pvs_S, IHn. f_equal. unfold vertex_size.\n    rewrite H. reflexivity.\n  - assert (forall gen, graph_has_gen g1 gen <-> graph_has_gen g2 gen). {\n      intros. unfold graph_has_gen.\n      cut (length (g_gen (glabel g1)) = length (g_gen (glabel g2))).\n      - intros. rewrite H1. reflexivity.\n      - do 2 rewrite <- (map_length start_address). rewrite H0. reflexivity.\n    } unfold gen_start. do 2 if_tac; [|rewrite H1 in H2; contradiction.. |reflexivity].\n    unfold nth_gen. rewrite <- !(map_nth start_address), H0. reflexivity.\nQed.\n\nLemma make_fields_the_same: forall (g1 g2: LGraph) v,\n    (forall e, dst g1 e = dst g2 e) ->\n    (forall v, g1.(vlabel) v = g2.(vlabel) v) ->\n    map start_address g1.(glabel).(g_gen) = map start_address g2.(glabel).(g_gen) ->\n    make_fields_vals g1 v = make_fields_vals g2 v.\nProof.\n  intros. unfold make_fields_vals, make_fields. remember O. clear Heqn. rewrite H0.\n  remember (raw_fields (vlabel g2 v)) as l. clear Heql.\n  cut (forall fl, map (field2val g1) fl = map (field2val g2) fl).\n  - intros. rewrite H2. rewrite (vertex_address_the_same g1 g2) by assumption.\n    reflexivity.\n  - apply map_ext. intros. unfold field2val. destruct a. 1: reflexivity.\n    rewrite H. apply vertex_address_the_same; assumption.\nQed.\n\nLemma start_address_reset: forall n l,\n   map start_address (reset_nth_gen_info n l) = map start_address l.\nProof.\n  intros. revert n.\n  induction l; intros; simpl; destruct n; simpl; [| | | rewrite IHl]; reflexivity.\nQed.\n\nLemma vertex_address_reset: forall (g: LGraph) v n,\n    vertex_address (reset_graph n g) v = vertex_address g v.\nProof.\n  intros. apply vertex_address_the_same; unfold reset_graph; simpl.\n  - intros. rewrite remove_ve_vlabel_unchanged. reflexivity.\n  - rewrite remove_ve_glabel_unchanged, start_address_reset. reflexivity.\nQed.\n\nLemma make_fields_reset: forall (g: LGraph) v n,\n    make_fields_vals (reset_graph n g) v = make_fields_vals g v.\nProof.\n  intros. apply make_fields_the_same; unfold reset_graph; simpl; intros.\n  - apply remove_ve_dst_unchanged.\n  - apply remove_ve_vlabel_unchanged.\n  - rewrite remove_ve_glabel_unchanged. apply start_address_reset.\nQed.\n\nLemma make_header_reset: forall (g: LGraph) v n,\n    make_header (reset_graph n g) v = make_header g v.\nProof.\n  intros. unfold make_header. simpl vlabel. rewrite remove_ve_vlabel_unchanged.\n  reflexivity.\nQed.\n\nDefinition copy_v_add_edge\n           (s: VType) (g: PreGraph VType EType) (p: EType * VType):\n  PreGraph VType EType := pregraph_add_edge g (fst p) s (snd p).\n\nDefinition pregraph_copy_v (g: LGraph) (old_v new_v: VType) : PreGraph VType EType :=\n  let old_edges := get_edges g old_v in\n  let new_edges := combine (repeat new_v (length old_edges)) (map snd old_edges) in\n  let new_edge_dst_l := combine new_edges (map (dst g) old_edges) in\n  fold_left (copy_v_add_edge new_v) new_edge_dst_l (pregraph_add_vertex g new_v).\n\nDefinition copy_v_mod_rvb (rvb: raw_vertex_block) (new_v: VType) : raw_vertex_block :=\n  Build_raw_vertex_block\n    true new_v (raw_fields rvb) (raw_color rvb) (raw_tag rvb) (raw_tag_range rvb)\n    (raw_color_range rvb) (raw_fields_range rvb) (tag_no_scan rvb).\n\nDefinition update_copied_new_vlabel (g: LGraph) (old_v new_v: VType) :=\n  update_vlabel (vlabel g) new_v (vlabel g old_v).\n\nDefinition update_copied_old_vlabel (g: LGraph) (old_v new_v: VType) :=\n  update_vlabel (vlabel g) old_v (copy_v_mod_rvb (vlabel g old_v) new_v).\n\nDefinition copy_v_mod_gen_info (gi: generation_info) : generation_info :=\n  Build_generation_info (start_address gi) (number_of_vertices gi + 1)\n                        (generation_sh gi) (start_isptr gi)\n                        (generation_share_writable gi).\n\nDefinition copy_v_mod_gen_info_list\n           (l: list generation_info) (to: nat) : list generation_info :=\n  firstn to l ++ copy_v_mod_gen_info (nth to l null_info) :: skipn (to + 1) l.\n\nLemma copy_v_mod_gen_no_nil: forall l to, copy_v_mod_gen_info_list l to <> nil.\nProof.\n  repeat intro. unfold copy_v_mod_gen_info_list in H. apply app_eq_nil in H.\n  destruct H. inversion H0.\nQed.\n\nDefinition copy_v_update_glabel (gi: graph_info) (to: nat): graph_info :=\n  Build_graph_info (copy_v_mod_gen_info_list (g_gen gi) to)\n                   (copy_v_mod_gen_no_nil (g_gen gi) to).\n\nDefinition new_copied_v (g: LGraph) (to: nat): VType :=\n  (to, number_of_vertices (nth_gen g to)).\n\nDefinition lgraph_add_copied_v (g: LGraph) (v: VType) (to: nat): LGraph :=\n  let new_v := new_copied_v g to in\n  Build_LabeledGraph _ _ _ (pregraph_copy_v g v new_v)\n                     (update_copied_new_vlabel g v new_v)\n                     (elabel g) (copy_v_update_glabel (glabel g) to).\n\nDefinition lgraph_mark_copied (g: LGraph) (old new: VType): LGraph :=\n  Build_LabeledGraph _ _ _ (pg_lg g)\n                     (update_copied_old_vlabel g old new) (elabel g) (glabel g).\n\nDefinition lgraph_copy_v (g: LGraph) (v: VType) (to: nat): LGraph :=\n  lgraph_mark_copied (lgraph_add_copied_v g v to) v (new_copied_v g to).\n\nDefinition forward_t: Type := Z + GC_Pointer + VType + EType.\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: field_t): 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 + (VType * Z).\n\nDefinition forward_p2forward_t\n           (p: forward_p_type) (roots: roots_t) (g: LGraph): forward_t :=\n  match p with\n  | inl root_index => root2forward (Znth root_index roots)\n  | inr (v, n) => if (vlabel g v).(raw_mark) && (n =? 0)\n                  then (inl (inr (vlabel g v).(copied_vertex)))\n                  else field2forward (Znth n (make_fields g v))\n  end.\n\nDefinition vertex_pos_pairs (g: LGraph) (v: VType) : list (forward_p_type) :=\n  map (fun x => inr (v, Z.of_nat x))\n      (nat_inc_list (length (raw_fields (vlabel g v)))).\n\nInductive forward_relation (from to: nat):\n  nat -> forward_t -> LGraph -> LGraph -> 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    vgeneration v <> from -> forward_relation from to depth (inl (inr v)) g g\n| fr_v_in_forwarded: forall depth v g,\n    vgeneration v = from -> (vlabel g v).(raw_mark) = true ->\n    forward_relation from to depth (inl (inr v)) g g\n| fr_v_in_not_forwarded_O: forall v g,\n    vgeneration v = from -> (vlabel g v).(raw_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    vgeneration v = from -> (vlabel g v).(raw_mark) = false ->\n    let new_g := lgraph_copy_v g v to in\n    forward_loop from to depth (vertex_pos_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: LGraph),\n    vgeneration (dst g e) <> from -> forward_relation from to depth (inr e) g g\n| fr_e_to_forwarded: forall depth e (g: LGraph),\n    vgeneration (dst g e) = from -> (vlabel g (dst g e)).(raw_mark) = true ->\n    let new_g := labeledgraph_gen_dst g e (vlabel g (dst g e)).(copied_vertex) in\n    forward_relation from to depth (inr e) g new_g\n| fr_e_to_not_forwarded_O: forall e (g: LGraph),\n    vgeneration (dst g e) = from -> (vlabel g (dst g e)).(raw_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': LGraph),\n    vgeneration (dst g e) = from -> (vlabel g (dst g e)).(raw_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 (vertex_pos_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 -> LGraph -> LGraph -> 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\nDefinition forward_p_compatible\n           (p: forward_p_type) (roots: roots_t) (g: LGraph) (from: nat): Prop :=\n  match p with\n  | inl root_index => 0 <= root_index < Zlength roots\n  | inr (v, n) => graph_has_v g v /\\ 0 <= n < Zlength (vlabel g v).(raw_fields) /\\\n                  (vlabel g v).(raw_mark) = false /\\ vgeneration v <> from\n  end.\n\nFixpoint collect_Z_indices {A} (eqdec: forall (a b: A), {a = b} + {a <> b})\n         (target: A) (l: list A) (ind: Z) : list Z :=\n  match l with\n  | nil => nil\n  | li :: l => if eqdec target li\n               then ind :: collect_Z_indices eqdec target l (ind + 1)\n               else collect_Z_indices eqdec target l (ind + 1)\n  end.\n\nLemma collect_Z_indices_spec:\n  forall {A} {d: Inhabitant A} eqdec (target: A) (l: list A) (ind: Z) c,\n    l = skipn (Z.to_nat ind) c -> 0 <= ind ->\n    forall j, In j (collect_Z_indices eqdec target l ind) <->\n              ind <= j < Zlength c /\\ Znth j c = target.\nProof.\n  intros. revert ind H H0 j. induction l; intros.\n  - simpl. split; intros. 1: exfalso; assumption. pose proof (Zlength_skipn ind c).\n    destruct H1. rewrite <- H, Zlength_nil, (Z.max_r _ _ H0) in H2. symmetry in H2.\n    rewrite Z.max_l_iff in H2. lia.\n  - assert (l = skipn (Z.to_nat (ind + 1)) c). {\n      clear -H H0. rewrite Z2Nat.inj_add by lia. simpl Z.to_nat at 2.\n      remember (Z.to_nat ind). clear ind Heqn H0.\n      replace (n + 1)%nat with (S n) by lia. revert a l c H.\n      induction n; intros; simpl in H; destruct c; [inversion H | | inversion H|].\n      - simpl. inversion H; reflexivity.\n      - apply IHn in H. rewrite H. simpl. destruct c; reflexivity. }\n    assert (0 <= ind + 1) by lia. specialize (IHl _ H1 H2). simpl.\n    assert (Znth ind c = a). {\n      clear -H H0. apply Z2Nat.id in H0. remember (Z.to_nat ind). rewrite <- H0.\n      clear ind Heqn H0. revert a l c H.\n      induction n; intros; simpl in H; destruct c; [inversion H | | inversion H|].\n      - simpl. inversion H. rewrite Znth_0_cons. reflexivity.\n      - rewrite Nat2Z.inj_succ, Znth_pos_cons by lia. apply IHn in H.\n        replace (Z.succ (Z.of_nat n) - 1) with (Z.of_nat n) by lia.\n        assumption. }\n    destruct (eqdec target a).\n    + simpl. rewrite IHl. clear IHl. split; intros; destruct H4; [|intuition|].\n      * subst j. split; [split|]; [lia | | rewrite <- e in H3; assumption].\n        pose proof (Zlength_skipn ind c). rewrite <- H in H4.\n        rewrite Zlength_cons in H4. pose proof (Zlength_nonneg l).\n        destruct (Z.max_spec 0 (Zlength c - Z.max 0 ind)). 2: exfalso; lia.\n        destruct H6 as [? _]. rewrite Z.max_r in H6; lia.\n      * assert (ind = j \\/ ind + 1 <= j < Zlength c) by lia.\n        destruct H6; [left | right; split]; assumption.\n    + rewrite IHl; split; intros; destruct H4; split;\n        [lia | assumption | | assumption].\n      assert (ind = j \\/ ind + 1 <= j < Zlength c) by lia. clear H4. destruct H6.\n      2: assumption. exfalso; subst j. rewrite H5 in H3. rewrite H3 in n.\n      apply n; reflexivity.\nQed.\n\nDefinition get_indices (index: Z) (live_indices: list Z) :=\n  collect_Z_indices Z.eq_dec (Znth index live_indices) live_indices 0.\n\nDefinition upd_bunch (index: Z) (f_info: fun_info)\n           (roots: roots_t) (v: root_t): roots_t :=\n  fold_right (fun i rs => upd_Znth i rs v) roots\n             (get_indices index (live_roots_indices f_info)).\n\nLemma fold_right_upd_Znth_Zlength {A}: forall (l: list Z) (roots: list A) (v: A),\n    (forall j, In j l -> 0 <= j < Zlength roots) ->\n    Zlength (fold_right (fun (i : Z) (rs : list A) => upd_Znth i rs v) roots l) =\n    Zlength roots.\nProof.\n  induction l; intros; simpl. 1: reflexivity. rewrite upd_Znth_Zlength.\n  - apply IHl. intros. apply H. right. assumption.\n  - rewrite IHl; intros; apply H; [left; reflexivity | right; assumption].\nQed.\n\nLemma get_indices_spec: forall (l: list Z) (z j : Z),\n    In j (get_indices z l) <-> 0 <= j < Zlength l /\\ Znth j l = Znth z l.\nProof.\n  intros. unfold get_indices. remember (Znth z l) as p. clear Heqp z.\n  apply collect_Z_indices_spec. 2: lia. rewrite skipn_0. reflexivity.\nQed.\n\nLemma upd_bunch_Zlength: forall (f_info : fun_info) (roots : roots_t) (z : Z),\n    Zlength roots = Zlength (live_roots_indices f_info) ->\n    forall r : root_t, Zlength (upd_bunch z f_info roots r) = Zlength roots.\nProof.\n  intros. unfold upd_bunch. apply fold_right_upd_Znth_Zlength.\n  intros. rewrite H. rewrite get_indices_spec in H0. destruct H0; assumption.\nQed.\n\nLemma fold_right_upd_Znth_same {A} {d: Inhabitant A}:\n  forall (l: list Z) (roots: list A) (v: A),\n    (forall j, In j l -> 0 <= j < Zlength roots) ->\n    forall j,\n      In j l ->\n      Znth j (fold_right (fun (i : Z) (rs : list A) => upd_Znth i rs v) roots l) = v.\nProof.\n  intros. induction l; simpl in H0. 1: exfalso; assumption.\n  assert (Zlength (fold_right (fun (i : Z) (rs : list A) => upd_Znth i rs v) roots l) =\n          Zlength roots) by\n      (apply fold_right_upd_Znth_Zlength; intros; apply H; right; assumption).\n  simpl. destruct H0.\n  - subst a. rewrite upd_Znth_same. reflexivity. rewrite H1. apply H.\n    left; reflexivity.\n  - destruct (Z.eq_dec j a).\n    + subst a. rewrite upd_Znth_same. reflexivity. rewrite H1. apply H.\n      left; reflexivity.\n    + rewrite upd_Znth_diff; [|rewrite H1; apply H; intuition..| assumption].\n      apply IHl; [intros; apply H; right |]; assumption.\nQed.\n\nLemma upd_bunch_same: forall f_info roots z j r,\n    0 <= j < Zlength roots ->\n    Zlength roots = Zlength (live_roots_indices f_info) ->\n    Znth j (live_roots_indices f_info) = Znth z (live_roots_indices f_info) ->\n    Znth j (upd_bunch z f_info roots r) = r.\nProof.\n  intros. unfold upd_bunch. apply fold_right_upd_Znth_same.\n  - intros. rewrite get_indices_spec in H2. destruct H2. rewrite H0; assumption.\n  - rewrite get_indices_spec. split; [rewrite <- H0|]; assumption.\nQed.\n\nLemma fold_right_upd_Znth_diff {A} {d: Inhabitant A}:\n  forall (l: list Z) (roots: list A) (v: A),\n    (forall j, In j l -> 0 <= j < Zlength roots) ->\n    forall j,\n      ~ In j l -> 0 <= j < Zlength roots ->\n      Znth j (fold_right (fun (i : Z) (rs : list A) => upd_Znth i rs v) roots l) =\n      Znth j roots.\nProof.\n  intros. induction l; simpl. 1: reflexivity.\n  assert (Zlength (fold_right (fun (i : Z) (rs : list A) => upd_Znth i rs v) roots l) =\n          Zlength roots) by\n      (apply fold_right_upd_Znth_Zlength; intros; apply H; right; assumption).\n  assert (j <> a) by (intro; apply H0; left; rewrite H3; reflexivity).\n  rewrite upd_Znth_diff; [ | rewrite H2.. | assumption];\n    [|assumption | apply H; intuition].\n  apply IHl; repeat intro; [apply H | apply H0]; right; assumption.\nQed.\n\nLemma upd_bunch_diff: forall f_info roots z j r,\n    0 <= j < Zlength roots ->\n    Zlength roots = Zlength (live_roots_indices f_info) ->\n    Znth j (live_roots_indices f_info) <> Znth z (live_roots_indices f_info) ->\n    Znth j (upd_bunch z f_info roots r) = Znth j roots.\nProof.\n  intros. unfold upd_bunch. apply fold_right_upd_Znth_diff. 3: assumption.\n  - intros. rewrite get_indices_spec in H2. destruct H2. rewrite H0; assumption.\n  - rewrite get_indices_spec. intro. destruct H2. apply H1. assumption.\nQed.\n\nLemma Znth_list_eq {X: Type} {d: Inhabitant X}: forall (l1 l2: list X),\n    l1 = l2 <-> (Zlength l1 = Zlength l2 /\\\n                 forall j, 0 <= j < Zlength l1 -> Znth j l1 = Znth j l2).\nProof.\n  induction l1; destruct l2; split; intros.\n  - split; intros; reflexivity.\n  - reflexivity.\n  - inversion H.\n  - destruct H. rewrite Zlength_nil, Zlength_cons in H. exfalso; rep_lia.\n  - inversion H.\n  - destruct H. rewrite Zlength_nil, Zlength_cons in H. exfalso; rep_lia.\n  - inversion H. subst a. subst l1. split; intros; reflexivity.\n  - destruct H. assert (0 <= 0 < Zlength (a :: l1)) by\n        (rewrite Zlength_cons; rep_lia). apply H0 in H1. rewrite !Znth_0_cons in H1.\n    subst a. rewrite !Zlength_cons in H. f_equal. rewrite IHl1. split. 1: rep_lia.\n    intros. assert (0 < j + 1) by lia.\n    assert (0 <= j + 1 < Zlength (x :: l1)) by (rewrite Zlength_cons; rep_lia).\n    specialize (H0 _ H3). rewrite !Znth_pos_cons in H0 by assumption.\n    replace (j + 1 - 1) with j in H0 by lia. assumption.\nQed.\n\nLemma upd_thread_info_Zlength: forall (t: thread_info) (i: Z) (v: val),\n    0 <= i < MAX_ARGS -> Zlength (upd_Znth i (ti_args t) v) = MAX_ARGS.\nProof.\n  intros. rewrite upd_Znth_Zlength; [apply arg_size | rewrite arg_size; assumption].\nQed.\n\nDefinition upd_thread_info_arg\n           (t: thread_info) (i: Z) (v: val) (H: 0 <= i < MAX_ARGS) : thread_info :=\n  Build_thread_info (ti_heap_p t) (ti_heap t) (upd_Znth i (ti_args t) v)\n                    (upd_thread_info_Zlength t i v H).\n\nLemma upd_fun_thread_arg_compatible: forall g t_info f_info roots z,\n    fun_thread_arg_compatible g t_info f_info roots ->\n    forall (v : VType) (HB : 0 <= Znth z (live_roots_indices f_info) < MAX_ARGS),\n      fun_thread_arg_compatible\n        g (upd_thread_info_arg t_info (Znth z (live_roots_indices f_info))\n                               (vertex_address g v) HB) f_info\n        (upd_bunch z f_info roots (inr v)).\nProof.\n  intros. red in H |-* . unfold upd_thread_info_arg. simpl. rewrite Znth_list_eq in H.\n  destruct H. rewrite !Zlength_map in H. rewrite Zlength_map in H0.\n  assert (Zlength (upd_bunch z f_info roots (inr v)) = Zlength roots) by\n      (rewrite upd_bunch_Zlength; [reflexivity | assumption]).\n  rewrite Znth_list_eq. split. 1: rewrite !Zlength_map, H1; assumption. intros.\n  rewrite Zlength_map, H1 in H2.\n  rewrite !Znth_map; [|rewrite <- H | rewrite H1]; [|assumption..].\n  specialize (H0 _ H2). rewrite !Znth_map in H0; [|rewrite <- H| ]; [|assumption..].\n  unfold flip in *.\n  destruct (Z.eq_dec (Znth j (live_roots_indices f_info))\n                     (Znth z (live_roots_indices f_info))).\n  - rewrite e, upd_Znth_same. 2: rewrite arg_size; rep_lia.\n    rewrite upd_bunch_same; [|assumption..]. reflexivity.\n  - rewrite upd_Znth_diff. 4: assumption. 3: rewrite arg_size; rep_lia.\n    + rewrite <- H0. rewrite upd_bunch_diff; [|assumption..]. reflexivity.\n    + rewrite arg_size. apply (fi_index_range f_info), Znth_In.\n      rewrite <- H. assumption.\nQed.\n\nLemma In_Znth {A} {d: Inhabitant A}: forall (e: A) l,\n    In e l -> exists i, 0 <= i < Zlength l /\\ Znth i l = e.\nProof.\n  intros. apply In_nth with (d := d) in H. destruct H as [n [? ?]].\n  exists (Z.of_nat n). assert (0 <= Z.of_nat n < Zlength l) by\n      (rewrite Zlength_correct; lia). split. 1: assumption.\n  rewrite <- nth_Znth by assumption. rewrite Nat2Z.id. assumption.\nQed.\n\nLemma upd_Znth_In {A}: forall (e: A) l i v, In v (upd_Znth i l e) -> In v l \\/ v = e.\nProof.\n  intros. destruct (Z_lt_le_dec i 0). 1: rewrite upd_Znth_out_of_range in H; auto; left; lia.\n  destruct (Z_lt_le_dec i (Zlength l)).\n  2: { rewrite upd_Znth_out_of_range in H; auto; right; lia. }\n  rewrite upd_Znth_unfold in H; auto. rewrite in_app_iff in H. simpl in H.\n  destruct H as [? | [? | ?]]; [|right; rewrite H; reflexivity|];\n    apply sublist_In in H; left; assumption.\nQed.\n\nLemma fold_right_upd_Znth_In {A}: forall (l: list Z) (roots: list A) (v: A) e,\n      In e (fold_right (fun (i : Z) (rs : list A) => upd_Znth i rs v) roots l) ->\n      In e roots \\/ e = v.\nProof.\n  induction l; intros; simpl in H. 1: left; assumption.\n  apply upd_Znth_In in H. destruct H; [apply IHl | right]; assumption.\nQed.\n\nLemma upd_roots_outlier_compatible: forall f_info roots outlier z v,\n    roots_outlier_compatible roots outlier ->\n    (* forall v : VType, *)\n    (*   graph_has_v g v -> *)\n    roots_outlier_compatible (upd_bunch z f_info roots (inr v)) outlier.\nProof.\n  intros. do 2 red in H |-* . intros.\n  rewrite <- filter_sum_right_In_iff, <- filter_sum_left_In_iff in H0.\n  unfold upd_bunch in H0. apply fold_right_upd_Znth_In in H0. destruct H0.\n  2: inversion H0. apply H.\n  rewrite <- filter_sum_right_In_iff, <- filter_sum_left_In_iff. assumption.\nQed.\n\nLemma upd_bunch_graph_compatible: forall g f_info roots z,\n    roots_graph_compatible roots g ->\n    forall v : VType,\n      graph_has_v g v ->\n      roots_graph_compatible (upd_bunch z f_info roots (inr v)) g.\nProof.\n  intros. red in H |-* . rewrite Forall_forall in H |-* . intros.\n  rewrite <- filter_sum_right_In_iff in H1. unfold upd_bunch in H1.\n  apply fold_right_upd_Znth_In in H1. destruct H1. 2: inversion H1; assumption.\n  apply H. rewrite <- filter_sum_right_In_iff. assumption.\nQed.\n\nLemma upd_roots_compatible: forall g f_info roots outlier z,\n    roots_compatible g outlier roots ->\n    forall v : VType, graph_has_v g v ->\n                      roots_compatible g outlier (upd_bunch z f_info roots (inr v)).\nProof.\n  intros. destruct H. split.\n  - apply upd_roots_outlier_compatible; assumption.\n  - apply upd_bunch_graph_compatible; assumption.\nQed.\n\nLocal Close Scope Z_scope.\n\nDefinition upd_roots (from to: nat) (forward_p: forward_p_type)\n           (g: LGraph) (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 (vgeneration v) from\n                            then if (vlabel g v).(raw_mark)\n                                 then upd_bunch index f_info roots\n                                                (inr (vlabel g v).(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\nInductive forward_roots_loop (from to: nat) (f_info: fun_info):\n  list nat -> roots_t -> LGraph -> roots_t -> LGraph -> 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\nDefinition nth_space (t_info: thread_info) (n: nat): space :=\n  nth n t_info.(ti_heap).(spaces) null_space.\n\nLemma nth_space_Znth: forall t n,\n    nth_space t n = Znth (Z.of_nat n) (spaces (ti_heap t)).\nProof.\n  intros. unfold nth_space, Znth. rewrite if_false. 2: lia.\n  rewrite Nat2Z.id. reflexivity.\nQed.\n\nDefinition gen_size t_info n := total_space (nth_space t_info n).\n\nLemma gsc_iff: forall (g: LGraph) t_info,\n    length (g_gen (glabel g)) <= length (spaces (ti_heap t_info)) ->\n    Forall (generation_space_compatible g)\n           (combine (combine (nat_inc_list (length (g_gen (glabel g))))\n                             (g_gen (glabel g))) (spaces (ti_heap t_info))) <->\n    forall gen,\n      graph_has_gen g gen ->\n      generation_space_compatible g (gen, nth_gen g gen, nth_space t_info gen).\nProof.\n  intros. rewrite Forall_forall. remember (g_gen (glabel g)).\n  remember (nat_inc_list (length l)). remember (spaces (ti_heap t_info)).\n  assert (length (combine l0 l) = length l) by\n      (subst; rewrite combine_length, nat_inc_list_length, Nat.min_id; reflexivity).\n  assert (length (combine (combine l0 l) l1) = length l) by\n      (rewrite combine_length, H0, min_l by assumption; reflexivity).\n  cut (forall x, In x (combine (combine l0 l) l1) <->\n                    exists gen, graph_has_gen g gen /\\\n                                x = (gen, nth_gen g gen, nth_space t_info gen)).\n  - intros. split; intros.\n    + apply H3. rewrite H2. exists gen. intuition.\n    + rewrite H2 in H4. destruct H4 as [gen [? ?]]. subst x. apply H3. assumption.\n  - intros.\n    assert (forall gen,\n               graph_has_gen g gen ->\n               nth gen (combine (combine l0 l) l1) (0, null_info, null_space) =\n               (gen, nth_gen g gen, nth_space t_info gen)). {\n      intros. red in H2. rewrite <- Heql in H2.\n      rewrite combine_nth_lt; [|rewrite H0; lia | lia].\n      rewrite combine_nth by (subst l0; rewrite nat_inc_list_length; reflexivity).\n      rewrite Heql0. rewrite nat_inc_list_nth by assumption.\n      rewrite Heql. unfold nth_gen, nth_space. rewrite Heql1. reflexivity. }\n    split; intros.\n    + apply (In_nth (combine (combine l0 l) l1) x (O, null_info, null_space)) in H3.\n      destruct H3 as [gen [? ?]]. exists gen. rewrite H1 in H3.\n      assert (graph_has_gen g gen) by (subst l; assumption). split. 1: assumption.\n      rewrite H2 in H4 by assumption. subst x. reflexivity.\n    + destruct H3 as [gen [? ?]]. rewrite <- H2 in H4 by assumption. subst x.\n      apply nth_In. rewrite H1. subst l. assumption.\nQed.\n\nLemma gt_gs_compatible:\n  forall (g: LGraph) (t_info: thread_info),\n    graph_thread_info_compatible g t_info ->\n    forall gen,\n      graph_has_gen g gen ->\n      generation_space_compatible g (gen, nth_gen g gen, nth_space t_info gen).\nProof.\n  intros. destruct H as [? [_ ?]]. rewrite gsc_iff in H by assumption.\n  apply H. assumption.\nQed.\n\nLemma pvs_mono_strict: forall g gen i j,\n    i < j -> (previous_vertices_size g gen i < previous_vertices_size g gen j)%Z.\nProof.\n  intros. assert (j = i + (j - i)) by lia. rewrite H0. remember (j - i). subst j.\n  unfold previous_vertices_size. rewrite nat_inc_list_app, fold_left_app.\n  apply vs_accum_list_lt. pose proof (nat_seq_length i n). destruct (nat_seq i n).\n  - simpl in H0. lia.\n  - intro S; inversion S.\nQed.\n\nLemma pvs_mono: forall g gen i j,\n    i <= j -> (previous_vertices_size g gen i <= previous_vertices_size g gen j)%Z.\nProof.\n  intros. rewrite Nat.le_lteq in H. destruct H. 2: subst; lia.\n  rewrite Z.le_lteq. left. apply pvs_mono_strict. assumption.\nQed.\n\nLemma pvs_lt_rev: forall g gen i j,\n    (previous_vertices_size g gen i < previous_vertices_size g gen j)%Z -> i < j.\nProof.\n  intros. destruct (le_lt_dec j i).\n  - apply (pvs_mono g gen) in l. exfalso. lia.\n  - assumption.\nQed.\n\nLocal Open Scope Z_scope.\n\nDefinition forward_roots_compatible\n           (from to: nat) (g: LGraph) (ti : thread_info): Prop :=\n  (nth_space ti from).(used_space) <= (nth_space ti to).(total_space) -\n                                      (nth_space ti to).(used_space).\n\nLemma vo_lt_gs: forall g v,\n    gen_has_index g (vgeneration v) (vindex v) ->\n    vertex_offset g v < graph_gen_size g (vgeneration v).\nProof.\n  intros. unfold vertex_offset, graph_gen_size. red in H.\n  remember (number_of_vertices (nth_gen g (vgeneration v))). remember (vgeneration v).\n  assert (S (vindex v) <= n)%nat by lia.\n  apply Z.lt_le_trans with (previous_vertices_size g n0 (S (vindex v))).\n  - rewrite pvs_S. apply Zplus_lt_compat_l, svs_gt_one.\n  - apply pvs_mono; assumption.\nQed.\n\nDefinition v_in_range (v: val) (start: val) (n: Z): Prop :=\n  exists i, 0 <= i < n /\\ v = offset_val i start.\n\nLemma graph_thread_v_in_range: forall g t_info v,\n    graph_thread_info_compatible g t_info -> graph_has_v g v ->\n    v_in_range (vertex_address g v) (gen_start g (vgeneration v))\n               (WORD_SIZE * gen_size t_info (vgeneration v)).\nProof.\n  intros. red. unfold vertex_address. exists (WORD_SIZE * vertex_offset g v).\n  split. 2: reflexivity. unfold gen_size. destruct H0. remember (vgeneration v). split.\n  - unfold vertex_offset. unfold WORD_SIZE.\n    pose proof (pvs_ge_zero g (vgeneration v) (vindex v)). rep_lia.\n  - unfold WORD_SIZE. apply Zmult_lt_compat_l. 1: rep_lia.\n    apply Z.lt_le_trans with (used_space (nth_space t_info n)).\n    2: apply (proj2 (space_order (nth_space t_info n))).\n    destruct (gt_gs_compatible _ _ H _ H0) as [? [? ?]].\n    rewrite <- H4, Heqn. apply vo_lt_gs. subst n. assumption.\nQed.\n\nDefinition nth_sh g gen := generation_sh (nth_gen g gen).\n\nLemma reset_nth_sh_diff: forall g i j,\n    i <> j -> nth_sh (reset_graph j g) i = nth_sh g i.\nProof. intros. unfold nth_sh. rewrite reset_nth_gen_diff; auto. Qed.\n\nLemma reset_nth_sh: forall g i j,\n    nth_sh (reset_graph j g) i = nth_sh g i.\nProof.\n  intros. destruct (Nat.eq_dec i j).\n  - subst. unfold reset_graph, nth_sh, nth_gen. simpl.\n    rewrite reset_nth_gen_info_same, remove_ve_glabel_unchanged. reflexivity.\n  - apply reset_nth_sh_diff. assumption.\nQed.\n\nLemma Znth_tl {A} {d: Inhabitant A}: forall (l: list A) i,\n    0 <= i -> Znth i (tl l) = Znth (i + 1) l.\nProof.\n  intros. destruct l; simpl.\n  - unfold Znth; if_tac; if_tac; try lia; destruct (Z.to_nat (i + 1));\n      destruct (Z.to_nat i); simpl; reflexivity.\n  - rewrite Znth_pos_cons by lia. replace (i + 1 - 1) with i by lia. reflexivity.\nQed.\n\nDefinition unmarked_gen_size (g: LGraph) (gen: nat) :=\n  fold_left (vertex_size_accum g gen)\n            (filter (fun i => negb (vlabel g (gen, i)).(raw_mark))\n                    (nat_inc_list (number_of_vertices (nth_gen g gen)))) 0.\n\nLemma unmarked_gen_size_le: forall g n, unmarked_gen_size g n <= graph_gen_size g n.\nProof.\n  intros g gen. unfold unmarked_gen_size, graph_gen_size, previous_vertices_size.\n  apply fold_left_mono_filter;\n    [intros; rewrite Z.le_lteq; left; apply vsa_mono | apply vsa_comm].\nQed.\n\nLemma single_unmarked_le: forall g v,\n    graph_has_v g v -> raw_mark (vlabel g v) = false ->\n    vertex_size g v <= unmarked_gen_size g (vgeneration v).\nProof.\n  intros. unfold unmarked_gen_size.\n  remember (filter (fun i : nat => negb (raw_mark (vlabel g (vgeneration v, i))))\n                   (nat_inc_list (number_of_vertices (nth_gen g (vgeneration v))))).\n  assert (In (vindex v) l). {\n    subst l. rewrite filter_In. split.\n    - rewrite nat_inc_list_In_iff. apply (proj2 H).\n    - destruct v; simpl. rewrite negb_true_iff. apply H0. }\n  apply In_Permutation_cons in H1. destruct H1 as [l1 ?]. symmetry in H1.\n  change (vindex v :: l1) with ([vindex v] ++ l1) in H1.\n  transitivity (fold_left (vertex_size_accum g (vgeneration v)) [vindex v] 0).\n  - simpl. destruct v; simpl. apply Z.le_refl.\n  - apply (fold_left_Z_mono (vertex_size_accum g (vgeneration v)) [vindex v] l1 l 0);\n      [intros; apply Z.le_lteq; left; apply vsa_mono | apply vsa_comm | apply H1].\nQed.\n\nDefinition rest_gen_size (t_info: thread_info) (gen: nat): Z :=\n  total_space (nth_space t_info gen) - used_space (nth_space t_info gen).\n\nDefinition enough_space_to_copy g t_info from to: Prop :=\n  unmarked_gen_size g from <= rest_gen_size t_info to.\n\nDefinition no_dangling_dst (g: LGraph): Prop :=\n  forall v, graph_has_v g v ->\n            forall e, In e (get_edges g v) -> graph_has_v g (dst g e).\n\nDefinition forward_condition g t_info from to: Prop :=\n  enough_space_to_copy g t_info from to /\\\n  graph_has_gen g from /\\ graph_has_gen g to /\\\n  copy_compatible g /\\ no_dangling_dst g.\n\nDefinition has_space (sp: space) (s: Z): Prop :=\n  0 <= s <= total_space sp - used_space sp.\n\nLemma cut_space_order: forall (sp : space) (s : Z),\n    has_space sp s -> 0 <= used_space sp + s <= total_space sp.\nProof. intros. pose proof (space_order sp). red in H. lia. Qed.\n\nDefinition cut_space (sp: space) (s: Z) (H: has_space sp s): space :=\n  Build_space (space_start sp) (used_space sp + s) (total_space sp)\n              (space_sh sp) (cut_space_order sp s H) (space_upper_bound sp).\n\nLemma cut_heap_size:\n  forall (h : heap) (i s : Z) (H : has_space (Znth i (spaces h)) s),\n    0 <= i < Zlength (spaces h) ->\n    Zlength (upd_Znth i (spaces h) (cut_space (Znth i (spaces h)) s H)) = MAX_SPACES.\nProof. intros. rewrite upd_Znth_Zlength; [apply spaces_size | assumption]. Qed.\n\nDefinition cut_heap (h: heap) (i s: Z) (H1: 0 <= i < Zlength (spaces h))\n           (H2: has_space (Znth i (spaces h)) s): heap :=\n  Build_heap (upd_Znth i (spaces h) (cut_space (Znth i (spaces h)) s H2))\n             (cut_heap_size h i s H2 H1).\n\nLemma heap_head_cut_thread_info: forall\n    h i s (H1: 0 <= i < Zlength (spaces h)) (H2: has_space (Znth i (spaces h)) s),\n    i <> 0 -> heap_head (cut_heap h i s H1 H2) = heap_head h.\nProof.\n  intros. destruct (heap_head_cons h) as [hs1 [l1 [? ?]]].\n  destruct (heap_head_cons (cut_heap h i s H1 H2)) as [hs2 [l2 [? ?]]].\n  rewrite H3, H5. simpl in H4.\n  pose proof (split3_full_length_list\n                0 i _ _ H1 (Zminus_0_l_reverse (Zlength (spaces h)))).\n  replace (i - 0) with i in H6 by lia. simpl in H6.\n  remember (firstn (Z.to_nat i) (spaces h)) as ls1.\n  remember (skipn (Z.to_nat (i + 1)) (spaces h)) as ls2.\n  assert (Zlength ls1 = i). {\n    rewrite Zlength_length by lia. subst ls1. apply firstn_length_le.\n    clear H5. rewrite Zlength_correct in H1. rep_lia. }\n  rewrite H6 in H4 at 1. rewrite (upd_Znth_char _ _ _ _ _ H7) in H4.\n  rewrite H6 in H0. clear -H0 H4 H H7. destruct ls1.\n  - rewrite Zlength_nil in H7. exfalso. apply H. subst i. reflexivity.\n  - simpl in H0, H4. inversion H0. subst hs1. inversion H4. reflexivity.\nQed.\n\nDefinition cut_thread_info (t: thread_info) (i s: Z)\n           (H1: 0 <= i < Zlength (spaces (ti_heap t)))\n           (H2: has_space (Znth i (spaces (ti_heap t))) s) : thread_info :=\n  Build_thread_info (ti_heap_p t) (cut_heap (ti_heap t) i s H1 H2) (ti_args t)\n                    (arg_size t).\n\nLemma cti_eq: forall t i s1 s2 (H1: 0 <= i < Zlength (spaces (ti_heap t)))\n                     (Hs1: has_space (Znth i (spaces (ti_heap t))) s1)\n                     (Hs2: has_space (Znth i (spaces (ti_heap t))) s2),\n    s1 = s2 -> cut_thread_info t i s1 H1 Hs1 = cut_thread_info t i s2 H1 Hs2.\nProof.\n  intros. unfold cut_thread_info. f_equal. subst s1. f_equal. apply proof_irr.\nQed.\n\nLemma upd_Znth_tl {A}: forall (i: Z) (l: list A) (x: A),\n    0 <= i -> l <> nil -> tl (upd_Znth (i + 1) l x) = upd_Znth i (tl l) x.\nProof.\n  intros. destruct l; simpl. 1: contradiction.\n  destruct (Z_lt_le_dec i (Zlength l)).\n  2: rewrite !upd_Znth_out_of_range; auto; [|rewrite Zlength_cons]; lia.\n  rewrite !upd_Znth_unfold; auto. 2: rewrite Zlength_cons; lia.\n  unfold_sublist_old. replace (i - 0) with i by lia.\n  replace (i + 1 - 0) with (i + 1) by lia. simpl.\n  assert (forall j, 0 <= j -> Z.to_nat (j + 1) = S (Z.to_nat j)) by\n      (intros; rewrite <- Z2Nat.inj_succ; rep_lia).\n  rewrite (H1 _ H). simpl tl. do 3 f_equal.\n  - f_equal. rewrite Zlength_cons. lia.\n  - remember (S (Z.to_nat i)). replace (Z.to_nat (i + 1 + 1)) with (S n).\n    + simpl. reflexivity.\n    + do 2 rewrite H1 by lia. subst n. reflexivity.\nQed.\n\nLemma isptr_is_pointer_or_integer: forall p, isptr p -> is_pointer_or_integer p.\nProof. intros. destruct p; try contradiction. exact I. Qed.\n\nLemma mfv_unmarked_all_is_ptr_or_int: forall (g : LGraph) (v : VType),\n    no_dangling_dst g -> graph_has_v g v ->\n    Forall is_pointer_or_integer (map (field2val g) (make_fields g v)).\nProof.\n  intros. rewrite Forall_forall. intros f ?. apply list_in_map_inv in H1.\n  destruct H1 as [x [? ?]]. destruct x as [[? | ?] | ?]; simpl in H1; subst.\n  - unfold odd_Z2val. exact I.\n  - destruct g0. exact I.\n  - apply isptr_is_pointer_or_integer. unfold vertex_address.\n    rewrite isptr_offset_val. apply graph_has_gen_start_isptr.\n    apply filter_sum_right_In_iff, H in H2; [destruct H2|]; assumption.\nQed.\n\nLemma mfv_all_is_ptr_or_int: forall g v,\n    copy_compatible g -> no_dangling_dst g -> graph_has_v g v ->\n    Forall is_pointer_or_integer (make_fields_vals g v).\nProof.\n  intros. rewrite Forall_forall. intros f ?. unfold make_fields_vals in H2.\n  pose proof (mfv_unmarked_all_is_ptr_or_int _ _ H0 H1). rewrite Forall_forall in H3.\n  specialize (H3 f). destruct (raw_mark (vlabel g v)) eqn:? . 2: apply H3; assumption.\n  simpl in H2. destruct H2. 2: apply H3, In_tail; assumption.\n  subst f. unfold vertex_address. apply isptr_is_pointer_or_integer.\n  rewrite isptr_offset_val. apply graph_has_gen_start_isptr, (proj1 (H _ H1 Heqb)).\nQed.\n\nLemma upd_tf_arg_Zlength: forall (t: thread_info) (index: Z) (v: val),\n    0 <= index < MAX_ARGS -> Zlength (upd_Znth index (ti_args t) v) = MAX_ARGS.\nProof.\n  intros. rewrite upd_Znth_Zlength; [apply arg_size | rewrite arg_size; assumption].\nQed.\n\nDefinition update_thread_info_arg (t: thread_info) (index: Z)\n           (v: val) (H: 0 <= index < MAX_ARGS): thread_info :=\n  Build_thread_info (ti_heap_p t) (ti_heap t) (upd_Znth index (ti_args t) v)\n                    (upd_tf_arg_Zlength t index v H).\n\nLocal Close Scope Z_scope.\n\nLemma cvmgil_length: forall l to,\n    to < length l -> length (copy_v_mod_gen_info_list l to) = length l.\nProof.\n  intros. unfold copy_v_mod_gen_info_list. rewrite app_length. simpl.\n  rewrite firstn_length_le by lia. rewrite skipn_length. lia.\nQed.\n\nLemma cvmgil_not_eq: forall to n l,\n    n <> to -> to < length l ->\n    nth n (copy_v_mod_gen_info_list l to) null_info = nth n l null_info.\nProof.\n  intros. unfold copy_v_mod_gen_info_list.\n  assert (length (firstn to l) = to) by (rewrite firstn_length_le; lia).\n  destruct (Nat.lt_ge_cases n to).\n  - rewrite app_nth1 by lia. apply nth_firstn. assumption.\n  - rewrite Nat.lt_eq_cases in H2. destruct H2. 2: exfalso; intuition.\n    rewrite <- (firstn_skipn (to + 1) l) at 4. rewrite app_cons_assoc, !app_nth2.\n    + do 2 f_equal. rewrite app_length, H1, firstn_length_le by lia. reflexivity.\n    + rewrite firstn_length_le; lia.\n    + rewrite app_length, H1. simpl. lia.\nQed.\n\nLemma cvmgil_eq: forall to l,\n    to < length l -> nth to (copy_v_mod_gen_info_list l to) null_info =\n                     copy_v_mod_gen_info (nth to l null_info).\nProof.\n  intros. unfold copy_v_mod_gen_info_list.\n  assert (length (firstn to l) = to) by (rewrite firstn_length_le; lia).\n  rewrite app_nth2 by lia. rewrite H0. replace (to - to) with O by lia.\n  simpl. reflexivity.\nQed.\n\nLemma lacv_nth_gen: forall g v to n,\n    n <> to -> graph_has_gen g to ->\n    nth_gen (lgraph_add_copied_v g v to) n = nth_gen g n.\nProof.\n  intros. unfold lgraph_add_copied_v, nth_gen. simpl. remember (g_gen (glabel g)).\n  apply cvmgil_not_eq; [|subst l]; assumption.\nQed.\n\nLemma lacv_graph_has_gen: forall g v to n,\n    graph_has_gen g to ->\n    graph_has_gen (lgraph_add_copied_v g v to) n <-> graph_has_gen g n.\nProof.\n  intros. unfold graph_has_gen. simpl.\n  rewrite cvmgil_length by assumption. reflexivity.\nQed.\n\nLemma lacv_gen_start: forall g v to n,\n    graph_has_gen g to -> gen_start (lgraph_add_copied_v g v to) n = gen_start g n.\nProof.\n  intros. unfold gen_start. do 2 if_tac.\n  - destruct (Nat.eq_dec n to).\n    + subst n. unfold nth_gen. simpl. rewrite cvmgil_eq by assumption.\n      simpl. reflexivity.\n    + rewrite lacv_nth_gen by assumption. reflexivity.\n  - rewrite lacv_graph_has_gen in H0 by assumption. contradiction.\n  - exfalso. apply H0. rewrite lacv_graph_has_gen; assumption.\n  - reflexivity.\nQed.\n\nLemma lacv_vlabel_old: forall (g : LGraph) (v : VType) (to: nat) x,\n    x <> new_copied_v g to -> vlabel (lgraph_add_copied_v g v to) x = vlabel g x.\nProof.\n  intros. simpl.\n  unfold update_copied_new_vlabel, graph_gen.update_vlabel.\n  rewrite if_false. 1: reflexivity. unfold Equivalence.equiv; intro S; apply H.\n  inversion S; reflexivity.\nQed.\n\nDefinition closure_has_index (g: LGraph) (gen index: nat) :=\n  index <= number_of_vertices (nth_gen g gen).\n\nDefinition closure_has_v (g: LGraph) (v: VType): Prop :=\n  graph_has_gen g (vgeneration v) /\\ closure_has_index g (vgeneration v) (vindex v).\n\nLemma lacv_vertex_address: forall (g : LGraph) (v : VType) (to: nat) x,\n    closure_has_v g x -> graph_has_gen g to ->\n    vertex_address (lgraph_add_copied_v g v to) x = vertex_address g x.\nProof.\n  intros. destruct x as [n m]. destruct H. simpl in *. unfold vertex_address. f_equal.\n  - f_equal. unfold vertex_offset. f_equal. unfold previous_vertices_size.\n    simpl. apply fold_left_ext. intros. unfold vertex_size_accum. f_equal.\n    unfold vertex_size. f_equal. rewrite lacv_vlabel_old. 1: reflexivity.\n    intro. unfold new_copied_v in H3. inversion H3.\n    rewrite nat_inc_list_In_iff in H2. subst n. red in H1. lia.\n  - simpl. apply lacv_gen_start. assumption.\nQed.\n\nLemma graph_has_v_in_closure: forall g v, graph_has_v g v -> closure_has_v g v.\nProof.\n  intros g v. destruct v as [gen index].\n  unfold graph_has_v, closure_has_v, closure_has_index, gen_has_index.\n  simpl. intros. intuition.\nQed.\n\nLemma lacv_vertex_address_old: forall (g : LGraph) (v : VType) (to: nat) x,\n    graph_has_v g x -> graph_has_gen g to ->\n    vertex_address (lgraph_add_copied_v g v to) x = vertex_address g x.\nProof.\n  intros. apply lacv_vertex_address; [apply graph_has_v_in_closure |]; assumption.\nQed.\n\nLemma lacv_vertex_address_new: forall (g : LGraph) (v : VType) (to: nat),\n    graph_has_gen g to ->\n    vertex_address (lgraph_add_copied_v g v to) (new_copied_v g to) =\n    vertex_address g (new_copied_v g to).\nProof.\n  intros. unfold new_copied_v. apply lacv_vertex_address. 2: assumption.\n  red. simpl.  split; [assumption | apply Nat.le_refl].\nQed.\n\nLemma lacv_make_header_old: forall (g : LGraph) (v : VType) (to : nat) x,\n    x <> new_copied_v g to ->\n    make_header (lgraph_add_copied_v g v to) x = make_header g x.\nProof.\n  intros. unfold make_header. rewrite lacv_vlabel_old by assumption. reflexivity.\nQed.\n\nLemma e_in_make_fields': forall l v n e,\n    In (inr e) (make_fields' l v n) -> exists s, e = (v, s).\nProof.\n  induction l; intros; simpl in *. 1: exfalso; assumption. destruct a; [destruct s|].\n  - simpl in H. destruct H. 1: inversion H. apply IHl with (n + 1). assumption.\n  - simpl in H. destruct H. 1: inversion H. apply IHl with (n + 1). assumption.\n  - simpl in H. destruct H.\n    + inversion H. exists n. reflexivity.\n    + apply IHl with (n + 1). assumption.\nQed.\n\nLemma flcvae_dst_old: forall g new (l: list (EType * VType)) e,\n    ~ In e (map fst l) -> dst (fold_left (copy_v_add_edge new) l g) e = dst g e.\nProof.\n  intros. revert g H. induction l; intros; simpl. 1: reflexivity.\n  rewrite IHl. 2: intro; apply H; simpl; right; assumption. simpl.\n  unfold updateEdgeFunc. rewrite if_false. 1: reflexivity. unfold equiv. intro.\n  apply H. simpl. left; assumption.\nQed.\n\nLemma flcvae_dst_new: forall g new (l: list (EType * VType)) e v,\n    NoDup (map fst l) -> In (e, v) l ->\n    dst (fold_left (copy_v_add_edge new) l g) e = v.\nProof.\n  intros. revert g. induction l. 1: simpl in H; exfalso; assumption.\n  intros. simpl in *. destruct H0.\n  - subst a. rewrite flcvae_dst_old.\n    + simpl. unfold updateEdgeFunc. rewrite if_true; reflexivity.\n    + simpl in H. apply NoDup_cons_2 in H. assumption.\n  - apply IHl; [apply NoDup_cons_1 in H|]; assumption.\nQed.\n\nLemma pcv_dst_old: forall g old new e,\n    fst e <> new -> dst (pregraph_copy_v g old new) e = dst g e.\nProof.\n  intros. unfold pregraph_copy_v. rewrite flcvae_dst_old. 1: simpl; reflexivity.\n  intro. apply H. rewrite map_fst_combine in H0.\n  - destruct e. simpl in *. apply in_combine_l, repeat_spec in H0. assumption.\n  - unfold EType. rewrite combine_length, repeat_length, !map_length, Nat.min_id.\n    reflexivity.\nQed.\n\nLemma pcv_dst_new: forall g old new n,\n    In n (map snd (get_edges g old)) ->\n    dst (pregraph_copy_v g old new) (new, n) = dst g (old, n).\nProof.\n  intros. unfold pregraph_copy_v. rewrite flcvae_dst_new with (v := dst g (old, n)).\n  - reflexivity.\n  - rewrite map_fst_combine.\n    + apply NoDup_combine_r. clear H. unfold get_edges. unfold make_fields.\n      remember (raw_fields (vlabel g old)). clear Heql. remember 0 as m. clear Heqm.\n      revert m. induction l; intros. simpl. 1: constructor.\n      simpl. destruct a; [destruct s|]; simpl; try apply IHl. constructor.\n      2: apply IHl. clear.\n      cut (forall a b,\n              In a (map snd (filter_sum_right (make_fields' l old b))) -> b <= a).\n      * repeat intro. apply H in H0. lia.\n      * induction l; intros; simpl in H. 1: exfalso; assumption.\n        destruct a; [destruct s|]; simpl in H; try (apply IHl in H; lia).\n        destruct H; [|apply IHl in H]; lia.\n    + unfold EType. rewrite combine_length, repeat_length, !map_length, Nat.min_id.\n      reflexivity.\n  - apply list_in_map_inv in H. destruct H as [[x ?] [? ?]]. simpl in H. subst n0.\n    assert (x = old). {\n      unfold get_edges in H0. rewrite <- filter_sum_right_In_iff in H0.\n      unfold make_fields in H0. apply e_in_make_fields' in H0. destruct H0 as [s ?].\n      inversion H. reflexivity. } subst x. remember (get_edges g old). clear Heql.\n    induction l; simpl in *. 1: assumption. destruct H0.\n    + subst a. simpl. left; reflexivity.\n    + right. apply IHl. assumption.\nQed.\n\nLemma graph_has_v_not_eq: forall g to x,\n    graph_has_v g x -> x <> new_copied_v g to.\nProof.\n  intros. destruct H. unfold new_copied_v. destruct x as [gen idx]. simpl in *.\n  destruct (Nat.eq_dec gen to).\n  - subst gen. intro S; inversion S. red in H0. lia.\n  - intro S; inversion S. apply n; assumption.\nQed.\n\nLemma lacv_make_fields_not_eq: forall (g : LGraph) (v : VType) (to : nat) x,\n    x <> new_copied_v g to ->\n    make_fields (lgraph_add_copied_v g v to) x = make_fields g x.\nProof.\n  intros. unfold make_fields. simpl. unfold update_copied_new_vlabel, update_vlabel.\n  rewrite if_false. 1: reflexivity. intuition.\nQed.\n\nLemma lacv_field2val_make_fields_old:  forall (g : LGraph) (v : VType) (to : nat) x,\n    graph_has_v g x -> graph_has_gen g to -> no_dangling_dst g ->\n    map (field2val (lgraph_add_copied_v g v to))\n        (make_fields (lgraph_add_copied_v g v to) x) =\n    map (field2val g) (make_fields g x).\nProof.\n  intros. unfold make_fields. pose proof (graph_has_v_not_eq _ to _ H).\n  rewrite lacv_vlabel_old by assumption. apply map_ext_in.\n  intros [[? | ?] | ?] ?; simpl; try reflexivity. unfold new_copied_v.\n  rewrite pcv_dst_old.\n  - apply lacv_vertex_address_old. 2: assumption. specialize (H1 _ H). apply H1.\n    unfold get_edges. rewrite <- filter_sum_right_In_iff. assumption.\n  - apply e_in_make_fields' in H3. destruct H3 as [s ?]. subst e. simpl. intro.\n    unfold new_copied_v in H2. contradiction.\nQed.\n\nLemma lacv_make_fields_vals_old: forall (g : LGraph) (v : VType) (to: nat) x,\n    graph_has_v g x -> graph_has_gen g to -> no_dangling_dst g -> copy_compatible g ->\n    make_fields_vals (lgraph_add_copied_v g v to) x = make_fields_vals g x.\nProof.\n  intros. pose proof (lacv_field2val_make_fields_old _ v _ _ H H0 H1).\n  unfold make_fields_vals. pose proof (graph_has_v_not_eq g to x H).\n  rewrite lacv_vlabel_old by assumption. rewrite H3.\n  destruct (raw_mark (vlabel g x)) eqn:? ; [f_equal | reflexivity].\n  apply lacv_vertex_address_old; [apply H2|]; assumption.\nQed.\n\nLemma lacv_nth_sh: forall (g : LGraph) (v : VType) (to : nat) n,\n    graph_has_gen g to -> nth_sh (lgraph_add_copied_v g v to) n = nth_sh g n.\nProof.\n  intros. unfold nth_sh, nth_gen. simpl. destruct (Nat.eq_dec n to).\n  - subst n. rewrite cvmgil_eq by assumption. simpl. reflexivity.\n  - rewrite cvmgil_not_eq by assumption. reflexivity.\nQed.\n\nLemma lacv_vlabel_new: forall g v to,\n    vlabel (lgraph_add_copied_v g v to) (new_copied_v g to) = vlabel g v.\nProof.\n  intros. simpl. unfold update_copied_new_vlabel, graph_gen.update_vlabel.\n  rewrite if_true; reflexivity.\nQed.\n\nLemma lacv_make_header_new: forall g v to,\n    make_header (lgraph_add_copied_v g v to) (new_copied_v g to) = make_header g v.\nProof. intros. unfold make_header. rewrite lacv_vlabel_new. reflexivity. Qed.\n\nLemma lacv_field2val_make_fields_new: forall g v to,\n    graph_has_v g v -> graph_has_gen g to -> no_dangling_dst g ->\n    map (field2val (lgraph_add_copied_v g v to))\n        (make_fields (lgraph_add_copied_v g v to) (new_copied_v g to)) =\n    map (field2val g) (make_fields g v).\nProof.\n  intros. unfold make_fields. rewrite lacv_vlabel_new.\n  remember (raw_fields (vlabel g v)). remember 0 as n.\n  assert (forall m, In m (map snd (filter_sum_right (make_fields' l v n))) ->\n                    In m (map snd (get_edges g v))). {\n    unfold get_edges, make_fields. subst. intuition. }\n  clear Heql Heqn. revert n H2. induction l; intros; simpl. 1: reflexivity.\n  destruct a; [destruct s|].\n  - simpl in *. rewrite IHl; [reflexivity | assumption].\n  - simpl in *. rewrite IHl; [reflexivity | assumption].\n  - simpl in *. rewrite IHl.\n    + assert (In n (map snd (get_edges g v))) by (apply H2; left; reflexivity).\n      f_equal. rewrite pcv_dst_new by assumption. apply lacv_vertex_address_old.\n      2: assumption. red in H1. apply (H1 v). 1: assumption. apply in_map_iff in H3.\n      destruct H3 as [[x ?] [? ?]]. simpl in H3. subst n0. clear -H4. pose proof H4.\n      unfold get_edges in H4. rewrite <- filter_sum_right_In_iff in H4.\n      unfold make_fields in H4. apply e_in_make_fields' in H4. destruct H4 as [s ?].\n      inversion H0. subst. assumption.\n    + intros. apply H2. right; assumption.\nQed.\n\nLemma lacv_make_fields_vals_new: forall g v to,\n    graph_has_v g v -> graph_has_gen g to -> no_dangling_dst g -> copy_compatible g ->\n    make_fields_vals (lgraph_add_copied_v g v to) (new_copied_v g to) =\n    make_fields_vals g v.\nProof.\n  intros. unfold make_fields_vals. rewrite lacv_vlabel_new.\n  rewrite (lacv_field2val_make_fields_new _ _ _ H H0 H1).\n  destruct (raw_mark (vlabel g v)) eqn:? . 2: reflexivity. f_equal.\n  apply lacv_vertex_address_old. 2: assumption. apply H2; assumption.\nQed.\n\nLemma lacv_graph_has_v_old: forall g v to x,\n    graph_has_gen g to -> graph_has_v g x ->\n    graph_has_v (lgraph_add_copied_v g v to) x.\nProof.\n  intros. destruct H0. split.\n  - rewrite lacv_graph_has_gen; assumption.\n  - red. destruct (Nat.eq_dec (vgeneration x) to).\n    + rewrite e in *. unfold nth_gen. simpl. rewrite cvmgil_eq by assumption.\n      simpl. red in H1. unfold nth_gen in H1. lia.\n    + rewrite lacv_nth_gen; assumption.\nQed.\n\nLemma lacv_graph_has_v_new: forall g v to,\n    graph_has_gen g to -> graph_has_v (lgraph_add_copied_v g v to) (new_copied_v g to).\nProof.\n  intros. split; simpl.\n  - red. simpl. rewrite cvmgil_length; assumption.\n  - red. unfold nth_gen. simpl. rewrite cvmgil_eq by assumption. simpl. lia.\nQed.\n\nLemma lmc_vertex_address: forall g v new_v x,\n    vertex_address (lgraph_mark_copied g v new_v) x = vertex_address g x.\nProof.\n  intros. unfold vertex_address. f_equal.\n  f_equal. unfold vertex_offset. f_equal. unfold previous_vertices_size.\n  apply fold_left_ext. intros. unfold vertex_size_accum. f_equal. unfold vertex_size.\n  f_equal. simpl. unfold update_copied_old_vlabel, graph_gen.update_vlabel.\n  destruct (EquivDec.equiv_dec v (vgeneration x, y)).\n  - unfold Equivalence.equiv in e. rewrite <- e. simpl. reflexivity.\n  - reflexivity.\nQed.\n\nLemma lmc_make_fields: forall (g : LGraph) (old new v: VType),\n    make_fields (lgraph_mark_copied g old new) v = make_fields g v.\nProof.\n  intros. unfold make_fields. simpl. unfold update_copied_old_vlabel, update_vlabel.\n  if_tac; [unfold equiv in H; subst v |]; reflexivity.\nQed.\n\nLemma lmc_field2val_make_fields: forall (g : LGraph) (v new_v x: VType),\n    map (field2val (lgraph_mark_copied g v new_v))\n        (make_fields (lgraph_mark_copied g v new_v) x) =\n    map (field2val g) (make_fields g x).\nProof.\n  intros. rewrite lmc_make_fields. apply map_ext; intros.\n  destruct a; [destruct s|]; simpl; [| |rewrite lmc_vertex_address]; reflexivity.\nQed.\n\nLemma lmc_vlabel_not_eq: forall g v new_v x,\n    x <> v -> vlabel (lgraph_mark_copied g v new_v) x = vlabel g x.\nProof.\n  intros. unfold lgraph_mark_copied, update_copied_old_vlabel, update_vlabel. simpl.\n  rewrite if_false. 1: reflexivity. unfold equiv. intuition.\nQed.\n\nLemma lmc_make_fields_vals_not_eq: forall (g : LGraph) (v new_v : VType) x,\n    x <> v -> make_fields_vals (lgraph_mark_copied g v new_v) x = make_fields_vals g x.\nProof.\n  intros. unfold make_fields_vals.\n  rewrite lmc_field2val_make_fields, lmc_vlabel_not_eq, lmc_vertex_address;\n    [reflexivity | assumption].\nQed.\n\nLemma lmc_make_fields_vals_eq: forall (g : LGraph) (v new_v : VType),\n    make_fields_vals (lgraph_mark_copied g v new_v) v =\n    vertex_address g new_v :: tl (make_fields_vals g v).\nProof.\n  intros. unfold make_fields_vals at 1. simpl.\n  unfold update_copied_old_vlabel, graph_gen.update_vlabel.\n  rewrite if_true by reflexivity. simpl. rewrite lmc_vertex_address.\n  assert (tl (make_fields_vals g v) = tl (map (field2val g) (make_fields g v))) by\n      (unfold make_fields_vals; destruct (raw_mark (vlabel g v)); simpl; reflexivity).\n  rewrite H. clear H. do 2 f_equal. apply lmc_field2val_make_fields.\nQed.\n\nLemma lcv_graph_has_gen: forall g v to x,\n    graph_has_gen g to -> graph_has_gen g x <-> graph_has_gen (lgraph_copy_v g v to) x.\nProof. unfold graph_has_gen. intros. simpl. rewrite cvmgil_length; intuition. Qed.\n\nLemma lmc_graph_has_v: forall g old new x,\n    graph_has_v g x <-> graph_has_v (lgraph_mark_copied g old new) x.\nProof.\n  intros. unfold graph_has_v, graph_has_gen, gen_has_index, nth_gen. reflexivity.\nQed.\n\nLemma lmc_copy_compatible: forall g old new,\n    graph_has_v g new -> vgeneration old <> vgeneration new -> copy_compatible g ->\n    copy_compatible (lgraph_mark_copied g old new).\nProof.\n  repeat intro. destruct (V_EqDec old v).\n  - compute in e. subst old. rewrite <- lmc_graph_has_v. simpl.\n    unfold update_copied_old_vlabel, update_vlabel. rewrite if_true by reflexivity.\n    simpl. split; assumption.\n  - assert (v <> old) by intuition. clear c.\n    rewrite lmc_vlabel_not_eq, <- lmc_graph_has_v in * by assumption.\n    apply H1; assumption.\nQed.\n\nLemma lacv_graph_has_v_inv: forall (g : LGraph) (v : VType) (to : nat) (x : VType),\n    graph_has_gen g to -> graph_has_v (lgraph_add_copied_v g v to) x ->\n    graph_has_v g x \\/ x = new_copied_v g to.\nProof.\n  intros. destruct (V_EqDec x (new_copied_v g to)).\n  - unfold equiv in e; right; assumption.\n  - left. destruct H0. split.\n    + rewrite lacv_graph_has_gen in H0; assumption.\n    + assert (x <> (new_copied_v g to)) by intuition. clear c H0.\n      unfold gen_has_index in *. unfold nth_gen, lgraph_add_copied_v in H1.\n      simpl in H1. destruct x as [gen index]. simpl in *. unfold new_copied_v in H2.\n      destruct (Nat.eq_dec gen to).\n      * subst gen. rewrite cvmgil_eq in H1 by assumption. simpl in H1.\n        change (nth to (g_gen (glabel g)) null_info) with (nth_gen g to) in H1.\n        remember (number_of_vertices (nth_gen g to)).\n        assert (index <> n) by (intro; apply H2; f_equal; assumption). lia.\n      * rewrite cvmgil_not_eq in H1; assumption.\nQed.\n\nLemma lacv_copy_compatible: forall (g : LGraph) (v : VType) (to : nat),\n    raw_mark (vlabel g v) = false -> graph_has_gen g to ->\n    copy_compatible g -> copy_compatible (lgraph_add_copied_v g v to).\nProof.\n  repeat intro. destruct (V_EqDec v0 (new_copied_v g to)).\n  - unfold equiv in e. subst v0. rewrite lacv_vlabel_new in *.\n    rewrite H3 in H. inversion H.\n  - assert (v0 <> (new_copied_v g to)) by intuition. clear c.\n    rewrite lacv_vlabel_old in * by assumption.\n    assert (graph_has_v g v0). {\n      apply lacv_graph_has_v_inv in H2. 2: assumption. destruct H2. 1: assumption.\n      contradiction. } split.\n    + apply lacv_graph_has_v_old; [|apply H1]; assumption.\n    + apply H1; assumption.\nQed.\n\nLemma lcv_copy_compatible: forall g v to,\n    raw_mark (vlabel g v) = false -> graph_has_gen g to ->\n    vgeneration v <> to -> copy_compatible g -> copy_compatible (lgraph_copy_v g v to).\nProof.\n  intros. unfold lgraph_copy_v. apply lmc_copy_compatible. 2: simpl; assumption.\n  - apply lacv_graph_has_v_new. assumption.\n  - apply lacv_copy_compatible; assumption.\nQed.\n\nLemma get_edges_In: forall g v s,\n    In (v, s) (get_edges g v) <-> In s (map snd (get_edges g v)).\nProof.\n  intros. unfold get_edges, make_fields. remember (raw_fields (vlabel g v)).\n  remember 0 as n. clear Heqn Heql. revert n. induction l; intros; simpl.\n  1: reflexivity. destruct a; [destruct s0 |]; simpl; rewrite IHl; try reflexivity.\n  intuition. inversion H0. left; reflexivity.\nQed.\n\nLemma get_edges_fst: forall g v e, In e (get_edges g v) -> fst e = v.\nProof.\n  intros g v e. unfold get_edges, make_fields. remember (raw_fields (vlabel g v)).\n  remember 0 as n. clear Heqn Heql. revert n. induction l; intros; simpl in *.\n  - exfalso; assumption.\n  - destruct a; [destruct s|]; simpl in *;\n      [| | destruct H; [subst e; simpl; reflexivity|]]; apply IHl in H; assumption.\nQed.\n\nLemma lmc_no_dangling_dst: forall g old new,\n    no_dangling_dst g -> no_dangling_dst (lgraph_mark_copied g old new).\nProof.\n  repeat intro. simpl. rewrite <- lmc_graph_has_v in *.\n  unfold get_edges in H1. rewrite lmc_make_fields in H1. apply (H v); assumption.\nQed.\n\nLemma lacv_get_edges_new: forall g v to,\n  map snd (get_edges (lgraph_add_copied_v g v to) (new_copied_v g to)) =\n  map snd (get_edges g v).\nProof.\n  intros. unfold get_edges, make_fields. rewrite lacv_vlabel_new.\n  remember (raw_fields (vlabel g v)). remember 0. clear Heql Heqn. revert n.\n  induction l; intros; simpl. 1: reflexivity.\n  destruct a; [destruct s|]; simpl; rewrite IHl; reflexivity.\nQed.\n\nLemma lacv_no_dangling_dst: forall (g : LGraph) (v : VType) (to : nat),\n    no_dangling_dst g -> graph_has_gen g to -> graph_has_v g v ->\n    no_dangling_dst (lgraph_add_copied_v g v to).\nProof.\n  intros; intro x; intros. simpl. destruct (V_EqDec x (new_copied_v g to)).\n  - unfold equiv in e0. subst x. pose proof H3. remember (new_copied_v g to) as new.\n    apply get_edges_fst in H3. destruct e as [? s]. simpl in H3. subst v0.\n    rewrite get_edges_In, Heqnew, lacv_get_edges_new in H4. rewrite pcv_dst_new.\n    2: assumption. apply lacv_graph_has_v_old. 1: assumption.\n    apply (H v); [|rewrite get_edges_In]; assumption.\n  - assert (x <> new_copied_v g to) by intuition. clear c. rewrite pcv_dst_old.\n    + apply lacv_graph_has_v_old. 1: assumption. apply lacv_graph_has_v_inv in H2.\n      2: assumption. destruct H2. 2: contradiction. apply (H x). 1: assumption.\n      unfold get_edges in *. rewrite lacv_make_fields_not_eq in H3; assumption.\n    + unfold get_edges in H3. rewrite <- filter_sum_right_In_iff in H3.\n      apply e_in_make_fields' in H3. destruct H3 as [s ?]. subst e. simpl. assumption.\nQed.\n\nLemma lcv_no_dangling_dst: forall g v to,\n    no_dangling_dst g -> graph_has_gen g to -> graph_has_v g v ->\n    no_dangling_dst (lgraph_copy_v g v to).\nProof.\n  intros. unfold lgraph_copy_v.\n  apply lmc_no_dangling_dst, lacv_no_dangling_dst; assumption.\nQed.\n\nLemma lmc_outlier_compatible: forall g outlier old new,\n    outlier_compatible g outlier ->\n    outlier_compatible (lgraph_mark_copied g old new) outlier.\nProof.\n  intros. intro v. intros. rewrite <- lmc_graph_has_v in H0.\n  unfold lgraph_mark_copied, update_copied_old_vlabel, update_vlabel; simpl.\n  if_tac; simpl; apply H; [unfold equiv in H1; subst|]; assumption.\nQed.\n\nLemma lacv_outlier_compatible: forall (g : LGraph) outlier (v : VType) (to : nat),\n    graph_has_gen g to -> graph_has_v g v -> outlier_compatible g outlier ->\n    outlier_compatible (lgraph_add_copied_v g v to) outlier.\nProof.\n  intros. intros x ?. apply lacv_graph_has_v_inv in H2. 2: assumption. destruct H2.\n  - rewrite lacv_vlabel_old; [apply H1 | apply graph_has_v_not_eq]; assumption.\n  - subst x. rewrite lacv_vlabel_new. apply H1; assumption.\nQed.\n\nLemma lcv_outlier_compatible: forall g outlier v to,\n    graph_has_gen g to -> graph_has_v g v -> outlier_compatible g outlier ->\n    outlier_compatible (lgraph_copy_v g v to) outlier.\nProof. intros. apply lmc_outlier_compatible, lacv_outlier_compatible; assumption. Qed.\n\nLocal Open Scope Z_scope.\n\nLemma utia_estc: forall g t_info from to index v (H : 0 <= index < MAX_ARGS),\n    enough_space_to_copy g t_info from to ->\n    enough_space_to_copy g (update_thread_info_arg t_info index v H) from to.\nProof.\n  unfold enough_space_to_copy. intros. unfold rest_gen_size, nth_space in *. apply H0.\nQed.\n\nLemma lacv_unmarked_gen_size: forall g v to from,\n    from <> to -> graph_has_gen g to ->\n    unmarked_gen_size g from = unmarked_gen_size (lgraph_add_copied_v g v to) from.\nProof.\n  intros. unfold unmarked_gen_size. rewrite lacv_nth_gen by assumption.\n  remember (nat_inc_list (number_of_vertices (nth_gen g from))) as l.\n  assert (forall i, (from, i) <> new_copied_v g to). {\n    intros. intro. inversion H1. apply H. assumption. }\n  assert (filter (fun i : nat => negb (raw_mark (vlabel g (from, i)))) l =\n          filter (fun i : nat =>\n                    negb(raw_mark(vlabel(lgraph_add_copied_v g v to) (from,i)))) l). {\n    apply filter_ext. intros. rewrite lacv_vlabel_old by apply H1. reflexivity. }\n  rewrite <- H2. apply fold_left_ext. intros. unfold vertex_size_accum. f_equal.\n  unfold vertex_size. rewrite lacv_vlabel_old by apply H1. reflexivity.\nQed.\n\nLemma lacv_estc: forall g t_info from to v,\n    from <> to -> graph_has_gen g to ->\n    enough_space_to_copy g t_info from to ->\n    enough_space_to_copy (lgraph_add_copied_v g v to) t_info from to.\nProof.\n  unfold enough_space_to_copy. intros. rewrite <- lacv_unmarked_gen_size; assumption.\nQed.\n\nLemma vsa_fold_left:\n  forall (g : LGraph) (gen : nat) (l : list nat) (z1 z2 : Z),\n    fold_left (vertex_size_accum g gen) l (z2 + z1) =\n    fold_left (vertex_size_accum g gen) l z2 + z1.\nProof.\n  intros. revert z1 z2. induction l; intros; simpl. 1: reflexivity.\n  rewrite <- IHl. f_equal. unfold vertex_size_accum. lia.\nQed.\n\nLemma lmc_unmarked_gen_size: forall g v v',\n    graph_has_v g v -> raw_mark (vlabel g v) = false ->\n    unmarked_gen_size g (vgeneration v) =\n    unmarked_gen_size (lgraph_mark_copied g v v') (vgeneration v) +\n     vertex_size g v.\nProof.\n  intros. unfold unmarked_gen_size. unfold nth_gen. simpl glabel.\n  destruct v as [gen index]. simpl vgeneration.\n  change (nth gen (g_gen (glabel g)) null_info) with (nth_gen g gen).\n  remember (nat_inc_list (number_of_vertices (nth_gen g gen))).\n  rewrite (fold_left_ext (vertex_size_accum (lgraph_mark_copied g (gen, index) v') gen)\n                         (vertex_size_accum g gen)).\n  - simpl. remember (fun i : nat => negb (raw_mark (vlabel g (gen, i)))) as f1.\n    remember (fun i : nat =>\n                negb (raw_mark (update_copied_old_vlabel g (gen, index) v' (gen, i))))\n      as f2. cut (Permutation (filter f1 l) (index :: filter f2 l)).\n    + intros. rewrite (fold_left_comm _ _ (index :: filter f2 l)). 3: assumption.\n      * simpl. rewrite <- vsa_fold_left. f_equal.\n      * apply vsa_comm.\n    + apply filter_singular_perm; subst.\n      * intros. unfold update_copied_old_vlabel, update_vlabel.\n        rewrite if_false. 1: reflexivity. unfold equiv. intro. apply H2.\n        inversion H3. reflexivity.\n      * rewrite nat_inc_list_In_iff. destruct H. simpl in *. assumption.\n      * unfold update_copied_old_vlabel, update_vlabel. rewrite if_true; reflexivity.\n      * rewrite H0. reflexivity.\n      * apply nat_inc_list_NoDup.\n  - intros. unfold vertex_size_accum. f_equal. unfold vertex_size. f_equal.\n    simpl. unfold update_copied_old_vlabel, update_vlabel. if_tac. 2: reflexivity.\n    simpl. unfold equiv in H2. rewrite H2. reflexivity.\nQed.\n\nLemma cti_rest_gen_size:\n  forall t_info to s\n         (Hi : 0 <= Z.of_nat to < Zlength (spaces (ti_heap t_info)))\n         (Hh : has_space (Znth (Z.of_nat to) (spaces (ti_heap t_info))) s),\n  rest_gen_size t_info to =\n  rest_gen_size (cut_thread_info t_info (Z.of_nat to) s Hi Hh) to + s.\nProof.\n  intros. unfold rest_gen_size. rewrite !nth_space_Znth. unfold cut_thread_info. simpl.\n  rewrite upd_Znth_same by assumption. simpl. lia.\nQed.\n\nLemma lmc_estc:\n  forall (g : LGraph) (t_info : thread_info) (v v': VType) (to : nat)\n         (Hi : 0 <= Z.of_nat to < Zlength (spaces (ti_heap t_info))),\n    enough_space_to_copy g t_info (vgeneration v) to ->\n    graph_has_v g v -> raw_mark (vlabel g v) = false ->\n    forall\n      Hh : has_space (Znth (Z.of_nat to) (spaces (ti_heap t_info))) (vertex_size g v),\n      enough_space_to_copy (lgraph_mark_copied g v v')\n                           (cut_thread_info\n                              t_info (Z.of_nat to) (vertex_size g v) Hi Hh)\n                           (vgeneration v) to.\nProof.\n  unfold enough_space_to_copy. intros.\n  rewrite (lmc_unmarked_gen_size g v v') in H by assumption.\n  rewrite (cti_rest_gen_size _ _ (vertex_size g v) Hi Hh) in H. lia.\nQed.\n\nLemma forward_estc_unchanged: forall\n    g t_info v to\n    (Hi : 0 <= Z.of_nat to < Zlength (spaces (ti_heap t_info)))\n    (Hh : has_space (Znth (Z.of_nat to) (spaces (ti_heap t_info))) (vertex_size g v)),\n    vgeneration v <> to -> graph_has_gen g to ->\n    graph_has_v g v -> raw_mark (vlabel g v) = false ->\n    enough_space_to_copy g t_info (vgeneration v) to ->\n    enough_space_to_copy (lgraph_copy_v g v to)\n         (cut_thread_info t_info (Z.of_nat to) (vertex_size g v) Hi Hh)\n      (vgeneration v) to.\nProof.\n  intros. unfold lgraph_copy_v.\n  apply (lacv_estc _ _ _ _ v) in H3; [| assumption..].\n  assert (vertex_size g v = vertex_size (lgraph_add_copied_v g v to) v). {\n    unfold vertex_size. rewrite lacv_vlabel_old. 1: reflexivity.\n    intro. destruct v as [gen index]. simpl in H. unfold new_copied_v in H4.\n    inversion H4. apply H. assumption. }\n  remember (lgraph_add_copied_v g v to) as g'.\n  pose proof Hh as Hh'. rewrite H4 in Hh'.\n  replace (cut_thread_info t_info (Z.of_nat to) (vertex_size g v) Hi Hh) with\n      (cut_thread_info t_info (Z.of_nat to) (vertex_size g' v) Hi Hh') by\n      (apply cti_eq; symmetry; assumption).\n  apply lmc_estc.\n  - assumption.\n  - subst g'. apply lacv_graph_has_v_old; assumption.\n  - subst g'. rewrite lacv_vlabel_old; [| apply graph_has_v_not_eq]; assumption.\nQed.\n\nLemma forward_estc: forall\n    g t_info v to index uv\n    (Hi : 0 <= Z.of_nat to < Zlength (spaces (ti_heap t_info)))\n    (Hh : has_space (Znth (Z.of_nat to) (spaces (ti_heap t_info))) (vertex_size g v))\n    (Hm : 0 <= index < MAX_ARGS),\n    vgeneration v <> to -> graph_has_gen g to ->\n    graph_has_v g v -> raw_mark (vlabel g v) = false ->\n    enough_space_to_copy g t_info (vgeneration v) to ->\n    enough_space_to_copy\n      (lgraph_copy_v g v to)\n      (update_thread_info_arg\n         (cut_thread_info t_info (Z.of_nat to) (vertex_size g v) Hi Hh) index uv Hm)\n      (vgeneration v) to.\nProof.\n  intros. apply utia_estc. clear index uv Hm.\n  apply forward_estc_unchanged; assumption.\nQed.\n\nLemma lcv_forward_condition: forall\n    g t_info v to index uv\n    (Hi : 0 <= Z.of_nat to < Zlength (spaces (ti_heap t_info)))\n    (Hh : has_space (Znth (Z.of_nat to) (spaces (ti_heap t_info))) (vertex_size g v))\n    (Hm : 0 <= index < MAX_ARGS),\n    vgeneration v <> to -> graph_has_v g v -> raw_mark (vlabel g v) = false ->\n    forward_condition g t_info (vgeneration 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) (vertex_size g v) Hi Hh) index uv Hm)\n      (vgeneration 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 (spaces (ti_heap t_info)))\n    (Hh : has_space (Znth (Z.of_nat to) (spaces (ti_heap t_info))) (vertex_size g v)),\n    vgeneration v <> to -> graph_has_v g v -> raw_mark (vlabel g v) = false ->\n    forward_condition g t_info (vgeneration v) to ->\n    forward_condition (lgraph_copy_v g v to)\n         (cut_thread_info t_info (Z.of_nat to) (vertex_size g v) Hi Hh)\n      (vgeneration 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\nLemma lcv_graph_has_v_new: forall g v to,\n    graph_has_gen g to -> graph_has_v (lgraph_copy_v g v to) (new_copied_v g to).\nProof.\n  intros. unfold lgraph_copy_v. rewrite <- lmc_graph_has_v.\n  apply lacv_graph_has_v_new. assumption.\nQed.\n\nLemma lcv_graph_has_v_old: forall g v to x,\n    graph_has_gen g to -> graph_has_v g x -> graph_has_v (lgraph_copy_v g v to) x.\nProof.\n  intros. unfold lgraph_copy_v. rewrite <- lmc_graph_has_v.\n  apply lacv_graph_has_v_old; assumption.\nQed.\n\nLemma lcv_rgc_unchanged: forall g roots v to,\n    graph_has_gen g to ->\n    roots_graph_compatible roots g ->\n    roots_graph_compatible roots (lgraph_copy_v g v to).\nProof.\n  intros. red in H0 |-*. rewrite Forall_forall in *. intros.\n  apply lcv_graph_has_v_old; [|apply H0]; assumption.\nQed.\n\nLemma lcv_roots_compatible_unchanged: forall g roots outlier v to,\n    graph_has_gen g to ->\n    roots_compatible g outlier roots ->\n    roots_compatible (lgraph_copy_v g v to) outlier roots.\nProof. intros. destruct H0. split; [|apply lcv_rgc_unchanged]; assumption. Qed.\n\nLemma lcv_roots_graph_compatible: forall g roots v to f_info z,\n    graph_has_gen g to ->\n    roots_graph_compatible roots g ->\n    roots_graph_compatible (upd_bunch z f_info roots (inr (new_copied_v g to)))\n                           (lgraph_copy_v g v to).\nProof.\n  intros. apply upd_bunch_graph_compatible.\n  - apply lcv_rgc_unchanged; assumption.\n  - unfold lgraph_copy_v; rewrite <- lmc_graph_has_v;\n      apply lacv_graph_has_v_new; assumption.\nQed.\n\nLemma lcv_roots_compatible: forall g roots outlier v to f_info z,\n    graph_has_gen g to ->\n    roots_compatible g outlier roots ->\n    roots_compatible (lgraph_copy_v g v to) outlier\n                     (upd_bunch z f_info roots (inr (new_copied_v g to))).\nProof.\n  intros. destruct H0. split.\n  - apply upd_roots_outlier_compatible; assumption.\n  - apply lcv_roots_graph_compatible; assumption.\nQed.\n\nLemma lcv_vertex_address: forall g v to x,\n    graph_has_gen g to -> closure_has_v g x ->\n    vertex_address (lgraph_copy_v g v to) x = vertex_address g x.\nProof.\n  intros. unfold lgraph_copy_v.\n  rewrite lmc_vertex_address, lacv_vertex_address; [reflexivity | assumption..].\nQed.\n\nLemma lcv_vertex_address_new: forall g v to,\n    graph_has_gen g to ->\n    vertex_address (lgraph_copy_v g v to) (new_copied_v g to) =\n    vertex_address g (new_copied_v g to).\nProof.\n  intros.\n  apply lcv_vertex_address;  [| red; simpl; split]; [assumption..| apply Nat.le_refl].\nQed.\n\nLemma lcv_vertex_address_old: forall g v to x,\n    graph_has_gen g to -> graph_has_v g x ->\n    vertex_address (lgraph_copy_v g v to) x = vertex_address g x.\nProof.\n  intros. apply lcv_vertex_address; [|apply graph_has_v_in_closure]; assumption.\nQed.\n\nLemma lcv_fun_thread_arg_compatible_unchanged: forall\n    g t_info f_info roots v to i s\n    (Hi : 0 <= i < Zlength (spaces (ti_heap t_info)))\n    (Hh : has_space (Znth i (spaces (ti_heap t_info))) s),\n    graph_has_gen g to ->\n    roots_graph_compatible roots g ->\n    fun_thread_arg_compatible g t_info f_info roots ->\n    fun_thread_arg_compatible (lgraph_copy_v g v to)\n         (cut_thread_info t_info i s Hi Hh) f_info roots.\nProof.\n  intros.\n  unfold fun_thread_arg_compatible in *. simpl. rewrite <- H1. apply map_ext_in.\n  intros. destruct a; [destruct s0|]; [reflexivity..| simpl].\n  apply lcv_vertex_address_old. 1: assumption. red in H0. rewrite Forall_forall in H0.\n  apply H0. rewrite <- filter_sum_right_In_iff. assumption.\nQed.\n\nLemma lcv_fun_thread_arg_compatible: forall\n    g t_info f_info roots z v to i s\n    (Hi : 0 <= i < Zlength (spaces (ti_heap t_info)))\n    (Hh : has_space (Znth i (spaces (ti_heap t_info))) s)\n    (Hm : 0 <= Znth z (live_roots_indices f_info) < MAX_ARGS),\n    graph_has_gen g to -> roots_graph_compatible roots g ->\n    fun_thread_arg_compatible g t_info f_info roots ->\n    fun_thread_arg_compatible\n      (lgraph_copy_v g v to)\n      (update_thread_info_arg\n         (cut_thread_info t_info i s Hi Hh) (Znth z (live_roots_indices f_info))\n         (vertex_address g (new_copied_v g to)) Hm)\n      f_info (upd_bunch z f_info roots (inr (new_copied_v g to))).\nProof.\n  intros. rewrite <- (lcv_vertex_address_new g v to H).\n  apply upd_fun_thread_arg_compatible with (HB := Hm).\n    apply lcv_fun_thread_arg_compatible_unchanged; assumption.\nQed.\n\nLemma upd_Znth_unchanged: forall {A : Type} {d : Inhabitant A} (i : Z) (l : list A),\n    0 <= i < Zlength l -> upd_Znth i l (Znth i l) = l.\nProof.\n  intros. assert (Zlength (upd_Znth i l (Znth i l)) = Zlength l) by\n      (rewrite upd_Znth_Zlength; [reflexivity | assumption]). rewrite Znth_list_eq.\n  split. 1: assumption. intros. rewrite H0 in H1. destruct (Z.eq_dec j i).\n  - subst j. rewrite upd_Znth_same; [reflexivity | assumption].\n  - rewrite upd_Znth_diff; [reflexivity | assumption..].\nQed.\n\n#[export] Instance share_inhabitant: Inhabitant share := emptyshare.\n\nLemma lcv_nth_gen: forall g v to n,\n    n <> to -> graph_has_gen g to -> nth_gen (lgraph_copy_v g v to) n = nth_gen g n.\nProof.\n  intros. unfold lgraph_copy_v, nth_gen. simpl.\n  rewrite cvmgil_not_eq; [reflexivity | assumption..].\nQed.\n\nLemma lcv_vertex_size_new: forall (g : LGraph) (v : VType) (to : nat),\n    vertex_size (lgraph_copy_v g v to) (new_copied_v g to) = vertex_size g v.\nProof.\n  intros. unfold vertex_size, lgraph_copy_v. simpl.\n  unfold update_copied_old_vlabel, update_vlabel. if_tac.\n  - simpl. unfold update_copied_new_vlabel, update_vlabel. if_tac; reflexivity.\n  - rewrite lacv_vlabel_new. reflexivity.\nQed.\n\nLemma lcv_vertex_size_old: forall (g : LGraph) (v : VType) (to : nat) x,\n        graph_has_gen g to -> graph_has_v g x ->\n        vertex_size (lgraph_copy_v g v to) x = vertex_size g x.\nProof.\n  intros. unfold vertex_size, lgraph_copy_v. simpl.\n  unfold update_copied_old_vlabel, update_vlabel. if_tac.\n  - simpl. unfold update_copied_new_vlabel, update_vlabel. unfold equiv in H1. subst.\n    if_tac; reflexivity.\n  - rewrite lacv_vlabel_old. 1: reflexivity. apply graph_has_v_not_eq. assumption.\nQed.\n\nLemma lcv_pvs_same: forall g v to,\n    graph_has_gen g to ->\n    previous_vertices_size (lgraph_copy_v g v to) to\n                           (number_of_vertices (nth_gen (lgraph_copy_v g v to) to)) =\n    previous_vertices_size g to (number_of_vertices (nth_gen g to)) + vertex_size g v.\nProof.\n  intros. unfold nth_gen. simpl. rewrite cvmgil_eq by assumption. simpl.\n  remember (number_of_vertices (nth to (g_gen (glabel g)) null_info)).\n  replace (n + 1)%nat with (S n) by lia. rewrite pvs_S. f_equal.\n  - unfold previous_vertices_size. apply fold_left_ext. intros.\n    unfold vertex_size_accum. f_equal. apply lcv_vertex_size_old. 1: assumption.\n    rewrite nat_inc_list_In_iff in H0; subst; split; simpl; assumption.\n  - assert ((to, n) = new_copied_v g to) by\n        (unfold new_copied_v, nth_gen; subst n; reflexivity). rewrite H0.\n    apply lcv_vertex_size_new.\nQed.\n\nLemma lcv_pvs_old: forall g v to gen,\n    gen <> to -> graph_has_gen g to -> graph_has_gen g gen ->\n    previous_vertices_size (lgraph_copy_v g v to) gen\n                           (number_of_vertices (nth_gen (lgraph_copy_v g v to) gen)) =\n    previous_vertices_size g gen (number_of_vertices (nth_gen g gen)).\nProof.\n  intros. unfold nth_gen. simpl. rewrite cvmgil_not_eq by assumption.\n  remember (number_of_vertices (nth gen (g_gen (glabel g)) null_info)).\n  unfold previous_vertices_size. apply fold_left_ext. intros.\n  unfold vertex_size_accum. f_equal. apply lcv_vertex_size_old. 1: assumption.\n  rewrite nat_inc_list_In_iff in H2. subst. split; simpl; assumption.\nQed.\n\nLemma lcv_graph_thread_info_compatible: forall\n    g t_info v to\n    (Hi : 0 <= Z.of_nat to < Zlength (spaces (ti_heap t_info)))\n    (Hh : has_space (Znth (Z.of_nat to) (spaces (ti_heap t_info))) (vertex_size g v)),\n    graph_has_gen g to ->\n    graph_thread_info_compatible g t_info ->\n    graph_thread_info_compatible (lgraph_copy_v g v to)\n      (cut_thread_info t_info (Z.of_nat to) (vertex_size g v)\n                       Hi Hh).\nProof.\n  unfold graph_thread_info_compatible. intros. destruct H0 as [? [? ?]].\n  assert (map space_start (spaces (ti_heap t_info)) =\n          map space_start\n              (upd_Znth (Z.of_nat to) (spaces (ti_heap t_info))\n                        (cut_space\n                           (Znth (Z.of_nat to) (spaces (ti_heap t_info)))\n                           (vertex_size g v) Hh))). {\n    rewrite <- upd_Znth_map. simpl. rewrite <- Znth_map by assumption.\n    rewrite upd_Znth_unchanged; [reflexivity | rewrite Zlength_map; assumption]. }\n  split; [|split]; [|simpl; rewrite cvmgil_length by assumption..].\n  - rewrite gsc_iff in *; simpl. 2: assumption.\n    + intros. unfold nth_space. simpl.\n      rewrite <- lcv_graph_has_gen in H4 by assumption. specialize (H0 _ H4).\n      simpl in H0. destruct H0 as [? [? ?]]. split; [|split].\n      * clear -H0 H3 H. rewrite <- map_nth, <- H3, map_nth. clear H3.\n        unfold nth_gen, nth_space in *. simpl. destruct (Nat.eq_dec gen to).\n        -- subst gen. rewrite cvmgil_eq; simpl; assumption.\n        -- rewrite cvmgil_not_eq; assumption.\n      * assert (map space_sh\n                    (upd_Znth (Z.of_nat to) (spaces (ti_heap t_info))\n                              (cut_space\n                                 (Znth (Z.of_nat to) (spaces (ti_heap t_info)))\n                                 (vertex_size g v) Hh)) =\n                map space_sh (spaces (ti_heap t_info))). {\n          rewrite <- upd_Znth_map. simpl. rewrite <- Znth_map by assumption.\n          rewrite upd_Znth_unchanged; [reflexivity|rewrite Zlength_map; assumption]. }\n        rewrite <- map_nth, H7, map_nth. clear -H5 H. unfold nth_gen, nth_space in *.\n        simpl. destruct (Nat.eq_dec gen to).\n        -- subst gen. rewrite cvmgil_eq; simpl; assumption.\n        -- rewrite cvmgil_not_eq; assumption.\n      * assert (0 <= Z.of_nat gen < Zlength (spaces (ti_heap t_info))). {\n          split. 1: apply Nat2Z.is_nonneg. rewrite Zlength_correct.\n          apply inj_lt. red in H4. lia. }\n        rewrite <- (Nat2Z.id gen) at 3. rewrite nth_Znth.\n        2: rewrite upd_Znth_Zlength; assumption. destruct (Nat.eq_dec gen to).\n        -- subst gen. rewrite upd_Znth_same by assumption. simpl.\n           rewrite lcv_pvs_same by assumption.\n           rewrite H6, nth_space_Znth. reflexivity.\n        -- assert (Z.of_nat gen <> Z.of_nat to) by\n              (intro; apply n, Nat2Z.inj; assumption).\n           rewrite upd_Znth_diff, <- nth_space_Znth, lcv_pvs_old; assumption.\n    + rewrite cvmgil_length, <- !ZtoNat_Zlength, upd_Znth_Zlength, !ZtoNat_Zlength;\n        assumption.\n  - intros. rewrite <- H3. assumption.\n  - rewrite <- !ZtoNat_Zlength, upd_Znth_Zlength, !ZtoNat_Zlength; assumption.\nQed.\n\nLemma lcv_super_compatible_unchanged: forall\n    g t_info roots f_info outlier to v\n    (Hi : 0 <= Z.of_nat to < Zlength (spaces (ti_heap t_info)))\n    (Hh : has_space (Znth (Z.of_nat to) (spaces (ti_heap t_info))) (vertex_size g v)),\n    graph_has_gen g to -> graph_has_v g v ->\n    super_compatible (g, t_info, roots) f_info outlier ->\n    super_compatible\n      (lgraph_copy_v g v to,\n       (cut_thread_info t_info (Z.of_nat to) (vertex_size g v) Hi Hh),\n       roots) f_info outlier.\nProof.\n  intros. destruct H1 as [? [? [? ?]]]. split; [|split; [|split]].\n  - apply lcv_graph_thread_info_compatible; assumption.\n  - destruct H3. apply lcv_fun_thread_arg_compatible_unchanged; assumption.\n  - apply lcv_roots_compatible_unchanged; assumption.\n  - apply lcv_outlier_compatible; assumption.\nQed.\n\nLemma lcv_super_compatible: forall\n    g t_info roots f_info outlier to v z\n    (Hi : 0 <= Z.of_nat to < Zlength (spaces (ti_heap t_info)))\n    (Hh : has_space (Znth (Z.of_nat to) (spaces (ti_heap t_info))) (vertex_size g v))\n    (Hm : 0 <= Znth z (live_roots_indices f_info) < MAX_ARGS),\n    graph_has_gen g to -> graph_has_v g v ->\n    super_compatible (g, t_info, roots) f_info outlier ->\n    super_compatible\n      (lgraph_copy_v g v to,\n       update_thread_info_arg\n         (cut_thread_info t_info (Z.of_nat to) (vertex_size g v) Hi Hh)\n         (Znth z (live_roots_indices f_info))\n         (vertex_address g (new_copied_v g to)) Hm,\n       upd_bunch z f_info roots (inr (new_copied_v g to))) f_info outlier.\nProof.\n  intros. destruct H1 as [? [? [? ?]]]. split; [|split; [|split]].\n  - apply lcv_graph_thread_info_compatible; assumption.\n  - destruct H3. apply lcv_fun_thread_arg_compatible; assumption.\n  - apply lcv_roots_compatible; assumption.\n  - apply lcv_outlier_compatible; assumption.\nQed.\n\nLemma lmc_gen_start: forall g old new n,\n    gen_start (lgraph_mark_copied g old new) n = gen_start g n.\nProof.\n  intros. unfold gen_start. do 2 if_tac.\n  - unfold nth_gen. simpl. reflexivity.\n  - unfold graph_has_gen in *. simpl in *. contradiction.\n  - unfold graph_has_gen in *. simpl in *. contradiction.\n  - reflexivity.\nQed.\n\nLemma lcv_gen_start: forall g v to n,\n    graph_has_gen g to -> gen_start (lgraph_copy_v g v to) n = gen_start g n.\nProof.\n  intros. unfold lgraph_copy_v.\n  rewrite lmc_gen_start, lacv_gen_start; [reflexivity | assumption].\nQed.\n\nLemma utia_ti_heap: forall t_info i ad (Hm : 0 <= i < MAX_ARGS),\n    ti_heap (update_thread_info_arg t_info i ad Hm) = ti_heap t_info.\nProof. intros. simpl. reflexivity. Qed.\n\nLemma cti_space_not_eq: forall t_info i s n\n    (Hi : 0 <= i < Zlength (spaces (ti_heap t_info)))\n    (Hh : has_space (Znth i (spaces (ti_heap t_info))) s),\n    (Z.of_nat n) <> i ->\n    nth_space (cut_thread_info t_info i s Hi Hh) n = nth_space t_info n.\nProof.\n  intros. rewrite !nth_space_Znth. simpl.\n  pose proof (Nat2Z.is_nonneg n). remember (Z.of_nat n). clear Heqz.\n  remember (spaces (ti_heap t_info)). destruct (Z_lt_le_dec z (Zlength l)).\n  - assert (0 <= z < Zlength l) by lia.\n    rewrite upd_Znth_diff; [reflexivity |assumption..].\n  - rewrite !Znth_overflow;\n      [reflexivity | | rewrite upd_Znth_Zlength by assumption]; lia.\nQed.\n\nLemma cti_space_eq: forall t_info i s\n    (Hi : 0 <= Z.of_nat i < Zlength (spaces (ti_heap t_info)))\n    (Hh : has_space (Znth (Z.of_nat i) (spaces (ti_heap t_info))) s),\n    nth_space (cut_thread_info t_info (Z.of_nat i) s Hi Hh) i =\n    cut_space (Znth (Z.of_nat i) (spaces (ti_heap t_info))) s Hh.\nProof.\n  intros. rewrite nth_space_Znth. simpl. rewrite upd_Znth_same by assumption.\n  reflexivity.\nQed.\n\nLemma cti_gen_size: forall t_info i s n\n    (Hi : 0 <= i < Zlength (spaces (ti_heap t_info)))\n    (Hh : has_space (Znth i (spaces (ti_heap t_info))) s),\n    gen_size (cut_thread_info t_info i s Hi Hh) n =\n    gen_size t_info n.\nProof.\n  intros. unfold gen_size. destruct (Z.eq_dec (Z.of_nat n) i).\n  - subst i. rewrite cti_space_eq. simpl. rewrite nth_space_Znth. reflexivity.\n  - rewrite cti_space_not_eq; [reflexivity | assumption].\nQed.\n\nLemma cti_space_start: forall t_info i s  n\n    (Hi : 0 <= i < Zlength (spaces (ti_heap t_info)))\n    (Hh : has_space (Znth i (spaces (ti_heap t_info))) s),\n    space_start (nth_space (cut_thread_info t_info i s Hi Hh) n) =\n    space_start (nth_space t_info n).\nProof.\n  intros. destruct (Z.eq_dec (Z.of_nat n) i).\n  - subst i. rewrite cti_space_eq. simpl. rewrite nth_space_Znth. reflexivity.\n  - rewrite cti_space_not_eq; [reflexivity | assumption].\nQed.\n\nLemma utiacti_gen_size: forall t_info i1 i2 s ad n\n    (Hi : 0 <= i1 < Zlength (spaces (ti_heap t_info)))\n    (Hh : has_space (Znth i1 (spaces (ti_heap t_info))) s)\n    (Hm : 0 <= i2 < MAX_ARGS),\n    gen_size (update_thread_info_arg (cut_thread_info t_info i1 s Hi Hh) i2 ad Hm) n =\n    gen_size t_info n.\nProof.\n  intros. unfold gen_size, nth_space. rewrite utia_ti_heap. apply cti_gen_size.\nQed.\n\nLemma utiacti_space_start: forall t_info i1 i2 s ad n\n    (Hi : 0 <= i1 < Zlength (spaces (ti_heap t_info)))\n    (Hh : has_space (Znth i1 (spaces (ti_heap t_info))) s)\n    (Hm : 0 <= i2 < MAX_ARGS),\n    space_start\n      (nth_space (update_thread_info_arg (cut_thread_info t_info i1 s Hi Hh) i2 ad Hm)\n                 n) = space_start (nth_space t_info n).\nProof. intros. unfold nth_space. rewrite utia_ti_heap. apply cti_space_start. Qed.\n\nDefinition thread_info_relation t t':=\n  ti_heap_p t = ti_heap_p t' /\\ (forall n, gen_size t n = gen_size t' n) /\\\n  forall n, space_start (nth_space t n) = space_start (nth_space t' n).\n\nLemma tir_id: forall t, thread_info_relation t t.\nProof. intros. red. split; [|split]; reflexivity. Qed.\n\nLemma upd_Znth_diff_strong : forall {A}{d: Inhabitant A} i j l (u : A),\n    0 <= j < Zlength l -> i <> j ->\n  Znth i (upd_Znth j l u) = Znth i l.\nProof.\n  intros.\n  destruct (zlt i 0).\n  { rewrite !Znth_underflow; auto. }\n  destruct (zlt i (Zlength l)).\n  apply upd_Znth_diff; auto; lia.\n  { rewrite !Znth_overflow; auto.\n    rewrite upd_Znth_Zlength; auto. }\nQed.\n\nLemma lgd_graph_has_v: forall g e v v',\n    graph_has_v g v <-> graph_has_v (labeledgraph_gen_dst g e v') v.\nProof. reflexivity. Qed.\n\nLemma lgd_graph_has_gen: forall g e v x,\n    graph_has_gen (labeledgraph_gen_dst g e v) x <-> graph_has_gen g x.\nProof. intros; unfold graph_has_gen; intuition. Qed.\n\nLemma lgd_raw_fld_length_eq: forall (g: LGraph) v e v',\n    Zlength (raw_fields (vlabel g v)) =\n    Zlength (raw_fields (vlabel (labeledgraph_gen_dst g e v') v)).\nProof. reflexivity. Qed.\n\nLemma lgd_vertex_address_eq: forall g e v' x,\n    vertex_address (labeledgraph_gen_dst g e v') x = vertex_address g x.\nProof. reflexivity. Qed.\n\nLemma lgd_make_fields_eq: forall (g : LGraph) (v v': VType) e,\n    make_fields (labeledgraph_gen_dst g e v') v = make_fields g v.\nProof. reflexivity. Qed.\n\nLemma lgd_make_header_eq: forall g e v' x,\n    make_header g x = make_header (labeledgraph_gen_dst g e v') x.\nProof. reflexivity. Qed.\n\nLemma lgd_raw_mark_eq: forall (g: LGraph) e (v v' : VType),\n    raw_mark (vlabel g v) = raw_mark (vlabel (labeledgraph_gen_dst g e v') v).\nProof. reflexivity. Qed.\n\nLemma lgd_dst_old: forall (g: LGraph) e v e',\n    e <> e' -> dst (labeledgraph_gen_dst g e v) e' = dst g e'.\nProof.\n  intros. simpl. unfold updateEdgeFunc. rewrite if_false. 1: reflexivity. auto.\nQed.\n\nLemma lgd_dst_new: forall (g: LGraph) e v,\n    dst (labeledgraph_gen_dst g e v) e = v.\nProof. intros. simpl. unfold updateEdgeFunc. rewrite if_true; reflexivity. Qed.\n\nLemma lgd_f2v_eq_except_one: forall g fd e v',\n    fd <> (inr e) ->\n    field2val g fd = field2val (labeledgraph_gen_dst g e v') fd.\nProof.\n  intros; unfold field2val; simpl.\n  destruct fd; [destruct s|]; try reflexivity.\n  unfold updateEdgeFunc; if_tac; [exfalso; apply H; rewrite H0|]; reflexivity.\nQed.\n\nLemma lgd_map_f2v_diff_vert_eq: forall g v v' v1 e n,\n    0 <= n < Zlength (make_fields g v) ->\n    Znth n (make_fields g v) = inr e ->\n    v1 <> v ->\n    map (field2val g) (make_fields g v1) =\n    map (field2val (labeledgraph_gen_dst g e v'))\n        (make_fields (labeledgraph_gen_dst g e v') v1).\nProof.\n    intros.\n    rewrite lgd_make_fields_eq.\n    apply Znth_list_eq. split.\n    1: repeat rewrite Zlength_map; reflexivity.\n    intros. rewrite Zlength_map in H2.\n    repeat rewrite Znth_map by assumption.\n    apply lgd_f2v_eq_except_one. intro.\n    pose proof (make_fields_edge_unique g e v\n                                        v1 n j H H2 H0 H3).\n    destruct H4. unfold not in H1. symmetry in H5.\n    apply (H1 H5).\nQed.\n\nLemma lgd_f2v_eq_after_update: forall g v v' e n j,\n  0 <= n < Zlength (make_fields g v) ->\n  0 <= j < Zlength (make_fields g v) ->\n  Znth n (make_fields g v) = inr e ->\n  Znth j (upd_Znth n (map (field2val g)\n                          (make_fields g v)) (vertex_address g v')) =\n  Znth j\n    (map (field2val (labeledgraph_gen_dst g e v'))\n         (make_fields (labeledgraph_gen_dst g e v') v)).\nProof.\n  intros.\n  rewrite Znth_map.\n  2: rewrite lgd_make_fields_eq; assumption.\n  assert (j = n \\/ j <> n) by lia; destruct H2.\n  + subst j; rewrite upd_Znth_same.\n    2: rewrite Zlength_map; assumption.\n    replace (make_fields (labeledgraph_gen_dst g e v') v)\n      with (make_fields g v) by reflexivity.\n    rewrite H1; simpl field2val.\n    unfold updateEdgeFunc; if_tac; try reflexivity.\n    unfold complement in H2; assert (e = e) by reflexivity.\n    apply H2 in H3; exfalso; assumption.\n  + rewrite upd_Znth_diff_strong; [|rewrite Zlength_map|]; try assumption.\n    rewrite Znth_map by assumption.\n    apply (lgd_f2v_eq_except_one g (Znth j (make_fields g v))).\n    intro. pose proof (make_fields_edge_unique g e v v n j H H0 H1 H3).\n    lia.\nQed.\n\nLemma lgd_mfv_change_in_one_spot: forall g v e v' n,\n    0 <= n < Zlength (make_fields g v) ->\n    raw_mark (vlabel g v) = false ->\n    Znth n (make_fields g v) = inr e ->\n    upd_Znth n (make_fields_vals g v) (vertex_address g v') =\n    (make_fields_vals (labeledgraph_gen_dst g e v') v).\nProof.\n  intros.\n  rewrite (Znth_list_eq (upd_Znth n (make_fields_vals g v)\n               (vertex_address g v')) (make_fields_vals\n                     (labeledgraph_gen_dst g e v') v)).\n  rewrite upd_Znth_Zlength, fields_eq_length.\n  2: rewrite fields_eq_length; rewrite make_fields_eq_length in H; assumption.\n  split. 1: rewrite fields_eq_length; reflexivity.\n  intros.\n  unfold make_fields_vals.\n  replace (raw_mark (vlabel (labeledgraph_gen_dst g e v') v))\n    with (raw_mark (vlabel g v)) by reflexivity.\n  rewrite H0; rewrite <- make_fields_eq_length in H2.\n  apply lgd_f2v_eq_after_update; assumption.\nQed.\n\nLemma lgd_no_dangling_dst: forall g e v',\n    graph_has_v g v' ->\n    no_dangling_dst g ->\n     no_dangling_dst (labeledgraph_gen_dst g e v').\nProof.\n  intros. unfold no_dangling_dst in *.\n  intros. rewrite <- lgd_graph_has_v.\n  simpl. unfold updateEdgeFunc; if_tac; [assumption | apply (H0 v)]; assumption.\nQed.\n\nLemma lgd_no_dangling_dst_copied_vert: forall g e v,\n    copy_compatible g ->\n    graph_has_v g v ->\n    raw_mark (vlabel g v) = true ->\n    no_dangling_dst g ->\n    no_dangling_dst (labeledgraph_gen_dst g e (copied_vertex (vlabel g v))).\nProof.\n  intros.\n  assert (graph_has_v g (copied_vertex (vlabel g v))) by apply (H v H0 H1).\n  apply lgd_no_dangling_dst; assumption.\nQed.\n\nLemma lgd_enough_space_to_copy: forall g e v' t_info gen sp,\n    enough_space_to_copy g t_info gen sp ->\n    enough_space_to_copy (labeledgraph_gen_dst g e v') t_info gen sp.\nProof.\n  intros. unfold enough_space_to_copy in *. intuition. Qed.\n\nLemma lgd_copy_compatible: forall g v' e,\n    copy_compatible g ->\n    copy_compatible (labeledgraph_gen_dst g e v').\nProof.\n  intros. unfold copy_compatible in *. intuition. Qed.\n\nLemma lgd_forward_condition: forall g t_info v to v' e,\n    vgeneration v <> to ->\n    graph_has_v g v ->\n    graph_has_v g v' ->\n    forward_condition g t_info (vgeneration v) to ->\n    forward_condition (labeledgraph_gen_dst g e v') t_info (vgeneration 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\nLemma lgd_rgc: forall g roots e v,\n    roots_graph_compatible roots g ->\n    roots_graph_compatible roots (labeledgraph_gen_dst g e v).\nProof.\n  intros. red in H |-*. rewrite Forall_forall in *. intros.\n  rewrite <- lgd_graph_has_v. apply H. assumption.\nQed.\n\nLemma lgd_roots_compatible: forall g outlier roots e v,\n    roots_compatible g outlier roots ->\n    roots_compatible (labeledgraph_gen_dst g e v) outlier roots.\nProof. intros. destruct H. split; [|apply lgd_rgc]; assumption. Qed.\n\nLemma lgd_graph_thread_info_compatible:\n  forall (g : LGraph) (t_info : thread_info) e (v' : VType),\n  graph_thread_info_compatible g t_info ->\n  graph_thread_info_compatible (labeledgraph_gen_dst g e v') t_info.\nProof.\n  intros; destruct H; split; assumption. Qed.\n\nLemma lgd_fun_thread_arg_compatible:\n  forall (g : LGraph) (t_info : thread_info) e (v' : VType) f_info roots,\n    fun_thread_arg_compatible g t_info f_info roots ->\n    fun_thread_arg_compatible (labeledgraph_gen_dst g e v') t_info f_info roots.\nProof.\n  intros. unfold fun_thread_arg_compatible in *.\n  rewrite <- H. apply map_ext_in. intros. destruct a; [destruct s|]; reflexivity.\nQed.\n\nLemma lgd_outlier_compatible:\n  forall (g : LGraph) (t_info : thread_info) e (v' : VType) outlier,\n    outlier_compatible g outlier ->\n    outlier_compatible (labeledgraph_gen_dst g e v') outlier.\nProof.\n  intros. intro v. intros.\n  rewrite <- lgd_graph_has_v in H0.\n  unfold labeledgraph_gen_dst, pregraph_gen_dst, updateEdgeFunc; simpl.\n  apply (H v H0).\nQed.\n\nLemma lgd_super_compatible: forall g t_info roots f_info outlier v' e,\n    super_compatible (g, t_info, roots) f_info outlier ->\n    super_compatible ((labeledgraph_gen_dst g e v'), t_info, roots) f_info outlier.\nProof.\n  intros. destruct H as [? [? [? ?]]]. split; [|split; [|split]].\n  - apply lgd_graph_thread_info_compatible; assumption.\n  - destruct H1. apply lgd_fun_thread_arg_compatible; assumption.\n  - apply lgd_roots_compatible; assumption.\n  - apply lgd_outlier_compatible; assumption.\nQed.\n\nLemma fr_general_prop_bootstrap: forall depth from to p g g'\n                                        (P: nat -> LGraph -> LGraph -> 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    graph_has_gen g to -> forward_relation from to depth p g g' ->\n    forall x, graph_has_gen g x <-> graph_has_gen g' x.\nProof.\n  intros. remember (fun to g1 g2 =>\n                      graph_has_gen g1 to ->\n                      forall x, graph_has_gen g1 x <-> graph_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 fl_graph_has_gen: forall from to depth l g g',\n    graph_has_gen g to -> forward_loop from to depth l g g' ->\n    forall x, graph_has_gen g x <-> graph_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, graph_has_gen g y <-> graph_has_gen g2 y) by\n      (intros; apply (fr_graph_has_gen _ _ _ _ _ _ H H4)).\n  transitivity (graph_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: LGraph -> A -> nat -> Prop)\n         (P: LGraph -> LGraph -> A -> Prop) (R: nat -> nat -> Prop),\n    R from to -> graph_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        graph_has_gen g to -> Q g x from -> (vlabel g v).(raw_mark) = false ->\n        R from to -> vgeneration v = from -> P g (lgraph_copy_v g v to) x) ->\n    (forall depth from to p g g',\n        graph_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, graph_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 (vgeneration 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 (vgeneration (dst g e))); [assumption.. | reflexivity].\n  - assert (forall l from to g1 g2,\n               graph_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 (graph_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 (vgeneration 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 (graph_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 (vgeneration (dst g e))); [assumption.. | reflexivity].\nQed.\n\nLemma fr_gen_start: forall depth from to p g g',\n    graph_has_gen g to -> forward_relation from to depth p g g' ->\n    forall x, gen_start g x = gen_start g' x.\nProof.\n  intros. remember (fun (g: LGraph) (v: nat) (x: nat) => True) as Q.\n  remember (fun g1 g2 x => gen_start g1 x = gen_start 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    graph_has_gen g to -> forward_loop from to depth l g g' ->\n    forall x, gen_start g x = gen_start g' x.\nProof.\n  intros. revert g g' H H0 x. induction l; intros; inversion H0. 1: reflexivity.\n  subst. transitivity (gen_start g2 x).\n  - apply (fr_gen_start _ _ _ _ _ _ H H4).\n  - assert (graph_has_gen g2 to) by\n        (rewrite <- (fr_graph_has_gen _ _ _ _ _ _ H H4); assumption).\n    apply IHl; assumption.\nQed.\n\nLemma lcv_closure_has_v: forall g v to x,\n    graph_has_gen g to -> closure_has_v g x -> closure_has_v (lgraph_copy_v g v to) x.\nProof.\n  intros. unfold closure_has_v in *. destruct x as [gen index]. simpl in *.\n  destruct H0. split. 1: rewrite <- lcv_graph_has_gen; assumption.\n  destruct (Nat.eq_dec gen to).\n  - subst gen. red. unfold nth_gen. simpl. rewrite cvmgil_eq by assumption.\n    simpl. red in H1. unfold nth_gen in H1. lia.\n  - red. rewrite lcv_nth_gen; assumption.\nQed.\n\nLemma fr_closure_has_v: forall depth from to p g g',\n    graph_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: LGraph) (v: VType) (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\nLemma fr_graph_has_v: forall depth from to p g g',\n    graph_has_gen g to -> forward_relation from to depth p g g' ->\n    forall v, graph_has_v g v -> graph_has_v g' v.\nProof.\n  intros. remember (fun (g: LGraph) (v: VType) (x: nat) => True) as Q.\n  remember (fun g1 g2 v => graph_has_v g1 v -> graph_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  - unfold lgraph_copy_v. rewrite <- lmc_graph_has_v.\n    apply lacv_graph_has_v_old; assumption.\nQed.\n\nLemma fl_graph_has_v: forall from to depth l g g',\n    graph_has_gen g to -> forward_loop from to depth l g g' ->\n    forall v, graph_has_v g v -> graph_has_v g' v.\nProof.\n  intros. revert g g' H H0 v H1. induction l; intros; inversion H0; subst.\n  1: assumption. cut (graph_has_v g2 v).\n  - intros. assert (graph_has_gen g2 to) by\n        (apply (fr_graph_has_gen _ _ _ _ _ _ H H5); assumption).\n    apply (IHl _ _ H3 H8 _ H2).\n  - apply (fr_graph_has_v _ _ _ _ _ _ H H5 _ H1).\nQed.\n\nLemma fr_vertex_address: forall depth from to p g g',\n    graph_has_gen g to -> forward_relation from to depth p g g' ->\n    forall v, closure_has_v g v -> vertex_address g v = vertex_address g' v.\nProof.\n  intros. remember (fun g v (x: nat) => closure_has_v g v) as Q.\n  remember (fun g1 g2 v => vertex_address g1 v = vertex_address 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_vertex_address; [reflexivity | assumption..].\n  - apply (fr_closure_has_v _ _ _ _ _ _ H2 H3 _ H4).\n  - apply lcv_closure_has_v; assumption.\nQed.\n\nLemma fl_vertex_address: forall from to depth l g g',\n    graph_has_gen g to -> forward_loop from to depth l g g' ->\n    forall v, closure_has_v g v -> vertex_address g v = vertex_address g' v.\nProof.\n  intros. revert g g' H H0 v H1. induction l; intros; inversion H0; subst.\n  1: reflexivity. transitivity (vertex_address g2 v).\n  - apply (fr_vertex_address _ _ _ _ _ _ H H5 _ H1).\n  - apply IHl; [|assumption|].\n    + erewrite <- fr_graph_has_gen; eauto.\n    + eapply fr_closure_has_v; eauto.\nQed.\n\nLemma lmc_raw_fields: forall g old new x,\n    raw_fields (vlabel g x) = raw_fields (vlabel (lgraph_mark_copied g old new) x).\nProof.\n  intros. destruct (V_EqDec old x).\n  - unfold equiv in e. subst. simpl. unfold update_copied_old_vlabel, update_vlabel.\n    rewrite if_true by reflexivity. simpl. reflexivity.\n  - assert (x <> old) by intuition.\n    rewrite lmc_vlabel_not_eq; [reflexivity | assumption].\nQed.\n\nLemma lcv_raw_fields: forall g v to x,\n    graph_has_gen g to -> graph_has_v g x ->\n    raw_fields (vlabel g x) = raw_fields (vlabel (lgraph_copy_v g v to) x).\nProof.\n  intros. unfold lgraph_copy_v. rewrite <- lmc_raw_fields, lacv_vlabel_old.\n  1: reflexivity. apply graph_has_v_not_eq; assumption.\nQed.\n\nLemma lcv_mfv_Zlen_eq: forall g v v' to,\n    graph_has_gen g to ->\n    graph_has_v g v ->\n    Zlength (make_fields_vals g v) =\n    Zlength (make_fields_vals (lgraph_copy_v g v' to) v).\nProof.\n  intros. repeat rewrite fields_eq_length.\n  rewrite <- lcv_raw_fields by assumption; reflexivity.\nQed.\n\nLemma fr_raw_fields: forall depth from to p g g',\n    graph_has_gen g to -> forward_relation from to depth p g g' ->\n    forall v, graph_has_v g v -> raw_fields (vlabel g v) = raw_fields (vlabel g' v).\nProof.\n  intros. remember (fun (g: LGraph) (v: VType) (x: nat) => graph_has_v g v) as Q.\n  remember (fun (g1 g2: LGraph) v =>\n              raw_fields (vlabel g1 v) = raw_fields (vlabel 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. apply H3.\n  - rewrite <- lcv_raw_fields; [reflexivity | assumption..].\n  - apply (fr_graph_has_v _ _ _ _ _ _ H2 H3 _ H4).\n  - apply lcv_graph_has_v_old; assumption.\nQed.\n\nLemma fl_raw_fields: forall from to depth l g g',\n    graph_has_gen g to -> forward_loop from to depth l g g' ->\n    forall v, graph_has_v g v -> raw_fields (vlabel g v) = raw_fields (vlabel g' v).\nProof.\n  intros. revert g g' H H0 v H1. induction l; intros; inversion H0; subst.\n  1: reflexivity. transitivity (raw_fields (vlabel g2 v)).\n  - apply (fr_raw_fields _ _ _ _ _ _ H H5 _ H1).\n  - apply IHl; [|assumption|].\n    + erewrite <- fr_graph_has_gen; eauto.\n    + eapply fr_graph_has_v; eauto.\nQed.\n\nLemma lmc_raw_mark: forall g old new x,\n    x <> old -> raw_mark (vlabel g x) =\n                raw_mark (vlabel (lgraph_mark_copied g old new) x).\nProof.\n  intros. destruct (V_EqDec x old).\n  - unfold equiv in e. contradiction.\n  - rewrite lmc_vlabel_not_eq; [reflexivity | assumption].\nQed.\n\nLemma lcv_raw_mark: forall g v to x,\n    x <> v -> graph_has_gen g to -> graph_has_v g x ->\n    raw_mark (vlabel g x) = raw_mark (vlabel (lgraph_copy_v g v to) x).\nProof.\n  intros. unfold lgraph_copy_v. rewrite <- lmc_raw_mark by assumption.\n  rewrite lacv_vlabel_old. 1: reflexivity. apply graph_has_v_not_eq; assumption.\nQed.\n\nLemma fr_raw_mark: forall depth from to p g g',\n    graph_has_gen g to -> forward_relation from to depth p g g' ->\n    forall v, graph_has_v g v -> vgeneration v <> from ->\n              raw_mark (vlabel g v) = raw_mark (vlabel g' v).\nProof.\n  intros. remember (fun (g: LGraph) (v: VType) (x: nat) =>\n                      graph_has_v g v /\\ vgeneration v <> x) as Q.\n  remember (fun (g1 g2: LGraph) v =>\n              raw_mark (vlabel g1 v) = raw_mark (vlabel 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 H3; clear H3; intros; try assumption; try reflexivity.\n  - rewrite H3. apply H4.\n  - destruct H4. rewrite <- lcv_raw_mark; [reflexivity | try assumption..].\n    destruct x, v0. simpl in *. intro. inversion H9. subst. contradiction.\n  - destruct H5. split. 2: assumption.\n    apply (fr_graph_has_v _ _ _ _ _ _ H3 H4 _ H5).\n  - destruct H4. split. 2: assumption. apply lcv_graph_has_v_old; assumption.\n  - split; assumption.\nQed.\n\nLemma fl_raw_mark: forall depth from to l g g',\n    graph_has_gen g to -> forward_loop from to depth l g g' ->\n    forall v, graph_has_v g v -> vgeneration v <> from ->\n              raw_mark (vlabel g v) = raw_mark (vlabel g' v).\nProof.\n  intros. revert g g' H H0 v H1 H2. induction l; intros; inversion H0; subst.\n  1: reflexivity. transitivity (raw_mark (vlabel g2 v)).\n  - apply (fr_raw_mark _ _ _ _ _ _ H H6 _ H1 H2).\n  - apply IHl; [|assumption| |assumption].\n    + erewrite <- fr_graph_has_gen; eauto.\n    + eapply fr_graph_has_v; eauto.\nQed.\n\nLemma tir_trans: forall t1 t2 t3,\n    thread_info_relation t1 t2 -> thread_info_relation t2 t3 ->\n    thread_info_relation t1 t3.\nProof.\n  intros. destruct H as [? [? ?]], H0 as [? [? ?]].\n  split; [|split]; [rewrite H; assumption | intros; rewrite H1; apply H3|\n                   intros; rewrite H2; apply H4].\nQed.\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 vpp_Zlength: forall g x,\n    Zlength (vertex_pos_pairs g x) = Zlength (raw_fields (vlabel g x)).\nProof.\n  intros. unfold vertex_pos_pairs.\n  rewrite Zlength_map, !Zlength_correct, nat_inc_list_length. reflexivity.\nQed.\n\n#[export] Instance forward_p_type_Inhabitant: Inhabitant forward_p_type := inl 0.\n\nLemma vpp_Znth: forall (x : VType) (g : LGraph) (i : Z),\n    0 <= i < Zlength (raw_fields (vlabel g x)) ->\n    Znth i (vertex_pos_pairs g x) = inr (x, i).\nProof.\n  intros. unfold vertex_pos_pairs.\n  assert (0 <= i < Zlength (nat_inc_list (length (raw_fields (vlabel g x))))) by\n      (rewrite Zlength_correct, nat_inc_list_length, <- Zlength_correct; assumption).\n  rewrite Znth_map by assumption. do 2 f_equal. rewrite <- nth_Znth by assumption.\n  rewrite nat_inc_list_nth. 1: rewrite Z2Nat.id; lia.\n  rewrite <- ZtoNat_Zlength, <- Z2Nat.inj_lt; lia.\nQed.\n\nLemma forward_loop_add_tail_vpp: forall from to depth x g g1 g2 g3 roots i,\n    0 <= i < Zlength (raw_fields (vlabel g x)) ->\n    forward_loop from to depth (sublist 0 i (vertex_pos_pairs g x)) g1 g2 ->\n    forward_relation from to depth (forward_p2forward_t (inr (x, i)) roots g2) g2 g3 ->\n    forward_loop from to depth (sublist 0 (i + 1) (vertex_pos_pairs g x)) g1 g3.\nProof.\n  intros. rewrite <- vpp_Zlength in H. rewrite sublist_last_1; [|lia..].\n  rewrite vpp_Zlength in H. rewrite vpp_Znth by assumption.\n  apply forward_loop_add_tail with (g2 := g2) (roots := roots); assumption.\nQed.\n\nLemma lcv_vlabel_new: forall g v to,\n    vgeneration v <> to ->\n    vlabel (lgraph_copy_v g v to) (new_copied_v g to) = vlabel g v.\nProof.\n  intros. unfold lgraph_copy_v.\n  rewrite lmc_vlabel_not_eq, lacv_vlabel_new;\n    [| unfold new_copied_v; intro; apply H; inversion H0; simpl]; reflexivity.\nQed.\n\nInductive scan_vertex_for_loop (from to: nat) (v: VType):\n  list nat -> LGraph -> LGraph -> Prop :=\n| svfl_nil: forall g, scan_vertex_for_loop from to v nil g g\n| svfl_cons: forall g1 g2 g3 i il,\n  forward_relation\n    from to O (forward_p2forward_t (inr (v, (Z.of_nat i))) nil g1) g1 g2 ->\n  scan_vertex_for_loop from to v il g2 g3 ->\n  scan_vertex_for_loop from to v (i :: il) g1 g3.\n\nDefinition no_scan (g: LGraph) (v: VType): Prop :=\n  NO_SCAN_TAG <= (vlabel g v).(raw_tag).\n\nInductive scan_vertex_while_loop (from to: nat):\n  list nat -> LGraph -> LGraph -> Prop :=\n| svwl_nil: forall g, scan_vertex_while_loop from to nil g g\n| svwl_no_scan: forall g1 g2 i il,\n    gen_has_index g1 to i -> no_scan g1 (to, i) ->\n    scan_vertex_while_loop from to il g1 g2 ->\n    scan_vertex_while_loop from to (i :: il) g1 g2\n| svwl_scan: forall g1 g2 g3 i il,\n    gen_has_index g1 to i -> ~ no_scan g1 (to, i) ->\n    scan_vertex_for_loop\n      from to (to, i)\n      (nat_inc_list (length (vlabel g1 (to, i)).(raw_fields))) g1 g2 ->\n    scan_vertex_while_loop from to il g2 g3 ->\n    scan_vertex_while_loop from to (i :: il) g1 g3.\n\nDefinition do_scan_relation (from to to_index: nat) (g1 g2: LGraph) : Prop :=\n  exists n, scan_vertex_while_loop from to (nat_seq to_index n) g1 g2 /\\\n            ~ gen_has_index g2 to (to_index + n).\n\nDefinition gen_unmarked (g: LGraph) (gen: nat): Prop :=\n  graph_has_gen g gen ->\n  forall idx, gen_has_index g gen idx -> (vlabel g (gen, idx)).(raw_mark) = false.\n\nLemma lcv_graph_has_v_inv: forall (g : LGraph) (v : VType) (to : nat) (x : VType),\n    graph_has_gen g to -> graph_has_v (lgraph_copy_v g v to) x ->\n    graph_has_v g x \\/ x = new_copied_v g to.\nProof.\n  intros. unfold lgraph_copy_v in H0. rewrite <- lmc_graph_has_v in H0.\n  apply (lacv_graph_has_v_inv g v); assumption.\nQed.\n\nLemma lcv_gen_unmarked: forall (to : nat) (g : LGraph) (v : VType),\n    graph_has_gen g to -> raw_mark (vlabel g v) = false ->\n    forall gen, vgeneration v <> gen ->\n                gen_unmarked g gen -> gen_unmarked (lgraph_copy_v g v to) gen.\nProof.\n  intros. unfold gen_unmarked in *. intros.\n  assert (graph_has_v (lgraph_copy_v g v to) (gen, idx)) by (split; assumption).\n  apply lcv_graph_has_v_inv in H5. 2: assumption. destruct H5.\n  - pose proof H5. destruct H6. simpl in * |- . specialize (H2 H6 _ H7).\n    rewrite <- lcv_raw_mark; try assumption. destruct v. simpl in *. intro. apply H1.\n    inversion H8. reflexivity.\n  - rewrite H5. rewrite lcv_vlabel_new; try assumption. unfold new_copied_v in H5.\n    inversion H5. subst. assumption.\nQed.\n\nLemma fr_gen_unmarked: forall from to depth p g g',\n    graph_has_gen g to -> forward_relation from to depth p g g' ->\n    forall gen, from  <> gen -> gen_unmarked g gen -> gen_unmarked g' gen.\nProof.\n  intros. remember (fun (g: LGraph) (gen: nat) (x: nat) => x <> gen) as Q.\n  remember (fun (g1 g2: LGraph) gen =>\n              gen_unmarked g1 gen -> gen_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_gen_unmarked; assumption.\nQed.\n\nLemma svfl_graph_has_gen: forall from to v l g g',\n    graph_has_gen g to -> scan_vertex_for_loop from to v l g g' ->\n    forall x, graph_has_gen g x <-> graph_has_gen g' x.\nProof.\n  intros from to v l. revert from to v. induction l; intros; inversion H0; subst.\n  1: reflexivity. transitivity (graph_has_gen g2 x).\n  - eapply fr_graph_has_gen; eauto.\n  - apply (IHl from to v). 2: assumption. rewrite <- fr_graph_has_gen; eauto.\nQed.\n\nLemma svfl_gen_unmarked: forall from to v l g g',\n    graph_has_gen g to -> scan_vertex_for_loop from to v l g g' ->\n    forall gen, from <> gen -> gen_unmarked g gen -> gen_unmarked g' gen.\nProof.\n  intros from to v l. revert from to v.\n  induction l; intros; inversion H0; subst; try assumption.\n  eapply (IHl from to _ g2); eauto.\n  - rewrite <- fr_graph_has_gen; eauto.\n  - eapply fr_gen_unmarked; eauto.\nQed.\n\nLemma svwl_gen_unmarked: forall from to l g g',\n    graph_has_gen g to -> scan_vertex_while_loop from to l g g' ->\n    forall gen, from <> gen -> gen_unmarked g gen -> gen_unmarked g' gen.\nProof.\n  do 3 intro. induction l; intros; inversion H0; subst;\n                [| apply (IHl g) | apply (IHl g2)]; try assumption.\n  - rewrite <- svfl_graph_has_gen; eauto.\n  - eapply svfl_gen_unmarked; eauto.\nQed.\n\nLemma make_header_tag_prep64: forall z,\n    0 <= z < two_p (8 * 8) ->\n    Int64.and (Int64.repr z) (Int64.repr 255) =\n    Int64.sub (Int64.repr z)\n              (Int64.mul (Int64.repr (z / two_p 8)) (Int64.repr (two_p 8))).\nProof.\n  intros. replace (Int64.repr 255) with (Int64.sub (Int64.repr 256) Int64.one) by\n      now vm_compute.\n  rewrite <- (Int64.modu_and _ _ (Int64.repr 8)) by now vm_compute.\n  rewrite Int64.modu_divu by (vm_compute; intro S; inversion S).\n  rewrite (Int64.divu_pow2 _ _ (Int64.repr 8)) by now vm_compute.\n  rewrite (Int64.mul_pow2 _ _ (Int64.repr 8)) by now vm_compute.\n  rewrite Int64.shru_div_two_p, !Int64.unsigned_repr; [| rep_lia | ].\n  - rewrite Int64.shl_mul_two_p, Int64.unsigned_repr by rep_lia. easy.\n  - simpl Z.mul in H. unfold Int64.max_unsigned, Int64.modulus.\n    unfold Int64.wordsize, Wordsize_64.wordsize. rewrite two_power_nat_two_p.\n    simpl Z.of_nat. lia.\nQed.\n\nLemma make_header_tag_prep32: forall z,\n    0 <= z < two_p (4 * 8) ->\n    Int.and (Int.repr z) (Int.repr 255) =\n    Int.sub (Int.repr z)\n              (Int.mul (Int.repr (z / two_p 8)) (Int.repr (two_p 8))).\nProof.\n  intros. replace (Int.repr 255) with (Int.sub (Int.repr 256) Int.one) by\n      now vm_compute.\n  rewrite <- (Int.modu_and _ _ (Int.repr 8)) by now vm_compute.\n  rewrite Int.modu_divu by (vm_compute; intro S; inversion S).\n  rewrite (Int.divu_pow2 _ _ (Int.repr 8)) by now vm_compute.\n  rewrite (Int.mul_pow2 _ _ (Int.repr 8)) by now vm_compute.\n  rewrite Int.shru_div_two_p, !Int.unsigned_repr; [| rep_lia | ].\n  - rewrite Int.shl_mul_two_p, Int.unsigned_repr by rep_lia. easy.\n  - simpl Z.mul in H. unfold Int.max_unsigned, Int.modulus.\n    unfold Int.wordsize, Wordsize_32.wordsize. rewrite two_power_nat_two_p.\n    simpl Z.of_nat. lia.\nQed.\n\nLemma make_header_tag: forall g v,\n    raw_mark (vlabel g v) = false ->\n    if Archi.ptr64 then\n        Int64.and (Int64.repr (make_header g v)) (Int64.repr 255) =\n        Int64.repr (raw_tag (vlabel g v))\n    else Int.and (Int.repr (make_header g v)) (Int.repr 255) =\n         Int.repr (raw_tag (vlabel g v)).\nProof.\n  intros. cbv delta [Archi.ptr64]. simpl.\n  first [rewrite make_header_tag_prep32 | rewrite make_header_tag_prep64].\n  2: apply make_header_range.\n  unfold make_header in *. remember (vlabel g v). clear Heqr.\n  rewrite H, !Zbits.Zshiftl_mul_two_p in * by lia. rewrite <- Z.add_assoc.\n  replace (raw_color r * two_p 8 + Zlength (raw_fields r) * two_p 10)\n    with ((raw_color r + Zlength (raw_fields r) * two_p 2) * two_p 8) by\n      (rewrite Z.mul_add_distr_r, <- Z.mul_assoc, <- two_p_is_exp by lia;\n       reflexivity). rewrite Z.div_add by (vm_compute; intros S; inversion S).\n  assert (raw_tag r / two_p 8 = 0) by (apply Z.div_small, raw_tag_range).\n  rewrite H0, Z.add_0_l.\n  first [rewrite mul_repr, sub_repr | rewrite mul64_repr, sub64_repr].\n  now rewrite <- Z.add_sub_assoc, Z.sub_diag, Z.add_0_r.\nQed.\n\nLemma svfl_vertex_address: forall from to v l g g',\n    graph_has_gen g to -> scan_vertex_for_loop from to v l g g' ->\n    forall x, closure_has_v g x -> vertex_address g x = vertex_address g' x.\nProof.\n  do 4 intro. revert from to v. induction l; intros; simpl; inversion H0; subst.\n  1: reflexivity. assert (graph_has_gen g2 to) by\n      (eapply fr_graph_has_gen in H4; [rewrite <- H4 |]; assumption).\n  assert (closure_has_v g2 x) by (eapply fr_closure_has_v in H4; eauto).\n  eapply (IHl from to _ g2) in H7; eauto. rewrite <- H7.\n  eapply fr_vertex_address; eauto.\nQed.\n\nLemma svfl_graph_has_v: forall from to v l g g',\n    graph_has_gen g to -> scan_vertex_for_loop from to v l g g' ->\n    forall x, graph_has_v g x -> graph_has_v g' x.\nProof.\n  do 4 intro. revert from to v. induction l; intros; simpl; inversion H0; subst.\n  1: assumption. assert (graph_has_gen g2 to) by\n      (eapply fr_graph_has_gen in H4; [rewrite <- H4 |]; assumption).\n  assert (graph_has_v g2 x) by (eapply fr_graph_has_v in H4; eauto).\n  eapply (IHl from to _ g2) in H7; eauto.\nQed.\n\nLemma svfl_raw_fields: forall from to v l g g',\n    graph_has_gen g to -> scan_vertex_for_loop from to v l g g' ->\n    forall x, graph_has_v g x -> raw_fields (vlabel g x) = raw_fields (vlabel g' x).\nProof.\n  do 4 intro. revert from to v. induction l; intros; simpl; inversion H0; subst.\n  1: reflexivity. assert (graph_has_gen g2 to) by\n      (eapply fr_graph_has_gen in H4; [rewrite <- H4 |]; assumption).\n  assert (graph_has_v g2 x) by (eapply fr_graph_has_v in H4; eauto).\n  eapply (IHl from to _ g2) in H7; eauto. rewrite <- H7.\n  eapply fr_raw_fields; eauto.\nQed.\n\nLemma svfl_raw_mark: forall from to v l g g',\n    graph_has_gen g to -> scan_vertex_for_loop from to v l g g' ->\n    forall x, graph_has_v g x -> vgeneration x <> from ->\n              raw_mark (vlabel g x) = raw_mark (vlabel g' x).\nProof.\n  do 4 intro. revert from to v. induction l; intros; simpl; inversion H0; subst.\n  1: reflexivity. assert (graph_has_gen g2 to) by\n      (eapply fr_graph_has_gen in H5; [rewrite <- H5 |]; assumption).\n  assert (graph_has_v g2 x) by (eapply fr_graph_has_v in H5; eauto).\n  eapply (IHl from to _ g2) in H8; eauto. rewrite <- H8.\n  eapply fr_raw_mark; eauto.\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 svfl_add_tail: forall from to v l roots i g1 g2 g3,\n    scan_vertex_for_loop from to v l g1 g2 ->\n    forward_relation from to 0\n                     (forward_p2forward_t (inr (v, Z.of_nat i)) roots g2) g2 g3 ->\n    scan_vertex_for_loop from to v (l +:: i) g1 g3.\nProof.\n  do 4 intro. revert from to v. induction l; intros; inversion H; subst.\n  - simpl. rewrite forward_p2t_inr_roots in H0.\n    apply svfl_cons with g3. 1: assumption. constructor.\n  - simpl app. apply svfl_cons with g4. 1: assumption.\n    apply IHl with roots g2; assumption.\nQed.\n\nLemma svwl_add_tail_no_scan: forall from to l g1 g2 i,\n    scan_vertex_while_loop from to l g1 g2 -> gen_has_index g2 to i ->\n    no_scan g2 (to, i) -> scan_vertex_while_loop from to (l +:: i) g1 g2.\nProof.\n  do 3 intro. revert from to. induction l; intros; inversion H; subst.\n  - simpl. apply svwl_no_scan; assumption.\n  - simpl app. apply svwl_no_scan; try assumption. apply IHl; assumption.\n  - simpl app. apply svwl_scan with g3; try assumption. apply IHl; assumption.\nQed.\n\nLemma svwl_add_tail_scan: forall from to l g1 g2 g3 i,\n    scan_vertex_while_loop from to l g1 g2 -> gen_has_index g2 to i ->\n    ~ no_scan g2 (to, i) ->\n    scan_vertex_for_loop\n      from to (to, i)\n      (nat_inc_list (length (raw_fields (vlabel g2 (to, i)))))\n      g2 g3 ->\n    scan_vertex_while_loop from to (l +:: i) g1 g3.\nProof.\n  do 3 intro. revert from to. induction l; intros; inversion H; subst.\n  - simpl. apply svwl_scan with g3; try assumption. constructor.\n  - simpl app. apply svwl_no_scan; try assumption. apply IHl with g2; assumption.\n  - simpl app. apply svwl_scan with g4; try assumption. apply IHl with g2; assumption.\nQed.\n\nLemma root_in_outlier: forall (roots: roots_t) outlier p,\n    In (inl (inr p)) roots ->\n    incl (filter_sum_right (filter_sum_left roots)) outlier -> In p outlier.\nProof.\n  intros. apply H0. rewrite <- filter_sum_right_In_iff, <- filter_sum_left_In_iff.\n  assumption.\nQed.\n\nDefinition do_generation_relation (from to: nat) (f_info: fun_info)\n           (roots roots': roots_t) (g g': LGraph): Prop := exists g1 g2,\n    forward_roots_relation from to f_info roots g roots' g1 /\\\n    do_scan_relation from to (number_of_vertices (nth_gen g to)) g1 g2 /\\\n    g' = reset_graph from g2.\n\nDefinition space_address (t_info: thread_info) (gen: nat) :=\n  offset_val (SPACE_STRUCT_SIZE * Z.of_nat gen) (ti_heap_p t_info).\n\nDefinition enough_space_to_have_g g t_info from to: Prop :=\n  graph_gen_size g from <= rest_gen_size t_info to.\n\nDefinition roots_fi_compatible (roots: roots_t) f_info: Prop :=\n  Zlength roots = Zlength (live_roots_indices f_info) /\\\n  forall i j,\n    0 <= i < Zlength roots -> 0 <= j < Zlength roots ->\n    Znth i (live_roots_indices f_info) = Znth j (live_roots_indices f_info) ->\n    Znth i roots = Znth j roots.\n\nDefinition do_generation_condition g t_info roots f_info from to: Prop :=\n  enough_space_to_have_g g t_info from to /\\ graph_has_gen g from /\\\n  graph_has_gen g to /\\ copy_compatible g /\\ no_dangling_dst g /\\\n  0 < gen_size t_info to /\\ gen_unmarked g to /\\ roots_fi_compatible roots f_info.\n\nLemma dgc_imply_fc: forall g t_info roots f_info from to,\n    do_generation_condition g t_info roots f_info from to ->\n    forward_condition g t_info from to /\\ 0 < gen_size t_info to /\\\n    gen_unmarked g to /\\ roots_fi_compatible roots f_info.\nProof.\n  intros. destruct H. do 2 (split; [|intuition]). clear H0. red in H |-* .\n  transitivity (graph_gen_size g from); [apply unmarked_gen_size_le | assumption].\nQed.\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 (raw_mark (vlabel g v)); rewrite upd_bunch_Zlength; auto.\nQed.\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\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_vertex_address: forall from to f_info roots1 g1 roots2 g2,\n    graph_has_gen g1 to -> forward_roots_relation from to f_info roots1 g1 roots2 g2 ->\n    forall v, closure_has_v g1 v -> vertex_address g1 v = vertex_address g2 v.\nProof.\n  intros. induction H0. 1: reflexivity. rewrite <- IHforward_roots_loop.\n  - eapply fr_vertex_address; 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    graph_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_gen_unmarked: forall from to f_info roots1 g1 roots2 g2,\n    graph_has_gen g1 to -> forward_roots_relation from to f_info roots1 g1 roots2 g2 ->\n    forall gen, gen <> from -> gen_unmarked g1 gen -> gen_unmarked g2 gen.\nProof.\n  intros. induction H0. 1: assumption. apply IHforward_roots_loop.\n  - rewrite <- fr_graph_has_gen; eauto.\n  - eapply fr_gen_unmarked; eauto.\nQed.\n\nDefinition graph_gen_clear (g: LGraph) (gen: nat) :=\n  number_of_vertices (nth_gen g gen) = O.\n\nLemma pvs_reset_unchanged: forall g gen n l,\n    previous_vertices_size (reset_graph gen g) n l =\n    previous_vertices_size g n l.\nProof.\n  intros. unfold previous_vertices_size. apply fold_left_ext. intros.\n  unfold vertex_size_accum. f_equal. unfold vertex_size. simpl.\n  rewrite remove_ve_vlabel_unchanged. reflexivity.\nQed.\n\nLemma graph_thread_info_compatible_reset: forall g t_info gen,\n    graph_thread_info_compatible g t_info ->\n    graph_thread_info_compatible (reset_graph gen g)\n                                 (reset_nth_heap_thread_info gen t_info).\nProof.\n  intros. destruct H as [? [? ?]].\n  split; [|split]; [|simpl; rewrite reset_nth_gen_info_length..].\n  - rewrite gsc_iff by\n        (simpl; rewrite remove_ve_glabel_unchanged, reset_nth_space_length,\n                reset_nth_gen_info_length; assumption).\n    intros n ?. rewrite gsc_iff in H by assumption. rewrite graph_has_gen_reset in H2.\n    specialize (H _ H2). red in H. simpl. unfold nth_gen, nth_space in *. simpl.\n    rewrite remove_ve_glabel_unchanged. destruct (Nat.eq_dec n gen).\n    + subst gen. red in H2. rewrite reset_nth_gen_info_same.\n      rewrite reset_nth_space_same by lia. intuition.\n    + rewrite reset_nth_gen_info_diff, reset_nth_space_diff by assumption.\n      destruct H as [? [? ?]]. split. 1: assumption. split. 1: assumption.\n      rewrite pvs_reset_unchanged. assumption.\n  - rewrite remove_ve_glabel_unchanged.\n    destruct (le_lt_dec (length (spaces (ti_heap t_info))) gen).\n    + rewrite reset_nth_space_overflow; assumption.\n    + rewrite reset_nth_space_Znth by assumption. rewrite <- upd_Znth_map. simpl.\n      remember (spaces (ti_heap t_info)).\n      assert (0 <= Z.of_nat gen < Zlength l0) by (rewrite Zlength_correct; lia).\n      replace (space_start (Znth (Z.of_nat gen) l0))\n        with (Znth (Z.of_nat gen) (map space_start l0)) by (rewrite Znth_map; auto).\n      rewrite upd_Znth_unchanged; [|rewrite Zlength_map]; assumption.\n  - rewrite remove_ve_glabel_unchanged, reset_nth_space_length. assumption.\nQed.\n\nLemma upd_bunch_rf_compatible: forall f_info roots z r,\n    roots_fi_compatible roots f_info ->\n    roots_fi_compatible (upd_bunch z f_info roots r) f_info.\nProof.\n  intros. unfold roots_fi_compatible in *. destruct H.\n  assert (Zlength (upd_bunch z f_info roots r) = Zlength (live_roots_indices f_info))\n    by (rewrite upd_bunch_Zlength; assumption). split; intros. 1: assumption.\n  rewrite H1 in *. rewrite <- H in *.\n  destruct (Z.eq_dec (Znth i (live_roots_indices f_info))\n                     (Znth z (live_roots_indices f_info))).\n  - rewrite !upd_bunch_same; try assumption; try reflexivity.\n    rewrite H4 in e; assumption.\n  - rewrite !upd_bunch_diff; try assumption; [apply H0 | rewrite <- H4]; assumption.\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 (raw_mark (vlabel g v)); apply upd_bunch_rf_compatible; assumption.\nQed.\n\nDefinition np_roots_rel from f_info (roots roots': roots_t) (l: list Z) : Prop :=\n  let lri := live_roots_indices f_info in\n  let maped_lri := (map (flip Znth lri) l) in\n  forall v j, Znth j roots' = inr v ->\n              (In (Znth j lri) maped_lri -> vgeneration v <> from) /\\\n              (~ In (Znth j lri) maped_lri -> Znth j roots = inr v).\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. unfold flip.\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 (raw_mark (vlabel g v0)) 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 (graph_has_v g v0). {\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 v0. assumption.\nQed.\n\nLemma np_roots_rel_cons: forall roots1 roots2 roots3 from f_info i l,\n    np_roots_rel from f_info roots1 roots2 [i] ->\n    np_roots_rel from f_info roots2 roots3 l ->\n    np_roots_rel from f_info roots1 roots3 (i :: l).\nProof.\n  intros. unfold np_roots_rel in *. intros. simpl. specialize (H0 _ _ H1).\n  destruct H0. split; intros; unfold flip in H2 at 1.\n  - destruct (in_dec Z.eq_dec (Znth j (live_roots_indices f_info))\n                     (map (flip Znth (live_roots_indices f_info)) l)).\n    1: apply H0; assumption. destruct H3. 2: contradiction. unfold flip in H3.\n    specialize (H2 n). specialize (H _ _ H2). destruct H. apply H. simpl. unfold flip.\n    left; assumption.\n  - unfold flip in H3 at 1. apply Decidable.not_or in H3. destruct H3.\n    specialize (H2 H4). specialize (H _ _ H2). destruct H. apply H5. simpl. tauto.\nQed.\n\nLemma fr_copy_compatible: forall depth from to p g g',\n    from <> to -> graph_has_gen g to -> forward_relation from to depth p g g' ->\n    copy_compatible g -> copy_compatible g'.\nProof.\n  intros. remember (fun (g: LGraph) (v: VType) (x: nat) => True) as Q.\n  remember (fun g1 g2 (v: VType) => 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). subst Q P R.\n  apply H3; clear H3; intros; try assumption; try reflexivity.\n  - apply H4, H3. assumption.\n  - subst from0. apply lcv_copy_compatible; auto.\n  - exact (O, O).\nQed.\n\nLemma fr_right_roots_graph_compatible: forall depth from to e g g' roots,\n    graph_has_gen g to -> forward_p_compatible (inr e) roots g from ->\n    forward_relation from to depth (forward_p2forward_t (inr e) [] g) g g' ->\n    roots_graph_compatible roots g -> roots_graph_compatible roots g'.\nProof.\n  intros. simpl in H1, H0. destruct e. destruct H0 as [_ [_ [? _]]]. rewrite H0 in H1.\n  simpl in H1. remember (fun (g: LGraph) (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\n                depth from to (field2forward (Znth z (make_fields g v))) g g' _ Q P R).\n  subst Q P R. apply H3; clear H3; intros; try assumption; try reflexivity.\n  - apply H4, H3. assumption.\n  - apply lcv_rgc_unchanged; assumption.\nQed.\n\nLemma fl_edge_roots_graph_compatible: forall depth from to l g g' v roots,\n    vgeneration v <> from ->\n    graph_has_gen g to -> graph_has_v g v -> raw_mark (vlabel 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 (raw_fields (vlabel 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_graph_has_v; eauto.\n    + rewrite <- H2. symmetry. eapply fr_raw_mark; eauto.\n    + assert (raw_fields (vlabel g v) = raw_fields (vlabel g2 v)) by\n          (eapply fr_raw_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 (raw_mark (vlabel g v)); apply upd_roots_outlier_compatible; assumption.\nQed.\n\nLemma fr_roots_graph_compatible: forall depth from to p g g' roots f_info,\n    graph_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    from <> to -> roots_graph_compatible roots g ->\n    roots_graph_compatible (upd_roots from to p g roots f_info) g'.\nProof.\n  intros. destruct p.\n  - simpl in *. destruct (Znth z roots) eqn: ?; simpl in H2.\n    + destruct s; inversion H2; subst; assumption.\n    + assert (graph_has_v g v). {\n        red in H4. rewrite Forall_forall in H4. apply H4.\n        rewrite <- filter_sum_right_In_iff. rewrite <- Heqr. apply Znth_In.\n        assumption. }\n      inversion H2; destruct (Nat.eq_dec (vgeneration v) from);\n        try contradiction; subst; try assumption.\n      * destruct (raw_mark (vlabel g' v)) eqn:? . 2: inversion H9.\n        apply upd_bunch_graph_compatible. 1: assumption. specialize (H1 _ H5 Heqb).\n        destruct H1; assumption.\n      * destruct (raw_mark (vlabel g v)) eqn:? . 1: inversion H9.\n        apply lcv_roots_graph_compatible; assumption.\n      * destruct (raw_mark (vlabel g v)) eqn:? . 1: inversion H8.\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\n            (subst; subst new_g; apply lcv_roots_graph_compatible; assumption).\n        assert (raw_mark (vlabel new_g (new_copied_v g to)) = false). {\n          subst new_g. unfold lgraph_copy_v. rewrite <- lmc_raw_mark.\n          - rewrite lacv_vlabel_new. assumption.\n          - unfold new_copied_v. destruct v. destruct H5. simpl in H7.\n            red in H7. intro HS. inversion HS. lia. }\n        assert (graph_has_v new_g (new_copied_v g to)) by\n            (subst new_g; apply lcv_graph_has_v_new; assumption).\n        unfold vertex_pos_pairs in H10.\n        remember (nat_inc_list\n                    (length (raw_fields (vlabel new_g (new_copied_v g to))))).\n        eapply (fl_edge_roots_graph_compatible\n                  depth0 (vgeneration v) to l new_g); eauto.\n        -- unfold new_copied_v. simpl; auto.\n        -- subst new_g. rewrite <- lcv_graph_has_gen; assumption.\n        -- intros. subst l. rewrite nat_inc_list_In_iff in H11. assumption.\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    graph_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 -> graph_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\nDefinition roots_have_no_gen (roots: roots_t) (gen: nat): Prop :=\n  forall v, In (inr v) roots -> vgeneration v <> gen.\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    graph_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. unfold flip.\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\nLemma fta_compatible_reset: forall g t_info fi r gen,\n    fun_thread_arg_compatible g t_info fi r ->\n    fun_thread_arg_compatible (reset_graph gen g)\n                              (reset_nth_heap_thread_info gen t_info) fi r.\nProof.\n  intros. unfold fun_thread_arg_compatible in *. rewrite Znth_list_eq in *.\n  destruct H. rewrite !Zlength_map in *. split. 1: assumption. intros.\n  specialize (H0 _ H1). rewrite Znth_map in * by assumption. simpl. rewrite <- H0.\n  destruct (Znth j r) eqn: ?; simpl. 1: reflexivity.\n  apply vertex_address_reset.\nQed.\n\nLemma gen_has_index_reset: forall (g: LGraph) gen1 gen2 idx,\n    gen_has_index (reset_graph gen1 g) gen2 idx <->\n    gen_has_index g gen2 idx /\\ gen1 <> gen2.\nProof.\n  intros. unfold gen_has_index. unfold nth_gen. simpl.\n  rewrite remove_ve_glabel_unchanged. destruct (Nat.eq_dec gen1 gen2).\n  - subst. rewrite reset_nth_gen_info_same. simpl. intuition.\n  - rewrite reset_nth_gen_info_diff by auto. intuition.\nQed.\n\nLemma graph_has_v_reset: forall (g: LGraph) gen v,\n    graph_has_v (reset_graph gen g) v <->\n    graph_has_v g v /\\ gen <> vgeneration v.\nProof.\n  intros. split; intros; destruct v; unfold graph_has_v in *; simpl in *.\n  - rewrite graph_has_gen_reset, gen_has_index_reset in H. intuition.\n  - rewrite graph_has_gen_reset, gen_has_index_reset. intuition.\nQed.\n\nLemma rgc_reset: forall g gen roots,\n    roots_graph_compatible roots g ->\n    roots_have_no_gen roots gen ->\n    roots_graph_compatible roots (reset_graph gen g).\nProof.\n  intros. red in H |-*. rewrite Forall_forall in *. intros.\n  specialize (H _ H1). destruct H. split.\n  - rewrite graph_has_gen_reset. assumption.\n  - rewrite gen_has_index_reset. split. 1: assumption.\n    rewrite <- filter_sum_right_In_iff in H1. apply H0 in H1. auto.\nQed.\n\nLemma roots_compatible_reset: forall g gen outlier roots,\n    roots_compatible g outlier roots ->\n    roots_have_no_gen roots gen ->\n    roots_compatible (reset_graph gen g) outlier roots.\nProof. intros. destruct H. split; [|apply rgc_reset]; assumption. Qed.\n\nLemma outlier_compatible_reset: forall g outlier gen,\n    outlier_compatible g outlier ->\n    outlier_compatible (reset_graph gen g) outlier.\nProof.\n  intros. unfold outlier_compatible in *. intros. simpl.\n  rewrite remove_ve_vlabel_unchanged. apply H.\n  rewrite graph_has_v_reset in H0. destruct H0. assumption.\nQed.\n\nLemma super_compatible_reset: forall g t_info roots f_info outlier gen,\n    roots_have_no_gen roots gen ->\n    super_compatible (g, t_info, roots) f_info outlier ->\n    super_compatible (reset_graph gen g,\n                      reset_nth_heap_thread_info gen t_info, roots) f_info outlier.\nProof.\n  intros. destruct H0 as [? [? [? ?]]]. split; [|split; [|split]].\n  - apply graph_thread_info_compatible_reset; assumption.\n  - apply fta_compatible_reset; assumption.\n  - apply roots_compatible_reset; assumption.\n  - apply outlier_compatible_reset; assumption.\nQed.\n\nLemma tir_reset: forall t_info gen,\n    thread_info_relation t_info (reset_nth_heap_thread_info gen t_info).\nProof.\n  intros. split; simpl. 1: reflexivity.\n  unfold gen_size, nth_space. simpl.\n  destruct (le_lt_dec (length (spaces (ti_heap t_info))) gen).\n  - rewrite reset_nth_space_overflow by assumption. split; intros; reflexivity.\n  - split; intros; destruct (Nat.eq_dec n gen).\n    + subst. rewrite reset_nth_space_same; simpl; [reflexivity | assumption].\n    + rewrite reset_nth_space_diff; [reflexivity | assumption].\n    + subst. rewrite reset_nth_space_same; simpl; [reflexivity | assumption].\n    + rewrite reset_nth_space_diff; [reflexivity | assumption].\nQed.\n\nLemma frr_graph_has_gen: forall from to f_info roots1 g1 roots2 g2,\n    graph_has_gen g1 to ->\n    forward_roots_relation from to f_info roots1 g1 roots2 g2 ->\n    forall gen, graph_has_gen g1 gen <-> graph_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\nLemma svwl_graph_has_gen: forall from to l g1 g2,\n    graph_has_gen g1 to ->\n    scan_vertex_while_loop from to l g1 g2 ->\n    forall gen, graph_has_gen g1 gen <-> graph_has_gen g2 gen.\nProof.\n  intros ? ? ?. induction l; intros; inversion H0; subst. 1: reflexivity.\n  - apply IHl; assumption.\n  - transitivity (graph_has_gen g3 gen).\n    + eapply svfl_graph_has_gen; eauto.\n    + apply IHl. 2: assumption. rewrite <- svfl_graph_has_gen; eauto.\nQed.\n\nLemma do_gen_graph_has_gen: forall from to f_info roots roots' g g',\n    graph_has_gen g to ->\n    do_generation_relation from to f_info roots roots' g g' ->\n    forall gen, graph_has_gen g gen <-> graph_has_gen g' gen.\nProof.\n  intros. destruct H0 as [g1 [g2 [? [? ?]]]]. transitivity (graph_has_gen g1 gen).\n  - eapply frr_graph_has_gen; eauto.\n  - transitivity (graph_has_gen g2 gen).\n    + destruct H1 as [n [? ?]]. eapply svwl_graph_has_gen; eauto.\n      rewrite <- frr_graph_has_gen; eauto.\n    + subst g'. rewrite graph_has_gen_reset. reflexivity.\nQed.\n\nDefinition graph_unmarked (g: LGraph): Prop := forall v,\n    graph_has_v g v -> raw_mark (vlabel g v) = false.\n\nLemma graph_gen_unmarked_iff: forall g,\n    graph_unmarked g <-> forall gen, gen_unmarked g gen.\nProof.\n  intros. unfold graph_unmarked, gen_unmarked. split; intros.\n  - apply H. unfold graph_has_v. simpl. split; assumption.\n  - destruct v as [gen idx]. destruct H0. simpl in *. apply H; assumption.\nQed.\n\nLemma graph_unmarked_copy_compatible: forall g,\n    graph_unmarked g -> copy_compatible g.\nProof.\n  intros. red in H |-* . intros. apply H in H0. rewrite H0 in H1. inversion H1.\nQed.\n\nLemma gen_unmarked_reset_same: forall g gen,\n    gen_unmarked (reset_graph gen g) gen.\nProof.\n  intros. red. intros. rewrite graph_has_gen_reset in H.\n  rewrite gen_has_index_reset in H0. destruct H0. contradiction.\nQed.\n\nLemma gen_unmarked_reset_diff: forall g gen1 gen2,\n    gen_unmarked g gen2 -> gen_unmarked (reset_graph gen1 g) gen2.\nProof.\n  intros. unfold gen_unmarked in *. intros. rewrite graph_has_gen_reset in H0.\n  rewrite gen_has_index_reset in H1. destruct H1. specialize (H H0 _ H1). simpl.\n  rewrite remove_ve_vlabel_unchanged. assumption.\nQed.\n\nLemma do_gen_graph_unmarked: forall from to f_info roots roots' g g',\n    graph_has_gen g to ->\n    do_generation_relation from to f_info roots roots' g g' ->\n    graph_unmarked g -> graph_unmarked g'.\nProof.\n  intros. destruct H0 as [g1 [g2 [? [? ?]]]]. rewrite graph_gen_unmarked_iff in H1.\n  assert (forall gen, from <> gen -> gen_unmarked g1 gen) by\n      (intros; eapply frr_gen_unmarked; eauto).\n  assert (forall gen, from <> gen -> gen_unmarked g2 gen). {\n    intros. destruct H2 as [n [? ?]]. eapply (svwl_gen_unmarked _ _ _ g1 g2); eauto.\n    rewrite <- frr_graph_has_gen; eauto. } subst g'.\n  rewrite graph_gen_unmarked_iff. intros. destruct (Nat.eq_dec from gen).\n  - subst. apply gen_unmarked_reset_same.\n  - apply gen_unmarked_reset_diff. apply H5. assumption.\nQed.\n\nDefinition graph_has_e (g: LGraph) (e: EType): Prop :=\n  let v := fst e in graph_has_v g v /\\ In e (get_edges g v).\n\nDefinition gen2gen_no_edge (g: LGraph) (gen1 gen2: nat): Prop :=\n  forall vidx eidx, let e := (gen1, vidx, eidx) in\n                    graph_has_e g e -> vgeneration (dst g e) <> gen2.\n\nDefinition no_edge2gen (g: LGraph) (gen: nat): Prop :=\n  forall another, another <> gen -> gen2gen_no_edge g another gen.\n\nDefinition egeneration (e: EType): nat := vgeneration (fst e).\n\nLemma get_edges_reset: forall g gen v,\n    get_edges (reset_graph gen g) v = get_edges g v.\nProof.\n  intros. unfold get_edges, make_fields. simpl. rewrite remove_ve_vlabel_unchanged.\n  reflexivity.\nQed.\n\nLemma graph_has_e_reset: forall g gen e,\n    graph_has_e (reset_graph gen g) e <->\n    graph_has_e g e /\\ gen <> egeneration e.\nProof.\n  intros. unfold graph_has_e, egeneration. destruct e as [v idx]. simpl.\n  rewrite graph_has_v_reset, get_edges_reset. intuition.\nQed.\n\nLemma gen2gen_no_edge_reset_inv: forall g gen1 gen2 gen3,\n    gen1 <> gen2 -> gen2gen_no_edge (reset_graph gen1 g) gen2 gen3 ->\n    gen2gen_no_edge g gen2 gen3.\nProof.\n  intros. unfold gen2gen_no_edge. intros. red in H0. simpl in H0.\n  specialize (H0 vidx eidx). rewrite remove_ve_dst_unchanged in H0. apply H0.\n  rewrite graph_has_e_reset. unfold egeneration. simpl. split; assumption.\nQed.\n\nLemma gen2gen_no_edge_reset: forall g gen1 gen2 gen3,\n    gen2gen_no_edge g gen2 gen3 ->\n    gen2gen_no_edge (reset_graph gen1 g) gen2 gen3.\nProof.\n  intros. unfold gen2gen_no_edge. intros. simpl. rewrite remove_ve_dst_unchanged.\n  apply H. rewrite graph_has_e_reset in H0. destruct H0. assumption.\nQed.\n\nLemma fr_O_dst_unchanged_root: forall from to r g g',\n    forward_relation from to O (root2forward r) g g' ->\n    forall e, graph_has_v g (fst e) -> dst g e = dst g' e.\nProof.\n  intros. destruct r; [destruct s|]; simpl in H; inversion H; subst; try reflexivity.\n  simpl. rewrite pcv_dst_old. 1: reflexivity. destruct e as [[gen vidx] eidx].\n  unfold graph_has_v in H0. unfold new_copied_v. simpl in *. destruct H0. intro.\n  inversion H2. subst. red in H1. lia.\nQed.\n\nLemma frr_dst_unchanged: forall from to f_info roots1 g1 roots2 g2,\n    graph_has_gen g1 to -> forward_roots_relation from to f_info roots1 g1 roots2 g2 ->\n    forall e, graph_has_v g1 (fst 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_graph_has_v; eauto.\nQed.\n\nLemma fr_O_graph_has_v_inv: forall from to p g g',\n    graph_has_gen g to -> forward_relation from to O p g g' ->\n    forall v, graph_has_v g' v -> graph_has_v g v \\/ v = new_copied_v g to.\nProof.\n  intros. inversion H0; subst; try (left; assumption);\n            [|subst new_g; rewrite <- lgd_graph_has_v in H1];\n            apply lcv_graph_has_v_inv in H1; assumption.\nQed.\n\nDefinition gen_v_num (g: LGraph) (gen: nat): nat := number_of_vertices (nth_gen g gen).\n\nDefinition nth_gen_size (n: nat) := NURSERY_SIZE * two_p (Z.of_nat n).\n\nDefinition nth_gen_size_spec (tinfo: thread_info) (n: nat): Prop :=\n  if Val.eq (nth_space tinfo n).(space_start) nullval\n  then True\n  else gen_size tinfo n = nth_gen_size n.\n\nDefinition ti_size_spec (tinfo: thread_info): Prop :=\n  Forall (nth_gen_size_spec tinfo) (nat_inc_list (Z.to_nat MAX_SPACES)).\n\nDefinition safe_to_copy_gen g from to: Prop :=\n  nth_gen_size from <= nth_gen_size to - graph_gen_size g to.\n\nLemma ngs_range: forall i,\n    0 <= i < MAX_SPACES -> 0 <= nth_gen_size (Z.to_nat i) < MAX_SPACE_SIZE.\nProof.\n  intros. unfold nth_gen_size. rewrite MAX_SPACES_eq in H.\n  rewrite Z2Nat.id, NURSERY_SIZE_eq, Zbits.Zshiftl_mul_two_p,\n  Z.mul_1_l, <- two_p_is_exp by lia. split.\n  - cut (two_p (16 + i) > 0). 1: intros; lia. apply two_p_gt_ZERO. lia.\n  - transitivity (two_p 28). 1: apply two_p_monotone_strict; lia.\n    vm_compute. reflexivity.\nQed.\n\nLemma ngs_int_singed_range: forall i,\n    0 <= i < MAX_SPACES ->\n    (if Archi.ptr64 then Int64.min_signed else Int.min_signed) <=\n    nth_gen_size (Z.to_nat i) <=\n    (if Archi.ptr64 then Int64.max_signed else Int.max_signed).\nProof.\n  intros. apply ngs_range in H. destruct H. split.\n  - transitivity 0. 2: assumption. vm_compute. intro HS; inversion HS.\n  - apply Z.lt_le_incl. transitivity MAX_SPACE_SIZE. 1: assumption.\n    unfold MAX_SPACE_SIZE. vm_compute. reflexivity.\nQed.\n\nLemma ngs_S: forall i,\n    0 <= i -> 2 * nth_gen_size (Z.to_nat i) = nth_gen_size (Z.to_nat (i + 1)).\nProof.\n  intros. unfold nth_gen_size. rewrite !Z2Nat.id by lia.\n  rewrite Z.mul_comm, <- Z.mul_assoc, (Z.mul_comm (two_p i)), <- two_p_S by assumption.\n  reflexivity.\nQed.\n\nLemma space_start_isptr: forall (g: LGraph) (t_info: thread_info) i,\n    graph_thread_info_compatible g t_info ->\n    0 <= i < Zlength (spaces (ti_heap t_info)) ->\n    graph_has_gen g (Z.to_nat i) ->\n    isptr (space_start (Znth i (spaces (ti_heap t_info)))).\nProof.\n  intros. destruct (gt_gs_compatible _ _ H _ H1) as [? _].\n  rewrite nth_space_Znth in H2. rewrite Z2Nat.id in H2 by lia. rewrite <- H2.\n  apply start_isptr.\nQed.\n\nLemma space_start_isnull: forall (g: LGraph) (t_info: thread_info) i,\n    graph_thread_info_compatible g t_info ->\n    0 <= i < Zlength (spaces (ti_heap t_info)) ->\n    ~ graph_has_gen g (Z.to_nat i) ->\n    space_start (Znth i (spaces (ti_heap t_info))) = nullval.\nProof.\n  intros. unfold graph_has_gen in H1. destruct H as [_ [? ?]].\n  rewrite Forall_forall in H. symmetry. apply H. rewrite <- map_skipn.\n  apply List.in_map. remember (g_gen (glabel g)).\n  replace i with (i - Zlength l + Zlength l) by lia.\n  assert (length l <= Z.to_nat i)%nat by lia. clear H1.\n  assert (0 <= i - Zlength l) by\n      (rewrite <- ZtoNat_Zlength, <- Z2Nat.inj_le in H3; rep_lia).\n  rewrite <- Znth_skipn by rep_lia. rewrite ZtoNat_Zlength.\n  apply Znth_In. split. 1: assumption. rewrite <- ZtoNat_Zlength, Zlength_skipn.\n  rewrite (Z.max_r 0 (Zlength l)) by rep_lia. rewrite Z.max_r; rep_lia.\nQed.\n\nLemma space_start_is_pointer_or_null: forall (g: LGraph) (t_info: thread_info) i,\n    graph_thread_info_compatible g t_info ->\n    0 <= i < Zlength (spaces (ti_heap t_info)) ->\n    is_pointer_or_null (space_start (Znth i (spaces (ti_heap t_info)))).\nProof.\n  intros. destruct (graph_has_gen_dec g (Z.to_nat i)).\n  - apply val_lemmas.isptr_is_pointer_or_null. eapply space_start_isptr; eauto.\n  - cut (space_start (Znth i (spaces (ti_heap t_info))) = nullval).\n    + intros. rewrite H1. apply mapsto_memory_block.is_pointer_or_null_nullval.\n    + eapply space_start_isnull; eauto.\nQed.\n\nLemma space_start_isptr_iff: forall (g: LGraph) (t_info: thread_info) i,\n    graph_thread_info_compatible g t_info ->\n    0 <= i < Zlength (spaces (ti_heap t_info)) ->\n    graph_has_gen g (Z.to_nat i) <->\n    isptr (space_start (Znth i (spaces (ti_heap t_info)))).\nProof.\n  intros. split; intros.\n  - eapply space_start_isptr; eauto.\n  - destruct (graph_has_gen_dec g (Z.to_nat i)). 1: assumption. exfalso.\n    eapply space_start_isnull in n; eauto. rewrite n in H1. inversion H1.\nQed.\n\nLemma space_start_isnull_iff: forall (g: LGraph) (t_info: thread_info) i,\n    graph_thread_info_compatible g t_info ->\n    0 <= i < Zlength (spaces (ti_heap t_info)) ->\n    ~ graph_has_gen g (Z.to_nat i) <->\n    space_start (Znth i (spaces (ti_heap t_info))) = nullval.\nProof.\n  intros. split; intros. 1: eapply space_start_isnull; eauto.\n  destruct (graph_has_gen_dec g (Z.to_nat i)). 2: assumption. exfalso.\n  eapply space_start_isptr in g0; eauto. rewrite H1 in g0. inversion g0.\nQed.\n\nLemma ti_size_gen: forall (g : LGraph) (t_info : thread_info) (gen : nat),\n    graph_thread_info_compatible g t_info ->\n    graph_has_gen g gen -> ti_size_spec t_info ->\n    gen_size t_info gen = nth_gen_size gen.\nProof.\n  intros. red in H1. rewrite Forall_forall in H1.\n  assert (0 <= (Z.of_nat gen) < Zlength (spaces (ti_heap t_info))). {\n    split. 1: rep_lia. rewrite Zlength_correct. apply inj_lt.\n    destruct H as [_ [_ ?]]. red in H0. lia. }\n  assert (nth_gen_size_spec t_info gen). {\n    apply H1. rewrite nat_inc_list_In_iff. destruct H as [_ [_ ?]]. red in H0.\n    rewrite <- (spaces_size (ti_heap t_info)), ZtoNat_Zlength. lia. } red in H3.\n  destruct (Val.eq (space_start (nth_space t_info gen)) nullval). 2: assumption.\n  rewrite nth_space_Znth in e. erewrite <- space_start_isnull_iff in e; eauto.\n  unfold graph_has_gen in e. exfalso; apply e. rewrite Nat2Z.id. assumption.\nQed.\n\nLemma ti_size_gt_0: forall (g : LGraph) (t_info : thread_info) (gen : nat),\n    graph_thread_info_compatible g t_info ->\n    graph_has_gen g gen -> ti_size_spec t_info -> 0 < gen_size t_info gen.\nProof.\n  intros. erewrite ti_size_gen; eauto. unfold nth_gen_size. apply Z.mul_pos_pos.\n  - rewrite NURSERY_SIZE_eq. vm_compute. reflexivity.\n  - cut (two_p (Z.of_nat gen) > 0). 1: lia. apply two_p_gt_ZERO. lia.\nQed.\n\nLocal Close Scope Z_scope.\n\nLemma lcv_gen_v_num_to: forall g v to,\n    graph_has_gen g to -> gen_v_num g to <= gen_v_num (lgraph_copy_v g v to) to.\nProof.\n  intros. unfold gen_v_num, nth_gen; simpl. rewrite cvmgil_eq by assumption.\n  simpl. lia.\nQed.\n\nLemma lgd_gen_v_num_to: forall g e v to,\n    gen_v_num (labeledgraph_gen_dst g e v) to = gen_v_num g to.\nProof. intros. reflexivity. Qed.\n\nLemma fr_O_gen_v_num_to: forall from to p g g',\n    graph_has_gen g to -> forward_relation from to O p g g' ->\n    gen_v_num g to <= gen_v_num g' to.\nProof.\n  intros. inversion H0; subst; try lia; [|subst new_g..].\n  - apply lcv_gen_v_num_to; auto.\n  - rewrite lgd_gen_v_num_to. lia.\n  - rewrite lgd_gen_v_num_to. 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    graph_has_gen g1 to -> forward_roots_relation from to f_info roots1 g1 roots2 g2 ->\n    gen_v_num g1 to <= gen_v_num g2 to.\nProof.\n  intros. induction H0. 1: lia. transitivity (gen_v_num 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_graph_has_v_inv: forall from to f_info roots1 g1 roots2 g2,\n    graph_has_gen g1 to -> forward_roots_relation from to f_info roots1 g1 roots2 g2 ->\n    forall v, graph_has_v g2 v -> graph_has_v g1 v \\/\n                                  (vgeneration v = to /\\\n                                   gen_v_num g1 to <= vindex v < gen_v_num g2 to).\nProof.\n  intros. induction H0. 1: left; assumption.\n  assert (graph_has_gen g2 to) by (rewrite <- fr_graph_has_gen; eauto).\n  specialize (IHforward_roots_loop H3 H1). destruct IHforward_roots_loop.\n  - eapply (fr_O_graph_has_v_inv from to _ g1 g2) in H0; eauto. destruct H0.\n    1: left; assumption. right. unfold new_copied_v in H0. subst v.\n    clear H2. destruct H1. red in H1. simpl in *. unfold gen_v_num. lia.\n  - right. destruct H4. split. 1: assumption. destruct H5. split. 2: assumption.\n    apply fr_O_gen_v_num_to in H0; [lia | assumption].\nQed.\n\nLemma frr_raw_fields: forall from to f_info roots1 g1 roots2 g2,\n    graph_has_gen g1 to -> forward_roots_relation from to f_info roots1 g1 roots2 g2 ->\n    forall v, graph_has_v g1 v -> raw_fields (vlabel g1 v) = raw_fields (vlabel g2 v).\nProof.\n  intros. induction H0. 1: reflexivity. rewrite <- IHforward_roots_loop.\n  - eapply fr_raw_fields; eauto.\n  - rewrite <- fr_graph_has_gen; eauto.\n  - eapply fr_graph_has_v; eauto.\nQed.\n\nLemma frr_gen2gen_no_edge: forall from to f_info roots1 g1 roots2 g2,\n    graph_has_gen g1 to -> forward_roots_relation from to f_info roots1 g1 roots2 g2 ->\n    forall gen1 gen2, gen1 <> to -> gen2gen_no_edge g1 gen1 gen2 ->\n                      gen2gen_no_edge g2 gen1 gen2.\nProof.\n  intros. unfold gen2gen_no_edge in *. intros.\n  cut (graph_has_e g1 (gen1, vidx, eidx)).\n  - intros. erewrite <- frr_dst_unchanged; eauto. destruct H4. assumption.\n  - destruct H3. eapply frr_graph_has_v_inv in H3; eauto. destruct H3 as [? | [? ?]].\n    2: simpl in H3; contradiction. split. 1: simpl; assumption. simpl in *.\n    cut (get_edges g1 (gen1, vidx) = get_edges g2 (gen1, vidx)).\n    + intros; rewrite H5; assumption.\n    + unfold get_edges. unfold make_fields. erewrite frr_raw_fields; eauto.\nQed.\n\nLemma fr_O_dst_unchanged_field: forall from to v n g g',\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, graph_has_v g (fst e) -> e <> (v, n) -> dst g e = dst g' e.\nProof.\n  intros. simpl in *. destruct H as [? [? [? ?]]]. rewrite H4 in H0. simpl in H0.\n  remember (Znth (Z.of_nat n) (make_fields g v)).\n  assert (forall e0, inr e0 = Znth (Z.of_nat n) (make_fields g v) -> e0 <> e). {\n    intros. symmetry in H6. apply make_fields_Znth_edge in H6. 2: assumption.\n    rewrite Nat2Z.id in H6. rewrite <- H6 in H2. auto. }\n  destruct f; [destruct s |]; simpl in H0; inversion H0; subst; try reflexivity.\n  - subst new_g. rewrite lgd_dst_old. 1: reflexivity. apply H6; assumption.\n  - subst new_g. rewrite lgd_dst_old. 2: apply H6; assumption. simpl.\n    rewrite pcv_dst_old. 1: reflexivity. intro. rewrite H7 in H1. destruct H1.\n    unfold new_copied_v in H8. simpl in H8. red in H8. lia.\nQed.\n\nLemma svfl_dst_unchanged: forall from to v l g1 g2,\n    graph_has_v g1 v -> raw_mark (vlabel g1 v) = false -> vgeneration v <> from ->\n    (forall i,  In i l -> i < length (raw_fields (vlabel g1 v))) ->\n    graph_has_gen g1 to -> scan_vertex_for_loop from to v l g1 g2 ->\n    forall e, graph_has_v g1 (fst e) -> (forall i, In i l -> e <> (v, i)) ->\n              dst g1 e = dst g2 e.\nProof.\n  intros ? ? ? ?. induction l; intros; inversion H4; subst. 1: reflexivity.\n  transitivity (dst g3 e).\n  - eapply fr_O_dst_unchanged_field; eauto.\n    + simpl. intuition. rewrite Zlength_correct. apply inj_lt. apply H2.\n      left; reflexivity.\n    + apply H6. left; reflexivity.\n  - apply IHl; auto.\n    + eapply fr_graph_has_v; eauto.\n    + erewrite <- fr_raw_mark; eauto.\n    + intros. erewrite <- fr_raw_fields; eauto. apply H2. right; assumption.\n    + erewrite <- fr_graph_has_gen; eauto.\n    + eapply fr_graph_has_v; eauto.\n    + intros. apply H6. right; assumption.\nQed.\n\nLemma svwl_dst_unchanged: forall from to l g1 g2,\n    graph_has_gen g1 to -> scan_vertex_while_loop from to l g1 g2 ->\n    from <> to -> gen_unmarked g1 to ->\n    forall e, graph_has_v g1 (fst e) ->\n              (vgeneration (fst e) = to -> ~ In (vindex (fst e)) l) ->\n              dst g1 e = dst g2 e.\nProof.\n  intros. induction H0. 1: reflexivity.\n  - apply IHscan_vertex_while_loop; try assumption. intros. specialize (H4 H7).\n    intro. apply H4. right. assumption.\n  - transitivity (dst g2 e).\n    + eapply (svfl_dst_unchanged from to (to, i)); eauto.\n      * split; assumption.\n      * intros. rewrite nat_inc_list_In_iff in H8. assumption.\n      * intros. destruct (Nat.eq_dec (vgeneration (fst e)) to).\n        -- specialize (H4 e0). intro. subst e. simpl in H4. apply H4. left; auto.\n        -- intro. subst e. simpl in n. apply n; reflexivity.\n    + apply IHscan_vertex_while_loop.\n      * erewrite <- svfl_graph_has_gen; eauto.\n      * eapply svfl_gen_unmarked; eauto.\n      * eapply svfl_graph_has_v; eauto.\n      * intros. specialize (H4 H8). intro. apply H4. right; assumption.\nQed.\n\nLemma svfl_gen_v_num_to: forall from to v l g1 g2,\n    graph_has_gen g1 to -> scan_vertex_for_loop from to v l g1 g2 ->\n    gen_v_num g1 to <= gen_v_num g2 to.\nProof.\n  intros ? ? ? ?. induction l; intros; inversion H0; subst. 1: lia.\n  assert (graph_has_gen g3 to) by (rewrite <- fr_graph_has_gen; eauto).\n  specialize (IHl _ _ H1 H6). transitivity (gen_v_num g3 to); auto.\n  eapply fr_O_gen_v_num_to; eauto.\nQed.\n\nLemma svfl_graph_has_v_inv: forall from to v l g1 g2,\n    graph_has_gen g1 to -> scan_vertex_for_loop from to v l g1 g2 ->\n    forall v2,\n      graph_has_v g2 v2 ->\n      graph_has_v g1 v2 \\/\n      (vgeneration v2 = to /\\ gen_v_num g1 to <= vindex v2 < gen_v_num g2 to).\nProof.\n  intros ? ? ? ?. induction l; intros; inversion H0; subst. 1: left; assumption.\n  assert (graph_has_gen g3 to) by (rewrite <- fr_graph_has_gen; eauto).\n  specialize (IHl _ _ H2 H7 _ H1). destruct IHl.\n  - eapply (fr_O_graph_has_v_inv from to _ g1 g3) in H4; eauto. destruct H4.\n    1: left; assumption. right. clear -H1 H4. unfold new_copied_v in H4. subst.\n    destruct H1. unfold gen_v_num. simpl in *. red in H0. lia.\n  - right. destruct H3. split. 1: assumption. destruct H5. split; auto.\n    eapply fr_O_gen_v_num_to in H4; [lia | assumption].\nQed.\n\nLemma svwl_graph_has_v: forall from to l g1 g2,\n    graph_has_gen g1 to -> scan_vertex_while_loop from to l g1 g2 ->\n    forall v, graph_has_v g1 v -> graph_has_v g2 v.\nProof.\n  intros ? ? ?. induction l; intros; inversion H0; subst. 1: assumption.\n  1: eapply IHl; eauto. assert (graph_has_gen g3 to) by\n      (rewrite <- svfl_graph_has_gen; eauto). eapply IHl; eauto.\n  eapply (svfl_graph_has_v _ _ _ _ g1 g3); eauto.\nQed.\n\nLemma svwl_gen_v_num_to: forall from to l g1 g2,\n    graph_has_gen g1 to -> scan_vertex_while_loop from to l g1 g2 ->\n    gen_v_num g1 to <= gen_v_num g2 to.\nProof.\n  intros ? ? ?. induction l; intros; inversion H0; subst. 1: lia.\n  1: apply IHl; auto. transitivity (gen_v_num g3 to).\n  - eapply svfl_gen_v_num_to; eauto.\n  - apply IHl; auto. rewrite <- svfl_graph_has_gen; eauto.\nQed.\n\nLemma svwl_graph_has_v_inv: forall from to l g1 g2,\n    graph_has_gen g1 to -> scan_vertex_while_loop from to l g1 g2 ->\n    forall v,\n      graph_has_v g2 v ->\n      graph_has_v g1 v \\/\n      (vgeneration v = to /\\ gen_v_num g1 to <= vindex v < gen_v_num g2 to).\nProof.\n  intros ? ? ?. induction l; intros; inversion H0; subst. 1: left; assumption.\n  1: eapply IHl; eauto. assert (graph_has_gen g3 to) by\n      (rewrite <- svfl_graph_has_gen; eauto).\n  specialize (IHl _ _ H2 H9 _ H1). destruct IHl.\n  - eapply svfl_graph_has_v_inv in H6; eauto. destruct H6; [left|right]. 1: assumption.\n    destruct H6 as [? [? ?]]. split; [|split]; [assumption..|].\n    apply svwl_gen_v_num_to in H9; [lia | assumption].\n  - right. destruct H3 as [? [? ?]]. split; [|split]; try assumption.\n    apply svfl_gen_v_num_to in H6; [lia | assumption].\nQed.\n\nLemma svwl_raw_fields: forall from to l g g',\n    graph_has_gen g to -> scan_vertex_while_loop from to l g g' ->\n    forall v, graph_has_v g v -> raw_fields (vlabel g v) = raw_fields (vlabel g' v).\nProof.\n  do 3 intro. induction l; intros; inversion H0; subst. 1: reflexivity.\n  1: eapply IHl; eauto. erewrite <- (IHl g2 g'); eauto.\n  - eapply svfl_raw_fields; eauto.\n  - rewrite <- svfl_graph_has_gen; eauto.\n  - eapply svfl_graph_has_v; eauto.\nQed.\n\nLemma svwl_gen2gen_no_edge: forall from to l g1 g2,\n    graph_has_gen g1 to -> from <> to -> gen_unmarked g1 to ->\n    scan_vertex_while_loop from to l g1 g2 ->\n    forall gen1 gen2, gen1 <> to -> gen2gen_no_edge g1 gen1 gen2 ->\n                      gen2gen_no_edge g2 gen1 gen2.\nProof.\n  intros. unfold gen2gen_no_edge in *. intros. destruct H5. simpl in H5.\n  eapply svwl_graph_has_v_inv in H5; eauto. simpl in H5. destruct H5 as [? | [? ?]].\n  2: contradiction. erewrite <- svwl_dst_unchanged; eauto.\n  apply H4. split; simpl in *. 1: assumption.\n  cut (get_edges g1 (gen1, vidx) = get_edges g2 (gen1, vidx)).\n  + intros; rewrite H7; assumption.\n  + unfold get_edges. unfold make_fields. erewrite svwl_raw_fields; eauto.\nQed.\n\nLemma frr_graph_has_v: forall from to f_info roots1 g1 roots2 g2,\n    graph_has_gen g1 to -> forward_roots_relation from to f_info roots1 g1 roots2 g2 ->\n    forall v, graph_has_v g1 v -> graph_has_v g2 v.\nProof.\n  intros. induction H0; subst. 1: assumption. cut (graph_has_v g2 v).\n  - intros. apply IHforward_roots_loop; auto. erewrite <- fr_graph_has_gen; eauto.\n  - eapply fr_graph_has_v; 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 -> graph_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) (make_fields g' v) = inr e ->\n              vgeneration (dst g' e) <> from.\nProof.\n  intros. simpl in *. destruct H3 as [? [? [? ?]]]. rewrite H7 in H4. simpl in H4.\n  assert (make_fields g v = make_fields g' v) by\n      (unfold make_fields; erewrite fr_raw_fields; eauto). rewrite <- H9 in *.\n  clear H9. remember (Znth (Z.of_nat n) (make_fields g v)). destruct f; inversion H5.\n  subst. clear H5. symmetry in Heqf. pose proof Heqf.\n  apply make_fields_Znth_edge in Heqf. 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 get_edges. rewrite <- filter_sum_right_In_iff, <- H5. apply Znth_In.\n    rewrite make_fields_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 -> graph_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 v0. 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 (make_fields g v0)); [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 (make_fields g v)) eqn:? ; [destruct s|];\n                     simpl in H5; inversion H5. subst e0. clear H5.\n      specialize (H4 _ H). apply H4. unfold get_edges.\n      rewrite <- filter_sum_right_In_iff, <- Heqf. apply Znth_In.\n      rewrite make_fields_eq_length. assumption.\n  - subst new_g. apply lgd_no_dangling_dst. 1: apply lcv_graph_has_v_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 (make_fields g v)) eqn:? ; [destruct s|];\n                     simpl in H5; inversion H5. subst e0. clear H5.\n      specialize (H4 _ H). apply H4. unfold get_edges.\n      rewrite <- filter_sum_right_In_iff, <- Heqf. apply Znth_In.\n      rewrite make_fields_eq_length. assumption.\nQed.\n\nLemma svfl_dst_changed: forall from to v l g1 g2,\n    graph_has_v g1 v -> raw_mark (vlabel g1 v) = false -> vgeneration v <> from ->\n    copy_compatible g1 -> no_dangling_dst g1 -> from <> to ->\n    (forall i,  In i l -> i < length (raw_fields (vlabel g1 v))) -> NoDup l ->\n    graph_has_gen g1 to -> scan_vertex_for_loop from to v l g1 g2 ->\n    forall e i, In i l -> Znth (Z.of_nat i) (make_fields g2 v) = inr e ->\n                vgeneration (dst g2 e) <> from.\nProof.\n  intros ? ? ? ?. induction l; intros; inversion H8; subst. 1: inversion H9.\n  assert (e = (v, i)). {\n    apply make_fields_Znth_edge in H10. 1: rewrite Nat2Z.id in H10; assumption.\n    split. 1: lia. rewrite Zlength_correct. apply inj_lt.\n    erewrite <- svfl_raw_fields; eauto. }\n  assert (graph_has_v g3 v) by (eapply fr_graph_has_v; eauto).\n  assert (raw_mark (vlabel g3 v) = false) by (erewrite <- fr_raw_mark; eauto).\n  assert (graph_has_gen g3 to) by (erewrite <- fr_graph_has_gen; eauto).\n  assert (forall j : nat, In j l -> j < Datatypes.length (raw_fields (vlabel g3 v))). {\n    intros. erewrite <- (fr_raw_fields _ _ _ _ g1); eauto. apply H5.\n    right; assumption. } simpl in H9. destruct H9.\n  - subst a. cut (vgeneration (dst g3 e) <> from).\n    + intros. cut (dst g2 e = dst g3 e). 1: intro HS; rewrite HS; assumption.\n      symmetry. apply (svfl_dst_unchanged from to v l); auto.\n      * subst e; simpl; assumption.\n      * intros. subst e. intro. inversion H11. subst. apply NoDup_cons_2 in H6.\n        contradiction.\n    + eapply (fr_O_dst_changed_field from to); eauto.\n      * simpl. intuition. rewrite Zlength_correct. apply inj_lt. apply H5.\n        left; reflexivity.\n      * unfold make_fields in H8 |-*. erewrite svfl_raw_fields; eauto.\n  - eapply (IHl g3); eauto.\n    + eapply (fr_copy_compatible _ _ _ _ g1); eauto.\n    + eapply (fr_O_no_dangling_dst _ _ _ g1); eauto.\n      * simpl. intuition. rewrite Zlength_correct. apply inj_lt. apply H5.\n        left; reflexivity.\n      * simpl. constructor.\n    + apply NoDup_cons_1 in H6; assumption.\nQed.\n\nLemma svfl_no_edge2from: forall from to v g1 g2,\n    graph_has_v g1 v -> raw_mark (vlabel g1 v) = false -> vgeneration v <> from ->\n    copy_compatible g1 -> no_dangling_dst g1 -> from <> to -> graph_has_gen g1 to ->\n    scan_vertex_for_loop\n      from to v (nat_inc_list (length (raw_fields (vlabel g1 v)))) g1 g2 ->\n    forall e, In e (get_edges g2 v) -> vgeneration (dst g2 e) <> from.\nProof.\n  intros. unfold get_edges in H7. rewrite <- filter_sum_right_In_iff in H7.\n  apply In_Znth in H7. destruct H7 as [i [? ?]].\n  rewrite <- (Z2Nat.id i) in H8 by lia. eapply svfl_dst_changed; eauto.\n  - intros. rewrite nat_inc_list_In_iff in H9. assumption.\n  - apply nat_inc_list_NoDup.\n  - rewrite nat_inc_list_In_iff. rewrite make_fields_eq_length in H7.\n    erewrite svfl_raw_fields; eauto. rewrite <- ZtoNat_Zlength.\n    apply Z2Nat.inj_lt; lia.\nQed.\n\nLemma no_scan_no_edge: forall g v, no_scan g v -> get_edges g v = nil.\nProof.\n  intros. unfold no_scan in H. apply tag_no_scan in H. unfold get_edges.\n  destruct (filter_sum_right (make_fields g v)) eqn:? . 1: reflexivity. exfalso.\n  assert (In e (filter_sum_right (make_fields g v))) by (rewrite Heql; left; auto).\n  rewrite <- filter_sum_right_In_iff in H0. clear l Heql. apply H. clear H.\n  unfold make_fields in H0. remember (raw_fields (vlabel g v)). clear Heql.\n  remember O. clear Heqn. revert n H0. induction l; simpl; intros; auto.\n  destruct a; [destruct s|]; simpl in H0;\n    [right; destruct H0; [inversion H | eapply IHl; eauto]..|left]; auto.\nQed.\n\nLemma svfl_copy_compatible: forall from to v l g1 g2,\n    from <> to -> graph_has_gen g1 to ->\n    scan_vertex_for_loop from to v l g1 g2 ->\n    copy_compatible g1 -> copy_compatible g2.\nProof.\n  do 4 intro. induction l; intros; inversion H1; subst. 1: assumption.\n  cut (copy_compatible g3).\n  - intros. apply (IHl g3); auto. erewrite <- fr_graph_has_gen; eauto.\n  - eapply fr_copy_compatible; eauto.\nQed.\n\nLemma svfl_no_dangling_dst: forall from to v l g1 g2,\n    graph_has_v g1 v -> raw_mark (vlabel g1 v) = false -> vgeneration v <> from ->\n    copy_compatible g1 -> graph_has_gen g1 to -> from <> to ->\n    scan_vertex_for_loop from to v l g1 g2 ->\n    (forall i,  In i l -> i < length (raw_fields (vlabel g1 v))) ->\n    no_dangling_dst g1 -> no_dangling_dst g2.\nProof.\n  do 4 intro. induction l; intros; inversion H5; subst. 1: assumption.\n  cut (no_dangling_dst g3).\n  - intros. apply (IHl g3); auto.\n    + eapply fr_graph_has_v; eauto.\n    + erewrite <- fr_raw_mark; eauto.\n    + eapply (fr_copy_compatible O from to); eauto.\n    + erewrite <- fr_graph_has_gen; eauto.\n    + intros. erewrite <- fr_raw_fields; eauto. apply H6. right; assumption.\n  - eapply fr_O_no_dangling_dst; eauto.\n    + simpl. intuition. rewrite Zlength_correct. apply inj_lt.\n      apply H6. left; reflexivity.\n    + simpl. constructor.\nQed.\n\nLemma svwl_no_edge2from: forall from to l g1 g2,\n    graph_has_gen g1 to -> scan_vertex_while_loop from to l g1 g2 ->\n    gen_unmarked g1 to -> copy_compatible g1 -> no_dangling_dst g1 ->\n    from <> to -> NoDup l ->\n    forall e i, In i l -> In e (get_edges g2 (to, i)) ->\n                vgeneration (dst g2 e) <> from.\nProof.\n  do 3 intro. induction l; intros; inversion H0; subst. 1: inversion H6.\n  - simpl in H6. destruct H6. 2: apply NoDup_cons_1 in H5; eapply IHl; eauto. subst a.\n    assert (In e (get_edges g1 (to, i))). {\n      unfold get_edges, make_fields in H7 |-*.\n      erewrite svwl_raw_fields; eauto. split; simpl; assumption. }\n    rewrite no_scan_no_edge in H6. 2: assumption. inversion H6.\n  - simpl in H6.\n    assert (graph_has_gen g3 to) by (erewrite <- svfl_graph_has_gen; eauto).\n    assert (gen_unmarked g3 to) by (eapply (svfl_gen_unmarked _ _ _ _ g1); eauto).\n    destruct H6.\n    + subst a. cut (vgeneration (dst g3 e) <> from).\n      * intros. cut (dst g3 e = dst g2 e). 1: intros HS; rewrite <- HS; assumption.\n        eapply svwl_dst_unchanged; eauto.\n        -- erewrite get_edges_fst; eauto. eapply (svfl_graph_has_v _ _ _ _ g1); eauto.\n           split; simpl; assumption.\n        -- intros. erewrite get_edges_fst; eauto. simpl.\n           apply NoDup_cons_2 in H5. assumption.\n      * assert (graph_has_v g1 (to, i)) by (split; simpl; assumption).\n        eapply svfl_no_edge2from; eauto. unfold get_edges, make_fields in H7 |-*.\n        erewrite svwl_raw_fields; eauto. eapply (svfl_graph_has_v _ _ _ _ g1); eauto.\n    + eapply (IHl g3); eauto.\n      * eapply (svfl_copy_compatible _ _ _ _ g1); eauto.\n      * eapply (svfl_no_dangling_dst from to); eauto.\n        -- split; simpl; assumption.\n        -- intros. rewrite nat_inc_list_In_iff in H13. assumption.\n      * apply NoDup_cons_1 in H5. assumption.\nQed.\n\nLemma no_dangling_dst_reset: forall g gen,\n    no_dangling_dst g -> no_edge2gen g gen ->\n    no_dangling_dst (reset_graph gen g).\nProof.\n  intros. unfold no_dangling_dst in *. red in H0. simpl. intros.\n  rewrite graph_has_v_reset in *. destruct H1. rewrite get_edges_reset in H2.\n  rewrite remove_ve_dst_unchanged. split.\n  - apply (H v); assumption.\n  - cut (vgeneration (dst g e) <> gen). 1: intuition. unfold gen2gen_no_edge in H0.\n    destruct e as [[vgen vidx] eidx]. pose proof H2. apply get_edges_fst in H2.\n    simpl in H2. subst v. simpl in *. apply H0; intuition. split; simpl; assumption.\nQed.\n\nLemma frr_copy_compatible: forall from to f_info roots g roots' g',\n    from <> to -> graph_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    graph_has_gen g to -> copy_compatible g -> from <> to ->\n    (forall i, In i l -> i < length roots) ->\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    graph_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_dsr_no_edge2gen: forall from to f_info roots roots' g g1 g2,\n    graph_has_gen g to -> from <> to -> gen_unmarked g to ->\n    copy_compatible g -> no_dangling_dst g ->\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' g1 ->\n    do_scan_relation from to (number_of_vertices (nth_gen g to)) g1 g2 ->\n    no_edge2gen g from -> no_edge2gen g2 from.\nProof.\n  intros. unfold no_edge2gen in *. intros. specialize (H8 _ H9).\n  destruct (Nat.eq_dec another to).\n  - subst. unfold gen2gen_no_edge in *. intros.\n    destruct H10. simpl fst in *. destruct H7 as [m [? ?]].\n    assert (graph_has_gen g1 to) by (erewrite <- frr_graph_has_gen; eauto).\n    assert (graph_has_v g (to, vidx) \\/ gen_v_num g to <= vidx < gen_v_num g2 to). {\n      eapply (svwl_graph_has_v_inv from to _ g1 g2) in H10; eauto. simpl in H10.\n      destruct H10.\n      - eapply (frr_graph_has_v_inv from _ _ _ g) in H10; eauto.\n        simpl in H10. destruct H10. 1: left; assumption.\n        right. destruct H10 as [_ [? ?]]. split; auto.\n        apply svwl_gen_v_num_to in H7; [lia | assumption].\n      - right. destruct H10 as [_ [? ?]]. split; auto.\n        apply frr_gen_v_num_to in H6; [lia | assumption]. } destruct H14.\n    + assert (graph_has_v g1 (to, vidx)) by\n          (eapply (frr_graph_has_v from to _ _ g); eauto).\n      assert (get_edges g (to, vidx) = get_edges g2 (to, vidx)). {\n        transitivity (get_edges g1 (to, vidx)); unfold get_edges, make_fields.\n        - erewrite frr_raw_fields; eauto.\n        - erewrite svwl_raw_fields; eauto. } rewrite <- H16 in H11.\n      assert (graph_has_e g (to, vidx, eidx)) by (split; simpl; assumption).\n      specialize (H8 _ _ H17).\n      erewrite (frr_dst_unchanged _ _ _ _ _ _ g1) in H8; eauto.\n      erewrite (svwl_dst_unchanged) in H8; eauto; simpl.\n      * eapply (frr_gen_unmarked _ _ _ _ g); eauto.\n      * repeat intro. rewrite nat_seq_In_iff in H19. destruct H19 as [? _].\n        destruct H14. simpl in H20. red in H20. lia.\n    + eapply svwl_no_edge2from; eauto.\n      * eapply (frr_gen_unmarked _ _ _ _ g); eauto.\n      * eapply (frr_copy_compatible from to _ _ g); eauto.\n      * eapply (frr_no_dangling_dst _ _ _ _ g); eauto.\n      * apply nat_seq_NoDup.\n      * rewrite nat_seq_In_iff. unfold gen_has_index in H12.\n        unfold gen_v_num in H14. lia.\n  - eapply (frr_gen2gen_no_edge _ _ _ _ g _ g1) in H8; eauto.\n    destruct H7 as [m [? ?]]. eapply (svwl_gen2gen_no_edge from to _ g1 g2); eauto.\n    + erewrite <- frr_graph_has_gen; eauto.\n    + eapply frr_gen_unmarked; eauto.\nQed.\n\nLemma svwl_no_dangling_dst: forall from to l g1 g2,\n    graph_has_gen g1 to -> scan_vertex_while_loop from to l g1 g2 ->\n    gen_unmarked g1 to -> copy_compatible g1 -> from <> to ->\n    no_dangling_dst g1 -> no_dangling_dst g2.\nProof.\n  do 3 intro. induction l; intros; inversion H0; subst;\n                [assumption | eapply IHl; eauto|]. cut (no_dangling_dst g3).\n  - intros. apply (IHl g3); auto.\n    + erewrite <- svfl_graph_has_gen; eauto.\n    + eapply svfl_gen_unmarked; eauto.\n    + eapply svfl_copy_compatible; eauto.\n  - eapply (svfl_no_dangling_dst from to _ _ g1); eauto.\n    + split; simpl; assumption.\n    + intros. rewrite nat_inc_list_In_iff in H5. 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\nDefinition no_backward_edge (g: LGraph): Prop :=\n  forall gen1 gen2, gen1 > gen2 -> gen2gen_no_edge g gen1 gen2.\n\nDefinition firstn_gen_clear (g: LGraph) (n: nat): Prop :=\n  forall i, i < n -> graph_gen_clear g i.\n\nDefinition safe_to_copy_to_except (g: LGraph) (gen: nat): Prop :=\n  forall n, n <> O -> n <> gen -> graph_has_gen g n -> safe_to_copy_gen g (pred n) n .\n\nDefinition safe_to_copy (g: LGraph): Prop :=\n  forall n, graph_has_gen g (S n) -> safe_to_copy_gen g n (S n).\n\nLemma stc_stcte_O_iff: forall g, safe_to_copy g <-> safe_to_copy_to_except g O.\nProof.\n  intros. unfold safe_to_copy, safe_to_copy_to_except. split; intros.\n  - destruct n. 1: contradiction. simpl. apply H; assumption.\n  - specialize (H (S n)). simpl in H. apply H; auto.\nQed.\n\nLemma fgc_nbe_no_edge2gen: forall g n,\n    firstn_gen_clear g n -> no_backward_edge g -> no_edge2gen g n.\nProof.\n  intros. red in H, H0 |-* . intros. red. intros. destruct H2. simpl in *.\n  destruct (lt_eq_lt_dec another n) as [[?|?]|?]. 2: contradiction.\n  - specialize (H _ l). red in H. destruct H2. simpl in *.\n    red in H4. rewrite H in H4. lia.\n  - assert (another > n) by lia. specialize (H0 _ _ H4). apply H0.\n    split; simpl; assumption.\nQed.\n\nDefinition add_new_gen (gi: graph_info) (gen_i: generation_info): graph_info :=\n  Build_graph_info (g_gen gi +:: gen_i) (app_not_nil (g_gen gi) gen_i).\n\nDefinition lgraph_add_new_gen (g: LGraph) (gen_i: generation_info): LGraph :=\n  Build_LabeledGraph _ _ _\n                     (pg_lg g) (vlabel g) (elabel g) (add_new_gen (glabel g) gen_i).\n\nDefinition new_gen_relation (gen: nat) (g1 g2: LGraph): Prop :=\n  if graph_has_gen_dec g1 gen then g1 = g2\n  else exists gen_i: generation_info, number_of_vertices gen_i = O /\\\n                                      g2 = lgraph_add_new_gen g1 gen_i.\n\nInductive garbage_collect_loop (f_info : fun_info)\n  : list nat -> roots_t -> LGraph -> roots_t -> LGraph -> 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: LGraph) (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: LGraph): Prop :=\n  exists n, garbage_collect_loop f_info (nat_inc_list (S n)) roots1 g1 roots2 g2 /\\\n            safe_to_copy_gen g2 n (S n).\n\nDefinition garbage_collect_condition (g: LGraph) (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 upd_heap_Zlength: forall (hp : heap) (sp : space) (i : Z),\n    0 <= i < MAX_SPACES -> Zlength (upd_Znth i (spaces hp) sp) = MAX_SPACES.\nProof.\n  intros. rewrite upd_Znth_Zlength; rewrite spaces_size; [reflexivity | assumption].\nQed.\n\nDefinition add_new_space (hp: heap) (sp: space) i (Hs: 0 <= i < MAX_SPACES): heap :=\n  Build_heap (upd_Znth i (spaces hp) sp) (upd_heap_Zlength hp sp i Hs).\n\nDefinition ti_add_new_space (ti: thread_info) (sp: space) i\n           (Hs: 0 <= i < MAX_SPACES): thread_info :=\n  Build_thread_info (ti_heap_p ti) (add_new_space (ti_heap ti) sp i Hs)\n                    (ti_args ti) (arg_size ti).\n\nLemma ang_nth_old: forall g gi gen,\n    graph_has_gen g gen -> nth_gen (lgraph_add_new_gen g gi) gen = nth_gen g gen.\nProof. intros. unfold nth_gen. simpl. rewrite app_nth1; [reflexivity|assumption]. Qed.\n\nLemma ang_nth_new: forall g gi,\n    nth_gen (lgraph_add_new_gen g gi) (length (g_gen (glabel g))) = gi.\nProof.\n  intros. unfold nth_gen. simpl. rewrite app_nth2 by lia. rewrite Nat.sub_diag.\n  simpl. reflexivity.\nQed.\n\nLemma ans_nth_old: forall ti sp i (Hs: 0 <= i < MAX_SPACES) gen,\n    gen <> Z.to_nat i -> nth_space (ti_add_new_space ti sp i Hs) gen =\n                         nth_space ti gen.\nProof.\n  intros. rewrite !nth_space_Znth. simpl. rewrite upd_Znth_diff_strong.\n  - reflexivity.\n  - rewrite spaces_size. assumption.\n  - intro. apply H. subst. rewrite Nat2Z.id. reflexivity.\nQed.\n\nLemma ans_nth_new: forall ti sp i (Hs: 0 <= i < MAX_SPACES),\n    nth_space (ti_add_new_space ti sp i Hs) (Z.to_nat i) = sp.\nProof.\n  intros. rewrite nth_space_Znth. simpl. rewrite Z2Nat.id by lia.\n  rewrite upd_Znth_same; [reflexivity | rewrite spaces_size; assumption].\nQed.\n\nLemma ang_graph_has_gen: forall g gi gen,\n    graph_has_gen (lgraph_add_new_gen g gi) gen <->\n    graph_has_gen g gen \\/ gen = length (g_gen (glabel g)).\nProof.\n  intros. unfold graph_has_gen. simpl. rewrite app_length. simpl. lia.\nQed.\n\nLemma gti_compatible_add: forall g ti gi sp i (Hs: 0 <= i < MAX_SPACES),\n    graph_thread_info_compatible g ti ->\n    ~ graph_has_gen g (Z.to_nat i) -> graph_has_gen g (Z.to_nat (i - 1)) ->\n    (forall (gr: LGraph), generation_space_compatible gr (Z.to_nat i, gi, sp)) ->\n    graph_thread_info_compatible (lgraph_add_new_gen g gi)\n                                 (ti_add_new_space ti sp i Hs).\nProof.\n  intros. unfold graph_thread_info_compatible in *. destruct H as [? [? ?]].\n  assert (length (g_gen (glabel g)) = Z.to_nat i). {\n    clear -H0 H1. unfold graph_has_gen in *.\n    rewrite Z2Nat.inj_sub in H1 by lia. simpl in H1. lia. }\n  pose proof (spaces_size (ti_heap ti)).\n  assert (length (g_gen (glabel (lgraph_add_new_gen g gi))) <=\n          length (spaces (ti_heap (ti_add_new_space ti sp i Hs))))%nat. {\n    simpl. rewrite <- !ZtoNat_Zlength, upd_Znth_Zlength by lia.\n    rewrite H6, ZtoNat_Zlength, app_length, H5. simpl. change (S O) with (Z.to_nat 1).\n    rewrite <- Z2Nat.inj_add, <- Z2Nat.inj_le by lia. lia. }\n  split; [|split]; auto.\n  - rewrite gsc_iff in H |- * by assumption. intros.\n    apply ang_graph_has_gen in H8. destruct H8.\n    + rewrite ang_nth_old by assumption. rewrite ans_nth_old.\n      1: apply H; assumption. red in H8. rewrite H5 in H8. lia.\n    + subst gen. rewrite ang_nth_new, H5, ans_nth_new. apply H2.\n  - simpl. rewrite <- upd_Znth_map. rewrite app_length. rewrite H5 in *. simpl.\n    change (S O) with (Z.to_nat 1).\n    rewrite <- Z2Nat.inj_add, <- sublist_skip in * by lia.\n    rewrite upd_Znth_Zlength; rewrite Zlength_map, spaces_size in *. 2: assumption.\n    rewrite sublist_upd_Znth_r. 2: lia. 2: rewrite Zlength_map, spaces_size; lia.\n    apply Forall_incl with\n        (sublist i MAX_SPACES (map space_start (spaces (ti_heap ti)))). 2: assumption.\n    rewrite Z.add_comm. replace MAX_SPACES with (MAX_SPACES - i + i) at 1 by lia.\n    rewrite <- sublist_sublist with (j := MAX_SPACES) by lia.\n    unfold incl. intro a. apply sublist_In.\nQed.\n\nLemma ang_graph_has_v: forall g gi v,\n    graph_has_v g v -> graph_has_v (lgraph_add_new_gen g gi) v.\nProof.\n  intros. destruct v as [gen idx]. destruct H; split; simpl in *.\n  - unfold graph_has_gen in *. simpl. rewrite app_length. simpl. lia.\n  - unfold gen_has_index in *. rewrite ang_nth_old; assumption.\nQed.\n\nLemma ang_roots_graph_compatible: forall roots g gi,\n    roots_graph_compatible roots g ->\n    roots_graph_compatible roots (lgraph_add_new_gen g gi).\nProof.\n  intros. unfold roots_graph_compatible in *. rewrite Forall_forall in *. intros.\n  apply ang_graph_has_v. apply H. assumption.\nQed.\n\nLemma ang_roots_compatible: forall roots out g gi,\n    roots_compatible g out roots ->\n    roots_compatible (lgraph_add_new_gen g gi) out roots.\nProof. intros. destruct H. split; auto. apply ang_roots_graph_compatible. auto. Qed.\n\nLemma ang_graph_has_v_inv: forall g gi v,\n    number_of_vertices gi = O -> graph_has_v (lgraph_add_new_gen g gi) v ->\n    graph_has_v g v.\nProof.\n  intros. destruct v as [gen idx]. destruct H0; split; simpl in *.\n  - apply ang_graph_has_gen in H0. destruct H0; auto. red in H1. exfalso. subst.\n    rewrite ang_nth_new, H in H1. lia.\n  - apply ang_graph_has_gen in H0. red in H1. destruct H0.\n    + rewrite ang_nth_old in H1; assumption.\n    + exfalso. subst. rewrite ang_nth_new, H in H1. lia.\nQed.\n\nLemma ang_outlier_compatible: forall g gi out,\n    number_of_vertices gi = O -> outlier_compatible g out ->\n    outlier_compatible (lgraph_add_new_gen g gi) out.\nProof.\n  intros. unfold outlier_compatible in *. intros.\n  apply ang_graph_has_v_inv in H1; auto. simpl. apply H0. assumption.\nQed.\n\nLemma ang_vertex_address_old: forall (g : LGraph) (gi : generation_info) (v : VType),\n    graph_has_v g v ->\n    vertex_address (lgraph_add_new_gen g gi) v = vertex_address g v.\nProof.\n  intros. unfold vertex_address. f_equal. unfold gen_start. destruct H.\n  rewrite if_true by (rewrite ang_graph_has_gen; left; assumption).\n  rewrite if_true by assumption. rewrite ang_nth_old by assumption. reflexivity.\nQed.\n\nLemma fta_compatible_add: forall g ti gi sp i (Hs: 0 <= i < MAX_SPACES) fi roots,\n    fun_thread_arg_compatible g ti fi roots -> roots_graph_compatible roots g ->\n    fun_thread_arg_compatible (lgraph_add_new_gen g gi)\n                              (ti_add_new_space ti sp i Hs) fi roots.\nProof.\n  intros. unfold fun_thread_arg_compatible in *. simpl. rewrite <- H.\n  apply map_ext_in. intros. destruct a; [destruct s|]; simpl; try reflexivity.\n  apply ang_vertex_address_old. red in H0. rewrite Forall_forall in H0. apply H0.\n  rewrite <- filter_sum_right_In_iff. assumption.\nQed.\n\nLemma super_compatible_add: forall g ti gi sp i (Hs: 0 <= i < MAX_SPACES) fi roots out,\n    ~ graph_has_gen g (Z.to_nat i) -> graph_has_gen g (Z.to_nat (i - 1)) ->\n    (forall (gr: LGraph), generation_space_compatible gr (Z.to_nat i, gi, sp)) ->\n    number_of_vertices gi = O -> super_compatible (g, ti, roots) fi out ->\n    super_compatible (lgraph_add_new_gen g gi, ti_add_new_space ti sp i Hs, roots)\n                     fi out.\nProof.\n  intros. destruct H3 as [? [? [? ?]]]. split; [|split; [|split]].\n  - apply gti_compatible_add; assumption.\n  - apply fta_compatible_add; [|destruct H5]; assumption.\n  - apply ang_roots_compatible; assumption.\n  - apply ang_outlier_compatible; assumption.\nQed.\n\nLemma ti_size_spec_add: forall ti sp i (Hs: 0 <= i < MAX_SPACES),\n    total_space sp = nth_gen_size (Z.to_nat i) -> ti_size_spec ti ->\n    ti_size_spec (ti_add_new_space ti sp i Hs).\nProof.\n  intros. unfold ti_size_spec in *. rewrite Forall_forall in *. intros.\n  specialize (H0 _ H1). unfold nth_gen_size_spec in *.\n  destruct (Nat.eq_dec x (Z.to_nat i)); unfold gen_size.\n  - subst x. rewrite !ans_nth_new. if_tac; auto.\n  - rewrite !ans_nth_old; assumption.\nQed.\n\nLemma firstn_gen_clear_add: forall g gi i,\n    graph_has_gen g (Z.to_nat i) -> firstn_gen_clear g (Z.to_nat i) ->\n    firstn_gen_clear (lgraph_add_new_gen g gi) (Z.to_nat i).\nProof.\n  intros. unfold firstn_gen_clear, graph_gen_clear in *. intros. specialize (H0 _ H1).\n  rewrite ang_nth_old; auto. unfold graph_has_gen in *. lia.\nQed.\n\nLemma ans_space_address: forall ti sp i (Hs: 0 <= i < MAX_SPACES) j,\n    space_address (ti_add_new_space ti sp i Hs) (Z.to_nat j) =\n    space_address ti (Z.to_nat j).\nProof. intros. unfold space_address. simpl. reflexivity. Qed.\n\nLemma ang_make_header: forall g gi v,\n    make_header g v = make_header (lgraph_add_new_gen g gi) v.\nProof. intros. unfold make_header. reflexivity. Qed.\n\nLemma ang_make_fields_vals_old: forall g gi v,\n    graph_has_v g v -> copy_compatible g -> no_dangling_dst g ->\n    make_fields_vals g v = make_fields_vals (lgraph_add_new_gen g gi) v.\nProof.\n  intros. unfold make_fields_vals. simpl.\n  assert (map (field2val g) (make_fields g v) =\n          map (field2val (lgraph_add_new_gen g gi))\n              (make_fields (lgraph_add_new_gen g gi) v)). {\n    unfold make_fields. simpl. apply map_ext_in. intros.\n    destruct a; [destruct s|]; simpl; auto. rewrite ang_vertex_address_old; auto.\n    red in H1. apply (H1 v); auto. unfold get_edges.\n    rewrite <- filter_sum_right_In_iff. assumption. } rewrite <- H2.\n  destruct (raw_mark (vlabel g v)) eqn:?; auto. f_equal.\n  rewrite ang_vertex_address_old; auto. destruct (H0 _ H Heqb). assumption.\nQed.\n\nLemma ang_graph_gen_size_old: forall g gi gen,\n    graph_has_gen g gen -> graph_gen_size g gen =\n                           graph_gen_size (lgraph_add_new_gen g gi) gen.\nProof.\n  intros. unfold graph_gen_size. rewrite ang_nth_old by assumption.\n  apply fold_left_ext. intros. unfold vertex_size_accum. reflexivity.\nQed.\n\nLemma nth_gen_size_le_S: forall n : nat, nth_gen_size n <= nth_gen_size (S n).\nProof.\n  intros n. unfold nth_gen_size. rewrite Nat2Z.inj_succ, two_p_S by lia.\n  assert (two_p (Z.of_nat n) > 0) by (apply two_p_gt_ZERO; lia).\n  assert (0 < NURSERY_SIZE) by (vm_compute; reflexivity).\n  rewrite Z.mul_assoc, (Z.mul_comm NURSERY_SIZE 2).\n  assert (0 < NURSERY_SIZE * two_p (Z.of_nat n)). apply Z.mul_pos_pos; lia.\n  rewrite <- Z.add_diag, Z.mul_add_distr_r. lia.\nQed.\n\nLemma stcte_add: forall g gi i,\n    number_of_vertices gi = O -> safe_to_copy_to_except g i ->\n    safe_to_copy_to_except (lgraph_add_new_gen g gi) i.\nProof.\n  intros. unfold safe_to_copy_to_except in *. intros. rewrite ang_graph_has_gen in H3.\n  destruct H3.\n  - specialize (H0 _ H1 H2 H3). unfold safe_to_copy_gen in *.\n    rewrite <- ang_graph_gen_size_old; assumption.\n  - unfold safe_to_copy_gen. simpl. unfold graph_gen_size.\n    rewrite H3 at 4. rewrite ang_nth_new, H. unfold previous_vertices_size.\n    simpl. destruct n. 1: contradiction. simpl. rewrite Z.sub_0_r.\n    apply nth_gen_size_le_S.\nQed.\n\nLemma graph_unmarked_add: forall g gi,\n    number_of_vertices gi = O -> graph_unmarked g ->\n    graph_unmarked (lgraph_add_new_gen g gi).\nProof.\n  intros. unfold graph_unmarked in *. intros. apply ang_graph_has_v_inv in H1; auto.\n  simpl. apply H0. assumption.\nQed.\n\nLemma ang_get_edges: forall g gi v,\n    get_edges g v = get_edges (lgraph_add_new_gen g gi) v.\nProof. intros. unfold get_edges, make_fields. simpl. reflexivity. Qed.\n\nLemma no_backward_edge_add: forall g gi,\n    number_of_vertices gi = O -> no_backward_edge g ->\n    no_backward_edge (lgraph_add_new_gen g gi).\nProof.\n  intros. unfold no_backward_edge, gen2gen_no_edge in *. intros. simpl.\n  destruct H2. simpl in *. rewrite <- ang_get_edges in H3.\n  apply ang_graph_has_v_inv in H2; auto. apply H0; auto. split; simpl; auto.\nQed.\n\nLemma no_dangling_dst_add: forall g gi,\n    number_of_vertices gi = O -> no_dangling_dst g ->\n    no_dangling_dst (lgraph_add_new_gen g gi).\nProof.\n  intros. unfold no_dangling_dst in *. intros. simpl.\n  apply ang_graph_has_v_inv in H1; auto. rewrite <- ang_get_edges in H2.\n  apply ang_graph_has_v, (H0 v); auto.\nQed.\n\nLemma gcc_add: forall g ti gi sp i (Hs: 0 <= i < MAX_SPACES) roots fi,\n    number_of_vertices gi = O -> total_space sp = nth_gen_size (Z.to_nat i) ->\n    garbage_collect_condition g ti roots fi ->\n    garbage_collect_condition (lgraph_add_new_gen 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\nLemma ngs_0_lt: forall i, 0 < nth_gen_size i.\nProof.\n  intros. unfold nth_gen_size.\n  rewrite NURSERY_SIZE_eq, Zbits.Zshiftl_mul_two_p, Z.mul_1_l,\n  <- two_p_is_exp by lia.\n  cut (two_p (16 + Z.of_nat i) > 0); [|apply two_p_gt_ZERO]; lia.\nQed.\n\nLemma gc_cond_implies_do_gen_cons: forall g t_info roots f_info i,\n    safe_to_copy_to_except g i ->\n    graph_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. destruct H2 as [? [? [? [? ?]]]].\n  assert (graph_has_gen g i) by (unfold graph_has_gen in H0 |-*; lia).\n  split; [|split; [|split; [|split; [|split; [|split; [|split]]]]]]; auto.\n  - unfold safe_to_copy_to_except, safe_to_copy_gen in H. red.\n    unfold rest_gen_size. specialize (H (S i)). simpl in H.\n    destruct (gt_gs_compatible _ _ H1 _ H0) as [_ [_ ?]].\n    destruct (gt_gs_compatible _ _ H1 _ H7) as [_ [_ ?]].\n    fold (graph_gen_size g (S i)) in H8. fold (graph_gen_size g i) in H9.\n    rewrite <- H8. fold (gen_size t_info (S i)).\n    destruct (space_order (nth_space t_info i)) as [_ ?].\n    fold (gen_size t_info i) in H10. rewrite <- H9 in H10.\n    transitivity (gen_size t_info i). 1: assumption.\n    rewrite (ti_size_gen _ _ _ H1 H7 H6), (ti_size_gen _ _ _ H1 H0 H6).\n    apply H; [lia.. | assumption].\n  - apply graph_unmarked_copy_compatible; assumption.\n  - rewrite (ti_size_gen _ _ _ H1 H0 H6). apply ngs_0_lt.\n  - rewrite graph_gen_unmarked_iff in H2. apply H2.\nQed.\n\nLemma do_gen_no_dangling_dst: forall g1 g2 roots1 roots2 f_info from to,\n  graph_has_gen g1 to -> copy_compatible g1 -> gen_unmarked g1 to ->\n  Zlength roots1 = Zlength (live_roots_indices f_info) -> from <> to ->\n  roots_graph_compatible roots1 g1 -> firstn_gen_clear g1 from ->\n  no_backward_edge g1 ->\n  do_generation_relation from to f_info roots1 roots2 g1 g2 ->\n  no_dangling_dst g1 -> no_dangling_dst g2.\nProof.\n  intros. destruct H7 as [g3 [g4 [? [? ?]]]].\n  assert (no_dangling_dst g3) by (eapply (frr_no_dangling_dst from); eauto).\n  assert (no_dangling_dst g4). {\n    destruct H9 as [n [? ?]]. eapply (svwl_no_dangling_dst _ _ _ g3); eauto.\n    - rewrite <- frr_graph_has_gen; eauto.\n    - eapply frr_gen_unmarked; eauto.\n    - eapply frr_copy_compatible; eauto. }\n  subst g2. apply no_dangling_dst_reset; auto.\n  eapply frr_dsr_no_edge2gen; eauto. apply fgc_nbe_no_edge2gen; auto.\nQed.\n\nLemma fr_O_nth_gen_unchanged: forall from to p g1 g2,\n    graph_has_gen g1 to -> forward_relation from to O p g1 g2 ->\n    forall gen, gen <> to -> nth_gen g1 gen = nth_gen g2 gen.\nProof.\n  intros. inversion H0; subst; try reflexivity.\n  - rewrite lcv_nth_gen; auto.\n  - subst new_g. transitivity (nth_gen (lgraph_copy_v g1 (dst g1 e) to) gen).\n    2: reflexivity. rewrite lcv_nth_gen; [reflexivity | assumption..].\nQed.\n\nLemma frr_nth_gen_unchanged: forall from to f_info roots1 g1 roots2 g2,\n    graph_has_gen g1 to -> forward_roots_relation from to f_info roots1 g1 roots2 g2 ->\n    forall gen, gen <> to -> nth_gen g1 gen = nth_gen g2 gen.\nProof.\n  intros. induction H0. 1: reflexivity. rewrite <- IHforward_roots_loop.\n  - eapply fr_O_nth_gen_unchanged; eauto.\n  - rewrite <- fr_graph_has_gen; eauto.\nQed.\n\nLemma svfl_nth_gen_unchanged: forall from to v l g1 g2,\n    graph_has_gen g1 to -> scan_vertex_for_loop from to v l g1 g2 ->\n    forall gen, gen <> to -> nth_gen g1 gen = nth_gen g2 gen.\nProof.\n  intros. induction H0; subst; try reflexivity. transitivity (nth_gen g2 gen).\n  - eapply fr_O_nth_gen_unchanged; eauto.\n  - apply IHscan_vertex_for_loop. rewrite <- fr_graph_has_gen; eauto.\nQed.\n\nLemma svwl_nth_gen_unchanged: forall from to l g1 g2,\n    graph_has_gen g1 to -> scan_vertex_while_loop from to l g1 g2 ->\n    forall gen, gen <> to -> nth_gen g1 gen = nth_gen g2 gen.\nProof.\n  do 3 intro. induction l; intros; inversion H0; subst; try reflexivity.\n  1: apply IHl; auto. transitivity (nth_gen g3 gen).\n  - eapply svfl_nth_gen_unchanged; eauto.\n  - apply IHl; auto. rewrite <- svfl_graph_has_gen; eauto.\nQed.\n\nLemma frr_firstn_gen_clear: forall from to f_info roots1 g1 roots2 g2,\n    graph_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_nth_gen_unchanged; eauto. lia.\nQed.\n\nLemma svwl_firstn_gen_clear: forall from to l g1 g2,\n    graph_has_gen g1 to -> scan_vertex_while_loop from to l g1 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 <- (svwl_nth_gen_unchanged from); eauto. lia.\nQed.\n\nLemma firstn_gen_clear_reset: forall g i,\n    firstn_gen_clear g i -> firstn_gen_clear (reset_graph i g) (S i).\nProof.\n  intros. unfold firstn_gen_clear, graph_gen_clear in *. intros.\n  assert (i0 < i \\/ i0 = i)%nat by lia. destruct H1.\n  - rewrite reset_nth_gen_diff by lia. apply H; assumption.\n  - subst i0. unfold nth_gen. simpl. rewrite reset_nth_gen_info_same.\n    simpl. reflexivity.\nQed.\n\nLemma do_gen_firstn_gen_clear: forall g1 g2 roots1 roots2 f_info i,\n    do_generation_relation i (S i) f_info roots1 roots2 g1 g2 ->\n    graph_has_gen g1 (S i) -> firstn_gen_clear g1 i -> firstn_gen_clear g2 (S i).\nProof.\n  intros. destruct H as [g3 [g4 [? [? ?]]]].\n  eapply frr_firstn_gen_clear in H1; eauto. destruct H2 as [n [? ?]].\n  eapply svwl_firstn_gen_clear in H1; eauto. 2: erewrite <- frr_graph_has_gen; eauto.\n  subst g2. apply firstn_gen_clear_reset. assumption.\nQed.\n\nLemma do_gen_no_backward_edge: forall g1 g2 roots1 roots2 f_info i,\n    do_generation_relation i (S i) f_info roots1 roots2 g1 g2 ->\n    no_dangling_dst g2 -> graph_has_gen g1 (S i) -> gen_unmarked g1 (S i) ->\n    firstn_gen_clear g1 i -> no_backward_edge g1 -> no_backward_edge g2.\nProof.\n  intros. unfold no_backward_edge in *. intros. destruct (Nat.eq_dec gen1 (S i)).\n  - red. intros. destruct H6. simpl in *. eapply do_gen_firstn_gen_clear in H3; eauto.\n    subst. specialize (H0 _ H6 _ H7). destruct H0. red in H8. intro. rewrite H9 in H8.\n    red in H3. assert (gen2 < S i)%nat by lia. specialize (H3 _ H10). red in H3.\n    rewrite H3 in H8. lia.\n  - destruct H as [g3 [g4 [? [? ?]]]]. subst g2. apply gen2gen_no_edge_reset.\n    assert (gen2gen_no_edge g3 gen1 gen2) by (eapply frr_gen2gen_no_edge; eauto).\n    destruct H6 as [m [? ?]]. eapply (svwl_gen2gen_no_edge i _ _ g3); eauto.\n    + rewrite <- frr_graph_has_gen; eauto.\n    + eapply frr_gen_unmarked; eauto.\nQed.\n\nLemma ti_relation_size_spec: forall t_info1 t_info2 : thread_info,\n    thread_info_relation t_info1 t_info2 ->\n    ti_size_spec t_info1 -> ti_size_spec t_info2.\nProof.\n  intros. unfold ti_size_spec in *. rewrite Forall_forall in *. intros.\n  specialize (H0 _ H1). unfold nth_gen_size_spec in *. destruct H as [? [? ?]].\n  rewrite <- H2, <- H3. assumption.\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 -> graph_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 (gen_unmarked g1 (S i)) by (rewrite graph_gen_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 fr_vertex_size: forall depth from to p g1 g2,\n    graph_has_gen g1 to -> forward_relation from to depth p g1 g2 ->\n    forall v, graph_has_v g1 v -> vertex_size g1 v = vertex_size g2 v.\nProof.\n  intros. remember (fun g v (x: nat) => graph_has_v g v) as Q.\n  remember (fun g1 g2 v => vertex_size g1 v = vertex_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). subst Q P R.\n  apply H2; clear H2; intros; try assumption; try reflexivity.\n  - rewrite H2. assumption.\n  - rewrite lcv_vertex_size_old; [reflexivity | assumption..].\n  - apply (fr_graph_has_v _ _ _ _ _ _ H2 H3 _ H4).\n  - apply lcv_graph_has_v_old; assumption.\nQed.\n\nLemma fr_O_graph_gen_size_unchanged: forall from to p g1 g2,\n    graph_has_gen g1 to -> forward_relation from to O p g1 g2 ->\n    forall gen, graph_has_gen g1 gen -> gen <> to ->\n                graph_gen_size g1 gen = graph_gen_size g2 gen.\nProof.\n  intros. unfold graph_gen_size.\n  erewrite <- (fr_O_nth_gen_unchanged from to _ g1 g2); eauto.\n  unfold previous_vertices_size. apply fold_left_ext. intros.\n  unfold vertex_size_accum. f_equal. rewrite nat_inc_list_In_iff in H3.\n  eapply (fr_vertex_size O from to); eauto. split; simpl; assumption.\nQed.\n\nLemma fr_O_stcg: forall from to p g1 g2,\n    graph_has_gen g1 to -> forward_relation from to O p g1 g2 ->\n    forall gen1 gen2, graph_has_gen g1 gen2 -> gen2 <> to ->\n                      safe_to_copy_gen g1 gen1 gen2 -> safe_to_copy_gen g2 gen1 gen2.\nProof.\n  intros. unfold safe_to_copy_gen in *.\n  erewrite <- (fr_O_graph_gen_size_unchanged from to); eauto.\nQed.\n\nLemma frr_stcg: forall from to f_info roots1 g1 roots2 g2,\n    graph_has_gen g1 to -> forward_roots_relation from to f_info roots1 g1 roots2 g2 ->\n    forall gen1 gen2, graph_has_gen g1 gen2 -> gen2 <> to ->\n                      safe_to_copy_gen g1 gen1 gen2 -> safe_to_copy_gen 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 svfl_stcg: forall from to v l g1 g2,\n    graph_has_gen g1 to -> scan_vertex_for_loop from to v l g1 g2 ->\n    forall gen1 gen2, graph_has_gen g1 gen2 -> gen2 <> to ->\n                      safe_to_copy_gen g1 gen1 gen2 -> safe_to_copy_gen g2 gen1 gen2.\nProof.\n  intros. induction H0; subst; try assumption. apply IHscan_vertex_for_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 svwl_stcg: forall from to l g1 g2,\n    graph_has_gen g1 to -> scan_vertex_while_loop from to l g1 g2 ->\n    forall gen1 gen2, graph_has_gen g1 gen2 -> gen2 <> to ->\n                      safe_to_copy_gen g1 gen1 gen2 -> safe_to_copy_gen g2 gen1 gen2.\nProof.\n  do 3 intro. induction l; intros; inversion H0; subst; try assumption.\n  1: apply (IHl g1); auto. apply (IHl g3); auto.\n  - erewrite <- (svfl_graph_has_gen from to); eauto.\n  - erewrite <- (svfl_graph_has_gen from to); eauto.\n  - eapply (svfl_stcg from to); eauto.\nQed.\n\nLemma reset_graph_gen_size_eq: forall g i j,\n    i <> j -> graph_gen_size (reset_graph i g) j = graph_gen_size g j.\nProof.\n  intros. unfold graph_gen_size.\n  rewrite pvs_reset_unchanged, reset_nth_gen_diff; auto.\nQed.\n\nLemma reset_stct: forall g i gen1 gen2,\n    i <> gen2 -> safe_to_copy_gen g gen1 gen2 ->\n    safe_to_copy_gen (reset_graph i g) gen1 gen2.\nProof.\n  intros. unfold safe_to_copy_gen in *. rewrite reset_graph_gen_size_eq; auto.\nQed.\n\nLemma do_gen_stcte: forall g1 roots1 g2 roots2 f_info i,\n    safe_to_copy_to_except g1 i -> graph_has_gen g1 (S i) ->\n    do_generation_relation i (S i) f_info roots1 roots2 g1 g2 ->\n    safe_to_copy_to_except g2 (S i).\nProof.\n  intros. unfold safe_to_copy_to_except in *. intros.\n  destruct H1 as [g3 [g4 [? [? ?]]]]. destruct (Nat.eq_dec n i).\n  - subst. red. unfold graph_gen_size, nth_gen. simpl.\n    rewrite reset_nth_gen_info_same. simpl. unfold previous_vertices_size.\n    simpl. destruct i. 1: contradiction. simpl. rewrite Z.sub_0_r.\n    apply nth_gen_size_le_S.\n  - subst g2. apply reset_stct; auto. destruct H5 as [m [? ?]].\n    rewrite graph_has_gen_reset in H4.\n    assert (graph_has_gen g3 (S i)) by (erewrite <- frr_graph_has_gen; eauto).\n    assert (graph_has_gen g3 n) by (erewrite svwl_graph_has_gen; eauto).\n    eapply (svwl_stcg i (S i) _ g3); eauto.\n    assert (graph_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.\n\nLemma safe_to_copy_complete: forall g i,\n    safe_to_copy_to_except g (S i) -> safe_to_copy_gen g i (S i) -> safe_to_copy g.\nProof.\n  intros. unfold safe_to_copy_to_except in H. unfold safe_to_copy. intros.\n  destruct (Nat.eq_dec n i).\n  - subst. assumption.\n  - specialize (H (S n)). simpl in H. apply H; auto.\nQed.\n\nLemma Int64_eq_false: forall x y : int64, Int64.eq x y = false -> x <> y.\nProof.\n  intros. destruct x, y. unfold Int64.eq in H. simpl in H.\n  destruct (zeq intval intval0). 1: inversion H. intro. inversion H0. easy.\nQed.\n\nLemma raw_fields_range2: forall r,\n    Zlength (raw_fields r) <= if Archi.ptr64 then Int64.max_signed else Int.max_signed.\nProof.\n  intros. pose proof (raw_fields_range r). remember (Zlength (raw_fields r)).\n  clear Heqz. cbv delta[Archi.ptr64]. simpl. rewrite <- Z.lt_succ_r. destruct H.\n  transitivity (two_p (WORD_SIZE * 8 - 10)); auto. now vm_compute.\nQed.\n\nLemma ltu64_repr_false: forall x y,\n    0 <= y <= Int64.max_unsigned -> 0 <= x <= Int64.max_unsigned ->\n    Int64.ltu (Int64.repr x) (Int64.repr y) = false -> x >= y.\nProof.\n  intros. unfold Int64.ltu in H1. rewrite !Int64.unsigned_repr in H1; auto.\n  if_tac in H1; auto. inversion H1.\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/GCGraph.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.26676049116565737}}
{"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 PCMLarge.\n\nSet Implicit Arguments.\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  Variable wf_stt: Type -> Type -> WF.\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) R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel)\n          (lsim: bool -> bool -> URA.car -> ((wf_stt R_src R_tgt).(T) * itree srcE R_src) -> itree tgtE R_tgt -> shared_rel)\n          (_lsim: bool -> bool -> URA.car -> ((wf_stt R_src R_tgt).(T) * itree srcE R_src) -> itree tgtE R_tgt -> shared_rel)\n    :\n    bool -> bool -> URA.car -> ((wf_stt R_src R_tgt).(T) * itree srcE R_src) -> itree tgtE R_tgt -> shared_rel :=\n  | lsim_ret\n      f_src f_tgt r_ctx o o0\n      ths im_src im_tgt st_src st_tgt\n      r_src r_tgt\n      (LT: (wf_stt R_src R_tgt).(lt) o0 o)\n      (LSIM: RR r_src r_tgt r_ctx (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid RR lsim _lsim f_src f_tgt r_ctx (o, 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 o\n      ths im_src im_tgt st_src st_tgt\n      itr_src itr_tgt\n      (LSIM: _lsim true f_tgt r_ctx (o, itr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid RR lsim _lsim f_src f_tgt r_ctx (o, Tau itr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_chooseL\n      f_src f_tgt r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      X ktr_src itr_tgt\n      (LSIM: exists x, _lsim true f_tgt r_ctx (o, ktr_src x) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid RR lsim _lsim f_src f_tgt r_ctx (o, 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 o\n      ths im_src im_tgt st_src st_tgt\n      X rmw ktr_src itr_tgt\n      (LSIM: _lsim true f_tgt r_ctx (o, ktr_src (snd (rmw st_src) : X)) itr_tgt (ths, im_src, im_tgt, fst (rmw st_src), st_tgt))\n    :\n    __lsim tid RR lsim _lsim f_src f_tgt r_ctx (o, 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 o\n      ths im_src im_tgt st_src st_tgt\n      ktr_src itr_tgt\n      (LSIM: _lsim true f_tgt r_ctx (o, ktr_src tid) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid RR lsim _lsim f_src f_tgt r_ctx (o, 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 o\n      ths im_src im_tgt st_src st_tgt\n      ktr_src itr_tgt\n    :\n    __lsim tid RR lsim _lsim f_src f_tgt r_ctx (o, 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 o\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 true f_tgt r_ctx (o, ktr_src tt) itr_tgt (ths, im_src1, im_tgt, st_src, st_tgt)>>))\n    :\n    __lsim tid RR lsim _lsim f_src f_tgt r_ctx (o, 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 o\n      ths im_src im_tgt st_src st_tgt\n      itr_src itr_tgt\n      (LSIM: _lsim f_src true r_ctx (o, itr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid RR lsim _lsim f_src f_tgt r_ctx (o, itr_src) (Tau itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_chooseR\n      f_src f_tgt r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      X itr_src ktr_tgt\n      (LSIM: forall x, _lsim f_src true r_ctx (o, itr_src) (ktr_tgt x) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid RR lsim _lsim f_src f_tgt r_ctx (o, 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 o\n      ths im_src im_tgt st_src st_tgt\n      X rmw itr_src ktr_tgt\n      (LSIM: _lsim f_src true r_ctx (o, itr_src) (ktr_tgt (snd (rmw st_tgt) : X)) (ths, im_src, im_tgt, st_src, fst (rmw st_tgt)))\n    :\n    __lsim tid RR lsim _lsim f_src f_tgt r_ctx (o, 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 o\n      ths im_src im_tgt st_src st_tgt\n      itr_src ktr_tgt\n      (LSIM: _lsim f_src true r_ctx (o, itr_src) (ktr_tgt tid) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid RR lsim _lsim f_src f_tgt r_ctx (o, 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 o\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 f_src true r_ctx (o, itr_src) (ktr_tgt tt) (ths, im_src, im_tgt1, st_src, st_tgt)>>))\n    :\n    __lsim tid RR lsim _lsim f_src f_tgt r_ctx (o, 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 o\n      ths im_src im_tgt st_src st_tgt\n      fn args ktr_src ktr_tgt\n      (LSIM: forall ret,\n          lsim true true r_ctx (o, ktr_src ret) (ktr_tgt ret) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid RR lsim _lsim f_src f_tgt r_ctx (o, 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 o\n      ths im_src im_tgt st_src st_tgt\n      fn args ktr_src itr_tgt\n    : __lsim tid RR lsim _lsim f_src f_tgt r_ctx (o, trigger (Call fn args) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n\n  | lsim_yieldR\n      f_src f_tgt r_ctx0 o0\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      o1\n      (STUTTER: (wf_stt R_src R_tgt).(lt) o1 o0)\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 true true r_ctx1 (o1, trigger (Yield) >>= ktr_src) (ktr_tgt tt) (ths1, im_src1, im_tgt2, st_src1, st_tgt1)>>))\n    :\n    __lsim tid RR lsim _lsim f_src f_tgt r_ctx0 (o0, trigger (Yield) >>= ktr_src) (trigger (Yield) >>= ktr_tgt) (ths0, im_src0, im_tgt0, st_src0, st_tgt0)\n  | lsim_yieldL\n      f_src f_tgt r_ctx o0\n      ths im_src0 im_tgt st_src st_tgt\n      ktr_src itr_tgt\n      (LSIM: exists im_src1 o1,\n          (<<FAIR: fair_update im_src0 im_src1 (prism_fmap inlp (tids_fmap tid ths))>>) /\\\n            (<<LSIM: _lsim true f_tgt r_ctx (o1, ktr_src tt) itr_tgt (ths, im_src1, im_tgt, st_src, st_tgt)>>))\n    :\n    __lsim tid RR lsim _lsim f_src f_tgt r_ctx (o0, trigger (Yield) >>= ktr_src) itr_tgt (ths, im_src0, im_tgt, st_src, st_tgt)\n\n  | lsim_progress\n      r_ctx o\n      ths im_src im_tgt st_src st_tgt\n      itr_src itr_tgt\n      (LSIM: lsim false false r_ctx (o, itr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid RR lsim _lsim true true r_ctx (o, 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 -> ((wf_stt R_src R_tgt).(T) * itree srcE R_src) -> itree tgtE R_tgt -> shared_rel :=\n    paco6 (fun r => pind6 (__lsim tid RR r) top6) bot6.\n\n  Lemma __lsim_mon tid R0 R1 (RR: R0 -> R1 -> _ -> _):\n    forall r r' (LE: r <6= r'), (__lsim tid RR r) <7= (__lsim tid RR r').\n  Proof.\n    ii. inv PR; try (econs; eauto; fail).\n    eapply lsim_yieldR; eauto. i. hexploit LSIM; eauto.\n  Qed.\n\n  Lemma _lsim_mon tid R0 R1 (RR: R0 -> R1 -> _ -> _): forall r, monotone6 (__lsim tid RR 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 R0 R1 (RR: R0 -> R1 -> _ -> _):\n    forall q, monotone6 (fun r => pind6 (__lsim tid RR r) q).\n  Proof.\n    ii. eapply pind6_mon_gen; eauto.\n    ii. eapply __lsim_mon; eauto.\n  Qed.\n\n  Variant lsim_indC tid R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel)\n          (r: bool -> bool -> URA.car -> ((wf_stt R_src R_tgt).(T) * itree srcE R_src) -> itree tgtE R_tgt -> shared_rel)\n    :\n    bool -> bool -> URA.car -> ((wf_stt R_src R_tgt).(T) * itree srcE R_src) -> itree tgtE R_tgt -> shared_rel :=\n    | lsim_indC_ret\n        f_src f_tgt r_ctx o o0\n        ths im_src im_tgt st_src st_tgt\n        r_src r_tgt\n        (LT: (wf_stt R_src R_tgt).(lt) o0 o)\n        (LSIM: RR r_src r_tgt r_ctx (ths, im_src, im_tgt, st_src, st_tgt))\n      :\n      lsim_indC tid RR r f_src f_tgt r_ctx (o, Ret r_src) (Ret r_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n\n    | lsim_indC_tauL\n        f_src f_tgt r_ctx o\n        ths im_src im_tgt st_src st_tgt\n        itr_src itr_tgt\n        (LSIM: r true f_tgt r_ctx (o, itr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n      :\n      lsim_indC tid RR r f_src f_tgt r_ctx (o, Tau itr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n    | lsim_indC_chooseL\n        f_src f_tgt r_ctx o\n        ths im_src im_tgt st_src st_tgt\n        X ktr_src itr_tgt\n        (LSIM: exists x, r true f_tgt r_ctx (o, ktr_src x) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n      :\n      lsim_indC tid RR r f_src f_tgt r_ctx (o, trigger (Choose X) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n    | lsim_indC_rmwL\n        f_src f_tgt r_ctx o\n        ths im_src im_tgt st_src st_tgt\n        X rmw ktr_src itr_tgt\n        (LSIM: r true f_tgt r_ctx (o, ktr_src (snd (rmw st_src) : X)) itr_tgt (ths, im_src, im_tgt, fst (rmw st_src), st_tgt))\n      :\n      lsim_indC tid RR r f_src f_tgt r_ctx (o, trigger (Rmw rmw) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n    | lsim_indC_tidL\n        f_src f_tgt r_ctx o\n        ths im_src im_tgt st_src st_tgt\n        ktr_src itr_tgt\n        (LSIM: r true f_tgt r_ctx (o, ktr_src tid) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n      :\n      lsim_indC tid RR r f_src f_tgt r_ctx (o, trigger (GetTid) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n    | lsim_indC_UB\n        f_src f_tgt r_ctx o\n        ths im_src im_tgt st_src st_tgt\n        ktr_src itr_tgt\n      :\n      lsim_indC tid RR r f_src f_tgt r_ctx (o, trigger (Undefined) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n    | lsim_indC_fairL\n        f_src f_tgt r_ctx o\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: r true f_tgt r_ctx (o, ktr_src tt) itr_tgt (ths, im_src1, im_tgt, st_src, st_tgt)>>))\n      :\n      lsim_indC tid RR r f_src f_tgt r_ctx (o, trigger (Fair f) >>= ktr_src) itr_tgt (ths, im_src0, im_tgt, st_src, st_tgt)\n\n    | lsim_indC_tauR\n        f_src f_tgt r_ctx o\n        ths im_src im_tgt st_src st_tgt\n        itr_src itr_tgt\n        (LSIM: r f_src true r_ctx (o, itr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n      :\n      lsim_indC tid RR r f_src f_tgt r_ctx (o, itr_src) (Tau itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n    | lsim_indC_chooseR\n        f_src f_tgt r_ctx o\n        ths im_src im_tgt st_src st_tgt\n        X itr_src ktr_tgt\n        (LSIM: forall x, r f_src true r_ctx (o, itr_src) (ktr_tgt x) (ths, im_src, im_tgt, st_src, st_tgt))\n      :\n      lsim_indC tid RR r f_src f_tgt r_ctx (o, itr_src) (trigger (Choose X) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n    | lsim_indC_rmwR\n        f_src f_tgt r_ctx o\n        ths im_src im_tgt st_src st_tgt\n        X rmw itr_src ktr_tgt\n        (LSIM: r f_src true r_ctx (o, itr_src) (ktr_tgt (snd (rmw st_tgt) : X)) (ths, im_src, im_tgt, st_src, fst (rmw st_tgt)))\n      :\n      lsim_indC tid RR r f_src f_tgt r_ctx (o, itr_src) (trigger (Rmw rmw) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n    | lsim_indC_tidR\n        f_src f_tgt r_ctx o\n        ths im_src im_tgt st_src st_tgt\n        itr_src ktr_tgt\n        (LSIM: r f_src true r_ctx (o, itr_src) (ktr_tgt tid) (ths, im_src, im_tgt, st_src, st_tgt))\n      :\n      lsim_indC tid RR r f_src f_tgt r_ctx (o, itr_src) (trigger (GetTid) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n    | lsim_indC_fairR\n        f_src f_tgt r_ctx o\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: r f_src true r_ctx (o, itr_src) (ktr_tgt tt) (ths, im_src, im_tgt1, st_src, st_tgt)>>))\n      :\n      lsim_indC tid RR r f_src f_tgt r_ctx (o, itr_src) (trigger (Fair f) >>= ktr_tgt) (ths, im_src, im_tgt0, st_src, st_tgt)\n\n    | lsim_indC_observe\n        f_src f_tgt r_ctx o\n        ths im_src im_tgt st_src st_tgt\n        fn args ktr_src ktr_tgt\n        (LSIM: forall ret,\n            r true true r_ctx (o, ktr_src ret) (ktr_tgt ret) (ths, im_src, im_tgt, st_src, st_tgt))\n      :\n      lsim_indC tid RR r f_src f_tgt r_ctx (o, trigger (Observe fn args) >>= ktr_src) (trigger (Observe fn args) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n\n    | lsim_indC_call\n        f_src f_tgt r_ctx o\n        ths im_src im_tgt st_src st_tgt\n        fn args ktr_src itr_tgt\n      : lsim_indC tid RR r f_src f_tgt r_ctx (o, trigger (Call fn args) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n\n    | lsim_indC_yieldR\n        f_src f_tgt r_ctx0 o0\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        o1\n        (STUTTER: (wf_stt R_src R_tgt).(lt) o1 o0)\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: r true true r_ctx1 (o1, trigger (Yield) >>= ktr_src) (ktr_tgt tt) (ths1, im_src1, im_tgt2, st_src1, st_tgt1)>>))\n      :\n      lsim_indC tid RR r f_src f_tgt r_ctx0 (o0, trigger (Yield) >>= ktr_src) (trigger (Yield) >>= ktr_tgt) (ths0, im_src0, im_tgt0, st_src0, st_tgt0)\n    | lsim_indC_yieldL\n        f_src f_tgt r_ctx o0\n        ths im_src0 im_tgt st_src st_tgt\n        ktr_src itr_tgt\n        (LSIM: exists im_src1 o1,\n            (<<FAIR: fair_update im_src0 im_src1 (prism_fmap inlp (tids_fmap tid ths))>>) /\\\n              (<<LSIM: r true f_tgt r_ctx (o1, ktr_src tt) itr_tgt (ths, im_src1, im_tgt, st_src, st_tgt)>>))\n      :\n      lsim_indC tid RR r f_src f_tgt r_ctx (o0, trigger (Yield) >>= ktr_src) itr_tgt (ths, im_src0, im_tgt, st_src, st_tgt)\n\n    | lsim_indC_progress\n        r_ctx o\n        ths im_src im_tgt st_src st_tgt\n        itr_src itr_tgt\n        (LSIM: r false false r_ctx (o, itr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n      :\n      lsim_indC tid RR r true true r_ctx (o, itr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  .\n\n  Lemma lsim_indC_mon tid R0 R1 (RR: R0 -> R1 -> _ -> _): monotone6 (lsim_indC tid RR).\n  Proof.\n    ii. inv IN; try (econs; eauto; fail).\n    { des; econs; eauto. }\n    { des; econs; eauto. }\n    { econs. i. specialize (LSIM _ FAIR). eauto. }\n    { econs; eauto. i. hexploit LSIM; eauto. }\n    { des; econs; eauto. esplits; eauto. }\n  Qed.\n\n  Hint Resolve lsim_indC_mon: paco.\n\n  Lemma lsim_indC_wrepectful tid R0 R1 (RR: R0 -> R1 -> _ -> _):\n    wrespectful6 (fun r => pind6 (__lsim tid RR r) top6) (lsim_indC tid RR).\n  Proof.\n    econs; eauto with paco.\n    i. eapply pind6_fold. inv PR.\n    { eapply lsim_ret; eauto. }\n    { eapply lsim_tauL; eauto. split; ss.\n      eapply GF in LSIM. eapply pind6_mon_gen; ss. eauto.\n      i. eapply __lsim_mon. 2: eauto. i. eapply rclo6_base; auto.\n    }\n    { des. eapply lsim_chooseL; eauto. esplits; eauto. split; ss.\n      eapply GF in LSIM. eapply pind6_mon_gen; ss. eauto.\n      i. eapply __lsim_mon. 2: eauto. i. eapply rclo6_base; auto.\n    }\n    { eapply lsim_rmwL; eauto. split; ss.\n      eapply GF in LSIM. eapply pind6_mon_gen; ss. eauto.\n      i. eapply __lsim_mon. 2: eauto. i. eapply rclo6_base; auto.\n    }\n    { eapply lsim_tidL; eauto. split; ss.\n      eapply GF in LSIM. eapply pind6_mon_gen; ss. eauto.\n      i. eapply __lsim_mon. 2: eauto. i. eapply rclo6_base; auto.\n    }\n    { eapply lsim_UB; eauto. }\n    { des. eapply lsim_fairL; eauto. esplits; eauto. split; ss.\n      eapply GF in LSIM0. eapply pind6_mon_gen; ss. eauto.\n      i. eapply __lsim_mon. 2: eauto. i. eapply rclo6_base; auto.\n    }\n    { eapply lsim_tauR; eauto. split; ss.\n      eapply GF in LSIM. eapply pind6_mon_gen; ss. eauto.\n      i. eapply __lsim_mon. 2: eauto. i. eapply rclo6_base; auto.\n    }\n    { eapply lsim_chooseR; eauto. i. specialize (LSIM x). split; ss.\n      eapply GF in LSIM. eapply pind6_mon_gen; ss. eauto.\n      i. eapply __lsim_mon. 2: eauto. i. eapply rclo6_base; auto.\n    }\n    { eapply lsim_rmwR; eauto. split; ss.\n      eapply GF in LSIM. eapply pind6_mon_gen; ss. eauto.\n      i. eapply __lsim_mon. 2: eauto. i. eapply rclo6_base; auto.\n    }\n    { eapply lsim_tidR; eauto. split; ss.\n      eapply GF in LSIM. eapply pind6_mon_gen; ss. eauto.\n      i. eapply __lsim_mon. 2: eauto. i. eapply rclo6_base; auto.\n    }\n    { eapply lsim_fairR; eauto. i. specialize (LSIM _ FAIR). split; ss.\n      eapply GF in LSIM. eapply pind6_mon_gen; ss. eauto.\n      i. eapply __lsim_mon. 2: eauto. i. eapply rclo6_base; auto.\n    }\n    { eapply lsim_observe; eauto. i. specialize (LSIM ret).\n      eapply rclo6_base; auto.\n    }\n    { eapply lsim_call. }\n    { eapply lsim_yieldR; eauto. i. specialize (LSIM _ _ _ _ _ _ _ INV0 VALID0 _ TGT).\n      des. esplits; eauto.\n      eapply rclo6_base; auto.\n    }\n    { des. eapply lsim_yieldL; eauto. esplits; eauto. split; ss.\n      eapply GF in LSIM0. eapply pind6_mon_gen; ss. eauto.\n      i. eapply __lsim_mon. 2: eauto. i. eapply rclo6_base; auto.\n    }\n    { eapply lsim_progress; eauto. eapply rclo6_base; auto. }\n  Qed.\n\n  Lemma lsim_indC_spec tid R0 R1 (RR: R0 -> R1 -> _ -> _):\n    (lsim_indC tid RR) <7= gupaco6 (fun r => pind6 (__lsim tid RR r) top6) (cpn6 (fun r => pind6 (__lsim tid RR r) top6)).\n  Proof.\n    i. eapply wrespect6_uclo; eauto with paco.\n    { eapply lsim_mon. }\n    eapply lsim_indC_wrepectful.\n  Qed.\n\n\n  Variant lsim_resetC R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel)\n          (r: bool -> bool -> URA.car -> ((wf_stt R_src R_tgt).(T) * itree srcE R_src) -> itree tgtE R_tgt -> shared_rel)\n    :\n    bool -> bool -> URA.car -> ((wf_stt R_src R_tgt).(T) * 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 ps1 pt1 r_ctx src tgt shr)\n        (SRC: ps1 = true -> ps0 = true)\n        (TGT: pt1 = true -> pt0 = true)\n      :\n      lsim_resetC RR r ps0 pt0 r_ctx src tgt shr\n  .\n\n  Lemma lsim_resetC_spec tid R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel)\n    :\n    lsim_resetC RR <7= gupaco6 (fun r => pind6 (__lsim tid RR r) top6) (cpn6 (fun r => pind6 (__lsim tid RR r) top6)).\n  Proof.\n    eapply wrespect6_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 pind6_acc in REL.\n    instantiate (1:= (fun ps1 pt1 r_ctx src tgt shr =>\n                        forall ps0 pt0,\n                          (ps1 = true -> ps0 = true) ->\n                          (pt1 = true -> pt0 = true) ->\n                          pind6 (__lsim tid RR (rclo6 (lsim_resetC RR) r)) top6 ps0 pt0 r_ctx src tgt shr)) in REL; eauto.\n    ss. i. eapply pind6_unfold in PR.\n    2:{ eapply _lsim_mon. }\n    rename PR into LSIM. inv LSIM.\n\n    { eapply pind6_fold. econs; eauto. }\n\n    { destruct LSIM0 as [LSIM0 IND]. clear LSIM0.\n      eapply pind6_fold. eapply lsim_tauL. split; ss.\n      hexploit IH; eauto.\n    }\n\n    { des. eapply pind6_fold. eapply lsim_chooseL. esplits; eauto. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind6_fold. eapply lsim_rmwL. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind6_fold. eapply lsim_tidL. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind6_fold. eapply lsim_UB. }\n\n    { des. eapply pind6_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 pind6_fold. eapply lsim_tauR. split; ss.\n      hexploit IH. eauto. all: eauto.\n    }\n\n    { eapply pind6_fold. eapply lsim_chooseR. i. split; ss. specialize (LSIM0 x).\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind6_fold. eapply lsim_rmwR. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind6_fold. eapply lsim_tidR. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind6_fold. eapply lsim_fairR. i. split; ss. specialize (LSIM0 _ FAIR).\n      des. destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind6_fold. eapply lsim_observe. i. eapply rclo6_base. auto. }\n\n    { eapply pind6_fold. eapply lsim_call. }\n\n    { eapply pind6_fold. eapply lsim_yieldR; eauto. i.\n      hexploit LSIM0; eauto. clear LSIM0. intros LSIM0. des. esplits; eauto.\n      eapply rclo6_base. auto.\n    }\n\n    { des. eapply pind6_fold. eapply lsim_yieldL. esplits; eauto. split; ss.\n      destruct LSIM as [LSIM IND]. hexploit IH; eauto.\n    }\n\n    { hexploit H; ss; i. hexploit H0; ss; i. clarify.\n      eapply pind6_fold. eapply lsim_progress. eapply rclo6_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 cpn6_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 RR. 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 pind6_acc in LSIM.\n\n    { instantiate (1:= (fun ps0 pt0 r_ctx src tgt shr =>\n                          ps0 = true ->\n                          pt0 = true ->\n                          forall ps pt,\n                            paco6 (fun r0 => pind6 (__lsim tid RR r0) top6) r 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 gps gpt r_ctx src tgt shr LSIM. clear DEC.\n    intros Egps Egpt ps pt.\n    eapply pind6_unfold in LSIM.\n    2:{ eapply _lsim_mon. }\n    inv LSIM.\n\n    { pfold. eapply pind6_fold. econs; eauto. }\n\n    { destruct LSIM0 as [LSIM0 IND]. clear LSIM0.\n      pfold. eapply pind6_fold. eapply lsim_tauL. split; ss.\n      hexploit IH. eauto. all: eauto. i. punfold H. eapply lsim_mon.\n    }\n\n    { des. pfold. eapply pind6_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 pind6_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 pind6_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 pind6_fold. eapply lsim_UB. }\n\n    { des. pfold. eapply pind6_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 pind6_fold. eapply lsim_tauR. split; ss.\n      hexploit IH. eauto. all: eauto. i. punfold H. eapply lsim_mon.\n    }\n\n    { pfold. eapply pind6_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 pind6_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 pind6_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 pind6_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 pind6_fold. eapply lsim_observe. i. eapply upaco6_mon_bot; eauto. }\n\n    { pfold. eapply pind6_fold. eapply lsim_call. }\n\n    { pfold. eapply pind6_fold. eapply lsim_yieldR; eauto. i.\n      hexploit LSIM0; eauto. clear LSIM0. intros LSIM0. des. esplits; eauto.\n      eapply upaco6_mon_bot; eauto.\n    }\n\n    { des. pfold. eapply pind6_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    { pclearbot. eapply paco6_mon_bot. eapply lsim_reset_prog. eauto. all: ss. }\n\n  Qed.\n\n\n  Variant lsim_ord_weakC R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel)\n          (r: bool -> bool -> URA.car -> ((wf_stt R_src R_tgt).(T) * itree srcE R_src) -> itree tgtE R_tgt -> shared_rel)\n    :\n    bool -> bool -> URA.car -> ((wf_stt R_src R_tgt).(T) * itree srcE R_src) -> itree tgtE R_tgt -> shared_rel :=\n    | lsim_ord_weakC_intro\n        src tgt shr r_ctx ps pt o0 o1\n        (REL: r ps pt r_ctx (o0, src) tgt shr)\n        (LE: (wf_stt R_src R_tgt).(le) o0 o1)\n      :\n      lsim_ord_weakC RR r ps pt r_ctx (o1, src) tgt shr\n  .\n\n  Lemma lsim_ord_weakC_spec tid R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel)\n    :\n    lsim_ord_weakC RR <7= gupaco6 (fun r => pind6 (__lsim tid RR r) top6) (cpn6 (fun r => pind6 (__lsim tid RR r) top6)).\n  Proof.\n    eapply wrespect6_uclo; eauto with paco.\n    { eapply lsim_mon. }\n    econs.\n    { ii. inv IN. econs; eauto. }\n    i. inv PR. destruct LE0 as [EQ | LT].\n    { clarify. eapply pind6_mon_gen. eapply GF; eauto. 2: ss.\n      i. eapply __lsim_mon. 2: eauto. i. eapply rclo6_base. auto.\n    }\n    eapply GF in REL.\n    remember (o0, src) as osrc. rename REL into LSIM.\n    move LSIM before GF. revert_until LSIM.\n    pattern x0, x1, x2, osrc, x4, x5.\n    revert x0 x1 x2 osrc x4 x5 LSIM. apply pind6_acc.\n    intros rr DEC IH. clear DEC. intros ps pt r_ctx osrc tgt shr LSIM.\n    i; clarify.\n    eapply pind6_unfold in LSIM.\n    2:{ eapply _lsim_mon. }\n    inv LSIM.\n\n    { eapply pind6_fold. eapply lsim_ret; eauto. }\n    { eapply pind6_fold. eapply lsim_tauL; eauto.\n      split; ss. destruct LSIM0 as [LSIM IND]. eapply IH in IND; eauto.\n    }\n    { eapply pind6_fold. eapply lsim_chooseL; eauto.\n      des. exists x.\n      split; ss. destruct LSIM0 as [LSIM IND]. eapply IH in IND; eauto.\n    }\n    { eapply pind6_fold. eapply lsim_rmwL; eauto.\n      split; ss. destruct LSIM0 as [LSIM IND]. eapply IH in IND; eauto.\n    }\n    { eapply pind6_fold. eapply lsim_tidL; eauto.\n      split; ss. destruct LSIM0 as [LSIM IND]. eapply IH in IND; eauto.\n    }\n    { eapply pind6_fold. eapply lsim_UB; eauto. }\n    { eapply pind6_fold. eapply lsim_fairL; eauto.\n      des. esplits; eauto.\n      split; ss. destruct LSIM as [LSIM IND]. eapply IH in IND; eauto.\n    }\n    { eapply pind6_fold. eapply lsim_tauR; eauto.\n      split; ss. destruct LSIM0 as [LSIM IND]. eapply IH in IND; eauto.\n    }\n    { eapply pind6_fold. eapply lsim_chooseR; eauto.\n      i. specialize (LSIM0 x).\n      split; ss. destruct LSIM0 as [LSIM IND]. eapply IH in IND; eauto.\n    }\n    { eapply pind6_fold. eapply lsim_rmwR; eauto.\n      split; ss. destruct LSIM0 as [LSIM IND]. eapply IH in IND; eauto.\n    }\n    { eapply pind6_fold. eapply lsim_tidR; eauto.\n      split; ss. destruct LSIM0 as [LSIM IND]. eapply IH in IND; eauto.\n    }\n    { eapply pind6_fold. eapply lsim_fairR; eauto.\n      i. specialize (LSIM0 _ FAIR).\n      split; ss. destruct LSIM0 as [LSIM IND]. eapply IH in IND; eauto.\n    }\n    { eapply pind6_fold. eapply lsim_observe; eauto.\n      i. specialize (LSIM0 ret).\n      eapply rclo6_clo_base. econs; eauto. right. auto.\n    }\n\n    { eapply pind6_fold. eapply lsim_call. }\n\n    { eapply pind6_fold. eapply lsim_yieldR; eauto.\n      i. hexploit LSIM0; clear LSIM0; eauto; intro LSIM. des. esplits; eauto.\n      eapply rclo6_clo_base. econs; eauto. right. auto.\n    }\n\n    { eapply pind6_fold. eapply lsim_yieldL; eauto.\n      des. esplits; eauto. destruct LSIM as [LSIM IND].\n      split; ss. eapply pind6_mon_gen. eapply LSIM. 2: ss.\n      i. eapply __lsim_mon. 2: eapply PR. i. eapply rclo6_base; eauto.\n    }\n\n    { eapply pind6_fold. eapply lsim_progress.\n      eapply rclo6_clo_base. econs; eauto. right. auto.\n    }\n\n  Qed.\n\n  Lemma stutter_ord_weak\n        tid\n        R0 R1 (LRR: R0 -> R1 -> URA.car -> shared_rel)\n        ps pt r_ctx src tgt (shr: shared) o0 o1\n        (LE: (wf_stt R0 R1).(le) o0 o1)\n        (LSIM: lsim tid LRR ps pt r_ctx (o0, src) tgt shr)\n    :\n    lsim tid LRR ps pt r_ctx (o1, src) tgt shr.\n  Proof.\n    ginit.\n    { eapply lsim_mon. }\n    { eapply cpn6_wcompat. eapply lsim_mon. }\n    guclo lsim_ord_weakC_spec.\n    { eapply lsim_mon. }\n    econs; eauto. gfinal.\n    { eapply lsim_mon. }\n    right. 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_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 o 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           im_tgt2\n           (TGT: fair_update im_tgt1 im_tgt2 (prism_fmap inlp (tids_fmap tid ths))),\n          exists im_src2, (<<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                             (o, 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 o :=\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            (o, 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          wf_stt : Type -> Type -> WF;\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 wf_stt 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          wf_stt : Type -> Type -> WF;\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 os,\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: Forall4\n                        (fun '(t1, src) '(t2, tgt) '(t3, r) '(t4, o) =>\n                           t1 = t2 /\\ t1 = t3 /\\ t1 = t4 /\\\n                             @local_sim_init _ md_src.(Mod.state) md_tgt.(Mod.state) md_src.(Mod.ident) md_tgt.(Mod.ident) wf_src wf_tgt wf_stt I _ _ (@eq Any.t) r t1 src tgt o)\n                        (Th.elements p_src) (Th.elements p_tgt) (NatMap.elements rs) (NatMap.elements os)>>) /\\\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/ModSimStutter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2667403882182929}}
{"text": "From oadt.lang_oadt Require Import\n     base syntax semantics typing infrastructure\n     equivalence admissible inversion values weakening.\nImport syntax.notations semantics.notations typing.notations equivalence.notations.\n\nImplicit Types (b : bool) (x X y Y : atom) (L : aset).\n\n#[local]\nCoercion EFVar : atom >-> expr.\n\n(** * Substitution lemmas *)\n\nSection fix_gctx.\n\nContext (Σ : gctx).\nContext (Hwf : gctx_wf Σ).\n\n#[local]\nSet Default Proof Using \"Hwf\".\n\nLemma subst_tctx_typing_kinding_ x s :\n  (forall Γ e l τ,\n      Γ ⊢ e :{l} τ ->\n      x ∉ fv τ ∪ dom Γ ->\n      ({x↦s} <$> Γ) ⊢ e :{l} τ) /\\\n  (forall Γ τ κ,\n      Γ ⊢ τ :: κ ->\n      x ∉ dom Γ ->\n      ({x↦s} <$> Γ) ⊢ τ :: κ).\nProof.\n  apply typing_kinding_mutind; intros; subst; simpl in *;\n    econstructor; eauto;\n      simpl_cofin?;\n      (* Try to apply induction hypotheses. *)\n      lazymatch goal with\n      | |- ?Γ ⊢ ?e : _ =>\n        auto_apply || lazymatch goal with\n                      | H : _ -> ?Γ' ⊢ e : _ |- _ =>\n                        replace Γ with Γ'; [auto_apply |]\n                      end\n      | |- ?Γ ⊢ ?τ :: _ =>\n        auto_apply || lazymatch goal with\n                      | H : _ -> ?Γ' ⊢ τ :: _ |- _ =>\n                        replace Γ with Γ'; [auto_apply |]\n                      end\n      | _ => idtac\n      end; eauto;\n        (* Solve other side conditions *)\n        repeat lazymatch goal with\n               | |- _ ∉ _ =>\n                 shelve\n               | |- _ <> _ =>\n                 shelve\n               | |- {_↦_} <$> (<[_:=_]>_) = <[_:=_]>({_↦_} <$> _) =>\n                 rewrite fmap_insert; try reflexivity; repeat f_equal\n               | |- _ !! _ = Some _ =>\n                 simplify_map_eq\n               | |- Some _ = Some _ =>\n                 try reflexivity; repeat f_equal\n               | |- {_↦_} _ = _ =>\n                 rewrite <- ?lexpr_subst_distr; rewrite subst_fresh\n               end;\n        eauto.\n\n  Unshelve.\n\n  all : try fast_set_solver!!; simpl_fv; fast_set_solver!!.\nQed.\n\nLemma subst_tctx_typing Γ e l τ x s :\n  Γ ⊢ e :{l} τ ->\n  x ∉ fv τ ∪ dom Γ ->\n  ({x↦s} <$> Γ) ⊢ e :{l} τ.\nProof.\n  qauto use: subst_tctx_typing_kinding_.\nQed.\n\n(* Note that [lc s] is not needed, and it is here only for convenience. I will\ndrop it in the actual lemma. *)\nLemma subst_preservation_ x s l' τ' :\n  lc s ->\n  (forall Γ' e l τ,\n      Γ' ⊢ e :{l} τ ->\n      forall Γ,\n        Γ' = <[x:=(l', τ')]>Γ ->\n        x ∉ fv τ' ∪ dom Γ ->\n        Γ ⊢ s :{l'} τ' ->\n        ({x↦s} <$> Γ) ⊢ {x↦s}e :{l} {x↦s}τ) /\\\n  (forall Γ' τ κ,\n      Γ' ⊢ τ :: κ ->\n      forall Γ,\n        Γ' = <[x:=(l', τ')]>Γ ->\n        x ∉ fv τ' ∪ dom Γ ->\n        Γ ⊢ s :{l'} τ' ->\n        ({x↦s} <$> Γ) ⊢ {x↦s}τ :: κ).\nProof.\n  intros Hlc.\n  apply typing_kinding_mutind; intros; subst; simpl in *;\n    (* First we normalize the typing and kinding judgments so they are ready\n    for applying typing and kinding rules to. *)\n    rewrite ?subst_open_distr by assumption;\n    rewrite ?subst_ite_distr;\n    try lazymatch goal with\n        | |- _ ⊢ [inj@_< ?ω > _] : {_↦_}?ω =>\n          rewrite subst_fresh by shelve\n        | |- context [decide (_ = _)] =>\n          (* The case of [fvar x] is the trickier one. Let's handle it later. *)\n          case_decide; subst; [shelve |]\n        end;\n      (* Apply typing and kinding rules. *)\n      econstructor;\n      simpl_cofin?;\n      (* We define this subroutine [go] for applying induction hypotheses. *)\n      let go Γ :=\n          (* We massage the typing and kinding judgments so that we can apply\n          induction hypotheses to them. *)\n          rewrite <- ?subst_ite_distr;\n            rewrite <- ?subst_open_distr by assumption;\n            rewrite <- ?subst_open_comm by (try assumption; shelve);\n            try lazymatch Γ with\n                | <[_:=_]>({_↦_} <$> _) =>\n                  try rewrite lexpr_subst_distr;\n                  rewrite <- fmap_insert\n                end;\n            (* Apply one of the induction hypotheses. *)\n            first [ auto_apply\n                  (* In [if] and [case] cases, prove the type matching the\n                  induction hypothesis later. *)\n                  | relax_typing_type; [ auto_apply | ] ] in\n      (* Make sure we complete handling the typing and kinding judgments first.\n      Otherwise some existential variables may have undesirable\n      instantiation. *)\n      lazymatch goal with\n      | |- ?Γ ⊢ _ : _ => go Γ\n      | |- ?Γ ⊢ _ :: _ => go Γ\n      | _ => idtac\n      end;\n        (* Try to solve other side conditions. *)\n        eauto;\n        repeat lazymatch goal with\n               | |- _ ∉ _ =>\n                 shelve\n               | |- _ <> _ =>\n                 shelve\n               | |- <[_:=_]>(<[_:=_]>_) = <[_:=_]>(<[_:=_]>_) =>\n                 apply insert_commute\n               | |- _ ≡ _ =>\n                 apply pared_equiv_subst2\n               | |- (_ <$> _) !! _ = Some _ =>\n                 simplify_map_eq\n               | |- <[_:=_]>_ ⊢ _ : _ =>\n                 apply weakening_insert\n               | |- Some _ = Some _ =>\n                 try reflexivity; repeat f_equal\n               | |- _ = <{ {_↦_} _ }> =>\n                 rewrite subst_fresh\n               | H : ?Σ !! ?x = Some _ |- ?Σ !! ?x = Some _ =>\n                 rewrite H\n               end;\n        eauto.\n\n  (* Prove the types of [if] and [case] match the induction hypotheses. *)\n  all : rewrite subst_open_distr by eassumption; simpl; eauto;\n    rewrite decide_False by shelve; eauto.\n\n  Unshelve.\n\n  (* Case [fvar x] *)\n  simplify_map_eq.\n  rewrite subst_fresh.\n  apply subst_tctx_typing; eauto.\n\n  (* Solve other side conditions of free variables. *)\n  all : try fast_set_solver!!; simpl_fv; fast_set_solver*!!.\nQed.\n\n(** The actual substitution lemma *)\nLemma subst_preservation x s l' τ' Γ e l τ :\n  <[x:=(l', τ')]>Γ ⊢ e :{l} τ ->\n  Γ ⊢ s :{l'} τ' ->\n  x ∉ fv τ' ∪ dom Γ ∪ tctx_fv Γ ->\n  Γ ⊢ {x↦s}e :{l} {x↦s}τ.\nProof.\n  intros.\n  rewrite <- (subst_tctx_fresh Γ x s) by fast_set_solver!!.\n  eapply subst_preservation_; eauto using typing_lc.\n  fast_set_solver!!.\nQed.\n\nLemma kinding_subst_preservation x s l' τ' Γ τ κ :\n  <[x:=(l', τ')]>Γ ⊢ τ :: κ ->\n  Γ ⊢ s :{l'} τ' ->\n  x ∉ fv τ' ∪ dom Γ ∪ tctx_fv Γ ->\n  Γ ⊢ {x↦s}τ :: κ.\nProof.\n  intros.\n  rewrite <- (subst_tctx_fresh Γ x s) by fast_set_solver!!.\n  eapply subst_preservation_; eauto using typing_lc.\n  fast_set_solver!!.\nQed.\n\nLemma open_preservation_alt x s l' τ' Γ e l τ :\n  <[x:=(l', τ')]>Γ ⊢ e^x :{l} τ ->\n  Γ ⊢ s :{l'} τ' ->\n  x ∉ fv τ' ∪ fv e ∪ dom Γ ∪ tctx_fv Γ ->\n  Γ ⊢ e^s :{l} {x↦s}τ.\nProof.\n  intros.\n  rewrite (subst_intro e s x) by fast_set_solver!!.\n  eapply subst_preservation; eauto.\n  fast_set_solver!!.\nQed.\n\nLemma open_preservation x s l' τ' Γ e l τ :\n  <[x:=(l', τ')]>Γ ⊢ e^x :{l} τ^x ->\n  Γ ⊢ s :{l'} τ' ->\n  x ∉ fv τ' ∪ fv e ∪ fv τ ∪ dom Γ ∪ tctx_fv Γ ->\n  Γ ⊢ e^s :{l} τ^s.\nProof.\n  intros.\n  rewrite (subst_intro e s x) by fast_set_solver!!.\n  rewrite (subst_intro τ s x) by fast_set_solver!!.\n  eapply subst_preservation; eauto.\n  fast_set_solver!!.\nQed.\n\nLemma kinding_open_preservation x s l' τ' Γ τ κ :\n  <[x:=(l', τ')]>Γ ⊢ τ^x :: κ ->\n  Γ ⊢ s :{l'} τ' ->\n  x ∉ fv τ' ∪ fv τ ∪ dom Γ ∪ tctx_fv Γ ->\n  Γ ⊢ τ^s :: κ.\nProof.\n  intros.\n  rewrite (subst_intro τ s x) by fast_set_solver!!.\n  eapply kinding_subst_preservation; eauto.\n  fast_set_solver!!.\nQed.\n\nLemma open_preservation_lc x s l' τ' Γ e l τ :\n  <[x:=(l', τ')]>Γ ⊢ e^x :{l} τ ->\n  Γ ⊢ s :{l'} τ' ->\n  x ∉ fv τ' ∪ fv e ∪ fv τ ∪ dom Γ ∪ tctx_fv Γ ->\n  Γ ⊢ e^s :{l} τ.\nProof.\n  intros H. intros.\n  erewrite <- (open_lc_intro τ s) by eauto using typing_type_lc.\n  erewrite <- (open_lc_intro τ x) in H by eauto using typing_type_lc.\n  eapply open_preservation; eauto.\nQed.\n\n(** * Other lemmas *)\n\n(** Types of well-typed expressions are well-kinded *)\nLemma regularity Γ e l τ :\n  Γ ⊢ e :{l} τ ->\n  exists κ, Γ ⊢ τ :: κ.\nProof.\n  induction 1; simp_hyps; eauto using kinding;\n    try (apply_gctx_wf; eauto using kinding_weakening_empty);\n    kind_inv; simpl_cofin?; simp_hyps;\n    try first [ eexists; typing_kinding_intro; eauto; fast_set_solver!!\n              (* Types may be opened. *)\n              | eexists; qauto use: kinding_open_preservation\n                               solve: fast_set_solver!! ].\n  (* Boxed injection case *)\n  sfirstorder use: otval_well_kinded, ovalty_elim.\nQed.\n\nLtac apply_regularity :=\n  select! (_ ⊢ _ : _)\n        (fun H => dup_hyp H (fun H => eapply regularity in H; simp_hyp H)).\n\n(** We can substitute with an equivalent type and a more permissive label in the\ntyping contexts. *)\nLemma subst_conv_ x l1 l2 τ1 τ2 :\n  τ1 ≡ τ2 ->\n  (forall Γ' e l τ,\n      Γ' ⊢ e :{l} τ ->\n      forall Γ κ',\n        Γ' = <[x:=(l1, τ1)]>Γ ->\n        x ∉ dom Γ ->\n        Γ ⊢ τ2 :: κ' ->\n        l2 ⊑ l1 ->\n        <[x:=(l2, τ2)]>Γ ⊢ e :{l} τ) /\\\n  (forall Γ' τ κ,\n      Γ' ⊢ τ :: κ ->\n      forall Γ κ',\n        Γ' = <[x:=(l1, τ1)]>Γ ->\n        x ∉ dom Γ ->\n        Γ ⊢ τ2 :: κ' ->\n        l2 ⊑ l1 ->\n        <[x:=(l2, τ2)]>Γ ⊢ τ :: κ).\nProof.\n  intros Heq.\n  apply typing_kinding_mutind; intros; subst;\n    (* [TFVar] is the key base case. Prove it later *)\n    try lazymatch goal with\n        | |- _ ⊢ fvar _ : _ =>\n          shelve\n        end;\n    try solve [ econstructor; eauto ];\n    simpl_cofin?;\n    repeat\n      match goal with\n      | H : forall _ _, _ -> _ -> _ -> _ -> _ |- _ =>\n        efeed specialize H;\n          [ try reflexivity; rewrite insert_commute by shelve; reflexivity\n          | fast_set_solver!!\n          | eauto using kinding_weakening_insert\n          | solve [eauto]\n          | .. ];\n          try rewrite insert_commute in H by shelve\n      end;\n\n    try apply_regularity;\n    try eapply TConv;\n      repeat\n        (eauto;\n         lazymatch goal with\n         | |- _ ⊢ _ : _ =>\n           typing_intro\n         | |- _ ⊢ _^_ :: _ =>\n           eapply kinding_open_preservation\n         | |- _ ⊢ _ :: _ =>\n           kinding_intro\n         | |- _ ≡ _ =>\n           equiv_naive_solver\n         | |- _ ∉ _ =>\n           shelve\n         end).\n\n  Unshelve.\n\n  (* [TFVar] *)\n  match goal with\n  | |- _ ⊢ fvar ?x' : _ => destruct (decide (x' = x))\n  end; subst;\n    try solve [ econstructor; simplify_map_eq; eauto ].\n  simplify_map_eq.\n  eapply TConv; eauto.\n  typing_intro; simplify_map_eq; eauto.\n  eauto using kinding_weakening_insert.\n  equiv_naive_solver.\n\n  all : try fast_set_solver!!; simpl_fv; fast_set_solver!!.\nQed.\n\nLemma subst_conv Γ e l τ κ' x l1 l2 τ1 τ2 :\n  <[x:=(l1, τ1)]>Γ ⊢ e :{l} τ ->\n  Γ ⊢ τ2 :: κ' ->\n  τ1 ≡ τ2 ->\n  l2 ⊑ l1 ->\n  x ∉ dom Γ ->\n  <[x:=(l2, τ2)]>Γ ⊢ e :{l} τ.\nProof.\n  hauto use: subst_conv_.\nQed.\n\nLemma kinding_subst_conv Γ τ κ κ' x l1 l2 τ1 τ2 :\n  <[x:=(l1, τ1)]>Γ ⊢ τ :: κ ->\n  Γ ⊢ τ2 :: κ' ->\n  τ1 ≡ τ2 ->\n  l2 ⊑ l1 ->\n  x ∉ dom Γ ->\n  <[x:=(l2, τ2)]>Γ ⊢ τ :: κ.\nProof.\n  hauto use: subst_conv_.\nQed.\n\nLemma oval_safe Γ v l τ :\n  Γ ⊢ v :{l} τ ->\n  oval v ->\n  Γ ⊢ v :{⊥} τ.\nProof.\n  intros Ht Hv.\n  apply_regularity.\n  apply woval_otval in Ht; eauto using oval_woval. simp_hyps.\n  eapply ovalty_intro in Hv; eauto.\n  select (_ ⊢ _ : _) (fun H => clear H).\n  eapply ovalty_elim in Hv. simp_hyps.\n  econstructor; eauto.\nQed.\n\n(** * Preservation *)\n\n(** The combined preservation theorems for parallel reduction. *)\nLemma pared_preservation_ :\n  (forall Γ e l τ,\n      Γ ⊢ e :{l} τ ->\n      forall e', e ⇛ e' ->\n            Γ ⊢ e' :{l} τ) /\\\n  (forall Γ τ κ,\n      Γ ⊢ τ :: κ ->\n      forall τ', τ ⇛ τ' ->\n            Γ ⊢ τ' :: κ).\nProof.\n  apply typing_kinding_mutind; intros; subst;\n    (* Inversion on parallel reduction. *)\n    repeat pared_inv;\n    simplify_eq;\n    try apply_gctx_wf;\n    simpl_cofin?;\n    (* Solve some trivial cases. *)\n    try solve [ lazymatch goal with\n                | H : _ !! _ = Some (DFun _ _) |- _ =>\n                  eauto using weakening_empty\n                end\n              | lazymatch goal with\n                | H : oval _ |- _ =>\n                    eauto using oval_safe\n                end\n              | try case_ite_expr;\n                simp_hyps;\n                repeat\n                  (eauto;\n                   lazymatch goal with\n                   | |- _ ⊢ _ : ?τ =>\n                     first [ is_evar τ | econstructor ]\n                   | |- _ ⊢ _ :: ?κ =>\n                     first [ is_evar κ | econstructor ]\n                   end)];\n    (* Now turn to the more interesting cases. *)\n    (* Derive some equivalence for later convenience. *)\n    try select! (_ ⇛ _)\n        (fun H => dup_hyp H (fun H => apply pared_equiv_pared in H));\n    (* Derive well-kindedness from typing. *)\n    try apply_regularity;\n    (* Apply inversion lemmas for typing and kinding. *)\n    kind_inv;\n    type_inv;\n    (* Instantiate induction hypotheses. *)\n    repeat\n      match goal with\n      | H : forall _, _ ⇛ _ -> _ |- _ =>\n        efeed specialize H; [\n          solve [ repeat\n                    (eauto;\n                     lazymatch goal with\n                     | |- ?e ⇛ _ =>\n                       first [ lazymatch e with\n                               | <{ ~if _ then _ else _ }> =>\n                                 eapply RCgrIte\n                               end\n                             | match goal with\n                               | H : ?e1 ⇛ _ |- _ =>\n                                   let e1 := lazymatch e1 with\n                                             | <{ ?e1^_ }> => e1\n                                             | _ => e1\n                                             end in\n                                   lazymatch e with\n                                   | context [e1] =>\n                                       head_constructor e; pared_intro\n                                   end\n                               end\n                             | eapply pared_open1\n                             | lcrefl ]\n                     | |- lc _ => eauto using lc, kinding_lc\n                     | |- _ ∉ _ => shelve\n                     end) ]\n         |];\n        try type_inv H;\n        try kind_inv H\n      end;\n    (* Derive equivalence for the sub-expressions. *)\n    try simpl_whnf_equiv;\n    (* We may have cofinite quantifiers that are generated by the inversion\n    lemmas. *)\n    simpl_cofin?;\n    simplify_eq;\n    (* Main solver. *)\n    repeat\n      (try case_ite_expr;\n       eauto;\n       match goal with\n       (* Replace the types in context with an equivalent ones. *)\n       | H : <[_:=_]>_ ⊢ _ :{?l} _ |- <[_:=_]>_ ⊢ _ :{?l} _ =>\n           eapply subst_conv\n       | |- <[_:=_]>_ ⊢ _ :{?l} _ =>\n           is_evar l; eapply subst_conv\n       | |- <[_:=_]>_ ⊢ _ :: _ =>\n           eapply kinding_subst_conv\n       (* Apply substitution/open lemmas. *)\n       | H : <[_:=_]>?Γ ⊢ ?e^(fvar _) : ?τ |- ?Γ ⊢ ?e^_ : ?τ =>\n           eapply open_preservation_lc\n       | H : <[_:=_]>?Γ ⊢ ?e^(fvar _) : _^(fvar _) |- ?Γ ⊢ ?e^_ : _ =>\n           eapply open_preservation\n       (* This is for the dependent case expression. *)\n       | H : <[_:=_]>?Γ ⊢ ?e^(fvar _) : _^_ |- ?Γ ⊢ ?e^_ : _ =>\n           eapply open_preservation_alt\n       | H : <[_:=_]>?Γ ⊢ ?e^(fvar _) :: _ |- ?Γ ⊢ ?e^_ :: _ =>\n           eapply kinding_open_preservation\n       (* Apply typing rules. *)\n       | |- _ ⊢ _ : _ =>\n           typing_intro\n       | |- _ ⊢ _ : ?τ =>\n           assert_fails is_evar τ; eapply TConv\n       (* Apply kinding rules. *)\n       | |- _ ⊢ _ :: ?κ =>\n           eauto using kinding_weakening_empty; kinding_intro\n       (* Solve equivalence. *)\n       | |- _ ≡ _ =>\n           try case_split; equiv_naive_solver\n       | |- _ ≡ _ =>\n           apply_pared_equiv_congr\n       | |- <{ _^_ }> ≡ <{ _^_ }> =>\n           eapply pared_equiv_open1; simpl_cofin?\n       | |- <{ _^_ }> ≡ <{ _^_ }> =>\n           eapply pared_equiv_open\n       (* Solve other side conditions. *)\n       | |- lc _ =>\n           eauto using lc, open_respect_lc,\n           typing_type_lc, typing_lc, kinding_lc\n       | |- _ ⊑ _ =>\n           first [ lattice_naive_solver\n                     by eauto using (top_ub (A:=bool)),\n                                    (join_ub_l (A:=bool)), (join_ub_r (A:=bool))\n                 | hauto use: (join_lub (A:=bool)) ]\n       | |- _ ∉ _ => shelve\n       end).\n\n  (* The case when oblivious injection steps to boxed injection. *)\n  hauto lq: on ctrs: ovalty inv: otval use: ovalty_intro.\n\n  (* These equivalence are generated by the case when the case discriminee takes\n  a step. *)\n  1-2 :\n  rewrite subst_open_distr by eauto using typing_lc; simpl;\n  rewrite decide_True by auto;\n  rewrite !subst_fresh by shelve;\n  eapply pared_equiv_open1; simpl_cofin?;\n  eauto 7 using lc, open_respect_lc, typing_lc, kinding_lc, pared_equiv_congr_inj\n          with equiv_naive_solver.\n\n  (* These 4 cases are generated by the case when oblivious case analysis steps\n  to oblivious condition. *)\n  1-4 :\n  repeat ovalty_inv;\n  select! (ovalty _ _) (fun H => apply ovalty_elim in H; simp_hyp H);\n  eapply TConv;\n  eauto using weakening, map_empty_subseteq with equiv_naive_solver.\n\n  (* The case when we apply oblivious type to its argument: [RAppOADT] *)\n  eapply kinding_open_preservation; eauto; try set_shelve.\n  eapply kinding_weakening; eauto.\n  rewrite insert_union_singleton_l.\n  apply map_union_subseteq_l.\n\n  Unshelve.\n\n  all : fast_set_solver!!.\nQed.\n\nLemma pared_preservation Γ e l e' τ :\n  Γ ⊢ e :{l} τ ->\n  e ⇛ e' ->\n  Γ ⊢ e' :{l} τ.\nProof.\n  hauto use: pared_preservation_.\nQed.\n\nLemma pared_kinding_preservation Γ τ τ' κ :\n  Γ ⊢ τ :: κ ->\n  τ ⇛ τ' ->\n  Γ ⊢ τ' :: κ.\nProof.\n  hauto use: pared_preservation_.\nQed.\n\n(** The preservation theorem for [step]. *)\nTheorem preservation Γ e l e' τ :\n  Γ ⊢ e :{l} τ ->\n  e -->! e' ->\n  Γ ⊢ e' :{l} τ.\nProof.\n  hauto use: pared_preservation, pared_step, typing_lc.\nQed.\n\nTheorem kinding_preservation Γ τ τ' κ :\n  Γ ⊢ τ :: κ ->\n  τ -->! τ' ->\n  Γ ⊢ τ' :: κ.\nProof.\n  hauto use: pared_kinding_preservation, pared_step, kinding_lc.\nQed.\n\nEnd fix_gctx.\n\nLtac apply_regularity :=\n  select! (_ ⊢ _ : _)\n        (fun H => dup_hyp H (fun H => eapply regularity in H;\n                                  [ simp_hyp H | assumption ])).\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/preservation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2667403882182928}}
{"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_recvA_Nack_procR_typing :\n  forall i k r 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 (SNack r k 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          Token (if if i then false else true then \"true\" else \"false\");\n        (New\n        (CoNm (Free (String.append \"recv_\" (if i 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 k r t xc xerr2 xout Hxc_nin Hxerr2_nin Hxout_nin.\n  (* err2!(1-i); rest *)\n  eapply TypPrefixOutput with\n      (s:=SDual (SNack r k t (token_of_bool (negb i))))\n      (rho:=TSingleton (token_of_bool (negb i)))\n      (t:=SDual (SAck t (token_of_bool (negb 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      | apply LToken; destruct i; ctx_wf; discriminate_w_list\n      | right; split; [reflexivity | constructor]\n      | reflexivity\n      | ].\n  (* main event *)\n  (* recv_i(err2, out), i.e. New d *)\n  apply TypNew with (s:=SRecv i)\n      (L:=xc :: xerr2 :: xout :: \"recv_true\" :: \"recv_false\" :: 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 i)))\n      (rho:=TChannel (SRecv i)) (t:=SDual (SFwd (SRecv 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 i))\n      (rho:=TChannel (SDual (SAck t (token_of_bool (negb i)))))\n      (t:=SDual (SRecv1 i (SAck t (token_of_bool (negb i))) t));\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  (* d!out; rest *)\n  eapply TypPrefixOutput with\n      (s:=SDual (SRecv1 i (SAck t (token_of_bool (negb i))) t))\n      (rho:=TChannel (SDual (SToks t)))\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/ExampleABPRecvANack.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.26672283058378915}}
{"text": "Require Import syntax.\nRequire Import alist.\nRequire Import FMapWeakList.\n\nRequire Import Coqlib.\nRequire Import infrastructure.\nRequire Import Metatheory.\nImport LLVMsyntax.\nImport LLVMinfra.\n\nRequire Import Exprs.\nRequire Import Hints.\nRequire Import TODO.\nRequire Import Postcond.\nRequire Import Infrules.\n\nRequire Import Debug.\n\nSet Implicit Arguments.\n\nParameter gen_infrules_from_insns : insn -> insn -> Assertion.t -> list Infrule.t.\nParameter gen_infrules_next_inv : bool -> Assertion.t -> Assertion.t -> list Infrule.t.\n\nFixpoint valid_cmds\n         (m_src m_tgt:module)\n         (src tgt:list cmd)\n         (hint:list (list Infrule.t * Assertion.t))\n         (inv0:Assertion.t): option Assertion.t :=\n  match hint, src, tgt with\n  | (infrules, inv)::hint, cmd_src::src, cmd_tgt::tgt =>\n    let (cmd_src, cmd_tgt) :=\n        (debug_print cmd_pair_printer (cmd_src, cmd_tgt)) in\n    if (Assertion.has_false inv0) then valid_cmds m_src m_tgt src tgt hint inv else\n    let oinv1 :=\n        match postcond_cmd cmd_src cmd_tgt inv0 with\n        | Some inv1 => Some inv1\n        | None =>\n          let infr := gen_infrules_from_insns (insn_cmd cmd_src)\n                                              (insn_cmd cmd_tgt)\n                                              inv0 in\n          let inv0_infr := apply_infrules m_src m_tgt infr inv0 in\n          let inv0_infr := debug_print_auto infr inv0_infr in\n          postcond_cmd cmd_src cmd_tgt inv0_infr\n        end\n    in\n    match oinv1 with\n    | None => failwith_None \"valid_cmds: postcond_cmd returned None\" nil\n    | Some inv1 =>\n      let infrules_auto := gen_infrules_next_inv true inv1 inv0 in\n      let inv2 := apply_infrules m_src m_tgt (infrules_auto++infrules) inv1 in\n      let inv3 := reduce_maydiff inv2 in\n      let inv := debug_print_validation_process infrules inv0 inv1 inv2 inv3 inv in\n      if\n        (if Assertion.implies inv3 inv\n         then true\n         else\n           (* TODO: need new print method *)\n           let infrules := gen_infrules_next_inv false inv3 inv in\n           let inv3_infr := apply_infrules m_src m_tgt infrules inv3 in\n           let inv3_red := reduce_maydiff inv3_infr in\n           let inv3_red := debug_print_auto infrules inv3_red in\n           Assertion.implies inv3_red inv)\n      then valid_cmds m_src m_tgt src tgt hint inv\n      else failwith_None \"valid_cmds: Assertion.implies returned false\" nil\n    end\n  | nil, nil, nil => Some inv0\n  | _, _, _ => None\n  end.\n\nDefinition lookup_phinodes_infrules hint_stmts l_from :=\n  match lookupAL _ hint_stmts.(ValidationHint.phinodes) l_from with\n  | None => nil\n  | Some infrules => infrules\n  end.\n\nDefinition valid_phinodes\n           (hint_fdef:ValidationHint.fdef)\n           (inv0:Assertion.t)\n           (m_src m_tgt:module)\n           (blocks_src blocks_tgt:blocks)\n           (l_from l_to:l): bool :=\n  let l_from := (debug_print atom_printer l_from) in\n  let l_to := (debug_print atom_printer l_to) in\n  match lookupAL _ hint_fdef l_to, lookupAL _ blocks_src l_to, lookupAL _ blocks_tgt l_to with\n  | Some hint_stmts, Some (stmts_intro phinodes_src _ _), Some (stmts_intro phinodes_tgt _ _) =>\n    let infrules := lookup_phinodes_infrules hint_stmts l_from in\n    match postcond_phinodes l_from phinodes_src phinodes_tgt inv0 with\n      | None => failwith_false \"valid_phinodes: postcond_phinodes returned None at phinode\" (l_from::l_to::nil)\n      | Some inv1 =>\n        let infrules_auto := gen_infrules_next_inv true inv1 inv0 in\n        let inv2 := apply_infrules m_src m_tgt (infrules_auto++infrules) inv1 in\n        let inv3 := reduce_maydiff inv2 in\n        let inv4 := hint_stmts.(ValidationHint.assertion_after_phinodes) in\n        let inv4 := debug_print_validation_process infrules inv0 inv1 inv2 inv3 inv4 in\n        if negb (Assertion.implies inv3 inv4)\n        then\n          let infrules := gen_infrules_next_inv false inv3 inv4 in\n          let inv3_infr := apply_infrules m_src m_tgt infrules inv3 in\n          let inv3_red := reduce_maydiff inv3_infr in\n          let inv3_red := debug_print_auto infrules inv3_red in\n          if negb (Assertion.implies inv3_red inv4)\n          then failwith_false \"valid_phinodes: Assertion.implies returned false at phinode\" (l_from::l_to::nil)\n          else true\n        else true\n    end\n  | _, _, _ => false\n  end.\n\n(* TODO: position *)\nLemma const_l_dec (cl1 cl2:const * l):\n  {cl1 = cl2} + {cl1 <> cl2}.\nProof.\n  decide equality. apply const_dec.\nDefined.\n\n(* TODO *)\nRequire Import sflib.\n\nLemma list_const_l_dec (cls1 cls2:list (const * l)):\n  {cls1 = cls2} + {cls1 <> cls2}.\nProof.\n  revert cls2.\n  induction cls1; destruct cls2;\n    (try by left);\n    (try by right).\n  decide equality. apply const_l_dec.\nDefined.\n\nDefinition valid_terminator\n           (hint_fdef:ValidationHint.fdef)\n           (inv0:Assertion.t)\n           (m_src m_tgt:module)\n           (blocks_src blocks_tgt:blocks)\n           (bid:l)\n           (src tgt:terminator): bool :=\n  if (Assertion.has_false inv0) then true else\n  match src, tgt with\n  | insn_return_void _, insn_return_void _ => true\n  | insn_return _ ty_src val_src, insn_return _ ty_tgt val_tgt =>\n    if negb (typ_dec ty_src ty_tgt)\n    then failwith_false \"valid_terminator: return type not matched at block\" [bid]\n    else\n\n    if negb (Assertion.inject_value\n               inv0\n               (ValueT.lift Tag.physical val_src)\n               (ValueT.lift Tag.physical val_tgt))\n    then failwith_false \"valid_terminator: inject_value of returned values failed at block\" [bid]\n    else true\n\n  | insn_br _ val_src l1_src l2_src, insn_br _ val_tgt l1_tgt l2_tgt =>\n    if negb (Assertion.inject_value\n               inv0\n               (ValueT.lift Tag.physical val_src)\n               (ValueT.lift Tag.physical val_tgt))\n    then failwith_false \"valid_terminator: inject_value of branch conditions failed at block\" [bid]\n    else\n\n    if negb (l_dec l1_src l1_tgt)\n    then failwith_false \"valid_terminator: labels of true branches not matched at block\" [bid]\n    else\n\n    if negb (l_dec l2_src l2_tgt)\n    then failwith_false \"valid_terminator: labels of false branches not matched at block\" [bid]\n    else\n\n    if negb (valid_phinodes hint_fdef (add_terminator_cond inv0 src tgt l1_src) m_src m_tgt blocks_src blocks_tgt bid l1_src)\n    then failwith_false \"valid_terminator: valid_phinodes of true branches failed at block\" [bid]\n    else\n\n    if negb (valid_phinodes hint_fdef (add_terminator_cond inv0 src tgt l2_src) m_src m_tgt blocks_src blocks_tgt bid l2_src)\n    then failwith_false \"valid_terminator: valid_phinodes of false branches failed at block\" [bid]\n    else true\n\n  | insn_br_uncond _ l_src, insn_br_uncond _ l_tgt =>\n    if negb (l_dec l_src l_tgt)\n    then failwith_false \"valid_terminator: labels of unconditional branches not matched at block\" [bid]\n    else\n\n    if negb (valid_phinodes hint_fdef (add_terminator_cond inv0 src tgt l_src) m_src m_tgt blocks_src blocks_tgt bid l_src)\n    then failwith_false \"valid_terminator: valid_phinodes of unconditional branches failed at block\" [bid]\n    else true\n\n  | insn_switch _ typ_src val_src l0_src ls_src,\n    insn_switch _ typ_tgt val_tgt l0_tgt ls_tgt =>\n    if negb (typ_dec typ_src typ_tgt)\n    then failwith_false \"valid_terminator: types of switch conditions failed at block\" [bid]\n    else\n\n    if negb (Assertion.inject_value\n               inv0\n               (ValueT.lift Tag.physical val_src)\n               (ValueT.lift Tag.physical val_tgt))\n    then failwith_false \"valid_terminator: value of switch conditions failed at block\" [bid]\n    else\n\n    if negb (l_dec l0_src l0_tgt)\n    then failwith_false \"valid_terminator: default labels of switch failed at block\" [bid]\n    else\n\n    if negb (list_const_l_dec ls_src ls_tgt)\n    then failwith_false \"valid_terminator: other labels conditions failed at block\" [bid]\n    else\n\n    if negb (forallb\n               (fun cl =>\n                  if negb (valid_phinodes hint_fdef (add_terminator_cond inv0 src tgt cl.(snd)) m_src m_tgt blocks_src blocks_tgt bid cl.(snd))\n                  then failwith_false \"valid_terminator: valid_phinodes of switches failed at block\" [bid]\n                  else true)\n               ls_src)\n    then failwith_false \"valid_terminator: valid_phinodes failed\" [bid]\n    else\n\n    if negb (valid_phinodes hint_fdef (add_terminator_cond inv0 src tgt l0_src) m_src m_tgt blocks_src blocks_tgt bid l0_src)\n    then failwith_false \"valid_terminator: valid_phinodes failed\" [bid]\n    else true\n\n  | insn_unreachable _, insn_unreachable _ => true\n  | _, _ => failwith_false \"valid_terminator: types of terminators not matched at block\" [bid]\n  end.\n\nDefinition valid_stmts\n           (hint_fdef:ValidationHint.fdef)\n           (hint:ValidationHint.stmts)\n           (m_src m_tgt:module)\n           (blocks_src blocks_tgt:blocks)\n           (bid:l) (src tgt:stmts): bool :=\n  let '(stmts_intro phinodes_src cmds_src terminator_src) := src in\n  let '(stmts_intro phinodes_tgt cmds_tgt terminator_tgt) := tgt in\n  match valid_cmds m_src m_tgt cmds_src cmds_tgt hint.(ValidationHint.cmds) hint.(ValidationHint.assertion_after_phinodes) with\n  | None => failwith_false \"valid_stmts: valid_cmds failed at block\" [bid]\n  | Some inv =>\n    (if (valid_terminator hint_fdef inv m_src m_tgt blocks_src blocks_tgt bid terminator_src terminator_tgt)\n     then true\n     else\n       let infrules := gen_infrules_from_insns\n                         (insn_terminator terminator_src)\n                         (insn_terminator terminator_tgt)\n                         inv in\n       let inv' := apply_infrules m_src m_tgt infrules inv in\n       let inv' := debug_print_auto infrules inv' in\n       (if (valid_terminator hint_fdef inv' m_src m_tgt blocks_src blocks_tgt bid terminator_src terminator_tgt)\n        then true\n        else failwith_false \"valid_stmts: valid_terminator failed at block\" [bid]))\n  end.\n\nDefinition valid_entry_stmts (src tgt:stmts) (hint:ValidationHint.stmts)\n                             (la_src la_tgt:args) (products_src products_tgt:products): bool :=\n  let '(stmts_intro phinodes_src _ _) := src in\n  let '(stmts_intro phinodes_tgt _ _) := tgt in\n  if negb (is_empty phinodes_src)\n  then failwith_false \"valid_entry_stmts: phinode of source not empty\" nil\n  else\n  if negb (is_empty phinodes_tgt)\n  then failwith_false \"valid_entry_stmts: phinode of target not empty\" nil\n  else\n  if negb (Assertion.implies (Assertion.function_entry_inv la_src la_tgt products_src products_tgt) hint.(ValidationHint.assertion_after_phinodes))\n  then failwith_false \"valid_entry_stmts: implies fail at function entry\" nil\n  else true\n  .\n\nDefinition valid_fdef\n           (m_src m_tgt:module)\n           (src tgt:fdef)\n           (hint:ValidationHint.fdef): bool :=\n  let '(fdef_intro fheader_src blocks_src) := src in\n  let '(fdef_intro fheader_tgt blocks_tgt) := tgt in\n  let '(module_intro layouts_src namedts_src products_src) := m_src in\n  let '(module_intro layouts_tgt namedts_tgt products_tgt) := m_tgt in\n\n  let fid_src := getFheaderID fheader_src in\n  let fid_tgt :=getFheaderID fheader_tgt in\n\n  if negb (fheader_dec fheader_src fheader_tgt)\n  then failwith_false \"valid_fdef: function headers not matched at fheaders\" (fid_src::fid_tgt::nil)\n  else\n  match blocks_src, blocks_tgt with\n  | (bid_src, block_src)::_, (bid_tgt, block_tgt)::_ =>\n    if negb (id_dec bid_src bid_tgt)\n    then failwith_false \"valid_fdef: entry block ids not matched at bids of\" (fid_src::bid_src::bid_tgt::nil)\n    else\n    match lookupAL _ hint bid_src with\n    | Some hint_stmts =>\n      if negb (valid_entry_stmts block_src block_tgt hint_stmts (getArgsOfFdef src) (getArgsOfFdef tgt) products_src products_tgt)\n      then failwith_false \"valid_fdef: valid_entry_stmts failed at\" (fid_src::bid_src::nil)\n      else true\n\n    | None => failwith_false \"valid_fdef: entry block hint not exist at block\" (fid_src::bid_src::nil)\n    end\n\n  | _, _ => failwith_false \"valid_fdef: empty source or target block\" (fid_src::nil)\n  end &&\n  forallb2AL\n    (fun bid stmts_src stmts_tgt =>\n       match lookupAL _ hint bid with\n       | Some hint_stmts =>\n         if negb (valid_stmts hint hint_stmts m_src m_tgt blocks_src blocks_tgt bid stmts_src stmts_tgt)\n         then failwith_false \"valid_fdef: valid_stmts failed at block\" (fid_src::bid::nil)\n         else true\n\n       | None => failwith_false \"valid_fdef: block hint not exist at block\" (fid_src::bid::nil)\n       end)\n    blocks_src blocks_tgt.\n\nDefinition valid_product (hint:ValidationHint.products) (m_src m_tgt:module) (src tgt:product): bool :=\n  match src, tgt with\n  | product_gvar gvar_src, product_gvar gvar_tgt =>\n    if negb (Decs.gvar_eqb gvar_src gvar_tgt)\n    then failwith_false \"valid_product: global variables not matched\" ((getGvarID gvar_src)::(getGvarID gvar_tgt)::nil)\n    else true\n  | product_fdec fdec_src, product_fdec fdec_tgt =>\n    if negb (fdec_dec fdec_src fdec_tgt)\n    then failwith_false \"valid_product: function declarations not matched\" ((getFdecID fdec_src)::(getFdecID fdec_tgt)::nil)\n    else true\n  | product_fdef fdef_src, product_fdef fdef_tgt =>\n    let fid_src := getFdefID fdef_src in\n    let fid_tgt := getFdefID fdef_tgt in\n    if negb (id_dec fid_src fid_tgt)\n    then failwith_false \"valid_product: function ids not matched\" (fid_src::fid_tgt::nil)\n    else\n    match lookupAL _ hint fid_src with\n    | None => failwith_false \"valid_product: hint of function not exist\" [fid_src]\n    | Some hint_fdef =>\n      if negb (valid_fdef m_src m_tgt fdef_src fdef_tgt hint_fdef)\n      then failwith_false \"valid_product: valid_fdef failed\" [fid_src]\n      else true\n    end\n  | _, _ =>\n    failwith_false \"valid_product: source and target product types not matched\" nil\n  end.\n\nDefinition valid_products (hint:ValidationHint.products) (m_src m_tgt:module) (src tgt:products): bool :=\n  list_forallb2 (valid_product hint m_src m_tgt) src tgt.\n\nDefinition valid_module (hint:ValidationHint.module) (src tgt:module): option bool :=\n  let '(module_intro layouts_src namedts_src products_src) := src in\n  let '(module_intro layouts_tgt namedts_tgt products_tgt) := tgt in\n  if negb (layouts_dec layouts_src layouts_tgt)\n  then Some false\n  else\n  if negb (namedts_dec namedts_src namedts_tgt)\n  then Some false\n  else\n  if negb (valid_products hint src tgt products_src products_tgt)\n  then failwith_None \"valid_module: valid_products failed\" nil\n  else Some true.\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/Validator.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2667228248133341}}
{"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 List.\n(*From Flocq\nRequire Import Binary 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\nDefinition default_nan_64 := (true, iter_nat 51 _ xO xH).\nDefinition default_nan_32 := (true, iter_nat 22 _ xO xH).\n\n(* Always choose the first NaN argument, if any *)\n\nDefinition choose_nan_64 (l: list (bool * positive)) : bool * positive :=\n  match l with nil => default_nan_64 | n :: _ => n end.\n\nDefinition choose_nan_32 (l: list (bool * positive)) : bool * positive :=\n  match l with nil => default_nan_32 | n :: _ => n end.\n\nLemma choose_nan_64_idem: forall n,\n  choose_nan_64 (n :: n :: nil) = choose_nan_64 (n :: nil).\nProof. auto. Qed.\n\nLemma choose_nan_32_idem: forall n,\n  choose_nan_32 (n :: n :: nil) = choose_nan_32 (n :: nil).\nProof. auto. Qed.\n\nDefinition fma_order {A: Type} (x y z: A) := (x, y, z).\n\nDefinition fma_invalid_mul_is_nan := false.\n\nDefinition float_of_single_preserves_sNaN := false.\n\nGlobal Opaque ptr64 big_endian splitlong\n              default_nan_64 choose_nan_64\n              default_nan_32 choose_nan_32\n              fma_order fma_invalid_mul_is_nan\n              float_of_single_preserves_sNaN.\n", "meta": {"author": "JulianXian", "repo": "addr_trans", "sha": "96c71b81a178591011aedbb296ca05548b8e2879", "save_path": "github-repos/coq/JulianXian-addr_trans", "path": "github-repos/coq/JulianXian-addr_trans/addr_trans-96c71b81a178591011aedbb296ca05548b8e2879/lib_from_compcert/Archi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.26672281904287887}}
{"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\n(** * Converting General Typing To Tight Typing *)\n\nSet Implicit Arguments.\n\nRequire Import Sequences.\nRequire Import Coq.Program.Equality.\nRequire Import Definitions RecordAndInertTypes PreciseTyping TightTyping InvertibleTyping\n        Narrowing Replacement ReplacementTyping GADTRules.\n\n(** ** Sel-<: Replacement *)\n\n\n(** This lemma strengthens the tight [Sel-<:-#] and [<:-Sel-#] subtyping rules\n    ([subtyp_sel1_t] and [subtyp_sel2_t]) by replacing the ⊢!!!\n    premise with a ⊢# premise: #<br>#\n    if [G ⊢# p: {A: S..U}] then [G ⊢# S <: p.A <: U] *)\nLemma sel_replacement: forall G p A S U,\n    inert G ->\n    G ⊢# trm_path p : typ_rcd {A >: S <: U} ->\n    G ⊢# p↓A <: U /\\ G ⊢# S <: p↓A.\nProof.\n  introv Hi Hty.\n  pose proof (replacement_closure Hi Hty) as Hinv.\n  pose proof (repl_to_precise_rcd Hi Hinv) as [T [Ht [Hs1 Hs2]]].\n  split.\n  - apply subtyp_sel1_t in Ht. apply subtyp_trans_t with (T:=T); auto.\n  - apply subtyp_sel2_t in Ht. apply subtyp_trans_t with (T:=T); auto.\nQed.\n\n(** If [Γ ⊢# p] then [Γ ⊢!! p] *)\nLemma tight_to_prec_exists G p T :\n  inert G ->\n  G ⊢# trm_path p : T ->\n  exists U, G ⊢!! p : U.\nProof.\n  intros Hi Hp. pose proof (replacement_closure Hi Hp).\n  apply repl_to_inv in H as [? ?]. apply inv_to_prec in H as [? ?]. apply* pt2_exists.\nQed.\n\n(** ** Sngl-<: Replacement *)\n\n(** This lemma strengthens the tight [Sngl-<:-#] and [<:-Sngl-#] subtyping rules\n    ([subtyp_sngl_pq_t] and [subtyp_sngl_qp_t]) by replacing the ⊢!!! premise\n    with a ⊢# premise: #<br>#\n    if [G ⊢# p: q.type] and [q] is well-typed then [G ⊢# T <: T[q/p] <: T] *)\nLemma sngl_replacement: forall G p q T U S,\n    inert G ->\n    G ⊢# trm_path p: {{ q }} ->\n    G ⊢# trm_path q : S ->\n    repl_typ p q T U ->\n    G ⊢# T <: U /\\ G ⊢# U <: T.\nProof.\n  introv Hi Hp Hr.\n  apply (tight_to_prec_exists Hi) in Hr as [V Hq].\n  lets Hc: (replacement_closure Hi Hp).\n  pose proof (repl_to_invertible_sngl Hi Hc Hq) as [r [W [Hpt [Hq' [-> | Hpq]]]]];\n    pose proof (inv_to_precise_sngl Hi Hpt (pt3 Hq')) as [r' [Ht [-> | Hrc']]].\n  - split. eauto. apply repl_swap in H. eauto.\n  - split.\n    + destruct (repl_insert r H) as [X [Hr1 Hr2]].\n      eapply subtyp_sngl_pq_t. eapply pt3_sngl_trans3. apply Ht. eauto. eauto. eauto.\n    + destruct (repl_insert r' H) as [X [Hr1 Hr2]].\n      apply subtyp_trans_t with (T:=X).\n      * apply repl_swap in Hr2. eauto.\n      * apply repl_swap in Hr1. eauto.\n  - split.\n    + destruct (repl_insert r H) as [X [Hr1 Hr2]].\n      apply subtyp_trans_t with (T:=X); eauto.\n    + destruct (repl_insert r H) as [X [Hr1 Hr2]].\n      apply subtyp_trans_t with (T:=X).\n      apply repl_swap in Hr2. eauto. apply repl_swap in Hr1. eauto.\n  - split.\n    + destruct (repl_insert r' H) as [X [Hr1 Hr2]].\n      apply subtyp_trans_t with (T:=X).\n      * eauto.\n      * destruct (repl_insert r Hr2) as [S' [Hr1' Hr2']].\n        apply subtyp_trans_t with (T:=S'); eauto.\n    + destruct (repl_insert r H) as [X [Hr1 Hr2]].\n      apply subtyp_trans_t with (T:=X).\n      * apply repl_swap in Hr2. eauto.\n      * destruct (repl_insert r' Hr1) as [S' [Hr1' Hr2']].\n        apply subtyp_trans_t with (T:=S').\n        ** apply repl_swap in Hr2'. eauto.\n        ** apply repl_swap in Hr1'. eauto.\nQed.\n\n(** ** General to Tight [⊢ to ⊢#] *)\n(** In an inert environment, general typing ([ty_trm] [⊢]) can\n    be reduced to tight typing ([ty_trm_t] [⊢#]).\n\n    [inert G]           #<br>#\n    [G ⊢ t: T]          #<br>#\n    [――――――――――――――]    #<br>#\n    [G ⊢# t: T] #<br># #<br>#\n\n    and                 #<br># #<br>#\n    [inert G]           #<br>#\n    [G ⊢ S <: U]        #<br>#\n    [――――――――――――――――]  #<br>#\n    [G ⊢# S <: U]         *)\nLemma general_to_tight: forall G0,\n  inert G0 ->\n  (forall G t T,\n     G ⊢ t : T ->\n     G = G0 ->\n     G ⊢# t : T) /\\\n  (forall G S U,\n     G ⊢ S <: U ->\n     G = G0 ->\n     G ⊢# S <: U).\nProof.\n  intros G0 Hi.\n  apply ts_mutind; intros; subst;\n    try solve [eapply sel_replacement; auto]; eauto.\n  - specialize (H eq_refl).\n    pose proof (invert_subtyp_rcd_t _ _ _ _ _ _ _ _ Hi e e0 H) as [Hg1 Hg2]. auto.\n  - specialize (H eq_refl).\n    pose proof (invert_subtyp_rcd_t _ _ _ _ _ _ _ _ Hi e e0 H) as [Hg1 Hg2]. auto.\n  - specialize (H eq_refl). apply* invert_subtyp_all_t.\n  - destruct* (sngl_replacement Hi (H eq_refl) (H0 eq_refl) r).\n  - apply repl_swap in r. destruct* (sngl_replacement Hi (H eq_refl) (H0 eq_refl) r).\nQed.\n\n(** The general-to-tight lemma, formulated for term typing. *)\nLemma general_to_tight_typing: forall G t T,\n  inert G ->\n  G ⊢ t : T ->\n  G ⊢# t : T.\nProof.\n  intros. apply* general_to_tight.\nQed.\n\n(** If [Γ ⊢ p] then [Γ ⊢!!! p] *)\nLemma pt3_exists G p T :\n  inert G ->\n  G ⊢ trm_path p : T ->\n  exists U, G ⊢!!! p : U.\nProof.\n  intros Hi Hp. apply (general_to_tight_typing Hi) in Hp.\n  apply tight_to_prec_exists in Hp as [? ?]; eauto.\nQed.\n\n(** ** Proof Recipe *)\n(** This tactic converts general typing of paths or values to as much precise typing\n    as possible. *)\nLtac proof_recipe :=\n  match goal with\n  | [ Hg: ?G ⊢ _ : _,\n      Hi: inert ?G |- _ ] =>\n    apply (general_to_tight_typing Hi) in Hg;\n    ((apply (replacement_closure Hi) in Hg) || (apply (replacement_closure_v Hi) in Hg));\n    try lets Hok: (inert_ok Hi);\n    try match goal with\n        | [ Hr: ?G ⊢// _ : ∀(_) _,\n            Hok: ok ?G |- _ ] =>\n          destruct (repl_to_precise_typ_all Hi Hr) as [Spr [Tpr [Lpr [Hpr [Hspr1 Hspr2]]]]]\n        | [ Hrv: ?G ⊢//v _ : μ _ |- _ ] =>\n          apply (repl_to_invertible_obj Hi) in Hrv as [U' [Hrv Hrc]];\n          apply (invertible_to_precise_obj Hi) in Hrv as [U'' [Hrv Hrc']];\n          try match goal with\n              | [ Hv: _ ⊢!v val_new ?T _ : μ ?U |- _ ] =>\n                assert (T = U) as <- by (inversion Hv; subst*)\n              end\n        | [ Hrv: ?G ⊢//v _ : ∀(_) _ |- _ ] =>\n           apply repl_val_to_precise_lambda in Hrv\n              as [L1 [S1 [T1 [Hvpr [HS1 HS2]]]]]; auto\n       end\n  end.\n\n(** If a path has a function type then its III-level precise type is\n    also a function type that is a subtype of the former. *)\nLemma path_typ_all_to_precise: forall G p T U,\n    inert G ->\n    G ⊢ trm_path p : ∀(T) U ->\n    (exists L T' U',\n        G ⊢!!! p : ∀(T') U' /\\\n        G ⊢ T <: T' /\\\n        (forall y, y \\notin L -> G & y ~ T ⊢ (open_typ y U') <: (open_typ y U))).\nProof.\n  introv Hin Ht. proof_recipe. repeat eexists. eauto. apply* tight_to_general. eauto.\nQed.\n\n(** If a value has a function type then the value is a function. *)\nLemma val_typ_all_to_lambda: forall G v T U,\n    inert G ->\n    G ⊢ trm_val v : ∀(T) U ->\n    (exists L T' t,\n        v = λ(T') t /\\\n        G ⊢ T <: T' /\\\n        (forall y, y \\notin L -> G & y ~ T ⊢ (open_trm y t) : open_typ y U)).\nProof.\n  introv Hin Ht. proof_recipe. inversions Hvpr.\n  exists (L1 \\u L \\u (dom G)) S1 t. repeat split~.\n  intros. assert (HL: y \\notin L) by auto. assert (HL0: y \\notin L1) by auto.\n  specialize (HS2 y HL0).\n  specialize (H2 y HL).\n  eapply ty_sub; eauto. eapply narrow_typing in H2; eauto.\nQed.\n\nLemma invert_subtyp_all : forall G S1 T1 S2 T2,\n    inert G ->\n    G ⊢ ∀(S1) T1 <: ∀(S2) T2 ->\n    G ⊢ S2 <: S1 /\\ (exists L, forall x, x \\notin L ->\n       G & x ~ S2 ⊢ open_typ x T1 <: open_typ x T2).\nProof.\n  introv H0 H.\n  lets Hgt: (general_to_tight H0). destruct Hgt as [_ Hgt].\n  apply Hgt in H; eauto 2.\n  lets Ht: (invert_subtyp_all_t _ _ _ _ _ H0 H).\n  destruct Ht as [Ht1 Ht2]. split; eauto 2.\n  apply* tight_to_general.\nQed.\n\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/GeneralToTight.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2667039998648025}}
{"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 bar_induction2.\nRequire Export subst_tacs.\nRequire Export per_props_equality.\nRequire Export lsubstc_vars.\n\n\nLemma eq_kseq_of_seq {o} :\n  forall lib (s : @CTerm o) v k,\n    is_seq lib s\n    -> eq_kseq lib s (seq2kseq s k v) k.\nProof.\n  introv iss.\n  unfold eq_kseq.\n  apply implies_equality_natk2nat.\n  introv l.\n  unfold is_seq in iss.\n\n  assert (equality lib (mkc_nat m) (mkc_nat m) mkc_tnat) as equ by (eauto with slow).\n\n  eapply equality_nat2nat_apply in iss;[|eauto].\n  allrw @member_eq.\n  apply member_tnat_implies_computes in iss; exrepnd.\n  eexists; dands; eauto.\n  unfold seq2kseq.\n\n  apply cequivc_nat_implies_computes_to_valc.\n  apply computes_to_valc_implies_cequivc in iss0.\n  eapply cequivc_trans;[apply cequivc_beta|].\n  repeat (rewrite mkcv_less_substc).\n  repeat (rewrite mkcv_apply_substc).\n  repeat (rewrite mkcv_bot_substc).\n  repeat (rewrite mkcv_nat_substc).\n  repeat (rewrite mkcv_zero_substc).\n  repeat (rewrite mkc_var_substc).\n  repeat (rewrite csubst_mk_cv).\n  rewrite mkc_zero_eq.\n\n  eapply cequivc_trans;[apply cequivc_mkc_less_nat|].\n  boolvar; try omega.\n  eapply cequivc_trans;[apply cequivc_mkc_less_nat|].\n  boolvar; try omega.\n  auto.\nQed.\nHint Resolve eq_kseq_of_seq : slow.\n\nLemma approxc_bot {o} :\n  forall lib (t : @CTerm o), approxc lib mkc_bot t.\nProof.\n  introv; destruct_cterms; unfold approxc; simpl.\n  unfold mk_bot.\n  apply bottom_approx_any; eauto 3 with slow.\nQed.\nHint Resolve approxc_bot : slow.\n\nLemma mk_seq2kseq0 {o} :\n  forall lib (c : @CTerm o) v,\n    cequivc lib (seq2kseq c 0 v) (mkc_lam v (mkcv_bot [v])).\nProof.\n  introv.\n  unfold seq2kseq.\n  apply implies_cequivc_lam; introv.\n\n  eapply cequivc_trans;[apply cequivc_sym;apply cequivc_beta|].\n  eapply cequivc_trans;[apply cequivc_beta|].\n  repeat (rewrite mkcv_less_substc).\n  repeat (rewrite mkcv_apply_substc).\n  repeat (rewrite mkc_var_substc).\n  repeat (rewrite mkcv_nat_substc).\n  repeat (rewrite mkcv_zero_substc).\n  repeat (rewrite mkcv_bot_substc).\n  repeat (rewrite csubst_mk_cv).\n\n  apply cequivc_iff_approxc; dands; eauto 3 with slow.\n  apply approxc_assume_hasvalue; intro hv.\n\n  destruct_cterms.\n  unfold hasvalue_likec in hv; unfold approxc; allsimpl.\n  apply hasvalue_like_implies_or in hv;\n    [|repeat (apply isprogram_mk_less; dands; eauto 2 with slow);\n       apply isprogram_apply; eauto 3 with slow].\n\n  destruct hv as [hv|hv].\n\n  - apply hasvalue_mk_less in hv; eauto 2 with slow;\n    [|apply wf_less; eauto 2 with slow; apply wf_apply; eauto 2 with slow].\n    exrepnd; repndors; repnd.\n\n    { apply not_hasvalue_bot in hv1; tcsp. }\n\n    apply reduces_to_if_isvalue_like in hv2; eauto 3 with slow.\n    rw <- @int_zero in hv2; ginv.\n\n    eapply approx_trans;\n      [apply approx_mk_less;\n        [apply reduces_to_implies_approx2;eauto 2 with slow\n        |apply approx_refl; eauto 2 with slow\n        |apply approx_refl; eauto 2 with slow\n        |apply approx_refl; eauto 2 with slow;\n         apply isprogram_mk_less; dands; eauto 2 with slow;\n         apply isprogram_apply; eauto 3 with slow]\n      |].\n\n    rw <- @int_zero.\n\n    eapply approx_trans;\n      [apply reduces_to_implies_approx2;\n        [repeat (apply isprogram_mk_less; dands; eauto 2 with slow);\n          apply isprogram_apply; eauto 3 with slow\n        |apply reduces_to_if_step; csunf; simpl; dcwf h; simpl;\n         unfold compute_step_comp; simpl; boolvar; try omega; reflexivity]\n      |].\n\n    apply hasvalue_mk_less in hv1; eauto 2 with slow;\n    [|apply wf_apply; eauto 2 with slow].\n    exrepnd.\n\n    eapply reduces_to_eq_val_like in hv0;try (exact hv2); eauto 2 with slow; ginv.\n    apply reduces_to_if_isvalue_like in hv4; eauto 3 with slow.\n    unfold mk_nat in hv4; ginv.\n\n    repndors; repnd;\n    [|apply not_hasvalue_bot in hv1; tcsp].\n\n    eapply approx_trans;\n      [apply approx_mk_less;\n        [apply reduces_to_implies_approx2;eauto 2 with slow\n        |apply approx_refl; eauto 2 with slow\n        |apply approx_refl; eauto 2 with slow;\n         apply isprogram_apply; eauto 2 with slow\n        |apply approx_refl; eauto 2 with slow]\n      |].\n\n    eapply approx_trans;\n      [apply reduces_to_implies_approx2;\n        [repeat (apply isprogram_mk_less; dands; eauto 2 with slow);\n          apply isprogram_apply; eauto 3 with slow\n        |apply reduces_to_if_step; csunf; simpl; dcwf h; simpl;\n         unfold compute_step_comp; simpl; boolvar;[|reflexivity]; try omega]\n      |].\n\n    eauto 3 with slow.\n\n  - unfold raises_exception in hv; exrepnd.\n    apply computes_to_exception_mk_less in hv1; eauto 2 with slow;\n    [|apply wf_less; eauto 2 with slow; apply wf_apply; eauto 2 with slow].\n    repndors; exrepnd; repndors; exrepnd.\n\n    + apply bottom_doesnt_raise_an_exception in hv1; tcsp.\n\n    + apply reduces_to_if_isvalue_like in hv2; eauto 3 with slow.\n      rw <- @int_zero in hv2; ginv.\n\n      eapply approx_trans;\n        [apply approx_mk_less;\n          [apply reduces_to_implies_approx2;eauto 2 with slow\n          |apply approx_refl; eauto 2 with slow\n          |apply approx_refl; eauto 2 with slow\n          |apply approx_refl; eauto 2 with slow;\n           apply isprogram_mk_less; dands; eauto 2 with slow;\n           apply isprogram_apply; eauto 3 with slow]\n        |].\n\n      rw <- @int_zero.\n\n      eapply approx_trans;\n        [apply reduces_to_implies_approx2;\n          [repeat (apply isprogram_mk_less; dands; eauto 2 with slow);\n            apply isprogram_apply; eauto 3 with slow\n          |apply reduces_to_if_step; csunf; simpl; dcwf h; simpl;\n           unfold compute_step_comp; simpl; boolvar; try omega; reflexivity]\n        |].\n\n      apply computes_to_exception_mk_less in hv1; eauto 2 with slow;\n      [|apply wf_apply; eauto 2 with slow].\n      repndors; exrepnd; repndors; exrepnd.\n\n      * eapply reduces_to_eq_val_like in hv0;try (exact hv2); eauto 2 with slow; ginv.\n        apply reduces_to_if_isvalue_like in hv4; eauto 3 with slow.\n        unfold mk_nat in hv4; ginv.\n        try omega.\n\n      * apply bottom_doesnt_raise_an_exception in hv1; tcsp.\n\n      * eapply reduces_to_exception_eq in hv0;[|eauto].\n        apply iscancan_doesnt_raise_an_exception in hv0; eauto 2 with slow; tcsp.\n\n      * apply iscancan_doesnt_raise_an_exception in hv2; eauto 2 with slow; tcsp.\n\n    +\nAbort.\n\n\n(**\n\n  Bar induction, where\n    X is the proposition\n    B is the bar\n    ext(s,n,t) = \\m. if m=n then t else s m\n<<\n   H |- squash(X 0 (norm c 0))\n\n     By bar_induction B i a s x m n t\n\n     H, n:nat, s: nat_n -> nat |- (B n s) in Type(i)      // B is a well-formed predicate on finite sequences\n     H, s: nat -> nat |- squash(exists n:nat. B n s)      // B is a bar\n     H, n:nat, s: nat_n -> nat, m: B n s |- X n s         // Base case: the conclusion is true at the bar\n     H, n:nat, s: nat_n -> nat, x: (forall m: nat. X (n + 1) (ext(s,n,m))) |- X n s // induction case\n>>\n\n*)\n\nDefinition rule_bar_induction_nat {o}\n           (f X c B e : @NTerm o)\n           (s n m v x : NVar)\n           (i : nat)\n           (H : barehypotheses) :=\n  mk_rule\n    (mk_bseq H (mk_conclax (mk_squash (mk_apply2 X mk_zero (mk_seq2kseq c (mk_nat 0) v)))))\n    [ mk_bseq (snoc (snoc H (mk_hyp n mk_tnat))\n                    (mk_hyp s (mk_natk2nat (mk_var n))))\n              (mk_conclax (mk_member (mk_apply2 B (mk_var n) (mk_var s)) (mk_uni i))),\n      mk_bseq (snoc H (mk_hyp s mk_nat2nat))\n              (mk_conclax (mk_squash\n                             (mk_exists mk_tnat\n                                        n\n                                        (mk_apply2 B (mk_var n) (mk_var s))))),\n      mk_bseq (snoc (snoc (snoc H (mk_hyp n mk_tnat))\n                          (mk_hyp s (mk_natk2nat (mk_var n))))\n                    (mk_hyp m (mk_apply2 B (mk_var n) (mk_var s))))\n              (mk_concl (mk_apply2 X (mk_var n) (mk_var s)) e),\n      mk_bseq (snoc (snoc (snoc H (mk_hyp n mk_tnat))\n                          (mk_hyp s (mk_natk2nat (mk_var n))))\n                    (mk_hyp x (mk_all\n                                 mk_tnat\n                                 m\n                                 (mk_squash (mk_apply2 X (mk_plus1 (mk_var n)) (mk_update_seq (mk_var s) (mk_var n) (mk_var m) v))))))\n              (mk_conclax (mk_apply2 X (mk_var n) (mk_var s)))\n    ]\n    [].\n\nLemma rule_bar_induction_nat_true {o} :\n  forall lib (f X c B d e : @NTerm o)\n         (s n m v x : NVar)\n         (i : nat)\n         (H : @barehypotheses o)\n         (dxv : x <> v)\n         (dsv : s <> v)\n         (dnv : n <> v)\n         (dnv : m <> v)\n         (dnm : n <> m)\n         (dsm : s <> m)\n         (nvc : !LIn v (free_vars c))\n         (nnB : !LIn n (free_vars B))\n         (nsB : !LIn s (free_vars B)),\n    rule_true lib (rule_bar_induction_nat f X c B e s n m v x i H).\nProof.\n  unfold rule_bar_induction_nat, 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  destruct Hyp  as [wf1 hyp_wfd].\n  destruct Hyp0 as [wf2 hyp_bar].\n  destruct Hyp1 as [wf3 hyp_imp].\n  destruct Hyp2 as [wf4 hyp_ind].\n  destseq; allsimpl; proof_irr; GC.\n\n  unfold closed_extract; simpl.\n\n  exists (@covered_axiom o (nh_vars_hyps H)).\n\n  (* We prove some simple facts on our sequents *)\n  assert (s <> n\n          # s <> x\n          # n <> x\n          # !LIn x (free_vars c)\n          # !LIn s (free_vars c)\n          # !LIn n (free_vars c)\n          # !LIn x (free_vars X)\n          # !LIn s (free_vars X)\n          # !LIn n (free_vars X)\n          # !LIn m (free_vars X)\n          # !LIn x (vars_hyps H)\n          # !LIn s (vars_hyps H)\n          # !LIn n (vars_hyps H)) as vhyps.\n\n  { clear hyp_wfd hyp_bar hyp_ind hyp_imp.\n    dwfseq.\n    assert (forall x : NVar, LIn x (free_vars c) -> x <> v -> LIn x (vars_hyps H)) as imp.\n    { introv h1 h2.\n      apply cg.\n      repeat (first [rw remove_nvars_cons_r|rw remove_nvars_app_r]).\n      allrw memvar_singleton.\n      allrw <- beq_var_refl.\n      allrw remove_nvars_nil_r; allrw app_nil_r.\n      rw in_remove_nvars; rw in_single_iff; sp. }\n    sp; GC;\n    try (complete (discover; allapply @subset_hs_vars_hyps; sp)).\n  }\n\n  destruct vhyps as [ nsn vhyps ].\n  destruct vhyps as [ nsx vhyps ].\n  destruct vhyps as [ nnx vhyps ].\n  destruct vhyps as [ nxc vhyps ].\n  destruct vhyps as [ nsc vhyps ].\n  destruct vhyps as [ nnc vhyps ].\n  destruct vhyps as [ nxX vhyps ].\n  destruct vhyps as [ nsX vhyps ].\n  destruct vhyps as [ nnX vhyps ].\n  destruct vhyps as [ nmX vhyps ].\n  destruct vhyps as [ nxH vhyps ].\n  destruct vhyps as [ nsH nnH ].\n  (* done with proving these simple facts *)\n\n  vr_seq_true.\n  lsubst_tac.\n\n  pose proof (lsubstc_mk_seq2kseq c 0 v w3 s1 c3) as sc1.\n  repeat (autodimp sc1 hyp).\n  exrepnd.\n  rw sc1.\n\n  pose proof (lsubstc_mk_seq2kseq c 0 v w3 s2 c7) as sc2.\n  autodimp sc2 hyp.\n  exrepnd.\n  rw sc2.\n\n  clear sc1 sc2.\n  clear_irr.\n  clear_wf_hyps.\n\n  rw @tequality_mkc_squash.\n  rw @member_mkc_squash.\n\n  assert (!LIn n (dom_csub s1)) as nns1.\n  { apply similarity_dom in sim; repnd.\n    rw sim0; auto. }\n\n  assert (!LIn n (dom_csub s2)) as nns2.\n  { apply similarity_dom in sim; repnd.\n    rw sim; auto. }\n\n  assert (!LIn s (dom_csub s1)) as nss1.\n  { apply similarity_dom in sim; repnd.\n    rw sim0; auto. }\n\n  assert (!LIn s (dom_csub s2)) as nss2.\n  { apply similarity_dom in sim; repnd.\n    rw sim; auto. }\n\n  assert (!LIn x (dom_csub s1)) as nxs1.\n  { apply similarity_dom in sim; repnd.\n    rw sim0; auto. }\n\n  assert (!LIn x (dom_csub s2)) as nxs2.\n  { apply similarity_dom in sim; repnd.\n    rw sim; auto. }\n\n  assert (wf_term B) as wB.\n  { clear hyp_wfd.\n    allrw @wf_member_iff2.\n    allrw <- @wf_apply2_iff; sp.\n  }\n\n  assert (cover_vars B s1 # cover_vars B s2) as cB.\n  { clear hyp_wfd.\n    allrw @covered_member.\n    allrw @covered_apply2; repnd.\n    allrw @vars_hyps_snoc; allsimpl.\n    apply covered_snoc_implies in ct6; auto.\n    apply covered_snoc_implies in ct6; auto.\n    dands.\n    - eapply s_cover_typ1;[exact ct6|exact sim].\n    - eapply s_cover_typ1;[exact ct6|].\n      apply similarity_sym in sim;[exact sim|]; auto.\n  }\n  destruct cB as [cB1 cB2].\n\n\n  assert (forall k seq1 seq2 s1a s2a cB1 cB2,\n            similarity lib s1a s2a H\n            -> hyps_functionality lib s1a H\n            -> eq_kseq lib seq1 seq2 k\n            -> tequality\n                 lib\n                 (mkc_apply2 (lsubstc B wB s1a cB1) (mkc_nat k) seq1)\n                 (mkc_apply2 (lsubstc B wB s2a cB2) (mkc_nat k) seq2)) as Bfunc.\n  { introv sim0 hf0 eqk.\n    vr_seq_true in hyp_wfd.\n    pose proof (hyp_wfd\n                  (snoc (snoc s1a (n,mkc_nat k)) (s,seq1))\n                  (snoc (snoc s2a (n,mkc_nat k)) (s,seq2)))\n      as h; clear hyp_wfd.\n    repeat (autodimp h hyp).\n\n    { apply hyps_functionality_snoc2; simpl; auto.\n\n      { introv equ' sim'.\n        apply similarity_snoc in sim'; simpl in sim'.\n        exrepnd; subst; ginv; inj.\n        eapply tequality_respects_alphaeqc_left;\n          [apply alphaeqc_sym; apply lsubstc_mk_natk2nat_sp2; auto;\n           apply similarity_dom in sim'3; repnd; rw sim'0; auto\n          |].\n        eapply tequality_respects_alphaeqc_right;\n          [apply alphaeqc_sym; apply lsubstc_mk_natk2nat_sp2; auto;\n           apply similarity_dom in sim'3; repnd; rw sim'3; auto\n          |].\n        allrw @lsubstc_mkc_tnat.\n        apply equality_int_nat_implies_cequivc in sim'1.\n        eapply tequality_respects_cequivc_right;\n          [apply implies_cequivc_natk2nat; exact sim'1|].\n        eauto 3 with slow.\n      }\n\n      apply hyps_functionality_snoc2; simpl; auto.\n\n      introv equ' sim'.\n      allrw @lsubstc_mkc_tnat.\n      apply tnat_type.\n    }\n\n    { assert (@wf_term o (mk_natk2nat (mk_var n))) as wfn.\n      { apply wf_term_mk_natk2nat; auto. }\n      assert (cover_vars (mk_natk2nat (mk_var n)) (snoc s1a (n,mkc_nat k))) as cvn.\n      { apply cover_vars_mk_natk2nat.\n        apply cover_vars_var.\n        rw @dom_csub_snoc.\n        rw in_snoc; simpl; sp. }\n      sim_snoc.\n      dands; auto.\n\n      { pose proof (cover_vars_mk_tnat s1a) as cvs1.\n        pose proof (@wf_tnat o) as wftn.\n        sim_snoc.\n        dands; auto.\n        allrw @lsubstc_mkc_tnat.\n        apply equality_in_tnat_nat.\n      }\n\n      eapply alphaeqc_preserving_equality;\n        [|apply alphaeqc_sym;\n           apply lsubstc_mk_natk2nat_sp2; auto];\n        auto.\n      apply similarity_dom in sim0; repnd.\n      rw sim1; auto.\n    }\n\n    exrepnd.\n    lsubst_tac.\n    apply tequality_in_uni_implies_tequality in h0; auto.\n    apply member_if_inhabited in h1. auto.\n    \n  }\n\n  pose proof (bar_induction_meta4\n                lib\n                (fun_sim_eq lib s1 H B wB)\n                (fun_sim_eq lib s1 H X w0)\n                (lsubstc B wB s1 cB1)\n                (lsubstc X w0 s1 c0)\n                (lsubstc c wt s1 ct3)\n                v)\n    as bi.\n\n  repeat (autodimp bi hyp);\n    [idtac\n    |idtac\n    |idtac\n    |pose proof (bi (lsubstc X w0 s2 c5) (seq2kseq (lsubstc c wt s2 ct4) 0 v)) as h;\n      allrw <- @mkc_zero_eq;\n      repeat (autodimp h hyp);[apply eq_kseq_seq2kseq_0|idtac|repnd; dands; complete auto];\n      exists s2 c5;\n      dands; complete auto].\n\n  - intros seq1 iss.\n\n    vr_seq_true in hyp_bar.\n    pose proof (hyp_bar\n                  (snoc s1 (s,seq1))\n                  (snoc s1 (s,seq1)))\n      as hf; clear hyp_bar.\n    repeat (autodimp hf hyp).\n\n    { apply hyps_functionality_snoc2; simpl; auto.\n\n      introv equ' sim'.\n      eapply tequality_respects_alphaeqc_left;\n        [apply alphaeqc_sym;\n          apply lsubstc_mk_nat2nat; auto\n        |].\n      eapply tequality_respects_alphaeqc_right;\n        [apply alphaeqc_sym;\n          apply lsubstc_mk_nat2nat; auto\n        |].\n      apply type_nat2nat.\n    }\n\n    { assert (@wf_term o mk_nat2nat) as wfn.\n      { apply wf_term_mk_nat2nat; auto. }\n      assert (cover_vars mk_nat2nat s1) as cvn.\n      { apply cover_vars_mk_nat2nat. }\n      sim_snoc.\n      dands; auto.\n      { eapply similarity_refl; eauto. }\n      eapply alphaeqc_preserving_equality;\n        [|apply alphaeqc_sym;\n           apply lsubstc_mk_nat2nat; auto].\n      auto.\n    }\n\n    exrepnd.\n    clear hf0.\n    lsubst_tac.\n    apply equality_in_mkc_squash in hf1; exrepnd.\n    clear hf0 hf2.\n    allunfold @mk_exists.\n    lsubst_tac.\n    allrw @lsubstc_mkc_tnat.\n    apply inhabited_product in hf1; exrepnd.\n    clear hf2.\n\n    apply member_tnat_implies_computes in hf1; exrepnd.\n\n    exists k.\n    introv eqs fse.\n    unfold fun_sim_eq in fse; exrepnd; subst.\n\n    repeat substc_lsubstc_vars3.\n    lsubst_tac.\n    clear_wf_hyps.\n    proof_irr.\n\n    pose proof (Bfunc k seq1 (seq2kseq seq1 k v) s1 s1 cB1 cB1) as h.\n    repeat (autodimp h hyp); eauto 3 with slow.\n    { eapply similarity_refl; eauto. }\n\n    eapply inhabited_type_cequivc in hf3;\n      [|apply implies_cequivc_apply2;\n         [apply cequivc_refl\n         |apply computes_to_valc_implies_cequivc;eauto\n         |apply cequivc_refl]\n      ].\n\n    eapply inhabited_type_tequality in hf3;[|eauto].\n\n    dands; auto.\n\n  - intros k seq1 iss sb C seq2 eqs fse.\n    clear iss.\n    unfold fun_sim_eq in fse; exrepnd; subst.\n    unfold meta2_fun_on_seq in sb.\n    rename fse0 into sim0.\n\n    assert (cover_vars B s0) as cB0.\n    { eapply similarity_cover_vars;[exact sim0|]; auto. }\n\n    pose proof (sb (lsubstc B wB s0 cB0) seq2) as h; clear sb.\n    repeat (autodimp h hyp).\n    { exists s0 cB0; dands; auto. }\n    repnd.\n\n    unfold inhabited_type in h0; exrepnd.\n    rename h1 into mem.\n    rename h into teq.\n\n    vr_seq_true in hyp_imp.\n    pose proof (hyp_imp\n                  (snoc (snoc (snoc s1 (n,mkc_nat k)) (s,seq1)) (m,t))\n                  (snoc (snoc (snoc s0 (n,mkc_nat k)) (s,seq2)) (m,t)))\n      as hf.\n    repeat (autodimp hf hyp).\n\n    { apply hyps_functionality_snoc2; simpl; auto.\n\n      { introv equ' sim'.\n        apply similarity_snoc in sim'; simpl in sim'.\n        exrepnd; subst; ginv; inj.\n        apply similarity_snoc in sim'3; simpl in sim'3.\n        exrepnd; subst; ginv; inj.\n        lsubst_tac.\n        allrw @lsubstc_mkc_tnat.\n        apply equality_int_nat_implies_cequivc in sim'2.\n        eapply alphaeqc_preserving_equality in sim'1;\n          [|apply lsubstc_mk_natk2nat_sp2; auto].\n        eapply tequality_respects_cequivc_right;\n          [apply implies_cequivc_apply2;\n            [apply cequivc_refl\n            |exact sim'2\n            |apply cequivc_refl]\n          |].\n        auto.\n      }\n\n      apply hyps_functionality_snoc2; simpl; auto.\n\n      { introv equ' sim'.\n        apply similarity_snoc in sim'; simpl in sim'.\n        exrepnd; subst; ginv; cpx.\n        assert (!LIn n (dom_csub s2a)) as nns2a.\n        { apply similarity_dom in sim'3; repnd.\n          rw sim'3; auto. }\n        eapply tequality_respects_alphaeqc_left;\n          [apply alphaeqc_sym;\n            apply lsubstc_mk_natk2nat_sp2; auto\n          |].\n        eapply tequality_respects_alphaeqc_right;\n          [apply alphaeqc_sym;\n            apply lsubstc_mk_natk2nat_sp2; auto\n          |].\n        rw @lsubstc_mkc_tnat in sim'1.\n        apply equality_int_nat_implies_cequivc in sim'1.\n        eapply tequality_respects_cequivc_right;\n          [apply implies_cequivc_natk2nat; exact sim'1|].\n        eauto 3 with slow.\n      }\n\n      apply hyps_functionality_snoc2; simpl; auto.\n\n      introv equ' sim'.\n      allrw @lsubstc_mkc_tnat.\n      apply tnat_type.\n    }\n\n    { assert (wf_term (mk_apply2 B (mk_var n) (mk_var s))) as wfn.\n      { apply wf_apply2; eauto 3 with slow. }\n      assert (cover_vars (mk_apply2 B (mk_var n) (mk_var s)) (snoc (snoc s1 (n,mkc_nat k)) (s,seq1))) as cvn.\n      { apply cover_vars_apply2.\n        repeat (rw @cover_vars_var_iff).\n        repeat (rw @dom_csub_snoc); simpl.\n        repeat (rw in_snoc).\n        dands; tcsp.\n        repeat (apply cover_vars_snoc_weak); auto. }\n      sim_snoc.\n      dands; auto.\n\n      { assert (@wf_term o (mk_natk2nat (mk_var n))) as wfk.\n        { apply wf_term_mk_natk2nat; auto. }\n        assert (cover_vars (mk_natk2nat (mk_var n)) (snoc s1 (n,mkc_nat k))) as cvk.\n        { apply cover_vars_mk_natk2nat.\n          apply cover_vars_var_iff.\n          repeat (rw @dom_csub_snoc); simpl.\n          repeat (rw in_snoc); sp. }\n        sim_snoc.\n        dands; auto.\n\n        { assert (@wf_term o mk_tnat) as wft.\n          { eauto 3 with slow. }\n          assert (cover_vars mk_tnat s1) as cvt.\n          { apply cover_vars_mk_tnat. }\n          sim_snoc.\n          dands; auto.\n          allrw @lsubstc_mkc_tnat.\n          eauto 3 with slow.\n        }\n\n        eapply alphaeqc_preserving_equality;\n          [|apply alphaeqc_sym; apply lsubstc_mk_natk2nat_sp2; auto].\n        auto.\n      }\n\n      { lsubst_tac; auto. }\n    }\n\n    exrepnd.\n    lsubst_tac.\n    apply inhabited_type_if_equality in hf1.\n    unfold meta_fun_on_seq.\n    dands; auto.\n\n  - intros k seq1 iss ind C seq2 eqs fse.\n    clear iss.\n    unfold fun_sim_eq in fse; exrepnd; subst.\n\n    vr_seq_true in hyp_ind.\n\n    pose proof (hyp_ind\n                  (snoc (snoc (snoc s1 (n,mkc_nat k)) (s,seq1)) (x,lam_axiom))\n                  (snoc (snoc (snoc s0 (n,mkc_nat k)) (s,seq2)) (x,lam_axiom)))\n      as hf; clear hyp_ind.\n    repeat (autodimp hf hyp).\n\n    { apply hyps_functionality_snoc2; simpl; auto.\n\n      { introv equ' sim'.\n        apply similarity_snoc in sim'; simpl in sim'.\n        exrepnd; subst; ginv; inj.\n        apply similarity_snoc in sim'3; simpl in sim'3.\n        exrepnd; subst; ginv; inj.\n        allunfold @mk_all.\n        lsubst_tac.\n        allrw @lsubstc_mkc_tnat.\n        apply equality_int_nat_implies_cequivc in sim'2.\n        eapply alphaeqc_preserving_equality in sim'1;\n          [|apply lsubstc_mk_natk2nat_sp2; auto].\n\n        apply tequality_function; dands.\n        { apply tnat_type. }\n        introv en.\n        repeat substc_lsubstc_vars3.\n        lsubst_tac.\n        apply equality_in_tnat in en.\n        unfold equality_of_nat in en; exrepnd; spcast.\n\n        apply tequality_mkc_squash.\n\n        eapply tequality_respects_cequivc_left;\n          [apply cequivc_sym;\n            apply implies_cequivc_apply2;\n            [apply cequivc_refl\n            |apply cequivc_lsubstc_mk_plus1_sp1;auto\n            |apply cequivc_lsubstc_mk_update_seq_sp1;auto;\n             exact en1]\n          |].\n\n        assert (!LIn n (dom_csub s2a0)) as nin2.\n        { apply similarity_dom in sim'4; repnd.\n          rw sim'4; auto. }\n\n        assert (!LIn s (dom_csub s2a0)) as nis2.\n        { apply similarity_dom in sim'4; repnd.\n          rw sim'4; auto. }\n\n        eapply tequality_respects_cequivc_right;\n          [apply cequivc_sym;\n            apply implies_cequivc_apply2;\n            [apply cequivc_refl\n            |apply cequivc_lsubstc_mk_plus1_sp2; auto;\n             apply cequivc_sym;exact sim'2\n            |apply cequivc_lsubstc_mk_update_seq_sp2;auto;\n             [exact en0\n             |apply cequivc_nat_implies_computes_to_valc;\n               apply cequivc_sym;exact sim'2]\n            ]\n          |].\n\n        pose proof (ind k0) as h; clear ind.\n        unfold meta2_fun_on_upd_seq in h.\n        unfold meta2_fun_on_seq in h; repnd.\n\n        pose proof (h (lsubstc X w0 s2a0 c27) (update_seq t2 k k0 v)) as q; clear h.\n        repeat (autodimp q hyp).\n        { apply eq_kseq_update; auto. }\n        { exists s2a0 c27; dands; auto. }\n        repnd; auto.\n      }\n\n      apply hyps_functionality_snoc2; simpl; auto.\n\n      { introv equ' sim'.\n        apply similarity_snoc in sim'; simpl in sim'.\n        exrepnd; subst; ginv; inj.\n        assert (!LIn n (dom_csub s2a)) as nns2a.\n        { apply similarity_dom in sim'3; repnd.\n          rw sim'3; auto. }\n        eapply tequality_respects_alphaeqc_left;\n          [apply alphaeqc_sym;\n            apply lsubstc_mk_natk2nat_sp2; auto\n          |].\n        eapply tequality_respects_alphaeqc_right;\n          [apply alphaeqc_sym;\n            apply lsubstc_mk_natk2nat_sp2; auto\n          |].\n        rw @lsubstc_mkc_tnat in sim'1.\n        apply equality_int_nat_implies_cequivc in sim'1.\n        eapply tequality_respects_cequivc_right;\n          [apply implies_cequivc_natk2nat; exact sim'1|].\n        eauto 3 with slow.\n      }\n\n      apply hyps_functionality_snoc2; simpl; auto.\n\n      introv equ' sim'.\n      allrw @lsubstc_mkc_tnat.\n      apply tnat_type.\n    }\n\n    { assert (wf_term (mk_all mk_tnat m\n                              (mk_squash\n                                 (mk_apply2 X (mk_plus1 (mk_var n))\n                                            (mk_update_seq (mk_var s) (mk_var n) (mk_var m) v))))) as wa.\n      { apply wf_function; auto.\n        apply wf_squash.\n        apply wf_apply2; auto. }\n      assert (cover_vars (mk_all mk_tnat m\n                              (mk_squash\n                                 (mk_apply2 X (mk_plus1 (mk_var n))\n                                            (mk_update_seq (mk_var s) (mk_var n) (mk_var m) v))))\n                         (snoc (snoc s1 (n, mkc_nat k)) (s, seq1))) as ca.\n      { apply cover_vars_function; dands; auto.\n        { apply cover_vars_mk_tnat. }\n        apply cover_vars_upto_squash.\n        apply cover_vars_upto_apply2; dands; auto.\n        { repeat (rw @csub_filter_snoc).\n          allrw memvar_singleton.\n          boolvar;tcsp;GC;[].\n          repeat (apply cover_vars_upto_snoc_weak).\n          apply cover_vars_upto_csub_filter_disjoint; auto.\n          apply disjoint_singleton_r; auto. }\n        { apply cover_vars_upto_add; dands; eauto 3 with slow.\n          repeat (rw @csub_filter_snoc).\n          allrw memvar_singleton.\n          boolvar;tcsp;GC;[].\n          apply cover_vars_upto_var; simpl.\n          repeat (rw @dom_csub_snoc).\n          repeat (rw in_snoc;simpl).\n          sp. }\n        { unfold mk_update_seq.\n          apply cover_vars_upto_lam.\n          rw @csub_filter_swap.\n          rw <- @csub_filter_app_r; simpl.\n          repeat (rw @csub_filter_snoc).\n          allrw memvar_cons; simpl.\n          boolvar;tcsp;GC;[].\n          apply cover_vars_upto_int_eq; dands.\n          { apply cover_vars_upto_var; simpl.\n            repeat (rw @dom_csub_snoc).\n            repeat (rw in_snoc;simpl).\n            sp. }\n          { apply cover_vars_upto_var; simpl.\n            repeat (rw @dom_csub_snoc).\n            repeat (rw in_snoc;simpl).\n            sp. }\n          { apply cover_vars_upto_var; simpl.\n            repeat (rw @dom_csub_snoc).\n            repeat (rw in_snoc;simpl).\n            sp. }\n          { apply cover_vars_upto_apply; dands.\n            { apply cover_vars_upto_var; simpl.\n              repeat (rw @dom_csub_snoc).\n              repeat (rw in_snoc;simpl).\n              sp. }\n            { apply cover_vars_upto_var; simpl.\n              repeat (rw @dom_csub_snoc).\n              repeat (rw in_snoc;simpl).\n              sp. }\n          }\n        }\n      }\n      sim_snoc.\n      dands; auto.\n\n      { assert (@wf_term o (mk_natk2nat (mk_var n))) as wfk.\n        { apply wf_term_mk_natk2nat; auto. }\n        assert (cover_vars (mk_natk2nat (mk_var n)) (snoc s1 (n,mkc_nat k))) as cvk.\n        { apply cover_vars_mk_natk2nat.\n          apply cover_vars_var_iff.\n          repeat (rw @dom_csub_snoc); simpl.\n          repeat (rw in_snoc); sp. }\n        sim_snoc.\n        dands; auto.\n\n        { assert (@wf_term o mk_tnat) as wft.\n          { eauto 3 with slow. }\n          assert (cover_vars mk_tnat s1) as cvt.\n          { apply cover_vars_mk_tnat. }\n          sim_snoc.\n          dands; auto.\n          allrw @lsubstc_mkc_tnat.\n          eauto 3 with slow.\n        }\n\n        eapply alphaeqc_preserving_equality;\n          [|apply alphaeqc_sym; apply lsubstc_mk_natk2nat_sp2; auto].\n        auto.\n      }\n\n      { unfold mk_all.\n        lsubst_tac.\n        allrw @lsubstc_mkc_tnat.\n        apply equality_in_function.\n        dands; auto.\n\n        { apply tnat_type. }\n\n        { introv en.\n          repeat substc_lsubstc_vars3.\n          lsubst_tac.\n          apply equality_in_tnat in en.\n          unfold equality_of_nat in en; exrepnd; spcast.\n\n          apply tequality_mkc_squash.\n\n          eapply tequality_respects_cequivc_left;\n            [apply cequivc_sym;\n              apply implies_cequivc_apply2;\n              [apply cequivc_refl\n              |apply cequivc_lsubstc_mk_plus1_sp1;auto\n              |apply cequivc_lsubstc_mk_update_seq_sp1;auto;\n               exact en1]\n            |].\n\n          eapply tequality_respects_cequivc_right;\n            [apply cequivc_sym;\n              apply implies_cequivc_apply2;\n              [apply cequivc_refl\n              |apply cequivc_lsubstc_mk_plus1_sp2; auto;\n               apply cequivc_sym;exact sim'2\n              |apply cequivc_lsubstc_mk_update_seq_sp1;auto;\n               exact en0]\n            |].\n\n          pose proof (ind k0) as h; clear ind.\n          unfold meta2_fun_on_upd_seq in h.\n          unfold meta2_fun_on_seq in h; repnd.\n\n          pose proof (h (lsubstc X w0 s1 c0) (update_seq seq1 k k0 v)) as q; clear h.\n          repeat (autodimp q hyp).\n          { apply eq_kseq_update; auto.\n            eapply eq_kseq_left; eauto. }\n          { exists s1 c0; dands; auto.\n            eapply similarity_refl; eauto. }\n          repnd; auto.\n        }\n\n        { introv en.\n          repeat substc_lsubstc_vars3.\n          eapply equality_respects_cequivc_left;\n            [apply cequivc_sym;apply cequivc_mkc_apply_lam_axiom|].\n          eapply equality_respects_cequivc_right;\n            [apply cequivc_sym;apply cequivc_mkc_apply_lam_axiom|].\n\n          clear_wf_hyps.\n          proof_irr.\n          lsubst_tac.\n\n          apply equality_in_mkc_squash; dands; spcast;\n          try (apply computes_to_valc_refl; eauto 3 with slow).\n\n          apply equality_in_tnat in en.\n          unfold equality_of_nat in en; exrepnd; spcast.\n\n          eapply inhabited_type_cequivc;\n            [apply cequivc_sym;\n              apply implies_cequivc_apply2;\n              [apply cequivc_refl\n              |apply cequivc_lsubstc_mk_plus1_sp1;auto\n              |apply cequivc_lsubstc_mk_update_seq_sp1;auto;\n               exact en1]\n            |].\n\n          pose proof (ind k0) as h; clear ind.\n          unfold meta2_fun_on_upd_seq in h.\n          unfold meta2_fun_on_seq in h; repnd.\n\n          pose proof (h (lsubstc X w0 s1 c0) (update_seq seq1 k k0 v)) as q; clear h.\n          repeat (autodimp q hyp).\n          { apply eq_kseq_update; auto.\n            eapply eq_kseq_left; eauto. }\n          { exists s1 c0; dands; auto.\n            eapply similarity_refl; eauto. }\n          repnd; auto.\n        }\n      }\n    }\n\n    exrepnd.\n    lsubst_tac.\n    apply inhabited_type_if_equality in hf1.\n    dands; 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/bar_induction/bar_induction3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2667039930876548}}
{"text": "(* infotheo: information theory and error-correcting codes in Coq             *)\n(* Copyright (C) 2020 infotheo authors, license: LGPL-2.1-or-later            *)\nFrom mathcomp Require Import all_ssreflect ssralg fingroup perm finalg matrix.\nFrom mathcomp Require boolp.\nFrom mathcomp Require Import Rstruct.\nRequire Import Reals. (* Lra Nsatz. *)\nRequire Import ssrR Reals_ext logb ssr_ext ssralg_ext bigop_ext Rbigop.\nRequire Import fdist proba.\n\n(******************************************************************************)\n(* wip                                                                        *)\n(* goal: BN_factorization\n   main definitions:\n   * RV_equiv\n   * univ_types / prod_types\n   * preim_vars\n   * cinde_preim\n   * bayesian network (Koller & Friedmann p 57)\n   main theorems:\n   * cinde_preim_ok\n   * prod_vars1\n   * cinde_preim_equiv\n   * BN_factorization\n *)\n(******************************************************************************)\n\nLocal Open Scope tuple_ext_scope.\nLocal Open Scope fdist_scope.\nLocal Open Scope proba_scope.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nSection ssr_ext.\nLemma tnth_uniq (T : eqType) n (t : n.-tuple T) (i j : 'I_n) :\n  uniq t -> (t \\_ i == t \\_ j) = (i == j).\nProof.\npose a := t \\_ i; rewrite 2!(tnth_nth a) => *.\nby rewrite nth_uniq // size_tuple.\nQed.\n\nSection boolP.\nVariables (p : bool) (R : Type) (T : is_true p -> R) (F : is_true (~~ p) -> R).\nLemma boolPT  (H : is_true p) :\n  match boolP p with\n  | AltTrue HT => T HT\n  | AltFalse HF => F HF\n  end = T H.\nProof.\ndestruct boolP.\n- congr T.\n  case: p => // in H i *.\n  exfalso.\n  rewrite H in i.\n- by elim: (negP i).\nQed.\n\nLemma boolPF  (H : is_true (~~ p)) :\n  match boolP p with\n  | AltTrue HT => T HT\n  | AltFalse HF => F HF\n  end = F H.\nProof.\ndestruct boolP.\n- by elim: (negP H).\n- by congr F.\nQed.\nEnd boolP.\nEnd ssr_ext.\n\nSection fin_img.\nVariables (T : finType) (S : eqType) (f : T -> S).\n\nDefinition Tfin_img := 'I_(size (fin_img f)).\nDefinition index_fin_img x (H : x \\in fin_img f) : Tfin_img.\napply (@Ordinal _ (index x (fin_img f))).\nabstract (by rewrite index_mem).\nDefined.\nDefinition map_fin_img (x : T) : Tfin_img.\nrefine (@index_fin_img (f x) _).\nabstract (by rewrite mem_undup map_f // mem_enum).\nDefined.\nDefinition nth_fin_img (i : Tfin_img) : S := tnth (in_tuple (fin_img f)) i.\nDefinition rev_fin_img (i : Tfin_img) : T.\nrefine (iinv (A:=predT) (f:=f) (y:=nth_fin_img i) _).\nabstract (move/mem_nth: (ltn_ord i); rewrite -mem_undup; exact).\nDefined.\nLemma nth_fin_imgK x : nth_fin_img (map_fin_img x) = f x.\nProof.\nrewrite /nth_fin_img /index_fin_img => /=.\nby rewrite (tnth_nth (f x)) nth_index // mem_undup map_f // mem_enum.\nQed.\nLemma rev_fin_imgK i : map_fin_img (rev_fin_img i) = i.\nProof.\ncase: i => i isz; apply val_inj => /=.\nby rewrite f_iinv nthK // undup_uniq.\nQed.\nLemma map_fin_imgK x : f (rev_fin_img (map_fin_img x)) = f x.\nProof. by rewrite /rev_fin_img f_iinv nth_fin_imgK. Qed.\nLemma fin_imgP y : reflect (exists x : T, y = f x) (y \\in fin_img f).\nProof.\nrewrite mem_undup; apply/(iffP mapP) => -[x].\n- move=> _ ->. by exists x.\n- move=> ->. by exists x; rewrite // mem_enum.\nQed.\nEnd fin_img.\n\nSection proba. (* proba.v ? *)\nVariables (U : finType) (P : fdist U).\n\nDefinition fdist_choice' : U.\nmove: (fdist_card_neq0 P).\nmove He: (enum U) => [|u l] //.\nmove/(f_equal size): He.\nby rewrite -cardE => ->.\nDefined.\nDefinition fdist_choice := Eval hnf in fdist_choice'.\n\nDefinition rvar_choice (A : eqType) (X : {RV P -> A}) := X fdist_choice.\n\nSection RV_equiv.\nVariables A B : eqType.\nVariables (X : {RV P -> A}) (Y : {RV P -> B}).\nDefinition cancel_both (fg : (A -> B) * (B -> A)) :=\n  cancel fg.1 fg.2 /\\ cancel fg.2 fg.1.\n\nDefinition RV_equiv := {fg | cancel_both fg & Y =1 fg.1 \\o X}.\nEnd RV_equiv.\n\nLemma RV_equivC (A B : eqType) (X : {RV P -> A}) (Y : {RV P -> B}) :\n  RV_equiv X Y -> RV_equiv Y X.\nProof.\ncase=> -[f g] []/= cfg cgf Hf.\nexists (g,f) => //.\nmove=> u /=.\nmove/(f_equal g): (Hf u).\nby rewrite cfg.\nQed.\nEnd proba.\n\nSection univ_types.\n(* heterogeneous types *)\nVariable n : nat.\nVariable types : 'I_n -> eqType.\nDefinition univ_types := [eqType of {dffun forall i, types i}].\n\nSection prod_types.\n(* sets of indices *)\nVariable I : {set 'I_n}.\n\nDefinition prod_types :=\n  [eqType of\n   {dffun forall i : 'I_n, if i \\in I then types i else unit_finType}].\n\nLemma prod_types_app i (A B : prod_types) : A = B -> A i = B i.\nProof. by move=> ->. Qed.\n\nLemma prod_types_out (i : 'I_n) (A B : prod_types) : i \\notin I -> A i = B i.\nProof.\nmove=> Hi.\nmove: (A i) (B i).\nby rewrite (negbTE Hi) => -[] [].\nQed.\n\nLemma prod_types_neq (A B : prod_types) :\n  A != B -> exists i, (i \\in I) && (A i != B i).\nProof.\nmove=> AB.\ncase /boolP: [forall i, A i == B i].\n  move/forallP => /= AB'.\n  elim: (negP AB).\n  apply/eqP/ffunP => /= x.\n  by apply/eqP.\nrewrite negb_forall => /existsP [x Hx].\nexists x.\nrewrite Hx.\ncase/boolP: (x \\in I) => //= xe.\nelim: (negP Hx).\nmove: (A x) (B x) {AB Hx} => /=.\nby rewrite (negbTE xe) => -[] [].\nQed.\n\nDefinition set_vals' (v : prod_types) (vals : univ_types) : univ_types.\nrefine [ffun j => _].\ncase: (j \\in I) (v j) => a.\n- exact: a.\n- exact: vals j.\nDefined.\nDefinition set_vals : prod_types -> univ_types -> univ_types :=\n  Eval hnf in set_vals'.\n\nLemma set_vals_hd vs2 (v : prod_types) vs1 i :\n  i \\in I -> set_vals v vs1 i = set_vals v vs2 i.\nProof. rewrite !ffunE; by case: (i \\in I) (v i). Qed.\n\nLemma set_vals_tl (v : prod_types) vs i :\n  i \\notin I -> set_vals v vs i = vs i.\nProof. rewrite !ffunE; by case: (i \\in I) (v i). Qed.\n\nLemma set_vals_id (v : prod_types) vs :\n  set_vals v (set_vals v vs) = set_vals v vs.\nProof.\napply/ffunP => i.\ncase/boolP: (i \\in I) => [/set_vals_hd | /set_vals_tl ->]; exact.\nQed.\n\nDefinition prod_vals' (vals : univ_types) : prod_types.\nrefine [ffun i => _].\nmove: (vals i).\ncase: (i \\in I) => a.\n- exact: a.\n- exact: tt.\nDefined.\nDefinition prod_vals vals : prod_types := Eval hnf in prod_vals' vals.\n\nLemma set_vals_prod_vals_id vals i :\n  set_vals (prod_vals vals) vals i = vals i.\nProof. rewrite !ffunE; by case: (i \\in _) (vals i). Qed.\n\nLemma set_vals_prod_vals vals vals' i :\n  i \\in I -> set_vals (prod_vals vals) vals' i = vals i.\nProof. rewrite !ffunE => ie. move: (vals i); by rewrite ie. Qed.\n\nLemma prod_vals_eqP vals1 vals2 i :\n  prod_vals vals1 i = prod_vals vals2 i <-> (i \\in I -> vals1 i = vals2 i).\nProof.\nsplit; rewrite !ffunE; case: (i \\in I) (vals1 i) (vals2 i) => // v1 v2; exact.\nQed.\n\nLemma prod_vals_eq (vals1 vals2 : univ_types) i :\n  (i \\in I -> vals1 i = vals2 i) -> prod_vals vals1 i = prod_vals vals2 i.\nProof. move=> Hi; exact/prod_vals_eqP. Qed.\n\nLemma set_vals_eq (A B : prod_types) vals i :\n  set_vals A vals i == set_vals B vals i = (A i == B i) || (i \\notin I).\nProof.\nrewrite !ffunE.\ncase: (i \\in I) (A i) (B i) => a b.\n- by rewrite orbF.\n- by rewrite eqxx orbT.\nQed.\n\nLemma set_vals_inj (A B : prod_types) vals i :\n  set_vals A vals i = set_vals B vals i -> A i = B i.\nProof.\nset goal := _ -> _.\ncase/boolP: (i \\in I) => Hi; subst goal.\n  move/eqP; rewrite set_vals_eq orbC.\n  by move: (A i) (B i); rewrite Hi => a b /= /eqP.\nmove=> _; exact: prod_types_out.\nQed.\n\nLemma prod_vals_set_vals (A : prod_types) vals :\n  prod_vals (set_vals A vals) = A.\nProof.\napply/ffunP => j.\napply (set_vals_inj (vals := vals)).\ncase/boolP: (j \\in I) => Hj.\n  by rewrite set_vals_prod_vals.\nby rewrite !set_vals_tl.\nQed.\n\nEnd prod_types.\n\nLemma set_vals_prod_vals_join (I J : {set 'I_n}) vals vals' :\n  set_vals (prod_vals I vals) (set_vals (prod_vals J vals) vals') =\n  set_vals (prod_vals (I :|: J) vals) vals'.\nProof.\napply/ffunP => i.\ncase/boolP: (i \\in I) => iI.\n  by rewrite !set_vals_prod_vals // inE iI.\nrewrite set_vals_tl //.\ncase/boolP: (i \\in J) => iJ.\n  by rewrite !set_vals_prod_vals // inE iJ orbT.\nby rewrite !set_vals_tl // inE negb_or iI.\nQed.\n\nLemma set_valsC I J (A : prod_types I) (B : prod_types J) V :\n  [disjoint I & J] -> set_vals A (set_vals B V) = set_vals B (set_vals A V).\nProof.\nmove/setDidPl/setP => Disj.\napply/ffunP => /= i.\ncase/boolP: (i \\in I) => iI.\n  move: (Disj i); rewrite inE iI andbT => /set_vals_tl ->.\n  by rewrite (set_vals_hd V).\ncase/boolP: (i \\in J) => iJ.\n  by rewrite set_vals_tl //; apply set_vals_hd.\nby rewrite !set_vals_tl.\nQed.\n\nSection set_val.\nDefinition set_val (i : 'I_n) (v : types i) (vals : univ_types) : univ_types :=\n  [ffun j : 'I_n =>\n    match Nat.eq_dec i j return types j with\n    | left ij => eq_rect i (fun i => (types i : Type)) v j (ord_inj ij)\n    | right _ => vals j\n    end].\n\nLemma eq_dec_refl i : Nat.eq_dec i i = left (erefl i).\nProof.\ncase: Nat.eq_dec => Hi; last by elim Hi.\ncongr left; by rewrite (Eqdep_dec.UIP_refl_nat _ Hi).\nQed.\n\nDefinition ord_eq_dec (i j : 'I_n) : {i = j}+{i <> j}.\ncase (Nat.eq_dec i j); intro ij.\n- left; now apply ord_inj.\n- right; intro ij'; apply ij; now f_equal.\nDefined.\n\nLemma set_val_hd i (v : types i) vs : set_val v vs i = v.\nrewrite ffunE eq_dec_refl -Eqdep_dec.eq_rect_eq_dec //; exact: ord_eq_dec.\nQed.\n\nLemma set_val_tl i (v : types i) vs j : i <> j -> set_val v vs j = vs j.\nrewrite ffunE => nij; case: Nat.eq_dec => ij //; elim nij; exact: ord_inj.\nQed.\nEnd set_val.\n\nEnd univ_types.\n\n\nModule BN.\nSection bn.\nVariable U : finType.\nVariable P : fdist U.\nVariable n : nat.\n\nSection preim.\nLocal Open Scope R_scope.\nVariable types : 'I_n -> eqType.\nVariable vars : forall i, {RV P -> types i}.\n\nDefinition vals0 : univ_types types := [ffun i => rvar_choice (vars i)].\n\nDefinition wrap_set_vals I := f_equal (set_vals (I:=I) ^~ vals0).\n\nSection prod_vars.\nVariable I : {set 'I_n}.\n\nDefinition vals_at (u : U) : univ_types types := [ffun i => vars i u].\n\nDefinition prod_vars : {RV P -> prod_types types I} :=\n  fun u => prod_vals I (vals_at u).\n\nLemma set_vals_prod_vars vals u i :\n  i \\in I -> set_vals (prod_vars u) vals i = vars i u.\nProof. move=> Hi; by rewrite set_vals_prod_vals // ffunE. Qed.\nEnd prod_vars.\n\nLemma prod_vars_inter (I J : {set 'I_n}) vals i u :\n  i \\in I -> i \\in J ->\n  set_vals (prod_vars I u) vals i = set_vals (prod_vars J u) vals i.\nProof. move=> *; by rewrite !set_vals_prod_vals. Qed.\n\nLemma prod_vars1 (i : 'I_n) : RV_equiv (prod_vars [set i]) (vars i).\nProof.\nexists ((fun A : prod_types types [set i] => set_vals A vals0 i),\n        prod_vals [set i] \\o set_val (i:=i) ^~ vals0).\n  split => x /=.\n    apply/ffunP => /= j.\n    apply (set_vals_inj (vals := vals0)).\n    case/boolP: (j \\in [set i]) => Hj; last by rewrite !set_vals_tl.\n    rewrite set_vals_prod_vals //.\n    rewrite inE in Hj.\n    move/eqP: Hj (set_vals _ _) => -> v.\n    by rewrite set_val_hd.\n  by rewrite set_vals_prod_vals ?inE // set_val_hd.\nmove=> u /=.\nby rewrite set_vals_prod_vars // inE.\nQed.\n\nLemma cancel_both_disjoint (I J : {set 'I_n}) :\n  [disjoint I & J] ->\n  cancel_both\n    ((fun A : prod_types types (I :|: J) =>\n        (prod_vals I (set_vals A vals0), prod_vals J (set_vals A vals0))),\n     (fun A : prod_types types I * prod_types types J =>\n        prod_vals (I :|: J) (set_vals (fst A) (set_vals (snd A) vals0)))).\nProof.\nmove=> Disj; split => [A | [A B]] /=.\n  by rewrite set_vals_prod_vals_join !prod_vals_set_vals.\ncongr pair; last rewrite setUC set_valsC //;\nby rewrite -set_vals_prod_vals_join !prod_vals_set_vals.\nQed.\n\nLemma prod_vars_pair (I J : {set 'I_n}) :\n  [disjoint I & J] ->\n  RV_equiv (prod_vars (I :|: J)) [% prod_vars I, prod_vars J].\nProof.\nmove=> Disj.\nesplit. exact: cancel_both_disjoint.\nmove=> u /=.\ncongr pair; apply/ffunP => i; apply prod_vals_eq => Hi;\n  rewrite set_vals_prod_vars ?ffunE //; by rewrite inE Hi ?orbT.\nQed.\n\nDefinition preim_vars (I : {set 'I_n}) (vals : forall i, types i) :=\n  \\bigcap_(i in I) finset (vars i @^-1 (vals i)).\n\nDefinition cinde_preim (e f g : {set 'I_n}) :=\n  forall vals : univ_types types,\n    cinde_events P (preim_vars e vals)\n                   (preim_vars f vals)\n                   (preim_vars g vals).\n\nLemma cinde_eventsC A (Q : fdist A) (E F G : {set A}) :\n  cinde_events Q E F G -> cinde_events Q F E G.\nProof. rewrite /cinde_events => Hef; by rewrite setIC mulRC. Qed.\n\nLemma cinde_preimC (e f g : {set 'I_n}) :\n  cinde_preim e f g  -> cinde_preim f e g.\nProof. move=> Hef vals; exact: cinde_eventsC. Qed.\n\nLemma preim_varsP  (I : {set 'I_n}) vals u :\n  reflect (forall i, i \\in I -> vars i u = vals i) (u \\in preim_vars I vals).\nProof. by apply/(iffP bigcapP) => H i /H; rewrite !inE => /eqP. Qed.\n\nLemma preim_prod_vars (g : {set 'I_n}) (C : prod_types types g) vals :\n  finset (prod_vars g @^-1 C) = preim_vars g (set_vals C vals).\nProof.\napply/setP => x; rewrite !inE.\napply/esym/preim_varsP; case: ifP.\n- move/eqP => <- i ig.\n  by rewrite set_vals_prod_vals // ffunE.\n- move/negP => /= Hf Hcap; elim: Hf.\n  apply/eqP/ffunP => /= i.\n  rewrite /prod_vars (prod_vals_eq (vals2:=set_vals C vals)).\n    by rewrite prod_vals_set_vals.\n  rewrite ffunE; exact: Hcap.\nQed.\n\n(* Simple version, using singletons *)\n\nLemma Rxx2 x : x = x * x -> x = 0 \\/ x = 1.\nProof.\ncase/boolP: (x == 0) => Hx.\n  rewrite (eqP Hx); by left.\nmove/(f_equal (Rdiv ^~ x)).\nrewrite divRR // /Rdiv -mulRA mulRV // mulR1 => <-; by right.\nQed.\n\nLemma cinde_preim_ok1 (i j k : 'I_n) :\n  cinde_preim [set i] [set j] [set k] <-> P |= (vars i) _|_ (vars j) | (vars k).\nProof.\nrewrite /cinde_preim /preim_vars.\nsplit.\n- move=> Hpreim.\n  apply/cinde_rv_events => a b c.\n  set vals := set_val a (set_val c (set_val b vals0)).\n  have vi : vals i = a by rewrite /vals set_val_hd.\n  move: (erefl vals) {Hpreim} (Hpreim vals).\n  rewrite {2}/vals /cinde_events; clearbody vals.\n  rewrite !big_set1.\n  wlog: c / vals k = c.\n    case: (ord_eq_dec i k) c vi.\n      move=> <- {k} c vi.\n      case ac: (a == c).\n        rewrite -(eqP ac); exact.\n      move=> _ _ _.\n      rewrite (proj2 (cPr_eq0 _ _ _)); last first.\n        apply/Pr_set0P => u.\n        by rewrite !inE => /andP [] /andP [] /= /eqP ->; rewrite ac.\n      rewrite (proj2 (cPr_eq0 _ _ _)); last first.\n        apply/Pr_set0P => u.\n        by rewrite !inE => /andP [] /= /eqP ->; rewrite ac.\n      by rewrite mul0R.\n    move=> nik c vi HG Hvals; apply: HG => //.\n    by rewrite Hvals set_val_tl // set_val_hd.\n  move=> vk.\n  wlog: b / vals j = b.\n    case: (ord_eq_dec i j) b.\n      move=> <- {j} b.\n      case ab: (a == b).\n        rewrite -(eqP ab); exact.\n      move=> _ _.\n      rewrite setIid vi vk.\n      set x := (X in X = X * X).\n      move/Rxx2 => [] Hx.\n        rewrite -/x Hx.\n        rewrite (proj2 (cPr_eq0 _ _ _)) ?mul0R //.\n        apply/Pr_set0P => u.\n        by rewrite !inE => /andP [] /andP [] /= /eqP ->; rewrite ab.\n      rewrite /cPr.\n      set den := (X in _ / X).\n      case/boolP: (den == 0) => /eqP Hden.\n        by rewrite setIC Pr_domin_setI // setIC Pr_domin_setI // !div0R mul0R.\n      set num := (X in _ * (X / _)).\n      case/boolP: (num == 0) => /eqP Hnum.\n        by rewrite -setIA setIC Pr_domin_setI // Hnum !div0R mulR0.\n      elim Hnum.\n      apply/Pr_set0P => u.\n      rewrite !inE => /andP [] /= Hi Hk.\n      move: Hx; subst x.\n      move/(f_equal (Rmult ^~ den)).\n      move/eqP in Hden.\n      rewrite /cPr /Rdiv -mulRA mulVR // mulR1 mul1R.\n      move/(f_equal (Rminus den)).\n      rewrite subRR setIC -Pr_diff => /Pr_set0P/(_ u).\n      rewrite !inE (eqP Hi) Hk eq_sym ab; exact.\n    case: (ord_eq_dec k j).\n      move=> <- {j} ik b.\n      case bc: (b == c).\n        rewrite (eqP bc); exact.\n      move=> _ _ _.\n      rewrite (proj2 (cPr_eq0 _ _ _)); last first.\n        apply/Pr_set0P => u.\n        by rewrite !inE => /andP [] /andP [] _ /= /eqP ->; rewrite bc.\n      rewrite mulRC (proj2 (cPr_eq0 _ _ _)) ?mul0R //.\n      by apply/Pr_set0P => u; rewrite !inE => /andP [] /= /eqP ->; rewrite bc.\n    move=> nkj nij b HG Hvals; apply: HG => //.\n    by rewrite Hvals set_val_tl // set_val_tl // set_val_hd.\n  by rewrite vi vk => -> _.\n- move=> Hdrv vals.\n  move/cinde_rv_events/(_ (vals i) (vals j) (vals k)): Hdrv.\n  by rewrite !big_set1.\nQed.\n\n(* Now start the hard version, using sets of variables *)\n\nLemma preim_vars_set_vals_tl (g e : {set 'I_n}) (A : prod_types types e) vals :\n  e :&: g = set0 ->\n  preim_vars g (set_vals A vals) = preim_vars g vals.\nProof.\nmove=> /setP eg.\napply/eq_bigr => /= i ig.\napply/setP => u.\nrewrite !inE set_vals_tl //.\nmove: (eg i); by rewrite !inE ig andbT => ->.\nQed.\n\nLemma preim_inter (T S : eqType) (e : U -> T) (g : U -> S) (A : T) (C : S) :\n  finset (preim (fun x => (e x, g x)) (pred1 (A, C))) =\n  finset (preim e (pred1 A)) :&: finset (preim g (pred1 C)).\nProof.\napply/setP => u; rewrite !inE.\napply/andP => /=.\nby case: ifPn => [/andP | /negP H /andP /H].\nQed.\n\nLemma preim_vars_inter (e f : {set 'I_n}) vals :\n  preim_vars (e :|: f) vals = preim_vars e vals :&: preim_vars f vals.\nProof. by rewrite /preim_vars bigcap_setU. Qed.\n\nLemma preim_vars_vals (e : {set 'I_n}) (A : prod_types types e) vals1 vals2 :\n  (forall x, x \\in e -> vals1 x = vals2 x) ->\n  preim_vars e vals1 = preim_vars e vals2.\nProof.\nmove=> Hvals.\napply/eq_bigr => /= i ie.\napply/setP => u; by rewrite !inE Hvals.\nQed.\n\nLemma disjoint_preim_vars (e f : {set 'I_n}) (A B : prod_types types f) vals :\n  f \\subset e -> A != B ->\n  [disjoint preim_vars e (set_vals A vals) & preim_vars e (set_vals B vals)].\nProof.\nmove=> fe AB.\nrewrite -setI_eq0.\napply/eqP/setP => u.\nrewrite !inE.\napply/negP => /andP [] /preim_varsP /= HA /preim_varsP /= HB.\ncase: (prod_types_neq AB) => /= i /andP [Hif HAB].\nhave ie : i \\in e by move/subsetP: fe; apply.\nmove/(_ _ ie)/eqP: HB.\nrewrite HA // set_vals_eq => /orP [] H.\n- by rewrite H in HAB.\n- by rewrite Hif in H.\nQed.\n\nLemma Pr_preim_vars_sub (e f : {set 'I_n}) (vals : univ_types types) :\n  f \\subset e ->\n  Pr P (preim_vars (e :\\: f) vals) =\n  \\sum_(A : Tfin_img (prod_vars f))\n   Pr P (preim_vars e (set_vals (nth_fin_img A) vals)).\nProof.\nrewrite /Pr => fe.\nrewrite -partition_disjoint_bigcup; last first.\n  move=> /= A B.\n  rewrite -(tnth_uniq A B (t:=in_tuple _)) ?undup_uniq => // AB.\n  exact: disjoint_preim_vars.\napply/eq_bigl => u.\napply/esym/bigcupP/(equivPif idP).\n  move=> [A _ /preim_varsP HA].\n  apply/preim_varsP => /= i /setDP [/HA -> Hif].\n  by rewrite set_vals_tl.\nmove=> /= /preim_varsP /= Hu.\nexists (map_fin_img (prod_vars f) u) => //.\napply/preim_varsP => /= i ie.\ncase/boolP: (i \\in f) => Hif.\n  by rewrite nth_fin_imgK set_vals_prod_vars.\nby rewrite set_vals_tl // Hu // inE Hif.\nQed.\n\nLtac cases_in i :=\n  rewrite ?inE; do !case: (i \\in _) => //=;\n  try by do! (move/(_ isT) => // || move=> _).\n\nLemma cinde_preim_sub (e e' f g : {set 'I_n}) :\n  e :&: (f :|: g) \\subset e' -> e' \\subset e ->\n  cinde_preim e f g -> cinde_preim e' f g.\nProof.\nrewrite /cinde_preim => ee' e'e Hef vals.\nhave ee'g : (e :\\: e') :&: g = set0.\n  apply/setP => i; move/subsetP/(_ i): ee'; by cases_in i.\ntransitivity (\\sum_(A : Tfin_img (prod_vars (e :\\: e')))\n          let v := set_vals (nth_fin_img A) vals in\n          `Pr_P[preim_vars e v :&: preim_vars f v | preim_vars g v]).\n  rewrite /cPr -!preim_vars_inter.\n  have -> : e' :|: f :|: g = (e :|: f :|: g) :\\: (e :\\: e').\n    apply/setP => i.\n    move/subsetP/(_ i): e'e.\n    move/subsetP/(_ i): ee'.\n    by cases_in i.\n  rewrite Pr_preim_vars_sub; last by apply/subsetP=> i; cases_in i.\n  rewrite /Rdiv big_distrl; apply eq_bigr => A _ /=.\n  by rewrite -!preim_vars_inter (@preim_vars_set_vals_tl g).\nunder eq_bigr => A _ /=.\n  rewrite Hef (@preim_vars_set_vals_tl g) // (@preim_vars_set_vals_tl f).\n    over.\n  apply/setP => i; move/subsetP/(_ i): ee'; by cases_in i.\nrewrite -2!big_distrl /=.\ncongr (_ / _ * _).\nrewrite -preim_vars_inter.\nhave -> : e' :|: g = (e :|: g) :\\: (e :\\: e').\n  apply/setP => i.\n  move/subsetP/(_ i): e'e.\n  move/subsetP/(_ i): ee'.\n  by cases_in i.\nrewrite Pr_preim_vars_sub; last by apply/subsetP=> i; cases_in i.\napply eq_bigr => A _.\nby rewrite preim_vars_inter (@preim_vars_set_vals_tl g) //.\nQed.\n\nLemma cinde_preim_inter e f g :\n  cinde_preim e f g -> cinde_preim (e :&: f) (e :&: f) g.\nProof.\nmove=> Hp.\nhave Hp2 : cinde_preim (e :\\: (e :\\: f :\\: g)) f g.\n  apply (@cinde_preim_sub e) => // ;\n    apply/subsetP => j; by cases_in j.\nhave : cinde_preim (e :\\: (e :\\: f :\\: g)) (f :\\: (f :\\: e :\\: g)) g.\n  move/cinde_preimC in Hp2.\n  apply/cinde_preimC.\n  apply (@cinde_preim_sub f) => // ;\n    apply/subsetP => j; by cases_in j.\nmove=> {}Hp vals.\nmove/(_ vals): Hp.\nrewrite /cinde_events /cPr /Pr -!preim_vars_inter.\nrewrite (_ : _ :|: g = (e :&: f) :|: g);\n  last by apply/setP => j; cases_in j.\nrewrite 2!(_ : _ :\\: _ :|: _ = (e :&: f) :|: g);\n  try by apply/setP => j; cases_in j.\nby rewrite setUid.\nQed.\n\nSection cinde_preim_lemmas.\nVariables e f g : {set 'I_n}.\nVariables (A : prod_types types e) (B : prod_types types f)\n          (C : prod_types types g).\nLemma cinde_events_vals :\n  [forall i in (e :&: g), set_vals C vals0 i == set_vals A vals0 i] \\/\n  cinde_events P (finset (prod_vars e @^-1 A)) (finset (prod_vars f @^-1 B))\n                 (finset (prod_vars g @^-1 C)).\nProof.\ncase /boolP: [forall i in (e :&: g), _].\n  by left.\nrewrite negb_forall => /existsP [i].\nrewrite inE negb_imply => /andP [] /andP [Hie Hig] /eqP Hvi.\nright; rewrite /cinde_events.\nrewrite (proj2 (cPr_eq0 _ _ _)); last first.\n  apply/Pr_set0P => u; rewrite !inE => Hprod; elim: Hvi.\n  case/andP: Hprod => /andP[] /eqP <- _ /eqP <-; exact: prod_vars_inter.\nrewrite (proj2 (cPr_eq0 _ _ _)) ?mul0R //.\napply/Pr_set0P => u; rewrite !inE => Hprod; elim: Hvi.\ncase/andP: Hprod => /eqP <- /eqP <-; exact: prod_vars_inter.\nQed.\n\nLemma cinde_events_cPr1 (i : 'I_n) :\n  let vals := set_vals C (set_vals A (set_vals B vals0)) in\n  (forall x : 'I_n, x \\in e -> vals x = set_vals A vals0 x) ->\n  i \\in e -> i \\in f -> i \\notin g ->\n  set_vals A vals0 i <> set_vals B vals0 i ->\n  `Pr_P[(preim_vars (e :&: f) vals) | (preim_vars g vals)] = 1 ->\n  cinde_events P [set x | preim (prod_vars e) (pred1 A) x]\n    [set x | preim (prod_vars f) (pred1 B) x]\n    [set x | preim (prod_vars g) (pred1 C) x].\nProof.\nmove=> vals He Hie Hif Hig Hvi.\nrewrite /cinde_events /cPr.\nset den := (X in _ / X).\ncase/boolP: (den == 0) => [/eqP|] Hden.\n  by rewrite setIC Pr_domin_setI // ?div0R => /esym/R1_neq_R0.\nset num := Pr _ _ => Hnum.\nhave {}Hnum : num = den.\n  by rewrite -[RHS]mul1R -Hnum /Rdiv -mulRA mulVR // mulR1.\nrewrite -Hnum in Hden.\nrewrite (proj2 (Pr_set0P _ _)); last first.\n  move=> u; rewrite !inE => /andP[] /andP[] /eqP HA /eqP HB.\n  by rewrite -HA -HB !set_vals_prod_vars in Hvi.\nsuff : `Pr_P[finset (prod_vars f @^-1 B) | finset (prod_vars g @^-1 C)] = 0.\n  by rewrite /cPr => ->; rewrite mulR0 div0R.\n(* prove incompatibility between B and C *)\napply/cPr_eq0/Pr_set0P => u.\nrewrite !inE => /andP [] /eqP HB /eqP HC.\nmove: Hnum; rewrite /den.\nhave -> : g = (e :&: f :|: g) :\\: ((e :&: f) :\\: g).\n  by apply/setP => j; cases_in j.\nrewrite Pr_preim_vars_sub; last by apply/subsetP => j; cases_in j.\nhave : prod_vals ((e :&: f) :\\: g) vals\n                 \\in fin_img (prod_vars ((e :&: f) :\\: g)).\n  case/boolP: (_ \\in _) => // /negP HA.\n  elim: (negP Hden); rewrite /num -preim_vars_inter.\n  have -> : e :&: f :|: g = (e :&: f :\\: g) :|: g.\n    apply/setP => k; by cases_in k.\n  apply/eqP/Pr_set0P => v.\n  rewrite preim_vars_inter inE => /andP [/preim_varsP /= HA'].\n  elim: HA; apply/fin_imgP.\n  exists v; apply/ffunP => k.\n  apply/prod_vals_eq => /HA' <-.\n  by rewrite ffunE.\ncase/fin_imgP => v Hv {Hden}.\nset a := map_fin_img (prod_vars ((e :&: f) :\\: g)) v.\nrewrite (bigD1 a) //= nth_fin_imgK -Hv.\nrewrite /num (@preim_vars_vals _ (prod_vals (e :&: f :|: g) vals) _ vals);\n  last by move=> j; rewrite set_vals_prod_vals_id.\nrewrite -preim_vars_inter addRC => /subR_eq; rewrite subRR => /esym Hnum.\nhave : Pr P (preim_vars (e :&: f :|: g)\n      (set_vals (prod_vals (e :&: f :\\: g) (set_vals B vals)) vals)) = 0.\n  rewrite (_ : prod_vals _ _ = prod_vars (e :&: f :\\: g) u); last first.\n    apply/ffunP => k; apply/prod_vals_eq => Hk.\n    rewrite -HB set_vals_prod_vars ?ffunE //.\n    move: Hk; cases_in k.\n  rewrite -(@nth_fin_imgK U).\n  move/psumR_eq0P: Hnum; apply.\n    move => *; by apply sumR_ge0.\n  apply/eqP => /(f_equal (fun x => nth_fin_img x)).\n  rewrite !nth_fin_imgK => /(prod_types_app i) /prod_vals_eqP Hi.\n  elim: Hvi; rewrite -He //.\n  have iefg : i \\in e :&: f :\\: g by move: Hif Hig Hie; cases_in i.\n  move/(prod_types_app i)/prod_vals_eqP: Hv => -> //.\n  by rewrite -HB set_vals_prod_vars // -Hi // ffunE.\nmove/Pr_set0P; apply.\napply/preim_varsP => j Hj.\ncase/boolP: (j \\in g) => jg.\n  by rewrite set_vals_tl ?inE ?jg // /vals -HC set_vals_prod_vars.\nrewrite inE (negbTE jg) orbF in Hj.\nrewrite -HB set_vals_prod_vals ?set_vals_prod_vars //.\n  move: Hj; by rewrite inE => /andP[].\nby rewrite inE Hj jg.\nQed.\nEnd cinde_preim_lemmas.\n\nLemma cinde_preim_ok (e f g : {set 'I_n}) :\n  cinde_preim e f g <-> P |= prod_vars e _|_ prod_vars f | (prod_vars g).\nProof.\nsplit.\n- move=> Hpreim.\n  apply/cinde_rv_events => A B C.\n  set vals := set_vals C (set_vals A (set_vals B vals0)).\n  case /boolP: [forall i in e, vals i == set_vals A vals0 i]; last first.\n    case: (cinde_events_vals A B C) => // /forallP Heg /negP; elim.\n    apply/forallP => i; apply /implyP => Hie.\n    case /boolP: (i \\in g) => Hig;\n      last by rewrite /vals set_vals_tl // (set_vals_hd vals0).\n    rewrite /vals (set_vals_hd vals0) //.\n    move/implyP: (Heg i); rewrite inE Hie; exact.\n  (* A and C are compatible *)\n  move/forallP => /= He.\n  have {}He x Hx := eqP (implyP (He x) Hx).\n  case /boolP: [forall i in f, vals i == set_vals B vals0 i].\n    (* A/C and B are compatible *)\n    move/forallP => /= Hf.\n    have {}Hf x Hx := eqP (implyP (Hf x) Hx).\n    move: (Hpreim vals).\n    rewrite (preim_vars_vals _ He) // (preim_vars_vals _ Hf) //.\n    by rewrite /cinde_events -!preim_prod_vars -!preim_inter.\n  move/cinde_preimC in Hpreim.\n  move=> HB; apply cinde_eventsC.\n  case: (cinde_events_vals B A C) HB => // /forallP Hfg.\n  (* A/C and B are incompatible *)\n  rewrite negb_forall => /existsP [i].\n  rewrite negb_imply /vals => /andP [Hif].\n  case /boolP: (i \\in g) => Hig.\n    (* B and C are incompatible *)\n    move: (Hfg i); by rewrite inE Hif Hig /= (set_vals_hd vals0) // => ->.\n  case /boolP: (i \\in e) => Hie;\n    last by rewrite set_vals_tl // set_vals_tl // eqxx.\n  (* A and B are incompatible *)\n  rewrite set_vals_tl // (set_vals_hd vals0) // => /eqP Hvi.\n  apply/cinde_eventsC.\n  (* Reduce to intersection *)\n  move/cinde_preimC/cinde_preim_inter/(_ vals): Hpreim.\n  rewrite {1}/cinde_events -!preim_vars_inter setUid /=.\n  case/Rxx2.\n    (* cPr = 0 *)\n    move/cPr_eq0/Pr_set0P => Hx.\n    have HAC :\n      Pr P (finset (prod_vars e @^-1 A) :&: finset (prod_vars g @^-1 C)) = 0.\n      apply Pr_set0P => u Hu; apply Hx.\n      rewrite -preim_vars_inter; apply/preim_varsP => j.\n      move: Hu; rewrite !inE.\n      rewrite /vals => /andP[] /eqP <- /eqP <-.\n      case/boolP: (j \\in g) => jg.\n        by rewrite set_vals_prod_vars.\n      case/boolP: (j \\in e) => // je.\n      by rewrite set_vals_tl // set_vals_prod_vars.\n    rewrite /cinde_events (proj2 (cPr_eq0 _ _ _)).\n      by rewrite (proj2 (cPr_eq0 _ _ _)) // mul0R.\n    apply/Pr_set0P => u Hu.\n    apply(proj1 (Pr_set0P _ _) HAC).\n    move: Hu; by rewrite !inE => /andP[] /andP[] -> _ ->.\n  (* cPr = 1 *)\n  exact: (cinde_events_cPr1 (i:=i)).\n- move=> Hdrv vals.\n  move/cinde_rv_events: Hdrv.\n  move/(_ (prod_vals e vals) (prod_vals f vals) (prod_vals g vals)).\n  rewrite -(preim_vars_vals (prod_vals e vals) (set_vals_prod_vals _ vals)).\n  rewrite -(preim_vars_vals (prod_vals f vals) (set_vals_prod_vals _ vals)).\n  rewrite -(preim_vars_vals (prod_vals g vals) (set_vals_prod_vals _ vals)).\n  by rewrite -!preim_prod_vars.\nQed.\n\nSection Imap.\nVariable parent : rel 'I_n.\n\nDefinition topological := forall i j : 'I_n, parent i j -> (i < j)%nat.\n\nDefinition independence (i j : 'I_n) :=\n  ~~ closure parent [set i] j ->\n  let parents := [set k | closure parent [set k] i] in\n  cinde_preim [set i] [set j] parents.\nEnd Imap.\n\n(* Koller and Friedman, Definition 3.1, page 57 *)\n\nRecord t := mkBN\n  { parent: rel 'I_n;\n    topo: topological parent;\n    indep: forall i j, independence parent i j\n  }.\nEnd preim.\n\nSection equiv.\nVariables types1 types2 : 'I_n -> finType.\nVariable vars1 : forall i, {RV P -> types1 i}.\nVariable vars2 : forall i, {RV P -> types2 i}.\nHypothesis varsE : forall i, RV_equiv (vars1 i) (vars2 i).\n\nDefinition vals1to2 (vals1 : univ_types types1) : univ_types types2\n := [ffun i => (sval (varsE i)).1 (vals1 i)].\n\nLemma preim_vars12 (I : {set 'I_n}) (vals1 : univ_types types1) :\n  preim_vars vars2 I (vals1to2 vals1) = preim_vars vars1 I vals1.\nProof.\nrewrite /preim_vars.\napply/setP => v.\napply/preim_varsP; case: ifP => /preim_varsP /= H1.\n- move=> i iI; rewrite ffunE.\n  move/H1: (iI).\n  by case: varsE => -[f g] [/= fK gK] /(_ v) -> <-.\n- move=> Hv; elim: H1 => /= i iI.\n  move/Hv: (iI); rewrite ffunE.\n  case: varsE => -[f g] [/= fK gK] /(_ v) -> /(f_equal g).\n  by rewrite !fK => ->.\nQed.\n\nLemma cinde_preim_equiv1 (I J K : {set 'I_n}) :\n  cinde_preim vars2 I J K -> cinde_preim vars1 I J K.\nProof.\nrewrite /cinde_preim => CI vals1.\nmove: (CI (vals1to2 vals1)).\nby rewrite !preim_vars12.\nQed.\nEnd equiv.\n\nLemma cinde_preim_equiv (types1 types2 : 'I_n -> finType)\n      (vars1 : forall i : 'I_n, {RV P -> types1 i})\n      (vars2 : forall i : 'I_n, {RV P -> types2 i}) I J K :\n  (forall i : 'I_n, RV_equiv (vars1 i) (vars2 i)) ->\n  cinde_preim vars1 I J K <-> cinde_preim vars2 I J K.\nProof. split; apply cinde_preim_equiv1 => // i; by apply RV_equivC. Qed.\n\nEnd bn.\nEnd BN.\n\nSection Factorization.\nImport BN.\nVariable U : finType.\nVariable P : fdist U.\nVariable n : nat.\nVariable types : 'I_n -> finType.\nVariable vars : forall i, {RV P -> types i}.\nVariable bn : t vars.\n\nLocal Open Scope R_scope.\n\n(* Theorem 3.1, page 62 *)\nTheorem BN_factorization vals :\n  Pr P (preim_vars vars setT vals) =\n  \\prod_(i < n)\n   let parents := [set k | closure (parent bn) [set k] i] in\n   `Pr_ P [ preim_vars vars [set i] vals | preim_vars vars parents vals ].\nAbort.\n\nEnd Factorization.\n", "meta": {"author": "affeldt-aist", "repo": "infotheo", "sha": "5f9efb859dbadcbcae2330e2e21e76f9b632d879", "save_path": "github-repos/coq/affeldt-aist-infotheo", "path": "github-repos/coq/affeldt-aist-infotheo/infotheo-5f9efb859dbadcbcae2330e2e21e76f9b632d879/probability/bayes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2667039930876548}}
{"text": "Require StlcIso.SpecSyntax.\nRequire StlcEqui.SpecSyntax.\nRequire Import StlcEqui.SpecTyping.\nRequire Import StlcIso.SpecTyping.\nRequire Import StlcIso.LemmasTyping.\nRequire Import StlcIso.CanForm.\nRequire Import StlcIso.SpecEvaluation.\nRequire Import StlcIso.LemmasEvaluation.\n(* Require Import StlcEqui.SpecScoping. *)\n(* Require Import StlcEqui.LemmasScoping. *)\n(* Require Import StlcEqui.DecideEval. *)\nRequire Import UValIE.UVal.\nRequire Import LogRelIE.PseudoType.\nRequire Import LogRelIE.LemmasPseudoType.\nRequire Import LogRelIE.LR.\nRequire Import LogRelIE.LemmasLR.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.Arith.Wf_nat.\nRequire Import Db.Lemmas.\n(* Require Import StlcEqui.Fix. *)\n\nLocal Ltac crushLRMatch :=\n  match goal with\n    | [ |- _ ∧ _ ] => split\n    | [ H : valrel _ _ ?τ ?ts ?tu   |- OfType ?τ ?ts ?tu ] => refine (valrel_implies_OfType H)\n    | [ H : valrel ?d _ ?τ ?ts ?tu  |- termrel ?d _ ?τ ?ts ?tu ] => apply valrel_in_termrel\n    | [ H : valrel ?d ?w ?τ ?ts ?tu |- valrel ?d ?w' ?τ ?ts ?tu ] => refine (valrel_mono _ _ H); try lia\n    | [ H : valrel _ _ _ ?ts _ |- I.Value ?ts ] => refine (proj1 (valrel_implies_Value H))\n    | [ H : valrel _ _ _ _ ?tu |- E.Value ?tu ] => refine (proj2 (valrel_implies_Value H))\n    | [ H : OfType _ ?ts _ |- I.Value ?ts ] => refine (proj1 (OfType_implies_Value H))\n    | [ H : OfType _ _ ?tu |- E.Value ?tu ] => refine (proj2 (OfType_implies_Value H))\n    | [ |- valrel _ _ _ _ _] => rewrite -> valrel_fixp; unfold valrel'\n    | [ |- context[ lev ]] => unfold lev\n    | [ H : context[ lev ] |- _ ] => unfold lev in *\n    | [ |- exists t1, ?t2 = t1 /\\ _ ] => eexists; split; [reflexivity|]\n  end.\n\nLocal Ltac crush :=\n  repeat\n    (try assumption;\n     simpl;\n     destruct_conjs;\n     subst*;\n     repeat crushLRMatch;\n     crushOfType;\n     repeat crushValidPTyMatch;\n     I.crushTyping;\n     E.crushTyping;\n     trivial;\n     try reflexivity\n    ); try lia; eauto.\n\nSection ValueRelation.\n\n  (* Lambda abstraction *)\n  Lemma valrel_lambda {d τ'' τ' τ ts tu w} :\n    ValidPTy τ → ValidPTy τ' → ValidTy τ'' →\n    OfType (ptarr τ' τ) (I.abs (repEmul τ') ts) (E.abs (isToEq τ') tu) →\n    ⟪ τ'' ≗ isToEq τ' ⟫ →\n    (∀ w' vs vu, w' < w → (d = dir_gt -> E.size vu <= w') -> valrel d w' τ' vs vu → termrel d w' τ (ts [beta1 vs]) (tu [beta1 vu])) →\n    valrel d w (ptarr τ' τ) (I.abs (repEmul τ') ts) (E.abs τ'' tu).\n  Proof.\n    intros.\n    rewrite valrel_fixp; unfold valrel'.\n    simpl.\n    split.\n    crush.\n    repeat eexists; crush.\n    now eapply H4.\n  Qed.\n\n  (* Unit *)\n  Lemma valrel_unit {d w} :\n    valrel d w ptunit I.unit E.unit.\n  Proof. crush. Qed.\n\n  (* True *)\n  Lemma valrel_true {d w} :\n    valrel d w ptbool I.true E.true.\n  Proof. crush. Qed.\n\n  (* False *)\n  Lemma valrel_false {d w} :\n    valrel d w ptbool I.false E.false.\n  Proof. crush. Qed.\n\n  (* Pair *)\n  Lemma valrel_pair'' {d w τ₁ τ₂ ts₁ ts₂ tu₁ tu₂} :\n    ValidPTy τ₁ -> ValidPTy τ₂ ->\n    OfType τ₁ ts₁ tu₁ →\n    OfType τ₂ ts₂ tu₂ →\n    (forall w', w' < w → valrel d w' τ₁ ts₁ tu₁) →\n    (forall w', w' < w → valrel d w' τ₂ ts₂ tu₂) →\n    valrel d w (ptprod τ₁ τ₂) (I.pair ts₁ ts₂) (E.pair tu₁ tu₂).\n  Proof.\n    crush.\n  Qed.\n\n  Lemma valrel_pair' {d w τ₁ τ₂ ts₁ ts₂ tu₁ tu₂} :\n    ValidPTy τ₁ -> ValidPTy τ₂ ->\n    valrel d w τ₁ ts₁ tu₁ →\n    valrel d w τ₂ ts₂ tu₂ →\n    valrel d (S w) (ptprod τ₁ τ₂) (I.pair ts₁ ts₂) (E.pair tu₁ tu₂).\n  Proof.\n    crush.\n  Qed.\n\n  Lemma valrel_0_pair {d τ₁ τ₂ vs₁ vu₁ vs₂ vu₂} :\n    ValidPTy τ₁ -> ValidPTy τ₂ ->\n    OfType τ₁ vs₁ vu₁ →\n    OfType τ₂ vs₂ vu₂ →\n    valrel d 0 (ptprod τ₁ τ₂) (I.pair vs₁ vs₂) (E.pair vu₁ vu₂).\n  Proof.\n    crush.\n  Qed.\n\n  Lemma valrel_pair {d w τ₁ τ₂ ts₁ ts₂ tu₁ tu₂} :\n    ValidPTy τ₁ -> ValidPTy τ₂ ->\n    valrel d w τ₁ ts₁ tu₁ →\n    valrel d w τ₂ ts₂ tu₂ →\n    valrel d w (ptprod τ₁ τ₂) (I.pair ts₁ ts₂) (E.pair tu₁ tu₂).\n  Proof.\n    crush.\n  Qed.\n\n\n  (* Inl *)\n  Lemma valrel_0_inl {d τ₁ τ₂ vs vu} :\n    ValidPTy τ₁ → ValidPTy τ₂ →\n    OfType τ₁ vs vu →\n    valrel d 0 (ptsum τ₁ τ₂) (I.inl vs) (E.inl vu).\n  Proof. crush. Qed.\n\n  Lemma valrel_inl {d w τ₁ τ₂ vs vu} :\n    ValidPTy τ₁ → ValidPTy τ₂ →\n    valrel d w τ₁ vs vu →\n    valrel d w (ptsum τ₁ τ₂) (I.inl vs) (E.inl vu).\n  Proof. crush. Qed.\n\n  Lemma valrel_inl' {d w τ₁ τ₂ vs vu} :\n    ValidPTy τ₁ → ValidPTy τ₂ →\n    valrel d w τ₁ vs vu →\n    valrel d (S w) (ptsum τ₁ τ₂) (I.inl vs) (E.inl vu).\n  Proof. crush. Qed.\n\n  Lemma valrel_inl'' {d w τ₁ τ₂ vs vu} :\n    ValidPTy τ₁ → ValidPTy τ₂ →\n    OfType τ₁ vs vu →\n    (∀ w', w' < w → valrel d w' τ₁ vs vu) →\n    valrel d w (ptsum τ₁ τ₂) (I.inl vs) (E.inl vu).\n  Proof. crush. Qed.\n\n  (* Inr *)\n  Lemma valrel_0_inr {d τ₁ τ₂ vs vu} :\n    ValidPTy τ₁ → ValidPTy τ₂ →\n    OfType τ₂ vs vu →\n    valrel d 0 (ptsum τ₁ τ₂) (I.inr vs) (E.inr vu).\n  Proof. crush. Qed.\n\n  Lemma valrel_inr {d w τ₁ τ₂ vs vu} :\n    ValidPTy τ₁ → ValidPTy τ₂ →\n    valrel d w τ₂ vs vu →\n    valrel d w (ptsum τ₁ τ₂) (I.inr vs) (E.inr vu).\n  Proof. crush. Qed.\n\n  Lemma valrel_inr' {d w τ₁ τ₂ vs vu} :\n    ValidPTy τ₁ → ValidPTy τ₂ →\n    valrel d w τ₂ vs vu →\n    valrel d (S w) (ptsum τ₁ τ₂) (I.inr vs) (E.inr vu).\n  Proof. crush. Qed.\n\n  Lemma valrel_inr'' {d w τ₁ τ₂ vs vu} :\n    ValidPTy τ₁ → ValidPTy τ₂ →\n    OfType τ₂ vs vu →\n    (∀ w', w' < w → valrel d w' τ₂ vs vu) →\n    valrel d w (ptsum τ₁ τ₂) (I.inr vs) (E.inr vu).\n  Proof. crush. Qed.\n\n  (* double check with Marco that these hypothesis are kosher *)\n  Lemma valrel_unk {d w n p vu τ} :\n    OfType (pEmulDV n p τ) (unkUVal n) vu → p = imprecise →\n    valrel d w (pEmulDV n p τ) (unkUVal n) vu.\n  Proof.\n    intros eq vvu; subst.\n    repeat crushLRMatch.\n    - unfold OfType, OfTypeStlcIso, OfTypeStlcEqui in *; split; simpl; split; try trivial;\n      eauto using unkUVal_Value, unkUValT; crush.\n    - cbn.\n      eexists; split; [reflexivity|]; split; [eapply unkUVal_Value|].\n      destruct n; [|left]; eauto.\n  Qed.\n\n  Lemma valrel_inUnit {d w n p vs vu} :\n    vs = I.unit ∧ vu = E.unit →\n    valrel d w (pEmulDV (S n) p E.tunit) (I.inl vs) vu.\n  Proof.\n    destruct 1 as [? ?]; subst.\n    repeat crushLRMatch.\n    - assert (⟪ empty i⊢ I.unit : tunit ⟫) by constructor.\n      unfold OfType, OfTypeStlcIso, OfTypeStlcEqui; split; simpl; crush.\n    - crush. right. exists I.unit. crush.\n  Qed.\n\n  Lemma valrel_inUnit' {d w n p vs vu} :\n    valrel d w ptunit vs vu →\n    valrel d w (pEmulDV (S n) p E.tunit) (I.inl vs) vu.\n  Proof.\n    intros vr.\n    rewrite valrel_fixp in vr.\n    destruct vr as [_ vr].\n    simpl in vr.\n    apply valrel_inUnit.\n    crush.\n  Qed.\n\n  Lemma valrel_inBool {d w n p vs vu} :\n    (vs = I.true ∧ vu = E.true) ∨ (vs = I.false ∧ vu = E.false) →\n    valrel d w (pEmulDV (S n) p E.tbool) (inBool n vs) vu.\n  Proof.\n    intros eqs;\n    repeat crushLRMatch.\n    - assert (⟪ empty i⊢ vs : tbool ⟫);\n      destruct eqs as [[? ?]|[? ?]]; subst; eauto with typing;\n      unfold OfType, OfTypeStlcIso, OfTypeStlcEqui; simpl;\n      eauto using inBool_Value, inBoolT with typing; crush.\n    - crush.\n      + destruct eqs as [[-> ->]|[-> ->]]; now cbn.\n      + right; exists vs; cbn; unfold is_inl; eauto.\n  Qed.\n\n  Lemma valrel_inBool' {d w n p vs vu} :\n    valrel d w ptbool vs vu →\n    valrel d w (pEmulDV (S n) p E.tbool) (inBool n vs) vu.\n  Proof.\n    intros vr.\n    rewrite valrel_fixp in vr.\n    destruct vr as [_ vr].\n    simpl in vr.\n    apply valrel_inBool.\n    crush.\n  Qed.\n\n  Lemma valrel_inProd {d w n p τ₁ τ₂ vs₁ vs₂ vu₁ vu₂} :\n    OfType (pEmulDV n p τ₁) vs₁ vu₁ →\n    OfType (pEmulDV n p τ₂) vs₂ vu₂ →\n    (forall w', w' < w → valrel d w' (pEmulDV n p τ₁) vs₁ vu₁) →\n    (forall w', w' < w → valrel d w' (pEmulDV n p τ₂) vs₂ vu₂) →\n    valrel d w (pEmulDV (S n) p (E.tprod τ₁ τ₂)) (inProd n (I.pair vs₁ vs₂)) (E.pair vu₁ vu₂).\n  Proof.\n    intros ot₁ ot₂ vr₁ vr₂.\n    destruct (OfType_implies_Value ot₁).\n    destruct (OfType_implies_Value ot₂).\n    repeat crushLRMatch.\n    - unfold OfType, OfTypeStlcIso, OfTypeStlcEqui in *; crush.\n    - crush. right. cbn. exists (I.pair vs₁ vs₂). unfold is_inl; cbn.\n      crush.\n  Qed.\n\n  Lemma valrel_inProd' {d w n p τ₁ τ₂ vs₁ vs₂ vu₁ vu₂} :\n    ValidTy τ₁ -> ValidTy τ₂ ->\n    (valrel d w (pEmulDV n p τ₁) vs₁ vu₁) →\n    (valrel d w (pEmulDV n p τ₂) vs₂ vu₂) →\n    valrel d (S w) (pEmulDV (S n) p (E.tprod τ₁ τ₂)) (inProd n (I.pair vs₁ vs₂)) (E.pair vu₁ vu₂).\n  Proof.\n    intros vτ₁ vτ₂ vr₁ vr₂.\n    eapply valrel_inProd; crush.\n Qed.\n\n  Lemma valrel_inProd'' {d w n p τ₁ τ₂ vs vu} :\n    ValidTy τ₁ -> ValidTy τ₂ ->\n    valrel d w (ptprod (pEmulDV n p τ₁) (pEmulDV n p τ₂)) vs vu →\n    valrel d w (pEmulDV (S n) p (tprod τ₁ τ₂)) (inProd n vs) vu.\n  Proof.\n    intros vτ₁ vτ₂ vr.\n    rewrite valrel_fixp in vr.\n    destruct vr as (val & vs2 & eqfolds & vvs & vr).\n    rewrite <-eqfolds in *.\n    simpl in vr; unfold prod_rel in vr.\n    destruct vs; try contradiction.\n    destruct vu; try contradiction.\n    destruct val as ((? & ?) & (? & ?)).\n    destruct vr as (? & ?).\n    simpl in H0.\n    simpl in H2.\n    I.stlcCanForm.\n    E.stlcCanForm.\n    destruct H as (? & ?).\n    eapply valrel_inProd; crush.\n  Qed.\n\n  Lemma valrel_inSum_l {d w n p vs vs' vu vu' τl τr} :\n    ValidTy τl -> ValidTy τr ->\n    OfType (pEmulDV n p τl) vs vu →\n    (forall w', w' < w → valrel d w' (pEmulDV n p τl) vs vu) →\n    vs' = I.inl vs ∧ vu' = E.inl vu →\n    valrel d w (pEmulDV (S n) p (E.tsum τl τr)) (I.inl vs') vu'.\n  Proof.\n    intros vτl vτr ot vr eq.\n    destruct (OfType_implies_Value ot).\n    assert (I.Value vs') by (crush).\n    assert (E.Value vu') by (crush).\n    assert ⟪ empty i⊢ vs' : UValIE n τl r⊎ UValIE n τr ⟫\n      by (destruct ot as [[? ?] ?]; crush; now apply UValIE_valid).\n    assert ⟪ empty e⊢ vu' : tsum τl τr ⟫\n      by (destruct ot as [? [? ?]]; crush).\n    repeat crushLRMatch.\n    - crush; now apply UValIE_valid.\n    - crush. right. exists (I.inl vs). crush.\n  Qed.\n\n  Lemma valrel_inSum_r {d w n p vs vs' vu vu' τl τr} :\n    ValidTy τl -> ValidTy τr ->\n    OfType (pEmulDV n p τr) vs vu →\n    (forall w', w' < w → valrel d w' (pEmulDV n p τr) vs vu) →\n    vs' = I.inr vs ∧ vu' = E.inr vu →\n    valrel d w (pEmulDV (S n) p (E.tsum τl τr)) (I.inl vs') vu'.\n  Proof.\n    intros vτl vτr ot vr eq.\n    destruct (OfType_implies_Value ot).\n    assert (I.Value vs') by (crush).\n    assert (E.Value vu') by (crush).\n    assert ⟪ empty i⊢ vs' : UValIE n τl r⊎ UValIE n τr ⟫\n      by (destruct ot as [[? ?] ?]; crush; now apply UValIE_valid).\n    assert ⟪ empty e⊢ vu' : tsum τl τr ⟫\n      by (destruct ot as [? [? ?]]; crush).\n    repeat crushLRMatch.\n    - crush; now apply UValIE_valid.\n    - crush. right. exists (I.inr vs). crush.\n  Qed.\n\n  (* Lemma valrel_inSum {d w n p vs vs' vu vu' τ τ'} : *)\n  (*   OfType (pEmulDV n p (I.tsum τ τ')) vs vu → *)\n  (*   (forall w', w' < w → valrel d w' (pEmulDV n p (I.tsum τ τ')) vs vu) → *)\n  (*   (vs' = F.inl vs ∧ vu' = I.inl vu) ∨ (vs' = F.inr vs ∧ vu' = I.inr vu) → *)\n  (*   valrel d w (pEmulDV (S n) p (I.tsum τ τ')) (F.inl vs') vu'. *)\n  (* Proof. *)\n  (*   intros ot vr eqs. *)\n  (*   destruct (OfType_implies_Value ot). *)\n  (*   assert (F.Value vs') by (destruct eqs as [[? ?]|[? ?]]; crush). *)\n  (*   assert (I.Value vu') by (destruct eqs as [[? ?]|[? ?]]; crush). *)\n  (*   destruct ot as [[? ?] [? ?]]. *)\n  (*   assert ⟪ F.empty ⊢ vs' : (UValFI n τ) ⊎ (UValFI n τ') ⟫. *)\n  (*   destruct eqs as [[? ?]|[? ?]]; crush. *)\n  (*     by (destruct eqs as [[? ?]|[? ?]]; crush). *)\n  (*   assert ⟨ 0 ⊢ vu' ⟩ *)\n  (*          by (destruct eqs as [[? ?]|[? ?]]; crush). *)\n  (*   crush. *)\n  (*   right. exists vs'. right. right. right. left. *)\n  (*   destruct eqs as [[? ?]|[? ?]]; crush. *)\n  (* Qed. *)\n\n  Lemma valrel_inSum' {d w n p vs vs' vu vu' τl τr} :\n    ValidTy τl -> ValidTy τr ->\n    (\n      valrel d w (pEmulDV n p τl) vs vu\n      ∧ (vs' = I.inl vs ∧ vu' = E.inl vu)\n    ) ∨ (\n      valrel d w (pEmulDV n p τr) vs vu\n      ∧ (vs' = I.inr vs ∧ vu' = E.inr vu)\n    ) →\n    valrel d (S w) (pEmulDV (S n) p (E.tsum τl τr)) (I.inl vs') vu'.\n  Proof.\n    intros vτl vτr.\n    destruct 1;\n    destruct H.\n    - refine (valrel_inSum_l _ _ _ _ H0); crush.\n    - refine (valrel_inSum_r _ _ _ _ H0); crush.\n  Qed.\n\n  Lemma valrel_inSum'' {d w n p vs vu τl τr} :\n    ValidTy τl -> ValidTy τr ->\n    valrel d w (ptsum (pEmulDV n p τl) (pEmulDV n p τr)) vs vu →\n    valrel d w (pEmulDV (S n) p (E.tsum τl τr)) (I.inl vs) vu.\n  Proof.\n   intros vτl vτr vr.\n   rewrite valrel_fixp in vr.\n   destruct vr as (val & ? & <- & vval & vr).\n   destruct val as ((? & ?) & ? & ?).\n   simpl in H0.\n   simpl in H2.\n   I.stlcCanForm;\n   E.stlcCanForm;\n     simpl in vr;\n     try contradiction.\n   - eapply valrel_inSum_l; auto; crush.\n   - eapply valrel_inSum_r; auto; crush.\n  Qed.\n\n  Lemma valrel_inArr {d w n p vs vu τ₁ τ₂} :\n    valrel d w (ptarr (pEmulDV n p τ₁) (pEmulDV n p τ₂)) vs vu →\n    valrel d w (pEmulDV (S n) p (E.tarr τ₁ τ₂)) (I.inl vs) vu.\n  Proof.\n    intros vr.\n    crush.\n    - destruct (valrel_implies_OfType vr) as [[_ ?] _].\n      eauto.\n    - destruct (valrel_implies_OfType vr) as (_ & _ & ?).\n      crush.\n    - right. exists vs. crush.\n      rewrite valrel_fixp in vr.\n      destruct vr as ([_ ?] & ? & <- & vrarr).\n      crush.\n  Qed.\n\n  (* Lemma valrel_0_inRec {d n p vs vu τ} : *)\n  (*   OfType (pEmulDV (S n) p τ[beta1 (I.trec τ)]) vs vu → *)\n  (*   valrel d 0 (pEmulDV (S n) p τ[beta1 (I.trec τ)]) vs vu. *)\n  (* Proof. *)\n  (*   intro ot. *)\n  (*   destruct ot as [[? ?] [? ?]]. *)\n  (*   crush. *)\n  (*   unfold UValFI in H0. *)\n  (*   F.stlcCanForm. *)\n  (*   right. *)\n  (*   2: destruct p; [right | left; auto]. *)\n  (*   revert H2 H4. *)\n  (*   generalize τ[beta1 (I.trec τ)] as τ'. *)\n  (*   intros τ' H2 H4. *)\n  (*   dependent destruction τ'; cbn. *)\n  (*   exists x. *)\n  (*   crush. *)\n  (*   exists unit. *)\n  (*   F.stlcCanForm. *)\n  (*   I.stlcCanForm. *)\n  (*   crush. *)\n  (*   exists x. *)\n  (*   crush. *)\n  (*   unfold sum_rel. *)\n  (*   F.stlcCanForm. *)\n  (*   dependent induction n. *)\n  (*   unfold UValFI in H0. *)\n\n\n  (* Lemma valrel_inRec {d w n p vs vu τ} : *)\n  (*   valrel d w (pEmulDV n p τ[beta1 (I.trec τ)]) vs vu → *)\n  (*   valrel d w (pEmulDV (S n) p (I.trec τ)) (F.inl vs) (I.fold_ vu). *)\n  (* Proof. *)\n  (*   intros vr. *)\n  (*   crush. *)\n  (*   - destruct (valrel_implies_OfType vr) as [[_ ?] _]. *)\n  (*     eauto. *)\n  (*   - destruct (valrel_implies_OfType vr) as (_ & _ & ?). *)\n  (*     eauto. *)\n  (*   - right. exists vs. split. *)\n  (*     + crush. *)\n  (*     + exists vu. split. reflexivity. *)\n  (*       destruct (valrel_implies_OfType vr) as [[? ?] [? ?]]. *)\n  (*       dependent induction n. *)\n  (*       intro w'; *)\n  (*       rewrite valrel_fixp in vr; destruct vr as [[_ ?] vrrec]; *)\n  (*       crush. *)\n  (*       dependent induction τ; crush. *)\n  (* Qed. *)\n  (* Lemma valrel_0_inRec {n dir p vs vu τ} : *)\n  (*   OfType (pEmulDV (S n) p (E.trec τ)) (I.inl (fold_ vs)) vu → *)\n  (*   valrel dir 0 (pEmulDV (S n) p (E.trec τ)) (I.inl (fold_ vs)) vu. *)\n  (* Proof. *)\n  (*   rewrite valrel_fixp; *)\n  (*   unfold valrel'; *)\n  (*   split; *)\n  (*   destruct 0 as [[? ?] [? ?]]; *)\n  (*   crush; *)\n  (*   right. *)\n  (*   exists vs; crush. *)\n  (*   exists vu; crush. *)\n  (* Qed. *)\n\n\n  Lemma valrel_inRec {d w n p vs vu τ} :\n    ValidTy (trec τ) →\n    valrel d w (pEmulDV n p τ[beta1 (trec τ)]) vs vu →\n    valrel d w (pEmulDV n p (trec τ)) vs vu.\n  Proof.\n    intros [clτ crτ] vr.\n    rewrite valrel_fixp in vr; unfold valrel' in vr; cbn in vr.\n    change (τ[beta1 (E.trec τ)]) with (unfoldOnce (trec τ)) in vr.\n    rewrite (LMC_unfoldOnce (trec τ)) in vr; try assumption; [|cbn;eauto with arith].\n    cbn in vr.\n    rewrite valrel_fixp; unfold valrel'; cbn.\n    destruct vr as [ot vr].\n    split; [|assumption].\n    destruct ot as ((vvs & tys) & (vvu & tyu));\n    crush;\n    cbn in tys, tyu.\n    rewrite UValIE_trec; try assumption.\n    now inversion crτ.\n    refine (WtEq _ _ _ _ tyu); try assumption.\n    eapply EqMuR, tyeq_refl.\n    now eapply E.ValidTy_unfold_trec.\n    crushValidTy.\n  Qed.\nEnd ValueRelation.\n\nLtac valrelIntro :=\n  match goal with\n    | |- valrel _ _ (ptarr ?τ _) (I.abs (repEmul ?τ) _) (E.abs (isToEq ?τ) _) => eapply valrel_lambda\n    | |- valrel _ _ ptunit I.unit E.unit => apply valrel_unit\n    (* | |- valrel _ _ ptbool F.true I.true => apply valrel_true *)\n    (* | |- valrel _ _ ptbool F.false I.false => apply valrel_false *)\n    (* | |- valrel _ ?w (ptprod _ _) (F.pair _ _) (I.pair _ _) => *)\n    (*   match w with *)\n    (*     | O   => apply valrel_0_pair *)\n    (*     | S _ => apply valrel_pair' *)\n    (*     | _   => apply valrel_pair *)\n    (*   end *)\n    | |- valrel _ ?w (ptsum _ _) (I.inl _) (E.inl _) =>\n      match w with\n        | O   => apply valrel_0_inl\n        | S _ => apply valrel_inl'\n        | _   => apply valrel_inl\n      end\n    | |- valrel _ ?w (ptsum _ _) (I.inr _) (E.inr _) =>\n      match w with\n        | O   => apply valrel_0_inr\n        | S _ => apply valrel_inr'\n        | _   => apply valrel_inr\n      end\n    | [ H : valrel ?d _ ?τ ?ts ?tu |- valrel ?d _ ?τ ?ts ?tu ] =>\n      refine (valrel_mono _ H); try lia\n  end.\n\nSection TermRelation.\n\n  (* Eval context *)\n  (* related terms plugged in related contexts are still related (lemma 20 in TR) *)\n  Lemma termrel_ectx {d w τ₁ τ₂ ts Cs tu Cu} (eCs : I.ECtx Cs) (eCu : E.ECtx Cu) :\n    termrel d w τ₁ ts tu →\n    (∀ w' (fw' : w' ≤ w) vs vu, valrel d w' τ₁ vs vu → termrel d w' τ₂ (I.pctx_app vs Cs) (E.pctx_app vu Cu)) →\n    termrel d w τ₂ (I.pctx_app ts Cs) (E.pctx_app tu Cu).\n  Proof.\n    intros tr cr Cs' Cu' eCs' eCu' cr'.\n    rewrite <- I.pctx_cat_app.\n    rewrite <- E.pctx_cat_app.\n    refine (tr (I.pctx_cat Cs Cs') (E.pctx_cat Cu Cu') _ _ _); eauto using I.ectx_cat, E.ectx_cat.\n    intros w' fw' vs vu vr.\n    destruct (valrel_implies_Value vr) as [vvs vvu].\n    rewrite -> I.pctx_cat_app.\n    rewrite -> E.pctx_cat_app.\n    refine (cr w' fw' vs vu vr Cs' Cu' eCs' eCu' _).\n    refine (contrel_mono fw' cr').\n  Qed.\n\n  Lemma termrel_ectx' {d w τ₁ τ₂ ts Cs tu ts' tu' Cu} :\n    termrel d w τ₁ ts tu →\n    (∀ w' (fw' : w' ≤ w) vs vu, valrel d w' τ₁ vs vu → termrel d w' τ₂ (I.pctx_app vs Cs) (E.pctx_app vu Cu)) →\n    ts' = I.pctx_app ts Cs →\n    tu' = E.pctx_app tu Cu →\n    I.ECtx Cs → E.ECtx Cu →\n    termrel d w τ₂ ts' tu'.\n  Proof.\n    intros; subst; eauto using termrel_ectx.\n  Qed.\n\n  (* Application *)\n  Lemma valrel_app {d w τ₁ τ₂ vs₁ vs₂ vu₁ vu₂} :\n    ValidPTy τ₁ -> ValidPTy τ₂ ->\n    valrel d w (ptarr τ₁ τ₂) vs₁ vu₁ →\n    valrel d w τ₁ vs₂ vu₂ →\n    termrel d w τ₂ (I.app vs₁ vs₂) (E.app vu₁ vu₂).\n  Proof.\n    (* destruct assumptions *)\n    intros vτ₁ vτ₂ vr₁ vr₂.\n    rewrite -> valrel_fixp in vr₁.\n    destruct vr₁ as (ot & ? & <- & vvs1 & hyp); subst; cbn in hyp.\n    apply OfType_inversion_ptarr in ot.\n    destruct ot as (tsb & tub & τ₁' & eqs & equ & eqτ & tytsb & tytub); subst.\n    destruct (valrel_implies_Value vr₂) as [vvs₂ vvu₂].\n\n    eapply termrel_size_right'.\n    intros szvs.\n\n    (* beta-reduce *)\n    assert (es : I.eval (I.app (I.abs (repEmul τ₁) tsb) vs₂) (tsb [beta1 vs₂])) by\n        (refine (I.eval_ctx₀ I.phole _ I); refine (I.eval_beta vvs₂)).\n    assert (es1 : I.evaln (I.app (I.abs (repEmul τ₁) tsb) vs₂) (tsb [beta1 vs₂]) 1) by\n        (unfold I.evaln; eauto with eval; lia).\n    assert (eu : E.eval (E.app (E.abs τ₁' tub) vu₂) (tub [beta1 vu₂])) by\n        (refine (E.eval_ctx₀ E.phole _ I); refine (E.eval_beta vvu₂)).\n    assert (eu1 : E.evaln (E.app (E.abs τ₁' tub) vu₂) (tub [beta1 vu₂]) 1) by\n        (unfold E.evaln; eauto with eval).\n    destruct w; try apply termrel_zero.\n    refine (termrel_antired w es1 eu1 _ _ _); unfold lev in *; simpl; try lia.\n\n    (* use assumption for function body *)\n    destruct hyp as (tsb' & tub' & τ₁'' & τ₂' & eq1 & eq2 & hyp).\n    inversion eq1; inversion eq2; subst.\n    eapply hyp; try lia; eauto using valrel_mono.\n    intros ->.\n    specialize (szvs eq_refl).\n    cbn in szvs.\n    lia.\n    assumption.\n    assumption.\n  Qed.\n\n  Lemma termrel_app {d w τ₁ τ₂ ts₁ ts₂ tu₁ tu₂} :\n    ValidPTy τ₁ -> ValidPTy τ₂ ->\n    termrel d w (ptarr τ₁ τ₂) ts₁ tu₁ →\n    (∀ w', w' ≤ w → termrel d w' τ₁ ts₂ tu₂) →\n    termrel d w τ₂ (I.app ts₁ ts₂) (E.app tu₁ tu₂).\n  Proof.\n    intros vτ₁ vτ₂ tr₁ tr₂.\n    change (I.app _ _) with (I.pctx_app ts₁ (I.papp₁ I.phole ts₂)).\n    change (E.app _ _) with (E.pctx_app tu₁ (E.papp₁ E.phole tu₂)).\n    refine (termrel_ectx _ _ tr₁ _); crush.\n    destruct (valrel_implies_Value H) as [vvs vvu].\n    change (I.app _ _) with (I.pctx_app ts₂ (I.papp₂ vs I.phole)).\n    change (E.app _ _) with (E.pctx_app tu₂ (E.papp₂ vu E.phole)).\n    refine (termrel_ectx _ _ (tr₂ w' fw')  _); crush.\n    refine (valrel_app _ _ _ H0); crush.\n  Qed.\n\n  Lemma termrel_ite {d w τ ts₁ ts₂ ts₃ tu₁ tu₂ tu₃} :\n    termrel d w ptbool ts₁ tu₁ →\n    (∀ w', w' ≤ w → termrel d w' τ ts₂ tu₂) →\n    (∀ w', w' ≤ w → termrel d w' τ ts₃ tu₃) →\n    termrel d w τ (I.ite ts₁ ts₂ ts₃) (E.ite tu₁ tu₂ tu₃).\n  Proof.\n    intros tr₁ tr₂ tr₃.\n\n    (* first evaluate ts₁ and tu₁ *)\n    change (I.ite _ _ _) with (I.pctx_app ts₁ (I.pite₁ I.phole ts₂ ts₃)).\n    change (E.ite _ _ _) with (E.pctx_app tu₁ (E.pite₁ E.phole tu₂ tu₃)).\n    refine (termrel_ectx _ _ tr₁ _); crush.\n\n    (* then evaluate the if-statement *)\n    rewrite -> valrel_fixp in H.\n    destruct H as (ot & ? & <- & _ & [[? ?]|[? ?]]); subst; clear ot.\n    - assert (I.eval (I.ite I.true ts₂ ts₃) ts₂) by\n          (apply (I.eval_ctx₀ I.phole); try refine (I.eval_ite_true _ _); simpl; intuition).\n      assert (esn : I.evaln (I.ite I.true ts₂ ts₃) ts₂ 1) by (unfold I.evaln; eauto with eval).\n      assert (E.eval (E.ite E.true tu₂ tu₃) tu₂) by\n          (apply (E.eval_eval₀); try refine E.eval_ite_true; simpl; intuition).\n      assert (eun : E.evaln (E.ite E.true tu₂ tu₃) tu₂ 1) by (unfold E.evaln; eauto with eval).\n      refine (termrel_antired w' esn eun _ _ _); crush.\n    - assert (I.eval (I.ite I.false ts₂ ts₃) ts₃) by\n          (apply (I.eval_ctx₀ I.phole); try refine I.eval_ite_false; simpl; intuition).\n      assert (esn : I.evaln (I.ite I.false ts₂ ts₃) ts₃ 1) by (unfold I.evaln; eauto with eval).\n      assert (E.eval (E.ite E.false tu₂ tu₃) tu₃) by\n          (apply (E.eval_eval₀); try refine E.eval_ite_false; simpl; intuition).\n      assert (eun : E.evaln (E.ite E.false tu₂ tu₃) tu₃ 1) by (unfold E.evaln; eauto with eval).\n      refine (termrel_antired w' esn eun _ _ _); crush.\n  Qed.\n\n  (* Pair *)\n  Lemma termrel_pair {d w τ₁ τ₂ ts₁ ts₂ tu₁ tu₂} :\n    ValidPTy τ₁ -> ValidPTy τ₂ ->\n    termrel d w τ₁ ts₁ tu₁ →\n    (∀ w', w' ≤ w → termrel d w' τ₂ ts₂ tu₂) →\n    termrel d w (ptprod τ₁ τ₂) (I.pair ts₁ ts₂) (E.pair tu₁ tu₂).\n  Proof.\n    intros vτ₁ vτ₂ tr₁ tr₂.\n    change (I.pair _ _) with (I.pctx_app ts₁ (I.ppair₁ I.phole ts₂)).\n    change (E.pair _ _) with (E.pctx_app tu₁ (E.ppair₁ E.phole tu₂)).\n    refine (termrel_ectx _ _ tr₁ _); crush.\n    destruct (valrel_implies_Value H) as [vvs₂ vvu₂].\n    change (I.pair _ _) with (I.pctx_app ts₂ (I.ppair₂ vs I.phole)).\n    change (E.pair _ _) with (E.pctx_app tu₂ (E.ppair₂ vu E.phole)).\n    refine (termrel_ectx _ _ (tr₂ w' fw')  _); crush.\n    eauto using valrel_in_termrel, valrel_mono, valrel_pair.\n  Qed.\n\n  (* Proj₁ *)\n  Lemma termrel_proj₁ {d w τ₁ τ₂ ts tu} :\n    ValidPTy τ₁ -> ValidPTy τ₂ ->\n    termrel d w (ptprod τ₁ τ₂) ts tu →\n    termrel d w τ₁ (I.proj₁ ts) (E.proj₁ tu).\n  Proof.\n    intros vτ₁ vτ₂ tr.\n\n    (* first evaluate ts and tu *)\n    change (I.proj₁ _) with (I.pctx_app ts (I.pproj₁ I.phole)).\n    change (E.proj₁ _) with (E.pctx_app tu (E.pproj₁ E.phole)).\n    refine (termrel_ectx _ _ tr _); crush.\n\n    (* then evaluate the projection *)\n    rewrite -> valrel_fixp in H.\n    destruct H as [ot hyp]; subst; cbn in hyp.\n    apply OfType_inversion_ptprod in ot; eauto.\n    destruct ot as (vs₁ & vu₁ & vs₂ & vu₂ & ? & ? & ot₁ & ot₂); subst.\n    destruct (OfType_implies_Value ot₁) as [vvs₁ vvs₂].\n    destruct (OfType_implies_Value ot₂) as [vvu₁ vvu₂].\n    destruct hyp as (? & <- & _ & vr₁ & vr₂).\n\n    assert (I.eval (I.proj₁ (I.pair vs₁ vs₂)) vs₁) by\n        (apply (I.eval_ctx₀ I.phole); try refine (I.eval_proj₁ _ _); simpl; intuition).\n    assert (esn : I.evaln (I.proj₁ (I.pair vs₁ vs₂)) vs₁ 1) by (unfold I.evaln; eauto with eval).\n    assert (E.eval (E.proj₁ (E.pair vu₁ vu₂)) vu₁) by\n        (apply (E.eval_eval₀); try refine (E.eval_proj₁ _ _); simpl; intuition).\n    assert (eun : E.evaln (E.proj₁ (E.pair vu₁ vu₂)) vu₁ 1) by (unfold E.evaln; eauto with eval).\n    destruct w'; try apply termrel_zero.\n    refine (termrel_antired w' esn eun _ _ _); crush.\n\n    (* then conclude *)\n    apply valrel_in_termrel.\n    apply vr₁; intuition; lia.\n  Qed.\n\n  Lemma termrel₀_proj₁ {d w τ₁ τ₂ ts tu} :\n    ValidPTy τ₁ -> ValidPTy τ₂ ->\n    valrel d (S w) (ptprod τ₁ τ₂) ts tu →\n    termrel₀ d w τ₁ (I.proj₁ ts) (E.proj₁ tu).\n  Proof.\n    intros vτ₁ vτ₂ vr.\n\n    rewrite -> valrel_fixp in vr.\n    destruct vr as [ot hyp]; subst; cbn in hyp.\n    apply OfType_inversion_ptprod in ot; eauto.\n    destruct ot as (vs₁ & vu₁ & vs₂ & vu₂ & ? & ? & ot₁ & ot₂); subst.\n    destruct (OfType_implies_Value ot₁) as [vvs₁ vvs₂].\n    destruct (OfType_implies_Value ot₂) as [vvu₁ vvu₂].\n    destruct hyp as (? & <- & _ & vr₁ & vr₂).\n\n    assert (I.eval (I.proj₁ (I.pair vs₁ vs₂)) vs₁) by\n        (apply (I.eval_ctx₀ I.phole); try refine (I.eval_proj₁ _ _); simpl; crush).\n    assert (esn : clos_refl_trans_1n I.Tm I.eval (I.proj₁ (I.pair vs₁ vs₂)) vs₁) by (eauto with eval).\n    assert (E.eval (E.proj₁ (E.pair vu₁ vu₂)) vu₁) by\n        (apply (E.eval_eval₀); try refine (E.eval_proj₁ _ _); simpl; intuition).\n    assert (eun : E.evalStar (E.proj₁ (E.pair vu₁ vu₂)) vu₁)\n      by (unfold E.evalStar; eauto with eval).\n    refine (termrel₀_antired_star esn eun _); crush.\n\n    eapply valrel_in_termrel₀.\n    apply vr₁; crush.\n  Qed.\n\n  Lemma termrel₀_proj₂ {d w τ₁ τ₂ ts tu} :\n    ValidPTy τ₁ -> ValidPTy τ₂ ->\n    valrel d (S w) (ptprod τ₁ τ₂) ts tu →\n    termrel₀ d w τ₂ (I.proj₂ ts) (E.proj₂ tu).\n  Proof.\n    intros vτ₁ vτ₂ vr.\n\n    rewrite -> valrel_fixp in vr.\n    destruct vr as [ot hyp]; subst; cbn in hyp.\n    apply OfType_inversion_ptprod in ot; eauto.\n    destruct ot as (vs₁ & vu₁ & vs₂ & vu₂ & ? & ? & ot₁ & ot₂); subst.\n    destruct (OfType_implies_Value ot₁) as [vvs₁ vvs₂].\n    destruct (OfType_implies_Value ot₂) as [vvu₁ vvu₂].\n    destruct hyp as (? & <- & _ & vr₁ & vr₂).\n\n    assert (I.eval (I.proj₂ (I.pair vs₁ vs₂)) vs₂) by\n        (apply (I.eval_ctx₀ I.phole); try refine (I.eval_proj₂ _ _); simpl; intuition).\n    assert (esn : clos_refl_trans_1n I.Tm I.eval (I.proj₂ (I.pair vs₁ vs₂)) vs₂) by (eauto with eval).\n    assert (E.eval (E.proj₂ (E.pair vu₁ vu₂)) vu₂) by\n        (apply (E.eval_eval₀); try refine (E.eval_proj₂ _ _); simpl; intuition).\n    assert (eun : E.evalStar (E.proj₂ (E.pair vu₁ vu₂)) vu₂)\n      by (unfold E.evalStar; eauto with eval).\n    refine (termrel₀_antired_star esn eun _); crush.\n\n    eapply valrel_in_termrel₀.\n    apply vr₂; crush.\n  Qed.\n\n  (* Proj₂ *)\n  Lemma termrel_proj₂ {d w τ₁ τ₂ ts tu} :\n    ValidPTy τ₁ -> ValidPTy τ₂ ->\n    termrel d w (ptprod τ₁ τ₂) ts tu →\n    termrel d w τ₂ (I.proj₂ ts) (E.proj₂ tu).\n  Proof.\n    intros vτ₁ vτ₂ tr.\n\n    (* first reduce ts and tu *)\n    change (I.proj₂ _) with (I.pctx_app ts (I.pproj₂ I.phole)).\n    change (E.proj₂ _) with (E.pctx_app tu (E.pproj₂ E.phole)).\n    refine (termrel_ectx _ _ tr _); crush.\n\n    (* then evaluate the projection *)\n    rewrite -> valrel_fixp in H.\n    destruct H as [ot hyp]; subst; cbn in hyp.\n    apply OfType_inversion_ptprod in ot; eauto.\n    destruct ot as (vs₁ & vu₁ & vs₂ & vu₂ & ? & ? & ot₁ & ot₂); subst.\n    destruct (OfType_implies_Value ot₁) as [vvs₁ vvs₂].\n    destruct (OfType_implies_Value ot₂) as [vvu₁ vvu₂].\n    destruct hyp as (? & <- & _ & vr₁ & vr₂).\n\n    assert (I.eval (I.proj₂ (I.pair vs₁ vs₂)) vs₂) by\n        (apply (I.eval_ctx₀ I.phole); try refine (I.eval_proj₂ _ _); simpl; intuition).\n    assert (esn : I.evaln (I.proj₂ (I.pair vs₁ vs₂)) vs₂ 1) by (unfold I.evaln; eauto with eval).\n    assert (E.eval (E.proj₂ (E.pair vu₁ vu₂)) vu₂) by\n        (apply E.eval_eval₀; try refine (E.eval_proj₂ _ _); simpl; intuition).\n    assert (eun : E.evaln (E.proj₂ (E.pair vu₁ vu₂)) vu₂ 1)\n      by (unfold E.evaln; eauto with eval).\n    destruct w'; try apply termrel_zero.\n    refine (termrel_antired w' esn eun _ _ _); crush.\n\n    apply valrel_in_termrel.\n    apply vr₂; crush.\n  Qed.\n\n  (* Inl *)\n  Lemma termrel_inl {d w τ₁ τ₂ ts tu} :\n    ValidPTy τ₁ -> ValidPTy τ₂ ->\n    termrel d w τ₁ ts tu →\n    termrel d w (ptsum τ₁ τ₂) (I.inl ts) (E.inl tu).\n  Proof.\n    intros vτ₁ vτ₂ tr.\n    change (I.inl ts) with (I.pctx_app ts (I.pinl I.phole)).\n    change (E.inl tu) with (E.pctx_app tu (E.pinl E.phole)).\n    refine (termrel_ectx _ _ tr _); crush.\n    apply valrel_in_termrel; crush.\n  Qed.\n\n  (* Inr *)\n  Lemma termrel_inr {d w τ₁ τ₂ ts tu} :\n    ValidPTy τ₁ -> ValidPTy τ₂ ->\n    termrel d w τ₂ ts tu →\n    termrel d w (ptsum τ₁ τ₂) (I.inr ts) (E.inr tu).\n  Proof.\n    intros vτ₁ vτ₂ tr.\n    change (I.inr ts) with (I.pctx_app ts (I.pinr I.phole)).\n    change (E.inr tu) with (E.pctx_app tu (E.pinr E.phole)).\n    refine (termrel_ectx _ _ tr _); crush.\n    apply valrel_in_termrel; crush.\n  Qed.\n\n  (* Caseof *)\n  Lemma termrel_caseof {d w τ τ₁ τ₂ ts₁ ts₂ ts₃ tu₁ tu₂ tu₃} :\n    ValidPTy τ₁ -> ValidPTy τ₂ ->\n    termrel d w (ptsum τ₁ τ₂) ts₁ tu₁ →\n    (∀ w' vs₁ vu₁, w' < w → valrel d w' τ₁ vs₁ vu₁ → termrel d w' τ (ts₂ [beta1 vs₁]) (tu₂ [ beta1 vu₁])) →\n    (∀ w' vs₂ vu₂, w' < w → valrel d w' τ₂ vs₂ vu₂ → termrel d w' τ (ts₃ [beta1 vs₂]) (tu₃ [ beta1 vu₂])) →\n    termrel d w τ (I.caseof ts₁ ts₂ ts₃) (E.caseof tu₁ tu₂ tu₃).\n  Proof.\n    intros vτ₁ vτ₂ tr₁ tr₂ tr₃.\n\n    (* first evaluate ts₁ and tu₁ *)\n    change (I.caseof _ _ _) with (I.pctx_app ts₁ (I.pcaseof₁ I.phole ts₂ ts₃)).\n    change (E.caseof _ _ _) with (E.pctx_app tu₁ (E.pcaseof₁ E.phole tu₂ tu₃)).\n    refine (termrel_ectx _ _ tr₁ _); crush.\n\n    (* then evaluate the caseof *)\n    rewrite -> valrel_fixp in H.\n    destruct H as (ot & ? & <- & _ & hyp); subst; cbn in hyp.\n    apply OfType_inversion_ptsum in ot; eauto.\n    destruct ot as (vs' & vu' & [(? & ? & ot)|[(? & ?)|[(? & ?)|(? & ? & ot)]]]);\n      subst; cbn in *; try contradiction;\n      destruct (OfType_implies_Value ot) as [vvs vvu]; clear ot.\n    - assert (I.eval (I.caseof (I.inl vs') ts₂ ts₃) (ts₂ [beta1 vs'])) by\n          (apply (I.eval_ctx₀ I.phole); try refine (I.eval_case_inl _); simpl; intuition).\n      assert (esn : I.evaln (I.caseof (I.inl vs') ts₂ ts₃) (ts₂ [beta1 vs']) 1) by (unfold I.evaln; eauto with eval).\n      assert (E.eval (E.caseof (E.inl vu') tu₂ tu₃) (tu₂ [beta1 vu'])) by\n          (apply (E.eval_ctx₀ E.phole); try refine (E.eval_case_inl _); simpl; intuition).\n      assert (eun : E.evaln (E.caseof (E.inl vu') tu₂ tu₃) (tu₂ [beta1 vu']) 1) by (unfold E.evaln; eauto with eval).\n      destruct w'; try apply termrel_zero.\n      refine (termrel_antired w' esn eun _ _ _); crush.\n    - assert (I.eval (I.caseof (I.inr vs') ts₂ ts₃) (ts₃ [beta1 vs'])) by\n          (apply (I.eval_ctx₀ I.phole); try refine (I.eval_case_inr _); simpl; intuition).\n      assert (esn : I.evaln (I.caseof (I.inr vs') ts₂ ts₃) (ts₃ [beta1 vs']) 1) by (unfold I.evaln; eauto with eval).\n      assert (E.eval (E.caseof (E.inr vu') tu₂ tu₃) (tu₃ [beta1 vu'])) by\n          (apply (E.eval_ctx₀ E.phole); try refine (E.eval_case_inr _); simpl; intuition).\n      assert (eun : E.evaln (E.caseof (E.inr vu') tu₂ tu₃) (tu₃ [beta1 vu']) 1) by (unfold E.evaln; eauto with eval).\n      destruct w'; try apply termrel_zero.\n      refine (termrel_antired w' esn eun _ _ _); crush.\n  Qed.\n\n  Lemma termreli₀_caseof {d dfc w τ τ₁ τ₂ vs₁ ts₂ ts₃ vu₁ tu₂ tu₃} :\n    ValidPTy τ₁ -> ValidPTy τ₂ ->\n    valrel d (S w) (ptsum τ₁ τ₂) vs₁ vu₁ →\n    (∀ vs₁ vu₁, valrel d w τ₁ vs₁ vu₁ → termreli₀ d dfc (S w) τ (ts₂ [beta1 vs₁]) (tu₂ [ beta1 vu₁])) →\n    (∀ vs₂ vu₂, valrel d w τ₂ vs₂ vu₂ → termreli₀ d dfc (S w) τ (ts₃ [beta1 vs₂]) (tu₃ [ beta1 vu₂])) →\n    termreli₀ d dfc (S w) τ (I.caseof vs₁ ts₂ ts₃) (E.caseof vu₁ tu₂ tu₃).\n  Proof.\n    intros vτ₁ vτ₂ vr₁ tr₂ tr₃.\n\n    (* then evaluate the caseof *)\n    rewrite -> valrel_fixp in vr₁.\n    destruct vr₁ as (ot & ? & <- & _ & hyp); subst; cbn in hyp.\n    apply OfType_inversion_ptsum in ot; eauto.\n    destruct ot as (vs' & vu' & [(? & ? & ot)|[(? & ?)|[(? & ?)|(? & ? & ot)]]]);\n      subst; cbn in *; try contradiction;\n      destruct (OfType_implies_Value ot) as [vvs vvu]; clear ot.\n    - assert (I.eval (I.caseof (I.inl vs') ts₂ ts₃) (ts₂ [beta1 vs'])) by\n          (apply (I.eval_ctx₀ I.phole); try refine (I.eval_case_inl _); simpl; intuition).\n      assert (esn : clos_refl_trans_1n I.Tm I.eval (I.caseof (I.inl vs') ts₂ ts₃) (ts₂ [beta1 vs'])) by (eauto with eval).\n      assert (E.eval (E.caseof (E.inl vu') tu₂ tu₃) (tu₂ [beta1 vu'])) by\n          (apply (E.eval_ctx₀ E.phole); try refine (E.eval_case_inl _); simpl; intuition).\n      assert (eun : E.evalStar (E.caseof (E.inl vu') tu₂ tu₃) (tu₂ [beta1 vu'])) by (unfold E.evalStar; eauto with eval).\n      refine (termreli₀_antired_star esn eun _); crush.\n    - assert (I.eval (I.caseof (I.inr vs') ts₂ ts₃) (ts₃ [beta1 vs'])) by\n          (apply (I.eval_ctx₀ I.phole); try refine (I.eval_case_inr _); simpl; intuition).\n      assert (esn : clos_refl_trans_1n I.Tm I.eval (I.caseof (I.inr vs') ts₂ ts₃) (ts₃ [beta1 vs'])) by (eauto with eval).\n      assert (E.eval (E.caseof (E.inr vu') tu₂ tu₃) (tu₃ [beta1 vu'])) by\n          (apply (E.eval_ctx₀ E.phole); try refine (E.eval_case_inr _); simpl; intuition).\n      assert (eun : E.evalStar (E.caseof (E.inr vu') tu₂ tu₃) (tu₃ [beta1 vu'])) by (unfold E.evalStar; eauto with eval).\n      refine (termreli₀_antired_star esn eun _); crush.\n  Qed.\n\n  (* Seq *)\n  Lemma termrel_seq {d w τ ts₁ ts₂ tu₁ tu₂} :\n    ValidPTy τ ->\n    termrel d w ptunit ts₁ tu₁ →\n    (∀ w', w' ≤ w → termrel d w' τ ts₂ tu₂) →\n    termrel d w τ (I.seq ts₁ ts₂) (E.seq tu₁ tu₂).\n  Proof.\n    intros vτ tr₁ tr₂.\n\n    (* first evaluate ts₁ and tu₁ *)\n    change (I.seq _ _) with (I.pctx_app ts₁ (I.pseq₁ I.phole ts₂)).\n    change (E.seq _ _) with (E.pctx_app tu₁ (E.pseq₁ E.phole tu₂)).\n    refine (termrel_ectx _ _ tr₁ _); crush.\n\n    (* then reduce to ts₂ and tu₂ *)\n    rewrite -> valrel_fixp in H.\n    destruct H as (ot & ? & <- & _ & eq₁ & eq₂); subst.\n    assert (I.eval (I.seq I.unit ts₂) ts₂) by\n        (apply (I.eval_ctx₀ I.phole); try refine (I.eval_seq_next _); simpl; intuition).\n    assert (esn : I.evaln (I.seq I.unit ts₂) ts₂ 1) by (unfold I.evaln; eauto with eval).\n    assert (E.eval (E.seq E.unit tu₂) tu₂) by\n        (apply (E.eval_ctx₀ E.phole); try refine (E.eval_seq_next _); simpl; intuition).\n    assert (eun : E.evaln (E.seq E.unit tu₂) tu₂ 1) by (unfold E.evaln; eauto with eval).\n\n    (* assert (∀ Cu, E.ECtx Cu → E.eval (E.pctx_app (E.seq E.unit tu₂) Cu) (E.pctx_app tu₂ Cu)) by  *)\n    (*     (intros Cu eCu; apply (E.eval_ctx₀ Cu); try refine (E.eval_seq_next _); simpl; intuition). *)\n    (* assert (eun : ∀ Cu, E.ECtx Cu → E.evaln (E.pctx_app (E.seq E.unit tu₂) Cu) (E.pctx_app tu₂ Cu) 1) by eauto using E.evaln. *)\n\n    (* attempt at using evalMax instead of doing manual labor *)\n    (* pose (e := evalMax 2 (E.seq E.unit (var 0)) nil (idm UTm · tu₂) I). *)\n\n    refine (termrel_antired w' esn eun _ _ _); try lia.\n\n    (* conclude *)\n    apply tr₂; intuition.\n  Qed.\n\n  (* unfold_ *)\n  Lemma termrel_unfold_ {d w τ ts tu} :\n    ValidPTy (ptrec τ) ->\n    termrel d w (ptrec τ) ts tu →\n    termrel d w (τ [beta1 (ptrec τ)]) (unfold_ ts) tu.\n  Proof.\n    intros vτ tr.\n\n    (* first evaluate the two terms *)\n    change (I.unfold_ ts) with (I.pctx_app ts (I.punfold I.phole)).\n    change tu with (E.pctx_app tu E.phole).\n    refine (termrel_ectx _ _ tr _); crush.\n\n    (* then evaluate the unfold_ *)\n    rewrite ->valrel_fixp in H.\n    destruct H as (ot & ? & (vs2 & -> & eqfolds) & vvs2 & vr); subst.\n    change (pUnfoldn (LMC_pty (ptrec τ)) (ptrec τ)) with (pUnfoldn (LMC_pty τ) (τ [ beta1 (ptrec τ )])) in *.\n\n    assert (I.eval (I.unfold_ (I.fold_ vs2)) vs2) as eval_fold.\n    { apply (I.eval_ctx₀ I.phole); [|now cbn].\n      eapply I.eval_fold_unfold.\n      simpl; intuition.\n    }\n    eapply (termrel_antired_eval_left eval_fold).\n\n    apply valrel_in_termrel.\n    rewrite ->valrel_fixp.\n    split.\n    - crush.\n    - eexists x.\n      replace (LMC_pty τ[beta1 (ptrec τ)]) with (LMC_pty τ) in *.\n      split; [assumption|].\n      split; [now cbn in vvs2|].\n      exact vr.\n      symmetry.\n      refine (LMC_pUnfoldOnce (ptrec τ) _ _).\n      now constructor.\n      cbn; now lia.\n  Qed.\n\n  (* fold_ *)\n  Lemma valrel_fold_ {d w τ vs vu} :\n    ValidPTy (ptrec τ) ->\n    valrel d w (τ [beta1 (ptrec τ)]) vs vu →\n    valrel d w (ptrec τ) (fold_ vs) vu.\n  Proof.\n    intros vμτ vvs.\n    rewrite valrel_fixp.\n    split.\n    - crush.\n    - rewrite valrel_fixp in vvs.\n      destruct vvs as ( tvs & vs' & unfolds & vvs & rel).\n      destruct vμτ as (wsμτ & cμτ).\n      assert (LMC_pty τ [beta1 (ptrec τ)] = LMC_pty τ) as eq.\n      { refine (LMC_pUnfoldOnce (ptrec τ) cμτ _); cbn; lia. }\n      rewrite eq in unfolds.\n      exists vs'.\n      split; [exists vs; intuition|].\n      split; crush.\n      now rewrite eq in rel.\n  Qed.\n\n  Lemma termrel_fold_ {d w τ ts tu} :\n    ValidPTy (ptrec τ) ->\n    termrel d w (τ [beta1 (ptrec τ)]) ts tu →\n    termrel d w (ptrec τ) (fold_ ts) tu.\n  Proof.\n    intros vτ tr.\n\n    (* first evaluate the two terms *)\n    change (I.fold_ ts) with (I.pctx_app ts (I.pfold I.phole)).\n    change tu with (E.pctx_app tu E.phole).\n    refine (termrel_ectx _ _ tr _); crush.\n\n    apply valrel_in_termrel.\n    eapply valrel_fold_; crush.\n  Qed.\n\nEnd TermRelation.\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/LogRelIE/LemmasIntro.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.26670399308765474}}
{"text": "\n\nUniverse i j.\n\nGoal False.\nProof.\n  Check Type@{i} : Type@{j}.\n  Fail constr_eq_strict Type@{i} Type@{j}.\n  assert_succeeds constr_eq Type@{i} Type@{j}. (* <- i=j is forgotten after assert_succeeds *)\n  Fail constr_eq_strict Type@{i} Type@{j}.\n\n  constr_eq Type@{i} Type@{j}. (* <- i=j is retained *)\n  constr_eq_strict Type@{i} Type@{j}.\n  Fail Check Type@{i} : Type@{j}.\n\n  Fail constr_eq Prop Set.\n  Fail constr_eq Prop Type.\n\n  Fail constr_eq_strict Type Type.\n  constr_eq Type Type.\n\n  constr_eq_strict Set Set.\n  constr_eq Set Set.\n  constr_eq Prop Prop.\n\n  let x := constr:(Type) in constr_eq_strict x x.\n  let x := constr:(Type) in constr_eq x x.\n\n  Fail lazymatch type of prod with\n       | ?A -> ?B -> _ => constr_eq_strict A B\n       end.\n  lazymatch type of prod with\n  | ?A -> ?B -> _ => constr_eq A B\n  end.\n  lazymatch type of prod with\n  | ?A -> ?B -> ?C => constr_eq A C\n  end.\n\nAbort.\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/7421.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.26670324212148805}}
{"text": "Require Import Coq.Lists.List.\n\nRequire Import MirrorCore.TypesI.\nRequire Import MirrorCore.Views.FuncView.\nRequire Import MirrorCore.Views.Ptrns.\nRequire Import MirrorCore.CTypes.CoreTypes.\nRequire Import MirrorCore.Reify.ReifyClass.\n\nRequire Import ExtLib.Core.RelDec.\nRequire Import ExtLib.Data.PList.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nInductive list_typ : nat -> Set :=\n| tList : list_typ 1.\n\nDefinition list_typ_dec {n} (a : list_typ n) : forall b, {a = b} + {a <> b} :=\n  match a as a in list_typ n\n        return forall b : list_typ n, {a = b} + {a <> b}\n  with\n  | tList =>\n    fun b =>\n      match b as b in list_typ 1 return {tList = b} + {tList <> b} with\n      | tList => left eq_refl\n      end\n  end.\n\nDefinition list_typD {n} (t : list_typ n) : type_for_arity n :=\n  match t with\n  | tList => list\n  end.\n\nSection FuncView_list_type.\n  Context {typ : Set}.\n  Context {FV : PartialView typ (list_typ 1 * typ)}.\n\n  Definition tyList t := f_insert (tList, t).\n\n  Definition ptrn_tyList {T : Type} (p : Ptrns.ptrn typ T)\n  : ptrn (list_typ 1 * typ) T :=\n    fun f U good bad => p (snd f) U good (fun x => bad f).\n\n  Global Instance ptrn_tyList_ok {T : Type} {p : ptrn typ T} {Hok : ptrn_ok p}\n  : ptrn_ok (ptrn_tyList p).\n  Proof.\n    red; intros.\n    destruct x; simpl; [destruct (Hok t)].\n    { left. destruct H; exists x. revert H. compute; intros.\n      rewrite H. reflexivity. }\n    { right; unfold Fails in *; intros; simpl;\n      unfold ptrn_tyList; rewrite H; reflexivity. }\n  Qed.\n\nEnd FuncView_list_type.\n\nSection RelDec_list_type.\n\n  Global Instance RelDec_list_typ (x : nat) : RelDec (@eq (list_typ x)) := {\n    rel_dec := fun a b =>\n                 match x with\n                 | 1 => true\n                 | _ => false\n                 end\n  }.\n\n  Definition list_typ_eq (x y : list_typ 1) : x = y :=\n    match x, y with\n    | tList, tList => eq_refl\n    end.\n\n  Global Instance RelDecOk_list_typ (x : nat) : RelDec_Correct (RelDec_list_typ x).\n  Proof.\n    split; intros.\n    destruct x; simpl in *; [inversion y|].\n    inversion x0; subst.\n    unfold rel_dec. simpl.\n    split; intros; [|reflexivity].\n    apply list_typ_eq.\n  Qed.\n\nEnd RelDec_list_type.\n\nSection TSym_list_type.\n\n  Global Instance TSym_list_typ : TSym list_typ := {\n    symbolD n := list_typD (n := n);\n    symbol_dec n := list_typ_dec (n := n)\n  }.\n\nEnd TSym_list_type.\n\nSection ListTypeReify.\n  Context {typ : Set} {FV : PartialView typ (list_typ 1 * typ)}.\n\n  Definition reify_tyList : Command typ :=\n    CPattern (ls := @cons Type typ nil) (RApp (RExact (@list)) (RGet 0 RIgnore))\n             (fun (x : function (CRec 0)) => tyList x).\n\n  Definition reify_list_typ : Command typ :=\n    CFirst (reify_tyList :: nil).\n\nEnd ListTypeReify.\n\nArguments reify_list_typ _ {_}.\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/CTypes/ListType.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.26670324212148805}}
{"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 sflib.\nRequire Import Axioms StdlibExt IntegersExt.\n\nRequire Import SysSem.\nRequire Import IPModel DiscreteTimeModel IntByteModel.\nRequire Import NWSysModel OSNodes OSModel.\nRequire Import ProgSem.\nRequire Import SyncSysModel.\nRequire Import CProgEventSem.\nRequire Import ProgSim.\nRequire Import RTSysEnv MWITree.\n\n(* Require Import SystemParams. *)\n(* Require Import SystemDefs ITreeSpec. *)\n(* Require Import SystemEventSem. *)\n(* Require Import main_p main_pi. *)\nRequire Import config_prm main_prm SystemProgs.\nRequire Import LinkLemmas.\n\nRequire Export CompcertLemmas.\nRequire Import CProgSimLemmas.\n\nRequire Import Arith ZArith Bool.\nRequire Import String List Lia.\n\nImport ITreeNotations.\nImport Clight Clightdefs.\n\nSet Nested Proofs Allowed.\n\nLocal Transparent Archi.ptr64.\n\nArguments Z.mul : simpl nomatch.\nArguments Z.add: simpl nomatch.\nArguments Z.sub: simpl nomatch.\n\nArguments Nat.add: simpl nomatch.\nArguments Nat.sub: simpl nomatch.\nArguments Nat.mul: simpl nomatch.\n\nArguments PTree.get : simpl nomatch.\nArguments PTree.set: simpl never.\n\nArguments firstn: simpl nomatch.\nArguments skipn: simpl nomatch.\n\n\n(* general lemmas (TODO: move) *)\n\n\n(* Local Open Scope Z. *)\n\nLocal Opaque Z.to_nat Z.of_nat Zlength.\n\nLocal Open Scope Z.\n\n\nSection INBOX.\n  Context `{SystemEnv}.\n\n  (* Definition empty_msg_entry : bool * bytes := *)\n  (*   (false, List.repeat Byte.zero msg_size). *)\n\n  (* effective size *)\n  Definition mentry_nsz: nat := max_msg_size + 1.\n  Notation mentry_sz := (Z.of_nat mentry_nsz).\n\n  Lemma mentry_sz_eq\n    : mentry_sz = msg_entry_sz (Z.of_nat msg_size_k).\n  Proof.\n    (* unfold mentry_sz, msg_entry_sz. *)\n    unfold msg_entry_sz.\n    unfold mentry_nsz. unfold max_msg_size.\n    nia.\n  Qed.\n\n  Lemma range_mentry_nsz_precise\n    : (mentry_nsz < Packet.maxlen)%nat.\n  Proof.\n    assert (mentry_nsz < max_pld_size)%nat.\n    { unfold mentry_nsz, max_pld_size. nia. }\n    pose proof packet_length_bound.\n    unfold max_pld_size, max_msg_size in *.\n    nia.\n  Qed.\n\n  Lemma range_mentry_sz_precise\n    : (0 <= mentry_sz < Z.of_nat Packet.maxlen)%Z.\n  Proof.\n    (* unfold mentry_sz. *)\n    pose proof range_mentry_nsz_precise. nia.\n  Qed.\n\n  Lemma range_mentry_nsz\n    : IntRange.sint mentry_nsz.\n  Proof.\n    pose proof range_mentry_nsz_precise.\n    pose proof range_packet_maxlen.\n    range_stac.\n  Qed.\n\n  Definition mentry_ensz: nat := (msg_size + 1).\n  Notation mentry_esz := (Z.of_nat mentry_ensz).\n\n  Lemma range_mentry_ensz\n    : (0 <= mentry_ensz <= mentry_nsz)%nat.\n  Proof.\n    unfold mentry_ensz, mentry_nsz.\n    pose proof msg_size_bound.\n    fold max_msg_size in *. nia.\n  Qed.\n\n  (* = 6 * 8 = 48 *)\n  Definition inb_nsz: nat := mentry_nsz * max_num_tasks.\n\n  Notation inb_sz := (Z.of_nat inb_nsz).\n\n  Lemma inb_sz_eq\n    : inb_sz = inbox_sz (Z.of_nat msg_size_k)\n                        (Z.of_nat max_num_tasks).\n  Proof.\n    unfold inbox_sz.\n    unfold inb_nsz.\n    rewrite <- mentry_sz_eq. nia.\n  Qed.\n\n  Lemma within_inb_nsz1\n        i\n        (VALID_TID: (i < num_tasks)%nat)\n    : (mentry_nsz * i <= inb_nsz)%nat.\n  Proof.\n    unfold inb_nsz.\n    pose proof num_tasks_bound.\n    fold num_tasks in *. nia.\n  Qed.\n\n  Lemma within_inb_nsz2\n        i ofs\n        (VALID_TID: (i < num_tasks)%nat)\n        (VALID_ENTRY_AREA: (ofs <= mentry_nsz)%nat)\n    : (mentry_nsz * i + ofs <= inb_nsz)%nat.\n  Proof.\n    unfold inb_nsz.\n    pose proof num_tasks_bound.\n    fold num_tasks in *.\n    unfold mentry_nsz in *. nia.\n  Qed.\n\n  Lemma maxlen_byte_aux\n    : (Z.of_nat Packet.maxlen * Byte.max_signed\n       < Int.max_signed)%Z.\n  Proof.\n    unfold Packet.maxlen.\n    rewrite Z2Nat.id by nia. ss.\n  Qed.\n\n  Lemma range_inb_sz_precise\n    : (inb_sz < Z.of_nat Packet.maxlen * Byte.max_signed)%Z.\n  Proof.\n    unfold inb_nsz.\n    pose proof range_max_num_tasks as R_MNT.\n    pose proof range_mentry_nsz_precise as PR_ENT.\n    pose proof maxlen_byte_aux.\n    range_stac.\n  Qed.\n\n  Lemma range_inb_nsz\n    : IntRange.sint inb_nsz.\n  Proof.\n    r.\n    pose proof range_inb_sz_precise.\n    pose proof maxlen_byte_aux.\n    range_stac.\n  Qed.\n\n  Lemma ptr_range_inb_sz\n    : (0 <= inb_sz < Ptrofs.max_unsigned)%Z.\n  Proof.\n    pose proof range_inb_nsz.\n    range_stac.\n  Qed.\n\n  Lemma ptr_range_mstore\n    : (Z.of_nat (4 + inb_nsz + inb_nsz) <= Ptrofs.max_unsigned)%Z.\n  Proof.\n    pose proof range_inb_sz_precise.\n    pose proof maxlen_byte_aux.\n    assert (4 + Int.max_signed + Int.max_signed <\n            Ptrofs.max_unsigned)%Z by ss.\n    nia.\n  Qed.\n\n  (* Definition mentry_to_bytes (ment: bool * bytes): bytes := *)\n  (*   let (rcv, cont) := ment in *)\n  (*   let b_hd := if rcv then Byte.one else Byte.zero in *)\n  (*   b_hd :: cont. *)\n\nEnd INBOX.\n\nNotation cglobvar := (globvar type).\nNotation mentry_sz := (Z.of_nat mentry_nsz).\nNotation mentry_esz := (Z.of_nat mentry_ensz).\nNotation inb_sz := (Z.of_nat inb_nsz).\n\n\nClass genv_props (ge: genv)\n      (gvar_ilist: list (ident * cglobvar))\n      (gfun_ilist: list (ident * fundef))\n      (cenv_ilist: list (ident * composite))\n  : Prop :=\n  { in_gvar_ilist: forall i gv,\n      In (i, gv) gvar_ilist -> exists b_gvar,\n        <<GVAR_SYMB: Genv.find_symbol ge i = Some b_gvar>> /\\\n        <<GVAR_VINFO: Genv.find_var_info ge b_gvar = Some gv>> ;\n\n    (* in_gvar_ids: forall i, *)\n    (*   In i gvar_ids -> exists b_gvar, *)\n    (*     Genv.find_symbol ge i = Some b_gvar; *)\n\n    in_gfun_ilist: forall i fd,\n        In (i, fd) gfun_ilist -> exists b_fdef,\n          <<FDEF_SYMB: Genv.find_symbol ge i = Some b_fdef>> /\\\n          <<FDEF_FPTR: Genv.find_funct ge (Vptr b_fdef Ptrofs.zero) = Some fd>> ;\n\n    in_cenv_ilist:\n      forall i co, In (i, co) cenv_ilist ->\n              (genv_cenv ge) ! i = Some co ;\n  }.\n\nDefinition genv_props_incl (ge: genv)\n           (gvs1 gvs2: list (ident * cglobvar))\n           (gfs1 gfs2: list (ident * fundef))\n           (cos1 cos2: list (ident * composite))\n           (GENV_P: genv_props ge gvs2 gfs2 cos2)\n           (INCL_GVS: List.incl gvs1 gvs2)\n           (INCL_GFS: List.incl gfs1 gfs2)\n           (INCL_COS: List.incl cos1 cos2)\n  : genv_props ge gvs1 gfs1 cos1.\nProof.\n  inv GENV_P.\n  econs; eauto.\nQed.\n\nLemma in_gvar_ids ge gvs gfs ces\n      `{genv_props ge gvs gfs ces}\n      i\n      (IN: In i (map fst gvs))\n  : exists b_gvar,\n    Genv.find_symbol ge i = Some b_gvar.\nProof.\n  cut (exists gv, In (i, gv) gvs).\n  { clear IN. i. des.\n    hexploit in_gvar_ilist; eauto.\n    i. des. eauto.\n  }\n\n  ss. eapply Coqlib.list_in_map_inv in IN.\n  des.\n  destruct x; subst. ss. eauto.\nQed.\n\nArguments in_gvar_ids {ge gvs gfs ces _} i.\n\n\n\n(* tactics *)\n\nLtac red_idx idx' :=\n  match goal with\n  | |- paco3 (_sim_itree ?p) _ _ _ _ =>\n    eapply (sim_itree_red_idx p) with (idx_small:= idx');\n    [nia|]\n  end.\n\n\nLtac fold_cenv :=\n  match goal with\n  | |- context[(prog_comp_env ?p)] =>\n    change (prog_comp_env p) with\n        (genv_cenv (globalenv p))\n  end.\n\nLtac sIn :=\n  s;\n  match goal with\n  | |- In _ _ => eauto\n  | |- (_ = _ \\/ _) =>\n    try (left; eauto; fail);\n    right; sIn\n  | |- _ => ss; fail\n  end.\n\nLtac solve_norepet :=\n  match goal with\n  | |- Coqlib.list_norepet ?l =>\n    let x := eval simpl in (Coqlib.list_norepet_dec ident_eq l) in\n        match x with\n        | left ?P => exact P\n        | _ => fail\n        end\n  end.\n\nLtac solve_disjoint :=\n  try by (clear;\n          r; s;\n          let X := fresh \"X\" in\n          let Y := fresh \"Y\" in\n          intros ? ? X Y;\n          des; subst; ss).\n\n  (* match goal with *)\n  (* | |- Coqlib.list_disjoint ?l1 ?l2 => *)\n  (*   let x := eval simpl in (Coqlib.list_disjoint_dec ident_eq l1 l2) in *)\n  (*       match x with *)\n  (*       | left ?P => exact P *)\n  (*       | _ => fail *)\n  (*       end *)\n  (* end. *)\n\n\nLtac eval_comput1 :=\n  match goal with\n  | |- eval_expr _ _ _ _ _ _ =>\n    apply eval_expr_comput\n  | |- eval_lvalue _ _ _ _ _ _ _ =>\n    apply eval_lvalue_comput\n  | |- eval_exprlist _ _ _ _ _ _ _ =>\n    apply eval_exprlist_comput\n  | |- assign_loc _ _ _ _ _ _ _ =>\n    apply assign_loc_comput\n  | |- Cop.sem_add _ _ _ _ _ _ = _ =>\n    unfold Cop.sem_add\n  | |- Cop.sem_cmp _ _ _ _ _ _  = _ =>\n    unfold Cop.sem_cmp\n  | |- Cop.sem_cast _ _ _ _ = _ =>\n    unfold Cop.sem_cast\n  | |- Cop.sem_binarith _ _ _ _ _ _ _ _ _ = _ =>\n    unfold Cop.sem_binarith\n  | |- context[ (?x ! ?id)] =>\n    match type of x with\n    | composite_env =>\n      fold_cenv;\n      erewrite (in_cenv_ilist id) by sIn\n    | _ =>\n      match goal with\n      | H: ptree_equiv ?x _ |- _ => rewrite H\n      end\n    end\n  end.\n\nLtac eval_comput := repeat (eval_comput1; cbn).\n\n\nLtac pre_start_func :=\n  match goal with\n  | H: genv_props ?ge _ _ _ |-\n    context[ Callstate (Internal ?f) _ _ ?m0 ] =>\n    assert (ALLOC_STACK: exists e m1 es blks_env,\n               alloc_variables ge empty_env m0\n                               (fn_vars f) e m1 /\\\n               env_equiv e es /\\\n               blocks_of_env ge e = blks_env)\n  end.\n\n\nLtac start_func :=\n  match goal with\n  | H: genv_props ?ge _ _ _ |-\n    paco3 _ _ _ _ (Callstate (Internal ?f) ?args ?k ?m) =>\n    hexploit (clight_function_entry ge f args k m)\n  end;\n  [solve_norepet | solve_norepet | solve_norepet\n   | solve_disjoint | eauto | ss | i; des ].\n\n(* Omit 2nd stmt *)\nNotation SeqAbbr s := (Ssequence s _).\n\n\nLtac simpl_idx :=\n  repeat\n    (first [rewrite <- Nat.sub_add_distr by nia |\n            rewrite <- Nat.add_sub_assoc by nia]; ss).\n\nLtac fw :=\n  eapply sim_itree_clight_silent;\n  [nia| simpl in *; econs; simpl in *; eauto; try by econs |\n   left; simpl_idx; simpl in *].\n\nLtac fw_tau idx :=\n  eapply sim_itree_clight_silent_tau with (idx_n:=idx);\n  [simpl in *; econs; simpl in *; eauto; try by econs | ss | left];\n  simpl_idx; s.\n\nLtac fw_r :=\n  eapply sim_itree_clight_silent;\n  [nia| simpl in *; econs; simpl in *; eauto; try by econs |\n   right; simpl_idx; simpl in *].\n\nLtac upd_lenv :=\n  match goal with\n  | H: lenv_equiv ?le_c _ |-\n    context[State _ _ _ _ (PTree.set ?i ?v ?le_c) _] =>\n    let le_p := fresh \"le_p\" in\n    let LE := fresh \"LE\" in\n    rename le_c into le_p;\n    remember (PTree.set i v le_p) as le_c eqn: LE;\n    eapply update_lenv_equiv in H;\n    try (apply LE || reflexivity);\n    clear dependent le_p;\n    (* simpl in H *)\n    cbn in H\n  end.\n\nLtac unf_resum :=\n  unfold resum, ReSum_id, id_, Id_IFun in *.\n\nLtac step_fptr_tac :=\n  match goal with\n  | |- context [Evar ?fid] =>\n    hexploit (in_gfun_ilist fid); [sIn|]; [];\n    intros (b_fdef & FDEF_SYMB & FDEF_FPTR); des;\n    econs; [ss| eval_comput; try rewrite FDEF_SYMB; ss | eval_comput; ss | eauto | ss]\n  end.\n\n\n(**)\n\nSection COMPOSITES.\n  Context `{SystemEnv}.\n\n  Program Definition co_pals_msg_t: composite :=\n    {|\n    co_su := Struct;\n    co_members := [(_period_base_time, Tlong Unsigned {| attr_volatile := false; attr_alignas := None |});\n                  (_sender, Tint I8 Signed {| attr_volatile := false; attr_alignas := None |});\n                  (_content,\n                   Tarray (Tint I8 Signed {| attr_volatile := false; attr_alignas := None |}) (Z.of_nat max_msg_size)\n                          {| attr_volatile := false; attr_alignas := None |})];\n    co_attr := {| attr_volatile := false; attr_alignas := None |};\n    co_sizeof := Z.of_nat max_pld_size ; (* 16 *)\n    co_alignof := 8;\n    co_rank := 1;\n    co_sizeof_pos := _ ;\n    co_sizeof_alignof := _ ;\n    |}.\n  Next Obligation.\n    unfold max_pld_size. nia.\n  Qed.\n  Next Obligation.\n    exists 3%nat. ss.\n  Qed.\n  Next Obligation.\n    unfold max_pld_size. unfold max_msg_size.\n    replace (Z.of_nat (msg_size_k * 8 + 7 + 9)) with\n        (Z.of_nat msg_size_k * 8 + 16)%Z by nia.\n    solve_divide.\n  Qed.\n\n  Program Definition co_inbox_t: composite :=\n    {|\n    co_su := Struct;\n    co_members := [(_entry,\n                    Tarray (Tstruct _msg_entry_t {| attr_volatile := false; attr_alignas := None |})\n                           (Z.of_nat max_num_tasks)\n                           {| attr_volatile := false; attr_alignas := None |})];\n    co_attr := {| attr_volatile := false; attr_alignas := None |};\n    co_sizeof := Z.of_nat inb_nsz;\n    co_alignof := 1;\n    co_rank := 3;\n    co_sizeof_pos := _ ;\n    co_alignof_two_p := _;\n    |}.\n  Next Obligation.\n    pose proof range_inb_sz_precise. nia.\n  Qed.\n  Next Obligation.\n    exists O. ss.\n  Qed.\n  Next Obligation.\n    solve_divide.\n  Qed.\n\n  Program Definition co_msg_entry_t: composite :=\n    {|\n    co_su := Struct;\n    co_members := [(_received, Tint I8 Signed {| attr_volatile := false; attr_alignas := None |});\n                  (_content,\n                   Tarray (Tint I8 Signed {| attr_volatile := false; attr_alignas := None |})\n                          (Z.of_nat max_msg_size)\n                          {| attr_volatile := false; attr_alignas := None |})];\n    co_attr := {| attr_volatile := false; attr_alignas := None |};\n    co_sizeof := Z.of_nat mentry_nsz;\n    co_alignof := 1;\n    co_rank := 1;\n    co_sizeof_pos := _ ;\n    co_alignof_two_p := _ ;\n    |}.\n  Next Obligation.\n    unfold mentry_nsz. nia.\n  Qed.\n  Next Obligation.\n    exists O. ss.\n  Qed.\n  Next Obligation.\n    solve_divide.\n  Qed.\n\n  Program Definition co_msg_store_t: composite :=\n    {|\n    co_su := Struct;\n    co_members := [(_cur_idx, Tint I32 Signed {| attr_volatile := false; attr_alignas := None |});\n                  (_inbox,\n                   Tarray (Tstruct _inbox_t {| attr_volatile := false; attr_alignas := None |}) 2\n                          {| attr_volatile := false; attr_alignas := None |})];\n    co_attr := {| attr_volatile := false; attr_alignas := None |};\n    co_sizeof := 4 + 2 * (Z.of_nat inb_nsz);\n    co_alignof := 4;\n    co_rank := 5;\n    co_sizeof_pos := _ ;\n    co_alignof_two_p := _ ;\n    co_sizeof_alignof := _ ;\n    |}.\n  Next Obligation.\n    nia.\n  Qed.\n  Next Obligation.\n    exists 2%nat; ss.\n  Qed.\n  Next Obligation.\n    unfold inb_nsz.\n    rewrite Nat2Z.inj_mul.\n    rewrite mentry_sz_eq.\n    unfold msg_entry_sz.\n    solve_divide.\n  Qed.\n\nEnd COMPOSITES.\n\n\nDefinition main_const_ids: list ident :=\n  [_TASK_ID; _PALS_PERIOD; _MAX_CSKEW; _MAX_NWDELAY;\n  _NUM_TASKS; _NUM_MCASTS; _MSG_SIZE;\n  _PORT; _IP_ADDR; _MCAST_MEMBER].\n\nDefinition main_gvar_ids: list ident :=\n  [_TASK_ID; _PALS_PERIOD; _MAX_CSKEW; _MAX_NWDELAY;\n  _NUM_TASKS; _NUM_MCASTS; _MSG_SIZE;\n  _PORT; _IP_ADDR; _MCAST_MEMBER;\n  _send_buf; _mstore; _send_hist; _txs; _rxs].\n\nDefinition main_gfun_ids: list ident :=\n  [ _get_cur_inbox; _get_nxt_inbox; _msg_copy; _check_send_hist;\n  _reset_send_hist; _pals_send; _get_base_time; _mcast_join;\n  _insert_msg; _fetch_msgs; _init_inbox; _switch_inbox;\n  _run_task; _main;\n  _pals_current_time; _pals_init_timer;  _pals_wait_timer;\n  _pals_socket;  _pals_bind;  _pals_mcast_join;  _pals_sendto;\n  _pals_recvfrom].\n\nDefinition main_cenv_ids: list ident :=\n  [_pals_msg_t; _msg_entry_t; _inbox_t; _msg_store_t].\n\nDefinition app_unch_gvar_ids: list ident :=\n  [_TASK_ID; _PALS_PERIOD; _MAX_CSKEW; _MAX_NWDELAY;\n  _NUM_TASKS; _NUM_MCASTS; _MSG_SIZE;\n  _PORT; _IP_ADDR; _MCAST_MEMBER;\n  _mstore; _txs; _rxs].\n\n\nDefinition v_TASK_ID_p (tid_z: Z) :=\n  {| gvar_info := tschar;\n     gvar_init := [Init_int8 (Int.repr tid_z)];\n     gvar_readonly := true;\n     gvar_volatile := false |}.\n\nDefinition main_gvar_ilist `{SystemEnv} (tid: nat)\n  : list (ident * cglobvar) :=\n  [(_TASK_ID, v_TASK_ID_p (Z.of_nat tid));\n  (_PALS_PERIOD, config_prm.v_PALS_PERIOD (Z.of_nat period));\n  (_MAX_CSKEW, config_prm.v_MAX_CSKEW (Z.of_nat max_clock_skew));\n  (_MAX_NWDELAY, config_prm.v_MAX_NWDELAY (Z.of_nat max_nw_delay));\n  (_NUM_TASKS, config_prm.v_NUM_TASKS (Z.of_nat num_tasks));\n  (_NUM_MCASTS, config_prm.v_NUM_MCASTS (Z.of_nat num_mcasts));\n  (_MSG_SIZE, config_prm.v_MSG_SIZE (Z.of_nat msg_size));\n\n  (_PORT, config_prm.v_PORT (Z.of_nat port));\n  (_IP_ADDR, config_prm.v_IP_ADDR\n               (Z.of_nat max_num_tasks)\n               (Z.of_nat max_num_mcasts)\n               (task_ips_brep ++ map fst mcasts)) ;\n  (_MCAST_MEMBER, config_prm.v_MCAST_MEMBER\n                    (Z.of_nat max_num_tasks)\n                    (Z.of_nat max_num_mcasts)\n                    mcast_memflags) ;\n\n  (_send_buf, main_prm.v_send_buf (Z.of_nat msg_size_k));\n  (_mstore, main_prm.v_mstore (Z.of_nat msg_size_k)\n                              (Z.of_nat max_num_tasks));\n  (_send_hist, main_prm.v_send_hist (Z.of_nat max_num_tasks));\n  (_txs, main_prm.v_txs);\n  (_rxs, main_prm.v_rxs)].\n\nDefinition main_cenv_ilist `{SystemEnv}\n  : list (ident * composite) :=\n  [(_pals_msg_t, co_pals_msg_t);\n  (_msg_entry_t, co_msg_entry_t);\n  (_inbox_t, co_inbox_t);\n  (_msg_store_t, co_msg_store_t)].\n\nDefinition main_gfun_ilist `{SystemEnv}\n  : list (ident * fundef) :=\n  [ (_get_cur_inbox, Internal f_get_cur_inbox);\n  (_get_nxt_inbox, Internal f_get_nxt_inbox);\n  (_msg_copy, Internal f_msg_copy);\n  (_check_send_hist, Internal (f_check_send_hist\n                                 (Z.of_nat max_num_tasks)\n                                 (Z.of_nat max_num_mcasts)));\n  (_reset_send_hist, Internal (f_reset_send_hist (Z.of_nat max_num_tasks)));\n  (_pals_send, Internal (f_pals_send (Z.of_nat msg_size_k)\n                                     (Z.of_nat max_num_tasks)\n                                     (Z.of_nat max_num_mcasts)));\n  (_get_base_time, Internal f_get_base_time);\n  (_mcast_join, Internal (f_mcast_join (Z.of_nat max_num_tasks)\n                                       (Z.of_nat max_num_mcasts)));\n  (_insert_msg, Internal (f_insert_msg (Z.of_nat msg_size_k)));\n  (_fetch_msgs, Internal (f_fetch_msgs (Z.of_nat msg_size_k)\n                                       (Z.of_nat max_num_tasks)));\n  (_init_inbox, Internal (f_init_inbox (Z.of_nat max_num_tasks)));\n  (_switch_inbox, Internal f_switch_inbox);\n  (_run_task, Internal f_run_task);\n  (_main, Internal f_main);\n\n  (_pals_current_time,\n   External get_time_ef Tnil tulong cc_default);\n  (_pals_init_timer,\n   External init_timer_ef Tnil tint cc_default);\n  (_pals_wait_timer, External wait_timer_ef\n    (Tcons tulong Tnil) tint cc_default);\n  (_pals_socket, External open_socket_ef Tnil tint cc_default);\n  (_pals_bind, External bind_socket_ef\n    (Tcons tint (Tcons tint Tnil)) tint cc_default);\n  (_pals_mcast_join, External join_socket_ef\n    (Tcons tint (Tcons (tptr tschar) Tnil)) tvoid cc_default);\n\n  (_pals_sendto,\n   External sendto_ef\n            (Tcons tint\n                   (Tcons (tptr tschar)\n                          (Tcons tint (Tcons (tptr tschar) (Tcons tint Tnil))))) tint cc_default);\n  (_pals_recvfrom,\n   External recvfrom_ef\n            (Tcons tint (Tcons (tptr tschar) (Tcons tint Tnil))) tint cc_default)\n].\n\n\nDefinition bool2memval (b: bool): memval :=\n  Byte (if b then Byte.one else Byte.zero).\n\n\nSection MATCH_MEM.\n  Local Open Scope Z.\n\n  Variable ge: genv.\n  Variable tid: nat.\n  Context `{SystemEnv}.\n  (* Context `{ genv_props *)\n  (*              ge (main_gvar_ilist tid) *)\n  (*              main_gfun_ilist main_cenv_ilist }. *)\n\n  Record mem_consts (m: mem) (tid: nat): Prop :=\n    MemConsts {\n        mem_consts_task_id:\n          forall b_tid\n            (FIND_SYMB: Genv.find_symbol\n                          ge _TASK_ID = Some b_tid),\n            Mem.load Mint8signed m b_tid 0%Z =\n            Some (Vint (IntNat.of_nat tid)) ;\n\n        mem_consts_pals_period:\n          forall b_pprd\n            (FIND_SYMB: Genv.find_symbol\n                          ge _PALS_PERIOD = Some b_pprd),\n          Mem.load Mint64 m b_pprd 0%Z =\n          Some (Vlong (IntNat.of_nat64 period)) ;\n\n        mem_consts_max_cskew:\n          forall b_sk\n            (FIND_SYMB: Genv.find_symbol\n                          ge _MAX_CSKEW = Some b_sk),\n            Mem.load Mint64 m b_sk 0%Z =\n            Some (Vlong (IntNat.of_nat64 max_clock_skew)) ;\n\n        mem_consts_max_nwdelay:\n          forall b_nd\n            (FIND_SYMB: Genv.find_symbol\n                          ge _MAX_NWDELAY = Some b_nd),\n            Mem.load Mint64 m b_nd 0%Z =\n            Some (Vlong (IntNat.of_nat64 max_nw_delay)) ;\n\n\n        mem_consts_num_tasks:\n          forall b_nt\n            (FIND_SYMB: Genv.find_symbol\n                          ge _NUM_TASKS = Some b_nt),\n            Mem.load Mint32 m b_nt 0%Z =\n            Some (Vint (IntNat.of_nat num_tasks)) ;\n\n        mem_consts_num_mcasts:\n          forall b_nmc\n            (FIND_SYMB: Genv.find_symbol\n                          ge _NUM_MCASTS = Some b_nmc),\n            Mem.load Mint32 m b_nmc 0%Z =\n            Some (Vint (IntNat.of_nat num_mcasts)) ;\n\n        mem_consts_msg_size:\n          forall b_msz\n            (FIND_SYMB: Genv.find_symbol\n                          ge _MSG_SIZE = Some b_msz),\n            Mem.load Mint32 m b_msz 0%Z =\n            Some (Vint (IntNat.of_nat msg_size)) ;\n\n        mem_consts_port:\n          forall b_pn\n            (FIND_SYMB: Genv.find_symbol\n                          ge _PORT = Some b_pn),\n            Mem.load Mint32 m b_pn 0%Z =\n            Some (Vint (IntNat.of_nat port)) ;\n\n        mem_consts_ip_addr:\n          forall b_ip_addr\n            (FIND_SYMB: Genv.find_symbol\n                          ge _IP_ADDR = Some b_ip_addr),\n\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        mem_consts_mcast_member:\n          forall b_mcm mid midx tid'\n            mip_bs mem\n            (FIND_SYMB: Genv.find_symbol\n                          ge _MCAST_MEMBER = Some b_mcm)\n            (MCAST_ID: mid = (num_tasks + midx)%nat)\n            (MCASTS_MID: nth_error mcasts midx = Some (mip_bs, mem))\n            (RANGE_TID: (tid' < num_tasks)%nat)\n          ,\n            Mem.load Mint8signed m b_mcm\n                     (Z.of_nat (max_num_tasks * midx + tid')) =\n            Some (Vint (if existsb (Nat.eqb tid') mem\n                        then Int.one else Int.zero)) ;\n      }.\n\n  Lemma mem_consts_unch\n        m m'\n        (MEM_CONSTS: mem_consts m tid)\n        (UNCH: Mem.unchanged_on\n                 (blocks_of ge main_const_ids) m m')\n    : mem_consts m' tid.\n  Proof.\n    inv MEM_CONSTS.\n    econs.\n    - i. hexploit mem_consts_task_id0; eauto.\n      intro LOAD.\n      eapply Mem.load_unchanged_on; eauto.\n      i. ss.\n      r. esplits; eauto. sIn.\n    - i. hexploit mem_consts_pals_period0; eauto.\n      intro LOAD.\n      eapply Mem.load_unchanged_on; eauto.\n      i. ss.\n      r. esplits; eauto. sIn.\n    - i. hexploit mem_consts_max_cskew0; eauto.\n      intro LOAD.\n      eapply Mem.load_unchanged_on; eauto.\n      i. ss.\n      r. esplits; eauto. sIn.\n    - i. hexploit mem_consts_max_nwdelay0; eauto.\n      intro LOAD.\n      eapply Mem.load_unchanged_on; eauto.\n      i. ss.\n      r. esplits; eauto. sIn.\n    - i. hexploit mem_consts_num_tasks0; eauto.\n      intro LOAD.\n      eapply Mem.load_unchanged_on; eauto.\n      i. ss.\n      r. esplits; eauto. sIn.\n    - i. hexploit mem_consts_num_mcasts0; eauto.\n      intro LOAD.\n      eapply Mem.load_unchanged_on; eauto.\n      i. ss.\n      r. esplits; eauto. sIn.\n    - i. hexploit mem_consts_msg_size0; eauto.\n      intro LOAD.\n      eapply Mem.load_unchanged_on; eauto.\n      i. ss.\n      r. esplits; eauto. sIn.\n    - i. hexploit mem_consts_port0; eauto.\n      intro LOAD.\n      eapply Mem.load_unchanged_on; eauto.\n      i. ss.\n      r. esplits; eauto. sIn.\n    - i. hexploit mem_consts_ip_addr0; eauto.\n      intro LOAD_FA.\n      eapply iForall_nth. i.\n      rewrite iForall_nth in LOAD_FA.\n      specialize (LOAD_FA n).\n\n      fold bytes in *.\n      destruct (nth_error (task_ips_brep ++ map fst mcasts) n); ss.\n      eapply Mem.loadbytes_unchanged_on; eauto.\n      i. ss.\n      r. esplits; eauto. sIn.\n    - i. hexploit mem_consts_mcast_member0; eauto.\n      intro LOAD.\n      eapply Mem.load_unchanged_on; eauto.\n      i. ss.\n      r. esplits; eauto. sIn.\n  Qed.\n\n  Lemma mem_consts_unch_diffblk\n        m m' b_ch\n        (MEM_CONSTS: mem_consts m tid)\n        (MEM_CHB: mem_changed_block b_ch m m')\n        (BLK_NOT_CONSTS: forall id,\n            In id main_const_ids ->\n            Genv.find_symbol ge id <> Some b_ch)\n    : mem_consts m' tid.\n  Proof.\n    eapply mem_consts_unch; eauto.\n    eapply Mem.unchanged_on_implies; eauto.\n    unfold blocks_of.\n    ii. subst. des.\n    hexploit BLK_NOT_CONSTS; eauto.\n  Qed.\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  Record mem_sbuf_blk (m: mem) (nsytm: nat) (tid: nat) (mcont: bytes)\n         (b_sbuf: block): Prop :=\n    MemSBuf {\n        mem_sbuf_next_sync_time:\n            Mem.loadbytes m b_sbuf 0 8 =\n            Some (inj_bytes (IntByte.to_bytes64 (IntNat.of_nat64 nsytm))) ;\n\n        mem_sbuf_task_id:\n          Mem.load Mint8signed m b_sbuf 8 =\n          Some (Vint (IntNat.of_nat tid)) ;\n\n        mem_sbuf_content:\n          Mem.loadbytes m b_sbuf 9 (Z.of_nat msg_size) =\n          Some (inj_bytes mcont) ;\n\n        mem_sbuf_writable:\n          Mem.range_perm m b_sbuf 0 (Z.of_nat pld_size)\n                         Cur Writable;\n      }.\n\n  Lemma mem_sbuf_next_sync_time'\n        (m: mem) (nsytm: nat) (tid': nat) (mcont: bytes)\n        (b_sbuf: block)\n        (MEM_SBUF_BLK: mem_sbuf_blk m nsytm tid' mcont b_sbuf)\n    : Mem.load Mint64 m b_sbuf 0 =\n      Some (Vlong (IntNat.of_nat64 nsytm)).\n  Proof.\n    erewrite Mem.loadbytes_load;\n      try (eapply mem_sbuf_next_sync_time; eauto).\n    2: { solve_divide. }\n    f_equal.\n    unfold decode_val.\n    rewrite proj_inj_bytes. f_equal.\n\n    unfold IntByte.to_bytes64.\n    rewrite decode_encode_int_8. ss.\n  Qed.\n\n  Definition mem_sbuf (m: mem)\n             (nsytm: nat) (tid: nat) (mcont: bytes): Prop :=\n    fsymb _send_buf (mem_sbuf_blk m nsytm tid mcont).\n\n  Lemma mem_sbuf_unch\n        m m' nsytm mcont\n        (MEM_SBUF: mem_sbuf m nsytm tid mcont)\n        (UNCH: Mem.unchanged_on\n                 (fun b _ => Genv.find_symbol ge _send_buf = Some b)\n                 m m')\n    : mem_sbuf m' nsytm tid mcont.\n  Proof.\n    ii. rr in MEM_SBUF.\n    hexploit MEM_SBUF; eauto. intro MEM_SBUF_BLK.\n    clear MEM_SBUF.\n\n    inv MEM_SBUF_BLK.\n    econs.\n    - eapply Mem.loadbytes_unchanged_on; eauto.\n    - eapply Mem.load_unchanged_on; eauto.\n    - eapply Mem.loadbytes_unchanged_on; eauto.\n    - ii. eapply Mem.perm_unchanged_on; eauto.\n  Qed.\n\n  Lemma mem_sbuf_unch_diffblk\n        b_ch m m' nsytm mcont\n        (MEM_SBUF: mem_sbuf m nsytm tid mcont)\n        (MEM_CHB: mem_changed_block b_ch m m')\n        (CHB_NOT_SBUF: Genv.find_symbol ge _send_buf <> Some b_ch)\n    : mem_sbuf m' nsytm tid mcont.\n  Proof.\n    eapply mem_sbuf_unch; eauto.\n    eapply Mem.unchanged_on_implies; eauto.\n    unfold blocks_of.\n    ii. subst. eauto.\n  Qed.\n\n  Definition Mem_msg_entry (mem: Mem.mem)\n             (b: block) (ofs: Z)\n             (idx: nat) (ment: bytes?): Prop :=\n    match ment with\n    | None =>\n      Mem.loadbytes mem b (ofs + Z.of_nat (mentry_nsz * idx)) 1 =\n      Some ([Byte Byte.zero])\n    | Some cont =>\n      Mem.loadbytes mem b (ofs + Z.of_nat (mentry_nsz * idx)) mentry_esz =\n      Some (inj_bytes (Byte.one :: cont))\n    end.\n\n  Definition Mem_inbox (mem: Mem.mem)\n             (b: block) (ofs: Z)\n             (ments: list (bytes?)): Prop :=\n    <<MSG_ENTRIES: iForall (Mem_msg_entry mem b ofs) 0 ments>> /\\\n    <<NUM_ENTRIES: length ments = num_tasks>> /\\\n                 (* ments (incr_nlist 0 num_tasks) /\\ *)\n    <<INBOX_PERM: Mem.range_perm mem b ofs (ofs + inb_sz)\n                                 Cur Writable>>.\n  (* (align_chunk Mint8signed | ofs)%Z. *)\n\n  Record mem_mstore_blk\n         (m: mem) (cflg: bool)\n         (ofsc ofsn: Z)\n         (inbc inbn: list (bytes?))\n         (b_mst: block): Prop :=\n    MemMStore {\n        mem_mst_curflag:\n          Mem.load Mint32 m b_mst 0 =\n          Some (Vint (if cflg then Int.one else Int.zero)) ;\n\n        mem_mst_curflag_writable:\n          Mem.range_perm m b_mst 0 4 Cur Writable;\n\n        mst_match_ofs_cur:\n          ofsc = if cflg then 4 + inb_sz else 4 ;\n        mst_match_ofs_nxt:\n          ofsn = if cflg then 4 else (4 + inb_sz)%Z ;\n\n        mem_mst_inbox_cur: Mem_inbox m b_mst ofsc inbc ;\n        mem_mst_inbox_nxt: Mem_inbox m b_mst ofsn inbn ;\n      }.\n\n\n  Lemma Mem_msg_entry_unch\n        m m' b ofs ment (i: nat)\n        (MEM_MENT: Mem_msg_entry m b ofs i ment)\n        (MEM_UNCH: Mem.unchanged_on\n                     (fun b' ofs' =>\n                        b' = b /\\\n                        (ofs + Z.of_nat (mentry_nsz * i) <= ofs' <\n                         ofs + Z.of_nat (mentry_nsz * i + mentry_nsz))%Z)\n                     m m')\n    : Mem_msg_entry m' b ofs i ment.\n  Proof.\n    rr in MEM_MENT. rr.\n    destruct ment.\n    - eapply Mem.loadbytes_unchanged_on; try apply MEM_MENT.\n      { eauto. }\n      i. ss.\n      split; ss.\n      pose proof range_mentry_ensz.\n      nia.\n    - eapply Mem.loadbytes_unchanged_on; try apply MEM_MENT.\n      { eauto. }\n      i. ss.\n      split; ss.\n      cut (1 <= mentry_nsz)%nat.\n      { nia. }\n      unfold mentry_nsz. nia.\n  Qed.\n\n  Lemma iForall_Mem_msg_entry_unch\n        m m' b ofs ments (i j: nat)\n        (MEM_MENT: iForall (Mem_msg_entry m b ofs) i ments)\n        (LEN_MENTS: j = length ments)\n        (MEM_UNCH: Mem.unchanged_on\n                     (fun b' ofs' =>\n                        b' = b /\\\n                        (ofs + Z.of_nat (mentry_nsz * i) <= ofs' <\n                         ofs + Z.of_nat (mentry_nsz * (i + j)))%Z)\n                     m m')\n    : iForall (Mem_msg_entry m' b ofs) i ments.\n  Proof.\n    subst j.\n    induction MEM_MENT; ss.\n    { econs. }\n\n    econs.\n    { eapply Mem_msg_entry_unch; eauto.\n      eapply Mem.unchanged_on_implies; eauto.\n      clear. intros b' ofs' [? OFS]. clarify.\n      unfold mentry_nsz in *. nia.\n    }\n\n    apply IHMEM_MENT.\n    eapply Mem.unchanged_on_implies; eauto.\n    clear. intros b' ofs' [? OFS]. clarify.\n    split; ss.\n    nia.\n  Qed.\n\n  Lemma Mem_inbox_unch\n        m m' b ofs inb\n        (MEM_INB: Mem_inbox m b ofs inb)\n        (MEM_UNCH: Mem.unchanged_on\n                     (fun b' ofs' =>\n                        b' = b /\\\n                        (ofs <= ofs' < ofs + inb_sz)%Z)\n                     m m')\n    : Mem_inbox m' b ofs inb.\n  Proof.\n    r. r in MEM_INB. des.\n    esplits; ss.\n    - eapply iForall_Mem_msg_entry_unch; eauto.\n      eapply Mem.unchanged_on_implies; eauto.\n      (* rewrite mentry_sz_eq. *)\n      rewrite NUM_ENTRIES. ss.\n      ii. des. subst.\n      split; ss.\n\n      pose proof range_mentry_sz_precise.\n      assert (0 < num_tasks)%nat by nia.\n\n      assert (exists x, num_tasks = S x).\n      { destruct num_tasks; ss.\n        - nia.\n        - esplits; eauto. }\n      des.\n\n      hexploit (within_inb_nsz2 x mentry_nsz).\n      { nia. }\n      { nia. }\n      unfold inb_nsz.\n      nia.\n    - ii. eapply Mem.perm_unchanged_on; eauto.\n      ss.\n  Qed.\n\n  Definition mem_mstore m cflg ofsc ofsn inbc inbn :=\n    fsymb _mstore (mem_mstore_blk m cflg ofsc ofsn inbc inbn).\n\n  Lemma mem_mstore_unch\n        m m' cf\n        ofsc ofsn inbc inbn\n        (MEM_MSTORE: mem_mstore m cf ofsc ofsn inbc inbn)\n        (UNCH: Mem.unchanged_on\n                 (fun b _ => Genv.find_symbol ge _mstore = Some b)\n                 m m')\n    : mem_mstore m' cf ofsc ofsn inbc inbn.\n  Proof.\n    ii. rr in MEM_MSTORE.\n    hexploit MEM_MSTORE; eauto. intro MEM_MSTORE_BLK.\n    clear MEM_MSTORE.\n\n    inv MEM_MSTORE_BLK.\n    econs.\n    - eapply Mem.load_unchanged_on; eauto.\n    - ii. eapply Mem.perm_unchanged_on; eauto.\n    - ss.\n    - ss.\n    - eapply Mem_inbox_unch; eauto.\n      eapply Mem.unchanged_on_implies; eauto.\n      ii. ss. des. subst. ss.\n    - eapply Mem_inbox_unch; eauto.\n      eapply Mem.unchanged_on_implies; eauto.\n      ii. ss. des. subst. ss.\n  Qed.\n\n  Lemma mem_mstore_unch_diffblk\n        b_ch m m' cf\n        ofsc ofsn inbc inbn\n        (MEM_SBUF: mem_mstore m cf ofsc ofsn inbc inbn)\n        (MEM_CHB: mem_changed_block b_ch m m')\n        (CHB_NOT_MST: Genv.find_symbol ge _mstore <> Some b_ch)\n    : mem_mstore m' cf ofsc ofsn inbc inbn.\n  Proof.\n    eapply mem_mstore_unch; eauto.\n    eapply Mem.unchanged_on_implies; eauto.\n    unfold blocks_of.\n    ii. subst. eauto.\n  Qed.\n\n\n  Record mem_sh_blk (m: mem) (sh: list bool) (b_sh: block): Prop :=\n    MemSendHist {\n        (* mem_sh_length: length sh = num_tasks ; *)\n        mem_sh_loadbytes:\n          Mem.loadbytes m b_sh 0 (Z.of_nat num_tasks) =\n          Some (map bool2memval sh);\n\n        mem_sh_writable:\n          Mem.range_perm m b_sh 0 (Z.of_nat num_tasks) Cur Writable ;\n      }.\n\n  Lemma mem_sh_blk_length\n        m sh b\n        (MEM_SH_BLK: mem_sh_blk m sh b)\n    : length sh = num_tasks.\n  Proof.\n    inv MEM_SH_BLK.\n    hexploit Mem.loadbytes_length; eauto.\n    rewrite map_length. rewrite Nat2Z.id. ss.\n  Qed.\n\n  Definition mem_sh m (sh: list bool): Prop :=\n    fsymb _send_hist (mem_sh_blk m sh).\n\n  Lemma mem_sh_unch\n        m m' sh\n        (MEM_SH: mem_sh m sh)\n        (UNCH: Mem.unchanged_on\n                 (fun b _ => Genv.find_symbol ge _send_hist = Some b)\n                 m m')\n    : mem_sh m' sh.\n  Proof.\n    ii. rr in MEM_SH.\n    hexploit MEM_SH; eauto. intro MEM_SH_BLK.\n    clear MEM_SH.\n\n    inv MEM_SH_BLK.\n    econs.\n    - eapply Mem.loadbytes_unchanged_on; eauto.\n    - ii. eapply Mem.perm_unchanged_on; eauto.\n  Qed.\n\n  Lemma mem_sh_unch_diffblk\n        b_sh m m' sh\n        (MEM_SH: mem_sh m sh)\n        (MEM_CHB: mem_changed_block b_sh m m')\n        (CHB_DIFF: Genv.find_symbol ge _send_hist <> Some b_sh)\n    : mem_sh m' sh.\n  Proof.\n    eapply mem_sh_unch; eauto.\n    eapply Mem.unchanged_on_implies; eauto.\n    unfold blocks_of.\n    ii. subst. eauto.\n  Qed.\n\n\n  Record mem_skt_blk (m: mem) (sid: nat) (b_sid: block): Prop :=\n    MemSocket {\n        mem_skt_id:\n          Mem.load Mint32 m b_sid 0 =\n          Some (Vint (IntNat.of_nat sid));\n        mem_skt_writable:\n          Mem.range_perm m b_sid 0 4 Cur Writable ;\n      }.\n\n  Definition mem_txs m txs :=\n    fsymb _txs (mem_skt_blk m txs).\n\n  Definition mem_rxs m rxs :=\n    fsymb _rxs (mem_skt_blk m rxs).\n\n  Lemma mem_txs_unch\n        m m' txs\n        (MEM_SKT: mem_txs m txs)\n        (UNCH: Mem.unchanged_on\n                 (fun b _ => Genv.find_symbol ge _txs = Some b)\n                 m m')\n    : mem_txs m' txs.\n  Proof.\n    ii. rr in MEM_SKT.\n    hexploit MEM_SKT; eauto.\n    clear MEM_SKT. intro MEM_SKT_BLK.\n    inv MEM_SKT_BLK.\n    econs.\n    - eapply Mem.load_unchanged_on; eauto.\n    - ii. eapply Mem.perm_unchanged_on; eauto.\n  Qed.\n\n  Lemma mem_txs_unch_diffblk\n        b_ch m m' txs\n        (MEM_SBUF: mem_txs m txs)\n        (MEM_CHB: mem_changed_block b_ch m m')\n        (CHB_NOT_MST: Genv.find_symbol ge _txs <> Some b_ch)\n    : mem_txs m' txs.\n  Proof.\n    eapply mem_txs_unch; eauto.\n    eapply Mem.unchanged_on_implies; eauto.\n    unfold blocks_of.\n    ii. subst. eauto.\n  Qed.\n\n  Lemma mem_rxs_unch\n        m m' rxs\n        (MEM_SKT: mem_rxs m rxs)\n        (UNCH: Mem.unchanged_on\n                 (fun b _ => Genv.find_symbol ge _rxs = Some b)\n                 m m')\n    : mem_rxs m' rxs.\n  Proof.\n    ii. rr in MEM_SKT.\n    hexploit MEM_SKT; eauto.\n    clear MEM_SKT. intro MEM_SKT_BLK.\n    inv MEM_SKT_BLK.\n    econs.\n    - eapply Mem.load_unchanged_on; eauto.\n    - ii. eapply Mem.perm_unchanged_on; eauto.\n  Qed.\n\n  Lemma mem_rxs_unch_diffblk\n        b_ch m m' rxs\n        (MEM_SBUF: mem_rxs m rxs)\n        (MEM_CHB: mem_changed_block b_ch m m')\n        (CHB_NOT_MST: Genv.find_symbol ge _rxs <> Some b_ch)\n    : mem_rxs m' rxs.\n  Proof.\n    eapply mem_rxs_unch; eauto.\n    eapply Mem.unchanged_on_implies; eauto.\n    unfold blocks_of.\n    ii. subst. eauto.\n  Qed.\n\nEnd MATCH_MEM.\n\n\n\nLemma mem_sbuf_loadbytes `{SystemEnv}\n      m sytm tid mcont b_sbuf\n      (RANGE_SYTM: IntRange.uint64 sytm)\n      (RANGE_TID: (tid < num_tasks)%nat)\n      (MEM_SBUF: mem_sbuf_blk m sytm tid mcont b_sbuf)\n  :\n    Mem.loadbytes m b_sbuf 0%Z (Z.of_nat pld_size) =\n    Some (inj_bytes (IntByte.to_bytes64\n                       (IntNat.of_nat64 sytm) ++\n                       [Byte.repr (Z.of_nat tid)] ++ mcont)).\nProof.\n  replace (Z.of_nat pld_size) with\n      (8 + (1 + Z.of_nat msg_size)).\n  2: { unfold pld_size. nia. }\n\n  erewrite Mem.loadbytes_concat; try nia.\n  { unfold inj_bytes.\n    rewrite map_app. reflexivity. }\n  { eapply mem_sbuf_next_sync_time; eauto. }\n  s.\n  erewrite Mem.loadbytes_concat; try nia.\n  { rewrite rw_cons_app. reflexivity. }\n  { hexploit Mem.load_loadbytes.\n    { eapply mem_sbuf_task_id; eauto. }\n    i. des.\n    ss.\n    hexploit Mem.loadbytes_length; eauto. i.\n    destruct bytes as [| b []]; ss.\n    destruct b; ss.\n    hexploit (decode_byte_one_inv (Z.of_nat tid)); eauto.\n    { split.\n      - transitivity 0.\n        { eapply Z.lt_le_incl. ss. }\n        nia.\n      - cut (Z.of_nat num_tasks < Int.max_signed)%Z.\n        { nia. }\n        generalize range_num_tasks.\n        inversion 1.\n        assert (Byte.max_signed < Int.max_signed)%Z by ss.\n        nia.\n    }\n    i. subst.\n    ss.\n  }\n  apply MEM_SBUF.\nQed.\n\nLemma ip_in_mem_exists `{SystemEnv}\n      ge tid tid_r b_ips m\n      (MEM_CONSTS: mem_consts ge m tid)\n      (FSYMB_IPS: Genv.find_symbol ge _IP_ADDR =\n                  Some b_ips)\n      (TID: (tid_r < num_tasks + num_mcasts)%nat)\n  : exists ip_dest,\n    ip_in_mem ip_dest m b_ips\n              (Ptrofs.repr (16 * Z.of_nat tid_r)) /\\\n    dest_id_ip tid_r ip_dest /\\\n    IntRange.uint ip_dest.\nProof.\n  hexploit mem_consts_ip_addr; eauto.\n  intro IPS.\n  rewrite iForall_nth in IPS.\n  specialize (IPS tid_r).\n\n  assert (LEN_TIPS: length task_ips_brep = length task_ips).\n  { pose proof task_ips_convert_brep as CONV_TASK_IPS.\n    apply Forall2_length in CONV_TASK_IPS. ss. }\n\n\n  hexploit (nth_error_Some2 _ (task_ips_brep ++ map fst mcasts) tid_r).\n  { rewrite app_length.\n    rewrite map_length.\n    rewrite <- num_mcasts_eq.\n    fold bytes in *.\n    rewrite LEN_TIPS.\n    fold num_tasks. ss.\n  }\n  i. des.\n  renames e1 NTH_EX into ip_bs IP_BS.\n  rewrite IP_BS in IPS. ss.\n\n  assert (exists ip,\n             <<CONV_IP: IP.convert_brep ip_bs = Some ip>> /\\\n             <<DEST_ID_IP: dest_id_ip tid_r ip>>).\n  { destruct (lt_ge_dec tid_r (length task_ips_brep)) as [LT|GE].\n    - rewrite nth_error_app1 in IP_BS by ss.\n      pose proof task_ips_convert_brep as CONV_IPS.\n      eapply Forall2_nth1 in CONV_IPS; eauto.\n      des.\n      esplits; eauto.\n      r. unfold dest_ips.\n      rewrite nth_error_app1 by nia.\n      ss.\n\n    - rewrite nth_error_app2 in IP_BS by ss.\n      pose proof mcast_ips_convert_brep as CONV_IPS.\n      (* hexploit Forall2_length; eauto. i. *)\n\n      apply map_nth_error_iff in IP_BS. des.\n      destruct a as (ip_bs' & mbrs). ss. clarify.\n\n      eapply Forall2_nth1 in CONV_IPS; eauto.\n      des.\n      esplits; eauto.\n      r. unfold dest_ips.\n      rewrite nth_error_app2 by nia.\n      rewrite <- LEN_TIPS. ss.\n  }\n  des.\n\n  hexploit IP.valid_ip_brep_spec; eauto.\n  intros (BS_NONZERO & IP_BS_LEN & IP_SINT).\n\n  exists ip.\n  splits; ss.\n  2: { range_stac. }\n\n  econs; eauto.\n  rewrite Ptrofs.unsigned_repr.\n  2: { split; [nia|].\n       cut (Z.of_nat tid_r <= Byte.max_signed)%Z.\n       { intro TID_R.\n         transitivity (16 * Byte.max_signed).\n         { nia. }\n         eapply Z.lt_le_incl. ss.\n       }\n       pose proof range_valid_dest_ids as RANGE_D.\n       fold num_tasks num_mcasts in *.\n       range_stac.\n  }\n  replace (16 * Z.of_nat tid_r) with (Z.of_nat (tid_r * 16)) by nia.\n  rewrite IPS.\n  unfold snoc.\n  unfold inj_bytes. rewrite map_app. ss.\nQed.\n\n\nLemma Mem_msg_entry_inv2 `{SystemEnv}\n      m b ofs_inb idx ment\n      (MEM_MENT: Mem_msg_entry m b ofs_inb idx ment)\n  : <<MENT_RCV: Mem.load Mint8signed m b (ofs_inb + Z.of_nat (mentry_nsz * idx)) =\n                Some (if ment then Vtrue else Vfalse)>> /\\\n                <<MENT_CONT: forall mcont, ment = Some mcont ->\n                                      Mem.loadbytes m b (ofs_inb + Z.of_nat (mentry_nsz * idx) + 1) (Z.of_nat msg_size) =\n                                      Some (inj_bytes mcont)>>.\nProof.\n  r in MEM_MENT. ss.\n  destruct ment as [mcont|]; ss.\n  - unfold mentry_ensz in MEM_MENT.\n    replace (Z.of_nat (msg_size + 1))%nat with\n        (1 + Z.of_nat msg_size)%Z in MEM_MENT by nia.\n    rewrite rw_cons_app in MEM_MENT.\n    apply Mem.loadbytes_split in MEM_MENT; [|nia..].\n    destruct MEM_MENT as (mvs1 & mvs2 & LBS_HB1 & LBS_HB2 & BS_EQ).\n    hexploit Mem.loadbytes_length; try apply LBS_HB1.\n    intro LEN_MVS1.\n    destruct mvs1 as [| rcv_hb []]; ss.\n    clarify.\n    split; ss.\n    + r.\n      erewrite Mem.loadbytes_load; cycle 1.\n      { apply LBS_HB1. }\n      { ss. solve_divide. }\n      ss.\n    + r. intros mcont' AUX.\n      symmetry in AUX. inv AUX.\n      ss.\n  - split; ss.\n    r.\n    erewrite Mem.loadbytes_load; cycle 1.\n    { ss. apply MEM_MENT. }\n    { ss. solve_divide. }\n    ss.\nQed.\n\n\n\n(* Import AppMod. *)\n\n(* Definition progE {sysE: Type -> Type} : Type -> Type := *)\n(*   osE +' tlimE +' sysE. *)\n\n(* Notation progE sysE := (osE +' tlimE +' sysE). *)\n\nExisting Instance cprog_event_instance.\n\nClass SimApp\n      `{SystemEnv}\n      (* {sysE: Type -> Type} *)\n      (* `{@CProgSysEvent sysE} *)\n      (tid: nat)\n      (cprog: Clight.program)\n      (app_mod: @AppMod.t obsE bytes)\n  : Type :=\n  { app_gvar_ilist: list (ident * cglobvar) ;\n    app_gfun_ilist: list (ident * fundef) ;\n    app_cenv_ilist: list (ident * composite) ;\n    app_gvar_ids := map fst app_gvar_ilist ;\n    app_gfun_ids := map fst app_gfun_ilist ;\n    app_cenv_ids := map fst app_cenv_ilist ;\n\n    main_app_gvar_ids_disj:\n      Coqlib.list_disjoint main_gvar_ids app_gvar_ids ;\n    main_app_gfun_ids_disj:\n      Coqlib.list_disjoint main_gfun_ids app_gfun_ids ;\n    main_app_cenv_ids_disj:\n      Coqlib.list_disjoint main_cenv_ids app_cenv_ids ;\n\n    (* astate_t: Type ; *)\n    inv_app: genv -> AppMod.abst_state_t app_mod -> mem -> Prop ;\n\n    (* itree_app: nat -> list bytes ? -> astate_t -> *)\n    (*            itree (sysE +' bsendE) astate_t ; *)\n\n    job_func: Clight.function ;\n    job_func_type: type_of_function job_func = Tfunction (Tcons tulong (Tcons (tptr (Tstruct _inbox_t noattr)) Tnil)) tvoid cc_default ;\n    job_func_in_app_gfun_ilist:\n      In (_job, Internal job_func) app_gfun_ilist;\n\n    idx_job: nat ;\n\n    ge := globalenv cprog;\n\n    (* tid: nat ; *)\n    range_tid: (tid < num_tasks)%nat ;\n\n    (* task_id_in_app_gvar_ilist: *)\n    (*   In (_TASK_ID, v_TASK_ID_p (Z.of_nat tid)) app_gvar_ilist; *)\n\n    inv_app_dep_app_blocks:\n      forall (* ge *) ast m m'\n        (INV_APP: inv_app ge ast m)\n        (UNCH_APP: Mem.unchanged_on\n                     (blocks_of ge app_gvar_ids) m m'),\n        inv_app ge ast m' ;\n\n    inv_app_init:\n      forall m_i (INIT_MEM: Genv.init_mem cprog = Some m_i),\n      inv_app ge (AppMod.init_abst_state app_mod) m_i;\n\n    sim_job_func:\n      forall (r: nat -> itree progE unit -> Clight.state -> Prop)\n        b_mst txs\n        idx' ast ki m kp sytm\n        cflg ofsc ofsn inbc inbn\n        (mcont: bytes)\n        (CALL_CONT: is_call_cont kp)\n        (RANGE_SYTM: IntRange.uint64 sytm)\n        (RANGE_SYTM2: IntRange.uint64 (sytm + period))\n\n        (RANGE_TXS: IntRange.sint txs)\n        (INV_APP: inv_app ge ast m)\n        (FSYMB_MST: Genv.find_symbol ge _mstore = Some b_mst)\n        (MEM_CONSTS: mem_consts ge m tid)\n        (MEM_SBUF: mem_sbuf ge m (sytm + period) tid mcont)\n        (MEM_MSTORE: mem_mstore ge m cflg\n                                ofsc ofsn inbc inbn)\n        (MEM_SH: mem_sh ge m (repeat false num_tasks))\n        (MEM_TXS: mem_txs ge m txs)\n        (SIM_REST:\n           forall sh' ast' m' mcont'\n             (UNCH_MAIN: Mem.unchanged_on\n                           (blocks_of ge app_unch_gvar_ids) m m')\n             (* (main_appinv_region cprog) m m') *)\n             (MEM_SH: mem_sh ge m' sh')\n             (MEM_SBUF: mem_sbuf ge m' (sytm + period)%nat tid mcont')\n             (INV_APP': inv_app ge ast' m'),\n             paco3 (_sim_itree (prog_of_clight cprog))\n                   r idx' (ki (sh', ast'))\n                   (Clight.Returnstate Vundef kp m'))\n      ,\n        paco3 (_sim_itree (prog_of_clight cprog)) r\n              (idx' + idx_job)%nat\n              (ret <- MWITree.interp_send\n                       tid app_mod txs sytm\n                       (repeat false num_tasks)\n                       ast inbc;;\n               ki ret)\n              (Clight.Callstate\n                 (Internal job_func)\n                 [Vlong (IntNat.of_nat64 sytm);\n                 Vptr b_mst (Ptrofs.repr ofsc)] kp m)\n    ;\n  }.\n\nSection SIM_APP_LEMMAS.\n  (* Variable cprog: Clight.program. *)\n  Variable (* tid *) txs rxs: nat.\n\n  Context `{SimApp}.\n  Let prog: Prog.t := prog_of_clight cprog.\n  Let ge := globalenv cprog.\n\n  Lemma inv_app_unch_diffblk\n        id ast b m m'\n        (INV_APP: inv_app ge ast m)\n        (MEM_CH: mem_changed_block b m m')\n        (IN_MAIN: In id main_gvar_ids)\n        (FIND_SYMB_CH: Genv.find_symbol ge id = Some b)\n    : inv_app ge ast m'.\n  Proof.\n    eapply inv_app_dep_app_blocks; eauto.\n    eapply Mem.unchanged_on_implies; eauto.\n    intros b_app ofs_app BLKS_OF_APP ?. simpl.\n    rr in BLKS_OF_APP. des.\n    eapply Genv.global_addresses_distinct; eauto.\n    apply not_eq_sym.\n    eapply main_app_gvar_ids_disj; eauto.\n  Qed.\n\nEnd SIM_APP_LEMMAS.\n\n\n\nLemma eval_max_time `{SystemEnv}\n  : Int64.sub (Int64.repr (-1))\n              (Int64.repr (10 * Z.of_nat period)) =\n    Int64.repr (Z.of_nat MAX_TIME).\nProof.\n  fold Int64.mone.\n  rewrite Int64_mone_max_unsigned.\n  unfold Int64.sub.\n  rewrite Int64.unsigned_repr by ss.\n  rewrite Int64.unsigned_repr.\n  2: { pose proof period_mul_10_lt_max. nia. }\n  rewrite Z.mul_comm.\n  fold MAX_TIME_Z.\n  rewrite max_time_to_z. ss.\nQed.\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/VerifProgBase.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.26660630620377734}}
{"text": "Require Export VST.veric.Clight_base.\nRequire Import VST.veric.rmaps.\nRequire Import VST.veric.compcert_rmaps.\nRequire Import VST.veric.res_predicates.\nRequire Import VST.veric.shares.\nRequire Import VST.veric.tycontext.\nRequire Import VST.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": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/veric/ghost.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178686187839, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.26646681285599805}}
{"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 A B C D M N Aprime Bprime Cprime Dprime Mprime Nprime H G L K : Universe, ((wd_ N M /\\ (wd_ M C /\\ (wd_ C D /\\ (wd_ N D /\\ (wd_ Nprime Mprime /\\ (wd_ Mprime Cprime /\\ (wd_ Cprime Dprime /\\ (wd_ Nprime Dprime /\\ (wd_ A B /\\ (wd_ B C /\\ (wd_ A D /\\ (wd_ A C /\\ (wd_ B D /\\ (wd_ Aprime Bprime /\\ (wd_ Bprime Cprime /\\ (wd_ Aprime Dprime /\\ (wd_ Aprime Cprime /\\ (wd_ Bprime Dprime /\\ (wd_ Nprime Aprime /\\ (wd_ Mprime Bprime /\\ (wd_ N A /\\ (wd_ M B /\\ (wd_ N H /\\ (wd_ H G /\\ (wd_ N G /\\ (wd_ M G /\\ (wd_ M H /\\ (wd_ N C /\\ (wd_ D G /\\ (wd_ A H /\\ (wd_ N L /\\ (wd_ L G /\\ (wd_ K H /\\ (wd_ N K /\\ (wd_ H C /\\ (wd_ D M /\\ (wd_ M A /\\ (wd_ K M /\\ (wd_ D H /\\ (wd_ Mprime Dprime /\\ (wd_ Nprime Cprime /\\ (wd_ L H /\\ (col_ A D H /\\ (col_ H A N /\\ (col_ M N L /\\ (col_ K M C /\\ (col_ C K H /\\ (col_ D K H /\\ (col_ G K H /\\ (col_ Nprime Aprime Dprime /\\ (col_ N A D /\\ (col_ Mprime Bprime Cprime /\\ (col_ M B C /\\ col_ N D H))))))))))))))))))))))))))))))))))))))))))))))))))))) -> col_ H G 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_0462.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.26646255143730296}}
{"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 DepMaps Protocols Worlds NetworkSem.\nFrom DiSeL\nRequire Import Actions Injection InductiveInv.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection ProcessSyntax.\n\nVariable this : nid.\n\n(* Syntax for process *)\nInductive proc (W : world) A :=\n  Unfinished | Ret of A | Act of action W A this |\n  Seq B of proc W B & B -> proc W A |\n  Inject V K of injects V W K & proc V A |\n  WithInv p I (ii : InductiveInv p I) of\n          W = mkWorld (ProtocolWithIndInv ii) & proc (mkWorld p) A.  \n\nDefinition pcat W A B (t : proc W A) (k : A -> Pred (proc W B)) :=\n  [Pred s | exists q, s = Seq t q /\\ forall x, q x \\In k x].\n\nInductive schedule :=\n  ActStep | SeqRet | SeqStep of schedule |  \n  InjectStep of schedule | InjectRet |\n  WithInvStep of schedule | WithInvRet.\n\nEnd ProcessSyntax.\n\nArguments Unfinished [this W A].\nArguments Ret [this W A].\nArguments Act [this W A].\nArguments Seq [this W A B].\nArguments WithInv [this W A].\n\nSection ProcessSemantics.\n\nVariable this : nid.\n\nFixpoint step (W : world) A (s1 : state) (p1 : proc this W A)\n         sc (s2 : state) (p2 : proc this W A) : Prop :=\n  match sc, p1 with\n  (* Action - make a step *)  \n  | ActStep, Act a => exists v pf, @a_step _ _ _ a s1 pf s2 v /\\ p2 = Ret v\n  (* Sequencing - apply a continuation *)  \n  | SeqRet, Seq _ (Ret v) k => s2 = s1 /\\ p2 = k v\n  | SeqStep sc', Seq _ p' k1 => \n    exists p'', step s1 p' sc' s2 p'' /\\ p2 = Seq p'' k1\n  (* Injection of a non-reduced term *)\n  | InjectRet, Inject V K pf (Ret v) =>\n     exists s1', [/\\ s2 = s1, p2 = Ret v & extends pf s1 s1']\n  | InjectStep sc', Inject V K pf t1' =>\n    exists s1' s2' s t2', \n    [/\\ p2 = Inject pf t2', s1 = s1' \\+ s, s2 = s2' \\+ s, \n     s1' \\In Coh V & step s1' t1' sc' s2' t2']\n  (* Imposing an inductive invariant on a non-reduced term *)\n  | WithInvRet, WithInv p inv ii pf (Ret v) =>\n     exists s1', [/\\ s2 = s1, p2 = Ret v & s1 = s1']\n  | WithInvStep sc', WithInv p inv ii pf t1' =>\n    exists t2', p2 = WithInv p inv ii pf t2' /\\  \n                     step s1 t1' sc' s2 t2'   \n  | _, _ => False\n  end.\n\nFixpoint good (W : world) A (p : proc this W A) sc  : Prop :=\n  match sc, p with\n  | ActStep, Act _ => True\n  | SeqRet, Seq _ (Ret _) _ => True\n  | SeqStep sc', Seq _ p' _ => good p' sc'\n  | InjectStep sc', Inject _ _ _ p' => good p' sc'\n  | InjectRet, Inject _ _ _ (Ret _) => True\n  | WithInvStep sc', WithInv _ _ _ _ p' => good p' sc'\n  | WithInvRet, WithInv _ _ _ _ (Ret _) => True\n  | _, _ => False\n  end.\n\n(*\n\n[Safety in small-step semantics]\n\nThe safety (in order to make the following step) with respect to the\nschedule is defined inductively on the shape of the program and the\nschedule. Omitting the schedule is not a good idea, at it's required\nin order to \"sequentialize\" the execution of the program\nstructure. Once it's dropped, this structure is lost.\n\n *)\n\nFixpoint safe (W : world) A (p : proc this W A) sc (s : state)  : Prop :=\n  match sc, p with\n  | ActStep, Act a => a_safe a s\n  | SeqRet, Seq _ (Ret _) _ => True\n  | SeqStep sc', Seq _ p' _ => safe p' sc' s\n  | InjectStep sc', Inject V K pf p' =>\n      exists s', extends pf s s' /\\ safe p' sc' s'\n  | InjectRet, Inject V K pf (Ret _) => exists s', extends pf s s'\n  | WithInvStep sc', WithInv _ _ _ _ p' => safe p' sc' s\n  | WithInvRet, WithInv _ _ _ _ (Ret _) => True\n  | _, _ => True\n  end.\n\nDefinition pstep (W : world) A s1 (p1 : proc this W A) sc s2 p2 := \n  [/\\ s1 \\In Coh W, safe p1 sc s1 & step s1 p1 sc s2 p2].\n\n(* Some sanity lemmas wrt. stepping *)\n\nLemma pstep_safe (W : world) A s1 (t : proc this W A) sc s2 q : \n        pstep s1 t sc s2 q -> safe t sc s1.\nProof. by case. Qed.\n\n\n(*\n\nThe following lemma established the operational \"progress\" property: a\nprogram, which is safe and also the schedule is appropriate. Together,\nthis implies that we can do a step. \n *)\n\nLemma proc_progress W A s (p : proc this W A) sc : \n        s \\In Coh W -> safe p sc s -> good p sc ->  \n        exists s' (p' : proc this W A), pstep s p sc s' p'.\nProof.\nmove=>C H1 H2; elim: sc W A s p H2 H1 C=>[||sc IH|sc IH||sc IH|]W A s. \n- case=>//=a _/= H; move/a_step_total: (H)=>[s'][r]H'.\n  by exists s', (Ret r); split=>//=; exists r, H.  \n- by case=>//; move=>B p k/=; case: p=>//b _ _; exists s, (k b). \n- case=>//B p k/=H1 H2 C.\n  case: (IH W B s p H1 H2 C)=>s'[p'][G1 G2].\n  by exists s', (Seq p' k); split=>//; exists p'. \n- case=>// V K pf p/=H1 [z][E]H2 C. \n  case: (E)=>s3[Z] C1 C2.\n  case: (IH V A z p H1 H2 C1) =>s'[p']H3; case: H3=>S St.\n  exists (s' \\+ s3), (Inject pf p'); split=>//; first by exists z.  \n  by subst s; exists z, s', s3, p'. \n- case=>//V K pf; case=>// v/=_[s'] E C.          \n  by exists s, (Ret v); split=>//=; exists s'.\n- case=>//pr I ii E p/= H1 H2 C.\n  have C' : s \\In Coh (mkWorld pr) by subst W; apply: (with_inv_coh C). \n  case: (IH (mkWorld pr) A s p H1 H2 C')=>s'[p']H3.\n  exists s', (WithInv pr I ii E p'); split=>//=.\n  by exists p'; split=>//; case: H3. \n- case=>//pr I ii E; case=>//v/=_ _ C.          \n  by exists s, (Ret v); split=>//=; exists s. \nQed.\n\n(* Some view lemmas for processes and corresponding schedules *)\n\nLemma stepUnfin W A s1 sc s2 (t : proc this W A) : \n        pstep s1 Unfinished sc s2 t <-> False.\nProof. by split=>//; case; case: sc. Qed.\n\nLemma stepRet W A s1 sc s2 (t : proc this W A) v : \n        pstep s1 (Ret v) sc s2 t <-> False.\nProof. by split=>//; case; case: sc. Qed.\n\nLemma stepAct W A s1 a sc s2 (t : proc this W A) : \n        pstep s1 (Act a) sc s2 t <->\n        exists v pf, [/\\ sc = ActStep, t = Ret v & @a_step _ _ _ a s1 pf s2 v].\nProof.\nsplit; first by case=>C; case: sc=>//= c [v [pf [H ->]]]; exists v, pf. \ncase=>v[pf] [->-> H]; split=>//; last by exists v, pf.\nby apply: (a_safe_coh pf). \nQed.\n\nLemma stepSeq W A B s1 (t : proc this W B) k sc s2 (q : proc this W A) :\n        pstep s1 (Seq t k) sc s2 q <->\n        (exists v, [/\\ sc = SeqRet, t = Ret v, q = k v, s2 = s1 &\n                       s1 \\In Coh W]) \\/\n         exists sc' p',\n           [/\\ sc = SeqStep sc', q = Seq p' k & pstep s1 t sc' s2 p'].\nProof.\nsplit; last first.\n- case; first by case=>v [->->->->]. \n  by case=>sc' [t'][->->][S H]; do !split=>//; exists t'. \ncase; case: sc=>//[|sc] C. \n- by case: t=>//= v _ [->->]; left; exists v. \nby move=>G /= [p' [H1 ->]]; right; exists sc, p'.\nQed.\n\nLemma stepInject V W K A (em : injects V W K) \n                s1 (t : proc this V A) sc s2 (q : proc this W A) :\n  pstep s1 (Inject em t) sc s2 q <->\n  (* Case 1 : stepped to the final state s1' of the inner program*)\n  (exists s1' v, [/\\ sc = InjectRet, t = Ret v, q = Ret v, s2 = s1 &\n                     extends em s1 s1']) \\/\n  (* Case 2 : stepped to the nextx state s12 of the inner program*)\n  exists sc' t' s1' s2' s, \n    [/\\ sc = InjectStep sc', q = Inject em t', \n     s1 = s1' \\+ s, s2 = s2' \\+ s, s1 \\In Coh W &\n              pstep s1' t sc' s2' t'].\nProof.\nsplit; last first.\n- case.\n  + case=>s1' [v][->->->->] E.\n    split=>//=; [by case: E=>x[] | by exists s1'|by exists s1'].\n  case=>sc' [t'][s1'][s2'][s][->->->-> C][[C' S] T]. \n  split=>//=; last by exists s1', s2', s, t'. \n  by exists s1'; split=>//; exists s. \ncase=>C; case: sc=>//=; last first.\n- case: t=>//= v [C1 S][s1'][->->{s2 q}] X.\n  by left; exists s1'; exists v. \nmove=>sc /= [s'][X] S [s1'][s2'][t'][t2'][??? C1'] T; subst q s1 s2. \nright; exists sc, t2', s1', s2', t'; do !split=>//.\nby case: X=>t'' [E] Cs' _; rewrite (coh_prec (cohS C)  _ Cs' E). \nQed.\n\nLemma stepWithInv W A pr I (ii : InductiveInv pr I) s1 \n      (t : proc this (mkWorld pr) A) sc s2 (q : proc this W A) pf :\n  pstep s1 (WithInv pr I ii pf t) sc s2 q <-> \n  (exists v, [/\\ sc = WithInvRet, t = Ret v, q = Ret v, s2 = s1,\n                 s1 \\In Coh W & W = mkWorld (ProtocolWithIndInv ii)]) \\/\n  exists sc' t' , [/\\ sc = WithInvStep sc', q = WithInv pr I ii pf t',\n                      W = mkWorld (ProtocolWithIndInv ii),\n                      s1 \\In Coh W & pstep s1 t sc' s2 t'].\nProof.\nsplit; last first.\n- case.\n  + by case=>v[->->->->{s2}]C E; split=>//=; exists s1.\n   by case=>sc' [t'][->->{sc q}]E C[C' S]T; split=>//=; exists t'.   \ncase=>C; case: sc=>//=; last first.\n- by case: t=>//=v _[s1'][Z1]Z2 Z3; subst s2 s1' q; left; exists v. \nmove=>sc /=S[t'][->{q}T]; right; exists sc, t'; split=>//.\nby split=>//; subst W; apply: (with_inv_coh C).\nQed.\n\n(*\n\n[Stepping and network semantics]\n\nThe following lemma ensures that the operational semantics of our\nprograms respect the global network semantics.\n\n *)\n\nLemma pstep_network_sem (W : world) A s1 (t : proc this W A) sc s2 q :\n        pstep s1 t sc s2 q -> network_step W this s1 s2.\nProof.\nelim: sc W A s1 s2 t q=>/=.\n- move=>W A s1 s2 p q; case: p; do?[by case|by move=>?; case].\n  + by move=>a/stepAct [v][pf][Z1]Z2 H; subst q; apply: (a_step_sem H).\n  + by move=>???; case. \n  + by move=>????; case.\n  by move=>?????; case.   \n- move=>W A s1 s2 p q; case: p; do?[by case|by move=>?; case].\n  + move=>B p p0/stepSeq; case=>[[v][_]??? C|[sc'][p'][]]//.\n    by subst p s2; apply: Idle. \n  by move=>????/stepInject; case=>[[?][?][?]|[?][?][?][?][?][?]]//.\n  by move=>?????; case.   \n- move=>sc HI W A s1 s2 p q; case: p; do?[by case|by move=>?; case].\n  + move=>B p p0/stepSeq; case=>[[?][?]|[sc'][p'][][]? ?]//.\n    by subst sc' q; apply: HI.\n  by move=>????; case=>? _.\n  by move=>?????; case.   \n- move=>sc HI W A s1 s2 p q; case: p; do?[by case|by move=>?; case].\n  + by move=>B p p0; case. \n  move=>V K pf p/stepInject; case=>[[?][?][?]|[sc'][t'][s1'][s2'][s][][]????]//. \n  subst sc' q s1 s2=>C; move/HI=>S; apply: (sem_extend pf)=>//.\n  apply/(cohE pf); exists s2', s; case: (step_coh S)=>C1 C2; split=>//.\n  move/(cohE pf): (C)=>[s1][s2][E]C' H.\n  by move: (coh_prec (cohS C) C1 C' E)=>Z; subst s1'; rewrite (joinxK (cohS C) E). \n  by move=>?????; case.   \n- move=>W A s1 s2 p q; case: p; do?[by case|by move=>?; case].\n  + by move=>???; case.\n  + move=>V K i p; case/stepInject=>[[s1'][v][_]??? X|[?][?][?][?][?][?]]//.\n    by subst p q s2; apply: Idle; split=>//; case: X=>x []. \n  by move=>?????; case.\n\n- move=>sc HI W A s1 s2 p q; case: p;\n           do?[by case|by move=>?; case|by move=>???; case|by move=>????; case].\n  move=>pr I ii E p; case/(stepWithInv s1); first by case=>?; case.\n  case=>sc'[t'][][]Z1 Z2 _ C1; subst q sc'.\n  by move/HI=>T; subst W; apply: with_inv_step. \nmove=>W A s1 s2 t q; do?[by case|by move=>?; case|by move=>???; case].\ncase=>C; case: t=>//pr I ii E; case=>//=v _[s1'][Z1]Z2 Z3.\nby subst s1' s2 q; apply: Idle. \nQed.\n\n(*\n\n[Inductive invariants and stepping]\n\nThe following lemma is the crux of wrapping into inductive invariants, as \nit leverages the proof of the fact that each transition preserves the invariant.\n\n*)\n\nLemma pstep_inv A pr I (ii : InductiveInv pr I) s1 s2 sc\n      (t t' : proc this (mkWorld pr) A):\n  s1 \\In Coh (mkWorld (ProtocolWithIndInv ii)) ->\n  pstep s1 t sc s2 t' -> \n  s2 \\In Coh (mkWorld (ProtocolWithIndInv ii)).\nProof. by move=>C1; case/pstep_network_sem/(with_inv_step C1)/step_coh. Qed.\n\nEnd ProcessSemantics.\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/Core/Process.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2664112360207945}}
{"text": "Require Coq.Lists.List. Import List.ListNotations.\nRequire Import Coq.ZArith.ZArith. Local Open Scope Z_scope.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.setoid_ring.Ring.\nRequire Import coqutil.Word.Interface coqutil.Word.Properties.\nRequire coqutil.Datatypes.List.\nRequire Import bedrock2.ListPushPullIf.\n\n(* Stores a rewrite opportunity. Will not show up in proof terms, only used in Ltac *)\nInductive rewr(P: Type): Type :=\n| mk_rewr(T: Type)(x y: T)(e: x = y)(ctx: T -> Type).\nExisting Class rewr.\n\nLemma rewr_fw{T: Type}{lhs rhs: T}:\n  lhs = rhs ->\n  forall P : T -> Type, P lhs -> P rhs.\nProof.\n  intros. subst. assumption.\nQed.\n\nLemma rewr_bw{T: Type}{lhs rhs: T}:\n  lhs = rhs ->\n  forall P : T -> Type, P rhs -> P lhs.\nProof.\n  intros. subst. assumption.\nQed.\n\nLtac rewr_step_in H :=\n  let t := type of H in\n  lazymatch constr:(_ : rewr t) with\n  | mk_rewr _ ?T ?x ?y ?e ?ctx  =>\n      let r := constr:(@rewr_fw T x y e ctx) in\n      apply r in H\n  end.\n\nLtac mk_rewr equ ctx :=\n  refine (mk_rewr _ _ _ _ equ ctx).\n\nModule WordRingAutorewr.\n  Ltac mkr orig ctx :=\n    refine (mk_rewr _ _ orig _ _ ctx);\n    ring_simplify;\n    let new := lazymatch goal with |- ?new = _ => new end in\n    tryif constr_eq orig new then fail \"no simplification opportunity\" else reflexivity.\n\n  Ltac mk_word_ring_simplify_rewr P :=\n    match P with\n    | context C[@word.add ?wi ?wo ?x ?y] =>\n        mkr (@word.add wi wo x y) (fun hole => ltac:(let r := context C[hole] in exact r))\n    | context C[@word.sub ?wi ?wo ?x ?y] =>\n        mkr (@word.sub wi wo x y) (fun hole => ltac:(let r := context C[hole] in exact r))\n    | context C[@word.opp ?wi ?wo ?x] =>\n        mkr (@word.opp wi wo x) (fun hole => ltac:(let r := context C[hole] in exact r))\n    | context C[@word.mul ?wi ?wo ?x ?y] =>\n        mkr (@word.mul wi wo x y) (fun hole => ltac:(let r := context C[hole] in exact r))\n    end.\n\n  #[export] Hint Extern 5 (rewr ?P) => mk_word_ring_simplify_rewr P : typeclass_instances.\nEnd WordRingAutorewr.\n\nModule HypAutorewr.\n  Ltac term_size t acc :=\n    lazymatch t with\n    | S ?x => lazymatch isnatcst x with\n              | true => constr:(S acc)\n              | false => term_size x (S acc)\n              end\n    | Zpos ?p => lazymatch isPcst p with\n                 | true => constr:(S acc)\n                 | false => term_size p (S acc)\n                 end\n    | Zneg ?p => lazymatch isPcst p with\n                 | true => constr:(S acc)\n                 | false => term_size p (S acc)\n                 end\n    | Z0 => constr:(S acc)\n    | ?f ?a => let r := term_size f (S acc) in term_size a r\n    | _ => let __ := match constr:(O) with\n                     | _ => is_var t\n                     | _ => is_const t\n                     end in\n           constr:(S acc)\n    end.\n\n  Ltac mk_rewr_with_hyp P :=\n    match goal with\n    | E: ?lhs = ?rhs |- _ =>\n        lazymatch P with\n        | lhs = rhs => fail (* don't rewrite a hypothesis with itself *)\n        | context C[lhs] =>\n            let s1 := term_size lhs O in\n            let s2 := term_size rhs O in\n            lazymatch eval cbv in (Nat.ltb s2 s1) with true =>\n              let ctx := constr:(fun hole => ltac:(let r := context C[hole] in exact r)) in\n              refine (mk_rewr P _ lhs rhs E ctx)\n            end\n        end\n    end.\n\n  #[export] Hint Extern 3 (rewr ?P) => mk_rewr_with_hyp P : typeclass_instances.\nEnd HypAutorewr.\n\nModule ListNoSCAutorewr.\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[@List.firstn ?A (S ?n) (?a :: ?l)] =>\n        let ctx := constr:(fun hole => ltac:(let r := context C[hole] in exact r)) in\n        refine (mk_rewr P (list A) _ _ (List.firstn_cons n a l) ctx)\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[@List.skipn ?A (S ?n) (?a :: ?l)] =>\n        let ctx := constr:(fun hole => ltac:(let r := context C[hole] in exact r)) in\n        refine (mk_rewr P (list A) _ _ (List.skipn_cons n a l) ctx)\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[@List.firstn ?A O ?l] =>\n        let ctx := constr:(fun hole => ltac:(let r := context C[hole] in exact r)) in\n        refine (mk_rewr P (list A) _ _ (List.firstn_O l) ctx)\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[@List.skipn ?A O ?l] =>\n        let ctx := constr:(fun hole => ltac:(let r := context C[hole] in exact r)) in\n        refine (mk_rewr P (list A) _ _ (List.skipn_O l) ctx)\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[((?a :: ?x) ++ ?y)%list] =>\n        let ctx := constr:(fun hole => ltac:(let r := context C[hole] in exact r)) in\n        refine (mk_rewr P _ _ _ (eq_sym (List.app_comm_cons x y a)) ctx)\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[([] ++ ?l)%list] =>\n        let ctx := constr:(fun hole => ltac:(let r := context C[hole] in exact r)) in\n        refine (mk_rewr P _ _ _ (List.app_nil_l l) ctx)\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[(?l ++ [])%list] =>\n        let ctx := constr:(fun hole => ltac:(let r := context C[hole] in exact r)) in\n        refine (mk_rewr P _ _ _ (List.app_nil_r l) ctx)\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[((?l ++ ?m) ++ ?n)%list] =>\n        mk_rewr (eq_sym (List.app_assoc l m n))\n                (fun hole => ltac:(let r := context C[hole] in exact r))\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[List.firstn ?n (?l1 ++ ?l2)] =>\n        mk_rewr (List.firstn_app n l1 l2)\n                (fun hole => ltac:(let r := context C[hole] in exact r))\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[List.firstn ?i (List.firstn ?j ?l)] =>\n        mk_rewr (List.firstn_firstn l i j)\n                (fun hole => ltac:(let r := context C[hole] in exact r))\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[List.length (List.firstn ?n ?l)] =>\n        mk_rewr (List.firstn_length n l)\n                (fun hole => ltac:(let r := context C[hole] in exact r))\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[List.firstn ?m (List.skipn ?n ?l)] =>\n        mk_rewr (List.firstn_skipn_comm m n l)\n                (fun hole => ltac:(let r := context C[hole] in exact r))\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[List.length (?x :: ?xs)] =>\n        let ctx := constr:(fun hole => ltac:(let r := context C[hole] in exact r)) in\n        refine (mk_rewr P _ (List.length (x :: xs)) (S (List.length xs)) eq_refl ctx)\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[List.length (@nil ?A)] =>\n        let ctx := constr:(fun hole => ltac:(let r := context C[hole] in exact r)) in\n        refine (mk_rewr P _ (List.length (@nil A)) O eq_refl ctx)\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[List.firstn ?m (List.skipn ?n ?l)] =>\n        mk_rewr (List.firstn_skipn_comm m n l)\n                (fun hole => ltac:(let r := context C[hole] in exact r))\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[List.nth ?i (List.skipn ?j ?l) ?d] =>\n        mk_rewr (List.nth_skipn i j l d)\n                (fun hole => ltac:(let r := context C[hole] in exact r))\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[List.repeat ?a O] =>\n        let ctx := constr:(fun hole => ltac:(let r := context C[hole] in exact r)) in\n        refine (mk_rewr P _ (List.repeat a O) nil eq_refl ctx)\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[List.skipn ?n (?xs ++ ?ys)] =>\n        mk_rewr (List.skipn_app n xs ys)\n                (fun hole => ltac:(let r := context C[hole] in exact r))\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[List.skipn ?n (List.skipn ?m ?xs)] =>\n        mk_rewr (List.skipn_skipn n m xs)\n                (fun hole => ltac:(let r := context C[hole] in exact r))\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[List.unfoldn ?f 0 ?start] =>\n        mk_rewr (List.unfoldn_0 f start)\n                (fun hole => ltac:(let r := context C[hole] in exact r))\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[List.unfoldn ?f (S ?n) ?start] =>\n        mk_rewr (List.unfoldn_S f start n)\n                (fun hole => ltac:(let r := context C[hole] in exact r))\n    end\n  : typeclass_instances.\nEnd ListNoSCAutorewr.\n\nModule PushPullIfAutorewr.\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[if ?b then ?a else ?a] =>\n        mk_rewr (if_same b a)\n                (fun hole => ltac:(let r := context C[hole] in exact r))\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[List.firstn ?n (if ?b then ?l1 else ?l2)] =>\n        mk_rewr (pull_if_firstn b l1 l2 n)\n                (fun hole => ltac:(let r := context C[hole] in exact r))\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[List.length (if ?b then ?l1 else ?l2)] =>\n        mk_rewr (pull_if_length b l1 l2)\n                (fun hole => ltac:(let r := context C[hole] in exact r))\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[List.skipn ?n (if ?b then ?l1 else ?l2)] =>\n        mk_rewr (pull_if_skipn b l1 l2 n)\n                (fun hole => ltac:(let r := context C[hole] in exact r))\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[if ?b then ?l1 ++ ?l2 else ?r] =>\n        mk_rewr (push_if_app_l b l1 l2 r)\n                (fun hole => ltac:(let r := context C[hole] in exact r))\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[if ?b then ?l else ?r1 ++ ?r2] =>\n        mk_rewr (push_if_app_r b l r1 r2)\n                (fun hole => ltac:(let r := context C[hole] in exact r))\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 1 (rewr ?P) =>\n    lazymatch P with\n    | context C[if ?b then [?a1] else [?a2]] =>\n        mk_rewr (push_if_singleton b a1 a2)\n                (fun hole => ltac:(let r := context C[hole] in exact r))\n    end\n  : typeclass_instances.\nEnd PushPullIfAutorewr.\n\nModule LiaSCAutorewr.\n  #[export] Hint Extern 5 (rewr ?P) =>\n    match P with\n    | context C[word.unsigned (word.of_Z ?x)] =>\n        let ctx := constr:(fun hole => ltac:(let r := context C[hole] in exact r)) in\n        refine (mk_rewr P _ _ _ (word.unsigned_of_Z_nowrap x _) ctx); lia\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 5 (rewr ?P) =>\n    match P with\n    | context C[List.nth ?j (List.firstn ?i ?l) ?d] =>\n        let ctx := constr:(fun hole => ltac:(let r := context C[hole] in exact r)) in\n        refine (mk_rewr P _ _ _ (List.nth_firstn i l j d _) ctx); lia\n    end\n  : typeclass_instances.\nEnd LiaSCAutorewr.\n\nRequire Import bedrock2.SepAutoArray bedrock2.ZnWords.\n\nModule ZnWordsSCAutorewr.\n  #[export] Hint Extern 10 (rewr ?P) =>\n    match P with\n    | context C[List.firstn ?n ?l] =>\n        let ctx := constr:(fun hole => ltac:(let r := context C[hole] in exact r)) in\n        refine (mk_rewr P _ _ _ (@List.firstn_all2 _ n l _) ctx);\n        unfold List.upd, List.upds;\n        list_length_rewrites_without_sideconds_in_goal;\n        ZnWords\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 10 (rewr ?P) =>\n    match P with\n    | context C[List.firstn ?n ?l] =>\n        let ctx := constr:(fun hole => ltac:(let r := context C[hole] in exact r)) in\n        refine (mk_rewr P _ _ _ (List.firstn_eq_O n l _) ctx);\n        unfold List.upd, List.upds;\n        list_length_rewrites_without_sideconds_in_goal;\n        ZnWords\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 10 (rewr ?P) =>\n    match P with\n    | context C[List.skipn ?n ?l] =>\n        let ctx := constr:(fun hole => ltac:(let r := context C[hole] in exact r)) in\n        refine (mk_rewr P _ _ _ (List.skipn_eq_O n l _) ctx);\n        unfold List.upd, List.upds;\n        list_length_rewrites_without_sideconds_in_goal;\n        ZnWords\n    end\n  : typeclass_instances.\n\n  #[export] Hint Extern 10 (rewr ?P) =>\n    match P with\n    | context C[List.skipn ?n ?l] =>\n        let ctx := constr:(fun hole => ltac:(let r := context C[hole] in exact r)) in\n        refine (mk_rewr P _ _ _ (@List.skipn_all2 _ n l _) ctx);\n        unfold List.upd, List.upds;\n        list_length_rewrites_without_sideconds_in_goal;\n        ZnWords\n    end\n  : typeclass_instances.\nEnd ZnWordsSCAutorewr.\n\nRequire Import bedrock2.groundcbv.\n\nLtac groundcbv_in H :=\n  let t := type of H in\n  let t' := groundcbv t in\n  progress change t' in H.\n\nLtac autorew_in_hyps :=\n  repeat match goal with\n         | H: _ |- _ => rewr_step_in H || groundcbv_in H\n         end.\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/autorew.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.26641122894607633}}
{"text": "Require Export WellFormedness.\nRequire Import SyntaxProp.\nRequire Import StaticProp.\nRequire Import DynamicProp.\nRequire Import MapProp.\n\nLemma wf_actor_ctx :\n  forall M H id l L C Q e ctx,\n    is_econtext ctx ->\n    wf_actor M H id (l, L, C, Q, ctx e) ->\n    wf_actor M H id (l, L, C, Q, e).\nProof with eauto using hasType_ctx, freeLocs_ctx, freeIds_ctx, freeBIds_ctx.\n  introv Hctx wfActor.\n  inverts wfActor as (t & hasType).\n  constructors...\nQed.\n\nLemma wf_msg_heapExtend :\n  forall M H L id msg a,\n    wf_msg M H L id msg ->\n    wf_msg M (heapExtend H a) L id msg.\nProof with (hauto; eauto using wf_msg).\n  introv wfMsg.\n  inverts wfMsg as Hex Hloc HId HBId...\n  constructors...\n  + Case \"Ids well-formed\". crush.\n  + Case \"BIds well-formed\".\n    introv HIn.\n    eapply HBId in HIn as [Hlt HBloc].\n    splits...\n    intros...\nQed.\n\nLemma wf_actor_heapExtend :\n  forall M H id a a',\n    wf_actor M H id a ->\n    wf_actor M (heapExtend H a') id a.\nProof with (hauto; eauto using wf_msg_heapExtend).\n  introv wfA.\n  inverts wfA as Hthis wfQueue [t hasType] Hloc HId HBId.\n  constructors...\n  + Case \"Ids well-formed\". crush.\n  + introv HIn.\n    eapply HBId in HIn as [Hlt HBloc].\n    split...\n    intros...\nQed.\n\nLemma wf_actors_heapExtend :\n  forall M H l L Q e id a,\n    (forall id a, heapLookup H id = Some a -> wf_actor M H id a) ->\n    wf_actor M H (length H) (l, L, Q, e) ->\n    heapLookup (heapExtend H (l, L, Q, e)) id = Some a ->\n    wf_actor M (heapExtend H (l, L, Q, e)) id a.\nProof with (hauto; eauto using wf_actor_heapExtend).\n  introv wfH wfA Hlookup...\nQed.\n\nLemma wf_queue_heapUpdate :\n  forall M H l L L' C' Q Q' e id id' l0 L0 P0 Q0 e0,\n    (forall id a, heapLookup H id = Some a -> wf_actor M H id a) ->\n    wf_queue M H L id Q ->\n    heapLookup H id' = Some (l0, L0, P0, Q0, e0) ->\n    (forall l, In l L0 -> In l L') ->\n    wf_queue M (heapUpdate H id' (l, L', C', Q', e)) L id Q.\nProof with (hauto; eauto using wf_msg).\n  introv wfActors wfQueue Hlookup Hmono.\n  introv HIn.\n  apply wfQueue in HIn as wfMsg.\n  inverts wfMsg as Hex Hloc HId HBId...\n  constructors...\n  introv HIn'.\n  eapply HBId in HIn' as [Hlt HBloc]...\n  splits...\n  introv HLH. inv_eq...\nQed.\n\nLemma wf_queue_snoc :\n  forall M H L id Q msg,\n    wf_queue M H L id Q ->\n    wf_msg M H L id msg ->\n    wf_queue M H L id (snoc Q msg).\nProof with eauto.\n  introv wfQueue wfMsg.\n  induction Q; simpls...\n  + unfolds; crush.\n  + unfolds wf_queue. introv HIn.\n    inv HIn; crush.\nQed.\n\nLemma wf_heap_heapUpdate :\n  forall M H l l' L C Q Q' e e' id,\n    wf_heap M H ->\n    heapLookup H id = Some (l, L, C, Q, e) ->\n    wf_actor M H id (l', L, C, Q', e') ->\n    local_heap_disjointness H ->\n    conversation_disjointness H ->\n    wf_heap M (heapUpdate H id (l', L, C, Q', e')).\nProof with (hauto; eauto using wf_queue_heapUpdate).\n  introv wfH Hlookup wfActor Hdisj HCdisj.\n  assert (id < length H)...\n  constructors.\n  + introv Hneq HLH1 HLH2 HIn.\n    hauto; eapply Hdisj...\n  + introv Hneq Hconv1 Hconv2 HC1 HC2.\n    eapply HCdisj; eauto; hauto.\n  + introv Hlookup'. inverts wfH as _ _ wfActors...\n    - inverts wfActor as Hthis wfQid wfQueue HnAtomic HnDup Htype Hloc HId HBId.\n      constructors...\n      introv HIn. eapply HBId in HIn as [Hlt' HBloc]...\n    - eapply wfActors in Hlookup' as wfActor'.\n      inverts wfActor' as Hthis wfQid wfQueue HnAtomic HnDup Htype Hloc HId HBId.\n      constructors...\n      * introv HIn. eapply HBId in HIn as [Hlt' HBloc]...\nQed.\n\nLemma conversation_lt :\n  forall M H id l L C Q e id' qid,\n    wf_queueMap M H ->\n    wf_actor M H id (l, L, C, Q, e) ->\n    C id' = Some qid ->\n    id' < length H.\nProof with eauto.\n  introv wfM wfActor HC.\n  inverts wfActor as _ wfC _ _ _ _ _ _.\n  eapply wfC in HC as [Q' HM].\n  eapply wfM in HM as [? [? [?L [HLH ?]]]]...\nQed.\n\nLemma wf_queueMap_heapUpdate :\n  forall M H n id L l C Q e,\n    wf_cfg (M, H, n) ->\n    conv H id = Some C ->\n    LH H id = Some L ->\n    wf_queueMap M (heapUpdate H id (l, L, C, Q, e)).\nProof with hauto.\n  introv wfCfg Hconv HLH.\n  inverts wfCfg as wfH wfM _ _.\n  inverts wfH as _ _ wfActors.\n  unfolds.\n  splits 3.\n  + introv HIn. eapply wfM in HIn...\n  + introv HIn Hconv' HC...\n    - eapply wfM...\n    - eapply wfM...\n  + eapply wfM in H0 as [_ [_ [L' []]]]...\n    - assert (id0 < length H)...\n      find_actor id0.\n      exists L'.\n      splits...\n      eapply wf_queue_heapUpdate...\n    - assert (id < length H)...\n      find_actor id.\n      exists L'.\n      splits...\n      eapply wf_queue_heapUpdate...\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/WellFormednessProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.26641122894607633}}
{"text": "From CTree Require Import\n     CTree\n\t   Eq\n\t   Interp.Interp.\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\t   Syntax\n\t   Denotation\n\t   Operational.\n\nImport CCSNotations.\nImport DenNotations.\nImport OpNotations.\nOpen Scope ccs_scope.\n\nSet Implicit Arguments.\nSet Contextual Implicit.\n\nLemma SRep': forall P a P'\n               (STEP : step a P P'),\n    step a (!P) (P' ∥ !P).\nProof.\n  intros * TR; apply SRep,SParL; auto.\nQed.\n\nLemma trans_nil_inv : forall l p, ~ trans l nil p.\nProof.\n  intros * abs; eapply stuckS_is_stuck; apply abs.\nQed.\n\nDefinition ι : option action -> @label ccsE :=\n  fun a => match a with\n        | None => tau\n        | Some a => comm a\n        end.\n\nDefinition γ : @label ccsE -> option action :=\n  fun l => match l with\n        | val x => None\n        | tau   => None\n        | obs (Act a) _ => Some a\n        end.\n\nLemma are_opposite_op : forall a, are_opposite a (op a).\nProof.\n  unfold op, are_opposite.\n  intros []; cbn; rewrite eqb_refl; auto.\nQed.\n\nLemma are_opposite_are_op : forall a b,\n    are_opposite a b ->\n    a = op b.\nProof.\n  unfold are_opposite,op; intros [] []; cbn; intuition.\n  all:destruct (c =? c0)%string eqn:EQ; try easy.\n  all:apply eqb_eq in EQ; subst; auto.\nQed.\n\nLemma use_channel_can_comm : forall c a,\n  use_channel c a = false <->\n  can_comm c (ι a) = true.\nProof.\n  unfold can_comm, use_channel.\n  intros ? [[]|]; cbn; split; auto.\n  all:match goal with |- context[if ?b then _ else _] => destruct b; easy end.\nQed.\n\nDefinition forward (R : term -> ccs -> Prop) : Prop :=\n  forall P P' q a,\n\t\tR P q ->\n\t\tP ⊢ a →op P' ->\n\t  exists q', trans (ι a) q q' /\\ R P' q'.\n\nDefinition backward (R : term -> ccs -> Prop) : Prop :=\n  forall P q q' l,\n\t\tR P q ->\n    trans l q q' ->\n\t  exists P', P ⊢ γ l →op P' /\\ R P' q'.\n\nDefinition bisim R := forward R /\\ backward R.\nDefinition bisimilar P q := exists R, bisim R /\\ R P q.\n\nLemma bisimilar_bisim : bisim bisimilar.\nProof.\n  split; red; intros * (R & BIS & HR) TR;\n    pose proof BIS as [F B].\n  - edestruct F as (? & ? & ?); eauto; eexists; split; eauto.\n    exists R; split; auto.\n  - edestruct B as (? & ? & ?); eauto; eexists; split; eauto.\n    exists R; split; auto.\nQed.\n\nDefinition bisim_model := fun P q => ⟦P⟧ ~ q.\n\nLemma complete : forward bisim_model.\nProof.\n  unfold bisim_model; red.\n  intros * HR TR.\n  revert q HR.\n  induction TR; intros * HR; cbn in *.\n  - step in HR; edestruct HR as [[? TR EQ] _].\n    apply trans_prefix.\n    cbn in *; eauto.\n  - step in HR; edestruct HR as [[? TR EQ] _].\n    cbn; apply trans_step.\n    cbn in *; eauto.\n  - edestruct IHTR as (q1 & TR1 & EQ1); eauto.\n    step in HR; edestruct HR as [[q' TR' EQ'] _].\n    apply trans_plusL; apply TR1. (* Need to fix automation w.r.t. trans/transR *)\n    eexists; split; [apply TR' |].\n    cbn; rewrite <- EQ', <- EQ1; auto.\n  - edestruct IHTR as (q2 & TR2 & EQ2); eauto.\n    step in HR; edestruct HR as [[q' TR' EQ'] _].\n    apply trans_plusR; apply TR2. (* Need to fix automation w.r.t. trans/transR *)\n    eexists; split; [apply TR' |].\n    cbn; rewrite <- EQ', <- EQ2; auto.\n  - edestruct IHTR as (q1 & TR1 & EQ1); eauto.\n    step in HR; edestruct HR as [[q' TR' EQ'] _].\n    pL; apply TR1. (* Need to fix automation w.r.t. trans/transR *)\n    eexists; split; [apply TR' |].\n    cbn; rewrite <- EQ', <- EQ1; auto.\n  - edestruct IHTR as (q2 & TR2 & EQ2); eauto.\n    step in HR; edestruct HR as [[q' TR' EQ'] _].\n    pR; apply TR2. (* Need to fix automation w.r.t. trans/transR *)\n    eexists; split; [apply TR' |].\n    cbn; rewrite <- EQ', <- EQ2; auto.\n  - edestruct IHTR1 as (q1 & TR1' & EQ1); eauto.\n    edestruct IHTR2 as (q2 & TR2' & EQ2); eauto.\n    step in HR; edestruct HR as [[q' TR' EQ'] _].\n    pS; [apply TR1' | apply TR2' | apply are_opposite_op]. (* Need to fix automation w.r.t. trans/transR *)\n    eexists; split; [apply TR' |].\n    cbn; rewrite <- EQ', <- EQ1, <- EQ2; auto.\n  - edestruct IHTR as (q' & TR' & EQ'); eauto.\n    eapply trans_new in TR' as (q'' & TR' & EQ''); [| apply use_channel_can_comm; eauto].\n    step in HR; edestruct HR as [[q''' TR'' EQ'''] _].\n    apply TR'.\n    eexists; split.\n    apply TR''.\n    rewrite <- EQ''', EQ'', <- EQ'; auto.\n  - rewrite unfold_bang', paraC in HR.\n    exact (IHTR _ HR).\nQed.\n\nLemma correct : backward bisim_model.\nProof.\n  unfold bisim_model; red.\n  induction P; intros * HR TR; copy TR; step in HR; destruct HR as [_ B]; apply B in TR as [? TR' EQ']; clear B; cbn in *.\n  - exfalso; eapply trans_nil_inv,TR'.\n  - apply trans_step_inv in TR' as [EQ ->].\n    eexists; split; [constructor |].\n    rewrite <- EQ',EQ; auto.\n  - apply trans_prefix_inv in TR' as [EQ ->].\n    eexists; split; [constructor |].\n    rewrite <- EQ', EQ.\n    auto.\n  - trans_para_invT TR'.\n    + edestruct IHP1 as (P' & STEP & EQ''); [reflexivity | apply TRp |].\n      eexists; split.\n      apply SParL; eauto.\n      rewrite <- EQ',EQ,<-EQ''.\n      auto.\n    + edestruct IHP2 as (P' & STEP & EQ''); [reflexivity | apply TRq |].\n      eexists; split.\n      apply SParR; eauto.\n      rewrite <- EQ',EQ,<-EQ''.\n      auto.\n    + edestruct IHP1 as (P' & STEP & EQ''); [reflexivity | apply TRp |].\n      edestruct IHP2 as (P'' & STEP' & EQ'''); [reflexivity | apply TRq |].\n      eexists; split.\n      apply SPar with a.\n      apply STEP.\n      apply are_opposite_sym in Op.\n      rewrite <- (are_opposite_are_op _ Op).\n      apply STEP'.\n      rewrite <- EQ',EQ,<-EQ'',<-EQ'''.\n      auto.\n  - apply trans_plus_inv in TR' as [(? & TRp & EQ) | (? & TRq & EQ)].\n    + edestruct IHP1 as (P' & STEP & EQ''); [reflexivity | apply TRp |].\n      eexists; split.\n      apply SSumL; eauto.\n      rewrite <- EQ',EQ,<-EQ''.\n      auto.\n    + edestruct IHP2 as (P' & STEP & EQ''); [reflexivity | apply TRq |].\n      eexists; split.\n      apply SSumR; eauto.\n      rewrite <- EQ',EQ,<-EQ''.\n      auto.\n  - apply trans_new_inv in TR' as (p' & COM & TR & EQ).\n    edestruct IHP as (P' & STEP & EQ''); [reflexivity | apply TR |].\n    exists (P' ∖ c); split.\n    apply SRes; auto.\n    rewrite use_channel_can_comm.\n    destruct l; auto; destruct e; auto.\n    rewrite <- EQ',EQ,sb_guard, <-EQ''; auto.\n  - trans_parabang_invT TR'.\n    + edestruct IHP as (P' & STEP & EQ''); [reflexivity | apply TRp' |].\n      exists (P' ∥ !P); split.\n      apply SRep, SParL; auto.\n      rewrite <- EQ',EQ,<-EQ''.\n      rewrite parabang_eq.\n      reflexivity.\n    + edestruct IHP as (P' & STEP & EQ''); [reflexivity | apply TRq' |].\n      rewrite EQ in EQ'; clear x EQ.\n      exists (P' ∥ !P); split.\n      apply SRep, SParL; auto.\n      rewrite <- EQ', <-EQ''.\n      cbn.\n      rewrite (paraC ⟦P⟧), parabang_aux, parabang_eq.\n      auto.\n    + edestruct IHP as (P' & STEP & EQ''); [reflexivity | apply TRp' |].\n      edestruct IHP as (P'' & STEP' & EQ'''); [reflexivity | apply TRq' |].\n      exists (P' ∥ (P'' ∥ !P)).\n      split.\n      apply SRep.\n      apply SPar with a.\n      apply STEP.\n      apply are_opposite_sym in Op.\n      rewrite <- (are_opposite_are_op _ Op).\n      apply SRep', STEP'.\n      rewrite <- EQ',EQ,<-EQ'',<-EQ'''.\n      rewrite parabang_eq.\n      cbn.\n      rewrite paraA; auto.\n    + edestruct IHP as (P' & STEP & EQ''); [reflexivity | apply TRq' |].\n      edestruct IHP as (P'' & STEP' & EQ'''); [reflexivity | apply TRq'' |].\n      rewrite EQ in EQ'; clear x EQ.\n      rewrite <- EQ'', <- EQ''' in EQ'.\n      rewrite paraC, parabang_aux, parabang_eq in EQ'.\n      exists (P' ∥ (P'' ∥ !P)).\n      split.\n      apply SRep.\n      apply SPar with a.\n      apply STEP.\n      apply are_opposite_sym in Op.\n      rewrite <- (are_opposite_are_op _ Op).\n      apply SRep', STEP'.\n      rewrite <- EQ'; cbn; rewrite paraA; auto.\nQed.\n\nTheorem term_model_bisimilar : forall P, bisimilar P ⟦P⟧.\nProof.\n  exists bisim_model; split; red; auto using correct,complete.\nQed.\n\n(* We depend currently on\n   - [Eqdep.Eq_rect_eq.eq_rect_eq]\n *)\nPrint Assumptions term_model_bisimilar.\n\nDefinition forward_inv (R : ccs -> term -> Prop) : Prop :=\n  forall p p' Q l,\n\t\tR p Q ->\n\t\ttrans l p p' ->\n\t  exists Q', Q ⊢ γ l →op Q' /\\ R p' Q'.\n\nDefinition backward_inv (R : ccs -> term -> Prop) : Prop :=\n  forall p Q Q' a,\n\t\tR p Q ->\n    Q ⊢ a →op Q' ->\n\t  exists p', trans (ι a) p p' /\\ R p' Q'.\n\nDefinition bisim_inv R := forward_inv R /\\ backward_inv R.\nDefinition bisimilar_inv t u := exists R, bisim_inv R /\\ R t u.\n\nLemma bisimilar_inv_bisim_inv : bisim_inv bisimilar_inv.\nProof.\n split; red; intros * (R & BIS & HR) TR;\n    pose proof BIS as [F B].\n  - edestruct F as (? & ? & ?); eauto; eexists; split; eauto.\n    exists R; split; auto.\n  - edestruct B as (? & ? & ?); eauto; eexists; split; eauto.\n    exists R; split; auto.\nQed.\n\nDefinition rev {A B} (R : A -> B -> Prop) : B -> A -> Prop := fun b a => R a b.\n\nLemma bisim_bisim_inv : forall R, bisim R -> bisim_inv (rev R).\nProof.\n  intros ? [F B]; split; red; unfold rev; cbn; intros * HR TR.\n  edestruct B; eauto.\n  edestruct F; eauto.\nQed.\n\nLemma term_model_bisimilar_inv : forall P, bisimilar_inv ⟦P⟧ P.\nProof.\n  intros P; edestruct (@term_model_bisimilar P) as (R & BIS & HR); eauto.\n  eexists; split.\n  apply bisim_bisim_inv; eauto.\n  auto.\nQed.\n\nLemma ιγ : forall l (t u : ccs),\n    trans l t u ->\n    ι (γ l) = l.\nProof.\n  intros [] ? ? TR; cbn; auto.\n  destruct e,v; auto.\n  eapply trans_val_invT in TR; subst; destruct v.\nQed.\n\nLemma γι : forall l,\n    γ (ι l) = l.\nProof.\n  intros []; auto.\nQed.\n\nLemma cross_model_compose : forall T t u U,\n    bisimilar t T ->\n    Operational.bisim t u ->\n    bisimilar u U ->\n    T ~ U.\nProof.\n  coinduction ? ?.\n  intros * EQtT EQtu EQuU.\n  pose proof bisimilar_bisim as [F B].\n  step in EQtu; destruct EQtu as [F' B'].\n  split; intros ? ? TRTt.\n  - edestruct B as (T' & TRT' & ?); [apply EQtT | |]; eauto.\n    edestruct F' as [U' TRU' ?]; eauto.\n    edestruct F as (u' & TRu' & ?); [apply EQuU | |]; eauto.\n    erewrite ιγ in TRu'; eauto.\n  - edestruct B as (T' & TRT' & ?); [apply EQuU | |]; eauto.\n    edestruct B' as [U' TRU' ?]; eauto.\n    edestruct F as (u' & TRu' & ?); [apply EQtT | |]; eauto.\n    erewrite ιγ in TRu'; eauto.\n    cbn in *; eauto.\nQed.\n\nLemma cross_model_compose' : forall T t u U,\n    bisimilar t T ->\n    T ~ U ->\n    bisimilar u U ->\n    Operational.bisim t u.\nProof.\n  coinduction ? ?.\n  intros * EQtT EQtu EQuU.\n  pose proof bisimilar_bisim as [F B].\n  step in EQtu; destruct EQtu as [F' B'].\n  split; intros ? ? TRTt.\n  - edestruct F as (T' & TRT' & ?); [apply EQtT | |]; eauto.\n    edestruct F' as [U' TRU' ?]; eauto.\n    edestruct B as (u' & TRu' & ?); [apply EQuU | |]; eauto.\n    erewrite γι in TRu'; eauto.\n  - edestruct F as (T' & TRT' & ?); [apply EQuU | |]; eauto.\n    edestruct B' as [U' TRU' ?]; eauto.\n    edestruct B as (u' & TRu' & ?); [apply EQtT | |]; eauto.\n    erewrite γι in TRu'; eauto.\n    cbn in *; eauto.\nQed.\n\nLemma bisimilar_bisimilar_inv : forall t T,\n    bisimilar_inv t T -> bisimilar T t.\nProof.\n  intros * (R & [F B] & HR).\n  exists (rev R); split; [| apply HR].\n  split.\n  red; intros; edestruct B; eauto.\n  red; intros; edestruct F; eauto.\nQed.\n\nLemma embed_sound : forall t u, Operational.bisim t u -> ⟦t⟧ ~ ⟦u⟧.\nProof.\n  intros * BIS.\n  apply (gfp_fp b t u) in BIS; destruct BIS as [F B]; cbn in *.\n  step; split.\n  - intros ? T' TR.\n    pose proof (@term_model_bisimilar t) as BISt.\n    pose proof (@term_model_bisimilar u) as BISu.\n    pose proof bisimilar_bisim as [F' B'].\n    edestruct B' as (t' & TRt & EQTt); [apply BISt | ..]; eauto.\n    edestruct F as [u' TR'' EQtu]; eauto.\n    edestruct F' as (U' & TRu & EQuU); [apply BISu |..]; eauto.\n    erewrite ιγ in TRu; eauto.\n    eexists. apply TRu.\n    eapply cross_model_compose; eauto.\n  - intros ? U' TR.\n    pose proof (@term_model_bisimilar_inv u) as BISu.\n    pose proof (@term_model_bisimilar_inv t) as BISt.\n    pose proof bisimilar_inv_bisim_inv as [F' B'].\n    cbn.\n    edestruct F' as (u' & TRu & EQuU); [apply BISu |..]; eauto.\n    edestruct B as [t' TR'' EQtu]; eauto.\n    edestruct B' as (T' & TRT & EQuT); [apply BISt |..]; eauto.\n    erewrite ιγ in TRT; eauto.\n    eexists. apply TRT.\n    apply bisimilar_bisimilar_inv in EQuU, EQuT.\n    eapply cross_model_compose; eauto.\nQed.\n\nLemma embed_complete : forall t u, ⟦t⟧ ~ ⟦u⟧ -> Operational.bisim t u.\nProof.\n  intros * BIS.\n  step in BIS; destruct BIS as [F B]; cbn in *.\n  step; split.\n  - intros ? T' TR.\n    pose proof (@term_model_bisimilar t) as BISt.\n    pose proof (@term_model_bisimilar u) as BISu.\n    pose proof bisimilar_bisim as [F' B'].\n    edestruct F' as (t' & TRt & EQTt); [apply BISt | ..]; eauto.\n    edestruct F as [u' TR'' EQtu]; eauto.\n    edestruct B' as (U' & TRu & EQuU); [apply BISu |..]; eauto.\n    erewrite γι in TRu; eauto.\n    eexists. apply TRu.\n    eapply cross_model_compose'; eauto.\n  - intros ? U' TR.\n    pose proof (@term_model_bisimilar_inv u) as BISu.\n    pose proof (@term_model_bisimilar_inv t) as BISt.\n    pose proof bisimilar_inv_bisim_inv as [F' B'].\n    cbn.\n    edestruct B' as (u' & TRu & EQuU); [apply BISu |..]; eauto.\n    edestruct B as [t' TR'' EQtu]; eauto.\n    edestruct F' as (T' & TRT & EQuT); [apply BISt |..]; eauto.\n    erewrite γι in TRT; eauto.\n    eexists. apply TRT.\n    apply bisimilar_bisimilar_inv in EQuU, EQuT.\n    eapply cross_model_compose'; eauto.\nQed.\n\nTheorem equiv_bisims : forall t u, ⟦t⟧ ~ ⟦u⟧ <-> Operational.bisim t u.\nProof.\n  intros; split; eauto using embed_complete, embed_sound.\nQed.\n\n", "meta": {"author": "ctrees-popl23", "repo": "ctrees-popl23", "sha": "f3cf2d6325e7e75e12d67bf263b6b5e0ec775b98", "save_path": "github-repos/coq/ctrees-popl23-ctrees-popl23", "path": "github-repos/coq/ctrees-popl23-ctrees-popl23/ctrees-popl23-f3cf2d6325e7e75e12d67bf263b6b5e0ec775b98/examples/CCS/OpDenot.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2663399982461721}}
{"text": "Require Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Maps.\nRequire Import compcert.lib.Integers.\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.Extensionality.\nRequire Import sepcomp.mem_lemmas.\nRequire Import sepcomp.semantics.\nRequire Import sepcomp.semantics_lemmas.\n\n(** * Semantics annotated with Owens-style trace*)\nInductive mem_event :=\n  Write : forall (b : block) (ofs : Z) (bytes : list memval), mem_event\n| Read : forall (b:block) (ofs n:Z) (bytes: list memval), mem_event\n| Alloc: forall (b:block)(lo hi:Z), mem_event\n(*| Lock: drf_event\n| Unlock: drf_event  -- these events are not generated by core steps*)\n| Free: forall (l: list (block * Z * Z)), mem_event.\n\nFixpoint ev_elim (m:mem) (T: list mem_event) (m':mem):Prop :=\n  match T with\n   nil => m'=m\n | (Read b ofs n bytes :: R) => Mem.loadbytes m b ofs n = Some bytes /\\ ev_elim m R m'\n | (Write b ofs bytes :: R) => exists m'', Mem.storebytes m b ofs bytes = Some m'' /\\ ev_elim m'' R m'\n | (Alloc b lo hi :: R) => exists m'', Mem.alloc m lo hi = (m'',b) /\\ ev_elim m'' R m'\n | (Free l :: R) => exists m'', Mem.free_list m l = Some m'' /\\ ev_elim m'' R m'\n  end.\n\nDefinition pmax (popt qopt: option permission): option permission :=\n  match popt, qopt with\n    _, None => popt\n  | None, _ => qopt\n  | Some p, Some q => if Mem.perm_order_dec p q then Some p else Some q\n  end.\n\nLemma po_pmax_I p q1 q2:\n  Mem.perm_order'' p q1 -> Mem.perm_order'' p q2 -> Mem.perm_order'' p (pmax q1 q2).\nProof.\n  intros. destruct q1; destruct q2; simpl in *; trivial.\n  destruct (Mem.perm_order_dec p0 p1); trivial.\nQed.\n\nFixpoint cur_perm (l: block * Z) (T: list mem_event): option permission :=\n  match T with\n      nil => None\n    | (mu :: R) =>\n          let popt := cur_perm l R in\n          match mu, l with\n            | (Read b ofs n bytes), (b',ofs') =>\n                 pmax (if eq_block b b' && zle ofs ofs' && zlt ofs' (ofs+n)\n                       then Some Readable else None) popt\n            | (Write b ofs bytes), (b',ofs') =>\n                 pmax (if eq_block b b' && zle ofs ofs' && zlt ofs' (ofs+ Zlength bytes)\n                       then Some Writable else None) popt\n            | (Alloc b lo hi), (b',ofs') =>  (*we don't add a constraint relating lo/hi/ofs*)\n                 if eq_block b b' then None else popt\n            | (Free l), (b',ofs') =>\n                 List.fold_right (fun tr qopt => match tr with (b,lo,hi) =>\n                                                   if eq_block b b' && zle lo ofs' && zlt ofs' hi\n                                                   then Some Freeable else qopt\n                                                end)\n                                 popt l\n          end\n  end.\n\nLemma po_None popt: Mem.perm_order'' popt None.\nProof. destruct popt; simpl; trivial. Qed.\n\nLemma ev_perm b ofs: forall T m m', ev_elim m T m' ->\n      Mem.perm_order'' ((Mem.mem_access m) !! b ofs Cur) (cur_perm (b,ofs) T).\nProof.\ninduction T; simpl; intros.\n+ subst. apply po_None.\n+ destruct a.\n  - (*Store*)\n     destruct H as [m'' [SB EV]]. specialize (IHT _ _ EV); clear EV.\n     rewrite (Mem.storebytes_access _ _ _ _ _ SB) in *.\n     eapply po_pmax_I; try eassumption.\n     remember (eq_block b0 b && zle ofs0 ofs && zlt ofs (ofs0 + Zlength bytes)) as d.\n     destruct d; try solve [apply po_None].\n     destruct (eq_block b0 b); simpl in *; try discriminate.\n     destruct (zle ofs0 ofs); simpl in *; try discriminate.\n     destruct (zlt ofs (ofs0 + Zlength bytes)); simpl in *; try discriminate.\n     rewrite Zlength_correct in *.\n     apply Mem.storebytes_range_perm in SB.\n     exploit (SB ofs); try omega.\n     intros; subst; assumption.\n  - (*Load*)\n     destruct H as [LB EV]. specialize (IHT _ _ EV); clear EV.\n     eapply po_pmax_I; try eassumption.\n     remember (eq_block b0 b && zle ofs0 ofs && zlt ofs (ofs0 + n)) as d.\n     destruct d; try solve [apply po_None].\n     destruct (eq_block b0 b); simpl in *; try discriminate.\n     destruct (zle ofs0 ofs); simpl in *; try discriminate.\n     destruct (zlt ofs (ofs0 + n)); simpl in *; try discriminate.\n     apply Mem.loadbytes_range_perm in LB.\n     exploit (LB ofs); try omega.\n     intros; subst; assumption.\n  - (*Alloc*)\n     destruct H as [m'' [ALLOC EV]]. specialize (IHT _ _ EV); clear EV.\n     destruct (eq_block b0 b); subst; try solve [apply po_None].\n     eapply po_trans; try eassumption.\n     remember ((Mem.mem_access m'') !! b ofs Cur) as d.\n     destruct d; try solve [apply po_None].\n     symmetry in Heqd.\n     apply (Mem.perm_alloc_4 _ _ _ _ _ ALLOC b ofs Cur p).\n     * unfold Mem.perm; rewrite Heqd. destruct p; simpl; constructor.\n     * intros N; subst; elim n; trivial.\n  - (*Free*)\n     destruct H as [m'' [FR EV]]. specialize (IHT _ _ EV); clear EV.\n     generalize dependent m.\n     induction l; simpl; intros.\n     * inv FR. assumption.\n     * destruct a as [[bb lo] hi].\n       remember (Mem.free m bb lo hi) as p.\n       destruct p; inv FR; symmetry in Heqp. specialize (IHl _ H0).\n       remember (eq_block bb b && zle lo ofs && zlt ofs hi) as d.\n       destruct d.\n       { clear - Heqp Heqd. apply Mem.free_range_perm in Heqp.\n         destruct (eq_block bb b); simpl in Heqd; inv Heqd.\n         exploit (Heqp ofs); clear Heqp; trivial.\n         destruct (zle lo ofs); try discriminate.\n         destruct (zlt ofs hi); try discriminate. omega. }\n       { eapply po_trans; try eassumption. clear - Heqp.\n         remember ((Mem.mem_access m0) !! b ofs Cur) as perm2.\n         destruct perm2; try solve [apply po_None].\n         exploit (Mem.perm_free_3 _ _ _ _ _ Heqp); unfold Mem.perm.\n            rewrite <- Heqperm2. apply perm_refl.\n         simpl; trivial. }\nQed.\n\nLemma ev_elim_app: forall T1 m1 m2 (EV1:ev_elim m1 T1 m2) T2 m3  (EV2: ev_elim m2 T2 m3), ev_elim m1 (T1++T2) m3.\nProof.\n  induction T1; simpl; intros; subst; trivial.\n  destruct a.\n+ destruct EV1 as [mm [SB EV]]. specialize (IHT1 _ _ EV _ _ EV2).\n  exists mm; split; trivial.\n+ destruct EV1 as [LB EV]. specialize (IHT1 _ _ EV _ _ EV2).\n  split; trivial.\n+ destruct EV1 as [mm [AL EV]]. specialize (IHT1 _ _ EV _ _ EV2).\n  exists mm; split; trivial.\n+ destruct EV1 as [mm [FL EV]]. specialize (IHT1 _ _ EV _ _ EV2).\n  exists mm; split; trivial.\nQed.\n\nLemma ev_elim_split: forall T1 T2 m1 m3 (EV1:ev_elim m1 (T1++T2) m3),\n      exists m2, ev_elim m1 T1 m2 /\\ ev_elim m2 T2 m3.\nProof.\n  induction T1; simpl; intros.\n+ exists m1; split; trivial.\n+ destruct a.\n  - destruct EV1 as [mm [SB EV]]. destruct (IHT1 _ _ _ EV) as [m2 [EV1 EV2]].\n    exists m2; split; trivial. exists mm; split; trivial.\n  - destruct EV1 as [LB EV]. destruct (IHT1 _ _ _ EV) as [m2 [EV1 EV2]].\n    exists m2; split; trivial. split; trivial.\n  - destruct EV1 as [mm [AL EV]]. destruct (IHT1 _ _ _ EV) as [m2 [EV1 EV2]].\n    exists m2; split; trivial. exists mm; split; trivial.\n  - destruct EV1 as [mm [SB EV]]. destruct (IHT1 _ _ _ EV) as [m2 [EV1 EV2]].\n    exists m2; split; trivial. exists mm; split; trivial.\nQed.\n\n(** Similar to effect semantics, event semantics augment memory semantics with suitable effects, in the form\n    of a set of memory access traces associated with each internal\n    step of the semantics. *)\n\nRecord EvSem {G C} :=\n  { (** [sem] is a memory semantics. *)\n    msem :> @MemSem G C\n\n    (** The step relation of the new semantics. *)\n  ; ev_step: G -> C -> mem -> list mem_event -> C -> mem -> Prop\n\n    (** The next four fields axiomatize [drfstep] and its relation to the\n        underlying step relation of [msem]. *)\n  ; ev_step_ax1: forall g c m T c' m',\n       ev_step g c m T c' m' ->\n            corestep msem g c m c' m'\n  ; ev_step_ax2: forall g c m c' m',\n       corestep msem g c m c' m' ->\n       exists T, ev_step g c m T c' m'\n  ; ev_step_fun: forall g c m T' c' m' T'' c'' m'',\n       ev_step g c m T' c' m' -> ev_step g c m T'' c'' m'' -> T'=T''\n(*  ; ev_step_elim: forall g c m T c' m',\n       ev_step g c m T c' m' -> ev_elim m T m'*)\n  ; ev_step_elim: forall g c m T c' m' (STEP: ev_step g c m T c' m'),\n       ev_elim m T m' /\\\n       (forall mm mm', ev_elim mm T mm' -> exists cc', ev_step g c mm T cc' mm')\n  }.\n\nLemma Ev_sem_cur_perm {G C} (R: @EvSem G C) g c m T c' m' b ofs (D: ev_step R g c m T c' m'):\n      Mem.perm_order'' ((Mem.mem_access m) !! b ofs Cur) (cur_perm (b,ofs) T).\nProof. eapply ev_perm. eapply ev_step_elim; eassumption. Qed.\n(*\nArguments EvSem G C.\n*)\n\nRequire Import List.\nImport ListNotations.\n\nDefinition in_free_list (b : block) ofs xs :=\n  exists x, List.In x xs /\\\n       let '(b', lo, hi) := x in\n       b = b' /\\\n       (lo <= ofs < hi)%Z.\n\n\nFixpoint in_free_list_trace (b : block) ofs es :=\n  match es with\n  | Free l :: es =>\n    in_free_list b ofs l \\/ in_free_list_trace b ofs es\n  | _ :: es =>\n    in_free_list_trace b ofs es\n  | nil =>\n    False\n  end.\n\n(*not needed later - not sure it's useful*)\nLemma EFLT_char es: forall b ofs, in_free_list_trace b ofs es <->\n                             exists l lo hi, In (Free l) es /\\ In ((b, lo), hi) l /\\ lo <= ofs < hi.\nProof. induction es; simpl.\n       + split; intros; try contradiction. destruct H as [? [? [? [? ?]]]]. contradiction.\n       + intros.\n       - destruct a.\n         * destruct (IHes b ofs).\n           split; intros.\n           ++ destruct (H H1) as [? [? [? [? ?]]]]. eexists; eexists; eexists. split. right. apply H2. apply H3.\n           ++ destruct H1 as [? [? [? [? ?]]]].\n              destruct H1. discriminate. apply H0.  eexists; eexists; eexists. split. eassumption. apply H2.\n         * destruct (IHes b ofs).\n           split; intros.\n           ++ destruct (H H1) as [? [? [? [? ?]]]]. eexists; eexists; eexists. split. right. apply H2. apply H3.\n           ++ destruct H1 as [? [? [? [? ?]]]].\n              destruct H1. discriminate. apply H0.  eexists; eexists; eexists. split. eassumption. apply H2.\n         * destruct (IHes b ofs).\n           split; intros.\n           ++ destruct (H H1) as [? [? [? [? ?]]]]. eexists; eexists; eexists. split. right. apply H2. apply H3.\n           ++ destruct H1 as [? [? [? [? ?]]]].\n              destruct H1. discriminate. apply H0.  eexists; eexists; eexists. split. eassumption. apply H2.\n         * destruct (IHes b ofs).\n           split; intros.\n           ++ destruct H1. destruct H1 as [[[? ?] ?] [? [? ?]]]; subst b0. exists l, z, z0. split; eauto.\n              destruct (H H1) as [? [? [? [? ?]]]]. eexists; eexists; eexists. split. right. apply H2. apply H3.\n           ++ destruct H1 as [? [? [? [? [? ?]]]]].\n              destruct H1. inv H1. left. red. exists ((b,x0),x1). split; trivial. split; trivial.\n              right. apply H0. exists x, x0 , x1. split; trivial. split; trivial.\nQed.\n\nLemma freelist_mem_access_1 b ofs p: forall l m (ACC:(Mem.mem_access m) !! b ofs Cur = Some p)\n                                       m1 (FL: Mem.free_list m1 l = Some m), (Mem.mem_access m1) !! b ofs Cur = Some p.\nProof. induction l; simpl; intros. inv FL; trivial.\n       destruct a. destruct p0.\n       case_eq (Mem.free m1 b0 z0 z); intros; rewrite H in FL; try discriminate.\n       eapply free_access_inv; eauto.\nQed.\n\nLemma freelist_access_2 b ofs: forall l  (FL: in_free_list b ofs l)\n                                 m m' (FR : Mem.free_list m l = Some m'),\n    (Mem.mem_access m') !! b ofs Cur = None /\\ Mem.valid_block m' b.\nProof. intros l FL. destruct FL as [[[? ?] ?] [? [? ?]]]; subst b0.\n       induction l; simpl; intros.\n       - inv H.\n       - destruct H.\n         * subst. case_eq (Mem.free m b z z0); intros; rewrite H in FR; try discriminate.\n           clear IHl. case_eq ((Mem.mem_access m') !! b ofs Cur); intros; trivial.\n           ++ exploit freelist_mem_access_1. eassumption. eassumption. intros XX.\n              exfalso. apply Mem.free_result in H. subst m0. simpl in XX.\n              rewrite PMap.gss in XX. case_eq (zle z ofs && zlt ofs z0); intros; rewrite H in *; try discriminate.\n              destruct (zle z ofs); try omega; simpl  in *. destruct ( zlt ofs z0); try omega. inv H.\n           ++ split; trivial. eapply freelist_forward; eauto.\n              exploit Mem.free_range_perm. eassumption. eassumption. intros.\n              eapply Mem.valid_block_free_1; try eassumption. eapply Mem.perm_valid_block; eauto.\n         * destruct a. destruct p.\n           case_eq (Mem.free m b0 z2 z1); intros; rewrite H0 in FR; try discriminate. eauto.\nQed.\n\nLemma freelist_access_3 b ofs: forall l m (ACC: (Mem.mem_access m) !! b ofs Cur = None)\n                                 (VB: Mem.valid_block m b) m' (FL: Mem.free_list m l = Some m'),\n    (Mem.mem_access m') !! b ofs Cur = None.\nProof. induction l; simpl; intros.\n       + inv FL; trivial.\n       + destruct a as [[? ?] ?].\n         case_eq (Mem.free m b0 z z0); intros; rewrite H in FL; try discriminate.\n         eapply (IHl m0); trivial.\n       - destruct (eq_block b0 b); subst. apply Mem.free_result in H. subst. simpl. rewrite PMap.gss, ACC. destruct (zle z ofs && zlt ofs z0); trivial.\n         apply Mem.free_result in H. subst. simpl. rewrite PMap.gso; eauto.\n       - eapply Mem.valid_block_free_1; eauto.\nQed.\n\nLemma ev_elim_accessNone b ofs: forall ev m' m'' (EV:ev_elim m'' ev m')\n                                  (ACC: (Mem.mem_access m'') !! b ofs Cur = None)\n                                  (VB: Mem.valid_block m'' b), (Mem.mem_access m') !! b ofs Cur = None.\nProof.  induction ev; simpl; intros. subst; trivial.\n        destruct a.\n        - destruct EV as [? [? EV]]. exploit Mem.storebytes_valid_block_1; eauto. intros.\n          apply Mem.storebytes_access in H. rewrite <- H in *; clear H.\n          apply (IHev _ _ EV ACC H0).\n        - destruct EV as [? EV]. eauto.\n        - destruct EV as [? [? EV]].\n          apply (IHev _ _ EV); clear IHev EV.\n          + Transparent Mem.alloc.\n            unfold Mem.alloc in H. Opaque Mem.alloc.  inv H. simpl. rewrite PMap.gso; trivial. unfold Mem.valid_block in VB. xomega.\n          + eapply Mem.valid_block_alloc; eauto.\n        - destruct EV as [? [? EV]]. apply (IHev _ _ EV); clear IHev.\n          2: eapply freelist_forward; eauto.\n          clear EV ev m'.\n          eapply freelist_access_3; eassumption.\nQed.\n\nLemma ev_elim_valid_block: forall ev m m' (EV: ev_elim m ev m') b\n                             (VB : Mem.valid_block m b), Mem.valid_block m' b.\nProof. induction ev; simpl; intros; subst; trivial.\n       destruct a.\n       + destruct EV as [? [? EV]]. exploit Mem.storebytes_valid_block_1. apply H. eassumption. eauto.\n       + destruct EV as [? EV]. eauto.\n       + destruct EV as [? [? EV]]. exploit Mem.valid_block_alloc. apply H. eassumption. eauto.\n       + destruct EV as [? [? EV]]. exploit freelist_forward; eauto. intros [? _]. eauto.\nQed.\n\n\n(** If (b, ofs) is in the list of freed addresses then the\n         permission was Freeable and became None or it was not allocated*)\nLemma ev_elim_free_1 b ofs:\n  forall ev m m',\n    ev_elim m ev m' ->\n    in_free_list_trace b ofs ev ->\n    (Mem.perm m b ofs Cur Freeable \\/\n     ~ Mem.valid_block m b) /\\\n    (Mem.mem_access m') !! b ofs Cur = None /\\\n    Mem.valid_block m' b /\\\n    exists e, List.In e ev /\\\n         match e with\n         | Free _ => True\n         | _ => False\n         end.\nProof.\n  induction ev; simpl; intros; try contradiction.\n  destruct a.\n  + destruct H as [m'' [ST EV]].\n    specialize (Mem.storebytes_access _ _ _ _ _ ST); intros ACCESS.\n    destruct (eq_block b0 b); subst.\n  - destruct (IHev _ _ EV H0) as [IHa [IHb [IHc [e [E HE]]]]]; clear IHev.\n    split. { destruct IHa. left. eapply Mem.perm_storebytes_2; eauto.\n             right. intros N. apply H. eapply Mem.storebytes_valid_block_1; eauto. }\n           split; trivial.\n    split; trivial.\n    exists e. split; trivial. right; trivial.\n  - destruct (IHev _ _ EV H0) as [IHa [IHb [IHc [e [E HE]]]]]; clear IHev.\n    split. { destruct IHa. left. eapply Mem.perm_storebytes_2; eassumption.\n             right; intros N. apply H. eapply Mem.storebytes_valid_block_1; eauto. }\n           split. trivial.\n    split; trivial. exists e. split; trivial. right; trivial.\n    + destruct H.\n      destruct (IHev _ _ H1 H0) as [IHa [IHb [IHc [e [E HE]]]]]; clear IHev.\n      split; trivial.\n      split; trivial.\n      split; trivial.\n      exists e. split; trivial. right; trivial.\n    + destruct H as [m'' [ALLOC EV]].\n      destruct (IHev _ _ EV H0) as [IHa [IHb [IHc [e [E HE]]]]]; clear IHev.\n      destruct (eq_block b0 b); subst.\n  - split. right. eapply Mem.fresh_block_alloc. eauto.\n    split; trivial.\n    split; trivial.\n    exists e.\n    split; trivial. right; trivial.\n  - split. { destruct IHa. left. eapply Mem.perm_alloc_4; eauto.\n             right; intros N. apply H. eapply Mem.valid_block_alloc; eauto. }\n           split; trivial.\n    split; trivial.\n    exists e. split; trivial. right; trivial.\n    + destruct H as [m'' [FR EV]].\n      destruct H0.\n  - clear IHev.\n    split. { destruct (valid_block_dec m b). 2: right; trivial. left.\n             clear EV m'. generalize dependent m''. generalize dependent m.\n             destruct H as [[[bb lo] hi] [X [? Y]]]; subst bb.\n             induction l; simpl in *; intros. contradiction.\n             destruct X; subst.\n             + case_eq (Mem.free m b lo hi); intros; rewrite H in FR; try discriminate.\n               eapply Mem.free_range_perm; eassumption.\n             + destruct a. destruct p.\n               case_eq (Mem.free m b0 z0 z); intros; rewrite H0 in FR; try discriminate.\n               eapply Mem.perm_free_3. eassumption.\n               eapply IHl; try eassumption.\n               eapply Mem.valid_block_free_1; eauto. }\n           split. { exploit freelist_access_2. eassumption. eassumption.\n                    intros [ACC VB].  clear FR m l H.\n                    eapply ev_elim_accessNone; eauto. }\n                  split. { exploit freelist_access_2; eauto. intros [ACC VB].\n                           eapply ev_elim_valid_block; eauto. }\n                         exists (Free l). intuition.\n  - destruct (IHev _ _ EV H) as [IHa [IHb [IHc [e [E HE]]]]]; clear IHev.\n    split. { destruct IHa. left. eapply perm_freelist; eauto.\n             right; intros N. apply H0. eapply freelist_forward; eauto. }\n           split; trivial.\n    split; trivial.\n    exists e. split; trivial. right; trivial.\nQed.\n\nLemma perm_order_pp_refl p: Mem.perm_order'' p p.\nProof. unfold Mem.perm_order''. destruct p; trivial. apply perm_refl. Qed.\n\nLemma in_free_list_dec b ofs xs: {in_free_list b ofs xs} + {~in_free_list b ofs xs}.\nProof. unfold in_free_list.\n       induction xs; simpl. right. intros N. destruct N as [[[? ?] ?] [? _]]. trivial.\n       destruct IHxs.\n       + left. destruct e as [? [? ?]]. exists x. split; eauto.\n       + destruct a as [[? ?] ?].\n         destruct (eq_block b0 b); subst.\n       - destruct (zle z ofs).\n         * destruct (zlt ofs z0). -- left. exists (b, z, z0). split; eauto.\n           -- right. intros [[[? ?] ?] [? [? ?]]]. subst b0.\n              destruct H. inv H. omega. apply n; clear n.\n              exists (b, z1, z2). split; eauto.\n         * right. intros [[[? ?] ?] [? [? ?]]]. subst b0.\n           destruct H. inv H. omega. apply n; clear n.\n           exists (b, z1, z2). split; eauto.\n       - right. intros [[[? ?] ?] [? [? ?]]]. subst b1.\n         destruct H. inv H. congruence.\n         apply n; clear n. exists (b, z1, z2). split; eauto.\nQed.\n\nLemma in_free_list_trace_dec b ofs: forall es, {in_free_list_trace b ofs es} + {~in_free_list_trace b ofs es}.\nProof.\n  induction es; simpl. right; intros N; trivial.\n  destruct IHes.\n  + destruct a; try solve [left; eauto].\n  + destruct a; try solve [right; eauto].\n    destruct (in_free_list_dec b ofs l). left; left; trivial.\n    right; intros N. destruct N; contradiction.\nQed.\n\nLemma freelist_access_1 b ofs: forall l,\n    ~ in_free_list b ofs l ->\n    forall m m' : mem, Mem.free_list m l = Some m' -> (Mem.mem_access m') !! b ofs Cur = (Mem.mem_access m) !! b ofs Cur.\nProof.\n  induction l; simpl; intros. inv H0. trivial.\n  destruct a as [[? ?] ?].\n  remember (Mem.free m b0 z z0) as q; destruct q; try discriminate. symmetry in Heqq.\n  assert (~ in_free_list b ofs l). { intros N. elim H. destruct N as [? [? ?]]. exists x. split; eauto. right; trivial. }\n                                   rewrite (IHl H1 _ _ H0). clear IHl H0.\n  Transparent Mem.free. unfold Mem.free in Heqq.\n  remember (Mem.range_perm_dec m b0 z z0 Cur Freeable).\n  destruct s; inv Heqq; clear Heqs. simpl.\n  rewrite PMap.gsspec. destruct (peq b b0); subst; trivial.\n  destruct (zle z ofs); simpl; trivial.\n  destruct (zlt ofs z0); simpl; trivial.\n  elim H. unfold in_free_list. exists (b0, z, z0). split; eauto. left; trivial.\nQed.\n\n(** If (b, ofs) is not in the list of freed locations then its permissions\ncannot decrease*)\nLemma ev_elim_free_2 b ofs:\n  forall ev m m' (EV: ev_elim m ev m')\n    (T: ~ in_free_list_trace b ofs ev),\n    Mem.perm_order'' ((Mem.mem_access m') !! b ofs Cur)\n                     ((Mem.mem_access m) !! b ofs Cur).\nProof.\n  induction ev; simpl; intros.\n  + subst. apply perm_order_pp_refl.\n  + destruct a.\n  - destruct EV  as [m'' [ST EV]].\n    apply Mem.storebytes_access in ST. rewrite <- ST. apply (IHev _ _ EV T).\n  - destruct EV  as [LD EV].\n    apply (IHev _ _ EV T).\n  - destruct EV  as [m'' [ALLOC EV]].\n    eapply po_trans. apply (IHev _ _ EV T). clear IHev.\n    unfold Mem.perm_order''. remember ((Mem.mem_access m'') !! b ofs Cur) as q.\n    symmetry in Heqq; destruct q.\n    * exploit Mem.perm_alloc_inv. eassumption. unfold Mem.perm. rewrite Heqq. simpl. apply perm_refl.\n      destruct (eq_block b b0); simpl; intros; subst.\n      ++ rewrite Mem.nextblock_noaccess; trivial. intros N.\n         eapply Mem.fresh_block_alloc; eassumption.\n      ++ Transparent Mem.alloc. unfold Mem.alloc in ALLOC. inv ALLOC. simpl in *. clear EV.\n         Opaque Mem.alloc.\n         remember ((Mem.mem_access m) !! b ofs Cur) as r. destruct r; trivial. symmetry in Heqr.\n         rewrite PMap.gso in Heqq; trivial. rewrite Heqq in Heqr. inv Heqr. apply perm_refl.\n    * erewrite alloc_access_inv_None; eauto.\n  - destruct EV  as [m'' [FR EV]]. specialize (IHev _ _ EV).\n    destruct (in_free_list_dec b ofs l).\n    * elim T. left; trivial.\n    * destruct (in_free_list_trace_dec b ofs ev).\n      elim T. right; trivial.\n      eapply po_trans. apply IHev; trivial.\n      erewrite freelist_access_1; eauto. apply perm_order_pp_refl.\nQed.\n\nLemma free_list_cases:\n  forall l m m' b ofs\n    (Hfree: Mem.free_list m l = Some m'),\n    ((Mem.mem_access m) !! b ofs Cur = Some Freeable /\\\n     (Mem.mem_access m') !! b ofs Cur = None) \\/\n    ((Mem.mem_access m) !! b ofs Cur =\n     (Mem.mem_access m') !! b ofs Cur).\nProof.\n  induction l; simpl; intros. inv Hfree. right; trivial.\n  destruct a as [[bb lo] hi].\n  remember (Mem.free m bb lo hi) as q; symmetry in Heqq. destruct q; inv Hfree.\n  specialize (IHl _ _ b ofs H0); clear H0.\n  Transparent Mem.free. unfold Mem.free in Heqq. Opaque Mem.free.\n  remember (Mem.range_perm_dec m bb lo hi Cur Freeable). destruct s; try discriminate. inv Heqq. clear Heqs.\n  simpl in *.\n  rewrite PMap.gsspec in *.\n  destruct (peq b bb); subst; trivial.\n  destruct IHl.\n  + destruct H.\n    rewrite H0; clear H0.\n    destruct (zle lo ofs); try discriminate; simpl in *.\n  - destruct (zlt ofs hi); try discriminate; simpl in *. rewrite H. left; split; trivial.\n  - rewrite H. left; split; trivial.\n    + destruct (zle lo ofs); simpl in *; try solve [right; trivial].\n      destruct (zlt ofs hi); simpl in *; try solve [right; trivial].\n      rewrite <- H; clear H.\n      assert (A: lo <= ofs < hi) by omega.\n      specialize (r _ A). unfold Mem.perm, Mem.perm_order' in r.\n      remember ((Mem.mem_access m) !! bb ofs Cur) as q. destruct q; try contradiction.\n      left; split; trivial. destruct p; simpl in *; trivial; inv r.\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/sepcomp/event_semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2663168884693415}}
{"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.\n\nRequire Import Mapping.\n\nRequire Import PFStep.\nRequire Import OrdStep.\n\nSet Implicit Arguments.\n\n\nModule ReleaseWrites.\n  Section ReleaseWrites.\n    Variable L: Loc.t -> bool.\n\n    Definition t: Type := list (Loc.t * Time.t).\n\n    Definition append (e: ThreadEvent.t) (rels: t): t :=\n      match ThreadEvent.is_writing e with\n      | Some (loc, from, to, val, released, ord) =>\n        if L loc\n        then if Ordering.le Ordering.acqrel ord then (loc, to) :: rels else rels\n        else rels\n      | None => rels\n      end.\n\n    Definition wf (rels: t) (promises mem: Memory.t): Prop :=\n      forall loc to (IN: List.In (loc, to) rels),\n        Memory.get loc to promises = None /\\\n        exists from val released,\n          Memory.get loc to mem = Some (from, Message.concrete val released).\n\n    Lemma append_app e rels1 rels2:\n      append e rels1 ++ rels2 = append e (rels1 ++ rels2).\n    Proof.\n      unfold append. des_ifs.\n    Qed.\n  End ReleaseWrites.\nEnd ReleaseWrites.\n\n\nModule RAThread.\n  Section RAThread.\n    Variable lang: language.\n    Variable L: Loc.t -> bool.\n\n    Inductive step rels1: forall (rels2: ReleaseWrites.t) (e: ThreadEvent.t) (e1 e2: Thread.t lang), Prop :=\n    | step_intro\n        pf e e1 e2\n        (STEP: @OrdThread.step lang L Ordering.acqrel pf e e1 e2):\n        step rels1 (ReleaseWrites.append L e rels1) e e1 e2\n    .\n\n    Inductive steps rels1: forall (rels2: ReleaseWrites.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.\n\n    Inductive tau_steps rels1: forall (rels2: ReleaseWrites.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.\n\n    Inductive opt_step rels1: forall (rels2: ReleaseWrites.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.\n\n\n    Lemma step_ord_step\n          rels1 rels2 e e1 e2\n          (STEP: step rels1 rels2 e e1 e2):\n      exists pf, OrdThread.step L Ordering.acqrel pf e e1 e2.\n    Proof.\n      inv STEP. 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 Ordering.acqrel) 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 Ordering.acqrel) 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 Ordering.acqrel) 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 (ReleaseWrites.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            (ReleaseWrites.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.\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            (ReleaseWrites.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 Ordering.acqrel) 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          (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; 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          (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; 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          (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; 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          (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; eauto.\n      inv STEP0; eauto using OrdThread.step_disjoint.\n    Qed.\n\n\n    (* ReleaseWrites.wf *)\n\n    Lemma promise_rels_wf\n          rels promises1 mem1 loc from to msg promises2 mem2 kind\n          (RELS1: ReleaseWrites.wf rels promises1 mem1)\n          (PROMISE: Memory.promise promises1 mem1 loc from to msg promises2 mem2 kind):\n      ReleaseWrites.wf rels promises2 mem2.\n    Proof.\n      ii. exploit RELS1; eauto. i. des. inv PROMISE; ss.\n      - exploit Memory.add_get1; try exact x0; eauto. i. esplits; eauto.\n        erewrite Memory.add_o; eauto. condtac; ss. des. subst.\n        exploit Memory.add_get0; try exact MEM. i. des. congr.\n      - exploit Memory.split_get1; try exact x0; eauto. i. des. subst. esplits; eauto.\n        erewrite Memory.split_o; eauto. repeat condtac; ss.\n        + des. subst. exploit Memory.split_get0; try exact MEM. i. des. congr.\n        + guardH o. des. subst.\n          exploit Memory.split_get0; try exact PROMISES. i. des. congr.\n      - exploit Memory.lower_get1; try exact x0; eauto. i. des. subst. inv MSG_LE.\n        esplits; eauto.\n        erewrite Memory.lower_o; eauto. condtac; ss. des. subst.\n        exploit Memory.lower_get0; try exact PROMISES. i. des. congr.\n      - erewrite (@Memory.remove_o promises2); eauto.\n        erewrite (@Memory.remove_o mem2); eauto. condtac; ss; eauto.\n        des. subst. exploit Memory.remove_get0; try exact PROMISES. i. des. congr.\n    Qed.\n\n    Lemma step_rels_wf\n          rels1 rels2 e e1 e2\n          (RELS1: ReleaseWrites.wf rels1 (Local.promises (Thread.local e1)) (Thread.memory e1))\n          (STEP: step rels1 rels2 e e1 e2):\n      ReleaseWrites.wf rels2 (Local.promises (Thread.local e2)) (Thread.memory e2).\n    Proof.\n      inv STEP. unfold ReleaseWrites.append.\n      inv STEP0; inv STEP; inv LOCAL; ss.\n      - eauto using promise_rels_wf.\n      - inv LOCAL0. inv STEP. ss.\n      - inv LOCAL0. inv STEP. inv WRITE. ss.\n        hexploit promise_rels_wf; eauto. i.\n        cut (ReleaseWrites.wf rels1 promises2 mem2).\n        { i. repeat condtac; ss. ii. inv IN; eauto. inv H1.\n          exploit Memory.promise_get0; eauto; try by (inv PROMISE; ss). i. des.\n          exploit Memory.remove_get0; eauto. i. des.\n          esplits; eauto. }\n        ii. exploit H; eauto. i. des. esplits; eauto.\n        erewrite Memory.remove_o; eauto. condtac; ss.\n      - inv LOCAL1. inv STEP. inv LOCAL2. inv STEP. inv WRITE. ss.\n        hexploit promise_rels_wf; eauto. i.\n        cut (ReleaseWrites.wf rels1 promises2 mem2).\n        { i. repeat condtac; ss. ii. inv IN; eauto. inv H1.\n          exploit Memory.promise_get0; eauto; try by (inv PROMISE; ss). i. des.\n          exploit Memory.remove_get0; eauto. i. des.\n          esplits; eauto. }\n        ii. exploit H; eauto. i. des. esplits; eauto.\n        erewrite Memory.remove_o; eauto. condtac; ss.\n      - inv LOCAL0. ss.\n      - inv LOCAL0. ss.\n    Qed.\n\n    Lemma steps_rels_wf\n          rels1 rels2 e1 e2\n          (RELS1: ReleaseWrites.wf rels1 (Local.promises (Thread.local e1)) (Thread.memory e1))\n          (STEPS: steps rels1 rels2 e1 e2):\n      ReleaseWrites.wf rels2 (Local.promises (Thread.local e2)) (Thread.memory e2).\n    Proof.\n      induction STEPS; eauto.\n      apply IHSTEPS. eapply step_rels_wf; eauto.\n    Qed.\n\n    Lemma promise_rels_disjoint\n          promises1 mem1 loc from to msg promises2 mem2 kind\n          promises\n          (PROMISE: Memory.promise promises1 mem1 loc from to msg promises2 mem2 kind)\n          (DISJOINT: Memory.disjoint promises1 promises)\n          (LE: Memory.le promises mem1):\n      Memory.get loc to promises = None.\n    Proof.\n      destruct (Memory.get loc to promises) as [[]|] eqn:GETP; ss.\n      exploit LE; eauto. i.\n      inv PROMISE; ss.\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.\n        inv DISJOINT. exploit DISJOINT0; eauto. i. des. exfalso.\n        exploit Memory.get_ts; try exact GETP. i. des; try congr.\n        exploit Memory.get_ts; try exact GET. i. des; try congr.\n        apply (x0 to); econs; try refl; ss.\n      - exploit Memory.remove_get0; try exact PROMISES. i. des.\n        inv DISJOINT. exploit DISJOINT0; eauto. i. des. exfalso.\n        exploit Memory.get_ts; try exact GETP. i. des; try congr.\n        exploit Memory.get_ts; try exact GET. i. des; try congr.\n        apply (x0 to); econs; try refl; ss.\n    Qed.\n\n    Lemma step_rels_disjoint\n          rels1 rels2 e e1 e2 promises\n          (RELS1: ReleaseWrites.wf 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: ReleaseWrites.wf rels1 promises (Thread.memory e1)):\n      ReleaseWrites.wf rels2 promises (Thread.memory e2).\n    Proof.\n      hexploit step_rels_wf; eauto. ii.\n      exploit H; eauto. i. des. esplits; eauto.\n      inv STEP. unfold ReleaseWrites.append in *.\n      inv STEP0; inv STEP; inv LOCAL; ss.\n      - exploit RELS; eauto. i. des. ss.\n      - exploit RELS; eauto. i. des. ss.\n      - exploit RELS; eauto. i. des. ss.\n      - inv LOCAL0. inv STEP. inv WRITE. ss. revert IN.\n        repeat condtac; ss; i; des; try by (exploit RELS; eauto; i; des; ss).\n        inv IN. eapply promise_rels_disjoint; eauto.\n      - inv LOCAL1. inv STEP. inv LOCAL2. inv STEP. inv WRITE. ss. revert IN.\n        repeat condtac; ss; i; des; try by (exploit RELS; eauto; i; des; ss).\n        inv IN. eapply promise_rels_disjoint; eauto.\n      - exploit RELS; eauto. i. des. ss.\n      - exploit RELS; eauto. i. des. ss.\n      - exploit RELS; eauto. i. des. ss.\n    Qed.\n\n    Lemma steps_rels_disjoint\n          rels1 rels2 e1 e2 lc\n          (RELS1: ReleaseWrites.wf 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: ReleaseWrites.wf rels1 (Local.promises lc) (Thread.memory e1)):\n      ReleaseWrites.wf 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_rels_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\n    Lemma cap_tau_steps_current_tau_steps\n          rels0 rels1 e0 e1 fe0\n          (THREAD: thread_map ident_map e0 fe0)\n          (STEPS: tau_steps rels0 rels1 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        exists fe1,\n          (<<THREAD: thread_map ident_map e1 fe1>>) /\\\n          (<<STEPS: tau_steps rels0 rels1 fe0 fe1>>).\n    Proof.\n      ginduction STEPS; eauto. i.\n      inv STEP; ss.\n      exploit OrdThread.cap_step_current_step; eauto. i. des.\n      exploit OrdThread.step_future; try apply STEP; eauto. i. des.\n      exploit OrdThread.step_future; try apply STEP0; eauto. i. des.\n      exploit IHSTEPS; eauto. i. des. exists fe2. splits; eauto.\n      replace (ReleaseWrites.append L e rels1) with (ReleaseWrites.append L fe rels1) in STEPS0; cycle 1.\n      { unfold ReleaseWrites.append. destruct e; inv EVENT; ss.\n        - inv FROM. inv TO. refl.\n        - inv FROM. inv TO. refl. }\n      econs; [econs 1; eauto|..]; eauto.\n      destruct e; inv EVENT; ss.\n    Qed.\n\n    Lemma cap_plus_step_current_plus_step\n          rels1 rels2 rels3 e e1 e2 e3 sc1 mem1\n          (LOCAL: Local.wf (Thread.local e1) (Thread.memory e1))\n          (MEMORY: Memory.closed (Thread.memory e1))\n          (SC: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CAP: Memory.cap (Thread.memory e1) mem1)\n          (SC_MAX: Memory.max_concrete_timemap mem1 sc1)\n          (STEPS: tau_steps rels1 rels2 (Thread.mk lang (Thread.state e1) (Thread.local e1) sc1 mem1) e2)\n          (STEP: RAThread.step rels2 rels3 e e2 e3):\n        exists rels3' e' e2' e3',\n          (<<STEPS: tau_steps rels1 rels2 e1 e2'>>) /\\\n          (<<STEP: RAThread.step rels2 rels3' e' e2' e3'>>) /\\\n          (<<LOCAL: local_map ident_map (Thread.local e2) (Thread.local e2')>>) /\\\n          (<<EVENT: tevent_map ident_map e' e>>).\n    Proof.\n      exploit cap_tau_steps_current_tau_steps; try apply STEPS; eauto; ss.\n      { destruct e1. ss. econs; eauto.\n        { eapply ident_map_local. }\n        { econs.\n          { i. eapply Memory.cap_inv in GET; eauto. des; auto.\n            right. exists to, from, msg, msg; splits; ss.\n            { eapply ident_map_message. }\n            { refl. }\n          }\n          { i. eapply CAP in GET. left. esplits; ss.\n            { refl. }\n            { refl. }\n            { i. econs; eauto. }\n          }\n        }\n        { eapply mapping_map_lt_collapsable_unwritable. eapply ident_map_lt. }\n        { eapply ident_map_timemap. }\n        { eapply Memory.max_concrete_timemap_spec; eauto.\n          eapply Memory.cap_closed_timemap; eauto. }\n      }\n      { eapply Local.cap_wf; eauto. }\n      { eapply Memory.cap_closed; eauto. }\n      { eapply Memory.max_concrete_timemap_closed; eauto. }\n      i. des.\n      exploit steps_future; try eapply tau_steps_steps; try apply STEPS; ss.\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 steps_future; try eapply tau_steps_steps; try apply STEPS0; ss. i. des.\n      inv STEP.\n      exploit OrdThread.cap_step_current_step; eauto. i. des.\n      esplits; eauto.\n      - econs; eauto.\n      - inv THREAD. ss.\n    Qed.\n\n\n    (* promises get *)\n\n    Lemma promise_get_None\n          promises1 mem1 loc' from' to' msg' promises2 mem2 kind\n          loc from to msg\n          (PROMISE: Memory.promise promises1 mem1 loc' from' to' msg' promises2 mem2 kind)\n          (PROMISES1: Memory.get loc to promises1 = None)\n          (MEM1: Memory.get loc to mem1 = Some (from, msg)):\n      (<<PROMISES2: Memory.get loc to promises2 = None>>) /\\\n      (<<MEM2: Memory.get loc to mem2 = Some (from, msg)>>) /\\\n      (<<LOCTS: __guard__ (loc' <> loc \\/ to' <> to)>>).\n    Proof.\n      unguard. inv PROMISE.\n      - exploit Memory.add_get0; try exact PROMISES. i. des.\n        exploit Memory.add_get0; try exact MEM. i. des.\n        erewrite Memory.add_o; eauto.\n        erewrite (@Memory.add_o mem2); eauto.\n        condtac; ss.\n        + des. subst. congr.\n        + splits; ss. des; eauto.\n      - exploit Memory.split_get0; try exact PROMISES. i. des.\n        exploit Memory.split_get0; try exact MEM. i. des.\n        erewrite Memory.split_o; eauto.\n        erewrite (@Memory.split_o mem2); eauto.\n        repeat condtac; ss.\n        + des. subst. congr.\n        + des; subst; congr.\n        + splits; ss. des; eauto.\n      - exploit Memory.lower_get0; try exact PROMISES. i. des.\n        exploit Memory.lower_get0; try exact MEM. i. des.\n        erewrite Memory.lower_o; eauto.\n        erewrite (@Memory.lower_o mem2); eauto.\n        condtac; ss.\n        + des. subst. congr.\n        + splits; ss. des; eauto.\n      - exploit Memory.remove_get0; try exact PROMISES. i. des.\n        exploit Memory.remove_get0; try exact MEM. i. des.\n        erewrite Memory.remove_o; eauto.\n        erewrite (@Memory.remove_o mem2); eauto.\n        condtac; ss.\n        + des. subst. congr.\n        + splits; ss. des; eauto.\n    Qed.\n\n    Lemma write_get_None\n          promises1 mem1 loc' from' to' val released promises2 mem2 kind\n          loc from to msg\n          (WRITE: Memory.write promises1 mem1 loc' from' to' val released promises2 mem2 kind)\n          (PROMISES1: Memory.get loc to promises1 = None)\n          (MEM1: Memory.get loc to mem1 = Some (from, msg)):\n      (<<PROMISES2: Memory.get loc to promises2 = None>>) /\\\n      (<<MEM2: Memory.get loc to mem2 = Some (from, msg)>>) /\\\n      (<<LOCTS: __guard__ (loc' <> loc \\/ to' <> to)>>).\n    Proof.\n      inv WRITE.\n      exploit promise_get_None; eauto. i. des. split; ss.\n      erewrite Memory.remove_o; eauto. condtac; ss.\n    Qed.\n\n    Lemma step_get_None\n          e rels1 rels2 e1 e2\n          loc from to msg\n          (STEP: step rels1 rels2 e e1 e2)\n          (PROMISES1: Memory.get loc to (Local.promises (Thread.local e1)) = None)\n          (MEM1: Memory.get loc to (Thread.memory e1) = Some (from, msg)):\n      (<<PROMISES2: Memory.get loc to (Local.promises (Thread.local e2)) = None>>) /\\\n      (<<MEM2: Memory.get loc to (Thread.memory e2) = Some (from, msg)>>) /\\\n      (<<EVENT: forall from' val released ord, ThreadEvent.is_writing e <> Some (loc, from', to, val, released, ord)>>).\n    Proof.\n      inv STEP. inv STEP0; inv STEP; inv LOCAL; ss.\n      - exploit promise_get_None; eauto. i. des. splits; ss.\n      - inv LOCAL0. inv STEP. ss.\n      - inv LOCAL0. inv STEP.\n        exploit write_get_None; eauto. i. des. splits; ss.\n        ii. inv H. unguard. des; ss.\n      - inv LOCAL1. inv STEP. inv LOCAL2. inv STEP.\n        exploit write_get_None; eauto. i. des. splits; ss.\n        ii. inv H. unguard. des; ss.\n      - inv LOCAL0. ss.\n      - inv LOCAL0. ss.\n    Qed.\n\n    Lemma opt_step_get_None\n          e rels1 rels2 e1 e2\n          loc from to msg\n          (STEP: opt_step rels1 rels2 e e1 e2)\n          (PROMISES1: Memory.get loc to (Local.promises (Thread.local e1)) = None)\n          (MEM1: Memory.get loc to (Thread.memory e1) = Some (from, msg)):\n      (<<PROMISES2: Memory.get loc to (Local.promises (Thread.local e2)) = None>>) /\\\n      (<<MEM2: Memory.get loc to (Thread.memory e2) = Some (from, msg)>>) /\\\n      (<<EVENT: forall from' val released ord, ThreadEvent.is_writing e <> Some (loc, from', to, val, released, ord)>>).\n    Proof.\n      inv STEP.\n      - splits; eauto. ss.\n      - exploit step_get_None; eauto.\n    Qed.\n\n    Lemma reserve_step_get_None\n          e1 e2\n          loc from to msg\n          (STEP: @Thread.reserve_step lang e1 e2)\n          (PROMISES1: Memory.get loc to (Local.promises (Thread.local e1)) = None)\n          (MEM1: Memory.get loc to (Thread.memory e1) = Some (from, msg)):\n      (<<PROMISES2: Memory.get loc to (Local.promises (Thread.local e2)) = None>>) /\\\n      (<<MEM2: Memory.get loc to (Thread.memory e2) = Some (from, msg)>>).\n    Proof.\n      inv STEP. inv STEP0; inv STEP; inv LOCAL; ss.\n      exploit promise_get_None; eauto. i. des. ss.\n    Qed.\n\n    Lemma cancel_step_get_None\n          e1 e2\n          loc from to msg\n          (STEP: @Thread.cancel_step lang e1 e2)\n          (PROMISES1: Memory.get loc to (Local.promises (Thread.local e1)) = None)\n          (MEM1: Memory.get loc to (Thread.memory e1) = Some (from, msg)):\n      (<<PROMISES2: Memory.get loc to (Local.promises (Thread.local e2)) = None>>) /\\\n      (<<MEM2: Memory.get loc to (Thread.memory e2) = Some (from, msg)>>).\n    Proof.\n      inv STEP. inv STEP0; inv STEP; inv LOCAL; ss.\n      exploit promise_get_None; eauto. i. des. ss.\n    Qed.\n\n    Lemma reserve_steps_get_None\n          e1 e2\n          loc from to msg\n          (STEP: rtc (@Thread.reserve_step lang) e1 e2)\n          (PROMISES1: Memory.get loc to (Local.promises (Thread.local e1)) = None)\n          (MEM1: Memory.get loc to (Thread.memory e1) = Some (from, msg)):\n      (<<PROMISES2: Memory.get loc to (Local.promises (Thread.local e2)) = None>>) /\\\n      (<<MEM2: Memory.get loc to (Thread.memory e2) = Some (from, msg)>>).\n    Proof.\n      induction STEP; ss.\n      exploit reserve_step_get_None; eauto. i. des. eauto.\n    Qed.\n\n    Lemma cancel_steps_get_None\n          e1 e2\n          loc from to msg\n          (STEP: rtc (@Thread.cancel_step lang) e1 e2)\n          (PROMISES1: Memory.get loc to (Local.promises (Thread.local e1)) = None)\n          (MEM1: Memory.get loc to (Thread.memory e1) = Some (from, msg)):\n      (<<PROMISES2: Memory.get loc to (Local.promises (Thread.local e2)) = None>>) /\\\n      (<<MEM2: Memory.get loc to (Thread.memory e2) = Some (from, msg)>>).\n    Proof.\n      induction STEP; ss.\n      exploit cancel_step_get_None; eauto. i. des. eauto.\n    Qed.\n\n\n    (* reserve_only *)\n\n    Definition reserve_only (promises: Memory.t): Prop :=\n      forall loc from to msg\n        (LOC: L loc)\n        (GET: Memory.get loc to promises = Some (from, msg)),\n        msg = Message.reserve.\n\n    Lemma step_reserve_only\n          rels1 rels2 e e1 e2\n          (PROMISES1: reserve_only (Local.promises (Thread.local e1)))\n          (STEP: step rels1 rels2 e e1 e2):\n      <<PROMISES2: reserve_only (Local.promises (Thread.local e2))>>.\n    Proof.\n      inv STEP. inv STEP0; inv STEP; inv LOCAL; ss; try by (inv LOCAL0; ss).\n      - destruct (L loc) eqn:LOC.\n        + ii. destruct msg.\n          { exploit PF; ss. }\n          revert GET. inv PROMISE; ss.\n          * erewrite Memory.add_o; eauto. condtac; ss; eauto.\n            i. des. subst. inv GET. ss.\n          * erewrite Memory.split_o; eauto. repeat (condtac; ss; eauto).\n            { i. des. subst. inv GET. ss. }\n            { guardH o. i. des. subst. inv GET. ss. }\n          * erewrite Memory.lower_o; eauto. condtac; ss; eauto.\n            i. des. subst. inv GET. ss.\n          * erewrite Memory.remove_o; eauto. condtac; ss; eauto.\n        + ii. revert GET. inv PROMISE; ss.\n          * erewrite Memory.add_o; eauto. condtac; ss; eauto.\n            i. des. subst. congr.\n          * erewrite Memory.split_o; eauto. repeat (condtac; ss; eauto).\n            { i. des. subst. congr. }\n            { guardH o. i. des. subst. congr. }\n          * erewrite Memory.lower_o; eauto. condtac; ss; eauto.\n            i. des. subst. congr.\n          * erewrite Memory.remove_o; eauto. condtac; ss; eauto.\n      - inv LOCAL0. inv STEP. ss.\n      - inv LOCAL0. inv STEP. inv WRITE. ss.\n        ii. revert GET. erewrite Memory.remove_o; eauto. condtac; ss.\n        guardH o. inv PROMISE; ss.\n        + erewrite Memory.add_o; eauto. condtac; ss; eauto.\n        + erewrite Memory.split_o; eauto. condtac; ss. condtac; ss; eauto.\n          guardH o0. i. des. inv GET.\n          exploit Memory.split_get0; try exact PROMISES. i. des.\n          exploit PROMISES1; try exact GET0; eauto.\n        + erewrite Memory.lower_o; eauto. condtac; ss; eauto.\n      - inv LOCAL1. inv STEP. inv LOCAL2. inv STEP. inv WRITE. ss.\n        ii. revert GET0. erewrite Memory.remove_o; eauto. condtac; ss.\n        guardH o. inv PROMISE; ss.\n        + erewrite Memory.add_o; eauto. condtac; ss; eauto.\n        + erewrite Memory.split_o; eauto. condtac; ss. condtac; ss; eauto.\n          guardH o0. i. des. inv GET0.\n          exploit Memory.split_get0; try exact PROMISES. i. des.\n          exploit PROMISES1; try exact GET0; eauto.\n        + erewrite Memory.lower_o; eauto. condtac; ss; eauto.\n    Qed.\n\n    Lemma opt_step_reserve_only\n          rels1 rels2 e e1 e2\n          (PROMISES1: reserve_only (Local.promises (Thread.local e1)))\n          (STEP: opt_step rels1 rels2 e e1 e2):\n      <<PROMISES2: reserve_only (Local.promises (Thread.local e2))>>.\n    Proof.\n      inv STEP; ss.\n      eapply step_reserve_only; eauto.\n    Qed.\n\n    Lemma reserve_step_reserve_only\n          e1 e2\n          (PROMISES1: reserve_only (Local.promises (Thread.local e1)))\n          (STEP: @Thread.reserve_step lang e1 e2):\n      <<PROMISES2: reserve_only (Local.promises (Thread.local e2))>>.\n    Proof.\n      inv STEP. inv STEP0; inv STEP; inv LOCAL. inv PROMISE. ss. ii.\n      revert GET. erewrite Memory.add_o; eauto. condtac; ss; eauto.\n      i. des. inv GET. ss.\n    Qed.\n\n    Lemma cancel_step_reserve_only\n          e1 e2\n          (PROMISES1: reserve_only (Local.promises (Thread.local e1)))\n          (STEP: @Thread.cancel_step lang e1 e2):\n      <<PROMISES2: reserve_only (Local.promises (Thread.local e2))>>.\n    Proof.\n      inv STEP. inv STEP0; inv STEP; inv LOCAL. inv PROMISE. ss. ii.\n      revert GET. erewrite Memory.remove_o; eauto. condtac; ss; eauto.\n    Qed.\n\n    Lemma reserve_steps_reserve_only\n          e1 e2\n          (PROMISES1: reserve_only (Local.promises (Thread.local e1)))\n          (STEPS: rtc (@Thread.reserve_step lang) e1 e2):\n      <<PROMISES2: reserve_only (Local.promises (Thread.local e2))>>.\n    Proof.\n      induction STEPS; ss.\n      hexploit reserve_step_reserve_only; eauto.\n    Qed.\n\n    Lemma cancel_steps_reserve_only\n          e1 e2\n          (PROMISES1: reserve_only (Local.promises (Thread.local e1)))\n          (STEPS: rtc (@Thread.cancel_step lang) e1 e2):\n      <<PROMISES2: reserve_only (Local.promises (Thread.local e2))>>.\n    Proof.\n      induction STEPS; ss.\n      hexploit cancel_step_reserve_only; 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 ReleaseWrites.append. des_ifs; eauto.\n    Qed.\n\n    Lemma step_non_concrete\n          rels1 rels2 e e1 e2 loc to\n          (STEP: step rels1 rels2 e e1 e2)\n          (LOC: L loc)\n          (EVENT: forall from val released ord,\n              ThreadEvent.is_writing e <> Some (loc, from, to, val, released, ord))\n          (GET1: forall from val released,\n              Memory.get loc to (Thread.memory e1) <> Some (from, Message.concrete val released)):\n      <<GET2: forall from val released,\n        Memory.get loc to (Thread.memory e2) <> Some (from, Message.concrete val released)>>.\n    Proof.\n      i. inv STEP. inv STEP0; inv STEP; inv LOCAL; ss; eauto.\n      - inv PROMISE.\n        + erewrite Memory.add_o; eauto. condtac; ss; eauto.\n          des. subst. ii. clarify. exploit PF; ss.\n        + erewrite Memory.split_o; eauto. repeat condtac; ss; eauto.\n          * des. subst. exploit PF; eauto.\n          * guardH o. des. subst. exploit PF; eauto.\n        + erewrite Memory.lower_o; eauto. condtac; ss; eauto.\n          des. subst. ii. clarify. exploit PF; ss.\n        + erewrite Memory.remove_o; eauto. condtac; ss; eauto.\n      - inv LOCAL0. inv STEP. inv WRITE. inv PROMISE; ss.\n        + erewrite Memory.add_o; eauto. condtac; ss; eauto.\n          des. subst. exploit EVENT; eauto.\n        + erewrite Memory.split_o; eauto. repeat condtac; ss; eauto.\n          * des. subst. exploit EVENT; eauto.\n          * des. subst. exploit EVENT; eauto.\n          * guardH o. des. subst.\n            exploit Memory.split_get0; try exact MEM. i. des.\n            exploit GET1; eauto.\n        + erewrite Memory.lower_o; eauto. condtac; ss; eauto.\n          des. subst. exploit EVENT; eauto.\n      - inv LOCAL1. inv STEP.\n        inv LOCAL2. inv STEP. inv WRITE. inv PROMISE; ss.\n        + erewrite Memory.add_o; eauto. condtac; ss; eauto.\n          des. subst. exploit EVENT; eauto.\n        + erewrite Memory.split_o; eauto. repeat condtac; ss; eauto.\n          * des. subst. exploit EVENT; eauto.\n          * des. subst. exploit EVENT; eauto.\n          * guardH o. des. subst.\n            exploit Memory.split_get0; try exact MEM. i. des.\n            exploit GET1; eauto.\n        + erewrite Memory.lower_o; eauto. condtac; ss; eauto.\n          des. subst. exploit EVENT; eauto.\n    Qed.\n\n    Lemma opt_step_non_concrete\n          rels1 rels2 e e1 e2 loc to\n          (STEP: opt_step rels1 rels2 e e1 e2)\n          (LOC: L loc)\n          (EVENT: forall from val released ord,\n              ThreadEvent.is_writing e <> Some (loc, from, to, val, released, ord))\n          (GET1: forall from val released,\n              Memory.get loc to (Thread.memory e1) <> Some (from, Message.concrete val released)):\n      <<GET2: forall from val released,\n        Memory.get loc to (Thread.memory e2) <> Some (from, Message.concrete val released)>>.\n    Proof.\n      inv STEP; eauto.\n      eapply step_non_concrete; eauto.\n    Qed.\n\n    Lemma reserve_steps_non_concrete\n          e1 e2 loc to\n          (STEPS: rtc (@Thread.reserve_step lang) e1 e2)\n          (LOC: L loc)\n          (GET1: forall from val released,\n              Memory.get loc to (Thread.memory e1) <> Some (from, Message.concrete val released)):\n      <<GET2: forall from val released,\n        Memory.get loc to (Thread.memory e2) <> Some (from, Message.concrete val released)>>.\n    Proof.\n      induction STEPS; eauto. i.\n      eapply IHSTEPS; eauto. i.\n      inv H. inv STEP; inv STEP0; inv LOCAL. inv PROMISE; ss.\n      erewrite Memory.add_o; eauto. condtac; ss; eauto.\n    Qed.\n\n    Lemma cancel_steps_non_concrete\n          e1 e2 loc to\n          (STEPS: rtc (@Thread.cancel_step lang) e1 e2)\n          (LOC: L loc)\n          (GET1: forall from val released,\n              Memory.get loc to (Thread.memory e1) <> Some (from, Message.concrete val released)):\n      <<GET2: forall from val released,\n        Memory.get loc to (Thread.memory e2) <> Some (from, Message.concrete val released)>>.\n    Proof.\n      induction STEPS; eauto. i.\n      eapply IHSTEPS; eauto. i.\n      inv H. inv STEP; inv STEP0; inv LOCAL. inv PROMISE; ss.\n      erewrite Memory.remove_o; eauto. condtac; ss; eauto.\n    Qed.\n  End RAThread.\nEnd RAThread.\n\n\nModule RAConfiguration.\n  Section RAConfiguration.\n    Variable L: Loc.t -> bool.\n\n    Inductive step:\n      forall (e: ThreadEvent.t) (tid: Ident.t) (rels1 rels2: ReleaseWrites.t) (c1 c2: Configuration.t), Prop :=\n    | step_intro\n        rels1 rels2\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: RAThread.opt_step L rels1 rels2 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 Ordering.acqrel (Thread.mk _ st4 lc4 sc4 memory4)):\n        step e tid rels1 rels2\n             c1 (Configuration.mk (IdentMap.add tid (existT _ _ st4, lc4) (Configuration.threads c1)) sc4 memory4)\n    .\n\n    Inductive steps rels1: forall (rels2: ReleaseWrites.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.\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.step L Ordering.acqrel e tid c1 c2.\n    Proof.\n      inv STEP. econs; eauto. inv STEP0; [econs 1|].\n      inv STEP. econs 2. eauto.\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 Ordering.acqrel) 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    Proof.\n      inv WF1. inv WF. inv STEP; s.\n      exploit THREADS; eauto. i.\n      exploit Thread.rtc_cancel_step_future; try exact CANCELS; eauto. s. i. des.\n      exploit RAThread.opt_step_future; try exact STEP0; eauto. i. des.\n      exploit Thread.rtc_reserve_step_future; try exact RESERVES; eauto. s. i. des.\n      econs; ss. econs.\n      - i. Configuration.simplify.\n        + exploit THREADS; try apply TH1; eauto. i.\n          exploit Thread.rtc_tau_step_disjoint; try eapply rtc_implies;\n            try eapply Thread.cancel_step_tau_step; try exact CANCELS; eauto. i. des.\n          exploit RAThread.opt_step_disjoint; try exact STEP0; eauto. i. des.\n          exploit Thread.rtc_tau_step_disjoint; try eapply rtc_implies;\n            try eapply Thread.reserve_step_tau_step; try exact RESERVES; eauto. s. i. des.\n          symmetry. ss.\n        + exploit THREADS; try apply TH1; eauto. i.\n          exploit Thread.rtc_tau_step_disjoint; try eapply rtc_implies;\n            try eapply Thread.cancel_step_tau_step; try exact CANCELS; eauto. i. des.\n          exploit RAThread.opt_step_disjoint; try exact STEP0; eauto. i. des.\n          exploit Thread.rtc_tau_step_disjoint; try eapply rtc_implies;\n            try eapply Thread.reserve_step_tau_step; try exact RESERVES; eauto. s. i. des.\n          ss.\n        + eapply DISJOINT; cycle 1; eauto.\n      - i. Configuration.simplify.\n        exploit THREADS; try apply TH; eauto. i. exploit THREADS; try apply TH1; eauto. i.\n        exploit Thread.rtc_tau_step_disjoint; try eapply rtc_implies;\n          try eapply Thread.cancel_step_tau_step; try exact CANCELS; eauto. i. des.\n        exploit RAThread.opt_step_disjoint; try exact STEP0; eauto. i. des.\n        exploit Thread.rtc_tau_step_disjoint; try eapply rtc_implies;\n          try eapply Thread.reserve_step_tau_step; try exact RESERVES; eauto. s. i. des.\n        ss.\n    Qed.\n\n    Lemma step_future2\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      (<<SC_FUTURE: TimeMap.le (Configuration.sc c1) (Configuration.sc c2)>>) /\\\n      (<<MEM_FUTURE: Memory.future (Configuration.memory c1) (Configuration.memory c2)>>).\n    Proof.\n      exploit step_future; eauto. i. des. split; ss.\n      inv STEP. s.\n      inv WF1. inv WF. exploit THREADS; eauto. i. clear DISJOINT THREADS.\n      exploit Thread.rtc_cancel_step_future; eauto. s. i. des.\n      exploit RAThread.opt_step_future; eauto. i. des.\n      exploit Thread.rtc_reserve_step_future; eauto. s. i. des.\n      splits; (etrans; [etrans|]; 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    Proof.\n      induction STEPS; ss.\n      exploit step_future; eauto.\n    Qed.\n\n    Lemma steps_future2\n          rels1 rels2 c1 c2\n          (WF1: Configuration.wf c1)\n          (STEPS: steps rels1 rels2 c1 c2):\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      induction STEPS.\n      - splits; ss; try refl.\n      - exploit step_future2; eauto. i. des.\n        exploit IHSTEPS; eauto. i. des.\n        splits; ss; etrans; eauto.\n    Qed.\n\n    Lemma write_get_None\n          e tid rels1 rels2 c1 c2\n          loc from to val released ord\n          (WF1: Configuration.wf c1)\n          (STEP: step e tid rels1 rels2 c1 c2)\n          (WRITE: ThreadEvent.is_writing e = Some (loc, from, to, val, released, ord)):\n      (<<PROMISES: forall tid lang st lc\n                     (FIND: IdentMap.find tid (Configuration.threads c2) = Some (existT _ lang st, lc)),\n          Memory.get loc to (Local.promises lc) = None>>) /\\\n      (<<MEM: Memory.get loc to (Configuration.memory c2) = Some (from, Message.concrete val released)>>).\n    Proof.\n      inv STEP. inv STEP0; ss.\n      split; cycle 1.\n      { inv STEP. inv STEP0; inv STEP; inv LOCAL; ss.\n        - inv LOCAL0. inv STEP. exploit Memory.write_get2; eauto. i. des.\n          exploit RAThread.reserve_steps_get_None; eauto. i. des. inv WRITE. ss.\n        - inv LOCAL1. inv STEP. inv LOCAL2. inv STEP.\n          exploit Memory.write_get2; eauto. i. des.\n          exploit RAThread.reserve_steps_get_None; eauto. i. des. inv WRITE. ss.\n      }\n      ii. revert FIND. rewrite IdentMap.gsspec. condtac; ss.\n      { i. inv FIND.\n        inv STEP. inv STEP0; inv STEP; inv LOCAL; ss.\n        - inv LOCAL0. inv STEP. exploit Memory.write_get2; eauto. i. des.\n          exploit RAThread.reserve_steps_get_None; eauto. i. des. inv WRITE. ss.\n        - inv LOCAL1. inv STEP. inv LOCAL2. inv STEP.\n          exploit Memory.write_get2; eauto. i. des.\n          exploit RAThread.reserve_steps_get_None; eauto. i. des. inv WRITE. ss.\n      }\n\n      i. inv WF1. inv WF. hexploit DISJOINT; eauto. i.\n      exploit THREADS; try eapply TID. i.\n      exploit THREADS; try eapply FIND. i.\n      exploit Thread.rtc_tau_step_disjoint; try eapply rtc_implies;\n        try eapply Thread.cancel_step_tau_step; try exact CANCELS; eauto. i. des.\n      exploit Thread.rtc_tau_step_future; try eapply rtc_implies;\n        try eapply Thread.cancel_step_tau_step; try exact CANCELS; eauto. s. i. des.\n      exploit RAThread.step_future; try exact STEP; eauto. i. des.\n      inv STEP. inv STEP0; inv STEP; inv LOCAL; inv WRITE; ss.\n      - inv LOCAL0. inv STEP. inv WRITE.\n        exploit Memory.promise_disjoint; try eapply WF; try eapply DISJOINT2; eauto. i. des.\n        exploit Memory.promise_get0; eauto; try by (inv PROMISE; ss). i. des.\n        destruct (Memory.get loc to (Local.promises lc)) as [[]|] eqn:GETP; ss.\n        exfalso.\n        exploit MemoryFacts.promise_time_lt; eauto; try by (inv PROMISE; ss). i.\n        inv DISJOINT0. hexploit DISJOINT1; eauto. i. des.\n        exploit Memory.get_ts; try exact GETP. i. des.\n        { subst. ss. }\n        apply (H0 to); econs; ss; refl.\n      - inv LOCAL1. inv STEP. inv LOCAL2. inv STEP. inv WRITE.\n        exploit Memory.promise_disjoint; try eapply WF; try eapply DISJOINT2; eauto. i. des.\n        exploit Memory.promise_get0; eauto; try by (inv PROMISE; ss). i. des.\n        destruct (Memory.get loc to (Local.promises lc)) as [[]|] eqn:GETP; ss.\n        exfalso.\n        exploit MemoryFacts.promise_time_lt; eauto; try by (inv PROMISE; ss). i.\n        inv DISJOINT0. hexploit DISJOINT1; eauto. i. des.\n        exploit Memory.get_ts; try exact GETP. i. des.\n        { subst. ss. }\n        apply (H0 to); econs; ss; refl.\n    Qed.\n\n    Lemma step_get_None\n          e tid rels1 rels2 c1 c2\n          loc from to msg\n          (STEP: step e tid rels1 rels2 c1 c2)\n          (PROMISES1: forall tid lang st lc\n                       (FIND: IdentMap.find tid (Configuration.threads c1) = Some (existT _ lang st, lc)),\n              Memory.get loc to (Local.promises lc) = None)\n          (MEM1: Memory.get loc to (Configuration.memory c1) = Some (from, msg)):\n      (<<PROMISES2: forall tid lang st lc\n                     (FIND: IdentMap.find tid (Configuration.threads c2) = Some (existT _ lang st, lc)),\n          Memory.get loc to (Local.promises lc) = None>>) /\\\n      (<<MEM2: Memory.get loc to (Configuration.memory c2) = Some (from, msg)>>) /\\\n      (<<EVENT: forall from' val released ord, ThreadEvent.is_writing e <> Some (loc, from', to, val, released, ord)>>).\n    Proof.\n      inv STEP. ss.\n      exploit PROMISES1; eauto. i.\n      exploit RAThread.cancel_steps_get_None; eauto. i. des.\n      exploit RAThread.opt_step_get_None; eauto. i. des.\n      exploit RAThread.reserve_steps_get_None; eauto. i. des.\n      splits; eauto. i.\n      revert FIND. rewrite IdentMap.gsspec. condtac; eauto. i. inv FIND. ss.\n    Qed.\n\n    Lemma steps_rels\n          rels1 rels2 c1 c2\n          loc from to msg\n          (STEPS: steps rels1 rels2 c1 c2)\n          (PROMISES1: forall tid lang st lc\n                       (FIND: IdentMap.find tid (Configuration.threads c1) = Some (existT _ lang st, lc)),\n              Memory.get loc to (Local.promises lc) = None)\n          (MEM1: Memory.get loc to (Configuration.memory c1) = Some (from, msg))\n          (RELS1: ~ List.In (loc, to) rels1):\n      ~ List.In (loc, to) rels2.\n    Proof.\n      induction STEPS; ss.\n      exploit step_get_None; eauto. i. des.\n      eapply IHSTEPS; eauto.\n      ii. inv STEP. ss. inv STEP0; ss. inv STEP.\n      unfold ReleaseWrites.append in H. des_ifs. inv H; ss. inv H0.\n      eapply EVENT; eauto.\n    Qed.\n\n    Lemma write_rels\n          e tid rels1 rels2 c1 c2\n          loc from to val released ord\n          (WF1: Configuration.wf c1)\n          (RELS1: forall tid lang st lc\n                    (TH: IdentMap.find tid (Configuration.threads c1) = Some (existT _ lang st, lc)),\n              ReleaseWrites.wf rels1 (Local.promises lc) (Configuration.memory c1))\n          (STEP: step e tid rels1 rels2 c1 c2)\n          (WRITE: ThreadEvent.is_writing e = Some (loc, from, to, val, released, ord)):\n      ~ List.In (loc, to) rels1.\n    Proof.\n      ii. inv STEP. inv STEP0; ss.\n      hexploit RELS1; eauto. i.\n      hexploit (@RAThread.steps_rels_wf lang L); try eapply RAThread.tau_steps_steps;\n        try eapply RAThread.cancel_steps_tau_steps; eauto; ss; eauto. i.\n      inv STEP. inv STEP0; inv STEP; inv LOCAL; ss.\n      - inv LOCAL0. inv STEP. inv WRITE0.\n        exploit RAThread.promise_rels_wf; eauto. i. des.\n        exploit Memory.promise_get0; eauto; try by (inv PROMISE; ss). i. des.\n        congr.\n      - inv LOCAL1. inv STEP. inv LOCAL2. inv STEP. inv WRITE0. ss.\n        exploit RAThread.promise_rels_wf; eauto. i. des.\n        exploit Memory.promise_get0; eauto; try by (inv PROMISE; ss). i. des.\n        congr.\n    Qed.\n\n\n    (* reserve_only *)\n\n    Definition reserve_only (c: Configuration.t): Prop :=\n      forall tid lang st lc\n        (FIND: IdentMap.find tid (Configuration.threads c) = Some (existT _ lang st, lc)),\n        RAThread.reserve_only L (Local.promises lc).\n\n    Lemma init_reserve_only s:\n      reserve_only (Configuration.init s).\n    Proof.\n      ii. unfold Configuration.init, Threads.init in *. ss.\n      rewrite IdentMap.Facts.map_o in *.\n      destruct (@UsualFMapPositive.UsualPositiveMap'.find\n                  (@sigT _ (@Language.syntax ProgramEvent.t)) tid s); inv FIND.\n      ss. rewrite Memory.bot_get in *. ss.\n    Qed.\n\n    Lemma step_reserve_only\n          tid e rels1 rels2 c1 c2\n          (RESERVE: reserve_only c1)\n          (STEP: step tid e rels1 rels2 c1 c2):\n      reserve_only c2.\n    Proof.\n      inv STEP. ii. ss.\n      revert FIND. rewrite IdentMap.gsspec. condtac; ss; i; cycle 1.\n      { eapply RESERVE; eauto. }\n      inv FIND. apply inj_pair2 in H1. subst.\n      unfold reserve_only in RESERVE.\n      hexploit RESERVE; eauto. i.\n      hexploit RAThread.cancel_steps_reserve_only; try exact CANCELS; eauto. i. des.\n      hexploit RAThread.opt_step_reserve_only; try exact STEP0; eauto. i.\n      hexploit RAThread.reserve_steps_reserve_only; try exact RESERVES; eauto.\n    Qed.\n\n    Lemma steps_reserve_only\n          rels1 rels2 c1 c2\n          (RESERVE: reserve_only c1)\n          (STEPS: steps rels1 rels2 c1 c2):\n      reserve_only c2.\n    Proof.\n      induction STEPS; ss.\n      hexploit step_reserve_only; eauto.\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 ReleaseWrites.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\n    Lemma step_non_concrete\n          e tid rels1 rels2 c1 c2 loc to\n          (STEP: step e tid rels1 rels2 c1 c2)\n          (LOC: L loc)\n          (EVENT: forall from val released ord,\n              ThreadEvent.is_writing e <> Some (loc, from, to, val, released, ord))\n          (GET1: forall from val released,\n              Memory.get loc to (Configuration.memory c1) <> Some (from, Message.concrete val released)):\n      <<GET2: forall from val released,\n        Memory.get loc to (Configuration.memory c2) <> Some (from, Message.concrete val released)>>.\n    Proof.\n      inv STEP. ss.\n      hexploit RAThread.cancel_steps_non_concrete; eauto. i. des.\n      hexploit RAThread.opt_step_non_concrete; eauto. i. des.\n      hexploit RAThread.reserve_steps_non_concrete; eauto.\n    Qed.\n  End RAConfiguration.\nEnd RAConfiguration.\n\n\nModule RARaceW.\n  Section RARace.\n    Variable L: Loc.t -> bool.\n\n    Definition ra_race (rels: ReleaseWrites.t) (tview: TView.t) (loc: Loc.t) (to: Time.t) (ordr: Ordering.t): Prop :=\n      (<<LOC: L loc>>) /\\\n      (<<HIGHER: Time.lt ((View.rlx (TView.cur tview)) loc) to>>) /\\\n      ((<<ORDW: ~ List.In (loc, to) rels>>) \\/\n       (<<ORDR: Ordering.le ordr Ordering.strong_relaxed>>)).\n\n    Definition ra_race_steps (rels: ReleaseWrites.t) (c: Configuration.t): Prop :=\n      exists tid rels2 rels3 rels4\n        c2 lang st2 lc2 e loc to val released ord e3 e4,\n        (<<STEPS: RAConfiguration.steps L rels rels2 c c2>>) /\\\n        (<<TID: IdentMap.find tid (Configuration.threads c2) = Some (existT _ lang st2, lc2)>>) /\\\n        (<<THREAD_STEPS: RAThread.steps L rels2 rels3\n                                        (Thread.mk _ st2 lc2 (Configuration.sc c2) (Configuration.memory c2)) e3>>) /\\\n        (<<CONS: Local.promise_consistent (Thread.local e3)>>) /\\\n        (<<THREAD_STEP: RAThread.step L rels3 rels4 e e3 e4>>) /\\\n        (<<READ: ThreadEvent.is_reading e = Some (loc, to, val, released, ord)>>) /\\\n        (<<RARACE: ra_race rels3 (Local.tview (Thread.local e3)) loc to ord>>).\n\n    Definition racefree (rels: ReleaseWrites.t) (c: Configuration.t): Prop :=\n      forall tid rels2 rels3 rels4\n        c2 lang st2 lc2 e loc to val released ord e3 e4\n        (STEPS: RAConfiguration.steps L rels rels2 c c2)\n        (TID: IdentMap.find tid (Configuration.threads c2) = Some (existT _ lang st2, lc2))\n        (THREAD_STEPS: RAThread.steps L rels2 rels3\n                                      (Thread.mk _ st2 lc2 (Configuration.sc c2) (Configuration.memory c2)) e3)\n        (CONS: Local.promise_consistent (Thread.local e3))\n        (THREAD_STEP: RAThread.step L rels3 rels4 e e3 e4)\n        (READ: ThreadEvent.is_reading e = Some (loc, to, val, released, ord))\n        (RARACE: ra_race rels3 (Local.tview (Thread.local e3)) loc to ord),\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: RAConfiguration.step L e tid rels1 rels2 c1 c2):\n      racefree rels2 c2.\n    Proof.\n      ii. eapply RACEFREE; eauto. econs 2; eauto.\n    Qed.\n\n    Lemma step_ord_step\n          e tid rels1 rels2 c1 c2\n          (STEP: RAConfiguration.step L e tid rels1 rels2 c1 c2):\n      OrdConfiguration.step L Ordering.acqrel e tid c1 c2.\n    Proof.\n      inv STEP. econs; eauto. inv STEP0.\n      - econs 1.\n      - inv STEP. econs 2. eauto.\n    Qed.\n  End RARace.\nEnd RARaceW.\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/RAStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.266286403824603}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import riscv.Decode.\nRequire Import riscv.Encode.\nRequire Import riscv.Utility.\nRequire Import riscv.util.Tactics.\nRequire Import riscv.util.div_mod_to_quot_rem.\nRequire Import riscv.proofs.invert_encode_R.\nRequire Import riscv.proofs.invert_encode_R_atomic.\nRequire Import riscv.proofs.invert_encode_I.\nRequire Import riscv.proofs.invert_encode_I_shift_57.\nRequire Import riscv.proofs.invert_encode_I_shift_66.\nRequire Import riscv.proofs.invert_encode_I_system.\nRequire Import riscv.proofs.invert_encode_S.\nRequire Import riscv.proofs.invert_encode_SB.\nRequire Import riscv.proofs.invert_encode_U.\nRequire Import riscv.proofs.invert_encode_UJ.\nRequire Import riscv.proofs.invert_encode_Fence.\n\nLocal Open Scope bool_scope.\nLocal Open Scope Z_scope.\n\n\nLtac somega_pre :=\n  rewrite? bitSlice_alt in * by omega; unfold bitSlice' in *;\n  repeat (so fun hyporgoal => match hyporgoal with\n  | context [signExtend ?l ?n] =>\n      let E := fresh \"E\" in\n      destruct (signExtend_alt' l n) as [[? [? E]] | [? [? E]]];\n      [ omega | rewrite E in *; clear E .. ]\n  end);\n  rewrite? Z.shiftl_mul_pow2 in * by omega;\n  repeat (so fun hyporgoal => match hyporgoal with\n     | context [2 ^ ?x] => let r := eval cbv in (2 ^ x) in change (2 ^ x) with r in *\n  end);\n  div_mod_to_quot_rem;\n  repeat match goal with\n         | z: ?T |- _ => progress change T with Z in *\n         end.\n\n(* omega which understands bitSlice and shift *)\nLtac somega := somega_pre; omega.\n\nLtac write_as_pow2_opportunities f :=\n    repeat (so fun hyporgoal => match hyporgoal with\n               | context [ Z.pos ?p ] =>\n                   match p with\n                   | 1%positive => fail 1\n                   | 2%positive => fail 1\n                   | _ => idtac\n                   end;\n                   let e := eval cbv in (Z.log2 (Z.pos p)) in\n                   f (Z.pos p) (2 ^ e)\n               end);\n    (* we might have been a bit too eager -- undo undesired chained powers: *)\n    repeat (so fun hyporgoal => match hyporgoal with\n               | context [2 ^ 2 ^ ?p] => let r := eval cbv in (2 ^ p) in\n                                         change (2 ^ 2 ^ p) with (2 ^ r) in *\n               end).\n\nTactic Notation \"write_as_pow2\" \"in\" \"*|-\" :=\n  write_as_pow2_opportunities ltac:(fun old new => change old with new in *|-).\n\nTactic Notation \"write_as_pow2\" \"in\" \"*\" :=\n  write_as_pow2_opportunities ltac:(fun old new => change old with new in *).\n\nLemma invert_encode_InvalidInstruction: forall i,\n  verify_Invalid i ->\n  forall inst,\n  encode_Invalid i = inst ->\n  False.\nProof. intros. assumption. Qed.\n\nLtac cbn_encode := repeat (\n  cbn [\n    Z.eqb\n    Pos.eqb andb\n    opcode_SYSTEM\n    opcode_STORE_FP\n    opcode_STORE\n    opcode_OP_IMM_32\n    opcode_OP_IMM\n    opcode_OP_FP\n    opcode_OP_32\n    opcode_OP\n    opcode_NMSUB\n    opcode_NMADD\n    opcode_MSUB\n    opcode_MISC_MEM\n    opcode_MADD\n    opcode_LUI\n    opcode_LOAD_FP\n    opcode_LOAD\n    opcode_JALR\n    opcode_JAL\n    opcode_BRANCH\n    opcode_AUIPC\n    opcode_AMO\n    funct3_JALR\n    funct7_XOR\n    funct7_SUBW\n    funct7_SRLIW\n    funct7_SRL\n    funct7_SUB\n    funct7_SRLW\n    funct7_SRA\n    funct7_SLTU\n    funct7_SLT\n    funct7_SLLW\n    funct7_SLLIW\n    funct7_SLL\n    funct7_SRAW\n    funct7_SRAIW\n    funct7_MUL\n    funct7_DIVW\n    funct7_DIVUW\n    funct7_DIVU\n    funct7_DIV\n    funct7_AND\n    funct7_SFENCE_VMA\n    funct7_REMW\n    funct7_REMUW\n    funct7_REMU\n    funct7_REM\n    funct7_OR\n    funct7_MULW\n    funct7_MULHU\n    funct7_MULHSU\n    funct7_MULH\n    funct3_SRAIW\n    funct3_SRAI\n    funct3_SRA\n    funct3_SLTU\n    funct3_SLTIU\n    funct3_SLTI\n    funct7_ADDW\n    funct7_ADD\n    funct6_SRLI\n    funct6_SRAI\n    funct6_SLLI\n    funct5_SC\n    funct5_LR\n    funct5_AMOXOR\n    funct5_AMOSWAP\n    funct5_AMOOR\n    funct5_AMOMINU\n    funct5_AMOMIN\n    funct5_AMOMAXU\n    funct5_AMOMAX\n    funct5_AMOAND\n    funct5_AMOADD\n    funct3_XORI\n    funct3_XOR\n    funct3_SW\n    funct3_SUBW\n    funct3_SUB\n    funct3_SRLW\n    funct3_SRLIW\n    funct3_SRLI\n    funct3_SRL\n    funct3_SRAW\n    funct12_EBREAK\n    funct3_DIVUW\n    funct3_SLT\n    funct3_SLLW\n    funct3_SLLIW\n    funct3_SLLI\n    funct3_SLL\n    funct3_SH\n    funct3_SD\n    funct3_SB\n    funct3_REMW\n    funct3_REMUW\n    funct3_REMU\n    funct3_REM\n    funct3_PRIV\n    funct3_ORI\n    funct3_OR\n    funct3_MULW\n    funct3_MULHU\n    funct3_MULHSU\n    funct3_MULH\n    funct3_MUL\n    funct3_LWU\n    funct3_LW\n    funct3_LHU\n    funct3_LH\n    funct3_LD\n    funct3_LBU\n    funct3_LB\n    funct3_FENCE_I\n    funct3_FENCE\n    funct3_DIVW\n    funct3_AND\n    funct3_DIVU\n    funct3_DIV\n    funct3_CSRRWI\n    funct3_CSRRW\n    funct3_CSRRSI\n    funct3_CSRRS\n    funct3_CSRRCI\n    funct3_CSRRC\n    funct3_BNE\n    funct3_BLTU\n    funct3_BLT\n    funct3_BGEU\n    funct3_BGE\n    funct3_BEQ\n    funct3_ANDI\n    funct12_URET\n    funct3_AMOW\n    funct3_AMOD\n    funct3_ADDW\n    funct3_ADDIW\n    funct3_ADDI\n    funct3_ADD\n    funct12_WFI\n    funct12_MRET\n    funct12_SRET\n    funct12_ECALL\n    isValidM64\n    isValidM\n    isValidI64\n    isValidI\n    isValidCSR\n    isValidA64\n    isValidA\n    supportsM\n    supportsA\n    bitwidth\n    app\n  ] in *;\n  cbv [machineIntToShamt id] in *\n).\n\nLemma decode_encode: forall (inst: Instruction) (iset: InstructionSet),\n    verify inst iset ->\n    decode iset (encode inst) = inst.\nProof.\n  intros. unfold verify in H. destruct H as [H H0].\n  unfold verify_iset in *.\n  cbv beta delta [decode].\n  repeat match goal with\n  | |- (let x := ?a in ?b) = ?c => change (let x := a in b = c); intro\n  | x := ?t : ?T |- _ => pose proof (eq_refl t : x = t); clearbody x\n  end.\n  remember (encode inst) as encoded eqn:Henc; symmetry in Henc.\n  cbv [encode] in Henc.\n  cbv [\n      Encoder\n        Verifier\n        apply_InstructionMapper \n        map_Fence\n        map_I\n        map_I_shift_57\n        map_I_shift_66\n        map_I_system\n        map_Invalid\n        map_R\n        map_R_atomic\n        map_S\n        map_SB\n        map_U\n        map_UJ\n    ] in Henc.\n\n  destruct inst as [i|i|i|i|i|i|i|i].\n  par: abstract (destruct i; try (\n    (lazymatch type of Henc with\n     | encode_I _ _ _ _ _ = _ =>\n       apply invert_encode_I in Henc\n     | encode_Fence _ _ _ _ _ _ _ = _ =>\n       apply invert_encode_Fence in Henc\n     | encode_I_shift_66 _ _ _ _ _ _ = _ =>\n       apply (@invert_encode_I_shift_66 (bitwidth iset)) in Henc\n     | encode_I_shift_57 _ _ _ _ _ _ = _ =>\n       apply invert_encode_I_shift_57 in Henc\n     | encode_R _ _ _ _ _ _ = _ =>\n       apply invert_encode_R in Henc\n     | encode_Invalid _ = _ =>\n       apply invert_encode_InvalidInstruction in Henc\n     | encode_R_atomic _ _ _ _ _ _ _ = _ => \n       apply invert_encode_R_atomic in Henc\n     | encode_I_system _ _ _ _ _ = _ =>\n       apply invert_encode_I_system in Henc\n     | encode_U _ _ _ = _ =>\n       apply invert_encode_U in Henc\n     | encode_UJ _ _ _ = _ =>\n       apply invert_encode_UJ in Henc\n     | encode_S _ _ _ _ _ = _ =>\n       apply invert_encode_S in Henc\n     | encode_SB _ _ _ _ _ = _ => \n       apply invert_encode_SB in Henc\n     end; [|trivial]);\n      repeat match type of Henc with\n               _ /\\ _ => let H := fresh \"H\" in destruct Henc as [H Henc]; rewrite <-?H in *\n             end; rewrite <-?Henc in *;\n      subst results; subst resultI; subst decodeI; subst opcode; subst funct3;\n      subst funct5; subst funct6; subst funct7; subst funct10; subst funct12;\n      destruct iset;\n      repeat match goal with\n      | H: False |- _ => destruct H\n      | |- ?x = ?x => exact_no_check (eq_refl x)\n      | |- _ => progress cbn_encode\n      | |- _ => rewrite !Bool.orb_true_r in *\n      | |- _ => rewrite !Bool.andb_false_r in *\n      | |- _ => progress subst\n      end);\n     (* cases where bitSlice in goal and hyps do not match *)\n     cbv [funct7_SFENCE_VMA opcode_SYSTEM funct3_PRIV funct12_WFI funct12_MRET\n          funct12_SRET funct12_URET funct12_EBREAK funct12_ECALL\n          funct3_FENCE_I opcode_MISC_MEM isValidI] in *;\n     repeat match goal with\n            | |- ?x = ?x => exact_no_check (eq_refl x)\n            | |- context [?x =? ?y] =>\n              let H := fresh \"H\" in\n              destruct (x =? y) eqn:H;\n                apply Z.eqb_eq in H || apply Z.eqb_neq in H\n            | _ => progress cbn in *\n            end;\n     try (intuition discriminate);\n     try solve [ exfalso;\n                 try (match goal with H: _ <> _ |- _ => apply H; clear H end);\n                 somega ]).\nQed.\n\nPrint Assumptions decode_encode.\n", "meta": {"author": "samuelgruetter", "repo": "riscv-coq", "sha": "bd89fbff49704b4476633a88abdedb4e410c200b", "save_path": "github-repos/coq/samuelgruetter-riscv-coq", "path": "github-repos/coq/samuelgruetter-riscv-coq/riscv-coq-bd89fbff49704b4476633a88abdedb4e410c200b/src/proofs/DecodeEncode.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.266286383949035}}
{"text": "From iris.algebra Require Export cmra.\nFrom iris.algebra Require Import local_updates.\nFrom iris.base_logic Require Import base_logic.\nFrom iris Require Import options.\nLocal Arguments pcore _ _ !_ /.\nLocal Arguments cmra_pcore _ !_ /.\nLocal Arguments validN _ _ _ !_ /.\nLocal Arguments valid _ _  !_ /.\nLocal Arguments cmra_validN _ _ !_ /.\nLocal Arguments cmra_valid _  !_ /.\n\nInductive csum (A B : Type) :=\n  | Cinl : A → csum A B\n  | Cinr : B → csum A B\n  | CsumBot : csum A B.\nArguments Cinl {_ _} _.\nArguments Cinr {_ _} _.\nArguments CsumBot {_ _}.\n\nInstance: Params (@Cinl) 2 := {}.\nInstance: Params (@Cinr) 2 := {}.\nInstance: Params (@CsumBot) 2 := {}.\n\nInstance maybe_Cinl {A B} : Maybe (@Cinl A B) := λ x,\n  match x with Cinl a => Some a | _ => None end.\nInstance maybe_Cinr {A B} : Maybe (@Cinr A B) := λ x,\n  match x with Cinr b => Some b | _ => None end.\n\nSection cofe.\nContext {A B : ofeT}.\nImplicit Types a : A.\nImplicit Types b : B.\n\n(* Cofe *)\nInductive csum_equiv : Equiv (csum A B) :=\n  | Cinl_equiv a a' : a ≡ a' → Cinl a ≡ Cinl a'\n  | Cinr_equiv b b' : b ≡ b' → Cinr b ≡ Cinr b'\n  | CsumBot_equiv : CsumBot ≡ CsumBot.\nExisting Instance csum_equiv.\nInductive csum_dist : Dist (csum A B) :=\n  | Cinl_dist n a a' : a ≡{n}≡ a' → Cinl a ≡{n}≡ Cinl a'\n  | Cinr_dist n b b' : b ≡{n}≡ b' → Cinr b ≡{n}≡ Cinr b'\n  | CsumBot_dist n : CsumBot ≡{n}≡ CsumBot.\nExisting Instance csum_dist.\n\nGlobal Instance Cinl_ne : NonExpansive (@Cinl A B).\nProof. by constructor. Qed.\nGlobal Instance Cinl_proper : Proper ((≡) ==> (≡)) (@Cinl A B).\nProof. by constructor. Qed.\nGlobal Instance Cinl_inj : Inj (≡) (≡) (@Cinl A B).\nProof. by inversion_clear 1. Qed.\nGlobal Instance Cinl_inj_dist n : Inj (dist n) (dist n) (@Cinl A B).\nProof. by inversion_clear 1. Qed.\nGlobal Instance Cinr_ne : NonExpansive (@Cinr A B).\nProof. by constructor. Qed.\nGlobal Instance Cinr_proper : Proper ((≡) ==> (≡)) (@Cinr A B).\nProof. by constructor. Qed.\nGlobal Instance Cinr_inj : Inj (≡) (≡) (@Cinr A B).\nProof. by inversion_clear 1. Qed.\nGlobal Instance Cinr_inj_dist n : Inj (dist n) (dist n) (@Cinr A B).\nProof. by inversion_clear 1. Qed.\n\nDefinition csum_ofe_mixin : OfeMixin (csum A B).\nProof.\n  split.\n  - intros mx my; split.\n    + by destruct 1; constructor; try apply equiv_dist.\n    + intros Hxy; feed inversion (Hxy 0); subst; constructor; try done;\n      apply equiv_dist=> n; by feed inversion (Hxy n).\n  - intros n; split.\n    + by intros [|a|]; constructor.\n    + by destruct 1; constructor.\n    + destruct 1; inversion_clear 1; constructor; etrans; eauto.\n  - by inversion_clear 1; constructor; apply dist_S.\nQed.\nCanonical Structure csumO : ofeT := OfeT (csum A B) csum_ofe_mixin.\n\nProgram Definition csum_chain_l (c : chain csumO) (a : A) : chain A :=\n  {| chain_car n := match c n return _ with Cinl a' => a' | _ => a end |}.\nNext Obligation. intros c a n i ?; simpl. by destruct (chain_cauchy c n i). Qed.\nProgram Definition csum_chain_r (c : chain csumO) (b : B) : chain B :=\n  {| chain_car n := match c n return _ with Cinr b' => b' | _ => b end |}.\nNext Obligation. intros c b n i ?; simpl. by destruct (chain_cauchy c n i). Qed.\nDefinition csum_compl `{Cofe A, Cofe B} : Compl csumO := λ c,\n  match c 0 with\n  | Cinl a => Cinl (compl (csum_chain_l c a))\n  | Cinr b => Cinr (compl (csum_chain_r c b))\n  | CsumBot => CsumBot\n  end.\nGlobal Program Instance csum_cofe `{Cofe A, Cofe B} : Cofe csumO :=\n  {| compl := csum_compl |}.\nNext Obligation.\n  intros ?? n c; rewrite /compl /csum_compl.\n  feed inversion (chain_cauchy c 0 n); first auto with lia; constructor.\n  + rewrite (conv_compl n (csum_chain_l c a')) /=. destruct (c n); naive_solver.\n  + rewrite (conv_compl n (csum_chain_r c b')) /=. destruct (c n); naive_solver.\nQed.\n\nGlobal Instance csum_ofe_discrete :\n  OfeDiscrete A → OfeDiscrete B → OfeDiscrete csumO.\nProof. by inversion_clear 3; constructor; apply (discrete _). Qed.\nGlobal Instance csum_leibniz :\n  LeibnizEquiv A → LeibnizEquiv B → LeibnizEquiv csumO.\nProof. by destruct 3; f_equal; apply leibniz_equiv. Qed.\n\nGlobal Instance Cinl_discrete a : Discrete a → Discrete (Cinl a).\nProof. by inversion_clear 2; constructor; apply (discrete _). Qed.\nGlobal Instance Cinr_discrete b : Discrete b → Discrete (Cinr b).\nProof. by inversion_clear 2; constructor; apply (discrete _). Qed.\n\n(** Internalized properties *)\nLemma csum_equivI {M} (x y : csum A B) :\n  x ≡ y ⊣⊢@{uPredI M} match x, y with\n                      | Cinl a, Cinl a' => a ≡ a'\n                      | Cinr b, Cinr b' => b ≡ b'\n                      | CsumBot, CsumBot => True\n                      | _, _ => False\n                      end.\nProof.\n  uPred.unseal; do 2 split; first by destruct 1.\n  by destruct x, y; try destruct 1; try constructor.\nQed.\nEnd cofe.\n\nArguments csumO : clear implicits.\n\n(* Functor on COFEs *)\nDefinition csum_map {A A' B B'} (fA : A → A') (fB : B → B')\n                    (x : csum A B) : csum A' B' :=\n  match x with\n  | Cinl a => Cinl (fA a)\n  | Cinr b => Cinr (fB b)\n  | CsumBot => CsumBot\n  end.\nInstance: Params (@csum_map) 4 := {}.\n\nLemma csum_map_id {A B} (x : csum A B) : csum_map id id x = x.\nProof. by destruct x. Qed.\nLemma csum_map_compose {A A' A'' B B' B''} (f : A → A') (f' : A' → A'')\n                       (g : B → B') (g' : B' → B'') (x : csum A B) :\n  csum_map (f' ∘ f) (g' ∘ g) x = csum_map f' g' (csum_map f g x).\nProof. by destruct x. Qed.\nLemma csum_map_ext {A A' B B' : ofeT} (f f' : A → A') (g g' : B → B') x :\n  (∀ x, f x ≡ f' x) → (∀ x, g x ≡ g' x) → csum_map f g x ≡ csum_map f' g' x.\nProof. by destruct x; constructor. Qed.\nInstance csum_map_cmra_ne {A A' B B' : ofeT} n :\n  Proper ((dist n ==> dist n) ==> (dist n ==> dist n) ==> dist n ==> dist n)\n         (@csum_map A A' B B').\nProof. intros f f' Hf g g' Hg []; destruct 1; constructor; by apply Hf || apply Hg. Qed.\nDefinition csumO_map {A A' B B'} (f : A -n> A') (g : B -n> B') :\n  csumO A B -n> csumO A' B' :=\n  OfeMor (csum_map f g).\nInstance csumO_map_ne A A' B B' :\n  NonExpansive2 (@csumO_map A A' B B').\nProof. by intros n f f' Hf g g' Hg []; constructor. Qed.\n\nSection cmra.\nContext {A B : cmraT}.\nImplicit Types a : A.\nImplicit Types b : B.\n\n(* CMRA *)\nInstance csum_valid : Valid (csum A B) := λ x,\n  match x with\n  | Cinl a => ✓ a\n  | Cinr b => ✓ b\n  | CsumBot => False\n  end.\nInstance csum_validN : ValidN (csum A B) := λ n x,\n  match x with\n  | Cinl a => ✓{n} a\n  | Cinr b => ✓{n} b\n  | CsumBot => False\n  end.\nInstance csum_pcore : PCore (csum A B) := λ x,\n  match x with\n  | Cinl a => Cinl <$> pcore a\n  | Cinr b => Cinr <$> pcore b\n  | CsumBot => Some CsumBot\n  end.\nInstance csum_op : Op (csum A B) := λ x y,\n  match x, y with\n  | Cinl a, Cinl a' => Cinl (a ⋅ a')\n  | Cinr b, Cinr b' => Cinr (b ⋅ b')\n  | _, _ => CsumBot\n  end.\n\nLemma Cinl_op a a' : Cinl (a ⋅ a') = Cinl a ⋅ Cinl a'.\nProof. done. Qed.\nLemma Cinr_op b b' : Cinr (b ⋅ b') = Cinr b ⋅ Cinr b'.\nProof. done. Qed.\n\nLemma csum_included x y :\n  x ≼ y ↔ y = CsumBot ∨ (∃ a a', x = Cinl a ∧ y = Cinl a' ∧ a ≼ a')\n                      ∨ (∃ b b', x = Cinr b ∧ y = Cinr b' ∧ b ≼ b').\nProof.\n  split.\n  - unfold included. intros [[a'|b'|] Hy]; destruct x as [a|b|];\n      inversion_clear Hy; eauto 10.\n  - intros [->|[(a&a'&->&->&c&?)|(b&b'&->&->&c&?)]].\n    + destruct x; exists CsumBot; constructor.\n    + exists (Cinl c); by constructor.\n    + exists (Cinr c); by constructor.\nQed.\nLemma Cinl_included a a' : Cinl a ≼ Cinl a' ↔ a ≼ a'.\nProof. rewrite csum_included. naive_solver. Qed.\nLemma Cinr_included b b' : Cinr b ≼ Cinr b' ↔ b ≼ b'.\nProof. rewrite csum_included. naive_solver. Qed.\n\nLemma csum_includedN n x y :\n  x ≼{n} y ↔ y = CsumBot ∨ (∃ a a', x = Cinl a ∧ y = Cinl a' ∧ a ≼{n} a')\n                         ∨ (∃ b b', x = Cinr b ∧ y = Cinr b' ∧ b ≼{n} b').\nProof.\n  split.\n  - unfold includedN. intros [[a'|b'|] Hy]; destruct x as [a|b|];\n      inversion_clear Hy; eauto 10.\n  - intros [->|[(a&a'&->&->&c&?)|(b&b'&->&->&c&?)]].\n    + destruct x; exists CsumBot; constructor.\n    + exists (Cinl c); by constructor.\n    + exists (Cinr c); by constructor.\nQed.\n\nLemma csum_cmra_mixin : CmraMixin (csum A B).\nProof.\n  split.\n  - intros [] n; destruct 1; constructor; by ofe_subst.\n  - intros ???? [n a a' Ha|n b b' Hb|n] [=]; subst; eauto.\n    + destruct (pcore a) as [ca|] eqn:?; simplify_option_eq.\n      destruct (cmra_pcore_ne n a a' ca) as (ca'&->&?); auto.\n      exists (Cinl ca'); by repeat constructor.\n    + destruct (pcore b) as [cb|] eqn:?; simplify_option_eq.\n      destruct (cmra_pcore_ne n b b' cb) as (cb'&->&?); auto.\n      exists (Cinr cb'); by repeat constructor.\n  - intros ? [a|b|] [a'|b'|] H; inversion_clear H; ofe_subst; done.\n  - intros [a|b|]; rewrite /= ?cmra_valid_validN; naive_solver eauto using O.\n  - intros n [a|b|]; simpl; auto using cmra_validN_S.\n  - intros [a1|b1|] [a2|b2|] [a3|b3|]; constructor; by rewrite ?assoc.\n  - intros [a1|b1|] [a2|b2|]; constructor; by rewrite 1?comm.\n  - intros [a|b|] ? [=]; subst; auto.\n    + destruct (pcore a) as [ca|] eqn:?; simplify_option_eq.\n      constructor; eauto using cmra_pcore_l.\n    + destruct (pcore b) as [cb|] eqn:?; simplify_option_eq.\n      constructor; eauto using cmra_pcore_l.\n  - intros [a|b|] ? [=]; subst; auto.\n    + destruct (pcore a) as [ca|] eqn:?; simplify_option_eq.\n      feed inversion (cmra_pcore_idemp a ca); repeat constructor; auto.\n    + destruct (pcore b) as [cb|] eqn:?; simplify_option_eq.\n      feed inversion (cmra_pcore_idemp b cb); repeat constructor; auto.\n  - intros x y ? [->|[(a&a'&->&->&?)|(b&b'&->&->&?)]]%csum_included [=].\n    + exists CsumBot. rewrite csum_included; eauto.\n    + destruct (pcore a) as [ca|] eqn:?; simplify_option_eq.\n      destruct (cmra_pcore_mono a a' ca) as (ca'&->&?); auto.\n      exists (Cinl ca'). rewrite csum_included; eauto 10.\n    + destruct (pcore b) as [cb|] eqn:?; simplify_option_eq.\n      destruct (cmra_pcore_mono b b' cb) as (cb'&->&?); auto.\n      exists (Cinr cb'). rewrite csum_included; eauto 10.\n  - intros n [a1|b1|] [a2|b2|]; simpl; eauto using cmra_validN_op_l; done.\n  - intros n [a|b|] y1 y2 Hx Hx'.\n    + destruct y1 as [a1|b1|], y2 as [a2|b2|]; try by exfalso; inversion Hx'.\n      destruct (cmra_extend n a a1 a2) as (z1&z2&?&?&?); [done|apply (inj Cinl), Hx'|].\n      exists (Cinl z1), (Cinl z2). by repeat constructor.\n    + destruct y1 as [a1|b1|], y2 as [a2|b2|]; try by exfalso; inversion Hx'.\n      destruct (cmra_extend n b b1 b2) as (z1&z2&?&?&?); [done|apply (inj Cinr), Hx'|].\n      exists (Cinr z1), (Cinr z2). by repeat constructor.\n    + by exists CsumBot, CsumBot; destruct y1, y2; inversion_clear Hx'.\nQed.\nCanonical Structure csumR := CmraT (csum A B) csum_cmra_mixin.\n\nGlobal Instance csum_cmra_discrete :\n  CmraDiscrete A → CmraDiscrete B → CmraDiscrete csumR.\nProof.\n  split; first apply _.\n  by move=>[a|b|] HH /=; try apply cmra_discrete_valid.\nQed.\n\nGlobal Instance Cinl_core_id a : CoreId a → CoreId (Cinl a).\nProof. rewrite /CoreId /=. inversion_clear 1; by repeat constructor. Qed.\nGlobal Instance Cinr_core_id b : CoreId b → CoreId (Cinr b).\nProof. rewrite /CoreId /=. inversion_clear 1; by repeat constructor. Qed.\n\nGlobal Instance Cinl_exclusive a : Exclusive a → Exclusive (Cinl a).\nProof. by move=> H[]? =>[/H||]. Qed.\nGlobal Instance Cinr_exclusive b : Exclusive b → Exclusive (Cinr b).\nProof. by move=> H[]? =>[|/H|]. Qed.\n\nGlobal Instance Cinl_cancelable a : Cancelable a → Cancelable (Cinl a).\nProof.\n  move=> ?? [y|y|] [z|z|] ? EQ //; inversion_clear EQ.\n  constructor. by eapply (cancelableN a).\nQed.\nGlobal Instance Cinr_cancelable b : Cancelable b → Cancelable (Cinr b).\nProof.\n  move=> ?? [y|y|] [z|z|] ? EQ //; inversion_clear EQ.\n  constructor. by eapply (cancelableN b).\nQed.\n\nGlobal Instance Cinl_id_free a : IdFree a → IdFree (Cinl a).\nProof. intros ? [] ? EQ; inversion_clear EQ. by eapply id_free0_r. Qed.\nGlobal Instance Cinr_id_free b : IdFree b → IdFree (Cinr b).\nProof. intros ? [] ? EQ; inversion_clear EQ. by eapply id_free0_r. Qed.\n\n(** Interaction with [option] *)\nLemma Some_csum_includedN x y n :\n  Some x ≼{n} Some y ↔\n    y = CsumBot ∨\n    (∃ a a', x = Cinl a ∧ y = Cinl a' ∧ Some a ≼{n} Some a') ∨\n    (∃ b b', x = Cinr b ∧ y = Cinr b' ∧ Some b ≼{n} Some b').\nProof.\n  repeat setoid_rewrite Some_includedN. rewrite csum_includedN. split.\n  - intros [Hxy|?]; [inversion Hxy|]; naive_solver.\n  - naive_solver by f_equiv.\nQed.\nLemma Some_csum_included x y :\n  Some x ≼ Some y ↔\n    y = CsumBot ∨\n    (∃ a a', x = Cinl a ∧ y = Cinl a' ∧ Some a ≼ Some a') ∨\n    (∃ b b', x = Cinr b ∧ y = Cinr b' ∧ Some b ≼ Some b').\nProof.\n  repeat setoid_rewrite Some_included. rewrite csum_included. split.\n  - intros [Hxy|?]; [inversion Hxy|]; naive_solver.\n  - naive_solver by f_equiv.\nQed.\n\n(** Internalized properties *)\nLemma csum_validI {M} (x : csum A B) :\n  ✓ x ⊣⊢@{uPredI M} match x with\n                    | Cinl a => ✓ a\n                    | Cinr b => ✓ b\n                    | CsumBot => False\n                    end.\nProof. uPred.unseal. by destruct x. Qed.\n\n(** Updates *)\nLemma csum_update_l (a1 a2 : A) : a1 ~~> a2 → Cinl a1 ~~> Cinl a2.\nProof.\n  intros Ha n [[a|b|]|] ?; simpl in *; auto.\n  - by apply (Ha n (Some a)).\n  - by apply (Ha n None).\nQed.\nLemma csum_update_r (b1 b2 : B) : b1 ~~> b2 → Cinr b1 ~~> Cinr b2.\nProof.\n  intros Hb n [[a|b|]|] ?; simpl in *; auto.\n  - by apply (Hb n (Some b)).\n  - by apply (Hb n None).\nQed.\nLemma csum_updateP_l (P : A → Prop) (Q : csum A B → Prop) a :\n  a ~~>: P → (∀ a', P a' → Q (Cinl a')) → Cinl a ~~>: Q.\nProof.\n  intros Hx HP n mf Hm. destruct mf as [[a'|b'|]|]; try by destruct Hm.\n  - destruct (Hx n (Some a')) as (c&?&?); naive_solver.\n  - destruct (Hx n None) as (c&?&?); naive_solver eauto using cmra_validN_op_l.\nQed.\nLemma csum_updateP_r (P : B → Prop) (Q : csum A B → Prop) b :\n  b ~~>: P → (∀ b', P b' → Q (Cinr b')) → Cinr b  ~~>: Q.\nProof.\n  intros Hx HP n mf Hm. destruct mf as [[a'|b'|]|]; try by destruct Hm.\n  - destruct (Hx n (Some b')) as (c&?&?); naive_solver.\n  - destruct (Hx n None) as (c&?&?); naive_solver eauto using cmra_validN_op_l.\nQed.\nLemma csum_updateP'_l (P : A → Prop) a :\n  a ~~>: P → Cinl a ~~>: λ m', ∃ a', m' = Cinl a' ∧ P a'.\nProof. eauto using csum_updateP_l. Qed.\nLemma csum_updateP'_r (P : B → Prop) b :\n  b ~~>: P → Cinr b ~~>: λ m', ∃ b', m' = Cinr b' ∧ P b'.\nProof. eauto using csum_updateP_r. Qed.\n\nLemma csum_local_update_l (a1 a2 a1' a2' : A) :\n  (a1,a2) ~l~> (a1',a2') → (Cinl a1,Cinl a2) ~l~> (Cinl a1',Cinl a2').\nProof.\n  intros Hup n mf ? Ha1; simpl in *.\n  destruct (Hup n (mf ≫= maybe Cinl)); auto.\n  { by destruct mf as [[]|]; inversion_clear Ha1. }\n  split. done. by destruct mf as [[]|]; inversion_clear Ha1; constructor.\nQed.\nLemma csum_local_update_r (b1 b2 b1' b2' : B) :\n  (b1,b2) ~l~> (b1',b2') → (Cinr b1,Cinr b2) ~l~> (Cinr b1',Cinr b2').\nProof.\n  intros Hup n mf ? Ha1; simpl in *.\n  destruct (Hup n (mf ≫= maybe Cinr)); auto.\n  { by destruct mf as [[]|]; inversion_clear Ha1. }\n  split. done. by destruct mf as [[]|]; inversion_clear Ha1; constructor.\nQed.\nEnd cmra.\n\nArguments csumR : clear implicits.\n\n(* Functor *)\nInstance csum_map_cmra_morphism {A A' B B' : cmraT} (f : A → A') (g : B → B') :\n  CmraMorphism f → CmraMorphism g → CmraMorphism (csum_map f g).\nProof.\n  split; try apply _.\n  - intros n [a|b|]; simpl; auto using cmra_morphism_validN.\n  - move=> [a|b|]=>//=; rewrite -cmra_morphism_pcore; by destruct pcore.\n  - intros [xa|ya|] [xb|yb|]=>//=; by rewrite cmra_morphism_op.\nQed.\n\nProgram Definition csumRF (Fa Fb : rFunctor) : rFunctor := {|\n  rFunctor_car A _ B _ := csumR (rFunctor_car Fa A B) (rFunctor_car Fb A B);\n  rFunctor_map A1 _ A2 _ B1 _ B2 _ fg := csumO_map (rFunctor_map Fa fg) (rFunctor_map Fb fg)\n|}.\nNext Obligation.\n  by intros Fa Fb A1 ? A2 ? B1 ? B2 ? n f g Hfg; apply csumO_map_ne; try apply rFunctor_map_ne.\nQed.\nNext Obligation.\n  intros Fa Fb A ? B ? x. rewrite /= -{2}(csum_map_id x).\n  apply csum_map_ext=>y; apply rFunctor_map_id.\nQed.\nNext Obligation.\n  intros Fa Fb A1 ? A2 ? A3 ? B1 ? B2 ? B3 ? f g f' g' x. rewrite /= -csum_map_compose.\n  apply csum_map_ext=>y; apply rFunctor_map_compose.\nQed.\n\nInstance csumRF_contractive Fa Fb :\n  rFunctorContractive Fa → rFunctorContractive Fb →\n  rFunctorContractive (csumRF Fa Fb).\nProof.\n  intros ?? A1 ? A2 ? B1 ? B2 ? n f g Hfg.\n  by apply csumO_map_ne; try apply rFunctor_map_contractive.\nQed.\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/csum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.26623505332575265}}
{"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 *)\nSet Implicit Arguments.\n\nRequire Import Morphisms.\nRequire Import ZArith.\nRequire Import DItv.\nRequire Import DomArrayBlk.\nRequire Import UserInputType.\nRequire Import UserProofType.\nRequire Import UserInput.\nRequire GenFunc.\nRequire Import VocabA.\nRequire Import vgtac.\nRequire Import Monad.\nRequire Import Fold.\n\nInclude Input.\nInclude GenFunc.Make.\n\nDefinition Var_g (x : DomCon.Var.t) : Var.t :=\n  match x with\n  | DomCon.Var.Inl gx => Var.Inl gx\n  | DomCon.Var.Inr (_, f, lx) => Var.Inr (f, lx)\n  end.\n\nLemma var_g_mor : Proper (DomCon.Var.eq ==> Var.eq) Var_g.\nProof.\ninversion 1.\n- by constructor.\n- destruct x' as [[n1 f1] x'], y' as [[n2 f2] y2']. simpl in Heq.\n  constructor. tauto.\nQed.\n\nDefinition Allocsite_g (a : DomCon.Allocsite.t) : Allocsite.t :=\n  match a with\n  | DomCon.Allocsite.Inl n => Allocsite.Inl n\n  | DomCon.Allocsite.Inr (DomCon.ExtAllocsite.Inl f) =>\n    Allocsite.Inr (ExtAllocsite.Inl f)\n  | DomCon.Allocsite.Inr (DomCon.ExtAllocsite.Inr f) =>\n    Allocsite.Inr (ExtAllocsite.Inr f)\n  end.\n\nDefinition allocsite_g_mor :\n  Proper (DomCon.Allocsite.eq ==> Allocsite.eq) Allocsite_g.\nProof.\ninversion 1.\n- constructor. tauto.\n- inversion Heq.\n  + constructor. constructor. by auto.\n  + constructor. constructor. by auto.\nQed.\n\nDefinition VarRegion_g (vr : DomCon.VarRegion.t) : VarAllocsite.t :=\n  match vr with\n  | DomCon.VarRegion.Inl x => VarAllocsite.Inl (Var_g x)\n  | DomCon.VarRegion.Inr (_, a, _) => VarAllocsite.Inr (Allocsite_g a)\n  end.\n\nLemma varregion_g_mor :\n  Proper (DomCon.VarRegion.eq ==> VarAllocsite.eq) VarRegion_g.\nProof.\ninversion 1.\n- constructor. by apply var_g_mor.\n- destruct x' as [[n1 a1] [[o1 s1] st1]], y' as [[n2 a2] [[o2 s2] st2]].\n  simpl in *.\n  constructor. apply allocsite_g_mor. by apply Heq.\nQed.\n\nFixpoint Fields_g (fs : DomCon.Fields.t) : Fields.t :=\n  match fs with\n  | DomCon.Fields.nil => Fields.nil\n  | DomCon.Fields.cons f tl => Fields.cons f (Fields_g tl)\n  end.\n\nLemma fields_g_mor :\n  Proper (DomCon.Fields.eq ==> Fields.eq) Fields_g.\nProof.\nunfold Fields.eq. induction DNList.size.\n- intros f1 f2 Hf. apply Fields.eq_zero.\n- induction 1.\n  + apply Fields.eq_nil.\n  + apply Fields.eq_cons; [by auto|by apply IHn].\nQed.\n\nDefinition Loc_g (l : DomCon.Loc.t) : Loc.t :=\n  let (vr, fs) := l in\n  Loc.Inl (VarRegion_g vr, Fields_g fs).\n\nLemma loc_g_mor : Proper (DomCon.Loc.eq ==> Loc.eq) Loc_g.\nProof.\nintros [vr1 f1] [vr2 f2] Hl. inversion Hl. constructor. simpl in *; split.\n- by apply varregion_g_mor.\n- by apply fields_g_mor.\nQed.\n\nDefinition Itv_g := Itv.gamma.\n\nInductive ArrayBlk_g' : DomCon.Region.t -> ArrayBlk.t -> Prop :=\n| ArrayBlk_g_intro :\n    forall s a o sz st o' sz' st' ab\n           (Ho : Itv_g o o') (Hsz : Itv_g sz sz' ) (Hst : Itv_g st st')\n           (Hab : ArrayBlk.find (Allocsite_g a) ab = (o', sz', st')),\n      ArrayBlk_g' (s, a, (o, sz, st)) ab.\n\nDefinition ArrayBlk_g := ArrayBlk_g'.\n\nInductive Val_g' : DomCon.val_t -> Val.t -> Prop :=\n| Val_g_z :\n    forall z i ls ab ps (Hz : Itv_g z i), Val_g' (inl (inl z)) (i, ls, ab, ps)\n| Val_g_loc :\n    forall l i ls ab ps (Hl : PowLoc.mem (Loc_g l) ls = true),\n      Val_g' (inl (inr l)) (i, ls, ab, ps)\n| Val_g_ab :\n    forall r i ls ab ps (Hl : ArrayBlk_g r ab),\n      Val_g' (inl (inr (DomCon.VarRegion.Inr r, DomCon.Fields.nil)))\n            (i, ls, ab, ps)\n| Val_g_proc :\n    forall p i ls ab ps (Hp : PowProc.mem p ps = true),\n      Val_g' (inr p) (i, ls, ab, ps)\n.\n\nDefinition Val_g := Val_g'.\n\n(** Abstraction of Proc.t in DomCon.stack1. *)\nDefinition SProc_g (f : DomCon.Proc.t) : Loc.t := Loc.Inr f.\n\nLemma arrayBlk_g_monotone : monotone ArrayBlk.le ArrayBlk_g.\nProof.\nintros v x y. inversion 1; i. subst.\nassert (ArrInfo.le (o', sz', st') (ArrayBlk.find (Allocsite_g a) y)) as Hy\n; [rewrite <- Hab; apply Hle|].\nremember (ArrayBlk.find (Allocsite_g a) y) as oss'.\ndestruct oss' as [[o'' sz''] st''].\ninversion Hy as [[Ho'' Hsz''] Hst'']; simpl in Ho'', Hsz'', Hst''.\napply ArrayBlk_g_intro with o'' sz'' st''.\n- by apply Itv.gamma_monotone with o'.\n- by apply Itv.gamma_monotone with sz'.\n- by apply Itv.gamma_monotone with st'.\n- by auto.\nQed.\n\nLemma val_g_monotone : monotone Val.le Val_g.\nProof.\nintros v [[[i ls] ab] ps] [[[i' ls'] ab'] ps'] Hx Hle.\nunfold Val.le, Val.E3.le, Val.E2.le in Hle; simpl in Hle.\ndestruct Hle as [[[Hi Hls] Hab] Hps].\ninversion Hx; subst.\n- apply Val_g_z. by apply Itv.gamma_monotone with i.\n- apply Val_g_loc. by apply PowLoc.le_mem_true with ls.\n- apply Val_g_ab. by apply arrayBlk_g_monotone with ab.\n- apply Val_g_proc. by apply PowProc.le_mem_true with ps.\nQed.\n\nLemma val_g_mor : Proper (Logic.eq ==> Val.eq ==> Basics.impl) Val_g.\nProof.\nintros v1 v2 Hv v1' v2' Hv'; intros Hvalg.\neapply val_g_monotone; [rewrite <- Hv; by apply Hvalg|by apply Val.le_refl].\nQed.\n\nLemma var_g_eq1 :\n  forall x1 x2 x (Heq1 : Var.eq (Var_g x1) (Var.Inl x))\n     (Heq2 : Var.eq (Var_g x2) (Var.Inl x)),\n    DomCon.Var.eq x1 x2.\nProof.\ni. unfold Var_g in *.\ndestruct x1 as [x1|[[? ?] ?]]; [|by inversion Heq1].\ndestruct x2 as [x2|[[? ?] ?]]; [|by inversion Heq2].\ninversion_clear Heq1; inversion_clear Heq2. subst.\nby apply DomCon.Var.eq_refl.\nQed.\n\nLemma var_g_eq2 g :\n  forall m (Hm : SemCon.wf_non_rec_mem g m)\n     f (Hf : Global.G.is_rec f g = false)\n     x1 fs1 x2 fs2 x\n     (Hml1 : DomCon.M.In (elt:=DomCon.val_t) (DomCon.VarRegion.Inl x1, fs1) m)\n     (Hml2 : DomCon.M.In (elt:=DomCon.val_t) (DomCon.VarRegion.Inl x2, fs2) m)\n     (Heq1 : Var.eq (Var_g x1) (Var.Inr (f, x)))\n     (Heq2 : Var.eq (Var_g x2) (Var.Inr (f, x))),\n    DomCon.Var.eq x1 x2.\nProof.\ni. unfold Var_g in *.\ndestruct x1 as [x1|[[? ?] ?]]; [by inversion Heq1|].\ndestruct x2 as [x2|[[? ?] ?]]; [by inversion Heq2|].\ninversion_clear Heq1; inversion_clear Heq2; simpl in *.\ndestruct Heq as [Hf1 Hx1], Heq0 as [Hf2 Hx2]. subst.\nconstructor; s.\nsplit; [|by auto]. split; [|by auto].\neapply Hm; [by apply Hf|by apply Hml1|by apply Hml2].\nQed.\n\nLemma varregion_g_eq1 :\n  forall vr1 vr2 x\n     (Hveq1 : VarAllocsite.eq (VarRegion_g vr1) (VarAllocsite.Inl (Var.Inl x)))\n     (Hveq2 : VarAllocsite.eq (VarRegion_g vr2) (VarAllocsite.Inl (Var.Inl x))),\n    DomCon.VarRegion.eq vr1 vr2.\nProof.\ni. unfold VarRegion_g in *.\ndestruct vr1 as [x1|[[? ?] ?]]; [|by inversion Hveq1].\ndestruct vr2 as [x2|[[? ?] ?]]; [|by inversion Hveq2].\ninversion_clear Hveq1; inversion_clear Hveq2.\nconstructor. eapply var_g_eq1; [by apply Heq|by apply Heq0].\nQed.\n\nLemma varregion_g_eq2 g :\n  forall m (Hm : SemCon.wf_non_rec_mem g m)\n     f (Hf : Global.G.is_rec f g = false)\n     vr1 fs1 (Hml1 : DomCon.M.In (elt:=DomCon.val_t) (vr1, fs1) m)\n     vr2 fs2 (Hml2 : DomCon.M.In (elt:=DomCon.val_t) (vr2, fs2) m)\n     x\n     (Hveq1 :\n        VarAllocsite.eq (VarRegion_g vr1) (VarAllocsite.Inl (Var.Inr (f, x))))\n     (Hveq2 :\n        VarAllocsite.eq (VarRegion_g vr2) (VarAllocsite.Inl (Var.Inr (f, x)))),\n    DomCon.VarRegion.eq vr1 vr2.\nProof.\ni. unfold VarRegion_g in *.\ndestruct vr1 as [x1|[[? ?] ?]]; [|by inversion Hveq1].\ndestruct vr2 as [x2|[[? ?] ?]]; [|by inversion Hveq2].\ninversion_clear Hveq1; inversion_clear Hveq2.\nconstructor. eapply var_g_eq2\n; [ by apply Hm | by apply Hf | by apply Hml1 | by apply Hml2\n  | by apply Heq | by apply Heq0 ].\nQed.\n\nLemma fields_g_nil' :\n  forall f n (Hn : n > 0) (Hf : Fields.eq' n (Fields_g f) Fields.nil),\n    f = DomCon.Fields.nil.\nProof.\ndestruct n; [by inversion 1|i].\ndestruct f; [reflexivity|].\nsimpl in Hf. by inversion Hf.\nQed.\n\nLemma fields_g_nil :\n  forall f (Hf : Fields.eq (Fields_g f) Fields.nil),\n    f = DomCon.Fields.nil.\nProof.\nintros. eapply fields_g_nil'; [|by apply Hf].\nunfold DNList.size. omega.\nQed.\n\nLemma prop_approx_one_loc :\n  forall g l (Hl: approx_one_loc g l = true)\n     m (Hm : SemCon.wf_non_rec_mem g m)\n     l1 (Hl1: Loc.eq (Loc_g l1) l) (Hml1 : DomCon.M.In l1 m)\n     l2 (Hl2: Loc.eq (Loc_g l2) l) (Hml2 : DomCon.M.In l2 m),\n    DomCon.Loc.eq l1 l2.\nProof.\ni. unfold approx_one_loc in Hl.\ndestruct l as [[[[x|[f x]]|a] fs]|p]; [| |discriminate|discriminate].\n- unfold Loc_g in *. destruct l1 as [vr1 fs1], l2 as [vr2 fs2].\n  inversion_clear Hl1; inversion_clear Hl2. simpl in Heq, Heq0.\n  destruct Heq as [Hveq1 Hfs1], Heq0 as [Hveq2 Hfs2].\n  constructor; s.\n  + eapply varregion_g_eq1; [by apply Hveq1|by apply Hveq2].\n  + destruct fs; [|discriminate].\n    rewrite (fields_g_nil _ Hfs1), (fields_g_nil _ Hfs2). constructor.\n- unfold Loc_g in *. destruct l1 as [vr1 fs1], l2 as [vr2 fs2].\n  inversion_clear Hl1; inversion_clear Hl2. simpl in Heq, Heq0.\n  destruct Heq as [Hveq1 Hfs1], Heq0 as [Hveq2 Hfs2].\n  constructor; s.\n  + destruct fs; [|discriminate].\n    eapply varregion_g_eq2\n    ; [ by apply Hm | apply Bool.negb_true_iff; by apply Hl\n      | by apply Hml1 | by apply Hml2 | by apply Hveq1 | by apply Hveq2 ].\n  + destruct fs; [|discriminate].\n    rewrite (fields_g_nil _ Hfs1), (fields_g_nil _ Hfs2). constructor.\nQed.\n\nInductive Loc_opt_g : option DomCon.Loc.t -> PowLoc.t -> Prop :=\n| Loc_opt_g_none : forall l', Loc_opt_g None l'\n| Loc_opt_g_some :\n    forall l l' (Hv : PowLoc.mem (Loc_g l) l' = true), Loc_opt_g (Some l) l'.\n\nImport RunOnly RunOnly.SemMem RunOnly.SemEval.\n\nLoad MemGCommon.\nLoad MemPfCommon.\n\nLemma cor_eval_const :\n  forall c v (Hc : SemCon.Eval_const c v), Val_g v (SemEval.eval_const c).\nProof.\ndestruct 1; constructor.\n- by apply Itv.cor_itv_top.\n- by apply Itv.cor_of_int.\n- by apply Itv.cor_of_int.\n- unfold Itv.of_ints. destruct (Z_le_dec lb ub); [constructor|omega].\n  + constructor; omega.\n  + constructor; omega.\n- by apply Itv.cor_itv_top.\nQed.\n\nLemma val_g_bot_false : forall x, ~ (Val_g x Val.bot).\nProof.\ninversion_clear 1; subst.\n- by inversion Hz.\n- by inversion Hl.\n- inversion_clear Hl; subst.\n  inversion Hab; subst.\n  by inversion Hsz.\n- by inversion Hp.\nQed.\n\nLemma cor_eval_uop :\n  forall op v v' abs_v (Hu : SemCon.Eval_uop op v v') (Habs : Val_g v abs_v),\n    Val_g v' (SemEval.eval_uop op abs_v).\nProof.\ni. unfold SemEval.eval_uop.\ndestruct (Val.eq_dec abs_v Val.bot)\n; [ eapply val_g_mor in Habs\n    ; [by apply val_g_bot_false in Habs|reflexivity|by apply e] |].\ninversion Hu; subst.\n- inversion Habs; subst. constructor.\n  rewrite <- Z.sub_0_l. apply Itv.cor_minus; [by apply Itv.cor_of_int|by auto].\n- inversion Habs; subst. constructor.\n  unfold Itv.b_not_itv. apply Itv.unknown_unary_prop; i.\n  inversion Hz; subst. by inversion FH.\n- inversion Habs; subst. constructor.\n  eapply Itv.not_itv_prop1; [by apply Ht|by auto].\n- inversion Habs; subst. constructor.\n  eapply Itv.not_itv_prop2; by auto.\nQed.\n\nLemma itv_non_bot :\n  forall z abs_v (Habs : Val_g (DomCon.val_of_z z) abs_v),\n    ~ (Itv.eq (itv_of_val abs_v) Itv.bot).\nProof.\ni. destruct abs_v as [[[i ls] ab] ps].\ninversion Habs; subst.\neapply Itv.non_bot; [by apply Hz|by apply FH].\nQed.\n\nLemma itv_non_zero :\n  forall z abs_v (Ht : z <> 0%Z) (Habs : Val_g (DomCon.val_of_z z) abs_v),\n    ~ (Itv.eq (itv_of_val abs_v) Itv.zero).\nProof.\ninversion 2; subst. s; i.\nexploit Itv.gamma_mor; [reflexivity|by apply FH|by apply Hz|].\ninversion 1; subst.\nelim Ht. inversion Hle1; inversion Hle2. omega.\nQed.\n\nLocal Open Scope sumbool.\n\nLemma cor_plus_offset :\n  forall step alloc o sz st z ab i\n     (Hab : ArrayBlk_g (step, alloc, (o, sz, st)) ab) (Hz : Itv_g z i),\n    ArrayBlk_g (step, alloc, ((o + z)%Z, sz, st)) (ArrayBlk.plus_offset ab i).\nProof.\ninversion 1; subst; i.\napply ArrayBlk_g_intro with (o':=Itv.plus o' i) (st':=st') (sz':=sz')\n; [by apply Itv.cor_plus|by auto|by auto|].\nunfold ArrayBlk.plus_offset.\ndestruct (Itv.eq_dec i Itv.bot)\n; [exploit Itv.non_bot; [by apply Hz|by apply e|by auto]|].\nerewrite ArrayBlk.map_1; [| |by apply Hab0].\n- unfold ArrInfo.plus_offset.\n  destruct (Itv.eq_dec Itv.bot o'); [|reflexivity].\n  exploit Itv.non_bot; [by apply Ho|by apply Itv.eq_sym|by auto].\n- unfold ArrInfo.plus_offset. simpl.\n  destruct (Itv.eq_dec Itv.bot Itv.bot)\n  ; [by auto|elim f0; by apply Itv.eq_refl].\nQed.\n\nLemma cor_minus_offset :\n  forall step alloc o sz st z ab i\n     (Hab : ArrayBlk_g (step, alloc, (o, sz, st)) ab) (Hz : Itv_g z i),\n    ArrayBlk_g (step, alloc, ((o - z)%Z, sz, st)) (ArrayBlk.minus_offset ab i).\nProof.\ninversion 1; subst; i.\napply ArrayBlk_g_intro with (o':=Itv.minus o' i) (st':=st') (sz':=sz')\n; [by apply Itv.cor_minus|by auto|by auto|].\nunfold ArrayBlk.minus_offset.\ndestruct (Itv.eq_dec i Itv.bot)\n; [exploit Itv.non_bot; [by apply Hz|by apply e|by auto]|].\nerewrite ArrayBlk.map_1; [| |by apply Hab0].\n- unfold ArrInfo.minus_offset.\n  destruct (Itv.eq_dec Itv.bot o'); [|reflexivity].\n  exploit Itv.non_bot; [by apply Ho|by apply Itv.eq_sym|by auto].\n- unfold ArrInfo.minus_offset. simpl.\n  destruct (Itv.eq_dec Itv.bot Itv.bot)\n  ; [by auto|elim f0; by apply Itv.eq_refl].\nQed.\n\nLemma cor_plus_pi :\n  forall step alloc o sz st z v i\n     (Hv : Val_g\n                (DomCon.val_of_loc\n                   (DomCon.loc_of_alloc\n                      step alloc (o, sz, st) DomCon.Fields.nil))\n                v)\n     (Hz : Itv_g z i),\n    Val_g\n      (DomCon.val_of_loc\n         (DomCon.loc_of_alloc step alloc ((o + z)%Z, sz, st) DomCon.Fields.nil))\n      (Val.join\n         (SemEval.array_loc_of_val v)\n         (val_of_array (ArrayBlk.plus_offset (array_of_val v) i))).\nProof.\ni; inversion_clear Hv; subst.\n- eapply val_g_monotone; [apply Val_g_loc|by apply Val.join_left].\n  unfold DomCon.loc_of_alloc, Loc_g, VarRegion_g in *.\n  apply PowLoc.filter1; [by apply SemEval.is_array_loc_mor|by apply Hl|by auto].\n- eapply val_g_monotone; [apply Val_g_ab|by apply Val.join_right].\n  by apply cor_plus_offset.\nQed.\n\nLemma cor_minus_pi :\n  forall step alloc o sz st z v i\n     (Hv : Val_g\n                (DomCon.val_of_loc\n                   (DomCon.loc_of_alloc\n                      step alloc (o, sz, st) DomCon.Fields.nil))\n                v)\n     (Hz : Itv_g z i),\n    Val_g\n      (DomCon.val_of_loc\n         (DomCon.loc_of_alloc step alloc ((o - z)%Z, sz, st) DomCon.Fields.nil))\n      (Val.join\n         (SemEval.array_loc_of_val v)\n         (val_of_array (ArrayBlk.minus_offset (array_of_val v) i))).\nProof.\ni; inversion_clear Hv; subst.\n- eapply val_g_monotone; [apply Val_g_loc|by apply Val.join_left].\n  unfold DomCon.loc_of_alloc, Loc_g, VarRegion_g in *.\n  apply PowLoc.filter1; [by apply SemEval.is_array_loc_mor|by apply Hl|by auto].\n- eapply val_g_monotone; [apply Val_g_ab|by apply Val.join_right].\n  by apply cor_minus_offset.\nQed.\n\nLemma cor_eval_bop :\n  forall op v1 v2 v' abs_v1 abs_v2 (Hu : SemCon.Eval_bop op v1 v2 v')\n     (Habs1 : Val_g v1 abs_v1) (Habs2 : Val_g v2 abs_v2),\n    Val_g v' (SemEval.eval_bop op abs_v1 abs_v2).\nProof.\ninversion_clear 1; subst.\n{                               (* PlusA *)\ni. unfold SemEval.eval_bop. constructor.\ninversion_clear Habs1; inversion_clear Habs2. by apply Itv.cor_plus.\n}\n{                               (* PlusPI *)\ni. unfold SemEval.eval_bop.\ninversion_clear Habs2; subst.\nby apply cor_plus_pi.\n}\n{                               (* IndexPI *)\ni. unfold SemEval.eval_bop.\ninversion_clear Habs2; subst.\nby apply cor_plus_pi.\n}\n{                               (* MinusA *)\ni. unfold SemEval.eval_bop.\ninversion_clear Habs1; inversion_clear Habs2.\nconstructor; by apply Itv.cor_minus.\n}\n{                               (* MinusPI *)\ni. unfold SemEval.eval_bop.\ninversion_clear Habs2; subst.\nby apply cor_minus_pi.\n}\n{                               (* Mult *)\ni. unfold SemEval.eval_bop.\ninversion_clear Habs1; inversion_clear Habs2. constructor.\nby apply Itv.times_prop.\n}\n{                               (* Div *)\ni. unfold SemEval.eval_bop. constructor.\ninversion_clear Habs1; inversion_clear Habs2.\nby apply Itv.divide_prop.\n}\n{                               (* Mod *)\ni. unfold SemEval.eval_bop, Itv.mod_itv.\nconstructor. apply Itv.unknown_binary_prop; i.\n- by apply itv_non_bot in Habs1.\n- by apply itv_non_bot in Habs2.\n}\n{                               (* Shiftlt *)\ni. unfold SemEval.eval_bop, Itv.l_shift_itv.\nconstructor. apply Itv.unknown_binary_prop; i.\n- by apply itv_non_bot in Habs1.\n- by apply itv_non_bot in Habs2.\n}\n{                               (* Shiftrt *)\ni. unfold SemEval.eval_bop, Itv.r_shift_itv.\nconstructor. apply Itv.unknown_binary_prop; i.\n- by apply itv_non_bot in Habs1.\n- by apply itv_non_bot in Habs2.\n}\n{                               (* Lt *)\ni. unfold SemEval.eval_bop. constructor.\ninversion_clear Habs1; inversion_clear Habs2.\nby apply Itv.cor_lt1 with (z1:=z1) (z2:=z2).\n}\n{                               (* Lt *)\ni. unfold SemEval.eval_bop. constructor.\ninversion_clear Habs1; inversion_clear Habs2.\nby apply Itv.cor_lt0 with (z1:=z1) (z2:=z2).\n}\n{                               (* Gt *)\ni. unfold SemEval.eval_bop. constructor.\ninversion_clear Habs1; inversion_clear Habs2.\nunfold Itv.gt_itv.\napply Itv.cor_lt1 with (z1:=z2) (z2:=z1); [omega|by auto|by auto].\n}\n{                               (* Gt *)\ni. unfold SemEval.eval_bop. constructor.\ninversion_clear Habs1; inversion_clear Habs2.\nunfold Itv.gt_itv.\napply Itv.cor_lt0 with (z1:=z2) (z2:=z1); [intro; elim Hle; omega|by auto|by auto].\n}\n{                               (* Le *)\ni. unfold SemEval.eval_bop. constructor.\ninversion_clear Habs1; inversion_clear Habs2.\napply Itv.cor_le1 with (z1:=z1) (z2:=z2); by auto.\n}\n{\ni. unfold SemEval.eval_bop. constructor.\ninversion_clear Habs1; inversion_clear Habs2.\napply Itv.cor_le0 with (z1:=z1) (z2:=z2); by auto.\n}\n{                               (* Ge *)\ni. unfold SemEval.eval_bop. constructor.\ninversion_clear Habs1; inversion_clear Habs2.\nunfold Itv.ge_itv.\napply Itv.cor_le1 with (z1:=z2) (z2:=z1); [omega|by auto|by auto].\n}\n{                               (* Ge *)\ni. unfold SemEval.eval_bop. constructor.\ninversion_clear Habs1; inversion_clear Habs2.\nunfold Itv.ge_itv.\napply Itv.cor_le0 with (z1:=z2) (z2:=z1); [intro; elim Hlt; omega|by auto|by auto].\n}\n{                               (* Eq *)\ni. unfold SemEval.eval_bop. constructor.\ninversion_clear Habs1; inversion_clear Habs2.\napply Itv.cor_eq1 with (z:=z2); by auto.\n}\n{                               (* Eq *)\ni. unfold SemEval.eval_bop. constructor.\ninversion_clear Habs1; inversion_clear Habs2.\napply Itv.cor_eq0 with (z1:=z1) (z2:=z2); by auto.\n}\n{                               (* Ne *)\ni. unfold SemEval.eval_bop. constructor.\ninversion_clear Habs1; inversion_clear Habs2.\napply Itv.cor_ne1 with (z1:=z1) (z2:=z2); by auto.\n}\n{                               (* Ne *)\ni. unfold SemEval.eval_bop. constructor.\ninversion_clear Habs1; inversion_clear Habs2.\napply Itv.cor_ne0 with (z:=z2); by auto.\n}\n{                               (* BAnd *)\ni. unfold SemEval.eval_bop, Itv.b_and_itv.\nconstructor. apply Itv.unknown_binary_prop; i.\n- by apply itv_non_bot in Habs1.\n- by apply itv_non_bot in Habs2.\n}\n{                               (* BXor *)\ni. unfold SemEval.eval_bop, Itv.b_xor_itv.\nconstructor. apply Itv.unknown_binary_prop; i.\n- by apply itv_non_bot in Habs1.\n- by apply itv_non_bot in Habs2.\n}\n{                               (* BOr *)\ni. unfold SemEval.eval_bop, Itv.b_or_itv.\nconstructor. apply Itv.unknown_binary_prop; i.\n- by apply itv_non_bot in Habs1.\n- by apply itv_non_bot in Habs2.\n}\n{                               (* LAnd *)\ni. unfold SemEval.eval_bop, Itv.and_itv.\ndest_if_dec; [|dest_if_dec; [|dest_if_dec]].\n- apply False_ind. destruct o; by eauto using itv_non_bot.\n- apply False_ind. destruct Hz. destruct o as [o|o].\n  + by apply (itv_non_zero (z:=z1)) in o.\n  + by apply (itv_non_zero (z:=z2)) in o.\n- constructor. by apply Itv.true_itv_prop.\n- constructor. by apply Itv.unknown_bool_prop1.\n}\n{                               (* LAnd *)\ni. unfold SemEval.eval_bop, Itv.and_itv.\ndest_if_dec; [|dest_if_dec; [|dest_if_dec]].\n- apply False_ind. destruct o; by eauto using itv_non_bot.\n- constructor. by apply Itv.false_itv_prop.\n- destruct a1 as [a1 _]; elim a1. inversion Habs1; subst. by apply Itv.false_itv1.\n- constructor. by apply Itv.unknown_bool_prop0.\n}\n{                               (* LAnd *)\ni. unfold SemEval.eval_bop, Itv.and_itv.\ndest_if_dec; [|dest_if_dec; [|dest_if_dec]].\n- apply False_ind. destruct o; by eauto using itv_non_bot.\n- constructor. by apply Itv.false_itv_prop.\n- destruct a1 as [_ a1]; elim a1. inversion Habs2; subst. by apply Itv.false_itv1.\n- constructor. by apply Itv.unknown_bool_prop0.\n}\n{                               (* LOr *)\ni. unfold SemEval.eval_bop, Itv.or_itv.\ndest_if_dec; [|dest_if_dec; [|dest_if_dec]].\n- apply False_ind. destruct o; by eauto using itv_non_bot.\n- destruct a0; by apply itv_non_zero in Habs1.\n- constructor. by apply Itv.true_itv_prop.\n- constructor. by apply Itv.unknown_bool_prop1.\n}\n{                               (* LOr *)\ni. unfold SemEval.eval_bop, Itv.or_itv.\ndest_if_dec; [|dest_if_dec; [|dest_if_dec]].\n- apply False_ind. destruct o; by eauto using itv_non_bot.\n- destruct a0; by apply itv_non_zero in Habs2.\n- constructor. by apply Itv.true_itv_prop.\n- constructor. by apply Itv.unknown_bool_prop1.\n}\n{                               (* LOr *)\ni. unfold SemEval.eval_bop, Itv.or_itv.\ndest_if_dec; [|dest_if_dec; [|dest_if_dec]].\n- apply False_ind. destruct o; by eauto using itv_non_bot.\n- constructor. by apply Itv.false_itv_prop.\n- destruct o0 as [o0|o0]; elim o0.\n  + inversion Habs1; subst; by apply Itv.false_itv1.\n  + inversion Habs2; subst; by apply Itv.false_itv1.\n- constructor. by apply Itv.unknown_bool_prop0.\n}\nQed.\n\nLocal Close Scope sumbool.\n\nLemma eval_zero :\n  forall abs_v (Habs : Val_g (DomCon.val_of_z 0) abs_v),\n    Itv.le Itv.zero (DomAbs.itv_of_val abs_v).\nProof. inversion 1; inversion Hz; subst. by constructor. Qed.\n\nLemma cor_cast :\n  forall step alloc o o' sz sz' st st' ab\n         (Ho' : o' = (c_div (o * st) st')%Z)\n         (Hsz' : sz' = (c_div (sz * st) st')%Z)\n         (Hab : ArrayBlk_g (step, alloc, (o, sz, st)) ab),\n    ArrayBlk_g (step, alloc, (o', sz', st')) (ArrayBlk.cast_array_int st' ab).\nProof.\ninversion 3; subst. econstructor.\n- apply Itv.divide_prop; [apply Itv.times_prop|].\n  + by apply Ho.\n  + by apply Hst.\n  + by apply Itv.cor_of_int.\n- apply Itv.divide_prop; [apply Itv.times_prop|].\n  + by apply Hsz.\n  + by apply Hst.\n  + by apply Itv.cor_of_int.\n- by apply Itv.cor_of_int.\n- unfold ArrayBlk.cast_array_int, ArrayBlk.cast_array.\n  rewrite ArrayBlk.map_1 with (v:=(o'0, sz'0, st'0)); [| |by auto].\n  + destruct (Itv.eq_dec Itv.bot st'0); [|by auto].\n    apply Itv.non_bot in Hst; [by elim Hst|by apply Itv.eq_sym].\n  + s; destruct (Itv.eq_dec Itv.bot Itv.bot)\n    ; [reflexivity|by elim f; apply Itv.eq_refl].\nQed.\n\nLemma cor_pow_loc_of_array :\n  forall r ab (Hr : ArrayBlk_g r ab),\n    PowLoc.mem (Loc_g (DomCon.VarRegion.Inr r, DomCon.Fields.nil))\n               (ArrayBlk.pow_loc_of_array ab) = true.\nProof.\ninversion 1; subst; s.\nunfold ArrayBlk.pow_loc_of_array.\neapply ArrayBlk.foldi_1\nwith (teq:=PowLoc.eq) (k:=Allocsite_g a) (v:=(o', sz', st')).\n- constructor\n  ; [ intros ?; by apply PowLoc.eq_refl\n    | intros ? ? ?; by apply PowLoc.eq_trans\n    | intros ? ?; by apply PowLoc.eq_sym ].\n- intros ls1 ls2 Hls; split; intro Hmem.\n  + rewrite PowLoc.mem_mor\n    ; [by apply Hmem|by apply Loc.eq_refl|by apply PowLoc.eq_sym].\n  + rewrite PowLoc.mem_mor; [by apply Hmem|by apply Loc.eq_refl|by auto].\n- rewrite Hab; by apply ArrInfo.eq_refl.\n- destruct (ArrInfo.eq_dec ArrInfo.bot (o', sz', st'))\n  ; [ inversion e; simpl in H0; apply Itv.non_bot in Hst\n      ; [by elim Hst|by apply Itv.eq_sym] |].\n  i; apply DomBasic.PowLoc.mem_add_1; by apply Loc.eq_refl.\n- i; destruct (ArrInfo.eq_dec ArrInfo.bot v)\n  ; [by apply PowLoc.eq_refl|by elim f].\n- i; destruct (ArrInfo.eq_dec ArrInfo.bot v); [by auto|].\n  by apply PowLoc.mem_add_3.\n- i; destruct (ArrInfo.eq_dec ArrInfo.bot v1).\n  + destruct (ArrInfo.eq_dec ArrInfo.bot v2)\n    ; [|elim f; eapply ArrInfo.eq_trans; [by apply e|by auto]].\n    by auto.\n  + destruct (ArrInfo.eq_dec ArrInfo.bot v2)\n    ; [ elim f; eapply ArrInfo.eq_trans; [by apply e|by apply ArrInfo.eq_sym]\n      | rewrite <- Hf ].\n    apply PowLoc.mem_mor; [by auto|].\n    apply PowLoc.add_mor; [|by apply PowLoc.eq_refl].\n    apply DomBasic.loc_of_allocsite_mor; by apply Allocsite.eq_sym.\nQed.\n\nLemma cor_deref_of_val :\n  forall l v (Habs : Val_g (DomCon.val_of_loc l) v),\n    PowLoc.mem (Loc_g l) (SemEval.deref_of_val v) = true.\nProof.\ninversion 1; subst.\n- unfold SemEval.deref_of_val.\n  eapply PowLoc.le_mem_true; [by apply PowLoc.join_left|by apply Hl].\n- unfold SemEval.deref_of_val.\n  eapply PowLoc.le_mem_true; [by apply PowLoc.join_right|].\n  apply cor_pow_loc_of_array. by apply Hl.\nQed.\n\nLemma cor_fields_app :\n  forall fs n f,\n    Fields.eq' n (Fields_g (SemCon.fields_app1 fs f))\n               (Fields.app (Fields_g fs) f).\nProof.\ninduction fs.\n- i; s; by apply Fields.eq'_refl.\n- i; s. destruct n; [by constructor|].\n  constructor; [by auto|by apply IHfs].\nQed.\n\nLemma cor_append_field :\n  forall va fs f v (Hl : Val_g (DomCon.val_of_loc (va, fs)) v),\n    PowLoc.mem (Loc_g (va, SemCon.fields_app1 fs f))\n               (PowLoc.join\n                  (DomBasic.pow_loc_append_field (DomAbs.pow_loc_of_val v) f)\n                  (ArrayBlk.pow_loc_of_struct_w_field (DomAbs.array_of_val v) f)) =\n    true.\nProof.\ninversion 1; subst; clear Hl.\n- eapply PowLoc.mem_monotone1\n  ; [by apply Loc.eq_refl|by apply PowLoc.join_left|].\n  unfold DomBasic.pow_loc_append_field.\n  remember (fun l : Loc.t' => append_field l f) as append_f.\n  assert\n    (Loc.eq (Loc_g (va, SemCon.fields_app1 fs f)) (append_f (Loc_g (va, fs))))\n  as Hl.\n  + rewrite Heqappend_f. unfold append_field, Loc_g. constructor; s.\n    split; [by apply VarAllocsite.eq_refl|by apply cor_fields_app].\n  + rewrite Hl. apply SMLocLoc.map_1; [|by apply Hl0].\n    intros l1 l2 Hl'. subst. by apply DomBasic.append_field_mor.\n- eapply PowLoc.mem_monotone1\n  ; [by apply Loc.eq_refl|by apply PowLoc.join_right|].\n  unfold ArrayBlk.pow_loc_of_struct_w_field.\n  inversion Hl0; subst; clear Hl0.\n  apply ArrayBlk.foldi_1\n  with (teq:=PowLoc.eq) (k:=Allocsite_g a) (v:=(o', sz', st')).\n  + constructor\n    ; [ intros ?; by apply PowLoc.eq_refl\n      | intros ? ? ?; by apply PowLoc.eq_trans\n      | intros ? ?; by apply PowLoc.eq_sym ].\n  + intros l1 l2 Hl; split; intro Hmem.\n    * rewrite DomBasic.PowLoc.mem_mor\n      ; [by apply Hmem|by apply Loc.eq_refl|by apply PowLoc.eq_sym].\n    * rewrite DomBasic.PowLoc.mem_mor\n      ; [by apply Hmem|by apply Loc.eq_refl|by auto].\n  + unfold DomAbs.array_of_val.\n    rewrite <- Hab; by apply ArrInfo.eq_refl.\n  + i; dest_if_dec\n    ; [ inversion e; simpl in H0; apply Itv.non_bot in Hst\n        ; [by elim Hst|by auto] |].\n    apply PowLoc.mem_add_1.\n    constructor; split; [by apply VarAllocsite.eq_refl|by apply cor_fields_app].\n  + i. dest_if_dec. elim f0; by apply ArrInfo.eq_sym.\n  + i; dest_if_dec. by apply PowLoc.mem_add_3.\n  + i. destruct (ArrInfo.eq_dec v1 ArrInfo.bot).\n    * destruct (ArrInfo.eq_dec v2 ArrInfo.bot)\n      ; [| elim f0; eapply ArrInfo.eq_trans\n           ; [apply ArrInfo.eq_sym; by apply Hv|by auto] ].\n      by auto.\n    * destruct (ArrInfo.eq_dec v2 ArrInfo.bot)\n      ; [elim f0; eapply ArrInfo.eq_trans; [by apply Hv|by auto]|].\n      rewrite <- Hf. apply PowLoc.mem_mor; [by apply Loc.eq_refl|].\n      apply PowLoc.add_mor; [|by apply PowLoc.eq_refl].\n      apply DomBasic.append_field_mor; [|by apply Field.eq_refl].\n      apply DomBasic.loc_of_allocsite_mor; by apply Allocsite.eq_sym.\nQed.\n\nLemma cor_plus_offset_val :\n  forall step alloc o idx sz st abs_idx abs_v\n         (Habs : Val_g\n                   (DomCon.val_of_loc\n                      (DomCon.loc_of_alloc\n                         step alloc (o, sz, st) DomCon.Fields.nil))\n                   abs_v)\n         (Hidx : Itv_g idx abs_idx),\n    Val_g\n      (DomCon.val_of_loc\n         (DomCon.loc_of_alloc\n            step alloc ((o + idx)%Z, sz, st) DomCon.Fields.nil))\n      (DomAbs.modify_array\n         abs_v (ArrayBlk.plus_offset (DomAbs.array_of_val abs_v) abs_idx)).\nProof.\ni. unfold ArrayBlk.plus_offset.\ndestruct (Itv.eq_dec abs_idx Itv.bot).\n- inversion Hidx; subst. inversion e.\n- inversion Habs; subst.\n  + apply Val_g_loc. by apply Hl.\n  + apply Val_g_ab.\n    inversion Hl; subst.\n    eapply ArrayBlk_g_intro\n    ; [ apply Itv.cor_plus; [by apply Ho|by apply Hidx]\n      | by apply Hsz\n      | by apply Hst |].\n    rewrite ArrayBlk.map_1 with (v:=(o', sz', st')).\n    * s. destruct (Itv.eq_dec Itv.bot o')\n         ; [inversion Ho; subst; inversion e|reflexivity].\n    * s. destruct (Itv.eq_dec Itv.bot Itv.bot); by auto.\n    * by auto.\nQed.\n\nLemma cor_eval :\n  forall step cn e cid callee m d abs_m\n         (Hm : Mem_g (cid, callee, m, d) abs_m)\n         v (Heval : SemCon.Eval_exp step cn cid m e v),\n    Val_g v (eval Strong cn e abs_m)\n\nwith cor_eval_lv :\n  forall step cn lv cid callee m d abs_m\n    (Hm : Mem_g (cid, callee, m, d) abs_m)\n    l (Heval : SemCon.Eval_lv step cn cid m lv l),\n    PowLoc.mem (Loc_g l)\n               (eval_lv Strong cn lv abs_m)\n    = true\n\nwith cor_resolve_offset :\n  forall cn step cid callee m d o l l' abs_m\n         (Hm : Mem_g (cid, callee, m, d) abs_m)\n         (Hres : SemCon.Resolve_offset step cn cid m l o l')\n         v (Hl : Val_g (DomCon.val_of_loc l) v),\n    PowLoc.mem (Loc_g l')\n               (resolve_offset Strong cn v o abs_m)\n    = true.\nProof.\ninduction 2.\n{ s. apply cor_eval_const. by apply Hc. }\n{ s. eapply cor_mem_lookup; [|by apply Hm0|by apply Hm].\neapply cor_eval_lv; [by apply Hm|by apply Hl].\n}\n{ s. constructor. by apply Itv.cor_of_int. }\n{ s. constructor. by apply Itv.cor_of_int. }\n{ s. constructor. by apply Itv.cor_of_int. }\n{ s. constructor. by apply Itv.cor_of_int. }\n{ s. constructor. by apply Itv.cor_itv_top. }\n{ s. eapply cor_eval_uop; [by apply Hu|by apply IHHeval]. }\n{ s. eapply cor_eval_bop; [by apply Hb|by apply IHHeval1|by apply IHHeval2]. }\n{ s. unfold MId.bind.\nmatch goal with [|- context[if ?c then _ else _]] => destruct c end\n; [apply False_ind; eapply itv_non_bot; [by apply IHHeval1|by apply e]|].\nmatch goal with [|- context[if ?c then _ else _]] => destruct c end\n; [ apply False_ind; eapply itv_non_zero\n    ; [by apply Ht|by apply IHHeval1|by apply e] |].\nmatch goal with [|- context[if ?c then _ else _]] => destruct c end\n; [ by apply IHHeval2 |].\neapply val_g_monotone; [by apply IHHeval2|by apply Val.join_left].\n}\n{ s. unfold MId.bind.\nmatch goal with [|- context[if ?c then _ else _]] => destruct c end\n; [apply False_ind; eapply itv_non_bot; [by apply IHHeval1|by apply e]|].\nmatch goal with [|- context[if ?c then _ else _]] => destruct c end\n; [by apply IHHeval2|].\nmatch goal with [|- context[if ?c then _ else _]] => destruct c end\n; [elim f1; apply eval_zero; by apply IHHeval1|].\neapply val_g_monotone; [by apply IHHeval2|by apply Val.join_right].\n}\n{ s. unfold MId.bind, MId.ret.\n  rewrite Hl in IHHeval. inversion_clear IHHeval.\n- apply Val_g_loc. rewrite Hl'. simpl in *. by apply Hl0.\n- rewrite Hl'. apply Val_g_ab.\n  eapply cor_cast; [by apply Ho'|by apply Hsz'|by apply Hl0].\n}\n{ s. constructor. eapply cor_eval_lv; [by apply Hm|by apply Hl]. }\n{ s. constructor. eapply cor_eval_lv; [by apply Hm|by apply Hl]. }\n\ninduction 2.\n{ s. eapply cor_resolve_offset; [by apply Hm|by apply Ho|].\nconstructor. apply PowLoc.singleton_1. by apply Loc.eq_refl. }\n{ s. eapply cor_resolve_offset; [by apply Hm|by apply Ho|].\nconstructor. apply PowLoc.singleton_1. by apply Loc.eq_refl. }\n{ s. eapply cor_resolve_offset; [by apply Hm|by apply Ho|].\neapply cor_eval; [by apply Hm|by apply Hv]. }\n\ninduction 2; i.\n{ s. apply cor_deref_of_val. by apply Hl. }\n{ s. eapply IHHres. constructor. eapply cor_append_field. by apply Hl. }\n{ s. eapply IHHres.\nrewrite Hl'. apply cor_plus_offset_val.\n- eapply cor_mem_lookup.\n  + apply cor_deref_of_val; by apply Hl0.\n  + rewrite <- Hl; by apply Hm0.\n  + by apply Hm.\n- assert (Val_g (DomCon.val_of_z idx) (SemEval.eval Strong cn e abs_m)) as Hval_g\n  ; [eapply cor_eval; [by apply Hm|by apply Hv]|].\n  inversion Hval_g; subst. by apply Hz.\n}\nQed.\n\nLemma cor_eval_alloc' :\n  forall step cn sz\n         a (Ha : a = DomCon.Allocsite.Inl cn)\n         al (Hal : al = DomCon.loc_of_alloc step a (0%Z, sz, 1%Z) DomCon.Fields.nil)\n         v (Hv : Val_g (DomCon.val_of_z sz) v),\n    Val_g (DomCon.val_of_loc al) (eval_alloc' cn v).\nProof.\ni. rewrite Hal, Ha.\neapply val_g_monotone; [|by apply Val.join_left].\nunfold DomCon.val_of_loc.\napply Val_g_loc. s.\nunfold loc_of_allocsite, allocsite_of_node.\napply PowLoc.singleton_1; by apply Loc.eq_refl.\nQed.\n\nLemma cor_eval_string :\n  forall g cn s step sz cid callee d m m' abs_m\n     base o (Hbase : base = DomCon.loc_of_alloc step (DomCon.Allocsite.Inl cn) (o, sz, 1%Z) DomCon.Fields.nil)\n     (Hinit : SemCon.Initial_s g step (DomCon.Allocsite.Inl cn) base s m m')\n     (Hmem_g : Mem_g (cid, callee, m, d) abs_m),\n    Mem_g (cid, callee, m', d)\n          (mem_wupdate Strong\n                      (PowLoc.singleton\n                         (loc_of_allocsite (allocsite_of_node cn)))\n                      (SemEval.eval_string s) abs_m).\nProof.\ninduction s.\n- i; inversion_clear Hinit; subst.\n  eapply cor_wupdate; [| |by apply Hmem_g|reflexivity|reflexivity].\n  + apply DomBasic.PowLoc.singleton_1; by apply Loc.eq_refl.\n  + constructor; constructor; [constructor; omega|by constructor].\n- i; inversion Hinit; subst. inversion Hl; subst.\n  eapply mem_g_mor; [reflexivity|by apply mem_wupdate_double|].\n  eapply IHs; [reflexivity|by apply Htl|].\n  eapply cor_wupdate; [| |by apply Hmem_g|reflexivity|reflexivity].\n  + apply DomBasic.PowLoc.singleton_1; by apply Loc.eq_refl.\n  + constructor; constructor; [constructor; omega|by constructor].\nQed.\n\nLemma cor_eval_string_loc :\n  forall step cn sz s\n         a (Ha : a = DomCon.Allocsite.Inl cn)\n         base (Hbase : base = DomCon.loc_of_alloc step a (0%Z, sz, 1%Z) DomCon.Fields.nil),\n    Val_g (DomCon.val_of_loc base)\n          (SemEval.eval_string_loc\n             s (allocsite_of_node cn)\n             (PowLoc.singleton (loc_of_allocsite (allocsite_of_node cn)))).\nProof.\ni. unfold DomCon.val_of_loc, SemEval.eval_string_loc, DomAbs.val_of_pow_loc, DomAbs.val_of_array.\neapply val_g_monotone; [|by apply Val.join_left].\napply Val_g_loc.\nrewrite Hbase, Ha. unfold allocsite_of_node, loc_of_allocsite. s.\napply PowLoc.singleton_1. by apply Loc.eq_refl.\nQed.\n\nLemma cor_ret_some :\n  forall callee callee' cid cid' m m' retl d abs_m abs_m'\n     (Hmem_g : Mem_g (cid, callee, m, (callee', Some retl, cid') :: d) abs_m)\n         v v' (Hv : Val_g v v')\n         (Habs_m' : abs_m' = mem_wupdate Strong\n                                     (SemEval.deref_of_val\n                                        (mem_lookup\n                                           (PowLoc.singleton\n                                              (loc_of_proc callee'))\n                                           abs_m))\n                                     v' abs_m)\n         (Hm' : DomCon.M.add retl v m = m'),\n    Mem_g (cid', callee, m', d) abs_m'.\nProof.\ni. rewrite Habs_m', <- Hm'.\neapply cor_wupdate\n; [|by apply Hv|eapply weaken_mem_g; by apply Hmem_g|reflexivity|reflexivity].\napply cor_deref_of_val.\ndestruct Hmem_g as [Hm Hs]. unfold Stack_g in Hs.\nassert (Hs' : Val_g (DomCon.val_of_loc retl) (Mem.find (SProc_g callee') abs_m))\n; [eapply Hs; s; left; reflexivity|].\neapply val_g_monotone; [by apply Hs'|].\napply mem_find_mem_lookup. apply PowLoc.singleton_1. by apply Loc.eq_refl.\nQed.\n\nLemma cor_modify_itv :\n  forall v z abs_v itv_v (Hv : v = DomCon.val_of_z z) (Hz : Itv_g z itv_v),\n    Val_g v (DomAbs.modify_itv abs_v itv_v).\nProof. i; unfold DomAbs.modify_itv; subst; by apply Val_g_z. Qed.\n\nLemma Itv_g_mor :\n  forall z i1 i2 (Hz : Itv_g z i1) (Hi : Itv.eq i1 i2), Itv_g z i2.\nProof.\ninversion 1; subst; inversion 1; subst; constructor.\n- apply Itv.le'_trans with lb.\nAbort.\n\nLemma cor_gen_itv :\n  forall z lb ub (Hlb : Itv.le' lb (Itv.Int z)) (Hub : Itv.le' (Itv.Int z) ub)\n     (lb_c : Itv.eq' lb Itv.PInf -> False) (ub_c : Itv.eq' ub Itv.MInf -> False),\n    Itv_g z (Itv.gen_itv lb ub).\nProof.\ni. unfold Itv.gen_itv.\ndestruct (Itv.le'_dec lb ub)\n; [|elim f; by apply Itv.le'_trans with (Itv.Int z)].\ndestruct lb; [|elim lb_c; by apply Itv.eq'_refl|].\n- destruct ub; [| |by inversion l]; by constructor.\n- destruct ub; [| |elim ub_c; by apply Itv.eq'_refl]; by constructor.\nQed.\n\nLemma cor_minus'_one :\n  forall z1 z2 ub (Hz : (z1 < z2)%Z) (Hub : Itv.le' (Itv.Int z2) ub),\n    Itv.le' (Itv.Int z1) (Itv.minus'_one ub).\nProof.\ninversion 2; subst; simpl Itv.minus'_one.\n- by constructor.\n- constructor; omega.\nQed.\n\nLemma cor_plus'_one :\n  forall z1 z2 lb (Hz : (z1 < z2)%Z) (Hub : Itv.le' lb (Itv.Int z1)),\n    Itv.le' (Itv.plus'_one lb) (Itv.Int z2).\nProof.\ninversion 2; subst; simpl Itv.plus'_one.\n- by constructor.\n- constructor; omega.\nQed.\n\nLemma Itv_eq_min :\n  forall a b c (Hle : Itv.eq' (Itv.min' a b) c), Itv.eq' a c \\/ Itv.eq' b c.\nProof. i. unfold Itv.min' in Hle. destruct (Itv.le'_dec a b); by auto. Qed.\n\nLemma Itv_eq_max :\n  forall a b c (Hle : Itv.eq' (Itv.max' a b) c), Itv.eq' a c \\/ Itv.eq' b c.\nProof. i. unfold Itv.max' in Hle. destruct (Itv.le'_dec a b); by auto. Qed.\n\nLemma Itv_eq_min_minf :\n  forall a (Ha : Itv.eq' (Itv.minus'_one a) Itv.MInf), Itv.eq' a Itv.MInf.\nProof.\ndestruct a; i; [by inversion Ha|by inversion Ha|by apply Itv.eq'_refl].\nQed.\n\nLemma Itv_eq_max_pinf :\n  forall a (Ha : Itv.eq' (Itv.plus'_one a) Itv.PInf), Itv.eq' a Itv.PInf.\nProof.\ndestruct a; i; [by inversion Ha|by apply Itv.eq'_refl|by inversion Ha].\nQed.\n\nLemma Itv_g_meet :\n  forall z x y (Hx : Itv_g z x) (Hy : Itv_g z y), Itv_g z (Itv.meet x y).\nProof.\ninversion 1; inversion 1; subst. unfold Itv.meet.\ndest_if_dec. dest_if_dec.\napply cor_gen_itv.\n- by apply Itv.max'3.\n- by apply Itv.min'3.\n- intro Heq; apply Itv_eq_max in Heq; destruct Heq\n  ; [by elim lb_c|by elim lb_c0].\n- intro Heq; apply Itv_eq_min in Heq; destruct Heq\n  ; [by elim ub_c|by elim ub_c0].\nQed.\n\nLemma cor_itv_prune :\n  forall b z z0 i v2 abs_v2\n    (Hprune : z <> 0%Z) (Hz : Itv_g z0 i)\n    (Hb : SemCon.Eval_bop b (inl (inl z0)) v2 (DomCon.val_of_z z))\n    (Habs_v2 : Val_g v2 abs_v2),\n  Itv_g z0 (SemPrune.itv_prune b i (DomAbs.itv_of_val abs_v2)).\nProof.\ni; inversion Hb; subst\n; try (unfold SemPrune.itv_prune\n     ; inversion Hz; subst; inversion Habs_v2; subst; inversion Hz0; subst\n     ; s; by auto)\n; try (unfold SemPrune.itv_prune\n       ; inversion Hz; subst; inversion Habs_v2; subst; inversion Hz1; subst\n       ; s; by auto)\n; unfold SemPrune.itv_prune\n; inversion Hz; subst; clear Hz\n; inversion Habs_v2; subst; clear Habs_v2\n; inversion Hz; subst; clear Hz; s.\n- apply cor_gen_itv.\n  + by auto.\n  + apply Itv.min'3.\n    * by auto.\n    * eapply cor_minus'_one; [by apply Hlt|by auto].\n  + by auto.\n  + intro Hminf; apply Itv_eq_min in Hminf; elim Hminf\n    ; [by auto|intro Hminf'; by apply Itv_eq_min_minf in Hminf'].\n- apply cor_gen_itv.\n  + apply Itv.max'3.\n    * by auto.\n    * eapply cor_plus'_one with z2; [omega|by auto].\n  + by auto.\n  + intro Hpinf; apply Itv_eq_max in Hpinf; elim Hpinf\n    ; [by auto|intro Hpinf'; by apply Itv_eq_max_pinf in Hpinf'].\n  + by auto.\n- apply cor_gen_itv.\n  + by auto.\n  + apply Itv.min'3.\n    * by auto.\n    * apply Itv.le'_trans with (Itv.Int z2); [by constructor|by auto].\n  + by auto.\n  + intro Hminf; apply Itv_eq_min in Hminf; elim Hminf; by auto.\n- apply cor_gen_itv.\n  + apply Itv.max'3.\n    * by auto.\n    * apply Itv.le'_trans with (Itv.Int z2); [by auto|constructor; omega].\n  + by auto.\n  + intro Hpinf; apply Itv_eq_max in Hpinf; elim Hpinf; by auto.\n  + by auto.\n- unfold DomAbs.itv_of_val. apply Itv_g_meet.\n  + by auto.\n  + by constructor.\nQed.\n\nLemma cor_prune :\n  forall g step cn abs_m abs_m' cid m d\n     (Hmem_g : Mem_g (cid, None, m, d) abs_m)\n     e z (Hv : SemCon.Eval_exp step cn cid m e (DomCon.val_of_z z))\n     (Hprune : z <> 0%Z)\n     (HAbs : abs_m' = SemPrune.prune g Strong cn e abs_m)\n     (Hwf : SemCon.wf_non_rec_mem g m),\n    Mem_g (cid, None, m, d) abs_m'.\nProof.\nunfold SemPrune.prune; i.\ndestruct e; try (subst; by apply Hmem_g).\ndestruct e1; try (subst; by apply Hmem_g).\ndestruct lv; try (subst; by apply Hmem_g).\ndestruct lh; try (subst; by apply Hmem_g).\ndestruct o; try (subst; by apply Hmem_g).\nsubst. unfold MId.bind.\ninversion_clear Hv. inversion_clear Hv1.\neapply cor_update' with (l:=l) (v:=v1); [| | |reflexivity| |]\n; [ inversion Hl; subst; inversion Ho; subst; by apply Loc.eq_refl\n  | | by auto\n  | symmetry; by apply DomCon.M.P.F.find_mapsto_iff\n  | by auto ].\nremember (SemPrune.SemMem.mem_lookup\n          (DomBasic.PowLoc.singleton\n             (SemPrune.SemEval.eval_var cn x is_global)) abs_m) as abs_v1.\nassert (Val_g v1 abs_v1) as Habs_v1.\n{ rewrite Heqabs_v1; eapply cor_mem_lookup; [|by apply Hm|by apply Hmem_g]\n  ; inversion Hl; subst; inversion Ho; subst; s\n  ; by apply DomBasic.PowLoc.singleton_1, Loc.eq_refl. }\nremember (SemPrune.SemEval.eval Strong cn e2 abs_m) as abs_v2.\nassert (Val_g v2 abs_v2) as Habs_v2.\n{ rewrite Heqabs_v2; eapply cor_eval; [by apply Hmem_g|by apply Hv2]. }\ninversion Habs_v1; try (by constructor).\neapply cor_modify_itv; [reflexivity|].\neapply cor_itv_prune; [by apply Hprune|by apply Hz|subst; by apply Hb|by auto].\nQed.\n\nLemma cor_update_rets :\n  forall cn cid m d step callee callees ret_opt l_opt abs_m abs_m'\n         (Hcallee : PowProc.mem callee callees = true)\n         (Hret : SemCon.Eval_lv_opt step cn cid m ret_opt l_opt)\n         (Habs : Mem_g (step, Some callee, m, d) abs_m)\n         (Hupdate :\n            update_rets Strong cn callees ret_opt abs_m\n            = abs_m'),\n    Mem_g (step, Some callee, m, (callee, l_opt, cid) :: d) abs_m'.\nProof. {\ni. subst. unfold update_rets, MId.bind, MId.ret. split.\n- apply mem_wupdate_diff; [by apply Habs|].\n  i. apply SMProcLoc.map_diff.\n  unfold Loc_g, DomBasic.loc_of_proc; destruct l; inversion 1.\n- unfold RunOnly.mem_wupdate, mem_wupdate, MId.bind, MId.ret.\n  unfold weak_add, DomMem.IdMem.mem_weak_add; s.\n  apply cor_update2 with\n  (m := abs_m)\n  (l' := match ret_opt with\n         | Some ret_lv =>\n           SemPrune.SemEval.eval_lv Strong cn ret_lv abs_m\n         | None => DomBasic.PowLoc.bot\n         end).\n  + by apply Habs.\n  + destruct l_opt; inversion Hret; subst; [constructor|by constructor].\n    apply cor_eval_lv with\n    (step:=step) (cid:=cid) (m:=m) (d:=d) (callee:=Some callee)\n    ; [|by apply Hl].\n    split; by apply Habs.\n  + apply PowLoc.fold_3; [|by apply Mem.le_refl, Mem.eq_refl].\n    i. eapply Mem.le_trans; [by apply Hx|].\n    intro. destruct (Loc.eq_dec k e).\n    * eapply Val.le_trans; [|by apply Val.le_refl, Mem.weak_add_prop].\n      eapply Val.le_trans; [|by apply Val.join_right].\n      apply Val.le_refl, Mem.find_mor; [by auto|by apply Mem.eq_refl].\n    * rewrite Mem.weak_add_diff; [by apply Val.le_refl, Val.eq_refl|by auto].\n  + destruct ret_opt; [|by apply Val.bot_prop].\n    generalize\n      (SemPrune.SemEval.eval_lv Strong cn l abs_m) as v\n    ; i.\n    apply PowLoc.fold_1 with (e:=loc_of_proc callee).\n    * apply SMProcLoc.map_1; [by apply DomBasic.loc_of_proc_mor|by auto].\n    * i.\n      eapply Val.le_trans\n      ; [ by apply Val.join_left\n        | by apply Val.le_refl, Mem.weak_add_prop, Loc.eq_refl ].\n    * i; s. destruct (Loc.eq_dec (loc_of_proc callee) e').\n      { eapply Val.le_trans\n        ; [by apply Val.join_left|by apply Val.le_refl, Mem.weak_add_prop]. }\n      { rewrite Mem.weak_add_diff; by auto. }\n    * i. eapply Val.le_trans; [by apply He0|].\n      apply Mem.find_mor'; [by apply Loc.eq_refl|].\n      apply Mem.weak_add_mor'\n      ; [ by auto\n        | by apply Val.le_refl, Val.eq_refl\n        | by apply Mem.le_refl, Mem.eq_refl ].\n} Qed.\n\n\nInductive Val_g_list : list DomCon.val_t -> list Val.t -> Prop :=\n| Val_g_list_nil : Val_g_list nil nil\n| Val_g_list_cons :\n    forall v v' vs vs' (Hv : Val_g v v') (Hvs : Val_g_list vs vs'),\n      Val_g_list (cons v vs) (cons v' vs').\n\nLemma cor_eval_list :\n  forall step cn cid callee m d m'\n     (Hm : Mem_g (cid, callee, m, d) m')\n     es vs (Hvs : SemCon.Eval_list step cn cid m es vs)\n     vs' (Hvs' : SemEval.eval_list Strong cn es m' = vs'),\n    Val_g_list vs vs'.\nProof.\ninduction 2; i.\n- simpl in Hvs'. subst. by constructor.\n- simpl in Hvs'. subst. constructor.\n  + eapply cor_eval; [by apply Hm|by apply Hv].\n  + by apply IHHvs.\nQed.\n\nLemma bind_arg_monotone :\n  forall f x v, Proper (Mem.le ==> Mem.le) (bind_arg Strong f x v).\nProof. unfold bind_arg. i. by apply mem_wupdate_monotone. Qed.\n\nLemma cor_bind_arg :\n  forall step opt_callee d  callee x v v' m m' abs_m abs_m'\n     (Hm_g : Mem_g (step, opt_callee, m, d) abs_m)\n     (Hv_g : Val_g v v')\n     (Hm :\n        DomCon.M.add (DomCon.loc_of_lvar step callee x DomCon.Fields.nil) v m\n        = m')\n     (Habs_m : bind_arg Strong callee x v' abs_m = abs_m'),\n    Mem_g (step, opt_callee, m', d) abs_m'.\nProof.\ni; subst. unfold bind_arg.\neapply cor_wupdate; [|by apply Hv_g|by apply Hm_g|reflexivity|reflexivity].\nby apply PowLoc.singleton_1.\nQed.\n\nLemma list_fold2_m_monotone A B :\n  forall (f: A -> B -> Mem.t -> Mem.t) l vs\n     (Hf : forall a b, Proper (Mem.le ==> Mem.le) (f a b)),\n    Proper (Mem.le ==> Mem.le) (list_fold2_m f l vs).\nProof.\ninduction l.\n- intros vs m1 m2 Hm. s. destruct vs; by auto.\n- intros vs Hf m1 m2 Hm. s. destruct vs; [by auto|].\n  apply IHl; [by auto|by apply Hf].\nQed.\n\nLemma list_fold2_m_ext A B :\n  forall (f : A -> B -> Mem.t -> Mem.t) l m m' vs\n     (Hm : Mem.le m m') (Hf : forall a b m, Mem.le m (f a b m)),\n    Mem.le m (list_fold2_m f l vs m').\nProof.\ninduction l.\n- i; s. destruct vs; by auto.\n- i; s. destruct vs; [by auto|].\n  unfold MId.bind. apply IHl; [|by auto].\n  eapply Mem.le_trans; [by apply Hm|by apply Hf].\nQed.\n\nLemma bind_args_monotone :\n  forall g vs f, Proper (Mem.le ==> Mem.le) (bind_args Strong g vs f).\nProof.\ni. intros m1 m2 Hm. unfold bind_args.\ndestruct (InterCfg.get_args (Global.G.icfg g) f); [|by auto].\napply list_fold2_m_monotone; [by apply bind_arg_monotone|by auto].\nQed.\n\nLemma bind_args_ext :\n  forall g vs e m, Mem.le m (bind_args Strong g vs e m).\nProof.\nunfold bind_args. i. destruct (InterCfg.get_args (Global.G.icfg g) e).\n- apply list_fold2_m_ext; [by apply Mem.le_refl, Mem.eq_refl|].\n  unfold bind_arg. i. by apply mem_wupdate_ext.\n- by apply Mem.le_refl, Mem.eq_refl.\nQed.\n\nLemma cor_bind_args :\n  forall g step opt_callee callee callees callee_args vs vs' m m' d\n     abs_m abs_m'\n     (Hmem_g : Mem_g (step, opt_callee, m, d) abs_m)\n     (Hargs_p : Some callee_args = InterCfg.get_args (Global.G.icfg g) callee)\n     (Hbind : SemCon.Bind_list step callee callee_args vs m m')\n     (Hval_g : Val_g_list vs vs')\n     (Hcallee_g : PowProc.mem callee callees = true)\n     (Habs_m' : abs_m' = BJProcMem.weak_big_join\n                           (bind_args Strong g vs')\n                           callees abs_m),\n    Mem_g (step, opt_callee, m', d) abs_m'.\nProof.\ni; subst.\neapply mem_g_monotone\n; [|apply BJProcMem.weak_big_join_1; [by apply Hcallee_g| |]].\n- unfold bind_args. rewrite <- Hargs_p.\n  generalize vs m m' Hbind vs' Hval_g abs_m Hmem_g Hcallee_g.\n  clear vs vs' m m' abs_m Hmem_g Hargs_p Hbind Hval_g Hcallee_g.\n  induction 1; i.\n  + inversion Hval_g; subst. simpl list_fold2_m. by apply Hmem_g.\n  + inversion Hval_g; subst. simpl list_fold2_m. unfold MId.bind. apply IHHbind.\n    * by inversion Hval_g.\n    * eapply cor_bind_arg\n      ; [by apply Hmem_g|by apply Hv|reflexivity|reflexivity].\n    * by auto.\n- intros f1 f2 Hf. subst. by apply bind_args_monotone.\n- unfold MId.le, MId.ret. i. by apply bind_args_ext.\nQed.\n\nLemma correct_run :\n  forall g step cn cmd con_s con_s' abs_m abs_m'\n    (Hmem_g : Mem_g con_s abs_m)\n    (HCon : SemCon.Run g step cn cmd con_s con_s')\n    (HAbs : abs_m' = run_only Strong g cn cmd abs_m),\n    Mem_g con_s' abs_m'.\nProof. {\ndestruct 2.\n{ simpl run_only; i; unfold MId.bind in HAbs; subst abs_m'; destruct lv, lh, o\n  ; try (eapply cor_update with (l:=l) (g:=g)\n         ; [ by apply Loc.eq_refl\n           | eapply cor_eval; [by apply Hmem_g|by apply Hv]\n           | by apply Hmem_g\n           | destruct is_global; inversion Hl; subst; inversion Ho; subst\n             ; reflexivity\n           | by auto\n           | by auto ])\n  ; try (eapply cor_wupdate with (l:=l)\n         ; [ eapply cor_eval_lv; [by apply Hmem_g|by apply Hl]\n           | eapply cor_eval; [by apply Hmem_g|by apply Hv]\n           | by apply Hmem_g\n           | try (destruct is_global; inversion Hl; subst; inversion Ho; subst)\n             ; reflexivity\n           | by auto ]).\n}\n{ simpl run_only. i.\neapply cor_wupdate; [| |by apply Hmem_g|by apply HAbs|symmetry; by apply Hm'].\n- eapply cor_eval_lv; [by apply Hmem_g|by apply Hl].\n- eapply cor_eval_alloc'; [by apply Ha|by apply Hal|].\n  eapply cor_eval; [by apply Hmem_g|by apply Hsz].\n}\n{ simpl run_only. i.\neapply cor_wupdate; [| | |by apply HAbs|symmetry; by apply Hm''].\n- eapply cor_eval_lv; [by apply Hmem_g|by apply Hl].\n- eapply cor_eval_string_loc; [by apply Ha|by apply Hbase].\n- rewrite Ha in *; eapply cor_eval_string\n  ; [by apply Hbase|by apply Hinit|by apply Hmem_g].\n}\n{ simpl run_only. i.\neapply cor_wupdate\n; [| |by apply Hmem_g|by apply HAbs|symmetry; by apply Hm'].\n- eapply cor_eval_lv; [by apply Hmem_g|by apply Hl].\n- unfold DomCon.val_of_proc, DomAbs.val_of_pow_proc.\n  apply Val_g_proc. by apply PowProc.singleton_1.\n}\n{ simpl run_only. i.\n  eapply cor_prune\n  ; [by apply Hmem_g|by apply Hv|by apply Hprune|by apply HAbs|by apply Hwf].\n}\n{ unfold run_only, run, MId.bind, MId.ret. i.\nremember (Global.G.is_undef_e f g) as ud; destruct ud; [discriminate|].\nrewrite HAbs. clear HAbs Hf_def Hequd.\neapply cor_bind_args\nwith (callees := powProc_of_val (eval Strong cn f abs_m))\n; [|by apply Hargs_p|by apply Hbind| | |reflexivity].\n- eapply cor_update_rets;\n  [|by apply Hret|by apply Hmem_g|reflexivity].\n  exploit cor_eval; [by apply Hmem_g|by apply Hf|].\n  i. inversion x0; subst.\n  assert (RunOnly.eval = eval) as eval'; [reflexivity|by rewrite eval', <- H].\n- eapply cor_eval_list; [by apply Hmem_g|by apply Hargs|reflexivity].\n- exploit cor_eval; [by apply Hmem_g|by apply Hf|].\n  i. inversion x0; subst. by auto.\n}\n{ simpl run_only. i.\neapply cor_ret_some with (cid:=cid)\n; [|eapply cor_eval; [by apply Hmem_g|by apply Hv]|by apply HAbs|by apply Hm'].\neapply cor_remove_local_variables; [by apply Hmem_g|reflexivity].\n}\n{ simpl run_only. i. rewrite HAbs.\neapply cor_remove_local_variables; [|by apply Hm'].\neapply weaken_mem_g. by apply Hmem_g.\n}\n{ simpl run_only. i. by rewrite HAbs. }\n{ simpl run_only. i. by rewrite HAbs. }\n} Qed.\n", "meta": {"author": "ropas", "repo": "zooberry", "sha": "17b1cb1a44c2a796d6b7d85c2026b142685d291b", "save_path": "github-repos/coq/ropas-zooberry", "path": "github-repos/coq/ropas-zooberry/zooberry-17b1cb1a44c2a796d6b7d85c2026b142685d291b/spec/ItvProof/SemProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.26623505332575265}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect ssrbool ssrfun eqtype ssrnat seq div.\nRequire Import fintype paths finfun bigops finset prime binomial groups.\nRequire Import morphisms perm action automorphism normal zmodp cyclic.\nRequire Import gfunc pgroups gprod center commutators.\nRequire Import gseries nilpotent sylow abelian maximal hall.\nRequire Import BGsection1 BGsection4 BGsection5 BGsection6.\nRequire Import BGsection7 BGsection8.\n\n(******************************************************************************)\n(*   This file covers B & G, section 9, i.e., the proof the Uniqueness        *)\n(* Theorem, along with the several variants and auxiliary results. Note that  *)\n(* this is the only file to import BGsection8.                                *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nImport GroupScope.\n\nSection Nine.\n\nVariable gT : minSimpleOddGroupType.\nLocal Notation G := (TheMinSimpleOddGroup gT).\nImplicit Types H K L M A B P Q R : {group gT}.\nImplicit Types p q r : nat.\n\n(* This is B & G, Theorem 9.1(b) *)\nLemma noncyclic_normed_sub_Uniqueness : forall p M B,\n    M \\in 'M -> B \\in 'E_p(M) -> ~~ cyclic B ->\n    \\bigcup_(K \\in |/|_G(B; p^')) K \\subset M ->\n  B \\in 'U.\nProof.\nmove=> p M B maxM; case/pElemP=> sBM abelB ncycB snbBp'_M.\nhave prM := mmax_proper maxM; have solM := mFT_sol prM.\nhave [pB cBB _] := and3P abelB.\napply/uniq_mmaxP; exists M; symmetry; apply/eqP.\nrewrite eqEsubset sub1set inE maxM sBM; apply/subsetPn=> [[H0 MB_H0 neH0M]].\nhave:= erefl [arg max_(H > H0 | (H \\in 'M(B)) && (H :!=: M)) #|H :&: M|`_p].\nhave [|H] := arg_maxP; first by rewrite MB_H0; rewrite inE in neH0M.\nrewrite inE -andbA; case/and3P=> maxH sBH neHM maxHM _ {H0 MB_H0 neH0M}.\nhave sB_HM: B \\subset H :&: M by rewrite subsetI sBH.\nhave{sB_HM} [R sylR sBR] := Sylow_superset sB_HM pB.\nhave [] := and3P sylR; rewrite subsetI; case/andP=> sRH sRM pR _.\nhave [P sylP sRP] := Sylow_superset sRM pR; have [sPM pP _] := and3P sylP.\nhave sHp'M: 'O_p^'(H) \\subset M.\n  apply: subset_trans snbBp'_M; rewrite (bigcup_max 'O_p^'(H)%G) // inE -andbA.\n  by rewrite subsetT pcore_pgroup (subset_trans sBH) ?bgFunc_norm.\nhave{snbBp'_M} defMp': <<\\bigcup_(K \\in |/|_G(P; p^')) K>> = 'O_p^'(M).\n  have nMp'M: M \\subset 'N('O_p^'(M)) by exact: bgFunc_norm.\n  have nMp'P := subset_trans sPM nMp'M.\n  apply/eqP; rewrite eqEsubset gen_subG sub_gen ?andbT; last first.\n    by rewrite (bigcup_max 'O_p^'(M)%G) // inE -andbA subsetT pcore_pgroup.\n  apply/bigcupsP=> K; rewrite inE -andbA; case/and3P=> _ p'K nKP.\n  have sKM: K \\subset M.\n    apply: subset_trans snbBp'_M; rewrite (bigcup_max K) // inE -andbA subsetT.\n    by rewrite p'K (subset_trans (subset_trans sBR sRP)).\n  rewrite -quotient_sub1 ?(subset_trans sKM) //=; set Mp' := 'O__(M).\n  have tiKp: 'O_p(M / Mp') :&: (K / _) = 1.\n    exact: coprime_TIg (pnat_coprime (pcore_pgroup _ _) (quotient_pgroup _ _)).\n  suffices sKMp: K / _ \\subset 'O_p(M / Mp') by rewrite -(setIidPr sKMp) tiKp.\n  rewrite -Fitting_eq_pcore ?trivg_pcore_quotient //.\n  apply: subset_trans (cent_sub_Fitting (quotient_sol _ solM)).\n  rewrite subsetI quotientS //= (Fitting_eq_pcore (trivg_pcore_quotient _ _)).\n  rewrite (sameP commG1P trivgP) /= -/Mp' -tiKp subsetI commg_subl commg_subr.\n  rewrite (subset_trans (quotientS _ sKM)) ?bgFunc_norm //=.\n  apply: subset_trans (pcore_sub_Hall (quotient_pHall nMp'P sylP)) _.\n  by rewrite quotient_norms.\nhave ntR: R :!=: 1.\n  by case: eqP sBR ncycB => // ->; move/trivgP->; rewrite cyclic1.\nhave{defMp'} sNPM: 'N(P) \\subset M.\n  case: (eqVneq 'O_p^'(M) 1) => [Mp'1 | ntMp'].\n    have nsZLP: 'Z('L(P)) <| M.\n      apply: Puig_center_normal Mp'1 => //; exact: mFT_odd.\n    rewrite -(mmax_normal maxM nsZLP).\n      exact: char_norm_trans (center_Puig_char P) _.\n    apply: contra ntR; move/eqP; move/(trivg_center_Puig_pgroup pP)=> P1.\n    by rewrite -subG1 -P1.\n  rewrite -(mmax_normal maxM (pcore_normal _ _) ntMp') /= -defMp' norms_gen //.\n  apply/subsetP=> x nPx; rewrite inE sub_conjg; apply/bigcupsP=> K.\n  rewrite inE -andbA -sub_conjg; case/and3P=> _ p'K nKP.\n  rewrite (bigcup_max (K :^ x)%G) // inE -andbA subsetT pgroupJ p'K /=.\n  by rewrite -(normP nPx) normJ conjSg.\nhave sylPG := mmax_sigma_Sylow maxM sylP sNPM.\nhave{sNPM} [sNRM sylRH]: 'N(R) \\subset M /\\ p.-Sylow(H) R.\n  have:= sRP; rewrite subEproper; case/predU1P=> [defR | ltRP].\n    by split; rewrite defR // (pHall_subl _ (subsetT _)) // -defR.\n  have [|D]:= @mmax_exists _ 'N(R).\n    by rewrite mFT_norm_proper // (mFT_pgroup_proper pR).\n  case/setIdP=> maxD sND; move/implyP: (maxHM D); rewrite inE {}maxD /= leqNgt.\n  rewrite (subset_trans (subset_trans sBR (normG R))) //= implybN.\n  have ltRN := nilpotent_proper_norm (pgroup_nil pP) ltRP.\n  rewrite -(card_Hall sylR) (leq_trans (proper_card ltRN)) /=; last first.\n    rewrite setIC -(part_pnat_id (pgroupS (subsetIr _ _) pP)) dvdn_leq //.\n    by rewrite partn_dvd ?cardG_gt0 // cardSg // setISS.\n  move/eqP=> defD; rewrite defD in sND; split; rewrite // -Sylow_subnorm.\n  by rewrite (pHall_subl _ _ sylR) ?setIS // subsetI sRH normG.\nhave sFH_RHp': 'F(H) \\subset R * 'O_p^'(H).\n  case/dprodP: (nilpotent_pcoreC p (Fitting_nil H)) => _ /= <- _ _.\n  by rewrite p_core_Fitting mulgSS ?(pcore_sub_Hall sylRH) ?pcore_Fitting.\nhave sFH_M: 'F(H) \\subset M by rewrite (subset_trans sFH_RHp') ?mul_subG.\ncase/(H :=P: M): neHM; case: (ltnP 2 'r('F(H))) => [le3r | ge2r].\n  have [D uF_D] := uniq_mmaxP (Fitting_Uniqueness maxH le3r).\n  by rewrite (eq_uniq_mmax uF_D maxM) // (eq_uniq_mmax uF_D maxH) ?Fitting_sub.\nhave nHp'R: R \\subset 'N('O_p^'(H)) by rewrite (subset_trans sRH) ?bgFunc_norm.\nhave nsRHp'H: R <*> 'O_p^'(H) <| H.\n  rewrite sub_der1_normal //= ?mulgen_subG ?sRH ?pcore_sub //.\n  rewrite norm_mulgenEl // (subset_trans _ sFH_RHp') //.\n  rewrite rank2_der1_sub_Fitting ?mFT_odd //.\n  by rewrite mFT_sol ?mmax_proper.\nhave sylR_RHp': p.-Sylow(R <*> 'O_p^'(H)) R.\n  by apply: (pHall_subl _ _ sylRH); rewrite ?mulgen_subl // normal_sub.\nrewrite (mmax_max maxH) // -(Frattini_arg nsRHp'H sylR_RHp') /=.\nby rewrite mulG_subG mulgen_subG sRM sHp'M /= setIC subIset ?sNRM.\nQed.\n\n(* This is B & G, Theorem 9.1(a) *)\nLemma noncyclic_cent1_sub_Uniqueness : forall p M B,\n    M \\in 'M -> B \\in 'E_p(M) -> ~~ cyclic B ->\n    \\bigcup_(b \\in B^#) 'C[b] \\subset M ->\n  B \\in 'U.\nProof.\nmove=> p M B maxM EpB ncycB sCB_M.\napply: (noncyclic_normed_sub_Uniqueness maxM EpB) => //.\napply/bigcupsP=> K; rewrite inE -andbA; case/and3P=> _ p'K nKB.\ncase/pElemP: EpB => _; case/and3P=> pB cBB _.\nrewrite (coprime_abelian_gen_cent1 cBB ncycB nKB); last first.\n  by rewrite coprime_sym (pnat_coprime pB).\nrewrite bigprodGE gen_subG (subset_trans _ sCB_M) //.\nby apply/bigcupsP=> b Bb; rewrite (bigcup_max b) // subsetIr.\nQed.\n\n(* This is B & G, Corollary 9.2 *)\nLemma cent_uniq_Uniqueness : forall K L,\n  L \\in 'U -> K \\subset 'C(L) -> 'r(K) >= 2 -> K \\in 'U.\nProof.\nmove=> K L uL; have ntL := uniq_mmax_neq1 uL.\ncase/uniq_mmaxP: uL => H uL_H cLK; have [maxH sLH] := mem_uniq_mmax uL_H.\ncase/rank_geP=> B; case/nElemP=> p; case/pnElemP=> sBK abelB; move/eqP=> dimB2.\nhave scBH: \\bigcup_(b \\in B^#) 'C[b] \\subset H.\n  apply/bigcupsP=> b; case/setIdP; rewrite inE -cycle_eq1 => ntb Bb.\n  apply: (sub_uniq_mmax uL_H); last by rewrite /= -cent_cycle mFT_cent_proper.\n  by rewrite sub_cent1 (subsetP cLK) ?(subsetP sBK).\nhave EpB: B \\in 'E_p(H).\n  apply/pElemP; split=> //; rewrite -(setD1K (group1 B)) subUset sub1G /=.\n  apply/subsetP=> b Bb; apply: (subsetP scBH).\n  by apply/bigcupP; exists b => //; exact/cent1P.\nhave prK: K \\proper G by rewrite (sub_proper_trans cLK) ?mFT_cent_proper.\napply: uniq_mmaxS prK (noncyclic_cent1_sub_Uniqueness _ EpB _ _) => //.\nby rewrite (abelem_cyclic abelB) (eqP dimB2).\nQed.\n\n(* This is B & G, Corollary 9.3 *)\nLemma any_cent_rank3_Uniquness : forall p A B,\n    abelian A -> p.-group A -> 'r(A) >= 3 -> A \\in 'U ->\n    p.-group B -> ~~ cyclic B -> 'r_p('C(B)) >= 3 ->\n  B \\in 'U.\nProof.\nmove=> p A B cAA pA rA3 uA pB ncycB; case/p_rank_geP=> C /= Ep3C.\nhave [cBC abelC dimC3] := pnElemP Ep3C; have [pC cCC _] := and3P abelC.\nhave [P /= sylP sCP] := Sylow_superset (subsetT _) pC.\nwlog sAP: A pA cAA rA3 uA / A \\subset P.\n  move=> IHA; have [x _] := Sylow_Jsub sylP (subsetT _) pA.\n  by apply: IHA; rewrite ?pgroupJ ?abelianJ ?rankJ ?uniq_mmaxJ.\nhave ncycC: ~~ cyclic C by rewrite (abelem_cyclic abelC) dimC3.\nhave ncycP: ~~ cyclic P := contra (cyclicS sCP) ncycC.\nhave [D] := ex_odd_normal_abelem2 (pHall_pgroup sylP) (mFT_odd _) ncycP.\ncase/andP=> sDP nDP; case/pnElemP=> _ abelD dimD2.\nhave CADge2: 'r('C_A(D)) >= 2.\n  move: rA3; rewrite (rank_pgroup pA); case/p_rank_geP=> E.\n  case/pnElemP=> sEA abelE dimE3; apply: leq_trans (rankS (setSI _ sEA)).\n  rewrite (rank_abelem (abelemS (subsetIl _ _) abelE)) -(leq_add2r 1) addn1.\n  rewrite -dimE3 -leq_sub_add -logn_div ?cardSg ?divgS ?subsetIl //.\n  rewrite logn_quotient_cent_abelem ?dimD2 //.\n  exact: subset_trans (subset_trans sAP nDP).\nhave CCDge2: 'r('C_C(D)) >= 2.\n  rewrite (rank_abelem (abelemS (subsetIl _ _) abelC)) -(leq_add2r 1) addn1.\n  rewrite -dimC3 -leq_sub_add -logn_div ?cardSg ?divgS ?subsetIl //.\n  by rewrite logn_quotient_cent_abelem ?dimD2 //; exact: subset_trans nDP.\nrewrite centsC in cBC; apply: cent_uniq_Uniqueness cBC _; last first.\n  by rewrite ltnNge (rank_pgroup pB) -odd_pgroup_rank1_cyclic ?mFT_odd.\nhave cCDC: C \\subset 'C('C_C(D))\n  by rewrite (sub_abelian_cent (abelem_abelian abelC)) ?subsetIl.\napply: cent_uniq_Uniqueness cCDC _; last by rewrite (rank_abelem abelC) dimC3.\napply: cent_uniq_Uniqueness (subsetIr _ _) CCDge2.\nhave cDCA: D \\subset 'C('C_A(D)) by rewrite centsC subsetIr.\napply: cent_uniq_Uniqueness cDCA _; last by rewrite (rank_abelem abelD) dimD2.\nby apply: cent_uniq_Uniqueness uA _ CADge2; rewrite subIset // -abelianE cAA.\nQed.\n\n(* This is B & G, Lemma 9.4 *)\nLemma any_rank3_Fitting_Uniqueness : forall p M P,\n  M \\in 'M -> 'r_p('F(M)) >= 3 -> p.-group P -> 'r(P) >= 3 -> P \\in 'U.\nProof.\nmove=> p M P maxM FMge3 pP; rewrite (rank_pgroup pP).\ncase/p_rank_geP=> B; case/pnElemP=> sBP abelB dimB3.\nhave [pB cBB _] := and3P abelB.\nhave CBge3: 'r_p('C(B)) >= 3 by rewrite -dimB3 -(p_rank_abelem abelB) p_rankS.\nhave ncycB: ~~ cyclic B by rewrite (abelem_cyclic abelB) dimB3.\napply: {P pP}uniq_mmaxS sBP (mFT_pgroup_proper pP) _.\ncase/orP: (orbN (p.-group 'F(M))) => [pFM | pFM'].\n  have [P sylP sFP] := Sylow_superset (Fitting_sub _) pFM.\n  have pP := pHall_pgroup sylP.\n  have [|A SCN_A]:= p_rank_3_SCN pP (mFT_odd _).\n    by rewrite (rank_pgroup pP) (leq_trans FMge3) ?p_rankS.\n  have [_ _ uA] := SCN_Fitting_Uniqueness maxM pFM sylP FMge3 SCN_A.\n  case/setIdP: SCN_A => SCN_A dimA3; case: (setIdP SCN_A); case/andP=> sAP _ _.\n  have cAA := SCN_abelian SCN_A; have pA := pgroupS sAP pP.\n  exact: (any_cent_rank3_Uniquness cAA pA).\nhave [A0 EpA0 A0ge3] := p_rank_pmaxElem_exists FMge3.\nhave uA := non_pcore_Fitting_Uniqueness maxM pFM' EpA0 A0ge3.\ncase/pmaxElemP: EpA0; case/setIdP=> _ abelA0 _.\nhave [pA0 cA0A0 _] := and3P abelA0; rewrite -rank_pgroup // in A0ge3.\nrewrite (any_cent_rank3_Uniquness _ pA0) // (cent_uniq_Uniqueness uA) 1?ltnW //.\nby rewrite centsC subsetIr.\nQed.\n\n(* This is B & G, Lemma 9.5 *)\nLemma SCN_3_Uniqueness : forall p A, A \\in 'SCN_3[p] -> A \\in 'U.\nProof.\nmove=> p A SCN3_A; apply/idPn=> uA'.\nhave [P]:= bigcupP SCN3_A; rewrite inE => sylP; case/setIdP=> SCN_A Age3.\nhave [nsAP _] := setIdP SCN_A; have [sAP nAP] := andP nsAP.\nhave cAA := SCN_abelian SCN_A.\nhave pP := pHall_pgroup sylP; have pA := pgroupS sAP pP.\nhave ntA: A :!=: 1 by rewrite -rank_gt0 -(subnKC Age3).\nhave [p_pr _ [e oA]] := pgroup_pdiv pA ntA.\nhave{e oA} def_piA: \\pi(#|A|) =i (p : nat_pred).\n  by rewrite oA pi_of_exp //; exact: pi_of_prime.\nhave FmCAp_le2: forall M, M \\in 'M('C(A)) -> 'r_p('F(M)) <= 2.\n  move=> M; case/setIdP=> maxM cCAM; rewrite leqNgt; apply: contra uA' => Fge3.\n  exact: (any_rank3_Fitting_Uniqueness maxM Fge3).\nhave sNP_mCA: forall M, M \\in 'M('C(A)) -> 'N(P) \\subset M.\n  move=> M mCA_M; have Fple2 := FmCAp_le2 M mCA_M.\n  case/setIdP: mCA_M => maxM sCAM; set F := 'F(M) in Fple2.\n  have sNR_M: forall R, A \\subset R -> R \\subset P :&: M -> 'N(R) \\subset M.\n    move=> R sAR; rewrite subsetI; case/andP=> sRP sRM.\n    pose q := if 'r(F) <= 2 then max_pdiv #|M| else s2val (rank_witness 'F(M)).\n    have nMqR: R \\subset 'N('O_q(M)) := subset_trans sRM (bgFunc_norm _ _).\n    have{nMqR} [Q maxQ sMqQ] := max_normed_exists (pcore_pgroup _ _) nMqR.\n    have [p'q sNQ_M]: q != p /\\ 'N(Q) \\subset M.\n      case/mem_max_normed: maxQ sMqQ; rewrite {}/q.\n      case: leqP => [Fle2 | ]; last first.\n        case: rank_witness => q /= q_pr -> Fge3 qQ _ sMqQ; split=> //.\n          by case: eqP Fge3 => // ->; rewrite ltnNge Fple2.\n        have Mqge3: 'r('O_q(M)) >= 3.\n          rewrite (rank_pgroup (pcore_pgroup _ _)) /= -p_core_Fitting.\n          by rewrite -(p_rank_Sylow (nilpotent_pcore_Hall _ (Fitting_nil _))).\n        have uMq: 'O_q(M)%G \\in 'U.\n          exact: (any_rank3_Fitting_Uniqueness _ Fge3 (pcore_pgroup _ _)).\n        have uMqM := def_uniq_mmax uMq maxM (pcore_sub _ _).\n        apply: sub_uniq_mmax (subset_trans sMqQ (normG _)) _ => //.\n        apply: mFT_norm_proper (mFT_pgroup_proper qQ).\n        by rewrite -rank_gt0 2?ltnW ?(leq_trans Mqge3) ?rankS.\n      set q := max_pdiv _ => qQ _ sMqQ.\n      have sylMq: q.-Sylow(M) 'O_q(M).\n        by rewrite [pHall _ _ _]rank2_pcore_max_Sylow ?mFT_odd ?mmax_sol.\n      have defNMq: 'N('O_q(M)) = M.\n        rewrite (mmax_normal maxM (pcore_normal _ _)) // -rank_gt0.\n        rewrite (rank_pgroup (pcore_pgroup _ _)) -(p_rank_Sylow sylMq).\n        by rewrite p_rank_gt0 pi_max_pdiv cardG_gt1 mmax_neq1.\n      have sylMqG: q.-Sylow(G) 'O_q(M).\n        by rewrite (mmax_sigma_Sylow maxM) ?defNMq.\n      rewrite (hall_maximal sylMqG (subsetT _) qQ) // defNMq; split=> //.\n      have: 'r_p(G) > 2.\n        by rewrite (leq_trans Age3) // (rank_pgroup pA) p_rankS ?subsetT.\n      apply: contraL; move/eqP <-; rewrite (p_rank_Sylow sylMqG).\n      rewrite -leqNgt -(rank_pgroup (pcore_pgroup _ _)) /=.\n      by rewrite -p_core_Fitting (leq_trans _ Fle2) // rankS ?pcore_sub.\n    have trCRq': [transitive 'O_p^'('C(R)), on |/|*(R; q) | 'JG].\n      have cstrA: normed_constrained A.\n        by apply: SCN_normed_constrained sylP _; rewrite inE SCN_A ltnW.\n      have pR: p.-group R := pgroupS sRP pP.\n      have snAR: A <|<| R by rewrite (nilpotent_subnormal (pgroup_nil pR)).\n      have A'q: q \\notin \\pi(#|A|) by rewrite def_piA.\n      rewrite -(eq_pgroup _ def_piA) in pR.\n      have [|? []] := normed_trans_superset cstrA A'q snAR pR.\n        by rewrite (eq_pcore _ (eq_negn def_piA)) Thompson_transitivity.\n      by rewrite (eq_pcore _ (eq_negn def_piA)).\n    apply/subsetP=> x nRx; have maxQx: (Q :^ x)%G \\in |/|*(R; q).\n      by rewrite (actsP (norm_acts_max_norm _ _)).\n    have [y cRy [defQx]] := atransP2 trCRq' maxQ maxQx.\n    rewrite -(mulgKV y x) groupMr.\n      by rewrite (subsetP sNQ_M) // inE conjsgM defQx conjsgK.\n    apply: subsetP cRy; apply: (subset_trans (pcore_sub _ _)).\n    exact: subset_trans (centS _) sCAM.\n  have sNA_M: 'N(A) \\subset M.\n    by rewrite sNR_M // subsetI sAP (subset_trans cAA).\n  by rewrite sNR_M // subsetI subxx (subset_trans nAP).\npose P0 := [~: P, 'N(P)].\nhave ntP0: P0 != 1.\n  apply/eqP; move/commG1P; rewrite centsC -(setIidPr (subsetT 'N(P))) /=.\n  move/(Burnside_normal_complement sylP); case/sdprodP=> _ /= defG nGp'P _.\n  have prGp': 'O_p^'(G) \\proper G.\n    rewrite properT; apply: contra ntA; move/eqP=> defG'.\n    rewrite -(setIidPl (subsetT A)) /= -defG'.\n    by rewrite coprime_TIg // (pnat_coprime pA (pcore_pgroup _ _)).\n  have ntGp': 'O_p^'(G) != 1.\n    apply: contraL (mFT_pgroup_proper pP).\n    by rewrite -{2}defG; move/eqP->; rewrite mul1g proper_irrefl.\n  by have:= mFT_norm_proper ntGp' prGp'; rewrite properE bgFunc_norm andbF.\nhave sP0P: P0 \\subset P by rewrite commg_subl.\nhave pP0: p.-group P0 := pgroupS sP0P pP.\nhave uNP0_mCA: forall M, M \\in 'M('C(A)) -> 'M('N(P0)) = [set M].\n  move=> M mCA_M; have [maxM sCAM] := setIdP mCA_M.\n  have sAM := subset_trans cAA sCAM.\n  pose F := 'F(M); pose D := 'O_p^'(F).\n  have cDP0: P0 \\subset 'C(D).\n    have sA1A := Ohm_sub 1 A.\n    have nDA1: 'Ohm_1(A) \\subset 'N(D).\n      apply: subset_trans sA1A (subset_trans sAM (char_norm _)).\n      exact: char_trans (pcore_char _ _) (Fitting_char _).\n    have abelA1: p.-abelem 'Ohm_1(A) by rewrite Ohm1_abelem.\n    have dimA1ge3: logn p #|'Ohm_1(A)| >= 3.\n      by rewrite -(rank_abelem abelA1) rank_Ohm1.\n    have coDA1: coprime #|D| #|'Ohm_1(A)|.\n      rewrite coprime_sym (coprimeSg sA1A) //.\n      exact: pnat_coprime pA (pcore_pgroup _ _).\n    rewrite centsC -[D]/(gval _).\n    rewrite (coprime_abelian_gen_cent (abelianS sA1A cAA) nDA1) //=.\n    rewrite bigprodGE gen_subG /= -/D; apply/bigcupsP=> B.\n    case/and3P=> cycqB sBA1 nBA1; have abelB := abelemS sBA1 abelA1.\n    have sBA := subset_trans sBA1 sA1A.\n    have{cycqB} ncycB: ~~ cyclic B.\n      move: cycqB; rewrite (abelem_cyclic (quotient_abelem _ abelA1)).\n      rewrite card_quotient // -divgS // logn_div ?cardSg // leq_sub_add addn1.\n      move/(leq_trans dimA1ge3); rewrite ltnS ltnNge.\n      by rewrite -(abelem_cyclic abelB).\n    have [x Bx sCxM']: exists2 x, x \\in B^# & ~~ ('C[x] \\subset M).\n      suff: ~~ (\\bigcup_(x \\in B^#) 'C[x] \\subset M).\n        case/subsetPn=> y; case/bigcupP=> x Bx cxy My'.\n        by exists x; last by apply/subsetPn; exists y.\n      have EpB: B \\in 'E_p(M) by rewrite inE (subset_trans sBA sAM).\n      apply: contra uA' => sCB_M.\n      apply: uniq_mmaxS sBA (mFT_pgroup_proper pA) _.\n      exact: noncyclic_cent1_sub_Uniqueness maxM EpB ncycB sCB_M.\n    case/setD1P: Bx; rewrite -cycle_eq1 => ntx Bx.\n    have{ntx} [L] := mmax_exists (mFT_cent_proper ntx).\n    case/setIdP=> maxL; rewrite /= cent_cycle => sCxL.\n    have{sCxM'} [neLM] : L != M by case: eqP sCxL sCxM' => // -> ->.\n    have sNP_LM: 'N(P) \\subset L :&: M.\n      rewrite subsetI !sNP_mCA // inE maxL (subset_trans _ sCxL) // -cent_set1.\n      by rewrite centS // sub1set (subsetP sBA).\n    have sP0_LM': P0 \\subset (L :&: M)^`(1).\n      exact: subset_trans (commSg _ (normG _)) (dergS 1 sNP_LM).\n    have DLle2: 'r(D :&: L) <= 2.\n      apply: contraR neLM; rewrite -ltnNge -in_set1; case/rank_geP=> E.\n      case/nElemP=> q /=; do 2!case/setIdP; rewrite subsetI /= -/D.\n      case/andP=> sED sEL abelE; rewrite -p_rank_abelem //; move/eqP => dimE3.\n      have sEF: E \\subset F := subset_trans sED (pcore_sub _ _).\n      have Fge3: 'r_q(F) >= 3 by rewrite -dimE3 p_rankS.\n      have qE := abelem_pgroup abelE.\n      have uE: E \\in 'U.\n        apply: any_rank3_Fitting_Uniqueness Fge3 _ _ => //.\n        by rewrite (rank_pgroup qE) dimE3.\n      rewrite -(def_uniq_mmax uE maxM (subset_trans sEF (Fitting_sub _))).\n      by rewrite inE maxL.\n    have cDL_P0: P0 \\subset 'C(D :&: L).\n      have nsDM: D <| M:= char_normal_trans (pcore_char _ _) (Fitting_normal M).\n      have{nsDM} [sDM nDM] := andP nsDM.\n      have sDL:  D :&: L \\subset L :&: M by rewrite setIC setIS.\n      have nsDL: D :&: L <| L :&: M by rewrite /normal sDL setIC normsIG.\n      have [s ch_s last_s_DL] := chief_series_exists nsDL.\n      have solLM := solvableS (subsetIl L M) (mmax_sol maxL).\n      have solDL := solvableS sDL solLM.\n      apply: (stable_series_cent (congr_group last_s_DL)) => //; first 1 last.\n        rewrite coprime_sym (coprimegS (subsetIl _ _)) //.\n        exact: pnat_coprime (pcore_pgroup _ _).\n      have{last_s_DL}: last 1%G s \\subset D :&: L by rewrite last_s_DL.\n      rewrite /= -/P0; elim/last_ind: s ch_s => //= s U IHs.\n      rewrite !path_rcons last_rcons /=; set V := last _ s.\n      case/andP=> ch_s chUV sUDL; have [maxU _ nU_LM] := and3P chUV.\n      case/andP: {maxU}(maxgroupp maxU); case/andP=> sVU _ nV_LM.\n      have nVU := subset_trans sUDL (subset_trans sDL nV_LM).\n      rewrite IHs ?(subset_trans sVU) // /stable_factor /normal sVU nVU !andbT.\n      have nVP0 := subset_trans (subset_trans sP0_LM' (der_sub _ _)) nV_LM.\n      rewrite commGC -sub_astabQR // (subset_trans sP0_LM') //. \n      have: is_abelem (U / V) := sol_chief_abelem solLM chUV.\n      case/is_abelemP=> q _; case/andP=> qUV _.\n      apply: rank2_cent_chief qUV sUDL; rewrite ?mFT_odd //.\n      exact: leq_trans (p_rank_le_rank _ _) DLle2.\n    rewrite centsC (subset_trans cDL_P0) ?centS ?setIS //.\n    by rewrite (subset_trans _ sCxL) // -cent_set1 centS ?sub1set.\n  case: (ltnP 2 'r(F)) => [| Fle2]. \n    have [q q_pr -> /= Fq3] := rank_witness [group of F].\n    have Mq3: 'r('O_q(M)) >= 3.\n      rewrite (rank_pgroup (pcore_pgroup _ _)) /= -p_core_Fitting.\n      by rewrite -(p_rank_Sylow (nilpotent_pcore_Hall _ (Fitting_nil _))).\n    have uMq: 'O_q(M)%G \\in 'U.\n      exact: any_rank3_Fitting_Uniqueness Fq3 (pcore_pgroup _ _) Mq3.\n    apply: def_uniq_mmaxS (def_uniq_mmax uMq maxM (pcore_sub q _)); last first.\n      exact: mFT_norm_proper ntP0 (mFT_pgroup_proper pP0).\n    rewrite cents_norm // centsC (subset_trans cDP0) ?centS //=.\n    rewrite -p_core_Fitting sub_pcore // => q1; move/eqnP=> ->{q1}.\n    by apply/eqnP=> def_q; rewrite ltnNge def_q FmCAp_le2 in Fq3.\n  rewrite (mmax_normal maxM) ?mmax_sup_id //.\n  have sNP_M := sNP_mCA M mCA_M; have sPM := subset_trans (normG P) sNP_M.\n  rewrite /normal comm_subG //= -/P0.\n  have nFP: P \\subset 'N(F) by rewrite (subset_trans _ (bgFunc_norm _ _)).\n  have <-: F <*> P * 'N_M(P) = M.\n    apply: Frattini_arg (pHall_subl (mulgen_subr _ _) (subsetT _) sylP).\n    rewrite -(quotientGK (Fitting_normal M)) /= norm_mulgenEr //= -/F.\n    rewrite -quotientK // cosetpre_normal -sub_abelian_normal ?quotientS //.\n    by rewrite sub_der1_abelian ?rank2_der1_sub_Fitting ?mFT_odd ?mmax_sol.\n  case/dprodP: (nilpotent_pcoreC p (Fitting_nil M)) => _ /= defF cDFp _.\n  rewrite norm_mulgenEr //= -{}defF (centC cDFp) -/D p_core_Fitting /= -/F.\n  rewrite -!mulgA mul_subG //; first by rewrite cents_norm // centsC.\n  rewrite mulgA [_ * P]mulSGid ?pcore_sub_Hall 1?(pHall_subl _ (subsetT _)) //.\n  by rewrite mulSGid ?subsetI ?sPM ?normG // subIset // orbC normsRr.\nhave [M mCA_M] := mmax_exists (mFT_cent_proper ntA).\nhave [maxM sCAM] := setIdP mCA_M; have sAM := subset_trans cAA sCAM.\nhave abelA1: p.-abelem 'Ohm_1(A) by rewrite Ohm1_abelem.\nhave sA1A := Ohm_sub 1 A.\nhave EpA1: 'Ohm_1(A)%G \\in 'E_p(M) by rewrite inE (subset_trans sA1A).\nhave ncycA1: ~~ cyclic 'Ohm_1(A).\n  rewrite (abelem_cyclic abelA1) -(rank_abelem abelA1) rank_Ohm1.\n  by rewrite -(subnKC Age3).\nhave [x A1x sCxM']: exists2 x, x \\in 'Ohm_1(A)^# & ~~ ('C[x] \\subset M).\n  suff: ~~ (\\bigcup_(x \\in 'Ohm_1(A)^#) 'C[x] \\subset M).\n    case/subsetPn=> y; case/bigcupP=> x A1 cxy My'.\n    by exists x; last by apply/subsetPn; exists y.\n  apply: contra uA' => sCA1_M.\n  apply: uniq_mmaxS sA1A (mFT_pgroup_proper pA) _.\n  exact: noncyclic_cent1_sub_Uniqueness maxM EpA1 ncycA1 sCA1_M.\ncase/setD1P: A1x; rewrite -cycle_eq1 => ntx A1x.\nhave: 'C[x] \\proper G by rewrite -cent_cycle mFT_cent_proper.\ncase/mmax_exists=> L; case/setIdP=> maxL sCxL.\nhave mCA_L: L \\in 'M('C(A)).\n  rewrite inE maxL (subset_trans _ sCxL) //= -cent_set1 centS // sub1set.\n  by rewrite (subsetP sA1A).\ncase/negP: sCxM'; move/uNP0_mCA: mCA_L; rewrite (uNP0_mCA M) //.\nby move/set1_inj->.\nQed.\n\n(* This is B & G, Theorem 9.6, first assertion; note that B & G omit the      *)\n(* (required!) condition K \\proper G.                                         *)\nTheorem rank3_Uniqueness : forall K, K \\proper G -> 'r(K) >= 3 -> K \\in 'U.\nProof.\nmove=> K prK; case/rank_geP=> B; case/nElemP=> p.\ncase/pnElemP=> sBK abelB dimB3; have [pB cBB _] := and3P abelB.\nsuffices: B \\in 'U by exact: uniq_mmaxS.\nhave [P sylP sBP] := Sylow_superset (subsetT _) pB.\nhave pP := pHall_pgroup sylP.\nhave [|A SCN3_A] :=  p_rank_3_SCN pP (mFT_odd _).\n  by rewrite -dimB3 -(rank_abelem abelB) rankS.\nhave [SCN_A Age3] := setIdP SCN3_A.\nhave: A \\in 'SCN_3[p] by apply/bigcupP; exists P; rewrite // inE.\nmove/SCN_3_Uniqueness=> uA; have cAA := SCN_abelian SCN_A.\ncase/setIdP: SCN_A; case/andP=> sAP _ _; have pA := pgroupS sAP pP.\napply: any_cent_rank3_Uniquness uA pB _ _ => //.\n  by rewrite (abelem_cyclic abelB) dimB3.\nby rewrite -dimB3 -p_rank_abelem ?p_rankS.\nQed.\n\n(* This is B & G, Theorem 9.6, second assertion *)\nTheorem cent_rank3_Uniqueness : forall K,\n  'r(K) >= 2 -> 'r('C(K)) >= 3 -> K \\in 'U.\nProof.\nmove=> K Kge2 CKge3; have cCK_K: K \\subset 'C('C(K)) by rewrite centsC.\napply: cent_uniq_Uniqueness cCK_K _ => //.\napply: rank3_Uniqueness (mFT_cent_proper _) CKge3.\nby rewrite -rank_gt0 ltnW.\nQed.\n\n(* This is B & G, Theorem 9.6, final observation *)\nTheorem nonmaxElem2_Uniqueness : forall p A,\n  A \\in 'E_p^2(G) :\\: 'E*_p(G) -> A \\in 'U.\nProof.\nmove=> p A; case/setDP=> EpA nmaxA; have [_ abelA dimA2]:= pnElemP EpA.\ncase/setIdP: EpA => EpA _; have [pA _] := andP abelA.\napply: cent_rank3_Uniqueness; first by rewrite -dimA2 -(rank_abelem abelA).\nhave [E maxE sAE] := pmaxElem_exists EpA.\nhave [] := pmaxElemP maxE; case/pElemP=> _ abelE _.\nhave [pE cEE _] := and3P abelE.\nhave: 'r(E) <= 'r('C(A)) by rewrite rankS // (subset_trans cEE) ?centS.\napply: leq_trans; rewrite (rank_abelem abelE) -dimA2 properG_ltn_log //.\nby rewrite properEneq; case: eqP maxE nmaxA => //; move/group_inj=> -> ->.\nQed.\n\nEnd Nine.\n\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/ssreflect12_trunk/theories/BGsection9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2662350466210917}}
{"text": "\nDefinition fresh_levels global_levels levels :=\n    LevelSet.For_all (fun l => ~ LevelSet.In l global_levels) levels.\n\n  Definition declared_constraints_levels levels cstrs :=\n    ConstraintSet.For_all (declared_cstr_levels levels) cstrs.\n\n  Definition declared_constraints_levels_union levels cstrs cstrs' :\n    declared_constraints_levels levels cstrs ->\n    declared_constraints_levels levels cstrs' ->\n    declared_constraints_levels levels (ConstraintSet.union cstrs cstrs').\n  Proof.\n    intros decl decl'.\n    rewrite /declared_constraints_levels.\n    intros x inx.\n    eapply ConstraintSetProp.FM.union_1 in inx as [].\n    now eapply decl. now eapply decl'.\n  Qed.\n\n  Definition declared_constraints_levels_union_left levels levels' cstrs :\n    declared_constraints_levels levels cstrs ->\n    declared_constraints_levels (LevelSet.union levels levels') cstrs.\n  Proof.\n    rewrite /declared_constraints_levels.\n    intros hx x inx.\n    specialize (hx x inx).\n    destruct x as [[l d] r]. split.\n    destruct hx. now eapply LevelSetFact.union_2.\n    destruct hx.\n    now eapply LevelSetFact.union_2.\n  Qed.\n\n  Definition declared_constraints_levels_union_right levels levels' cstrs :\n    declared_constraints_levels levels' cstrs ->\n    declared_constraints_levels (LevelSet.union levels levels') cstrs.\n  Proof.\n    rewrite /declared_constraints_levels.\n    intros hx x inx.\n    specialize (hx x inx).\n    destruct x as [[l d] r].\n    destruct hx; split. now eapply LevelSetFact.union_3.\n    now eapply LevelSetFact.union_3.\n  Qed.\n\n  Definition declared_constraints_levels_subset levels levels' cstrs :\n    declared_constraints_levels levels cstrs ->\n    LevelSet.Subset levels levels' ->\n    declared_constraints_levels levels' cstrs.\n  Proof.\n    rewrite /declared_constraints_levels.\n    intros hx sub x inx.\n    specialize (hx x inx). red in hx.\n    destruct x as [[l d] r]; cbn in *.\n    split.\n    red in inx.\n    now eapply sub.\n    now eapply sub.\n  Qed.\n\n  Lemma on_udecl_spec `{checker_flags} Σ (udecl : universes_decl) :\n    on_udecl Σ udecl =\n    let levels := levels_of_udecl udecl in\n    let global_levels := global_levels Σ in\n    let all_levels := LevelSet.union levels global_levels in\n    fresh_levels global_levels levels\n    /\\ declared_constraints_levels all_levels (constraints_of_udecl udecl)\n    /\\ satisfiable_udecl Σ udecl.\n  Proof. unfold on_udecl. reflexivity. Qed.\n\n  Lemma on_udecl_prop_spec `{checker_flags} Σ (udecl : universes_decl) :\n    on_udecl_prop Σ udecl =\n      let levels := levels_of_udecl udecl in\n      let global_levels := global_levels Σ in\n      let all_levels := LevelSet.union levels global_levels in\n      declared_constraints_levels all_levels (constraints_of_udecl udecl).\n  Proof. reflexivity. Qed.\n\n  Notation levels_of_list := LevelSetProp.of_list.\n\n  Lemma levels_of_list_app l l' :\n    levels_of_list (l ++ l') =\n    LevelSet.union (levels_of_list l)\n      (levels_of_list l').\n  Proof.\n    rewrite /LevelSetProp.of_list fold_right_app.\n    induction l; cbn.\n    apply LevelSet.eq_leibniz. red.\n    rewrite LevelSet_union_empty //.\n    apply LevelSet.eq_leibniz. red.\n    rewrite IHl. rewrite LevelSetProp.union_add //.\n  Qed.\n\n  Definition aulevels inst cstrs :\n    AUContext.levels (inst, cstrs) =\n    LevelSetProp.of_list (unfold #|inst| Level.Var).\n  Proof.\n    cbn.\n    now rewrite mapi_unfold.\n  Qed.\n\n  #[global] Instance unfold_proper {A} : Proper (eq ==> `=1` ==> eq) (@unfold A).\n  Proof.\n    intros x y -> f g eqfg.\n    induction y; cbn; auto. f_equal; auto. f_equal. apply eqfg.\n  Qed.\n\n  (* sLemma unfold_add {A} n k (f : nat -> A) : skipn k (unfold (k + n) f) = unfold k (fun x => f (x + n)). *)\n\n  Lemma unfold_add {A} n k (f : nat -> A) : unfold (n + k) f = unfold k f ++ unfold n (fun x => f (x + k)).\n  Proof.\n    induction n in k |- *.\n    cbn. now rewrite app_nil_r.\n    cbn. rewrite IHn. now rewrite app_assoc.\n  Qed.\n\n\n  Definition unfold_levels_app n k :\n    LevelSetProp.of_list (unfold (n + k) Level.Var) =\n    LevelSet.union (LevelSetProp.of_list (unfold k Level.Var))\n      (LevelSetProp.of_list (unfold n (fun i => Level.Var (k + i)))).\n  Proof.\n    rewrite unfold_add levels_of_list_app //.\n    now setoid_rewrite Nat.add_comm at 1.\n  Qed.\n\n  Lemma levels_of_list_spec l ls :\n    LevelSet.In l (levels_of_list ls) <-> In l ls.\n  Proof.\n    now rewrite LevelSetProp.of_list_1 InA_In_eq.\n  Qed.\n\n  Lemma In_unfold k l n :\n    In l (unfold n (λ i : nat, Level.Var (k + i))) <-> ∃ k' : nat, l = Level.Var k' ∧ k <= k' < k + n.\n  Proof.\n    induction n; cbn => //. firstorder. lia.\n    split. intros [] % in_app_or => //.\n    eapply IHn in H as [k' [eq lt]]. subst l; exists k'. intuition lia.\n    destruct H as []; subst => //.\n    exists (k + n). intuition lia.\n    intros [k' [-> lt]].\n    apply/in_or_app.\n    destruct (eq_dec k' (k + n)). subst k'.\n    right => //. cbn; auto.\n    left. eapply IHn. exists k'; intuition lia.\n  Qed.\n\n  Lemma In_levels_of_list k l n :\n    LevelSet.In l (levels_of_list (unfold n (fun i => Level.Var (k + i)))) <->\n    exists k', l = Level.Var k' /\\ k <= k' < k + n.\n  Proof.\n    rewrite LevelSetProp.of_list_1 InA_In_eq. now apply In_unfold.\n  Qed.\n\n  Lemma In_lift_level k l n : LevelSet.In l (levels_of_list (unfold n (λ i : nat, Level.Var i))) <->\n    LevelSet.In (lift_level k l) (levels_of_list (unfold n (λ i : nat, Level.Var (k + i)))).\n  Proof.\n    split.\n    - move/(In_levels_of_list 0) => [k' [-> l'lt]].\n      eapply In_levels_of_list. exists (k + k'); cbn; intuition lia.\n    - move/(In_levels_of_list k) => [k' [eq l'lt]].\n      eapply (In_levels_of_list 0).\n      destruct l; noconf eq. exists n0; cbn; intuition lia.\n  Qed.\n\n  Lemma not_var_lift l k s :\n    LS.For_all (λ x : LS.elt, ~~ Level.is_var x) s ->\n    LevelSet.In l s ->\n    LevelSet.In (lift_level k l) s.\n  Proof.\n    intros.\n    specialize (H _ H0). cbn in H.\n    destruct l; cbn => //.\n  Qed.\n\n  Lemma declared_constraints_levels_lift s n k cstrs :\n    LS.For_all (λ x : LS.elt, (negb ∘ Level.is_var) x) s ->\n    declared_constraints_levels\n      (LevelSet.union (levels_of_list (unfold n (λ i : nat, Level.Var i))) s) cstrs ->\n    declared_constraints_levels\n      (LevelSet.union (levels_of_list (unfold n (λ i : nat, Level.Var (k + i)))) s)\n      (lift_constraints k cstrs).\n  Proof.\n    rewrite /declared_constraints_levels.\n    intros hs ha [[l d] r] inx.\n    eapply In_lift_constraints in inx as [c' [eq incs]].\n    specialize (ha _ incs). destruct c' as [[l' d'] r']; cbn in eq; noconf eq.\n    destruct ha as [inl' inr'].\n    apply LevelSetFact.union_1 in inl'. apply LevelSetFact.union_1 in inr'.\n    split.\n    - apply LevelSet.union_spec.\n      destruct inl'.\n      + left. now apply In_lift_level.\n      + right. apply not_var_lift => //.\n    - apply LevelSet.union_spec.\n      destruct inr'.\n      + left. now apply In_lift_level.\n      + right. apply not_var_lift => //.\n  Qed.\n\n  Definition levels_of_cstr (c : ConstraintSet.elt) :=\n    let '(l, d, r) := c in\n    LevelSet.add l (LevelSet.add r LevelSet.empty).\n\n  Definition levels_of_cstrs cstrs :=\n    ConstraintSet.fold (fun c acc => LevelSet.union (levels_of_cstr c) acc) cstrs.\n\n  Lemma levels_of_cstrs_acc l cstrs acc :\n    LevelSet.In l acc \\/ LevelSet.In l (levels_of_cstrs cstrs LevelSet.empty) <->\n    LevelSet.In l (levels_of_cstrs cstrs acc).\n  Proof.\n    rewrite /levels_of_cstrs.\n    rewrite !ConstraintSet.fold_spec.\n    induction (ConstraintSet.elements cstrs) in acc |- * => /=.\n    split. intros []; auto. inversion H. firstorder.\n    split.\n    intros []. apply IHl0. left. now eapply LevelSetFact.union_3.\n    apply IHl0 in H as []. apply IHl0. left.\n    eapply LevelSet.union_spec. left.\n    eapply LevelSet.union_spec in H. destruct H => //. inversion H.\n    apply IHl0. right => //.\n    intros. apply IHl0 in H as [].\n    eapply LevelSet.union_spec in H. destruct H => //.\n    right. apply IHl0. left. apply LevelSet.union_spec. now left.\n    now left. right.\n    eapply IHl0. now right.\n  Qed.\n\n  Lemma levels_of_cstrs_spec l cstrs :\n    LevelSet.In l (levels_of_cstrs cstrs LevelSet.empty) <->\n    exists d r, ConstraintSet.In (l, d, r) cstrs \\/ ConstraintSet.In (r, d, l) cstrs.\n  Proof.\n    rewrite -levels_of_cstrs_acc.\n    split.\n    - intros []. inversion H.\n      move: H.\n      rewrite /levels_of_cstrs.\n      eapply ConstraintSetProp.fold_rec.\n      + intros s' em inl. inversion inl.\n      + intros x a s' s'' inx ninx na.\n        intros.\n        destruct x as [[l' d] r].\n        eapply LevelSet.union_spec in H0 as [].\n        eapply LevelSet.add_spec in H0 as []; subst.\n        exists d, r. left. now apply na.\n        eapply LevelSet.add_spec in H0 as []; subst.\n        exists d, l'. right; now apply na. inversion H0.\n        specialize (H H0) as [d' [r' h]].\n        exists d', r'. red in na.\n        destruct h. destruct (na (l, d', r')).\n        firstorder. firstorder.\n\n    - intros [d [r [indr|indr]]].\n      rewrite /levels_of_cstrs. right.\n      move: indr; eapply ConstraintSetProp.fold_rec.\n      intros. now specialize (H _ indr).\n      intros x a s' s'' inx inx' add inih ihih'.\n      eapply LevelSet.union_spec.\n      eapply add in ihih' as []; subst. left.\n      eapply LevelSet.add_spec. now left. firstorder.\n      right.\n      rewrite /levels_of_cstrs.\n      move: indr; eapply ConstraintSetProp.fold_rec.\n      intros. now specialize (H _ indr).\n      intros x a s' s'' inx inx' add inih ihih'.\n      eapply LevelSet.union_spec.\n      eapply add in ihih' as []; subst. left.\n      eapply LevelSet.add_spec. right. eapply LevelSet.add_spec; now left. firstorder.\n  Qed.\n\n  Lemma declared_constraints_levels_in levels cstrs :\n    LevelSet.Subset (levels_of_cstrs cstrs LevelSet.empty) levels ->\n    declared_constraints_levels levels cstrs.\n  Proof.\n    rewrite /declared_constraints_levels.\n    intros sub [[l d] r] inx. red in sub.\n    split. apply (sub l). eapply levels_of_cstrs_spec. do 2 eexists; firstorder eauto.\n    apply (sub r). eapply levels_of_cstrs_spec. do 2 eexists; firstorder eauto.\n  Qed.\n\n  Lemma In_variance_cstrs l d r v i i' :\n    ConstraintSet.In (l, d, r) (variance_cstrs v i i') ->\n      (In l i \\/ In l i') /\\ (In r i \\/ In r i').\n  Proof.\n    induction v in i, i' |- *; destruct i, i'; intros; try solve [inversion H].\n    cbn in H.\n    destruct a. apply IHv in H. cbn. firstorder auto.\n    eapply ConstraintSet.add_spec in H as []. noconf H. cbn; firstorder.\n    eapply IHv in H; firstorder.\n    eapply ConstraintSet.add_spec in H as []. noconf H. cbn; firstorder.\n    eapply IHv in H; firstorder.\n  Qed.\n\n  Lemma In_lift l n k : In l (map (lift_level k) (unfold n Level.Var)) <->\n    In l (unfold n (fun i => Level.Var (k + i))).\n  Proof.\n    induction n; cbn; auto. firstorder.\n    firstorder.\n    move: H1; rewrite map_app.\n    intros [] % in_app_or.\n    apply/in_or_app. firstorder.\n    apply/in_or_app. firstorder.\n    move: H1; intros [] % in_app_or.\n    rewrite map_app. apply/in_or_app. firstorder.\n    rewrite map_app. apply/in_or_app. firstorder.\n  Qed.\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/PCUICUnivLevels.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804478040617, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2661667689796777}}
{"text": "\nRequire Export VST.msl.msl_standard.\nRequire Import VST.veric.base.\nRequire Import VST.veric.shares.\nRequire Import VST.veric.rmaps.\nRequire Import VST.veric.rmaps_lemmas.\n\nInductive kind : Type := VAL : memval -> kind\n                                   | LK : Z -> kind\n                                   | CT: Z -> kind\n                                   | FUN: funsig -> calling_convention -> kind.\n\nDefinition isVAL (k: kind) := match k with | VAL _ => True | _ => False end.\nDefinition isFUN (k: kind) := match k with | FUN _ _ => True | _ => False end.\n\nLemma isVAL_i: forall v, isVAL (VAL v).\nProof. intros; simpl; auto. Qed.\nHint Resolve isVAL_i.\n\nLemma isVAL_dec: forall k, {isVAL k}+{~isVAL k}.\nProof.\nintros; destruct k; auto.\nQed.\n\nModule CompCert_AV <: ADR_VAL.\n\nDefinition address := address.\nDefinition some_address : address := (xH,0).\nDefinition kind := kind.\n\nDefinition valid (f: address -> option (rshare*kind)) := \n  forall b ofs, \n     match f (b,ofs) with\n     | Some (sh, LK n) => forall i, 0 < i < n -> f(b,ofs+i) = Some (sh, CT i)\n     | Some (sh, CT i) => exists n, 0 < i < n /\\ f(b,ofs-i) = Some (sh,LK n)\n     | _ => True\n    end.\n\nLemma valid_empty: valid (fun _ => None).\nProof.\nunfold valid; intros.\nauto.\nQed.\n\nLemma valid_join: forall f g h : address -> option (rshare * kind),\n   @join _ (Join_fun address (option (rshare * kind))\n                   (Join_lower (Join_prod rshare Join_rshare kind (Join_equiv kind))))\n      f g h  ->\n valid f -> valid g -> valid h.\nProof.\n unfold valid; intros f g h J H H0 b ofs.\ncase_eq (h(b,ofs)); auto; intros [sh k] ?.\ndestruct k; auto; intros.\n(**  LK -> CT **)\n generalize (H b ofs); intro H'; generalize (H0 b ofs); intro H0'.\n generalize (J (b,ofs)); rewrite H1; intro H8.\n inv H8. clear H'.  rewrite H6 in H0'. specialize (H0' _ H2).\n specialize (J (b,ofs+i)); rewrite H0' in J.\n inv J; auto.\n specialize (H b (ofs+i)). rewrite <- H3 in H. destruct a1. inv H8. simpl in *.\n inv H9. destruct H as [n [? ?]]. replace (ofs+i-i) with ofs in H8 by omega.\n rewrite <- H4 in H8; inv H8.\n clear H0'. rewrite H6 in H'. specialize (H' _ H2).\n specialize (J (b,ofs+i)); rewrite H' in J.\n inv J; auto.\n specialize (H0 b (ofs+i)). rewrite <- H4 in H0. destruct a2. inv H8. simpl in *.\n inv H9. destruct H0 as [n [? ?]]. replace (ofs+i-i) with ofs in H8 by omega.\n rewrite <- H5 in H8; inv H8.\n rewrite <- H3 in H'. rewrite <- H4 in H0'. destruct a1; destruct a2.\n destruct H6. simpl in *. destruct H6; subst k k0.\n specialize (H b (ofs+i)); specialize (H0 b (ofs+i)).\n rewrite (H0' _ H2) in H0.  rewrite (H' _ H2) in H.\n destruct H as [n [? ?]]; destruct H0 as [n' [? ?]].\n replace (ofs+i-i) with ofs in H6,H7 by omega.\n rewrite <- H4 in H7; inv H7. rewrite <- H3 in H6; inv H6.\n specialize (J (b,ofs+i)). rewrite (H' _ H2) in J. rewrite (H0' _ H2) in J.\n inv J; auto. inv H9; auto. simpl in *. destruct a3; simpl in *. inv H7.\n f_equal. f_equal. eapply join_eq; eauto.\n(** CT -> LK **)\n generalize (H b ofs); intros H'; generalize (H0 b ofs); intro H0'.\n generalize (J (b,ofs)); intro H8; inv H8.\n rewrite H1 in H5. rewrite H5 in H0'. destruct H0' as [n [? ?]]; exists n; split; auto.\n specialize (J (b,ofs-z)); rewrite H4 in J.\n inv J; auto. destruct a1; destruct a3. destruct H9. simpl in *. inv H9.\n specialize (H b (ofs-z)). rewrite <- H6 in H.\n specialize (H _ H2).\n replace (ofs-z+z) with ofs in H by omega. congruence.\n rewrite H1 in H5. rewrite H5 in H'. destruct H' as [n [? ?]]; exists n; split; auto.\n specialize (J (b,ofs-z)); rewrite H3 in J.\n inv J; auto. destruct a2; destruct a3. destruct H9. simpl in *. inv H9.\n specialize (H0 b (ofs-z)). rewrite <- H7 in H0.\n specialize (H0 _ H2).\n replace (ofs-z+z) with ofs in H0 by omega. congruence.\n destruct a1; destruct a2; destruct a3.\n rewrite <- H3 in H0'; rewrite <- H2 in H'. destruct H5. destruct H6. simpl in *; subst.\n rewrite H1 in H4. inv H4.\n destruct H' as [n [? ?]]. exists n; split; auto.\n specialize (J (b,ofs-z)). rewrite H6 in J.\n assert (g (b,ofs-z) = Some (r0, LK n)).\n destruct H0' as [n' [? ?]]. rewrite H8 in J. inv J. destruct H12. inv H10; simpl in *. inv H12; auto.\n rewrite H7 in J. inv J. inv H11. simpl in *. destruct a3; simpl in *. inv H9.\n repeat f_equal. eapply join_eq; auto.\nQed.\n\nEnd CompCert_AV.\n\nLemma getVAL: forall k, {v : memval & k = VAL v}  + {~isVAL k}.\nProof.\nintros.\ndestruct k;\n  try solve [simpl; right; tauto].\nleft.\neauto.\nQed.\n\nLemma VAL_inj: forall v v', VAL v = VAL v' -> v = v'.\nProof.\nintros.\ninv H; auto.\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   CompCert_AV.valid f.\nProof.\nintros.\nintros b ofs.\ncase_eq (f (b,ofs)); intros; auto.\ndestruct p.\nspecialize (H _ _ _ H0).\ndestruct k; try solve [auto | inversion H].\nQed.\n\nLemma VAL_or_FUN_valid:\n forall (f: address -> option (rshare*kind)),\n   (forall l sh k, f l = Some (sh,k) -> isVAL k \\/ isFUN k) ->\n   CompCert_AV.valid f.\nProof.\nintros.\nintros b ofs.\ncase_eq (f (b,ofs)); intros; auto.\ndestruct p.\nspecialize (H _ _ _ H0).\ndestruct k; try solve [auto | simpl in H; tauto].\nQed.\n\nLemma blockwise_valid:\n  forall f,\n    (forall b, exists g, CompCert_AV.valid g /\\ forall ofs, f (b,ofs) = g (b,ofs)) ->\n     CompCert_AV.valid f.\nProof.\nintros.\nintros b ofs.\ndestruct (H b); clear H.\ndestruct H0.\nrewrite H0.\ngeneralize (H b ofs); case_eq (x (b,ofs)); intros; auto.\ndestruct p; auto.\ndestruct k; auto.\nintros.\nrewrite H0; auto.\ndestruct H2 as [n [? ?]]; exists n; split; auto.\nrewrite H0; auto.\nQed.\n\nLemma store_valid:\n  forall (f f' :  address -> option (rshare*kind)),\n   CompCert_AV.valid f ->\n     (forall l, f l = f' l \\/\n                  match f l, f' l with\n                  | Some (_, k) , Some (_, k') =>    isVAL k /\\ isVAL k'\n                  | Some(_, k), None => isVAL k\n                  | None, Some(_, k') => isVAL k'\n                  | None, None => True\n                  end) ->\n   CompCert_AV.valid f'.\nProof.\nintros.\nintros b ofs.\ngeneralize (H b ofs) (H0 (b,ofs)).\ncase_eq (f' (b,ofs)); simpl in *; intros; auto.\ndestruct p.\ndestruct k; simpl; auto.\nintros.\ndestruct H3.\nrewrite H3 in H2.\nspecialize (H2 _ H4).\nspec H0 (b,ofs+i).\ndestruct H0.\ncongruence.\nrewrite H2 in H0.\ndestruct (f' (b,ofs+i)).\ndestruct p.\ndestruct H0.\ndestruct H0; inv H0.\ndestruct H0; inv H0.\ndestruct (f(b,ofs)).\ndestruct p.\ndestruct H3.\ninv H5.\ninv H3.\ndestruct H3.\nrewrite H3 in H2.\ndestruct H2 as [n [? ?]]; exists n; split; auto.\nspecialize (H0 (b,ofs-z)).\ndestruct H0; try congruence.\nrewrite H4 in H0.\ndestruct (f' (b,ofs-z)); auto.\ndestruct p.\ndestruct H0.\ndestruct H0; inv H0.\ndestruct H0; inv H0.\ndestruct (f(b,ofs)).\ndestruct p.\ndestruct H3.\ninv H4.\ninv H3.\nQed.\n\nInstance EqDec_calling_convention: EqDec calling_convention.\nProof.\n  hnf. decide equality.\n  destruct cc_structret, cc_structret0; intuition.\n  destruct cc_unproto, cc_unproto0; intuition.\n  destruct cc_vararg, cc_vararg0; intuition.\nQed.\n\nInstance EqDec_kind: EqDec kind.\nProof.\n  hnf. decide equality; try apply eq_dec; try apply zeq.\nQed.\n\nModule R := Rmaps (CompCert_AV).\nModule RML := Rmaps_Lemmas(R).\n\nExport RML.\nExport R.\n\nLemma rmap_valid_e1: forall r b ofs n i, 0 < i < n ->\n     forall sh, res_option (r @ (b,ofs)) = Some (sh, LK n) -> res_option (r @ (b,ofs+i))= Some (sh, CT i).\nProof.\nintros until sh.\ngeneralize (rmap_valid r b ofs); unfold compose.\ncase_eq (r @ (b,ofs)); simpl; intros; try discriminate.\ninv H2.\nauto.\nQed.\n\nLemma rmap_valid_e2:  forall r b ofs i sh,\n    res_option (r @ (b,ofs+i)) = Some (sh, CT i) ->\n            exists n, 0 < i < n /\\ res_option (r @ (b,ofs)) = Some (sh, LK n).\nProof.\nintros until sh.\ngeneralize (rmap_valid r b (ofs+i)); unfold compose.\ncase_eq (r @ (b,ofs+i)); simpl; intros; try discriminate.\ninv H1.\ndestruct H0 as [n [? ?]].\nreplace (ofs+i-i) with ofs in H1 by omega.\neauto.\nQed.\n\nDefinition mk_rshare: forall p: Share.t, pure_readable_share p -> rshare := exist pure_readable_share.\nDefinition rshare_sh (p: rshare) : Share.t := proj1_sig p.\n(*\nDefinition mk_pshare : forall p: Share.t, nonunit p -> pshare := exist nonunit.\n*)\n\nLemma mk_rshare_sh: forall p (H: pure_readable_share (rshare_sh p)),\n  mk_rshare (rshare_sh p) H = p.\nProof.\n  intros.\n  unfold mk_rshare.\n  destruct p; simpl.\n  auto with extensionality.\nQed.\n\nDefinition fixup_splitting\n  (a:address -> Share.t) (z: address -> option (rshare * kind)) : address -> option (rshare * kind) :=\n  fun l => \n    match z l with\n    | Some (sh, CT i) => \n       match dec_readable (a (fst l, snd l - i)) with\n       | left p => Some (readable_part p,  CT i)\n       | right _ => None\n       end\n    | Some (sh, k) =>\n       match dec_readable (a l) with\n       | left p => Some (readable_part p,  k)\n       | right _ => None\n       end\n    | None => None\n    end.\n\nDefinition share_of (x: option (rshare * kind)) : Share.t :=\n  match x with Some (p,_) => proj1_sig p | None => Share.bot end.\n\nDefinition Join_pk := (Join_lower (Join_prod rshare _ kind (Join_equiv _))).\n\nLemma fixup_splitting_valid : forall (a: address->Share.t) (z:address -> option (rshare * kind)),\n    (forall x, join_sub (a x) (share_of (z x))) ->\n    AV.valid z ->\n    AV.valid (fixup_splitting a z).\nProof.\n  unfold AV.valid, res_option, compose; intros.\n  unfold fixup_splitting.\n  spec H0 b ofs.\n  case_eq (z (b,ofs)); intros;\n    rewrite H1 in H0; auto. destruct p.\n  destruct k.\n* simpl. destruct (dec_readable (a (b,ofs))); auto.\n* destruct (dec_readable (a (b,ofs))); auto.\n  intros.\n  specialize (H0 _ H2). rewrite H0. simpl.\n  replace (ofs+i-i) with ofs by omega.\n  destruct (dec_readable (a (b, ofs))); try contradiction.\n  f_equal. f_equal. f_equal. apply proof_irr. \n*\n  simpl.\n  destruct H0 as [n [? ?]].\n  destruct ( dec_readable (a (b, ofs - z0))); auto.\n  exists n. split; auto.\n  rewrite H2.\n  destruct ( dec_readable (a (b, ofs - z0))); auto with extensionality; contradiction.\n*\n  simpl.\n  destruct (dec_readable (a (b,ofs))); auto.\nQed.\n\nLemma share_of_Some: forall p: rshare * AV.kind, readable_share (share_of (Some p)).\nProof.\n intros. destruct p as [[? ?] ?]; simpl.\n auto.\n destruct p; auto.\nQed.\n\n(*Lemma fixup_trace_ok_share_of:\n  forall a (OKa: fixup_trace_ok a) x, \n       Share.glb Share.Rsh (share_of (a x)) = share_of (a x).\nProof.\n  intros.\n specialize (OKa x). destruct (a x) as [[? ?]|]; simpl in *.\n auto. apply Share.glb_bot.\nQed.*)\n\nLemma join_sub_same_k:\n forall {a a' : rshare} {k k': AV.kind},\n      @join_sub _ Join_pk (Some (a,k)) (Some (a',k')) -> k=k'.\nProof.\n  intros. destruct H. inv H; auto. inv H3. simpl in H0. inv H0; congruence.\nQed.\n\nLemma pure_readable_glb_Rsh:\n forall sh, pure_readable_share sh -> Share.glb Share.Rsh sh = sh.\nProof.\n intros.\n destruct H.\n rewrite (comp_parts comp_Lsh_Rsh sh) at 2. rewrite H.\n rewrite Share.lub_commute, Share.lub_bot; auto.\nQed.\n\nLemma join_glb_Rsh:  \n  forall a b c : Share.t,\n  join a b c ->\n  join (Share.glb Share.Rsh a) (Share.glb Share.Rsh b) (Share.glb Share.Rsh c).\nProof.\nintros.\napply (join_comp_parts comp_Lsh_Rsh). auto.\nQed.\n\nLemma pure_readable_share_glb:\n  forall a, pure_readable_share a -> Share.glb Share.Rsh a = a.\nProof.\n intros. destruct H.\n rewrite (comp_parts comp_Lsh_Rsh a) at 2. rewrite H.\n rewrite Share.lub_commute, Share.lub_bot. auto.\nQed.\n\nLemma glb_Rsh_bot_unreadable:\n  forall a, Share.glb Share.Rsh a = Share.bot -> ~readable_share a.\nProof.\n intros. unfold readable_share. rewrite H. intro. apply H0.\n apply bot_identity.\nQed.\n\nLemma fixup_join : forall a (ac ad: address -> Share.t)  z,\n  AV.valid a ->\n  AV.valid z ->\n  (forall x, @join_sub _ Join_pk (a x) (z x)) ->\n  (forall x, join (ac x) (ad x) (share_of (a x))) ->\n  (forall x,\n    @join _ Join_pk\n    (fixup_splitting ac z x)\n    (fixup_splitting ad z x)\n    (a x)).\nProof.\n  intros.\n  unfold fixup_splitting.\n\nLtac glb_Rsh_tac :=\n repeat\n match goal with\n | |- Some _ = None => elimtype False\n | |- None = Some _ => elimtype False\n | |- join (Some _) _ None => elimtype False\n | |- join _ (Some _) None => elimtype False\n | |- join _ None _ => apply join_unit2; [ apply None_unit |]\n | |- join None _ _ => apply join_unit1; [ apply None_unit |]\n | |- Some (_,_) = Some(_,_) => do 2 f_equal; try apply exist_ext; auto\n | H: ~readable_share ?X, H1: join (Share.glb Share.Rsh ?X) _ _ |- _ =>\n         rewrite (not_readable_Rsh_part H) in H1;\n         apply join_unit1_e in H1; [ | apply bot_identity];\n         rewrite ?H1 in *\n | H: ~readable_share ?X, H1: join _ (Share.glb Share.Rsh ?X) _ |- _ =>\n         rewrite (not_readable_Rsh_part H) in H1;\n         apply join_unit2_e in H1; [ | apply bot_identity];\n         rewrite ?H1 in *\n | H: identity ?A, H1: readable_share ?A |- _ =>\n    apply (readable_not_identity A _ H1 H)\n | H: pure_readable_share ?A |- Share.glb Share.Rsh ?A = ?A =>\n     apply pure_readable_glb_Rsh; auto\n | H: join ?A ?B Share.bot |- _ =>\n     let H1 := fresh in \n         assert (H1 := identity_share_bot _ (split_identity _ _ H bot_identity));\n         rewrite ?H1 in *;\n     let H2 := fresh in \n         assert (H2 := identity_share_bot _ (split_identity _ _ (join_comm H) bot_identity));\n         rewrite ?H2 in *;\n     clear H\n | H: readable_share Share.bot |- _ => contradiction bot_unreadable\n | H: join_sub None _ |- _ => clear H\n | H: join_sub (Some(_,?A)) (Some (_,?B)) |- _ =>\n      unify A B || \n      (is_var A; pose proof (join_sub_same_k H); subst A)\n | |- _ => rewrite Share.glb_bot in *\n | H: Share.glb Share.Rsh _ = Share.bot |- _ => \n          apply glb_Rsh_bot_unreadable in H; try contradiction\n | H: pure_readable_share ?A |- _ => rewrite (pure_readable_share_glb _ H) in *\n | |- _ => assumption\n end;\n auto.\n\n  case_eq (z x); intros; [destruct p;  destruct k| ].\n*\n  specialize (H1 x); specialize (H2 x).\n  clear H H0. rewrite H3 in *. clear z H3.\n  destruct (dec_readable (ac x)).\n +\n  destruct (dec_readable (ad x)).\n -\n  destruct (a x) as [[[? ?] ?] | ]; simpl in *.\n  constructor.\n  pose proof (join_sub_same_k H1); subst k.\n  constructor; auto. simpl.\n  red. red. simpl.\n  apply join_glb_Rsh in H2.\n  glb_Rsh_tac.\n  glb_Rsh_tac.\n  -\n  apply join_glb_Rsh in H2.\n  glb_Rsh_tac.\n  destruct (a x) as [[[? ?] ?]|]; simpl in *.\n  glb_Rsh_tac.\n  glb_Rsh_tac.\n+\n  glb_Rsh_tac.\n  apply join_glb_Rsh in H2.\n  destruct (a x) as [[[? ?] ?]|]; simpl in *.\n  glb_Rsh_tac.\n  destruct (dec_readable (ad x)).\n  glb_Rsh_tac.\n  glb_Rsh_tac.\n  apply n0.\n  unfold readable_share. rewrite H2. destruct p. intro.\n  glb_Rsh_tac.\n  glb_Rsh_tac.\n  destruct (dec_readable (ad x)).\n  glb_Rsh_tac.\n  glb_Rsh_tac.\n*\n  specialize (H1 x); specialize (H2 x).\n  clear H H0. rewrite H3 in *. clear z H3.\n  destruct (dec_readable (ac x)).\n +\n  destruct (dec_readable (ad x)).\n -\n  destruct (a x) as [[[? ?] ?] | ]; simpl in *.\n  apply join_glb_Rsh in H2.  \n  glb_Rsh_tac.\n  constructor. do 2 red. simpl; split; auto.\n  glb_Rsh_tac.\n  -\n  apply join_glb_Rsh in H2.  \n  glb_Rsh_tac.\n  destruct (a x) as [[[? ?] ?]|]; simpl in *.\n  glb_Rsh_tac.\n  glb_Rsh_tac.\n +\n  glb_Rsh_tac.\n  destruct (a x) as [[[? ?] ?]|]; simpl in *.\n -\n  glb_Rsh_tac.\n  apply join_glb_Rsh in H2.\n  glb_Rsh_tac.\n  destruct (dec_readable (ad x)).\n  glb_Rsh_tac.\n  glb_Rsh_tac.\n  destruct p. apply n0.\n  unfold readable_share. rewrite H2. intro.\n  glb_Rsh_tac.\n -\n  glb_Rsh_tac. \n  destruct (dec_readable Share.bot); glb_Rsh_tac.\n*\n destruct x as [b ofs]. simpl.\n assert (H1' := H1 (b,ofs)).\n assert (H' := H b ofs).\n specialize (H2 (b,ofs-z0)).\n specialize (H b (ofs-z0)).\n specialize (H0 b ofs).\n specialize (H1 (b,ofs-z0)).\n simpl in *. rewrite H3 in *.\n destruct H0 as [s [? ?]]. rewrite H4 in *.\n clear z H3 H4.\n apply join_glb_Rsh in H2.\n destruct (dec_readable (ac (b, ofs - z0))).\n +\n destruct (dec_readable (ad (b,ofs-z0))).\n -\n destruct (a (b,ofs-z0)) as [[? ?]|] eqn:?; simpl in *.\n glb_Rsh_tac.\n specialize (H _ H0). clear H0.\n rewrite Z.sub_add in H. rewrite H in *.\n constructor. constructor; simpl; auto.\n do 2 red. simpl.\n destruct r2; simpl in *.\n glb_Rsh_tac.\n rewrite Share.glb_bot in *.\n glb_Rsh_tac.\n -\n glb_Rsh_tac.\n destruct (a (b,ofs-z0)) as [[? ?]|] eqn:?; simpl in *.\n glb_Rsh_tac.\n specialize (H _ H0).\n rewrite Z.sub_add in H. rewrite H in *.\n glb_Rsh_tac.\n destruct r1; apply exist_ext. rewrite H2.\n simpl.\n glb_Rsh_tac.\n elimtype False;\n glb_Rsh_tac.\n +\n glb_Rsh_tac.\n destruct (a (b,ofs-z0))  as [[? ?]|] eqn:?.\n glb_Rsh_tac.\n specialize (H _ H0). clear H0.\n rewrite Z.sub_add in H. rewrite H in *.\n simpl in H2.\n destruct (dec_readable (ad (b, ofs - z0))).\n glb_Rsh_tac.\n destruct r0; simpl in *; apply exist_ext.\n glb_Rsh_tac.\n glb_Rsh_tac.\n contradiction n0.\n unfold readable_share. rewrite H2.\n clear. destruct r0; simpl. destruct p.\n glb_Rsh_tac.\n simpl in H2. glb_Rsh_tac.\n destruct (dec_readable (ad (b, ofs - z0))).\n contradiction.\n destruct(a (b,ofs)) as  [[[? ?] ?]|]; auto.\n glb_Rsh_tac.\n destruct H' as [s' [? ?]]. rewrite Heqo in H3; inv H3.\n*\n  specialize (H1 x); specialize (H2 x).\n  clear H H0. rewrite H3 in *. clear z H3.\n  apply join_glb_Rsh in H2.\n  destruct (dec_readable (ac x)).\n +\n  destruct (dec_readable (ad x)).\n -\n  destruct (a x) as [[[? ?] ?] | ]; simpl in *.\n glb_Rsh_tac.\n constructor. constructor; simpl. glb_Rsh_tac. constructor; auto.\n glb_Rsh_tac.\n  -\n glb_Rsh_tac.\n  destruct (a x) as [[[? ?] ?]|]; simpl in *.\n glb_Rsh_tac.\n glb_Rsh_tac.\n +\n glb_Rsh_tac.\n  destruct (a x) as [[[? ?] ?]|]; simpl in *.\n -\n  glb_Rsh_tac.\n  destruct (dec_readable (ad x)).\n  glb_Rsh_tac.\n  glb_Rsh_tac.\n  apply n0. unfold readable_share. rewrite H2. intro.\n  destruct p. glb_Rsh_tac.\n - \n  glb_Rsh_tac.\n  destruct (dec_readable (ad x)).\n  glb_Rsh_tac.\n  glb_Rsh_tac.\n*\n specialize (H1 x). rewrite H3 in H1.\n destruct H1.\n inv H1. constructor. rewrite H7; constructor.\nQed.\n\nLemma join_share_of: forall a b c,\n     @join _ Join_pk a b c -> join (share_of a) (share_of b) (share_of c).\nProof.\n  intros. inv H; simpl. apply join_unit1; auto. apply join_unit2; auto.\n  destruct a1; destruct a2; destruct a3.\n  destruct r,r0,r1; simpl.\n  destruct H0. simpl in *. do 3 red in H. simpl in H. auto.\nQed.\n\nInstance Cross_rmap_aux: Cross_alg (sig AV.valid).\nProof.\n hnf. intros [a Ha] [b Hb] [c Hc] [d Hd] [z Hz] ? ?.\n hnf in H,H0. simpl in H,H0.\n destruct (cross_split_fun Share.t _ address share_cross_split\n                   (share_of oo a) (share_of oo b) (share_of oo c) (share_of oo d) (share_of oo z))\n  as [[[[ac ad] bc] bd] [? [? [? ?]]]].\n intro x. specialize (H x). unfold compose.\n clear - H. inv H; simpl in *. apply join_unit1; auto. apply join_unit2; auto.\n destruct a1; destruct a2; destruct a3; apply H3.\n intro x. specialize (H0 x). unfold compose.\n clear - H0. inv H0; simpl in *. apply join_unit1; auto. apply join_unit2; auto.\n destruct a1; destruct a2; destruct a3; apply H3.\n assert (Sac: forall x : address, join_sub (ac x) (share_of (z x))).\n   intro x.  apply join_sub_trans with (share_of (a x)). eexists; apply (H1 x).\n   exists (share_of (b x)).  apply join_share_of; auto.\n assert (Sad: forall x : address, join_sub (ad x) (share_of (z x))).\n   intro x.  apply join_sub_trans with (share_of (a x)). eexists; eapply join_comm; apply (H1 x).\n   exists (share_of (b x)).  apply join_share_of; auto.\n assert (Sbc: forall x : address, join_sub (bc x) (share_of (z x))).\n   intro x.  apply join_sub_trans with (share_of (b x)). eexists; apply (H2 x).\n   exists (share_of (a x)).  eapply join_comm; apply join_share_of; auto.\n assert (Sbd: forall x : address, join_sub (bd x) (share_of (z x))).\n   intro x.  apply join_sub_trans with (share_of (b x)). eexists; eapply join_comm; apply (H2 x).\n   exists (share_of (a x)).  eapply join_comm; apply join_share_of; auto.\n exists (exist AV.valid _ (fixup_splitting_valid ac z Sac Hz),\n            exist AV.valid _ (fixup_splitting_valid ad z Sad Hz),\n            exist AV.valid _ (fixup_splitting_valid bc z Sbc Hz),\n            exist AV.valid _ (fixup_splitting_valid bd z Sbd Hz)).\n split3; [ | | split];  do 2 red; simpl; intro;\n apply fixup_join; auto; intros.\n exists (b x0); apply H.\n exists (a x0); apply join_comm; apply H.\n exists (d x0); apply H0.\n exists (c x0); apply join_comm; apply H0.\nQed.\n\nInstance Trip_resource: Trip_alg resource.\nProof.\nintro; intros.\ndestruct a as [ra | ra sa ka pa | ka pa].\ndestruct b as [rb | rb sb kb pb | kb pb]; try solve [elimtype False; inv H].\ndestruct ab as [rab | rab sab kab pab | kab pab]; try solve [elimtype False; inv H].\ndestruct c as [rc | rc sc kc pc | kc pc]; try solve [elimtype False; inv H0].\ndestruct bc as [rbc | rbc sbc kbc pbc | kbc pbc]; try solve [elimtype False; inv H0].\ndestruct ac as [rac | rac sac kac pac | kac pac]; try solve [elimtype False; inv H1].\ndestruct (triple_join_exists_share ra rb rc rab rbc rac) as [rabc ?];\n  [inv H | inv H0 | inv H1 | ] ; auto.\nassert (n5 := join_unreadable_shares j n1 n2).\nexists (NO rabc n5); constructor; auto.\ndestruct bc as [rbc | rbc sbc kbc pbc | kbc pbc]; try solve [elimtype False; inv H0].\ndestruct ac as [rac | rac sac kac pac | kac pac]; try solve [elimtype False; inv H1].\ndestruct (triple_join_exists_share ra rb rc rab rbc rac) as [rabc ?];\n  [inv H | inv H0 | inv H1 | ] ; auto.\nassert (sabc := join_readable2 j sc).\nexists (YES rabc sabc kc pc); constructor; auto.\ndestruct ab as [rab | rab sab kab pab | kab pab]; try solve [elimtype False; inv H].\ndestruct c as [rc | rc sc kc pc | kc pc]; try solve [elimtype False; inv H0].\ndestruct bc as [rbc | rbc sbc kbc pbc | kbc pbc]; try solve [elimtype False; inv H0].\ndestruct ac as [rac | rac sac kac pac | kac pac]; try solve [elimtype False; inv H1].\ndestruct (triple_join_exists_share ra rb rc rab rbc rac) as [rabc ?];\n  [inv H | inv H0 | inv H1 | ] ; auto.\nassert (sabc := join_readable1 j sab).\nexists (YES rabc sabc kab pab); constructor; auto.\ndestruct bc as [rbc | rbc sbc kbc pbc | kbc pbc]; try solve [elimtype False; inv H0].\ndestruct ac as [rac | rac sac kac pac | kac pac]; try solve [elimtype False; inv H1].\ndestruct (triple_join_exists_share ra rb rc rab rbc rac) as [rabc ?];\n  [inv H | inv H0 | inv H1 | ] ; auto.\nassert (sabc := join_readable1 j sab).\nexists (YES rabc sabc kbc pbc). inv H0; inv H; inv H1; constructor; auto.\ndestruct b as [rb | rb sb kb pb | kb pb]; try solve [elimtype False; inv H].\ndestruct ab as [rab | rab sab kab pab | kab pab]; try solve [elimtype False; inv H].\ndestruct c as [rc | rc sc kc pc | kc pc]; try solve [elimtype False; inv H0].\ndestruct bc as [rbc | rbc sbc kbc pbc | kbc pbc]; try solve [elimtype False; inv H0].\ndestruct ac as [rac | rac sac kac pac | kac pac]; try solve [elimtype False; inv H1].\ndestruct (triple_join_exists_share ra rb rc rab rbc rac) as [rabc ?];\n  [inv H | inv H0 | inv H1 | ] ; auto.\nassert (sabc := join_readable1 j sab).\nexists (YES rabc sabc kab pab); constructor; auto.\ndestruct bc as [rbc | rbc sbc kbc pbc | kbc pbc]; try solve [elimtype False; inv H0].\ndestruct ac as [rac | rac sac kac pac | kac pac]; try solve [elimtype False; inv H1].\ndestruct (triple_join_exists_share ra rb rc rab rbc rac) as [rabc ?];\n  [inv H | inv H0 | inv H1 | ] ; auto.\nassert (sabc := join_readable1 j sab).\nexists (YES rabc sabc kac pac).  inv H; inv H0; inv H1; constructor; auto.\ndestruct ab as [rab | rab sab kab pab | kab pab]; try solve [elimtype False; inv H].\ndestruct c as [rc | rc sc kc pc | kc pc]; try solve [elimtype False; inv H0].\ndestruct bc as [rbc | rbc sbc kbc pbc | kbc pbc]; try solve [elimtype False; inv H0].\ndestruct ac as [rac | rac sac kac pac | kac pac]; try solve [elimtype False; inv H1].\ndestruct (triple_join_exists_share ra rb rc rab rbc rac) as [rabc ?];\n  [inv H | inv H0 | inv H1 | ] ; auto.\nassert (sabc := join_readable1 j sab).\nexists (YES rabc sabc kab pab); constructor; auto.\ndestruct bc as [rbc | rbc sbc kbc pbc | kbc pbc]; try solve [elimtype False; inv H0].\ndestruct ac as [rac | rac sac kac pac | kac pac]; try solve [elimtype False; inv H1].\ndestruct (triple_join_exists_share ra rb rc rab rbc rac) as [rabc ?];\n  [inv H | inv H0 | inv H1 | ] ; auto.\nassert (sabc := join_readable1 j sab).\nexists (YES rabc sabc kc pc).\n inv H. inv H1. inv H0.\nconstructor; auto.\n exists ab. inv H. inv H1. inv H0. constructor.\nQed.\n\nLemma pure_readable_share_i:\n  forall sh, readable_share sh -> (pure_readable_share (Share.glb Share.Rsh sh)).\nProof.\nintros. split. rewrite <- Share.glb_assoc. rewrite glb_Lsh_Rsh.\nrewrite Share.glb_commute. apply Share.glb_bot.\ndo 3 red in H|-*. contradict H.\nrewrite glb_twice in H. auto.\nQed.\n\nInstance Trip_rmap : Trip_alg rmap.\nProof.\nintro; intros.\npose (f loc := @Trip_resource _ _ _ _ _ _\n                 (resource_at_join _ _ _ loc H)\n                 (resource_at_join _ _ _ loc H0)\n                 (resource_at_join _ _ _ loc H1)).\nassert (CompCert_AV.valid (res_option oo (fun l => proj1_sig (f l)))).\nintros b' z'.\nunfold compose. simpl.\ndestruct (f (b',z')); simpl.\ndestruct x; simpl; auto.\ndestruct k; simpl; auto.\nintros.\ndestruct (f (b',z'+i)). simpl.\ncase_eq (ab @ (b', z')); case_eq (c @ (b', z')); intros; try solve [rewrite H3 in j; inv j];\n  try solve [rewrite H4 in j; inv j].\nrewrite H3 in j; rewrite H4 in j. inv j.\nrename H3 into H6.\npose proof (rmap_valid_e1 c b' z' _ _ H2 (readable_part r0)).\nrewrite H4 in j; rewrite H6 in j.\nassert (k = LK z) by (inv j; auto). subst.\nassert (p0 = p) by (inv j; auto). subst.\nspec H3; [rewrite H6; auto|].\ninv j. rename RJ into j.\ndestruct (c @ (b',z'+i)); inv H3.\ncase_eq (ab @ (b', z' + i)); intros.\n*\nrewrite H3 in j0; inv j0.\nsimpl. f_equal; f_equal.\nclear f nsh2 rsh4 rsh0 H2 H4 H6 H3 p.\nclear rsh1 i p0 nsh0.\napply exist_ext.\n  apply join_glb_Rsh in RJ.\n  apply join_glb_Rsh in j.\n  glb_Rsh_tac.\n*\nassert (H9 := pure_readable_share_i _ r2).\ngeneralize (rmap_valid_e2 ab b' z' i (mk_rshare _ H9)); intro.\nrewrite H3 in *. clear H3.\nsimpl in H5.\nspec H5. inv j0. do 2 f_equal. apply exist_ext. auto.\ndestruct H5 as [nx [? ?]].\nrewrite H4 in H5. inv H5.\n*\nintros.\nrewrite H3 in j0. inv j0.\n*\nrewrite H4 in j. inv j.\nassert (H99 := pure_readable_share_i _ r0).\npose proof (rmap_valid_e1 ab b' z' _ _ H2 (mk_rshare _ H99)).\nrewrite H4 in H5.\nspec H5. simpl. f_equal. f_equal. apply exist_ext; reflexivity.\ndestruct (ab @ (b',z'+i)); inv H5.\nrewrite H3 in H9; inv H9.\ninv j0. simpl.  repeat f_equal. apply exist_ext.\n  apply join_glb_Rsh in RJ.\n  apply join_glb_Rsh in RJ0.\n  glb_Rsh_tac.\n simpl. do 2 f_equal. apply exist_ext.\nassert (H98 := pure_readable_share_i _ rsh3).\n pose proof (rmap_valid_e2 c b' z' i  (mk_rshare _ H98)).\n rewrite <- H10 in H5.\n spec H5. simpl. do 2 f_equal. apply exist_ext. auto.\ndestruct H5 as [nx [? ?]]; auto. rewrite H3 in H6. inv H6.\n congruence.\n*\nrewrite H3 in j. rewrite H4 in j. inv j.\nassert (H99 := pure_readable_share_i _ r0).\npose proof (rmap_valid_e1 c b' z' _ _ H2 (mk_rshare _ H99)).\nspec H5.  rewrite H3. simpl. repeat f_equal. apply exist_ext; auto.\nassert (H98 := pure_readable_share_i _ r1).\npose proof (rmap_valid_e1 ab b' z' _ _ H2 (mk_rshare _ H98)).\nspec H6.  rewrite H4. simpl. repeat f_equal. apply exist_ext; auto.\ndestruct (c @ (b',z'+i)); inv H5.\ndestruct (ab @ (b',z'+i)); inv H6.\ninv j0. simpl. repeat f_equal. apply exist_ext.\napply join_glb_Rsh in RJ.\napply join_glb_Rsh in RJ0.\nrewrite H8 in *; rewrite H7 in *.\neapply join_eq;  eauto.\n* (**)\ndestruct (f (b',z'-z)).\nsimpl.\ncase_eq (ab @ (b', z')); case_eq (c @ (b', z')); intros; try solve [rewrite H2, H3 in j; inv j].\n+\nrewrite H2 in j; rewrite H3 in j; inv j.\nrename H2 into H5.\nsymmetry in H3.\nassert (H99 := pure_readable_share_i _ r0).\npose proof (rmap_valid_e2 c b' (z'-z) z  (mk_rshare _ H99)).\nrewrite Z.sub_add, H5 in H2.\nspec H2.  simpl. repeat f_equal. apply exist_ext. auto.\ndestruct H2 as [nx [? ?]]; exists nx; split; auto.\ndestruct (c @ (b',z'-z)); inv H4.\ninv j0. simpl. repeat f_equal. apply exist_ext.\napply join_glb_Rsh in RJ.\napply join_glb_Rsh in RJ0.\nglb_Rsh_tac.\nassert (H98 := pure_readable_share_i _ rsh2).\npose proof (rmap_valid_e1 ab b' (z'-z) _ _ H2 (mk_rshare _ H98)).\nspec H4. rewrite <- H6. simpl. repeat f_equal. apply exist_ext. auto.\nrewrite Z.sub_add in H4.\nrewrite <- H3 in H4; inv H4.\n+\nrewrite H2 in j; inv j. rewrite H3 in H5; inv H5.\nassert (H99 := pure_readable_share_i _ r0).\npose proof (rmap_valid_e2 ab b' (z'-z) z (mk_rshare _ H99)).\nspec H4. rewrite Z.sub_add. rewrite H3. simpl. repeat f_equal. apply exist_ext. auto.\nrename H4 into H2'; rename H2 into H4; rename H2' into H2.\nrename H3 into H5.\ndestruct H2 as [nx [? ?]]; exists nx; split; auto.\ndestruct (ab @ (b',z'-z)); inv H3.\ninv j0; try reflexivity.\nsimpl; repeat f_equal; apply exist_ext.\napply join_glb_Rsh in RJ.\napply join_glb_Rsh in RJ0.\nglb_Rsh_tac.\nsimpl; repeat f_equal. \nassert (H98 := pure_readable_share_i _ rsh3).\npose proof (rmap_valid_e1 c b' (z'-z) _ _ H2 (mk_rshare _ H98)).\nspec H3. rewrite <- H10. simpl. repeat f_equal; apply exist_ext. auto.\nrewrite Z.sub_add in H3. \nrewrite H4 in H3; inv H3.\n+\nrewrite H3 in j; rewrite H2 in j; inv j.\nassert (H99 := pure_readable_share_i _ r0).\npose proof (rmap_valid_e2 c b' (z'-z) z (mk_rshare _ H99)).\nspec H4. rewrite Z.sub_add. rewrite H2. simpl. repeat f_equal; apply exist_ext; auto.\ndestruct H4 as [n [? ?]]; exists n; split; auto.\ndestruct (c @ (b',z'-z)); inv H5.\nassert (H98 := pure_readable_share_i _ r1).\npose proof (rmap_valid_e2 ab b' (z'-z) z  (mk_rshare _ H98)).\nspec H5. rewrite Z.sub_add. rewrite H3. simpl; repeat f_equal; apply exist_ext; auto.\ndestruct H5 as [n' [? ?]].\ndestruct (ab @ (b',z'-z)); inv j0; inv H6.\nsimpl. do 2 f_equal. apply exist_ext.\napply join_glb_Rsh in RJ.\napply join_glb_Rsh in RJ0.\nrewrite H9 in *; rewrite H7 in *.\neapply join_eq; eauto.\n*\ndestruct (make_rmap _ H2 (level a)) as [abc [? ?]].\nextensionality loc. unfold compose; simpl.\ndestruct (f loc); simpl.\ndestruct x; simpl; auto.\nf_equal.\ngeneralize (resource_at_join _ _ _ loc H);\ngeneralize (resource_at_join _ _ _ loc H0);\ngeneralize (resource_at_join _ _ _ loc H1);\ninv j; intros.\ninv H7.\ngeneralize (resource_at_approx a loc); rewrite <- H9;  intro.\ninjection (YES_inj _ _ _ _ _ _ _ _ H7); auto.\nreplace (level a) with (level b).\n 2:  clear - H; apply join_level in H; destruct H; congruence.\ngeneralize (resource_at_approx b loc); rewrite <- H10;  intro.\ninjection (YES_inj _ _ _ _ _ _ _ _ H7); auto.\ngeneralize (resource_at_approx a loc); rewrite <- H9;  intro.\ninjection (YES_inj _ _ _ _ _ _ _ _ H7); auto.\nreplace (level a) with (level c).\n 2:  clear - H1; apply join_level in H1; destruct H1; congruence.\ngeneralize (resource_at_approx c loc); rewrite <- H5;  intro.\ninjection (YES_inj _ _ _ _ _ _ _ _ H8); auto.\nreplace (level a) with (level c).\n 2:  clear - H1; apply join_level in H1; destruct H1; congruence.\ngeneralize (resource_at_approx c loc); rewrite <- H5;  intro.\ninjection (YES_inj _ _ _ _ _ _ _ _ H8); auto.\ninv j.\nreplace (level a) with (level c).\n 2:  clear - H1; apply join_level in H1; destruct H1; congruence.\ngeneralize (resource_at_approx c loc); rewrite <- H5;  intro.\nauto.\nexists abc.\napply resource_at_join2.\nrewrite H3. clear - H. apply join_level in H; destruct H; auto.\nrewrite H3. clear - H1; apply join_level in H1; destruct H1; congruence.\nintro loc.\nrewrite H4.\ndestruct (f loc).\nsimpl.\nauto.\nQed.\n\nObligation Tactic := Tactics.program_simpl.\n\nLemma pure_readable_Rsh: pure_readable_share Share.Rsh.\nProof.\nsplit. apply glb_Lsh_Rsh. intro. rewrite Share.glb_idem in H.\npose proof (Share.split_nontrivial Share.Lsh Share.Rsh Share.top).\nspec H0.\nunfold Share.Lsh, Share.Rsh.\ndestruct (Share.split Share.top); auto.\napply identity_share_bot in H.\nspec H0; auto.\ncontradiction Share.nontrivial.\nQed.\n\nDefinition rfullshare : rshare := mk_rshare _ pure_readable_Rsh.\n\nProgram Definition writable (l: address): pred rmap :=\n fun phi =>\n  match phi @ l with\n    | YES sh _ k lp => writable_share sh /\\ isVAL k\n    | _ => False\n  end.\n Next Obligation.\n  intro; intros.\n  generalize (age1_res_option a a' l H); intro.\n  destruct (a @ l); try contradiction.\n  simpl in H1.\n  destruct (a' @ l); inv H1; auto.\n  destruct H0; split; auto.\n  unfold writable_share in *.\n  clear - H3 H0.\n  apply leq_join_sub in H0.\n  apply leq_join_sub.\n  apply Share.ord_spec2 in H0. rewrite <- H0 in H3.\n  rewrite Share.glb_absorb in H3.\n  clear H0.\n  rewrite H3.\n  apply Share.glb_lower2.\nQed.\n\nProgram Definition readable (loc: address) : pred rmap :=\n   fun phi => match phi @ loc with YES _ _ k _ => isVAL k | _ => False end.\n Next Obligation.\n  intro; intros.\n  generalize (age1_res_option a a' loc H); intro.\n  destruct (a @ loc); try contradiction.\n  simpl in H1.\n  destruct (a' @ loc); inv H1; auto.\n  Qed.\n\nLemma readable_join:\n  forall phi1 phi2 phi3 loc, join phi1 phi2 phi3 ->\n            readable loc phi1 -> readable loc phi3.\nProof.\nunfold readable; intros until loc.\nintros.\nsimpl in *.\ngeneralize (resource_at_join _ _ _ loc H); clear H; intros.\nrevert H0 H; destruct (phi1 @ loc); intros; try contradiction.\ninv H; auto.\nQed.\n\nLemma readable_writable_join:\nforall phi1 phi2 l, readable l phi1 -> writable l phi2 -> joins phi1 phi2 -> False.\nProof.\nintros.\nunfold readable, writable in *.\nsimpl in H, H0.\ndestruct H1 as [phi ?].\ngeneralize (resource_at_join _ _ _ l H1); clear H1; revert H H0.\ndestruct (phi1 @ l); intros; try contradiction.\ndestruct (phi2 @ l); try contradiction.\ninv H1.\ndestruct H0.\nclear - RJ H0 r.\nunfold readable_share, writable_share in *.\ndestruct H0.\ndestruct (join_assoc (join_comm H) (join_comm RJ)) as [a [? ?]].\nclear - r H0.\napply r; clear r.\ndestruct H0.\nrewrite H. auto.\nQed.\n\nLemma writable_join_sub:\n  forall sh sh', join_sub sh sh' -> writable_share sh -> writable_share sh'.\nProof.\nintros.\ndestruct H.\ndestruct H0 as [b ?].\ndestruct (join_assoc H0 H) as [c [? ?]].\nexists c; auto.\nQed.\n\nLemma writable_join: forall loc phi1 phi2, join_sub phi1 phi2 ->\n            writable loc phi1 -> writable loc phi2.\nProof.\nunfold writable; intros.\nsimpl in *.\ndestruct H; generalize (resource_at_join _ _ _ loc H); clear H.\nrevert H0; destruct (phi1 @ loc); intros; try contradiction.\ndestruct H0; subst.\ninv H; split; auto; eapply writable_join_sub; eauto; eexists; eauto.\nQed.\n\nLemma writable_readable: forall loc m, writable loc m -> readable loc m.\nProof.\n unfold writable, readable.\n intros ? ?. simpl.  destruct (m @ loc); auto. intros [? ?]. auto.\nQed.\n\nLemma writable_e: forall loc m, \n   writable loc m -> \n   exists sh, exists rsh, exists v, exists p, \n     m @ loc = YES sh rsh (VAL v) p /\\ writable_share sh.\nProof.\nunfold writable; simpl; intros; destruct (m@loc); try contradiction.\ndestruct H.\ndestruct k; try solve [inversion H0].\nexists sh, r, m0, p; split; auto.\nQed.\nArguments writable_e [loc] [m] _.\n\nLemma readable_e: forall loc m, \n   readable loc m -> \n  exists sh, exists rsh, exists v, exists p, m @ loc = YES sh rsh (VAL v) p.\nProof.\nunfold readable; simpl; intros; destruct (m@loc); try contradiction.\ndestruct k; try solve [inversion H].\nsubst.\neconstructor; eauto.\nQed.\nArguments readable_e [loc] [m] _.\n\nDefinition bytes_writable (loc: address) (size: Z) (phi: rmap) : Prop :=\n  forall i, (0 <= i < size) -> writable (adr_add loc i) phi.\n\nDefinition bytes_readable (loc: address) (size: Z) (phi: rmap) : Prop :=\n  forall i, (0 <= i < size) -> readable (adr_add loc i) phi.\n\nLemma readable_dec (loc: address) (phi: rmap) : {readable loc phi} + {~readable loc phi}.\nProof. intros.\nunfold readable. simpl.\ncase (phi @ loc); intros; auto.\napply isVAL_dec.\nQed.\n\nLemma writable_dec: forall loc phi, {writable loc phi}+{~writable loc phi}.\nProof.\nintros.\nunfold writable. simpl.\ndestruct (phi @ loc); auto.\ndestruct (isVAL_dec k).\ndestruct (writable_share_dec sh).\nleft; auto.\nright; auto. contradict n; auto.\ndestruct n; auto.\nright; contradict n; destruct n; auto.\nQed.\n\nLemma bytes_writable_dec:\n   forall loc n m, {bytes_writable loc n m}+{~bytes_writable loc n m}.\nProof.\nintros.\ndestruct n.\nleft; intro; intros; omegaContradiction.\n2: generalize (Zlt_neg_0 p); intro; left; intro; intros; omegaContradiction.\nrewrite Zpos_eq_Z_of_nat_o_nat_of_P.\nremember (nat_of_P p) as n.\nclear.\ndestruct loc as [b z].\nrevert z;\ninduction n; intros.\nleft; intro; intros.\nsimpl in H; omegaContradiction.\nrewrite inj_S.\ndestruct (IHn (z+1)).\ndestruct (writable_dec (b,z) m).\nleft.\nintro; intros.\nunfold adr_add; simpl.\ndestruct (zeq i 0).\nsubst.\nreplace (z+0) with z by omega.\nauto.\nreplace (z+i) with (z+1+(i-1)) by omega.\napply b0.\nomega.\nright.\ncontradict n0.\nspec n0 0.\nunfold adr_add in n0; simpl in n0.\nreplace (z+0) with z in n0.\napply n0.\nomega.\nomega.\nright.\ncontradict n0.\nintro; intros.\nunfold adr_add; simpl.\nreplace (z+1+i) with (z+(1+i)) by omega.\napply n0.\nomega.\nQed.\n\nLemma bytes_readable_dec:\n   forall loc n m, {bytes_readable loc n m}+{~bytes_readable loc n m}.\nProof.\nintros.\ndestruct n.\nleft; intro; intros; omegaContradiction.\n2: generalize (Zlt_neg_0 p); intro; left; intro; intros; omegaContradiction.\nrewrite Zpos_eq_Z_of_nat_o_nat_of_P.\nremember (nat_of_P p) as n.\nclear.\ndestruct loc as [b z].\nrevert z;\ninduction n; intros.\nleft; intro; intros.\nsimpl in H; omegaContradiction.\nrewrite inj_S.\ndestruct (IHn (z+1)).\ndestruct (readable_dec (b,z) m).\nleft.\nintro; intros.\nunfold adr_add; simpl.\ndestruct (zeq i 0).\nsubst.\nreplace (z+0) with z by omega.\nauto.\nreplace (z+i) with (z+1+(i-1)) by omega.\napply b0.\nomega.\nright.\ncontradict n0.\nspec n0 0.\nunfold adr_add in n0; simpl in n0.\nreplace (z+0) with z in n0.\napply n0.\nomega.\nomega.\nright.\ncontradict n0.\nintro; intros.\nunfold adr_add; simpl.\nreplace (z+1+i) with (z+(1+i)) by omega.\napply n0.\nomega.\nQed.\n\nLemma bytes_writable_readable:\n  forall m loc n, bytes_writable m loc n -> bytes_readable m loc n.\nProof.\nunfold bytes_writable, bytes_readable; intros.\napply writable_readable; auto.\nQed.\n\nHint Resolve bytes_writable_readable : mem.\n\nLemma rmap_age_i:\n forall w w' : rmap,\n    level w = S (level w') ->\n   (forall l, resource_fmap (approx (level w')) (approx (level w')) (w @ l) = w' @ l) ->\n    age w w'.\nProof.\nintros.\nhnf.\ndestruct (levelS_age1 _ _ H).\nassert (x=w'); [ | subst; auto].\nassert (level x = level w')\n  by (apply age_level in H1; omega).\napply rmap_ext; auto.\nintros.\nspecialize (H0 l).\nrewrite (age1_resource_at w x H1 l (w@l)).\nrewrite H2.\napply H0.\nsymmetry; apply resource_at_approx.\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/compcert_rmaps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.26616676897967767}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Import Tweetnacl_verif.init_tweetnacl.\nRequire Import Tweetnacl.Libs.Export.\nRequire Import Tweetnacl.ListsOp.Export.\nRequire Import Tweetnacl.Low.M.\nRequire Export Tweetnacl_verif.verif_M_compute_pre.\n\nLocal Open Scope Z.\n\n\nLocal Instance term_dec : Decidable := \n{\n  decide := term_decide;\n  denote := term_denote;\n  decide_impl := term_decide_impl\n}.\n\nLocal Instance expr_dec : Decidable := \n{\n  decide := expr_decide;\n  denote := expr_denote;\n  decide_impl := expr_decide_impl\n}.\n\nLocal Instance list_expr_dec : Decidable := Build_Decidable\n  (list expr) (list Z) \n  (list_decide) (list_denote) (list_decide_impl).\n\nLocal Instance list_term_dec : Decidable := Build_Decidable\n  (list term) (list Z) \n  (list_decide) (list_denote) (list_decide_impl).\n\nLocal Ltac solve_this_thing_please_autorewrite i j:= \n    subst i;\n    let H' := fresh in\n    gen_i H' j ; simpl;\n    repeat orewrite inner_M_i_j_eq;\n    repeat orewrite Znth_nth;\n    unfold nat_of_Z;\n    simpl;\n    unfold update_M_i_j';\n    unfold local_update_M; simpl; \n    autorewrite with innerouterMdb;\n    repeat orewrite upd_Znth_upd_nth;\n    simpl;\n    mini_ring.\n\nLemma outer_M_fix_i_1' : forall i j contents_a contents_b,\nZlength contents_a = 16 ->\nZlength contents_b = 16 ->\n0 <= i < 4 ->\n0 <= j < 16 ->\n0 < i ->\nouter_M_fix (i - 1) 16 contents_a contents_b\n  (inner_M_fix i (j + 1)\n     (option.from_option id 0 (base.lookup (Z.to_nat i) contents_a))\n     contents_b\n     [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     0; 0; 0; 0; 0; 0; 0]) =\nupd_Znth (i + j)\n  (outer_M_fix i j contents_a contents_b\n     [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     0; 0; 0; 0; 0; 0; 0])\n  (Znth (i + j)\n     (outer_M_fix i j contents_a contents_b\n        [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0;\n        0; 0; 0; 0; 0; 0; 0; 0]) 0 +\n   Znth i contents_a 0 * Znth j contents_b 0).\nProof.\n  intros i j a b Ha Hb Hi Hj Hii.\n  rewrite Zlength_correct in Ha.\n  rewrite Zlength_correct in Hb.\n  assert(Ha' : (length a = 16)%nat) by go.\n  assert(Hb' : (length b = 16)%nat) by go.\n  repeat (destruct a ; tryfalse).\n  repeat (destruct b ; tryfalse).\n  rewrite <- Zlength_correct in *.\n  rewrite (outer_M_fix_equation i).\n  flatten.\n    apply Z.leb_le in Eq ; omega.\n    clear Eq.\n  assert_gen_hyp_ H i 3 3. omega.\n    destruct H ; try (subst i ; omega).\n  Opaque outer_M_fix.\n    repeat (destruct H ; [solve_this_thing_please_autorewrite i j|]).\n    solve_this_thing_please_autorewrite i j.\nQed.\n\nLemma outer_M_fix_i_1'' : forall i j contents_a contents_b,\nZlength contents_a = 16 ->\nZlength contents_b = 16 ->\n4 <= i < 8 ->\n0 <= j < 16 ->\n0 < i ->\nouter_M_fix (i - 1) 16 contents_a contents_b\n  (inner_M_fix i (j + 1)\n     (option.from_option id 0 (base.lookup (Z.to_nat i) contents_a))\n     contents_b\n     [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     0; 0; 0; 0; 0; 0; 0]) =\nupd_Znth (i + j)\n  (outer_M_fix i j contents_a contents_b\n     [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     0; 0; 0; 0; 0; 0; 0])\n  (Znth (i + j)\n     (outer_M_fix i j contents_a contents_b\n        [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0;\n        0; 0; 0; 0; 0; 0; 0; 0]) 0 +\n   Znth i contents_a 0 * Znth j contents_b 0).\nProof.\n  intros i j a b Ha Hb Hi Hj Hii.\n  rewrite Zlength_correct in Ha.\n  rewrite Zlength_correct in Hb.\n  assert(Ha' : (length a = 16)%nat) by go.\n  assert(Hb' : (length b = 16)%nat) by go.\n  repeat (destruct a ; tryfalse).\n  repeat (destruct b ; tryfalse).\n  rewrite <- Zlength_correct in *.\n  rewrite (outer_M_fix_equation i).\n  flatten.\n    apply Z.leb_le in Eq ; omega.\n    clear Eq.\n  assert(H: i = 4 \\/ i = 5 \\/ i = 6 \\/ i = 7) by omega.\n  Opaque outer_M_fix.\n    repeat (destruct H ; [solve_this_thing_please_autorewrite i j|]).\n    solve_this_thing_please_autorewrite i j.\nQed.\n\nLemma outer_M_fix_i_1''' : forall i j contents_a contents_b,\nZlength contents_a = 16 ->\nZlength contents_b = 16 ->\n8 <= i < 12 ->\n0 <= j < 16 ->\n0 < i ->\nouter_M_fix (i - 1) 16 contents_a contents_b\n  (inner_M_fix i (j + 1)\n     (option.from_option id 0 (base.lookup (Z.to_nat i) contents_a))\n     contents_b\n     [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     0; 0; 0; 0; 0; 0; 0]) =\nupd_Znth (i + j)\n  (outer_M_fix i j contents_a contents_b\n     [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     0; 0; 0; 0; 0; 0; 0])\n  (Znth (i + j)\n     (outer_M_fix i j contents_a contents_b\n        [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0;\n        0; 0; 0; 0; 0; 0; 0; 0]) 0 +\n   Znth i contents_a 0 * Znth j contents_b 0).\nProof.\n  intros i j a b Ha Hb Hi Hj Hii.\n  rewrite Zlength_correct in Ha.\n  rewrite Zlength_correct in Hb.\n  assert(Ha' : (length a = 16)%nat) by go.\n  assert(Hb' : (length b = 16)%nat) by go.\n  repeat (destruct a ; tryfalse).\n  repeat (destruct b ; tryfalse).\n  rewrite <- Zlength_correct in *.\n  rewrite (outer_M_fix_equation i).\n  flatten.\n    apply Z.leb_le in Eq ; omega.\n    clear Eq.\n  assert(H: i = 8 \\/ i = 9 \\/ i = 10 \\/ i = 11 \\/ i = 12) by omega.\n  Opaque outer_M_fix.\n    repeat (destruct H ; [solve_this_thing_please_autorewrite i j|]).\n    solve_this_thing_please_autorewrite i j.\nQed.\n\nLemma outer_M_fix_i_1'''' : forall i j contents_a contents_b,\nZlength contents_a = 16 ->\nZlength contents_b = 16 ->\n12 <= i < 16 ->\n0 <= j < 16 ->\n0 < i ->\nouter_M_fix (i - 1) 16 contents_a contents_b\n  (inner_M_fix i (j + 1)\n     (option.from_option id 0 (base.lookup (Z.to_nat i) contents_a))\n     contents_b\n     [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     0; 0; 0; 0; 0; 0; 0]) =\nupd_Znth (i + j)\n  (outer_M_fix i j contents_a contents_b\n     [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     0; 0; 0; 0; 0; 0; 0])\n  (Znth (i + j)\n     (outer_M_fix i j contents_a contents_b\n        [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0;\n        0; 0; 0; 0; 0; 0; 0; 0]) 0 +\n   Znth i contents_a 0 * Znth j contents_b 0).\nProof.\n  intros i j a b Ha Hb Hi Hj Hii.\n  rewrite Zlength_correct in Ha.\n  rewrite Zlength_correct in Hb.\n  assert(Ha' : (length a = 16)%nat) by go.\n  assert(Hb' : (length b = 16)%nat) by go.\n  repeat (destruct a ; tryfalse).\n  repeat (destruct b ; tryfalse).\n  rewrite <- Zlength_correct in *.\n  rewrite (outer_M_fix_equation i).\n  flatten.\n    apply Z.leb_le in Eq ; omega.\n    clear Eq.\n  assert(H: i = 12 \\/ i = 13 \\/ i = 14 \\/ i = 15) by omega.\n(*   assert(H: i = 8 \\/ i = 9 \\/ i = 10 \\/ i = 11 \\/ i = 12) by omega. *)\n  Opaque outer_M_fix.\n    repeat (destruct H ; [solve_this_thing_please_autorewrite i j|]).\n    solve_this_thing_please_autorewrite i j.\nQed.\n\nLemma outer_M_fix_i_1 : forall i j contents_a contents_b,\nZlength contents_a = 16 ->\nZlength contents_b = 16 ->\n0 <= i < 16 ->\n0 <= j < 16 ->\n0 < i ->\nouter_M_fix (i - 1) 16 contents_a contents_b\n  (inner_M_fix i (j + 1)\n     (option.from_option id 0 (base.lookup (Z.to_nat i) contents_a))\n     contents_b\n     [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     0; 0; 0; 0; 0; 0; 0]) =\nupd_Znth (i + j)\n  (outer_M_fix i j contents_a contents_b\n     [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     0; 0; 0; 0; 0; 0; 0])\n  (Znth (i + j)\n     (outer_M_fix i j contents_a contents_b\n        [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0;\n        0; 0; 0; 0; 0; 0; 0; 0]) 0 +\n   Znth i contents_a 0 * Znth j contents_b 0).\nProof.\n  intros i j a b Ha Hb Hi Hj Hii.\n  assert(H: i < 4 \\/ 4 <= i < 8 \\/  8 <= i < 12 \\/ 12 <= i) by omega.\n  destruct H.\n  apply outer_M_fix_i_1' ; go.\n  destruct H.\n  apply outer_M_fix_i_1'' ; go.\n  destruct H.\n  apply outer_M_fix_i_1''' ; go.\n  apply outer_M_fix_i_1'''' ; go.\nQed.\n\n\nClose Scope Z.\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/proofs/vst/proofs/verif_M_compute.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.26616676293171493}}
{"text": "Require Export basic_facts_plane.\n\nModule back (M: ProjectivePlane') : ProjectivePlane\nwith Definition Point := M.Point\nwith Definition Line := M.Line\nwith Definition Incid := M.Incid.\n\nDefinition Point := M.Point.\nDefinition Line := M.Line.\nDefinition Incid := M.Incid.\n\nDefinition incid_dec := M.incid_dec.\nDefinition a1_exist := M.a1_exist.\nDefinition a2_exist := M.a2_exist.\nDefinition uniqueness := M.uniqueness.\n\nModule Import uniq := uniqueness_axioms M.\n\n(** M and P are the same and lie at the meeting point between l1 and l2 **)\n\nLemma case1 : forall M N O P Q R : Point, forall l1 l2 : Line, \n  l1 <> l2 -> \n  dist3 M N O /\\ Incid M l1 /\\ Incid N l1 /\\ Incid O l1 ->\n  dist3 P Q R /\\ Incid P l2 /\\ Incid Q l2 /\\ Incid R l2 ->\n  Incid M l2 -> Incid P l1 -> \n  {A : Point & {B : Point & {C : Point & {D : Point |\n          forall l : Line,\n            dist4 A B C D /\\\n            (Incid A l /\\ Incid B l -> ~ Incid C l /\\ ~ Incid D l) /\\\n            (Incid A l /\\ Incid C l -> ~ Incid B l /\\ ~ Incid D l) /\\\n            (Incid A l /\\ Incid D l -> ~ Incid C l /\\ ~ Incid B l) /\\\n            (Incid C l /\\ Incid B l -> ~ Incid A l /\\ ~ Incid D l) /\\\n            (Incid D l /\\ Incid B l -> ~ Incid C l /\\ ~ Incid A l) /\\\n            (Incid C l /\\ Incid D l -> ~ Incid B l /\\ ~ Incid A l)}}}}.\nintros M N O P Q R l1 l2 H1 H2 H3 HMl2 HPl1.\nunfold dist3 in H2,H3.\nintuition.\nassert (~Incid N l2).\nintro HNl2.\ngeneralize (a2_unique l1 l2 M N H1 H HMl2 H5 HNl2); intros H'.\nsubst M.\napply H3; trivial.\nassert (~Incid O l2).\nintro HOl2.\ngeneralize (a2_unique l1 l2 M O H1 H HMl2 H10 HOl2); intros H'.\nsubst M.\napply H4; trivial.\nassert (~Incid Q l1).\nintros HQl1.\ngeneralize (a2_unique l1 l2 P Q H1 HPl1 H2 HQl1 H7); intros H'.\nsubst P.\napply H0; trivial.\nassert (~Incid R l1).\nintros HRl1.\ngeneralize (a2_unique l1 l2 P R H1 HPl1 H2 HRl1 H12); intros H'.\nsubst P.\napply H6; trivial.\nexists N. \nexists O. \nexists Q. \nexists R.\nintros l.\nsplit.\nsplit.\nassumption.\nsplit.\nintros HNQ.\nsubst N.\ntauto.\nsplit.\nintros HNR.\nsubst N.\ntauto.\nsplit.\nintros HOQ.\nsubst O.\ntauto.\nsplit.\nintros HOR.\nsubst O.\ntauto.\nassumption.\nsplit.\nintros (Hnew1, Hnew2).\ngeneralize (a1_unique N O l l1 H9 Hnew1 Hnew2 H5 H10); intros H'.\nsubst l.\ntauto.\nsplit.\nintros (Hnew1, Hnew2).\nsplit.\nintros HOl.\n\ngeneralize (a1_unique N O l l1 H9 Hnew1 HOl H5 H10); intros H'.\nsubst l.\ntauto.\nintros HRl.\ngeneralize (a1_unique Q R l l2 H11 Hnew2 HRl H7 H12) ; intros H'.\nsubst l.\ntauto.\n\nsplit.\nintros (Hnew1,Hnew2).\nsplit.\nintros HQl.\ngeneralize (a1_unique Q R l l2 H11 HQl Hnew2 H7 H12) ; intros H'.\nsubst l.\ntauto.\nintros HOl.\ngeneralize (a1_unique N O l l1 H9 Hnew1 HOl H5 H10); intros H'.\nsubst l.\ntauto.\n \nsplit.\nintros (Hnew1, Hnew2).\nsplit.\nintros HNl.\ngeneralize (a1_unique N O l l1 H9 HNl Hnew2 H5 H10); intros H'.\nsubst l.\ntauto.\nintros HRl.\ngeneralize (a1_unique Q R l l2 H11 Hnew1 HRl H7 H12) ; intros H'.\nsubst l.\ntauto.\n\nsplit.\nintros (Hnew1,Hnew2).\nsplit.\nintros HQl.\ngeneralize (a1_unique Q R l l2 H11 HQl Hnew1 H7 H12) ; intros H'.\nsubst l.\ntauto.\nintros HNl.\ngeneralize (a1_unique N O l l1 H9 HNl Hnew2 H5 H10); intros H'.\nsubst l.\ntauto.\nintros (Hnew1, Hnew2).\ngeneralize (a1_unique Q R l l2 H11 Hnew1 Hnew2 H7 H12) ; intros H'.\nsubst l.\ntauto.\nQed.\n\nLemma case2 : forall M N O P Q R : Point, forall l1 l2 : Line, \n  l1 <> l2 -> \n  dist3 M N O /\\ Incid M l1 /\\ Incid N l1 /\\ Incid O l1 ->\n  dist3 P Q R /\\ Incid P l2 /\\ Incid Q l2 /\\ Incid R l2 ->\n  Incid M l2 -> ~Incid P l1 -> ~Incid Q l1 -> ~Incid R l1 -> \n  {A : Point & {B : Point & {C : Point & {D : Point |\n          forall l : Line,\n            dist4 A B C D /\\\n            (Incid A l /\\ Incid B l -> ~ Incid C l /\\ ~ Incid D l) /\\\n            (Incid A l /\\ Incid C l -> ~ Incid B l /\\ ~ Incid D l) /\\\n            (Incid A l /\\ Incid D l -> ~ Incid C l /\\ ~ Incid B l) /\\\n            (Incid C l /\\ Incid B l -> ~ Incid A l /\\ ~ Incid D l) /\\\n            (Incid D l /\\ Incid B l -> ~ Incid C l /\\ ~ Incid A l) /\\\n            (Incid C l /\\ Incid D l -> ~ Incid B l /\\ ~ Incid A l)}}}}.\nintros M N O P Q R l1 l2 H1 H2 H3 HMl2 HPl1 HQl1 HRl1.\nunfold dist3 in H2,H3.\nintuition.\nassert (~Incid N l2).\nintro HNl2.\ngeneralize (a2_unique l1 l2 M N H1 H HMl2 H5 HNl2); intros H'.\nsubst M.\napply H3; trivial.\nassert (~Incid O l2).\nintro HOl2.\ngeneralize (a2_unique l1 l2 M O H1 H HMl2 H10 HOl2); intros H'.\nsubst M.\napply H4; trivial.\nexists N.\nexists R.\nexists Q.\nexists O.\nintros l.\nsplit.\nunfold dist4.\nsplit.\nintros HNR; subst N; tauto.\nsplit.\nintros HNR; subst N; tauto.\nsplit.\nassumption.\nsplit.\nintros HRQ; apply H11.\nsymmetry;trivial.\nsplit.\nintros HRO; subst R.\ntauto.\nintros HQO; subst Q.\ntauto.\nsplit.\nintros (Hnew1,Hnew2).  \nsplit.\nintros HQl.\ngeneralize (a1_unique Q R l l2 H11 HQl Hnew2 H7 H12); intros H'.\nsubst l.\ntauto.\nintros HOl.\ngeneralize (a1_unique N O l l1 H9 Hnew1 HOl H5 H10); intros H'. \nsubst l.\ntauto.\nsplit.\nintros (Hnew1, Hnew2).\nsplit.\nintros HRl.\ngeneralize (a1_unique Q R l l2 H11 Hnew2 HRl H7 H12); intros H'.\nsubst l.\ntauto.\nintros HOl.\ngeneralize (a1_unique N O l l1 H9 Hnew1 HOl H5 H10); intros H'. \nsubst l.\ntauto.\nsplit.\nintros (Hnew1, Hnew2).\ngeneralize (a1_unique N O l l1 H9 Hnew1 Hnew2 H5 H10); intros H'. \nsubst l.\ntauto.\nsplit.\nintros (Hnew1, Hnew2).\ngeneralize (a1_unique Q R l l2 H11 Hnew1 Hnew2 H7 H12); intros H'.\nsubst l.\ntauto.\nsplit.\nintros (Hnew1, Hnew2).\nsplit.\nintros HQl.\ngeneralize (a1_unique Q R l l2 H11 HQl Hnew2 H7 H12); intros H'.\nsubst l.\ntauto.\nintros HNl.\ngeneralize (a1_unique N O l l1 H9 HNl Hnew1 H5 H10); intros H'. \nsubst l.\ntauto.\nintros (Hnew1, Hnew2).\nsplit.\nintros HRl.\ngeneralize (a1_unique Q R l l2 H11 Hnew1 HRl H7 H12); intros H'.\nsubst l.\ntauto.\nintros HNl.\ngeneralize (a1_unique N O l l1 H9 HNl Hnew2 H5 H10); intros H'. \nsubst l.\ntauto.\nQed.\n\n(** case2 with l1 and l2 inverted *)\nLemma case3 : forall M N O P Q R : Point, forall l1 l2 : Line, \n  l1 <> l2 -> \n  dist3 M N O /\\ Incid M l1 /\\ Incid N l1 /\\ Incid O l1 ->\n  dist3 P Q R /\\ Incid P l2 /\\ Incid Q l2 /\\ Incid R l2 ->\n  Incid P l1 -> ~Incid M l2 -> ~Incid N l2 -> ~Incid O l2 -> \n  {A : Point & {B : Point & {C : Point & {D : Point |\n          forall l : Line,\n            dist4 A B C D /\\\n            (Incid A l /\\ Incid B l -> ~ Incid C l /\\ ~ Incid D l) /\\\n            (Incid A l /\\ Incid C l -> ~ Incid B l /\\ ~ Incid D l) /\\\n            (Incid A l /\\ Incid D l -> ~ Incid C l /\\ ~ Incid B l) /\\\n            (Incid C l /\\ Incid B l -> ~ Incid A l /\\ ~ Incid D l) /\\\n            (Incid D l /\\ Incid B l -> ~ Incid C l /\\ ~ Incid A l) /\\\n            (Incid C l /\\ Incid D l -> ~ Incid B l /\\ ~ Incid A l)}}}}.\nintros M N O P Q R l1 l2 H1 H2 H3 HPl1 HMl2 HNl2 HOl2.\neapply case2 with (l1:=l2) (l2:=l1);eauto.\nQed.\n\n(** none of M, N, O, P, Q, and R are at the meeting point of l1 and l2 *)\nLemma case4 : forall M N O P Q R : Point, forall l1 l2 : Line, \n  l1 <> l2 -> \n  dist3 M N O /\\ Incid M l1 /\\ Incid N l1 /\\ Incid O l1 ->\n  dist3 P Q R /\\ Incid P l2 /\\ Incid Q l2 /\\ Incid R l2 ->\n  ~Incid P l1 -> ~Incid Q l1 -> ~Incid R l1 -> ~Incid M l2 -> ~Incid N l2 -> ~Incid O l2 -> \n  {A : Point & {B : Point & {C : Point & {D : Point |\n          forall l : Line,\n            dist4 A B C D /\\\n            (Incid A l /\\ Incid B l -> ~ Incid C l /\\ ~ Incid D l) /\\\n            (Incid A l /\\ Incid C l -> ~ Incid B l /\\ ~ Incid D l) /\\\n            (Incid A l /\\ Incid D l -> ~ Incid C l /\\ ~ Incid B l) /\\\n            (Incid C l /\\ Incid B l -> ~ Incid A l /\\ ~ Incid D l) /\\\n            (Incid D l /\\ Incid B l -> ~ Incid C l /\\ ~ Incid A l) /\\\n            (Incid C l /\\ Incid D l -> ~ Incid B l /\\ ~ Incid A l)}}}}.\nintros M N O P Q R l1 l2 H1 H2 H3 HPl1 HQl1 HRl1 HMl2 HNl2 HOl2.\nunfold dist3 in H2,H3.\nintuition.\nexists N.\nexists R.\nexists Q.\nexists O.\nintros l.\nsplit.\nunfold dist4.\nsplit.\nintros HNR; subst N; tauto.\nsplit.\nintros HNR; subst N; tauto.\nsplit.\nassumption.\nsplit.\nintros HRQ; apply H11.\nsymmetry;trivial.\nsplit.\nintros HRO; subst R.\ntauto.\nintros HQO; subst Q.\ntauto.\nsplit.\nintros (Hnew1,Hnew2).  \nsplit.\nintros HQl.\ngeneralize (a1_unique Q R l l2 H11 HQl Hnew2 H7 H12); intros H'.\nsubst l.\ntauto.\nintros HOl.\ngeneralize (a1_unique N O l l1 H9 Hnew1 HOl H5 H10); intros H'. \nsubst l.\ntauto.\nsplit.\nintros (Hnew1, Hnew2).\nsplit.\nintros HRl.\ngeneralize (a1_unique Q R l l2 H11 Hnew2 HRl H7 H12); intros H'.\nsubst l.\ntauto.\nintros HOl.\ngeneralize (a1_unique N O l l1 H9 Hnew1 HOl H5 H10); intros H'. \nsubst l.\ntauto.\nsplit.\nintros (Hnew1, Hnew2).\ngeneralize (a1_unique N O l l1 H9 Hnew1 Hnew2 H5 H10); intros H'. \nsubst l.\ntauto.\nsplit.\nintros (Hnew1, Hnew2).\ngeneralize (a1_unique Q R l l2 H11 Hnew1 Hnew2 H7 H12); intros H'.\nsubst l.\ntauto.\nsplit.\nintros (Hnew1, Hnew2).\nsplit.\nintros HQl.\ngeneralize (a1_unique Q R l l2 H11 HQl Hnew2 H7 H12); intros H'.\nsubst l.\ntauto.\nintros HNl.\ngeneralize (a1_unique N O l l1 H9 HNl Hnew1 H5 H10); intros H'. \nsubst l.\ntauto.\nintros (Hnew1, Hnew2).\nsplit.\nintros HRl.\ngeneralize (a1_unique Q R l l2 H11 Hnew1 HRl H7 H12); intros H'.\nsubst l.\ntauto.\nintros HNl.\ngeneralize (a1_unique N O l l1 H9 HNl Hnew2 H5 H10); intros H'. \nsubst l.\ntauto.\nQed.\n\nDefinition a3 : {A:Point & {B :Point & {C:Point & {D :Point |\n  (forall l :Line, dist4 A B C D/\\ \n    (Incid A l /\\ Incid B l -> ~Incid C l /\\ ~Incid D l)\n    /\\ (Incid A l /\\ Incid C l -> ~Incid B l /\\ ~Incid D l)\n    /\\  (Incid A l /\\ Incid D l -> ~Incid C l /\\ ~Incid B l)\n    /\\  (Incid C l /\\ Incid B l -> ~Incid A l /\\ ~Incid D l)\n    /\\ (Incid D l /\\ Incid B l -> ~Incid C l /\\ ~Incid A l)\n    /\\  (Incid C l /\\ Incid D l -> ~Incid B l /\\ ~Incid A l))}}}}.\ngeneralize M.a3_1 M.a3_2.\nintros H1 H2.\nelim H2; clear H2; intros l1 Hl1.\nelim Hl1; clear Hl1; intros l2 HdistL.\ngeneralize (H1 l1); intros Hl1.\ngeneralize (H1 l2); intros Hl2.\nclear H1.\nelim Hl1; clear Hl1; intros A1 HA1.\nelim HA1; clear HA1; intros B1 HB1.\nelim HB1; clear HB1; intros C1 H1.\nelim Hl2; clear Hl2; intros A2 HA2.\nelim HA2; clear HA2; intros B2 HB2.\nelim HB2; clear HB2; intros C2 H2.\nelim (incid_dec A1 l2).\nelim (incid_dec A2 l1).\nintros Ha Hb.\neapply case1;eauto.\nintros Ha Hb.\nelim (incid_dec B1 l2).\nintros Hc.\nassert (~Incid B1 l2).\nintuition.\ngeneralize (a2_unique l1 l2 A1 B1 HdistL H2 Hb H4 Hc); intros H'.\nsubst A1.\nunfold dist3 in H0.\ntauto.\ntauto.\nintros Hc.\nelim (incid_dec C1 l2).\nintros Hd.\nassert (~Incid C1 l2).\nintuition.\ngeneralize (a2_unique l1 l2 A1 C1 HdistL H2 Hb H7 Hd); intros H'.\nsubst A1.\nunfold dist3 in H0.\ntauto.\ntauto.\nintros Hd.\nelim (incid_dec B2 l1).\nintros H.\neapply case1 with (M:=A1) (N:=B1) (O:=C1) (P:=B2) (Q:=A2) (R:=C2);eauto;unfold dist3 in *;intuition.\nintros He.\nelim (incid_dec C2 l1).\nintros H.\neapply case1 with (M:=A1) (N:=B1) (O:=C1) (P:=C2) (Q:=A2) (R:=B2);eauto;unfold dist3 in *;intuition.\nintros Hf.\neapply case2;eauto.\nintros Ha.\nelim (incid_dec B1 l2).\nintros Hb.\nelim (incid_dec A2 l1).\nintros Hc.\neapply case1 with (M:=B1) (N:=A1) (O:=C1) (P:=A2) (Q:=B2) (R:=C2);eauto;unfold dist3 in *;intuition.\nintros Hc.\nelim (incid_dec B2 l1).\nintros Hd.\neapply case1 with (M:=B1) (N:=A1) (O:=C1) (P:=B2) (Q:=A2) (R:=C2);eauto;unfold dist3 in *;intuition.\nintros He.\nelim (incid_dec C2 l1).\nintros Hf.\neapply case1 with (M:=B1) (N:=A1) (O:=C1) (P:=C2) (Q:=A2) (R:=B2);eauto;unfold dist3 in *;intuition.\nintros Hf.\neapply case2 with (M:=B1) (N:=A1) (O:=C1) (P:=A2) (Q:=B2) (R:=C2);eauto;unfold dist3 in *;intuition.\nintros Hb.\nelim (incid_dec C1 l2).\nintros Hc.\nelim (incid_dec A2 l1).\nintros Hd.\neapply case1 with (M:=C1) (N:=A1) (O:=B1) (P:=A2) (Q:=B2) (R:=C2);eauto;unfold dist3 in *;intuition.\nintros Hd.\nelim (incid_dec B2 l1).\nintros He.\neapply case1 with (M:=C1) (N:=A1) (O:=B1) (P:=B2) (Q:=A2) (R:=C2);eauto;unfold dist3 in *;intuition.\nintros He.\nelim (incid_dec C2 l1).\nintros Hf.\neapply case1 with (M:=C1) (N:=A1) (O:=B1) (P:=C2) (Q:=A2) (R:=B2);eauto;unfold dist3 in *;intuition.\nintros Hf.\neapply case2 with (M:=C1) (N:=A1) (O:=B1) (P:=A2) (Q:=B2) (R:=C2);eauto;unfold dist3 in *;intuition.\nintros Hc.\nelim (incid_dec A2 l1).\nintros Hd.\neapply case3 with (M:=A1) (N:=B1) (O:=C1) (P:=A2) (Q:=B2) (R:=C2);eauto;unfold dist3 in *;intuition.\nintros Hd.\nelim (incid_dec B2 l1).\nintros He.\neapply case3 with (M:=A1) (N:=B1) (O:=C1) (P:=B2) (Q:=A2) (R:=C2);eauto;unfold dist3 in *;intuition.\nintros He.\nelim (incid_dec C2 l1).\nintros Hf.\neapply case3 with (M:=A1) (N:=B1) (O:=C1) (P:=C2) (Q:=A2) (R:=B2);eauto;unfold dist3 in *;intuition.\nintros Hf.\neapply case4;eauto.\nQed.\n\n\nEnd back.\n", "meta": {"author": "coq-contribs", "repo": "projective-geometry", "sha": "bd3b5d752d323ee26033d07f4cc5f9ef1b96f40e", "save_path": "github-repos/coq/coq-contribs-projective-geometry", "path": "github-repos/coq/coq-contribs-projective-geometry/projective-geometry-bd3b5d752d323ee26033d07f4cc5f9ef1b96f40e/Plane/back.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.2660872841397838}}
{"text": "Require Import Coq.Program.Basics.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Program.Combinators.\n\nRequire Import FinProof.Common.\nRequire Import FinProof.CommonInstances.\nRequire Import FinProof.StateMonad2.\nRequire Import FinProof.StateMonadInstances.\nRequire Import FinProof.ProgrammingWith.\n\nRequire Import FinProof.CommonProofs.\n\nRequire Import depoolContract.SolidityNotations.\nRequire Import depoolContract.ProofEnvironment.\nRequire Import depoolContract.DePoolSpec.\n(* Require Import MultiSigWallet.Proofs.Tactics. *)\n\nRequire Import Lists.List.\nImport ListNotations.\nLocal Open Scope list_scope.\n\nLocal Open Scope struct_scope.\nLocal Open Scope Z_scope.\n\n\nModule CommonModelProofs (sm: StateMonadSig).\nExport sm.\nExisting Instance monadStateT.\nExisting Instance monadStateStateT.\n\n(*TODO: wrong module to import!*)\n\nModule DePoolSpec := DePoolSpec ProofEnvironment.XTypesSig sm.\nImport DePoolSpec.\nImport LedgerClass.\nImport SolidityNotations.\n\nLocal Open Scope solidity_scope.\n\nSet Typeclasses Iterative Deepening.\n(*Set Typeclasses Depth 1.\nSet 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\n(* more generic proofs *)\n\nLtac destructMonads := compute; destruct monadStateStateT; destruct monadStateT.\n\n\n(* Lemma requireOldM_eval_correct1: forall {S X} (b:bool) (f: StateT S  (option X)) l,\n                         b = true ->\n                         eval_state (requireOldM b f) l = eval_state f l.\nProof.\n intros. rewrite H. compute. auto.\nQed.\n\nLemma requireOldM_eval_correct2: forall {S X} (b:bool) (f: StateT S (option X)) l,\n                         b = false ->  \n                         eval_state (requireOldM b f) l = None.\nProof.\n intros. rewrite H. destructMonads. rewrite rununit. auto. \nQed.\n\nLemma requireOld_eval_correct1: forall {S X} (b:bool) (f: StateT S  X) l,\n                         b = true ->\n                         eval_state (requireOld b f) l = Some (eval_state f l).\nProof.\n intros. rewrite H. destructMonads.\n rewrite runbind. remember (run X f l). destruct p. rewrite rununit. auto.\nQed.\n\nLemma requireOld_eval_correct2: forall {S X} (b:bool) (f: StateT S  X) l,\n                         b = false ->\n                         eval_state (requireOld  b f) l = None.\nProof.\n intros. rewrite H. destructMonads. rewrite rununit. auto. \nQed.\n\nLemma requireOld_exec_correct1: forall {S X} (b:bool) (f: StateT S  X) l,\n                         b = true ->\n                         exec_state (requireOld b f) l = exec_state f l.\nProof.\n intros. rewrite H. destructMonads. \n rewrite runbind. remember (run X f l). destruct p. rewrite rununit. auto.\nQed.\n\nLemma requireOld_exec_correct2: forall {S X} (b:bool) (f: StateT S X) l,\n                         b = false ->  \n                         exec_state (requireOld b f) l = l.\nProof.\n intros. rewrite H. destructMonads. rewrite rununit. auto. \nQed.\n*)\n(* Check eval_state (do _ ← require _ _ ??; _) _. *)\nLemma requireE_eval_correct1: forall {S X E} (b:bool) (e: E) (f: StateT S (ErrorValue X E) ) l,\n                         b = true ->\n                         eval_state (do _ ← require b e ??; f) l = eval_state f l.\nProof.\n intros. rewrite H. unfold require. simpl. rewrite left_unit. simpl. auto.\nQed. \n\nLemma requireE_eval_correct2: forall {S X E} (b:bool) (e: E) (f: StateT S (ErrorValue X E)) l,\n                         b = false ->\n                         eval_state (do _ ← require b e ??; f) l = Error e.\nProof.\n intros. rewrite H. unfold require. simpl. rewrite left_unit. simpl. rewrite eval_unit. auto.\nQed. \n\nLemma requireE_eval_correct3: forall {S X E} (b:bool) (e x: E) (f: StateT S (ErrorValue X E)) l,\n                         (b = false /\\ (x = e))  \\/ (b = true /\\ eval_state f l = Error x) <->\n                         eval_state (do _ ← require b e ??; f) l = Error x.\nProof.\n intros. split. intros. inversion H. rewrite requireE_eval_correct2.\n inversion H0. congruence. inversion H0. congruence.\n inversion H0. rewrite requireE_eval_correct1. auto. auto. \n intros. destruct b. right. split. auto. rewrite requireE_eval_correct1 in H. auto.\n auto. left. rewrite requireE_eval_correct2 in H. split. auto. inversion H.  auto.\n auto.\nQed.\n\nLemma requireE_eval_correct4: forall {S X E} (b:bool) e (v: X) (f: StateT S (ErrorValue X E)) l,\n                         (b = true /\\ eval_state f l = Value v) <->\n                         eval_state (do _ ← require b e ??; f) l = Value v.\nProof.\n intros. split. intros. inversion H.\n rewrite requireE_eval_correct1; auto.\n intros. split. destruct b. auto.\n rewrite requireE_eval_correct2 in H. inversion H. auto.\n destruct b. rewrite requireE_eval_correct1 in H. auto. auto.\n rewrite requireE_eval_correct2 in H. inversion H. auto.\nQed.\n\nLemma require_eval_correct1: forall {S X E} (b:bool) (e: E) (f: StateT S X) l,\n                         b = true ->\n                         eval_state (do _ ← require b e ?; f) l = Value (eval_state f l).\nProof.\n intros. rewrite H. unfold require. simpl. rewrite left_unit. simpl. \n rewrite eval_bind2. rewrite eval_unit. \n auto.\nQed. \n\n\nLemma require_eval_correct2: forall {S X E} (b:bool) (e: E) (f: StateT S X) l,\n                         b = false <->\n                         eval_state (do _ ← require b e ?; f) l = Error e.\nProof.\n intros. split; intros. rewrite H.\n unfold require. simpl. rewrite left_unit. simpl. rewrite eval_unit. auto.\n intros. destruct b. rewrite require_eval_correct1 in H. inversion H.\n auto. auto.\nQed.\n\nLemma require_eval_correct2': forall {S X E} (b:bool) (x e: E) (f: StateT S X) l,\n                         b = false /\\ x = e <->\n                         eval_state (do _ ← require b e ?; f) l = Error x .\nProof.\n intros. split; intros. inversion_clear H.\n rewrite (require_eval_correct2 (S:=S) (X:=X) (E:=E)) in H0.\n rewrite H0. congruence. remember b. destruct b0. \n rewrite require_eval_correct1 in H.\n discriminate. auto. split. auto.\n rewrite Heqb0 in H. symmetry in Heqb0.\n rewrite (require_eval_correct2 (S:=S) (X:=X) (E:=E)) in Heqb0.\n rewrite H in Heqb0. congruence.\nQed.\n \n\nLemma require_exec_correct1: forall {S X E} (b:bool) (e: E) (f: StateT S X) l,\n                            b = true ->\n                            exec_state (do _ ← require b e ?; f) l = exec_state f l.\nProof.\n intros. rewrite H.\n unfold require. simpl. rewrite left_unit. simpl. \n  rewrite exec_bind. rewrite exec_unit. auto. \nQed.\n\nLemma require_exec_correct2: forall {S X E} (b:bool) (e: E) (f: StateT S X) l,\n                         b = false ->  \n                         exec_state (do _ ← require b e ?; f) l = l.\nProof.\n intros. rewrite H.\n unfold require. simpl. rewrite left_unit. simpl. rewrite exec_unit. auto.\nQed.\n\n\nLemma requireE_exec_correct1: forall {S X E} (b:bool) (e: E) (f: StateT S (ErrorValue X E)) (l:S),\n                         b = false ->  \n                         exec_state (do _ ← require b e ??; f) l = l.\nProof.\n intros. rewrite H.\n unfold require. simpl. rewrite left_unit. simpl. rewrite exec_unit. auto.\nQed.\n\nLemma requireE_exec_correct2: forall {S X E} (b:bool) (e: E) (f: StateT S (ErrorValue X E)) l,\n                            b = true ->\n                            exec_state (do _ ← require b e ??; f) l = exec_state f l.\nProof.\n intros. rewrite H.\n unfold require. simpl. rewrite left_unit. simpl. auto.\nQed.\n\n\nLemma errorBindCorrect1: forall (S X Y E: Type) (f:StateT S (ErrorValue X E)) \n                                      (g: X -> StateT S Y) l n, \neval_state f l = Error n ->\neval_state (do x ← f ?; g x) l = Error n.\nProof.\n intros. rewrite eval_bind2.\n rewrite H. simpl.\n rewrite eval_unit. auto.\nQed.\n\nLemma errorBindCorrect2: forall S X Y E (f:StateT S (ErrorValue X E)) \n                                (g: X -> StateT S Y) l x, \neval_state f l = Value x ->\neval_state (do x ← f ?; g x) l = Value (eval_state (g x) (exec_state f l)).\nProof.\n intros. rewrite eval_bind2.\n rewrite H. simpl.\n rewrite eval_bind2. rewrite eval_unit. auto.\nQed.\n\nLemma errorBindCorrect3: forall S X Y E (f:StateT S (ErrorValue X E)) \n                                      (g: X -> StateT S (ErrorValue Y E)) l n, \neval_state f l = Error n ->\neval_state (do x ← f ??; g x) l = Error n.\nProof.\n intros. rewrite eval_bind2.\n rewrite H. simpl. rewrite eval_unit. auto.\nQed.\n\nLemma errorBindCorrect4: forall S X Y E (f:StateT S (ErrorValue X E)) \n                                (g: X -> StateT S (ErrorValue Y E)) l x, \neval_state f l = Value x ->\neval_state (do x ← f ??; g x) l = eval_state (g x) (exec_state f l).\nProof.\n intros. rewrite eval_bind2.\n rewrite H. simpl. auto.\nQed.\n\nLemma errorBindCorrect5: forall S X Y E (f:StateT S (ErrorValue X E)) \n                                (g: X -> StateT S (ErrorValue Y E)) l x, \neval_state f l = Value x ->\nexec_state (do x ← f ??; g x) l = exec_state (g x) (exec_state f l).\nProof.\n intros. rewrite exec_bind.\n rewrite H. simpl. auto.\nQed.\n\nLemma errorBindCorrect3': forall S X Y E (f:StateT S (ErrorValue X E)) \n                                      (g: X -> StateT S (ErrorValue Y E)) l n, \neval_state (do x ← f ??; g x) l = Error n <->\n(eval_state f l = Error n) \\/\n(exists v, eval_state f l = Value v /\\ eval_state (g v) (exec_state f l) = Error n).\nProof.\n split. intros. \nrewrite eval_bind2 in H.\n remember (eval_state f l).\n  destruct e. unfold xErrorMapDefaultF in H.\n unfold errorMapDefaultF in H. simpl in H. rewrite eval_unit in H.\n  inversion H. left. auto.\n right.  exists x. split; auto.\n intros.\n inversion_clear H. apply errorBindCorrect3. apply H0.\n inversion_clear H0. inversion_clear H.\n rewrite <- H1.\n apply errorBindCorrect4. apply H0.\nQed.\n\n\n(*TODO: define notModifedState by equalRelativeState*)\nDefinition notModifiedState {S X Y} (f: StateT S X) (m: StateT S Y) := forall s, \n                        eval_state f s = eval_state f (exec_state m s).\n\nLemma notModifiedState_correct: forall {S X Y} (f: StateT S X) (m: StateT S Y) s,\n                 notModifiedState f m ->\n                 eval_state f s = eval_state f (exec_state m s).\nProof. auto. Qed.\n\nDefinition equalRelativeState {S X Y1 Y2} (f: StateT S X) (m1: StateT S Y1) (m2: StateT S Y2) := forall s, \n                        eval_state f (exec_state m1 s) = eval_state f (exec_state m2 s).\n\nDefinition commuteRelativeState {S X Y1 Y2} (f: StateT S X) (m1: StateT S Y1) (m2: StateT S Y2) := forall s, \n                        eval_state f (exec_state (m1 >> m2)  s) = eval_state f (exec_state (m2 >> m1) s).\n\nLemma equalRelativeState_correct: forall {S X Y1 Y2} (f: StateT S X) (m1: StateT S Y1) (m2: StateT S Y2) s,\n                 equalRelativeState f m1 m2 ->\n                 eval_state f (exec_state m1 s) = eval_state f (exec_state m2 s).\nProof. auto. Qed.\n\nLemma equalRelativeState_sym: forall {S X Y1 Y2} (f: StateT S X) (m1: StateT S Y1) (m2: StateT S Y2),\n                 equalRelativeState f m1 m2 -> equalRelativeState f m2 m1.\nProof.\n intros. unfold equalRelativeState. unfold equalRelativeState in H.\n intros. auto.\n Qed.\n\nLemma equalStatesRight: forall {S  X Y Y1} (f: StateT S X) \n                       (m1: StateT S Y1) (m: StateT S Y),\n                       notModifiedState f m ->\n                       equalRelativeState f (m1 >> m) m1.\nProof.\n intros. unfold equalRelativeState.\n intros. rewrite ?exec_bind'.\n unfold  notModifiedState in H.\n rewrite <- H. auto.\nQed.\n\nLemma equalStatesLeft: forall {S  X Y Y1} (f: StateT S X) \n                       (m1: StateT S Y1) (m: StateT S Y) s,\n                       equalRelativeState f m1 (m >> m1) ->\n                        eval_state f (exec_state m1 s) = \n                        eval_state f (exec_state m1 (exec_state m s)).\nProof.\n intros. rewrite (equalRelativeState_correct f  m1 (m>>m1)).\n rewrite exec_bind'. auto. apply H.\n Qed.\n\nLemma equalRelativeState_notModified: forall {S  X Y} (f: StateT S X) (m: StateT S Y),\n                         notModifiedState f m <-> equalRelativeState f get m.\nProof.\n intros. split. unfold notModifiedState. unfold equalRelativeState.\n intros. unfold exec_state. rewrite runget.\n simpl. rewrite H. unfold exec_state. auto.\n unfold notModifiedState. unfold equalRelativeState.\n intros. unfold exec_state in H. unfold exec_state.\n rewrite <- H. rewrite runget. simpl. auto.\nQed.\n\nLemma notModifiedLeft: forall {S  X Y} (f: StateT S X) \n                       (m1: StateT S Y) (m2: StateT S Y) s,\n               equalRelativeState f m2 (m1 >> m2) -> \n               eval_state f (exec_state (m1 >> m2) s) = eval_state f (exec_state m2 s).\nProof.\n  intros. rewrite exec_bind'.\n  unfold equalRelativeState in H.\n  remember (H s). clear Heqe.\n  rewrite exec_bind' in e.  auto.\n  Qed.\n(*\nLemma requireOldNotModifiedState {S  X} (f: StateT S X) (m: StateT S True) (b:bool): \n                              notModifiedState f m -> \n                              notModifiedState f (requireOld b m).\nProof.\n intros. destruct b. unfold notModifiedState. intros.\n rewrite requireOld_exec_correct1. apply H. auto.\n unfold notModifiedState. intros.\n rewrite requireOld_exec_correct2. auto. auto.\n Qed.\n*)\nLemma notModifiedRequire {S E X} (f: StateT S X) (m: StateT S True) (b:bool) (e: E): \n                              notModifiedState f m -> \n                              notModifiedState f (do _ ← require b e ?; m).\nProof.\n intros. destruct b. unfold notModifiedState. intros.\n rewrite require_exec_correct1. apply H. auto.\n unfold notModifiedState. intros.\n rewrite require_exec_correct2. auto. auto.\n Qed.\n\nLemma notModifiedBind_: forall {S  X Y1 Y2} (f: StateT S X) (m1: StateT S Y1) (m2: StateT S Y2),\n                       notModifiedState f m1 ->\n                       notModifiedState f m2 ->\n                       notModifiedState f (m1 >> m2).\nProof.\n intros. unfold notModifiedState in H. \n unfold notModifiedState in H0. unfold notModifiedState.\n intros. rewrite exec_bind'. rewrite <-  H0.\n auto.\nQed.\n\nLemma notModifiedBind: forall {S  X Y1 Y2} (f: StateT S X) (m1: StateT S Y1) (m2: Y1 -> StateT S Y2),\n                       notModifiedState f m1 ->\n                       (forall y, notModifiedState f (m2 y)) ->\n                       notModifiedState f (m1 >>= m2).\nProof.\n intros. unfold notModifiedState in H. \n unfold notModifiedState in H0. unfold notModifiedState.\n intros. rewrite exec_bind. rewrite <-  H0.\n auto.\nQed. \n\n\nLemma equalRelativeBind: forall {S  X Y1 Y2 U T} (f: StateT S X)  \n                                (m1: StateT S Y1) (m2: Y1 -> StateT S Y2) (h: StateT S T) (g: StateT S U),\n                       equalRelativeState f h g ->\n                       equalRelativeState f (m1 >> h) g ->\n                       (forall y, equalRelativeState f (m2 y >> h) g) ->\n                       equalRelativeState f ((m1 >>= m2) >> h) g.\nProof.\n intros. \n unfold equalRelativeState in H. \n unfold equalRelativeState in H0. \n unfold equalRelativeState.\n unfold equalRelativeState in H1. intros.\n rewrite exec_bind'. rewrite exec_bind.\n remember (H1 (eval_state m1 s) (exec_state m1 s)).\n clear Heqe. rewrite exec_bind' in e.\n rewrite e. rewrite <- ?H.\n rewrite <- exec_bind'. rewrite H0.\n rewrite H. auto.\n Qed.\n\n\nLemma equalRelativeBind_: forall {S  X Y1 Y2 U T} (f: StateT S X)  \n                                (m1: StateT S Y1) (m2:StateT S Y2) (h: StateT S T) (g: StateT S U),\n                       equalRelativeState f h g ->\n                       equalRelativeState f (m1 >> h) g ->\n                       equalRelativeState f (m2 >> h) g ->\n                       equalRelativeState f (m1 >> m2 >> h) g.\nProof.\n intros. unfold bind_. apply equalRelativeBind.\n auto. auto. intros. auto.\nQed.\n\n(*FIXME: find the less weak conditions*)\nLemma equalRelativeBind_': forall {S  X Y1 Y2 T} (f: StateT S X)  \n                                (m1: StateT S Y1) (m2:StateT S Y2) (h: Y2 -> StateT S T),\n                       notModifiedState m2 m1 ->\n                       commuteRelativeState get m1 m2 -> \n                       equalRelativeState f (m1 >> m2 >>= h) (m2 >>= (fun x => m1 >> h x)).\nProof.\n intros. \n intros. unfold commuteRelativeState in H.\n unfold equalRelativeState. intros. unfold bind_.\n rewrite ?exec_bind. rewrite eval_bind2.\n rewrite <- ?exec_bind'. rewrite <- H.\n rewrite <- ?bind_assoc_. \n rewrite exec_bind'. symmetry. rewrite exec_bind'.\n unfold commuteRelativeState in H0.\n remember (H0 s). unfold eval_state in e. clear Heqe.\n rewrite ?runget in e. simpl in e. rewrite e. auto.\nQed.\n\n\nLemma notModifiedFold: forall {S  X A B} \n                              (f: StateT S X) (m: B -> StateT S A) (l:list B) (a0:StateT S A),\n                       notModifiedState f a0 ->\n                       (forall (x:B), notModifiedState f (m x)) -> \n                       notModifiedState f (fold_left (fun a i => a >> m i) l a0).\nProof.\n intros. generalize dependent a0. induction l;intros. simpl. auto.\n simpl. apply IHl. apply notModifiedBind_. auto. auto.\n Qed. \n\nLemma notModifiedUnit: forall {S  X A} \n                               (f: StateT S X) (a: A),\n                       notModifiedState f (return! a).\nProof.\n intros. destructMonads.\n intros. rewrite rununit. auto.\nQed.\n\nLemma notModifiedFold2: forall {S  X A B} \n                               (f: StateT S X) (m: (bool*A)%type -> B -> StateT S (bool*A)%type) \n                               (l:list B) (a0: StateT S (bool * A)%type),\n                       notModifiedState f a0 -> \n                       (forall p (x:B), notModifiedState f (m p x)) -> \n                       notModifiedState f (fold_left (fun (a: StateT S (bool * A)%type) (i:B) => do p ← a;\n                                                        if (fst p:bool) then return! p else (m p i)) l a0).\nProof.\n intros. generalize dependent a0. induction l;intros. simpl. auto.\n simpl. apply IHl. apply notModifiedBind. auto. intros. \n destruct (fst y). apply notModifiedUnit. auto.\n Qed.\n\nLemma notModifiedEFoldLeftBreakable: forall {S X A B}\n                               (f: StateT S  X) (m: B -> StateT S  (bool*A)%type) \n                               (l:list B) (a0: A),\n                       (forall (x:B), notModifiedState f (m x)) -> \n                       notModifiedState f (listEFoldLeftBreakableM m l a0).\nProof.\n intros. unfold listEFoldLeftBreakableM. \n apply notModifiedFold2. apply notModifiedUnit. \n auto. \nQed.\n\n\nLemma notModifiedFold': forall {S  X A B} \n                              (f: StateT S X) (m: B -> StateT S A) (l:list B) (a0:StateT S A),\n                       notModifiedState f a0 ->\n                       (forall (x:B), notModifiedState f (a0 >> m x)) ->\n                       (forall (x y:B), notModifiedState f (m x >> m y)) -> \n                       notModifiedState f (fold_left (fun a i => a >> m i) l a0).\nProof.\n intros. generalize dependent a0. induction l; intros. simpl. auto.\n simpl. apply IHl. auto. intros. rewrite bind_assoc_. \n apply notModifiedBind_. auto. auto.\n Qed.\n\n\nLemma notModifiedFold'': forall {S  X A B} \n                              (f: StateT S X) (m: B -> StateT S A) (l:list B) (a0:StateT S A),\n                       notModifiedState f a0 ->\n                       (forall (x:B), notModifiedState f (a0 >> m x)) ->\n                       (forall (x y:B) s, eval_state f (exec_state (m x >> m y) s) = eval_state f (exec_state (m x) s)\\/\n                                          eval_state f (exec_state (m x >> m y) s) = eval_state f (exec_state (m y) s)) -> \n                       notModifiedState f (fold_left (fun a i => a >> m i) l a0).\nProof.\n intros. generalize dependent a0. induction l; intros. simpl. auto.\n simpl. apply IHl. auto. intros.\n rewrite bind_assoc_. unfold notModifiedState. intros.\n rewrite exec_bind'. \n remember (H1 a x (exec_state a0 s)). clear Heqo. clear H1. \n inversion o. rewrite H1. unfold notModifiedState in H0.\n rewrite H0 with (x:=a). rewrite exec_bind'. auto.\n rewrite H1. unfold notModifiedState in H0.\n rewrite H0 with (x:=x). rewrite exec_bind'. auto.\nQed.\n\nLemma equalRelativeFold: forall {S  X Y T A B} \n                              (f: StateT S X) (g: StateT S Y) (h: StateT S T) (m: B -> StateT S A) (l:list B) (a0:StateT S A),\n                       equalRelativeState f h g -> \n                       equalRelativeState f (a0 >> h) g ->\n                       (forall (x:B), equalRelativeState f (m x >> h) g) -> \n                       equalRelativeState f ((fold_left (fun a i => a >> m i) l a0) >> h) g.\nProof.\n intros. generalize dependent a0. induction l;intros. simpl. auto.\n simpl. apply IHl. apply equalRelativeBind_. auto. auto. auto. \n Qed.\n\nLemma foldStateToAccumulator: forall {S  X Y A B} \n                              (f: StateT S X) (m: B -> StateT S A) (l:list B) (a0:StateT S A) (a: StateT S Y) (s:S),\n                      eval_state f (exec_state (fold_left (fun a i => a >> m i) l a0) (exec_state a s)) = \n                      eval_state f (exec_state (fold_left (fun a i => a >> m i) l (a >> a0)) s).\nProof.\n intros. rewrite <- exec_bind'.\n generalize dependent a0. induction l; intros. simpl. auto.\n simpl. rewrite IHl. rewrite bind_assoc_. auto.\nQed.\n\nLemma notModifiedFoldWithProp: \n                      forall {S X A B} \n                      (f: StateT S X) (m: B -> StateT S A) (l:list B) \n                      (a0: StateT S A) (P: StateT S Prop),\n                      notModifiedState f a0 ->\n                      (forall s i, (eval_state P s: Prop) -> (eval_state P (exec_state (m i) s)): Prop) ->\n                      (forall s, eval_state P (exec_state a0 s) : Prop) -> \n                      (forall s i, (eval_state P s: Prop) ->\n                      eval_state f (exec_state (m i) s) = eval_state f s) ->\n                       notModifiedState f (fold_left (fun a i => a >> m i) l a0).\nProof.\n intros. generalize dependent a0. induction l; intros.\n\n simpl. auto.\n simpl. apply IHl.\n unfold notModifiedState.\n intros. rewrite exec_bind'.\n rewrite H2. auto. auto.\n intros. rewrite exec_bind'.\n apply H0. auto.\nQed.\n\n(* a > 0 -> a + 1 > 0\na >? 0 = true  -> a + 1 >?0 = true   *)\n\nLemma notModifiedFoldWithBool: \n                      forall {S X A B} \n                      (f: StateT S X) (m: B -> StateT S A) (l:list B) \n                      (a0: StateT S A) (P: StateT S bool),\n                      notModifiedState f a0 ->\n                      (forall s i, (eval_state P s = true) -> (eval_state P (exec_state (m i) s)) = true) ->\n                      (forall s, eval_state P (exec_state a0 s) = true) -> \n                      (forall s i, (eval_state P s = true) ->\n                      eval_state f (exec_state (m i) s) = eval_state f s) ->\n                       notModifiedState f (fold_left (fun a i => a >> m i) l a0).\nProof.\n intros. generalize dependent a0. induction l; intros.\n\n simpl. auto.\n simpl. apply IHl.\n unfold notModifiedState.\n intros. rewrite exec_bind'.\n rewrite H2. auto. auto.\n intros. rewrite exec_bind'.\n apply H0. auto.\nQed.\n\nLemma notModifiedFoldWithBoolWeak: \n                      forall {S X A B} \n                      (f: StateT S X) (m: B -> StateT S A) (l:list B) \n                      (a0: StateT S A) (P: StateT S bool) s,\n                      eval_state f (exec_state a0 s) =  eval_state f s ->\n                      eval_state P (exec_state a0 s) =  true -> \n                      (forall s i, (eval_state P s = true) -> (eval_state P (exec_state (m i) s)) = true) ->\n                      (forall s i, (eval_state P s = true) ->\n                      eval_state f (exec_state (m i) s) = eval_state f s) ->\n                       eval_state f (exec_state (fold_left (fun a i => a >> m i) l a0) s) = eval_state f s.\nProof.\n intros. generalize dependent a0. induction l; intros.\n\n simpl. apply H.\n simpl. apply IHl.\n rewrite exec_bind'.\n rewrite H2. apply H. apply H0. rewrite exec_bind'.\n rewrite H1. auto. apply H0.\nQed.\n\nLemma foldExecConj: forall {S X K} (s: S) (a0: StateT S X)\n                           (f: K -> StateT S X) (l: list K) (x: K),\nexec_state (fold_left (fun a0 (i : K) => a0 >> f i) (l ++ [ x ]) a0) s = \nexec_state (f x) \n           (exec_state (fold_left (fun a0  (i : K) => a0 >> f i) l a0) s).\nProof.\n intros. generalize dependent a0.\n induction l; intros.\n simpl. rewrite exec_bind'.\n auto.\n simpl. rewrite IHl. auto.\nQed.\n\n\nLemma foldExecEq: forall {S X K} (s: S) (a0: StateT S X)\n                           (f g: K -> StateT S X) (l: list K),\n(forall i, In i l -> f i = g i) ->\nexec_state (fold_left (fun a0 (i : K) => a0 >> f i) l a0) s = \nexec_state (fold_left (fun a0  (i : K) => a0 >> g i) l a0) s.\nProof.\n intros. generalize dependent a0. induction l; intros.\n simpl. auto.\n simpl. rewrite <- IHl.\n replace (g a) with (f a). auto.\n apply H. constructor. auto.\n intros. apply H. simpl. right. auto.\nQed.\n\n\nLemma foldExecBreakableEq: forall {S X K} (s: S) (a0: StateT S X)\n                           (f g: X -> K -> StateT S X) (l: list K),\n(forall p i, In i l -> f p i = g p i) ->\nexec_state (fold_left (fun a0 (i : K) => do p ← a0; f p i) l a0) s = \nexec_state (fold_left (fun a0  (i : K) => do p ← a0; g p i) l a0) s.\nProof.\n intros. generalize dependent a0. induction l; intros.\n simpl. auto.\n simpl. rewrite <- IHl.\n replace (do p ← a0; g p a) with (do p ← a0; f p a). auto.\n apply bind_eq. extensionality p.\n apply H. constructor. auto. intros.\n apply H. simpl. right. auto.\nQed.\n\nLemma foldEvalBreakableEq: forall {S X K} (s: S) (a0: StateT S X)\n                           (f g: X -> K -> StateT S X) (l: list K),\n(forall p i, In i l -> f p i = g p i) ->\neval_state (fold_left (fun a0 (i : K) => do p ← a0; f p i) l a0) s = \neval_state (fold_left (fun a0 (i : K) => do p ← a0; g p i) l a0) s.\nProof.\n intros. generalize dependent a0. induction l; intros.\n simpl. auto.\n simpl. rewrite <- IHl.\n replace (do p ← a0; g p a) with (do p ← a0; f p a). auto.\n apply bind_eq. extensionality p.\n apply H. constructor. auto. intros.\n apply H. simpl. right. auto.\nQed.\n\nLemma foldRunBreakableEq: forall {S X K} (s: S) (a0: StateT S X)\n                           (f g: X -> K -> StateT S X) (l: list K),\n(forall p i, In i l -> f p i = g p i) ->\nrun (fold_left (fun a0 (i : K) => do p ← a0; f p i) l a0) s = \nrun (fold_left (fun a0  (i : K) => do p ← a0; g p i) l a0) s.\nProof.\nintros.\nassert (forall X (f: StateT S X) (l: S), run f l = (eval_state f l, exec_state f l)).\nintros. unfold exec_state. unfold eval_state. \ndestruct (run f0 l0). auto.\nrewrite 2H0. rewrite (foldEvalBreakableEq s a0 f g l).\nrewrite (foldExecBreakableEq s a0 f g l). auto.\nauto. auto.\nQed.\n\nLemma fold_left_cons: forall A B (f: A -> B -> A) x l a,\nfold_left f (x::l) a = fold_left f l (f a x).\nProof.\n intros. simpl. auto.\nQed.\n\nLemma foldBreakableExec: forall S X Y y a0 (l:S) f, \nexec_state\n  (fold_left\n     (fun (a : StateT S X) (y0 : Y) => do p ← a; f p y0) y a0) l = \nexec_state\n  (a0 >> fold_left\n     (fun (a : StateT S X) (y0 : Y) => do p ← a; f p y0) y (return! (eval_state a0 l))) l.\nProof. \n intros. generalize dependent a0.\n generalize dependent l.\n induction y; intros.\n Opaque unit bind bind_. simpl.\n rewrite exec_bind'. rewrite exec_unit. auto.\n rewrite 2fold_left_cons. \n rewrite IHy. symmetry. rewrite exec_bind'.\n rewrite IHy. rewrite ?exec_bind'.\n rewrite eval_bind2. rewrite eval_unit.\n rewrite exec_unit. rewrite exec_bind.\n rewrite eval_unit. rewrite exec_unit.\n rewrite eval_bind2. rewrite exec_bind.\n auto.\n Transparent unit bind bind_.\nQed.\n\nLemma foldBreakableEval: forall S X Y y a0 (l:S) f, \neval_state\n  (fold_left\n     (fun (a : StateT S X) (y0 : Y) => do p ← a; f p y0) y a0) l = \neval_state\n  (a0 >> fold_left\n     (fun (a : StateT S X) (y0 : Y) => do p ← a; f p y0) y (return! (eval_state a0 l))) l.\nProof. \n intros. generalize dependent a0.\n generalize dependent l.\n induction y; intros.\n Opaque unit bind bind_. simpl.\n rewrite eval_bind. rewrite eval_unit. auto.\n rewrite 2fold_left_cons. \n rewrite IHy. symmetry. rewrite eval_bind.\n rewrite IHy. rewrite ?eval_bind.\n rewrite eval_bind2. rewrite eval_unit.\n rewrite exec_unit. rewrite exec_bind.\n rewrite eval_unit. rewrite exec_unit.\n rewrite eval_bind2. rewrite exec_bind.\n auto.\n Transparent unit bind bind_.\nQed.\n\nLemma foldBreakableRun: forall S X Y y a0 (l:S) f, \nrun\n  (fold_left\n     (fun (a : StateT S X) (y0 : Y) => do p ← a; f p y0) y a0) l = \nrun\n  (a0 >> fold_left\n     (fun (a : StateT S X) (y0 : Y) => do p ← a; f p y0) y (return! (eval_state a0 l))) l.\nProof. \nintros.\n assert (forall X (f: StateT S X) (l: S), run f l = (eval_state f l, exec_state f l)).\n intros. unfold exec_state. unfold eval_state. \n destruct (run f0 l0). auto.\n rewrite 2H. rewrite foldBreakableEval.\n rewrite foldBreakableExec. auto.\n Qed.\n\nLemma foldBreakableExecConj: forall {S X K} (a0: StateT S X)\n                           (f: X -> K -> StateT S X) (s: list K) (x: K) (l:S),\nexec_state\n  (fold_left\n     (fun (a : StateT S X) (y0 : K) => do p ← a; f p y0) (s ++ [x]) a0) l  = \n\nexec_state\n  (do p ← fold_left (fun (a : StateT S X) (y0 : K) => do p ← a; f p y0) s a0;\n   f p x) l.\n\nProof.\n intros. generalize dependent a0.\n induction s; intros.\n simpl. rewrite ?exec_bind. auto.\n simpl. rewrite IHs. auto.\nQed.\n\nLemma foldBreakableEvalConj: forall {S X K} (a0: StateT S X)\n                           (f: X -> K -> StateT S X) (s: list K) (x: K) (l:S),\neval_state\n  (fold_left\n     (fun (a : StateT S X) (y0 : K) => do p ← a; f p y0) (s ++ [x]) a0) l  = \n\neval_state\n  (do p ← fold_left (fun (a : StateT S X) (y0 : K) => do p ← a; f p y0) s a0;\n   f p x) l.\n\nProof.\n intros. generalize dependent a0.\n induction s; intros.\n simpl. rewrite ?exec_bind. auto.\n simpl. rewrite IHs. auto.\nQed.\n\nLemma foldBreakableRunConj: forall {S X K} (a0: StateT S X)\n                           (f: X -> K -> StateT S X) (s: list K) (x: K) (l:S),\nrun (fold_left\n        (fun (a : StateT S X) (y0 : K) => do p ← a; f p y0) (s ++ [x]) a0) l  = \nrun\n(do p ← fold_left (fun (a : StateT S X) (y0 : K) => do p ← a; f p y0) s a0;\n f p x) l.\nProof.  \n intros.\n assert (forall X (f: StateT S X) (l: S), run f l = (eval_state f l, exec_state f l)).\n intros. unfold exec_state. unfold eval_state. \n destruct (run f0 l0). auto.\n rewrite 2H. rewrite foldBreakableEvalConj.\n rewrite foldBreakableExecConj. auto.\n Qed.\n\n\n(* Lemma foldExec2: forall S X Y y a0 (l:S) (b: X -> bool) f, \nexec_state\n  (fold_left\n     (fun (a : StateT S X) (y0 : Y) => do p ← a; if b p then a else f y0) y a0) l = \nexec_state\n  (a0 >> fold_left\n     (fun (a : StateT S X) (y0 : Y) => do p ← a; if b p then a else f y0) y (return! (eval_state a0 l))) l.\nProof. \n intros. generalize dependent a0.\n generalize dependent l.\n induction y; intros.\n Opaque unit bind bind_. simpl.\n rewrite exec_bind'. rewrite exec_unit. auto.\n rewrite 2fold_left_cons. \n rewrite IHy. symmetry. rewrite exec_bind'.\n rewrite IHy. rewrite ?exec_bind'.\n rewrite eval_bind2. rewrite eval_unit.\n rewrite exec_unit. rewrite ifEval.\n rewrite eval_unit. rewrite exec_bind.\n rewrite eval_unit. rewrite exec_unit.\n rewrite ifExec. rewrite exec_unit.\n rewrite eval_bind2. rewrite ifEval.\n rewrite exec_bind. rewrite ifExec.\n rewrite ?H. auto. \n\n rewrite exec_bind. rewrite eval_unit.\n rewrite exec_unit. destructIf.\n rewrite exec_unit. auto.\n auto.\n Transparent unit bind bind_.\nQed. *)\n\nLemma foldBreakableBreakExec: forall S X l a y f, \nexec_state\n  (fold_left\n     (fun (mbx : StateT S (bool * True)) (y0 : X) =>\n      do p ← mbx;\n      if (fst p: bool) then (return! p) else (f y0)) y a) l =\nif (fst (eval_state a l): bool) then exec_state a l else\nexec_state\n  (fold_left\n     (fun (mbx : StateT S (bool * True)) (y0 : X) =>\n      do p ← mbx;\n      if (fst p: bool) then (return! p) else (f y0)) y (return! (false, I))) (exec_state a l).\nProof.\n intros. remember (eval_state a l) as p.\n rewrite foldBreakableExec. rewrite exec_bind'.\n rewrite <- Heqp.\n destruct p. destruct b; unfold fst; destruct t; auto.\n generalize dependent a. induction y; intros.\n simpl. rewrite exec_unit. auto.\n rewrite fold_left_cons. rewrite foldBreakableExec.\n rewrite exec_bind'. rewrite eval_bind2.\n rewrite eval_unit. rewrite eval_unit.\n rewrite exec_bind. rewrite eval_unit.\n rewrite exec_unit. rewrite exec_unit.\n rewrite IHy. auto.\n auto.\nQed.\n\nLemma foldBreakableBreakEval: forall S X l a y f, \neval_state\n  (fold_left\n     (fun (mbx : StateT S (bool * True)) (y0 : X) =>\n      do p ← mbx;\n      if (fst p: bool) then (return! p) else (f y0)) y a) l =\nif (fst (eval_state a l): bool) then (true, I) else\neval_state\n  (fold_left\n     (fun (mbx : StateT S (bool * True)) (y0 : X) =>\n      do p ← mbx;\n      if (fst p: bool) then (return! p) else (f y0)) y (return! (false, I))) (exec_state a l).\nProof.\n intros. remember (eval_state a l) as p.\n rewrite foldBreakableEval. rewrite eval_bind.\n rewrite <- Heqp.\n destruct p. destruct b; unfold fst; destruct t; auto.\n generalize dependent a. induction y; intros.\n simpl. rewrite eval_unit. auto.\n rewrite fold_left_cons. rewrite foldBreakableEval.\n rewrite eval_bind. rewrite eval_bind2.\n rewrite eval_unit. rewrite eval_unit.\n rewrite exec_bind. rewrite eval_unit.\n rewrite exec_unit. rewrite exec_unit.\n rewrite IHy. auto.\n auto.\nQed.\n\nLemma foldBreakableBreakRun: forall S X l a y f, \nrun\n  (fold_left\n     (fun (mbx : StateT S (bool * True)) (y0 : X) =>\n      do p ← mbx;\n      if (fst p: bool) then (return! p) else (f y0)) y a) l =\nif (fst (eval_state a l): bool) then ((true, I), exec_state a l) else\nrun\n  (fold_left\n     (fun (mbx : StateT S (bool * True)) (y0 : X) =>\n      do p ← mbx;\n      if (fst p: bool) then (return! p) else (f y0)) y (return! (false, I))) (exec_state a l).\nProof.\n intros. rewrite 2run_eval_exec.\n rewrite foldBreakableBreakEval.\n rewrite foldBreakableBreakExec. \n destruct (fst (eval_state a l)); auto.\nQed.\n\n \n\n\n(* Lemma foldExecEq2: forall {S X K} (s1 s2: S) (a0: StateT S (bool*X))\n                         (f: K -> StateT S (bool*X)) (l1 l2: list K) (d: K) (t: K->K),\n(l2 = List.map t l1) ->\nexec_state a0 s1 = s1 ->\nexec_state a0 s2 = s2 -> \nfst (eval_state a0 s1) = false ->\nfst (eval_state a0 s2) = false -> \n(forall i, exec_state (f (nth i l1 d)) s1 = exec_state (f (nth i l2 d)) s2 /\\ \n           (fst (eval_state (f (nth i l1 d)) s1) = true <-> fst (eval_state (f (nth i l2 d)) s2) = true)) -> \nexec_state (fold_left (fun (a0: StateT S (bool*X)) (i : K) => do p ← a0; if (fst p: bool) then (return! p) else f i) l1 a0) s1 = \nexec_state (fold_left (fun (a0: StateT S (bool*X)) (i : K) => do p ← a0; if (fst p: bool) then (return! p) else f i) l2 a0) s2.\nProof.\n intros. generalize dependent a0. \n generalize dependent l2. induction l1; intros.\n simpl in H. rewrite H. simpl. auto.\n simpl in H. rewrite H. simpl.\n rewrite foldExec.\n rewrite exec_bind'. \n rewrite eval_bind2. \n rewrite exec_bind. rewrite H1.\n \n \nAbort.  *)\n \n\nLemma notModifiedEmbed: forall{S T X Y}`{EmbeddedType S T}\n                              (f: StateT S X) (m: T -> Y),\n                        notModifiedState f (↑ (ε m)).\nProof.\n intros. compute. intros. repeat destructMonads.\n rewrite runbind. rewrite runget.\n rewrite runembed0. rewrite runbind.\n rewrite runput. rewrite rununit. destruct H.\n rewrite injproj. auto.\n Qed.\n \n \nLemma equalStateEmbed: forall{S T X Y U W}`{EmbeddedType S T}\n                              (f: StateT S X) (m: T -> Y) (h: StateT S U) (g: StateT S W),\n                        equalRelativeState f h g -> \n                        equalRelativeState f (↑ (ε m) >> h) g.\nProof.\n intros. unfold equalRelativeState in H0. compute in H0.\n repeat destructMonads. \n intros.\n rewrite ?runbind. rewrite runget. \n rewrite runembed0. rewrite runbind.\n rewrite runput. rewrite rununit. destruct H.\n rewrite injproj.  auto.\n Qed.\n\nLemma notModifiedLifted: forall {S T X Y}`{EmbeddedType S T}\n                          (f: T -> X) (m: StateT T Y),\n                          notModifiedState (ε f) m ->\n                          notModifiedState (↑ (ε f)) (↑ m).\nProof.\n intros. unfold notModifiedState. intros.\n rewrite liftEmbeddedStateExec2.\n rewrite eval_bind. rewrite eval_embed.\n rewrite eval_lift_embed. unfold notModifiedState in H0.\n remember (H0 (projEmbed s)). clear Heqe.\n rewrite ?eval_embed in e. auto.\nQed.\n\nLemma notModifiedWithMap: forall {S T X Y A B}`{EmbeddedType S T}`{XBoolEquable bool A}`{XDefault B} \n                          (f: StateT S X) (g: B -> StateT S Y) (m: T -> listPair A B) (i:A),\n                          (forall k, notModifiedState f (g k)) -> \n                          notModifiedState f (withEmbeddedMapDefault m i g).\nProof. intros.\n  unfold withEmbeddedMapDefault.\n  apply notModifiedBind.\n  apply notModifiedEmbed. intros.\n  apply H2.\n  Qed.\n\nLemma notModifiedWithMap': forall {S T X Y A B}`{EmbeddedType S T}`{XBoolEquable bool A}`{XDefault B} \n                          (f: StateT S X) (g: B -> StateT S Y) (m: T -> listPair A B) (i:A) s,\n                          (forall k, eval_state f (exec_state (g k) s) = eval_state f s) -> \n                          eval_state f (exec_state (withEmbeddedMapDefault m i g) s) = eval_state f s.\nProof.\n intros. unfold withEmbeddedMapDefault.\n rewrite exec_bind. rewrite exec_lift_embed.\n remember (eval_state (↑ (ε m)) s).\n setoid_rewrite <- Heql. apply H2.\nQed.\n  \nLemma equalStatesWithMap: forall {S T X Y U W A B}`{EmbeddedType S T}`{XBoolEquable bool A}`{XDefault B} \n                          (f: StateT S X) (g: B -> StateT S Y) (m: T -> listPair A B) (i:A) (h: StateT S U) (r: StateT S W),\n                          equalRelativeState f h r -> \n                          (forall k, equalRelativeState f (g k >> h) r) -> \n                          equalRelativeState f (withEmbeddedMapDefault m i g >> h) r.\nProof.\n intros. unfold withEmbeddedMapDefault.\n apply equalRelativeBind. auto. apply equalStateEmbed. auto.\n intros. apply H3.\n Qed.\n\nLemma withMapOnExecWeak: forall {S T X Y U A B}`{EmbeddedType S T}`{XBoolEquable bool A}`{XDefault B} \n                              (f: StateT S X) (m: T -> listPair A B) (i:A) (s:S) (a: StateT S Y) (g: B -> StateT S U),\n                      notModifiedState (↑ (ε m)) a ->\n                      eval_state f (exec_state (withEmbeddedMapDefault m i g) (exec_state a s)) = \n                      eval_state f (exec_state (withEmbeddedMapDefault m i (fun x => a >> g x)) s).\nProof.\n intros. rewrite <- exec_bind'.\n unfold withEmbeddedMapDefault. \n apply equalRelativeState_correct. \n unfold bind_. rewrite <- bind_assoc2.\n apply equalRelativeBind_' .\n auto. unfold commuteRelativeState.\n intros. rewrite ?exec_bind'.\n unfold exec_state. unfold liftEmbeddedState. rewrite ?runbind.\n rewrite ?runget.\n rewrite ?runembed. rewrite ?injproj.\n rewrite ?runbind'. remember (run a s0). destruct p. simpl.\n rewrite ?runput. rewrite ?rununit. simpl. rewrite <- Heqp. simpl.\n auto.\nQed.\n\nLemma ifBindCommute: forall {S  X Y} (m: StateT S X) (m1: StateT S Y) (m2: StateT S Y) (b:bool),\n                       m >> (if b then m1 else m2) = if b then (m >> m1) else (m >> m2).\nProof.\n intros. destruct b; auto.\nQed.\n\n\nLemma notModifiedIf: forall {S  X Y} (f: StateT S X) (m1: StateT S Y) (m2: StateT S Y) (b:bool),\n                       notModifiedState f m1 ->\n                       notModifiedState f m2 ->\n                       notModifiedState f (if b then m1 else m2).\nProof.\n intros. unfold notModifiedState in H. \n unfold notModifiedState in H0. unfold notModifiedState.\n intros. destruct b; auto.\nQed.\n\nLemma notModifiedIf': forall {S  X Y} (f: StateT S X) (m1: StateT S Y) (m2: StateT S Y) (b:bool) s,\n                       eval_state f (exec_state m1 s) = eval_state f s ->\n                       eval_state f (exec_state m2 s) = eval_state f s ->\n                       eval_state f (exec_state (if b then m1 else m2) s) = eval_state f s.\nProof.\n intros. destruct b; auto.\nQed.\n\nLemma notModifiedBreakBind_: forall {S  X} \n                       (f: StateT S X) (m1 m2: StateT S (bool*True)%type),\n                       notModifiedState f m1 ->\n                       notModifiedState f m2 ->\n                       notModifiedState f (break_bind m1 m2).\nProof.\n intros. unfold notModifiedState in H. \n unfold notModifiedState in H0. unfold notModifiedState.\n intros. unfold break_bind.\n rewrite exec_bind. simpl. \n rewrite <- notModifiedIf. auto. auto. auto.\nQed.\n\nLemma equalRelativeIf: forall {S  X Y T U} (f: StateT S X) \n                       (m1: StateT S Y) (m2: StateT S Y) (g:StateT S T) (h: StateT S U) (b:bool),\n                       equalRelativeState f (m1 >> h) g ->\n                       equalRelativeState f (m2 >> h) g ->\n                       equalRelativeState f ((if b then (m1) else (m2)) >> h) g.\nProof.\n intros. destruct b; auto.\n Qed.\n \nLemma ifExec: forall {S X}  \n                     (m1: StateT S X) (m2: StateT S X) \n                     (s:S) (b:bool),\n              exec_state (if b then m1 else m2) s = \n              if b then (exec_state m1 s) else (exec_state m2 s).\nProof.\n intros. destruct b; auto.\nQed. \n\nLemma ifEval: forall {S X}  \n                     (m1: StateT S X) (m2: StateT S X) \n                     (s:S) (b:bool),\n              eval_state (if b then m1 else m2) s = \n              if b then (eval_state m1 s) else (eval_state m2 s).\nProof.\n intros. destruct b; auto.\nQed. \n(*\nLemma modifyMapCorrect: forall {S  X} \n                        (f: S -> listPair Z X) (l:S) (x:X) (n:Z) (i:listPair Z X -> S -> S),\n                        (forall x l, f (i x l) = x) ->\n       eval_state (do m ← ε f; \n                   return! hmapLookup Z.eqb n m)\n       (exec_state (modifyXHMap1 f i n x) l) = Some x.\nProof.\n intros. unfold modifyXHMap1.\n unfold hmapInsert. \n Opaque hmapIsMember get put run bind bind_ embed_fun unit modify exec_state.\n rewrite exec_bind.\n rewrite eval_bind2. unfold eval_state. rewrite rununit.\n rewrite runembed. \n simpl fst.\n rewrite exec_bind'. rewrite exec_unit.\n Transparent exec_state. unfold exec_state. rewrite runembed. simpl.\n Transparent modify. unfold modify. unfold compose. \n rewrite getput. rewrite runbind. rewrite runembed.\n rewrite runput. simpl.\n Transparent get put run bind bind_ embed_fun unit modify exec_state.\n rewrite H.\n Opaque hmapLookup hmapIsMember adjustListPair Z.eqb. compute.\n apply modifyMapCorrect_helper. unfold boolEquivalence. intros.\n apply intBoolEquivalence.  intros. apply zeqb_refl.\n Transparent hmapLookup hmapIsMember adjustListPair Z.eqb.\nQed.\n\n\n\nLemma modifyMapCorrect': forall {S T X}`{EmbeddedType T S}\n                        (f: S -> listPair Z X) (l:T) (x:X) (n:Z) (i:listPair Z X -> S -> S),\n                        (forall x l, f (i x l) = x) ->\n       eval_state (do m ← ↑ (ε f); \n                   return! hmapLookup Z.eqb n m)\n       (exec_state (↑ (modifyXHMap1 f i n x)) l) = Some x.\nProof.\n intros. rewrite liftEmbeddedStateBind.\n rewrite liftEmbeddedStateExec. rewrite  eval_bind.\n rewrite eval_embed_bind. apply modifyMapCorrect.\n auto.\nQed.\n\nLemma modifyMapDefaultCorrect': forall {S T X}`{EmbeddedType T S}\n                        (f: S -> listPair Z X) (l:T) (x:X) (n:Z) (i:listPair Z X -> S -> S) d,\n                        (forall x l, f (i x l) = x) ->\n       eval_state (do m ← ↑ (ε f); \n                   return! hmapFindWithDefault d Z.eqb n m)\n       (exec_state (↑ (modifyXHMap1 f i n x)) l) = x.\nProof.\n intros. unfold hmapFindWithDefault.\n rewrite eval_bind2. rewrite eval_unit.\n remember (modifyMapCorrect' f l x n i H0). clear Heqe.\n rewrite eval_bind2 in e. rewrite eval_unit in e.\n setoid_rewrite e. auto.\nQed. \n*)\n\nLemma modifyMapCorrect2: forall {S  X} \n                        (f: S -> listPair Z X) (l:S) (x:X) (n k:Z) (i:listPair Z X -> S -> S),\n                        (forall x l, f (i x l) = x) ->\n       n <> k ->\n       eval_state (do m ← ε f; \n                   return! hmapLookup Z.eqb n m)\n       (exec_state (modifyXHMap1 f i k x) l) = \n      eval_state (do m ← ε f; \n                   return! hmapLookup Z.eqb n m) l.\nProof.\n intros. unfold modifyXHMap1.\n unfold hmapInsert. \n Opaque hmapIsMember get put run bind bind_ embed_fun unit modify exec_state.\n rewrite ?exec_bind. rewrite exec_embed. rewrite eval_embed. \n rewrite ?eval_bind2. unfold eval_state. \n rewrite ?rununit.\n rewrite ?runembed. simpl. \n rewrite exec_bind'. rewrite exec_unit.\n Transparent exec_state. unfold exec_state. \n Transparent modify. unfold modify. unfold compose. \n rewrite getput. rewrite runbind. rewrite runembed.\n rewrite runput. simpl. Transparent hmapIsMember get put run bind bind_ embed_fun unit modify exec_state.\n rewrite H. unfold Datatypes.id. \n apply modifyMapCorrect2_helper.\n unfold boolEquivalence. intros. apply intBoolEquivalence.\n auto.\nQed.\n\nLemma modifyMapCorrect2': forall {S T  X}`{EmbeddedType T S}\n                        (f: S -> listPair Z X) (l:T) (x:X) (n k:Z) (i:listPair Z X -> S -> S),\n                        (forall x l, f (i x l) = x) ->\n                        n <> k ->\n       eval_state (do m ← ↑ (ε f); \n                   return! hmapLookup Z.eqb n m)\n       (exec_state (↑ (modifyXHMap1 f i k x)) l) = \n      eval_state (do m ← ↑ (ε f); \n                   return! hmapLookup Z.eqb n m) l.\n\nProof.\n intros. rewrite ?liftEmbeddedStateBind.\n rewrite ?liftEmbeddedStateExec. rewrite  ?eval_bind.\n rewrite ?eval_embed_bind.\n rewrite modifyMapCorrect2. rewrite ?eval_bind2.\n rewrite ?exec_embed. rewrite eval_embed.\n unfold eval_state. rewrite rununit.\n unfold embed_funInducted. rewrite runembed. simpl.\n unfold compose.\n auto. auto. auto.\nQed.\n\nLemma modifyMapDefaultCorrect2': forall {S T X}`{EmbeddedType T S}\n                        (f: S -> listPair Z X) (l:T) (x:X) (n k:Z) (i:listPair Z X -> S -> S) d,\n                        (forall x l, f (i x l) = x) ->\n       n <> k -> \n       eval_state (do m ← ↑ (ε f); \n                   return! hmapFindWithDefault d Z.eqb n m)\n       (exec_state (↑ (modifyXHMap1 f i k x)) l) = \n       eval_state (do m ← ↑ (ε f); \n                   return! hmapFindWithDefault d Z.eqb n m) l.\nProof.\n intros. unfold hmapFindWithDefault.\n rewrite eval_bind2. rewrite eval_unit.\n remember (modifyMapCorrect2' f l x n k i H0 H1). clear Heqe.\n rewrite eval_bind2 in e. rewrite eval_unit in e.\n setoid_rewrite e. symmetry.\n rewrite eval_bind2. rewrite eval_unit.\n rewrite eval_bind2. rewrite eval_unit.\n auto.\nQed.\n\n(*\n(fun r : PendingLimitP =>\n              ProgrammingWith.wrapWith r votes_ι_PendingLimit\n                (votes_ι_PendingLimit r) [sender]← xBoolFalse\n                Struct_PendingLimit Acc_PendingLimit__votes)\n                f [k] ^ g [n]\n*)\n\nExisting Instance xint_booleq.\n(*\nLemma modifyMapFieldMapCorrect:  forall {S T X}`{XDefault X}`{XDefault T} \n                                 (f: S -> listPair Z T) (l:S)\n                                 (x:X) (n k:Z) (i:listPair Z T -> S -> S)\n                                 (g: T -> listPair Z X) (s:X) t z,\n                                 hmapLookup Z.eqb k (f l) = Some z -> \n                                 g default = [ ] -> \n                                 (forall x l, f (i x l) = x) ->\n                                 (forall r, ((t r) ->> g) [n] = s) ->\n((eval_state (ε f)\n    (exec_state\n       ((modifyXHMapRecordByFun f i t k)) l)) [k] ->> g) [n] = s.\nProof.\n intros. unfold modifyXHMapRecordByFun.\n rewrite exec_bind.\n rewrite exec_embed.\n remember ((eval_state (ε f) l) [k] ?).\n setoid_rewrite <- Heqy.\n destruct y. simpl.\n unfold modify. rewrite exec_bind'.\n rewrite exec_unit.\n rewrite exec_bind.\n unfold compose.\n rewrite exec_get.\n rewrite eval_get.\n rewrite exec_put.\n rewrite 2eval_embed. rewrite eval_embed in Heqy.\n rewrite H3. unfold hmapFindWithDefault.\n unfold hmapInsert.\n assert (hmapIsMember Z.eqb k (f l) = true).\n apply memberLookup.\n unfold boolEquivalence. intros. apply intBoolEquivalence.\n exists t0. rewrite Heqy. simpl. auto.\n setoid_rewrite H5. simpl.\n rewrite lookupAdjust2.\n simpl. unfold Datatypes.id.\n unfold hmapFindWithDefault in H4.\n unfold Datatypes.id in H4.\n rewrite H4. auto.\n unfold boolEquivalence. intros. apply intBoolEquivalence.\n auto.  simpl.\n rewrite eval_embed. rewrite exec_unit.\n unfold hmapFindWithDefault.\n assert (hmapLookup Z.eqb k (f l) = None).\n rewrite  eval_embed in Heqy.\n rewrite Heqy.\n simpl. auto.\n rewrite H5. simpl. unfold get_field.\n rewrite H2.\n unfold  hmapLookup.\n simpl. congruence.\nQed.\n\nLemma modifyMapFieldMapCorrect2:  forall {S T X}`{XDefault X}`{XDefault T} \n                                 (f: S -> listPair Z T) (l:S)\n                                 (x:X) (n k:Z) (i:listPair Z T -> S -> S)\n                                 (g: T -> listPair Z X) (s:X) t,\n                                 (* hmapLookup Z.eqb k (f l) = Some z ->  *)\n                                 g default = [ ] -> \n                                 (forall x l, f (i x l) = x) ->\n                                 (forall r, ((t r) ->> g) [n] = s) ->\n((eval_state (ε f)\n    (exec_state\n       ((modifyXHMapRecordByFunDefault f i t k)) l)) [k] ->> g) [n] = s.\nProof.\nintros. unfold modifyXHMapRecordByFunDefault.\n rewrite exec_bind.\n rewrite exec_embed.\n rewrite ?eval_embed.\n unfold modify. rewrite exec_bind'.\n rewrite exec_unit.\n rewrite exec_bind.\n unfold compose.\n rewrite exec_get.\n rewrite eval_get.\n rewrite exec_put.\n rewrite H2.\n unfold hmapFindWithDefault.\n unfold hmapInsert. simpl.\n remember (hmapIsMember Z.eqb k (f l)).\n setoid_rewrite <- Heqb.\n destruct b.\n rewrite lookupAdjust2.\n simpl. unfold Datatypes.id.\n assert (exists y, hmapLookup Z.eqb k (f l) = Some y).\n apply memberLookup.\n unfold boolEquivalence. intros. apply intBoolEquivalence.\n auto. inversion H4. setoid_rewrite H5.\n simpl. unfold hmapFindWithDefault in H3. \n rewrite H3. auto.\n unfold boolEquivalence. intros. apply intBoolEquivalence.\n auto. unfold Datatypes.id.\n unfold hmapLookup.\n simpl. assert (k =? k = true).\n apply Z.eqb_eq. auto.\n rewrite H4. simpl.\n unfold Datatypes.id.\n match goal with\n | |- optionMapDefault (fun x0 : X => x0)\n  (hd_error ?m) default = s => remember m\n end. unfold get_field in Heql0.\n unfold hmapFindWithDefault in H3.\n match goal with\n | H: l0 = List.map snd\n          (filter (fun p : Z * X => n =? fst p)\n             (g\n                (t ?r))) |- _ => remember r\n end.\n rewrite Heql0.\n unfold Datatypes.id in H3.\n unfold hmapLookup in H3.\n simpl in H3.\n unfold Datatypes.id in H3.\n unfold get_field in H3.\n rewrite H3. auto.\nQed.\n\nLemma modifyMapFieldMapCorrectLift: forall {S T L X}`{XDefault X}`{XDefault T}`{EmbeddedType L S}\n                                 (f: S -> listPair Z T) (l:L)\n                                 (x:X) (n k:Z) (i:listPair Z T -> S -> S)\n                                 (g: T -> listPair Z X) (s:X) t z,\n                                 hmapLookup Z.eqb k (f (projEmbed l)) = Some z -> \n                                 g default = [ ] -> \n                                 (forall x l, f (i x l) = x) ->\n                                 (forall r, ((t r) ->> g) [n] = s) ->\n((eval_state (↑(ε f))\n    (exec_state\n       (↑ (modifyXHMapRecordByFun f i t k)) l)) [k] ->> g) [n] = s.\nProof.\n intros.\n rewrite liftEmbeddedStateExec2.\n rewrite eval_bind. \n apply (modifyMapFieldMapCorrect f (projEmbed l) x n k i g s t z).\n auto. auto. auto. auto.\nQed.\n\nLemma modifyMapFieldMapCorrect3:  forall {S T X}`{XDefault X}`{XDefault T} \n                                 (f: S -> listPair Z T) (l:S)\n                                 (x:X) (k:Z) (i:listPair Z T -> S -> S)\n                                 (s:T) t z,\n                                 hmapLookup Z.eqb k (f l) = Some z -> \n                                 (forall x l, f (i x l) = x) ->\n                                 t z = s ->\n((eval_state (ε f)\n    (exec_state\n       ((modifyXHMapRecordByFun f i t k)) l)) [k]) = s.\nProof.\n intros.\n unfold modifyXHMapRecordByFun.\n rewrite exec_bind.\n rewrite exec_embed.\n remember ((eval_state (ε f) l) [k] ?).\n setoid_rewrite <- Heqy.\n destruct y. simpl.\n unfold modify. rewrite exec_bind'.\n rewrite exec_unit.\n rewrite exec_bind.\n unfold compose.\n rewrite exec_get.\n rewrite eval_get.\n rewrite exec_put.\n rewrite 2eval_embed. rewrite eval_embed in Heqy.\n assert (Some t0 = Some z).\n rewrite Heqy. rewrite <- H1. simpl. auto.\n inversion H4.  \n rewrite H3. unfold hmapFindWithDefault.\n unfold hmapInsert.\n assert (hmapIsMember Z.eqb k (f l) = true).\n apply memberLookup.\n unfold boolEquivalence. intros. apply intBoolEquivalence.\n exists t0. rewrite Heqy. simpl. auto.\n setoid_rewrite H5. simpl.\n unfold Datatypes.id. rewrite H2.\n rewrite lookupAdjust2. simpl. auto.\n unfold boolEquivalence. intros. apply intBoolEquivalence.\n auto.  simpl.\n rewrite eval_embed. rewrite exec_unit.\n unfold hmapFindWithDefault.\n assert (hmapLookup Z.eqb k (f l) = None).\n rewrite  eval_embed in Heqy.\n rewrite Heqy.\n simpl. auto.\n rewrite H4. simpl.  congruence.\nQed.\n\n\nLemma modifyMapFieldMapCorrect3':  forall {S T X}`{XDefault X}`{XDefault T} \n                                 (f: S -> listPair Z T) (l:S)\n                                 (x:X) (k:Z) (i:listPair Z T -> S -> S)\n                                  t,\n                                 hmapLookup Z.eqb k (f l) = None -> \n                                 (forall x l, f (i x l) = x) ->\n((eval_state (ε f)\n    (exec_state\n       ((modifyXHMapRecordByFun f i t k)) l)) [k]) = default.\nProof.\n intros.\n unfold modifyXHMapRecordByFun.\n rewrite exec_bind.\n rewrite exec_embed.\n remember ((eval_state (ε f) l) [k] ?).\n setoid_rewrite <- Heqy.\n destruct y. rewrite eval_embed in Heqy.\n simpl in Heqy.\n congruence. simpl.\n rewrite eval_embed. rewrite exec_unit.\n unfold hmapFindWithDefault.\n rewrite H1. compute. auto.\nQed.\n*)\nLemma modifyMapCorrect3: forall {X}`{XDefault X}\n                        (m: listPair Z X) (k:Z) (x:X),\n                        (m [k]← x) [k] = x.\nProof.\n intros. unfold hmapFindWithDefault.\n remember (m [k]← x [k] ?).\n destruct y. symmetry in Heqy.\n assert (exists z : X, hmapLookup Z.eqb k (m [k]← x) = Some z).\n exists x0. auto.\n apply memberLookup in H0.\n remember ((hmapIsMember eqb k m)).\n unfold hmapInsert in H0.  unfold hmapInsert in Heqy.\n destruct y. rewrite <- Heqy0 in H0.\n rewrite <- Heqy0 in Heqy. simpl in H0.\n remember (adjustListPair Z.eqb (fun _ : X => x) k m).\n remember Heql.\n symmetry in Heqy0. apply memberLookup in Heqy0.\n inversion Heqy0. clear Heqe.\n apply (lookupAdjust1  (z:=x1) (k:=k)) in e.\n inversion_clear e. inversion_clear H3.\n simpl. unfold Datatypes.id.\n apply H4 in H1. unfold hmapInsert in Heqy.\n simpl in Heqy.\n rewrite <- Heql in Heqy. setoid_rewrite Heqy in H1.\n inversion H1. auto.\n unfold boolEquivalence. intros. apply intBoolEquivalence.\n unfold boolEquivalence. intros. apply intBoolEquivalence.\n simpl. rewrite <- Heqy0 in  H0. rewrite <- Heqy0 in  Heqy.\n simpl in H0. simpl in Heqy.\n unfold Datatypes.id in Heqy. unfold Datatypes.id in H0.\n unfold hmapLookup in Heqy. simpl in Heqy.\n rewrite Z.eqb_refl in Heqy. \n simpl in Heqy. inversion Heqy. compute. auto.\n unfold boolEquivalence. intros. apply intBoolEquivalence.\n unfold hmapInsert in Heqy.\n remember (hmapIsMember eqb k m).\n simpl. destruct y. simpl in Heqy.\n remember (adjustListPair Z.eqb (fun _ : X => x) k m).\n symmetry in Heqy0. apply memberLookup in Heqy0. inversion Heqy0.\n apply (lookupAdjust1  (z:=x0) (k:=k)) in Heql.\n inversion_clear Heql. inversion_clear H2. \n apply H3 in H0. setoid_rewrite <- Heqy in H0.\n inversion H0. \n unfold boolEquivalence. intros. apply intBoolEquivalence.\n unfold boolEquivalence. intros. apply intBoolEquivalence.\n simpl in Heqy. unfold hmapLookup in Heqy.\n simpl in Heqy. rewrite Z.eqb_refl in Heqy.  simpl in Heqy.\n inversion Heqy.\nQed.\n\nLemma modifyMapFieldMapCorrect3Default:  forall {S T X}`{XDefault X}`{XDefault T} \n                                 (f: S -> listPair Z T) (l:S)\n                                 (x:X) (k:Z) (i:listPair Z T -> S -> S)\n                                 (s:T) t,\n                                 (forall x l, f (i x l) = x) ->\n                                 t (f l) [k] = s ->\n((eval_state (ε f)\n    (exec_state\n       ((modifyXHMapRecordByFunDefault f i t k)) l)) [k]) = s.\nProof.\n intros.\n unfold modifyXHMapRecordByFunDefault.\n rewrite exec_bind.\n rewrite exec_embed.\n (* remember ((eval_state (ε f) l) [k] ?). \n setoid_rewrite <- Heqy.\n destruct y. simpl.*)\n unfold modify. rewrite exec_bind'.\n rewrite exec_unit.\n rewrite exec_bind.\n unfold compose.\n rewrite exec_get.\n rewrite eval_get.\n rewrite exec_put.\n rewrite 2eval_embed. \n rewrite ?H1.\n rewrite modifyMapCorrect3.\n auto.\n Qed.\n\nLemma modifyStateCorrect: forall {S T X}`{EmbeddedType S T} (f:T->X) (l:S) m, \neval_state (↑ (ε f)) (exec_state (↑ (modify m)) l) = f (m (projEmbed l)).\nProof.\n intros. rewrite liftEmbeddedStateExec2.\n rewrite eval_bind. unfold modify.\n rewrite exec_bind. unfold compose.\n rewrite exec_put. rewrite eval_embed.\n rewrite eval_get. auto.\nQed.\n\n\nLemma adjustListPairDouble:\nforall X x y k m,\nadjustListPair Z.eqb (fun _ : X => y) k\n  (adjustListPair Z.eqb (fun _ : X => x) k m) =\nadjustListPair Z.eqb (fun _ : X => y) k m.\nProof.\n intros. induction m.\n simpl. auto.\n simpl. destruct a.\n remember (k =? z).\n destruct  b.\n simpl. rewrite Z.eqb_refl.\n rewrite IHm. auto.\n simpl. rewrite <- Heqb. rewrite IHm.  auto.\n Qed.\n(*\nLemma memberFalseAdjust:\nforall X x k m, hmapIsMember eqb k m = false ->\n      adjustListPair Z.eqb (fun _ : X => x) k m = m.\nProof.\n intros.\n induction m.\n simpl. auto.\n simpl. destruct a.\n replace (k =? z) with false.\n rewrite IHm. auto. \n simpl in H. apply memberLookup2.\n unfold boolEquivalence. intros. apply intBoolEquivalence.\n apply memberLookup2 in H.\n unfold  hmapLookup in H.\n simpl in H.\n remember (k=?z). destruct b.\n simpl in H. inversion H.\n apply H.\n unfold boolEquivalence. intros. apply intBoolEquivalence.\n apply memberLookup2 in H.\n unfold  hmapLookup in H.\n simpl in H.\n remember (k=?z). destruct b.\n simpl in H. inversion H. auto.\n unfold boolEquivalence. intros. apply intBoolEquivalence.\n Qed.\n\nLemma modifyMapCorrect4: forall {X}`{XDefault X}\n                        (m: listPair Z X) (k:Z) (x y:X),\n                        (m [k]← x) [k] ← y = \n                        (m [k]← y).\nProof.\n intros.\n unfold hmapInsert.\n remember (hmapIsMember eqb k m).\n destruct  y0.\n simpl.\n replace (hmapIsMember Z.eqb k\n    (adjustListPair Z.eqb (fun _ : X => x) k m)) with true.\n apply adjustListPairDouble.\n symmetry.\n apply memberLookup.\n unfold boolEquivalence. intros. apply intBoolEquivalence.\n exists x.\n apply lookupAdjust2.\n unfold boolEquivalence. intros. apply intBoolEquivalence.\n auto.\n simpl. unfold Datatypes.id.\n rewrite Z.eqb_refl.\n replace (hmapIsMember Z.eqb k ((k, x) :: m)) with true.\n rewrite memberFalseAdjust.\n auto. auto.  symmetry.\n apply memberLookup.\n unfold boolEquivalence. intros. apply intBoolEquivalence.\n exists x.\n unfold hmapLookup.\n simpl. rewrite Z.eqb_refl.\n simpl.  auto.\nQed.\n\nLemma modifyMapFieldsCommute:\nforall {S T}`{XDefault T} \n(f: S -> listPair Z T) i (n: Z) (s: S) t1 t2, \n(forall x l, f (i x l) = x) ->\n(forall x y l, i x (i y l) = i x l) ->\n(forall t, t1 (t2 t) = t2 (t1 t)) ->\nexec_state\n  (modifyXHMapRecordByFunDefault f i t1 n)\n  (exec_state\n     (modifyXHMapRecordByFunDefault f i t2 n) s) =\nexec_state\n  (modifyXHMapRecordByFunDefault f i t2 n) \n  (exec_state\n     (modifyXHMapRecordByFunDefault f i t1 n) s).\nProof.\n intros.\n unfold modifyXHMapRecordByFunDefault.\n rewrite ?exec_bind.\n rewrite ?eval_embed.\n unfold modify.\n rewrite ?exec_embed.\n rewrite ?exec_bind'.\n rewrite ?exec_bind.\n unfold compose.\n rewrite ?exec_get.\n rewrite ?exec_unit.\n rewrite ?exec_put.\n rewrite ?eval_get.\n rewrite ?H0.\n remember (f s).\n remember (l [n]).\n setoid_rewrite <- Heqt.\n rewrite ?modifyMapCorrect3.\n rewrite ?H1.\n rewrite ?modifyMapCorrect4.\n rewrite H2.\n auto.\nQed.\n \nLemma hmapDoubleInsert: forall X m (k: Z) (x y: X),\n(m [k] ← x) [k] ← y = m [k] ← y.\nProof.\n intros. unfold hmapInsert.\n simpl. unfold Datatypes.id.\n remember (hmapIsMember Z.eqb k m). destruct b.\n replace (hmapIsMember Z.eqb k\n    (adjustListPair Z.eqb (fun _ : X => x) k m)) with true.\n rewrite adjustListPairDouble. auto.\n symmetry. \n apply memberLookup.\n unfold boolEquivalence. intros. apply intBoolEquivalence.\n symmetry in Heqb. remember Heqb. clear Heqe.\n apply memberLookup in Heqb. inversion Heqb.\n exists x. \n apply lookupAdjust2.\n unfold boolEquivalence. intros. apply intBoolEquivalence.\n auto. unfold boolEquivalence. intros. apply intBoolEquivalence.\n simpl. rewrite Z.eqb_refl.\n unfold hmapIsMember. simpl. rewrite Z.eqb_refl. simpl.\n rewrite memberFalseAdjust. auto. auto.\nQed.\n\nLemma hmapDoubleInsertNeq: forall X`{XDefault X} (m: listPair Z X) (k n: Z) (x y: X),\nk <> n  ->\n(((m [k] ← x) [n] ← y) [k]) = x.\nProof.\n intros.\n remember (m [k]← x)  as m'.\n remember (modifyMapCorrect2_helper (K:=Z) (V:=X) (m:=m') (x:=y)  (n:=k) (k:=n)  (eqK := Z.eqb)).\n apply e in H0. clear Heqe.\n unfold hmapFindWithDefault.\n unfold hmapInsert. \n remember(hmapIsMember Z.eqb n m').\n setoid_rewrite <- Heqb.\n unfold xBoolIfElse.\n unfold xiBoolFunRec.\n unfold xlIntFunRec.\n unfold xhmListFunRec.\n unfold hmfr.\n unfold hmapFunRec.\n unfold listFunRec.\n unfold intFunRec.\n unfold boolFunRec.\n setoid_rewrite H0.\n rewrite Heqm'. apply modifyMapCorrect3.\n unfold boolEquivalence. intros. apply intBoolEquivalence.\nQed.\n\n\n\nLemma hmapDeleteInsert: forall X (k:Z) (x: X) m,\ndeleteListPair Z.eqb k (m [k] ← x) =\ndeleteListPair Z.eqb k m.\nProof.\n intros. induction m.\n simpl. rewrite Z.eqb_refl. auto.\n simpl. destruct a.\n unfold hmapInsert.\n simpl. unfold hmapIsMember. simpl.\n remember (z=?k).\n replace (k=?z) with b.\n unfold Datatypes.id.\n unfold hmapInsert in IHm.\n simpl in IHm. unfold Datatypes.id  in IHm.\n unfold hmapIsMember in IHm.\n destruct b. simpl. rewrite Z.eqb_refl.\n remember (xListIn Z.eqb k (xHMapKeys m)).\n destruct b. \n auto. rewrite memberFalseAdjust. auto.\n unfold hmapIsMember. auto.\n simpl. remember (bIn Z.eqb k (List.map fst m)).\n destruct b. setoid_rewrite <- Heqb0 in IHm.\n rewrite <- IHm. simpl.\n replace (k=?z) with false. auto.\n symmetry. rewrite Z.eqb_sym. auto. \n simpl. rewrite Z.eqb_refl.\n replace (k=?z) with false.\n auto. rewrite Z.eqb_sym. auto.\n rewrite Z.eqb_sym. auto.\nQed.\n*)\nLemma hmapIsMemberDelete: forall X (k:Z) m,\nhmapIsMember (V:=X) Z.eqb k (deleteListPair Z.eqb k m) = false.\nProof.\n intros.\n induction m.\n simpl. auto.\n simpl. destruct a. remember (k =? z).\n destruct b. auto.\n unfold hmapIsMember. simpl.\n replace (z =? k) with false.\n simpl. apply IHm.\n symmetry. rewrite Z.eqb_sym. auto.\nQed.\n\n\n\n\nEnd CommonModelProofs.\n\n", "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/Lib/CommonModelProofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.2660872841397838}}
{"text": "From Coq Require Import ssreflect ssrfun ssrbool.\n\nFrom Ltac2 Require Import Ltac2.\n\nFrom Coq Require Import Ensembles Bool String Btauto.\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\n                                  ProofSystem\n                                  wftactics\n                                  NamedAxioms\n                                  IndexManipulation.\n\nFrom stdpp Require Import list tactics fin_sets coGset gmap sets.\n\nFrom MatchingLogic.Utils Require Import stdpp_ext.\n\nImport extralibrary.\n\nImport\n  MatchingLogic.Syntax.Notations\n  MatchingLogic.DerivedOperators_Syntax.Notations\n  MatchingLogic.ProofSystem.Notations_private\n.\n\nSet Default Proof Mode \"Classic\".\n\nOpen Scope ml_scope.\n\nSection with_signature.\n  Context {Σ : Signature}.\n  (* TODO make this return well-formed patterns. *)\n  Fixpoint framing_patterns Γ ϕ (pf : Γ ⊢H ϕ) : gset wfPattern :=\n  match pf with\n  | hypothesis _ _ _ _ => ∅\n  | P1 _ _ _ _ _ => ∅\n  | P2 _ _ _ _ _ _ _ => ∅\n  | P3 _ _ _ => ∅\n  | Modus_ponens _ _ _ m0 m1\n    => (@framing_patterns _ _ m0) ∪ (@framing_patterns _ _ m1)\n  | Ex_quan _ _ _ _ => ∅\n  | Ex_gen _ _ _ x _ _ pf _ => @framing_patterns _ _ pf\n  | Prop_bott_left _ _ _ => ∅\n  | Prop_bott_right _ _ _ => ∅\n  | Prop_disj_left _ _ _ _ _ _ _ => ∅\n  | Prop_disj_right _ _ _ _ _ _ _ => ∅\n  | Prop_ex_left _ _ _ _ _ => ∅\n  | Prop_ex_right _ _ _ _ _ => ∅\n  | Framing_left _ _ _ psi wfp m0 => {[(exist _ psi wfp)]} ∪ (@framing_patterns _ _ m0)\n  | Framing_right _ _ _ psi wfp m0 => {[(exist _ psi wfp)]} ∪ (@framing_patterns _ _ m0)\n  | Svar_subst _ _ _ _ _ _ m0 => @framing_patterns _ _ m0\n  | Pre_fixp _ _ _ => ∅\n  | Knaster_tarski _ _ phi psi m0 => @framing_patterns _ _ m0\n  | Existence _ => ∅\n  | Singleton_ctx _ _ _ _ _ _ => ∅\n  end.\n\n\n  Fixpoint uses_ex_gen (EvS : EVarSet) Γ ϕ (pf : ML_proof_system Γ ϕ) :=\n  match pf with\n  | hypothesis _ _ _ _ => false\n  | P1 _ _ _ _ _ => false\n  | P2 _ _ _ _ _ _ _ => false\n  | P3 _ _ _ => false\n  | Modus_ponens _ _ _ m0 m1\n    => uses_ex_gen EvS _ _ m0\n        || uses_ex_gen EvS _ _ m1\n  | Ex_quan _ _ _ _ => false\n  | Ex_gen _ _ _ x _ _ pf _ => if decide (x ∈ EvS) is left _ then true else uses_ex_gen EvS _ _ pf\n  | Prop_bott_left _ _ _ => false\n  | Prop_bott_right _ _ _ => false\n  | Prop_disj_left _ _ _ _ _ _ _ => false\n  | Prop_disj_right _ _ _ _ _ _ _ => false\n  | Prop_ex_left _ _ _ _ _ => false\n  | Prop_ex_right _ _ _ _ _ => false\n  | Framing_left _ _ _ _ _ m0 => uses_ex_gen EvS _ _ m0\n  | Framing_right _ _ _ _ _ m0 => uses_ex_gen EvS _ _ m0\n  | Svar_subst _ _ _ _ _ _ m0 => uses_ex_gen EvS _ _ m0\n  | Pre_fixp _ _ _ => false\n  | Knaster_tarski _ _ phi psi m0 => uses_ex_gen EvS _ _ m0\n  | Existence _ => false\n  | Singleton_ctx _ _ _ _ _ _ => false\n  end.\n\nFixpoint uses_of_ex_gen Γ ϕ (pf : ML_proof_system Γ ϕ) : EVarSet :=\n  match pf with\n  | hypothesis _ _ _ _ => ∅\n  | P1 _ _ _ _ _ => ∅\n  | P2 _ _ _ _ _ _ _ => ∅\n  | P3 _ _ _ => ∅\n  | Modus_ponens _ _ _ m0 m1\n    => uses_of_ex_gen _ _ m0\n        ∪ uses_of_ex_gen _ _ m1\n  | Ex_quan _ _ _ _ => ∅\n  | Ex_gen _ _ _ x _ _ pf _ => {[x]} ∪ uses_of_ex_gen _ _ pf\n  | Prop_bott_left _ _ _ => ∅\n  | Prop_bott_right _ _ _ => ∅\n  | Prop_disj_left _ _ _ _ _ _ _ => ∅\n  | Prop_disj_right _ _ _ _ _ _ _ => ∅\n  | Prop_ex_left _ _ _ _ _ => ∅\n  | Prop_ex_right _ _ _ _ _ => ∅\n  | Framing_left _ _ _ _ _ m0 => uses_of_ex_gen _ _ m0\n  | Framing_right _ _ _ _ _ m0 => uses_of_ex_gen _ _ m0\n  | Svar_subst _ _ _ _ _ _ m0 => uses_of_ex_gen _ _ m0\n  | Pre_fixp _ _ _ => ∅\n  | Knaster_tarski _ _ phi psi m0 => uses_of_ex_gen _ _ m0\n  | Existence _ => ∅\n  | Singleton_ctx _ _ _ _ _ _ => ∅\n  end.\n  \n  Lemma uses_of_ex_gen_correct Γ ϕ (pf : ML_proof_system Γ ϕ) (x : evar) :\n    x ∈ uses_of_ex_gen Γ ϕ pf <-> uses_ex_gen {[x]} Γ ϕ pf = true.\n  Proof.\n    induction pf; simpl; try set_solver.\n    {\n      rewrite orb_true_iff. set_solver.\n    }\n    {\n      rewrite elem_of_union. rewrite IHpf.\n      destruct (decide (x0 ∈ {[x]})) as [Hin|Hnotin].\n      {\n        rewrite elem_of_singleton in Hin. subst.\n        split; intros H. reflexivity. left. rewrite elem_of_singleton.\n        reflexivity.\n      }\n      {\n        split; intros H.\n        {\n          destruct H as [H|H].\n          {\n            exfalso. set_solver.\n          }\n          exact H.\n        }\n        {\n          right. exact H.\n        }\n      }\n    }\n  Qed.\n\n  Fixpoint uses_svar_subst (S : SVarSet) Γ ϕ (pf : Γ ⊢H ϕ) :=\n    match pf with\n    | hypothesis _ _ _ _ => false\n    | P1 _ _ _ _ _ => false\n    | P2 _ _ _ _ _ _ _ => false\n    | P3 _ _ _ => false\n    | Modus_ponens _ _ _ m0 m1\n      => uses_svar_subst S _ _ m0\n         || uses_svar_subst S _ _ m1\n    | Ex_quan _ _ _ _ => false\n    | Ex_gen _ _ _ _ _ _ pf' _ => uses_svar_subst S _ _ pf'\n    | Prop_bott_left _ _ _ => false\n    | Prop_bott_right _ _ _ => false\n    | Prop_disj_left _ _ _ _ _ _ _ => false\n    | Prop_disj_right _ _ _ _ _ _ _ => false\n    | Prop_ex_left _ _ _ _ _ => false\n    | Prop_ex_right _ _ _ _ _ => false\n    | Framing_left _ _ _ _ _ m0 => uses_svar_subst S _ _ m0\n    | Framing_right _ _ _ _ _ m0 => uses_svar_subst S _ _ m0\n    | Svar_subst _ _ _ X _ _ m0 => if decide (X ∈ S) is left _ then true else uses_svar_subst S _ _ m0\n    | Pre_fixp _ _ _ => false\n    | Knaster_tarski _ _ phi psi m0 => uses_svar_subst S _ _ m0\n    | Existence _ => false\n    | Singleton_ctx _ _ _ _ _ _ => false\n    end.\n\n  Fixpoint uses_of_svar_subst Γ ϕ (pf : Γ ⊢H ϕ) : SVarSet :=\n    match pf with\n    | hypothesis _ _ _ _ => ∅\n    | P1 _ _ _ _ _ => ∅\n    | P2 _ _ _ _ _ _ _ => ∅\n    | P3 _ _ _ => ∅\n    | Modus_ponens _ _ _ m0 m1\n      => uses_of_svar_subst _ _ m0\n          ∪ uses_of_svar_subst _ _ m1\n    | Ex_quan _ _ _ _ => ∅\n    | Ex_gen _ _ _ _ _ _ pf' _ => uses_of_svar_subst _ _ pf'\n    | Prop_bott_left _ _ _ => ∅\n    | Prop_bott_right _ _ _ => ∅\n    | Prop_disj_left _ _ _ _ _ _ _ => ∅\n    | Prop_disj_right _ _ _ _ _ _ _ => ∅\n    | Prop_ex_left _ _ _ _ _ => ∅\n    | Prop_ex_right _ _ _ _ _ => ∅\n    | Framing_left _ _ _ _ _ m0 => uses_of_svar_subst _ _ m0\n    | Framing_right _ _ _ _ _ m0 => uses_of_svar_subst _ _ m0\n    | Svar_subst _ _ _ X _ _ m0 => {[X]} ∪ uses_of_svar_subst _ _ m0\n    | Pre_fixp _ _ _ => ∅\n    | Knaster_tarski _ _ phi psi m0 => uses_of_svar_subst _ _ m0\n    | Existence _ => ∅\n    | Singleton_ctx _ _ _ _ _ _ => ∅\n    end.\n\n  Lemma uses_of_svar_subst_correct Γ ϕ (pf : ML_proof_system Γ ϕ) (X : svar) :\n    X ∈ uses_of_svar_subst Γ ϕ pf <-> uses_svar_subst {[X]} Γ ϕ pf = true.\n  Proof.\n    induction pf; simpl; try set_solver.\n    {\n      rewrite orb_true_iff. set_solver.\n    }\n    {\n      rewrite elem_of_union. rewrite IHpf. clear IHpf.\n      destruct (decide (X0 ∈ {[X]})) as [Hin|Hnotin].\n      {\n        rewrite elem_of_singleton in Hin. subst.\n        split; intros H. reflexivity. left. rewrite elem_of_singleton.\n        reflexivity.\n      }\n      {\n        split; intros H.\n        {\n          destruct H as [H|H].\n          {\n            exfalso. set_solver.\n          }\n          exact H.\n        }\n        {\n          right. exact H.\n        }\n      }\n    }\n  Qed.\n\n  Fixpoint uses_kt Γ ϕ (pf : Γ ⊢H ϕ) :=\n    match pf with\n    | hypothesis _ _ _ _ => false\n    | P1 _ _ _ _ _ => false\n    | P2 _ _ _ _ _ _ _ => false\n    | P3 _ _ _ => false\n    | Modus_ponens _ _ _ m0 m1\n      => uses_kt _ _ m0 || uses_kt _ _ m1\n    | Ex_quan _ _ _ _ => false\n    | Ex_gen _ _ _ _ _ _ pf' _ => uses_kt _ _ pf'\n    | Prop_bott_left _ _ _ => false\n    | Prop_bott_right _ _ _ => false\n    | Prop_disj_left _ _ _ _ _ _ _ => false\n    | Prop_disj_right _ _ _ _ _ _ _ => false\n    | Prop_ex_left _ _ _ _ _ => false\n    | Prop_ex_right _ _ _ _ _ => false\n    | Framing_left _ _ _ _ _ m0 => uses_kt _ _ m0\n    | Framing_right _ _ _ _ _ m0 => uses_kt _ _ m0\n    | Svar_subst _ _ _ X _ _ m0 => uses_kt _ _ m0\n    | Pre_fixp _ _ _ => false\n    | Knaster_tarski _ _ phi psi m0 => true\n    | Existence _ => false\n    | Singleton_ctx _ _ _ _ _ _ => false\n    end.\n\n  Fixpoint propositional_only Γ ϕ (pf : Γ ⊢H ϕ) :=\n    match pf with\n    | hypothesis _ _ _ _ => true\n    | P1 _ _ _ _ _ => true\n    | P2 _ _ _ _ _ _ _ => true\n    | P3 _ _ _ => true\n    | Modus_ponens _ _ _ m0 m1\n      => propositional_only _ _ m0 && propositional_only _ _ m1\n    | Ex_quan _ _ _ _ => false\n    | Ex_gen _ _ _ _ _ _ pf' _ => false\n    | Prop_bott_left _ _ _ => false\n    | Prop_bott_right _ _ _ => false\n    | Prop_disj_left _ _ _ _ _ _ _ => false\n    | Prop_disj_right _ _ _ _ _ _ _ => false\n    | Prop_ex_left _ _ _ _ _ => false\n    | Prop_ex_right _ _ _ _ _ => false\n    | Framing_left _ _ _ _ _ m0 => false\n    | Framing_right _ _ _ _ _ m0 => false\n    | Svar_subst _ _ _ X _ _ m0 => false\n    | Pre_fixp _ _ _ => false\n    | Knaster_tarski _ _ phi psi m0 => false\n    | Existence _ => false\n    | Singleton_ctx _ _ _ _ _ _ => false\n    end.\n\n  Lemma propositional_implies_no_frame Γ ϕ (pf : Γ ⊢H ϕ) :\n    propositional_only Γ ϕ pf = true -> framing_patterns Γ ϕ pf = ∅.\n  Proof.\n    intros H.\n    induction pf; simpl in *; try apply reflexivity; try congruence.\n    {\n      destruct_and!. specialize (IHpf1 ltac:(assumption)). specialize (IHpf2 ltac:(assumption)).\n      rewrite IHpf1. rewrite IHpf2. set_solver.\n    }\n  Qed.\n\n  Lemma propositional_implies_noKT Γ ϕ (pf : Γ ⊢H ϕ) :\n    propositional_only Γ ϕ pf = true -> uses_kt Γ ϕ pf = false.\n  Proof.\n    induction pf; simpl; intros H; try reflexivity; try congruence.\n    { destruct_and!. rewrite IHpf1;[assumption|]. rewrite IHpf2;[assumption|]. reflexivity. }\n  Qed.\n\n  Lemma propositional_implies_no_uses_svar Γ ϕ (pf : ML_proof_system Γ ϕ) (SvS : SVarSet) :\n    propositional_only Γ ϕ pf = true -> uses_svar_subst SvS Γ ϕ pf = false.\n  Proof.\n    induction pf; simpl; intros H; try reflexivity; try congruence.\n    { destruct_and!. rewrite IHpf1;[assumption|]. rewrite IHpf2;[assumption|]. reflexivity. }\n  Qed.\n\n  Lemma propositional_implies_no_uses_ex_gen Γ ϕ (pf : ML_proof_system Γ ϕ) (EvS : EVarSet) :\n    propositional_only Γ ϕ pf = true -> uses_ex_gen EvS Γ ϕ pf = false.\n  Proof.\n    induction pf; simpl; intros H; try reflexivity; try congruence.\n    { destruct_and!. rewrite IHpf1;[assumption|]. rewrite IHpf2;[assumption|]. reflexivity. }\n  Qed.\n  \n  Lemma propositional_implies_no_uses_ex_gen_2 Γ ϕ (pf : ML_proof_system Γ ϕ) :\n    propositional_only Γ ϕ pf = true -> uses_of_ex_gen Γ ϕ pf = ∅.\n  Proof.\n    induction pf; simpl; intros H; try reflexivity; try congruence.\n    { destruct_and!. rewrite IHpf1;[assumption|]. rewrite IHpf2;[assumption|]. set_solver. }\n  Qed.\n\n  Lemma propositional_implies_no_uses_svar_2 Γ ϕ (pf : ML_proof_system Γ ϕ)  :\n    propositional_only Γ ϕ pf = true -> uses_of_svar_subst Γ ϕ pf = ∅.\n  Proof.\n    induction pf; simpl; intros H; try reflexivity; try congruence.\n    { destruct_and!. rewrite IHpf1;[assumption|]. rewrite IHpf2;[assumption|]. set_solver. }\n  Qed.\n    \n  Definition proofbpred := forall (Γ : Theory) (ϕ : Pattern),  Γ ⊢H ϕ -> bool.\n\n  Definition indifferent_to_cast (P : proofbpred)\n    := forall (Γ : Theory) (ϕ ψ : Pattern) (e: ψ = ϕ) (pf : Γ ⊢H ϕ),\n         P Γ ψ (cast_proof e pf) = P Γ ϕ pf.\n\n  Lemma indifferent_to_cast_uses_svar_subst SvS:\n    indifferent_to_cast (uses_svar_subst SvS).\n  Proof.\n   unfold indifferent_to_cast. intros Γ ϕ ψ e pf.\n   induction pf; unfold cast_proof; unfold eq_rec_r;\n     unfold eq_rec; unfold eq_rect; unfold eq_sym; simpl; auto;\n     pose proof (e' := e); move: e; rewrite e'; clear e'; intros e;\n     match type of e with\n     | ?x = ?x => replace e with (@erefl _ x) by (apply UIP_dec; intros x' y'; apply Pattern_eqdec)\n     end; simpl; try reflexivity.\n  Qed.\n\n  Lemma indifferent_to_cast_uses_kt:\n    indifferent_to_cast uses_kt.\n  Proof.\n   unfold indifferent_to_cast. intros Γ ϕ ψ e pf.\n   induction pf; unfold cast_proof; unfold eq_rec_r;\n     unfold eq_rec; unfold eq_rect; unfold eq_sym; simpl; auto;\n     pose proof (e' := e); move: e; rewrite e'; clear e'; intros e;\n     match type of e with\n     | ?x = ?x => replace e with (@erefl _ x) by (apply UIP_dec; intros x' y'; apply Pattern_eqdec)\n     end; simpl; try reflexivity.\n  Qed.\n\n\n  Lemma indifferent_to_cast_uses_ex_gen EvS:\n    indifferent_to_cast (uses_ex_gen EvS).\n  Proof.\n   unfold indifferent_to_cast. intros Γ ϕ ψ e pf.\n   induction pf; unfold cast_proof; unfold eq_rec_r;\n     unfold eq_rec; unfold eq_rect; unfold eq_sym; simpl; auto;\n     pose proof (e' := e); move: e; rewrite e'; clear e'; intros e;\n     match type of e with\n     | ?x = ?x => replace e with (@erefl _ x) by (apply UIP_dec; intros x' y'; apply Pattern_eqdec)\n     end; simpl; try reflexivity.\n  Qed.\n\nEnd with_signature.\n\nDefinition has_bound_variable_under_mu {Σ : Signature} (ϕ : Pattern) : bool\n:= let x := fresh_evar ϕ in\n  mu_in_evar_path x (bsvar_subst (patt_free_evar x) 0 ϕ) 0\n.\n\nFixpoint uses_kt_unreasonably {Σ : Signature} Γ ϕ (pf : ML_proof_system Γ ϕ) :=\n  match pf with\n  | ProofSystem.hypothesis _ _ _ _ => false\n  | ProofSystem.P1 _ _ _ _ _ => false\n  | ProofSystem.P2 _ _ _ _ _ _ _ => false\n  | ProofSystem.P3 _ _ _ => false\n  | ProofSystem.Modus_ponens _ _ _ m0 m1\n    => uses_kt_unreasonably _ _ m0 || uses_kt_unreasonably _ _ m1\n  | ProofSystem.Ex_quan _ _ _ _ => false\n  | ProofSystem.Ex_gen _ _ _ _ _ _ pf' _ => uses_kt_unreasonably _ _ pf'\n  | ProofSystem.Prop_bott_left _ _ _ => false\n  | ProofSystem.Prop_bott_right _ _ _ => false\n  | ProofSystem.Prop_disj_left _ _ _ _ _ _ _ => false\n  | ProofSystem.Prop_disj_right _ _ _ _ _ _ _ => false\n  | ProofSystem.Prop_ex_left _ _ _ _ _ => false\n  | ProofSystem.Prop_ex_right _ _ _ _ _ => false\n  | ProofSystem.Framing_left _ _ _ _ _ m0 => uses_kt_unreasonably _ _ m0\n  | ProofSystem.Framing_right _ _ _ _ _ m0 => uses_kt_unreasonably _ _ m0\n  | ProofSystem.Svar_subst _ _ _ X _ _ m0 => uses_kt_unreasonably _ _ m0\n  | ProofSystem.Pre_fixp _ _ _ => false\n  | ProofSystem.Knaster_tarski _ phi psi wf m0 =>\n    has_bound_variable_under_mu phi || uses_kt_unreasonably _ _ m0\n  | ProofSystem.Existence _ => false\n  | ProofSystem.Singleton_ctx _ _ _ _ _ _ => false\n  end.\n\n  Lemma indifferent_to_cast_uses_kt_unreasonably {Σ : Signature}:\n    indifferent_to_cast uses_kt_unreasonably.\n  Proof.\n   unfold indifferent_to_cast. intros Γ ϕ ψ e pf.\n   induction pf; unfold cast_proof; unfold eq_rec_r;\n     unfold eq_rec; unfold eq_rect; unfold eq_sym; simpl; auto;\n     pose proof (e' := e); move: e; rewrite e'; clear e'; intros e;\n     match type of e with\n     | ?x = ?x => replace e with (@erefl _ x) by (apply UIP_dec; intros x' y'; apply Pattern_eqdec)\n     end; simpl; try reflexivity.\n  Qed.\n\nLemma kt_unreasonably_implies_somehow {Σ : Signature} Γ ϕ (pf : ML_proof_system Γ ϕ) :\n  uses_kt_unreasonably Γ ϕ pf -> uses_kt Γ ϕ pf.\nProof.\n  induction pf; cbn; auto with nocore.\n  { intros H. unfold is_true in *. rewrite orb_true_iff in H.\n    destruct H as [H|H].\n    {\n      specialize (IHpf1 H).\n      rewrite IHpf1.\n      reflexivity.\n    }\n    {\n      specialize (IHpf2 H).\n      rewrite IHpf2.\n      rewrite orb_true_r.\n      reflexivity.\n    }\n  }\n  {\n    intros _. reflexivity.\n  }\nQed.\n\nArguments uses_svar_subst {Σ} S {Γ} {ϕ} pf : rename.\nArguments uses_kt {Σ} {Γ} {ϕ} pf : rename.\nArguments uses_kt_unreasonably {Σ} {Γ} {ϕ} pf : rename.\nArguments uses_ex_gen {Σ} E {Γ} {ϕ} pf : rename.\n\n\nSection proof_constraint.\n  Context {Σ : Signature}.\n\n  Lemma instantiate_named_axiom (NA : NamedAxioms) (name : (NAName NA)) :\n    (theory_of_NamedAxioms NA) ⊢H (@NAAxiom Σ NA name).\n  Proof.\n    apply hypothesis.\n    { apply NAwf. }\n    unfold theory_of_NamedAxioms.\n    apply propset.elem_of_PropSet.\n    exists name.\n    reflexivity.\n  Defined.\n\n\n\n  Definition coEVarSet := coGset evar.\n  Definition coSVarSet := coGset svar.\n  Definition WfpSet := gmap.gset wfPattern.\n  Definition coWfpSet := coGset wfPattern.\n\n  Record ProofInfo :=\n    mkProofInfo\n    {\n      pi_generalized_evars : coEVarSet ;\n      pi_substituted_svars : coSVarSet ;\n      pi_uses_kt : bool ;\n      pi_uses_advanced_kt : bool ;\n      (* pi_framing_patterns : coWfpSet ;  *)\n    }.\n\n  Definition ProofInfoLe (i₁ i₂ : ProofInfo) : Prop :=\n    pi_generalized_evars i₁ ⊆ pi_generalized_evars i₂ /\\\n    pi_substituted_svars i₁ ⊆ pi_substituted_svars i₂ /\\\n    (pi_uses_kt i₁ ==> pi_uses_kt i₂) /\\\n    (pi_uses_advanced_kt i₁ ==> pi_uses_advanced_kt i₂)\n  .\n\n\n  (* A proof together with some properties of it. *)\n  Record ProofInfoMeaning\n    (Γ : Theory)\n    (ϕ : Pattern)\n    (pwi_pf : Γ ⊢H ϕ)\n    (pi : ProofInfo)\n    : Prop\n    :=\n  mkProofInfoMeaning\n  {\n    pwi_pf_ge : gset_to_coGset (@uses_of_ex_gen Σ Γ ϕ pwi_pf) ⊆ pi_generalized_evars pi ;\n    pwi_pf_svs : gset_to_coGset (@uses_of_svar_subst Σ Γ ϕ pwi_pf) ⊆ pi_substituted_svars pi ;\n    pwi_pf_kt : implb (@uses_kt Σ Γ ϕ pwi_pf) (pi_uses_kt pi) ;\n    pwi_pf_kta : implb (@uses_kt_unreasonably Σ Γ ϕ pwi_pf) (pi_uses_advanced_kt pi && (@uses_kt Σ Γ ϕ pwi_pf)) ;\n    (* pwi_pf_fp : gset_to_coGset (@framing_patterns Σ Γ ϕ pwi_pf) ⊆ (pi_framing_patterns pi) ; *)\n  }.\n\n  Definition ProofLe (i₁ i₂ : ProofInfo) :=\n    forall (Γ : Theory) (ϕ : Pattern) (pf : Γ ⊢H ϕ),\n      @ProofInfoMeaning Γ ϕ pf i₁ -> @ProofInfoMeaning Γ ϕ pf i₂.\n\n\n  Lemma ProofInfoLe_ProofLe (i₁ i₂ : ProofInfo) :\n    ProofInfoLe i₁ i₂ -> ProofLe i₁ i₂.\n  Proof.\n    intros H. intros Γ φ pf Hpf. destruct Hpf.\n    destruct H as [HEV [HSV [HKT HKTA] ] ].\n    constructor. 1-2: set_solver.\n    {\n      apply implb_true_iff.\n      pose proof (proj1 (implb_true_iff _ _) HKT).\n      pose proof (proj1 (implb_true_iff _ _) pwi_pf_kt0).\n      tauto.\n    }\n    {\n      apply implb_true_iff.\n      pose proof (H1 := proj1 (implb_true_iff _ _) HKTA).\n      pose proof (H2 := proj1 (implb_true_iff _ _) pwi_pf_kta0).\n      intro H.\n      rewrite andb_true_iff.\n      specialize (H2 H).\n      unfold is_true in pwi_pf_kta0.\n      rewrite implb_true_iff in pwi_pf_kta0.\n      specialize (pwi_pf_kta0 H).\n      split.\n      {\n        apply H1. clear H1.\n        rewrite andb_true_iff in pwi_pf_kta0.\n        apply pwi_pf_kta0.\n      }\n      rewrite andb_true_iff in H2. apply H2.\n    }\n  Qed.\n\nEnd proof_constraint.\n\n  Ltac convert_implb :=\n  unfold is_true in *;\n  match goal with\n  | |- context G [implb _ _ = true] => rewrite implb_true_iff\n  | H : context G [implb _ _ = true] |- _ => rewrite implb_true_iff in H\n  end.\n\n  Ltac convert_orb :=\n  unfold is_true in *;\n  match goal with\n  | |- context G [orb _ _ = true] => rewrite orb_true_iff\n  | H : context G [orb _ _ = true] |- _ => rewrite orb_true_iff in H\n  end.\n\n  Ltac convert_andb :=\n  unfold is_true in *;\n  match goal with\n  | |- context G [orb _ _ = true] => rewrite andb_true_iff\n  | H : context G [orb _ _ = true] |- _ => rewrite andb_true_iff in H\n  end.\n\n  Ltac destruct_pile :=\n    match goal with\n    | H : @ProofInfoLe _ _ _ |- _ => destruct H as [? [? ?] ]\n    end.\n\n  (** To solve goals shaped like: ProofInfoLe i₁ i₂ *)\n  Ltac try_solve_pile :=\n    assumption + (* optimization *)\n    (repeat destruct_pile;\n    simpl in *;\n    split; [try set_solver|split;[try set_solver\n    |try (repeat convert_implb;\n          repeat convert_orb;\n          repeat convert_andb;\n          set_solver)] ]).\n\nSection proof_info.\n  Context {Σ : Signature}.\n  Import Notations_private.\n  (*\n  #[global]\n  Instance\n  *)\n  Lemma pile_refl (i : ProofInfo) : ProofInfoLe i i.\n  Proof.\n    try_solve_pile. \n  Qed.\n\n  (*\n  #[global]\n  Instance\n  *)\n  Lemma pile_trans\n    (i₁ i₂ i₃ : ProofInfo) (PILE12 : ProofInfoLe i₁ i₂) (PILE23 : ProofInfoLe i₂ i₃)\n  : ProofInfoLe i₁ i₃.\n  Proof.\n    try_solve_pile.\n  Qed.\n\n  Definition BasicReasoning : ProofInfo := ((@mkProofInfo _ ∅ ∅ false false)).\n  Definition AnyReasoning : ProofInfo := (@mkProofInfo _ ⊤ ⊤ true true).\n\n\n  Definition derives_using Γ ϕ pi\n  := ({pf : Γ ⊢H ϕ | @ProofInfoMeaning _ _ _ pf pi }).\n\n  Definition derives Γ ϕ\n  := derives_using Γ ϕ AnyReasoning.\n\n  Definition raw_proof_of {Γ} {ϕ} {pi}:\n    derives_using Γ ϕ pi ->\n    ML_proof_system Γ ϕ\n  := fun pf => proj1_sig pf.\n\nEnd proof_info.\n\n\nModule Notations.\n\nNotation \"Γ '⊢i' ϕ 'using' pi\"\n:= (derives_using Γ ϕ pi)  (at level 95, no associativity).\n\nNotation \"Γ ⊢ ϕ\" := (derives Γ ϕ)\n(at level 95, no associativity).\n\nNotation \"'ExGen' ':=' evs ',' 'SVSubst' := svs ',' 'KT' := bkt ',' 'AKT' := akt\"\n  := (@mkProofInfo _ evs svs bkt akt) (at level 95, no associativity).\n\nEnd Notations.\n\n(* We cannot turn a proof into wellformedness hypotheses\n   if there is a ProofLe hypothesis depending on the proof\n  *)\nLtac2 clear_piles () :=\n  repeat (\n    lazy_match! goal with\n    | [ h : @ProofInfoLe _ _ _ |- _]\n      => clear $h\n      | [ h : @ProofLe _ _ _ |- _]\n      => clear $h\n      | [ h : @ProofInfoMeaning _ _ _ _ _ |- _]\n      => clear $h\n    end\n  )\n.  \n\nLtac2 pfs_to_wfs () :=\n  repeat (\n    match! goal with\n    | [h : @derives _ _ _ |- _]\n      => unfold derives\n    | [h : @derives_using _ _ _ _ |- _]\n      => apply @raw_proof_of in $h\n    | [ h: @ML_proof_system _ _ _ |- _]\n      => apply @proved_impl_wf in $h\n    end\n  ).\n\n\nLtac2 Set proved_hook_wfauto as oldhook\n:= (fun () => (*Message.print (Message.of_string \"hook_wfauto p2w\");*) clear_piles (); pfs_to_wfs () (*; oldhook ()*)).\n\n(*\nLtac2 Set hook_wfauto\n:= (fun () => Message.print (Message.of_string \"hook_wfauto p2w\")).\n*)\n\n\n\n(** For goals shaped like ProoInforMeeaning _ _ _ BasicReasoning *)\nLtac solve_pim_simple := constructor; simpl;[(set_solver)|(set_solver)|(reflexivity)|(reflexivity)].\n\nImport Notations.\n\nLemma useBasicReasoning {Σ : Signature} {Γ : Theory} {ϕ : Pattern} (i : ProofInfo) :\n  Γ ⊢i ϕ using BasicReasoning ->\n  Γ ⊢i ϕ using i.\nProof.\n  intros H.\n  pose proof (Hpf := proj2_sig H).\n  remember (proj1_sig H) as _H.\n  exists (_H).\n  clear Heq_H.\n  destruct Hpf as [Hpf1 Hpf2 Hpf3 Hpf4].\n  destruct i; constructor; simpl in *;\n  [set_solver|set_solver|idtac|idtac].\n  {\n    (destruct (uses_kt _H); simpl in *; try congruence).\n  }\n  {\n    (destruct (uses_kt_unreasonably _H); simpl in *; try congruence).\n  }\nDefined.\n\n\nTactic Notation \"remember_constraint\" \"as\" ident(i') :=\n    match goal with\n    | [|- (_ ⊢i _ using ?constraint)] => remember constraint as i'\n    end.\n\nLemma useGenericReasoning  {Σ : Signature} (Γ : Theory) (ϕ : Pattern) i' i:\n  (ProofInfoLe i' i) ->\n  Γ ⊢i ϕ using i' ->\n  Γ ⊢i ϕ using i.\nProof.\n  intros pile [pf Hpf].\n  exists pf.\n\n  destruct Hpf as [Hpf2 Hpf3 Hpf4 Hpf5].\n  destruct i, i'; cbn in *.\n  destruct pile as [H [H0 H1] ].\n  constructor; simpl.\n  { set_solver. }\n  { set_solver. }\n  { simpl in *. apply implb_true_iff.\n    unfold is_true in *. rewrite implb_true_iff in Hpf4 H1.\n    set_solver.\n  }\n  {\n    simpl in *. apply implb_true_iff.\n    unfold is_true in *. rewrite implb_true_iff in Hpf5 H1.\n    destruct H1 as [H11 H12].\n    rewrite implb_true_iff in H11.\n    rewrite implb_true_iff in H12.\n    intros H'.\n    naive_solver.\n  }\nDefined.\n\nTactic Notation \"gapply\" uconstr(pf) := eapply useGenericReasoning;[|eapply pf].\n\nTactic Notation \"gapply\" uconstr(pf) \"in\" ident(H) :=\n  eapply useGenericReasoning in H;[|apply pf].\n\nLemma pile_any {Σ : Signature} i:\n  ProofInfoLe i AnyReasoning.\nProof.\n  try_solve_pile.\nQed.\n\nTactic Notation \"aapply\" uconstr(pf)\n  := gapply pf; try apply pile_any.\n\nLemma pile_basic_generic {Σ : Signature} i:\n  ProofInfoLe BasicReasoning i.\nProof.\n  try_solve_pile.\nQed.\n\nLemma pile_impl_allows_gen_x {Σ : Signature} x gpi svs kt:\n  ProofInfoLe ( (ExGen := {[x]}, SVSubst := svs, KT := kt, AKT := false)) ( gpi) ->\n  x ∈ pi_generalized_evars gpi.\nProof.\n  destruct gpi. intro H.\n  destruct_pile. set_solver.\nQed.\n\nLemma pile_impl_uses_kt {Σ : Signature} gpi evs svs:\n  ProofInfoLe ( (ExGen := evs, SVSubst := svs, KT := true, AKT := false)) ( gpi) ->\n  pi_uses_kt gpi.\nProof.\n  destruct gpi. intro H.\n  destruct_pile. set_solver.\nQed.\n\nLemma pile_impl_allows_svsubst_X {Σ : Signature} gpi evs X kt:\n  ProofInfoLe ( (ExGen := evs, SVSubst := {[X]}, KT := kt, AKT := false)) ( gpi) ->\n  X ∈ pi_substituted_svars gpi.\nProof.\n  destruct gpi. intro H.\n  destruct_pile. set_solver.\nQed.\n\nLemma liftProofLe {Σ : Signature} (Γ : Theory) (ϕ : Pattern) (i₁ i₂ : ProofInfo)\n  {pile : ProofLe i₁ i₂}\n  :\n  Γ ⊢i ϕ using i₁ ->\n  Γ ⊢i ϕ using i₂.\nProof.\n    intros [pf Hpf].\n    apply pile in Hpf.\n    exists pf.\n    exact Hpf.\nQed.\n\nLemma liftProofInfoLe {Σ : Signature} (Γ : Theory) (ϕ : Pattern) (i₁ i₂ : ProofInfo)\n  {pile : ProofInfoLe i₁ i₂}\n  :\n  Γ ⊢i ϕ using i₁ ->\n  Γ ⊢i ϕ using i₂.\nProof.\n    intros H.\n    eapply liftProofLe.\n    apply ProofInfoLe_ProofLe.\n    all: eassumption.\nQed.\n\nTactic Notation \"use\" constr(i) \"in\" ident(H) :=\n  apply liftProofInfoLe with (i₂ := i) in H; [|try_solve_pile].\n\nClose Scope ml_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/ProofInfo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2660872841397837}}
{"text": "(************************************************************\n* Core Caml                                                 *\n* Syntax                                                    *\n*************************************************************)\n\nSet Implicit Arguments.\nRequire Export Common LibHeap.\nModule Heap := LibHeap.HeapList.\nNotation \"x ~~ a\" := (single x a)\n  (at level 27, left associativity) : env_scope.\n\n\n(*==========================================================*)\n(* * Definitions *)\n\n(************************************************************)\n(* ** Auxiliary definitions for the syntax *)\n\n(** Representation of record labels *)\n\nDefinition lab := var.\n\n(** Representation of constructors *)\n\nDefinition constr := var.\n\n(** Particular exceptions *)\n\nParameter constr_unit : constr.\nParameter constr_div_by_zero : constr.\nParameter constr_matching_failure : constr.\nParameter constr_assert_failure : constr.\n\n(** Representation of locations *)\n\nDefinition loc := var.\n\n(** Representation of the direction of a for-loop *)\n\nInductive dir : Type := dir_upto | dir_downto.\n\n(** Grammar of primitive operators *)\n\nInductive prim : Type :=\n  | prim_raise : prim\n  | prim_eq : prim\n  | prim_not : prim\n  | prim_neg : prim\n  | prim_add : prim\n  | prim_sub : prim\n  | prim_mul : prim\n  | prim_div : prim\n  | prim_and : prim\n  | prim_or : prim.\n\n(** Grammar of constants *)\n\nInductive cst : Type :=\n  | cst_bool : bool -> cst\n  | cst_int : int -> cst.\n\n(** Grammar of patterns *)\n\nInductive pat : Type :=\n  | pat_var : var -> pat\n  | pat_wild : pat\n  | pat_alias : pat -> var -> pat\n  | pat_or : pat -> pat -> pat\n  | pat_cst : cst -> pat\n  | pat_constr : constr -> list pat -> pat\n  | pat_tuple : list pat -> pat\n  | pat_record : list (lab*pat) -> pat.\n\n(** Grammar of terms *)\n\nInductive trm : Type :=\n  | trm_var : var -> trm\n  | trm_cst : cst -> trm\n  | trm_abs : option var -> pat -> trm -> trm\n  | trm_constr : constr -> list trm -> trm\n  | trm_tuple : list trm -> trm\n  | trm_record : list (lab*trm) -> trm\n  | trm_unary : prim -> trm -> trm\n  | trm_binary : prim -> trm -> trm -> trm\n  | trm_lazy_binary : prim -> trm -> trm -> trm\n  | trm_app : trm -> trm -> trm\n  | trm_seq : trm -> trm -> trm\n  | trm_let : pat -> trm -> trm -> trm\n  | trm_get : trm -> lab -> trm\n  | trm_set : trm -> lab -> trm -> trm\n  | trm_if : trm -> trm -> option trm -> trm\n  | trm_while : trm -> trm -> trm \n  | trm_for : var -> dir -> trm -> trm -> trm -> trm\n  | trm_match : trm -> list branch -> trm \n  | trm_try : trm -> list branch -> trm\n  | trm_assert : trm -> trm \n  | trm_rand : trm\n\nwith branch : Type := \n  | branch_intro : pat -> option trm -> trm -> branch.\n\n(** Grammar of values *)\n\nInductive val : Type :=\n  | val_cst : cst -> val\n  | val_loc : loc -> val\n  | val_abs : option var -> pat -> trm -> val\n  | val_constr : constr -> list val -> val\n  | val_tuple : list val -> val\n  | val_record : list (lab*val) -> val.\n\n(** Representation of the memory store *)\n\nDefinition mem := Heap.heap loc val.\n\n\n(************************************************************)\n(* ** Auxiliary definitions *)\n\n(** Substitution *)\n\nDefinition inst := LibEnv.env val.\n\nParameter subst : forall (x:var) (v:val) (t:trm), trm.\nParameter substs : forall (i:inst) (t:trm), trm.\n\n(** [val] is inhabited *)\n\nInstance val_inhab : Inhab val.\nProof. intros. apply (Inhab_of_val (val_cst (cst_bool true))). Qed.\n\n(** Shortnames for lists of terms and values *)\n\nDefinition trms := list trm.\nDefinition vals := list val.\nDefinition labtrms := list (lab*trm).\nDefinition labvals := list (lab*val).\nDefinition branches := list branch.\n\n(** Shortcuts for building terms and values *)\n\nDefinition val_exn k := val_constr k nil.\n\nDefinition val_unit := val_constr constr_unit nil.\n\n(** Coercions *)\n\nCoercion val_exn : constr >-> val.\nCoercion cst_int : Z >-> cst.\nCoercion cst_bool : bool >-> cst.\nCoercion pat_var : var >-> pat.\nCoercion val_loc : loc >-> val.\nCoercion val_cst : cst >-> val.\nCoercion trm_cst : cst >-> trm.\n\n\n(** Fresh locations *)\n\nDefinition fresh (m:mem) l :=\n  ~ Heap.indom m l.\n\n\n", "meta": {"author": "charguer", "repo": "formalmetacoq", "sha": "0f24ffe7416352c1a275671d8d857f8aa6a5bb39", "save_path": "github-repos/coq/charguer-formalmetacoq", "path": "github-repos/coq/charguer-formalmetacoq/formalmetacoq-0f24ffe7416352c1a275671d8d857f8aa6a5bb39/pretty/CoreCaml_Syntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2660872841397837}}
{"text": "Require Import CertiGraph.lib.List_ext.\nRequire Import CertiGraph.sample_mark.env_unionfind_arr.\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.graph.UnionFind.\nRequire Import CertiGraph.msl_application.UnionFindGraph.\nRequire Import CertiGraph.msl_application.ArrayGraph.\nRequire Import CertiGraph.floyd_ext.share.\nRequire Import CertiGraph.sample_mark.spatial_array_graph.\nRequire Import Coq.Lists.List.\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.\nExisting Instances maGraph finGraph liGraph.\n\nLocal Open Scope Z_scope.\n\nDefinition mallocN_spec :=\n DECLARE _mallocN\n  WITH sh:wshare, 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 (memory_block sh n (pointer_val_val v)).\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 sh: wshare, V: Z\n    PRE [tint]\n      PROP (0 < V <= Int.max_signed / 8)\n      PARAMS (Vint (Int.repr V))\n      GLOBALS ()\n      SEP ()\n    POST [tptr vertex_type]\n      EX g: UFGraph, EX rt: pointer_val, (*creates a graph where*)\n      PROP (forall i: Z, 0 <= i < V -> vvalid g i) (*anything between 0 and V is a vertex*)\n      LOCAL (temp ret_temp (pointer_val_val rt))\n      SEP (whole_graph sh g rt). (*representation in heap...*)\n\nDefinition find_spec :=\n  DECLARE _find\n  WITH sh: wshare, g: UFGraph, subsets: pointer_val, i: Z\n    PRE [tptr vertex_type, tint]\n      PROP (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: wshare, g: UFGraph, subsets: pointer_val, x: Z, y: Z\n  PRE [tptr vertex_type, tint, tint]\n          PROP  (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\nDefinition Gprog : funspecs :=\n  ltac:(with_library prog [mallocN_spec; makeSet_spec; find_spec; union_spec]).\n\nFixpoint prog_list_helper (i: nat) (n: nat) : list (val * val) :=\n  match n with\n  | O => nil\n  | S n' => if (le_dec i n') then (Vundef, Vundef) :: prog_list_helper i n'\n            else (Vint (Int.repr (Z.of_nat (n'))),\n                  Vint (Int.repr 0)) :: prog_list_helper i n'\n  end.\n\nDefinition progressive_list (i: nat) (n: nat) := rev (prog_list_helper i n).\n\nLemma progressive_list_repeat:\n  forall n, list_repeat n (Vundef, Vundef) = progressive_list O n.\nProof.\n  induction n; unfold progressive_list; simpl; auto. unfold progressive_list in IHn.\n  rewrite <- IHn. change ((Vundef, Vundef) :: list_repeat n (Vundef, Vundef)) with\n                      (((Vundef, Vundef) :: nil) ++ list_repeat n (Vundef, Vundef)).\n  change ((Vundef, Vundef) :: nil) with (list_repeat 1 (Vundef, Vundef)).\n  rewrite !list_repeat_app. rewrite Nat.add_comm. auto.\nQed.\n\nLemma progressive_list_length: forall i n, length (progressive_list i n) = n.\nProof.\n  intros. unfold progressive_list. rewrite rev_length. induction n; simpl; auto.\n  destruct (le_dec i n); simpl; rewrite IHn; auto.\nQed.\n\nDefinition progressive_array sh i V rt :=\n  data_at sh (tarray vertex_type V) (progressive_list (Z.to_nat i) (Z.to_nat V))\n          (pointer_val_val rt).\n\nLemma upd_Znth_twice: forall {A: Type} i (l: list A) v1 v2,\n    0 <= i < Zlength l -> upd_Znth i (upd_Znth i l v1) v2 = upd_Znth i l v2.\nProof.\n  intros. rewrite !upd_Znth_unfold; auto. 2: now rewrite upd_Znth_Zlength.\n  f_equal; [|f_equal].\n  - rewrite sublist0_app1.\n    + rewrite sublist_same; auto. rewrite Zlength_sublist; lia.\n    + rewrite Zlength_sublist; lia.\n  - assert (Zlength (sublist 0 i l) = i) by (rewrite Zlength_sublist; lia).\n    rewrite sublist_app2; rewrite H0. 2: lia.\n    assert (i + 1 - i = 1) by lia. rewrite H1. clear H1. rewrite Zlength_app.\n    rewrite H0. simpl. rewrite Zlength_cons. unfold Z.succ.\n    rewrite Zlength_sublist; [|lia..].\n    assert (i + (Zlength l - (i + 1) + 1) - i = Zlength l - i) by lia.\n    rewrite H1; clear H1. rewrite sublist_1_cons.\n    rewrite sublist_same; [auto | lia |]. rewrite Zlength_sublist; lia.\nQed.\n\nLemma prog_list_helper_gt: forall i j n,\n    (i >= n)%nat -> (j >= n)%nat -> prog_list_helper i n = prog_list_helper j n.\nProof.\n  intros. revert i j H H0. induction n; intros; simpl; auto.\n  destruct (le_dec i n), (le_dec j n); [exfalso; lia ..|]. f_equal. apply IHn; lia.\nQed.\n\nLemma upd_Znth_progressive_list: forall i V,\n    0 <= i < Z.of_nat V -> upd_Znth i (progressive_list (Z.to_nat i) V) (Vint (Int.repr i), Vint (Int.repr 0)) = progressive_list (Z.to_nat (i + 1)) V.\nProof.\n  intros. induction V. 1: exfalso; simpl in H; intuition. rewrite Nat2Z.inj_succ in H. unfold Z.succ in H. unfold progressive_list. simpl. destruct (le_dec (Z.to_nat i) V).\n  - destruct (le_dec (Z.to_nat (i + 1)) V).\n    + simpl. assert (0 <= i < Z.of_nat V) by (apply inj_le in l0; rewrite Z2Nat.id in l0; lia). unfold progressive_list in IHV. rewrite <- IHV; auto.\n      rewrite upd_Znth_app1; auto. change (rev (prog_list_helper (Z.to_nat i) V)) with (progressive_list (Z.to_nat i) V).\n      rewrite Zlength_correct, progressive_list_length. auto.\n    + assert (Z.to_nat (i + 1) > V)%nat by lia. apply inj_gt in H0. rewrite Z2Nat.id in H0. 2: lia. assert (i = Z.of_nat V) by lia. subst i.\n      clear IHV l n H0 H. rewrite Nat2Z.id. simpl. rewrite upd_Znth_char.\n      * f_equal. change 1 with (Z.of_nat 1). rewrite <- Nat2Z.inj_add, Nat2Z.id. f_equal. apply prog_list_helper_gt; lia.\n      * change (rev (prog_list_helper V V)) with (progressive_list V V). rewrite Zlength_correct, progressive_list_length. auto.\n  - exfalso. assert (Z.to_nat i > V)%nat by lia. apply inj_gt in H0. rewrite Z2Nat.id in H0; lia.\nQed.\n\nLemma progressive_nat_inc_list: forall n i, (i >= n)%nat -> map (fun x : Z => (Vint (Int.repr x), Vint (Int.repr 0))) (nat_inc_list n) = progressive_list i n.\nProof.\n  induction n; intros; unfold progressive_list in *; simpl; auto. destruct (le_dec i n). 1: exfalso; lia. rewrite map_app. simpl. rewrite <- IHn; intuition.\nQed.\n\nLemma body_makeSet: semax_body Vprog Gprog f_makeSet makeSet_spec.\nProof.\n  start_function. forward_call (sh, Z.mul V 8).\n  - assert (Int.min_signed <= 8 <= Int.max_signed) by rep_lia.\n    assert (Int.min_signed <= V <= Int.max_signed). {\n      split; rewrite Z.le_lteq; left.\n      - rep_lia.\n      - apply Z.le_lt_trans with (Int.max_signed / 8); [intuition | apply Z.div_lt; lia].\n    } rewrite !Int.signed_repr; auto. split. 1: lia.\n    assert (Z.mul 8 (Int.max_signed /8) <= Int.max_signed) by (apply Z_mult_div_ge; intuition). rep_lia.\n  - split. 1: lia. assert (Z.mul 8 (Int.max_signed /8) <= Int.max_signed) by (apply Z_mult_div_ge; intuition). rep_lia.\n  - Intros rt.\n    assert (memory_block sh (V * 8) (pointer_val_val rt) = data_at_ sh (tarray vertex_type V) (pointer_val_val rt)). {\n      assert (memory_block sh (V * 8) (pointer_val_val rt) = memory_block sh (sizeof (tarray vertex_type V)) (pointer_val_val rt)). {\n        simpl sizeof. rewrite Zmax0r. 2: intuition. assert (V * 8 = 8 * V)%Z by lia. rewrite H1. auto.\n      } rewrite <- memory_block_data_at_; auto. apply malloc_compatible_field_compatible; auto.\n      unfold malloc_compatible in *. destruct (pointer_val_val rt); auto. destruct H0. split; auto. simpl sizeof. rewrite Zmax0r; intuition.\n    } rewrite H1. clear H1.\n    assert (data_at_ sh (tarray vertex_type V) (pointer_val_val rt) = data_at sh (tarray vertex_type V) (progressive_list O (Z.to_nat V)) (pointer_val_val rt)). {\n      unfold data_at_, field_at_, data_at. assert (default_val (nested_field_type (tarray vertex_type V) []) = list_repeat (Z.to_nat V) (Vundef, Vundef)) by reflexivity.\n      rewrite H1. rewrite progressive_list_repeat. auto.\n    } rewrite H1. clear H1.\n    forward_for_simple_bound V\n      (EX i: Z,\n       PROP ()\n       LOCAL (temp _subsets (pointer_val_val rt); temp _V (Vint (Int.repr V)))\n       SEP (progressive_array sh i V rt)); unfold progressive_array.\n    + destruct H. apply Z.le_trans with (Int.max_signed / 8); auto. rewrite Z.lt_eq_cases. left. apply Z_div_lt; intuition.\n    + entailer.\n    + Opaque Znth. forward. remember (Znth i (progressive_list (Z.to_nat i) (Z.to_nat V))) as lll. destruct lll. forward.\n      assert (0 <= i < Zlength (progressive_list (Z.to_nat i) (Z.to_nat V))) by (split; [|rewrite Zlength_correct, progressive_list_length, Z2Nat.id]; lia).\n      rewrite upd_Znth_same, upd_Znth_twice; [|auto ..]. unfold progressive_array, data_at.\n      rewrite upd_Znth_progressive_list. 2: rewrite Z2Nat.id; lia. entailer. Transparent Znth.\n    + forward. Exists (makeSet_discrete_Graph (Z.to_nat V)) rt. entailer!.\n      * intros. simpl. rewrite makeSet_vvalid. rewrite Z2Nat.id; lia.\n      * unfold whole_graph, full_graph_at. simpl. Exists (Z.to_nat V). apply andp_right; intros; [apply andp_right; apply prop_right|].\n        -- intros. rewrite makeSet_vvalid. intuition.\n        -- rewrite Z2Nat.id; lia.\n        -- simpl. unfold vcell_array_at, SAG_VST. rewrite map_length, nat_inc_list_length. rewrite Z2Nat.id. 2: intuition.\n           assert (map (fun x : Z => vgamma (makeSet_discrete_LabeledGraph (Z.to_nat V)) x) (nat_inc_list (Z.to_nat V)) =\n                   map (fun x => (0%nat, x)) (nat_inc_list (Z.to_nat V))). {\n             apply list_map_exten. intros. unfold vgamma, UnionFindGraph.vgamma. simpl. rewrite makeSet_dst. simpl. auto.\n           } rewrite H6. clear H6. rewrite list_map_compose. unfold vgamma2cdata. simpl. rewrite <- progressive_nat_inc_list; intuition.\nQed.\n\nLemma whole_graph_fold: forall n sh g p,\n    (forall v : Z, 0 <= v < Z.of_nat n <-> vvalid (lg_gg g) v) -> Z.of_nat n <= Int.max_signed / 8 ->\n    data_at sh (tarray vertex_type (Z.of_nat n)) (map (fun x : Z => vgamma2cdata (vgamma (lg_gg g) x)) (nat_inc_list n)) (pointer_val_val p) = whole_graph sh g p.\nProof.\n  intros. apply pred_ext; unfold whole_graph, full_graph_at, vcell_array_at, SAG_VST; [apply (exp_right n)|Intros n']; rewrite map_length, nat_inc_list_length, list_map_compose.\n  - apply andp_right; auto. apply andp_right; apply prop_right; auto.\n  - destruct (lt_eq_lt_dec n n') as [[? | ?] | ?]; [exfalso | subst n' | exfalso]; auto.\n    + assert (vvalid (lg_gg g) (Z.of_nat n)) by (rewrite <- H1; intuition). rewrite <- H in H3. intuition.\n    + assert (vvalid (lg_gg g) (Z.of_nat n')) by (rewrite <- H; intuition). rewrite <- H1 in H3. intuition.\nQed.\n\nLemma whole_graph_unfold: forall sh g p,\n    whole_graph sh g p =\n    EX n: nat, !! (forall v : Z, 0 <= v < Z.of_nat n <-> vvalid (lg_gg g) v) && !!(Z.of_nat n <= Int.max_signed / 8) &&\n                  (data_at sh (tarray vertex_type (Z.of_nat n)) (map (fun x : Z => vgamma2cdata (vgamma (lg_gg g) x)) (nat_inc_list n)) (pointer_val_val p)).\nProof.\n  intros. unfold whole_graph, full_graph_at, vcell_array_at, SAG_VST.\n  apply pred_ext; Intros n; apply (exp_right n); apply andp_right; [apply andp_right; apply prop_right| |apply andp_right; apply prop_right|];\n    auto; rewrite map_length, nat_inc_list_length, list_map_compose; auto.\nQed.\n\nLemma Znth_nat_inc_list: forall {A: Type} {d: Inhabitant A} n (f: Z -> A) i, 0 <= i < Z.of_nat n -> Znth i (map f (nat_inc_list n)) = f i.\nProof.\n  intros. rewrite Znth_map. 2: rewrite Zlength_correct, nat_inc_list_length; auto. f_equal. induction n.\n  - exfalso. simpl in H. intuition.\n  - simpl. assert (0 <= i < Z.of_nat n \\/ i = Z.of_nat n). {\n      rewrite Nat2Z.inj_succ in H. destruct H. rewrite Z.lt_succ_r, Z.lt_eq_cases in H0. destruct H0; [left | right]; auto.\n    } assert (Zlength (nat_inc_list n) = Z.of_nat n) by (rewrite Zlength_correct, nat_inc_list_length; auto). destruct H0.\n    + rewrite app_Znth1. 2: rewrite H1; destruct H0; auto. apply IHn; auto.\n    + rewrite app_Znth2. 2: rewrite H1; intuition. rewrite H0, H1. replace (Z.of_nat n - Z.of_nat n) with 0 by lia. rewrite Znth_0_cons. auto.\nQed.\n\nLemma graph_same_size: forall (g g': UFGraph) n n', (forall x : Z, vvalid g x <-> vvalid g' x) -> (forall v : Z, 0 <= v < Z.of_nat n' <-> vvalid (lg_gg g') v) ->\n                                                  (forall v : Z, 0 <= v < Z.of_nat n <-> vvalid (lg_gg g) v) -> n = n'.\nProof.\n  intros. assert (forall v, 0 <= v < Z.of_nat n' <-> 0 <= v < Z.of_nat n). intros. rewrite H0. rewrite H1. symmetry. apply H. clear -H2.\n  destruct (lt_eq_lt_dec n n'); [destruct s|]; auto; exfalso.\n  - specialize (H2 (Z.of_nat n)). lia.\n  - specialize (H2 (Z.of_nat n')). lia.\nQed.\n\nLemma list_eq_Znth {A} {d: Inhabitant A}: forall (l1 l2: list A) n, length l1 = n -> length l2 = n -> (forall j, 0 <= j < Z.of_nat n -> Znth j l1 = Znth j l2) -> l1 = l2.\nProof.\n  intros l1 l2 n. revert l1 l2. induction n; intros.\n  - simpl in *. destruct l1, l2; simpl in *; [auto | exfalso; intuition..].\n  - destruct l1, l2; simpl in H, H0; [exfalso; intuition..| ]. assert (a = a0) by (specialize (H1 0); rewrite !Znth_0_cons in H1; apply H1; rewrite Nat2Z.inj_succ; lia).\n    subst a0. cut (l1 = l2); intros. 1: subst l2; auto. inversion H. inversion H0. apply (IHn _ _); auto. intros. specialize (H1 (j + 1)).\n    assert (0 < j + 1) by lia. assert (j + 1 - 1 = j) by lia. rewrite !Znth_pos_cons in H1; auto. rewrite !H6 in H1. apply H1. rewrite Nat2Z.inj_succ. lia.\nQed.\n\nLemma upd_Znth_Graph_redirect_parent: forall (i root : Z) (g: UFGraph) n (Hw: weak_valid g root) (Hv: vvalid g i) (Hi: ~ reachable g root i),\n    0 <= i < Z.of_nat n -> 0 <= root < Z.of_nat n -> upd_Znth i (map (fun m : Z => vgamma2cdata (vgamma (lg_gg g) m)) (nat_inc_list n))\n                                                              (Vint (Int.repr root), Vint (Int.repr (Z.of_nat (vlabel (lg_gg g) i)))) =\n                                                     map (fun m : Z => vgamma2cdata (vgamma (lg_gg (Graph_gen_redirect_parent g i root Hw Hv Hi)) m))(nat_inc_list n).\nProof.\n  intros.\n  assert (Zlength (map (fun m : Z => vgamma2cdata (vgamma (lg_gg g) m)) (nat_inc_list n)) = Z.of_nat n) by (rewrite Zlength_map, Zlength_correct, nat_inc_list_length; auto).\n  apply (list_eq_Znth _ _ n).\n  - rewrite <- (Nat2Z.id n) at 2. rewrite <- Zlength_length. 2: lia. rewrite upd_Znth_Zlength; auto. rewrite <- H1 in H. auto.\n  - rewrite list_length_map, nat_inc_list_length; auto.\n  - intros. rewrite Znth_nat_inc_list; auto. rewrite (upd_Znth_lookup' (Z.of_nat n)); auto. rewrite Znth_nat_inc_list; auto.\n    unfold vgamma2cdata, vgamma, UnionFindGraph.vgamma. simpl. unfold graph_gen.updateEdgeFunc. unfold EquivDec.equiv_dec, Z_EqDec, zeq. destruct (Z.eq_dec j i).\n    + subst j. destruct (Z.eq_dec i i). 2: exfalso; apply n0; auto. f_equal. destruct (Z_lt_dec root 0); [exfalso; lia | auto].\n    + f_equal. destruct (Z.eq_dec i j). 1: exfalso; intuition. auto.\nQed.\n\nLemma body_find: semax_body Vprog Gprog f_find find_spec.\nProof.\n  start_function. rewrite whole_graph_unfold. Intros n. forward.\n  assert (H_BOUND: 0 <= i < Zlength (nat_inc_list n)) by (rewrite Zlength_correct, nat_inc_list_length, H0; assumption). forward.\n  - apply prop_right. rewrite H0. auto.\n  - rewrite <- (map_id (nat_inc_list n)) at 1. rewrite Znth_nat_inc_list. 2: rewrite H0; auto. simpl id.\n    forward_if\n      (EX g': UFGraph, EX rt: Z,\n       PROP (uf_equiv g g' /\\ uf_root g' i rt)\n       LOCAL (temp _p (Vint (Int.repr rt)); temp _subsets (pointer_val_val subsets); temp _i (Vint (Int.repr i)))\n       SEP (whole_graph sh g' subsets)).\n    + rewrite whole_graph_fold; [|intuition..]. destruct (vgamma (lg_gg g) i) eqn: ?. forward_call (sh, g, subsets, z).\n      * unfold vgamma, UnionFindGraph.vgamma in Heqp. inversion Heqp. clear Heqp. destruct (Z_lt_dec (dst (lg_gg g) i) 0). 1: exfalso; apply H2; auto.\n        destruct ((proj2 (@only_one_edge _ _ _ _ _ _ (liGraph g) _ i H)) (eq_refl i)) as [_ ?]. destruct (valid_graph g _ H3) as [_ [? | ?]]; auto.\n        hnf in H6. exfalso. apply n1. auto.\n      * Intros vret. destruct vret as [g' root]. simpl fst in *. simpl snd in *. rewrite whole_graph_unfold. Intros n'. forward. Opaque Znth. forward. Transparent Znth.\n        -- apply prop_right. rewrite H5. destruct H3. rewrite <- H3. auto.\n        -- assert (n' = n). {\n             destruct H3, (lt_eq_lt_dec n n'); [destruct s|]; auto; exfalso.\n             - specialize (H3 (Z.of_nat n)). specialize (H0 (Z.of_nat n)). specialize (H5 (Z.of_nat n)). rewrite <- H0 in H3. rewrite <- H3 in H5. lia.\n             - specialize (H3 (Z.of_nat n')). specialize (H0 (Z.of_nat n')). specialize (H5 (Z.of_nat n')). rewrite <- H0 in H3. rewrite <- H3 in H5. lia.\n           } subst n'. assert (z <> i) by (unfold vgamma, UnionFindGraph.vgamma in Heqp; inversion Heqp; intro; apply H2; rewrite H9 in H7; rewrite H9; subst i; auto).\n           assert (weak_valid g' root) by (right; destruct H4; apply reachable_foot_valid in H4; auto).\n           assert (vvalid g' i) by (destruct H3 as [? _]; rewrite <- H3; apply H).\n           assert (~ reachable g' root i) by (apply (uf_equiv_not_reachable g g' i n0 z root); auto).\n           apply (exp_right (Graph_gen_redirect_parent g' i root H8 H9 H10)). apply (exp_right root). rewrite Znth_nat_inc_list. 2: rewrite H0; auto.\n           Opaque vgamma2cdata. Opaque vgamma. entailer !; [split|]. Transparent vgamma. Transparent vgamma2cdata.\n           ++ apply (graph_gen_redirect_parent_equiv g g' i n0 z); auto.\n           ++ apply (uf_root_gen_dst_same g' (liGraph g') i i root); auto.\n              ** rewrite <- (uf_equiv_root_the_same g g' i root); auto.\n                 apply (uf_root_edge _ (liGraph g) _ z); [| apply (vgamma_not_dst g i n0 z) | rewrite (uf_equiv_root_the_same g g')]; auto.\n              ** apply reachable_refl; auto.\n           ++ rewrite whole_graph_unfold. apply (exp_right n). entailer. unfold vgamma2cdata at 2. unfold vgamma at 2. unfold UnionFindGraph.vgamma.\n              cut ((upd_Znth i (map (fun x : Z => vgamma2cdata (vgamma (lg_gg g') x)) (nat_inc_list n))\n                             (Vint (Int.repr root), Vint (Int.repr (Z.of_nat (vlabel (lg_gg g') i))))) =\n                   (map (fun x : Z => vgamma2cdata (vgamma (lg_gg (Graph_gen_redirect_parent g' i root H8 H9 H10)) x)) (nat_inc_list n))); intros.\n              ** rewrite <- H15. apply derives_refl.\n              ** rewrite <- H0 in H. destruct H4. apply reachable_foot_valid in H4. rewrite <- H5 in H4. clear -H H4. rewrite <- upd_Znth_Graph_redirect_parent; auto.\n    + unfold vgamma2cdata at 1. unfold vgamma at 1. unfold UnionFindGraph.vgamma. forward. rewrite whole_graph_fold; [|intuition..]. apply (exp_right g).\n      simpl projT2. simpl id. apply (exp_right i). entailer !.\n      split; [|split]. 1: apply (uf_equiv_refl _  (liGraph g)). 2: rewrite <- H2; reflexivity. destruct (Z_lt_dec (dst (lg_gg g) i) 0).\n      * split. 1: apply reachable_refl; auto. intros. destruct H4 as [[? ?] ?]. destruct H4 as [[? ?] [? ?]]. simpl in H4. subst z. destruct l0.\n        -- simpl in H5. auto.\n        -- simpl in H6. destruct H6. assert (strong_evalid g z) by (destruct l0; [|destruct H6]; auto). destruct H8 as [? [? ?]]. symmetry in H4.\n           destruct (@only_one_edge _ _ _ _ _ _ (liGraph g) _ z H) as [? _]. specialize (H11 (conj H4 H8)). simpl in H11. subst z. rewrite <- H0 in H10.\n           destruct H10. assert (dst g i < 0) by apply l. exfalso; lia.\n      * destruct (vvalid_src_evalid _ (liGraph g) i H) as [_ ?]. destruct (valid_graph g _ H4) as [_ [? | ?]]. 1: simpl in H5; exfalso; auto. simpl id in *.\n        rewrite <- H0 in H5. rewrite <- H0 in H. apply repr_inj_unsigned in H2.\n        -- exfalso. rewrite H0 in H. assert (reachable g i i) by (apply reachable_refl; auto). pose proof (dst_not_reachable _ (liGraph g) _ _ _ H H2 H6). auto.\n        -- split. 1: lia. rewrite Z.lt_eq_cases. left. apply Z.lt_trans with (Int.max_signed / 8). 2: reflexivity. destruct H5. apply Z.lt_le_trans with (Z.of_nat n); auto.\n        -- split. 1: lia. rewrite Z.lt_eq_cases. left. apply Z.lt_trans with (Int.max_signed / 8). 2: compute; auto. destruct H. apply Z.lt_le_trans with (Z.of_nat n); auto.\n    + Intros g' rt. forward. apply (exp_right g'). apply (exp_right rt). entailer !.\nQed.\n\nLemma bounded_vertex: forall v n, 0 <= v < n -> n <= Int.max_signed / 8 -> Int.min_signed <= v <= Int.max_signed.\nProof.\n  intros. destruct H. split.\n  - apply Z.le_trans with 0; auto. rewrite Z.lt_eq_cases. left. apply Int.min_signed_neg.\n  - apply Z.le_trans with n. 1: rewrite Z.lt_eq_cases; left; auto. apply Z.le_trans with (Int.max_signed / 8); auto. rewrite Z.lt_eq_cases; left. apply Z_div_lt; intuition.\nQed.\n\nLemma body_union: semax_body Vprog Gprog f_Union union_spec.\nProof.\n  start_function.\n  forward_call (sh, g, subsets, x). Intros vret. destruct vret as [g1 x_root].\n  simpl fst in *. simpl snd in *.\n  assert (vvalid g1 y) by (destruct H1 as [? _]; rewrite <- H1; apply H0).\n  forward_call (sh, g1, subsets, y). Intros vret. destruct vret as [g2 y_root].\n  simpl fst in *. simpl snd in *.\n  forward_if\n    (PROP (x_root <> y_root)\n     LOCAL (temp _yroot (Vint (Int.repr y_root)); temp _xroot (Vint (Int.repr x_root));\n     temp _subsets (pointer_val_val subsets); temp _x (Vint (Int.repr x));\n     temp _y (Vint (Int.repr y)))  SEP (whole_graph sh g2 subsets)).\n  - forward. apply (exp_right g2). entailer. rewrite whole_graph_unfold. Intros n. apply prop_right. apply (the_same_root_union g g1 g2 x y y_root); auto.\n    assert (x_root = y_root). {\n      assert (Int.signed (Int.repr x_root) = Int.signed (Int.repr y_root)) by (rewrite H6; auto). rewrite !Int.signed_repr in H10; auto.\n      - apply (bounded_vertex _ (Z.of_nat n)); auto. destruct H5. apply reachable_foot_valid in H5. rewrite <- H8 in H5; auto.\n      - apply (bounded_vertex _ (Z.of_nat n)); auto. destruct H4. destruct H2. apply reachable_foot_valid in H2. rewrite H4 in H2. rewrite <- H8 in H2; auto.\n    } subst y_root. apply H2.\n  - forward. entailer!.\n  - rewrite whole_graph_unfold. Intros n.\n    assert (0 <= x_root < Z.of_nat n) by (destruct H4; destruct H2; apply reachable_foot_valid in H2; rewrite H4 in H2; rewrite <- H7 in H2; auto).\n    assert (H_XROOT_BOUND: 0 <= x_root < Zlength (nat_inc_list n)) by (rewrite Zlength_correct, nat_inc_list_length; apply H9). forward.\n    rewrite <- (map_id (nat_inc_list n)) at 1. rewrite Znth_nat_inc_list; auto. simpl id. unfold vgamma2cdata at 1. unfold vgamma at 1.\n    unfold UnionFindGraph.vgamma. assert (0 <= y_root < Z.of_nat n) by (destruct H5; apply reachable_foot_valid in H5; rewrite <- H7 in H5; auto).\n    assert (H_YROOT_BOUND: 0 <= y_root < Zlength (nat_inc_list n)) by (rewrite Zlength_correct, nat_inc_list_length; apply H10). forward.\n    rewrite <- (map_id (nat_inc_list n)) at 1. rewrite Znth_nat_inc_list; auto. unfold vgamma2cdata at 1. unfold vgamma at 1. unfold UnionFindGraph.vgamma. simpl id.\n    forward_if\n      (EX g': UFGraph,\n       PROP (uf_union g x y g')\n       LOCAL (temp _yRank (Vint (Int.repr (Z.of_nat (vlabel (lg_gg g2) y_root)))); temp _xRank (Vint (Int.repr (Z.of_nat (vlabel (lg_gg g2) x_root))));\n              temp _yroot (Vint (Int.repr y_root)); temp _xroot (Vint (Int.repr x_root)); temp _subsets (pointer_val_val subsets); temp _x (Vint (Int.repr x));\n              temp _y (Vint (Int.repr y)))\n       SEP (whole_graph sh g' subsets)).\n    + Opaque Znth. forward. rewrite Znth_nat_inc_list; auto.\n      assert (weak_valid g2 y_root) by (right; rewrite <- H7; auto). assert (vvalid g2 x_root) by (rewrite <- H7; auto).\n      assert (~ reachable g2 y_root x_root) by (intro; destruct H5; specialize (H15 _ H14); auto).\n      apply (exp_right (Graph_gen_redirect_parent g2 x_root y_root H12 H13 H14)). unfold vgamma2cdata at 2. unfold vgamma at 2. unfold UnionFindGraph.vgamma.\n      Opaque vgamma2cdata. Opaque vgamma. entailer !. Transparent vgamma. Transparent vgamma2cdata.\n      * apply (diff_root_union_1 g g1 g2 x y x_root y_root); auto.\n      * rewrite whole_graph_unfold. apply (exp_right n). rewrite <- upd_Znth_Graph_redirect_parent; auto. entailer!.\n    + assert (weak_valid g2 x_root) by (right; rewrite <- H7; auto). assert (vvalid g2 y_root) by (rewrite <- H7; auto).\n      assert (~ reachable g2 x_root y_root) by (intro; rewrite (uf_equiv_root_the_same g1 g2) in H2; auto; destruct H2; specialize (H15 _ H14); auto).\n      forward_if\n        (EX g': UFGraph,\n         PROP (uf_union g x y g')\n         LOCAL (temp _yRank (Vint (Int.repr (Z.of_nat (vlabel (lg_gg g2) y_root)))); temp _xRank (Vint (Int.repr (Z.of_nat (vlabel (lg_gg g2) x_root))));\n                temp _yroot (Vint (Int.repr y_root)); temp _xroot (Vint (Int.repr x_root)); temp _subsets (pointer_val_val subsets); temp _x (Vint (Int.repr x));\n                temp _y (Vint (Int.repr y)))\n         SEP (whole_graph sh g' subsets)).\n      * forward. rewrite Znth_nat_inc_list; auto. apply (exp_right (Graph_gen_redirect_parent g2 y_root x_root H12 H13 H14)). unfold vgamma2cdata at 2. unfold vgamma at 2.\n        unfold UnionFindGraph.vgamma. Opaque vgamma2cdata. Opaque vgamma. entailer!. Transparent vgamma. Transparent vgamma2cdata.\n        -- apply (diff_root_union_2 g g1 g2 x y x_root y_root); auto.\n        -- rewrite whole_graph_unfold. apply (exp_right n). rewrite <- upd_Znth_Graph_redirect_parent; auto. entailer!.\n      * forward. rewrite Znth_nat_inc_list; auto. remember (Graph_gen_redirect_parent g2 y_root x_root H12 H13 H14) as g3.\n        assert (uf_union g x y g3) by (rewrite Heqg3; simpl; apply (diff_root_union_2 g g1 g2 x y x_root y_root); auto).\n        unfold vgamma2cdata at 2. unfold vgamma at 2. unfold UnionFindGraph.vgamma. forward. apply (exp_right (Graph_vgen g3 x_root ((vlabel (lg_gg g2) x_root) + 1)%nat)).\n        Opaque vgamma2cdata. Opaque vgamma. entailer !. Transparent vgamma. Transparent vgamma2cdata.\n        rewrite upd_Znth_diff; auto; [|rewrite Zlength_map, Zlength_correct, nat_inc_list_length; auto..]. rewrite Znth_nat_inc_list; auto.\n        rewrite whole_graph_unfold. apply (exp_right n). entailer !.\n        cut (upd_Znth x_root (upd_Znth y_root (map (fun x0 : Z => vgamma2cdata (vgamma (lg_gg g2) x0)) (nat_inc_list n))\n                                        (Vint (Int.repr x_root), Vint (Int.repr (Z.of_nat (vlabel (lg_gg g2) y_root)))))\n                       (let (x0, _) := vgamma2cdata (vgamma (lg_gg g2) x_root) in x0, Vint (Int.repr (Z.of_nat (vlabel (lg_gg g2) x_root) + 1))) =\n             map (fun x0 : Z => vgamma2cdata (vgamma (lg_gg (Graph_vgen (Graph_gen_redirect_parent g2 y_root x_root H12 H13 H14) x_root\n                                                                        (vlabel (lg_gg g2) x_root + 1)%nat)) x0)) (nat_inc_list n)); intros.\n        -- rewrite <- H23. apply derives_refl.\n        -- clear -H6 H9 H10. assert (Zlength (map (fun m : Z => vgamma2cdata (vgamma (lg_gg g2) m)) (nat_inc_list n)) = Z.of_nat n) by\n               (rewrite Zlength_map, Zlength_correct, nat_inc_list_length; auto).\n           assert (Zlength (upd_Znth y_root (map (fun x0 : Z => vgamma2cdata (vgamma (lg_gg g2) x0)) (nat_inc_list n))\n                                     (Vint (Int.repr x_root), Vint (Int.repr (Z.of_nat (vlabel (lg_gg g2) y_root))))) = Z.of_nat n) by\n               (rewrite upd_Znth_Zlength; auto; rewrite <- H in H10; auto). apply (list_eq_Znth _ _ n).\n           ++ rewrite <- (Nat2Z.id n) at 2. rewrite <- Zlength_length. 2: lia. rewrite <- H in H10, H9. rewrite upd_Znth_Zlength; auto; rewrite upd_Znth_Zlength; auto.\n           ++ rewrite list_length_map, nat_inc_list_length; auto.\n           ++ intros. rewrite Znth_nat_inc_list; auto. rewrite (upd_Znth_lookup' (Z.of_nat n)); auto. rewrite (upd_Znth_lookup' (Z.of_nat n)); auto.\n              rewrite Znth_nat_inc_list; auto. unfold vgamma2cdata, vgamma, UnionFindGraph.vgamma. simpl.\n              unfold graph_gen.updateEdgeFunc, graph_gen.update_vlabel, EquivDec.equiv_dec, Z_EqDec, zeq. destruct (Z.eq_dec j x_root).\n              ** subst j. destruct (Z.eq_dec y_root x_root). 1: exfalso; auto. destruct (Z.eq_dec x_root x_root). 2: exfalso; apply n1; auto. do 3 f_equal.\n                 transitivity (Z.succ (Z.of_nat (vlabel (lg_gg g2) x_root))). 2: rewrite <- Nat2Z.inj_succ; f_equal; unfold Z_EqDec; lia. rewrite Z.add_1_r. auto.\n              ** destruct (Z.eq_dec j y_root).\n                 --- subst j. destruct (Z.eq_dec y_root y_root). 2: exfalso; apply n1; auto. destruct (Z.eq_dec x_root y_root). 1: exfalso; auto. destruct (Z_lt_dec x_root 0).\n                     1: destruct H9; exfalso; lia. auto.\n                 --- destruct (Z.eq_dec y_root j). 1: exfalso; apply n1; auto. destruct (Z.eq_dec x_root j). 1: exfalso; auto. auto.\n    + Intros g'. apply (exp_right g'). entailer!.\nQed.\n", "meta": {"author": "CertiGraph", "repo": "CertiGraph", "sha": "1be51414c139f8bc16b3e22f72989e454c37ce3c", "save_path": "github-repos/coq/CertiGraph-CertiGraph", "path": "github-repos/coq/CertiGraph-CertiGraph/CertiGraph-1be51414c139f8bc16b3e22f72989e454c37ce3c/unionfind/bak_verif_unionfind_arr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.26608269638833787}}
{"text": "(*  ----------------------------------------------------------- *)\n\nRecord Foldable1__Dict (t : Type -> Type) := Foldable1__Dict_Build {\n  foldl1__ : forall {a}, (a -> a -> a) -> t a -> a  }.\n\nDefinition Foldable1 a :=\n  forall r, (Foldable1__Dict a -> r) -> r.\n\nExisting Class Foldable1.\n\nDefinition foldl1 `{g : Foldable1 t} : forall {a}, (a -> a -> a) -> t a -> a :=\n  g _ (foldl1__ t).\n\nDefinition Digit_foldl1 {a} (f : a -> a -> a) (t : Digit a) : a :=\n  match t with\n  | One x => x\n  | Two x y => f x y\n  | Three x y z => f (f x y) z\n  | Four x y z w => f (f (f x y) z) w\n  end.\n\n(*  ----------------------------------------------------------- *)\n\nProgram Instance Foldable1_Digit : Foldable1 Digit := fun _ k =>\n  k {| foldl1__ := fun {a} => Digit_foldl1 |}.\n\n(*  ----------------------------------------------------------- *)\n\nInstance Unpeel_Elem a : GHC.Prim.Unpeel (Elem a) a :=\n  GHC.Prim.Build_Unpeel _ _ (fun x => match x with Mk_Elem y => y end) Mk_Elem.\n\n(*  ----------------------------------------------------------- *)\n\nNotation \"'_:<_'\" := (op_ZCzl__).\n\nInfix \":<\" := (_:<_) (at level 99).\n\nNotation \"'_:>_'\" := (op_ZCzg__).\n\nInfix \":>\" := (_:>_) (at level 99).\n\nNotation \"'_:&_'\" := (op_ZCza__).\n\nInfix \":&\" := (_:&_) (at level 99).\n\n\n(*  ----------------------------------------------------------- *)\n(* CHANGE to Default.panic *)\n\nParameter error : forall {a}, a.\n\n(* Move to base: missing record selectors *)\nDefinition runIdentity {a} (x: Data.Functor.Identity.Identity a) : a :=\n  match x with\n  | Data.Functor.Identity.Mk_Identity y => y\n  end.\n\nDefinition unwrapMonad {m}{a} (x: Control.Applicative.WrappedMonad m a) :=\n  match x with\n  | Control.Applicative.WrapMonad y => y\n  end.\n\n(*  ----------------------------------------------------------- *)\n(* Needs a termination argument *)\n\nDefinition map_elem {a} : list a -> list (Elem a) := fun xs => GHC.Prim.coerce xs.\nDefinition getNodes {a} : GHC.Num.Int -> a -> list a -> (list (Node a) * Digit a)%type :=\n    fix getNodes arg_1__ arg_2__ arg_3__\n          := let j_9__ :=\n               match arg_1__ , arg_2__ , arg_3__ with\n                 | _ , x1 , nil => pair nil (One x1)\n                 | _ , x1 , cons x2 nil => pair nil (Two x1 x2)\n                 | _ , x1 , cons x2 (cons x3 nil) => pair nil (Three x1 x2 x3)\n                 | s , x1 , cons x2 (cons x3 (cons x4 xs)) =>\n                   match getNodes s x4 xs with\n                   | pair ns d => pair (cons (Node3 s x1 x2 x3) ns) d\n                   end\n               end in\n             match arg_1__ , arg_2__ , arg_3__ with\n             | arg , _ , _ => j_9__\n             end.\n\n(*\nRequire Import Omega.\nProgram Fixpoint  mkTree {a} `{(Sized a)} (s: GHC.Num.Int) (x : list a) {measure (length x)} : FingerTree a :=\n    match x with\n    | nil => Empty\n    | cons x1 nil => Single x1\n    | cons x1 (cons x2 nil) => Deep (GHC.Num.fromInteger 2 GHC.Num.* s) (One x1)\n                                   Empty (One x2)\n    | cons x1 (cons x2 (cons x3 nil)) => Deep (GHC.Num.fromInteger 3 GHC.Num.*\n                                                                  s) (One x1) Empty (Two x2 x3)\n    | cons x1 (cons x2 (cons x3 (cons x4 xs))) =>\n      match getNodes (GHC.Num.fromInteger 3 GHC.Num.* s) x4 xs with\n      | pair ns sf => match mkTree (GHC.Num.fromInteger 3 GHC.Num.* s) ns with\n                     | m => GHC.Prim.seq m (Deep (((GHC.Num.fromInteger 3 GHC.Num.* size x1)\n                                                    GHC.Num.+ size m)\n                                                   GHC.Num.+ size sf)\n                                                (Three x1 x2 x3) m sf)\n                     end\n      end\n    end.\nObligation 1.\nadmit.\nAdmitted.\n\nDefinition fromList {a} : list a -> Seq a :=\n  Mk_Seq GHC.Base.∘ ((@mkTree (Elem a) _ (GHC.Num.fromInteger 1)) GHC.Base.∘ map_elem). *)\n\n(*  ----------------------------------------------------------- *)\n\nDefinition  mapWithIndexNode {a} {b} `{Sized a}\n                             : (GHC.Num.Int -> a -> b) -> GHC.Num.Int -> Node a -> Node b :=\n                             fun arg_2__ arg_3__ arg_4__ =>\n                               match arg_2__ , arg_3__ , arg_4__ with\n                                 | f , s , Node2 ns a b => let sPsa := s GHC.Num.+ size a in\n                                                           GHC.Prim.seq sPsa (Node2 ns (f s a) (f sPsa b))\n                                 | f , s , Node3 ns a b c => let sPsa := s GHC.Num.+ size a in\n                                                             let sPsab := sPsa GHC.Num.+ size b in\n                                                             GHC.Prim.seq sPsa (GHC.Prim.seq sPsab (Node3 ns (f s a) (f\n                                                                                                                     sPsa\n                                                                                                                     b)\n                                                                                             (f sPsab c)))\n                               end.\n\nDefinition  mapWithIndexDigit {a} {b} `{Sized a}\n  : (GHC.Num.Int -> a -> b) -> GHC.Num.Int -> Digit a -> Digit b :=\n  fun arg_11__ arg_12__ arg_13__ =>\n    match arg_11__ , arg_12__ , arg_13__ with\n    | f , s , One a => One (f s a)\n    | f , s , Two a b => let sPsa := s GHC.Num.+ size a in\n                        GHC.Prim.seq sPsa (Two (f s a) (f sPsa b))\n    | f , s , Three a b c => let sPsa := s GHC.Num.+ size a in\n                            let sPsab := sPsa GHC.Num.+ size b in\n                            GHC.Prim.seq sPsa (GHC.Prim.seq sPsab (Three (f s a) (f sPsa\n                                                                                    b) (f\n                                                                                          sPsab\n                                                                                          c)))\n    | f , s , Four a b c d => let sPsa := s GHC.Num.+ size a in\n                             let sPsab := sPsa GHC.Num.+ size b in\n                             let sPsabc := sPsab GHC.Num.+ size c in\n                             GHC.Prim.seq sPsa (GHC.Prim.seq sPsab (GHC.Prim.seq sPsabc\n                                                                                 (Four (f\n                                                                                          s\n                                                                                          a)\n                                                                                       (f sPsa\n                                                                                          b) (f\n                                                                                                sPsab\n                                                                                                c) (f\n                                                                                                      sPsabc\n                                                                                                      d))))\n    end.\n\n(*\nFixpoint mapWithIndexTree {a} {b} `{Sized a} (f : GHC.Num.Int -> a -> b) (s : GHC.Num.Int) (ft: FingerTree a) : FingerTree b :=\n  match ft with\n  | Empty => GHC.Prim.seq s Empty\n  | Single xs => Single GHC.Base.$ f s xs\n  | Deep n pr m sf => let sPsprm := (s GHC.Num.+ n) GHC.Num.- size sf in\n                             let sPspr := s GHC.Num.+ size pr in\n                             GHC.Prim.seq sPspr (GHC.Prim.seq sPsprm (Deep n\n                                                                           (mapWithIndexDigit\n                                                                              f s pr)\n                                                                           (mapWithIndexTree\n                                                                              (mapWithIndexNode\n                                                                                 f) sPspr m)\n                                                                           (mapWithIndexDigit\n                                                                              f sPsprm sf)))\n  end.\n\nDefinition mapWithIndex {a} {b} : (GHC.Num.Int -> a -> b) -> Seq a -> Seq b :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__ , arg_1__ with\n      | f' , Mk_Seq xs' =>  Mk_Seq GHC.Base.$ mapWithIndexTree (fun arg_34__ arg_35__ =>\n                                                                match arg_34__ , arg_35__ with\n                                                                  | s , Mk_Elem a => Mk_Elem (f' s a)\n                                                                end) (GHC.Num.fromInteger 0) xs'\n    end.\n*)\n\n(* ---------------------------------------- *)\n\nParameter viewLTree : forall {a} `{Sized a}, (FingerTree a) -> Maybe2 a (FingerTree a).\n(*\nFixpoint viewLTree {a} `{Sized a} ( arg_0__ : FingerTree a) : Maybe2 a (FingerTree a) :=\n  let pullL {a} : GHC.Num.Int -> FingerTree (Node a) -> Digit\n                       a -> FingerTree a :=\n  fun s m sf =>\n    match viewLTree m with\n      | Nothing2 => digitToTree' s sf\n      | Just2 pr m' => Deep s (nodeToDigit pr) m' sf\n    end in\n\n    match arg_0__ with\n      | Empty => Nothing2\n      | Single a => Just2 a Empty\n      | Deep s (One a) m sf => Just2 a (pullL (s GHC.Num.- size a) m sf)\n      | Deep s (Two a b) m sf => Just2 a (Deep (s GHC.Num.- size a) (One b) m sf)\n      | Deep s (Three a b c) m sf => Just2 a (Deep (s GHC.Num.- size a) (Two b c) m\n                                             sf)\n      | Deep s (Four a b c d) m sf => Just2 a (Deep (s GHC.Num.- size a) (Three b c d)\n                                              m sf)\n    end. *)\n\nParameter viewRTree : forall {a} `{Sized a}, (FingerTree a) -> Maybe2 (FingerTree a) a.\n\n(*\nFixpoint viewRTree {a} `{Sized a} (arg_0__ : FingerTree a) : Maybe2 (FingerTree a) a :=\n  let pullR {a} : GHC.Num.Int -> Digit a -> FingerTree (Node\n                                                            a) -> FingerTree a :=\n  fun s pr m =>\n    match viewRTree m with\n      | Nothing2 => digitToTree' s pr\n      | Just2 m' sf => Deep s pr m' (nodeToDigit sf)\n    end in\n\n    match arg_0__ with\n      | Empty => Nothing2\n      | Single z => Just2 Empty z\n      | Deep s pr m (One z) => Just2 (pullR (s GHC.Num.- size z) pr m) z\n      | Deep s pr m (Two y z) => Just2 (Deep (s GHC.Num.- size z) pr m (One y)) z\n      | Deep s pr m (Three x y z) => Just2 (Deep (s GHC.Num.- size z) pr m (Two x y))\n                                     z\n      | Deep s pr m (Four w x y z) => Just2 (Deep (s GHC.Num.- size z) pr m (Three w x\n                                                                            y)) z\n    end.\n*)\n\n(*\nFixpoint initsTree {a} {b} `{_:Sized a} (f : (FingerTree a) -> b) (arg_1__ : FingerTree a) : FingerTree b :=\n      match arg_1__ with\n             | Empty => Empty\n             | Single x => Single (f (Single x))\n             | Deep n pr m sf =>\n                let f' := fun ms =>\n                            (match viewRTree ms with\n                            | Just2 m' node => GHC.Base.fmap (fun sf' => f (deep pr m' sf')) (initsNode node)\n                            | Nothing2 => error\n                            end) in\n                Deep n (GHC.Base.fmap (f GHC.Base.∘ digitToTree) (initsDigit pr)) (initsTree f' m)\n                     (GHC.Base.fmap (f GHC.Base.∘ deep pr m) (initsDigit sf))\n           end. *)\n\nParameter applicativeTree : forall {f} {a} `{GHC.Base.Applicative f},\n     GHC.Num.Int -> GHC.Num.Int -> f a -> f (FingerTree a).\n\nParameter cycleNMiddle : forall {c}, GHC.Num.Int -> Rigid c -> FingerTree (Node c).\n\nParameter initsTree : forall {a} {b} `{_:Sized a}, ((FingerTree a) -> b) -> (FingerTree a) -> FingerTree b.\n\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/module-edits/Data/Sequence/Internal/midamble.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.26604922152065086}}
{"text": "Require Import MirrorCore.Lambda.ExprCore.\nRequire Import MirrorCore.Lambda.ExprD.\nRequire Import MirrorCore.Lambda.Red.\nRequire Import MirrorCore.Lambda.ExprLift.\nRequire Import MirrorCore.TypesI.\nRequire Import MirrorCore.SymI.\nRequire Import MirrorCore.ExprI.\n\nRequire Import ExtLib.Core.RelDec.\nRequire Import ExtLib.Data.Fun.\nRequire Import ExtLib.Data.Nat.\nRequire Import ExtLib.Tactics.\nRequire Import MirrorCore.syms.SymSum.\n\nRequire Import Charge.SetoidRewrite.AutoSetoidRewrite.\nRequire Import Charge.ModularFunc.BaseFunc.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nSection SetoidRewrite.\n  Context {typ func : Type} {RType_typ : RType typ}.\n  Context {HB : BaseFunc typ func}.\n\n  Context {RelDec_typ_eq : RelDec (@eq typ)}\n          {RelDecCorrect_typ_eq : RelDec_Correct RelDec_typ_eq}.\n\n  Context {RelDec_func_eq : RelDec (@eq (expr typ func))}.\n\n  Let Rbase := expr typ func.\n\n  Definition m (T : Type) : Type :=\n    rsubst Rbase -> option (T * rsubst Rbase).\n\n  Definition rewriter :=\n    expr typ func ->\n    list (AutoSetoidRewrite.RG Rbase) ->\n    AutoSetoidRewrite.RG Rbase -> m (expr typ func).\n    \n  Definition rw_type :=\n    expr typ func -> list (RG Rbase) -> RG Rbase -> m (expr typ func).\n\n  Definition rw_under (r : RG Rbase) (rw : rw_type) : rw_type :=\n    fun e rvars => rw e (r :: rvars).\n\n  Definition rg_bind {T U} (a : m T) (b : T -> m U) : m U :=\n    fun s => match a s with\n               | None => None\n               | Some (val,s') => b val s'\n             end.\n             \n  Definition rg_fail {T} : m T := fun _ => None.\n  Definition rg_ret {T} (v : T) : m T := fun s => Some (v, s).\n  Definition rg_plus {T} (l r : m T) : m T :=\n    fun s =>\n      let v := l s in\n      match v with\n        | None => r s\n        | Some _ => v\n      end.\n  Definition rg_fmap {T U} (f : T -> U) (l : m T) : m U :=\n    fun s =>\n      match l s with\n        | None => None\n        | Some (x,y) => Some (f x, y)\n      end.\n\n  Section do_several.\n    Variable (rw : rewriter).\n\n    Fixpoint do_several (n : nat) a b c {struct n} :=\n      match n with\n        | 0 => rg_ret a\n        | S n => fun d => match rw a b c d with\n                            | None => rg_ret a d\n                            | Some (a',d') => do_several n a' b c d'\n                          end\n      end.\n  End do_several.\n\n  Section do_severalK.\n    Variable (rw : rewriter -> rewriter).\n\n    Fixpoint do_severalK  (n : nat) (rw' : rewriter)\n             (a : expr typ func) (b : list (AutoSetoidRewrite.RG Rbase))\n             (c :  AutoSetoidRewrite.RG Rbase) {struct n} :=\n      match n with\n        | 0 => rg_ret a\n        | S n => fun d =>\n                   AutoSetoidRewrite.tryRewrite\n                     (rw (fun a b c d => do_severalK n rw' a b c d))\n                     a b c d\n      end.\n  End do_severalK.\n\n  Definition rw_fail : rewriter := fun _ _ _ => rg_fail.\n\n  Definition sr_combine (f g : expr typ func -> list (RG (expr typ func)) -> RG (expr typ func) -> m (expr typ func))\n    (e : (expr typ func)) (rvars : list (RG (expr typ func))) (rg : RG (expr typ func)) :\n  \tm (expr typ func) :=\n    rg_plus (f e rvars rg) (g e rvars rg).\n\n  Definition sr_combineK (f g : rw_type -> rw_type)\n             (k : rw_type)\n             (e : (expr typ func)) (rvars : list (AutoSetoidRewrite.RG (expr typ func))) (rg : AutoSetoidRewrite.RG (expr typ func)) :\n    m (expr typ func) :=\n    rg_plus (f k e rvars rg) (g k e rvars rg).\n\n  Definition setoid_rewrite vars := \n  fun (RelDec_func_eq : RelDec.RelDec eq) =>\n  let Rbase := expr typ func in\n  fun (rel : typ -> Rbase)\n    (rewrite_start : rewriter)\n    (rewrite_respects : rewriter)\n    (rewrite_exs : rewriter -> rewriter)\n    (l : typ) (e : expr typ func) =>\n    (AutoSetoidRewrite.setoid_rewrite\n       RelDec.rel_dec\n       rewrite_start\n       rewrite_respects\n       (do_severalK rewrite_exs 1024 (fun a _ _ => rg_ret a)))\n      e (map (fun t => RGinj (Inj (fEq t))) vars) (AutoSetoidRewrite.RGinj (rel l))\n      (AutoSetoidRewrite.rsubst_empty Rbase).\n\nEnd SetoidRewrite.", "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/SetoidRewrite/Base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2660492152990642}}
{"text": "Require Export MinBFTcount.\nRequire Export MinBFTacc_exec.\nRequire Export MinBFTacc_new.\nRequire Export MinBFTvreq_mon.\n\n\nSection MinBFTprops1.\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 accepted_counter_if_know_UI_primary :\n    forall {eo    : EventOrdering}\n           (e     : Event)\n           (R     : Rep)\n           (r     : Request)\n           (i     : nat)\n           (l     : list name),\n      In (send_accept (accept r i) l) (M_output_ls_on_event (MinBFTlocalSys R) e)\n      ->\n      exists (s  : MAIN_state)\n             (s1 : USIG_state)\n             (s2 : LOG_state)\n             (ui : UI),\n        M_run_ls_on_event (MinBFTlocalSys R) e = Some (MinBFTlocalSys_new R s s1 s2)\n        /\\ kc_knows (minbft_data_rdata (request_data (current_view s) r ui)) s2\n        /\\ kc_Tknows ui s2\n        /\\ kc_trust2owner ui = Some (MinBFTprimary (current_view s))\n        /\\ kc_trust_has_id ui i.\n  Proof.\n    introv h.\n    apply accepted_counter_if_received_UI_primary in h.\n    exrepnd.\n    exists s s1 s2 ui.\n    simpl.\n    dands; auto; unfold MinBFT_data_knows; simpl; subst; allrw; eauto 3 with minbft;[].\n    unfold request_data_in_log; simpl.\n    allrw <-; autorewrite with minbft; allrw; auto.\n  Qed.\n\n  Lemma kc_Tknows_implies :\n    forall  (ui : UI) (l : LOG_state),\n      kc_Tknows ui l\n      -> exists en,\n        In en l                     (* FIX: Do we need this one instead? find_entry rd l = Some e *)\n        /\\ ui_in_log ui l = true    (* FIX: do we need this one? *)\n        /\\\n        (\n          (exists rd, request_data2ui rd = ui )\n          \\/\n          (In ui (log_entry_commits en))\n        ).\n  Proof.\n    introv H.\n    unfold kc_Tknows in *.\n    unfold kc_knows in *. simpl in *.\n    unfold MinBFT_data_knows in *.\n    unfold MinBFT_data_in_log in *.\n\n    unfold ui_in_log in *.\n    eapply existsb_exists in H.\n    exrepnd.\n    rename x into en.\n\n    unfold ui_in_log_entry in *.\n    dest_cases w;[|].\n    {\n      exists en; dands; eauto.\n      eapply existsb_exists.\n      exists en. dands; eauto.\n      dest_cases x.\n    }\n    {\n      dest_cases x;[].\n      exists en; dands; eauto.\n      eapply existsb_exists.\n      exists en; dands; eauto.\n      dest_cases x;[].\n      dest_cases y.\n    }\n  Qed.\n\n(*  Lemma uis_where_verified :\n    forall {eo : EventOrdering} (e : Event) (l : LOG_state) (u : USIG_state) (ui : UI),\n      is_replica e\n      -> M_state_sys_on_event MinBFTsys e LOGname = Some l\n      -> M_state_sys_on_event MinBFTsys e USIGname = Some u\n      -> kc_Tknows ui l\n      ->\n      exists hd,\n        kc_knows (minbft_data_hdata hd) l\n        /\\ verify_hash_usig hd (ui2digest ui) (usig_local_keys u) = true.\n  Proof.\n    introv isr eqst1 eqst2 unl.\n\n    unfold kc_Tknows in unl; simpl in unl.\n    unfold MinBFT_data_knows in unl; simpl in unl.\n\n    rewrite M_state_sys_on_event_unfold in eqst1.\n    rewrite M_state_sys_on_event_unfold in eqst2.\n\n    apply map_option_Some in eqst1.\n    apply map_option_Some in eqst2.\n    exrepnd; try rev_Some.\n\n    rewrite eqst1 in eqst2; ginv.\n\n    unfold is_replica in *; exrepnd.\n\n    revert dependent u.\n    revert dependent l.\n    revert dependent a.\n    rewrite isr0; simpl.\n\n    (* WARNING *)\n    clear isr0.\n\n    induction e as [e ind] using predHappenedBeforeInd;[]; introv run stl inlog stu.\n\n    rewrite M_run_ls_on_event_unroll in run.\n    rewrite M_run_ls_before_event_unroll_on in run.\n\n    destruct (dec_isFirst e) as [d|d].\n\n    {\n      clear ind.\n\n      unfold M_run_ls_on_this_one_event in run; simpl in *.\n      apply map_option_Some in run; exrepnd; rev_Some.\n      unfold M_break in run0; simpl in *; smash_minbft; repnd; simpl in *.\n      apply option_map_Some in run0; exrepnd; subst; simpl in *.\n\n      minbft_dest_msg Case a0; simpl in *;\n        try (complete (inversion Heqx; subst; simpl in *;\n                       unfold state_of_subcomponents in *;\n                       simpl in *; ginv));\n        [| |].\n\n      { Case \"Request\".\n\n        unfold call_create_ui, bind in *; simpl in *.\n        inversion Heqx; subst; simpl in *; clear Heqx;\n          unfold state_of_subcomponents in *; simpl in *; ginv.\n        unfold ui_in_log in *; simpl in *.\n        unfold ui_in_log_entry in *; simpl in *.\n        smash_minbft; simpl in *.\n        unfold MinBFT_data_knows; simpl.\n        unfold hash_data_in_log_entry, RequestData2HashData; simpl.\n        exists (Build_HashData initial_view (request_b m) (Build_preUI r 1)).\n        simpl; smash_minbft; GC; dands; auto. }\n\n      { Case \"Prepare\".\n\n        unfold call_verify_ui, bind in *; simpl in *; smash_minbft;\n          try (complete (unfold state_of_subcomponents in *; simpl in *;\n                         ginv; eapply ind in run1; eauto; eauto 3 with eo)).\n\n        { unfold state_of_subcomponents in *; simpl in *; ginv.\n          unfold ui2rep, ui_in_log in *; simpl in *; autorewrite with bool in *; subst.\n          unfold ui_in_log_entry in *; simpl in *; autorewrite with minbft in *; smash_minbft.\n          unfold verify_UI in *; simpl in *; autorewrite with minbft in *.\n          exists (prepare2hash_data p); dands; auto.\n          unfold MinBFT_data_knows; simpl.\n          unfold hash_data_in_log_entry; simpl; smash_minbft. }\n\n        { unfold state_of_subcomponents in *; simpl in *; ginv.\n          unfold ui2rep, ui_in_log in *; simpl in *; autorewrite with bool in *; subst.\n          unfold ui_in_log_entry in *; simpl in *; autorewrite with minbft in *; smash_minbft.\n\n          { unfold verify_UI in *; simpl in *; autorewrite with minbft in *.\n            exists (prepare2hash_data p); dands; auto.\n            unfold MinBFT_data_knows; simpl.\n            unfold hash_data_in_log_entry; simpl; smash_minbft. }\n\n          { exists (Build_HashData\n                      (prepare2view p)\n                      (request_b (prepare2request p))\n                      (Build_preUI r 1)); simpl.\n            autorewrite with minbft; dands; auto.\n            unfold MinBFT_data_knows; simpl.\n            unfold hash_data_in_log_entry; simpl; smash_minbft. } }\n\n        { unfold state_of_subcomponents in *; simpl in *; ginv.\n          unfold ui2rep, ui_in_log in *; simpl in *; autorewrite with bool in *; subst.\n          unfold ui_in_log_entry in *; simpl in *; autorewrite with minbft in *; smash_minbft.\n\n          { unfold verify_UI in *; simpl in *; autorewrite with minbft in *.\n            exists (prepare2hash_data p); dands; auto.\n            unfold MinBFT_data_knows; simpl.\n            unfold hash_data_in_log_entry; simpl; smash_minbft. }\n\n          { unfold invalid_prepare in *; smash_minbft.\n            apply valid_prepare_implies_view in Heqx0; rewrite Heqx0 in *.\n            autorewrite with minbft in *; tcsp. } }\n      }\n\n      { Case \"Commit\".\n        unfold call_verify_ui, bind in *; simpl in *; smash_minbft;\n          try (complete (unfold state_of_subcomponents in *; simpl in *; ginv));[].\n\n        unfold call_prepare_already_in_log, bind_pair, bind in *; simpl in *; smash_minbft;[].\n        unfold call_log_commit, bind in *; simpl in *; smash_minbft;[|].\n\n        { unfold invalid_commit, valid_commit in *; smash_minbft. }\n\n        { unfold call_is_committed, bind in *; simpl in *; smash_minbft;[|].\n\n          { unfold state_of_subcomponents in *; simpl in *; ginv; simpl in *.\n            smash_minbft; repndors; ginv.\n            unfold ui_in_log_entry in *; simpl in *; autorewrite with minbft in *; smash_minbft;[|].\n\n            { exists (commit2hash_data_i c).\n              unfold verify_UI in *; autorewrite with minbft in *; dands; auto.\n              unfold MinBFT_data_knows; simpl.\n              unfold hash_data_in_log_entry; simpl; smash_minbft. }\n\n            { unfold add_commit2commits, ui2rep in *; simpl in *; smash_minbft;\n                repndors; subst; tcsp;[| |].\n              { exists (Build_HashData\n                          (commit2view c)\n                          (request_b (commit2request c))\n                          (Build_preUI (commit2sender_j c) 1)); simpl.\n                autorewrite with minbft; dands; auto.\n                unfold MinBFT_data_knows; simpl.\n                unfold hash_data_in_log_entry; simpl; smash_minbft; tcsp. }\n              { exists (commit2hash_data_j c).\n                unfold verify_UI in *; autorewrite with minbft in *; dands; auto.\n                unfold MinBFT_data_knows; simpl.\n                unfold hash_data_in_log_entry; simpl; smash_minbft. }\n              { unfold ui2digest; simpl.\n                exists (Build_HashData\n                          (commit2view c)\n                          (request_b (commit2request c))\n                          (Build_preUI r 1)); simpl.\n                autorewrite with minbft; dands; auto;[].\n                unfold MinBFT_data_knows; simpl.\n                unfold hash_data_in_log_entry; simpl; smash_minbft; tcsp. }\n            }\n          }\n\n          { unfold state_of_subcomponents in *; simpl in *; ginv.\n            unfold ui_in_log in *; simpl in *; autorewrite with bool in *.\n            unfold ui_in_log_entry in *; simpl in *; smash_minbft;[|].\n\n            { exists (commit2hash_data_i c).\n              unfold verify_UI in *; autorewrite with minbft in *; dands; auto.\n              unfold MinBFT_data_knows; simpl.\n              unfold hash_data_in_log_entry; simpl; smash_minbft. }\n\n            { unfold add_commit2commits, ui2rep in *; simpl in *; smash_minbft;\n                repndors; subst; tcsp;[| |].\n              { exists (Build_HashData\n                          (commit2view c)\n                          (request_b (commit2request c))\n                          (Build_preUI (commit2sender_j c) 1)); simpl.\n                autorewrite with minbft; dands; auto.\n                unfold MinBFT_data_knows; simpl.\n                unfold hash_data_in_log_entry; simpl; smash_minbft; tcsp. }\n              { exists (commit2hash_data_j c).\n                unfold verify_UI in *; autorewrite with minbft in *; dands; auto.\n                unfold MinBFT_data_knows; simpl.\n                unfold hash_data_in_log_entry; simpl; smash_minbft. }\n              { unfold ui2digest; simpl.\n                exists (Build_HashData\n                          (commit2view c)\n                          (request_b (commit2request c))\n                          (Build_preUI r 1)); simpl.\n                autorewrite with minbft; dands; auto;[].\n                unfold MinBFT_data_knows; simpl.\n                unfold hash_data_in_log_entry; simpl; smash_minbft; tcsp. }\n            }\n          }\n        }\n      }\n    }\n\n    {\n      apply map_option_Some in run; exrepnd; rev_Some.\n      applydup M_run_ls_on_event_ls_is_minbft in run1; exrepnd; subst.\n\n      unfold M_run_ls_on_this_one_event in run0; simpl in *.\n      apply map_option_Some in run0; exrepnd; rev_Some.\n      unfold M_break in run2; simpl in *; smash_minbft; repnd; simpl in *.\n      apply option_map_Some in run2; exrepnd; subst; simpl in *.\n\n      minbft_dest_msg Case a0; simpl in *;\n        try (complete (inversion Heqx; subst; simpl in *;\n                       unfold state_of_subcomponents in *;\n                       simpl in *; ginv;\n                       eapply ind in run1; eauto; eauto 3 with eo));\n        [| |].\n\n      { Case \"Request\".\n\n        unfold call_create_ui, bind in *; simpl in *.\n        inversion Heqx; subst; simpl in *; clear Heqx;\n          unfold state_of_subcomponents in *; simpl in *; ginv.\n\n        rewrite ui_in_log_log_new_prepare in inlog; simpl in *.\n        smash_minbft; simpl in *.\n\n        { unfold MinBFT_data_knows; simpl.\n          exists (Build_HashData\n                    (current_view s)\n                    (request_b m)\n                    (Build_preUI (usig_id s1) (S (usig_counter s1)))).\n          rewrite hash_data_in_log_log_new_prepare.\n          Opaque HashData_Deq.\n          simpl.\n          unfold RequestData2HashData; simpl.\n          smash_minbft. }\n\n        eapply ind in run1; try exact inlog; try reflexivity; eauto 3 with eo;[].\n        exrepnd.\n        exists hd.\n\n        unfold MinBFT_data_knows; simpl.\n        rewrite hash_data_in_log_log_new_prepare; simpl in *.\n        unfold RequestData2HashData; simpl; allrw.\n        smash_minbft. }\n\n      { Case \"Prepare\".\n\n        unfold call_verify_ui, bind in Heqx; simpl in *; smash_minbft;\n          try (complete (unfold state_of_subcomponents in *; simpl in *;\n                         ginv; eapply ind in run1; eauto; eauto 3 with eo));[].\n        unfold call_prepare_already_in_log, bind in Heqx2; simpl in *; smash_minbft;\n          try (complete (unfold state_of_subcomponents in *; simpl in *;\n                         ginv; eapply ind in run1; eauto; eauto 3 with eo));[].\n        unfold state_of_subcomponents in *; simpl in *; ginv.\n        unfold invalid_prepare in *; smash_minbft.\n        rewrite ui_in_log_log_new_commit in inlog ;simpl in *.\n        unfold commit2ui_i in inlog; simpl in *.\n        unfold commit_ui_j_rep_not_in_log in inlog; simpl in *.\n        unfold commit2sender_j in inlog; simpl in *.\n        unfold MinBFT_data_knows; simpl.\n        applydup valid_prepare_implies_view in Heqx0 as eqv.\n        rewrite eqv in inlog; autorewrite with minbft in *.\n        rewrite prepare_not_already_in_log_implies_find_entry in inlog; auto;[].\n        simpl in *; autorewrite with minbft in *.\n\n        smash_minbft;[| |].\n\n        { exists (prepare2hash_data p); simpl.\n          unfold verify_UI in *; autorewrite with minbft in *.\n          dands; auto;[].\n          rewrite hash_data_in_log_log_new_commit_eq.\n          unfold commit2hash_data_i; simpl.\n          unfold commit_ui_j_rep_not_in_log; simpl.\n          unfold commit2sender_j in *; simpl in *.\n          unfold commit2hash_data_j; simpl.\n          unfold RequestData2HashData; simpl in *.\n          rewrite eqv; autorewrite with minbft.\n          smash_minbft. }\n\n        { rewrite ui_in_log_log_new_prepare in Heqx2; smash_minbft;[]; GC.\n          eapply ind in run1; try exact Heqx2; try reflexivity; eauto 3 with eo.\n          exrepnd.\n          exists hd; dands; auto.\n          unfold MinBFT_data_knows; simpl.\n          rewrite hash_data_in_log_log_new_commit_eq; simpl.\n          unfold commit2hash_data_i; simpl.\n          unfold commit_ui_j_rep_not_in_log; simpl.\n          unfold commit2sender_j in *; simpl in *.\n          unfold commit2hash_data_j; simpl.\n          unfold RequestData2HashData; simpl in *.\n          rewrite eqv; autorewrite with minbft.\n          rewrite prepare_not_already_in_log_implies_find_entry; auto;[].\n          simpl in *; autorewrite with minbft.\n          unfold MinBFT_data_knows in run1;simpl in run1.\n          smash_minbft; allrw MinBFTprops0.not_over_or; repnd; tcsp; GC;\n            try rewrite @hash_data_in_log_log_new_prepare in *; smash_minbft. }\n\n        { exists (Build_HashData\n                    (prepare2view p)\n                    (request_b (prepare2request p))\n                    (Build_preUI (usig_id s1) (S (usig_counter s1)))); simpl.\n          autorewrite with minbft; dands; auto;[].\n          allrw not_over_or; repnd; GC.\n          Opaque UI_dec.\n          rewrite @ui_in_log_log_new_prepare in *; simpl in *.\n          smash_minbft;[]; GC.\n          rewrite hash_data_in_log_log_new_commit_eq; simpl.\n          unfold commit2hash_data_i; simpl.\n          unfold commit_ui_j_rep_not_in_log; simpl.\n          unfold commit2sender_j in *; simpl in *.\n          unfold commit2hash_data_j; simpl.\n          unfold RequestData2HashData; simpl in *.\n          rewrite eqv; autorewrite with minbft.\n          rewrite prepare_not_already_in_log_implies_find_entry; auto;[].\n          simpl in *; autorewrite with minbft.\n          smash_minbft. }\n      }\n\n      { Case \"Commit\".\n\n        unfold call_verify_ui, bind in Heqx; simpl in *; smash_minbft;\n          try (complete (unfold state_of_subcomponents in *; simpl in *;\n                         ginv; eapply ind in run1; eauto; eauto 3 with eo));[].\n        unfold call_prepare_already_in_log, bind_pair, bind in *; simpl in *; smash_minbft;\n          try (complete (unfold state_of_subcomponents in *; simpl in *;\n                         ginv; eapply ind in run1; eauto; eauto 3 with eo));[|].\n\n        {\n          unfold call_log_commit, bind in Heqx4; simpl in *; smash_minbft;\n            try (complete (unfold state_of_subcomponents in *; simpl in *;\n                           ginv; eapply ind in run1; eauto; eauto 3 with eo));[].\n          unfold call_is_committed, bind in Heqx; simpl in *; smash_minbft;\n            try (complete (unfold state_of_subcomponents in *; simpl in *;\n                           ginv; eapply ind in run1; eauto; eauto 3 with eo));[|].\n\n          { unfold state_of_subcomponents in *; simpl in *; ginv.\n            rewrite ui_in_log_log_new_commit in inlog; smash_minbft;\n              try (complete (eapply ind in run1; eauto; eauto 3 with eo));\n              [| |].\n\n            { exists (commit2hash_data_i c); simpl.\n              unfold verify_UI in *; simpl in *; autorewrite with minbft in *.\n              dands; auto;[].\n              unfold MinBFT_data_knows in *; simpl in *.\n              rewrite hash_data_in_log_log_new_commit_eq; smash_minbft. }\n\n            { eapply ind in run1; try exact Heqx; simpl in *;\n                unfold state_of_subcomponents in *; simpl in *; try reflexivity;\n                  eauto 3 with eo; exrepnd; exists hd; dands; auto.\n              unfold MinBFT_data_knows in *; simpl in *.\n              rewrite hash_data_in_log_log_new_commit_eq; smash_minbft. }\n\n            { exists (commit2hash_data_j c).\n              unfold verify_UI in *; simpl in *; autorewrite with minbft in *.\n              dands; auto;[].\n              unfold MinBFT_data_knows in *; simpl in *.\n              rewrite hash_data_in_log_log_new_commit_eq; smash_minbft. }\n          }\n\n          { unfold state_of_subcomponents in *; simpl in *; ginv.\n            rewrite ui_in_log_log_new_commit in inlog; smash_minbft;\n              try (complete (eapply ind in run1; eauto; eauto 3 with eo));\n              [| |].\n\n            { exists (commit2hash_data_i c); simpl.\n              unfold verify_UI in *; simpl in *; autorewrite with minbft in *.\n              dands; auto;[].\n              unfold MinBFT_data_knows in *; simpl in *.\n              rewrite hash_data_in_log_log_new_commit_eq; smash_minbft. }\n\n            { eapply ind in run1; try exact Heqx; simpl in *;\n                unfold state_of_subcomponents in *; simpl in *; try reflexivity;\n                  eauto 3 with eo; exrepnd; exists hd; dands; auto.\n              unfold MinBFT_data_knows in *; simpl in *.\n              rewrite hash_data_in_log_log_new_commit_eq; smash_minbft. }\n\n            { exists (commit2hash_data_j c).\n              unfold verify_UI in *; simpl in *; autorewrite with minbft in *.\n              dands; auto;[].\n              unfold MinBFT_data_knows in *; simpl in *.\n              rewrite hash_data_in_log_log_new_commit_eq; smash_minbft. }\n          }\n        }\n\n        {\n          unfold call_log_commit, bind in Heqx4; simpl in *; smash_minbft;\n            try (complete (unfold state_of_subcomponents in *; simpl in *;\n                           ginv; eapply ind in run1; eauto; eauto 3 with eo));[].\n          unfold call_is_committed, bind in Heqx; simpl in *; smash_minbft;\n            try (complete (unfold state_of_subcomponents in *; simpl in *;\n                           ginv; eapply ind in run1; eauto; eauto 3 with eo));[|].\n\n          { unfold state_of_subcomponents in *; simpl in *; ginv.\n            rewrite ui_in_log_log_new_commit in inlog; smash_minbft;\n              try (complete (eapply ind in run1; eauto; eauto 3 with eo));\n              [| |].\n\n            { exists (commit2hash_data_i c); simpl.\n              unfold verify_UI in *; simpl in *; autorewrite with minbft in *.\n              dands; auto;[].\n              unfold MinBFT_data_knows in *; simpl in *.\n              rewrite hash_data_in_log_log_new_commit_eq; smash_minbft. }\n\n            { rewrite ui_in_log_log_new_commit in Heqx; smash_minbft;\n                try (complete (eapply ind in run1; eauto; eauto 3 with eo));\n                [| |].\n\n              { exists (commit2hash_data_i c); simpl.\n                unfold verify_UI in *; simpl in *; autorewrite with minbft in *.\n                dands; auto;[].\n                unfold MinBFT_data_knows in *; simpl in *.\n                rewrite hash_data_in_log_log_new_commit_eq; smash_minbft. }\n\n              { eapply ind in run1; try exact Heqx; simpl in *;\n                  unfold state_of_subcomponents in *; simpl in *; try reflexivity;\n                    eauto 3 with eo; exrepnd; exists hd; dands; auto.\n                unfold MinBFT_data_knows in *; simpl in *.\n                unfold commit2ui_i in *; simpl in *.\n                autorewrite with minbft in *.\n                rewrite hash_data_in_log_log_new_commit_eq; smash_minbft.\n                { rewrite hash_data_in_log_log_new_commit_eq in Heqx; simpl in *.\n                  unfold commit_ui_j_rep_not_in_log in *; simpl in *; smash_minbft. }\n                { rewrite hash_data_in_log_log_new_commit_eq in Heqx; simpl in *.\n                  unfold commit_ui_j_rep_not_in_log in *; simpl in *; smash_minbft. }\n              }\n\n              { exists (Build_HashData\n                          (commit2view c)\n                          (request_b (commit2request c))\n                          (Build_preUI (usig_id s1) (S (usig_counter s1)))); simpl.\n                unfold verify_UI in *; simpl in *; autorewrite with minbft in *.\n                dands; auto;[].\n                unfold MinBFT_data_knows in *; simpl in *.\n                rewrite hash_data_in_log_log_new_commit_eq; smash_minbft.\n                { rewrite hash_data_in_log_log_new_commit_eq in Heqx; simpl in *.\n                  unfold commit_ui_j_rep_not_in_log in *; simpl in *; smash_minbft. }\n                { rewrite hash_data_in_log_log_new_commit_eq in Heqx; simpl in *.\n                  unfold commit_ui_j_rep_not_in_log in *; simpl in *; smash_minbft. }\n              }\n            }\n\n            { exists (commit2hash_data_j c).\n              unfold verify_UI in *; simpl in *; autorewrite with minbft in *.\n              dands; auto;[].\n              unfold MinBFT_data_knows in *; simpl in *.\n              rewrite hash_data_in_log_log_new_commit_eq; smash_minbft. }\n          }\n\n          { unfold state_of_subcomponents in *; simpl in *; ginv.\n            rewrite ui_in_log_log_new_commit in inlog; smash_minbft;\n              try (complete (eapply ind in run1; eauto; eauto 3 with eo));\n              [| |].\n\n            { exists (commit2hash_data_i c); simpl.\n              unfold verify_UI in *; simpl in *; autorewrite with minbft in *.\n              dands; auto;[].\n              unfold MinBFT_data_knows in *; simpl in *.\n              rewrite hash_data_in_log_log_new_commit_eq; smash_minbft. }\n\n            { rewrite ui_in_log_log_new_commit in Heqx; smash_minbft;\n                try (complete (eapply ind in run1; eauto; eauto 3 with eo));\n                [| |].\n\n              { exists (commit2hash_data_i c); simpl.\n                unfold verify_UI in *; simpl in *; autorewrite with minbft in *.\n                dands; auto;[].\n                unfold MinBFT_data_knows in *; simpl in *.\n                rewrite hash_data_in_log_log_new_commit_eq; smash_minbft. }\n\n              { eapply ind in run1; try exact Heqx; simpl in *;\n                  unfold state_of_subcomponents in *; simpl in *; try reflexivity;\n                    eauto 3 with eo; exrepnd; exists hd; dands; auto.\n                unfold MinBFT_data_knows in *; simpl in *.\n                unfold commit2ui_i in *; simpl in *.\n                autorewrite with minbft in *.\n                rewrite hash_data_in_log_log_new_commit_eq; smash_minbft.\n                { rewrite hash_data_in_log_log_new_commit_eq in Heqx; simpl in *.\n                  unfold commit_ui_j_rep_not_in_log in *; simpl in *; smash_minbft. }\n                { rewrite hash_data_in_log_log_new_commit_eq in Heqx; simpl in *.\n                  unfold commit_ui_j_rep_not_in_log in *; simpl in *; smash_minbft. }\n              }\n\n              { exists (Build_HashData\n                          (commit2view c)\n                          (request_b (commit2request c))\n                          (Build_preUI (usig_id s1) (S (usig_counter s1)))); simpl.\n                unfold verify_UI in *; simpl in *; autorewrite with minbft in *.\n                dands; auto;[].\n                unfold MinBFT_data_knows in *; simpl in *.\n                rewrite hash_data_in_log_log_new_commit_eq; smash_minbft.\n                { rewrite hash_data_in_log_log_new_commit_eq in Heqx; simpl in *.\n                  unfold commit_ui_j_rep_not_in_log in *; simpl in *; smash_minbft. }\n                { rewrite hash_data_in_log_log_new_commit_eq in Heqx; simpl in *.\n                  unfold commit_ui_j_rep_not_in_log in *; simpl in *; smash_minbft. }\n              }\n            }\n\n            { exists (commit2hash_data_j c).\n              unfold verify_UI in *; simpl in *; autorewrite with minbft in *.\n              dands; auto;[].\n              unfold MinBFT_data_knows in *; simpl in *.\n              rewrite hash_data_in_log_log_new_commit_eq; smash_minbft. }\n          }\n        }\n      }\n    }\n  Qed.*)\n\n  Lemma are_procs_n_procs_minbft_subs_new :\n    forall u l, are_procs_n_procs (MinBFTsubs_new u l).\n  Proof.\n    introv i; simpl in *; repndors; subst; tcsp;\n      unfold is_proc_n_nproc; simpl; eauto 3 with minbft;\n        unfold is_proc_n_proc; simpl; eexists; introv; try reflexivity.\n  Qed.\n  Hint Resolve are_procs_n_procs_minbft_subs_new : minbft.\n\n  Lemma similar_minbft_implies_subs_new :\n    forall (subs : n_procs 1) u l,\n      similar_subs (MinBFTsubs_new u l) subs\n      -> exists u' l', subs = MinBFTsubs_new u' l'.\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 p2, 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 M_run_ls_on_input_ls_is_minbft_new :\n    forall cn i o r s u l ls,\n      M_run_ls_on_input (MinBFTlocalSys_new r s u l) cn i = (ls, o)\n      -> exists s' u' l',\n        ls = MinBFTlocalSys_new r s' u' l'.\n  Proof.\n    introv run.\n    apply M_run_ls_on_input_ls_is_minbft_newP in run; eauto 3 with minbft; tcsp;\n      try (complete (unfold get_names; simpl; introv xx; repndors; tcsp; inversion xx)).\n    exrepnd; subst; simpl in *.\n    apply similar_minbft_implies_subs_new in run1; exrepnd; subst.\n    eexists; eexists; eexists; try reflexivity.\n  Qed.\n\n  Lemma request_data_was_verified :\n    forall {eo : EventOrdering} (e : Event) (l : LOG_state) (u : USIG_state) v r ui,\n      is_replica e\n      -> M_state_sys_on_event MinBFTsys e LOGname = Some l\n      -> M_state_sys_on_event MinBFTsys e USIGname = Some u\n      -> kc_knows (minbft_data_rdata (request_data v r ui)) l\n      -> verify_hash_usig (Build_HashData v r (ui_pre ui)) (ui2digest ui) (usig_local_keys u) = true.\n  Proof.\n    introv isr eqst1 eqst2 unl.\n\n    unfold kc_Tknows in unl; simpl in unl.\n    unfold MinBFT_data_knows in unl; simpl in unl.\n\n    rewrite M_state_sys_on_event_unfold in eqst1.\n    rewrite M_state_sys_on_event_unfold in eqst2.\n\n    apply map_option_Some in eqst1.\n    apply map_option_Some in eqst2.\n    exrepnd; try rev_Some.\n\n    rewrite eqst1 in eqst2; ginv.\n\n    unfold is_replica in *; exrepnd.\n\n    revert dependent u.\n    revert dependent l.\n    revert dependent a.\n    rewrite isr0; simpl.\n\n    (* WARNING *)\n    clear isr0.\n\n    induction e as [e ind] using predHappenedBeforeInd;[]; introv run stl inlog stu.\n\n    rewrite M_run_ls_on_event_unroll2 in run.\n\n    (*rewrite M_run_ls_before_event_unroll_on in run.\n\n    destruct (dec_isFirst e) as [d|d].\n\n    {\n      clear ind.\n\n      unfold M_run_ls_on_this_one_event in run; simpl in *.\n      apply map_option_Some in run; exrepnd; rev_Some.\n      autorewrite with minbft in *.\n\n      Time minbft_dest_msg Case;\n        repeat (simpl in *; autorewrite with minbft in *; smash_minbft2);\n        ginv; simpl in *; autorewrite with minbft in *; auto;\n          unfold verify_UI in *; simpl in *; autorewrite with minbft in *;\n            first [destruct p as [b pui], b\n                  |destruct c as [b pui], b]; simpl in *; ginv;\n              unfold prepare2hash_data, RequestData2HashData, prepare2request in *; simpl in *; auto;\n                unfold invalid_prepare, valid_prepare in *; simpl in *; smash_minbft;\n                  unfold prepare2view in *; simpl in *; subst; tcsp;\n                    try (complete (unfold state_of_subcomponents in *; simpl in *; ginv)).\n    }*)\n\n    {\n      apply map_option_Some in run; exrepnd; rev_Some.\n      applydup M_run_ls_before_event_ls_is_minbft in run1; exrepnd; subst.\n\n      unfold M_run_ls_on_this_one_event in run0; simpl in *.\n      apply map_option_Some in run0; exrepnd; rev_Some; minbft_simp.\n      unfold M_run_ls_on_input_ls in *; simpl in *.\n      remember (M_run_ls_on_input (MinBFTlocalSys_new r0 s s1 s2) (msg_comp_name 0) a0) as run.\n      symmetry in Heqrun; repnd; simpl in *.\n      applydup (M_run_ls_on_input_ls_is_minbft_new (msg_comp_name 0)) in Heqrun; exrepnd; subst; simpl in *.\n      autorewrite with minbft in *; minbft_simp.\n      unfold M_run_ls_on_input in Heqrun; simpl in *.\n      autorewrite with minbft in *; simpl in *.\n\n      Time minbft_dest_msg Case;\n        repeat (simpl in *; autorewrite with minbft in *; smash_minbft2);\n        (unfold lower_out_break in *; simpl in *; minbft_simp;\n                  repeat (smash_minbft1; ginv; simpl in *;tcsp);\n                  rewrite M_run_ls_before_event_unroll_on in run1;\n                  destruct (dec_isFirst e); simpl in *;\n                    minbft_simp; simpl in *; repeat (smash_minbft1; ginv; simpl in *;tcsp);\n                      try (complete (eapply ind in run1; eauto; eauto 3 with eo));\n                      first [destruct p as [b pui], b\n                            |destruct c as [b pui], b]; simpl in *; ginv;\n                        unfold prepare2hash_data, RequestData2HashData, prepare2request in *; simpl in *; auto;\n                          unfold invalid_prepare, valid_prepare in *; simpl in *; smash_minbft3;\n                            unfold prepare2view in *; simpl in *; subst; tcsp; ginv; auto).\n    }\n  Qed.\n\n  Lemma M_run_ls_on_event_MinBFT_to_components :\n    forall i {eo : EventOrdering} (e : Event) j s l u,\n      loc e = MinBFT_replica i\n      -> M_run_ls_on_event (MinBFTlocalSys i) e = Some (MinBFTlocalSys_new j s u l)\n      -> M_state_sys_on_event MinBFTsys e MAINname = Some s\n         /\\ M_state_sys_on_event MinBFTsys e USIGname = Some u\n         /\\ M_state_sys_on_event MinBFTsys e LOGname = Some l.\n  Proof.\n    introv eqrep h.\n    unfold M_state_sys_on_event; allrw; simpl.\n    unfold M_state_ls_on_event.\n    allrw; simpl.\n    unfold state_of_component; simpl; tcsp.\n  Qed.\n\nEnd MinBFTprops1.\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/MinBFTprops1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.26604921529906417}}
{"text": "Require Import bedrock2.Syntax bedrock2.NotationsCustomEntry Coq.Strings.String.\nRequire Import coqutil.Z.div_mod_to_equations.\nRequire Import coqutil.Z.Lia.\nRequire Import coqutil.Word.Interface.\nRequire Import coqutil.Byte.\n\nImport BinInt String List.ListNotations ZArith.\nLocal Open Scope Z_scope. Local Open Scope string_scope. Local Open Scope list_scope.\n\nLocal Notation MMIOWRITE := \"MMIOWRITE\".\nLocal Notation MMIOREAD := \"MMIOREAD\".\n\nRequire bedrock2Examples.lightbulb_spec.\nLocal Notation patience := lightbulb_spec.patience.\n\nDefinition spi_write : function :=\n  let SPI_WRITE_ADDR := 0x10024048 in\n  (\"spi_write\", ([\"b\"], [\"busy\"], bedrock_func_body:(\n    busy = ($-1);\n    i = ($patience); while (i) { i = (i - $1);\n      io! busy = $MMIOREAD($SPI_WRITE_ADDR);\n      if !(busy >> $31) {\n        i = (i^i)\n      }\n    };\n    if !(busy >> $31) {\n      output! $MMIOWRITE($SPI_WRITE_ADDR, b);\n      busy = (busy ^ busy)\n    }\n  ))).\n\nDefinition spi_read : function :=\n  let SPI_READ_ADDR := 0x1002404c in\n  (\"spi_read\", (nil, (\"b\"::\"busy\"::nil), bedrock_func_body:(\n    busy = ($-1);\n    b = ($0x5a);\n    i = ($patience); while (i) { i = (i - $1);\n      io! busy = $MMIOREAD($SPI_READ_ADDR);\n      if !(busy >> $31) {\n        b = (busy & $0xff);\n        i = (i^i);\n        busy = (busy ^ busy)\n      }\n    }\n  ))).\n\nDefinition spi_xchg : function :=\n  (\"spi_xchg\", (\"b\"::nil, \"b\"::\"busy\"::nil, bedrock_func_body:(\n    unpack! busy = spi_write(b);\n    require !busy;\n    unpack! b, busy = spi_read()\n  ))).\n\nRequire Import bedrock2.ProgramLogic.\nRequire Import bedrock2.FE310CSemantics bedrock2.Semantics.\nRequire Import Coq.Lists.List. Import ListNotations.\nRequire Import bedrock2.TracePredicate. Import TracePredicateNotations.\nRequire Import bedrock2.ZnWords.\n\nImport coqutil.Map.Interface.\nImport ReversedListNotations.\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 mmio_event_abstraction_relation\n    (h : lightbulb_spec.OP word)\n    (l : mem * string * list word * (mem * list word)) :=\n    Logic.or\n      (exists a v, h = (\"st\", a, v) /\\ l = (map.empty, \"MMIOWRITE\", [a; v], (map.empty, [])))\n      (exists a v, h = (\"ld\", a, v) /\\ l = (map.empty, \"MMIOREAD\", [a], (map.empty, [v]))).\n  Definition mmio_trace_abstraction_relation := List.Forall2 mmio_event_abstraction_relation.\n\n  Global Instance spec_of_spi_write : spec_of \"spi_write\" := fun functions => forall t m b,\n    word.unsigned b < 2 ^ 8 ->\n    WeakestPrecondition.call functions \"spi_write\" t m [b] (fun T M RETS =>\n      M = m /\\ exists iol, T = t ;++ iol /\\ exists ioh, mmio_trace_abstraction_relation ioh iol /\\ exists err, RETS = [err] /\\ Logic.or\n        (((word.unsigned err <> 0) /\\ lightbulb_spec.spi_write_full _ ^* ioh /\\ Z.of_nat (length ioh) = patience))\n        (word.unsigned err = 0 /\\ lightbulb_spec.spi_write word (byte.of_Z (word.unsigned b)) ioh)).\n\n  Global Instance spec_of_spi_read : spec_of \"spi_read\" := fun functions => forall t m,\n    WeakestPrecondition.call functions \"spi_read\" t m [] (fun T M RETS =>\n      M = m /\\ exists iol, T = t ;++ iol /\\ exists ioh, mmio_trace_abstraction_relation ioh iol /\\ exists (b: byte) (err : word), RETS = [word.of_Z (byte.unsigned b); err] /\\ Logic.or\n        (word.unsigned err <> 0 /\\ lightbulb_spec.spi_read_empty _ ^* ioh /\\ Z.of_nat (length ioh) = patience)\n        (word.unsigned err = 0 /\\ lightbulb_spec.spi_read word b ioh)).\n\n  Lemma nonzero_because_high_bit_set (x : word) (H : word.unsigned (word.sru x (word.of_Z 31)) <> 0)\n    : word.unsigned x <> 0.\n  Proof. ZnWords. Qed.\n\n  Add Ring wring : (Properties.word.ring_theory (word := word))\n        (preprocess [autorewrite with rew_word_morphism],\n         morphism (Properties.word.ring_morph (word := word)),\n         constants [Properties.word_cst]).\n\n  Import coqutil.Tactics.letexists.\n  Import Loops.\n  Lemma spi_write_ok : program_logic_goal_for_function! spi_write.\n  Proof.\n    repeat straightline.\n    rename H into Hb.\n\n    (* WHY do theese parentheses matter? *)\n    refine ((atleastonce [\"b\"; \"busy\"; \"i\"] (fun v T M B BUSY I =>\n       b = B /\\ v = word.unsigned I /\\ word.unsigned I <> 0 /\\ M = m /\\\n       exists tl, T = tl++t /\\\n       exists th, mmio_trace_abstraction_relation th tl /\\\n       lightbulb_spec.spi_write_full _ ^* th /\\\n       Z.of_nat (length th) + word.unsigned I = patience\n       )) _ _ _ _ _ _ _);\n      cbn [reconstruct map.putmany_of_list HList.tuple.to_list\n           HList.hlist.foralls HList.tuple.foralls\n           HList.hlist.existss HList.tuple.existss\n           HList.hlist.apply  HList.tuple.apply\n           HList.hlist\n           List.repeat Datatypes.length\n           HList.polymorphic_list.repeat HList.polymorphic_list.length\n           PrimitivePair.pair._1 PrimitivePair.pair._2] in *.\n    { repeat straightline. }\n    { eapply (Z.lt_wf 0). }\n    { eexists; split; repeat straightline.\n      exfalso. ZnWords. }\n    { repeat (split; trivial; []).\n      subst i. rewrite word.unsigned_of_Z.\n      split.\n      { discriminate. }\n      split; trivial.\n      eexists; split.\n      { rewrite app_nil_l; trivial. }\n      eexists; split.\n      { constructor. }\n      split.\n      { constructor. }\n      exact eq_refl. }\n    repeat straightline.\n    eapply WeakestPreconditionProperties.interact_nomem; repeat straightline.\n    letexists; split; [exact eq_refl|]; split; [split; trivial|].\n    {\n      cbv [isMMIOAddr addr].\n      ZnWords. }\n    repeat straightline. split; trivial.\n    letexists. split.\n    { repeat straightline. exact eq_refl. }\n    (* evaluate condition then split if *) letexists; split; [solve[repeat straightline]|split].\n    all: intros.\n    { (* CASE if-condition was true (word.unsigned v0 <> 0), i.e. NOP, loop exit depends on whether timeout *)\n    repeat straightline. (* <-- does split on a postcondition of the form\n                        (word.unsigned br <> 0 -> loop invariant still holds) /\\\n                        (word.unsigned br =  0 -> code after loop is fine)\n                        which corresponds to case distinction over whether loop was exited *)\n    { (* SUBCASE loop condition was true (do loop again) *)\n      eexists; split.\n      { repeat (split; trivial; []). subst t0.\n        eexists (_ ;++ cons _ nil); split; [exact eq_refl|].\n        eexists; split.\n        { refine (List.Forall2_app _ _); try eassumption.\n          econstructor; [|constructor].\n          right; eexists _, _; repeat split. }\n        split.\n        { eapply kleene_app; eauto.\n          refine (kleene_step _ _ nil _ (kleene_empty _)).\n          repeat econstructor.\n          ZnWords. }\n        { ZnWordsL. } }\n        { ZnWords. } }\n    { (* SUBCASE loop condition was false (exit loop because of timeout *)\n      letexists; split; [solve[repeat straightline]|split]; repeat straightline; try contradiction.\n      split; eauto.\n      subst t0.\n      eexists (_ ;++ cons _ nil); split.\n      { rewrite <-app_assoc; cbn [app]; f_equal. }\n      eexists. split.\n      { eapply Forall2_app; eauto.\n        constructor; [|constructor].\n        right; eauto. }\n      eexists. split; trivial.\n      { left; repeat split; eauto using nonzero_because_high_bit_set.\n        { (* copied from above -- trace element for \"fifo full\" *)\n          eapply kleene_app; eauto.\n          refine (kleene_step _ _ nil _ (kleene_empty _)).\n          repeat econstructor.\n          ZnWords. }\n        { ZnWordsL. } } }\n    }\n    (* CASE if-condition was false (word.unsigned v0 = 0), i.e. we'll set i=i^i and exit loop *)\n    repeat straightline.\n    { subst i.\n      rewrite Properties.word.unsigned_xor_nowrap in *; rewrite Z.lxor_nilpotent in *; contradiction. }\n    (* evaluate condition then split if *) letexists; split; [solve[repeat straightline]|split].\n    1:contradiction.\n    repeat straightline.\n    eapply WeakestPreconditionProperties.interact_nomem; repeat straightline.\n    letexists; letexists; split; [exact eq_refl|]; split; [split; trivial|].\n    { cbv [isMMIOAddr]. ZnWords. }\n    repeat straightline. split; trivial.\n    repeat straightline.\n    split; trivial. subst t0.\n    eexists (_ ;++ cons _ (cons _ nil)). split.\n    { rewrite <-app_assoc. cbn [app]. f_equal. }\n    eexists. split.\n    { eapply List.Forall2_app; eauto.\n      { constructor.\n        { left. eexists _, _; repeat split. }\n        { right; [|constructor].\n          right; eexists _, _; repeat split. } } }\n    eexists; split; trivial.\n    right.\n    subst busy.\n    split.\n    { f_equal. rewrite Properties.word.unsigned_xor_nowrap; rewrite Z.lxor_nilpotent; reflexivity. }\n    cbv [lightbulb_spec.spi_write].\n    eexists _, _; split; eauto; []; split; eauto.\n    eexists (cons _ nil), (cons _ nil); split; cbn [app]; eauto.\n    split; repeat econstructor.\n    { ZnWords. }\n    { cbv [lightbulb_spec.spi_write_enqueue one].\n      repeat f_equal.\n      eapply Properties.word.unsigned_inj.\n      rewrite byte.unsigned_of_Z; cbv [byte.wrap]; rewrite Z.mod_small; ZnWords. }\n  Qed.\n\n  Local Ltac split_if :=\n    lazymatch goal with\n      |- WeakestPrecondition.cmd _ ?c _ _ _ ?post =>\n      let c := eval hnf in c in\n          lazymatch c with\n          | cmd.cond _ _ _ => letexists; split; [solve[repeat straightline]|split]\n          end\n    end.\n\n  Lemma spi_read_ok : program_logic_goal_for_function! spi_read.\n    repeat straightline.\n    refine ((atleastonce [\"b\"; \"busy\"; \"i\"] (fun v T M B BUSY I =>\n       v = word.unsigned I /\\ word.unsigned I <> 0 /\\ M = m /\\\n       B = word.of_Z (byte.unsigned (byte.of_Z (word.unsigned B))) /\\\n       exists tl, T = tl++t /\\\n       exists th, mmio_trace_abstraction_relation th tl /\\\n       lightbulb_spec.spi_read_empty _ ^* th /\\\n       Z.of_nat (length th) + word.unsigned I = patience\n            ))\n            _ _ _ _ _ _ _);\n      cbn [reconstruct map.putmany_of_list HList.tuple.to_list\n           HList.hlist.foralls HList.tuple.foralls\n           HList.hlist.existss HList.tuple.existss\n           HList.hlist.apply  HList.tuple.apply\n           HList.hlist\n           List.repeat Datatypes.length\n           HList.polymorphic_list.repeat HList.polymorphic_list.length\n           PrimitivePair.pair._1 PrimitivePair.pair._2] in *; repeat straightline.\n    { exact (Z.lt_wf 0). }\n    { exfalso. ZnWords. }\n    { split; trivial.\n      subst i. rewrite word.unsigned_of_Z.\n      split; [inversion 1|].\n      split; trivial.\n      subst b; rewrite byte.unsigned_of_Z; cbv [byte.wrap];\n        rewrite Z.mod_small; rewrite word.unsigned_of_Z.\n      2: { cbv. split; congruence. }\n      split; trivial.\n      eexists nil; split; trivial.\n      eexists nil; split; try split; solve [constructor]. }\n    { eapply WeakestPreconditionProperties.interact_nomem; repeat straightline.\n      letexists; split; [exact eq_refl|]; split; [split; trivial|].\n    { cbv [isMMIOAddr]. ZnWords. }\n      repeat ((split; trivial; []) || straightline || split_if).\n      {\n        letexists. split; split.\n        { subst v'; exact eq_refl. }\n        { split; trivial.\n          split; trivial.\n          split; trivial.\n          eexists (x2 ;++ cons _ nil); split; cbn [app]; eauto.\n          eexists. split.\n          { econstructor; try eassumption; right; eauto. }\n          split.\n          {\n            refine (kleene_app _ (cons _ nil) _ x3 _); eauto.\n            refine (kleene_step _ (cons _ nil) nil _ (kleene_empty _)).\n            eexists; split.\n            { exact eq_refl. }\n            { ZnWords. } }\n          { ZnWordsL. } }\n          { ZnWords. }\n          { ZnWords. } }\n      { letexists; split; repeat straightline.\n        split; trivial.\n        eexists (x2 ;++ cons _ nil); split; cbn [app]; eauto.\n        eexists. split.\n        { econstructor; try eassumption; right; eauto. }\n        eexists (byte.of_Z (word.unsigned x)), _; split.\n        { f_equal. eassumption. }\n        left; repeat split; eauto using nonzero_because_high_bit_set.\n        { refine (kleene_app _ (cons _ nil) _ x3 _); eauto.\n          refine (kleene_step _ (cons _ nil) nil _ (kleene_empty _)).\n          eexists; split.\n          { exact eq_refl. }\n          { ZnWords. } }\n        { ZnWordsL. } }\n      { repeat straightline.\n        repeat letexists; split.\n        1: split.\n        { repeat straightline. }\n        2: {\n          subst v'.\n          subst v.\n          subst i.\n          rewrite Properties.word.unsigned_xor_nowrap, Z.lxor_nilpotent.\n          ZnWords. }\n        repeat straightline.\n        repeat (split; trivial; []).\n        split.\n        { subst b.\n          (* automatable: multi-word bitwise *)\n          change (255) with (Z.ones 8).\n          pose proof Properties.word.unsigned_range v0.\n          eapply Properties.word.unsigned_inj.\n          repeat (\n              cbv [byte.wrap word.wrap];\n              rewrite ?byte.unsigned_of_Z, ?word.unsigned_of_Z, ?Properties.word.unsigned_and_nowrap,\n                      ?Z.land_ones, ?Z.mod_mod, ?Z.mod_small\n                by blia;\n              change (Z.ones 8 mod 2 ^ 32) with (Z.ones 8)).\n          symmetry; eapply Z.mod_small.\n          pose proof Z.mod_pos_bound (word.unsigned v0) (2^8) eq_refl.\n          clear. Z.div_mod_to_equations. blia. }\n        { (* copy-paste from above, trace manipulation *)\n          eexists (x2 ;++ cons _ nil); split; cbn [app]; eauto.\n          eexists. split.\n          { econstructor; try eassumption; right; eauto. }\n          subst i.\n          rewrite Properties.word.unsigned_xor_nowrap, Z.lxor_nilpotent in H1; contradiction. } }\n      { eexists _; split.\n        { repeat straightline. }\n        split; trivial.\n        (* copy-paste from above, trace manipulation *)\n        eexists (x2 ;++ cons _ nil); split; cbn [app]; eauto.\n        eexists. split.\n        { econstructor; try eassumption; right; eauto. }\n        eexists (byte.of_Z (word.unsigned b)), _; split.\n        { subst b; f_equal.\n          (* tag:bitwise *)\n          (* automatable: multi-word bitwise *)\n          change (255) with (Z.ones 8).\n          pose proof Properties.word.unsigned_range v0.\n          eapply Properties.word.unsigned_inj.\n          repeat (\n              cbv [byte.wrap word.wrap];\n              rewrite ?byte.unsigned_of_Z, ?word.unsigned_of_Z, ?Properties.word.unsigned_and_nowrap,\n                      ?Z.land_ones, ?Z.mod_mod, ?Z.mod_small\n                by blia;\n              change (Z.ones 8 mod 2 ^ 32) with (Z.ones 8)).\n          symmetry; eapply Z.mod_small.\n          pose proof Z.mod_pos_bound (word.unsigned v0) (2^8) eq_refl.\n          clear. Z.div_mod_to_equations. blia. }\n        (* tag:symex *)\n        { right; split.\n          { subst busy. rewrite Properties.word.unsigned_xor_nowrap, Z.lxor_nilpotent; exact eq_refl. }\n          eexists x3, (cons _ nil); split; cbn [app]; eauto.\n          split; eauto.\n          eexists; split; cbv [one]; trivial.\n          split.\n          (* tag:bitwise *)\n          { ZnWords. }\n          subst b.\n          (* automatable: multi-word bitwise *)\n          change (255) with (Z.ones 8).\n          pose proof Properties.word.unsigned_range v0.\n          eapply byte.unsigned_inj.\n          repeat (\n              cbv [byte.wrap word.wrap];\n              rewrite ?byte.unsigned_of_Z, ?word.unsigned_of_Z, ?Properties.word.unsigned_and_nowrap,\n                      ?Z.land_ones, ?Z.mod_mod, ?Z.mod_small\n                by blia;\n              change (Z.ones 8 mod 2 ^ 32) with (Z.ones 8)).\n          trivial. } } }\n  Qed.\n\n  Global Instance spec_of_spi_xchg : spec_of \"spi_xchg\" := fun functions => forall t m b_out,\n    word.unsigned b_out < 2 ^ 8 ->\n    WeakestPrecondition.call functions \"spi_xchg\" t m [b_out] (fun T M RETS =>\n      M = m /\\ exists iol, T = t ;++ iol /\\ exists ioh, mmio_trace_abstraction_relation ioh iol /\\ exists (b_in:byte) (err : word), RETS = [word.of_Z (byte.unsigned b_in); err] /\\ Logic.or\n        (word.unsigned err <> 0 /\\ (any +++ lightbulb_spec.spi_timeout _) ioh)\n        (word.unsigned err = 0 /\\ lightbulb_spec.spi_xchg word (byte.of_Z (word.unsigned b_out)) b_in ioh)).\n\n  Lemma spi_xchg_ok : program_logic_goal_for_function! spi_xchg.\n  Proof.\n    repeat (\n    match goal with\n    | |- ?F ?a ?b ?c =>\n        match F with WeakestPrecondition.get => idtac end;\n        let f := (eval cbv beta delta [WeakestPrecondition.get] in F) in\n        change (f a b c); cbv beta\n      | H :  _ /\\ _ \\/ ?Y /\\ _, G : not ?X |- _ =>\n          constr_eq X Y; let Z := fresh in destruct H as [|[Z ?]]; [|case (G Z)]\n      | H :  not ?Y /\\ _ \\/ _ /\\ _, G : ?X |- _ =>\n          constr_eq X Y; let Z := fresh in destruct H as [[Z ?]|]; [case (Z G)|]\n    end ||\n\n    straightline || straightline_call || split_if || refine (conj _ _) || eauto).\n\n  { eexists. split.\n    { exact eq_refl. }\n    eexists. split.\n    { eauto. }\n    eexists. eexists. split.\n    { repeat f_equal.\n      instantiate (1 := byte.of_Z (word.unsigned b_out)).\n      (* automatable: multi-word bitwise *)\n      change (255) with (Z.ones 8).\n      pose proof Properties.word.unsigned_range b_out.\n      eapply Properties.word.unsigned_inj;\n      repeat (\n      cbv [word.wrap byte.wrap];\n      rewrite ?byte.unsigned_of_Z, ?word.unsigned_of_Z, ?Properties.word.unsigned_and_nowrap, ?Z.land_ones, ?Z.mod_mod, ?Z.mod_small by blia;\n      change (Z.ones 8 mod 2 ^ 32) with (Z.ones 8));\n      rewrite ?Z.mod_small; rewrite ?Z.mod_small; trivial; blia. }\n      left; split; eauto.\n      eexists nil, x0; repeat split; cbv [any choice lightbulb_spec.spi_timeout]; eauto.\n      rewrite app_nil_r; trivial. }\n\n      { destruct H10; intuition eauto.\n        { eexists. split.\n          { subst a0. subst a.\n            rewrite List.app_assoc; trivial. }\n            eexists. split.\n            { eapply Forall2_app; eauto. }\n            eexists _, _; split.\n            { subst v; trivial. }\n            left; split; eauto.\n            eapply concat_app; cbv [any choice lightbulb_spec.spi_timeout]; eauto. }\n            eexists.\n            subst a0.\n            subst a.\n            split.\n            { rewrite List.app_assoc; trivial. }\n            eexists.\n            split.\n            { eapply Forall2_app; eauto. }\n            eexists _, _; split.\n            { subst v. eauto. }\n            right. split; eauto.\n            cbv [lightbulb_spec.spi_xchg].\n\n  assert (Trace__concat_app : forall T (P Q:list T->Prop) x y, P x -> Q y -> (P +++ Q) (y ++ x)). {\n    cbv [concat]; eauto. }\n\n    eauto using Trace__concat_app. }\n  Qed.\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/SPI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.26604921529906417}}
{"text": "From mathcomp Require Import ssreflect ssrbool ssrnat eqtype ssrfun seq path.\nFrom Coq Require Import Eqdep Relation_Operators.\nFrom pcm Require Import axioms pred prelude ordtype finmap pcm unionmap heap.\nFrom DiSeL Require Import Freshness State EqTypeX Protocols Worlds NetworkSem.\nFrom Coq Require Classical_Prop.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* \"Atomic\" send/receive actions, coherent with the network semantics *)\n\nModule Actions.\n\nSection Actions.\n\nVariable W : world.\nNotation getS s l := (getStatelet s l).\n\n(*\n\nAction is defined with respect to the world (i.e., a number of\nprotocols) and label.\n\nIt changes the state as a whole, but, in fact, affects only a specific\nstatelet in it, associated with a specific label.\n\n\n*)\n\n\nStructure action (V : Type) (this : nid)\n  := Action\n       {\n         (* a_lab : Label; *)\n         (* a_lab_dom : a_lab \\in ddom W; *)\n\n         a_safe : state -> Prop;\n\n         a_safe_coh : forall s, a_safe s -> s \\In Coh W;\n\n\n         (* safe_coh : forall s, a_safe s -> coh (getP a_lab) (getS s a_lab); *)\n\n         a_step : forall s1, (a_safe s1) -> state -> V -> Prop;\n\n         step_total : forall s (pf : a_safe s), exists s' r, a_step pf s' r;\n\n         (* step_coh  : forall s1 s2 r, Coh W s1 -> *)\n         (*     a_safe s1 -> a_step s1 s2 r -> coh (getP a_lab) (getS s2 a_lab); *)\n\n         (* step_frame : forall s1 s2 r z, *)\n         (*     a_lab != z -> Coh W s1 -> *)\n         (*     a_safe s1 -> a_step s1 s2 r -> getS s1 z  = getS s2 z; *)\n\n         (* Action step semantics respects the overall network semantics *)\n         step_sem  : forall s1 (pf : a_safe s1) s2 r,\n             a_step pf s2 r -> network_step W this s1 s2\n\n       }.\n\n\n(* Framing follows from the network semantics *)\nLemma step_other this V (a : action V this) l s1 s2 r n (pf : a_safe a s1):\n  this != n -> a_step pf s2 r ->\n  getLocal n (getS s1 l) = getLocal n (getS s2 l).\nProof.\nmove=>N S2; move: (step_sem S2)=>H.\nby rewrite eq_sym in N; rewrite /getLocal !(step_is_local l H N).\nQed.\n\nEnd Actions.\n\nSection SkipActionWrapper.\n\nVariable W : world.\nNotation getP l := (getProtocol W l).\nNotation getS s l := (getStatelet s l).\nVariable this : nid.\nVariable l : Label.\nVariable p : protocol.\nVariable pf : getP l = p.\n\nDefinition skip_safe s := Coh W s.\n\nVariable V : Type.\n\n(* Skip-like actions allow for reading from the state *)\nVariable f : forall s, coh p (getS s l) -> V.\n\nLemma safe_local s : skip_safe s -> coh p (getS s l).\nProof. by rewrite -pf=>/(coh_s l). Qed.\n\nDefinition skip_step s1 (pf : skip_safe s1) (s2 : state) r :=\n  [/\\ s1 \\In Coh W, s1 = s2 & r = f (safe_local pf)].\n\n(* Lemma skip_step_safe s1 s2 r: skip_step s1 s2 r -> skip_safe s1. *)\n(* Proof. by case. Qed. *)\n\nLemma skip_step_total s (S : skip_safe s) : exists s' r, skip_step S s' r.\nProof. by exists s, (f (safe_local S)). Qed.\n\nLemma skip_safe_coh s1 : skip_safe s1 -> Coh W s1.\nProof. by []. Qed.\n\nLemma skip_step_sem s1 (S : skip_safe s1) s2 r:\n  skip_step S s2 r -> network_step W this s1 s2.\nProof. by move=>H; apply: Idle; case: H. Qed.\n\nDefinition skip_action_wrapper :=\n  Action skip_safe_coh skip_step_total skip_step_sem.\n\nEnd SkipActionWrapper.\n\n\nSection TryReceiveActionWrapper.\n\nVariable W : world.\nNotation getP l := (getProtocol W l).\nNotation getS s l := (getStatelet s l).\nVariable this : nid.\n\n(*\n\nFilter for specific\n - protocol labels\n - message tags\n - message bodies\n *)\nVariable filter : Label -> nid -> nat -> pred (seq nat).\n\n(* Necessary validity lemmas *)\nVariable f_valid_label : forall l n t m ,\n    filter l n t m -> l \\in dom (getc W).\n\n(* Variable f_valid_tags : forall l t m , *)\n(*     filter l t m -> t \\in rcv_tags (getP l). *)\n\nDefinition tryrecv_act_safe (s : state) := s \\In Coh W.\n\nLemma tryrecv_act_safe_coh s : tryrecv_act_safe s -> Coh W s.\nProof. by []. Qed.\n\n(* Can we make it decidable rather than classic? *)\nDefinition tryrecv_act_step s1 s2 (r : option (nid * nat * seq nat)) :=\n  exists (pf : s1 \\In Coh W),\n  (* No message to receive -- all relevant messages are marked *)\n    ([/\\ (forall l m tms from rt b,\n          this \\in nodes (getP l) (getS s1 l) ->\n          Some (Msg tms from this b) = find m (dsoup (getS s1 l)) ->\n          rt \\In (rcv_trans (getP l)) ->\n          tag tms = (t_rcv rt) ->\n          (* This is required for safety *)\n          msg_wf rt (coh_s l pf) this from tms ->\n          (* The filter applies *)\n          filter l from (t_rcv rt) (tms_cont tms) ->\n          ~~b),\n    r = None & s2 = s1] \\/\n   (* There is a message to receive and the transition can be executed *)\n   exists l m tms from rt (pf' : this \\in nodes (getP l) (getS s1 l)),\n     let: d :=  getS s1 l in\n     [/\\ [/\\ Some (Msg tms from this true) = find m (dsoup (getS s1 l)),\n          rt \\In (rcv_trans (getP l)),\n          tag tms = (t_rcv rt),\n          (* This is required for safety *)\n          msg_wf rt (coh_s l pf) this from tms &\n          (* The filter applies *)\n          filter l from (t_rcv rt) (tms_cont tms)],\n      let loc' := receive_step rt from tms (coh_s l pf) pf' in\n      let: f' := upd this loc' (dstate d) in\n      let: s' := consume_msg (dsoup d) m in\n      s2 = upd l (DStatelet f' s') s1 &\n      r = Some (from, tag tms, tms_cont tms)]).\n\nImport Classical_Prop.\n\nLemma tryrecv_act_step_total s:\n  tryrecv_act_safe s -> exists s' r , tryrecv_act_step s s' r.\nProof.\nmove=>C; rewrite /tryrecv_act_step.\ncase: (classic (exists l m tms from rt (pf' : this \\in nodes (getP l) (getS s l)),\n                   let: d :=  getS s l in\n                   [/\\ Some (Msg tms from this true) = find m (dsoup (getS s l)),\n                    rt \\In (rcv_trans (getP l)),\n                    tag tms = (t_rcv rt),\n                    msg_wf rt (coh_s l C) this from tms &\n                    filter l from (t_rcv rt) (tms_cont tms)])); last first.\n- move=>H; exists s, None, C; left; split=>//l m tms from rt b T E1 E2 E3 E M.\n  apply/negP=>Z; rewrite Z in E1; clear Z b; apply: H.\n  by exists l, m, tms, from, rt.\ncase=>[l][m][tms][from][rt][T][E1 E2 E3 E M].\nexists (let: d :=  getS s l in\n        let loc' := receive_step rt from tms (coh_s l C) T in\n        let: f' := upd this loc' (dstate d) in\n        let: s' := consume_msg (dsoup d) m in\n        upd l (DStatelet f' s') s), (Some (from, tag tms, tms_cont tms)).\nby exists C; right; exists l, m, tms, from, rt, T.\nQed.\n\nLemma tryrecv_act_step_safe s1 s2 r:\n  tryrecv_act_step s1 s2 r -> tryrecv_act_safe s1.\nProof. by case. Qed.\n\nLemma tryrecv_act_step_sem s1 (S : tryrecv_act_safe s1) s2 r:\n  tryrecv_act_step s1 s2 r -> network_step W this s1 s2.\nProof.\ncase=>C; rewrite /tryrecv_act_step; case; first by case=>_ _ ->; apply: Idle.\ncase=>[l][m][tms][from][rt][Y][[E R E1 M]]F/=Z _.\nhave X1: l \\in dom s1 by move: (f_valid_label F); rewrite (cohD C).\nby apply: (ReceiveMsg R X1 E1 (i := m) (from := from)).\nQed.\n\nDefinition tryrecv_action_wrapper :=\n  Action tryrecv_act_safe_coh tryrecv_act_step_total tryrecv_act_step_sem.\n\nEnd TryReceiveActionWrapper.\n\n(* A wrapper for the send-action *)\nSection SendActionWrapper.\n\nVariable W : world.\nVariable p : protocol.\nNotation getP l := (getProtocol W l).\nNotation getS s l := (getStatelet s l).\nVariable this : nid.\n\nVariable l : Label.\n\nVariable pf : (getProtocol W l) = p.\n\n(* A dedicated send-transition *)\nVariable st: send_trans (coh p).\n(* The transition is present *)\nVariable pf' : st \\In (snd_trans p).\n\n(* The message and the recipient *)\nVariable msg : seq nat.\nVariable to  : nid.\n\n(* This check is implicit in the action semantics *)\nDefinition can_send (s : state) := (l \\in dom s) && (this \\in nodes p (getS s l)).\n\n\n(* Take only the hooks that affect the transition with a tag st of *)\n(* protocol l *)\nDefinition filter_hooks (h : hooks) :=\n  um_filterk (fun e => e.2 == (l, t_snd st)) h.\n\nDefinition send_act_safe s :=\n  [/\\ Coh W s, send_safe st this to (getS s l) msg, can_send s &\n      (* All hooks from a \"reduced footprint\" are applicable *)\n      all_hooks_fire (filter_hooks (geth W)) l (t_snd st) s this msg to].\n\nLemma send_act_safe_coh s : send_act_safe s -> Coh W s.\nProof. by case. Qed.\n\nLemma safe_safe s : send_act_safe s -> send_safe st this to (getS s l) msg.\nProof. by case. Qed.\n\nDefinition send_act_step s1 (S: send_act_safe s1) s2 r :=\n   r = msg /\\\n   exists b,\n     Some b = send_step (safe_safe S) /\\\n     let: d :=  getS s1 l in\n     let: f' := upd this b (dstate d) in\n     let: s' := (post_msg (dsoup d) (Msg (TMsg (t_snd st) msg)\n                                         this to true)).1 in\n     s2 = upd l (DStatelet f' s') s1.\n\nLemma send_act_step_total s (S: send_act_safe s): exists s' r , send_act_step S s' r.\nProof.\nrewrite /send_act_step/send_act_safe.\ncase: S=>C S J K.\nmove/(s_safe_def): (S)=>[b][S']E.\nset s2 := let: d :=  getS s l in\n          let: f' := upd this b (dstate d) in\n          let: s' := (post_msg (dsoup d) (Msg (TMsg (t_snd st) msg)\n                                                this to true)).1 in\n          upd l (DStatelet f' s') s.\nexists s2, msg; split=>//; exists b; split=>//.\nmove: (safe_safe (And4 C S J K))=> S''.\nby rewrite -E (pf_irr S'' S') .\nQed.\n\nLemma send_act_step_sem s1 (S : send_act_safe s1) s2 r:\n  send_act_step S s2 r -> network_step W this s1 s2.\nProof.\ncase=>_[b][E Z]; case: (S)=>C S' /andP[D1] D2 K; subst s2=>/=.\nrewrite (pf_irr (safe_safe S) S') in E; clear S.\nrewrite /all_hooks_fire/filter_hooks in K.\nmove: st S' E K pf'; clear pf' st; subst p=>st S' E K' pf'.\napply: (@SendMsg W this s1 _ l st pf' to msg)=>////.\nmove=>z lc hk E'; apply: (K' z); rewrite E'.\nby rewrite find_umfiltk/= eqxx.\nQed.\n\nDefinition send_action_wrapper :=\n  Action send_act_safe_coh send_act_step_total send_act_step_sem.\n\nEnd SendActionWrapper.\n\nEnd Actions.\n\nModule ActionExports.\n\nDefinition action := Actions.action.\nDefinition a_safe := Actions.a_safe.\nDefinition a_step := Actions.a_step.\n\nDefinition a_safe_coh := Actions.a_safe_coh.\nDefinition a_step_total := Actions.step_total.\nDefinition a_step_sem := Actions.step_sem.\nDefinition a_step_other := Actions.step_other.\n\nDefinition skip_action_wrapper := Actions.skip_action_wrapper.\nDefinition send_action_wrapper := Actions.send_action_wrapper.\nDefinition tryrecv_action_wrapper := Actions.tryrecv_action_wrapper.\n\nEnd ActionExports.\n\nExport ActionExports.\n\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/Actions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2660388925637835}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nRequire Export Coq.Strings.String Coq.Lists.List.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Program.\nRequire Import Permutation.\n\nFrom Fairness Require Import Axioms.\nFrom Fairness Require Export ITreeLib FairBeh FairSim NatStructsLarge.\nFrom Fairness Require Import pind PCMLarge World.\nFrom Fairness Require Export Mod Concurrency.\nFrom Fairness Require Import KnotSim LocalAdequacyAux.\nFrom Fairness Require Import\n     ModSim MSim2YOrd YOrd2Stid Stid2NoSync NoSync2Stutter\n     Stutter2Knot Knot2Glob.\nFrom Fairness Require Import SchedSim Adequacy.\n\n\n\nSet Implicit Arguments.\n\n\nSection LADEQ.\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  Let nm_wf_stt: Type -> Type -> WF := nm_wf_stt wf_stt.\n\n  Let shared := shared state_src state_tgt _ident_src _ident_tgt wf_src wf_tgt.\n\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  (* Variable I: shared -> URA.car -> Prop. *)\n\n  Variable St: wf_tgt.(T) -> wf_tgt.(T).\n  Hypothesis lt_succ_diag_r_t: forall (t: wf_tgt.(T)), wf_tgt.(lt) t (St t).\n\n  Lemma ModSimStutter_lsim_implies_gsim\n        R0 R1 (RR: R0 -> R1 -> Prop)\n        (ths_src: threads_src1 R0)\n        (ths_tgt: threads_tgt R1)\n        (WF: th_wf_pair ths_src ths_tgt)\n        tid\n        (FINDS: Th.find tid ths_src = None)\n        (FINDT: Th.find tid ths_tgt = None)\n        src tgt\n        (st_src: state_src) (st_tgt: state_tgt)\n        ps pt\n        (LSIM: forall im_tgt,\n          exists (I: shared -> URA.car -> Prop),\n          exists im_src (os: (nm_wf_stt R0 R1).(T)) rs_ctx o,\n            (<<RSWF: Th.find tid rs_ctx = None>>) /\\\n              (<<OSWF: (forall tid', Th.In tid' ths_src -> Th.In tid' os) /\\ (Th.find tid os = None)>>) /\\\n              (<<LSIM:\n                forall im_tgt0\n                  (FAIR: fair_update im_tgt im_tgt0 (prism_fmap inlp (tids_fmap tid (NatSet.add tid (key_set ths_tgt))))),\n                exists im_src0,\n                  (fair_update im_src im_src0 (prism_fmap inlp (tids_fmap tid (NatSet.add tid (key_set ths_src))))) /\\\n                    (ModSimStutter.lsim (wf_stt) I tid (local_RR I RR tid)\n                                        ps pt (sum_of_resources rs_ctx) (o, src) tgt\n                                        (NatSet.add tid (key_set ths_src),\n                                          im_src0, im_tgt0, st_src, st_tgt))>>) /\\\n              (<<LOCAL: forall tid (src: itree srcE R0) (tgt: itree tgtE R1) o r_own\n                          (OWN: r_own = fst (get_resource tid rs_ctx))\n                          (LSRC: Th.find tid ths_src = Some src)\n                          (LTGT: Th.find tid ths_tgt = Some tgt)\n                          (ORD: Th.find tid os = Some o),\n                  (local_sim_pick wf_stt I RR src tgt tid o r_own)>>))\n    :\n    gsim wf_src wf_tgt RR\n         (interp_all st_src (Th.add tid src ths_src) tid)\n         (interp_all st_tgt (Th.add tid tgt ths_tgt) tid).\n  Proof.\n    remember (Th.map (fun th => (false, th)) ths_src) as ths_src2.\n    assert (FINDS2: Th.find tid ths_src2 = None).\n    { subst. rewrite NatMapP.F.map_o. rewrite FINDS. ss. }\n    assert (WF0: th_wf_pair ths_src2 ths_tgt).\n    { subst. unfold th_wf_pair, nm_wf_pair in *. rewrite <- WF. unfold key_set. rewrite nm_map_unit1_map_eq. auto. }\n    replace ths_src with (nm_proj_v2 ths_src2).\n    2:{ subst. unfold nm_proj_v2. rewrite nm_map_map_eq. ss. apply nm_map_self_eq. }\n    eapply ksim_implies_gsim; auto.\n    eapply Stutter2Knot.lsim_implies_ksim; eauto.\n    i. specialize (LSIM im_tgt). des.\n    replace (NatSet.add tid (key_set ths_src2)) with (NatSet.add tid (key_set ths_src)).\n    2:{ unfold key_set. clarify. rewrite nm_map_unit1_map_eq. auto. }\n    esplits; eauto.\n    { i. apply OSWF. rewrite Heqths_src2 in H. eapply Th.map_2 in H. auto. }\n    i. assert (SF: sf = false).\n    { clarify. rewrite NatMapP.F.map_o in LSRC.\n      destruct (NatMap.find (elt:=thread _ident_src (sE state_src) R0) tid0 ths_src); ss. clarify. }\n    subst sf. split; i; ss. eapply LOCAL; auto.\n    clarify. rewrite NatMapP.F.map_o in LSRC.\n    destruct (NatMap.find (elt:=thread _ident_src (sE state_src) R0) tid0 ths_src); ss. clarify.\n    Unshelve. exact true.\n  Qed.\n\n  Definition ModSimStutter_local_sim_threads\n             (I: shared -> URA.car -> Prop)\n             R0 R1 (RR: R0 -> R1 -> Prop)\n             (ths_src: threads_src1 R0)\n             (ths_tgt: threads_tgt R1)\n    :=\n    List.Forall2\n      (fun '(t1, src) '(t2, tgt) => (t1 = t2) /\\ (ModSimStutter.local_sim wf_stt I RR src tgt))\n      (Th.elements ths_src) (Th.elements ths_tgt).\n\n  Lemma ModSimStutter_local_sim_threads_local_sim_pick\n        R0 R1 (RR: R0 -> R1 -> Prop)\n        (ths_src: threads_src1 R0)\n        (ths_tgt: threads_tgt R1)\n        (* (LOCAL: ModSimStutter_local_sim_threads RR ths_src ths_tgt) *)\n        (st_src: state_src) (st_tgt: state_tgt)\n        (INV: forall im_tgt, exists (I: shared -> URA.car -> Prop), exists im_src r_shared,\n            (ModSimStutter_local_sim_threads I RR ths_src ths_tgt) /\\\n              (I (NatSet.empty, im_src, im_tgt, st_src, st_tgt) r_shared) /\\ (URA.wf r_shared))\n    :\n    forall im_tgt,\n    exists (I: shared -> URA.car -> Prop),\n    exists (im_src0 : imap ident_src wf_src) r_shared0 (os: (nm_wf_stt R0 R1).(T)) (rs_local: local_resources),\n      (I (key_set ths_src, im_src0, im_tgt, st_src, st_tgt) r_shared0) /\\\n        (resources_wf r_shared0 rs_local) /\\\n        (Forall4 (fun '(t1, src) '(t2, tgt) '(t3, r_own) '(t4, o) =>\n                    (t1 = t2) /\\ (t1 = t3) /\\ (t1 = t4) /\\ (local_sim_pick wf_stt I RR src tgt t1 o r_own))\n                 (Th.elements (elt:=thread _ident_src (sE state_src) R0) ths_src)\n                 (Th.elements (elt:=thread _ident_tgt (sE state_tgt) R1) ths_tgt)\n                 (Th.elements rs_local) (Th.elements os)).\n  Proof.\n    i. specialize (INV im_tgt). des. rename INV into LOCAL. exists I. move I after St.\n    unfold ModSimStutter_local_sim_threads in LOCAL.\n    match goal with\n    | FA: List.Forall2 _ ?_ml1 ?_ml2 |- _ => remember _ml1 as tl_src; remember _ml2 as tl_tgt\n    end.\n    move LOCAL before RR. revert_until LOCAL. induction LOCAL; i.\n    {\n      (* specialize (INV im_tgt). des. *)\n      symmetry in Heqtl_src; apply NatMapP.elements_Empty in Heqtl_src.\n      symmetry in Heqtl_tgt; apply NatMapP.elements_Empty in Heqtl_tgt.\n      apply nm_empty_eq in Heqtl_src, Heqtl_tgt. clarify.\n      esplits; ss; eauto.\n      - unfold NatSet.empty in *. rewrite !key_set_empty_empty_eq. eauto.\n      - instantiate (1:=@NatMap.empty _). unfold resources_wf. r_wf INV1.\n        rewrite sum_of_resources_empty. r_solve.\n      - instantiate (1:=NatMap.empty _). econs.\n    }\n\n    des_ifs. des; clarify. rename k0 into tid1, i into src1, i0 into tgt1.\n    hexploit nm_elements_cons_rm. eapply Heqtl_src. intro RESS.\n    hexploit nm_elements_cons_rm. eapply Heqtl_tgt. intro REST.\n    hexploit IHLOCAL; clear IHLOCAL; eauto. intro IND.\n    des.\n    (* clear INV. *)\n    unfold ModSimStutter.local_sim in H0.\n    specialize (H0 _ _ _ _ _ _ (sum_of_resources rs_local) IND tid1 (key_set ths_src)).\n    hexploit H0; clear H0.\n    { econs. rewrite key_set_pull_rm_eq. eapply nm_find_rm_eq.\n      erewrite <- key_set_pull_add_eq. instantiate (1:=src1).\n      rewrite <- nm_find_some_rm_add_eq; auto. eapply nm_elements_cons_find_some; eauto.\n    }\n    { r_wf IND0. }\n    { instantiate (1:=im_tgt). clear. ii. unfold prism_fmap; ss. des_ifs. }\n    i; des.\n    assert (WFPAIR: nm_wf_pair (NatMap.remove (elt:=thread _ident_src (sE state_src) R0) tid1 ths_src) rs_local).\n    { hexploit list_forall4_implies_forall2_3. eauto.\n      { i. instantiate (1:=fun '(t1, src) '(t3, r_own) => t1 = t3). ss. des_ifs. des; auto. }\n      intros FA2. rewrite RESS in FA2. apply nm_forall2_wf_pair in FA2. auto.\n    }\n    assert (RSL: NatMap.find (elt:=M) tid1 rs_local = None).\n    { eapply nm_wf_pair_find_cases in WFPAIR. des. eapply WFPAIR. apply nm_find_rm_eq. }\n    assert (WFPAIRO: nm_wf_pair (NatMap.remove (elt:=thread _ident_src (sE state_src) R0) tid1 ths_src) os).\n    { hexploit list_forall4_implies_forall2_4. eauto.\n      { i. instantiate (1:=fun '(t1, src) '(t4, o) => t1 = t4). ss. des_ifs. des; auto. }\n      intros FA2. rewrite RESS in FA2. apply nm_forall2_wf_pair in FA2. auto.\n    }\n    assert (FINDOS: NatMap.find tid1 os = None).\n    { eapply nm_wf_pair_find_cases in WFPAIRO. des. eapply WFPAIRO. apply nm_find_rm_eq. }\n\n    esplits; eauto.\n    { instantiate (1:=Th.add tid1 r_own rs_local). unfold resources_wf. rewrite sum_of_resources_add. r_wf VALID. auto. }\n    replace (Th.elements (Th.add tid1 r_own rs_local)) with ((tid1, r_own) :: (Th.elements rs_local)).\n    instantiate (1:=Th.add tid1 o os).\n    replace (Th.elements (Th.add tid1 o os)) with ((tid1, o) :: (Th.elements os)).\n    { econs; auto. }\n    { remember (Th.add tid1 o os) as os1.\n      assert (REP: os = (NatMap.remove tid1 os1)).\n      { rewrite Heqos1. rewrite nm_find_none_rm_add_eq; auto. }\n      rewrite REP. rewrite REP in WFPAIRO. rewrite RESS in Heqtl_src.\n      eapply wf_pair_elements_cons_rm; eauto.\n      { eapply nm_wf_pair_rm_inv; eauto.\n        - unfold NatMap.In, NatMap.Raw.PX.In. exists src1. unfold NatMap.Raw.PX.MapsTo. ss.\n          unfold Th.elements, Th.Raw.elements in Heqtl_src. rewrite <- Heqtl_src. econs 1. ss.\n        - rewrite Heqos1. apply NatMapP.F.add_in_iff. auto.\n      }\n      { rewrite Heqos1. rewrite nm_find_add_eq; auto. }\n    }\n    { remember (Th.add tid1 r_own rs_local) as rs_local1.\n      assert (REP: rs_local = (NatMap.remove tid1 rs_local1)).\n      { rewrite Heqrs_local1. rewrite nm_find_none_rm_add_eq; auto. }\n      rewrite REP. rewrite REP in WFPAIR. rewrite RESS in Heqtl_src.\n      eapply wf_pair_elements_cons_rm; eauto.\n      { eapply nm_wf_pair_rm_inv; eauto.\n        - unfold NatMap.In, NatMap.Raw.PX.In. exists src1. unfold NatMap.Raw.PX.MapsTo. ss.\n          unfold Th.elements, Th.Raw.elements in Heqtl_src. rewrite <- Heqtl_src. econs 1. ss.\n        - rewrite Heqrs_local1. apply NatMapP.F.add_in_iff. auto.\n      }\n      { rewrite Heqrs_local1. rewrite nm_find_add_eq; auto. }\n    }\n  Qed.\n\n  Lemma forall4_implies_gsim\n        R0 R1 (RR: R0 -> R1 -> Prop)\n        (ths_src: threads_src1 R0)\n        (ths_tgt: threads_tgt R1)\n        (st_src: state_src) (st_tgt: state_tgt)\n        tid\n    :\n    (forall im_tgt,\n      exists (I: shared -> URA.car -> Prop),\n      exists (im_src0 : imap ident_src wf_src) r_shared0 (os: (nm_wf_stt R0 R1).(T)) (rs_local: local_resources),\n        (I (key_set ths_src, im_src0, im_tgt, st_src, st_tgt) r_shared0) /\\\n          (resources_wf r_shared0 rs_local) /\\\n          (Forall4 (fun '(t1, src) '(t2, tgt) '(t3, r_own) '(t4, o) =>\n                      (t1 = t2) /\\ (t1 = t3) /\\ (t1 = t4) /\\ (local_sim_pick wf_stt I RR src tgt t1 o r_own))\n                   (Th.elements (elt:=thread _ident_src (sE state_src) R0) ths_src)\n                   (Th.elements (elt:=thread _ident_tgt (sE state_tgt) R1) ths_tgt)\n                   (Th.elements rs_local) (Th.elements os))) ->\n    gsim wf_src wf_tgt RR\n         (interp_all st_src ths_src tid)\n         (interp_all st_tgt ths_tgt tid).\n  Proof.\n    intros USIM. ii. assert (WFP: nm_wf_pair ths_src ths_tgt).\n    { specialize (USIM mt). des. eapply list_forall4_implies_forall2_2 in USIM1.\n      2:{ i. instantiate (1:= fun '(k1, _) '(k2, _) => k1 = k2). des_ifs. des; clarify. }\n      eapply nm_forall2_wf_pair.  auto.\n    }\n    cut (gsim wf_src wf_tgt RR (interp_all st_src ths_src tid) (interp_all st_tgt ths_tgt tid)).\n    { i. specialize (H mt). auto. }\n    clear mt.\n\n    destruct (NatMapP.F.In_dec ths_src tid).\n    2:{ destruct (NatMapP.F.In_dec ths_tgt tid).\n        { eapply nm_wf_pair_find_cases in WFP. des. eapply NatMapP.F.not_find_in_iff in n.\n          eapply WFP in n. eapply NatMapP.F.not_find_in_iff in n. clarify. }\n        eapply NatMapP.F.not_find_in_iff in n. eapply NatMapP.F.not_find_in_iff in n0.\n        unfold interp_all.\n        rewrite (unfold_interp_sched_nondet_None tid _ _ n).\n        rewrite (unfold_interp_sched_nondet_None tid _ _ n0).\n        rewrite !interp_state_vis. unfold gsim. i.\n        specialize (USIM mt). des. exists im_src0, false, false.\n        rewrite <- bind_trigger. pfold. econs 10.\n    }\n    rename i into INS.\n    assert (INT: Th.In tid ths_tgt).\n    { destruct (NatMapP.F.In_dec ths_tgt tid); auto.\n      apply nm_wf_pair_sym in WFP. eapply nm_wf_pair_find_cases in WFP. des.\n      eapply NatMapP.F.not_find_in_iff in n. eapply WFP in n.\n      eapply NatMapP.F.not_find_in_iff in n. clarify.\n    }\n    (* clear WFP. *)\n\n    eapply NatMapP.F.in_find_iff in INS, INT.\n    destruct (Th.find tid ths_src) eqn:FINDS.\n    2:{ clarify. }\n    destruct (Th.find tid ths_tgt) eqn:FINDT.\n    2:{ clarify. }\n    clear INS INT. rename i into src0, i0 into tgt0.\n    remember (Th.remove tid ths_src) as ths_src0.\n    remember (Th.remove tid ths_tgt) as ths_tgt0.\n    assert (POPS: nm_pop tid ths_src = Some (src0, ths_src0)).\n    { unfold nm_pop. rewrite FINDS. rewrite Heqths_src0. auto. }\n    assert (POPT: nm_pop tid ths_tgt = Some (tgt0, ths_tgt0)).\n    { unfold nm_pop. rewrite FINDT. rewrite Heqths_tgt0. auto. }\n    i. replace ths_src with (Th.add tid src0 ths_src0).\n    2:{ symmetry; eapply nm_pop_res_is_add_eq; eauto. }\n    replace ths_tgt with (Th.add tid tgt0 ths_tgt0).\n    2:{ symmetry; eapply nm_pop_res_is_add_eq; eauto. }\n\n    assert (WFST0: nm_wf_pair ths_src0 ths_tgt0).\n    { subst. eapply nm_wf_pair_rm. auto. }\n    clear WFP.\n    eapply ModSimStutter_lsim_implies_gsim; auto.\n    { eapply nm_pop_res_find_none; eauto. }\n    { eapply nm_pop_res_find_none; eauto. }\n\n    cut (forall im_tgt0,\n            exists (I: shared -> URA.car -> Prop),\n          exists im_src0 r_shared0 (os0: (nm_wf_stt R0 R1).(T)) rs_ctx0,\n            (I (key_set ths_src, im_src0, im_tgt0, st_src, st_tgt) r_shared0) /\\\n              (resources_wf r_shared0 rs_ctx0) /\\\n              (nm_wf_pair ths_src os0) /\\\n              (forall (tid0 : Th.key) (src : thread _ident_src (sE state_src) R0)\n                 (tgt : thread _ident_tgt (sE state_tgt) R1) o r_own,\n                  (r_own = fst (get_resource tid0 rs_ctx0)) ->\n                  (Th.find (elt:=thread _ident_src (sE state_src) R0) tid0 ths_src = Some src) ->\n                  (Th.find (elt:=thread _ident_tgt (sE state_tgt) R1) tid0 ths_tgt = Some tgt) ->\n                  (Th.find tid0 os0 = Some o) ->\n                  local_sim_pick wf_stt I RR src tgt tid0 o r_own)).\n    { i. specialize (H im_tgt). des.\n      assert (POPOS: exists o os, nm_pop tid os0 = Some (o, os)).\n      { hexploit nm_wf_pair_pop_cases. eapply H1. instantiate (1:=tid). i; des; eauto.\n        unfold nm_pop in H3. rewrite FINDS in H3. ss. }\n      des. exists I, im_src0, os, (snd (get_resource tid rs_ctx0)), o. splits.\n      - eapply get_resource_snd_find_eq_none.\n      - i. eapply nm_wf_pair_pop_cases in H1. des. erewrite POPS in H1. ss.\n        rewrite POPS in H1; rewrite POPOS in H4. clarify.\n        eapply nm_wf_pair_find_cases in H5. des. eapply NatMapP.F.in_find_iff. eapply H1.\n        eapply NatMapP.F.in_find_iff. auto.\n      - eapply find_none_aux; eauto.\n      - ii. specialize (H2 tid src0 tgt0 o (fst (get_resource tid rs_ctx0))). hexploit H2; clear H2; auto.\n        { eapply nm_pop_find_some; eauto. }\n        i. unfold local_sim_pick in H2.\n        assert (SETS: NatSet.add tid (key_set ths_src0) = key_set ths_src).\n        { subst. rewrite key_set_pull_rm_eq. unfold NatSet.add.\n          rewrite <- nm_find_some_rm_add_eq; auto. eapply key_set_find_some1; eauto.\n        }\n        hexploit H2; clear H2. eapply H.\n        { instantiate (1:=sum_of_resources (snd (get_resource tid rs_ctx0))).\n          hexploit resources_wf_get_wf. eapply H0.\n          2:{ i. des. eapply WF. }\n          instantiate (1:=tid). destruct (get_resource tid rs_ctx0); ss.\n        }\n        { rewrite <- SETS; eauto. unfold nm_wf_pair in WFST0. rewrite WFST0. eauto. }\n        rewrite !SETS. i; des. esplits; eauto.\n      - i. eapply H2.\n        { rewrite OWN. eapply get_resource_rs_neq. destruct (tid_dec tid tid0); auto. clarify.\n          rewrite nm_find_rm_eq in LSRC. ss. }\n        eapply find_some_aux; eauto. eapply find_some_aux; eauto. eapply find_some_aux; eauto.\n    }\n\n    cut (forall im_tgt,\n            exists (I: shared -> URA.car -> Prop),\n          exists (im_src0 : imap ident_src wf_src) r_shared0 (os0: (nm_wf_stt R0 R1).(T)) rs_ctx0,\n            (I (key_set ths_src, im_src0, im_tgt, st_src, st_tgt) r_shared0) /\\\n              (resources_wf r_shared0 rs_ctx0) /\\\n              (Forall3 (fun '(t1, src) '(t2, tgt) '(t3, o) =>\n                          (t1 = t2) /\\ (t1 = t3) /\\\n                            (local_sim_pick wf_stt I RR src tgt t1 o (fst (get_resource t1 rs_ctx0))))\n                       (Th.elements (elt:=thread _ident_src (sE state_src) R0) ths_src)\n                       (Th.elements (elt:=thread _ident_tgt (sE state_tgt) R1) ths_tgt)\n                       (Th.elements os0))).\n    { intro FA. i. specialize (FA im_tgt0). des. esplits; eauto.\n      { hexploit list_forall3_implies_forall2_3. eauto.\n        { i. instantiate (1:= fun '(t1, src) '(t3, o) => t1 = t3). ss. des_ifs. des; auto. }\n        intros FA2. apply nm_forall2_wf_pair in FA2. eauto.\n      }\n      i. subst. eapply nm_forall3_implies_find_some in FA1; eauto.\n    }\n\n    i. rename USIM into FAALL. specialize (FAALL im_tgt). des.\n    exists I, im_src0, r_shared0, os, rs_local. splits; auto.\n    clear - FAALL1.\n    eapply nm_find_some_implies_forall3.\n    { hexploit list_forall4_implies_forall2_2. eauto.\n      { i. instantiate (1:=fun '(t1, src) '(t2, tgt) => t1 = t2). ss. des_ifs. des; auto. }\n      intros FA2. apply nm_forall2_wf_pair; auto.\n    }\n    { hexploit list_forall4_implies_forall2_4. eauto.\n      { i. instantiate (1:=fun '(t1, src) '(t4, o) => t1 = t4). ss. des_ifs. des; auto. }\n      intros FA2. apply nm_forall2_wf_pair; auto.\n    }\n    { i. hexploit nm_forall4_implies_find_some. eapply FAALL1. all: eauto.\n      2:{ ss. eauto. }\n      assert (WFPAIR: nm_wf_pair ths_src rs_local).\n      { hexploit list_forall4_implies_forall2_3. eauto.\n        { i. instantiate (1:=fun '(t1, src) '(t3, r_own) => t1 = t3). ss. des_ifs. des; auto. }\n        intros FA2. apply nm_forall2_wf_pair in FA2. auto.\n      }\n      hexploit nm_wf_pair_find_cases. eapply WFPAIR. i. des. clear H. hexploit H0.\n      { ii. rewrite FIND1 in H. ss. }\n      i. destruct (NatMap.find k rs_local) eqn:FRS; ss. erewrite get_resource_find_some_fst; eauto.\n    }\n    Unshelve. all: exact true.\n  Qed.\n\n  Theorem ModSimStutter_local_sim_implies_gsim\n          R0 R1 (RR: R0 -> R1 -> Prop)\n          (ths_src: threads_src1 R0)\n          (ths_tgt: threads_tgt R1)\n          (* (LOCAL: ModSimStutter_local_sim_threads RR ths_src ths_tgt) *)\n          (st_src: state_src) (st_tgt: state_tgt)\n          (INV: forall im_tgt, exists (I: shared -> URA.car -> Prop), exists im_src r_shared,\n              (ModSimStutter_local_sim_threads I RR ths_src ths_tgt) /\\\n                (I (NatSet.empty, im_src, im_tgt, st_src, st_tgt) r_shared) /\\ (URA.wf r_shared))\n          tid\n    :\n    gsim wf_src wf_tgt RR\n         (interp_all st_src ths_src tid)\n         (interp_all st_tgt ths_tgt tid).\n  Proof.\n    eapply forall4_implies_gsim. i.\n    i. hexploit ModSimStutter_local_sim_threads_local_sim_pick; eauto.\n  Qed.\n\nEnd LADEQ.\n\n\nSection ADEQ.\n\n  Lemma _numbering_cons\n        E (l: list E) n x\n    :\n    _numbering (x :: l) n = (n, x) :: (_numbering l (S n)).\n  Proof. reflexivity. Qed.\n\n  Lemma of_list_cons\n        elt (l: list (NatMap.key * elt)) k e\n    :\n    NatMapP.of_list ((k, e) :: l) = Th.add k e (NatMapP.of_list l).\n  Proof. reflexivity. Qed.\n\n  Lemma mod_funs_cases\n        (m: Mod.t)\n    :\n    (forall fn, Mod.funs m fn = None) \\/ (exists fn ktr, Mod.funs m fn = Some ktr).\n  Proof.\n    destruct (classic (forall fn, Mod.funs m fn = None)); auto.\n    apply Classical_Pred_Type.not_all_ex_not in H. right. des.\n    destruct (Mod.funs m n) eqn:FUNS; ss; eauto.\n  Qed.\n\n  Theorem modsim_adequacy\n          m_src m_tgt\n          (MSIM: ModSim.ModSim.mod_sim m_src m_tgt)\n    :\n    forall tid (p: program),\n      Adequacy.improves (interp_all m_src.(Mod.st_init) (prog2ths m_src p) tid)\n                        (interp_all m_tgt.(Mod.st_init) (prog2ths m_tgt p) tid).\n  Proof.\n    apply modsim_implies_yord_mod in MSIM.\n    apply yord_implies_stid_mod in MSIM.\n    apply stid_implies_nosync_mod in MSIM.\n    apply nosync_implies_stutter_mod in MSIM.\n    inv MSIM. i.\n    eapply Adequacy.adequacy. eapply wf_tgt_inhabited. eapply wf_tgt_open.\n    instantiate (1:=wf_src).\n    destruct (mod_funs_cases m_src).\n    { ii. specialize (init mt). des. exists im_src, false, false.\n      destruct (Th.find tid (prog2ths m_src p)) eqn:FIND.\n      2:{ unfold interp_all. rewrite unfold_interp_sched_nondet_None.\n          rewrite interp_state_vis. rewrite <- bind_trigger. pfold. econs 10. auto.\n      }\n      unfold interp_all. erewrite unfold_interp_sched_nondet_Some.\n      2: eauto.\n      rename init0 into funs.\n      assert (UB: i = (Vis (inl1 (inl1 (inl1 Undefined))) (Empty_set_rect _))).\n      { revert_until funs. clear. i. unfold prog2ths, numbering in FIND.\n        remember 0 as k. clear Heqk. move p after tid. revert_until p. induction p; i; ss.\n        destruct a as [fn args]. unfold NatMapP.uncurry in FIND. ss.\n        destruct (tid_dec tid k); clarify.\n        { rewrite nm_find_add_eq in FIND. clarify. unfold fn2th. rewrite H. auto. }\n        rewrite nm_find_add_neq in FIND; auto. eapply IHp; eauto.\n      }\n      clarify. rewrite interp_thread_vis_eventE. ired. rewrite interp_state_vis.\n      rewrite <- bind_trigger. pfold. econs 10.\n    }\n\n    des. rename fn into fn0, ktr into ktr0, H into SOME0.\n    eapply ModSimStutter_local_sim_implies_gsim.\n    instantiate (1:= fun o0 => @epsilon _ wf_tgt_inhabited (fun o1 => wf_tgt.(lt) o0 o1)).\n    { i. hexploit (@epsilon_spec _ wf_tgt_inhabited (fun o1 => wf_tgt.(lt) t o1)); eauto. }\n    instantiate (1:=wf_stt).\n    i. specialize (init im_tgt). des. esplits; eauto.\n    unfold ModSimStutter_local_sim_threads, prog2ths. unfold numbering.\n    remember 0 as k. clear Heqk. move p before k. revert_until p.\n    induction p; i.\n    { ss. unfold NatMap.Raw.empty. econs. }\n    rewrite !map_cons, !_numbering_cons. destruct a as [fn args].\n    rewrite !of_list_cons. eapply nm_find_some_implies_forall2.\n    { apply nm_wf_pair_add. clear. move p after m_src. revert_until p. induction p; i.\n      { ss. apply nm_wf_pair_empty_empty_eq. }\n      ss. destruct a as [fn args]. unfold NatMapP.uncurry. ss. eapply nm_wf_pair_add.\n      eauto.\n    }\n    i. destruct (tid_dec k k0); clarify.\n    { clear IHp. rewrite nm_find_add_eq in FIND1, FIND2. clarify. unfold fn2th.\n      rename init0 into funs.\n      dup funs. specialize (funs0 fn0 ([]: list Val)↑). rewrite SOME0 in funs0.\n      specialize (funs fn args). des_ifs; ss.\n      unfold local_sim in funs0. ii.\n      specialize (funs0 _ _ _ _ _ _ _ INV _ _ THS VALID _ UPD). des.\n      esplits; eauto. i. specialize (funs0 _ _ _ _ _ _ _ INV1 VALID1 _ TGT). des.\n      esplits. eapply SRC. i. instantiate (1:=o).\n      pfold. eapply pind6_fold. rewrite <- bind_trigger. eapply lsim_UB.\n    }\n    rewrite nm_find_add_neq in FIND1, FIND2; auto.\n    specialize (IHp (S k)). eapply nm_forall2_implies_find_some in IHp; eauto.\n  Qed.\n\nEnd ADEQ.\n\n\n\nSection USERADEQ.\n\n  Theorem usersim_adequacy\n          m_src m_tgt\n          p_src p_tgt\n          (MSIM: ModSim.UserSim.sim m_src m_tgt p_src p_tgt)\n    :\n    forall tid,\n      Adequacy.improves (interp_all m_src.(Mod.st_init) p_src tid)\n                        (interp_all m_tgt.(Mod.st_init) p_tgt tid).\n  Proof.\n    apply modsim_implies_yord_user in MSIM.\n    apply yord_implies_stid_user in MSIM.\n    apply stid_implies_nosync_user in MSIM.\n    apply nosync_implies_stutter_user in MSIM.\n    inv MSIM. i.\n    eapply Adequacy.adequacy. eapply wf_tgt_inhabited. eapply wf_tgt_open.\n    instantiate (1:=wf_src).\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 forall4_implies_gsim. eauto.\n    instantiate (1:=wf_stt). i. specialize (funs im_tgt). des. exists I. esplits; eauto.\n  Qed.\n\nEnd USERADEQ.\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/ModAdequacy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6654105454764746, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2660388819525113}}
{"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)                    *)\nRequire Export Sets.\nRequire Export Axioms.\nRequire Export Omega.\n\nDefinition ord : forall E E' : Ens, INC E' E -> Prop.\nsimple induction E.\nintros A f HR.\nintros E' i.\napply and.\nexact (forall a : A, IN (f a) E' -> HR a (f a) (INC_refl (f a))).\n\nexact\n (forall (a : A) (e : Ens),\n  IN (f a) E' -> forall p : INC e (f a), HR a e p -> IN e E').\n\nDefined.\n\n\nLemma ord_ext :\n forall (E E' E'' : Ens) (p' : INC E' E) (p'' : INC E'' E),\n EQ E' E'' -> ord E E' p' -> ord E E'' p''.\nsimple induction E.\nintros A f HR.\nsimpl in |- *.\nintros E' E'' I' I'' e.\nsimple induction 1.\nintros o1 o2.\nclear H.\nsplit.\nauto with zfc.\nintros; apply o1.\napply IN_sound_right with E''; auto with zfc.\n\nintros.\napply IN_sound_right with E'; auto with zfc.\napply (o2 a) with (p := p).\napply IN_sound_right with E''; auto with zfc.\n\nauto with zfc.\nQed.\n\nLemma ord_sound :\n forall E E' : Ens,\n EQ E E' ->\n forall (E'' : Ens) (p : INC E'' E) (p' : INC E'' E'),\n (ord E E'' p -> ord E' E'' p') /\\ (ord E' E'' p' -> ord E E'' p).\nsimple induction E; intros A f HR; simple induction E'; intros A' f' HR'.\nintros e E'' p p'.\nelim e; intros e1 e2.\nsplit.\nintros o.\nelim o; intros o1 o2.\nsimpl in |- *.\nsplit.\nintros a' i.\nelim (e2 a'); intros a eq.\ncut (INC (f' a') (f a)).\nintros inc.\nelim (HR a (f' a') eq (f' a') inc (INC_refl (f' a'))).\nintros h1 h2.\nauto with zfc.\napply h1.\napply ord_ext with (f a) (INC_refl (f a)).\nauto with zfc.\n\nauto with zfc.\napply o1.\napply IN_sound_left with (f' a'); auto with zfc.\n\nauto with zfc.\n\nintros a' E0 i inc.\nintros or.\nelim (e2 a'); intros a eq.\ncut (INC E0 (f a)).\nintros inc0.\napply (o2 a E0) with inc0.\napply IN_sound_left with (f' a'); auto with zfc.\n\nelim (HR a (f' a')) with (E'' := E0) (p := inc0) (p' := inc).\nintros h1 h2.\nauto with zfc.\n\nauto with zfc.\n\napply INC_sound_right with (f' a'); auto with zfc.\n\nintros o; elim o; intros o1 o2.\nsplit.\nintros a i.\nelim (e1 a); intros a' eq.\ncut (INC (f a) (f' a')); auto with zfc.\ncut (INC (f' a') (f a)); auto with zfc.\nintros inc1 inc2.\nelim (HR a (f' a')) with (E'' := f a) (p := INC_refl (f a)) (p' := inc2).\nintros h1 h2.\napply h2.\napply ord_ext with (E' := f' a') (p' := INC_refl (f' a')).\nauto with zfc.\n\nauto with zfc.\napply o1.\napply IN_sound_left with (f a); auto with zfc.\n\nauto with zfc.\nintros a E0 i inc ord0.\nelim (e1 a); intros a' eq.\ncut (INC E0 (f' a')).\nintros inc0.\napply (o2 a') with (p := inc0).\napply IN_sound_left with (f a); auto with zfc.\n\nelim (HR a (f' a') eq E0 inc inc0).\nintros h1 h2.\nauto with zfc.\n\napply INC_sound_right with (f a); auto with zfc.\nQed.\n\nDefinition Ord (E : Ens) := ord E E (INC_refl E).\n\n\nLemma Ord_sound : forall E E' : Ens, EQ E E' -> Ord E -> Ord E'.\nunfold Ord in |- *.\nintros.\ncut (INC E' E).\nintros inc; elim (ord_sound E E' H E' inc (INC_refl E')).\nintros h1 h2.\nunfold Ord in |- *.\n\napply h1.\napply ord_ext with E (INC_refl E); auto with zfc.\nauto with zfc.\nQed.\n\n\nLemma IN_Ord_Ord : forall E E' : Ens, Ord E -> IN E' E -> Ord E'.\n\nsimple induction E; intros A f HR E'.\nsimple induction 1; intros o1 o2.\nchange (forall a : A, IN (f a) (sup A f) -> Ord (f a)) in o1.\nintros i.\nelim i; intros a eq.\napply Ord_sound with (f a); auto with zfc.\napply o1.\nauto with zfc.\nexists a; auto with zfc.\nQed.\n\nLemma ord_tech :\n forall (E1 E2 E : Ens) (p1 : INC E E1) (p2 : INC E E2),\n ord E1 E p1 -> ord E2 E p2.\nsimple induction E1; intros A1 f1 HR1; simple induction E2;\n intros A2 f2 HR2 E p1 p2.\nsimple induction 1; intros o1 o2.\nsplit.\nintros a2 i2.\nelim (IN_EXType _ _ i2).\nintros x e.\nchange (Ord (f2 a2)) in |- *.\napply Ord_sound with (pi2 E x).\nauto with zfc.\n\ncut (IN (pi2 E x) (sup A1 f1)).\nsimple induction 1; intros a1 e1.\napply Ord_sound with (f1 a1); auto with zfc.\nunfold Ord in |- *; apply o1.\napply IN_sound_left with (pi2 E x); auto with zfc.\napply IN_sound_left with (f2 a2); auto with zfc.\n\nunfold INC in p1; apply p1; auto with zfc.\napply IN_sound_left with (f2 a2); auto with zfc.\n\nintros a2 e i inc o.\nelim (IN_EXType _ _ i).\nintros x e2.\ncut (IN (pi2 E x) (sup A1 f1)).\nsimple induction 1; intros a1 e1.\ncut (INC e (f1 a1)).\nintros inc1.\napply (o2 a1) with (p := inc1).\napply IN_sound_left with (pi2 E x).\nauto with zfc.\n\napply IN_sound_left with (f2 a2); auto with zfc.\n\nelim (ord_sound (f1 a1) (f2 a2)) with (p := inc1) (p' := inc).\nintros h1 h2.\nauto with zfc.\n\napply EQ_tran with (pi2 E x).\nauto with zfc.\n\nauto with zfc.\n\nauto with zfc.\napply INC_sound_right with (pi2 E x).\nauto with zfc.\n\napply INC_sound_right with (f2 a2); auto with zfc.\n\napply IN_sound_left with (f2 a2); auto with zfc.\n\nQed.\n\n\nLemma plump :\n forall E : Ens,\n Ord E ->\n forall E1 E2 : Ens, Ord E1 -> Ord E2 -> IN E1 E -> INC E2 E1 -> IN E2 E.\nsimple induction E; intros A f HR.\nsimple induction 1; intros o1 o2.\nintros E1 E2 o11 o22 i inc.\nelim (IN_EXType _ _ i).\nintros a eq; simpl in a; simpl in eq.\ncut (INC E2 (f a)).\nintros inc0; apply (o2 a) with (p := inc0).\nexists a; auto with zfc.\n\napply ord_tech with (E1 := E2) (p1 := INC_refl E2) (p2 := inc0).\nassumption.\n\napply INC_sound_right with E1; auto with zfc.\n\nQed.\n\nLemma Ord_intro :\n forall E : Ens,\n (forall E' : Ens, IN E' E -> Ord E') ->\n (forall E1 E2 : Ens, Ord E1 -> Ord E2 -> IN E1 E -> INC E2 E1 -> IN E2 E) ->\n Ord E.\nsimple induction E; intros A f HR h1 h2; split.\nintros a i.\nchange (Ord (f a)) in |- *; apply h1; exists a; auto with zfc.\n\nintros a E1 i inc o.\napply h2 with (E1 := f a).\nauto with zfc.\n\nauto with zfc.\nunfold Ord in |- *.\napply (ord_tech (f a)) with (p1 := inc) (p2 := INC_refl E1);\n auto with zfc.\n\nexists a; auto with zfc.\n\nauto with zfc.\nQed.\n\nLemma Ord_trans :\n forall E : Ens, Ord E -> forall E' : Ens, IN E' E -> INC E' E.\nsimple induction E; intros A f HR o E' i.\nunfold INC in |- *.\nintros E'' i'.\napply plump with E'.\n\nauto with zfc.\n\napply IN_Ord_Ord with (sup A f); auto with zfc.\n\napply IN_Ord_Ord with E'; auto with zfc; apply IN_Ord_Ord with (sup A f);\n auto with zfc.\n\nauto with zfc.\n\nelim i; intros a e.\napply INC_sound_right with (f a); auto with zfc.\napply HR; auto with zfc.\napply IN_Ord_Ord with (sup A f); auto with zfc; exists a;\n auto with zfc.\n\napply IN_sound_right with E'; auto with zfc.\n\nQed.\n\n\n\nLemma inter_ord : forall E : Ens, Ord E -> Ord (Inter E).\nsimple induction E; intros A f HR o; apply Ord_intro.\nintros E'.\nsimple induction 1.\nsimple induction x; intro a.\nsimple induction p.\nintros b.\nintros h e.\napply Ord_sound with (pi2 (f a) b); auto with zfc.\napply IN_Ord_Ord with (f a); auto with zfc.\napply IN_Ord_Ord with (sup A f).\nassumption.\n\nexists a; auto with zfc.\n\nintros.\nelim H1; simple induction x.\nintro a; simple induction p.\nintros b h e.\napply all_IN_Inter with (f a).\nexists a; auto with zfc.\n\nintros.\napply plump with E1.\nauto with zfc.\napply IN_Ord_Ord with (sup A f); auto with zfc.\n\nauto with zfc.\n\nauto with zfc.\n\napply IN_Inter_all with (sup A f); auto with zfc.\n\nauto with zfc.\nQed.\n\n\nLemma union_Ord : forall E : Ens, Ord E -> Ord (Union E).\nsimple induction E; intros A f HR o.\napply Ord_intro.\nintros E'; simple induction 1.\nsimple induction x.\nintros a b.\nsimpl in |- *.\nintros e.\napply IN_Ord_Ord with (f a); auto with zfc.\napply IN_Ord_Ord with (sup A f); try exists a; auto with zfc.\n\napply IN_sound_left with (pi2 (f a) b); auto with zfc.\ngeneralize b; elim (f a).\nsimpl in |- *.\nintros.\nexists b0; auto with zfc.\n\nintros E1 E2 o1 o2; simple induction 1.\nsimple induction x.\nintros a b e inc.\nsimpl in e.\napply IN_Union with (f a).\nexists a; try trivial with zfc.\n\napply plump with E1; auto with zfc.\napply IN_Ord_Ord with (sup A f); try exists a; auto with zfc.\n\napply IN_sound_left with (pi2 (f a) b); auto with zfc.\ngeneralize b; elim (f a); simpl in |- *; intros.\nexists b0; auto with zfc.\n\nQed.\n\nLemma Inter_Ord :\n forall E : Ens, (forall E' : Ens, IN E' E -> Ord E') -> Ord (Inter E).\nsimple induction E; intros A f HR H.\napply Ord_intro.\nintros E' i.\nelim i.\nsimple induction x.\nintro a; simple induction p.\nintros b h.\nintros e.\napply IN_Ord_Ord with (f a).\napply H; exists a; auto with zfc.\n\napply IN_sound_left with (pi2 (f a) b); auto with zfc.\n\nintros E1 E2 o1 o2 i inc.\nelim i.\nsimple induction x.\nintro a; simple induction p.\nintros b h e.\napply all_IN_Inter with (f a).\nexists a; auto with zfc.\n\nintros.\napply plump with E1; auto with zfc.\napply IN_Inter_all with (sup A f); auto with zfc.\nQed.\n\nLemma Union_Ord :\n forall E : Ens, (forall E' : Ens, IN E' E -> Ord E') -> Ord (Union E).\nsimple induction E; intros A f HR h.\napply Ord_intro.\nintros E' i.\nelim i.\nsimple induction x; intros a.\nintros b e.\nsimpl in e.\napply Ord_sound with (pi2 (f a) b).\nauto with zfc.\napply IN_Ord_Ord with (f a); auto with zfc.\napply h; exists a; auto with zfc.\ngeneralize b; elim (f a); simpl in |- *.\nintros.\nexists b0; auto with zfc.\nintros.\nelim (Union_IN (sup A f) E1); auto with zfc.\nintros E3.\nsimple induction 1.\nintros i1 i2.\napply IN_Union with E3.\nauto with zfc.\napply plump with E1; auto with zfc.\nQed.\n\n\nDefinition Succ (E : Ens) := Comp (Power E) Ord.\n\nLemma Ord_Succ : forall E : Ens, Ord E -> Ord (Succ E).\nunfold Succ in |- *; intros E o.\napply Ord_intro.\nintros.\napply IN_Comp_P with (Power E).\nintros w1 w2 o1 e; apply Ord_sound with w1; auto with zfc.\n\nauto with zfc.\n\nintros E1 E2 o1 o2 i inc.\napply IN_P_Comp; auto with zfc.\nintros w1 w2 ow1 e; apply Ord_sound with w1; auto with zfc.\n\napply INC_IN_Power.\napply INC_tran with E1; auto with zfc.\ncut (IN E1 (Power E)).\nintros i1.\napply IN_Power_INC; try trivial with zfc.\n\ncut (INC (Comp (Power E) Ord) (Power E)).\nintros inc1.\napply inc1; try trivial with zfc.\n\napply Comp_INC; try trivial with zfc.\n\nQed.\n\nLemma Succ_incr : forall E : Ens, Ord E -> IN E (Succ E).\n\nunfold Succ in |- *; intros.\napply IN_P_Comp.\nintros w1 w2 o1 e; apply Ord_sound with w1; auto with zfc.\nauto with zfc.\napply INC_IN_Power; auto with zfc.\ntry trivial with zfc.\nQed.\n\nDefinition PI1 : forall (A : Type) (P : A -> Type), depprod A P -> A.\nsimple induction 1; intros a p.\nexact a.\nDefined.\n\nDefinition PI2 :\n  forall (A : Type) (P : A -> Type) (c : depprod A P), P (PI1 A P c).\nsimple induction c.\nintros a p.\nexact p.\nDefined.\n", "meta": {"author": "coq-contribs", "repo": "zfc", "sha": "ede7126560844c381c2b021003a8dbcb0668ecad", "save_path": "github-repos/coq/coq-contribs-zfc", "path": "github-repos/coq/coq-contribs-zfc/zfc-ede7126560844c381c2b021003a8dbcb0668ecad/Plump.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.26586389749020967}}
{"text": "(*\n   Quark is Copyright (C) 2012-2015, Quark Team.\n\n   You can redistribute and modify it under the terms of the GNU GPL,\n   version 2 or later, but it is made available WITHOUT ANY WARRANTY.\n\n   For more information about Quark, see our web site at:\n   http://goto.ucsd.edu/quark/\n*)\n\n\nRequire Import Ynot.\nRequire Import Basis.\nRequire Import List.\nRequire Import Ascii.\nRequire Import String.\nRequire Import List.\nRequire Import RSep.\nRequire Import NArith.\nRequire Import Arith.\nRequire Import VCRIO.\nRequire Import Message.\nRequire Import Sumbool.\n\nOpen Local Scope stsepi_scope.\nOpen Local Scope hprop_scope.\n\nLtac inv H :=\n  inversion H; subst; clear H.\n\nLtac Unify :=\n  match goal with\n  | H1: ?x = ?a,\n    H2: ?x = ?b |- _ =>\n      rewrite H1 in H2; symmetry in H2;\n      inversion H2; subst; clear H2;\n      try Unify\n  end.\n\nFixpoint beq_la (la:list ascii) (la2:list ascii) : bool :=\n  match la with \n  | a :: la =>\n    match la2 with\n      | a2 :: la2 => if ascii_dec a a2 then beq_la la la2 else false\n      | nil => false \n    end\n  | nil =>\n    match la2 with\n      | nil => true\n      | _ => false\n    end\n  end.\n\nLemma la_eq_cons :\n  forall (a:ascii) a' la la',\n    a = a' -> la = la' -> a::la = a'::la'.\nProof.\n  intros.\n  rewrite H. rewrite H0. reflexivity.\nQed.\n\nLemma la_eq_refl :\n  forall la,\n    (la_eq la la).\nProof.\n  induction la.\n  apply nil_la.\n  apply not_nil_la.\n  auto.\nQed.  \n\nLemma la_eq_same :\n  forall la la' another,\n    (la_eq la another) -> (la_eq la' another) -> (la = la').\nProof.\n  induction la.\n  \n  intros.\n  inversion H. rewrite<- H2 in H0.\n  inversion H0. auto.\n\n  intros.\n  destruct la'.\n  inversion H0. rewrite<- H2 in H.\n  inversion H.\n\n  inversion H.\n  inversion H0.\n  apply la_eq_cons.\n  \n  rewrite<- H6 in H.\n  inversion H. auto.\n\n  eapply IHla.\n  apply H4.\n\n  rewrite<- H2 in H0.\n  inversion H0.\n  auto.\nQed.\n\n\nFixpoint la_ends_with_bool (la:list ascii) (sym:list ascii) : bool :=\n  if (laeq la sym) then\n    true\n  else\n    match la with\n      | a :: la' => la_ends_with_bool la' sym\n      | nil => false\n    end.\n\nLemma la_ends_equal :\n  forall la sym, \n    la_ends_with_bool la sym = true -> la_endswith la sym.\nProof.\n  induction la.\n  intros.\n  simpl in H.\n  destruct (laeq nil sym).\n  rewrite<- e.\n  apply la_endswith_same. apply nil_la.\n\n  discriminate.\n\n  intros.\n  destruct (laeq (a :: la) sym).\n  rewrite <- e.\n  apply la_endswith_same.\n  apply not_nil_la.\n  apply la_eq_refl.\n\n  apply la_endswith_strict.\n  apply IHla.\n  \n  simpl in H.\n  destruct (laeq (a::la) sym).\n  destruct n. apply e.\n\n  auto.\nQed.\n\n\nLemma la_ends_equal_inv :\n  forall la sym, \n    la_endswith la sym -> la_ends_with_bool la sym = true.\nProof.\n  induction la.\n\n  intros.\n  inversion H.\n  inversion H0. simpl.\n  destruct (laeq nil nil).\n  auto.\n\n  destruct n; auto.\n\n  intros.\n  simpl.\n  destruct (laeq (a :: la) sym).\n  auto.\n  \n  apply IHla.\n\n  inversion H.\n  destruct n.\n  eapply la_eq_same.\n  apply H0.\n  apply la_eq_refl.\n\n  auto.\nQed.\n\n\nLemma app_assoc {A}:\n  forall (l0 l1 l2:list A),\n    (l0 ++ l1) ++ l2 = l0 ++ (l1 ++ l2).\nProof.\n  intros. induction l0. auto.\n\n  simpl. rewrite IHl0. reflexivity.\nQed.\n\n\nTheorem app_nil_r (A:Type) : forall l:list A, l ++ nil = l.\nProof.\n  induction l; simpl; f_equal; auto.\nQed.\n\n\n", "meta": {"author": "bgoodspeed", "repo": "idris-secure", "sha": "6bc7e0834fbcd6641b42e3456b7e76bdf9530de7", "save_path": "github-repos/coq/bgoodspeed-idris-secure", "path": "github-repos/coq/bgoodspeed-idris-secure/idris-secure-6bc7e0834fbcd6641b42e3456b7e76bdf9530de7/login-coq/VCRBase.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.26586389749020967}}
{"text": "From Perennial.algebra Require Import append_list.\nFrom Perennial.Helpers Require Import Integers List Map.\nFrom Perennial.program_proof.wal Require Import abstraction.\n\nFrom Perennial.program_proof Require Import disk_prelude.\n\n(*\ntxns: list (u64 * list update.t)\ntxn_id is referenced by pos, log < pos contains updates through and including upds\n[txn_id: (pos, upds)]\n*)\n\nClass txns_ctxG Σ := { txns_ctx_alist :> alistG Σ (u64 * list update.t) }.\nDefinition txns_ctxΣ : gFunctors := #[alistΣ (u64 * list update.t)].\n\n#[global]\nInstance subG_txns_ctx Σ : subG txns_ctxΣ Σ → txns_ctxG Σ.\nProof. solve_inG. Qed.\n\nSection goose.\nContext `{!heapGS Σ} `{!txns_ctxG Σ}.\nImplicit Types (γ:gname).\n\nDefinition txn_val γ txn_id (txn: u64 * list update.t): iProp Σ :=\n  list_el γ txn_id txn.\n\nDefinition txn_pos γ txn_id (pos: u64) : iProp Σ :=\n  ∃ upds, txn_val γ txn_id (pos, upds).\n\nDefinition txns_ctx γ txns : iProp Σ := list_ctx γ 1 txns.\n\nTheorem alloc_txns_ctx E txns :\n  ⊢ |={E}=> ∃ γtxns, txns_ctx γtxns txns.\nProof.\n  iMod (alist_alloc txns) as (γtxns) \"Hctx\".\n  iExists γtxns.\n  rewrite /txns_ctx //=.\nQed.\n\nTheorem txn_val_to_pos γ txn_id pos upds :\n  txn_val γ txn_id (pos, upds) -∗ txn_pos γ txn_id pos.\nProof.\n  rewrite /txn_pos.\n  iIntros \"Hval\".\n  iExists _; iFrame.\nQed.\n\nLemma txns_ctx_app {γ} txns' txns : txns_ctx γ txns ==∗ txns_ctx γ (txns ++ txns').\nProof.\n  rewrite /txns_ctx.\n  iIntros \"Hctx\".\n  by iMod (alist_app _ txns' with \"Hctx\") as \"[$ _]\".\nQed.\n\nGlobal Instance txn_pos_timeless γ txn_id pos :\n  Timeless (txn_pos γ txn_id pos) := _.\n\nGlobal Instance txn_pos_persistent γ txn_id pos :\n  Persistent (txn_pos γ txn_id pos) := _.\n\nDefinition txns_are γ (start: nat) (txns_sub: list (u64*list update.t)) : iProp Σ :=\n  list_subseq γ start txns_sub.\n\nGlobal Instance txns_are_Persistent γ start txns_sub : Persistent (txns_are γ start txns_sub).\nProof. apply _. Qed.\n\nTheorem txns_are_sound γ txns start txns_sub :\n  txns_ctx γ txns -∗\n  txns_are γ start txns_sub -∗\n  ⌜subslice start (start + length txns_sub)%nat txns = txns_sub⌝.\nProof.\n  iIntros \"Hctx Htxns_are\".\n  iDestruct (alist_subseq_lookup with \"Hctx Htxns_are\") as \"$\".\nQed.\n\nLemma txns_are_unify γ txns start txns_sub1 txns_sub2 :\n  txns_ctx γ txns -∗\n  txns_are γ start txns_sub1 -∗\n  txns_are γ start txns_sub2 -∗\n  ⌜length txns_sub1 = length txns_sub2⌝ -∗\n  ⌜txns_sub1 = txns_sub2⌝.\nProof.\n  iIntros \"Htxns_ctx Htxns_sub1 Htxns_sub2 %Hlen\".\n  iDestruct (txns_are_sound with \"Htxns_ctx Htxns_sub1\") as %<-.\n  iDestruct (txns_are_sound with \"Htxns_ctx Htxns_sub2\") as %<-.\n  rewrite <-Hlen.\n  eauto.\nQed.\n\nLemma txns_are_nil γ start : ⊢ txns_are γ start [].\nProof.\n  iApply list_subseq_nil.\nQed.\n\n(** * some facts about txn_ctx *)\nTheorem alloc_txn_pos pos upds γ txns :\n  txns_ctx γ txns ==∗\n  txns_ctx γ (txns ++ [(pos, upds)]) ∗ txn_val γ (length txns) (pos, upds).\nProof.\n  iIntros \"Hctx\".\n  iMod (alist_app1 (pos,upds) with \"Hctx\") as \"[Hctx Hval]\".\n  by iFrame.\nQed.\n\nTheorem txns_ctx_complete γ txns txn_id txn :\n  txns !! txn_id = Some txn ->\n  txns_ctx γ txns -∗ txn_val γ txn_id txn.\nProof.\n  iIntros (Hlookup) \"Hctx\".\n  iDestruct (alist_lookup_el with \"Hctx\") as \"Hel\"; eauto.\nQed.\n\nTheorem txns_ctx_complete' γ txns txn_id txn :\n  txns !! txn_id = Some txn ->\n  ▷ txns_ctx γ txns -∗ ▷ txn_val γ txn_id txn ∗ ▷ txns_ctx γ txns.\nProof.\n  iIntros (Hlookup) \"Hctx\".\n  iDestruct (txns_ctx_complete with \"Hctx\") as \"#Hel\"; eauto.\nQed.\n\nTheorem txns_ctx_txn_pos γ txns txn_id pos :\n  is_txn txns txn_id pos ->\n  txns_ctx γ txns -∗ txn_pos γ txn_id pos.\nProof.\n  intros [txn [Hlookup ->]]%fmap_Some_1.\n  rewrite txns_ctx_complete; eauto.\n  iIntros \"Htxn_val\".\n  destruct txn as [pos upds].\n  iExists _; iFrame.\nQed.\n\nTheorem txn_val_valid_general γ txns txn_id txn :\n  txns_ctx γ txns -∗\n  txn_val γ txn_id txn -∗\n  ⌜txns !! txn_id = Some txn⌝.\nProof.\n  iIntros \"Hctx Htxn\".\n  iDestruct (alist_lookup with \"Hctx Htxn\") as %Hlookup.\n  eauto.\nQed.\n\nTheorem txn_pos_valid_general γ txns txn_id pos :\n  txns_ctx γ txns -∗\n  txn_pos γ txn_id pos -∗\n  ⌜is_txn txns txn_id pos⌝.\nProof.\n  iIntros \"Hctx Htxn\".\n  iDestruct \"Htxn\" as (upds) \"Hval\".\n  iDestruct (alist_lookup with \"Hctx Hval\") as %Hlookup.\n  iPureIntro.\n  rewrite /is_txn Hlookup //.\nQed.\n\nGlobal Instance txns_ctx_disc γ x: Discretizable (txns_ctx γ x).\nProof.\n  rewrite /txns_ctx/list_ctx. apply _.\nQed.\n\n(** * txns_ctx factory:\n\na way to remember that some [txn_val]s are valid even after a crash *)\n\n(* the crux of this approach is this resource, which has an auth over the old\ntransactions in [γ] and connects them to the transactions in [γ']. [txn_val]s in\n[γ] that are prior to the crash point can be used to get one in the new\ngeneration. *)\nDefinition old_txn_factory γ crash_txn γ' : iProp Σ :=\n  ∃ txns, txns_ctx γ txns ∗\n  [∗ list] i↦txn ∈ (take (S crash_txn) txns), list_el γ' i txn.\n\nLemma txns_ctx_make_factory γ txns crash_txn γ' :\n  txns_ctx γ txns -∗\n  txns_ctx γ' (take (S crash_txn) txns) -∗\n  old_txn_factory γ crash_txn γ' ∗ txns_ctx γ' (take (S crash_txn) txns).\nProof.\n  rewrite {2 3}/txns_ctx /list_ctx /old_txn_factory.\n  iIntros \"Htxn [Hctx #Hels]\".\n  iFrame \"#∗\".\n  iExists _; iFrame \"#∗\".\nQed.\n\nLemma old_txn_get γ γ' crash_txn txn_id txn :\n  (txn_id ≤ crash_txn)%nat →\n  old_txn_factory γ crash_txn γ' -∗\n  txn_val γ txn_id txn -∗\n  txn_val γ' txn_id txn.\nProof.\n  iIntros (?) \"Hfactory Hel\".\n  iDestruct \"Hfactory\" as (txns) \"[Hctx Hels]\".\n  iDestruct (alist_lookup with \"Hctx Hel\") as %Hloookup.\n  iDestruct (big_sepL_lookup with \"Hels\") as \"$\".\n  rewrite -> lookup_take by lia. done.\nQed.\n\nLemma old_txn_get_pos γ γ' crash_txn txn_id pos :\n  (txn_id ≤ crash_txn)%nat →\n  old_txn_factory γ crash_txn γ' -∗\n  txn_pos γ txn_id pos -∗\n  txn_pos γ' txn_id pos.\nProof.\n  iIntros (?) \"Hfactory Hel\".\n  iDestruct \"Hel\" as (txn) \"Hel\".\n  iExists txn.\n  iApply (old_txn_get with \"[$] [$]\"); auto.\nQed.\n\nLemma old_txns_are_get γ γ' crash_txn start txns_sub :\n  (start + length txns_sub ≤ S crash_txn)%nat →\n  old_txn_factory γ crash_txn γ' -∗\n  txns_are γ start txns_sub -∗\n  txns_are γ' start txns_sub.\nProof.\n  iIntros (Hbound) \"Hfactory Htxns\".\n  iInduction txns_sub as [|txn txns] \"IH\" forall (start Hbound).\n  - iApply txns_are_nil.\n  - rewrite /txns_are /list_subseq.\n    simpl in Hbound.\n    rewrite !big_sepL_cons.\n    iDestruct \"Htxns\" as \"[Htxn Htxns]\".\n    rewrite Nat.add_0_r.\n    iDestruct (old_txn_get with \"Hfactory Htxn\") as \"#$\"; first by lia.\n    setoid_rewrite <- Nat.add_succ_comm.\n    iApply (\"IH\" with \"[%] [$] Htxns\").\n    lia.\nQed.\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/wal/txns_ctx.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2658476945542929}}
{"text": "Require Import LibTactics.\nRequire Import Metalib.Metatheory.\nRequire Export syntax_ott.\nRequire Import\n        Infrastructure\n        SubtypingInversion\n        Disjointness.\n\n\nCreate HintDb common.\n#[export] Hint Extern 1 (exists _, _) => exists : common.\n#[export] Hint Extern 1 => match goal with\n                   [ h : exists _ , _ |- _ ] => destruct h\n                 end : common.\n\n\n#[export] Hint Extern 0 => match goal with\n                   | [ H: value (e_app _ _) |- _ ] => inverts H\n                   | [ H: value (e_fixpoint _ _ ) |- _ ] => inverts H\n                   | [ H: prevalue (e_app _ _) |- _ ] => inverts H\n                   | [ H: prevalue (e_fixpoint _ _) |- _ ] => inverts H\n                 end : falseHd.\n\nLemma principal_type_checks: forall e A B,\n    pType e A -> Typing nil e Inf B -> A = B.\nProof.\n  intros e A B H H0. gen B.\n  induction H; intros; try solve [inverts* H0].\n  - inverts* H0. forwards*: IHpType H3. subst*.\n  - inverts H1;\n      forwards*: IHpType1;\n      forwards*: IHpType2;\n      subst*.\nQed.\n\nLemma prevalue_exists_ptype : forall u,\n    prevalue u -> exists A, pType u A.\nProof with eauto with common.\n  intros u H.\n  induction H... induction H...\nQed.\n\n\nLemma typ_value_ptype: forall v A,\n    Typing nil v Inf A -> value v -> pType v A.\nProof.\n  introv Ht Hv. gen A.\n  induction Hv; intros; inverts~ Ht.\nQed.\n\n#[export] Hint Immediate typ_value_ptype : core.\n\nLemma typ_prevalue_ptype: forall u A,\n    Typing nil u Inf A -> prevalue u -> pType u A.\nProof.\n  introv Ht Hp. gen A.\n  induction Hp; intros; inverts~ Ht; inverts~ H.\nQed.\n\n#[export] Hint Immediate typ_prevalue_ptype : core.\n\nLtac unify_pType e :=\n  match goal with\n  | [H1: pType e _, H2: Typing _ e Inf _ |- _] =>\n    (forwards: principal_type_checks H1 H2; subst)\n  | [H1: prevalue e, H2: Typing _ e Inf _ |- _] =>\n    (forwards: typ_prevalue_ptype H2 H1)\n  | [H1: value e, H2: Typing _ e Inf _ |- _] =>\n    (forwards: typ_value_ptype H2 H1)\n  | [H1: prevalue e |- _] =>\n    (forwards (?&?): prevalue_exists_ptype H1)\n  end.\n\n\nLemma prevalue_merge_l_inv : forall u1 u2,\n    prevalue (e_merge u1 u2) -> prevalue u1.\nProof.\n  intros u1 u2 H.\n  inductions H; auto.\n  inverts~ H.\nQed.\n\nLemma prevalue_merge_r_inv : forall u1 u2,\n    prevalue (e_merge u1 u2) -> prevalue u2.\nProof.\n  intros u1 u2 H.\n  inductions H; auto.\n  inverts~ H.\nQed.\n\nLemma prevalue_rcd_inv : forall l u,\n    prevalue (e_rcd l u) -> prevalue u.\nProof.\n  intros l u  H.\n  inductions H; auto.\n  inverts~ H.\nQed.\n\n#[export] Hint Immediate prevalue_merge_l_inv prevalue_merge_r_inv prevalue_rcd_inv: core.\n\n(* TypedReduce *)\nLemma TypedReduce_prv_value: forall v A v',\n    value v -> TypedReduce v A v' -> value v'.\nProof with eauto with termDb.\n  intros v A v' Val Red.\n  induction* Red; try solve [inverts* Val]...\nQed.\n\n#[export] Hint Immediate TypedReduce_prv_value : core.\n\nLemma TypedReduce_top_normal : forall (v v': exp),\n    TypedReduce v t_top v' -> v' = e_top.\nProof.\n  intros v v' H.\n  inductions H;\n    solve [inverts* H].\nQed.\n\n\nLemma TypedReduce_toplike : forall A v1 v2 v1' v2',\n    topLike A -> value v1 -> value v2 -> TypedReduce v1 A v1' -> TypedReduce v2 A v2' -> v1' = v2'.\nProof with (solve_false; auto).\n  assert (HH: forall v v' A, value v -> ord A -> topLike A -> TypedReduce v A v' -> v' = e_top). {\n    intros.\n    induction H2...\n    - inverts~ H. inverts* H1...\n    - inverts~ H.\n    - inverts~ H.\n  }\n  intros A v1 v2 v1' v2' TL Val1 Val2 Red1 Red2.\n  gen v1' v2'.\n  proper_ind A; inverts TL; intros;\n    try solve [ (* ordinary *)\n          forwards*: HH Val1 Red1;\n          forwards*: HH Val2 Red2;\n          subst* ];\n    try solve [ (* splittable *)\n          inverts H;\n          inverts Red1; solve_false; auto;\n          inverts Red2; solve_false; auto;\n          split_unify;\n          forwards*: IHr1;\n          forwards*: IHr2;\n          congruence].\nQed.\n\n\nLemma TypedReduce_sub: forall v v' A B,\n    value v -> TypedReduce v A v' -> pType v B -> algo_sub B A.\nProof with eauto with common.\n  introv Val Red Typ. gen B.\n  induction Red; intros.\n  - inverts Typ...\n  - inverts Typ...\n  - inverts Typ...\n  - inverts Val.\n    inverts Typ.\n    forwards*: IHRed...\n  - inverts Val.\n    inverts Typ...\n  - inverts Val.\n    inverts Typ...\n  - forwards*: IHRed1...\nQed.\n\n\n(* consistency *)\nDefinition consistencySpec v1 v2 :=\n  forall A v1' v2', ord A -> TypedReduce v1 A v1' -> TypedReduce v2 A v2' -> v1' = v2'.\n\n#[export] Hint Unfold consistencySpec : core.\n\n\nLemma consistent_symm: forall e1 e2,\n    consistent e1 e2 -> consistent e2 e1.\nProof with eauto.\n  intros e1 e2 H.\n  induction H...\nQed.\n\n#[export] Hint Resolve consistent_symm : core.\n\n\nLemma consistent_refl: forall v A,\n    value v -> Typing nil v Inf A -> consistent v v.\nProof with eauto.\n  intros v A H Typ.\n  gen A.\n  induction H; intros...\n  - constructor; constructor;\n      inverts Typ;\n      forwards* (?&?): prevalue_exists_ptype v1;\n      forwards* (?&?): prevalue_exists_ptype v2;\n      forwards* : principal_type_checks v1;\n      forwards* : principal_type_checks v2; subst...\n  - inverts* Typ.\nQed.\n\n\n#[export] Hint Resolve consistent_refl : 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/KeyProperties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2658476945542929}}
{"text": "(*! Stdlib | Standard library !*)\nRequire Import Koika.Frontend.\n\nSection Maybe.\n  Context (tau: type).\n\n  Definition Maybe :=\n    {| struct_name := \"maybe_\" ++ type_id tau;\n       struct_fields := [(\"valid\", bits_t 1); (\"data\", tau)] |}.\n\n  Definition valid {reg_t fn} : UInternalFunction reg_t fn :=\n    {{ fun valid (x: tau) : struct_t Maybe =>\n         struct Maybe { valid := Ob~1; data := x } }}.\n\n  Definition invalid {reg_t fn} : UInternalFunction reg_t fn :=\n    {{ fun invalid () : struct_t Maybe =>\n         struct Maybe { valid := Ob~0 } }}.\nEnd Maybe.\n\nNotation maybe tau := (struct_t (Maybe tau)).\n\nModule Type Fifo.\n  Parameter T:type.\nEnd Fifo.\n\nModule Fifo1 (f: Fifo).\n  Import f.\n  Inductive reg_t := data0 | valid0.\n\n  Definition R r :=\n    match r with\n    | data0 => T\n    | valid0 => bits_t 1\n    end.\n\n  Definition r idx : R idx :=\n    match idx with\n    | data0 => value_of_bits Bits.zero\n    | valid0 => Bits.zero\n    end.\n\n  Definition name_reg r :=\n    match r with\n    | data0 => \"data0\"\n    | valid0 => \"valid0\"\n    end.\n\n  Definition can_enq : UInternalFunction reg_t empty_ext_fn_t :=\n    {{ fun can_enq () : bits_t 1 => !read1(valid0) }}.\n\n  Definition enq : UInternalFunction reg_t empty_ext_fn_t :=\n    {{ fun enq (data : T) : bits_t 0 =>\n        guard (can_enq ());\n        write1(data0, data);\n        write1(valid0, #Ob~1) }}.\n\n  Definition can_deq : UInternalFunction reg_t empty_ext_fn_t :=\n    {{ fun can_deq () : bits_t 1 => read0(valid0) }}.\n\n  Definition peek : UInternalFunction reg_t empty_ext_fn_t :=\n    {{ fun peek () : maybe T =>\n         if can_deq () then {valid T}(read0(data0))\n         else {invalid T}() }}.\n\n  Definition deq : UInternalFunction reg_t empty_ext_fn_t :=\n    {{ fun deq () : T =>\n        guard (can_deq ());\n        write0(valid0, Ob~0);\n        read0(data0) }}.\n\n  Instance FiniteType_reg_t : FiniteType reg_t := _.\nEnd Fifo1.\n\nModule Fifo1Bypass (f: Fifo).\n  Import f.\n  Inductive reg_t := data0 |  valid0.\n\n  Definition R r :=\n    match r with\n    | data0 => T\n    | valid0 => bits_t 1\n    end.\n\n  Definition r idx : R idx :=\n    match idx with\n    | data0 => value_of_bits Bits.zero\n    | valid0 => Bits.zero\n    end.\n\n  Definition name_reg r :=\n    match r with\n    | data0 => \"data0\"\n    | valid0 => \"valid0\"\n    end.\n\n  Definition can_enq : UInternalFunction reg_t empty_ext_fn_t :=\n    {{ fun can_enq () : bits_t 1 => !read0(valid0) }}.\n\n  Definition enq : UInternalFunction reg_t empty_ext_fn_t :=\n   {{ fun enq (data : T) : bits_t 0 =>\n       guard (can_enq ());\n       write0(data0, data);\n       write0(valid0, #Ob~1) }}.\n\n  Definition can_deq : UInternalFunction reg_t empty_ext_fn_t :=\n    {{ fun can_deq () : bits_t 1 => read1(valid0) }}.\n\n  Definition peek : UInternalFunction reg_t empty_ext_fn_t :=\n    {{ fun peek () : maybe T =>\n         if can_deq () then {valid T}(read1(data0))\n         else {invalid T}() }}.\n\n  Definition deq :  UInternalFunction reg_t empty_ext_fn_t :=\n    {{ fun deq () : T =>\n       guard (can_deq ());\n       write1(valid0, Ob~0);\n       read1(data0) }}.\n\n  Instance FiniteType_reg_t : FiniteType reg_t := _.\nEnd Fifo1Bypass.\n\nModule Type RfPow2_sig.\n  Parameter idx_sz: nat.\n  Parameter T: type.\n  Parameter init: T.\n  Parameter read_style : @switch_style var_t.\n  Parameter write_style : @switch_style var_t.\nEnd RfPow2_sig.\n\nModule RfPow2 (s: RfPow2_sig).\n  Definition sz := pow2 s.idx_sz.\n  Inductive reg_t := rData (n: Vect.index sz).\n\n  Definition R r :=\n    match r with\n    | rData _ => s.T\n    end.\n\n  Definition r idx : R idx :=\n    match idx with\n    | rData _ => s.init\n    end.\n\n  Definition name_reg r :=\n    match r with\n    | rData n => String.append \"rData_\" (show n)\n    end.\n\n  Definition read_0 : UInternalFunction reg_t empty_ext_fn_t :=\n    {{ fun read_0 (idx : bits_t s.idx_sz) : s.T =>\n         `UCompleteSwitch s.read_style s.idx_sz \"idx\"\n              (fun idx => {{ read0(rData idx) }})` }}.\n\n  Definition write_0 : UInternalFunction reg_t empty_ext_fn_t :=\n    {{ fun write_0 (idx : bits_t s.idx_sz) (val: s.T) : unit_t =>\n         `UCompleteSwitch s.write_style s.idx_sz \"idx\"\n              (fun idx => {{ write0(rData idx, val) }})` }}.\n\n  Definition read_1 : UInternalFunction reg_t empty_ext_fn_t :=\n    {{ fun read_1 (idx : bits_t s.idx_sz) : s.T =>\n         `UCompleteSwitch s.read_style s.idx_sz \"idx\"\n              (fun idx => {{ read1(rData idx) }})` }}.\n\n  Definition write_1 : UInternalFunction reg_t empty_ext_fn_t :=\n    {{ fun write_1 (idx : bits_t s.idx_sz) (val: s.T) : unit_t =>\n         `UCompleteSwitch s.write_style s.idx_sz \"idx\"\n              (fun idx => {{ write1(rData idx, val) }})` }}.\nEnd RfPow2.\n\nModule Type Rf_sig.\n  Parameter lastIdx: nat.\n  Parameter T: type.\n  Parameter init: T.\nEnd Rf_sig.\n\nModule Rf (s: Rf_sig).\n  Definition lastIdx := s.lastIdx.\n  Definition log_sz := log2 lastIdx.\n  Definition sz := S lastIdx.\n  Inductive reg_t := rData (n: Vect.index sz).\n\n  Definition R r :=\n    match r with\n    | rData _ => s.T\n    end.\n\n  Definition r idx : R idx :=\n    match idx with\n    | rData _ => s.init\n    end.\n\n  Definition name_reg r :=\n    match r with\n    | rData n => String.append \"rData_\" (show n)\n    end.\n\n  Definition read : UInternalFunction reg_t empty_ext_fn_t :=\n    {{ fun read (idx : bits_t log_sz) : s.T =>\n         `USugar\n             (USwitch\n                {{idx}}\n                {{fail(type_sz s.T)}}\n                (List.map\n                   (fun idx =>\n                      (USugar (UConstBits\n                                 (Bits.of_nat log_sz idx)),\n                       {{ read0(rData (match (index_of_nat sz idx) with\n                                       | Some idx => idx\n                                       | _ => thisone\n                                       end)) }}))\n                   (List.seq 0 sz))) ` }}.\n\n  Definition write : UInternalFunction reg_t empty_ext_fn_t :=\n    {{ fun write (idx : bits_t log_sz) (val: s.T) : unit_t =>\n         `USugar\n          (USwitch\n             {{idx}}\n             {{fail}}\n             (List.map\n                (fun idx =>\n                   (USugar (UConstBits\n                              (Bits.of_nat log_sz idx)),\n                    {{ write0(rData (match (index_of_nat sz idx) with\n                                    | Some idx => idx\n                                    | _ => thisone\n                                    end), val) }}))\n                   (List.seq 0 sz))) ` }}.\nEnd Rf.\n\nDefinition signExtend {reg_t} (n:nat) (m:nat) : UInternalFunction reg_t empty_ext_fn_t :=\n  {{ fun signExtend (arg : bits_t n) : bits_t (m+n) => sext(arg, m + n) }}.\n\nModule RfEhr (s: Rf_sig).\n\n  Definition lastIdx := s.lastIdx.\n  Definition log_sz := log2 lastIdx.\n  Definition sz := S lastIdx.\n  Inductive reg_t := rData (n: Vect.index sz).\n\n  Definition R r :=\n    match r with\n    | rData _ => s.T\n    end.\n\n  Definition r idx : R idx :=\n    match idx with\n    | rData _ => s.init\n    end.\n\n  Definition name_reg r :=\n    match r with\n    | rData n => String.append \"rData_\" (show n)\n    end.\n\n  Definition read_0 : UInternalFunction reg_t empty_ext_fn_t :=\n    {{ fun read_0 (idx : bits_t log_sz) : s.T =>\n         `USugar\n             (USwitch\n                {{idx}}\n                {{fail(type_sz s.T)}}\n                (List.map\n                   (fun idx =>\n                      (USugar (UConstBits\n                                 (Bits.of_nat log_sz idx)),\n                       {{ read0(rData (match (index_of_nat sz idx) with\n                                       | Some idx => idx\n                                       | _ => thisone\n                                       end)) }}))\n                   (List.seq 0 sz))) ` }}.\n\n  Definition read_1 : UInternalFunction reg_t empty_ext_fn_t :=\n    {{ fun read_1 (idx : bits_t log_sz) : s.T =>\n         `USugar\n             (USwitch\n                {{idx}}\n                {{fail(type_sz s.T)}}\n                (List.map\n                   (fun idx =>\n                      (USugar (UConstBits\n                                 (Bits.of_nat log_sz idx)),\n                       {{ read1(rData (match (index_of_nat sz idx) with\n                                       | Some idx => idx\n                                       | _ => thisone\n                                       end)) }}))\n                   (List.seq 0 sz))) ` }}.\n\n  Definition write_0 : UInternalFunction reg_t empty_ext_fn_t :=\n    {{ fun write_0 (idx : bits_t log_sz) (val: s.T) : unit_t =>\n         `USugar\n          (USwitch\n             {{idx}}\n             {{fail}}\n             (List.map\n                (fun idx =>\n                   (USugar (UConstBits\n                              (Bits.of_nat log_sz idx)),\n                    {{ write0(rData (match (index_of_nat sz idx) with\n                                    | Some idx => idx\n                                    | _ => thisone\n                                    end), val) }}))\n                (List.seq 0 sz))) ` }}.\n\n  Definition write_1 : UInternalFunction reg_t empty_ext_fn_t :=\n    {{ fun write_1 (idx : bits_t log_sz) (val: s.T) : unit_t =>\n         `USugar\n          (USwitch\n             {{idx}}\n             {{fail}}\n             (List.map\n                (fun idx =>\n                   (USugar (UConstBits\n                              (Bits.of_nat log_sz idx)),\n                    {{ write1(rData (match (index_of_nat sz idx) with\n                                    | Some idx => idx\n                                    | _ => thisone\n                                    end), val) }}))\n                   (List.seq 0 sz))) ` }}.\nEnd RfEhr.\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/Std.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2658476869407446}}
{"text": "Require Import LibTactics.\nRequire Import Coq.micromega.Lia.\nRequire Import LN_Lemmas.\nRequire Export SimpleSub.\n\n\nDefinition typ_as_ftyp := fty_StackArg.\nCoercion typ_as_ftyp : typ >-> Fty.\n\nNotation \"[| A |]\"        := (fty_StackTyArg A)\n                               (at level 5) : type_scope.\n\n(*****************************************************************************)\n\n#[export] Hint Immediate orduFty_lc : core.\n\nLemma napplyty_lc_1 : forall A B, NApplyTy A B -> lc_typ A.\nProof.  introv H.  induction* H.  Qed.\n\nLemma napplyty_lc_2 : forall A B, NApplyTy A B -> lc_Fty B.\nProof.  introv H.  induction* H.  Qed.\n\n#[export] Hint Immediate napplyty_lc_1 napplyty_lc_2 : core.\n\nLemma applyty_lc_1 : forall A B C, ApplyTy A B C -> lc_typ A.\nProof.  introv H.  induction* H.  Qed.\n\nLemma applyty_lc_2 : forall A B C, ApplyTy A B C -> lc_Fty B.\nProof.  introv H.  induction* H. Qed.\n\nLemma applyty_lc_3 : forall A B C, ApplyTy A B C -> lc_typ C.\nProof.  introv H.  induction~ H. inverts H. eauto with lngen. Qed.\n\n#[export] Hint Immediate applyty_lc_1 applyty_lc_2 applyty_lc_3 : core.\n\nLemma lc_fty_inv_1 : forall A:typ , lc_Fty A -> lc_typ A.\nProof. introv H. inverts~ H. Qed.\n\nLemma lc_fty_inv_2 : forall A:typ , lc_Fty [| A |] -> lc_typ A.\nProof. introv H. inverts~ H. Qed.\n\n#[export] Hint Resolve lc_fty_inv_1 lc_fty_inv_2 : core.\n\nLemma napplyty_bot : forall A,\n    NApplyTy t_bot A -> False.\nProof.\n  introv App. inductions App.\n  all: eauto.\nQed.\n\n#[export] Hint Immediate napplyty_bot : core.\n\nLemma napplyty_splitu_arg_inv : forall A B B1 B2,\n    NApplyTy A (fty_StackArg B) -> splu B B1 B2 ->\n    NApplyTy A (fty_StackArg B1) \\/ NApplyTy A (fty_StackArg B2).\nProof.\n  introv HN HS.\n  inverts HN; solve_false; auto_unify; eauto.\nQed.\n\nLemma applyty_contradication : forall A B C,\n   ApplyTy A B C -> NApplyTy A B -> False.\nProof with solve_false.\n  introv HA HN.\n  indTypFtySize (size_typ A + size_Fty B).\n\n  inverts HA;\n    match goal with\n    | H1: NApplyTy _ (fty_StackArg ?B), H2: splu ?B _ _  |- _ =>\n      forwards~ [?|?]: napplyty_splitu_arg_inv H1 H2\n    | _ => inverts HN\n    end.\n\n  all: repeat match goal with\n  | H1: ApplyTy (t_forall _) (fty_StackArg _) _ |- _ => forwards: IH H1; elia; applys~ NApplyFunTy\n  | H1: ApplyTy (t_arrow _ _) (fty_StackTyArg _) _ |- _ => forwards: IH H1; elia; applys~ NApplyTyFunFty\n  | H1: ApplyTy ?A ?B _, H2: NApplyTy ?A ?B |- _ => forwards: IH H2 H1; elia\n              end.\n  all: solve_false.\nQed.\n\n#[export] Hint Extern 1 => lazymatch goal with\n                            | H1: ApplyTy ?T _ _, H2: NApplyTy ?T _  |- _ =>\n                              applys applyty_contradication H1 H2\n                            end : FalseHd.\n\nLemma applyty_unique : forall A B C1 C2,\n    ApplyTy A B C1 -> ApplyTy A B C2 -> C1 = C2.\nProof.\n  introv HA1 HA2. gen C1 C2.\n  indTypFtySize (size_typ A + size_Fty B).\n  inverts HA1; inverts HA2.\n  all: auto_unify; repeat match goal with\n  | H1: ApplyTy ?A ?B _, H2: ApplyTy ?A ?B _ |- _ => forwards: IH H1 H2; elia; clear H1 H2\n              end; subst~.\n  all: solve_false.\nQed.\n\nLtac auto_unify_2 :=\n  auto_unify; (* unify split *)\n  (* unify applyty *)\n  repeat lazymatch goal with\n         | [ H1: ApplyTy ?A ?B _ , H2: ApplyTy ?A ?B _ |- _ ] =>\n           (forwards : applyty_unique H1 H2;\n            subst; clear H2)\n             end.\n\nLemma ordu_or_split_Fty: forall F,\n    lc_Fty F -> UnionOrdinaryFty F \\/ exists A B C, F = fty_StackArg A /\\ splu A B C.\nProof.\n  introv HL.\n  destruct~ HL.\n  forwards~ [?|(?&?&?)]: ordu_or_split A. intuition eauto.\nQed.\n\nLemma applyty_total : forall A F,\n    lc_typ A -> lc_Fty F -> (exists C, ApplyTy A F C) \\/ NApplyTy A F.\nProof with (elia; destruct_conj).\n  introv.\n  indTypFtySize (size_typ A + size_Fty F).\n  lets~ [?|(?&?&?&?&?)]: (ordu_or_split_Fty F).\n  - destruct* H.\n    (* and / or *)\n    all: try forwards~ [?|?]: IH F A1...\n    all: try forwards~ [?|?]: IH F A2...\n    all: eauto.\n\n    (* arrow / forall *)\n    all: destruct H0.\n    2,3: now right*.\n\n    + destruct* (sub_dec A0 A).\n    + eauto.\n\n  - subst.\n    forwards~ [?|?]: IH (fty_StackArg x0) A...\n    forwards~ [?|?]: IH (fty_StackArg x1) A...\n    all: eauto.\nQed.\n\n\nLemma applyty_splitu_arg_inv : forall A B B1 B2 C,\n    ApplyTy A (fty_StackArg B) C -> splu B B1 B2 ->\n    exists C1 C2, C = (t_or C1 C2) /\\\n    ApplyTy A (fty_StackArg B1) C1 /\\ ApplyTy A (fty_StackArg B2) C2.\nProof.\n  introv HA HS.\n  inverts HA; auto_unify; solve_false; eauto.\nQed.\n\n\nLemma applyty_splitu_fun_aux : forall A A1 A2 F,\n    (forall C1 C2, ApplyTy A1 F C1 -> ApplyTy A2 F C2 -> splu A A1 A2 ->\n     exists C', ApplyTy A F C') /\\\n    (NApplyTy A1 F \\/ NApplyTy A2 F -> splu A A1 A2 -> NApplyTy A F).\nProof with elia; solve_false; try eassumption.\n  introv.\n  indTypFtySize (size_typ A + size_Fty F).\n  split.\n\n  introv HA1 HA2 HS.\n  lets~ [?|(?&?&?&?&?)]: (ordu_or_split_Fty F). eauto.\n  - inverts HS...\n    + (* or *) exists*.\n    + (* and *) inverts HA1...\n      * (* interBoth *) inverts HA2... forwards (?&?): proj1 (IH F A0) H1... exists*.\n      * (* interR *) exists*. applys* ApplyTyInterR.\n        forwards~ : proj2 (IH F A0) H1...\n      * (* Both *)  inverts HA2...\n        ** exists*. applys* ApplyTyInterR. forwards~ : proj2 (IH F A0) H1...\n        ** forwards (?&?): proj1 (IH F A0) H1... exists*.\n    + (* and *) inverts HA1...\n      * (* interL *) exists*. applys* ApplyTyInterL. forwards~ : proj2 (IH F B) H1...\n      * (* interBoth *) inverts HA2... forwards (?&?): proj1 (IH F B) H1... exists*.\n      * (* Both *)  inverts HA2...\n        ** exists*. applys* ApplyTyInterL. forwards~ : proj2 (IH F B) H1...\n        ** forwards (?&?): proj1 (IH F B) H1... exists*.\n    + (* forall *) inverts HA1... inverts HA2... exists~.\n    + (* rcd *) inverts HA1...\n  - subst.\n    forwards: applyty_splitu_arg_inv HA1 H0. forwards: applyty_splitu_arg_inv HA2 H0.\n    destruct_conj. subst.\n    forwards (?&?): proj1 (IH (fty_StackArg x0) A) H4 H2...\n    forwards (?&?): proj1 (IH (fty_StackArg x1) A) H5 H3...\n    exists*.\n\n  -\n    intros [HA|HA] HS;\n      lets~ [?|(?&?&?&?&?)]: (ordu_or_split_Fty F); subst; eauto.\n    + (* ord *) inverts~ HS...\n      * (* and *) inverts HA... forwards~ : proj2 (IH F A0) H1...\n      * (* and *) inverts HA... forwards~ : proj2 (IH F B) H1...\n      * (* forall *) inverts HA... constructor~.\n    + (* split *) forwards* [?|?]: napplyty_splitu_arg_inv HA.\n      * forwards~ : proj2 (IH (fty_StackArg x0) A) HS... eauto.\n      * forwards~ : proj2 (IH (fty_StackArg x1) A) HS... eauto.\n    + (* ord *) inverts~ HS...\n      * (* and *) inverts HA... forwards~ : proj2 (IH F A0) H1...\n      * (* and *) inverts HA... forwards~ : proj2 (IH F B) H1...\n      * (* forall *) inverts HA... constructor~.\n    + (* split *) forwards* [?|?]: napplyty_splitu_arg_inv HA.\n      * forwards~ : proj2 (IH (fty_StackArg x0) A) HS... eauto.\n      * forwards~ : proj2 (IH (fty_StackArg x1) A) HS... eauto.\n\n   Unshelve. all: apply t_top.\nQed.\n\n(* Lemma B.9 *)\nLemma napplyty_splitu_fun : forall A A1 A2 F,\n    NApplyTy A1 F \\/ NApplyTy A2 F -> splu A A1 A2 -> NApplyTy A F.\nProof.\n  intros.\n  forwards* (?&?): applyty_splitu_fun_aux.\nQed.\n\nLemma napplyty_rename : forall A B C,\n    NApplyTy A (fty_StackTyArg B) -> lc_typ C -> NApplyTy A (fty_StackTyArg C).\nProof.\n  introv H Lc. inductions H; eauto.\nQed.\n\nLemma applyty_rename : forall A B X C,\n    ApplyTy A (fty_StackTyArg (t_tvar_f X)) B -> lc_typ C -> X `notin` [[A]] ->\n    ApplyTy A (fty_StackTyArg C) ( [X ~~> C] B).\nProof.\n  introv H Lc Fry. inductions H; simpl; simpl in Fry; eauto.\n  all: try solve [ simpl_rename_goal; simpl in Fry; solve_notin ].\n  - forwards~: napplyty_rename C H1.\n  - forwards~: napplyty_rename C H0.\nQed.\n\n(*------------------- Soundness Type-Level Dispatch --------------------------*)\n\n(* Soundness of Type-Level Dispatch [1] *)\nLemma applyty_soundness_1 : forall A B C,\n    ApplyTy A (fty_StackArg B) C -> A <: (t_arrow B C).\nProof with try eassumption; try applys ASub_refl; try match goal with |- lc_typ _ => eauto with lngen end.\n  introv H. inductions H.\n  all: try match goal with\n           | H: UnionOrdinaryFty (_ _) |- _ => inverts H\n           end.\n  1-2: eauto.\n  all: try forwards~ : IHApplyTy.\n  all: try forwards~ : IHApplyTy1. all: try forwards~ : IHApplyTy2.\n  - convert2asub. split_l.\n    applys algo_trans H. applys ASub_arrow... use_left_r...\n    applys algo_trans H2. applys ASub_arrow... use_right_r...\n  - convert2asub.\n    applys algo_trans ((t_arrow B1 (B1' | B2'))&(t_arrow B2 (B1' | B2'))).\n    applys algo_trans ((t_arrow B1 B1')&(t_arrow B2 B2')). split_r...\n    + split_r... * use_left_l... applys ASub_arrow... use_left_r...\n      * use_right_l... applys ASub_arrow... use_right_r...\n    + applys asub2nsub. applys NSub_and. applys NSpI_arrowUnion...\n      applys splu2nsplu H. all: applys asub2nsub.\n      * use_left_l... * use_right_l...\n  - convert2asub. use_left_l...\n  - convert2asub. swap_and_l... use_left_l...\n  - convert2asub. split_r; eauto.\nQed.\n\n(* Soundness of Type-Level Dispatch [2] *)\nLemma applyty_soundness_2 : forall A B C,\n    ApplyTy A (fty_StackTyArg B) C ->\n    exists C',  C = C'^-^B /\\\n                forall X, X `notin` [[C]] -> ApplyTy A (fty_StackTyArg (t_tvar_f X)) (C'-^X) /\\ A <: (t_forall C').\nProof with simpl in *; try eassumption; try applys ASub_refl; try match goal with |- lc_typ _ => eauto with lngen end; destruct_conj.\n  introv H. inductions H.\n  all: try match goal with\n           | H: UnionOrdinaryFty (_ _) |- _ => inverts H\n           end.\n  all: try forwards~ : IHApplyTy.\n  all: try forwards~ : IHApplyTy1. all: try forwards~ : IHApplyTy2.\n  all: destruct_conj.\n  - exists t_bot. split~.\n  - exists A. split~.\n  - exists (x0|x). split~.\n    + assert (Heq: forall B C X, (t_or B C) ^-^ X = t_or (B ^-^ X) (C ^-^ X)) by eauto.\n      rewrite Heq. congruence.\n    + assert (Heq: forall B C X, (t_or B C) -^ X = t_or (B -^ X) (C -^ X)) by eauto.\n      intros X Fry... forwards~ : H5 X. forwards~ : H4 X...\n      split~.\n      * rewrite Heq. applys~ ApplyTyUnion H6 H4.\n      * convert2asub.\n        split_l. use_left_r...  use_right_r...\n  - exists. split... intros X Fry. forwards~ : H2 X...\n    split. eapply napplyty_rename in H1. eauto. eauto.\n    convert2asub. use_left_l...\n  - exists. split... intros X Fry. forwards~ : H2 X...\n    split. eapply napplyty_rename in H0. eauto. eauto.\n    convert2asub. swap_and_l... use_left_l...\n  - exists (x0 & x). split...\n    + assert (Heq: forall B C X, (t_and B C) ^-^ X = t_and (B ^-^ X) (C ^-^ X)) by eauto.\n      rewrite Heq. congruence.\n    + intros X Fry. forwards~ : H4 X... forwards~ : H5 X...\n      split.\n      * assert (Heq: forall B C X, (t_and B C) -^ X = t_and (B -^ X) (C -^ X)) by eauto.\n        rewrite Heq. eauto.\n      * convert2asub. split_r; eauto.\n  Unshelve. all: apply empty.\nQed.\n\n\n(* Soundness of Type-Level Dispatch [2] *)\nLemma applyty_soundness_2_simple : forall A B C,\n    ApplyTy A (fty_StackTyArg B) C ->\n    exists A', A <: t_forall A' /\\ C <: (A' ^-^ B).\nProof.\n  introv H. pick fresh X.\n  forwards~ (?&?&?): applyty_soundness_2 H.\n  subst. forwards~ (?&?): H1 X.\n  exists x. split~. convert2asub. applys* ASub_refl.\nQed.\n\nLemma applyty_completeness_1 : forall A B D,\n    A <: (t_arrow B D) -> ordu B ->\n         exists C, ApplyTy A (fty_StackArg B) C /\\ (t_arrow B C) <: (t_arrow B D).\nProof with try eassumption; elia; solve_false; destruct_conj.\n  introv HS Hord. apply dsub2asub in HS.\n  indTypFtySize (size_typ A + size_typ D).\n  forwards (?&?): algo_sub_lc HS. inverts_all_lc.\n  lets~ [?|(?&?&?)]: (ordi_or_split D).\n  - destruct H...\n    + forwards~ [Ha|Ha]: algo_sub_andlr_inv HS;\n        forwards: IH Ha...\n      * forwards~ [?|?]: applyty_total A2 (fty_StackArg B)...\n        inv_arrow.\n        exists (t_and x x0). split~. applys~ DSub_CovArr. applys~ DSub_InterLL.\n        eauto with lngen. solve_dsub...\n        exists* x.\n      * forwards~ [?|?]: applyty_total A1 (fty_StackArg B)...\n        inv_arrow.\n        exists (t_and x0 x). split~. applys~ DSub_CovArr. applys~ DSub_InterLR.\n        eauto with lngen. solve_dsub...\n        exists x. split~.\n    + apply dsub2asub in HS.\n      assert (EASY1: A1 <: (t_arrow B D)) by applys~ DSub_Trans HS. apply dsub2asub in EASY1.\n      assert (EASY2: A2 <: (t_arrow B D)) by applys~ DSub_Trans HS. apply dsub2asub in EASY2.\n      forwards: IH B EASY1... forwards: IH B EASY2...\n      exists (t_or x x0). split~. inv_arrow. applys~ DSub_CovArr.\n      convert2dsub. applys~ DSub_UnionL.\n    + inv_arrow. convert2dsub. exists B0. split~.\n    + exists*.\n  -  forwards~ (Ha1&Ha2): algo_sub_and_inv HS. eauto.\n     forwards: IH Ha1... forwards: IH Ha2... inv_arrow.\n     auto_unify_2. exists x2. split~. applys~ DSub_CovArr.\n     convert2asub. eauto.\nQed.\n\nLemma applyty_completeness_1_all : forall A B D,\n    A <: (t_arrow B D) ->\n         exists C, ApplyTy A (fty_StackArg B) C /\\ (t_arrow B C) <: (t_arrow B D).\nProof with try eassumption; elia.\n  introv Sub.\n  indTypFtySize (size_Fty B).\n  forwards [?|(T&T1&T2&?&?)]: ordu_or_split_Fty B... now eauto.\n  - applys applyty_completeness_1... inverts~ H.\n  - inverts H.\n    assert (Sub1: A <: t_arrow T1 D).\n    { applys DSub_Trans Sub. constructor~. convert2asub. eauto. }\n    assert (Sub2: A <: t_arrow T2 D).\n    { applys DSub_Trans Sub. constructor~. convert2asub. eauto. }\n    forwards: IH Sub1... forwards: IH Sub2...\n    all: destruct_conj.\n    + exists (x0 | x). split. econstructor...\n      convert2asub.  auto_inv. constructor*.\nQed.\n\nLemma applyty_completeness_2 : forall A B,\n    A <: (t_forall B) ->\n         exists C L, forall X, X `notin` L ->\n             ApplyTy A (fty_StackTyArg (t_tvar_f X)) (C-^X) /\\ (t_forall C) <: (t_forall B).\nProof with try eassumption; elia; solve_false; destruct_conj.\n  introv HS. apply dsub2asub in HS.\n  indTypFtySize (size_typ A + size_typ B).\n  lets~ [?|(?&?&?)]: (ordi_or_split (t_forall B)).\n  - assert (lc_typ A) by eauto. destruct H0...\n    + forwards~ [Ha|Ha]: algo_sub_andlr_inv HS;\n        forwards: IH Ha...\n      * pick fresh X for ([[A1]] `union` [[A2]] `union` x0 `union` [[x]]). forwards~ : H0 X.\n        forwards~ [?|?]: applyty_total A2 (fty_StackTyArg (t_tvar_f X))...\n        ** exists. intros Y Fry.\n           forwards~ HR1: applyty_rename (t_tvar_f Y) H1. forwards~ HR2: applyty_rename (t_tvar_f Y) H2.\n           simpl_rename HR1. simpl_rename HR2.\n           assert (Heq: forall Y, (t_and x (close_typ_wrt_typ X x1)) -^ Y = t_and (x -^ Y) (close_typ_wrt_typ X x1 -^ Y)) by eauto. rewrite Heq.\n           split~. applys DSub_CovAll. intros X0 Fry2.\n           apply dsub2asub in H3. forwards: algo_sub_forall_inv X0 H3.\n           rewrite Heq. applys DSub_InterLL. eauto.\n           solve_dsub...\n           autorewrite with lngen. all: solve_notin.\n        ** exists. intros Y Fry.\n           forwards~ HR1: applyty_rename (t_tvar_f Y) H1. simpl_rename HR1.\n           forwards~ HR2: napplyty_rename (t_tvar_f Y) H2.\n           split. applys~ ApplyTyInterL HR1. auto. eauto with lngen.\n      * pick fresh X for ([[A1]] `union` [[A2]] `union` x0 `union` [[x]]). forwards~ : H0 X.\n        forwards~ [?|?]: applyty_total A1 (fty_StackTyArg (t_tvar_f X))...\n        ** exists. intros Y Fry.\n           forwards~ HR1: applyty_rename (t_tvar_f Y) H1. forwards~ HR2: applyty_rename (t_tvar_f Y) H2.\n           simpl_rename HR1. simpl_rename HR2.\n           assert (Heq: forall Y, (t_and (close_typ_wrt_typ X x1) x) -^ Y = t_and (close_typ_wrt_typ X x1 -^ Y) (x -^ Y)) by eauto. rewrite Heq.\n           split~. applys DSub_CovAll. intros X0 Fry2.\n           apply dsub2asub in H3. forwards: algo_sub_forall_inv X0 H3.\n           rewrite Heq. applys DSub_InterLR. eauto.\n           solve_dsub...\n           autorewrite with lngen.\n           all : solve_notin.\n        ** exists. intros Y Fry.\n           forwards~ HR1: applyty_rename (t_tvar_f Y) H1. simpl_rename HR1.\n           forwards~ HR2: napplyty_rename (t_tvar_f Y) H2.\n           split. applys~ ApplyTyInterR HR1. auto. eauto with lngen.\n\n    + apply dsub2asub in HS.\n      assert (EASY1: A1 <: (t_forall B)) by applys~ DSub_Trans HS. apply dsub2asub in EASY1.\n      assert (EASY2: A2 <: (t_forall B)) by applys~ DSub_Trans HS. apply dsub2asub in EASY2.\n      forwards: IH B EASY1... forwards: IH B EASY2...\n      exists (t_or x x1).\n      exists (union x0\n                 (union x2\n                    (union [[B]]\n                           (union [[A1]] (union [[A2]] (union [[x]] [[x1]])))))).\n      intros. instantiate_cofinites.\n      assert (Heq:forall X, (x | x1 -^ X) = (x -^ X) | (x1-^X)) by eauto. rewrite Heq.\n      split~. applys DSub_CovAll. intros. rewrite Heq. inv_forall.\n      convert2dsub. applys~ DSub_UnionL H3 H6.\n    + exists B0. exists (union [[B]] [[B0]]). convert2dsub. split~.\n    + exists t_bot. exists. split~. eauto.\n  -  forwards~ (Ha1&Ha2): algo_sub_and_inv HS... inverts H.\n     forwards: IH Ha1... forwards: IH Ha2...\n     exists x. exists (x0 `union` x2 `union` [[x]] `union` [[x1]]).\n     intros. instantiate_cofinites.\n     auto_unify_2. forwards~ : open_typ_wrt_typ_inj H5.\n     subst. split~.\n     convert2asub. applys ASub_forall. intros Y Fry.\n     instantiate_cofinites_with Y.\n     inv_forall. applys* ASub_and H1.\n\n     Unshelve. all: apply empty.\nQed.\n\nLemma napplyty_sub_inv : forall (A B C : typ),\n    NApplyTy (t_arrow A B) C -> C <: A -> False.\nProof.\n  introv HA Sub.\n  indTypSize (size_typ C).\n  lets~ [Hu|(?&?&Hu)]: ordu_or_split C...\n  - forwards~ : applyty_completeness_1 (t_arrow A B) C B.\n    applys~ DSub_FunCon. forwards* : napplyty_lc_1 HA.\n    destruct_conj.\n    solve_false.\n  - forwards [?|?]: napplyty_splitu_arg_inv HA Hu.\n    + cut (x <: A).\n      * intros Sub'. applys IH H Sub'. elia.\n      * applys DSub_Trans Sub. convert2asub. eauto.\n    + cut (x0 <: A).\n      * intros Sub'. applys IH H Sub'. elia.\n      * applys DSub_Trans Sub. convert2asub. eauto.\nQed.\n\nLemma applyty_forall_inv : forall (A B C : typ),\n    ApplyTy (t_forall A) B C -> False.\nProof.\n  introv HA. inductions HA. eauto.\nQed.\n\n#[export] Hint Immediate napplyty_sub_inv applyty_forall_inv : FalseHd.\n\n(*------------------------------ Lemma B.10 ----------------------------------*)\n\n(* B.10 [1] *)\nLemma monotonicity_applyty_1 : forall A A' (F : Fty) C,\n    ApplyTy A F C -> A' <: A -> exists C', C' <: C /\\ ApplyTy A' F C'.\nProof with try eassumption; elia; solve_false; destruct_conj.\n  introv HA HS.\n  indTypFtySize (size_typ A' + size_typ A + size_Fty F).\n  lets~ [HF|(?&?&?&?&?)]: (ordu_or_split_Fty F). eauto.\n  2: { subst. forwards : applyty_splitu_arg_inv HA H0. destruct_conj.\n       subst. forwards (?&?&?): IH H1... forwards (?&?&?): IH H2...\n       exists. split. 2: applys~ ApplyTyUnionArg H0...\n       applys~ DSub_UnionL. }\n  inverts HF.\n  - forwards: applyty_soundness_1 HA.\n    forwards HSN: DSub_Trans HS...\n    forwards~ : applyty_completeness_1 HSN. destruct_conj.\n    inv_arrow. convert2dsub. exists* x.\n  - forwards: applyty_soundness_2 HA...\n    pick_fresh Y. forwards~ : H1 Y...\n    forwards HSN: DSub_Trans HS...\n    forwards~ : applyty_completeness_2 HSN...\n    pick fresh X.\n    forwards~ : H4 X. destruct_conj.\n    eapply applyty_rename in H5. exists. split...\n    simpl_rename_goal. subst~.\n    convert2asub.\n    forwards : algo_sub_forall_inv X H6.\n    eapply asub2nsub in H0.\n    eapply typsubst_typ_new_sub in H0.\n    rewrite 2 typsubst_typ_spec in H0;\n      rewrite 2 close_typ_wrt_typ_open_typ_wrt_typ in H0.\n    apply asub2nsub.\n    all: eauto.\nQed.\n\n(* B.10 [2] *)\nLemma monotonicity_applyty_2_1 : forall (A B B' C : typ),\n    ApplyTy A B C -> B' <: B ->\n    exists C', C' <: C /\\ ApplyTy A B' C'.\nProof with try eassumption; elia; solve_false; destruct_conj.\n  introv HA HS.\n  indTypFtySize (size_typ A + size_typ B' + size_typ B).\n  lets~ [HF|(?&?&?)]: (ordu_or_split B').\n  - forwards: applyty_soundness_1 HA.\n    forwards HSN: DSub_Trans H... applys DSub_FunCon HS. eauto.\n    forwards~ : applyty_completeness_1 HSN. destruct_conj.\n    inv_arrow. convert2dsub. exists* x.\n  - assert (S1: x <: B). {\n      applys~ DSub_Trans HS.\n      convert2asub. use_left_r... applys ASub_refl. eauto.\n    }\n    forwards: IH S1...\n    assert (S2: x0 <: B). {\n      applys~ DSub_Trans HS.\n      convert2asub. use_right_r... applys ASub_refl. eauto.\n    }\n    forwards: IH S2...\n    exists (x1|x2). split~. applys~ ApplyTyUnionArg H.\nQed.\n\n(*---------------------- Inversion of Subtyping on (Co-)Value types ----------*)\n\n(* [5] *)\nLemma applyty_arrow : forall A1 A2 V B,\n    ApplyTy (t_arrow A1 A2) V B -> isValFty V -> exists V', V = fty_StackArg V' /\\ isValTyp V'.\nProof.\n  introv App Val.\n  inductions App.\n  - inverts* Val.\n  - inverts* Val.\nQed.\n\n(* [6] *)\nLemma applyty_forall : forall A V B,\n    ApplyTy (t_forall A) V B -> isValFty V -> exists C, V = fty_StackTyArg C.\nProof.\n  introv App Val.\n  inductions App.\n  - inverts* Val.\n  - exfalso.\n    inverts Val. inverts_typ.\n    forwards~ (?&?): IHApp1. solve_false.\nQed.\n\n(* [7] *)\nLemma apply_top_false_1 : forall V,\n    isValTyp V -> NApplyTy t_top [| V |].\n  introv Val. constructor*.\nQed.\n\n(* [7] *)\nLemma apply_top_false_2 : forall V,\n    isValTyp V -> NApplyTy t_top V.\nProof with eauto.\n  introv Val. induction* Val.\nQed.\n\n(* [7] *)\nLemma applyty_top : forall V A,\n    ApplyTy t_top V A -> False.\nProof.\n  introv App.\n  inductions App.\n  forwards~ : IHApp1.\nQed.\n\n#[export] Hint Immediate applyty_top : FalseHd.\n\n(* [8] *)\nLemma apply_box_false_1 : forall l V1 V2,\n    isValTyp V1 -> isValTyp V2 -> NApplyTy (t_rcd l V1) [| V2 |].\n  introv Val. constructor*.\nQed.\n\n(* [8] *)\nLemma apply_box_false_2 : forall l V1 V2,\n    isValTyp V1 -> isValTyp V2 -> NApplyTy (t_rcd l V1) V2.\nProof with eauto.\n  introv Val. induction* Val.\nQed.\n\n(*------------------------- Inversion of Type-Level Dispatch -----------------*)\n\n(* [1] *)\nLemma applyty_bot : forall B C,\n    ApplyTy t_bot B C -> C ~= t_bot.\nProof. introv H. inductions H; eauto using iso_or_2. Qed.\n\n(* [2] the argument must be a type *)\nLemma applyty_arrow_sound_1 : forall A B F D,\n    ApplyTy (t_arrow A B) F D -> exists (C:typ), F = C.\nProof. introv H. inverts* H. Qed.\n\n(* [2] *)\nLemma applyty_arrow_sound_2 : forall (A B C D : typ),\n    ApplyTy (t_arrow A B) C D -> C <: A /\\ B ~= D.\nProof with try eassumption; elia; destruct_conj; auto_unify_2.\n  introv HA.\n  indTypSize (size_typ C).\n  forwards [?|(?&?&?)]: ordu_or_split C. now eauto.\n  - forwards Sub: applyty_soundness_1 HA.\n    convert2asub. inv_arrow. convert2dsub.\n    splits*. split~.\n    forwards~ : applyty_completeness_1 (t_arrow A B) C B...\n    convert2asub. inv_arrow. convert2dsub. easy.\n  - forwards (?&?) : applyty_splitu_arg_inv HA...\n    forwards: IH H1...\n    forwards: IH H2...\n    split.\n    + convert2asub. applys ASub_or...\n    + subst. applys~ iso_dup_1.\nQed.\n\n(* [3] the argument must be a type argument *)\nLemma applyty_forall_sound_1 : forall A F D,\n    ApplyTy (t_forall A) F D -> exists (C:typ), F = [| C |].\nProof. introv H. inductions H.\n       - eauto.\n       - forwards~ : IHApplyTy1. forwards~ : IHApplyTy2. destruct_conj.\n         solve_false.\nQed.\n\n(* [3] *)\nLemma applyty_forall_sound_2 : forall (A B D : typ),\n    ApplyTy (t_forall A) [|B|] D -> D ~= (A ^-^ B).\nProof with destruct_conj.\n  introv HA. inverts HA.\n  applys iso_refl.\n  inverts* H1. eauto with lngen.\nQed.\n\n(* [7] *)\nLemma napplyty_splitu_inv : forall A (F: Fty) A1 A2,\n    NApplyTy A F -> splu A A1 A2 ->\n    NApplyTy A1 F \\/ NApplyTy A2 F.\nProof.\n  introv HA HS. gen A1 A2.\n  induction HA; intros; solve_false; inverts_all_spl; auto_unify.\n  all: try (forwards: IHHA; [ eassumption |.. ]).\n  all: try (forwards [?|?]: IHHA; [ eassumption |.. ]).\n  all: try (forwards [?|?]: IHHA1; [ eassumption |.. ]).\n  all: try (forwards [?|?]: IHHA2; [ eassumption |.. ]).\n  all: try solve [left*; auto]; try solve [right*; auto].\nQed.\n\n(* [4] *)\nLemma applyty_splitu_inv : forall A (F: Fty) A1 A2 C,\n    ApplyTy A F C -> splu A A1 A2 ->\n    exists C1 C2, C ~= C1 | C2 /\\ ApplyTy A1 F C1 /\\ ApplyTy A2 F C2.\nProof with exists; splits.\n  introv HA HS. gen A1 A2.\n  induction HA; intros; solve_false; inverts_all_spl; auto_unify.\n  all: try (forwards: IHHA; [ eassumption |.. ]).\n  all: try solve [exists; splits; eauto].\n  all: try (forwards: IHHA; [ eassumption |.. ]; destruct_conj).\n  all: try (forwards: IHHA1; [ eassumption |.. ]; destruct_conj).\n  all: try (forwards: IHHA2; [ eassumption |.. ]; destruct_conj).\n  all: try lazymatch goal with\n         | H: NApplyTy _ _ |- _ =>\n             forwards [?|?]: napplyty_splitu_inv H; [ eassumption | .. ]\n         end.\n  all: auto_unify_2.\n  - instantiate_cofinites...\n    forwards HN: splu2nsplu H2. forwards HN': typsubst_typ_splu x B HN.\n    now eauto.\n    rewrite 3 typsubst_typ_spec in HN'.\n    rewrite 3 close_typ_wrt_typ_open_typ_wrt_typ in HN'; [ eauto | .. ].\n    all: try solve_notin.\n  - exists; splits.\n    2-3: applys ApplyTyUnionArg; try eassumption.\n    applys iso_trans. 2: applys iso_shuffle.\n    applys* iso_or_match.\n    all: iso_inverts_all_lc; eauto.\n  - exists; splits.\n    2-3: applys ApplyTyInterL; try eassumption.\n    all: eauto.\n  - forwards~ [(?&?)|?]: applyty_total B2 Fty5...\n    all: try (applys ApplyTyInterBoth; now eassumption).\n    all: try (applys ApplyTyInterL; now eassumption).\n    all: try (applys ApplyTyInterR; now eassumption).\n    all: try applys iso_absorb_1.\n    all: try applys* iso_dup_1.\n    all: iso_inverts_all_lc; eauto.\n  - forwards~ [(?&?)|?]: applyty_total B1 Fty5...\n    all: try (applys ApplyTyInterBoth; now eassumption).\n    all: try (applys ApplyTyInterL; now eassumption).\n    all: try (applys ApplyTyInterR; now eassumption).\n    all: try applys iso_absorb_2.\n    all: try applys iso_dup_1.\n    all: iso_inverts_all_lc; eauto.\n  - forwards~ [(?&?)|?]: applyty_total A5 Fty5...\n    all: try (applys ApplyTyInterBoth; now eassumption).\n    all: try (applys ApplyTyInterL; now eassumption).\n    all: try (applys ApplyTyInterR; now eassumption).\n    all: try applys iso_absorb_3.\n    all: try applys iso_dup_1.\n    all: iso_inverts_all_lc; eauto.\n  - forwards~ [(?&?)|?]: applyty_total A4 Fty5...\n    all: try (applys ApplyTyInterBoth; now eassumption).\n    all: try (applys ApplyTyInterL; now eassumption).\n    all: try (applys ApplyTyInterR; now eassumption).\n    all: try applys iso_absorb_4.\n    all: try applys iso_dup_1.\n    all: iso_inverts_all_lc; eauto.\n  - exists; splits.\n    all: try (applys ApplyTyInterBoth; now eassumption).\n    all: try (applys ApplyTyInterL; now eassumption).\n    all: try (applys ApplyTyInterR; now eassumption).\n    all: easy.\n  - exists; splits.\n    all: try (applys ApplyTyInterBoth; now eassumption).\n    all: try (applys ApplyTyInterL; now eassumption).\n    all: try (applys ApplyTyInterR; now eassumption).\n    applys iso_trans. 2: applys* iso_dist_1.\n    applys* iso_and_match.\n    all: iso_inverts_all_lc; eauto.\n  - exists; splits.\n    all: try (applys ApplyTyInterBoth; now eassumption).\n    applys iso_trans. 2: applys* iso_dist_2.\n    applys* iso_and_match.\n    all: iso_inverts_all_lc; eauto.\nQed.\n\n(* [5] *)\nLemma napplyty_spliti_inv : forall A B A1 A2,\n    NApplyTy A B -> spli A A1 A2 ->\n    NApplyTy A1 B /\\ NApplyTy A2 B.\nProof with destruct_conj; try match goal with |- lc_typ _ => eauto end; try eassumption.\n  introv HN HS. gen A1 A2.\n  induction HN; intros; solve_false; inverts_all_spl; auto_unify.\n  all: try (forwards: IHHN; [ eassumption |.. ])...\n  all: try solve [split; eauto]...\n  - cut (~ B <: A3). cut (~ B <: A4).\n    + split; eauto.\n    + intro HF. apply H2. convert2asub.\n      applys algo_trans HF. applys ASub_orr... eauto.\n    + intro HF. apply H2. convert2asub.\n      applys algo_trans HF. applys ASub_orl... eauto.\nQed.\n\n(* [6] *)\nLemma apply_top_false : forall A,\n    lc_typ A -> NApplyTy t_top A.\nProof with eauto.\n  introv Lc. induction* Lc.\nQed.\n\n(*------------------------------ Lemma B.22 -----------------------------------*)\n\n(* B.22 (1) *)\nLemma applyty_arrow_complete : forall A B C,\n    C <: A -> lc_typ B -> exists D, ApplyTy (t_arrow A B) C D.\nProof with elia.\n  introv Sub HB.\n  indTypSize (size_typ C).\n  forwards [?|(?&?&?)]: ordu_or_split C. now eauto.\n  - forwards: applyty_completeness_1 (t_arrow A B) C B.\n    + convert2asub. applys* ASub_arrow.\n    + easy.\n    + destruct_conj. eauto.\n  - cut (x <: A). cut (x0 <: A).\n    + introv Sub1 Sub2.\n      forwards~ : IH A B Sub1...\n      forwards~ : IH A B Sub2...\n      destruct_conj.\n      exists*.\n    + convert2asub. applys* algo_trans Sub.\n    + convert2asub. applys* algo_trans Sub.\nQed.\n\n(* B.22 (2) *)\nLemma applyty_forall_complete : forall A B,\n    lc_typ (t_forall A) -> lc_typ B -> exists C, ApplyTy (t_forall A) [|B|] C.\nProof with elia.\n  intros. exists.\n  constructor*.\nQed.\n\n(* B.22 (3) *)\nLemma applyty_inter : forall B A1 A2 C1 C2,\n    ApplyTy A1 B C1 -> ApplyTy A2 B C2 ->\n    exists C, ApplyTy (A1&A2) B C.\nProof with destruct_conj.\n  introv H1 H2.\n  indTypFtySize (size_Fty B).\n  forwards [?|(?&?&?)]: ordu_or_split_Fty B... now eauto.\n  - exists. applys* ApplyTyInterBoth.\n  - subst.\n    forwards* (?&?) : applyty_splitu_arg_inv H1.\n    forwards* (?&?) : applyty_splitu_arg_inv H2...\n    forwards: IH (fty_StackArg x0) A1 A2; try eassumption; elia.\n    forwards: IH (fty_StackArg x1) A1 A2; try eassumption; elia...\n    exists*.\nQed.\n\n(* B.22 (4) *)\nLemma applyty_union : forall B A1 A2 C1 C2,\n    ApplyTy A1 B C1 -> ApplyTy A2 B C2 ->\n    exists C, ApplyTy (A1 | A2) B C.\nProof with try eassumption; destruct_conj.\n  introv H1 H2.\n  indTypFtySize (size_Fty B).\n  forwards [?|(?&?&?)]: ordu_or_split_Fty B... now eauto.\n  - exists. applys ApplyTyUnion...\n  - subst.\n    forwards* (?&?) : applyty_splitu_arg_inv H1.\n    forwards* (?&?) : applyty_splitu_arg_inv H2...\n    forwards: IH (fty_StackArg x0) A1 A2; try eassumption; elia.\n    forwards: IH (fty_StackArg x1) A1 A2; try eassumption; elia...\n    exists*.\nQed.\n\n(*------------------------- Type Substitution --------------------------------*)\nLemma typsubst_iso : forall A B C X,\n  A ~= B -> lc_typ C ->\n  ([X ~~> C] A) ~= ([X ~~> C] B).\nProof.\n  introv (HS1&HS2) Lc. unfold iso.\n  split; convert2asub;\n    applys~ typsubst_typ_algo_sub.\nQed.\n\nLemma applyty_iso : forall (A A' B B' C : typ),\n    ApplyTy A B C -> A' ~= A -> B' ~= B ->\n    exists C', C' <: C /\\ ApplyTy A' B' C'.\nProof with try eassumption.\n  introv App (HS1&HS1') (HS2&HS2').\n  forwards (?&Sub&App'): monotonicity_applyty_1 App...\n  forwards (?&Sub'&App''): monotonicity_applyty_2_1 App'...\n  exists. split. applys DSub_Trans... apply App''.\nQed.\n\n(* Type Substitution Over Type-Level Dispatch *)\nLemma typsubst_applyty : forall (A B C U : typ) X,\n    ApplyTy A B C -> lc_typ U ->\n    exists C', ApplyTy ([X ~~> U] A) ([X ~~> U] B) C' /\\ C' <: [X ~~> U] C.\nProof with try eassumption.\n  introv App Lc.\n  apply applyty_soundness_1 in App.\n  convert2asub. eapply typsubst_typ_algo_sub in App...\n  convert2dsub. simpl in App.\n  forwards (?&?&?): applyty_completeness_1_all App.\n  exists x; split; convert2asub; auto_inv...\nQed.\n", "meta": {"author": "XSnow", "repo": "bowtie_coq", "sha": "9e963e7afbd5da832534c1c40cbcf5dd28e69ee7", "save_path": "github-repos/coq/XSnow-bowtie_coq", "path": "github-repos/coq/XSnow-bowtie_coq/bowtie_coq-9e963e7afbd5da832534c1c40cbcf5dd28e69ee7/coq/ApplyTy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.2658476869407446}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import Coq.Lists.List.\nRequire Import Coq.ZArith.ZArith.\nRequire Export RBTree.definitions2.\nRequire Import RBTree.AuxiliaryTac.\nRequire Import Coq.Logic.Classical.\nImport ListNotations.\nLocal Open Scope Z.\n\n(* --------------------------------------------------------- *)\n\n\n(* --------------------------------------------------------- *)\nModule getColor1.\n\nDefinition get_color1_spec :=\n  DECLARE _get_color1\n  WITH p: val,\n       p_par: val,\n       p_l: val,\n       p_r: val,\n       n: Node,\n       b: bool\n  PRE [tptr t_struct_tree]\n    PROP (b = false <-> p = nullval)\n    PARAMS (p)\n    GLOBALS ()\n    SEP (if b then\n           data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node n))),\n                                      (Vint (Int.repr (key_of_node n)),\n                                       (Vint (Int.repr (value_of_node n)),\n                                        (p_l, (p_r, p_par))))) p\n         else emp)\n  POST [tint]\n    PROP (b = false <-> p = nullval)\n    RETURN ( Vint (Int.repr (\n      if b then (* p <> nullval *)\n        Col2Z (color_of_node n)\n      else -1)) )\n    SEP (if b then\n           data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node n))),\n                                      (Vint (Int.repr (key_of_node n)),\n                                       (Vint (Int.repr (value_of_node n)),\n                                        (p_l, (p_r, p_par))))) p\n         else emp)\n.\n\nDefinition Gprog : funspecs :=\n         ltac:(with_library prog [ get_color1_spec ]).\n\nLemma body_get_color1: semax_body Vprog Gprog\n                                    f_get_color1 get_color1_spec.\nProof.\n  start_function.\n  destruct b.\n  + (* b = true *)\n    assert_PROP (p <> nullval) by entailer!.\n    forward_if. (* if (p == NULL) *)\n    - congruence. (* p == NULL *)\n    - forward.\n      forward.\n  + (* b = false *)\n    assert_PROP (p = nullval).\n    { entailer!.\n      pose proof proj1 H eq_refl.\n      auto. }\n    forward_if. (* if (p == NULL) *)\n    - forward. (* p == NULL *)\n    - congruence.\nQed.\n\nEnd getColor1.\n\n\n(*  --------------------------------------------------------- *)\n\nModule getColor2.\n\nDefinition get_color2_spec :=\n  DECLARE _get_color2\n  WITH t: tree,\n       p: val,\n       p_par: val,\n       b: bool\n  PRE [tptr t_struct_tree]\n    PROP (b = false <-> p = nullval)\n    PARAMS (p)\n    GLOBALS ()\n    SEP (if b then\n           rbtree_rep t p p_par\n         else emp)\n  POST [tint]\n    PROP (b = false <-> p = nullval)\n    RETURN ( Vint (Int.repr (\n      if b then (* p <> nullval *)\n        match t with\n        | T _ n _ => Col2Z(color_of_node(n))\n        | E => -2 (* unknown error *)\n        end\n      else -1)) )\n    SEP (if b then\n           rbtree_rep t p p_par\n         else emp)\n.\n\nDefinition Gprog : funspecs :=\n         ltac:(with_library prog [ get_color2_spec ]).\n\nLemma body_get_color2: semax_body Vprog Gprog\n                                    f_get_color2 get_color2_spec.\nProof.\n  start_function.\n  destruct b.\n  + (* b = true *)\n    assert_PROP (p <> nullval).\n    { entailer!.\n      pose proof proj2 H eq_refl.\n      congruence. }\n    forward_if. (* if (p == NULL) *)\n    - congruence. (* p == NULL *)\n    - assert_PROP ( t <> E ).\n      { entailer!. \n        pose proof proj2 H2 eq_refl.\n        tauto. }\n      destruct t as [|l n r] eqn:Et; [tauto|]. (* t = T l n r *)\n      expand rbtree_rep.\n      Intros p_lch p_rch.\n      forward.\n      forward.\n      expand rbtree_rep.\n      Exists p_lch p_rch.\n      entailer!.\n  + (* b = false *)\n    assert_PROP (p = nullval).\n    { entailer!.\n      pose proof proj1 H eq_refl.\n      auto. }\n    forward_if. (* if (p == NULL) *)\n    - forward. (* p == NULL *)\n    - congruence.\nQed.\n\nEnd getColor2.\n\n(* --------------------------------------------------------- *)\nModule makeBlack.\nDefinition make_black_spec :=\n  DECLARE _make_black\n  WITH t_initial: tree,\n       b_initial: val,\n       p_par_initial: val\n  PRE [ tptr (tptr t_struct_tree) ]\n    PROP (b_initial <> nullval)\n    PARAMS (b_initial)\n    GLOBALS ()\n    SEP (treebox_rep t_initial b_initial p_par_initial)\n  POST [ Tvoid ]\n    PROP ()\n    RETURN ()\n    SEP (treebox_rep (makeBlack t_initial) b_initial p_par_initial)\n.\n\nDefinition Gprog : funspecs :=\n         ltac:(with_library prog [ make_black_spec ]).\n\n\nLemma body_make_black: semax_body Vprog Gprog\n                                    f_make_black make_black_spec.\nProof.\n  start_function.\n  forward_if.\n  + forward.\n  + expand treebox_rep.\n    Intros p_initial.\n    forward.\n    forward_if.\n    - assert_PROP(t_initial = E).\n      pose proof rbtree_rep_nullval t_initial p_par_initial.\n      entailer!. tauto.\n      forward.\n      simpl. unfold treebox_rep, rbtree_rep. Exists nullval.\n      entailer!.\n    - assert_PROP(t_initial <> E).\n      { destruct t_initial.\n        { unfold rbtree_rep. entailer!. }\n        { pose proof T_neq_E t_initial1 t_initial2 n.\n          entailer!. } }\n      destruct t_initial; [congruence|].\n      unfold makeBlack.\n      expand rbtree_rep.\n      Intros p_lch p_rch.\n      forward.\n      expand treebox_rep.\n      Exists p_initial.\n      entailer!.\n      expand rbtree_rep.\n      Exists p_lch p_rch.\n      entailer!.\nQed.\nEnd makeBlack.\n\n\n(* --------------------------------------------------------- *)\nModule leftRotate.\n\nDefinition left_rotate_spec :=\n  DECLARE _left_rotate\n  WITH p_l: val, \n       p_r: val,\n       p_par: val,\n       p_mid: val,\n       p_l_l: val,\n       p_r_r: val,\n       l_n: Node,\n       r_n: Node,\n       tree_l_l: tree,\n       tree_r_r: tree,\n       tree_mid: tree\n  PRE [ tptr t_struct_tree ]\n    PROP (is_pointer_or_null p_par; \n          Int.min_signed <= key_of_node r_n <= Int.max_signed;\n          Int.min_signed <= key_of_node l_n <= Int.max_signed)\n    PARAMS (p_l)\n    GLOBALS ()\n    SEP (data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node l_n))),\n                                    (Vint (Int.repr (key_of_node l_n)),\n                                     (Vint (Int.repr (value_of_node l_n)),\n                                      (p_l_l, (p_r, p_par))))) p_l;\n         data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node r_n))),\n                                    (Vint (Int.repr (key_of_node r_n)),\n                                     (Vint (Int.repr (value_of_node r_n)),\n                                      (p_mid, (p_r_r, p_l))))) p_r;\n         rbtree_rep tree_mid p_mid p_r;\n         rbtree_rep tree_l_l p_l_l p_l;\n         rbtree_rep tree_r_r p_r_r p_r )\n  POST [ tptr t_struct_tree ]\n    PROP (isptr p_r; p_r <> nullval;\n          is_pointer_or_null p_par;\n          Int.min_signed <= key_of_node r_n <= Int.max_signed;\n          Int.min_signed <= key_of_node l_n <= Int.max_signed)\n    RETURN (p_r)\n    SEP (data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node l_n))),\n                                    (Vint (Int.repr (key_of_node l_n)),\n                                     (Vint (Int.repr (value_of_node l_n)),\n                                      (p_l_l, (p_mid, p_r))))) p_l;\n         data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node r_n))),\n                                    (Vint (Int.repr (key_of_node r_n)),\n                                     (Vint (Int.repr (value_of_node r_n)),\n                                      (p_l, (p_r_r, p_par))))) p_r;\n         rbtree_rep tree_mid p_mid p_l;\n         rbtree_rep tree_l_l p_l_l p_l;\n         rbtree_rep tree_r_r p_r_r p_r ) (* p_par还连在p_l上 *)\n.\n\nDefinition Gprog : funspecs :=\n         ltac:(with_library prog [ left_rotate_spec ]).\n\nLemma body_left_rotate: semax_body Vprog Gprog\n                                    f_left_rotate left_rotate_spec.\nProof.\n  start_function.\n  forward. (* struct tree * r = l->right; *)\n  forward. (* struct tree * mid = r->left; *)\n  forward. \n  forward. (* r->left = l; *)\n  forward.\n  forward.\n  forward. (* l->par = r; *)\n  forward_if ( \n    PROP (isptr p_r; is_pointer_or_null p_par)\n    LOCAL (temp _t'1 p_par; temp _mid p_mid; temp _r p_r; temp _l p_l)\n    SEP (data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node l_n))),\n                                    (Vint (Int.repr (key_of_node l_n)),\n                                     (Vint (Int.repr (value_of_node l_n)),\n                                      (p_l_l, (p_mid, p_r))))) p_l;\n         data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node r_n))),\n                                    (Vint (Int.repr (key_of_node r_n)),\n                                     (Vint (Int.repr (value_of_node r_n)),\n                                      (p_l, (p_r_r, p_par))))) p_r;\n         rbtree_rep tree_mid p_mid p_l;\n         rbtree_rep tree_l_l p_l_l p_l;\n         rbtree_rep tree_r_r p_r_r p_r )).\n  + assert_PROP (tree_mid <> E) by (entailer!; tauto). (* mid != NULL *)\n    destruct tree_mid eqn:tree_mid_fact; [congruence|]. (* tree_mid = T t1 n t2 *)\n    expand rbtree_rep. (* rbtree_rep (T t1 n t2) p_mid p_r *)\n    Intros p_mid_l p_mid_r.\n    forward. (* mid->par = l; *)\n    entailer!.\n    expand rbtree_rep.\n    Exists p_mid_l p_mid_r.\n    entailer!.\n  + forward. (* mid = NULL *)\n    entailer!.\n    assert (tree_mid = E) by tauto.\n    subst.\n    expand rbtree_rep.\n    entailer!.\n  + forward. (* return r; 证明r满足后条件 *)\nQed.\n\nEnd leftRotate.\n\n\n(* --------------------------------------------------------- *)\nModule leftRotateWrap.\n\nDefinition left_rotate_wrap_spec := (* 就是为了处理p_l父亲的不同情况的 *)\n  DECLARE _left_rotate_wrap\n  WITH p_l: val, \n       p_r: val,\n       p_par: val,\n       p_mid: val,\n       p_l_l: val,\n       p_r_r: val,\n       p_root: val,\n       p_top: val,\n       l_n: Node,\n       r_n: Node,\n       tree_l_l: tree,\n       tree_r_r: tree,\n       tree_mid: tree,\n       root: val,\n       b: bool,\n       isleft: bool,\n       p_gpar: val,\n       p_unc: val,\n       par_n: Node,\n       uncisnull: bool,\n       tree_unc: tree\n  PRE [ tptr t_struct_tree, tptr (tptr t_struct_tree) ]\n    PROP (nullval = p_par <-> b = false;\n          Int.min_signed <= key_of_node r_n <= Int.max_signed;\n          Int.min_signed <= key_of_node l_n <= Int.max_signed;\n          p_top = nullval; p_l <> nullval;\n          is_pointer_or_null p_par;\n          is_pointer_or_null p_unc;\n          p_unc <> p_l)\n    PARAMS (p_l; root)\n    GLOBALS ()\n    SEP (data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node l_n))),\n                                    (Vint (Int.repr (key_of_node l_n)),\n                                     (Vint (Int.repr (value_of_node l_n)),\n                                      (p_l_l, (p_r, p_par))))) p_l;\n         data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node r_n))),\n                                    (Vint (Int.repr (key_of_node r_n)),\n                                     (Vint (Int.repr (value_of_node r_n)),\n                                      (p_mid, (p_r_r, p_l))))) p_r;\n         rbtree_rep tree_mid p_mid p_r;\n         rbtree_rep tree_l_l p_l_l p_l;\n         rbtree_rep tree_r_r p_r_r p_r;\n         if b then\n           data_at Tsh (tptr t_struct_tree) p_root root *\n           (if uncisnull then !! (p_unc = nullval) &&emp\n             else rbtree_rep tree_unc p_unc p_par) *\n           if isleft then\n             data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node par_n))),\n                                        (Vint (Int.repr (key_of_node par_n)),\n                                         (Vint (Int.repr (value_of_node par_n)),\n                                          (p_l, (p_unc, p_gpar))))) p_par\n           else\n             data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node par_n))),\n                                        (Vint (Int.repr (key_of_node par_n)),\n                                         (Vint (Int.repr (value_of_node par_n)),\n                                          (p_unc, (p_l, p_gpar))))) p_par\n         else\n           data_at Tsh (tptr t_struct_tree) p_root root\n         )\n  POST [ tvoid ]\n      PROP (nullval = p_par <-> b = false;\n            isptr p_r; p_r <> nullval;\n            Int.min_signed <= key_of_node r_n <= Int.max_signed;\n            Int.min_signed <= key_of_node l_n <= Int.max_signed;\n            is_pointer_or_null p_par;\n            is_pointer_or_null p_unc;\n            p_unc <> p_l)\n      RETURN ()\n      SEP (data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node l_n))),\n                                      (Vint (Int.repr (key_of_node l_n)),\n                                       (Vint (Int.repr (value_of_node l_n)),\n                                        (p_l_l, (p_mid, p_r))))) p_l;\n           data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node r_n))),\n                                      (Vint (Int.repr (key_of_node r_n)),\n                                       (Vint (Int.repr (value_of_node r_n)),\n                                        (p_l, (p_r_r, p_par))))) p_r;\n           rbtree_rep tree_mid p_mid p_l;\n           rbtree_rep tree_l_l p_l_l p_l;\n           rbtree_rep tree_r_r p_r_r p_r;\n           if b then\n             data_at Tsh (tptr t_struct_tree) p_root root *\n             (if uncisnull then !! (p_unc = nullval) &&emp\n               else rbtree_rep tree_unc p_unc p_par) *\n             if isleft then\n               data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node par_n))),\n                                        (Vint (Int.repr (key_of_node par_n)),\n                                         (Vint (Int.repr (value_of_node par_n)),\n                                          (p_r, (p_unc, p_gpar))))) p_par\n             else\n               data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node par_n))),\n                                        (Vint (Int.repr (key_of_node par_n)),\n                                         (Vint (Int.repr (value_of_node par_n)),\n                                          (p_unc, (p_r, p_gpar))))) p_par\n           else\n             data_at Tsh (tptr t_struct_tree) p_r root )\n.\n\nDefinition Gprog : funspecs :=\n         ltac:(with_library prog [ leftRotate.left_rotate_spec; left_rotate_wrap_spec ]).\n         \nLemma body_left_rotate_wrap: semax_body Vprog Gprog\n                                    f_left_rotate_wrap left_rotate_wrap_spec.\nProof.\n  start_function.\n  subst p_top.\n  (* assert_PROP (is_pointer_or_null p_par) by entailer!. *)\n  forward.\n  forward_if.\n  { destruct b. destruct isleft; entailer!.\n    assert (nullval = p_par) by tauto.\n    entailer!. }\n  + destruct b.\n    { subst p_par. assert(true = false) by tauto.\n      congruence. }\n    forward_call(p_l, p_r, (* l->par == NULL *)\n        p_par, p_mid,\n        p_l_l, p_r_r,\n        l_n, r_n,\n        tree_l_l, tree_r_r, tree_mid).\n    forward.\n    entailer!.\n  + destruct b.\n    2: { assert(nullval = p_par) by tauto. congruence. }\n    destruct isleft; destruct uncisnull; Intros;\n    forward; forward; forward_if_wrp; try contradiction; \n    forward_call(p_l, p_r, \n        p_par, p_mid,\n        p_l_l, p_r_r,\n        l_n, r_n,\n        tree_l_l, tree_r_r, tree_mid);\n    forward; entailer!.\nQed.\n\nEnd leftRotateWrap.\n\n\n(* --------------------------------------------------------- *)\nModule rightRotate.\n\nDefinition right_rotate_spec :=\n  DECLARE _right_rotate\n  WITH p_l: val, \n       p_r: val,\n       p_par: val,\n       p_mid: val,\n       p_l_l: val,\n       p_r_r: val,\n       l_n: Node,\n       r_n: Node,\n       tree_l_l: tree,\n       tree_r_r: tree,\n       tree_mid: tree\n  PRE [ tptr t_struct_tree ]\n    PROP (is_pointer_or_null p_par; \n          Int.min_signed <= key_of_node l_n <= Int.max_signed;\n          Int.min_signed <= key_of_node r_n <= Int.max_signed)\n    PARAMS (p_r)\n    GLOBALS ()\n    SEP (data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node l_n))),\n                                    (Vint (Int.repr (key_of_node l_n)),\n                                     (Vint (Int.repr (value_of_node l_n)),\n                                      (p_l_l, (p_mid, p_r))))) p_l;\n         data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node r_n))),\n                                    (Vint (Int.repr (key_of_node r_n)),\n                                     (Vint (Int.repr (value_of_node r_n)),\n                                      (p_l, (p_r_r, p_par))))) p_r;\n         rbtree_rep tree_mid p_mid p_l;\n         rbtree_rep tree_l_l p_l_l p_l;\n         rbtree_rep tree_r_r p_r_r p_r )\n  POST [ tptr t_struct_tree ]\n    PROP (isptr p_l; p_l <> nullval;\n          is_pointer_or_null p_par;\n          Int.min_signed <= key_of_node r_n <= Int.max_signed;\n          Int.min_signed <= key_of_node l_n <= Int.max_signed)\n    RETURN (p_l)\n    SEP (data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node l_n))),\n                                    (Vint (Int.repr (key_of_node l_n)),\n                                     (Vint (Int.repr (value_of_node l_n)),\n                                      (p_l_l, (p_r, p_par))))) p_l;\n         data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node r_n))),\n                                    (Vint (Int.repr (key_of_node r_n)),\n                                     (Vint (Int.repr (value_of_node r_n)),\n                                      (p_mid, (p_r_r, p_l))))) p_r;\n         rbtree_rep tree_mid p_mid p_r;\n         rbtree_rep tree_l_l p_l_l p_l;\n         rbtree_rep tree_r_r p_r_r p_r )\n.\nDefinition Gprog : funspecs :=\n         ltac:(with_library prog [ right_rotate_spec ]).\n\nLemma body_right_rotate: semax_body Vprog Gprog\n                                    f_right_rotate right_rotate_spec.\nProof.\n  start_function.\n  forward.\n  forward.\n  forward. \n  forward.\n  forward.\n  forward.\n  forward.\n  forward_if ( \n    PROP (isptr p_l; is_pointer_or_null p_par)\n    LOCAL (temp _t'1 p_par; temp _mid p_mid; temp _r p_r; temp _l p_l)\n    SEP (data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node l_n))),\n                                    (Vint (Int.repr (key_of_node l_n)),\n                                     (Vint (Int.repr (value_of_node l_n)),\n                                      (p_l_l, (p_r, p_par))))) p_l;\n         data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node r_n))),\n                                    (Vint (Int.repr (key_of_node r_n)),\n                                     (Vint (Int.repr (value_of_node r_n)),\n                                      (p_mid, (p_r_r, p_l))))) p_r;\n         rbtree_rep tree_mid p_mid p_r;\n         rbtree_rep tree_l_l p_l_l p_l;\n         rbtree_rep tree_r_r p_r_r p_r )).\n  + assert_PROP (tree_mid <> E) by (entailer!; tauto).\n    destruct tree_mid eqn:tree_mid_fact; [congruence|]. \n    expand rbtree_rep.\n    Intros p_mid_l p_mid_r.\n    forward.\n    entailer!.\n    expand rbtree_rep.\n    Exists p_mid_l p_mid_r.\n    entailer!.\n  + forward. (* mid = NULL *)\n    entailer!.\n    assert (tree_mid = E) by tauto.\n    subst.\n    expand rbtree_rep.\n    entailer!.\n  + forward.\nQed.\n\nEnd rightRotate.\n\n\n(* --------------------------------------------------------- *)\nModule rightRotateWrap.\n\n\nDefinition right_rotate_wrap_spec := (* 就是为了处理p_r父亲的不同情况的 *)\n  DECLARE _right_rotate_wrap\n  WITH p_l: val, \n       p_r: val,\n       p_par: val,\n       p_mid: val,\n       p_l_l: val,\n       p_r_r: val,\n       p_root: val,\n       p_top: val,\n       l_n: Node,\n       r_n: Node,\n       tree_l_l: tree,\n       tree_r_r: tree,\n       tree_mid: tree,\n       root: val,\n       b: bool,\n       isleft: bool,\n       p_gpar: val,\n       p_unc: val,\n       par_n: Node,\n       uncisnull: bool,\n       tree_unc: tree\n  PRE [ tptr t_struct_tree, tptr (tptr t_struct_tree) ]\n    PROP (nullval = p_par <-> b = false;\n          Int.min_signed <= key_of_node l_n <= Int.max_signed;\n          Int.min_signed <= key_of_node r_n <= Int.max_signed;\n          p_r <> nullval; p_top = nullval;\n          is_pointer_or_null p_par;\n          is_pointer_or_null p_unc;\n          p_unc <> p_r)\n    PARAMS (p_r; root)\n    GLOBALS ()\n    SEP (data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node l_n))),\n                                    (Vint (Int.repr (key_of_node l_n)),\n                                     (Vint (Int.repr (value_of_node l_n)),\n                                      (p_l_l, (p_mid, p_r))))) p_l;\n         data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node r_n))),\n                                    (Vint (Int.repr (key_of_node r_n)),\n                                     (Vint (Int.repr (value_of_node r_n)),\n                                      (p_l, (p_r_r, p_par))))) p_r;\n         rbtree_rep tree_mid p_mid p_l;\n         rbtree_rep tree_l_l p_l_l p_l;\n         rbtree_rep tree_r_r p_r_r p_r;\n         if b then\n           data_at Tsh (tptr t_struct_tree) p_root root *\n           (if uncisnull then !! (p_unc = nullval) && emp\n               else rbtree_rep tree_unc p_unc p_par) *\n           if isleft then\n             data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node par_n))),\n                                        (Vint (Int.repr (key_of_node par_n)),\n                                         (Vint (Int.repr (value_of_node par_n)),\n                                          (p_r, (p_unc, p_gpar))))) p_par\n           else\n             data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node par_n))),\n                                        (Vint (Int.repr (key_of_node par_n)),\n                                         (Vint (Int.repr (value_of_node par_n)),\n                                          (p_unc, (p_r, p_gpar))))) p_par\n         else\n           data_at Tsh (tptr t_struct_tree) p_root root\n         )\n  POST [ tvoid ]\n      PROP (nullval = p_par <-> b = false; \n            Int.min_signed <= key_of_node l_n <= Int.max_signed;\n            Int.min_signed <= key_of_node r_n <= Int.max_signed;\n            is_pointer_or_null p_par;\n            is_pointer_or_null p_unc;\n            p_unc <> p_r)\n      RETURN ()\n      SEP (data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node l_n))),\n                                      (Vint (Int.repr (key_of_node l_n)),\n                                       (Vint (Int.repr (value_of_node l_n)),\n                                        (p_l_l, (p_r, p_par))))) p_l;\n           data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node r_n))),\n                                      (Vint (Int.repr (key_of_node r_n)),\n                                       (Vint (Int.repr (value_of_node r_n)),\n                                        (p_mid, (p_r_r, p_l))))) p_r;\n           rbtree_rep tree_mid p_mid p_r;\n           rbtree_rep tree_l_l p_l_l p_l;\n           rbtree_rep tree_r_r p_r_r p_r;\n           if b then\n             data_at Tsh (tptr t_struct_tree) p_root root *\n             (if uncisnull then !! (p_unc = nullval) && emp\n               else rbtree_rep tree_unc p_unc p_par) *\n             if isleft then\n               data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node par_n))),\n                                        (Vint (Int.repr (key_of_node par_n)),\n                                         (Vint (Int.repr (value_of_node par_n)),\n                                          (p_l, (p_unc, p_gpar))))) p_par\n             else\n               data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node par_n))),\n                                        (Vint (Int.repr (key_of_node par_n)),\n                                         (Vint (Int.repr (value_of_node par_n)),\n                                          (p_unc, (p_l, p_gpar))))) p_par\n           else\n             data_at Tsh (tptr t_struct_tree) p_l root )\n.\n\nDefinition Gprog : funspecs :=\n         ltac:(with_library prog [ rightRotate.right_rotate_spec; right_rotate_wrap_spec ]).\n\nLemma body_right_rotate_wrap: semax_body Vprog Gprog\n                                    f_right_rotate_wrap right_rotate_wrap_spec.\nProof.\n  start_function.\n  subst p_top.\n  (* assert_PROP (is_pointer_or_null p_par) by entailer!. *)\n  forward.\n  forward_if.\n  { destruct b. destruct isleft; entailer!.\n    assert (nullval = p_par) by tauto.\n    entailer!. }\n  + destruct b.\n    { subst p_par. assert(true = false) by tauto.\n      congruence. }\n    forward_call(p_l, p_r, (* l->par == NULL *)\n        p_par, p_mid,\n        p_l_l, p_r_r,\n        l_n, r_n,\n        tree_l_l, tree_r_r, tree_mid).\n    forward.\n    entailer!.\n  + destruct b.\n    2: { assert(nullval = p_par) by tauto. congruence. }\n    destruct isleft, uncisnull; Intros;\n    forward; forward; forward_if_wrp; try contradiction; try solve[\n    forward_call(p_l, p_r, \n        p_par, p_mid,\n        p_l_l, p_r_r,\n        l_n, r_n,\n        tree_l_l, tree_r_r, tree_mid);\n    forward; entailer!].\nQed.\n\nEnd rightRotateWrap.\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/api_spec2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.5117166047041652, "lm_q1q2_score": 0.26584768694074445}}
{"text": "\nRequire Import Iron.Language.SimpleData.Exp.\nRequire Export Iron.Data.Context.\nRequire Export Iron.Data.Chain.\n\n\n(********************************************************************)\n(*  Evaluation contexts for expressions.\n    This describes a place in the exp AST where the sub-expression\n    there is able to take an evaluation step *)\nInductive exp_ctx : (exp -> exp) -> Prop :=\n\n (* The top level context names the entire expression *)\n | XcTop\n   : exp_ctx  (fun x => x)\n\n (* Left of an application *)\n | XcApp1\n   :  forall x2\n   ,  exp_ctx  (fun xx => XApp xx x2)\n\n (* The right of an application can step only when the left is\n    already a value. *)\n | XcApp2\n   :  forall v1\n   ,  value v1\n   -> exp_ctx  (fun xx => XApp v1 xx)\n\n (* As the XCon constructor contains a list of sub-expressions,\n    we need an additional exps_ctx context to indicate which one\n    we're talking about. *)\n | XcCon\n   :  forall dc C\n   ,  exps_ctx wnfX C\n   -> exp_ctx  (fun xx => XCon dc (C xx))\n\n (* We need to reduce the discriminant of a case to a value. *)\n | XcCase\n   :  forall alts\n   ,  exp_ctx  (fun xx => XCase xx alts).\n\nHint Constructors exp_ctx.\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/SimpleData/StepContext.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213070736461, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2658476793271963}}
{"text": "Require Import memory.\nRequire Import language.\nRequire Import opsem.\nRequire Import assertion.\nSet Asymmetric Patterns.\n(*\nDefinition emposspec : osspec :=\n  ( fun (i : fid) => None,   fun (i : hid) => None, fun _ _ =>  True ).\n *)\n\nNotation hmstep := spec_step.\nNotation hmstepstar:=spec_stepstar.\n\n(*\nDefinition absimp' sc (p p' : asrt) := \nforall (s : taskst) (O : osabst) (gamma : absop),\n(s, O, gamma) |= p ->\nforall Of OO,\n  join O Of OO ->\n  exists O' gamma' OO OO',\n    join O' Of OO' /\\\n    hmstepstar sc gamma OO gamma'\n               OO' /\\ (s, O', gamma') |= p'.\n *)\n\nDefinition satp o O p := forall aop,   (o,O, aop)  |= p.\n\nDefinition LocalInv := tid -> list logicvar ->  asrt.\n\nDefinition p_exact lasrt :=\n  forall ge le M ir aux O le' M' aux' ir' O',\n    satp (ge,le,M,ir,aux) O lasrt ->\n    satp (ge,le',M',ir',aux') O' lasrt ->\n    M' = M /\\ O' = O.\n\nDefinition GoodLInvAsrt (p : LocalInv):= forall t lg, GoodLocalInvAsrt (p t lg) /\\ p_exact (p t lg).\n\nDefinition CurTid t :=  (EX tp : type, GV OSTCBCur @ Tptr tp |-r-> Vptr t).\n\nDefinition LINV p t lg :=  p t lg ** [|GoodLInvAsrt p|].\n\nDefinition p_local (p : LocalInv) (t:tid) lg  := CurTid t **  LINV p t lg.\n\nDefinition CurLINV p t := EX lg, CurTid t **  LINV p t lg ** Atrue.\n\n\n(**For specifying the spawned tasked in ucos**)\nDefinition  init_lg := (logic_val  (Vint32 (Int.repr 1%Z)) :: nil).\n(**Configure it in terms of different target kernels***)\n\nDefinition  absimplication sc (li : LocalInv) (p p' : asrt) (t : tid) := \n  forall (s : taskst) (O : osabst) (gamma : absop),\n    (s, O, gamma) |= p /\\ satp s O  (CurLINV li t)  ->\n    exists O' gamma',\n      hmstepstar sc gamma O gamma' O' /\\ (s, O', gamma') |= p' /\\\n      satp s O'  (CurLINV li t)  .\n\nDefinition sched_self sc (O : osabst) :=\n  exists t, get O curtid = Some (oscurt t) /\\ sc O t.\n\nInductive absinferfull : ossched ->LocalInv ->  asrt -> asrt -> tid -> Prop :=\n| absinfer_eq' :\n    forall p sc li t,\n      absinferfull sc li p p t\n                   \n| absinfer_trans' :\n    forall p q r sc li t,\n      absinferfull sc li p q t -> absinferfull sc li  q r t -> absinferfull sc li  p r t\n                                                                            \n| absinfer_disj':\n    forall p1 p2 q1 q2 sc li t,\n      absinferfull sc li p1 q1 t ->\n      absinferfull sc li p2 q2 t ->\n      absinferfull sc li (p1\\\\//p2) (q1\\\\// q2) t\n\n| absinfer_conseq' :\n    forall p q p' q' sc li t, \n      q ==> q' ->\n      absinferfull sc li p q  t->\n      p'==> p -> absinferfull sc li p' q' t\n\n| absinfer_ex' :\n    forall  (tp:Type) (p:tp->asrt) q sc li t,\n      (forall x,absinferfull sc li (p x) q t)  -> absinferfull sc li  (EX x:tp,p x) q t \n                                                               \n| absinfer_frm' :\n    forall p q r sc li t,\n      can_change_aop r ->\n      p ==> (CurLINV li t)  ->\n      absinferfull sc li p q t -> absinferfull sc li (p ** r) (q ** r) t\n                                               \n| absinfer_prim':\n    forall p q step vl v sc li t,\n      can_change_aop p ->\n      can_change_aop q ->\n      absimplication sc li (<||step (|vl|)||> ** p) (<||END v||> ** q) t\n      -> absinferfull sc li (<||step (|vl|)||> ** p) (<||END v||> ** q) t\n                      \n| absinfer_seq': forall p q s1 s2 s1' sc li t,\n                   can_change_aop p ->\n                   can_change_aop q -> \n                   absinferfull sc li (<||s1||> ** p) (<||s1'||> ** q) t ->\n                   absinferfull sc li  (<||s1 ;; s2 ||> **p ) (<||s1';;s2||>**q) t\n\n                                \n| absinfer_seq_end': forall p q s v sc li t,\n                       can_change_aop p ->\n                       can_change_aop q -> \n                       p ==> q ->\n                       absinferfull sc li  (<||END v ;; s ||> **p ) (<||s||> ** q) t\n                                    \n| absinfer_choice1':\n    forall p q s1 s2 sc li t,\n      can_change_aop p ->\n      can_change_aop q -> \n      p ==> q -> \n      absinferfull sc li (<||s1 ?? s2 ||> ** p) (<||s1||> ** q) t\n                   \n| absinfer_choice2' :\n    forall p q s1 s2 sc li t,\n      can_change_aop p ->\n      can_change_aop q -> \n      p ==> q -> \n      absinferfull sc li (<||s1 ?? s2 ||> ** p ) (<||s2||> ** q) t\n                   \n|absinfer_assume' :\n   forall  p (b:absexpr) q sc li t,\n     can_change_aop p ->\n     can_change_aop q ->\n     p  ==> q ->\n     (forall s, (s |= p) -> b (getabst s)) ->     \n     absinferfull sc li (<||ASSUME b||> ** p) (<||END None||> ** q) t\n                  \n|absinfer_sched' :\n   forall  p (b:absexpr) q sc li t,\n     can_change_aop p ->\n     can_change_aop q ->\n     p  ==> q ->\n     (forall s, (s |= p) -> sched_self sc  (getabst s)) ->     \n     absinferfull sc li (<||sched||> ** p) (<||END None||> ** q) t.\n\nNotation \"  '#' sc , li , t '⊢' p '⇒' q \" := (absinferfull sc li  p q t) (at level 80).\n\nDefinition match_tid_prio (tls:  TcbMod.map) (v v' : val) := \n  (exists pr a tid msg, v = Vptr tid /\\\n                        get tls tid = Some (pr, a, msg) /\\ v' = Vint32 pr).\n\nDefinition  retpost (p : fpost) : Prop :=\n  forall s vl v logicl tid, sat s (getasrt (p vl v logicl tid)) -> v <> None.\n\nFixpoint GoodStmt' s := \n  match s with\n    | sskip _ => True\n    | sassign _ _ => True\n    | sif _ s1 s2 => GoodStmt' s1 /\\ GoodStmt' s2\n    | sifthen _ s => GoodStmt' s\n    | swhile _ s' => GoodStmt' s'\n    | sret => True\n    | srete _ => True\n    | scall f _ => True\n    | scalle _ f _ => True\n    | sseq s1 s2 => GoodStmt' s1 /\\ GoodStmt' s2\n    | sprint _ => True\n    | sfexec _ _ _ => False\n    | sfree _ _ => False\n    | salloc _ _ => False\n    | sprim _ => True\n    | hapi_code _ => False\n  end.\n\n\n\nDefinition GoodSched (sd : ossched) :=  \n  (\n    forall x a y t, join x a y -> sd x t -> sd y t\n  ) /\\\n  (\n    forall x t,  sd x t ->\n                 (exists tcbls tcb,\n                    get x abstcblsid =\n                    Some (abstcblist tcbls) /\\ \n                    get tcbls t = Some tcb)\n  ) /\\\n  (\n    forall O1 O2 O t t',\n      join O1 O2 O ->\n      sd O1 t ->\n      sd O t' ->\n      sd O1 t'\n  ).\n\n\nFixpoint GoodFrm (p : asrt){struct p}: Prop :=\n  match p with\n    | Aie _ => False\n    | Ais _ => False\n    | ATopis  _ =>  False\n    | Aisr _ => False\n    | Acs _ => False         \n    | p' //\\\\ q' =>  GoodFrm  p' /\\ GoodFrm q'\n    | p' \\\\// q' => GoodFrm  p' /\\ GoodFrm  q'\n    | p' ** q' => GoodFrm p' /\\ GoodFrm q'\n    | Aexists t p' => forall x, GoodFrm (p' x)\n    | Anot _ => False\n    | Aop _ => False\n    | _ => True\n  end.\n\nDefinition GoodI (I:Inv) (sd : ossched) (pa:LocalInv):=\n  (\n    forall o O O' ab OO, (o,O,ab) |= starinv_noisr I 0%nat (S INUM) -> join O O' OO-> O' = empabst\n  ) /\\ \n  (\n    forall o O ab tid, (o,O,ab)|= SWINVt I tid->  \n                       exists b tp, get (get_genv (get_smem o)) OSTCBCur = Some (b,(Tptr tp)) /\\\n                                    load (Tptr tp) (get_mem (get_smem o)) (b,0%Z) = Some (Vptr tid) /\\\n                                    get O curtid = Some (oscurt tid)\n  )  /\\\n  (\n    forall o O ab tid b tp M' ct,\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%Z) (Vptr tid) = Some M' -> \n      exists tls,\n        get O abstcblsid = Some (abstcblist tls)/\\\n        (\n          (\n            indom tls ct /\\\n            (substaskst o M', set O curtid (oscurt tid), ab) |= SWINVt I tid\n          ) \\/\n          \n          (\n            ~ indom tls ct /\\\n            forall Mx Ox MM OO,\n              satp (substaskst o Mx) Ox (EX lg, pa ct lg) ->\n              join M' Mx MM ->\n              join O Ox OO ->\n              (substaskst o MM, set OO curtid (oscurt tid), ab) |= SWINVt I tid)\n        )\n  )/\\ \n  GoodSched sd. \n\n\n\nDefinition SWPRE_NDEAD sd x tc:= SWPRE sd x tc //\\\\ EX tls,Aabsdata abstcblsid (abstcblist tls) ** [| indom tls tc |] ** Atrue.\n\nDefinition SWPRE_DEAD sd x tc:= SWPRE sd x tc //\\\\ EX tls,Aabsdata abstcblsid (abstcblist tls) ** [|~indom tls tc |] ** Atrue.\n\n(*\nDefinition p_local (p : LocalInv) (t:tid) lg  :=\n  (EX tp : type, GV OSTCBCur @ Tptr tp |-r-> Vptr t) ** p t lg ** [|GoodLInvAsrt p|].\n *)\n\nInductive InfRules: funspec -> ossched -> LocalInv -> Inv -> retasrt -> asrt ->\n                    asrt -> stmts -> asrt -> tid -> Prop:=\n(*| skip_rule :  forall (Spec:funspec) (I:Inv) (r:retasrt) (ri:asrt) (t:tid)\n        (p:asrt) (v:option val),  InfRules Spec I r ri t p (sskip v) p (*done*)*)\n| pfalse_rule: forall Spec  sd I r ri q s pa t, \n                 InfRules Spec sd pa I r ri\n                          Afalse s q t\n| pure_split_rule: forall Spec sd I r ri p q (pu:Prop) s pa t, \n                     (pu -> InfRules Spec sd pa I r ri \n                                     p s q t) -> (InfRules Spec sd pa I r ri \n                                                           (p**[|pu|]) s q t)\n\n| genv_introret_rule :  forall Spec sd I r ri p q  s G pa t, \n                          InfRules Spec sd pa I r ri p s q  t->\n                          InfRules Spec sd pa I (fun v => (Agenv G //\\\\ r v)) ri\n                                   (Agenv G //\\\\ p) s q t\n\n| genv_introexint_rule :  forall Spec sd I r ri p q s G pa t, \n                            InfRules Spec sd pa I r ri p s q t ->\n                            InfRules Spec sd pa I r (Agenv G //\\\\ ri)\n                                     (Agenv G //\\\\ p) s q t\n\n| ret_rule : forall Spec sd  I r p pa t,   \n               (p ==> r None) ->\n               InfRules Spec sd pa I r Afalse p sret Afalse  t(*done*)\n\n\n| iret_rule : forall Spec sd I ri p pa t,  (p ==>  ri ) -> \n                                           InfRules Spec  sd pa I arfalse ri p  (sprim exint ) Afalse  t(*done*)\n                                                    \n| rete_rule :  forall (Spec:funspec) sd I r p e v t pa tid, \n                 (p ==>  r (Some v) //\\\\  Rv e@t == v) ->\n                 InfRules Spec sd pa I r Afalse p (srete e) Afalse tid\n                          \n\n| call_rule :forall f Spec sd I r ri pre post p P el vl logicl tp tl pa t,\n               GoodFrm p ->\n               Spec f = Some (pre, post, (tp, tl)) ->\n               P ==> PRE [pre, vl, logicl, t] ** p ->\n               P ==> Rvl el @ tl == vl ->\n               tl_vl_match tl vl = true ->\n               PRE [pre, vl, logicl, t] ==> CurLINV pa t ->\n               EX v : option val, POST [post, vl, v, logicl, t] ==> CurLINV pa t ->\n                InfRules Spec sd pa I r ri (P) (scall f el) \n                        (EX v,POST[post, vl, v ,logicl,t] ** p ) t (*done*)\n                        \n      | calle_rule :  forall f e l Spec sd  I r ri pre post p P el v' vl logicl tp tl pa t,  \n                        GoodFrm p ->\n                        retpost post ->\n                        Spec f = Some (pre, post, (tp, tl)) ->\n                        P ==> PRE [pre, vl, logicl, t] ** PV l @ tp |-> v' ** p ->\n                        P ==> Rvl el @ tl == vl ->\n                        PV l @ tp |-> v' ** p ==> Lv e @ tp == l ->\n                        tl_vl_match tl vl = true ->\n                        PRE [pre, vl, logicl, t] ==> CurLINV pa t ->\n                        EX v : option val, POST [post, vl, v, logicl, t] ==> CurLINV pa t ->\n                                           InfRules Spec sd pa I r ri ( P)\n                                                    (scalle e f el) (EX v, POST[post, vl, Some v,logicl,t] ** PV l @ tp|-> v ** p )  t(*done*)\n\n      | calle_rule_lvar: forall f x Spec sd t I r ri pre post P p el v' vl logicl tp tl pa tid,  \n                           GoodFrm p ->\n                           retpost post ->\n                           Spec f = Some (pre, post, (tp, tl)) ->\n                           P ==> PRE [pre, vl, logicl, tid] ** LV x @ t |-> v' ** p ->\n                           P ==> Rvl el @ tl == vl ->\n                           tl_vl_match tl vl = true ->\n                           PRE [pre, vl, logicl, tid] ==> CurLINV pa tid ->\n                           EX v : option val, POST [post, vl, v, logicl, tid] ==>\n                                                   CurLINV pa tid ->\n                                              InfRules Spec sd pa I r ri (P )\n                                                       (scalle (evar x) f el) (EX v, POST[post, vl, Some v,logicl,tid] ** LV x @ t |-> v ** p) tid\n\n| conseq_rule : forall   Spec  sd  I r ri p' p q q' s pa t, \n                  (p' ==>  p) ->  (q ==> q') ->\n                  InfRules Spec sd pa I r ri p s q t->\n                  InfRules Spec sd pa I r ri p' s q' t (*done*)\n\n| r_conseq_rule : forall   Spec sd  I r ri r' p q ri' s pa t, \n                    (forall v,r v ==> r' v) ->  (ri ==> ri') ->\n                    InfRules Spec  sd pa I r ri p s q t->\n                    InfRules Spec sd pa I r' ri' p s q t (*done*)\n\n| abscsq_rule_full : forall   Spec sd  I r ri p' p q q' s pa t, \n                       #sd,pa,t ⊢ p'⇒p  -> #sd, pa, t ⊢ q ⇒ q' ->\n                                                    InfRules Spec sd pa I r ri p s q  t->\n                                                    InfRules Spec sd pa I r ri p' s q' t (*done*)\n\n  | seq_rule : forall  Spec sd  I r ri p p' q  s1 s2 pa t, \n                     InfRules Spec sd pa I r ri p s1 p' t -> \n                     InfRules Spec sd pa I r ri p' s2 q t ->\n                     InfRules Spec sd pa I r ri p (sseq s1 s2) q t (*done*)\n                              \n   | if_rule :  forall Spec  sd I r ri p q e tp s1 s2 pa t,\n                     (p ==> EX v , Rv e @ tp ==  v) ->\n                     InfRules Spec sd pa I r ri (p//\\\\ Aistrue e) s1 q t  -> \n                     InfRules Spec sd pa I r ri (p //\\\\ Aisfalse e) s2 q t ->\n                     InfRules Spec sd pa I r ri p (sif e s1 s2) q t (*done*)\n                              \n   | ift_rule :  forall Spec sd  I r ri p q e tp s pa t,\n                      (p ==> EX v , Rv e @ tp ==  v) ->\n                      (p//\\\\ Aisfalse e ==> q) ->\n                      InfRules Spec sd pa I r ri (p//\\\\ Aistrue e) s q t  -> \n                      InfRules Spec  sd pa I r ri p (sifthen e s) q  t(*done*)\n\n\n   | while_rule :  forall Spec sd  I r ri p  e s  tp pa t,  \n                        ( p ==> EX v , Rv e @ tp ==  v) ->\n                        InfRules  Spec sd pa I r ri ( p //\\\\ (Aistrue e)) s p t  -> \n                        InfRules Spec sd pa I r ri p (swhile e s) (p //\\\\ (Aisfalse e)) t   (*done*)\n\n   | frame_rule :  forall Spec sd I p q frm s aop aop' pa t, \n                     GoodI I sd pa ->\n                     GoodStmt' s ->\n                     GoodFrm frm ->\n                     p ==> CurLINV pa t ->\n                     InfRules Spec sd pa I arfalse Afalse ( <|| aop ||> ** p) s ( <|| aop' ||> ** q) t -> \n                     InfRules Spec  sd pa I arfalse Afalse ( <|| aop ||> ** p ** frm ) s (<|| aop' ||> ** q ** frm) t (*done*)\n\n   | frame_rule_all:  forall Spec sd  I r ri p q frm s pa t, \n                        GoodI I sd pa ->\n                        GoodStmt' s ->\n                        GoodFrm frm ->\n                        p ==> CurLINV pa t ->\n                        InfRules  Spec sd pa I r ri p s q t ->\n                        InfRules Spec sd pa I  (fun v =>(r v) ** frm)\n                                 (ri**frm) (p ** frm ) s (q ** frm )  t(*done*)\n\n   | retspec_intro_rule :  forall Spec sd pa I r ri p q s t, \n                                InfRules Spec sd pa I arfalse Afalse p s q t -> \n                                InfRules Spec  sd pa I r  ri p  s q  t (*done*)\n\n   | assign_rule : forall Spec  sd I r ri p e1 e2 l v1 v2 tp1 tp2 aop pa t,  \n                        assign_type_match tp1 tp2 ->  \n                        ((p ** PV l @ tp1|-> v1) ==> Lv e1 @ tp1 == l //\\\\ Rv e2 @ tp2 == v2) ->\n                        (p ** PV l @ tp1 |-> v2 ==> CurLINV pa t) ->\n                        InfRules Spec sd pa I r ri ((<||aop||> ** p ** PV l @ tp1 |-> v1) \n                                                   ) (sassign e1 e2) (<|| aop ||> ** p ** PV l @ tp1 |-> v2 ) t (*done*)\n\n   | encrit1_rule : forall Spec sd I r ri isr is cs i aop pa t  P,\n                         GoodFrm P ->\n                         InfRules Spec sd pa I r ri \n                                  ( <|| aop ||> ** OS[isr, true, is, cs] ** (ATopis i) ** (Apure (i <= INUM)%nat) ** P ) \n                                  (sprim encrit)\n                                  (<||aop||> ** OS[isr, false, is, true::cs] ** (invlth_isr I O i) ** P) t (*done*)\n\n\n   | encrit2_rule :  forall Spec sd  I r ri isr is cs  aop pa t  P,\n                          GoodFrm P ->\n                          InfRules Spec sd pa I r ri \n                                   (<||aop||> ** OS[isr, false, is, cs] ** P) \n                                   (sprim encrit)\n                                   (<||aop||> ** OS[isr, false, is, false::cs] ** P) t\n\n   | excrit1_rule : forall Spec sd  I r ri isr is cs  i aop pa t  P,\n                         GoodFrm P ->\n                         P ==> CurLINV pa t ->\n                         InfRules Spec sd pa I r ri \n                                  (<||aop||> ** OS[isr, false, is, true::cs] ** (ATopis i) ** (invlth_isr I O i) ** P)\n                                  (sprim excrit)\n                                  (<||aop||> ** OS[isr, true,  is, cs] ** P) t\n\n   | excrit2_rule :  forall Spec  sd I r ri isr is cs aop pa t  P,\n                          GoodFrm P ->            \n                          InfRules Spec sd pa I r ri \n                                   (<||aop||> ** OS[isr, false, is, false::cs] ** P)\n                                   (sprim excrit)\n                                   (<||aop||> ** OS[isr, false, is, cs] ** P) t\n                                   \n   | cli1_rule :forall Spec sd  I r ri isr is i aop pa t P,\n                     GoodFrm P ->\n                     InfRules Spec sd pa I r ri \n                              ( <||aop||> ** OS[isr, true, is, nil]  ** (ATopis i) ** (Apure (i <= INUM)%nat) ** P \n                              )\n                              (sprim cli)\n                              (<||aop||> ** OS[isr, false,is, nil] ** (invlth_isr I O i) ** P) t\n                              \n   | cli2_rule : forall Spec  sd I r ri isr is aop pa t  P,\n                      GoodFrm P ->\n                      InfRules Spec sd pa I r ri \n                               (<||aop||> ** OS[isr, false, is, nil] ** P)\n                               (sprim cli)\n                               (<||aop||> ** OS[isr, false, is, nil] ** P) t\n\n   | sti1_rule : forall Spec  sd I r ri isr i is  aop pa t P,  \n                      GoodFrm P ->\n                      P ==> CurLINV pa  t ->\n                      InfRules Spec  sd pa I r ri \n                               (<||aop||> ** OS[isr, false, is, nil] **  (ATopis i) ** (invlth_isr I O i) ** P)   \n                               (sprim sti)\n                               (<||aop||> ** OS[isr, true, is, nil] ** P) t\n\n   | sti2_rule :  forall Spec pa sd I r ri isr is aop t P,  \n                    GoodFrm P ->\n                    InfRules Spec sd pa I r ri \n                             (<||aop||> ** OS[isr, true, is, nil] ** P)\n                             (sprim sti)\n                             (<||aop||> ** OS[isr, true, is, nil] ** P) t\n\n   | switch_rule :  forall  Spec sd lg  I r ri x li   t aop P P'  Px is cs,\n                      GoodFrm Px ->\n                      P ==> P' ** Px ->\n                      P' ==> <|| sched;; aop ||>  ** SWINVt I t ** Ais is ** Acs cs  ->\n                      P' ==> SWPRE_NDEAD sd x t ->\n                      Px ==> LINV li t lg ** Atrue ->\n                      InfRules Spec sd li  I r ri  P  \n                               (sprim (switch x))  (<|| aop ||>  ** SWINVt I t ** Ais is ** Acs cs ** Px) t\n\n   | switchdead_rule :\n       forall  Spec sd lg  I r ri x li   t aop P P'  Px is cs,\n         GoodFrm Px ->\n         P ==> P' ** Px ->\n         P' ==> <|| sched;; aop ||>  ** SWINVt I t ** Ais is ** Acs cs  ->\n         P' ==> SWPRE_DEAD sd x t  ->\n         Px ==> LINV li t lg ** Atrue ->\n         InfRules Spec sd li  I r ri  P  \n                 (sprim (switch x))  Afalse t\n\n                                     \n   | checkis_rule : forall  Spec sd pa I r ri x aop isr is ie cs v t P,\n                         GoodFrm P ->\n                         P ==> CurLINV pa t->\n                         InfRules Spec sd pa I r ri\n                                  (<||aop||> ** OS[isr, ie, is, cs] **  LV x @ Tint32 |-> v **  P) \n                                  (sprim (checkis x))\n                                  (<||aop||> ** OS[isr, ie, is, cs] **  LV x @ Tint32 |-> (is_length is) ** P)  t\n\n   | eoi_ieon_rule  :  forall Spec sd pa I r ri isr is id cs  i aop t  P,  \n                        (0 <= Int.unsigned id < Z.of_nat INUM)%Z ->\n                         i = Z.to_nat (Int.intval id) ->\n                         GoodFrm P ->\n                         P ==> CurLINV pa t ->\n                         isr i = true ->\n                          InfRules Spec sd pa I r ri \n                                     (  <||aop||> ** OS[isr, true, i::is, cs] ** (getinv (I i)) **  P)\n                                     (sprim (eoi id))\n                                     (  <||aop||> ** OS[isrupd isr i false, true, i::is, cs]  ** P) t\n                                     \n   | eoi_ieoff_rule  :  forall Spec sd pa I r ri isr is id  i cs aop t  P,  \n                          (0 <= Int.unsigned id < Z.of_nat INUM)%Z ->\n                          i = Z.to_nat (Int.unsigned id) ->\n                          GoodFrm P ->\n                          InfRules Spec sd pa I r ri \n                                      (<||aop||> ** OS[isr, false, i::is, cs] ** P)\n                                      (sprim (eoi id))\n                                      (<||aop||> ** OS[isrupd isr i false, false, i::is, cs] ** P) t\n\n   | ex_intro_rule : forall Spec sd pa I r ri q s {tp:Type} p t,\n                          (forall v',InfRules Spec sd pa I r ri (p v') s q t) ->\n                          InfRules Spec sd pa I r ri (EX v:tp,p v) s q t\n\n   | disj_rule : forall Spec sd pa I r ri p1 p2 s q t,\n                      InfRules Spec sd pa I r ri p1 s q  t ->\n                      InfRules Spec sd pa I r ri p2 s q t ->\n                      InfRules Spec sd pa I r ri (p1\\\\//p2) s q t\n\n                               \n  | cre_rule :  forall (Spec : funspec) (sd : ossched) \n                           (I : Inv) (r : retasrt) (ri P : asrt) \n                           (aop : spec_code) (tls : TcbMod.map) \n                           (t1 : addrval) (prio : int32) (tls' : TcbMod.map)\n                           (v1 v2 : val) (e1 e2 e3 : expr) (tp1 tp3 : type)\n                           (pa : LocalInv) (t : tid) isr ie is cs,\n                      GoodLInvAsrt pa ->\n                      GoodFrm P ->\n                      joinsig t1 (prio, rdy, Vnull) tls tls'  ->\n                      indom tls t ->\n                      P ==>\n                       Rv e1 @ tp1 == v1 //\\\\\n                       Rv e2 @ Tptr Tvoid == v2 //\\\\\n                       Rv e3 @ tp3 == Vptr t1 //\\\\  CurLINV pa t ->\n                      InfRules Spec sd pa I r ri \n                               (\n                                 <|| spec_crt v1 v2 (Vint32 prio);; aop ||>  ** P **\n                                     pa t1 init_lg  **\n                                     Aabsdata abstcblsid (abstcblist tls) **\n                                     Aabsdata curtid (oscurt t) **\n                                     OS[isr, ie, is, cs]  \n                               ) \n                               (sprim (stkinit e1 e2 e3))\n                               (\n                                 <|| aop ||>   ** P **\n                                     Aabsdata abstcblsid (abstcblist tls') ** \n                                     Aabsdata curtid (oscurt t)  **\n                                     OS[isr, ie, is, cs]\n                               ) t\n\n  | delself_rule : forall pa P  prio st msg tls' tls t e tp  aop r ri sd Spec I isr ie is cs,\n                         GoodLInvAsrt pa ->\n                         GoodFrm P ->\n                         joinsig t (prio, st, msg) tls' tls  ->\n                         P ==>  Rv e @ tp == Vptr t //\\\\  CurLINV pa t ->\n                         InfRules Spec sd pa I r ri \n                                 (\n                                   <|| spec_del  (Vint32 prio);; aop ||>  **\n                                       P ** Aabsdata abstcblsid (abstcblist tls) **\n                                       Aabsdata curtid (oscurt t) **\n                                       OS[isr, ie, is, cs]  \n                                 ) \n                                 (sprim (stkfree e))\n                                 (\n                                   <|| aop ||>  ** P  **\n                                       Aabsdata abstcblsid (abstcblist tls') ** \n                                       Aabsdata curtid (oscurt t) **\n                                       OS[isr, ie, is, cs]  \n                                 ) t\n\n | delother_rule : forall pa P  prio st msg tls' tls t e tp t1 aop r ri sd Spec I isr ie is cs,\n                         GoodLInvAsrt pa ->\n                         GoodFrm P ->\n                         joinsig t1 (prio, st, msg) tls' tls  ->\n                         indom tls t ->\n                         t <> t1 ->\n                         P ==>  Rv e @ tp == Vptr t1 //\\\\  CurLINV pa t ->\n                         InfRules Spec sd pa I r ri \n                                 (\n                                   <|| spec_del  (Vint32 prio);; aop ||>  **\n                                       P ** Aabsdata abstcblsid (abstcblist tls) **\n                                       Aabsdata curtid (oscurt t) **\n                                       OS[isr, ie, is, cs]  \n                                 ) \n                                 (sprim (stkfree e))\n                                 (\n                                   <|| aop ||>  ** P ** (EX lg,  pa t1 lg)  **\n                                       Aabsdata abstcblsid (abstcblist tls') ** \n                                       Aabsdata curtid (oscurt t) **\n                                       OS[isr, ie, is, cs]  \n                                 ) t.\n\nNotation   \" '{|' F , sd , pa , I , r , ri '|}' '|-' t '{{' p '}}' s '{{' q '}}'\" :=\n  (InfRules F sd pa I r ri p s q t) (at level 50). \n\nDefinition EqDom (P : progunit) (F : funspec) : Prop :=\n  forall f, (exists a, P f = Some a) <-> (exists b, F f = Some b).\n\n\nFixpoint getlenvdom  (dl:decllist) : edom :=\n  match dl with\n    |  dnil => nil\n    |  dcons x t dl' => (x,t)::(getlenvdom dl')\n  end. \n\nFixpoint in_decllist (x:var) (dl : decllist) : bool :=\n  match dl with\n    | dnil => false\n    | dcons x' t' dl' => orb (Zeq_bool x x')  (in_decllist x dl')\n  end.\n\n\nFixpoint good_decllist (dl: decllist) : bool :=\n  match dl with\n    | dnil => true\n    | dcons x t dl' => andb ( negb (in_decllist x dl')) (good_decllist dl')\n  end.\n\nFixpoint buildp (dl:decllist) (vl:vallist) :option asrt:=\n  match good_decllist dl with\n    | true =>\n      match dl, vl with\n        | dnil,nil => Some Aemp\n        | dcons x t dl',cons v vl' => match buildp dl' vl' with\n                                        | Some p => Some (Astar (LV x @ t |-> v) p)\n                                        | None => None\n                                      end\n        | dcons x t dl',nil => match buildp dl' nil with\n                                 | Some p => Some (Astar (Aexists (fun (v:val) => \n                                                                     LV x @ t |-> v)) p)\n                                 | None => None\n                               end\n        | _,_ => None\n      end\n    | false => None\n  end.\n\n\nFixpoint buildq (dl:decllist) : option asrt:=\n  if good_decllist dl then\n    match dl with\n      | dnil => Some Aemp\n      | dcons x t dl' => match buildq dl' with\n                           | Some p => Some ( (EX v, LV x @ t|-> v)  ** p )\n                           | None => None\n                         end\n    end\n  else None.\n\n\nFixpoint dl_vl_match (dl:decllist) (vl:vallist) :=\n  match dl with\n    | dnil => match vl with\n                | nil => true\n                | _ => false\n              end\n    | dcons x t dl' => match vl with\n                         | v :: vl' => if type_val_match t v then dl_vl_match dl' vl' else false\n                         | _ => false\n                       end\n  end.\n\n(*\nDefinition BuildPreA (p:progunit) (f:fid) (abs:osapi) (vl:vallist) G:option asrt:= \n    match p f with\n      | Some (t, d1, d2, s) => \n        match dl_vl_match d1 (rev vl) with \n          | true =>\n            match buildp (revlcons d1 d2) vl with\n              | Some p =>Some (Aconj (Agenv G)\n                                     (Aconj \n                                        (Astar (p ** Aie true ** Ais nil ** Acs nil ** Aisr empisr)\n                                               (A_dom_lenv (getlenvdom  (revlcons d1 d2)))) \n                                        (Aop (fst abs (rev vl))))) \n              | _ => None\n            end\n          | false => None\n        end\n      | _ => None\n    end.\n\n\nDefinition BuildRetA (p:progunit) (f:fid) (abs:osapi) (vl:vallist) G:option retasrt:= \n  match p f with\n    | Some (t, d1, d2, s) => match buildq (revlcons d1 d2) with\n                               | Some p =>\n                                 Some\n                                   (fun (v:option val) => \n                                      (Aconj (Agenv G)\n                                             (Aconj (Astar\n                                                       (p** Aie true ** Ais nil ** Acs nil ** Aisr empisr)\n                                                       (A_dom_lenv (getlenvdom  (revlcons d1 d2))))\n                                                    (Aop (spec_done v)))))\n                                       |_ => None\n                                     end\n    | _ => None\n end.\n *)\n\n\n\n\nDefinition BuildPreI (p:progunit) (f:fid) (vl:vallist) (logicl:list logicvar) (fp:fpre) tid : option asrt:= \n  match p f with\n    | Some (t, d1, d2, s) => \n      match dl_vl_match d1 (rev vl) with \n        | true =>\n          match buildp (revlcons d1 d2) vl with\n            | Some p => Some  (p ** (getasrt (fp (rev vl) logicl tid))**\n                                 (A_dom_lenv (getlenvdom  (revlcons d1 d2))))\n            | _ => None\n          end\n        | false => None\n      end\n    | _ => None\n  end.\n\nDefinition BuildRetI (p:progunit) (f:fid) (vl:vallist) (logicl:list logicvar) (fq:fpost) tid :option retasrt:= \n  match p f with\n    | Some (t, d1 , d2,  s) =>\n      match buildq (revlcons d1 d2) with\n        | Some p => Some (fun (v:option val) =>\n                            (p **  (getasrt (fq (rev vl) v logicl tid)) **\n                               (A_dom_lenv (getlenvdom  (revlcons d1 d2)))))\n        | _ => None\n      end\n    | _ => None\n  end.\n\nDefinition lift (q : asrt):  retasrt := fun _ => q.\n\nDefinition WFFunEnv (P:progunit) (FSpec:funspec) (sd:ossched) pa (I:Inv) :Prop:=\n  EqDom P FSpec /\\\n  forall f pre post t tl, FSpec f = Some (pre, post, (t, tl)) -> \n                          exists  d1 d2 s,   P f = Some (t, d1, d2, s)/\\   \n                                             tlmatch tl d1 /\\\n                                             good_decllist (revlcons d1 d2) = true /\\ \n                                             (\n                                               forall vl p r logicl tid,\n                                                 Some p = BuildPreI P f vl logicl pre tid-> \n                                                 Some r = BuildRetI P f vl logicl post tid->\n                                                 InfRules FSpec sd pa I r Afalse p s Afalse tid\n                                             ).\n\n\n\n(*----------------------*)\n\nDefinition EqDomAPI (api:progunit) (aspec:osapispec) :=\n  (forall f, \n     (exists fdef, api f = Some fdef) <-> (exists fspec,aspec f=Some fspec))/\\\n  (forall f fdef fspec,  api f = Some fdef -> aspec f = Some fspec ->\n                         tlmatch (snd (snd fspec)) (snd (fst (fst fdef))) /\\ fst (fst (fst fdef)) = (fst (snd fspec)) ).\n\nDefinition EqDomInt (P:intunit) (intspec:osintspec) :=\n  (forall i,\n     (exists idef, P i = Some idef) <-> (exists absi,intspec i=Some absi)).\n\nDefinition InitAsrt:= osstate -> osabst -> Prop.\n\n\nDefinition retfalse:= fun (v:option val)=> Afalse.\n\nFixpoint dladd (d1 d2 : decllist) : decllist :=\n  match d1 with\n    | dnil => d2\n    | dcons x y d1' => revlcons d1' (dcons x y d2)\n  end.\n\nFixpoint dl_add d1 d2:= \n  match d1 with\n    | dnil => d2\n    | dcons a b d1' => dcons a b (dl_add d1' d2)\n  end.\n\n\n\nDefinition BuildPreA':= \n  fun (p : progunit) (f : fid) (abs : osapi) (vl : vallist)  (pa : LocalInv) t lg=>\n    match p f with\n      | Some (_, d1, d2, _) =>\n        match dl_vl_match d1 (rev vl) with\n          | true =>\n            match buildp (dladd d1 d2) vl with\n              | Some p2 =>\n                Some   \n                  ( ((<|| (fst abs) (rev vl) ||> ** p_local pa t lg ** p2 **Aie true ** Ais nil ** Acs nil ** Aisr empisr) ** A_dom_lenv (getlenvdom (revlcons d1 d2))))\n                  \n              | None => None\n            end\n          |false => None\n        end\n      | None => None\n    end.\n\n\nDefinition BuildRetA':= \n  fun (p : progunit) (f : fid) (_ : osapi) (_ : vallist) (pa : LocalInv) t lg=>\n    match p f with\n      | Some (_, d1, d2, _) =>\n        match buildq (dladd d1 d2) with\n          | Some p2 =>\n            Some\n              (fun v : option val =>\n                 ((  <|| spec_done v ||>  ** p_local pa t lg **p2 **  Aie true ** Ais nil ** Acs nil ** Aisr empisr) **  A_dom_lenv (getlenvdom (revlcons d1 d2))) )\n              \n          | None => None\n        end\n      | None => None\n    end.\n\nInductive APIRule: progunit -> osapispec -> funspec -> ossched -> LocalInv -> Inv  -> list logicvar-> Prop :=\n| api_rule :\n    forall (P:progunit) (apispec:osapispec) (pa : LocalInv) (Spec:funspec) (sd : ossched) (I : Inv) lg,\n      EqDomAPI P apispec ->\n      (\n        forall (f:fid) ab vl p r ft tid, \n          apispec f = Some (ab,ft) ->\n          Some p = BuildPreA' P f (ab,ft) vl pa tid lg->\n          Some r = BuildRetA' P f (ab,ft) vl pa tid lg ->\n          (\n            exists  t d1 d2 s,\n              P f = Some (t, d1, d2, s) /\\\n              InfRules Spec sd pa I r Afalse p s Afalse tid\n          ) \n      ) ->\n      APIRule P apispec Spec sd pa I lg.\n\nInductive InterRule: progunit -> funspec -> ossched -> LocalInv -> Inv  -> Prop :=\n| inter_rule :\n    forall (P : progunit) (FSpec : funspec) (sd : ossched) (I : Inv) pa,\n      EqDom P FSpec ->\n      (forall (f : fid) (pre : fpre) (post : fpost) (t : type) (tl : typelist),\n         FSpec f = Some (pre, post, (t, tl)) ->\n         exists d1 d2 s,\n           P f = Some (t, d1, d2, s) /\\\n           tlmatch tl d1 /\\\n           (forall (vl : vallist) (p : asrt) (r : retasrt) (logicl : list logicvar) tid,\n              Some p = BuildPreI P f vl logicl pre tid->\n              Some r = BuildRetI P f vl logicl post tid->\n              {|FSpec , sd, pa , I, r, Afalse|}|- tid {{p}} s {{Afalse}})) ->\n      InterRule P FSpec sd pa I.\n\n\nDefinition iretasrt' (i:hid) (isrreg:isr) (si:is)  (I:Inv) :asrt:= \n  (Astar (Aop (spec_done None)) \n         (Astar (Aisr (isrupd isrreg i false))\n                (Astar (Ais (cons i si))\n                       (Astar (Acs  nil)\n                              (IRINV I ** A_dom_lenv nil))))).\n\nDefinition ipreasrt' (i:hid) (isrreg:isr) (si:is) (ispec:spec_code) (I:Inv):=\n  (Astar (Aop ispec)\n         (Astar (Aisr (isrupd isrreg i true))\n                (Astar (Ais (cons i si))\n                       (Astar (Acs  nil) \n                              ((Astar (Aie false))  \n                                 (isr_inv ** invlth_noisr I 0%nat i ** A_dom_lenv nil)))))). \n\n\nDefinition BuildintPre (i:nat) i_spec (isrreg:isr) (si:is) (I:Inv) (pintpre:LocalInv) t lg:=\n  match i_spec i with\n    | None => None\n    | Some ispec => Some (ipreasrt' i isrreg si ispec  I ** p_local pintpre t lg)\n  end.\n\nDefinition BuildintRet (i:nat) (i_spec:osintspec) (isrreg:isr) (si:is) (I:Inv) (pa:LocalInv) t lg:=\n  match i_spec i with\n    | None => None\n    | Some ispec => Some (iretasrt' i isrreg si I ** p_local pa  t lg)\n  end.\n\n\nInductive ItrpRule: intunit -> osintspec ->  funspec -> ossched  -> LocalInv  -> Inv  -> Prop :=\n| itrp_rule: forall (P:intunit) (intspec:osintspec) (pa: LocalInv)(Spec:funspec) sd (I:Inv),\n               EqDomInt P intspec ->\n               (\n                 forall i isrreg si p r t  lg,\n                   Some p = BuildintPre i intspec isrreg si I pa t lg->\n                   Some r = BuildintRet i intspec isrreg si I pa t lg->\n                   exists s,\n                     P i = Some s /\\\n                     {|Spec , sd, pa , I, retfalse, r|}|-t {{p}}s {{Afalse}}\n                                                           \n               ) ->\n               ItrpRule P intspec Spec sd pa  I.\n\n\nDefinition eqevntls (env: CltEnvMod.map) (tls:TcbMod.map) :=\n  forall (t:tid), indom env t <-> indom tls t.\n\nDefinition eqisttls (lst:ltaskstset) (tls:TcbMod.map) :=\n  forall (t:tid), indom lst t <-> indom tls t.\n\nDefinition eqdomSO (S : osstate)  (O:osabst) :=\n  match S with\n    | (G,pi,M,isr,lst) =>\n      match get O abstcblsid with\n        | Some (abstcblist tls) => eqevntls pi tls /\\ eqisttls lst tls\n        | _ => False\n      end\n  end.\n\n\nDefinition init_rdy (pa : tid-> list logicvar -> asrt) (t:tid)  lg := pa t lg ** [| GoodLInvAsrt pa |] **  OS [empisr, true, nil , nil ]  ** A_dom_lenv nil.\n\nDefinition init_cur I (pa : tid-> list logicvar -> asrt)  t lg := (INV I) ** (EX tp : type, GV OSTCBCur @ Tptr tp |-r-> Vptr t)  ** init_rdy pa t lg.\n\nInductive initst: osstate -> osabst -> Inv -> LocalInv -> list logicvar -> Prop:=\n| init_O: forall S O G envs M isr lst E auxs I pa t lg,\n            S = ((G,envs,M),isr,lst) ->\n            envs = sig t E ->\n            lst = sig t auxs ->\n            get O curtid = Some (oscurt t) ->\n            (forall ab, sat (((G,E,M),isr,auxs),O,ab) (init_cur I pa t lg)) ->\n            initst S O I pa lg\n| init_S: forall S O G envs envs' M m M' isr lst lst' E auxs I pa t tc lg,\n            S = ((G,envs,M),isr,lst) ->\n            join (sig t E) envs' envs ->\n            join (sig t auxs) lst' lst ->\n            join m M' M ->\n            get O curtid = Some (oscurt tc) ->\n            t <> tc ->\n            (forall ab, sat (((G,E,m),isr,auxs),emp,ab) (init_rdy pa t lg ** A_dom_lenv nil)) ->\n            initst ((G,envs',M'),isr,lst') O I pa lg ->\n            initst S O I pa lg.\n(*\nDefinition side_condition I pa schedmethod init:=\n  (\n    GoodI I schedmethod /\\\n    (forall S O,  init S O ->\n                      (forall o, (projS S tid) = Some o  ->\n                         forall ab, sat ((pair o O),ab) (init_asrt I pa tid )) /\\ eqdomSO S O) \n  ).\n *)\nDefinition side_condition I pa schedmethod init lg:=\n  (\n    GoodI I schedmethod pa /\\\n    (forall S O,  init S O ->\n                  initst S O I pa lg/\\ eqdomSO S O) \n  ).\n\n\n\nInductive TopRule : oscode -> osspec -> InitAsrt -> Prop :=\n| top_rule: forall osc A (init:InitAsrt) (I:Inv) (lasrt: LocalInv )(Spec:funspec) \n                   pa pi ip apispec intspec schedmethod ,\n              osc = (pa,pi,ip) ->\n              A = (apispec,intspec,schedmethod) ->\n              APIRule pa apispec Spec schedmethod lasrt I init_lg ->\n              ItrpRule ip intspec Spec schedmethod lasrt I ->\n              InterRule pi Spec schedmethod lasrt  I ->\n              side_condition I lasrt  schedmethod init init_lg -> \n              TopRule osc A init.\n\n\n(***Abstract Implications when local invariants do not specify high-level states *****)\n\nDefinition  NoAbs (p: LocalInv) := \n  forall  o O t, satp o O  (CurLINV p t) ->\n                 forall O', satp o O'  (CurLINV p t).\n\nDefinition  absimp sc (p p' : asrt) := \n  forall (s : taskst) (O : osabst) (gamma : absop),\n    (s, O, gamma) |= p ->\n    exists O' gamma',\n      hmstepstar sc gamma O gamma' O' /\\ (s, O', gamma') |= p'.\n\nLemma absimp_imp_full:\n  forall sc p p' li t,  \n    absimp sc  p p' -> \n    NoAbs li ->\n    absimplication sc li p p' t.\nProof.          \n  intros.\n  unfolds.\n  intros.\n  destruct H1.\n  apply H in H1.\n  simp join.\n  do 2 eexists; splits; eauto.\nQed.\n\n\nInductive absinfer :  ossched -> asrt -> asrt -> Prop :=\n| absinfer_eq :\n    forall p sc,\n      absinfer sc p p\n               \n| absinfer_trans :\n    forall p q r sc,\n      absinfer sc p q -> absinfer sc q r -> absinfer sc p r\n                                                     \n| absinfer_disj:\n    forall p1 p2 q1 q2 sc,\n      absinfer sc p1 q1 ->\n      absinfer sc p2 q2 ->\n      absinfer sc (p1\\\\//p2) (q1\\\\// q2)\n\n| absinfer_conseq :\n    forall p q p' q' sc, \n      q ==> q' ->\n      absinfer sc p q ->\n      p'==> p -> absinfer sc p' q'\n\n| absinfer_ex :\n    forall  (tp:Type) (p:tp->asrt) q sc,\n      (forall x,absinfer sc (p x) q) -> absinfer sc (EX x:tp,p x) q \n(**                                   \n| absinfer_frm :\n    forall p q r sc,\n     p ==> \n      can_change_aop r ->\n      absinfer sc p q -> absinfer sc (p ** r) (q ** r)\n *)\n                                                 \n| absinfer_prim:\n    forall p q step vl v sc,\n      can_change_aop p ->\n      can_change_aop q ->\n      absimp sc (<||step (|vl|)||> ** p) (<||END v||> ** q)\n      -> absinfer sc (<||step (|vl|)||> ** p) (<||END v||> ** q)\n                  \n| absinfer_seq: forall p q s1 s2 s1' sc,\n                  can_change_aop p ->\n                  can_change_aop q -> \n                  absinfer sc (<||s1||> ** p) (<||s1'||> ** q) ->\n                  absinfer sc (<||s1 ;; s2 ||> **p ) (<||s1';;s2||>**q)\n\n                           \n| absinfer_seq_end: forall p q s v sc,\n                      can_change_aop p ->\n                      can_change_aop q -> \n                      p ==> q ->\n                      absinfer sc (<||END v ;; s ||> **p ) (<||s||> ** q)\n                               \n| absinfer_choice1 :\n    forall p q s1 s2 sc,\n      can_change_aop p ->\n      can_change_aop q -> \n      p ==> q -> \n      absinfer sc (<||s1 ?? s2 ||> ** p) (<||s1||> ** q)\n               \n| absinfer_choice2 :\n    forall p q s1 s2 sc,\n      can_change_aop p ->\n      can_change_aop q -> \n      p ==> q -> \n      absinfer sc (<||s1 ?? s2 ||> ** p ) (<||s2||> ** q)\n               \n|absinfer_assume :\n   forall  p (b:absexpr) q sc,\n     can_change_aop p ->\n     can_change_aop q ->\n     p  ==> q ->\n     (forall s, (s |= p) -> b (getabst s)) ->     \n     absinfer sc (<||ASSUME b||> ** p) (<||END None||> ** q)\n              \n|absinfer_sched :\n   forall  p (b:absexpr) q sc,\n     can_change_aop p ->\n     can_change_aop q ->\n     p  ==> q ->\n     (forall s, (s |= p) -> sched_self sc  (getabst s)) ->     \n     absinfer sc (<||sched||> ** p) (<||END None||> ** q).\n\nNotation \" sc '⊢' p '⇒' q \" := (absinfer sc p q) (at level 80).\n\nLemma  absinfer_imp_full:\n  forall li sc p q t,\n    NoAbs li ->\n    absinfer sc p q ->\n    absinferfull sc li p q t .\nProof.\n  intros.\n  inductions H0.   \n  apply  absinfer_eq'.\n  eapply absinfer_trans'; eauto.\n  eapply absinfer_disj'; eauto.\n  eapply absinfer_conseq'; eauto.\n  eapply absinfer_ex'; eauto.\n  eapply absinfer_prim'; eauto.\n  eapply  absimp_imp_full; eauto.\n  eapply  absinfer_seq'; eauto.\n  eapply absinfer_seq_end'; eauto.\n  eapply absinfer_choice1'; eauto.\n  eapply absinfer_choice2'; eauto.\n  eapply absinfer_assume' ; eauto.\n  eapply absinfer_sched' ; eauto.\nQed.\n\nLemma   abscsq_rule : \n  forall   Spec sd  I r ri p' p q q' s pa t, \n    NoAbs pa ->\n    sd ⊢ p'⇒p  ->  sd  ⊢ q ⇒ q' ->\n    InfRules Spec sd pa I r ri p s q  t->\n    InfRules Spec sd pa I r ri p' s q' t .\nProof.\n  intros.\n  eapply abscsq_rule_full; eauto.\n  eapply absinfer_imp_full; eauto.\n  eapply absinfer_imp_full; eauto.\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/framework/logic/inferules.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2657990824424557}}
{"text": "From VLSM.Lib Require Import Itauto.\nFrom stdpp Require Import prelude finite.\nFrom VLSM.Lib Require Import EquationsExtras.\nFrom VLSM.Lib Require Import Preamble StdppExtras.\nFrom VLSM.Core Require Import VLSM MessageDependencies.\n\n(** * Basic Definitions and Lemmas for UMO, MO and ELMO\n\n  This module contains basic definitions and lemmas needed for the UMO, MO and\n  ELMO protocols. In contrast to the paper, which uses natural numbers,\n  we abstract over the implementation of an [Address] by making it an arbitrary\n  type with decidable equality.\n*)\n\nSection sec_base_ELMO.\n\nContext\n  {Address : Type}\n  `{EqDecision Address}.\n\n(** ** Labels, States, Observations and Messages *)\n\n(** Messages can be labeled as either sent or received. *)\nInductive Label : Type :=\n| Receive\n| Send.\n\nInductive State : Type := MkState\n{\n  obs : list Observation;\n  adr  : Address;\n}\nwith Observation : Type := MkObservation\n{\n  label   : Label;\n  message : Message;\n}\n(** A [Message] is a wrapper for [State]. *)\nwith Message : Type := MkMessage\n{\n  state : State;\n}.\n\n(**\n  [State]s, [Observation]s and [Message]s are printed like ordinary inductive\n  types, using their constructor names, instead of as records with the\n  {| ... |} notation.\n*)\n#[export] Unset Printing Records.\n\n(** Two states are equal when they have equal observations and equal addresses. *)\nLemma eq_State :\n  forall s1 s2 : State,\n    obs s1 = obs s2 -> adr s1 = adr s2 -> s1 = s2.\nProof.\n  by intros [] []; cbn; congruence.\nQed.\n\nLemma eq_Message :\n  forall m1 m2 : Message,\n    obs (state m1) = obs (state m2) -> adr (state m1) = adr (state m2) -> m1 = m2.\nProof.\n  by intros [[]] [[]]; cbn; congruence.\nQed.\n\nLemma eq_Observation :\n  forall ob1 ob2 : Observation,\n    label ob1 = label ob2 -> message ob1 = message ob2 -> ob1 = ob2.\nProof.\n  by intros [] []; cbn; congruence.\nQed.\n\n(** [Label]s, [State]s, [Observation]s and [Message]s have decidable equality. *)\n#[export] Instance EqDecision_Label : EqDecision Label.\nProof. by intros x y; unfold Decision; decide equality. Defined.\n\n#[local] Lemma State_eq_dec : forall x y : State, {x = y} + {x <> y}\nwith Observation_eq_dec : forall x y : Observation, {x = y} + {x <> y}\nwith Message_eq_dec : forall x y : Message, {x = y} + {x <> y}.\nProof.\n  - intros x y; decide equality.\n    + by apply EqDecision0.\n    + by decide equality.\n  - by do 2 decide equality.\n  - by intros x y; decide equality.\nDefined.\n\n#[export] Instance EqDecision_State : EqDecision State := State_eq_dec.\n#[export] Instance EqDecision_Observation : EqDecision Observation := Observation_eq_dec.\n#[export] Instance EqDecision_Message : EqDecision Message := Message_eq_dec.\n\n(** A notion of size for [State]s, [Observation]s and [Message]s. *)\nFixpoint sizeState (s : State) : nat :=\n  1 + fold_right (fun ob sizeObs => sizeObservation ob + sizeObs) 0 (obs s)\n\nwith sizeObservation (ob : Observation) : nat :=\n  1 + sizeMessage (message ob)\n\nwith sizeMessage (msg : Message) : nat :=\n  1 + sizeState (state msg).\n\nLemma sizeObservation_unfold (ob : Observation) :\n  sizeObservation ob = 2 + sizeState (state (message ob)).\nProof. by destruct ob as [? []]. Qed.\n\n(** ** Extending States with new Observations\n\n  We want to abstract over from the \"direction\" of the [list] of [Observation]s,\n  so that we can [cons] new observations at the beginning, whereas in the paper\n  they are [app]ended to the end. We will use the function [addObservation] to\n  extend a state with a new observations and [addObservations] to extend a state\n  with a list of new observations.\n*)\n\nDefinition addObservation' (ob : Observation) (obs : list Observation) : list Observation :=\n  ob :: obs.\n\nLemma addObservation'_ind (P : list Observation -> Prop)\n  (Hempty : P [])\n  (Hadd : forall ob obs, P obs -> P (addObservation' ob obs)) :\n  forall obs, P obs.\nProof.\n  exact (list_ind P Hempty Hadd).\nQed.\n\nLemma addObservation'_rec (P : list Observation -> Set)\n  (Hempty : P [])\n  (Hadd : forall ob obs, P obs -> P (addObservation' ob obs)) :\n  forall obs, P obs.\nProof.\n  exact (list_rec P Hempty Hadd).\nDefined.\n\nLemma addObservation'_rect (P : list Observation -> Type)\n  (Hempty : P [])\n  (Hadd : forall ob obs, P obs -> P (addObservation' ob obs)) :\n  forall obs, P obs.\nProof.\n  exact (list_rect P Hempty Hadd).\nDefined.\n\nDefinition addObservation (ob : Observation) (s : State) : State :=\n  MkState (addObservation' ob (obs s)) (adr s).\n\nNotation \"s <+> ob\" := (addObservation ob s) (left associativity, at level 50).\n\n(**\n  The induction principle [addObservation_ind] considers a [State]\n  as built up using [addObservation] from an initial state.\n*)\nLemma addObservation_ind (P : State -> Prop)\n  (Hempty : forall a, P (MkState [] a))\n  (Hadd : forall ob s, P s -> P (addObservation ob s)) :\n  forall obs, P obs.\nProof.\n  intros [obs a].\n  induction obs using addObservation'_ind; [done |].\n  by apply (Hadd ob) in IHobs.\nQed.\n\nLemma addObservation_rec (P : State -> Set)\n  (Hempty : forall a, P (MkState [] a))\n  (Hadd : forall ob s, P s -> P (s <+> ob)) :\n  forall obs, P obs.\nProof.\n  intros [obs a].\n  induction obs using addObservation'_rec; [done |].\n  by apply (Hadd ob) in IHobs.\nDefined.\n\nLemma addObservation_rect (P : State -> Type)\n  (Hempty : forall a, P (MkState [] a))\n  (Hadd : forall ob s, P s -> P (addObservation ob s)) :\n  forall obs, P obs.\nProof.\n  intros [obs a].\n  induction obs using addObservation'_rect; [done |].\n  by apply (Hadd ob) in IHobs.\nDefined.\n\n(**\n  This induction principle is like [addObservation_ind], but\n  also provides an induction hypothesis for the [State] contained\n  in the message of the added observation.\n*)\nDefinition addObservation_both_ind\n  (P : State -> Prop)\n  (Hinit : forall a, P (MkState [] a))\n  (Hadd : forall [s l ms], P s -> P ms -> P (s <+> MkObservation l (MkMessage ms))) :\n  forall s, P s :=\n  fix rec s :=\n    let '(MkState ol a) := s in\n    let Hcons := fun '(MkObservation _ (MkMessage ms)) _ IHol' => Hadd IHol' (rec ms)\n    in list_ind _ (Hinit a) Hcons ol.\n\n(**\n  A property on [sizeState] of [addObservation].\n  Useful because a [Fixpoint] can't be unfolded unless\n  the argument is in the form of a constructor application.\n*)\nLemma addObservation_size s ob :\n  sizeState (s <+> ob) = sizeState s + sizeObservation ob.\nProof. by destruct s; cbn; lia. Qed.\n\nDefinition addObservations (obs' : list Observation) (s : State) : State :=\n  MkState (obs' ++ (obs s)) (adr s).\n\nNotation \"s <++> obs\" := (addObservations obs s) (left associativity, at level 50).\n\nDefinition addObservationToMessage (ob : Observation) (m : Message) : Message :=\n  MkMessage (state m <+> ob).\n\nNotation \"m <*> ob\" := (addObservationToMessage ob m) (left associativity, at level 50).\n\nDefinition addObservationsToMessage (obs' : list Observation) (m : Message) : Message :=\n  MkMessage (state m <++> obs').\n\nNotation \"m <**> obs\" := (addObservationsToMessage obs m) (left associativity, at level 50).\n\n(** [<+>] is injective in both arguments. *)\nLemma addObservation_inj :\n  forall (ob1 ob2 : Observation) (s1 s2 : State),\n    s1 <+> ob1 = s2 <+> ob2 -> ob1 = ob2 /\\ s1 = s2.\nProof.\n  intros ob1 ob2 s1 s2 [= ->].\n  by split; [| apply eq_State].\nQed.\n\n(** Adding an observation to a state results in a different state. *)\nLemma addObservation_acyclic :\n  forall (ob : Observation) (s : State),\n    s <+> ob <> s.\nProof.\n  intros ob [obs adr] [= Heq].\n  unfold addObservation' in Heq.\n  by apply (app_inv_tail _ [ob] []) in Heq.\nQed.\n\n(** Adding no observations does not change the state. *)\nLemma addObservations_nil :\n  forall s : State,\n    s <++> [] = s.\nProof.\n  by intros [].\nQed.\n\n(**\n  Adding a single observation is compatible with adding many observations at\n  once, in the obvious way.\n*)\nLemma addObservations_app :\n  forall (s : State) (ob : Observation) (obs' : list Observation),\n    s <+> ob <++> obs' = s <++> (obs' ++ [ob]).\nProof.\n  intros s ob obs'.\n  by apply eq_State; cbn; [rewrite <- app_assoc |].\nQed.\n\nLemma addObservation_cons :\n  forall (s : State) (ob : Observation) (obs' : list Observation),\n    s <++> obs' <+> ob = s <++> (ob :: obs').\nProof.\n  intros s ob obs'.\n  by apply eq_State; cbn.\nQed.\n\n(**\n  An observation in [s <+> ob] is either the added observation [ob]\n  or an observation in the original state.\n*)\nLemma elem_of_addObservation :\n  forall (s : State) (ob ob' : Observation),\n    ob' ∈ obs (s <+> ob) <-> ob' = ob \\/ ob' ∈ obs s.\nProof.\n  intros [s_obs a] ob ob'.\n  cbn; unfold addObservation'.\n  by apply elem_of_cons.\nQed.\n\n(**\n  The immediate substate relation. May be used to prove that\n  a [State] does not contain itself.\n*)\nInductive immediate_substate : State -> State -> Prop :=\n| substate_prev : forall s ob, immediate_substate s (s <+> ob)\n| substate_new : forall s ob, immediate_substate (state (message ob)) (s <+> ob).\n\nLemma immediate_substate_wf : wf immediate_substate.\nProof.\n  intro s; induction s using addObservation_both_ind; constructor.\n  - by inversion 1.\n  - by inversion 1; [rewrite (eq_State y s1) | subst y].\nQed.\n\n(** *** Messages sent and received by a State *)\n\nDefinition isSend (ob : Observation) : Prop :=\nmatch label ob with\n| Send => True\n| Receive => False\nend.\n\nDefinition isReceive (ob : Observation) : Prop :=\nmatch label ob with\n| Send => False\n| Receive => True\nend.\n\n#[export] Instance isSend_dec (ob : Observation) : Decision (isSend ob).\nProof.\n  by destruct ob as [[] m]; cbn; typeclasses eauto.\nDefined.\n\n#[export] Instance isReceive_dec (ob : Observation) : Decision (isReceive ob).\nProof.\n  by destruct ob as [[] m]; cbn; typeclasses eauto.\nDefined.\n\nDefinition messages' (obs : list Observation) : list Message :=\n  map message obs.\n\nDefinition messages (st : State) : list Message :=\n  messages' (obs st).\n\nDefinition sentMessages' (obs : list Observation) : list Message :=\n  map message (filter isSend obs).\n\nDefinition sentMessages (st : State) : list Message :=\n  sentMessages' (obs st).\n\nDefinition receivedMessages' (obs : list Observation) : list Message :=\n  map message (filter isReceive obs).\n\nDefinition receivedMessages (st : State) : list Message :=\n  receivedMessages' (obs st).\n\nDefinition receivedAddresses (st : State) : list Address :=\n  map (fun m => adr (state m)) (receivedMessages st).\n\nLemma elem_of_map_filter_addObservation\n  [B] (f : Observation -> B)\n  (P : Observation -> Prop) {P_dec : forall a, Decision (P a)} :\n  forall s ob v,\n    v ∈ map f (filter P (obs (s <+> ob)))\n      <->\n    v = f ob /\\ P ob \\/ v ∈ map f (filter P (obs s)).\nProof.\n  intros s ob v.\n  rewrite !elem_of_list_fmap.\n  setoid_rewrite elem_of_list_filter.\n  cbn; unfold addObservation'.\n  setoid_rewrite elem_of_cons.\n  by split; intros H; decompose [and or ex] H; subst; eauto.\nQed.\n\n(**\n  When a message belongs to the [sentMessages] of some state, then the state\n  contains a corresponding observation which was sent. The converse also holds.\n*)\nLemma elem_of_sentMessages :\n  forall (s : State) (m : Message),\n    m ∈ sentMessages s <-> MkObservation Send m ∈ obs s.\nProof.\n  intros; unfold sentMessages, sentMessages'.\n  rewrite elem_of_list_fmap; setoid_rewrite elem_of_list_filter.\n  split; [| by firstorder].\n  by intros ([[] ?] & -> & []); cbn in *.\nQed.\n\n(**\n  A message in [sentMessages (s <+> ob)] is either in\n  [sentMessages s] or is the message in the new observation [ob],\n  and can only be the message from [ob] if that is a [Send] observation.\n*)\nLemma elem_of_sentMessages_addObservation :\n  forall (s : State) (ob : Observation) (m : Message),\n    m ∈ sentMessages (s <+> ob)\n      <->\n    m = message ob /\\ isSend ob \\/ m ∈ sentMessages s.\nProof.\n  by apply elem_of_map_filter_addObservation.\nQed.\n\nLemma sentMessages_addObservation :\n  forall (s : State) (ob : Observation),\n    sentMessages (s <+> ob)\n      =\n    if decide (isSend ob) then message ob :: sentMessages s else sentMessages s.\nProof.\n  intros s ob.\n  unfold sentMessages, sentMessages'; cbn.\n  by destruct (decide (isSend ob)).\nQed.\n\n(**\n  When a message belongs to the [receivedMessages] of some state, then the state\n  contains a corresponding observation which was received. The converse also holds.\n*)\nLemma elem_of_receivedMessages :\n  forall (s : State) (m : Message),\n    m ∈ receivedMessages s <-> MkObservation Receive m ∈ obs s.\nProof.\n  intros; unfold receivedMessages, receivedMessages'.\n  rewrite elem_of_list_fmap; setoid_rewrite elem_of_list_filter.\n  split; [| by firstorder].\n  by intros ([[] ?] & -> & []); cbn in *.\nQed.\n\n(**\n  A message in [receivedMessages (s <+> ob)] is either in\n  [receivedMessages s] or is the message in the new observation [ob],\n  and can only be the message from [ob] if that is a [Receive] observation.\n*)\nLemma elem_of_receivedMessages_addObservation :\n  forall (s : State) (ob : Observation) (m : Message),\n    m ∈ receivedMessages (s <+> ob)\n      <->\n    m = message ob /\\ isReceive ob \\/ m ∈ receivedMessages s.\nProof.\n  by apply elem_of_map_filter_addObservation.\nQed.\n\nLemma receivedMessages_addObservation :\n  forall (s : State) (ob : Observation),\n    receivedMessages (s <+> ob)\n      =\n    if decide (isReceive ob) then message ob :: receivedMessages s else receivedMessages s.\nProof.\n  intros s ob.\n  unfold receivedMessages, receivedMessages'; cbn.\n  by destruct (decide (isReceive ob)).\nQed.\n\nLemma elem_of_messages :\n  forall (s : State) (m : Message),\n    m ∈ messages s <-> m ∈ sentMessages s \\/ m ∈ receivedMessages s.\nProof.\n  intros; unfold messages, messages'.\n  rewrite elem_of_sentMessages, elem_of_receivedMessages, elem_of_list_fmap.\n  split.\n  - by intros [[[]] [-> Hm]]; auto.\n  - by intros []; (eexists; split; [| eauto]).\nQed.\n\n(**\n  A message in [s <+> ob] is either the message of the added\n  observation [ob] or a message in the original state.\n*)\nLemma elem_of_messages_addObservation :\n  forall (s : State) (ob : Observation) (m : Message),\n    m ∈ messages (s <+> ob) <-> m = message ob \\/ m ∈ messages s.\nProof.\n  by intros; apply elem_of_cons.\nQed.\n\nLemma messages_addObservation :\n  forall (s : State) (ob : Observation),\n    messages (s <+> ob) = message ob :: messages s.\nProof. done. Qed.\n\n(**\n  An address in [receivedAddresses (s <+> ob)] is either in\n  [receivedAddresses s] or is the address from the message in the\n  new observation [ob], and can only be from [ob] if that is\n  a [Receive] observation.\n*)\nLemma elem_of_receivedAddresses :\n  forall (s : State) (ob : Observation) (a : Address),\n    a ∈ receivedAddresses (s <+> ob)\n      <->\n    a = adr (state (message ob)) /\\ isReceive ob \\/ a ∈ receivedAddresses s.\nProof.\n  intros s ob a.\n  unfold receivedAddresses, receivedMessages, receivedMessages'.\n  by rewrite !map_map, elem_of_map_filter_addObservation.\nQed.\n\nLemma receivedAddresses_addObservation :\n  forall (s : State) (ob : Observation),\n    receivedAddresses (s <+> ob)\n      =\n    if decide (isReceive ob)\n    then adr (state (message ob)) :: receivedAddresses s\n    else receivedAddresses s.\nProof.\n  intros s ob.\n  unfold receivedAddresses; cbn.\n  by destruct (decide (isReceive ob)).\nQed.\n\nEnd sec_base_ELMO.\n\nNotation \"s <+> ob\" := (addObservation ob s) (left associativity, at level 50).\nNotation \"s <++> obs\" := (addObservations obs s) (left associativity, at level 50).\nNotation \"m <*> ob\" := (addObservationToMessage ob m) (left associativity, at level 50).\nNotation \"m <**> obs\" := (addObservationsToMessage obs m) (left associativity, at level 50).\n\n(** [ram_state_prop] defines the \"reachable by any means\" or ram states of a VLSM. *)\nDefinition ram_state_prop {message} (V : VLSM message) (s : vstate V) : Prop :=\n  valid_state_prop (pre_loaded_with_all_messages_vlsm V) s.\n\nSection sec_BaseELMO_Observations.\n\nContext\n  {Address : Type}\n  `{EqDecision Address}\n  (State := @State Address)\n  (Observation := @Observation Address)\n  (Message := @Message Address)\n  .\n\n#[export] Instance ELMOComponentType : VLSMType Message :=\n{\n  state := State;\n  label := Label;\n}.\n\n(** We can extract a trace from a [list] of [Observation]s. *)\nFixpoint observations2trace (obs : list Observation) (adr : Address)\n  : list transition_item :=\nmatch obs with\n| [] => []\n| MkObservation Send msg as ob :: obs =>\n    let s'   := MkState obs adr in\n    let msg' := MkMessage s' in\n    let ob'  := MkObservation Send msg' in\n    let obs' := addObservation' ob' obs in\n    let dest := MkState obs' adr in\n      observations2trace obs adr ++ [Build_transition_item Send None dest (Some msg')]\n| MkObservation Receive msg as ob :: obs =>\n    let dest := MkState (ob :: obs) adr in\n      observations2trace obs adr ++ [Build_transition_item Receive (Some msg) dest None]\nend.\n\n(** A state contains a list of observations, so we can extract a trace from a state. *)\nDefinition state2trace (s : State) : list transition_item :=\n  observations2trace (obs s) (adr s).\n\n(** ** Observations and message dependencies *)\n\nLemma obs_sizeState :\n  forall (s : State) (ob : Observation), ob ∈ obs s ->\n    sizeState (state (message ob)) < sizeState s.\nProof.\n  induction s using addObservation_ind; inversion 1; subst.\n  - by destruct ob as [? []]; unfold sizeState; cbn; lia.\n  - etransitivity; [by apply IHs |].\n    by destruct s, ob as [? []]; unfold sizeState; cbn; lia.\nQed.\n\nLemma messages_sizeState :\n  forall (s : State) (m : Message), m ∈ messages s ->\n    sizeState (state m) < sizeState s.\nProof.\n  intros s m Hm.\n  apply elem_of_list_fmap in Hm as (o & -> & Hobs).\n  by apply obs_sizeState.\nQed.\n\nInductive rec_obs : State -> Observation -> Prop :=\n| rec_new :\n    forall (s : State) (ob : Observation),\n      rec_obs (s <+> ob) ob\n| rec_prev :\n    forall (s : State) (ob' ob : Observation),\n      rec_obs s ob -> rec_obs (s <+> ob') ob\n| rec_recv :\n    forall (s : State) (m : Message) (ob : Observation),\n      rec_obs (state m) ob -> rec_obs (s <+> MkObservation Receive m) ob.\n\nEquations rec_obs_fn (s : State) : listset Observation by wf (sizeState s) lt :=\n| {| obs := [] |} => ∅\n| {| obs := o :: os; adr := a |} =>\n  {[ o ]} ∪ rec_obs_fn (state (message o)) ∪ rec_obs_fn {| obs := os; adr := a |}.\nNext Obligation.\nProof. by intros [? []] os a _; unfold sizeState; cbn; lia. Qed.\nNext Obligation.\nProof. by intros [? []] os a _; unfold sizeState; cbn; lia. Qed.\n\nLemma elem_of_rec_obs_fn_1 :\n  forall (s : State) (o : Observation),\n    rec_obs s o -> o ∈ rec_obs_fn s.\nProof.\n  intro s; apply_funelim (rec_obs_fn s); clear s; [by inversion 1 |].\n  by intros [] os a Hindm Hindos o; inversion 1 as [[] ? | [] ? | [] ?]; subst;\n    cbn in *; unfold Observation; rewrite !elem_of_union, ?elem_of_singleton; itauto.\nQed.\n\nLemma rec_obs_fn_sizeState :\n  forall (s : State) (o : Observation), o ∈ rec_obs_fn s ->\n    sizeState (state (message o)) < sizeState s.\nProof.\n  intro s; apply_funelim (rec_obs_fn s); clear s;\n    [intros * Ho; contradict Ho; apply not_elem_of_empty |].\n  intros o os a Hindo Hindos o0; rewrite !elem_of_union; intros [[Heq | Ho] | Hos].\n  - apply elem_of_singleton in Heq as ->.\n    by unfold sizeState; destruct o as [? []]; cbn; lia.\n  - transitivity (sizeState (state (message o))); [by apply Hindo |].\n    by unfold sizeState; destruct o as [? []]; cbn; lia.\n  - transitivity (sizeState (MkState os a)); [by apply Hindos |].\n    by unfold sizeState; destruct o as [? []]; cbn; lia.\nQed.\n\nDefinition Message_dependencies (m : Message) : listset Message :=\n  list_to_set (map message (obs (state m))).\n\nDefinition Message_full_dependencies (m : Message) : listset Message :=\n  fin_sets.set_map message (rec_obs_fn (state m)).\n\nLemma Message_full_dependencies_sizeState (dm m : Message) :\n  dm ∈ Message_full_dependencies m -> sizeState (state dm) < sizeState (state m).\nProof.\n  unfold Message_full_dependencies; intro Hdm.\n  apply elem_of_map in Hdm as (o & -> & Ho).\n  by apply rec_obs_fn_sizeState.\nQed.\n\n#[export] Instance Message_FullMessageDependencies :\n  FullMessageDependencies Message_dependencies Message_full_dependencies.\nProof.\n  constructor; cycle 1.\n  - by intros m Hm; apply Message_full_dependencies_sizeState in Hm; lia.\n  - intros dm [s]; revert dm; unfold Message_full_dependencies; cbn.\n    apply_funelim (rec_obs_fn s);\n      [intros adr dm; split | intros [l m] os a Hindm Hindos dm; split].\n    + by rewrite set_map_empty, elem_of_empty.\n    + rewrite msg_dep_happens_before_iff_one; unfold msg_dep_rel; cbn.\n      rewrite set_map_empty; setoid_rewrite elem_of_empty.\n      by firstorder.\n    + intros Hdm; apply elem_of_map in Hdm as (o & -> & Hdm).\n      unfold Message in Hdm; rewrite !elem_of_union, !elem_of_singleton in Hdm; cbn in Hdm.\n      destruct Hdm as [[-> | Hm] | Hos].\n      * apply msg_dep_happens_before_iff_one; left.\n        unfold msg_dep_rel, compose; cbn; unfold Message.\n        by rewrite elem_of_union, elem_of_singleton; left.\n      * transitivity m; cbn in *.\n        -- by destruct m; apply Hindm, elem_of_map; cbn; eexists; split.\n        -- apply msg_dep_happens_before_iff_one; left.\n           unfold msg_dep_rel, compose; cbn; unfold Message.\n           by rewrite elem_of_union, elem_of_singleton; left.\n      * assert (Hmos : message o ∈@{listset Message} set_map message (rec_obs_fn (MkState os a)))\n          by (apply elem_of_map; eexists; split; done).\n        apply Hindos in Hmos.\n        cut (forall dm,\n              msg_dep_rel Message_dependencies\n                dm (MkMessage (MkState os a)) ->\n              msg_dep_rel Message_dependencies\n                dm (MkMessage (MkState (MkObservation l m :: os) a))).\n        {\n          intro Hext; apply msg_dep_happens_before_iff_one.\n          apply msg_dep_happens_before_iff_one in Hmos as [Hdep | (dm & Hhb & Hdep)].\n          - by left; apply Hext.\n          - by right; eexists; split; [| apply Hext].\n        }\n        unfold msg_dep_rel; cbn.\n        by intros dm; rewrite elem_of_union; right.\n    + intros Hb; apply elem_of_map.\n      do 2 setoid_rewrite elem_of_union; setoid_rewrite elem_of_singleton; cbn.\n      apply msg_dep_happens_before_iff_one in Hb.\n      unfold msg_dep_rel, compose in Hb; cbn in Hb; unfold Message in Hb.\n      setoid_rewrite elem_of_union in Hb;\n        setoid_rewrite elem_of_singleton in Hb.\n      destruct Hb as [[-> | Hdm] | Hos].\n      * by eexists; split; [| by left; left].\n      * cut (msg_dep_happens_before Message_dependencies dm (MkMessage (MkState os a))).\n        {\n          intro Hb; apply Hindos, elem_of_map in Hb as (y & -> & Hy).\n          by eexists; split; [| right].\n        }\n        by apply msg_dep_happens_before_iff_one; left.\n      * destruct Hos as (y & Hb & [-> | Hos]).\n        -- destruct m as [state_m].\n           apply Hindm, elem_of_map in Hb as (y & -> & Hy).\n           by eexists; split; [| left; right].\n        -- cut (msg_dep_happens_before Message_dependencies dm\n                (MkMessage (MkState os a))).\n           {\n             intros (z & -> & Hz)%Hindos%elem_of_map.\n             by eexists; split; [| right].\n           }\n           transitivity y; [done |].\n           by apply msg_dep_happens_before_iff_one; left.\nQed.\n\nDefinition Message_sender (m : Message) : option Address :=\n  Some (adr (state m)).\n\nContext\n  `{finite.Finite index}\n  `{Inhabited index}\n  (idx : index -> Address)\n  `{!Inj (=) (=) idx}\n  .\n\nDefinition ELMO_A (a : Address) : index :=\n  hd inhabitant (filter (fun i => idx i = a) (enum index)).\n\nLemma ELMO_A_inv : forall i, ELMO_A (idx i) = i.\nProof.\n  intro i; unfold ELMO_A; cbn.\n  replace (filter _ _) with [i]; [done |].\n  generalize (enum index), (NoDup_enum index) as Hnodup, (elem_of_enum i) as Hi.\n  induction l; intros; [by inversion Hi |].\n  inversion Hnodup; subst.\n  assert (Hnil : forall i, i ∉ l -> filter (fun i0 : index => idx i0 = idx i) l = []).\n  {\n    intros; apply Forall_filter_nil, Forall_forall.\n    intros j Hj; contradict Hj.\n    by eapply inj in Hj; [| done]; subst.\n  }\n  inversion Hi; subst; cbn.\n  - by rewrite decide_True, Hnil.\n  - rewrite decide_False, IHl; [done.. |].\n    by intro Hcontra; eapply inj in Hcontra; [| done]; subst.\nQed.\n\nEnd sec_BaseELMO_Observations.\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/BaseELMO.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2657990707454105}}
{"text": "(*\n * Notations_rewrites.v\n *\n * Rewriting rules useful for Notation definitions\n *)\nRequire Import Kami.AllNotations.\nRequire Import List.\nImport ListNotations.\nRequire Import Kami.Notations.\n\nLemma app_rewrite1: forall T (a:T) b c, (a::b)++c=a::(b++c).\nProof.\n  simpl.\n  intros.\n  reflexivity.\nQed.\n\nLemma Registers1: forall a b, Registers (a::b) = (MERegister a)::(Registers b).\nProof.\n  intros.\n  simpl Registers.\n  reflexivity.\nQed.\n\nLemma Registers2: Registers []=[].\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nLemma Registers_dist_append : forall l1 l2, Registers (l1++l2)=(Registers l1)++(Registers l2).\nProof.\n  intros.\n  induction l1.\n  + simpl.\n    reflexivity.\n  + simpl.\n    rewrite IHl1.\n    reflexivity.\nQed.\n\nHint Rewrite Registers_dist_append : kami_rewrite_db.\n\nLemma app_rewrite2: forall A (f:A) (r:list A), [f]++r=f::r.\n  Proof. reflexivity. Qed.\n\nHint Rewrite app_rewrite1 app_rewrite2 app_nil_l app_nil_r Registers1 Registers2 : kami_rewrite_db.\nHint Rewrite Registers1 Registers2 : kami_rewrite_db.\n\nLemma makeModule_rules_Registers: forall l, makeModule_rules (Registers l)=[].\nProof.\n  intros.\n  induction l.\n  + simpl.\n    reflexivity.\n  + simpl.\n    rewrite IHl.\n    simpl.\n    reflexivity.\nQed.\n \nLemma makeModule_rules_append: forall l1 l2, (makeModule_rules (l1++l2))=(makeModule_rules l1)++(makeModule_rules l2).\nProof.\n  intros.\n  induction l1.\n  + simpl.\n    reflexivity.\n  + simpl.\n    rewrite IHl1.\n    destruct a; reflexivity.\nQed.\n\nLemma makeModule_rules_MERegister: forall a b, makeModule_rules ((MERegister a)::b)=makeModule_rules b.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nLemma makeModule_rules_MERule: forall a b, makeModule_rules ((MERule a)::b)=a::(makeModule_rules b).\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nLemma makeModule_rules_nil: makeModule_rules []=[].\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nHint Rewrite makeModule_rules_Registers makeModule_rules_append makeModule_rules_MERegister makeModule_rules_MERule makeModule_rules_nil : kami_rewrite_db.\n \nLemma makeModule_meths_Registers: forall l, makeModule_meths (Registers l)=[].\nProof.\n  intros.\n  induction l.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite IHl.\n  simpl.\n  reflexivity.\nQed.\n \nLemma makeModule_meths_append: forall l1 l2, makeModule_meths (l1++l2)=(makeModule_meths l1)++(makeModule_meths l2).\nProof.\n  intros.\n  induction l1.\n  + simpl.\n    reflexivity.\n  + simpl.\n    rewrite IHl1.\n    destruct a; reflexivity.\nQed.\n\nLemma makeModule_meths_MERegister: forall a b, makeModule_meths ((MERegister a)::b)=makeModule_meths b.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nLemma makeModule_meths_MERule: forall a b, makeModule_meths ((MERule a)::b)=(makeModule_meths b).\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nLemma makeModule_meths_nil: makeModule_meths []=[].\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nHint Rewrite makeModule_meths_Registers makeModule_meths_append makeModule_meths_MERegister makeModule_meths_MERule makeModule_meths_nil : kami_rewrite_db.\n\n \nLemma makeModule_regs_Registers: forall l, makeModule_regs (Registers l)=l.\nProof.\n  intros.\n  induction l.\n  + simpl.\n    reflexivity.\n  + simpl.\n    rewrite IHl.\n    simpl.\n    reflexivity.\nQed.\n \nLemma makeModule_regs_append: forall l1 l2, makeModule_regs (l1++l2)=(makeModule_regs l1)++(makeModule_regs l2).\nProof.\n  intros.\n  induction l1.\n  + simpl.\n    reflexivity.\n  + simpl.\n    rewrite IHl1.\n    destruct a; reflexivity.\nQed.\n\n\nLemma makeModule_regs_MERegister: forall a b, makeModule_regs ((MERegister a)::b)=a::(makeModule_regs b).\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nLemma makeModule_regs_MERule: forall a b, makeModule_regs ((MERule a)::b)=makeModule_regs b.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nLemma makeModule_regs_nil: makeModule_regs []=[].\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nHint Rewrite makeModule_regs_Registers makeModule_regs_append makeModule_regs_MERegister makeModule_regs_MERule makeModule_regs_nil : kami_rewrite_db.\n\nLemma map1: forall T R (f: T -> R) (h:T) t, List.map f (h::t)=(f h)::(List.map f t).\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nLemma fold_right1: forall A B (f : B -> A -> A) (a0 : A) (h : B) (t : list B), List.fold_right f a0 (h::t)=f h (List.fold_right f a0 t).\nProof.\n  intros.\n  simpl.\n  reflexivity.\nQed.\n\nLemma getAllRegisters_fold_right_ConcatMod : forall (b: Mod) (l:list Mod), getAllRegisters (List.fold_right ConcatMod b l)=(concat (List.map getAllRegisters l))++(getAllRegisters b).\nProof.\n    induction l.\n    + simpl.\n      reflexivity.\n    + simpl.\n      rewrite IHl.\n      rewrite app_assoc.\n      reflexivity.\nQed.\n\nLemma getAllMethods_fold_right_ConcatMod : forall (b: Mod) (l:list Mod), getAllMethods (List.fold_right ConcatMod b l)=(concat (List.map getAllMethods l))++(getAllMethods b).\nProof.\n    induction l.\n    + simpl.\n      reflexivity.\n    + simpl.\n      rewrite IHl.\n      rewrite app_assoc.\n      reflexivity.\nQed.\n\nLemma getAllRules_fold_right_ConcatMod : forall (b: Mod) (l:list Mod), getAllRules (List.fold_right ConcatMod b l)=(concat (List.map getAllRules l))++(getAllRules b).\nProof.\n    induction l.\n    + simpl.\n      reflexivity.\n    + simpl.\n      rewrite IHl.\n      rewrite app_assoc.\n      reflexivity.\nQed.\n\nLemma getAllRules_ConcatMod : forall a b, getAllRules (ConcatMod a b)=getAllRules a++getAllRules b.\nProof.\n  intros.\n  simpl.\n  reflexivity.\nQed.\n\nLemma getAllMethods_ConcatMod : forall a b, getAllMethods (ConcatMod a b)=getAllMethods a++getAllMethods b.\nProof.\n  intros.\n  simpl.\n  reflexivity.\nQed.\n\n(*\nLemma getCallsWithSignPerRule_append: forall T a b, getCallsWithSignPerRule (a++b)=getCallsWithSignPerRule a++getCallsWithSignPerRule b.\nProof.*)\n\nLemma getCallsPerMod_ConcatMod : forall a b, getCallsPerMod (ConcatMod a b)=(getCallsPerMod a)++(getCallsPerMod b).\nProof.\n  unfold getCallsPerMod.\n  simpl.\n  intros.\n  rewrite map_app.\n  reflexivity.\nQed.\n\nLemma getCallsPerMod_BaseRegFile: forall m,\n  getCallsPerMod (Base (BaseRegFile m)) = [].\nProof.\n  intros.\n  unfold getCallsPerMod.\n  unfold getCallsWithSignPerMod.\n  simpl.\n  unfold getRegFileMethods.\n  destruct m.\n  destruct rfRead.\n  + simpl.\n    unfold getCallsWithSignPerMeth.\n    destruct rfIsWrMask.\n    - simpl.\n      unfold readRegFile.\n      induction reads.\n      * reflexivity.\n      * simpl.\n        rewrite IHreads.\n        reflexivity.\n    - simpl.\n      unfold readRegFile.\n      induction reads.\n      * reflexivity.\n      * simpl.\n        rewrite IHreads.\n        reflexivity.\n  + simpl.\n    unfold getCallsWithSignPerMeth.\n    simpl.\n    unfold readSyncRegFile.\n    destruct rfIsWrMask.\n    simpl.\n    destruct isAddr.\n    * simpl.\n      induction reads.\n      -- reflexivity.\n      -- simpl.\n         rewrite map_app in IHreads.\n         rewrite map_app.\n         rewrite map_cons.\n         simpl.\n         rewrite concat_app in IHreads.\n         rewrite concat_app.\n         rewrite concat_cons.\n         rewrite app_nil_l.\n         rewrite IHreads.\n         reflexivity.\n    * simpl.\n      induction reads.\n      -- reflexivity.\n      -- simpl.\n         rewrite map_app in IHreads.\n         rewrite map_app.\n         rewrite map_cons.\n         simpl.\n         rewrite concat_app in IHreads.\n         rewrite concat_app.\n         rewrite concat_cons.\n         rewrite app_nil_l.\n         rewrite IHreads.\n         reflexivity.\n    * simpl.\n      destruct isAddr.\n      -- simpl.\n         induction reads.\n         ++ reflexivity.\n         ++ simpl.\n            rewrite map_app in IHreads.\n            rewrite map_app.\n            rewrite map_cons.\n            simpl.\n            rewrite concat_app in IHreads.\n            rewrite concat_app.\n            rewrite concat_cons.\n            rewrite app_nil_l.\n            rewrite IHreads.\n            reflexivity.\n      -- simpl.\n         induction reads.\n         ++ reflexivity.\n         ++ simpl.\n            rewrite map_app in IHreads.\n            rewrite map_app.\n            rewrite map_cons.\n            simpl.\n            rewrite concat_app in IHreads.\n            rewrite concat_app.\n            rewrite concat_cons.\n            rewrite app_nil_l.\n            rewrite IHreads.\n            reflexivity.\nQed.\n\n  Lemma getCallsPerMod_Base: forall (m : BaseModule), getCallsPerMod (Base m)=List.map fst (getCallsWithSignPerMod m).\n  Proof.\n    unfold getCallsPerMod.\n    reflexivity.\n  Qed.\n\nLemma map_getCallsPerMod_map_BaseRegFile: forall l,\n  (concat (List.map getCallsPerMod\n     (List.map (fun m : RegFileBase => (Base (BaseRegFile m))) l)))=[].\nProof.\n  intros.\n  induction l.\n  + reflexivity.\n  + simpl.\n    rewrite IHl.\n    rewrite app_nil_r.\n    rewrite getCallsPerMod_BaseRegFile.\n    reflexivity.\nQed.\n\n  Lemma getCallsPerMod_fold_right_ConcatMod: forall (a:Mod) (l:list Mod), getCallsPerMod (List.fold_right ConcatMod a l)=concat (List.map getCallsPerMod l)++(getCallsPerMod a).\n  Proof.\n    intros.\n    induction l.\n    + reflexivity.\n    + simpl.\n      rewrite <- app_assoc.\n      rewrite <- IHl.\n      rewrite getCallsPerMod_ConcatMod.\n      reflexivity. \nQed.\n \n  Hint Rewrite map1 fold_right1 getAllRules_ConcatMod getAllMethods_ConcatMod getCallsPerMod_ConcatMod map_getCallsPerMod_map_BaseRegFile : kami_rewrite_db.\n  Hint Rewrite getCallsPerMod_fold_right_ConcatMod getCallsPerMod_BaseRegFile : kami_rewrite_db.\n\n  Theorem getAllRegisters_ConcatMod: forall a b, getAllRegisters (ConcatMod a b)=getAllRegisters(a)++getAllRegisters(b).\n  Proof.\n     reflexivity.\n  Qed.\n\n  (*Axiom EquivThenEqual: prop_extensionality.\n\n  Theorem equiv_rewrite: forall x y, (x=y)=(x<->y).\n  Proof.\n    intros.\n    apply EquivThenEqual.\n    split.\n    + intros.\n      subst.\n      split.\n      - intros.\n        apply H.\n      - intros.\n        apply H.\n    + intros.\n      inversion H; subst; clear H.\n      apply EquivThenEqual.\n      split.\n      - apply H0.\n      - apply H1.\n  Qed.*)\n\n  Theorem DisjKey_Cons1:\n    forall T Q (a:(T*Q)) x z (W:forall (a1:T) (a2:T), {a1=a2}+{a1<>a2}),\n           DisjKey (a::x) z <-> ((~(List.In (fst a) (List.map fst z))) /\\ DisjKey x z).\n  Proof.\n    intros.\n    rewrite ?DisjKeyWeak_same.\n    split.\n    + intros.\n      split.\n      - unfold DisjKeyWeak in H.\n        assert (List.In (fst a) (List.map fst (a::x)) -> List.In (fst a) (List.map fst z) -> False).\n        apply H.\n        intro X.\n        apply H0.\n        simpl.\n        left.\n        reflexivity.\n        apply X.\n      - simpl.\n        intros.\n        unfold DisjKeyWeak in H.\n        unfold DisjKeyWeak.\n        intros.\n        assert (List.In k (List.map fst (a::x)) -> List.In k (List.map fst z) -> False).\n        apply H.\n        apply H2.\n        simpl.\n        right.\n        apply H0.\n        apply H1.\n    + intros.\n      inversion H; subst; clear H.\n      unfold DisjKeyWeak.\n      unfold DisjKeyWeak in H1.\n      intros.\n      assert (List.In k (List.map fst x) -> List.In k (List.map fst z) -> False).\n      apply H1.\n      simpl in H.\n      inversion H;subst;clear H.\n      - apply H0.\n        apply H2.\n      - apply H3.\n        apply H4.\n        apply H2.\n    + apply W.\n    + apply W.\nQed.\n\nTheorem DisjKey_Cons2:\n    forall T Q (a:(T*Q)) x z (W:forall (a1:T) (a2:T), {a1=a2}+{a1<>a2}),\n           DisjKey x (a::z) <-> ((~(List.In (fst a) (List.map fst x))) /\\ DisjKey x z).\nProof.\n    intros.\n    rewrite ?DisjKeyWeak_same.\n    split.\n    + intros.\n      split.\n      - intros.\n        unfold DisjKeyWeak in H.\n        assert (List.In (fst a) (List.map fst x) -> List.In (fst a) (List.map fst (a::z)) -> False).\n        apply H.\n        intro X.\n        apply H0.\n        apply X.\n        simpl.\n        left.\n        reflexivity.\n      - simpl.\n        intros.\n        unfold DisjKeyWeak in H.\n        unfold DisjKeyWeak.\n        intros.\n        assert (List.In k (List.map fst x) -> List.In k (List.map fst (a::z)) -> False).\n        apply H.\n        apply H2.\n        apply H0.\n        simpl.\n        right.\n        apply H1.\n    + intros.\n      inversion H; subst; clear H.\n      unfold DisjKeyWeak.\n      unfold DisjKeyWeak in H1.\n      intros.\n      inversion H2;subst;clear H2.\n      - apply H0 in H.\n        inversion H.\n      - assert (List.In k (List.map fst x) -> List.In k (List.map fst z) -> False).\n        apply H1.\n        apply H2.\n        apply H.\n        apply H3.\n    +  apply W.\n    + apply W.\nQed.\n\nTheorem DisjKey_Append1:\n  forall T Q (x:list (T*Q)) y z (W:forall (a1:T) (a2:T), {a1=a2}+{a1<>a2}),\n  DisjKey (x++y) z<->(DisjKey x z /\\ DisjKey y z).\n  Proof.\n    intros.\n    rewrite ?DisjKeyWeak_same.\n    induction x.\n    + simpl.\n      unfold DisjKeyWeak.\n      simpl.\n      split.\n      - intros.\n        * split.\n          tauto.\n          apply H.\n      - intros.\n        inversion H. subst. clear H.\n        eapply H3.\n        apply H0.\n        apply H1.\n    + simpl.\n      repeat (rewrite <- DisjKeyWeak_same).\n      rewrite ?DisjKey_Cons1.\n      rewrite ?DisjKeyWeak_same.\n      split.\n      - intros.\n        inversion H; subst; clear H.\n        split.\n        * split.\n          ++ apply H0.\n          ++ rewrite IHx in H1.\n             inversion H1; subst; clear H1.\n             apply H.\n        * rewrite IHx in H1.\n          inversion H1; subst; clear H1.\n          apply H2.\n      - simpl.\n        intros.\n        inversion H; subst; clear H.\n        split.\n        * inversion H0; subst; clear H0.\n          apply H.\n        * simpl.\n          rewrite IHx.\n          split.\n          ++ inversion H0; subst; clear H0.\n             apply H2.\n          ++ simpl.\n             apply H1.\n      - apply W.\n      - apply W.\n      - apply W.\n      - apply W.\n      - apply W.\n      - apply W.\n      - apply W.\n      - apply W.\n    + apply W.\n    + apply W.\n    + apply W.\nQed.\n\n  Theorem DisjKey_Append2:\n    forall T Q (x:list (T*Q)) y z (W:forall (a1:T) (a2:T), {a1=a2}+{a1<>a2}),\n           DisjKey x (y++z)<->(DisjKey x y /\\ DisjKey x z).\n  Proof.\n    intros.\n    rewrite ?DisjKeyWeak_same.\n    induction y.\n    + simpl.\n      unfold DisjKeyWeak.\n      split.\n      - intros.\n        tauto.\n      - simpl.\n        intros.\n        inversion H; subst; clear H.\n        assert (List.In k (List.map fst x) -> List.In k (List.map fst z) -> False).\n        apply H3.\n        apply H.\n        apply H0.\n        apply H1.\n    + simpl.\n      repeat (rewrite <- DisjKeyWeak_same).\n      rewrite ?DisjKey_Cons2.\n      rewrite ?DisjKeyWeak_same.\n      split.\n      - intros.\n        inversion H; subst; clear H.\n        * split.\n          ++ split.\n             -- apply H0.\n             -- apply IHy in H1.\n                inversion H1; subst; clear H1.\n                apply H.\n          ++ apply IHy in H1.\n             inversion H1; subst; clear H1.\n             apply H2.\n      - intros.\n        inversion H; subst; clear H.\n        inversion H0; subst; clear H0.\n        split.\n        * apply H.\n        * apply IHy.\n          split.\n          ++ apply H2.\n          ++ apply H1.\n      - apply W.\n      - apply W.\n      - apply W.\n      - apply W.\n      - apply W.\n      - apply W.\n      - apply W.\n      - apply W.\n    + apply W.\n    + apply W.\n    + apply W.\n  Qed.\n\n  Theorem DisjKey_In_map2:\n    forall A B a (k:A) r l (W:forall (a1:A) (a2:A), {a1=a2}+{a1<>a2}), @DisjKey A B a ((k,r)::l)<->(~List.In k (List.map fst a) /\\ (DisjKey a l)).\n  Proof.\n    intros.\n    rewrite DisjKey_Cons2.\n    simpl.\n    reflexivity.\n    apply W.\n  Qed.\n    \n  Theorem DisjKey_In_map1: forall A B b (k:A) r l (W:forall (a1:A) (a2:A), {a1=a2}+{a1<>a2}),\n                           @DisjKey A B ((k,r)::l) b<->(~List.In k (List.map fst b) /\\ (DisjKey l b)).\n  Proof.\n    intros.\n    rewrite DisjKey_Cons1.\n    simpl.\n    reflexivity.\n    apply W.\n  Qed.\n\n  Theorem DisjKey_In_map_fst2: forall A B a (f:(A*B)) l (W:forall (a1:A) (a2:A), {a1=a2}+{a1<>a2}),\n                               @DisjKey A B a (f::l)<->(~List.In (fst f) (List.map fst a) /\\ (DisjKey a l)).\n  Proof.\n    intros.\n    rewrite DisjKey_Cons2.\n    reflexivity.\n    apply W.\n  Qed.\n\n    \n  Theorem DisjKey_In_map_fst1: forall A B b (f:(A*B)) l (W:forall (a1:A) (a2:A), {a1=a2}+{a1<>a2}),\n          @DisjKey A B (f::l) b<->(~List.In (fst f) (List.map fst b) /\\ (DisjKey l b)).\n  Proof.\n    intros.\n    rewrite DisjKey_Cons1.\n    reflexivity.\n    apply W.\n  Qed.\n\n  Theorem map_getAllRegisters_map_RegFileBase: forall m,\n    (List.map getAllRegisters (List.map (fun mm: RegFileBase =>  (Base (BaseRegFile mm))) m))=\n        (List.map (fun mm: RegFileBase => getRegFileRegisters mm) m).\n  Proof.\n      induction m.\n      + reflexivity.\n      + simpl.\n        rewrite IHm.\n        reflexivity.\n  Qed.\n\n  Theorem map_getAllMethods_map_RegFileBase: forall m,\n    (List.map getAllMethods (List.map (fun mm: RegFileBase =>  (Base (BaseRegFile mm))) m))=\n        (List.map (fun mm: RegFileBase => getRegFileMethods mm) m).\n  Proof.\n      induction m.\n      + reflexivity.\n      + simpl.\n        rewrite IHm.\n        reflexivity.\n  Qed.\n\n  Theorem concat_map_getAllRules_map_RegFileBase: forall m,\n    (concat (List.map getAllRules (List.map (fun mm: RegFileBase =>  (Base (BaseRegFile mm))) m))) = List.nil.\n  Proof.\n      induction m.\n      + reflexivity.\n      + simpl.\n        rewrite IHm.\n        reflexivity.\n  Qed.\n\n  Hint Rewrite getAllRegisters_fold_right_ConcatMod getAllMethods_fold_right_ConcatMod\n       getAllRules_fold_right_ConcatMod\n       concat_map_getAllRules_map_RegFileBase\n       map_getAllMethods_map_RegFileBase map_getAllRegisters_map_RegFileBase : kami_rewrite_db.\n  Hint Rewrite getAllRegisters_ConcatMod DisjKey_Append1 DisjKey_Append2 DisjKey_In_map2 DisjKey_In_map1 : kami_rewrite_db.\n  Hint Rewrite DisjKey_In_map_fst2 DisjKey_In_map_fst1: kami_rewrite_db.\n\n  Theorem getAllRegisters_BaseMod: forall regs rules dms,\n      getAllRegisters (BaseMod regs rules dms)=regs.\n  Proof.\n      simpl.\n      reflexivity.\n  Qed.\n  \n  Theorem append_equal_prefix: forall T (a: list T) (b: list T) (c: list T), (a++b=a++c)->(b=c).\n  Proof.\n    intros.\n    induction a.\n    + rewrite ?app_nil_l.\n      apply H.\n    + inversion H; subst; clear H.\n      apply IHa.\n      apply H1.\n  Qed.\n  \n  (*Theorem append_nequal_prefix: forall T (a: list T) (b: list T) (c: list T), (List.app a b<>List.app a c)<>(b=c).\n  Proof.\n      induction a.\n      + reflexivity.\n      + intros.\n        simpl.\n        destruct eq.\n  Admitted.*)\n    \n  Hint Rewrite getAllRegisters_BaseMod append_equal_prefix : kami_rewrite_db.\n\n  Theorem getAllRegisters_makeModule_MERegister: forall a b, getAllRegisters (makeModule ((MERegister a)::b))=a::getAllRegisters (makeModule b).\nProof.\n    simpl.\n    intros.\n    reflexivity.\nQed.\n\nTheorem getAllRegisters_makeModule_MERule: forall a b, getAllRegisters (makeModule ((MERule a)::b))=getAllRegisters (makeModule b).\nProof.\n    simpl.\n    intros.\n    reflexivity.\nQed.\n\nTheorem getAllRegisters_makeModule_Registers: forall a b, getAllRegisters (makeModule ((Registers a)++b))=a++getAllRegisters (makeModule b).\nProof.\n    simpl.\n    intros.\n    induction a.\n    + simpl.\n      reflexivity.\n    + simpl.\n      rewrite IHa.\n      reflexivity.\nQed.\n\nHint Rewrite getAllRegisters_makeModule_MERegister\n             getAllRegisters_makeModule_Registers\n           getAllRegisters_makeModule_MERule : kami_rewrite_db.\n\nTheorem in_app: forall T (x:T) (a:List.list T) (b:List.list T), (List.In x (a++b)) <-> (List.In x a)\\/(List.In x b).\nProof.\n    intros.\n    split.\n    + intros.\n      induction a.\n      - simpl in H.\n        right.\n        apply H.\n      - simpl in H.\n        simpl.\n        inversion H; subst; clear H.\n        * left.\n          left.\n          reflexivity.\n        * apply <- or_assoc.\n          right.\n          apply IHa.\n          apply H0.\n    + intros.\n      inversion H; subst; clear H.\n      - induction a.\n        * unfold List.In in H0.\n          inversion H0.\n        * simpl.\n          simpl in H0.\n          inversion H0; subst; clear H0.\n          ++ left.\n             reflexivity.\n          ++ right.\n             apply IHa.\n             apply H.\n      - induction a.\n        * simpl.\n          apply H0.\n        * simpl.\n          right.\n          apply IHa.\nQed.\n\nHint Rewrite in_app : kami_rewrite_db.\n\nLemma getAllMethods_makeModule_append: forall a b, getAllMethods (makeModule (a++b))=getAllMethods (makeModule a)++getAllMethods (makeModule b).\nProof.\n    induction a.\n    + reflexivity.\n    + intros.\n      destruct a.\n      - apply IHa.\n      - apply IHa.\n      - unfold makeModule.\n        simpl.\n        simpl in IHa.\n        rewrite IHa.\n        reflexivity.\nQed.\n\nHint Rewrite getAllMethods_makeModule_append : kami_rewrite_db.\n\nLemma getAllMethods_makeModule_MERegister: forall a b, getAllMethods (makeModule ((MERegister a)::b))=getAllMethods (makeModule b).\nProof.\n    simpl.\n    reflexivity.\nQed.\n\nHint Rewrite getAllMethods_makeModule_MERegister : kami_rewrite_db.\n\nLemma getAllMethods_makeModule_MERule: forall a b, getAllMethods (makeModule ((MERule a)::b))=getAllMethods (makeModule b).\nProof.\n    simpl.\n    reflexivity.\nQed.\n\nHint Rewrite getAllMethods_makeModule_MERule : kami_rewrite_db.\n\nLemma getAllMethods_makeModule_Registers: forall a, getAllMethods (makeModule (Registers a))=[].\nProof.\n    induction a.\n    + reflexivity.\n    + simpl.\n      apply IHa.\nQed.\n\nHint Rewrite getAllMethods_makeModule_Registers : kami_rewrite_db.\n\nLemma getAllRules_makeModule_append: forall a b, getAllRules (makeModule (a++b))=getAllRules (makeModule a)++getAllRules (makeModule b).\nProof.\n    induction a.\n    + reflexivity.\n    + intros.\n      destruct a.\n      - apply IHa.\n      - unfold makeModule.\n        simpl.\n        simpl in IHa.\n        rewrite IHa.\n        reflexivity.\n      - apply IHa.\nQed.\n\nHint Rewrite getAllRules_makeModule_append : kami_rewrite_db.\n\nLemma getAllRules_makeModule_MERegister: forall a b, getAllRules (makeModule ((MERegister a)::b))=getAllRules (makeModule b).\nProof.\n    simpl.\n    reflexivity.\nQed.\n\nHint Rewrite getAllRules_makeModule_MERegister : kami_rewrite_db.\n\nLemma getAllRules_makeModule_MERule: forall a b, getAllRules (makeModule ((MERule a)::b))=a::(getAllRules (makeModule b)).\nProof.\n    simpl.\n    reflexivity.\nQed.\n\nHint Rewrite getAllRules_makeModule_MERule : kami_rewrite_db.\n\nLemma getAllRules_makeModule_Registers: forall a, getAllRules (makeModule (Registers a))=[].\nProof.\n    induction a.\n    + reflexivity.\n    + simpl.\n      apply IHa.\nQed.\n\nHint Rewrite getAllRules_makeModule_Registers : kami_rewrite_db.\n\nHint Rewrite map_app : kami_rewrite_db.\n\nLemma getAllMethods_createHideMod: forall m h, getAllMethods (createHideMod m h)=getAllMethods m.\nProof.\n  intros.\n  induction h.\n  - reflexivity.\n  - simpl.\n    apply IHh.\nQed.\n\nHint Rewrite getAllMethods_createHideMod : kami_rewrite_db.\n\n", "meta": {"author": "sifive", "repo": "Kami", "sha": "ffb77238f27b603dbd42d2622ba911740bf5eadf", "save_path": "github-repos/coq/sifive-Kami", "path": "github-repos/coq/sifive-Kami/Kami-ffb77238f27b603dbd42d2622ba911740bf5eadf/Rewrites/Notations_rewrites.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.26579906319502644}}
{"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 of parallel moves into sequences of individual moves.\n\n  In this file, we adapt the generic \"parallel move\" algorithm\n  (developed and proved correct in module [Parmov]) to the idiosyncraties\n  of the [LTLin] and [Linear] intermediate languages.  While the generic\n  algorithm assumes that registers never overlap, the locations\n  used in [LTLin] and [Linear] can overlap, and assigning one location\n  can set the values of other, overlapping locations to [Vundef].\n  We address this issue in the remainder of this file.\n*)\n\nRequire Import Coqlib.\nRequire Parmov.\nRequire Import Values.\nRequire Import AST.\nRequire Import Locations.\nRequire Import Conventions.\n\n(** * Instantiating the generic parallel move algorithm *)\n\n(** The temporary location to use for a move is determined\n  by the type of the data being moved: register [IT2] for an\n  integer datum, and register [FT2] for a floating-point datum. *)\n\nDefinition temp_for (l: loc) : loc :=\n  match Loc.type l with Tint => R IT2 | Tfloat => R FT2 end.\n\nDefinition parmove (srcs dsts: list loc) :=\n  Parmov.parmove2 loc Loc.eq temp_for srcs dsts.\n\nDefinition moves := (list (loc * loc))%type.\n\n(** [exec_seq m] gives semantics to a sequence of elementary moves.\n  This semantics ignores the possibility of overlap: only the\n  target locations are updated, but the locations they\n  overlap with are not set to [Vundef].  See [effect_seqmove] below\n  for a semantics that accounts for overlaps. *)\n\nDefinition exec_seq (m: moves) (e: Locmap.t) : Locmap.t :=\n  Parmov.exec_seq loc Loc.eq val m e.\n  \nLemma temp_for_charact:\n  forall l, temp_for l = R IT2 \\/ temp_for l = R FT2.\nProof.\n  intro; unfold temp_for. destruct (Loc.type l); tauto.\nQed.\n\nLemma is_not_temp_charact:\n  forall l,\n  Parmov.is_not_temp loc temp_for l <-> l <> R IT2 /\\ l <> R FT2.\nProof.\n  intros. unfold Parmov.is_not_temp. \n  destruct (Loc.eq l (R IT2)). \n  subst l. intuition. apply (H (R IT2)). reflexivity. discriminate.\n  destruct (Loc.eq l (R FT2)).\n  subst l. intuition. apply (H (R FT2)). reflexivity. \n  assert (forall d, l <> temp_for d). \n    intro. elim (temp_for_charact d); congruence.\n  intuition. \nQed.\n\nLemma disjoint_temp_not_temp:\n  forall l, Loc.notin l temporaries -> Parmov.is_not_temp loc temp_for l.\nProof.\n  intros. rewrite is_not_temp_charact. \n  unfold temporaries in H; simpl in H. \n  split; apply Loc.diff_not_eq; tauto.\nQed.\n\nLemma loc_norepet_norepet:\n  forall l, Loc.norepet l -> list_norepet l.\nProof.\n  induction 1; constructor. \n  apply Loc.notin_not_in; auto. auto.\nQed.\n\n(** Instantiating the theorems proved in [Parmov], we obtain\n  the following properties of semantic correctness and well-typedness\n  of the generated sequence of moves.  Note that the semantic\n  correctness result is stated in terms of the [exec_seq] semantics,\n  and therefore does not account for overlap between locations. *)\n\nLemma parmove_prop_1:\n  forall srcs dsts,\n  List.length srcs = List.length dsts ->\n  Loc.norepet dsts ->\n  Loc.disjoint srcs temporaries ->\n  Loc.disjoint dsts temporaries ->\n  forall e,\n  let e' := exec_seq (parmove srcs dsts) e in\n  List.map e' dsts = List.map e srcs /\\\n  forall l, ~In l dsts -> l <> R IT2 -> l <> R FT2 -> e' l = e l.\nProof.\n  intros. \n  assert (NR: list_norepet dsts) by (apply loc_norepet_norepet; auto).\n  assert (NTS: forall r, In r srcs -> Parmov.is_not_temp loc temp_for r).\n    intros. apply disjoint_temp_not_temp. apply Loc.disjoint_notin with srcs; auto.\n  assert (NTD: forall r, In r dsts -> Parmov.is_not_temp loc temp_for r).\n    intros. apply disjoint_temp_not_temp. apply Loc.disjoint_notin with dsts; auto.\n  generalize (Parmov.parmove2_correctness loc Loc.eq temp_for val srcs dsts H NR NTS NTD e).\n  change (Parmov.exec_seq loc Loc.eq val (Parmov.parmove2 loc Loc.eq temp_for srcs dsts) e) with e'.\n  intros [A B].\n  split. auto. intros. apply B. auto. rewrite is_not_temp_charact; auto.\nQed.\n\nLemma parmove_prop_2:\n  forall srcs dsts s d,\n  In (s, d) (parmove srcs dsts) ->\n     (In s srcs \\/ s = R IT2 \\/ s = R FT2)\n  /\\ (In d dsts \\/ d = R IT2 \\/ d = R FT2).\nProof.\n  intros srcs dsts.\n  set (mu := List.combine srcs dsts).\n  assert (forall s d, Parmov.wf_move loc temp_for mu s d ->\n            (In s srcs \\/ s = R IT2 \\/ s = R FT2)\n         /\\ (In d dsts \\/ d = R IT2 \\/ d = R FT2)).\n  unfold mu; induction 1. \n  split. \n    left. eapply List.in_combine_l; eauto.\n    left. eapply List.in_combine_r; eauto.\n  split. \n    right. apply temp_for_charact. \n    tauto.\n  split.\n    tauto.\n    right. apply temp_for_charact.\n  intros. apply H. \n  apply (Parmov.parmove2_wf_moves loc Loc.eq temp_for srcs dsts s d H0). \nQed.\n\nLemma loc_type_temp_for:\n  forall l, Loc.type (temp_for l) = Loc.type l.\nProof.\n  intros; unfold temp_for. destruct (Loc.type l); reflexivity. \nQed.\n\nLemma loc_type_combine:\n  forall srcs dsts,\n  List.map Loc.type srcs = List.map Loc.type dsts ->\n  forall s d,\n  In (s, d) (List.combine srcs dsts) ->\n  Loc.type s = Loc.type d.\nProof.\n  induction srcs; destruct dsts; simpl; intros; try discriminate.\n  elim H0.\n  elim H0; intros. inversion H1; subst. congruence.\n  apply IHsrcs with dsts. congruence. auto.\nQed.\n\nLemma parmove_prop_3:\n  forall srcs dsts,\n  List.map Loc.type srcs = List.map Loc.type dsts ->\n  forall s d,\n  In (s, d) (parmove srcs dsts) -> Loc.type s = Loc.type d.\nProof.\n  intros srcs dsts TYP.\n  set (mu := List.combine srcs dsts).\n  assert (forall s d, Parmov.wf_move loc temp_for mu s d ->\n            Loc.type s = Loc.type d).\n  unfold mu; induction 1. \n  eapply loc_type_combine; eauto.\n  rewrite loc_type_temp_for; auto.\n  rewrite loc_type_temp_for; auto.\n  intros. apply H. \n  apply (Parmov.parmove2_wf_moves loc Loc.eq temp_for srcs dsts s d H0). \nQed.\n\n(** * Accounting for overlap between locations *)\n\nSection EQUIVALENCE.\n\n(** We now prove the correctness of the generated sequence of elementary\n  moves, accounting for possible overlap between locations.\n  The proof is conducted under the following hypotheses: there must\n  be no partial overlap between\n- two distinct destinations (hypothesis [NOREPET]);\n- a source location and a destination location (hypothesis [NO_OVERLAP]).\n*)\n\nVariables srcs dsts: list loc.\nHypothesis LENGTH: List.length srcs = List.length dsts.\nHypothesis NOREPET: Loc.norepet dsts.\nHypothesis NO_OVERLAP: Loc.no_overlap srcs dsts.\nHypothesis NO_SRCS_TEMP: Loc.disjoint srcs temporaries.\nHypothesis NO_DSTS_TEMP: Loc.disjoint dsts temporaries.\n\n(** [no_overlap_dests l] holds if location [l] does not partially overlap\n  a destination location: either it is identical to one of the\n  destinations, or it is disjoint from all destinations. *)\n\nDefinition no_overlap_dests (l: loc) : Prop :=\n  forall d, In d dsts -> l = d \\/ Loc.diff l d.\n\n(** We show that [no_overlap_dests] holds for any destination location\n  and for any source location. *)\n\nLemma dests_no_overlap_dests:\n  forall l, In l dsts -> no_overlap_dests l.\nProof.\n  assert (forall d, Loc.norepet d ->\n          forall l1 l2, In l1 d -> In l2 d -> l1 = l2 \\/ Loc.diff l1 l2).\n  induction 1; simpl; intros.\n  contradiction.\n  elim H1; intro; elim H2; intro.\n  left; congruence.\n  right. subst l1. eapply Loc.in_notin_diff; eauto.\n  right. subst l2. apply Loc.diff_sym. eapply Loc.in_notin_diff; eauto.\n  eauto.\n  intros; red; intros. eauto. \nQed.\n\nLemma notin_dests_no_overlap_dests:\n  forall l, Loc.notin l dsts -> no_overlap_dests l.\nProof.\n  intros; red; intros.\n  right. eapply Loc.in_notin_diff; eauto.\nQed.\n\nLemma source_no_overlap_dests:\n  forall s, In s srcs \\/ s = R IT2 \\/ s = R FT2 -> no_overlap_dests s.\nProof.\n  intros. elim H; intro. exact (NO_OVERLAP s H0). \n  elim H0; intro; subst s; red; intros;\n  right; apply Loc.diff_sym; apply NO_DSTS_TEMP; auto; simpl; tauto.\nQed.\n\nLemma source_not_temp1:\n  forall s, In s srcs \\/ s = R IT2 \\/ s = R FT2 -> \n  Loc.diff s (R IT1) /\\ Loc.diff s (R FT1) /\\ Loc.notin s destroyed_at_move.\nProof.\n  intros. destruct H.\n  exploit Loc.disjoint_notin. eexact NO_SRCS_TEMP. eauto. \n  simpl; tauto.\n  destruct H; subst s; simpl; intuition congruence.\nQed.\n\nLemma dest_noteq_diff:\n  forall d l, \n  In d dsts \\/ d = R IT2 \\/ d = R FT2 ->\n  l <> d ->\n  no_overlap_dests l ->\n  Loc.diff l d.\nProof.\n  intros. elim H; intro.\n  elim (H1 d H2); intro. congruence. auto.\n  assert (forall r, l <> R r -> Loc.diff l (R r)).\n    intros. destruct l; simpl. congruence. destruct s; auto.\n  elim H2; intro; subst d; auto.\nQed.\n\n(** [locmap_equiv e1 e2] holds if the location maps [e1] and [e2]\n  assign the same values to all locations except temporaries [IT1], [FT1]\n  and except locations that partially overlap a destination. *)\n\nDefinition locmap_equiv (e1 e2: Locmap.t): Prop :=\n  forall l,\n  no_overlap_dests l -> Loc.diff l (R IT1) -> Loc.diff l (R FT1) -> Loc.notin l destroyed_at_move -> e2 l = e1 l.\n\n(** The following predicates characterize the effect of one move\n  move ([effect_move]) and of a sequence of elementary moves\n  ([effect_seqmove]).  We allow the code generated for one move\n  to use the temporaries [IT1] and [FT1] and [destroyed_at_move] in any way it needs. *)\n\nDefinition effect_move (src dst: loc) (e e': Locmap.t): Prop :=\n  e' dst = e src /\\\n  forall l, Loc.diff l dst -> Loc.diff l (R IT1) -> Loc.diff l (R FT1) -> Loc.notin l destroyed_at_move -> e' l = e l.\n\nInductive effect_seqmove: list (loc * loc) -> Locmap.t -> Locmap.t -> Prop :=\n  | effect_seqmove_nil: forall e,\n      effect_seqmove nil e e\n  | effect_seqmove_cons: forall s d m e1 e2 e3,\n      effect_move s d e1 e2 ->\n      effect_seqmove m e2 e3 ->\n      effect_seqmove ((s, d) :: m) e1 e3.\n\n(** The following crucial lemma shows that [locmap_equiv] is preserved\n  by executing one move [d <- s], once using the [effect_move]\n  predicate that accounts for partial overlap and the use of\n  temporaries [IT1], [FT1], or via the [Parmov.update] function that\n  does not account for any of these. *)\n\nLemma effect_move_equiv:\n  forall s d e1 e2 e1',\n  (In s srcs \\/ s = R IT2 \\/ s = R FT2) ->\n  (In d dsts \\/ d = R IT2 \\/ d = R FT2) ->\n  locmap_equiv e1 e2 -> effect_move s d e1 e1' ->\n  locmap_equiv e1' (Parmov.update loc Loc.eq val d (e2 s) e2).\nProof.\n  intros. destruct H2. red; intros. \n  unfold Parmov.update. destruct (Loc.eq l d). \n  subst l. destruct (source_not_temp1 _ H) as [A [B C]]. \n  rewrite H2. apply H1; auto. apply source_no_overlap_dests; auto.\n  rewrite H3; auto. apply dest_noteq_diff; auto. \nQed.\n\n(** We then extend the previous lemma to a sequence [mu] of elementary moves.\n*)\n\nLemma effect_seqmove_equiv:\n  forall mu e1 e1',\n  effect_seqmove mu e1 e1' ->\n  forall e2,\n  (forall s d, In (s, d) mu ->\n     (In s srcs \\/ s = R IT2 \\/ s = R FT2) /\\\n     (In d dsts \\/ d = R IT2 \\/ d = R FT2)) ->\n  locmap_equiv e1 e2 ->\n  locmap_equiv e1' (exec_seq mu e2).\nProof.\n  induction 1; intros.\n  simpl. auto.\n  simpl. apply IHeffect_seqmove. \n  intros. apply H1. apply in_cons; auto. \n  destruct (H1 s d (in_eq _ _)).\n  eapply effect_move_equiv; eauto. \nQed.\n\n(** Here is the main result in this file: executing the sequence\n  of moves returned by the [parmove] function results in the\n  desired state for locations: the final values of destination locations\n  are the initial values of source locations, and all locations\n  that are disjoint from the temporaries and the destinations\n  keep their initial values. *)\n\nLemma effect_parmove:\n  forall e e',\n  effect_seqmove (parmove srcs dsts) e e' ->\n  List.map e' dsts = List.map e srcs /\\\n  forall l, Loc.notin l dsts -> Loc.notin l temporaries -> e' l = e l.\nProof.\n  set (mu := parmove srcs dsts). intros.\n  assert (locmap_equiv e e) by (red; auto).\n  generalize (effect_seqmove_equiv mu e e' H e (parmove_prop_2 srcs dsts) H0).\n  intro. \n  generalize (parmove_prop_1 srcs dsts LENGTH NOREPET NO_SRCS_TEMP NO_DSTS_TEMP e).\n  fold mu. intros [A B]. \n  (* e' dsts = e srcs *)\n  split. rewrite <- A. apply list_map_exten; intros.\n  exploit Loc.disjoint_notin. eexact NO_DSTS_TEMP. eauto. simpl; intros.\n  apply H1. apply dests_no_overlap_dests; auto.\n  tauto. tauto. simpl; tauto. \n  (* other locations *)\n  intros. transitivity (exec_seq mu e l). \n  symmetry. apply H1. apply notin_dests_no_overlap_dests; auto.\n  eapply Loc.in_notin_diff; eauto. simpl; tauto.\n  eapply Loc.in_notin_diff; eauto. simpl; tauto.\n  simpl in H3; simpl; tauto.\n  apply B. apply Loc.notin_not_in; auto.\n  apply Loc.diff_not_eq. eapply Loc.in_notin_diff; eauto. simpl; tauto.\n  apply Loc.diff_not_eq. eapply Loc.in_notin_diff; eauto. simpl; tauto.\nQed.\n\nEnd EQUIVALENCE.\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/backend/Parallelmove.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.26579906319502644}}
{"text": "(**\n\n== Representation and verification of WordCount ==\n\nWordCount is a standard MapReduce application.\nIt counts each word's frequency in a CBS file.\n\nThis file shows how we represent the actual application, \nand how we specify and verify the behavior of programs.\n\nAdvice: readers need to read Language.v first.\n\nAuthor: Bowen Zhang.\n\nDate : 2022.11.1\n*)\n\nFrom SLF (* TLC *) Require Export LibCore TLCbuffer.\nFrom SLF (* Sep *) Require Export Rules AuxLmm.\n(*------------------------------------------------------------------------*)\n\nExport NotationForTrm.\nExport NotationForVariables.\n\nOpen Scope val_scope.\nOpen Scope trm_scope.\nOpen Scope Z_scope.\n\n(* ########################### WordCount ########################### *)\n\n(*  \n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nSuppose a HDFS state before WordCount:\n\n--f\n  | bk1 [n1;n2]\n  | bk2 [n3;n1]\n  | bk3 [n2]\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nThe state after WordCount:\n\n--f\n  | bk1 [n1;n2]\n  | bk2 [n3;n1]\n  | bk3 [n2]\n\n--f2\n  | bk4 [n1;2]\n  | bk5 [n2;2]\n  | bk6 [n3;1]\n*)\n\n(* \n------- Representation and Specification ----------\n\nDefinition WordCount := \n  Fun 'f :=\n    Let 'L1 := Mapper 'f 0 in\n    Let 'L2 := Shuffle 'L1 in\n    Let 'l := Reducer 'L2 in\n    Create_File 'l.\n\n\nLemma triple_WordCount: forall Hf Hb (f:floc) (n1 n2 n3 :int) (p1 p2 p3:bloc),\n  diff_each_3 n1 n2 n3 ->\n  Hf = ( f ~f~> (p1::p2::p3::nil) ) ->\n  Hb = ( (p1 ~b~> (n1::n2::nil)) \\b* (p2 ~b~> (n3::n1::nil)) \\b* (p3 ~b~> (n2::nil)) ) ->\n  triple (WordCount f)\n    (\\R[Hf,Hb])\n    (fun r => \\exists f1 b4 b5 b6,( \\[r= (val_floc f1)] \\* \n        (\\R[(f1 ~f~> (b4::b5::b6::nil) \\f* Hf),\n        Hb \\b* (b4 ~b~> (n1::2::nil)) \\b* (b5 ~b~> (n2::2::nil))\n        \\b* (b6 ~b~> (n3::1::nil))] ))).\n\n*)\n\n(*============= Mapper ================*)\nDefinition Mapper := \n  Fix 'F 'f 'i :=\n    Let 'n := 'fsize 'f in\n    Let 'be := ('i '= 'n) in\n    If_ 'be\n    Then (val_Listwd nil)\n    Else\n      Let 'bk := 'nth_blk 'f 'i in\n      Let 'i1 := 'i '+ 1 in\n      Let 'ln := 'wdmap 'bk in\n      Let 'ln1 := 'F 'f 'i1 in\n      'ln 'w:: 'ln1.\n\n(* specification of mapper *)\nLemma triple_Mapper: forall Hf Hb (f:floc) (n1 n2 n3:int) (p1 p2 p3:bloc) (L:(list (list wdpair))),\n  diff_each_3 n1 n2 n3 ->\n  Hf = ( f ~f~> (p1::p2::p3::nil) ) ->\n  Hb = ( (p1 ~b~> (n1::n2::nil)) \\b* (p2 ~b~> (n3::n1::nil)) \\b* (p3 ~b~> (n2::nil)) ) ->\n  L = ( ((n1,1)::(n2,1)::nil) :: ((n3,1)::(n1,1)::nil) :: ((n2,1)::nil) :: nil ) ->\n  triple (Mapper f 0)\n    (\\R[Hf,Hb])\n    (fun r => \\[r= val_Listwd L] \\* \\R[Hf,Hb]).\nProof.\n  fix_map.\n  rewrite hstar_sep, hfstar_hempty_l. apply himpl_refl.\n  rew_read. ext.\n\n  applys triple_let.\n  fix_map.\n  rewrite hstar_sep, hfstar_hempty_l,hbstar_comm,hbstar_assoc. apply himpl_refl.\n  rew_read. ext.\n\n  applys triple_let.\n  fix_map.\n  rewrite hstar_sep, hfstar_hempty_l,hbstar_comm,hbstar_assoc. apply himpl_refl.\n  rew_read. ext.\n\n  applys triple_let.\n  exp_fix.\n  applys triple_val'. ext.\n  applys triple_app_wdlist. ext.\n  applys triple_app_wdlist. ext.\n  applys triple_conseq triple_app_wdlist.\n  apply himpl_refl.\n  intros r. rew_list. \n  rewrite hbstar_comm,hbstar_assoc. apply himpl_refl.\nQed.\n\n(*============= Shuffle ================*)\nDefinition Shuffle :=\n Fun 'L :=\n    Let 'l := 'wdmerge 'L in\n      'wdshuffle 'l.\n\nLemma triple_Shuffle: forall Hf Hb (n1 n2 n3 : int) (L1 L2: (list (list wdpair))),\n  diff_each_3 n1 n2 n3 ->\n  L1 = ( ((n1,1)::(n2,1)::nil) :: ((n3,1)::(n1,1)::nil) :: ((n2,1)::nil) :: nil ) ->\n  L2 = ( ((n1,1)::(n1,1)::nil) :: ((n2,1)::(n2,1)::nil) :: ((n3,1)::nil) ::nil ) ->\n  triple (Shuffle (val_Listwd L1))\n    (\\R[Hf,Hb])\n    (fun r => \\[r= val_Listwd L2] \\* \\R[Hf,Hb]).\nProof.\n  intros. subst.\n  applys* triple_app_fun. simpl.\n  applys triple_let.\n  applys triple_conseq_frame triple_wdmerge.\n  rewrite hstar_hempty_r'. applys himpl_refl.\n  intros r. rewrite hstar_hempty_r'.\n  unfold wordmerge,merge. simpl. applys himpl_refl.\n  ext.\n  applys triple_conseq_frame triple_wdshuffle.\n  rewrite hstar_hempty_r'. applys himpl_refl.\n  intros r. rewrite hstar_hempty_r'.\n  apply shuffle_diff in H.\n  rewrite <- H.\n  applys himpl_refl.\nQed.\n\n(*============= Reducer ================*)\nDefinition Reducer :=\n  Fun 'L :=  'wdreduce 'L.\n\nLemma triple_Reducer: forall Hf Hb (n1 n2 n3 : int) (lwd:list wdpair) (L : (list (list wdpair))),\n  diff_each_3 n1 n2 n3 ->\n  L = ( ((n1,1)::(n1,1)::nil) :: ((n2,1)::(n2,1)::nil) :: ((n3,1)::nil) ::nil ) ->\n  lwd = ((n1,2)::(n2,2)::(n3,1)::nil ) ->\n  triple (Reducer (val_Listwd L))\n    (\\R[Hf,Hb])\n    (fun r => \\[r= val_listwdpair lwd] \\* \\R[Hf,Hb]).\nProof.\n  intros. subst.\n  applys* triple_app_fun. simpl.\n  applys triple_conseq_frame triple_wdreduce.\n  rewrite hstar_hempty_r'. applys himpl_refl.\n  intros r. rewrite hstar_hempty_r'.\n  applys himpl_refl.\nQed.\n\n\n(*============= Create files ================*)\nDefinition Create_Blks_buffer : val :=\n  Fix 'F 'l 'lb:=\n    Let 'm := 'len 'l in\n    Let 'be := ('m '<= 2) in\n    If_ 'be\n    Then \n      Let 'bk := 'bcreate 'l in\n        'bk 'b+ 'lb\n    Else\n      Let 'l1 := 'hd 'l in\n      Let 'l2 := 'tl 'l in\n      Let 'bk1 := 'bcreate 'l1 in\n      Let 'lb1 := 'bk1 'b+ 'lb in\n        'F 'l2 'lb1.\n\nLemma triple_Create_Blks_buffer : forall Hf (n1 n2 n3 n4 n5 n6:int),\n  triple (Create_Blks_buffer (val_listint (n1::n2::n3::n4::n5::n6::nil)) (val_listbloc nil))\n    (\\R[Hf, \\b[] ])\n     (fun r => \\exists b1 b2 b3,( \\[r=(val_listbloc (b3::b2::b1::nil))] \\* \n               (\\R[Hf, (b1 ~b~> (n1::n2::nil)) \\b* (b2 ~b~> (n3::n4::nil) \\b* (b3 ~b~> (n5::n6::nil)))]))).\nProof.\n  intros. applys* triple_app_fix2. simpl.\n  applys triple_let triple_list_len.\n  ext. applys triple_let triple_le. ext.\n  applys triple_if. case_if*. destruct C. auto.\n  applys triple_let triple_list_hd. ext.\n  applys triple_let triple_list_tl. ext.\n  applys triple_let.\n  applys triple_conseq_frame triple_bcreate.\n  rewrite hstar_sep. rewrite hfstar_hempty_r, hbstar_hempty_l.\n  apply himpl_refl. intros r. simpl.\n  apply himpl_refl. intros r. simpl.\n  rewrite hstar_hexists.\n  applys triple_hexists. intros b1.\n  rewrite hstar_hempty_r. ext.\n  applys triple_let triple_fbuffer_list.\n  intros. simpl. ext.\n\n  applys* triple_app_fix2. simpl.\n  applys triple_let triple_list_len.\n  ext. applys triple_let triple_le. ext.\n  applys triple_if. case_if*.\n  applys triple_let triple_list_hd. ext.\n  applys triple_let triple_list_tl. ext.\n  applys triple_let.\n  applys triple_conseq_frame triple_bcreate.\n  rewrite hstar_sep. rewrite hfstar_hempty_r, hbstar_hempty_l.\n  apply himpl_refl. intros r. simpl.\n  apply himpl_refl. intros r. simpl.\n  rewrite hstar_hexists.\n  applys triple_hexists. intros b2.\n  rewrite hstar_assoc, hstar_sep, hfstar_hempty_r. ext.\n  applys triple_let triple_fbuffer_list.\n  intros. simpl. ext.\n\n  applys* triple_app_fix2. simpl.\n  applys triple_let triple_list_len.\n  ext. applys triple_let triple_le. ext.\n  applys triple_if. case_if*.\n  applys triple_let.\n  applys triple_conseq_frame triple_bcreate.\n  rewrite hstar_sep. rewrite hfstar_hempty_r, hbstar_hempty_l.\n  apply himpl_refl. intros r. simpl.\n  apply himpl_refl. intros r. simpl.\n  rewrite hstar_hexists.\n  applys triple_hexists. intros b3.\n  rewrite hstar_assoc, hstar_sep, hfstar_hempty_r. ext.\n  applys triple_conseq_frame triple_fbuffer_list.\n  rewrite hstar_hempty_l'. apply himpl_refl.\n  intros r. simpl. rewrite hstar_hempty_r.\n  rewrite hbstar_comm3. intros h H.\n  rewrite hstar_hpure_iff in H.\n  destruct H as (H1&H2).\n  exists b1 b2 b3.\n  applys hstar_hpure_iff. splits~.\n  destruct C1. rew_list. discriminate.\nQed.\n\nDefinition Create_File : val :=\n  Fun 'l:=\n    Let 'l1 := 'reform 'l in\n    Let 'lb1 := Create_Blks_buffer 'l1 (val_listbloc nil) in\n    Let 'lb := 'frev 'lb1 in\n      'fcreate 'lb.\n\nLemma triple_Create_File : forall (w1 w2 w3 n1 n2 n3:int),\n  triple (Create_File (val_listwdpair ((w1,n1)::(w2,n2)::(w3,n3)::nil)) )\n    (\\R[\\f[], \\b[] ])\n     (fun r => \\exists f b1 b2 b3,( \\[r= (val_floc f)] \\* \n               (\\R[(f ~f~> (b1::b2::b3::nil)), (b1 ~b~> (w1::n1::nil)) \\b* (b2 ~b~> (w2::n2::nil) \\b* (b3 ~b~> (w3::n3::nil)))]))).\nProof.\n  intros. applys* triple_app_fun. simpl.\n  applys triple_let triple_MRlist_reform.\n  ext.\n  applys triple_let triple_Create_Blks_buffer.\n  intros v. ext. intros b1. ext. intros b2. ext. intros b3. ext.\n  applys triple_let.\n  applys triple_conseq_frame triple_frev_blist.\n  rewrite hstar_hempty_l'. apply himpl_refl.\n  intros r. rewrite hstar_assoc, hstar_hempty_l. apply himpl_refl.\n  ext.\n  applys triple_conseq_frame triple_fcreate.\n  rewrite hstar_hempty_r'.\n  apply himpl_noduplicate3.\n  intros v. rewrite hstar_hempty_r'.\n  apply himpl_hexists_l. intros f.\n  intros h M. exists~ f b1 b2 b3.\nQed.\n\n\n\n(* $$$$$$$$$$$$$==================$$$$$$$$$$$$$$$$$$$$$ *)\n\n\nDefinition WordCount := \n  Fun 'f :=\n    Let 'L1 := Mapper 'f 0 in\n    Let 'L2 := Shuffle 'L1 in\n    Let 'l := Reducer 'L2 in\n    Create_File 'l.\n\nLemma triple_WordCount: forall Hf Hb (f:floc) (n1 n2 n3 :int) (p1 p2 p3:bloc),\n  diff_each_3 n1 n2 n3 ->\n  Hf = ( f ~f~> (p1::p2::p3::nil) ) ->\n  Hb = ( (p1 ~b~> (n1::n2::nil)) \\b* (p2 ~b~> (n3::n1::nil)) \\b* (p3 ~b~> (n2::nil)) ) ->\n  triple (WordCount f)\n    (\\R[Hf,Hb])\n    (fun r => \\exists f1 b4 b5 b6,( \\[r= (val_floc f1)] \\* \n        (\\R[(f1 ~f~> (b4::b5::b6::nil) \\f* Hf),\n        Hb \\b* (b4 ~b~> (n1::2::nil)) \\b* (b5 ~b~> (n2::2::nil))\n        \\b* (b6 ~b~> (n3::1::nil))] ))).\nProof.\n    intros. subst.\n  applys* triple_app_fun. simpl.\n  applys triple_let.\n  applys* triple_Mapper.\n  simpl. intros r. ext.\n  applys triple_let. applys* triple_Shuffle H.\n  ext.\n  applys triple_let. applys* triple_Reducer.\n  ext.\n  applys triple_conseq_frame triple_Create_File.\n  rewrite hstar_hempty_l'. apply himpl_refl.\n  intros r. rewrite hstar_hexists.\n  apply himpl_hexists_l. intros f1.\n  rewrite hstar_hexists.\n  apply himpl_hexists_l. intros b4.\n  rewrite hstar_hexists.\n  apply himpl_hexists_l. intros b5.\n  rewrite hstar_hexists.\n  apply himpl_hexists_l. intros b6.\n  rewrite hstar_assoc.\n  intros h M.\n  rewrite hstar_hpure_iff in M.\n  destruct M as (M1&M2).\n  rewrite hstar_sep in M2.\n  exists f1 b4 b5 b6.\n  rewrite hstar_hpure_iff.\n  splits*. rewrite~ hbstar_comm.\nQed.\n \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/WordCount.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.26579906319502644}}
{"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.\nRequire Import MemoryFacts.\n\nRequire Import Cover.\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_split_same\n        mem0 loc ts1 ts2 ts3 msg2 msg3 mem1 mem2\n        (ADD1: Memory.add mem0 loc ts1 ts3 msg3 mem1)\n        (SPLIT2: Memory.split mem1 loc ts1 ts2 ts3 msg2 msg3 mem2):\n    exists mem1',\n      <<ADD1: Memory.add mem0 loc ts1 ts2 msg2 mem1'>> /\\\n      <<ADD2: Memory.add mem1' loc ts2 ts3 msg3 mem2>>.\n  Proof.\n    exploit (@Memory.add_exists mem0 loc ts1 ts2 msg2); eauto.\n    { i. inv ADD1. inv ADD. hexploit DISJOINT; eauto. i.\n      eapply Interval.le_disjoint; eauto. econs; [refl|].\n      inv SPLIT2. inv SPLIT. left. auto.\n    }\n    { inv SPLIT2. inv SPLIT. auto. }\n    { inv SPLIT2. inv SPLIT. auto. }\n    i. des.\n    exploit (@Memory.add_exists mem3 loc ts2 ts3 msg3); eauto.\n    { i. revert GET2. erewrite Memory.add_o; eauto. condtac; ss.\n      - des. subst. i. inv GET2.\n        symmetry. apply Interval.disjoint_imm.\n      - i. inv ADD1. inv ADD. hexploit DISJOINT; eauto. i.\n        eapply Interval.le_disjoint; eauto. econs; [|refl].\n        inv SPLIT2. inv SPLIT. left. auto.\n    }\n    { inv SPLIT2. inv SPLIT. auto. }\n    { inv ADD1. inv ADD. auto. }\n    i. des.\n    cut (mem4 = mem2); [by i; subst; eauto|].\n    apply Memory.ext. i.\n    erewrite Memory.add_o; eauto. erewrite Memory.add_o; eauto.\n    erewrite (@Memory.split_o mem2); eauto. erewrite (@Memory.add_o mem1); eauto.\n    repeat (condtac; ss). des. repeat subst.\n    inv SPLIT2. inv SPLIT. exfalso. eapply Time.lt_strorder. eauto.\n  Qed.\n\n  Lemma add_split\n        mem0 loc1 from1 to1 msg1\n        mem1 loc2 ts21 ts22 ts23 msg22 msg23\n        mem2\n        (ADD1: Memory.add mem0 loc1 from1 to1 msg1 mem1)\n        (SPLIT2: Memory.split mem1 loc2 ts21 ts22 ts23 msg22 msg23 mem2):\n    (loc1 = loc2 /\\ from1 = ts21 /\\ to1 = ts23 /\\ msg1 = msg23 /\\\n     exists mem1',\n       <<ADD1: Memory.add mem0 loc2 ts21 ts22 msg22 mem1'>> /\\\n       <<ADD2: Memory.add mem1' loc2 ts22 ts23 msg23 mem2>>) \\/\n    (<<LOCTS1: (loc1, to1) <> (loc2, ts23)>> /\\\n     exists mem1',\n       <<SPLIT1: Memory.split mem0 loc2 ts21 ts22 ts23 msg22 msg23 mem1'>> /\\\n       <<ADD2: Memory.add mem1' loc1 from1 to1 msg1 mem2>>).\n  Proof.\n    exploit Memory.split_get0; eauto. i. des.\n    revert GET0. erewrite Memory.add_o; eauto. condtac; ss.\n    { des. i. inv GET0. left. splits; eauto.\n      eapply add_split_same; eauto.\n    }\n    guardH o. i. right. splits.\n    { ii. inv H. unguardH o. des; congr. }\n    exploit (@Memory.split_exists mem0 loc2 ts21 ts22 ts23);\n      try by inv SPLIT2; inv SPLIT; eauto.\n    i. des.\n    exploit (@Memory.add_exists mem3 loc1 from1 to1);\n      try by inv ADD1; inv ADD; eauto.\n    { i. revert GET3. erewrite Memory.split_o; eauto. repeat condtac; ss.\n      - des. subst. i. inv GET3.\n        inv ADD1. inv ADD. hexploit DISJOINT; eauto. i. symmetry in H.\n        symmetry. eapply Interval.le_disjoint; eauto. econs; [refl|].\n        inv SPLIT2. inv SPLIT. left. auto.\n      - guardH o0. i. des. inv GET3.\n        inv ADD1. inv ADD. hexploit DISJOINT; eauto. i. symmetry in H.\n        symmetry. eapply Interval.le_disjoint; eauto. econs; [|refl].\n        inv SPLIT2. inv SPLIT. left. auto.\n      - guardH o0. i. inv ADD1. inv ADD. eapply DISJOINT; eauto.\n    }\n    i. des.\n    esplits; eauto.\n    cut (mem4 = mem2); [by i; subst; eauto|].\n    apply Memory.ext. i.\n    erewrite Memory.add_o; eauto. erewrite Memory.split_o; eauto.\n    setoid_rewrite Memory.split_o; cycle 1; eauto.\n    erewrite (@Memory.add_o mem1); eauto.\n    repeat (condtac; ss).\n    - des. repeat subst.\n      exploit Memory.add_get0; try exact ADD1; eauto. i. des.\n      exploit Memory.split_get0; try exact SPLIT2; eauto. i. des.\n      congr.\n    - guardH o0. des. repeat subst. unguardH o. des; congr.\n  Qed.\n\n  Lemma add_lower\n        mem0 loc1 from1 to1 msg1\n        mem1 loc2 from2 to2 msg2 msg2'\n        mem2\n        (ADD1: Memory.add mem0 loc1 from1 to1 msg1 mem1)\n        (LOWER2: Memory.lower mem1 loc2 from2 to2 msg2 msg2' mem2):\n    (loc1 = loc2 /\\ from1 = from2 /\\ to1 = to2 /\\ msg1 = msg2 /\\\n     Memory.add mem0 loc1 from1 to1 msg2' mem2) \\/\n    (<<LOCTS1: (loc1, to1) <> (loc2, to2)>> /\\\n     exists mem1',\n       <<LOWER1: Memory.lower mem0 loc2 from2 to2 msg2 msg2' mem1'>> /\\\n       <<ADD2: Memory.add mem1' loc1 from1 to1 msg1 mem2>>).\n  Proof.\n    exploit Memory.lower_get0; eauto.\n    erewrite Memory.add_o; eauto. condtac; ss.\n    - des. subst. i. des. inv GET. left. splits; eauto.\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    - guardH o. i. des. right. splits.\n      { ii. inv H. unguardH o. des; congr. }\n      exploit (@Memory.lower_exists mem0 loc2 from2 to2);\n        try by inv LOWER2; inv LOWER; eauto.\n      i. des.\n      exploit (@Memory.add_exists mem3 loc1 from1 to1).\n      { i. revert GET2. erewrite Memory.lower_o; eauto. condtac; ss.\n        - des. subst. i. inv GET2.\n          exploit Memory.lower_get0; eauto. i. des.\n          inv ADD1. inv ADD. eapply DISJOINT. eauto.\n        - guardH o0. 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.\n      cut (mem4 = mem2); [by i; subst; eauto|].\n      apply Memory.ext. i.\n      erewrite Memory.add_o; eauto. erewrite Memory.lower_o; eauto.\n      setoid_rewrite Memory.lower_o; cycle 1; eauto.\n      erewrite (@Memory.add_o mem1); eauto.\n      repeat (condtac; ss). des. repeat subst.\n      unguardH o. des; 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 split_add\n        mem0 loc1 ts11 ts12 ts13 msg12 msg13\n        mem1 loc2 from2 to2 msg2\n        mem2\n        (SPLIT1: Memory.split mem0 loc1 ts11 ts12 ts13 msg12 msg13 mem1)\n        (ADD2: Memory.add mem1 loc2 from2 to2 msg2 mem2):\n    <<LOCTS1: (loc1, ts12) <> (loc2, to2)>> /\\\n    <<LOCTS2: (loc1, ts13) <> (loc2, to2)>> /\\\n    exists mem1',\n      <<ADD1: Memory.add mem0 loc2 from2 to2 msg2 mem1'>> /\\\n      <<SPLIT2: Memory.split mem1' loc1 ts11 ts12 ts13 msg12 msg13 mem2>>.\n  Proof.\n    exploit (@Memory.add_exists mem0 loc2 from2 to2);\n      try by inv ADD2; inv ADD; eauto.\n    { apply covered_disjoint_get_disjoint. i. rewrite <- split_covered in H; eauto.\n      eapply get_disjoint_covered_disjoint; eauto. inv ADD2. inv ADD. auto.\n    }\n    i. des.\n    exploit (@Memory.split_exists mem3 loc1 ts11 ts12 ts13);\n      try by inv SPLIT1; inv SPLIT; eauto.\n    { erewrite Memory.add_o; eauto. condtac; ss.\n      - des. subst.\n        hexploit Memory.add_get0; try exact ADD2; eauto. i. des.\n        revert GET. erewrite Memory.split_o; eauto. repeat condtac; ss.\n      - guardH o. hexploit Memory.split_get0; eauto. i. des. eauto.\n    }\n    i. des.\n    splits.\n    { ii. inv H.\n      hexploit Memory.add_get0; try exact ADD2; eauto. i. des.\n      revert GET. erewrite Memory.split_o; eauto. repeat condtac; ss.\n      guardH o0. des; congr.\n    }\n    { ii. inv H.\n      hexploit Memory.add_get0; try exact ADD2; eauto. i. des.\n      revert GET. erewrite Memory.split_o; eauto. repeat condtac; ss.\n      guardH o. des; congr.\n    }\n    cut (mem4 = mem2); [by i; subst; eauto|].\n    apply Memory.ext. i.\n    erewrite Memory.split_o; eauto. erewrite Memory.add_o; eauto.\n    erewrite (@Memory.add_o mem2); eauto. erewrite (@Memory.split_o mem1); eauto.\n    repeat (condtac; ss).\n    - des. repeat subst.\n      hexploit Memory.add_get0; try exact ADD2; eauto. i. des.\n      revert GET. erewrite Memory.split_o; eauto. repeat condtac; ss.\n    - guardH o. des. repeat subst.\n      hexploit Memory.add_get0; try exact ADD2; eauto. i. des.\n      revert GET. erewrite Memory.split_o; eauto. repeat condtac; ss.\n  Qed.\n\n  Lemma split_split\n        mem0 loc1 ts11 ts12 ts13 msg12 msg13\n        mem1 loc2 ts21 ts22 ts23 msg22 msg23\n        mem2\n        (LOCTS1: (loc1, ts13) <> (loc2, ts23))\n        (SPLIT1: Memory.split mem0 loc1 ts11 ts12 ts13 msg12 msg13 mem1)\n        (SPLIT2: Memory.split mem1 loc2 ts21 ts22 ts23 msg22 msg23 mem2):\n    (loc1 = loc2 /\\ ts21 = ts11 /\\ ts23 = ts12 /\\\n     exists mem1',\n       <<SPLIT1: Memory.split mem0 loc2 ts21 ts22 ts13 msg22 msg13 mem1'>> /\\\n       <<SPLIT2: Memory.split mem1' loc1 ts22 ts12 ts13 msg12 msg13 mem2>>) \\/\n    ((loc2, ts21, ts23) <> (loc1, ts11, ts12) /\\\n     exists mem1',\n       <<SPLIT1: Memory.split mem0 loc2 ts21 ts22 ts23 msg22 msg23 mem1'>> /\\\n       <<SPLIT2: Memory.split mem1' loc1 ts11 ts12 ts13 msg12 msg13 mem2>>).\n  Proof.\n    exploit Memory.split_get0; try exact SPLIT2; eauto. i. des.\n    revert GET0. erewrite Memory.split_o; eauto. repeat condtac; ss.\n    - i. des. inv GET0. left. splits; auto.\n      exploit Memory.split_get0; try exact SPLIT1; eauto. i. des.\n      exploit Memory.split_get0; try exact SPLIT2; eauto. i. des.\n      revert GET4. erewrite Memory.split_o; eauto. condtac; ss.\n      exploit (@Memory.split_exists mem0 loc1 ts21 ts22 ts13);\n        try by inv SPLIT2; inv SPLIT; eauto.\n      { etrans.\n        - inv SPLIT2. inv SPLIT. eauto.\n        - inv SPLIT1. inv SPLIT. eauto.\n      }\n      i. des.\n      exploit (@Memory.split_exists mem3 loc1 ts22 ts12 ts13);\n        (try by inv SPLIT1; inv SPLIT; eauto);\n        (try by inv SPLIT2; inv SPLIT; eauto).\n      { erewrite Memory.split_o; eauto. repeat condtac; ss.\n        - des. subst. inv x0. inv SPLIT.\n          exfalso. eapply Time.lt_strorder. eauto.\n        - guardH o. des; congr.\n      }\n      i. des.\n      cut (mem4 = mem2); [by i; subst; eauto|].\n      apply Memory.ext. i.\n      erewrite Memory.split_o; eauto. erewrite Memory.split_o; eauto.\n      erewrite (@Memory.split_o mem2); eauto. erewrite (@Memory.split_o mem1); eauto.\n      repeat (condtac; ss).\n      + des. repeat subst. inv x1. inv SPLIT.\n        exfalso. eapply Time.lt_strorder. eauto.\n      + guardH o. des. repeat subst. inv x0. inv SPLIT.\n        exfalso. eapply Time.lt_strorder. eauto.\n    - guardH o. i. des. inv GET0. congr.\n    - guardH o. guardH o0. i. right.\n      exploit (@Memory.split_exists mem0 loc2 ts21 ts22 ts23);\n        try by inv SPLIT2; inv SPLIT; eauto. i. des.\n      exploit (@Memory.split_exists mem3 loc1 ts11 ts12 ts13);\n        try by inv SPLIT1; inv SPLIT; eauto.\n      { erewrite Memory.split_o; eauto. repeat condtac; ss.\n        - des. subst. hexploit Memory.split_get0; try exact SPLIT2; eauto. i. des.\n          revert GET3. erewrite Memory.split_o; eauto. repeat condtac; ss.\n        - guardH o1. des. subst. unguardH o0. des; congr.\n        - guardH o1. guardH o2. hexploit Memory.split_get0; try exact SPLIT1; eauto. i. des. eauto.\n      }\n      i. des. splits.\n      { ii. inv H. unguardH o. des; congr. }\n      cut (mem4 = mem2); [by i; subst; eauto|].\n      apply Memory.ext. i.\n      erewrite Memory.split_o; eauto. erewrite Memory.split_o; eauto.\n      erewrite (@Memory.split_o mem2); eauto. erewrite (@Memory.split_o mem1); eauto.\n      repeat (condtac; ss).\n      + des. repeat subst.\n        exploit Memory.split_get0; try exact SPLIT2; eauto. i. des.\n        revert GET3. erewrite Memory.split_o; eauto. repeat condtac; ss.\n      + guardH o1. des. repeat subst. unguardH o. des; congr.\n      + guardH o1. des. repeat subst.\n        exploit Memory.split_get0; try exact SPLIT2; eauto. i. des.\n        revert GET3. erewrite Memory.split_o; eauto. repeat condtac; ss.\n      + guardH o1. guardH o2. des. repeat subst. unguardH o0. des; congr.\n  Qed.\n\n  Lemma split_lower_diff\n        mem0 loc1 ts11 ts12 ts13 msg12 msg13\n        mem1 loc2 from2 to2 msg2 msg2'\n        mem2\n        (LOCTS1: (loc1, ts13) <> (loc2, to2))\n        (SPLIT1: Memory.split mem0 loc1 ts11 ts12 ts13 msg12 msg13 mem1)\n        (LOWER2: Memory.lower mem1 loc2 from2 to2 msg2 msg2' mem2):\n    (loc1 = loc2 /\\ ts11 = from2 /\\ ts12 = to2 /\\ msg12 = msg2 /\\\n     Memory.split mem0 loc1 ts11 ts12 ts13 msg2' msg13 mem2) \\/\n    ((loc1, ts12) <> (loc2, to2) /\\\n     exists mem1',\n        <<LOWER1: Memory.lower mem0 loc2 from2 to2 msg2 msg2' mem1'>> /\\\n        <<SPLIT2: Memory.split mem1' loc1 ts11 ts12 ts13 msg12 msg13 mem2>>).\n  Proof.\n    exploit Memory.lower_get0; eauto. i. des.\n    revert GET. erewrite Memory.split_o; eauto. repeat condtac; ss.\n    - des. subst. i. inv GET. left. splits; auto.\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    - guardH o. des. subst. congr.\n    - guardH o. guardH o0. i. right.\n      exploit (@Memory.lower_exists mem0 loc2 from2 to2);\n        try by inv LOWER2; inv LOWER; eauto. i. des.\n      exploit (@Memory.split_exists mem3 loc1 ts11 ts12 ts13);\n        try by inv SPLIT1; inv SPLIT; eauto.\n      { erewrite Memory.lower_o; eauto. condtac; ss.\n        - des. subst. congr.\n        - guardH o1. hexploit Memory.split_get0; try exact SPLIT1; eauto. i. des. eauto.\n      }\n      i. des.\n      splits.\n      { ii. inv H. exploit Memory.split_get0; try exact SPLIT1; eauto. i. des.\n        exploit Memory.lower_get0; eauto. i. des. congr.\n      }\n      cut (mem4 = mem2); [by i; subst; eauto|].\n      apply Memory.ext. i.\n      erewrite Memory.split_o; eauto. erewrite Memory.lower_o; eauto.\n      erewrite (@Memory.lower_o mem2); eauto. erewrite (@Memory.split_o mem1); eauto.\n      repeat (condtac; ss).\n      + des. repeat subst. congr.\n      + guardH o1. des. repeat subst. congr.\n  Qed.\n\n  Lemma split_lower_same\n        loc\n        mem0 ts11 ts12 ts13 msg12 msg13\n        mem1 from2 msg2 msg2'\n        mem2\n        (SPLIT1: Memory.split mem0 loc ts11 ts12 ts13 msg12 msg13 mem1)\n        (LOWER2: Memory.lower mem1 loc from2 ts13 msg2 msg2' mem2):\n    from2 = ts12 /\\ msg13 = msg2 /\\\n    exists mem1',\n      <<LOWER1: Memory.lower mem0 loc ts11 ts13 msg2 msg2' mem1'>> /\\\n      <<SPLIT2: Memory.split mem1' loc ts11 ts12 ts13 msg12 msg2' mem2>>.\n  Proof.\n    exploit Memory.lower_get0; eauto. erewrite Memory.split_o; eauto. repeat condtac; ss; cycle 2.\n    { clear -o0. des; congr. }\n    { des. subst. inv SPLIT1. inv SPLIT. exfalso. eapply Time.lt_strorder. eauto. }\n    clear o a COND COND0. i. des. inv GET. splits; ss.\n    exploit Memory.split_get0; eauto. i. des.\n    exploit (@Memory.lower_exists mem0 loc ts11 ts13);\n      try by inv LOWER2; inv LOWER; eauto.\n    { inv SPLIT1. inv SPLIT. etrans; eauto. }\n    i. des.\n    exploit (@Memory.split_exists mem3 loc ts11 from2 ts13);\n      try by inv SPLIT1; inv SPLIT; eauto.\n    { erewrite Memory.lower_o; eauto. condtac; ss. des; congr. }\n    i. des.\n    cut (mem4 = mem2); [by i; subst; esplits; eauto|].\n    apply Memory.ext. i.\n    erewrite Memory.split_o; eauto. erewrite Memory.lower_o; eauto.\n    erewrite (@Memory.lower_o mem2); eauto. erewrite (@Memory.split_o mem1); eauto.\n    repeat (condtac; ss).\n    des. repeat subst. congr.\n  Qed.\n\n  Lemma split_remove\n        mem0 loc1 ts11 ts12 ts13 msg12 msg13\n        mem1 loc2 from2 to2 msg2\n        mem2\n        (LOCTS1: (loc1, ts12) <> (loc2, to2))\n        (LOCTS2: (loc1, ts13) <> (loc2, to2))\n        (SPLIT1: Memory.split mem0 loc1 ts11 ts12 ts13 msg12 msg13 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      <<SPLIT2: Memory.split mem1' loc1 ts11 ts12 ts13 msg12 msg13 mem2>>.\n  Proof.\n    exploit (@Memory.remove_exists mem0 loc2 from2 to2).\n    { hexploit Memory.remove_get0; eauto.\n      erewrite Memory.split_o; eauto. repeat condtac; ss.\n      { des. subst. congr. }\n      { guardH o. des. subst. congr. }\n      guardH o. guardH o0. i. des. eauto.\n    }\n    i. des.\n    exploit (@Memory.split_exists mem3 loc1 ts11 ts12 ts13);\n      try by inv SPLIT1; inv SPLIT; eauto.\n    { erewrite Memory.remove_o; eauto. condtac; ss.\n      { des. subst. congr. }\n      guardH o. hexploit Memory.split_get0; eauto. i. des. eauto.\n    }\n    i. des.\n    cut (mem4 = mem2); [by i; subst; eauto|].\n    apply Memory.ext. i.\n    erewrite Memory.split_o; eauto. erewrite Memory.remove_o; eauto.\n    erewrite (@Memory.remove_o mem2); eauto. erewrite (@Memory.split_o mem1); eauto.\n    repeat (condtac; ss).\n    - des. repeat subst. congr.\n    - guardH o. des. repeat subst. congr.\n  Qed.\n\n  Lemma split_remove_same\n        mem0 loc1 ts11 ts12 ts13 msg12 msg13\n        mem1 from2 msg2\n        mem2\n        (SPLIT1: Memory.split mem0 loc1 ts11 ts12 ts13 msg12 msg13 mem1)\n        (REMOVE2: Memory.remove mem1 loc1 from2 ts13 msg2 mem2):\n    from2 = ts12 /\\ msg13 = msg2 /\\\n    exists mem1',\n      <<REMOVE1: Memory.remove mem0 loc1 ts11 ts13 msg13 mem1'>> /\\\n      <<ADD2: Memory.add mem1' loc1 ts11 ts12 msg12 mem2>>.\n  Proof.\n    exploit Memory.split_get0; eauto. i. des.\n    exploit Memory.remove_get0; eauto. i. des.\n    rewrite GET3 in *. inv GET2. splits; auto.\n    exploit (@Memory.remove_exists mem0 loc1 ts11 ts13 msg13); eauto. i. des.\n    exploit (@Memory.add_exists mem3 loc1 ts11 ts12 msg12); eauto.\n    { ii. revert GET2.\n      erewrite Memory.remove_o; eauto. condtac; ss. i. des; ss.\n      exploit Memory.get_disjoint; [exact GET0|exact GET2|..]. i. des.\n      { subst. ss. }\n      inv LHS. inv RHS. ss.\n      apply (x2 x); econs; ss.\n      inv SPLIT1. inv SPLIT.\n      etrans; try exact TO. econs; ss. }\n    { inv SPLIT1. inv SPLIT. ss. }\n    { inv SPLIT1. inv SPLIT. ss. }\n    i. des. esplits; eauto.\n    cut (mem4 = mem2); [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.split_o mem1); eauto.\n    repeat (condtac; ss).\n    des. subst. congr.\n  Qed.\n\n  Lemma lower_add\n        mem0 loc1 from1 to1 msg1 msg1'\n        mem1 loc2 from2 to2 msg2\n        mem2\n        (LOWER1: Memory.lower mem0 loc1 from1 to1 msg1 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      <<LOWER2: Memory.lower mem1' loc1 from1 to1 msg1 msg1' mem2>> /\\\n      <<LOCTS: (loc1, to1) <> (loc2, to2)>>.\n  Proof.\n    exploit (@Memory.add_exists mem0 loc2 from2 to2);\n      try by inv ADD2; inv ADD; eauto.\n    { apply covered_disjoint_get_disjoint. i. rewrite <- lower_covered in H; eauto.\n      eapply get_disjoint_covered_disjoint; eauto. inv ADD2. inv ADD. auto.\n    }\n    i. des.\n    exploit (@Memory.lower_exists mem3 loc1 from1 to1);\n      try by inv LOWER1; inv LOWER; eauto.\n    { erewrite Memory.add_o; eauto. condtac; ss.\n      - des. subst. hexploit Memory.lower_get0; eauto. i. des.\n        hexploit Memory.add_get0; eauto. i. des. congr.\n      - guardH o. hexploit Memory.lower_get0; eauto. i. des. eauto.\n    }\n    i. des.\n    esplits; eauto; cycle 1.\n    { ii. inv H.\n      exploit Memory.lower_get0; try exact LOWER1; eauto. i. des.\n      exploit Memory.add_get0; eauto. i. des. congr.\n    }\n    cut (mem4 = mem2); [by i; subst; eauto|].\n    apply Memory.ext. i.\n    erewrite Memory.lower_o; eauto. erewrite Memory.add_o; eauto.\n    erewrite (@Memory.add_o mem2); eauto. erewrite (@Memory.lower_o mem1); eauto.\n    repeat (condtac; ss). des. repeat subst.\n    exploit Memory.add_get0; try exact ADD2; eauto. i. des.\n    revert GET. erewrite Memory.lower_o; eauto. condtac; ss.\n  Qed.\n\n  Lemma lower_split\n        mem0 loc1 from1 to1 msg1 msg1'\n        mem1 loc2 ts21 ts22 ts23 msg22 msg23\n        mem2\n        (LOWER1: Memory.lower mem0 loc1 from1 to1 msg1 msg1' mem1)\n        (SPLIT2: Memory.split mem1 loc2 ts21 ts22 ts23 msg22 msg23 mem2):\n    exists from1' msg23' mem1',\n      <<SPLIT1: Memory.split mem0 loc2 ts21 ts22 ts23 msg22 msg23' mem1'>> /\\\n      <<LOWER2: Memory.lower mem1' loc1 from1' to1 msg1 msg1' mem2>> /\\\n      <<FROM1: __guard__ ((loc1, to1, from1', msg1', msg23') = (loc2, ts23, ts22, msg23, msg1) \\/\n                          ((loc1, to1) <> (loc2, ts23) /\\ (from1', msg23') = (from1, msg23)))>>.\n  Proof.\n    destruct (loc_ts_eq_dec (loc1, to1) (loc2, ts23)); ss.\n    - des. subst.\n      exploit Memory.split_get0; eauto. i. des.\n      revert GET0. erewrite Memory.lower_o; eauto. condtac; ss; cycle 1.\n      { des; congr. }\n      i. inv GET0.\n      exploit (@Memory.split_exists mem0 loc2 ts21 ts22 ts23);\n        try by inv SPLIT2; inv SPLIT; eauto.\n      { hexploit Memory.lower_get0; eauto. i. des. eauto. }\n      i. des.\n      exploit (@Memory.lower_exists mem3 loc2 ts22 ts23);\n        try by inv LOWER1; inv LOWER; eauto.\n      { erewrite Memory.split_o; eauto. repeat condtac; ss.\n        ss. des. subst. inv SPLIT2. inv SPLIT.\n        exfalso. eapply Time.lt_strorder. eauto.\n      }\n      { inv SPLIT2. inv SPLIT. auto. }\n      i. des.\n      esplits; eauto; cycle 1.\n      { left. eauto. }\n      cut (mem4 = mem2); [by i; subst; eauto|].\n      apply Memory.ext. i.\n      erewrite Memory.lower_o; eauto. erewrite Memory.split_o; eauto.\n      erewrite (@Memory.split_o mem2); eauto. erewrite (@Memory.lower_o mem1); eauto.\n      repeat (condtac; ss).\n      des. repeat subst.\n      revert GET. erewrite Memory.lower_o; eauto. condtac; ss.\n    - guardH o.\n      exploit Memory.split_get0; eauto. i. des.\n      exploit (@Memory.split_exists mem0 loc2 ts21 ts22 ts23);\n        try by inv SPLIT2; inv SPLIT; eauto.\n      { revert GET0. erewrite Memory.lower_o; eauto. condtac; eauto.\n        ss. i. des. inv GET0. unguardH o. des; congr.\n      }\n      i. des.\n      exploit (@Memory.lower_exists mem3 loc1 from1 to1);\n        try by inv LOWER1; inv LOWER; eauto.\n      { erewrite Memory.split_o; eauto. repeat condtac; ss.\n        - des. subst. hexploit Memory.split_get0; eauto.\n          hexploit Memory.lower_get0; eauto. i. des. congr.\n        - guardH o0. des. subst.\n          unguardH o. des; congr.\n        - guardH o0. guardH o1. hexploit Memory.lower_get0; eauto. i. des. eauto.\n      }\n      i. des.\n      esplits; eauto; cycle 1.\n      { right. splits; eauto. ii. inv H. unguardH o. des; congr. }\n      cut (mem4 = mem2); [by i; subst; eauto|].\n      apply Memory.ext. i.\n      erewrite Memory.lower_o; eauto. erewrite Memory.split_o; eauto.\n      erewrite (@Memory.split_o mem2); eauto. erewrite (@Memory.lower_o mem1); eauto.\n      repeat (condtac; ss).\n      + des. repeat subst.\n        revert GET. erewrite Memory.lower_o; eauto. condtac; ss.\n      + guardH o0. des. repeat subst. unguardH o. des; congr.\n  Qed.\n\n  Lemma lower_lower\n        mem0 loc1 from1 to1 msg1 msg1'\n        mem1 loc2 from2 to2 msg2 msg2'\n        mem2\n        (LOWER1: Memory.lower mem0 loc1 from1 to1 msg1 msg1' mem1)\n        (LOWER2: Memory.lower mem1 loc2 from2 to2 msg2 msg2' mem2):\n    (loc1 = loc2 /\\ from1 = from2 /\\ to1 = to2 /\\ msg1' = msg2 /\\\n     Memory.lower mem0 loc1 from1 to1 msg1 msg2' mem2) \\/\n    (<<LOCTS1: (loc1, to1) <> (loc2, to2)>> /\\\n     exists mem1',\n       <<LOWER1: Memory.lower mem0 loc2 from2 to2 msg2 msg2' mem1'>> /\\\n       <<LOWER2: Memory.lower mem1' loc1 from1 to1 msg1 msg1' mem2>>).\n  Proof.\n    exploit Memory.lower_get0; eauto. i. des.\n    revert GET. erewrite Memory.lower_o; eauto. condtac; ss.\n    - des. subst. i. inv GET. left. splits; eauto.\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    - guardH o. i. right. splits.\n      { ii. inv H. unguardH o. des; congr. }\n      exploit (@Memory.lower_exists mem0 loc2 from2 to2);\n        try by inv LOWER2; inv LOWER; eauto.\n      i. des.\n      exploit (@Memory.lower_exists mem3 loc1 from1 to1);\n        try by inv LOWER1; inv LOWER; eauto.\n      { erewrite Memory.lower_o; eauto. condtac; ss.\n        - des. subst. unguardH o. des; congr.\n        - guardH o0. hexploit Memory.lower_get0; try exact LOWER1; eauto. i. des. eauto.\n      }\n      i. des.\n      esplits; eauto.\n      cut (mem4 = mem2); [by i; subst; eauto|].\n      apply Memory.ext. i.\n      erewrite Memory.lower_o; eauto. erewrite Memory.lower_o; eauto.\n      erewrite (@Memory.lower_o mem2); eauto. erewrite (@Memory.lower_o mem1); eauto.\n      repeat (condtac; ss). des. repeat subst.\n      unguardH o. des; congr.\n  Qed.\n\n  Lemma lower_remove\n        mem0 loc1 from1 to1 msg1 msg1'\n        mem1 loc2 from2 to2 msg2\n        mem2\n        (LOCTS1: (loc1, to1) <> (loc2, to2))\n        (LOWER1: Memory.lower mem0 loc1 from1 to1 msg1 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      <<LOWER2: Memory.lower mem1' loc1 from1 to1 msg1 msg1' mem2>>.\n  Proof.\n    exploit (@Memory.remove_exists mem0 loc2 from2 to2).\n    { hexploit Memory.remove_get0; eauto. i. des.\n      revert GET. erewrite Memory.lower_o; eauto. condtac; ss.\n      { des. subst. congr. }\n      eauto.\n    }\n    i. des.\n    exploit (@Memory.lower_exists mem3 loc1 from1 to1);\n      try by inv LOWER1; inv LOWER; eauto.\n    { erewrite Memory.remove_o; eauto. condtac; ss.\n      { des. subst. congr. }\n      inv LOWER1. inv LOWER. eauto.\n    }\n    i. des.\n    cut (mem4 = mem2); [by i; subst; eauto|].\n    apply Memory.ext. i.\n    erewrite Memory.lower_o; eauto. erewrite Memory.remove_o; eauto.\n    erewrite (@Memory.remove_o mem2); eauto. erewrite (@Memory.lower_o mem1); eauto.\n    repeat (condtac; ss). des. repeat subst. congr.\n  Qed.\n\n  Lemma lower_remove_same\n        mem0 loc1 from1 to1 msg1 msg1'\n        mem1 from2 msg2\n        mem2\n        (LOWER1: Memory.lower mem0 loc1 from1 to1 msg1 msg1' mem1)\n        (REMOVE2: Memory.remove mem1 loc1 from2 to1 msg2 mem2):\n    from1 = from2 /\\ msg1' = msg2 /\\\n    <<REMOVE1: Memory.remove mem0 loc1 from1 to1 msg1 mem2>>.\n  Proof.\n    exploit Memory.lower_get0; eauto. i. des.\n    exploit Memory.remove_get0; eauto. i. des.\n    rewrite GET1 in *. inv GET0. splits; auto.\n    exploit (@Memory.remove_exists mem0 loc1 from1 to1 msg1); eauto. i. des.\n    cut (mem3 = mem2); [i; subst; eauto|].\n    apply Memory.ext. i.\n    erewrite Memory.remove_o; eauto.\n    erewrite (@Memory.remove_o mem2); try exact REMOVE2.\n    erewrite (@Memory.lower_o mem1); eauto.\n    repeat (condtac; ss).\n  Qed.\n\n  Lemma remove_add\n        mem0 loc1 from1 to1 msg1\n        mem1 loc2 from2 to2 msg2\n        mem2\n        mem1'\n        (REMOVE1: Memory.remove mem0 loc1 from1 to1 msg1 mem1)\n        (ADD2: Memory.add mem1 loc2 from2 to2 msg2 mem2)\n        (ADD1: Memory.add mem0 loc2 from2 to2 msg2 mem1'):\n    Memory.remove mem1' loc1 from1 to1 msg1 mem2.\n  Proof.\n    exploit Memory.remove_get0; try eexact REMOVE1; eauto. i. des.\n    exploit (@Memory.remove_exists mem1' loc1 from1 to1 msg1); eauto.\n    { erewrite Memory.add_o; eauto. condtac; ss; eauto.\n      des. subst. exploit Memory.add_get0; eauto. i. des. congr.\n    }\n    i. des.\n    cut (mem3 = mem2); [by i; subst|].\n    apply Memory.ext. i.\n    erewrite Memory.remove_o; eauto. erewrite Memory.add_o; eauto.\n    erewrite (@Memory.add_o mem2); eauto. erewrite (@Memory.remove_o mem1); eauto.\n    repeat (condtac; ss). des. subst. subst.\n    exploit Memory.add_get0; try eexact ADD1; eauto. i. des. congr.\n  Qed.\n\n  Lemma remove_split\n        mem0 loc1 from1 to1 msg1\n        mem1 loc2 ts21 ts22 ts23 msg22 msg23\n        mem2\n        mem1'\n        (REMOVE1: Memory.remove mem0 loc1 from1 to1 msg1 mem1)\n        (SPLIT2: Memory.split mem1 loc2 ts21 ts22 ts23 msg22 msg23 mem2)\n        (SPLIT1: Memory.split mem0 loc2 ts21 ts22 ts23 msg22 msg23 mem1'):\n    Memory.remove mem1' loc1 from1 to1 msg1 mem2.\n  Proof.\n    exploit Memory.remove_get0; try eexact REMOVE1; eauto. i. des.\n    exploit Memory.split_get0; try exact SPLIT1; eauto. i. des.\n    exploit (@Memory.remove_exists mem1' loc1 from1 to1 msg1); eauto.\n    { erewrite Memory.split_o; eauto. repeat condtac; ss.\n      - des. subst. congr.\n      - guardH o. des. subst. rewrite GET0 in GET0. inv GET0.\n        exploit Memory.split_get0; try exact SPLIT2; eauto. i. des.\n        revert GET5. erewrite Memory.remove_o; eauto. condtac; ss.\n    }\n    i. des.\n    cut (mem3 = mem2); [by i; subst|].\n    apply Memory.ext. i.\n    erewrite Memory.remove_o; eauto. erewrite Memory.split_o; eauto.\n    erewrite (@Memory.split_o mem2); eauto. erewrite (@Memory.remove_o mem1); eauto.\n    repeat (condtac; ss).\n    - des; congr.\n    - guardH o. des. subst. rewrite GET in GET2. inv GET2.\n      exploit Memory.remove_get0; try exact GET1; eauto. i. des.\n      revert GET2. erewrite Memory.split_o; eauto. repeat condtac; ss. i. inv GET2.\n      inv SPLIT1. inv SPLIT. exfalso. eapply Time.lt_strorder. eauto.\n  Qed.\n\n  Lemma remove_lower\n        mem0 loc1 from1 to1 msg1\n        mem1 loc2 from2 to2 msg2' msg2\n        mem2\n        mem1'\n        (REMOVE1: Memory.remove mem0 loc1 from1 to1 msg1 mem1)\n        (LOWER2: Memory.lower mem1 loc2 from2 to2 msg2' msg2 mem2)\n        (LOWER1: Memory.lower mem0 loc2 from2 to2 msg2' msg2 mem1'):\n    Memory.remove mem1' loc1 from1 to1 msg1 mem2.\n  Proof.\n    exploit Memory.remove_get0; try eexact REMOVE1; eauto. i. des.\n    exploit (@Memory.remove_exists mem1' loc1 from1 to1 msg1); eauto.\n    { erewrite Memory.lower_o; eauto. condtac; ss.\n      des. subst.\n      exploit Memory.lower_get0; try exact LOWER2; eauto. i. des.\n      revert GET1. erewrite Memory.remove_o; eauto. condtac; ss.\n    }\n    i. des.\n    cut (mem3 = mem2); [by i; subst|].\n    apply Memory.ext. i.\n    erewrite Memory.remove_o; eauto. erewrite Memory.lower_o; eauto.\n    erewrite (@Memory.lower_o mem2); eauto. erewrite (@Memory.remove_o mem1); eauto.\n    repeat (condtac; ss). des. repeat subst.\n    exploit Memory.lower_get0; try exact LOWER2; eauto. i. des.\n    revert GET1. erewrite Memory.remove_o; eauto. condtac; ss.\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.\n\n\n  (* Lemmas on promise *)\n\n  Lemma promise_add_remove\n        loc1 from1 to1 msg1\n        loc2 from2 to2 msg2\n        promises0 mem0\n        promises1 mem1\n        promises2\n        (LOCTS1: (loc1, to1) <> (loc2, to2))\n        (PROMISE1: Memory.promise promises0 mem0 loc1 from1 to1 msg1 promises1 mem1 Memory.op_kind_add)\n        (REMOVE2: Memory.remove promises1 loc2 from2 to2 msg2 promises2):\n    exists promises1',\n      <<REMOVE1: Memory.remove promises0 loc2 from2 to2 msg2 promises1'>> /\\\n      <<PROMISE2: Memory.promise promises1' mem0 loc1 from1 to1 msg1 promises2 mem1 Memory.op_kind_add>>.\n  Proof.\n    inv PROMISE1.\n    exploit add_remove; try exact PROMISES; eauto. i. des.\n    esplits; eauto.\n  Qed.\n\n  Lemma promise_split_remove\n        loc1 from1 to1 msg1\n        loc2 from2 to2 msg2\n        to3 msg3\n        promises0 mem0\n        promises1 mem1\n        promises2\n        (LOCTS1: (loc1, to1) <> (loc2, to2))\n        (LOCTS2: (loc1, to3) <> (loc2, to2))\n        (PROMISE1: Memory.promise promises0 mem0 loc1 from1 to1 msg1 promises1 mem1 (Memory.op_kind_split to3 msg3))\n        (REMOVE2: Memory.remove promises1 loc2 from2 to2 msg2 promises2):\n    exists promises1',\n      <<REMOVE1: Memory.remove promises0 loc2 from2 to2 msg2 promises1'>> /\\\n      <<PROMISE2: Memory.promise promises1' mem0 loc1 from1 to1 msg1 promises2 mem1 (Memory.op_kind_split to3 msg3)>>.\n  Proof.\n    inv PROMISE1.\n    exploit split_remove; try exact PROMISES; eauto. i. des.\n    esplits; eauto. econs; eauto.\n  Qed.\n\n  Lemma promise_lower_remove\n        loc1 from1 to1 msg0 msg1\n        loc2 from2 to2 msg2\n        promises0 mem0\n        promises1 mem1\n        promises2\n        (LOCTS1: (loc1, to1) <> (loc2, to2))\n        (PROMISE1: Memory.promise promises0 mem0 loc1 from1 to1 msg1 promises1 mem1 (Memory.op_kind_lower msg0))\n        (REMOVE2: Memory.remove promises1 loc2 from2 to2 msg2 promises2):\n    exists promises1',\n      <<REMOVE1: Memory.remove promises0 loc2 from2 to2 msg2 promises1'>> /\\\n      <<PROMISE2: Memory.promise promises1' mem0 loc1 from1 to1 msg1 promises2 mem1 (Memory.op_kind_lower msg0)>>.\n  Proof.\n    inv PROMISE1.\n    exploit lower_remove; try exact PROMISES; eauto. i. des.\n    esplits; eauto.\n  Qed.\n\n  Lemma remove_promise\n        promises1 loc1 from1 to1 msg1\n        promises2 loc2 from2 to2 msg2\n        promises3\n        mem1 mem3\n        kind\n        (LE: Memory.le promises1 mem1)\n        (REMOVE: Memory.remove promises1 loc1 from1 to1 msg1 promises2)\n        (PROMISE: Memory.promise promises2 mem1 loc2 from2 to2 msg2 promises3 mem3 kind):\n    exists promises2',\n      Memory.promise promises1 mem1 loc2 from2 to2 msg2 promises2' mem3 kind /\\\n      Memory.remove promises2' loc1 from1 to1 msg1 promises3.\n  Proof.\n    inv PROMISE.\n    - exploit Memory.add_exists_le; eauto. i. des.\n      exploit remove_add; eauto.\n    - exploit Memory.split_get0; try eexact PROMISES; eauto. i. des.\n      revert GET0. erewrite Memory.remove_o; eauto. condtac; ss. i. guardH o.\n      exploit Memory.split_exists; try exact GET0; try by inv PROMISES; inv SPLIT; eauto. i. des.\n      exploit remove_split; eauto. i.\n      esplits; eauto. econs; eauto.\n    - exploit Memory.lower_get0; try eexact PROMISES; eauto. i. des.\n      revert GET. erewrite Memory.remove_o; eauto. condtac; ss. i. guardH o.\n      exploit Memory.lower_exists; try exact GET; try by inv PROMISES; inv LOWER; eauto. i. des.\n      exploit remove_lower; eauto. i.\n      esplits; eauto.\n    - exploit remove_remove; try exact REMOVE; eauto. i. des. eauto.\n  Qed.\n\n  Lemma promise_add_promise_split_same\n        promises0 mem0 loc ts1 ts2 ts3 msg2 msg3\n        promises1 mem1\n        promises2 mem2\n        (ADD1: Memory.promise promises0 mem0 loc ts1 ts3 msg3 promises1 mem1 Memory.op_kind_add)\n        (SPLIT2: Memory.promise promises1 mem1 loc ts1 ts2 msg2 promises2 mem2 (Memory.op_kind_split ts3 msg3)):\n    exists promises1' mem1',\n      <<ADD1: Memory.promise promises0 mem0 loc ts1 ts2 msg2 promises1' mem1' Memory.op_kind_add>> /\\\n      <<ADD2: Memory.promise promises1' mem1' loc ts2 ts3 msg3 promises2 mem2 Memory.op_kind_add>>.\n  Proof.\n    inv ADD1. inv SPLIT2.\n    exploit add_split; try exact PROMISES; eauto. i. des; [|congr].\n    exploit add_split; try exact MEM; eauto. i. des; [|congr].\n    esplits.\n    - econs; eauto.\n      i. exploit Memory.add_get0; try exact MEM. i. des.\n      exploit Memory.add_get1; try exact GET; try exact MEM. i.\n      exploit Memory.get_ts; try exact GET1. i. des.\n      { subst. inv ADD3. inv ADD. inv TO. }\n      exploit Memory.get_ts; try exact x8. i. des.\n      { subst. inv ADD0. inv ADD. inv TO. }\n      exploit Memory.get_disjoint; [exact GET1|exact x8|..]. i. des.\n      { subst. inv ADD0. inv ADD. timetac. }\n      destruct (TimeFacts.le_lt_dec ts3 to').\n      + apply (x11 ts3); econs; ss; try refl.\n        inv ADD3. inv ADD. ss.\n      + apply (x11 to'); econs; ss; try refl.\n        { etrans; try exact x10. inv ADD0. inv ADD. ss. }\n        { econs. ss. }\n    - econs; eauto.\n      i. revert GET.\n      erewrite Memory.add_o; eauto. condtac; ss; eauto.\n      i. des. subst. inv GET. inv MEM. inv ADD. timetac.\n  Qed.\n\n  Lemma promise_split_promise_split_same\n        promises0 mem0 loc ts1 ts2 ts3 ts4 val2 released2 msg3 msg4\n        promises1 mem1\n        promises2 mem2\n        (SPLIT1: Memory.promise promises0 mem0 loc ts1 ts3 msg3 promises1 mem1 (Memory.op_kind_split ts4 msg4))\n        (SPLIT2: Memory.promise promises1 mem1 loc ts1 ts2 (Message.concrete val2 released2) promises2 mem2 (Memory.op_kind_split ts3 msg3)):\n    exists promises1' mem1',\n      <<SPLIT1: Memory.promise promises0 mem0 loc ts1 ts2 (Message.concrete val2 released2) promises1' mem1' (Memory.op_kind_split ts4 msg4)>> /\\\n      <<SPLIT2: Memory.promise promises1' mem1' loc ts2 ts3 msg3 promises2 mem2 (Memory.op_kind_split ts4 msg4)>>.\n  Proof.\n    assert (LOCTS: (loc, ts4) <> (loc, ts3)).\n    { intro X. inv X. inv SPLIT1. inv MEM. inv SPLIT. timetac. }\n    inv SPLIT1. inv SPLIT2.\n    exploit split_split; try exact PROMISES; eauto. i. des; [|congr].\n    exploit split_split; try exact MEM; eauto. i. des; [|congr].\n    esplits.\n    - econs; eauto; congr.\n    - econs; eauto.\n  Qed.\n\n  Lemma promise_lower_promise_split_same\n        promises0 mem0 loc ts1 ts2 ts3 msg0 val2 released2 msg3\n        promises1 mem1\n        promises2 mem2\n        (LOWER1: Memory.promise promises0 mem0 loc ts1 ts3 msg3 promises1 mem1 (Memory.op_kind_lower msg0))\n        (SPLIT2: Memory.promise promises1 mem1 loc ts1 ts2 (Message.concrete val2 released2) promises2 mem2 (Memory.op_kind_split ts3 msg3)):\n    exists promises1' mem1',\n      <<SPLIT1: Memory.promise promises0 mem0 loc ts1 ts2 (Message.concrete val2 released2) promises1' mem1' (Memory.op_kind_split ts3 msg0)>> /\\\n      <<LOWER2: Memory.promise promises1' mem1' loc ts2 ts3 msg3 promises2 mem2 (Memory.op_kind_lower msg0)>>.\n  Proof.\n    inv LOWER1. inv SPLIT2.\n    exploit lower_split; try exact PROMISES; eauto. i. des.\n    unguard. des; [|congr]. inv FROM1.\n    exploit lower_split; try exact MEM; eauto. i. des.\n    unguard. des; [|congr]. inv FROM1.\n    esplits.\n    - econs; eauto; congr.\n    - econs; eauto.\n  Qed.\nEnd MemoryReorder.\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/MemoryReorder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2657990631950264}}
{"text": "Require Forcing.\n\nSet Primitive Projections.\n\nSection Sigma.\n\nVariable Obj : Type.\nVariable Hom : Obj -> Obj -> Type.\n\nNotation \"P ≤ Q\" := (forall R, Hom Q R -> Hom P R) (at level 70).\nNotation \"#\" := (fun (R : Obj) (k : Hom _ R) => k).\nNotation \"f ∘ g\" := (fun (R : Obj) (k : Hom _ R) => f R (g R k)) (at level 40).\n\nForcing Translate sigT using Obj Hom.\n\nDefinition sig_rec : forall A (B:A -> Type) P, (forall a:A, B a -> P) -> sigT B -> P :=\n  fun A B P f x => match x with existT _ a b => f a b end.\n\nForcing Translate sig_rec using Obj Hom.\n\nDefinition sig_mem A (B:A -> Type) : forall R, sigT B -> (sigT B -> R) -> R:=\n  fun R x => sig_rec A B (({x : A & B x} -> R) -> R) (fun a b k => k (existT _ a b)) x.\n\nForcing Translate sig_mem using Obj Hom.\n\nForcing Definition sig_rect' : forall A (B:A -> Type) P,\n    (forall (a:A) (b: B a), P (existT _ a b)) -> forall (x : sigT B), sig_mem A B _ x P\n                                                     using Obj Hom.\nintros p A B P H x.\ncompute. generalize (x p #).\nexact (fun x => match x with\n        | existTᶠ _ _ _ a b => H p # a b\n                end).\n(* Universe issue *)\nShow Proof.\nAbort.\n\nForcing Definition sig_rect' : forall A (B:A -> Type) P,\n    (forall (a:A) (b: B a), P (existT _ a b)) -> forall (x : sigT B), sig_mem A B _ x P\n                                                     using Obj Hom.\n\nexact (fun (p : Obj)\n   (A : forall p0 : Obj, p ≤ p0 -> forall p1 : Obj, p0 ≤ p1 -> Type)\n   (B : forall (p0 : Obj) (α : p ≤ p0),\n        (forall (p1 : Obj) (α0 : p0 ≤ p1),\n         A p1 (# ∘ (α ∘ (# ∘ (α0 ∘ #)))) p1 #) ->\n        forall p1 : Obj, p0 ≤ p1 -> Type)\n   (P : forall (p0 : Obj) (α : p ≤ p0),\n        (forall (p1 : Obj) (α0 : p0 ≤ p1),\n         (fun\n            (A0 : forall p2 : Obj,\n                  p1 ≤ p2 -> forall p3 : Obj, p2 ≤ p3 -> Type)\n            (P : forall (p2 : Obj) (α1 : p1 ≤ p2),\n                 (forall (p3 : Obj) (α2 : p2 ≤ p3),\n                  A0 p3 (α1 ∘ (# ∘ (α2 ∘ #))) p3 #) ->\n                 forall p3 : Obj, p2 ≤ p3 -> Type) \n            (p2 : Obj) (α1 : p1 ≤ p2) =>\n          sigTᶠ p2\n            (fun (p3 : Obj) (α2 : p2 ≤ p3) => A0 p3 (α1 ∘ (α2 ∘ #)))\n            (fun (p3 : Obj) (α2 : p2 ≤ p3) => P p3 (α1 ∘ (α2 ∘ #))))\n           (fun (p2 : Obj) (α1 : p1 ≤ p2) =>\n            A p2 (# ∘ (# ∘ (α ∘ (# ∘ (α0 ∘ (α1 ∘ #)))))))\n           (fun (p2 : Obj) (α1 : p1 ≤ p2) =>\n            B p2 (# ∘ (α ∘ (# ∘ (α0 ∘ (α1 ∘ #)))))) p1 \n           #) -> forall p1 : Obj, p0 ≤ p1 -> Type)\n   (H : forall (p0 : Obj) (α : p ≤ p0)\n          (a : forall (p1 : Obj) (α0 : p0 ≤ p1),\n               A p1 (# ∘ (# ∘ (# ∘ (α ∘ (# ∘ (α0 ∘ #)))))) p1 #)\n          (b : forall (p1 : Obj) (α0 : p0 ≤ p1),\n               B p1 (# ∘ (# ∘ (α ∘ (# ∘ (# ∘ (α0 ∘ #))))))\n                 (fun (p2 : Obj) (α1 : p1 ≤ p2) =>\n                  a p2 (# ∘ (α0 ∘ (α1 ∘ #)))) p1 \n                 #),\n        P p0 (# ∘ (α ∘ (# ∘ (# ∘ #))))\n          (fun (p1 : Obj) (α0 : p0 ≤ p1) =>\n           existTᶠ p1\n             (fun (p2 : Obj) (α1 : p1 ≤ p2) =>\n              A p2 (# ∘ (# ∘ (# ∘ (α ∘ (# ∘ (# ∘ (α0 ∘ (α1 ∘ #)))))))))\n             (fun (p2 : Obj) (α1 : p1 ≤ p2) =>\n              B p2 (# ∘ (# ∘ (α ∘ (# ∘ (# ∘ (α0 ∘ (α1 ∘ #))))))))\n             (fun (p2 : Obj) (α1 : p1 ≤ p2) => a p2 (# ∘ (α0 ∘ (α1 ∘ #))))\n             (fun (p2 : Obj) (α1 : p1 ≤ p2) => b p2 (α0 ∘ (α1 ∘ #)))) p0 \n          #)\n   (x : forall (p0 : Obj) (α : p ≤ p0),\n        (fun\n           (A0 : forall p1 : Obj,\n                 p0 ≤ p1 -> forall p2 : Obj, p1 ≤ p2 -> Type)\n           (P0 : forall (p1 : Obj) (α0 : p0 ≤ p1),\n                 (forall (p2 : Obj) (α1 : p1 ≤ p2),\n                  A0 p2 (α0 ∘ (# ∘ (α1 ∘ #))) p2 #) ->\n                 forall p2 : Obj, p1 ≤ p2 -> Type) \n           (p1 : Obj) (α0 : p0 ≤ p1) =>\n         sigTᶠ p1 (fun (p2 : Obj) (α1 : p1 ≤ p2) => A0 p2 (α0 ∘ (α1 ∘ #)))\n           (fun (p2 : Obj) (α1 : p1 ≤ p2) => P0 p2 (α0 ∘ (α1 ∘ #))))\n          (fun (p1 : Obj) (α0 : p0 ≤ p1) =>\n           A p1 (# ∘ (# ∘ (# ∘ (# ∘ (α ∘ (α0 ∘ #)))))))\n          (fun (p1 : Obj) (α0 : p0 ≤ p1) =>\n           B p1 (# ∘ (# ∘ (# ∘ (α ∘ (α0 ∘ #)))))) p0 \n          #) =>\n (fun\n    x0 : sigTᶠ p\n           (fun (p0 : Obj) (α : p ≤ p0) =>\n            A p0 (fun (R : Obj) (k : Hom p0 R) => α R k))\n           (fun (p0 : Obj) (α : p ≤ p0) =>\n            B p0 (fun (R : Obj) (k : Hom p0 R) => α R k)) =>\n  match\n    x0 as x1\n    return\n      (match x1 with\n       | existTᶠ _ _ _ a b =>\n           fun\n             k : forall (p0 : Obj) (α : p ≤ p0),\n                 (forall (p1 : Obj) (α0 : p0 ≤ p1),\n                  sigTᶠ p1\n                    (fun (p2 : Obj) (α1 : p1 ≤ p2) =>\n                     A p2\n                       (fun (R : Obj) (k : Hom p2 R) =>\n                        α R (α0 R (α1 R k))))\n                    (fun (p2 : Obj) (α1 : p1 ≤ p2)\n                       (x2 : forall (p3 : Obj) (α2 : p2 ≤ p3),\n                             A p3\n                               (fun (R : Obj) (k : Hom p3 R) =>\n                                α R (α0 R (α1 R (α2 R k)))) p3 \n                               #) =>\n                     B p2\n                       (fun (R : Obj) (k : Hom p2 R) =>\n                        α R (α0 R (α1 R k)))\n                       (fun (p3 : Obj) (α2 : p2 ≤ p3) =>\n                        x2 p3 (fun (R : Obj) (k : Hom p3 R) => α2 R k)))) ->\n                 forall p1 : Obj, p0 ≤ p1 -> Type =>\n           k p #\n             (fun (p0 : Obj) (α : p ≤ p0) =>\n              existTᶠ p0 (fun (p1 : Obj) (α0 : p0 ≤ p1) => A p1 (α ∘ α0))\n                (fun (p1 : Obj) (α0 : p0 ≤ p1)\n                   (x2 : forall (p2 : Obj) (α1 : p1 ≤ p2),\n                         A p2\n                           (fun (R : Obj) (k0 : Hom p2 R) =>\n                            α R (α0 R (α1 R k0))) p2 \n                           #) =>\n                 B p1 (α ∘ α0)\n                   (fun (p2 : Obj) (α1 : p1 ≤ p2) =>\n                    x2 p2 (fun (R : Obj) (k0 : Hom p2 R) => α1 R k0)))\n                (fun (p1 : Obj) (α0 : p0 ≤ p1) => a p1 (α ∘ α0))\n                (fun (p1 : Obj) (α0 : p0 ≤ p1) => b p1 (α ∘ α0)))\n       end\n         (fun (p0 : Obj) (α : p ≤ p0) =>\n          P p0 (fun (R : Obj) (k : Hom p0 R) => α R k)) p \n         #)\n  with\n  | existTᶠ _ _ _ a b => H p # a b\n  end) (x p #)).\nDefined. \n\nEnd Sigma.\n", "meta": {"author": "ppedrot", "repo": "coq-forcing", "sha": "2dec07e5781c6ba0e5d064d0e23f2d0f5272c1b6", "save_path": "github-repos/coq/ppedrot-coq-forcing", "path": "github-repos/coq/ppedrot-coq-forcing/coq-forcing-2dec07e5781c6ba0e5d064d0e23f2d0f5272c1b6/theories/Sigma.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.26573498633881704}}
{"text": "Require compcert.backend.LTL.\nRequire EventsX.\nRequire Import LocationsX.\n\nImport Coqlib.\nImport Integers.\nImport AST.\nImport Values.\nImport Memory.\nImport Globalenvs.\nImport EventsX.\nImport Smallstep.\nImport Locations.\nImport Conventions.\nExport LTL.\n\nSection WITHCONFIG.\nContext `{external_calls_prf: ExternalCalls}.\n\n(** Execution of LTL functions with Asm-style arguments (long long 64-bit integers NOT allowed) *)\n\nInductive initial_state (lm: locset) (p: LTL.program) (i: ident) (sg: signature) (args: list val) (m: mem): state -> Prop :=\n| initial_state_intro    \n    b\n    (Hb: Genv.find_symbol (Genv.globalenv p) i = Some b)\n    f\n    (Hf: Genv.find_funct_ptr (Genv.globalenv p) b = Some f)\n    (Hsig: sg = funsig f)\n    (Hargs: args = map (fun pa => Locmap.getpair pa lm) (loc_arguments sg))\n  :\n      initial_state lm p i sg args m (Callstate nil f lm m)\n.\n\nInductive final_state (lm: locset) (sg: signature): state -> (val * mem) -> Prop :=\n| final_state_intro\n    rs\n    v\n    (Hv: v = getpair (loc_result sg) rs)\n    (** Callee-save registers *)\n    (CALLEE_SAVE: forall r,\n       ~ In r destroyed_at_call ->\n       rs (R r) = lm (R r))\n    m :\n    final_state lm sg (Returnstate nil rs m) (v, m)\n.\n\nDefinition semantics\n           (lm: locset)\n           (p: LTL.program) (i: ident) (sg: signature) (args: list val) (m: mem) :=\n  Semantics (\n      LTL.step lm\n    ) (initial_state lm p i sg args m) (final_state lm sg) (Genv.globalenv p).\n\nEnd WITHCONFIG.\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/LTLX.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.265734986338817}}
{"text": "From Coq Require Import\n     String\n     Fin\n     Relations.\n\nFrom Equations Require Import Equations.\n\nFrom ITree Require Import\n     Indexed.Sum\n     Subevent.\n\nFrom CTree Require Import\n     CTree\n     Equ\n     SBisim\n     Core.Utils\n     Interp.State.\n\nFrom ExtLib Require Import\n     Maps\n     FMapAList\n     RelDec\n     String\n     Monad.\n\nFrom Coinduction Require Import\n     coinduction rel tactics.\n\nFrom DSL Require Import Vectors.\n\nImport MonadNotation EquNotations SBisimNotations.\nLocal Open Scope monad_scope.\nLocal Open Scope string_scope.\n\nSet Implicit Arguments.\nSet Contextual Implicit.\n\n(** Some general Sets needed for Systems work *)\nModule Type Systems.\n\n  Parameter uid: nat -> Set.      (** Principal *)\n  Parameter bytestring: Set.      (** ByteString *)\n  Parameter var : Set.            (** binders *)\n  Parameter channel: Type -> Set. (** Typed channels *)\n  \n  Parameter eqdec_bytestring: RelDec (@eq bytestring).\n  Parameter eqdec_var: RelDec (@eq var).\n  Parameter eqdec_channel: forall T, RelDec (@eq (channel T)).\n  Parameter eqdec_uid: forall t, RelDec (@eq (uid t)).\n  \n  Global Existing Instance eqdec_bytestring.\n  Global Existing Instance eqdec_var.\n  Global Existing Instance eqdec_channel.\n  Global Existing Instance eqdec_uid.\n\n  Parameter uid_coerce: forall t, uid t -> fin t.\n  Global Coercion uid_coerce: uid >-> fin.\n  Parameter fin_coerce: forall t, fin t -> uid t.\n  Global Coercion fin_coerce: fin >-> uid.\nEnd Systems.\n\nModule DistrSystem <: Systems.\n  \n  Definition uid := fin.\n\n  Definition uid_coerce t (a: uid t) := a.\n  Definition fin_coerce t (a: fin t) := a.\n\n  Equations reldec_uid: forall t, fin t -> fin t -> bool :=\n    reldec_uid F1 F1 := true;\n    reldec_uid (FS i) (FS j) := reldec_uid i j;\n    reldec_uid _ _ := false.\n  \n  (** Decidable UIDs *)\n  Global Instance eqdec_uid: forall t, RelDec (@eq (uid t)) := {\n      rel_dec a b := @reldec_uid t a b\n    }.\n  \n  Definition bytestring := nat.  \n  Global Instance eqdec_bytestring: RelDec (@eq bytestring) := _.\n  \n  Definition var : Set := string.     (** binders *)\n  Definition channel(T: Type) := nat. (** Typed channels *)\n\n  Definition eqdec_var: RelDec (@eq var) := _.\n  Definition eqdec_channel: forall T, RelDec (@eq (channel T)) :=\n    fun T => _.\n \nEnd DistrSystem.\n\nModule Messaging(S: Systems).\n  Import S.\n\n   (** Messages exchagend *)\n  Record Msg t := {\n      principal: uid t;\n      payload: bytestring\n    }.\n\n  (** Decidable messages *)\n  Global Instance eqdec_msg: forall t, RelDec (@eq (Msg t)) := {\n      rel_dec m1 m2 := match m1, m2 with\n                         {| principal := u1; payload := p1 |},\n                         {| principal := u2; payload := p2 |} =>\n                           andb (rel_dec u1 u2) (rel_dec p1 p2)\n                       end      \n    }.\n\n  (** A queue of messages *)\n  Definition queue t := list (Msg t).\n\n  (** A task is either running or returned *)\n  Inductive Task t (E: Type -> Type)(T: Type) :=\n  | Done (r: T)(q: queue t)\n  | Running (c: ctree E T)(q: queue t)\n  | Blocked (c: ctree E T)(q: queue t).\n\n  (** Network effects *)\n  Inductive Net(n: nat): Type -> Type :=\n  | Recv: Net n (Msg n)\n  | Send : (Msg n) -> Net n unit\n  | Broadcast: bytestring -> Net n unit.\n\n  Arguments Send {n}.\n  Arguments Recv {n}.\n  Arguments Broadcast {n}.\n  \n  Definition recv {E n} `{Net n -< E}: ctree E (Msg n) := trigger Recv.\n  Definition send {E n} `{Net n -< E}: Msg n -> ctree E unit :=\n    fun m => trigger (Send m).\n  Definition broadcast {E n} `{Net n -< E}: bytestring -> ctree E unit :=\n    fun bs => trigger (Broadcast bs).\n\n  Fixpoint num_done{E A m n}(a: vec m (Task n (Net n +' E) A)): nat :=\n    match a with\n    | ((Done _ _) :: ts) => S (num_done ts)\n    | ((Running _ _) :: ts) => num_done ts\n    | ((Blocked _ _) :: ts) => num_done ts\n    | [] => 0\n    end.\n\n  Fixpoint num_running{E A m n}(a: vec m (Task n E A)): nat :=\n    match a with\n    | ((Done _ _) :: ts) => num_running ts\n    | ((Running _ _) :: ts) => S (num_running ts)\n    | ((Blocked _ _) :: ts) => num_running ts\n    | [] => 0\n    end.\n  \nEnd Messaging.\n\nModule PKI(S: Systems).\n  Import S.\n  Context {n: nat}.\n\n  Definition Enc (p: uid n) := bytestring.\n  Definition Sig (p: uid n) := bytestring.\n  Definition Pub (p: uid n) := bytestring.\n  Definition Priv (p: uid n) := bytestring.\n  \n  Inductive PKI: Type -> Type :=\n  | EncPub(p: uid n)(k: Pub p)(plain: bytestring): PKI (Enc p)\n  | DecPriv(p: uid n)(k: Priv p)(cipher: Enc p): PKI bytestring\n  | SignPriv(p: uid n)(k: Priv p)(plain: bytestring): PKI (Sig p)\n  | CheckPub(p: uid n)(k: Pub p)(signed: Sig p): PKI bool.\n\n  Definition encrypt {E} `{PKI -< E} := embed EncPub.\n  Definition decrypt {E} `{PKI -< E} := embed DecPriv.\n  Definition sign {E} `{PKI -< E} := embed SignPriv.\n  Definition check {E} `{PKI -< E} := embed CheckPub.\nEnd PKI.\n\nModule Spawn(S: Systems).\n  Import S.\n\n  Inductive spawnE E : Type -> Type :=\n  | Spawn : forall T (c: channel T) (t: ctree (spawnE E +' E) T), spawnE E (channel T)\n  | Make: forall (T: Type), spawnE E (channel T)\n  | Block: forall T (c: channel T), spawnE E T.\n\n  Definition spawn {F E T} `{(spawnE F) -< E} (c: channel T)(t:ctree (spawnE F +' F) T) :=\n    trigger (@Spawn F T c t).\n  \n  Definition make {F E T} `{(spawnE F) -< E} :=\n    trigger (@Make F T).\n  \n  Definition block {F E} `{(spawnE F) -< E} {t} (c: channel t) :=\n    trigger (@Block F t c).\n  \nEnd Spawn.  \n\nModule Storage(S: Systems).\n  Import S Monads.\n\n  Definition Map_heap := Map_alist eqdec_var bytestring.\n  Global Existing Instance Map_heap.\n  \n  Notation heap := (alist var bytestring).\n  Notation Storage := (stateE heap).\n\n  Definition load {E} `{stateE heap -< E}(v: var): ctree E (option bytestring) :=\n    get >>= fun s => ret (lookup v s).\n\n  Definition store {E} `{Storage -< E}(v: var)(b: bytestring): ctree E unit :=\n    get >>= fun s => put (add v b s).\n\n  (** Evaluates, takes a single heap for all agents *)\n  Definition run_storage{E R m}(a: vec m (ctree (Storage +' E) R)):\n    stateT heap (fun T => vec m (ctree E T)) R :=\n    fun st => Vector.map (fun it => run_state it st) a.\n  \nEnd Storage.\n\nModule DistributedSystems(S: Systems).\n  Module St := Storage(S).\n  Module Mg := Messaging(S).\n  Import S Monads St Mg.\n\n  Variable (n: nat).\n  Definition proc := ctree (Net n +' Storage) void.\n\n  Definition mkproc{R}(t: ctree (Net n +' Storage) R): proc :=\n    CTree.iter (fun _ : unit =>\n            _ <- t ;;\n            Ret (@inl unit void tt))\n         tt.\n\n  Lemma proc_noret: forall (p: proc) x,\n      not (p ≅ Ret x).\n    intros _ [].\n  Defined.\n\n  Lemma mkproc_noret: forall R (t: ctree (Net n +' Storage) R) x,\n      not (@mkproc R t ≅ Ret x).\n    intros _ _ [].\n  Defined.\nEnd DistributedSystems.  \n", "meta": {"author": "elefthei", "repo": "reasoning-about-distributed-systems", "sha": "f85bccad8ce15dcac10ecdd9f6cec39a8e98a2d7", "save_path": "github-repos/coq/elefthei-reasoning-about-distributed-systems", "path": "github-repos/coq/elefthei-reasoning-about-distributed-systems/reasoning-about-distributed-systems-f85bccad8ce15dcac10ecdd9f6cec39a8e98a2d7/denotational/System.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150636, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.26573153597839505}}
{"text": "Require Import Frap Setoid Classes.Morphisms SepCancel.\n\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\n\n(** * Shared notations and definitions; main material starts afterward. *)\n\nNotation heap := (fmap nat nat).\nNotation locks := (set nat).\n\nLocal Hint Extern 1 (_ <= _) => linear_arithmetic : core.\nLocal Hint Extern 1 (@eq nat _ _) => linear_arithmetic : core.\n\nLtac simp := repeat (simplify; subst; propositional;\n                     try match goal with\n                         | [ H : ex _ |- _ ] => invert H\n                         end); try linear_arithmetic.\n\n\n(** * A shared-memory concurrent language with loops *)\n\nInductive loop_outcome acc :=\n| Done (a : acc)\n| Again (a : acc).\n\nDefinition valueOf {A} (o : loop_outcome A) :=\n  match o with\n  | Done v => v\n  | Again v => v\n  end.\n\nInductive cmd : Set -> Type :=\n| Return {result : Set} (r : result) : cmd result\n| Fail {result} : cmd result\n| Bind {result result'} (c1 : cmd result') (c2 : result' -> cmd result) : cmd result\n| Loop {acc : Set} (init : acc) (body : acc -> cmd (loop_outcome acc)) : cmd acc\n\n| Read (a : nat) : cmd nat\n| Write (a v : nat) : cmd unit\n| Lock (a : nat) : cmd unit\n| Unlock (a : nat) : cmd unit\n| Alloc (numWords : nat) : cmd nat\n| Free (base numWords : nat) : cmd unit\n\n| Par (c1 c2 : cmd unit) : cmd unit.\n\nNotation \"x <- c1 ; c2\" := (Bind c1 (fun x => c2)) (right associativity, at level 80).\nNotation \"'for' x := i 'loop' c1 'done'\" := (Loop i (fun x => c1)) (right associativity, at level 80).\nInfix \"||\" := Par.\n\nFixpoint initialize (h : heap) (base numWords : nat) : heap :=\n  match numWords with\n  | O => h\n  | S numWords' => initialize h base numWords' $+ (base + numWords', 0)\n  end.\n\nFixpoint deallocate (h : heap) (base numWords : nat) : heap :=\n  match numWords with\n  | O => h\n  | S numWords' => deallocate (h $- base) (base+1) numWords'\n  end.\n\nInductive step : forall A, heap * locks * cmd A -> heap * locks * cmd A -> Prop :=\n| StepBindRecur : forall result result' (c1 c1' : cmd result') (c2 : result' -> cmd result) h l h' l',\n  step (h, l, c1) (h', l', c1')\n  -> step (h, l, Bind c1 c2) (h', l', Bind c1' c2)\n| StepBindProceed : forall (result result' : Set) (v : result') (c2 : result' -> cmd result) h l,\n  step (h, l, Bind (Return v) c2) (h, l, c2 v)\n\n| StepLoop : forall (acc : Set) (init : acc) (body : acc -> cmd (loop_outcome acc)) h l,\n  step (h, l, Loop init body) (h, l, o <- body init; match o with\n                                                     | Done a => Return a\n                                                     | Again a => Loop a body\n                                                     end)\n\n| StepRead : forall h l a v,\n  h $? a = Some v\n  -> step (h, l, Read a) (h, l, Return v)\n| StepWrite : forall h l a v v',\n  h $? a = Some v\n  -> step (h, l, Write a v') (h $+ (a, v'), l, Return tt)\n| StepAlloc : forall h l numWords a,\n  a <> 0\n  -> (forall i, i < numWords -> h $? (a + i) = None)\n  -> step (h, l, Alloc numWords) (initialize h a numWords, l, Return a)\n| StepFree : forall h l a numWords,\n  step (h, l, Free a numWords) (deallocate h a numWords, l, Return tt)\n\n| StepLock : forall h l a,\n  ~a \\in l\n  -> step (h, l, Lock a) (h, l \\cup {a}, Return tt)\n| StepUnlock : forall h l a,\n  a \\in l\n  -> step (h, l, Unlock a) (h, l \\setminus {a}, Return tt)\n\n| StepPar1 : forall h l c1 c2 h' l' c1',\n  step (h, l, c1) (h', l', c1')\n  -> step (h, l, Par c1 c2) (h', l', Par c1' c2)\n| StepPar2 : forall h l c1 c2 h' l' c2',\n  step (h, l, c2) (h', l', c2')\n  -> step (h, l, Par c1 c2) (h', l', Par c1 c2').\n    \nDefinition trsys_of (h : heap) (l : locks) {result} (c : cmd result) := {|\n  Initial := {(h, l, c)};\n  Step := step (A := result)\n|}.\n\nModule Import S <: SEP.\n  Definition hprop := heap -> Prop.\n  (* We add the locks to the mix. *)\n\n  Definition himp (p q : hprop) := forall h, p h -> q h.\n  Definition heq (p q : hprop) := forall h, p h <-> q h.\n\n  (* Lifting a pure proposition: it must hold, and the heap must be empty. *)\n  Definition lift (P : Prop) : hprop :=\n    fun h => P /\\ h = $0.\n\n  (* Separating conjunction, one of the two big ideas of separation logic.\n   * When does [star p q] apply to [h]?  When [h] can be partitioned into two\n   * subheaps [h1] and [h2], respectively compatible with [p] and [q].  See book\n   * module [Map] for definitions of [split] and [disjoint]. *)\n  Definition star (p q : hprop) : hprop :=\n    fun h => exists h1 h2, split h h1 h2 /\\ disjoint h1 h2 /\\ p h1 /\\ q h2.\n\n  (* Existential quantification *)\n  Definition exis A (p : A -> hprop) : hprop :=\n    fun h => exists x, p x h.\n\n  (* Convenient notations *)\n  Notation \"[| P |]\" := (lift P) : sep_scope.\n  Infix \"*\" := star : sep_scope.\n  Notation \"'exists' x .. y , p\" := (exis (fun x => .. (exis (fun y => p)) ..)) : sep_scope.\n  Delimit Scope sep_scope with sep.\n  Notation \"p === q\" := (heq p%sep q%sep) (no associativity, at level 70).\n  Notation \"p ===> q\" := (himp p%sep q%sep) (no associativity, at level 70).\n\n  Local Open Scope sep_scope.\n\n  (* And now we prove some key algebraic properties, whose details aren't so\n   * important.  The library automation uses these properties. *)\n\n  Lemma iff_two : forall A (P Q : A -> Prop),\n    (forall x, P x <-> Q x)\n    -> (forall x, P x -> Q x) /\\ (forall x, Q x -> P x).\n  Proof.\n    firstorder.\n  Qed.\n\n  Local Ltac t := (unfold himp, heq, lift, star, exis; propositional; subst);\n                 repeat (match goal with\n                         | [ H : forall x, _ <-> _ |- _  ] =>\n                           apply iff_two in H\n                         | [ H : ex _ |- _ ] => destruct H\n                         | [ H : split _ _ $0 |- _ ] => apply split_empty_fwd in H\n                         end; propositional; subst); eauto 15.\n\n  Theorem himp_heq : forall p q, p === q\n    <-> (p ===> q /\\ q ===> p).\n  Proof.\n    t.\n  Qed.\n\n  Theorem himp_refl : forall p, p ===> p.\n  Proof.\n    t.\n  Qed.\n\n  Theorem himp_trans : forall p q r, p ===> q -> q ===> r -> p ===> r.\n  Proof.\n    t.\n  Qed.\n\n  Theorem lift_left : forall p (Q : Prop) r,\n    (Q -> p ===> r)\n    -> p * [| Q |] ===> r.\n  Proof.\n    t.\n  Qed.\n\n  Theorem lift_right : forall p q (R : Prop),\n    p ===> q\n    -> R\n    -> p ===> q * [| R |].\n  Proof.\n    t.\n  Qed.\n\n  Local Hint Resolve split_empty_bwd' : core.\n\n  Theorem extra_lift : forall (P : Prop) p,\n    P\n    -> p === [| P |] * p.\n  Proof.\n    t.\n    apply split_empty_fwd' in H1; subst; auto.\n  Qed.    \n\n  Theorem star_comm : forall p q, p * q === q * p.\n  Proof.\n    t.\n  Qed.\n\n  Theorem star_assoc : forall p q r, p * (q * r) === (p * q) * r.\n  Proof.\n    t.\n  Qed.\n\n  Theorem star_cancel : forall p1 p2 q1 q2, p1 ===> p2\n    -> q1 ===> q2\n    -> p1 * q1 ===> p2 * q2.\n  Proof.\n    t.\n  Qed.\n\n  Theorem exis_gulp : forall A p (q : A -> _),\n    p * exis q === exis (fun x => p * q x).\n  Proof.\n    t.\n  Qed.\n\n  Theorem exis_left : forall A (p : A -> _) q,\n    (forall x, p x ===> q)\n    -> exis p ===> q.\n  Proof.\n    t.\n  Qed.\n\n  Theorem exis_right : forall A p (q : A -> _) x,\n    p ===> q x\n    -> p ===> exis q.\n  Proof.\n    t.\n  Qed.\nEnd S.\n\nExport S.\n(* Instantiate our big automation engine to these definitions. *)\nModule Import Se := SepCancel.Make(S).\n\n\n(* ** Some extra predicates outside the set that the engine knows about *)\n\n(* Capturing single-mapping heaps *)\nDefinition heap1 (a v : nat) : heap := $0 $+ (a, v).\nDefinition ptsto (a v : nat) : hprop :=\n  fun h => h = heap1 a v.\n\n(* Helpful notations, some the same as above *)\nNotation \"[| P |]\" := (lift P) : sep_scope.\nNotation emp := (lift True).\nInfix \"*\" := star : sep_scope.\nNotation \"'exists' x .. y , p\" := (exis (fun x => .. (exis (fun y => p)) ..)) : sep_scope.\nDelimit Scope sep_scope with sep.\nNotation \"p === q\" := (heq p%sep q%sep) (no associativity, at level 70).\nNotation \"p ===> q\" := (himp p%sep q%sep) (no associativity, at level 70).\nInfix \"|->\" := ptsto (at level 30) : sep_scope.\n\nFixpoint multi_ptsto (a : nat) (vs : list nat) : hprop :=\n  match vs with\n  | nil => emp\n  | v :: vs' => a |-> v * multi_ptsto (a + 1) vs'\n  end%sep.\n\nInfix \"|-->\" := multi_ptsto (at level 30) : sep_scope.\n\nFixpoint zeroes (n : nat) : list nat :=\n  match n with\n  | O => nil\n  | S n' => zeroes n' ++ 0 :: nil\n  end.\n\nFixpoint allocated (a n : nat) : hprop :=\n  match n with\n  | O => emp\n  | S n' => (exists v, a |-> v) * allocated (a+1) n'\n  end%sep.\n\nInfix \"|->?\" := allocated (at level 30) : sep_scope.\n\n\n(** * Finally, the Hoare logic *)\n\n(* The whole thing is parameterized on a map from locks to invariants on their\n * owned state.  The map is a list, with lock [i] getting the [i]th invariant in\n * the list.  Lock numbers at or beyond the list length are forbidden.  Beyond\n * this new wrinkle, the type signature of the predicate is the same. *)\n\nInductive hoare_triple (linvs : list hprop) : forall {result}, hprop -> cmd result -> (result -> hprop) -> Prop :=\n\n(* First, we have the basic separation-logic rules from before.  The only change\n * is in the threading-through of parameter [linvs]. *)\n| HtReturn : forall P {result : Set} (v : result),\n    hoare_triple linvs P (Return v) (fun r => P * [| r = v |])%sep\n| HtBind : forall P {result' result} (c1 : cmd result') (c2 : result' -> cmd result) Q R,\n    hoare_triple linvs P c1 Q\n    -> (forall r, hoare_triple linvs (Q r) (c2 r) R)\n    -> hoare_triple linvs P (Bind c1 c2) R\n| HtLoop : forall {acc : Set} (init : acc) (body : acc -> cmd (loop_outcome acc)) I,\n    (forall acc, hoare_triple linvs (I (Again acc)) (body acc) I)\n    -> hoare_triple linvs (I (Again init)) (Loop init body) (fun r => I (Done r))\n| HtFail : forall {result},\n    hoare_triple linvs [| False |]%sep (Fail (result := result)) (fun _ => [| False |])%sep\n| HtRead : forall a R,\n    hoare_triple linvs (exists v, a |-> v * R v)%sep (Read a) (fun r => a |-> r * R r)%sep\n| HtWrite : forall a v',\n    hoare_triple linvs (exists v, a |-> v)%sep (Write a v') (fun _ => a |-> v')%sep\n| HtAlloc : forall numWords,\n    hoare_triple linvs emp%sep (Alloc numWords) (fun r => r |--> zeroes numWords * [| r <> 0 |])%sep\n| HtFree : forall a numWords,\n    hoare_triple linvs (a |->? numWords)%sep (Free a numWords) (fun _ => emp)%sep\n\n(* Next, how to handle locking: the thread takes ownership of a memory chunk\n * satisfying the lock's invariant. *)\n| HtLock : forall a I,\n    nth_error linvs a = Some I\n    -> hoare_triple linvs emp%sep (Lock a) (fun _ => I)\n\n(* When unlocking, the thread relinquishes ownership of a memory chunk\n * satisfying the lock's invariant. *)\n| HtUnlock : forall a I,\n    nth_error linvs a = Some I\n    -> hoare_triple linvs I (Unlock a) (fun _ => emp)%sep\n\n(* When forking into two threads, divide the (local) heap among them.\n * For simplicity, we never let parallel compositions terminate,\n * so it is appropriate to assign a contradictory overall postcondition. *)\n| HtPar : forall P1 c1 Q1 P2 c2 Q2,\n    hoare_triple linvs P1 c1 Q1\n    -> hoare_triple linvs P2 c2 Q2\n    -> hoare_triple linvs (P1 * P2)%sep (Par c1 c2) (fun _ => [| False |])%sep\n\n(* Now we repeat these two structural rules from before. *)\n| HtConsequence : forall {result} (c : cmd result) P Q (P' : hprop) (Q' : _ -> hprop),\n    hoare_triple linvs P c Q\n    -> P' ===> P\n    -> (forall r, Q r ===> Q' r)\n    -> hoare_triple linvs P' c Q'\n| HtFrame : forall {result} (c : cmd result) P Q R,\n    hoare_triple linvs P c Q\n    -> hoare_triple linvs (P * R)%sep c (fun r => Q r * R)%sep.\n\n\nNotation \"linvs ||- {{ P }} c {{ r ~> Q }}\" :=\n  (hoare_triple linvs P%sep c (fun r => Q%sep)) (at level 90, c at next level).\n\nLemma HtStrengthen : forall linvs {result} (c : cmd result) P Q (Q' : _ -> hprop),\n    hoare_triple linvs P c Q\n    -> (forall r, Q r ===> Q' r)\n    -> hoare_triple linvs P c Q'.\nProof.\n  simplify.\n  eapply HtConsequence; eauto.\n  reflexivity.\nQed.\n\nLemma HtStrengthenFalse : forall linvs {result} (c : cmd result) P (Q' : _ -> hprop),\n    hoare_triple linvs P c (fun _ => [| False |])%sep\n    -> hoare_triple linvs P c Q'.\nProof.\n  simplify.\n  eapply HtStrengthen; eauto.\n  simplify.\n  unfold himp; simplify.\n  cases H0.\n  tauto.\nQed.\n\nLemma HtWeaken : forall linvs {result} (c : cmd result) P Q (P' : hprop),\n    hoare_triple linvs P c Q\n    -> P' ===> P\n    -> hoare_triple linvs P' c Q.\nProof.\n  simplify.\n  eapply HtConsequence; eauto.\n  reflexivity.\nQed.\n\n\n(** * Examples *)\n\nOpaque heq himp lift star exis ptsto.\n\n(* Here comes some automation that we won't explain in detail, instead opting to\n * use examples.  Search for \"nonzero\" to skip ahead to the first one. *)\n\nTheorem use_lemma : forall linvs result P' (c : cmd result) (Q : result -> hprop) P R,\n  hoare_triple linvs P' c Q\n  -> P ===> P' * R\n  -> hoare_triple linvs P c (fun r => Q r * R)%sep.\nProof.\n  simp.\n  eapply HtWeaken.\n  eapply HtFrame.\n  eassumption.\n  eauto.\nQed.\n\nTheorem HtRead' : forall linvs a v,\n  hoare_triple linvs (a |-> v)%sep (Read a) (fun r => a |-> v * [| r = v |])%sep.\nProof.\n  simp.\n  apply HtWeaken with (exists r, a |-> r * [| r = v |])%sep.\n  eapply HtStrengthen.\n  apply HtRead.\n  simp.\n  cancel; auto.\n  subst; cancel.\nQed.\n\nTheorem HtRead'' : forall linvs p P R,\n  P ===> (exists v, p |-> v * R v)\n  -> hoare_triple linvs P (Read p) (fun r => p |-> r * R r)%sep.\nProof.\n  simp.\n  eapply HtWeaken.\n  apply HtRead.\n  assumption.\nQed.\n\nLemma HtReturn' : forall linvs P {result : Set} (v : result) Q,\n    P ===> Q v\n    -> hoare_triple linvs P (Return v) Q.\nProof.\n  simp.\n  eapply HtStrengthen.\n  constructor.\n  simp.\n  cancel.\n  subst.\n  assumption.\nQed.\n\nLtac basic := apply HtReturn' || eapply HtWrite || eapply HtAlloc || eapply HtFree\n              || (eapply HtLock; simplify; solve [ eauto ])\n              || (eapply HtUnlock; simplify; solve [ eauto ]).\nLtac step0 := basic || eapply HtBind || (eapply use_lemma; [ basic | cancel ])\n              || (eapply use_lemma; [ eapply HtRead' | solve [ cancel ] ])\n              || (eapply HtRead''; solve [ cancel ])\n              || (eapply HtStrengthen; [ eapply use_lemma; [ basic | cancel ] | ])\n              || (eapply HtConsequence; [ apply HtFail | .. ]).\nLtac step := step0; simp.\nLtac ht := simp; repeat step.\nLtac conseq := simplify; eapply HtConsequence.\nLtac use_IH H := conseq; [ apply H | .. ]; ht.\nLtac loop_inv0 Inv := (eapply HtWeaken; [ apply HtLoop with (I := Inv) | .. ])\n                      || (eapply HtConsequence; [ apply HtLoop with (I := Inv) | .. ]).\nLtac loop_inv Inv := loop_inv0 Inv; ht.\nLtac fork0 P1 P2 := apply HtWeaken with (P := (P1 * P2)%sep); [ eapply HtPar | ].\nLtac fork P1 P2 := fork0 P1 P2 || (eapply HtStrengthenFalse; fork0 P1 P2).\nLtac use H := (eapply use_lemma; [ eapply H | cancel ])\n              || (eapply HtStrengthen; [ eapply use_lemma; [ eapply H | cancel ] | ]).\n\nLtac heq := intros; apply himp_heq; split.\n\n(* Fancy theorem to help us rewrite within preconditions and postconditions *)\nLocal Instance hoare_triple_morphism : forall linvs A,\n  Proper (heq ==> eq ==> (eq ==> heq) ==> iff) (@hoare_triple linvs A).\nProof.\n  Transparent himp.\n  repeat (hnf; intros).\n  unfold pointwise_relation in *; intuition subst.\n\n  eapply HtConsequence; eauto.\n  rewrite H; reflexivity.\n  intros.\n  hnf in H1.\n  specialize (H1 r _ eq_refl).\n  rewrite H1; reflexivity.\n\n  eapply HtConsequence; eauto.\n  rewrite H; reflexivity.\n  intros.\n  hnf in H1.\n  specialize (H1 r _ eq_refl).\n  rewrite H1; reflexivity.\n  Opaque himp.\nQed.\n\nTheorem try_ptsto_first : forall a v, try_me_first (ptsto a v).\nProof.\n  simplify.\n  apply try_me_first_easy.\nQed.\n\nLocal Hint Resolve try_ptsto_first : core.\n\n\n(** ** The nonzero shared counter *)\n\n(* This program has two threads sharing a numeric counter, which starts out as\n * nonzero and remains that way, since each thread only increments the counter,\n * with the lock held to avoid race conditions. *)\n\nExample incrementer :=\n  for i := tt loop\n    _ <- Lock 0;\n    n <- Read 0;\n    _ <- Write 0 (n + 1);\n    _ <- Unlock 0;\n    if n ==n 0 then\n      Fail\n    else\n      Return (Again tt)\n  done.\n\nDefinition incrementer_inv := emp%sep.\n\nTheorem incrementers_ok :\n    [incrementer_inv] ||- {{emp}} incrementer || incrementer {{_ ~> emp}}.\nProof.\n  unfold incrementer, incrementer_inv.\nAdmitted.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nFixpoint incrementers (n : nat) :=\n  match n with\n  | O => incrementer\n  | S n' => incrementers n' || incrementers n'\n  end.\n\nTheorem any_incrementers_ok : forall n,\n    [incrementer_inv] ||- {{emp}} incrementers n {{_ ~> emp}}.\nProof.\nAdmitted.\n\n\n(** ** Producer-consumer with a linked list *)\n\n(* First, here's a literal repetition of the definition of linked lists from\n * SeparationLogic.v. *)\n\nFixpoint linkedList (p : nat) (ls : list nat) :=\n  match ls with\n    | nil => [| p = 0 |]\n    | x :: ls' => [| p <> 0 |]\n                  * exists p', p |--> [x; p'] * linkedList p' ls'\n  end%sep.\n\nTheorem linkedList_null : forall ls,\n  linkedList 0 ls === [| ls = nil |].\nProof.\n  heq; cases ls; cancel.\nQed.\n\nTheorem linkedList_nonnull : forall p ls,\n  p <> 0\n  -> linkedList p ls === exists x ls' p', [| ls = x :: ls' |] * p |--> [x; p'] * linkedList p' ls'.\nProof.\n  heq; cases ls; cancel; match goal with\n                         | [ H : _ = _ :: _ |- _ ] => invert H\n                         end; cancel.\nQed.\n\n(* Now let's use linked lists as shared stacks for communication between\n * threads, with a lock protecting each stack.  To start out with, here's a\n * producer-consumer example with just one stack.  The producer is looping\n * pushing the consecutive even numbers to the stack, and the consumer is\n * looping popping numbers and failing if they're odd. *)\n\nExample producer :=\n  _ <- for i := 0 loop\n    cell <- Alloc 2;\n    _ <- Write cell i;\n    _ <- Lock 0;\n    head <- Read 0;\n    _ <- Write (cell+1) head;\n    _ <- Write 0 cell;\n    _ <- Unlock 0;\n    Return (Again (2 + i))\n  done;\n  Return tt.\n\nFixpoint isEven (n : nat) : bool :=\n  match n with\n  | O => true\n  | S (S n) => isEven n\n  | _ => false\n  end.\n\nExample consumer :=\n  for i := tt loop\n    _ <- Lock 0;\n    head <- Read 0;\n    if head ==n 0 then\n      _ <- Unlock 0;\n      Return (Again tt)\n    else\n      tail <- Read (head+1);\n      _ <- Write 0 tail;\n      _ <- Unlock 0;\n      data <- Read head;\n      _ <- Free head 2;\n      if isEven data then\n        Return (Again tt)\n      else\n        Fail\n  done.\n\nDefinition producer_consumer_inv := emp%sep.\n\nTheorem producer_consumer_ok :\n  [producer_consumer_inv] ||- {{emp}} producer || consumer {{_ ~> emp}}.\nProof.\n  unfold producer_consumer_inv, producer, consumer.\nAdmitted.\n\n\n(** ** A length-3 producer-consumer chain *)\n\n(* Here's a variant on the last example.  Now we have three stages.\n * Stage 1: push consecutive even numbers to stack 1.\n * Stage 2: pop from stack 1 and push to stack 1, reusing the memory for the\n *          list node.\n * Stage 3: pop from stack 2 and fail if odd. *)\n\nExample stage1 :=\n  _ <- for i := 0 loop\n    cell <- Alloc 2;\n    _ <- Write cell i;\n    _ <- Lock 0;\n    head <- Read 0;\n    _ <- Write (cell+1) head;\n    _ <- Write 0 cell;\n    _ <- Unlock 0;\n    Return (Again (2 + i))\n  done;\n  Return tt.\n\nExample stage2 :=\n  for i := tt loop\n    _ <- Lock 0;\n    head <- Read 0;\n    if head ==n 0 then\n      _ <- Unlock 0;\n      Return (Again tt)\n    else\n      tail <- Read (head+1);\n      _ <- Write 0 tail;\n      _ <- Unlock 0;\n\n      _ <- Lock 1;\n      head' <- Read 1;\n      _ <- Write (head+1) head';\n      _ <- Write 1 head;\n      _ <- Unlock 1;\n\n      Return (Again tt)\n  done.\n\nExample stage3 :=\n  for i := tt loop\n    _ <- Lock 1;\n    head <- Read 1;\n    if head ==n 0 then\n      _ <- Unlock 1;\n      Return (Again tt)\n    else\n      tail <- Read (head+1);\n      _ <- Write 1 tail;\n      _ <- Unlock 1;\n      data <- Read head;\n      _ <- Free head 2;\n      if isEven data then\n        Return (Again tt)\n      else\n        Fail\n  done.\n\n(* Same invariant as before, for each of the two stacks. *)\nDefinition stages_inv root :=\n  (exists ls p, root |-> p * linkedList p ls * [| forallb isEven ls = true |])%sep.\n\nTheorem stages_ok :\n  [stages_inv 0; stages_inv 1] ||- {{emp}} stage1 || stage2 || stage3 {{_ ~> emp}}.\nProof.\n  unfold stages_inv, stage1, stage2, stage3.\n  fork (emp%sep) (emp%sep); ht.\n  fork (emp%sep) (emp%sep); ht.\n\n  loop_inv (fun o => [| isEven (valueOf o) = true |]%sep).\n  match goal with\n  | [ H : r = 0 -> False |- _ ] => erewrite (linkedList_nonnull _ H)\n  end.\n  cancel.\n  simp.\n  apply andb_true_iff; propositional.\n  cancel.\n  cancel.\n  cancel.\n  \n  loop_inv (fun _ : loop_outcome unit => emp%sep).\n  simp.\n  cases (r0 ==n 0).\n  ht.\n  cancel.\n  setoid_rewrite (linkedList_nonnull _ n).\n  ht.\n  apply andb_true_iff in H.\n  simp.\n  erewrite (linkedList_nonnull _ n).\n  cancel.\n  simp.\n  apply andb_true_iff in H1.\n  apply andb_true_iff.\n  simp.\n  cancel.\n  cancel.\n  cancel.\n\n  loop_inv (fun _ : loop_outcome unit => emp%sep).\n  simp.\n  cases (r0 ==n 0).\n  ht.\n  cancel.\n  setoid_rewrite (linkedList_nonnull _ n).\n  ht.\n  apply andb_true_iff in H.\n  simp.\n  simp.\n  cases (isEven r4); ht.\n  cancel.\n  cancel.\n  simp.\n  rewrite Heq in H0.\n  simp.\n  try equality.\n  cancel.\n  cancel.\n  cancel.\nQed.\n\n\n(** * Soundness proof *)\n\nLocal Hint Resolve himp_refl : core.\n\nLemma invert_Return : forall linvs {result : Set} (r : result) P Q,\n  hoare_triple linvs P (Return r) Q\n  -> P ===> Q r.\nProof.\n  induct 1; propositional; eauto.\n\n  cancel.\n\n  eauto using himp_trans.\n\n  rewrite IHhoare_triple; eauto.\nQed.\n\nLocal Hint Constructors hoare_triple : core.\n\nLemma invert_Bind : forall linvs {result' result} (c1 : cmd result') (c2 : result' -> cmd result) P Q,\n  hoare_triple linvs P (Bind c1 c2) Q\n  -> exists R, hoare_triple linvs P c1 R\n               /\\ forall r, hoare_triple linvs (R r) (c2 r) Q.\nProof.\n  induct 1; propositional; eauto.\n\n  invert IHhoare_triple; propositional.\n  eexists; propositional.\n  eapply HtWeaken.\n  eassumption.\n  auto.\n  eapply HtStrengthen.\n  apply H4.\n  auto.\n\n  simp.\n  exists (fun r => x r * R)%sep.\n  propositional.\n  eapply HtFrame; eauto.\n  eapply HtFrame; eauto.\nQed.\n\nTransparent heq himp lift star exis ptsto.\n\nLemma invert_Loop : forall linvs {acc : Set} (init : acc) (body : acc -> cmd (loop_outcome acc)) P Q,\n    hoare_triple linvs P (Loop init body) Q\n    -> exists I, (forall acc, hoare_triple linvs (I (Again acc)) (body acc) I)\n                 /\\ P ===> I (Again init)\n                 /\\ (forall r, I (Done r) ===> Q r).\nProof.\n  induct 1; propositional; eauto.\n\n  invert IHhoare_triple; propositional.\n  exists x; propositional; eauto.\n  unfold himp in *; eauto.\n\n  eauto using himp_trans.\n\n  simp.\n  exists (fun o => x o * R)%sep; propositional; eauto.\n  rewrite H0; eauto.\n  rewrite H3; eauto.\nQed.\n\nOpaque heq himp lift star exis ptsto.\n\nLemma unit_not_nat : unit = nat -> False.\nProof.\n  simplify.\n  assert (exists x : unit, forall y : unit, x = y).\n  exists tt; simplify.\n  cases y; reflexivity.\n  rewrite H in H0.\n  invert H0.\n  specialize (H1 (S x)).\n  linear_arithmetic.\nQed.\n\nLemma invert_Read : forall linvs a P Q,\n  hoare_triple linvs P (Read a) Q\n  -> exists R, (P ===> exists v, a |-> v * R v)%sep\n               /\\ forall r, a |-> r * R r ===> Q r.\nProof.\n  induct 1; simp; eauto.\n\n  apply unit_not_nat in x0; simp.\n\n  apply unit_not_nat in x0; simp.\n\n  apply unit_not_nat in x0; simp.\n\n  apply unit_not_nat in x0; simp.\n\n  apply unit_not_nat in x0; simp.\n\n  eauto 7 using himp_trans.\n\n  exists (fun n => x n * R)%sep; simp.\n  rewrite H1.\n  cancel.\n\n  rewrite <- H2.\n  cancel.\nQed.\n\nLemma invert_Write : forall linvs a v' P Q,\n  hoare_triple linvs P (Write a v') Q\n  -> exists R, (P ===> (exists v, a |-> v) * R)%sep\n               /\\ a |-> v' * R ===> Q tt.\nProof.\n  induct 1; simp; eauto.\n\n  symmetry in x0.\n  apply unit_not_nat in x0; simp.\n\n  exists emp; simp.\n  cancel; auto.\n  cancel; auto.\n\n  symmetry in x0.\n  apply unit_not_nat in x0; simp.\n\n  eauto 7 using himp_trans.\n\n  exists (x * R)%sep; simp.\n  rewrite H1.\n  cancel.\n\n  cancel.\n  rewrite <- H2.\n  cancel.\nQed.\n\nLemma invert_Alloc : forall linvs numWords P Q,\n  hoare_triple linvs P (Alloc numWords) Q\n  -> forall r, P * r |--> zeroes numWords * [| r <> 0 |] ===> Q r.\nProof.\n  induct 1; simp; eauto.\n\n  apply unit_not_nat in x0; simp.\n\n  cancel.\n\n  apply unit_not_nat in x0; simp.\n\n  apply unit_not_nat in x0; simp.\n\n  apply unit_not_nat in x0; simp.\n\n  apply unit_not_nat in x0; simp.\n\n  rewrite H0; eauto.\n  eauto 7 using himp_trans.\n\n  rewrite <- IHhoare_triple.\n  cancel.\nQed.\n\nTransparent heq himp lift star exis ptsto.\n\nLemma zeroes_initialize' : forall h a v,\n    h $? a = None\n    -> (fun h' : heap => h' = h $+ (a, v)) ===> (fun h' => h' = h) * a |-> v.\nProof.\n  unfold himp, star, split, ptsto, disjoint; simp.\n  exists h, (heap1 a v).\n  propositional.\n  maps_equal.\n  unfold heap1.\n  rewrite lookup_join2.\n  simp.\n  simp.\n  apply lookup_None_dom in H.\n  propositional.\n  cases (h $? k).\n  rewrite lookup_join1; auto.\n  eauto using lookup_Some_dom.\n  rewrite lookup_join2; auto.\n  unfold heap1; simp.\n  eauto using lookup_None_dom.\n  unfold heap1 in *.\n  cases (a ==n a0); simp.\nQed.\n\nOpaque heq himp lift star exis ptsto.\n\nLemma multi_ptsto_app : forall ls2 ls1 a,\n     a |--> ls1 * (a + length ls1) |--> ls2 ===> a |--> (ls1 ++ ls2).\nProof.\n  induct ls1; simp; cancel; auto.\n\n  replace (a + 0) with a by linear_arithmetic.\n  cancel.\n\n  rewrite <- IHls1.\n  cancel.\n  replace (a0 + 1 + length ls1) with (a0 + S (length ls1)) by linear_arithmetic.\n  cancel.\nQed.\n\nLemma length_zeroes : forall n,\n    length (zeroes n) = n.\nProof.\n  induct n; simplify; auto.\n  rewrite app_length; simplify.\n  linear_arithmetic.\nQed.\n\nLemma initialize_fresh : forall a' h a numWords,\n    a' >= a + numWords\n    -> initialize h a numWords $? a' = h $? a'.\nProof.\n  induct numWords; simp; auto.\nQed.\n\nLemma zeroes_initialize : forall numWords a h,\n    (forall i, i < numWords -> h $? (a + i) = None)\n    -> (fun h' => h' = initialize h a numWords) ===> (fun h' => h' = h) * a |--> zeroes numWords.\nProof.\n  induct numWords; simp.\n\n  cancel; auto.\n  rewrite <- multi_ptsto_app.\n  rewrite zeroes_initialize'.\n  erewrite IHnumWords.\n  simp.\n  rewrite length_zeroes.\n  cancel; auto.\n  auto.\n  rewrite initialize_fresh; auto.\nQed.\n\nLemma invert_Free : forall linvs a numWords P Q,\n  hoare_triple linvs P (Free a numWords) Q\n  -> P ===> a |->? numWords * Q tt.\nProof.\n  induct 1; simp; eauto.\n\n  symmetry in x0.\n  apply unit_not_nat in x0; simp.\n\n  symmetry in x0.\n  apply unit_not_nat in x0; simp.\n\n  cancel; auto.\n\n  rewrite H0.\n  rewrite IHhoare_triple.\n  cancel; auto.\n\n  rewrite IHhoare_triple.\n  cancel; auto.\nQed.\n\nTransparent heq himp lift star exis ptsto.\n\nLemma do_deallocate' : forall a Q h,\n    ((exists v, a |-> v) * Q)%sep h\n    -> Q (h $- a).\nProof.\n  unfold ptsto, star, split, heap1; simp.\n  invert H1.\n  replace ($0 $+ (a, x1) $++ x0 $- a) with x0; auto.\n  maps_equal.\n  cases (k ==n a); simp.\n  specialize (H a).\n  simp.\n  cases (x0 $? a); auto.\n  exfalso; apply H; equality.\n  rewrite lookup_join2; auto.\n  apply lookup_None_dom.\n  simp.\nQed.\n\nLemma do_deallocate : forall Q numWords a h,\n    (a |->? numWords * Q)%sep h\n    -> Q (deallocate h a numWords).\nProof.\n  induct numWords; simp.\n\n  unfold star, exis, lift in H; simp.\n  apply split_empty_fwd' in H0; simp.\n\n  apply IHnumWords.\n  clear IHnumWords.\n  \n  apply do_deallocate'.\n  Opaque heq himp lift star exis ptsto.\n  match goal with\n  | [ H : ?P h |- ?Q h ] => assert (P ===> Q) by cancel\n  end.\n  Transparent himp.\n  apply H0; auto.\n  Opaque himp.\nQed.\n\nOpaque heq himp lift star exis ptsto.\n\nLemma invert_Lock : forall linvs a P Q,\n  hoare_triple linvs P (Lock a) Q\n  -> exists I, nth_error linvs a = Some I\n               /\\ P * I ===> Q tt.\nProof.\n  induct 1; simp; eauto 10.\n\n  symmetry in x0.\n  apply unit_not_nat in x0; simp.\n\n  symmetry in x0.\n  apply unit_not_nat in x0; simp.\n\n  eexists; simp.\n  eauto.\n  cancel.\n\n  eexists; simp.\n  eauto.\n  rewrite H0; eauto using himp_trans.\n\n  eexists; simp.\n  eauto.\n  rewrite <- H2.\n  cancel.\nQed.\n\nLemma invert_Unlock : forall linvs a P Q,\n  hoare_triple linvs P (Unlock a) Q\n  -> exists I, nth_error linvs a = Some I\n               /\\ P ===> Q tt * I.\nProof.\n  induct 1; simp; eauto 10.\n\n  symmetry in x0.\n  apply unit_not_nat in x0; simp.\n\n  symmetry in x0.\n  apply unit_not_nat in x0; simp.\n\n  eexists; simp.\n  eauto.\n  cancel.\n\n  eexists; simp.\n  eauto.\n  rewrite <- H1; eauto using himp_trans.\n\n  eexists; simp.\n  eauto.\n  rewrite H2.\n  cancel.\nQed.\n\nLemma invert_Par : forall linvs c1 c2 P Q,\n  hoare_triple linvs P (Par c1 c2) Q\n  -> exists P1 P2 Q1 Q2,\n      hoare_triple linvs P1 c1 Q1\n      /\\ hoare_triple linvs P2 c2 Q2\n      /\\ P ===> P1 * P2.\nProof.\n  induct 1; simp; eauto 7.\n\n  symmetry in x0.\n  apply unit_not_nat in x0; simp.\n\n  symmetry in x0.\n  apply unit_not_nat in x0; simp.\n\n  eauto 8 using himp_trans.\n\n  exists (x * R)%sep, x0, (fun r => x1 r * R)%sep, x2; simp; eauto.\n  rewrite H3; cancel.\nQed.\n\nTransparent heq himp lift star exis ptsto.\n\nDefinition guarded (P : Prop) (p : hprop) : hprop :=\n  fun h => IFF P then p h else emp%sep h.\n\nInfix \"===>\" := guarded : sep_scope.\n\nTheorem guarded_true : forall (P : Prop) p, P\n  -> (P ===> p) === p.\nProof.\n  unfold heq, guarded, IF_then_else; simp.\nQed.\n\nTheorem guarded_false : forall (P : Prop) p, ~P\n  -> (P ===> p) === emp.\nProof.\n  unfold heq, guarded, IF_then_else; simp.\nQed.\n\nFixpoint bigstar A (P : nat -> A -> hprop) (ls : list A) : hprop :=\n  match ls with\n  | nil => emp\n  | x :: ls' => P 0 x * bigstar (fun n => P (S n)) ls'\n  end%sep.\n\nDefinition lockChunks (l : locks) (ls : list hprop) :=\n  bigstar (fun i I => (~i \\in l) ===> I)%sep ls.\n\nLemma use_himp : forall P Q, P ===> Q\n  -> forall h, P h -> Q h.\nProof.\n  auto.\nQed.\n\nLemma ptsto_out : forall h a v p,\n    h $? a = Some v\n    -> (exists v', a |-> v' * p v')%sep h\n    -> (a |-> v * p v)%sep h\n       /\\ forall v', (a |-> v' * p v)%sep (h $+ (a, v')).\nProof.\n  invert 2.\n  invert H1.\n  simp.\n\n  invert H2.\n  unfold split in H0; subst.\n  rewrite lookup_join1 in H.\n  unfold heap1 in H.\n  simplify.\n  invert H.\n  exists (heap1 a v), x1; simp.\n  eauto.\n  unfold ptsto.\n  eauto.\n  unfold heap1; simplify.\n  sets.\n\n  invert H2.\n  unfold split in H0; subst.\n  rewrite lookup_join1 in H.\n  unfold heap1 in H.\n  simplify.\n  invert H.\n  exists (heap1 a v'), x1; simp.\n  unfold split.\n  maps_equal.\n  rewrite lookup_join1.\n  unfold heap1; simplify; auto.\n  unfold heap1; simplify; sets.\n  repeat rewrite lookup_join2; auto.\n  unfold heap1; simplify; sets.\n  unfold heap1; simplify; sets.\n  unfold disjoint in *; simp.\n  apply (H1 a0); eauto.\n  cases (a ==n a0); simp.\n  unfold heap1 in *; simplify; equality.\n  unfold heap1 in *; simplify; equality.\n  unfold ptsto.\n  eauto.\n  unfold heap1; simplify; sets.\nQed.\n\nLemma specialize_hprop : forall (p : hprop) h,\n    p h\n    -> (fun h' => h' = h) ===> p.\nProof.\n  unfold himp; equality.\nQed.\n\nOpaque heq himp lift star exis ptsto.\n\nLemma bigstar_impl : forall A ls (p q : nat -> A -> hprop),\n    (forall i x, p i x ===> q i x)\n    -> bigstar p ls ===> bigstar q ls.\nProof.\n  induct ls; simplify; auto.\n  rewrite H.\n  rewrite IHls.\n  cancel.\n  simp.\n  eauto.\nQed.\n\nLemma guarded_impl : forall P Q p,\n    (P <-> Q)\n    -> (P ===> p) ===> (Q ===> p).\nProof.\n  simp.\n  excluded_middle P.\n  repeat rewrite guarded_true by propositional.\n  auto.\n  repeat rewrite guarded_false by propositional.\n  auto.\nQed.\n\nLemma lockChunks_lock' : forall l I linvs (f : nat -> nat) a,\n    ~f a \\in l\n    -> nth_error linvs a = Some I\n    -> (forall x y, f x = f y -> x = y)\n    -> bigstar (fun i I => (~f i \\in l) ===> I)%sep linvs ===> I * bigstar (fun i I => (~(f i \\in {f a} \\cup l)) ===> I)%sep linvs.\nProof.\n  induct linvs; simplify.\n\n  cases a; simplify; try unfold error in *; equality.\n\n  cases a0; simplify.\n  invert H0.\n  rewrite guarded_true by sets.\n  rewrite guarded_false by sets.\n  cancel.\n  apply bigstar_impl.\n  simp.\n  apply guarded_impl.\n  sets.\n  apply H1 in H2.\n  equality.\n\n  apply (IHlinvs (fun n => f (S n))) in H0; auto.\n  rewrite H0.\n  cancel.\n  apply guarded_impl.\n  sets.\n  apply H1 in H3.\n  equality.\n  simp.\n  apply H1 in H2.\n  equality.\nQed.\n\nLemma lockChunks_lock : forall a l I linvs,\n    ~a \\in l\n    -> nth_error linvs a = Some I\n    -> lockChunks l linvs ===> I * lockChunks ({a} \\cup l) linvs.\nProof.\n  simp.\n  apply lockChunks_lock' with (f := fun n => n); auto.\nQed.\n\nLemma lockChunks_unlock' : forall l I linvs (f : nat -> nat) a,\n    f a \\in l\n    -> nth_error linvs a = Some I\n    -> (forall x y, f x = f y -> x = y)\n    -> I * bigstar (fun i I => (~f i \\in l) ===> I)%sep linvs ===> bigstar (fun i I => (~(f i \\in l \\setminus {f a})) ===> I)%sep linvs.\nProof.\n  induct linvs; simplify.\n\n  cases a; simplify; try unfold error in *; equality.\n\n  cases a0; simplify.\n  invert H0.\n  rewrite guarded_false by sets.\n  rewrite guarded_true by sets.\n  cancel.\n  apply bigstar_impl.\n  simp.\n  apply guarded_impl.\n  sets.\n  apply H0; propositional.\n  apply H1 in H4.\n  equality.\n\n  apply (IHlinvs (fun n => f (S n))) in H0; auto.\n  rewrite <- H0.\n  cancel.\n  apply guarded_impl.\n  sets.\n  apply H2; propositional.\n  apply H1 in H5.\n  equality.\n  simp.\n  apply H1 in H2.\n  equality.\nQed.\n\nLemma lockChunks_unlock : forall a l I linvs,\n    a \\in l\n    -> nth_error linvs a = Some I\n    -> I * lockChunks l linvs ===> lockChunks (l \\setminus {a}) linvs.\nProof.\n  simp.\n  apply lockChunks_unlock' with (f := fun n => n); auto.\nQed.\n\nLemma preservation : forall linvs {result} (c : cmd result) h l c' h' l',\n    step (h, l, c) (h', l', c')\n    -> forall P Q R, hoare_triple linvs P c Q\n                     -> (P * R * lockChunks l linvs)%sep h\n                     -> exists P', hoare_triple linvs P' c' Q\n                                   /\\ (P' * R * lockChunks l' linvs)%sep h'.\nProof.\n  induct 1; simplify.\n\n  apply invert_Bind in H0; simp.\n  eapply IHstep in H0; eauto.\n  simp.\n  eauto.\n  \n  apply invert_Bind in H; simp.\n  specialize (invert_Return H); eauto using HtWeaken.\n\n  apply invert_Loop in H; simp.\n  eexists; simp.\n  econstructor.\n  eauto.\n  simp.\n  cases r.\n  apply HtReturn'.\n  auto.\n  eapply HtStrengthen.\n  eauto.\n  eauto.\n  eapply use_himp; try eassumption.\n  rewrite H1.\n  eauto.\n\n  apply invert_Read in H0; simp.\n  assert ((exists v, a |-> v * (x v * R * lockChunks l' linvs))%sep h').\n  eapply use_himp; try eassumption.\n  rewrite H0.\n  cancel.\n  eapply ptsto_out in H2; eauto.\n  eexists; simp.\n  apply HtReturn'.\n  eauto.\n  eapply use_himp; try eassumption.\n  cancel.\n\n  apply invert_Write in H0; simp.\n  assert ((exists v, a |-> v * (x * R * lockChunks l' linvs))%sep h).\n  eapply use_himp; try eassumption.\n  rewrite H0.\n  cancel.\n  eapply ptsto_out in H2; eauto.\n  propositional.\n  eexists; simp.\n  apply HtReturn'.\n  eauto.\n  eapply use_himp; try apply H5.\n  cancel.\n\n  apply invert_Alloc with (r := a) in H1.\n  eexists; propositional.\n  apply HtReturn'.\n  eassumption.\n  apply use_himp with ((P * R * lockChunks l' linvs) * a |--> zeroes numWords)%sep.\n  cancel.\n  apply use_himp with ((fun h' => h' = h) * a |--> zeroes numWords)%sep.\n  cancel.\n  eauto using specialize_hprop.\n  eapply use_himp.\n  apply zeroes_initialize; auto.\n  simp.\n\n  apply invert_Free in H.\n  eexists; propositional.\n  instantiate (1 := Q tt).\n  apply HtReturn'.\n  auto.\n  apply do_deallocate; simplify.\n  change (fun f => (Q tt * lockChunks l' linvs) f)%sep with (Q tt * lockChunks l' linvs)%sep.\n  eapply use_himp; try eassumption.\n  rewrite H.\n  cancel.\n\n  apply invert_Lock in H0.\n  simp.\n  eexists; propositional.\n  apply HtReturn'; auto.\n  eapply use_himp; try eassumption.\n  rewrite <- H3.\n  cancel.\n  apply lockChunks_lock; auto.\n\n  apply invert_Unlock in H0.\n  simp.\n  eexists; propositional.\n  apply HtReturn'; auto.\n  eapply use_himp; try eassumption.\n  rewrite H3.\n  cancel.\n  rewrite <- lockChunks_unlock; eauto.\n  cancel.\n\n  apply invert_Par in H0.\n  simp.\n  eapply IHstep in H2.\n  simp.\n  eexists; propositional.\n  apply HtStrengthenFalse.\n  econstructor.\n  eassumption.\n  eassumption.\n  eapply use_himp; try eassumption.\n  cancel.\n  eapply use_himp; try eassumption.\n  cancel.\n  \n  apply invert_Par in H0.\n  simp.\n  eapply IHstep in H0.\n  simp.\n  eexists; propositional.\n  apply HtStrengthenFalse.\n  econstructor.\n  eassumption.\n  eassumption.\n  eapply use_himp; try eassumption.\n  cancel.\n  eapply use_himp; try eassumption.\n  rewrite H4.\n  cancel.\nQed.\n\nDefinition allLockChunks (linvs : list hprop) := bigstar (fun _ I => I) linvs.\n\nLemma allLockChunks_lockChunks' : forall linvs (f : nat -> nat),\n   bigstar (fun _ I => I) linvs ===> bigstar (fun i I => (~f i \\in {}) ===> I) linvs.\nProof.\n  induct linvs; simp; auto.\n\n  rewrite guarded_true by sets.\n  rewrite IHlinvs.\n  cancel.\nQed.\n\nLemma allLockChunks_lockChunks : forall linvs,\n    allLockChunks linvs ===> lockChunks {} linvs.\nProof.\n  simp.\n  apply allLockChunks_lockChunks' with (f := fun n => n).\nQed.\n\nLemma hoare_triple_sound' : forall linvs P {result} (c : cmd result) Q,\n    hoare_triple linvs P c Q\n    -> forall h, (P * allLockChunks linvs)%sep h\n    -> invariantFor (trsys_of h {} c)\n                    (fun p =>\n                       let '(h, l, c) := p in\n                       exists P', hoare_triple linvs P' c Q\n                                  /\\ (P' * lockChunks l linvs)%sep h).\nProof.\n  simplify.\n\n  apply invariant_induction; simplify.\n\n  propositional; subst; simplify.\n  eexists; propositional.\n  eauto.\n  eapply use_himp; try eassumption.\n  rewrite allLockChunks_lockChunks.\n  auto.\n\n  cases s.\n  cases p.\n  cases s'.\n  cases p.\n  simp.\n  eapply preservation with (R := emp%sep) in H1; eauto.\n  simp.\n  eexists; propositional; eauto.\n  eapply use_himp; try eassumption.\n  cancel.\n  eapply use_himp; try eassumption.\n  cancel.\nQed.\n\nFixpoint notAboutToFail {result} (c : cmd result) :=\n  match c with\n  | Fail _ => false\n  | Bind _ _ c1 _ => notAboutToFail c1\n  | Par c1 c2 => notAboutToFail c1 && notAboutToFail c2\n  | _ => true\n  end.\n\nLemma hoare_triple_notAboutToFail : forall linvs P result (c : cmd result) Q,\n    hoare_triple linvs P c Q\n    -> notAboutToFail c = false\n    -> P ===> [| False |].\nProof.\n  induct 1; simp; try equality; eauto using himp_trans.\n\n  apply andb_false_iff in H1; propositional.\n  rewrite H1; cancel.\n  rewrite H1; cancel.\n\n  rewrite H1; cancel.\nQed.\n\nLemma False_star : forall p,\n    [| False |] * p ===> [| False |].\nProof.\n  cancel.\nQed.\n\nTheorem hoare_triple_sound : forall linvs P {result} (c : cmd result) Q,\n    hoare_triple linvs P c Q\n    -> forall h, (P * allLockChunks linvs)%sep h\n    -> invariantFor (trsys_of h {} c)\n                    (fun p => let '(_, _, c) := p in\n                              notAboutToFail c = true).\nProof.\n  simplify.\n\n  eapply invariant_weaken.\n  eapply hoare_triple_sound'; eauto.\n  simp.\n  cases s.\n  cases p.\n  simp.\n  cases (notAboutToFail c0); auto.\n  eapply hoare_triple_notAboutToFail in Heq; eauto.\n  assert ([| False |]%sep f).\n  apply use_himp with (x * lockChunks s linvs)%sep.\n  rewrite Heq.\n  apply False_star.\n  assumption.\n  invert H2; propositional.\nQed.\n", "meta": {"author": "achlipala", "repo": "frap", "sha": "ac0a15e9f23bb9bfbff7c376a5597b0850b3d4bb", "save_path": "github-repos/coq/achlipala-frap", "path": "github-repos/coq/achlipala-frap/frap-ac0a15e9f23bb9bfbff7c376a5597b0850b3d4bb/ConcurrentSeparationLogic_template.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.26573153597839505}}
{"text": "(* This file is automatically generated from the OCaml source file\n<repository_root>/ml_sources/examples/crdt/oplib/examples/remove_wins_set/remove_wins_set_code.ml *)\n\nFrom aneris.aneris_lang Require Import ast.\nFrom aneris.aneris_lang.lib Require Import list_code.\nFrom aneris.aneris_lang.lib.vector_clock Require Import vector_clock_code.\nFrom aneris.aneris_lang.lib.serialization Require Import serialization_code.\nFrom aneris.examples.crdt.oplib Require Import oplib_code.\n\nDefinition init_st : val := λ: <>, ([], []).\n\nDefinition effect_remove_op : val :=\n  λ: \"v\" \"vc\" \"st\",\n  let: \"contents\" := Fst \"st\" in\n  let: \"removes\" := Snd \"st\" in\n  let: \"updated_removes\" := (\"v\", \"vc\") :: \"removes\" in\n  let: \"should_keep_in_contents\" := λ: \"p\",\n  (if: (Fst \"p\") = \"v\"\n   then  let: \"vc'\" := Snd \"p\" in\n         vect_leq \"vc\" \"vc'\"\n   else  #true) in\n  let: \"updated_contents\" := list_filter \"should_keep_in_contents\" \"contents\" in\n  (\"updated_contents\", \"updated_removes\").\n\nDefinition effect_add_op : val :=\n  λ: \"v\" \"vc\" \"st\",\n  let: \"contents\" := Fst \"st\" in\n  let: \"removes\" := Snd \"st\" in\n  let: \"permits_add\" := λ: \"r\",\n  (if: (Fst \"r\") = \"v\"\n   then  let: \"vc'\" := Snd \"r\" in\n         vect_leq \"vc'\" \"vc\"\n   else  #true) in\n  let: \"should_add\" := list_fold (λ: \"p\" \"r\", \"p\" && (\"permits_add\" \"r\"))\n                       #true \"removes\" in\n  let: \"updated_contents\" := (if: \"should_add\"\n   then  (\"v\", \"vc\") :: \"contents\"\n   else  \"contents\") in\n  (\"updated_contents\", \"removes\").\n\nDefinition effect : val :=\n  λ: \"msg\" \"st\",\n  let: \"v\" := Fst (Fst \"msg\") in\n  let: \"vc\" := Snd (Fst \"msg\") in\n  let: \"_u\" := Snd \"msg\" in\n  match: \"v\" with\n    InjL \"w\" => effect_add_op \"w\" \"vc\" \"st\"\n  | InjR \"w\" => effect_remove_op \"w\" \"vc\" \"st\"\n  end.\n\nDefinition rws_crdt : val := λ: <>, (init_st, effect).\n\nDefinition rws_init val_ser val_deser : val :=\n  λ: \"addrs\" \"rid\",\n  let: \"initRes\" := oplib_init (sum_ser val_ser val_ser)\n                    (sum_deser val_deser val_deser) \"addrs\" \"rid\" rws_crdt in\n  let: \"get_state\" := Fst \"initRes\" in\n  let: \"update\" := Snd \"initRes\" in\n  (\"get_state\", \"update\").\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/remove_wins_set/remove_wins_set_code.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.265731535978395}}
{"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 A B C G Aprime Aprimeprime Bprime Cprime Bprimeprime Bprimeprimeprime : Universe, ((wd_ Aprime Bprimeprime /\\ (wd_ A B /\\ (wd_ B C /\\ (wd_ A C /\\ (wd_ Bprime A /\\ (wd_ Bprime C /\\ (wd_ Aprime B /\\ (wd_ Aprime C /\\ (wd_ Cprime A /\\ (wd_ Cprime B /\\ (wd_ Aprimeprime Bprimeprime /\\ (wd_ Aprime Bprimeprimeprime /\\ (wd_ Aprime Bprime /\\ (wd_ Bprime Bprimeprimeprime /\\ (wd_ G Aprime /\\ (wd_ G Aprimeprime /\\ (wd_ G Bprimeprime /\\ (wd_ Bprimeprime Bprimeprimeprime /\\ (wd_ G Bprimeprimeprime /\\ (wd_ Aprime Aprimeprime /\\ (wd_ B G /\\ (wd_ Bprimeprime B /\\ (wd_ A G /\\ (wd_ Aprimeprime A /\\ (col_ Aprime Bprime Bprimeprimeprime /\\ (col_ Aprime Bprimeprime Aprime /\\ (col_ G Aprimeprime Aprime /\\ (col_ G Bprimeprime Bprimeprimeprime /\\ (col_ Bprimeprime B G /\\ (col_ Cprime A B /\\ (col_ Bprime A C /\\ (col_ Aprimeprime A G /\\ (col_ Aprime B C /\\ col_ A B G))))))))))))))))))))))))))))))))) -> 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_1103.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.26572999337901143}}
{"text": "Require Import List FMap Lia.\nRequire Import Common Topology Syntax IndexSupport.\nRequire Import RqRsLang. Import RqRsNotations.\n\nRequire Import Ex.TopoTemplate Ex.RuleTemplate.\n\nSet Implicit Arguments.\n\nLocal Open Scope list.\nLocal Open Scope fmap.\n\nSection RssHolder.\n  Variable (dtr: DTree).\n  Context `{dv:DecValue} `{oifc: OStateIfc}.\n\n  Definition RsWaiting (cidx: IdxT): OPrec :=\n    fun ost orq mins =>\n      (orq@[downRq])\n        >>=[False]\n        (fun rqid => In (rsUpFrom cidx, None) rqid.(rqi_rss)).\n\n  Definition RssFullWithId (msgId: IdxT): OPrec :=\n    fun ost orq mins =>\n      (orq@[downRq])\n        >>=[False]\n        (fun rqid => Forall (fun ors => match snd ors with\n                                        | Some rs => rs.(msg_id) = msgId\n                                        | None => False\n                                        end) rqid.(rqi_rss)).\n\n  Definition RssFullOne (msgId: IdxT): OPrec :=\n    fun ost orq mins =>\n      (orq@[downRq])\n        >>=[False]\n        (fun rqid =>\n           List.length rqid.(rqi_rss) = 1 /\\\n           Forall (fun ors => match snd ors with\n                              | Some rs => rs.(msg_id) = msgId\n                              | None => False\n                              end) rqid.(rqi_rss)).\n\n  Fixpoint putRs (midx: IdxT) (msg: Msg) (rss: list (IdxT * option Msg)) :=\n    match rss with\n    | nil => nil\n    | rs :: rss' =>\n      if idx_dec midx (fst rs)\n      then (midx, Some msg) :: rss'\n      else rs :: (putRs midx msg rss')\n    end.\n\n  Definition addRs (orq: ORq Msg) (midx: IdxT) (msg: Msg) :=\n    (orq@[downRq])\n      >>=[orq]\n      (fun rqid => orq +[downRq <- {| rqi_msg := rqid.(rqi_msg);\n                                      rqi_rss := putRs midx msg rqid.(rqi_rss);\n                                      rqi_midx_rsb := rqid.(rqi_midx_rsb) |}]).\n\n  Fixpoint retRss (rss: list (IdxT * option Msg)): list (Id Msg) :=\n    match rss with\n    | nil => nil\n    | rs :: rss' =>\n      match snd rs with\n      | Some rsm => (fst rs, rsm) :: (retRss rss')\n      | None => retRss rss'\n      end\n    end.\n\n  Definition getRss (orq: ORq Msg) :=\n    (orq@[downRq]) >>=[nil] (fun rqid => retRss rqid.(rqi_rss)).\n\n  Variables\n    (ridx msgId rqId: IdxT)\n    (prec: OState -> Prop).\n\n  Variable (cidx: IdxT).\n\n  Definition rsTakeOne :=\n    rule[ridx]\n    :requires (MsgsFrom [rsUpFrom cidx] /\\ MsgIdsFrom [msgId] /\\\n               DownLockMsgId MRq rqId /\\\n               RsAccepting /\\ RsWaiting cidx)\n    :transition\n       (do (st --> (msg <-- getFirstMsg st.(msgs);\n                    return {{ st.(ost),\n                              addRs st.(orq) (rsUpFrom cidx) msg,\n                              nil }}))).\n\n  Definition rsRelease (trs: OState ->\n                             list (Id Msg) (* incoming messages *) ->\n                             Msg (* the original request *) ->\n                             IdxT (* response back to *) ->\n                             OState * Miv) :=\n    rule[ridx]\n    :requires (MsgsFrom nil /\\ DownLockMsgId MRq rqId /\\\n               DownLockIdxBack /\\ RssFullWithId msgId /\\\n               fun ost _ _ => prec ost)\n    :transition\n       (do (st --> (rq <-- getDownLockMsg st.(orq);\n                   rsbTo <-- getDownLockIdxBack st.(orq);\n                   nst ::= trs st.(ost) (getRss st.(orq)) rq rsbTo;\n                    return {{ fst nst,\n                              removeRq st.(orq) downRq,\n                              [(rsbTo, rsMsg rq.(msg_addr) (snd nst))] }}))).\n\n  Definition rsReleaseOne (trs: OState ->\n                                Id Msg (* incoming messages *) ->\n                                Msg (* the original request *) ->\n                                IdxT (* response back to *) ->\n                                OState * Miv) :=\n    rule[ridx]\n    :requires (MsgsFrom nil /\\ DownLockMsgId MRq rqId /\\\n               DownLockIdxBack /\\ RssFullOne msgId /\\\n               fun ost _ _ => prec ost)\n    :transition\n       (do (st --> (rq <-- getDownLockMsg st.(orq);\n                   rsbTo <-- getDownLockIdxBack st.(orq);\n                   nst ::= trs st.(ost) (getFirstIdMsgI (getRss st.(orq))) rq rsbTo;\n                    return {{ fst nst,\n                              removeRq st.(orq) downRq,\n                              [(rsbTo, rsMsg rq.(msg_addr) (snd nst))] }}))).\n\nEnd RssHolder.\n\nNotation \"'rule.rsuo' '[' RIDX ']' ':accepts' MSGID ':holding' RQID ':from' FROM\" :=\n  (rsTakeOne RIDX MSGID RQID FROM) (at level 5, only parsing).\n\nNotation \"'rule.rsr' '[' RIDX ']' ':holding' RQID ':rs-holding' MSGID ':requires' PREC ':transition' TRS\" :=\n  (rsRelease RIDX MSGID RQID PREC TRS%trs) (at level 5, only parsing).\n\nNotation \"'rule.rsro' '[' RIDX ']' ':holding' RQID ':rs-holding' MSGID ':requires' PREC ':transition' TRS\" :=\n  (rsReleaseOne RIDX MSGID RQID PREC TRS%trs) (at level 5, only parsing).\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/RuleTransform.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.26572858233746804}}
{"text": "\n(************************************************************************)\n(* Copyright (c) 2017-2018, Ajay Kumar Eeralla <ae266@mail.missouri.edu>*)\n(************************************************************************)\n\nRequire Export prop_17.\nRequire Import Coq.Bool.Bool.\nSet Nested Proofs Allowed.\nSection lemma148.\n\n  Definition V (b:bool) :=\n    match b with\n    | false => (V0 (N 0))\n    | true => (V1 (N 0))\n    end.\n\n  Definition cn (b:bool) :nat :=\n    match b with\n    | false => 0\n    | true => 1\n    end.\nSearchAbout eqb%bool.\n(** abbreviations *)\n\nDefinition tau n (m:message) := match n, m with\n                                | 1, m => (pi1 m)\n                                | 2, m => (pi1 (pi2 m))\n                                | 3, m => (pi2 (pi2 m))\n                                | _, _ => O\n                                end.\n\nDefinition d n x := (dec (tau n x) (ske 2)).\nDefinition pvchecks x := ((pi2 (d 1 x)) #? TWO) & ((pi2 (d 2 x)) #? TWO) & ((pi2 (d 3 x)) #? TWO).\nDefinition pochecks x := ((tau 3 (d 1 x)) #? THREE) & ((tau 3 (d 2 x)) #? THREE) & ((tau 3 (d 3 x)) #? THREE).\n\nDefinition dist x := !((d 1 x) #? (d 2 x)) & !((d 1 x) #? (d 3 x))& ! ((d 2 x) #? (d 3 x)).\nDefinition isin (x y:message):Bool := (x #? (tau 1 y)) or (x #? (tau 2 y)) or (x #? (tau 3 y)).\nDefinition bcheck (x y:message):Bool := (isin x ((tau 1 (pi2 (tau 1 y))), ((tau 1 (pi2 (tau 2 y))), (tau 1 (pi2 (tau 3 y)))))).\nDefinition ncheck (x y:message):Bool := (isin x ((tau 3 (pi2 (tau 1 y))), ((tau 3 (pi2 (tau 2 y))), (tau 3 (pi2 (tau 3 y)))))).\n\n\nDefinition lbl:= |(N 100)|.\nDefinition label x y := If (x #? (tau 2 (pi2 (tau 1 y)))) then (pi1 (tau 1 y))\n                           else  (If (x#? (tau 2 (pi2 (tau 2 y)))) then (pi1 (tau 2 y))\n                                                       else (If (x #? (tau 2 (pi2 (tau 3 y)))) then (pi1 (tau 3 y))\n                                                             else O)).\n\nDefinition bnlcheck( x y z:message):Bool:= (bcheck x z) & (|(label x z)| #? lbl) & (ncheck y z).\n\nDefinition mvchecks x (n n':nat) := (dist (x n n')) & (pvchecks (x n n')).\n\nDefinition p n x := ( (tau 1 (d n x)), (tau 2 (d n x))).\n\nDefinition sotrm x := (shufl (p 1 x) (p 2 x) (p 3 x)).\n\nDefinition isink (x y:message):Bool := (x #? (tau 2 (d 1 y))) or (x #? (tau 2 (d 2 y))) or (x #? (tau 2 (d 3 y))).\n(** **)\nAxiom funcapp_f1m': forall {n n'} f p1 (z z':mylist n) (z1 z1':mylist n'), (z ++ z1) ~ (z' ++ z1') -> ((z ++ z1) ++ [msg (f (ostomsg (getelt_at_pos p1 z1)))]) ~ ((z' ++ z1') ++ [msg (f (ostomsg (getelt_at_pos p1 z1')))]).\nLtac funcapp_f1m'_in g n H:= apply funcapp_f1m' with (f:=g) (p1:=n) in H; unfold getelt_at_pos in H; simpl in H.\nAxiom ifmor_ifm: forall f b x y, (f (If b then x else y)) # (If b then (f x) else (f y)).\n Lemma extFuncapp1: forall n b b' x x' y y' (z z': mylist n) g, (z ++ [bol b, msg (If b then x else y)]) ~ (z' ++ [bol b', msg (If b' then x' else y')]) -> (z ++ [bol b, msg (If b then x else y), msg (If b then (g x) else |_)])~ (z' ++ [bol b', msg (If b' then x' else y'), msg (If b' then (g x') else |_)]).\n\n\n                      Proof. intros.\n\n                             funcapp_f1m'_in g 2 H.\n\n                             simpl.\n                             repeat rewrite ifmor_ifm in H.\nfuncapp_fm_last |_ H; auto.    apply ind_assoc in H; simpl in H.\n       apply funcapp_f3bm' with (f:= (ifm_then_else_)) (p1:= 1) (p2:=3) (p3:=4) in H; unfold getelt_at_pos; simpl in H.\n       simpl in H.\n(********************)\n\n       apply ind_assoc in H; simpl in H.\n\n do 2  apply restr with (p:= droplastsec) in H; unfold droplastsec in H; simpl in H; simpl; try rewrite Nat.eqb_refl; auto.\n repeat rewrite aply_ifeval_gen in H;auto. Qed.\n\n                      Axiom eqm_cong: forall m1 m2 m3 m4, m1 # m2 -> m3 # m4 -> (eqm m1 m3) ## (eqm m2 m4).\nSet Nested Proofs Allowed.\nAdd Parametric Morphism: (@ eqm) with\n    signature EQm ==> EQm ==> EQb as eqm_mor.\nProof.    intros.  rewrite H, H0. reflexivity.  Qed.\nAxiom orB_cong: forall b1 b2 b3 b4, b1 ## b2 -> b3 ## b4 -> (IF b1 then TRue else b3) ## (IF b2 then TRue else b4).\nAdd Parametric Morphism: (@orB) with\n      signature EQb ==> EQb ==> EQb as orB_mor.\nProof. intros. apply orB_cong; auto.  Qed.\nLemma rep_first_ballot: forall t t0 t1 : message,\n      let v0 := V0 (N 0) in\n      let v1 := V1 (N 0) in\n      (| v0 |) #? (| v1 |) ## TRue ->\n      Fresh [1; 2; 3; 4] [msg t, msg v0, msg v1, msg t0, msg t1] = true ->\n      closMylist [msg t] = true ->\n      (Datatypes.length (distMvars [msg t0, msg t1]) =? 2)%nat = true ->\n      bVarMylist [msg t0, msg t1] = nil ->\n      let mvl := [5; 6] in\n      mVarMsg t0 = mvl /\\ mVarMsg t1 = mvl ->\n\n                 let r0 := (r 1) in\n                 let r1 := (r 2) in\n                 let k0 := (kc (N 3)) in\n                 let k1 := (kc (N 4)) in\n                 let c00 := (comm v0 k0) in\n                 let c01 := (comm v0 k1) in\n                 let c10 := (comm v1 k0) in\n                 let c11 := (comm v1 k1) in\n                 let b00 := (bl c00 t r0) in\n                 let b11 := (bl c11 t r1) in\n                 let b10 := (bl c10 t r0) in\n                 let b01 := (bl c01 t r0) in\n                 let t2 := ({{ 5 := (bl c00 t r0) }} ({{ 6:=(bl c11 t r1) }} t0)) in\n                 let t3 := ({{ 5 := (bl c00 t r0) }} ({{ 6:=(bl c11 t r1) }} t1)) in\n                 let t4 := ({{ 5 := (bl c10 t r0) }} ({{ 6:=(bl c01 t r1) }} t0)) in\n                 let t5 := ({{ 5 := (bl c10 t r0) }} ({{ 6:=(bl c01 t r1) }} t1)) in\n                 let e00 := (enc ((c00, ((ub c00 t r0 t2), (N 0))), TWO) (pke 11) (er 7)) in\n                 let e11 := (enc ((c11, ((ub c11 t r1 t3), (N 1))), TWO) (pke 11) (er 8)) in\n                 let e10 := (enc ((c10, ((ub c10 t r0 t4), (N 0))), TWO) (pke 11) (er 7)) in\n                 let e01 := (enc ((c01, ((ub c01 t r1 t5), (N 1))), TWO) (pke 11) (er 8)) in\n                 let pv00 := (c00, ((ub c00 t r0 t2), (N 0))) in\n                 let pv11 := (c11, ((ub c11 t r1 t3), (N 1))) in\n                 let pv10 := (c10, ((ub c10 t r0 t4), (N 0))) in\n                 let pv01 := (c01, ((ub c01 t r1 t5), (N 1))) in\n                 let phi02:= [msg b00, msg b11, msg e00, msg e11] in\n                 let phi12:= [msg b10, msg b01, msg e10, msg e01] in\n                 let fphi02:= f (toListm phi02) in\n\n                 let s0 := (If (! (isin pv00 ((pi1 (d 1 fphi02)), ((pi1 (d 2 fphi02)), (pi1 (d 3 fphi02)))))) then (shufl (pi1 (d 1 fphi02)) (pi1 (d 2 fphi02)) (pi1 (d 3 fphi02))) else O)in\n\n                 let dv0 := (If (dist fphi02) & (pvchecks fphi02) then s0 else |_) in\n                 let fphi12:= f (toListm phi12) in\n                 let s1 := (If (! (isin pv10 ((pi1 (d 1 fphi12)), ((pi1 (d 2 fphi12)), (pi1 (d 3 fphi12)))))) then (shufl (pi1 (d 1 fphi12)) (pi1 (d 2 fphi12)) (pi1 (d 3 fphi12))) else O)in\n                 let dv1 := (If (dist fphi12) & (pvchecks fphi12) then s1 else |_) in\n                 let acc00 := (acc c00 t r0 t2) in\n                 let acc11 := (acc c11 t r1 t3) in\n                 let acc10 := (acc c10 t r0 t4) in\n                 let acc01 := (acc c01 t r1 t5) in\n                 let phi03:= phi02 ++[msg dv0] in\n                 let phi13:= phi12 ++[msg dv1] in\n                 let fphi03 := f (toListm phi03) in\n                 let l00 := (If (bnlcheck c00 (N 0) fphi03) then (enc ((label c00 fphi03), (k0, THREE)) (pke 11) (er 9)) else O) in\n                 let l11 := (If (bnlcheck c11 (N 1) fphi03) then (enc ((label c11 fphi03), (k1, THREE)) (pke 11) (er 10)) else O) in\n                 let fphi13 := f (toListm phi13) in\n                 let l10 := (If (bnlcheck c10 (N 0) fphi13) then (enc ((label c10 fphi13), (k0, THREE)) (pke 11) (er 9)) else O) in\n                 let l01 := (If (bnlcheck c01 (N 1) fphi13) then (enc ((label c01 fphi13), (k1, THREE)) (pke 11) (er 10)) else O) in\n                 let phi05:= phi03++[msg l00, msg l11] in\n                 let phi15:= phi13++[msg l10, msg l01] in\n                 let fphi05 := f (toListm phi05) in\n                 let fphi15 := f (toListm phi15) in\n                 let do0 := (If (dist fphi05)& (pochecks fphi05)& (((isink k0 fphi05)&(isink k1 fphi05)) or (! ((isink k0 fphi05)or (isink k1 fphi05)))) then (sotrm fphi05) else |_) in\n   let do1 := (If (dist fphi15)& (pochecks fphi15)& ((isink k0 fphi15)&(isink k1 fphi15)) (* or (! ((isink k0 fphi15)or (isink k1 fphi15)))) *) then (sotrm fphi15) else |_) in\n                 let t0s0 := (If acc00 & acc11 then ((e00, (e11, dv0)), (l00, (l11, do0))) else |_) in\n                 let t1s1 := (If acc10 & acc01 then ((e10, (e01, dv1)), (l10, (l01, do1))) else |_) in\n                 (occur_name_mylist 100 [msg t, msg t0, msg t1] = false) -> (Fresh (cons 0 nil) [msg t, msg t2, msg t3, msg t4, msg t5] = true) ->\n                 [msg b00, msg b11, msg t0s0] ~ [msg b10, msg b01, msg t1s1].\n\nProof.            intros.\n                      unfold t0s0, t1s1, l00, l10, bnlcheck.\n                      (** x ~ y **)\n                      (**x~ x' and y~y', x' ~ y' **)\n                      (** replace the first voters' nonce (N 0) with a fresh nonce (N 20) **)\n\n                      unfold do0, dv0.\n                      unfold s0. unfold e00.\nAxiom dummy: forall {n} (z z': mylist n), z ~ z'.\npose proof(dummy  [msg b00, msg b11,\n   msg\n     (If (acc00) & acc11\n         then (e00,\n              (e11,\n              If (dist fphi02) & (pvchecks fphi02)\n                 then If ! (isin pv00 (pi1 (d 1 fphi02), (pi1 (d 2 fphi02), pi1 (d 3 fphi02))))\n                         then shufl (pi1 (d 1 fphi02)) (pi1 (d 2 fphi02)) (pi1 (d 3 fphi02))\n                         else O\n                 else |_),\n              (l00,\n              (l11,\n              If (dist fphi05) &\n                 (pochecks fphi05) & ((isin k0 fphi05) & (isin k1 fphi05)) or ! ((isin k0 fphi05) or (isin k1 fphi05))\n                 then sotrm fphi05\n                 else |_)))\n         else |_)] (let phi02' := [msg b00, msg b11, msg {(c00, (ub c00 t r0 t2, N 20), TWO) }_ 11 ^^ 7 , msg e11] in\n                                          let fphi02':= f (toListm phi02') in\n                                          let s0' := (If (! (isin pv00 ((pi1 (d 1 fphi02')), ((pi1 (d 2 fphi02')), (pi1 (d 3 fphi02')))))) then (shufl (pi1 (d 1 fphi02')) (pi1 (d 2 fphi02')) (pi1 (d 3 fphi02'))) else O) in\n                                          let dv0' :=  (If (dist fphi02') & (pvchecks fphi02') then s0' else |_) in\n                                          let phi03':= phi02' ++ [msg (shufl (pi1 (d 1 fphi02')) (pi1 (d 2 fphi02')) (pi1 (d 3 fphi02')))] in\n                                          let fphi03':= f (toListm phi03') in\n                                          let l00' := (If (bnlcheck c00 (N 0) fphi03') then (enc ((label c00 fphi03'), (k0, THREE)) (pke 11) (er 9)) else O) in\n                                          let l11' := (If (bnlcheck c11 (N 1) fphi03') then (enc ((label c11 fphi03'), (k1, THREE)) (pke 11) (er 10)) else O) in\n                                          let phi05':= phi03' ++ [msg l00', msg l11'] in\n                                          let fphi05':= f (toListm phi05') in\n                                          let do0' := (If (dist fphi05')& (pochecks fphi05')& (((isink k0 fphi05')&(isink k1 fphi05')) or (! ((isink k0 fphi05')or (isink k1 fphi05')))) then (sotrm fphi05') else |_) in\n                                          [msg b00, msg b11, msg (If (acc00) & acc11 then ( (enc (c00, (ub c00 t r0 t2, N 20), TWO) (pke 11) (er 9)) , (e11, dv0'), (l00', (l11', do0'))) else |_)])).\n unfold e10.\nassert( (let phi02' :=\n          [msg b00, msg b11,\n          msg {(c00, (ub c00 t r0 t2, N 20), TWO) }_ 11 ^^ 7,\n          msg e11] in\n         let fphi02' := f (toListm phi02') in\n        let s0' :=\n          If ! (isin pv00\n                  (pi1 (d 1 fphi02'), (pi1 (d 2 fphi02'), pi1 (d 3 fphi02'))))\n             then shufl (pi1 (d 1 fphi02')) (pi1 (d 2 fphi02'))\n                    (pi1 (d 3 fphi02'))\n             else O in\n        let dv0' := If (dist fphi02') & (pvchecks fphi02')\n                       then s0'\n                       else |_ in\n        let phi03' :=\n          phi02' ++\n          [msg\n             (shufl (pi1 (d 1 fphi02')) (pi1 (d 2 fphi02'))\n                (pi1 (d 3 fphi02')))] in\n        let fphi03' := f (toListm phi03') in\n        let l00' :=\n          If bnlcheck c00 (N 0) fphi03'\n             then (enc (label c00 fphi03', (k0, THREE)) (pke 11) (er 9))\n             else O in\n        let l11' :=\n          If bnlcheck c11 (N 1) fphi03'\n             then (enc (label c11 fphi03', (k1, THREE)) (pke 11) (er 10))\n             else O in\n        let phi05' := phi03' ++ [msg l00', msg l11'] in\n        let fphi05' := f (toListm phi05') in\n        let do0' :=\n          If (dist fphi05') &\n             (pochecks fphi05') &\n             ((isink k0 fphi05') & (isink k1 fphi05')) (*or\n             ! ((isink k0 fphi05') or (isink k1 fphi05')) *)\n             then sotrm fphi05'\n             else |_ in\n        [msg b00, msg b11,\n        msg\n          (If (acc00) & acc11\n              then ((enc (c00, (ub c00 t r0 t2, N 20), TWO) (pke 11) (er 9)),\n                   (e11, dv0'), (l00', (l11', do0')))\n           else |_)]) ~\n\n\n                      (let phi12' :=\n          [msg b10, msg b01,\n          msg {(c10, (ub c10 t r0 t4, N 20), TWO) }_ 11 ^^ 7,\n          msg e01] in\n        let fphi12' := f (toListm phi12') in\n        let s1' :=\n          If ! (isin pv10\n                  (pi1 (d 1 fphi12'), (pi1 (d 2 fphi12'), pi1 (d 3 fphi12'))))\n             then shufl (pi1 (d 1 fphi12')) (pi1 (d 2 fphi12'))\n                    (pi1 (d 3 fphi12'))\n             else O in\n        let dv1' := If (dist fphi12') & (pvchecks fphi12')\n                       then s1'\n                       else |_ in\n        let phi13' :=\n          phi12' ++\n          [msg\n             (shufl (pi1 (d 1 fphi12')) (pi1 (d 2 fphi12'))\n                (pi1 (d 3 fphi12')))] in\n        let fphi13' := f (toListm phi13') in\n        let l10' :=\n          If bnlcheck c10 (N 0) fphi13'\n             then (enc (label c10 fphi13', (k0, THREE)) (pke 11) (er 9))\n             else O in\n        let l01' :=\n          If bnlcheck c10 (N 1) fphi13'\n             then (enc (label c10 fphi13', (k1, THREE)) (pke 11) (er 10))\n             else O in\n        let phi15' := phi13' ++ [msg l10', msg l01'] in\n        let fphi15' := f (toListm phi15') in\n        let do1' :=\n          If (dist fphi15') &\n             (pochecks fphi15') &\n             ((isink k0 fphi15') & (isink k1 fphi15')) (* or\n             ! ((isink k0 fphi15') or (isink k1 fphi15')) *)\n             then sotrm fphi15'\n             else |_ in\n        [msg b10, msg b01,\n        msg\n          (If (acc10) & acc01\n              then ((enc (c10, (ub c10 t r0 t4, N 20), TWO) (pke 11) (er 9)),\n                   (e01, dv1'), (l10', (l01', do1')))\n           else |_)])).\nsimpl.\nassert( (ncheck (N 0) (f\n                                 [b10; b01; (enc (c10, (ub c10 t r0 t4, N 20), TWO) (pke 11) (er 7)); e01;\n                                 shufl (pi1 (d 1 (f [b10; b01; (enc (c10, (ub c10 t r0 t4, N 20), TWO) (pke 11) (er 7)); e01])))\n                                   (pi1 (d 2 (f [b10; b01; (enc (c10, (ub c10 t r0 t4, N 20), TWO) (pke 11) (er 7)); e01])))\n                                   (pi1 (d 3 (f [b10; b01; (enc (c10, (ub c10 t r0 t4, N 20), TWO) (pke 11) (er 7)); e01])))])) ## FAlse).\nunfold ncheck.\nunfold isin.\n\nLemma tau1: forall x y z, (tau 1 (x, (y, z))) # x.\nProof. intros. unfold tau. rewrite proj1; auto. reflexivity.\nQed.\nLemma tau2: forall x y z, (tau 2 (x, (y, z))) # y.\nProof. intros. unfold tau; rewrite proj2, proj1;auto. reflexivity. Qed.\nLemma tau3: forall x y z, (tau 3 (x, (y, z))) # z.\nProof. intros. unfold tau. repeat rewrite proj2; try reflexivity.\nQed.\n(*Eval compute in FAlse or TRue. *)\nrewrite tau1, tau2, tau3.\nAxiom freshneq: forall (n : nat) (m : message),\n       ^? (m) = true  -> Fresh (cons n nil) [msg m] = true ->\n       ([bol (N n) #? m]) ~ [bol FAlse].\nsimpl.\npose proof(freshneq 0 (pi2\n      (pi2\n         (pi2\n            (pi1\n               (f\n                  [b10; b01; (enc (c10, (ub c10 t r0 t4, N 20), TWO) (pke 11) (er 7));\n                  e01;\n                  shufl\n                    (pi1\n                       (d 1\n                          (f\n                             [b10; b01;\n                             (enc (c10, (ub c10 t r0 t4, N 20), TWO) (pke 11) (er 7));\n                             e01])))\n                    (pi1\n                       (d 2\n                          (f\n                             [b10; b01;\n                             (enc (c10, (ub c10 t r0 t4, N 20), TWO) (pke 11) (er 7));\n                             e01])))\n                    (pi1\n                       (d 3\n                          (f\n                             [b10; b01;\n                             (enc (c10, (ub c10 t r0 t4, N 20), TWO) (pke 11) (er 7));\n                             e01])))])))))).\nsimpl in H8.\n\nsimpl in H1. rewrite andb_true_iff in H1. inversion H1.\nrepeat rewrite H9 in H8.\nunfold t4, t5 in H8.\n rewrite  clos_sub_vtrm in H8;auto.\n rewrite  clos_sub_vtrm in H8;auto.\nrepeat rewrite andb_true_r, andb_true_l in H8.\n unfold Fresh in H8, H6.  simpl in H8, H6.\n (** ********)\n assert( occur_name_msg 0 t = false).\ndestruct (occur_name_msg 0 t). simpl in H6.\ninversion H6. reflexivity.\nassert( occur_name_msg 0 t2 = false).\ndestruct (occur_name_msg 0 t2).\nsimpl in H6. rewrite H11 in H6. simpl in H6. inversion H6. reflexivity.\nassert( occur_name_msg 0 t3 = false).\ndestruct (occur_name_msg 0 t3).\nsimpl in H6. rewrite H12 in H6. simpl in H6. inversion H6. rewrite H11. reflexivity. reflexivity.\nassert( occur_name_msg 0 t4 = false).\ndestruct (occur_name_msg 0 t4).\nsimpl in H6. rewrite H11, H12, H13 in H6. simpl in H6. inversion H6. reflexivity.\nassert( occur_name_msg 0 t5 = false).\ndestruct (occur_name_msg 0 t5).\nsimpl in H6. rewrite H11, H12, H13, H14 in H6. simpl in H6. inversion H6. reflexivity.\nfold t4 in H8.\nrewrite H11, H14, H15 in H8. simpl in H8.\nAxiom consteql: forall x f, const_bol f = true -> [bol x]~[bol f] -> x ## f.\nassert( (const_bol FAlse) = true). reflexivity.\napply consteql in H8; auto.\nrewrite H8.\n(** prove N0 is fresh in tau2 of the decrypted message **)\n\n\npose proof(freshneq 0 (pi2\n      (pi2\n         (pi2\n            (pi1\n               (pi2 (f\n                  [b10; b01; (enc (c10, (ub c10 t r0 t4, N 20), TWO) (pke 11) (er 7));\n                  e01;\n                  shufl\n                    (pi1\n                       (d 1\n                          (f\n                             [b10; b01;\n                             (enc (c10, (ub c10 t r0 t4, N 20), TWO) (pke 11) (er 7));\n                             e01])))\n                    (pi1\n                       (d 2\n                          (f\n                             [b10; b01;\n                             (enc (c10, (ub c10 t r0 t4, N 20), TWO) (pke 11) (er 7));\n                             e01])))\n                    (pi1\n                       (d 3\n                          (f\n                             [b10; b01;\n                             (enc (c10, (ub c10 t r0 t4, N 20), TWO) (pke 11) (er 7));\n                             e01])))]))))))).\nsimpl in H17.\n\nrepeat rewrite H9 in H17.\nunfold t4, t5 in H17.\n rewrite  clos_sub_vtrm in H17;auto.\n rewrite  clos_sub_vtrm in H17;auto. simpl in H17.\n unfold Fresh in H17; simpl in H17.\n fold t4 in H17.\n rewrite H11, H14, H15 in H17. simpl in H17.\n\n\n\napply consteql in H17; auto.\nrewrite H17.\nclear H8 H17.\n\npose proof(freshneq 0 (pi2 (pi2 (pi2 (pi2 (pi2 (f\n                  [b10; b01; (enc (c10, (ub c10 t r0 t4, N 20), TWO) (pke 11) (er 7));\n                  e01;\n                  shufl\n                    (pi1\n                       (d 1\n                          (f\n                             [b10; b01;\n                             (enc (c10, (ub c10 t r0 t4, N 20), TWO) (pke 11) (er 7));\n                             e01])))\n                    (pi1\n                       (d 2\n                          (f\n                             [b10; b01;\n                             (enc (c10, (ub c10 t r0 t4, N 20), TWO) (pke 11) (er 7));\n                             e01])))\n                    (pi1\n                       (d 3\n                          (f\n                             [b10; b01;\n                             (enc (c10, (ub c10 t r0 t4, N 20), TWO) (pke 11) (er 7));\n                             e01])))]))))))).\nsimpl in H8.\nunfold t4, t5 in H8.\n rewrite  clos_sub_vtrm in H8;auto.\n rewrite  clos_sub_vtrm in H8;auto. simpl in H8.\nrepeat rewrite H9 in H8. simpl in H8.\nunfold Fresh in H8; simpl in H8.\nfold t4 in H8.\nrewrite H11, H14, H15 in H8. simpl in H8.\napply consteql in H8; auto.\nrewrite H8; clear H8; auto.\nunfold orB.\n repeat rewrite IFFALSE_B. reflexivity.\n  (left;inversion H4; unfold distMvars; simpl; try rewrite H17; try rewrite H18; try reflexivity).\n(left;inversion H4; unfold distMvars; simpl; try rewrite H17; try rewrite H18; try rewrite H19; try reflexivity).\n(left;inversion H4; unfold distMvars; simpl; try rewrite H17; try rewrite H18; try rewrite H19; try reflexivity).\n(left;inversion H4; unfold distMvars; simpl; try rewrite H17; try rewrite H18; try rewrite H19; try reflexivity).\n(left;inversion H4; unfold distMvars; simpl; try rewrite H17; try rewrite H18; try rewrite H19; try rewrite H11; try rewrite H12; try reflexivity).\n(left;inversion H4; unfold distMvars; simpl; try rewrite H17; try rewrite H18; try rewrite H19; try rewrite H11; try rewrite H12; try reflexivity).\n\n(*******************************************)\nassert( let x:= (enc (c10, (ub c10 t r0 t4, N 20), TWO) (pke 11) (er 7)) in (bnlcheck c10 (N 0)\n                  (f\n                     [b10; b01; x; e01;\n                     shufl (pi1 (d 1 (f [b10; b01; x; e01])))\n                       (pi1 (d 2 (f [b10; b01; x; e01])))\n                       (pi1 (d 3 (f [b10; b01; x; e01])))])) ## FAlse).\nsimpl. unfold bnlcheck.\nrewrite H8. repeat rewrite andB_FAlse_r; try reflexivity.\nrewrite H9.\nrewrite IFFALSE_M.\nclear H8 H9.\n(********************************************)\n\nassert( let x:= (enc (c00, (ub c00 t r0 t2, N 20), TWO) (pke 11) (er 7)) in  (bnlcheck c00 (N 0)\n                    (f\n                       [b00; b11; x; e11;\n                       shufl (pi1 (d 1 (f [b00; b11; x; e11])))\n                         (pi1 (d 2 (f [b00; b11; x; e11])))\n                         (pi1 (d 3 (f [b00; b11; x; e11])))])) ## FAlse).\n unfold bnlcheck.\nunfold ncheck. unfold isin.\nrewrite tau1, tau2, tau3.\npose proof( freshneq 0 (let x:= (enc (c00, (ub c00 t r0 t2, N 20), TWO) (pke 11) (er 7)) in (tau 3 (pi2 (tau 1 (f\n                       [b00; b11; x; e11;\n                       shufl (pi1 (d 1 (f [b00; b11; x; e11])))\n                         (pi1 (d 2 (f [b00; b11; x; e11])))\n                         (pi1 (d 3 (f [b00; b11; x; e11])))])))))).\nsimpl in H8.\nunfold t2, t3 in H8.\n rewrite  clos_sub_vtrm in H8;auto.\n rewrite  clos_sub_vtrm in H8;auto. simpl in H8.\nsimpl in H1.\nsimpl in H1. rewrite andb_true_iff in H1. inversion H1.\nrepeat rewrite H9 in H8.\nsimpl in H8.\nunfold Fresh in H8, H6; simpl in H8, H6.\nassert( occur_name_msg 0 t = false).\ndestruct (occur_name_msg 0 t). simpl in H6.\ninversion H6. reflexivity.\nassert( occur_name_msg 0 t2 = false).\ndestruct (occur_name_msg 0 t2).\nsimpl in H6. rewrite H11 in H6. simpl in H6. inversion H6. reflexivity.\nassert( occur_name_msg 0 t3 = false).\ndestruct (occur_name_msg 0 t3).\nsimpl in H6. rewrite H12 in H6. simpl in H6. inversion H6. rewrite H11. reflexivity. reflexivity.\nfold t2 in H8.\nrewrite H11, H12, H13 in H8. simpl in H8.\napply consteql in H8; auto; try  (left;inversion H4; unfold distMvars; simpl; try rewrite H16; try rewrite H17; try rewrite H18; try rewrite H19; try reflexivity).\nAxiom extcomphid: forall {n} (z z': mylist n), z ~ z'.\n(******)\npose proof( freshneq 0 (let x:= (enc (c00, (ub c00 t r0 t2, N 20), TWO) (pke 11) (er 7)) in (tau 3 (pi2 (tau 2 (f\n                       [b00; b11; x; e11;\n                       shufl (pi1 (d 1 (f [b00; b11; x; e11])))\n                             (pi1 (d 2 (f [b00; b11; x; e11])))\n                             (pi1 (d 3 (f [b00; b11; x; e11])))])))))).\nsimpl in H14.\nrewrite H9 in H14.\nunfold t2, t3 in H14.\n rewrite  clos_sub_vtrm in H14;auto.\n rewrite  clos_sub_vtrm in H14;auto. simpl in H14.\nunfold Fresh in H14. simpl in H14.\nfold t2 in H14.\nrewrite H11, H12, H13 in H14. simpl in H14.\napply consteql in H14; auto; try (left;inversion H4; unfold distMvars; simpl; try rewrite H16; try rewrite H17; try rewrite H18; try rewrite H19; try reflexivity).\n(*******************************)\npose proof(freshneq 0 (let x:= (enc (c00, (ub c00 t r0 t2, N 20), TWO) (pke 11) (er 7)) in (tau 3 (pi2 (tau 3 (f\n                       [b00; b11; x; e11;\n                       shufl (pi1 (d 1 (f [b00; b11; x; e11])))\n                             (pi1 (d 2 (f [b00; b11; x; e11])))\n                             (pi1 (d 3 (f [b00; b11; x; e11])))])))))).\nsimpl in H15.\nrewrite H9 in H15.\nunfold t2, t3 in H15.\n rewrite  clos_sub_vtrm in H15;auto.\n rewrite  clos_sub_vtrm in H15;auto. simpl in H15.\nunfold Fresh in H15, H6. simpl in H15, H6.\nfold t2 in H15.\nrewrite H11, H12, H13 in H15. simpl in H15.\napply consteql in H15; auto; try (left; try inversion H4; unfold distMvars; simpl; try rewrite H16; try rewrite H17; try reflexivity).\nrewrite H8, H14, H15. unfold orB. repeat rewrite IFFALSE_B. simpl.\nrepeat rewrite andB_FAlse_r; try reflexivity.\n(left;inversion H4; unfold distMvars; simpl; try rewrite H16; try rewrite H17; try rewrite H18; try rewrite H19; try reflexivity).\n(left;inversion H4; unfold distMvars; simpl; try rewrite H16;  try rewrite H17; try rewrite H18; try rewrite H19; try reflexivity).\n(left;inversion H4; unfold distMvars; simpl; try rewrite H16;  try rewrite H17; try rewrite H18; try rewrite H19; try reflexivity).\n(left;inversion H4; unfold distMvars; simpl; try rewrite H15;  try rewrite H16; try rewrite H18; try rewrite H19; try reflexivity).\n(left;inversion H4; unfold distMvars; simpl; try rewrite H9;  try rewrite H10; try rewrite H17; try rewrite H18; try rewrite H19; try reflexivity).\n(left;inversion H4; unfold distMvars; simpl; try rewrite H9;  try rewrite H10; try rewrite H17; try rewrite H18; try rewrite H19; try reflexivity). rewrite H8.\nrewrite IFFALSE_M.\nunfold isink.\nunfold k0.\n(** we need to prove that the attacker cannot compute the commitment key **)\npose proof (ENCCCA2).\nAxiom infeasible_comp_ck: forall n t g, (closMsg t) = true ->\n                                          (** (distMvars [msg t']) = (cons m nil) ->  I can prove this:Fresh (cons n nil) [msg t, msg t'] = true **) ((g t) #? (kc (N n)))  ## FAlse.\n(*** I will prove this later **) unfold b00.\n(*Eval compute in b00. *)\nAxiom eqm_sym: forall m1 m2, (m1 #? m2) ## (m2 #? m1).\n repeat rewrite eqm_sym with (m1:= (kc (N 3))).\nrepeat rewrite infeasible_comp_ck with (n:= 3); auto.\nunfold orB.\nrepeat rewrite IFFALSE_B.\nrepeat rewrite andB_FAlse_l.  repeat rewrite andB_FAlse_r. repeat rewrite IFFALSE_M. simpl.\n(** we replace the encryption that emits *)\n\n\npose proof(compHid_ext).\napply extcomphid.\n\n simpl.\nsimpl in H1;\nrewrite andb_true_iff in H1;\ninversion H1;\nrewrite H10; unfold t4, t5; repeat rewrite clos_sub_vtrm;try left; inversion H4; unfold distMvars; simpl; try rewrite H12; try rewrite H13; try reflexivity.\n\nsimpl.\nsimpl in H1;\nrewrite andb_true_iff in H1;\ninversion H1;\nrewrite H10; unfold t4, t5; repeat rewrite clos_sub_vtrm;try left; inversion H4; unfold distMvars; simpl; try rewrite H12; try rewrite H13; try reflexivity.\n\nsimpl.\nsimpl in H1;\nrewrite andb_true_iff in H1;\ninversion H1;\nrewrite H10; unfold t4, t5; repeat rewrite clos_sub_vtrm;try left; inversion H4; unfold distMvars; simpl; try rewrite H12; try rewrite H13; try reflexivity.\n\n\nsimpl.\nsimpl in H1;\nrewrite andb_true_iff in H1;\ninversion H1;\nrewrite H10; unfold t2, t3; repeat rewrite clos_sub_vtrm;try left; inversion H4; unfold distMvars; simpl; try rewrite H12; try rewrite H13; try reflexivity.\n\n\n\nsimpl.\nsimpl in H1;\nrewrite andb_true_iff in H1;\ninversion H1;\nrewrite H10; unfold t2, t3; repeat rewrite clos_sub_vtrm;try left; inversion H4; unfold distMvars; simpl; try rewrite H12; try rewrite H13; try reflexivity.\n\nsimpl.\nsimpl in H1;\nrewrite andb_true_iff in H1;\ninversion H1;\nrewrite H10; unfold t2, t3; repeat rewrite clos_sub_vtrm;try left; inversion H4; unfold distMvars; simpl; try rewrite H12; try rewrite H13; try reflexivity.\napply extcomphid.\nQed.\nEnd lemma148.\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/lemma14.8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2657285759455107}}
{"text": "From iris Require Import program_logic.weakestpre.\nFrom iris.proofmode Require Import tactics.\nFrom iris.base_logic.lib Require Import invariants gen_heap.\n\nLocal Notation \"l ↦ v\" := (mapsto l (DfracOwn 1) v)\n  (at level 20, format \"l  ↦  v\") : bi_scope.\n\nFrom st.prelude Require Import big_op_three.\n\nFrom st.STLCmuVS Require Import lang contexts.\nFrom st.STLCmuST Require Import wkpre lang types contexts.\n\nFrom st.backtranslations.st_sem Require Import ghost heap_emul.base.\nFrom st.backtranslations.st_sem.correctness.st_le_sem.logrel Require Import lift.\nFrom st Require Import resources.\n\nSection value_relation.\n\n  Context `{Σ : !gFunctors} `{st_le_semΣ_inst : !st_le_semΣ Σ}.\n\n  (* Context `{inG_Σ_auth_nat_to_ag_loc : !inG Σ () } *)\n  Context (Δ : list (gname * gname)).\n\n  Fixpoint valrel_typed_gen_pre (Ψ : typeO -n> valO -n> STLCmuVS.lang.valO -n> iPropO Σ) (τ : typeO) : valO -n> STLCmuVS.lang.valO -n> iPropO Σ := λne v v',\n    (match τ with\n     | TUnit => ⌜ v = (()%Vₛₜ : valO) ⌝ ∧ ⌜ v' = (()%Vₙₒ : STLCmuVS.lang.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' = STLCmuVS.lang.InjLV vi' ⌝ ∧ valrel_typed_gen_pre Ψ τ1 vi vi') ∨\n                              (⌜ v = InjRV vi ⌝ ∧ ⌜ v' = STLCmuVS.lang.InjRV vi' ⌝ ∧ valrel_typed_gen_pre Ψ τ2 vi vi')\n     | TArrow τ1 τ2 => □ (∀ w w', valrel_typed_gen_pre Ψ τ1 w w' -∗ lift MaybeStuck (valrel_typed_gen_pre Ψ τ2) (v w) (v' w'))\n     | TRec τb => ∃ w w', ⌜ v = FoldV w ⌝ ∧ ⌜ v' = STLCmuVS.lang.FoldV w' ⌝ ∧ ▷ (Ψ τb.[TRec τb/] w w')\n     | TVar X => False\n     | TSTref ρ τ =>\n       match ρ with\n       | TVar X =>\n         match Δ !! X with\n         | Some (γ, γ') => ∃ (i : nat) (l : loc), ⌜ v = l ⌝ ∧ i ↪[γ]□ l ∧ ⌜ v' = i ⌝ ∧\n                             inv (nroot .@ γ .@ γ' .@ i) (∃ (w : val) (w' : STLCmuVS.lang.val), i ↪[γ'] w' ∗ l ↦ w ∗ valrel_typed_gen_pre Ψ τ w w')\n         | None => False\n         end\n       | _ => False\n       end\n     | TST ρ τ' =>\n       match ρ with\n       | TVar X =>\n         match Δ !! X with\n         | Some (γ, γ') => ∀ psᵢ : list (prod loc STLCmuVS.lang.val),\n             let lsᵢ := psᵢ.*1 in\n             let vsᵢ := psᵢ.*2 in\n             □ (auth_list γ lsᵢ ∗ auth_list γ' vsᵢ -∗\n                          WP RunST v ?{{ w, ∃ (w' : STLCmuVS.lang.val) (psₜ : list (prod loc STLCmuVS.lang.val)),\n                                                let lsₜ := psₜ.*1 in\n                                                let vsₜ := psₜ.*2 in\n                                                auth_list γ lsₜ ∗\n                                                auth_list γ' vsₜ ∗\n                                                ⌜ rtc STLCmuVS_step (v' (encode vsᵢ)) (encode vsₜ, w')%Vₙₒ ⌝ ∧\n                                                valrel_typed_gen_pre Ψ τ' w w'\n                                           }}\n               )\n         | None => True\n         end\n       | _ => True\n       end\n     end)%I.\n\n  Definition valrel_typed_gen (Ψ : typeO -n> valO -n> STLCmuVS.lang.valO -n> iPropO Σ) : typeO -n> valO -n> STLCmuVS.lang.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    - intros v v'. simpl. destruct τ1; try done. clear IHτ1.\n      destruct (Δ !! X) as [γ|] eqn:eq; auto.\n      f_equiv. f_equiv. intros i. f_equiv. f_equiv. f_equiv. f_equiv. f_equiv. f_equiv. solve_contractive.\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ₙₒ : STLCmuVS.lang.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 MaybeStuck (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' = STLCmuVS.lang.InjLV vi' ⌝ ∧ valrel_typed τ1 vi vi') ∨ (⌜ v = InjRV vi ⌝ ∧ ⌜ v' = STLCmuVS.lang.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' = STLCmuVS.lang.FoldV w' ⌝ ∧ ▷ (valrel_typed τ.[TRec τ/] w w'))%I.\n  Proof. rewrite valrel_typed_unfold. 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  Lemma valrel_typed_TSTRef_unfold ρ τ v v' :\n    valrel_typed (TSTref ρ τ) v v' ≡\n                 (match ρ with\n                  | TVar X =>\n                    match Δ !! X with\n                    | Some (γ, γ') => ∃ (i : nat) (l : loc), ⌜ v = l ⌝ ∧ i ↪[γ]□ l ∧ ⌜ v' = i ⌝ ∧\n                                                    inv (nroot .@ γ .@ γ' .@ i) (∃ (w : val) (w' : STLCmuVS.lang.val), i ↪[γ'] w' ∗ l ↦ w ∗ valrel_typed τ w w')\n                 | None => False\n                  end\n                 | _ => False\n                  end)%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_TST_unfold ρ τ v v' :\n    valrel_typed (TST ρ τ) v v' ≡\n      (match ρ with\n       | TVar X =>\n         match Δ !! X with\n         | Some (γ, γ') => ∀ psᵢ : list (prod loc STLCmuVS.lang.val),\n             let lsᵢ := psᵢ.*1 in\n             let vsᵢ := psᵢ.*2 in\n             □ (auth_list γ lsᵢ ∗ auth_list γ' vsᵢ -∗\n                          WP RunST v ?{{ w, ∃ (w' : STLCmuVS.lang.val) (psₜ : list (prod loc STLCmuVS.lang.val)),\n                                                let lsₜ := psₜ.*1 in\n                                                let vsₜ := psₜ.*2 in\n                                                auth_list γ lsₜ ∗\n                                                auth_list γ' vsₜ ∗\n                                                ⌜ rtc STLCmuVS_step (v' (encode vsᵢ)) (encode vsₜ, w')%Vₙₒ ⌝ ∧\n                                                valrel_typed τ w w'\n                                     }}\n               )\n         | None => True\n         end\n       | _ => True\n       end\n      )%I.\n  Proof. rewrite valrel_typed_unfold. simpl. repeat f_equiv. rewrite valrel_typed_gen_pre_gen'; rewrite -valrel_typed_unfold'; auto. Qed.\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 | τb | ρ τ | ρ τ ] \"IH\";\n      iIntros (v v'); try by rewrite valrel_typed_unfold; iIntros \"#H\".\n    - rewrite valrel_typed_TProd_unfold. iIntros \"H\". iDestruct \"H\" as (v1 v2 v1' v2') \"(-> & -> & H1 & H2)\".\n      iExists v1, v2, v1', v2'. repeat iSplit; auto. iApply (\"IH\" with \"H1\"). iApply (\"IH1\" with \"H2\").\n    - rewrite valrel_typed_TSum_unfold. iIntros \"H\". iDestruct \"H\" as (vi vi') \"[(-> & -> & H1) | (-> & -> & H2)]\"; iExists vi, vi'.\n      + iLeft. repeat iSplit; auto. by iApply (\"IH\" with \"H1\").\n      + iRight. repeat iSplit; auto. by iApply (\"IH1\" with \"H2\").\n    - rewrite valrel_typed_TRec_unfold. iIntros \"H\". iDestruct \"H\" as (w w') \"(-> & -> & H)\". iExists w, w'. repeat iSplitL \"\"; auto.\n      iApply bi.later_persistently_1. iNext. by iApply \"IHlob\".\n    - rewrite valrel_typed_TSTRef_unfold. destruct ρ; auto.\n      destruct (Δ !! X); auto. destruct p; auto.\n    - rewrite valrel_typed_TST_unfold. destruct ρ; auto.\n      destruct (Δ !! X); auto. destruct p; auto.\n  Qed.\n\nEnd value_relation.\n\nSection expr_relation.\n\n  Context `{Σ : !gFunctors} `{st_le_semΣ_inst : !st_le_semΣ Σ}.\n\n  Definition exprel_typed (Δ : list (gname * gname)) : typeO -n> exprO -n> STLCmuVS.lang.exprO -n> iPropO Σ :=\n    λne τ eᵢ eₛ, lift MaybeStuck (valrel_typed Δ τ) eᵢ eₛ.\n\n  Definition open_exprel_typed (Γ : list type) (e : expr) (e' : STLCmuVS.lang.expr) (τ : type) :=\n    ∀ (Δ : list (gname * gname)) (vs : list val) (vs' : list STLCmuVS.lang.val),\n      big_sepL3 (fun τ v v' => valrel_typed Δ τ v v') Γ vs vs' ⊢\n                exprel_typed Δ τ e.[subst_list_val vs] e'.[STLCmuVS.lang.subst_list_val vs'].\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  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  Definition ctx_item_rel_typed (Ci : STLCmuST.contexts.ctx_item) (Ci' : STLCmuVS.contexts.ctx_item) Γ τ Γ' τ' :=\n    ∀ e e', open_exprel_typed Γ e e' τ → open_exprel_typed Γ' (STLCmuST.contexts.fill_ctx_item Ci e) (STLCmuVS.contexts.fill_ctx_item Ci' e') τ'.\n\n  Definition ctx_rel_typed (C : STLCmuST.contexts.ctx) (C' : STLCmuVS.contexts.ctx) Γ τ Γ' τ' :=\n    ∀ e e', open_exprel_typed Γ e e' τ → open_exprel_typed Γ' (STLCmuST.contexts.fill_ctx C e) (STLCmuVS.contexts.fill_ctx C' e') τ'.\n\nEnd expr_relation.\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/definition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2657285759455107}}
{"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 arith_props.\nRequire Import continuity.\nRequire Import continuity2_2.\nRequire Import continuity3_2_v2.\nRequire Export continuity_defs2.\nRequire Export continuity_defs_ceq.\n\nLemma comp_force_int_app_F_c {o} :\n  forall lib (F f : @CTerm o) x z,\n    reduces_toc\n      lib\n      (force_int_F_c x F f)\n      (mkc_integer z)\n    -> {b : nat\n        & forall (e : CTerm) b',\n            b <= b'\n            -> reduces_toc\n                 lib\n                 (force_int_bound_F_c x b' F f e)\n                 (mkc_integer z)}.\nProof.\n  introv r.\n  unfold reduces_toc in r.\n  rw @get_cterm_force_int_F_c in r.\n  simpl in r.\n  apply comp_force_int_app_F in r; exrepnd; eauto with slow.\n  exists b.\n  introv l.\n  pose proof (r0 (get_cterm e) b') as h.\n  repeat (autodimp h hyp); eauto with slow.\n  { rw @free_vars_cterm; sp. }\n  unfold reduces_toc.\n  rw @get_cterm_force_int_bound_F_c; auto.\nQed.\n\nDefinition agree_upto_c {o} lib b (f g : @CTerm o) :=\n  forall (i : Z),\n    Z.abs_nat i < b\n    -> {v1 : CTerm\n       & {v2 : CTerm\n        & reduces_toc lib (mkc_apply f (mkc_integer i)) v1\n        # reduces_toc lib (mkc_apply g (mkc_integer i)) v2\n        # alphaeqc v1 v2}}.\n\nLemma comp_force_int_app_F3_c_2 {o} :\n  forall lib (F f g : @CTerm o) x z b,\n    agree_upto_c lib b f g\n    -> reduces_toc\n         lib\n         (force_int_bound_F_c x b F f (mkc_vbot x))\n         (mkc_integer z)\n    -> reduces_toc\n         lib\n         (force_int_bound_F_c x b F g (mkc_vbot x))\n         (mkc_integer z).\nProof.\n  introv agree r.\n  allunfold @reduces_toc.\n  allrw @get_cterm_force_int_bound_F_c.\n  allsimpl.\n  apply (comp_force_int_app_F3_2 lib (get_cterm F) (get_cterm f) (get_cterm g)); auto;\n  allrw @free_vars_cterm; allsimpl; tcsp; eauto with slow.\n  introv j; apply agree in j.\n  exrepnd.\n  exists (get_cterm v1) (get_cterm v2).\n  destruct_cterms.\n  allunfold @reduces_toc; allsimpl.\n  allunfold @alphaeqc; allsimpl.\n  clear agree.\n  allapply @closed_if_isprog.\n  rw i3.\n  rw i2.\n  dands; auto.\nQed.\n\nLemma comp_force_int_app_F2_c {o} :\n  forall lib (F g : @CTerm o) x z b,\n    reduces_toc\n      lib\n      (force_int_bound_F_c x b F g (mkc_vbot x))\n      (mkc_integer z)\n    -> reduces_toc\n         lib\n         (force_int_F_c x F g)\n         (mkc_integer z).\nProof.\n  introv r.\n  allunfold @reduces_toc.\n  allrw @get_cterm_force_int_bound_F_c.\n  allrw @get_cterm_force_int_F_c.\n  allsimpl.\n  apply (comp_force_int_app_F2 lib (get_cterm F) (get_cterm g) x z b); auto;\n  allrw @free_vars_cterm; allsimpl; tcsp; eauto with slow.\nQed.\n\nLemma mkcv_cont1_mkcv_apply {o} :\n  forall v (t1 t2 : @CVTerm o [v,v]),\n    mkcv_cont1 v (mkcv_apply [v,v] t1 t2)\n    = mkcv_apply [v] (mkcv_cont1 v t1) (mkcv_cont1 v t2).\nProof.\n  introv.\n  destruct_cterms.\n  apply cvterm_eq; simpl; auto.\nQed.\n\nLemma mkcv_cont1_mk_cv {o} :\n  forall v (t : @CTerm o),\n    mkcv_cont1 v (mk_cv [v,v] t)\n    = mk_cv [v] t.\nProof.\n  introv.\n  destruct_cterms.\n  apply cvterm_eq; simpl; auto.\nQed.\n\nLemma mkcv_cont1_mk_cv_app_r {o} :\n  forall v (t : @CVTerm o [v]),\n    mkcv_cont1 v (mk_cv_app_r [v] [v] t)\n    = t.\nProof.\n  introv.\n  destruct_cterms.\n  apply cvterm_eq; simpl; auto.\nQed.\n\nLemma equality_force_int_f_c_T {o} :\n  forall lib (f : @CTerm o) T,\n    member lib f (mkc_fun mkc_int T)\n    -> equality lib f (force_int_f_c nvarx f) (mkc_fun mkc_int T).\nProof.\n  introv m.\n  allrw @equality_in_fun; repnd; dands; auto.\n  introv e.\n\n  allrw @equality_in_int.\n  allunfold @equality_of_int.\n  exrepnd; spcast.\n\n  pose proof (m (mkc_integer k) (mkc_integer k)) as h.\n  autodimp h hyp.\n  { apply equality_in_int.\n    exists k.\n    dands; spcast; apply computes_to_valc_refl; eauto 3 with slow. }\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 e1]\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 e0]\n    |].\n\n  clear dependent a.\n  clear dependent a'.\n\n  unfold force_int_f_c.\n  eapply equality_respects_cequivc_right;\n    [apply cequivc_sym;apply cequivc_beta|].\n  rw @mkcv_cbv_substc_same.\n  unfold force_int_cv.\n  rw @mkcv_add_substc.\n  rw @mkc_var_substc.\n  rw @mkcv_zero_substc.\n\n  eapply equality_respects_cequivc_right;\n    [apply simpl_cequivc_mkc_cbv;\n      apply cequivc_sym;\n      apply cequivc_mkc_add_integer|].\n  rw <- Zplus_0_r_reverse.\n\n  eapply equality_respects_cequivc_right;\n    [apply cequivc_sym;\n      apply reduces_toc_implies_cequivc;\n      apply reduces_toc_mkc_cbv_val;\n      eauto 3 with slow|].\n\n  rw @mkcv_cont1_mkcv_apply.\n  rw @mkcv_apply_substc.\n  rw @mkcv_cont1_mk_cv.\n  rw @csubst_mk_cv.\n  rw @mkcv_cont1_mk_cv_app_r.\n  rw @mkc_var_substc.\n  auto.\nQed.\n\nDefinition agree_upto_red_bc_T {o} lib b (f g : @CTerm o) T :=\n  forall (t1 t2 : CTerm) (i : Z),\n    reduces_toc lib t1 (mkc_integer i)\n    -> reduces_toc lib t2 (mkc_integer i)\n    -> Z.abs_nat i < b\n    -> equality lib (mkc_apply f t1) (mkc_apply g t2) T.\n\nDefinition simple_eq_type {o} lib (T : @CTerm o) :=\n  forall a b,\n    equality lib a b T\n    -> {v1 : CTerm\n        & {v2 : CTerm\n        & reduces_toc lib a v1\n        # reduces_toc lib b v2\n        # alphaeqc v1 v2 }}.\n\nLemma agree_upto_red_bc_T_implies_agree_upto_c {o} :\n  forall lib b (f g : @CTerm o) T,\n    simple_eq_type lib T\n    -> agree_upto_red_bc_T lib b f g T\n    -> agree_upto_c lib b f g.\nProof.\n  introv spe agree j.\n  pose proof (agree (mkc_integer i) (mkc_integer i) i) as h.\n  repeat (autodimp h hyp); try (apply reduces_toc_refl).\nQed.\n\nDefinition continuous_T {o} lib (F : @CTerm o) T :=\n  forall f,\n    member lib f (mkc_fun mkc_int T)\n    -> {b : nat\n        & forall g,\n            member lib g (mkc_fun mkc_int T)\n            -> agree_upto_red_bc_T lib b f g T\n            -> equality_of_int_tt lib (mkc_apply F f) (mkc_apply F g)}.\n\n(*\n\n  F f -> z\n  => (* by typing *)\n  F (\\x.let x:=(x + 0) in f(x)) -> z\n  => (* by comp_force_int_app_F *)\n  exists b. forall e.\n    F (\\x.let x:=(let x:=x in if |x|<b then x else e) in f(x)) -> z\n    => (* if e cannot get caught, because the 2 functions agree upto b *)\n    F (\\x.let x:=(let x:=x in if |x|<b then x else e) in g(x)) -> z\n    => (* comp_force_int_app_F2 *)\n    F (\\x.let x:=(x + 0) in g(x)) -> z\n    => (* by typing *)\n    F g -> z\n\n*)\nLemma continuity_axiom {o} :\n  forall lib (F : @CTerm o) T,\n    simple_eq_type lib T\n    -> member lib F (mkc_fun (mkc_fun mkc_int T) mkc_int)\n    -> continuous_T lib F T.\nProof.\n  introv spe mT mt.\n\n  assert (member lib (mkc_apply F f) mkc_int) as ma.\n  { rw @equality_in_fun in mT; repnd.\n    apply mT; auto. }\n\n  (* by typing *)\n  assert (equality lib f (force_int_f_c nvarx f) (mkc_fun mkc_int T)) as ea.\n  { apply equality_force_int_f_c_T; auto. }\n\n  assert (equality lib  (mkc_apply F f) (mkc_apply F (force_int_f_c nvarx f)) mkc_int) as mb.\n  { rw @equality_in_fun in mT; repnd.\n    apply mT; auto. }\n\n  apply equality_in_int in mb.\n  apply equality_of_int_imp_tt in mb.\n  unfold equality_of_int_tt in mb; exrepnd; GC.\n\n  (* 1st step *)\n  pose proof (comp_force_int_app_F_c lib F f nvarx k) as step1.\n  autodimp step1 hyp.\n  { rw @computes_to_valc_iff_reduces_toc in mb0; repnd; auto. }\n  destruct step1 as [b step1].\n\n  exists b.\n  introv mg agree.\n\n  (* 2nd step *)\n  pose proof (comp_force_int_app_F3_c_2 lib F f g nvarx k b) as step2.\n  repeat (autodimp step2 hyp).\n  { apply agree_upto_red_bc_T_implies_agree_upto_c in agree; auto. }\n\n  (* 3rd step *)\n  pose proof (comp_force_int_app_F2_c lib F g nvarx k b) as step3.\n  repeat (autodimp step3 hyp).\n\n  (* by typing *)\n  assert (equality lib g (force_int_f_c nvarx g) (mkc_fun mkc_int T)) as eb.\n  { apply equality_force_int_f_c_T; auto. }\n\n  assert (equality lib (mkc_apply F g) (mkc_apply F (force_int_f_c nvarx g)) mkc_int) as mc.\n  { rw @equality_in_fun in mT; repnd.\n    apply mT; auto. }\n\n  apply equality_in_int in mc.\n  apply equality_of_int_imp_tt in mc.\n  unfold equality_of_int_tt in mc; exrepnd; GC.\n\n  assert (computes_to_valc lib (force_int_F_c nvarx F g) (mkc_integer k)) as c.\n  { rw @computes_to_valc_iff_reduces_toc; dands; eauto with slow. }\n\n  repeat computes_to_eqval.\n\n  exists k0; dands; auto.\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/continuity_axiom2_v2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.26571804995290604}}
{"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 DataRuntime.\nRequire Import NNRS.\n\nSection NNRSSize.\n  Context {fruntime:foreign_runtime}.\n\n  Fixpoint nnrs_expr_size (n:nnrs_expr) : nat\n    := match n with\n       | NNRSGetConstant v => 1\n       | NNRSVar v => 1\n       | NNRSConst d => 1\n       | NNRSBinop op n₁ n₂ => S (nnrs_expr_size n₁ + nnrs_expr_size n₂)\n       | NNRSUnop op n₁ => S (nnrs_expr_size n₁)\n       | NNRSGroupBy g sl e => S (nnrs_expr_size e)\n       end.\n\n    Fixpoint nnrs_stmt_size (n:nnrs_stmt) : nat\n    := match n with\n       | NNRSSeq s₁ s₂ => S (nnrs_stmt_size s₁ + nnrs_stmt_size s₂)\n       | NNRSLet v e s => S (nnrs_expr_size e + nnrs_stmt_size s)\n       | NNRSLetMut v eo s => S (nnrs_stmt_size s + nnrs_stmt_size s)\n       | NNRSLetMutColl _ s₁ s₂ => S (nnrs_stmt_size s₁ + nnrs_stmt_size s₂)\n       | NNRSAssign _ e => S (nnrs_expr_size e)\n       | NNRSPush _ e => S (nnrs_expr_size e)\n       | NNRSFor v n₁ n₂ => S (nnrs_expr_size n₁ + nnrs_stmt_size n₂)\n       | NNRSIf n₁ n₂ n₃ => S (nnrs_expr_size n₁ + nnrs_stmt_size n₂ + nnrs_stmt_size n₃)\n       | NNRSEither nd vl nl vr nr => S (nnrs_expr_size nd + nnrs_stmt_size nl + nnrs_stmt_size nr)\n       end.\n\n    Definition nnrs_size (q:nnrs) : nat :=\n      let (n, v) := q in\n      nnrs_stmt_size n.\n\n    Lemma nnrs_expr_size_nzero (n:nnrs_expr) : nnrs_expr_size n <> 0.\n    Proof.\n      induction n; simpl; lia.\n    Qed.\n\n    Lemma nnrs_stmt_size_nzero (n:nnrs_stmt) : nnrs_stmt_size n <> 0.\n    Proof.\n      induction n; simpl; lia.\n    Qed.\n\n    Corollary nnrs_size_nzero (q:nnrs) : nnrs_size q <> 0.\n    Proof.\n      destruct q.\n      apply nnrs_stmt_size_nzero.\n    Qed.\n\n    Section Core.\n      Program Definition nnrs_core_size (q:nnrs_core) : nat\n        := nnrs_size q.\n\n      Lemma nnrs_core_size_nzero (q:nnrs_core) :\n        nnrs_core_size q <> 0.\n      Proof.\n        apply nnrs_size_nzero.\n      Qed.\n    End Core.\n\nEnd NNRSSize.\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/NNRS/Lang/NNRSSize.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5, "lm_q1q2_score": 0.26560468668687814}}
{"text": "(** Infrastructure lemmas and tactic definitions for Fsub.\n\n    Authors: Brian Aydemir and Arthur Chargu\\'eraud, 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=\"##gather_atoms\">The \"gather_atoms\" 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      - #<a href=\"##body\">Properties of body_e</a># *)\n\nRequire Export Fsub.Fsub_LetSum_Definitions.\n\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_top => {}\n  | typ_bvar J => {}\n  | typ_fvar X => {{ X }}\n  | typ_arrow T1 T2 => (fv_tt T1) `union` (fv_tt T2)\n  | typ_all T1 T2 => (fv_tt T1) `union` (fv_tt T2)\n  | typ_sum T1 T2 => (fv_tt T1) `union` (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 V e1  => (fv_tt V) `union` (fv_te e1)\n  | exp_app e1 e2 => (fv_te e1) `union` (fv_te e2)\n  | exp_tabs V e1 => (fv_tt V) `union` (fv_te e1)\n  | exp_tapp e1 V => (fv_tt V) `union` (fv_te e1)\n  | exp_let e1 e2 => (fv_te e1) `union` (fv_te e2)\n  | exp_inl e1 => (fv_te e1)\n  | exp_inr e1 => (fv_te e1)\n  | exp_case e1 e2 e3 => (fv_te e1) `union` (fv_te e2) `union` (fv_te e3)\n  end.\n\nFixpoint fv_ee (e : exp) {struct e} : atoms :=\n  match e with\n  | exp_bvar i => {}\n  | exp_fvar x => {{ x }}\n  | exp_abs V e1 => (fv_ee e1)\n  | exp_app e1 e2 => (fv_ee e1) `union` (fv_ee e2)\n  | exp_tabs V e1 => (fv_ee e1)\n  | exp_tapp e1 V => (fv_ee e1)\n  | exp_let e1 e2 => (fv_ee e1) `union` (fv_ee e2)\n  | exp_inl e1 => (fv_ee e1)\n  | exp_inr e1 => (fv_ee e1)\n  | exp_case e1 e2 e3 => (fv_ee e1) `union` (fv_ee e2) `union` (fv_ee e3)\n  end.\n\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_top => typ_top\n  | typ_bvar J => typ_bvar J\n  | typ_fvar X => if X == Z then U else T\n  | typ_arrow T1 T2 => typ_arrow (subst_tt Z U T1) (subst_tt Z U T2)\n  | typ_all T1 T2 => typ_all (subst_tt Z U T1) (subst_tt Z U T2)\n  | typ_sum T1 T2 => typ_sum (subst_tt Z U T1) (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 V e1 => exp_abs  (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 V e1 => exp_tabs (subst_tt Z U V)  (subst_te Z U e1)\n  | exp_tapp e1 V => exp_tapp (subst_te Z U e1) (subst_tt Z U V)\n  | exp_let e1 e2 => exp_let (subst_te Z U e1) (subst_te Z U e2)\n  | exp_inl e1 => exp_inl (subst_te Z U e1)\n  | exp_inr e1 => exp_inr (subst_te Z U e1)\n  | exp_case e1 e2 e3 => exp_case (subst_te Z U e1)\n                                  (subst_te Z U e2) (subst_te Z U e3)\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 V e1 => exp_abs 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 V e1 => exp_tabs V (subst_ee z u e1)\n  | exp_tapp e1 V => exp_tapp (subst_ee z u e1) V\n  | exp_let e1 e2 => exp_let (subst_ee z u e1) (subst_ee z u e2)\n  | exp_inl e1 => exp_inl (subst_ee z u e1)\n  | exp_inr e1 => exp_inr (subst_ee z u e1)\n  | exp_case e1 e2 e3 => exp_case (subst_ee z u e1)\n                                  (subst_ee z u e2) (subst_ee z u e3)\n  end.\n\nDefinition subst_tb (Z : atom) (P : typ) (b : binding) : binding :=\n  match b with\n  | bind_sub T => bind_sub (subst_tt Z P T)\n  | bind_typ T => bind_typ (subst_tt Z P T)\n  end.\n\n\n(* ********************************************************************** *)\n(** * #<a name=\"gather_atoms\"></a># The \"[gather_atoms]\" tactic *)\n\n(** The Metatheory and MetatheoryAtom libraries define a number of\n    tactics for working with cofinite quantification and for picking\n    fresh atoms.  To specialize those tactics to this language, we\n    only need to redefine the [gather_atoms] tactic, which returns the\n    set of all atoms in the current context.\n\n    The definition of [gather_atoms] follows a pattern based on\n    repeated calls to [gather_atoms_with].  The one argument to this\n    tactic is a function that takes an object of some particular type\n    and returns a set of atoms that appear in that argument.  It is\n    not necessary to understand exactly how [gather_atoms_with] works.\n    If we add a new inductive datatype, say for kinds, to our\n    language, then we would need to modify [gather_atoms].  On the\n    other hand, if we merely add a new type, say products, then there\n    is no need to modify [gather_atoms]; the required changes would be\n    made in [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  constr:(A `union` B `union` C `union` D `union` E `union` F).\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 congruence || 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    contradict 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 congruence || 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 congruence || 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)... contradict 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 congruence || 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.\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 congruence || 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 congruence || 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    contradict 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 congruence || 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 congruence || 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)... contradict 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],\n    [subst_te_open_ee_var], and [sbust_te_open_te_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    instantiate;\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    instantiate;\n    auto\n  ].\n  Case \"expr_var\".\n    destruct (x == z)...\nQed.\n\n\n(* *********************************************************************** *)\n(** * #<a name=\"body\"></a># Properties of [body_e] *)\n\n(** The two kinds of facts we need about [body_e] are the following:\n      - How to use it to derive that terms are locally closed.\n      - How to derive it from the facts that terms are locally closed.\n\n    Since we use it only in the context of [exp_let] and [exp_sum]\n    (see the definition of reduction), those two constructors are the\n    only ones we consider below. *)\n\nLemma expr_let_from_body : forall e1 e2,\n  expr e1 ->\n  body_e e2 ->\n  expr (exp_let e1 e2).\nProof.\n  intros e1 e2 H [J1 J2].\n  pick fresh y and apply expr_let; auto.\nQed.\n\nLemma body_from_expr_let : forall e1 e2,\n  expr (exp_let e1 e2) ->\n  body_e e2.\nProof.\n  intros e1 e2 H.\n  unfold body_e.\n  inversion H; eauto.\nQed.\n\nLemma expr_case_from_body : forall e1 e2 e3,\n  expr e1 ->\n  body_e e2 ->\n  body_e e3 ->\n  expr (exp_case e1 e2 e3).\nProof.\n  intros e1 e2 e3 H [J1 J2] [K1 K2].\n  pick fresh y and apply expr_case; auto.\nQed.\n\nLemma body_inl_from_expr_case : forall e1 e2 e3,\n  expr (exp_case e1 e2 e3) ->\n  body_e e2.\nProof.\n  intros e1 e2 e3 H.\n  unfold body_e.\n  inversion H; eauto.\nQed.\n\nLemma body_inr_from_expr_case : forall e1 e2 e3,\n  expr (exp_case e1 e2 e3) ->\n  body_e e3.\nProof.\n  intros e1 e2 e3 H.\n  unfold body_e.\n  inversion H; eauto.\nQed.\n\nLemma open_ee_body_e : forall e1 e2,\n  body_e e1 -> expr e2 -> expr (open_ee e1 e2).\nProof.\n  intros e1 e2 [L H] J.\n  pick fresh x.\n  rewrite (subst_ee_intro x); auto using subst_ee_expr.\nQed.\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\n#[export] Hint Resolve subst_tt_type subst_te_expr subst_ee_expr : core.\n\n(** We also add as hints the lemmas concerning [body_e]. *)\n\n#[export] Hint Resolve expr_let_from_body body_from_expr_let : core.\n#[export] Hint Resolve expr_case_from_body : core.\n#[export] Hint Resolve body_inl_from_expr_case body_inr_from_expr_case : core.\n#[export] Hint Resolve open_ee_body_e : core.\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 MetatheoryEnv library. *)\n\n#[export] Hint Extern 1 (binds _ (?F (subst_tt ?X ?U ?T)) _) =>\n  unsimpl (subst_tb X U (F T)) : core.\n", "meta": {"author": "plclub", "repo": "metalib", "sha": "4ea92d82286cf66e54b4119b2bb2b039827204ab", "save_path": "github-repos/coq/plclub-metalib", "path": "github-repos/coq/plclub-metalib/metalib-4ea92d82286cf66e54b4119b2bb2b039827204ab/Fsub/Fsub_LetSum_Infrastructure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2654590286012472}}
{"text": "Require Import VST.floyd.proofauto.\nImport ListNotations.\nLocal Open Scope logic.\n\nRequire Import hmacdrbg.HMAC_DRBG_algorithms.\nRequire Import hmacdrbg.spec_hmac_drbg.\nRequire Import sha.HMAC256_functional_prog.\n\nFixpoint HMAC_DRBG_update_round (HMAC: list Z -> list Z -> list Z) (provided_data K V: list Z) (round: nat): (list Z * list Z) :=\n  match round with\n    | O => (K, V)\n    | S round' =>\n      let (K, V) := HMAC_DRBG_update_round HMAC provided_data K V round' in\n      let K := HMAC (V ++ [Z.of_nat round'] ++ provided_data) K in\n      let V := HMAC V K in\n      (K, V)\n  end.\n\nDefinition HMAC_DRBG_update_concrete (HMAC: list Z -> list Z -> list Z) (provided_data K V: list Z): (list Z * list Z) :=\n  let rounds := match provided_data with\n                  | [] => 1%nat\n                  | _ => 2%nat\n                end in\n  HMAC_DRBG_update_round HMAC provided_data K V rounds.\n\nTheorem HMAC_DRBG_update_concrete_correct:\n  forall HMAC provided_data K V, HMAC_DRBG_update HMAC provided_data K V = HMAC_DRBG_update_concrete HMAC provided_data K V.\nProof.\n  intros.\n  destruct provided_data; reflexivity.\nQed.\n\nDefinition update_rounds (non_empty_additional: bool): Z :=\n  if non_empty_additional then 2 else 1.\n\nLemma HMAC_DRBG_update_round_incremental:\n  forall key V initial_state_abs contents n,\n    (key, V) = HMAC_DRBG_update_round HMAC256 contents\n                           (hmac256drbgabs_key initial_state_abs)\n                           (hmac256drbgabs_value initial_state_abs) n ->\n    (HMAC256 (V ++ (Z.of_nat n) :: contents) key,\n     HMAC256 V (HMAC256 (V ++ (Z.of_nat n) :: contents) key)) =\n    HMAC_DRBG_update_round HMAC256 contents\n                           (hmac256drbgabs_key initial_state_abs)\n                           (hmac256drbgabs_value initial_state_abs) (n + 1).\nProof.\n  intros.\n  rewrite plus_comm.\n  simpl.\n  rewrite <- H.\n  reflexivity.\nQed.\n\nLemma HMAC_DRBG_update_round_incremental_Z:\n  forall key V initial_state_abs contents i,\n    0 <= i ->\n    (key, V) = HMAC_DRBG_update_round HMAC256 contents\n                           (hmac256drbgabs_key initial_state_abs)\n                           (hmac256drbgabs_value initial_state_abs) (Z.to_nat i) ->\n    (HMAC256 (V ++ i :: contents) key,\n     HMAC256 V (HMAC256 (V ++ i :: contents) key)) =\n    HMAC_DRBG_update_round HMAC256 contents\n                           (hmac256drbgabs_key initial_state_abs)\n                           (hmac256drbgabs_value initial_state_abs) (Z.to_nat (i + 1)).\nProof.\n  intros.\n  specialize (HMAC_DRBG_update_round_incremental _ _ _ _ _ H0); intros. clear H0.\n  rewrite (Z2Nat.id _ H) in H1.\n  rewrite Z2Nat.inj_add; try assumption; omega.\nQed.\n\nLemma update_char add_len contents (HL:add_len = Zlength contents \\/ add_len = 0)\n       (key1 V0 : list Z) additional reseed_counter entropy_len prediction_resistance V key0\n     reseed_interval\n    (H : (key1, V0) =\n    HMAC_DRBG_update_round HMAC256 (contents_with_add additional add_len contents) key0 V\n      (Z.to_nat\n         (if\n           (negb (Memory.EqDec_val additional nullval) &&\n            negb (initial_world.EqDec_Z add_len 0))%bool\n          then 2\n          else 1))):\nhmac256drbgabs_hmac_drbg_update\n  (HMAC256DRBGabs key0 V reseed_counter entropy_len prediction_resistance\n     reseed_interval) (contents_with_add additional add_len contents) =\nHMAC256DRBGabs key1 V0 reseed_counter entropy_len prediction_resistance\n  reseed_interval.\nProof. rename key0 into K. rename V0 into VV. rename key1 into KK.\nunfold hmac256drbgabs_hmac_drbg_update, HMAC256_DRBG_functional_prog.HMAC256_DRBG_update.\nrewrite HMAC_DRBG_update_concrete_correct. unfold HMAC_DRBG_update_concrete, contents_with_add in *; simpl in *.\ndestruct (Memory.EqDec_val additional nullval); simpl in *.\n+ inv H; trivial.\n+ destruct (initial_world.EqDec_Z add_len 0).\n  -  subst add_len. change (negb (left eq_refl)) with false in *. simpl. simpl in H. inv H; trivial.\n  - change (negb (right n0)) with true in *. simpl.\n    destruct HL; try omega; subst add_len.\n    destruct contents. rewrite Zlength_nil in n0; omega. \n    change  (Z.to_nat 2) with 2%nat in H. rewrite <- H; trivial.\nQed. ", "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/verif_hmac_drbg_update_common.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.3557749003442964, "lm_q1q2_score": 0.2654575258885091}}
{"text": "From stdpp Require Import gmap stringmap.\nFrom melocoton.ml_lang Require Export lang.\nFrom iris.prelude Require Import options.\nImport ML_lang.\n\n(* This file contains some metatheory about the heap_lang language,\n  which is not needed for verifying programs. *)\n\n(* Adding a binder to a set of identifiers. *)\nLocal Definition set_binder_insert (x : binder) (X : stringset) : stringset :=\n  match x with\n  | BAnon => X\n  | BNamed f => {[f]} ∪ X\n  end.\n\nLemma dom_binder_insert {T} (m : gmap string T) b v : dom (binder_insert b v m) = set_binder_insert b (dom m).\nProof.\n  destruct b; try done.\n  unfold binder_insert, set_binder_insert. rewrite dom_insert_L. done.\nQed.\n\n(* Check if expression [e] is closed w.r.t. the set [X] of variable names,\n   and that all the values in [e] are closed *)\nFixpoint is_closed_expr (X : stringset) (e : expr) : bool :=\n  match e with\n  | Val v => is_closed_val v\n  | Var x => bool_decide (x ∈ X)\n  | Rec f x e => is_closed_expr (set_binder_insert f (set_binder_insert x X)) e\n  | UnOp _ e | Fst e | Snd e | InjL e | InjR e | Length e =>\n     is_closed_expr X e\n  | App e1 e2 | BinOp _ e1 e2 | Pair e1 e2 | AllocN e1 e2 | LoadN e1 e2 =>\n     is_closed_expr X e1 && is_closed_expr X e2\n  | If e0 e1 e2 | Case e0 e1 e2 | StoreN e0 e1 e2 =>\n     is_closed_expr X e0 && is_closed_expr X e1 && is_closed_expr X e2\n  | Extern _ ea => forallb (is_closed_expr X) ea\n  end\nwith is_closed_val (v : val) : bool :=\n  match v with\n  | LitV _ => true\n  | RecV f x e => is_closed_expr (set_binder_insert f (set_binder_insert x ∅)) e\n  | PairV v1 v2 => is_closed_val v1 && is_closed_val v2\n  | InjLV v | InjRV v => is_closed_val v\n  end.\n\nDefinition is_closed_context (g:gmap string val) := map_Forall (fun a b => is_closed_val b) g.\n\n(* Properties *)\nLocal Instance set_unfold_elem_of_insert_binder x y X Q :\n  SetUnfoldElemOf y X Q →\n  SetUnfoldElemOf y (set_binder_insert x X) (Q ∨ BNamed y = x).\nProof. destruct 1; constructor; destruct x; set_solver. Qed.\n\nLemma is_closed_weaken X Y e : is_closed_expr X e → X ⊆ Y → is_closed_expr Y e.\nProof. revert X Y; induction e; try naive_solver (eauto; set_solver).\n       + cbn. intros X Y H2%forallb_True HXY.\n         apply forallb_True, Forall_forall. intros x Hx.\n         rewrite List.Forall_forall in H. apply H with X. \n         3: assumption. 1: now apply elem_of_list_In. rewrite Forall_forall in H2. now apply H2.\nQed.\n\nLemma is_closed_subst_all X e g :\n  is_closed_context g →\n  is_closed_expr (dom g ∪ X) e →\n  is_closed_expr X (subst_all g e).\nProof with eauto using is_closed_weaken with set_solver.\n  revert X g.\n  induction e=> X g  HH /= HHyp; destruct_and?; split_and?; simplify_option_eq.\n  all: idtac...\n  all: repeat match goal with H : ?x ∈ ?l1 ∪ ?l2 |- _ => apply elem_of_union in H; destruct H end.\n  - apply elem_of_dom in H as H2. destruct H2 as [k Hrew]; rewrite Hrew. unfold is_closed_context in HH.\n    rewrite map_Forall_lookup in HH. eapply HH. by rewrite <- Hrew.\n  - destruct (g !! x) eqn:Heq; try naive_solver.\n  - cbn. destruct x,f1; cbn; split_and?...\n    + apply IHe. 1: unfold is_closed_context in *; now apply map_Forall_delete.\n      cbn in HHyp. eapply is_closed_weaken. 1: apply HHyp.\n      rewrite dom_delete. intros x [->%elem_of_singleton|H2]%elem_of_union.\n      * set_solver.\n      * destruct (decide (s = x)) as [->|Hr].\n        -- set_solver.\n        -- set_solver.\n    + apply IHe. 1: unfold is_closed_context in *; now apply map_Forall_delete.\n      cbn in HHyp. eapply is_closed_weaken. 1: apply HHyp.\n      rewrite dom_delete. intros x [->%elem_of_singleton|H2]%elem_of_union.\n      * set_solver.\n      * destruct (decide (s = x)) as [->|Hr].\n        -- set_solver.\n        -- set_solver.\n    + apply IHe. 1: unfold is_closed_context in *; now apply map_Forall_delete, map_Forall_delete.\n      cbn in HHyp. eapply is_closed_weaken. 1: apply HHyp.\n      rewrite dom_delete. intros x [->%elem_of_singleton|H2]%elem_of_union.\n      * set_solver.\n      * destruct (decide (s = x)) as [->|Hr].\n        -- set_solver.\n        -- destruct (decide (s0 = x)) as [->|Hr2].\n        --- set_solver.\n        --- set_solver.\n  - rewrite forallb_True.\n    rewrite Forall_forall. rewrite Forall_forall in H.\n    rewrite forallb_True in HHyp. rewrite Forall_forall in HHyp.\n    intros x [xx [<- Hin]]%elem_of_list_In%in_map_iff.\n    apply H. 1: now apply elem_of_list_In. 1:easy. eapply HHyp. now apply elem_of_list_In.\nQed.\n\nLemma is_closed_subst X e y v :\n  is_closed_val v →\n  is_closed_expr ({[y]} ∪ X) e →\n  is_closed_expr X (subst y v e).\nProof.\n  intros Hv H. apply is_closed_subst_all. 2: erewrite dom_singleton_L ; exact H.\n  unfold is_closed_context. now apply map_Forall_singleton.\nQed.\n\nLemma is_closed_subst' X e x v :\n  is_closed_val v →\n  is_closed_expr (set_binder_insert x X) e →\n  is_closed_expr X (subst' x v e).\nProof. destruct x; eauto using is_closed_subst. Qed.\n\n\nLemma subst_all_is_closed X g e :\n  is_closed_expr X e → dom g ∩ X = ∅ → subst_all g e = e.\nProof.\n  revert X g. induction e; intros X g;\n   rewrite ?bool_decide_spec; rewrite ?andb_True; cbn; intros;\n   repeat case_decide; simplify_eq/=; f_equal; intuition eauto with set_solver.\n  - destruct (g !! x) eqn:Heq. 2:easy.\n    apply elem_of_dom_2 in Heq. set_solver.\n  - fold is_closed_expr in *. destruct x,f1; f_equal; intuition eauto with set_solver.\n    all: cbn; cbn in H; eapply IHe.\n    1,3,5: exact H.\n    all: set_solver.\n  - fold is_closed_expr in *. erewrite map_ext_in. 1: apply map_id.\n    intros ea' Hin. cbn. rewrite Forall_forall in H. apply H with X.\n    * now apply elem_of_list_In.\n    * rewrite forallb_True in H0. rewrite List.Forall_forall in H0. now apply H0.\n    * set_solver.\nQed.\n\nLemma subst_is_closed X e x es : is_closed_expr X e → x ∉ X → subst x es e = e.\nProof.\n  intros H1 H2. eapply subst_all_is_closed. 1: exact H1. set_solver.\nQed.\n\nLemma subst_is_closed_empty e x v : is_closed_expr ∅ e → subst x v e = e.\nProof. intros. apply subst_is_closed with (∅:stringset); set_solver. Qed.\n\n\nLemma subst_all_comp e g1 g2 :\n  subst_all g1 (subst_all g2 e) = subst_all (g2 ∪ g1) e.\nProof.\n  intros. induction e in g1,g2|-*; simpl; try (f_equal; by auto);\n    simplify_option_eq; auto using subst_is_closed_empty with f_equal.\n  - destruct (g2 !! x) eqn:Heq2; [|cbn;destruct (g1 !! x) eqn:Heq1].\n    + cbn. erewrite lookup_union_Some_l. 2: exact Heq2. easy.\n    + erewrite lookup_union_r. 2: easy. rewrite Heq1. easy.\n    + erewrite lookup_union_r. 2: easy. rewrite Heq1. easy.\n  - destruct x, f1.\n    + cbn. auto using subst_is_closed_empty with f_equal.\n    + cbn. rewrite delete_union. auto using subst_is_closed_empty with f_equal.\n    + cbn. rewrite delete_union. auto using subst_is_closed_empty with f_equal.\n    + cbn. do 2 rewrite delete_union. auto using subst_is_closed_empty with f_equal.\n  - f_equal. erewrite map_map. apply map_ext_in.\n    intros a Ha. rewrite Forall_forall in H. apply H. now apply elem_of_list_In.\nQed.\n\nLemma subst_subst e x v v' :\n  subst x v (subst x v' e) = subst x v' e.\nProof.\n  unfold subst. rewrite subst_all_comp. f_equal.\n  apply map_eq_iff. intros i. destruct ({[x := v']} !! i) eqn:Heq.\n  - erewrite lookup_union_Some_l. 2: exact Heq. easy.\n  - rewrite lookup_union_r. 2:easy. apply lookup_singleton_None in Heq.\n    apply lookup_singleton_None. easy.\nQed.\n\nLemma subst_subst' e x v v' :\n  subst' x v (subst' x v' e) = subst' x v' e.\nProof. destruct x; simpl; auto using subst_subst. Qed.\n\nLemma subst_subst_ne e x y v v' :\n  x ≠ y → subst x v (subst y v' e) = subst y v' (subst x v e).\nProof.\n  intros H. unfold subst. rewrite !subst_all_comp.\n  f_equal. apply map_eq_iff. intros i. rewrite !lookup_union.\n  destruct ({[y := v']} !! i) eqn:Heq1; destruct ({[x := v]} !! i) eqn:Heq2; cbn.\n  2-4: easy.\n  exfalso. apply lookup_singleton_Some in Heq1. apply lookup_singleton_Some in Heq2.\n  destruct Heq1, Heq2. congruence.\nQed.\n\nLemma subst_subst_ne' e x y v v' :\n  x ≠ y → subst' x v (subst' y v' e) = subst' y v' (subst' x v e).\nProof. destruct x, y; simpl; auto using subst_subst_ne with congruence. Qed.\n\n\nLemma subst_all_empty e : subst_all ∅ e = e.\nProof.\n  induction e; simplify_map_eq; auto with f_equal.\n  + destruct x,f1; cbn. 2,3,4: repeat rewrite delete_empty. all: simplify_map_eq; rewrite ?Hdel; auto with f_equal.\n  + rewrite Forall_forall in H. f_equal. erewrite map_ext_in. 1: apply map_id. intros a Ha. cbn. now apply H, elem_of_list_In.\nQed.\n\nLemma subst_rec' f y e x v :\n  x = f ∨ x = y ∨ x = BAnon →\n  subst' x v (Rec f y e) = Rec f y e.\nProof. intros. destruct x; simplify_option_eq; try naive_solver. cbn. f_equal.\n  destruct H as [<-|[<-|H3]]. \n  - cbn. destruct y; cbn. all: rewrite <- subst_all_empty; f_equal.\n    1: now rewrite delete_singleton. now  rewrite delete_commute delete_singleton delete_empty.\n  - cbn. rewrite delete_singleton. destruct f; cbn; try rewrite delete_empty.\n    all: apply subst_all_empty.\n  - congruence. \nQed.\n(*\nLemma subst_rec_ne' f y e x v :\n  (x ≠ f ∨ f = BAnon) → (x ≠ y ∨ y = BAnon) →\n  subst' x v (Rec f y e) = Rec f y (subst' x v e).\nProof. intros. destruct x; simplify_option_eq; naive_solver. Qed. *)\n\nLemma bin_op_eval_closed op v1 v2 v' :\n  is_closed_val v1 → is_closed_val v2 → bin_op_eval op v1 v2 = Some v' →\n  is_closed_val v'.\nProof.\n  rewrite /bin_op_eval /bin_op_eval_bool /bin_op_eval_int;\n    repeat case_match; by naive_solver.\nQed.\n\nDefinition is_closed_ml_function X f := match f with\n  MlFun lst expr => is_closed_expr (X ∪ list_to_set \n        (flat_map (fun k => match k with BAnon => [] | BNamed l => [l] end) lst)) expr end.\n\nLemma zip_args_closed a b c : zip_args a b = Some c -> Forall is_closed_val b -> is_closed_context c.\nProof.\n  induction b in a,c|-*; intros H1 H2.\n  - destruct a as [|[|x] ar]; cbn in *; try congruence.\n    assert (c = ∅) as -> by congruence. apply map_Forall_empty.\n  - destruct a as [|[|x] ar]; cbn in *; try congruence.\n    + eapply IHb. 1: apply H1. eapply Forall_inv_tail, H2.\n    + destruct (zip_args ar b) eqn:Heq; cbn in H1; try congruence.\n      injection H1. intros <-. apply map_Forall_insert_2. \n      1: now apply Forall_inv in H2.\n      1: eapply IHb. 1: apply Heq. eapply Forall_inv_tail, H2.\nQed.\n\n(* The stepping relation preserves closedness *)\nLemma head_step_is_closed p e1 σ1 e2 σ2 :\n  (forall f e, (p:gmap string ml_function) !! f = Some e → is_closed_ml_function ∅ e) →\n  is_closed_expr ∅ e1 →\n  map_Forall (λ _ v, is_closed_val v) σ1 →\n  head_step p e1 σ1 e2 σ2 →\n  is_closed_expr ∅ e2 ∧\n  map_Forall (λ _ v, is_closed_val v) σ2.\nProof.\n  intros Clp Cl1 Clσ1 STEP.\n  induction STEP; simpl in *; split_and!;\n    try apply map_Forall_insert_2; try by naive_solver.\n  - subst. repeat apply is_closed_subst'; naive_solver.\n  - unfold un_op_eval in *. repeat case_match; naive_solver.\n  - eapply bin_op_eval_closed; eauto; naive_solver.\n  - intros [l' i] v' HH.\n    destruct (decide (l = l')) as [->|?].\n    { rewrite store_lookup_eq in HH.\n      case_bool_decide; simplify_map_eq/=.\n      by apply lookup_replicate in HH as (-> & ?). }\n    rewrite store_lookup_eq in HH.\n    case_bool_decide; simplify_map_eq/=.\n    destruct (σ !! l') eqn:Heqo; simplify_map_eq/=.\n    apply (Clσ1 (Locoff l' i)).\n    rewrite store_lookup_eq; by case_bool_decide; simplify_map_eq/=.\n  - intros ℓi v'.\n    destruct (decide (ℓi = (l.[i])%L)) as [->|?].\n    { rewrite (store_lookup_insert _ l.[i] v) //. congruence. }\n    rewrite store_lookup_insert_ne //. intro. by eapply Clσ1.\n  - edestruct (zip_args args va) as [σ'|] eqn:Heq. 2: congruence.\n    injection H0. intros <-. clear H0.\n    eapply is_closed_subst_all.\n    1: {rewrite forallb_True in Cl1. rewrite Forall_map in Cl1. cbn in Cl1.\n        eapply zip_args_closed. 1: apply Heq. apply Cl1. }\n    specialize (Clp _ _ H).\n    cbn in Clp.\n    assert (forall a b, a = b -> is_closed_expr a e -> is_closed_expr b e) as Happ by (now intros ? ? ->).\n    eapply Happ, Clp.\n    clear Happ H.\n    induction args as [|[|a] ar IH] in Heq,va,σ'|-*; cbn; destruct va; cbn in *; try congruence.\n    + injection Heq. intros <-. set_solver. \n    + eapply IH. apply Heq.\n    + unfold option_map in Heq. specialize (IH va). destruct (zip_args ar va) as [σ''|] eqn:Heq2; last congruence.\n      specialize (IH σ'' eq_refl). \n      injection Heq. intros <-. set_solver.\nQed.\n\n\nLemma subst_all_insert x v vs e :\n  subst_all (<[x:=v]>vs) e = subst x v (subst_all (delete x vs) e).\nProof.\n  unfold subst. rewrite subst_all_comp. f_equal. apply map_eq_iff.\n  intros i. destruct (decide (x = i)) as [->|?].\n  + rewrite lookup_insert. rewrite lookup_union_r.\n    * now rewrite lookup_singleton.\n    * now rewrite lookup_delete.\n  + rewrite lookup_insert_ne. 2:easy.\n    rewrite lookup_union.\n    rewrite lookup_singleton_ne. 2: easy.\n    rewrite union_with_right_id.\n    now rewrite lookup_delete_ne.\nQed.\n\nLemma subst_all_binder_insert b v vs e :\n  subst_all (binder_insert b v vs) e =\n  subst' b v (subst_all (binder_delete b vs) e).\nProof. destruct b; cbn. 1: easy. now rewrite subst_all_insert. Qed.\nLemma subst_all_binder_insert_empty b v e :\n  subst_all (binder_insert b v ∅) e = subst' b v e.\nProof. by rewrite subst_all_binder_insert binder_delete_empty subst_all_empty. Qed.\n\nLemma subst_all_binder_insert_2 b1 v1 b2 v2 vs e :\n  subst_all (binder_insert b1 v1 (binder_insert b2 v2 vs)) e =\n  subst' b2 v2 (subst' b1 v1 (subst_all (binder_delete b2 (binder_delete b1 vs)) e)).\nProof.\n  destruct b1 as [|s1], b2 as [|s2]=> /=; auto using subst_all_insert.\n  rewrite subst_all_insert. destruct (decide (s1 = s2)) as [->|].\n  - by rewrite delete_idemp subst_subst delete_insert_delete.\n  - by rewrite delete_insert_ne // subst_all_insert subst_subst_ne.\nQed.\nLemma subst_all_binder_insert_2_empty b1 v1 b2 v2 e :\n  subst_all (binder_insert b1 v1 (binder_insert b2 v2 ∅)) e =\n  subst' b2 v2 (subst' b1 v1 e).\nProof.\n  by rewrite subst_all_binder_insert_2 !binder_delete_empty subst_all_empty.\nQed.\n\nLemma subst_all_is_closed_empty e vs : is_closed_expr ∅ e → subst_all vs e = e.\nProof. intros. apply subst_all_is_closed with (∅ : stringset); set_solver. Qed.\n", "meta": {"author": "logsem", "repo": "melocoton", "sha": "b77eecc3381f53db0eb3c4cf1314e881a8dc41b3", "save_path": "github-repos/coq/logsem-melocoton", "path": "github-repos/coq/logsem-melocoton/melocoton-b77eecc3381f53db0eb3c4cf1314e881a8dc41b3/theories/ml_lang/metatheory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2653678593456402}}
{"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 Recdef.\nRequire Export Eqdep_dec.\nRequire Export opid.\nRequire Export variables.\n(** printing #  $\\times$ #×# *)\n(** printing <=>  $\\Leftrightarrow$ #&hArr;# *)\n(** printing $  $\\times$ #×# *)\n(** printing &  $\\times$ #×# *)\n\n\n\n(**\n  We can now define the terms of the Nuprl language as an inductive type.\n  There are several considerations in choosing the right definition.\n  The definition needs to be general enough so that adding\n  new constructs to the term language does\n  not break proofs about general properties of general operations on terms.\n  For example, the substitution operation and the alpha equality\n  relation only care about the getting access to the variables and\n  do not care about the other operators(constucts) of the language.\n\n  Our term definition(similar to %\\cite{Howe:1989}%)\n  exposes the variables, especially the concept\n  of bound variables in a uniform way so that these\n  and many other operations and proofs work unchanged\n  when adding/removing constructs from the language.\n  These robust proofs run into several thousands of lines and include the\n  many properties about substitution and alpha equality that\n  we need for formalizing all of Nurpl.\n\n  Many alternative approaches for variable bindings\n  have been discussed in the\n  literature %~\\cite{Pfenning:1988,Capretta:2007,Chlipala:cpdt}%.\n  Our choice avoided the overhead of translating\n  the paper definitions about Nuprl to some other style of variable\n  bindings.\n\n  We will first intuitively explain parts of the definition before showing it.\n  Firstly, we have a constructor ([vterm]) that builds a term([NTerm]) from a variable([NVar])).\n  Variable bindings are made explicit by the concept of a bound term ([BTerm]).\n  [bterm] is the only constructor of [BTerm]. It takes a list of variables (say [lv])\n  and a term (say [nt]) and constructs a bound term. Intuitively, a variable that is\n  free in [nt] gets bound to its first occurence in [lv], if any.\n  For example, the bound term [bterm [nvarx] (vterm nvarx)] will\n  be used soon in constructing an identity function($\\lambda x.x$).\n\n  The rest of our term definition is\n  parametrized by a collection of\n  operators([Opid]). Operators take bound terms as input and construct another\n  term.  For example, there is an operator that takes [[bterm [nvarx] (vterm nvarx)]]\n  and constructs the lambda term $\\lambda x.x$.\n  With that in mind, here is the inductive type([NTerm]) that represents the terms of Nurpl:\n\n\n *)\nInductive NTerm {p} : tuniv :=\n| vterm: NVar -> NTerm\n| sterm : (nat -> NTerm) -> NTerm (* closed free choice sequence *)\n| oterm: @Opid p -> list BTerm -> NTerm\nwith BTerm {p} : tuniv :=\n| bterm: (list NVar) -> NTerm -> BTerm.\n\n(*\n  The [Opid] type contains one element corresponding to every operator\n  of the language, e.g. lambda abstraction, funtion application,\n  dependent function type constructor. As a more concrete example,\n  the [Can NLambda] is the element of [Opid] that represents lambda\n  abstractions.\n  To construct a bound term([BTerm]), we need a list of variables and\n  an [NTerm] (see the [bterm] constructor). As a concrete example,\n   $ \\lambda x.x$ is represented in this type\n  as [(oterm  (Can NLambda) (bterm [nvarx] (vterm nvarx)))].\n*)\n\n(**\n  It is a mutually inductive definition that simultaneously defines terms\n  and bound terms. As mentioned before, the [vterm] constructor\n  takes an [NVar] and constructs an [NTerm]. The other constructor([oterm])\n  takes an [Opid] and a list of bound terms ([BTerm]s) and constructs an [NTerm].\n  Note that not all members of [NTerm] are meaningful(well-formed).\n  For example, the [Opid] corresponding to lambda abstractions must be\n  provided with exactly one bound term as argument. Moreover, that\n  bound term must have exactly one bound variable. So, we have a function\n  [OpBindings] in type [Opid -> list nat] that specifies both the\n  number of arguments and the number of bound variables in each argument([BTerm]).\n  We will use it soon to define the subcollection of well-formed terms.\n*)\n\n(* begin hide *)\nInductive ord :=\n| OZ : ord\n| OS : ord -> ord\n| OL : (nat -> ord) -> ord.\n\nNotation O1 := (OS OZ).\n\nFixpoint oadd (o1 o2 : ord) :=\n  match o1 with\n    | OZ => o2\n    | OS o => OS (oadd o o2)\n    | OL f => OL (fun x => oadd (f x) o2)\n  end.\n\nFixpoint oaddl (ts : list ord) : ord :=\n  match ts with\n  | nil => OZ\n  | n :: ns => oadd n (oaddl ns)\n  end.\n\nFixpoint osize {o} (t : @NTerm o) : ord :=\n  match t with\n    | vterm _ => O1\n    | sterm f => OS (OL (fun x => osize (f x)))\n    | oterm op bterms => OS (oaddl (map osize_bterm bterms))\n  end\nwith osize_bterm {o} (bt : BTerm) : ord :=\n  match bt with\n    | bterm lv nt => osize nt\n  end.\n\nFixpoint opred_type (o : ord) : Set :=\n  match o with\n    | OZ    => False\n    | OS o' => option (opred_type o')\n    | OL f  => { n : nat & opred_type (f n) }\n  end.\n\nFixpoint opred (o : ord) : opred_type o -> ord :=\n  match o return opred_type o -> ord with\n    | OZ    => fun i => match i with end\n    | OS o' => fun i => match i with\n                          | None => o'\n                          | Some t  => opred o' t\n                        end\n    | OL f  => fun i => match i with\n                          | existT _ n t => opred (f n) t\n                        end\n  end.\n\nInductive ord_le : ord -> ord -> Type :=\n| le_OZ : forall o, ord_le OZ o\n| le_OS : forall o1 o2 i, ord_le o1 (opred o2 i) -> ord_le (OS o1) o2\n| le_OL : forall f o, (forall n, ord_le (f n) o) -> ord_le (OL f) o.\nHint Constructors ord_le.\n\nDefinition ord_lt (o1 o2 : ord) := {i : opred_type o2 & ord_le o1 (opred o2 i)}.\n\nDefinition ord_eq o1 o2 := ord_le o1 o2 # ord_le o2 o1.\n\nNotation \"o1 << o2\" := (ord_lt o1 o2) (at level 0).\nNotation \"o1 <=< o2\" := (ord_le o1 o2) (at level 0).\nNotation \"o1 =o= o2\" := (ord_eq o1 o2) (at level 0).\n\nLemma not_ord_lt_zero : forall o, !(o << OZ).\nProof.\n  induction o; intro olt; unfold ord_lt in olt; exrepnd; allsimpl; tcsp.\nQed.\n\nLemma ord_le_opred_implies_ord_lt :\n  forall o1 o2 t, o1 <=< (opred o2 t) -> o1 << o2.\nProof.\n  introv ole.\n  exists t; auto.\nQed.\n\nLemma ord_le_ex_opred_type :\n  forall o1 o2,\n    opred_type o1\n    -> o1 <=< o2\n    -> opred_type o2.\nProof.\n  induction o1 as [|?|? ind]; introv opt ole; allsimpl; tcsp.\n  - destruct opt as [t|].\n    + inversion ole as [|? ? t' ole'|]; subst; clear ole; auto.\n    + inversion ole as [|? ? t' ole'|]; subst; clear ole; auto.\n  - exrepnd.\n    inversion ole as [|?|? ? i]; subst; clear ole.\n    pose proof (i n) as ole; clear i.\n    apply ind in ole; auto.\nQed.\n\nLemma ord_le_opred_right_implies_le :\n  forall o1 o2 (t : opred_type o2),\n    o1 <=< (opred o2 t)\n    -> o1 <=< o2.\nProof.\n  induction o1 as [|? ind|? ind]; introv ole; allsimpl; tcsp.\n  - apply (le_OS _ _ t).\n    inversion ole as [|? ? t' ole'|]; subst; clear ole.\n    apply ind in ole'; auto.\n  - inversion ole as [|?|? ? i]; subst; clear ole.\n    constructor; introv.\n    pose proof (i n) as h; clear i.\n    apply ind in h; auto.\nQed.\n\nLemma ord_le_opred_right_implies_lt :\n  forall o1 o2 (t : opred_type o2),\n    o1 <=< (opred o2 t)\n    -> o1 << o2.\nProof.\n  introv ole; exists t; auto.\nQed.\n\nLemma implies_ord_le_opred_left :\n  forall o1 o2 (t1 : opred_type o1),\n    o1 <=< o2\n    -> (opred o1 t1) <=< o2.\nProof.\n  induction o1 as [|? ind|? ind]; introv ole; allsimpl; tcsp.\n  - inversion ole as [|? ? t ole'|]; subst; clear ole.\n    apply ord_le_opred_right_implies_le in ole'; auto.\n    destruct t1; tcsp.\n  - inversion ole as [|?|? ? i]; subst; clear ole; exrepnd.\n    apply ind; auto.\nQed.\n\nLemma ord_le_trans :\n  forall o1 o2 o3, o1 <=< o2 -> o2 <=< o3 -> o1 <=< o3.\nProof.\n  introv ole.\n  revert o3.\n\n  induction ole as [|? ? ? ? ind|]; introv ole2; auto; clear ole.\n\n  induction ole2 as [|? ? ? ? ind2|? ? ? ind2]; introv; allsimpl; tcsp.\n\n  - apply (le_OS _ _ i0).\n    apply ind.\n    destruct i; allsimpl; tcsp.\n    apply implies_ord_le_opred_left; auto.\n\n  - exrepnd.\n    apply (ind2 n i0); auto.\nQed.\nHint Resolve ord_le_trans : slow.\n\nLemma ord_lt_trans :\n  forall o1 o2 o3, o1 << o2 -> o2 << o3 -> o1 << o3.\nProof.\n  introv olt1 olt2.\n  allunfold ord_lt; exrepnd.\n  exists i.\n  eapply ord_le_trans;[exact olt2|].\n  apply implies_ord_le_opred_left; auto.\nQed.\nHint Resolve ord_lt_trans : slow.\n\nLemma implies_ord_le_opred :\n  forall o1 o2 (t1 : opred_type o1),\n    o1 <=< o2\n    -> {t2 : opred_type o2 & (opred o1 t1) <=< (opred o2 t2)}.\nProof.\n  induction o1 as [|? ind|? ind]; introv ole; allsimpl; tcsp.\n\n  - inversion ole as [|? ? t ole'|]; subst; clear ole.\n    destruct t1; allsimpl.\n\n    + apply ind.\n      eapply ord_le_opred_right_implies_le; eauto.\n\n    + exists t; auto.\n\n  - inversion ole as [|?|? ? i]; subst; clear ole; exrepnd.\n    pose proof (i n) as h; clear i.\n    applydup ind in h as t; auto.\nQed.\n\nLemma ord_lt_le_trans :\n  forall o1 o2 o3, o1 << o2 -> o2 <=< o3 -> o1 << o3.\nProof.\n  introv olt1 olt2.\n  allunfold ord_lt; exrepnd.\n  pose proof (implies_ord_le_opred o2 o3 i olt2) as h; exrepnd.\n  exists t2.\n  eapply ord_le_trans;[|exact h0]; auto.\nQed.\n\nLemma implies_ord_le_limit_right :\n  forall o f n, o <=< (f n) -> o <=< (OL f).\nProof.\n  induction o as [|?|? ind]; introv ole; auto.\n  - inversion ole as [|? ? t ole'|]; subst; clear ole.\n    apply (le_OS o (OL f) (existT (fun n => opred_type (f n)) n t)); simpl; auto.\n  - inversion ole as [|?|? ? i]; subst; clear ole; exrepnd.\n    constructor; introv.\n    eapply ind; apply i.\nQed.\n\nLemma ord_le_refl : forall o, o <=< o.\nProof.\n  induction o; auto.\n  - apply (le_OS o (OS o) None); simpl; auto.\n  - constructor; introv.\n    eapply implies_ord_le_limit_right; eauto.\nQed.\nHint Resolve ord_le_refl : slow.\n\nLemma ord_eq_refl : forall o, o =o= o.\nProof.\n  introv.\n  split; apply ord_le_refl.\nQed.\n\nLemma ord_eq_sym :\n  forall o1 o2, o1 =o= o2 -> o2 =o= o1.\nProof.\n  introv oeq.\n  allunfold ord_eq; sp.\nQed.\n\nLemma ord_le_eq_trans :\n  forall o1 o2 o3, o1 <=< o2 -> o2 =o= o3 -> o1 <=< o3.\nProof.\n  introv ole oeq.\n  allunfold ord_eq; repnd.\n  eapply ord_le_trans;eauto.\nQed.\n\nLemma ord_lt_eq_trans :\n  forall o1 o2 o3, o1 << o2 -> o2 =o= o3 -> o1 << o3.\nProof.\n  introv olt oeq.\n  allunfold ord_eq; repnd.\n  eapply ord_lt_le_trans;eauto.\nQed.\n\nLemma implies_ord_lt_OS :\n  forall o1 o2, o1 <=< o2 -> o1 << (OS o2).\nProof.\n  introv ole.\n  unfold ord_lt.\n  exists (None : opred_type (OS o2)); simpl; auto.\nQed.\n\nLemma ord_le_oadd_l :\n  forall o1 o2, o1 <=< (oadd o1 o2).\nProof.\n  induction o1; introv; auto; simpl.\n  - apply (le_OS o1 (OS (oadd o1 o2)) None); simpl; auto.\n  - constructor; introv.\n    eapply implies_ord_le_limit_right; eauto.\nQed.\n\nLemma ord_le_OS :\n  forall o, o <=< (OS o).\nProof.\n  induction o as [|? ind|? ind]; introv; auto; simpl.\n  - apply (le_OS o (OS (OS o)) None); simpl; auto.\n  - constructor; introv.\n    eapply ord_le_trans;[apply ind|].\n    apply (le_OS (o n) (OS (OL o)) None); simpl; auto.\n    eapply implies_ord_le_limit_right; apply ord_le_refl.\nQed.\n\nLemma ord_le_oadd_r :\n  forall o1 o2, o2 <=< (oadd o1 o2).\nProof.\n  induction o1 as [|? ind|? ind]; introv; auto; simpl.\n  - apply ord_le_refl.\n  - eapply ord_le_trans;[apply ind|]; auto.\n    apply ord_le_OS.\n  - eapply ord_le_trans;[apply (ind 0)|]; auto.\n    eapply implies_ord_le_limit_right; apply ord_le_refl.\nQed.\n\nLemma ord_lt_OS_implies :\n  forall o1 o2,\n    o1 << (OS o2)\n    -> o1 <=< o2.\nProof.\n  introv olt.\n  unfold ord_lt in olt; exrepnd; allsimpl.\n  destruct i; allsimpl; tcsp.\n  eapply ord_le_trans;[exact olt0|].\n  apply implies_ord_le_opred_left.\n  apply ord_le_refl.\nQed.\n\nLemma comp_ind_ord :\n  forall (P: ord -> Type),\n    (forall n, (forall m, m << n -> P m) -> P n)\n    -> forall n, P n.\nProof.\n intros P IH n.\n\n assert (forall n m, ord_lt m n -> P m) as h.\n { intro n0.\n   induction n0 as [|n' ind|f ind]; introv h.\n   - apply not_ord_lt_zero in h; tcsp.\n   - unfold ord_lt in h; exrepnd; allsimpl.\n     destruct i; allsimpl.\n     + apply IH; auto.\n       apply ord_le_opred_implies_ord_lt in h0.\n       introv q.\n       eapply ord_lt_trans in h0;[|exact q].\n       apply ind; auto.\n     + apply IH.\n       introv ltm.\n       apply ind.\n       eapply ord_lt_le_trans; eauto.\n   - unfold ord_lt in h; exrepnd; allsimpl.\n     exrepnd; allsimpl.\n     apply ord_le_opred_right_implies_lt in h0.\n     apply ind in h0; auto. }\n\n apply IH; apply h.\nDefined.\n\nDefinition ntseq {o} : Type := nat -> @NTerm o.\n\nDefinition bterm2term {o} (b : @BTerm o) :=\n  match b with\n    | bterm _ t => t\n  end.\n\n(*\nScheme NTerm_mut := Induction for NTerm Sort Prop\nwith BTerm_mut := Induction for BTerm Sort Prop.\n*)\n\n(*\nDefinition term_rel := NTerm -> NTerm -> Type.\n*)\n\nDefinition isvar {p} (t : @NTerm p) :=\n  match t with\n    | vterm _ => true\n    | _ => false\n  end.\n\nDefinition isvariable {p} (t : @NTerm p) :=\n  match t with\n    | vterm _ => True\n    | _ => False\n  end.\n\nDefinition iscanonical {p} (t : @NTerm p) :=\n  match t with\n    | oterm (Can _) _ => true\n    | sterm _ => true\n    | _ => false\n  end.\n\nDefinition iscan {p} (t : @NTerm p) :=\n  match t with\n    | oterm (Can _) _ => True\n    | sterm _ => True\n    | _ => False\n  end.\n\nDefinition isnoncan {p} (t : @NTerm p) :=\n  match t with\n    | vterm _ => False\n    | sterm _ => False\n    | oterm o _ =>\n      match o with\n        | NCan _ => True\n        | _ => False\n      end\n  end.\n\nDefinition isexception {p} (t: @NTerm p) :=\n  match t with\n    | vterm _ => false\n    | sterm _ => false\n    | oterm o _ =>\n      match o with\n        | Exc => true\n        | _ => false\n      end\n  end.\n\nDefinition isexc {p} (t: @NTerm p) :=\n  match t with\n    | vterm _ => False\n    | sterm _ => False\n    | oterm o _ =>\n      match o with\n        | Exc => True\n        | _ => False\n      end\n  end.\n\nDefinition isabs {p} (t: @NTerm p) :=\n  match t with\n    | vterm _ => False\n    | sterm _ => False\n    | oterm o _ =>\n      match o with\n        | Abs _ => True\n        | _ => False\n      end\n  end.\n\nDefinition isseq {p} (t : @NTerm p) :=\n  match t with\n    | vterm _ => False\n    | sterm _ => True\n    | oterm _ _ => False\n  end.\n\nLtac d_isnoncan H :=\n  match type of H with\n      isnoncan ?t =>\n      let tlbt := fresh t \"lbt\" in\n      let tnc := fresh t \"nc\" in\n      let tt := fresh \"temp\" in\n      destruct t as [tt|tt|tt tlbt];\n        [complete (inverts H as H)|complete (inverts H as H)|];\n        destruct tt as [tt|tnc|tex|tabs];\n        [ complete(inverts H as H)\n        | idtac\n        | complete(inverts H as H)\n        | complete(inverts H as H)\n        ]\n  end.\n\nLtac d_isexc H :=\n  match type of H with\n      isexc ?t =>\n      let tlbt := fresh t \"lbt\" in\n      let tnc := fresh t \"nc\" in\n      let tt := fresh \"temp\" in\n      destruct t as [tt|tt|tt tlbt];\n        [complete (inverts H as H)|complete (inverts H as H)|];\n        destruct tt as [tt|tnc|tex|tabs];\n        [ complete(inverts H as H)\n        | complete(inverts H as H)\n        | idtac\n        | complete(inverts H as H)\n        ]\n  end.\n\nLtac d_isabs H :=\n  match type of H with\n      isabs ?t =>\n      let x  := fresh t \"x\" in\n      let bs := fresh t \"bs\" in\n      let tt := fresh \"temp\" in\n      destruct t as [tt|tt|tt tlbt];\n        [complete (inverts H as H)|complete (inverts H as H)|];\n        destruct tt as [tt|tnc|tex|tabs];\n        [ complete(inverts H as H)\n        | complete(inverts H as H)\n        | complete(inverts H as H)\n        | idtac\n        ]\n  end.\n\n\n(*Notation \"x # b\" := (bterm [x] b) (at level 70, right associativity).\n(*Check [[ btermO (vterm(nvar 0))]] *)\n(* Notation \"< N >\" := (btermO N). *)\nNotation \"\\\\ f\" :=\n  (oterm (Can NLambda) [[f]]) (at level 70, right associativity).\n\n*)\n\nNotation \"(| a , b |)\" :=\n  (oterm (Can NPair) [bterm [] a, bterm [] b]) (at level 70, right associativity).\n\n\n(* ------ CONSTRUCTORS ------ *)\n\n\n(* --- primitives --- *)\n\n(* end hide *)\n\n(** Here are some handy definitions that will\n    reduce the verbosity of some of our later definitions.\n*)\n\nDefinition nobnd {p} (f : @NTerm p) := bterm [] f.\n\nDefinition mk_var {p} (nv : NVar) : @NTerm p := vterm nv.\n\nDefinition mk_lam {p} (v : NVar) (b : @NTerm p) := oterm (Can NLambda) [bterm [v] b].\n\nDefinition mk_fix {p} (f : @NTerm p) := oterm (NCan NFix) [ bterm [] f ].\n\nDefinition mk_apply {p} (f a : @NTerm p) := oterm (NCan NApply) [nobnd f , nobnd a].\n\nDefinition mk_eapply {p} (f a : @NTerm p) := oterm (NCan NEApply) [nobnd f , nobnd a].\n\nDefinition mk_apseq {p} (f : nseq) (a : @NTerm p) := oterm (NCan (NApseq f)) [nobnd a].\n\nDefinition mk_token {p} s : @NTerm p := oterm (Can (NTok s)) [].\n\nDefinition mk_utoken {p} (u : get_patom_set p) : @NTerm p := oterm (Can (NUTok u)) [].\n\nDefinition mk_exception {p} (a e : @NTerm p) := oterm Exc [nobnd a; nobnd e].\n\n(** %\\noindent \\\\*% We define similar abstractions for other [Opid]s.\n    This document does not show them. As mentioned before, one can click\n    at the hyperlinked filename that is closest above to open a\n    webpage that shows complete contents of this file.\n*)\n\n(** %\\noindent% Whenever we talk about the [NTerm] of a [BTerm], this is\nwhat we would mean:\n\n*)\nDefinition get_nt {p} (bt : @BTerm p) : NTerm :=\n match bt with\n | bterm lv nt => nt\n end.\n\nDefinition get_vars {p} (bt: @BTerm p) : list NVar :=\n match bt with\n | bterm lv nt => lv\n end.\n\nDefinition num_bvars {p} (bt : @BTerm p) := length (get_vars bt).\n\n\n(**\n    We define functions that compute the free variables and\n    bound variables of a term.\n    Note how these functions have just two cases\n    and are robust against addition/deletion of new operators([Opid]s) to the\n    language.\n    If we had defined [NTerm] in the usual way(with one constructor for each [Opid]),\n    these definitions would be of the form of a long pattern match with one case for each [Opid].\n    However, these definitions only care about the binding structure.\n    We will reap more benefits of this uniformity when we define substitution and alpha equality\n    in the next subsection.\n*)\n\n\n(* --- variables --- *)\n\n(* What could be the free vars of [sterm f]?  The union of the free vars of\n   all the [f n] for all nats [n]?  For now let's consider closed sequences\n   only.\n *)\nFixpoint free_vars {p} (t:@NTerm p) : list NVar :=\n  match t with\n  | vterm v => [v]\n  | sterm _ => []\n  | oterm op bts => flat_map free_vars_bterm bts\n  end\n with free_vars_bterm {p} (bt : BTerm) :=\n  match bt with\n  | bterm  lv nt => remove_nvars lv (free_vars nt)\n  end.\n\nFixpoint bound_vars {p} (t : @NTerm p) : list NVar :=\n  match t with\n  | vterm _ => []\n  | sterm _ => []\n  | oterm _ bts => flat_map bound_vars_bterm bts\n  end\n with bound_vars_bterm {p} (bt : BTerm) :=\n  match bt with\n  | bterm lv nt => lv ++ bound_vars nt\n  end.\n\nDefinition all_vars {p} (t : @NTerm p) := free_vars t ++ bound_vars t.\n\nDefinition closed {p} (t : @NTerm p) := free_vars t = [].\n\nDefinition get_utokens_c {p} (c : @CanonicalOp p) : list (get_patom_set p) :=\n  match c with\n    | NUTok u => [u]\n    | _ => []\n  end.\n\nDefinition get_utokens_o {p} (o : @Opid p) : list (get_patom_set p) :=\n  match o with\n    | Can c => get_utokens_c c\n    | _ => []\n  end.\n\nFixpoint get_utokens {p} (t : @NTerm p) : list (get_patom_set p) :=\n  match t with\n    | vterm _ => []\n    | sterm _ => []\n    | oterm o bterms => (get_utokens_o o) ++ (flat_map get_utokens_b bterms)\n  end\nwith get_utokens_b {p} (bt : @BTerm p) : list (get_patom_set p) :=\n       match bt with\n         | bterm _ t => get_utokens t\n       end.\n\nDefinition noutokens {o} (t : @NTerm o) := get_utokens t = [].\n\n(**\n\n  First, we define the [allvars] function that extracts all the\n  variables from a term, i.e., both its free and bound variables.  We\n  prove that [allvars t] is equivalent as a set to [all_vars t].\n\n *)\n\nFixpoint allvars {p} (t : @NTerm p) : list NVar :=\n  match t with\n    | vterm v => [v]\n    | sterm _ => []\n    | oterm o bts => flat_map allvarsbt bts\n  end\nwith allvarsbt {p} (bt : BTerm) :=\n  match bt with\n    | bterm vs t => vs ++ allvars t\n  end.\n\nSet Implicit Arguments.\n\nInductive OList T :=\n| OLO : T -> OList T\n| OLL : list (OList T) -> OList T\n| OLS : (nat -> OList T) -> OList T.\n\nFixpoint olist_size {T} (l : OList T) : ord :=\n  match l with\n    | OLO _ => O1\n    | OLL l => OS (oaddl (map olist_size l))\n    | OLS f => OS (OL (fun x => olist_size (f x)))\n  end.\n\nLemma implies_ord_le_oaddl :\n  forall l o,\n    {x : ord & LIn x l # o <=< x}\n    -> o <=< (oaddl l).\nProof.\n  induction l; introv h; exrepnd; allsimpl; tcsp.\n  eapply ord_le_trans;[exact h0|]; clear h0.\n  repndors; subst; tcsp.\n  - apply ord_le_oadd_l.\n  - eapply ord_le_trans;[apply IHl|].\n    { eexists; dands; eauto 3 with slow. }\n    { apply ord_le_oadd_r. }\nQed.\n\nLemma olist_better_ind {T} :\n  forall P : OList T -> Type,\n    (forall x : T, P (OLO x))\n    -> (forall l, (forall x, LIn x l -> P x) -> P (OLL l))\n    -> (forall f, (forall n, P (f n)) -> P (OLS f))\n    -> forall o, P o.\nProof.\n  introv ho hl hs.\n\n  assert (forall n o, (olist_size o) =o= n -> P o) as Hass;\n    [|introv;\n       apply Hass with (n := olist_size o);\n       apply ord_eq_refl];[].\n\n  induction n as [n Hind] using comp_ind_ord.\n  introv Hsz.\n  destruct o as [v|l|f]; auto.\n\n  - apply hl; introv i; allsimpl.\n    pose proof (Hind (olist_size x)) as h; clear Hind.\n    autodimp h hyp; [|apply h; apply ord_eq_refl].\n    eapply ord_lt_eq_trans;[|exact Hsz]; clear Hsz.\n    apply implies_ord_lt_OS.\n    apply implies_ord_le_oaddl.\n    exists (olist_size x); dands; eauto 3 with slow.\n    rw in_map_iff; eexists; eauto.\n\n  - apply hs; introv; allsimpl.\n    pose proof (Hind (olist_size (f n0))) as h; clear Hind.\n    autodimp h hyp; [|apply h; apply ord_eq_refl].\n    eapply ord_lt_eq_trans;[|exact Hsz]; clear Hsz.\n    apply implies_ord_lt_OS.\n    eapply implies_ord_le_limit_right; apply ord_le_refl.\nDefined.\n\nInductive in_olist {T} (v : T) : OList T -> Type :=\n| in_olist_v : in_olist v (OLO v)\n| in_olist_l :\n    forall l,\n      {o : OList T & LIn o l # in_olist v o}\n      -> in_olist v (OLL l)\n| in_olist_s :\n    forall f,\n      {n : nat & in_olist v (f n)}\n      -> in_olist v (OLS f).\nHint Constructors in_olist.\n\nDefinition subseto {T} (l : list T) (o : OList T) : Type :=\n  forall x, LIn x l -> in_olist x o.\n\nDefinition osubset {T} (o1 o2 : OList T) :=\n  forall x, in_olist x o1 -> in_olist x o2.\n\nLemma osubset_singleton_OLS_l {T} :\n  forall f (l : OList T),\n    osubset (OLS f) l <=> (forall n, osubset (f n) l).\nProof.\n  unfold osubset.\n  introv; split; introv h i; allsimpl.\n  - apply h.\n    constructor; eexists; eauto.\n  - inversion i; exrepnd; subst.\n    eapply h; eauto.\nQed.\n\nLemma implies_osubset_singleton_OLS_r {T} :\n  forall (o : @OList T) n f,\n    osubset o (f n)\n    -> osubset o (OLS f).\nProof.\n  introv i j.\n  constructor.\n  exists n; auto.\nQed.\n\nLemma implies_osubset_singleton_OLS_r_ex {T} :\n  forall (l : OList T) f,\n    {n : nat & osubset l (f n)}\n    -> osubset l (OLS f).\nProof.\n  introv h; exrepnd.\n  eapply implies_osubset_singleton_OLS_r; eauto.\nQed.\n\nDefinition onil {T} : OList T := OLL [].\n\nLemma osubset_nil_l {T} :\n  forall (l : OList T), osubset onil l.\nProof.\n  introv i.\n  inversion i; subst; exrepnd; allsimpl; tcsp.\nQed.\nHint Resolve osubset_nil_l : slow.\n\nLemma in_olist_in_trans {T} :\n  forall l (x : T) o,\n    in_olist x o\n    -> LIn o l\n    -> in_olist x (OLL l).\nProof.\n  introv i j.\n  constructor.\n  eexists; eauto.\nQed.\n\nLemma osubset_in_trans {T} :\n  forall (o1 : OList T) o2 l,\n    osubset o1 o2\n    -> LIn o2 l\n    -> osubset o1 (OLL l).\nProof.\n  introv i j k.\n  constructor.\n  eexists; dands; eauto.\nQed.\n\nLemma osubset_OLO_implies_in_olist_eq {T} :\n  forall (o : OList T) x,\n    osubset o (OLO x)\n    -> (forall v, in_olist v o -> v = x).\nProof.\n  introv h q.\n  apply h in q.\n  inversion q; auto.\nQed.\n\nLemma osubset_refl {T} :\n  forall (l : OList T), osubset l l.\nProof.\n  introv i; auto.\nQed.\nHint Resolve osubset_refl : slow.\n\n(*\nLemma olist_in_if_in {T} :\n  forall o (l : list (OList T)), LIn o l -> olist_in o (OLL l).\nProof.\n  introv i.\n  apply olist_in_iff; introv j.\n  constructor.\n  eexists; dands; eauto.\nQed.\n*)\n\nDefinition osubset_as_osubseto {T} :\n  forall (l : list T) (os : OList T),\n    subseto l os <=> osubset (OLL (map (@OLO T) l)) os.\nProof.\n  unfold osubset, subseto.\n  introv; split; introv h.\n  - introv i.\n    inversion i as [|? q|]; subst; clear i; exrepnd.\n    allrw in_map_iff; exrepnd; subst.\n    inversion q0; subst; clear q0; auto.\n  - introv i.\n    apply h.\n    constructor.\n    exists (OLO x); dands; auto.\n    rw in_map_iff; eexists; eauto.\nQed.\n\nLemma subseto_nil_l {T} :\n  forall (os : OList T), subseto [] os.\nProof.\n  introv h; allsimpl; tcsp.\nQed.\nHint Resolve subseto_nil_l : slow.\n\nLemma subseto_app_l {T} :\n  forall l1 l2 (os : OList T),\n    subseto (l1 ++ l2) os <=> (subseto l1 os # subseto l2 os).\nProof.\n  introv; split; intro h.\n  - dands; introv i; apply h; rw in_app_iff; sp.\n  - repnd; introv i; allrw in_app_iff; repndors; discover; auto.\nQed.\n\nLemma implies_subseto_app_r {T} :\n  forall l (os1 os2 : list (OList T)),\n    (subseto l (OLL os1) [+] subseto l (OLL os2))\n    -> subseto l (OLL (os1 ++ os2)).\nProof.\n  introv h i.\n  constructor.\n  repndors; apply h in i; clear h; inversion i; subst; exrepnd;\n  eexists; dands; eauto; rw in_app_iff; tcsp.\nQed.\n\nLemma implies_subseto_cons_ols_r {T} :\n  forall l f (os : list (OList T)),\n    ({n : nat & subseto l (f n)} [+] subseto l (OLL os))\n    -> subseto l (OLL (OLS f :: os)).\nProof.\n  introv h i.\n  repndors.\n  - exrepnd.\n    apply h0 in i.\n    constructor; simpl.\n    eexists; dands; eauto.\n  - apply h in i; exrepnd.\n    inversion i; subst; exrepnd.\n    constructor; simpl.\n    eexists; dands; eauto.\nQed.\n\nLemma subseto_refl {T} :\n  forall (l : list T), subseto l (OLL (map (@OLO T) l)).\nProof.\n  introv i.\n  constructor.\n  exists (OLO x); dands; auto.\n  rw in_map_iff; eexists; eauto.\nQed.\nHint Resolve osubset_refl : slow.\n\nLemma subseto_flat_map_l :\n  forall {A B} (f : A -> list B) (l : list A) (k : OList B),\n    subseto (flat_map f l) k <=> (forall x : A, LIn x l -> subseto (f x) k).\nProof.\n  introv; split; intro h.\n  - introv i j.\n    apply h.\n    rw lin_flat_map; eexists; eauto.\n  - introv i; allrw lin_flat_map; exrepnd.\n    applydup h in i1.\n    applydup i2 in i0; auto.\nQed.\n\nLemma subseto_flat_map2 :\n  forall {A B} (f : A -> list B) (g : A -> OList B) (l : list A),\n    (forall x : A, LIn x l -> subseto (f x) (g x))\n    -> subseto (flat_map f l) (OLL (map g l)).\nProof.\n  introv imp i.\n  allrw lin_flat_map; exrepnd.\n  applydup imp in i1.\n  applydup i2 in i0.\n  constructor.\n  eexists; dands; eauto.\n  rw in_map_iff; eexists; eauto.\nQed.\n\nLemma osubset_singleton_OLL_l {T} :\n  forall l (o : OList T),\n    osubset (OLL l) o <=> (forall x, LIn x l -> osubset x o).\nProof.\n  unfold osubset.\n  introv; split; introv h i; allsimpl.\n  - introv j.\n    apply h.\n    constructor.\n    eexists; eauto.\n  - inversion i; exrepnd; subst; clear i.\n    eapply h; eauto.\nQed.\n\nLemma implies_osubset_singleton_OLL_r {T} :\n  forall l (o : OList T),\n    {x : OList T & LIn x l # osubset o x}\n    -> osubset o (OLL l).\nProof.\n  unfold osubset; introv h i; exrepnd.\n  constructor.\n  eexists; eauto.\nQed.\n\nDefinition oeqset {T} (o1 o2 : OList T) :=\n  forall x, in_olist x o1 <=> in_olist x o2.\n\nLemma oeqset_refl {T} :\n  forall o : OList T, oeqset o o.\nProof.\n  introv; unfold oeqset; introv; sp.\nQed.\nHint Resolve oeqset_refl : slow.\n\nLemma oeqset_sym {T} :\n  forall (o1 o2 : OList T), oeqset o1 o2 <=> oeqset o2 o1.\nProof.\n  introv; unfold oeqset; split; intro h; introv; rw h; sp.\nQed.\nHint Resolve oeqset_sym : slow.\n\nLemma oeqset_trans {T} :\n  forall (o1 o2 o3 : OList T), oeqset o1 o2 -> oeqset o2 o3 -> oeqset o1 o3.\nProof.\n  unfold oeqset; introv h1 h2; introv.\n  rw h1; rw h2; sp.\nQed.\nHint Resolve oeqset_trans : slow.\n\nFixpoint oflatten {T} (o : OList T) : list (OList T) :=\n  match o with\n    | OLL l => flat_map oflatten l\n    | _ => [o]\n  end.\n\nDefinition oappl {T} (l : list (OList T)) : OList T :=\n  match flat_map oflatten l with\n    | [o] => o\n    | l => OLL l\n  end.\n\nDefinition oapp {T} (o1 o2 : OList T) : OList T := oappl [o1, o2].\n\nLemma in_olist_OLL_app {T} :\n  forall x (l1 l2 : list (OList T)),\n    in_olist x (OLL (l1 ++ l2))\n    <=> (in_olist x (OLL l1) [+] in_olist x (OLL l2)).\nProof.\n  introv; split; introv h.\n  - inversion h as [|? q|]; clear h; subst; exrepnd.\n    allrw in_app_iff; repndors.\n    + left; constructor; eexists; eauto.\n    + right; constructor; eexists; eauto.\n  - constructor; repndors; inversion h as [|? q|]; clear h; subst; exrepnd.\n    + eexists;dands;[|eauto]; rw in_app_iff; sp.\n    + eexists;dands;[|eauto]; rw in_app_iff; sp.\nQed.\n\nLemma in_olist_OLL_cons {T} :\n  forall x o (l : list (OList T)),\n    in_olist x (OLL (o :: l))\n    <=> (in_olist x o [+] in_olist x (OLL l)).\nProof.\n  introv; split; introv h.\n  - inversion h as [|? q|]; clear h; subst; exrepnd.\n    allsimpl; repndors; subst; tcsp.\n    right; constructor; eexists; eauto.\n  - constructor; repndors; inversion h as [|? q|]; clear h; subst; exrepnd; simpl;\n    try (complete (eexists; eauto)).\n    exists (OLL l0); dands; auto.\n    constructor.\n    eexists; eauto.\nQed.\n\nLemma in_olist_OLL_singleton {T} :\n  forall x (o : OList T),\n    in_olist x (OLL [o]) <=> in_olist x o.\nProof.\n  introv; split; intro h.\n  - inversion h as [|? q|]; subst; clear h; exrepnd.\n    allsimpl; repndors; subst; tcsp.\n  - constructor; simpl; eexists; eauto.\nQed.\n\nLemma oeqset_singleton_l {T} :\n  forall (o : OList T), oeqset (OLL [o]) o.\nProof.\n  repeat introv.\n  apply in_olist_OLL_singleton.\nQed.\n\nLemma implies_oeqset_OLL_OLL2 {T} :\n  forall (l1 l2 : list (OList T)),\n    (forall o x, LIn o l1 -> in_olist x o -> in_olist x (OLL l2))\n    -> (forall o x, LIn o l2 -> in_olist x o -> in_olist x (OLL l1))\n    -> oeqset (OLL l1) (OLL l2).\nProof.\n  introv h1 h2; introv; split; intro h.\n  - inversion h as [|? q|]; subst; clear h; exrepnd.\n    apply h1 in q0; auto.\n  - inversion h as [|? q|]; subst; clear h; exrepnd.\n    apply h2 in q0; auto.\nQed.\n\nLemma in_olist_OLL_map {A T} :\n  forall x (f : A -> OList T) (l : list A),\n    in_olist x (OLL (map f l)) <=> {a : A & LIn a l # in_olist x (f a)}.\nProof.\n  introv; split; intro h.\n  - inversion h as [|? q|]; subst; clear h; exrepnd.\n    allrw in_map_iff; exrepnd; subst.\n    eexists; eauto.\n  - exrepnd.\n    constructor; eexists; dands; eauto.\n    rw in_map_iff; eexists; eauto.\nQed.\n\nLemma in_olist_OLL_flat_map {A T} :\n  forall x (f : A -> list (OList T)) (l : list A),\n    in_olist x (OLL (flat_map f l))\n    <=> {a : A & LIn a l # in_olist x (OLL (f a))}.\nProof.\n  introv; split; intro h.\n  - inversion h as [|? q|]; subst; clear h; exrepnd.\n    allrw lin_flat_map; exrepnd; subst.\n    eexists; eauto.\n  - exrepnd.\n    constructor.\n    inversion h0; subst; exrepnd; clear h0.\n    eexists; dands; eauto.\n    rw lin_flat_map; dands.\n    eexists; dands; eauto.\nQed.\n\nLemma oeqset_OLL_oflatten {T} :\n  forall o : OList T, oeqset (OLL (oflatten o)) o.\nProof.\n  induction o as [|l ind|f ind] using olist_better_ind; allsimpl.\n  - apply oeqset_singleton_l.\n  - introv; split; intro h; allrw @in_olist_OLL_flat_map; exrepnd.\n    + applydup ind in h1.\n      apply h2 in h0.\n      constructor.\n      eexists; dands; eauto.\n    + inversion h as [|? q|]; clear h; subst; exrepnd.\n      applydup ind in q1.\n      eexists; dands; eauto.\n      apply q2; auto.\n  - apply oeqset_singleton_l.\nQed.\n\nLemma oeqset_oapp_OLL_app_oflatten {T} :\n  forall (o1 o2 : OList T),\n    oeqset (oapp o1 o2) (OLL (oflatten o1 ++ oflatten o2)).\nProof.\n  repeat introv.\n  unfold oapp, oappl; simpl; allrw app_nil_r.\n  remember (oflatten o1) as l1.\n  remember (oflatten o2) as l2.\n  destruct l1; simpl.\n  - destruct l2; simpl; tcsp.\n    destruct l2; simpl; tcsp.\n    rw @oeqset_singleton_l; tcsp.\n  - destruct l1; simpl; tcsp.\n    destruct l2; simpl; tcsp.\n    rw @oeqset_singleton_l; tcsp.\nQed.\n\nLemma oeqset_app_if {T} :\n  forall (l1 l2 l3 l4 : list (OList T)),\n    oeqset (OLL l1) (OLL l3)\n    -> oeqset (OLL l2) (OLL l4)\n    -> oeqset (OLL (l1 ++ l2)) (OLL (l3 ++ l4)).\nProof.\n  unfold oeqset.\n  introv h1 h2; introv.\n  split; introv q;\n  allrw @in_olist_OLL_app; repndors;\n  try (complete (apply h1 in q; sp));\n  try (complete (apply h2 in q; sp)).\nQed.\n\nLemma oeqset_cons_if {T} :\n  forall o1 o2 (l1 l2 : list (OList T)),\n    oeqset o1 o2\n    -> oeqset (OLL l1) (OLL l2)\n    -> oeqset (OLL (o1 :: l1)) (OLL (o2 :: l2)).\nProof.\n  unfold oeqset.\n  introv h1 h2; introv.\n  split; introv q;\n  allrw @in_olist_OLL_cons; repndors; tcsp;\n  try (complete (apply h1 in q; sp));\n  try (complete (apply h2 in q; sp)).\nQed.\n\nLemma fold_oapp {T} :\n  forall (o1 o2 : OList T), oeqset (oapp o1 o2) (OLL [o1, o2]).\nProof.\n  introv.\n  eapply oeqset_trans;[apply oeqset_oapp_OLL_app_oflatten|].\n  assert ([o1,o2] = [o1] ++ [o2]) as e by sp.\n  rw e; clear e.\n  apply oeqset_app_if.\n  - eapply oeqset_trans;[apply oeqset_OLL_oflatten|].\n    apply oeqset_sym.\n    apply oeqset_singleton_l.\n  - eapply oeqset_trans;[apply oeqset_OLL_oflatten|].\n    apply oeqset_sym.\n    apply oeqset_singleton_l.\nQed.\n\nLemma oapp_nil_l {T} :\n  forall (o : OList T), oeqset (oapp onil o) o.\nProof.\n  introv.\n  eapply oeqset_trans;[apply oeqset_oapp_OLL_app_oflatten|].\n  simpl.\n  apply oeqset_OLL_oflatten.\nQed.\n\nLemma flat_map_eq_singleton_implies :\n  forall {A B} (f : A -> list B) l x,\n    flat_map f l = [x] -> {a : A & LIn a l # f a = [x]}.\nProof.\n  induction l; introv e; allsimpl; ginv.\n  remember (f a) as l1.\n  destruct l1; allsimpl.\n  - apply IHl in e; exrepnd.\n    eexists; dands; eauto.\n  - destruct l1; allsimpl; ginv.\n    remember (flat_map f l) as l2.\n    destruct l2; allsimpl; ginv.\n    exists a; sp.\nQed.\n\nLemma oflatten_singleton {T} :\n  forall o1 o2 : OList T,\n    oflatten o1 = [o2] -> oflatten o2 = [o2].\nProof.\n  induction o1 as [|l ind|f ind] using olist_better_ind;\n  introv h; allsimpl; ginv; allsimpl; auto.\n  apply flat_map_eq_singleton_implies in h; exrepnd.\n  eapply ind; eauto.\nQed.\n\nLemma oeqset_OLL_cons {T} :\n  forall (o : OList T) l, oeqset (OLL (o :: l)) (oapp o (OLL l)).\nProof.\n  introv.\n  eapply oeqset_trans;[|apply oeqset_sym; apply fold_oapp].\n  apply oeqset_cons_if; eauto 3 with slow.\n  eapply oeqset_sym.\n  apply oeqset_singleton_l.\nQed.\n\nLemma oeqset_flat_map_oflatten {T} :\n  forall (l : list (OList T)),\n    oeqset (OLL (flat_map oflatten l)) (OLL l).\nProof.\n  induction l; simpl; eauto 3 with slow.\n  rw cons_as_app.\n  apply oeqset_app_if; auto.\n  eapply oeqset_trans;[apply oeqset_OLL_oflatten|].\n  apply oeqset_sym.\n  apply oeqset_singleton_l.\nQed.\n\nLemma oappl_nil {T} : @oappl T [] = OLL [].\nProof. sp. Qed.\nHint Rewrite @oappl_nil : slow.\n\nLemma oappl_OLL_nil {T} :\n  oappl [OLL []] = @OLL T [].\nProof.\n  sp.\nQed.\nHint Rewrite @oappl_OLL_nil : slow.\n\nLemma in_oflatten_singleton {T} :\n  forall (o1 o2 : OList T),\n    LIn o2 (oflatten o1) -> oflatten o2 = [o2].\nProof.\n  induction o1 as [|l ind|f ind] using olist_better_ind;\n  introv i; allsimpl; ginv; allsimpl; auto; repndors; subst; tcsp.\n  allrw lin_flat_map; exrepnd.\n  eapply ind; eauto.\nQed.\n\nLemma in_oflatten_diff_OLL {T} :\n  forall (o1 o2 : OList T) l,\n    LIn o2 (oflatten o1) -> o2 <> OLL l.\nProof.\n  induction o1 as [|l ind|f ind] using olist_better_ind;\n  introv i; introv e; allsimpl; ginv; allsimpl; auto; repndors; subst; tcsp; ginv.\n  allrw lin_flat_map; exrepnd.\n  eapply ind; eauto.\nQed.\n\nLemma subset_flat_map_oflatten_singleton {T} :\n  forall (k l : list (OList T)),\n    subset k (flat_map oflatten l)\n    -> flat_map oflatten k = k.\nProof.\n  induction k; introv h; allsimpl; auto.\n  allrw @cons_subset; repnd.\n  allrw lin_flat_map; exrepnd.\n  apply in_oflatten_singleton in h1; rw h1; simpl; f_equal.\n  eapply IHk; eauto.\nQed.\n\nLemma osubset_app_left {T} :\n  forall (l1 l2 l : list (OList T)),\n    osubset (OLL l1) (OLL l)\n    -> osubset (OLL l2) (OLL l)\n    -> osubset (OLL (l1 ++ l2)) (OLL l).\nProof.\n  introv h1 h2 i.\n  apply in_olist_OLL_app in i; repndors.\n  - apply h1 in i; auto.\n  - apply h2 in i; auto.\nQed.\n\nLemma oappl_cons_oappl {T} :\n  forall l1 l2 : list (OList T),\n    oappl (oappl l1 :: l2) = oappl (l1 ++ l2).\nProof.\n  introv; unfold oappl; simpl.\n  rw flat_map_app.\n  remember (flat_map oflatten l1) as k1.\n  remember (flat_map oflatten l2) as k2.\n  destruct k1; simpl; auto.\n  destruct k1; simpl; auto.\n  - symmetry in Heqk1.\n    apply flat_map_eq_singleton_implies in Heqk1; exrepnd.\n    apply oflatten_singleton in Heqk0; rw Heqk0; simpl; auto.\n  - symmetry in Heqk1.\n\n    assert (LIn o (flat_map oflatten l1)) as i1.\n    { rw Heqk1; simpl; sp. }\n    assert (LIn o0 (flat_map oflatten l1)) as i2.\n    { rw Heqk1; simpl; sp. }\n    assert (subset k1 (flat_map oflatten l1)) as ss.\n    { rw Heqk1; repeat (apply subset_cons1); auto. }\n\n    allrw lin_flat_map; exrepnd.\n    apply in_oflatten_singleton in i3.\n    apply in_oflatten_singleton in i0.\n    apply subset_flat_map_oflatten_singleton in ss.\n    rw i0; rw i3; rw ss; simpl; auto.\nQed.\nHint Rewrite @oappl_cons_oappl : slow.\n\nLemma implies_oappl_cons {T} :\n  forall (o : OList T) l1 l2,\n    oappl l1 = oappl l2\n    -> oappl (o :: l1) = oappl (o :: l2).\nProof.\n  introv h.\n  allunfold @oappl; allsimpl.\n  remember (oflatten o) as k1.\n  remember (flat_map oflatten l1) as k2.\n  remember (flat_map oflatten l2) as k3.\n  destruct k1; allsimpl; tcsp; ginv.\n  destruct k1; allsimpl; tcsp; ginv.\n  - destruct k2; allsimpl; tcsp; ginv.\n    + destruct k3; allsimpl; tcsp; ginv.\n      destruct k3; allsimpl; tcsp; ginv.\n      subst.\n      assert (LIn (OLL []) (flat_map oflatten l2)) as i.\n      { rw <- Heqk3; simpl; tcsp. }\n      rw lin_flat_map in i; exrepnd.\n      apply in_oflatten_singleton in i0; allsimpl; ginv.\n    + destruct k2; allsimpl; tcsp; ginv.\n      * destruct k3; allsimpl; tcsp; ginv.\n        { subst.\n          assert (LIn (OLL []) (flat_map oflatten l1)) as i.\n          { rw <- Heqk2; simpl; tcsp. }\n          rw lin_flat_map in i; exrepnd.\n          apply in_oflatten_singleton in i0; allsimpl; ginv. }\n        { destruct k3; allsimpl; tcsp; ginv.\n          subst.\n          assert (LIn (OLL (o2 :: o3 :: k3)) (flat_map oflatten l1)) as i.\n          { rw <- Heqk2; simpl; tcsp. }\n          rw lin_flat_map in i; exrepnd.\n          eapply in_oflatten_diff_OLL in i0; destruct i0; eauto. }\n      * destruct k3; allsimpl; tcsp; ginv.\n        destruct k3; allsimpl; tcsp; ginv.\n        subst.\n        assert (LIn (OLL (o1 :: o2 :: k2)) (flat_map oflatten l2)) as i.\n        { rw <- Heqk3; simpl; tcsp. }\n        rw lin_flat_map in i; exrepnd.\n        eapply in_oflatten_diff_OLL in i0; destruct i0; eauto.\n  - destruct k2; allsimpl; tcsp; ginv.\n    + destruct k3; allsimpl; tcsp; ginv.\n      destruct k3; allsimpl; tcsp; ginv.\n      subst.\n      assert (LIn (OLL []) (flat_map oflatten l2)) as i.\n      { rw <- Heqk3; simpl; tcsp. }\n      rw lin_flat_map in i; exrepnd.\n      apply in_oflatten_singleton in i0; allsimpl; ginv.\n    + destruct k2; allsimpl; tcsp; ginv.\n      * destruct k3; allsimpl; tcsp; ginv.\n        { subst.\n          assert (LIn (OLL []) (flat_map oflatten l1)) as i.\n          { rw <- Heqk2; simpl; tcsp. }\n          rw lin_flat_map in i; exrepnd.\n          apply in_oflatten_singleton in i0; allsimpl; ginv. }\n        { destruct k3; allsimpl; tcsp; ginv.\n          subst.\n          assert (LIn (OLL (o3 :: o4 :: k3)) (flat_map oflatten l1)) as i.\n          { rw <- Heqk2; simpl; tcsp. }\n          rw lin_flat_map in i; exrepnd.\n          eapply in_oflatten_diff_OLL in i0; destruct i0; eauto. }\n      * destruct k3; allsimpl; tcsp; ginv.\n        destruct k3; allsimpl; tcsp; ginv.\n        subst.\n        assert (LIn (OLL (o2 :: o3 :: k2)) (flat_map oflatten l2)) as i.\n        { rw <- Heqk3; simpl; tcsp. }\n        rw lin_flat_map in i; exrepnd.\n        eapply in_oflatten_diff_OLL in i0; destruct i0; eauto.\nQed.\n\nLemma oappl_cons_oappl2 {T} :\n  forall (o : OList T) l1 l2,\n    oappl (o :: oappl l1 :: l2)\n    = oappl (o :: l1 ++ l2).\nProof.\n  introv.\n  apply implies_oappl_cons.\n  autorewrite with slow; auto.\nQed.\nHint Rewrite @oappl_cons_oappl2 : slow.\n\nLemma oappl_cons_oappl3 {T} :\n  forall (o1 o2 : OList T) l1 l2,\n    oappl (o1 :: o2 :: oappl l1 :: l2)\n    = oappl (o1 :: o2 :: l1 ++ l2).\nProof.\n  introv.\n  repeat (apply implies_oappl_cons).\n  autorewrite with slow; auto.\nQed.\nHint Rewrite @oappl_cons_oappl3 : slow.\n\nLemma oappl_cons_oappl4 {T} :\n  forall (o1 o2 o3 : OList T) l1 l2,\n    oappl (o1 :: o2 :: o3 :: oappl l1 :: l2)\n    = oappl (o1 :: o2 :: o3 :: l1 ++ l2).\nProof.\n  introv.\n  repeat (apply implies_oappl_cons).\n  autorewrite with slow; auto.\nQed.\nHint Rewrite @oappl_cons_oappl4 : slow.\n\nLemma oappl_cons_oappl5 {T} :\n  forall (o1 o2 o3 o4 : OList T) l1 l2,\n    oappl (o1 :: o2 :: o3 :: o4 :: oappl l1 :: l2)\n    = oappl (o1 :: o2 :: o3 :: o4 :: l1 ++ l2).\nProof.\n  introv.\n  repeat (apply implies_oappl_cons).\n  autorewrite with slow; auto.\nQed.\nHint Rewrite @oappl_cons_oappl5 : slow.\n\nLemma oappl_app_oappl {T} :\n  forall (l1 l2 : list (OList T)),\n    oappl (l1 ++ [oappl l2])\n    = oappl (l1 ++ l2).\nProof.\n  induction l1; introv; simpl.\n  - rw @oappl_cons_oappl; allrw app_nil_r; auto.\n  - apply implies_oappl_cons; auto.\nQed.\n\nLemma oappl_app_as_oapp {T} :\n  forall (l1 l2 : list (OList T)),\n    oappl (l1 ++ l2) = oapp (oappl l1) (oappl l2).\nProof.\n  unfold oapp; introv.\n  rw @oappl_cons_oappl.\n  rw @oappl_app_oappl; auto.\nQed.\n\nLemma oapp_assoc {T} :\n  forall (o1 o2 o3 : OList T),\n    oapp (oapp o1 o2) o3 = oapp o1 (oapp o2 o3).\nProof.\n  introv; unfold oapp.\n  allrw @oappl_cons_oappl; simpl.\n  allrw @oappl_cons_oappl2; simpl; auto.\nQed.\n\nLemma oeqset_oappl_cons {T} :\n  forall (o : OList T) l, oappl (o :: l) = oapp o (oappl l).\nProof.\n  introv; unfold oapp.\n  rw @oappl_cons_oappl2; allrw app_nil_r; auto.\nQed.\n\nLemma oeqset_oappl_OLL {T} :\n  forall l : list (OList T),\n    oeqset (oappl l) (OLL l).\nProof.\n  induction l; simpl; eauto 3 with slow.\n  rw @oeqset_oappl_cons.\n  eapply oeqset_trans;[apply fold_oapp|].\n  apply oeqset_cons_if; eauto 3 with slow.\n  eapply oeqset_trans;[apply oeqset_singleton_l|]; auto.\nQed.\n\nLemma in_olist_oapp {T} :\n  forall x (o1 o2 : OList T),\n    in_olist x (oapp o1 o2) <=> (in_olist x o1 [+] in_olist x o2).\nProof.\n  introv.\n  rw @oeqset_oapp_OLL_app_oflatten.\n  rw @in_olist_OLL_app.\n  allrw @oeqset_OLL_oflatten; sp.\nQed.\n\nLemma oeqset_oapp_sym {T} :\n  forall (o1 o2 : OList T), oeqset (oapp o1 o2) (oapp o2 o1).\nProof.\n  introv; unfold oeqset; introv; split; intro h; allrw @in_olist_oapp;\n  repndors; tcsp.\nQed.\n\nLemma oapp_OLL_left {T} :\n  forall l (o : OList T),\n    oeqset (oapp (OLL l) o) (OLL (l ++ [o])).\nProof.\n  repeat introv.\n\n  split; intro h;\n  allrw @in_olist_oapp;\n  allrw @in_olist_OLL_app;\n  allrw @oeqset_singleton_l; tcsp.\nQed.\n\nLemma implies_oeqset_OLL_OLL {T} :\n  forall (l1 l2 : list (OList T)),\n    (forall o x, LIn o l1 -> in_olist x o -> {z : OList T & LIn z l2 # in_olist x z})\n    -> (forall o x, LIn o l2 -> in_olist x o -> {z : OList T & LIn z l1 # in_olist x z})\n    -> oeqset (OLL l1) (OLL l2).\nProof.\n  introv h1 h2; introv; split; intro h.\n  - inversion h as [|? q|]; subst; clear h; exrepnd.\n    apply h1 in q0; auto.\n  - inversion h as [|? q|]; subst; clear h; exrepnd.\n    apply h2 in q0; auto.\nQed.\n\nLemma oeqset_oapp_if {T} :\n  forall (o1 o2 o3 o4 : OList T),\n    oeqset o1 o3\n    -> oeqset o2 o4\n    -> oeqset (oapp o1 o2) (oapp o3 o4).\nProof.\n  introv oeq1 oeq2.\n  constructor; introv i;\n  allrw @in_olist_oapp; repndors;\n  try (complete (apply oeq1 in i; tcsp));\n  try (complete (apply oeq2 in i; tcsp)).\nQed.\n\nLemma osubset_oapp_if {T} :\n  forall (o1 o2 o3 o4 : OList T),\n    osubset o1 o3\n    -> osubset o2 o4\n    -> osubset (oapp o1 o2) (oapp o3 o4).\nProof.\n  introv oeq1 oeq2.\n  introv i;\n  allrw @in_olist_oapp; repndors;\n  try (complete (apply oeq1 in i; tcsp));\n  try (complete (apply oeq2 in i; tcsp)).\nQed.\n\nLemma osubset_trans {T} :\n  forall (o1 o2 o3 : OList T), osubset o1 o2 -> osubset o2 o3 -> osubset o1 o3.\nProof.\n  introv h1 h2 i.\n  apply h2; apply h1; auto.\nQed.\n\nLemma oeqset_implies_osubset {T} :\n  forall (o1 o2 : OList T), oeqset o1 o2 -> osubset o1 o2.\nProof.\n  introv h i.\n  apply h; auto.\nQed.\n\nLemma implies_osubset_oapp {T} :\n  forall o o1 o2 : OList T,\n    (osubset o o1 [+] osubset o o2)\n    -> osubset o (oapp o1 o2).\nProof.\n  introv h i.\n  apply in_olist_oapp; sp.\nQed.\n\nLemma osubset_app_if {T} :\n  forall (l1 l2 l3 l4 : list (OList T)),\n    osubset (OLL l1) (OLL l3)\n    -> osubset (OLL l2) (OLL l4)\n    -> osubset (OLL (l1 ++ l2)) (OLL (l3 ++ l4)).\nProof.\n  introv h1 h2 i.\n  allrw @in_olist_OLL_app; repndors.\n  - apply h1 in i; sp.\n  - apply h2 in i; sp.\nQed.\n\nLemma subseto_oeqset {T} :\n  forall l (o1 o2 : OList T),\n    subseto l o1\n    -> oeqset o1 o2\n    -> subseto l o2.\nProof.\n  introv h1 h2 i.\n  apply h2; auto.\nQed.\n\nDefinition OVar := OList NVar.\nDefinition ovar_v v : OVar := OLO v.\nDefinition ovar_l l : OVar := OLL l.\nDefinition ovar_s f : OVar := OLS f.\n\nFixpoint allovars {p} (t : @NTerm p) : OVar :=\n  match t with\n    | vterm v => ovar_v v\n    | sterm f => ovar_s (fun n => allovars (f n))\n    | oterm o bts => oappl (map allovarsbt bts)\n  end\nwith allovarsbt {p} (bt : BTerm) : OVar :=\n       match bt with\n         | bterm vs t => oappl (map ovar_v vs ++ [allovars t])\n       end.\n\nDefinition disj_ovar (v : NVar) l := !(in_olist v l).\n\nDefinition disj_ovars (vs : list NVar) (os : OVar) : Prop :=\n  forall v o, LIn v vs -> disj_ovar v o.\n\nDefinition sat_ntseq {o} (f : ntseq) (P : @NTerm o -> Prop) : Prop :=\n  forall n, P (f n).\n\n(** % \\noindent \\\\* % We define\n    a predicate [nt_wf] on [NTerm] such that\n    [nt_wf nt] asserts that [nt] is a well-formed term.  %\\\\* %\n*)\nInductive nt_wf {p} : @NTerm p -> [univ] :=\n| wfvt: forall nv, nt_wf (vterm nv)\n| wfst: forall f,\n          (forall n, nt_wf (f n) # closed (f n) # noutokens (f n))\n          -> nt_wf (sterm f)\n| wfot: forall (o: Opid) (lnt: list BTerm),\n          (forall l, LIn l lnt -> bt_wf l)\n          -> map (num_bvars) lnt\n             = OpBindings o\n          -> nt_wf (oterm o lnt)\nwith bt_wf {p} : @BTerm p -> [univ] :=\n| wfbt : forall (lnv : list NVar) (nt: NTerm),\n           nt_wf nt -> bt_wf (bterm lnv nt).\nHint Constructors nt_wf bt_wf.\n\n(*  For example, the Opid [(Can NLambda)] takes only one [BTerm] an that [BTerm]\n  must have exactly one bound variable.\n  Hence [OpBindings (Can NLambda) = [1]]. *)\n\n(** % \\noindent \\\\* %\n  The only interesting case here is for the [oterm] case. The\n  [wfot] constructor requires\n  that the number of bound variables of the bound terms in the list\n  match the signature ([OpBindings o]) of the corresponding operator [o].\n\n  % \\noindent \\\\* % We abstract the [Opid]s into two categories, canonical\n    and noncanonical.\n\n  [\n    Inductive Opid : Set :=\n\n     | Can  : CanonicalOp -> Opid\n\n     | NCan : NonCanonicalOp -> Opid.\n\n  ]\n% \\noindent \\\\* % This distinction is important from the point of view of computation\n    and simplifies many definitions and properties about computation and\n    also makes them more easily extensible.\n    Nuprl has a lazy computation system and\n    an [NTerm] is in normal(canonical) form if its outermost [Opid] is a [CanonicalOp].\n    No further computation is performed on terms in canonical form.\n    For example, lambda abstraction are constructed by the following [Opid] :\n\n% \\noindent \\\\* % [Can NLambda]\n\n% \\noindent \\\\* % We have [OpBindings (Can NLambda) = [1]].\n\n\n    On the other hand, an [NTerm] whose outermost [Opid] is a [NonCanonicalOp] is\n    not in normal form and can compute to some other term, or to an error.\n    An an  example, terms denoting function applications are constructed by the\n    following [Opid]:\n% \\noindent \\\\* % [NCan NApply]\n\n% \\noindent \\\\* % We have [OpBindings (NCan NApply) = [0,0]].\n\n\n    The only restriction in defining [CanonicalOp] and [NonCanonicalOp] is\n    that the equality in these types should be decidable.\n    We will soon show the full-blown definition of\n    the [Opid]s of Nuprl.\n*)\n\n(* Howe's T_0(L) *)\nDefinition isprogram {p} (t : @NTerm p) := closed t # nt_wf t.\n\n(** %\\noindent \\\\*% Now, we will describe the [Opid]s of Nuprl and then describe some\nother useful definitions and lemmas about [NTerm]. *)\n\n\n(* begin hide *)\n\nDefinition isvalue_like {o} (t : @NTerm o) := iscan t [+] isexc t.\nDefinition is_can_or_exc {p} (t : @NTerm p) := iscan t [+] isexc t.\nDefinition isp_can_or_exc {p} (t : @NTerm p) := isprogram t # is_can_or_exc t.\n\nLemma is_can_or_exc_implies_isvalue_like {o} :\n  forall (t : @NTerm o),\n    is_can_or_exc t -> isvalue_like t.\nProof.\n  introv h.\n  unfold isvalue_like; unfold is_can_or_exc in h; sp.\nQed.\nHint Resolve is_can_or_exc_implies_isvalue_like : slow.\n\nLemma isp_can_or_exc_implies_is_program {p} :\n  forall t : @NTerm p, isp_can_or_exc t -> isprogram t.\nProof.\n  introv i; inversion i; sp.\nQed.\nHint Resolve isp_can_or_exc_implies_is_program : slow.\n\nLemma isexc_exc {o} :\n  forall (l : list (@BTerm o)),\n    isexc (oterm Exc l).\nProof. sp. Qed.\nHint Resolve isexc_exc.\n\nLemma iscan_can {o} :\n  forall c (l : list (@BTerm o)),\n    iscan (oterm (Can c) l).\nProof. sp. Qed.\nHint Resolve iscan_can.\n\nLemma isnoncan_noncan {o} :\n  forall nc (l : list (@BTerm o)),\n    isnoncan (oterm (NCan nc) l).\nProof. sp. Qed.\nHint Resolve isnoncan_noncan.\n\nLemma isabs_abs {o} :\n  forall abs (l : list (@BTerm o)),\n    isabs (oterm (Abs abs) l).\nProof. sp. Qed.\nHint Resolve isabs_abs.\n\nLemma noncan_not_is_can_or_exc {p} :\n  forall e : @NTerm p,\n    isnoncan e\n    -> is_can_or_exc e\n    -> False.\nProof.\n  introv Hisnc Hisv.\n  destruct e as [|?| o lbt]; allsimpl; cpx.\n  destruct o; cpx.\n  destruct Hisv as [Hisv|Hisv]; auto.\nQed.\nHint Resolve noncan_not_is_can_or_exc : slow.\n\nLemma isabs_not_is_can_or_exc {p} :\n  forall e : @NTerm p,\n    isabs e\n    -> is_can_or_exc e\n    -> False.\nProof.\n  introv Hisnc Hisv.\n  destruct e as [|?|o lbt]; allsimpl; cpx.\n  destruct o; cpx.\n  destruct Hisv as [Hisv|Hisv]; auto.\nQed.\nHint Resolve isabs_not_is_can_or_exc : slow.\n\nDefinition ispexc {p} (t : @NTerm p) := isexc t # isprogram t.\n\nLemma ispexc_implies_is_can_or_exc {p} :\n  forall t : @NTerm p, ispexc t -> is_can_or_exc t.\nProof.\n  introv i.\n  destruct i as [isp ise].\n  right; sp.\nQed.\n\nLemma isexc_exception {o} :\n  forall a e : @NTerm o, isexc (mk_exception a e).\nProof. sp. Qed.\nHint Resolve isexc_exception : slow.\n\nLemma is_can_or_exc_isexc {o} :\n  forall t : @NTerm o, isexc t -> is_can_or_exc t.\nProof. sp. Qed.\nHint Resolve is_can_or_exc_isexc : slow.\n\nLemma isvalue_like_can {o} :\n  forall t : @NTerm o, iscan t -> isvalue_like t.\nProof. sp. Qed.\nHint Resolve isvalue_like_can : slow.\n\nLemma isvalue_like_exc {o} :\n  forall t : @NTerm o, isexc t -> isvalue_like t.\nProof. sp. Qed.\nHint Resolve isvalue_like_exc : slow.\n\n(* end hide *)", "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.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.26536785337402036}}
{"text": "(* Contribution to the Coq Library   V6.3 (July 1999)                    *)\nRequire Import securite.\n\nLemma POinvprel3 :\n forall (l l0 : list C) (k k0 k1 k2 : K) (c c0 c1 c2 : C)\n   (d d0 d1 d2 d3 d4 d5 d6 d7 d8 d9 d10 d11 d12 d13 d14 d15 d16 d17 d18 d19\n    d20 : D),\n inv0\n   (ABSI (MBNaKab d7 d8 d9 k0) (MANbKabCaCb d4 d5 d6 k c c0)\n      (MABNaNbKeyK d d0 d1 d2 d3) l) ->\n inv1\n   (ABSI (MBNaKab d7 d8 d9 k0) (MANbKabCaCb d4 d5 d6 k c c0)\n      (MABNaNbKeyK d d0 d1 d2 d3) l) ->\n invP\n   (ABSI (MBNaKab d7 d8 d9 k0) (MANbKabCaCb d4 d5 d6 k c c0)\n      (MABNaNbKeyK d d0 d1 d2 d3) l) ->\n rel3\n   (ABSI (MBNaKab d7 d8 d9 k0) (MANbKabCaCb d4 d5 d6 k c c0)\n      (MABNaNbKeyK d d0 d1 d2 d3) l)\n   (ABSI (MBNaKab d18 d19 d20 k2) (MANbKabCaCb d15 d16 d17 k1 c1 c2)\n      (MABNaNbKeyK d10 d11 d12 d13 d14) l0) ->\n invP\n   (ABSI (MBNaKab d18 d19 d20 k2) (MANbKabCaCb d15 d16 d17 k1 c1 c2)\n      (MABNaNbKeyK d10 d11 d12 d13 d14) l0).\n\nProof.\ndo 32 intro.\nunfold inv0, invP, rel3 in |- *; intros know_c_c0_l Inv1 know_Kab and1.\nelim know_c_c0_l; intros know_c_l know_c0_l.\nelim and1; intros eq_l0 t1.\nclear know_c_c0_l Inv1 and1 t1.\nrewrite eq_l0.\nunfold quint in |- *.\napply D2.\nsimpl in |- *.\nrepeat apply C2 || apply C3 || apply C4.\napply\n equivncomp\n  with\n    (Encrypt\n       (quad (B2C (D2B d17)) (B2C (D2B d4)) (B2C (D2B d16)) (B2C (D2B Bid)))\n       (KeyX Bid) :: l ++ rngDDKKeyABminusKab).\napply AlreadyIn; apply E0; apply EP0; assumption.\nunfold quad in |- *.\nrepeat apply C2 || apply C3 || apply C4.\napply D1; assumption.\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\nQed.", "meta": {"author": "coq-contribs", "repo": "otway-rees", "sha": "7956542fbb559fcda240c6059919a95ae4c10590", "save_path": "github-repos/coq/coq-contribs-otway-rees", "path": "github-repos/coq/coq-contribs-otway-rees/otway-rees-7956542fbb559fcda240c6059919a95ae4c10590/invprel3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.26536784740240044}}
{"text": "Require Import FloydSeq.base2.\nRequire Import FloydSeq.client_lemmas.\nRequire Import CSplit.strong.\n\nImport LiftNotation.\nLocal Open Scope logic.\n\nLemma typed_true_nullptr:\n forall v t0 t t',\n   typed_true t0 (force_val (sem_cmp Ceq (tptr t) (tptr t') v (Vint Int.zero))) ->\n   v=nullval.\nProof.\n intros.\n simpl in H. rewrite !andb_false_r in H. simpl in H.\n unfold typed_true, force_val, sem_cmp_pp, strict_bool_val, nullval in *.\n destruct Archi.ptr64  eqn:Hp;\n destruct t0, v; inv H;\n unfold sem_cmp_pp, strict_bool_val in H1;\n try (clear i; rename i0 into i);\n pose proof (Int.eq_spec i Int.zero);\n destruct (Int.eq i Int.zero); inv H1; auto.\nQed.\n\n\nLemma typed_true_nullptr':\n  forall  {cs: compspecs} t0  t t' v,\n    typed_true t0 (eval_binop Cop.Oeq (tptr t) (tptr t') v nullval) -> v=nullval.\nProof.\n intros.\n simpl in H. unfold sem_binary_operation' in H.\n unfold tptr, typed_true, force_val, sem_cmp, Cop.classify_cmp, sem_cmp_pp, \n   typeconv, remove_attributes, change_attributes, strict_bool_val, nullval, Val.of_bool in *.\n   rewrite (proj2 (eqb_type_false (Tpointer t noattr) int_or_ptr_type)) in H\n     by (intro Hx; inv Hx).\n   rewrite (proj2 (eqb_type_false (Tpointer t' noattr) int_or_ptr_type)) in H\n     by (intro Hx; inv Hx).\n   simpl in H.\n destruct Archi.ptr64  eqn:Hp;\n destruct t0, v; inv H;\n try solve [revert H1; simple_if_tac; intro H1; inv H1].\n pose proof (Int64.eq_spec i0 Int64.zero);\n destruct (Int64.eq i0 Int64.zero); inv H1; auto.\n pose proof (Int.eq_spec i0 Int.zero);\n destruct (Int.eq i0 Int.zero); inv H1; auto.\nQed.\n\nLemma typed_true_Oeq_nullval:\n forall  {cs: compspecs}  v t t',\n   local (`(typed_true tint) (`(eval_binop Cop.Oeq (tptr t) (tptr t')) v `(nullval))) |--\n   local (`(eq nullval) v).\nProof.\nintros.\n intro rho; unfold local, lift1; unfold_lift.\n apply prop_derives; intro.\n unfold tptr in H; simpl in H. unfold sem_binary_operation' in H.\n simpl in H. rewrite !andb_false_r in H.\n destruct (v rho); inv H.\n unfold sem_cmp_pp, strict_bool_val, nullval in *.\n destruct Archi.ptr64  eqn:Hp; simpl in H1;\n try solve [inv H1];\n try solve [pose proof (Int64.eq_spec i Int64.zero);\n                destruct (Int64.eq i Int64.zero); inv H1; auto];\n try solve [pose proof (Int.eq_spec i Int.zero);\n                destruct (Int.eq i Int.zero); inv H1; auto].\nQed.\n\nDefinition  binary_operation_to_comparison (op: Cop.binary_operation) :=\n match op with\n | Cop.Oeq => Some (@eq Z)\n | Cop.One => Some Zne\n | Cop.Olt => Some Z.lt\n | Cop.Ole => Some Z.le\n | Cop.Ogt => Some Z.gt\n | Cop.Oge => Some Z.ge\n | _ => None\n end.\n\n(*\nLemma typed_true_binop_int:\n  forall op op' e1 e2 Espec  {cs: compspecs} Delta P Q R c Post,\n   binary_operation_to_comparison op = Some op' ->\n   typeof e1 = tint ->\n   typeof e2 = tint ->\n   (PROPx P (LOCALx (tc_env Delta :: Q) (SEPx R))) |--  tc_expr Delta e1 ->\n   (PROPx P (LOCALx (tc_env Delta :: Q) (SEPx R))) |-- tc_expr Delta e2 ->\n  @semax cs Espec Delta (PROPx P (LOCALx\n      (`op' (`force_signed_int (eval_expr e1)) (`force_signed_int (eval_expr e2))\n          :: Q) (SEPx R))) c Post ->\n  @semax cs Espec Delta (PROPx P (LOCALx\n      (`(typed_true\n          (typeof (Ebinop op e1 e2 tint)))\n          (eval_expr (Ebinop op e1 e2 tint)) :: Q) (SEPx R))) c Post.\nProof.\nintros.\neapply semax_pre; [clear H4 | apply H4].\neapply derives_trans with\n (tc_expr Delta e1 && (tc_expr Delta e2\n   && PROPx P (LOCALx (tc_environ Delta :: `(typed_true (typeof (Ebinop op e1 e2 tint)))(eval_expr (Ebinop op e1 e2 tint)) :: Q) (SEPx R)))).\nrewrite <- andp_assoc.\napply andp_right; auto.\ndo 2 rewrite <- insert_local.\nrewrite <- andp_assoc.\nrewrite (andp_comm (local _)).\nrewrite andp_assoc.\napply andp_left2.\nrewrite insert_local.\napply andp_right; auto.\nclear H2 H3.\n(*do 2 rewrite insert_local.*)\nunfold PROPx, LOCALx; intro rho; simpl.\nnormalize.\nautorewrite with norm1 norm2; normalize.\nrewrite <- andp_assoc.\napply andp_derives; auto.\neapply derives_trans.\napply andp_derives; apply typecheck_expr_sound; auto.\nnormalize. split; auto.\nrewrite H1,H0 in *.\nclear H5 H2 H0 H1.\ndestruct (eval_expr e1 rho); inv H6.\ndestruct (eval_expr e2 rho); inv H7.\nunfold force_signed_int, force_int.\nunfold typed_true, eval_binop in H4.\ndestruct op; inv H; simpl in H4.\npose proof (Int.eq_spec i i0); destruct (Int.eq i i0); subst; auto.\n contradiction H4; auto.\nunfold Zne.\npose proof (Int.eq_spec i i0); destruct (Int.eq i i0); subst; auto.\ncontradict H.\nrewrite <- (Int.repr_signed i).\nrewrite <- (Int.repr_signed i0).\nf_equal; auto.\nunfold Int.lt in H4.\ndestruct (zlt (Int.signed i) (Int.signed i0)); auto; contradict H4; auto.\nunfold Int.lt in H4.\ndestruct (zlt (Int.signed i0) (Int.signed i)); auto; try omega; contradict H4; auto.\nunfold Int.lt in H4.\ndestruct (zlt (Int.signed i0) (Int.signed i)); auto; try omega; contradict H4; auto.\nunfold Int.lt in H4.\ndestruct (zlt (Int.signed i) (Int.signed i0)); auto; try omega; contradict H4; auto.\nQed.\n*)\n\nDefinition  binary_operation_to_opp_comparison (op: Cop.binary_operation) :=\n match op with\n | Cop.Oeq => Some Zne\n | Cop.One => Some (@eq Z)\n | Cop.Olt => Some Z.ge\n | Cop.Ole => Some Z.gt\n | Cop.Ogt => Some Z.le\n | Cop.Oge => Some Z.lt\n | _ => None\n end.\n\n(*\nLemma typed_false_binop_int:\n  forall op op' e1 e2 Espec  {cs: compspecs} Delta P Q R c Post,\n   binary_operation_to_opp_comparison op = Some op' ->\n   typeof e1 = tint ->\n   typeof e2 = tint ->\n   (PROPx P (LOCALx (tc_environ Delta :: Q) (SEPx R))) |-- (tc_expr Delta e1) ->\n   (PROPx P (LOCALx (tc_environ Delta :: Q) (SEPx R))) |-- (tc_expr Delta e2) ->\n  @semax cs Espec Delta (PROPx P (LOCALx\n      (`op' (`force_signed_int (eval_expr e1)) (`force_signed_int (eval_expr e2))\n          :: Q) (SEPx R))) c Post ->\n  @semax cs Espec Delta (PROPx P (LOCALx\n      (`(typed_false\n          (typeof (Ebinop op e1 e2 tint)))\n          (eval_expr (Ebinop op e1 e2 tint)) :: Q) (SEPx R))) c Post.\nProof.\nintros.\neapply semax_pre; [clear H4 | apply H4].\neapply derives_trans with\n ( local (tc_environ Delta) && ((tc_expr Delta e1) && ( (tc_expr Delta e2)\n   && PROPx P (LOCALx (tc_environ Delta :: `(typed_false (typeof (Ebinop op e1 e2 tint)))(eval_expr (Ebinop op e1 e2 tint)) :: Q) (SEPx R))))).\napply andp_right.\nrewrite <- insert_local. apply andp_left1; auto.\nrewrite <- andp_assoc.\napply andp_right; auto.\ndo 2 rewrite <- insert_local.\nrewrite <- andp_assoc.\nrewrite (andp_comm (local _)).\nrewrite andp_assoc.\napply andp_left2.\nrewrite insert_local.\napply andp_right; auto.\nclear H2 H3.\nunfold PROPx, LOCALx; intro rho; simpl.\nunfold local,lift1 at 1.\napply derives_extract_prop; intro TCE.\neapply derives_trans.\napply andp_derives; [ apply typecheck_expr_sound; auto | ].\napply andp_derives; [ apply typecheck_expr_sound; auto | ].\napply derives_refl.\nnormalize. autorewrite with norm1 norm2; normalize.\napply andp_right; auto. apply prop_right.\nsplit; auto.\nclear H6 TCE.\nrewrite H0 in *; rewrite H1 in *.\nclear H0 H1 H4.\ndestruct (eval_expr e1 rho); inv H2.\ndestruct (eval_expr e2 rho); inv H3.\nunfold force_signed_int, force_int.\nunfold typed_true, eval_binop in H5.\ndestruct op; inv H; simpl in H5.\npose proof (Int.eq_spec i i0); destruct (Int.eq i i0); inv H5; auto.\nintro; apply H.\nrewrite <- (Int.repr_signed i).\nrewrite <- (Int.repr_signed i0).\nf_equal; auto.\npose proof (Int.eq_spec i i0); destruct (Int.eq i i0); inv H5; auto.\nunfold Int.lt in H5.\ndestruct (zlt (Int.signed i) (Int.signed i0)); inv H5; auto.\nunfold Int.lt in H5.\ndestruct (zlt (Int.signed i0) (Int.signed i)); inv H5; omega.\nunfold Int.lt in H5.\ndestruct (zlt (Int.signed i0) (Int.signed i)); inv H5; omega.\nunfold Int.lt in H5.\ndestruct (zlt (Int.signed i) (Int.signed i0)); inv H5; omega.\nQed.\n*)\n\nLemma typed_false_One_nullval:\n forall  {cs: compspecs}  v t t',\n   local (`(typed_false tint) (`(eval_binop Cop.One (tptr t) (tptr t')) v `(nullval))) |--\n    local (`(eq nullval) v).\nProof.\nintros.\n intro rho; unfold local, lift1; unfold_lift.\n apply prop_derives; intro.\n simpl in H. unfold sem_binary_operation' in H.\n simpl in H. rewrite !andb_false_r in H.\n unfold sem_cmp_pp, nullval in *.\n destruct Archi.ptr64 eqn:Hp;\n destruct (v rho); inv H.\n pose proof (Int64.eq_spec i Int64.zero).\n destruct (Int64.eq i Int64.zero); inv H1.\n reflexivity.\n pose proof (Int.eq_spec i Int.zero).\n destruct (Int.eq i Int.zero); inv H1.\n reflexivity.\nQed.\n\nLemma typed_true_One_nullval:\n forall  {cs: compspecs}  v t t',\n   local (`(typed_true tint) (`(eval_binop Cop.One (tptr t) (tptr t')) v `(nullval))) |--\n   local (`(ptr_neq nullval) v).\nProof.\nintros.\n intro rho; unfold local, lift1; unfold_lift.\n apply prop_derives; intro.\n simpl in H. unfold sem_binary_operation' in H.\n simpl in H. rewrite !andb_false_r in H.\n unfold sem_cmp_pp, ptr_neq, ptr_eq, nullval in *; simpl; intro.\n destruct (v rho); try contradiction.\n simpl in *.\n unfold typed_true, force_val, strict_bool_val in *.\n destruct Archi.ptr64 eqn:?; auto.\n destruct H0 as [? [? ?]].\n first [ pose proof (Int64.eq_spec Int64.zero i)\n        | pose proof (Int.eq_spec Int.zero i)];\n rewrite H1 in H3; \n subst; inv H.\nQed.\n\n\nLemma typed_false_Oeq_nullval:\n forall  {cs: compspecs} v t t',\n   local (`(typed_false tint) (`(eval_binop Cop.Oeq (tptr t) (tptr t')) v `(nullval))) |--\n   local (`(ptr_neq nullval) v).\nProof.\nintros. subst.\n unfold_lift; intro rho.  unfold local, lift1; apply prop_derives; intro.\n simpl in H. unfold sem_binary_operation' in H.\n simpl in H. rewrite !andb_false_r in H.\n intro. apply ptr_eq_e in H0. rewrite <- H0 in H.\n inv H.\nQed.\n\nLemma local_entail_at:\n  forall n S T (H: local (locald_denote S) |-- local (locald_denote T))\n    P Q R,\n    nth_error Q n = Some S ->\n    PROPx P (LOCALx Q (SEPx R)) |--\n    PROPx P (LOCALx (replace_nth n Q T) (SEPx R)).\nProof.\n intros.\n unfold PROPx, LOCALx; simpl; intro rho;  apply andp_derives; auto.\n apply andp_derives; auto.\n unfold local, lift1.\n specialize (H rho). unfold local,lift1 in H.\n revert Q H0; induction n; destruct Q; simpl; intros; inv H0.\n unfold_lift; repeat rewrite prop_and.\n apply andp_derives; auto.\n  unfold_lift; repeat rewrite prop_and.\n apply andp_derives; auto.\nQed.\n\nLemma local_entail_at_semax_0:\n  forall Espec {cs: compspecs}Delta P Q1 Q1' Q R c Post,\n   local (locald_denote Q1) |-- local (locald_denote Q1') ->\n   @semax cs Espec Delta (PROPx P (LOCALx (Q1'::Q) (SEPx R))) c Post  ->\n   @semax cs Espec Delta (PROPx P (LOCALx (Q1::Q) (SEPx R))) c Post.\nProof.\nintros.\neapply semax_pre0.\neapply (local_entail_at 0).\napply H. reflexivity.\nauto.\nQed.\n\n(*\nLtac simplify_typed_comparison :=\nmatch goal with\n| |- semax _ (PROPx _ (LOCALx (`(typed_true _) ?A :: _) _)) _ _ =>\n (eapply typed_true_binop_int;\n   [reflexivity | reflexivity | reflexivity\n   | try solve [go_lowerx; apply prop_right; auto ]\n   | try solve [go_lowerx; apply prop_right; auto ]\n   | ])\n ||\n  (let a := fresh \"a\" in set (a:=A); simpl in a; unfold a; clear a;\n   eapply local_entail_at_semax_0; [\n    first [ apply typed_true_Oeq_nullval\n           | apply typed_true_One_nullval\n           ]\n    |  ])\n| |- semax _ (PROPx _ (LOCALx (`(typed_false _) ?A :: _) _)) _ _ =>\n (eapply typed_false_binop_int;\n   [reflexivity | reflexivity | reflexivity\n   | try solve [go_lowerx; apply prop_right; auto ]\n   | try solve [go_lowerx; apply prop_right; auto ]\n   | ])\n ||\n  let a := fresh \"a\" in set (a:=A); simpl in a; unfold a; clear a;\n   eapply local_entail_at_semax_0; [\n    first [ apply typed_false_Oeq_nullval\n           | apply typed_false_One_nullval\n           ]\n    |  ]\n| |- _ => idtac\nend.\n*)\n\nDefinition compare_pp op p q :=\n   match p with\n            | Vptr b z =>\n               match q with\n               | Vptr b' z' => if eq_block b b'\n                              then Vint (if Ptrofs.cmpu op z z' then Int.one else Int.zero)\n                              else Vundef\n               | _ => Vundef\n               end\n             | _ => Vundef\n   end.\n\nLemma force_sem_cmp_pp:\n  forall op p q,\n  isptr p -> isptr q ->\n  force_val (sem_cmp_pp op p q) =\n   match op with\n   | Ceq => Vint (if eq_dec p q then Int.one else Int.zero)\n   | Cne => Vint (if eq_dec p q then Int.zero else Int.one)\n   | _ => compare_pp op p q\n   end.\nProof.\nintros.\ndestruct p; try contradiction.\ndestruct q; try contradiction.\nclear.\nunfold sem_cmp_pp, compare_pp, Ptrofs.cmpu, Val.cmplu_bool.\ndestruct Archi.ptr64 eqn:Hp.\ndestruct op; simpl; auto.\nif_tac. if_tac. inv H0. rewrite Ptrofs.eq_true; reflexivity.\nrewrite Ptrofs.eq_false by congruence; reflexivity.\nif_tac. congruence. reflexivity.\nif_tac. if_tac. inv H0. rewrite Ptrofs.eq_true by auto. reflexivity.\nrewrite Ptrofs.eq_false by congruence; reflexivity.\nrewrite if_false by congruence. reflexivity.\nif_tac; [destruct (Ptrofs.ltu i i0); reflexivity | reflexivity].\nif_tac; [destruct (Ptrofs.ltu i0 i); reflexivity | reflexivity].\nif_tac; [destruct (Ptrofs.ltu i0 i); reflexivity | reflexivity].\nif_tac; [destruct (Ptrofs.ltu i i0); reflexivity | reflexivity].\ndestruct op; simpl; auto; rewrite Hp.\nif_tac. if_tac. inv H0. rewrite Ptrofs.eq_true; reflexivity.\nrewrite Ptrofs.eq_false by congruence; reflexivity.\nif_tac. congruence. reflexivity.\nif_tac. if_tac. inv H0. rewrite Ptrofs.eq_true by auto. reflexivity.\nrewrite Ptrofs.eq_false by congruence; reflexivity.\nrewrite if_false by congruence. reflexivity.\nif_tac; [destruct (Ptrofs.ltu i i0); reflexivity | reflexivity].\nif_tac; [destruct (Ptrofs.ltu i0 i); reflexivity | reflexivity].\nif_tac; [destruct (Ptrofs.ltu i0 i); reflexivity | reflexivity].\nif_tac; [destruct (Ptrofs.ltu i i0); reflexivity | reflexivity].\nQed.\n\nHint Rewrite force_sem_cmp_pp using (now auto) : norm.\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/floyd-seq/compare_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819874558604, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.265328450470813}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import x448.\nRequire Import stdpp.list.\nRequire Import ZArith.\nRequire Import compcert.lib.Coqlib.\nRequire Import list_int_functions.\nRequire Import Verif_gf_cpy.\n\nInstance CompSpecs : compspecs. Proof. make_compspecs prog. Defined.\nDefinition Vprog : varspecs.  mk_varspecs prog. Defined.\n\nDefinition t_gf := Tstruct __257 noattr.\n\nLocal Open Scope Z.\n\nDefinition gf_mul_spec : ident * funspec :=\n    DECLARE _gf_mul\n    WITH \n        c: val, shc : share, contents_c : list val,\n        a: val, sha : share, contents_a : list Z,\n        b: val, shb : share, contents_b : list Z,\n        gv : globals\n    PRE [ tptr t_gf, tptr t_gf, tptr t_gf ]\n        PROP   (writable_share shc;\n                readable_share sha;\n                readable_share shb;\n                Zlength contents_a = 16;\n                Zlength contents_b = 16;\n                Zlength contents_c = 16)\n        PARAMS (c ; a ; b) GLOBALS (gv)\n        SEP    (field_at shc t_gf (DOT _limb) contents_c c;\n                field_at sha t_gf (DOT _limb) (map Vint (map Int.repr contents_a)) a;\n                field_at shb t_gf (DOT _limb) (map Vint (map Int.repr contents_b)) b)\n    POST [ tvoid ]\n        PROP   ()\n        RETURN ()\n        SEP    (field_at shc t_gf (DOT _limb) (map Vint \n                (map Int.repr (int_to_list ((list_to_int contents_a) * (list_to_int contents_b))))) c;\n                field_at sha t_gf (DOT _limb) (map Vint (map Int.repr contents_a)) a;\n                field_at shb t_gf (DOT _limb) (map Vint (map Int.repr contents_b)) b).\n\nDefinition Gprog : funspecs := ltac:(with_library prog [ gf_mul_spec; gf_cpy_spec ]).\n\nLemma body_gf_cpy : semax_body Vprog Gprog f_gf_mul gf_mul_spec.\nProof.\n    start_function.\n    Search \"field_address\".\n    forward_call (v_aa, Tsh, (field_address t_gf (DOT _limb) v_aa)).\nAdmitted.", "meta": {"author": "david-hrnndz", "repo": "verif-x448", "sha": "19374b39c86f1644347b50a017a26985d2196f4b", "save_path": "github-repos/coq/david-hrnndz-verif-x448", "path": "github-repos/coq/david-hrnndz-verif-x448/verif-x448-19374b39c86f1644347b50a017a26985d2196f4b/Verif_gf_mul.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.26532844432489366}}
{"text": "(* En este archivo se demuestra la corrección de la acción grantAuto*)\nRequire Export Exec.\nRequire Export Implementacion.\nRequire Export AuxFunsCorrect.\nRequire Export ListAuxFuns.\nRequire Import Classical.\nRequire Import Estado.\nRequire Import DefBasicas.\nRequire Import EqTheorems.\nRequire Import Semantica.\nRequire Import RuntimePermissions.\nRequire Import Operaciones.\nRequire Import ErrorManagement.\nRequire Import Maps.\nRequire Import Tacticas.\nRequire Import ValidStateLemmas.\n\nSection GrantAuto.\n\n\nLemma postGrantAutoCorrect : forall (s:System) (a:idApp) (p:Perm), (pre (grantAuto p a) s) -> validstate s -> post_grantAuto p a s (grantAuto_post p a s).\nProof.\n    intros.\n    unfold post_grantAuto.\n    split. simpl; auto.\n    simpl in H.\n    unfold pre_grantAuto in H;simpl in H.\n    destruct H.\n\n    split.\n  - destruct H .\n    destruct H.\n    assert (In a (apps (state s)) \\/ (exists sysapp:SysImgApp, In sysapp (systemImage (environment s)) /\\ idSI sysapp = a)).\n    destruct H.\n    left.\n    apply (ifManifestThenInApps s H0 a x);auto.\n    right.\n    destruct H.\n    destruct_conj H.\n    exists x0;auto.\n    assert (exists v, map_apply idApp_eq (perms (state s)) a = Value idApp v).\n    apply (ifInAppsOrSysAppThenPerms);auto.\n    destruct H4.\n    unfold grantPerm.\n    unfold grantAuto_post;unfold grantPermission;simpl.\n    rewrite H4.\n    split;intros.\n    elim (classic (a=a'));intros.\n    \n    exists (p::x0).\n    split.\n    rewrite H6.\n    rewrite<- (addAndApply idApp_eq a' (p::x0) (perms (state s))).\n    auto.\n    rewrite H6 in H4.\n    rewrite H4 in H5.\n    assert (x0=lPerm).\n    inversion H5.\n    auto.\n    intros.\n    rewrite H7.\n    apply in_cons.\n    auto.\n\n    exists lPerm.\n    split.\n    rewrite overrideNotEq; auto.\n    intros.\n    auto.\n\n    split;intros.\n    elim (classic (a=a'));intro.\n    \n    \n    exists x0.\n    split.\n    rewrite H6 in H4.\n    auto.\n    intros.\n    split;auto.\n    rewrite H6 in H5.\n    rewrite <-(addAndApply idApp_eq a' (p::x0) (perms (state s))) in H5.\n    inversion H5.\n    rewrite <-H10 in H7.\n    inversion H7.\n    auto.\n    contradiction.\n    \n    exists lPerm'.\n    rewrite overrideNotEq in H5.\n    split;auto.\n    intros;contradiction.\n    auto.\n    split.\n    exists (p::x0).\n    split.\n    symmetry.\n    apply addAndApply.\n    apply in_eq.\n    apply addPreservesCorrectness.\n    apply permsCorrect;auto.\n  - unfold grantAuto_post. simpl. repeat split; auto.\nQed.\n\nLemma existsManifest : forall (a: idApp) (s: System) (p: Perm),\n  negb (InBool Perm Perm_eq p (permsInUse a s)) = false ->\n    exists m : Manifest, isManifestOfApp a m s /\\ In p (use m).\nProof.\n  intros a s p H.\n  rewrite negb_false_iff in H.\n  unfold InBool in H.\n  rewrite existsb_exists in H.\n  destruct H as [perm H].\n  destruct H as [H H0].\n  unfold permsInUse in H.\n\n  unfold isManifestOfApp.\n  case_eq (map_apply idApp_eq (manifest (environment s)) a); intros m H1; rewrite H1 in *.\n  exists m.\n  destruct Perm_eq in H0.\n  rewrite e.\n  split;auto.\n  discriminate H0.\n\n  case_eq ((map (fun sysapp : SysImgApp => use (manifestSI sysapp)) (filter (fun sysapp : SysImgApp => if idApp_eq a (idSI sysapp) then true else false) (systemImage (environment s)))));intros; rewrite H2 in *;simpl in H.\n  destruct H.\n  assert (In l (map (fun sysapp : SysImgApp => use (manifestSI sysapp)) (filter (fun sysapp : SysImgApp => if idApp_eq a (idSI sysapp) then true else false) (systemImage (environment s))))).\n  rewrite H2.\n  apply in_eq.\n  rewrite in_map_iff in H3.\n  destruct H3 as [sysImg H3].\n  destruct H3.\n  exists (manifestSI sysImg).\n  split.\n  right.\n  exists sysImg.\n  rewrite filter_In in H4.\n  destruct H4.\n  destruct idApp_eq in H5.\n  rewrite e;auto.\n  discriminate H5.\n  destruct Perm_eq in H0.\n  rewrite e.\n  rewrite H3 in *.\n  auto.\n  discriminate H0.\nQed.\n\nLemma notPreGrantAutoThenError : forall (s:System) (a:idApp) (p:Perm), ~(pre (grantAuto p a) s) -> validstate s -> exists ec : ErrorCode, response (step s (grantAuto p a)) = error ec /\\ ErrorMsg s (grantAuto p a) ec /\\ s = system (step s (grantAuto p a)).\nProof.\n    intros.\n    simpl.\n    simpl in H.\n    unfold pre_grantAuto in H.\n    unfold grantAuto_safe.\n    unfold grantAuto_pre.\n    \n    case_eq (negb (InBool Perm Perm_eq p (permsInUse a s)));intros.\n    exists perm_not_in_use.\n    split;auto.\n    split;auto.\n    rewrite negb_true_iff in H1.\n    invertBool H1.\n    intro.\n    apply H1.\n    destruct H2.\n    unfold InBool.\n    rewrite existsb_exists.\n    exists p.\n    unfold permsInUse.\n    destruct H2.\n    rewrite H2.\n    destruct Perm_eq;auto.\n\n\n    case_eq (negb (InBool Perm Perm_eq p (getAllPerms s)));intros.\n    exists no_such_perm.\n    split;auto.\n    split;auto.\n    rewrite negb_true_iff in H2.\n    invertBool H2.\n    intro;apply H2.\n    unfold getAllPerms.\n    unfold InBool.\n    rewrite existsb_exists.\n    exists p.\n    rewrite in_app_iff.\n    split.\n    destruct H3.\n    left.\n    apply isSysPermCorrect;auto.\n    right.\n    apply inUsrDefPermsIff;auto.\n    destruct Perm_eq;auto.\n\n    case_eq (InBool Perm Perm_eq p (grantedPermsForApp a s));intros.\n    exists perm_already_granted.\n    split;auto.\n    split;auto.\n    unfold InBool in H3.\n    rewrite existsb_exists in H3.\n    destruct H3.\n    destruct H3.\n    unfold grantedPermsForApp in H3.\n    case_eq (map_apply idApp_eq (perms (state s)) a);intros; rewrite H5 in H3.\n    exists l.\n    destruct Perm_eq in H4.\n    rewrite e;auto.\n    discriminate H4.\n    inversion H3.\n    case_eq ((if permLevel_eq (pl p) dangerous then false else true));intros.\n    exists perm_not_dangerous.\n    split;auto.\n    split;auto.\n    destruct permLevel_eq in H4.\n    discriminate H4.\n    auto.\n\n    case_eq (negb (isSomethingBool idGrp (maybeGrp p))); intros.\n    exists perm_not_grouped. simpl.\n    split; auto. split; auto.\n    rewrite negb_true_iff in H5.\n    unfold isSomethingBool in H5.\n    destruct (maybeGrp p); auto. inversion H5.\n\n    case_eq (negb (groupIsGranted a p s)); intros.\n    simpl. exists cannot_auto_grant. split; auto.\n    \n    rewrite negb_true_iff in H6.\n    rewrite negb_false_iff in H5.\n    unfold isSomethingBool in H5.\n\n    case_eq (maybeGrp p);intros.\n  - unfold groupIsGranted in H6.\n    clear H5. rewrite H7 in H6.\n    case_eq (map_apply idApp_eq (grantedPermGroups (state s)) a); intros.\n -- rewrite H5 in H6. split; auto.\n    exists i, l. repeat split;auto.\n    unfold not. intros.\n    clear H5.\n    induction l. inversion H8.\n    simpl in H6.\n    destruct (idGrp_eq i a0).\n    inversion H6.\n    simpl in H6, H8.\n    destruct H8.\n    symmetry in H5. contradiction.\n    apply IHl; auto.\n -- apply existsManifest in H1.\n    destruct H1 as [m [H1 _]].\n    assert (vs:= H0).\n    destructVS H0.\n    destructSC statesConsistencyVS a.\n    destruct grantedPermGroupsSC.\n    assert (exists l : list idGrp,\n       map_apply idApp_eq (grantedPermGroups (state s)) a = Value idApp l).\n    destruct H1. clear mfstSC certSC defPermsSC permsSC.\n    apply ifManifestThenInApps in H1; auto.\n    apply H0. right. destruct H1 as [sysImg [H9 [H10 H11]]].\n    exists sysImg; auto.\n    destruct H9. rewrite H5 in H9. inversion H9.\n  - unfold groupIsGranted in H6. rewrite H7 in H5.\n    inversion H5.\n  - destruct H.\n    split.\n    apply existsManifest; auto.\n\n    split.\n    rewrite negb_false_iff in H2.\n    unfold InBool in H2.\n    rewrite existsb_exists in H2.\n    destruct H2.\n    destruct H.\n    destruct Perm_eq in H2.\n    rewrite e.\n    unfold getAllPerms in H.\n    rewrite in_app_iff in H.\n    destruct H.\n    left.\n    apply isSysPermCorrect;auto.\n    right.\n    apply inUsrDefPermsIff;auto.\n    discriminate H2.\n    split.\n    invertBool H3.\n    intro;apply H3.\n    unfold InBool.\n    rewrite existsb_exists.\n    exists p.\n    destruct H.\n    destruct H.\n    unfold grantedPermsForApp.\n    rewrite H.\n    destruct Perm_eq;auto.\n    split.\n    destruct permLevel_eq in H4.\n    auto.\n    discriminate H4.\n    rewrite negb_false_iff in H5.\n    rewrite negb_false_iff in H6.\n    unfold isSomethingBool in H5.\n    case_eq (maybeGrp p); intros.\n -- unfold groupIsGranted in H6.\n    rewrite H in H6.\n    case_eq (map_apply idApp_eq (grantedPermGroups (state s)) a);intros.\n    exists i, l. repeat split;auto.\n    rewrite H7 in H6.\n    unfold InBool in H6.\n    rewrite existsb_exists in H6.\n    destruct H6 as [i' [H6 H8]].\n    destruct (idGrp_eq i i').\n    rewrite e. auto.\n    inversion H8.\n    rewrite H7 in H6. inversion H6.\n -- rewrite H in H5. inversion H5.\nQed.\n\n\nLemma grantAutoIsSound : forall (s:System) (a:idApp) (p:Perm),\n        validstate s -> exec s (grantAuto p a) (system (step s (grantAuto p a))) (response (step s (grantAuto p a))).\nProof.\n    intros.\n    unfold exec.\n    split.\n    auto.\n    elim (classic (pre (grantAuto p a) s));intro.\n    left.\n    assert(grantAuto_pre p a s = None).\n    unfold grantAuto_pre.\n    destruct H0.\n\n    assert (InBool Perm Perm_eq p (permsInUse a s) = true).\n    unfold InBool.\n    rewrite existsb_exists.\n    exists p.\n    split.\n    destruct H0.\n    destruct H0.\n    unfold permsInUse.\n    destruct H0.\n    rewrite H0.\n    auto.\n    case_eq (map_apply idApp_eq (manifest (environment s)) a);intros.\n    apply ifManifestThenInApps in H3;auto.\n    destruct H0.\n    assert (~(In a (apps (state s)) /\\ In x0 (systemImage (environment s)) /\\ idSI x0 = a)).\n    apply sysAppInApps;auto.\n    destruct_conj H0.\n    destruct H4;auto.\n    destruct H0.\n    destruct_conj H0.\n    assert (In x0 (filter (fun sysapp : SysImgApp => if idApp_eq a (idSI sysapp) then true else false) (systemImage (environment s)))).\n    rewrite filter_In.\n    rewrite H0.\n    destruct idApp_eq;auto.\n    remember (fun sysapp : SysImgApp => use (manifestSI sysapp)) as theFun.\n    remember (filter (fun sysapp : SysImgApp => if idApp_eq a (idSI sysapp) then true else false) (systemImage (environment s))) as theList.\n    assert ((hd nil (map theFun theList)) = theFun (hd defaultSysApp theList )).\n    apply ifNotNilHdMap.\n    apply inNotNilExists.\n    exists x0;auto.\n    rewrite H7.\n    rewrite HeqtheFun.\n    assert ((hd defaultSysApp theList)=x0).\n    rewrite HeqtheList in H5.\n    assert (exists x0, In x0 (filter (fun sysapp : SysImgApp => if idApp_eq a (idSI sysapp) then true else false) (systemImage (environment s)))).\n    exists x0;auto.\n    apply ifExistsFilter with (dflt:=defaultSysApp) in H8.\n    rewrite HeqtheList.\n    remember (hd defaultSysApp (filter (fun sysapp : SysImgApp => if idApp_eq a (idSI sysapp) then true else false) (systemImage (environment s)))) as theHead.\n    destruct H8.\n    apply (notDupSysAppVS s);auto.\n    rewrite H0 in *.\n    destruct idApp_eq in H9;auto.\n    discriminate H9.\n\n    rewrite H8;rewrite H6;auto.\n\n\n\n\n    destruct Perm_eq.\n    auto.\n    auto.\n    rewrite H2.\n    assert (negb true=false).\n    rewrite negb_false_iff;auto.\n    rewrite H3.\n\n    assert (InBool Perm Perm_eq p (getAllPerms s) = true).\n    unfold InBool.\n    rewrite existsb_exists.\n    exists p.\n    split.\n    destruct H1.\n    unfold getAllPerms.\n    apply in_app_iff.\n    destruct H1.\n    left.\n    apply isSysPermCorrect;auto.\n    right.\n    unfold usrDefPerms.\n    apply in_concat.\n    unfold usrDefPerm in H1.\n    destruct H1.\n    destruct H1.\n    destruct H1.\n    destruct H1.\n    exists x0.\n    split.\n    apply in_app_iff.\n    left.\n    apply inGetValuesBack.\n    exists (map_apply idApp_eq (defPerms (environment s)) x).\n    split.\n    apply in_map_iff.\n    exists x.\n    split.\n    auto.\n    apply (ifDefPermsThenInApps s H x x0);auto.\n    auto.\n    auto.\n    destruct H1.\n    destruct H1.\n    exists (defPermsSI x).\n    split.\n    apply in_app_iff.\n    right.\n    apply in_map_iff.\n    exists x.\n    split;auto.\n    auto.\n    destruct Perm_eq.\n    auto.\n    destruct n;auto.\n    rewrite H4.\n    assert (negb true=false).\n    rewrite negb_false_iff;auto.\n    rewrite H3.\n\n    assert (InBool Perm Perm_eq p (grantedPermsForApp a s) <> true).\n    unfold InBool.\n    unfold not;intros.\n    rewrite existsb_exists in H6.\n    destruct H6.\n    destruct H6.\n    destruct H1.\n    apply H8.\n    unfold grantedPermsForApp in H6.\n    case_eq (map_apply idApp_eq (perms (state s)) a);intros; rewrite H9 in H6.\n    exists l.\n    destruct Perm_eq in H7.\n    rewrite<- e in H6.\n    split;auto.\n    discriminate H7.\n    destruct H6.\n    rewrite not_true_iff_false in H6.\n    rewrite H6.\n    destruct_conj H1.\n    destruct permLevel_eq.\n    destruct H10 as [g [lGroup [H10 H11]]].\n    rewrite H10. simpl.\n    destruct H11 as [H11 H12].\n    unfold groupIsGranted.\n    rewrite H10, H11.\n    case_eq (negb (InBool idGrp idGrp_eq g lGroup)); intros.\n    rewrite negb_true_iff in H9.\n    clear H11.\n    induction lGroup. inversion H12.\n    simpl in H12, H9.\n    destruct (idGrp_eq g a0).\n    inversion H9.\n    destruct H12.\n    symmetry in H11. contradiction.\n    simpl in H9. apply IHlGroup; auto.\n    auto.\n    contradiction.\n    unfold step;simpl.\n    unfold grantAuto_safe;simpl.\n    rewrite H1;simpl.\n    split;auto. split; auto.\n    apply postGrantAutoCorrect;auto.\n    right.\n    apply (notPreGrantAutoThenError);auto.\nQed.\nEnd GrantAuto.\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/GrantAutoIsSound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2653185916608806}}
{"text": "Require Import String.\nRequire Import Functors.\nRequire Import MonadLib.\nRequire Import Names.\nRequire Import EffPure.\nRequire Import EffState.\nRequire Import Ref.\nRequire Import ESoundS.\n\nOpen Scope string_scope.\n\nSection Test_Section.\n\n  Definition D := UnitType :+: RefType.\n\n  Definition E := RefE.\n\n  Definition V := StuckValue :+: LocValue :+: UnitValue.\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 `{State_ME : StateM ME (list (Value V))}.\n  Context {Fail_ME : FailMonad ME}.\n\n  Definition WFV := (WFValue_Unit D V _) ::+:: (WFValue_Loc D V _).\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\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  Lemma eval_Sound :\n    forall (Sigma : Env (DType D)) (e : Exp E) (T : DType D) (env : Env (Value V)),\n      WF_Environment D V _ WFV Sigma env Sigma ->\n      typeof D E MT (proj1_sig e) = return_ T ->\n      exists v : Value V,\n        exists env' : Env (Value V),\n          exists Sigma' : Env (DType D),\n            (put env) >> evalM V E ME (proj1_sig e) =\n            put env' >> return_ (M := ME) v /\\\n            WFValueC D V _ WFV Sigma' v T.\n  Proof.\n    intros; eapply eval_State_Sound with (WFVM' := WFVM);\n      eauto 10 with typeclass_instances.\n    eauto 15 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    simpl; eauto.\n  Qed.\n\n  Eval compute in (\"Soundness for 'References' 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_R.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.26531858614732956}}
{"text": "Require Import CoqlibC.\nRequire Import Simulation.\nRequire Import LinkingC.\nRequire Import Skeleton.\nRequire Import Values.\nRequire Import JMeq.\nRequire Import Smallstep.\nRequire Import Integers.\nRequire Import Events.\n\nRequire Import Skeleton ModSem Mod Sem.\nRequire Import SimSymb SimMem SimMod SimModSem SimProg (* SimLoad *) SimProg.\nRequire Import SemProps Ord.\nRequire Import Sound Preservation.\nRequire Import Memory.\n\nSet Implicit Arguments.\n\n\n\n\nSection ADQSOUND.\n\n  Context `{SM: SimMem.class}.\n  Context {SS: SimSymb.class SM}.\n  Context `{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  Hypothesis (WFSKSRC: forall md (IN: In md p_src), <<WF: Sk.wf md>>).\n  Hypothesis (WFSKTGT: forall md (IN: In md p_tgt), <<WF: Sk.wf md>>).\n\n  Variable sk_link_src sk_link_tgt: Sk.t.\n  Hypothesis LINKSRC: (link_sk p_src) = Some sk_link_src.\n  Hypothesis LINKTGT: (link_sk p_tgt) = Some sk_link_tgt.\n  Let sem_src := Sem.sem p_src.\n  Let sem_tgt := Sem.sem p_tgt.\n\n  Let skenv_link_src := (Sk.load_skenv sk_link_src).\n  Let skenv_link_tgt := (Sk.load_skenv sk_link_tgt).\n\n  Variable ss_link: SimSymb.t.\n  Hypothesis (SIMSKENV: exists sm, SimSymb.sim_skenv sm ss_link skenv_link_src skenv_link_tgt).\n\n  Hypothesis INCLSRC: forall mp (IN: In mp pp), SkEnv.includes skenv_link_src (Mod.sk mp.(ModPair.src)).\n  Hypothesis INCLTGT: forall mp (IN: In mp pp), SkEnv.includes skenv_link_tgt (Mod.sk mp.(ModPair.tgt)).\n  Hypothesis SSLE: forall mp (IN: In mp pp), SimSymb.le mp.(ModPair.ss) ss_link.\n\n  Let WFSKLINKSRC: Sk.wf sk_link_src. eapply link_list_preserves_wf_sk; et. Qed.\n  Let WFSKLINKTGT: Sk.wf sk_link_tgt. eapply link_list_preserves_wf_sk; et. Qed.\n\n  (* Let ge: Ge.t := sem_src.(Smallstep.globalenv). *)\n\n  Inductive sound_ge (su0: Sound.t) (m0: mem): Prop :=\n  | sound_ge_intro\n      (GE: Forall (fun ms => su0.(Sound.skenv) m0 ms.(ModSem.skenv) /\\ su0.(Sound.skenv) m0 ms.(ModSem.skenv_link))\n                  (fst sem_src.(Smallstep.globalenv)))\n  .\n\n  Lemma lepriv_preserves_sound_ge\n        m0 su0 su1\n        (GE: sound_ge su0 m0)\n        (LE: Sound.lepriv su0 su1):\n      <<GE: sound_ge su1 m0>>.\n  Proof.\n    inv GE. econs; eauto. rewrite Forall_forall in *. ii. split; eapply Sound.skenv_lepriv; try apply GE0; eauto.\n  Qed.\n\n  Lemma hle_preserves_sound_ge\n        m0 su0 su1\n        (WF: Sound.wf su0)\n        (GE: sound_ge su0 m0)\n        (LE: Sound.hle su0 su1):\n      <<GE: sound_ge su1 m0>>.\n  Proof.\n    eapply lepriv_preserves_sound_ge; eauto. eapply Sound.hle_lepriv; et.\n  Qed.\n\n  Lemma mle_preserves_sound_ge\n        m0 m1 su0\n        (GE: sound_ge su0 m0)\n        (LE: Sound.mle su0 m0 m1):\n      <<GE: sound_ge su0 m1>>.\n  Proof.\n    inv GE. econs; eauto. rewrite Forall_forall in *. ii. split; eapply Sound.skenv_mle; try apply GE0; eauto.\n  Qed.\n\n  (* stack can go preservation when su0 is given *)\n  Inductive sound_stack (args: Args.t): list Frame.t -> Prop :=\n  | sound_stack_nil\n      (EXSU: exists su_ex, Sound.args su_ex args /\\ sound_ge su_ex (Args.get_m args)):\n      sound_stack args []\n  | sound_stack_cons\n      args_tail tail ms lst0\n      (TL: sound_stack args_tail tail)\n      (FORALLSU: forall su0\n          (SUARGS: Sound.args su0 args_tail)\n          (SUGE: sound_ge su0 (Args.get_m args_tail)),\n          (<<HD: forall\n                 sound_state_all\n                 (PRSV: local_preservation_noguarantee ms sound_state_all),\n                 <<SUST: sound_state_all su0 (Args.get_m args_tail) lst0>>>>)\n          /\\\n          (<<K: forall\n                 sound_state_all\n                 (PRSV: local_preservation_noguarantee ms sound_state_all),\n                 (* (<<SUST: sound_state_all su0 args.(Args.get_m) lst0>>) *)\n                 (* /\\ *)\n                 exists su_gr,\n                   (<<ARGS: Sound.args su_gr args>>) /\\\n                   (<<LE: Sound.lepriv su0 su_gr>>) /\\\n                   (<<K: forall retv lst1 su_ret\n                       (LE: Sound.hle su_gr su_ret)\n                       (SURETV: Sound.retv su_ret retv)\n                       (MLE: Sound.mle su_gr (Args.get_m args) (Retv.get_m retv))\n                       (AFTER: ms.(ModSem.after_external) lst0 retv lst1),\n                       (* sound_state_all su0 args.(Args.get_m) lst1>>) *)\n                       sound_state_all su0 (Args.get_m args_tail) lst1>>)\n             >>)\n          /\\\n          (<<MLE: Sound.mle su0 (Args.get_m args_tail) (Args.get_m args)>>)\n      )\n      (EXSU: exists su_ex, Sound.args su_ex args_tail /\\ sound_ge su_ex (Args.get_m args_tail))\n      (EX: exists sound_state_ex, local_preservation ms sound_state_ex):\n      sound_stack args ((Frame.mk ms lst0) :: tail).\n\n  Inductive sound_state: state -> Prop :=\n  | sound_state_normal\n      args_tail tail ms lst0 m_arg\n      (TL: sound_stack args_tail tail)\n      (EXSU: exists su_ex, Sound.args su_ex args_tail /\\ sound_ge su_ex m_arg)\n      (FORALLSU: forall su0\n          (SUARGS: Sound.args su0 args_tail)\n          (SUGE: sound_ge su0 (Args.get_m args_tail)),\n          (<<HD: forall\n              sound_state_all\n              (PRSV: local_preservation_noguarantee ms sound_state_all),\n              <<SUST: sound_state_all su0 m_arg lst0>>>>))\n      (EX: exists sound_state_ex, local_preservation ms sound_state_ex)\n      (ABCD: (Args.get_m args_tail) = m_arg)\n    :\n      sound_state (State ((Frame.mk ms lst0) :: tail))\n  | sound_state_call\n      m_tail frs args\n      (* (ARGS: Sound.args su0 args) *)\n      (STK: sound_stack args frs)\n      (* (MLE: Sound.mle su0 m_tail args.(Args.get_m)) *)\n      (EQ: (Args.get_m args) = m_tail)\n      (EXSU: exists su_ex, Sound.args su_ex args /\\ sound_ge su_ex m_tail):\n      sound_state (Callstate args frs).\n\n  Lemma sound_init\n        st0\n        (INIT: sem_src.(Smallstep.initial_state) st0):\n    <<SU: sound_state st0>>.\n  Proof.\n    inv INIT. clarify. clear skenv_link_tgt p_tgt skenv_link_tgt sem_tgt LINKTGT INCLTGT WFSKTGT SIMSKENV.\n    hexploit Sound.init_spec; eauto. i; des. esplits; eauto.\n    assert(WFSKE: SkEnv.wf (Sk.load_skenv sk_link_src)).\n    { eapply SkEnv.load_skenv_wf; et. }\n    assert(GE: sound_ge su_init m_init).\n    { econs. rewrite Forall_forall. intros ? IN. ss. des_ifs. u in IN.\n      rewrite in_map_iff in IN. des; ss; clarify.\n      + s. split; try eapply Sound.system_skenv; eauto.\n      + assert(INCL: SkEnv.includes (Sk.load_skenv sk_link_src) (Mod.sk x0)).\n        { unfold p_src in IN0. unfold ProgPair.src in *. rewrite in_map_iff in IN0. des. clarify. eapply INCLSRC; et. }\n        split; ss.\n        * eapply Sound.skenv_project; eauto.\n          { eapply link_load_skenv_wf_mem; et. }\n          rewrite <- Mod.get_modsem_skenv_spec; ss. eapply SkEnv.project_impl_spec; et.\n        * rewrite Mod.get_modsem_skenv_link_spec. ss.\n    }\n    econs; eauto. econs; eauto.\n    (* - eapply Sound.greatest_adq; eauto. *)\n    (* - econs; eauto. *)\n    (* - eapply vle_preserves_sound_ge; eauto. *)\n    (*   eapply Sound.greatest_adq; eauto. *)\n  Unshelve.\n    all: ss.\n  Qed.\n\n  Lemma sound_progress\n        st0 tr st1\n        (SUST: sound_state st0)\n        (STEP: Step sem_src st0 tr st1):\n      <<SUST: sound_state st1>>.\n  Proof.\n    inv STEP.\n    - (* CALL *)\n      inv SUST. ss. des. exploit FORALLSU; eauto. { eapply local_preservation_noguarantee_weak; eauto. } intro T; des.\n      inv EX. exploit CALL; eauto. i; des. esplits; eauto. econs; eauto; cycle 1.\n      + esplits; eauto. eapply lepriv_preserves_sound_ge; eauto.\n        { eapply mle_preserves_sound_ge; eauto. }\n      + econs; eauto; cycle 1.\n        { esplits; eauto. econs; eauto. }\n        ii. esplits; eauto.\n        * ii. exploit FORALLSU; try apply SUARGS; eauto.\n        * ii. exploit FORALLSU; try apply SUARGS; eauto. intro U; des.\n          inv PRSV. exploit CALL0; eauto. i; des. esplits; eauto. ii. eapply K0; eauto.\n        * exploit FORALLSU; eauto.\n          { eapply local_preservation_noguarantee_weak; eauto. econs; eauto. }\n          i; des. exploit CALL; eauto. i; des. ss.\n    - (* INIT *)\n      inv SUST. ss. des_ifs. esplits; eauto. econs; eauto.\n      + ii. esplits; eauto.\n        * ii. inv PRSV. inv SUGE. rewrite Forall_forall in *.\n          exploit GE; eauto. { ss. des_ifs. eapply MSFIND. } intro T; des. eapply INIT0; et.\n      + inv MSFIND. ss. rr in SIMPROG. rewrite Forall_forall in *. des; clarify.\n        { eapply system_local_preservation. }\n        u in MODSEM. rewrite in_map_iff in MODSEM. des; clarify. rename x into md_src.\n        assert(exists mp, In mp pp /\\ mp.(ModPair.src) = md_src).\n        { clear - MODSEM0. rr in pp. rr in p_src. subst p_src. rewrite in_map_iff in *. des. eauto. }\n        des. exploit SIMPROG; eauto. intros MPSIM. inv MPSIM.\n        destruct SIMSKENV. exploit SIMMS.\n        { eapply INCLSRC; et. }\n        { eapply INCLTGT; et. }\n        { eapply SkEnv.load_skenv_wf; et. }\n        { eapply SkEnv.load_skenv_wf; et. }\n        { eapply SSLE; eauto. }\n        { eauto. }\n        intro SIM; des. inv SIM. ss. esplits; eauto.\n    - (* INTERNAL *)\n      inv SUST. ss. esplits; eauto. econs; eauto. i. des.\n      exploit FORALLSU; eauto. { eapply local_preservation_noguarantee_weak; eauto. } intro U; des. esplits; eauto. i. ss. inv PRSV.\n      eapply STEP; eauto.\n      + eapply FORALLSU; eauto. econs; eauto.\n      + split; ii; ModSem.tac.\n    - (* RETURN *)\n      inv SUST. ss. rename ms into ms_top. rename args_tail into args_tail_top.\n      inv TL. ss. unfold Frame.update_st. s. des. esplits; eauto. econs; eauto. ii. esplits; eauto.\n      + ii. exploit FORALLSU0; eauto. i; des. exploit K; eauto. i; des. inv EX.\n        exploit RET; eauto.\n        { eapply FORALLSU; eauto.\n          { eapply lepriv_preserves_sound_ge. { eapply mle_preserves_sound_ge; eauto. } eauto. }\n          { eapply local_preservation_noguarantee_weak; eauto. econs; et. } }\n        i; des.\n        eapply K0; eauto.\n  Unshelve.\n    all: ss.\n  Qed.\n\n  (* Lemma sound_progress_star *)\n  (*       st0 tr st1 *)\n  (*       (SUST: sound_state st0) *)\n  (*       (STEP: Star sem_src st0 tr st1): *)\n  (*     <<SUST: sound_state st1>>. *)\n  (* Proof. *)\n  (*   induction STEP. *)\n  (*   - esplits; eauto. *)\n  (*   - clarify. i. exploit sound_progress; eauto. *)\n  (* Qed. *)\n\n  (* Lemma sound_progress_plus *)\n  (*       st0 tr st1 *)\n  (*       (SUST: sound_state st0) *)\n  (*       (STEP: Plus sem_src st0 tr st1): *)\n  (*     <<SUST: sound_state st1>>. *)\n  (* Proof. *)\n  (*   eapply sound_progress_star; eauto. eapply plus_star; eauto. *)\n  (* Qed. *)\n\n  Theorem preservation: @preservation sem_src sound_state.\n  Proof.\n    econs.\n    - eapply sound_init.\n    - eapply sound_progress.\n  Qed.\n\nEnd ADQSOUND.\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/AdequacySound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2653129259935299}}
{"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 milieu.\nSet Implicit Arguments.\nUnset Strict Implicit.\nParameter DR : Type.\nParameter droite : PO -> PO -> DR.\n \nAxiom\n  droite_permute : forall A B : PO, A <> B :>PO -> droite A B = droite B A.\n#[export] Hint Resolve droite_permute: geo.\n \nAxiom\n  alignes_droite :\n    forall A B C : PO,\n    A <> B :>PO -> A <> C :>PO -> alignes A B C -> droite A B = droite A C.\n \nLemma alignes_droite2 :\n forall A B C : PO,\n A <> B :>PO -> B <> C :>PO -> alignes A B C -> droite A B = droite B C.\nintros.\nrewrite droite_permute; auto.\napply alignes_droite; auto with geo.\nQed.\n#[export] Hint Resolve alignes_droite alignes_droite2: geo.\nParameter paralleles : DR -> DR -> Prop.\n \nAxiom\n  def_paralleles :\n    forall (A B C D : PO) (k : R),\n    A <> B :>PO ->\n    C <> D :>PO ->\n    add_PP (cons 1 B) (cons (-1) A) = add_PP (cons k D) (cons (- k) C) ->\n    paralleles (droite A B) (droite C D).\n \nAxiom\n  def_paralleles2 :\n    forall A B C D : PO,\n    A <> B :>PO ->\n    C <> D :>PO ->\n    paralleles (droite A B) (droite C D) ->\n    exists k : R,\n      add_PP (cons 1 B) (cons (-1) A) = add_PP (cons k D) (cons (- k) C) :>PP.\n \nLemma paralleles_refl :\n forall A B : PO, A <> B :>PO -> paralleles (droite A B) (droite A B).\nintros A B H; try assumption.\napply def_paralleles with (k := 1); auto.\nQed.\n#[export] Hint Resolve paralleles_refl: geo.\n \nLemma paralleles_sym :\n forall A B C D : PO,\n A <> B ->\n C <> D ->\n paralleles (droite A B) (droite C D) -> paralleles (droite C D) (droite A B).\nintros A B C D H H1 H0; try assumption.\nelim def_paralleles2 with (3 := H0); intros; auto.\nelim (classic (x = 0)); intros.\nrewrite H3 in H2.\nabsurd (A = B); auto.\napply conversion_PP with (a := 1) (b := 1); auto.\nRingPP1 H2; RingPP; auto with *.\nauto with *.\napply def_paralleles with (k := / x); auto.\napply mult_PP_regulier with x; auto.\nVReplace (mult_PP x (add_PP (cons 1 D) (cons (-1) C)))\n (add_PP (cons x D) (cons (- x) C)).\nrewrite <- H2.\nFieldPP x.\nQed.\n \nLemma paralleles_trans :\n forall A B C D E F : PO,\n A <> B ->\n C <> D :>PO ->\n E <> F :>PO ->\n paralleles (droite A B) (droite C D) ->\n paralleles (droite C D) (droite E F) -> paralleles (droite A B) (droite E F).\nintros A B C D E F H H10 H11 H0 H1; try assumption.\nelim def_paralleles2 with (3 := H0); intros; auto.\nelim def_paralleles2 with (3 := H1); intros; auto.\napply def_paralleles with (k := x * x0); auto.\nrewrite H2.\nelim (classic (x = 0)); intros.\nrewrite H4 in H2.\nabsurd (A = B); auto.\napply conversion_PP with (a := 1) (b := 1); auto.\nRingPP1 H2; RingPP; auto with *.\nauto with *.\nreplace (add_PP (cons x D) (cons (- x) C)) with\n (mult_PP x (add_PP (cons 1 D) (cons (-1) C))).\nrewrite H3.\nRingPP.\nRingPP.\nQed.\n \nLemma paralleles_vecteur :\n forall A B C D : PO,\n A <> B :>PO ->\n C <> D :>PO ->\n paralleles (droite A B) (droite C D) ->\n exists k : R, vec A B = mult_PP k (vec C D) :>PP.\nunfold vec in |- *; intros.\nelim def_paralleles2 with (3 := H1); auto.\nintros k H2; try assumption.\nexists k.\nRingPP1 H2; RingPP.\nQed.\n \nLemma colineaires_paralleles :\n forall (k : R) (A B C D : PO),\n A <> B :>PO ->\n C <> D :>PO ->\n vec A B = mult_PP k (vec C D) -> paralleles (droite A B) (droite C D).\nunfold vec in |- *; intros.\napply def_paralleles with k; auto.\nRingPP1 H1; RingPP.\nQed.\n \nLemma alignes_paralleles :\n forall A B C : PO,\n A <> B -> A <> C -> alignes A B C -> paralleles (droite A B) (droite A C).\nintros.\napply paralleles_sym; auto.\nhalignes H1 x.\napply colineaires_paralleles with x; intros; auto.\nQed.\n \nLemma paralleles_ABBA :\n forall A B : PO, A <> B -> paralleles (droite A B) (droite B A).\nintros.\napply def_paralleles with (-1); auto.\nRingPP.\nQed.\n#[export] Hint Immediate paralleles_ABBA paralleles_sym: geo.\n \nLemma non_paralleles_trans :\n forall A B C D E F : PO,\n A <> B :>PO ->\n C <> D :>PO ->\n E <> F :>PO ->\n paralleles (droite A B) (droite C D) ->\n ~ paralleles (droite A B) (droite E F) ->\n ~ paralleles (droite C D) (droite E F).\nintros; red in |- *; intros.\napply H3.\napply paralleles_trans with (4 := H2); auto.\nQed.\n#[export] Hint Resolve alignes_paralleles: geo.\n \nLemma paralleles_alignes :\n forall A B C D : PO,\n A <> B :>PO ->\n C <> D :>PO ->\n paralleles (droite A B) (droite C D) -> alignes A B C -> alignes A B D.\nintros.\nelim (paralleles_vecteur (A:=C) (B:=D) (C:=A) (D:=B)); intros; auto with geo.\nhalignes H2 x0.\napply colineaire_alignes with (x + x0).\nVReplace (vec A D) (add_PP (vec A C) (vec C D)).\nrewrite H3; rewrite H4; Ringvec.\nQed.\n \nLemma paralleles_alignes1 :\n forall A B C D E F : PO,\n A <> B :>PO ->\n C <> D :>PO ->\n vec E F = vec A B :>PP ->\n paralleles (droite A B) (droite C D) -> alignes C D E -> alignes C D F.\nintros A B C D E F H H0 H1 H2 H3; try assumption.\nelim (paralleles_vecteur (A:=A) (B:=B) (C:=C) (D:=D)); intros; auto.\nhalignes H3 x0.\napply colineaire_alignes with (x0 + x).\nVReplace (vec C F) (add_PP (vec C E) (vec E F)).\nrewrite H5; rewrite H1; rewrite H4.\nRingvec.\nQed.\n \nLemma paralleles_alignes2 :\n forall A B C D E F : PO,\n A <> B :>PO ->\n C <> D :>PO ->\n vec E F = vec A B :>PP ->\n paralleles (droite A B) (droite C D) -> alignes C D E -> alignes F C E.\nintros A B C D E F H H0 H1 H2 H3; try assumption.\nelim (paralleles_vecteur (A:=C) (B:=D) (C:=A) (D:=B)); intros; auto with geo.\nhalignes H3 x0.\nrewrite H4 in H5.\ndiscrimine F C.\ncut (1 + x0 * x <> 0); intros.\napply colineaire_alignes with (/ (1 + x0 * x)).\nVReplace (vec F C) (add_PP (vec F E) (mult_PP (-1) (vec C E))).\nVReplace (vec F E) (mult_PP (-1) (vec E F)).\nrewrite H1; rewrite H5.\nFieldvec (1 + x0 * x).\nred in |- *; intros; apply H6.\napply vecteur_nul_conf.\nVReplace (vec F C) (add_PP (mult_PP (-1) (vec E F)) (mult_PP (-1) (vec C E))).\nrewrite H1; rewrite H5.\nVReplace\n (add_PP (mult_PP (-1) (vec A B))\n    (mult_PP (-1) (mult_PP x0 (mult_PP x (vec A B)))))\n (mult_PP (-1) (mult_PP (1 + x0 * x) (vec A B))).\nrewrite H7; Ringvec.\nQed.\n \nLemma paralleles_alignes3 :\n forall A B C D : PO,\n A <> B :>PO ->\n C <> D :>PO ->\n paralleles (droite A B) (droite C D) -> alignes C D A -> alignes A C B.\nintros A B C D H H0 H1 H2; try assumption.\nelim (paralleles_vecteur (A:=A) (B:=B) (C:=C) (D:=D)); intros; auto.\ndiscrimine C A.\nassert (alignes C A D); auto with geo.\nhalignes H5 x0.\nrewrite H6 in H3.\napply colineaire_alignes with (- (x * x0)).\nrewrite H3; Ringvec.\nQed.\n \nLemma alignes_paralleles_confondus :\n forall A B C J : PO,\n triangle A B C ->\n alignes A C J -> paralleles (droite B C) (droite B J) -> J = C :>PO.\nintros.\ncut (triangle B C A); auto with geo; intros.\nderoule_triangle B C A.\napply (concours_unique (A:=B) (B:=A) (A1:=C) (B1:=C) (I:=J) (J:=C));\n auto with geo.\ncut (B <> J); intros.\nelim paralleles_vecteur with (A := B) (B := J) (C := B) (D := C);\n [ intros k0 H8 | auto | auto | auto with geo ].\napply colineaire_alignes with k0; auto.\ncut (triangle A C B); auto with geo; intros.\nderoule_triangle A C B.\nred in |- *; intros; apply H8.\nrewrite H12; auto.\nQed.\nParameter concours : DR -> DR -> Prop.\n \nAxiom\n  def_concours :\n    forall A B C D I : PO,\n    A <> B ->\n    C <> D ->\n    alignes A B I -> alignes C D I -> concours (droite A B) (droite C D).\n \nAxiom\n  def_concours2 :\n    forall A B C D : PO,\n    A <> B ->\n    C <> D ->\n    concours (droite A B) (droite C D) ->\n    exists I : PO, alignes A B I /\\ alignes C D I.\n \nLemma paralleles_non_concours :\n forall A B C D : PO,\n A <> B :>PO ->\n C <> D :>PO ->\n ~ alignes A B D ->\n paralleles (droite C D) (droite A B) -> ~ concours (droite C D) (droite A B).\nintros A B C D H10 H11 H H0.\nelim def_paralleles2 with (3 := H0); intros; auto.\nunfold not in |- *; intros.\nelim def_concours2 with (3 := H2); intros; auto.\nelim H3; [ intros H4 H5; try clear H3; try exact H5 ].\nelim H4; clear H4; (unfold alignes1 in |- *; intros); [ tauto | idtac ].\nelim H3; [ intros k H4; try clear H3; try exact H4 ].\nelim H5; clear H5; (unfold alignes1 in |- *; intros); [ tauto | idtac ].\nelim H3; [ intros k0 H5; try clear H3; try exact H5 ].\napply H.\ncut\n (add_PP (cons k0 A) (cons (1 + - k0) B) =\n  add_PP (cons k C) (cons (1 + - k) D)); intros.\nunfold alignes, alignes1 in |- *.\nright; try assumption.\nexists (k0 + - (x * k)).\npattern 1 at 1 in |- *.\nreplace 1 with (k + (1 + - k)); try ring.\nreplace (cons (k + (1 + - k)) D) with (add_PP (cons k D) (cons (1 + - k) D)).\nreplace (cons k D) with (mult_PP k (cons 1 D)).\nRingPP1 H1.\nreplace (cons (k0 + - (x * k)) A) with\n (add_PP (cons k0 A) (cons (- (x * k)) A)).\nreplace (1 + - (k0 + - (x * k))) with (1 + - k0 + x * k); try ring.\nRingPP1 H3.\nRingPP.\nRingPP.\nRingPP.\nRingPP.\nrewrite <- H4; auto.\nQed.\n \nLemma concours_non_paralleles :\n forall A B C D : PO,\n A <> B :>PO ->\n C <> D :>PO ->\n ~ alignes A B D ->\n concours (droite C D) (droite A B) -> ~ paralleles (droite C D) (droite A B).\nintros A B C D H10 H20 H H0; try assumption.\ncut (~ ~ concours (droite C D) (droite A B)); intros.\nunfold not in |- *; intros.\napply H1.\napply paralleles_non_concours; auto.\nintuition.\nQed.\nParameter pt_intersection : DR -> DR -> PO.\n \nAxiom\n  def_pt_intersection :\n    forall A B C D I : PO,\n    A <> B ->\n    C <> D ->\n    ~ alignes A B C \\/ ~ alignes A B D ->\n    alignes A B I ->\n    alignes C D I -> I = pt_intersection (droite A B) (droite C D).\n \nAxiom\n  def_pt_intersection2 :\n    forall A B C D I : PO,\n    A <> B ->\n    C <> D ->\n    ~ alignes A B C \\/ ~ alignes A B D ->\n    I = pt_intersection (droite A B) (droite C D) ->\n    alignes A B I /\\ alignes C D I.\n \nLemma existence_pt_intersection :\n forall A B C D : PO,\n A <> B ->\n C <> D ->\n ~ alignes A B C \\/ ~ alignes A B D ->\n concours (droite A B) (droite C D) ->\n exists I : PO, I = pt_intersection (droite A B) (droite C D) :>PO.\nintros.\nelim def_concours2 with (A := A) (B := B) (C := C) (D := D);\n [ intros I H3; elim H3; intros H4 H5; try clear H3 def_concours2;\n    try exact H5\n | auto\n | auto\n | auto ].\nexists I.\napply def_pt_intersection; auto.\nQed.\n \nLemma ordre_alignement_4points :\n forall A B C D : PO,\n A <> B :>PO ->\n alignes A B C /\\ alignes A B D -> alignes C D A /\\ alignes C D B.\nintros.\nelim H0; intros H1 H2; try clear H0; try exact H2.\nsplit; [ try assumption | idtac ].\neauto with geo.\neauto with geo.\nQed.\n \nLemma pt_intersection_commute :\n forall A B C D I : PO,\n A <> B :>PO ->\n C <> D :>PO ->\n ~ alignes A B C \\/ ~ alignes A B D ->\n I = pt_intersection (droite A B) (droite C D) :>PO ->\n I = pt_intersection (droite C D) (droite A B) :>PO.\nintros.\nelim def_pt_intersection2 with (A := A) (B := B) (C := C) (D := D) (I := I);\n [ try clear def_pt_intersection2; intros | auto | auto | auto | auto ].\napply def_pt_intersection; auto.\napply not_and_or; auto.\ncut (~ (alignes A B C /\\ alignes A B D)); intros.\nred in |- *; intros; apply H5.\napply ordre_alignement_4points; auto.\napply or_not_and; auto.\nQed.\n \nLemma concours_barycentre :\n forall A B C D : PO,\n A <> B ->\n C <> D ->\n concours (droite A B) (droite C D) ->\n exists I : PO,\n   ex\n     (fun a : R =>\n      ex\n        (fun b : R =>\n         I = barycentre (cons (1 + - a) A) (cons a B) :>PO /\\\n         I = barycentre (cons (1 + - b) C) (cons b D) :>PO)).\nintros A B C D H10 H11 H; try assumption.\nelim def_concours2 with (3 := H); auto.\nintros I H0; elim H0; intros H1 H2; clear H0 H; try exact H2.\nelim alignes_barycentre with (A := A) (B := B) (C := I);\n [ intros a H; try clear alignes_barycentre; try exact H | auto | auto ].\nelim alignes_barycentre with (A := C) (B := D) (C := I);\n [ intros b H'; try clear alignes_barycentre | auto | auto ].\nexists I; exists (1 + - a); exists (1 + - b).\nreplace (1 + - (1 + - a)) with a; try ring.\nreplace (1 + - (1 + - b)) with b; try ring.\nsplit; [ try assumption | try assumption ].\nQed.\n \nLemma barycentre_concours :\n forall (a b c d : R) (A B C D I : PO),\n A <> B ->\n C <> D :>PO ->\n a + b <> 0 :>R ->\n barycentre (cons a A) (cons b B) = I :>PO ->\n c + d <> 0 :>R ->\n barycentre (cons c C) (cons d D) = I :>PO ->\n concours (droite A B) (droite C D).\nintros a b c d A B C D I H H0 H1 H2 H3 H4; try assumption.\napply def_concours with I; auto.\nrewrite <- H2.\napply barycentre_alignes; auto.\nrewrite <- H4.\napply barycentre_alignes; auto.\nQed.\n \nLemma add_PP_concours :\n forall (a b c d : R) (A B C D I : PO),\n A <> B :>PO ->\n C <> D :>PO ->\n a + b <> 0 :>R ->\n add_PP (cons a A) (cons b B) = cons (a + b) I :>PP ->\n c + d <> 0 :>R ->\n add_PP (cons c C) (cons d D) = cons (c + d) I :>PP ->\n concours (droite A B) (droite C D).\nintros a b c d A B C D I H H0 H1 H2 H3 H4; try assumption.\napply def_concours with I; auto.\napply add_PP_alignes with (a := a) (b := b); auto.\napply add_PP_alignes with (a := c) (b := d); auto.\nQed.\n \nLemma concours_mediane :\n forall A B C : PO,\n A <> milieu B C :>PO ->\n milieu A B <> C :>PO ->\n concours (droite A (milieu B C)) (droite (milieu A B) C).\nintros A B C H H0; try assumption.\ngeneralize (add_PP_milieu_asso A B C); intros.\ngeneralize\n (add_PP_concours (a:=1) (b:=2) (c:=2) (d:=1) (A:=A) (B:=\n    milieu B C) (C:=milieu A B) (D:=C)\n    (I:=barycentre (cons 1 A) (cons 2 (milieu B C)))); \n intros H8; apply H8; auto.\ntry discrR; auto with *.\nrewrite add_PP_barycentre; try discrR; auto with *.\ntry discrR; auto with *.\nrewrite <- H1; auto.\nrewrite add_PP_barycentre; try discrR; auto with *.\napply cons_comp; try ring; auto.\nQed.\n \nDefinition concours_3 (A B C D E F : PO) :=\n  exists I : PO, alignes A B I /\\ alignes C D I /\\ alignes E F I.\n \nLemma concours_3_mediane :\n forall A B C : PO, concours_3 A (milieu B C) (milieu A B) C (milieu A C) B.\nintros A B C; try assumption.\ngeneralize (add_PP_milieu_asso A B C); intros.\ngeneralize (add_PP_milieu_permute A B C); intros.\nunfold concours_3 in |- *.\nexists (barycentre (cons 1 A) (cons 2 (milieu B C))).\nsplit; [ try assumption | idtac ].\napply barycentre_alignes; try discrR; auto with *.\nsplit; [ try assumption | idtac ].\napply add_PP_alignes with (a := 2) (b := 1); try discrR; auto with *.\nrewrite <- H; auto.\nrewrite add_PP_barycentre; try discrR; auto with *.\napply cons_comp; (try ring; auto).\napply add_PP_alignes with (a := 2) (b := 1); try discrR; auto with *.\nrewrite <- H0; auto.\nrewrite add_PP_barycentre; try discrR; auto with *.\napply cons_comp; try ring; auto.\nQed.\n \nLemma concours_3_barycentre :\n forall (a b c : R) (A B C : PO),\n a + (b + c) <> 0 :>R ->\n a + b <> 0 :>R ->\n b + c <> 0 :>R ->\n a + c <> 0 :>R ->\n concours_3 A (barycentre (cons b B) (cons c C))\n   (barycentre (cons a A) (cons b B)) C (barycentre (cons a A) (cons c C)) B.\nunfold concours_3 in |- *.\nintros a b c A B C H H0 H1 H2; try assumption.\nexists\n (barycentre (cons a A) (cons (b + c) (barycentre (cons b B) (cons c C)))).\ngeneralize (add_PP_assoc (cons a A) (cons b B) (cons c C)); intros.\ngeneralize (add_PP_assoc_permute (cons a A) (cons b B) (cons c C)); intros.\nsplit; [ try assumption | idtac ].\napply add_PP_alignes with (a := a) (b := b + c); auto with geo.\nsplit; [ try assumption | idtac ].\napply add_PP_alignes with (a := a + b) (b := c); auto with geo.\nunfold not in |- *; intros; apply H.\nrewrite <- H5; ring.\nrewrite <- add_PP_barycentre; auto with geo.\nrewrite <- H3; auto.\nrepeat rewrite add_PP_barycentre; auto with geo.\napply cons_comp; auto.\nring.\napply add_PP_alignes with (a := a + c) (b := b); auto with geo.\nunfold not in |- *; intros; apply H.\nrewrite <- H5; ring.\nrewrite <- add_PP_barycentre; auto.\nrewrite <- H4; auto.\nrepeat rewrite add_PP_barycentre; auto.\napply cons_comp; auto.\nring.\nQed.\n \nLemma centre_gravite_intersection_medianes :\n forall A B C I J G : PO,\n triangle A B C ->\n I = milieu B C :>PO ->\n J = milieu A B :>PO ->\n G = centre_gravite A B C :>PO ->\n G = pt_intersection (droite A I) (droite C J) :>PO.\nintros.\nderoule_triangle A B C.\ncut (triangle B C A); auto with geo; unfold triangle in |- *; intros.\ncut (C <> J); intros.\ncut (A <> I); intros.\ncut (3 <> 0); intros; auto with real.\nreplace (droite C J) with (droite J C); auto with geo.\napply def_pt_intersection; auto.\nleft.\napply triangle_medianes_triangle with (1 := H); auto.\napply colineaire_alignes with (/ 3 * 2); auto.\nrewrite (centre_gravite_mediane_vecteur (A:=A) (B:=B) (C:=C) (I:=I) (G:=G));\n auto.\nFieldvec 3.\napply permute_alignes; auto.\napply colineaire_alignes with (/ 3 * 2); auto.\nrewrite (centre_gravite_mediane_vecteur (A:=C) (B:=A) (C:=B) (I:=J) (G:=G));\n auto.\nFieldvec 3.\nrewrite H2; auto with geo.\nrewrite H0.\napply triangle_milieu_distinct; auto.\nrewrite H1.\napply triangle_milieu_distinct; auto.\nQed.\n \nLemma centre_gravite_intersection_trois_medianes :\n forall A B C I J K G : PO,\n triangle A B C ->\n I = milieu B C :>PO ->\n J = milieu A B :>PO ->\n K = milieu A C :>PO ->\n G = centre_gravite A B C :>PO ->\n G = pt_intersection (droite A I) (droite B K) :>PO /\\\n G = pt_intersection (droite A I) (droite C J) :>PO.\nintros.\nsplit; [ idtac | try assumption ].\napply centre_gravite_intersection_medianes with (B := C); auto with geo.\nrewrite H3; auto with geo.\napply centre_gravite_intersection_medianes with (B := B); auto.\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/parallelisme_concours.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.26528115386465334}}
{"text": "Require 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.predicates_sl.\nRequire Import VST.msl.subtypes.\n\nLocal Open Scope pred.\n\n\nLemma unfash_derives {A} `{agA : ageable A}:\n  forall {P Q}, (P |-- Q) -> @derives A _ (! P) (! Q).\nProof.\nintros. intros w ?. simpl in *. apply H. auto.\nQed.\n\nLemma subp_sepcon {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A} : forall G P P' Q Q',\n  G |-- P >=> P' ->\n  G |-- Q >=> Q' ->\n  G |-- P * Q >=> P' * Q'.\nProof.\n  pose proof I.\n  repeat intro.\n  specialize (H0 _ H2).\n  specialize (H1 _ H2).\n  clear G H2.\n  destruct H5 as [w1 [w2 [? [? ?]]]].\n  exists w1; exists w2; split; auto.\n  split.\n  eapply H0; auto.\n  assert (level w1 = level a').\n  apply comparable_fashionR.  eapply join_sub_comparable; eauto.\n apply necR_level in H4. lia.\n  eapply H1; auto.\n  assert (level w2 = level a').\n  apply comparable_fashionR. eapply join_sub_comparable; eauto.\n apply necR_level in H4. lia.\nQed.\n\nLemma sub_wand {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A} : forall G P P' Q Q',\n  G |-- P' >=> P ->\n  G |-- Q >=> Q' ->\n  G |-- (P -* Q) >=> (P' -* Q').\nProof.\n  pose proof I.\n  repeat intro.\n  specialize (H0 _ H2); specialize (H1 _ H2); clear G H2; pose (H2:=True).\n  eapply H0 in H8; try apply necR_refl.\n  eapply H1; try apply necR_refl.\n  apply necR_level in H4. apply necR_level in H6. apply join_comparable in H7.\n  apply comparable_fashionR in H7. unfold fashionR in H7. lia.\n  eapply H5; eauto.\n  apply necR_level in H4. apply necR_level in H6.\n   apply join_comparable2 in H7.\n  apply comparable_fashionR in H7. unfold fashionR in H7. lia.\nQed.\n\nLemma find_superprecise {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A}:\n   forall Q, Q |-- EX P:_, P && !(P >=> Q) && !!superprecise (P).\nProof.\nintros.\nintros w ?.\nexists (exactly w).\nsplit; auto.\nsplit; auto.\nhnf; apply necR_refl.\nintros w' ? w'' ? ?.\nhnf in H2.\napply pred_nec_hereditary with w; auto.\ndo 3 red.\napply superprecise_exactly.\nQed.\n\nLemma sepcon_subp' {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A}:\n  forall (P P' Q Q' : pred A) (st: nat),\n    (P >=> P') st ->\n    (Q >=> Q') st ->\n    (P * Q >=> P' * Q') st.\nProof.\n pose proof I.\nintros.\nintros w' ? w'' ? [w1 [w2 [? [? ?]]]].\ndestruct (nec_join4 _ _ _ _ H4 H3) as [w1' [w2' [? [? ?]]]].\nexists w1; exists w2; repeat split; auto.\neapply (H0 w1'); eauto.\nsimpl in *.\nsubst.\nreplace (level w1') with (level w'); auto.\nsymmetry; apply comparable_fashionR; eapply join_comparable; eauto.\neapply (H1 w2'); eauto.\nreplace (level w2') with (level w'); auto.\nsymmetry. apply comparable_fashionR.\neapply join_comparable; eauto.\nQed.\n\nLemma subp_refl'  {A} `{agA : ageable A} :  forall (Q: pred A) (st: nat), (Q >=> Q) st.\nProof.\nintros.\nintros ? ? ? ?; auto.\nQed.\n\nLemma subp_trans' {A} `{agA : ageable A}:\n  forall (B C D: pred A) (w: nat), (B >=> C)%pred w -> (C >=> D)% pred w -> (B >=> D)%pred w.\nProof.\nintros.\nintros w' ? w'' ? ?.\neapply H0; eauto.\neapply H; eauto.\nQed.\n\nLemma andp_subp'  {A} `{agA : ageable A} :\n forall (P P' Q Q': pred A) (w: nat), (P >=> P') w -> (Q >=> Q') w -> (P && Q >=> P' && Q') w.\nProof.\nintros.\nintros w' ? w'' ? [? ?]; split.\neapply H; eauto.\neapply H0; eauto.\nQed.\n\nLemma allp_subp' {A} `{agA : ageable A}: forall T (F G: T -> pred A) (w: nat),\n   (forall x,  (F x >=> G x) w) -> (allp (fun x:T => (F x >=> G x)) w).\nProof.\nintros.\nintro x; apply H; auto.\nQed.\n\n\nLemma pred_eq_e1 {A} `{agA : ageable A}: forall (P Q: pred A) w,\n       ((P <=> Q) w -> (P >=> Q) w).\nProof.\nintros.\nintros w' ? w'' ? ?.\neapply H; eauto.\nQed.\n\nLemma pred_eq_e2 {A} `{agA : ageable A}: forall (P Q: pred A)  w,\n     ((P <=> Q) w -> (Q >=> P) w).\nProof.\nProof.\nintros.\nintros w' ? w'' ? ?.\neapply H; eauto.\nQed.\n\n#[export] Hint Resolve sepcon_subp' : core.\n#[export] Hint Resolve subp_refl' : core.\n#[export] Hint Resolve andp_subp' : core.\n#[export] Hint Resolve allp_subp' : core.\n#[export] Hint Resolve derives_subp : core.\n#[export] Hint Resolve pred_eq_e1 : core.\n#[export] Hint Resolve pred_eq_e2 : core.\n\n\nLemma allp_imp2_later_e2 {B}{A}{agA: ageable A}:\n   forall (P Q: B -> pred A) (y: B) ,\n      (ALL x:B, |> P x <=> |> Q x) |-- |> Q y >=> |> P y.\nProof.\n  intros.  intros w ?. specialize (H y). apply pred_eq_e2. auto.\nQed.\nLemma allp_imp2_later_e1 {B}{A}{agA: ageable A}:\n   forall (P Q: B -> pred A) (y: B) ,\n      (ALL x:B, |> P x <=> |> Q x) |-- |> P y >=> |> Q y.\nProof.\n  intros.  intros w ?. specialize (H y). apply pred_eq_e1. auto.\nQed.\n\n(*\nLemma subp_later {A} `{agA:  ageable A} (SS: natty A):\n forall (P Q: pred A), |> (P >=> Q) |-- |> P >=> |> Q.\nProof.\nintros.\nrewrite later_fash; auto.\napply fash_derives.\napply axiomK.\nQed.\n*)\n\nLemma extend_unfash {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A} : forall (P: pred nat), boxy extendM (! P).\nProof.\nintros.\napply boxy_i; auto; intros.\nunfold unfash in *.\nsimpl in H. destruct H.\nhnf in H0|-*.\nreplace (level w') with (level w); auto.\napply comparable_fashionR.\neapply join_comparable; eauto.\nQed.\n\n#[export] Hint Resolve extend_unfash : core.\n\nLemma subp_unfash {A} `{Age_alg A}:\n  forall (P Q : pred nat) (n: nat), (P >=> Q) n -> ( ! P >=> ! Q) n.\nProof.\nintros.\nintros w ?. specialize (H0 _ H1).\nintros w' ? ?. apply (H0 _ (necR_level' H2)).\nauto.\nQed.\n#[export] Hint Resolve subp_unfash : core.\n\n\nLemma unfash_sepcon_distrib:\n        forall {T}{agT: ageable T}{JoinT: Join T}{PermT: Perm_alg T}{SepT: Sep_alg T}{AgeT: Age_alg T}\n           (P: pred nat) (Q R: pred T),\n               unfash P && (Q*R) = (unfash P && Q) * (unfash P && R).\nProof.\nintros.\napply pred_ext.\nintros w [? [w1 [w2 [? [? ?]]]]].\nexists w1; exists w2; repeat split; auto.\napply join_level in H0. destruct H0.\nhnf in H|-*. congruence.\napply join_level in H0. destruct H0.\nhnf in H|-*. congruence.\nintros w [w1 [w2 [? [[? ?] [? ?]]]]].\nsplit.\napply join_level in H. destruct H.\nhnf in H0|-*. congruence.\nexists w1; exists w2; repeat split; auto.\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/msl/subtypes_sl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.4921881357207955, "lm_q1q2_score": 0.2652811465750613}}
{"text": "Require Import Primitives Simulation Layer1 Layer2 BlockAllocator.\nClose Scope pred_scope.\nImport ListNotations.\n\nFixpoint compile {T} (p2: Layer2.prog T) : Layer1.prog T :=\n    match p2 with\n    | Read a => read a\n    | Write a v => write a v\n    | Alloc v => alloc v\n    | Free a => free a\n    | Ret v => Layer1.Ret v\n    | Bind px py => Layer1.Bind (compile px) (fun x => compile (py x))\n    end.\n\n(* October 12: I need oracle_ok in here because specifications of block allocator requires it as a precondition *)\nFixpoint oracle_refines_to T (d1: State layer1_lts) (p: Layer2.prog T)  (o1: Oracle layer1_lts) (o2: Layer2.oracle) : Prop :=\n  oracle_ok _ (compile p) o1 d1 /\\\n    match p with\n    | Alloc v =>\n      if (in_dec Layer1.token_dec Layer1.Crash o1) then\n        forall d1',\n          Layer1.exec o1 d1 (compile p) (Crashed d1') ->\n          let sv := Disk.read d1 0 in\n          let sv' := Disk.read d1' 0 in\n          match sv, sv' with\n          | Some v, Some v' =>\n            (v = v' ->\n             o2 = [Crash1]) /\\\n            (v <> v' ->\n             let bits := bits (value_to_bits v) in\n             let index := get_first_zero bits in\n             o2 = [CrashAlloc index])\n          | _, _ => False\n          end\n      else\n        let sv := Disk.read d1 0 in\n        match sv with\n        | Some v =>\n          let bits := bits (value_to_bits v) in\n          let index := get_first_zero bits in\n          \n          if Compare_dec.lt_dec index block_size then\n            o2 = [BlockNum index]\n          else\n            o2 = [DiskFull]\n        | None => False\n        end\n    | @Bind T1 T2 p1 p2 =>\n      exists o1' o1'',\n      o1 = o1'++o1'' /\\\n     ((exists d1', Layer1.exec o1 d1 (compile p1) (Crashed d1') /\\\n         oracle_refines_to T1 d1 p1 o1 o2 /\\ o1'' = []) \\/\n      (exists d1' r ret,\n          Layer1.exec o1' d1 (compile p1) (Finished d1' r) /\\\n          Layer1.exec o1'' d1' (compile (p2 r)) ret /\\\n         exists o2' o2'',\n         oracle_refines_to T1 d1 p1 o1' o2' /\\\n         oracle_refines_to T2 d1' (p2 r) o1'' o2'' /\\\n         o2 = o2' ++ o2''))\n    | Read _ =>\n      if (in_dec Layer1.token_dec Layer1.Crash o1) then\n        o2 = [Crash1]\n      else\n        o2 = [Cont]\n    | Ret _ =>\n      if (in_dec Layer1.token_dec Layer1.Crash o1) then\n        o2 = [Crash1]\n      else\n        o2 = [Cont]\n    | Free _ =>\n      if (in_dec Layer1.token_dec Layer1.Crash o1) then\n        o2 = [Crash1]\n      else\n        o2 = [Cont]\n    | Write a _ =>\n      if (in_dec Layer1.token_dec Layer1.Crash o1) then\n         forall d1',\n          Layer1.exec o1 d1 (compile p) (Crashed d1') ->\n          let sv := d1 a in\n          let sv' := d1' a in\n          match sv, sv' with\n          | Some v, Some v' =>\n            (v = v' ->\n             o2 = [Crash1]) /\\\n            (v <> v' ->\n             o2 = [Crash2])\n          | _, _ => False\n          end\n      else\n        o2 = [Cont]\n    end.\n\n  Definition refines_to d1 d2 :=\n    exists F, (F * rep d2)%pred d1.\n\n  Definition compilation_of T p1 p2 :=\n    p1 = @compile T p2.", "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/L1To2Refinement/Definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2652604577485596}}
{"text": "Require Import DACandMAC. \n \nSection Close. \n \nVariable s : SFSstate. \n \n \n(*********************************************************************) \n(*                   Some Useful Synonymous                          *) \n(*********************************************************************) \n \nDefinition NEWRW (u : SUBJECT) (o : OBJECT) (y : ReadersWriters) :\n  ReadersWriters :=\n  mkRW (set_remove SUBeq_dec u (ActReaders y))\n    (set_remove SUBeq_dec u (ActWriters y)). \n \n \nLet NEWSET (u : SUBJECT) (o : OBJECT) (y : ReadersWriters) :\n  set (OBJECT * ReadersWriters) :=\n  match\n    set_remove SUBeq_dec u (ActReaders y),\n    set_remove SUBeq_dec u (ActWriters y)\n  with\n  | nil, nil => set_remove SECMATeq_dec (o, y) (secmat s)\n  | _, _ =>\n      set_add SECMATeq_dec (o, NEWRW u o y)\n        (set_remove SECMATeq_dec (o, y) (secmat s))\n  end. \n \n(*close_sm is assuming the precondition of close (i.e, that u is an  *) \n(*active reader or an active writer of o); with this assumption,     *) \n(*(ActReaders z)=(ActWriters z)=nil, means that the only active      *) \n(*reader and writer of o was u, and so, if he is closing the file, it*) \n(*should be erased from memory.                                      *) \n \nDefinition close_sm (u : SUBJECT) (o : OBJECT) :\n  set (OBJECT * ReadersWriters) :=\n  match fsecmat (secmat s) o with\n  | None => secmat s\n  | Some y => NEWSET u o y\n  end. \n \n \nLet t (u : SUBJECT) (o : OBJECT) : SFSstate :=\n  mkSFS (groups s) (primaryGrp s) (subjectSC s) (AllGrp s) \n    (RootGrp s) (SecAdmGrp s) (objectSC s) (acl s) \n    (close_sm u o) (files s) (directories s). \n \n \n(*********************************************************************) \n(*                            Close                                  *) \n(*********************************************************************) \n \n(*This operation closes an open object. Acctually the user           *) \n(*requesting the operation is removed from the set of active readers *) \n(*or writers associated with the object.                             *) \n \nInductive close (u : SUBJECT) (o : OBJECT) : SFSstate -> Prop :=\n    CloseOK :\n      match fsecmat (secmat s) o with\n      | None => False\n      | Some y =>\n          set_In u (set_union SUBeq_dec (ActReaders y) (ActWriters y))\n      end -> close u o (t u o). \n \nHint Unfold close_sm t. \n \nEnd Close.", "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/close.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737214979746, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2652604527298106}}
{"text": "\nRequire Import Axioms.\nRequire Import Tactics.\nRequire Import Sigma.\nRequire Import Equality.\nRequire Import Relation.\nRequire Import Syntax.\nRequire Import Ofe.\nRequire Import Uniform.\nRequire Import Spaces.\nRequire Import Dynamic.\nRequire Import Hygiene.\nRequire Import Equivalence.\nRequire Import Intensional.\nRequire Import Ordinal.\nRequire Import Candidate.\nRequire Import System.\nRequire Import MapTerm.\nRequire Import Extend.\nRequire Import Model.\nRequire Import Standard.\nRequire Import Truncate.\nRequire Import Equivalences.\nRequire Import Ceiling.\nRequire Import Page.\nRequire Import Urelsp.\n\n\nDefinition ext_action (w u : ordinal) (hu : u << w) (i : nat) : nat -> relation (wterm w)\n  :=\n  fun j m m' =>\n    j <= i\n    /\\ exists Q Q' (h : level (pi1 Q) <<= u) (h' : level (pi1 Q') <<= u),\n         hygiene clo m\n         /\\ hygiene clo m'\n         /\\ star step m (ext (objin (objsome Q (le_lt_ord_trans _#3 h hu))))\n         /\\ star step m' (ext (objin (objsome Q' (le_lt_ord_trans _#3 h' hu))))\n         /\\ projc j Q = projc j Q'.\n\n\nDefinition ext_uniform :\n  forall w u hu i, uniform _ (ext_action w u hu i).\nProof.\nintros w u hu i.\ndo2 3 split.\n\n(* closed *)\n{\nintros j m n H.\ndecompose H; auto.\n}\n\n(* equiv *)\n{\nintros j m m' n n' Hclm Hcln Hm Hn H.\ndestruct H as (Hj & Q & Q' & h & h' & _ & _ & Hstepsm & Hstepsn & Heq).\nsplit; auto.\nexists Q, Q', h, h'.\ndo2 4 split; auto.\n  {\n  so (equiv_eval _#4 Hm (conj Hstepsm value_ext)) as (x & (Hstepsm' & _) & Hmc).\n  invertc_mc Hmc.\n  intros <-.\n  exact Hstepsm'.\n  }\n\n  {\n  so (equiv_eval _#4 Hn (conj Hstepsn value_ext)) as (x & (Hstepsn' & _) & Hmc).\n  invertc_mc Hmc.\n  intros <-.\n  exact Hstepsn'.\n  }\n}\n\n(* zigzag *)\n{\nintros j m n p q Hmn Hpn Hpq.\ndestruct Hmn as (Hj & Q1 & Q2 & h1 & h2 & Hclm & _ & Hstepsm & Hstepsn & Heq12).\ndestruct Hpn as (_ & Q3 & Q2' & h3 & h2' & _ & _ & Hstepsp & Hstepsn' & Heq32).\ndestruct Hpq as (_ & Q3' & Q4 & h3' & h4 & _ & Hclq & Hstepsp' & Hstepsq & Heq34).\nso (determinism_eval _#4 (conj Hstepsn value_ext) (conj Hstepsn' value_ext)) as H.\ninjectionc H.\nintros H.\nso (objin_inj _ _ _ H) as H'.\ninjection H'.\nintros <-.\nclear H H'.\nso (determinism_eval _#4 (conj Hstepsp value_ext) (conj Hstepsp' value_ext)) as H.\ninjectionc H.\nintros H.\nso (objin_inj _ _ _ H) as H'.\ninjection H'.\nintros <-.\nclear H H'.\nsplit; auto.\nexists Q1, Q4, h1, h4.\ndo2 4 split; auto.\nexact (eqtrans Heq12 (eqtrans (eqsymm Heq32) Heq34)).\n}\n\n(* downward *)\n{\nintros j m n H.\ndestruct H as (Hj & Q & Q' & h & h' & Hclm & Hcln & Hstepsm & Hstepsn & Heq).\nsplit.\n  {\n  omega.\n  }\nexists Q, Q', h, h'.\ndo2 4 split; auto.\nso (f_equal (projc j) Heq) as Heq'.\nrewrite -> !projc_combine_le in Heq'; auto.\n}\nQed.\n\n\nDefinition ext_urel w u huw i :=\n  mk_urel (ext_action w u huw i) (ext_uniform w u huw i).\n\n\nLemma rel_ext_intro :\n  forall w u i j Q Q' h h' (hu : u << w),\n    level (pi1 Q) <<= u\n    -> level (pi1 Q') <<= u\n    -> j <= i\n    -> projc j Q = projc j Q'\n    -> rel (ext_urel w u hu i) j (ext (objin (objsome Q h))) (ext (objin (objsome Q' h'))).\nProof.\nintros w u i j Q Q' h h' Huw Hlev Hlev' Hj Heq.\ncbn.\nsplit; auto.\nexists Q, Q', Hlev, Hlev'.\nso (proof_irrelevance _ h (le_lt_ord_trans _#3 Hlev Huw)); subst h.\nso (proof_irrelevance _ h' (le_lt_ord_trans _#3 Hlev' Huw)); subst h'.\ndo2 4 split; auto using star_refl.\n  {\n  apply hygiene_auto; cbn; auto.\n  }\n\n  {\n  apply hygiene_auto; cbn; auto.\n  }\nQed.\n\n\nLemma rel_ext_refl :\n  forall w u (hu : u << w) i j Q h,\n    level (pi1 Q) <<= u\n    -> j <= i\n    -> rel (ext_urel w u hu i) j (ext (objin (objsome Q h))) (ext (objin (objsome Q h))).\nProof.\nintros w u hu i j Q h Hlev Hj.\napply rel_ext_intro; auto.\nQed.\n\n\nLemma rel_ext_invert :\n  forall w u (hu : u << w) i j Q Q' h h',\n    rel (ext_urel w u hu i) j (ext (objin (objsome Q h))) (ext (objin (objsome Q' h')))\n    -> projc j Q = projc j Q'.\nProof.\nintros w u hu i j Q1 Q2 h1 h2 H.\ndestruct H as (Hj & Q1' & Q2' & h1' & h2' & _ & _ & Hsteps1 & Hsteps2 & Heq).\nso (determinism_normal_value _#3 value_ext Hsteps1) as H.\ninjectionc H.\nintros H.\nso (objin_inj _ _ _ H) as H'.\ninjection H'.\nintros <-.\nclear H H'.\nso (determinism_normal_value _#3 value_ext Hsteps2) as H.\ninjectionc H.\nintros H.\nso (objin_inj _ _ _ H) as H'.\ninjection H'.\nintros <-.\nclear H H'.\nexact Heq.\nQed.\n\n\nLemma ceiling_ext_urel :\n  forall w u hu i j,\n    ceiling (S i) (ext_urel w u hu j) = ext_urel w u hu (min i j).\nProof.\nintros w u hu i j.\napply urel_extensionality.\nfextensionality 3.\nintros k m p.\ncbn.\npextensionality.\n  {\n  intros (Hki & H).\n  destruct H as (Hkj & H).\n  split; auto.\n  apply Nat.min_glb; omega.\n  }\n\n  {\n  intros (Hk & H).\n  do2 2 split; auto.\n    {\n    so (Nat.min_glb_l _#3 Hk).\n    omega.\n    }\n\n    {\n    exact (Nat.min_glb_r _#3 Hk).\n    }\n  }\nQed.\n\n       \n\nLemma extend_ext_urel :\n  forall v w u hu i (hvw : v <<= w),\n    extend_urel v w (ext_urel v u hu i) = ext_urel w u (lt_le_ord_trans _#3 hu hvw) i.\nProof.\nintros v w u hu i Hvw.\napply urel_extensionality.\nfextensionality 3.\nintros j m p.\ncbn.\npextensionality.\n  {\n  intro H.\n  destruct H as (Hj & Q & Q' & h & h' & Hclm & Hclp & Hstepsm & Hstepsp & Heq).\n  split; auto.\n  exists Q, Q', h, h'.\n  do2 4 split; eauto using map_hygiene_conv.\n    {\n    so (map_steps_form _#5 Hstepsm) as (m' & Heqm & Hsteps).\n    so (map_eq_ext_invert _#5 (eqsymm Heqm)) as (x & -> & Heqx).\n    so (extend_eq_objsome_form _#5 Heqx) as (h'' & ->).\n    so (proof_irrelevance _ h'' (le_lt_ord_trans _#3 h (lt_le_ord_trans _#3 hu Hvw))); subst h''.\n    exact Hsteps.\n    }\n\n    {\n    so (map_steps_form _#5 Hstepsp) as (m' & Heqm & Hsteps).\n    so (map_eq_ext_invert _#5 (eqsymm Heqm)) as (x & -> & Heqx).\n    so (extend_eq_objsome_form _#5 Heqx) as (h'' & ->).\n    so (proof_irrelevance _ h'' (le_lt_ord_trans _#3 h' (lt_le_ord_trans _#3 hu Hvw))); subst h''.\n    exact Hsteps.\n    }\n  }\n\n  {\n  intro H.\n  destruct H as (Hj & Q & Q' & h & h' & Hclm & Hclp & Hstepsm & Hstepsp & Heq).\n  split; auto.\n  exists Q, Q', h, h'.\n  do2 4 split; auto using map_hygiene.\n    {\n    so (map_steps _ _ (extend w v) _ _ Hstepsm) as Hsteps.\n    simpmapin Hsteps.\n    rewrite -> (extend_some _#4 (le_lt_ord_trans _#3 h hu)) in Hsteps.\n    exact Hsteps.\n    }\n\n    {\n    so (map_steps _ _ (extend w v) _ _ Hstepsp) as Hsteps.\n    simpmapin Hsteps.\n    rewrite -> (extend_some _#4 (le_lt_ord_trans _#3 h' hu)) in Hsteps.\n    exact Hsteps.\n    }\n  }\nQed.\n\n\nDefinition meta_ext {w : ordinal} u (hu : u << w) i (Q : candidate) (h : level (pi1 Q) <<= u) : meta (obj w)\n  :=\n  meta_term (ext_urel w u hu i) (urelspinj (ext_urel w u hu i) i _ _ (rel_ext_refl w u hu i i Q (le_lt_ord_trans _#3 h hu) h (le_refl _))).\n\n\nLemma meta_ext_inj :\n  forall w u hu i Q Q' h h',\n    @meta_ext w u hu i Q h = @meta_ext w u hu i Q' h'\n    -> projc i Q = projc i Q'.\nProof.\nintros w u hu i Q Q' h h' Heqmeta.\nunfold meta_ext in Heqmeta.\nso (meta_term_inj _#5 Heqmeta) as Heq.\ninjectionT Heq.\nintros Heq.\nso (urelspinj_equal_invert _#10 Heq) as (_ & Hrel).\nexact (rel_ext_invert _#9 Hrel).\nQed.\n\n\nLemma meta_truncate_ext :\n  forall cur u (hu : u << cur) n i Q (h : level (pi1 Q) <<= u) (h' : level (approx n (pi1 Q)) <<= u),\n    meta_truncate (S n) (meta_ext u hu i Q h)\n    =\n    meta_ext u hu (min n i) (projc n Q) h'.\nProof.\nintros cur u hu  n i Q h h'.\nunfold meta_ext.\nassert (S n > 0) as Hpos by omega.\nrewrite -> (meta_truncate_term _#4 Hpos).\napply f_equal_dep.\napply (eq_impl_eq_dep _#6 (ceiling_ext_urel cur u hu n i)).\nset (h'' := le_lt_ord_trans _#3 h hu).\nassert (rel (ceiling (S n) (ext_urel cur u hu i)) (min i n) (ext (objin (objsome Q h''))) (ext (objin (objsome Q h'')))) as Hrel.\n  {\n  cbn.\n  split.\n    {\n    apply Nat.min_lt_iff.\n    right; omega.\n    }\n  apply rel_ext_refl; auto.\n  apply Nat.le_min_l.\n  }\nrewrite -> (proj_ceiling_urelspinj _#8 Hrel).\nso (rel_ext_refl cur u hu (min i n) (min i n) Q (le_lt_ord_trans _#3 h hu) h (le_refl _)) as Hrel'.\nrewrite -> Nat.min_comm in Hrel' at 1.\nrewrite -> (transport_urelspinj _#3 (ceiling_ext_urel cur u hu n i) _#4 Hrel').\napply urelspinj_equal'.\n  {\n  apply Nat.min_comm.\n  }\napply rel_ext_intro; auto.\n  {\n  rewrite -> Nat.min_comm.\n  apply le_refl.\n  }\nrewrite -> projc_combine_le; auto.\napply Nat.le_min_r.\nQed.\n\n\nLemma extend_meta_ext :\n  forall v w (h : v <<= w) u (hu : u << v) i Q (lev : level (pi1 Q) <<= u),\n    extend_meta h (meta_ext u hu i Q lev)\n    =\n    meta_ext u (lt_le_ord_trans _#3 hu h) i Q lev.\nProof.\nintros v w hvw u huv i Q lev.\nunfold meta_ext.\nrewrite -> extend_meta_term.\napply f_equal_dep.\napply (eq_impl_eq_dep _#6 (extend_ext_urel v w u huv i hvw)).\nset (lev' := le_lt_ord_trans _#3 lev (lt_le_ord_trans _#3 huv hvw)).\nerewrite -> extend_urelspinj.\nUnshelve.\n2:{\n  unfold extend_urel.\n  cbn [rel].\n  rewrite -> !extend_term_cancel; auto.\n  apply rel_ext_refl; auto.\n  }\nerewrite -> (transport_urelspinj _ _ _ (extend_ext_urel v w u huv i hvw)).\nUnshelve.\n2:{\n  simpmap.\n  erewrite -> (extend_some _#4 lev').\n  apply rel_ext_refl; auto.\n  }\napply urelspinj_equal.\nsimpmap.\nerewrite -> (extend_some _#4 lev').\napply rel_ext_refl; 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/ExtSpace.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.26523366771978535}}
{"text": "Require Import\n  MathClasses.interfaces.abstract_algebra MathClasses.interfaces.monads MathClasses.theory.functors.\n\n#[global]\nInstance default_mon_join `{MonadBind M} : MonadJoin M | 20 := λ _, bind id.\n#[global]\nInstance default_mon_map `{MonadReturn M} `{MonadBind M} : SFmap M | 20 := λ _ _ f, bind (ret ∘ f).\n#[global]\nInstance default_mon_bind `{SFmap M} `{MonadJoin M} : MonadBind M | 20 := λ _ _ f, join ∘ (sfmap f).\n\n#[global]\nHint Extern 0 (ProperProxy (@respectful _ _ _ _) _) =>\n  class_apply @proper_proper_proxy : typeclass_instances.\n\n#[global]\nInstance equiv_ext_equiv `{Equiv A} `{Equiv B} :\n  Setoid A -> Setoid B ->\n  Proper ((equiv ==> equiv) ==> (equiv ==> equiv) ==> flip impl)\n         (@equiv _ (@ext_equiv A _ B _)).\nProof.\n  unfold ext_equiv. repeat (red; intros).\n  assert ((equiv ==> equiv)%signature x x0).\n  eapply transitivity. eauto.\n  eapply transitivity. eauto.\n  eapply symmetry. eauto.\n  eapply H7. eapply H6.\nQed.\n\n#[global]\nInstance equiv_ext_equiv_partial `{Equiv A} `{Equiv B} (f : A -> B) :\n  Setoid A -> Setoid B ->\n  Proper (equiv ==> equiv) f ->\n  Proper ((equiv ==> equiv) ==> flip impl)\n         (@equiv _ (@ext_equiv A _ B _) f).\nProof. intros. partial_application_tactic; eauto. apply equiv_ext_equiv; eauto. Qed.\n\nSection monad.\n  Context `{Monad M}.\n\n  Lemma bind_lunit_applied `{Equiv A} `{Setoid B} `{!Setoid_Morphism (f : A → M B)} (x : A) : \n    ret x ≫= f = f x.\n  Proof. pose proof (setoidmor_a f). now apply bind_lunit. Qed.\n\n  Lemma bind_runit_applied `{Setoid A} (m : M A) : \n    m ≫= ret = m.\n  Proof. now apply bind_runit. Qed.\n\n  Lemma bind_assoc_applied `{Equiv A} `{Equiv B} `{Setoid C} \n       `{!Setoid_Morphism (f : A → M B)} `{!Setoid_Morphism (g : B → M C)} (m : M A) :\n    (m ≫= f) ≫= g = x ← m ; f x ≫= g.\n  Proof. pose proof (setoidmor_a f). now apply bind_assoc. Qed.\n\n  Global Instance ret_mor `{Setoid A} : Setoid_Morphism (@ret _ _ A) := {}.\n  Global Instance bind_mor `{Equiv A} `{Setoid B} `{!Setoid_Morphism (f : A → M B)} :\n    Setoid_Morphism (bind f).\n  Proof. pose proof (setoidmor_a f). split; try apply _. Qed.\n\n  Definition liftM2 `(f: A → B → C) (m : M A) (n : M B) : M C :=\n    x ← m ; y ← n ; ret (f x y).\n\n  Section to_strong_monad.\n  Context `{MonadJoin M} `{SFmap M}\n    (map_proper : ∀ `{Setoid A} `{Setoid B}, Proper (((=) ==> (=)) ==> ((=) ==> (=))) (@sfmap M _ A B))\n    (map_correct : ∀ `{Equiv A} `{Equiv B} `{!Setoid_Morphism (f : A → B)}, sfmap f = bind (ret ∘ f))\n    (join_correct : ∀ `{Setoid A}, join = bind id).\n  Existing Instance map_proper.\n\n  Let bind_correct `{Equiv A} `{Setoid B} `{!Setoid_Morphism (f : A → M B)} : \n    bind f = join ∘ sfmap f.\n  Proof.\n    pose proof (setoidmor_a f). pose proof (setoidmor_b f).\n    rewrite join_correct, map_correct by apply _.\n    rewrite bind_assoc.\n    change (bind f = bind ((bind id ∘ ret) ∘ f)).\n    rewrite bind_lunit.\n    now apply setoids.ext_equiv_refl.\n  Qed.\n\n  Instance: SFunctor M.\n  Proof.\n    split; try apply _.\n     intros A ? ?.\n     rewrite map_correct by apply _. \n     now apply bind_runit.\n    intros A ? B ? C ? f ? g ?.\n    pose proof (setoidmor_a g). pose proof (setoidmor_b g). pose proof (setoidmor_b f).\n    rewrite !map_correct by apply _.\n    rewrite bind_assoc.\n    change (bind (ret ∘ (f ∘ g)) = bind ((bind (ret ∘ f) ∘ ret) ∘ g)).\n    rewrite bind_lunit.\n    now apply setoids.ext_equiv_refl.\n  Qed.\n\n  Instance: ∀ `{Setoid A}, Setoid_Morphism (@join _ _ A).\n  Proof.\n    split; try apply _. intros x y E1. \n    assert (∀ z, join z = bind id z) as E2 by (intros; now apply join_correct).\n    now rewrite !E2, E1.\n  Qed.\n\n  Instance monad_strong_monad: StrongMonad M.\n  Proof.\n    split; try apply _.\n        intros A ? B ? f ?. pose proof (setoidmor_a f). pose proof (setoidmor_b f).\n        rewrite map_correct by apply _.\n        rewrite bind_lunit.\n        now apply setoids.ext_equiv_refl.\n       intros A ? B ? f ?. pose proof (setoidmor_a f). pose proof (setoidmor_b f).\n       rewrite <-bind_correct.\n       rewrite !join_correct by apply _.\n       rewrite map_correct by apply _.\n       rewrite bind_assoc.\n       now apply setoids.ext_equiv_refl.\n      intros A ??. rewrite join_correct by apply _. \n      rewrite bind_lunit.\n      now apply setoids.ext_equiv_refl.\n     intros A ??.\n     rewrite <-bind_correct.\n     rewrite bind_runit.\n     now apply setoids.ext_equiv_refl.\n    intros A ??. rewrite <-bind_correct.\n    rewrite !join_correct by apply _.\n    rewrite bind_assoc.\n    now apply setoids.ext_equiv_refl.\n  Qed.\n\n  Instance monad_full_monad: FullMonad M.\n  Proof. split; try apply _; auto. Qed.\n  End to_strong_monad.\n\n  Instance monad_default_full_monad: FullMonad M.\n  Proof.\n    apply monad_full_monad; unfold sfmap, default_mon_map.\n      intros A ?? B ?? f g E1 m n E2.\n      apply mon_bind_proper.\n       intros x y E3. now apply mon_ret_proper, E1.\n      easy.\n     intros A ? B ? f ??? E. pose proof (setoidmor_a f). pose proof (setoidmor_b f).\n     now rewrite E.\n    intros A ?? ?? E. unfold join, default_mon_join.\n    now rewrite E.\n  Qed.\nEnd monad.\n\nSection strong_monad.\n  Context `{StrongMonad M}.\n\n  Global Instance sret_mor `{Setoid A} : Setoid_Morphism (@ret _ _ A) := {}.\n  Global Instance join_mor `{Setoid A} : Setoid_Morphism (@join _ _ A) := {}.\n\n  Hint Immediate setoidmor_a : typeclass_instances.\n  Hint Immediate setoidmor_b : typeclass_instances.\n\n  Lemma sfmap_ret_applied `{Equiv A} `{Equiv B} `{!Setoid_Morphism (f : A → B)} (x : A) : \n    sfmap f (ret x) = ret (f x).\n  Proof. now apply sfmap_ret. Qed.\n\n  Lemma sfmap_join_applied `{Equiv A} `{Equiv B} `{!Setoid_Morphism (f : A → B)} (m : M (M A)) : \n    sfmap f (join m) = join (sfmap (sfmap f) m).\n  Proof. now apply sfmap_join. Qed.\n\n  Lemma join_ret_applied `{Setoid A} (m : M A) :\n    join (ret m) = m.\n  Proof. now apply join_ret. Qed.\n\n  Lemma join_sfmap_ret_applied `{Setoid A} (m : M A):\n    join (sfmap ret m) = m.\n  Proof. now apply join_sfmap_ret. Qed.\n\n  Lemma join_sfmap_join_applied `{Setoid A} (m : M (M (M A))) : \n    join (sfmap join m) = join (join m).\n  Proof. now apply join_sfmap_join. Qed.\n\n  Section to_monad.\n  Context `{MonadBind M}\n    (bind_proper : ∀ `{Setoid A} `{Setoid B}, Proper (((=) ==> (=)) ==> ((=) ==> (=))) (@bind M _ A B))\n    (bind_correct : ∀ `{Equiv A} `{Setoid B} `{!Setoid_Morphism (f : A → M B)}, bind f = join ∘ sfmap f).\n\n  Instance: ∀ `{Equiv A} `{Setoid B} `{!Setoid_Morphism (f : A → M B)},\n    Setoid_Morphism (bind f).\n  Proof. intros. split; try apply _. Qed.\n\n  Let bind_correct_applied `{Equiv A} `{Setoid B} `{!Setoid_Morphism (f : A → M B)} m :\n    bind f m = join (sfmap f m).\n  Proof. now eapply bind_correct. Qed.\n\n  Instance strong_monad_monad: Monad M.\n  Proof.\n    split; try apply _.\n      intros A ? B ?? f ?. pose proof (setoidmor_a f). pose proof (setoidmor_b f).\n      rewrite bind_correct by apply _.\n      rewrite compose_assoc, sfmap_ret.\n      rewrite <-compose_assoc, join_ret.\n      now apply setoids.ext_equiv_refl.\n     intros A ? ?.\n     rewrite bind_correct by apply _.\n     now apply join_sfmap_ret.\n    intros A ? B ? C ?? f ? g ? m n E. pose proof (setoidmor_a f). pose proof (setoidmor_a g).\n    unfold compose at 1. rewrite !bind_correct_applied.\n    rewrite bind_correct by apply _.\n    rewrite sfmap_join_applied.\n    rewrite !sfmap_comp_applied.\n    rewrite join_sfmap_join_applied.\n    now rewrite E.\n  Qed.\n\n  Instance strong_monad_full_monad: FullMonad M.\n  Proof. split; try apply _; auto. Qed.\n  End to_monad.\n\n  Instance strong_monad_default_full_monad: FullMonad M.\n  Proof.\n    apply strong_monad_full_monad; unfold bind, default_mon_bind.\n     intros A ?? B ?? f g E1 m n E2.\n     apply smon_join_proper. apply sfmap_proper; intuition.\n    intros A ? B ?? f ? ?? E.\n    now rewrite E.\n  Qed.\nEnd strong_monad.\n\nSection full_monad.\n  Context `{FullMonad M}.\n\n  Lemma bind_as_join_sfmap_applied `{Equiv A} `{Setoid B} `{!Setoid_Morphism (f : A → M B)} (m : M A) : \n    m ≫= f = join (sfmap f m).\n  Proof. pose proof (setoidmor_a f). now  apply bind_as_join_sfmap. Qed.\n\n  Lemma sfmap_as_bind_ret `{Equiv A} `{Equiv B} `{!Setoid_Morphism (f : A → B)} : \n     sfmap f = bind (ret ∘ f).\n  Proof.\n    pose proof (setoidmor_a f). pose proof (setoidmor_b f).\n    rewrite bind_as_join_sfmap.\n    rewrite sfmap_comp.\n    rewrite <-compose_assoc.\n    rewrite join_sfmap_ret.\n    now apply setoids.ext_equiv_refl.\n  Qed.\n\n  Lemma sfmap_as_bind_ret_applied `{Equiv A} `{Equiv B} `{!Setoid_Morphism (f : A → B)} (m : M A) : \n    sfmap f m = x ← m ; ret (f x).\n  Proof. pose proof (setoidmor_a f). now apply sfmap_as_bind_ret. Qed.\n\n  Lemma join_as_bind `{Setoid A} : \n    join = bind id.\n  Proof.\n    rewrite bind_as_join_sfmap.\n    rewrite sfmap_id.\n    now apply setoids.ext_equiv_refl.\n  Qed.\n\n  Lemma join_as_bind_applied `{Setoid A} (m : M (M A)) : \n    join m = m ≫= id.\n  Proof. now apply join_as_bind. Qed.\n\n  Lemma join_spec_applied_alt `{Setoid A} (m : M (M A)) : \n    join m = x ← m ; x.\n  Proof. now apply join_as_bind. Qed.\n\n  Lemma bind_twice `{Equiv A} `{Equiv B} `{Setoid C} \n       `{!Setoid_Morphism (f : B → M C)} `{!Setoid_Morphism (g : A → M B)} :\n    bind (bind f) = bind f ∘ join.\n  Proof.\n    pose proof (setoidmor_a f). pose proof (setoidmor_b f).\n    pose proof (setoidmor_b g).\n    rewrite join_as_bind.\n    rewrite bind_assoc.\n    now apply setoids.ext_equiv_refl.\n  Qed.\n\n  Lemma bind_twice_applied `{Equiv A} `{Equiv B} `{Setoid C} \n       `{!Setoid_Morphism (f : B → M C)} `{!Setoid_Morphism (g : A → M B)} (m : M (M B)) :\n    m ≫= bind f = join m ≫= f.\n  Proof. pose proof (setoidmor_a f). now apply bind_twice. Qed. \n\n  Lemma bind_join `{Setoid A} : \n    bind join = join ∘ join.\n  Proof.\n    rewrite !join_as_bind.\n    rewrite bind_assoc.\n    now apply setoids.ext_equiv_refl.\n  Qed.\n\n  Lemma bind_join_applied `{Setoid A} (m : M (M (M A))) : \n    m ≫= join = join (join m).\n  Proof. now apply bind_join. Qed.\nEnd full_monad.\n", "meta": {"author": "coq-community", "repo": "math-classes", "sha": "c11eb05a1e58a7293ef9a9a046ca02a9fd5b44bc", "save_path": "github-repos/coq/coq-community-math-classes", "path": "github-repos/coq/coq-community-math-classes/math-classes-c11eb05a1e58a7293ef9a9a046ca02a9fd5b44bc/theory/monads.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2652040369885607}}
{"text": "(* En este archivo se definen lemas auxiliares utilizados en\n* la demostración de las propiedades postuladas *)\nRequire Export Exec.\nRequire Export Estado.\nRequire Export Operaciones.\nRequire Export Semantica.\nRequire Export ErrorManagement.\nRequire Export DefBasicas.\nRequire Export Implementacion.\nRequire Export ValidityInvariance.\nRequire Export Soundness.\n\nLemma stepIsInvariant :forall (s:System) (sValid:validstate s) (act:Action), validstate (system (step s act)).\nProof.\n    intros.\n    apply (validityIsInvariant s (system (step s act)) act (response (step s act)));auto.\n    apply stepIsSound;auto.\nQed.\n\nLemma grantPreservesEnv : forall (s s':System) (p:Perm) (a:idApp), environment s=environment s'-> environment s = environment (system (step s' (grant p a))).\nProof.\n    intros.\n    unfold step.\n    unfold grant_safe.\n    case_eq (grant_pre p a s');intros;simpl;auto.\nQed.\n\nLemma revokePreservesEnv : forall (s s':System) (p:Perm) (a:idApp), environment s=environment s'-> environment s = environment (system (step s' (revoke p a))).\nProof.\n    intros.\n    unfold step.\n    unfold revoke_safe.\n    case_eq (revoke_pre p a s');intros;simpl;auto.\nQed.\n\nLemma grantPPreservesEnv : forall (s s':System) (ic:iCmp) (cp:CProvider) (a:idApp) (u:uri) (pt:PType), environment s=environment s'-> environment s = environment (system (step s' (grantP ic cp a u pt))).\nProof.\n    intros.\n    unfold step.\n    unfold grantP_safe.\n    case_eq (grantP_pre ic cp a u pt s');intros;simpl;auto.\nQed.\n\n\nLemma grantPreservesResCont : forall (s s':System) (p:Perm) (a:idApp), resCont (state s)=resCont (state s')-> resCont (state s) = resCont (state (system (step s' (grant p a)))).\nProof.\n    intros.\n    unfold step.\n    unfold grant_safe.\n    case_eq (grant_pre p a s');intros;simpl;auto.\nQed.\n\nLemma revokePreservesResCont : forall (s s':System) (p:Perm) (a:idApp), resCont (state s)=resCont (state s')-> resCont (state s )= resCont (state (system (step s' (revoke p a)))).\nProof.\n    intros.\n    unfold step.\n    unfold revoke_safe.\n    case_eq (revoke_pre p a s');intros;simpl;auto.\nQed.\n\nLemma grantPPreservesResCont : forall (s s':System) (ic:iCmp) (cp:CProvider) (a:idApp) (u:uri) (pt:PType), resCont (state s)=resCont (state s')-> resCont (state s) = resCont (state (system (step s' (grantP ic cp a u pt)))).\nProof.\n    intros.\n    unfold step.\n    unfold grantP_safe.\n    case_eq (grantP_pre ic cp a u pt s');intros;simpl;auto.\nQed.\n\n\nLemma grantPreservesRunning : forall (s s':System) (p:Perm) (a:idApp), running (state s)=running (state s')-> running (state s) = running (state (system (step s' (grant p a)))).\nProof.\n    intros.\n    unfold step.\n    unfold grant_safe.\n    case_eq (grant_pre p a s');intros;simpl;auto.\nQed.\n\nLemma revokePreservesRunning : forall (s s':System) (p:Perm) (a:idApp), running (state s)=running (state s')-> running (state s )= running (state (system (step s' (revoke p a)))).\nProof.\n    intros.\n    unfold step.\n    unfold revoke_safe.\n    case_eq (revoke_pre p a s');intros;simpl;auto.\nQed.\n\nLemma grantPPreservesRunning : forall (s s':System) (ic:iCmp) (cp:CProvider) (a:idApp) (u:uri) (pt:PType), running (state s)=running (state s')-> running (state s) = running (state (system (step s' (grantP ic cp a u pt)))).\nProof.\n    intros.\n    unfold step.\n    unfold grantP_safe.\n    case_eq (grantP_pre ic cp a u pt s');intros;simpl;auto.\nQed.\n\n\nLemma grantPreservesDelPPerms : forall (s s':System) (p:Perm) (a:idApp), delPPerms (state s)=delPPerms (state s')-> delPPerms (state s) = delPPerms (state (system (step s' (grant p a)))).\nProof.\n    intros.\n    unfold step.\n    unfold grant_safe.\n    case_eq (grant_pre p a s');intros;simpl;auto.\nQed.\n\nLemma revokePreservesDelPPerms : forall (s s':System) (p:Perm) (a:idApp), delPPerms (state s)=delPPerms (state s')-> delPPerms (state s )= delPPerms (state (system (step s' (revoke p a)))).\nProof.\n    intros.\n    unfold step.\n    unfold revoke_safe.\n    case_eq (revoke_pre p a s');intros;simpl;auto.\nQed.\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/PropertiesAuxFuns.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.26520403043009194}}
{"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 dummyTransaction : TransactionLRecord := Eval compute in default. \n\nDefinition ETR_1 l u (dest :  address) (value :  uint128) (bounce :  boolean) (allBalance :  boolean) (payload :  cell_) (stateInit :  optional  ( TvmCell )) : Prop := \n  let transactions := toValue (eval_state (sRReader (m_transactions_right rec def) ) l) in\n  let lifetime := uint2N (toValue (eval_state (sRReader (m_lifetime_right rec def) ) l)) in\n  let MAX_CLEANUP_TXNS := uint2N (toValue (eval_state (sRReader (MAX_CLEANUP_TXNS_right rec def) ) l)) in\n  let m_updateRequests := toValue (eval_state (sRReader (m_updateRequests_right rec def) ) l) in\n  let tvm_now := uint2N (toValue (eval_state (sRReader || now ||) l)) in\n  let id := (getPruvendoRecord Transaction_ι_id u) in\n  let l' := exec_state (Uinterpreter (_removeExpiredTransactions rec def)) l in \n  let m_transactions := toValue (eval_state (sRReader (m_transactions_right rec def) ) l') in\n  isError (eval_state (Uinterpreter (submitTransaction rec def dest value bounce allBalance payload stateInit)) l) = false -> \n  hmapIsMember id m_updateRequests = true ->\n  (N.shiftr (uint2N id) 32) + lifetime <= tvm_now  ->\n  length_ (xHMapFilter (fun _k t => (eqb (getPruvendoRecord Transaction_ι_id t) id)) transactions) < MAX_CLEANUP_TXNS  <->\n  hmapIsMember id transactions = true /\\\n  hmapIsMember id m_transactions = false.\n\n\nDefinition MTS_1 l (dest :  address) (value :  uint128) (bounce :  boolean) (allBalance :  boolean) (payload :  cell_) (stateInit :  optional  ( TvmCell )) : Prop := \n  let custodians := toValue (eval_state (sRReader (m_custodians_right rec def) ) l) in\n  let msgPubkey := toValue (eval_state (sRReader || msg->pubkey() ||) l) in\n  correctState l ->\n  isError (eval_state (Uinterpreter (submitTransaction rec def dest value bounce allBalance payload stateInit)) l) = false ->\n  hmapIsMember msgPubkey custodians = true.\n\nDefinition MTS_2 l id (dest :  address) (value :  uint128) (bounce :  boolean) (allBalance :  boolean) (payload :  cell_) (stateInit :  optional  ( TvmCell )) : Prop := \n  let custodians := toValue (eval_state (sRReader (m_custodians_right rec def) ) l) in\n  let msgPubkey := toValue (eval_state (sRReader || msg->pubkey() ||) l) in\n  let l' := exec_state (Uinterpreter (submitTransaction rec def dest value bounce allBalance payload stateInit)) l in \n  let transactions := toValue (eval_state (sRReader (m_transactions_right rec def) ) l') in\n  let u := xMaybeMapDefault (fun x => x) (hmapLookup id transactions) dummyTransaction  in  \n  correctState l ->\n  isError (eval_state (Uinterpreter (submitTransaction rec def dest value bounce allBalance payload stateInit)) l) = true ->\n  hmapIsMember msgPubkey custodians = true ->\n  hmapIsMember id transactions = true -> \n  ETR_1 l' u dest value bounce allBalance payload stateInit. \n\nDefinition MTS_3 l (dest :  address) (value :  uint128) (bounce :  boolean) (allBalance :  boolean) (payload :  cell_) (stateInit :  optional  ( TvmCell )) : Prop := \n  let custodians := toValue (eval_state (sRReader (m_custodians_right rec def) ) l) in\n  let requestsMask := toValue (eval_state (sRReader (m_requestsMask_right rec def) ) l) in \n  let msgPubkey := toValue (eval_state (sRReader || msg->pubkey() ||) l) in\n  let i := uint2N (hmapFindWithDefault (Build_XUBInteger 0) msgPubkey custodians) in\n  let bitsMask := N.land (N.shiftr (uint2N requestsMask) (8 * i)) 255 in\n  let transactions := toValue (eval_state (sRReader (m_transactions_right rec def) ) l) in\n  let lifetime := uint2N (toValue (eval_state (sRReader (m_lifetime_right rec def) ) l)) in\n  let MAX_QUEUED_REQUESTS := uint2N (toValue (eval_state (sRReader (MAX_QUEUED_REQUESTS_right rec def) ) l)) in\n  let tvm_now := uint2N (toValue (eval_state (sRReader || now ||) l)) in\n  let expiredTransactions := xHMapFilter (fun k v =>\n    let index := uint2N (getPruvendoRecord Transaction_ι_index v) in\n    andb (N.eqb index i) (N.leb ((N.shiftr (uint2N k) 32) + lifetime) tvm_now)\n  ) transactions in\n  let bitsMask' := bitsMask - length_ expiredTransactions in\n  correctState l ->\n  isError (eval_state (Uinterpreter (submitTransaction rec def dest value bounce allBalance payload stateInit)) l) = false ->\n  bitsMask' < MAX_QUEUED_REQUESTS. \n\nDefinition MTS_4 l id (dest :  address) (value :  uint128) (bounce :  boolean) (allBalance :  boolean) (payload :  cell_) (stateInit :  optional  ( TvmCell )) : Prop := \n  let FLAG_IGNORE_ERRORS := uint2N (toValue (eval_state (sRReader (FLAG_IGNORE_ERRORS_right rec def) ) l)) in\n  let FLAG_SEND_ALL_REMAINING := uint2N (toValue (eval_state (sRReader (FLAG_SEND_ALL_REMAINING_right rec def) ) l)) in\n  let custodians := toValue (eval_state (sRReader (m_custodians_right rec def) ) l) in\n  let requestsMask :=  (toValue (eval_state (sRReader (m_requestsMask_right rec def) ) l)) in\n  let m_defaultRequiredConfirmations :=  uint2N (toValue (eval_state (sRReader (m_defaultRequiredConfirmations_right rec def) ) l)) in (* ???? *)\n  let msgPubkey := toValue (eval_state (sRReader || msg->pubkey() ||) l) in\n  let l' := exec_state (Uinterpreter (submitTransaction rec def dest value bounce allBalance payload stateInit)) l in\n  let messqueue := toValue ((eval_state (sRReader (ULtoRValue (IDefault_left rec def)))) l') in \n  let stateInit' := xMaybeMapDefault (fun x => x) stateInit default in\n  let mes := EmptyMessage IDefault (Build_XUBInteger 0, (bounce, (Build_XUBInteger (N.lor FLAG_IGNORE_ERRORS FLAG_SEND_ALL_REMAINING) , (payload, stateInit')))) in\n  let transactions := toValue (eval_state (sRReader (m_transactions_right rec def) ) l') in\n  let u := xMaybeMapDefault (fun x => x) (hmapLookup id transactions) dummyTransaction  in\n  let i := uint2N (hmapFindWithDefault (Build_XUBInteger 0) msgPubkey custodians) in\n  let bitsMask := N.land (N.shiftr (uint2N requestsMask) (8 * i)) 255 in\n  let lifetime := uint2N (toValue (eval_state (sRReader (m_lifetime_right rec def) ) l)) in\n  let MAX_QUEUED_REQUESTS := uint2N (toValue (eval_state (sRReader (MAX_QUEUED_REQUESTS_right rec def) ) l)) in\n  let tvm_now := uint2N (toValue (eval_state (sRReader || now ||) l)) in\n  let expiredTransactions := xHMapFilter (fun k v =>\n    let index := uint2N (getPruvendoRecord Transaction_ι_index v) in\n    andb (N.eqb index i) (N.leb ((N.shiftr (uint2N k) 32) + lifetime) tvm_now)\n  ) transactions in\n  let bitsMask' := bitsMask - length_ expiredTransactions in\n  correctState l ->\n  isError (eval_state (Uinterpreter (submitTransaction rec def dest value bounce allBalance payload stateInit)) l) = false ->\n  hmapIsMember msgPubkey custodians = true -> \n  ETR_1 l' u dest value bounce allBalance payload stateInit -> \n  bitsMask' < MAX_QUEUED_REQUESTS -> \n  m_defaultRequiredConfirmations < 2 ->\n  allBalance = true ->\n  isOnlyMessage messqueue = true /\\\n  isMessageSent mes dest 0 messqueue = true . \n\n\nDefinition MTS_5 l id (dest :  address) (value :  uint128) (bounce :  boolean) (allBalance :  boolean) (payload :  cell_) (stateInit :  optional  ( TvmCell )) : Prop := \n  let FLAG_IGNORE_ERRORS := uint2N (toValue (eval_state (sRReader (FLAG_IGNORE_ERRORS_right rec def) ) l)) in\n  let FLAG_PAY_FWD_FEE_FROM_BALANCE := uint2N (toValue (eval_state (sRReader (FLAG_PAY_FWD_FEE_FROM_BALANCE_right rec def) ) l)) in\n  let custodians := toValue (eval_state (sRReader (m_custodians_right rec def) ) l) in\n  let requestsMask := (toValue (eval_state (sRReader (m_requestsMask_right rec def) ) l)) in\n  let m_defaultRequiredConfirmations :=  uint2N (toValue (eval_state (sRReader (m_defaultRequiredConfirmations_right rec def) ) l)) in (* ???? *)\n  let msgPubkey := toValue (eval_state (sRReader || msg->pubkey() ||) l) in\n  let l' := exec_state (Uinterpreter (submitTransaction rec def dest value bounce allBalance payload stateInit)) l in\n  let messqueue := toValue ((eval_state (sRReader (ULtoRValue (IDefault_left rec def)))) l') in \n  let stateInit' := xMaybeMapDefault (fun x => x) stateInit default in\n  let mes := EmptyMessage IDefault (value, (bounce, ((Build_XUBInteger  (N.lor FLAG_IGNORE_ERRORS FLAG_PAY_FWD_FEE_FROM_BALANCE)), (payload, stateInit')))) in\n  let transactions := toValue (eval_state (sRReader (m_transactions_right rec def) ) l') in\n  let u := xMaybeMapDefault (fun x => x) (hmapLookup id transactions) dummyTransaction  in\n  let i := uint2N (hmapFindWithDefault (Build_XUBInteger 0) msgPubkey custodians) in\n  let bitsMask := N.land (N.shiftr (uint2N requestsMask) (8 * i)) 255 in\n  let lifetime := uint2N (toValue (eval_state (sRReader (m_lifetime_right rec def) ) l)) in\n  let MAX_QUEUED_REQUESTS := uint2N (toValue (eval_state (sRReader (MAX_QUEUED_REQUESTS_right rec def) ) l)) in\n  let tvm_now := uint2N (toValue (eval_state (sRReader || now ||) l)) in\n  let expiredTransactions := xHMapFilter (fun k v =>\n    let index := uint2N (getPruvendoRecord Transaction_ι_index v) in\n    andb (N.eqb index i) (N.leb ((N.shiftr (uint2N k) 32) + lifetime) tvm_now)\n  ) transactions in\n  let bitsMask' := bitsMask - length_ expiredTransactions in\n  correctState l ->\n  isError (eval_state (Uinterpreter (submitTransaction rec def dest value bounce allBalance payload stateInit)) l) = false ->\n  hmapIsMember msgPubkey custodians = true -> \n  ETR_1 l' u dest value bounce allBalance payload stateInit -> \n  bitsMask' < MAX_QUEUED_REQUESTS ->\n  m_defaultRequiredConfirmations < 2 ->\n  allBalance = false ->\n  isOnlyMessage messqueue = true /\\\n  isMessageSent mes dest 0 messqueue = true . \n\n(* MTS_6_1 checked as part of correctState *)\n(* MTS_6_2 checked as part of correctState *)\n\nDefinition MTS_6_3  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  let custodians := toValue (eval_state (sRReader (m_custodians_right rec def) ) l) in\n  let transactions := toValue (eval_state (sRReader (m_transactions_right rec def) ) l) in\n  let transactions' := toValue (eval_state (sRReader (m_transactions_right rec def) ) l') in\n  let newTransactions := xHMapFilter (fun k v =>\n    negb (hmapIsMember k transactions)\n  ) transactions' in\n  let transaction := snd (hd (Build_XUBInteger 0, dummyTransaction) (unwrap newTransactions)) in\n  let mask := uint2N (getPruvendoRecord Transaction_ι_confirmationsMask transaction) in\n  let creator := getPruvendoRecord Transaction_ι_creator transaction in\n  let index := getPruvendoRecord Transaction_ι_index transaction in\n  let bounce' := getPruvendoRecord Transaction_ι_bounce transaction in\n  let dest' := getPruvendoRecord Transaction_ι_dest transaction in\n  let payload' := getPruvendoRecord Transaction_ι_payload transaction in\n  let value' := getPruvendoRecord Transaction_ι_value transaction in\n  let flags := getPruvendoRecord Transaction_ι_sendFlags transaction in\n  let IGNORE_ERRORS := uint2N (toValue (eval_state (sRReader (FLAG_IGNORE_ERRORS_right rec def) ) l)) in\n  let SEND_ALL_REMAINING := uint2N (toValue (eval_state (sRReader (FLAG_SEND_ALL_REMAINING_right rec def) ) l)) in\n  let PAY_FWD_FEE_FROM_BALANCE := uint2N (toValue (eval_state (sRReader (FLAG_PAY_FWD_FEE_FROM_BALANCE_right rec def) ) l)) in\n  let msgPubkey := toValue (eval_state (sRReader || msg->pubkey() ||) l) in\n  let i := uint2N (hmapFindWithDefault (Build_XUBInteger 0) msgPubkey custodians) in\n  let m_defaultRequiredConfirmations := uint2N (toValue (eval_state (sRReader (m_defaultRequiredConfirmations_right rec def) ) l)) in\n  let requestsMask := toValue (eval_state (sRReader (m_requestsMask_right rec def) ) l) in \n  let bitsMask := N.land (N.shiftr (uint2N requestsMask) (8 * i)) 255 in\n  let lifetime := uint2N (toValue (eval_state (sRReader (m_lifetime_right rec def) ) l)) in\n  let tvm_now := uint2N (toValue (eval_state (sRReader || now ||) l)) in\n  let expiredTransactions := xHMapFilter (fun k v =>\n    let index := uint2N (getPruvendoRecord Transaction_ι_index v) in\n    andb (N.eqb index i) (N.leb ((N.shiftr (uint2N k) 32) + lifetime) tvm_now)\n  ) transactions in\n  let bitsMask' := bitsMask - length_ expiredTransactions in\n  let MAX_QUEUED_REQUESTS := uint2N (toValue (eval_state (sRReader (MAX_QUEUED_REQUESTS_right rec def) ) l)) in\n  correctState l ->\n  m_defaultRequiredConfirmations > 1 ->\n  hmapIsMember msgPubkey custodians = true ->\n  bitsMask' < MAX_QUEUED_REQUESTS ->\n  length_ newTransactions = 1 /\\\n  mask = N.shiftl 1 i /\\\n  creator = msgPubkey /\\\n  i = uint2N index /\\\n  dest = dest' /\\\n  bounce = bounce' /\\\n  payload = payload' /\\\n  (allBalance = true ->\n   uint2N value' = 0 /\\ \n   uint2N flags = N.lor IGNORE_ERRORS SEND_ALL_REMAINING\n  ) /\\\n  (allBalance = false ->\n   value' = value /\\\n   uint2N flags = N.lor IGNORE_ERRORS PAY_FWD_FEE_FROM_BALANCE).\n\nDefinition equalExceptLocalExpired (l l': LedgerLRecord rec) := \n  let transactions := toValue (eval_state (sRReader (m_transactions_right rec def) ) l) in\n  let lifetime := uint2N (toValue (eval_state (sRReader (m_lifetime_right rec def) ) l)) in\n  let tvm_now := uint2N (toValue (eval_state (sRReader || now ||) l)) in\n  let newTransactions : field_type _m_transactions := xHMapFilter (fun k v =>\n    negb (N.leb ((N.shiftr (uint2N k) 32) + lifetime) tvm_now)\n  ) transactions in\n  ledgerEqb {$$ {$$ l with Ledger_MainState := \n  {$$ {$$\n   getPruvendoRecord Ledger_MainState l\n   with _m_transactions := newTransactions $$} : @field_type (LedgerLRecord rec) _ _ Ledger_MainState with \n   _m_requestsMask := getPruvendoRecord _m_requestsMask \n     (getPruvendoRecord Ledger_MainState l')\n   \n $$} \n$$} with Ledger_LocalState := getPruvendoRecord Ledger_LocalState l' \n$$} l'.\n\nDefinition equalExceptLocal (l l': LedgerLRecord rec) := \n  ledgerEqb {$$ l with Ledger_LocalState := getPruvendoRecord Ledger_LocalState l' $$} l'.\n\nDefinition MTS_7 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  let lifetime := uint2N (toValue (eval_state (sRReader (m_lifetime_right rec def) ) l)) in\n  let tvm_now := uint2N (toValue (eval_state (sRReader || now ||) l)) in\n  correctState l ->\n  isError (eval_state (Uinterpreter (submitTransaction rec def dest value bounce allBalance payload stateInit)) l) = true ->\n  equalExceptLocalExpired l l' = true \\/\n  equalExceptLocal l l' = true. ", "meta": {"author": "Pruvendo", "repo": "multisig2", "sha": "d4f8242ecfb79b9f8f61dcbc9d19f889c7051d6c", "save_path": "github-repos/coq/Pruvendo-multisig2", "path": "github-repos/coq/Pruvendo-multisig2/multisig2-d4f8242ecfb79b9f8f61dcbc9d19f889c7051d6c/src/ursus/MTS/Props.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757646010190477, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.26512734150295386}}
{"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.\n\nRequire Import MemoryProps.\nRequire Import Mapping.\n\nSet Implicit Arguments.\n\nSection CAPFLEX.\n\n  Record cap_flex (mem1 mem2: Memory.t) (tm: TimeMap.t): Prop :=\n    {\n      cap_flex_le: Memory.le mem1 mem2;\n      cap_flex_middle: forall loc from1 to1 from2 to2\n                              (ADJ: Memory.adjacent loc from1 to1 from2 to2 mem1)\n                              (TO: Time.lt to1 from2),\n          Memory.get loc from2 mem2 = Some (to1, Message.reserve);\n      cap_flex_back: forall loc, Memory.get loc (tm loc) mem2 =\n                                 Some (Memory.max_ts loc mem1, Message.reserve);\n      cap_flex_complete: forall loc from to msg\n                               (GET1: Memory.get loc to mem1 = None)\n                               (GET2: Memory.get loc to mem2 = Some (from, msg)),\n          (exists f m, Memory.get loc from mem1 = Some (f, m));\n    }\n  .\n\n  Lemma cap_flex_inv\n        mem1 mem2 tm\n        loc from to msg\n        (CLOSED: Memory.closed mem1)\n        (CAP: cap_flex mem1 mem2 tm)\n        (GET: Memory.get loc to mem2 = Some (from, msg))\n        (TM: forall loc, Time.lt (Memory.max_ts loc mem1) (tm loc))\n    :\n    Memory.get loc to mem1 = Some (from, msg) \\/\n    (Memory.get loc to mem1 = None /\\\n     exists from1 to2,\n        Memory.adjacent loc from1 from to to2 mem1 /\\\n        Time.lt from to /\\\n        msg = Message.reserve) \\/\n    (Memory.get loc to mem1 = None /\\\n     from = Memory.max_ts loc mem1 /\\\n     to = tm loc /\\\n     msg = Message.reserve).\n  Proof.\n    inv CAP. move GET at bottom.\n    destruct (Memory.get loc to mem1) as [[]|] eqn:GET1.\n    { exploit cap_flex_le0; eauto. i.\n      rewrite GET in x. inv x. auto. }\n    right. exploit cap_flex_complete0; eauto. i. des.\n    exploit Memory.max_ts_spec; eauto. i. des. inv MAX.\n    - left.\n      exploit Memory.adjacent_exists; try eapply H; eauto. i. des.\n      assert (LT: Time.lt from from2).\n      { clear cap_flex_middle0 cap_flex_back0 cap_flex_complete0 GET0 H.\n        (* clear MIDDLE BACK COMPLETE GET0 H. *)\n        inv x1. rewrite GET0 in x. inv x.\n        exploit Memory.get_ts; try exact GET2. i. des.\n        { subst. inv TS. }\n        destruct (Time.le_lt_dec from2 from); auto.\n        inv l.\n        - exfalso.\n          exploit Memory.get_ts; try exact GET0. i. des.\n          { subst. inv H. }\n          exploit Memory.get_disjoint; [exact GET0|exact GET2|..]. i. des.\n          { subst. timetac. }\n          apply (x2 from); econs; ss.\n          + refl.\n          + econs. auto.\n        - exfalso. inv H.\n          exploit cap_flex_le0; try exact GET2. i.\n          exploit Memory.get_ts; try exact GET. i. des.\n          { subst. rewrite GET1 in GET0. inv GET0. }\n          exploit Memory.get_disjoint; [exact GET|exact x|..]. i. des.\n          { subst. rewrite GET1 in GET2. inv GET2. }\n          destruct (Time.le_lt_dec to to2).\n          + apply (x3 to); econs; ss. refl.\n          + apply (x3 to2); econs; ss.\n            * econs. auto.\n            * refl.\n      }\n      exploit cap_flex_middle0; try eapply x1; eauto. i.\n      destruct (Time.eq_dec to from2).\n      + subst. rewrite GET in x0. inv x0. esplits; eauto.\n      + exfalso. inv x1.\n        exploit Memory.get_ts; try exact GET. i. des.\n        { subst. rewrite GET1 in x. inv x. }\n        exploit Memory.get_ts; try exact x0. i. des.\n        { subst. exploit cap_flex_le0; try exact GET3. i.\n          exploit Memory.get_disjoint; [exact GET|exact x1|..]. i. des.\n          { subst. rewrite GET1 in GET3. inv GET3. }\n          destruct (Time.le_lt_dec to to2).\n          - apply (x4 to); econs; ss. refl.\n          - apply (x4 to2); econs; ss.\n            + econs. auto.\n            + refl.\n        }\n        exploit Memory.get_disjoint; [exact GET|exact x0|..]. i. des; try congr.\n        destruct (Time.le_lt_dec to from2).\n        * apply (x4 to); econs; ss. refl.\n        * apply (x4 from2); econs; ss.\n          { econs. auto. }\n          { refl. }\n    - right. inv H. do 2 (split; auto).\n      rewrite GET0 in x. inv x.\n      specialize (cap_flex_back0 loc).\n      exploit Memory.get_ts; try exact GET. i. des; try congr.\n      exploit Memory.get_disjoint; [exact GET|exact cap_flex_back0|..]. i. des.\n      { subst. esplits; eauto. }\n      exfalso.\n      destruct (Time.le_lt_dec to (tm loc)).\n      + apply (x1 to); econs; ss. refl.\n      + apply (x1 (tm loc)); econs; s;\n          eauto using TM; try refl.\n        econs. ss.\n  Qed.\n\n  Lemma cap_flex_exists\n        mem1 tm\n        (CLOSED1: Memory.closed mem1)\n        (TM: forall loc, Time.lt (Memory.max_ts loc mem1) (tm loc))\n    :\n      exists mem2, (<<CAP: cap_flex mem1 mem2 tm>>).\n  Proof.\n    hexploit Memory.cap_exists; eauto. i. des.\n    hexploit (@choice\n                Loc.t Cell.t\n                (fun loc cell =>\n                   forall ts,\n                     Cell.get ts cell =\n                     if (Time.eq_dec ts (tm loc))\n                     then Some (Memory.max_ts loc mem1, Message.reserve)\n                     else if (Time.eq_dec ts (Time.incr (Memory.max_ts loc mem1)))\n                          then None\n                          else Memory.get loc ts mem2)).\n    { intros loc.\n      hexploit (@Cell.remove_exists (mem2 loc)).\n      { inv CAP. eapply BACK. } i. des.\n      hexploit (@Cell.add_exists cell2 (Memory.max_ts loc mem1) (tm loc) Message.reserve).\n      { i. erewrite Cell.remove_o in GET2; eauto. des_ifs.\n        eapply Memory.cap_inv in GET2; eauto. des; clarify.\n        { symmetry. eapply interval_le_disjoint.\n          eapply Memory.max_ts_spec in GET2. des. auto. }\n        { inv GET0. symmetry. eapply interval_le_disjoint.\n          transitivity to0.\n          { eapply memory_get_ts_le; eauto. }\n          { eapply Memory.max_ts_spec in GET4. des. auto. }\n        }\n      }\n      { eauto. }\n      { econs. } i. des.\n      exists cell0. i.\n      erewrite Cell.add_o; eauto. erewrite Cell.remove_o; eauto. des_ifs. }\n    intros [mem3 SPEC].\n\n    exists mem3. dup CAP. inv CAP. econs.\n    { ii. unfold Memory.get. rewrite SPEC. des_ifs.\n      { eapply Memory.max_ts_spec in LHS. des.\n        exfalso. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n        { eapply TM. }\n        { eapply MAX. }\n      }\n      { eapply Memory.max_ts_spec in LHS. des.\n        exfalso. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n        { eapply Time.incr_spec. }\n        { eapply MAX. }\n      }\n      { eapply SOUND; auto. }\n    }\n    { i. unfold Memory.get. erewrite SPEC. dup ADJ. inv ADJ. des_ifs.\n      { dup GET2. apply Memory.max_ts_spec in GET2. des.\n        apply Memory.get_ts in GET0. des; subst.\n        { exfalso. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n          { eapply TS. }\n          { eapply Time.bot_spec. }\n        }\n        { exfalso. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n          { eapply GET0. } etrans.\n          { eapply MAX. }\n          { left. eauto. }\n        }\n      }\n      { dup GET2. apply Memory.max_ts_spec in GET2. des.\n        apply Memory.get_ts in GET0. des; subst.\n        { exfalso. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n          { eapply TS. }\n          { eapply Time.bot_spec. }\n        }\n        { exfalso. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n          { eapply GET0. } etrans.\n          { eapply MAX. }\n          { left. eapply Time.incr_spec. }\n        }\n      }\n      { eapply MIDDLE; eauto. }\n    }\n    { i. unfold Memory.get. erewrite SPEC. des_ifs. }\n    { i. unfold Memory.get in GET2. rewrite SPEC in GET2. des_ifs.\n      { hexploit (@Memory.max_ts_spec loc).\n        { inv CLOSED1. eapply INHABITED. }\n        i. des. eauto. }\n      { eapply COMPLETE; eauto. }\n    }\n  Qed.\n\n  Lemma cap_cap_flex mem1 mem2\n        (CAP: Memory.cap mem1 mem2)\n    :\n      cap_flex mem1 mem2 (fun loc => Time.incr (Memory.max_ts loc mem1)).\n  Proof.\n    inv CAP. econs; eauto.\n  Qed.\n\n  Lemma cap_flex_max_ts mem1 mem2 tm\n        (CLOSED: Memory.closed mem1)\n        (CAP: cap_flex mem1 mem2 tm)\n        (TM: forall loc, Time.lt (Memory.max_ts loc mem1) (tm loc))\n    :\n      forall loc,\n        Memory.max_ts loc mem2 = tm loc.\n  Proof.\n    i. set (BACK:=(cap_flex_back CAP) loc).\n    exploit Memory.max_ts_spec; try exact BACK. i. des.\n    apply TimeFacts.antisym; ss.\n    destruct (Time.le_lt_dec (Memory.max_ts loc mem2) (tm loc)); ss.\n    exploit cap_flex_inv; try exact GET; eauto. i. des.\n    - exploit Memory.max_ts_spec; try exact x0. i. des.\n      exploit TimeFacts.lt_le_lt; try exact l; try exact MAX0. i.\n      specialize (TM loc). rewrite x1 in TM. timetac.\n    - inv x1. exploit Memory.get_ts; try exact GET2. i. des.\n      { rewrite x1 in *. inv l. }\n      exploit Memory.max_ts_spec; try exact GET2. i. des.\n      exploit TimeFacts.lt_le_lt; try exact x1; try exact MAX0. i.\n      rewrite x3 in l. specialize (TM loc). rewrite l in TM. timetac.\n    - subst. rewrite x2 in *. timetac.\n  Qed.\n\n  Lemma cap_flex_covered\n        mem0 mem1 tm\n        (CAP: cap_flex mem0 mem1 tm)\n        (CLOSED: Memory.closed mem0)\n        (TM: forall loc, Time.lt (Memory.max_ts loc mem0) (tm loc))\n        loc to\n    :\n      Interval.mem (Time.bot, (tm loc)) to\n      <->\n      covered loc to mem1.\n  Proof.\n    split; i.\n    {\n      inv H. set (@cell_elements_least\n                             (mem0 loc)\n                             (fun to' => Time.le to to')). des; cycle 1.\n      { destruct (Time.le_lt_dec to (Memory.max_ts loc mem0)).\n        - exfalso. exploit Memory.max_ts_spec.\n          + eapply CLOSED.\n          + i. des. exploit EMPTY; eauto.\n        - econs.\n          + eapply cap_flex_back; eauto.\n          + econs; eauto. }\n      set (@cell_elements_greatest\n             (mem0 loc)\n             (fun to' => Time.lt to' to)). des; cycle 1.\n      { exfalso. exploit EMPTY.\n        - eapply CLOSED.\n        - eauto.\n        - ss. }\n      destruct (Time.le_lt_dec to from).\n      - exploit (cap_flex_middle CAP).\n        + econs.\n          * eapply GET0.\n          * eapply GET.\n          * eapply TimeFacts.lt_le_lt; eauto.\n          * i. destruct (Memory.get loc ts mem0) eqn:GET1; auto.\n            exfalso. destruct p.\n            destruct (Time.le_lt_dec to ts).\n            { exploit LEAST; eauto. i.\n              eapply Time.lt_strorder. eapply TimeFacts.le_lt_lt.\n              { eapply x. }\n              eapply TimeFacts.le_lt_lt.\n              { eapply TS2. }\n              { eapply memory_get_ts_strong in GET. des; clarify; ss.\n                exfalso. eapply Time.lt_strorder. eapply TimeFacts.le_lt_lt.\n                - eapply l.\n                - eauto. } }\n            { exploit GREATEST; eauto. i.\n              eapply Time.lt_strorder. eapply TimeFacts.le_lt_lt.\n              { eapply x. }\n              { eauto. } }\n        + eapply TimeFacts.lt_le_lt; eauto.\n        + i. econs; eauto. econs; eauto.\n      - econs.\n        + eapply (cap_flex_le CAP). eapply GET.\n        + econs; eauto.\n    }\n    {\n      inv H. apply Memory.max_ts_spec in GET. des.\n      inv ITV. ss. econs; ss.\n      - eapply TimeFacts.le_lt_lt; eauto. apply Time.bot_spec.\n      - etrans; eauto. erewrite <- cap_flex_max_ts; eauto.\n    }\n  Qed.\n\n  Record cap_flex_map_loc (max tm0 tm1: Time.t)\n         (times: list Time.t)\n         (f: Time.t -> Time.t -> Prop): Prop :=\n    {\n      cap_flex_map_loc_map_lt:\n        mapping_map_lt_loc f;\n      cap_flex_map_loc_map_bot:\n        f Time.bot Time.bot;\n      cap_flex_map_loc_ident:\n        forall ts (TS: Time.le ts max),\n          f ts ts;\n      cap_flex_map_loc_max:\n        exists fts,\n          (<<MAP: f tm0 fts>>) /\\\n          (<<TS: Time.le tm1 fts>>);\n      cap_flex_map_loc_bound:\n        forall ts fts (TS: Time.lt max ts) (MAP: f ts fts),\n          Time.le tm1 fts;\n      cap_flex_map_loc_complete:\n        forall ts (IN: List.In ts times),\n        exists fts, <<MAP: f ts fts>>;\n    }.\n\n  Record cap_flex_map (max tm0 tm1: TimeMap.t)\n         (times: Loc.t -> list Time.t)\n         (f: Loc.t -> Time.t -> Time.t -> Prop): Prop :=\n    {\n      cap_flex_map_map_lt:\n        mapping_map_lt f;\n      cap_flex_map_map_bot:\n        mapping_map_bot f;\n      cap_flex_map_ident:\n        forall loc ts (TS: Time.le ts (max loc)),\n          f loc ts ts;\n      cap_flex_map_max:\n        forall loc,\n        exists fts,\n          (<<MAP: f loc (tm0 loc) fts>>) /\\\n          (<<TS: Time.le (tm1 loc) fts>>);\n      cap_flex_map_bound:\n        forall loc ts fts (TS: Time.lt (max loc) ts) (MAP: f loc ts fts),\n          Time.le (tm1 loc) fts;\n      cap_flex_map_complete:\n        forall loc ts (IN: List.In ts (times loc)),\n          mappable_time f loc ts;\n    }.\n\n  Lemma cap_flex_map_locwise (max tm0 tm1: TimeMap.t)\n        (times: Loc.t -> list Time.t)\n        (f: Loc.t -> Time.t -> Time.t -> Prop)\n        (LOCWISE: forall loc, cap_flex_map_loc (max loc) (tm0 loc) (tm1 loc) (times loc) (f loc))\n    :\n      cap_flex_map max tm0 tm1 times f.\n  Proof.\n    econs.\n    { eapply mapping_map_lt_locwise.\n      eapply LOCWISE. }\n    { ii. eapply LOCWISE. }\n    { ii. eapply LOCWISE. auto. }\n    { ii. eapply LOCWISE. }\n    { ii. eapply LOCWISE; eauto. }\n    { ii. eapply LOCWISE. auto. }\n  Qed.\n\n  Lemma cap_flex_map_loc_exists max tm0 tm1 times\n        (TM0: Time.lt max tm0)\n        (TM1: Time.lt max tm1)\n    :\n      exists f,\n        (<<MAP: cap_flex_map_loc max tm0 tm1 times f>>).\n  Proof.\n    hexploit (@shift_map_exists\n                max tm1 (Time.incr tm1)\n                (tm0::times)); ss.\n    { left. auto. }\n    { apply Time.incr_spec. }\n    intros [f SPEC]. exists f. des. splits; auto.\n    econs; eauto.\n    { eapply SAME. eapply Time.bot_spec. }\n    { exploit (COMPLETE tm0); auto. i. des. esplits; eauto.\n      eapply BOUND in MAPPED; eauto. left. des. auto. }\n    { i. exploit BOUND; eauto. i. des. left. auto. }\n  Qed.\n\n  Lemma cap_flex_map_exists max tm0 tm1 times\n        (TM0: forall loc, Time.lt (max loc) (tm0 loc))\n        (TM1: forall loc, Time.lt (max loc) (tm1 loc))\n    :\n      exists f,\n        (<<MAP: cap_flex_map max tm0 tm1 times f>>).\n  Proof.\n    hexploit (@choice Loc.t (Time.t -> Time.t -> Prop)\n                      (fun loc f =>\n                         cap_flex_map_loc (max loc) (tm0 loc) (tm1 loc) (times loc) f)).\n    { i. eapply cap_flex_map_loc_exists; eauto. }\n    intros [f SPEC]. exists f.\n    eapply cap_flex_map_locwise; eauto.\n  Qed.\n\n  Lemma cap_flex_map_ident_concrete maxmap max tm0 tm1 times f mem0\n        (MAP: cap_flex_map max tm0 tm1 times f)\n        (MAXMAP: Memory.max_concrete_timemap mem0 maxmap)\n        (MAX: TimeMap.le maxmap max)\n    :\n      map_ident_concrete f mem0.\n  Proof.\n    ii. inv CONCRETE. eapply Memory.max_concrete_ts_spec in GET; eauto.\n    des. eapply MAP; eauto.\n  Qed.\n\n  Lemma concrete_messages_le_cap_flex_memory_map\n        mem0 mem1 maxmap max tm0 tm1 cap0 cap1 times f\n        (CONCRETE: concrete_messages_le mem0 mem1)\n        (MAXMAP: Memory.max_concrete_timemap mem0 maxmap)\n        (MAX: TimeMap.le maxmap max)\n        (TM0: forall loc, Time.lt (Memory.max_ts loc mem0) (tm0 loc))\n        (TM1: forall loc, Time.lt (Memory.max_ts loc mem1) (tm1 loc))\n        (CAP0: cap_flex mem0 cap0 tm0)\n        (CAP1: cap_flex mem1 cap1 tm1)\n        (MEM0: Memory.closed mem0)\n        (MEM1: Memory.closed mem1)\n        (MAP: cap_flex_map max tm0 tm1 times f)\n    :\n      memory_map f cap0 cap1.\n  Proof.\n    assert (IDENT: map_ident_concrete f mem0).\n    { ii. inv CONCRETE0. eapply Memory.max_concrete_ts_spec in GET; eauto.\n      des. eapply MAP; eauto. }\n    econs.\n    { i. eapply (@cap_flex_inv mem0 cap0 tm0) in GET; eauto. des; eauto.\n      destruct msg as [val released|]; auto. right.\n      exploit CONCRETE; eauto. i. des. esplits.\n      { eapply cap_flex_map_ident; eauto. transitivity (maxmap loc); auto.\n        eapply Memory.max_concrete_ts_spec; eauto. }\n      { eapply map_ident_concrete_closed_message; eauto.\n        eapply MEM0 in GET. des; auto. }\n      { refl. }\n      { eapply (cap_flex_le CAP1) in GET1. eauto. }\n    }\n    { i. hexploit ((cap_flex_map_max MAP) loc). i. des.\n      left. exists (tm0 loc), Time.bot, fts, Time.bot. splits; auto.\n      { eapply Time.bot_spec. }\n      { hexploit (@cap_flex_max_ts mem1 cap1 tm1); eauto.\n        i. eapply Memory.max_ts_spec in GET. des.\n        erewrite H in MAX0. etrans; eauto. }\n      { eapply (cap_flex_map_map_bot MAP). }\n      { i. eapply cap_flex_covered; eauto. }\n    }\n  Qed.\n\n  Lemma cap_flex_closed mem cap tm\n        (CAP: cap_flex mem cap tm)\n        (TM: forall loc, Time.lt (Memory.max_ts loc mem) (tm loc))\n        (CLOSED: Memory.closed mem)\n    :\n      Memory.closed cap.\n  Proof.\n    dup CLOSED. inv CLOSED. econs.\n    { i. eapply cap_flex_inv in MSG; eauto. des; subst.\n      { exploit CLOSED1; eauto. i. des. splits; auto.\n        eapply concrete_promised_le_closed_message; eauto.\n        eapply concrete_messages_le_concrete_promised_le; eauto.\n        eapply memory_le_concrete_messages_le; eauto.\n        eapply cap_flex_le; eauto. }\n      { esplits; eauto. econs. }\n      { esplits; eauto. econs. }\n    }\n    { ii. specialize (INHABITED loc).\n      eapply cap_flex_le in INHABITED; eauto.\n    }\n  Qed.\n\n  Lemma cap_left_end mem1 mem2 tm loc ts1 ts2 msg1\n        (MEM: Memory.closed mem1)\n        (CAP: cap_flex mem1 mem2 tm)\n        (GET: Memory.get loc ts2 mem1 = Some (ts1, msg1))\n    :\n      exists ts0 msg0,\n        (<<GET: Memory.get loc ts1 mem2 = Some (ts0, msg0)>>).\n  Proof.\n    destruct (Memory.get loc ts1 mem1) as [[ts0 msg0]|] eqn:GETORG.\n    { eapply cap_flex_le in GETORG; eauto. }\n    { hexploit (@cell_elements_greatest\n                  (mem1 loc)\n                  (fun ts => Time.lt ts ts1)). i. des; cycle 1.\n      { inv MEM. specialize (INHABITED loc).\n        hexploit EMPTY; eauto. intros TS.\n        destruct (Time.le_lt_dec ts1 Time.bot); ss. destruct l.\n        { exfalso. eapply Time.lt_strorder.\n          eapply TimeFacts.lt_le_lt; eauto. eapply Time.bot_spec. }\n        { inv H. clarify. }\n      }\n      hexploit (cap_flex_middle CAP).\n      { econs.\n        { eapply GET0. }\n        { eapply GET. }\n        { eapply TimeFacts.lt_le_lt; eauto. eapply memory_get_ts_le; eauto. }\n        { i. destruct TS2.\n          { destruct (Memory.get loc ts mem1) eqn:GETTS; auto. destruct p.\n            eapply GREATEST in GETTS; eauto. timetac. }\n          { inv H. eauto. }\n        }\n      }\n      { auto. }\n      eauto.\n    }\n  Qed.\n\n  Lemma cap_flex_wf\n        lc mem1 mem2 tm\n        (CAP: cap_flex mem1 mem2 tm)\n        (WF: Local.wf lc mem1):\n    Local.wf lc mem2.\n  Proof.\n    eapply memory_concrete_le_local_wf.\n    { eapply memory_concrete_le_le. eapply CAP. }\n    { etrans.\n      { eapply WF. }\n      { eapply CAP. }\n    }\n    { eauto. }\n  Qed.\n\n  Lemma cap_flex_future_memory_map\n        mem0 mem1 tm cap\n        (TM0: forall loc, Time.lt (Memory.max_ts loc mem0) (tm loc))\n        (TM1: TimeMap.le (Memory.max_timemap mem1) tm)\n        (CAP: cap_flex mem0 cap tm)\n        (MEM0: Memory.closed mem0)\n        (FUTURE: Memory.future_weak mem0 mem1)\n    :\n      memory_map ident_map cap mem1.\n  Proof.\n    econs.\n    { i. destruct msg as [val released|]; auto. right.\n      eapply cap_flex_inv in GET; eauto. des; clarify.\n      eapply Memory.future_weak_get1 in GET; eauto. des.\n      esplits; eauto; ss. eapply ident_map_message. }\n    { i. left. exists (tm loc), Time.bot, (tm loc), Time.bot.\n      splits; ss; auto.\n      { eapply Time.bot_spec. }\n      { eapply Memory.max_ts_spec in GET. des. etrans; eauto. }\n      { i. eapply cap_flex_covered; eauto. }\n    }\n  Qed.\n\n  Lemma cap_flex_future_weak\n        mem1 mem2 tm\n        (CAP: cap_flex mem1 mem2 tm)\n        (TM: forall loc, Time.lt (Memory.max_ts loc mem1) (tm loc))\n        (CLOSED: Memory.closed mem1):\n    Memory.future_weak mem1 mem2.\n  Proof.\n    econs; ii.\n    { eapply CAP in GET. esplits; eauto. refl. }\n    { eapply cap_flex_inv in GET2; eauto. des; clarify. }\n    { eapply cap_flex_inv in GET2; eauto. des; clarify. }\n  Qed.\n\n  Lemma cap_flex_concrete_messages_le mem cap tm\n        (CAP: cap_flex mem cap tm)\n        (CLOSED: Memory.closed mem)\n        (TM: forall loc, Time.lt (Memory.max_ts loc mem) (tm loc))\n    :\n      concrete_messages_le cap mem.\n  Proof.\n    ii. eapply cap_flex_inv in GET0; eauto. des; clarify. eauto.\n  Qed.\n\nEnd CAPFLEX.\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/CapFlex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.26512734150295386}}
{"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(** this module provides a denotational/axiomatic semantics to c++ compilation\n    units.\n *)\nRequire Import bedrock.prelude.base.\nRequire Import bedrock.lang.cpp.ast.\nFrom bedrock.lang.cpp Require Import\n     semantics logic.pred logic.path_pred logic.heap_pred.\nRequire Import iris.proofmode.proofmode.\n\nImport ChargeNotation.\n\nSection with_cpp.\n  Context `{Σ : cpp_logic} {resolve:genv}.\n\n  Set Default Proof Using \"Σ resolve\".\n\n  Definition denoteSymbol (tu : translation_unit) (n : obj_name) (o : ObjValue) : mpred :=\n    _global n |->\n        match o with\n        | Ovar t e =>\n          (* no need for [erase_qualifiers], we only check the head *)\n          match drop_qualifiers t with\n          | Tarray _ 0 =>\n            (* TODO: maybe arrays of unknown size should also use [validR]? *)\n            validR\n          | _ =>\n            svalidR\n          end\n        | Ofunction f =>\n          match f.(f_body) with\n          | None => svalidR\n          | Some body => as_Rep (code_at resolve tu f)\n          end\n        | Omethod m =>\n          match m.(m_body) with\n          | None => svalidR\n          | Some body => as_Rep (method_at resolve tu m)\n          end\n        | Oconstructor c =>\n          match c.(c_body) with\n          | None => svalidR\n          | Some body => as_Rep (ctor_at resolve tu c)\n          end\n        | Odestructor d =>\n          match d.(d_body) with\n          | None => svalidR\n          | Some body => as_Rep (dtor_at resolve tu d)\n          end\n        end.\n\n  #[global] Instance denoteSymbol_persistent {tu n o} : Persistent (denoteSymbol tu n o).\n  Proof. rewrite /denoteSymbol; repeat case_match; apply _. Qed.\n\n  #[global] Instance denoteSymbol_affine {tu n o} : Affine (denoteSymbol tu n o) := _.\n\n  (** [is_strict_valid o] states that if the declaration [o] occurs in a\n      translation unit, the pointer to it is guaranteed to be strictly valid.\n   *)\n  Definition is_strict_valid o : Prop :=\n    match o with\n    | None => False\n    | Some (Ovar t _) =>\n        match drop_qualifiers t with\n        | Tarray _ 0 => False\n        | _ => True\n        end\n    | Some _ => True\n    end.\n\n  Lemma denoteSymbol_strict_valid tu n o :\n    is_strict_valid (Some o) ->\n    denoteSymbol tu n o |-- strict_valid_ptr (_global n).\n  Proof.\n    rewrite /is_strict_valid/denoteSymbol; destruct o.\n    { case_match; intros; try by rewrite _at_svalidR.\n      destruct n0; try tauto. by rewrite _at_svalidR. }\n    all: case_match; by\n        intros;rewrite !(_at_as_Rep, _at_svalidR,\n      code_at_strict_valid, method_at_strict_valid, ctor_at_strict_valid, dtor_at_strict_valid).\n  Qed.\n\n  Lemma denoteSymbol_valid tu n o :\n    denoteSymbol tu n o |-- valid_ptr (_global n).\n  Proof.\n    case: o. {\n      rewrite /denoteSymbol => t o; repeat case_match => //=; intros;\n        rewrite (_at_validR, _at_svalidR); trivial using strict_valid_valid.\n    }\n    all: intros; rewrite denoteSymbol_strict_valid //; apply strict_valid_valid.\n  Qed.\n\n  (** TODO incomplete *)\n  Definition initSymbol (n : obj_name) (o : ObjValue) : mpred :=\n    _at (_global n)\n        match o with\n        | Ovar t (Some e) =>\n          emp (*\n      Exists Q : FreeTemps -> mpred,\n      □ (_at (_eq a) (uninitR (resolve:=resolve) t 1) -*\n         Forall ρ ti, wp_init (resolve:=resolve) ti ρ t (Vptr a) e Q) ** Q emp\n*)\n      (* ^^ todo(gmm): static initialization is not yet supported *)\n        | Ovar t None =>\n          uninitR (resolve:=resolve) t (cQp.m 1)\n        | _ => emp\n        end.\n\n  Definition denoteModule_def (tu : translation_unit) : mpred :=\n    ([∗list] sv ∈ map_to_list tu.(symbols), denoteSymbol tu sv.1 sv.2) **\n    [| module_le tu resolve.(genv_tu) |].\n  Definition denoteModule_aux : seal (@denoteModule_def). Proof. by eexists. Qed.\n  Definition denoteModule := denoteModule_aux.(unseal).\n  Definition denoteModule_eq : @denoteModule = _ := denoteModule_aux.(seal_eq).\n\n  #[global] Hint Opaque denoteModule : typeclass_instances.\n\n  #[global] Instance denoteModule_persistent {module} : Persistent (denoteModule module).\n  Proof.\n    red. rewrite denoteModule_eq /denoteModule_def; intros.\n    destruct module; simpl.\n    iIntros \"[#M #H]\"; iFrame \"#\".\n  Qed.\n\n  #[global] Instance denoteModule_affine {module} : Affine (denoteModule module).\n  Proof using . refine _. Qed.\n\n  Lemma denoteModule_denoteSymbol n m o :\n    m.(symbols) !! n = Some o ->\n    denoteModule m |-- denoteSymbol m n o.\n  Proof.\n    rewrite denoteModule_eq/denoteModule_def.\n    intros; iIntros \"[M _]\".\n    rewrite /lookup /symbol_lookup /= /lookup in H.\n    rewrite /map_to_list /avl.IM_maptolist.\n    assert (exists xs ys, avl.IM.elements (symbols m) = xs ++ (n, o) :: ys) as [ ? [ ? -> ] ].\n    { apply avl.IM.find_2 in H.\n      apply avl.IM.elements_1 in H.\n      eapply SetoidList.InA_alt in H.\n      destruct H as [ ? [ ? H ]].\n      do 2 red in H0; simpl in H0. destruct H0; subst.\n      eapply in_split in H.\n      destruct x; apply H. }\n    rewrite big_opL_app.\n    rewrite big_opL_cons.\n    by iDestruct \"M\" as \"[_ [M _]]\".\n  Qed.\n\n  Lemma denoteModule_strict_valid n m :\n    is_strict_valid (m.(symbols) !! n) ->\n    denoteModule m |-- strict_valid_ptr (_global n).\n  Proof.\n    rewrite /is_strict_valid.\n    case_match; try tauto.\n    intros; iIntros \"M\".\n    iDestruct (denoteModule_denoteSymbol with \"M\") as \"M\"; eauto.\n    iApply denoteSymbol_strict_valid; eauto.\n  Qed.\n\n  Lemma denoteModule_valid n m :\n    m.(symbols) !! n <> None ->\n    denoteModule m |-- valid_ptr (_global n).\n  Proof.\n    intros; iIntros \"M\".\n    destruct (symbols m !! n) eqn:?; try congruence.\n    iDestruct (denoteModule_denoteSymbol with \"M\") as \"M\"; eauto.\n    by iApply denoteSymbol_valid.\n  Qed.\n\n  #[global] Instance denoteModule_models_observe tu : Observe [| tu ⊧ resolve |] (denoteModule tu).\n  Proof.\n    apply observe_intro_only_provable.\n    rewrite denoteModule_eq/denoteModule_def.\n    iIntros \"[_ %]\". iPureIntro. constructor.\n    destruct (module_le_spec tu (genv_tu resolve)); eauto.\n    destruct H.\n  Qed.\n\nEnd with_cpp.\n\nArguments denoteModule _ : simpl never.\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/translation_unit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188373563072, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.26508700291656506}}
{"text": "Require Import POCS.\n\n(**\nTwoDiskBaseAPI supports reading and writing to two disks. It also allows one\ndisk to fail at any time (just before any operation). Note that disk failure is\nseparate from program crashes: programs can still crash and recover. In this\nmodel, there is no way to recover from a disk failure (that is, we have a\nfail-stop model).\n\nWe provide a more convenient set of specifications (for the same operations) in\nTwoDiskAPI.\n*)\n\nInductive diskId :=\n| d0\n| d1.\n\nInductive DiskResult T :=\n| Working (v:T)\n| Failed.\n\nArguments Failed {T}.\n\nInductive State :=\n| BothDisks (d_0:disk) (d_1:disk)\n| OnlyDisk0 (d_0:disk)\n| OnlyDisk1 (d_1:disk).\n\nDefinition disk0 (state:State) : option disk :=\n  match state with\n  | BothDisks d_0 _ => Some d_0\n  | OnlyDisk0 d => Some d\n  | OnlyDisk1 _ => None\n  end.\n\nDefinition disk1 (state:State) : option disk :=\n  match state with\n  | BothDisks _ d_1 => Some d_1\n  | OnlyDisk0 _ => None\n  | OnlyDisk1 d => Some d\n  end.\n\nDefinition get_disk (i:diskId) (state:State) : option disk :=\n  match i with\n  | d0 => disk0 state\n  | d1 => disk1 state\n  end.\n\nDefinition set_disk (i:diskId) (state:State) (d:disk) : State :=\n  match i with\n  | d0 => match state with\n         | BothDisks _ d_1 => BothDisks d d_1\n         | OnlyDisk0 _ => OnlyDisk0 d\n         | OnlyDisk1 d_1 => BothDisks d d_1\n         end\n  | d1 => match state with\n         | BothDisks d_0 _ => BothDisks d_0 d\n         | OnlyDisk0 d_0 => BothDisks d_0 d\n         | OnlyDisk1 _ => OnlyDisk1 d\n         end\n  end.\n\nInductive Op : Type -> Type :=\n| op_read (i : diskId) (a : addr) : Op (DiskResult block)\n| op_write (i : diskId) (a : addr) (b : block) : Op (DiskResult unit)\n| op_size (i : diskId) : Op (DiskResult nat).\n\nInductive op_step : forall `(op: Op T), Semantics State T :=\n| step_read : forall a i r state,\n    match get_disk i state with\n    | Some d => match diskGet d a with\n               | Some b0 => r = Working b0\n               | None => exists b, r = Working b\n               end\n    | None => r = Failed\n    end ->\n    op_step (op_read i a) state r state\n| step_write : forall a i b state r state',\n    match get_disk i state with\n    | Some d => state' = set_disk i state (diskUpd d a b) /\\\n               r = Working tt\n    | None => r = Failed /\\ state' = state\n    end ->\n    op_step (op_write i a b) state r state'\n| step_size : forall i state r,\n    match get_disk i state with\n    | Some d => r = Working (diskSize d)\n    | None => r = Failed\n    end ->\n    op_step (op_size i) state r state.\n\nInductive bg_failure : State -> State -> Prop :=\n| step_id : forall (state: State), bg_failure state state\n| step_fail0 : forall d_0 d_1,\n    bg_failure (BothDisks d_0 d_1) (OnlyDisk1 d_1)\n| step_fail1 : forall d_0 d_1,\n    bg_failure (BothDisks d_0 d_1) (OnlyDisk0 d_0).\n\nDefinition combined_step := pre_step bg_failure (@op_step).\n\n\nModule Type TwoDiskBaseAPI.\n\n  Axiom init : proc InitResult.\n  Axiom read : diskId -> addr -> proc (DiskResult block).\n  Axiom write : diskId -> addr -> block -> proc (DiskResult unit).\n  Axiom size : diskId -> proc (DiskResult nat).\n  Axiom recover : proc unit.\n\n  Axiom abstr : Abstraction State.\n\n  Axiom init_ok : init_abstraction init recover abstr inited_any.\n  Axiom read_ok : forall i a, proc_spec (op_spec (combined_step (op_read i a))) (read i a) recover abstr.\n  Axiom write_ok : forall i a b, proc_spec (op_spec (combined_step (op_write i a b))) (write i a b) recover abstr.\n  Axiom size_ok : forall i, proc_spec (op_spec (combined_step (op_size i))) (size i) recover abstr.\n  Axiom recover_noop : rec_noop recover abstr no_wipe.\n\n  Hint Resolve init_ok.\n  Hint Resolve read_ok.\n  Hint Resolve write_ok.\n  Hint Resolve size_ok.\n  Hint Resolve recover_noop.\n\nEnd TwoDiskBaseAPI.\n", "meta": {"author": "mit-pdos", "repo": "6.826-2017-labs", "sha": "5b9fdc9bf92c35e9f9a836d2b92cc0f2287a645c", "save_path": "github-repos/coq/mit-pdos-6.826-2017-labs", "path": "github-repos/coq/mit-pdos-6.826-2017-labs/6.826-2017-labs-5b9fdc9bf92c35e9f9a836d2b92cc0f2287a645c/src/Lab4/TwoDiskBaseAPI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.26508699659937485}}
{"text": "Require Import List.\nRequire Import ListSet.\nImport ListNotations.\nRequire Import Nat.\nRequire Import Bool.\nFrom Legion Require Import Map.\n\nParameter region : Type.\nParameter location : Type.\nDefinition physical_region : Type := set location.\nParameter Id_T : Type.\n\nDefinition Task_ID := nat.\n\n(* Declarations for ListSet and Map *)\n\n\nAxiom Id_T_dec :\n  forall x y : Id_T, {x = y} + {x <> y}.\n\nAxiom loc_dec :\n  forall x y : location, {x = y} + {x <> y}.\n\nAxiom option_loc_dec:\n forall x y : option location, {x = y} + {x <> y}.\n\nAxiom region_eq_neq :\n  forall x y : region, {x = y} + {x <> y}.\n\nDefinition set_inter_reg := set_inter region_eq_neq.\n\nAxiom physical_region_eq_neq :\n  forall r1 r2 : physical_region, {r1 = r2} + {r1 <> r2}.\n\n(* Core Legion Types (page 4) *)\nInductive coherence_mode : Type :=\n  | Atomic (r : region) | Simult (r : region)\n.\n\nDefinition Qs : Type := set coherence_mode.\n\nInductive priv_T : Type :=\n  | Reads (r : region)\n  | Writes (r : region)\n  | Reduces (id : Id_T) (r : region)\n.\n\nDefinition Phis := set priv_T.\n\nInductive constraint : Type :=\n| Subregion (r1:region) (r2 : region)\n| Disjoint (r1 : region) (r2 : region)\n.\n\nAxiom constraint_dec :\n  forall x y : constraint, {x = y} + {x <> y}.\n\nDefinition Omegas : Type := set constraint.\n\nInductive T : Type :=\n  | TBool | TInt\n  | TTuple (tup : list T)\n  | TPointer (t : T) (rs : list region)\n  | TColoring (r : region)\n  | (* ∃rs.t *) TRegionRelation (rs : list region) (t:T) (Ω : Omegas)\n    (* TODO change to universal quantification over regions *)\n  | (* ∀ *) TTask (rs : list region) (ts : list T) (Φ : list Phis) (Q : list Qs) (tr : T)\n.\n\nInductive expr : Type :=\n  | EBool (b : bool)\n  | EInt (i : nat)\n  | Tuple (es : list expr)\n  | ExprIndex (e : expr) (n : nat)\n  | Id (id : Id_T)\n  | NewPointer (t : T) (r : region)\n  | NullPointer (t : T) (r : region)\n  | IsNull (e : expr)\n  | Upregion (e : expr) (rs : list region)\n  | Downregion (e : expr) (rs : list region)\n  | Read (e1 : expr)\n  | Write (e1 : expr) (e2 : expr)\n  | Reduce (id : Id_T) (e1 : expr) (e2 : expr)\n  | NewColor (r : region)\n  | Color (e1 : expr) (e2 : expr) (e3 : expr)\n  | Add (e1 : expr) (e2 : expr)\n  | Compare (e1 : expr) (e2 : expr)\n  | LetIn (id : Id_T) (t : T) (e1 : expr) (e2 : expr)\n  | If (e1 : expr) (e2 : expr) (e3 : expr)\n  | Call (id : Id_T) (rs : list region) (es : list expr)\n  | Partition (rp : region) (e1 : expr) (rs : list region) (e2 : expr)\n  | Pack (e1 : expr) (t : T) (rs : list region)\n  | Unpack (e1 : expr) (id : Id_T) (t : T) (rs : list region) (e2 : expr)\n.\n\n\nInductive value : Type :=\n  | VBool (b : bool)\n  | VInt (i : nat)\n  (* Value tuples in the paper have two entries; changed for consistency with expressions. *)\n  | VTuple (vs : list value)\n  | VNull\n  | VLocation (l : location)\n  | VColoring (l : list (location * nat))\n  | VRegionRelationInstance (rs : list physical_region) (v : value)\n.\n\nAxiom value_dec :\n  forall x y : value, {x = y} + {x <> y}.\n\n(* Heap, takes heap location to type *)\nDefinition Hs := partial_map location T.\n\n(* Store takes global variables to values *)\nDefinition Ss := partial_map location value.\n\nInductive CoherenceMode :=\n  | SSimult | SAtomic | SExcl\n.\n\n(* entry in an execution history *)\nInductive entry : Type :=\n  | SRead (l : location) (c : CoherenceMode) (v : value) (a : Task_ID)\n  | SWrite (l : location) (c : CoherenceMode) (v : value) (a : Task_ID)\n  | SReduce (id : Id_T) (l : location) (c : CoherenceMode) (v : value) (a : Task_ID)\n.\n\n\nDefinition get_loc (eps : entry) :=\n  match eps with\n  | SRead l _ _ _ | SWrite l _ _ _ | SReduce _ l _ _ _ => l\n  end.\n\nDefinition get_mode (eps : entry) :=\n  match eps with\n  | SRead _ m _ _ | SWrite _ m _ _ | SReduce _ _ m _ _ => m\n  end.\n\nDefinition get_val (eps : entry) :=\n  match eps with\n  | SRead _ _ v _ | SWrite _ _ v _ | SReduce _ _ _ v _ => v\n  end.\n\nDefinition get_tag (eps : entry) :=\n  match eps with\n  | SRead _ _ _ t | SWrite _ _ _ t | SReduce _ _ _ _ t => t\n  end.\n\n(* E is stored backwards in some rules. TODO: Change throughout to store forwards *)\nDefinition Es := list entry.\n\n(* a type map *)\nDefinition Gammas : Type := partial_map Id_T T.\n\n(* map *)\nDefinition Ms : Type := partial_map region physical_region.\n\n(* map *)\nDefinition Ls : Type := partial_map Id_T value.\n\nDefinition ClobberSet : Type := set location.\n\n(* Helper Functions (Figure 5, page 9)\n ******************\n*)\n\n(* Figure 5, page 9 *)\nFixpoint apply_rev (S : Ss) (E : Es) : Ss :=\nmatch E with\n  | nil => S\n  | SRead l c v t :: E' => apply_rev S E'\n  | SWrite l c v t :: E' => add_mapping loc_dec (apply_rev S E') l v\n  | SReduce id l _ v _ :: E' =>\n      let S' := apply_rev S E' in\n      (match S' l with\n      | Some sl => add_mapping loc_dec S' l (Call id [] [sl; v])\n      | None => S' (* error *)\n      end)\n  end.\nDefinition apply (S : Ss) (E : Es) : Ss :=\n  apply_rev S (rev E).\n\n(* Valid Interleaving Test, fig 7, page 14 *)\n\nInductive any_interleave : Es -> list Es -> Prop :=\n  | any_interleave_empty l :\n      (forall (empty : Es), empty = []) ->\n      any_interleave [] l\n  | any_interleave_nonempty ep E' Elist Elist':\n      is_append_one Elist ep Elist' ->\n      any_interleave (ep::E') Elist'\nwith\n  is_append_one : list Es -> entry -> list Es -> Prop :=\n  | is_append_one_hd ep Elist Elist' :\n    tl Elist = Elist' ->\n    is_append_one Elist ep ((ep :: hd [] Elist) :: tl Elist)\n  | is_append_one_tl ep Elist Elist' E1:\n    is_append_one Elist ep Elist' ->\n    is_append_one (E1::Elist) ep (E1::Elist')\n.\n\n\nInductive coherent : Ss -> set location -> set location -> Es -> Prop :=\n  | coherent_empty S L1 L2 :\n      coherent S L1 L2 []\n  | coherent_read S L1 L2 E ep l c v t :\n      (~ (In l L2) \\/ S l = Some v) ->\n      coherent S L1 L2 E ->\n      ep = SRead l c v t ->\n      coherent S L1 L2 (ep::E)\n  | coherent_write S L1 L2 E ep l c v t :\n      coherent (apply S [ep]) L1 (l :: L2) E ->\n      ep = SWrite l c v t ->\n      In l L1 ->\n      coherent S L1 L2 (ep::E)\n  | coherent_other S L1 L2 E ep l c v t :\n      coherent (apply S [ep]) L1 L2 E ->\n      (ep = SWrite l c v t /\\ ~ (In l L1)) \\/ (exists id, ep = SReduce id l c v t) ->\n      coherent S L1 L2 (ep::E)\n.\n\n(* Takes a single ex. trace, not a list of execution traces *)\nDefinition seq_equiv (S:Ss) (L1 : set location) (L2 : set location) (E' : Es) (Eseq : Es)\n  : Prop :=\n  coherent S L1 L2 Eseq /\\\n  (forall (l : location), In l L1 -> (apply S E') l = (apply S Eseq) l).\n\n\nFixpoint Lexcl_helper (E:Es) (C:ClobberSet) : set location :=\n  match E with\n  | [] => []\n  | h :: E' => let L' := Lexcl_helper E' C in (\n    match get_mode h with\n    | SExcl => get_loc h :: L'\n    | _ => L' end)\n  end.\n\nAxiom location_eq_neq:\n  forall x y : location, {x = y} + {x <> y}.\n\nDefinition Lexcl (E:Es) (C:ClobberSet) : set location :=\n  set_diff location_eq_neq (Lexcl_helper E C) C.\n\nFixpoint Latomic_helper (E:Es) (C:ClobberSet) : set location :=\n  match E with\n  | [] => []\n  | h :: E' => let L' := Latomic_helper E' C in (\n    match get_mode h with\n    | SAtomic => get_loc h :: L'\n    | _ => L' end)\n  end.\n\nDefinition Latomic (E:Es) (C:ClobberSet) : set location :=\n  set_diff location_eq_neq\n    (Latomic_helper E C)\n    (set_union location_eq_neq C (Lexcl E C)).\n\n(* filters by tag *)\nFixpoint darrow (t : Task_ID) (E : Es) : Es :=\n  match E with\n  | [] => []\n  | h :: E' => if Nat.eqb t (get_tag h) then h::darrow t E'\n                  else darrow t E'\n  end.\n\nDefinition valid_interleave (S : Ss) (C : ClobberSet)\n  (E' : Es) (Elist : list Es) : Prop :=\n  any_interleave E' Elist /\\\n  coherent S (Lexcl E' C) (Lexcl E' C) E' /\\\n  seq_equiv S (Lexcl E' C) (Lexcl E' C) E' (fold_right (@app entry) nil Elist) /\\\n  forall t, seq_equiv S (Latomic E' C) (empty_set location) (darrow t E')\n    (darrow t (fold_right (@app entry) nil Elist))\n.\n\n(* ======== *)\n\n\n(* need to reference M *)\nFixpoint coherence_marking_helper\n  (M : Ms) (l : location) (Q : Qs) (has_atomic : bool) : CoherenceMode :=\n  match Q with\n  | [] => if has_atomic then SAtomic else SExcl\n  | Simult r :: Q' =>\n    (match M r with\n    | Some rho => if set_mem loc_dec l rho then SSimult\n                  else coherence_marking_helper M l Q' has_atomic\n    | None => coherence_marking_helper M l Q' has_atomic\n    end\n    )\n  | Atomic r :: Q' =>\n    (match M r with\n    | Some rho => coherence_marking_helper M l Q' (orb has_atomic (set_mem loc_dec l rho))\n    | None => coherence_marking_helper M l Q' has_atomic\n    end\n    )\n  end.\n\nDefinition coherence_marking (M : Ms) (l : location) (Q : Qs) : CoherenceMode :=\n  coherence_marking_helper M l Q false.\n\n(* mark coherence (page 9) *)\nFixpoint mark_coherence (M : Ms) (E : Es) (Q : Qs) (taskid : nat) : Es :=\n  let cm l := coherence_marking M l Q in\n  match E with\n  | [] => []\n  | SRead l c v t :: E' => SRead l (cm l) v t :: mark_coherence M E' Q taskid\n  | SWrite l c v t :: E' => SWrite l (cm l) v t :: mark_coherence M E' Q taskid\n  | SReduce id l c v t :: E' => SReduce id l (cm l) v t :: mark_coherence M E' Q taskid\n  end.\n\n(* needed for [nth] *)\nDefinition default_E : Es := [].\nDefinition default_expr := EBool false.\nDefinition default_val := VBool false.\nParameter default_loc : location.\nParameter default_S : Ss.\n\n(* Type rules\n   *************************\n *)\n\n(* Privilege and Constraint Closure (Fig. 3, page 7) *)\n\n(* Note: Although privilege and constraint sets are implemented as sets,\n    we implement privilege and constraint closure as relations,\n    because constructing an explicit set is intractable.\n*)\n\nInductive constraint_closure : Omegas -> constraint -> Prop :=\n  | Cc_in Ω c : In c Ω -> constraint_closure Ω c\n  | Cc_sub_refl_l Ω ri rj:\n      constraint_closure Ω (Subregion ri rj) ->\n      constraint_closure Ω (Subregion ri ri)\n  | Cc_sub_refl_r Ω ri rj:\n      constraint_closure Ω (Subregion ri rj) ->\n      constraint_closure Ω (Subregion rj rj)\n  | Cc_sub_trans Ω ri rj rk :\n      constraint_closure Ω (Subregion ri rj) ->\n      constraint_closure Ω (Subregion rj rk) ->\n      constraint_closure Ω (Subregion ri rk)\n  | Cc_sub_disj Ω ri rj rk :\n      constraint_closure Ω (Subregion ri rj) ->\n      constraint_closure Ω (Disjoint rj rk) ->\n      constraint_closure Ω (Disjoint ri rk)\n  | Cc_disj_symm Ω ri rj :\n      constraint_closure Ω (Disjoint ri rj) ->\n      constraint_closure Ω (Disjoint rj ri)\n.\n\nInductive privilege_closure : Omegas -> Phis -> priv_T -> Prop :=\n  | Pc_in Ω Φ P : In P Φ -> privilege_closure Ω Φ P\n  | Pc_sub_reads Ω Φ ri rj :\n      constraint_closure Ω (Subregion ri rj) ->\n      privilege_closure Ω Φ (Reads rj) ->\n      privilege_closure Ω Φ (Reads ri)\n  | Pc_sub_writes Ω Φ ri rj :\n      constraint_closure Ω (Subregion ri rj) ->\n      privilege_closure Ω Φ (Writes rj) ->\n      privilege_closure Ω Φ (Writes ri)\n  | Pc_sub_reduces Ω Φ id ri rj :\n      constraint_closure Ω (Subregion ri rj) ->\n      privilege_closure Ω Φ (Reduces id rj) ->\n      privilege_closure Ω Φ (Reduces id ri)\n  | Pc_rw_reduces Ω Φ r id :\n      privilege_closure Ω Φ (Reads r) ->\n      privilege_closure Ω Φ (Writes r) ->\n      privilege_closure Ω Φ (Reduces id r)\n.\n\n(* Substitutes regions in types parametrized over regions *)\nDefinition subst_regions (t : T) (rs' : list region) :=\n  match t with\n  | TBool | TInt | TTuple _ | TColoring _ => t\n  | TPointer t rs => TPointer t rs'\n  | TRegionRelation rs t Ω => TRegionRelation rs' t Ω\n  | TTask rs ts Φ Q tr => TTask rs' ts Φ Q tr\n  end.\n\n\n(* ⊢ *)\nInductive typed : Gammas -> Phis -> Omegas -> expr -> T -> Prop :=\n  (* Figure 4, page 8 *)\n  | T_Read Γ Φ Ω e1 t rs :\n      typed Γ Φ Ω e1 (TPointer t rs) ->\n      (forall (r:region), In r rs -> privilege_closure Ω Φ (Reads r)) ->\n      typed Γ Φ Ω (Read e1) t\n  | T_Write Γ Φ Ω e1 e2 t rs :\n      typed Γ Φ Ω e1 (TPointer t rs) ->\n      typed Γ Φ Ω e2 t ->\n      (forall (r : region), In r rs -> privilege_closure Ω Φ (Writes r)) ->\n      typed Γ Φ Ω (Write e1 e2) (TPointer t rs)\n  | T_Reduce Γ Φ Ω id e1 e2 t1 t2 rs :\n      Γ id = Some (TTask rs [t1; t2] [] [] t1) ->\n      typed Γ Φ Ω e1 (TPointer t1 rs) ->\n      typed Γ Φ Ω e2 t2 ->\n      (forall (r : region), In r rs -> privilege_closure Ω Φ (Reduces id r)) ->\n      typed Γ Φ Ω (Reduce id e1 e2) (TPointer t1 rs)\n  | T_New Γ Φ Ω t r :\n      typed Γ Φ Ω (NewPointer t r) (TPointer t [r])\n  | T_UpRgn Γ Φ Ω e t rs rs' :\n      typed Γ Φ Ω e (TPointer t rs') ->\n      (forall ri : region, forall rj' : region,\n        In ri rs -> In rj' rs' -> constraint_closure Ω (Subregion ri rj')) ->\n      typed Γ Φ Ω (Upregion e rs) (TPointer t rs)\n  | T_DnRgn Γ Φ Ω e t rs rs' :\n      typed Γ Φ Ω e (TPointer t rs') ->\n      typed Γ Φ Ω (Downregion e rs) (TPointer t rs)\n  | T_NewColor Γ Φ Ω r :\n      typed Γ Φ Ω (NewColor r) (TColoring r)\n  | T_Color Γ Φ Ω e1 e2 e3 t r :\n      typed Γ Φ Ω e1 (TColoring r) ->\n      typed Γ Φ Ω e2 (TPointer t [r]) ->\n      typed Γ Φ Ω e3 TInt ->\n      typed Γ Φ Ω (Color e1 e2 e3) (TColoring r)\n  | T_Partition Γ Φ Ω Ω' e1 e2 rp rs t :\n      typed Γ Φ Ω e1 (TColoring rp) ->\n      Ω' = (let cd := constraint_dec in set_union cd\n            (set_union cd Ω (set_map cd (fun r => Subregion r rp) rs))\n            (set_diff cd\n              (set_map cd (fun rr => Disjoint (fst rr) (snd rr)) (set_prod rs rs))\n              (set_map cd (fun rr => Disjoint rr rr) rs))) ->\n      typed Γ Φ Ω' e2 t ->\n      (* (forall r, (exists id, Γ id = r) -> ~ (In rs r)) -> *)\n      (* set_inter rs regions_of(Γ,t) *)\n      typed Γ Φ Ω' (Partition rp e1 rs e2) t\n  | T_Pack Γ Φ Ω Ω1 e1 rs rs' t1 t2 :\n      t1 = (TRegionRelation rs' t2 Ω1) ->\n      (* Ω1[rs' / rs] ⊆ Ω* -> *)\n      typed Γ Φ Ω e1 (subst_regions t2 rs') ->\n      typed Γ Φ Ω (Pack e1 t1 rs) (subst_regions t2 rs')\n  | T_Unpack Γ Γ' Φ Ω Ω' Ω1 e1 e2 id rs rs' t1 t2 t3 :\n      t1 = (TRegionRelation rs' t2 Ω1) ->\n      typed Γ Φ Ω e1 t1 ->\n      Γ' = add_mapping Id_T_dec Γ id (subst_regions t2 rs) ->\n      Ω' = Ω (* ∪ (add_mappings Ω1 rs) *) ->\n      typed Γ' Φ Ω' e2 t3 ->\n      (* what is regions_of(Γ, T1, T3)? *)\n      typed Γ Φ Ω (Unpack e1 id t1 rs e2) t3\n  | T_Call Γ Φ Φ' Ω es id rs rs' Q' tr ts :\n      Γ id = Some (TTask rs' ts Φ' Q' tr) ->\n      all_typed_subst Γ Φ Ω es ts rs ->\n      (* Φ′[r1/r′1,...,rk/r′k]⊆Φ∗ *)\n      typed Γ Φ Ω (Call id rs es) (subst_regions tr rs)\nwith\n  all_typed_subst : Gammas -> Phis -> Omegas -> list expr -> list T -> list region -> Prop :=\n  | all_typed_subst_empty Γ Φ Ω rs :\n      all_typed_subst Γ Φ Ω [] [] rs\n  | all_typed_subst_nonempty Γ Φ Ω e1 es t1 ts rs :\n      all_typed_subst Γ Φ Ω es ts rs ->\n      typed Γ Φ Ω e1 (subst_regions t1 rs)->\n      all_typed_subst Γ Φ Ω (e1::es) (t1::ts) rs\n.\n\n(* Evaluation rules *)\n\nDefinition oset_mem {X Y : Type} dec (m : partial_map X (set Y)) (x : X) (a:Y) :=\n  match m x with\n  | Some s => set_mem dec a s\n  | None => false\n  end.\n\n(* ↦ *)\nInductive eval : Ms -> Ls -> Hs -> Ss -> ClobberSet -> expr -> value -> Es -> Prop :=\n  (* Trivial evaluation rules from page 23 *)\n  | E_Bool (M:Ms) (L:Ls) (H:Hs) (S:Ss) (C:ClobberSet) (b:bool) :\n      eval M L H S C (EBool b) (VBool b) []\n  | E_Int (M:Ms) (L:Ls) (H:Hs) (S:Ss) (C:ClobberSet) (i:nat) :\n      eval M L H S C (EInt i) (VInt i) []\n  | E_Tuple (M:Ms) (L:Ls) (H:Hs) (S:Ss) (C:ClobberSet)\n      (es : list expr) (vs : list value) (E : Es) (n:nat)\n      (z1 : eval M L H S C (Tuple es) (VTuple vs) E) :\n      eval M L H S C (ExprIndex (Tuple es) n) (nth n vs default_val) E\n\n  | E_MakeTuple (M:Ms) (L:Ls) (H:Hs) (S:Ss) (C:ClobberSet)\n      (es : list expr) (vs : list value) (Elist : list Es) (E' : Es)\n      (zvalid : valid_interleave S C E' Elist)\n      (zeval : eval_chain M L H S C es vs Elist) :\n    eval M L H S C (Tuple es) (VTuple vs) (last Elist default_E)\n\n  | E_Var (M:Ms) (L:Ls) (H:Hs) (S:Ss) (C:ClobberSet) (id : Id_T) (v : value)\n      (z1 : L id = Some v) :\n    eval M L H S C (Id id) v []\n\n  | E_Let (M:Ms) (L:Ls) (H:Hs) (S:Ss) (C:ClobberSet) (e1 : expr) (v1 : value) (E1 : Es)\n      (id : Id_T) (t : T)\n      (L' : Ls) (S' : Ss) (e2 : expr) (v2 : value) (E2 : Es) (E' : Es)\n      (zvalid : valid_interleave S C E' [E1; E2])\n      (* L' = L[v1 / id] *):\n    eval M L H S C (LetIn id t e1 e2) v2 E'\n\n  | E_Add (M:Ms) (L:Ls) (H:Hs) (S:Ss) (C:ClobberSet) (e1 : expr) (E1 : Es)\n      (S' : Ss) (e2 : expr) (E2 : Es) (E' : Es)\n      (v' : value) (i1 : nat) (i2 : nat) (i' : nat)\n      (zeval1 : eval M L H S C e1 (VInt i1) E1)\n      (zapply : S' = apply S E1)\n      (zeval2 : eval M L H S' C e2 (VInt i2) E2)\n      (z' : v' = VInt i')\n      (zplus : i' = i1 + i2)\n      (zvalid : valid_interleave S C E' [E1; E2]) :\n    eval M L H S C (Add e1 e2) v' E'\n\n  | E_Compare (M:Ms) (L:Ls) (H:Hs) (S:Ss) (C:ClobberSet) (e1 : expr) (v1 : value) (E1 : Es)\n      (S' : Ss) (e2 : expr) (v2 : value) (E2 : Es) (E' : Es)\n      (v' : value) (i1 : nat) (i2 : nat) (b : bool)\n      (zeval1 : eval M L H S C e1 (VInt i1) E1)\n      (zapply : S' = apply S E1)\n      (zeval2 : eval M L H S' C e2 (VInt i2) E2)\n      (z' : v' = VBool b)\n      (zltb : b = ltb i1 i2)\n      (zvalid : valid_interleave S C E' [E1; E2]) :\n    eval M L H S C (Compare e1 e2) v' E'\n\n  | E_IsNull_F (M:Ms) (L:Ls) (H:Hs) (S:Ss) (C:ClobberSet) (e : expr) (l : location) (E : Es)\n      (zeval : eval M L H S C e (VLocation l) E) :\n    eval M L H S C (IsNull e) (VBool false) E\n\n  | E_IsNull_T (M:Ms) (L:Ls) (H:Hs) (S:Ss) (C:ClobberSet) (e : expr) (l : location) (E : Es)\n      (zeval : eval M L H S C e (VNull) E) :\n    eval M L H S C (IsNull e) (VBool true) E\n\n  | E_IfElse_F (M:Ms) (L:Ls) (H:Hs) (S:Ss) (C:ClobberSet) (e1 : expr) (E1 : Es)\n      (S' : Ss) (e2 : expr) (e3 : expr) (v3 : value) (E3 : Es)\n      (zeval1 : eval M L H S C e1 (VBool false) E1)\n      (zapply : S' = apply S E1)\n      (zeval3 : eval M L H S' C e3 (v3) E3) :\n    eval M L H S C (If e1 e2 e3) v3 (E1 ++ E3)\n\n  | E_IfElse_T (M:Ms) (L:Ls) (H:Hs) (S:Ss) (C:ClobberSet) (e1 : expr) (E1 : Es)\n      (S' : Ss) (e2 : expr) (e3 : expr) (v2 : value) (E2 : Es)\n      (zeval1 : eval M L H S C e1 (VBool true) E1)\n      (zapply : S' = apply S E1)\n      (zeval3 : eval M L H S' C e2 (v2) E2) :\n    eval M L H S C (If e1 e2 e3) v2 (E1 ++ E2)\n\n  (* Main rules, from page 8 *)\n  | E_Read (M:Ms) (L:Ls) (H:Hs) (S:Ss) (C:ClobberSet) (e : expr) (l : location) (E : Es)\n      (S' : Ss) (v : value) (v' : value)\n      (zeval : eval M L H S C e (VLocation l) E)\n      (zapply : S' = apply S E)\n      (zv : Some v = if set_mem loc_dec l C then S' l else Some v' (* : H(l) *) ):\n    eval M L H S C (Read e) v (E ++ [SRead l SExcl v 0])\n\n  | E_Write (M:Ms) (L:Ls) (H:Hs) (S:Ss) (C:ClobberSet)\n      (e1 : expr) (l : location) (E1 : Es) (S' : Ss)\n      (e2 : expr) (v : value) (E2 : Es) (E' : Es)\n      (zeval1 : eval M L H S C e1 (VLocation l) E1)\n      (zapply : S' = apply S E1)\n      (zeval2 : eval M L H S C e2 v E2)\n      (zvalid : valid_interleave S C E' [E1; E2]) :\n    eval M L H S C (Write e1 e2) (VLocation l) (E' ++ [SWrite l SExcl v 0])\n\n  | E_Reduce (M:Ms) (L:Ls) (H:Hs) (S:Ss) (C:ClobberSet)\n      (e1 : expr) (l : location) (E1 : Es) (S' : Ss)\n      (e2 : expr) (v : value) (E2 : Es) (E' : Es)\n      (id : Id_T)\n      (zeval1 : eval M L H S C e1 (VLocation l) E1)\n      (zapply : S' = apply S E1)\n      (zeval2 : eval M L H S C e2 v E2)\n      (zvalid : valid_interleave S C E' [E1; E2]) :\n    eval M L H S C (Reduce id e1 e2) (VLocation l) (E' ++ [SReduce id l SExcl v 0])\n\n  | E_New (M:Ms) (L:Ls) (H:Hs) (S:Ss) (C:ClobberSet) (l : location) (r : region)\n      (t : T)\n      (zincl : match (M r) with | Some rho => In l rho | None => False end)\n      (* znotls : l not in domain S *)\n      (zheap : H l = Some TBool (* should be H l = M[[t]] somehow? *) ):\n    eval M L H S C (NewPointer t r) (VLocation l) []\n\n  | E_UpRgn (M:Ms) (L:Ls) (H:Hs) (S:Ss) (C:ClobberSet) (e : expr) (v : value) (E : Es)\n      (rs : list region)\n      (zeval : eval M L H S C e v E) :\n    eval M L H S C (Upregion e rs) v E\n\n  | E_DnRgn (M:Ms) (L:Ls) (H:Hs) (S:Ss) (C:ClobberSet) (e : expr) (v : value) (E : Es)\n      (l : location)\n      (rs : list region)\n      (zeval : eval M L H S C e v E)\n      (zv : v = if (existsb (fun ri => oset_mem loc_dec M ri l) rs)\n        then (VLocation l) else VNull) :\n    eval M L H S C (Downregion e rs) v E\n\n  | E_NewColor (M:Ms) (L:Ls) (H:Hs) (S:Ss) (C:ClobberSet)\n      (r : region) (K : list (location * nat))\n      (zm : forallb (fun lk => oset_mem loc_dec M r (fst lk)) K = true )\n      (zdistinct: forall i j,\n        (i >= 1 /\\ i <= length K /\\ j >= 1 /\\ j <= length K /\\ i <> j) ->\n        fst (nth i K (default_loc, 0)) <> fst (nth j K (default_loc, 0))) :\n    eval M L H S C (NewColor r) (VColoring K) []\n\n  | E_Color (M:Ms) (L:Ls) (H:Hs) (S:Ss) (C:ClobberSet)\n      (e1 : expr) (K : list (location * nat)) (E1 : Es) (S' : Ss)\n      (e2 : expr) (l : location) (E2 : Es)\n      (e3 : expr) (v : value) (E3 : Es) (E' : Es) (S'' : Ss)\n      (K' : list (location * nat))\n      (* (zK' : K' = (l, v) :: li, vi for li, vi in K if l <> li) *)\n      (zeval1 : eval M L H S C e1 (VColoring K) E1)\n      (zapply : S' = apply S E1)\n      (zeval2 : eval M L H S C e2 (VLocation l) E2)\n      (zapply' : S'' = apply S E2)\n      (zeval3 : eval M L H S C e3 v E3)\n      (zvalid : valid_interleave S C E' [E1; E2; E3]) :\n    eval M L H S C (Color e1 e2 e3) (VColoring K') E'\n\n  | E_Partition  (M:Ms) (L:Ls) (H:Hs) (S:Ss) (C:ClobberSet) (rp : region)\n      (e1 : expr) (K : list (location * nat)) (E1 : Es) (S' : Ss)\n      (rs : list region) (rhos : list physical_region) (e2 : expr)\n      (v : value) (E2 : Es) (E' : Es)\n      (zeval1 : eval M L H S C e1 (VColoring K) E1)\n      (zrhos: forall i : nat, i >= 1 /\\ i <= length rhos ->\n        forall l : location, set_In l (nth i rhos []) <-> set_In (l, i) K)\n      (zapply : S' = apply S E1)\n      (zeval2 : eval M L H S C e2 v E2)\n      (zvalid : valid_interleave S C E' [E1; E2])\n    : eval M L H S C (Partition rp e1 rs e2) v E'\n\n  | E_Pack (M:Ms) (L:Ls) (H:Hs) (S:Ss) (C:ClobberSet)\n      (e1 : expr) (v : value) (E : Es) (rhos : list physical_region) (rs : list region)\n      (t1 : T) (v' : value)\n      (zeval1 : eval M L H S C e1 v E)\n      (zrhos : map Some rhos = map M rs)\n      (zv' : v' = VRegionRelationInstance rhos v)\n    : eval M L H S C (Pack e1 t1 rs) v' E\n\n  | E_Unpack  (M:Ms) (L:Ls) (H:Hs) (S:Ss) (C:ClobberSet)\n      (e1 : expr) (rhos : list physical_region) (v1 : value) (E1 : Es)\n      (M' : Ms) (rs : list region)\n      (L' : Ls) (id : Id_T) (S' : Ss)\n      (e2 : expr) (t : T)\n      (v2 : value) (E2 : Es) (E' : Es)\n      (zeval1 : eval M L H S C e1 (VRegionRelationInstance rhos v1) E1)\n      (zM' : M' = add_mappings region_eq_neq M rs rhos)\n      (zL' : L' = add_mapping Id_T_dec L id v1)\n      (zapply : S' = apply S E1)\n      (zvalid : valid_interleave S C E' [E1; E2])\n    : eval M L H S C (Unpack e1 id t rs e2) v2 E'\n\n  | E_Call (M:Ms) (L:Ls) (H:Hs) (S:Ss) (C:ClobberSet) (rs : list region)\n      (aas : list Id_T) (rs' : list region)\n      ( es : list expr) (vs : list value) (Elist : list Es) (Slist : list Ss)\n      (M' : Ms) (L' : Ls) (S' : Ss) (C' : ClobberSet) (E' : Es) (Q' : Qs) (id : Id_T)\n      (enp1 : expr) (vnp1 : value) (E'' : Es) (Enp1 : Es) (Enp1' : Es) (taskid : Task_ID)\n      (zeval_chain : eval_chain_call M L H Slist C es vs Elist)\n      (zS : S = hd default_S Slist)\n      (zvalid : valid_interleave S C E' Elist)\n      (zfunction : True) (* TODO fix *)\n      (zM' : M' = add_mappings region_eq_neq (@empty region physical_region) rs'\n                    (map (fun r => match M r with | Some rho => rho | None => [] end) rs))\n      (zL' : L' = add_mappings Id_T_dec (@empty Id_T value) aas vs )\n      (zapply : S' = apply S E')\n      (zC' : True)   (* TODO: fix *)\n      (zeval_np1 : eval M' L' H S' C' enp1 vnp1 Enp1)\n      (zEnp1' : Enp1 = mark_coherence M' Enp1 Q' taskid) (* taskid fresh *)\n      (zvalid' : valid_interleave S C E'' [E'; Enp1'])\n    : eval M L H S C (Call id rs es) vnp1 E''\nwith\n  (* needed for E_MakeTuple *)\n  eval_chain : Ms -> Ls -> Hs -> Ss -> ClobberSet ->\n    list expr -> list value -> list Es -> Prop :=\n  | eval_chain_empty (M:Ms) (L:Ls) (H:Hs) (S:Ss) (C:ClobberSet) :\n    eval_chain M L H S C [] [] []\n  | eval_chain_nonempty (M:Ms) (L:Ls) (H:Hs) (S0:Ss) (C:ClobberSet)\n      (e1 : expr) (v1 : value) (E1 : Es)\n      (es : list expr) (vs : list value) (Elist : list Es)\n    (z1 : let S1 := apply S0 E1 in eval M L H S1 C e1 v1 E1 /\\\n      eval_chain M L H S1 C es vs Elist) :\n      eval_chain M L H (apply S0 E1) C (e1::es) (v1::vs) (E1::Elist)\nwith\n  eval_chain_call : Ms -> Ls -> Hs -> list Ss -> ClobberSet ->\n    list expr -> list value -> list Es -> Prop :=\n  | eval_chain_call_empty (M:Ms) (L:Ls) (H:Hs) (S:Ss) (C:ClobberSet) :\n    eval_chain_call M L H [] C [] [] []\n  | eval_chain_call_nonempty (M:Ms) (L:Ls) (H:Hs) (S1:Ss) (C:ClobberSet)\n      (e1 : expr) (v1 : value) (E1 : Es)\n      (Slist : list Ss) (es : list expr) (vs : list value) (Elist : list Es)\n    (z1 : eval M L H S1 C e1 v1 E1 /\\ eval_chain_call M L H Slist C es vs Elist) :\n      eval_chain_call M L H (S1::Slist) C (e1::es) (v1::vs) (E1::Elist)\n.\n\nCheck eval.\n\n(* alternate Fixpoint version of eval_chain\n    match es, vs, Elist with\n    | [] , [] , [] => True\n    | e1::es', v1 :: vs', E1 :: Elist' =>\n      let S1 := apply S0 E1 in\n      eval M L H S0 C e1 v1 E1 /\\ eval_chain M L H S1 C es' vs' Elist'\n    | _, _ => False\n    end\n*)\n\n(* used in theorem 1, 3 *)\n(* E :M Φ *)\nDefinition privileges_cover_ops (E:Es) (M:Ms) (Φ:Phis) : Prop :=\n  forall ep, In ep E -> match ep with\n  | SRead l _ _ _ =>\n      exists r mr, M r = Some mr /\\ In l mr /\\ In (Reads r) Φ\n  | SWrite l _ _ _ =>\n      exists r mr, M r = Some mr /\\ In l mr /\\ In (Writes r) Φ\n  | SReduce id l _ _ _ =>\n      exists r mr, M r = Some mr /\\ In l mr /\\ In (Reduces id r) Φ\n  end.\n", "meta": {"author": "tkwa", "repo": "CoqLegion", "sha": "0989eec8c2cb2e960fe8f3c796ecc30888edb6c0", "save_path": "github-repos/coq/tkwa-CoqLegion", "path": "github-repos/coq/tkwa-CoqLegion/CoqLegion-0989eec8c2cb2e960fe8f3c796ecc30888edb6c0/Definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.26508699659937485}}
{"text": "Require Export assetmapping_spl_def.\nRequire Export featuremodel_spl_def.\nRequire Export cktrans_spl_def. \nRequire Export spl_int.\nRequire Export assetmapping_spl_int.\nRequire Export assetmapping_spl_inst.\n\nRequire Export featuremodel_spl_int.\nRequire Export featuremodel_spl_inst.\nRequire Export featuremodel_spl_proofs.\n\nRequire Export cktrans_spl_int.\nRequire Export cktrans_spl_proofs.\nRequire Export cktrans_spl_inst.\n\nRequire Export maps_proofs.\nRequire Export maps_int.\nRequire Export maps_def.\nRequire Export maps_inst.\n\nRequire Export spl_def.\nRequire Export spl_proofs.\n\nRequire Import Coq.Lists.ListSet.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Init.Specif.\nRequire Export Coq.Lists.List.\nImport Maps.\nImport CKTransSPL.\nImport FeatureModelSPL.\nImport AssetMappingSPL.\nImport SPL. \n\nProgram Instance Ins_SPL {FMs: FeatureModel FM Conf}\n         {AssetM : AssetMapping Asset AssetName AM}\n         {ckTrans: CKTrans FM Asset AM CK Conf}\n         {spl: SPL Asset Conf FM AM CK ArbitrarySPL} :\n           SPL Asset Conf FM AM CK PL :=\n{\n  getFM:= getFM_func;\n  getAM:= getAM_func;\n  getCK:= getCK_func;\n  getCk:= getCk_func;\n  genPL:= genPL_func;\n  genPLCK := genPLCK_func;\n  gerPL:= gerPL_func; \n  wfPL := wfPL_func;\n  plRefinement:= plRefinement_func;\n  products:= products_func;\n  plRefinementAlt:= plRefinementAlt_func;\n  subsetProducts:= subsetProducts_func;\n  plWeakRefinement:= plWeakRefinement_func;\n  strongerPLRefinement:= strongerPLrefinement_func;\n\n}.\n Next Obligation. {(*fmEquivalenceCompositionality*)\n  intros.\n    split.\n    + unfold plRefinement_func. intros. exists c1. split.\n      -  unfold getFM_func. simpl.  unfold getFM_func in H0. destruct pl in H0.\n         simpl in H0. destruct pls0 in H0. simpl in H0. destruct p. simpl in H0. \n         rewrite f in H0. rewrite fm. apply H0.\n      - unfold getCK_func. unfold getAM_func. simpl.\n        apply assetRefinementReflexivity_axiom.\n    + unfold wfPL_func. intros.\n      unfold equivalentFMs in H. intuition.\n} Qed. Next Obligation. {(*weakFMcompositionality*)\n  intros.  \n    unfold plRefinement_func. \n    intros. exists c1.  split.\n      +  unfold getFM_func. simpl.  unfold getFM_func in H1. destruct pl in H1.\n        simpl in H1. destruct pls0 in H1. simpl in H1. destruct p. simpl in H1.  rewrite f in H1.\n        rewrite fm. apply H1. \n      + unfold getCK_func. unfold getAM_func. simpl.\n        apply assetRefinementReflexivity_axiom.\n\n} Qed. Next Obligation. {(*ckEquivalenceCompositionality*) \n  intros.\n    split.\n    + unfold plRefinement_func. intros. exists c1. split.\n      -  unfold getFM_func. simpl.  unfold getFM_func in H0. destruct pl in H0.\n        simpl in H0. destruct pls0 in H0. simpl in H0. destruct p. simpl in H0.\n        destruct fm, f. apply H0.\n      - unfold getCK_func. unfold getAM_func. simpl.\n        apply assetRefinementReflexivity_axiom.\n     + unfold wfPL_func. intros.\n      unfold equivalentFMs in H.\n      intuition.\n\n} Qed. Next Obligation. {(*weakerCKcompositionality*)\n intros.\n    split.\n    + unfold plRefinement_func. intros. exists c1. split.\n      -  unfold getFM_func. simpl.  unfold getFM_func in H0. destruct pl in H0.\n        simpl in H0. destruct pls0 in H0. simpl in H0. destruct p. simpl in H0.  rewrite f in H0.\n        rewrite fm. apply H0.\n      - unfold getCK_func. unfold getAM_func. simpl.\n        apply assetRefinementReflexivity_axiom.\n    + unfold wfPL_func. intros.\n      unfold equivalentFMs in H.\n      intuition.\n} Qed. Next Obligation. {(*amRefinementCompositionality*)\n   intros.\n    split.\n    + unfold plRefinement_func. intros. exists c1. split.\n      -  unfold getFM_func. simpl.  unfold getFM_func in H0. destruct pl in H0.\n        simpl in H0. destruct pls0 in H0. simpl in H0. destruct p. simpl in H0.  rewrite f in H0.\n        rewrite fm. apply H0.\n      - unfold getCK_func. unfold getAM_func. simpl.\n        apply assetRefinementReflexivity_axiom.\n    + unfold wfPL_func. intros.\n      unfold equivalentFMs in H.\n      intuition.\n\n} Qed. Next Obligation. {(*fullCompositionality*)\n   intros.\n    split.\n    +  unfold plRefinement_func. intros. exists c1. split.\n      -  unfold getFM_func. simpl. unfold getFM_func in H2. \n        simpl in H2. destruct pl in H2. simpl in H2. \n        destruct pls0 in H2. simpl in H2. destruct p. simpl in H2. \n        destruct fm. rewrite f in H2. apply H2.\n      - unfold getCK_func. unfold getAM_func. simpl.\n        apply assetRefinementReflexivity_axiom.\n    + unfold wfPL_func. intros.\n      unfold equivalentFMs in H.\n      intuition.\n\n} Qed. Next Obligation. \n{(*weakFullCompositionality*)\n\n intros.  \n    unfold plRefinement_func. \n    intros. exists c1.  split.\n      +  unfold getFM_func. simpl.  unfold getFM_func in H2. destruct pl in H2.\n        simpl in H2. destruct pls0 in H2. simpl in H2. destruct p. \n        simpl in H2.  rewrite f in H2.\n        rewrite fm. apply H2. \n      + unfold getCK_func. unfold getAM_func. simpl.\n        apply assetRefinementReflexivity_axiom.\n\n} Qed. Next Obligation. \n{(*fullCompositionality2*)\n intros.\n    split.\n    +  unfold plRefinement_func. intros. exists c1. split.\n      -  unfold getFM_func. simpl. unfold getFM_func in H2. \n        simpl in H2. destruct pl in H2. simpl in H2. destruct pls0 in H2. simpl in H2. destruct p. \n        simpl in H2.  destruct fm. rewrite f in H2. apply H2.\n      - unfold getCK_func. unfold getAM_func. simpl.\n        apply assetRefinementReflexivity_axiom.\n    + unfold wfPL_func. intros.\n      unfold equivalentFMs in H.\n      intuition.\n\n} Qed. Next Obligation. { (*weakFullCompositionality2*)\n intros.  \n    unfold plRefinement_func. \n    intros. exists c1.  split.\n      +  unfold getFM_func. simpl.  unfold getFM_func in H2. destruct pl in H2.\n        simpl in H2. destruct pls0 in H2. simpl in H2. destruct p. \n        simpl in H2.  rewrite f in H2.\n        rewrite fm. apply H2. \n      + unfold getCK_func. unfold getAM_func. simpl.\n        apply assetRefinementReflexivity_axiom.\n\n}  Qed. Next Obligation. \n{(*plRefAlt*)\n  split.\n        + intros.  apply equalsRefinementAlt. reflexivity.\n        + intros. destruct H. unfold plRefinementAlt in H. unfold plRefinementAlt_func.\n          intros p3 H1.\n           specialize (H p3). apply H in H1. destruct H1. unfold plRefinementAlt_func in H0.\n           specialize (H0 x). destruct H1. apply H0 in H1.\n           destruct H1. destruct H1.  exists x0.  split.   \n            - apply H1.\n            - generalize H2, H3. apply assetRefinementTranstivity_axiom. \n\n} Qed. Next Obligation.\n{(*strongerPLref*)\n  intros.\n    split.\n    + apply equalsStrongerPL. reflexivity. \n    + unfold strongerPLrefinement_func. intros. destruct H. specialize (H c). specialize (H1 c).\n      destruct c. apply H in H0. destruct H0.\n      split.\n      - apply H1 in H0. destruct H0. apply H0.\n      -  apply H1 in H0. destruct H0.  generalize H3. generalize H2. apply assetRefinementTranstivity_axiom.\n\n} Qed. Next Obligation.\n{(*plRef*)\n  intros.\n      split.\n      + apply equalsPL. reflexivity.\n      + unfold plRefinement_func. intros. destruct H. specialize (H c1).\n        specialize (H1 c1). destruct c1. apply H in H0. destruct H0.\n        destruct H0. destruct x. apply H1 in H0. destruct H0. destruct H0.\n        exists x. split.\n        - apply H0.\n        - generalize H3. generalize H2. apply assetRefinementTranstivity_axiom.\n\n} Qed. ", "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/Instances/spl_inst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.26508699659937485}}
{"text": "Set Implicit Arguments.\n\nRequire Import Platform.Cito.CModule.\nRequire Import Platform.Cito.GoodModuleDec.\nRequire Import Platform.Cito.GoodModule.\nRequire Import Platform.Cito.GoodFunction.\n\nDefinition cfun_to_gfun (name : string) (f : CFun) : GoodFunction.\n  refine (Build_GoodFunction (Build_Func name f) _).\n  destruct f; simpl in *.\n  Require Import Platform.Cito.GoodModuleDecFacts.\n  eapply is_good_func_sound; eauto.\nDefined.\n\nRequire Import Platform.Cito.StringMap.\nRequire Import Platform.Cito.StringMapFacts.\n\nDefinition cfuns_to_gfuns (fs : StringMap.t CFun) : list GoodFunction := List.map (uncurry cfun_to_gfun) (StringMap.elements fs).\n\nRequire Import Platform.Cito.NameDecoration.\n\nLemma cfuns_to_gfuns_nodup fs : NoDup (List.map (fun (f : GoodFunction) => SyntaxFunc.Name f) (cfuns_to_gfuns fs)).\nProof.\n  unfold cfuns_to_gfuns.\n  rewrite map_map.\n  simpl.\n  eapply NoDup_elements; eauto.\nQed.\n\nDefinition cmodule_to_gmodule name (H : is_good_module_name name = true) (m : CModule) : GoodModule.GoodModule.\n  refine (@Build_GoodModule name _ (cfuns_to_gfuns (Funs m)) _).\n  eapply is_good_module_name_sound; eauto.\n  eapply cfuns_to_gfuns_nodup.\nDefined.\n\nLemma NoDup_ArgVars (f : CFun) : NoDup (ArgVars f).\nProof.\n  destruct f; simpl.\n  Require Import Platform.Cito.GoodModuleDecFacts.\n  eapply is_good_func_sound in good_func.\n  destruct good_func.\n  eauto.\nQed.\n\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/CModuleFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883592602049, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2650869965993748}}
{"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 quiztree.\nRequire Import part.\nRequire Import znat.\nRequire Import discharge.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(* Ruling out a part using a combination of discharging and reducibility.    *)\n(* In principle, this brings together almost all the elements of the proof   *)\n(* development, so for modularity we only import a predicate on parts from   *)\n(* the reducibility half, with the assumption that it is always false when   *)\n(* the part fits the map. We'll tie up everithing in present.v (anyway,      *)\n(* we can't really use the reducibility check in recursive functions, that   *)\n(* causes the recursion check to diverge).                                   *)\n\n(* The hubcap concrete syntax is used directly in the source file, so the    *)\n(* sector indices start at 1 in the concrete syntax, and are shifted by the  *)\n(* parsing and pretty-printing. An additional shift by 2 is done during the  *)\n(* verification, to line up with the rules.                                  *)\n\n(* We also define a simpler source cap check, which is used in present12.v   *)\n(* to exclude hub sizes greater than 11 (using lemma dscore_cap1).           *)\n\n(* The sequence structure of hubcaps is compressed, not for speed, but to    *)\n(* save space in the large proofs generated by the presentation scripts.     *)\n\nInductive hubcap : Set :=\n  | Hubcap0\n  | Hubcap1 (j : nat) (b : znat) (hc : hubcap)\n  | Hubcap2 (j1 j2 : nat) (b : znat) (hc : hubcap).\n\nModule HubcapSyntax.\n\nNotation \"'[]'\" := Hubcap0 (at level 8).\nNotation \"'T' [ j1 ] '<=' b h\" := (Hubcap1 (pred j1) (Zpos b) h)\n  (at level 8, j1, b at level 0, h at level 9,\n   format \"'T' [ j1 ] '<=' b  h\").\nNotation \"'T' [ j1 ] '<=' ( - b ) h\" := (Hubcap1 (pred j1) (- (Zpos b)) h)\n  (at level 8, j1, b at level 0, h at level 9,\n   format \"'T' [ j1 ] '<=' ( - b )  h\").\nNotation \"'T' [ j1 , j2 ] '<=' b h\" := (Hubcap2 (pred j1) (pred j2) (Zpos b) h)\n  (at level 8, j1, j2, b at level 0, h at level 9,\n   format \"'T' [ j1 , j2 ] '<=' b  h\").\nNotation \"'T' [ j1 , j2 ] '<=' ( - b ) h\" :=\n     (Hubcap2 (pred j1) (pred j2) (- (Zpos b)) h)\n  (at level 8, j1, j2, b at level 0, h at level 9,\n   format \"'T' [ j1 , j2 ] '<=' ( - b )  h\").\n\nEnd HubcapSyntax.\n\nSection Hubcap.\n\nVariables (nhub : nat) (redp : part -> bool) (rf : drule_fork nhub).\nLet rs0 := source_drules rf.\nLet rt0 := target_drules rf.\n\nVariable g : hypermap.\nHypothesis Hg : plain_cubic_pentagonal g.\nLet HgF : pentagonal g := Hg.\nHypothesis Hredp : forall (x : g) p, redp p -> negb (exact_fitp x p).\n\n(* Source bound checking.                                                   *)\n\nFixpoint check_dbound1_rec (p : part) (rs : drules) (ns m : nat) {struct m}\n                       : bool :=\n  if m is S m' then\n    if rs is Adds r rs' then\n      if size rs' < ns then true else\n      let p' := meet_part p r in\n      (let: SortDrules dns rs'' := sort_drules p' rs' in\n       if ns - dns is S ns' then check_dbound1_rec p' rs'' ns' m' else redp p')\n      && check_dbound1_rec p rs' ns m'\n    else true\n  else false.\n\nDefinition check_dbound1 p ns :=\n  let: DruleFork rs _ _ := rf in check_dbound1_rec p rs ns (size rs + 1).\n\nLemma check_dbound1P : forall (x : g) p ns,\n arity x = nhub -> exact_fitp x p -> check_dbound1 p ns -> dbound1 rs0 x <= ns.\nProof.\nmove=> x p ns Hxn; rewrite /check_dbound1 /rs0 /source_drules.\ncase: rf => rs _ _; move: (size rs + 1) => m.\nelim: m ns rs p => // [m Hrec] ns [|r rs] //= p Hxp.\ncase Hns: (size rs < ns).\n  clear; apply: leq_trans Hns.\n  by rewrite -add1n; apply leq_add2; [ case (fitp x r) | apply: count_size ].\nset p' := meet_part p r; case/andP{Hn}.\ncase Hxr: (fitp x r); last by clear; apply: Hrec => //=; rewrite Hxr.\nhave Exp': exact_fitp x p' by apply: exact_fitp_meet.\ncase/andP: (Exp') => _ Hxp'.\ncase: (sort_drulesP Hxp' rs) => [dns rs'].\ncase Dns': (ns - dns) => [|ns']; first by move=> *; case/idPn: Exp'; auto.\nhave Hns': dns < ns by rewrite ltn_lt0sub Dns'.\nmove=> Hrsp' _; rewrite -(leq_add_sub (ltnW Hns')) Dns' /=.\nrewrite add1n addnS ltnS leq_add2l; eauto.\nQed.\n\nFixpoint check_unfit (p : part) (ru : drules) {struct ru} : bool :=\n  if ru is Adds r ru' then\n    if cmp_part p r is Psubset then true else check_unfit p ru'\n  else false.\n\nLemma check_unfitP : forall (x : g) p, fitp x p -> forall ru,\n  dbound1 ru x = 0 -> check_unfit p ru = false.\nProof.\nmove=> x p Hxp; elim=> [|r ru Hrec] //=.\ncase Hxr: (fitp x r) => // Hru; rewrite {Hrec Hru}(Hrec Hru).\nby rewrite (fitp_cmp Hxp) in Hxr; case: (cmp_part p r) Hxr.\nQed.\n\n(* Single target bound checking.                                               *)\n\nFixpoint check_dbound2_rec (p : part) (rt rs ru : drules) (nt m : nat) {struct m}\n                         : bool :=\n  if m is S m' then\n    if rt is Adds r rt' then\n      if size rt' < nt then true else\n      let p' := meet_part p r in\n      (if check_unfit p' ru then true else\n       let: SortDrules dnt rt'' := sort_drules p' rt' in\n       let: SortDrules dns rs' := sort_drules p' rs in\n       if dns + nt - dnt is S nt' then\n          check_dbound2_rec p' rt'' rs' ru nt' m'\n       else redp p')\n      && check_dbound2_rec p rt' rs (Adds r ru) nt m'\n    else true\n  else false.\n\nDefinition check_dbound2 p b :=\n  let: DruleFork rs rt _ := rf in\n  let: SortDrules dnt rt' := sort_drules p rt in\n  let: SortDrules dns rs' := sort_drules p rs in\n  if (dns - dnt + b)%Z is Zpos nt then\n    check_dbound2_rec p rt' rs' seq0 nt (size rt' + 2)\n  else false.\n\nLemma check_dbound2P : forall (x : g) p b, arity x = nhub ->\n  exact_fitp x p -> check_dbound2 p b -> (dbound2 rt0 rs0 x <= b)%Z.\nProof.\nmove=> x p b Hxn Exp; rewrite /check_dbound2 /dbound2; case/andP: (Exp) => _ Hxp.\nrewrite /rs0 /rt0 /source_drules /target_drules; case: rf => rs rt _.\nset ru : drules := seq0; have Hru: dbound1 ru x = 0 by done.\ncase: {rt}(sort_drulesP Hxp rt)=> dnt rt; set m := size rt + 2.\ncase: {rs Hxp}(sort_drulesP Hxp rs) => dns rs Hp.\nrewrite !zpos_addn -addzA addzCA /leqz -addzA -oppz_sub leqzI oppz_sub.\nrewrite addzC -!addzA addzCA (addzA dns).\ncase: {dns dnt b}(dns - dnt + b)%Z Hp => // nt; rewrite -zpos_addn leqz_nat.\nelim: {rt}m nt (rt) rs ru Hru p Exp => // [m Hrec] nt.\ncase=> //= [r rt] rs ru Hru p Exp; case Hnt: (size rt < nt).\n  clear; apply: (leq_trans _ (leq_addl _ _)); apply: leq_trans Hnt.\n  by rewrite -add1n; apply leq_add2; [ case (fitp x r) | apply: count_size ].\nset p' := meet_part p r; case/andP{Hnt}.\ncase Hxr: (fitp x r); last by clear; apply: Hrec => //=; rewrite Hxr.\nhave Exp': exact_fitp x p' by apply: exact_fitp_meet.\ncase/andP: (Exp') => [_ Hxp'] Hp'rt _; move: Hp'rt.\nrewrite (check_unfitP Hxp' Hru).\ncase: {rt}(sort_drulesP Hxp' rt) => [dnt rt].\ncase: {Hxp' rs}(sort_drulesP Hxp' rs) => [dns rs].\ncase Dnt': (subn (addn dns nt) dnt) => [|nt'].\n  by move=> *; case/idPn: Exp'; auto.\nhave Hnt': dnt < dns + nt by rewrite ltn_lt0sub Dnt'.\nmove=> Hrp'; rewrite -!addnA (addnCA dns) -(leq_add_sub (ltnW Hnt')) Dnt' /=.\nrewrite !(addnC dnt) !addnA leq_add2r addnS add1n ltnS; eauto.\nQed.\n\n(* Dual target bound check.                                                      *)\n\nFixpoint check_2dbound2_rec\n          (p1 p2 : part) (rt1 rs1 ru1 rt2 rs2 ru2 : drules) (i nt m : nat)\n           {struct m} : bool :=\n  if m is S m' then\n    if rt1 is Adds r rt1' then\n      if size rt1' + size rt2 < nt then true else\n      let p1' := meet_part p1 r in\n      let p2' := rot_part i p1' in\n      (if check_unfit p1' ru1 || check_unfit p2' ru2 then true else\n       let: SortDrules dnt1 rt1'' := sort_drules p1' rt1' in\n       let: SortDrules dns1 rs1' := sort_drules p1' rs1 in\n       let: SortDrules dnt2 rt2' := sort_drules p2' rt2 in\n       let: SortDrules dns2 rs2' := sort_drules p2' rs2 in\n       if dns1 + (dns2 + nt) - (dnt1 + dnt2) is S nt' then\n         check_2dbound2_rec p1' p2' rt1'' rs1' ru1 rt2' rs2' ru2 i nt' m'\n       else redp p1')\n      && check_2dbound2_rec p1 p2 rt1' rs1 (Adds r ru1) rt2 rs2 ru2 i nt m'\n    else\n     if rt2 is Seq0 then true else\n     check_2dbound2_rec p2 p1 rt2 rs2 ru2 rt1 rs1 ru1 (nhub - i) nt m'\n  else false.\n\nDefinition check_2dbound2 p1 i b :=\n  let p2 := rot_part i p1 in\n  let: DruleFork rs rt _ := rf in\n  let: SortDrules dnt1 rt1 := sort_drules p1 rt in\n  let: SortDrules dns1 rs1 := sort_drules p1 rs in\n  let: SortDrules dnt2 rt2 := sort_drules p2 rt in\n  let: SortDrules dns2 rs2 := sort_drules p2 rs in\n  if ((dns1 + dns2)%dnat - (dnt1 + dnt2)%dnat + b)%Z is Zpos nt then\n    let m := size rt1 + (size rt2 + 3) in\n    check_2dbound2_rec p1 p2 rt1 rs1 seq0 rt2 rs2 seq0 i nt m\n  else false.\n\nLemma check_2dbound2P : forall (x : g) p i b,\n    arity x = nhub -> exact_fitp x p -> i <= nhub -> check_2dbound2 p i b ->\n  (dbound2 rt0 rs0 x + dbound2 rt0 rs0 (iter i face x) <= b)%Z.\nProof.\nmove=> x1 p1 i b Hx1n Ex1p Hi; rewrite /check_2dbound2 /dbound2.\nrewrite /rs0 /rt0 /source_drules /target_drules; case: rf => rs rt _.\nset ru : drules := seq0; have Hru: forall x : g, dbound1 ru x = 0 by done.\nset p2 := rot_part i p1; set x2 := iter i face x1.\nmove: ru {2 4}ru {Hru}(Hru x1) (Hru x2) => ru1 ru2 Hru1 Hru2.\ncase/andP: (Ex1p); rewrite Hx1n; move/eqP=> Ep1 Hx1p.\nhave Ex2p: exact_fitp x2 p2 by rewrite /x2 /p2 -fitp_rot -?Ep1.\ncase: (sort_drulesP Hx1p rt) => [dnt1 rt1].\ncase: {Hx1p Ep1}(sort_drulesP Hx1p rs) => [dns1 rs1].\ncase/andP: (Ex2p) => [_ Hx2p].\ncase: {rt}(sort_drulesP Hx2p rt) => [dnt2 rt2]; move: (size rt1 + _) => m.\ncase: {rs Hx2p}(sort_drulesP Hx2p rs) => [dns2 rs2]; rewrite !zpos_addn => Hp.\nrewrite -addzA (addzCA (- _)) -oppz_add (addzC dnt1) -addzA 2!(addzA dnt1).\nrewrite -(addzA (dnt1 + _)) (addzCA (dnt1 + _)) addzA -oppz_sub.\nrewrite (addzC dns1) -(addzA _ dns1) (addzA dns1) (addzC (dns1 + _)).\nrewrite /leqz -addzA -oppz_add leqzI addzA -2!addzA (addzA (dns1 + _)).\ncase: {dns1 dns2 dnt1 dnt2 b}(dns1 + dns2 - (dnt1 + dnt2) + b)%Z Hp => // nt.\nrewrite -!zpos_addn -addnA leqz_nat; move: rt2 rs2 ru2 p2 Hru2 Ex2p; rewrite {}/x2.\nelim: m rt1 => // m Hrec [|r rt1] /= in nt x1 i Hx1n Hi rs1 ru1 p1 Hru1 Ex1p |- *.\n  set x2 := iter i face x1; set i' := nhub - i.\n  case=> // r rt; move: {r rt}(Adds r rt) => rt2 rs2 ru2 p2 Hru2 Ex2p.\n  rewrite addnC addnCA -[0]/(dbound1 seq0 x1); move: rs1 ru1 p1 Hru1 Ex1p.\n  have <-: iter i' face x2 = x1.\n    rewrite /x2 -iter_addn addnC /i' leq_add_sub // -Hx1n; exact: iter_face_arity.\n  apply: Hrec; auto; [by rewrite /x2 arity_iter_face | exact: leq_subr].\nset x2 := iter i face x1 => rt2 rs2 ru2 p2 Hru2 Ex2p.\ncase Hnt: (size rt1 + size rt2 < nt).\n  rewrite addnA => _; apply: leq_trans (leq_addl _ _); apply: leq_trans Hnt.\n  rewrite -add1n -addnA; apply leq_add2; first by case (fitp x1 r).\n  by apply leq_add2; apply: count_size.\nset p1' := meet_part p1 r; case/andP{Hnt}.\ncase Hxr: (fitp x1 r);\n  last by clear; rewrite /= add0n /x2; apply Hrec; rewrite //= Hxr.\nhave Ex1p': exact_fitp x1 p1' by apply: exact_fitp_meet.\ncase/andP: (Ex1p'); rewrite Hx1n; move/eqP=> Ep1' Hx1p'.\nset p2' := rot_part i p1'.\nhave Ex2p': exact_fitp x2 p2' by rewrite /x2 /p2' -fitp_rot -?Ep1'.\ncase/andP: (Ex2p') => [_ Hx2p'] Hp'nt _; move: Hp'nt.\nrewrite (check_unfitP Hx1p' Hru1) (check_unfitP Hx2p' Hru2) /=.\ncase: {rt1}(sort_drulesP Hx1p' rt1) => [dnt1 rt1].\ncase: {rs1 Hx1p'}(sort_drulesP Hx1p' rs1) => [dns1 rs1].\ncase: {rt2}(sort_drulesP Hx2p' rt2) => [dnt2 rt2].\ncase: {rs2 Hx2p'}(sort_drulesP Hx2p' rs2) => [dns2 rs2].\ncase Dnt': (dns1 + (dns2 + nt) - (dnt1 + dnt2)) => [|nt'].\n  by move=> *; case/idPn: Ex1p'; auto.\nhave Hnt': dnt1 + dnt2 < dns1 + (dns2 + nt) by rewrite ltn_lt0sub Dnt'.\nmove=> Hrp'; rewrite -!addnA !(addnCA dns1) !(addnCA dns2).\nrewrite -(leq_add_sub (ltnW Hnt')) {}Dnt' add1n !addnS ltnS.\nrewrite -!addnA -!(addnCA dnt1) -!(addnCA dnt2) !leq_add2l /x2; eauto.\nQed.\n\n(* Cover checking; we compute the multiset of indices in a first pass, then *)\n(* check coverage.                                                          *)\n\nFixpoint tally_hubcap (hc : hubcap) : natseq :=\n  match hc with\n  | Hubcap1 i _ hc' => incr_sub (tally_hubcap hc') i\n  | Hubcap2 i j _ hc' => incr_sub (incr_sub (tally_hubcap hc') i) j\n  | _ => seq0\n  end.\n\nFixpoint hubcap_cover_rec (v : natseq) (b : znat) (hc : hubcap) {struct hc}\n                          : bool :=\n  match hc with\n  | Hubcap1 i b' hc' =>\n    match sub 0 v i with\n    | 1 => hubcap_cover_rec v (b' + (b' + b)) hc'\n    | _ => false\n    end\n  | Hubcap2 i j b' hc' =>\n    match sub 0 v i, sub 0 v j with\n    | 2, 2 => hubcap_cover_rec v (b' + b) hc'\n    | 1, 1 => hubcap_cover_rec v (b' + (b' + b)) hc'\n    | _, _ => false\n    end\n  | Hubcap0 =>\n    negb (posz b)\n  end.\n\nDefinition hubcap_cover hc :=\n  let b := dboundK nhub in\n  let bb := decz (b + b) in\n  let v := tally_hubcap hc in\n  and3b (size v =d nhub) (negb (v 0)) (hubcap_cover_rec v bb hc).\n\nDefinition hubcap_rot j := rot_part (if j is S (S j') then j' else nhub + j - 2).\n\nLemma fit_hubcap_rot : forall (x : g) p, arity x = nhub -> exact_fitp x p ->\n  forall j, j < nhub -> exact_fitp (iter j face (inv_face2 x)) (hubcap_rot j p).\nProof.\nmove=> x p Hxn Hxp; have Hn := (ltnW (ltnW (ltnW (HgF x)))); rewrite Hxn in Hn.\ncase/andP: (Hxp); rewrite Hxn; move/eqP=> Ep _.\ncase=> [|[|j]] Hj; rewrite -?iter_f.\n- rewrite -(iter_face_arity x) Hxn -(leq_add_sub Hn) /hubcap_rot addn0.\n  by rewrite /inv_face2 /= !Eface -fitp_rot -?Ep ?leq_subr.\n- rewrite -(iter_face_arity x) Hxn -(leq_add_sub (ltnW Hn)) /hubcap_rot addn1.\n  by rewrite subSS /inv_face2 /= Enode Eface -fitp_rot -?Ep ?leq_subr.\nby rewrite /hubcap_rot /inv_face2 /= !Enode -fitp_rot -?Ep //; do 3 apply ltnW.\nQed.\n\nDefinition hub_subn i j := (if j <= i then i else i + nhub) - j.\n\nLemma hub_subn_hub : forall i j, i < nhub -> j < nhub -> (hub_subn i j) <= nhub.\nProof.\nmove=> i j Hi Hj; rewrite /hub_subn leq_sub_add.\ncase: (leqP j i) => Hij; first by apply: (leq_trans (ltnW Hi)); apply leq_addl.\nby rewrite leq_add2r; apply ltnW.\nQed.\n\nLemma iter_hub_subn : forall i j, j < nhub -> forall x : g, arity x = nhub ->\n  iter (hub_subn i j) face (iter j face x) = iter i face x.\nProof.\nmove=> i j Hj x Hxn; rewrite -iter_addn addnC /hub_subn leq_add_sub //.\n  by case (j <= i); last by rewrite iter_addn -Hxn iter_face_arity.\nby case Hij: (j <= i); last by apply: (leq_trans (ltnW Hj)); apply leq_addl.\nQed.\n\nFixpoint hubcap_fit (p : part) (hc : hubcap) {struct hc} : bool :=\n  match hc with\n  | Hubcap1 j b hc' =>\n    check_dbound2 (hubcap_rot j p) b && hubcap_fit p hc'\n  | Hubcap2 j1 j2 b hc' =>\n    check_2dbound2 (hubcap_rot j1 p) (hub_subn j2 j1) b && hubcap_fit p hc'\n  | Hubcap0 =>\n    true\n  end.\n\nLemma hubcap_fit_bound : forall (x : g) p hc, size_part p = nhub ->\n  posz (dscore x) -> hubcap_cover hc && hubcap_fit p hc -> negb (exact_fitp x p).\nProof.\nmove=> x p hc Ep Hx Hhc; apply/idP => Exp; case/andP: (Exp); rewrite Ep.\nmove/eqP=> Hxn _; case/idPn: Hx; case/andP: Hhc; case/and3P.\nset v := tally_hubcap hc; set b0 := dboundK nhub; move/eqP=> Ev Hv0 Hhc Hhcp.\npose vb (v' : natseq) := forall i, sub 0 v' i <= sub 0 v i.\nhave Hvb: forall v' i, vb (incr_sub v' i) -> sub 0 v' i < sub 0 v i /\\ vb v'.\n  move=> v' i Hv'; split; first by move: (Hv' i); rewrite sub_incr_sub set11.\n  by move=> j; apply: leq_trans (Hv' j); rewrite sub_incr_sub leq_addl.\npose x' := inv_face2 x.\npose db2 (v' : natseq) (y : g) :=\n  let b := dbound2 rt0 rs0 y in\n  let i := findex face x' y in\n  match sub 0 v' i, sub 0 v i with\n  | 1, 1 => (b + b)%Z\n  | n, _ => iter n (addz b) 0\n  end.\nhave Hxx': cface x x' by rewrite 2!cface1r /x' /inv_face2 !Enode connect0.\nhave Edb2: forall v' i, vb (incr_sub v' i) -> i < nhub ->\n    let y := iter i face x' in let b := dbound2 rt0 rs0 y in\n    let is11 := (sub 0 v' i =d 0) && (sub 0 v i =d 1) in\n    let bb := if is11 then (b + b)%Z else b in\n    sumz (db2 (incr_sub v' i)) (cface x') = (bb + sumz (db2 v') (cface x'))%Z.\n  move=> v' i Hv' Hi y b is11 bb; rewrite -Hxn (arity_cface Hxx') in Hi.\n  rewrite 2!(sumz_setID (set1 y) _ (cface x')) addzA; congr addz.\n    have Ex'y: setI (cface x') (set1 y) =1 set1 y.\n      move=> z; rewrite /setI andbC; case: (y =P z) => // <-.\n      by rewrite /y fconnect_iter.\n    rewrite !(eq_sumz_r Ex'y) !sumz_set1 /db2 /= /y findex_iter //.\n    rewrite sub_incr_sub set11 /= /bb /is11; case/Hvb: Hv'.\n    by case: (sub 0 v' i) (sub 0 v i) => [|[|m]] [|[|k]] // _ _; rewrite addz0.\n  apply: eq_sumz_l => z; move/andP=> [Hyz Hz]; rewrite /db2 sub_incr_sub.\n  case: (i =P findex face x' z) => // Di; case/eqP: Hyz.\n  by rewrite /y Di; apply iter_findex.\nhave Hdb2: negb (posz (decz (b0 + b0) + sumz (db2 v) (cface x'))).\n  have Hvbv: vb v by move=> i; apply leqnn.\n  move: (decz (addz b0 b0)) Hvbv Hhc Hhcp => b.\n  rewrite {1 3}/v -{2}[b]subz0 addzC addz_subA -oppz_sub -leq0z sub0z.\n  elim: (hc) b => [|i b' hc' Hrec|j i b' hc' Hrec] b /= Hiv'.\n  - rewrite -(@eq_sumz g (@zconst g 0)).\n      by rewrite sumz_const leq0z oppz_opp addzC /= addz0.\n    by move=> y; rewrite /db2 /= sub_default.\n  - case Dvi: (sub 0 v i) (Hvb _ _ Hiv') => [|[|k]] // [Hiv Hv'] Hhc'.\n    move/andP=> [Hip Hhc'p]; rewrite ltnS leqn0 in Hiv.\n    case: (leqP nhub i) => Hi; first by rewrite sub_default ?Ev in Dvi.\n    apply: {Hrec Hv' Hhc' Hhc'p}(leqz_trans (Hrec _ Hv' Hhc' Hhc'p)).\n    rewrite leqz_opp2 Edb2 // Dvi Hiv /= !addzA leqz_add2r {b}.\n    rewrite addzC -addzA leqz_add2l {db2 Edb2}.\n    have Hx'p := fit_hubcap_rot Hxn Exp Hi.\n    rewrite (arity_cface Hxx') -(arity_iter_face i x') in Hxn.\n    by apply leqz_add2; exact (check_dbound2P Hxn Hx'p Hip).\n  case Dvi: (sub 0 v i) (Hvb _ _ Hiv') => [|[|[|k]]] // [Hiv Hjv'];\n    case Dvj: (sub 0 v j) (Hvb _ _ Hjv') => [|[|[|k']]] // [Hjv Hv'] Hhc'.\n  - move/andP=> [Hijp Hhc'p]; rewrite !ltnS !leqn0 in Hiv Hjv.\n    case: (leqP nhub i) => Hi; first by rewrite sub_default ?Ev in Dvi.\n    case: (leqP nhub j) => Hj; first by rewrite sub_default ?Ev in Dvj.\n    apply: {Hrec Hv' Hhc' Hhc'p}(leqz_trans (Hrec _ Hv' Hhc' Hhc'p)).\n    rewrite leqz_opp2 !Edb2 // Dvi Dvj Hiv Hjv /= !addzA leqz_add2r addzC {b}.\n    rewrite -!addzA leqz_add2l addzC addzCA !addzA -addzA {db2 Edb2}.\n    have Hx'p := fit_hubcap_rot Hxn Exp Hj; rewrite (arity_cface Hxx') in Hxn.\n    rewrite -(iter_hub_subn i Hj Hxn); rewrite -(arity_iter_face j x') in Hxn.\n    apply leqz_add2; exact (check_2dbound2P Hxn Hx'p (hub_subn_hub Hi Hj) Hijp).\n  move/andP=> [Hijp Hhc'p]; rewrite !ltnS in Hiv Hjv.\n  case: (leqP nhub i) => Hi; first by rewrite sub_default ?Ev in Dvi.\n  case: (leqP nhub j) => Hj; first by rewrite sub_default ?Ev in Dvj.\n  apply: {Hrec Hv' Hhc' Hhc'p}(leqz_trans (Hrec _ Hv' Hhc' Hhc'p)).\n  rewrite leqz_opp2 !Edb2 // Dvi Dvj !andbF /= !addzA leqz_add2r {b}.\n  rewrite addzC {db2 Edb2}leqz_add2l addzC.\n  have Hx'p := fit_hubcap_rot Hxn Exp Hj; rewrite (arity_cface Hxx') in Hxn.\n  rewrite -(iter_hub_subn i Hj Hxn); rewrite -(arity_iter_face j x') in Hxn.\n  exact (check_2dbound2P Hxn Hx'p (hub_subn_hub Hi Hj) Hijp).\nset db := (b0 + sumz (dbound2 rt0 rs0) (cface x'))%Z.\nsuffice: ~ posz (decz (db + db)).\n  move=> H; apply/idP => Hx; case: H; move: (dscore_cap2 rf Hg Hxn Hx).\n  rewrite -/rs0 -/rt0 -/b0 (eq_sumz_r (same_cface Hxx')) -/db.\n  by rewrite decz_def -addzA; case: db => [[|n]|n].\napply: negP; apply: etrans Hdb2 {p Ep Exp vb Hvb Edb2 Hhcp}; congr negb.\ncongr posz; rewrite !decz_def -!(addzC (-(1))) -!addzA; congr addz.\nrewrite /db -!addzA; congr addz; rewrite addzCA -sumz_add; congr addz.\napply: eq_sumz_l => y Hy; rewrite {}/db2.\nmove: (dbound2 rt0 rs0 y) => b; set i := findex face x' y.\nhave Hi: i < nhub by rewrite -Hxn (arity_cface Hxx'); apply: findex_max.\ncase Hi0: (sub 0 v i =d 0).\n  by case/idP: Hv0; rewrite -(eqP Hi0) mem_sub ?Ev.\ncase Dvi: (sub 0 v i) (Hi0) => [|[|[|k]]] //=; first by rewrite addz0.\ncase/eqP: {b Ev Hv0}Hi0; rewrite /v.\nmove: v Dvi (decz (b0 + b0)) Hhc => v Dvi.\nelim: hc => [|j b' hc' Hrec|j1 j2 b' hc' Hrec] b /=; try by case i.\n  rewrite sub_incr_sub; case: (j =P i) => [->|_]; first by rewrite Dvi.\n  by case: (sub 0 v j) => [|[|k']] //; apply: Hrec.\nrewrite !sub_incr_sub; case: (j1 =P i) => [->|_]; first by rewrite Dvi.\ncase: (sub 0 v j1) => [|[|[|k1]]] //;\n (case: (j2 =P i) => [->|_]; first by rewrite Dvi);\n case: (sub 0 v j2) => [|[|[|k2]]] //; exact: Hrec.\nQed.\n\nEnd Hubcap.\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/hubcap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.3738758367247084, "lm_q1q2_score": 0.2650851218977297}}
{"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\nUnset Standard Proposition Elimination Names.\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  Zsgn\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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 (Zsgn\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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zle_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zle_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zle_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zle_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zle_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zle_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zle_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zle_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 (Zsgn (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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zlt_irrefl with 0%Z.\n      apply Zle_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 Zlt_irrefl with 0%Z.\n      apply Zle_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 Zlt_irrefl with 0%Z.\n      apply Zle_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 Zlt_irrefl with 0%Z.\n      apply Zle_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zlt_irrefl with 0%Z.\n      apply Zle_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 Zlt_irrefl with 0%Z.\n      apply Zle_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 Zlt_irrefl with 0%Z.\n      apply Zle_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 Zlt_irrefl with 0%Z.\n      apply Zle_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 <= Zsgn (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 Zlt_irrefl with 0%Z.\n      apply Zle_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 Zlt_irrefl with 0%Z.\n      apply Zle_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 Zlt_irrefl with 0%Z.\n      apply Zle_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 Zle_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 Zlt_irrefl with 0%Z.\n      apply Zle_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 Zle_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zlt_irrefl with 0%Z.\n      apply Zle_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 Zle_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zlt_irrefl with 0%Z.\n      apply Zle_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 Zle_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 Zlt_irrefl with 0%Z.\n      apply Zle_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 Zlt_irrefl with 0%Z.\n      apply Zle_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 Zlt_irrefl with 0%Z.\n      apply Zle_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 Zle_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 Zlt_irrefl with 0%Z.\n      apply Zle_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 Zle_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zlt_irrefl with 0%Z.\n      apply Zle_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 Zle_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 Zlt_irrefl with 0%Z.\n      apply Zlt_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 Zlt_irrefl with 0%Z.\n      apply Zle_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 Zle_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 Zlt_irrefl with 0%Z.\n      apply Zle_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 Zlt_irrefl with 0%Z.\n      apply Zle_lt_trans with (na + nb)%Z.\n      assumption.\n      assumption.\nDefined.", "meta": {"author": "verimath", "repo": "real", "sha": "8586b22050077cc1ad095d80ca1ac2f79f781b51", "save_path": "github-repos/coq/verimath-real", "path": "github-repos/coq/verimath-real/real-8586b22050077cc1ad095d80ca1ac2f79f781b51/src/binrat/homographicAcc_Qhomographic_sign.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.265071127088915}}
{"text": "Require Export SystemFR.TypeErasureLemmas.\nRequire Export SystemFR.ReducibilityDefinition.\nRequire Export SystemFR.AnnotatedTermLemmas.\n\nLemma open_reducible_same:\n  forall Θ Γ t T Θ' Γ' t' T',\n    [ Θ; Γ ⊨ t : T ] ->\n    Θ = Θ' ->\n    Γ = Γ' ->\n    t = t' ->\n    T = T' ->\n    [ Θ'; Γ' ⊨ t' : T' ].\nProof.\n  steps.\nQed.\n\nLtac erase_open := repeat\n  (progress rewrite erase_type_open in * by (steps; eauto with annot)) ||\n  (progress rewrite erase_term_open in * by (steps; eauto with annot)) ||\n  (progress rewrite erase_type_topen in * by (steps; eauto with annot)) ||\n  (progress rewrite erase_term_topen in * by (steps; eauto with annot)).\n\nLtac side_conditions :=\n  repeat rewrite erased_context_support in *;\n  try solve [ t_subset_erase; auto ];\n  eauto 2 with fv;\n  eauto 2 with wf;\n  eauto 2 with twf;\n  eauto 2 with erased;\n  try solve [ eapply_anywhere fv_context_support; eauto 2 ].\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/AnnotatedTactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.265071127088915}}
{"text": "Definition p := true.\nObligation Tactic := idtac.\nRequire Import Program.\nUnset Program Cases.\nTime Program Fixpoint f (n : nat) {struct n} : nat :=\n  match p with false => n | _ =>\n    match p with false => n | _ =>\n      match p with false => n | _ =>\n        match p with false => n | _ =>\n          match p with false => n | _ =>\n            match p with false => n | _ =>\n              match p with false => n | _ =>\n                match p with false => n | _ =>\n                  match p with false => n | _ =>\n                    match n with\n                    | 0 => 0\n                    | S n => S (f n)\n                    end\n                  end\n                end\n              end\n            end\n          end\n        end\n      end\n    end\n  end.\n\nRequire Import Lia.\nRequire Import Omega.\nRequire Import ssreflect.\nInductive limitedNat {n} : Type :=\n| lim i : i < n -> limitedNat.\nDefinition test i j (H: (i < j) /\\ True) : @limitedNat (S j).\nProof.\n  refine (lim (S i) _). omega.\nDefined.\n\n    ltac:(lazymatch goal with H : ?i < ?j |- _ => idtac H end)\n    end)).\n  refine (lim (S i) (match H with conj IJ _ =>\n    ltac:(lazymatch goal with H : ?i < ?j |- _ => idtac H end)\n    end)).\n  lia.\n  (match H with conj IJ _ => ltac:(lia) end).\n :=\n  lim (S i) _.\n  (match H with conj IJ _ => ltac:(lia) end).\n  Lemma test (n: nat) : nat. Proof.\n  Fail idtac n.\n  destruct n eqn:B.\n  Fail idtac B.\n  Fail idtac n.\nmatch goal with\n| H : _ = _ |- _ => idtac H\nend.\ndestruct n eqn:B. idtac B. exact 0. Defined.\nexact 0. Defined.\nFrom Coq Require Import String.\nFrom Coq Require Import List.\n\nImport ListNotations.\nInductive Expression : Type :=\n| EEmptyList\n| EVar (s : string)\n| EMap (l : list (Expression * Expression)).\n\nFixpoint variables (e : Expression) : list string :=\n  match e with\n  | EEmptyList => []\n  | EVar x => [x]\n  | EMap l => fold_right (fun '(a, b) r => app (app (variables a) (variables b)) r) [] l\n  end.\nLemma equiv l :\n  fold_right (fun '(a, b) r => app (app (variables a) (variables b)) r) [] l =\n  (fix fp l :=\n    match l with\n    | [] => []\n    | (a,b)::xs => app (app (variables a) (variables b)) (fp xs)\n    end) l.\nProof. now induction l; [|destruct a; rewrite <-IHl]. Qed.\n\nRequire Import iris.algebra.base.\nLemma foo : ∀ {A : Set} {P : A → Prop} (a : A), (∀ x, ¬ (P x)) → ¬ (∀ x, P x).\nintros * a H Hn.\neapply (H a), Hn.\nintros.\nfirstorder.\nintuition.\ntauto.\n\n\n\nGoal let f := plus in f (0 + 0) 0 = 0.\n  cbv beta delta. cbv iota beta.\n  intro f.\n  cbv delta. (* let f := (fix add ...) in f ((fix add ...) 0 0) 0 = 0 *)\n  intro f.\n  cbv delta;clear f.\n\nRequire Import Lia.\nFrom Coq Require Export ZArith NPeano.\nLemma foo2 : forall (z:Z), (z >=0)%Z -> { n : nat | Z.of_nat n = z }.\nProof. intros z. exists (Z.to_nat z). apply Z2Nat.id. lia. Qed.\n\nFrom Coq.ssr Require Import ssreflect.\nFrom Coq Require Export EqdepFacts PArith NArith ZArith NPeano.\n\nLemma foo : forall (z:Z), (z >=0)%Z -> exists n : nat , Z.of_nat n = z.\nProof. intros z. exists (Z.to_nat z). apply Z2Nat.id. lia. Qed.\nLemma to_nat2 : Z -> nat. intros z. Fail destruct (foo z). Abort.\n\nLemma to_nat2 (z : Z) (H : (z >= 0)%Z): nat. destruct (foo2 z H) as [n _]. exact n. Defined.\n\nAbout Z.\nFrom mathcomp.ssreflect Require Import ssrnat.\nSearch _ (forall (z:Z), (z >=0)%Z -> { n : nat | Z.to_nat z = n }).\nSearch _ (forall (z:Z), (z >=0)%Z -> exists n : nat , Z.to_nat z = n).\nSearch _ (_ >= 0 -> Z.abs _ = _).\nRequire Import Lia.\n\nInductive foo := .\n\nInductive bar := .\n\nRequire Import Lia.\nFrom Coq.ssr Require Import ssreflect.\nLemma baz : 1 = 2 -> 3 = 4.\nmove => Hi. have {Hi} -Hi: 2 = 3 by lia. lia.\nQed.\n\nLemma foo (H:True) : True -> True.\nProof.\n  move => {H} -H.\n  exact I.\nQed.\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/bugs-misc/foo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.265071127088915}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\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\nRequire Import List.\nRequire Import Coq.Program.Syntax.\nRequire Import Equality.\n\n(** A curryfied function with multiple parameters **)\nDefinition arrows_left: list Type -> Type -> Type :=\n  fold_left (fun A B => B -> A).\n\n(** A curryfied function with multiple parameters **)\nDefinition arrows_right: Type -> list Type -> Type :=\n  fold_right (fun A B => A -> B).\n\n(** A tuple is a heterogeneous list. For convenience, we use pairs. **)\nFixpoint tuple (types : list Type) : Type :=\n  match types with\n  | nil => unit\n  | t::q => prod t (tuple q)\n  end.\n\nFixpoint uncurry {args:list Type} {res:Type}:\n  arrows_left args res -> tuple args -> res :=\n  match args return forall res, arrows_left args res -> tuple args -> res with\n    | [] => fun _ f _ => f\n    | t::q => fun res f p => let (d, t) := p in\n      (@uncurry q _ f t) d\n  end res.\n\nLemma JMeq_eqrect:\n  forall (U:Type) (a b:U) (P:U -> Type) (x:P a) (e:a=b),\n    eq_rect a P x b e ~= x.\nProof.\ndestruct e.\nreflexivity.\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/cparser/validator/Tuples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.265071127088915}}
{"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\n\n(***************************** Specialised Imports *****************************)\n\nRequire Import ComhCoq.StandardResults.\nRequire Import ComhCoq.ComhBasics.\nRequire Import ComhCoq.LanguageFoundations.\nRequire Import ComhCoq.SoftwareLanguage.\nRequire Import ComhCoq.ProcEquiv.\n\n(********************** Single ProcTerm State Predicates **********************)\n\n(******** Simple ********)\n\n(*Broadcast*)\n\nDefinition bcWaitState (m : Mode) (x : Time) (p : ProcTerm) : Prop := \n    p ~p~ (bcWait m x).\n\nDefinition sleepingState (p : ProcTerm) : Prop :=\n  p ~p~ sleeping.\n\nDefinition bcReadyState (m : Mode) (l : Position) (p : ProcTerm) : Prop :=\n  p ~p~ (bcReady m l).\n\n(*Overlap*)\n\nDefinition dormantState (p : ProcTerm) : Prop :=\n  p ~p~ dormant.\n\nDefinition ovWaitState (m : Mode) (t x y: Time) (p : ProcTerm) : Prop :=\n  p ~p~ ovWait m t x y.\n\nDefinition ovReadyState (m : Mode) (t : Time) (l : Position) (p : ProcTerm) : Prop :=\n  p ~p~ ovReady m t l.\n\nDefinition switchBcState (m : Mode) (p : ProcTerm) : Prop :=\n  p ~p~ switchBc m.\n\nDefinition switchCurrState (p : ProcTerm) : Prop :=\n  p ~p~ switchCurr.\n\nDefinition switchListenState (p : ProcTerm) : Prop :=\n  p ~p~ switchListen.\n\nDefinition tfsStartState (p : ProcTerm) : Prop := \n  p ~p~ tfsStart.\n\nDefinition tfsNextState (m : Mode) (p : ProcTerm) : Prop :=\n  p ~p~ tfsNext m.\n \nDefinition tfsCurrState (p : ProcTerm) : Prop := \n  p ~p~ tfsCurr.\n\nDefinition tfsBcState (p : ProcTerm) : Prop := \n  p ~p~ tfsBc.\n\nDefinition tfsListenState (p : ProcTerm) : Prop := \n  p ~p~ tfsListen.\n\nDefinition initState (m : Mode) (p : ProcTerm) : Prop := \n  p ~p~ init m.\n\nDefinition ovAbortState (p : ProcTerm) : Prop := \n  p ~p~ ovAbort.\n\n(*Listening*)\n\n(*Note that many of the constructors for listeningState actually take a state\nthat \"evaluates\" to listeningState so to speak i.e. it is a conditional branch\nwhose condition is true and whose then branch is the listeningState.*)\nDefinition listeningState (p : ProcTerm) : Prop :=\n  p ~p~ listening.\n\nDefinition rangeBadState (m : Mode) (p : ProcTerm) : Prop :=\n  p ~p~ rangeBad m.\n\nDefinition currOKState (m' : Mode) (p : ProcTerm) : Prop :=\n  p ~p~ currOK m'.\n  \nDefinition abortOvlpState (p : ProcTerm) : Prop :=\n  p ~p~ abortOvlp.\n \nDefinition badOvlpState (p : ProcTerm) : Prop :=\n  p ~p~ badOvlp.\n\nDefinition currCompState (m : Mode) (r : Distance) (p : ProcTerm) : Prop :=\n  p ~p~ currComp m r.\n\nDefinition pausedState (p : ProcTerm) : Prop := \n  p ~p~ paused.\n\nDefinition gotMsgState (m : Mode) (l : Position) (p : ProcTerm) : Prop :=\n  p ~p~ gotMsg m l.\n\nDefinition gotRangeState (m : Mode) (r : Distance) (p : ProcTerm) : Prop :=\n  p ~p~ gotRange m r.\n\nDefinition currEqState (m m' : Mode) (p : ProcTerm) : Prop := \n  p ~p~ currEq m m'.\n\nDefinition nextEqState (m m' : Mode) (p : ProcTerm) : Prop := \n  p ~p~ nextEq m m'.\n\nDefinition currPincCheckState (m m' : Mode) (d : Distance) (p : ProcTerm) : Prop := \n  p ~p~ currPincCheck m m' d.\n\t\nDefinition nextPincCheckState (m m' : Mode) (d : Distance) (p : ProcTerm) : Prop := \n  p ~p~ nextPincCheck m m' d.\n\n(******** Compound ********)\n\n(*Broadcast*)\n\nInductive broadcastState (p : ProcTerm) : Prop :=\n  | broadBcwSt (m : Mode) (x : Time) : bcWaitState m x p -> broadcastState p\n  | broadSlpSt : sleepingState p -> broadcastState p\n  | broadBcrSt (m : Mode) (l : Position) : bcReadyState m l p -> broadcastState p.\n\n(*Overlap*)\n\n(*INCOMPLETE- Need to add constructors for ALL the overlap states.*)\nInductive overlapState (p : ProcTerm) : Prop :=\n  | ovlpDorSt : dormantState p -> overlapState p\n  | ovlpWaSt (m : Mode) (t x y : Time) : ovWaitState m t x y p -> overlapState p.\n\nInductive nextSinceState (p : ProcTerm) : Prop :=\n  | nexsOvwSt (m : Mode) (t x y : Time) : ovWaitState m t x y p -> nextSinceState p\n  | nexsOvrSt (m : Mode) (t : Time) (l : Position) : ovReadyState m t l p -> nextSinceState p\n  | nexsSbcSt (m : Mode) : switchBcState m p -> nextSinceState p\n  | nexsScSt (m : Mode) : switchCurrState p -> nextSinceState p.\n\nInductive tfsState (p : ProcTerm) : Prop :=\n  | tfsStaSt : tfsStartState p -> tfsState p\n  | tfsNexSt (m : Mode) : tfsNextState m p -> tfsState p\n  | tfsCurSt : tfsCurrState p -> tfsState p\n  | tfsBcSt : tfsBcState p -> tfsState p\n  | tfsLisSt : tfsListenState p -> tfsState p.\n\nInductive switchState (p : ProcTerm) : Prop :=\n  | switBcSt (m : Mode) : switchBcState m p -> switchState p\n  | switCurSt : switchCurrState p -> switchState p\n  | switLisSt : switchListenState p -> switchState p.\n\n(*Listening*)\n\nInductive listenerState (p : ProcTerm) : Prop :=\n  | listLisSt : listeningState p -> listenerState p\n  | listRbSt (m : Mode) : rangeBadState m p -> listenerState p\n  | listCokSt (m : Mode) : currOKState m p -> listenerState p\n  | listAovSt : abortOvlpState p -> listenerState p\n  | listBovSt : badOvlpState p -> listenerState p\n  | listCucost (m : Mode) (r : Distance) : currCompState m r p -> listenerState p.\n\n  \n\n(********************** Protocol Lift State Predicates **********************)\n\n(******** Lifting Functions ********)\n\nInductive liftBroadcast (X : ProcTerm -> Prop) : ProcTerm -> Prop :=\n  | lftbc (p p2 p3 : ProcTerm) : X p -> liftBroadcast X (p $||$ p2 $||$ p3) .\n\nInductive liftOverlap (X : ProcTerm -> Prop) : ProcTerm -> Prop :=\n  | lftOv (p1 p p3 : ProcTerm) : X p -> liftOverlap X (p1 $||$ p $||$ p3) .\n\nInductive liftListen (X : ProcTerm -> Prop) : ProcTerm -> Prop :=\n  | lftlst (p1 p2 p : ProcTerm) : X p -> liftListen X (p1 $||$ p2 $||$ p) .\n\n(******** Simple ********)\n\n(*Broadcast*)\n\nDefinition bcWaitStateProt m x := liftBroadcast (bcWaitState m x).\nDefinition sleepingStateProt := liftBroadcast sleepingState.\nDefinition bcReadyStateProt m l := liftBroadcast (bcReadyState m l).\n\n(*Overlap*)\n\nDefinition dormantStateProt := liftOverlap dormantState.\nDefinition ovWaitStateProt m' t x y := liftOverlap (ovWaitState m' t x y).\nDefinition tfsListenStateProt := liftOverlap tfsListenState.\nDefinition tfsBcStateProt := liftOverlap tfsBcState.\nDefinition tfsCurrStateProt := liftOverlap tfsCurrState.\nDefinition ovAbortStateProt := liftOverlap ovAbortState.\nDefinition switchBcStateProt m := liftOverlap (switchBcState m).\nDefinition tfsNextStateProt m := liftOverlap (tfsNextState m).\nDefinition tfsStartStateProt := liftOverlap tfsStartState.\nDefinition initStateProt m := liftOverlap (initState m).\nDefinition ovReadyStateProt m t l := liftOverlap (ovReadyState m t l).\nDefinition switchCurrStateProt := liftOverlap switchCurrState.\nDefinition switchListenStateProt := liftOverlap switchListenState.\n\n(*Listening*)\n\nDefinition listeningStateProt := liftListen listeningState.\nDefinition currCompStateProt m'' r := liftListen (currCompState m'' r).\nDefinition abortOvlpStateProt := liftListen abortOvlpState.\nDefinition badOvlpStateProt := liftListen badOvlpState.\nDefinition pausedStateProt := liftListen pausedState.\nDefinition gotMsgStateProt m l := liftListen (gotMsgState m l).\nDefinition gotRangeStateProt m r := liftListen (gotRangeState m r).\nDefinition rangeBadStateProt m := liftListen (rangeBadState m).\nDefinition currOKStateProt m := liftListen (currOKState m).\nDefinition currEqStateProt m m'' := liftListen (currEqState m m'').\nDefinition nextEqStateProt m m' := liftListen (nextEqState m m').\nDefinition currPincCheckStateProt m m'' r := liftListen (currPincCheckState m m'' r).\nDefinition nextPincCheckStateProt m m'' r := liftListen (nextPincCheckState m m'' r).\n\n(******** Compound ********)\n\n(*Broadcast*)\n\nDefinition broadcastStateProt :=  liftBroadcast broadcastState.\n\n(*Overlap*)\n\nDefinition overlapStateProt := liftOverlap overlapState.\nDefinition nextSinceStateProt := liftOverlap nextSinceState.\nDefinition tfsStateProt := liftOverlap tfsState.\nDefinition switchStateProt := liftOverlap switchState.\n\n(*Listening*)\n\nDefinition listenerStateProt := liftListen listenerState.\n\n(********************** Other **********************)\n\nInductive protocolState : ProcTerm -> Prop :=\n  | protState (p1 p2 p3 : ProcTerm) :\n    broadcastState p1 -> overlapState p2 -> listenerState p3 ->\n    protocolState (p1 $||$ p2 $||$ p3).\n\n(** Reachability from the protocol process. Any process that is reachable from the\n  protocol process via a finite number of steps as per the semantics satisfies this relation.*)\nInductive reachableProt : ProcTerm -> Prop :=\n  | reachprBase : reachableProt procProtocol\n  | reachprDisc (p p' : ProcTerm) (a : DiscAct) : reachableProt p ->\n  p -PA- a -PA> p' -> reachableProt p'\n  | reachprDel (p p' : ProcTerm) (d : Delay) : reachableProt p ->\n  p -PD- d -PD> p' -> reachableProt p'.\n\nInductive initialProc : ProcTerm -> Prop :=\n  initProcProt : initialProc procProtocol.\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/ProtAuxDefs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.265071127088915}}
{"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            Existence of Right Adjoint                \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\nRequire Export Adj_UA. \n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nSection ua_to_radj.\n\nVariables (C D : Category) (F : Functor D C).\n\nHypothesis UA_of : forall c : C, CoUA c F.\n\n(* construction de l'adj droit *)\n\nDefinition CoadjointUA_ob (c : C) := CoUA_ob (UA_of c).\n \n Section coadjoint_ua_map_def.\n\n Variable c c' : C.\n\n Definition CoadjointUA_mor (f : c --> c') :=\n   CoUA_diese (UA_of c') (CoUA_mor (UA_of c) o f).\n\n Lemma CoadjointUA_map_law : Map_law CoadjointUA_mor.\n Proof.\n unfold Map_law, CoadjointUA_mor in |- *; intros f g H.\n apply\n  (Codiese_map (UA_of c') (x:=CoUA_mor (UA_of c) o f)\n     (y:=CoUA_mor (UA_of c) o g)).\n apply Comp_l; assumption.\n Qed.\n\n Canonical Structure CoadjointUA_map :\n   Map (c --> c') (CoadjointUA_ob c --> CoadjointUA_ob c') :=\n   CoadjointUA_map_law.\n\n End coadjoint_ua_map_def.\n\nLemma CoadjointUA_id_law : Fid_law CoadjointUA_map.\nProof.\nunfold Fid_law in |- *; simpl in |- *.\nunfold CoadjointUA_mor, CoadjointUA_ob in |- *.\nintro c.\napply CoUA_unic1.\n(* *) apply Trans with (Id (F (CoUA_ob (UA_of c))) o CoUA_mor (UA_of c)).\napply Comp_r; apply FId.\n(* *) apply Trans with (CoUA_mor (UA_of c)).\napply Idl.\napply Idr.\nQed.\n\nLemma CoadjointUA_comp_law : Fcomp_law CoadjointUA_map.\nProof.\nunfold Fcomp_law in |- *; simpl in |- *.\nunfold CoadjointUA_mor, CoadjointUA_ob in |- *; intros c1 c2 c3 f g.\napply CoUA_unic1.\n(* *) apply\n       Trans\n        with\n          ((FMor F (CoUA_diese (UA_of c2) (CoUA_mor (UA_of c1) o f))\n            o FMor F (CoUA_diese (UA_of c3) (CoUA_mor (UA_of c2) o g)))\n           o CoUA_mor (UA_of c3)).\napply Comp_r; apply FComp.\n(* *) apply\n       Trans\n        with\n          (FMor F (CoUA_diese (UA_of c2) (CoUA_mor (UA_of c1) o f))\n           o FMor F (CoUA_diese (UA_of c3) (CoUA_mor (UA_of c2) o g))\n             o CoUA_mor (UA_of c3)).\napply Ass1.\n(* *) apply\n       Trans\n        with\n          (FMor F (CoUA_diese (UA_of c2) (CoUA_mor (UA_of c1) o f))\n           o CoUA_mor (UA_of c2) o g).\napply Comp_l; apply CoUA_diag.\n\n(* *) apply\n       Trans\n        with\n          ((FMor F (CoUA_diese (UA_of c2) (CoUA_mor (UA_of c1) o f))\n            o CoUA_mor (UA_of c2)) o g).\napply Ass.\n\n(* *) apply Trans with ((CoUA_mor (UA_of c1) o f) o g).\napply Comp_r; apply CoUA_diag.\napply Ass1.\nQed.\n\nCanonical Structure CoadjointUA :=\n  Build_Functor CoadjointUA_comp_law CoadjointUA_id_law.\n\n(* *)\n\n(* definition de PhiUA':C(F-,-) -> D(-,G-) *)\n\n Section psi_ua_tau_def.\n\n Variable dxc : POb (Dual D) C.\n\n Definition PsiUA_arrow (f : F (Ob_l dxc) --> Ob_r dxc) :=\n   CoUA_diese (UA_of (Ob_r dxc)) f.\n\n Lemma PsiUA_arrow_map_law : Map_law PsiUA_arrow.\n Proof.\n unfold Map_law, PsiUA_arrow in |- *.\n intros f g H.\n apply (Codiese_map (UA_of (Ob_r dxc)) (x:=f) (y:=g)).\n assumption.\n Qed.\n\n Canonical Structure PsiUA_tau := Build_Map PsiUA_arrow_map_law.\n\n End psi_ua_tau_def.\n\nLemma PsiUA_tau_nt_law :\n NT_law (F:=FunSET2_r F) (G:=FunSET2_l CoadjointUA) PsiUA_tau.\nProof.\nunfold NT_law, PsiUA_tau, PsiUA_arrow in |- *; simpl in |- *.\nunfold Ext in |- *; simpl in |- *.\nintros d1xc1 d2xc2 fxg h.\nunfold FunSET2_r_mor1, FunSET2_l_mor1, FunSET2_l_ob in |- *; simpl in |- *;\n unfold CoadjointUA_ob in |- *.\napply CoUA_unic1.\n(* *) apply\n       Trans\n        with\n          ((FMor F (HOM_l fxg o CoUA_diese (UA_of (Ob_r d1xc1)) h)\n            o FMor F (FMor CoadjointUA (Hom_r fxg)))\n           o CoUA_mor (UA_of (Ob_r d2xc2))).\napply Comp_r; apply FComp.\n(* *) apply\n       Trans\n        with\n          (((FMor F (HOM_l fxg) o FMor F (CoUA_diese (UA_of (Ob_r d1xc1)) h))\n            o FMor F (FMor CoadjointUA (Hom_r fxg)))\n           o CoUA_mor (UA_of (Ob_r d2xc2))).\napply Comp_r; apply Comp_r; apply FComp.\n(* *) apply\n       Trans\n        with\n          ((FMor F (HOM_l fxg) o FMor F (CoUA_diese (UA_of (Ob_r d1xc1)) h))\n           o FMor F (FMor CoadjointUA (Hom_r fxg))\n             o CoUA_mor (UA_of (Ob_r d2xc2))).\napply Ass1.\n(* *) apply\n       Trans\n        with\n          (FMor F (HOM_l fxg)\n           o FMor F (CoUA_diese (UA_of (Ob_r d1xc1)) h)\n             o FMor F (FMor CoadjointUA (Hom_r fxg))\n               o CoUA_mor (UA_of (Ob_r d2xc2))).\napply Ass1.\n(* *) apply Trans with (FMor F (HOM_l fxg) o h o Hom_r fxg).\napply Comp_l.\n(* *) apply\n       Trans\n        with\n          (FMor F (CoUA_diese (UA_of (Ob_r d1xc1)) h)\n           o CoUA_mor (UA_of (Ob_r d1xc1)) o Hom_r fxg).\napply Comp_l.\nunfold FMor at 2 in |- *; simpl in |- *;\n unfold CoadjointUA_mor, CoadjointUA_ob in |- *.\napply CoUA_diag.\n(* *) apply\n       Trans\n        with\n          ((FMor F (CoUA_diese (UA_of (Ob_r d1xc1)) h)\n            o CoUA_mor (UA_of (Ob_r d1xc1))) o Hom_r fxg).\napply Ass.\napply Comp_r; apply CoUA_diag.\napply Ass.\nQed.\n\nCanonical Structure PsiUA := Build_NT PsiUA_tau_nt_law.\n               \n(* PsiUA_1 *)\n\n Section psi_ua_1_tau_def.\n\n Variable dxc : POb (Dual D) C.\n\n Definition PsiUA_1_arrow (f : OB_l dxc --> CoadjointUA (Ob_r dxc)) :=\n   FMor F f o CoUA_mor (UA_of (Ob_r dxc)).\n\n Lemma PsiUA_1_arrow_map_law : Map_law PsiUA_1_arrow.                     \n Proof.\n unfold Map_law, PsiUA_1_arrow in |- *.\n intros f g H.\n apply Comp_r; apply FPres; assumption. \n Qed.\n\n Canonical Structure PsiUA_1_tau := Build_Map PsiUA_1_arrow_map_law.\n \n End psi_ua_1_tau_def.\n      \nLemma PsiUA_1_tau_nt_law :\n NT_law (F:=FunSET2_l CoadjointUA) (G:=FunSET2_r F) PsiUA_1_tau.\nProof.\nunfold NT_law, PsiUA_1_tau, PsiUA_1_arrow in |- *; simpl in |- *.\nunfold Ext in |- *; simpl in |- *.\nintros d1xc1 d2xc2 fxg h.\nunfold FunSET2_r_mor1, FunSET2_l_mor1 in |- *.\nunfold FOb at 1 in |- *; simpl in |- *; unfold FunSET2_r_ob in |- *.\n(* *) apply\n       Trans\n        with\n          (((FMor F (HOM_l fxg) o FMor F h)\n            o FMor F (FMor CoadjointUA (Hom_r fxg)))\n           o CoUA_mor (UA_of (Ob_r d2xc2))).\napply Comp_r.\n(* *) apply\n       Trans\n        with (FMor F (HOM_l fxg o h) o FMor F (FMor CoadjointUA (Hom_r fxg))).\napply FComp.\napply Comp_r; apply FComp.\n(* *) apply\n       Trans\n        with\n          ((FMor F (HOM_l fxg) o FMor F h)\n           o FMor F (FMor CoadjointUA (Hom_r fxg))\n             o CoUA_mor (UA_of (Ob_r d2xc2))).\napply Ass1.\n(* *) apply\n       Trans\n        with\n          (FMor F (HOM_l fxg)\n           o FMor F h\n             o FMor F (FMor CoadjointUA (Hom_r fxg))\n               o CoUA_mor (UA_of (Ob_r d2xc2))).\napply Ass1.\n(* *) apply\n       Trans\n        with\n          (FMor F (HOM_l fxg)\n           o (FMor F h o CoUA_mor (UA_of (Ob_r d1xc1))) o Hom_r fxg).\napply Comp_l.\n(* *) apply Trans with (FMor F h o CoUA_mor (UA_of (Ob_r d1xc1)) o Hom_r fxg).\napply Comp_l.\nunfold FMor at 2 in |- *; simpl in |- *;\n unfold CoadjointUA_mor, CoadjointUA_ob in |- *.\napply CoUA_diag.\napply Ass.\napply Ass.\nQed.\n\nCanonical Structure PsiUA_1 := Build_NT PsiUA_1_tau_nt_law.\n\n(* PsiUA et PsiUA_1 sont iso *)\n\n Section psi_ua_iso.\n\n Variable dxc : POb (Dual D) C.\n\n Lemma PsiUA_1_o_PsiUA : AreIsos (PsiUA dxc) (PsiUA_1 dxc).\n Proof.\n unfold AreIsos, RIso_law in |- *; simpl in |- *; split.\n unfold Ext in |- *; simpl in |- *.\n unfold PsiUA_arrow, Id_fun, PsiUA_1_arrow in |- *.\n intro f.\n unfold FunSET2_l_ob in |- *; simpl in |- *; unfold CoadjointUA_ob in |- *.\n apply CoUA_unic1; apply Refl.\n (**)\n unfold Ext in |- *; simpl in |- *.\n unfold PsiUA_arrow, Id_fun, PsiUA_1_arrow in |- *.\n intro f.\n unfold FunSET2_r_ob in |- *; apply (CoUA_diag (UA_of (Ob_r dxc))). \n Qed.\n\n End psi_ua_iso.\n\nDefinition CoAdjUA := Build_Adj (NT_Iso PsiUA_1_o_PsiUA).\n\nCanonical Structure RightAdjUA := Build_RightAdj CoAdjUA.\n\nEnd ua_to_radj.\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/Th_CoAdjoint.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.265071127088915}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom Coq Require Import Arith.\n\n(* Defining variables as nats is basically a convenience because the String_as_OT item\n   from the OrderedTypeEx module is broken, so using strings is out *)\nDefinition var := nat.\n\nInductive type : Type :=\n| Unit\n| Arrow (a : type) (b : type)\n| Ref (a : type)\n.\n\nInductive const : Type :=\n| unit\n| cell\n| exch\n| thread\n| handle\n.\n\nInductive expr : Type :=\n| evar (x : var)\n| econst (c : const)\n| lam (x : var) (T : type) (e : expr)\n| app (e1 : expr) (e2 : expr)\n.\n\nInductive val : Type :=\n| value_var (x : var)\n| value_c (c : const)\n| value_lam (x : var) (T : type) (e : expr)\n| value_exch (v : val).\n\nInductive config : Type :=\n| conc (c1 : config) (c2 : config)\n| newplace (x : var) (c : config)\n| cellmake (x : var) (v : expr)\n| threadval (x : var) (e : expr)\n| handledfut (y : var) (x : var)\n| usedhandle (y : var)\n.\n\n(* Notation and Coercions *)\n\nNotation \"t1 '>>' t2\" := (Arrow t1 t2) (at level 90, right associativity).\nNotation \"f @ g\" := (app f g) (at level 71, left associativity).\n\nNotation \"c1 $$ c2\" := (conc c1 c2) (at level 93, left associativity).\nNotation \"x '<-' e\" := (threadval x e) (at level 91).\nNotation \"h ~ x\" := (handledfut h x) (at level 91).\nNotation \"h ~ 'used'\" := (usedhandle h) (at level 91).\nNotation \"x 'c=' v\" := (cellmake x v) (at level 91).\nNotation \"x ** cfg\" := (newplace x cfg) (at level 92, right associativity).\n\n(* Coercions between the various types *)\n\nDefinition coerce_const_to_val (c : const) : val :=\n  value_c c.\nCoercion coerce_const_to_val : const >-> val.\n\nDefinition coerce_var_to_val (x : var) : val :=\n  value_var x.\nCoercion coerce_var_to_val : var >-> val.\n\nFixpoint coerce_val_to_expr (v : val) : expr :=\n  match v with\n  | value_var x => (evar x)\n  | value_lam x T e => lam x T e\n  | value_c c => (econst c)\n  | value_exch v => (app (econst exch) (coerce_val_to_expr v))\n  end.\nCoercion coerce_val_to_expr : val >-> expr.\n", "meta": {"author": "anlsh", "repo": "lambda-futures", "sha": "447a19a5e817584f61d5266ddc5351ef2df8ebc2", "save_path": "github-repos/coq/anlsh-lambda-futures", "path": "github-repos/coq/anlsh-lambda-futures/lambda-futures-447a19a5e817584f61d5266ddc5351ef2df8ebc2/lang_spec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.265071119866397}}
{"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(** * Weights of encodings\n\n- Key definitions: [weight]\n- Initial author: Laurent.Thery@inria.fr (2003)\n\n*)\n\nFrom Coq Require Import Sorting.Permutation.\nFrom Huffman Require Export Code Frequency ISort UniqueKey.\n\nSet Default Proof Using \"Type\".\n\nSection Weight.\nVariable A : Type.\nVariable A_eq_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.\nintros B l; elim l; simpl in |- *; auto.\nintros a l0 H c f.\nrewrite <- (H (f a)).\nrewrite <- (H (c + f a)).\nrewrite Nat.add_assoc; 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.\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 <- Nat.add_assoc; rewrite (Nat.add_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 A_eq_dec ((a, l1) :: l) (id_list a n)) = n * length l1.\nProof.\nintros a l1 l n; elim n; simpl in |- *; auto.\nintros n0 H; case (A_eq_dec a a); auto.\nintros e; rewrite app_length; 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 A_eq_dec c m) =\n fold_left\n   (fun a b => a + number_of_occurrences A_eq_dec (fst b) m * length (snd b))\n   c 0.\nProof.\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 A_eq_dec m a);\n intros m1 (Hm1, Hm2).\nrewrite\n Permutation_length\n                    with\n                    (1 := \n                      encode_permutation_val _ A_eq_dec _ _ ((a, l1) :: l) Hm1).\nrewrite encode_app; auto.\nrewrite app_length; 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 A_eq_dec (fst b) m * length (snd b))\n                (c := number_of_occurrences A_eq_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 A_eq_dec a2 m1 * length l2)\n                (f := \n                  fun b : A * list bool =>\n                  number_of_occurrences A_eq_dec (fst b) m1 * length (snd b)).\nrewrite <-\n fold_plus_split\n                 with\n                 (c := number_of_occurrences A_eq_dec a2 m * length l2)\n                (f := \n                  fun b : A * list bool =>\n                  number_of_occurrences A_eq_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 _ A_eq_dec _ _ a2\n            (Permutation_sym Hm1)).\nrewrite number_of_occurrences_app.\nreplace\n (number_of_occurrences A_eq_dec a2\n    (id_list a (number_of_occurrences A_eq_dec a m))) with 0; \n auto.\ncut (a2 <> a).\nelim (number_of_occurrences A_eq_dec a m); simpl in |- *; auto.\nintros n H0 H1; case (A_eq_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 A_eq_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.\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 A_eq_dec (fst x) c))\n    (frequency_list A_eq_dec m).\n\nTheorem NoDup_unique_key :\n forall (A B : Type) (l : list (A * B)),\n NoDup (map (fst (B:=_)) l) -> unique_key l.\nProof.\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 NoDup_cons_iff 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.\nintros m c; apply NoDup_unique_key.\nunfold restrict_code in |- *.\nreplace\n (map (fst (B:=_))\n    (map (fun x : A * nat => (fst x, find_code A_eq_dec (fst x) c))\n       (frequency_list A_eq_dec m))) with\n (map (fst (B:=_)) (frequency_list A_eq_dec m)).\napply unique_key_NoDup; auto.\nelim (frequency_list A_eq_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 A_eq_dec a c = find_code A_eq_dec a (restrict_code m c).\nProof.\nintros m a c H.\napply sym_equal; apply find_code_correct2; auto.\napply restrict_code_unique_key.\ngeneralize (in_frequency_map _ A_eq_dec m a H).\nunfold restrict_code in |- *; elim (frequency_list A_eq_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 A_eq_dec c m1 = encode A_eq_dec (restrict_code m c) m1.\nProof.\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 A_eq_dec c m = encode A_eq_dec (restrict_code m c) m.\nProof.\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": "coq-community", "repo": "huffman", "sha": "0857dc9ac31c5bfb71b398c9df62a39eda1fd675", "save_path": "github-repos/coq/coq-community-huffman", "path": "github-repos/coq/coq-community-huffman/huffman-0857dc9ac31c5bfb71b398c9df62a39eda1fd675/theories/Weight.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.26492539988609726}}
{"text": "(** * Definition of minimal parse trees *)\nRequire Import Coq.Strings.String Coq.Lists.List Coq.Setoids.Setoid.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.Reachable.All.Reachable.\nRequire Import Fiat.Parsers.BaseTypes.\n\nLocal Coercion is_true : bool >-> Sortclass.\n\nSet Implicit Arguments.\nLocal Open Scope string_like_scope.\n\nSection cfg.\n  Context {Char} {HSLM : StringLikeMin Char} {G : grammar Char}.\n  Context {predata : @parser_computational_predataT Char}\n          {rdata' : @parser_removal_dataT' _ G predata}.\n\n  Context (ch : Char).\n\n  Inductive minimal_reachable_from_productions : nonterminals_listT -> productions Char -> Type :=\n  | MinReachableHead : forall valid pat pats, minimal_reachable_from_production valid pat\n                                              -> minimal_reachable_from_productions valid (pat::pats)\n  | MinReachableTail : forall valid pat pats, minimal_reachable_from_productions valid pats\n                                              -> minimal_reachable_from_productions valid (pat::pats)\n  with minimal_reachable_from_production : nonterminals_listT -> production Char -> Type :=\n  | MinReachableProductionHead : forall valid it its, minimal_reachable_from_item valid it\n                                                      -> minimal_reachable_from_production valid (it::its)\n  | MinReachableProductionTail : forall valid it its, minimal_reachable_from_production valid its\n                                                      -> minimal_reachable_from_production valid (it::its)\n  with minimal_reachable_from_item : nonterminals_listT -> item Char -> Type :=\n  | MinReachableTerminal : forall valid P, is_true (P ch) -> minimal_reachable_from_item valid (Terminal P)\n  | MinReachableNonTerminal : forall valid nt, is_valid_nonterminal valid (of_nonterminal nt)\n                                               -> minimal_reachable_from_productions (remove_nonterminal valid (of_nonterminal nt)) (Lookup G nt)\n                                               -> minimal_reachable_from_item valid (NonTerminal nt).\n\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/Reachable/All/MinimalReachable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2649253930937334}}
{"text": "From Relational Require Import OrderEnrichedCategory GenericRulesSimple.\n\nSet Warnings \"-notation-overridden,-ambiguous-paths\".\nFrom mathcomp Require Import all_ssreflect all_algebra reals distr realsum\n  ssrnat ssreflect ssrfun ssrbool ssrnum eqtype choice seq.\nSet Warnings \"notation-overridden,ambiguous-paths\".\n\nFrom Crypt Require Import Axioms ChoiceAsOrd SubDistr Couplings\n  UniformDistrLemmas FreeProbProg Theta_dens RulesStateProb UniformStateProb\n  pkg_core_definition choice_type pkg_composition pkg_rhl\n  Package Prelude.\n\nFrom Coq Require Import Utf8.\nFrom extructures Require Import ord fset fmap.\n\nSet Bullet Behavior \"Strict Subproofs\".\nSet Default Goal Selector \"!\".\nSet Primitive Projections.\n\nImport Num.Def.\nImport Num.Theory.\n\nImport PackageNotation.\n\nModule Type ROParams.\n\n  Parameter Query : finType.\n  Parameter Random : finType.\n\n  Parameter Query_pos : Positive #|Query|.\n  Parameter Random_pos : Positive #|Random|.\n\nEnd ROParams.\n\nModule RO (π : ROParams).\n\n  Import π.\n\n  #[local] Existing Instance Query_pos.\n  #[local] Existing Instance Random_pos.\n\n  Definition chQuery := 'fin #|Query|.\n  Definition chRandom := 'fin #|Random|.\n  Notation \" 'query \" := chQuery (in custom pack_type at level 2).\n  Notation \" 'random \" := chRandom (in custom pack_type at level 2).\n\n  Definition i_random := #|Random|.\n  Definition INIT : nat := 0.\n  Definition QUERY : nat := 1.\n\n  Definition queries_loc : Location := (chMap chQuery chRandom ; 2).\n  Definition RO_locs : {fset Location} := fset [:: queries_loc].\n\n  Definition RO_exports :=\n    [interface\n      #val #[ INIT ] : 'unit → 'unit ;\n      #val #[ QUERY ] : 'query → 'random\n    ].\n\n  Definition RO : package RO_locs [interface] RO_exports :=\n    [package\n      #def #[ INIT ] (_ : 'unit) : 'unit\n      {\n        #put queries_loc := emptym ;;\n        ret Datatypes.tt\n      } ;\n      #def #[ QUERY ] (q : 'query) : 'random\n      {\n        queries ← get queries_loc ;;\n        match queries q with\n        | Some r =>\n          ret r\n        | None =>\n          r ← sample uniform i_random ;;\n          #put queries_loc := setm queries q r ;;\n          ret r\n        end\n      }\n    ].\n\nEnd RO.\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/examples/RandomOracle.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2649253930937334}}
{"text": "(** * Definition of a boolean-returning CFG parser-recognizer *)\nRequire Import Coq.Lists.List.\nRequire Import Fiat.Parsers.BaseTypes Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.MinimalParse.\nRequire Import Fiat.Common.\n\nLocal Open Scope string_like_scope.\n\nSection general.\n  Context {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char} {G : grammar Char}.\n\n  Definition split_list_completeT_for {data : @parser_computational_predataT Char}\n             {len0 valid}\n             (it : item Char) (its : production Char)\n             (str : String)\n             (pf : length str <= len0)\n             (split_list : list nat)\n    := ({ n : nat\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) }%type)\n       -> ({ n : nat\n                 & (In (min (length str) n) (map (min (length str)) split_list))\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) }%type).\n\n  Definition split_list_completeT {data : @parser_computational_predataT Char}\n             (splits : production_carrierT -> String -> nat -> nat -> list nat)\n    := forall len0 valid str offset len (pf : length (substring offset len str) <= len0) nt,\n         is_valid_nonterminal initial_nonterminals_data (of_nonterminal nt)\n         -> len = 0 \\/ offset + len <= length str\n         -> ForallT\n              (Forall_tails\n                 (fun prod\n                  => match prod return Type with\n                       | nil => True\n                       | it::its\n                         => forall idx,\n                              production_carrier_valid idx\n                              -> to_production idx = it::its\n                              -> @split_list_completeT_for data len0 valid it its (substring offset len str) pf (splits idx str offset len)\n                     end))\n              (Lookup G nt).\n\n  Class boolean_parser_completeness_dataT' {data : boolean_parser_dataT} :=\n    { split_string_for_production_complete\n      : split_list_completeT split_string_for_production }.\n\n  Class boolean_parser_correctness_dataT :=\n    { data :> boolean_parser_dataT;\n      rdata' :> @parser_removal_dataT' _ G _;\n      cdata' :> boolean_parser_completeness_dataT' }.\nEnd general.\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/CorrectnessBaseTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2649253930937334}}
{"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 MIPS-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 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 uniproc := acyclic (po_loc ⊔ com).\nDefinition atomic := is_empty (rmw ⊓ fre ⋅ coe).\nDefinition sync : relation events := (*failed: try fencerel SYNC with 0*) 0.\nDefinition ppo := po ⊓ !([W] ⋅ top ⋅ [R]) ⊔ sync.\nDefinition ghb := ppo ⊔ (rfe ⊔ (fr ⊔ co)).\nDefinition tso := acyclic ghb.\nDefinition witness_conditions := generate_cos cobase co.\nDefinition model_conditions := uniproc /\\ (atomic /\\ 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 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 uniproc atomic sync ppo 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 MIPS-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/mips_tso.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6688802735722129, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.26492218341062573}}
{"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 5\n*)\n\n(** 1 Mutual Coinduction *)\n\nSection Arg5_1.\n\nDefinition monotone5 T0 T1 T2 T3 T4 (gf: rel5 T0 T1 T2 T3 T4 -> rel5 T0 T1 T2 T3 T4) :=\n  forall x0 x1 x2 x3 x4 r r' (IN: gf r x0 x1 x2 x3 x4) (LE: r <5= r'), gf r' x0 x1 x2 x3 x4.\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 gf : rel5 T0 T1 T2 T3 T4 -> rel5 T0 T1 T2 T3 T4.\nImplicit Arguments gf [].\n\nTheorem paco5_acc: forall\n  l r (OBG: forall rr (INC: r <5= rr) (CIH: l <_paco_5= rr), l <_paco_5= paco5 gf rr),\n  l <5= paco5 gf r.\nProof.\n  intros; assert (SIM: paco5 gf (r \\5/ l) x0 x1 x2 x3 x4) by eauto.\n  clear PR; repeat (try left; do 6 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco5_mon: monotone5 (paco5 gf).\nProof. paco_cofix_auto; repeat (left; do 6 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco5_mult_strong: forall r,\n  paco5 gf (upaco5 gf r) <5= paco5 gf r.\nProof. paco_cofix_auto; repeat (left; do 6 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco5_mult: forall r,\n  paco5 gf (paco5 gf r) <5= paco5 gf r.\nProof. intros; eapply paco5_mult_strong, paco5_mon; eauto. Qed.\n\nTheorem paco5_fold: forall r,\n  gf (upaco5 gf r) <5= paco5 gf r.\nProof. intros; econstructor; [ |eauto]; eauto. Qed.\n\nTheorem paco5_unfold: forall (MON: monotone5 gf) r,\n  paco5 gf r <5= gf (upaco5 gf r).\nProof. unfold monotone5; intros; destruct PR; eauto. Qed.\n\nEnd Arg5_1.\n\nHint Unfold monotone5.\nHint Resolve paco5_fold.\n\nImplicit Arguments paco5_acc            [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_mon            [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_mult_strong    [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_mult           [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_fold           [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_unfold         [ T0 T1 T2 T3 T4 ].\n\nInstance paco5_inst  T0 T1 T2 T3 T4 (gf : rel5 T0 T1 T2 T3 T4->_) r x0 x1 x2 x3 x4 : paco_class (paco5 gf r x0 x1 x2 x3 x4) :=\n{ pacoacc    := paco5_acc gf;\n  pacomult   := paco5_mult gf;\n  pacofold   := paco5_fold gf;\n  pacounfold := paco5_unfold gf }.\n\n(** 2 Mutual Coinduction *)\n\nSection Arg5_2.\n\nDefinition monotone5_2 T0 T1 T2 T3 T4 (gf: rel5 T0 T1 T2 T3 T4 -> rel5 T0 T1 T2 T3 T4 -> rel5 T0 T1 T2 T3 T4) :=\n  forall x0 x1 x2 x3 x4 r_0 r_1 r'_0 r'_1 (IN: gf r_0 r_1 x0 x1 x2 x3 x4) (LE_0: r_0 <5= r'_0)(LE_1: r_1 <5= r'_1), gf r'_0 r'_1 x0 x1 x2 x3 x4.\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 gf_0 gf_1 : rel5 T0 T1 T2 T3 T4 -> rel5 T0 T1 T2 T3 T4 -> rel5 T0 T1 T2 T3 T4.\nImplicit Arguments gf_0 [].\nImplicit Arguments gf_1 [].\n\nTheorem paco5_2_0_acc: forall\n  l r_0 r_1 (OBG: forall rr (INC: r_0 <5= rr) (CIH: l <_paco_5= rr), l <_paco_5= paco5_2_0 gf_0 gf_1 rr r_1),\n  l <5= paco5_2_0 gf_0 gf_1 r_0 r_1.\nProof.\n  intros; assert (SIM: paco5_2_0 gf_0 gf_1 (r_0 \\5/ l) r_1 x0 x1 x2 x3 x4) by eauto.\n  clear PR; repeat (try left; do 6 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco5_2_1_acc: forall\n  l r_0 r_1 (OBG: forall rr (INC: r_1 <5= rr) (CIH: l <_paco_5= rr), l <_paco_5= paco5_2_1 gf_0 gf_1 r_0 rr),\n  l <5= paco5_2_1 gf_0 gf_1 r_0 r_1.\nProof.\n  intros; assert (SIM: paco5_2_1 gf_0 gf_1 r_0 (r_1 \\5/ l) x0 x1 x2 x3 x4) by eauto.\n  clear PR; repeat (try left; do 6 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco5_2_0_mon: monotone5_2 (paco5_2_0 gf_0 gf_1).\nProof. paco_cofix_auto; repeat (left; do 6 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco5_2_1_mon: monotone5_2 (paco5_2_1 gf_0 gf_1).\nProof. paco_cofix_auto; repeat (left; do 6 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco5_2_0_mult_strong: forall r_0 r_1,\n  paco5_2_0 gf_0 gf_1 (upaco5_2_0 gf_0 gf_1 r_0 r_1) (upaco5_2_1 gf_0 gf_1 r_0 r_1) <5= paco5_2_0 gf_0 gf_1 r_0 r_1.\nProof. paco_cofix_auto; repeat (left; do 6 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco5_2_1_mult_strong: forall r_0 r_1,\n  paco5_2_1 gf_0 gf_1 (upaco5_2_0 gf_0 gf_1 r_0 r_1) (upaco5_2_1 gf_0 gf_1 r_0 r_1) <5= paco5_2_1 gf_0 gf_1 r_0 r_1.\nProof. paco_cofix_auto; repeat (left; do 6 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco5_2_0_mult: forall r_0 r_1,\n  paco5_2_0 gf_0 gf_1 (paco5_2_0 gf_0 gf_1 r_0 r_1) (paco5_2_1 gf_0 gf_1 r_0 r_1) <5= paco5_2_0 gf_0 gf_1 r_0 r_1.\nProof. intros; eapply paco5_2_0_mult_strong, paco5_2_0_mon; eauto. Qed.\n\nCorollary paco5_2_1_mult: forall r_0 r_1,\n  paco5_2_1 gf_0 gf_1 (paco5_2_0 gf_0 gf_1 r_0 r_1) (paco5_2_1 gf_0 gf_1 r_0 r_1) <5= paco5_2_1 gf_0 gf_1 r_0 r_1.\nProof. intros; eapply paco5_2_1_mult_strong, paco5_2_1_mon; eauto. Qed.\n\nTheorem paco5_2_0_fold: forall r_0 r_1,\n  gf_0 (upaco5_2_0 gf_0 gf_1 r_0 r_1) (upaco5_2_1 gf_0 gf_1 r_0 r_1) <5= paco5_2_0 gf_0 gf_1 r_0 r_1.\nProof. intros; econstructor; [ | |eauto]; eauto. Qed.\n\nTheorem paco5_2_1_fold: forall r_0 r_1,\n  gf_1 (upaco5_2_0 gf_0 gf_1 r_0 r_1) (upaco5_2_1 gf_0 gf_1 r_0 r_1) <5= paco5_2_1 gf_0 gf_1 r_0 r_1.\nProof. intros; econstructor; [ | |eauto]; eauto. Qed.\n\nTheorem paco5_2_0_unfold: forall (MON: monotone5_2 gf_0) (MON: monotone5_2 gf_1) r_0 r_1,\n  paco5_2_0 gf_0 gf_1 r_0 r_1 <5= gf_0 (upaco5_2_0 gf_0 gf_1 r_0 r_1) (upaco5_2_1 gf_0 gf_1 r_0 r_1).\nProof. unfold monotone5_2; intros; destruct PR; eauto. Qed.\n\nTheorem paco5_2_1_unfold: forall (MON: monotone5_2 gf_0) (MON: monotone5_2 gf_1) r_0 r_1,\n  paco5_2_1 gf_0 gf_1 r_0 r_1 <5= gf_1 (upaco5_2_0 gf_0 gf_1 r_0 r_1) (upaco5_2_1 gf_0 gf_1 r_0 r_1).\nProof. unfold monotone5_2; intros; destruct PR; eauto. Qed.\n\nEnd Arg5_2.\n\nHint Unfold monotone5_2.\nHint Resolve paco5_2_0_fold.\nHint Resolve paco5_2_1_fold.\n\nImplicit Arguments paco5_2_0_acc            [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_2_1_acc            [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_2_0_mon            [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_2_1_mon            [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_2_0_mult_strong    [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_2_1_mult_strong    [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_2_0_mult           [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_2_1_mult           [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_2_0_fold           [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_2_1_fold           [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_2_0_unfold         [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_2_1_unfold         [ T0 T1 T2 T3 T4 ].\n\nInstance paco5_2_0_inst  T0 T1 T2 T3 T4 (gf_0 gf_1 : rel5 T0 T1 T2 T3 T4->_) r_0 r_1 x0 x1 x2 x3 x4 : paco_class (paco5_2_0 gf_0 gf_1 r_0 r_1 x0 x1 x2 x3 x4) :=\n{ pacoacc    := paco5_2_0_acc gf_0 gf_1;\n  pacomult   := paco5_2_0_mult gf_0 gf_1;\n  pacofold   := paco5_2_0_fold gf_0 gf_1;\n  pacounfold := paco5_2_0_unfold gf_0 gf_1 }.\n\nInstance paco5_2_1_inst  T0 T1 T2 T3 T4 (gf_0 gf_1 : rel5 T0 T1 T2 T3 T4->_) r_0 r_1 x0 x1 x2 x3 x4 : paco_class (paco5_2_1 gf_0 gf_1 r_0 r_1 x0 x1 x2 x3 x4) :=\n{ pacoacc    := paco5_2_1_acc gf_0 gf_1;\n  pacomult   := paco5_2_1_mult gf_0 gf_1;\n  pacofold   := paco5_2_1_fold gf_0 gf_1;\n  pacounfold := paco5_2_1_unfold gf_0 gf_1 }.\n\n(** 3 Mutual Coinduction *)\n\nSection Arg5_3.\n\nDefinition monotone5_3 T0 T1 T2 T3 T4 (gf: rel5 T0 T1 T2 T3 T4 -> rel5 T0 T1 T2 T3 T4 -> rel5 T0 T1 T2 T3 T4 -> rel5 T0 T1 T2 T3 T4) :=\n  forall x0 x1 x2 x3 x4 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) (LE_0: r_0 <5= r'_0)(LE_1: r_1 <5= r'_1)(LE_2: r_2 <5= r'_2), gf r'_0 r'_1 r'_2 x0 x1 x2 x3 x4.\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 gf_0 gf_1 gf_2 : rel5 T0 T1 T2 T3 T4 -> rel5 T0 T1 T2 T3 T4 -> rel5 T0 T1 T2 T3 T4 -> rel5 T0 T1 T2 T3 T4.\nImplicit Arguments gf_0 [].\nImplicit Arguments gf_1 [].\nImplicit Arguments gf_2 [].\n\nTheorem paco5_3_0_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_0 <5= rr) (CIH: l <_paco_5= rr), l <_paco_5= paco5_3_0 gf_0 gf_1 gf_2 rr r_1 r_2),\n  l <5= paco5_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco5_3_0 gf_0 gf_1 gf_2 (r_0 \\5/ l) r_1 r_2 x0 x1 x2 x3 x4) by eauto.\n  clear PR; repeat (try left; do 6 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco5_3_1_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_1 <5= rr) (CIH: l <_paco_5= rr), l <_paco_5= paco5_3_1 gf_0 gf_1 gf_2 r_0 rr r_2),\n  l <5= paco5_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco5_3_1 gf_0 gf_1 gf_2 r_0 (r_1 \\5/ l) r_2 x0 x1 x2 x3 x4) by eauto.\n  clear PR; repeat (try left; do 6 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco5_3_2_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_2 <5= rr) (CIH: l <_paco_5= rr), l <_paco_5= paco5_3_2 gf_0 gf_1 gf_2 r_0 r_1 rr),\n  l <5= paco5_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco5_3_2 gf_0 gf_1 gf_2 r_0 r_1 (r_2 \\5/ l) x0 x1 x2 x3 x4) by eauto.\n  clear PR; repeat (try left; do 6 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco5_3_0_mon: monotone5_3 (paco5_3_0 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 6 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco5_3_1_mon: monotone5_3 (paco5_3_1 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 6 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco5_3_2_mon: monotone5_3 (paco5_3_2 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 6 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco5_3_0_mult_strong: forall r_0 r_1 r_2,\n  paco5_3_0 gf_0 gf_1 gf_2 (upaco5_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco5_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco5_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <5= paco5_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 6 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco5_3_1_mult_strong: forall r_0 r_1 r_2,\n  paco5_3_1 gf_0 gf_1 gf_2 (upaco5_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco5_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco5_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <5= paco5_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 6 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco5_3_2_mult_strong: forall r_0 r_1 r_2,\n  paco5_3_2 gf_0 gf_1 gf_2 (upaco5_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco5_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco5_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <5= paco5_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 6 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco5_3_0_mult: forall r_0 r_1 r_2,\n  paco5_3_0 gf_0 gf_1 gf_2 (paco5_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco5_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco5_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <5= paco5_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco5_3_0_mult_strong, paco5_3_0_mon; eauto. Qed.\n\nCorollary paco5_3_1_mult: forall r_0 r_1 r_2,\n  paco5_3_1 gf_0 gf_1 gf_2 (paco5_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco5_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco5_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <5= paco5_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco5_3_1_mult_strong, paco5_3_1_mon; eauto. Qed.\n\nCorollary paco5_3_2_mult: forall r_0 r_1 r_2,\n  paco5_3_2 gf_0 gf_1 gf_2 (paco5_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco5_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco5_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <5= paco5_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco5_3_2_mult_strong, paco5_3_2_mon; eauto. Qed.\n\nTheorem paco5_3_0_fold: forall r_0 r_1 r_2,\n  gf_0 (upaco5_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco5_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco5_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <5= paco5_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco5_3_1_fold: forall r_0 r_1 r_2,\n  gf_1 (upaco5_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco5_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco5_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <5= paco5_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco5_3_2_fold: forall r_0 r_1 r_2,\n  gf_2 (upaco5_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco5_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco5_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <5= paco5_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco5_3_0_unfold: forall (MON: monotone5_3 gf_0) (MON: monotone5_3 gf_1) (MON: monotone5_3 gf_2) r_0 r_1 r_2,\n  paco5_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2 <5= gf_0 (upaco5_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco5_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco5_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2).\nProof. unfold monotone5_3; intros; destruct PR; eauto. Qed.\n\nTheorem paco5_3_1_unfold: forall (MON: monotone5_3 gf_0) (MON: monotone5_3 gf_1) (MON: monotone5_3 gf_2) r_0 r_1 r_2,\n  paco5_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2 <5= gf_1 (upaco5_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco5_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco5_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2).\nProof. unfold monotone5_3; intros; destruct PR; eauto. Qed.\n\nTheorem paco5_3_2_unfold: forall (MON: monotone5_3 gf_0) (MON: monotone5_3 gf_1) (MON: monotone5_3 gf_2) r_0 r_1 r_2,\n  paco5_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2 <5= gf_2 (upaco5_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco5_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco5_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2).\nProof. unfold monotone5_3; intros; destruct PR; eauto. Qed.\n\nEnd Arg5_3.\n\nHint Unfold monotone5_3.\nHint Resolve paco5_3_0_fold.\nHint Resolve paco5_3_1_fold.\nHint Resolve paco5_3_2_fold.\n\nImplicit Arguments paco5_3_0_acc            [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_3_1_acc            [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_3_2_acc            [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_3_0_mon            [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_3_1_mon            [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_3_2_mon            [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_3_0_mult_strong    [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_3_1_mult_strong    [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_3_2_mult_strong    [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_3_0_mult           [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_3_1_mult           [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_3_2_mult           [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_3_0_fold           [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_3_1_fold           [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_3_2_fold           [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_3_0_unfold         [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_3_1_unfold         [ T0 T1 T2 T3 T4 ].\nImplicit Arguments paco5_3_2_unfold         [ T0 T1 T2 T3 T4 ].\n\nInstance paco5_3_0_inst  T0 T1 T2 T3 T4 (gf_0 gf_1 gf_2 : rel5 T0 T1 T2 T3 T4->_) r_0 r_1 r_2 x0 x1 x2 x3 x4 : paco_class (paco5_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2 x0 x1 x2 x3 x4) :=\n{ pacoacc    := paco5_3_0_acc gf_0 gf_1 gf_2;\n  pacomult   := paco5_3_0_mult gf_0 gf_1 gf_2;\n  pacofold   := paco5_3_0_fold gf_0 gf_1 gf_2;\n  pacounfold := paco5_3_0_unfold gf_0 gf_1 gf_2 }.\n\nInstance paco5_3_1_inst  T0 T1 T2 T3 T4 (gf_0 gf_1 gf_2 : rel5 T0 T1 T2 T3 T4->_) r_0 r_1 r_2 x0 x1 x2 x3 x4 : paco_class (paco5_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2 x0 x1 x2 x3 x4) :=\n{ pacoacc    := paco5_3_1_acc gf_0 gf_1 gf_2;\n  pacomult   := paco5_3_1_mult gf_0 gf_1 gf_2;\n  pacofold   := paco5_3_1_fold gf_0 gf_1 gf_2;\n  pacounfold := paco5_3_1_unfold gf_0 gf_1 gf_2 }.\n\nInstance paco5_3_2_inst  T0 T1 T2 T3 T4 (gf_0 gf_1 gf_2 : rel5 T0 T1 T2 T3 T4->_) r_0 r_1 r_2 x0 x1 x2 x3 x4 : paco_class (paco5_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2 x0 x1 x2 x3 x4) :=\n{ pacoacc    := paco5_3_2_acc gf_0 gf_1 gf_2;\n  pacomult   := paco5_3_2_mult gf_0 gf_1 gf_2;\n  pacofold   := paco5_3_2_fold gf_0 gf_1 gf_2;\n  pacounfold := paco5_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/paco5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2649221834106257}}
{"text": "Require Import Raft.\nRequire Import RaftRefinementInterface.\n\nSection AllEntriesLeaderLogs.\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 leader_without_missing_entry net :=\n    forall t e h,\n      In (t, e) (allEntries (fst (nwState net h))) ->\n      In e (log (snd (nwState  net h))) \\/\n      exists t' log' leader,\n        t' > t /\\\n        In (t', log') (leaderLogs (fst (nwState net leader))) /\\\n        ~ In e log'.\n\n  Definition appendEntriesRequest_exists_leaderLog 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      exists log,\n        In (t, log) (leaderLogs (fst (nwState net (pSrc p)))).\n\n  Definition appendEntriesRequest_leaderLog_not_in net :=\n    forall p t leaderId prevLogIndex prevLogTerm entries leaderCommit log e,\n      In p (nwPackets net) ->\n      pBody p = AppendEntries t leaderId prevLogIndex prevLogTerm\n                              entries leaderCommit ->\n      eIndex e > prevLogIndex ->\n      ~ In e entries ->\n      In (t, log) (leaderLogs (fst (nwState net (pSrc p)))) ->\n      ~ In e log.\n\n  Definition leaderLogs_leader net :=\n    forall h,\n      type (snd (nwState net h)) = Leader ->\n      exists log' es,\n        In (currentTerm (snd (nwState net h)), log') (leaderLogs (fst (nwState net h))) /\\\n        log (snd (nwState net h)) = es ++ log'.\n\n  Definition all_entries_leader_logs net :=\n    leader_without_missing_entry net /\\ appendEntriesRequest_exists_leaderLog net /\\\n    appendEntriesRequest_leaderLog_not_in net /\\\n    leaderLogs_leader net.\n  \n  Class all_entries_leader_logs_interface : Prop :=\n    {\n      all_entries_leader_logs_invariant :\n        forall net,\n          refined_raft_intermediate_reachable net ->\n          all_entries_leader_logs net\n    }.\nEnd AllEntriesLeaderLogs.", "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/AllEntriesLeaderLogsInterface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802471698041, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2649221729534721}}
{"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 CertiGraph.lib.Coqlib.\nRequire Import CertiGraph.lib.EquivDec_ext.\nRequire Import CertiGraph.msl_ext.log_normalize.\nRequire Import CertiGraph.msl_ext.iter_sepcon.\nRequire Import CertiGraph.msl_ext.seplog.\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 Export CertiGraph.graph.BiGraph.\nRequire Export CertiGraph.graph.MathGraph.\nRequire Export CertiGraph.graph.FiniteGraph.\nRequire Import CertiGraph.msl_application.Graph.\nRequire Import Coq.Logic.Classical.\nImport OconNotation.\n\nLocal Open Scope logic.\n\nInductive LR :=\n  | L\n  | R.\n\nClass pPointwiseGraph_Graph_Bi: Type := {\n  addr: Type;\n  null: addr;\n  SGBA: PointwiseGraphBasicAssum addr (addr * LR)\n}.\n\nExisting Instance SGBA.\n\nDefinition is_null_SGBA {pSGGB: pPointwiseGraph_Graph_Bi} : DecidablePred addr := (existT (fun P => forall a, {P a} + {~ P a}) (fun x => x = null) (fun x => SGBA_VE x null)).\n\nClass sPointwiseGraph_Graph_Bi {pSGG_Bi: pPointwiseGraph_Graph_Bi} (DV DE: Type): Type := {\n  pred: Type;\n  SGP: PointwiseGraphPred addr (addr * LR) (DV * addr * addr) unit pred;\n  SGA: PointwiseGraphAssum SGP;\n  SGAvs: PointwiseGraphAssum_vs SGP;\n  SGAvn: PointwiseGraphAssum_vn SGP null\n}.\n\nExisting Instances SGP SGA SGAvs.\n\nSection GRAPH_BI.\n\n(*********************************************************\n\nPure Facts Part\n\n*********************************************************)\n\nContext {pSGG_Bi: pPointwiseGraph_Graph_Bi}.\nContext {DV DE DG: Type}.\n\nClass BiMaFin (g: PreGraph addr (addr * LR)) := {\n  bi: BiGraph g (fun x => (x, L)) (fun x => (x, R));\n  ma: MathGraph g is_null_SGBA;\n  fin: FiniteGraph g\n}.\n\nClass BiMaFin' (g: PreGraph addr (addr * LR)) := {\n  bi': BiGraph g (fun x => (x, L)) (fun x => (x, R));\n  ma': MathGraph' g is_null_SGBA;\n  fin': FiniteGraph g\n}.\n\nDefinition Graph := (GeneralGraph addr (addr * LR) DV DE DG (fun g => BiMaFin (pg_lg g))).\nDefinition Graph' := (GeneralGraph addr (addr * LR) DV DE DG (fun g => BiMaFin' (pg_lg g))).\nDefinition LGraph := (LabeledGraph addr (addr * LR) DV DE DG).\nDefinition SGraph := (PointwiseGraph addr (addr * LR) (DV * addr * addr) unit).\n\nInstance SGC_Bi: PointwiseGraphConstructor addr (addr * LR) DV DE DG (DV * addr * addr) unit.\nProof.\n  refine (Build_PointwiseGraphConstructor _ _ _ _ _ _ _ SGBA _ _).\n  + exact (fun G v => (vlabel G v, dst (pg_lg G) (v, L), dst (pg_lg G) (v, R))).\n  + exact (fun _ _ => tt).\nDefined.\n\nInstance L_SGC_Bi: Local_PointwiseGraphConstructor addr (addr * LR) DV DE DG (DV * addr * addr) unit.\nProof.\n  refine (Build_Local_PointwiseGraphConstructor _ _ _ _ _ _ _ SGBA SGC_Bi\n    (fun G v => evalid (pg_lg G) (v, L) /\\ evalid (pg_lg G) (v, R) /\\\n                src (pg_lg G) (v, L) = v /\\ src (pg_lg G) (v, R) = v) _\n    (fun _ _ => True) _).\n  + intros.\n    simpl.\n    destruct H as [? [? [? ?]]], H0 as [? [? [? ?]]].\n    f_equal; [f_equal |]; auto.\n  + intros; simpl.\n    auto.\nDefined.\n\nGlobal Existing Instances SGC_Bi L_SGC_Bi.\n\nDefinition Graph_LGraph (G: Graph): LGraph := lg_gg G.\nDefinition Graph'_LGraph (G: Graph'): LGraph := lg_gg G.\nDefinition LGraph_SGraph (G: LGraph): SGraph := Graph_PointwiseGraph G.\n\nLocal Coercion Graph_LGraph: Graph >-> LGraph.\nLocal Coercion Graph'_LGraph: Graph' >-> LGraph.\nLocal Coercion LGraph_SGraph: LGraph >-> SGraph.\nLocal Identity Coercion Graph_GeneralGraph: Graph >-> GeneralGraph.\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\nInstance biGraph (G: Graph): BiGraph G (fun x => (x, L)) (fun x => (x, R)) :=\n  @bi G (@sound_gg _ _ _ _ _ _ _ _ G).\n\nInstance biGraph' (G: Graph'): BiGraph G (fun x => (x, L)) (fun x => (x, R)) :=\n  @bi' G (@sound_gg _ _ _ _ _ _ _ _ G).\n\nInstance maGraph(G: Graph): MathGraph G is_null_SGBA :=\n  @ma G (@sound_gg _ _ _ _ _ _ _ _ G).\n\nInstance maGraph'(G: Graph'): MathGraph' G is_null_SGBA :=\n  @ma' G (@sound_gg _ _ _ _ _ _ _ _ G).\n\nInstance finGraph (G: Graph): FiniteGraph G :=\n  @fin G (@sound_gg _ _ _ _ _ _ _ _ G).\n\nInstance finGraph' (G: Graph'): FiniteGraph G :=\n  @fin' G (@sound_gg _ _ _ _ _ _ _ _ G).\n\nInstance RGF (G: Graph): ReachableFiniteGraph G.\n  apply Build_ReachableFiniteGraph.\n  intros.\n  apply finite_reachable_computable with (is_null := is_null_SGBA) in H.\n  + destruct H as [l [? ?]].\n    exists l; auto.\n  + apply maGraph.\n  + apply (LocalFiniteGraph_FiniteGraph G), finGraph.\n  + apply (FiniteGraph_EnumCovered G), finGraph.\nDefined.\n\nDefinition Graph_vgen (G: Graph) (x: addr) (d: DV) : Graph :=\n  generalgraph_vgen G x d (sound_gg G).\n\nDefinition Graph_egen (G: Graph) (e: addr * LR) (d: DE) : Graph :=\n  generalgraph_egen G e d (sound_gg G).\n\nDefinition empty_BiGraph: BiGraph (empty_pregraph (fun e => fst e) (fun e => null)) (fun x => (x, L)) (fun x => (x, R)).\n  constructor.\n  + intros ? [].\n  + intros ? ? [].\nDefined.\n      \nDefinition empty_MathGraph: MathGraph (empty_pregraph (fun e => fst e) (fun e => null)) is_null_SGBA.\n  apply (Build_MathGraph _ is_null_SGBA).\n  + intros ? [].\n  + intros ? [].\nDefined.\n\nDefinition empty_MathGraph': MathGraph' (empty_pregraph (fun e => fst e) (fun e => null)) is_null_SGBA.\n  apply (Build_MathGraph' _ is_null_SGBA).\n  + intros ? [].\n  + intros ? [].\nDefined.\n\nDefinition empty_FiniteGraph: FiniteGraph (empty_pregraph (fun e => fst e) (fun e => null)).\n  constructor.\n  + exists nil.\n    split; [constructor | intros].\n    simpl.\n    unfold Ensembles.In; reflexivity. \n  + exists nil.\n    split; [constructor | intros].\n    simpl.\n    unfold Ensembles.In; reflexivity. \nDefined.\n\nDefinition empty_sound: BiMaFin (empty_pregraph (fun e => fst e) (fun e => null)) :=\n  Build_BiMaFin _ empty_BiGraph empty_MathGraph empty_FiniteGraph.\n\nDefinition empty_sound': BiMaFin' (empty_pregraph (fun e => fst e) (fun e => null)) :=\n  Build_BiMaFin' _ empty_BiGraph empty_MathGraph' empty_FiniteGraph.\n\nDefinition empty_Graph (default_v: DV) (default_e: DE) (default_g : DG) : Graph :=\n  Build_GeneralGraph _ _ _ _ (empty_labeledgraph (fun e => fst e) (fun e => null) default_v default_e default_g) empty_sound.\n\nDefinition empty_Graph' (default_v: DV) (default_e: DE) (default_g : DG) : Graph' :=\n  Build_GeneralGraph _ _ _ _ (empty_labeledgraph (fun e => fst e) (fun e => null) default_v default_e default_g) empty_sound'.\n\nDefinition is_BiMaFin (g: LGraph): Prop := exists X: BiMaFin (pg_lg g), True.\n\nDefinition is_BiMaFin' (g: LGraph): Prop := exists X: BiMaFin' (pg_lg g), True.\n\nDefinition is_guarded_BiMaFin (PV: addr -> Prop) (PE: addr * LR -> Prop) (g: LGraph): Prop := is_BiMaFin (gpredicate_sub_labeledgraph PV PE g).\n\nDefinition is_guarded_BiMaFin' (PV: addr -> Prop) (PE: addr * LR -> Prop) (g: LGraph): Prop := is_BiMaFin' (gpredicate_sub_labeledgraph PV PE g).\n\nDefinition left_right_sound: forall (g: Graph) (x: addr) lr,\n  vvalid g x ->\n  src g (x, lr) = x.\nProof.\n  intros.\n  destruct lr.\n  + apply (@left_sound _ _ _ _ _ _ g (biGraph _) x); auto.\n  + apply (@right_sound _ _ _ _ _ _ g (biGraph _) x); auto.\nQed.\n\nDefinition left_right_sound0: forall (g: Graph) (x: addr) lr,\n  evalid g (x, lr) ->\n  src g (x, lr) = x.\nProof.\n  intros.\n  destruct lr.\n  + destruct (@valid_graph _ _ _ _ g _ (maGraph _) (x, L) H) as [? _].\n    pose proof (@only_two_edges _ _ _ _ g _ _ (biGraph _) _ (x, L) H0).\n    simpl in H1.\n    destruct H1 as [? _].\n    specialize (H1 (conj eq_refl H)).\n    destruct H1; inversion H1.\n    rewrite <- ! H3; auto.\n  + destruct (@valid_graph _ _ _ _ g _ (maGraph _) (x, R) H) as [? _].\n    pose proof (@only_two_edges _ _ _ _ g _ _ (biGraph _) _ (x, R) H0).\n    simpl in H1.\n    destruct H1 as [? _].\n    specialize (H1 (conj eq_refl H)).\n    destruct H1; inversion H1.\n    rewrite <- ! H3; auto.\nQed.\n\nDefinition left_right_sound': forall (g: Graph') (x: addr) lr,\n  vvalid g x ->\n  src g (x, lr) = x.\nProof.\n  intros.\n  destruct lr.\n  + apply (@left_sound _ _ _ _ _ _ g (biGraph' _) x); auto.\n  + apply (@right_sound _ _ _ _ _ _ g (biGraph' _) x); auto.\nQed.\n\nDefinition left_right_sound0': forall (g: Graph') (x: addr) lr,\n  evalid g (x, lr) ->\n  src g (x, lr) = x.\nProof.\n  intros.\n  destruct lr.\n  + pose proof @valid_graph' _ _ _ _ g _ (maGraph' _) (x, L) H.\n    pose proof (@only_two_edges _ _ _ _ g _ _ (biGraph' _) _ (x, L) H0).\n    simpl in H1.\n    destruct H1 as [? _].\n    specialize (H1 (conj eq_refl H)).\n    destruct H1; inversion H1.\n    rewrite <- ! H3; auto.\n  + pose proof @valid_graph' _ _ _ _ g _ (maGraph' _) (x, R) H.\n    pose proof (@only_two_edges _ _ _ _ g _ _ (biGraph' _) _ (x, R) H0).\n    simpl in H1.\n    destruct H1 as [? _].\n    specialize (H1 (conj eq_refl H)).\n    destruct H1; inversion H1.\n    rewrite <- ! H3; auto.\nQed.\n\nLemma weak_valid_vvalid_dec: forall (g : Graph) (x: addr),\n  weak_valid g x -> Decidable (vvalid g x).\nProof.\n  intros.\n  apply null_or_valid in H.\n  destruct H; [right | left]; auto.\n  pose proof valid_not_null g x; tauto.\nQed.\nHint Resolve weak_valid_vvalid_dec : GraphDec.\n\nLemma invalid_null: forall (g: Graph), ~ vvalid g null.\nProof.\n  intros.\n  pose proof @valid_not_null _ _ _ _ g _ (maGraph g) null.\n  cbv beta delta [is_null_SGBA] in H; simpl in H.\n  tauto.\nQed.\n\nLemma vvalid_vguard: forall (g: Graph) x,\n  vvalid g x ->\n  vguard g x.\nProof.\n  intros.\n  pose proof biGraph g.\n  simpl.\n  split; [| split; [| split]].\n  + apply left_valid with (x0 := x) in H0; auto.\n  + apply right_valid with (x0 := x) in H0; auto.\n  + pose proof (proj2 (only_two_edges x (x, L) H)).\n    specialize (H1 (or_introl eq_refl)).\n    tauto.\n  + pose proof (proj2 (only_two_edges x (x, R) H)).\n    specialize (H1 (or_intror eq_refl)).\n    tauto.\nQed.\n\nLemma vvalid_vguard': forall (g: Graph') x,\n  vvalid g x ->\n  vguard g x.\nProof.\n  intros.\n  pose proof biGraph' g.\n  simpl.\n  split; [| split; [| split]].\n  + apply left_valid with (x0 := x) in H0; auto.\n  + apply right_valid with (x0 := x) in H0; auto.\n  + pose proof (proj2 (only_two_edges x (x, L) H)).\n    specialize (H1 (or_introl eq_refl)).\n    tauto.\n  + pose proof (proj2 (only_two_edges x (x, R) H)).\n    specialize (H1 (or_intror eq_refl)).\n    tauto.\nQed.\n\nDefinition Graph_gen_left_null (G : Graph) (x : addr) : Graph.\nProof.\n  refine (generalgraph_gen_dst G (x, L) null _).\n  assert (weak_valid G null) by (left; reflexivity).\n  refine (Build_BiMaFin _ (gen_dst_preserve_bi G (x, L) null _)\n                        (gen_dst_preserve_math G (x, L) null ma H)\n                        (gen_dst_preserve_finite G (x, L) null (finGraph G))).\nDefined.\n\nDefinition Graph_gen_right_null (G : Graph) (x : addr) : Graph.\nProof.\n  refine (generalgraph_gen_dst G (x, R) null _).\n  assert (weak_valid G null) by (left; reflexivity).\n  refine (Build_BiMaFin _ (gen_dst_preserve_bi G (x, R) null _)\n                        (gen_dst_preserve_math G (x, R) null ma H)\n                        (gen_dst_preserve_finite G (x, R) null (finGraph G))).\nDefined.\n\nLtac s_rewrite p :=\n  let H := fresh \"H\" in\n  pose proof p as H;\n  simpl in H;\n  rewrite H;\n  clear H.\n\nLemma Graph_vgen_vgamma: forall (G: Graph) (x: addr) (d d': DV) l r,\n  vgamma G x = (d, l, r) ->\n  vgamma (Graph_vgen G x d') x = (d', l, r).\nProof.\n  intros.\n  simpl in H |- *.\n  inversion H; subst.\n  f_equal.\n  f_equal.\n  unfold update_vlabel.\n  destruct_eq_dec x x; [| congruence].\n  auto.\nQed.\n\n(*\nLemma Graph_gen_spatial_spec: forall (G: Graph) (x: addr) (d d': DV) l r,\n  vgamma G x = (d, l, r) ->\n  (Graph_gen G x d') -=- (spatialgraph_vgen G x (d', l, r)).\nProof.\n  intros.\n  split; [reflexivity | split; [| auto]].\n  simpl in *; intros.\n  simpl in *; unfold update_vlabel.\n  destruct_eq_dec x v; subst.\n  + inversion H; subst; f_equal; f_equal.\n  + auto.\nQed.\n\n(* TODO: This lemma is not true. They are not even structural identical.\n   But we should change the definition of validly identical or some how fix this. *)\nLemma Graph_gen_left_null_spatial_spec: forall (G: Graph) (x: addr) (d : DV) l r,\n    vgamma G x = (d, l, r) ->\n    (Graph_gen_left_null G x) -=- (spatialgraph_vgen G x (d, null, r)).\nProof.\n  intros.\n  split; [|split; [| auto]].\n  + split; [|split; [|split]]; intros; simpl; intuition.\n    unfold Graph_gen_left_null in H0. simpl in H0. unfold spatialgraph_vgen in H1. simpl in H1.\n  + intros. simpl. unfold Graph_gen_left_null. unfold generalgraph_gen_dst. simpl.\n    unfold update_dst. destruct_eq_dec (x, L) (v, L).\n    - destruct_eq_dec (x, L) (v, R). inversion H3. inversion H2. destruct_eq_dec v v. 2: exfalso; auto.\n      simpl in H. inversion H; subst; auto.\n    - destruct_eq_dec (x, L) (v, R). inversion H3. destruct_eq_dec x v.\n      * subst. exfalso; auto.\n      * auto.\nQed.\n*)\n\nLemma weak_valid_si: forall (g1 g2: Graph) n, g1 ~=~ g2 -> (weak_valid g1 n <-> weak_valid g2 n).\nProof.\n  intros.\n  unfold weak_valid.\n  destruct H as [? _].\n  rewrite H.\n  reflexivity.\nQed.\n\nLemma gamma_step: forall (g : Graph) x (d: DV) (l r: addr), vvalid g x -> vgamma g x = (d, l, r) -> forall y, step g x y <-> y = l \\/ y = r.\nProof.\n  intros. simpl in H0; inversion H0; subst.\n  rewrite step_spec; split; intros.\n  + destruct H1 as [e [? [? ?]]].\n    pose proof (only_two_edges x e H).\n    cbv beta in H4.\n    pose proof (proj1 H4 (conj H2 H1)).\n    destruct H5; subst e; auto.\n  + destruct H1.\n    - exists (x, L).\n      s_rewrite (left_sound g); auto.\n      apply (left_valid g) in H.\n      auto.\n    - exists (x, R).\n      s_rewrite (right_sound g); auto.\n      apply (right_valid g) in H.\n      auto.\nQed.\n\nLemma gamma_left_weak_valid: forall (g : Graph) x d l r, vvalid g x -> vgamma g x = (d, l, r) -> weak_valid g l.\nProof.\n  intros.\n  simpl in H0.\n  inversion H0.\n  pose proof valid_graph g (x, L).\n  spec H1; [pose proof (left_valid g); auto |].\n  tauto.\nQed.\nHint Resolve gamma_left_weak_valid : GraphDec.\n\nLemma gamma_right_weak_valid: forall (g : Graph) x d l r, vvalid g x -> vgamma g x = (d, l, r) -> weak_valid g r.\nProof.\n  intros.\n  simpl in H0.\n  inversion H0.\n  pose proof valid_graph g (x, R).\n  spec H1; [pose proof (right_valid g); auto |].\n  tauto.\nQed.\nHint Resolve gamma_right_weak_valid : GraphDec.\n\nLemma gamma_step_list: forall (g : Graph) x d l r, vvalid g x -> vgamma g x = (d, l, r) -> step_list g x (l :: r :: nil).\nProof.\n  intros.\n  unfold step_list.\n  intros y.\n  rewrite gamma_step by eauto.\n  simpl.\n  pose proof (@eq_sym _ l y).\n  pose proof (@eq_sym _ r y).\n  pose proof (@eq_sym _ y l).\n  pose proof (@eq_sym _ y r).\n  tauto.\nQed.\n\nLemma gamma_step_list': forall (g : Graph) x d l r, vvalid g x -> vgamma g x = (d, l, r) -> step_list g x (r :: l :: nil).\nProof.\n  intros.\n  unfold step_list.\n  intros y.\n  rewrite gamma_step by eauto.\n  simpl.\n  pose proof (@eq_sym _ l y).\n  pose proof (@eq_sym _ r y).\n  pose proof (@eq_sym _ y l).\n  pose proof (@eq_sym _ y r).\n  tauto.\nQed.\n\nLemma Graph_reachable_dec: forall (G: Graph) x,\n    Decidable (vvalid G x) -> forall y, Decidable (reachable G x y).\nProof.\n  intros.\n  apply reachable_decidable with (is_null := is_null_SGBA); auto.\n  + apply maGraph.\n  + apply LocalFiniteGraph_FiniteGraph, finGraph.\n  + apply FiniteGraph_EnumCovered, finGraph.\nQed.\nHint Resolve Graph_reachable_dec : GraphDec.\n\nLemma Graph_reachable_by_dec: forall (G: Graph) x (P: NodePred addr),\n    Decidable (vvalid G x) -> ReachDecidable G x P.\nProof.\n  intros.\n  intro y.\n  apply reachable_by_decidable with (is_null := is_null_SGBA); auto.\n  + apply maGraph.\n  + apply LocalFiniteGraph_FiniteGraph, finGraph.\n  + apply FiniteGraph_EnumCovered, finGraph.\nQed.\n(*\nLemma Graph_partialgraph_vi_spec: forall (G G': Graph) (P P': addr -> Prop),\n  (predicate_partialgraph G P) ~=~ (predicate_partialgraph G' P') ->\n  (forall v, vvalid G v -> P v -> vvalid G' v -> P' v -> vlabel G v = vlabel G' v) ->\n  (predicate_partial_spatialgraph G P) -=- (predicate_partial_spatialgraph G' P').\nProof.\n  intros.\n  split; [auto |].\n  split; [| intros; simpl; auto].\n  simpl; unfold predicate_vvalid.\n  intros.\n  f_equal; [f_equal |].\n  + apply H0; tauto.\n  + destruct H as [_ [_ [_ ?]]].\n    generalize (left_sound G v); intro.\n    generalize (left_sound G' v); intro.\n    apply H; simpl; unfold predicate_weak_evalid.\n    - destruct H1. apply (left_valid G) in H1. change (pg_lg G) with (G: PGraph). rewrite H3. auto.\n    - destruct H2. apply (left_valid G') in H2. change (pg_lg G') with (G': PGraph). rewrite H4. auto.\n  + destruct H as [_ [_ [_ ?]]].\n    generalize (right_sound G v); intro.\n    generalize (right_sound G' v); intro.\n    apply H; simpl; unfold predicate_weak_evalid.\n    - destruct H1. apply (right_valid G) in H1. change (pg_lg G) with (G: PGraph). rewrite H3. auto.\n    - destruct H2. apply (right_valid G') in H2. change (pg_lg G') with (G': PGraph). rewrite H4. auto.\nQed.\n*)\nLemma gamma_left_reachable_included: forall (g: Graph) x d l r,\n                                       vvalid g x -> vgamma g x = (d, l, r) -> Included (reachable g l) (reachable g x).\nProof.\n  intros. intro y; intros. apply edge_reachable_by with l; auto. split; auto. split.\n  + apply reachable_head_valid in H1; auto.\n  + rewrite (gamma_step _ _ _ _ _ H H0). auto.\nQed.\n\nLemma gamma_right_reachable_included: forall (g: Graph) x d l r,\n                                        vvalid g x -> vgamma g x = (d, l, r) -> Included (reachable g r) (reachable g x).\nProof.\n  intros. intro y; intros. apply edge_reachable_by with r; auto. split; auto. split.\n  + apply reachable_head_valid in H1; auto.\n  + rewrite (gamma_step _ _ _ _ _ H H0). auto.\nQed.\n\nLemma Prop_join_reachable_left: forall (g: Graph) x d l r,\n  vvalid g x ->\n  vgamma g x = (d, l, r) ->\n  Prop_join\n    (reachable g l)\n    (Intersection _ (reachable g x) (Complement addr (reachable g l)))\n    (reachable g x).\nProof.\n  intros.\n  apply Ensemble_join_Intersection_Complement.\n  - eapply gamma_left_reachable_included; eauto.\n  - intros.\n    apply gamma_left_weak_valid in H0; [| auto].\n    apply decidable_prop_decidable, Graph_reachable_dec, weak_valid_vvalid_dec; auto.\nQed.\n\nLemma Prop_join_reachable_right: forall (g: Graph) x d l r,\n  vvalid g x ->\n  vgamma g x = (d, l, r) ->\n  Prop_join\n    (reachable g r)\n    (Intersection _ (reachable g x) (Complement addr (reachable g r)))\n    (reachable g x).\nProof.\n  intros.\n  apply Ensemble_join_Intersection_Complement.\n  - eapply gamma_right_reachable_included; eauto.\n  - intros.\n    apply gamma_right_weak_valid in H0; [| auto].\n    apply decidable_prop_decidable, Graph_reachable_dec, weak_valid_vvalid_dec; auto.\nQed.\n\nLemma dst_L_eq: forall (g1 g2: Graph) x,\n  vvalid g1 x ->\n  g1 ~=~ g2 ->\n  dst g1 (x, L) = dst g2 (x, L).\nProof.\n  intros.\n  destruct H0 as [? [? [? ?]]].\n  assert (vvalid g2 x) by (clear - H H0; firstorder).\n  apply H3.\n  + eapply left_valid in H; [| apply biGraph].\n    auto.\n  + eapply left_valid in H4; [| apply biGraph].\n    auto.\nQed.\n\nLemma dst_R_eq: forall (g1 g2: Graph) x,\n  vvalid g1 x ->\n  g1 ~=~ g2 ->\n  dst g1 (x, R) = dst g2 (x, R).\nProof.\n  intros.\n  destruct H0 as [? [? [? ?]]].\n  assert (vvalid g2 x) by (clear - H H0; firstorder).\n  apply H3.\n  + eapply right_valid in H; [| apply biGraph].\n    auto.\n  + eapply right_valid in H4; [| apply biGraph].\n    auto.\nQed.\n\nInstance BiMaFin_Normal: NormalGeneralGraph (fun g: LGraph => BiMaFin g).\nProof.\n  constructor.\n  + intros.\n    destruct X as [?H ?H ?H].\n    apply (bi_graph_si _ _ (proj1 H)) in H0.\n    apply (math_graph_si _ _ (proj1 H)) in H1.\n    apply (finite_graph_si _ _ (proj1 H)) in H2.\n    constructor; auto.\n  + intros.\n    destruct X as [?H ?H ?H].\n    destruct X0 as [?H ?H ?H].\n    constructor.\n    - eapply bi_graph_join; eauto.\n    - eapply math_graph_join; eauto.\n    - eapply finite_graph_join; eauto.\nQed.\n\nInstance BiMaFin'_Normal: NormalGeneralGraph (fun g: LGraph => BiMaFin' g).\nProof.\n  constructor.\n  + intros.\n    destruct X as [?H ?H ?H].\n    apply (bi_graph_si _ _ (proj1 H)) in H0.\n    apply (math_graph_si' _ _ (proj1 H)) in H1.\n    apply (finite_graph_si _ _ (proj1 H)) in H2.\n    constructor; auto.\n  + intros.\n    destruct X as [?H ?H ?H].\n    destruct X0 as [?H ?H ?H].\n    constructor.\n    - eapply bi_graph_join'; eauto.\n    - eapply math_graph_join'; eauto.\n    - eapply finite_graph_join; eauto.\nQed.\n\nLemma Graph_is_BiMaFin: forall (g: Graph), is_BiMaFin g.\nProof.\n  intros.\n  destruct g.\n  exists sound_gg; auto.\nQed.\n\nLemma Graph'_is_BiMaFin': forall (g: Graph'), is_BiMaFin' g.\nProof.\n  intros.\n  destruct g.\n  exists sound_gg; auto.\nQed.\n\nLemma single_vertex_guarded_BiMaFin: forall (x0: addr) dv de dg,\n  is_guarded_BiMaFin (fun v : addr => x0 <> v) (fun _ : addr * LR => ~ False)\n    (single_vertex_labeledgraph x0 dv de dg).\nProof.\n  intros.\n  constructor; auto.\n  simpl.\n  constructor.\n  + constructor; simpl; intros.\n    - congruence.\n    - rewrite Intersection_spec in H; destruct H; congruence.\n  + constructor; simpl; intros.\n    - rewrite Intersection_spec in H; destruct H; tauto.\n    - rewrite Intersection_spec in H; destruct H; congruence.\n  + constructor; exists nil; repeat constructor.\n    - inversion H.\n    - inversion H.\n    - simpl; intros.\n      unfold Ensembles.In in H; rewrite Intersection_spec in H; destruct H; congruence.\n    - inversion H.\n    - inversion H.\n    - simpl; intros.\n      unfold Ensembles.In in H; rewrite Intersection_spec in H; destruct H; congruence.\nQed.\n  \nLemma single_vertex_guarded_BiMaFin': forall (x0: addr) dv de dg,\n  is_guarded_BiMaFin' (fun v : addr => x0 <> v) (fun _ : addr * LR => ~ False)\n    (single_vertex_labeledgraph x0 dv de dg).\nProof.\n  intros.\n  constructor; auto.\n  simpl.\n  constructor.\n  + constructor; simpl; intros.\n    - congruence.\n    - rewrite Intersection_spec in H; destruct H; congruence.\n  + constructor; simpl; intros.\n    - rewrite Intersection_spec in H; destruct H; tauto.\n    - rewrite Intersection_spec in H; destruct H; congruence.\n  + constructor; exists nil; repeat constructor.\n    - inversion H.\n    - inversion H.\n    - simpl; intros.\n      unfold Ensembles.In in H; rewrite Intersection_spec in H; destruct H; congruence.\n    - inversion H.\n    - inversion H.\n    - simpl; intros.\n      unfold Ensembles.In in H; rewrite Intersection_spec in H; destruct H; congruence.\nQed.\n  \nLemma is_BiMaFin_si: forall (g1 g2: LGraph),\n  g1 ~=~ g2 ->\n  is_BiMaFin g1 ->\n  is_BiMaFin g2.\nProof.\n  intros.\n  destruct H0 as [[?H ?H ?H] _].\n  apply (bi_graph_si _ _ H) in H0.\n  apply (math_graph_si _ _ H) in H1.\n  apply (finite_graph_si _ _ H) in H2.\n  constructor; constructor; auto.\nQed.\n\nLemma is_BiMaFin_si': forall (g1 g2: LGraph),\n  g1 ~=~ g2 ->\n  is_BiMaFin' g1 ->\n  is_BiMaFin' g2.\nProof.\n  intros.\n  destruct H0 as [[?H ?H ?H] _].\n  apply (bi_graph_si _ _ H) in H0.\n  apply (math_graph_si' _ _ H) in H1.\n  apply (finite_graph_si _ _ H) in H2.\n  constructor; constructor; auto.\nQed.\n\nLemma is_guarded_BiMaFin_labeledgraph_add_edge: forall (g: LGraph) PV PE PE' e s d data_e,\n  ~ evalid g e ->\n  Same_set PE' (Intersection _ PE (fun e0 => e0 <> e)) ->\n  is_guarded_BiMaFin PV PE g ->\n  is_guarded_BiMaFin PV PE' (labeledgraph_add_edge g e s d data_e).\nProof.\n  unfold is_guarded_BiMaFin.\n  intros.\n  eapply is_BiMaFin_si; [| eassumption].\n  simpl.\n  rewrite Same_set_spec in H0.\n  split; [| split; [| split]].\n  + intros; simpl; reflexivity.\n  + intros; simpl.\n    specialize (H0 e0).\n    rewrite !Intersection_spec in *.\n    unfold addValidFunc.\n    rewrite H0.\n    destruct_eq_dec e0 e; [subst |]; try tauto.\n  + simpl; intros.\n    unfold updateEdgeFunc.\n    destruct_eq_dec e e0; auto; subst.\n    specialize (H0 e0).\n    rewrite Intersection_spec in *.\n    destruct H3.\n    tauto.\n  + simpl; intros.\n    unfold updateEdgeFunc.\n    destruct_eq_dec e e0; auto; subst.\n    specialize (H0 e0).\n    rewrite Intersection_spec in *.\n    destruct H3.\n    tauto.\nQed.\n\nLemma is_guarded_BiMaFin'_labeledgraph_add_edge: forall (g: LGraph) PV PE PE' e s d data_e,\n  ~ evalid g e ->\n  Same_set PE' (Intersection _ PE (fun e0 => e0 <> e)) ->\n  is_guarded_BiMaFin' PV PE g ->\n  is_guarded_BiMaFin' PV PE' (labeledgraph_add_edge g e s d data_e).\nProof.\n  unfold is_guarded_BiMaFin'.\n  intros.\n  eapply is_BiMaFin_si'; [| eassumption].\n  simpl.\n  rewrite Same_set_spec in H0.\n  split; [| split; [| split]].\n  + intros; simpl; reflexivity.\n  + intros; simpl.\n    specialize (H0 e0).\n    rewrite !Intersection_spec in *.\n    unfold addValidFunc.\n    rewrite H0.\n    destruct_eq_dec e0 e; [subst |]; try tauto.\n  + simpl; intros.\n    unfold updateEdgeFunc.\n    destruct_eq_dec e e0; auto; subst.\n    specialize (H0 e0).\n    rewrite Intersection_spec in *.\n    destruct H3.\n    tauto.\n  + simpl; intros.\n    unfold updateEdgeFunc.\n    destruct_eq_dec e e0; auto; subst.\n    specialize (H0 e0).\n    rewrite Intersection_spec in *.\n    destruct H3.\n    tauto.\nQed.\n\n(*********************************************************\n\nSpatial Facts Part\n\n*********************************************************)\n\nContext {sSGG_Bi: sPointwiseGraph_Graph_Bi DV DE}.\n\nLemma va_reachable_dag_unfold: forall (g: Graph) x d l r,\n  vvalid g x ->\n  vgamma g x = (d, l, r) ->\n  reachable_dag_vertices_at x g = vertex_at x (d, l, r) * reachable_through_dag_vertices_at (l :: r :: nil) g.\nProof.\n  intros.\n  apply va_reachable_dag_unfold; auto.\n  eapply gamma_step_list; eauto.\nQed.\n\nLemma va_reachable_dag_update_unfold: forall (g: Graph) x d l r v,\n  vvalid g x ->\n  vgamma g x = (d, l, r) ->\n  reachable_dag_vertices_at x (Graph_vgen g x v) = vertex_at x (v, l, r) * reachable_through_dag_vertices_at (l :: r :: nil) g.\nProof.\n  intros.\n  apply va_reachable_dag_update_unfold; auto.\n  + eapply gamma_step_list; eauto.\n  + eapply Graph_vgen_vgamma; eauto.\n  + unfold Included, Ensembles.In; intros.\n    apply vvalid_vguard.\n    apply reachable_through_set_foot_valid in H1; auto.\n  + unfold Included, Ensembles.In; intros.\n    apply vvalid_vguard.\n    apply reachable_through_set_foot_valid in H1; auto.\nQed.\n\nLemma va_reachable_root_stable_ramify: forall (g: Graph) (x: addr) (gx: DV * 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 * (vertex_at x gx -* reachable_vertices_at x g)).\nProof. intros; apply va_reachable_root_stable_ramify; auto. Qed.\n\nLemma va_reachable_root_update_ramify: forall (g: Graph) (x: addr) (lx: DV) (gx gx': DV * addr * addr),\n  vvalid g x ->\n  vgamma g x = gx ->\n  vgamma (Graph_vgen g x lx) x = gx' ->\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.\n  intros.\n  apply va_reachable_root_update_ramify; auto.\n  + unfold Included, Ensembles.In; intros.\n    apply vvalid_vguard.\n    rewrite Intersection_spec in H2.\n    destruct H2 as [? _].\n    apply reachable_foot_valid in H2; auto.\n  + unfold Included, Ensembles.In; intros.\n    apply vvalid_vguard.\n    rewrite Intersection_spec in H2.\n    destruct H2 as [? _].\n    apply reachable_foot_valid in H2; auto.\nQed.\n\nLemma va_reachable_internal_stable_ramify: forall (g: Graph) (x y: addr) (gy: DV * addr * addr),\n  vvalid g y ->\n  vgamma g y = gy ->\n  reachable g x y ->\n  @derives pred _\n    (reachable_vertices_at x g)\n    (vertex_at y gy *\n      (vertex_at y gy -* reachable_vertices_at x g)).\nProof. intros. apply va_reachable_internal_stable_ramify; auto. Qed.\n\n(*\nTODO: maybe as a general lemma for normal_general_graph\nLemma is_guarded_BiMaFin_si: forall (g1 g2: LGraph),\n*)\n\nLemma is_BiMaFin_LGraph_Graph: forall (g: LGraph) (P: LGraph -> pred),\n  is_BiMaFin g ->\n  P g |-- EX g: Graph, P g.\nProof.\n  intros.\n  destruct H as [X _].\n  apply (exp_right (Build_GeneralGraph _ _ _ BiMaFin g X)).\n  simpl.\n  auto.\nQed.\n\nLemma va_labeledgraph_add_edge_eq: forall (g: LGraph) es e s d data,\n  ~ evalid g e ->\n  is_guarded_BiMaFin (fun x => s <> x) (fun e => ~ In e es) g ->\n  let g' := labeledgraph_add_edge g e s d data in\n  @vertices_at _ _ _ _ _ _ SGP _\n   (Intersection _ (vvalid g) (fun x => s <> x)) (Graph_PointwiseGraph g) =\n  @vertices_at _ _ _ _ _ _ SGP _\n   (Intersection _ (vvalid g') (fun x => s <> x)) (Graph_PointwiseGraph g').\nProof.\n  intros.\n  apply va_labeledgraph_add_edge_eq; auto.\n  + unfold Included, Ensembles.In.\n    intros x0 ?.\n    destruct H0 as [X _].\n    pose (g0 := Build_GeneralGraph _ _ _ (fun g => BiMaFin (pg_lg g)) _ X: Graph).\n    assert (vvalid g0 x0) by auto.\n    apply vvalid_vguard in H0.\n    simpl in H0 |- *.\n    rewrite !Intersection_spec in H0.\n    tauto.\n  + unfold Included, Ensembles.In.\n    intros x0 ?.\n    destruct H0 as [X _].\n    pose (g0 := Build_GeneralGraph _ _ _ (fun g => BiMaFin (pg_lg g)) _ X: Graph).\n    assert (vvalid g0 x0) by auto.\n    apply vvalid_vguard in H0.\n    simpl in H0 |- *.\n    rewrite !Intersection_spec in H0.\n    unfold addValidFunc, updateEdgeFunc.\n    split; [| split]; [tauto | tauto |].\n    destruct_eq_dec e (x0, L); subst; [tauto |].\n    destruct_eq_dec e (x0, R); subst; [tauto |].\n    tauto.\nQed.\n\nLemma va_labeledgraph_add_edge_eq': forall (g: LGraph) es e s d data,\n  ~ evalid g e ->\n  is_guarded_BiMaFin' (fun x => s <> x) (fun e => ~ In e es) g ->\n  let g' := labeledgraph_add_edge g e s d data in\n  @vertices_at _ _ _ _ _ _ SGP _\n   (Intersection _ (vvalid g) (fun x => s <> x)) (Graph_PointwiseGraph g) =\n  @vertices_at _ _ _ _ _ _ SGP _\n   (Intersection _ (vvalid g') (fun x => s <> x)) (Graph_PointwiseGraph g').\nProof.\n  intros.\n  apply Graph.va_labeledgraph_add_edge_eq; auto.\n  + unfold Included, Ensembles.In.\n    intros x0 ?.\n    destruct H0 as [X _].\n    pose (g0 := Build_GeneralGraph _ _ _ (fun g => BiMaFin' (pg_lg g)) _ X: Graph').\n    assert (vvalid g0 x0) by auto.\n    apply vvalid_vguard' in H0.\n    simpl in H0 |- *.\n    rewrite !Intersection_spec in H0.\n    tauto.\n  + unfold Included, Ensembles.In.\n    intros x0 ?.\n    destruct H0 as [X _].\n    pose (g0 := Build_GeneralGraph _ _ _ (fun g => BiMaFin' (pg_lg g)) _ X: Graph').\n    assert (vvalid g0 x0) by auto.\n    apply vvalid_vguard' in H0.\n    simpl in H0 |- *.\n    rewrite !Intersection_spec in H0.\n    unfold addValidFunc, updateEdgeFunc.\n    split; [| split]; [tauto | tauto |].\n    destruct_eq_dec e (x0, L); subst; [tauto |].\n    destruct_eq_dec e (x0, R); subst; [tauto |].\n    tauto.\nQed.\n\nLemma va_labeledgraph_egen_eq: forall (g: LGraph) e data P,\n  @vertices_at _ _ _ _ _ _ SGP _\n   P (Graph_PointwiseGraph g) =\n  @vertices_at _ _ _ _ _ _ SGP _\n   P (Graph_PointwiseGraph (labeledgraph_egen g e data)).\nProof.\n  intros.\n  apply vertices_at_vertices_identical.\n  rewrite vertices_identical_spec; intros.\n  simpl; auto.\nQed.\n\n(*********************************************************\n\nSpatial Facts (with Strong Assumption) Part\n\n*********************************************************)\n\n  Context {SGSA: PointwiseGraphStrongAssum SGP}.\n\n  Notation graph x g := (@reachable_vertices_at _ _ _ _ _ _ _ _ (_) _ (@SGP pSGG_Bi DV DE sSGG_Bi) _ x g).\n\n  Lemma bi_graph_unfold: forall (g: Graph) x d l r,\n      vvalid g x -> vgamma g x = (d, l, r) ->\n      graph x g = vertex_at x (d, l, r) ⊗ graph l g ⊗ graph r g.\n  Proof.\n    intros. rewrite graph_unfold with (S := (l :: r :: nil)); auto.\n    + change (Graph_PointwiseGraph g) with (LGraph_SGraph g).\n      rewrite H0. simpl. rewrite ocon_emp. rewrite <- ocon_assoc. auto.\n    + apply RGF.\n    + intros. apply weak_valid_vvalid_dec. simpl in H1.\n      destruct H1; [|destruct H1]; [subst x0 ..|exfalso; auto].\n      - apply (gamma_left_weak_valid _ x d l r); auto.\n      - apply (gamma_right_weak_valid _ x d l r); auto.\n    + apply (gamma_step_list _ _ d l r); auto.\n  Qed.\n\n  Lemma bi_graph_precise_left: forall (g: Graph) x l,\n      vvalid g x -> dst g (x, L) = l -> precise (graph l g).\n  Proof.\n    intros. apply precise_graph. 1: apply RGF.\n    apply weak_valid_vvalid_dec.\n    pose proof (left_valid g x H). simpl in H1.\n    destruct (@valid_graph _ _ _ _ g _ (maGraph g) (x, L) H1).\n    rewrite H0 in H3. apply H3.\n  Qed.\n\n  Lemma bi_graph_precise_right: forall (g: Graph) x r,\n      vvalid g x -> dst g (x, R) = r -> precise (graph r g).\n  Proof.\n    intros. apply precise_graph. 1: apply RGF.\n    apply weak_valid_vvalid_dec.\n    pose proof (right_valid g x H). simpl in H1.\n    destruct (@valid_graph _ _ _ _ g _ (maGraph g) (x, R) H1).\n    rewrite H0 in H3. apply H3.\n  Qed.\n\n  Lemma reachable_through_set_unreachable: forall (g: Graph) (S1 S2: list addr) (v: addr),\n      reachable_through_set (predicate_partialgraph g (Intersection addr (vvalid g) (Complement addr (reachable_through_set g S1)))) S2 v ->\n      Complement addr (reachable_through_set g S1) v.\n  Proof.\n    intros. hnf in H. destruct H as [s [? ?]]. unfold Complement. unfold Ensembles.In . rewrite <- reachable_by_eq_partialgraph_reachable in H0.\n    apply reachable_by_foot_prop in H0. rewrite Intersection_spec in H0. destruct H0. unfold Complement, Ensembles.In in H1. auto.\n  Qed.\n\n  Lemma unreachable_partialgraph_si_vertices_identical: forall (g g': Graph) (S1 S1' S2: list addr),\n      (predicate_partial_labeledgraph g (Complement addr (reachable_through_set g S1)))\n        ~=~\n        (predicate_partial_labeledgraph g' (Complement addr (reachable_through_set g' S1')))%LabeledGraph ->\n      vertices_identical2 (reachable_through_set (predicate_partialgraph g (Intersection addr (vvalid g) (Complement addr (reachable_through_set g S1)))) S2)\n                          (reachable_through_set (predicate_partialgraph g' (Intersection addr (vvalid g') (Complement addr (reachable_through_set g' S1')))) S2)\n                          (Graph_PointwiseGraph g) (Graph_PointwiseGraph g').\n  Proof.\n  intros.\n  apply GSG_PartialGraphPreserve2.\n  - unfold Included, Ensembles.In.\n    intros.\n    apply vvalid_vguard.\n    apply reachable_through_set_foot_valid in H0.\n    destruct H0; auto.\n  - unfold Included, Ensembles.In.\n    intros.\n    apply vvalid_vguard.\n    apply reachable_through_set_foot_valid in H0.\n    destruct H0; auto.\n  - unfold Included, Ensembles.In.\n    intros.\n    apply reachable_through_set_foot_valid in H0.\n    destruct H0; auto.\n  - unfold Included, Ensembles.In.\n    intros.\n    apply reachable_through_set_foot_valid in H0.\n    destruct H0; auto.\n  - assert ((predicate_partialgraph g (Intersection addr (vvalid g) (Complement addr (reachable_through_set g S1))))\n              ~=~\n              (predicate_partialgraph g' (Intersection addr (vvalid g') (Complement addr (reachable_through_set g' S1'))))). {\n      destruct H as [[? [? [? ?]]] _]. hnf. simpl in *. unfold predicate_vvalid in *. unfold predicate_weak_evalid in *.\n      split; [|split; [|split]]; intros; rewrite !Intersection_spec in *.\n      - clear -H. specialize (H v). intuition.\n      - clear H2. specialize (H0 e). specialize (H1 e). intuition.\n        + rewrite <- H2 in *. specialize (H (src g e)). intuition.\n        + rewrite H2 in *. specialize (H (src g' e)). intuition.\n      - apply H1; intuition.\n      - apply H2; intuition.\n    } rewrite <- H0. destruct H as [[? [? [? ?]]] [? ?]]. hnf. unfold structurally_identical. simpl in *. unfold predicate_vvalid in *. unfold predicate_weak_evalid in *.\n    split; [split; [|split; [|split]] |split]; intros.\n    + clear -H H0. intuition.\n      * apply reachable_through_set_unreachable in H3. specialize (H v). intuition.\n      * rewrite H0 in H3. apply reachable_through_set_unreachable in H3. specialize (H v). intuition.\n    + clear -H1 H2 H0. specialize (H1 e). specialize (H2 e). intuition.\n      * apply reachable_through_set_unreachable in H5. apply H1 in H5. intuition.\n      * pose proof H5. apply reachable_through_set_unreachable in H5. specialize (H3 H5). specialize (H1 H5). specialize (H3 H1). rewrite <- H3. auto.\n      * rewrite H0 in H5. apply reachable_through_set_unreachable in H5. specialize (H3 H5). intuition.\n      * pose proof H5. rewrite H0 in H5. apply reachable_through_set_unreachable in H5. specialize (H3 H5). destruct H3. specialize (H1 H3 H6).\n        assert (src g e = src g' e) by (apply H1; auto). rewrite H7. auto.\n    + destruct H6, H7. rewrite H0 in H9. apply reachable_through_set_unreachable in H8. apply reachable_through_set_unreachable in H9. apply H2; auto.\n    + destruct H6, H7. rewrite H0 in H9. apply reachable_through_set_unreachable in H8. apply reachable_through_set_unreachable in H9. apply H3; auto.\n    + destruct H6, H7. rewrite H0 in H9. apply reachable_through_set_unreachable in H8. apply reachable_through_set_unreachable in H9. apply H4; auto.\n    + destruct H6, H7. rewrite H0 in H9. apply reachable_through_set_unreachable in H8. apply reachable_through_set_unreachable in H9. apply H5; auto.\n  Qed.\n\n  Lemma subgraph_update:\n    forall (g g': Graph) (S1 S1' S2: list addr),\n      (forall x : addr, In x (S1 ++ S2) -> Decidable (vvalid g x)) ->\n      (forall x : addr, In x (S1' ++ S2) -> Decidable (vvalid g' x)) ->\n      (predicate_partial_labeledgraph g (Complement addr (reachable_through_set g S1))) ~=~\n      (predicate_partial_labeledgraph g' (Complement addr (reachable_through_set g' S1')))%LabeledGraph ->\n      @derives pred _ (graphs S1 g ⊗ graphs S2 g) (graphs S1 g * (graphs S1' g' -* graphs S1' g' ⊗ graphs S2 g')).\n  Proof.\n    intros.\n    apply subgraph_update; auto.\n    + apply RGF.\n    + apply RGF.\n    + apply unreachable_partialgraph_si_vertices_identical; auto.\n    + apply Included_trans with (vvalid g).\n      - hnf; intros.\n        apply reachable_through_set_foot_valid in H0.\n        destruct H0; auto.\n      - intro v; apply vvalid_vguard.\n    + apply Included_trans with (vvalid g').\n      - hnf; intros.\n        apply reachable_through_set_foot_valid in H0.\n        destruct H0; auto.\n      - intro v; apply vvalid_vguard.\n  Qed.\n\nEnd GRAPH_BI.\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.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2648479491251195}}
{"text": "(*! Understanding conflicts and forwarding !*)\nRequire Import Koika.Frontend.\n\nInductive reg_t :=\n| in0_empty | in0_data\n| in1_empty | in1_data\n| fifo_empty | fifo_data\n| out_empty | out_data.\n\nInductive rule_name_t := deq0 | deq1 | process.\n\nDefinition R (reg: reg_t) : type :=\n  match reg with\n  | in0_empty | in1_empty | fifo_empty | out_empty => bits_t 1\n  | in0_data | in1_data | fifo_data | out_data => bits_t 32\n  end.\n\nDefinition urules (rl: rule_name_t) : uaction reg_t empty_ext_fn_t :=\n  match rl with\n  | deq0 =>\n    {{ guard(!read0(in0_empty) && read0(fifo_empty));\n       write0(fifo_data, read0(in0_data));\n       write0(fifo_empty, Ob~0);\n       write0(in0_empty, Ob~1) }}\n  | deq1 =>\n    {{ guard(!read0(in1_empty) && read0(fifo_empty));\n       write0(fifo_data, read0(in1_data));\n       write0(fifo_empty, Ob~0);\n       write0(in1_empty, Ob~1) }}\n  | process =>\n    {{ guard(!read1(fifo_empty) && read0(out_empty));\n       write0(out_data, read1(fifo_data) + |32`d412|);\n       write1(fifo_empty, Ob~1);\n       write0(out_empty, Ob~0) }}\n  end.\n\nDefinition rules : rule_name_t -> rule R empty_Sigma :=\n  tc_rules R empty_Sigma urules.\n\nDefinition pipeline : scheduler :=\n  deq0 |> deq1 |> process |> done.\n\nDefinition external (r: rule_name_t) := false.\n\nDefinition r (reg: reg_t) : R reg :=\n  match reg with\n  | in0_empty => Ob~0\n  | in0_data => Bits.of_nat _ 42\n  | in1_empty => Ob~0\n  | in1_data => Bits.of_nat _ 73\n  | fifo_empty => Ob~1\n  | fifo_data => Bits.zero\n  | out_empty => Ob~1\n  | out_data => Bits.zero\n  end.\n\nDefinition cr := ContextEnv.(create) r.\n\nDefinition interp_result :=\n  tc_compute (commit_update cr (interp_scheduler cr empty_sigma rules pipeline)).\n\nDefinition circuits :=\n  compile_scheduler rules external pipeline.\n\nDefinition circuits_result :=\n  tc_compute (interp_circuits empty_sigma circuits (lower_r cr)).\n\nDefinition package :=\n  {| ip_koika := {| koika_reg_types := R;\n                   koika_reg_init reg := r reg;\n                   koika_ext_fn_types := empty_Sigma;\n                   koika_rules := rules;\n                   koika_rule_external := external;\n                   koika_scheduler := pipeline;\n                   koika_module_name := \"conflicts\" |};\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 \"conflicts.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/examples/conflicts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.26482907213575}}
{"text": "(** This file collects facts on proof irrelevant types/propositions. *)\nFrom stdpp Require Export base.\nFrom stdpp Require Import options.\n\nHint 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": "SkySkimmer", "repo": "stdpp", "sha": "a40580e6d7e6cd16e60aba6deed496a301804c9f", "save_path": "github-repos/coq/SkySkimmer-stdpp", "path": "github-repos/coq/SkySkimmer-stdpp/stdpp-a40580e6d7e6cd16e60aba6deed496a301804c9f/theories/proof_irrel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.26482907213574997}}
{"text": "(* Copyright (c) 2014, Robert Dockins *)\n\nRequire Import List.\n\nRequire Import Domains.basics.\nRequire Import Domains.categories.\nRequire Import Domains.preord.\nRequire Import Domains.sets.\nRequire Import Domains.finsets.\nRequire Import Domains.esets.\nRequire Import Domains.effective.\nRequire Import Domains.plotkin.\nRequire Import Domains.profinite.\nRequire Import Domains.embed.\nRequire Import Domains.joinable.\nRequire Import Domains.directed.\nRequire Import Domains.cont_functors.\nRequire Import Domains.bilimit.\nRequire Import Domains.exp_functor.\nRequire Import Domains.profinite_adj.\nRequire Import Domains.cont_adj.\n\nNotation Ue := liftEMBED.\nNotation Le := forgetEMBED.\n\n(**  * Models of untyped λ-calculi\n  *)\n\nDefinition eagerLamF : functor (EMBED true) (EMBED true)\n  := expF true ∘ pairF id id.\n\nDefinition cbvLamF : functor (EMBED true) (EMBED true)\n  := Le ∘ Ue ∘ expF true ∘ pairF id id.\n\nDefinition cbnLamF : functor (EMBED true) (EMBED true)\n  := Le ∘ expF false ∘ pairF id id ∘ Ue.\n\nLemma eagerLamF_continuous : continuous_functor eagerLamF.\nProof.\n  unfold eagerLamF.\n  apply composeF_continuous.\n  apply expF_continuous.\n  apply pairF_continuous.\n  apply identF_continuous.\n  apply identF_continuous.\nQed.\n\nLemma cbvLamF_continuous : continuous_functor cbvLamF.\nProof.\n  unfold cbvLamF.\n  apply composeF_continuous.\n  apply composeF_continuous.\n  apply composeF_continuous.\n  apply forgetEMBED_continuous.\n  apply liftEMBED_continuous.\n  apply expF_continuous.\n  apply pairF_continuous.\n  apply identF_continuous.\n  apply identF_continuous.\nQed.\n\nLemma cbnLamF_continuous : continuous_functor cbnLamF.\nProof.\n  unfold cbnLamF.\n  apply composeF_continuous.\n  apply composeF_continuous.\n  apply composeF_continuous.\n  apply forgetEMBED_continuous.\n  apply expF_continuous.\n  apply pairF_continuous.\n  apply identF_continuous.\n  apply identF_continuous.\n  apply liftEMBED_continuous.\nQed.\n\nDefinition lamModelEager : ∂PLT := fixpoint eagerLamF.\n\nDefinition lamModelCBV : ∂PLT := fixpoint cbvLamF.\n\nDefinition lamModelCBN : ∂PLT := fixpoint cbnLamF.\n\nLemma lamModelEager_iso :\n  ((lamModelEager ⊸ lamModelEager) : ob (EMBED true)) ↔ lamModelEager.\nProof.\n  apply (fixpoint_iso eagerLamF).\n  apply eagerLamF_continuous.\nQed.\n\nLemma lamModelCBV_iso :\n  (colift (lamModelCBV ⊸ lamModelCBV) : ob (EMBED true)) ↔ lamModelCBV.\nProof.\n  apply (fixpoint_iso cbvLamF).\n  apply cbvLamF_continuous.\nQed.\n\nLemma lamModelCBN_iso :\n  (L (U lamModelCBN ⇒ U lamModelCBN) : ob (EMBED true))  ↔ lamModelCBN.\nProof.\n  apply (fixpoint_iso cbnLamF).\n  apply cbnLamF_continuous.\nQed.\n\n\n(* We can also directly construct a model of lambdas in total PLT...\n     but this seems to be the trivial one-point model.\n\nProgram Definition lamModelIn : PLT.unit false ⇀ lamF false (PLT.unit false) :=\n  Embedding false (PLT.unit false) (lamF false (PLT.unit false)) \n    (fun x => exist _ ((tt,tt)::nil) _) _ _ _ _.\nNext Obligation.\n  repeat intro.\n  hnf. split. hnf; auto.\n  simpl. intros. exists tt.\n  destruct x0. split; auto.\n  apply cons_elem. auto.\n  hnf; simpl; intros.\n  hnf; auto.\nQed.\nNext Obligation.\n  hnf; simpl; intros.\n  red. hnf. simpl. intros.\n  exists tt. exists tt.\n  split.\n  apply cons_elem; auto.\n  split; hnf; auto.\nQed.\nNext Obligation.\n  repeat intro; hnf; auto.\nQed.\nNext Obligation.\n  intros. exists tt.\n  simpl. hnf; auto.\n  simpl; intros.\n  exists tt. exists tt.\n  split.\n  destruct y. simpl.\n  destruct i.\n  simpl in H1.\n  destruct (H1 x) with tt; auto.\n  hnf; auto.\n  split.\n  hnf. intros; hnf; auto.\n  intros; hnf; auto.\n  destruct H2. destruct x0; auto.\n  split; hnf; auto.\nQed.\nNext Obligation.\n  hnf; simpl. intros.\n  exists tt.\n  split; hnf; auto.\n  split; hnf; auto.\nQed.\n\nDefinition lamModelCBN : ob PLT\n  := fixpoint_alt (lamF false) (PLT.unit false) lamModelIn.\n\nLemma lamModelCBN_iso : (PLT.exp lamModelCBN lamModelCBN : ob (EMBED false)) ↔ lamModelCBN.\nProof.\n  apply (fixpoint_alt_iso (lamF false)).\n  apply lamF_continuous.\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/lam_models.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.26464447103678984}}
{"text": "Require config.\nRequire Import config_tactics.\n\nRequire Import syntax.\nRequire Import tt.\nRequire ett ptt ptt_sanity.\nRequire Import inversion.\n\nSection Ett2Ptt.\n\nContext `{configReflection : config.Reflection}.\nContext `{configBinaryProdType : config.BinaryProdType}.\nContext `{configProdEta : config.ProdEta}.\nContext `{configUniverses : config.Universes}.\nContext `{configPropType : config.PropType}.\nContext `{configIdType : config.IdType}.\nContext `{configIdEliminator : config.IdEliminator}.\nContext `{configEmptyType : config.EmptyType}.\nContext `{configUnitType : config.UnitType}.\nContext `{configBoolType : config.BoolType}.\nContext `{configProdType : config.ProdType}.\nContext `{configSyntax : syntax.Syntax}.\n\n(* We need inversion lemmata and we can't prove them since the syntax\n   is not necessarilly inductive and thus not necessarilly injective.\n\n   We want them for PTT.\n*)\nExisting Instance ptt.havePrecondition.\nContext {haveCtxExtendInversion : HaveCtxExtendInversion}.\nContext {haveTyIdInversion : HaveTyIdInversion}.\nContext {haveTyProdInversion : HaveTyProdInversion}.\nContext {haveTyBinaryProdInversion : HaveTyBinaryProdInversion}.\n\n(* Renaming ptt_sanity lemmata for readability. *)\nDefinition ptt_sane_issubst := ptt_sanity.sane_issubst.\nDefinition ptt_sane_istype  := ptt_sanity.sane_istype.\nDefinition ptt_sane_isterm  := ptt_sanity.sane_isterm.\nDefinition ptt_sane_eqctx   := ptt_sanity.sane_eqctx.\nDefinition ptt_sane_eqtype  := ptt_sanity.sane_eqtype.\nDefinition ptt_sane_eqsubst := ptt_sanity.sane_eqsubst.\nDefinition ptt_sane_eqterm  := ptt_sanity.sane_eqterm.\n\n\nFixpoint sane_isctx G (P : ett.isctx G) {struct P} : ptt.isctx G\n\nwith sane_issubst sbs G D (P : ett.issubst sbs G D) {struct P} : ptt.issubst sbs G D\n\nwith sane_istype G A (P : ett.istype G A) {struct P} : ptt.istype G A\n\nwith sane_isterm G u A (P : ett.isterm G u A) {struct P} : ptt.isterm G u A\n\nwith sane_eqctx G D (P : ett.eqctx G D) {struct P} : ptt.eqctx G D\n\nwith sane_eqsubst sbs sbt G D (P : ett.eqsubst sbs sbt G D) {struct P} : ptt.eqsubst sbs sbt G D\n\nwith sane_eqtype G A B (P : ett.eqtype G A B) {struct P} : ptt.eqtype G A B\n\nwith sane_eqterm G u v A (P : ett.eqterm G u v A) {struct P} : ptt.eqterm G u v A.\n\nProof.\n\n  (****** sane_isctx ******)\n  { destruct P ; doConfig.\n\n    (* CtxEmpty *)\n    - { capply CtxEmpty. }\n\n    (* CtxExtend *)\n    - {\n        intros ; capply CtxExtend.\n        + now apply (ptt_sane_istype G A), sane_istype.\n        + now apply sane_istype.\n      }\n  }\n\n  (****** sane_issubst ******)\n  { destruct P ; doConfig.\n\n    (* SubstZero *)\n    - { capply SubstZero.\n        + now apply sane_isterm.\n        + eapply ptt_sane_isterm.\n          eapply sane_isterm ; eassumption.\n        + eapply ptt_sane_isterm.\n          eapply sane_isterm ; eassumption.\n      }\n\n    (* SubstWeak *)\n    - {\n        capply SubstWeak.\n        + now apply sane_istype.\n        + eapply ptt_sane_istype.\n          eapply sane_istype ; eassumption.\n      }\n\n    (* SubstShift. *)\n    - {\n        capply SubstShift.\n        + now apply sane_issubst.\n        + now apply sane_istype.\n        + eapply (ptt_sane_issubst sbs G D).\n          now apply sane_issubst.\n        + eapply (ptt_sane_istype D A).\n          now apply sane_istype.\n      }\n\n     (* SubstId *)\n     - {\n         capply SubstId.\n         - now apply sane_isctx.\n       }\n\n     (* SubstComp *)\n     - {\n         config apply @SubstComp with (D := D).\n         - now apply sane_issubst.\n         - now apply sane_issubst.\n         - apply (ptt_sane_issubst sbs G D).\n           now apply sane_issubst.\n         - apply (ptt_sane_issubst sbt D E).\n           now apply sane_issubst.\n         - apply (ptt_sane_issubst sbt D E).\n           now apply sane_issubst.\n       }\n\n     (* SubstTerminal *)\n     - { capply SubstTerminal.\n         now apply sane_isctx.\n       }\n\n     (* SubstCtxConv *)\n     - {\n         config apply @SubstCtxConv with (G1 := G1) (D1 := D1).\n         - now apply sane_issubst.\n         - now apply sane_eqctx.\n         - now apply sane_eqctx.\n         - apply (ptt_sane_eqctx G1 G2).\n           now apply sane_eqctx.\n         - apply (ptt_sane_eqctx G1 G2).\n           now apply sane_eqctx.\n         - apply (ptt_sane_eqctx D1 D2).\n           now apply sane_eqctx.\n         - apply (ptt_sane_eqctx D1 D2).\n           now apply sane_eqctx.\n       }\n  }\n\n  (****** sane_istype ******)\n  { destruct P.\n\n    (* TyCtxConv *)\n    { config apply @TyCtxConv with (G := G).\n      - now apply sane_istype.\n      - now apply sane_eqctx.\n      - now apply (ptt_sane_eqctx G D), sane_eqctx.\n      - now apply (ptt_sane_eqctx G D), sane_eqctx.\n    }\n\n    (* TySubst *)\n    { config apply @TySubst with (D := D).\n      - now apply sane_issubst.\n      - now apply sane_istype.\n      - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n      - now apply (ptt_sane_istype D A), sane_istype.\n    }\n\n    (* TyProd *)\n    { capply TyProd.\n      - now apply sane_istype.\n      - now apply (CtxExtendInversion G A),\n                  (ptt_sane_istype _ B), sane_istype.\n      - now apply (CtxExtendInversion G A),\n                  (ptt_sane_istype _ B), sane_istype.\n    }\n\n    (* TyId *)\n    { capply TyId.\n      - now apply (ptt_sane_isterm G u A), sane_isterm.\n      - now apply (ptt_sane_isterm G u A), sane_isterm.\n      - now apply sane_isterm.\n      - now apply sane_isterm.\n    }\n\n    (* TyEmpty *)\n    { capply TyEmpty.\n      - now apply sane_isctx.\n    }\n\n    (* TyUnit *)\n    { capply TyUnit.\n      - now apply sane_isctx.\n    }\n\n    (* TyBool *)\n    { capply TyBool.\n      - now apply sane_isctx.\n    }\n\n    (* TyBinaryProd *)\n    { capply TyBinaryProd.\n      - now apply (ptt_sane_istype G A), sane_istype.\n      - now apply sane_istype.\n      - now apply sane_istype.\n    }\n\n    (* TyUni *)\n    { capply TyUni.\n      now apply sane_isctx.\n    }\n\n    (* TyEl *)\n    { capply TyEl.\n      - now apply sane_isterm.\n      - now apply (ptt_sane_isterm G a (Uni l)), sane_isterm.\n    }\n  }\n\n  (****** sane_isterm ******)\n  { destruct P.\n\n    (* TermTyConv *)\n    - { config apply @TermTyConv with (A := A).\n        - now apply sane_isterm.\n        - now apply sane_eqtype.\n        - now apply (@ptt_sane_isterm G u A), sane_isterm.\n        - now apply (@ptt_sane_isterm G u A), sane_isterm.\n        - now apply (@ptt_sane_eqtype G A B), sane_eqtype.\n      }\n\n    (* TermCtxConv *)\n    - { config apply @TermCtxConv with (G := G).\n        - now apply sane_isterm.\n        - now apply sane_eqctx.\n        - now apply (@ptt_sane_isterm G u A), sane_isterm.\n        - now apply (@ptt_sane_eqctx G D), sane_eqctx.\n        - now apply (@ptt_sane_isterm G u A), sane_isterm.\n      }\n\n    (* TermSubst *)\n    - { config apply @TermSubst with (D := D).\n        - now apply sane_issubst.\n        - now apply sane_isterm.\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (@ptt_sane_isterm D u A), sane_isterm.\n        - now apply (@ptt_sane_isterm D u A), sane_isterm.\n      }\n\n    (* TermVarZero *)\n    - { capply TermVarZero.\n        - now apply (@ptt_sane_istype G A), sane_istype.\n        - now apply sane_istype.\n      }\n\n    (* TermVarSucc *)\n    - { capply TermVarSucc.\n        - now apply (@ptt_sane_istype G B), sane_istype.\n        - now apply (@ptt_sane_isterm G (var k)A), sane_isterm.\n        - now apply sane_isterm.\n        - now apply sane_istype.\n      }\n\n    (* TermAbs *)\n    - { capply TermAbs.\n        - now apply (CtxExtendInversion G A),\n                    (ptt_sane_isterm _ u B), sane_isterm.\n        - now apply (CtxExtendInversion G A),\n                    (ptt_sane_isterm _ u B), sane_isterm.\n        - now apply (@ptt_sane_isterm (ctxextend G A) u B), sane_isterm.\n        - now apply sane_isterm.\n      }\n\n    (* TermApp *)\n    - { capply TermApp.\n        - now apply (@ptt_sane_isterm G v A), sane_isterm.\n        - now apply (@ptt_sane_isterm G v A), sane_isterm.\n        - now apply (TyProdInversion G A B),\n                    (ptt_sane_isterm G u (Prod A B)),\n                    sane_isterm.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n      }\n\n    (* TermRefl *)\n    - { capply TermRefl.\n        - now apply (ptt_sane_isterm G u A), sane_isterm.\n        - now apply (ptt_sane_isterm G u A), sane_isterm.\n        - now apply sane_isterm.\n      }\n\n    (* TermJ *)\n    - { capply TermJ.\n        - now apply (ptt_sane_isterm G u A), sane_isterm.\n        - now apply (ptt_sane_isterm G u A), sane_isterm.\n        - now apply sane_isterm.\n        - now apply sane_istype.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n      }\n\n    (* TermExfalso *)\n    - { capply TermExfalso.\n        - now apply (@ptt_sane_istype G A), sane_istype.\n        - now apply sane_istype.\n        - now apply sane_isterm.\n      }\n\n    (* TermUnit *)\n    - { capply TermUnit.\n        - now apply sane_isctx.\n      }\n\n    (* TermTrue *)\n    - { capply TermTrue.\n        - now apply sane_isctx.\n      }\n\n    (* TermFalse *)\n    - { capply TermFalse.\n        - now apply sane_isctx.\n      }\n\n    (* TermCond *)\n    - { capply TermCond.\n        - now apply (@ptt_sane_isterm G u Bool), sane_isterm.\n        - now apply sane_isterm.\n        - now apply sane_istype.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n      }\n\n    (* TermPair *)\n    - { capply TermPair.\n        - now apply (ptt_sane_isterm G u A), sane_isterm.\n        - now apply (ptt_sane_isterm G u A), sane_isterm.\n        - now apply (ptt_sane_isterm G v B), sane_isterm.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n      }\n\n    (* TermProjOne *)\n    - { capply TermProjOne.\n        - now apply (ptt_sane_isterm G p (BinaryProd A B)), sane_isterm.\n        - now apply (TyBinaryProdInversion G A B),\n                    (ptt_sane_isterm G p (BinaryProd A B)),\n                    sane_isterm.\n        - now apply (TyBinaryProdInversion G A B),\n                    (ptt_sane_isterm G p (BinaryProd A B)),\n                    sane_isterm.\n        - now apply sane_isterm.\n      }\n\n    (* TermProjTwo *)\n    - { capply TermProjTwo.\n        - now apply (ptt_sane_isterm G p (BinaryProd A B)), sane_isterm.\n        - now apply (TyBinaryProdInversion G A B),\n                    (ptt_sane_isterm G p (BinaryProd A B)),\n                    sane_isterm.\n        - now apply (TyBinaryProdInversion G A B),\n                    (ptt_sane_isterm G p (BinaryProd A B)),\n                    sane_isterm.\n        - now apply sane_isterm.\n      }\n\n    (* TermUniProd *)\n    - { capply TermUniProd.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n        - now apply (ptt_sane_isterm G a (Uni (uni n))), sane_isterm.\n      }\n\n    (* TermUniProdProp *)\n    - { capply TermUniProdProp.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n        - now apply (ptt_sane_isterm G a (Uni l)), sane_isterm.\n      }\n\n    (* TermUniId *)\n    - { capply TermUniId.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n        - now apply (ptt_sane_isterm G a (Uni n)), sane_isterm.\n      }\n\n    (* TermUniEmpty *)\n    - { capply TermUniEmpty.\n        now apply sane_isctx.\n      }\n\n    (* TermUniUnit *)\n    - { capply TermUniUnit.\n        now apply sane_isctx.\n      }\n\n    (* TermUniBool *)\n    - { capply TermUniBool.\n        now apply sane_isctx.\n      }\n\n    (* TermUniBinaryProd *)\n    - { capply TermUniBinaryProd.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n        - now apply (ptt_sane_isterm G a (Uni (uni n))), sane_isterm.\n      }\n\n    (* TermUniBinaryProdProp *)\n    - { capply TermUniBinaryProdProp.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n        - now apply (ptt_sane_isterm G a (Uni prop)), sane_isterm.\n      }\n\n    (* TermUniUni *)\n    - { capply TermUniUni.\n        now apply sane_isctx.\n      }\n\n    (* TermUniProp *)\n    - { capply TermUniProp.\n        now apply sane_isctx.\n      }\n  }\n\n  (****** sane_eqctx ******)\n  { destruct P.\n\n    (* CtxRefl *)\n    - { capply CtxRefl.\n        - now apply sane_isctx.\n      }\n\n    (* CtxSym *)\n    - { capply CtxSym.\n        - now apply sane_eqctx.\n        - now apply (@ptt_sane_eqctx G D), sane_eqctx.\n        - now apply (@ptt_sane_eqctx G D), sane_eqctx.\n      }\n\n    (* CtxTrans *)\n    - { config apply @CtxTrans with (D := D).\n        - now apply (@ptt_sane_eqctx G D), sane_eqctx.\n        - now apply (@ptt_sane_eqctx G D), sane_eqctx.\n        - now apply (@ptt_sane_eqctx D E), sane_eqctx.\n        - now apply sane_eqctx.\n        - now apply sane_eqctx.\n      }\n\n    (* EqCtxEmpty *)\n    - { capply EqCtxEmpty.\n      }\n\n    (* EqCtxExtend *)\n    - { capply EqCtxExtend.\n        - now apply (@ptt_sane_eqctx G D), sane_eqctx.\n        - now apply (@ptt_sane_eqctx G D), sane_eqctx.\n        - now apply (@ptt_sane_eqtype G A B), sane_eqtype.\n        - now apply (@ptt_sane_eqtype G A B), sane_eqtype.\n        - now apply sane_eqctx.\n        - now apply sane_eqtype.\n      }\n  }\n\n  (****** sane_eqsubst ******)\n  { destruct P.\n\n    (* SubstRefl *)\n    - { capply SubstRefl.\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply sane_issubst.\n      }\n\n    (* SubstSym *)\n    - { capply SubstSym.\n        - now apply sane_eqsubst.\n        - now apply (@ptt_sane_eqsubst sbs sbt G D), sane_eqsubst.\n        - now apply (@ptt_sane_eqsubst sbs sbt G D), sane_eqsubst.\n        - now apply (@ptt_sane_eqsubst sbs sbt G D), sane_eqsubst.\n        - now apply (@ptt_sane_eqsubst sbs sbt G D), sane_eqsubst.\n      }\n\n    (* SubstTrans *)\n    - { config apply @SubstTrans with (sb2 := sb2).\n        - now apply sane_eqsubst.\n        - now apply sane_eqsubst.\n        - now apply (@ptt_sane_eqsubst sb1 sb2 G D), sane_eqsubst.\n        - now apply (@ptt_sane_eqsubst sb1 sb2 G D), sane_eqsubst.\n        - now apply (@ptt_sane_eqsubst sb2 sb3 G D), sane_eqsubst.\n        - now apply (@ptt_sane_eqsubst sb1 sb2 G D), sane_eqsubst.\n        - now apply (@ptt_sane_eqsubst sb1 sb2 G D), sane_eqsubst.\n      }\n\n    (* CongSubstZero *)\n    - { config apply @CongSubstZero with (G := G).\n        - now apply sane_eqtype.\n        - now apply sane_eqterm.\n        - now apply (@ptt_sane_eqtype G A1 A2), sane_eqtype.\n        - now apply (@ptt_sane_eqtype G A1 A2), sane_eqtype.\n        - now apply (@ptt_sane_eqtype G A1 A2), sane_eqtype.\n        - now apply (@ptt_sane_eqterm G u1 u2 A1), sane_eqterm.\n        - now apply (@ptt_sane_eqterm G u1 u2 A1), sane_eqterm.\n      }\n\n    (* CongSubstWeak *)\n    - { capply CongSubstWeak.\n        - now apply sane_eqtype.\n        - now apply (@ptt_sane_eqtype G A1 A2), sane_eqtype.\n        - now apply (@ptt_sane_eqtype G A1 A2), sane_eqtype.\n        - now apply (@ptt_sane_eqtype G A1 A2), sane_eqtype.\n      }\n\n    (* CongSubstShift *)\n    - { capply CongSubstShift.\n        - now apply sane_eqsubst.\n        - now apply sane_eqtype.\n        - now apply (@ptt_sane_eqsubst sbs1 sbs2 G D), sane_eqsubst.\n        - now apply (@ptt_sane_eqtype D A1 A2), sane_eqtype.\n        - now apply (@ptt_sane_eqtype D A1 A2), sane_eqtype.\n        - now apply (@ptt_sane_eqtype D A1 A2), sane_eqtype.\n        - now apply (@ptt_sane_eqsubst sbs1 sbs2 G D), sane_eqsubst.\n        - now apply (@ptt_sane_eqsubst sbs1 sbs2 G D), sane_eqsubst.\n      }\n\n    (* CongSubstComp *)\n    - { config apply @CongSubstComp with (D := D).\n        - now apply sane_eqsubst.\n        - now apply sane_eqsubst.\n        - now apply (@ptt_sane_eqsubst sbs1 sbs2 G D), sane_eqsubst.\n        - now apply (@ptt_sane_eqsubst sbs1 sbs2 G D), sane_eqsubst.\n        - now apply (@ptt_sane_eqsubst sbt1 sbt2 D E), sane_eqsubst.\n        - now apply (@ptt_sane_eqsubst sbt1 sbt2 D E), sane_eqsubst.\n        - now apply (@ptt_sane_eqsubst sbs1 sbs2 G D), sane_eqsubst.\n        - now apply (@ptt_sane_eqsubst sbs1 sbs2 G D), sane_eqsubst.\n        - now apply (@ptt_sane_eqsubst sbt1 sbt2 D E), sane_eqsubst.\n      }\n\n    (* EqSubstCtxConv *)\n    - { config apply @EqSubstCtxConv with (G1 := G1) (D1 := D1).\n        - now apply sane_eqsubst.\n        - now apply sane_eqctx.\n        - now apply sane_eqctx.\n        - now apply (@ptt_sane_eqctx G1 G2), sane_eqctx.\n        - now apply (@ptt_sane_eqctx G1 G2), sane_eqctx.\n        - now apply (@ptt_sane_eqctx D1 D2), sane_eqctx.\n        - now apply (@ptt_sane_eqctx D1 D2), sane_eqctx.\n        - now apply (@ptt_sane_eqsubst sbs sbt G1 D1), sane_eqsubst.\n        - now apply (@ptt_sane_eqsubst sbs sbt G1 D1), sane_eqsubst.\n      }\n\n    (* CompAssoc *)\n    - { config apply @CompAssoc with (D := D) (E := E).\n        - now apply sane_issubst.\n        - now apply sane_issubst.\n        - now apply sane_issubst.\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (@ptt_sane_issubst sbr E F), sane_issubst.\n        - now apply (@ptt_sane_issubst sbr E F), sane_issubst.\n      }\n\n    (* WeakNat *)\n    - { capply WeakNat.\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply sane_issubst.\n        - now apply sane_istype.\n      }\n\n    (* WeakZero *)\n    - { capply WeakZero.\n        - now apply (@ptt_sane_isterm G u A), sane_isterm.\n        - now apply (@ptt_sane_isterm G u A), sane_isterm.\n        - now apply sane_isterm.\n      }\n\n    (* ShiftZero *)\n    - { capply ShiftZero.\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (@ptt_sane_isterm D u A), sane_isterm.\n        - now apply sane_issubst.\n        - now apply sane_isterm.\n      }\n\n    (* CompShift *)\n    - { config apply @CompShift with (D := D).\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (@ptt_sane_istype E A), sane_istype.\n        - now apply sane_issubst.\n        - now apply sane_issubst.\n        - now apply sane_istype.\n      }\n\n    (* CompIdRight *)\n    - { capply CompIdRight.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply sane_issubst.\n      }\n\n    (* CompIdLeft *)\n    - { capply CompIdLeft.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply sane_issubst.\n      }\n  }\n\n\n  (****** sane_eqtype ******)\n  { destruct P.\n\n    (* EqTyCtxConv *)\n    { config apply @EqTyCtxConv with (G := G).\n      - now apply sane_eqtype.\n      - now apply sane_eqctx.\n      - now apply (ptt_sane_eqtype G A B), sane_eqtype.\n      - now apply (ptt_sane_eqtype G A B), sane_eqtype.\n      - now apply (ptt_sane_eqctx G D), sane_eqctx.\n      - now apply (ptt_sane_eqctx G D), sane_eqctx.\n    }\n\n    (* EqTyRefl *)\n    { capply EqTyRefl.\n      - now apply (ptt_sane_istype G A), sane_istype.\n      - now apply sane_istype.\n    }\n\n    (* EqTySym *)\n    { capply EqTySym.\n      - now apply sane_eqtype.\n      - now apply (ptt_sane_eqtype G A B), sane_eqtype.\n      - now apply (ptt_sane_eqtype G A B), sane_eqtype.\n      - now apply (ptt_sane_eqtype G A B), sane_eqtype.\n    }\n\n    (* EqTyTrans *)\n    { config apply @EqTyTrans with (B := B).\n      - now apply sane_eqtype.\n      - now apply sane_eqtype.\n      - now apply (ptt_sane_eqtype G A B), sane_eqtype.\n      - now apply (ptt_sane_eqtype G A B), sane_eqtype.\n      - now apply (ptt_sane_eqtype G A B), sane_eqtype.\n      - now apply (ptt_sane_eqtype G B C), sane_eqtype.\n    }\n\n    (* EqTyIdSubst *)\n    { capply EqTyIdSubst.\n      - now apply (ptt_sane_istype G A), sane_istype.\n      - now apply sane_istype.\n    }\n\n    (* EqTySubstComp *)\n    { config apply @EqTySubstComp with (D := D) (E := E).\n      - now apply sane_istype.\n      - now apply sane_issubst.\n      - now apply sane_issubst.\n      - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n      - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n      - now apply (@ptt_sane_issubst sbt D E), sane_issubst.\n    }\n\n    (* EqTySubstProd *)\n    { config apply @EqTySubstProd with (D := D).\n      - now apply sane_issubst.\n      - now apply (CtxExtendInversion D A),\n            (ptt_sane_istype _ B), sane_istype.\n      - now apply sane_istype.\n      - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n      - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n    }\n\n    (* EqTySubstId *)\n    { config apply @EqTySubstId with (D := D).\n      - now apply sane_issubst.\n      - now apply (@ptt_sane_isterm D u A), sane_isterm.\n      - now apply sane_isterm.\n      - now apply sane_isterm.\n      - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n      - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n    }\n\n    (* EqTySubstEmpty *)\n    { config apply @EqTySubstEmpty with (D := D).\n      - now apply sane_issubst.\n      - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n      - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n    }\n\n    (* EqTySubstUnit *)\n    { config apply @EqTySubstUnit with (D := D).\n      - now apply sane_issubst.\n      - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n      - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n    }\n\n    (* EqTySubstBool *)\n    { config apply @EqTySubstBool with (D := D).\n      - now apply sane_issubst.\n      - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n      - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n    }\n\n    (* EqTyExfalso *)\n    { config apply @EqTyExfalso with (u := u).\n      - now apply (@ptt_sane_istype G A), sane_istype.\n      - now apply sane_istype.\n      - now apply sane_istype.\n      - now apply sane_isterm.\n    }\n\n    (* CongProd *)\n    { capply CongProd.\n      - now apply (@ptt_sane_eqtype G A1 B1), sane_eqtype.\n      - now apply (@ptt_sane_eqtype G A1 B1), sane_eqtype.\n      - now apply (@ptt_sane_eqtype (ctxextend G A1) A2 B2), sane_eqtype.\n      - now apply (@ptt_sane_eqtype G A1 B1), sane_eqtype.\n      - now apply (@ptt_sane_eqtype (ctxextend G A1) A2 B2), sane_eqtype.\n      - now apply sane_eqtype.\n      - now apply sane_eqtype.\n    }\n\n    (* CongId *)\n    { capply CongId.\n      - now apply (@ptt_sane_eqtype G A B), sane_eqtype.\n      - now apply (@ptt_sane_eqtype G A B), sane_eqtype.\n      - now apply (@ptt_sane_eqtype G A B), sane_eqtype.\n      - now apply (@ptt_sane_eqterm G u1 v1 A), sane_eqterm.\n      - now apply (@ptt_sane_eqterm G u2 v2 A), sane_eqterm.\n      - now apply (@ptt_sane_eqterm G u1 v1 A), sane_eqterm.\n      - now apply (@ptt_sane_eqterm G u2 v2 A), sane_eqterm.\n      - now apply sane_eqtype.\n      - now apply sane_eqterm.\n      - now apply sane_eqterm.\n    }\n\n    (* CongTySubst *)\n    { config apply @CongTySubst with (D := D).\n      - now apply sane_eqsubst.\n      - now apply sane_eqtype.\n      - now apply (@ptt_sane_eqsubst sbs sbt G D), sane_eqsubst.\n      - now apply (@ptt_sane_eqsubst sbs sbt G D), sane_eqsubst.\n      - now apply (@ptt_sane_eqtype D A B), sane_eqtype.\n      - now apply (@ptt_sane_eqtype D A B), sane_eqtype.\n      - now apply (@ptt_sane_eqsubst sbs sbt G D), sane_eqsubst.\n      - now apply (@ptt_sane_eqsubst sbs sbt G D), sane_eqsubst.\n    }\n\n    (* CongBinaryProd *)\n    { capply CongBinaryProd.\n      - now apply (ptt_sane_eqtype G A1 A2), sane_eqtype.\n      - now apply (ptt_sane_eqtype G A1 A2), sane_eqtype.\n      - now apply (ptt_sane_eqtype G A1 A2), sane_eqtype.\n      - now apply (ptt_sane_eqtype G B1 B2), sane_eqtype.\n      - now apply (ptt_sane_eqtype G B1 B2), sane_eqtype.\n      - now apply sane_eqtype.\n      - now apply sane_eqtype.\n    }\n\n    (* EqTySubstBinaryProd *)\n    { config apply @EqTySubstBinaryProd with (D := D).\n      - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n      - now apply (ptt_sane_istype D A), sane_istype.\n      - now apply sane_issubst.\n      - now apply sane_istype.\n      - now apply sane_istype.\n    }\n\n    (* EqTySubstUni *)\n    { config apply @EqTySubstUni with (D := D).\n      - now apply sane_issubst.\n      - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n      - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n    }\n\n    (* ElProd *)\n    { config apply @ElProd.\n      - now apply sane_isterm.\n      - now apply sane_isterm.\n      - now apply (ptt_sane_isterm G a (Uni (uni n))), sane_isterm.\n    }\n\n    (* ElProdProp *)\n    { config apply @ElProdProp.\n      - now apply sane_isterm.\n      - now apply sane_isterm.\n      - now apply (ptt_sane_isterm G a (Uni l)), sane_isterm.\n    }\n\n    (* ElId *)\n    { config apply @ElId.\n      - now apply sane_isterm.\n      - now apply sane_isterm.\n      - now apply sane_isterm.\n      - now apply (ptt_sane_isterm G a (Uni n)), sane_isterm.\n    }\n\n    (* ElSubst *)\n    { config apply @ElSubst with (D := D) (n := n).\n      - now apply sane_issubst.\n      - now apply sane_isterm.\n      - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n      - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n    }\n\n    (* ElEmpty *)\n    { capply ElEmpty.\n      now apply sane_isctx.\n    }\n\n    (* ElUnit *)\n    { capply ElUnit.\n      now apply sane_isctx.\n    }\n\n    (* ElBool *)\n    { capply ElBool.\n      now apply sane_isctx.\n    }\n\n    (* ElBinaryProd *)\n    { config apply @ElBinaryProd.\n      - now apply sane_isterm.\n      - now apply sane_isterm.\n      - now apply (ptt_sane_isterm G a (Uni (uni n))), sane_isterm.\n    }\n\n    (* ElBinaryProdProp *)\n    { config apply @ElBinaryProdProp.\n      - now apply sane_isterm.\n      - now apply sane_isterm.\n      - now apply (ptt_sane_isterm G a (Uni prop)), sane_isterm.\n    }\n\n    (* ElUni *)\n    { config apply @ElUni with (n := n).\n      now apply sane_isctx.\n    }\n\n    (* ElProp *)\n    { config apply @ElProp.\n      now apply sane_isctx.\n    }\n\n    (* CongEl *)\n    { config apply @CongEl with (n := n).\n      - now apply sane_eqterm.\n      - now apply (ptt_sane_eqterm G a b (Uni n)), sane_eqterm.\n      - now apply (ptt_sane_eqterm G a b (Uni n)), sane_eqterm.\n      - now apply (ptt_sane_eqterm G a b (Uni n)), sane_eqterm.\n    }\n\n  }\n\n  (****** sane_eqterm ******)\n  { destruct P.\n\n    (* EqTyConv *)\n    - { config apply @EqTyConv with (A := A).\n        - now apply sane_eqterm.\n        - now apply sane_eqtype.\n        - now apply (@ptt_sane_eqtype G A B), sane_eqtype.\n        - now apply (@ptt_sane_eqtype G A B), sane_eqtype.\n        - now apply (@ptt_sane_eqtype G A B), sane_eqtype.\n        - now apply (@ptt_sane_eqterm G u v A), sane_eqterm.\n        - now apply (@ptt_sane_eqterm G u v A), sane_eqterm.\n    }\n\n    (* EqCtxConv *)\n    - { config apply @EqCtxConv with (G := G).\n        - now apply (@ptt_sane_eqctx G D), sane_eqctx.\n        - now apply (@ptt_sane_eqctx G D), sane_eqctx.\n        - now apply (@ptt_sane_eqterm G u v A), sane_eqterm.\n        - now apply (@ptt_sane_eqterm G u v A), sane_eqterm.\n        - now apply (@ptt_sane_eqterm G u v A), sane_eqterm.\n        - now apply sane_eqterm.\n        - now apply sane_eqctx.\n      }\n\n    (* EqRefl *)\n    - { capply EqRefl.\n        - now apply (@ptt_sane_isterm G u A), sane_isterm.\n        - now apply (@ptt_sane_isterm G u A), sane_isterm.\n        - now apply sane_isterm.\n      }\n\n    (* EqSym *)\n    - { capply EqSym.\n        - now apply sane_eqterm.\n        - now apply (@ptt_sane_eqterm G v u A), sane_eqterm.\n        - now apply (@ptt_sane_eqterm G v u A), sane_eqterm.\n        - now apply (@ptt_sane_eqterm G v u A), sane_eqterm.\n        - now apply (@ptt_sane_eqterm G v u A), sane_eqterm.\n      }\n\n    (* EqTrans *)\n    - { config apply @EqTrans with (v := v).\n        - now apply sane_eqterm.\n        - now apply sane_eqterm.\n        - now apply (@ptt_sane_eqterm G u v A), sane_eqterm.\n        - now apply (@ptt_sane_eqterm G u v A), sane_eqterm.\n        - now apply (@ptt_sane_eqterm G u v A), sane_eqterm.\n        - now apply (@ptt_sane_eqterm G u v A), sane_eqterm.\n        - now apply (@ptt_sane_eqterm G v w A), sane_eqterm.\n      }\n\n    (* EqIdSubst *)\n    - { capply EqIdSubst.\n        - now apply (@ptt_sane_isterm G u A), sane_isterm.\n        - now apply (@ptt_sane_isterm G u A), sane_isterm.\n        - now apply sane_isterm.\n      }\n\n    (* EqSubstComp *)\n    - { config apply @EqSubstComp with (D := D) (E := E).\n        - now apply sane_isterm.\n        - now apply sane_issubst.\n        - now apply sane_issubst.\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (@ptt_sane_issubst sbt D E), sane_issubst.\n        - now apply (@ptt_sane_isterm E u A), sane_isterm.\n      }\n\n    (* EqSubstWeak *)\n    - { capply EqSubstWeak.\n        - now apply (@ptt_sane_istype G B), sane_istype.\n        - now apply (@ptt_sane_isterm G (var k) A), sane_isterm.\n        - now apply sane_isterm.\n        - now apply sane_istype.\n      }\n\n    (* EqSubstZeroZero *)\n    - { capply EqSubstZeroZero.\n        - now apply (@ptt_sane_isterm G u A), sane_isterm.\n        - now apply (@ptt_sane_isterm G u A), sane_isterm.\n        - now apply sane_isterm.\n      }\n\n    (* EqSubstZeroSucc *)\n    - { capply EqSubstZeroSucc.\n        - now apply (@ptt_sane_isterm G u B), sane_isterm.\n        - now apply (@ptt_sane_isterm G (var k) A), sane_isterm.\n        - now apply (@ptt_sane_isterm G u B), sane_isterm.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n      }\n\n    (* EqSubstShiftZero *)\n    - { config apply @EqSubstShiftZero with (D := D).\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply sane_issubst.\n        - now apply sane_istype.\n      }\n\n    (* EqSubstShiftSucc *)\n    - { config apply @EqSubstShiftSucc with (D := D).\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (@ptt_sane_isterm D (var k) B), sane_isterm.\n        - now apply sane_issubst.\n        - now apply sane_isterm.\n        - now apply sane_istype.\n      }\n\n    (* EqSubstAbs *)\n    - { config apply @EqSubstAbs with (D := D).\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (CtxExtendInversion D A),\n                    (ptt_sane_isterm _ u B),\n                    sane_isterm.\n        - now apply (@ptt_sane_isterm (ctxextend D A) u B), sane_isterm.\n        - now apply sane_isterm.\n        - now apply sane_issubst.\n      }\n\n    (* EqSubstApp *)\n    - { config apply @EqSubstApp with (D := D).\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (@ptt_sane_isterm D v A), sane_isterm.\n        - now apply (TyProdInversion D A B),\n                    (ptt_sane_isterm D u _),\n                    sane_isterm.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n        - now apply sane_issubst.\n      }\n\n    (* EqSubstRefl *)\n    - { config apply @EqSubstRefl with (D := D).\n        - now apply sane_issubst.\n        - now apply sane_isterm.\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (@ptt_sane_isterm D u A), sane_isterm.\n      }\n\n    (* EqSubstJ *)\n    - { config apply @EqSubstJ with (D := D).\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (@ptt_sane_isterm D v A), sane_isterm.\n        - now apply sane_issubst.\n        - now apply sane_isterm.\n        - now apply sane_istype.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n      }\n\n    (* EqSubstExfalso *)\n    - { config apply @EqSubstExfalso with (D := D).\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply sane_istype.\n        - now apply sane_isterm.\n        - now apply sane_issubst.\n      }\n\n    (* EqSubstUnit *)\n    - { config apply @EqSubstUnit with (D := D).\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply sane_issubst.\n      }\n\n    (* EqSubstTrue *)\n    - { config apply @EqSubstTrue with (D := D).\n        - now apply sane_issubst.\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n      }\n\n    (* EqSubstFalse *)\n    - { config apply @EqSubstFalse with (D := D).\n        - now apply sane_issubst.\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n      }\n\n    (* EqSubstCond *)\n    - { config apply @EqSubstCond with (D := D).\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (@ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply sane_issubst.\n        - now apply sane_isterm.\n        - now apply sane_istype.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n      }\n\n    (* EqTermExfalso *)\n    - { config apply @EqTermExfalso with (w := w).\n        - now apply (ptt_sane_isterm G u A), sane_isterm.\n        - now apply (ptt_sane_isterm G u A), sane_isterm.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n      }\n\n    (* UnitEta *)\n    - { capply UnitEta.\n        - now apply (@ptt_sane_isterm G u Unit), sane_isterm.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n      }\n\n    (* EqReflection *)\n    - { config apply @EqReflection with (p := p).\n        - now apply (@ptt_sane_isterm G p (Id A u v)), sane_isterm.\n        - now apply (TyIdInversion G A u v),\n                    (ptt_sane_isterm G p (Id A u v)),\n                    sane_isterm.\n        - now apply (TyIdInversion G A u v),\n                    (ptt_sane_isterm G p (Id A u v)),\n                    sane_isterm.\n        - now apply (TyIdInversion G A u v),\n                    (ptt_sane_isterm G p (Id A u v)),\n                    sane_isterm.\n        - now apply sane_isterm.\n      }\n\n    (* ProdBeta *)\n    - { capply ProdBeta.\n        - now apply (@ptt_sane_isterm G v A), sane_isterm.\n        - now apply (@ptt_sane_isterm G v A), sane_isterm.\n        - now apply (@ptt_sane_isterm (ctxextend G A) u B), sane_isterm.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n      }\n\n    (* CondTrue *)\n    - { capply CondTrue.\n        - now apply (@ptt_sane_isterm G v (Subst C (sbzero Bool true))), sane_isterm.\n        - now apply sane_istype.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n      }\n\n    (* CondFalse *)\n    - { capply CondFalse.\n        - now apply (@ptt_sane_isterm G v (Subst C (sbzero Bool true))), sane_isterm.\n        - now apply sane_istype.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n      }\n\n    (* ProdEta *)\n    - { capply ProdEta.\n        - now apply (@ptt_sane_isterm G u (Prod A B)), sane_isterm.\n        - now apply (TyProdInversion G A B),\n                    (ptt_sane_isterm G u (Prod A B)),\n                    sane_isterm.\n        - now apply (TyProdInversion G A B),\n                    (ptt_sane_isterm G u (Prod A B)),\n                    sane_isterm.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n        - now apply sane_eqterm.\n      }\n\n    (* JRefl *)\n    - { capply JRefl.\n        - now apply (ptt_sane_isterm G u A), sane_isterm.\n        - now apply (ptt_sane_isterm G u A), sane_isterm.\n        - now apply sane_isterm.\n        - now apply sane_istype.\n        - now apply sane_isterm.\n      }\n\n    (* CongAbs *)\n    - { capply CongAbs.\n        - now apply (ptt_sane_eqtype G A1 B1), sane_eqtype.\n        - now apply (ptt_sane_eqtype G A1 B1), sane_eqtype.\n        - now apply (ptt_sane_eqtype G A1 B1), sane_eqtype.\n        - now apply (ptt_sane_eqtype (ctxextend G A1) A2 B2), sane_eqtype.\n        - now apply (ptt_sane_eqtype (ctxextend G A1) A2 B2), sane_eqtype.\n        - now apply (ptt_sane_eqterm (ctxextend G A1) u1 u2 A2), sane_eqterm.\n        - now apply (ptt_sane_eqterm (ctxextend G A1) u1 u2 A2), sane_eqterm.\n        - now apply sane_eqtype.\n        - now apply sane_eqtype.\n        - now apply sane_eqterm.\n      }\n\n    (* CongApp *)\n    - { capply CongApp.\n        - now apply (ptt_sane_eqtype G A1 B1), sane_eqtype.\n        - now apply (ptt_sane_eqtype G A1 B1), sane_eqtype.\n        - now apply (ptt_sane_eqtype (ctxextend G A1) A2 B2), sane_eqtype.\n        - now apply (ptt_sane_eqtype G A1 B1), sane_eqtype.\n        - now apply (ptt_sane_eqtype (ctxextend G A1) A2 B2), sane_eqtype.\n        - now apply (ptt_sane_eqterm G u1 v1 (Prod A1 A2)), sane_eqterm.\n        - now apply (ptt_sane_eqterm G u1 v1 (Prod A1 A2)), sane_eqterm.\n        - now apply (ptt_sane_eqterm G u2 v2 A1), sane_eqterm.\n        - now apply (ptt_sane_eqterm G u2 v2 A1), sane_eqterm.\n        - now apply sane_eqtype.\n        - now apply sane_eqtype.\n        - now apply sane_eqterm.\n        - now apply sane_eqterm.\n      }\n\n    (* CongRefl *)\n    - { capply CongRefl.\n        - now apply (ptt_sane_eqtype G A1 A2), sane_eqtype.\n        - now apply (ptt_sane_eqtype G A1 A2), sane_eqtype.\n        - now apply (ptt_sane_eqtype G A1 A2), sane_eqtype.\n        - now apply (ptt_sane_eqterm G u1 u2 A1), sane_eqterm.\n        - now apply (ptt_sane_eqterm G u1 u2 A1), sane_eqterm.\n        - now apply sane_eqterm.\n        - now apply sane_eqtype.\n      }\n\n    (* CongJ *)\n    - { capply CongJ.\n        - now apply (ptt_sane_eqtype G A1 A2), sane_eqtype.\n        - now apply (ptt_sane_eqtype G A1 A2), sane_eqtype.\n        - now apply (ptt_sane_eqtype G A1 A2), sane_eqtype.\n        - now apply (ptt_sane_eqtype _ C1 C2), sane_eqtype.\n        - now apply (ptt_sane_eqtype _ C1 C2), sane_eqtype.\n        - now apply (ptt_sane_eqterm G u1 u2 A1), sane_eqterm.\n        - now apply (ptt_sane_eqterm G u1 u2 A1), sane_eqterm.\n        - now apply (ptt_sane_eqterm G v1 v2 A1), sane_eqterm.\n        - now apply (ptt_sane_eqterm G v1 v2 A1), sane_eqterm.\n        - now apply (ptt_sane_eqterm G p1 p2 _), sane_eqterm.\n        - now apply (ptt_sane_eqterm G p1 p2 _), sane_eqterm.\n        - now apply sane_eqtype.\n        - now apply sane_eqterm.\n        - now apply sane_eqtype.\n        - now apply (ptt_sane_eqterm G w1 w2 _), sane_eqterm.\n        - now apply (ptt_sane_eqterm G w1 w2 _), sane_eqterm.\n        - now apply sane_eqterm.\n        - now apply sane_eqterm.\n        - now apply sane_eqterm.\n      }\n\n    (* CongCond *)\n    - { capply CongCond.\n        - now apply (ptt_sane_eqterm G v1 v2 (Subst C1 (sbzero Bool true))), sane_eqterm.\n        - now apply (ptt_sane_eqtype (ctxextend G Bool) C1 C2), sane_eqtype.\n        - now apply (ptt_sane_eqtype (ctxextend G Bool) C1 C2), sane_eqtype.\n        - now apply (ptt_sane_eqterm G u1 u2 Bool), sane_eqterm.\n        - now apply (ptt_sane_eqterm G u1 u2 Bool), sane_eqterm.\n        - now apply (ptt_sane_eqterm G v1 v2 (Subst C1 (sbzero Bool true))), sane_eqterm.\n        - now apply (ptt_sane_eqterm G v1 v2 (Subst C1 (sbzero Bool true))), sane_eqterm.\n        - now apply (ptt_sane_eqterm G w1 w2 (Subst C1 (sbzero Bool false))), sane_eqterm.\n        - now apply (ptt_sane_eqterm G w1 w2 (Subst C1 (sbzero Bool false))), sane_eqterm.\n        - now apply sane_eqterm.\n        - now apply sane_eqtype.\n        - now apply sane_eqterm.\n        - now apply sane_eqterm.\n      }\n\n    (* CongTermSubst *)\n    - { config apply @CongTermSubst with (D := D).\n        - now apply sane_eqsubst.\n        - now apply sane_eqterm.\n        - now apply (@ptt_sane_eqsubst sbs sbt G D), sane_eqsubst.\n        - now apply (@ptt_sane_eqsubst sbs sbt G D), sane_eqsubst.\n        - now apply (@ptt_sane_eqterm D u1 u2 A), sane_eqterm.\n        - now apply (@ptt_sane_eqterm D u1 u2 A), sane_eqterm.\n        - now apply (@ptt_sane_eqterm D u1 u2 A), sane_eqterm.\n        - now apply (@ptt_sane_eqsubst sbs sbt G D), sane_eqsubst.\n        - now apply (@ptt_sane_eqsubst sbs sbt G D), sane_eqsubst.\n      }\n\n    (* CongPair *)\n    - { capply CongPair.\n        - now apply sane_eqterm.\n        - now apply sane_eqterm.\n        - now apply sane_eqtype.\n        - now apply sane_eqtype.\n        - now apply (ptt_sane_eqterm G u1 u2 A1), sane_eqterm.\n        - now apply (ptt_sane_eqtype G A1 A2), sane_eqtype.\n        - now apply (ptt_sane_eqtype G A1 A2), sane_eqtype.\n        - now apply (ptt_sane_eqtype G B1 B2), sane_eqtype.\n        - now apply (ptt_sane_eqtype G B1 B2), sane_eqtype.\n        - now apply (ptt_sane_eqterm G u1 u2 A1), sane_eqterm.\n        - now apply (ptt_sane_eqterm G u1 u2 A1), sane_eqterm.\n        - now apply (ptt_sane_eqterm G v1 v2 B1), sane_eqterm.\n        - now apply (ptt_sane_eqterm G v1 v2 B1), sane_eqterm.\n      }\n\n    (* CongProjOne *)\n    - { capply CongProjOne.\n        - now apply sane_eqterm.\n        - now apply sane_eqtype.\n        - now apply sane_eqtype.\n        - now apply (ptt_sane_eqtype G A1 A2), sane_eqtype.\n        - now apply (ptt_sane_eqtype G A1 A2), sane_eqtype.\n        - now apply (ptt_sane_eqtype G A1 A2), sane_eqtype.\n        - now apply (ptt_sane_eqtype G B1 B2), sane_eqtype.\n        - now apply (ptt_sane_eqtype G B1 B2), sane_eqtype.\n        - now apply (ptt_sane_eqterm G p1 p2 (BinaryProd A1 B1)), sane_eqterm.\n        - now apply (ptt_sane_eqterm G p1 p2 (BinaryProd A1 B1)), sane_eqterm.\n      }\n\n    (* CongProjTwo *)\n    - { capply CongProjTwo.\n        - now apply sane_eqterm.\n        - now apply sane_eqtype.\n        - now apply sane_eqtype.\n        - now apply (ptt_sane_eqtype G A1 A2), sane_eqtype.\n        - now apply (ptt_sane_eqtype G A1 A2), sane_eqtype.\n        - now apply (ptt_sane_eqtype G A1 A2), sane_eqtype.\n        - now apply (ptt_sane_eqtype G B1 B2), sane_eqtype.\n        - now apply (ptt_sane_eqtype G B1 B2), sane_eqtype.\n        - now apply (ptt_sane_eqterm G p1 p2 (BinaryProd A1 B1)), sane_eqterm.\n        - now apply (ptt_sane_eqterm G p1 p2 (BinaryProd A1 B1)), sane_eqterm.\n      }\n\n    (* EqSubstPair *)\n    - { (* The fact that D gets renamed to D0 is utterly stupid!\n           This isn't a variable name...\n         *)\n        config apply EqSubstPair with (D0 := D).\n        - now apply sane_issubst.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (ptt_sane_isterm D u A), sane_isterm.\n        - now apply (ptt_sane_isterm D v B), sane_isterm.\n      }\n\n    (* EqSubstProjOne *)\n    - { config apply EqSubstProjOne with (D0 := D).\n        - now apply sane_issubst.\n        - now apply sane_isterm.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (TyBinaryProdInversion D A B),\n                    (ptt_sane_isterm D p (BinaryProd A B)),\n                    sane_isterm.\n        - now apply (TyBinaryProdInversion D A B),\n                    (ptt_sane_isterm D p (BinaryProd A B)),\n                    sane_isterm.\n      }\n\n    (* EqSubstProjTwo *)\n    - { config apply EqSubstProjTwo with (D0 := D).\n        - now apply sane_issubst.\n        - now apply sane_isterm.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (TyBinaryProdInversion D A B),\n                    (ptt_sane_isterm D p (BinaryProd A B)),\n                    sane_isterm.\n        - now apply (TyBinaryProdInversion D A B),\n                    (ptt_sane_isterm D p (BinaryProd A B)),\n                    sane_isterm.\n      }\n\n    (* ProjOnePair *)\n    - { capply ProjOnePair.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n        - now apply (ptt_sane_isterm G u A), sane_isterm.\n        - now apply (ptt_sane_isterm G u A), sane_isterm.\n        - now apply (ptt_sane_isterm G v B), sane_isterm.\n      }\n\n    (* ProjTwoPair *)\n    - { capply ProjTwoPair.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n        - now apply (ptt_sane_isterm G u A), sane_isterm.\n        - now apply (ptt_sane_isterm G u A), sane_isterm.\n        - now apply (ptt_sane_isterm G v B), sane_isterm.\n      }\n\n    (* PairEta *)\n    - { capply PairEta.\n        - now apply sane_eqterm.\n        - now apply sane_eqterm.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n        - now apply (ptt_sane_eqterm G (proj1 A B p) (proj1 A B q) A),\n                    sane_eqterm.\n        - now apply (ptt_sane_eqterm G (proj1 A B p) (proj1 A B q) A),\n                    sane_eqterm.\n        - now apply (ptt_sane_eqterm G (proj2 A B p) (proj2 A B q) B),\n                    sane_eqterm.\n      }\n\n    (* EqSubstUniProd *)\n    - { config apply @EqSubstUniProd with (D := D).\n        - now apply sane_issubst.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n      }\n\n    (* EqSubstUniProdProp *)\n    - { config apply @EqSubstUniProdProp with (D := D).\n        - now apply sane_issubst.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n      }\n\n    (* EqSubstUniId *)\n    - { config apply @EqSubstUniId with (D := D).\n        - now apply sane_issubst.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n      }\n\n    (* EqSubstUniEmpty *)\n    - { config apply @EqSubstUniEmpty with (D := D).\n        - now apply sane_issubst.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n      }\n\n    (* EqSubstUniUnit *)\n    - { config apply @EqSubstUniUnit with (D := D).\n        - now apply sane_issubst.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n      }\n\n    (* EqSubstUniBool *)\n    - { config apply @EqSubstUniBool with (D := D).\n        - now apply sane_issubst.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n      }\n\n    (* EqSubstUniBinaryProd *)\n    - { config apply @EqSubstUniBinaryProd with (D := D).\n        - now apply sane_issubst.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n      }\n\n    (* EqSubstUniBinaryProdProp *)\n    - { config apply @EqSubstUniBinaryProdProp with (D := D).\n        - now apply sane_issubst.\n        - now apply sane_isterm.\n        - now apply sane_isterm.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n      }\n\n    (* EqSubstUniUni *)\n    - { config apply @EqSubstUniUni with (D := D).\n        - now apply sane_issubst.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n      }\n\n    (* EqSubstUniProp *)\n    - { config apply @EqSubstUniProp with (D := D).\n        - now apply sane_issubst.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n        - now apply (ptt_sane_issubst sbs G D), sane_issubst.\n      }\n\n    (* CongUniProd *)\n    - { capply CongUniProd.\n        - now apply sane_eqterm.\n        - now apply sane_eqterm.\n        - now apply (ptt_sane_eqterm G a1 a2 (Uni (uni n))), sane_eqterm.\n        - now apply (ptt_sane_eqterm G a1 a2 (Uni (uni n))), sane_eqterm.\n        - now apply (ptt_sane_eqterm (ctxextend G (El (uni n) a1))\n                                     b1 b2 (Uni (uni m))),\n                    sane_eqterm.\n        - now apply (ptt_sane_eqterm (ctxextend G (El (uni n) a1)) b1 b2 (Uni (uni m))),\n                    sane_eqterm.\n        - now apply (ptt_sane_eqterm G a1 a2 (Uni (uni n))), sane_eqterm.\n      }\n\n    (* CongUniProdProp *)\n    - { capply CongUniProdProp.\n        - now apply sane_eqterm.\n        - now apply sane_eqterm.\n        - now apply (ptt_sane_eqterm G a1 a2 (Uni l)), sane_eqterm.\n        - now apply (ptt_sane_eqterm G a1 a2 (Uni l)), sane_eqterm.\n        - now apply (ptt_sane_eqterm (ctxextend G (El l a1)) b1 b2 (Uni prop)),\n                    sane_eqterm.\n        - now apply (ptt_sane_eqterm (ctxextend G (El l a1)) b1 b2 (Uni prop)),\n                    sane_eqterm.\n        - now apply (ptt_sane_eqterm G a1 a2 (Uni l)), sane_eqterm.\n      }\n\n    (* CongUniId *)\n    - { capply CongUniId.\n        - now apply sane_eqterm.\n        - now apply sane_eqterm.\n        - now apply sane_eqterm.\n        - now apply (ptt_sane_eqterm G a1 a2 (Uni n)), sane_eqterm.\n        - now apply (ptt_sane_eqterm G a1 a2 (Uni n)), sane_eqterm.\n        - now apply (ptt_sane_eqterm G u1 u2 (El n a1)), sane_eqterm.\n        - now apply (ptt_sane_eqterm G u1 u2 (El n a1)), sane_eqterm.\n        - now apply (ptt_sane_eqterm G v1 v2 (El n a1)), sane_eqterm.\n        - ceapply TermTyConv.\n          + now apply (ptt_sane_eqterm G v1 v2 (El n a1)), sane_eqterm.\n          + config apply @CongEl with (n := n).\n            * now apply sane_eqterm.\n            * now apply (ptt_sane_eqterm G a1 a2 (Uni n)), sane_eqterm.\n            * now apply (ptt_sane_eqterm G a1 a2 (Uni n)), sane_eqterm.\n            * now apply (ptt_sane_eqterm G a1 a2 (Uni n)), sane_eqterm.\n          + now apply (ptt_sane_eqterm G a1 a2 (Uni n)), sane_eqterm.\n          + now apply (ptt_sane_eqterm G v1 v2 (El n a1)), sane_eqterm.\n          + capply @TyEl.\n            * now apply (ptt_sane_eqterm G a1 a2 (Uni n)), sane_eqterm.\n            * now apply (ptt_sane_eqterm G a1 a2 (Uni n)), sane_eqterm.\n        - now apply (ptt_sane_eqterm G a1 a2 (Uni n)), sane_eqterm.\n      }\n\n    (* CongUniBinaryProd *)\n    - { capply CongUniBinaryProd.\n        - now apply sane_eqterm.\n        - now apply sane_eqterm.\n        - now apply (ptt_sane_eqterm G a1 a2 (Uni (uni n))), sane_eqterm.\n        - now apply (ptt_sane_eqterm G a1 a2 (Uni (uni n))), sane_eqterm.\n        - now apply (ptt_sane_eqterm G b1 b2 (Uni (uni m))), sane_eqterm.\n        - now apply (ptt_sane_eqterm G b1 b2 (Uni (uni m))), sane_eqterm.\n        - now apply (ptt_sane_eqterm G b1 b2 (Uni (uni m))), sane_eqterm.\n      }\n\n    (* CongUniBinaryProdProp *)\n    - { capply CongUniBinaryProdProp.\n        - now apply sane_eqterm.\n        - now apply sane_eqterm.\n        - now apply (ptt_sane_eqterm G a1 a2 (Uni prop)), sane_eqterm.\n        - now apply (ptt_sane_eqterm G a1 a2 (Uni prop)), sane_eqterm.\n        - now apply (ptt_sane_eqterm G b1 b2 (Uni prop)), sane_eqterm.\n        - now apply (ptt_sane_eqterm G b1 b2 (Uni prop)), sane_eqterm.\n        - now apply (ptt_sane_eqterm G b1 b2 (Uni prop)), sane_eqterm.\n      }\n  }\n\nDefined.\n\nEnd Ett2Ptt.\n", "meta": {"author": "TheoWinterhalter", "repo": "formal-type-theory", "sha": "93ac197dfde912d77af9b0f4fd9f7d2422ba7dfc", "save_path": "github-repos/coq/TheoWinterhalter-formal-type-theory", "path": "github-repos/coq/TheoWinterhalter-formal-type-theory/formal-type-theory-93ac197dfde912d77af9b0f4fd9f7d2422ba7dfc/src/ett2ptt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2646424443682477}}
{"text": "Require Import CSPEC.\nRequire Import Relations.Relation_Operators.\nRequire Import RelationClasses.\nRequire Import Morphisms.\n\nImport ListNotations.\nRequire Import String.\nRequire Import FSModel.\n\n(** Definition of concurrent tree modifications, to write specifications *)\n\nDefinition tree_transform := FSet.t Link -> FSet.t Link.\n\nDefinition transform_fs (fs : FS) (xform : tree_transform) :=\n  mkFS (FSRoot fs) (xform (FSLinks fs)) (FSFiles fs).\n\nDefinition add_link (srcdir : nat) (dst : Node) (name : string) : tree_transform :=\n  fun links => FSet.add (mkLink srcdir dst name) links.\n\nDefinition remove_link (srcdir : nat) (dst : Node) (name : string) : tree_transform :=\n  fun links => FSet.remove (mkLink srcdir dst name) links.\n\nDefinition xform_both (x1 x2 : tree_transform) :=\n  fun t => x2 (x1 t).\n\nDefinition xform_id : tree_transform :=\n  fun t => t.\n\nNotation \"x1 ;; x2\" := (xform_both x1 x2) (at level 50).\n\n(** This is what a specification looks like *)\n\nRecord specification (R : Type) := mkSpec {\n  Result : forall (result : R) (fs : FS), Prop;\n  AddLinks : tree_transform;\n  RemoveLinks : tree_transform;\n}.\n\nDefinition spec_start {R} (fs : FS) (spec : specification R) : FS :=\n  transform_fs fs (AddLinks spec).\n\nDefinition spec_finish {R} (fs : FS) (spec : specification R) : FS :=\n  transform_fs fs (RemoveLinks spec ;; AddLinks spec).\n\nDefinition spec_ok {R} (fs : FS) (spec : specification R) (r : R) : Prop :=\n  Result spec r fs.\n\n\n(** Concrete specifications *)\n\nDefinition lookup_spec (pn : Pathname) : specification (option Node) := {|\n  Result := fun result fs =>\n    (exists node, result = Some node /\\ path_eval_root fs pn node) \\/\n    result = None /\\ ~ exists node, path_eval_root fs pn node;\n  AddLinks := xform_id;\n  RemoveLinks := xform_id;\n|}.\n\nDefinition rename_overwrite_spec srcdir srcname node dstdir dstname oldnode := {|\n  Result := fun r _ => r = tt;\n  AddLinks := add_link dstdir node dstname;\n  RemoveLinks := remove_link srcdir node srcname;;\n                 remove_link dstdir oldnode dstname\n|}.\n\nDefinition rename_nonexist_spec srcdir srcname node dstdir dstname := {|\n  Result := fun r _ => r = tt;\n  AddLinks := add_link dstdir node dstname;\n  RemoveLinks := remove_link srcdir node srcname\n|}.\n\n(**\n  TODO: take just Pathname arguments, rather than relying on knowing\n  node (and oldnode, if exists) already.\n\n  tricky issues:\n  - moving a symlink: need to move the SymlinkNode, not the evaluated target.\n  - overwriting a symlink?\n  - what if there are multiple possibilities for a given name?\n    saying \"~ exists .., path_eval_root\" seems to imply NONE of\n    these concurrent syscalls can be running now.\n *)\n\n(*\nDefinition rename_spec srcdir srcname dstdir dstname := {|\n  Result := fun r _ =>\n    r = true <-> exists n, path_eval_root fs (srcdir ++ [srcname]) n /\\\n      ~ exists d, path_eval_root fs (dstdir ++ [dstname]) (DirNode d);\n  AddLinks := add_link \n|}.\n*)\n\nDefinition names := list string.\n\nDefinition dirents dirnum (g: FSet.t Link) :=\n  FSet.filter (fun (l: Link) => (beq_nat (LinkFrom l) dirnum)) g.\n\nDefinition dirnames dirnum g : names :=\n  let dir := dirents dirnum g in\n  map (fun (l:Link) => (LinkName l)) (FSet.elements dir).\n\nDefinition readdir_spec pn : specification (option names)  := {|\n  Result := fun result fs =>\n              (exists node dir n, dir = Some (DirNode n) /\\ path_eval_root fs pn node /\\\n                           result = Some (dirnames n (FSLinks fs))\n              ) \\/\n              result = None /\\  ~ exists node n, path_eval_root fs pn node /\\ node = (DirNode n);\n  AddLinks := xform_id;\n  RemoveLinks := xform_id;\n|}.\n\n(** Example valid (and some invalid) lookups *)\n\nHint Extern 1 False =>\n  match goal with\n  | H : {| LinkFrom := ?a; LinkTo := ?b; LinkName := ?c |} =\n        {| LinkFrom := ?d; LinkTo := ?e; LinkName := ?f |} |- _ =>\n    destruct ((mkLink a b c) == (mkLink d e f)); congruence\n  end.\n\nDefinition example_fs := mkFS 1\n (FSet.add (mkLink 1 (DirNode 2) \"etc\")\n (FSet.add (mkLink 2 (FileNode 10) \"passwd\")\n (FSet.add (mkLink 2 (SymlinkNode [\"passwd\"]) \"passwd~\")\n (FSet.add (mkLink 1 (SymlinkNode [\"etc\"]) \"etc~\")\n (FSet.add (mkLink 1 (DirNode 3) \"tmp\")\n (FSet.add (mkLink 3 (SymlinkNode [\"..\"; \"etc\"]) \"foo\")\n (FSet.add (mkLink 3 (SymlinkNode [\"..\"; \"..\"; \"etc\"]) \"foo2\")\n (FSet.add (mkLink 3 (SymlinkNode [\"..\"]) \"root\")\n             FSet.empty))))))))\n  [].\n\nLtac resolve_link := constructor; compute; auto 20.\nLtac resolve_filename :=  apply PathEvalFileLink; resolve_link.\nLtac resolve_dirname :=  eapply PathEvalDirLink; [ resolve_link |].\nLtac resolve_fsymname := eapply PathEvalSymlink; [ resolve_link | resolve_filename; auto | auto].\nLtac resolve_dsymname := eapply PathEvalSymlink; [ resolve_link | resolve_dirname; auto | auto].\nLtac resolve_dotdot := eapply PathEvalDirLink; [ eapply ValidDotDot; compute; auto | ].\nLtac resolve_dotdotRoot :=  eapply PathEvalDirLink; [ eapply ValidDotDotRoot; compute; auto| ].\nLtac resolve_init := left; eexists; unfold path_eval_root; split; auto.\n\nTheorem etc_passwd :\n  spec_ok example_fs (lookup_spec [\"etc\"; \"passwd\"]) (Some (FileNode 10)).\nProof.\n  resolve_init.\n  resolve_dirname.\n  resolve_filename.\nQed.\n\nTheorem etc_passwd' :\n  spec_ok example_fs (lookup_spec [\"etc\"; \"passwd~\"]) (Some (FileNode 10)).\nProof.\n  resolve_init.\n  resolve_dirname.\n  resolve_fsymname.\nQed.\n\nTheorem etc'_passwd :\n  spec_ok example_fs (lookup_spec [\"etc~\"; \"passwd\"]) (Some (FileNode 10)).\nProof.\n  resolve_init.\n  resolve_dsymname.\n  resolve_filename.\nQed.\n\nTheorem tmp_foo_passwd :\n  spec_ok example_fs (lookup_spec [\"tmp\"; \"foo\"; \"passwd\"]) (Some (FileNode 10)).\nProof.\n  resolve_init.\n  resolve_dirname.\n  \n  eapply PathEvalSymlink.\n  resolve_link.\n \n  resolve_dotdot.\n  \n  resolve_dirname; auto.\n  resolve_filename.\nQed.\n\nTheorem tmp_foo2_passwd :\n  spec_ok example_fs (lookup_spec [\"tmp\"; \"foo2\"; \"passwd\"]) (Some (FileNode 10)).\nProof.\n  resolve_init.\n  resolve_dirname.\n\n  eapply PathEvalSymlink.\n  resolve_link.\n \n  resolve_dotdot.\n  2: resolve_filename.\n  resolve_dotdotRoot.\n  resolve_dirname.\n  auto.\nQed.\n\nLtac resolve_none :=\n  repeat match goal with\n         | [ H: FSet.In _ _ |- _ ] =>\n           apply FSet.add_in' in H\n         | [ H: (_ = _) \\/ _ |- _ ] =>\n           destruct H;\n           [ exfalso; congruence | ]\n         | [ H: FSet.In _ FSet.empty |- _ ] =>\n           apply FSet.empty_in in H; solve [ destruct H ]\n         end.\n\nTheorem no_usr :\n  spec_ok example_fs (lookup_spec [\"usr\"]) None.\nProof.\n  simpl.\n  right; eauto.\n  split; eauto.\n  intuition. deex.\n  inversion H; clear H; subst.\n  inversion H3; clear H3; subst.\n  resolve_none.\n  inversion H4; subst.\n  resolve_none.\n  inversion H4; subst.\n  resolve_none.\nQed.\n\n\n(** Example lookups (positive and negative) in the presence of a concurrent rename *)\n\nDefinition rename_example :=\n  rename_nonexist_spec 1 \"tmp\" (DirNode 3) 1 \"tmp2\".\n\nTheorem tmp_root_tmp2_foo_passwd_concur_during :\n  spec_ok\n    (spec_start example_fs rename_example)\n    (lookup_spec [\"tmp\"; \"root\"; \"tmp2\"; \"foo\"; \"passwd\"])\n    (Some (FileNode 10)).\nProof.\n  resolve_init.\n\n  unfold rename_example, spec_start, rename_nonexist_spec, transform_fs, add_link; simpl.\n  \n  (* lookup tmp, root  *)\n  resolve_dirname.\n  \n  eapply PathEvalSymlink.\n  resolve_link.\n  resolve_dotdot; auto.\n\n  (* finish lookup *)\n  resolve_dirname.\n\n  eapply PathEvalSymlink.\n  resolve_link.\n  resolve_dotdot; auto.\n  resolve_dirname; auto.\n  resolve_filename.\nQed.\n\nTheorem tmp_root_tmp2_foo_passwd_concur_after :\n  spec_ok\n    (spec_finish example_fs rename_example)\n    (lookup_spec [\"tmp2\"; \"foo\"; \"passwd\"])\n    (Some (FileNode 10)).\nProof.\n  resolve_init.\n\n  unfold rename_example, spec_finish, transform_fs; simpl.\n  unfold remove_link, add_link;\n    resolve_dirname.\n  eapply PathEvalSymlink.\n  resolve_link.\n  resolve_dotdot. auto.\n  2: resolve_dirname; auto.\n  (* 2: resolve_filename; auto.\n  Unshelve.\n  2: exact \"tmp2\".\n  compute. auto 20. *)\nAdmitted.\n\nTheorem no_tmp_root_tmp2_foo_passwd_concur_after :\n  spec_ok\n    (spec_finish example_fs rename_example)\n    (lookup_spec [\"tmp\"; \"root\"; \"tmp2\"; \"foo\"; \"passwd\"])\n    None.\nProof.\n  simpl.\n  right.\n  split; auto.\n  unfold rename_example, spec_finish, transform_fs, rename_nonexist_spec in *.\n  intuition. deex.\n  inversion H; clear H; subst.\n  inversion H4; clear H4; subst.\n\n  resolve_none.\n  apply FSet.remove_in' in H; intuition idtac; try congruence.\n  resolve_none.\n\n  inversion H4; subst; clear H4.\n  resolve_none.\n  apply FSet.remove_in' in H.\n  intuition idtac; try congruence.\n  \n  inversion H5; subst; clear H5; resolve_none.\nQed.\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/FS/symlinks/ExampleTrees.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.2646424378834184}}
{"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 pind Axioms\n     Mod Linking SCM Red IRed WeakestAdequacy.\nFrom Ordinal Require Export ClassicalHessenberg.\nFrom Fairness Require Import NatStructs NatMapRA.\n\nSet Implicit Arguments.\n\nModule TicketLock.\n  Definition gvs : list nat := [2].\n  Definition now_serving: SCMem.val := SCMem.val_ptr (0, 0).\n  Definition next_ticket: SCMem.val := SCMem.val_ptr (0, 1).\n\n  Notation tk := nat.\n\n  Definition lock_loop (myticket: SCMem.val):\n    itree (programE void unit) unit\n    :=\n    ITree.iter\n      (fun (_: unit) =>\n         now <- (OMod.call \"load\" (now_serving));;\n         b <- (OMod.call \"compare\" (now: SCMem.val, myticket: SCMem.val));;\n         if (b: bool) then Ret (inr tt) else Ret (inl tt)) tt.\n\n  Lemma lock_loop_red myticket\n    :\n    lock_loop myticket\n    =\n      now <- (OMod.call \"load\" (now_serving));;\n      b <- (OMod.call \"compare\" (now: SCMem.val, myticket: SCMem.val));;\n      if (b: bool)\n      then Ret tt else tau;; lock_loop myticket.\n  Proof.\n    unfold lock_loop. etransitivity.\n    { apply unfold_iter_eq. }\n    grind.\n  Qed.\n\n  Definition lock_fun:\n    ktree (programE void unit) unit unit :=\n    fun _ =>\n      myticket <- (OMod.call \"faa\" (next_ticket, 1));;\n      _ <- lock_loop myticket;;\n      trigger Yield\n  .\n\n  Definition unlock_fun:\n    ktree (programE void unit) unit unit :=\n    fun _ =>\n      upd <- (OMod.call \"load\" now_serving);;\n      let upd := SCMem.val_add upd 1 in\n      `_: unit <- (OMod.call \"store\" (now_serving, upd));;\n      trigger Yield\n  .\n\n  Definition omod: Mod.t :=\n    Mod.mk\n      tt\n      (Mod.get_funs [(\"lock\", Mod.wrap_fun lock_fun);\n                     (\"unlock\", Mod.wrap_fun unlock_fun)])\n  .\n\n  Definition mod: Mod.t :=\n    OMod.close\n      (omod)\n      (SCMem.mod gvs)\n  .\n\nEnd TicketLock.\n\n\n\nFrom Fairness Require Import IProp IPM Weakest.\nFrom Fairness Require Import ModSim PCM MonotonePCM StateRA FairRA.\nFrom Fairness Require Import FairLock.\nFrom Fairness Require Import NatStructs NatMapRA.\n\nSection AUX.\n\n  Variant prod_le\n          {A B: Type} {RA: A -> A -> Prop} {RB: B -> B -> Prop}\n          (PRA: PartialOrder RA) (PRB: PreOrder RB) :\n    (A * B) -> (A * B) -> Prop :=\n    | prod_le_l\n        a0 a1 b0 b1\n        (ORD: RA a0 a1)\n        (NEQ: a0 <> a1)\n      :\n      prod_le PRA PRB (a0, b0) (a1, b1)\n    | prod_le_r\n        a b0 b1\n        (ORD: RB b0 b1)\n      :\n      prod_le PRA PRB (a, b0) (a, b1)\n  .\n\n  Global Program Instance prod_le_PreOrder\n         {A B: Type} {RA: A -> A -> Prop} {RB: B -> B -> Prop}\n         (PRA: PartialOrder RA) (PRB: PreOrder RB)\n    : PreOrder (prod_le PRA PRB).\n  Next Obligation.\n    ii. destruct x. econs 2. inv PRB. auto.\n  Qed.\n  Next Obligation.\n    ii. destruct x as [a0 b0], y as [a1 b1], z as [a2 b2].\n    inv H.\n    - inv H0.\n      + econs 1; inv PRA.\n        * inv partial_order_pre. eapply PreOrder_Transitive; eauto.\n        * ii. clarify. apply NEQ0. apply partial_order_anti_symm; auto.\n      + econs 1; auto.\n    - inv H0.\n      + econs 1; auto.\n      + econs 2. inv PRB. eapply PreOrder_Transitive; eauto.\n  Qed.\n\nEnd AUX.\n\nModule Tkst.\n  Section TKST.\n\n    Definition t X := (nat * X)%type.\n\n    Definition le {X} (s0 s1: @t X): Prop :=\n      let '(n0, x0) := s0 in\n      let '(n1, x1) := s1 in\n      (n0 <= n1) /\\ (n0 = n1 -> x0 = x1).\n\n    Global Program Instance le_PreOrder X: PreOrder (@le X).\n    Next Obligation.\n      ii. unfold le. des_ifs.\n    Qed.\n    Next Obligation.\n      ii. unfold le in *. des_ifs. des; clarify. split; auto; try lia.\n      i. clarify. assert (n0 = n1). lia. clarify. rewrite H2; auto.\n    Qed.\n\n\n    Definition a {X} x : t X := (1, x).\n    Definition b {X} x : t X := (2, x).\n    Definition c {X} x : t X := (3, x).\n    Definition d {X} x : t X := (4, x).\n\n  End TKST.\nEnd Tkst.\n\nSection TKQ.\n\n  Inductive tkqueue\n            (l: list thread_id) (tks: NatMap.t TicketLock.tk) (inc exc: TicketLock.tk)\n    : Prop :=\n  | tkqueue_nil\n      (EMP1: l = [])\n      (EMP2: tks = @NatMap.empty _)\n      (EQ: inc = exc)\n    :\n    tkqueue l tks inc exc\n  | tkqueue_cons\n      hd tl\n      (QUEUE: l = hd :: tl)\n      (FIND: NatMap.find hd tks = Some inc)\n      (TL: tkqueue tl (NatMap.remove hd tks) (S inc) exc)\n    :\n    tkqueue l tks inc exc\n  .\n\n  Lemma tkqueue_enqueue\n        l tks inc exc\n        (TQ: tkqueue l tks inc exc)\n        k\n        (FIND: NatMap.find k tks = None)\n    :\n    tkqueue (l ++ [k]) (NatMap.add k exc tks) inc (S exc).\n  Proof.\n    revert_until TQ. induction TQ; i; clarify; ss.\n    { econs 2. ss. apply nm_find_add_eq. econs 1; auto. rewrite nm_find_none_rm_add_eq; auto. }\n    assert (NEQ: hd <> k).\n    { ii. clarify. }\n    econs 2. instantiate (2:=hd). ss. rewrite nm_find_add_neq; auto.\n    erewrite <- nm_find_none_add_rm_is_eq. eapply IHTQ.\n    rewrite nm_find_rm_neq; auto. rewrite nm_find_add_neq; auto. apply nm_find_rm_eq.\n    instantiate (1:=inc). rewrite nm_add_rm_comm_eq; auto.\n    rewrite <- nm_find_some_rm_add_eq; auto. rewrite nm_find_add_neq; auto.\n  Qed.\n\n  Lemma tkqueue_dequeue\n        l tks inc exc\n        (TQ: tkqueue l tks inc exc)\n        hd tl\n        (HD: l = hd :: tl)\n    :\n    tkqueue tl (NatMap.remove hd tks) (S inc) exc.\n  Proof.\n    revert_until TQ. induction TQ; i; clarify; ss.\n  Qed.\n\n  Lemma tkqueue_range\n        l tks inc exc\n        (TQ: tkqueue l tks inc exc)\n    :\n    inc <= exc.\n  Proof.\n    induction TQ; i; clarify; ss. lia.\n  Qed.\n\n  Lemma tkqueue_val_range_l\n        l tks inc exc\n        (TQ: tkqueue l tks inc exc)\n        t v\n        (FIND: NatMap.find t tks = Some v)\n    :\n    inc <= v.\n  Proof.\n    revert_until TQ. induction TQ; i; clarify; ss.\n    destruct (tid_dec t hd) eqn:DEC; clarify.\n    hexploit (IHTQ t v). rewrite nm_find_rm_neq; auto. i. lia.\n  Qed.\n\n  Lemma tkqueue_val_range_r\n        l tks inc exc\n        (TQ: tkqueue l tks inc exc)\n        t v\n        (FIND: NatMap.find t tks = Some v)\n    :\n    v < exc.\n  Proof.\n    revert_until TQ. induction TQ; i; clarify; ss.\n    destruct (tid_dec t hd) eqn:DEC; clarify.\n    - eapply tkqueue_range in TQ. lia.\n    - hexploit (IHTQ t v). rewrite nm_find_rm_neq; auto. i. lia.\n  Qed.\n\n  Lemma tkqueue_inv_unique\n        l tks inc exc\n        (TQ: tkqueue l tks inc exc)\n        t0 t1 v\n        (FIND0: NatMap.find t0 tks = Some v)\n        (FIND1: NatMap.find t1 tks = Some v)\n    :\n    t0 = t1.\n  Proof.\n    revert_until TQ. induction TQ; i; clarify; ss.\n    destruct (tid_dec t0 hd) eqn:DEC0; clarify; eauto.\n    { destruct (tid_dec t1 hd) eqn:DEC1; clarify; eauto.\n      hexploit tkqueue_val_range_l. eapply TQ. erewrite nm_find_rm_neq.\n      2:{ ii. apply n. symmetry. eapply H. }\n      eapply FIND1. i. lia.\n    }\n    { destruct (tid_dec t1 hd) eqn:DEC1; clarify; eauto.\n      { hexploit tkqueue_val_range_l. eapply TQ. erewrite nm_find_rm_neq.\n        2:{ ii. apply n. symmetry. eapply H. }\n        eapply FIND0. i. lia.\n      }\n      eapply IHTQ; rewrite nm_find_rm_neq; eauto.\n    }\n  Qed.\n\n  Lemma tkqueue_inv_hd\n        l tks inc exc\n        (TQ: tkqueue l tks inc exc)\n        t\n        (FIND: NatMap.find t tks = Some inc)\n    :\n    exists tl, l = t :: tl.\n  Proof.\n    revert_until TQ. induction TQ; i; clarify; ss.\n    destruct (tid_dec t hd) eqn:DEC; clarify; eauto.\n    hexploit tkqueue_inv_unique. 2: eapply FIND. 2: eapply FIND0.\n    { instantiate (1:=exc). instantiate (1:=inc). instantiate (1:=hd :: tl).\n      econs 2; eauto.\n    }\n    i; clarify.\n  Qed.\n\n  Lemma tkqueue_find_in\n        l tks inc exc\n        (TQ: tkqueue l tks inc exc)\n        t v\n        (FIND: NatMap.find t tks = Some v)\n    :\n    In t l.\n  Proof.\n    revert_until TQ. induction TQ; i; clarify; ss.\n    destruct (tid_dec t hd) eqn:DEC; clarify; auto.\n    right. hexploit (IHTQ t v). rewrite nm_find_rm_neq; auto. i. auto.\n  Qed.\n\n  Lemma tkqueue_in_find\n        l tks inc exc\n        (TQ: tkqueue l tks inc exc)\n        t\n        (IN: In t l)\n    :\n    exists v, NatMap.find t tks = Some v.\n  Proof.\n    revert_until TQ. induction TQ; i; clarify; ss. des; clarify; eauto.\n    hexploit (IHTQ t IN). i. des. exists v. rewrite NatMapP.F.remove_o in H. des_ifs.\n  Qed.\n\nEnd TKQ.\n\n\nSection SIM.\n\n  Context `{Σ: GRA.t}.\n\n  Context `{MONORA: @GRA.inG monoRA Σ}.\n  Context `{THDRA: @GRA.inG ThreadRA Σ}.\n  Context `{STATESRC: @GRA.inG (stateSrcRA (Mod.state AbsLock.mod)) Σ}.\n  Context `{STATETGT: @GRA.inG (stateTgtRA (OMod.closed_state TicketLock.omod (SCMem.mod TicketLock.gvs))) Σ}.\n  Context `{IDENTSRC: @GRA.inG (identSrcRA (Mod.ident AbsLock.mod)) Σ}.\n  Context `{IDENTTGT: @GRA.inG (identTgtRA (OMod.closed_ident TicketLock.omod (SCMem.mod TicketLock.gvs))) Σ}.\n  Context `{OBLGRA: @GRA.inG ObligationRA.t Σ}.\n  Context `{ARROWRA: @GRA.inG (ArrowRA (OMod.closed_ident TicketLock.omod (SCMem.mod TicketLock.gvs))) Σ}.\n  Context `{EDGERA: @GRA.inG EdgeRA Σ}.\n  Context `{ONESHOTSRA: @GRA.inG (@FiniteMap.t (OneShot.t unit)) Σ}.\n  Context `{MEMRA: @GRA.inG memRA Σ}.\n\n  Context `{NATMAPRA: @GRA.inG (Auth.t (NatMapRALarge.t TicketLock.tk)) Σ}.\n  Context `{AUTHRA1: @GRA.inG (Auth.t (Excl.t nat)) Σ}.\n  Context `{AUTHRA2: @GRA.inG (Auth.t (Excl.t (nat * nat))) Σ}.\n  Context `{IN2: @GRA.inG (thread_id ==> (Auth.t (Excl.t nat)))%ra Σ}.\n\n  Let mypreord := prod_le_PreOrder Nat.le_po (Tkst.le_PreOrder nat).\n  Variable monok: nat.\n  Variable tk_mono: nat.\n\n  Definition ticket_lock_inv_unlocking\n             (l: list thread_id) (tks: NatMap.t nat) (now next: nat) (myt: thread_id) : iProp :=\n    (own_thread myt)\n      ∗\n      (⌜tkqueue l tks (S now) next⌝)\n      ∗\n      (natmap_prop_sum tks (fun th tk => FairRA.white th (Ord.from_nat (tk - (S now)))))\n      ∗\n      (list_prop_sum (fun th => ((ObligationRA.duty (inl th) [])\n                                ∗ (∃ u, maps_to th (Auth.black (Excl.just u: Excl.t nat))))%I) l)\n      ∗\n      (∃ (k: nat) (o: Ord.t),\n          (monoBlack monok mypreord (now, Tkst.d k))\n            ∗ (ObligationRA.black k o)\n            ∗ (ObligationRA.pending k 1)\n            ∗ (ObligationRA.duty (inl myt) [(k, Ord.S Ord.O)])\n      )\n  .\n\n  Definition ticket_lock_inv_unlocked0\n             (l: list thread_id) (tks: NatMap.t nat) (now next: nat) (myt: thread_id) : iProp :=\n    (OwnM (Auth.white (Excl.just (now, myt): Excl.t (nat * nat)%type)))\n      ∗\n      (⌜(l = []) /\\ (tks = @NatMap.empty _) /\\ (now = next)⌝)\n      ∗\n      (∃ (k: nat),\n          (monoBlack monok mypreord (now, Tkst.a k))\n      )\n  .\n\n  Definition ticket_lock_inv_unlocked1\n             (l: list thread_id) (tks: NatMap.t nat) (now next: nat) (myt: thread_id) : iProp :=\n    ∃ yourt waits,\n      (OwnM (Auth.white (Excl.just (now, myt): Excl.t (nat * nat)%type)))\n        ∗\n        (⌜(l = yourt :: waits)⌝)\n        ∗\n        (⌜tkqueue l tks now next⌝)\n        ∗\n        (natmap_prop_sum tks (fun th tk => FairRA.white th (Ord.from_nat (tk - (now)))))\n        ∗\n        (list_prop_sum (fun th => ((ObligationRA.duty (inl th) [])\n                                  ∗ (∃ u, maps_to th (Auth.black (Excl.just u: Excl.t nat))))%I) waits)\n        ∗\n        (∃ (k: nat) (o: Ord.t) (u: nat),\n            (monoBlack monok mypreord (now, Tkst.b k))\n              ∗ (ObligationRA.black k o)\n              ∗ (ObligationRA.pending k 1)\n              ∗ (ObligationRA.duty (inl yourt) [(k, Ord.S Ord.O)])\n              ∗ (ObligationRA.white k (((Ord.S Ord.O) × Ord.omega) × (Ord.from_nat u))%ord)\n              ∗ (maps_to yourt (Auth.black (Excl.just u: Excl.t nat)))\n        )\n  .\n\n  Definition ticket_lock_inv_locked\n             (l: list thread_id) (tks: NatMap.t nat) (now next: nat) (myt: thread_id) : iProp :=\n    (OwnM (Auth.white (Excl.just (now, myt): Excl.t (nat * nat)%type)))\n      ∗\n      (⌜tkqueue l tks (S now) next⌝)\n      ∗\n      (natmap_prop_sum tks (fun th tk => FairRA.white th (Ord.from_nat (tk - (S now)))))\n      ∗\n      (list_prop_sum (fun th => ((ObligationRA.duty (inl th) [])\n                                ∗ (∃ u, maps_to th (Auth.black (Excl.just u: Excl.t nat))))%I) l)\n      ∗\n      (∃ (k: nat),\n          (monoBlack monok mypreord (now, Tkst.c k))\n      )\n  .\n\n  Definition ticket_lock_inv_tks\n             (tks: NatMap.t nat) : iProp :=\n    ((OwnM (Auth.black (Some tks: NatMapRALarge.t nat)))\n       ∗ (FairRA.whites (fun id => (~ NatMap.In id tks)) Ord.omega)\n       ∗ (natmap_prop_sum tks (fun tid tk => (own_thread tid)))\n       ∗ (OwnMs (fun id => (~ NatMap.In id tks))\n                ((Auth.black (Excl.just 0: Excl.t nat)) ⋅ (Auth.white (Excl.just 0: Excl.t nat))))\n    )\n  .\n\n  Definition ticket_lock_inv_mem\n             (mem: SCMem.t) (now next: nat) (myt: thread_id) : iProp :=\n    ((memory_black mem)\n       ∗ (points_to TicketLock.now_serving (SCMem.val_nat now))\n       ∗ (points_to TicketLock.next_ticket (SCMem.val_nat next))\n       ∗ (OwnM (Auth.black (Excl.just (now, myt): Excl.t (nat * nat)%type)))\n       ∗ (monoBlack tk_mono Nat.le_preorder now)\n    )\n  .\n\n  Definition ticket_lock_inv_state\n             (mem: SCMem.t) (own: bool) (tks: NatMap.t nat) : iProp :=\n    ((St_tgt (tt, mem)) ∗ (St_src (own, (key_set tks))))\n  .\n\n  Definition ticket_lock_inv : iProp :=\n    ∃ (mem: SCMem.t) (own: bool)\n      (l: list thread_id) (tks: NatMap.t nat) (now next: nat) (myt: thread_id),\n      (ticket_lock_inv_tks tks)\n        ∗\n        (ticket_lock_inv_mem mem now next myt)\n        ∗\n        (ticket_lock_inv_state mem own tks)\n        ∗\n        (((⌜own = true⌝)\n            ∗ (ticket_lock_inv_locked l tks now next myt)\n         )\n         ∨\n           ((⌜own = false⌝)\n              ∗ ((ticket_lock_inv_unlocking l tks now next myt)\n                 ∨\n                   ((ticket_lock_inv_unlocked0 l tks now next myt)\n                    ∨\n                      (ticket_lock_inv_unlocked1 l tks now next myt))\n                )\n        ))\n  .\n\n  Let I: list iProp := [ticket_lock_inv].\n\n  (* Properties *)\n  Lemma unlocking_mono\n        l tks now next myt:\n    (ticket_lock_inv_unlocking l tks now next myt)\n      -∗\n      ((⌜tkqueue l tks (S now) next⌝)\n         ∗\n         (∃ k o, (monoWhite monok mypreord (now, Tkst.d k))\n                   ∗ (ObligationRA.black k o)\n      )).\n  Proof.\n    iIntros \"I\". iDestruct \"I\" as \"[_ [%I2 [_ [_ I]]]]\". do 2 iDestruct \"I\" as \"[% I]\".\n    iDestruct \"I\" as \"[MB [OB _]]\". iPoseProof (black_white with \"MB\") as \"#MYTURN\".\n    iSplit. auto. iExists k, o. iFrame. auto.\n  Qed.\n\n  Lemma unlocking_contra\n        tid l tks now next myt\n        (FIND: NatMap.find tid tks = Some now)\n    :\n    (ticket_lock_inv_unlocking l tks now next myt)\n      -∗ ⌜False⌝.\n  Proof.\n    iIntros \"I\". iDestruct \"I\" as \"[_ [%I2 [_ [_ _]]]]\". exfalso.\n    hexploit (tkqueue_val_range_l I2 _ FIND). i. lia.\n  Qed.\n\n  Lemma unlocking_myturn\n        tid l tks now next myt\n        mytk o\n        (FIND: NatMap.find tid tks = Some mytk)\n    :\n    (monoWhite monok mypreord (mytk, o))\n      -∗\n      (ticket_lock_inv_unlocking l tks now next myt)\n      -∗ ⌜False⌝.\n  Proof.\n    iIntros \"MYT I\". iDestruct \"I\" as \"[_ [%I2 [_ [_ I3]]]]\".\n    do 2 (iDestruct \"I3\" as \"[% I3]\"). iDestruct \"I3\" as \"[I3 _]\".\n    iPoseProof (black_white_compare with \"MYT I3\") as \"%LE\". exfalso.\n    hexploit (tkqueue_val_range_l I2 _ FIND). i. inv LE; try lia.\n  Qed.\n\n  Lemma unlocked0_contra\n        tid l tks now next myt mytk\n        (FIND: NatMap.find tid tks = Some mytk)\n    :\n    (ticket_lock_inv_unlocked0 l tks now next myt)\n      -∗ ⌜False⌝.\n  Proof.\n    iIntros \"I\". iDestruct \"I\" as \"[_ [%I2 _]]\". exfalso. des; clarify.\n  Qed.\n\n  Lemma unlocked1_mono\n        l tks now next myt:\n    (ticket_lock_inv_unlocked1 l tks now next myt)\n      -∗\n      ((⌜tkqueue l tks now next⌝)\n         ∗\n         (∃ k o, (monoWhite monok mypreord (now, Tkst.b k))\n                   ∗ (ObligationRA.black k o)\n      )).\n  Proof.\n    iIntros \"I\". do 2 iDestruct \"I\" as \"[% I]\". iDestruct \"I\" as \"[_ [_ [%I3 [_ [_ I]]]]]\".\n    do 3 iDestruct \"I\" as \"[% I]\". iDestruct \"I\" as \"[MB [OB _]]\".\n    iSplit. auto. iPoseProof (black_white with \"MB\") as \"#MYTURN\". iExists k, o. iFrame. auto.\n  Qed.\n\n  Lemma unlocked1_myturn\n        tid l tks now next myt\n        mytk o\n        (FIND: NatMap.find tid tks = Some mytk)\n    :\n    (monoWhite monok mypreord (mytk, o))\n      -∗\n      (ticket_lock_inv_unlocked1 l tks now next myt)\n      -∗ ⌜now = mytk⌝.\n  Proof.\n    iIntros \"MYT I\". do 2 iDestruct \"I\" as \"[% I]\". iDestruct \"I\" as \"[_ [%I1 [%I2 [_ [_ I]]]]]\".\n    do 3 iDestruct \"I\" as \"[% I]\". iDestruct \"I\" as \"[MB _]\".\n    iPoseProof (black_white_compare with \"MYT MB\") as \"%LE\".\n    hexploit (tkqueue_val_range_l I2 _ FIND). i. inv LE; auto. lia.\n  Qed.\n\n  Lemma locked_contra\n        tid l tks now next myt\n        (FIND: NatMap.find tid tks = Some now)\n    :\n    (ticket_lock_inv_locked l tks now next myt)\n      -∗ ⌜False⌝.\n  Proof.\n    iIntros \"I\". iDestruct \"I\" as \"[_ [%I2 _]]\". exfalso.\n    hexploit (tkqueue_val_range_l I2 _ FIND). clear. i. lia.\n  Qed.\n\n  Lemma locked_myturn\n        tid l tks now next myt\n        mytk o\n        (FIND: NatMap.find tid tks = Some mytk)\n    :\n    (monoWhite monok mypreord (mytk, o))\n      -∗\n      (ticket_lock_inv_locked l tks now next myt)\n      -∗ ⌜False⌝.\n  Proof.\n    iIntros \"MYT I\". iDestruct \"I\" as \"[_ [%I2 [_ [_ [% I3]]]]]\".\n    iPoseProof (black_white_compare with \"MYT I3\") as \"%LE\". exfalso.\n    hexploit (tkqueue_val_range_l I2 _ FIND). i. inv LE; try lia.\n  Qed.\n\n  Lemma mytk_find_some tid mytk tks:\n    (OwnM (Auth.white (NatMapRALarge.singleton tid mytk: NatMapRALarge.t nat)))\n      ∗ (ticket_lock_inv_tks tks)\n      -∗ ⌜NatMap.find tid tks = Some mytk⌝.\n  Proof.\n    iIntros \"[MYTK TKS]\". iDestruct \"TKS\" as \"[TKS0 _]\".\n    iApply (NatMapRALarge_find_some with \"TKS0 MYTK\").\n  Qed.\n\n  Lemma ticket_lock_inv_mem_mono\n        mem now next myt\n    :\n    (ticket_lock_inv_mem mem now next myt)\n      -∗\n      (monoWhite tk_mono Nat.le_preorder now).\n  Proof.\n    iIntros \"MEM\". iDestruct \"MEM\" as \"[MEM0 [MEM1 [MEM2 [MEM3 MEM4]]]]\".\n    iPoseProof (black_white with \"MEM4\") as \"#MONOTK\".\n    auto.\n  Qed.\n\n  (* Simulations *)\n  Lemma lock_enqueue tid:\n    ((own_thread tid)\n       ∗ (ObligationRA.duty (inl tid) [])\n    )\n      ∗\n      (∀ mytk,\n          (\n            (OwnM (Auth.white (NatMapRALarge.singleton tid mytk: NatMapRALarge.t TicketLock.tk)))\n              ∗ (maps_to tid (Auth.white (Excl.just 2: Excl.t nat)))\n          )\n          -∗\n  (stsim I tid (topset I) ibot7 ibot7\n         (λ r_src r_tgt : (), (own_thread tid ** ObligationRA.duty (inl tid) []) ** ⌜r_src = r_tgt⌝)\n         false false\n    (ITree.iter\n        (λ _ : (),\n           trigger Yield;;;\n           ` x_0 : bool * NatMap.t () <- trigger (Get id);;\n           (let (own0, _) := x_0 in if Bool.eqb own0 true then Ret (inl ()) else Ret (inr ())))\n        ();;;\n      ` x_0 : bool * NatMap.t () <- trigger (Get id);;\n      (let (_, ts0) := x_0 in\n       trigger (Put (true, NatMap.remove (elt:=()) tid ts0));;;\n       trigger\n         (Fair\n            (λ i : nat,\n               if tid_dec i tid\n               then Flag.success\n               else\n                if NatMapP.F.In_dec (NatMap.remove (elt:=()) tid ts0) i\n                then Flag.fail\n                else Flag.emp));;; trigger Yield;;; Ret ()))\n    (OMod.close_itree TicketLock.omod (SCMem.mod TicketLock.gvs)\n       (TicketLock.lock_loop (SCMem.val_nat mytk));;;\n     OMod.close_itree TicketLock.omod (SCMem.mod TicketLock.gvs) (trigger Yield))\n  )\n      )\n      ⊢\n      (stsim I tid (topset I) ibot7 ibot7\n             (fun r_src r_tgt => own_thread tid ** ObligationRA.duty (inl tid) [] ** ⌜r_src = r_tgt⌝)\n             false false\n             (AbsLock.lock_fun tt)\n             (OMod.close_itree TicketLock.omod (SCMem.mod TicketLock.gvs)\n                               (TicketLock.lock_fun tt))).\n  Proof.\n    iIntros \"[[MYTH DUTY] SIM]\".\n    unfold AbsLock.lock_fun, TicketLock.lock_fun. rred.\n    rewrite close_itree_call. rred.\n    iApply (stsim_sync with \"[DUTY]\"). msubtac. iFrame. iIntros \"DUTY _\".\n    unfold Mod.wrap_fun, SCMem.faa_fun. rred.\n    iApply stsim_tidL. lred.\n\n    iopen 0 \"I\" \"K\". do 7 iDestruct \"I\" as \"[% I]\". iDestruct \"I\" as \"[TKS [MEM [ST CASES]]]\".\n    iDestruct \"ST\" as \"[ST0 ST1]\".\n    iApply stsim_getL. iSplit. auto. ss. rewrite put_rmw. iApply (stsim_rmwL with \"ST1\"). iIntros \"ST1\".\n\n    iApply stsim_getR. iSplit. auto. rred.\n    iDestruct \"MEM\" as \"[MEM0 [MEM1 [MEM2 MEM3]]]\".\n    iPoseProof (memory_ra_faa with \"MEM0 MEM2\") as \"[% [%FAA >[MEM0 MEM2]]]\".\n    erewrite FAA. rred. unfold OMod.emb_callee. rewrite put_rmw. rred.\n    iApply (stsim_rmwR with \"ST0\"). iIntros \"ST0\". rred.\n    iApply stsim_tauR. rred.\n\n    iAssert (⌜NatMap.find tid tks = None⌝)%I as \"%FINDNONE\".\n    { destruct (NatMap.find tid tks) eqn:FIND; auto.\n      iDestruct \"TKS\" as \"[_ [_ [YTH _]]]\". iPoseProof (natmap_prop_sum_in with \"YTH\") as \"FALSE\".\n      eauto. iPoseProof (own_thread_unique with \"MYTH FALSE\") as \"%FALSE\". auto.\n    }\n\n    iDestruct \"TKS\" as \"[TKS0 [TKS1 [TKS2 TKS3]]]\".\n    set (tks' := NatMap.add tid next tks).\n    iPoseProof (NatMapRALarge_add with \"TKS0\") as \">[TKS0 MYTK]\". eauto. instantiate (1:=next).\n    iAssert (St_src (own, (key_set tks')))%I with \"[ST1]\" as \"ST1\".\n    { subst tks'. rewrite key_set_pull_add_eq. iFrame. }\n    iPoseProof ((FairRA.whites_unfold (fun id => ~ NatMap.In id tks') _ (i:=tid)) with \"TKS1\") as \"[TKS1 MYTRI]\".\n    { subst tks'. i. ss. des; clarify.\n      - ii. apply IN. destruct (tid_dec j tid); clarify.\n        apply NatMapP.F.not_find_in_iff in H; clarify. apply NatMapP.F.add_in_iff; auto.\n      - apply NatMapP.F.not_find_in_iff; auto.\n    }\n    { subst tks'. ii. apply H. apply NatMapP.F.add_in_iff. auto. }\n\n    iPoseProof ((OwnMs_unfold (fun id => ~ NatMap.In id tks') _ (i:=tid)) with \"TKS3\") as \"[TKS3 MYNUM]\".\n    { subst tks'. i. ss. des; clarify.\n      - ii. apply IN. destruct (tid_dec j tid); clarify.\n        apply NatMapP.F.not_find_in_iff in H; clarify. apply NatMapP.F.add_in_iff; auto.\n      - apply NatMapP.F.not_find_in_iff; auto.\n    }\n    { subst tks'. ii. apply H. apply NatMapP.F.add_in_iff. auto. }\n    iPoseProof (OwnM_Upd with \"MYNUM\") as \"> MYNUM\".\n    { eapply maps_to_updatable. apply Auth.auth_update.\n      instantiate (1:=Excl.just 2). instantiate (1:=Excl.just 2).\n      ii. des. ur in FRAME. des_ifs. split.\n      { ur. ss. }\n      { ur. ss. }\n    }\n    rewrite <- maps_to_res_add. iDestruct \"MYNUM\" as \"[MYNB MYNW]\".\n\n    iAssert (natmap_prop_sum tks' (λ tid0 _ : nat, own_thread tid0))%I with \"[MYTH TKS2]\" as \"TKS2\".\n    { subst tks'. iApply (natmap_prop_sum_add with \"TKS2\"). iFrame. }\n\n    iDestruct \"CASES\" as \"[[%TRUE INV] | [%FALSE INV]]\"; subst.\n    { iPoseProof (FairRA.white_mon with \"MYTRI\") as \">MYTRI\".\n      { instantiate (1:=Ord.from_nat (next - (S now))). ss.\n        apply Ord.lt_le. apply Ord.omega_upperbound.\n      }\n      iMod (\"K\" with \"[DUTY TKS0 TKS1 TKS2 TKS3 MEM0 MEM1 MEM2 MEM3 INV ST0 ST1 MYTRI MYNB]\") as \"_\".\n      { subst tks'. unfold ticket_lock_inv.\n        iExists m1, true, (l ++ [tid]), (NatMap.add tid next tks), now, (S next), myt.\n        iFrame.\n        iSplitL \"MEM2\".\n        { ss. replace (S next) with (next + 1). iFrame. lia. }\n        iLeft. iSplit; auto. unfold ticket_lock_inv_locked.\n        iDestruct \"INV\" as \"[INV0 [INV1 [INV2 [INV3 INV4]]]]\". iFrame.\n        iSplit.\n        { iPure \"INV1\" as ?. iPureIntro. apply tkqueue_enqueue; auto. }\n        iPoseProof (natmap_prop_sum_add with \"INV2 MYTRI\") as \"INV2\". iFrame.\n        iApply list_prop_sum_add. iFrame. iExists 2. iFrame.\n      }\n      iApply stsim_reset. iApply \"SIM\". iFrame.\n    }\n\n    iDestruct \"INV\" as \"[INV | INV]\".\n    { iPoseProof (FairRA.white_mon with \"MYTRI\") as \">MYTRI\".\n      { instantiate (1:=Ord.from_nat (next - (S now))). ss.\n        apply Ord.lt_le. apply Ord.omega_upperbound.\n      }\n      iMod (\"K\" with \"[DUTY TKS0 TKS1 TKS2 TKS3 MEM0 MEM1 MEM2 MEM3 INV ST0 ST1 MYTRI MYNB]\") as \"_\".\n      { subst tks'. unfold ticket_lock_inv.\n        iExists m1, false, (l ++ [tid]), (NatMap.add tid next tks), now, (S next), myt.\n    remember ((⌜false = true⌝ **\n     ticket_lock_inv_locked (l ++ [tid]) (NatMap.add tid next tks) now (S next) myt)\n    ∨ (⌜false = false⌝ **\n       ticket_lock_inv_unlocking (l ++ [tid]) (NatMap.add tid next tks) now (S next) myt\n       ∨ ticket_lock_inv_unlocked0 (l ++ [tid]) (NatMap.add tid next tks) now (S next) myt\n         ∨ ticket_lock_inv_unlocked1 (l ++ [tid]) (NatMap.add tid next tks) now (S next) myt))%I as temp.\n        iFrame. subst temp.\n        iSplitL \"MEM2\".\n        { ss. replace (S next) with (next + 1). iFrame. lia. }\n        iRight. iSplit; auto. iLeft. unfold ticket_lock_inv_unlocking.\n        iDestruct \"INV\" as \"[INV0 [INV1 [INV2 [INV3 INV4]]]]\". iFrame.\n        iSplit.\n        { iPure \"INV1\" as ?. iPureIntro. apply tkqueue_enqueue; auto. }\n        iPoseProof (natmap_prop_sum_add with \"INV2 MYTRI\") as \"INV2\". iFrame.\n        iApply list_prop_sum_add. iFrame. iExists 2. iFrame.\n      }\n      iApply stsim_reset. iApply \"SIM\". iFrame.\n    }\n\n    iDestruct \"INV\" as \"[INV | INV]\".\n    { iPoseProof (FairRA.white_mon with \"MYTRI\") as \">MYTRI\".\n      { instantiate (1:=Ord.from_nat (next - (now))). ss.\n        apply Ord.lt_le. apply Ord.omega_upperbound.\n      }\n      iPoseProof (ObligationRA.alloc (((Ord.S Ord.O) × Ord.omega) × (Ord.from_nat 3))%ord) as \"> [% [[OBLK OWHI] OPEND]]\".\n      iPoseProof (ObligationRA.white_eq with \"OWHI\") as \"OWHI\".\n      { rewrite Ord.from_nat_S. rewrite Jacobsthal.mult_S. reflexivity. }\n      iPoseProof (ObligationRA.white_split_eq with \"OWHI\") as \"[OWHI TAX]\".\n      iPoseProof (ObligationRA.duty_alloc with \"DUTY OWHI\") as \"> DUTY\".\n      unfold ticket_lock_inv_unlocked0. iDestruct \"INV\" as \"[INV0 [% [% INV2]]]\".\n      iPoseProof ((black_updatable _ _ _ (now, Tkst.b k)) with \"INV2\") as \">INV2\".\n      { econs 2. ss. split; auto. i; ss. }\n\n      iMod (\"K\" with \"[DUTY TKS0 TKS1 TKS2 TKS3 MEM0 MEM1 MEM2 MEM3 INV0 INV2 ST0 ST1 MYTRI MYNB OBLK OPEND TAX]\") as \"_\".\n      { subst tks'. unfold ticket_lock_inv.\n        iExists m1, false, (l ++ [tid]), (NatMap.add tid next tks), now, (S next), myt.\n    remember ((⌜false = true⌝ **\n     ticket_lock_inv_locked (l ++ [tid]) (NatMap.add tid next tks) now (S next) myt)\n    ∨ (⌜false = false⌝ **\n       ticket_lock_inv_unlocking (l ++ [tid]) (NatMap.add tid next tks) now (S next) myt\n       ∨ ticket_lock_inv_unlocked0 (l ++ [tid]) (NatMap.add tid next tks) now (S next) myt\n         ∨ ticket_lock_inv_unlocked1 (l ++ [tid]) (NatMap.add tid next tks) now (S next) myt))%I as temp.\n        iFrame. subst temp.\n        iSplitL \"MEM2\".\n        { ss. replace (S next) with (next + 1). iFrame. lia. }\n        iRight. iSplit; auto. iRight. iRight.\n        unfold ticket_lock_inv_unlocked1.\n        des; clarify. ss. iExists tid, []. ss. iFrame.\n        iSplit; auto.\n        iSplit.\n        { iPureIntro. econs 2; eauto. apply NatMapP.F.add_eq_o; auto. econs 1; auto.\n          apply nm_find_none_rm_add_eq. apply NatMapP.F.empty_o.\n        }\n        iSplitR. auto. iExists k, _, 2. iFrame.\n      }\n      iApply stsim_reset. iApply \"SIM\". iFrame.\n    }\n\n    { iPoseProof (FairRA.white_mon with \"MYTRI\") as \">MYTRI\".\n      { instantiate (1:=Ord.from_nat (next - (now))). ss.\n        apply Ord.lt_le. apply Ord.omega_upperbound.\n      }\n      iMod (\"K\" with \"[DUTY TKS0 TKS1 TKS2 TKS3 MEM0 MEM1 MEM2 MEM3 INV ST0 ST1 MYTRI MYNB]\") as \"_\".\n      { subst tks'. unfold ticket_lock_inv.\n        iExists m1, false, (l ++ [tid]), (NatMap.add tid next tks), now, (S next), myt.\n    remember ((⌜false = true⌝ **\n     ticket_lock_inv_locked (l ++ [tid]) (NatMap.add tid next tks) now (S next) myt)\n    ∨ (⌜false = false⌝ **\n       ticket_lock_inv_unlocking (l ++ [tid]) (NatMap.add tid next tks) now (S next) myt\n       ∨ ticket_lock_inv_unlocked0 (l ++ [tid]) (NatMap.add tid next tks) now (S next) myt\n         ∨ ticket_lock_inv_unlocked1 (l ++ [tid]) (NatMap.add tid next tks) now (S next) myt))%I as temp.\n        iFrame. subst temp.\n        iSplitL \"MEM2\".\n        { ss. replace (S next) with (next + 1). iFrame. lia. }\n        iRight. iSplit; auto. iRight. iRight. unfold ticket_lock_inv_unlocked1.\n        do 2 iDestruct \"INV\" as \"[% INV]\".\n        iDestruct \"INV\" as \"[INV0 [% [INV2 [INV3 [INV4 INV5]]]]]\". subst.\n        iExists yourt, (waits ++ [tid]). ss. iFrame.\n        iSplit. auto.\n        iSplit.\n        { iPure \"INV2\" as ?. iPureIntro. rewrite app_comm_cons. apply tkqueue_enqueue; auto. }\n        iPoseProof (natmap_prop_sum_add with \"INV3 MYTRI\") as \"INV3\". iFrame.\n        iApply list_prop_sum_add. iFrame. iExists 2. iFrame.\n      }\n      iApply stsim_reset. iApply \"SIM\". iFrame.\n    }\n  Qed.\n\n  Lemma lock_myturn_yieldR\n        (g0 g1 : ∀ R_src R_tgt : Type,\n            (R_src → R_tgt → iProp)\n            → bool\n            → bool\n            → itree (programE _ (Mod.state AbsLock.mod)) R_src\n            → itree\n                (programE _ (OMod.closed_state TicketLock.omod (SCMem.mod TicketLock.gvs))) R_tgt\n            → iProp)\n        (ps pt: bool)\n        (src: itree (programE _ (Mod.state AbsLock.mod)) unit)\n        (tgt: itree (programE _ (OMod.closed_state TicketLock.omod (SCMem.mod TicketLock.gvs))) unit)\n        (tid mytk u: nat)\n        x\n    :\n    (\n      (OwnM (Auth.white ((NatMapRALarge.singleton tid mytk: NatMapRALarge.t TicketLock.tk))))\n        ∗ (maps_to tid (Auth.white (Excl.just (S u): Excl.t nat)))\n        ∗ (monoWhite monok mypreord (mytk, x))\n    )\n      ∗\n      (\n      ((OwnM (Auth.white ((NatMapRALarge.singleton tid mytk: NatMapRALarge.t TicketLock.tk))))\n        ∗ (maps_to tid (Auth.white (Excl.just u: Excl.t nat)))\n        ∗ (monoWhite monok mypreord (mytk, x)))\n        -∗\n  (stsim I tid (topset I) g0 g1\n    (λ r_src r_tgt : (), (own_thread tid ** ObligationRA.duty (inl tid) []) ** ⌜r_src = r_tgt⌝)\n    ps true\n    (trigger Yield;;; src)\n    (tgt))\n      )\n      ⊢\n  (stsim I tid (topset I) g0 g1\n    (λ r_src r_tgt : (), (own_thread tid ** ObligationRA.duty (inl tid) []) ** ⌜r_src = r_tgt⌝)\n    ps pt\n    (trigger Yield;;; src)\n    (trigger Yield;;; tgt)).\n  Proof.\n    iIntros \"[[MYTK [MYNW MYTURN]] SIM]\".\n    iopen 0 \"I\" \"K\". do 7 iDestruct \"I\" as \"[% I]\". iDestruct \"I\" as \"[TKS [MEM [ST CASES]]]\".\n    iPoseProof (mytk_find_some with \"[MYTK TKS]\") as \"%FIND\". iFrame.\n    iDestruct \"CASES\" as \"[[%CT I] | [%CF [I | [I | I]]]]\".\n    { iPoseProof (locked_myturn with \"MYTURN I\") as \"%FF\". eauto. inv FF. }\n    { iPoseProof (unlocking_myturn with \"MYTURN I\") as \"%FF\". eauto. inv FF. }\n    { iPoseProof (unlocked0_contra with \"I\") as \"%FF\". eauto. inv FF. }\n    iPoseProof (unlocked1_myturn with \"MYTURN I\") as \"%EQ\". eauto. subst mytk.\n    do 2 iDestruct \"I\" as \"[% I]\". iDestruct \"I\" as \"[I0 [% [%I2 [I3 [I4 I5]]]]]\".\n    do 3 iDestruct \"I5\" as \"[% I5]\". iDestruct \"I5\" as \"[I5 I6]\".\n    iDestruct \"I6\" as \"[I6 [I7 [I8 [I9 I10]]]]\".\n    hexploit (tkqueue_inv_hd I2 _ FIND). i. des.\n    inv H. symmetry in H1. inv H1.\n\n    iCombine \"I10 MYNW\" as \"MYNUM\".\n    iPoseProof (OwnM_valid with \"MYNUM\") as \"%EQ\".\n    assert (u0 = S u).\n    { clear -EQ. ur in EQ. specialize (EQ tid). unfold maps_to_res in EQ.\n      des_ifs. ur in EQ. des. rr in EQ. des. ur in EQ. des_ifs.\n    }\n    subst u0. clear EQ.\n    iPoseProof (OwnM_Upd with \"MYNUM\") as \"> MYNUM\".\n    { rewrite maps_to_res_add. eapply maps_to_updatable. eapply Auth.auth_update.\n      instantiate (1:=Excl.just u). instantiate (1:=Excl.just u).\n      ii. des. ur in FRAME. des_ifs. split; ur; ss.\n    }\n    rewrite <- maps_to_res_add. iDestruct \"MYNUM\" as \"[I10 MYNW]\".\n\n    iPoseProof (ObligationRA.white_eq with \"I9\") as \"I9\".\n    { rewrite Ord.from_nat_S. rewrite Jacobsthal.mult_S. reflexivity. }\n    iPoseProof (ObligationRA.white_split_eq with \"I9\") as \"[TAX I9]\".\n    iApply (stsim_yieldR_strong with \"[I8 TAX]\").\n    { iFrame. iApply ObligationRA.tax_cons_fold. iFrame. }\n    iIntros \"I8 _\".\n    iMod (\"K\" with \"[TKS MEM ST I0 I3 I4 I5 I6 I7 I8 I9 I10]\") as \"_\".\n    { iExists mem, false, (tid :: tl), tks, now, next, myt.\n      remember (\n          (⌜false = true⌝ ** ticket_lock_inv_locked (tid :: tl) tks now next myt)\n          ∨ (⌜false = false⌝ **\n                           ticket_lock_inv_unlocking (tid :: tl) tks now next myt\n             ∨ ticket_lock_inv_unlocked0 (tid :: tl) tks now next myt\n             ∨ ticket_lock_inv_unlocked1 (tid :: tl) tks now next myt))%I as temp.\n      iFrame. subst temp.\n      iRight. iSplit. auto. iRight. iRight.\n      iExists tid, tl. iFrame. iSplit. auto. iSplit. auto.\n      iExists k, o, u. iFrame.\n    }\n    iModIntro. iApply \"SIM\". iFrame.\n  Qed.\n\n  Lemma lock_yourturn_yieldR\n        (g0 g1 : ∀ R_src R_tgt : Type,\n            (R_src → R_tgt → iProp)\n            → bool\n            → bool\n            → itree (programE _ (Mod.state AbsLock.mod)) R_src\n            → itree\n                (programE _ (OMod.closed_state TicketLock.omod (SCMem.mod TicketLock.gvs))) R_tgt\n            → iProp)\n        (ps pt: bool)\n        (src: itree (programE _ (Mod.state AbsLock.mod)) unit)\n        (tgt: itree (programE _ (OMod.closed_state TicketLock.omod (SCMem.mod TicketLock.gvs))) unit)\n        (tid mytk now: nat)\n        tks mem next l myt own\n        (NEQ: mytk <> now)\n    :\n  (OwnM (Auth.white (NatMapRALarge.singleton tid mytk: NatMapRALarge.t nat)) **\n    (ticket_lock_inv_tks tks **\n     (ticket_lock_inv_mem mem now next myt **\n      (ticket_lock_inv_state mem own tks **\n       ((⌜own = true⌝ ** ticket_lock_inv_locked l tks now next myt)\n        ∨ (⌜own = false⌝ **\n           ticket_lock_inv_unlocking l tks now next myt\n           ∨ ticket_lock_inv_unlocked0 l tks now next myt\n             ∨ ticket_lock_inv_unlocked1 l tks now next myt) **\n        (ticket_lock_inv -*\n         MUpd (nth_default True%I I)\n           (fairI (ident_tgt:=OMod.closed_ident TicketLock.omod (SCMem.mod TicketLock.gvs))) []\n           [0] True))))))\n      ∗\n      (((OwnM (Auth.white ((NatMapRALarge.singleton tid mytk: NatMapRALarge.t nat))))\n          ∗ (FairRA.white_thread (_Id:=_)))\n        -∗\n  (stsim I tid (topset I) g0 g1\n    (λ r_src r_tgt : (), (own_thread tid ** ObligationRA.duty (inl tid) []) ** ⌜r_src = r_tgt⌝)\n    ps true\n    (trigger Yield;;; src)\n    (tgt))\n      )\n      ⊢\n  (stsim I tid [] g0 g1\n    (λ r_src r_tgt : (), (own_thread tid ** ObligationRA.duty (inl tid) []) ** ⌜r_src = r_tgt⌝)\n    ps pt\n    (trigger Yield;;; src)\n    (trigger Yield;;; tgt)).\n  Proof.\n    iIntros \"[[MYTH [TKS [MEM [ST [CASES K]]]]] SIM]\".\n    iPoseProof (mytk_find_some with \"[MYTH TKS]\") as \"%FIND\". iFrame.\n    iDestruct \"CASES\" as \"[[CT INV]|[CF INV]]\".\n    { unfold ticket_lock_inv_locked. iDestruct \"INV\" as \"[INV0 [%INV1 [INV2 [INV3 INV4]]]]\".\n      hexploit (tkqueue_find_in INV1 _ FIND). i.\n      iPoseProof (list_prop_sum_in_split with \"INV3\") as \"[[DUTY MAPS] INV3]\". eapply H.\n      iApply (stsim_yieldR_strong with \"[DUTY]\"). iFrame. iIntros \"DUTY RIGHT\".\n      iMod (\"K\" with \"[TKS MEM ST CT INV0 INV2 INV4 MAPS INV3 DUTY]\") as \"_\".\n      { iExists mem, own, l, tks, now, next, myt.\n        remember \n    ((⌜own = true⌝ ** ticket_lock_inv_locked l tks now next myt)\n    ∨ (⌜own = false⌝ **\n       ticket_lock_inv_unlocking l tks now next myt\n       ∨ ticket_lock_inv_unlocked0 l tks now next myt\n       ∨ ticket_lock_inv_unlocked1 l tks now next myt))%I as temp. iFrame. subst temp.\n        iLeft. iSplit. auto. iFrame. iSplit. auto. iApply \"INV3\". iFrame.\n      }\n      iModIntro. iApply \"SIM\". iFrame.\n    }\n    iDestruct \"INV\" as \"[INV | [INV | INV]]\".\n    { iDestruct \"INV\" as \"[INV0 [%INV1 [INV2 [INV3 INV4]]]]\".\n      hexploit (tkqueue_find_in INV1 _ FIND). i.\n      iPoseProof (list_prop_sum_in_split with \"INV3\") as \"[[DUTY MAPS] INV3]\". eapply H.\n      iApply (stsim_yieldR_strong with \"[DUTY]\"). iFrame. iIntros \"DUTY RIGHT\".\n      iMod (\"K\" with \"[TKS MEM ST CF INV0 INV2 INV4 MAPS INV3 DUTY]\") as \"_\".\n      { iExists mem, own, l, tks, now, next, myt.\n        remember \n    ((⌜own = true⌝ ** ticket_lock_inv_locked l tks now next myt)\n    ∨ (⌜own = false⌝ **\n       ticket_lock_inv_unlocking l tks now next myt\n       ∨ ticket_lock_inv_unlocked0 l tks now next myt\n       ∨ ticket_lock_inv_unlocked1 l tks now next myt))%I as temp. iFrame. subst temp.\n        iRight. iSplit. auto. iLeft. iFrame. iSplit. auto. iApply \"INV3\". iFrame.\n      }\n      iModIntro. iApply \"SIM\". iFrame.\n    }\n    { iDestruct \"INV\" as \"[INV0 [%INV1 INV2]]\". exfalso. des; clarify. }\n    { do 2 iDestruct \"INV\" as \"[% INV]\".\n      iDestruct \"INV\" as \"[INV0 [%INV1 [%INV2 [INV3 [INV4 INV5]]]]]\".\n      hexploit (tkqueue_dequeue INV2). eapply INV1. i.\n      assert (NOTMT: tid <> yourt).\n      { ii. clarify. inv INV2; ss. clarify. } (* setoid_rewrite FIND in FIND0. inv FIND0. ss. } *)\n      hexploit (tkqueue_find_in H).\n      { instantiate (1:=mytk). instantiate (1:=tid). rewrite nm_find_rm_neq; auto. }\n      intro IN.\n      iPoseProof (list_prop_sum_in_split with \"INV4\") as \"[[DUTY MAPS] INV4]\". eapply IN.\n      iApply (stsim_yieldR_strong with \"[DUTY]\"). iFrame. iIntros \"DUTY RIGHT\".\n      iMod (\"K\" with \"[TKS MEM ST CF INV0 INV3 INV5 MAPS INV4 DUTY]\") as \"_\".\n      { iExists mem, own, l, tks, now, next, myt.\n        remember \n    ((⌜own = true⌝ ** ticket_lock_inv_locked l tks now next myt)\n    ∨ (⌜own = false⌝ **\n       ticket_lock_inv_unlocking l tks now next myt\n       ∨ ticket_lock_inv_unlocked0 l tks now next myt\n       ∨ ticket_lock_inv_unlocked1 l tks now next myt))%I as temp. iFrame. subst temp.\n        iRight. iSplit. auto. iRight. iRight. iFrame. iExists yourt, waits.\n        iSplit. auto. iSplit. auto. iFrame. iApply \"INV4\". iFrame.\n      }\n      iModIntro. iApply \"SIM\". iFrame.\n    }\n  Qed.\n\n  Lemma lock_myturn0\n        (g0 g1 : ∀ R_src R_tgt : Type,\n            (R_src → R_tgt → iProp)\n            → bool\n            → bool\n            → itree (programE _ (Mod.state AbsLock.mod)) R_src\n            → itree (programE _ (OMod.closed_state TicketLock.omod (SCMem.mod TicketLock.gvs))) R_tgt → iProp)\n        (ps pt: bool)\n        (tid : nat)\n        (mytk : TicketLock.tk)\n        x tx\n        (TX: 1 <= tx)\n    :\n    ((monoWhite monok mypreord (mytk, x))\n       ∗ (OwnM (Auth.white (NatMapRALarge.singleton tid mytk: NatMapRALarge.t nat)))\n       ∗ (maps_to tid (Auth.white (Excl.just tx: Excl.t nat))))\n  ⊢ stsim I tid (topset I) g0 g1\n      (λ r_src r_tgt : (), (own_thread tid ** ObligationRA.duty (inl tid) []) ** ⌜r_src = r_tgt⌝)\n      ps pt\n      (trigger Yield;;;\n       ` x : () + () <-\n       (` x_0 : bool * NatMap.t () <- trigger (Get id);;\n        (let (own0, _) := x_0 in if Bool.eqb own0 true then Ret (inl ()) else Ret (inr ())));;\n       match x with\n       | inl l0 =>\n           tau;; ITree.iter\n                   (λ _ : (),\n                      trigger Yield;;;\n                      ` x_0 : bool * NatMap.t () <- trigger (Get id);;\n                      (let (own0, _) := x_0 in\n                       if Bool.eqb own0 true then Ret (inl ()) else Ret (inr ()))) l0\n       | inr r0 => Ret r0\n       end;;;\n       ` x_0 : bool * NatMap.t () <- trigger (Get id);;\n       (let (_, ts0) := x_0 in\n        trigger (Put (true, NatMap.remove (elt:=()) tid ts0));;;\n        trigger\n          (Fair\n             (λ i : nat,\n                if tid_dec i tid\n                then Flag.success\n                else\n                 if NatMapP.F.In_dec (NatMap.remove (elt:=()) tid ts0) i\n                 then Flag.fail\n                 else Flag.emp));;; trigger Yield;;; Ret ()))\n      (` r : Any.t <-\n       map_event (OMod.emb_callee TicketLock.omod (SCMem.mod TicketLock.gvs))\n         (Mod.wrap_fun SCMem.load_fun (Any.upcast TicketLock.now_serving));;\n       ` x : SCMem.val <- (tau;; unwrap (Any.downcast r));;\n       OMod.close_itree TicketLock.omod (SCMem.mod TicketLock.gvs)\n         (` b : bool <- OMod.call \"compare\" (x, SCMem.val_nat mytk);;\n          (if b then Ret () else tau;; TicketLock.lock_loop (SCMem.val_nat mytk)));;;\n         OMod.close_itree TicketLock.omod (SCMem.mod TicketLock.gvs) (trigger Yield)).\n  Proof.\n    iIntros \"[#MYTN [MYTK MYNU]]\". \n    iopen 0 \"I\" \"K\". do 7 iDestruct \"I\" as \"[% I]\". iDestruct \"I\" as \"[TKS [MEM [ST CASES]]]\".\n    iPoseProof (mytk_find_some with \"[MYTK TKS]\") as \"%FIND\". iFrame.\n    iDestruct \"CASES\" as \"[[%CT I] | [%CF [I | [I | I]]]]\".\n    { iPoseProof (locked_myturn with \"MYTN I\") as \"%FF\". eauto. inv FF. }\n    { iPoseProof (unlocking_myturn with \"MYTN I\") as \"%FF\". eauto. inv FF. }\n    { iPoseProof (unlocked0_contra with \"I\") as \"%FF\". eauto. inv FF. }\n    iPoseProof (unlocked1_myturn with \"MYTN I\") as \"%EQ\". eauto. subst now.\n\n    unfold Mod.wrap_fun, SCMem.load_fun. rred.\n    iDestruct \"MEM\" as \"[MEM0 [MEM1 [MEM2 MEM3]]]\". iDestruct \"ST\" as \"[ST0 ST1]\".\n    iApply stsim_getR. iSplit. eauto. rred.\n    iPoseProof (memory_ra_load with \"MEM0 MEM1\") as \"%LOAD\". des. rewrite LOAD. rred.\n    iApply stsim_tauR. rred.\n    rewrite close_itree_call. rred.\n\n    iMod (\"K\" with \"[TKS MEM0 MEM1 MEM2 MEM3 ST0 ST1 I]\") as \"_\".\n    { iExists mem, own, l, tks, mytk, next, myt. iFrame. iRight. iSplit; auto. }\n    clear pt mem own l tks next myt FIND CF LOAD LOAD0.\n    assert (exists tx0, tx = S tx0).\n    { inv TX; eauto. }\n    des. subst tx.\n    iApply lock_myturn_yieldR. iSplitL. iFrame. auto.\n    iIntros \"[MYTK [MYNUM _]]\". rred.\n\n    iopen 0 \"I\" \"K\". do 7 iDestruct \"I\" as \"[% I]\". iDestruct \"I\" as \"[TKS [MEM [ST CASES]]]\".\n    iPoseProof (mytk_find_some with \"[MYTK TKS]\") as \"%FIND\". iFrame.\n    iDestruct \"CASES\" as \"[[%CT I] | [%CF [I | [I | I]]]]\".\n    { iPoseProof (locked_myturn with \"MYTN I\") as \"%FF\". eauto. inv FF. }\n    { iPoseProof (unlocking_myturn with \"MYTN I\") as \"%FF\". eauto. inv FF. }\n    { iPoseProof (unlocked0_contra with \"I\") as \"%FF\". eauto. inv FF. }\n    iPoseProof (unlocked1_myturn with \"MYTN I\") as \"%EQ\". eauto. subst now.\n\n    unfold Mod.wrap_fun, SCMem.compare_fun. rred.\n    iDestruct \"MEM\" as \"[MEM0 [MEM1 [MEM2 MEM3]]]\". iDestruct \"ST\" as \"[ST0 ST1]\".\n    iApply stsim_getR. iSplit. eauto. rred.\n    iApply stsim_tauR. rred.\n    destruct (Nat.eq_dec mytk mytk).\n    2:{ exfalso. auto. }\n    clear e. subst. rred.\n\n    iApply stsim_yieldL. lred.\n    iApply stsim_getL. iSplit. auto. lred.\n    iApply stsim_getL. iSplit. auto. ss. rewrite put_rmw.\n    iApply (stsim_rmwL with \"ST1\"). iIntros \"ST1\".\n\n    remember (NatMap.remove tid tks) as tks'.\n    rewrite <- key_set_pull_rm_eq. rewrite <- Heqtks'.\n    iAssert (ticket_lock_inv_state mem true tks')%I with \"[ST0 ST1]\" as \"ST\". iFrame.\n    iAssert (ticket_lock_inv_mem mem mytk next myt)%I with \"[MEM0 MEM1 MEM2 MEM3]\" as \"MEM\". iFrame.\n    iDestruct \"TKS\" as \"[TKS0 [TKS1 [TKS2 TKS3]]]\".\n    do 2 iDestruct \"I\" as \"[% I]\". iDestruct \"I\" as \"[I0 [% [%I2 [I3 [I4 I5]]]]]\".\n    do 3 iDestruct \"I5\" as \"[% I5]\". iDestruct \"I5\" as \"[I5 [I6 [I7 [I8 [I9 I10]]]]]\".\n    hexploit (tkqueue_inv_hd I2 _ FIND). i. des.\n    subst l. inversion H0; clear H0. subst yourt waits.\n\n    iPoseProof (NatMapRALarge_remove with \"TKS0 MYTK\") as \">TKS0\". rewrite <- Heqtks'.\n    iPoseProof (natmap_prop_remove_find with \"TKS2\") as \"[MYTH TKS2]\". eauto. rewrite <- Heqtks'.\n    iCombine \"I10 MYNUM\" as \"MYNUM\". rewrite maps_to_res_add.\n    iPoseProof (OwnM_Upd with \"MYNUM\") as \"> MYNUM\".\n    { eapply maps_to_updatable. apply Auth.auth_update.\n      instantiate (1:=Excl.just 0). instantiate (1:=Excl.just 0).\n      ii. des. ur in FRAME. des_ifs. split; ur; ss.\n    }\n    iPoseProof (OwnMs_fold with \"[TKS3 MYNUM]\") as \"TKS3\".\n    2:{ iSplitL \"TKS3\". iFrame. iFrame. }\n    { instantiate (1:= fun id => ~ NatMap.In id tks'). i. ss. subst tks'.\n      destruct (tid_dec j tid); auto. left. ii. apply IN.\n      rewrite NatMapP.F.remove_neq_in_iff; auto.\n    }\n\n    iClear \"I6 I9\". iPoseProof (ObligationRA.pending_shot with \"I7\") as \">I7\".\n    iPoseProof (ObligationRA.duty_done with \"I8 I7\") as \">DUTY\".\n    iPoseProof (black_updatable with \"I5\") as \">I5\".\n    { instantiate (1:=(mytk, Tkst.c k)). econs 2. ss. split; ss. lia. }\n    hexploit (tkqueue_dequeue I2).\n    { reflexivity. }\n    i. rename I2 into I2Old, H into I2. (* unfold TicketLock.tk in I2. *) rewrite <- Heqtks' in I2.\n    iPoseProof (natmap_prop_remove with \"I3\") as \"I3\". rewrite <- Heqtks'.\n\n    iPoseProof (natmap_prop_sum_impl with \"I3\") as \"I3\".\n    { instantiate (1:= fun th tk =>\n                         ((FairRA.white th (Ord.from_nat (tk - (S mytk))))\n                            ∗ (FairRA.white th Ord.one))%I).\n      i. ss. iIntros \"WHI\". erewrite FairRA.white_eq.\n      2:{ instantiate (1:= (OrderedCM.add (Ord.from_nat (a - (S mytk))) (Ord.one))).\n          rewrite <- Ord.from_nat_1. ss. rewrite <- Hessenberg.add_from_nat. rr. ss.\n          hexploit (tkqueue_val_range_l I2 _ IN). i. split.\n          { apply OrdArith.le_from_nat. lia. }\n          { apply OrdArith.le_from_nat. lia. }\n      }\n      iPoseProof (FairRA.white_split with \"WHI\") as \"[WHI1 WHI2]\". iFrame.\n    }\n    iPoseProof (natmap_prop_sepconj_sum with \"I3\") as \"[I3 TAX]\".\n\n    iApply (stsim_fairL with \"[TAX]\").\n    { i. ss. instantiate (1:= (NatSet.elements (key_set tks'))). des_ifs. \n      eapply NatSetIn_In. auto.\n    }\n    { instantiate (1:=[tid]). i; ss. des; clarify. des_ifs. }\n    { unfold natmap_prop_sum. unfold NatSet.elements. unfold nm_proj1.\n      unfold key_set. rewrite <- list_map_elements_nm_map. unfold unit1. rewrite List.map_map.\n      iPoseProof (list_prop_sum_map with \"TAX\") as \"TAX\".\n      2: iFrame.\n      ss. i. destruct a; ss.\n    }\n    instantiate (1:= Ord.omega). iIntros \"[MYW _]\".\n    iPoseProof (FairRA.whites_fold with \"[TKS1 MYW]\") as \"TKS1\".\n    2:{ iSplitL \"TKS1\". iFrame. iFrame. }\n    { instantiate (1:= fun id => ~ NatMap.In id tks'). ss. i. destruct (tid_dec j tid); auto.\n      left. ii. apply IN. subst tks'. rewrite NatMapP.F.remove_neq_in_iff; auto.\n    }\n\n    iMod (\"K\" with \"[I0 I4 ST MEM TKS0 TKS2 TKS3 I5 I3 TKS1]\") as \"_\".\n    { iExists mem, true, tl, tks', mytk, next, myt.\n      remember \n    ((⌜true = true⌝ ** ticket_lock_inv_locked tl tks' mytk next myt)\n    ∨ (⌜true = false⌝ **\n       ticket_lock_inv_unlocking tl tks' mytk next myt\n       ∨ ticket_lock_inv_unlocked0 tl tks' mytk next myt\n       ∨ ticket_lock_inv_unlocked1 tl tks' mytk next myt))%I as temp.\n      iFrame. subst temp. iLeft. iSplit. auto.\n      iFrame. iSplit. auto. iExists k. iFrame.\n    }\n    iApply (stsim_sync with \"[DUTY]\"). msubtac. iFrame.\n    iIntros \"DUTY _\". rred.\n    iApply stsim_tauR. iApply stsim_ret. iModIntro. iFrame. auto.\n\n  Qed.\n\n  Lemma lock_myturn1\n        (g0 g1 : ∀ R_src R_tgt : Type,\n            (R_src → R_tgt → iProp)\n            → bool\n            → bool\n            → itree (programE _ (Mod.state AbsLock.mod)) R_src\n            → itree (programE _ (OMod.closed_state TicketLock.omod (SCMem.mod TicketLock.gvs))) R_tgt → iProp)\n        (ps pt: bool)\n        (tid : nat)\n        (mytk : TicketLock.tk)\n        (mem : SCMem.t)\n        (own : bool)\n        (l : list nat)\n        (tks : NatMap.t nat)\n        (next myt : nat)\n    :\n  (OwnM (Auth.white (NatMapRALarge.singleton tid mytk: NatMapRALarge.t nat)) **\n   (maps_to tid (Auth.white (Excl.just 2: Excl.t nat)) **\n    (ticket_lock_inv_tks tks **\n     (ticket_lock_inv_mem mem mytk next myt **\n      (ticket_lock_inv_state mem own tks **\n       ((⌜own = true⌝ ** ticket_lock_inv_locked l tks mytk next myt)\n        ∨ (⌜own = false⌝ **\n           ticket_lock_inv_unlocking l tks mytk next myt\n           ∨ ticket_lock_inv_unlocked0 l tks mytk next myt\n             ∨ ticket_lock_inv_unlocked1 l tks mytk next myt) **\n        (ticket_lock_inv -*\n         MUpd (nth_default True%I I)\n           (fairI (ident_tgt:=OMod.closed_ident TicketLock.omod (SCMem.mod TicketLock.gvs))) []\n           [0] True)))))))\n  ⊢ (stsim I tid [] g0 g1\n      (λ r_src r_tgt : (), (own_thread tid ** ObligationRA.duty (inl tid) []) ** ⌜r_src = r_tgt⌝)\n      ps pt\n      (trigger Yield;;;\n       ` x : () + () <-\n       (` x_0 : bool * NatMap.t () <- trigger (Get id);;\n        (let (own0, _) := x_0 in if Bool.eqb own0 true then Ret (inl ()) else Ret (inr ())));;\n       match x with\n       | inl l0 =>\n           tau;; ITree.iter\n                   (λ _ : (),\n                      trigger Yield;;;\n                      ` x_0 : bool * NatMap.t () <- trigger (Get id);;\n                      (let (own0, _) := x_0 in\n                       if Bool.eqb own0 true then Ret (inl ()) else Ret (inr ()))) l0\n       | inr r0 => Ret r0\n       end;;;\n       ` x_0 : bool * NatMap.t () <- trigger (Get id);;\n       (let (_, ts0) := x_0 in\n        trigger (Put (true, NatMap.remove (elt:=()) tid ts0));;;\n        trigger\n          (Fair\n             (λ i : nat,\n                if tid_dec i tid\n                then Flag.success\n                else\n                 if NatMapP.F.In_dec (NatMap.remove (elt:=()) tid ts0) i\n                 then Flag.fail\n                 else Flag.emp));;; trigger Yield;;; Ret ()))\n      (trigger Yield;;;\n       ` x : SCMem.val <-\n       (` rv : Any.t <-\n        map_event (OMod.emb_callee TicketLock.omod (SCMem.mod TicketLock.gvs))\n          (Mod.wrap_fun SCMem.load_fun (Any.upcast TicketLock.now_serving));;\n        (tau;; unwrap (Any.downcast rv)));;\n       OMod.close_itree TicketLock.omod (SCMem.mod TicketLock.gvs)\n         (` b : bool <- OMod.call \"compare\" (x, SCMem.val_nat mytk);;\n          (if b then Ret () else tau;; TicketLock.lock_loop (SCMem.val_nat mytk)));;;\n         OMod.close_itree TicketLock.omod (SCMem.mod TicketLock.gvs) (trigger Yield))).\n  Proof.\n    iIntros \"[MYTK [MYN [TKS [MEM [ST [CASES K]]]]]]\".\n    iAssert (⌜NatMap.find tid tks = Some mytk⌝)%I as \"%FIND\".\n    { iDestruct \"TKS\" as \"[TKS0 _]\". iApply (NatMapRALarge_find_some with \"TKS0 MYTK\"). }\n    iDestruct \"CASES\" as \"[[%CT I] | [%CF [I | [I | I]]]]\".\n    { iPoseProof (locked_contra with \"I\") as \"%F\". eauto. inv F. }\n    { iPoseProof (unlocking_contra with \"I\") as \"%F\". eauto. inv F. }\n    { iPoseProof (unlocked0_contra with \"I\") as \"%F\". eauto. inv F. }\n    iPoseProof (unlocked1_mono with \"I\") as \"[%TKQ #MYMW]\".\n    iDestruct \"MYMW\" as \"[% [% [MYMW _]]]\".\n    iMod (\"K\" with \"[TKS MEM ST I]\") as \"_\".\n    { iExists mem, own, l, tks, mytk, next, myt. iFrame. iRight. iSplit; auto. }\n    iApply lock_myturn_yieldR. iSplitL. iFrame. auto.\n    iIntros \"[MYTK [MYN _]]\". rred.\n    iApply lock_myturn0. 2: iFrame; auto. lia.\n  Qed.\n\n  Lemma lock_myturn2\n        (g0 g1 : ∀ R_src R_tgt : Type,\n            (R_src → R_tgt → iProp)\n            → bool\n            → bool\n            → itree (programE _(Mod.state AbsLock.mod)) R_src\n            → itree (programE _ (OMod.closed_state TicketLock.omod (SCMem.mod TicketLock.gvs))) R_tgt → iProp)\n        (ps pt: bool)\n        (tid : nat)\n        (mytk : TicketLock.tk)\n        (mem : SCMem.t)\n        (own : bool)\n        (l : list nat)\n        (tks : NatMap.t nat)\n        (next myt : nat)\n        now_old\n        (NEQ: mytk <> now_old)\n    :\n  (OwnM (Auth.white (NatMapRALarge.singleton tid mytk: NatMapRALarge.t nat)) **\n   (maps_to tid (Auth.white (Excl.just 2: Excl.t nat)) **\n    (ticket_lock_inv_tks tks **\n     (ticket_lock_inv_mem mem mytk next myt **\n      (ticket_lock_inv_state mem own tks **\n       ((⌜own = true⌝ ** ticket_lock_inv_locked l tks mytk next myt)\n        ∨ (⌜own = false⌝ **\n           ticket_lock_inv_unlocking l tks mytk next myt\n           ∨ ticket_lock_inv_unlocked0 l tks mytk next myt\n             ∨ ticket_lock_inv_unlocked1 l tks mytk next myt) **\n        (ticket_lock_inv -*\n         MUpd (nth_default True%I I)\n           (fairI (ident_tgt:=OMod.closed_ident TicketLock.omod (SCMem.mod TicketLock.gvs))) []\n           [0] True)))))))\n  ⊢ (stsim I tid [] g0 g1\n    (λ r_src r_tgt : (), (own_thread tid ** ObligationRA.duty (inl tid) []) ** ⌜r_src = r_tgt⌝)\n    ps pt\n    (trigger Yield;;;\n     ` x : () + () <-\n     (` x_0 : bool * NatMap.t () <- trigger (Get id);;\n      (let (own0, _) := x_0 in if Bool.eqb own0 true then Ret (inl ()) else Ret (inr ())));;\n     match x with\n     | inl l0 =>\n         tau;; ITree.iter\n                 (λ _ : (),\n                    trigger Yield;;;\n                    ` x_0 : bool * NatMap.t () <- trigger (Get id);;\n                    (let (own0, _) := x_0 in\n                     if Bool.eqb own0 true then Ret (inl ()) else Ret (inr ()))) l0\n     | inr r0 => Ret r0\n     end;;;\n     ` x_0 : bool * NatMap.t () <- trigger (Get id);;\n     (let (_, ts0) := x_0 in\n      trigger (Put (true, NatMap.remove (elt:=()) tid ts0));;;\n      trigger\n        (Fair\n           (λ i : nat,\n              if tid_dec i tid\n              then Flag.success\n              else\n               if NatMapP.F.In_dec (NatMap.remove (elt:=()) tid ts0) i\n               then Flag.fail\n               else Flag.emp));;; trigger Yield;;; Ret ()))\n    (` r : Any.t <-\n     map_event (OMod.emb_callee TicketLock.omod (SCMem.mod TicketLock.gvs))\n       (Mod.wrap_fun SCMem.compare_fun (Any.upcast (SCMem.val_nat now_old, SCMem.val_nat mytk)));;\n     ` x : bool <- (tau;; unwrap (Any.downcast r));;\n     OMod.close_itree TicketLock.omod (SCMem.mod TicketLock.gvs)\n       (if x then Ret () else tau;; TicketLock.lock_loop (SCMem.val_nat mytk));;;\n       OMod.close_itree TicketLock.omod (SCMem.mod TicketLock.gvs) (trigger Yield))).\n  Proof.\n    iIntros \"[MYTK [MYN [TKS [MEM [ST [CASES K]]]]]]\".\n    unfold Mod.wrap_fun, SCMem.compare_fun. rred.\n    iDestruct \"MEM\" as \"[MEM0 [MEM1 [MEM2 MEM3]]]\". iDestruct \"ST\" as \"[ST0 ST1]\".\n    iApply stsim_getR. iSplit. eauto. rred.\n    iApply stsim_tauR. rred.\n    destruct (Nat.eq_dec now_old mytk).\n    { exfalso. clarify. }\n    rred. iApply stsim_tauR.\n    rewrite TicketLock.lock_loop_red. rred. rewrite close_itree_call. rred.\n    iApply lock_myturn1.\n    iSplitL \"MYTK\". iFrame. iSplitL \"MYN\". iFrame. iSplitL \"TKS\". iFrame.\n    iSplitL \"MEM0 MEM1 MEM2 MEM3\". iFrame. iSplitL \"ST0 ST1\". iFrame. iSplitL \"CASES\". iFrame.\n    iFrame.\n  Qed.\n\n  Let src_code_coind tid: itree (programE _ (Mod.state AbsLock.mod)) () :=\n          ((` lr : () + () <-\n            (trigger Yield;;;\n             ` x_0 : bool * NatMap.t () <- trigger (Get id);;\n             (let (own0, _) := x_0 in if Bool.eqb own0 true then Ret (inl ()) else Ret (inr ())));;\n            match lr with\n            | inl l0 =>\n                tau;; ITree.iter\n                        (λ _ : (),\n                           trigger Yield;;;\n                           ` x_0 : bool * NatMap.t () <- trigger (Get id);;\n                           (let (own0, _) := x_0 in\n                            if Bool.eqb own0 true then Ret (inl ()) else Ret (inr ()))) l0\n            | inr r0 => Ret r0\n            end);;;\n           ` x_0 : bool * NatMap.t () <- trigger (Get id);;\n           (let (_, ts0) := x_0 in\n            trigger (Put (true, NatMap.remove (elt:=()) tid ts0));;;\n            trigger\n              (Fair\n                 (λ i : nat,\n                    if tid_dec i tid\n                    then Flag.success\n                    else\n                     if NatMapP.F.In_dec (NatMap.remove (elt:=()) tid ts0) i\n                     then Flag.fail\n                     else Flag.emp));;; trigger Yield;;; Ret ())).\n\n  Let tgt_code_coind a :=\n          (trigger Yield;;;\n           ` x : SCMem.val <-\n           (` rv : Any.t <-\n            map_event (OMod.emb_callee TicketLock.omod (SCMem.mod TicketLock.gvs))\n              (` arg : SCMem.val <- unwrap (Any.downcast (Any.upcast TicketLock.now_serving));;\n               ` ret : SCMem.val <-\n               (` m : SCMem.t <- trigger (Get id);;\n                ` v : SCMem.val <- unwrap (SCMem.load m arg);; Ret v);; \n               Ret (Any.upcast ret));; (tau;; unwrap (Any.downcast rv)));;\n           OMod.close_itree TicketLock.omod (SCMem.mod TicketLock.gvs)\n             (` b : bool <- OMod.call \"compare\" (x, SCMem.val_nat a);;\n              (if b then Ret () else tau;; TicketLock.lock_loop (SCMem.val_nat a)));;;\n           OMod.close_itree TicketLock.omod (SCMem.mod TicketLock.gvs) (trigger Yield)).\n\n  Lemma lock_yourturn_coind\n        (g0 g1 : ∀ R_src R_tgt : Type,\n            (R_src → R_tgt → iProp)\n            → bool\n            → bool\n            → itree (programE _ (Mod.state AbsLock.mod)) R_src\n            → itree (programE _ (OMod.closed_state TicketLock.omod (SCMem.mod TicketLock.gvs))) R_tgt → iProp)\n        (ps pt: bool)\n        (tid : nat)\n        (mytk : TicketLock.tk)\n        (mem : SCMem.t)\n        (l : list nat)\n        (tks : NatMap.t nat)\n        (now next myt : nat)\n        now_old\n        (NEQ: mytk <> now_old)\n    :\n  (□ (∀ a : TicketLock.tk,\n        (OwnM (Auth.white (NatMapRALarge.singleton tid a: NatMapRALarge.t nat)) ** maps_to tid (Auth.white (Excl.just 2: Excl.t nat))) -*\n        g1 ()%type ()%type\n          (λ r_src r_tgt : (),\n              (own_thread tid ** ObligationRA.duty (inl tid) []) ** ⌜r_src = r_tgt⌝) false false\n          (src_code_coind tid)\n          (tgt_code_coind a)\n     ) **\n   (maps_to tid (Auth.white (Excl.just 2: Excl.t nat)) **\n    (OwnM (Auth.white (NatMapRALarge.singleton tid mytk: NatMapRALarge.t nat)) **\n     (ticket_lock_inv_tks tks **\n      (ticket_lock_inv_mem mem now next myt **\n       (ticket_lock_inv_state mem true tks **\n        (ticket_lock_inv_locked l tks now next myt **\n         (ticket_lock_inv -*\n          MUpd (nth_default True%I I)\n            (fairI (ident_tgt:=OMod.closed_ident TicketLock.omod (SCMem.mod TicketLock.gvs))) []\n            [0] True)))))))\n  )\n  ⊢ (stsim I tid [] g0 g1\n      (λ r_src r_tgt : (), (own_thread tid ** ObligationRA.duty (inl tid) []) ** ⌜r_src = r_tgt⌝)\n      ps pt\n      (trigger Yield;;;\n       ` x : () + () <-\n       (` x_0 : bool * NatMap.t () <- trigger (Get id);;\n        (let (own0, _) := x_0 in if Bool.eqb own0 true then Ret (inl ()) else Ret (inr ())));;\n       match x with\n       | inl l0 =>\n           tau;; ITree.iter\n                   (λ _ : (),\n                      trigger Yield;;;\n                      ` x_0 : bool * NatMap.t () <- trigger (Get id);;\n                      (let (own0, _) := x_0 in\n                       if Bool.eqb own0 true then Ret (inl ()) else Ret (inr ()))) l0\n       | inr r0 => Ret r0\n       end;;;\n       ` x_0 : bool * NatMap.t () <- trigger (Get id);;\n       (let (_, ts0) := x_0 in\n        trigger (Put (true, NatMap.remove (elt:=()) tid ts0));;;\n        trigger\n          (Fair\n             (λ i : nat,\n                if tid_dec i tid\n                then Flag.success\n                else\n                 if NatMapP.F.In_dec (NatMap.remove (elt:=()) tid ts0) i\n                 then Flag.fail\n                 else Flag.emp));;; trigger Yield;;; Ret ()))\n      (` r : Any.t <-\n       map_event (OMod.emb_callee TicketLock.omod (SCMem.mod TicketLock.gvs))\n         (Mod.wrap_fun SCMem.compare_fun (Any.upcast (SCMem.val_nat now_old, SCMem.val_nat mytk)));;\n       ` x : bool <- (tau;; unwrap (Any.downcast r));;\n       OMod.close_itree TicketLock.omod (SCMem.mod TicketLock.gvs)\n         (if x then Ret () else tau;; TicketLock.lock_loop (SCMem.val_nat mytk));;;\n       OMod.close_itree TicketLock.omod (SCMem.mod TicketLock.gvs) (trigger Yield))).\n  Proof.\n    iIntros \"[#CIH [MYTK [MYN [TKS [MEM [ST [I K]]]]]]]\".\n    unfold Mod.wrap_fun, SCMem.compare_fun. rred.\n    iDestruct \"MEM\" as \"[MEM0 [MEM1 [MEM2 MEM3]]]\". iDestruct \"ST\" as \"[ST0 ST1]\".\n    iApply stsim_getR. iSplit. eauto. rred.\n    iApply stsim_tauR. rred.\n    destruct (Nat.eq_dec now_old mytk).\n    { exfalso. clarify. }\n    rred. iApply stsim_tauR.\n    rewrite TicketLock.lock_loop_red. rred. rewrite close_itree_call. rred.\n\n    iApply stsim_yieldL. lred.\n    iApply stsim_getL. iSplit. auto. lred.\n    iApply stsim_tauL.\n    iMod (\"K\" with \"[TKS MEM0 MEM1 MEM2 MEM3 ST0 ST1 I]\") as \"_\".\n    { do 7 iExists _.\n      iSplitL \"TKS\". iFrame. iSplitL \"MEM0 MEM1 MEM2 MEM3\". iFrame.\n      iSplitL \"ST0 ST1\". iFrame.\n      iLeft. iSplit. auto. iFrame.\n    }\n    iApply stsim_progress. iApply stsim_base. msubtac.\n    rewrite unfold_iter_eq. iApply \"CIH\". iFrame.\n  Qed.\n\n  Lemma yourturn_range\n        tid tks mytk now next own l myt\n        (FIND : NatMap.find tid tks = Some mytk)\n        (NEQ : mytk ≠ now)\n    :\n    ((⌜own = true⌝ ∗ ticket_lock_inv_locked l tks now next myt)\n     ∨ (⌜own = false⌝ ∗\n                    (ticket_lock_inv_unlocking l tks now next myt\n                     ∨ ticket_lock_inv_unlocked0 l tks now next myt\n                     ∨ ticket_lock_inv_unlocked1 l tks now next myt)))\n      ⊢\n      (⌜now < mytk⌝).\n  Proof.\n    iIntros \"[[%CT I] | [%CF [I | [I | I]]]]\".\n    { iDestruct \"I\" as \"[_ [%I1 _]]\".\n      hexploit (tkqueue_val_range_l I1 _ FIND). i. iPureIntro. lia. }\n    { iDestruct \"I\" as \"[_ [%I1 _]]\".\n      hexploit (tkqueue_val_range_l I1 _ FIND). i. iPureIntro. lia. }\n    { iPoseProof (unlocked0_contra with \"I\") as \"%FF\". eauto. inv FF. }\n    { iPoseProof (unlocked1_mono with \"I\") as \"[%I1 _]\".\n      hexploit (tkqueue_val_range_l I1 _ FIND). i. iPureIntro. lia. }\n  Qed.\n\n  Let src_code_ind tid: itree (programE _ (Mod.state AbsLock.mod)) () :=\n                         (trigger Yield;;;\n                          ` x : () + () <-\n                          (` x_0 : bool * NatMap.t () <- trigger (Get id);;\n                           (let (own0, _) := x_0 in\n                            if Bool.eqb own0 true then Ret (inl ()) else Ret (inr ())));;\n                          match x with\n                          | inl l0 =>\n                              tau;; ITree.iter\n                                      (λ _ : (),\n                                         trigger Yield;;;\n                                         ` x_0 : bool * NatMap.t () <-\n                                         trigger (Get id);;\n                                         (let (own0, _) := x_0 in\n                                          if Bool.eqb own0 true\n                                          then Ret (inl ())\n                                          else Ret (inr ()))) l0\n                          | inr r0 => Ret r0\n                          end;;;\n                          ` x_0 : bool * NatMap.t () <- trigger (Get id);;\n                          (let (_, ts0) := x_0 in\n                           trigger (Put (true, NatMap.remove (elt:=()) tid ts0));;;\n                           trigger\n                             (Fair\n                                (λ i : nat,\n                                   if tid_dec i tid\n                                   then Flag.success\n                                   else\n                                    if NatMapP.F.In_dec (NatMap.remove (elt:=()) tid ts0) i\n                                    then Flag.fail\n                                    else Flag.emp));;; trigger Yield;;; Ret ())).\n\n  Let tgt_code_ind mytk now_old :=\n                         (` r : Any.t <-\n                          map_event (OMod.emb_callee TicketLock.omod (SCMem.mod TicketLock.gvs))\n                            (Mod.wrap_fun SCMem.compare_fun\n                               (Any.upcast (SCMem.val_nat now_old, SCMem.val_nat mytk)));;\n                          ` x : bool <- (tau;; unwrap (Any.downcast r));;\n                          OMod.close_itree TicketLock.omod (SCMem.mod TicketLock.gvs)\n                            (if x\n                             then Ret ()\n                             else tau;; TicketLock.lock_loop (SCMem.val_nat mytk));;;\n                          OMod.close_itree TicketLock.omod (SCMem.mod TicketLock.gvs)\n                            (trigger Yield)).\n\n  Lemma lock_yourturn_ind0\n        (g0 g1 : ∀ R_src R_tgt : Type,\n            (R_src → R_tgt → iProp)\n            → bool\n            → bool\n            → itree (programE _ (Mod.state AbsLock.mod)) R_src\n            → itree (programE _ (OMod.closed_state TicketLock.omod (SCMem.mod TicketLock.gvs))) R_tgt → iProp)\n        (tid : nat)\n        (mytk : TicketLock.tk)\n  (now : nat)\n  (LT : now < mytk)\n  (IH : ∀ y : nat,\n         y < mytk - now\n         → ∀ now_old : nat,\n             mytk ≠ now_old\n             → ∀ (mem : SCMem.t) (own : bool) (l : list nat) (tks : NatMap.t nat)\n                 (now next myt : nat),\n                 now < mytk\n                 → y = mytk - now\n                   → (□ ((∀ a : TicketLock.tk,\n                            (OwnM (Auth.white (NatMapRALarge.singleton tid a: NatMapRALarge.t nat)) **\n                             maps_to tid (Auth.white (Excl.just 2: Excl.t nat))) -*\n                            g1 ()%type ()%type\n                              (λ r_src r_tgt : (),\n                                 (own_thread tid ** ObligationRA.duty (inl tid) []) **\n                                 ⌜r_src = r_tgt⌝) false false\n                              (src_code_coind tid)\n                              (tgt_code_coind a)\n                         ) ∧ monoWhite tk_mono Nat.le_preorder now) **\n                      (maps_to tid (Auth.white (Excl.just 2: Excl.t nat)) **\n                       (OwnM (Auth.white (NatMapRALarge.singleton tid mytk: NatMapRALarge.t nat)) **\n                        (ticket_lock_inv_tks tks **\n                         (ticket_lock_inv_state mem own tks **\n                          ((⌜own = true⌝ ** ticket_lock_inv_locked l tks now next myt)\n                           ∨ (⌜own = false⌝ **\n                              ticket_lock_inv_unlocking l tks now next myt\n                              ∨ ticket_lock_inv_unlocked0 l tks now next myt\n                                ∨ ticket_lock_inv_unlocked1 l tks now next myt) **\n                           ((ticket_lock_inv -*\n                             MUpd (nth_default True%I I)\n                               (fairI\n                                  (ident_tgt:=OMod.closed_ident TicketLock.omod\n                                                (SCMem.mod TicketLock.gvs))) [] [0] True) **\n                            ticket_lock_inv_mem mem now next myt)))))))\n                     ⊢ stsim I tid [] g0 g1\n                         (λ r_src r_tgt : (),\n                            (own_thread tid ** ObligationRA.duty (inl tid) []) ** ⌜r_src = r_tgt⌝)\n                         false true\n                         (src_code_ind tid)\n                         (tgt_code_ind mytk now_old)\n  )\n  (now_old : nat)\n  (NEQ : mytk ≠ now_old)\n  (mem : SCMem.t)\n  (l : list nat)\n  (tks : NatMap.t nat)\n  (next myt : nat)\n    :\n  (□ ((∀ a : TicketLock.tk,\n        (OwnM (Auth.white (NatMapRALarge.singleton tid a: NatMapRALarge.t nat)) ** maps_to tid (Auth.white (Excl.just 2: Excl.t nat))) -*\n        g1 ()%type ()%type\n          (λ r_src r_tgt : (),\n             (own_thread tid ** ObligationRA.duty (inl tid) []) ** ⌜r_src = r_tgt⌝) false false\n          (src_code_coind tid)\n          (tgt_code_coind a))\n          ∧\n  (monoWhite tk_mono Nat.le_preorder now)\n     ) **\n   (maps_to tid (Auth.white (Excl.just 2: Excl.t nat)) **\n    (OwnM (Auth.white (NatMapRALarge.singleton tid mytk: NatMapRALarge.t nat)) **\n     (ticket_lock_inv_tks tks **\n      (ticket_lock_inv_mem mem now next myt **\n       (ticket_lock_inv_state mem false tks **\n        (ticket_lock_inv_unlocking l tks now next myt **\n         (ticket_lock_inv -*\n          MUpd (nth_default True%I I)\n            (fairI (ident_tgt:=OMod.closed_ident TicketLock.omod (SCMem.mod TicketLock.gvs))) []\n            [0] True)))))))\n  )\n  ⊢ (stsim I tid [] g0 g1\n      (λ r_src r_tgt : (), (own_thread tid ** ObligationRA.duty (inl tid) []) ** ⌜r_src = r_tgt⌝)\n      false true\n      (trigger Yield;;;\n       ` x : () + () <-\n       (` x_0 : bool * NatMap.t () <- trigger (Get id);;\n        (let (own0, _) := x_0 in if Bool.eqb own0 true then Ret (inl ()) else Ret (inr ())));;\n       match x with\n       | inl l0 =>\n           tau;; ITree.iter\n                   (λ _ : (),\n                      trigger Yield;;;\n                      ` x_0 : bool * NatMap.t () <- trigger (Get id);;\n                      (let (own0, _) := x_0 in\n                       if Bool.eqb own0 true then Ret (inl ()) else Ret (inr ()))) l0\n       | inr r0 => Ret r0\n       end;;;\n       ` x_0 : bool * NatMap.t () <- trigger (Get id);;\n       (let (_, ts0) := x_0 in\n        trigger (Put (true, NatMap.remove (elt:=()) tid ts0));;;\n        trigger\n          (Fair\n             (λ i : nat,\n                if tid_dec i tid\n                then Flag.success\n                else\n                 if NatMapP.F.In_dec (NatMap.remove (elt:=()) tid ts0) i\n                 then Flag.fail\n                 else Flag.emp));;; trigger Yield;;; Ret ()))\n      (` r : Any.t <-\n       map_event (OMod.emb_callee TicketLock.omod (SCMem.mod TicketLock.gvs))\n         (Mod.wrap_fun SCMem.compare_fun (Any.upcast (SCMem.val_nat now_old, SCMem.val_nat mytk)));;\n       ` x : bool <- (tau;; unwrap (Any.downcast r));;\n       OMod.close_itree TicketLock.omod (SCMem.mod TicketLock.gvs)\n         (if x then Ret () else tau;; TicketLock.lock_loop (SCMem.val_nat mytk));;;\n       OMod.close_itree TicketLock.omod (SCMem.mod TicketLock.gvs) (trigger Yield))).\n  Proof.\n    iIntros \"[#[CIH MONOTK] [MYN [MYTK [TKS [MEM [ST [I K]]]]]]]\".\n    iPoseProof (mytk_find_some with \"[MYTK TKS]\") as \"%FIND\". iFrame.\n    iPoseProof (unlocking_mono with \"I\") as \"[%TKQ #[% [% [MONOW OBLB]]]]\".\n    clear FIND TKQ.\n    iStopProof. move o before IH. revert_until o. pattern o. revert o.\n    apply (well_founded_induction Ord.lt_well_founded).\n    intros o IHo. intros.\n    iIntros \"[#[CIH [MONOTK [MONOW BLK]]] [MYN [MYTK [TKS [MEM [ST [I K]]]]]]]\".\n\n    unfold Mod.wrap_fun, SCMem.compare_fun. rred.\n    iDestruct \"MEM\" as \"[MEM0 [MEM1 [MEM2 MEM3]]]\". iDestruct \"ST\" as \"[ST0 ST1]\".\n    iApply stsim_getR. iSplit. eauto. rred.\n    iApply stsim_tauR. rred.\n    destruct (Nat.eq_dec now_old mytk).\n    { exfalso. clarify. }\n    rred. iApply stsim_tauR.\n    rewrite TicketLock.lock_loop_red. rred. rewrite close_itree_call. rred.\n    iAssert (ticket_lock_inv_mem mem now next myt)%I with \"[MEM0 MEM1 MEM2 MEM3]\" as \"MEM\". iFrame.\n    iAssert (ticket_lock_inv_state mem false tks)%I with \"[ST0 ST1]\" as \"ST\". iFrame.\n    iMod (\"K\" with \"[TKS MEM ST I]\") as \"_\".\n    { do 7 iExists _. iSplitL \"TKS\". iFrame. iSplitL \"MEM\". iFrame. iSplitL \"ST\". iFrame.\n      iRight. iSplit. auto. iLeft. iFrame.\n    }\n    clear mem l tks next myt now_old NEQ n.\n    rename now into now_past, LT into LTPAST, k into k_past, o into o_past.\n\n    iopen 0 \"I\" \"K\". do 7 iDestruct \"I\" as \"[% I]\". iDestruct \"I\" as \"[TKS [MEM [ST CASES]]]\".\n    destruct (Nat.eq_dec mytk now); subst.\n    { iClear \"CIH\".\n      iApply lock_myturn1.\n      iSplitL \"MYTK\". iFrame. iSplitL \"MYN\". iFrame. iSplitL \"TKS\". iFrame.\n      iSplitL \"MEM\". iFrame. iSplitL \"ST\". iFrame. iSplitL \"CASES\". iFrame.\n      iFrame.\n    }\n\n    rename n into NEQ.\n    iApply lock_yourturn_yieldR. eapply NEQ.\n    iSplitL \"MYTK TKS MEM ST CASES K\".\n    iSplitL \"MYTK\". iFrame. iSplitL \"TKS\". iFrame. iSplitL \"MEM\". iFrame.\n    iSplitL \"ST\". iFrame. iSplitL \"CASES\". iFrame. iFrame.\n    iIntros \"[MYTK _]\". rred.\n    clear mem own l tks now next myt NEQ.\n    iopen 0 \"I\" \"K\". do 7 iDestruct \"I\" as \"[% I]\". iDestruct \"I\" as \"[TKS [MEM [ST CASES]]]\".\n    destruct (Nat.eq_dec mytk now); subst.\n    { iClear \"CIH\".\n      iPoseProof (mytk_find_some with \"[MYTK TKS]\") as \"%FIND\". iFrame.\n      iDestruct \"CASES\" as \"[[%CT I] | [%CF [I | [I | I]]]]\".\n      { iPoseProof (locked_contra with \"I\") as \"%F\". eauto. inv F. }\n      { iPoseProof (unlocking_contra with \"I\") as \"%F\". eauto. inv F. }\n      { iPoseProof (unlocked0_contra with \"I\") as \"%F\". eauto. inv F. }\n      iPoseProof (unlocked1_mono with \"I\") as \"[%TKQ #[% [% [MYTN _]]]]\".\n      iMod (\"K\" with \"[TKS MEM ST I]\") as \"_\".\n      { do 7 iExists _. iSplitL \"TKS\". iFrame. iSplitL \"MEM\". iFrame. iSplitL \"ST\". iFrame.\n        iRight. iSplit. auto. iFrame.\n      }\n      iApply lock_myturn0. 2: iFrame; auto. lia.\n    }\n\n    rename n into NEQ. unfold Mod.wrap_fun, SCMem.load_fun. rred.\n    iDestruct \"MEM\" as \"[MEM0 [MEM1 [MEM2 MEM3]]]\". iDestruct \"ST\" as \"[ST0 ST1]\".\n    iApply stsim_getR. iSplit. eauto. rred.\n    iPoseProof (memory_ra_load with \"MEM0 MEM1\") as \"%LOAD\". des. rewrite LOAD. rred.\n    iApply stsim_tauR. rred.\n    rewrite close_itree_call. rred.\n    iApply lock_yourturn_yieldR. eapply NEQ.\n    iSplitL \"MYTK TKS MEM0 MEM1 MEM2 MEM3 ST0 ST1 CASES K\".\n    iSplitL \"MYTK\". iFrame. iSplitL \"TKS\". iFrame. iSplitL \"MEM0 MEM1 MEM2 MEM3\". iFrame.\n    iSplitL \"ST0 ST1\". iFrame. iSplitL \"CASES\". iFrame. iFrame.\n    iIntros \"[MYTK RIGHT]\". rred.\n    rename now into now_old. clear mem own l tks next myt LOAD LOAD0.\n\n    iopen 0 \"I\" \"K\". do 7 iDestruct \"I\" as \"[% I]\". iDestruct \"I\" as \"[TKS [MEM [ST CASES]]]\".\n    destruct (Nat.eq_dec mytk now); subst.\n    { iClear \"CIH\". iApply lock_myturn2. auto.\n      iSplitL \"MYTK\". iFrame. iSplitL \"MYN\". iFrame. iSplitL \"TKS\". iFrame.\n      iSplitL \"MEM\". iFrame. iSplitL \"ST\". iFrame. iSplitL \"CASES\". iFrame.\n      iFrame.\n    }\n\n    iPoseProof (mytk_find_some with \"[MYTK TKS]\") as \"%FIND\". iFrame.\n    rename n into NEQ2. iPoseProof (yourturn_range with \"CASES\") as \"%LT\". eapply FIND. auto.\n    clear NEQ2. iDestruct \"CASES\" as \"[[%CT I] | [%CF [I | [I | I]]]]\".\n    { subst own. iApply lock_yourturn_coind. auto. iSplit. iApply \"CIH\".\n      iSplitL \"MYN\". iFrame. iSplitL \"MYTK\". iFrame. iSplitL \"TKS\". iFrame.\n      iSplitL \"MEM\". iFrame. iSplitL \"ST\". iFrame. iSplitL \"I\". iFrame. iFrame.\n    }\n\n    { iPoseProof (ticket_lock_inv_mem_mono with \"MEM\") as \"#MONOTK2\".\n      iDestruct \"I\" as \"[I0 [%I1 [I2 [I3 I4]]]]\".\n      do 2 iDestruct \"I4\" as \"[% I4]\". iDestruct \"I4\" as \"[I4 [I5 [I6 I7]]]\".\n      iPoseProof (black_white_compare with \"MONOW I4\") as \"%LE\".\n      inv LE.\n      { remember (mytk - now) as ind. specialize (IH ind).\n        iApply IH.\n        { subst ind. lia. }\n        { auto. }\n        { eapply LT. }\n        { eapply Heqind. }\n        iSplit.\n        { iClear \"MYN MYTK RIGHT TKS MEM ST I0 I2 I3 I4 I5 I6 I7 K\".\n          iModIntro. iSplit. iApply \"CIH\". auto.\n        }\n        iSplitL \"MYN\". iFrame. iSplitL \"MYTK\". iFrame. iSplitL \"TKS\". iFrame.\n        iSplitL \"ST\". iFrame. iSplitR \"K MEM\". 2: iFrame.\n        iRight. iSplit. auto. iLeft. iFrame. iSplit. auto. iExists _, _. iFrame.\n      }\n      { inv ORD. hexploit H0. lia. i. clear H H0. subst k.\n        iClear \"MONOTK2\".\n        iPoseProof (ObligationRA.duty_correl_thread with \"I7\") as \"#COR\".\n        { ss. left; eauto. }\n        iPoseProof (ObligationRA.correl_thread_correlate with \"COR RIGHT\") as \">[DROP | FF]\".\n        2:{ iPoseProof (ObligationRA.pending_not_shot with \"I6 FF\") as \"%FF\". inv FF. }\n        iPoseProof (ObligationRA.black_white_decr with \"BLK DROP\") as \">[%o_now [#OBLK2 %DROP]]\".\n        iClear \"BLK\".\n        specialize (IHo o_now).\n        iApply IHo.\n        { rewrite Hessenberg.add_S_r in DROP. rewrite Hessenberg.add_O_r in DROP.\n          eapply Ord.lt_le_lt. 2: eapply DROP. apply Ord.S_lt.\n        }\n        { auto. }\n        iSplit.\n        { iClear \"MYN MYTK TKS MEM ST I0 I2 I3 I4 I5 I6 I7 K\".\n          iModIntro. iSplit. iApply \"CIH\". iSplit; auto.\n        }\n        iSplitL \"MYN\". iFrame. iSplitL \"MYTK\". iFrame. iSplitL \"TKS\". iFrame.\n        iSplitL \"MEM\". iFrame. iSplitL \"ST\". iFrame. iSplitR \"K\". 2: iFrame.\n        iFrame. iSplit. auto. iExists _, _. iFrame.\n      }\n    }\n    { iPoseProof (unlocked0_contra with \"I\") as \"%FF\". eauto. inv FF. }\n\n    { iPoseProof (ticket_lock_inv_mem_mono with \"MEM\") as \"#MONOTK2\".\n      do 2 iDestruct \"I\" as \"[% I]\". iDestruct \"I\" as \"[I0 [I1 [%I2 [I3 [I4 I5]]]]]\".\n      do 3 iDestruct \"I5\" as \"[% I5]\". iDestruct \"I5\" as \"[I5 [I6 [I7 [I8 [I9 I10]]]]]\".\n      iPoseProof (black_white_compare with \"MONOW I5\") as \"%LE\".\n      inv LE.\n      { remember (mytk - now) as ind. specialize (IH ind).\n        iApply IH.\n        { subst ind. lia. }\n        { auto. }\n        { eapply LT. }\n        { eapply Heqind. }\n        iSplit.\n        { iClear \"MYN MYTK RIGHT TKS MEM ST I0 I1 I3 I4 I5 I6 I7 I8 I9 I10 K\".\n          iModIntro. iSplit. iApply \"CIH\". auto.\n        }\n        iSplitL \"MYN\". iFrame. iSplitL \"MYTK\". iFrame. iSplitL \"TKS\". iFrame.\n        iSplitL \"ST\". iFrame. iSplitR \"K MEM\". 2: iFrame.\n        iRight. iSplit. auto. iRight. iRight. iFrame.\n        iExists yourt, waits. iSplit. auto. iSplit. auto. iFrame.\n        iExists k, o, u. iFrame.\n      }\n      { exfalso. inv ORD. lia. }\n    }\n  Qed.\n\n  Lemma lock_yourturn_ind1\n        (g0 g1 : ∀ R_src R_tgt : Type,\n            (R_src → R_tgt → iProp)\n            → bool\n            → bool\n            → itree (programE _ (Mod.state AbsLock.mod)) R_src\n            → itree (programE _ (OMod.closed_state TicketLock.omod (SCMem.mod TicketLock.gvs))) R_tgt → iProp)\n        (tid : nat)\n        (mytk : TicketLock.tk)\n  (now : nat)\n  (LT : now < mytk)\n  (IH : ∀ y : nat,\n         y < mytk - now\n         → ∀ now_old : nat,\n             mytk ≠ now_old\n             → ∀ (mem : SCMem.t) (own : bool) (l : list nat) (tks : NatMap.t nat)\n                 (now next myt : nat),\n                 now < mytk\n                 → y = mytk - now\n                   → (□ ((∀ a : TicketLock.tk,\n                            (OwnM (Auth.white (NatMapRALarge.singleton tid a: NatMapRALarge.t nat)) **\n                             maps_to tid (Auth.white (Excl.just 2: Excl.t nat))) -*\n                            g1 ()%type ()%type\n                              (λ r_src r_tgt : (),\n                                 (own_thread tid ** ObligationRA.duty (inl tid) []) **\n                                 ⌜r_src = r_tgt⌝) false false\n                              (src_code_coind tid)\n                              (tgt_code_coind a)\n                         ) ∧ monoWhite tk_mono Nat.le_preorder now) **\n                      (maps_to tid (Auth.white (Excl.just 2: Excl.t nat)) **\n                       (OwnM (Auth.white (NatMapRALarge.singleton tid mytk: NatMapRALarge.t nat)) **\n                        (ticket_lock_inv_tks tks **\n                         (ticket_lock_inv_state mem own tks **\n                          ((⌜own = true⌝ ** ticket_lock_inv_locked l tks now next myt)\n                           ∨ (⌜own = false⌝ **\n                              ticket_lock_inv_unlocking l tks now next myt\n                              ∨ ticket_lock_inv_unlocked0 l tks now next myt\n                                ∨ ticket_lock_inv_unlocked1 l tks now next myt) **\n                           ((ticket_lock_inv -*\n                             MUpd (nth_default True%I I)\n                               (fairI\n                                  (ident_tgt:=OMod.closed_ident TicketLock.omod\n                                                (SCMem.mod TicketLock.gvs))) [] [0] True) **\n                            ticket_lock_inv_mem mem now next myt)))))))\n                     ⊢ stsim I tid [] g0 g1\n                         (λ r_src r_tgt : (),\n                            (own_thread tid ** ObligationRA.duty (inl tid) []) ** ⌜r_src = r_tgt⌝)\n                         false true\n                         (src_code_ind tid)\n                         (tgt_code_ind mytk now_old)\n  )\n  (now_old : nat)\n  (NEQ : mytk ≠ now_old)\n  (mem : SCMem.t)\n  (l : list nat)\n  (tks : NatMap.t nat)\n  (next myt : nat)\n    :\n  (□ ((∀ a : TicketLock.tk,\n        (OwnM (Auth.white (NatMapRALarge.singleton tid a: NatMapRALarge.t nat)) ** maps_to tid (Auth.white (Excl.just 2: Excl.t nat))) -*\n        g1 ()%type ()%type\n          (λ r_src r_tgt : (),\n             (own_thread tid ** ObligationRA.duty (inl tid) []) ** ⌜r_src = r_tgt⌝) false false\n          (src_code_coind tid)\n          (tgt_code_coind a))\n          ∧\n  (monoWhite tk_mono Nat.le_preorder now)\n     ) **\n   (maps_to tid (Auth.white (Excl.just 2: Excl.t nat)) **\n    (OwnM (Auth.white (NatMapRALarge.singleton tid mytk: NatMapRALarge.t nat)) **\n     (ticket_lock_inv_tks tks **\n      (ticket_lock_inv_mem mem now next myt **\n       (ticket_lock_inv_state mem false tks **\n        (ticket_lock_inv_unlocked1 l tks now next myt **\n         (ticket_lock_inv -*\n          MUpd (nth_default True%I I)\n            (fairI (ident_tgt:=OMod.closed_ident TicketLock.omod (SCMem.mod TicketLock.gvs))) []\n            [0] True)))))))\n  )\n  ⊢ (stsim I tid [] g0 g1\n      (λ r_src r_tgt : (), (own_thread tid ** ObligationRA.duty (inl tid) []) ** ⌜r_src = r_tgt⌝)\n      false true\n      (trigger Yield;;;\n       ` x : () + () <-\n       (` x_0 : bool * NatMap.t () <- trigger (Get id);;\n        (let (own0, _) := x_0 in if Bool.eqb own0 true then Ret (inl ()) else Ret (inr ())));;\n       match x with\n       | inl l0 =>\n           tau;; ITree.iter\n                   (λ _ : (),\n                      trigger Yield;;;\n                      ` x_0 : bool * NatMap.t () <- trigger (Get id);;\n                      (let (own0, _) := x_0 in\n                       if Bool.eqb own0 true then Ret (inl ()) else Ret (inr ()))) l0\n       | inr r0 => Ret r0\n       end;;;\n       ` x_0 : bool * NatMap.t () <- trigger (Get id);;\n       (let (_, ts0) := x_0 in\n        trigger (Put (true, NatMap.remove (elt:=()) tid ts0));;;\n        trigger\n          (Fair\n             (λ i : nat,\n                if tid_dec i tid\n                then Flag.success\n                else\n                 if NatMapP.F.In_dec (NatMap.remove (elt:=()) tid ts0) i\n                 then Flag.fail\n                 else Flag.emp));;; trigger Yield;;; Ret ()))\n      (` r : Any.t <-\n       map_event (OMod.emb_callee TicketLock.omod (SCMem.mod TicketLock.gvs))\n         (Mod.wrap_fun SCMem.compare_fun (Any.upcast (SCMem.val_nat now_old, SCMem.val_nat mytk)));;\n       ` x : bool <- (tau;; unwrap (Any.downcast r));;\n       OMod.close_itree TicketLock.omod (SCMem.mod TicketLock.gvs)\n         (if x then Ret () else tau;; TicketLock.lock_loop (SCMem.val_nat mytk));;;\n       OMod.close_itree TicketLock.omod (SCMem.mod TicketLock.gvs) (trigger Yield))).\n  Proof.\n    iIntros \"[#[CIH MONOTK] [MYN [MYTK [TKS [MEM [ST [I K]]]]]]]\".\n    iPoseProof (mytk_find_some with \"[MYTK TKS]\") as \"%FIND\". iFrame.\n    iPoseProof (unlocked1_mono with \"I\") as \"[%TKQ #[% [% [MONOW OBLB]]]]\".\n    clear FIND TKQ.\n    iStopProof. move o before IH. revert_until o. pattern o. revert o.\n    apply (well_founded_induction Ord.lt_well_founded).\n    intros o IHo. intros.\n    iIntros \"[#[CIH [MONOTK [MONOW BLK]]] [MYN [MYTK [TKS [MEM [ST [I K]]]]]]]\".\n\n    unfold Mod.wrap_fun, SCMem.compare_fun. rred.\n    iDestruct \"MEM\" as \"[MEM0 [MEM1 [MEM2 MEM3]]]\". iDestruct \"ST\" as \"[ST0 ST1]\".\n    iApply stsim_getR. iSplit. eauto. rred.\n    iApply stsim_tauR. rred.\n    destruct (Nat.eq_dec now_old mytk).\n    { exfalso. clarify. }\n    rred. iApply stsim_tauR.\n    rewrite TicketLock.lock_loop_red. rred. rewrite close_itree_call. rred.\n    iAssert (ticket_lock_inv_mem mem now next myt)%I with \"[MEM0 MEM1 MEM2 MEM3]\" as \"MEM\". iFrame.\n    iAssert (ticket_lock_inv_state mem false tks)%I with \"[ST0 ST1]\" as \"ST\". iFrame.\n    iMod (\"K\" with \"[TKS MEM ST I]\") as \"_\".\n    { do 7 iExists _. iSplitL \"TKS\". iFrame. iSplitL \"MEM\". iFrame. iSplitL \"ST\". iFrame.\n      iRight. iSplit. auto. iRight. iRight. iFrame.\n    }\n    clear mem l tks next myt now_old NEQ n.\n    rename now into now_past, LT into LTPAST, k into k_past, o into o_past.\n\n    iopen 0 \"I\" \"K\". do 7 iDestruct \"I\" as \"[% I]\". iDestruct \"I\" as \"[TKS [MEM [ST CASES]]]\".\n    destruct (Nat.eq_dec mytk now); subst.\n    { iClear \"CIH\".\n      iApply lock_myturn1.\n      iSplitL \"MYTK\". iFrame. iSplitL \"MYN\". iFrame. iSplitL \"TKS\". iFrame.\n      iSplitL \"MEM\". iFrame. iSplitL \"ST\". iFrame. iSplitL \"CASES\". iFrame.\n      iFrame.\n    }\n\n    rename n into NEQ.\n    iApply lock_yourturn_yieldR. eapply NEQ.\n    iSplitL \"MYTK TKS MEM ST CASES K\".\n    iSplitL \"MYTK\". iFrame. iSplitL \"TKS\". iFrame. iSplitL \"MEM\". iFrame.\n    iSplitL \"ST\". iFrame. iSplitL \"CASES\". iFrame. iFrame.\n    iIntros \"[MYTK _]\". rred.\n    clear mem own l tks now next myt NEQ.\n    iopen 0 \"I\" \"K\". do 7 iDestruct \"I\" as \"[% I]\". iDestruct \"I\" as \"[TKS [MEM [ST CASES]]]\".\n    destruct (Nat.eq_dec mytk now); subst.\n    { iClear \"CIH\".\n      iPoseProof (mytk_find_some with \"[MYTK TKS]\") as \"%FIND\". iFrame.\n      iDestruct \"CASES\" as \"[[%CT I] | [%CF [I | [I | I]]]]\".\n      { iPoseProof (locked_contra with \"I\") as \"%F\". eauto. inv F. }\n      { iPoseProof (unlocking_contra with \"I\") as \"%F\". eauto. inv F. }\n      { iPoseProof (unlocked0_contra with \"I\") as \"%F\". eauto. inv F. }\n      iPoseProof (unlocked1_mono with \"I\") as \"[%TKQ #[% [% [MYTN _]]]]\".\n      iMod (\"K\" with \"[TKS MEM ST I]\") as \"_\".\n      { do 7 iExists _. iSplitL \"TKS\". iFrame. iSplitL \"MEM\". iFrame. iSplitL \"ST\". iFrame.\n        iRight. iSplit. auto. iFrame.\n      }\n      iApply lock_myturn0. 2: iFrame; auto. lia.\n    }\n\n    rename n into NEQ. unfold Mod.wrap_fun, SCMem.load_fun. rred.\n    iDestruct \"MEM\" as \"[MEM0 [MEM1 [MEM2 MEM3]]]\". iDestruct \"ST\" as \"[ST0 ST1]\".\n    iApply stsim_getR. iSplit. eauto. rred.\n    iPoseProof (memory_ra_load with \"MEM0 MEM1\") as \"%LOAD\". des. rewrite LOAD. rred.\n    iApply stsim_tauR. rred.\n    rewrite close_itree_call. rred.\n    iApply lock_yourturn_yieldR. eapply NEQ.\n    iSplitL \"MYTK TKS MEM0 MEM1 MEM2 MEM3 ST0 ST1 CASES K\".\n    iSplitL \"MYTK\". iFrame. iSplitL \"TKS\". iFrame. iSplitL \"MEM0 MEM1 MEM2 MEM3\". iFrame.\n    iSplitL \"ST0 ST1\". iFrame. iSplitL \"CASES\". iFrame. iFrame.\n    iIntros \"[MYTK RIGHT]\". rred.\n    rename now into now_old. clear mem own l tks next myt LOAD LOAD0.\n\n    iopen 0 \"I\" \"K\". do 7 iDestruct \"I\" as \"[% I]\". iDestruct \"I\" as \"[TKS [MEM [ST CASES]]]\".\n    destruct (Nat.eq_dec mytk now); subst.\n    { iClear \"CIH\". iApply lock_myturn2. auto.\n      iSplitL \"MYTK\". iFrame. iSplitL \"MYN\". iFrame. iSplitL \"TKS\". iFrame.\n      iSplitL \"MEM\". iFrame. iSplitL \"ST\". iFrame. iSplitL \"CASES\". iFrame.\n      iFrame.\n    }\n\n    iPoseProof (mytk_find_some with \"[MYTK TKS]\") as \"%FIND\". iFrame.\n    rename n into NEQ2. iPoseProof (yourturn_range with \"CASES\") as \"%LT\". eapply FIND. auto.\n    clear NEQ2. iDestruct \"CASES\" as \"[[%CT I] | [%CF [I | [I | I]]]]\".\n    { subst own. iApply lock_yourturn_coind. auto. iSplit. iApply \"CIH\".\n      iSplitL \"MYN\". iFrame. iSplitL \"MYTK\". iFrame. iSplitL \"TKS\". iFrame.\n      iSplitL \"MEM\". iFrame. iSplitL \"ST\". iFrame. iSplitL \"I\". iFrame. iFrame.\n    }\n\n    { iPoseProof (ticket_lock_inv_mem_mono with \"MEM\") as \"#MONOTK2\".\n      iAssert (⌜now_past <= now⌝)%I with \"[MEM]\" as \"%PROG\".\n      { iDestruct \"MEM\" as \"[MEM0 [MEM1 [MEM2 [MEM3 MEM4]]]]\".\n        iPoseProof (black_white_compare with \"MONOTK MEM4\") as \"%\". auto.\n      }\n      iApply lock_yourturn_ind0. apply LT.\n      { clear IHo. move LT before IH. move PROG before LT. clear_upto PROG.\n        intros y H. eapply IH. lia.\n      }\n      auto.\n      iSplit.\n      { iClear \"MYN MYTK RIGHT TKS MEM ST I K\". iModIntro. iSplit. iApply \"CIH\". auto. }\n      iSplitL \"MYN\". iFrame. iSplitL \"MYTK\". iFrame. iSplitL \"TKS\". iFrame. iSplitL \"MEM\". iFrame.\n      iSplitL \"ST\". subst. iFrame. iSplitR \"K\". 2: iFrame.\n      iFrame.\n    }\n\n    { iPoseProof (unlocked0_contra with \"I\") as \"%FF\". eauto. inv FF. }\n\n    { iPoseProof (ticket_lock_inv_mem_mono with \"MEM\") as \"#MONOTK2\".\n      do 2 iDestruct \"I\" as \"[% I]\". iDestruct \"I\" as \"[I0 [%I1 [%I2 [I3 [I4 I5]]]]]\".\n      do 3 iDestruct \"I5\" as \"[% I5]\". iDestruct \"I5\" as \"[I5 [I6 [I7 [I8 [I9 I10]]]]]\".\n      iPoseProof (black_white_compare with \"MONOW I5\") as \"%LE\".\n      inv LE.\n      { remember (mytk - now) as ind. specialize (IH ind).\n        iApply IH.\n        { subst ind. lia. }\n        { auto. }\n        { eapply LT. }\n        { eapply Heqind. }\n        iSplit.\n        { iClear \"MYN MYTK RIGHT TKS MEM ST I0 I3 I4 I5 I6 I7 I8 I9 I10 K\".\n          iModIntro. iSplit. iApply \"CIH\". auto.\n        }\n        iSplitL \"MYN\". iFrame. iSplitL \"MYTK\". iFrame. iSplitL \"TKS\". iFrame.\n        iSplitL \"ST\". iFrame. iSplitR \"K MEM\". 2: iFrame.\n        iRight. iSplit. auto. iRight. iRight. iFrame. iExists yourt, waits.\n        iSplit. auto. iSplit. auto. iFrame. iExists k, o, u. iFrame.\n      }\n      { inv ORD. hexploit H0. lia. i. clear H H0. subst k.\n        iClear \"MONOTK2\".\n        iPoseProof (ObligationRA.duty_correl_thread with \"I8\") as \"#COR\".\n        { ss. left; eauto. }\n        iPoseProof (ObligationRA.correl_thread_correlate with \"COR RIGHT\") as \">[DROP | FF]\".\n        2:{ iPoseProof (ObligationRA.pending_not_shot with \"I7 FF\") as \"%FF\". inv FF. }\n        iPoseProof (ObligationRA.black_white_decr with \"BLK DROP\") as \">[%o_now [#OBLK2 %DROP]]\".\n        iClear \"BLK\".\n        specialize (IHo o_now). iApply IHo.\n        { rewrite Hessenberg.add_S_r in DROP. rewrite Hessenberg.add_O_r in DROP.\n          eapply Ord.lt_le_lt. 2: eapply DROP. apply Ord.S_lt.\n        }\n        { auto. }\n        iSplit.\n        { iClear \"MYN MYTK TKS MEM ST I0 I3 I4 I5 I6 I7 I8 I9 I10 K\".\n          iModIntro. iSplit. iApply \"CIH\". auto.\n        }\n        iSplitL \"MYN\". iFrame. iSplitL \"MYTK\". iFrame. iSplitL \"TKS\". iFrame.\n        iSplitL \"MEM\". iFrame. iSplitL \"ST\". iFrame. iSplitR \"K\". 2: iFrame.\n        iFrame. iExists yourt, waits.\n        iSplit. auto. iSplit. auto. iFrame. iExists _, _, u. iFrame.\n      }\n    }\n  Qed.\n\n  Lemma correct_lock tid:\n    ((own_thread tid)\n       ∗ (ObligationRA.duty (inl tid) [])\n    )\n      ⊢\n      (stsim I tid (topset I) ibot7 ibot7\n             (fun r_src r_tgt => own_thread tid ** ObligationRA.duty (inl tid) [] ** ⌜r_src = r_tgt⌝)\n             false false\n             (AbsLock.lock_fun tt)\n             (OMod.close_itree TicketLock.omod (SCMem.mod TicketLock.gvs)\n                               (TicketLock.lock_fun tt))).\n  Proof.\n    iIntros \"[MYTH DUTY]\".\n    iApply lock_enqueue. iSplitL. iFrame.\n    iIntros \"% [MYTK MYN]\".\n    rewrite TicketLock.lock_loop_red. rred. rewrite close_itree_call. rred.\n    iStopProof. revert mytk. eapply stsim_coind. msubtac.\n    iIntros \"% %mytk\". iIntros \"#[_ CIH] [MYTK MYN]\".\n\n    iopen 0 \"I\" \"K\". do 7 iDestruct \"I\" as \"[% I]\". iDestruct \"I\" as \"[TKS [MEM [ST CASES]]]\".\n    destruct (Nat.eq_dec mytk now); subst.\n    { iClear \"CIH\".\n      rewrite unfold_iter_eq. lred. iApply lock_myturn1.\n      iSplitL \"MYTK\". iFrame. iSplitL \"MYN\". iFrame. iSplitL \"TKS\". iFrame.\n      iSplitL \"MEM\". iFrame. iSplitL \"ST\". iFrame. iSplitL \"CASES\". iFrame.\n      iFrame.\n    }\n\n    rename n into NEQ. rewrite unfold_iter_eq. lred.\n    iApply lock_yourturn_yieldR. eapply NEQ.\n    iSplitL \"MYTK TKS MEM ST CASES K\".\n    iSplitL \"MYTK\". iFrame. iSplitL \"TKS\". iFrame. iSplitL \"MEM\". iFrame.\n    iSplitL \"ST\". iFrame. iSplitL \"CASES\". iFrame. iFrame.\n    iIntros \"[MYTK _]\". rred.\n    clear mem own l tks now next myt NEQ.\n    iopen 0 \"I\" \"K\". do 7 iDestruct \"I\" as \"[% I]\". iDestruct \"I\" as \"[TKS [MEM [ST CASES]]]\".\n    destruct (Nat.eq_dec mytk now); subst.\n    { iClear \"CIH\".\n      iPoseProof (mytk_find_some with \"[MYTK TKS]\") as \"%FIND\". iFrame.\n      iDestruct \"CASES\" as \"[[%CT I] | [%CF [I | [I | I]]]]\".\n      { iPoseProof (locked_contra with \"I\") as \"%F\". eauto. inv F. }\n      { iPoseProof (unlocking_contra with \"I\") as \"%F\". eauto. inv F. }\n      { iPoseProof (unlocked0_contra with \"I\") as \"%F\". eauto. inv F. }\n      iPoseProof (unlocked1_mono with \"I\") as \"[%TKQ #[% [% [MYTN _]]]]\".\n      iMod (\"K\" with \"[TKS MEM ST I]\") as \"_\".\n      { do 7 iExists _. iSplitL \"TKS\". iFrame. iSplitL \"MEM\". iFrame. iSplitL \"ST\". iFrame.\n        iRight. iSplit. auto. iFrame.\n      }\n      iApply lock_myturn0. 2: iFrame; auto. lia.\n    }\n\n    rename n into NEQ.\n    unfold Mod.wrap_fun, SCMem.load_fun. rred.\n    iDestruct \"MEM\" as \"[MEM0 [MEM1 [MEM2 MEM3]]]\". iDestruct \"ST\" as \"[ST0 ST1]\".\n    iApply stsim_getR. iSplit. eauto. rred.\n    iPoseProof (memory_ra_load with \"MEM0 MEM1\") as \"%LOAD\". des. rewrite LOAD. rred.\n    iApply stsim_tauR. rred.\n    rewrite close_itree_call. rred.\n    iApply lock_yourturn_yieldR. eapply NEQ.\n    iSplitL \"MYTK TKS MEM0 MEM1 MEM2 MEM3 ST0 ST1 CASES K\".\n    iSplitL \"MYTK\". iFrame. iSplitL \"TKS\". iFrame. iSplitL \"MEM0 MEM1 MEM2 MEM3\". iFrame.\n    iSplitL \"ST0 ST1\". iFrame. iSplitL \"CASES\". iFrame. iFrame.\n    iIntros \"[MYTK _]\". rred.\n    rename now into now_old. clear mem own l tks next myt LOAD LOAD0.\n\n    iopen 0 \"I\" \"K\". do 7 iDestruct \"I\" as \"[% I]\". iDestruct \"I\" as \"[TKS [MEM [ST CASES]]]\".\n    destruct (Nat.eq_dec mytk now); subst.\n    { iClear \"CIH\". iApply lock_myturn2. auto.\n      iSplitL \"MYTK\". iFrame. iSplitL \"MYN\". iFrame. iSplitL \"TKS\". iFrame.\n      iSplitL \"MEM\". iFrame. iSplitL \"ST\". iFrame. iSplitL \"CASES\". iFrame.\n      iFrame.\n    }\n\n    rename n into NEQ2.\n    iPoseProof (mytk_find_some with \"[MYTK TKS]\") as \"%FIND\". iFrame.\n    iDestruct \"MEM\" as \"[MEM0 [MEM1 [MEM2 [MEM3 MEM4]]]]\".\n    iPoseProof (black_white with \"MEM4\") as \"#MONOTK\".\n    iAssert (ticket_lock_inv_mem mem now next myt)%I with \"[MEM0 MEM1 MEM2 MEM3 MEM4]\" as \"MEM\".\n    iFrame.\n    iPoseProof (yourturn_range with \"CASES\") as \"%LT\". eapply FIND. auto.\n    clear FIND NEQ2.\n    remember (mytk - now) as ind.\n    iStopProof. move ind before mytk. revert_until ind. pattern ind. revert ind.\n    apply (well_founded_induction Nat.lt_wf_0).\n    intros ind IH. intros.\n    iIntros \"[#[CIH MONOTK] [MYN [MYTK [TKS [ST [CASES [K MEM]]]]]]]\".\n\n    iDestruct \"CASES\" as \"[[%CT I] | [%CF [I | [I | I]]]]\".\n    { subst own. iApply lock_yourturn_coind. auto. iSplit. iApply \"CIH\".\n      iSplitL \"MYN\". iFrame. iSplitL \"MYTK\". iFrame. iSplitL \"TKS\". iFrame.\n      iSplitL \"MEM\". iFrame. iSplitL \"ST\". iFrame. iSplitL \"I\". iFrame. iFrame.\n    }\n    { subst. iApply lock_yourturn_ind0. apply LT. apply IH. auto.\n      iSplit.\n      { iClear \"MYN MYTK TKS MEM ST I K\".\n        iModIntro. iSplit. iApply \"CIH\". auto.\n      }\n      iSplitL \"MYN\". iFrame. iSplitL \"MYTK\". iFrame. iSplitL \"TKS\". iFrame.\n      iSplitL \"MEM\". iFrame. iSplitL \"ST\". iFrame. iSplitR \"K\". 2: iFrame.\n      iFrame.\n    }\n    { iPoseProof (mytk_find_some with \"[MYTK TKS]\") as \"%FIND\". iFrame.\n      iPoseProof (unlocked0_contra with \"I\") as \"%FF\". eauto. inv FF.\n    }\n    { subst. iApply lock_yourturn_ind1. apply LT. apply IH. auto.\n      iSplit.\n      { iClear \"MYN MYTK TKS MEM ST I K\". iModIntro. iSplit. iApply \"CIH\". auto. }\n      iSplitL \"MYN\". iFrame. iSplitL \"MYTK\". iFrame. iSplitL \"TKS\". iFrame.\n      iSplitL \"MEM\". iFrame. iSplitL \"ST\". iFrame. iSplitR \"K\". 2: iFrame.\n      iFrame.\n    }\n\n  Qed.\n\n  Lemma correct_unlock tid:\n    ((own_thread tid)\n       ∗ (ObligationRA.duty (inl tid) [])\n    )\n      ⊢\n      (stsim I tid (topset I) ibot7 ibot7\n             (fun r_src r_tgt => own_thread tid ** ObligationRA.duty (inl tid) [] ** ⌜r_src = r_tgt⌝)\n             false false\n             (AbsLock.unlock_fun tt)\n             (OMod.close_itree TicketLock.omod (SCMem.mod TicketLock.gvs)\n                               (TicketLock.unlock_fun tt))).\n  Proof.\n    iIntros \"[MYTH DUTY]\".\n    unfold AbsLock.unlock_fun, TicketLock.unlock_fun. rred.\n    rewrite close_itree_call. rred.\n    iApply (stsim_sync with \"[DUTY]\"). msubtac. iFrame. iIntros \"DUTY _\".\n    iopen 0 \"I\" \"K\". do 7 iDestruct \"I\" as \"[% I]\". iDestruct \"I\" as \"[TKS [MEM [ST CASES]]]\".\n    iDestruct \"CASES\" as \"[[%CT I] | [%CF [I | [I | I]]]]\"; cycle 1.\n    { subst own. iDestruct \"ST\" as \"[ST0 ST1]\".\n      iApply stsim_getL. iSplit. auto. rred.\n      destruct (Bool.eqb false true) eqn:BEQ. exfalso. inv BEQ.\n      iApply stsim_UB.\n    }\n    { subst own. iDestruct \"ST\" as \"[ST0 ST1]\".\n      iApply stsim_getL. iSplit. auto. rred.\n      destruct (Bool.eqb false true) eqn:BEQ. exfalso. inv BEQ.\n      iApply stsim_UB.\n    }\n    { subst own. iDestruct \"ST\" as \"[ST0 ST1]\".\n      iApply stsim_getL. iSplit. auto. rred.\n      destruct (Bool.eqb false true) eqn:BEQ. exfalso. inv BEQ.\n      iApply stsim_UB.\n    }\n\n    subst own. iDestruct \"ST\" as \"[ST0 ST1]\".\n    iApply stsim_getL. iSplit. auto. rred.\n    destruct (Bool.eqb true true) eqn:BEQ. 2: exfalso; inv BEQ.\n    clear BEQ. ss. rewrite put_rmw.\n    iApply (stsim_rmwL with \"ST1\"). iIntros \"ST1\".\n\n    unfold Mod.wrap_fun, SCMem.load_fun. rred.\n    iDestruct \"MEM\" as \"[MEM0 [MEM1 [MEM2 [MEM3 MEM4]]]]\".\n    iApply stsim_getR. iSplit. eauto. rred.\n    iPoseProof (memory_ra_load with \"MEM0 MEM1\") as \"%LOAD\". des. rewrite LOAD. rred.\n    iApply stsim_tauR. rred.\n    rewrite close_itree_call. rred.\n\n    iPoseProof (ObligationRA.alloc (((Ord.S Ord.O) × Ord.omega) × (Ord.from_nat 2))%ord) as \"> [% [[OBLK OWHI] OPEND]]\".\n    iPoseProof (ObligationRA.white_eq with \"OWHI\") as \"OWHI\".\n    { rewrite Ord.from_nat_S. rewrite Jacobsthal.mult_S. reflexivity. }\n    iPoseProof (ObligationRA.white_split_eq with \"OWHI\") as \"[OWHI TAX]\".\n    iPoseProof (ObligationRA.duty_alloc with \"DUTY OWHI\") as \"> DUTY\".\n\n    iDestruct \"I\" as \"[I0 [I1 [I2 [I3 [% I5]]]]]\".\n    iPoseProof (black_updatable with \"I5\") as \">I5\".\n    { instantiate (1:=(now, Tkst.d k)). econs 2. ss. split; try lia. }\n    iPoseProof (black_white_update with \"MEM3 I0\") as \">[MEM3 HOLD]\". instantiate (1:=(now, tid)).\n\n    iApply (stsim_yieldR_strong with \"[DUTY TAX]\").\n    { iSplitL \"DUTY\". iFrame. iApply ObligationRA.tax_cons_fold. iSplit. 2: auto.\n      iApply ObligationRA.white_eq. 2: iFrame.\n      rewrite Ord.from_nat_1. rewrite Jacobsthal.mult_1_r. reflexivity.\n    }\n    iIntros \"DUTY _\".\n    iMod (\"K\" with \"[MYTH TKS MEM0 MEM1 MEM2 MEM3 MEM4 ST0 ST1 I1 I2 I3 I5 OBLK OPEND DUTY]\") as \"_\".\n    { iExists mem, false, l, tks, now, next, tid.\n      remember (\n    (⌜false = true⌝ ** ticket_lock_inv_locked l tks now next tid)\n    ∨ (⌜false = false⌝ **\n       ticket_lock_inv_unlocking l tks now next tid\n       ∨ ticket_lock_inv_unlocked0 l tks now next tid\n       ∨ ticket_lock_inv_unlocked1 l tks now next tid))%I as temp.\n      iFrame. subst temp.\n      iRight. iSplit. auto. iLeft. iFrame.\n      iExists _, _. iFrame.\n    }\n    iModIntro. clear_upto tid.\n\n    iopen 0 \"I\" \"K\". do 7 iDestruct \"I\" as \"[% I]\". iDestruct \"I\" as \"[TKS [MEM [ST CASES]]]\".\n    iDestruct \"CASES\" as \"[[%CT I] | [%CF [I | [I | I]]]]\"; cycle 2.\n    { iDestruct \"I\" as \"[I _]\". iPoseProof (white_white_excl with \"HOLD I\") as \"%FF\". inv FF. }\n    { do 2 iDestruct \"I\" as \"[% I]\". iDestruct \"I\" as \"[I _]\".\n      iPoseProof (white_white_excl with \"HOLD I\") as \"%FF\". inv FF. }\n    { iDestruct \"I\" as \"[I _]\". iPoseProof (white_white_excl with \"HOLD I\") as \"%FF\". inv FF. }\n\n    unfold Mod.wrap_fun, SCMem.store_fun. rred.\n    iDestruct \"ST\" as \"[ST0 ST1]\". iDestruct \"MEM\" as \"[MEM0 [MEM1 [MEM2 [MEM3 MEM4]]]]\".\n    iApply stsim_getR. iSplit. auto. rred.\n    iPoseProof (memory_ra_store with \"MEM0 MEM1\") as \"[% [%STORE >[MEM0 MEM1]]]\".\n    rewrite STORE. rred. rewrite put_rmw. rred.\n    iApply (stsim_rmwR with \"ST0\"). iIntros \"ST0\". rred.\n    iApply stsim_tauR. rred.\n\n    iPoseProof (black_white_equal with \"MEM3 HOLD\") as \"%EQ\". inv EQ.\n    remember (S now) as now'.\n    replace (now + 1) with now'. 2: lia.\n    iPoseProof (black_white_update with \"MEM3 HOLD\") as \">[MEM3 HOLD]\". instantiate (1:=(now', tid)).\n    iPoseProof (black_updatable with \"MEM4\") as \">MEM4\".\n    { instantiate (1:=now'). lia. }\n    iDestruct \"I\" as \"[I1 [%I2 [I3 [I4 I5]]]]\".\n    do 2 iDestruct \"I5\" as \"[% I5]\". iDestruct \"I5\" as \"[I5 [_ [OPEND DUTY]]]\".\n    iPoseProof (ObligationRA.pending_shot with \"OPEND\") as \">OSHOT\".\n    iPoseProof (ObligationRA.duty_done with \"DUTY OSHOT\") as \">DUTY\".\n\n    destruct l as [ | yourt waits].\n    { iPoseProof (black_updatable with \"I5\") as \">I5\".\n      { instantiate (1:=(now', Tkst.a k)). econs 1; try lia. }\n      iAssert (ticket_lock_inv_mem m1 now' next tid)%I with \"[MEM0 MEM1 MEM2 MEM3 MEM4]\" as \"MEM\".\n      iFrame.\n      iAssert (ticket_lock_inv_state m1 false tks)%I with \"[ST0 ST1]\" as \"ST\". iFrame.\n      iMod (\"K\" with \"[TKS MEM ST I3 I4 I5 HOLD]\") as \"_\".\n      { do 7 iExists _. iSplitL \"TKS\". iFrame. iSplitL \"MEM\". iFrame. iSplitL \"ST\". iFrame.\n        iRight. iSplit. auto. iRight. iLeft. iFrame. iSplit.\n        iPureIntro. split; eauto. inv I2; ss.\n        iExists _. iFrame.\n      }\n      iApply (stsim_sync with \"[DUTY]\"). msubtac. iFrame. iIntros \"DUTY _\".\n      iApply stsim_tauR.\n      iApply stsim_ret. iModIntro. iFrame. auto.\n    }\n\n    iPoseProof (list_prop_sum_cons_unfold with \"I4\") as \"[[YDUTY [% YMAPS]] I4]\".\n    iPoseProof (ObligationRA.alloc (((Ord.S Ord.O) × Ord.omega) × (Ord.S (Ord.from_nat u)))%ord) as \"> [% [[OBLK OWHI] OPEND]]\".\n    iPoseProof (ObligationRA.white_eq with \"OWHI\") as \"OWHI\".\n    { rewrite Jacobsthal.mult_S. reflexivity. }\n    iPoseProof (ObligationRA.white_split_eq with \"OWHI\") as \"[OWHI YTAX]\".\n    iPoseProof (ObligationRA.duty_alloc with \"YDUTY OWHI\") as \"> YDUTY\".\n\n    iPoseProof (black_updatable with \"I5\") as \">I5\".\n    { instantiate (1:=(now', Tkst.b k0)). econs 1; try lia. }\n    iAssert (ticket_lock_inv_mem m1 now' next tid)%I with \"[MEM0 MEM1 MEM2 MEM3 MEM4]\" as \"MEM\".\n    iFrame.\n    iAssert (ticket_lock_inv_state m1 false tks)%I with \"[ST0 ST1]\" as \"ST\". iFrame.\n    iMod (\"K\" with \"[TKS MEM ST I3 HOLD YMAPS I4 OBLK OPEND YTAX YDUTY I5]\") as \"_\".\n    { subst now'. do 7 iExists _. iSplitL \"TKS\". iFrame. iSplitL \"MEM\". iFrame.\n      iSplitL \"ST\". iFrame. iRight. iSplit. auto. iRight. iRight. iExists yourt, waits.\n      iFrame. iSplit. auto. iSplit. auto.\n      iExists k0, _, u. iFrame.\n    }\n    iApply (stsim_sync with \"[DUTY]\"). msubtac. iFrame. iIntros \"DUTY _\".\n    iApply stsim_tauR.\n    iApply stsim_ret. iModIntro. iFrame. auto.\n\n  Qed.\n\nEnd SIM.\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/example/TicketLockSC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.26457841019758804}}
{"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\nRequire Export Fiat.QueryStructure.Implementation.DataStructures.Bags.BagsInterface\n        Fiat.QueryStructure.Implementation.DataStructures.Bags.BagsProperties.\nRequire Import\n        Coq.FSets.FMapInterface\n        Coq.FSets.FMapFacts\n        Coq.FSets.FMapAVL\n        Coq.ZArith.ZArith\n        Fiat.Common\n        Fiat.Common.List.ListFacts\n        Fiat.Common.List.FlattenList\n        Fiat.Common.SetEqProperties\n        Fiat.Common.FMapExtensions\n        Fiat.Common.List.PermutationFacts\n        Fiat.QueryStructure.Specification.SearchTerms.ListPrefix.\n\nModule TrieBag (X:OrderedType).\n\n  Module XMap := FMapAVL.Make X.\n  Module Import XMapFacts := WFacts_fun X XMap.\n  Module Import MoreXMapFacts := FMapExtensions_fun X XMap.\n\n  Section TrieBagDefinitions.\n\n    Definition SearchTerm := option (list X.t).\n\n    Context {BagType TItem SearchTermType UpdateTermType : Type}\n            (TBag : Bag BagType TItem SearchTermType UpdateTermType)\n            (RepInv : BagType -> Prop)\n            (ValidUpdate : UpdateTermType -> Prop)\n            (TBagCorrect : CorrectBag RepInv ValidUpdate TBag)\n            (projection: TItem -> list X.t).\n\n    Import XMap.Raw.\n    Import XMap.Raw.Proofs.\n\n    Definition Map := t.\n\n    Inductive Trie :=\n    | Node : BagType -> Map Trie -> Trie.\n\n    Definition TrieNode (trie : Trie) :=\n      match trie with\n        | Node bag tries => bag\n      end.\n\n    Definition SubTries (trie : Trie) :=\n      match trie with\n        | Node bag tries => tries\n      end.\n\n    (* Emptiness *)\n\n    Definition TrieBag_bempty := Node bempty (empty Trie).\n\n    Definition IsPrefix l (st : list X.t) : bool :=\n      if Prefix_dec X.eq_dec l st then true else false.\n\n    Arguments IsPrefix _ _  / .\n\n    Definition TrieBag_bfind_matcher\n               (search_term: SearchTerm * SearchTermType) (item: TItem) :=\n      match fst search_term with\n        | Some st =>\n          IsPrefix (projection item) st\n        | None => true\n      end && (bfind_matcher (snd search_term) item).\n\n    Definition XMapfold\n               (A : Type) (f : X.t -> Trie -> A -> A) :=\n      fix XMapfold (m : tree Trie) (a : A) {struct m} : A :=\n      match m with\n        | XMap.Raw.Leaf => a\n        | XMap.Raw.Node l x d r _ => XMapfold r (f x d (XMapfold l a))\n      end.\n\n    Lemma XMapfold_eq A f\n    : forall m acc,\n        @XMapfold A f m acc =\n        @XMap.Raw.fold _ A f m acc.\n    Proof.\n      unfold XMapfold, XMap.Raw.fold; simpl.\n      induction m; eauto.\n      intros; rewrite IHm1, IHm2; reflexivity.\n    Qed.\n\n    Fixpoint Trie_enumerate\n             (t : Trie)\n             {struct t}\n    : list BagType :=\n      match t with\n        | Node bag tries =>\n          XMapfold (fun _ tries bags =>\n                      Trie_enumerate tries ++ bags) tries [bag]\n      end.\n\n    Definition TrieBag_benumerate\n               (container: Trie)\n      := flatten (List.map benumerate (Trie_enumerate container)).\n\n    Fixpoint Trie_find\n             (trie : Trie)\n             (st : list X.t)\n    : list BagType :=\n      (TrieNode trie) :: match st with\n                           | nil => [ ]\n                           | key :: st' =>\n                             match find key (SubTries trie) with\n                               | Some subtrie => Trie_find subtrie st'\n                               | None => [ ]\n                             end\n                         end.\n\n    Fixpoint Trie_find'\n             (trie : Trie)\n             (st : list X.t)\n      : list BagType :=\n      (TrieNode trie) ::\n                      XMapfold (fun k tries found =>\n                                  (Trie_find' tries st) ++ found) (SubTries trie) [ ].\n\n    Definition TrieBag_bcount\n               (trie : Trie)\n               (key_searchterm: SearchTerm * SearchTermType)\n    : nat :=\n      match key_searchterm with\n        | (Some st, search_term) =>\n          fold_left plus (List.map (fun bag : BagType => bcount bag search_term)\n                                   (Trie_find trie st)) 0\n        | (None, search_term) =>\n          fold_left plus (List.map (fun bag : BagType => bcount bag search_term)\n                                   (Trie_enumerate trie)) 0\n      end.\n\n    Definition TrieBag_bfind\n               (trie : Trie)\n               (key_searchterm: SearchTerm * SearchTermType)\n    : list TItem :=\n      match key_searchterm with\n      | (Some st, search_term) =>\n        flatten (List.map (fun bag : BagType => bfind bag search_term)\n                                 (Trie_find trie st))\n      | (None, search_term) =>\n        flatten (List.map (fun bag : BagType => bfind bag search_term)\n                                 (Trie_enumerate trie))\n      end.\n\n    Fixpoint Trie_add\n             (trie : Trie)\n             (st : list X.t)\n             (item : TItem) : Trie :=\n      match st with\n        | [ ] =>\n          Node (binsert (TrieNode trie) item) (SubTries trie)\n        | key :: st' =>\n          match find key (SubTries trie) with\n            | Some subtrie =>\n              Node (TrieNode trie)\n                   (add key (Trie_add subtrie st' item)\n                        (SubTries trie))\n            | None =>\n              Node (TrieNode trie)\n                   (add key (Trie_add TrieBag_bempty st' item)\n                        (SubTries trie))\n          end\n      end.\n\n    Definition TrieBag_binsert\n               (trie : Trie)\n               (item: TItem) : Trie :=\n      Trie_add trie (projection item) item.\n\n    Fixpoint Trie_delete\n             (trie : Trie)\n             (st : list X.t)\n             (search_term : SearchTermType)\n    : (list TItem) * Trie :=\n      match st with\n        | nil =>\n          let (deletedItems, bag') :=\n              bdelete (TrieNode trie) search_term in\n          (deletedItems, Node bag' (SubTries trie))\n        | key :: st' =>\n          let (deletedItems, bag') :=\n              bdelete (TrieNode trie) search_term in\n          match find key (SubTries trie) with\n            | Some subtrie =>\n              let (deletedSubItems, bag'') :=\n                  Trie_delete subtrie st' search_term in\n              (deletedItems ++ deletedSubItems,\n               Node bag' (add key bag'' (SubTries trie)))\n            | None =>\n              (deletedItems, Node bag' (SubTries trie))\n          end\n      end.\n\n    Fixpoint Trie_delete'\n             (trie : Trie)\n             (search_term : SearchTermType)\n             {struct trie}\n    : (list TItem) * Trie :=\n      match trie with\n      | Node bag tries =>\n        let (deletedItems, bag') :=\n            bdelete (TrieNode trie) search_term in\n        let tries' :=\n            XMapfold (fun k tries (deleted : (list TItem) * _)  =>\n                        let (deletedItems', bag') := Trie_delete' tries search_term in\n                        let (deletedItems'', bags') := deleted in\n                        (deletedItems' ++ deletedItems'', XMap.add k bag' bags'))\n                     tries ([ ], XMap.empty _) in\n        (deletedItems ++ fst tries', Node bag' (XMap.this (snd tries')))\n      end.\n\n    Definition TrieBag_bdelete\n               (trie : Trie)\n               (key_searchterm : SearchTerm * SearchTermType)\n      : (list TItem) * Trie :=\n      match key_searchterm with\n      | (Some st, search_term) => Trie_delete trie st search_term\n      | (None, search_term) => Trie_delete' trie search_term\n      end.\n\n    Fixpoint Trie_update\n             (trie : Trie)\n             (st : list _)\n             (search_term : SearchTermType)\n             (updateTerm : UpdateTermType)\n    : (list TItem) * Trie :=\n      match st with\n        | nil =>\n          let (updatedItems, bag') :=\n              bupdate (TrieNode trie) search_term updateTerm in\n          (updatedItems, Node bag' (SubTries trie))\n        | key :: st' =>\n          let (updatedItems, bag') :=\n              bupdate (TrieNode trie) search_term updateTerm in\n          match find key (SubTries trie) with\n            | Some subtrie =>\n              let (updatedSubItems, bag'') :=\n                  Trie_update subtrie st' search_term updateTerm in\n              (updatedItems ++ updatedSubItems,\n               Node bag' (add key bag'' (SubTries trie)))\n            | None =>\n              (updatedItems, Node bag' (SubTries trie))\n          end\n      end.\n\n    Fixpoint Trie_update'\n             (trie : Trie)\n             (search_term : SearchTermType)\n             (updateTerm : UpdateTermType)\n             {struct trie}\n    : (list TItem) * Trie :=\n      match trie with\n      | Node bag tries =>\n        let (updatedItems, bag') :=\n            bupdate (TrieNode trie) search_term updateTerm in\n        let tries' :=\n            XMapfold (fun k tries (updated : (list TItem) * _)  =>\n                        let (updatedItems', bag') := Trie_update' tries search_term updateTerm in\n                        let (updatedItems'', bags') := updated in\n                        (updatedItems' ++ updatedItems'', XMap.add k bag' bags'))\n                     tries ([ ], XMap.empty _) in\n        (updatedItems ++ fst tries', Node bag' (XMap.this (snd tries')))\n      end.\n\n    Definition TrieBag_bupdate\n               (trie : Trie)\n               (key_searchterm : SearchTerm * SearchTermType)\n               (updateTerm : UpdateTermType)\n      : (list TItem) * Trie :=\n      match key_searchterm with\n      | (Some st, search_term) => Trie_update trie st search_term updateTerm\n      | (None, search_term) => Trie_update' trie search_term updateTerm\n      end.\n\n    Definition WFMap := bst.\n\n    Definition Prefix (s s' : list X.t) :=\n      exists s'', eqlistA X.eq (s ++ s'') s'.\n\n    Lemma IsPrefix_iff_Prefix :\n      forall (s s' : list X.t),\n        IsPrefix s s' = true <-> Prefix s s'.\n    Proof.\n      unfold Prefix; split; revert s'; induction s; intros s' H.\n      - eexists s'; reflexivity.\n      - destruct s'; simpl in H.\n        + discriminate.\n        + destruct (F.eq_dec a t); [subst | discriminate].\n          unfold IsPrefix in IHs.\n          destruct (IHs s').\n          destruct (Prefix_dec F.eq_dec s s'); try discriminate; eauto.\n          eexists; subst; eauto.\n          simpl; econstructor; eauto.\n      - simpl; reflexivity.\n      - destruct s'; simpl in *; destruct H.\n        + inversion H.\n        + inversion H; subst; destruct (F.eq_dec a t).\n          destruct (Prefix_dec F.eq_dec s s'); eauto.\n          exfalso; apply n; eexists; eauto.\n          congruence.\n    Qed.\n\n    Inductive TrieOK : Trie -> list X.t -> Prop :=\n    | NodeSomeOK :\n        forall bag subtries st,\n          RepInv bag\n          -> bst subtries\n          -> (forall (item: TItem),\n                List.In item (benumerate bag) ->\n                eqlistA X.eq (projection item) st)\n          -> (forall k subtrie,\n                MapsTo k subtrie subtries\n                -> TrieOK subtrie (st ++ [k]))\n          -> TrieOK (Node bag subtries) st.\n\n    Lemma SubTrieMapBST\n    : forall bag subtries st,\n        TrieOK (Node bag subtries) st\n        -> bst subtries.\n    Proof.\n      inversion 1; eauto.\n    Qed.\n\n    Lemma SubTrieMapBST'\n    : forall trie st,\n        TrieOK trie st -> bst (SubTries trie).\n    Proof.\n      inversion 1; eauto.\n    Qed.\n\n    Hint Resolve SubTrieMapBST SubTrieMapBST'.\n\n    Lemma TrieNode_RepInv\n    : forall bag subtries st,\n        TrieOK (Node bag subtries) st\n        -> RepInv bag.\n    Proof.\n      inversion 1; eauto.\n    Qed.\n\n    Lemma TrieNode_RepInv'\n    : forall trie st,\n        TrieOK trie st -> RepInv (TrieNode trie).\n    Proof.\n      inversion 1; eauto.\n    Qed.\n\n    Hint Resolve TrieNode_RepInv TrieNode_RepInv'.\n\n    Lemma SubTrieOK\n    : forall trie k subtrie st,\n        TrieOK trie st\n        -> find k (SubTries trie) = Some subtrie\n        -> TrieOK subtrie (st ++ [k]).\n    Proof.\n      destruct trie; simpl.\n      induction m; simpl in *; intros.\n      - discriminate.\n      - inversion H; subst.\n        case_eq (X.compare k0 k); intros; rewrite H1 in H0.\n        + eapply IHm1; eauto.\n          econstructor; simpl in *; eauto.\n          inversion H4; subst; eauto.\n        + injections; simpl in *.\n          eapply (H7 k0 _); eauto.\n        + eapply IHm2; eauto.\n          econstructor; simpl in *; eauto.\n          inversion H4; subst; eauto.\n    Qed.\n\n    Hint Resolve SubTrieOK.\n\n    Definition TrieBagRepInv (trie : Trie) := TrieOK trie [ ].\n\n    Definition TrieBag_ValidUpdate (update_term : UpdateTermType) :=\n      ValidUpdate update_term /\\\n      forall K item,\n        eqlistA X.eq (projection item) K\n        -> eqlistA X.eq (projection (bupdate_transform update_term item)) K.\n\n    Lemma Trie_Empty_RepInv :\n      TrieBagRepInv (TrieBag_bempty).\n    Proof.\n      unfold TrieBagRepInv; intros; econstructor; simpl in *.\n      apply bempty_RepInv.\n      econstructor.\n      intros; exfalso; eapply benumerate_empty; eauto.\n      intros; exfalso; eapply empty_1; eauto.\n    Qed.\n\n    Functional Scheme Trie_add_ind := Induction for Trie_add Sort Prop.\n    Functional Scheme Trie_delete_ind := Induction for Trie_delete Sort Prop.\n    Functional Scheme Trie_update_ind := Induction for Trie_update Sort Prop.\n    Functional Scheme Trie_find_ind := Induction for Trie_find Sort Prop.\n\n    Hint Resolve add_bst.\n    Hint Constructors eqlistA.\n\n    Lemma Trie_add_Preserves_TreeOK\n    : forall trie item st1 st2,\n        eqlistA X.eq (projection item) (st2 ++ st1)\n        -> TrieOK trie st2\n        -> TrieOK (Trie_add trie st1 item) st2.\n    Proof.\n      intros trie item st1; eapply Trie_add_ind; intros; subst.\n      - econstructor; inversion H0; subst; eauto.\n        + eapply binsert_RepInv; eauto.\n        + intros; rewrite binsert_enumerate in H5 by eauto.\n          simpl in *; intuition; subst.\n          rewrite H, app_nil_r; reflexivity.\n      - econstructor; inversion H1; subst; simpl; eauto.\n        intros; destruct (X.eq_dec k key0).\n        apply find_1 in H6; eauto.\n        pose proof (add_1 subtries (Trie_add subtrie st' item0) (X.eq_sym e)) as H7; apply find_1 in H7; eauto.\n        rewrite H6 in H7; injections; intros; subst.\n        eapply H; eauto.\n        rewrite <- app_assoc.\n        rewrite H0.\n        apply eqlistA_app;\n          repeat first [econstructor; eauto\n                       | try reflexivity ]; try typeclasses eauto;\n          try (symmetry; assumption).\n        apply H5.\n        apply MapsTo_1 with (x := key0).\n        symmetry; eauto.\n        apply find_2; eassumption.\n        apply H5.\n        eapply add_3 in H6; eauto; intuition.\n      - econstructor; inversion H1; subst; simpl; eauto.\n        + intros; destruct (X.eq_dec k key0).\n          apply find_1 in H6; eauto.\n          pose proof (add_1 subtries (Trie_add TrieBag_bempty st' item0) (X.eq_sym e)) as H7; apply find_1 in H7; eauto.\n          rewrite H6 in H7; injections; intros; subst.\n          eapply H; eauto.\n          rewrite <- app_assoc.\n          rewrite H0.\n          apply eqlistA_app;\n            repeat first [econstructor; eauto\n                         | try reflexivity ]; try typeclasses eauto;\n            try (symmetry; assumption).\n          unfold TrieBagRepInv; intros; econstructor; simpl in *.\n          apply bempty_RepInv.\n          econstructor.\n          intros; exfalso; eapply benumerate_empty; eauto.\n          intros; exfalso; eapply empty_1; eauto.\n          apply H5.\n          eapply add_3 in H6; eauto; intuition.\n    Qed.\n\n    Corollary TrieBag_binsert_Preserves_RepInv :\n      binsert_Preserves_RepInv TrieBagRepInv TrieBag_binsert.\n    Proof.\n      unfold binsert_Preserves_RepInv; intros.\n      eapply Trie_add_Preserves_TreeOK; simpl.\n      reflexivity.\n      apply containerCorrect.\n    Qed.\n\n    Lemma Trie_ind'\n          (P : Trie -> list key -> Prop)\n          (IH : forall (b : BagType) (m : Map Trie) l,\n              (forall k trie l, MapsTo k trie m -> P trie (l ++ [k]))\n              -> P (Node b m) l)\n          (trie : Trie)\n      : forall l, P trie l.\n          refine ((fix Trie_ind trie :=\n                    match trie return forall l, P trie l with\n                    | Node b tries => fun l => IH _ _ _ ((fun f0 =>\n                                                fix F (t : t Trie) : (forall k trie l, MapsTo k trie t -> P trie (l ++ [k])) :=\n                                                match t as t0 return ((forall k trie l, MapsTo k trie t0 -> P trie (l ++ [k]))) with\n                                                | Leaf =>  _\n                                                | XMap.Raw.Node t0 k e t1 t2 => f0 t0 (F t0) k e t1 (F t1) t2\n                                                end) _ tries)\n                    end) trie).\n          - intros; inversion H.\n          - intros; inversion H; subst.\n            + let Trie_ind0 := match goal with Trie_ind0 : forall (trie : Trie) (l : list key), ?P trie l |- _ => constr:(Trie_ind0) end in\n              apply Trie_ind0.\n            + eapply x0; eauto.\n            + eapply x4; eauto.\n    Qed.\n\n    Definition XMapfold_ind\n               (P : Trie -> list BagType -> list X.t-> Prop)\n               (f : forall trie st, P trie (Trie_enumerate trie) st)\n               (m : tree Trie) (is_bst : bst m) :\n      forall k trie st , MapsTo k trie m ->\n                         P trie (Trie_enumerate trie) (st ++ [k]).\n    Proof.\n      refine ((fix XMapfold (m : tree Trie) {struct m} :\n                 bst m ->\n                 forall k trie st, MapsTo k trie m ->\n                                   P trie (Trie_enumerate trie) (st ++ [k]) :=\n                 match m with\n                   | XMap.Raw.Leaf => _\n                   | XMap.Raw.Node l x d r _ => _\n                 end) m is_bst).\n      - intros; apply find_1 in H0; simpl in H0;\n        [ discriminate | eauto ].\n      - intros; apply find_1 in H0; simpl in H0;\n        [ destruct (X.compare k x)\n        | eassumption ].\n        + apply find_2 in H0.\n          let XMapfold0 := match goal with XMapfold0 : forall m : XMap.Raw.t Trie, _ -> forall (k : key) (trie : Trie) (st : list key), _ -> _ |- _ => constr:(XMapfold0) end in\n          eapply (XMapfold0 l); eauto.\n          inversion H; subst; eauto.\n        + pose proof (f d (st ++ [k])).\n          injections; eassumption.\n        + apply find_2 in H0.\n          let XMapfold0 := match goal with XMapfold0 : forall m : XMap.Raw.t Trie, _ -> forall (k : key) (trie : Trie) (st : list key), _ -> _ |- _ => constr:(XMapfold0) end in\n          eapply (XMapfold0 r); eauto.\n          inversion H; subst; eauto.\n    Defined.\n\n    Lemma TrieBag_bdelete_Preserves_RepInv :\n      bdelete_Preserves_RepInv TrieBagRepInv TrieBag_bdelete.\n    Proof.\n      unfold bdelete_Preserves_RepInv, TrieBagRepInv;\n      intros trie search_term; remember []; clear Heql; revert l.\n      unfold TrieBag_bdelete.\n      destruct search_term as [ [l | ] s].\n      { eapply Trie_delete_ind; intros; subst.\n        - econstructor; inversion containerCorrect; subst; eauto.\n          + pose proof (bdelete_RepInv bag search_term) as e'; simpl in *;\n            rewrite e0 in e'; eapply e'.\n            inversion containerCorrect; eauto.\n          + intros; eapply H1.\n            destruct (bdelete_correct bag search_term); eauto.\n            simpl in *; rewrite e0 in *; simpl in *.\n            rewrite H4 in H3.\n            rewrite In_partition; eauto.\n        - econstructor; inversion containerCorrect; subst; eauto.\n          + pose proof (bdelete_RepInv bag search_term) as e'; simpl in *;\n            rewrite e0 in e'; eapply e'; eauto.\n          + intros; eapply H2.\n            destruct (bdelete_correct bag search_term); eauto.\n            simpl in *; rewrite e0 in *; simpl in *.\n            rewrite H5 in H4.\n            rewrite In_partition; eauto.\n          + intros; destruct (X.eq_dec k key0).\n            * apply find_1 in H4; eauto.\n              simpl in *.\n              pose proof (add_1 subtries bag'' (X.eq_sym e)) as H7; apply find_1 in H7; eauto.\n              rewrite H4 in H7; injections; intros; subst.\n              rewrite e2 in H; eapply H.\n              eapply H3.\n              apply MapsTo_1 with (x := key0).\n              symmetry; eauto.\n              apply find_2; eauto.\n            * apply H3.\n              eapply add_3; eauto; intuition.\n        - simpl; econstructor; inversion containerCorrect; subst; eauto.\n          + pose proof (bdelete_RepInv bag search_term) as e'; simpl in *;\n            rewrite e0 in e'; eapply e'.\n            inversion containerCorrect; eauto.\n          + intros; eapply H1.\n            destruct (bdelete_correct bag search_term); eauto.\n            simpl in *; rewrite e0 in *; simpl in *.\n            rewrite H4 in H3.\n            rewrite In_partition; eauto.\n      }\n      { intro; pattern trie, l; apply Trie_ind'; simpl; intros.\n        intros; inversion containerCorrect; subst.\n        case_eq (bdelete b s); simpl; intros.\n        econstructor.\n        + pose proof (bdelete_RepInv b s) as e'; simpl in *.\n          rewrite H0 in e'; eapply e'; eauto.\n        + apply XMap.is_bst.\n        + intros; eapply H4.\n          destruct (bdelete_correct b s); eauto.\n          simpl in *; rewrite H0 in *; simpl in *.\n          rewrite H5 in H1.\n          rewrite In_partition; eauto.\n        + intros; rewrite XMapfold_eq in H1.\n          setoid_rewrite (fold_pair (XMap.Bst H3)) in H1; simpl in H1.\n          assert (XMap.MapsTo k subtrie\n                              (XMap.fold\n                                 (fun (k0 : XMap.key) (m0 : Trie) (b' : XMap.t Trie) =>\n                                    XMap.add k0 (snd (Trie_delete' m0 s)) b')\n                                 {| XMap.this := m; XMap.is_bst := H3 |}\n                                 (XMap.empty Trie))) by apply H1; clear H1.\n          setoid_rewrite FMap_Insert_fold_add_map_eq in H5.\n          rewrite map_mapsto_iff in H5; destruct_ex; intuition; subst.\n          eapply H; eauto.\n      }\n    Qed.\n\n    Lemma ValidUpdate_TrieBag_ValidUpdate :\n      forall updateTerm,\n        TrieBag_ValidUpdate updateTerm\n        -> ValidUpdate updateTerm.\n    Proof.\n      inversion 1; subst; eauto.\n    Qed.\n\n    Hint Resolve ValidUpdate_TrieBag_ValidUpdate.\n\n    Lemma TrieBag_bupdate_Preserves_RepInv :\n      bupdate_Preserves_RepInv\n        TrieBagRepInv\n        TrieBag_ValidUpdate\n        TrieBag_bupdate.\n    Proof.\n      unfold bupdate_Preserves_RepInv, TrieBagRepInv;\n      intros trie search_term update_term; remember [];\n      clear Heql; revert l.\n      unfold TrieBag_bupdate.\n      destruct search_term as [ [l | ] s].\n      {\n        eapply Trie_update_ind; intros; subst.\n      - econstructor; inversion containerCorrect; subst; eauto.\n        + pose proof (bupdate_RepInv bag search_term updateTerm) as e'; simpl in *;  rewrite e0 in e'; eapply e'; eauto.\n        + intros; destruct (bupdate_correct bag search_term updateTerm);\n          eauto.\n          simpl in *; rewrite e0 in *; simpl in *.\n          rewrite H4 in H3.\n          apply in_app_or in H3; intuition.\n          * eapply H1; erewrite In_partition; eauto.\n          * rewrite in_map_iff in H6; destruct_ex; intuition.\n            inversion valid_update; subst.\n            apply H8; apply H1; rewrite In_partition; eauto.\n      - econstructor; inversion containerCorrect; subst; eauto.\n        + pose proof (bupdate_RepInv bag search_term updateTerm) as e'; simpl in *;  rewrite e0 in e'; eapply e'; eauto.\n        + intros; destruct (bupdate_correct bag search_term updateTerm);\n          eauto.\n          simpl in *; rewrite e0 in *; simpl in *.\n          rewrite H5 in H4.\n          apply in_app_or in H4; intuition.\n          * eapply H2; erewrite In_partition; eauto.\n          * rewrite in_map_iff in H7; destruct_ex; intuition.\n            inversion valid_update; subst.\n            apply H9; apply H2; rewrite In_partition; eauto.\n        + intros; destruct (X.eq_dec k key0).\n          * apply find_1 in H4; eauto.\n            simpl in *.\n            pose proof (add_1 subtries bag'' (X.eq_sym e)) as H7; apply find_1 in H7; eauto.\n            rewrite H4 in H7; injections; intros; subst.\n            rewrite e2 in H; eapply H; eauto.\n            eapply H3.\n            apply MapsTo_1 with (x := key0).\n            symmetry; eauto.\n            apply find_2; eauto.\n          * apply H3.\n            eapply add_3; eauto; intuition.\n      - simpl; econstructor; inversion containerCorrect; subst; eauto.\n        + pose proof (bupdate_RepInv bag search_term updateTerm) as e'; simpl in *;  rewrite e0 in e'; eapply e'; eauto.\n        + intros; destruct (bupdate_correct bag search_term updateTerm);\n          eauto.\n          simpl in *; rewrite e0 in *; simpl in *.\n          rewrite H4 in H3.\n          apply in_app_or in H3; intuition.\n          * eapply H1; erewrite In_partition; eauto.\n          * rewrite in_map_iff in H6; destruct_ex; intuition.\n            inversion valid_update; subst.\n            apply H8; apply H1; rewrite In_partition; eauto.\n      }\n      { intro; pattern trie, l; apply Trie_ind'; simpl; intros.\n        intros; inversion containerCorrect; subst.\n        case_eq (bupdate b s update_term); simpl; intros.\n        econstructor.\n        + pose proof (bupdate_RepInv b s update_term) as e'; simpl in *.\n          rewrite H0 in e'; eapply e'; eauto.\n        + apply XMap.is_bst.\n        + intros; destruct (bupdate_correct b s update_term); eauto.\n          simpl in *; rewrite H0 in *; simpl in *.\n          intros; rewrite H5 in H1.\n          apply in_app_or in H1; destruct H1.\n          * intros; eapply H4.\n            rewrite In_partition; eauto.\n          * rewrite in_map_iff in H1; destruct H1 as [item' [item'_eq In_item'] ].\n            rewrite <- item'_eq in *.\n            destruct valid_update as [valid_update valid_update'].\n            eapply valid_update'.\n            eapply H4.\n            rewrite In_partition; eauto.\n        + intros; rewrite XMapfold_eq in H1.\n          setoid_rewrite (fold_pair (XMap.Bst H3)) in H1; simpl in H1.\n          assert (XMap.MapsTo k subtrie\n                              (XMap.fold\n                                 (fun (k0 : XMap.key) (m0 : Trie) (b' : XMap.t Trie) =>\n                                    XMap.add k0 (snd (Trie_update' m0 s update_term)) b')\n                                 {| XMap.this := m; XMap.is_bst := H3 |}\n                                 (XMap.empty Trie))) by apply H1; clear H1.\n          setoid_rewrite FMap_Insert_fold_add_map_eq in H5.\n          rewrite map_mapsto_iff in H5; destruct_ex; intuition; subst.\n          eapply H; eauto.\n      }\n    Qed.\n\n    Lemma Permutation_app_fold_left\n    : forall l bags,\n        Permutation ((fold_left\n                        (fun (a : list BagType) (p : key * Trie) =>\n                           Trie_enumerate (snd p) ++ a) l\n                        bags))\n                    (bags ++\n                          (fold_left\n                             (fun (a : list BagType) (p : key * Trie) =>\n                                Trie_enumerate (snd p) ++ a) l\n                             [ ])).\n    Proof.\n      induction l; simpl; intros.\n      - rewrite app_nil_r; reflexivity.\n      - rewrite IHl, <- app_assoc,\n        Permutation_app_comm, <- app_assoc.\n        f_equiv.\n        rewrite Permutation_app_comm, <- IHl, app_nil_r; reflexivity.\n    Qed.\n\n    Lemma Permutation_benumerate_fold_left\n    : forall l bags,\n        Permutation (List.map benumerate\n                              (fold_left\n                                 (fun (a : list BagType) (p : key * Trie) =>\n                                    Trie_enumerate (snd p) ++ a) l\n                                 bags))\n                    ((List.map benumerate bags) ++\n                                                (List.map benumerate (fold_left\n                                                                        (fun (a : list BagType) (p : key * Trie) =>\n                                                                           Trie_enumerate (snd p) ++ a) l\n                                                                        [ ]))).\n    Proof.\n      intros; rewrite Permutation_app_fold_left, map_app; eauto.\n    Qed.\n\n    Lemma XMapfoldBst A :\n      forall f m (acc : A) (WFm : bst m),\n        XMapfold f m acc =\n        XMap.fold f (XMap.Bst WFm) acc.\n    Proof.\n      intros; rewrite XMapfold_eq; reflexivity.\n    Qed.\n\n    Ltac replaceXMapfold :=\n      match goal with\n          |- context [XMapfold ?f ?m ?acc] =>\n          let Bst_m := fresh in\n          assert (bst m) as Bst_m;\n            [ eauto | setoid_rewrite (XMapfoldBst f acc Bst_m)]\n      end.\n\n    Lemma XMapfindBst elt :\n      forall k (m : Map elt) (WFm : bst m),\n        find k m = XMap.find k (XMap.Bst WFm).\n    Proof.\n      reflexivity.\n    Qed.\n\n    Lemma Tries_enumerate_app_Proper\n    : Proper\n        (X.eq ==> eq ==> Permutation (A:=BagType) ==> Permutation (A:=BagType))\n        (fun (_ : X.t) (tries : Trie) (bags : list BagType) =>\n           Trie_enumerate tries ++ bags).\n    Proof.\n      unfold Proper, respectful; intros.\n      subst; rewrite H1; reflexivity.\n    Qed.\n\n    Lemma Tries_enumerate_app_transpose_neqkey\n    : transpose_neqkey (Permutation (A:=BagType))\n                       (fun (_ : X.t) (tries : Trie) (bags : list BagType) =>\n                          Trie_enumerate tries ++ bags).\n    Proof.\n      unfold transpose_neqkey; intros; rewrite Permutation_app_swap, <- app_assoc; f_equiv; apply Permutation_app_swap.\n    Qed.\n\n    Lemma benumerate_bempty_nil :\n      benumerate bempty = nil.\n      pose proof benumerate_empty; unfold BagEnumerateEmpty in *.\n      induction (benumerate bempty); eauto.\n      simpl in *; exfalso; eapply H; eauto.\n    Qed.\n\n    Lemma Proper_KeyBasedPartitioningFunction\n    : forall key, Proper (X.eq ==> eq ==> eq) (KeyBasedPartitioningFunction Trie key).\n      unfold Proper, respectful; intros; subst.\n      unfold KeyBasedPartitioningFunction.\n      repeat find_if_inside; eauto;\n        rewrite H in *; intuition.\n    Qed.\n\n    Lemma TrieBag_BagEnumerateEmpty :\n      BagEnumerateEmpty TrieBag_benumerate TrieBag_bempty.\n    Proof.\n      intros;\n      unfold BagEnumerateEmpty, TrieBag_benumerate, flatten; simpl.\n      rewrite app_nil_r; apply benumerate_empty.\n    Qed.\n\n    Lemma Trie_find_TreeOK\n    : forall trie st2 st1,\n        TrieOK trie st1\n        -> forall bag,\n             List.In bag (Trie_find trie st2)\n             -> RepInv bag.\n    Proof.\n      intros trie st2; eapply Trie_find_ind; intros; subst.\n      - inversion H; subst; eauto.\n        simpl in H0; intuition eauto; subst; eauto.\n      - simpl in H1; intuition; subst.\n        + inversion H0; subst; eauto.\n        + eapply (H (st1 ++ [key0])); eauto.\n      - simpl in H0; intuition; subst; eauto.\n    Qed.\n\n    Fixpoint Trie_enumerate_ind\n             (P : Trie -> list BagType -> list X.t -> Prop)\n             (H : forall trie st,\n                    (bst (SubTries trie)\n                     -> forall (k : key) (trie' : Trie),\n                          MapsTo k trie' (SubTries trie) -> P trie' (Trie_enumerate trie') (st ++ [k])) -> P trie (Trie_enumerate trie) st)\n             (trie : Trie)\n             (st : list X.t)\n             {struct trie}\n    : P trie (Trie_enumerate trie) st.\n    Proof.\n      refine (match trie with\n                | Node bag tries => _\n              end).\n      pose proof (@XMapfold_ind P (Trie_enumerate_ind P H) tries).\n      clear Trie_enumerate_ind.\n      eauto.\n    Qed.\n\n    Lemma Permute_XMapfold_cons\n      : forall m l,\n        XMapfold\n          (fun (_ : X.t) (tries : Trie) (bags : list BagType) =>\n             Trie_enumerate tries ++ bags) m l =\n        (XMapfold (fun (_ : X.t) (tries : Trie) (bags : list BagType) =>\n                     Trie_enumerate tries ++ bags) m []) ++ l.\n    Proof.\n      induction m; simpl; eauto.\n      intros.\n      rewrite IHm2; symmetry; rewrite IHm2.\n      rewrite <- !app_assoc; f_equiv; f_equiv.\n      symmetry; eauto.\n    Qed.\n\n    Lemma Trie_enumerate_RepInv\n      : forall trie l,\n        TrieOK trie l\n        -> forall item,\n          List.In item (Trie_enumerate trie)\n          -> RepInv item.\n    Proof.\n      intros trie l; pattern trie, l; eapply Trie_ind'; simpl; intros.\n      inversion H0; subst; clear H0.\n      rewrite Permute_XMapfold_cons in H1; apply List.in_app_or in H1; intuition.\n      - rewrite XMapfold_eq in H0.\n        pose fold_spec_right as e; unfold XMap.fold in e; rewrite (e _ (XMap.Bst H5)) in H0;\n        clear e.\n        assert (exists k trie, List.In (k, trie)\n                                       (XMap.elements (elt := Trie)\n                                       {| XMap.this := m;\n                                          XMap.is_bst := H5 |})\n                               /\\ List.In item (Trie_enumerate trie)).\n        { revert H0; clear.\n          induction\n            (XMap.elements (elt := Trie)\n                           {| XMap.this := m;\n                              XMap.is_bst := H5 |}); simpl; intros; intuition.\n          rewrite fold_right_app in H0; simpl in H0.\n          rewrite fold_left_rev_right in H0; simpl in H0.\n          unfold uncurry in *.\n          rewrite Permutation_app_fold_left in H0; apply in_app_or in H0; intuition.\n          apply in_app_or in H; intuition.\n          destruct a; eauto.\n          destruct IHl as [k [trie' [In_k In_trie] ] ].\n          rewrite fold_left_rev_right; eauto.\n          eexists; eauto.\n          }\n        destruct H1 as [k [trie' [In_k In_trie'] ] ].\n        eapply (H k trie' l0); eauto.\n        eapply elements_mapsto_iff with (m := XMap.Bst H5).\n        eapply InA_In; eauto.\n        econstructor; reflexivity.\n        apply H8.\n        eapply elements_mapsto_iff with (m := XMap.Bst H5).\n        eapply InA_In; eauto.\n        econstructor; reflexivity.\n      - simpl in H0; intuition; subst; eauto.\n    Qed.\n\n    Lemma TrieBag_BagCountCorrect :\n      BagCountCorrect TrieBagRepInv TrieBag_bcount TrieBag_bfind .\n    Proof.\n      unfold TrieBagRepInv, TrieBag_bcount, TrieBag_bfind, BagCountCorrect.\n      simpl; intros; destruct search_term as [ [key | ] search_term ].\n      - rewrite length_flatten.\n        rewrite !foldright_compose.\n        rewrite <- !fold_left_rev_right.\n        rewrite map_map.\n        generalize (Trie_find_TreeOK key containerCorrect).\n        remember 0 as n; clear Heqn; revert n.\n        induction (Trie_find container key); simpl; eauto.\n        intros.\n        intros; rewrite IHl by eauto.\n        rewrite fold_right_app; simpl.\n        rewrite bcount_correct by eauto.\n        rewrite !fold_left_rev_right; simpl.\n        clear; revert n; induction l; simpl; eauto with arith.\n        intros; rewrite IHl; f_equal; omega.\n      - rewrite length_flatten.\n        remember [] as l; replace 0 with (length l) by (subst; eauto).\n        clear Heql; generalize (Trie_enumerate_RepInv containerCorrect).\n        induction (Trie_enumerate container); simpl; eauto.\n        rewrite !foldright_compose, <- !fold_left_rev_right, map_map.\n        intros; unfold compose in *; rewrite bcount_correct by eauto.\n        rewrite !fold_left_rev_right.\n        rewrite <- map_map, <- foldright_compose.\n        unfold compose; rewrite IHl0 by eauto.\n        remember (length l) as n; clear Heqn; generalize n.\n        clear; induction l0; simpl; eauto with arith; intros.\n        rewrite IHl0; f_equal; omega.\n    Qed.\n\n    Lemma Permutation_KeyBasedPartition\n    : forall key m bst_m b,\n        Permutation\n          (fold\n             (fun (_ : XMap.Raw.key) (trie : Trie) (a : list BagType) =>\n                Trie_enumerate trie ++ a) m b)\n          (XMap.fold\n             (fun (_ : XMap.key) (trie : Trie) (a : list BagType) =>\n                Trie_enumerate trie ++ a)\n             (fst\n                (partition (KeyBasedPartitioningFunction Trie key)\n                           {|\n                             XMap.this := m;\n                             XMap.is_bst := bst_m |}))\n             (XMap.fold\n                (fun (_ : XMap.key) (trie : Trie) (a : list BagType) =>\n                   Trie_enumerate trie ++ a)\n                (snd\n                   (partition (KeyBasedPartitioningFunction Trie key)\n                              {|\n                                XMap.this := m;\n                                XMap.is_bst :=  bst_m |}))\n                b)) .\n    Proof.\n      intros.\n      pose proof (partition_Partition_simple\n                    _\n                    (KeyBasedPartitioningFunction Trie key0)\n                    (KeyBasedPartitioningFunction_Proper _ _)\n                    (XMap.Bst bst_m)) as part.\n      erewrite Partition_fold with\n      (f := (fun (_ : key) (trie : Trie) (a : list BagType) =>\n               Trie_enumerate trie ++ a))\n        (m := {| XMap.this := m; XMap.is_bst := bst_m |} )\n        (i := b);\n        (eauto using part, Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n    Qed.\n\n      Lemma In_fold_left_split' :\n      forall bag l acc,\n        List.In bag\n                (acc ++ fold_left\n                     (fun (a0 : list BagType) (p : key * Trie) =>\n                        Trie_enumerate (snd p) ++ a0) l\n                     [ ])\n        <-> List.In bag\n                    ((fold_left\n                        (fun (a0 : list BagType) (p : key * Trie) =>\n                           Trie_enumerate (snd p) ++ a0) l\n                        acc)).\n    Proof.\n      induction l; simpl; intros.\n      - rewrite app_nil_r in *; eauto.\n        reflexivity.\n      - rewrite <- IHl.\n        split; intros.\n        rewrite <- app_assoc; apply in_or_app.\n        apply in_app_or in H; intuition eauto.\n        right; apply in_or_app; eauto.\n        rewrite <- IHl in H0.\n        rewrite <- !app_assoc in H0.\n        apply in_app_or in H0; intuition.\n        apply in_app_or in H; intuition.\n        apply in_app_or in H0; intuition.\n        apply in_or_app; intuition.\n        right; rewrite <- IHl; intuition.\n        apply in_or_app; intuition.\n        rewrite <- IHl in H0.\n        apply in_app_or in H0; intuition.\n        right.\n        rewrite <- IHl.\n        apply in_or_app; auto.\n    Qed.\n\n    Corollary In_fold_left_split :\n      forall (k : X.t) t bag l acc,\n        List.In (k, bag)\n                (List.map (fun bag0 : BagType => (t, bag0))\n                          (acc ++ fold_left\n                               (fun (a0 : list BagType) (p : key * Trie) =>\n                                  Trie_enumerate (snd p) ++ a0) l\n                               [ ]))\n        <-> List.In (k, bag)\n                    (List.map (fun bag0 : BagType => (t, bag0))\n                              (fold_left\n                                 (fun (a0 : list BagType) (p : key * Trie) =>\n                                    Trie_enumerate (snd p) ++ a0) l\n                                 acc)).\n    Proof.\n      intros; rewrite !in_map_iff;\n      split; intros; destruct_ex; intuition;\n      eexists; split; eauto.\n      rewrite In_fold_left_split' in H1; eauto.\n      rewrite <- In_fold_left_split' in H1; eauto.\n    Qed.\n\n    Lemma In_fold_left_map_split' :\n      forall bag l acc,\n        List.In bag\n                (acc ++ fold_left\n                     (fun (a0 : list (key * BagType)) (p : key * Trie) =>\n                      List.map (fun bag0 : BagType => (fst p, bag0))\n                               (Trie_enumerate (snd p)) ++ a0)\n                     l\n                     [ ])\n        <-> List.In bag\n                    (fold_left\n                         (fun (a0 : list (key * BagType)) (p : key * Trie) =>\n                               List.map (fun bag0 : BagType => (fst p, bag0))\n                                        (Trie_enumerate (snd p)) ++ a0)\n                         l\n                         acc).\n    Proof.\n      induction l; simpl; intros.\n      - rewrite app_nil_r in *; eauto.\n        reflexivity.\n      - rewrite <- IHl.\n        split; intros.\n        rewrite <- app_assoc; apply in_or_app.\n        apply in_app_or in H; intuition eauto.\n        right; apply in_or_app; eauto.\n        rewrite <- IHl in H0.\n        rewrite <- !app_assoc in H0.\n        apply in_app_or in H0; intuition.\n        apply in_app_or in H; intuition.\n        apply in_app_or in H0; intuition.\n        apply in_or_app; intuition.\n        right; rewrite <- IHl; intuition.\n        apply in_or_app; intuition.\n        rewrite <- IHl in H0.\n        apply in_app_or in H0; intuition.\n        right.\n        rewrite <- IHl.\n        apply in_or_app; auto.\n    Qed.\n\n    Lemma Trie_add_Correct\n    : forall trie item st1 st2,\n        eqlistA X.eq (projection item) (st2 ++ st1)\n        -> TrieOK trie st2\n        -> Permutation\n             (TrieBag_benumerate (Trie_add trie st1 item))\n             (item :: TrieBag_benumerate trie).\n    Proof.\n      intros trie item st1; eapply Trie_add_ind; intros; subst.\n      - destruct trie0; simpl.\n        unfold TrieBag_benumerate; simpl.\n        rewrite !XMapfold_eq, !fold_1 by eauto.\n        rewrite Permutation_benumerate_fold_left.\n        simpl; rewrite binsert_enumerate; eauto.\n        simpl; constructor.\n        symmetry.\n        rewrite Permutation_benumerate_fold_left; simpl.\n        reflexivity.\n      - destruct trie0; simpl.\n        unfold TrieBag_benumerate; simpl.\n        replaceXMapfold.\n        replaceXMapfold.\n        unfold XMap.fold at 2.\n\n        rewrite Permutation_KeyBasedPartition with (key0 := key0)\n                                                     (bst_m := SubTrieMapBST H1).\n\n        pose proof (@partition_after_KeyBasedPartition_and_add\n                      _ key0 (Trie_add subtrie st' item0) (XMap.Bst (SubTrieMapBST H1)))\n          as part_add.\n\n        rewrite Partition_fold at 1;\n          (eauto using part_add, Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n\n        apply find_2 in e0.\n\n        pose proof (KeyBasedPartition_fst_singleton key0 subtrie (XMap.Bst (SubTrieMapBST H1)) e0) as singleton.\n        pose proof (add_Equal_simple singleton key0 (Trie_add subtrie st' item0)) as singleton'.\n        rewrite (fold_Equal_simpl (eqA := @Permutation BagType) singleton')\n          by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n        rewrite (fold_Equal_simpl (eqA := @Permutation BagType) singleton)\n          by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n        rewrite (fold_Equal_simpl (multiple_adds _ _ _ _))\n          by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n        rewrite !fold_add\n          by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey, empty_In).\n\n        rewrite fold_empty.\n        rewrite !map_app.\n        unfold TrieBag_benumerate in H.\n        rewrite !flatten_app, (H (st2 ++ [key0])); eauto.\n        rewrite <- app_assoc; simpl; eauto.\n        inversion H1; subst; eauto.\n      - destruct trie0; simpl.\n        unfold TrieBag_benumerate; simpl.\n        replaceXMapfold.\n        replaceXMapfold.\n\n        pose proof (@partition_after_KeyBasedPartition_and_add\n                      _ key0 (Trie_add TrieBag_bempty st' item0) (XMap.Bst (SubTrieMapBST H1)))\n          as part_add.\n\n        pose proof (partition_Partition_simple\n                      _\n                      (KeyBasedPartitioningFunction Trie key0)\n                      (KeyBasedPartitioningFunction_Proper _ _)\n                      (XMap.Bst (SubTrieMapBST H1))) as part.\n\n        rewrite Partition_fold at 1;\n          (eauto using part_add, Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n        rewrite Partition_fold with (m := {| XMap.this := m; XMap.is_bst := H3 |} );\n          (eauto using part, Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n        rewrite !fold_add;\n          eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey, empty_In.\n        rewrite map_app, flatten_app.\n        rewrite (H (st2 ++ [key0])); simpl.\n        unfold TrieBag_benumerate; simpl.\n        rewrite benumerate_bempty_nil; simpl.\n        reflexivity.\n        rewrite <- app_assoc; eauto.\n        econstructor; eauto using bempty_RepInv.\n        + rewrite benumerate_bempty_nil in *; simpl in *; intuition.\n        + intros; exfalso; eapply empty_1; eauto.\n        + intro H4.\n          destruct H4.\n          apply (@partition_iff_1 _\n                                  (KeyBasedPartitioningFunction Trie key0)\n                                  (Proper_KeyBasedPartitioningFunction key0)\n                                  {| XMap.this := m; XMap.is_bst := SubTrieMapBST H1 |}\n                                  _\n                                  key0 x\n                                  (refl_equal _)) in H4; intuition.\n          apply find_1 in H5; eauto; simpl in *; congruence.\n    Qed.\n\n    Corollary TrieBag_BagInsertEnumerate :\n      BagInsertEnumerate TrieBagRepInv TrieBag_benumerate TrieBag_binsert.\n    Proof.\n      unfold BagInsertEnumerate; intros; eapply Trie_add_Correct; eauto.\n      simpl; reflexivity.\n    Qed.\n\n    Lemma TrieBag_enumerateOK\n    : forall l st1 (bags : list (key * BagType)) k bag,\n        (forall (k : X.t) (subtrie : Trie),\n           InA (PX.eqke (elt:=Trie)) (k, subtrie) l ->\n           TrieOK subtrie (st1 ++ [k])) ->\n        (forall (k : key) (bag : BagType),\n           List.In (k, bag) bags ->\n           forall (item: TItem),\n              List.In item (benumerate bag) ->\n              Prefix (st1 ++ [k]) (projection item))\n        -> List.In (k, bag) (fold_left\n                          (fun (a : list (key * BagType)) (p : key * Trie) =>\n                             (List.map (fun bag => (fst p, bag)) (Trie_enumerate (snd p)) ++ a)) l bags)\n        -> forall (item: TItem),\n              List.In item (benumerate bag) ->\n              Prefix (st1 ++ [k]) (projection item).\n    Proof.\n      induction l; simpl; eauto.\n      - intros.\n        rewrite <- In_fold_left_map_split' in H1.\n        rewrite <- app_assoc in H1.\n        apply in_app_or in H1; intuition eauto.\n        destruct a as [k' t]; simpl in *.\n        assert (InA (PX.eqke (elt:=Trie)) (k', t) ((k', t) :: l))\n               by (econstructor; eauto || typeclasses eauto).\n        generalize (H k' t H1).\n        assert (k = k')\n          by (revert H3; clear; induction (Trie_enumerate t);\n              simpl; intro; intuition; injections; eauto).\n        subst.\n        apply in_map with (f := snd) in H3; rewrite map_map, map_id in H3.\n        remember (st1 ++ [k']).\n        setoid_rewrite <- Heql0.\n        generalize bag H2 H3; clear.\n        eapply (fun P H => @Trie_enumerate_ind P H t l0).\n        simpl; intros.\n        destruct trie; simpl in *.\n        rewrite !XMapfold_eq, !fold_1 in H3; eauto.\n        rewrite <- In_fold_left_split' in H3.\n        apply in_app_or in H3; intuition.\n        + simpl in H1; intuition; injections; subst.\n          inversion H0; subst.\n          apply H6 in H2; revert H2; clear.\n          * revert st; induction (projection item); simpl.\n            intros; inversion H2; subst.\n            eexists nil; rewrite app_nil_r.\n            constructor; symmetry; eauto.\n            eexists nil; simpl; rewrite app_nil_r; symmetry; eauto.\n        +  assert\n             (forall (k : key) (trie' : Trie),\n                InA (XMap.eq_key_elt (elt:=Trie)) (k,trie') (elements m) ->     List.In item (benumerate bag) ->\n                List.In (t, bag)\n                        (List.map (fun bag0 : BagType => (t, bag0)) (Trie_enumerate trie')) ->\n                TrieOK trie' (st ++ [k]) -> Prefix (st ++ [k]) (projection item)).\n           { intros; eapply H; eauto.\n             eapply (@XMap.elements_2 _ (XMap.Bst (SubTrieMapBST H0))); eauto.\n             apply in_map with (f := snd) in H5;\n               rewrite map_map, map_id in H5; simpl in *;\n               eauto.\n           }\n           assert (forall k' trie,\n                     InA (XMap.eq_key_elt (elt:=Trie)) (k', trie) (elements m)\n                     -> TrieOK trie (st ++ [k'])).\n           {  revert H0; clear.\n              intros; inversion H0; subst.\n              apply (@XMap.elements_2 _ (XMap.Bst H4)) in H.\n              apply H7 in H; simpl in H; eauto.\n           }\n           generalize st bag item b t H2 H3 H1 H4; clear.\n           induction (elements m); simpl; intros.\n           * intuition.\n           * rewrite <- In_fold_left_split' in H1.\n             apply in_app_or in H1; intuition eauto.\n             assert (forall a b c, Prefix (a ++ [b]) c ->\n                                   Prefix a c).\n             {\n               clear; intros; destruct H.\n               exists (b :: x); rewrite <- app_assoc in H; eauto.\n             }\n             destruct a; eapply H0; eapply H3.\n             econstructor; reflexivity.\n             eauto.\n             rewrite app_nil_r in H.\n             eauto.\n             simpl in H.\n             apply in_map_iff; eauto.\n             eapply H4; econstructor; eauto.\n             reflexivity.\n             eapply IHl; eauto.\n        + eapply IHl; eauto.\n          apply In_fold_left_map_split'; eauto.\n    Qed.\n\n    Lemma TrieBag_enumerateOK1\n    : forall l st1 search_term bags,\n        (forall (k : X.t) (subtrie : Trie),\n           InA (PX.eqke (elt:=Trie)) (k, subtrie) l ->\n           TrieOK subtrie (st1 ++ [k])) ->\n        (forall (k : X.t) (bag : BagType) item,\n           List.In (k, bag) bags\n           -> List.In item (benumerate (Bag := TBag) bag)\n           -> Prefix (st1 ++ [k]) (projection item))\n        -> Permutation\n             (List.filter (TrieBag_bfind_matcher (Some st1, search_term))\n                          (flatten\n                             (List.map (fun p => benumerate (snd p))\n                                       (fold_left\n                                          (fun (a : list (key * BagType)) (p : key * Trie) =>\n                                             (List.map (fun bag => (fst p, bag)) (Trie_enumerate (snd p)) ++ a)) l bags))))\n             [].\n    Proof.\n      induction l; simpl; eauto.\n      - induction bags; simpl in *; intros; eauto.\n        rewrite filter_app, IHbags; eauto.\n        destruct a.\n        rewrite app_nil_r.\n        simpl.\n        generalize (fun item => H0 _ _ item (or_introl (refl_equal _))) ; clear; simpl.\n        induction (benumerate b); simpl; eauto.\n        intros.\n        unfold TrieBag_bfind_matcher, IsPrefix; simpl.\n        destruct (Prefix_dec F.eq_dec (projection a) st1); simpl in *.\n        find_if_inside; eauto.\n        intros.\n        pose proof (H _ (or_introl (refl_equal _))).\n        exfalso.\n        generalize st1 p H0; clear.\n        induction (projection a); simpl.\n        + destruct st1; simpl; intros;  destruct H0; inversion H.\n        + destruct st1; simpl; try congruence.\n          intros; inversion p; inversion H.\n          intros; eapply (IHl st1).\n          destruct p; simpl in *; inversion H; subst; eexists; eauto.\n          intros; destruct H0; inversion H; subst.\n          eexists; eauto.\n        + eauto.\n      - intros; rewrite IHl; eauto.\n        intros.\n        apply in_app_or in H1; intuition eauto.\n        destruct a.\n        assert (InA (PX.eqke (elt:=Trie)) (t, t0) ((t, t0) :: l)) by\n            (econstructor; eauto || typeclasses eauto).\n        apply H in H1; simpl in *.\n        assert (k = t).\n        {\n          revert H3; clear; induction (Trie_enumerate t0); simpl;\n          intros; intuition;  congruence.\n        }\n        subst.\n        revert H2 H3 H1.\n        clear.\n        eapply (fun P H => @Trie_enumerate_ind P H t0 (st1 ++ [t])).\n        simpl; intros.\n        destruct trie; simpl in *.\n        rewrite !XMapfold_eq, !fold_1 in H3; eauto.\n        rewrite <- In_fold_left_split, map_app in H3.\n        apply in_app_or in H3; intuition.\n        + simpl in H0; intuition; injections; subst.\n          inversion H1; subst.\n          apply H6 in H2; revert H2; clear.\n          * revert st; induction (projection item); simpl.\n            intros; inversion H2; subst.\n            eexists nil; rewrite app_nil_r.\n            constructor; symmetry; eauto.\n            eexists nil; simpl; rewrite app_nil_r; symmetry; eauto.\n        +  assert\n             (forall (k : key) (trie' : Trie),\n                InA (XMap.eq_key_elt (elt:=Trie)) (k,trie') (elements m) ->     List.In item (benumerate bag) ->\n                List.In (t, bag)\n                        (List.map (fun bag0 : BagType => (t, bag0)) (Trie_enumerate trie')) ->\n                TrieOK trie' (st ++ [k]) -> Prefix (st ++ [k]) (projection item)).\n           { intros; eapply H; eauto.\n             eapply (@XMap.elements_2 _ (XMap.Bst (SubTrieMapBST H1))); eauto. }\n           assert (forall k' trie,\n                     InA (XMap.eq_key_elt (elt:=Trie)) (k', trie) (elements m)\n                     -> TrieOK trie (st ++ [k'])).\n           {  revert H1; clear.\n              intros; inversion H1; subst.\n              apply (@XMap.elements_2 _ (XMap.Bst H4)) in H.\n              apply H7 in H; simpl in H; eauto.\n           }\n           generalize st bag item b t H2 H3 H0 H4; clear.\n           induction (elements m); simpl; intros.\n           * intuition.\n           * rewrite <- In_fold_left_split, map_app in H0.\n             apply in_app_or in H0; intuition eauto.\n             assert (forall a b c, Prefix (a ++ [b]) c ->\n                                   Prefix a c).\n             {\n               clear; intros; destruct H.\n               exists (b :: x); rewrite <- app_assoc in H; eauto.\n             }\n             destruct a; eapply H0; eapply H3.\n             econstructor; reflexivity.\n             eauto.\n             rewrite app_nil_r in H.\n             eauto.\n             eapply H4; econstructor; eauto.\n             reflexivity.\n             eapply IHl; eauto.\n    Qed.\n\n    Corollary TrieBag_enumerateOK'\n    : forall l st1 search_term,\n        (forall (k : X.t) (subtrie : Trie),\n           InA (PX.eqke (elt:=Trie)) (k, subtrie) l ->\n           TrieOK subtrie (st1 ++ [k]))\n        -> Permutation\n             (List.filter (TrieBag_bfind_matcher (Some st1, search_term))\n                          (flatten\n                             (List.map benumerate\n                                       (fold_left\n                                          (fun (a : list (BagType)) (p : key * Trie) =>\n                                             (Trie_enumerate (snd p)) ++ a) l [ ]))))\n             [].\n    Proof.\n      intros.\n      rewrite <- (@TrieBag_enumerateOK1 l st1 search_term [ ] H) by\n          intuition.\n      remember (@nil BagType); remember (@nil (X.t * BagType)).\n      assert (List.map snd l1 = l0) by (subst; eauto).\n      generalize l1 l0 H0; clear; induction l; simpl; intros.\n      rewrite <- map_map with (f := snd). setoid_rewrite H0.\n      reflexivity.\n      rewrite <- IHl; eauto.\n      rewrite map_app, map_map, map_id; simpl.\n      setoid_rewrite H0; reflexivity.\n    Qed.\n\n    Global Instance Prefix_refl :\n      Reflexive Prefix.\n    Proof.\n      intros; eexists nil; rewrite app_nil_r; reflexivity.\n    Qed.\n\n    Global Instance Prefix_trans :\n      Transitive Prefix.\n    Proof.\n      unfold Transitive;\n      intros; destruct H as [k H]; destruct H0 as [k' H0].\n      eexists (k ++ k'); rewrite <- H0, <- H, <- app_assoc; reflexivity.\n    Qed.\n\n    (*Add Parametric Relation\n    : (list _) (Prefix)\n        reflexivity proved by reflexivity\n        transitivity proved by transitivity\n          as refine_rel.*)\n\n    Lemma Prefix_app :\n      forall l l',\n        Prefix l (l ++ l').\n    Proof.\n      intros; eexists l'; reflexivity.\n    Qed.\n\n    Lemma filter_Prefix\n    : forall (b : BagType) m st l search_term',\n        TrieOK (Node b m) l\n        -> Prefix l st\n        -> Permutation (List.filter (bfind_matcher search_term') (benumerate b))\n                       (List.filter (TrieBag_bfind_matcher (Some st, search_term'))\n                                    (benumerate b)).\n    Proof.\n      intros; inversion H; subst.\n      revert H0 H5; clear.\n      induction (benumerate b); simpl; eauto.\n      unfold TrieBag_bfind_matcher; simpl.\n      intros; case_eq (Prefix_dec F.eq_dec (projection a) st); simpl; intros.\n      find_if_inside; simpl; rewrite IHl0; eauto.\n      assert (Prefix (projection a) l)\n        by (eexists nil; rewrite app_nil_r; eauto).\n      destruct n.\n      rewrite H1; apply H0.\n    Qed.\n\n    Lemma filter_negb_Prefix\n    : forall (b : BagType) m st l search_term',\n        TrieOK (Node b m) l\n        -> Prefix l st\n        -> Permutation (List.filter (fun a => negb (bfind_matcher search_term' a)) (benumerate b))\n                       (List.filter (fun a => negb (TrieBag_bfind_matcher (Some st, search_term') a))\n                                    (benumerate b)).\n    Proof.\n      intros; inversion H; subst.\n      revert H0 H5; clear.\n      induction (benumerate b); simpl; eauto.\n      unfold TrieBag_bfind_matcher; simpl.\n      intros; case_eq (Prefix_dec F.eq_dec (projection a) st); simpl; intros.\n      find_if_inside; simpl; rewrite IHl0; eauto.\n      assert (Prefix (projection a) l)\n        by (eexists nil; rewrite app_nil_r; eauto).\n      destruct n.\n      rewrite H1; apply H0.\n    Qed.\n\n    Lemma Prefix_cons_inv\n    : forall a l l',\n        Prefix (a :: l) (a :: l') -> Prefix l l'.\n    Proof.\n      induction l; simpl; intros.\n      - eexists l'; simpl; reflexivity.\n      - destruct H; inversion H; subst.\n        exists x; eauto.\n    Qed.\n\n    Lemma Prefix_app_inv\n    : forall a l l',\n        Prefix (a ++ l) (a ++ l') -> Prefix l l'.\n    Proof.\n      induction a; simpl; intros; eauto.\n      apply IHa; eapply Prefix_cons_inv; eauto.\n    Qed.\n\n    Lemma filter_remove_key :\n      forall key' m l st' search_term,\n        (forall (k : X.t) (subtrie : Trie),\n           InA (PX.eqke (elt:=Trie)) (k, subtrie)\n               (elements (remove key' (XMap.this m))) ->\n           TrieOK subtrie (l ++ [k]))\n        -> Permutation\n          (flatten\n             (List.map\n                (fun x : BagType =>\n                   List.filter\n                     (TrieBag_bfind_matcher (Some (l ++ key' :: st'), search_term))\n                     (benumerate x))\n                (XMap.fold\n                   (fun (_ : key) (trie : Trie) (a : list BagType) =>\n                      Trie_enumerate trie ++ a)\n                   (XMap.remove (elt:=Trie) key' m\n                   )\n                   []))) [].\n    Proof.\n      intros; unfold XMap.fold; rewrite fold_1; simpl; eauto.\n      remember (@nil BagType) as bags.\n      remember (@nil (key * BagType)) as bags'.\n      assert (forall (k0 : key) (bag0 : BagType),\n     List.In (k0, bag0) bags' ->\n     forall item : TItem,\n       List.In item (benumerate bag0) -> Prefix (l ++ [k0]) (projection item)) by (rewrite Heqbags'; intuition).\n      generalize\n           (fun k bag =>\n              @TrieBag_enumerateOK\n                (elements (remove key' (XMap.this m))) l bags' k bag\n                H H0).\n      clear H0.\n      assert (bags = List.map (@snd _ _) bags')  as H0\n        by (rewrite Heqbags', Heqbags; reflexivity);\n        rewrite H0; clear H0.\n      assert (forall (k : X.t) (subtrie : Trie),\n                InA (PX.eqke (elt:=Trie)) (k, subtrie)\n                    (elements (remove key' (XMap.this m))) ->\n                ~X.eq k key')\n        by (intros;\n            rewrite <- (@elements_mapsto_iff _ (XMap.Bst (remove_bst key' (XMap.is_bst m)))) in H0;\n            apply remove_mapsto_iff in H0; intuition).\n      assert (forall (k : X.t) b,\n                InA (PX.eqke (elt:=BagType)) (k, b) bags' ->\n                ~X.eq k key')\n        by (intros;\n            rewrite Heqbags' in *; inversion H1).\n      generalize bags' H H0 H1; clear; induction (elements (remove key' (XMap.this m))); simpl.\n      - induction bags'; simpl; intros; eauto.\n        rewrite IHbags'; eauto.\n        destruct a; simpl in *.\n        assert (~ X.eq k key') by\n            (intros; eapply H1; econstructor; eauto || typeclasses eauto).\n        generalize (fun item => H2 k b (or_introl (refl_equal _)) item) H3;\n          clear.\n        induction (benumerate b); simpl; eauto; intros.\n        pose proof (H _ (or_introl (refl_equal _))).\n        rewrite <- IsPrefix_iff_Prefix in H0.\n        unfold TrieBag_bfind_matcher, IsPrefix in *; simpl in *.\n        case_eq (Prefix_dec F.eq_dec (projection a) (l ++ key' :: st')); eauto.\n        intros.\n        assert (Prefix (l ++ [k]) (l ++ key' :: st')).\n        etransitivity; eauto.\n        pose proof (Prefix_app_inv _ _ _ H2).\n        destruct H4; inversion H4; subst.\n        exfalso; eapply H3; eauto.\n      - intros.\n        rewrite <- (IHl0 ((List.map (fun a' => (fst a, a')) (Trie_enumerate (snd a))) ++ bags')); eauto.\n        rewrite map_app, map_map, map_id; reflexivity.\n        intros.\n        apply InA_app in H3; intuition eauto.\n        assert (~X.eq k (fst a))\n          by (destruct a; intro; eapply H0; [\n                 constructor; typeclasses eauto\n               | simpl in *;\n                 repeat match goal with\n                        | [ H : X.eq ?k _ |- _ ] => rewrite H in *; clear H\n                        end; reflexivity ]).\n        apply H3; revert H5; clear; induction (Trie_enumerate (snd a));\n        intros; inversion H5; subst; eauto.\n        destruct H0; simpl in *; eauto.\n      - eapply (remove_bst _ (XMap.is_bst m)).\n    Qed.\n\n    Lemma elements_add_eq elt\n    : forall k (v : elt) m,\n        XMap.Equal (XMap.add k v m)\n                   (XMap.add k v (XMap.remove k m)).\n    Proof.\n      unfold XMap.Equal; intros.\n      symmetry; case_eq (XMap.find (elt:=elt) y (XMap.add k v m)); intros.\n      apply find_2 in H.\n      rewrite (@add_mapsto_iff _ m k y v e) in H; intuition; subst.\n      apply find_1; eauto.\n      exact (XMap.is_bst _).\n      apply add_1; eauto.\n      apply find_1; eauto.\n      exact (XMap.is_bst _).\n      apply add_2; eauto.\n      apply remove_2; eauto.\n      exact (XMap.is_bst _).\n      rewrite <- not_find_in_iff in *.\n      intro; apply H.\n      destruct H0.\n      rewrite (@add_mapsto_iff _ (XMap.remove k m) k y v x) in H0; intuition; subst.\n      eexists; eapply add_1; eauto.\n      rewrite (@remove_mapsto_iff _ m k y x) in H2; intuition.\n      eexists; eauto.\n      apply add_2; eauto.\n    Qed.\n\n    Lemma Permutation_benumerate_add\n    : forall k v m,\n        Permutation\n          (flatten\n             (List.map benumerate\n                       (fold_left\n                          (fun (a : list BagType) (p : XMap.key * Trie) =>\n                             Trie_enumerate (snd p) ++ a) (XMap.elements (XMap.add k v m))\n                          [])))\n          (flatten\n             (List.map benumerate\n                       (Trie_enumerate v ++\n                                       (fold_left\n                                          (fun (a : list BagType) (p : key * Trie) =>\n                                             Trie_enumerate (snd p) ++ a) (XMap.elements (XMap.remove k m))\n                                          [])))).\n    Proof.\n      intros; pose (@XMap.fold_1 _ (XMap.add k v m) _ nil\n                                 (fun _ (p : Trie) (a : list BagType) =>\n                                    Trie_enumerate p ++ a)).\n      simpl in e.\n      rewrite <- !e.\n      rewrite (fold_Equal_simpl (eqA := @Permutation BagType) (elements_add_eq k v m))\n        by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n      rewrite !fold_add;\n        eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey, empty_In.\n      rewrite XMap.fold_1; simpl.\n      f_equiv.\n      eapply XMap.remove_1; reflexivity.\n    Qed.\n\n    Corollary TrieBag_enumerateOK'''\n    : forall l st1 key' st' search_term,\n        (forall (k : X.t) (subtrie : Trie),\n           InA (PX.eqke (elt:=Trie)) (k, subtrie) l ->\n           TrieOK subtrie (st1 ++ [k]))\n        -> ( forall (k : X.t) (subtrie : Trie),\n               InA (PX.eqke (elt:=Trie)) (k, subtrie)\n                   l -> ~X.eq k key')\n        -> Permutation\n             (List.filter (fun a => negb (TrieBag_bfind_matcher (Some (st1 ++ key' :: st'), search_term) a))\n                          (flatten\n                             (List.map benumerate\n                                       (fold_left\n                                          (fun (a : list (BagType)) (p : key * Trie) =>\n                                             (Trie_enumerate (snd p)) ++ a) l [ ]))))\n             (flatten\n                (List.map benumerate\n                          (fold_left\n                             (fun (a : list (BagType)) (p : key * Trie) =>\n                                (Trie_enumerate (snd p)) ++ a) l [ ]))).\n    Proof.\n      intros.\n      remember (@nil BagType) as bags.\n      remember (@nil (key * BagType)) as bags'.\n      assert (forall (k0 : key) (bag0 : BagType),\n                List.In (k0, bag0) bags' ->\n                forall item : TItem,\n                  List.In item (benumerate bag0) -> Prefix (st1 ++ [k0]) (projection item)) by (rewrite Heqbags'; intuition).\n      generalize\n        (fun k bag =>\n           @TrieBag_enumerateOK\n             l st1 bags' k bag\n             H H1).\n      clear H1.\n      assert (bags = List.map (@snd _ _) bags') as H1\n          by (rewrite Heqbags', Heqbags; reflexivity);\n        rewrite H1; clear H1.\n      assert (forall (k : X.t) b,\n                InA (PX.eqke (elt:=BagType)) (k, b) bags' ->\n                ~X.eq k key')\n        by (intros;\n            rewrite Heqbags' in *; inversion H1).\n      generalize bags' H H0 H1; clear; induction l; simpl; intros.\n      - induction bags'; simpl; intros; eauto.\n        rewrite filter_app, IHbags'; eauto; f_equiv.\n        destruct a; simpl in *.\n        assert (~ X.eq k key') by\n          (intros; eapply H1; econstructor; eauto || typeclasses eauto).\n        generalize (fun item => H2 k b (or_introl (refl_equal _)) item) H3;\n          clear.\n        induction (benumerate b); simpl; eauto; intros.\n        pose proof (H _ (or_introl (refl_equal _))).\n        rewrite <- IsPrefix_iff_Prefix in H0.\n        unfold TrieBag_bfind_matcher, IsPrefix in *; simpl in *.\n        case_eq (Prefix_dec F.eq_dec (projection a) (st1 ++ key' :: st')); eauto.\n        intros.\n        assert (Prefix (st1 ++ [k]) (st1 ++ key' :: st'))\n          by (etransitivity; eauto).\n        pose proof (Prefix_app_inv _ _ _ H2).\n        destruct H4; inversion H4; subst.\n        exfalso; eapply H3; eauto.\n        simpl; intros; f_equiv.\n        generalize (fun item In_item => H item (or_intror In_item)).\n        generalize H3; clear; induction l; simpl; intros; eauto.\n        pose proof (H _ (or_introl (refl_equal _))).\n        destruct (Prefix_dec F.eq_dec (projection a) (st1 ++ key' :: st')); simpl in *; eauto.\n        intros.\n        assert (Prefix (st1 ++ [k]) (st1 ++ key' :: st'))\n          by (etransitivity; eauto).\n        apply Prefix_app_inv in H1.\n        destruct H1; simpl in H1; inversion H1; subst.\n        intuition.\n        try rewrite IHl; eauto.\n        intros; try eapply H2; eauto.\n        constructor 2; eauto.\n      - intros.\n        pose proof (IHl ((List.map (fun a' => (fst a, a')) (Trie_enumerate (snd a))) ++ bags')) as H'.\n        rewrite map_app, map_map, map_id in H'.\n        rewrite <- H' at 2; clear H'; intros.\n        rewrite !flatten_filter; eauto.\n        destruct a; eapply H; econstructor 2; eauto.\n        eapply H0; eauto.\n        apply InA_app in H3; intuition eauto.\n        assert (~X.eq k (fst a))\n          by (destruct a; intro; eapply H0; [\n                 constructor; typeclasses eauto\n               | simpl in *;\n                 repeat match goal with\n                        | [ H : X.eq ?k _ |- _ ] => rewrite H in *; clear H\n                        end; reflexivity ]).\n        apply H3; revert H5; clear; induction (Trie_enumerate (snd a));\n        intros; inversion H5; subst; eauto.\n        destruct H0; simpl in *; eauto.\n        eapply H2; eauto.\n    Qed.\n\n    Lemma filter_negb_remove\n    : forall key m,\n        XMap.Equal (filter\n                      (fun (k : XMap.key) (e : Trie) =>\n                         negb (KeyBasedPartitioningFunction Trie key k e))\n                      m)\n                   (XMap.remove key m).\n    Proof.\n      unfold XMap.Equal; intros.\n      destruct (X.eq_dec key0 y).\n      - rewrite remove_eq_o; eauto.\n        rewrite <- e; unfold filter; clear y e.\n        destruct m; unfold XMap.fold; rewrite fold_1; simpl; eauto.\n        assert (XMap.find (elt:=Trie) key0 (XMap.empty Trie) = None).\n        { rewrite <- not_find_in_iff.\n          intro H; destruct H; simpl in *; eapply empty_1; eauto.\n        }\n        revert H.\n        remember (XMap.empty Trie); generalize t; clear Heqt.\n        induction (elements this); intros; simpl.\n        + eauto.\n        + eapply IHl.\n          case_eq (negb (KeyBasedPartitioningFunction Trie key0 (fst a) (snd a)));\n            intros; eauto.\n          rewrite add_neq_o; eauto.\n          intro; unfold KeyBasedPartitioningFunction in *.\n          case_eq (F.eq_dec (fst a) key0); intros; rewrite H2 in H0;\n          simpl in *; try congruence.\n      - rewrite remove_neq_o by eauto.\n        destruct m; unfold filter, XMap.fold; rewrite fold_1; simpl; eauto.\n        case_eq (XMap.find (elt:=Trie) y {| XMap.this := this; XMap.is_bst := is_bst |}).\n        + intros; apply find_2 in H.\n          pose (@elements_mapsto_iff _ (XMap.Bst is_bst)) as H2; simpl in H2;\n          unfold XMap.MapsTo in H2; simpl in H2; rewrite H2 in H;\n          unfold XMap.elements in H; simpl in H; clear H2.\n          assert (InA (XMap.eq_key_elt (elt:=Trie)) (y, t) (elements this) \\/\n                  InA (XMap.eq_key_elt (elt:=Trie)) (y, t) (XMap.elements (XMap.empty Trie)))\n            by eauto.\n          assert (forall key' v, XMap.MapsTo key' v (XMap.empty Trie) ->\n                                 ~ X.eq key' key0)\n            by (unfold not; intros; eapply XMap.empty_1; eauto).\n          assert (forall key' v, XMap.MapsTo key' v (XMap.empty Trie) ->\n                                 ~ InA X.eq key' (List.map fst (elements this)))\n            by (unfold not; intros; eapply XMap.empty_1; eauto).\n          assert (forall key' v, InA X.eq key' (List.map fst (elements this))\n                                 -> ~ XMap.MapsTo key' v (XMap.empty Trie))\n            by (unfold not; intros; eapply XMap.empty_1; eauto).\n          assert (NoDupA X.eq (List.map fst (XMap.elements (elt:=_) (XMap.Bst is_bst)))).\n          { pose proof (@XMap.elements_3w _ (XMap.Bst is_bst)).\n            unfold XMap.eq_key, PX.eqk in H4.\n            revert H4; clear; induction (XMap.elements (XMap.Bst is_bst)); intros;\n            constructor; eauto;\n            inversion H4; subst;\n            [ | apply IHl; eauto].\n            intro; apply H1; revert H; clear; induction l; intros; inversion H; subst.\n            constructor; eauto.\n            constructor 2; eauto.\n          }\n          unfold XMap.elements in H4; simpl in H4.\n          revert H1 H0 H2 H3 H4.\n          remember (XMap.empty Trie) as t'; generalize t'; clear Heqt' H.\n          induction (elements this); intros; simpl.\n          destruct t'0; apply find_1; eauto.\n          apply elements_mapsto_iff; simpl in H0; intuition.\n          inversion H.\n          eapply IHl; simpl in *; intuition.\n          * unfold KeyBasedPartitioningFunction in *.\n            destruct (X.eq_dec (fst a) key0); simpl in *; eauto; try congruence.\n            destruct a; simpl in *.\n            eapply XMap.add_3 in H0; eauto;\n              match goal with\n              | [ H : X.eq _ _ |- _ ] => rewrite H; auto\n              end.\n          * unfold KeyBasedPartitioningFunction in *.\n            destruct (X.eq_dec (fst a) key0); simpl in *; eauto; try congruence.\n            eapply XMap.add_3 in H0; eauto;\n              match goal with\n              | [ H : X.eq _ _ |- _ ] => rewrite H; auto\n              end.\n          * inversion H; subst.\n            destruct H5; destruct a; simpl in *; subst.\n            right; rewrite <- elements_mapsto_iff; simpl.\n            unfold KeyBasedPartitioningFunction in *.\n            destruct (X.eq_dec k key0); simpl in *; eauto; try congruence.\n            rewrite e in H0; symmetry in H0; intuition.\n            apply add_1; eauto; try symmetry; eauto.\n            eauto;\n              match goal with\n              | [ H : X.eq _ _ |- _ ] => rewrite H; auto\n              end.\n          * right; rewrite <- elements_mapsto_iff; simpl.\n            unfold KeyBasedPartitioningFunction in *.\n            destruct (X.eq_dec (fst a) key0); simpl in *; eauto; try congruence.\n            rewrite <- elements_mapsto_iff in *; simpl; eauto.\n            rewrite <- elements_mapsto_iff in *; simpl; eauto.\n            apply add_2; eauto;\n              intuition; eapply H2; [ eassumption | left; symmetry; auto ].\n          * unfold KeyBasedPartitioningFunction in *.\n            destruct (F.eq_dec (fst a) key0); simpl in *; eauto.\n            pose proof (proj1 (add_mapsto_iff _ _ _ _ _) H0); intuition; subst.\n            inversion H4; subst; eauto.\n            rewrite H6 in H9; eauto.\n            eapply H3; eauto.\n          * unfold KeyBasedPartitioningFunction in *.\n            destruct (F.eq_dec (fst a) key0); simpl in *; eauto.\n            pose proof (proj1 (add_mapsto_iff _ _ _ _ _) H0); intuition; subst.\n            inversion H4; subst; eauto.\n            rewrite H6 in H9; eauto.\n            eapply H3; eauto.\n          *  unfold KeyBasedPartitioningFunction in *.\n             destruct (F.eq_dec (fst a) key0); simpl in *; eauto.\n             pose proof (proj1 (add_mapsto_iff _ _ _ _ _) H5); intuition; subst.\n             inversion H4; subst; eauto.\n             rewrite H6 in H9; eauto.\n             eapply H3; eauto.\n          * unfold KeyBasedPartitioningFunction in *.\n            destruct (F.eq_dec (fst a) key0); simpl in *; eauto.\n            pose proof (proj1 (add_mapsto_iff _ _ _ _ _) H5); intuition; subst.\n            inversion H4; subst; eauto.\n            rewrite H6 in H9; eauto.\n            eapply H3; eauto.\n          * inversion H4; eauto.\n          * inversion H4; eauto.\n        + intros; apply not_find_in_iff in H.\n          assert (forall v, ~ InA (XMap.eq_key_elt (elt:=Trie)) (y, v) (XMap.elements (XMap.Bst is_bst)) /\\\n                            ~ InA (XMap.eq_key_elt (elt:=Trie)) (y, v) (XMap.elements (XMap.empty Trie))).\n          { unfold not in*; split; intros.\n            rewrite <- elements_mapsto_iff in H0.\n            apply H; eexists v; simpl in *; apply H0.\n            rewrite <- elements_mapsto_iff in H0.\n            eapply XMap.empty_1; eauto.\n          }\n          assert (forall key' v, XMap.MapsTo key' v (XMap.empty Trie) ->\n                                 ~ X.eq key' key0)\n            by (unfold not; intros; eapply XMap.empty_1; eauto).\n          assert (forall key' v, XMap.MapsTo key' v (XMap.empty Trie) ->\n                                 ~ InA X.eq key' (List.map fst (elements this)))\n            by (unfold not; intros; eapply XMap.empty_1; eauto).\n          assert (forall key' v, InA X.eq key' (List.map fst (elements this))\n                                 -> ~ XMap.MapsTo key' v (XMap.empty Trie))\n            by (unfold not; intros; eapply XMap.empty_1; eauto).\n          assert (NoDupA X.eq (List.map fst (XMap.elements (elt:=_) (XMap.Bst is_bst)))).\n          { pose proof (@XMap.elements_3w _ (XMap.Bst is_bst)).\n            unfold XMap.eq_key, PX.eqk in H4.\n            revert H4; clear; induction (XMap.elements (XMap.Bst is_bst)); intros;\n            constructor; eauto;\n            inversion H4; subst;\n            [ | apply IHl; eauto].\n            intro; apply H1; revert H; clear; induction l; intros; inversion H; subst.\n            constructor; eauto.\n            constructor 2; eauto.\n          }\n          unfold XMap.elements in H4; simpl in H4, H0.\n          unfold XMap.elements at 1 in H0; simpl in H0.\n          rewrite <- not_find_in_iff.\n          revert H1 H0 H2 H3 H4.\n          remember (XMap.empty Trie) as t'; generalize t'; clear Heqt' H.\n          induction (elements this); intros; simpl.\n          unfold not; intros; destruct H as [x H].\n          apply (proj2 (H0 x)).\n          rewrite <- elements_mapsto_iff; eassumption.\n          eapply IHl; simpl in *; intuition.\n          * unfold KeyBasedPartitioningFunction in *.\n            destruct (X.eq_dec (fst a) key0); simpl in *; eauto; try congruence.\n            destruct a; simpl in *.\n            eapply XMap.add_3 in H; eauto; try match goal with\n                                               | [ H : X.eq _ _ |- _ ] => rewrite H; solve [ eauto ]\n                                               end.\n          * apply (proj1 (H0 v)); eauto.\n          * unfold KeyBasedPartitioningFunction in *.\n            destruct (X.eq_dec (fst a) key0); simpl in *; eauto; try congruence.\n            apply (proj2 (H0 v)); eauto.\n            rewrite <- elements_mapsto_iff in H.\n            pose proof (proj1 (add_mapsto_iff _ _ _ _ _) H); intuition; subst.\n            apply (proj1 (H0 (snd a))); econstructor.\n            constructor; eauto; simpl; symmetry; assumption.\n            apply (proj2 (H0 v)); rewrite <- elements_mapsto_iff; eauto.\n          * unfold KeyBasedPartitioningFunction in *.\n            destruct (X.eq_dec (fst a) key0); simpl in *; eauto; try congruence.\n            pose proof (proj1 (add_mapsto_iff _ _ _ _ _) H); intuition; subst.\n            inversion H4; subst; eauto.\n            rewrite H6 in H9; eauto.\n            eapply H2; eauto.\n          * unfold KeyBasedPartitioningFunction in *.\n            destruct (F.eq_dec (fst a) key0); simpl in *; eauto.\n            pose proof (proj1 (add_mapsto_iff _ _ _ _ _) H5); intuition; subst.\n            inversion H4; subst; eauto.\n            rewrite H6 in H9; eauto.\n            eapply H3; eauto.\n          * inversion H4; eauto.\n    Qed.\n\n    Hint Resolve filter_negb_Prefix filter_Prefix Prefix_app.\n\n    Lemma TrieOK_subtrie_remove\n    : forall b m l key' k subtrie,\n        TrieOK (Node b m) l\n        -> bst m\n        -> InA (PX.eqke (elt:=Trie)) (k, subtrie)\n            (elements\n               (remove key' m)) ->\n        TrieOK subtrie (l ++ [k]).\n    Proof.\n      intros.\n      inversion H; subst; intros; eapply H8.\n      assert (bst (remove key'\n                          (XMap.this\n                             {| XMap.this := m; XMap.is_bst := H0 |}))).\n      apply remove_bst; eauto.\n      rewrite <- (@elements_mapsto_iff _ (XMap.Bst H2)) in H1.\n      simpl in H1; unfold XMap.MapsTo in H1; simpl in H1.\n      eapply remove_3; eauto.\n    Qed.\n\n    Lemma TrieOK_subtrie_filter\n    : forall b m l bst_m f k subtrie,\n        Proper (X.eq ==> eq ==> eq) f\n        -> TrieOK (Node b m) l\n        -> InA (PX.eqke (elt:=Trie)) (k, subtrie)\n            (XMap.elements\n               (filter f\n                       {| XMap.this := m; XMap.is_bst := bst_m |})) ->\n        TrieOK subtrie (l ++ [k]).\n    Proof.\n      intros.\n      inversion H0; subst; intros; eapply H8.\n      rewrite <- elements_mapsto_iff in H1.\n      rewrite filter_iff in H1; intuition.\n    Qed.\n\n    Hint Resolve TrieOK_subtrie_remove TrieOK_subtrie_filter.\n\n    Lemma TrieBag_BagFindCorrect :\n      BagFindCorrect TrieBagRepInv TrieBag_bfind TrieBag_bfind_matcher TrieBag_benumerate.\n    Proof.\n      intros container search_term.\n      destruct search_term as [ [st |] search_term].\n      { unfold TrieBag_bfind.\n        rewrite <- (app_nil_l st) at 1.\n        unfold TrieBagRepInv; remember [] as l; clear Heql; revert l.\n        eapply Trie_find_ind; intros; subst; simpl.\n        - rewrite !app_nil_r, <- bfind_correct by eauto.\n          destruct trie; simpl.\n          unfold TrieBag_benumerate; simpl.\n          rewrite !XMapfold_eq, !fold_1 by eauto.\n          rewrite Permutation_benumerate_fold_left, flatten_app; simpl;\n          rewrite filter_app, app_nil_r; simpl.\n          rewrite <- app_nil_r; f_equiv.\n          + rewrite filter_Prefix; eauto; reflexivity.\n          + match goal with\n            | [ H : TrieOK _ _ |- _ ] =>\n                inversion H; subst;\n                eapply TrieBag_enumerateOK'; intros;\n                match goal with\n                | [ H5 : _ |- _ ] => eapply H5;\n                                     eapply (@XMap.elements_2 _ (XMap.Bst (SubTrieMapBST' H))); eauto\n                end\n            end.\n        - rewrite <- H; eauto.\n          destruct trie; simpl in *.\n          unfold TrieBag_benumerate; simpl.\n          rewrite !XMapfold_eq, !fold_1 by eauto.\n          rewrite Permutation_benumerate_fold_left, flatten_app; simpl;\n          rewrite filter_app, app_nil_r; simpl; f_equiv.\n          rewrite <- bfind_correct by eauto.\n          + match goal with\n            | [ H0 : TrieOK _ _ |- _ ] => inversion H0; subst\n            end.\n            rewrite filter_Prefix; eauto.\n          + rewrite <- (fun H => @fold_1 _ m H (list BagType) [ ] (fun k trie a => Trie_enumerate trie ++ a)) by eauto.\n            match goal with\n            | [ H0 : TrieOK _ _ |- _ ] =>\n                rewrite Permutation_KeyBasedPartition with (key0 := key0)\n                                                           (bst_m := SubTrieMapBST H0)\n            end.\n            simpl.\n            apply find_2 in e0.\n            match goal with\n            | [ H0 : TrieOK _ _ |- _ ] =>\n                pose proof (KeyBasedPartition_fst_singleton key0 subtrie (XMap.Bst (SubTrieMapBST H0)) e0) as singleton\n            end.\n            rewrite (fold_Equal_simpl (eqA := @Permutation BagType) singleton)\n              by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n            rewrite !fold_add;\n              eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey, empty_In.\n            rewrite map_app, flatten_app, filter_app, <- app_nil_r.\n            f_equiv.\n            rewrite <- app_assoc; simpl; eauto.\n            rewrite fold_empty, flatten_filter,map_map.\n\n            rewrite (fold_Equal_simpl (eqA := @Permutation BagType) (filter_negb_remove key0 _))\n              by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n            eapply filter_remove_key; eauto.\n        - rewrite !app_nil_r, <- bfind_correct by eauto.\n          destruct trie; simpl.\n          unfold TrieBag_benumerate; simpl.\n          rewrite !XMapfold_eq, !fold_1 by eauto.\n          rewrite Permutation_benumerate_fold_left, flatten_app; simpl;\n          rewrite filter_app, app_nil_r; simpl.\n          rewrite <- app_nil_r; f_equiv.\n          + rewrite filter_Prefix; eauto.\n          + rewrite <- (fun H => @fold_1 _ m H (list BagType) [ ] (fun k trie a => Trie_enumerate trie ++ a)) by eauto.\n            match goal with\n            | [ H : TrieOK _ _ |- _ ] =>\n                rewrite Permutation_KeyBasedPartition with (key0 := key0)\n                                                           (bst_m := SubTrieMapBST' H)\n            end.\n            simpl in *.\n            match goal with\n            | [ H : TrieOK _ _ |- _ ] =>\n                rewrite <- (@not_find_in_iff _ (XMap.Bst (SubTrieMapBST' H)) key0) in e0\n            end.\n            match goal with\n            | [ H : TrieOK _ _ |- _ ] =>\n                pose proof (KeyBasedPartition_fst_singleton_None key0 (XMap.Bst (SubTrieMapBST H)) e0) as singleton\n            end.\n            rewrite (fold_Equal_simpl (eqA := @Permutation BagType) singleton)\n              by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n            rewrite fold_empty, flatten_filter, map_map.\n            rewrite (fold_Equal_simpl (eqA := @Permutation BagType) (filter_negb_remove key0 _))\n              by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n            eapply filter_remove_key; eauto.\n      }\n      { simpl; unfold TrieBag_bfind_matcher; simpl.\n        intros.\n        generalize (Trie_enumerate_RepInv containerCorrect).\n        unfold TrieBag_benumerate.\n        induction (Trie_enumerate container); simpl.\n        - eauto.\n        - intros; rewrite <- bfind_correct by eauto.\n          rewrite !filter_app; f_equiv; eauto.\n      }\n    Qed.\n\n    Corollary TrieBag_enumerateOK''\n      : forall l st1 search_term,\n        (forall (k : X.t) (subtrie : Trie),\n            InA (PX.eqke (elt:=Trie)) (k, subtrie) l ->\n            TrieOK subtrie (st1 ++ [k]))\n        -> Permutation\n             (List.filter (fun a => negb (TrieBag_bfind_matcher (Some st1, search_term) a))\n                          (flatten\n                             (List.map benumerate\n                                       (fold_left\n                                          (fun (a : list (BagType)) (p : key * Trie) =>\n                                             (Trie_enumerate (snd p)) ++ a) l [ ]))))\n             (flatten\n                (List.map benumerate\n                          (fold_left\n                             (fun (a : list (BagType)) (p : key * Trie) =>\n                                (Trie_enumerate (snd p)) ++ a) l [ ]))).\n    Proof.\n      intros; generalize (@TrieBag_enumerateOK' l st1 search_term H); clear.\n      induction (flatten\n                   (List.map benumerate\n                             (fold_left\n                                (fun (a : list (BagType)) (p : key * Trie) =>\n                                   (Trie_enumerate (snd p)) ++ a) l [ ])));\n        simpl; eauto.\n      find_if_inside; intros; simpl.\n      symmetry in H; apply Permutation_nil in H; discriminate.\n      eauto.\n    Qed.\n\n    Lemma TrieOK_distinct_subtries :\n      forall b m key' l k subtrie bst_m\n             (OK : TrieOK (Node b m) l),\n        InA (PX.eqke (elt:=Trie)) (k, subtrie)\n            (elements\n               (XMap.this\n                  (XMap.remove (elt:=Trie) key'\n                               {|\n                                 XMap.this := m;\n                                 XMap.is_bst := bst_m  |}))) ->\n        ~ X.eq k key'.\n    Proof.\n      simpl; intros.\n      assert (bst (remove key' m)) by eauto using remove_bst.\n      rewrite <- (@elements_mapsto_iff _ (XMap.Bst (H0))) in H;\n        simpl in H0.\n      unfold not; intros.\n      symmetry in H1; revert H1.\n      pose proof (@remove_mapsto_iff  _ (XMap.Bst (bst_m))).\n      eapply H1; simpl; eauto.\n    Qed.\n\n    Lemma TrieOK_distinct_subtries' :\n      forall b m key' l k subtrie bst_m\n             (OK : TrieOK (Node b m) l),\n        InA (PX.eqke (elt:=Trie)) (k, subtrie)\n            (elements\n               (XMap.this\n                  (filter\n                     (fun (k0 : XMap.key) (e : Trie) =>\n                        negb (KeyBasedPartitioningFunction Trie key' k0 e))\n                     {|\n                       XMap.this := m;\n                       XMap.is_bst := bst_m |}))) ->\n        ~ X.eq k key'.\n    Proof.\n      intros * OK H2.\n      assert (bst ((XMap.this\n                              (filter\n                                 (fun (k0 : XMap.key) (e : Trie) =>\n                                    negb (KeyBasedPartitioningFunction Trie key' k0 e))\n                                 {|\n                                   XMap.this := m;\n                                   XMap.is_bst := bst_m |})))) by exact (XMap.is_bst _).\n      intros; rewrite <- (@elements_mapsto_iff _ (XMap.Bst H) k subtrie) in H2.\n      apply (@filter_iff _ (fun (k0 : XMap.key) (e : Trie) =>\n                              negb\n                                (KeyBasedPartitioningFunction Trie key' k0 e))) in H2.\n      intuition.\n      unfold KeyBasedPartitioningFunction in *.\n      find_if_inside; simpl in *; try congruence.\n      unfold Proper, respectful; intros; subst.\n      unfold KeyBasedPartitioningFunction; repeat find_if_inside; eauto;\n        rewrite <- e in n; intuition.\n    Qed.\n\n    Lemma Proper_negb_KeyBasedPartitioningFunction\n    : forall key',\n        Proper (X.eq ==> eq ==> eq)\n               (fun (k0 : XMap.key) (e : Trie) =>\n                  negb (KeyBasedPartitioningFunction Trie key' k0 e)).\n    Proof.\n      unfold Proper, respectful, KeyBasedPartitioningFunction; intros.\n      repeat find_if_inside; subst; simpl; eauto;\n        rewrite H in *; intuition.\n    Qed.\n\n    Instance Proper_Trie_enumerate_app\n      : Proper\n          (X.eq ==> eq ==> Permutation (A:=BagType) ==> Permutation (A:=BagType))\n          (fun (_ : X.t) (tries : Trie) (bags : list BagType) =>\n             Trie_enumerate tries ++ bags).\n    Proof.\n      unfold Proper, respectful, KeyBasedPartitioningFunction; intros.\n      subst; rewrite H1.\n      reflexivity.\n    Qed.\n\n    Lemma transpose_neqkey_Trie_enumerate_app\n      : transpose_neqkey (Permutation (A:=BagType))\n                         (fun (_ : X.t) (tries : Trie) (bags : list BagType) =>\n                            Trie_enumerate tries ++ bags).\n    Proof.\n      unfold transpose_neqkey; intros.\n      rewrite !app_assoc; f_equiv.\n      apply Permutation_app_swap.\n    Qed.\n\n    Lemma TrieBag_BagDeleteCorrect :\n      BagDeleteCorrect TrieBagRepInv TrieBag_bfind TrieBag_bfind_matcher\n                       TrieBag_benumerate TrieBag_bdelete.\n    Proof.\n      intros container search_term.\n      destruct search_term as [ [st | ] search_term].\n      { unfold TrieBag_bdelete.\n        split.\n        {\n          rewrite <- (app_nil_l st) at 2.\n          revert containerCorrect.\n          unfold TrieBagRepInv; remember [] as l; clear Heql; revert l.\n          eapply Trie_delete_ind; intros; subst; simpl.\n          - destruct (bdelete_correct (TrieNode trie) search_term0); eauto.\n            destruct trie; simpl.\n            unfold TrieBag_benumerate; simpl.\n            rewrite !XMapfold_eq, !fold_1 by eauto.\n            rewrite e0 in H.\n            rewrite partition_filter_neq.\n            rewrite Permutation_benumerate_fold_left, flatten_app; simpl.\n            rewrite (Permutation_benumerate_fold_left _ [b]), flatten_app; simpl.\n            rewrite filter_app.\n            rewrite H, partition_filter_neq, !app_nil_r; simpl.\n            f_equiv.\n            + eapply filter_negb_Prefix; eauto; reflexivity.\n            + inversion containerCorrect; subst.\n              rewrite <- TrieBag_enumerateOK'' at 1.\n              unfold TrieBag_bfind_matcher, IsPrefix; reflexivity.\n              intros; eapply H7.\n              eapply (@XMap.elements_2 _ (XMap.Bst H4)); eauto.\n          - rewrite e2 in H; simpl in *.\n            destruct trie; simpl in *.\n            unfold TrieBag_benumerate; simpl.\n            rewrite !XMapfold_eq, !fold_1 by eauto.\n            rewrite partition_filter_neq.\n            rewrite Permutation_benumerate_fold_left, flatten_app; simpl.\n            rewrite (Permutation_benumerate_fold_left _ [b]), flatten_app; simpl.\n            rewrite !filter_app.\n            rewrite app_nil_r, <- app_assoc.\n            f_equiv.\n            + replace (bag') with (snd  (bdelete b search_term0))\n                by (rewrite e0; eauto).\n              destruct (bdelete_correct b search_term0); eauto.\n              rewrite H0.\n              rewrite partition_filter_neq.\n              eapply filter_negb_Prefix; eauto; reflexivity.\n            + simpl.\n              rewrite <- (fun H => @fold_1 _ m H (list BagType) [ ] (fun k trie a => Trie_enumerate trie ++ a)) by eauto.\n              rewrite Permutation_KeyBasedPartition with (key0 := key0)\n                                                           (bst_m := SubTrieMapBST containerCorrect).\n              simpl in *.\n              apply find_2 in e1.\n              pose proof (KeyBasedPartition_fst_singleton key0 subtrie (XMap.Bst (SubTrieMapBST containerCorrect)) e1) as singleton.\n              rewrite (fold_Equal_simpl (eqA := @Permutation BagType) singleton)\n                by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n              rewrite !fold_add;\n                eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey, empty_In.\n              rewrite flatten_filter.\n              rewrite !map_app, fold_empty, !map_map.\n              rewrite flatten_app.\n              rewrite (Permutation_benumerate_add key0 bag'' (XMap.Bst (SubTrieMapBST containerCorrect))).\n              rewrite map_app, flatten_app.\n              f_equiv.\n              * rewrite (H (l ++ [key0])), partition_filter_neq.\n                unfold TrieBag_benumerate; rewrite flatten_filter, map_map.\n                unfold TrieBag_bfind_matcher; rewrite <- app_assoc.\n                repeat f_equiv.\n                inversion containerCorrect; subst; eauto.\n              * pose (@XMap.fold_1 _ (XMap.remove key0 (XMap.Bst (SubTrieMapBST containerCorrect)))\n                                   _ nil\n                                   (fun (_ : key) (trie : Trie) (a : list BagType) =>\n                                      Trie_enumerate trie ++ a)).\n                simpl in e;  unfold XMap.key, key in *; rewrite <- e.\n                rewrite (fold_Equal_simpl (eqA := @Permutation BagType) (filter_negb_remove key0 _))\n                  by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n                unfold XMap.fold.\n                rewrite !fold_1.\n                rewrite <- TrieBag_enumerateOK'''.\n                rewrite flatten_filter.\n                rewrite map_map.\n                unfold TrieBag_bfind_matcher, IsPrefix; simpl.\n                f_equiv.\n                intros; eapply TrieOK_subtrie_remove; simpl in *;\n                eauto using Proper_negb_KeyBasedPartitioningFunction.\n                intros; eapply TrieOK_distinct_subtries; eauto.\n                exact (XMap.is_bst _).\n          - destruct trie; simpl in *.\n            unfold TrieBag_benumerate; simpl.\n            rewrite !XMapfold_eq, !fold_1 by eauto.\n            rewrite partition_filter_neq.\n            rewrite Permutation_benumerate_fold_left, flatten_app; simpl.\n            rewrite (Permutation_benumerate_fold_left _ [b]), flatten_app; simpl.\n            rewrite !filter_app.\n            rewrite app_nil_r, <- app_assoc.\n            f_equiv.\n            + replace (bag') with (snd  (bdelete b search_term0))\n                by (rewrite e0; eauto).\n              destruct (bdelete_correct b search_term0); eauto.\n              rewrite H.\n              rewrite partition_filter_neq.\n              eapply filter_negb_Prefix; eauto; reflexivity.\n            + simpl.\n              rewrite <- (fun H => @fold_1 _ m H (list BagType) [ ] (fun k trie a => Trie_enumerate trie ++ a)) by eauto.\n              rewrite Permutation_KeyBasedPartition with (key0 := key0)\n                                                           (bst_m := SubTrieMapBST containerCorrect).\n              simpl.\n              rewrite <- (@not_find_in_iff _ (XMap.Bst (SubTrieMapBST' containerCorrect)) key0) in e1.\n              pose proof (KeyBasedPartition_fst_singleton_None key0 (XMap.Bst (SubTrieMapBST containerCorrect)) e1) as singleton.\n              rewrite (fold_Equal_simpl (eqA := @Permutation BagType) singleton)\n                by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n              rewrite !fold_empty;\n                eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey, empty_In.\n              unfold XMap.fold; rewrite !fold_1.\n              rewrite <- TrieBag_enumerateOK''' at 1.\n              unfold TrieBag_bfind_matcher, IsPrefix.\n              f_equiv.\n              intros; eapply TrieOK_subtrie_filter; simpl in *;\n              eauto using Proper_negb_KeyBasedPartitioningFunction.\n              intros; eapply TrieOK_distinct_subtries'; eauto.\n              exact (XMap.is_bst _).\n        }\n        { rewrite <- (app_nil_l st) at 2.\n          revert containerCorrect.\n          unfold TrieBagRepInv; remember [] as l; clear Heql; revert l.\n          eapply Trie_delete_ind; intros; subst; simpl.\n          - destruct (bdelete_correct (TrieNode trie) search_term0); eauto.\n            destruct trie; simpl.\n            unfold TrieBag_benumerate; simpl.\n            rewrite !XMapfold_eq, !fold_1 by eauto.\n            rewrite e0 in H.\n            rewrite partition_filter_eq.\n            rewrite Permutation_benumerate_fold_left, flatten_app; simpl.\n            rewrite filter_app.\n            replace deletedItems with (fst (bdelete b search_term0)) by\n                (simpl in *; rewrite e0; eauto).\n            destruct (bdelete_correct b search_term0); eauto.\n            rewrite H2, partition_filter_eq; simpl.\n            rewrite <- app_nil_r at 1.\n            f_equiv.\n            + inversion containerCorrect; subst.\n              revert H7; clear.\n              induction (benumerate b); simpl; eauto.\n              unfold TrieBag_bfind_matcher, IsPrefix.\n              intros; case_eq (Prefix_dec F.eq_dec (projection a) l); simpl; intros.\n              find_if_inside; simpl; rewrite IHl0; eauto.\n              rewrite app_nil_r, H; simpl; eauto.\n              rewrite andb_false_r; eauto.\n              find_if_inside.\n              simpl; rewrite app_nil_r, H; simpl.\n              assert (Prefix (projection a) l)\n                by (eexists nil; rewrite app_nil_r; eauto).\n              rewrite <- IsPrefix_iff_Prefix in H0; simpl in *; rewrite H in H0; congruence.\n              assert (Prefix (projection a) l)\n                by (eexists nil; rewrite app_nil_r; eauto).\n              rewrite <- IsPrefix_iff_Prefix in H0; simpl in *; rewrite H in H0; congruence.\n            + inversion containerCorrect; subst.\n              rewrite TrieBag_enumerateOK' at 1; eauto.\n              rewrite app_nil_r.\n              intros; eapply H9.\n              eapply (@XMap.elements_2 _ (XMap.Bst H6)); eauto.\n          - rewrite e2 in H; simpl in *.\n            destruct trie; simpl in *.\n            unfold TrieBag_benumerate; simpl.\n            rewrite !XMapfold_eq, !fold_1 by eauto.\n            rewrite partition_filter_eq.\n            rewrite Permutation_benumerate_fold_left, flatten_app; simpl.\n            rewrite !filter_app; simpl.\n            f_equiv.\n            + replace deletedItems with (fst (bdelete b search_term0))\n                by (rewrite e0; eauto).\n              destruct (bdelete_correct b search_term0); eauto.\n              rewrite H1, partition_filter_eq, app_nil_r.\n              inversion containerCorrect; subst.\n              intros; eapply filter_Prefix; eauto; reflexivity.\n            + rewrite (H (l ++ [key0])); simpl; eauto.\n              rewrite partition_filter_eq.\n              rewrite <- (fun H => @fold_1 _ m H (list BagType) [ ] (fun k trie a => Trie_enumerate trie ++ a)) by eauto.\n              rewrite Permutation_KeyBasedPartition with (key0 := key0)\n                                                           (bst_m := SubTrieMapBST containerCorrect).\n              simpl.\n              apply find_2 in e1.\n              pose proof (KeyBasedPartition_fst_singleton key0 subtrie (XMap.Bst (SubTrieMapBST containerCorrect)) e1) as singleton.\n              rewrite (fold_Equal_simpl (eqA := @Permutation BagType) singleton)\n                by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n              rewrite !fold_add;\n                eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey, empty_In.\n              rewrite flatten_filter.\n              rewrite !map_app, fold_empty, !map_map.\n              rewrite flatten_app.\n              rewrite <- app_nil_r at 1.\n              f_equiv.\n              * unfold TrieBag_benumerate; rewrite flatten_filter, map_map, <- app_assoc; reflexivity.\n              * rewrite <- filter_remove_key; eauto.\n                rewrite (fold_Equal_simpl (eqA := @Permutation BagType) (filter_negb_remove key0 _))\n                  by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n                eauto.\n                simpl; eauto.\n          - destruct trie; simpl in *.\n            unfold TrieBag_benumerate; simpl.\n            rewrite !XMapfold_eq, !fold_1 by eauto.\n            rewrite partition_filter_eq.\n            rewrite Permutation_benumerate_fold_left, flatten_app; simpl.\n            rewrite !filter_app.\n            rewrite <- app_nil_r at 1.\n            f_equiv.\n            + replace deletedItems with (fst (bdelete b search_term0))\n                by (rewrite e0; eauto).\n              destruct (bdelete_correct b search_term0); eauto.\n              rewrite H0, partition_filter_eq, app_nil_r.\n              eapply filter_Prefix; eauto.\n            + simpl.\n              rewrite <- (fun H => @fold_1 _ m H (list BagType) [ ] (fun k trie a => Trie_enumerate trie ++ a)) by eauto.\n              rewrite Permutation_KeyBasedPartition with (key0 := key0)\n                                                           (bst_m := SubTrieMapBST containerCorrect).\n              rewrite <- (@not_find_in_iff _ (XMap.Bst (SubTrieMapBST' containerCorrect)) key0) in e1.\n              pose proof (KeyBasedPartition_fst_singleton_None key0 (XMap.Bst (SubTrieMapBST containerCorrect)) e1) as singleton.\n              rewrite (fold_Equal_simpl (eqA := @Permutation BagType) singleton)\n                by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n              rewrite !fold_empty;\n                eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey, empty_In.\n              simpl.\n              rewrite (fold_Equal_simpl (eqA := @Permutation BagType) (filter_negb_remove key0 _))\n                by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n              rewrite <- filter_remove_key, flatten_filter, map_map; eauto.\n        }\n      }\n      { unfold TrieBag_bfind_matcher; simpl.\n        unfold TrieBagRepInv.\n        pattern container, (@nil X.t) ; apply Trie_ind'; simpl; intros.\n        unfold TrieBag_benumerate; simpl.\n        intros; inversion containerCorrect; subst.\n        case_eq (bdelete b search_term); simpl; intros.\n        destruct (bdelete_correct b search_term); eauto.\n        rewrite H0 in H1, H5; simpl in H1, H5.\n        rewrite (Permute_XMapfold_cons m [b]), Permute_XMapfold_cons with (l := [b0]).\n        rewrite !map_app, !flatten_app, !partition_app; simpl.\n        rewrite !app_nil_r.\n        split.\n        - rewrite H1; f_equiv.\n          rewrite !XMapfold_eq.\n          setoid_rewrite (fold_pair (XMap.Bst H3)); simpl.\n          rewrite fold_spec_right.\n          pose fold_spec_right as e; unfold XMap.fold in e; rewrite (e _ (XMap.Bst H3));\n          clear e.\n          assert (forall k trie,\n                     InA (@XMap.eq_key_elt _)\n                         (k, trie)\n                         (rev\n                            (XMap.elements (elt:=Trie)\n                                           {| XMap.this := m; XMap.is_bst := H3 |}))\n                     -> Permutation (TrieBag_benumerate (snd (Trie_delete' trie search_term)))\n                                    (snd\n                                       (List.partition\n                                          (fun item : TItem => bfind_matcher search_term item)\n                                          (TrieBag_benumerate trie)))).\n          { intros; eapply H; eauto using elements_mapsto_iff.\n            pose elements_mapsto_iff as e; unfold XMap.MapsTo in e; rewrite (e _ (XMap.Bst H3));\n            clear e.\n            rewrite <- InA_rev; eauto with typeclass_instances.\n            eapply H6.\n            eapply (@elements_mapsto_iff _ (XMap.Bst H3)).\n            eapply InA_rev; eauto with typeclass_instances.\n          }\n          generalize H7; clear.\n          assert (NoDupA (@XMap.eq_key _)\n                         (rev\n                            (XMap.elements (elt:=Trie) {| XMap.this := m; XMap.is_bst := H3 |})))\n          by (apply NoDupA_rev; eauto with typeclass_instances;\n              eapply XMap.elements_3w).\n          revert H.\n          induction (rev\n                       (XMap.elements (elt:=Trie) {| XMap.this := m; XMap.is_bst := H3 |}));\n            simpl; intros; eauto.\n          unfold uncurry.\n          pose fold_add as e; unfold XMap.fold, XMap.add in e; simpl in e.\n          rewrite e; clear e.\n          rewrite !map_app, !flatten_app, !partition_app; simpl.\n          unfold TrieBag_benumerate in H7.\n          rewrite H7 with (k := fst a); f_equiv; eauto.\n          rewrite <- IHl; eauto.\n          inversion H; eauto;\n            intros; eapply H7; simpl; econstructor 2; eauto.\n          econstructor; destruct a; simpl; reflexivity.\n          eauto with typeclass_instances.\n          eauto with typeclass_instances.\n          eauto using transpose_neqkey_Trie_enumerate_app.\n          inversion H; subst; intro; apply H2.\n          unfold XMap.In, In0 in H0.\n          revert H0; clear; induction l; simpl.\n          + intros; destruct H0; inversion H.\n          + intros; destruct H0.\n            pose add_mapsto_iff as e; unfold XMap.add, XMap.MapsTo in e; simpl in e;\n            rewrite e in H; clear e.\n            intuition.\n            * econstructor 1; symmetry; apply H.\n            * eauto.\n        - rewrite H5, Permutation_app_swap; f_equiv.\n          rewrite !XMapfold_eq.\n          setoid_rewrite (fold_pair (XMap.Bst H3)); simpl.\n          rewrite fold_spec_right.\n          pose fold_spec_right as e; unfold XMap.fold in e; rewrite (e _ (XMap.Bst H3));\n          clear e.\n          assert (forall k trie,\n                     InA (@XMap.eq_key_elt _)\n                         (k, trie)\n                         (rev\n                            (XMap.elements (elt:=Trie)\n                                           {| XMap.this := m; XMap.is_bst := H3 |}))\n                     -> Permutation ((fst (Trie_delete' trie search_term)))\n                                    (fst\n                                       (List.partition\n                                          (fun item : TItem => bfind_matcher search_term item)\n                                          (TrieBag_benumerate trie)))).\n          { intros; eapply H; eauto using elements_mapsto_iff.\n            pose elements_mapsto_iff as e; unfold XMap.MapsTo in e; rewrite (e _ (XMap.Bst H3));\n            clear e.\n            rewrite <- InA_rev; eauto with typeclass_instances.\n            eapply H6.\n            eapply (@elements_mapsto_iff _ (XMap.Bst H3)).\n            eapply InA_rev; eauto with typeclass_instances.\n          }\n          generalize H7; clear.\n          assert (NoDupA (@XMap.eq_key _)\n                         (rev\n                            (XMap.elements (elt:=Trie) {| XMap.this := m; XMap.is_bst := H3 |})))\n          by (apply NoDupA_rev; eauto with typeclass_instances;\n              eapply XMap.elements_3w).\n          revert H.\n          induction (rev\n                       (XMap.elements (elt:=Trie) {| XMap.this := m; XMap.is_bst := H3 |}));\n            simpl; intros; eauto.\n          unfold uncurry.\n          rewrite !map_app, !flatten_app, !partition_app; simpl.\n          unfold TrieBag_benumerate in H7.\n          rewrite H7 with (k := fst a); f_equiv; eauto.\n          rewrite <- IHl; eauto.\n          inversion H; eauto.\n          econstructor; destruct a; simpl; reflexivity.\n      }\n    Qed.\n\n    Lemma TrieBag_BagUpdateCorrect :\n      BagUpdateCorrect TrieBagRepInv TrieBag_ValidUpdate\n                       TrieBag_bfind TrieBag_bfind_matcher\n                       TrieBag_benumerate bupdate_transform TrieBag_bupdate.\n    Proof.\n      intros container search_term.\n      destruct search_term as [ [st | ] search_term].\n      {\n        unfold TrieBag_bupdate.\n        split.\n        {\n          rewrite <- (app_nil_l st); rewrite app_nil_l at 1.\n          revert containerCorrect.\n          unfold TrieBagRepInv; remember [] as l; clear Heql; revert l valid_update.\n          eapply Trie_update_ind; intros; subst; simpl.\n          - destruct (bupdate_correct (TrieNode trie) search_term0 updateTerm); eauto.\n            destruct trie; simpl.\n            rewrite partition_filter_neq, partition_filter_eq.\n            unfold TrieBag_benumerate; simpl.\n            rewrite !XMapfold_eq, !fold_1 by eauto.\n            rewrite e0 in H, H0; simpl in *.\n            rewrite Permutation_benumerate_fold_left, flatten_app; simpl.\n            rewrite (Permutation_benumerate_fold_left _ [b]), flatten_app; simpl.\n            rewrite H, partition_filter_neq,\n            partition_filter_eq, !app_nil_r, !filter_app, <- !app_assoc ; simpl.\n            f_equiv.\n            + eapply filter_negb_Prefix; eauto; reflexivity.\n            + symmetry.\n              rewrite map_app, Permutation_app_swap, <- app_assoc; f_equiv.\n              f_equiv.\n              * symmetry; eapply filter_Prefix; eauto; reflexivity.\n              * inversion containerCorrect; subst.\n                rewrite TrieBag_enumerateOK'; simpl.\n                rewrite <- TrieBag_enumerateOK'' at 2.\n                unfold TrieBag_bfind_matcher, IsPrefix; reflexivity.\n                intros; eapply H7; eapply (@elements_mapsto_iff _ (XMap.Bst H4)); eauto.\n                intros; eapply H7; eapply (@elements_mapsto_iff _ (XMap.Bst H4)); eauto.\n          - rewrite e2 in H; simpl in *.\n            destruct trie; simpl in *.\n            unfold TrieBag_benumerate; simpl.\n            rewrite !XMapfold_eq, !fold_1 by eauto.\n            rewrite partition_filter_neq, partition_filter_eq.\n            rewrite Permutation_benumerate_fold_left, flatten_app; simpl.\n            rewrite (Permutation_benumerate_fold_left _ [b]), flatten_app; simpl.\n            rewrite !filter_app.\n            rewrite app_nil_r, <- !app_assoc; simpl.\n            rewrite map_app.\n            replace (bag') with (snd  (bupdate b search_term0 updateTerm))\n              by (rewrite e0; eauto).\n            destruct (bupdate_correct b search_term0 updateTerm); eauto.\n            rewrite H0, partition_filter_neq, partition_filter_eq, <- !app_assoc.\n            f_equiv.\n            + eapply filter_negb_Prefix; eauto; reflexivity.\n            + symmetry; rewrite Permutation_app_swap, <- app_assoc.\n              f_equiv.\n              * symmetry; f_equiv; eapply filter_Prefix; eauto.\n              * rewrite <- (fun H => @fold_1 _ m H (list BagType) [ ] (fun k trie a => Trie_enumerate trie ++ a)) by eauto.\n                rewrite Permutation_KeyBasedPartition with (key0 := key0)\n                                                             (bst_m := SubTrieMapBST containerCorrect).\n                rewrite (Permutation_benumerate_add key0 bag'' (XMap.Bst (SubTrieMapBST containerCorrect))).\n                rewrite map_app, flatten_app.\n                rewrite (H (l ++ [key0])), partition_filter_neq, partition_filter_eq.\n                rewrite <- app_assoc.\n                symmetry; rewrite Permutation_app_swap; symmetry.\n                rewrite <- app_assoc.\n                f_equiv.\n                { simpl.\n                  apply find_2 in e1.\n                  pose proof (KeyBasedPartition_fst_singleton key0 subtrie (XMap.Bst (SubTrieMapBST containerCorrect)) e1) as singleton.\n                  rewrite (fold_Equal_simpl (eqA := @Permutation BagType) singleton)\n                    by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n                  rewrite !fold_add;\n                    eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey, empty_In.\n                  rewrite flatten_filter.\n                  rewrite !map_app, fold_empty, !map_map.\n                  rewrite flatten_app.\n                  rewrite Permutation_app_swap, map_app.\n                  rewrite (fold_Equal_simpl (eqA := @Permutation BagType) (filter_negb_remove key0 _))\n                    by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n                  rewrite filter_remove_key; eauto.\n                  simpl.\n                  unfold TrieBag_benumerate.\n                  rewrite <- map_map.\n                  rewrite flatten_filter, map_flatten.\n                  setoid_rewrite map_id; setoid_rewrite map_id.\n                  rewrite map_map, <- app_assoc; reflexivity.\n                }\n                simpl.\n                rewrite flatten_filter, map_map.\n                apply find_2 in e1.\n                pose proof (KeyBasedPartition_fst_singleton key0 subtrie (XMap.Bst (SubTrieMapBST containerCorrect)) e1) as singleton.\n                rewrite (fold_Equal_simpl (eqA := @Permutation BagType) singleton)\n                  by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n                rewrite !fold_add;\n                  eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey, empty_In.\n                rewrite map_app, flatten_app.\n                symmetry; rewrite Permutation_app_swap; symmetry.\n                f_equiv.\n                { unfold TrieBag_benumerate;\n                  rewrite <- map_map.\n                  rewrite flatten_filter, <- app_assoc; simpl; reflexivity.\n                }\n                rewrite fold_empty.\n                rewrite (fold_Equal_simpl (eqA := @Permutation BagType) (filter_negb_remove key0 _))\n                  by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n                unfold XMap.fold, XMap.remove, XMap.elements; simpl.\n                rewrite fold_1; simpl.\n                rewrite <- TrieBag_enumerateOK'''; eauto.\n                rewrite flatten_filter, map_map; unfold TrieBag_bfind_matcher, IsPrefix; reflexivity; eauto.\n                intros; eapply TrieOK_distinct_subtries; eauto.\n                apply remove_bst.\n                eauto.\n                eauto.\n                eauto.\n          - destruct trie; simpl in *.\n            unfold TrieBag_benumerate; simpl.\n            rewrite !XMapfold_eq, !fold_1 by eauto.\n            rewrite partition_filter_neq, partition_filter_eq.\n            rewrite Permutation_benumerate_fold_left, flatten_app; simpl.\n            rewrite (Permutation_benumerate_fold_left _ [b]), flatten_app; simpl.\n            rewrite !filter_app.\n            rewrite app_nil_r, <- !app_assoc; simpl.\n            rewrite map_app.\n            replace (bag') with (snd  (bupdate b search_term0 updateTerm))\n              by (rewrite e0; eauto).\n            destruct (bupdate_correct b search_term0 updateTerm); eauto.\n            rewrite H, partition_filter_neq, partition_filter_eq, <- !app_assoc.\n            f_equiv.\n            + eapply filter_negb_Prefix; eauto; reflexivity.\n            + symmetry; rewrite Permutation_app_swap, <- app_assoc.\n              f_equiv.\n              * rewrite filter_Prefix; eauto; reflexivity.\n              * simpl.\n                rewrite <- (fun H => @fold_1 _ m H (list BagType) [ ] (fun k trie a => Trie_enumerate trie ++ a)) by eauto.\n                rewrite Permutation_KeyBasedPartition with (key0 := key0)\n                                                             (bst_m := SubTrieMapBST containerCorrect).\n                simpl.\n                rewrite <- (@not_find_in_iff _ (XMap.Bst (SubTrieMapBST' containerCorrect)) key0) in e1.\n                pose proof (KeyBasedPartition_fst_singleton_None key0 (XMap.Bst (SubTrieMapBST containerCorrect)) e1) as singleton.\n                rewrite (fold_Equal_simpl (eqA := @Permutation BagType) singleton)\n                  by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n                rewrite !fold_empty;\n                  eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey, empty_In.\n                rewrite <- app_nil_l; f_equiv.\n                {\n                  replace (@nil TItem) with (List.map (bupdate_transform updateTerm) (@nil _)) by\n                      reflexivity.\n                  f_equiv.\n                  rewrite (fold_Equal_simpl (eqA := @Permutation BagType) (filter_negb_remove key0 _))\n                    by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n                  rewrite <- filter_remove_key; eauto.\n                  rewrite flatten_filter, map_map; eauto.\n                  eauto.\n                }\n                unfold XMap.fold; symmetry.\n                rewrite fold_1, <- TrieBag_enumerateOK''' at 1.\n                rewrite fold_1; unfold TrieBag_bfind_matcher, IsPrefix; eauto.\n                exact (XMap.is_bst _).\n                eauto using Proper_negb_KeyBasedPartitioningFunction.\n                intros; eapply TrieOK_distinct_subtries'; eauto.\n                exact (XMap.is_bst _).\n        }\n        {\n          rewrite <- (app_nil_l st); rewrite app_nil_l at 1.\n          revert containerCorrect.\n          unfold TrieBagRepInv; remember [] as l; clear Heql; revert l valid_update.\n          eapply Trie_update_ind; intros; subst; simpl.\n          - destruct (bupdate_correct (TrieNode trie) search_term0 updateTerm); eauto.\n            destruct trie; simpl.\n            rewrite partition_filter_eq.\n            unfold TrieBag_benumerate; simpl.\n            rewrite !XMapfold_eq, !fold_1 by eauto.\n            rewrite e0 in H, H0; simpl in *.\n            rewrite Permutation_benumerate_fold_left, flatten_app; simpl.\n            rewrite H0, partition_filter_eq, !app_nil_r, !filter_app ; simpl.\n            rewrite <- app_nil_r at 1.\n            f_equiv.\n            + rewrite filter_Prefix; eauto; reflexivity.\n            + inversion containerCorrect; subst.\n              rewrite TrieBag_enumerateOK' at 1; eauto.\n              intros; eapply H7.\n              eapply (@XMap.elements_2 _ (XMap.Bst H4)); eauto.\n          - rewrite e2 in H; simpl in *.\n            destruct trie; simpl in *.\n            unfold TrieBag_benumerate; simpl.\n            rewrite !XMapfold_eq, !fold_1 by eauto.\n            rewrite partition_filter_eq.\n            rewrite Permutation_benumerate_fold_left, flatten_app; simpl.\n            rewrite !filter_app, app_nil_r; simpl.\n            replace (updatedItems) with (fst (bupdate b search_term0 updateTerm))\n              by (rewrite e0; eauto).\n            destruct (bupdate_correct b search_term0 updateTerm); eauto.\n            rewrite H1, partition_filter_eq.\n            f_equiv.\n            + rewrite filter_Prefix; eauto; reflexivity.\n            + rewrite (H (l ++ [key0])); simpl; eauto.\n              rewrite partition_filter_eq.\n              rewrite <- (fun H => @fold_1 _ m H (list BagType) [ ] (fun k trie a => Trie_enumerate trie ++ a)) by eauto.\n              rewrite Permutation_KeyBasedPartition with (key0 := key0)\n                                                           (bst_m := SubTrieMapBST containerCorrect).\n              simpl.\n              apply find_2 in e1.\n              pose proof (KeyBasedPartition_fst_singleton key0 subtrie (XMap.Bst (SubTrieMapBST containerCorrect)) e1) as singleton.\n              rewrite (fold_Equal_simpl (eqA := @Permutation BagType) singleton)\n                by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n              rewrite !fold_add;\n                eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey, empty_In.\n              rewrite flatten_filter.\n              rewrite !map_app, fold_empty, !map_map.\n              rewrite flatten_app.\n              rewrite <- app_nil_r at 1.\n              f_equiv.\n              * unfold TrieBag_benumerate; rewrite flatten_filter, map_map, <- app_assoc; reflexivity.\n              * rewrite <- filter_remove_key; eauto.\n                rewrite (fold_Equal_simpl (eqA := @Permutation BagType) (filter_negb_remove key0 _))\n                  by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n                eauto.\n                eauto.\n          - destruct trie; simpl in *.\n            unfold TrieBag_benumerate; simpl.\n            rewrite !XMapfold_eq, !fold_1 by eauto.\n            rewrite partition_filter_eq.\n            rewrite Permutation_benumerate_fold_left, flatten_app; simpl.\n            rewrite !filter_app, app_nil_r; simpl.\n            replace (updatedItems) with (fst (bupdate b search_term0 updateTerm))\n              by (rewrite e0; eauto).\n            destruct (bupdate_correct b search_term0 updateTerm); eauto.\n            rewrite H0, partition_filter_eq.\n            rewrite <- app_nil_r at 1.\n            f_equiv.\n            + rewrite filter_Prefix; eauto.\n            + simpl.\n              rewrite <- (fun H => @fold_1 _ m H (list BagType) [ ] (fun k trie a => Trie_enumerate trie ++ a)) by eauto.\n              rewrite Permutation_KeyBasedPartition with (key0 := key0)\n                                                           (bst_m := SubTrieMapBST containerCorrect).\n              rewrite <- (@not_find_in_iff _ (XMap.Bst (SubTrieMapBST' containerCorrect)) key0) in e1.\n              pose proof (KeyBasedPartition_fst_singleton_None key0 (XMap.Bst (SubTrieMapBST containerCorrect)) e1) as singleton.\n              rewrite (fold_Equal_simpl (eqA := @Permutation BagType) singleton)\n                by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n              rewrite !fold_empty;\n                eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey, empty_In.\n              simpl.\n              rewrite (fold_Equal_simpl (eqA := @Permutation BagType) (filter_negb_remove key0 _))\n                by (eauto using Permutation_Equivalence, Tries_enumerate_app_Proper, Tries_enumerate_app_transpose_neqkey).\n              rewrite <- filter_remove_key; eauto.\n              rewrite flatten_filter, map_map; eauto.\n              eauto.\n        }\n      }\n      { unfold TrieBag_bfind_matcher; simpl.\n        unfold TrieBagRepInv.\n        pattern container, (@nil X.t) ; apply Trie_ind'; simpl; intros.\n        unfold TrieBag_benumerate; simpl.\n        intros; inversion containerCorrect; subst.\n        case_eq (bupdate b search_term update_term); simpl; intros.\n        destruct (bupdate_correct b search_term update_term); eauto.\n        rewrite H0 in H1, H5; simpl in H1, H5.\n        rewrite (Permute_XMapfold_cons m [b]), Permute_XMapfold_cons with (l := [b0]).\n        rewrite !map_app, !flatten_app, !partition_app; simpl.\n        rewrite !app_nil_r.\n        split.\n        - rewrite H1.\n          rewrite app_assoc.\n          symmetry.\n          rewrite (Permutation_app_swap).\n          symmetry.\n          rewrite <- !app_assoc.\n          rewrite (Permutation_app_swap (snd _)).\n          rewrite !app_assoc, map_app.\n          f_equiv.\n          symmetry; rewrite Permutation_app_swap, app_assoc.\n          f_equiv.\n          rewrite !XMapfold_eq.\n          symmetry.\n          setoid_rewrite (fold_pair (XMap.Bst H3)); simpl.\n          rewrite fold_spec_right.\n          pose fold_spec_right as e; unfold XMap.fold in e; rewrite (e _ (XMap.Bst H3));\n          clear e.\n          assert (forall k trie,\n                     InA (@XMap.eq_key_elt _)\n                         (k, trie)\n                         (rev\n                            (XMap.elements (elt:=Trie)\n                                           {| XMap.this := m; XMap.is_bst := H3 |}))\n                     -> Permutation (TrieBag_benumerate (snd (Trie_update' trie search_term update_term)))\n                                    (snd\n                                       (List.partition\n                                          (fun item : TItem => bfind_matcher search_term item)\n                                          (TrieBag_benumerate trie))\n                                          ++ List.map (bupdate_transform update_term)\n                                          (fst\n                                             (List.partition\n                                                (fun item : TItem => bfind_matcher search_term item)\n                                                (TrieBag_benumerate trie)))\n                 )).\n          { intros; eapply H; eauto using elements_mapsto_iff.\n            pose elements_mapsto_iff as e; unfold XMap.MapsTo in e; rewrite (e _ (XMap.Bst H3));\n            clear e.\n            rewrite <- InA_rev; eauto with typeclass_instances.\n            eapply H6.\n            eapply (@elements_mapsto_iff _ (XMap.Bst H3)).\n            eapply InA_rev; eauto with typeclass_instances.\n          }\n          generalize H7; clear.\n          assert (NoDupA (@XMap.eq_key _)\n                         (rev\n                            (XMap.elements (elt:=Trie) {| XMap.this := m; XMap.is_bst := H3 |})))\n          by (apply NoDupA_rev; eauto with typeclass_instances;\n              eapply XMap.elements_3w).\n          revert H.\n          induction (rev\n                       (XMap.elements (elt:=Trie) {| XMap.this := m; XMap.is_bst := H3 |}));\n            simpl; intros; eauto.\n          unfold uncurry.\n          pose fold_add as e; unfold XMap.fold, XMap.add in e; simpl in e.\n          rewrite e; clear e.\n          rewrite !map_app, !flatten_app, !partition_app; simpl.\n          unfold TrieBag_benumerate in H7.\n          rewrite H7 with (k := fst a); eauto with typeclass_instances.\n          rewrite <- !app_assoc; f_equiv; eauto.\n          rewrite IHl.\n          rewrite Permutation_app_swap, <- app_assoc, map_app.\n          f_equiv.\n          rewrite Permutation_app_swap; f_equiv.\n          inversion H; eauto.\n          intros; eapply H7; econstructor 2; eauto.\n          destruct a; econstructor 1; reflexivity.\n          eauto with typeclass_instances.\n          eauto with typeclass_instances.\n          eauto using transpose_neqkey_Trie_enumerate_app.\n          inversion H; subst; intro; apply H2.\n          unfold XMap.In, In0 in H0.\n          revert H0; clear; induction l; simpl.\n          + intros; destruct H0; inversion H.\n          + intros; destruct H0.\n            pose add_mapsto_iff as e; unfold XMap.add, XMap.MapsTo in e; simpl in e;\n            rewrite e in H; clear e.\n            intuition.\n            * econstructor 1; symmetry; apply H.\n            * eauto.\n        - rewrite H5, Permutation_app_swap; f_equiv.\n          rewrite !XMapfold_eq.\n          setoid_rewrite (fold_pair (XMap.Bst H3)); simpl.\n          rewrite fold_spec_right.\n          pose fold_spec_right as e; unfold XMap.fold in e; rewrite (e _ (XMap.Bst H3));\n          clear e.\n          assert (forall k trie,\n                     InA (@XMap.eq_key_elt _)\n                         (k, trie)\n                         (rev\n                            (XMap.elements (elt:=Trie)\n                                           {| XMap.this := m; XMap.is_bst := H3 |}))\n                     -> Permutation ((fst (Trie_update' trie search_term update_term)))\n                                    (fst\n                                       (List.partition\n                                          (fun item : TItem => bfind_matcher search_term item)\n                                          (TrieBag_benumerate trie)))).\n          { intros; eapply H; eauto using elements_mapsto_iff.\n            pose elements_mapsto_iff as e; unfold XMap.MapsTo in e; rewrite (e _ (XMap.Bst H3));\n            clear e.\n            rewrite <- InA_rev; eauto with typeclass_instances.\n            eapply H6.\n            eapply (@elements_mapsto_iff _ (XMap.Bst H3)).\n            eapply InA_rev; eauto with typeclass_instances.\n          }\n          generalize H7; clear.\n          assert (NoDupA (@XMap.eq_key _)\n                         (rev\n                            (XMap.elements (elt:=Trie) {| XMap.this := m; XMap.is_bst := H3 |})))\n          by (apply NoDupA_rev; eauto with typeclass_instances;\n              eapply XMap.elements_3w).\n          revert H.\n          induction (rev\n                       (XMap.elements (elt:=Trie) {| XMap.this := m; XMap.is_bst := H3 |}));\n            simpl; intros; eauto.\n          unfold uncurry.\n          rewrite !map_app, !flatten_app, !partition_app; simpl.\n          unfold TrieBag_benumerate in H7.\n          rewrite H7 with (k := fst a); f_equiv; eauto.\n          rewrite <- IHl; eauto.\n          inversion H; eauto.\n          econstructor; destruct a; simpl; reflexivity.\n      }\n      Unshelve.\n      eauto.\n    Qed.\n\n  End TrieBagDefinitions.\n\n  Global Instance TrieAsBag\n         {BagType TItem SearchTermType UpdateTermType : Type}\n         (TBag : Bag BagType TItem SearchTermType UpdateTermType)\n         projection\n  : Bag Trie TItem ((option (list TKey)) * (SearchTermType)) UpdateTermType :=\n    {\n\n      bempty            := TrieBag_bempty TBag;\n\n      bfind_matcher     := TrieBag_bfind_matcher TBag projection;\n      bupdate_transform := bupdate_transform;\n\n      benumerate := TrieBag_benumerate TBag;\n      bfind      := TrieBag_bfind TBag;\n      binsert    := TrieBag_binsert TBag projection;\n      bcount     := TrieBag_bcount TBag;\n      bdelete    := TrieBag_bdelete TBag;\n      bupdate    := TrieBag_bupdate TBag }.\n\n  Global Instance TrieBagAsCorrectBag\n         {BagType TItem SearchTermType UpdateTermType : Type}\n         (TBag : Bag BagType TItem SearchTermType UpdateTermType)\n         (RepInv : BagType -> Prop)\n         (ValidUpdate : UpdateTermType -> Prop)\n         (CorrectTBag : CorrectBag RepInv ValidUpdate TBag)\n         projection\n  : CorrectBag (TrieBagRepInv TBag RepInv projection)\n               (TrieBag_ValidUpdate _ ValidUpdate projection)\n               (TrieAsBag TBag projection ) :=\n    {\n      bempty_RepInv     := Trie_Empty_RepInv CorrectTBag projection;\n      binsert_RepInv    := @TrieBag_binsert_Preserves_RepInv _ _ _ _ TBag _ _ _ projection;\n      bdelete_RepInv    := @TrieBag_bdelete_Preserves_RepInv _ _ _ _ TBag _ _ _ projection;\n      bupdate_RepInv    := @TrieBag_bupdate_Preserves_RepInv _ _ _ _ TBag _ _ CorrectTBag projection;\n\n      binsert_enumerate := @TrieBag_BagInsertEnumerate _ _ _ _ _ _ _ CorrectTBag projection;\n      benumerate_empty  := @TrieBag_BagEnumerateEmpty _ _ _ _ _ _ _ CorrectTBag;\n      bfind_correct     := @TrieBag_BagFindCorrect _ _ _ _ _ _ _ CorrectTBag projection;\n      bcount_correct    := @TrieBag_BagCountCorrect _ _ _ _ _ _ _ CorrectTBag projection;\n      bdelete_correct   := @TrieBag_BagDeleteCorrect _ _ _ _ _ _ _ CorrectTBag projection ;\n      bupdate_correct   := @TrieBag_BagUpdateCorrect _ _ _ _ _ _ _ CorrectTBag projection\n    }.\n\nEnd TrieBag.\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/TrieBags.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283035, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.26454036684817844}}
{"text": "Require Import Fiat.Parsers.BaseTypes.\nRequire Import Fiat.Parsers.Splitters.RDPList.\nRequire Import Fiat.Parsers.ContextFreeGrammar.PreNotations.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Carriers.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Fix.Fix.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Fix.Properties.\nRequire Import Fiat.Common.\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          (G : pregrammar' Char).\n\n  Let predata := @rdp_list_predata _ G.\n  Local Existing Instance predata.\n\n  Lemma pre_Fix_grammar_fixedpoint_correct_valid\n        (P : default_nonterminal_carrierT -> state gdata -> Type)\n        (Pinit : forall nt, is_true (is_valid_nonterminal initial_nonterminals_data nt)\n                            -> P nt ⊥)\n        (IH : forall nt st v,\n            st nt = v\n            -> is_true (is_valid_nonterminal initial_nonterminals_data nt)\n            -> P nt v\n            -> P nt (v ⊔ step_constraints gdata st nt v))\n    : forall nt, is_true (is_valid_nonterminal initial_nonterminals_data nt) -> P nt (lookup_state (pre_Fix_grammar gdata initial_nonterminals_data) nt).\n  Proof.\n    specialize (fun nt st => IH nt st _ eq_refl).\n    assert (Hvalid' : forall nt,\n               is_true (is_valid_nonterminal initial_nonterminals_data nt)\n               -> match FMapPositive.PositiveMap.find\n                          (nonterminal_to_positive nt)\n                          (aggregate_state_max gdata initial_nonterminals_data)\n                  with\n                  | Some v => P nt v\n                  | None => False\n                  end).\n    { intros nt Hvalid.\n      pose proof (find_aggregate_state_max_spec gdata G (nonterminal_to_positive nt)) as Hvalid'.\n      rewrite nonterminal_to_positive_to_nonterminal in Hvalid'.\n      edestruct Hvalid' as [Hvalid'0 Hvalid'1].\n      simpl in *.\n      rewrite Hvalid'1 by (split; [ reflexivity | assumption ]).\n      eauto. }\n    pose proof (fun nt (pf : is_true (is_valid_nonterminal (@initial_nonterminals_data _ (@rdp_list_predata _ G)) nt))\n                => match eq_sym pf in (_ = b)\n                         return (if b then ⊥ else ⊤) =\n                                lookup_state (aggregate_state_max gdata initial_nonterminals_data) nt\n                                -> _\n                   with\n                   | eq_refl => eq_rect _ (P nt) (Pinit _ pf) _\n                   end (eq_sym (lookup_state_aggregate_state_max gdata G nt))) as Pinit'.\n    unfold pre_Fix_grammar, pre_Fix_grammar_helper.\n    let Rwf := lazymatch goal with |- context[Fix ?Rwf _ _ ?v] => Rwf end in\n    let v := lazymatch goal with |- context[Fix Rwf _ _ ?v] => v end in\n    pose proof (fun nt => IH nt (lookup_state v)) as IHv;\n      specialize (fun nt pf => IHv nt pf (Pinit' _ pf));\n      induction (Rwf v) as [a Ha IHa].\n    rewrite Init.Wf.Fix_eq by (intros; edestruct Sumbool.sumbool_of_bool; trivial).\n    edestruct Sumbool.sumbool_of_bool; [ intros; apply Pinit'; assumption | ].\n    fold (pre_Fix_grammar_helper (gdata := gdata) initial_nonterminals_data) in *.\n    destruct (aggregate_state_eq a (aggregate_step a)) eqn:Heq.\n    { intuition congruence. }\n    { apply step_lt in Heq.\n      intros nt.\n      apply IHa; eauto; intros; try apply IH;\n        repeat match goal with\n               | _ => progress intros\n               | _ => rewrite find_aggregate_step\n               | _ => rewrite lookup_state_aggregate_step\n               | _ => rewrite nonterminal_to_positive_to_nonterminal\n               | _ => tauto\n               | _ => assumption\n               | _ => progress unfold lookup_state, PositiveMapExtensions.find_default, state, option_map, option_rect in *\n               | [ H : forall nt, is_true (?P nt) -> _, H' : is_true (?P _) |- _ ]\n                 => specialize (H _ H')\n               | [ |- ?P ?nt (_ ⊔ _) ] => apply P_lub\n               | [ H : context[match ?e with _ => _ end] |- _ ] => destruct e eqn:?\n               | [ |- context[match ?e with _ => _ end] ] => destruct e eqn:?\n               end. }\n  Qed.\n\n  Lemma pre_Fix_grammar_fixedpoint_correct\n        (P : default_nonterminal_carrierT -> state gdata -> Type)\n        (Pbot : forall nt, is_true (is_valid_nonterminal initial_nonterminals_data nt)\n                          -> P nt ⊥)\n        (Ptop : forall nt, is_valid_nonterminal initial_nonterminals_data nt = false\n                           -> P nt ⊤)\n        (IH : forall nt st v,\n            st nt = v\n            -> is_true (is_valid_nonterminal initial_nonterminals_data nt)\n            -> P nt v\n            -> P nt (v ⊔ step_constraints gdata st nt v))\n    : forall nt, P nt (lookup_state (pre_Fix_grammar gdata initial_nonterminals_data) nt).\n  Proof.\n    intro nt.\n    destruct (is_valid_nonterminal (@initial_nonterminals_data _ (@rdp_list_predata _ G)) nt) eqn:Hvalid.\n    { apply pre_Fix_grammar_fixedpoint_correct_valid; eauto with nocore. }\n    { simpl rewrite lookup_state_invalid_pre_Fix_grammar; [ | assumption ]. eauto with nocore. }\n  Qed.\n\n  Lemma pre_Fix_grammar_fixedpoint_correct_stronger'\n        (P : default_nonterminal_carrierT -> state gdata -> Type)\n        (Pbot : forall nt, is_true (is_valid_nonterminal initial_nonterminals_data nt)\n                          -> P nt ⊥)\n        (Ptop : forall nt, is_valid_nonterminal initial_nonterminals_data nt = false\n                           -> P nt ⊤)\n        (IH : forall nt st,\n            (forall nt', is_valid_nonterminal initial_nonterminals_data nt' = false -> st nt' = ⊤)\n            -> (forall nt', P nt' (st nt'))\n            -> P nt (st nt ⊔ step_constraints gdata st nt (st nt)))\n    : forall nt, is_true (is_valid_nonterminal initial_nonterminals_data nt) -> P nt (lookup_state (pre_Fix_grammar gdata initial_nonterminals_data) nt).\n  Proof.\n    assert (Htop : forall nt', is_valid_nonterminal initial_nonterminals_data nt' = false -> lookup_state (aggregate_state_max gdata initial_nonterminals_data) nt' = ⊤).\n    { intros nt' Hinvalid.\n      simpl rewrite lookup_state_aggregate_state_max; simpl in *; rewrite Hinvalid.\n      reflexivity. }\n    assert (Hvalid' : forall nt,\n               is_true (is_valid_nonterminal initial_nonterminals_data nt)\n               -> match FMapPositive.PositiveMap.find\n                          (nonterminal_to_positive nt)\n                          (aggregate_state_max gdata initial_nonterminals_data)\n                  with\n                  | Some v => P nt v\n                  | None => False\n                  end).\n    { intros nt Hvalid.\n      pose proof (find_aggregate_state_max_spec gdata G (nonterminal_to_positive nt)) as Hvalid'.\n      rewrite nonterminal_to_positive_to_nonterminal in Hvalid'.\n      edestruct Hvalid' as [Hvalid'0 Hvalid'1].\n      simpl rewrite Hvalid'1; [ | split; [ reflexivity | assumption ] ].\n      eauto. }\n    pose proof (fun nt\n                => match is_valid_nonterminal (@initial_nonterminals_data _ (@rdp_list_predata _ G)) nt as b\n                         return is_valid_nonterminal (@initial_nonterminals_data _ (@rdp_list_predata _ G)) nt = b\n                                -> (if b then ⊥ else ⊤) =\n                                   lookup_state (aggregate_state_max gdata initial_nonterminals_data) nt\n                                -> _\n                   with\n                   | true => fun pf => eq_rect _ (P nt) (Pbot _ pf) _\n                   | false => fun pf => eq_rect _ (P nt) (Ptop _ pf) _\n                   end eq_refl (eq_sym (lookup_state_aggregate_state_max gdata G nt))) as Pinit'.\n    unfold pre_Fix_grammar, pre_Fix_grammar_helper.\n    let Rwf := lazymatch goal with |- context[Fix ?Rwf _ _ ?v] => Rwf end in\n    let v := lazymatch goal with |- context[Fix Rwf _ _ ?v] => v end in\n    pose proof (fun nt => IH nt (lookup_state v)) as IHv;\n      specialize (fun nt => IHv nt Htop Pinit');\n      induction (Rwf v) as [a Ha IHa].\n    rewrite Init.Wf.Fix_eq by (intros; edestruct Sumbool.sumbool_of_bool; trivial).\n    edestruct Sumbool.sumbool_of_bool; [ intros; apply Pinit'; assumption | ].\n    fold (pre_Fix_grammar_helper (gdata := gdata) initial_nonterminals_data) in *.\n    destruct (aggregate_state_eq a (aggregate_step a)) eqn:Heq.\n    { intuition congruence. }\n    { apply step_lt in Heq.\n      intros nt.\n      simpl @nonterminal_carrierT in *.\n      apply IHa; eauto; intros; try apply IH;\n        repeat match goal with\n               | _ => progress intros\n               | _ => rewrite find_aggregate_step\n               | _ => rewrite lookup_state_aggregate_step\n               | _ => rewrite nonterminal_to_positive_to_nonterminal\n               | _ => tauto\n               | _ => assumption\n               | _ => progress subst\n               | _ => progress unfold lookup_state, PositiveMapExtensions.find_default, state, option_map, option_rect in *\n               | [ H : ?A -> ?B, H' : ?A |- _ ]\n                 => specialize (H H')\n               | [ H : is_true true -> _ |- _ ] => specialize (H eq_refl)\n               | [ |- is_true true ] => reflexivity\n               | [ |- is_true false ] => exfalso\n               | [ |- ?P ?nt (_ ⊔ _) ] => apply P_lub\n               | _ => rewrite top_lub_l\n               | [ H : Some _ = Some _ |- _ ] => inversion H; clear H\n               | [ H : forall nt : default_nonterminal_carrierT, _ |- _ ]\n                 => repeat match goal with\n                           | [ nt' : default_nonterminal_carrierT |- _ ]\n                             => unique pose proof (H nt')\n                           | [ H' : context[is_valid_nonterminal _ ?nt'] |- _ ]\n                             => unique pose proof (H nt')\n                           | [ |- context[is_valid_nonterminal _ ?nt'] ]\n                             => unique pose proof (H nt')\n                           end;\n                      clear H\n               | [ H : forall a b, is_true (is_valid_nonterminal ?ls ?nt) -> _ |- _ ]\n                 => destruct (is_valid_nonterminal ls nt) eqn:?\n               | [ P_lub : forall a b, _ -> _ -> _ -> ?P ?nt (_ ⊔ _) |- ?P ?nt (_ ⊔ _) ] => apply P_lu\n               | [ H : context[match ?e with _ => _ end] |- _ ] => destruct e eqn:?\n               | [ |- context[match ?e with _ => _ end] ] => destruct e eqn:?\n               end. }\n  Qed.\n\n  Lemma pre_Fix_grammar_fixedpoint_correct_stronger\n        (P : default_nonterminal_carrierT -> state gdata -> Type)\n        (Pbot : forall nt, is_true (is_valid_nonterminal initial_nonterminals_data nt)\n                            -> P nt ⊥)\n        (Ptop : forall nt, is_valid_nonterminal initial_nonterminals_data nt = false\n                           -> P nt ⊤)\n        (IH : forall nt st,\n            (forall nt', is_valid_nonterminal initial_nonterminals_data nt' = false -> st nt' = ⊤)\n            -> (forall nt', P nt' (st nt'))\n            -> is_true (is_valid_nonterminal initial_nonterminals_data nt)\n            -> P nt (st nt ⊔ step_constraints gdata st nt (st nt)))\n    : forall nt, P nt (lookup_state (pre_Fix_grammar gdata initial_nonterminals_data) nt).\n  Proof.\n    intro nt.\n    destruct (is_valid_nonterminal (@initial_nonterminals_data _ (@rdp_list_predata _ G)) nt) eqn:Hvalid.\n    { apply pre_Fix_grammar_fixedpoint_correct_stronger'; eauto with nocore.\n      { intros nt'' st'' Hfalse H''.\n        move IH at bottom.\n        specialize (IH nt'').\n        let v := match type of IH with context[is_true ?v] => v end in\n        destruct v eqn:Hvalid'; eauto; [].\n        { rewrite Hfalse by assumption.\n          rewrite top_lub_l.\n          eauto. } } }\n    { simpl rewrite lookup_state_invalid_pre_Fix_grammar; [ | assumption ]. eauto with nocore. }\n  Qed.\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/Correct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2645403668481784}}
{"text": "(* -*- coding:utf-8 -*- *)\n(************************************************************************)\n(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)\n(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2011     *)\n(*   \\VV/  **************************************************************)\n(*    //   *      This file is distributed under the terms of the       *)\n(*         *       GNU Lesser General Public License Version 2.1        *)\n(************************************************************************)\n\n(* Logic *)\nNotation \"∀  x .. y , P\" := (forall x, .. (forall y, P) ..)\n  (at level 200, x binder, y binder, right associativity) : type_scope.\nNotation \"∃  x .. y , P\" := (exists x, .. (exists y, P) ..)\n  (at level 200, x binder, y binder, right associativity) : type_scope.\n\nNotation \"x ∨ y\" := (x \\/ y) (at level 85, right associativity) : type_scope.\nNotation \"x ∧ y\" := (x /\\ y) (at level 80, right associativity) : type_scope.\nNotation \"x → y\" := (x -> y) (at level 90, right associativity): type_scope.\nNotation \"x ↔ y\" := (x <-> y) (at level 95, no associativity): type_scope.\nNotation \"¬ x\" := (~x) (at level 75, right associativity) : type_scope.\nNotation \"x ≠ y\" := (x <> y) (at level 70) : type_scope.\n\n(* Abstraction *)\nNotation \"'λ'  x .. y , t\" := (fun x => .. (fun y => t) ..)\n  (at level 200, x binder, y binder, right associativity).\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/coq/coq-8.3pl5-foundations/theories/Unicode/Utf8_core.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2644753784852913}}
{"text": "Require Import GHC.Types.\n\nDefinition arrow  := (fun (x y :Type) => x -> y).\n\nDefinition seq {A} {B} (a : A) (b:B) := b.\n\n(* Coq has no levity polymorphism, so map everything to Type *)\nDefinition TYPE (_ : RuntimeRep) := Type.\n\n\n(* Unpeel class: A directed form of Coercible, where a is the newtype type,\n   and b the base type *)\nClass Unpeel a b :=\n  { unpeel : a -> b\n  ; repeel : b -> a }.\n\n#[export] Instance Unpeel_refl a : Unpeel a a := Build_Unpeel _ _ (fun x => x) (fun x => x).\n\n#[export] Instance Unpeel_arrow\n  a b c d\n  `{Unpeel b a}\n  `{Unpeel c d}\n  : Unpeel (b -> c) (a -> d) :=\n  { unpeel f x := unpeel (f (repeel x))\n  ; repeel f x := repeel (f (unpeel x))\n  }.\n\n#[export] Instance Unpeel_pair\n  a b c d\n  `{Unpeel a b}\n  `{Unpeel c d}\n  : Unpeel (a * c) (b * d) :=\n  { unpeel '(x,y) := (unpeel x, unpeel y)\n  ; repeel '(x,y) := (repeel x, repeel y)\n  }.\n\n\nRequire Coq.Lists.List.\n#[export] Instance Unpeel_list a b\n   `{Unpeel a b} : Unpeel (list a) (list b) :=\n  { unpeel x := Coq.Lists.List.map unpeel x\n  ; repeel x := Coq.Lists.List.map repeel x\n  }.\n\nClass Coercible a b := { coerce : a -> b }.\n\n#[export] Instance Coercible_Unpeel\n  a b c\n  {U1 : Unpeel a c}\n  {U2 : Unpeel b c}\n  : Coercible a b :=\n  { coerce x := @repeel b c U2 (@unpeel a c U1 x) }.\n", "meta": {"author": "lastland", "repo": "ProgramAdverbs", "sha": "1f8086d379d1fc0eb896539adae66cd9f7d8ec04", "save_path": "github-repos/coq/lastland-ProgramAdverbs", "path": "github-repos/coq/lastland-ProgramAdverbs/ProgramAdverbs-1f8086d379d1fc0eb896539adae66cd9f7d8ec04/GHC/Prim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2644753784852913}}
{"text": "From CasperCBC Require Import Lib.Preamble VLSM.Common VLSM.Composition VLSM.Decisions VLSM.ProjectionTraces.\n\n(** * VLSM Common Futures and Decision Consistency *)\n\n(**\nIn this module we provide a definition for the [HasCommonFuturesEstimates]\nproperty and then we show that a VLSM equiped with this property\nhas [final_and_consistent] decisions.\n*)\n\nSection CommonFutures.\n\nContext\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 := composite_vlsm IM constraint)\n  {CV : consensus_values}\n  (ID : forall i : index, vdecision (IM i))\n  (IE : forall i : index, Estimator (vstate (IM i)) C)\n  (DE : forall i : index, composite_projection_decision_estimator_property IM constraint ID IE i)\n  .\n\n(**\nLet us fix an indexed set of VLSMs <<IM>> and their composition <<X>> using <<constraint>>.\nFor each component of index i, let <<IE i>> be an [Estimator] for Xi and let\n<<ID i>> be a [decision] function for Xi, linked together by the\n[decision_estimator_property].\n\n*)\n\n(** ** Common futures estimates definition *)\n\n(**\nWe say that the composition <<X>> [HasCommonFutureEstimates] if there\nexists a function [union] taking composite states to composit states\nsuch that for each composite state <<s>>, its [union_is_reachable] from <<s>>,\nand the [union_has_consistent_estimators]; i.e.,\nall components yields the same estimates.\n*)\n\nClass HasCommonFutureEstimates :=\n  { union : vstate X -> vstate X\n  ; union_is_reachable\n    : forall\n      (s : vstate X)\n      (Hps : protocol_state_prop X s)\n      , in_futures X s (union s)\n  ; union_has_consistent_estimators\n    : forall\n      (s : vstate X)\n      (Hps : protocol_state_prop X s)\n      (i j : index)\n      (c : C),\n      estimator (union s i) c <-> estimator (union s j) c\n  }.\n\n(** ** Final and consistent decisions\n\nIf a [VLSM] composition <<X>> [HasCommonFuturesEstimates] and its component\ndecisions are linked with the corresponding estimators through the\n[decision_estimator_property], then <<X>> has [final_and_consistent]\ndecisions.\n*)\n\n\nLemma consistent_estimator_decisions\n  (HCFE : HasCommonFutureEstimates)\n  : final_and_consistent IM constraint ID.\nProof.\n  unfold final_and_consistent; intros.\n  specialize (in_futures_protocol_snd X s1 s2 Hfuture); intros Hps2.\n  specialize (union_is_reachable s2 Hps2); intro HcmnFuture.\n  specialize (union_has_consistent_estimators s2 Hps2 j k)\n  ; intros HconsEst.\n  specialize (in_futures_trans X s1 s2 (union s2) Hfuture HcmnFuture)\n  ; intro HcmnFuture1.\n  specialize (in_futures_projection IM constraint j s1 (union s2) HcmnFuture1)\n  ; intros HFuture1.\n  assert (Dej := DE j).\n  specialize (Dej (s1 j) c1 HDecided1 (union s2 j) HFuture1).\n  specialize (in_futures_projection IM constraint k s2 (union s2) HcmnFuture)\n  ; intros HFuture2.\n  assert (Dek := DE k).\n  specialize (Dek (s2 k) c2 HDecided2 (union s2 k) HFuture2).\n  specialize (estimator_total (union s2 j)); intros [c Hc].\n  specialize (HconsEst c).\n  specialize (Dej c Hc).\n  apply HconsEst in Hc.\n  specialize (Dek c Hc).\n  subst.\n  reflexivity.\nQed.\n\nEnd CommonFutures.\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/CommonFutures.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784220301064, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2644753784852912}}
{"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_set_flag.\nRequire Import RVIC2.LowSpecs.rvic_set_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       atomic_bit_set_release_64_spec\n       get_bitmap_loc_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_set_flag_spec_exists:\n    forall habd habd'  labd intid bitmap\n           (Hspec: rvic_set_flag_spec intid bitmap habd = Some habd')\n            (Hrel: relate_RData habd labd),\n    exists labd', rvic_set_flag_spec0 intid bitmap labd = Some labd' /\\ relate_RData habd' labd'.\n  Proof.\n    intros. inv Hrel. destruct bitmap.\n    unfold rvic_set_flag_spec, rvic_set_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_set_flag.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2644753717647745}}
{"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.Specs.data_destroy1.\nRequire Import TableDataOpsRef1.LowSpecs.data_destroy1.\nRequire Import TableDataOpsRef1.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    .\n\n  Lemma data_destroy1_spec_exists:\n    forall habd habd'  labd g_rd map_addr res\n      (Hspec: data_destroy1_spec g_rd map_addr habd = Some (habd', res))\n      (Hrel: relate_RData habd labd),\n    exists labd', data_destroy1_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_destroy1_spec, data_destroy1_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 C3; 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 1) :: oracle habd (log habd) ++ log habd)) s1 = Some s1).\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; simpl).\n      rewrite_oracle_rel rel_oracle C; simpl in *.\n      repeat (grewrite; try simpl_htarget; simpl).\n      rewrite_oracle_rel rel_oracle C2; 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    - 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 C; 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 1) :: oracle habd (log habd) ++ log habd)) s0 = Some s0).\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; simpl).\n      rewrite_oracle_rel rel_oracle C2; simpl in *.\n      repeat (grewrite; try simpl_htarget; simpl).\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).\n      assert(Hwalk: repl habd (oracle habd\n                                      (EVT CPU_ID (RTT_WALK (g_rtt (gnorm (gs (share habd)) @ z)) z0 1) :: oracle habd (log habd) ++ log habd)) s = Some s).\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; 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 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/TableDataOpsRef1/RefProof/data_destroy1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2644753717647745}}
{"text": "Require Export MinBFTprops2.\nRequire Export MinBFTsame.\nRequire Export MinBFTass_mon.\nRequire Export MinBFTass_tlearn.\nRequire Export MinBFTass_uniq.\nRequire Export MinBFTass_new2.\nRequire Export MinBFTass_tknew.\nRequire Export ComponentAxiom.\n\n\nSection MinBFTagreement.\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 agreement :\n    forall (eo : EventOrdering) (e1 e2 : Event) r1 r2 i l1 l2,\n      AXIOM_authenticated_messages_were_sent_or_byz eo MinBFTsys\n      -> In (send_accept (accept r1 i) l1) (M_output_sys_on_event MinBFTsys e1)\n      -> In (send_accept (accept r2 i) l2) (M_output_sys_on_event MinBFTsys e2)\n      -> r1 = r2.\n  Proof.\n    introv sendbyz send1 send2.\n    applydup in_output_implies_is_replica in send1 as isrep1.\n    applydup in_output_implies_is_replica in send2 as isrep2.\n\n    unfold is_replica in *.\n    destruct isrep1 as [i1 isrep1].\n    destruct isrep2 as [i2 isrep2].\n    unfold M_output_sys_on_event in send1; rewrite isrep1 in send1; simpl in send1.\n    unfold M_output_sys_on_event in send2; rewrite isrep2 in send2; simpl in send2.\n\n    applydup @accepted_counter_if_know_UI_primary in send1 as statea.\n    applydup @accepted_counter_if_know_UI_primary in send2 as stateb.\n    exrepnd.\n\n    applydup preserves_view_init_ls in statea0 as eqv1; auto.\n    applydup preserves_view_init_ls in stateb0 as eqv2; auto.\n    rewrite eqv1, eqv2 in *.\n    clear eqv1 eqv2.\n\n    applydup M_run_ls_on_event_MinBFT_to_components in statea0; repnd; auto;[].\n    applydup M_run_ls_on_event_MinBFT_to_components in stateb0; repnd; auto;[].\n\n    pose proof (request_data_was_verified e1 s4 s3 initial_view r1 ui0) as ka.\n    repeat (autodimp ka hyp); try (complete (eexists; eauto)); exrepnd;[].\n\n    pose proof (request_data_was_verified e2 s2 s1 initial_view r2 ui) as kb.\n    repeat (autodimp kb hyp); try (complete (eexists; eauto)); exrepnd;[].\n\n    assert (ex_node_e e1) as ex1 by (unfold ex_node_e; allrw; simpl; eauto).\n    assert (ex_node_e e2) as ex2 by (unfold ex_node_e; allrw; simpl; eauto).\n\n    pose proof (DERIVED_RULE_trusted_knowledge_unique3_true\n                  (MkEventN e1 ex1) (MkEventN e2 ex2) (MkEventN e2 ex2)\n                  [] []\n                  (MinBFTprimary initial_view)\n                  ui0\n                  ui\n                  (ui2counter ui0)\n                  (ui2counter ui)\n                  (minbft_data_rdata (request_data initial_view r1 ui0))\n                  (minbft_data_rdata (request_data initial_view r2 ui))) as knc.\n    unfold rule_true in knc; simpl in knc.\n    repeat (autodimp knc hyp); eauto 2 with minbft;[|].\n\n    { Opaque ASSUMPTION_trusted_learns_if_gen.\n      Opaque ASSUMPTION_trusted_knew_or_learns_or_gen.\n      Opaque ASSUMPTION_monotonicity.\n      Opaque ASSUMPTION_generates_new.\n      Opaque ASSUMPTION_disseminate_unique.\n      introv vt vd vc vn xx yy zz.\n      induction es using Vector.caseS'; simpl in *.\n      clear vt vd vc vn es.\n      repndors; subst; unfold seq_concl, seq_event in *;\n        simpl in *; introv; simpl in *; tcsp;\n          try (complete (unfold data_is_owned_by; minbft_simp; allrw; auto));\n          try (complete (apply ASSUMPTION_trusted_learns_if_gen_true; auto; destruct h0; auto));\n          try (complete (apply ASSUMPTION_trusted_knew_or_learns_or_gen_true; auto; destruct h0; auto));\n          try (complete (apply ASSUMPTION_monotonicity_true; auto; destruct h0; auto));\n          try (complete (apply ASSUMPTION_disseminate_unique_true; auto; destruct h0; auto));\n          try (complete (apply ASSUMPTION_generates_new_true; auto; destruct h0; auto));\n          try (complete (eexists; simpl;allrw; simpl; eauto));\n          try (complete (repeat (eexists; dands; eauto)));\n          try (complete (allrw; auto));\n          try (complete (rewrite (state_usig_same_keys e1) in ka; auto; rewrite isrep1 in ka;\n                         unfold generated_for; simpl; dands; auto; introv xx; ginv; eexists; eauto));\n          try (complete (rewrite (state_usig_same_keys e2) in kb; auto; rewrite isrep2 in kb;\n                         unfold generated_for; simpl; dands; auto; introv xx; ginv; eexists; eauto)). }\n\n    unfold sequent_true in knc; simpl in knc; repeat (autodimp knc hyp); tcsp;[].\n    inversion knc; subst; subst; auto.\n  Qed.\n\nEnd MinBFTagreement.\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/MinBFTagreement2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2644155549105461}}
{"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.\nFrom Velus Require Import Transcription.Tr.\n\nFrom Velus Require Import CoreExpr.CEIsFree.\nFrom Velus Require Import CoreExpr.CEClocking.\nFrom Velus Require Import Lustre.LClocking.\nFrom Velus Require Import NLustre.IsDefined.\nFrom Velus Require Import NLustre.IsFree.\nFrom Velus Require Import NLustre.Memories.\nFrom Velus Require Import NLustre.NLOrdered.\nFrom Velus Require Import NLustre.NLClocking.\n\nFrom Coq Require Import String.\nFrom Coq Require Import Permutation.\n\nFrom Coq Require Import List.\nImport List.ListNotations.\n\nFrom compcert Require Import common.Errors.\nOpen Scope error_monad_scope.\n\n(** * Clocking Preservation for Transcription *)\n\n\nModule Type TRCLOCKING\n       (Import Ids  : IDS)\n       (Import Op   : OPERATORS)\n       (Import OpAux: OPERATORS_AUX  Op)\n       (L           : LSYNTAX    Ids Op)\n       (LC          : LCLOCKING  Ids Op L)\n       (Import CE   : CESYNTAX       Op)\n       (NL          : NLSYNTAX   Ids Op CE)\n       (Import Ord  : NLORDERED  Ids Op CE NL)\n       (Import Mem  : MEMORIES   Ids Op CE NL)\n       (Import IsD  : ISDEFINED  Ids Op CE NL Mem)\n       (Import CEIsF: CEISFREE   Ids Op CE)\n       (Import IsF  : ISFREE     Ids Op CE NL CEIsF)\n       (Import CEClo: CECLOCKING Ids Op CE)\n       (NLC         : NLCLOCKING Ids Op CE NL Ord Mem IsD CEIsF IsF CEClo)\n       (Import TR   : TR Ids Op OpAux L CE NL).\n\n  Lemma envs_eq_in :\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 Hin.\n    cases_eqn HH. inv Hin. apply Heq; eauto.\n  Qed.\n\n  Lemma find_clock_det :\n    forall env x ck ck',\n      find_clock env x = OK ck ->\n      find_clock env x = OK ck' ->\n      ck = ck'.\n  Proof.\n    unfold find_clock. intros. cases. congruence.\n  Qed.\n\n  Lemma wc_lexp :\n    forall G vars e e',\n      to_lexp e = OK e' ->\n      LC.wc_exp G vars e ->\n      (exists ck,\n          L.clockof e = [ck]\n          /\\ wc_exp vars e' ck).\n  Proof.\n    intros * Hto Hwc. revert dependent e'.\n    induction e using L.exp_ind2; intros; inv Hto; inv Hwc.\n    - exists Cbase. split; constructor.\n    - simpl. unfold L.clock_of_nclock, stripname. simpl. esplit; split; eauto.\n      monadInv H0. now constructor.\n    - simpl. unfold L.clock_of_nclock, stripname. simpl. esplit; split; eauto.\n      monadInv H0. now constructor.\n    - simpl. unfold L.clock_of_nclock, stripname. simpl. esplit; split; eauto.\n      monadInv H0. constructor. apply IHe in EQ as (?&?&?); eauto.\n      congruence.\n    - simpl. unfold L.clock_of_nclock, stripname. simpl. esplit; split; eauto.\n      monadInv H0. constructor.\n      + apply IHe1 in EQ as (?&?&?); eauto. congruence.\n      + apply IHe2 in EQ1 as (?&?&?); eauto. congruence.\n    - cases.\n      simpl. unfold L.clock_of_nclock, stripname. simpl. esplit; split; eauto.\n      take (_ = OK e') and monadInv it. simpl_Foralls.\n      constructor; auto.\n      take (_ -> _) and apply it in EQ as (?& Heq &?); auto.\n      unfold L.clocksof in *. simpl in *. rewrite app_nil_r in *.\n      rewrite Heq in *. simpl_Foralls. congruence.\n  Qed.\n\n  Lemma wc_exp_cexp :\n    forall vars e ck,\n      wc_exp vars e ck ->\n      wc_cexp vars (Eexp e) ck.\n  Proof.\n    now constructor.\n  Qed.\n\n  Lemma wc_cexp :\n    forall G vars e e',\n      to_cexp e = OK e' ->\n      LC.wc_exp G vars e ->\n      (exists ck,\n          L.clockof e = [ck]\n          /\\ wc_cexp vars e' ck).\n  Proof.\n    intros * Hto Hwc. revert dependent e'.\n    induction e using L.exp_ind2; intros;\n      unfold to_cexp in Hto; try monadInv Hto;\n        repeat (take (to_lexp _ = _) and eapply wc_lexp in it as (?&?&?);\n                eauto); eauto using wc_exp_cexp.\n    - cases. monadInv Hto.\n      simpl_Foralls.\n      simpl. unfold L.clock_of_nclock, stripname. simpl. esplit; split; eauto.\n      inv Hwc. simpl_Foralls. constructor; simpl; auto.\n      + take (_ -> _) and apply it in EQ as (?& Heq &?); auto.\n        unfold L.clocksof in *. simpl in *. rewrite app_nil_r in *.\n        rewrite Heq in *. simpl_Foralls. congruence.\n      + take (LC.wc_exp _ _ e0 -> _) and apply it in EQ1 as (?& Heq &?); auto.\n        unfold L.clocksof in *. simpl in *. rewrite app_nil_r in *.\n        rewrite Heq in *. simpl_Foralls. congruence.\n    - cases. monadInv Hto.\n      simpl_Foralls.\n      simpl. unfold L.clock_of_nclock, stripname. simpl. esplit; split; eauto.\n      inv Hwc. simpl_Foralls. constructor; simpl; auto.\n      + eapply wc_lexp in EQ as (?& Heq &?); eauto. congruence.\n      + take (_ -> _) and apply it in EQ1 as (?& Heq &?); auto.\n        unfold L.clocksof in *. simpl in *. rewrite app_nil_r in *.\n        rewrite Heq in *. simpl_Foralls. congruence.\n      + take (LC.wc_exp _ _ e1 -> _) and apply it in EQ0 as (?& Heq &?); auto.\n        unfold L.clocksof in *. simpl in *. rewrite app_nil_r in *.\n        rewrite Heq in *. simpl_Foralls. congruence.\n  Qed.\n\n  (* correctness of substition extension *)\n  Lemma instck_sub_ext :\n    forall bck sub ck ck' P,\n      instck bck sub ck = Some ck' ->\n      instck bck (fun x => match sub x with\n                        | None => P x\n                        | s => s\n                        end) ck = Some ck'.\n  Proof.\n    intros * Hinst.\n    revert dependent ck'. induction ck; intros; auto.\n    inv Hinst.\n    destruct (instck bck sub ck) eqn:?; try discriminate.\n    destruct (sub i) eqn:Hs; try discriminate.\n    specialize (IHck c eq_refl).\n    simpl. now rewrite IHck, Hs.\n  Qed.\n\n  Lemma wc_equation :\n    forall G Hprefs P env envo vars e e',\n      to_global G Hprefs = OK P ->\n      to_equation env envo e = OK e' ->\n      envs_eq env vars ->\n      LC.wc_global G ->\n      LC.wc_equation G vars e ->\n      NLC.wc_equation P vars e'.\n  Proof.\n    intros ?????? [xs [|? []]] e' Hg Htr Henvs Hwcg (Hwc & Hlift & Hf2);\n      try (inv Htr; cases; discriminate).\n    destruct e; simpl in *; simpl_Foralls; try monadInv Htr.\n    - constructor; eauto using envs_eq_in.\n      eapply envs_eq_find in Henvs; eauto.\n      pose proof (find_clock_det _ _ _ _ EQ Henvs) as ->.\n      repeat constructor.\n    - constructor; eauto using envs_eq_in.\n      monadInv EQ1. destruct a. inv EQ0.\n      unfold L.clock_of_nclock, stripname in *; simpl in *.\n      take (LC.wc_exp _ _ _) and inv it; simpl in *; subst.\n      + eapply envs_eq_find with (x:=i) in Henvs; eauto.\n        rewrite EQ in Henvs; inv Henvs.\n        now repeat constructor.\n      + eapply envs_eq_find with (x:=x) in Henvs; eauto.\n        rewrite EQ in Henvs; inv Henvs.\n        now repeat constructor.\n    - constructor; eauto using envs_eq_in. destruct a.\n      monadInv EQ1. monadInv EQ0.\n      take (LC.wc_exp _ _ _) and inv it.\n      eapply wc_lexp in EQ1 as (?&?&?); eauto.\n      unfold L.clock_of_nclock, stripname in *. simpl in *.\n      eapply envs_eq_find in Henvs; eauto.\n      pose proof (find_clock_det _ _ _ _ EQ Henvs) as ->.\n      repeat constructor.\n      congruence.\n    - constructor; eauto using envs_eq_in. destruct a.\n      monadInv EQ1. monadInv EQ0.\n      take (LC.wc_exp _ _ _) and inv it.\n      eapply wc_lexp in EQ0 as (?&?&?); eauto.\n      eapply wc_lexp in EQ1 as (?&?&?); eauto.\n      unfold L.clock_of_nclock, stripname in *. simpl in *.\n      eapply envs_eq_find in Henvs; eauto.\n      pose proof (find_clock_det _ _ _ _ EQ Henvs) as ->.\n      repeat constructor; congruence.\n    - cases; try monadInv Htr.\n      constructor; eauto using envs_eq_in.\n      take (LC.wc_exp _ _ _) and inv it. simpl_Foralls.\n      eapply wc_lexp in EQ2 as (?& Heq &?); eauto.\n      take (Forall2 eq _ _) and rewrite Forall2_eq in it.\n      unfold L.clocksof in it. simpl in *. rewrite app_nil_r in *.\n      rewrite Heq in it. rewrite it in *.\n      eapply envs_eq_find in Henvs; eauto.\n      pose proof (find_clock_det _ _ _ _ EQ0 Henvs) as ->.\n      congruence.\n    - cases; try monadInv Htr; monadInv EQ1; monadInv EQ0.\n    - cases; try monadInv Htr; monadInv EQ1; monadInv EQ0.\n      constructor; eauto using envs_eq_in. constructor.\n      take (LC.wc_exp _ _ _) and inv it. simpl_Foralls.\n      eapply wc_lexp in EQ1 as (?& Heq &?); eauto.\n      unfold L.clock_of_nclock, stripname in *. simpl in *.\n      eapply envs_eq_find in Henvs; eauto.\n      pose proof (find_clock_det _ _ _ _ EQ Henvs) as ->.\n      constructor; auto.\n      rewrite app_nil_r in *.\n      take (Forall (eq _) _) and rewrite Heq in it. now inv it.\n    - cases; try monadInv Htr; monadInv EQ1.\n      constructor; eauto using envs_eq_in.\n      take (LC.wc_exp _ _ _) and inv it. simpl_Foralls.\n      unfold L.clock_of_nclock, stripname in *. simpl in *. rewrite app_nil_r in *.\n      eapply envs_eq_find in Henvs; eauto.\n      pose proof (find_clock_det _ _ _ _ EQ Henvs) as ->.\n      constructor; auto.\n      + eapply wc_cexp in EQ0 as (?& Heq &?); eauto.\n        rewrite Heq in *. now simpl_Foralls.\n      + eapply wc_cexp in EQ1 as (?& Heq &?); eauto.\n        rewrite Heq in *. now simpl_Foralls.\n    - cases; try monadInv Htr; monadInv EQ1.\n      constructor; eauto using envs_eq_in.\n      take (LC.wc_exp _ _ _) and inv it. simpl_Foralls.\n      unfold L.clock_of_nclock, stripname in *. simpl in *. rewrite app_nil_r in *.\n      eapply envs_eq_find in Henvs; eauto.\n      pose proof (find_clock_det _ _ _ _ EQ Henvs) as ->.\n      constructor; auto.\n      + eapply wc_lexp in EQ0 as (?& Heq &?); eauto. congruence.\n      + eapply wc_cexp in EQ1 as (?& Heq &?); eauto.\n        rewrite Heq in *. now simpl_Foralls.\n      + eapply wc_cexp in EQ2 as (?& Heq &?); eauto.\n        rewrite Heq in *. now simpl_Foralls.\n    - cases; monadInv Htr;\n        take (LC.wc_exp _ _ _) and inversion_clear it\n        as [| | | | | | | | | |???? bck sub Wce ? WIi WIo|?????? bck sub Wce ? WIi WIo];\n        eapply find_node_global in Hg as (n' & Hpref & Hfind & Hton); eauto;\n          assert (find_base_clock (L.clocksof l) = bck) as ->\n            by (take (L.find_node _ _ = Some n) and\n                     pose proof (LC.wc_find_node _ _ n Hwcg it) as (?& (Wcin &?));\n                apply find_base_clock_bck;\n                [rewrite L.clocksof_nclocksof; eapply LC.WellInstantiated_bck; eauto;\n                 unfold idck; rewrite map_length; exact (L.n_ingt0 n)\n                | apply LC.WellInstantiated_parent in WIi;\n                  rewrite L.clocksof_nclocksof, Forall_map;\n                  eapply Forall_impl; eauto; now simpl]).\n      + econstructor; eauto; try discriminate;\n          rewrite app_nil_r in *.\n        (* We can't use [sub] directly because some variables\n           in the left side of the equation may have no image bu [sub].\n           -> see LClocking.wc_equation *)\n        * instantiate (1 := fun x => match sub x with\n                                  | None => assoc_ident x (combine (L.idents (L.n_out n)) xs)\n                                  | s => s\n                                  end).\n          (* inputs *)\n          erewrite <- (to_node_in n n'); eauto.\n          apply mmap_inversion in EQ.\n          pose proof (L.n_nodup n) as Hdup.\n          remember (L.n_in n) as ins. clear Heqins.\n          revert dependent ins.\n          revert dependent x.\n          induction l as [| e].\n          { intros. inv EQ. simpl in WIi. inv WIi.\n            take ([] = _) and apply symmetry, map_eq_nil in it.\n            now subst. }\n          intros le Htr ins WIi.\n          inv Htr. simpl in WIi.\n          take (Forall _ (e::_)) and inv it.\n          take (to_lexp e = _) and pose proof it as Tolexp; eapply wc_lexp in it as (ck & Hck & Wce);\n            eauto.\n          rewrite L.clockof_nclockof in Hck.\n          destruct (L.nclockof e) as [|nc []] eqn:Hcke; simpl in *; inv Hck.\n          inversion WIi as [|???? Wi ? Hmap]. subst.\n          unfold idck in Hmap.\n          apply symmetry, map_cons'' in Hmap as ((?&(?&?))&?&?&?&?). subst.\n          unfold LC.WellInstantiated in Wi. destruct Wi; simpl in *.\n          constructor; eauto.\n          2:{ eapply IHl; eauto. now apply nodupmembers_cons in Hdup. }\n          split; simpl; eauto.\n          2:{ exists (stripname nc). split. apply Wce. auto using instck_sub_ext. }\n          simpl in *. take (sub _ = _) and rewrite it. destruct nc as (ck & []).\n          2:{ simpl.\n              rewrite assoc_ident_false. constructor.\n              apply nodupmembers_cons in Hdup as [Hin].\n              rewrite <- In_InMembers_combine. unfold L.idents. intro Hin'.\n              apply in_map_iff in Hin' as ((?&?)&?&?). simpl in *. subst.\n              eapply Hin, In_InMembers.\n              repeat rewrite in_app_iff. right; right; left; eauto.\n              apply Forall2_length in Hf2. apply Forall2_length in WIo.\n              unfold L.idents, idck in *. repeat rewrite map_length in *.\n              congruence.\n          }\n          simpl. destruct e; take (LC.wc_exp G vars _) and inv it;\n                   inv Hcke; inv Tolexp.\n          -- constructor.\n          -- destruct tys; take (map _ _ = [_]) and inv it.\n        * (* outputs *)\n          unfold idck in *.\n          erewrite <- (to_node_out n n'); eauto.\n          clear - Hlift Hf2 WIo.\n          apply Forall2_forall. split.\n          2:{ apply Forall2_length in Hlift. apply Forall2_length in WIo.\n              repeat rewrite map_length in *. congruence. }\n          intros (?&(?&?)) ? Hin. split.\n          -- destruct (sub i) eqn:Hsub.\n             apply Forall2_swap_args in Hlift.\n             pose proof (Forall2_trans_ex _ _ _ _ _ WIo Hlift) as Ho.\n             rewrite Forall2_map_1 in Ho.\n             eapply Forall2_In in Hin; eauto.\n             destruct Hin as (?&?&(Heq&?)&Hl). simpl in *.\n             rewrite Hsub in Heq. rewrite <- Heq in Hl. simpl in Hl.\n             now subst.\n             unfold L.idents. apply assoc_ident_true.\n             2:{ rewrite combine_map_fst, in_map_iff.\n                 esplit; split; eauto. now simpl. }\n             apply NoDup_NoDupMembers_combine.\n             pose proof (L.n_nodup n) as Hdup.\n             rewrite fst_NoDupMembers in Hdup. repeat rewrite map_app in Hdup.\n             eauto using NoDup_app_l, NoDup_app_r.\n          -- rewrite Forall2_map_2 in Hf2. rewrite Forall2_map_2 in WIo.\n             apply Forall2_swap_args in Hf2.\n             pose proof (Forall2_trans_ex _ _ _ _ _ WIo Hf2) as Ho.\n             rewrite Forall2_map_1 in Ho.\n             eapply Forall2_In in Hin; eauto.\n             destruct Hin as (?&?&(Heq&?)&Hl). simpl in *.\n             esplit; split; eauto.\n             eauto using instck_sub_ext.\n        * intros (y, cky) E; inv E.\n          take (LC.wc_exp _ _ _) and inv it; auto.\n\n      + econstructor; eauto; try discriminate;\n          rewrite app_nil_r in *.\n        (* We can't use [sub] directly because some variables\n           in the left side of the equation may have no image bu [sub].\n           -> see LClocking.wc_equation *)\n        * instantiate (1 := fun x => match sub x with\n                                  | None => assoc_ident x (combine (L.idents (L.n_out n)) xs)\n                                  | s => s\n                                  end).\n          (* inputs *)\n          erewrite <- (to_node_in n n'); eauto.\n          apply mmap_inversion in EQ.\n          pose proof (L.n_nodup n) as Hdup.\n          remember (L.n_in n) as ins. clear Heqins.\n          revert dependent ins.\n          revert dependent x.\n          induction l as [| e].\n          { intros. inv EQ. simpl in WIi. inv WIi.\n            take ([] = _) and apply symmetry, map_eq_nil in it.\n            now subst. }\n          intros le Htr ins WIi.\n          inv Htr. simpl in WIi.\n          take (Forall _ (e::_)) and inv it.\n          take (to_lexp e = _) and pose proof it as Tolexp; eapply wc_lexp in it as (ck & Hck & Wce);\n            eauto.\n          rewrite L.clockof_nclockof in Hck.\n          destruct (L.nclockof e) as [|nc []] eqn:Hcke; simpl in *; inv Hck.\n          inversion WIi as [|???? Wi ? Hmap]. subst.\n          unfold idck in Hmap.\n          apply symmetry, map_cons'' in Hmap as ((?&(?&?))&?&?&?&?). subst.\n          unfold LC.WellInstantiated in Wi. destruct Wi; simpl in *.\n          constructor; eauto.\n          2:{ eapply IHl; eauto. now apply nodupmembers_cons in Hdup. }\n          split; simpl; eauto.\n          2:{ exists (stripname nc). split. apply Wce. auto using instck_sub_ext. }\n          simpl in *. take (sub _ = _) and rewrite it. destruct nc as (ck & []).\n          2:{ simpl.\n              rewrite assoc_ident_false. constructor.\n              apply nodupmembers_cons in Hdup as [Hin].\n              rewrite <- In_InMembers_combine. unfold L.idents. intro Hin'.\n              apply in_map_iff in Hin' as ((?&?)&?&?). simpl in *. subst.\n              eapply Hin, In_InMembers.\n              repeat rewrite in_app_iff. right; right; left; eauto.\n              apply Forall2_length in Hf2. apply Forall2_length in WIo.\n              unfold L.idents, idck in *. repeat rewrite map_length in *.\n              congruence.\n          }\n          simpl. destruct e; take (LC.wc_exp G vars _) and inv it;\n                   inv Hcke; inv Tolexp.\n          -- constructor.\n          -- destruct tys; take (map _ _ = [_]) and inv it.\n        * (* outputs *)\n          unfold idck in *.\n          erewrite <- (to_node_out n n'); eauto.\n          clear - Hlift Hf2 WIo.\n          apply Forall2_forall. split.\n          2:{ apply Forall2_length in Hlift. apply Forall2_length in WIo.\n              repeat rewrite map_length in *. congruence. }\n          intros (?&(?&?)) ? Hin. split.\n          -- destruct (sub i) eqn:Hsub.\n             apply Forall2_swap_args in Hlift.\n             pose proof (Forall2_trans_ex _ _ _ _ _ WIo Hlift) as Ho.\n             rewrite Forall2_map_1 in Ho.\n             eapply Forall2_In in Hin; eauto.\n             destruct Hin as (?&?&(Heq&?)&Hl). simpl in *.\n             rewrite Hsub in Heq. rewrite <- Heq in Hl. simpl in Hl.\n             now subst.\n             unfold L.idents. apply assoc_ident_true.\n             2:{ rewrite combine_map_fst, in_map_iff.\n                 esplit; split; eauto. now simpl. }\n             apply NoDup_NoDupMembers_combine.\n             pose proof (L.n_nodup n) as Hdup.\n             rewrite fst_NoDupMembers in Hdup. repeat rewrite map_app in Hdup.\n             eauto using NoDup_app_l, NoDup_app_r.\n          -- rewrite Forall2_map_2 in Hf2. rewrite Forall2_map_2 in WIo.\n             apply Forall2_swap_args in Hf2.\n             pose proof (Forall2_trans_ex _ _ _ _ _ WIo Hf2) as Ho.\n             rewrite Forall2_map_1 in Ho.\n             eapply Forall2_In in Hin; eauto.\n             destruct Hin as (?&?&(Heq&?)&Hl). simpl in *.\n             esplit; split; eauto.\n             eauto using instck_sub_ext.\n  Qed.\n\n  Lemma wc_node :\n    forall G P n n' Hpref Hprefs,\n      to_node n Hpref = OK n' ->\n      to_global G Hprefs = OK P ->\n      LC.wc_global G ->\n      LC.wc_node G n ->\n      NLC.wc_node P n'.\n  Proof.\n    intros * Htn Hwcg Htg Hwc.\n    unfold NLC.wc_node.\n    erewrite <- (to_node_in n n'), <- (to_node_out n n'), <- (to_node_vars n n');\n      eauto.\n    inversion Hwc as (?&?&?& WCeq). repeat (split; try tauto).\n    now setoid_rewrite  Permutation_app_comm at 2.\n    unfold to_node in Htn. cases. inv Htn. simpl.\n    revert dependent x. induction (L.n_eqs n) as [| e]; intros * Hmmap.\n    now inv Hmmap. inv WCeq.\n    apply mmap_cons in Hmmap as (e' & es & -> & Htoeq & Hmmap).\n    constructor; eauto using wc_equation, envs_eq_node.\n  Qed.\n\n  Lemma wc_transcription :\n    forall G P Hprefs,\n      LC.wc_global G ->\n      to_global G Hprefs = OK P ->\n      NLC.wc_global P.\n  Proof.\n    induction G as [| n]. inversion 2. constructor.\n    intros * Hwt Htr. monadInv Htr.\n    inversion_clear Hwt as [|???? Hf ].\n    constructor; eauto using wc_node.\n  Qed.\n\nEnd TRCLOCKING.\n\nModule TrClockingFun\n       (Ids   : IDS)\n       (Op    : OPERATORS)\n       (OpAux : OPERATORS_AUX  Op)\n       (L     : LSYNTAX    Ids Op)\n       (LC    : LCLOCKING  Ids Op L)\n       (CE    : CESYNTAX       Op)\n       (NL    : NLSYNTAX   Ids Op CE)\n       (Ord   : NLORDERED  Ids Op CE NL)\n       (Mem   : MEMORIES   Ids Op CE NL)\n       (IsD   : ISDEFINED  Ids Op CE NL Mem)\n       (CEIsF : CEISFREE   Ids Op CE)\n       (IsF   : ISFREE     Ids Op CE NL CEIsF)\n       (CEClo : CECLOCKING Ids Op CE)\n       (NLC   : NLCLOCKING Ids Op CE NL Ord Mem IsD CEIsF IsF CEClo)\n       (TR    : TR Ids Op OpAux L CE NL)\n<: TRCLOCKING Ids Op OpAux L LC CE NL Ord Mem IsD CEIsF IsF CEClo NLC TR.\n  Include TRCLOCKING Ids Op OpAux L LC CE NL Ord Mem IsD CEIsF IsF CEClo NLC TR.\nEnd TrClockingFun.\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/TrClocking.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2644155549105461}}
{"text": "Theorem frame8TraceInd:\n                let u:= (c 0 3, (ub (c 0 3) pk (bk 5) (x3tt 0 1), TWO)) in\n                let u':= (c 1 3, (ub (c 1 3) pk (bk 5) (x3tt 1 0), TWO)) in\n                let v:= (c 1 4, (ub (c 1 4) pk (bk 6) (x3tt 0 1), TWO)) in\n                let v':= (c 0 4, (ub (c 0 4) pk (bk 6) (x3tt 1 0), TWO)) in\n                let u1 := (label (c 0 3) (x6t 0 1), (kc (nonce 3), THREE)) in\n                let v1:= (label (c 0 4) (x7t 0 1), (kc (nonce 4), THREE)) in\n                let u1' := (label (c 1 3) (x6t 1 0), (kc (nonce 3), THREE)) in\n                let v1' := (label (c 1 4) (x7t 1 0), (kc (nonce 4), THREE)) in \n   [msg A, msg B, msg M, msg C1, msg C2, msg C3, msg ONE, msg TWO, msg THREE, msg (vk 0), msg (vk 1), \n   msg (pke 2), bol (theta x1 A), msg (tr 0 0 3 5 9), bol (theta (x2t 0) B), msg (tr 1 1 4 6 10), \n   bol (to (x3tt 0 1)) #? A, bol (acpt 0 3 5 (x3tt 0 1)),\n   msg {u}_ 2 ^^ 11, bol (to (x4ttt 0 1)) #? B,\n   bol (acpt 1 4 6 (x3tt 0 1)), msg {v}_ 2 ^^ 12,\n   bol (to (x5t 0 1)) #? M, bol (tau 1 (x5t 0 1)) #? {u}_ 2 ^^ 11,\n   bol (tau 2 (x5t 0 1)) #? {v}_ 2 ^^ 12,\n   bol (!((tau 3 (x5t 0 1)) #? {u}_ 2 ^^ 11)) & (!((tau 3 (x5t 0 1)) #? {v}_ 2 ^^ 12)),\n   bol ((tau 3 u)#? TWO) & ((tau 3 v) #? TWO) & ((tau 3 (dec (tau 3 (x5t 0 1)) (ske 2))) #? TWO), msg (shufl ((tau 1 u), (tau 2 u)) ((tau 1 v), (tau 2 v)) ((tau 1 (dec (tau 3 (x5t 0 1)) (ske 2))),  (tau 2 (dec (tau 3 (x5t 0 1)) (ske 2))))), bol ((to (x6t 0 1)) #? A) & (distbb x6t 0 1), bol (acc1 0 1 3 5)& (bcheck (c 0 3) (x6t 0 1)), msg (e1 0 3 x6t 1 13), bol ((to (x7t 0 1)) #? B) & (distbb x7t 0 1), bol (acc2 0 1 4 6)& (bcheck (c 1 4) (x7t 0 1)), msg (e1 0 4 x7t 1 14),  bol (to (x8t 0 1)) #? M, bol (tau 1 (x8t 0 1)) #? {u1}_ 2 ^^ 11,\n   bol (tau 2 (x8t 0 1)) #? {v1}_ 2 ^^ 12,\n   bol (!((tau 3 (x8t 0 1)) #? {u1}_ 2 ^^ 11)) & (!((tau 3 (x8t 0 1)) #? {v1}_ 2 ^^ 12)), msg (If (let D := ((d 1 (x8t 0 1)), ((d 2 (x8t 0 1)), (d 3 (x8t 0 1)))) in\n                             let kOcc := (isin (bk 3) D) & (isin (bk 4) D) in\n                             let kdnOcc := !(isin (bk 3) D) or !(isin (bk 4) D) in\n                                   (mchecks x8t 0 1 THREE)& (kOcc or kdnOcc)) then  (shufl ((tau 1 u1), (tau 2 u1)) ((tau 1 v1), (tau 2 v1)) ((tau 1 (dec (tau 3 (x8t 0 1)) (ske 2))),  (tau 2 (dec (tau 3 (x8t 0 1)) (ske 2))))) else O) ] ~\n\n[msg A, msg B, msg M, msg C1, msg C2, msg C3, msg ONE, msg TWO, msg THREE, msg (vk 0), msg (vk 1), \n   msg (pke 2), bol (theta x1 A), msg (tr 0 1 3 5 9), bol (theta (x2t 1) B), msg (tr 1 0 4 6 10), \n   bol (to (x3tt 1 0)) #? A, bol (acpt 1 3 5 (x3tt 1 0)),\n   msg {u'}_2 ^^ 11, bol (to (x4ttt 1 0)) #? B,\n   bol (acpt 0 4 6 (x3tt 1 0)), msg {v'}_ 2 ^^ 12,\n   bol (to (x5t 1 0)) #? M, bol (tau 1 (x5t 1 0)) #? {u'}_ 2 ^^ 11,\n   bol (tau 2 (x5t 1 0)) #? {v'}_ 2 ^^ 12,\n   bol (!((tau 3 (x5t 1 0)) #? {u'}_ 2 ^^ 11)) & (! ((tau 3 (x5t 1 0)) #? {v'}_ 2 ^^ 12)),\n   bol ((tau 3 u')#? TWO) & ((tau 3 v') #? TWO) & ((tau 3 (dec (tau 3 (x5t 1 0)) (ske 2))) #? TWO), msg (shufl ((tau 1 u'), (tau 2 u')) ((tau 1 v'), (tau 2 v')) ((tau 1 (dec (tau 3 (x5t 1 0)) (ske 2))),  (tau 2 (dec (tau 3 (x5t 1 0)) (ske 2))))), bol ((to (x6t 1 0)) #? A) & (distbb x6t 1 0), bol (acc1 1 1 3 5)& (bcheck (c 1 3) (x6t 1 0)), msg (e1 1 3 x6t 0 13), bol ((to (x7t 1 0)) #? B) & (distbb x7t 1 0), bol (acc2 1 0 4 6)& (bcheck (c 0 4) (x7t 1 0)), msg (e1 1 4 x7t 0 14), bol (to (x5t 1 0)) #? M, bol (tau 1 (x8t 1 0)) #? {u1'}_ 2 ^^ 13,\n   bol (tau 2 (x8t 1 0)) #? {v1'}_ 2 ^^ 14,\n   bol (!((tau 3 (x8t 1 0)) #? {u1'}_ 2 ^^ 13)) & (! ((tau 3 (x8t 1 0)) #? {v1'}_ 2 ^^ 14)),   msg (If \n   (let D := ((d 1 (x8t 1 0)), ((d 2 (x8t 1 0)), (d 3 (x8t 1 0)))) in\n                             let kOcc := (isin (bk 3) D) & (isin (bk 4) D) in\n                             let kdnOcc := !(isin (bk 3) D) or !(isin (bk 4) D) in\n                             (mchecks x8t 1 0 THREE)& (kOcc or kdnOcc)) then (shufl ((tau 1 u1'), (tau 2 u1')) ((tau 1 v1'), (tau 2 v1')) ((tau 1 (dec (tau 3 (x8t 1 0)) (ske 2))),  (tau 2 (dec (tau 3 (x8t 1 0)) (ske 2))))) else O)].", "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/newgoal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2644155486683555}}
{"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 Aes.Sbox.\n\nImport VectorNotations.\nImport KappaNotation.\nOpen Scope kind_scope.\n\nProgram Definition aes_key_expand\n  (sbox_impl: SboxImpl)\n  : <<\n   (* Bit (1* cfg_valid_i *1) *) (*cfg_valid_i is used for gating assertions only. *)\n      Bit (* op_i *)\n    , Bit (* step_i *)\n    , Bit (* clear_i *)\n    , Vector Bit 4 (* round_i *)\n    (* , Vector Bit 4 (1* key_len_e *1) *)\n    , Vector (Vector (Vector Bit 8) 4) 8 (* input key *)\n    , Unit\n    >> ~> << Vector (Vector (Vector Bit 8) 4) 8>> :=\n  <[\\op_i step_i clear_i round_i key_i =>\n    (* if (key_len_i == AES_256 && rnd[0] == 1'b0) begin\n    use_rcon = 1'b0;\n    end *)\n    let use_rcon = round_i[#0] in\n    let clear_i =\n      round_i == #0 in\n\n    (* rcon_d = (op_i == CIPH_FWD) ? aes_mul2(rcon_q) :\n                (op_i == CIPH_INV) ? aes_div2(rcon_q) : 8'h01; *)\n    letrec rcon = delay (\n      if clear_i\n      then\n        if op_i == !CIPH_FWD\n        then #1\n        else #64\n      else if use_rcon\n      then\n        if op_i == !CIPH_FWD\n        then !aes_mul2 rcon\n        else !aes_div2 rcon\n      else\n        rcon\n        ) in\n\n    (* AES_256: begin\n      unique case (op_i)\n        CIPH_FWD: rot_word_in = key_i[7];\n        CIPH_INV: rot_word_in = key_i[3];\n        default:  rot_word_in = key_i[7]; *)\n    let rot_word_in =\n      if op_i == !CIPH_FWD\n      then key_i[#7]\n      else key_i[#3] in\n\n    (* assign rot_word_out = aes_circ_byte_shift(rot_word_in, 2'h3); *)\n    let rot_word_out = !aes_circ_byte_shift rot_word_in #3 in\n\n    (* assign sub_word_in = use_rot_word ? rot_word_out : rot_word_in; *)\n    let sub_word_in =\n      if use_rcon (* for AES_256 use_rcon == use_rot_word *)\n      then rot_word_out\n      else rot_word_in in\n\n    let sub_word_out = !(map <[!(aes_sbox sbox_impl) !CIPH_FWD]>) sub_word_in in\n    let sub_word_out_flat = !(flatten (n:=4)) sub_word_out in\n\n    (* assign rcon_add_in  = sub_word_out[7:0]; *)\n    let rcon_add_in = sub_word_out_flat[:7:0] in\n    (* assign rcon_add_out = rcon_add_in ^ rcon_q; *)\n    let rcon_add_out = rcon_add_in ^ rcon in\n    (* assign rcon_added   = {sub_word_out[31:8], rcon_add_out}; *)\n    let rcon_added   = concat rcon_add_out sub_word_out_flat[:31:8] in\n\n    (* // Mux output coming from Rcon & SubWord\n    assign irregular = use_rcon ? rcon_added : sub_word_out; *)\n    let irregular = if use_rcon then rcon_added else sub_word_out_flat in\n\n    (* AES_256: begin\n        unique case (op_i)\n          CIPH_FWD: begin\n            if (rnd == 0) begin\n              // Round 0: Nothing to be done\n              // The Full Key registers are not updated\n              regular = {key_i[3:0], key_i[7:4]};\n            end else begin\n              // Shift down old upper half\n              regular[3:0] = key_i[7:4];\n              // Generate new upper half\n              regular[4]   = irregular ^ key_i[0];\n              for (int i=1; i<4; i++) begin\n                regular[i+4] = regular[i+4-1] ^ key_i[i];\n              end\n            end // rnd == 0\n          end\n\n        endcase\n      end *)\n    let regular =\n      if round_i == #0\n      then concat key_i[:7:4] key_i[:3:0]\n      else\n        if op_i == !CIPH_FWD\n        then\n          (* todo: this is a \"scan\" op *)\n          let regular_4 = (!reshape irregular) ^ key_i[#0] in\n          let regular_5 = regular_4 ^ key_i[#1] in\n          let regular_6 = regular_5 ^ key_i[#2] in\n          let regular_7 = regular_6 ^ key_i[#3] in\n          snoc (snoc (snoc (snoc key_i[:7:4] regular_4) regular_5) regular_6) regular_7\n\n          (* CIPH_INV: begin\n            if (rnd == 0) begin\n              // Round 0: Nothing to be done\n              // The Full Key registers are not updated\n              regular = {key_i[3:0], key_i[7:4]};\n            end else begin\n              // Shift up old lower half\n              regular[7:4] = key_i[3:0];\n              // Generate new lower half\n              regular[0]   = irregular ^ key_i[4];\n              for (int i=0; i<3; i++) begin\n                regular[i+1] = key_i[4+i] ^ key_i[4+i+1];\n              end\n            end // rnd == 0\n          end *)\n        else\n          let regular_0 = (!reshape irregular) ^ key_i[#4] in\n          let regular_1 = key_i[#4] ^ key_i[#5] in\n          let regular_2 = key_i[#5] ^ key_i[#6] in\n          let regular_3 = key_i[#6] ^ key_i[#7] in\n          cons regular_0 (cons regular_1 (cons regular_2 (cons regular_3 key_i[:3:0])))\n      in\n    regular\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/KeyExpand.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318194686359, "lm_q2_score": 0.4378234991142018, "lm_q1q2_score": 0.2644155424261646}}
{"text": "From iris.proofmode Require Import proofmode.\nFrom iris.program_logic Require Export weakestpre.\nFrom RobustSafety Require Export persistent_pred.\nFrom RobustSafety Require Export rules.\nFrom iris.algebra Require Import list.\nFrom iris.base_logic Require Import invariants.\nFrom iris.prelude Require Import options.\nImport uPred.\n\nDefinition logN : namespace := nroot .@ \"logN\".\n\n(** interp : is a unary logical relation. *)\nSection logrel.\n  Context `{heapIG Σ}.\n  Notation D := (persistent_predO val (iPropI Σ)).\n  Implicit Types interp : D.\n\n  Local Arguments ofe_car !_.\n\n  Program Definition interp_prod : D -n> D :=\n    λne interp, PersPred (λ w, ▷ ∃ w1 w2, ⌜w = PairV w1 w2⌝ ∧ interp w1 ∧ interp w2)%I.\n  Solve Obligations with solve_proper.\n  Instance interp_prod_contractive : Contractive interp_prod.\n  Proof. solve_contractive. Qed.\n\n  Program Definition interp_sum : D -n> D :=\n    λne interp,\n      PersPred (λ w, ▷ ((∃ w1, ⌜w = InjLV w1⌝ ∧ interp w1) ∨ (∃ w2, ⌜w = InjRV w2⌝ ∧ interp w2)))%I.\n  Solve Obligations with solve_proper.\n  Instance interp_sum_contractive : Contractive interp_sum.\n  Proof. solve_contractive. Qed.\n\n  Program Definition interp_arrow : D -n> D :=\n    λne interp, PersPred (λ w, □ ∀ v, ▷ interp v → WP App (of_val w) (of_val v) ? {{ interp }})%I.\n  Solve Obligations with solve_proper.\n  Instance interp_arrow_contractive : Contractive interp_arrow.\n  Proof.\n    intros n interp interp' Hinterps w.\n    rewrite /interp_arrow /=.\n    f_equiv.\n    f_equiv; intros v.\n    f_equiv.\n    - solve_contractive.\n    - apply wp_contractive; first apply _.\n      destruct n; first done.\n      apply Hinterps.\n  Qed.\n\n  Program Definition interp_ref_inv (l : loc) : D -n> iPropO Σ :=\n    λne interp, (∃ v, l ↦ v ∗ interp v)%I.\n  Solve Obligations with solve_proper.\n\n  Program Definition interp_ref : D -n> D :=\n    λne interp, PersPred (λ w, ∃ l, ⌜w = LocV l⌝ ∧ inv (logN .@ l) (interp_ref_inv l interp))%I.\n  Solve Obligations with solve_proper.\n  Instance interp_ref_contractive : Contractive interp_ref.\n  Proof. solve_contractive. Qed.\n\n  Program Definition interp_of (w : val) : (D -n> D) :=\n    λne interp, match w return D with\n      | RecV _ | LamV _ => interp_arrow interp\n      | UnitV => PersPred (λ _, True)\n      | NatV _ => PersPred (λ _, True)\n      | BoolV _ => PersPred (λ _, True)\n      | PairV _ _ => interp_prod interp\n      | InjLV _ | InjRV _ => interp_sum interp\n      | LocV _ => interp_ref interp\n      end%I.\n  Next Obligation.\n  Proof. intros []; solve_proper. Qed.\n\n  Instance interp_of_contractive w : Contractive (interp_of w).\n  Proof.\n    destruct w; cbn -[interp_arrow interp_prod interp_sum interp_ref]; apply (_ : Contractive _).\n  Qed.\n\n  Program Definition interp_one : D -n> D :=\n    λne interp, PersPred (λ w, interp_of w interp w).\n  Next Obligation.\n  Proof.\n    intros ???? w; cbn -[interp_of]; f_equiv; by apply contractive_ne; first apply _.\n  Qed.\n  Instance interp_one_contractive : Contractive interp_one.\n  Proof.\n    intros n interp interp' Hinterps w; cbn -[interp_of]; f_equiv; apply (_ : Contractive _); done.\n  Qed.\n\n  Definition interp : D := fixpoint interp_one.\n\n  Lemma interp_unfold : interp ≡ interp_one interp.\n  Proof. rewrite /interp; apply fixpoint_unfold. Qed.\n\n  Definition interp_env (vs : list val) : iProp Σ := [∗ list] v ∈ vs, interp v.\n\n  Definition interp_expr (e : expr) : iProp Σ := WP e ? {{ interp }}%I.\n\n  Global Instance interp_env_persistent vs : Persistent (interp_env vs) := _.\n\n  Lemma interp_env_Some_l vs x v :\n    vs !! x = Some v → interp_env vs ⊢ interp v.\n  Proof.\n    iIntros (?) \"Henv\".\n    iApply (big_sepL_elem_of with \"Henv\").\n    apply elem_of_list_lookup_2 with x; done.\n  Qed.\n\n  Lemma interp_env_nil : ⊢ interp_env [].\n  Proof. done. Qed.\n  Lemma interp_env_cons vs v :\n    interp_env (v :: vs) ⊣⊢ interp v ∗ interp_env vs.\n  Proof. done. Qed.\n\n  (* The logical relation *)\n\n  Definition logrel (e : expr) : iProp Σ := □ ∀ vs, interp_env vs -∗ interp_expr e.[env_subst vs].\n\nEnd logrel.\n\nGlobal Typeclasses Opaque interp_env.\n", "meta": {"author": "amintimany", "repo": "robustsafety", "sha": "b5a86d59d5ca033d4f4bb874de745f75a7b36690", "save_path": "github-repos/coq/amintimany-robustsafety", "path": "github-repos/coq/amintimany-robustsafety/robustsafety-b5a86d59d5ca033d4f4bb874de745f75a7b36690/theories/logrel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370308082623216, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.26430334708502}}
{"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 develops the memory model that is used in the dynamic\n  semantics of all the languages used in the compiler.\n  It defines a type [mem] of memory states, the following 4 basic\n  operations over memory states, and their properties:\n- [load]: read a memory chunk at a given address;\n- [store]: store a memory chunk at a given address;\n- [alloc]: allocate a fresh memory block;\n- [free]: invalidate a memory block.\n*)\n\nRequire Import Zwf.\nRequire Import Axioms.\nRequire Import Coqlib.\nRequire Intv.\nRequire Import Maps.\nRequire Archi.\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\" := (PMap.get b a) (at level 1).\n\nModule Mem <: MEM.\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: PMap.t (ZMap.t memval);  (**r [block -> offset -> memval] *)\n  mem_access: PMap.t (Z -> perm_kind -> option permission);\n                                         (**r [block -> offset -> kind -> option permission] *)\n  nextblock: block;\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, ~(Plt b nextblock) -> mem_access#b ofs k = None;\n  contents_default:\n    forall b, fst mem_contents#b = Undef\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) := Plt 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 (plt 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 (PMap.init (ZMap.init Undef))\n        (PMap.init (fun ofs k => None))\n        1%positive _ _ _.\nNext Obligation.\n  repeat rewrite PMap.gi. red; auto.\nQed.\nNext Obligation.\n  rewrite PMap.gi. auto.\nQed.\nNext Obligation.\n  rewrite PMap.gi. auto.\nQed.\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 (PMap.set m.(nextblock) \n                   (ZMap.init Undef)\n                   m.(mem_contents))\n         (PMap.set m.(nextblock)\n                   (fun ofs k => if zle lo ofs && zlt ofs hi then Some Freeable else None)\n                   m.(mem_access))\n         (Psucc m.(nextblock))\n         _ _ _,\n   m.(nextblock)).\nNext Obligation.\n  repeat rewrite PMap.gsspec. destruct (peq 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 PMap.gsspec. destruct (peq b (nextblock m)). \n  subst b. elim H. apply Plt_succ. \n  apply nextblock_noaccess. red; intros; elim H. \n  apply Plt_trans_succ; auto.\nQed.\nNext Obligation.\n  rewrite PMap.gsspec. destruct (peq b (nextblock m)). auto. apply contents_default. \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        (PMap.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  repeat rewrite PMap.gsspec. destruct (peq 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 PMap.gsspec. destruct (peq b0 b). subst.\n  destruct (zle lo ofs && zlt ofs hi). auto. apply nextblock_noaccess; auto.\n  apply nextblock_noaccess; auto.\nQed.\nNext Obligation.\n  apply contents_default.\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' => ZMap.get p c :: 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  ZMap.get q (setN vl p c) = ZMap.get q c.\nProof.\n  induction vl; intros; simpl.\n  auto. \n  simpl length in H. rewrite inj_S in H.\n  transitivity (ZMap.get q (ZMap.set p a c)).\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  ZMap.get q (setN vl p c) = ZMap.get q c.\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 -> ZMap.get i c1 = ZMap.get i c2) ->\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_disjoint:\n  forall vl q c n p,\n  Intv.disjoint (p, p + Z_of_nat n) (q, q + Z_of_nat (length vl)) ->\n  getN n p (setN vl q c) = getN n p c.\nProof.\n  intros. apply getN_exten. intros. apply setN_other.\n  intros; red; intros; subst r. eelim H; eauto. \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_setN_disjoint. apply Intv.disjoint_range. auto. \nQed.\n\nRemark setN_default:\n  forall vl q c, fst (setN vl q c) = fst c.\nProof.\n  induction vl; simpl; intros. auto. rewrite IHvl. auto. \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\nProgram Definition 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 (PMap.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                _ _ _)\n  else\n    None.\nNext Obligation. apply access_max. Qed.\nNext Obligation. apply nextblock_noaccess; auto. Qed.\nNext Obligation. \n  rewrite PMap.gsspec. destruct (peq b0 b).\n  rewrite setN_default. apply contents_default. \n  apply contents_default.\nQed.\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\nProgram Definition 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             (PMap.set b (setN bytes ofs (m.(mem_contents)#b)) m.(mem_contents))\n             m.(mem_access)\n             m.(nextblock)\n             _ _ _)\n  else\n    None.\nNext Obligation. apply access_max. Qed.\nNext Obligation. apply nextblock_noaccess; auto. Qed.\nNext Obligation. \n  rewrite PMap.gsspec. destruct (peq b0 b).\n  rewrite setN_default. apply contents_default. \n  apply contents_default.\nQed.\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                (PMap.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  repeat rewrite PMap.gsspec. destruct (peq 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 PMap.gsspec. destruct (peq 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.\nNext Obligation.\n  apply contents_default.\nQed.\n\n(** * Properties of the memory operations *)\n\n(** Properties of the empty store. *)\n\nTheorem nextblock_empty: nextblock empty = 1%positive.\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 PMap.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  | _ => 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\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 -> ZMap.get (ofs + z) m1.(mem_contents)#b = ZMap.get (ofs + z) m2.(mem_contents)#b) ->\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\nTheorem load_int64_split:\n  forall m b ofs v,\n  load Mint64 m b ofs = Some v ->\n  exists v1 v2,\n     load Mint32 m b ofs = Some (if Archi.big_endian then v1 else v2)\n  /\\ load Mint32 m b (ofs + 4) = Some (if Archi.big_endian then v2 else v1)\n  /\\ Val.lessdef v (Val.longofwords v1 v2).\nProof.\n  intros. \n  exploit load_valid_access; eauto. intros [A B]. simpl in *.\n  exploit load_loadbytes. eexact H. simpl. intros [bytes [LB EQ]].\n  change 8 with (4 + 4) in LB. \n  exploit loadbytes_split. eexact LB. omega. omega. \n  intros (bytes1 & bytes2 & LB1 & LB2 & APP).\n  change 4 with (size_chunk Mint32) in LB1.\n  exploit loadbytes_load. eexact LB1.\n  simpl. apply Zdivides_trans with 8; auto. exists 2; auto.\n  intros L1.\n  change 4 with (size_chunk Mint32) in LB2.\n  exploit loadbytes_load. eexact LB2.\n  simpl. apply Zdivide_plus_r. apply Zdivides_trans with 8; auto. exists 2; auto. exists 1; auto.\n  intros L2.\n  exists (decode_val Mint32 (if Archi.big_endian then bytes1 else bytes2));\n  exists (decode_val Mint32 (if Archi.big_endian then bytes2 else bytes1)).\n  split. destruct Archi.big_endian; auto.\n  split. destruct Archi.big_endian; auto.\n  rewrite EQ. rewrite APP. apply decode_val_int64.\n  erewrite loadbytes_length; eauto. reflexivity. \n  erewrite loadbytes_length; eauto. reflexivity. \nQed.\n\nTheorem loadv_int64_split:\n  forall m a v,\n  loadv Mint64 m a = Some v ->\n  exists v1 v2,\n     loadv Mint32 m a = Some (if Archi.big_endian then v1 else v2)\n  /\\ loadv  Mint32 m (Val.add a (Vint (Int.repr 4))) = Some (if Archi.big_endian then v2 else v1)\n  /\\ Val.lessdef v (Val.longofwords v1 v2).\nProof.\n  intros. destruct a; simpl in H; try discriminate.\n  exploit load_int64_split; eauto. intros (v1 & v2 & L1 & L2 & EQ).\n  assert (NV: Int.unsigned (Int.add i (Int.repr 4)) = Int.unsigned i + 4).\n    rewrite Int.add_unsigned. apply Int.unsigned_repr.\n    exploit load_valid_access. eexact H. intros [P Q]. simpl in Q.\n    exploit (Zdivide_interval (Int.unsigned i) Int.modulus 8).\n    omega. apply Int.unsigned_range. auto. exists (two_p (32-3)); reflexivity. \n    unfold Int.max_unsigned. omega.\n  exists v1; exists v2.\nOpaque Int.repr.\n  split. auto.\n  split. simpl. rewrite NV. auto. \n  auto.\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 = PMap.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 PMap.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 PMap.gsspec. destruct (peq 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 PMap.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 PMap.gsspec. destruct (peq 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_in:\n  forall vl p q c,\n  p <= q < p + Z_of_nat (length vl) ->\n  In (ZMap.get q (setN vl p c)) vl.\nProof.\n  induction vl; intros.\n  simpl in H. omegaContradiction.\n  simpl length in H. rewrite inj_S in H. simpl. \n  destruct (zeq p q). subst q. rewrite setN_outside. rewrite ZMap.gss. \n  auto with coqlib. omega.\n  right. apply IHvl. omega.\nQed.\n\nLemma getN_in:\n  forall c q n p,\n  p <= q < p + Z_of_nat n ->\n  In (ZMap.get q c) (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\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\nLemma load_store_overlap:\n  forall chunk m1 b ofs v m2 chunk' ofs' v',\n  store chunk m1 b ofs v = Some m2 ->\n  load chunk' m2 b ofs' = Some v' ->\n  ofs' + size_chunk chunk' > ofs ->\n  ofs + size_chunk chunk > ofs' ->\n  exists mv1 mvl mv1' mvl',\n      shape_encoding chunk v (mv1 :: mvl)\n  /\\  shape_decoding chunk' (mv1' :: mvl') v'\n  /\\  (   (ofs' = ofs /\\ mv1' = mv1)\n       \\/ (ofs' > ofs /\\ In mv1' mvl)\n       \\/ (ofs' < ofs /\\ In mv1 mvl')).\nProof.\n  intros. \n  exploit load_result; eauto. erewrite store_mem_contents by eauto; simpl.\n  rewrite PMap.gss. \n  set (c := (mem_contents m1)#b). intros V'. \n  destruct (size_chunk_nat_pos chunk) as [sz SIZE]. \n  destruct (size_chunk_nat_pos chunk') as [sz' SIZE'].\n  destruct (encode_val chunk v) as [ | mv1 mvl] eqn:ENC.\n  generalize (encode_val_length chunk v); rewrite ENC; simpl; congruence.\n  set (c' := setN (mv1::mvl) ofs c) in *.\n  exists mv1, mvl, (ZMap.get ofs' c'), (getN sz' (ofs' + 1) c').\n  split. rewrite <- ENC. apply encode_val_shape.\n  split. rewrite V', SIZE'. apply decode_val_shape. \n  destruct (zeq ofs' ofs).\n- subst ofs'. left; split. auto. unfold c'. simpl. \n  rewrite setN_outside by omega. apply ZMap.gss.\n- right. destruct (zlt ofs ofs').\n(* If ofs < ofs':  the load reads (at ofs') a continuation byte from the write.\n       ofs   ofs'   ofs+|chunk|\n        [-------------------]       write\n             [-------------------]  read\n*)\n+ left; split. omega. unfold c'. simpl. apply setN_in. \n  assert (Z.of_nat (length (mv1 :: mvl)) = size_chunk chunk).\n  { rewrite <- ENC; rewrite encode_val_length. rewrite size_chunk_conv; auto. }\n  simpl length in H3. rewrite inj_S in H3. omega.\n(* If ofs > ofs':  the load reads (at ofs) the first byte from the write.\n       ofs'   ofs   ofs'+|chunk'|\n               [-------------------]  write\n         [----------------]           read\n*)\n+ right; split. omega. replace mv1 with (ZMap.get ofs c'). \n  apply getN_in. \n  assert (size_chunk chunk' = Zsucc (Z.of_nat sz')).\n  { rewrite size_chunk_conv. rewrite SIZE'. rewrite inj_S; auto. }\n  omega.\n  unfold c'. simpl. rewrite setN_outside by omega. apply ZMap.gss.\nQed.\n\nDefinition compat_pointer_chunks (chunk1 chunk2: memory_chunk) : Prop :=\n  match chunk1, chunk2 with\n  | (Mint32 | Many32), (Mint32 | Many32) => True\n  | Many64, Many64 => True\n  | _, _ => False\n  end.\n\nLemma compat_pointer_chunks_true:\n  forall chunk1 chunk2,\n  (chunk1 = Mint32 \\/ chunk1 = Many32 \\/ chunk1 = Many64) ->\n  (chunk2 = Mint32 \\/ chunk2 = Many32 \\/ chunk2 = Many64) ->\n  quantity_chunk chunk1 = quantity_chunk chunk2 ->\n  compat_pointer_chunks chunk1 chunk2.\nProof.\n  intros. destruct H as [P|[P|P]]; destruct H0 as [Q|[Q|Q]];\n  subst; red; auto; discriminate.\nQed.\n\nTheorem load_pointer_store:\n  forall chunk m1 b ofs v m2 chunk' b' ofs' v_b v_o,\n  store chunk m1 b ofs v = Some m2 ->\n  load chunk' m2 b' ofs' = Some(Vptr v_b v_o) ->\n  (v = Vptr v_b v_o /\\ compat_pointer_chunks chunk chunk' /\\ b' = b /\\ ofs' = ofs)\n  \\/ (b' <> b \\/ ofs' + size_chunk chunk' <= ofs \\/ ofs + size_chunk chunk <= ofs').\nProof.\n  intros.\n  destruct (peq b' b); auto. subst b'.\n  destruct (zle (ofs' + size_chunk chunk') ofs); auto.\n  destruct (zle (ofs + size_chunk chunk) ofs'); auto.\n  exploit load_store_overlap; eauto. \n  intros (mv1 & mvl & mv1' & mvl' & ENC & DEC & CASES).\n  inv DEC; try contradiction.\n  destruct CASES as [(A & B) | [(A & B) | (A & B)]].\n- (* Same offset *)\n  subst. inv ENC. \n  assert (chunk = Mint32 \\/ chunk = Many32 \\/ chunk = Many64)\n  by (destruct chunk; auto || contradiction). \n  left; split. rewrite H3.\n  destruct H4 as [P|[P|P]]; subst chunk'; destruct v0; simpl in H3; congruence.\n  split. apply compat_pointer_chunks_true; auto.\n  auto.\n- (* ofs' > ofs *)\n  inv ENC. \n  + exploit H10; eauto. intros (j & P & Q). inv P. congruence.\n  + exploit H8; eauto. intros (n & P); congruence.\n  + exploit H2; eauto. congruence.\n- (* ofs' < ofs *)\n  exploit H7; eauto. intros (j & P & Q). subst mv1. inv ENC. congruence.\nQed.\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 load_store_overlap; eauto. \n  intros (mv1 & mvl & mv1' & mvl' & ENC & DEC & CASES).\n  destruct CASES as [(A & B) | [(A & B) | (A & B)]].\n- congruence.\n- inv ENC. \n  + exploit H9; eauto. intros (j & P & Q). subst mv1'. inv DEC. congruence. auto.\n  + contradiction.\n  + exploit H5; eauto. intros; subst. inv DEC; auto.\n- inv DEC. \n  + exploit H10; eauto. intros (j & P & Q). subst mv1. inv ENC. congruence. \n  + exploit H8; eauto. intros (n & P). subst mv1. inv ENC. contradiction. \n  + auto.\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  ~compat_pointer_chunks chunk chunk' ->\n  v = Vundef.\nProof.\n  intros.\n  exploit load_store_overlap; eauto. \n  generalize (size_chunk_pos chunk'); omega.\n  generalize (size_chunk_pos chunk); omega.\n  intros (mv1 & mvl & mv1' & mvl' & ENC & DEC & CASES).\n  destruct CASES as [(A & B) | [(A & B) | (A & B)]]; try omegaContradiction.\n  inv ENC; inv DEC; auto.\n- elim H1. apply compat_pointer_chunks_true; auto.\n- contradiction.\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  destruct (valid_access_dec m chunk2 b ofs Writable); auto.\n  f_equal. apply mkmem_ext; auto. congruence.\n  elim n. apply valid_access_compat with chunk1; auto. omega.\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\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  destruct (valid_access_dec m Mfloat64al32 b ofs Writable).\n  rewrite <- H. f_equal. apply mkmem_ext; auto.\n  elim 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\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. unfold storebytes.\n  destruct (range_perm_dec m1 b ofs (ofs + Z_of_nat (length bytes)) Cur Writable).\n  econstructor; 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  f_equal. apply mkmem_ext; 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  f_equal. apply mkmem_ext; 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 = PMap.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 PMap.gss. rewrite nat_of_Z_of_nat. \n  apply getN_setN_same. \n  red; eauto with mem. \nQed.\n\nTheorem loadbytes_storebytes_disjoint:\n  forall b' ofs' len,\n  len >= 0 ->\n  b' <> b \\/ Intv.disjoint (ofs', ofs' + len) (ofs, ofs + Z_of_nat (length bytes)) ->\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 PMap.gsspec. destruct (peq b' b). subst b'. \n  apply getN_setN_disjoint. 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 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. apply loadbytes_storebytes_disjoint; auto. \n  destruct H0; auto. right. apply Intv.disjoint_range; auto. \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 PMap.gsspec. destruct (peq 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 PMap.gss.  rewrite setN_concat. symmetry. apply PMap.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\nTheorem store_int64_split:\n  forall m b ofs v m',\n  store Mint64 m b ofs v = Some m' ->\n  exists m1,\n     store Mint32 m b ofs (if Archi.big_endian then Val.hiword v else Val.loword v) = Some m1\n  /\\ store Mint32 m1 b (ofs + 4) (if Archi.big_endian then Val.loword v else Val.hiword v) = Some m'.\nProof.\n  intros. \n  exploit store_valid_access_3; eauto. intros [A B]. simpl in *.\n  exploit store_storebytes. eexact H. intros SB.\n  rewrite encode_val_int64 in SB. \n  exploit storebytes_split. eexact SB. intros [m1 [SB1 SB2]]. \n  rewrite encode_val_length in SB2. simpl in SB2. \n  exists m1; split. \n  apply storebytes_store. exact SB1.\n  simpl. apply Zdivides_trans with 8; auto. exists 2; auto.\n  apply storebytes_store. exact SB2. \n  simpl. apply Zdivide_plus_r. apply Zdivides_trans with 8; auto. exists 2; auto. exists 1; auto.\nQed.\n\nTheorem storev_int64_split:\n  forall m a v m',\n  storev Mint64 m a v = Some m' ->\n  exists m1,\n     storev Mint32 m a (if Archi.big_endian then Val.hiword v else Val.loword v) = Some m1\n  /\\ storev Mint32 m1 (Val.add a (Vint (Int.repr 4))) (if Archi.big_endian then Val.loword v else Val.hiword v) = Some m'.\nProof.\n  intros. destruct a; simpl in H; try discriminate.\n  exploit store_int64_split; eauto. intros [m1 [A B]].\n  exists m1; split.\n  exact A.\n  unfold storev, Val.add. rewrite Int.add_unsigned. rewrite Int.unsigned_repr. exact B.\n  exploit store_valid_access_3. eexact H. intros [P Q]. simpl in Q.\n  exploit (Zdivide_interval (Int.unsigned i) Int.modulus 8).\n    omega. apply Int.unsigned_range. auto. exists (two_p (32-3)); reflexivity. \n  change (Int.unsigned (Int.repr 4)) with 4. unfold Int.max_unsigned. omega. \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 = Psucc (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. \n  apply Plt_trans_succ; auto.\nQed.\n\nTheorem fresh_block_alloc:\n  ~(valid_block m1 b).\nProof.\n  unfold valid_block. rewrite alloc_result. apply Plt_strict. \nQed.\n\nTheorem valid_new_block:\n  valid_block m2 b.\nProof.\n  unfold valid_block. rewrite alloc_result. rewrite nextblock_alloc. apply Plt_succ.\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  exploit Plt_succ_inv; eauto. tauto.\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 PMap.gsspec. destruct (peq b' (nextblock m1)); auto.\n  rewrite nextblock_noaccess in H. contradiction. subst b'. apply Plt_strict. \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 PMap.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 eq_block 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 PMap.gsspec. unfold eq_block. destruct (peq 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 dec_eq_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 dec_eq_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  destruct (eq_block 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 dec_eq_true. intro.\n  exploit perm_alloc_inv. eexact H3. rewrite dec_eq_true. intro. \n  intuition omega. \n  split; auto. red; intros. \n  exploit perm_alloc_inv. apply H0. eauto. rewrite dec_eq_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 PMap.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 PMap.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\nTheorem loadbytes_alloc_unchanged:\n  forall b' ofs n,\n  valid_block m1 b' ->\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  injection ALLOC; intros A B. rewrite <- B; simpl. \n  rewrite PMap.gso. auto. rewrite A. eauto with mem.\n  red; intros. eapply perm_alloc_1; eauto. \n  rewrite pred_dec_false; auto.\n  red; intros; elim n0. red; intros. eapply perm_alloc_4; eauto. eauto with mem. \nQed.\n\nTheorem loadbytes_alloc_same:\n  forall n ofs bytes byte,\n  loadbytes m2 b ofs n = Some bytes ->\n  In byte bytes -> byte = Undef.\nProof.\n  unfold loadbytes; intros. destruct (range_perm_dec m2 b ofs (ofs + n) Cur Readable); inv H.\n  revert H0.\n  injection ALLOC; intros A B. rewrite <- A; rewrite <- B; simpl. rewrite PMap.gss. \n  generalize (nat_of_Z n) ofs. induction n0; simpl; intros. \n  contradiction. \n  rewrite ZMap.gi in H0. destruct H0; 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 PMap.gsspec. destruct (peq 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 PMap.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 PMap.gsspec. destruct (peq 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 PMap.gsspec. destruct (peq 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 PMap.gsspec. destruct (peq 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\nTheorem load_free_2:\n  forall chunk b ofs v,\n  load chunk m2 b ofs = Some v -> load chunk m1 b ofs = Some v.\nProof.\n  intros. unfold load. rewrite pred_dec_true. \n  rewrite (load_result _ _ _ _ _ H). rewrite free_result; auto. \n  apply valid_access_free_inv_1. eauto with mem.\nQed.\n\nTheorem loadbytes_free:\n  forall b ofs n,\n  b <> bf \\/ lo >= hi \\/ ofs + n <= lo \\/ hi <= ofs ->\n  loadbytes m2 b ofs n = loadbytes m1 b ofs n.\nProof.\n  intros. unfold loadbytes. \n  destruct (range_perm_dec m2 b ofs (ofs + n) Cur Readable).\n  rewrite pred_dec_true. \n  rewrite free_result; auto. \n  red; intros. eapply perm_free_3; eauto. \n  rewrite pred_dec_false; auto. \n  red; intros. elim n0; red; intros. \n  eapply perm_free_1; eauto. destruct H; auto. right; omega. \nQed.\n\nTheorem loadbytes_free_2:\n  forall b ofs n bytes,\n  loadbytes m2 b ofs n = Some bytes -> loadbytes m1 b ofs n = Some bytes.\nProof.\n  intros. unfold loadbytes in *.\n  destruct (range_perm_dec m2 b ofs (ofs + n) Cur Readable); inv H.\n  rewrite pred_dec_true. rewrite free_result; auto.\n  red; intros. apply perm_free_3; auto. \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 PMap.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 PMap.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 PMap.gsspec. destruct (peq 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 PMap.gsspec. destruct (peq 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 (eq_block 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\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\nTheorem loadbytes_drop:\n  forall b' ofs n, \n  b' <> b \\/ ofs + n <= lo \\/ hi <= ofs \\/ perm_order p Readable ->\n  loadbytes m' b' ofs n = loadbytes m b' ofs n.\nProof.\n  intros.\n  unfold loadbytes.\n  destruct (range_perm_dec m b' ofs (ofs + n) Cur 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  red; intros.\n  destruct (eq_block 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. intuition.\n  eapply perm_drop_3; eauto. \n  rewrite pred_dec_false; eauto. \n  red; intros; elim n0; red; intros. \n  eapply perm_drop_4; 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_align:\n      forall b1 b2 delta chunk ofs p,\n      f b1 = Some(b2, delta) ->\n      range_perm m1 b1 ofs (ofs + size_chunk chunk) Max p ->\n      (align_chunk chunk | delta);\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 (ZMap.get ofs m1.(mem_contents)#b1) (ZMap.get (ofs+delta) m2.(mem_contents)#b2)\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\nLemma valid_access_inj:\n  forall f m1 m2 b1 b2 delta chunk ofs p,\n  mem_inj f m1 m2 ->\n  f b1 = Some(b2, delta) ->\n  valid_access m1 chunk b1 ofs p ->\n  valid_access m2 chunk b2 (ofs + delta) p.\nProof.\n  intros. destruct H1 as [A B]. constructor.\n  replace (ofs + delta + size_chunk chunk)\n     with ((ofs + size_chunk chunk) + delta) by omega.\n  eapply range_perm_inj; eauto.\n  apply Z.divide_add_r; auto. eapply mi_align; eauto with mem.\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  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 valid_access_inj; 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              /\\ 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  Forall2 (memval_inject f) vl1 vl2 ->\n  forall p c1 c2,\n  (forall q, access q -> memval_inject f (ZMap.get q c1) (ZMap.get (q + delta) c2)) ->\n  (forall q, access q -> memval_inject f (ZMap.get q (setN vl1 p c1)) \n                                         (ZMap.get (q + delta) (setN vl2 (p + delta) c2))).\nProof.\n  induction 1; intros; simpl. \n  auto.\n  replace (p + delta + 1) with ((p + 1) + delta) by omega.\n  apply IHForall2; 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 valid_access_inj; 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(* align *)\n  intros. eapply mi_align with (ofs := ofs0) (p := p); eauto.\n  red; intros; eauto with mem.\n(* mem_contents *)\n  intros.\n  rewrite (store_mem_contents _ _ _ _ _ _ H0).\n  rewrite (store_mem_contents _ _ _ _ _ _ STORE).\n  rewrite ! PMap.gsspec. \n  destruct (peq 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 peq_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 (peq 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(* align *)\n  intros. eapply mi_align with (ofs := ofs0) (p := p); eauto.\n  red; intros; eauto with mem.\n(* mem_contents *)\n  intros. \n  rewrite (store_mem_contents _ _ _ _ _ _ H0).\n  rewrite PMap.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  intros; eapply mi_align0; eauto.\n(* mem_contents *)\n  intros. \n  rewrite (store_mem_contents _ _ _ _ _ _ H1).\n  rewrite PMap.gsspec. destruct (peq 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  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 (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(* align *)\n  intros. eapply mi_align with (ofs := ofs0) (p := p); eauto.\n  red; intros. eapply perm_storebytes_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  rewrite ! PMap.gsspec. destruct (peq 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 peq_true.\n  apply setN_inj with (access := fun ofs => perm m1 b1 ofs Cur Readable); auto.\n  destruct (peq 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 (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(* align *)\n  intros. eapply mi_align with (ofs := ofs0) (p := p); eauto.\n  red; intros. eapply perm_storebytes_2; eauto. \n(* mem_contents *)\n  intros. \n  rewrite (storebytes_mem_contents _ _ _ _ _ H0).\n  rewrite PMap.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(* align *)\n  eauto.\n(* mem_contents *)\n  intros. \n  rewrite (storebytes_mem_contents _ _ _ _ _ H1).\n  rewrite PMap.gsspec. destruct (peq 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\nLemma storebytes_empty_inj:\n  forall f m1 b1 ofs1 m1' m2 b2 ofs2 m2',\n  mem_inj f m1 m2 ->\n  storebytes m1 b1 ofs1 nil = Some m1' ->\n  storebytes m2 b2 ofs2 nil = Some m2' ->\n  mem_inj f m1' m2'.\nProof.\n  intros. destruct H. constructor. \n(* perm *)\n  intros.\n  eapply perm_storebytes_1; eauto. \n  eapply mi_perm0; eauto.\n  eapply perm_storebytes_2; eauto.\n(* align *)\n  intros. eapply mi_align0 with (ofs := ofs) (p := p); eauto.\n  red; intros. eapply perm_storebytes_2; eauto. \n(* mem_contents *)\n  intros.\n  assert (perm m1 b0 ofs Cur Readable). eapply perm_storebytes_2; eauto. \n  rewrite (storebytes_mem_contents _ _ _ _ _ H0).\n  rewrite (storebytes_mem_contents _ _ _ _ _ H1).\n  simpl. rewrite ! PMap.gsspec. \n  destruct (peq b0 b1); destruct (peq b3 b2); subst; eapply mi_memval0; eauto.\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(* align *)\n  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 PMap.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 (eq_block b0 b1). congruence. eauto. \n(* align *)\n  intros. eapply mi_align0 with (ofs := ofs) (p := p); eauto.\n  red; intros. exploit perm_alloc_inv; eauto.\n  destruct (eq_block b0 b1); auto. congruence. \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 PMap.gsspec. unfold eq_block in H4. destruct (peq 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 (eq_block b0 b1). subst b0.\n  rewrite H4 in H5; inv H5. eauto. eauto. \n(* align *)\n  intros. destruct (eq_block b0 b1).\n  subst b0. assert (delta0 = delta) by congruence. subst delta0.\n  assert (lo <= ofs < hi).\n  { eapply perm_alloc_3; eauto. apply H6. generalize (size_chunk_pos chunk); omega. }\n  assert (lo <= ofs + size_chunk chunk - 1 < hi).\n  { eapply perm_alloc_3; eauto. apply H6. generalize (size_chunk_pos chunk); omega. }\n  apply H2. omega. \n  eapply mi_align0 with (ofs := ofs) (p := p); eauto.\n  red; intros. eapply perm_alloc_4; 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 PMap.gsspec. unfold eq_block in H7. \n  destruct (peq 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(* align *)\n  intros. eapply mi_align0 with (ofs := ofs) (p := p); eauto.\n  red; intros; eapply perm_free_3; eauto.\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 (eq_block 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(* align *)\n  eapply mi_align0; eauto.\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(* align *)\n  intros. eapply mi_align0 with (ofs := ofs) (p := p0); eauto.\n  red; intros; eapply perm_drop_4; eauto.\n(* contents *)\n  intros.\n  replace (ZMap.get ofs m1'.(mem_contents)#b1) with (ZMap.get ofs m1.(mem_contents)#b1).\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  constructor.\n(* perm *)\n  intros. \n  assert (perm m2 b3 (ofs + delta0) k p0).\n    eapply mi_perm0; eauto. eapply perm_drop_4; eauto. \n  destruct (eq_block 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 (eq_block 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  intuition.\n(* align *)\n  intros. eapply mi_align0 with (ofs := ofs) (p := p0); eauto.\n  red; intros; eapply perm_drop_4; eauto.\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. constructor.\n  (* perm *)\n  intros. eapply perm_drop_3; eauto. \n  destruct (eq_block b2 b); auto. subst b2. right. \n  destruct (zlt (ofs + delta) lo); auto.\n  destruct (zle hi (ofs + delta)); auto.\n  byContradiction. exploit H1; eauto. omega.\n  (* align *)\n  eapply mi_align0; eauto.\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. apply Z.divide_0_r. \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              /\\ 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  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. tauto. \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 valid_access_inj; 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      perm m1 b (Int.unsigned ofs) Max Nonempty \\/ perm m1 b (Int.unsigned ofs - 1) Max Nonempty ->\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 (plt 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 valid_access_inj; 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\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.\n  assert (perm m1 b1 (Int.unsigned ofs1) Max Nonempty) by eauto with mem.\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. rewrite weak_valid_pointer_spec in H0. \n  rewrite ! valid_pointer_nonempty_perm in H0.\n  exploit mi_representable; eauto. destruct H0; eauto with mem.\n  intros [A B].\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.\n  exploit weak_valid_pointer_inject; eauto. intros W.\n  rewrite weak_valid_pointer_spec in H0. \n  rewrite ! valid_pointer_nonempty_perm in H0.\n  exploit mi_representable; eauto. destruct H0; eauto with mem. \n  intros [A B].\n  pose proof (Int.unsigned_range ofs).\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  intuition. \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 Mint64; 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              /\\ 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  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  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  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  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  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\nTheorem storebytes_empty_inject:\n  forall f m1 b1 ofs1 m1' m2 b2 ofs2 m2',\n  inject f m1 m2 ->\n  storebytes m1 b1 ofs1 nil = Some m1' ->\n  storebytes m2 b2 ofs2 nil = Some m2' ->\n  inject f m1' m2'.\nProof.\n  intros. inversion H. constructor; intros.\n(* inj *)\n  eapply storebytes_empty_inj; eauto.\n(* freeblocks *)\n  intros. apply mi_freeblocks0. red; intros; elim H2; 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  destruct H3; eauto using perm_storebytes_2. \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 eq_block b b1 then None else f b).\n  assert (inject_incr f f').\n    red; unfold f'; intros. destruct (eq_block 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 (eq_block b0 b1). congruence. eauto.\n    unfold f'; intros. destruct (eq_block b0 b1). congruence. eauto.\n    unfold f'; intros. destruct (eq_block 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 dec_eq_true. \n(* freeblocks *)\n  intros. unfold f'. destruct (eq_block b b1). auto. \n  apply mi_freeblocks0. red; intro; elim H3. eauto with mem. \n(* mappedblocks *)\n  unfold f'; intros. destruct (eq_block b b1). congruence. eauto. \n(* no overlap *)\n  unfold f'; red; intros.\n  destruct (eq_block b0 b1); destruct (eq_block b2 b1); try congruence.\n  eapply mi_no_overlap0. eexact H3. eauto. eauto.\n  exploit perm_alloc_inv. eauto. eexact H6. rewrite dec_eq_false; auto.  \n  exploit perm_alloc_inv. eauto. eexact H7. rewrite dec_eq_false; auto. \n(* representable *)\n  unfold f'; intros.\n  destruct (eq_block b b1); try discriminate.\n  eapply mi_representable0; try eassumption.\n  destruct H4; eauto using perm_alloc_4.\n(* incr *)\n  split. auto. \n(* image *)\n  split. unfold f'; apply dec_eq_true. \n(* incr *)\n  intros; unfold f'; apply dec_eq_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 eq_block b b1 then Some(b2, delta) else f b).\n  assert (inject_incr f f').\n    red; unfold f'; intros. destruct (eq_block 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 (eq_block 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 (eq_block b0 b1).\n      inversion H8. subst b0 b3 delta0.\n      elim (fresh_block_alloc _ _ _ _ _ H0).\n      eapply perm_valid_block with (ofs := ofs). apply H9. generalize (size_chunk_pos chunk); omega.\n      eauto.\n    unfold f'; intros. destruct (eq_block 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 dec_eq_true. \n(* freeblocks *)\n  unfold f'; intros. destruct (eq_block b b1). subst b. \n  elim H9. eauto with mem.\n  eauto with mem.\n(* mappedblocks *)\n  unfold f'; intros. destruct (eq_block 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 (eq_block b0 b1); destruct (eq_block b3 b1).\n  congruence.\n  inversion H10; subst b0 b1' delta1. \n    destruct (eq_block b2 b2'); auto. subst b2'. right; red; intros.\n    eapply H6; eauto. omega.\n  inversion H11; subst b3 b2' delta2. \n    destruct (eq_block b1' b2); auto. subst b1'. right; red; intros.\n    eapply H6; eauto. omega.\n  eauto.\n(* representable *)\n  unfold f'; intros.\n  destruct (eq_block b b1).\n   subst. injection H9; intros; subst b' delta0. destruct H10.\n    exploit 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 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  eapply mi_representable0; try eassumption.\n  destruct H10; eauto using perm_alloc_4.\n(* incr *)\n  split. auto.\n(* image of b1 *)\n  split. unfold f'; apply dec_eq_true. \n(* image of others *)\n  intros. unfold f'; apply dec_eq_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  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].\n  destruct (free m1 b lo hi) as [m11|] eqn:E; try discriminate.\n  apply IHl with m11; auto. eapply free_left_inject; eauto.\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; simpl; intros.\n  inv H. auto. \n  destruct a as [[b1 lo1] hi1].\n  destruct (free m b1 lo1 hi1) as [m1|] eqn:E; try discriminate.\n  exploit IHl; eauto. intros [A B].\n  split. eauto with mem.\n  intros. destruct H1. inv H1.\n  elim (perm_free_2 _ _ _ _ _ E 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\nTheorem free_parallel_inject:\n  forall f m1 m2 b lo hi m1' b' delta,\n  inject f m1 m2 ->\n  free m1 b lo hi = Some m1' ->\n  f b = Some(b', delta) ->\n  exists m2',\n     free m2 b' (lo + delta) (hi + delta) = Some m2'\n  /\\ inject f m1' m2'.\nProof.\n  intros. \n  destruct (range_perm_free m2 b' (lo + delta) (hi + delta)) as [m2' FREE].\n  eapply range_perm_inject; eauto. eapply free_range_perm; eauto.\n  exists m2'; split; auto.\n  eapply free_inject with (m1 := m1) (l := (b,lo,hi)::nil); eauto. \n  simpl; rewrite H0; auto.\n  intros. destruct (eq_block b1 b).\n  subst b1. rewrite H1 in H2; inv H2. \n  exists lo, hi; split; auto with coqlib. omega.\n  exploit mi_no_overlap. eexact H. eexact n. eauto. eauto.\n  eapply perm_max. eapply perm_implies. eauto. auto with mem. \n  instantiate (1 := ofs + delta0 - delta). \n  apply perm_cur_max. apply perm_implies with Freeable; auto with mem. \n  eapply free_range_perm; eauto. omega.\n  intros [A|A]. congruence. omega.\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  (* align *)\n  destruct (f b1) as [[b' delta'] |] eqn:?; try discriminate.\n  destruct (f' b') as [[b'' delta''] |] eqn:?; inv H. \n  apply Z.divide_add_r.\n  eapply mi_align0; eauto.\n  eapply mi_align1 with (ofs := ofs + delta') (p := p); eauto.\n  red; intros. replace ofs0 with ((ofs0 - delta') + delta') by omega.\n  eapply mi_perm0; eauto. apply H0. omega. \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  intuition 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  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  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 plt 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 (plt b1 thr); inversion H0; subst.\n  destruct (plt 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 pred_dec_false. auto. \n(* mappedblocks *)\n  unfold flat_inj, valid_block; intros. \n  destruct (plt 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 (plt 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 (plt b1 thr); inv H.\n  replace (ofs + 0) with ofs by omega; auto.\n(* align *)\n  unfold flat_inj; intros. destruct (plt b1 thr); inv H. apply Z.divide_0_r.\n(* mem_contents *)\n  intros; simpl. rewrite ! PMap.gi. 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  Plt (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 pred_dec_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  Plt 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 pred_dec_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  Plt 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 pred_dec_true; eauto. \n  repeat rewrite Zplus_0_r. intros [m'' [A B]]. congruence.\nQed.\n\n(** * Invariance properties between two memory states *)\n\nSection UNCHANGED_ON.\n\nVariable P: block -> Z -> Prop.\n\nRecord unchanged_on (m_before m_after: mem) : Prop := mk_unchanged_on {\n  unchanged_on_perm:\n    forall b ofs k p,\n    P b ofs -> valid_block m_before b ->\n    (perm m_before b ofs k p <-> perm m_after b ofs k p);\n  unchanged_on_contents:\n    forall b ofs,\n    P b ofs -> perm m_before b ofs Cur Readable ->\n    ZMap.get ofs (PMap.get b m_after.(mem_contents)) =\n    ZMap.get ofs (PMap.get b m_before.(mem_contents))\n}.\n\nLemma unchanged_on_refl:\n  forall m, unchanged_on m m.\nProof.\n  intros; constructor; tauto.\nQed.\n\nLemma perm_unchanged_on:\n  forall m m' b ofs k p,\n  unchanged_on m m' -> P b ofs -> valid_block m b ->\n  perm m b ofs k p -> perm m' b ofs k p.\nProof.\n  intros. destruct H. apply unchanged_on_perm0; auto. \nQed.\n\nLemma perm_unchanged_on_2:\n  forall m m' b ofs k p,\n  unchanged_on m m' -> P b ofs -> valid_block m b ->\n  perm m' b ofs k p -> perm m b ofs k p.\nProof.\n  intros. destruct H. apply unchanged_on_perm0; auto. \nQed.\n\nLemma loadbytes_unchanged_on_1:\n  forall m m' b ofs n,\n  unchanged_on m m' ->\n  valid_block m b ->\n  (forall i, ofs <= i < ofs + n -> P b i) ->\n  loadbytes m' b ofs n = loadbytes m b ofs n.\nProof.\n  intros. \n  destruct (zle n 0).\n+ erewrite ! loadbytes_empty by assumption. auto.\n+ unfold loadbytes. destruct H.\n  destruct (range_perm_dec m b ofs (ofs + n) Cur Readable).\n  rewrite pred_dec_true. f_equal.\n  apply getN_exten. intros. rewrite nat_of_Z_eq in H by omega.\n  apply unchanged_on_contents0; auto.\n  red; intros. apply unchanged_on_perm0; auto. \n  rewrite pred_dec_false. auto.\n  red; intros; elim n0; red; intros. apply <- unchanged_on_perm0; auto.\nQed.\n\nLemma loadbytes_unchanged_on:\n  forall m m' b ofs n bytes,\n  unchanged_on m m' ->\n  (forall i, ofs <= i < ofs + n -> P b i) ->\n  loadbytes m b ofs n = Some bytes ->\n  loadbytes m' b ofs n = Some bytes.\nProof.\n  intros. \n  destruct (zle n 0).\n+ erewrite loadbytes_empty in * by assumption. auto.\n+ rewrite <- H1. apply loadbytes_unchanged_on_1; auto. \n  exploit loadbytes_range_perm; eauto. instantiate (1 := ofs). omega. \n  intros. eauto with mem.\nQed.\n\nLemma load_unchanged_on_1:\n  forall m m' chunk b ofs,\n  unchanged_on m m' ->\n  valid_block m b ->\n  (forall i, ofs <= i < ofs + size_chunk chunk -> P b i) ->\n  load chunk m' b ofs = load chunk m b ofs.\nProof.\n  intros. unfold load. destruct (valid_access_dec m chunk b ofs Readable).\n  destruct v. rewrite pred_dec_true. f_equal. f_equal. apply getN_exten. intros. \n  rewrite <- size_chunk_conv in H4. eapply unchanged_on_contents; eauto.\n  split; auto. red; intros. eapply perm_unchanged_on; eauto.\n  rewrite pred_dec_false. auto. \n  red; intros [A B]; elim n; split; auto. red; intros; eapply perm_unchanged_on_2; eauto. \nQed.\n\nLemma load_unchanged_on:\n  forall m m' chunk b ofs v,\n  unchanged_on m m' ->\n  (forall i, ofs <= i < ofs + size_chunk chunk -> P b i) ->\n  load chunk m b ofs = Some v ->\n  load chunk m' b ofs = Some v.\nProof.\n  intros. rewrite <- H1. eapply load_unchanged_on_1; eauto with mem.\nQed.\n\nLemma store_unchanged_on:\n  forall chunk m b ofs v m',\n  store chunk m b ofs v = Some m' ->\n  (forall i, ofs <= i < ofs + size_chunk chunk -> ~ P b i) ->\n  unchanged_on m m'.\nProof.\n  intros; constructor; intros.\n- split; intros; eauto with mem.\n- erewrite store_mem_contents; eauto. rewrite PMap.gsspec. \n  destruct (peq b0 b); auto. subst b0. apply setN_outside. \n  rewrite encode_val_length. rewrite <- size_chunk_conv. \n  destruct (zlt ofs0 ofs); auto. \n  destruct (zlt ofs0 (ofs + size_chunk chunk)); auto.\n  elim (H0 ofs0). omega. auto.\nQed.\n\nLemma storebytes_unchanged_on:\n  forall m b ofs bytes m',\n  storebytes m b ofs bytes = Some m' ->\n  (forall i, ofs <= i < ofs + Z_of_nat (length bytes) -> ~ P b i) ->\n  unchanged_on m m'.\nProof.\n  intros; constructor; intros.\n- split; intros. eapply perm_storebytes_1; eauto. eapply perm_storebytes_2; eauto. \n- erewrite storebytes_mem_contents; eauto. rewrite PMap.gsspec. \n  destruct (peq b0 b); auto. subst b0. apply setN_outside. \n  destruct (zlt ofs0 ofs); auto. \n  destruct (zlt ofs0 (ofs + Z_of_nat (length bytes))); auto.\n  elim (H0 ofs0). omega. auto.\nQed.\n\nLemma alloc_unchanged_on:\n  forall m lo hi m' b, \n  alloc m lo hi = (m', b) ->\n  unchanged_on m m'.\nProof.\n  intros; constructor; intros.\n- split; intros.\n  eapply perm_alloc_1; eauto.\n  eapply perm_alloc_4; eauto. \n  eapply valid_not_valid_diff; eauto with mem.\n- injection H; intros A B. rewrite <- B; simpl.\n  rewrite PMap.gso; auto. rewrite A.  eapply valid_not_valid_diff; eauto with mem.\nQed.\n\nLemma free_unchanged_on:\n  forall m b lo hi m',\n  free m b lo hi = Some m' ->\n  (forall i, lo <= i < hi -> ~ P b i) ->\n  unchanged_on m m'.\nProof.\n  intros; constructor; intros.\n- split; intros. \n  eapply perm_free_1; eauto. \n  destruct (eq_block b0 b); auto. destruct (zlt ofs lo); auto. destruct (zle hi ofs); auto. \n  subst b0. elim (H0 ofs). omega. auto.\n  eapply perm_free_3; eauto.\n- unfold free in H. destruct (range_perm_dec m b lo hi Cur Freeable); inv H.\n  simpl. auto.\nQed.\n\nEnd UNCHANGED_ON.\n\n(** During the execution of the semantics, the semantics cannot:\n\n- Invalidate memory blocks.\n  (Remember that freeing a block does not invalidate its block identifier.)\n- Increase the max permissions of a valid block.\n  (They can decrease the max permissions, e.g. by freeing).\n- Modify memory unless they have [Max, Writable] permissions.\n\nWe prove that the step relation of each semantics is \"forward\", which captures\nprecisely these properties. *)\n\nDefinition loc_not_writable (m: mem) (b: block) (ofs: Z) : Prop :=\n  ~Mem.perm m b ofs Max Writable.\n\nRecord forward (m1 m2:mem) := {\n  forward_valid_block:\n    forall b, valid_block m1 b -> valid_block m2 b;\n  forward_max_perm:\n    forall b ofs p,\n    valid_block m1 b -> perm m2 b ofs Max p -> perm m1 b ofs Max p;\n  forward_readonly:\n    unchanged_on (loc_not_writable m1) m1 m2\n}.\n\nLemma forward_refl:\n  forall m, forward m m.\nProof. split; auto using unchanged_on_refl. Qed.\n\nLemma forward_trans:\n  forall m1 m2 m3, \n  forward m1 m2 -> forward m2 m3 -> forward m1 m3.\nProof.\n  intros m1 m2 m3 [V1 P1 RO1] [V2 P2 RO2]; split; auto. split.\n  * intros. erewrite unchanged_on_perm by eauto.\n    eapply unchanged_on_perm; eauto. unfold loc_not_writable in *; eauto.\n  * intros. etransitivity; [|eapply unchanged_on_contents; eauto].\n    eapply unchanged_on_contents; eauto.\n    unfold loc_not_writable in *; eauto using perm_valid_block.\n    now erewrite <-unchanged_on_perm by eauto using perm_valid_block.\nQed.\n\nLemma unchanged_trans:\n  forall P m1 m2 m3,\n  unchanged_on P m1 m2 -> unchanged_on P m2 m3 ->\n  forward m1 m2 -> unchanged_on P m1 m3.\nProof.\n  intros; split.\n  { intros b ofs k p ??. assert (valid_block m2 b) by (now apply H1).\n    now rewrite (unchanged_on_perm _ _ _ H),\n      (unchanged_on_perm _ _ _ H0) by auto. }\n  intros b ofs ??. assert (perm m2 b ofs Cur Readable).\n  { eapply H; eauto using perm_valid_block. }\n  now rewrite <-(unchanged_on_contents _ _ _ H),\n    <-(unchanged_on_contents _ _ _ H0) by auto.\nQed.\n\nLemma store_forward:\n  forall m b ofs v ch m',\n  store ch m b ofs v = Some m' -> forward m m'.\nProof.\n  split; eauto using store_valid_block_1, perm_store_2.\n  eapply store_unchanged_on; eauto.\n  intros i ? []. eapply perm_cur_max, store_valid_access_3; eauto.\nQed.\n\nLemma storev_forward:\n  forall m vaddr v ch m',\n  storev ch m vaddr v = Some m' -> forward m m'.\nProof.\n  now destruct vaddr; eauto using store_forward.\nQed.\n\nLemma storebytes_forward:\n  forall m b ofs bytes m',\n  storebytes m b ofs bytes = Some m' -> forward m m'.\nProof.\n  split; eauto using storebytes_valid_block_1, perm_storebytes_2.\n  eapply storebytes_unchanged_on; eauto.\n  intros i ? []. eapply perm_cur_max, storebytes_range_perm; eauto.\nQed.\n\nLemma alloc_forward:\n  forall m lo hi m' b,\n  alloc m lo hi = (m',b) -> forward m m'.\nProof.\n  split; intros.\n  * eauto using valid_block_alloc.\n  * eapply perm_alloc_4; eauto.\n    intros ->; eapply fresh_block_alloc; eauto.\n  * eauto using alloc_unchanged_on.\nQed.\n\nLemma free_forward:\n  forall b z0 z m m',\n  free m b z0 z = Some m' -> forward m m'.\nProof.\n  split; eauto using valid_block_free_1, perm_free_3.\n  eapply free_unchanged_on; eauto.\n  intros i ? []. eapply perm_cur_max, perm_implies with Freeable.\n  eapply free_range_perm; eauto. constructor.\nQed.\n\nLemma free_list_forward:\n  forall l m m',\n  free_list m l = Some m' -> forward m m'.\nProof.\n  induction l as [|[[??]?]]; simpl; intros.\n  { inv H. apply forward_refl. }\n  destruct (free m b z z0) eqn:?; inv H.\n  eauto using forward_trans, free_forward.\nQed.\n\nLemma forward_nextblock:\n  forall m m',\n  forward m m' -> (nextblock m <= nextblock m')%positive.\nProof.\n  intros. apply Pos.le_nlt; intros ?.\n  now apply (Pos.lt_irrefl (nextblock m')), H.\nQed.\nEnd Mem.\n\nNotation mem := Mem.mem.\n\nGlobal Opaque Mem.alloc Mem.free Mem.store Mem.load Mem.storebytes Mem.loadbytes.\n\nHint Resolve\n  Mem.valid_not_valid_diff\n  Mem.perm_implies\n  Mem.perm_cur\n  Mem.perm_max\n  Mem.perm_valid_block\n  Mem.range_perm_implies\n  Mem.range_perm_cur\n  Mem.range_perm_max\n  Mem.valid_access_implies\n  Mem.valid_access_valid_block\n  Mem.valid_access_perm\n  Mem.valid_access_load\n  Mem.load_valid_access\n  Mem.loadbytes_range_perm\n  Mem.valid_access_store\n  Mem.perm_store_1\n  Mem.perm_store_2\n  Mem.nextblock_store\n  Mem.store_valid_block_1\n  Mem.store_valid_block_2\n  Mem.store_valid_access_1\n  Mem.store_valid_access_2\n  Mem.store_valid_access_3\n  Mem.storebytes_range_perm\n  Mem.perm_storebytes_1\n  Mem.perm_storebytes_2\n  Mem.storebytes_valid_access_1\n  Mem.storebytes_valid_access_2\n  Mem.nextblock_storebytes\n  Mem.storebytes_valid_block_1\n  Mem.storebytes_valid_block_2\n  Mem.nextblock_alloc\n  Mem.alloc_result\n  Mem.valid_block_alloc\n  Mem.fresh_block_alloc\n  Mem.valid_new_block\n  Mem.perm_alloc_1\n  Mem.perm_alloc_2\n  Mem.perm_alloc_3\n  Mem.perm_alloc_4\n  Mem.perm_alloc_inv\n  Mem.valid_access_alloc_other\n  Mem.valid_access_alloc_same\n  Mem.valid_access_alloc_inv\n  Mem.range_perm_free\n  Mem.free_range_perm\n  Mem.nextblock_free\n  Mem.valid_block_free_1\n  Mem.valid_block_free_2\n  Mem.perm_free_1\n  Mem.perm_free_2\n  Mem.perm_free_3\n  Mem.valid_access_free_1\n  Mem.valid_access_free_2\n  Mem.valid_access_free_inv_1\n  Mem.valid_access_free_inv_2\n  Mem.unchanged_on_refl\n: mem.\n", "meta": {"author": "robbertkrebbers", "repo": "compcert", "sha": "524c26591e884a3676a5fbef77d8c79193955b82", "save_path": "github-repos/coq/robbertkrebbers-compcert", "path": "github-repos/coq/robbertkrebbers-compcert/compcert-524c26591e884a3676a5fbef77d8c79193955b82/common/Memory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.26430334708502}}
{"text": "(** * NotModifyDec.v : Decision procedure for determining the \n   variables that a progam (not) modifies *)\n\nSet Implicit Arguments.\n\nRequire Export SemTheory.\n\n\nModule Make (Sem:SEM). \n \n Module SemTh := SemTheory.Make Sem.\n Export SemTh.\n\n Definition modify_base X (i:I.baseInstr) := \n   match i with\n   | I.Assign t x e =>\n      if E.eqb e x then X else Vset.add x X\n   | I.Random t x _ => Vset.add x X\n   | I.IAssert e => X\n   end.\n\n Section MODIFY.\n\n  Variable E: env.\n\n  Variable mod_info :  forall t (f:Proc.proc t), option Vset.t.\n\n  Hypothesis mod_info_correct : forall t (f:Proc.proc t) GM,\n   mod_info f = Some GM ->  \n   (forall x, Vset.mem x GM -> Var.is_global x) /\\\n   (exists L, (forall x, Vset.mem x L -> Var.is_local x) /\\ \n    Modify E (Vset.union L GM) (proc_body E f)).\n   \n  Fixpoint modify_i_1 (X:Vset.t) (i:I.instr) {struct i} : option Vset.t :=\n   match i with\n   | I.Instr i  => Some (modify_base X i)\n   | I.Cond _ c1 c2 => \n     opt_app (fold_left_opt modify_i_1 c1) (fold_left_opt modify_i_1 c2 X)\n   | I.While _ c => fold_left_opt modify_i_1 c X\n   | I.Call t d f _ => \n     match mod_info f with\n     | Some GM => Some (Vset.add d (Vset.union GM X))\n     | None => None\n     end\n    end.\n\n  Definition modify_1 X (c:cmd) := fold_left_opt modify_i_1 c X.\n \n  Lemma modify_1_correct_aux : \n   (forall i X, spec_opt (fun R => Modify E R [i] /\\ X [<=] R) \n    (modify_i_1 X i)) /\\\n   (forall c X, spec_opt (fun R => Modify E R c /\\ X [<=] R) \n    (modify_1 X c)).\n  Proof.\n   unfold modify_1; intros; apply I.cmd_ind2; simpl; intros.\n   (* baseInstr *)\n   destruct i; simpl.\n   generalize (E.eqb_spec e v); destruct (E.eqb e v); \n    intros; split; auto with set.\n   rewrite H; apply Modify_weaken with Vset.empty; auto with set.\n   apply Modify_assign_same.\n   apply Modify_weaken with (Vset.singleton v).\n   apply Modify_assign.\n   apply Vset.subset_complete; intro; rewrite VsetP.add_spec.\n   intros H1; left; apply (Vset.singleton_complete _ _ H1).\n   split; auto with set.\n   apply Modify_weaken with (Vset.singleton v).\n   apply Modify_random.\n   apply Vset.subset_complete; intro; rewrite VsetP.add_spec.\n   intros H1; left; apply (Vset.singleton_complete _ _ H1).\n\n   split; [ | auto with set].\n   apply Modify_weaken with Vset.empty.\n   apply Modify_assert.\n   auto with set.  \n   \n   (* Cond *)\n   assert (H0' := H0 X); clear H0.\n   destruct (fold_left_opt modify_i_1 c2 X) as [R2|]; try exact I.\n   assert (H' := H R2); clear H.\n   unfold opt_app; destruct (fold_left_opt modify_i_1 c1 R2) as [R1|]; \n    try exact I.\n   destruct H0'; destruct H'; split.\n   apply Modify_weaken with (Vset.union R1 R2).\n   apply Modify_cond; auto.\n   rewrite VsetP.union_sym; rewrite VsetP.subset_union; auto with set.\n   apply VsetP.subset_trans with R2; auto. \n   \n   (* While *)\n   assert (H' := H X); destruct (fold_left_opt modify_i_1 c X); destruct H'; \n    split; auto.\n   apply Modify_while; auto.\n\n   (* Call *)\n   generalize (@mod_info_correct _ f).\n   destruct (mod_info f) as [GM | ]; simpl; trivial; split;auto with set.\n   destruct (H _ (eq_refl _)) as (H2,(L,(H0,H1))).\n   apply Modify_weaken with  (Vset.add x GM).\n   eapply Modify_weaken;[ apply Modify_call with (1:=H1) | ].\n   apply VsetP.subset_add_ctxt.\n   apply Vset.subset_complete; intros.\n   assert (W:=get_globals_spec _ _ H3).\n   assert (Vset.mem x0 (Vset.union L GM)).\n   apply Vset.subset_correct with \n    (1:= get_globals_subset(Vset.union L GM)); trivial.\n   rewrite VsetP.union_spec in H4; destruct H4; trivial.\n   apply H0 in H4; unfold Var.is_local in H4; rewrite W in H4; discriminate.\n   apply VsetP.subset_add_ctxt;auto with set.\n\n   (* nil *)\n   split; auto with set.\n   apply Modify_weaken with Vset.empty; auto with set.\n   apply Modify_nil.\n   \n   (* cons *)\n   assert (H':= H X); clear H; destruct (modify_i_1 X i) as [Ri|]; try exact I; simpl.\n   assert (H0' := H0 Ri); clear H0; unfold opt_app; \n     destruct (fold_left_opt modify_i_1 c Ri) as [Rc|]; try exact I; simpl in *.\n   destruct H'; destruct H0'; split.\n   apply Modify_weaken with (Vset.union Ri Rc); auto with set.\n   apply Modify_cons; auto.\n   rewrite VsetP.subset_union; auto with set.\n   apply VsetP.subset_trans with Ri; auto.\n  Qed.\n \n  Definition modify_2 := modify_1 Vset.empty.\n \n  Lemma modify_2_correct : \n    forall c M, modify_2 c = Some M -> Modify E M c.\n  Proof.\n    destruct modify_1_correct_aux;unfold modify_2;intros.\n    assert (W:=H0 c Vset.empty);rewrite H1 in W;destruct W;trivial.\n  Qed.\n\n End MODIFY.\n\n Section LOSSLESS.\n\n  Variable E: env.\n\n  Variable lossless_info :  forall t, Proc.proc t ->  bool.\n\n  Hypothesis lossless_info_correct : forall t (f:Proc.proc t),\n   lossless_info f -> lossless E (proc_body E f).\n\n  Definition list_forall := Eval cbv beta delta [forallb andb ifb] in forallb.\n  \n  Fixpoint is_lossless_i_1 (i:I.t) : bool :=\n   match i with\n   | I.Instr (I.Assign _ _ _) => true\n   | I.Instr (I.Random _ _ _) => true\n   | I.Cond _ c1 c2 => \n     if list_forall is_lossless_i_1 c1 then list_forall is_lossless_i_1 c2\n     else false\n   | I.Call t d f arg => lossless_info f\n   | _ => false\n  end.\n \n  Definition is_lossless_1 : cmd -> bool := list_forall is_lossless_i_1.\n\n  Lemma is_lossless_1_correct_aux : \n   (forall i, is_lossless_i_1 i -> lossless E [i]) /\\ \n   (forall c, is_lossless_1 c -> lossless E c).\n  Proof.\n   apply I.cmd_ind2; simpl; intros; trivialb.\n   destruct i; auto using lossless_assign, lossless_random; discriminate.\n   unfold is_lossless_1 in *.\n   destruct (list_forall is_lossless_i_1 c1); trivialb.\n   destruct (list_forall is_lossless_i_1 c2); trivialb.\n   apply lossless_cond; trivial.\n   apply lossless_call; auto.\n   apply lossless_nil.\n   destruct (is_lossless_i_1 i); trivialb.\n   apply lossless_cons; trivial.\n  Qed.\n\n  Lemma is_lossless_1_correct : forall c, is_lossless_1 c -> lossless E c.\n  Proof. \n   destruct is_lossless_1_correct_aux; trivial.\n  Qed.\n\n End LOSSLESS.\n\n Section NOTMODIFY.\n \n  Variable E : env.\n\n  Variable pi : eq_refl_info E.\n\n  Definition pi_to_mod_info := fun t f => \n    match @pi t f with \n    | Some i => Some (pi_mod i) \n    | _ => None \n    end.\n\n  Definition modify_i := modify_i_1 pi_to_mod_info.\n\n  Definition modify X (c:cmd) := fold_left_opt modify_i c X.\n \n  Lemma modify_correct_aux : \n   (forall i X, spec_opt (fun R => Modify E R [i] /\\ X [<=] R) \n    (modify_i X i)) /\\\n   (forall c X, spec_opt (fun R => Modify E R c /\\ X [<=] R) \n    (modify X c)).\n  Proof.\n   apply modify_1_correct_aux.\n   unfold pi_to_mod_info;intros t f GM.\n   destruct (pi f);[ | discriminate].\n   intros Heq;injection Heq;intros;subst;split.\n   apply mod_global. apply mod_spec.\n  Qed.\n\n  Lemma modify_i_correct_subset : forall i X R,\n   modify_i X i = Some R ->\n   Modify E R [i] /\\ X [<=] R.\n  Proof.\n   destruct modify_correct_aux as (H1,H2); intros i Y R Heq.\n   assert (H3 := H1 i Y); rewrite Heq in H3; trivial.\n  Qed.\n  \n  Lemma modify_i_correct : forall i X R,\n   modify_i X i = Some R ->\n   Modify E R [i].\n  Proof.\n   intros i X R H; destruct (modify_i_correct_subset _ _ H); trivial.\n  Qed.\n  \n  Lemma modify_correct_subset : forall c X R, \n   modify X c = Some R ->\n   Modify E R c /\\ X [<=] R.\n  Proof.\n   destruct modify_correct_aux as (H1,H2); intros c Y R Heq.\n   assert (H3 := H2 c Y); rewrite Heq in H3; trivial.\n  Qed.\n  \n  Lemma modify_correct : forall c X R, \n   modify X c = Some R ->\n   Modify E R c.\n  Proof.\n   intros c Y R H; destruct (modify_correct_subset _ _ H); trivial.\n  Qed.\n  \n  Definition is_notmodify X c := \n   match modify Vset.empty c with\n   | Some X' => Vset.disjoint X X'\n   | _ => false\n   end.\n\n  Definition is_notmodify_i X i := \n   match modify_i Vset.empty i with\n   | Some X' => Vset.disjoint X X'\n   | _ => false\n   end.\n\n  Lemma is_notmodify_correct : forall X c,\n   is_notmodify X c -> exists M, Modify E M c /\\ Vset.disjoint X M.\n  Proof.\n   unfold is_notmodify; intros X c.\n   case_eq (modify Vset.empty c); intros; trivialb.\n   exists t; split; trivial.\n   eapply modify_correct; eauto.\n  Qed.\n  \n  Lemma is_notmodify_i_correct : forall X i,\n   is_notmodify_i X i -> exists M, Modify E M [i] /\\ Vset.disjoint X M.\n  Proof.\n   unfold is_notmodify_i; intros X i.\n   case_eq (modify_i Vset.empty i); intros; trivialb.\n   exists t; split; trivial.\n   eapply modify_i_correct; eauto.\n  Qed.\n\n\n  (** Deciding lossless *)\n \n  Definition pi_to_lossless_info := fun t f => \n    match @pi t f with \n    | Some i =>  pi_lossless i\n    | _ => false\n    end.\n\n  Lemma pi_to_lossless_info_correct : forall t (f:Proc.proc t),\n   pi_to_lossless_info f -> lossless E (proc_body E f).\n  Proof.\n   unfold pi_to_lossless_info;intros.\n   destruct (pi f);[ | discriminate].\n   apply pi_lossless_spec with p;trivial.\n  Qed.\n\n  Definition is_lossless_i := is_lossless_i_1 pi_to_lossless_info.\n \n  Definition is_lossless : cmd -> bool := is_lossless_1 pi_to_lossless_info.\n\n  Lemma is_lossless_correct_aux : \n   (forall i, is_lossless_i i -> lossless E [i]) /\\ \n   (forall c, is_lossless c -> lossless E c).\n  Proof.\n   apply is_lossless_1_correct_aux;apply pi_to_lossless_info_correct.\n  Qed.\n  \n  Lemma is_lossless_i_correct : forall i, is_lossless_i i -> lossless E [i].\n  Proof. \n   destruct is_lossless_correct_aux; trivial.\n  Qed.\n  \n  Lemma is_lossless_correct : forall c, is_lossless c -> lossless E c.\n  Proof. \n   destruct is_lossless_correct_aux; trivial.\n  Qed.\n\n End NOTMODIFY.\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/NotModifyDec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.26430334136690964}}
{"text": "(* This file is a monster. Working with type classes is great, but the mechanisms for\n   creating an instance are currently very fragile. One major piece of work will be to\n   make this easier. Ideally, this file should not be larger than a few tens of lines\n   at most. *)\n\nRequire Import ILogic ILInsts SepAlg BILogic BILInsts IBILogic SepAlgMap Maps String Rel.\nRequire Import RelationClasses Setoid Morphisms Program. \nRequire Import MapInterface MapFacts.\nRequire Import Charge.Open.Open.\nRequire Import Charge.Open.Stack Lang OpenILogic Pure ILEmbed PureInsts.\nRequire Import UUSepAlg SepAlgInsts HeapArr.\n\nRequire Import ExtLib.Core.RelDec.\nRequire Import ExtLib.Data.String.\n\nLocal Existing Instance ILPre_Ops.\nLocal Existing Instance ILPre_ILogic.\n\nLocal Existing Instance ILFun_Ops.\nLocal Existing Instance ILFun_ILogic.\nLocal Existing Instance SAIBIOps.\nLocal Existing Instance SAIBILogic.\nLocal Existing Instance BILPre_Ops.\nLocal Existing Instance IBILPreLogic.\nLocal Existing Instance BILFun_Ops.\nLocal Existing Instance IBILFunLogic.\n\nLocal Existing Instance MapSepAlgOps.\nLocal Existing Instance MapSepAlg.\nLocal Existing Instance MapEquiv.\nLocal Existing Instance EquivPreorder.\nLocal Existing Instance UUMapSepAlg.\nLocal Existing Instance SepAlgOps_prod.\nLocal Existing Instance SepAlg_prod.\nLocal Existing Instance UUSepAlg_prod.\n\nDefinition heap_ptr := Map [ptr * field, val].\n\nDefinition heap := (heap_ptr * heap_arr)%type.\n\nDefinition heap_ptr_unit : heap_ptr := @map_unit _ _ _ val.\nDefinition heap_unit : heap := (heap_ptr_unit, heap_arr_unit).\n\nDefinition heap_add_ptr (h : heap) (p : ptr) (f : field) (v : val) : heap :=\n  (add (p, f) v (fst h), snd h).\nDefinition heap_add_arr (h : heap) (n m : nat) (v : val) : heap :=\n  (fst h, add (n, m) v (snd h)).\n\n\nInstance RelHeapPtr : Rel heap_ptr := _.\nInstance PreorderHeapPtr : PreOrder (@rel heap_ptr RelHeapPtr) := _.\nInstance HeapPtrSepAlgOps : SepAlgOps heap_ptr := _.\nInstance SepAlgHeapPtr : SepAlg heap_ptr := _.\nInstance UUSepAlgHeapPtr : UUSepAlg heap_ptr := _.\n\n(*\nInstance SepAlgArrPtr : SepAlg heap_arr := _.\n\n\nInstance RelHeap : Rel heap := _.\nInstance PreorderHeap : PreOrder (@rel heap RelHeap) := _.\nInstance HeapSepAlgOps : SepAlgOps heap := _.\nInstance SepAlgHeap : SepAlg heap := _.\nInstance UUSepAlgHeap : UUSepAlg heap := _.\n*)\n\nInstance HeapSepAlgOps : SepAlgOps heap := _.\nInstance UUSepAlgHeap : UUSepAlg heap := _.\n\nDefinition asn := ILPreFrm Prog_sub (ILPreFrm ge (ILPreFrm (@rel heap subheap) Prop)).\n\nInstance ILogicOpsAsn : ILogicOps asn := _.\nInstance BILogicOpsAsn : BILOperators asn. Admitted.\nInstance BILogicAsn : IBILogic asn. Admitted.\n\nLocal Existing Instance EmbedILPreDropOp.\nLocal Existing Instance EmbedILPreDrop.\nLocal Existing Instance EmbedOpPropProp.\nLocal Existing Instance EmbedPropProp.\n\nInstance EmbedAsnPropOp : EmbedOp Prop asn := _.\nInstance EmbedAsnProp : Embed Prop asn := _.\n\nInstance RelDec_var : RelDec (@eq var) := _.\n\nDefinition sasn := (Stack.stack var val) -> asn.\n\nInstance ILogicOpsSAsn : ILogicOps sasn := _.\nInstance BILogicOpsSAsn : BILOperators sasn := _.\nInstance BILogicSAsn : IBILogic sasn := _.\n\nLocal Existing Instance EmbedILFunDropOp.\nLocal Existing Instance EmbedILFunDrop.\nLocal Existing Instance EmbedILFunOp.\nLocal Existing Instance EmbedILFun.\nLocal Existing Instance EmbedILPreOp.\nLocal Existing Instance EmbedILPre.\n\nLocal Existing Instance SABIOps.\nLocal Existing Instance SABILogic.\nLocal Existing Instance pureop_bi_sepalg.\n\nInstance EmbedSasnPureOp : EmbedOp vlogic sasn := _.\nInstance EmbedSasnPure : Embed vlogic sasn := _.\n\nRequire Import SpecLogic.\n\nInstance EmbedAsnSpecOp  : EmbedOp spec asn := _.\nInstance EmbedAsnSpec    : Embed spec asn := _.\nInstance EmbedSAsnSpecOp : EmbedOp spec sasn := _.\nInstance EmbedSAsnSpec   : Embed spec sasn := _.\n\nLocal Existing Instance pure_embed_pre_drop.\nLocal Existing Instance pure_embed_pre.\nLocal Existing Instance pure_embed_fun_drop.\nLocal Existing Instance pure_embed_fun.\nLocal Existing Instance pure_ibi_sepalg.\nLocal Existing Instance pureop_pure_ibi_sepalg.\nLocal Existing Instance pure_ibi_embed_drop.\nLocal Existing Instance PureBILPre.\nLocal Existing Instance PureBILPreOp.\nLocal Existing Instance PureBILFun.\nLocal Existing Instance PureBILFunOp.\n\nPrint pureop_bi_sepalg.\n(*\nLocal Instance PureOpAsn1 : @PureOp asn1 := _.\nLocal Instance PureAsn1 : Pure PureOpAsn1 := _.\nLocal Instance PureOpAsn2 : @PureOp asn2 := _.\nLocal Instance PureAsn2 : Pure PureOpAsn2 := _.\nLocal Instance PureOpAsn : @PureOp asn := _.\nLocal Instance PureAsn : Pure PureOpAsn := _.\nLocal Instance PureOpSasn : @PureOp sasn := _.\nLocal Instance PureSAsn : Pure PureOpSasn := _.\n*)\n\n(*\nInstance pure_prop (p : Prop) : pure (@embed Prop sasn _ p) := _.\nInstance pure_vlogic (p : vlogic) : pure (@embed vlogic sasn _ p) := _.\nInstance pure_spec_asn (p : spec) : pure (@embed spec asn _ p) := _.\nInstance pure_spec (p : spec) : pure (@embed spec sasn _ p) := _.\n*)\n\nLocal Transparent ILPre_Ops.\n\nDefinition mk_asn (f: Program -> nat -> heap -> Prop)\n  (Hnat: forall P k h, f P (S k) h -> f P k h)\n  (HProg: forall P P' k h, Prog_sub P P' -> f P k h -> f P' k h)\n  (Hheap: forall P k h h', subheap h h' -> f P k h -> f P k h') : asn.\n  refine (mkILPreFrm (fun P => mkILPreFrm (fun k => mkILPreFrm (fun h => f P k h) _) _) _).\nProof.\n  intros P P' HP Hn h H; simpl.\n  eapply HProg; eassumption.\nGrab Existential Variables.\n  assert (forall k' k P h, k' >= k -> f P k' h -> f P k h) as Hnat'.\n  intros k k' P' h Hkk' S.  \n  induction Hkk'. assumption.\n  apply IHHkk'. apply Hnat. assumption.\n  intros n n' Hn'' p S; simpl in *. eapply Hnat'; eassumption.\n  intros h h' Hh H. eapply Hheap; eassumption.\nDefined.\n\nProgram Definition pointsto_aux (x : ptr) (f : field) (v : val) : asn :=\n  mk_asn (fun P k h => subheap (add (x, f) v (empty val)) (fst h)) _ _ _.\nNext Obligation.\n  destruct h, h'; simpl in *.\n  apply subheap_prod in H as [H _].\n  setoid_rewrite H in H0. assumption.\nQed.\n\nDefinition pointsto (p : val) (f : field) (v : val) : asn :=\n  (p <> null) /\\\\ pointsto_aux (val_to_ptr p) f v.\n\nProgram Definition pointsto_arr_element_aux (x : val) (path : list val) (v : val) : asn :=\n  mk_asn (fun P k h => exists (h' : heap) , \n                         subheap h' h /\\\n                         find_heap_arr (val_to_nat x)\n                                       (List.map val_to_nat path) (snd h') = \n                         Some v) _ _ _.\nNext Obligation.\n  exists H; split; [assumption | reflexivity].\nQed.\nNext Obligation.\n  exists H0; split; [assumption | reflexivity].\nQed.\nNext Obligation.\n  exists H0; split; [etransitivity; eassumption | reflexivity].\nQed.\n\nDefinition pointsto_arr_element (x i : val) (v : val) : asn := \n  pointsto_arr_element_aux x (i::nil) v.\n\nRequire Import ZArith.\n\nFixpoint pointsto_arr_aux (x : val) (n : nat) (vs : list val) : asn :=\n  match vs with\n    | nil   => empSP\n    | v::vs => pointsto_arr_element x (vint (Z_of_nat n)) v ** \n                                    pointsto_arr_aux x (S n) vs\n  end.\n\nLemma firstn_nil {A : Type} (n : nat) : firstn n (@nil A) = nil.\nProof.\n  destruct n; simpl; reflexivity.\nQed.\n\nLemma skipn_nil {A : Type} (n : nat) : skipn n (@nil A) = nil.\nProof.\n  destruct n; simpl; reflexivity.\nQed.\n\nLemma firstn_cons {A : Type} (n : nat) (x : A) (xs : list A) (H : n > 0) :\n  firstn n (x :: xs) = x :: (firstn (n - 1) xs).\nProof.\n  destruct n; simpl.\n  + omega.\n  + replace (n - 0) with n by omega; reflexivity.\nQed.\n\nLemma firstn_app1 {A : Type} (n : nat) (xs ys : list A) (H : n <= List.length xs) :\n  firstn n (xs ++ ys) = firstn n xs.\nProof.\n  generalize dependent n; induction xs; simpl in *; intros.\n  + assert (n = 0) by omega; clear H; subst; simpl; reflexivity.\n  + destruct n; simpl in *; [reflexivity|].\n    f_equal. apply IHxs. omega.\nQed.\n  \nLemma firstn_app2 {A : Type} (n : nat) (xs ys : list A) (H : n >= List.length xs) :\n  firstn n (xs ++ ys) = xs++(firstn (n - List.length xs) ys).\nProof.\n  generalize dependent n; induction xs; simpl in *; intros.\n  + replace (n - 0) with n by omega; reflexivity.\n  + destruct n; simpl in *; [omega|].\n    f_equal. apply IHxs. omega.\nQed.\n  \nLemma skipn_cons {A : Type} (n : nat) (x : A) (xs : list A) (H : n > 0) :\n  skipn n (x :: xs) = skipn (n - 1) xs.\nProof.\n  destruct n; simpl.\n  + omega.\n  + replace (n - 0) with n by omega; reflexivity.\nQed.\n\nLemma skipn_drop {A : Type} (n : nat) (xs : list A) (H : n >= List.length xs) :\n  skipn n xs = nil.\nProof.\n  generalize dependent xs; induction n; simpl; intros.\n  + destruct xs; simpl in *; [reflexivity | omega].\n  + destruct xs; [reflexivity|].\n    apply IHn; simpl in *; omega.\nQed.\n\nLemma skipn_length {A : Type} (n : nat) (vs : list A) :\n  List.length (skipn n vs) = (List.length vs - n).\nProof.\n  generalize dependent n; induction vs; simpl.\n  + destruct n; simpl; reflexivity.\n  + destruct n; simpl; [reflexivity|].\n    rewrite IHvs. reflexivity.\nQed.\n      \n\n(*\nLemma pointsto_arr_aux_app (x : val) (n : nat) (xs ys : list val) :\n  pointsto_arr_aux x n (xs++ys) -|- pointsto_arr_aux x n xs ** pointsto_arr_aux x (n + List.length xs) ys.\nProof.\n  generalize dependent n; induction xs; simpl in *; intros.\n  + rewrite sepSPC, empSPR. replace (n + 0) with n by omega. reflexivity.\n  + rewrite IHxs. \n    replace (n + S (Datatypes.length xs)) with (S n + Datatypes.length xs) by omega.\n    rewrite sepSPA. reflexivity.\nQed.\n\nLemma pointsto_arr_aux_split (x : val) (n m : nat) (vs : list val) (H : n < m) :\n  pointsto_arr_aux x n vs -|- pointsto_arr_aux x n (firstn (m - n) vs) **\n                              pointsto_arr_aux x m (skipn (m - n) vs).\nProof.\n  rewrite <- (firstn_skipn (m - n) vs) at 1.\n  rewrite pointsto_arr_aux_app.\n  rewrite firstn_length.\n  destruct (Min.min_dec (m - n) (Datatypes.length vs)) as [H1 | H1]; rewrite H1.\n  + replace (n + (m - n)) with m by omega; reflexivity.\n  + rewrite skipn_drop; simpl; [reflexivity|].\n    setoid_rewrite <- H1.\n    assert (min (m - n) (Datatypes.length vs) <= m - n); [|omega].\n    apply Min.le_min_l.\nQed.\n\nDefinition pointsto_arr (x n m : val) (vs : list val) : asn :=\n  let n' := val_to_nat n in\n  let m' := val_to_nat m in\n  (n' <= m' /\\ List.length vs = S (m' - n')) /\\\\ pointsto_arr_aux x n' vs.\n\n(* Gregory should be able to pull this off with his cancellation magic. *)\n\nLemma embed_and_admit (p q : asn) (P Q : Prop) : \n  (P /\\\\ p) ** (Q /\\\\ q) -|- P /\\\\ Q /\\\\ p ** q.\nProof.\n  admit.\nQed.\n\n\nLemma pointsto_arr_split (x i j k : val) (vs : list val) \n      (Hij : val_to_nat i <= val_to_nat j) \n      (Hjk : val_to_nat j < val_to_nat k) :\n  pointsto_arr x i k vs -|- pointsto_arr x i j (firstn (S ((val_to_nat j) - \n                                                           (val_to_nat i))) vs) ** \n                            pointsto_arr x (vint (Z_of_nat (S (val_to_nat j)))) k \n                                         (skipn (S ((val_to_nat j) - (val_to_nat i))) vs).\nProof.\n  unfold pointsto_arr.\n   replace (val_to_nat (Z.of_nat (S (val_to_nat j)))) with (S (val_to_nat j)) by\n    (destruct j; unfold val_to_nat; simpl in *; try reflexivity;\n     rewrite SuccNat2Pos.id_succ; reflexivity).\n   split.\n  + apply lpropandL; intros [H1 H2].\n    rewrite embed_and_admit.\n    apply lpropandR. {\n      split; [assumption|].\n      rewrite firstn_length.\n      simpl. setoid_rewrite H2.\n      f_equal; apply Min.min_l; omega.\n    }\n    apply lpropandR. {\n      split; [omega|].\n      rewrite skipn_length; omega.\n    }\n    rewrite (pointsto_arr_aux_split x (val_to_nat i) (S(val_to_nat j))); [|omega].\n    replace (S (val_to_nat j) - val_to_nat i) with (S (val_to_nat j - val_to_nat i)) by omega.\n    reflexivity.\n\n  + rewrite embed_and_admit.\n    apply lpropandL; intros [H1 H2].\n    apply lpropandL; intros [H3 H4].\n    apply lpropandR. split; [omega|].\n    rewrite <- (firstn_skipn (S (val_to_nat j - val_to_nat i)) vs), app_length; omega.\n    etransitivity; [|rewrite (pointsto_arr_aux_split x (val_to_nat i) (S(val_to_nat j))); [|omega]]; [|reflexivity]. \n    replace (S (val_to_nat j) - val_to_nat i) with (S (val_to_nat j - val_to_nat i)) by omega.\n    reflexivity.\nQed.\n\nTransparent ILogicOpsAsn.\nTransparent BILOperatorsAsn.\nTransparent BILPre_Ops.\nTransparent EmbedAsnPropOp.\nTransparent EmbedILPreDropOp.\nOpaque MapSepAlgOps.\nOpaque SepAlgOps_prod.\n\nLemma pointsto_arr_pointsto_element_lst (x i : val) (vs : list val) :\n  pointsto_arr x i i vs |-- Exists v, vs = v::nil /\\\\ pointsto_arr_element x i v.\nProof.\n  unfold pointsto_arr, pointsto_arr_element.\n  apply lpropandL; intros [H1 H2].\n  destruct vs; simpl in H2; [omega|].\n  destruct vs; simpl in H2; [|omega].\n  cbv [pointsto_arr_aux].\n  rewrite empSPR.\n  intros P n h H.\n  simpl in *.\n  destruct H as [h' [Hh H]].\n  exists v; split; simpl; [reflexivity|].\n  exists h'; split; [assumption|].\n  destruct h'; simpl in *.\n  assert (val_to_nat (Z.of_nat (val_to_nat i)) = val_to_nat i). {\n      clear H.\n      induction i; simpl in *; unfold val_to_nat in *; simpl in *; try reflexivity.\n      rewrite Nat2Z.id; reflexivity.\n    }\n  rewrite <- H0. apply H.\nQed.\n\nLemma pointsto_arr_pointsto_element (x i : val) (v : val) :\n  pointsto_arr x i i (v::nil) -|- pointsto_arr_element x i v.\nProof.\n  split.\n  + rewrite pointsto_arr_pointsto_element_lst.\n    apply lexistsL; intro v'.\n    apply lpropandL; intros H; inversion H; subst; clear H.\n    reflexivity.\n  + unfold pointsto_arr_element, pointsto_arr.\n    apply lpropandR; [split; [reflexivity | simpl; omega]|].\n    cbv [pointsto_arr_aux]. rewrite empSPR.\n    intros P n h H; simpl in *.\n    destruct H as [h' [Hh H]].\n    exists h'; split; [apply Hh|].\n    assert (val_to_nat (Z.of_nat (val_to_nat i)) = val_to_nat i). {\n      clear H.\n      induction i; simpl in *; unfold val_to_nat in *; simpl in *; try reflexivity.\n      rewrite Nat2Z.id; reflexivity.\n    }\n    rewrite H0. apply H.\nQed.\n\nDefinition update {A : Type} (lst : list A) (n : nat) (p : A) :=\n  firstn n lst ++ (p::(skipn (n+1) lst)).\n\nLemma pointsto_arr_update (x i j k : val) (vs : list val) (v : val) \n      (Hij : val_to_nat i <= val_to_nat j) \n      (Hjk : val_to_nat j < val_to_nat k) :\n  pointsto_arr x i k (update vs (val_to_nat j - val_to_nat i) v) -|- \n  pointsto_arr x i j (firstn ((val_to_nat j) - \n                              (val_to_nat i)) vs) ** \n  pointsto_arr_element k j v **\n  pointsto_arr x (vint (Z_of_nat (S (val_to_nat j)))) k \n  (skipn (S ((val_to_nat j) - (val_to_nat i))) vs).\nProof.\n  rewrite pointsto_arr_split with (j := S (val_to_nat j)). try eassumption.\n  unfold update.\n  replace (firstn (val_to_nat j - val_to_nat i) vs ++\n                  v :: skipn (val_to_nat j - val_to_nat i + 1) vs) with\n  ((firstn (val_to_nat j - val_to_nat i) vs ++\n         (v::nil)) ++ (skipn (val_to_nat j - val_to_nat i + 1) vs)) \n    by (rewrite <- app_assoc; reflexivity).\n  rewrite firstn_app1.\n  rewrite firstn_app2.\n  replace (S (val_to_nat j - val_to_nat i) -\n         Datatypes.length (firstn (val_to_nat j - val_to_nat i) vs)) with 1.\n  replace (firstn 1 (v :: nil)) with (v :: nil) by reflexivity.\n  cbv delta [firstn].\nSearchAbout firstn.\n  simpl.\nQed.\n*)\n(*\n\nLemma pointsto_arr_get_element x i j k vs\n      (Hij : val_to_nat i <= val_to_nat j)\n      (Hjk : val_to_nat j <= val_to_nat k) :\n      pointsto_arr x i k vs |-- pointsto_arr_element x j \n                                (List.nth (val_to_nat j - val_to_nat i) vs null).\nProof.\n  unfold pointsto_arr.\n  apply lpropandL; intros [H1 H2].\n  unfold pointsto_arr_element.\n  intros p n h; simpl; intros.\n  generalize dependent (val_to_nat i).\n  generalize dependent (val_to_nat j).\n  generalize dependent (val_to_nat k).\n  clear i j k.\n  intros k j Hjk i Hij Hik Hlength H.\n  destruct h as [hp ha].\n  exists (hp, heap_arr_unit [(val_to_nat x, j) <- nth (j - i) vs null]).\n  split; simpl; [|rewrite add_eq_o; reflexivity].\n  apply subheap_prod; split; [reflexivity|].\n  generalize dependent k; induction vs; simpl in *; intros. omega.\n  inversion Hlength; clear Hlength.\n  unfold sepSP in H. unfold BILOperatorsAsn in H.\n  simpl in H.\n  destruct H as [h1 [h2 [Hh [[h3 [H2 H3]] H4]]]].\n  destruct h1, h2, h3.\n  apply subheap_prod in H2 as [H2 H5].\n  simpl in *.\n  remember (j - i) as l; destruct l; simpl in *.\n  assert (i = j) by omega; subst.\n  admit.\n  admit.\nQed.\n\n\nFixpoint arr_heap (h : heap_arr) (x : nat) (path indexes : list nat) (v : val) : heap_arr :=\n\tmatch path, indexes with\n\t\t| nil, i::indexes     => h [(x, i) <- v]\n\t\t| n::path, i::indexes => (arr_heap h n path indexes v) [(x, i) <- (varr n)]\n\t\t| _, _                => empty val\n\tend.\n\nProgram Definition in_arr_aux (p : val) (path : list nat) (indexes : list val) (v : val) : asn :=\n\tmk_asn (fun P k h => subheap (arr_heap (empty val) (val_to_arr p) path \n                                               (List.map val_to_arr indexes) v) (snd h)) _ _ _.\nNext Obligation.\n\tdestruct h as [_h h]; destruct h' as [_h' h']; simpl in *.\n\tapply subheap_prod in H as [_ H]; clear _h _h'.\n\trewrite H in H0. assumption.\nQed.\n\nDefinition in_arr (p : val) (indexes : list val) (v : val) : asn :=\n\tExists path : list nat, in_arr_aux p path indexes v.\n\nFixpoint alloc_arr_val (h : heap_arr) (x size : nat) (f : nat -> val) : heap_arr :=\n\tmatch size with\n\t\t| 0   => h [(x, 0) <- (f x)]\n\t\t| S n => (alloc_arr_val h x n f) [(x, S n) <- null]\n\tend.\n\nFixpoint alloc_arr_aux (h : heap_arr) (x : nat) (size : list nat) \n         (paths : list (list nat)) : heap_arr :=\n\tmatch size, paths with\n\t\t| s::nil, nil            => alloc_arr_val h x s (fun x => null)\n\t\t| s :: size, ps :: paths => List.fold_right (fun n h => h [(x, s) <- (varr n)]) h ps\n\t\t| _, _                   => empty val\n\tend.\n\t\nDefinition alloc_arr (x : nat) (size : list nat) (paths : list (list nat)) : heap_arr :=\n\talloc_arr_aux (empty val) x size paths.\n*)\t", "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/Logic/AssertionLogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.26430334136690964}}
{"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.Events.\nRequire Import compcert.common.Memory.\nRequire Import compcert.common.Values.\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Globalenvs.\n\nRequire Import sepcomp.mem_lemmas.\nRequire Import sepcomp.semantics.\nRequire Import sepcomp.semantics_lemmas.\nRequire Import sepcomp.wholeprog_simulations.\nRequire Import sepcomp.closed_safety.\nRequire Import sepcomp.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(** * Safety and semantics preservation *)\n\nSection safety_preservation_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 : meminj (*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 safety_preservation_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  (n1 < n2)%nat ->\n  exists a b,\n    (a > O)%nat\n    /\\ (b=0 -> S n1=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\n(** ** Equitermination *)\n\nDefinition terminates {G C M} (csem : CoreSemantics G C M)\n    (ge : G) (c : C) (m : M) :=\n  exists c' m', corestep_star csem ge c m c' m'\n  /\\ exists v, halted csem c' = Some v.\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 : meminj (*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 : meminj (*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 : meminj (*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. 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", "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/wholeprog_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.26430333564879915}}
{"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 Language.\nFrom PromisingLib Require Import Loc.\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 Pred.\nRequire Import Trace.\n\nRequire Import MemoryMerge.\nRequire Import PromiseConsistent.\nRequire Import PFConsistent.\nRequire Import ReorderCancel.\nRequire Import MemoryProps.\nRequire Import OrderedTimes.\n\nRequire Import Mapping.\nRequire Import CapFlex.\nRequire Import GoodFuture.\nRequire Import Cover.\n\nSet Implicit Arguments.\n\nSection CONCRETEMAX.\n\n  Lemma map_ident_concrete_promises mem prom tm (f: Loc.t -> Time.t -> Time.t -> Prop)\n        (MAX: concrete_promise_max_timemap mem prom tm)\n        (IDENT: forall loc ts (TS: Time.le ts (tm loc)), f loc ts ts)\n        (MAPLT: mapping_map_lt f)\n        (CLOSED: Memory.closed mem)\n        (MLE: Memory.le prom mem)\n    :\n      promises_map f prom prom.\n  Proof.\n    assert (CONCRETE: map_ident_concrete f mem).\n    { ii. inv CONCRETE. eapply MAX in GET. auto. }\n    econs.\n    { i. exists to, from, msg. splits; auto.\n      { eapply mapping_map_lt_non_collapsable; eauto. }\n      { eapply IDENT. eapply MAX in GET; eauto. }\n      { eapply map_ident_concrete_closed_message; eauto.\n        eapply MLE in GET. eapply CLOSED; eauto. }\n    }\n    { i. exists fto, ffrom, fmsg. splits; auto.\n      { eapply IDENT. eapply MAX in GET; eauto. }\n      { eapply IDENT. transitivity fto.\n        { eapply memory_get_ts_le; eauto. }\n        { eapply MAX in GET; eauto. }\n      }\n    }\n  Qed.\n\n  Lemma memory_ident_map_concrete_max f mem fmem\n        (MEM: memory_map f mem fmem)\n        (IDENT: forall loc to fto (MAP: f loc to fto), to = fto)\n        loc max fmax\n        (CLOSED: Memory.closed mem)\n        (MAX: Memory.max_concrete_ts mem loc max)\n        (FMAX: Memory.max_concrete_ts fmem loc fmax)\n    :\n      Time.le max fmax.\n  Proof.\n    eapply Memory.max_concrete_ts_spec in MAX; eauto.\n    { des. eapply MEM in GET. des; ss. inv MSG. inv MSGLE.\n      eapply Memory.max_concrete_ts_spec in GET; eauto. des.\n      eapply IDENT in TO. subst. auto. }\n    { eapply CLOSED. }\n  Qed.\n\n  Lemma memory_ident_map_concrete_promise_max_timemap\n        f mem_src mem_tgt prom_src prom_tgt tm_src tm_tgt\n        (MAXSRC: concrete_promise_max_timemap mem_src prom_src tm_src)\n        (MAXTGT: concrete_promise_max_timemap mem_tgt prom_tgt tm_tgt)\n        (LOCAL: promises_map f prom_tgt prom_src)\n        (MEM: memory_map f mem_tgt mem_src)\n        (IDENT: forall loc to fto (MAP: f loc to fto), to = fto)\n    :\n      TimeMap.le tm_tgt tm_src.\n  Proof.\n    ii. specialize (MAXTGT loc). inv MAXTGT. des.\n    { eapply MEM in GET. des; ss.\n      eapply IDENT in TO. subst. inv MSG. inv MSGLE.\n      eapply MAXSRC in GET. auto. }\n    { eapply LOCAL in GET. des; ss.\n      eapply IDENT in TO. subst.\n      eapply MAXSRC in GET. auto. }\n  Qed.\n\nEnd CONCRETEMAX.\n\n\n\n\nDefinition pf_consistent_strong lang (e0:Thread.t lang): Prop :=\n  forall mem1 sc1\n         (CAP: Memory.cap (Thread.memory e0) mem1),\n  exists e1,\n    (<<STEPS0: rtc (tau (@pred_step ThreadEvent.is_cancel lang)) (Thread.mk _ (Thread.state e0) (Thread.local e0) sc1 mem1) e1>>) /\\\n    (<<NORESERVE: no_reserves (Local.promises (Thread.local e1))>>) /\\\n    exists e2,\n      (<<STEPS1: rtc (tau (@pred_step ((promise_free /1\\ (fun e => ~ ThreadEvent.is_cancel e)) /1\\ no_sc) lang)) e1 e2>>) /\\\n      (__guard__((exists st',\n                     (<<LOCAL: Local.failure_step (Thread.local e2)>>) /\\\n                     (<<FAILURE: Language.step lang ProgramEvent.failure (@Thread.state lang e2) st'>>)) \\/\n                 (<<PROMISES: (Local.promises (Thread.local e2)) = Memory.bot>>))).\n\nLemma pf_consistent_pf_consistent_strong lang (th: Thread.t lang)\n      (WF: Local.wf (Thread.local th) (Thread.memory th))\n      (MEM: Memory.closed (Thread.memory th))\n      (CONSISTENT: pf_consistent th)\n  :\n    pf_consistent_strong th.\nProof.\n  assert (INHABITED: Memory.inhabited (Thread.memory th)).\n  { inv MEM. auto. }\n  ii. exploit Memory.max_concrete_timemap_exists; eauto. intros MAX. des.\n  ii. exploit Memory.max_concrete_timemap_exists.\n  { eapply le_inhabited; eauto. eapply Memory.cap_le; eauto. refl. }\n  i. des. exploit CONSISTENT; eauto. i.\n\n  assert (exists e2,\n             (<<STEPS: rtc (tau (Thread.step true))\n                           (Thread.mk _ (Thread.state th) (Thread.local th)\n                                      tm0 mem1) e2 >>) /\\\n             (<<NORESERVES: no_reserves (Local.promises (Thread.local e2))>>) /\\\n             (__guard__ ((exists e3, (<< FAILURE: Thread.step true ThreadEvent.failure e2 e3 >>)) \\/\n                         (<<PROMISES: Local.promises (Thread.local e2) = Memory.bot >>)))).\n  { des.\n    - exploit Thread.rtc_tau_step_future.\n      + eapply rtc_implies; [|apply STEPS].\n        i. inv H. econs; eauto. econs; eauto.\n      + ss. eapply Local.cap_wf; eauto.\n      + ss. eapply Memory.max_concrete_timemap_closed; eauto.\n      + ss. eapply Memory.cap_closed; eauto.\n      + i. des.\n        destruct e2. destruct local. inv WF2. ss.\n        exploit reserves_cancelable; eauto. i. des.\n        esplits.\n        * etrans.\n          { eapply STEPS. }\n          { eapply rtc_implies; [|apply STEPS0].\n            i. inv H. inv TSTEP. inv STEP.\n            unfold ThreadEvent.is_cancel in SAT. des_ifs.\n            inv STEP0; inv STEP.\n            - econs; eauto. econs; eauto. econs; eauto.\n            - inv LOCAL. }\n        * ss.\n        * left. inv FAILURE; inv STEP. inv LOCAL. inv LOCAL0.\n          exists (Thread.mk _ st2 (Local.mk tview proms1) sc2 mem0).\n          ss. econs 2. econs; eauto. econs; eauto. econs; eauto.\n          eapply cancels_promises_decrease in STEPS0; auto. ss.\n          ii. eapply CONSISTENT0; eauto.\n    - unguard. esplits; eauto. rewrite PROMISES. ii.\n      rewrite Memory.bot_get in GET. clarify. }\n\n  clear x. des.\n  eapply pf_step_promise_free_step_rtc in STEPS.\n  eapply steps_cancels_not_cancels in STEPS; cycle 1. des.\n\n  exploit Thread.rtc_cancel_step_future.\n  { eapply STEPS1. }\n  { ss. eapply Local.cap_wf; eauto. }\n  { ss. eapply Memory.max_concrete_timemap_closed; eauto. }\n  { ss. eapply Memory.cap_closed; eauto. }\n  i. des. ss.\n\n  eapply rtc_implies with (R2 := tau (@pred_step ThreadEvent.is_cancel lang)) in STEPS1; cycle 1.\n  { clear. i. inv H. econs.\n    { econs; eauto.\n      { econs; eauto. }\n      { ss. }\n    }\n    { ss. }\n  }\n  destruct th1. exploit no_sc_any_sc_rtc; try apply STEPS1; ss.\n  { i. unfold ThreadEvent.is_cancel in PR. des_ifs. }\n  i. des. instantiate (1:=sc1) in STEP. clear STEPS1.\n\n  eexists. splits.\n  { eapply STEP. }\n  { ss. ii. clarify.\n    eapply steps_not_cancel_reserves_same in STEPS2; eauto.\n    unguard. des.\n    - eapply NORESERVES; eauto.\n    - rewrite PROMISES in *. erewrite Memory.bot_get in STEPS2. clarify. }\n\n  eapply hold_or_not with (Q := no_sc) in STEPS2. des.\n\n  - destruct e2. ss.\n    exploit no_sc_any_sc_rtc; try eapply HOLD; eauto.\n    { ss. i. des. auto. } i. des.\n    esplits.\n    + eapply pred_step_rtc_mon; try eapply STEP0. i. ss.\n    + ss. unguard. des.\n      * left. ss. inv FAILURE; inv STEP1. inv LOCAL. eauto.\n      * right. esplits; eauto.\n\n  - exploit Thread.rtc_tau_step_future.\n    { eapply thread_steps_pred_steps. eapply STEPS0. }\n    { ss. }\n    { ss. }\n    { ss. } i. des.\n    inv STEP0.\n    exploit Thread.step_future; eauto. i. des.\n\n    assert (PROMS: Local.promise_consistent (Thread.local e3)).\n    { eapply rtc_tau_step_promise_consistent.\n      - eapply thread_steps_pred_steps. eapply STEPS1.\n      - unguard. des.\n        + inv FAILURE; inv STEP0. inv LOCAL. inv LOCAL0. ss.\n        + ii. rewrite PROMISES in PROMISE.\n          rewrite Memory.bot_get in PROMISE. clarify.\n      - eauto.\n      - eauto.\n      - eauto. }\n\n    assert (NOPROMISE: (Local.promises (Thread.local e2')) = Memory.bot).\n    { apply Memory.ext. i. rewrite Memory.bot_get.\n      destruct (Memory.get loc ts (Local.promises (Thread.local e2')))\n        as [[from [val released|]]|] eqn:GET; auto; cycle 1.\n      - exfalso.\n        eapply step_not_cancel_reserves_same in GET; cycle 1.\n        + econs.\n          * econs; eauto.\n          * instantiate (1:=promise_free /1\\ (fun e => ~ ThreadEvent.is_cancel e)). ss.\n        + ss.\n        + des. eapply steps_not_cancel_reserves_same in GET; eauto.\n          des. eapply NORESERVES; eauto.\n      - exfalso.\n        exploit pf_step_rtc_promises_decrease.\n        { eapply STEPS0. }\n        { i. ss. des. auto. }\n        { econs; eauto. } ss. i.\n        exploit pf_step_rtc_promises_decrease.\n        { eapply STEP. }\n        { i. unfold ThreadEvent.is_cancel in *. des_ifs. }\n        { ss. eauto. }\n        ss. i. inv x2.\n        ss. unfold no_sc in BREAKQ. des_ifs; try by (exfalso; eauto).\n        + des; clarify. apply NNPP in BREAKQ.\n          inv STEP1; inv STEP0. ss. inv LOCAL. inv LOCAL0. ss.\n          eapply PROMS in GET. ss. des_ifs. ss.\n          hexploit max_concrete_timemap_get; eauto.\n          * inv WF. eapply Memory.cap_le; eauto.\n          * i. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt; eauto.\n        + inv STEP1; inv STEP0. ss. inv LOCAL. inv LOCAL0. ss.\n          eapply PROMS in GET. ss. des_ifs. ss.\n          hexploit max_concrete_timemap_get; eauto.\n          * inv WF. eapply Memory.cap_le; eauto.\n          * i. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt; eauto.\n    }\n\n    destruct e2'. destruct local. ss.\n    eapply no_sc_any_sc_rtc in STEPS0; ss; cycle 1.\n    { i. des; ss. } des.\n    esplits.\n    * eapply pred_step_rtc_mon; eauto. i. ss.\n    * unguard. ss. eauto.\nQed.\n\nDefinition cancel_normal_trace (tr: Trace.t): Prop :=\n  exists tr_cancel tr_normal,\n    (<<EQ: tr = tr_cancel ++ tr_normal>>) /\\\n    (<<CANCEL: List.Forall (fun em => <<SAT: ThreadEvent.is_cancel (snd em)>>) tr_cancel>>) /\\\n    (<<NORMAL: List.Forall (fun em => <<SAT: (fun e => ~ ThreadEvent.is_cancel e) (snd em)>>) tr_normal>>).\n\nDefinition pf_consistent_strong_aux lang (e0:Thread.t lang): Prop :=\n  forall mem1\n         (CAP: Memory.cap (Thread.memory e0) mem1),\n  exists tr e1 times,\n    (<<STEPS: Trace.steps tr (Thread.mk _ (Thread.state e0) (Thread.local e0) TimeMap.bot mem1) e1>>) /\\\n    (<<EVENTS: List.Forall (fun em => <<SAT: (promise_free /1\\ no_sc /1\\ (wf_time_evt (fun loc to => List.In to (times loc)))) (snd em)>> /\\ <<TAU: ThreadEvent.get_machine_event (snd em) = MachineEvent.silent>>) tr >>) /\\\n    (<<CANCEL: cancel_normal_trace tr>>) /\\\n    (__guard__((exists st',\n                   (<<LOCAL: Local.failure_step (Thread.local e1)>>) /\\\n                   (<<FAILURE: Language.step lang ProgramEvent.failure (@Thread.state lang e1) st'>>)) \\/\n               ((<<PROMISES: (Local.promises (Thread.local e1)) = Memory.bot>>)))).\n\nLemma pf_consistent_strong_pf_consistent_strong_aux lang (th: Thread.t lang)\n      (WF: Local.wf (Thread.local th) (Thread.memory th))\n      (MEM: Memory.closed (Thread.memory th))\n      (CONSISTENT: pf_consistent_strong th)\n  :\n    pf_consistent_strong_aux th.\nProof.\n  ii. exploit CONSISTENT; eauto. i. des.\n  eapply pred_steps_trace_steps in STEPS0. des.\n  eapply pred_steps_trace_steps in STEPS1. des.\n  hexploit (trace_times_list_exists (tr ++ tr0)); eauto. i. des.\n  eexists (tr ++ tr0), e2, times. esplits; eauto.\n  { eapply Trace.steps_trans; eauto. }\n  { eapply list_Forall_sum.\n    { eapply WFTIME. }\n    { instantiate (1:=(fun em => <<SAT: (promise_free /1\\ no_sc) (snd em)>> /\\ <<TAU: ThreadEvent.get_machine_event (snd em) = MachineEvent.silent>>)).\n      eapply Forall_app.\n      { eapply List.Forall_impl; eauto. i. ss. destruct a. ss. des.\n        destruct t0; ss. des_ifs. }\n      { eapply List.Forall_impl; eauto. i. ss. des. splits; auto. }\n    }\n    { i. ss. des. splits; auto. }\n  }\n  { unfold cancel_normal_trace. esplits; eauto.\n    { eapply List.Forall_impl; eauto. i. ss. des; auto. }\n    { eapply List.Forall_impl; eauto. i. ss. des; auto. }\n  }\nQed.\n\nDefinition certification_times (times : Loc.t -> list Time.t)\n           (f: Loc.t -> nat -> (Time.t -> Time.t -> Prop))\n           (max: TimeMap.t)\n           (maxmap: TimeMap.t)\n           (loc: Loc.t) (fts: Time.t): Prop :=\n  ((<<IN: List.In fts (times loc)>>) /\\ (<<TS: Time.le fts (max loc)>>)) \\/\n  (exists ts n,\n      (<<IN: List.In ts (times loc)>>) /\\ (<<TS: Time.lt (max loc) ts>>)\n      /\\ (<<MAX: Time.lt (maxmap loc) (incr_time_seq n)>>)\n      /\\ (<<MAP: f loc n ts fts>>)).\n\nLemma certification_times_well_ordered times f max maxmap tm\n      (MAP: forall loc n\n                   (TS: Time.lt (maxmap loc) (incr_time_seq n)),\n          cap_flex_map_loc\n            (max loc)\n            (tm loc)\n            (incr_time_seq n) (times loc) (f loc n))\n      (TM: forall loc, Time.lt (maxmap loc) (tm loc))\n      (MAXMAP: TimeMap.le max maxmap)\n  :\n    forall loc, well_ordered (certification_times times f max maxmap loc).\nProof.\n  i. hexploit (@increasing_join_well_ordered\n                 incr_time_seq\n                 (fun n fts =>\n                    (exists ts,\n                        (<<IN: List.In ts (times loc)>>)\n                        /\\ (<<TS: Time.lt (max loc) ts>>)\n                        /\\ (<<MAX: Time.lt (maxmap loc) (incr_time_seq n)>>)\n                        /\\ (<<MAP: f loc n ts fts>>)))).\n  { i. eapply incr_time_seq_lt; eauto. }\n  { eapply incr_time_seq_diverge. }\n  { i. des. exploit MAP; eauto. intros FLEXMAP.\n    eapply ((cap_flex_map_loc_bound FLEXMAP)); try apply MAP0. auto. }\n  { i. destruct (classic (Time.lt (maxmap loc) (incr_time_seq n))).\n    { specialize (MAP _ _ H). eapply mapped_well_ordered.\n      { eapply MAP. }\n      { eapply (finite_well_ordered (times loc)). }\n      i. des. esplits; eauto.\n    }\n    { eapply sub_well_ordered.\n      { eapply empty_well_ordered. }\n      i. des; ss.\n    }\n  }\n  intros WO.\n  eapply sub_well_ordered.\n  { eapply join_well_ordered.\n    { eapply WO. }\n    { eapply (finite_well_ordered (times loc)). }\n  }\n  { i. unfold certification_times in *. des; eauto. left. esplits; eauto. }\nQed.\n\n\nDefinition pf_consistent_flex lang (e0:Thread.t lang)\n           (tr : Trace.t) (times : Loc.t -> list Time.t)\n           (f: Loc.t -> nat -> (Time.t -> Time.t -> Prop))\n  : Prop :=\n  forall max\n         (MAX: concrete_promise_max_timemap\n                 ((Thread.memory e0))\n                 ((Local.promises (Thread.local e0)))\n                 max),\n    (<<MAP: forall loc n\n                   (TS: Time.lt (Memory.max_ts loc (Thread.memory e0)) (incr_time_seq n)),\n        cap_flex_map_loc\n          (max loc)\n          (Time.incr (Memory.max_ts loc (Thread.memory e0)))\n          (incr_time_seq n) (times loc) (f loc n)>>) /\\\n    (<<CONSISTENT: forall mem1 (tm: Loc.t -> nat)\n                          (TM: forall loc, Time.lt (Memory.max_ts loc (Thread.memory e0)) (incr_time_seq (tm loc)))\n                          (CAP: cap_flex (Thread.memory e0) mem1 (fun loc => incr_time_seq (tm loc))),\n        exists ftr e1,\n          (<<STEPS: Trace.steps ftr (Thread.mk _ (Thread.state e0) (Thread.local e0) TimeMap.bot mem1) e1>>) /\\\n          (<<EVENTS: List.Forall (fun em => <<SAT: (promise_free\n                                                      /1\\ no_sc\n                                                      /1\\ wf_time_evt (fun loc => certification_times times f max (Memory.max_timemap (Thread.memory e0)) loc)) (snd em)>> /\\ <<TAU: ThreadEvent.get_machine_event (snd em) = MachineEvent.silent>>) ftr >>) /\\\n          (<<TRACE: List.Forall2 (fun em fem => tevent_map (fun loc => f loc (tm loc)) (snd fem) (snd em)) tr ftr>>) /\\\n          (__guard__((exists st',\n                         (<<LOCAL: Local.failure_step (Thread.local e1)>>) /\\\n                         (<<FAILURE: Language.step lang ProgramEvent.failure (@Thread.state lang e1) st'>>)) \\/\n                     (<<PROMISES: (Local.promises (Thread.local e1)) = Memory.bot>>)))>>).\n\n\nLemma pf_consistent_strong_aux_pf_consistent_flex lang (th: Thread.t lang)\n      (WF: Local.wf (Thread.local th) (Thread.memory th))\n      (MEM: Memory.closed (Thread.memory th))\n      (CONSISTENT: pf_consistent_strong_aux th)\n  :\n    exists tr times f, <<CONSISTENT: pf_consistent_flex th tr times f>> /\\ <<CANCELNORMAL: cancel_normal_trace tr>>.\nProof.\n  exploit Memory.cap_exists; eauto. i. des.\n  exploit CONSISTENT; eauto. i. des. exists tr, times.\n  hexploit (@concrete_promise_max_timemap_exists\n              ((Thread.memory th))\n              ((Local.promises (Thread.local th)))).\n  { eapply MEM. } intros [max MAX]. des.\n  hexploit (@choice\n              (Loc.t * nat)\n              (Time.t -> Time.t -> Prop)\n              (fun locn f =>\n                 let (loc, n) := locn in\n                 forall\n                   (TS: Time.lt (Memory.max_ts loc (Thread.memory th)) (incr_time_seq n)),\n                   cap_flex_map_loc\n                     (max loc)\n                     (Time.incr (Memory.max_ts loc (Thread.memory th)))\n                     (incr_time_seq n) (times loc) f)).\n  { intros [loc n].\n    destruct (classic (Time.lt (Memory.max_ts loc (Thread.memory th)) (incr_time_seq n))).\n    { des. hexploit (@cap_flex_map_loc_exists\n                       (max loc)\n                       (Time.incr (Memory.max_ts loc (Thread.memory th)))\n                       (incr_time_seq n)).\n      { eapply TimeFacts.le_lt_lt.\n        { eapply concrete_promise_max_ts_max_ts; eauto. eapply WF. }\n        { eapply Time.incr_spec. }\n      }\n      { eapply TimeFacts.le_lt_lt.\n        { eapply concrete_promise_max_ts_max_ts; eauto. eapply WF. }\n        { auto. }\n      }\n      i. des. eauto. }\n    { exists bot2. i. exfalso. eapply H. auto. }\n  }\n  intros [f SPEC]. des. exists (fun loc ts => f (loc, ts)). splits; auto. ii.\n  assert (max0 = max).\n  { eapply concrete_promise_max_timemap_inj; eauto. } subst. econs.\n  { ii. specialize (SPEC (loc, n)). ss. eauto. }\n  ii. assert (MAP: cap_flex_map\n                     max\n                     (fun loc => Time.incr (Memory.max_ts loc (Thread.memory th)))\n                     (fun loc => incr_time_seq (tm loc))\n                     times (fun loc => f (loc, tm loc))).\n  { eapply cap_flex_map_locwise. i.\n    eapply (SPEC (loc, tm loc)). eauto. }\n\n  assert (IDENT: map_ident_concrete (fun loc => f (loc, tm loc)) (Thread.memory th)).\n  { ii. inv CONCRETE. eapply MAX in GET. eapply MAP; eauto. }\n  destruct e1. ss.\n  hexploit trace_steps_map.\n  { eapply mapping_map_lt_map_le. eapply MAP. }\n  { eapply MAP. }\n  { eapply mapping_map_lt_map_eq. eapply MAP. }\n  { eapply wf_time_mapped_mappable.\n    { eapply List.Forall_impl; eauto. i. ss. des; eauto. }\n    { eapply cap_flex_map_complete; eauto. }\n  }\n  { eapply STEPS. }\n  { ss. }\n  { ss. }\n  { ss. }\n  { eapply Local.cap_wf; eauto. }\n  { instantiate (1:=mem1). instantiate (1:=(Thread.local th)).\n    eapply cap_flex_wf; eauto. }\n  { eapply cap_flex_closed; eauto. }\n  { eapply Memory.cap_closed; eauto. }\n  { eapply Memory.closed_timemap_bot.\n    eapply cap_flex_closed in CAP0; auto. eapply CAP0. }\n  { eapply Memory.closed_timemap_bot.\n    eapply Memory.cap_closed in CAP; auto. eapply CAP. }\n  { econs.\n    { refl. }\n    { eapply map_ident_concrete_closed_tview; eauto. eapply WF. }\n    { eapply map_ident_concrete_promises; eauto.\n      { i. eapply MAP; eauto. }\n      { eapply MAP. }\n      { eapply WF. }\n    }\n  }\n  { exploit (@Memory.max_concrete_timemap_exists (Thread.memory th)).\n    { eapply MEM. } i. des.\n    eapply concrete_messages_le_cap_flex_memory_map.\n    { refl. }\n    { eauto. }\n    { ii. eapply concrete_promise_max_ts_max_concrete_ts; eauto. }\n    { instantiate (1:=(fun loc => Time.incr (Memory.max_ts loc (Thread.memory th)))).\n      i. eapply Time.incr_spec. }\n    { eapply TM. }\n    { eapply cap_cap_flex; eauto. }\n    { eauto. }\n    { eauto. }\n    { eauto. }\n    { eauto. }\n  }\n  { eapply mapping_map_lt_collapsable_unwritable. eapply MAP. }\n  { eapply timemap_bot_map. eapply MAP. }\n  { refl. } i. des.\n  exists ftr, (Thread.mk _ state flc1 fsc1 fmem1). splits; auto.\n  { eapply List.Forall_forall. i.\n    cut ((promise_free /1\\ no_sc) (snd x) /\\ ThreadEvent.get_machine_event (snd x) = MachineEvent.silent).\n    { i. des. splits; auto.\n      { eapply list_Forall2_in in H; eauto. des.\n        eapply List.Forall_forall in IN; eauto. ss. des.\n        eapply wf_time_evt_map in EVENT; eauto. eapply wf_time_evt_mon; try apply EVENT.\n        i. ss. des. destruct (Time.le_lt_dec ts (max x1)).\n        { left. assert (ts = x2).\n          { eapply mapping_map_lt_map_eq.\n            { eapply MAP. }\n            { ss. eapply MAP. eauto. }\n            { eauto. }\n          }\n          subst. splits; auto.\n        }\n        { right. esplits; eauto. }\n      }\n    }\n    eapply list_Forall2_in in H; eauto. des.\n    eapply List.Forall_forall in IN; eauto. ss. des.\n    destruct x, a. ss. inv EVENT; ss. inv KIND; ss.\n    splits; auto. inv MSG0; ss. inv MSG; ss. inv MAP1; ss.\n  }\n  { eapply list_Forall2_impl; eauto. i. ss. des. auto. }\n  { ss. unguard. des; eauto.\n    { left. esplits; eauto. eapply failure_step_map; eauto.\n      { eapply mapping_map_lt_map_le. eapply MAP. }\n      { eapply mapping_map_lt_map_eq. eapply MAP. }\n    }\n    { right. splits.\n      { inv LOCAL. erewrite PROMISES in *. eapply bot_promises_map; eauto. }\n    }\n  }\nQed.\n\n\nDefinition pf_consistent_super_strong_easy lang (e0:Thread.t lang)\n           (tr : Trace.t)\n           (times: Loc.t -> (Time.t -> Prop))\n  : Prop :=\n  forall cap (tm: Loc.t -> nat) max\n         (CAPTM: forall loc, Time.lt (Memory.max_ts loc (Thread.memory e0)) (incr_time_seq (tm loc)))\n         (CAP: cap_flex (Thread.memory e0) cap (fun loc => incr_time_seq (tm loc)))\n         (MAX: concrete_promise_max_timemap\n                 ((Thread.memory e0))\n                 ((Local.promises (Thread.local e0)))\n                 max),\n  exists ftr e1 f,\n    (<<STEPS: Trace.steps ftr (Thread.mk _ (Thread.state e0) (Thread.local e0) TimeMap.bot cap) e1>>) /\\\n    (<<EVENTS: List.Forall (fun em => <<SAT: (promise_free\n                                                /1\\ no_sc\n                                                /1\\ wf_time_evt times) (snd em)>> /\\ <<TAU: ThreadEvent.get_machine_event (snd em) = MachineEvent.silent>>) ftr >>) /\\\n    (<<CANCELNORMAL: cancel_normal_trace ftr>>) /\\\n    (<<MAPLT: mapping_map_lt f>>) /\\\n    (<<MAPIDENT: forall loc ts fts\n                        (TS: Time.le fts (max loc))\n                        (MAP: f loc ts fts),\n        ts = fts>>) /\\\n    (<<BOUND: forall loc ts fts (TS: Time.lt (max loc) fts) (MAP: f loc ts fts),\n        Time.lt (max loc) ts /\\ Time.le (incr_time_seq (tm loc)) fts>>) /\\\n    (<<TRACE: List.Forall2 (fun em fem => tevent_map_weak f (snd fem) (snd em)) tr ftr>>) /\\\n    (__guard__((exists st',\n                   (<<LOCAL: Local.failure_step (Thread.local e1)>>) /\\\n                   (<<FAILURE: Language.step lang ProgramEvent.failure (@Thread.state lang e1) st'>>)) \\/\n               (<<PROMISES: (Local.promises (Thread.local e1)) = Memory.bot>>))).\n\nLemma pf_consistent_super_strong_easy_same_sc lang (e0: Thread.t lang) tr times sc\n      (CONSISTENT: pf_consistent_super_strong_easy e0 tr times)\n  :\n    pf_consistent_super_strong_easy (Thread.mk _ (Thread.state e0) (Thread.local e0) sc (Thread.memory e0)) tr times.\nProof.\n  ii. exploit CONSISTENT; eauto.\nQed.\n\nDefinition pf_consistent_super_strong_easy_mon lang e0 tr certimes0 certimes1\n           (CONSISTENT: @pf_consistent_super_strong_easy\n                          lang e0 tr certimes0)\n           (LE: certimes0 <2= certimes1)\n  :\n    pf_consistent_super_strong_easy e0 tr certimes1.\nProof.\n  ii. exploit CONSISTENT; eauto. i. des. esplits; eauto.\n  eapply List.Forall_impl; eauto. i. ss. des. splits; eauto.\n  eapply wf_time_evt_mon; eauto.\nQed.\n\nLemma memory_times_wf_exists (mem: Memory.t)\n  :\n    exists times_mem,\n      (<<MWF: memory_times_wf times_mem mem>>) /\\\n      (<<MEMWO: forall loc, well_ordered (times_mem loc)>>).\nProof.\n  hexploit (choice\n              (fun loc times =>\n                 (<<WF: forall to from msg\n                               (GET: Memory.get loc to mem = Some (from, msg)),\n                     times from /\\ times to>>) /\\ (<<WO: well_ordered times>>))).\n  { intros loc. hexploit (Cell.finite (mem loc)). i. des.\n    set (f := (fun to => match (Memory.get loc to mem) with\n                         | Some (from, _) => from\n                         | _ => Time.bot\n                         end)).\n    set (froms:=List.map f dom).\n    hexploit (finite_well_ordered (dom++froms)). intros WO. esplits; try apply WO.\n    i. ss. dup GET. eapply H in GET. split.\n    { eapply List.in_map with (f:=f) in GET. unfold f in GET. erewrite GET0 in *.\n      eapply List.in_or_app; eauto. }\n    { eapply List.in_or_app; eauto. }\n  }\n  i. des. exists f. splits.\n  { ii. specialize (H loc). des. apply WF in GET. auto. }\n  { apply H; eauto. }\nQed.\n\nLemma pf_consistent_flex_super_strong_easy\n      lang (th: Thread.t lang) tr times f\n      (WF: Local.wf (Thread.local th) (Thread.memory th))\n      (MEM: Memory.closed (Thread.memory th))\n      (CONSISTENT: pf_consistent_flex th tr times f)\n      (CANCELNORMAL: cancel_normal_trace tr)\n  :\n    exists certimes,\n      (<<WO: forall loc, well_ordered (certimes loc)>>) /\\\n      (<<MWF: memory_times_wf certimes (Thread.memory th)>>) /\\\n      (<<DIVERGE: forall loc n, certimes loc (incr_time_seq n)>>) /\\\n      (<<CONSISTENT: pf_consistent_super_strong_easy th tr certimes>>).\nProof.\n  hexploit (@concrete_promise_max_timemap_exists\n              ((Thread.memory th))\n              ((Local.promises (Thread.local th)))).\n  { eapply MEM. } intros [max MAX]. specialize (CONSISTENT _ MAX). des.\n  hexploit (memory_times_wf_exists (Thread.memory th)). i. des.\n  exists ((certification_times times f max (Memory.max_timemap (Thread.memory th))) \\2/ times_mem \\2/ (fun loc => incr_times)). splits.\n  { i. eapply join_well_ordered.\n    { eapply join_well_ordered; eauto.\n      eapply certification_times_well_ordered; eauto.\n      { i. eapply MAP. auto. }\n      { i. ss. eapply Time.incr_spec. }\n      { ii. eapply concrete_promise_max_ts_max_ts; eauto. eapply WF. }\n    }\n    eapply incr_times_well_ordered.\n  }\n  { ii. eapply MWF in GET. des; auto. }\n  { i. right. unfold incr_times. eauto. }\n  ii. assert (max0 = max).\n  { eapply concrete_promise_max_timemap_inj; eauto. } subst.\n  hexploit CONSISTENT0; eauto. i. des.\n  assert (MAPALL: cap_flex_map\n                    max\n                    (fun loc => Time.incr (Memory.max_ts loc (Thread.memory th)))\n                    (fun loc => incr_time_seq (tm loc))\n                    times (fun loc => f loc (tm loc))).\n  { eapply cap_flex_map_locwise; eauto. }\n  eexists _, _, (fun loc => f loc (tm loc)). splits; eauto.\n  { eapply List.Forall_impl; eauto. i. ss. des. splits; auto.\n    eapply wf_time_evt_mon; try apply SAT0; eauto. }\n  { unfold cancel_normal_trace in *. des. subst.\n    eapply List.Forall2_app_inv_l in TRACE. des. esplits; eauto.\n    { eapply List.Forall_forall. i. eapply list_Forall2_in in H; eauto. des.\n      destruct a, x. ss. eapply List.Forall_forall in IN; eauto. ss. inv SAT; ss.\n      inv KIND; ss; des_ifs. inv MSG. }\n    { eapply List.Forall_forall. i. eapply list_Forall2_in in H; eauto. des.\n      destruct a, x. ss. eapply List.Forall_forall in IN; eauto. ss. inv SAT; ss.\n      inv KIND; ss; des_ifs. inv MSG. }\n  }\n  { eapply MAPALL. }\n  { i. eapply MAPALL in TS; eauto.\n    eapply mapping_map_lt_inj.\n    { eapply MAPALL; eauto. }\n    { ss. eauto. }\n    { eauto. }\n  }\n  { i. destruct (Time.le_lt_dec ts (max loc)).\n    { dup l. eapply MAPALL in l; eauto.\n      exploit mapping_map_lt_map_eq.\n      { eapply MAPALL. }\n      { eapply MAP0. }\n      { eapply l. }\n      i. subst. timetac.\n    }\n    { split; auto. eapply (cap_flex_map_bound MAPALL) in l; eauto. }\n  }\n  { eapply list_Forall2_impl; eauto. i. eapply tevent_map_tevent_map_weak; eauto. }\nQed.\n\nRequire Import PreReserve.\n\n\nDefinition pf_consistent_special lang (e0:Thread.t lang)\n           (tr : Trace.t)\n           (times: Loc.t -> (Time.t -> Prop))\n  : Prop :=\n  forall cap (tm: Loc.t -> nat) max\n         (CAPTM: forall loc, Time.lt (Memory.max_ts loc (Thread.memory e0)) (incr_time_seq (tm loc)))\n         (CAP: cap_flex (Thread.memory e0) cap (fun loc => incr_time_seq (tm loc)))\n         (MAX: concrete_promise_max_timemap\n                 ((Thread.memory e0))\n                 ((Local.promises (Thread.local e0)))\n                 max),\n  exists ftr e1,\n    (<<STEPS: Trace.steps ftr (Thread.mk _ (Thread.state e0) (Thread.local e0) TimeMap.bot cap) e1>>) /\\\n    (<<EVENTS: List.Forall (fun em => <<SAT: (promise_free\n                                                /1\\ no_sc\n                                                /1\\ wf_time_evt times) (snd em)>> /\\ <<TAU: ThreadEvent.get_machine_event (snd em) = MachineEvent.silent>>) ftr >>) /\\\n    (<<CANCELNORMAL: cancel_normal_trace ftr>>) /\\\n    (<<TRACE: List.Forall2 (fun em fem => tevent_map_weak (fun loc ts fts => ts = fts /\\ Time.le ts (max loc)) (snd fem) (snd em)) tr ftr>>) /\\\n    (__guard__((exists st',\n                   (<<LOCAL: Local.failure_step (Thread.local e1)>>) /\\\n                   (<<FAILURE: Language.step lang ProgramEvent.failure (@Thread.state lang e1) st'>>)) \\/\n               (<<PROMISES: (Local.promises (Thread.local e1)) = Memory.bot>>))).\n\nLemma pf_consistent_speciali_strong_easy\n      lang (th: Thread.t lang) tr times\n      (CONSISTENT: pf_consistent_special th tr times)\n  :\n    pf_consistent_super_strong_easy th tr times.\nProof.\n  ii. exploit CONSISTENT; eauto. i. des. esplits; eauto.\n  { ii. des. subst. auto. }\n  { ii. ss. des. auto. }\n  { ii. ss. des. subst. exfalso. timetac. }\nQed.\n\nLemma pf_consistent_speciali_events_map\n      lang (th: Thread.t lang) tr0 tr1 times\n      (CONSISTENT: pf_consistent_special th tr0 times)\n      (EVENTS: List.Forall2 (fun em fem => tevent_map_weak ident_map (snd fem) (snd em)) tr0 tr1)\n  :\n    pf_consistent_special th tr1 times.\nProof.\n  ii. exploit CONSISTENT; eauto. i. des. esplits; eauto.\n  eapply list_Forall2_compose.\n  { eapply list_Forall2_rev; eauto. }\n  { eauto. }\n  { i. ss. eapply tevent_map_weak_rev with (f1:=ident_map) in SAT0; ss.\n    eapply tevent_map_weak_compose; eauto. i. ss. inv MAP0. des; auto. }\nQed.\n\n\nDefinition pf_consistent_super_strong_split lang (e0:Thread.t lang)\n           (tr : Trace.t)\n           (times: Loc.t -> (Time.t -> Prop))\n  : Prop :=\n  forall cap (tm: Loc.t -> nat) max\n         (CAPTM: forall loc, Time.lt (Memory.max_ts loc (Thread.memory e0)) (incr_time_seq (tm loc)))\n         (CAP: cap_flex (Thread.memory e0) cap (fun loc => incr_time_seq (tm loc)))\n         (MAX: concrete_promise_max_timemap\n                 ((Thread.memory e0))\n                 ((Local.promises (Thread.local e0)))\n                 max),\n  exists ftr e1 f,\n    (<<STEPS: Trace.steps ftr (Thread.mk _ (Thread.state e0) (Thread.local e0) TimeMap.bot cap) e1>>) /\\\n    (<<EVENTS: List.Forall (fun em => <<SAT: (promise_free\n                                                /1\\ no_sc\n                                                /1\\ wf_time_evt times) (snd em)>> /\\ <<TAU: ThreadEvent.get_machine_event (snd em) = MachineEvent.silent>>) ftr >>) /\\\n    (<<CANCELNORMAL: cancel_normal_trace ftr>>) /\\\n\n    (<<SPLIT:\n       forall ftr0 ftr1 e_mid\n              (FTRACE: ftr = ftr0 ++ ftr1)\n              (NORMAL: List.Forall (fun em => ~ ThreadEvent.is_cancel (snd em)) ftr1)\n              (STEPS0: Trace.steps ftr0 (Thread.mk _ (Thread.state e0) (Thread.local e0) TimeMap.bot cap) e_mid)\n              (STEPS1: Trace.steps ftr1 e_mid e1)\n       ,\n       exists ftr_reserve ftr_cancel e2,\n         (<<STEPS: Trace.steps ftr_reserve e_mid e2>>) /\\\n         (<<RESERVE: List.Forall (fun em => <<SAT: (ThreadEvent.is_reserve /1\\ wf_time_evt times) (snd em)>>) ftr_reserve>>) /\\\n         (<<CANCEL: List.Forall (fun em => <<SAT: (ThreadEvent.is_cancel /1\\ wf_time_evt times) (snd em)>>) ftr_cancel>>) /\\\n         (<<CONSISTENT: pf_consistent_special e2 (ftr_cancel ++ ftr1) times>>) /\\\n         (<<CANCELNORMAL: cancel_normal_trace (ftr_cancel ++ ftr1)>>)>>) /\\\n\n    (<<MAPLT: mapping_map_lt f>>) /\\\n    (<<MAPIDENT: forall loc ts fts\n                        (TS: Time.le fts (max loc))\n                        (MAP: f loc ts fts),\n        ts = fts>>) /\\\n    (<<BOUND: forall loc ts fts (TS: Time.lt (max loc) fts) (MAP: f loc ts fts),\n        Time.lt (max loc) ts /\\ Time.le (incr_time_seq (tm loc)) fts>>) /\\\n    (<<TRACE: List.Forall2 (fun em fem => tevent_map_weak f (snd fem) (snd em)) tr ftr>>) /\\\n    (__guard__((exists st',\n                   (<<LOCAL: Local.failure_step (Thread.local e1)>>) /\\\n                   (<<FAILURE: Language.step lang ProgramEvent.failure (@Thread.state lang e1) st'>>)) \\/\n               (<<PROMISES: (Local.promises (Thread.local e1)) = Memory.bot>>))).\n\nLemma cap_flex_memory_times_wf times mem cap tm\n      (MEMWF: memory_times_wf times mem)\n      (CAP: cap_flex mem cap tm)\n      (TM: forall loc, Time.lt (Memory.max_ts loc mem) (tm loc))\n      (IN: forall loc, times loc (tm loc))\n      (CLOSED: Memory.closed mem)\n  :\n    memory_times_wf times cap.\nProof.\n  ii. eapply cap_flex_inv in GET; eauto. des.\n  { eapply MEMWF; eauto. }\n  { inv GET0. eapply MEMWF in GET3. eapply MEMWF in GET4. des. auto. }\n  { subst. split; auto. exploit Memory.max_ts_spec.\n    { eapply CLOSED. }\n    i. des. eapply MEMWF in GET0. des. eauto.\n  }\nQed.\n\nLemma list_Forall_refl_Forall2 A (P: A -> A -> Prop) (l: list A)\n      (FORALL: List.Forall (fun a => P a a) l)\n  :\n    List.Forall2 P l l.\nProof.\n  ginduction l; eauto. i. inv FORALL. econs; eauto.\nQed.\n\n\nLemma ident_map_compose_tevent_weak f te0 te1 te2\n      (MAP0: tevent_map_weak f te1 te0)\n      (MAP1: tevent_map_weak ident_map te2 te1)\n  :\n    tevent_map_weak f te2 te0.\nProof.\n  inv MAP0; inv MAP1; econs.\n  { inv FROM0. auto. }\n  { inv TO0. auto. }\n  { inv TO0. etrans; eauto. }\n  { inv TO0. eauto. }\n  { inv FROM0. eauto. }\n  { inv TO0. eauto. }\n  { inv FROM0. eauto. }\n  { inv TO0. eauto. }\nQed.\n\nLemma ident_map_compose_tevent_weak2 f te0 te1 te2\n      (MAP0: tevent_map_weak ident_map te1 te0)\n      (MAP1: tevent_map_weak f te2 te1)\n  :\n    tevent_map_weak f te2 te0.\nProof.\n  inv MAP0; inv MAP1; econs.\n  { inv FROM. auto. }\n  { inv TO. auto. }\n  { inv TO. eauto. etrans; eauto. }\n  { inv TO. eauto. }\n  { inv FROM. eauto. }\n  { inv TO. eauto. }\n  { inv FROM. eauto. }\n  { inv TO. eauto. }\nQed.\n\nLemma ident_map_pf_consistent_super_strong_easy\n      lang (th0 th1: Thread.t lang) tr times\n      (CONSISTENT: pf_consistent_special th0 tr times)\n      (WF0: Local.wf (Thread.local th0) (Thread.memory th0))\n      (MEM0: Memory.closed (Thread.memory th0))\n      (WF1: Local.wf (Thread.local th1) (Thread.memory th1))\n      (MEM1: Memory.closed (Thread.memory th1))\n      (MAP: thread_map ident_map th0 th1)\n  :\n    pf_consistent_special th1 tr times.\nProof.\n  ii.\n  assert (exists (tm_src: Loc.t -> nat),\n             (<<CAPTMSRC: forall loc,\n                 Time.lt (Memory.max_ts loc (Thread.memory th0)) (incr_time_seq (tm_src loc))>>)  /\\\n             (<<TMLE: forall loc, Time.le (incr_time_seq (tm loc)) (incr_time_seq (tm_src loc))>>)).\n  { exploit (choice (fun loc n =>\n                       (<<CAPTMSRC:\n                          Time.lt (Memory.max_ts loc (Thread.memory th0)) (incr_time_seq n)>>)  /\\\n                       (<<TMLE: Time.le (incr_time_seq (tm loc)) (incr_time_seq n)>>))).\n    { i. hexploit (@incr_time_seq_diverge\n                     (Time.join\n                        (Memory.max_ts x (Thread.memory th0))\n                        (incr_time_seq (tm x)))). i. des.\n      exists n. splits; auto.\n      { eapply TimeFacts.le_lt_lt; eauto. eapply Time.join_l. }\n      { left. eapply TimeFacts.le_lt_lt; eauto. eapply Time.join_r. }\n    }\n    i. des. exists f. splits.\n    { i. specialize (x0 loc). des; auto. }\n    { i. specialize (x0 loc). des; auto. }\n  }\n  des.\n  exploit (@concrete_promise_max_timemap_exists (Thread.memory th0) (Local.promises (Thread.local th0))).\n  { eapply MEM0. }\n  i. des.\n  assert (MAXLE: TimeMap.le tm0 max).\n  { inv MAP. ss. inv LOCAL. eapply memory_ident_map_concrete_promise_max_timemap; eauto. }\n  exploit (@cap_flex_exists (Thread.memory th0) (fun loc => incr_time_seq (tm_src loc))); eauto.\n  i. des.\n  exploit CONSISTENT; eauto. i. des. inv MAP. ss.\n  destruct e1. ss. hexploit trace_steps_map.\n  { eapply ident_map_le; eauto. }\n  { eapply ident_map_bot; eauto. }\n  { eapply ident_map_eq; eauto. }\n  { eapply List.Forall_forall. i. eapply ident_map_mappable_evt. }\n  { eapply STEPS. }\n  { ss. }\n  { ss. }\n  { ss. }\n  { eapply cap_flex_wf; eauto. }\n  { eapply cap_flex_wf; try apply CAP; eauto. }\n  { eapply cap_flex_closed; eauto. }\n  { eapply cap_flex_closed; eauto. }\n  { eapply Memory.closed_timemap_bot; eauto.\n    eapply cap_flex_closed; eauto. }\n  { eapply Memory.closed_timemap_bot; eauto.\n    eapply cap_flex_closed; eauto. }\n  all: eauto.\n  { econs.\n    { i. eapply cap_flex_inv in GET; try apply CAP0; eauto. des; auto.\n      eapply MEM in GET. des; auto. right. esplits; eauto.\n      eapply CAP in GET; eauto. }\n    { i. left.\n      exists (incr_time_seq (tm_src loc)), Time.bot, (incr_time_seq (tm_src loc)), Time.bot.\n      splits; auto; ss.\n      { eapply Time.bot_spec. }\n      { eapply Memory.max_ts_spec in GET. des.\n        erewrite (@cap_flex_max_ts fmem cap) in MAX1; eauto. ss.\n        etrans; eauto. }\n      i. eapply cap_flex_covered; eauto.\n    }\n  }\n  { eapply mapping_map_lt_collapsable_unwritable. eapply ident_map_lt. }\n  { eapply ident_map_timemap. }\n  { refl. }\n  i. des. esplits.\n  { eauto. }\n  { eapply List.Forall_forall. i. eapply list_Forall2_in in H; eauto. des.\n    eapply List.Forall_forall in IN; eauto. ss. des.\n    destruct a, x. ss. unfold ident_map in *.\n    inv EVENT; ss; des; subst; auto. splits; auto.\n    inv KIND; ss. inv MSG0; auto. inv MSG; auto. inv MAP0; ss. }\n  { clear - CANCELNORMAL TRACE0. unfold cancel_normal_trace in *. des.\n    subst. eapply List.Forall2_app_inv_l in TRACE0. des. subst. esplits; eauto.\n    { eapply List.Forall_forall. i. eapply list_Forall2_in in H; eauto. des.\n      eapply List.Forall_forall in IN; eauto. ss.\n      destruct a, x. ss. inv EVENT; ss. inv KIND; ss; des_ifs. inv MSG. }\n    { eapply List.Forall_forall. i. eapply list_Forall2_in in H; eauto. des.\n      eapply List.Forall_forall in IN; eauto. ss.\n      destruct a, x. ss. inv EVENT; ss. inv KIND; ss; des_ifs. inv MSG. }\n  }\n  { eapply list_Forall2_compose.\n    { eapply TRACE. }\n    { eapply TRACE0. }\n    i. ss. des. eapply tevent_map_tevent_map_weak in EVENT.\n    eapply tevent_map_weak_compose; eauto.\n    i. ss. des; subst. inv MAP1. split; auto. etrans; eauto.\n  }\n  { i. unguard. des.\n    { left. ss. esplits; eauto. eapply failure_step_map; eauto.\n      { eapply ident_map_le. }\n      { eapply ident_map_eq. }\n    }\n    { right. ss. inv LOCAL0.\n      rewrite PROMISES in *. eapply bot_promises_map in PROMISES0; auto. }\n  }\nQed.\n\n\nLemma pf_consistent_flex_super_strong_easy_split\n      lang (th: Thread.t lang) tr times\n      (WF: Local.wf (Thread.local th) (Thread.memory th))\n      (MEM: Memory.closed (Thread.memory th))\n      (CONSISTENT: pf_consistent_super_strong_easy th tr times)\n      (CANCELNORMAL: cancel_normal_trace tr)\n      (MWF: memory_times_wf times (Thread.memory th))\n      (DIVERGE: forall loc n, times loc (incr_time_seq n))\n  :\n    pf_consistent_super_strong_split th tr times.\nProof.\n  ii. exploit CONSISTENT; eauto. i. des. esplits; eauto.\n  i. subst. exploit Trace.steps_future; try apply STEPS0; eauto; ss.\n  { eapply cap_flex_wf; eauto. }\n  { eapply Memory.closed_timemap_bot; eauto.\n    eapply cap_flex_closed; eauto. }\n  { eapply cap_flex_closed; eauto. } i. des.\n  eapply Forall_app_inv in EVENTS. des.\n  destruct e_mid, e1. ss.\n  assert (sc = TimeMap.bot).\n  { eapply no_sc_same_sc_traced in STEPS0; eauto.\n    eapply List.Forall_impl; eauto. i. ss. des; auto. } subst.\n  hexploit can_reserve_all_needed.\n  { instantiate (1:=times). i. hexploit (incr_time_seq_diverge ts).\n    i. des. esplits; eauto. }\n  { instantiate (1:=memory).\n    eapply memory_times_wf_traced in STEPS0; eauto.\n    { ss. eapply cap_flex_memory_times_wf; eauto. ss. }\n    { eapply List.Forall_impl; eauto. i. ss. des; auto. }\n  }\n  { eapply STEPS1. }\n  { eapply list_Forall_sum.\n    { eapply FORALL2. }\n    { eapply NORMAL. }\n    i. ss. des; auto.\n  }\n  { eauto. }\n  { eauto. }\n  { eauto. }\n  i. des. exists tr_reserve, tr_cancel. esplits; eauto.\n  { ii. exploit (CAP0 cap0).\n    { eapply CAP1. } i. des.\n    eexists (tr_cancel ++ ftr1), _. esplits.\n    { eapply Trace.steps_trans.\n      { eapply CANCELSTEPS. }\n      { eapply STEPS2. }\n    }\n    { eapply Forall_app; eauto.\n      eapply List.Forall_impl; eauto. i. ss. des.\n      destruct a. ss. destruct t0; ss. des_ifs.\n    }\n    { unfold cancel_normal_trace. esplits; eauto.\n      eapply List.Forall_impl; eauto. i. ss. des; auto.\n    }\n    { eauto. }\n    { ss. }\n  }\n  { unfold cancel_normal_trace. esplits; eauto.\n    eapply List.Forall_impl; eauto. i. ss. des; auto. }\nQed.\n\n\nDefinition pf_consistent_super_strong_aux lang (e0:Thread.t lang)\n           (tr : Trace.t)\n           (times: Loc.t -> (Time.t -> Prop))\n  : Prop :=\n  forall cap (tm: Loc.t -> nat) max\n         (CAPTM: forall loc, Time.lt (Memory.max_ts loc (Thread.memory e0)) (incr_time_seq (tm loc)))\n         (CAP: cap_flex (Thread.memory e0) cap (fun loc => incr_time_seq (tm loc)))\n         (MAX: concrete_promise_max_timemap\n                 ((Thread.memory e0))\n                 ((Local.promises (Thread.local e0)))\n                 max),\n  exists ftr e1 f,\n    (<<STEPS: Trace.steps ftr (Thread.mk _ (Thread.state e0) (Thread.local e0) TimeMap.bot cap) e1>>) /\\\n    (<<EVENTS: List.Forall (fun em => <<SAT: (promise_free\n                                                /1\\ no_sc\n                                                /1\\ no_read_msgs (fun loc ts => ~ (covered loc ts (Local.promises (Thread.local e0)) \\/ concrete_promised (Thread.memory e0) loc ts \\/ Time.lt (incr_time_seq (tm loc)) ts))\n                                                /1\\ write_not_in (fun loc ts => (<<TS: Time.le ts (incr_time_seq (tm loc))>>) /\\ (<<PROM: ~ covered loc ts (Local.promises (Thread.local e0))>>))\n                                                /1\\ wf_time_evt times) (snd em)>> /\\ <<TAU: ThreadEvent.get_machine_event (snd em) = MachineEvent.silent>>) ftr >>) /\\\n\n    (<<CANCELNORMAL: cancel_normal_trace ftr>>) /\\\n    (<<SPLIT:\n       forall ftr0 ftr1 e_mid\n              (FTRACE: ftr = ftr0 ++ ftr1)\n              (STEPS0: Trace.steps ftr0 (Thread.mk _ (Thread.state e0) (Thread.local e0) TimeMap.bot cap) e_mid)\n              (STEPS1: Trace.steps ftr1 e_mid e1)\n              (NORMAL: List.Forall (fun em => ~ ThreadEvent.is_cancel (snd em)) ftr1),\n       exists ftr_reserve ftr_cancel e2,\n         (<<STEPS: Trace.steps ftr_reserve e_mid e2>>) /\\\n         (<<RESERVE: List.Forall (fun em => <<SAT: (ThreadEvent.is_reserve\n                                                     /1\\ wf_time_evt times\n                                                     /1\\ write_not_in (fun loc ts => (<<TS: Time.le ts (incr_time_seq (tm loc))>>) /\\ (<<PROM: ~ covered loc ts (Local.promises (Thread.local e0))>>))) (snd em)>>) ftr_reserve>>) /\\\n         (<<CANCEL: List.Forall (fun em => <<SAT: (ThreadEvent.is_cancel /1\\ wf_time_evt times) (snd em)>>) ftr_cancel>>) /\\\n         (<<CONSISTENT: pf_consistent_special e2 (ftr_cancel ++ ftr1) times>>) /\\\n         (<<CANCELNORMAL: cancel_normal_trace (ftr_cancel ++ ftr1)>>)>>) /\\\n\n    (<<MAPLT: mapping_map_lt f>>) /\\\n    (<<MAPIDENT: forall loc ts fts\n                        (TS: Time.le fts (max loc))\n                        (MAP: f loc ts fts),\n        ts = fts>>) /\\\n    (<<BOUND: forall loc ts fts (TS: Time.lt (max loc) fts) (MAP: f loc ts fts),\n        Time.lt (max loc) ts /\\ Time.le (incr_time_seq (tm loc)) fts>>) /\\\n    (<<TRACE: List.Forall2 (fun em fem => tevent_map_weak f (snd fem) (snd em)) tr ftr>>) /\\\n    (__guard__((exists st',\n                   (<<LOCAL: Local.failure_step (Thread.local e1)>>) /\\\n                   (<<FAILURE: Language.step lang ProgramEvent.failure (@Thread.state lang e1) st'>>)) \\/\n               (<<PROMISES: (Local.promises (Thread.local e1)) = Memory.bot>>))).\n\nLemma pf_consistent_super_strong_easy_aux\n      lang (th: Thread.t lang) tr times\n      (WF: Local.wf (Thread.local th) (Thread.memory th))\n      (MEM: Memory.closed (Thread.memory th))\n      (CONSISTENT: pf_consistent_super_strong_split th tr times)\n  :\n    pf_consistent_super_strong_aux th tr times.\nProof.\n  ii. exploit CONSISTENT; eauto. i. des.\n  assert (MLE: Memory.le (Local.promises (Thread.local th)) cap).\n  { etrans.\n    { eapply WF. }\n    { eapply CAP. }\n  }\n  esplits; eauto.\n  { exploit write_not_in_traced; eauto.\n    intros WRITENOTIN.\n    exploit no_read_unreadable_traced; eauto.\n    intros NOREAD. ss.\n    esplits; eauto.\n    eapply list_Forall_sum.\n    { eapply list_Forall_sum.\n      { eapply WRITENOTIN. }\n      { eapply NOREAD. }\n      instantiate (1:=fun lce => (no_read_msgs (fun loc ts => ~ (covered loc ts (Local.promises (Thread.local th)) \\/ concrete_promised (Thread.memory th) loc ts \\/ Time.lt (incr_time_seq (tm loc)) ts))\n                                               /1\\ write_not_in (fun loc ts => (<<TS: Time.le ts (incr_time_seq (tm loc))>>) /\\ (<<PROM: ~ covered loc ts (Local.promises (Thread.local th))>>))) (snd lce)).\n      i. ss. splits.\n      { eapply no_read_msgs_mon; eauto. i.\n        eapply not_or_and in PR. des.\n        eapply not_or_and in PR0. des. econs.\n        { eapply unwritable_eq; eauto. econs; eauto.\n          eapply cap_flex_covered; eauto. ss. econs; eauto.\n          { ss. destruct (Time.bot_spec x2); auto. inv H.\n            exfalso. eapply PR0. econs. eapply MEM. }\n          { ss. destruct (Time.le_lt_dec x2 (incr_time_seq (tm x0))); ss. }\n        }\n        { i. eapply PR0.\n          eapply cap_flex_inv in GET; eauto. des; ss. econs; eauto. }\n      }\n      { eapply write_not_in_mon_bot; eauto. i. des.\n        eapply unwritable_eq; eauto. econs; eauto.\n        eapply cap_flex_covered; eauto. ss. }\n    }\n    { eapply EVENTS. }\n    { i. ss. des. splits; auto. }\n  }\n  { i. exploit SPLIT; eauto. i. des. esplits; eauto.\n    exploit write_not_in_traced.\n    { eapply Trace.steps_trans.\n      { eapply STEPS0. }\n      { eapply STEPS2. }\n    }\n    { eauto. }\n    i. ss.\n    eapply list_Forall_sum.\n    { eapply RESERVE. }\n    { eapply Forall_app_inv in x0. des. eapply FORALL2. }\n    i. ss. des. splits; auto.\n    { eapply write_not_in_mon_bot; eauto. i. des.\n      eapply unwritable_eq; eauto. econs; eauto.\n      eapply cap_flex_covered; eauto. ss. }\n  }\nQed.\n\n\nDefinition pf_consistent_super_strong_aux2 lang (e0:Thread.t lang)\n           (tr : Trace.t)\n           (times: Loc.t -> (Time.t -> Prop))\n  : Prop :=\n  forall mem1 tm max\n         (FUTURE: Memory.future_weak (Thread.memory e0) mem1)\n         (CLOSED: Memory.closed mem1)\n         (LOCAL: Local.wf (Thread.local e0) mem1)\n         (MAX: concrete_promise_max_timemap\n                 ((Thread.memory e0))\n                 ((Local.promises (Thread.local e0)))\n                 max),\n  exists ftr e1 f,\n    (<<STEPS: Trace.steps ftr (Thread.mk _ (Thread.state e0) (Thread.local e0) TimeMap.bot mem1) e1>>) /\\\n    (<<EVENTS: List.Forall (fun em => <<SAT: (promise_free\n                                                /1\\ no_sc\n                                                /1\\ no_read_msgs (fun loc ts => ~ (covered loc ts (Local.promises (Thread.local e0)) \\/ concrete_promised (Thread.memory e0) loc ts \\/ Time.lt (tm loc) ts))\n                                                /1\\ write_not_in (fun loc ts => (<<TS: Time.le ts (tm loc)>>) /\\ (<<PROM: ~ covered loc ts (Local.promises (Thread.local e0))>>))\n                                                /1\\ wf_time_evt times) (snd em)>> /\\ <<TAU: ThreadEvent.get_machine_event (snd em) = MachineEvent.silent>>) ftr >>) /\\\n\n    (<<CANCELNORMAL: cancel_normal_trace ftr>>) /\\\n    (<<SPLIT:\n       forall ftr0 ftr1\n              (FTRACE: ftr = ftr0 ++ ftr1)\n              (NORMAL: List.Forall (fun em => ~ ThreadEvent.is_cancel (snd em)) ftr1),\n       exists ftr_reserve ftr_cancel e2,\n         (<<STEPS: Trace.steps (ftr0 ++ ftr_reserve) (Thread.mk _ (Thread.state e0) (Thread.local e0) TimeMap.bot mem1) e2>>) /\\\n         (<<RESERVE: List.Forall (fun em => <<SAT: (ThreadEvent.is_reserve\n                                                      /1\\ wf_time_evt times\n                                                      /1\\ write_not_in (fun loc ts => (<<TS: Time.le ts (tm loc)>>) /\\ (<<PROM: ~ covered loc ts (Local.promises (Thread.local e0))>>))) (snd em)>>) ftr_reserve>>) /\\\n         (<<CANCEL: List.Forall (fun em => <<SAT: (ThreadEvent.is_cancel /1\\ wf_time_evt times) (snd em)>>) ftr_cancel>>) /\\\n         (<<CONSISTENT: pf_consistent_special e2 (ftr_cancel ++ ftr1) times>>) /\\\n         (<<CANCELNORMAL: cancel_normal_trace (ftr_cancel ++ ftr1)>>)>>) /\\\n\n    (<<MAPLT: mapping_map_lt f>>) /\\\n    (<<MAPIDENT: forall loc ts fts\n                     (TS: Time.le fts (max loc))\n                     (MAP: f loc ts fts),\n        ts = fts>>) /\\\n    (<<BOUND: forall loc ts fts (TS: Time.lt (max loc) fts) (MAP: f loc ts fts),\n        Time.lt (max loc) ts /\\ Time.le (tm loc) fts>>) /\\\n    (<<TRACE: List.Forall2 (fun em fem => tevent_map_weak f (snd fem) (snd em)) tr ftr>>) /\\\n    (__guard__((exists st',\n                   (<<LOCAL: Local.failure_step (Thread.local e1)>>) /\\\n                   (<<FAILURE: Language.step lang ProgramEvent.failure (@Thread.state lang e1) st'>>)) \\/\n               ((<<PROMISES: (Local.promises (Thread.local e1)) = Memory.bot>>)))).\n\nLemma thread_trace_trace_match_map lang (ttr: ThreadTrace.t lang) (tr: Trace.t)\n      (MATCH: List.Forall2\n                (fun the lce =>\n                   (Thread.local (fst the)) = (fst lce) /\\\n                   (snd the) = (snd lce)) ttr tr)\n  :\n    tr = List.map (fun the => ((Thread.local (fst the)), snd the)) ttr.\nProof.\n  ginduction ttr; eauto; i; ss.\n  { inv MATCH. ss. }\n  { inv MATCH. f_equal; eauto. destruct a, y. ss. des. clarify. }\nQed.\n\nLemma pf_consistent_super_strong_aux_aux2\n      lang (th: Thread.t lang) tr times\n      (WF: Local.wf (Thread.local th) (Thread.memory th))\n      (MEM: Memory.closed (Thread.memory th))\n      (CONSISTENT: pf_consistent_super_strong_aux th tr times)\n  :\n    pf_consistent_super_strong_aux2 th tr times.\nProof.\n  ii.\n  assert (TM: exists (ftm: Loc.t -> nat),\n             forall loc,\n               (<<TM0: Time.lt (Memory.max_ts loc (Thread.memory th)) (incr_time_seq (ftm loc))>>) /\\\n               (<<TM1: Time.lt (Memory.max_ts loc mem1) (incr_time_seq (ftm loc))>>) /\\\n               (<<TM2: Time.le (tm loc) (incr_time_seq (ftm loc))>>)).\n  { eapply (choice\n              (fun loc n =>\n                 (<<TM0: Time.lt (Memory.max_ts loc (Thread.memory th)) (incr_time_seq n)>>) /\\\n                 (<<TM1: Time.lt (Memory.max_ts loc mem1) (incr_time_seq n)>>) /\\\n                 (<<TM2: Time.le (tm loc) (incr_time_seq n)>>))).\n    intros loc. hexploit (incr_time_seq_diverge\n                            (Time.join (Time.join\n                                          (Memory.max_ts loc (Thread.memory th))\n                                          (Memory.max_ts loc mem1))\n                                       (tm loc))).\n    i. des. exists n. splits.\n    { eapply TimeFacts.le_lt_lt; eauto. etrans.\n      { eapply Time.join_l. }\n      eapply Time.join_l. }\n    { eapply TimeFacts.le_lt_lt; eauto. etrans.\n      { eapply Time.join_r. }\n      eapply Time.join_l. }\n    { left. eapply TimeFacts.le_lt_lt; eauto.\n      eapply Time.join_r. }\n  }\n  des.\n  hexploit (@cap_flex_exists (Thread.memory th) (fun loc => incr_time_seq (ftm loc))); eauto.\n  { i. eapply TM. }\n  intros [cap CAP]. des.\n  exploit CONSISTENT; eauto.\n  { i. eapply TM. }\n  i. des.\n  exploit ThreadTrace.trace_steps_thread_trace_steps; eauto. i. des.\n  hexploit (@cap_flex_future_memory_map (Thread.memory th)); eauto.\n  { i. eapply TM. }\n  { i. left. eapply TM. }\n  intros MEMORY. destruct e1. ss.\n  hexploit thread_trace_steps_map.\n  { eapply ident_map_le; eauto. }\n  { eapply ident_map_bot; eauto. }\n  { eapply ident_map_eq; eauto. }\n  { eapply List.Forall_forall. i. eapply ident_map_mappable_evt. }\n  { eapply STEPS0. }\n  { ss. }\n  { ss. }\n  { ss. }\n  { eapply cap_flex_wf; eauto. }\n  { eapply LOCAL. }\n  { eauto. }\n  { eapply cap_flex_closed; eauto. i. eapply TM. }\n  { eapply Memory.closed_timemap_bot; eauto. eapply CLOSED. }\n  { eapply Memory.closed_timemap_bot; eauto.\n    eapply cap_flex_closed; eauto. i. eapply TM. }\n  { econs; eauto.\n    { eapply ident_map_local. }\n    { eapply mapping_map_lt_collapsable_unwritable. eapply ident_map_lt. }\n    { eapply ident_map_timemap. }\n    { refl. }\n  }\n  i. des.\n  exploit ThreadTrace.thread_trace_steps_trace_steps; eauto. i. des.\n  assert (LCTRACE: List.Forall2\n                     (fun em fem : Local.t * ThreadEvent.t => tevent_map ident_map (snd fem) (snd em)) ftr tr0).\n  { eapply list_Forall2_compose.\n    { eapply list_Forall2_rev. eauto. }\n    { eapply list_Forall2_compose.\n      { eauto. }\n      { eauto. }\n      simpl. i.\n      instantiate (1:=fun em fem => tevent_map ident_map (snd fem) (snd em)).\n      ss. des. rewrite SAT2 in *. auto.\n    }\n    i. ss. des. rewrite SAT2 in *. auto.\n  }\n  assert (FEVENTS: List.Forall\n                     (fun em : Local.t * ThreadEvent.t =>\n                        ((((promise_free (snd em) /\\ no_sc (snd em)) /\\\n                           no_read_msgs\n                             (fun (loc : Loc.t) (ts : Time.t) =>\n                                ~\n                                  (covered loc ts (Local.promises (Thread.local th)) \\/\n                                   concrete_promised (Thread.memory th) loc ts \\/ Time.lt (tm loc) ts))\n                             (snd em)) /\\\n                          write_not_in\n                            (fun (loc : Loc.t) (ts : Time.t) =>\n                               Time.le ts (tm loc) /\\ ~ covered loc ts (Local.promises (Thread.local th)))\n                            (snd em)) /\\ wf_time_evt times (snd em)) /\\\n                        ThreadEvent.get_machine_event (snd em) = MachineEvent.silent) tr0).\n  { esplits; eauto.\n    eapply List.Forall_forall. i.\n    eapply list_Forall2_in in H; eauto. des.\n    eapply List.Forall_forall in IN; eauto. ss. des.\n    destruct a, x. ss. splits; auto.\n    { inv SAT; ss. inv FROM. inv TO. inv KIND; ss.\n      inv MSG0; ss. inv MSG; ss. inv MAP1; ss. }\n    { inv SAT; ss. }\n    { inv SAT; ss.\n      { inv TO. ii. eapply SAT3. ii. eapply H. des; auto.\n        right. right. eapply TimeFacts.le_lt_lt; eauto. apply TM. }\n      { inv FROM. ii. eapply SAT3. ii. eapply H. des; auto.\n        right. right. eapply TimeFacts.le_lt_lt; eauto. apply TM. }\n    }\n    { inv SAT; ss.\n      { inv TO. inv FROM. inv KIND; ss. ii. eapply SAT2; eauto.\n        des. split; auto. red. etrans; eauto. eapply TM. }\n      { inv TO. inv FROM. ii. eapply SAT2; eauto.\n        des. split; auto. red. etrans; eauto. eapply TM. }\n      { inv TO. inv FROM. ii. eapply SAT2; eauto.\n        des. split; auto. red. etrans; eauto. eapply TM. }\n    }\n    { inv SAT; ss.\n      { inv FROM. inv TO. auto. }\n      { inv FROM. inv TO. auto. }\n      { inv FROM. inv TO. auto. }\n    }\n    { inv SAT; ss. }\n  }\n  esplits; eauto.\n  { unfold cancel_normal_trace in *. des. subst.\n    eapply List.Forall2_app_inv_l in LCTRACE. des. subst. esplits; eauto.\n    { eapply List.Forall_forall. i. eapply list_Forall2_in in H; eauto. des.\n      destruct a, x. ss. eapply List.Forall_forall in IN; eauto. ss. inv SAT; ss.\n      inv KIND; ss; des_ifs. inv MSG. }\n    { eapply List.Forall_forall. i. eapply list_Forall2_in in H; eauto. des.\n      destruct a, x. ss. eapply List.Forall_forall in IN; eauto. ss. inv SAT; ss.\n      inv KIND; ss; des_ifs. inv MSG. }\n  }\n  { i. subst.\n    assert (exists l1 l2 e_mid fe_mid,\n               (<<EQ: ftr = l1 ++ l2>>) /\\\n               (<<STEPSCAP1: Trace.steps\n                               l1\n                               (Thread.mk _ (Thread.state th) (Thread.local th) TimeMap.bot cap) e_mid>>) /\\\n               (<<STEPSCAP2: Trace.steps\n                               l2\n                               e_mid\n                               (Thread.mk _ state local sc memory)>>) /\\\n               (<<STEPSMEM: Trace.steps\n                              ftr1\n                              (Thread.mk _ (Thread.state th) (Thread.local th) TimeMap.bot mem1) fe_mid>>) /\\\n               (<<MAP: thread_map ident_map e_mid fe_mid>>) /\\\n               (<<LCTRACE0: List.Forall2\n                             (fun em fem => tevent_map ident_map (snd fem) (snd em))\n                             l1 ftr1>>) /\\\n               (<<LCTRACE1: List.Forall2\n                              (fun em fem => tevent_map ident_map (snd fem) (snd em))\n                              l2 ftr2>>)).\n    { clear SPLIT CANCELNORMAL EVENTS x1 CAP MAPLT MAPIDENT BOUND FEVENTS.\n      eapply List.Forall2_app_inv_r in MATCH0. des. subst.\n      eapply List.Forall2_app_inv_r in TRACE0. des. subst.\n      eapply ThreadTrace.steps_separate in STEPS0. des.\n      eapply ThreadTrace.steps_separate in STEPS1. des.\n      eapply ThreadTrace.thread_trace_steps_trace_steps in STEPS3.\n      dup STEPS4. eapply ThreadTrace.thread_trace_steps_trace_steps in STEPS4.\n      eapply ThreadTrace.thread_trace_steps_trace_steps in STEPS0. des.\n      assert (ftr1 = tr0).\n      { eapply thread_trace_trace_match_map in MATCH2.\n        eapply thread_trace_trace_match_map in MATCH0. subst. auto. }\n      subst.\n      assert (ftr = tr2 ++ tr1).\n      { eapply thread_trace_trace_match_map in MATCH.\n        eapply thread_trace_trace_match_map in MATCH4.\n        eapply thread_trace_trace_match_map in MATCH3. subst.\n        eapply List.map_app. }\n      subst. esplits; eauto.\n      { destruct l3.\n        { inv TRACE1. inv MATCH1. inv NORMAL. inv MATCH3.\n          inv STEPS5; ss. inv STEPS0; ss. }\n        { inv TRACE1. inv MATCH1. inv MATCH3.\n          inv STEPS5; ss. inv STEPS1; ss. clarify. ss. des. auto. }\n      }\n      { eapply list_Forall2_compose.\n        { eapply list_Forall2_rev. eapply MATCH4. }\n        { eapply list_Forall2_compose.\n          { eapply TRACE0. }\n          { eauto. }\n          { simpl. i. instantiate (1:=fun em fem =>tevent_map ident_map (snd fem) (snd em)).\n            ss. des. rewrite SAT2 in *. auto. }\n        }\n        { i. ss. des. rewrite SAT2 in *. auto. }\n      }\n      { eapply list_Forall2_compose.\n        { eapply list_Forall2_rev. eapply MATCH3. }\n        { eapply list_Forall2_compose.\n          { eapply TRACE1. }\n          { eauto. }\n          { simpl. i. instantiate (1:=fun em fem =>tevent_map ident_map (snd fem) (snd em)).\n            ss. des. rewrite SAT2 in *. auto. }\n        }\n        { i. ss. des. rewrite SAT2 in *. auto. }\n      }\n    }\n    clear LCTRACE. des. exploit SPLIT; eauto.\n    { clear - LCTRACE1 NORMAL.\n      eapply List.Forall_forall. i. eapply list_Forall2_in2 in H; eauto.\n      des. eapply List.Forall_forall in IN; eauto. ss.\n      destruct b, x. ss. inv SAT; ss.\n      inv KIND; ss; des_ifs. inv MSG. }\n    i. des.\n    inv MAP0. destruct e2. ss.\n\n    exploit Trace.steps_future; try apply STEPSCAP1; eauto.\n    { eapply cap_flex_wf; eauto. }\n    { eapply Memory.closed_timemap_bot; eauto.\n      eapply cap_flex_closed; eauto. i. eapply TM. }\n    { eapply cap_flex_closed; eauto. i. eapply TM. } i. des. ss.\n    exploit Trace.steps_future; try apply STEPSMEM; eauto.\n    { eapply Memory.closed_timemap_bot; eauto. eapply CLOSED. } i. des. ss.\n\n    hexploit trace_steps_map; try apply STEPS3.\n    { eapply ident_map_le; eauto. }\n    { eapply ident_map_bot; eauto. }\n    { eapply ident_map_eq; eauto. }\n    { eapply List.Forall_forall. i. eapply ident_map_mappable_evt. }\n    { ss. }\n    { ss. }\n    { ss. }\n    { eauto. }\n    { eapply WF0. }\n    all: eauto. i. des.\n    eexists ftr, ftr_cancel, _. splits.\n    { eapply Trace.steps_trans.\n      { eapply STEPSMEM. }\n      { eapply STEPS4. }\n    }\n    { clear - TM RESERVE TRACE1. eapply List.Forall_forall. i.\n      eapply list_Forall2_in in H; eauto. des.\n      eapply List.Forall_forall in IN; eauto. ss. des.\n      destruct a, x. ss. unfold ident_map in *.\n      inv EVENT; ss; des; subst; eauto. inv MSG; inv KIND; ss. splits; auto.\n      ii. eapply IN0; eauto. des. splits; auto. etrans; eauto. eapply TM. }\n    { eauto. }\n    { eapply pf_consistent_speciali_events_map with (tr1 := ftr_cancel ++ ftr2) in CONSISTENT0; cycle 1.\n      { eapply list_Forall2_app.\n        { eapply list_Forall_refl_Forall2; eauto. eapply List.Forall_forall.\n          ii. destruct x. ss. destruct t0; econs; ss. }\n        { eapply list_Forall2_impl; eauto. i. eapply tevent_map_tevent_map_weak; eauto. }\n      }\n      { eapply Trace.steps_future in STEPS3; eauto. des.\n        eapply Trace.steps_future in STEPS4; eauto. des.\n        eapply ident_map_pf_consistent_super_strong_easy; eauto.\n        econs; eauto.\n        eapply mapping_map_lt_collapsable_unwritable; eauto. eapply ident_map_lt; eauto.\n      }\n    }\n    { exists ftr_cancel, ftr2. splits; auto.\n      eapply List.Forall_impl; eauto. i. ss. des. auto. }\n  }\n  { ii. exploit BOUND; eauto. i. des. split; auto.\n    etrans; eauto. eapply TM. }\n  { eapply list_Forall2_compose; eauto. i. ss. des.\n    eapply ident_map_compose_tevent_weak; eauto.\n    eapply tevent_map_tevent_map_weak; eauto.\n  }\n  { ss. unguard. des.\n    { left. esplits; eauto. eapply failure_step_map; eauto.\n      { eapply ident_map_le. }\n      { eapply ident_map_eq. }\n      { inv MAP. auto. }\n    }\n    { right. inv MAP. inv LOCAL0. rewrite PROMISES in *.\n      eapply bot_promises_map; eauto. }\n  }\nQed.\n\nLemma pf_consistent_super_strong_easy_promise_consistent lang (e0: Thread.t lang) tr times\n      (CONSISTENT: pf_consistent_super_strong_easy e0 tr times)\n      (CLOSED: Memory.closed (Thread.memory e0))\n      (LOCAL: Local.wf (Thread.local e0) (Thread.memory e0))\n  :\n    Local.promise_consistent (Thread.local e0).\nProof.\n  hexploit (@concrete_promise_max_timemap_exists\n              (Thread.memory e0)\n              (Local.promises (Thread.local e0))); eauto.\n  { eapply CLOSED. } i. des.\n  assert (exists (f: Loc.t -> nat),\n             forall loc,\n               Time.lt (Memory.max_ts loc (Thread.memory e0)) (incr_time_seq (f loc))).\n  { eapply (choice\n              (fun loc n =>\n                 Time.lt (Memory.max_ts loc (Thread.memory e0)) (incr_time_seq n))).\n    i. eapply incr_time_seq_diverge; eauto. }\n  des.\n  exploit (@cap_flex_exists\n             (Thread.memory e0)\n             (fun loc => incr_time_seq (f loc))); eauto. i. des.\n  exploit CONSISTENT; eauto. i. des.\n  eapply Trace.steps_promise_consistent in STEPS; eauto; ss.\n  { unguard. des.\n    { inv LOCAL0. ss. }\n    { ii. erewrite PROMISES in *. erewrite Memory.bot_get in *. ss. }\n  }\n  { eapply cap_flex_wf; eauto. }\n  { eapply Memory.closed_timemap_bot; eauto.\n    eapply cap_flex_closed; eauto. }\n  { eapply cap_flex_closed; eauto. }\nQed.\n\nDefinition pf_consistent_super_strong lang (e0:Thread.t lang)\n           (tr : Trace.t)\n           (times: Loc.t -> (Time.t -> Prop))\n  : Prop :=\n  forall mem1 tm sc max\n         (FUTURE: Memory.future_weak (Thread.memory e0) mem1)\n         (CLOSED: Memory.closed mem1)\n         (LOCAL: Local.wf (Thread.local e0) mem1)\n         (MAX: concrete_promise_max_timemap\n                 ((Thread.memory e0))\n                 ((Local.promises (Thread.local e0)))\n                 max),\n  exists ftr e1 f,\n    (<<STEPS: Trace.steps ftr (Thread.mk _ (Thread.state e0) (Thread.local e0) sc mem1) e1>>) /\\\n    (<<EVENTS: List.Forall (fun em => <<SAT: (promise_free\n                                                /1\\ no_sc\n                                                /1\\ no_read_msgs (fun loc ts => ~ (covered loc ts (Local.promises (Thread.local e0)) \\/ concrete_promised (Thread.memory e0) loc ts \\/ Time.lt (tm loc) ts))\n                                                /1\\ write_not_in (fun loc ts => (<<TS: Time.le ts (tm loc)>>) /\\ (<<PROM: ~ covered loc ts (Local.promises (Thread.local e0))>>))\n                                                /1\\ wf_time_evt times) (snd em)>> /\\ <<TAU: ThreadEvent.get_machine_event (snd em) = MachineEvent.silent>>) ftr >>) /\\\n\n    (<<CANCELNORMAL: cancel_normal_trace ftr>>) /\\\n    (<<SPLIT:\n       forall ftr0 ftr1\n              (FTRACE: ftr = ftr0 ++ ftr1)\n              (NORMAL: List.Forall (fun em => ~ ThreadEvent.is_cancel (snd em)) ftr1),\n       exists ftr_reserve ftr_cancel e2,\n         (<<STEPS: Trace.steps (ftr0 ++ ftr_reserve) (Thread.mk _ (Thread.state e0) (Thread.local e0) sc mem1) e2>>) /\\\n         (<<RESERVE: List.Forall (fun em => <<SAT: (ThreadEvent.is_reserve\n                                                      /1\\ wf_time_evt times\n                                                      /1\\ write_not_in (fun loc ts => (<<TS: Time.le ts (tm loc)>>) /\\ (<<PROM: ~ covered loc ts (Local.promises (Thread.local e0))>>))) (snd em)>>) ftr_reserve>>) /\\\n         (<<CANCEL: List.Forall (fun em => <<SAT: (ThreadEvent.is_cancel /1\\ wf_time_evt times) (snd em)>>) ftr_cancel>>) /\\\n         (<<CONSISTENT: pf_consistent_super_strong_easy e2 (ftr_cancel ++ ftr1) times>>) /\\\n         (<<PROMCONSISTENT: Local.promise_consistent (Thread.local e2)>>) /\\\n         (<<CANCELNORMAL: cancel_normal_trace (ftr_cancel ++ ftr1)>>) /\\\n         (<<GOOD: good_future tm mem1 (Thread.memory e2)>>) /\\\n         (<<SC: (Thread.sc e2) = sc>>)>>) /\\\n\n    (<<MAPLT: mapping_map_lt f>>) /\\\n    (<<MAPIDENT: forall loc ts fts\n                        (TS: Time.le fts (max loc))\n                        (MAP: f loc ts fts),\n        ts = fts>>) /\\\n    (<<BOUND: forall loc ts fts (TS: Time.lt (max loc) fts) (MAP: f loc ts fts),\n        Time.lt (max loc) ts /\\ Time.le (tm loc) fts>>) /\\\n    (<<TRACE: List.Forall2 (fun em fem => tevent_map_weak f (snd fem) (snd em)) tr ftr>>) /\\\n    (<<GOOD: good_future tm mem1 (Thread.memory e1)>>) /\\\n    (<<SC: (Thread.sc e1) = sc>>) /\\\n    (<<PROMCONSISTENT: Local.promise_consistent (Thread.local e1)>>) /\\\n    (__guard__((exists st',\n                   (<<LOCAL: Local.failure_step (Thread.local e1)>>) /\\\n                   (<<FAILURE: Language.step lang ProgramEvent.failure (@Thread.state lang e1) st'>>)) \\/\n               ((<<PROMISES: (Local.promises (Thread.local e1)) = Memory.bot>>) /\\\n                (<<WRITES: forall loc from to val released\n                                  (GET: Memory.get loc to (Local.promises (Thread.local e0)) = Some (from, Message.concrete val released)),\n                    exists th e,\n                      (<<WRITING: promise_writing_event loc from to val released e>>) /\\\n                      (<<IN: List.In (th, e) ftr>>)>>)))).\n\nLemma pf_consistent_super_strong_aux2_super_strong\n      lang (th: Thread.t lang) tr times\n      (WF: Local.wf (Thread.local th) (Thread.memory th))\n      (MEM: Memory.closed (Thread.memory th))\n      (CONSISTENT: pf_consistent_super_strong_aux2 th tr times)\n  :\n    pf_consistent_super_strong th tr times.\nProof.\n  ii. set (tm0:=TimeMap.join tm (fun loc => Time.incr (Memory.max_ts loc mem1))).\n  assert (TM0: forall loc, Time.lt (Memory.max_ts loc mem1) (tm0 loc)).\n  { i. eapply TimeFacts.lt_le_lt.\n    { eapply Time.incr_spec. }\n    { eapply Time.join_r. }\n  }\n  assert (TM1: TimeMap.le tm tm0).\n  { eapply TimeMap.join_l. }\n  exploit (CONSISTENT mem1 tm0 max); eauto. i. des. destruct e1. ss.\n  dup STEPS. eapply no_sc_any_sc_traced in STEPS; eauto; cycle 1.\n  { eapply List.Forall_impl; eauto. i. ss. des. auto. } des.\n  esplits; eauto.\n  { eapply List.Forall_impl; eauto. i. ss. des. splits; auto.\n    { eapply no_read_msgs_mon; eauto. ii. eapply PR. des; auto.\n      right. right. eapply TimeFacts.le_lt_lt; eauto. }\n    { eapply write_not_in_mon; eauto. ii. des. split; auto.\n      red. etrans; eauto. }\n  }\n  { i. subst.\n    exploit SPLIT; eauto. i. des. destruct e2. ss.\n    assert (NOSC: List.Forall (fun em => no_sc (snd em)) (ftr0 ++ ftr_reserve)).\n    { eapply Forall_app.\n      { eapply Forall_app_inv in EVENTS. des.\n        eapply List.Forall_impl; eauto. i. ss. des. auto. }\n      { eapply List.Forall_impl; eauto. i. ss. des.\n        destruct a. ss. destruct t0; ss. }\n    }\n    dup STEPS.\n    eapply no_sc_any_sc_traced in STEPS; eauto; cycle 1. des.\n    esplits; eauto.\n    { eapply List.Forall_impl; eauto. i. ss. des. splits; auto.\n      eapply write_not_in_mon; eauto. i. ss. des. splits; auto. etrans; eauto. }\n    { eapply pf_consistent_speciali_strong_easy in CONSISTENT0; eauto. }\n    { eapply Trace.steps_future in STEPS2; eauto.\n      { ss. des. eapply pf_consistent_speciali_strong_easy in CONSISTENT0; eauto.\n        eapply pf_consistent_super_strong_easy_promise_consistent in CONSISTENT0; eauto. }\n      { ss. eapply Memory.closed_timemap_bot. eapply CLOSED. }\n    }\n    { eapply good_future_mon with (tm1:=tm0); auto.\n      eapply write_not_in_good_future_traced in STEPS2; eauto.\n      { ss. eapply Memory.closed_timemap_bot; eauto. eapply CLOSED. }\n      { eapply Forall_app.\n        { eapply Forall_app_inv in EVENTS. des. ss.\n          eapply List.Forall_impl; eauto. i. ss. des.\n          eapply write_not_in_mon; eauto. ii. des. split; auto.\n          ii. eapply PROM. eapply memory_le_covered; eauto. eapply LOCAL. }\n        { eapply List.Forall_impl; eauto. i. ss. des.\n          eapply write_not_in_mon; eauto. ii. des. split; auto.\n          ii. eapply PROM. eapply memory_le_covered; eauto. eapply LOCAL. }\n      }\n    }\n    { ss. eapply no_sc_same_sc_traced in STEPS3; eauto. }\n  }\n  { ii. exploit BOUND; eauto. i. des. splits; auto. etrans; eauto. }\n  { eapply good_future_mon with (tm1:=tm0); auto.\n    eapply write_not_in_good_future_traced in STEPS0; eauto.\n    { ss. eapply Memory.closed_timemap_bot; eauto. eapply CLOSED. }\n    { eapply List.Forall_impl; eauto. i. ss. des. splits; auto.\n      eapply write_not_in_mon; eauto. ii. des. split; auto.\n      ii. eapply PR0. eapply memory_le_covered; eauto. eapply LOCAL. }\n  }\n  { eapply no_sc_same_sc_traced in STEPS1; eauto.\n    eapply List.Forall_impl; eauto. i. ss. des. auto. }\n  { unguard. des.\n    { inv LOCAL0. ss. }\n    { ss. eapply Local.bot_promise_consistent; eauto. }\n  }\n  { ss. unguard. des; eauto. right. splits; auto.\n    i. eapply steps_promise_decrease_promise_writing_event in STEPS1; eauto.\n    des; eauto. ss. erewrite PROMISES in *. erewrite Memory.bot_get in *. ss. }\nQed.\n\n\nLemma pf_consistent_super_strong_not_easy lang (th: Thread.t lang)\n      tr times\n      (LOCAL: Local.wf (Thread.local th) (Thread.memory th))\n      (MEM: Memory.closed (Thread.memory th))\n      (CONSISTENT: pf_consistent_super_strong_easy th tr times)\n      (CANCELNORMAL: cancel_normal_trace tr)\n      (MWF: memory_times_wf times (Thread.memory th))\n      (DIVERGE: forall loc n, times loc (incr_time_seq n))\n  :\n    pf_consistent_super_strong th tr times.\nProof.\n  eapply pf_consistent_super_strong_aux2_super_strong; eauto.\n  eapply pf_consistent_super_strong_aux_aux2; eauto.\n  eapply pf_consistent_super_strong_easy_aux; eauto.\n  eapply pf_consistent_flex_super_strong_easy_split; eauto.\nQed.\n\nLemma consistent_pf_consistent_super_strong lang (th: Thread.t lang)\n      (LOCAL: Local.wf (Thread.local th) (Thread.memory th))\n      (MEM: Memory.closed (Thread.memory th))\n      (CONSISTENT: Thread.consistent th)\n  :\n    exists tr certimes,\n      (<<WO: forall loc, well_ordered (certimes loc)>>) /\\\n      <<CONSISTENT: pf_consistent_super_strong th tr certimes>>.\nProof.\n  eapply consistent_pf_consistent in CONSISTENT; eauto.\n  eapply pf_consistent_pf_consistent_strong in CONSISTENT; eauto.\n  eapply pf_consistent_strong_pf_consistent_strong_aux in CONSISTENT; eauto.\n  eapply pf_consistent_strong_aux_pf_consistent_flex in CONSISTENT; eauto. des.\n  eapply pf_consistent_flex_super_strong_easy in CONSISTENT0; eauto. des.\n  eapply pf_consistent_super_strong_not_easy in CONSISTENT; eauto.\nQed.\n\nLemma pf_consistent_super_strong_consistent lang (th: Thread.t lang)\n      (LOCAL: Local.wf (Thread.local th) (Thread.memory th))\n      (MEM: Memory.closed (Thread.memory th))\n      tr certimes\n      (CONSISTENT: pf_consistent_super_strong th tr certimes)\n  :\n    Thread.consistent th.\nProof.\n  hexploit (@concrete_promise_max_timemap_exists\n              ((Thread.memory th))\n              ((Local.promises (Thread.local th)))).\n  { eapply MEM. } intros [max MAX]. des.\n  ii. exploit (CONSISTENT mem1 sc1 sc1).\n  { eapply Memory.cap_future_weak; eauto. }\n  { eapply Memory.cap_closed; eauto. }\n  { eapply Local.cap_wf; eauto. }\n  { eauto. }\n  i. des.\n  eapply pred_steps_trace_steps2 in STEPS; cycle 1.\n  { instantiate (1:=fun _ => True). eapply List.Forall_impl; eauto.\n    i. ss. des. splits; auto. }\n  eapply thread_steps_pred_steps in STEPS.\n  unguard. des.\n  { destruct e1. ss. left. econs. esplits; eauto. }\n  { right. esplits; eauto. }\nQed.\n\nDefinition pf_consistent_super_strong_mon lang e0 tr certimes0 certimes1\n           (CONSISTENT: @pf_consistent_super_strong\n                          lang e0 tr certimes0)\n           (LE: certimes0 <2= certimes1)\n  :\n    pf_consistent_super_strong e0 tr certimes1.\nProof.\n  ii. exploit CONSISTENT; eauto. i. des. esplits; eauto.\n  { eapply List.Forall_impl; eauto. i. ss. des. splits; auto.\n    eapply wf_time_evt_mon; eauto. }\n  { i. exploit SPLIT; eauto. i. des. exists ftr_reserve, ftr_cancel, e2. splits; ss.\n    { eapply List.Forall_impl; eauto. i. ss. des. splits; auto.\n      eapply wf_time_evt_mon; eauto. }\n    { eapply List.Forall_impl; eauto. i. ss. des. splits; auto.\n      eapply wf_time_evt_mon; eauto. }\n    { eapply pf_consistent_super_strong_easy_mon; eauto. }\n  }\nQed.\n\nLemma promises_bot_certify_nil_easy times lang (th: Thread.t lang)\n      (PROMISES: (Local.promises (Thread.local th)) = Memory.bot)\n  :\n    pf_consistent_super_strong_easy th [] times.\nProof.\n  ii. eexists [], _, bot3. esplits; eauto.\n  { exists [], []. splits; ss. }\n  { ii. ss. }\n  { ii. ss. }\n  { ii. ss. }\n  { right. ss. }\nQed.\n\nLemma failure_certify_nil_easy times lang (th: Thread.t lang) st'\n      (FAILURE: Language.step lang ProgramEvent.failure (@Thread.state lang th) st')\n      (LOCAL: Local.failure_step (Thread.local th))\n  :\n    pf_consistent_super_strong_easy th [] times.\nProof.\n  ii. eexists [], _, bot3. esplits; eauto.\n  { exists [], []. splits; ss. }\n  { ii. ss. }\n  { ii. ss. }\n  { ii. ss. }\n  { left. ss. esplits; eauto. }\nQed.\n\nLemma promises_bot_certify_nil times lang (th: Thread.t lang)\n      (PROMISES: (Local.promises (Thread.local th)) = Memory.bot)\n  :\n    pf_consistent_super_strong th [] times.\nProof.\n  ii. eexists [], _, bot3. esplits; eauto.\n  { exists [], []. splits; ss. }\n  { i. destruct ftr0; ss. subst. esplits; eauto.\n    { ss. eapply promises_bot_certify_nil_easy; ss. }\n    { ss. ii. erewrite PROMISES in *. erewrite Memory.bot_get in *. ss. }\n    { exists [], []. splits; ss. }\n    { refl. }\n  }\n  { ii. ss. }\n  { ii. ss. }\n  { ii. ss. }\n  { refl. }\n  { eapply Local.bot_promise_consistent; eauto. }\n  { right. ss. splits; auto. i.\n    rewrite PROMISES in *. erewrite Memory.bot_get in *. ss. }\nQed.\n\nLemma failure_certify_nil times lang (th: Thread.t lang) st'\n      (FAILURE: Language.step lang ProgramEvent.failure (@Thread.state lang th) st')\n      (LOCAL: Local.failure_step (Thread.local th))\n  :\n    pf_consistent_super_strong th [] times.\nProof.\n  ii. eexists [], _, bot3. esplits; eauto.\n  { exists [], []. splits; ss. }\n  { i. destruct ftr0; ss. subst. esplits; eauto.\n    { ss. inv LOCAL. eapply failure_certify_nil_easy; eauto. }\n    { inv LOCAL. ss. }\n    { exists [], []. splits; ss. }\n    { refl. }\n  }\n  { ii. ss. }\n  { ii. ss. }\n  { ii. ss. }\n  { refl. }\n  { inv LOCAL. ss. }\n  { left. ss. esplits; eauto. }\nQed.\n\nLemma certify_nil_promises_bot_or_failure times lang (th: Thread.t lang)\n      (CONSISTENT: pf_consistent_super_strong th [] times)\n      (CLOSED: Memory.closed (Thread.memory th))\n      (LOCAL: Local.wf (Thread.local th) (Thread.memory th))\n  :\n    (<<PROMISES: (Local.promises (Thread.local th)) = Memory.bot>>) \\/\n    exists st',\n      (<<FAILURE: Language.step lang ProgramEvent.failure (@Thread.state lang th) st'>>) /\\\n      (<<LOCAL: Local.failure_step (Thread.local th)>>).\nProof.\n  exploit concrete_promise_max_timemap_exists.\n  { eapply CLOSED. } i. des.\n  exploit (CONSISTENT (Thread.memory th) TimeMap.bot (Thread.sc th) tm); eauto.\n  { refl. } i. des. inv TRACE. inv STEPS; ss.\n  unguard. des; eauto.\nQed.\n\nLemma good_future_future_future mem0 mem_good0 mem_good1 tm\n      (f0: Loc.t -> Time.t -> Time.t -> Prop)\n      (IDENT: forall loc to fto (MAP: f0 loc to fto), to = fto)\n      (MAPBOT: mapping_map_bot f0)\n      (GOOD: memory_map f0 mem0 mem_good0)\n      (FUTURE: Memory.future_weak mem_good0 mem_good1)\n      (CLOSED: Memory.closed mem0)\n      (TM0: forall loc, Time.lt (Memory.max_ts loc mem_good1) (tm loc))\n      (TM1: forall loc, Time.lt (Memory.max_ts loc mem0) (tm loc))\n  :\n    exists mem1,\n      (<<CAP: cap_flex mem0 mem1 tm>>) /\\\n      (<<MAP: memory_map ident_map mem1 mem_good1>>).\nProof.\n  exploit (@cap_flex_exists mem0 tm); eauto. intros [mem1 CAP].\n  exists mem1. splits; auto. econs.\n  { i. eapply cap_flex_inv in GET; eauto. des; auto.\n    apply GOOD in GET. des; auto. destruct fmsg as [val freleased|]; cycle 1.\n    { inv MSGLE. inv MSG. auto. }\n    eapply Memory.future_weak_get1 in GET; eauto. des.\n    dup MSG. dup MSGLE. dup MSG_LE.\n    inv MSG; inv MSGLE; inv MSG_LE; auto.\n    right. esplits; cycle 3.\n    { eauto. }\n    { eapply IDENT; eauto. }\n    { eapply message_map_incr; eauto. }\n    { econs; eauto. }\n  }\n  { i. left. exists (tm loc), Time.bot, (tm loc), Time.bot. splits; ss.\n    { eapply Time.bot_spec. }\n    { eapply Memory.max_ts_spec in GET. des. left.\n      eapply TimeFacts.le_lt_lt; eauto. }\n    { i. erewrite cap_flex_covered in ITV; eauto. }\n  }\nQed.\n\nLemma good_future_consistent times lang st lc_src lc_tgt sc_src sc_tgt mem_src mem_tgt tr\n      (f: Loc.t -> Time.t -> Time.t -> Prop)\n      (CONSISTENT: pf_consistent_super_strong\n                     (Thread.mk lang st lc_tgt sc_tgt mem_tgt)\n                     tr times)\n      (IDENT: forall loc to fto (MAP: f loc to fto), to = fto)\n      (MAPBOT: mapping_map_bot f)\n      (LOCALSRC: Local.wf lc_src mem_src)\n      (LOCALTGT: Local.wf lc_tgt mem_tgt)\n      (MEMSRC: Memory.closed mem_src)\n      (MEMTGT: Memory.closed mem_tgt)\n      (LOCAL: local_map f lc_tgt lc_src)\n      (MEM: memory_map f mem_tgt mem_src)\n      max_tgt\n      (MAXTGT: concrete_promise_max_timemap mem_tgt (Local.promises lc_tgt) max_tgt)\n      (MWF: memory_times_wf times mem_src)\n      (DIVERGE: forall loc n, times loc (incr_time_seq n))\n  :\n    exists tr_good f_good,\n      (<<MAPLT: mapping_map_lt f_good>>) /\\\n      (<<MAPIDENT: forall loc ts fts\n                          (TS: Time.le fts (max_tgt loc))\n                          (MAP: f_good loc ts fts),\n          ts = fts>>) /\\\n      (<<BOUND: forall loc ts fts (TS: Time.lt (max_tgt loc) fts) (MAP: f_good loc ts fts),\n          Time.lt (max_tgt loc) ts /\\ Time.lt (Memory.max_ts loc mem_tgt) fts>>) /\\\n      (<<TRACE: List.Forall2 (fun em fem => tevent_map_weak f_good (snd fem) (snd em)) tr tr_good>>) /\\\n      (<<CONSISTENT:\n         pf_consistent_super_strong (Thread.mk lang st lc_src sc_src mem_src) tr_good times>>)\n.\nProof.\n  hexploit (CONSISTENT mem_tgt (fun loc => Time.incr (Time.join (Memory.max_ts loc mem_tgt) (Memory.max_ts loc mem_src))) sc_tgt); eauto.\n  { refl. } ss.\n  intros [tr_good [e1_good [f_good [STEPSGOOD [EVENTSGOOD [CANCELNORMALGOOD [SPLITGOOD [MAPLTGOOD [IDENTGOOD [BOUNDGOOD [TRACEGOOD [GOODFUTURE [SCGOOD GOODEND]]]]]]]]]]]]]. des.\n  exists tr_good, f_good. splits; auto.\n  { i. eapply BOUNDGOOD in MAP; eauto. des. splits; eauto.\n    eapply TimeFacts.lt_le_lt; eauto. eapply TimeFacts.le_lt_lt.\n    { eapply Time.join_l. }\n    { eapply Time.incr_spec. }\n  }\n  eapply pf_consistent_super_strong_not_easy; eauto. ii. ss.\n  assert (MAXMAP: TimeMap.le max_tgt max).\n  { eapply memory_ident_map_concrete_promise_max_timemap; eauto.\n    eapply LOCAL. }\n\n  set (tm0 := TimeMap.join (fun loc => incr_time_seq (tm loc))\n                           (fun loc => Time.incr\n                                         (Time.join\n                                            (max loc)\n                                            (Time.join\n                                               (Memory.max_ts loc cap)\n                                               (Memory.max_ts loc mem_tgt))))).\n  assert (TM0: forall loc, Time.lt (Memory.max_ts loc cap) (tm0 loc)).\n  { i. unfold tm0. eapply TimeFacts.le_lt_lt.\n    { eapply Time.join_l. } eapply TimeFacts.le_lt_lt.\n    { eapply Time.join_r. } eapply TimeFacts.lt_le_lt.\n    { eapply Time.incr_spec. }\n    { eapply Time.join_r. }\n  }\n  assert (TM1: forall loc, Time.lt (Memory.max_ts loc mem_tgt) (tm0 loc)).\n  { i. unfold tm0. eapply TimeFacts.le_lt_lt.\n    { eapply Time.join_r. } eapply TimeFacts.le_lt_lt.\n    { eapply Time.join_r. } eapply TimeFacts.lt_le_lt.\n    { eapply Time.incr_spec. }\n    { eapply Time.join_r. }\n  }\n  assert (TM2: TimeMap.le (fun loc => incr_time_seq (tm loc)) tm0).\n  { eapply TimeMap.join_l. }\n  assert (TM3: forall loc, Time.lt (max loc) (tm0 loc)).\n  { i. unfold tm0. eapply TimeFacts.le_lt_lt.\n    { eapply Time.join_l. } eapply TimeFacts.lt_le_lt.\n    { eapply Time.incr_spec. }\n    { eapply Time.join_r. }\n  }\n  exploit (@good_future_future_future mem_tgt mem_src cap); eauto.\n  { eapply cap_flex_future_weak; eauto. }\n  i. des.\n\n  exploit (CONSISTENT mem1 tm0 TimeMap.bot); eauto.\n  { ss. eapply cap_flex_future_weak; eauto. }\n  { eapply cap_flex_closed; eauto. }\n  { ss. eapply cap_flex_wf; eauto. }\n  ss. i. des. destruct e1. ss.\n  hexploit trace_steps_map.\n  { eapply ident_map_le; eauto. }\n  { eapply ident_map_bot; eauto. }\n  { eapply ident_map_eq; eauto. }\n  { eapply List.Forall_forall. i. eapply ident_map_mappable_evt. }\n  { eauto. }\n  { ss. }\n  { ss. }\n  { ss. }\n  { eapply cap_flex_wf; eauto. }\n  { eapply cap_flex_wf; try apply CAP; eauto. }\n  { eapply cap_flex_closed; eauto. }\n  { eapply cap_flex_closed; eauto. }\n  { eapply Memory.closed_timemap_bot.\n    eapply cap_flex_closed; eauto. }\n  { eapply Memory.closed_timemap_bot.\n    eapply cap_flex_closed; eauto. }\n  { eapply local_map_incr; eauto. eapply ident_map_lt; eauto. }\n  { eauto. }\n  { eapply mapping_map_lt_collapsable_unwritable; eauto. eapply ident_map_lt. }\n  { eapply ident_map_timemap. }\n  { refl. }\n  i. des.\n  eexists ftr0, _, (fun loc ts0 ts2 => exists ts1, <<TS0: f_good loc ts1 ts0>> /\\ <<TS1: f0 loc ts1 ts2>>).\n  esplits; eauto; ss.\n  { eapply List.Forall_forall. i. eapply list_Forall2_in in H; eauto. des.\n    eapply List.Forall_forall in IN; eauto. ss. des. destruct a, x. ss.\n    inv EVENT; splits; ss.\n    { inv KIND; ss. inv MSG0; ss. inv MSG; ss. inv MAP1; ss. }\n    { inv FROM. inv TO. auto. }\n    { inv FROM. inv TO. auto. }\n    { inv FROM. inv TO. auto. }\n  }\n  { clear - CANCELNORMAL TRACE0. unfold cancel_normal_trace in *. des. subst.\n    eapply List.Forall2_app_inv_l in TRACE0. des. subst. esplits; eauto.\n    { eapply List.Forall_forall. i. eapply list_Forall2_in in H; eauto. des.\n      eapply List.Forall_forall in IN; eauto. destruct a, x. ss. inv EVENT; ss.\n      inv KIND; ss; des_ifs. inv MSG. }\n    { eapply List.Forall_forall. i. eapply list_Forall2_in in H; eauto. des.\n      eapply List.Forall_forall in IN; eauto. destruct a, x. ss. inv EVENT; ss.\n      inv KIND; ss; des_ifs. inv MSG. }\n  }\n  { ii. des. erewrite <- (MAPLTGOOD loc ts0 ts1 t0 t1); eauto. }\n  { ii. des.\n    destruct (Time.le_lt_dec fts (max_tgt loc)).\n    { dup l. eapply MAPIDENT in l; cycle 1; eauto. subst.\n      destruct (Time.le_lt_dec ts (max_tgt loc)).\n      { dup l. eapply IDENTGOOD in l; eauto. }\n      { dup l. eapply BOUNDGOOD in l; eauto. des. timetac. }\n    }\n    { dup l. eapply BOUND in l; cycle 1; eauto. des.\n      exfalso. eapply Time.lt_strorder. eapply TimeFacts.le_lt_lt.\n      { eapply l1. } eapply TimeFacts.le_lt_lt.\n      { eapply TS. }\n      auto.\n    }\n  }\n  { ii. des.\n    destruct (Time.le_lt_dec fts (max_tgt loc)).\n    { dup l. eapply MAPIDENT in l; cycle 1; eauto. subst.\n      exfalso. eapply Time.lt_strorder. eapply TimeFacts.le_lt_lt.\n      { eapply l0. } eapply TimeFacts.le_lt_lt.\n      { eapply MAXMAP. }\n      auto.\n    }\n    { dup l. eapply BOUND in l; cycle 1; eauto. des. splits; eauto.\n      destruct (Time.le_lt_dec ts (max_tgt loc)).\n      { dup l2. eapply IDENTGOOD in l2; eauto. subst. timetac. }\n      { dup l2. eapply BOUNDGOOD in l2; eauto. des.\n        eapply TimeFacts.le_lt_lt.\n        { eapply concrete_promise_max_ts_max_ts; eauto. eapply LOCALSRC. } eapply TimeFacts.le_lt_lt.\n        { eapply Time.join_r. } eapply TimeFacts.lt_le_lt.\n        { eapply Time.incr_spec. }\n        eauto.\n      }\n    }\n  }\n  { dup TRACEGOOD. dup TRACE. dup TRACE0.\n    eapply list_Forall2_compose.\n    { eapply list_Forall2_rev. eapply TRACEGOOD. }\n    { eapply list_Forall2_compose.\n      { eapply TRACE. }\n      { eapply TRACE0. }\n      simpl. instantiate (1:=fun the fthe => tevent_map_weak f0 (snd fthe) (snd the)).\n      i. ss. des. eapply tevent_map_tevent_map_weak in EVENT.\n      eapply tevent_map_weak_compose; eauto.\n      i. inv MAP1. auto.\n    }\n    i. ss. eapply tevent_map_weak_rev in SAT0.\n    { instantiate (1:=fun loc ts fts => f_good loc fts ts) in SAT0.\n      eapply tevent_map_weak_compose; eauto.\n      i. ss. eauto. }\n    { i. ss. }\n  }\n  { clear GOODEND0. unguard. des.\n    { left. esplits; eauto. eapply failure_step_map; eauto.\n      { eapply ident_map_le. }\n      { eapply ident_map_eq. }\n    }\n    { inv LOCAL0. right. rewrite PROMISES in *.\n      eapply bot_promises_map in PROMISES0; eauto. }\n  }\nQed.\n\n\n\n\n\nInductive relaxed_writing_event\n          (loc: Loc.t) (to: Time.t) (val: Const.t)\n  : forall (e: ThreadEvent.t), Prop :=\n| relaxed_event_write\n    from released ord\n    (ORD: Ordering.le ord Ordering.relaxed)\n  :\n    relaxed_writing_event\n      loc to val\n      (ThreadEvent.write loc from to val released ord)\n| relaxed_event_update\n    from releasedw valr releasedr ordr ordw\n    (ORD: Ordering.le ordw Ordering.relaxed)\n  :\n    relaxed_writing_event\n      loc to val\n      (ThreadEvent.update loc from to valr val releasedr releasedw ordr ordw)\n.\nHint Constructors relaxed_writing_event.\n\nLemma pf_consistent_super_strong_same_sc lang (e0: Thread.t lang) tr times sc\n      (CONSISTENT: pf_consistent_super_strong e0 tr times)\n  :\n    pf_consistent_super_strong (Thread.mk _ (Thread.state e0) (Thread.local e0) sc (Thread.memory e0)) tr times.\nProof.\n  ii. exploit CONSISTENT; eauto.\nQed.\n\n\nFixpoint map_somes A B (f: A -> option B) (l: list A): list B :=\n  match l with\n  | [] => []\n  | hd :: tl =>\n    match (f hd) with\n    | Some b => b :: map_somes f tl\n    | None => map_somes f tl\n    end\n  end.\n\nLemma map_somes_in A B (f: A -> option B) l a b\n      (IN: List.In a l)\n      (APP: f a = Some b)\n  :\n    List.In b (map_somes f l).\nProof.\n  ginduction l; eauto. i. ss. des.\n  { subst. erewrite APP. ss. auto. }\n  { eapply IHl in IN; eauto. destruct (f a); ss; auto. }\nQed.\n\nLemma map_somes_in_rev A B (f: A -> option B) l b\n      (IN: List.In b (map_somes f l))\n  :\n    exists a,\n      (<<IN: List.In a l>>) /\\\n      (<<APP: f a = Some b>>).\nProof.\n  ginduction l; eauto; ss. i. destruct (f a) eqn:EQ.\n  { ss. des; subst.\n    { esplits; eauto. }\n    { eapply IHl in IN. des. esplits; eauto. }\n  }\n  { eapply IHl in IN. des. esplits; eauto. }\nQed.\n\nLemma map_somes_split A B (f: A -> option B) l0 l1\n  :\n    map_somes f (l0 ++ l1) =\n    map_somes f l0 ++ map_somes f l1.\nProof.\n  ginduction l0; ss; eauto. i. destruct (f a); ss.\n  f_equal. eapply IHl0; eauto.\nQed.\n\nLemma map_somes_split_inv A B (f: A -> option B) l fl0 fl1\n      (MAP: map_somes f l = fl0 ++ fl1)\n  :\n    exists l0 l1,\n      (<<EQ: l = l0 ++ l1>>) /\\\n      (<<MAP0: map_somes f l0 = fl0>>) /\\\n      (<<MAP1: map_somes f l1 = fl1>>).\nProof.\n  ginduction l; eauto.\n  { i. ss. destruct fl0; ss. destruct fl1; ss. exists [], []. splits; auto. }\n  { i. ss. destruct (f a) eqn:EQ.\n    { destruct fl0; ss.\n      { destruct fl1; ss. inv MAP.\n        exists [], (a::l). splits; auto.\n        ss. rewrite EQ. auto.\n      }\n      { inv MAP. eapply IHl in H1. des. subst.\n        exists (a::l0), l1. splits; auto.\n        ss. rewrite EQ. auto.\n      }\n    }\n    { eapply IHl in MAP. des. subst.\n      exists (a::l0), l1. splits; ss. rewrite EQ. auto. }\n  }\nQed.\n\nLemma map_somes_one A B (f: A -> option B) l b\n      (MAP: map_somes f l = [b])\n  :\n    exists l0 a l1,\n      (<<EQ: l = l0 ++ a :: l1>>) /\\\n      (<<MAP0: map_somes f l0 = []>>) /\\\n      (<<MAP1: f a = Some b>>) /\\\n      (<<MAP2: map_somes f l1 = []>>).\nProof.\n  ginduction l; eauto.\n  { i. ss. }\n  { i. ss. destruct (f a) eqn:EQ.\n    { inv MAP. exists [], a, l. splits; auto. }\n    { eapply IHl in MAP. des. subst.\n      exists (a::l0), a0, l1. splits; ss.\n      rewrite EQ. auto.\n    }\n  }\nQed.\n\nLemma map_somes_split_inv_one A B (f: A -> option B) l fl0 fl1 b\n      (MAP: map_somes f l = fl0 ++ b :: fl1)\n  :\n    exists l0 a l1,\n      (<<EQ: l = (l0 ++ [a]) ++ l1>>) /\\\n      (<<MAP0: map_somes f l0 = fl0>>) /\\\n      (<<MAP1: f a = Some b>>) /\\\n      (<<MAP2: map_somes f l1 = fl1>>).\nProof.\n  eapply map_somes_split_inv in MAP. des. subst.\n  replace (b::fl1) with ([b]++fl1) in MAP2; auto.\n  eapply map_somes_split_inv in MAP2. des. subst.\n  eapply map_somes_one in MAP1. des. subst.\n  exists (l0 ++ l1), a, (l4 ++ l3). splits; auto.\n  { repeat erewrite <- List.app_assoc. auto. }\n  { erewrite map_somes_split. erewrite MAP1.\n    erewrite List.app_nil_end. auto. }\n  { erewrite map_somes_split. erewrite MAP3. ss. }\nQed.\n\nDefinition writing_loc_prom (prom: Memory.t)\n           (te: ThreadEvent.t): option (Loc.t * Time.t) :=\n  match te with\n  | ThreadEvent.write loc _ to _ _ ord =>\n    if Ordering.le ord Ordering.relaxed then\n      match Memory.get loc to prom with\n      | Some (_, Message.concrete _ _) => Some (loc, to)\n      | _ => None\n      end\n    else None\n  | ThreadEvent.update loc _ to _ _ _ _ _ ord =>\n    if Ordering.le ord Ordering.relaxed then\n      match Memory.get loc to prom with\n      | Some (_, Message.concrete _ _) => Some (loc, to)\n      | _ => None\n      end\n    else None\n  | _ => None\n  end.\n\nLemma final_event_trace_post te tr0 tr1\n      (FINAL: final_event_trace te tr1)\n  :\n    final_event_trace te (tr0 ++ tr1).\nProof.\n  ginduction tr0; eauto. i. ss. econs; eauto.\nQed.\n\nLemma cancel_normal_normals_after_normal tr0 lc te tr1\n      (CANCELNORMAL: cancel_normal_trace (tr0 ++ (lc, te) :: tr1))\n      (NORMAL: ~ ThreadEvent.is_cancel te)\n  :\n    List.Forall (fun em => <<SAT: (fun e => ~ ThreadEvent.is_cancel e) (snd em)>>) tr1.\nProof.\n  unfold cancel_normal_trace in *. des.\n  eapply List.Forall_forall. ii.\n  eapply List.in_split in H. des. subst.\n  ginduction tr_cancel.\n  { i. ss. subst. eapply List.Forall_forall in NORMAL0; eauto.\n    eapply List.in_or_app. right. ss. right.\n    eapply List.in_or_app. right. ss. auto. }\n  { i. inv CANCEL. destruct tr0.\n    { ss. inv EQ. ss. }\n    ss. inv EQ. eapply IHtr_cancel; eauto.\n  }\nQed.\n\nLemma no_concrete_promise_concrete_decrease_write prom0 mem0 loc from to val released prom1 mem1 kind\n      (WRITE: Memory.write prom0 mem0 loc from to val released prom1 mem1 kind)\n      loc0 ts0 from0 val0 released0\n      (GET: Memory.get loc0 ts0 prom1 = Some (from0, Message.concrete val0 released0))\n  :\n    exists from1 released1,\n      (<<GET: Memory.get loc0 ts0 prom0 = Some (from1, Message.concrete val0 released1)>>).\nProof.\n  inv WRITE. erewrite Memory.remove_o in GET; eauto. des_ifs. guardH o.\n  inv PROMISE.\n  { erewrite Memory.add_o in GET; eauto. des_ifs.\n    { ss. unguard. des; clarify. }\n    { esplits; eauto. }\n  }\n  { erewrite Memory.split_o in GET; eauto. des_ifs.\n    { ss. unguard. des; clarify. }\n    { ss. unguard. des; clarify. eapply Memory.split_get0 in PROMISES. des.\n      eapply Memory.remove_get1 in GET2; eauto. }\n    { esplits; eauto. }\n  }\n  { erewrite Memory.lower_o in GET; eauto. des_ifs.\n    { ss. unguard. des; clarify. }\n    { esplits; eauto. }\n  }\n { erewrite Memory.remove_o in GET; eauto. des_ifs. }\nQed.\n\nLemma no_concrete_promise_concrete_decrease_steps lang (th0 th1: Thread.t lang) tr\n      (STEPS: Trace.steps tr th0 th1)\n      (NOPROMISE: List.Forall (fun em => <<SAT: (promise_free \\1/ ThreadEvent.is_reserve) (snd em)>>) tr)\n      loc ts from val released\n      (GET: Memory.get loc ts (Local.promises (Thread.local th1)) =\n            Some (from, Message.concrete val released))\n  :\n    exists from0 released0,\n      (<<GET: Memory.get loc ts (Local.promises (Thread.local th0)) =\n              Some (from0, Message.concrete val released0)>>).\nProof.\n  ginduction STEPS; eauto. i. subst. inv NOPROMISE. guardH H1. ss.\n  eapply IHSTEPS in GET; eauto. des. inv STEP.\n  { unguard. inv STEP0; ss. inv LOCAL. inv PROMISE; ss.\n    { des_ifs; des; ss. erewrite Memory.add_o in GET0; eauto. des_ifs. eauto. }\n    { des; ss; clarify. }\n    { clear H1. erewrite Memory.lower_o in GET0; eauto. des_ifs; eauto.\n      ss. des; clarify. eapply Memory.lower_get0 in PROMISES; eauto.\n      des. inv MSG_LE. esplits; eauto. }\n    { des; ss. erewrite Memory.remove_o in GET0; eauto. des_ifs; eauto. }\n  }\n  { inv STEP0. inv LOCAL; eauto.\n    { inv LOCAL0; ss; eauto. }\n    { inv LOCAL0; ss; eauto.\n      eapply no_concrete_promise_concrete_decrease_write; eauto. }\n    { inv LOCAL1; ss; eauto. inv LOCAL2; ss; eauto.\n      eapply no_concrete_promise_concrete_decrease_write; eauto. }\n    { inv LOCAL0; ss; eauto. }\n    { inv LOCAL0; ss; eauto. }\n  }\nQed.\n\nLemma write_become_unchangable prom0 mem0 loc from to val released prom1 mem1 kind\n      (WRITE: Memory.write prom0 mem0 loc from to val released prom1 mem1 kind)\n  :\n    unchangable mem1 prom1 loc to from (Message.concrete val released).\nProof.\n  inv WRITE. eapply Memory.remove_get0 in REMOVE. des.\n  eapply Memory.promise_get0 in PROMISE.\n  { des. econs; eauto. }\n  { inv PROMISE; ss. }\nQed.\n\nDefinition writing_loc\n           (te: ThreadEvent.t): option (Loc.t * Time.t) :=\n  match te with\n  | ThreadEvent.write loc _ to _ _ _ => Some (loc, to)\n  | ThreadEvent.update loc _ to _ _ _ _ _ _ => Some (loc, to)\n  | _ => None\n  end.\n\nLemma writed_unchangable lang (th0 th1: Thread.t lang) tr lc we loc ts\n      (STEPS: Trace.steps tr th0 th1)\n      (IN: List.In (lc, we) tr)\n      (WRITING: writing_loc we = Some (loc, ts))\n  :\n    exists from msg,\n      (<<UNCH: unchangable (Thread.memory th1) (Local.promises (Thread.local th1)) loc ts from msg>>).\nProof.\n  ginduction STEPS; eauto; ss. i. subst. ss. des.\n  { clarify. inv STEP; inv STEP0; inv LOCAL; ss.\n    { clarify. inv LOCAL0. eapply write_become_unchangable in WRITE.\n      eapply unchangable_trace_steps_increase in STEPS; eauto. }\n    { clarify. inv LOCAL2. eapply write_become_unchangable in WRITE.\n      eapply unchangable_trace_steps_increase in STEPS; eauto. }\n  }\n  { exploit IHSTEPS; eauto. }\nQed.\n\n\n\nDefinition pf_consistent_super_strong_promises_list lang (e0:Thread.t lang)\n           (tr : Trace.t)\n           (times: Loc.t -> (Time.t -> Prop))\n           (pl: list (Loc.t * Time.t))\n  : Prop :=\n  (<<COMPLETE: forall loc from to val released\n                      (GET: Memory.get loc to (Local.promises (Thread.local e0)) = Some (from, Message.concrete val released)),\n      List.In (loc, to) pl>>) /\\\n  (<<CONSISTENT: forall\n      pl0 loc to pl1\n      (PROMISES: pl = pl0 ++ (loc, to) :: pl1)\n      mem1 tm sc max\n      (FUTURE: Memory.future_weak (Thread.memory e0) mem1)\n      (CLOSED: Memory.closed mem1)\n      (LOCAL: Local.wf (Thread.local e0) mem1)\n      (MWF: memory_times_wf times mem1)\n      (MAX: concrete_promise_max_timemap\n              ((Thread.memory e0))\n              ((Local.promises (Thread.local e0)))\n              max),\n      (exists ftr0 ftr1 ftr_reserve ftr_cancel e1 f we val,\n          (<<STEPS: Trace.steps (ftr0 ++ ftr_reserve) (Thread.mk _ (Thread.state e0) (Thread.local e0) sc mem1) e1>>) /\\\n          (<<EVENTS: List.Forall (fun em => <<SAT: ((promise_free \\1/ ThreadEvent.is_reserve)\n                                                      /1\\ no_sc\n                                                      /1\\ no_read_msgs (fun loc ts => ~ (covered loc ts (Local.promises (Thread.local e0)) \\/ concrete_promised (Thread.memory e0) loc ts \\/ Time.lt (tm loc) ts))\n                                                      /1\\ write_not_in (fun loc ts => (<<TS: Time.le ts (tm loc)>>) /\\ (<<PROM: ~ covered loc ts (Local.promises (Thread.local e0))>>))\n                                                      /1\\ wf_time_evt times) (snd em)>> /\\ <<TAU: ThreadEvent.get_machine_event (snd em) = MachineEvent.silent>>) (ftr0 ++ ftr_reserve) >>) /\\\n\n          (<<RESERVE: List.Forall (fun em => <<SAT: (ThreadEvent.is_reserve\n                                                       /1\\ wf_time_evt times\n                                                       /1\\ write_not_in (fun loc ts => (<<TS: Time.le ts (tm loc)>>) /\\ (<<PROM: ~ covered loc ts (Local.promises (Thread.local e0))>>))) (snd em)>>) ftr_reserve>>) /\\\n          (<<CANCEL: List.Forall (fun em => <<SAT: (ThreadEvent.is_cancel /1\\ wf_time_evt times) (snd em)>>) ftr_cancel>>) /\\\n\n          (<<EVENTSCERT: List.Forall (fun em => <<SAT: ((promise_free \\1/ ThreadEvent.is_reserve)\n                                                          /1\\ no_sc\n                                                          /1\\ no_read_msgs (fun loc ts => ~ (covered loc ts (Local.promises (Thread.local e0)) \\/ concrete_promised (Thread.memory e0) loc ts \\/ Time.lt (tm loc) ts))\n                                                          /1\\ write_not_in (fun loc ts => (<<TS: Time.le ts (tm loc)>>) /\\ (<<PROM: ~ covered loc ts (Local.promises (Thread.local e0))>>))\n                                                          /1\\ wf_time_evt times) (snd em)>> /\\ <<TAU: ThreadEvent.get_machine_event (snd em) = MachineEvent.silent>>) (ftr_cancel ++ ftr1) >>) /\\\n\n          (<<CONSISTENT: pf_consistent_super_strong e1 (ftr_cancel ++ ftr1) times>>) /\\\n\n          (<<PROMCONSISTENT: Local.promise_consistent (Thread.local e1)>>) /\\\n\n          (<<MAPLT: mapping_map_lt f>>) /\\\n          (<<MAPIDENT: forall loc ts fts\n                              (TS: Time.le fts (max loc))\n                              (MAP: f loc ts fts),\n              ts = fts>>) /\\\n          (<<BOUND: forall loc ts fts (TS: Time.lt (max loc) fts) (MAP: f loc ts fts),\n              Time.lt (max loc) ts /\\ Time.le (tm loc) fts>>) /\\\n          (<<TRACE: List.Forall2 (fun em fem => tevent_map_weak f (snd fem) (snd em)) tr (ftr0 ++ ftr1)>>) /\\\n          (<<GOOD: good_future tm mem1 (Thread.memory e1)>>) /\\\n          (<<SC: (Thread.sc e1) = sc>>) /\\\n\n          (<<FINAL: final_event_trace we (ftr0 ++ ftr_reserve)>>) /\\\n          (<<WRITING: relaxed_writing_event loc to val we>>) /\\\n          (<<SOUND: forall loc0 from0 to0 val0 released0\n                           (GET: Memory.get loc0 to0 (Local.promises (Thread.local e1)) = Some (from0, Message.concrete val0 released0)),\n              exists from0' released0',\n                (<<GET: Memory.get loc0 to0 (Local.promises (Thread.local e0)) = Some (from0', Message.concrete val0 released0')>>)>>) /\\\n          (<<WRITTEN: forall loc0 to0\n                             (IN: List.In (loc0, to0) (pl0 ++ [(loc, to)])),\n              Memory.get loc0 to0 (Local.promises (Thread.local e1)) = None>>)) \\/\n      (exists ftr e1 f,\n          (<<STEPS: Trace.steps ftr (Thread.mk _ (Thread.state e0) (Thread.local e0) sc mem1) e1>>) /\\\n          (<<EVENTS: List.Forall (fun em => <<SAT: (promise_free\n                                                      /1\\ no_sc\n                                                      /1\\ no_read_msgs (fun loc ts => ~ (covered loc ts (Local.promises (Thread.local e0)) \\/ concrete_promised (Thread.memory e0) loc ts \\/ Time.lt (tm loc) ts))\n                                                      /1\\ write_not_in (fun loc ts => (<<TS: Time.le ts (tm loc)>>) /\\ (<<PROM: ~ covered loc ts (Local.promises (Thread.local e0))>>))\n                                                      /1\\ wf_time_evt times) (snd em)>> /\\ <<TAU: ThreadEvent.get_machine_event (snd em) = MachineEvent.silent>>) ftr >>) /\\\n\n          (<<CANCELNORMAL: cancel_normal_trace ftr>>) /\\\n\n          (<<MAPLT: mapping_map_lt f>>) /\\\n          (<<MAPIDENT: forall loc ts fts\n                              (TS: Time.le fts (max loc))\n                              (MAP: f loc ts fts),\n              ts = fts>>) /\\\n          (<<BOUND: forall loc ts fts (TS: Time.lt (max loc) fts) (MAP: f loc ts fts),\n              Time.lt (max loc) ts /\\ Time.le (tm loc) fts>>) /\\\n          (<<TRACE: List.Forall2 (fun em fem => tevent_map_weak f (snd fem) (snd em)) tr ftr>>) /\\\n          (<<GOOD: good_future tm mem1 (Thread.memory e1)>>) /\\\n          (<<SC: (Thread.sc e1) = sc>>) /\\\n          (<<PROMCONSISTENT: Local.promise_consistent (Thread.local e1)>>) /\\\n          (__guard__((exists st',\n                         (<<LOCAL: Local.failure_step (Thread.local e1)>>) /\\\n                         (<<FAILURE: Language.step lang ProgramEvent.failure (@Thread.state lang e1) st'>>)))))\n        >>)\n.\n\n\nLemma pf_consistent_super_strong_promises_list_exists lang (e0: Thread.t lang)\n      (tr : Trace.t)\n      (times: Loc.t -> (Time.t -> Prop))\n      (CONSISTENT: pf_consistent_super_strong e0 tr times)\n      (CLOSED: Memory.closed (Thread.memory e0))\n      (LOCAL: Local.wf (Thread.local e0) (Thread.memory e0))\n      (DIVERGE: forall loc n, times loc (incr_time_seq n))\n  :\n    exists pl,\n      (<<PROMISES: pf_consistent_super_strong_promises_list e0 tr times pl>>)\n.\nProof.\n  assert (exists dom,\n             (<<SOUND: forall loc to\n                              (IN: List.In (loc, to) dom),\n                 exists from val released,\n                   (<<GET: Memory.get loc to (Local.promises (Thread.local e0)) = Some (from, Message.concrete val released)>>)>>) /\\\n             (<<COMPLETE: forall loc from to val released\n                                 (GET: Memory.get loc to (Local.promises (Thread.local e0)) = Some (from, Message.concrete val released)),\n                 List.In (loc, to) dom>>)).\n  { inv LOCAL. inv FINITE.\n    hexploit (list_filter_exists\n                (fun (locto: Loc.t * Time.t) =>\n                   let (loc, to) := locto in\n                   exists from val released,\n                     Memory.get loc to (Local.promises (Thread.local e0)) = Some (from, Message.concrete val released)) x).\n    { i. des. exists l'. splits.\n      { i. eapply COMPLETE in IN. des. esplits; eauto. }\n      { i. eapply COMPLETE. esplits; eauto. }\n    }\n  }\n  des.\n  set (pl := map_somes (fun lce => writing_loc_prom (Local.promises (Thread.local e0)) (snd lce)) tr).\n  destruct (classic (exists loc ts,\n                        (<<IN: List.In (loc, ts) dom>>) /\\\n                        (<<NIN: ~ List.In (loc, ts) pl>>))) as [EXIST|ALL].\n  { exists dom. split.\n    { ii. eapply COMPLETE in GET. auto. }\n    ii. exploit CONSISTENT; eauto. i. des. right. esplits; eauto.\n    unguard. des; eauto. exfalso.\n    eapply SOUND in IN. des.\n    exploit WRITES; eauto. i. des.\n    eapply list_Forall2_in in IN; eauto. des. destruct a. ss.\n    assert (WRITE: writing_loc_prom (Local.promises (Thread.local e0)) t0 = Some (loc0, ts)).\n    { inv WRITING; inv SAT; ss.\n      { rewrite ORD. replace ts with to0 in *.\n        { erewrite GET. auto. }\n        eapply MAPIDENT; eauto.\n        eapply MAX in GET. auto. }\n      { rewrite ORD. replace ts with to0 in *.\n        { erewrite GET. auto. }\n        eapply MAPIDENT; eauto.\n        eapply MAX in GET. auto. }\n    }\n    eapply NIN. eapply map_somes_in; eauto.\n  }\n  { exists pl. split.\n    { ii. eapply COMPLETE in GET. eapply NNPP. ii.\n      eapply ALL. esplits; eauto. }\n    ii. left. exploit (@CONSISTENT mem1 tm sc max); eauto.\n    hexploit map_somes_split_inv_one; try apply PROMISES. i. des. subst.\n    dup TRACE.\n    eapply List.Forall2_app_inv_l in TRACE. des. subst.\n    dup TRACE. eapply List.Forall2_app_inv_l in TRACE. des. subst.\n    inv TRACE3. inv H3. destruct y, a. ss.\n    assert (TO: forall fto (MAP: f loc to fto), to = fto).\n    { i. destruct (Time.le_lt_dec fto (max loc)).\n      { eapply MAPIDENT; eauto. }\n      dup l. eapply BOUND in l; eauto. des.\n      exfalso. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n      { eapply l. }\n      unfold writing_loc_prom in MAP1. des_ifs.\n      { eapply MAX in Heq0. auto. }\n      { eapply MAX in Heq0. auto. }\n    }\n    assert (WRITING: exists val0,\n               (<<WRITING: relaxed_writing_event loc to val0 t0>>)).\n    { unfold writing_loc_prom in MAP1. des_ifs.\n      { inv H1; ss. replace fto with to; eauto. }\n      { inv H1; ss. replace fto with to; eauto. }\n    } des.\n    hexploit SPLIT; eauto.\n    { clear - WRITING0 CANCELNORMAL. erewrite <- List.app_assoc in CANCELNORMAL.\n      eapply cancel_normal_normals_after_normal; eauto. inv WRITING0; ss. } i. des.\n    eexists (l1'0 ++ [(t, t0)]), l2', ftr_reserve, ftr_cancel. esplits; eauto.\n    { eapply Forall_app.\n      { eapply Forall_app_inv in EVENTS. des.\n        eapply List.Forall_impl; eauto. i. ss. des. splits; auto. }\n      { eapply List.Forall_impl; eauto. i. ss. des. destruct a. ss. splits; auto.\n        { destruct t4; ss. }\n        { destruct t4; ss. }\n        { destruct t4; ss. }\n      }\n    }\n    { eapply Forall_app.\n      { eapply List.Forall_impl; eauto. i. ss. des. destruct a. ss. splits; auto.\n        { destruct t4; ss. destruct kind; ss; des_ifs. auto. }\n        { destruct t4; ss. }\n        { destruct t4; ss. }\n        { destruct t4; ss. des_ifs. }\n        { destruct t4; ss. }\n      }\n      { eapply Forall_app_inv in EVENTS. des.\n        eapply List.Forall_impl; eauto. i. ss. des. splits; auto. }\n    }\n    { destruct e2. eapply no_sc_any_sc_traced in STEPS0; ss.\n      { des. exploit Trace.steps_future; try apply STEPS1; eauto; ss.\n        { instantiate (1:=TimeMap.bot). ss.\n          eapply Memory.closed_timemap_bot; eauto. eapply CLOSED0. }\n        i. des. hexploit pf_consistent_super_strong_same_sc.\n        { eapply pf_consistent_super_strong_not_easy; try apply CONSISTENT0; eauto.\n          { ss. eapply memory_times_wf_traced in STEPS1; eauto. eapply Forall_app.\n            { eapply Forall_app_inv in EVENTS. des. eapply List.Forall_impl; eauto.\n              i. ss. des; auto. }\n            { eapply List.Forall_impl; eauto. i. ss. des; auto. }\n          }\n        }\n        i. eauto. }\n      { eapply Forall_app.\n        { eapply Forall_app_inv in EVENTS. des. eapply List.Forall_impl; eauto.\n          i. ss. des; auto. }\n        { eapply List.Forall_impl; eauto. i. ss. des; auto.\n          destruct a. ss. destruct t4; ss. }\n      }\n    }\n    { erewrite <- List.app_assoc. eapply final_event_trace_post.\n      econs. eapply List.Forall_impl; eauto. i. ss.\n      des. destruct a. unfold ThreadEvent.is_reserve in *. des_ifs. }\n    { i. eapply no_concrete_promise_concrete_decrease_steps in STEPS0; eauto.\n      eapply Forall_app.\n      { eapply Forall_app_inv in EVENTS. des.\n        eapply List.Forall_impl; eauto. i. ss. des. splits; auto. }\n      { eapply List.Forall_impl; eauto. i. ss. des. destruct a. ss. splits; auto. }\n    }\n    { i. assert (WRITED: exists flc fwe,\n                    (<<IN: List.In (flc, fwe) (l0 ++ [(t1, t2)])>>) /\\\n                    (<<WRITING: writing_loc_prom (Local.promises (Thread.local e0)) fwe = Some (loc0, to0)>>)).\n      { apply List.in_app_or in IN. des.\n        { eapply map_somes_in_rev in IN. des. destruct a. ss. esplits; eauto.\n          eapply List.in_or_app; eauto. }\n        { inv IN; clarify. esplits; eauto.\n          eapply List.in_or_app; ss; eauto. }\n      } des.\n      assert (TO0: forall fto (MAP: f loc0 to0 fto), to0 = fto).\n      { i. destruct (Time.le_lt_dec fto (max loc0)).\n        { eapply MAPIDENT; eauto. }\n        dup l. eapply BOUND in l; eauto. des.\n        exfalso. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n        { eapply l. }\n        clear - WRITING MAX.\n        unfold writing_loc_prom in WRITING. des_ifs.\n        { eapply MAX in Heq0. auto. }\n        { eapply MAX in Heq0. auto. }\n      }\n      assert (WRITED: exists lc we,\n                 (<<IN: List.In (lc, we) (l1'0 ++ [(t, t0)])>>) /\\\n                 (<<WRITING: writing_loc we = Some (loc0, to0)>>)).\n      { eapply list_Forall2_in2 in IN0; eauto. des. destruct b. ss. esplits; eauto.\n        clear - TO0 WRITING SAT.\n        unfold writing_loc_prom in WRITING. des_ifs.\n        { inv SAT; ss. eapply TO0 in TO. subst. auto. }\n        { inv SAT; ss. eapply TO0 in TO. subst. auto. }\n      }\n      des. eapply writed_unchangable in STEPS0; cycle 1.\n      { eapply List.in_or_app. left. eauto. }\n      { eauto. }\n      { des. inv UNCH. auto. }\n    }\n  }\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/PFConsistentStrong.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.36296919173767833, "lm_q1q2_score": 0.2642326645785251}}
{"text": "From iris.proofmode Require Import tactics.\nFrom iris.program_logic Require Export atomic.\nFrom iris.heap_lang Require Import proofmode notation lang.\n\nDefinition getAndSet : val :=\n  rec: \"getAndSet\" \"l\" \"v\" :=\n    let: \"o\" := ! \"l\" in\n    if: CAS \"l\" \"o\" \"v\"\n    then \"o\"\n    else \"getAndSet\" \"l\" \"v\".\n\nSection getAndSetProof.\n\nContext `{heapG}.\n\nTheorem getAndSet_spec (ℓ: loc) (v: val):\n  ⊢ <<< ∀ k, ▷ ℓ ↦ k ∧ ⌜val_is_unboxed k⌝>>>\n    getAndSet #ℓ v @ ⊤\n  <<< ℓ ↦ v, RET k >>>.\nProof.\n  iIntros (Φ) \"AU\". iLöb as \"IH\". wp_lam. wp_pures.\n  wp_bind (!_)%E. iMod \"AU\" as (k) \"[[Hℓ %] [HClose _]]\".\n  wp_load. iMod (\"HClose\" with \"[Hℓ]\") as \"AU\"; first by iSplit. iModIntro.\n  wp_let. wp_bind (CmpXchg _ _ _)%E. iMod \"AU\" as (k') \"[[Hℓ %] HClose]\".\n  destruct (decide (k = k')) as [[= ->]|Hx];\n    [wp_cmpxchg_suc|wp_cmpxchg_fail];\n    [iDestruct \"HClose\" as \"[_ HClose]\" | iDestruct \"HClose\" as \"[HClose _]\"].\n  all: iMod (\"HClose\" with \"[Hℓ]\") as \"HΦ\"; first by auto.\n  all: iModIntro; wp_pures; auto.\n  by wp_apply \"IH\".\nQed.\n\nEnd getAndSetProof.\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/util/getAndSet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2640504811218927}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Classes.EquivDec.\nRequire Import MirrorShard.Heaps.\nRequire MirrorShard.SepExpr MirrorShard.Expr.\nRequire Import MirrorShard.Provers.\n\n\nSet Implicit Arguments.\n\nModule SepExprTests (B : Heap).\n  Module ST := SepTheoryX.SepTheoryX (B).\n  Module Sep := SepExpr.SepExpr B ST.\n\n  (** Just a test separation logic predicate **)\n  Section Tests.\n    Variable f : forall a b, nat -> ST.hprop a b nil.\n    Variable h : forall a b, nat -> ST.hprop a b nil.\n    Variable i : forall a b, nat -> ST.hprop a b nil.\n    Variable g : bool -> nat -> nat -> nat.\n\n    Ltac isConst e :=\n      match e with\n        | true => true\n        | false => true\n        | O => true\n        | S ?e => isConst e\n        | _ => false\n      end.\n\n    Definition nat_type : Expr.type :=\n      {| Expr.Impl := nat\n       ; Expr.Eq := fun x y => match equiv_dec x y with\n                                 | left pf => Some pf\n                                 | _ => None\n                               end\n       |}.\n\n\n    Fixpoint star_all a b (f : nat -> ST.hprop a b nil) (n : nat) : ST.hprop a b nil :=\n      match n with\n        | 0 => f 0\n        | S n => ST.star (f (S n)) (star_all f n)\n      end.\n\n    Fixpoint star_all_back a b (f : nat -> ST.hprop a b nil) (n m : nat) : ST.hprop a b nil :=\n      match n with\n        | 0 => f m\n        | S n => ST.star (f (m - S n)) (star_all_back f n m)\n      end.\n\n    Opaque ST.himp ST.star ST.emp ST.inj ST.ex.\n\n    Import SepExpr Sep Expr ExprUnify DepList.\n\n    Ltac simplifier := cbv beta iota zeta delta [CancelSep sepCancel hash hash' liftSHeap sheapSubstU liftExpr\n      SepExpr.FM.add SepExpr.FM.fold SepExpr.FM.map SepExpr.FM.find SepExpr.FM.remove\n        SepExpr.FM.empty SepExpr.FM.insert_at_right\n        other pures impures star_SHeap SHeap_empty\n        unify_remove unify_remove_all exprUnifyArgs exprUnify empty_Subst Subst_lookup env_of_Subst\n        Expr.Impl Expr.Eq\n        List.map List.length List.app fold_left_2_opt List.fold_right List.nth_error\n        starred sheapD exprD\n        exprSubstU\n        Compare_dec.lt_eq_lt_dec Compare_dec.lt_dec Peano_dec.eq_nat_dec\n        nat_rec nat_rect forallEach env exists_subst multimap_join equiv_dec seq_dec\n        Domain Range\n        EqDec_tvar tvar_rec tvar_rect\n        lookupAs sumbool_rec sumbool_rect\n        fst snd\n        eq_rec_r eq_rec eq_rect Logic.eq_sym f_equal get_Eq value\n        nat_eq_eqdec\n        eq_summary eq_summarize eq_prove\n        sexprD Compare_dec.le_dec Compare_dec.le_gt_dec Compare_dec.le_lt_dec\n        Subst_replace plus minus substV\n\n        transitivityEqProverRec groupsOf transitivityEqProver addEquality expr_seq_dec\n        applyD\n        in_seq_dec eqD_seq groupWith Expr.typeof unifyArgs inSameGroup fold_right\n        bool_eqdec Bool.bool_dec bool_rec bool_rect\n\n        nat_type\n    ]; fold plus; fold minus.\n\n    Ltac sep := simpl; intros;\n      Sep.sep isConst transitivityEqProverRec simplifier (nat_type :: nil); try reflexivity.\n\n    Goal forall a b c x y, @ST.himp a b c (f _ _ (g y (x + x) 1)) (f _ _ 1).\n      sep.\n    Abort.\n\n    Theorem t1 : forall a b c, @ST.himp a b c (f _ _ 0) (f _ _ 0).\n      sep.\n    Qed.\n\n    Theorem t2 : forall a b c,\n      @ST.himp a b c (ST.star (star_all_back (@h a b) 15 15) (star_all_back (@f a b) 15 15))\n                     (ST.star (star_all (@f a b) 15) (star_all (@h a b) 15)).\n      sep.\n    Qed.\n\n    Theorem t3 : forall a b c, @ST.himp a b c\n      (ST.star (f _ _ 2) (f _ _ 1))\n      (f _ _ 1).\n      sep.\n    Abort.\n\n    Theorem t4 : forall a b c, @ST.himp a b c\n      (ST.ex (fun y : nat => ST.ex (fun x : bool => ST.star (f _ _ (g x 1 2)) (f _ _ 1) )))\n      (f _ _ 1).\n      sep.\n    Abort.\n\n    Theorem t5 : forall a b c, @ST.himp a b c\n      (ST.ex (fun y : nat => f _ _ y))\n      (f _ _ 1).\n      sep.\n    Abort.\n\n    Theorem t6 : forall a b c, @ST.himp a b c\n      (f _ _ 1)\n      (ST.ex (fun y : nat => f _ _ y)).\n      sep.\n    Qed.\n\n    Theorem t7 : forall a b c, @ST.himp a b c\n      (ST.star (f _ _ (g true 0 1)) (f _ _ (g true 1 2)))\n      (ST.ex (fun y : nat => ST.star (f _ _ (g true 0 y)) (ST.ex (fun z : nat => f _ _ (g true 1 z))))).\n      sep.\n    Qed.\n\n    Theorem t8 : forall a b c, @ST.himp a b c\n      (ST.star (f _ _ (g true 0 1)) (f _ _ (g true 1 2)))\n      (ST.ex (fun y : nat => ST.star (f _ _ (g true 1 y)) (ST.ex (fun z : nat => f _ _ (g true 0 z))))).\n      sep.\n    Qed.\n\n\n    (** ** Test use of transitivity prover in cancellation *)\n\n    Theorem t9 : forall a b c x y, x = y\n      -> @ST.himp a b c  (f _ _ x) (f _ _ y).\n      sep.\n    Qed.\n\n    Theorem t10 : forall a b c x y, x = y\n      -> @ST.himp a b c  (f _ _ y) (f _ _ x).\n      sep.\n    Qed.\n\n    Theorem t11 : forall a b c x y z, x = y\n      -> x = z\n      -> @ST.himp a b c  (f _ _ x) (f _ _ y).\n      sep.\n    Qed.\n\n    Theorem t12 : forall a b c x y u v, x = y\n      -> u = v\n      -> @ST.himp a b c  (ST.star (f _ _ x) (f _ _ v)) (ST.star (f _ _ y) (f _ _ u)).\n      sep.\n    Qed.\n\n    Theorem t13 : forall a b c x y z u v, x = y\n      -> z = y\n      -> u = v\n      -> @ST.himp a b c  (ST.star (f _ _ x) (f _ _ v)) (ST.star (f _ _ z) (f _ _ u)).\n      sep.\n    Qed.\n\n  End Tests.\n\nEnd SepExprTests.\n", "meta": {"author": "gmalecha", "repo": "mirror-shard", "sha": "24f34dee2f78de731f4ef398733ff2c1f1551375", "save_path": "github-repos/coq/gmalecha-mirror-shard", "path": "github-repos/coq/gmalecha-mirror-shard/mirror-shard-24f34dee2f78de731f4ef398733ff2c1f1551375/src/SepExprTests.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.26405047471102117}}
{"text": "Set Implicit Arguments.\n\nRequire Import ADT.\n\nModule Make (Import E : ADT).\n\n  Require Import Semantics.\n  Module Import SemanticsMake := Make E.\n\n  Section TopSection.\n\n    Require Import GoodModule.\n    Require Import GLabelMap.\n    Import GLabelMap.\n    \n    Open Scope bool_scope.\n    Notation \"! b\" := (negb b) (at level 35).\n\n    Require Import 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 ListFacts3.\n    Require Import GoodModuleFacts.\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        NoDup_bool string_bool module_names &&\n        forallb (fun s => ! sumbool_to_bool (in_dec string_dec s module_names)) imported_module_names &&\n        forallb GoodModuleName_bool imported_module_names.\n\n    Require Import GeneralTactics.\n    Require Import ListFacts1.\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      Require Import GeneralTactics.\n      Require Import Bool.\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 NoDup_bool_string_eq_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      eapply GoodModuleName_bool_sound; eauto.\n      rewrite <- map_map.\n      eapply in_map.\n      Require Import GLabelMapFacts.\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.", "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/LinkFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.26405047471102117}}
{"text": "(* Distributed under the terms of the MIT license. *)\nRequire Import ssreflect ssrbool.\nRequire PeanoNat.\nFrom MetaCoq.Utils Require Import utils.\nFrom MetaCoq.Common Require Import config Reflect.\nFrom MetaCoq.Template Require Import Ast AstUtils Induction UnivSubst WfAst Typing.\nFrom Equations Require Import Equations.\n\nImplicit Types (cf : checker_flags).\n\nExisting Class wf.\n\n(** * Well-formedness of terms and types in typing derivations\n\n  The internal representation of terms is not canonical, so we show\n  that only well-formed terms and types can appear in typing derivations\n  and the global context.\n*)\n\nLemma All_local_env_wf_decl Σ :\n  forall (Γ : context),\n    All (wf_decl Σ) Γ -> All_local_env (wf_decl_pred Σ) Γ.\nProof.\n  intros Γ X.\n  induction Γ in X |- *.\n  - constructor; eauto.\n  - destruct a as [na [body|] ty].\n    + econstructor.\n      * apply IHΓ. inv X; eauto.\n      * red. inv X. split.\n        -- apply X0.\n        -- constructor.\n      * red. inv X. eauto.\n    + econstructor.\n      * apply IHΓ. inv X; eauto.\n      * red. inv X. split.\n        -- apply X0.\n        -- constructor.\nQed.\n\nLemma on_global_decl_impl `{checker_flags} Σ P Q kn d :\n  (forall Σ Γ t T, on_global_env cumul_gen P Σ.1 -> P Σ Γ t T -> Q Σ Γ t T) ->\n  on_global_env cumul_gen P Σ.1 ->\n  on_global_decl cumul_gen P Σ kn d -> on_global_decl cumul_gen Q Σ kn d.\nProof.\n  unfold on_global_env.\n  intros X X0 o.\n  destruct d; simpl.\n  - destruct c; simpl. destruct cst_body0; simpl in *.\n    red in o |- *. simpl in *. now eapply X.\n    red in o |- *. simpl in *. now eapply X.\n  - simpl in *.\n    destruct o as [onI onP onNP].\n    constructor; auto.\n    -- eapply Alli_impl. exact onI. eauto. intros.\n\n       refine {| ind_arity_eq := X1.(ind_arity_eq);\n                 ind_cunivs := X1.(ind_cunivs) |}.\n       --- apply onArity in X1. unfold on_type in *; simpl in *.\n           now eapply X.\n       --- pose proof X1.(onConstructors) as X11. red in X11.\n           eapply All2_impl; eauto.\n           simpl. intros. destruct X2 as [? ? ? ?]; unshelve econstructor; eauto.\n           * apply X; eauto.\n           * clear -X0 X on_cargs. revert on_cargs.\n              generalize (cstr_args x0), y.\n              induction c; destruct y0; simpl; auto;\n              destruct a as [na [b|] ty]; simpl in *; auto;\n           split; intuition eauto.\n           * clear -X0 X on_cindices.\n             revert on_cindices.\n             generalize (List.rev (lift_context #|cstr_args x0| 0 (ind_indices x))).\n             generalize (cstr_indices x0).\n             induction 1; simpl; constructor; auto.\n       --- simpl; intros. apply (onProjections X1).\n       --- destruct X1. simpl. unfold check_ind_sorts in *.\n           destruct Universe.is_prop; auto.\n           destruct Universe.is_sprop; auto.\n           split. apply ind_sorts. destruct indices_matter; auto.\n           eapply type_local_ctx_impl. eapply ind_sorts. auto.\n       --- apply (onIndices X1).\n    -- red in onP. red.\n       eapply All_local_env_impl. eauto.\n       intros. now apply X.\nQed.\n\nLemma on_global_env_impl `{checker_flags} Σ P Q :\n  (forall Σ Γ t T, on_global_env cumul_gen P Σ.1 -> P Σ Γ t T -> Q Σ Γ t T) ->\n  on_global_env cumul_gen P Σ -> on_global_env cumul_gen Q Σ.\nProof.\n  destruct Σ as [univs Σ]; cbn.\n  intros X [cu X0]; split => /= //. cbn in *.\n  induction X0; try destruct o; constructor; auto; constructor; eauto.\n  clear IHX0.\n  eapply on_global_decl_impl; tea. split => //.\nQed.\n\nLemma All_local_env_wf_decl_inv Σ (a : context_decl) (Γ : list context_decl)\n         (X : All_local_env (wf_decl_pred Σ) (a :: Γ)) :\n    on_local_decl (wf_decl_pred Σ) Γ a * All_local_env (wf_decl_pred Σ) Γ.\nProof.\n  inv X; intuition; red; simpl; eauto.\nQed.\n\nLemma unfold_fix_wf:\n  forall Σ (mfix : mfixpoint term) (idx : nat) (narg : nat) (fn : term),\n    unfold_fix mfix idx = Some (narg, fn) ->\n    WfAst.wf Σ (tFix mfix idx) ->\n    WfAst.wf Σ fn.\nProof.\n  intros Σ mfix idx narg fn Hf Hwf.\n  unfold unfold_fix in Hf. inv Hwf.\n  destruct nth_error eqn:eqnth; try congruence.\n  pose proof (nth_error_all eqnth X) as [ _ wfd].\n  injection Hf. intros <- <-.\n  apply wf_subst; auto. clear wfd Hf eqnth.\n  assert(forall n, WfAst.wf Σ (tFix mfix n)). constructor; auto.\n  unfold fix_subst. generalize #|mfix|; intros. induction n; auto.\nQed.\n\nLemma unfold_cofix_wf Σ:\n  forall (mfix : mfixpoint term) (idx : nat) (narg : nat) (fn : term),\n    unfold_cofix mfix idx = Some (narg, fn) ->\n    WfAst.wf Σ (tCoFix mfix idx) -> WfAst.wf Σ fn.\nProof.\n  intros mfix idx narg fn Hf Hwf.\n  unfold unfold_cofix in Hf. inv Hwf.\n  destruct nth_error eqn:eqnth; try congruence.\n  pose proof (nth_error_all eqnth X) as [_ wfd].\n  injection Hf. intros <- <-.\n  apply wf_subst; auto. clear wfd Hf eqnth.\n  assert(forall n, WfAst.wf Σ (tCoFix mfix n)). constructor; auto.\n  unfold cofix_subst. generalize #|mfix|; intros. induction n; auto.\nQed.\n\nLemma red1_isLambda Σ Γ t u :\n  red1 Σ Γ t u -> isLambda t -> isLambda u.\nProof.\n  induction 1 using red1_ind_all; simpl; try discriminate; auto.\nQed.\n\nLemma OnOne2_All_All {A} {P Q} {l l' : list A} :\n  OnOne2 P l l' ->\n  (forall x y, P x y -> Q x -> Q y) ->\n  All Q l -> All Q l'.\nProof. intros Hl H. induction Hl; intros H'; inv H'; constructor; eauto. Qed.\n\nLemma All_mapi {A B} (P : B -> Type) (l : list A) (f : nat -> A -> B) :\n  Alli (fun i x => P (f i x)) 0 l -> All P (mapi f l).\nProof.\n  unfold mapi. generalize 0.\n  induction 1; constructor; auto.\nQed.\n\nLemma Alli_id {A} (P : nat -> A -> Type) n (l : list A) :\n  (forall n x, P n x) -> Alli P n l.\nProof.\n  intros H. induction l in n |- *; constructor; auto.\nQed.\n\n\nLemma All_Alli {A} {P : A -> Type} {Q : nat -> A -> Type} {l n} :\n  All P l ->\n  (forall n x, P x -> Q n x) ->\n  Alli Q n l.\nProof. intro H. revert n. induction H; constructor; eauto. Qed.\n\n\nLtac wf := intuition try (eauto with wf || congruence || solve [constructor]).\n#[global]\nHint Unfold wf_decl vass vdef : wf.\n#[global]\nHint Extern 10 => progress simpl : wf.\n#[global]\nHint Unfold snoc : wf.\n#[global]\nHint Extern 3 => apply wf_lift || apply wf_subst || apply wf_subst_instance : wf.\n#[global]\nHint Extern 10 => constructor : wf.\n#[global]\nHint Resolve All_skipn : wf.\n\nLemma on_global_decls_extends_not_fresh {cf} {univs retro} k (Σ : global_declarations) k' (Σ' : global_declarations) P :\n  on_global_decls cumul_gen P univs retro ((k :: Σ) ++ [k'] ++ Σ') -> k.1 = k'.1 -> False.\nProof.\n  intros H eq.\n  depelim H. destruct o as [f ? ? ?].\n  eapply Forall_app in f as [_ f].\n  depelim f. cbn in *. subst. contradiction.\nQed.\n\nLemma lookup_env_extends {cf : checker_flags} (Σ : global_env) k d (Σ' : global_env) P :\n  on_global_env cumul_gen P Σ' ->\n  lookup_env Σ k = Some d ->\n  extends Σ Σ' -> lookup_env Σ' k = Some d.\nProof.\n  intro H; eapply lookup_env_extends_NoDup, NoDup_on_global_decls, H.\nQed.\n\nLemma In_lookup_globals k decls : In k (map fst decls) -> #| lookup_globals decls k | >= 1.\nProof.\n  induction decls; cbn => //.\n  case_eq (k == a.1).\n  - intros e _. cbn. lia.\n  - intros e [].\n   + rewrite H in e. rewrite eqb_refl in e. inversion e.\n   + now apply IHdecls.\nQed.\n\nLemma NoDup_extends (Σ : global_env) (Σ' : global_env) :\n        NoDup (map fst (declarations Σ')) -> extends Σ Σ' -> NoDup (map fst (declarations Σ)).\nProof.\n  intros Hl [_ Hex _].\n  destruct Σ, Σ'; cbn in *. clear - Hl Hex.\n  induction declarations0; cbn in *; econstructor.\n  - intros H. specialize (Hex a.1). destruct Hex as [decls Hdecls].\n    pose proof (NoDup_length_lookup_globals _ Hl a.1).\n    rewrite eqb_refl in Hdecls. apply In_lookup_globals in H.\n    rewrite Hdecls in H0. rewrite app_length in H0. cbn in H0.\n    destruct lookup_global; lia.\n  - eapply IHdeclarations0. intros. specialize (Hex c).\n    destruct Hex as [decls Hdecls]. case_eq (c == a.1).\n    + intros e. exists (decls ++ [a.2]). rewrite Hdecls e.\n      now rewrite <- app_assoc.\n    + intros e. exists decls. now rewrite Hdecls e.\nQed.\n\nLemma declared_env_extends {cf : checker_flags} (Σ : global_env) k d (Σ' : global_env) P :\n  on_global_env cumul_gen P Σ' ->\n  In (k, InductiveDecl d) (declarations Σ) -> extends Σ Σ' -> In (k,InductiveDecl d) (declarations Σ').\nProof.\n  intros; apply lookup_global_Some_iff_In_NoDup.\n  - destruct X; eapply NoDup_on_global_decls; eauto.\n  - eapply lookup_env_extends; eauto.\n    destruct X; eapply lookup_global_Some_iff_In_NoDup; eauto.\n    eapply NoDup_extends; eauto.\n    now eapply NoDup_on_global_decls.\nQed.\n\nLemma wf_extends {cf} {Σ : global_env} T {Σ' : global_env} P :\n  on_global_env cumul_gen P Σ' -> WfAst.wf Σ T -> extends Σ Σ' -> WfAst.wf Σ' T.\nProof.\n  intros wfΣ'.\n  induction 1 using term_wf_forall_list_ind; try solve [econstructor; eauto; solve_all].\n  - intros. destruct H. destruct X0.\n    unfold declared_minductive in H.\n    eapply declared_env_extends in H; tea.\n    econstructor; repeat split; eauto; solve_all.\nQed.\n\nLemma wf_decl_extends {cf} {Σ : global_env} T {Σ' : global_env} P :\n  on_global_env cumul_gen P Σ' -> wf_decl Σ T -> extends Σ Σ' -> wf_decl Σ' T.\nProof.\n  intros wf [] ext. red. destruct decl_body; split; eauto using wf_extends.\nQed.\n\nArguments lookup_on_global_env {H} {Pcmp P Σ c decl}.\n\nLemma declared_inductive_wf {cf:checker_flags} {Σ : global_env} ind\n         (mdecl : mutual_inductive_body) (idecl : one_inductive_body) :\n  on_global_env cumul_gen wf_decl_pred Σ ->\n  declared_inductive Σ ind mdecl idecl -> WfAst.wf Σ (ind_type idecl).\nProof.\n  intros.\n  destruct H as [Hmdecl Hidecl]. red in Hmdecl.\n  eapply lookup_global_Some_iff_In_NoDup in  Hmdecl; eauto.\n  2: destruct X; now eapply NoDup_on_global_decls.\n  destruct (lookup_on_global_env X Hmdecl) as [Σ' [wfΣ' [ext prf]]]; eauto.\n  apply onInductives in prf.\n  eapply nth_error_alli in Hidecl; eauto.\n  eapply onArity in Hidecl.\n  destruct Hidecl.\n  eapply wf_extends in w; tea; typeclasses eauto.\nQed.\n\nLemma wf_it_mkProd_or_LetIn Σ Γ t\n  : WfAst.wf Σ (it_mkProd_or_LetIn Γ t) -> All (wf_decl Σ) Γ * WfAst.wf Σ t.\nProof.\n  revert t. induction Γ; [simpl; auto with wf|]. intros t XX.\n  destruct a, decl_body; simpl in *.\n  apply IHΓ in XX as []. depelim w; simpl in *; split; auto with wf.\n  apply IHΓ in XX as []. depelim w. simpl in *.\n  split; auto. constructor; auto with wf.\nQed.\n\nLemma declared_inductive_wf_indices {cf:checker_flags} {Σ : global_env} {ind mdecl idecl} :\n  on_global_env cumul_gen wf_decl_pred Σ ->\n  declared_inductive Σ ind mdecl idecl -> All (wf_decl Σ) (ind_indices idecl).\nProof.\n  intros.\n  destruct H as [Hmdecl Hidecl]. red in Hmdecl.\n  eapply lookup_global_Some_iff_In_NoDup in  Hmdecl; eauto.\n  2: destruct X; now eapply NoDup_on_global_decls.\n  destruct (lookup_on_global_env X Hmdecl) as [Σ' [wfΣ' [ext prf]]]; eauto.\n  apply onInductives in prf.\n  eapply nth_error_alli in Hidecl; eauto.\n  pose proof (onArity Hidecl).\n  rewrite Hidecl.(ind_arity_eq) in X0.\n  destruct X0 as [s Hs]; wf.\n  eapply wf_it_mkProd_or_LetIn in s as [? H].\n  eapply wf_it_mkProd_or_LetIn in H as [].\n  solve_all. eapply wf_decl_extends; tea; typeclasses eauto.\nQed.\n\nLemma declared_inductive_wf_ctors {cf:checker_flags} {Σ} {ind} {mdecl idecl} :\n  on_global_env cumul_gen wf_decl_pred Σ ->\n  declared_inductive Σ ind mdecl idecl ->\n  All (fun ctor => All (wf_decl Σ) ctor.(cstr_args)) (ind_ctors idecl).\nProof.\n  intros.\n  destruct H as [Hmdecl Hidecl]. red in Hmdecl.\n  eapply lookup_global_Some_iff_In_NoDup in  Hmdecl; eauto.\n  2: destruct X; now eapply NoDup_on_global_decls.\n  destruct (lookup_on_global_env X Hmdecl) as [Σ' [wfΣ' [ext prf]]]; eauto.\n  apply onInductives in prf.\n  eapply nth_error_alli in Hidecl; eauto.\n  pose proof (onConstructors Hidecl). red in X0.\n  solve_all. destruct X0.\n  clear -X ext on_cargs.\n  induction (cstr_args x) as [|[na [b|] ty] args] in on_cargs, y |- * ;\n    try destruct on_cargs;\n   constructor; unfold wf_decl in *; cbn in *; intuition eauto using wf_extends; simpl in *.\n   destruct b0. intuition eauto using wf_extends with typeclass_instances.\n   destruct a. intuition eauto using wf_extends with typeclass_instances.\n   destruct y => //. destruct on_cargs. destruct w; eauto using wf_extends with typeclass_instances.\n   destruct y => //. eapply IHargs; intuition eauto.\nQed.\n\nLemma All_local_env_wf_decls Σ ctx :\n  TemplateEnvTyping.All_local_env (wf_decl_pred Σ) ctx ->\n  All (wf_decl Σ) ctx.\nProof.\n  induction 1; constructor; auto.\n  destruct t0 as [s Hs]. split; simpl; intuition auto.\nQed.\n\nLemma on_global_inductive_wf_params {cf:checker_flags} {Σ : global_env_ext} {kn mdecl} :\n  on_global_decl cumul_gen (fun Σ : global_env_ext => wf_decl_pred Σ) Σ kn (InductiveDecl mdecl) ->\n  All (wf_decl Σ) (ind_params mdecl).\nProof.\n  intros prf.\n  apply onParams in prf. red in prf.\n  apply All_local_env_wf_decls in prf.\n  solve_all.\nQed.\n\nLemma destArity_spec ctx T :\n  match destArity ctx T with\n  | Some (ctx', s) => it_mkProd_or_LetIn ctx T = it_mkProd_or_LetIn ctx' (tSort s)\n  | None => True\n  end.\nProof.\n  induction T in ctx |- *; simpl; try easy.\n  - specialize (IHT2 (ctx,, vass na T1)). now destruct destArity.\n  - specialize (IHT3 (ctx,, vdef na T1 T2)). now destruct destArity.\nQed.\n\nLemma destArity_it_mkProd_or_LetIn ctx ctx' t :\n  destArity ctx (it_mkProd_or_LetIn ctx' t) =\n  destArity (ctx ,,, ctx') t.\nProof.\n  induction ctx' in ctx, t |- *; simpl; auto.\n  rewrite IHctx'. destruct a as [na [b|] ty]; reflexivity.\nQed.\n\nLemma it_mkProd_or_LetIn_inj ctx s ctx' s' :\n  it_mkProd_or_LetIn ctx (tSort s) = it_mkProd_or_LetIn ctx' (tSort s') ->\n  ctx = ctx' /\\ s = s'.\nProof.\n  move/(f_equal (destArity [])).\n  rewrite !destArity_it_mkProd_or_LetIn /=.\n  now rewrite !app_context_nil_l => [= -> ->].\nQed.\n\n(*\nLemma case_predicate_contextP ind mdecl idecl params uinst pctx :\n  build_case_predicate_context ind mdecl idecl params uinst = Some pctx <~>\n  case_predicate_context ind mdecl idecl params uinst pctx.\nProof.\n  unfold build_case_predicate_context.\n  unfold instantiate_params.\n  destruct instantiate_params_subst as [[ictx p]|] eqn:ipars => /= //.\n  2:{ split => //. intros H. depelim H.\n      eapply instantiate_params_substP in i.\n      rewrite ipars in i. discriminate. }\n  move: (destArity_spec [] (subst0 ictx p)).\n  destruct destArity as [[idctx inds]|] eqn:da => //.\n  simpl. intros eqs.\n  split.\n  eapply instantiate_params_substP in ipars.\n  intros [= <-]. econstructor. eauto. eauto.\n  intros H. depelim H. subst sty.\n  eapply instantiate_params_substP in i.\n  rewrite ipars in i. noconf i. rewrite eqs in e.\n  eapply it_mkProd_or_LetIn_inj in e as [<- <-].\n  reflexivity.\n  split => // [] [] s ty ictxt inds.\n  move/instantiate_params_substP.\n  rewrite ipars /= => [=] <- <- H.\n  rewrite H destArity_it_mkProd_or_LetIn in da.\n  noconf da.\nQed.\n*)\n\nLemma wf_subst_context Σ s k Γ : All (wf_decl Σ) Γ -> All (WfAst.wf Σ) s -> All (wf_decl Σ) (subst_context s k Γ).\nProof.\n  intros wfΓ. induction wfΓ in s |- *.\n  - intros. constructor.\n  - rewrite subst_context_snoc. constructor; auto.\n    destruct p. destruct x as [? [] ?]; constructor; simpl in *; wf.\nQed.\n\nLemma wf_smash_context Σ Γ Δ : All (wf_decl Σ) Γ -> All (wf_decl Σ) Δ ->\n  All (wf_decl Σ) (smash_context Δ Γ).\nProof.\n  intros wfΓ; induction wfΓ in Δ |- *; intros wfΔ; simpl; auto.\n  destruct x as [? [] ?]; simpl. apply IHwfΓ.\n  eapply wf_subst_context; auto. constructor; auto. apply p.\n  eapply IHwfΓ. apply All_app_inv; auto.\nQed.\n\nSection WfAst.\n  Context {cf:checker_flags}.\n  Context {Σ : global_env}.\n\n  Lemma wf_reln n acc Γ : All (WfAst.wf Σ) acc -> All (WfAst.wf Σ) (reln acc n Γ).\n  Proof using Type.\n    induction Γ in acc, n |- * => wfacc /= //.\n    destruct a as [? [|] ?] => //. now eapply IHΓ.\n    eapply IHΓ. constructor; auto. constructor.\n  Qed.\n\n  #[local]\n  Hint Resolve wf_reln : wf.\n\n  (* Lemma wf_instantiate_params_subst_spec params pars s ty s' ty' :\n    instantiate_params_subst_spec params pars s ty s' ty' ->\n    All (wf_decl Σ) params ->\n    WfAst.wf Σ ty ->\n    All (WfAst.wf Σ) pars ->\n    All (WfAst.wf Σ) s ->\n    All (WfAst.wf Σ) s' * WfAst.wf Σ ty'.\n  Proof.\n    intros ipars. induction ipars; intros wfparams wfty wfpars wfs => //.\n    depelim wfparams. depelim wfpars. depelim wfty.\n    apply IHipars; auto.\n    depelim wfparams. depelim wfty. destruct H; simpl in *.\n    apply IHipars; auto with wf.\n  Qed. *)\n\n  Lemma wf_map2_set_binder_name l l' :\n    All (wf_decl Σ) l' ->\n    All (wf_decl Σ) (map2 set_binder_name l l').\n  Proof using Type.\n    induction 1 in l |- *; destruct l; simpl; constructor.\n    apply p. apply IHX.\n  Qed.\n\n  Definition lift_context_snoc0 n k Γ d : lift_context n k (d :: Γ) = lift_context n k Γ ,, lift_decl n (#|Γ| + k) d.\n  Proof using Type. unfold lift_context. now rewrite fold_context_k_snoc0. Qed.\n  Hint Rewrite lift_context_snoc0 : lift.\n\n  Lemma lift_context_snoc n k Γ d : lift_context n k (Γ ,, d) = lift_context n k Γ ,, lift_decl n (#|Γ| + k) d.\n  Proof using Type.\n    unfold snoc. apply lift_context_snoc0.\n  Qed.\n  Hint Rewrite lift_context_snoc : lift.\n\n\n  Lemma wf_lift_context n k Γ : All (wf_decl Σ) Γ -> All (wf_decl Σ) (lift_context n k Γ).\n  Proof using Type.\n    intros wfΓ. induction wfΓ in n, k |- *.\n    - intros. constructor.\n    - rewrite lift_context_snoc0. constructor; auto.\n      destruct p. destruct x as [? [] ?]; constructor; simpl in *; wf.\n  Qed.\n\n  Lemma wf_subst_instance_context u Γ :\n    All (wf_decl Σ) Γ ->\n    All (wf_decl Σ) (subst_instance u Γ).\n  Proof using Type.\n    induction 1; constructor; auto.\n    destruct x as [na [b|] ty]; simpl in *.\n    destruct p. now split; apply wf_subst_instance.\n    destruct p. now split; auto; apply wf_subst_instance.\n  Qed.\n\n  Lemma wf_extended_subst Γ n :\n    All (wf_decl Σ) Γ ->\n    All (WfAst.wf Σ) (extended_subst Γ n).\n  Proof using Type.\n    induction 1 in n |- *.\n    - simpl; constructor.\n    - destruct x as [na [b|] ty]; simpl; constructor; auto.\n      2:constructor.\n      eapply wf_subst; auto.\n      eapply wf_lift. apply p.\n  Qed.\n\n  Lemma wf_case_predicate_context ind mdecl idecl p :\n    declared_inductive Σ ind mdecl idecl ->\n    All (wf_decl Σ) mdecl.(ind_params) ->\n    All (wf_decl Σ) (ind_indices idecl) ->\n    All (WfAst.wf Σ) p.(pparams) ->\n    All (wf_decl Σ) (case_predicate_context ind mdecl idecl p).\n  Proof using Type.\n    intros decl wfparams wfindty wfpars.\n    unfold case_predicate_context. destruct p.\n    apply wf_map2_set_binder_name.\n    unfold pre_case_predicate_context_gen. cbn [Ast.pparams Ast.puinst].\n    unfold inst_case_context.\n    eapply wf_subst_context => //.\n    2:now eapply All_rev.\n    apply wf_subst_instance_context.\n    rewrite /ind_predicate_context.\n    constructor.\n    simpl; split; auto. simpl. auto. simpl.\n    eapply wf_mkApps. now econstructor.\n    apply wf_reln. constructor.\n    eapply wf_subst_context.\n    now apply wf_lift_context.\n    now apply wf_extended_subst.\n  Qed.\n\n  Lemma Forall_decls_on_global_wf :\n    Forall_decls_typing\n      (fun (Σ : global_env_ext) (_ : context) (t T : term) =>\n      WfAst.wf Σ t * WfAst.wf Σ T) Σ ->\n    on_global_env cumul_gen wf_decl_pred Σ.\n  Proof using Type.\n    apply on_global_env_impl => Σ' Γ t []; simpl; unfold wf_decl_pred;\n    intros; auto. destruct X0 as [s []]; intuition auto.\n  Qed.\n\n  (* Hint Resolve on_global_wf_Forall_decls : wf. *)\n  Lemma wf_inds mind u mdecl :\n    All (WfAst.wf Σ) (inds mind u mdecl.(ind_bodies)).\n  Proof using Type.\n    unfold inds. induction #|ind_bodies mdecl|; constructor; auto.\n    now constructor.\n  Qed.\n\n  Hint Resolve wf_inds : wf.\n\n  Lemma on_inductive_wf_params {Σ' : global_env_ext} {kn mdecl} :\n      forall (oib : on_inductive cumul_gen wf_decl_pred Σ'  kn mdecl),\n      All (wf_decl Σ') (ind_params mdecl).\n  Proof using Type.\n    intros oib. apply onParams in oib.\n    red in oib.\n    induction (ind_params mdecl) as [|[? [] ?] ?]; simpl in oib; inv oib; constructor;\n      try red in X0; try red in X1; try red; simpl; intuition auto.\n  Qed.\n\n  Lemma declared_inductive_wf_params {ind mdecl idecl} :\n    on_global_env cumul_gen wf_decl_pred Σ ->\n    declared_inductive Σ ind mdecl idecl -> All (wf_decl Σ) (ind_params mdecl).\n  Proof using Type.\n    intros.\n    destruct H as [Hmdecl Hidecl]. red in Hmdecl.\n    eapply lookup_global_Some_iff_In_NoDup in  Hmdecl; eauto.\n    2: destruct X; now eapply NoDup_on_global_decls.\n      destruct (lookup_on_global_env X Hmdecl) as [Σ' [wfΣ' [ext prf]]]; eauto.\n    eapply on_global_inductive_wf_params in prf.\n    solve_all. eapply wf_decl_extends; tea; typeclasses eauto.\n  Qed.\n\n  Lemma declared_constructor_wf\n    (ind : inductive) (i : nat) (u : list Level.t)\n          (mdecl : mutual_inductive_body) (idecl : one_inductive_body) (cdecl : constructor_body) :\n      on_global_env cumul_gen wf_decl_pred Σ ->\n      declared_constructor Σ (ind, i) mdecl idecl cdecl ->\n      WfAst.wf Σ (cstr_type cdecl).\n  Proof using Type.\n    intros X isdecl.\n    destruct isdecl as [[Hmdecl Hidecl] Hcdecl]. red in Hmdecl.\n    eapply lookup_global_Some_iff_In_NoDup in  Hmdecl; eauto.\n    2: destruct X; now eapply NoDup_on_global_decls.\n      destruct (lookup_on_global_env X Hmdecl) as [Σ' [wfΣ' [ext prf]]]; eauto. red in prf.\n    apply onInductives in prf.\n    eapply nth_error_alli in Hidecl; eauto. simpl in *.\n    pose proof (onConstructors Hidecl) as h. unfold on_constructors in h.\n    eapply All2_nth_error_Some in Hcdecl. 2: eassumption.\n    destruct Hcdecl as [cs [Hnth [? ? [? ?]]]].\n    eapply wf_extends; tea; typeclasses eauto.\n  Qed.\n\n  Lemma wf_case_branch_context_gen {ind mdecl idecl cdecl p br} :\n    on_global_env cumul_gen wf_decl_pred Σ ->\n    declared_constructor Σ ind mdecl idecl cdecl ->\n    All (WfAst.wf Σ) (pparams p) ->\n    All (fun ctor => All (wf_decl Σ) (cstr_args ctor)) (ind_ctors idecl) ->\n    All (wf_decl Σ) (case_branch_context (fst ind) mdecl cdecl p br).\n  Proof using Type.\n    intros ong decli wfpars.\n    intros Hforall.\n    destruct decli as [decli hcstr].\n    eapply nth_error_all in Hforall; tea. cbn in Hforall.\n    unfold case_branch_context, case_branch_context_gen.\n    eapply wf_map2_set_binder_name.\n    apply wf_subst_context; auto.\n    apply wf_subst_instance_context.\n    rewrite /cstr_branch_context.\n    unfold expand_lets_ctx, expand_lets_k_ctx.\n    eapply wf_subst_context.\n    eapply wf_lift_context.\n    eapply wf_subst_context => //.\n    eapply wf_inds.\n    apply wf_extended_subst.\n    eapply declared_inductive_wf_params in decli => //.\n    now eapply All_rev.\n  Qed.\n\n  Lemma wf_case_branches_context ind mdecl idecl p brs :\n    on_global_env cumul_gen wf_decl_pred Σ ->\n    declared_inductive Σ ind mdecl idecl ->\n    All (WfAst.wf Σ) (pparams p) ->\n    All (fun ctor => All (wf_decl Σ) (cstr_args ctor)) (ind_ctors idecl) ->\n    All (fun ctx => All (wf_decl Σ) ctx) (case_branches_contexts ind mdecl idecl p brs).\n  Proof using Type.\n    intros ong decli wfpars.\n    unfold case_branches_contexts.\n    intros Hforall.\n    induction Hforall in brs |- *; destruct brs; cbn; constructor; auto.\n    unfold case_branch_context_gen.\n    eapply wf_map2_set_binder_name.\n    apply wf_subst_context; auto.\n    apply wf_subst_instance_context.\n    2:now eapply All_rev.\n    rewrite /cstr_branch_context.\n    unfold expand_lets_ctx, expand_lets_k_ctx.\n    eapply wf_subst_context.\n    eapply wf_lift_context.\n    eapply wf_subst_context => //.\n    eapply wf_inds.\n    apply wf_extended_subst.\n    now eapply declared_inductive_wf_params in decli.\n  Qed.\n\nEnd WfAst.\n\nRecord wf_inductive_body Σ idecl := {\n  wf_ind_type : WfAst.wf Σ (ind_type idecl);\n  wf_ind_indices : All (WfAst.wf_decl Σ) (ind_indices idecl);\n  wf_ind_ctors : All (fun cdecl => WfAst.wf Σ (cstr_type cdecl)) (ind_ctors idecl);\n  wf_ind_ctor_args : All (fun cs => All (wf_decl Σ) (cstr_args cs)) idecl.(ind_ctors);\n  wf_ind_ctors_indices : All (fun cdecl => All (WfAst.wf Σ) (cstr_indices cdecl)) (ind_ctors idecl);\n  wf_ind_projs : All (fun pdecl => WfAst.wf Σ pdecl.(proj_type)) (ind_projs idecl)\n}.\n\nSection WfLookup.\n  Context {cf:checker_flags}.\n  Context {Σ : global_env_ext}.\n\n  Lemma wf_projs ind npars p : All (WfAst.wf Σ) (projs ind npars p).\n  Proof using Type.\n    unfold projs. induction p; constructor; wf.\n  Qed.\n\n  Lemma on_global_inductive_wf_bodies {kn mdecl} :\n    on_global_decl cumul_gen wf_decl_pred Σ kn (InductiveDecl mdecl) ->\n    All (wf_inductive_body Σ) mdecl.(ind_bodies).\n  Proof using Type.\n    cbn. intros oni.\n    have wfpars : All (wf_decl Σ) (ind_params mdecl).\n    { now eapply on_inductive_wf_params in oni. }\n    eapply onInductives in oni.\n    solve_all.\n    induction oni; constructor; auto.\n    clear oni IHoni.\n    destruct p.\n\n    have wfargs : All (fun cs => All (wf_decl Σ) (cstr_args cs)) hd.(ind_ctors).\n    { unfold on_constructors in onConstructors.\n      clear -onConstructors.\n      induction onConstructors; constructor; auto.\n      destruct r.\n      clear -on_cargs.\n      revert on_cargs. revert y. generalize (cstr_args x).\n      induction c as [|[? [] ?] ?]; simpl;\n        destruct y; intuition auto;\n        constructor;\n        try red; simpl; try red in a0, b0; intuition eauto.\n        now red in b. }\n    split => //.\n    - now destruct onArity.\n    - rewrite ind_arity_eq in onArity .\n      destruct onArity as [ona _].\n      eapply wf_it_mkProd_or_LetIn in ona as [_ ona].\n      now eapply wf_it_mkProd_or_LetIn in ona as [].\n    - unfold on_constructors in onConstructors.\n      clear -onConstructors.\n      induction onConstructors; constructor; auto.\n      destruct r.\n      eapply on_ctype.\n    - unfold on_constructors in onConstructors.\n      clear -onConstructors.\n      induction onConstructors; constructor; auto.\n      destruct r.\n      rewrite cstr_eq in on_ctype.\n      destruct on_ctype as [wf _].\n      eapply wf_it_mkProd_or_LetIn in wf as [_ wf].\n      eapply wf_it_mkProd_or_LetIn in wf as [_ wf].\n      rewrite /cstr_concl in wf.\n      eapply wf_mkApps_inv in wf.\n      now apply All_app in wf as [].\n    - rename onProjections into on_projs.\n      destruct (ind_projs hd) eqn:eqprojs. constructor.\n      destruct (ind_ctors hd) as [|? [|]] eqn:Heq; try contradiction.\n      destruct on_projs. rewrite eqprojs in on_projs.\n      solve_all. eapply Alli_All; tea.\n      intros. red in H.\n      destruct (nth_error (smash_context _ _) _) eqn:Heq'; try contradiction.\n      simpl in Heq. inv wfargs. clear X0.\n      destruct H as [onna ->].\n      eapply wf_subst.\n      eapply wf_inds. eapply wf_subst.\n      eapply wf_projs.\n      eapply wf_lift.\n      eapply All_app_inv in wfpars; [|eapply X].\n      eapply (wf_smash_context _ _ []) in wfpars.\n      2:constructor.\n      eapply nth_error_all in Heq'; eauto.\n      apply Heq'.\n  Qed.\n\nEnd WfLookup.\n\nLemma OnOne2All_All2_All2 (A B C : Type) (P : B -> A -> A -> Type) (Q : C -> A -> Type)\n\t(i : list B) (j : list C) (R : B -> Type) (l l' : list A) :\n  OnOne2All P i l l' ->\n  All2 Q j l ->\n  All R i ->\n  (forall x y a b, R x -> P x a b -> Q y a -> Q y b) ->\n  All2 Q j l'.\nProof.\n  induction 1 in j |- *; intros.\n  depelim X. depelim X0. constructor; eauto.\n  depelim X0. depelim X1.\n  constructor; auto.\nQed.\n\nSection WfRed.\n  Context {cf:checker_flags}.\n  Context {Σ : global_env}.\n\n  Lemma wf_red1 Γ M N :\n    on_global_env cumul_gen wf_decl_pred Σ ->\n    All (wf_decl Σ) Γ ->\n    WfAst.wf Σ M ->\n    red1 Σ Γ M N ->\n    WfAst.wf Σ N.\n  Proof using Type.\n    intros wfΣ wfΓ wfM H.\n    induction H using red1_ind_all in wfM, wfΓ |- *.\n    all: inv wfM.\n    all: try solve[ constructor; intuition auto with wf ].\n    all:auto.\n\n    - inv X. inv X0.\n      eauto with wf.\n    - auto with wf.\n    - apply wf_lift.\n      unfold option_map in H. destruct nth_error eqn:Heq; try discriminate.\n      eapply nth_error_all in wfΓ; eauto. unfold wf_decl in *.\n      apply some_inj in H; rewrite H in wfΓ; apply wfΓ.\n    - unfold iota_red.\n      eapply wf_mkApps_inv in X2.\n      apply wf_subst. eapply All_rev. now eapply All_skipn.\n      rewrite /expand_lets /expand_lets_k.\n      apply wf_subst. apply wf_extended_subst. rewrite /bctx.\n      eapply (wf_case_branch_context_gen (ind := (ci_ind ci, c))); tea.\n      eapply declared_inductive_wf_ctors; tea. apply H0.\n      eapply wf_lift. solve_all.\n      now eapply All2_nth_error_Some_r in X3 as [cb [? []]]; tea.\n    - eapply unfold_fix_wf in H; eauto. eapply wf_mkApps; auto.\n    - econstructor; eauto. apply wf_mkApps_napp in X2 as [Hcof Hargs]; auto.\n      eapply unfold_cofix_wf in H; eauto.\n      apply wf_mkApps; intuition auto.\n    - constructor; auto. apply wf_mkApps_napp in X as [Hcof Hargs]; auto.\n      eapply unfold_cofix_wf in H; eauto.\n      apply wf_mkApps; intuition auto.\n    - apply wf_subst_instance.\n      unfold declared_constant in H.\n      eapply lookup_global_Some_iff_In_NoDup in H; eauto.\n      2: destruct wfΣ; now eapply NoDup_on_global_decls.\n      eapply lookup_on_global_env in H as [Σ' [onΣ' [ext prf]]]; eauto.\n      destruct decl; simpl in *.\n      subst cst_body0; simpl in *; unfold on_constant_decl in prf; cbn in prf.\n      unfold wf_decl_pred in prf. intuition eauto using wf_extends with typeclass_instances.\n    - apply wf_mkApps_inv in X.\n      eapply nth_error_all in X; eauto.\n    - simpl in *. econstructor; eauto. cbn.\n      now rewrite -(OnOne2_length X).\n      cbn. clear H1. induction X; constructor; inv X1; intuition auto.\n    - econstructor; eauto; simpl in *.\n      apply IHred1; eauto.\n      apply All_app_inv => //.\n      apply wf_case_predicate_context; auto.\n      eapply declared_inductive_wf_params in isdecl; eauto.\n      eapply declared_inductive_wf_indices; eauto; wf.\n    - econstructor; eauto.\n    - econstructor; eauto.\n      assert (wf := wf_case_branches_context _ _ _ _ brs wfΣ isdecl X1).\n      forward wf.\n      eapply declared_inductive_wf_ctors; eauto; wf.\n      solve_all.\n      eapply OnOne2All_All2_All2; tea. cbn. intuition auto.\n      now rewrite b0 in a1.\n      apply b2 => //.\n      apply All_app_inv => //.\n    - now eapply wf_mkApps.\n    - constructor; auto. induction X; auto; congruence.\n      clear H X0 H0. induction X; inv X1; constructor; intuition auto; try congruence.\n    - constructor.\n      induction X; inv X0; constructor; intuition auto.\n    - constructor; auto.\n      induction X; inv X0; constructor; intuition auto; congruence.\n    - constructor; auto. solve_all.\n      pose proof X0 as H'. revert X0.\n      apply (OnOne2_All_All X). clear X.\n      intros [na bo ty ra] [nb bb tb rb] [[r ih] e] [? ?].\n      simpl in *.\n      inversion e. subst. clear e.\n      intuition eauto.\n      eapply ih. 2: assumption.\n      solve_all.\n      apply All_app_inv. 2: assumption.\n      unfold fix_context. apply All_rev. eapply All_mapi.\n      eapply All_Alli. 1: exact H'.\n      cbn. unfold wf_decl. simpl.\n      intros ? [? ? ? ?] ?. simpl in *.\n      intuition eauto with wf.\n    - constructor; auto.\n      induction X; inv X0; constructor; intuition auto; congruence.\n    - constructor; auto. solve_all.\n      pose proof X0 as H'. revert X0.\n      apply (OnOne2_All_All X). clear X.\n      intros [na bo ty ra] [nb bb tb rb] [[r ih] e] [? ?].\n      simpl in *.\n      inversion e. subst. clear e.\n      intuition eauto.\n      eapply ih. 2: assumption.\n      solve_all. apply All_app_inv. 2: assumption.\n      unfold fix_context. apply All_rev. eapply All_mapi.\n      eapply All_Alli. 1: exact H'.\n      cbn. unfold wf_decl. simpl.\n      intros ? [? ? ? ?] ?. simpl in *.\n      intuition eauto with wf.\n  Qed.\n\n\n  Lemma wf_lift_wf n k t : WfAst.wf Σ (lift n k t) -> WfAst.wf Σ t.\n  Proof using Type.\n    induction t in n, k |- * using term_forall_list_rect; simpl in *;\n      intros Hwf; inv Hwf; try constructor; eauto;\n        repeat (unfold snd, on_snd in *; simpl in *; solve_all).\n\n    - destruct t; try reflexivity. discriminate.\n    - destruct l; simpl in *; congruence.\n    - eapply All2_map_right_inv in X5. econstructor; eauto; solve_all.\n      now rewrite map_length in H1.\n  Qed.\n\n  Lemma declared_projection_wf (p : projection)\n          (mdecl : mutual_inductive_body) (idecl : one_inductive_body) cdecl pdecl :\n      declared_projection Σ p mdecl idecl cdecl pdecl ->\n      on_global_env cumul_gen wf_decl_pred Σ ->\n      WfAst.wf Σ pdecl.(proj_type).\n  Proof using Type.\n    intros isdecl X.\n    destruct isdecl as [[[Hmdecl Hidecl] Hcdecl] Hpdecl].\n    eapply lookup_global_Some_iff_In_NoDup in Hmdecl; eauto.\n    2: destruct X; now eapply NoDup_on_global_decls.\n    destruct (lookup_on_global_env X Hmdecl) as [Σ' [wfΣ' [ext prf]]]; eauto.\n    assert (wfpars := on_inductive_wf_params prf).\n    eapply on_global_inductive_wf_bodies in prf => //.\n    eapply nth_error_all in Hidecl; eauto. intuition auto.\n    destruct Hidecl.\n    eapply nth_error_all in wf_ind_projs0; eauto. intuition auto.\n    eauto using wf_extends with typeclass_instances.\n  Qed.\n\n  Lemma declared_constant_wf cst decl :\n    on_global_env cumul_gen wf_decl_pred Σ ->\n    declared_constant Σ cst decl ->\n    WfAst.wf Σ decl.(cst_type) *\n    on_some_or_none (WfAst.wf Σ) decl.(cst_body).\n  Proof using Type.\n    intros wΣ h.\n    unfold declared_constant in h.\n    eapply lookup_global_Some_iff_In_NoDup in h; eauto.\n    2: destruct wΣ; now eapply NoDup_on_global_decls.\n    destruct (lookup_on_global_env wΣ h) as [Σ' [wΣ' [ext h']]].\n    simpl in h'.\n    destruct decl as [ty [bo|]]. all: cbn in *.\n    - destruct h'. intuition eauto using wf_extends with typeclass_instances.\n    - destruct h'. intuition eauto using wf_extends with typeclass_instances.\n  Qed.\n\n  Lemma wf_it_mkProd_or_LetIn_inv (Σ' : global_env_ext) Γ (wfΓ : wf_local Σ' Γ)\n    : All_local_env_over typing\n    (fun (Σ : global_env_ext) (Γ : context) (_ : wf_local Σ Γ)\n      (t T : term) (_ : Σ;;; Γ |- t : T) => WfAst.wf Σ t * WfAst.wf Σ T) Σ'\n          Γ wfΓ\n  -> forall t, WfAst.wf Σ' t -> WfAst.wf Σ' (it_mkProd_or_LetIn Γ t).\n  Proof using Type.\n    induction 1; simpl.\n    - trivial.\n    - intros t0 Ht0. apply IHX. constructor. apply Hs. assumption.\n    - intros t0 Ht0. apply IHX. constructor. apply Hc. apply Hc. assumption.\n  Qed.\n\n  Lemma wf_Lambda_or_LetIn {d t} :\n    wf_decl Σ d ->\n    WfAst.wf Σ t ->\n    WfAst.wf Σ (mkLambda_or_LetIn d t).\n  Proof using Type.\n    destruct d as [? [|] ?]; simpl; wf;\n    unfold wf_decl, mkLambda_or_LetIn in *; simpl in *.\n    constructor; intuition auto.\n    constructor; intuition auto.\n  Qed.\n\n  Lemma wf_it_mkLambda_or_LetIn {Γ t} :\n    All (wf_decl Σ) Γ ->\n    WfAst.wf Σ t ->\n    WfAst.wf Σ (it_mkLambda_or_LetIn Γ t).\n  Proof using Type.\n    intros wfΓ wft; induction wfΓ in t, wft |- *; simpl.\n    - trivial.\n    - apply IHwfΓ. now apply wf_Lambda_or_LetIn.\n  Qed.\n\nEnd WfRed.\n\n#[global]\nHint Resolve wf_extends strictly_extends_decls_extends_decls strictly_extends_decls_extends_strictly_on_decls extends_decls_extends extends_strictly_on_decls_extends : wf.\n\nLemma All2i_All2 {A B} {P : nat -> A -> B -> Type} {Q : A -> B -> Type} n l l' :\n  All2i P n l l' ->\n  (forall i x y, P i x y -> Q x y) ->\n  All2 Q l l'.\nProof.\n  induction 1; constructor; eauto.\nQed.\n\nLemma cstr_branch_context_length ind mdecl cdecl :\n  #|cstr_branch_context ind mdecl cdecl| = #|cdecl.(cstr_args)|.\nProof. rewrite /cstr_branch_context. now len. Qed.\n\nGlobal Hint Rewrite cstr_branch_context_length : len.\n\n(* Lemma case_branch_context_gen_length ind mdecl p puinst pctx :\n  #|case_branch_context_gen ind mdecl p puinst pctx | = #|pctx|. *)\n\nSection TypingWf.\n  Context {cf}.\n\n  Ltac specialize_goal :=\n    repeat match goal with\n    | H : ?P -> _, H' : ?P |- _ => specialize (H H')\n    end.\n\n  Lemma typing_wf_gen :\n    env_prop\n      (fun Σ Γ t T => WfAst.wf Σ t * WfAst.wf Σ T)\n      (fun Σ Γ wfΓ => All (wf_decl Σ) Γ).\n  Proof using Type.\n    apply typing_ind_env; intros; auto with wf;\n      specialize_goal;\n      try solve [split; try constructor; intuition auto with wf].\n\n    - eapply All_local_env_wf_decls.\n      induction X; constructor; auto; red; intuition auto.\n    - split; wf. apply wf_lift.\n      apply (nth_error_all H X).\n    - split. constructor; auto. wf.\n      clear -X1.\n      induction X1; constructor; now auto.\n      destruct X0 as [_ X0].\n      clear X H H0.\n      induction X1; auto. apply IHX1.\n      apply wf_subst. now destruct p0. destruct p. now inv w.\n    - split. wf. apply wf_subst_instance. wf.\n      eapply lookup_global_Some_iff_In_NoDup in H; eauto.\n      2: destruct wfΣ; now eapply NoDup_on_global_decls.\n      destruct (lookup_on_global_env X H) as [Σ' [wfΣ' [ext prf]]]; eauto.\n      red in prf. destruct decl; destruct cst_body0; red in prf; simpl in *; wf.\n      destruct prf as [s []]. wf.\n\n    - split. wf. apply wf_subst_instance.\n      eapply declared_inductive_wf; eauto.\n      now eapply Forall_decls_on_global_wf.\n\n    - split. wf. unfold type_of_constructor.\n      apply wf_subst; auto with wf.\n      apply wf_inds.\n      apply wf_subst_instance.\n      eapply declared_constructor_wf; eauto.\n      now eapply Forall_decls_on_global_wf.\n\n    - destruct X3 as [wfret wps].\n      destruct X6 as [wfc wfapps].\n      eapply wf_mkApps_inv in wfapps.\n      eapply All_app in wfapps as [wfp wfindices].\n      assert (All (wf_decl Σ) predctx).\n      { now apply All_app in X4 as [? ?]. }\n      split; [econstructor; simpl; eauto; solve_all|].\n      eapply All2i_All2; tea; repeat intuition auto.\n      apply wf_mkApps. subst ptm. wf. apply wf_it_mkLambda_or_LetIn; auto.\n      apply All_app_inv; auto.\n    - split. wf. apply wf_subst. solve_all. constructor. wf.\n      apply wf_mkApps_inv in b. apply All_rev. solve_all.\n      eapply declared_projection_wf in isdecl; eauto.\n      now eapply wf_subst_instance.\n      now eapply Forall_decls_on_global_wf.\n\n    - subst types.\n      clear H.\n      split.\n      + constructor.\n        solve_all; destruct a, b.\n        all: intuition.\n      + eapply All_nth_error in X0; eauto.\n        destruct X0 as [s ?]; intuition.\n\n    - subst types.\n      split.\n      + constructor.\n        solve_all; destruct a, b.\n        all: intuition.\n      + eapply All_nth_error in X0; eauto. destruct X0 as [s ?]; intuition.\n  Qed.\n\n  Lemma typing_all_wf_decl Σ (wfΣ : wf Σ.1) Γ (wfΓ : wf_local Σ Γ) :\n    All (wf_decl Σ.1) Γ.\n  Proof using Type.\n    eapply (env_prop_wf_local typing_wf_gen); eauto.\n  Qed.\n  Hint Resolve typing_all_wf_decl : wf.\n\n  Lemma typing_wf_sigma Σ (wfΣ : wf Σ) :\n    on_global_env cumul_gen wf_decl_pred Σ.\n  Proof using Type.\n    intros.\n    pose proof (env_prop_sigma typing_wf_gen _ wfΣ). red in X.\n    do 2 red in wfΣ.\n    eapply on_global_env_impl; eauto; simpl; intros.\n    destruct T. red. apply X1. red. destruct X1 as [x [a wfs]]. split; auto.\n  Qed.\n\n  Lemma typing_wf Σ (wfΣ : wf Σ.1) Γ t T :\n    Σ ;;; Γ |- t : T -> WfAst.wf Σ.1 t * WfAst.wf Σ.1 T.\n  Proof using Type.\n    intros. eapply typing_wf_gen in X; intuition eauto with wf.\n  Qed.\n\n  Lemma declared_minductive_wf {Σ : global_env} {mind mdecl} {wfΣ : wf Σ} :\n    declared_minductive Σ mind mdecl ->\n    All (wf_decl Σ) (ind_params mdecl) *\n    All (@wf_inductive_body Σ) (ind_bodies mdecl).\n  Proof using Type.\n    intros declm.\n    pose proof (typing_wf_gen (Env.empty_ext Σ) wfΣ _ localenv_nil _ _ (type_Prop _)) as [X _].\n    eapply Forall_decls_on_global_wf in X.\n    eapply lookup_global_Some_iff_In_NoDup in declm; eauto.\n    2: destruct X; now eapply NoDup_on_global_decls.\n    destruct (lookup_on_global_env X declm) as [? [? [ext ?]]]; eauto.\n    split. eapply on_global_inductive_wf_params in o0. solve_all. eauto using wf_decl_extends with typeclass_instances.\n    eapply on_global_inductive_wf_bodies in o0. solve_all.\n    destruct X0; split; solve_all; eauto using wf_extends, wf_decl_extends with typeclass_instances.\n  Qed.\n\n  Lemma declared_inductive_wf_case_predicate_context\n     {Σ : global_env} {wfΣ : wf Σ} {ind mdecl idecl p} :\n    declared_inductive Σ ind mdecl idecl ->\n    All (WfAst.wf Σ) p.(pparams) ->\n    All (wf_decl Σ) (case_predicate_context ind mdecl idecl p).\n  Proof using Type.\n    intros decli.\n    destruct (declared_minductive_wf (proj1 decli)) as [wfp wfb].\n    intros wfpars.\n    eapply wf_case_predicate_context => //.\n    destruct decli as [declm hi].\n    eapply nth_error_all in wfb; tea. apply wfb.\n  Qed.\n\n  Lemma declared_constructor_wf_case_branch_context\n    {Σ} {wfΣ : wf Σ} {ind mdecl idecl cdecl p br} :\n    declared_constructor Σ ind mdecl idecl cdecl ->\n    All (WfAst.wf Σ) (pparams p) ->\n    All (wf_decl Σ) (case_branch_context (fst ind) mdecl cdecl p br).\n  Proof using Type.\n    intros.\n    eapply wf_case_branch_context_gen; tea => //.\n    now apply typing_wf_sigma.\n    destruct (declared_minductive_wf (proj1 (proj1 H))).\n    destruct H as [[hm hnth] hnth'].\n    eapply nth_error_all in a0; tea.\n    now eapply wf_ind_ctor_args.\n  Qed.\n\n  Lemma mkApp_ex_wf Σ t u : WfAst.wf Σ (mkApp t u) ->\n    exists f args, mkApp t u = tApp f args /\\ ~~ isApp f.\n  Proof using Type.\n    induction t; simpl; try solve [eexists _, _; split; reflexivity].\n    intros wf.\n    eapply wf_inv in wf as [[[appt _] wft] wfargs].\n    eapply All_app in wfargs as [wfargs wfu]. depelim wfu.\n    forward IHt. eapply wf_mkApp; intuition auto.\n    destruct IHt as [f [ar [eqf isap]]].\n    eexists _, _; split; auto. rewrite appt //.\n  Qed.\n\n  Lemma decompose_app_mkApp f u :\n    (decompose_app (mkApp f u)).2 <> [].\n  Proof using Type.\n    induction f; simpl; auto; try congruence.\n    destruct args; simpl; congruence.\n  Qed.\n\n  Lemma mkApps_tApp' f u f' u' :\n    ~~ isApp f' ->\n    mkApp f u = tApp f' u' -> mkApps f [u] = mkApps f' u'.\n  Proof using Type.\n    intros.\n    rewrite -(mkApp_mkApps f u []).\n    simpl. rewrite H0.\n    rewrite -(mkApps_tApp f') // ?H //.\n    destruct u' => //.\n    eapply (f_equal decompose_app) in H0.\n    simpl in H0. pose proof (decompose_app_mkApp f u).\n    rewrite H0 /= in H1. congruence.\n  Qed.\n\n  Lemma eq_decompose_app Σ x y :\n    WfAst.wf Σ x -> WfAst.wf Σ y ->\n    decompose_app x = decompose_app y -> x = y.\n  Proof using Type.\n    intros wfx; revert y.\n    induction wfx using term_wf_forall_list_ind; intros [] wfy;\n    eapply wf_inv in wfy; simpl in wfy; simpl;\n    intros [= ?]; try intuition congruence.\n  Qed.\n\n  Lemma mkApp_ex t u : ∑ f args, mkApp t u = tApp f args.\n  Proof using Type.\n    induction t; simpl; try solve [eexists _, _; reflexivity].\n  Qed.\n\n  Lemma strip_casts_decompose_app Σ t :\n    WfAst.wf Σ t ->\n    forall f l, decompose_app t = (f, l) ->\n    strip_casts t = mkApps (strip_casts f) (map strip_casts l).\n  Proof using Type.\n    intros wf.\n    induction wf using term_wf_forall_list_ind; simpl; intros; auto; noconf H;\n    try noconf H0;\n      rewrite ?map_map_compose  ?compose_on_snd ?compose_map_def ?map_length;\n        f_equal; solve_all; eauto.\n    - now noconf H1.\n    - now noconf H1.\n    - now noconf H2.\n  Qed.\n\n  Lemma mkApps_tApp f args :\n    ~~ isApp f ->\n    ~~ is_empty args ->\n    tApp f args = mkApps f args.\n  Proof using Type.\n    intros.\n    destruct args, f; try discriminate; auto.\n  Qed.\n\n  Lemma strip_casts_mkApps_napp_wf Σ f u :\n    ~~ isApp f -> WfAst.wf Σ f -> All (WfAst.wf Σ) u ->\n    strip_casts (mkApps f u) = mkApps (strip_casts f) (map strip_casts u).\n  Proof using Type.\n    intros nisapp wf wf'.\n    destruct u.\n    simpl. auto.\n    rewrite -(mkApps_tApp f (t :: u)) //.\n  Qed.\n\n  Lemma mkApp_mkApps f u : mkApp f u = mkApps f [u].\n  Proof using Type. reflexivity. Qed.\n\n  Lemma decompose_app_inv Σ f l hd args :\n    WfAst.wf Σ f ->\n    decompose_app (mkApps f l) = (hd, args) ->\n    ∑ n, ~~ isApp hd /\\ l = skipn n args /\\ f = mkApps hd (firstn n args).\n  Proof using Type.\n    destruct (isApp f) eqn:Heq.\n    revert l args hd.\n    induction f; try discriminate. intros.\n    simpl in X.\n    move/wf_inv: X => /= [[[isAppf Hargs] wff] wfargs].\n    rewrite mkApps_tApp ?isAppf in H => //. destruct args => //.\n    rewrite -mkApps_app in H.\n    rewrite decompose_app_mkApps ?isAppf in H; auto. noconf H.\n    exists #|args|; split; auto. now rewrite isAppf.\n    rewrite skipn_all_app.\n    rewrite firstn_app. rewrite firstn_all2. lia.\n    rewrite Nat.sub_diag firstn_O app_nil_r. split; auto.\n    rewrite mkApps_tApp ?isAppf //. now destruct args.\n\n    intros wff fl.\n    rewrite decompose_app_mkApps in fl; auto. now apply negbT.\n    inversion fl. subst; exists 0.\n    split; auto. now eapply negbT.\n  Qed.\n\n  Lemma eq_tip_skipn {A} (x : A) n l : [x] = skipn n l ->\n    exists l', l = l' ++ [x] /\\ n = #|l'|.\n  Proof using Type.\n    induction l in n |- *. rewrite skipn_nil //.\n    destruct n. simpl. destruct l => //.\n    intros eq. noconf eq. exists []; split; auto.\n    rewrite skipn_S. intros Hx.\n    destruct (IHl _ Hx) as [l' [-> ->]].\n    exists (a :: l'); split; reflexivity.\n  Qed.\n\n  Lemma strip_casts_mkApp_wf Σ f u :\n    WfAst.wf Σ f -> WfAst.wf Σ u ->\n    strip_casts (mkApp f u) = mkApp (strip_casts f) (strip_casts u).\n  Proof using Type.\n    intros wf wf'.\n    assert (wfa : WfAst.wf Σ (mkApp f u)). now apply wf_mkApp.\n    destruct (mkApp_ex_wf Σ f u wfa) as [f' [args [eq isapp]]].\n    eapply (f_equal decompose_app) in eq. simpl in eq.\n    epose proof (strip_casts_decompose_app Σ _ wfa _ _ eq).\n    rewrite H.\n    rewrite mkApp_mkApps in eq.\n    destruct (decompose_app_inv Σ _ _ _ _ wf eq) as [n [ng [stripeq stripf]]].\n    apply eq_tip_skipn in stripeq. destruct stripeq as [l' [eqargs eqn]].\n    subst n args. rewrite firstn_app_left // in stripf. subst f.\n    eapply wf_mkApps_napp in wf as [wff' wfl] => //.\n    rewrite (strip_casts_mkApps_napp_wf Σ) //.\n    now rewrite mkApp_mkApps -mkApps_app map_app.\n  Qed.\n\n  Lemma strip_casts_mkApps_wf Σ f u :\n    WfAst.wf Σ f -> All (WfAst.wf Σ) u ->\n    strip_casts (mkApps f u) = mkApps (strip_casts f) (map strip_casts u).\n  Proof using Type.\n    intros wf wf'. induction wf' in f, wf |- *.\n    simpl. auto.\n    rewrite -mkApps_mkApp IHwf'.\n    apply wf_mkApp; auto with wf.\n    rewrite (strip_casts_mkApp_wf Σ) //.\n    now rewrite mkApps_mkApp.\n  Qed.\nEnd TypingWf.\n", "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/TypingWf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2640504747110211}}
{"text": "Require Import List. \nImport ListNotations.\n\nRequire Import oeuf.StuartTact.\nRequire Import StructTact.StructTactics.\nRequire Import oeuf.ListLemmas.\n\nRequire Import Setoid.\n\nRequire SHA256_N.\n\n\nRequire Arith.\nRequire Import ZArith.\n\nLocal Open Scope positive.\nSet Default Timeout 5.\n\n\nFixpoint pos_succ0 (x : positive) {struct x} : positive :=\n    match x with\n    | x~1 => (pos_succ0 x)~0\n    | x~0 => x~1\n    | 1 => 2\n    end.\n\nLemma pos_succ0_eq : forall x,\n    pos_succ0 x = Pos.succ x.\ninduction x; simpl; congruence.\nQed.\n\nDefinition pos_succ (x : positive) : positive :=\n    positive_rect _\n        (fun x IHx dummy => (IHx dummy)~0)\n        (fun x IHx dummy => x~1)\n        (fun dummy => 2)\n        x tt.\n\nLemma pos_succ_eq' : forall x,\n    pos_succ x = pos_succ0 x.\ninduction x; unfold pos_succ; simpl; try fold (pos_succ x); congruence.\nQed.\n\nLemma pos_succ_eq : forall x,\n    pos_succ x = Pos.succ x.\nintros. rewrite pos_succ_eq', pos_succ0_eq. auto.\nQed.\n\n\nFixpoint pos_add_with_carry0 (x y : positive) (c : bool) {struct x} : positive :=\n    match x with\n    | x~1 =>\n            match y with\n            | y~1 =>\n                    if c then (pos_add_with_carry0 x y true)~1\n                    else (pos_add_with_carry0 x y true)~0\n            | y~0 =>\n                    if c then (pos_add_with_carry0 x y true)~0\n                    else (pos_add_with_carry0 x y false)~1\n            | 1 =>\n                    if c then (pos_succ x)~1\n                    else (pos_succ x)~0\n            end\n    | x~0 =>\n            match y with\n            | y~1 =>\n                    if c then (pos_add_with_carry0 x y true)~0\n                    else (pos_add_with_carry0 x y false)~1\n            | y~0 =>\n                    if c then (pos_add_with_carry0 x y false)~1\n                    else (pos_add_with_carry0 x y false)~0\n            | 1 =>\n                    if c then (pos_succ x)~0\n                    else x~1\n            end\n    | 1 =>\n            match y with\n            | y~1 =>\n                    if c then (pos_succ y)~1\n                    else (pos_succ y)~0\n            | y~0 =>\n                    if c then (pos_succ y)~0\n                    else y~1\n            | 1 =>\n                    if c then 3\n                    else 2\n            end\n    end.\n\nLemma pos_add_with_carry0_eq : forall x y,\n    pos_add_with_carry0 x y false = Pos.add x y.\nfix go 1\nwith (go_carry x y {struct x} : pos_add_with_carry0 x y true = Pos.add_carry x y).\n\n{\ndestruct x, y; simpl.\nall: repeat rewrite pos_succ_eq.\nall: try reflexivity.\n- f_equal. apply go_carry.\n- f_equal. apply go.\n- f_equal. apply go.\n- f_equal. apply go.\n}\n\n{\ndestruct x, y; simpl.\nall: repeat rewrite pos_succ_eq.\nall: try reflexivity.\n- f_equal. apply go_carry.\n- f_equal. apply go_carry.\n- f_equal. apply go_carry.\n- f_equal. apply go.\n}\nQed.\n\nDefinition pos_add_with_carry (x y : positive) (c : bool) : positive :=\n    positive_rect _\n        (fun x IHx => fun y => positive_rect _\n            (fun y IHy => fun c => bool_rect _\n                (fun dummy => (IHx y true dummy)~1)\n                (fun dummy => (IHx y true dummy)~0)\n                c)\n            (fun y IHy => fun c => bool_rect _\n                (fun dummy => (IHx y true dummy)~0)\n                (fun dummy => (IHx y false dummy)~1)\n                c)\n            (fun c => bool_rect _\n                (fun dummy => (pos_succ x)~1)\n                (fun dummy => (pos_succ x)~0)\n                c)\n            y)\n        (fun x IHx => fun y => positive_rect _\n            (fun y IHy => fun c => bool_rect _\n                (fun dummy => (IHx y true dummy)~0)\n                (fun dummy => (IHx y false dummy)~1)\n                c)\n            (fun y IHy => fun c => bool_rect _\n                (fun dummy => (IHx y false dummy)~1)\n                (fun dummy => (IHx y false dummy)~0)\n                c)\n            (fun c => bool_rect _\n                (fun dummy => (pos_succ x)~0)\n                (fun dummy => x~1)\n                c)\n            y)\n        (fun y => positive_rect _\n            (fun y IHy => fun c => bool_rect _\n                (fun dummy => (pos_succ y)~1)\n                (fun dummy => (pos_succ y)~0)\n                c)\n            (fun y IHy => fun c => bool_rect _\n                (fun dummy => (pos_succ y)~0)\n                (fun dummy => y~1)\n                c)\n            (fun c => bool_rect _\n                (fun dummy => 3)\n                (fun dummy => 2)\n                c)\n            y)\n        x y c tt.\n\nLemma pos_add_with_carry_eq : forall x y c,\n    pos_add_with_carry x y c = pos_add_with_carry0 x y c.\ninduction x; destruct y; destruct c; simpl.\nall: unfold pos_add_with_carry; simpl;\n  try fold (pos_add_with_carry x y true);\n  try fold (pos_add_with_carry x y false).\n\nall: try rewrite IHx.\nall: reflexivity.\nQed.\n\nDefinition pos_add (x y : positive) : positive :=\n    positive_rect (fun _ => positive -> bool -> unit -> positive)\n        (fun x IHx => fun y => positive_rect _\n            (fun y IHy => fun c => bool_rect _\n                (fun dummy => (IHx y true dummy)~1)\n                (fun dummy => (IHx y true dummy)~0)\n                c)\n            (fun y IHy => fun c => bool_rect _\n                (fun dummy => (IHx y true dummy)~0)\n                (fun dummy => (IHx y false dummy)~1)\n                c)\n            (fun c => bool_rect _\n                (fun dummy => (pos_succ x)~1)\n                (fun dummy => (pos_succ x)~0)\n                c)\n            y)\n        (fun x IHx => fun y => positive_rect _\n            (fun y IHy => fun c => bool_rect _\n                (fun dummy => (IHx y true dummy)~0)\n                (fun dummy => (IHx y false dummy)~1)\n                c)\n            (fun y IHy => fun c => bool_rect _\n                (fun dummy => (IHx y false dummy)~1)\n                (fun dummy => (IHx y false dummy)~0)\n                c)\n            (fun c => bool_rect _\n                (fun dummy => (pos_succ x)~0)\n                (fun dummy => x~1)\n                c)\n            y)\n        (fun y => positive_rect _\n            (fun y IHy => fun c => bool_rect _\n                (fun dummy => (pos_succ y)~1)\n                (fun dummy => (pos_succ y)~0)\n                c)\n            (fun y IHy => fun c => bool_rect _\n                (fun dummy => (pos_succ y)~0)\n                (fun dummy => y~1)\n                c)\n            (fun c => bool_rect _\n                (fun dummy => 3)\n                (fun dummy => 2)\n                c)\n            y)\n        x y false tt.\n\nLemma pos_add_eq' : forall x y,\n    pos_add x y = pos_add_with_carry x y false.\nintros. reflexivity.\nQed.\n\nLemma pos_add_eq : forall x y,\n    pos_add x y = Pos.add x y.\nintros.\nrewrite pos_add_eq', pos_add_with_carry_eq, pos_add_with_carry0_eq.\nreflexivity.\nQed.\n\nDefinition N_add (x y : N) : N :=\n    N_rect _\n        (fun y => y)\n        (fun xp => fun y => N_rect _\n            (x)\n            (fun yp => N.pos (pos_add xp yp))\n            y)\n        x y.\n\nLemma N_add_eq : forall x y,\n    N_add x y = N.add x y.\ndestruct x, y; simpl; try rewrite pos_add_eq; reflexivity.\nQed.\n\n\nDefinition Pos_Ndouble (x : N) : N :=\n    N_rect _\n        (0%N)\n        (fun xp => N.pos xp~0)\n        x.\n\nLemma Pos_Ndouble_eq : forall x,\n    Pos_Ndouble x = Pos.Ndouble x.\ndestruct x; simpl; reflexivity.\nQed.\n\nDefinition Pos_Nsucc_double (x : N) : N :=\n    N_rect _\n        (1%N)\n        (fun xp => N.pos xp~1)\n        x.\n\nLemma Pos_Nsucc_double_eq : forall x,\n    Pos_Nsucc_double x = Pos.Nsucc_double x.\ndestruct x; simpl; reflexivity.\nQed.\n\n\nDefinition Pos_land (x y : positive) : N :=\n    positive_rect (fun _ => positive -> unit -> N)\n        (fun x IHx => fun y => positive_rect (fun _ => unit -> N)\n            (fun y IHy => fun dummy => Pos_Nsucc_double (IHx y dummy))\n            (fun y IHy => fun dummy => Pos_Ndouble (IHx y dummy))\n            (fun dummy => 1%N)\n            y)\n        (fun x IHx => fun y => positive_rect _\n            (fun y IHy => fun dummy => Pos_Ndouble (IHx y dummy))\n            (fun y IHy => fun dummy => Pos_Ndouble (IHx y dummy))\n            (fun dummy => 0%N)\n            y)\n        (fun y => positive_rect _\n            (fun y IHy => fun dummy => 1%N)\n            (fun y IHy => fun dummy => 0%N)\n            (fun dummy => 1%N)\n            y)\n        x y tt.\n\nLemma Pos_land_eq : forall x y,\n    Pos_land x y = Pos.land x y.\ninduction x; destruct y; simpl; try reflexivity.\n- rewrite <- Pos_Nsucc_double_eq, <- IHx. reflexivity.\n- rewrite <- Pos_Ndouble_eq, <- IHx. reflexivity.\n- rewrite <- Pos_Ndouble_eq, <- IHx. reflexivity.\n- rewrite <- Pos_Ndouble_eq, <- IHx. reflexivity.\nQed.\n\nDefinition N_land (x y : N) : N :=\n    N_rect (fun _ => N -> N)\n        (fun y => 0%N)\n        (fun xp => fun y => N_rect (fun _ => N)\n            (0%N)\n            (fun yp => Pos_land xp yp)\n            y)\n        x y.\n\nLemma N_land_eq : forall x y,\n    N_land x y = N.land x y.\ndestruct x, y; simpl; try reflexivity.\n- rewrite <- Pos_land_eq. reflexivity.\nQed.\n\n\nDefinition Pos_lor (x y : positive) : positive :=\n    positive_rect (fun _ => positive -> unit -> positive)\n        (fun x IHx => fun y => positive_rect (fun _ => unit -> positive)\n            (fun y IHy => fun dummy => (IHx y dummy)~1)\n            (fun y IHy => fun dummy => (IHx y dummy)~1)\n            (fun dummy => x~1)\n            y)\n        (fun x IHx => fun y => positive_rect _\n            (fun y IHy => fun dummy => (IHx y dummy)~1)\n            (fun y IHy => fun dummy => (IHx y dummy)~0)\n            (fun dummy => x~1)\n            y)\n        (fun y => positive_rect _\n            (fun y IHy => fun dummy => y~1)\n            (fun y IHy => fun dummy => y~1)\n            (fun dummy => xH)\n            y)\n        x y tt.\n\nLemma Pos_lor_eq : forall x y,\n    Pos_lor x y = Pos.lor x y.\ninduction x; destruct y; simpl; try reflexivity.\n- rewrite <- IHx. reflexivity.\n- rewrite <- IHx. reflexivity.\n- rewrite <- IHx. reflexivity.\n- rewrite <- IHx. reflexivity.\nQed.\n\nDefinition N_lor (x y : N) : N :=\n    N_rect (fun _ => N -> N)\n        (fun y => y)\n        (fun xp => fun y => N_rect (fun _ => N)\n            (x)\n            (fun yp => N.pos (Pos_lor xp yp))\n            y)\n        x y.\n\nLemma N_lor_eq : forall x y,\n    N_lor x y = N.lor x y.\ndestruct x, y; simpl; try reflexivity.\n- rewrite <- Pos_lor_eq. reflexivity.\nQed.\n\n\nDefinition Pos_lxor (x y : positive) : N :=\n    positive_rect (fun _ => positive -> unit -> N)\n        (fun x IHx => fun y => positive_rect (fun _ => unit -> N)\n            (fun y IHy => fun dummy => Pos_Ndouble (IHx y dummy))\n            (fun y IHy => fun dummy => Pos_Nsucc_double (IHx y dummy))\n            (fun dummy => N.pos x~0)\n            y)\n        (fun x IHx => fun y => positive_rect _\n            (fun y IHy => fun dummy => Pos_Nsucc_double (IHx y dummy))\n            (fun y IHy => fun dummy => Pos_Ndouble (IHx y dummy))\n            (fun dummy => N.pos x~1)\n            y)\n        (fun y => positive_rect _\n            (fun y IHy => fun dummy => N.pos y~0)\n            (fun y IHy => fun dummy => N.pos y~1)\n            (fun dummy => 0%N)\n            y)\n        x y tt.\n\nLemma Pos_lxor_eq : forall x y,\n    Pos_lxor x y = Pos.lxor x y.\ninduction x; destruct y; simpl; try reflexivity.\n- rewrite <- Pos_Ndouble_eq, <- IHx. reflexivity.\n- rewrite <- Pos_Nsucc_double_eq, <- IHx. reflexivity.\n- rewrite <- Pos_Nsucc_double_eq, <- IHx. reflexivity.\n- rewrite <- Pos_Ndouble_eq, <- IHx. reflexivity.\nQed.\n\nDefinition N_lxor (x y : N) : N :=\n    N_rect (fun _ => N -> N)\n        (fun y => y)\n        (fun xp => fun y => N_rect (fun _ => N)\n            (x)\n            (fun yp => Pos_lxor xp yp)\n            y)\n        x y.\n\nLemma N_lxor_eq : forall x y,\n    N_lxor x y = N.lxor x y.\ndestruct x, y; simpl; try reflexivity.\n- rewrite <- Pos_lxor_eq. reflexivity.\nQed.\n\n\nDefinition Pos_pred_double (x : positive) : positive :=\n    positive_rect _\n        (fun x IHx => fun dummy => x~0~1)\n        (fun x IHx => fun dummy => (IHx dummy)~1)\n        (fun dummy => 1)\n        x tt.\n\nLemma Pos_pred_double_eq : forall x,\n    Pos_pred_double x = Pos.pred_double x.\ninduction x; simpl; try reflexivity.\n- rewrite <- IHx. reflexivity.\nQed.\n\nDefinition Pos_pred_N (x : positive) : N :=\n    positive_rect _\n        (fun x IHx => fun dummy => N.pos x~0)\n        (fun x IHx => fun dummy => N.pos (Pos_pred_double x))\n        (fun dummy => 0%N)\n        x tt.\n\nLemma Pos_pred_N_eq : forall x,\n    Pos_pred_N x = Pos.pred_N x.\ninduction x; simpl; try reflexivity.\n- rewrite <- Pos_pred_double_eq. reflexivity.\nQed.\n\nDefinition N_pred (x : N) : N :=\n    N_rect _\n        (0%N)\n        (fun xp => Pos_pred_N xp)\n        x.\n\nLemma N_pred_eq : forall x,\n    N_pred x = N.pred x.\ndestruct x; simpl; try reflexivity.\n- rewrite <- Pos_pred_N_eq. reflexivity.\nQed.\n\n\nDefinition Pos_iter {A} (f : A -> A) (x : A) (n : positive) : A :=\n    positive_rect (fun _ => A -> A)\n        (fun n' IHn' => fun x => f (IHn' (IHn' x)))\n        (fun n' IHn' => fun x => IHn' (IHn' x))\n        (f)\n        n x.\n\nLemma Pos_iter_eq : forall {A} (f : A -> A) n x,\n    Pos_iter f x n = Pos.iter f x n.\ninduction n; intros; simpl; try reflexivity.\n- rewrite <- 2 IHn. reflexivity.\n- rewrite <- 2 IHn. reflexivity.\nQed.\n\nLemma Pos_iter_ext : forall {A} (f f' : A -> A) n x,\n    (forall x, f x = f' x) ->\n    Pos_iter f x n = Pos_iter f' x n.\ninduction n; intros0 Hf; simpl; try reflexivity.\n- rewrite <- Hf, <- 2 IHn by auto. reflexivity.\n- rewrite <- 2 IHn by auto. reflexivity.\n- apply Hf.\nQed.\n\n\nDefinition Pos_shiftl (x : positive) (n : N) : positive :=\n    N_rect _\n        x\n        (fun n' => Pos_iter (fun y => xO y) x n')\n        n.\n\nLemma Pos_shiftl_eq : forall n x,\n    Pos_shiftl x n = Pos.shiftl x n.\ndestruct n; intros; simpl; try reflexivity.\n- rewrite <- Pos_iter_eq. reflexivity.\nQed.\n\nDefinition N_shiftl (x b : N) : N :=\n    N_rect _\n        (0%N)\n        (fun xp => N.pos (Pos_shiftl xp b))\n        x.\n\nLemma N_shiftl_eq : forall x y,\n    N_shiftl x y = N.shiftl x y.\ndestruct x; intros; simpl; try reflexivity.\n- rewrite <- Pos_shiftl_eq. reflexivity.\nQed.\n\n\nDefinition Pos_div2 (x : positive) : positive :=\n    positive_rect _\n        (fun x IHx => x)\n        (fun x IHx => x)\n        (1)\n        x.\n\nLemma Pos_div2_eq : forall x,\n    Pos_div2 x = Pos.div2 x.\ndestruct x; simpl; try reflexivity.\nQed.\n\nDefinition N_div2 (x : N) : N :=\n    N_rect _\n        (0%N)\n        (fun xp => positive_rect (fun _ => N)\n            (fun xp' IHxp' => N.pos xp')\n            (fun xp' IHxp' => N.pos xp')\n            (0%N)\n            xp)\n        x.\n\nLemma N_div2_eq : forall x,\n    N_div2 x = N.div2 x.\ndestruct x; try destruct p; simpl; try reflexivity.\nQed.\n\n\nDefinition Pos_shiftr (x : positive) (n : N) : positive :=\n    N_rect _\n        x\n        (fun n' => Pos_iter Pos_div2 x n')\n        n.\n\nLemma Pos_shiftr_eq : forall n x,\n    Pos_shiftr x n = Pos.shiftr x n.\ndestruct n; intros; simpl; try reflexivity.\n- rewrite <- Pos_iter_eq.\n  apply Pos_iter_ext. apply Pos_div2_eq.\nQed.\n\nDefinition N_shiftr (x b : N) : N :=\n    N_rect _\n        (x)\n        (fun bp => Pos_iter N_div2 x bp)\n        b.\n\nLemma N_shiftr_eq : forall b x,\n    N_shiftr x b = N.shiftr x b.\ninduction b; intros; simpl; try reflexivity.\n- rewrite <- Pos_iter_eq.\n  apply Pos_iter_ext. apply N_div2_eq.\nQed.\n\n\nDefinition N_ones b := N_pred (N_shiftl 1 b).\n\nLemma N_ones_eq : forall b,\n    N_ones b = N.ones b.\nintros. unfold N_ones.\nrewrite N_pred_eq, N_shiftl_eq. reflexivity.\nQed.\n\n\nDefinition N_lnot a n := N_lxor a (N_ones n).\n\nLemma N_lnot_eq : forall a n,\n    N_lnot a n = N.lnot a n.\nintros. unfold N_lnot.\nrewrite N_lxor_eq, N_ones_eq. reflexivity.\nQed.\n\n\n\n\nDefinition mask w z := N_land z (N_ones w).\n\nLemma mask_eq : forall w z,\n    mask w z = SHA256_N.mask w z.\nintros. unfold mask.\nrewrite N_land_eq, N_ones_eq. reflexivity.\nQed.\n\nDefinition trunc z := mask 32 z.\n\nLemma trunc_eq : forall z,\n    trunc z = SHA256_N.trunc z.\nintros. unfold trunc.\nrewrite mask_eq. reflexivity.\nQed.\n\n\nDefinition t_add x y := trunc (N_add x y).\n\nLemma t_add_eq : forall x y,\n    t_add x y = SHA256_N.t_add x y.\nintros. unfold t_add.\nrewrite trunc_eq, N_add_eq. reflexivity.\nQed.\n\nDefinition t_and x y := trunc (N_land x y).\nDefinition t_or x y := trunc (N_lor x y).\nDefinition t_xor x y := trunc (N_lxor x y).\nDefinition t_not x := trunc (N_lnot x 32).\n\nLemma t_and_eq : forall x y,\n    t_and x y = SHA256_N.t_and x y.\nintros. unfold t_and.\nrewrite trunc_eq, N_land_eq. reflexivity.\nQed.\n\nLemma t_or_eq : forall x y,\n    t_or x y = SHA256_N.t_or x y.\nintros. unfold t_or.\nrewrite trunc_eq, N_lor_eq. reflexivity.\nQed.\n\nLemma t_xor_eq : forall x y,\n    t_xor x y = SHA256_N.t_xor x y.\nintros. unfold t_xor.\nrewrite trunc_eq, N_lxor_eq. reflexivity.\nQed.\n\nLemma t_not_eq : forall x,\n    t_not x = SHA256_N.t_not x.\nintros. unfold t_not.\nrewrite trunc_eq, N_lnot_eq. reflexivity.\nQed.\n\nDefinition t_shiftl x b := trunc (N_shiftl x b).\nDefinition Shr b x := trunc (N_shiftr x b).\n\nLemma t_shiftl_eq : forall x b,\n    t_shiftl x b = SHA256_N.t_shiftl x b.\nintros. unfold t_shiftl.\nrewrite trunc_eq, N_shiftl_eq. reflexivity.\nQed.\n\nLemma Shr_eq : forall x b,\n    Shr x b = SHA256_N.Shr x b.\nintros. unfold Shr.\nrewrite trunc_eq, N_shiftr_eq. reflexivity.\nQed.\n\n\nDefinition wordlist_to_bytelist (l : list N) : list N :=\n    list_rect (fun _ => list N)\n        ([])\n        (fun w l IHl =>\n            trunc (Shr 24 w) ::\n            trunc (t_and (Shr 16 w) 255) ::\n            trunc (t_and (Shr 8 w) 255) ::\n            trunc (t_and w 255) ::\n            IHl)\n        l.\n\nLemma wordlist_to_bytelist_eq : forall l,\n    wordlist_to_bytelist l = SHA256_N.wordlist_to_bytelist l.\ninduction l; cbn [wordlist_to_bytelist list_rect].\n- reflexivity.\n- fold (wordlist_to_bytelist l). rewrite IHl.\n  rewrite 4 trunc_eq, 3 Shr_eq, 3 t_and_eq.\n  reflexivity.\nQed.\n\n\nDefinition bytes_to_word (a b c d : N) : N :=\n    t_or (t_or (t_or\n        (t_shiftl (trunc a) 24)\n        (t_shiftl (trunc b) 16))\n        (t_shiftl (trunc c) 8))\n        (trunc d).\n\nLemma bytes_to_word_eq : forall a b c d,\n    bytes_to_word a b c d = SHA256_N.bytes_to_word a b c d.\nintros. unfold bytes_to_word.\nrewrite 4 trunc_eq, 3 t_shiftl_eq, 3 t_or_eq. reflexivity.\nQed.\n\n\nFixpoint pair_up'0 {A} (l : list A) (first : option A) : list (A * A) :=\n    match l with\n    | [] => []\n    | y :: l' =>\n            match first with\n            | None => pair_up'0 l' (Some y)\n            | Some x => (x, y) :: pair_up'0 l' None\n            end\n    end.\n\nDefinition pair_up0 {A} (l : list A) : list (A * A) :=\n    pair_up'0 l None.\n\nFixpoint bytelist_to_wordlist'0 (l : list ((N * N) * (N * N))) : list N :=\n    match l with\n    | [] => []\n    | ((a, b), (c, d)) :: l =>\n            bytes_to_word a b c d :: bytelist_to_wordlist'0 l\n    end.\n\nDefinition bytelist_to_wordlist0 (l : list N) : list N :=\n    bytelist_to_wordlist'0 (pair_up0 (pair_up0 l)).\n\nLemma bytelist_to_wordlist0_eq : forall l,\n    bytelist_to_wordlist0 l = SHA256_N.bytelist_to_wordlist l.\nfix go 1.\nintros.\ndestruct l as [| a [| b [| c [| d l ] ] ] ]; simpl; try reflexivity.\ncbn [ bytelist_to_wordlist'0 bytelist_to_wordlist0 pair_up0 pair_up'0 ].\nrewrite bytes_to_word_eq.\nfold (pair_up0 l). fold (pair_up0 (pair_up0 l)).\nfold (bytelist_to_wordlist0 l).  rewrite (go l).\nreflexivity.\nQed.\n\nDefinition pair_up' {A} (l : list A) (first : option A) : list (A * A) :=\n    list_rect (fun _ => option A -> unit -> list (A * A))\n        (fun first => fun dummy => [])\n        (fun y l' IHl => fun first =>\n            option_rect (fun _ => unit -> list (A * A))\n                (fun x => fun dummy => (x, y) :: IHl None dummy)\n                (fun dummy => IHl (Some y) dummy)\n                first)\n        l first tt.\n\nLemma pair_up'_eq : forall {A} (l : list A) first,\n    pair_up' l first = pair_up'0 l first.\ninduction l; destruct first; simpl; try reflexivity.\n- unfold pair_up'. simpl. fold (pair_up' l None).\n  rewrite IHl. reflexivity.\n- unfold pair_up'. simpl. fold (pair_up' l (Some a)).\n  rewrite IHl. reflexivity.\nQed.\n\nDefinition pair_up {A} (l : list A) : list (A * A) :=\n    list_rect (fun _ => option A -> unit -> list (A * A))\n        (fun first dummy => [])\n        (fun y l' IHl => fun first =>\n            option_rect (fun _ => unit -> list (A * A))\n                (fun x dummy => (x, y) :: IHl None dummy)\n                (fun dummy => IHl (Some y) dummy)\n                first)\n        l None tt.\n\nLemma pair_up_eq : forall {A} (l : list A),\n    pair_up l = pair_up0 l.\nintros.\nchange (pair_up l) with (pair_up' l None).\nchange (pair_up0 l) with (pair_up'0 l None).\napply pair_up'_eq.\nQed.\n\nDefinition bytelist_to_wordlist' (l : list ((N * N) * (N * N))) : list N :=\n    list_rect (fun _ => list N)\n        ([])\n        (fun abcd l IHl =>\n            prod_rect (fun _ => list N) (fun ab cd =>\n            prod_rect (fun _ => list N) (fun a b =>\n            prod_rect (fun _ => list N) (fun c d =>\n                bytes_to_word a b c d :: IHl\n            ) cd) ab) abcd)\n        l.\n\nLemma bytelist_to_wordlist'_eq : forall l,\n    bytelist_to_wordlist' l = bytelist_to_wordlist'0 l.\ninduction l; simpl; try reflexivity.\nQed.\n\nDefinition bytelist_to_wordlist (l : list N) : list N :=\n    bytelist_to_wordlist' (pair_up (pair_up l)).\n\nLemma bytelist_to_wordlist_eq : forall l,\n    bytelist_to_wordlist l = SHA256_N.bytelist_to_wordlist l.\ninduction l; rewrite <- bytelist_to_wordlist0_eq; simpl; try reflexivity.\nunfold bytelist_to_wordlist, bytelist_to_wordlist0.\nrewrite bytelist_to_wordlist'_eq, 2 pair_up_eq.\nreflexivity.\nQed.\n\n\nDefinition Pos_succ (x : positive) : positive :=\n    positive_rect _\n        (fun x' IHx => IHx~0)\n        (fun x' IHx => x'~1)\n        (2)\n        x.\n\nLemma Pos_succ_eq : forall x,\n    Pos_succ x = Pos.succ x.\ninduction x; simpl; try rewrite IHx; reflexivity.\nQed.\n\nDefinition Pos_of_succ_nat (x : nat) : positive :=\n    nat_rect _\n        (1)\n        (fun x IHx => Pos_succ IHx)\n        x.\n\nLemma Pos_of_succ_nat_eq : forall x,\n    Pos_of_succ_nat x = Pos.of_succ_nat x.\ninduction x; simpl; try reflexivity.\nQed.\n\nDefinition N_succ (x : N) : N :=\n    N_rect _\n        (1%N)\n        (fun xp => N.pos (Pos_succ xp))\n        x.\n\nLemma N_succ_eq : forall x,\n    N_succ x = N.succ x.\ninduction x; simpl; try reflexivity.\nQed.\n\n\nFixpoint Nlength0 {A} (l : list A) : N :=\n    match l with\n    | [] => 0%N\n    | _ :: l' => N_succ (Nlength0 l')\n    end.\n\nLemma Nlength0_eq : forall {A} (l : list A),\n    Nlength0 l = Z.to_N (Zlength l).\ninduction l; simpl; try reflexivity.\n- rewrite N_succ_eq. rewrite IHl.\n  rewrite <- Z2N.inj_succ. f_equal.\n  rewrite 2 Zlength_correct. rewrite <- Nat2Z.inj_succ. reflexivity.\n    { rewrite Zlength_correct. apply Nat2Z.is_nonneg. }\nQed.\n\nDefinition Nlength {A} (l : list A) : N :=\n    list_rect _\n        (0%N)\n        (fun x l' IHl => N_succ IHl)\n        l.\n\nLemma Nlength_eq : forall {A} (l : list A),\n    Nlength l = Z.to_N (Zlength l).\ninduction l; intros; try rewrite <- Nlength0_eq; try reflexivity.\n- rewrite <- Nlength0_eq in IHl. simpl. congruence.\nQed.\n\n\nDefinition Pos_to_nat (x : positive) : nat :=\n    Pos_iter (fun n => S n) 0%nat x.\n\nLemma Pos_to_nat_eq : forall x,\n    Pos_to_nat x = Pos.to_nat x.\ninduction x using Pos.peano_ind; simpl; try reflexivity.\n- unfold Pos_to_nat in *. rewrite Pos_iter_eq. rewrite Pos_iter_eq in IHx.\n  rewrite Pos.iter_succ.  rewrite Pos2Nat.inj_succ. congruence.\nQed.\n\nDefinition N_to_nat (x : N) : nat :=\n    N_rect _\n        (0%nat)\n        (fun xp => Pos_to_nat xp)\n        x.\n\nLemma N_to_nat_eq : forall x,\n    N_to_nat x = N.to_nat x.\ndestruct x; simpl; try rewrite Pos_to_nat_eq; reflexivity.\nQed.\n\n\nDefinition List_repeat {A} (x : A) (n : nat) : list A :=\n    nat_rect _\n        ([])\n        (fun n' IHn => x :: IHn)\n        n.\n\nLemma List_repeat_eq : forall {A} (x : A) n,\n    List_repeat x n = List.repeat x n.\ninduction n; simpl; congruence.\nQed.\n\n\nDefinition List_app {A} (xs ys : list A) : list A :=\n    list_rect _\n        (ys)\n        (fun x xs IHxs => x :: IHxs)\n        xs.\n\nLemma List_app_eq : forall {A} (xs ys : list A),\n    List_app xs ys = List.app xs ys.\ninduction xs; simpl; congruence.\nQed.\n\n\nDefinition generate_and_pad msg :=\n    (fun n =>\n    (fun pad_amount =>\n    (List_app\n        (bytelist_to_wordlist\n            (List_app msg\n            (List_app [128%N]\n                (List_repeat 0%N (N_to_nat pad_amount)))))\n        ([trunc (N_shiftr (N_shiftl n 3) 32);\n          trunc (N_shiftl n 3)]))\n    ) (* pad-amount *) (N_land (N_add 1 (N_lnot (N_land (N_add n 9) 63) 6)) 63)\n    ) (* N *) (Nlength msg).\n\nLemma generate_and_pad_eq : forall msg,\n    generate_and_pad msg = SHA256_N.generate_and_pad msg.\nintros. unfold generate_and_pad.\nrewrite bytelist_to_wordlist_eq, 3 List_app_eq.\nrewrite List_repeat_eq, N_to_nat_eq, 2 N_land_eq, 2 N_add_eq, N_lnot_eq, Nlength_eq.\nrewrite 2 trunc_eq, N_shiftl_eq, N_shiftr_eq.\nrewrite N.shiftl_mul_pow2, N.shiftr_div_pow2.\nreflexivity.\nQed.\n\nLemma generate_and_pad_length : forall msg,\n    (length (generate_and_pad msg) mod 16 = 0)%nat.\nintros.\nrewrite generate_and_pad_eq.\napply SHA256_N.generate_and_pad_length.\nQed.\n\n\nDefinition nthi_test n :=\n    (nat_rect _ (fun dummy => 10)\n    (fun n _ dummy => nat_rect _ (fun dummy => 20)\n    (fun n _ dummy => nat_rect _ (fun dummy => 30)\n    (fun n _ dummy => nat_rect _ (fun dummy => 40)\n\n    (fun n _ dummy => 0) n dummy) n dummy) n dummy) n tt)%Z.\n\n\n(*\nDefinition nthi_K256 n :=\n    (nat_rect _ (fun dummy => 1116352408)\n    (fun n _ dummy => nat_rect _ (fun dummy => 1899447441)\n    (fun n _ dummy => nat_rect _ (fun dummy => 3049323471)\n    (fun n _ dummy => nat_rect _ (fun dummy => 3921009573)\n\n    (fun n _ dummy => nat_rect _ (fun dummy => 961987163)\n    (fun n _ dummy => nat_rect _ (fun dummy => 1508970993)\n    (fun n _ dummy => nat_rect _ (fun dummy => 2453635748)\n    (fun n _ dummy => nat_rect _ (fun dummy => 2870763221)\n\n    (fun n _ dummy => nat_rect _ (fun dummy => 3624381080)\n    (fun n _ dummy => nat_rect _ (fun dummy => 310598401)\n    (fun n _ dummy => nat_rect _ (fun dummy => 607225278)\n    (fun n _ dummy => nat_rect _ (fun dummy => 1426881987)\n\n    (fun n _ dummy => nat_rect _ (fun dummy => 1925078388)\n    (fun n _ dummy => nat_rect _ (fun dummy => 2162078206)\n    (fun n _ dummy => nat_rect _ (fun dummy => 2614888103)\n    (fun n _ dummy => nat_rect _ (fun dummy => 3248222580)\n\n    (fun n _ dummy => nat_rect _ (fun dummy => 3835390401)\n    (fun n _ dummy => nat_rect _ (fun dummy => 4022224774)\n    (fun n _ dummy => nat_rect _ (fun dummy => 264347078)\n    (fun n _ dummy => nat_rect _ (fun dummy => 604807628)\n\n    (fun n _ dummy => nat_rect _ (fun dummy => 770255983)\n    (fun n _ dummy => nat_rect _ (fun dummy => 1249150122)\n    (fun n _ dummy => nat_rect _ (fun dummy => 1555081692)\n    (fun n _ dummy => nat_rect _ (fun dummy => 1996064986)\n\n    (fun n _ dummy => nat_rect _ (fun dummy => 2554220882)\n    (fun n _ dummy => nat_rect _ (fun dummy => 2821834349)\n    (fun n _ dummy => nat_rect _ (fun dummy => 2952996808)\n    (fun n _ dummy => nat_rect _ (fun dummy => 3210313671)\n\n    (fun n _ dummy => nat_rect _ (fun dummy => 3336571891)\n    (fun n _ dummy => nat_rect _ (fun dummy => 3584528711)\n    (fun n _ dummy => nat_rect _ (fun dummy => 113926993)\n    (fun n _ dummy => nat_rect _ (fun dummy => 338241895)\n\n    (fun n _ dummy => nat_rect _ (fun dummy => 666307205)\n    (fun n _ dummy => nat_rect _ (fun dummy => 773529912)\n    (fun n _ dummy => nat_rect _ (fun dummy => 1294757372)\n    (fun n _ dummy => nat_rect _ (fun dummy => 1396182291)\n\n    (fun n _ dummy => nat_rect _ (fun dummy => 1695183700)\n    (fun n _ dummy => nat_rect _ (fun dummy => 1986661051)\n    (fun n _ dummy => nat_rect _ (fun dummy => 2177026350)\n    (fun n _ dummy => nat_rect _ (fun dummy => 2456956037)\n\n    (fun n _ dummy => nat_rect _ (fun dummy => 2730485921)\n    (fun n _ dummy => nat_rect _ (fun dummy => 2820302411)\n    (fun n _ dummy => nat_rect _ (fun dummy => 3259730800)\n    (fun n _ dummy => nat_rect _ (fun dummy => 3345764771)\n\n    (fun n _ dummy => nat_rect _ (fun dummy => 3516065817)\n    (fun n _ dummy => nat_rect _ (fun dummy => 3600352804)\n    (fun n _ dummy => nat_rect _ (fun dummy => 4094571909)\n    (fun n _ dummy => nat_rect _ (fun dummy => 275423344)\n\n    (fun n _ dummy => nat_rect _ (fun dummy => 430227734)\n    (fun n _ dummy => nat_rect _ (fun dummy => 506948616)\n    (fun n _ dummy => nat_rect _ (fun dummy => 659060556)\n    (fun n _ dummy => nat_rect _ (fun dummy => 883997877)\n\n    (fun n _ dummy => nat_rect _ (fun dummy => 958139571)\n    (fun n _ dummy => nat_rect _ (fun dummy => 1322822218)\n    (fun n _ dummy => nat_rect _ (fun dummy => 1537002063)\n    (fun n _ dummy => nat_rect _ (fun dummy => 1747873779)\n\n    (fun n _ dummy => nat_rect _ (fun dummy => 1955562222)\n    (fun n _ dummy => nat_rect _ (fun dummy => 2024104815)\n    (fun n _ dummy => nat_rect _ (fun dummy => 2227730452)\n    (fun n _ dummy => nat_rect _ (fun dummy => 2361852424)\n\n    (fun n _ dummy => nat_rect _ (fun dummy => 2428436474)\n    (fun n _ dummy => nat_rect _ (fun dummy => 2756734187)\n    (fun n _ dummy => nat_rect _ (fun dummy => 3204031479)\n    (fun n _ dummy => nat_rect _ (fun dummy => 3329325298)\n\n    (fun n _ dummy => 0)\n    n dummy) n dummy) n dummy) n dummy)  n dummy) n dummy) n dummy) n dummy)\n    n dummy) n dummy) n dummy) n dummy)  n dummy) n dummy) n dummy) n dummy)\n    n dummy) n dummy) n dummy) n dummy)  n dummy) n dummy) n dummy) n dummy)\n    n dummy) n dummy) n dummy) n dummy)  n dummy) n dummy) n dummy) n dummy)\n    n dummy) n dummy) n dummy) n dummy)  n dummy) n dummy) n dummy) n dummy)\n    n dummy) n dummy) n dummy) n dummy)  n dummy) n dummy) n dummy) n dummy)\n    n dummy) n dummy) n dummy) n dummy)  n dummy) n dummy) n dummy) n dummy)\n    n dummy) n dummy) n dummy) n dummy)  n dummy) n dummy) n dummy) n tt)%N.\n\nLemma nthi_K256_eq : forall n,\n    nthi_K256 n = SHA256_N.nthi SHA256_N.K256 n.\nrepeat (destruct n; try reflexivity).\nQed.\n*)\n\nDefinition nthi (l: list N) (t: nat) :=\n    list_rect (fun _ => nat -> unit -> N)\n        (fun t dummy => 0%N)\n        (fun x l IHl => fun t => nat_rect (fun _ => unit -> N)\n            (fun dummy => x)\n            (fun x' IHx => fun dummy => IHl x' dummy)\n            t)\n        l t tt.\n\nLemma nthi_eq : forall l t,\n    nthi l t = SHA256_N.nthi l t.\ninduction l; destruct t; simpl; try reflexivity.\n- unfold nthi. simpl. fold (nthi l t).\n  unfold SHA256_N.nthi. simpl. fold (SHA256_N.nthi l t).\n  apply IHl.\nQed.\n\n\nDefinition nthi_K256 t :=\n    nthi\n        [1116352408; 1899447441; 3049323471; 3921009573; \n          961987163; 1508970993; 2453635748; 2870763221; \n         3624381080;  310598401;  607225278; 1426881987; \n         1925078388; 2162078206; 2614888103; 3248222580; \n         3835390401; 4022224774;  264347078;  604807628; \n          770255983; 1249150122; 1555081692; 1996064986; \n         2554220882; 2821834349; 2952996808; 3210313671; \n         3336571891; 3584528711;  113926993;  338241895; \n          666307205;  773529912; 1294757372; 1396182291; \n         1695183700; 1986661051; 2177026350; 2456956037; \n         2730485921; 2820302411; 3259730800; 3345764771; \n         3516065817; 3600352804; 4094571909;  275423344; \n          430227734;  506948616;  659060556;  883997877; \n          958139571; 1322822218; 1537002063; 1747873779; \n         1955562222; 2024104815; 2227730452; 2361852424; \n         2428436474; 2756734187; 3204031479; 3329325298]%N\n    t.\n\nLemma nthi_K256_eq : forall n,\n    nthi_K256 n = SHA256_N.nthi SHA256_N.K256 n.\nrepeat (destruct n; try reflexivity).\nQed.\n\n\nDefinition Ch (x y z : N) : N :=\n    t_xor (t_and x y) (t_and (t_not x) z).\n\nLemma Ch_eq : forall x y z,\n    Ch x y z = SHA256_N.Ch x y z.\nintros. unfold Ch.\nrewrite t_xor_eq, 2 t_and_eq, t_not_eq.\nreflexivity.\nQed.\n\n\nDefinition Maj (x y z : N) : N :=\n    t_xor (t_xor (t_and x z) (t_and y z)) (t_and x y).\n\nLemma Maj_eq : forall x y z,\n    Maj x y z = SHA256_N.Maj x y z.\nintros. unfold Maj.\nrewrite 2 t_xor_eq, 3 t_and_eq.\nreflexivity.\nQed.\n\n\nDefinition Rotr (b x : N) :=\n    trunc (N_lor\n        (N_shiftr x b)\n        (N_shiftl x (N_add 1 (N_lnot b 5)))).\n\nLemma Rotr_eq : forall b x,\n    (b < 32)%N ->\n    Rotr b x = SHA256_N.Rotr b x.\nintros. unfold Rotr.\nrewrite trunc_eq, N_lor_eq, N_shiftr_eq, N_shiftl_eq, N_add_eq, N_lnot_eq.\nunfold SHA256_N.Rotr.\nf_equal. f_equal. f_equal.\n\ndestruct b; try reflexivity.\ndo 5 try destruct p; try reflexivity.\nall: destruct p; compute in H; try discriminate H.\nQed.\n\n\nDefinition Sigma_0 (x : N) : N :=\n    t_xor (t_xor (Rotr 2 x) (Rotr 13 x)) (Rotr 22 x).\nDefinition Sigma_1 (x : N) : N :=\n    t_xor (t_xor (Rotr 6 x) (Rotr 11 x)) (Rotr 25 x).\nDefinition sigma_0 (x : N) : N :=\n    t_xor (t_xor (Rotr 7 x) (Rotr 18 x)) (Shr 3 x).\nDefinition sigma_1 (x : N) : N :=\n    t_xor (t_xor (Rotr 17 x) (Rotr 19 x)) (Shr 10 x).\n\nLemma Sigma_0_eq : forall x,\n    Sigma_0 x = SHA256_N.Sigma_0 x.\nintros. unfold Sigma_0.\nrewrite 2 t_xor_eq, 3 Rotr_eq by reflexivity.\nreflexivity.\nQed.\n\nLemma Sigma_1_eq : forall x,\n    Sigma_1 x = SHA256_N.Sigma_1 x.\nintros. unfold Sigma_1.\nrewrite 2 t_xor_eq, 3 Rotr_eq by reflexivity.\nreflexivity.\nQed.\n\nLemma sigma_0_eq : forall x,\n    sigma_0 x = SHA256_N.sigma_0 x.\nintros. unfold sigma_0.\nrewrite 2 t_xor_eq, 2 Rotr_eq, Shr_eq by reflexivity.\nreflexivity.\nQed.\n\nLemma sigma_1_eq : forall x,\n    sigma_1 x = SHA256_N.sigma_1 x.\nintros. unfold sigma_1.\nrewrite 2 t_xor_eq, 2 Rotr_eq, Shr_eq by reflexivity.\nreflexivity.\nQed.\n\n\nDefinition lt (n m : nat) : bool :=\n    nat_rect (fun _ => nat -> unit -> bool)\n        (fun m => nat_rect (fun _ => unit -> bool)\n            (fun dummy => false)\n            (fun m' IHm dummy => true)\n            m)\n        (fun n' IHn => fun m => nat_rect (fun _ => unit -> bool)\n            (fun dummy => false)\n            (fun m IHm dummy => IHn m dummy)\n            m)\n        n m tt.\n\nLemma lt_correct : forall n m,\n    lt n m = true <-> (n < m)%nat.\ninduction n; destruct m; split; intros; simpl in *.\nall: try solve [discriminate | exfalso; omega].\nall: try solve [reflexivity].\nall: try solve [omega].\n- change (lt (S n) (S m)) with (lt n m) in *.\n  rewrite IHn in *. omega.\n- change (lt (S n) (S m)) with (lt n m).\n  rewrite IHn. omega.\nQed.\n\n\nDefinition List_length {A} (l : list A) : nat :=\n    list_rect _\n        0%nat\n        (fun _ _ IHl => S IHl)\n        l.\n\nLemma List_length_eq : forall {A} (l : list A),\n    List_length l = List.length l.\ninduction l; simpl; try congruence.\nQed.\n\n\nDefinition W' (M : nat -> N) (t : nat) : list N :=\n    nat_rect _\n        ([M 0])%nat\n        (fun t' IHt =>\n            bool_rect (fun _ => list N)\n                (M (S t') :: IHt)\n                (t_add (t_add (sigma_1 (nthi IHt 1)) (nthi IHt 6))\n                       (t_add (sigma_0 (nthi IHt 14)) (nthi IHt 15))\n                    :: IHt)\n                (lt (List_length IHt) 16))\n        t.\n\nLemma W'_length : forall M t,\n    length (W' M t) = S t.\ninduction t; simpl; try reflexivity.\ndestruct (lt _ 16); simpl; congruence.\nQed.\n\nLemma W'_nthi_S : forall M t i,\n    nthi (W' M (S t)) (S i) = nthi (W' M t) i.\nintros.\nsimpl. destruct (lt _ 16); simpl.\nall: cbn [nthi list_rect nat_rect].\nall: fold (nthi (W' M t) i).\nall: reflexivity.\nQed.\n\nLemma W'_eq : forall M M' t i,\n    (i <= t)%nat ->\n    (forall t, M t = M' t) ->\n    nthi (W' M t) i = SHA256_N.W M' (t - i).\ninduction t; induction i; intros0 Hi HM.\n\n- simpl. rewrite <- HM. reflexivity.\n\n- exfalso. omega.\n\n- rewrite Nat.sub_0_r.\n  destruct (lt_dec (S t) 16) as [Hlt | Hge].\n\n  + rewrite SHA256_N.W_unfold_last by omega.\n    rewrite <- lt_correct in Hlt.\n    simpl. rewrite W'_length, Hlt. simpl. cbn [nthi list_rect nat_rect].\n    eapply HM.\n\n  + replace (S t) with (16 + (S t - 16))%nat at 2 by omega.\n    rewrite SHA256_N.W_unfold.\n    remember (SHA256_N.t_add _ _) as rhs.\n\n    pose proof Hge as Hge'.\n    rewrite <- lt_correct in Hge'. destruct (lt _ _) eqn:Hlt; try congruence.\n    simpl. rewrite W'_length, Hlt. simpl.\n    cbn [nthi list_rect nat_rect].\n\n    rewrite 4 IHt; auto; try omega.\n    subst rhs.\n    rewrite 3 t_add_eq, sigma_1_eq, sigma_0_eq.\n    f_equal; f_equal; [ f_equal | | f_equal ]; f_equal; omega.\n\n- rewrite W'_nthi_S. replace (S t - S i)%nat with (t - i)%nat by omega.\n  eapply IHt. omega. auto.\nQed.\n\nDefinition W (M : nat -> N) (t : nat) : N :=\n    list_rect (fun _ => N)\n        0%N\n        (fun x _ _ => x)\n        (W' M t).\n\nLemma W_eq : forall M M' t,\n    (forall t, M t = M' t) ->\n    W M t = SHA256_N.W M' t.\nintros.\nreplace t with (t - 0)%nat at 2 by omega.\nerewrite <- W'_eq with (i := 0%nat); cycle 1.\n  { omega. }\n  { auto. }\nunfold W. destruct (W' M t); simpl; reflexivity.\nQed.\n\n\nDefinition registers := (N * N * N * N * N * N * N * N)%type.\n\n\nDefinition rnd_function (x : registers) (k : N) (w : N) : registers :=\n    prod_rect (fun _ => registers) (fun abcdefg h =>\n    prod_rect (fun _ => registers) (fun abcdef g =>\n    prod_rect (fun _ => registers) (fun abcde f =>\n    prod_rect (fun _ => registers) (fun abcd e =>\n    prod_rect (fun _ => registers) (fun abc d =>\n    prod_rect (fun _ => registers) (fun ab c =>\n    prod_rect (fun _ => registers) (fun a b =>\n        (t_add (t_add (t_add (t_add (t_add h (Sigma_1 e)) (Ch e f g)) k) w)\n               (t_add (Sigma_0 a) (Maj a b c)),\n         a, b, c,\n         t_add d (t_add (t_add (t_add (t_add h (Sigma_1 e)) (Ch e f g)) k) w),\n         e, f, g)\n    ) ab) abc) abcd) abcde) abcdef) abcdefg) x.\n\nLemma rnd_function_eq : forall x k w,\n    rnd_function x k w = SHA256_N.rnd_function x k w.\nintros.\ndestruct x as [[[[[[[a b] c] d] e] f] g] h].\nsimpl.\nrepeat rewrite t_add_eq.\nrewrite Sigma_1_eq, Ch_eq, Sigma_0_eq, Maj_eq.\nreflexivity.\nQed.\n\n\nDefinition Round (regs : registers) (M : nat -> N) (t : nat) : registers :=\n    nat_rect _\n        (rnd_function regs (nthi_K256 0) (W M 0))\n        (fun t' IHt => rnd_function IHt (nthi_K256 (S t')) (W M (S t')))\n        t.\n\nLemma Round_eq : forall regs M M' t,\n    (forall t, M t = M' t) ->\n    Round regs M t = SHA256_N.Round regs M' t.\ninduction t; intros0 HM; unfold Round; cbn [nat_rect].\n\n- rewrite rnd_function_eq. unfold W; simpl.\n  rewrite <- HM. reflexivity.\n\n- fold (Round regs M t). rewrite rnd_function_eq.\n  rewrite IHt by auto. rewrite nthi_K256_eq. erewrite W_eq by auto.\n  reflexivity.\nQed.\n\n\nDefinition hash_block (r : registers) (block : list N) : registers :=\n    prod_rect (fun _ => registers) (fun abcdefg0 h0 =>\n    prod_rect (fun _ => registers) (fun abcdef0 g0 =>\n    prod_rect (fun _ => registers) (fun abcde0 f0 =>\n    prod_rect (fun _ => registers) (fun abcd0 e0 =>\n    prod_rect (fun _ => registers) (fun abc0 d0 =>\n    prod_rect (fun _ => registers) (fun ab0 c0 =>\n    prod_rect (fun _ => registers) (fun a0 b0 =>\n    prod_rect (fun _ => registers) (fun abcdefg1 h1 =>\n    prod_rect (fun _ => registers) (fun abcdef1 g1 =>\n    prod_rect (fun _ => registers) (fun abcde1 f1 =>\n    prod_rect (fun _ => registers) (fun abcd1 e1 =>\n    prod_rect (fun _ => registers) (fun abc1 d1 =>\n    prod_rect (fun _ => registers) (fun ab1 c1 =>\n    prod_rect (fun _ => registers) (fun a1 b1 =>\n        (t_add a0 a1,\n         t_add b0 b1,\n         t_add c0 c1,\n         t_add d0 d1,\n         t_add e0 e1,\n         t_add f0 f1,\n         t_add g0 g1,\n         t_add h0 h1)\n    ) ab1) abc1) abcd1) abcde1) abcdef1) abcdefg1) (Round r (nthi block) 63)\n    ) ab0) abc0) abcd0) abcde0) abcdef0) abcdefg0) r.\n\nOpaque Round t_add nthi.\nOpaque SHA256_N.Round SHA256_N.t_add SHA256_N.nthi.\nLemma hash_block_eq : forall r block,\n    hash_block r block = SHA256_N.hash_block r block.\nintros.\ndestruct r as [[[[[[[a0 b0] c0] d0] e0] f0] g0] h0].\ncompute.\nerewrite Round_eq by eapply nthi_eq.\ndestruct (SHA256_N.Round _ _ _) as [[[[[[[a1 b1] c1] d1] e1] f1] g1] h1].\nrewrite 8 t_add_eq. reflexivity.\nQed.\nTransparent Round t_add nthi.\nTransparent SHA256_N.Round SHA256_N.t_add SHA256_N.nthi.\n\n\nDefinition pairs_to_list_16 x : list N :=\n    prod_rect (fun _ => list N) (fun x0 x1 =>\n\n    prod_rect (fun _ => list N) (fun x00 x01 =>\n    prod_rect (fun _ => list N) (fun x10 x11 =>\n\n    prod_rect (fun _ => list N) (fun x000 x001 =>\n    prod_rect (fun _ => list N) (fun x010 x011 =>\n    prod_rect (fun _ => list N) (fun x100 x101 =>\n    prod_rect (fun _ => list N) (fun x110 x111 =>\n\n    prod_rect (fun _ => list N) (fun x0000 x0001 =>\n    prod_rect (fun _ => list N) (fun x0010 x0011 =>\n    prod_rect (fun _ => list N) (fun x0100 x0101 =>\n    prod_rect (fun _ => list N) (fun x0110 x0111 =>\n    prod_rect (fun _ => list N) (fun x1000 x1001 =>\n    prod_rect (fun _ => list N) (fun x1010 x1011 =>\n    prod_rect (fun _ => list N) (fun x1100 x1101 =>\n    prod_rect (fun _ => list N) (fun x1110 x1111 =>\n\n    [x0000; x0001; x0010; x0011;\n     x0100; x0101; x0110; x0111;\n     x1000; x1001; x1010; x1011;\n     x1100; x1101; x1110; x1111]\n\n    ) x111) x110) x101) x100) x011) x010) x001) x000\n    ) x11) x10) x01) x00\n    ) x1) x0\n    ) x.\n\n(* used for verification only *)\nDefinition hash_blocks' (r : registers) msg_blocks : registers :=\n    list_rect _\n        (fun r => r)\n        (fun block msg IHmsg => fun r =>\n            IHmsg (hash_block r (pairs_to_list_16 block)))\n        msg_blocks r.\n\nDefinition hash_blocks (r : registers) (msg : list N) : registers :=\n    list_rect _\n        (fun r => r)\n        (fun block msg IHmsg => fun r =>\n            IHmsg (hash_block r (pairs_to_list_16 block)))\n        (pair_up (pair_up (pair_up (pair_up msg)))) r.\n\nLemma hash_blocks'_unfold_cons : forall r block blocks,\n    hash_blocks' r (block :: blocks) = hash_blocks' (hash_block r (pairs_to_list_16 block)) blocks.\nintros. reflexivity.\nQed.\n\nLemma pair_up_unfold_cons : forall {A} (x1 x2 : A) xs,\n    pair_up (x1 :: x2 :: xs) = (x1, x2) :: pair_up xs.\nintros. reflexivity.\nQed.\n\nLemma hash_blocks_eq : forall r msg,\n    (length msg mod 16 = 0)%nat ->\n    hash_blocks r msg = SHA256_N.hash_blocks r msg.\nintros0 Hlen.\nunfold hash_blocks. fold (hash_blocks' r (pair_up (pair_up (pair_up (pair_up msg))))).\nremember (pair_up _) as msg_p.\nrevert msg_p msg r Hlen Heqmsg_p. induction msg_p; intros.\n\n- do 16 try destruct msg as [| ?m0 msg ].\n  (* empty msg *)\n    { reflexivity. }\n\n  (* uneven-length messages *)\n    all: try solve [exfalso; simpl in Hlen; discriminate Hlen].\n\n  (* impossible - nil = cons *)\n    { exfalso. repeat rewrite pair_up_unfold_cons in Heqmsg_p. discriminate. }\n\n- rewrite hash_blocks'_unfold_cons.\n\n  do 16 try destruct msg as [| ?m0 msg ].\n  (* empty msg *)\n    { discriminate Heqmsg_p. }\n  (* uneven-length messages *)\n    all: try solve [exfalso; simpl in Hlen; discriminate Hlen].\n\n  (* remaining case: nonempty message of appropriate length *)\n  repeat rewrite pair_up_unfold_cons in Heqmsg_p.\n  change (length _) with (16 + length msg)%nat in Hlen.\n  invc Heqmsg_p. simpl.\n  rewrite hash_block_eq.\n  eapply IHmsg_p; eauto.\n\n  + rewrite Nat.add_mod in Hlen by discriminate.\n    change (16 mod 16)%nat with (0 mod 16)%nat in Hlen.\n    rewrite <- Nat.add_mod in Hlen by discriminate.\n    exact Hlen.\nQed.\n\n\nDefinition SHA_256 (str : list N) : list N :=\n    prod_rect (fun _ => list N) (fun abcdefg h =>\n    prod_rect (fun _ => list N) (fun abcdef g =>\n    prod_rect (fun _ => list N) (fun abcde f =>\n    prod_rect (fun _ => list N) (fun abcd e =>\n    prod_rect (fun _ => list N) (fun abc d =>\n    prod_rect (fun _ => list N) (fun ab c =>\n    prod_rect (fun _ => list N) (fun a b =>\n    wordlist_to_bytelist [a; b; c; d; e; f; g; h]\n    ) ab) abc) abcd) abcde) abcdef) abcdefg)\n    (hash_blocks \n        (* init_registers *)\n        (1779033703, 3144134277, 1013904242, 2773480762,\n         1359893119, 2600822924,  528734635, 1541459225)%N\n     (generate_and_pad str)).\n\nLemma SHA_256_eq : forall str,\n    SHA_256 str = SHA256_N.SHA_256 str.\nintros.\nunfold SHA_256.\nrewrite generate_and_pad_eq.\nrewrite hash_blocks_eq.\nfold SHA256_N.init_registers.\n\nunfold SHA256_N.SHA_256.\ndestruct (SHA256_N.hash_blocks _ _) as [[[[[[[a b] c] d] e] f] g] h].\ncbn [prod_rect]. apply wordlist_to_bytelist_eq.\napply SHA256_N.generate_and_pad_length.\nQed.\n", "meta": {"author": "uwplse", "repo": "oeuf", "sha": "f3e4d236465ba872d1f1b8229548fa0edf8f7a3f", "save_path": "github-repos/coq/uwplse-oeuf", "path": "github-repos/coq/uwplse-oeuf/oeuf-f3e4d236465ba872d1f1b8229548fa0edf8f7a3f/demos/sha256/SHA256_elim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2640504683001495}}
{"text": "Require Import Poulet4.P4light.Syntax.P4defs.\nRequire Import Poulet4.P4light.Semantics.Semantics.\nRequire Import ProD3.core.Core.\nRequire Import Poulet4.P4light.Architecture.Tofino.\nRequire Import ProD3.core.Tofino.\nRequire Import ProD3.examples.count.common.\nRequire Import ProD3.examples.count.ModelRepr.\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\"].\n\nOpen Scope func_spec.\n\nDefinition regact_counter_apply_body :=\n  ltac:(auto_regact ge am_ge (p ++ [\"regact_counter\"])).\n\nDefinition regact_counter_execute_body :=\n  ltac:(build_execute_body ge regact_counter_apply_body).\n\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply regact_counter_execute_body) : func_specs.\n\nDefinition counter_act_fundef :=\n  ltac:(get_fd [\"SwitchIngress\"; \"act_counter\"] ge).\n\nDefinition counter_act_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD (Some [[\"ig_md\"]]) [p]\n    WITH (counter : Z),\n      PRE\n        (ARG []\n        (MEM [([\"ig_md\"], ValBaseStruct [(\"num_pkt\", P4Bit_ 32)])]\n        (EXT [counter_repr p counter])))\n      POST\n        (ARG_RET [] ValBaseNull\n        (MEM [([\"ig_md\"], ValBaseStruct [(\"num_pkt\", P4Bit 32 (counter + 1))])]\n        (EXT [counter_repr p (counter + 1)]))).\n\nLemma counter_act_body:\n  func_sound ge counter_act_fundef nil counter_act_spec.\nProof.\n  start_function.\n  unfold counter_repr, counter_reg_repr.\n  normalize_EXT.\n  Intros_prop. simpl.\n  step_call regact_counter_execute_body;\n    [entailer | list_solve | lia | reflexivity |].\n  step.\n  entailer.\n  repeat intro. hnf. simpl. lia.\nQed.\n\nDefinition tbl_counter_fd :=\n  ltac:(get_fd [\"SwitchIngress\"; \"tbl_counter\"; \"apply\"] ge).\n\nDefinition tbl_counter_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD (Some [[\"ig_md\"]]) [p]\n    WITH (counter : Z),\n      PRE\n        (ARG []\n        (MEM [([\"ig_md\"], ValBaseStruct [(\"num_pkt\", P4Bit_ 32)])]\n        (EXT [counter_repr p counter])))\n      POST\n        (EX retv,\n        (ARG_RET [] retv\n        (MEM [([\"ig_md\"], ValBaseStruct [(\"num_pkt\", P4Bit 32 (counter + 1))])]\n        (EXT [counter_repr p (counter + 1)]))))%arg_ret_assr.\n\nLemma tbl_counter_body:\n  func_sound ge tbl_counter_fd nil tbl_counter_spec.\nProof.\n  start_function.\n  table_action counter_act_body.\n  { entailer. }\n  { entailer. }\nQed.\n\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_counter_body) : func_specs.\n\nDefinition Ingress_fd :=\n  ltac:(get_fd [\"SwitchIngress\"; \"apply\"] ge).\n\nDefinition header_t: P4Type := ltac:(get_type \"header_t\" ge).\nDefinition metadata_t: P4Type := ltac:(get_type \"metadata_t\" ge).\nDefinition ingress_intrinsic_metadata_t: P4Type :=\n  ltac:(get_type \"ingress_intrinsic_metadata_t\" ge).\nDefinition ingress_intrinsic_metadata_from_parser_t: P4Type :=\n  ltac:(get_type \"ingress_intrinsic_metadata_from_parser_t\" ge).\nDefinition ingress_intrinsic_metadata_for_deparser_t: P4Type :=\n  ltac:(get_type \"ingress_intrinsic_metadata_for_deparser_t\" ge).\nDefinition ingress_intrinsic_metadata_for_tm_t: P4Type :=\n  ltac:(get_type \"ingress_intrinsic_metadata_for_tm_t\" ge).\n\nDefinition Ingress_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD None [p]\n    WITH (counter : Z) (dprsr_md: Sval),\n      PRE\n        (ARG [force ValBaseNull (uninit_sval_of_typ None header_t);\n              force ValBaseNull (uninit_sval_of_typ None metadata_t);\n              force ValBaseNull (uninit_sval_of_typ None ingress_intrinsic_metadata_t);\n              force ValBaseNull (uninit_sval_of_typ None ingress_intrinsic_metadata_from_parser_t);\n              dprsr_md;\n              force ValBaseNull (uninit_sval_of_typ None ingress_intrinsic_metadata_for_tm_t)\n           ]\n        (MEM []\n        (EXT [counter_repr p counter])))\n      POST\n        (ARG_RET [force ValBaseNull (uninit_sval_of_typ None header_t);\n                  ValBaseStruct [(\"num_pkt\", P4Bit 32 (counter + 1))];\n                  if (Z.eqb ((counter + 1) mod 1024) 0) then\n                    (update \"digest_type\" (P4Bit 3 1) dprsr_md)\n                  else dprsr_md;\n                  force ValBaseNull (uninit_sval_of_typ None ingress_intrinsic_metadata_for_tm_t)\n         ] ValBaseNull\n        (MEM []\n        (EXT [counter_repr p (counter + 1)]))).\n\nLemma Ingress_body:\n  func_sound ge Ingress_fd nil Ingress_spec.\nProof.\n  start_function.\n  step_call tbl_counter_body.\n  { entailer. }\n  Intros _.\n  step_if; simpl abs_eq in H;\n    replace (Pos.to_nat 9) with (N.to_nat (10 - 1)) in H by lia;\n    rewrite bitstring_slice_lower_bit in H by lia; rewrite abs_eq_bit in H;\n    unfold P4Arith.BitArith.mod_bound, P4Arith.BitArith.upper_bound in H;\n    rewrite Zmod_0_l in H; change (2 ^ Z.of_N 10) with 1024 in H; simpl in H;\n    destruct ((counter + 1) mod 1024 =? 0); try now exfalso.\n  - step. step. step. entailer.\n  - step. step. entailer.\nQed.\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/count/verif_counter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2639943418723695}}
{"text": "From iris.base_logic.lib Require Export invariants.\nFrom aneris.aneris_lang Require Import lang tactics proofmode.\n\nDefinition coin_flip : val :=\n  λ: <>, let: \"l\" := ref #true in Fork (\"l\" <- #false);; !\"l\".\n\nSection proof.\n  Context `{!anerisG Mdl Σ}.\n\n  Lemma coin_flip_spec ip :\n    {{{ True }}} coin_flip #() @[ip] {{{ (b : bool), RET #b; True }}}.\n  Proof.\n    iIntros (Φ) \"_ HΦ\".\n    wp_lam. wp_alloc l as \"Hl\". wp_let.\n    pose proof (nroot .@ \"rnd\") as rndN.\n    iMod (inv_alloc rndN _ (∃ (b : bool), l ↦[ip] #b)%I with \"[Hl]\") as \"#Hinv\";\n      first by eauto.\n    wp_apply aneris_wp_fork; iSplitL.\n    - iModIntro. wp_seq. iInv rndN as (?) \"?\". wp_load.\n      iSplitR \"HΦ\"; first by eauto. by iApply \"HΦ\".\n    - iModIntro. iInv rndN as (?) \"?\". wp_store; eauto.\n  Qed.\n\nEnd 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/aneris_lang/lib/coin_flip.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.26399433522413707}}
{"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 type_sys.\n\n\n\nLemma defines_only_universes_eq_L :\n  forall ts : candidate-type-system,\n  forall T T1 T2 eq1 eq2,\n    type_system ts\n    -> defines_only_universes ts\n    -> ts T T2 eq2\n    -> per_eq (close ts) T T1 eq1\n    -> False.\nProof.\n  intros.\n  allunfold defines_only_universes.\n  assert (ts T T eq2) by (apply type_system_type_mem with (T' := T2); allunfold type_system; sp).\n  apply_in_hyp p; close_diff.\nQed.\n\nLemma defines_only_universes_eq_LR :\n  forall ts : candidate-type-system,\n  forall T T1 T2 eq1 eq2,\n    type_system ts\n    -> defines_only_universes ts\n    -> ts T2 T eq2\n    -> per_eq (close ts) T T1 eq1\n    -> False.\nProof.\n  intros.\n  allunfold defines_only_universes.\n  assert (ts T T eq2) by (apply type_system_type_mem with (T' := T2); allunfold type_system; sp).\n  apply_in_hyp p; close_diff.\nQed.\n\nLemma defines_only_universes_eq_R :\n  forall ts : candidate-type-system,\n  forall T T1 T2 eq1 eq2,\n    type_system ts\n    -> defines_only_universes ts\n    -> ts T T2 eq2\n    -> per_eq (close ts) T1 T eq1\n    -> False.\nProof.\n  intros.\n  allunfold defines_only_universes.\n  assert (ts T T eq2) by (apply type_system_type_mem with (T' := T2); allunfold type_system; sp).\n  apply_in_hyp p; close_diff.\nQed.\n\nLemma defines_only_universes_eq_RR :\n  forall ts : candidate-type-system,\n  forall T T1 T2 eq1 eq2,\n    type_system ts\n    -> defines_only_universes ts\n    -> ts T2 T eq2\n    -> per_eq (close ts) T1 T eq1\n    -> False.\nProof.\n  intros.\n  allunfold defines_only_universes.\n  assert (ts T T eq2) by (apply type_system_type_mem with (T' := T2); allunfold type_system; sp).\n  apply_in_hyp p; close_diff.\nQed.\n\n\nLemma close_type_system_eq :\n  forall ts : candidate-type-system,\n    type_system ts\n    -> is_type_system (per_eq ts).\nProof.\n  introv tysys.\n  unfold is_type_system; introv pereq.\n  unfold per_eq in pereq; exrepnd.\n  unfold type_system_props; dands.\n\n  - unfold uniquely_valued_body.\n    introv pereq'.\n    allunfold per_eq; exrepnd.\n    spcast; repeat computes_to_eqval.\n    unfold eq_term_equals; introv.\n    rw pereq0.\n    rw pereq'0.\n    onedts uv tye tys tyt tyvr tes tet tevr.\n    generalize (uv A B eqa eqa0); intro k; repeat (dest_imp k hyp).\n    rw k; sp.\n\n  - unfold type_extensionality_body; introv teq.\n    unfold per_eq.\n    exists A B a1 a2 b1 b2 eqa; sp.\n    rw <- teq.\n    rw pereq0; sp.\n\n  - unfold type_symmetric_body; introv.\n    unfold per_eq.\n\n    generalize (type_system_ts_refl ts A B eqa); introv r;\n    repeat (dest_imp r hyp); repnd.\n\n    assert (term_equality_symmetric eqa)\n      as eqs\n        by (onedts uv tye tys tyt tyvr tes tet tevr; apply (tes A B eqa); sp).\n\n    assert (term_equality_transitive eqa)\n      as eqt\n        by (onedts uv tye tys tyt tyvr tes tet tevr; apply (tet A B eqa); sp).\n\n    assert (term_equality_respecting eqa)\n      as eqc\n        by (onedts uv tye tys tyt tyvr tes tet tevr; apply (tevr A eqa); sp).\n\n    exists B A b1 b2 a1 a2 eqa; sp.\n    onedts uv tye tys tyt tyvr tes tet tevr.\n    generalize (tys A B eqa); intro k; dest_imp k hyp.\n    apply eqorsq_sym; sp.\n    apply eqorsq_sym; sp.\n    rw pereq0; split; sp.\n\n    apply eqorsq_commutes with (a := a1) (c := a2); sp.\n\n    apply eqorsq_commutes with (a := b1) (c := b2); sp;\n    apply eqorsq_sym; sp.\n\n  - unfold type_transitive_body; introv pereq.\n    unfold per_eq in pereq; exrepnd.\n    spcast; repeat computes_to_eqval.\n    unfold per_eq.\n\n    assert (eq_term_equals eqa eqa0)\n      as eqt\n        by (apply uniquely_valued_eq2_ts with (ts := ts) (T := B) (T1 := A) (T2 := B0); sp).\n\n    exists A B0 a1 a2 b0 b3 eqa; sp.\n\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_eq2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.26399433522413707}}
{"text": "Require Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nRequire Import PeanoNat.\nRequire Import Psatz. (* lia tactic for linear integer arithmetic *)\n\nRequire Export Parser.FocusedSyntaxDerive.\nRequire Export Parser.HasConflictFun.\n\nOpaque unfocus_helper.\nOpaque should_not_follow_fun.\nOpaque locate.\n\nOpaque FocusedSyntaxDerive.derive_obligation_1.\nOpaque FocusedSyntaxDerive.derive_obligation_2.\n\nLemma should_not_follow_fun_unfocus_monotone:\n  forall A T (ls: Layers T A) k core1 core2,\n    In k (should_not_follow_fun (unfocus_helper ls core1)) ->\n    (forall ts v, matches core1 ts v -> exists ts' v', matches core2 ts' v') ->\n    (forall k, In k (should_not_follow_fun core1) -> In k (should_not_follow_fun core2)) ->\n    In k (should_not_follow_fun (unfocus_helper ls core2)).\nProof.\n  induction ls; lights; destruct_layer; unfocus_helper_def; eapply IHls; eauto;\n    repeat light || invert_matches ||\n           match goal with\n           | H1: forall _ _, _ -> _, H2: matches _ _ _ |- _ => pose proof (H1 _ _ H2); clear H1\n           end;\n    eauto with matches;\n    eauto with should_not_follow_fun;\n    eauto using should_not_follow_fun_seq_monotone_l.\nQed.\n\nLemma should_not_follow_fun_plug_subset:\n  forall A T (ls: Layers T A) (v: T) core k ts0 v0,\n    matches core ts0 v0 ->\n    In k (should_not_follow_fun (unfocus (plug ls v))) ->\n    In k (should_not_follow_fun (unfocus_helper ls core)).\nProof.\n  induction ls;\n    repeat light || unfocus_helper_def || plug_def ||\n           unfold unfocus in * || destruct_layer || apply_anywhere should_not_follow_fun_eps_seq2;\n    eauto using should_not_follow_fun_epsilon with exfalso matches.\n\n  eapply should_not_follow_fun_unfocus_monotone; eauto;\n    repeat light || invert_matches || invert_constructor_equalities;\n    eauto with matches.\n\n  eapply should_not_follow_fun_seq_monotone_l;\n    eauto using should_not_follow_fun_epsilon with exfalso matches.\nQed.\n\nLemma should_not_follow_fun_locate_subset_helper:\n  forall n A (fs fs': Focused_Syntax A) k1 k2,\n    length (layers fs) + count_follow_by (layers fs) < n ->\n    locate k1 fs = Some fs' ->\n    In k2 (should_not_follow_fun (unfocus fs')) ->\n    In k2 (should_not_follow_fun (unfocus fs)).\nProof.\n  unfold unfocus; induction n; destruct fs; intros; try lia.\n\n  locate_def; repeat light || destruct_match || invert_constructor_equalities.\n\n  unshelve epose proof (IHn _ _ _ _ _ _ H0 H1);\n    repeat light || nullable_fun_spec;\n    try solve [ pose proof (plug_count_follow_by _ _ layers i); lights; eauto with lia ];\n    eauto using should_not_follow_fun_plug_subset with eapply_any.\nQed.\n\nLemma should_not_follow_fun_locate_subset:\n  forall A (fs fs': Focused_Syntax A) k1 k2,\n    locate k1 fs = Some fs' ->\n    In k2 (should_not_follow_fun (unfocus fs')) ->\n    In k2 (should_not_follow_fun (unfocus fs)).\nProof.\n  eauto using should_not_follow_fun_locate_subset_helper.\nQed.\n\nLemma should_not_follow_fun_pierce_helper_subset_helper:\n  forall m A T (ls: Layers A T) core t k gv pre,\n    (List.length vars - List.length gv, syntax_size core) = m ->\n    In k (should_not_follow_fun (unfocus_helper (pierce_helper (get_kind t) core ls gv pre) (Epsilon t))) ->\n    In k (should_not_follow_fun (unfocus_helper ls core)).\nProof.\n  induction m using measure_induction; destruct core;\n    repeat light || pierce_helper_def || find_false || unfocus_helper_def || destruct_match.\n\n  - eapply should_not_follow_fun_unfocus_monotone; eauto;\n      repeat light;\n      eauto with matches;\n      eauto using should_not_follow_fun_epsilon with exfalso.\n\n  - apply should_not_follow_fun_unfocus_monotone with core1; lights;\n      eauto with matches;\n      eauto with should_not_follow_fun;\n      eauto with lex;\n      try solve [ eapply_any; eauto; eauto with lex has_conflict_ind ].\n\n  - apply should_not_follow_fun_unfocus_monotone with core2; lights;\n      eauto with matches;\n      eauto with should_not_follow_fun;\n      eauto with lex;\n      try solve [ eapply_any; eauto; eauto with lex has_conflict_ind ].\n\n  - unshelve epose proof (H _ _ _ _ _ _ _ _ _ _ eq_refl H1);\n      repeat light || unfocus_helper_def; try lex.\n\n  - pose proof i as ip.\n    repeat light || options || destruct_match.\n    destruct (nullable_fun core1) eqn:N in ip; lights.\n    pose proof (nullable_fun_some _ _ _ N).\n\n    unshelve epose proof (H _ _ _ _ _ _ _ _ _ _ eq_refl H1) as IH;\n      repeat light || unfocus_helper_def || options || destruct_match || clear_some_dec; try lex.\n\n    revert IH.\n    generalize i.\n    generalize (FocusedSyntaxPierce.pierce_helper'_obligations_obligation_9 A B\n                          (get_kind t) core1 core2 gv pre).\n    rewrite N;\n      lights.\n\n    eapply should_not_follow_fun_unfocus_monotone; eauto;\n      repeat light || invert_matches;\n      eauto with matches;\n      eauto with should_not_follow_fun.\n\n  - unshelve epose proof (H _ _ _ _ _ _ _ _ _ _ eq_refl H1) as IH;\n      repeat light || unfocus_helper_def || options || destruct_match || clear_some_dec; try lex.\n\n  - unshelve epose proof (H _ _ _ _ _ _ _ _ _ _ eq_refl H1) as IH;\n      repeat light || unfocus_helper_def || options || destruct_match || clear_some_dec; try lex.\n\n  - unshelve epose proof (H _ _ _ _ _ _ _ _ _ _ eq_refl H1) as IH;\n      repeat light || unfocus_helper_def || options || destruct_match || destruct_and ||\n             clear_some_dec;\n      try lex;\n        eauto using pierce_var_measure.\n\n    eapply should_not_follow_fun_unfocus_monotone; eauto;\n      repeat light || invert_matches;\n      eauto with matches;\n      eauto with should_not_follow_fun.\nQed.\n\nLemma should_not_follow_fun_pierce_helper_subset:\n  forall A T (ls: Layers A T) core t k gv pre,\n    In k (should_not_follow_fun (unfocus_helper (pierce_helper (get_kind t) core ls gv pre) (Epsilon t))) ->\n    In k (should_not_follow_fun (unfocus_helper ls core)).\nProof.\n  eauto using should_not_follow_fun_pierce_helper_subset_helper.\nQed.\n\nLemma should_not_follow_fun_pierce_subset:\n  forall A T (ls: Layers A T) core t k pre,\n    In k (should_not_follow_fun (unfocus_helper (pierce (get_kind t) core ls pre) (Epsilon t))) ->\n    In k (should_not_follow_fun (unfocus_helper ls core)).\nProof.\n  unfold pierce;\n    eauto using should_not_follow_fun_pierce_helper_subset.\nQed.\n\nLemma should_not_follow_fun_derive_subset:\n  forall A (s ds: Focused_Syntax A) t k pre,\n    derive s t pre = Some ds ->\n    In k (should_not_follow_fun (unfocus ds)) ->\n    In k (should_not_follow_fun (unfocus s)).\nProof.\n  unfold derive, unfocus;\n    repeat light || destruct_match || invert_constructor_equalities.\n\n  clear matched.\n  revert H0.\n  generalize (FocusedSyntaxDerive.derive_obligation_2 A s t pre).\n  generalize (FocusedSyntaxDerive.derive_obligation_1 A s t pre).\n  repeat light || options || destruct_match.\n  generalize (locate (get_kind t) s).\n  destruct (locate (get_kind t) s) eqn:L;\n    repeat light || invert_constructor_equalities.\n  eapply should_not_follow_fun_locate_subset; eauto; unfold unfocus;\n    eauto using should_not_follow_fun_pierce_subset.\nQed.\n\nTheorem should_not_follow_fun_complete':\n  forall xs A (fs: Focused_Syntax A) t ys v1 v2,\n    matches (unfocus fs) xs v1 ->\n    matches (unfocus fs) (xs ++ t :: ys) v2 ->\n    ll1_fun (unfocus fs) = true ->\n    In (get_kind t) (should_not_follow_fun (unfocus fs)).\nProof.\n  unfold unfocus;\n    induction xs; repeat light || apply_anywhere ll1_fun_true;\n    eauto using should_not_follow_fun_first.\n\n  unshelve epose proof (derive_complete _ fs a xs _ v1 H);\n    repeat light || options || destruct_match;\n    eauto using unfocus_conflict_remains;\n    eauto using unfocus_conflict_remains2.\n\n  eapply should_not_follow_fun_derive_subset; eauto; lights.\n  apply IHxs with ys v1 v2; lights;\n    try solve [ eapply derive_sound_remove; eauto ].\n\n  destruct (ll1_fun (unfocus_helper (layers f) (core f))) eqn:LL1;\n    repeat light || apply_anywhere ll1_fun_false || apply_anywhere derive_no_conflict_unfocus.\nQed.\n\nTheorem should_not_follow_fun_complete:\n  forall xs A (s: Syntax A) t ys v1 v2,\n    matches s xs v1 ->\n    matches s (xs ++ t :: ys) v2 ->\n    ll1_fun s = true ->\n    In (get_kind t) (should_not_follow_fun s).\nProof.\n  intros.\n  pose proof (unfocus_focus _ s) as HU.\n  rewrite <- HU in *; eauto using should_not_follow_fun_complete'.\nQed.\n\nTheorem should_not_follow_ind_correct:\n  forall A (s: Syntax A) k,\n    ll1_ind s ->\n      should_not_follow_ind s k <->\n      exists t ts1 ts2 v1 v2,\n        get_kind t = k /\\\n        matches s ts1 v1 /\\\n        matches s (ts1 ++ t :: ts2) v2.\nProof.\n  lights.\n  - apply_anywhere should_not_follow_ind_sound; lights; eauto 8.\n  - apply should_not_follow_ind_fun.\n    apply should_not_follow_fun_complete with ts1 ts2 v1 v2; lights.\n    unfold ll1_ind in *; repeat light || bools.\n    destruct (ll1_fun s) eqn:LL1; lights; eauto using ll1_fun_false.\nQed.\n", "meta": {"author": "epfl-lara", "repo": "scallion-proofs", "sha": "3f048aabee5c961446d9993a70355eff510a2ddb", "save_path": "github-repos/coq/epfl-lara-scallion-proofs", "path": "github-repos/coq/epfl-lara-scallion-proofs/scallion-proofs-3f048aabee5c961446d9993a70355eff510a2ddb/ShouldNotFollowComplete.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.26394108585418663}}
{"text": "(********************)\n(********************)\n(****            ****)\n(****   Monads   ****)\n(****            ****)\n(********************)\n(********************)\n\nRequire Import Coq.Logic.ProofIrrelevance.\nRequire Import Main.CategoryTheory.Functor.\nRequire Import Main.CategoryTheory.NaturalTransformation.\n\n#[local] Set Universe Polymorphism.\n\n(* Metavariable for monads: `M` *)\n\nRecord monad\n  {C}\n  {F : endofunctor C}\n  (Eta : naturalTransformation idFunctor F)\n  (Mu : naturalTransformation (compFunctor F F) F) :=\nnewMonad {\n  mAssoc :\n    eta (vertCompNaturalTransformation Mu (leftWhisker Mu F)) =\n    eta (vertCompNaturalTransformation Mu (rightWhisker F Mu));\n  mIdent1 :\n    eta (vertCompNaturalTransformation Mu (leftWhisker Eta F)) =\n    eta idNaturalTransformation;\n  mIdent2 :\n    eta (vertCompNaturalTransformation Mu (rightWhisker F Eta)) =\n    eta idNaturalTransformation;\n}.\n\n#[export] Hint Resolve mAssoc : main.\n#[export] Hint Resolve mIdent1 : main.\n#[export] Hint Rewrite @mIdent1 : main.\n#[export] Hint Resolve mIdent2 : main.\n#[export] Hint Rewrite @mIdent2 : main.\n\nTheorem eqMonad\n  {C}\n  {F : endofunctor C}\n  (Eta : naturalTransformation idFunctor F)\n  (Mu : naturalTransformation (compFunctor F F) F)\n  (M1 M2 : monad Eta Mu)\n: M1 = M2.\nProof.\n  destruct M1.\n  destruct M2.\n  f_equal; apply proof_irrelevance.\nQed.\n\n#[export] Hint Resolve eqMonad : main.\n", "meta": {"author": "stepchowfun", "repo": "proofs", "sha": "00da33f63a56080227d06d37fd0f28b560f24624", "save_path": "github-repos/coq/stepchowfun-proofs", "path": "github-repos/coq/stepchowfun-proofs/proofs-00da33f63a56080227d06d37fd0f28b560f24624/proofs/CategoryTheory/Monad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.2639410858541866}}
{"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 int.MinMax.\nRequire list.List.\nRequire list.Length.\nRequire list.Mem.\nRequire map.Map.\nRequire list.Append.\n\n(* Why3 assumption *)\nDefinition unit := unit.\n\nAxiom qtmark : Type.\nParameter qtmark_WhyType : WhyType qtmark.\nExisting Instance qtmark_WhyType.\n\nAxiom char : Type.\nParameter char_WhyType : WhyType char.\nExisting Instance char_WhyType.\n\n(* Why3 assumption *)\nDefinition word := (list char).\n\n(* Why3 assumption *)\nInductive dist: (list char) -> (list char) -> Z -> Prop :=\n  | dist_eps : (dist Init.Datatypes.nil Init.Datatypes.nil 0%Z)\n  | dist_add_left : forall (w1:(list char)) (w2:(list char)) (n:Z), (dist w1\n      w2 n) -> forall (a:char), (dist (Init.Datatypes.cons a w1) w2\n      (n + 1%Z)%Z)\n  | dist_add_right : forall (w1:(list char)) (w2:(list char)) (n:Z), (dist w1\n      w2 n) -> forall (a:char), (dist w1 (Init.Datatypes.cons a w2)\n      (n + 1%Z)%Z)\n  | dist_context : forall (w1:(list char)) (w2:(list char)) (n:Z), (dist w1\n      w2 n) -> forall (a:char), (dist (Init.Datatypes.cons a w1)\n      (Init.Datatypes.cons a w2) n).\n\n(* Why3 assumption *)\nDefinition min_dist (w1:(list char)) (w2:(list char)) (n:Z): Prop := (dist w1\n  w2 n) /\\ forall (m:Z), (dist w1 w2 m) -> (n <= m)%Z.\n\n(* Why3 assumption *)\nFixpoint last_char (a:char) (u:(list char)) {struct u}: char :=\n  match u with\n  | Init.Datatypes.nil => a\n  | (Init.Datatypes.cons c u') => (last_char c u')\n  end.\n\n(* Why3 assumption *)\nFixpoint but_last (a:char) (u:(list char)) {struct u}: (list char) :=\n  match u with\n  | Init.Datatypes.nil => Init.Datatypes.nil\n  | (Init.Datatypes.cons c u') => (Init.Datatypes.cons a (but_last c u'))\n  end.\n\nAxiom first_last_explicit : forall (u:(list char)) (a:char),\n  ((Init.Datatypes.app (but_last a u) (Init.Datatypes.cons (last_char a\n  u) Init.Datatypes.nil)) = (Init.Datatypes.cons a u)).\n\nAxiom first_last : forall (a:char) (u:(list char)), exists v:(list char),\n  exists b:char,\n  ((Init.Datatypes.app v (Init.Datatypes.cons b Init.Datatypes.nil)) = (Init.Datatypes.cons a u)) /\\\n  ((list.Length.length v) = (list.Length.length u)).\n\nAxiom key_lemma_right : forall (w1:(list char)) (w'2:(list char)) (m:Z)\n  (a:char), (dist w1 w'2 m) -> forall (w2:(list char)),\n  (w'2 = (Init.Datatypes.cons a w2)) -> exists u1:(list char),\n  exists v1:(list char), exists k:Z, (w1 = (Init.Datatypes.app u1 v1)) /\\\n  ((dist v1 w2 k) /\\ ((k + (list.Length.length u1))%Z <= (m + 1%Z)%Z)%Z).\n\nAxiom dist_symetry : forall (w1:(list char)) (w2:(list char)) (n:Z), (dist w1\n  w2 n) -> (dist w2 w1 n).\n\nAxiom key_lemma_left : forall (w1:(list char)) (w2:(list char)) (m:Z)\n  (a:char), (dist (Init.Datatypes.cons a w1) w2 m) -> exists u2:(list char),\n  exists v2:(list char), exists k:Z, (w2 = (Init.Datatypes.app u2 v2)) /\\\n  ((dist w1 v2 k) /\\ ((k + (list.Length.length u2))%Z <= (m + 1%Z)%Z)%Z).\n\nAxiom dist_concat_left : forall (u:(list char)) (v:(list char))\n  (w:(list char)) (n:Z), (dist v w n) -> (dist (Init.Datatypes.app u v) w\n  ((list.Length.length u) + n)%Z).\n\nAxiom dist_concat_right : forall (u:(list char)) (v:(list char))\n  (w:(list char)) (n:Z), (dist v w n) -> (dist v (Init.Datatypes.app u w)\n  ((list.Length.length u) + n)%Z).\n\nAxiom min_dist_equal : forall (w1:(list char)) (w2:(list char)) (a:char)\n  (n:Z), (min_dist w1 w2 n) -> (min_dist (Init.Datatypes.cons a w1)\n  (Init.Datatypes.cons a w2) n).\n\nAxiom min_dist_diff : forall (w1:(list char)) (w2:(list char)) (a:char)\n  (b:char) (m:Z) (p:Z), (~ (a = b)) -> ((min_dist (Init.Datatypes.cons a w1)\n  w2 p) -> ((min_dist w1 (Init.Datatypes.cons b w2) m) -> (min_dist\n  (Init.Datatypes.cons a w1) (Init.Datatypes.cons b w2)\n  ((ZArith.BinInt.Z.min m p) + 1%Z)%Z))).\n\nAxiom min_dist_eps : forall (w:(list char)) (a:char) (n:Z), (min_dist w\n  Init.Datatypes.nil n) -> (min_dist (Init.Datatypes.cons a w)\n  Init.Datatypes.nil (n + 1%Z)%Z).\n\nAxiom min_dist_eps_length : forall (w:(list char)), (min_dist\n  Init.Datatypes.nil w (list.Length.length w)).\n\n(* Why3 assumption *)\nInductive ref (a:Type) :=\n  | mk_ref : a -> ref a.\nAxiom ref_WhyType : forall (a:Type) {a_WT:WhyType a}, WhyType (ref a).\nExisting Instance ref_WhyType.\nImplicit Arguments mk_ref [[a]].\n\n(* Why3 assumption *)\nDefinition contents {a:Type} {a_WT:WhyType a} (v:(ref a)): a :=\n  match v with\n  | (mk_ref x) => x\n  end.\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\nParameter make: forall {a:Type} {a_WT:WhyType a}, Z -> a -> (array a).\n\nAxiom make_length : forall {a:Type} {a_WT:WhyType a}, forall (n:Z) (v:a),\n  ((length (make n v)) = n).\n\nAxiom make_elts : forall {a:Type} {a_WT:WhyType a}, forall (n:Z) (i:Z) (v:a),\n  ((get (make n v) i) = v).\n\nParameter suffix: (array char) -> Z -> (list char).\n\nAxiom suffix_nil : forall (a:(array char)), ((suffix a\n  (length a)) = Init.Datatypes.nil).\n\nAxiom suffix_cons : forall (a:(array char)) (i:Z), ((0%Z <= i)%Z /\\\n  (i < (length a))%Z) -> ((suffix a i) = (Init.Datatypes.cons (get a\n  i) (suffix a (i + 1%Z)%Z))).\n\nAxiom suffix_length : forall (a:(array char)) (i:Z), ((0%Z <= i)%Z /\\\n  (i <= (length a))%Z) -> ((list.Length.length (suffix a\n  i)) = ((length a) - i)%Z).\n\n(* Why3 assumption *)\nDefinition min_suffix (a1:(array char)) (a2:(array char)) (i:Z) (j:Z)\n  (n:Z): Prop := (min_dist (suffix a1 i) (suffix a2 j) n).\n\n(* Why3 goal *)\nTheorem WP_parameter_distance : forall (w1:Z) (w11:(map.Map.map Z char))\n  (w2:Z) (w21:(map.Map.map Z char)), let w22 := (mk_array w2 w21) in\n  let w12 := (mk_array w1 w11) in (((0%Z <= w1)%Z /\\ (0%Z <= w2)%Z) ->\n  let o := (w2 + 1%Z)%Z in ((0%Z <= o)%Z -> forall (t:Z) (t1:(map.Map.map Z\n  Z)), ((0%Z <= t)%Z /\\ ((t = o) /\\ forall (i:Z), ((map.Map.get t1\n  i) = 0%Z))) -> ((0%Z <= w2)%Z -> forall (t2:(map.Map.map Z Z)),\n  (forall (j:Z), ((0%Z <= j)%Z /\\ (j < (w2 + 1%Z)%Z)%Z) -> ((map.Map.get t2\n  j) = (w2 - j)%Z)) -> let o1 := (w1 - 1%Z)%Z in ((0%Z <= o1)%Z ->\n  forall (t3:(map.Map.map Z Z)), forall (i:Z), ((i <= o1)%Z /\\\n  (0%Z <= i)%Z) -> ((forall (j:Z), ((0%Z <= j)%Z /\\ (j <= w2)%Z) -> (min_dist\n  (suffix w12 (i + 1%Z)%Z) (suffix w22 j) (map.Map.get t3 j))) ->\n  (((0%Z <= t)%Z /\\ ((0%Z <= w2)%Z /\\ (w2 < t)%Z)) -> (((0%Z <= w2)%Z /\\\n  (w2 < t)%Z) -> (((0%Z <= w2)%Z /\\ (w2 < t)%Z) -> forall (t4:(map.Map.map Z\n  Z)), ((0%Z <= t)%Z /\\ (t4 = (map.Map.set t3 w2 ((map.Map.get t3\n  w2) + 1%Z)%Z))) -> let o2 := (w2 - 1%Z)%Z in ((0%Z <= o2)%Z ->\n  forall (oldt:Z) (t5:(map.Map.map Z Z)), forall (j:Z), ((j <= o2)%Z /\\\n  (0%Z <= j)%Z) -> (((forall (k:Z), ((j < k)%Z /\\ (k <= w2)%Z) -> (min_dist\n  (suffix w12 i) (suffix w22 k) (map.Map.get t5 k))) /\\ ((forall (k:Z),\n  ((0%Z <= k)%Z /\\ (k <= j)%Z) -> (min_dist (suffix w12 (i + 1%Z)%Z)\n  (suffix w22 k) (map.Map.get t5 k))) /\\ (min_dist (suffix w12 (i + 1%Z)%Z)\n  (suffix w22 (j + 1%Z)%Z) oldt))) -> (((0%Z <= t)%Z /\\ ((0%Z <= j)%Z /\\\n  (j < t)%Z)) -> forall (oldt1:Z), (oldt1 = (map.Map.get t5 j)) ->\n  (((0%Z <= j)%Z /\\ (j < w2)%Z) -> (((0%Z <= i)%Z /\\ (i < w1)%Z) ->\n  ((~ ((map.Map.get w11 i) = (map.Map.get w21 j))) -> let o3 :=\n  (j + 1%Z)%Z in (((0%Z <= o3)%Z /\\ (o3 < t)%Z) -> (((0%Z <= j)%Z /\\\n  (j < t)%Z) -> (((0%Z <= j)%Z /\\ (j < t)%Z) -> forall (t6:(map.Map.map Z\n  Z)), ((0%Z <= t)%Z /\\ (t6 = (map.Map.set t5 j\n  ((ZArith.BinInt.Z.min (map.Map.get t5 j) (map.Map.get t5\n  o3)) + 1%Z)%Z))) -> forall (k:Z), (((j - 1%Z)%Z < k)%Z /\\ (k <= w2)%Z) ->\n  (min_dist (suffix w12 i) (suffix w22 k) (map.Map.get t6\n  k))))))))))))))))))).\nintros w1 w11 w2 w21 w22 w12 (h1,h2) o h3 t t1 (h4,(h5,h6)) h7 t2 h8\n        o1 h9 t3 i (h10,h11) h12 (h13,(h14,h15)) (h16,h17) (h18,h19) t4\n        (h20,h21) o2 h22 oldt t5 j (h23,h24) (h25,(h26,h27)) (h28,(h29,h30))\n        oldt1 h31 (h32,h33) (h34,h35) h36 o3 (h37,h38) (h39,h40) (h41,h42) t6\n        (h43,h44) k (h45,h46).\n(*\nintros w1 w11 w2 w21 w22 w12 (h1,h2) o h3 h4 h5 t h6 o1 h7 t1 i\n        (h8,h9) h10 (h11,(h12,h13)) (h14,h15) (h16,h17) t2 (h18,h19) o2 h20\n        oldt t3 j (h21,h22) (h23,(h24,h25)) (h26,(h27,h28)) oldt1 h29\n        (h30,h31) (h32,h33) h34 o3 (h35,h36) (h37,h38) (h39,h40) t4 (h41,h42)\n        k (h43,h44).\n*)\nsubst t4 t6 w12 w22 o o1 o2 o3.\nunfold min_suffix.\nassert (k=j \\/ j<k)%Z by omega. intuition.\n  (* j=k *)\n  subst j.\n  rewrite (suffix_cons _ i).\n  2: unfold length; simpl; omega.\n  rewrite (suffix_cons _ k).\n  2: unfold length; simpl; omega.\n  rewrite Map.Select_eq; try omega.\n  apply min_dist_diff.\n  subst; auto.\n  rewrite <- (suffix_cons _ i).\n  2: unfold length; simpl; omega.\n  subst.\n  apply h25; omega.\n  rewrite <- (suffix_cons _ k).\n  subst.\n  apply h26. omega.\n  unfold length; simpl; omega.\n  (* j<k *)\n  subst.\n  rewrite Map.Select_neq; try omega.\n  apply h25. omega.\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/edit_distance/edit_distance_WP_EditDistance_WP_parameter_distance_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2639119517211647}}
{"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 Tools.Matches Compilers.Compilers Elab.ElabCompilers.\nFrom Pyrosome.Lang Require Import SimpleVSubst SimpleVCPS.\nImport Core.Notations.\nImport CompilerDefs.Notations.\n\nRequire Coq.derive.Derive.\n\n\nNotation compiler := (compiler string).\n\nDefinition let_lang_def : lang :=\n  {[l/subst\n  [:| \"G\" : #\"env\",\n      \"A\" : #\"ty\",\n      \"B\" : #\"ty\",\n      \"e\" : #\"exp\" \"G\" \"A\",\n      \"e'\" : #\"exp\" (#\"ext\" \"G\" \"A\") \"B\"\n      -----------------------------------------------\n      #\"let\" \"e\" \"e'\" : #\"exp\" \"G\" \"B\"\n  ];\n  [:= \"G\" : #\"env\",\n      \"A\" : #\"ty\",\n      \"B\" : #\"ty\",\n      \"v\" : #\"val\" \"G\" \"A\",\n      \"e\" : #\"exp\" (#\"ext\" \"G\" \"A\") \"B\"\n      ----------------------------------------------- (\"eval let\")\n      #\"let\" (#\"ret\" \"v\") \"e\"\n      = #\"exp_subst\" (#\"snoc\" #\"id\" \"v\") \"e\"\n      : #\"exp\" \"G\" \"B\"\n  ] ]}.\n\nDerive let_lang\n       SuchThat (elab_lang_ext (exp_subst++value_subst) let_lang_def let_lang)\n       As let_lang_wf.\nProof. auto_elab. Qed.\n#[export] Hint Resolve let_lang_wf : elab_pfs.\n\nDefinition let_cps_def : compiler :=\n  match # from (let_lang) with\n  | {{e #\"let\" \"G\" \"A\" \"B\" \"e\" \"e'\"}} =>\n    bind_k 1 (var \"e\") (var \"A\")\n    {{e#\"blk_subst\" (#\"snoc\" (#\"snoc\" {wkn_n 2} #\"hd\") {ovar 1}) \"e'\"}}\n  end.\n\nDerive let_cps\n       SuchThat (elab_preserving_compiler cps_subst\n                                          (cps_lang ++ block_subst ++ value_subst)\n                                          let_cps_def\n                                          let_cps\n                                          let_lang)\n       As let_cps_preserving.\nProof. auto_elab_compiler. Qed.\n#[export] Hint Resolve let_cps_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/Let.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2639119517211647}}
{"text": "Require Import Coq.Strings.String Coq.Strings.Ascii.\nRequire Import Fiat.Parsers.Reflective.Syntax.\nSet Implicit Arguments.\n\nLocal Open Scope list_scope.\nLocal Open Scope string_scope.\n\nSection syntactify.\n  Context (var : TypeCode -> Type).\n\n  Definition syntactify_list {T : SimpleTypeCode} (ls : list (Term var T)) : Term var (clist T)\n    := list_rect\n         (fun _ => Term _ _)\n         (RLiteralApp Rnil noargs)\n         (fun x _ xs\n          => RLiteralApp Rcons (x :: xs :: noargs))\n         ls.\n\n  Definition syntactify_prod {A B : SimpleTypeCode} (xy : Term var A * Term var B) : Term var (A * B)\n    := RLiteralApp Rpair (fst xy :: snd xy :: noargs).\n\n  Definition syntactify_nat (n : nat) : Term var cnat\n    := nat_rect\n         (fun _ => Term _ _)\n         (RLiteralApp RO noargs)\n         (fun _ n'\n          => RLiteralApp RS (n' :: noargs))\n         n.\n\n  Definition syntactify_bool (v : bool) : Term var cbool\n    := RLiteralApp (Rbool v) noargs.\n  Definition syntactify_rchar_expr_ascii (v : Reflective.RCharExpr ascii)\n    : Term var crchar_expr_ascii\n    := RLiteralApp (Rrchar_expr_ascii v) noargs.\n  Definition syntactify_ritem_ascii (v : Reflective.ritem ascii)\n    : Term var critem_ascii\n    := RLiteralApp (Rritem_ascii v) noargs.\n  Definition syntactify_string (v : string)\n    : Term var cstring\n    := RLiteralApp (Rstring v) noargs.\n  Definition syntactify_rproductions\n             (Gp : list (string * Reflective.rproductions ascii))\n    : Term var _\n    := syntactify_list\n         (List.map\n            (fun xy\n             => syntactify_prod\n                  (syntactify_string (fst xy),\n                   syntactify_list\n                     (List.map\n                        (fun ls\n                         => syntactify_list\n                              (List.map\n                                 syntactify_ritem_ascii\n                                 ls))\n                        (snd xy))))\n            Gp).\nEnd syntactify.\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/Reflective/Syntactify.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.4726834766204329, "lm_q1q2_score": 0.26391194477348157}}
{"text": "Require Export LogRel.PseudoType.\nRequire Import LogRel.LemmasPseudoType.\nRequire Import LogRel.PseudoType.\nRequire Import Stlc.SpecSyntax.\nRequire Import Stlc.SpecEvaluation.\nRequire Import Stlc.SpecTyping.\nRequire Import Utlc.SpecSyntax.\nRequire Import Utlc.SpecEvaluation.\nRequire Import Utlc.Inst.\nRequire Import UVal.UVal.\n\nRequire Import Coq.Program.Basics.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Arith.Wf_nat.\nRequire Import Omega.\n\nInductive Direction : Set :=\n| dir_lt\n| dir_gt.\n\nDefinition World := nat.\nDefinition lev : World → nat := fun w => w.\nDefinition later : World → World := pred.\nFixpoint lateri (i : nat) : World → World :=\n  match i with \n    | 0 => id\n    | S i => fun w => pred (lateri i w)\n  end.\n\nDefinition PTRel := PTy → S.Tm → U.UTm → Prop.\nDefinition PCRel := PTy → S.PCtx → U.PCtx → Prop.\n\n(* Intuitively: observing termination takes a step in addition to the actual evaluation steps *)\nDefinition Observe (n : nat) (T : nat → Prop) : Prop :=\n  match n with\n    | 0 => False\n    | S n' => T n'\n  end.\n\nLemma lt_le {w w' w''} (fw : w' < w) (fw' : w'' ≤ w') : w'' < w.\nProof.\n  unfold lt in *.\n  refine (le_trans _ _ _ _ fw).\n  refine (le_n_S _ _ fw').\nDefined.\n\nDefinition prod_rel (R₁ R₂ : S.Tm → U.UTm → Prop) : S.Tm → U.UTm → Prop :=\n  fun ts tu =>\n    match ts , tu with\n      | S.pair ts₁ ts₂ , U.pair tu₁ tu₂ => R₁ ts₁ tu₁ ∧ R₂ ts₂ tu₂\n      | _              , _              => False\n    end.\nDefinition sum_rel (R₁ R₂ : S.Tm → U.UTm → Prop) : S.Tm → U.UTm → Prop :=\n  fun ts tu =>\n    match ts , tu with\n      | S.inl ts' , U.inl tu' => R₁ ts' tu'\n      | S.inr ts' , U.inr tu' => R₂ ts' tu'\n      | _         , _         => False\n    end.\nDefinition arr_rel (R₁ R₂ : S.Tm → U.UTm → Prop) : S.Tm → U.UTm → Prop :=\n  fun ts tu =>\n    match ts , tu with\n      | S.abs τ₁' tsb , U.abs tub =>\n        ∀ ts' tu',\n          R₁ ts' tu' →\n          R₂ (tsb [beta1 ts']) (tub [beta1 tu'])\n      | _ , _ => False\n    end.\n\nArguments prod_rel R₁ R₂ !ts !tu.\nArguments sum_rel R₁ R₂ !ts !tu.\nArguments arr_rel R₁ R₂ !ts !tu.\n\nSection LogicalRelation.\n\n  Variable (d: Direction).\n\n  Definition Obs (w : World) (ts : S.Tm) (tu : U.UTm) :=\n    match d with\n      | dir_lt => Observe (lev w) (S.TerminatingN ts) → U.Terminating tu\n      | dir_gt => Observe (lev w) (U.TerminatingN tu) → S.Terminating ts\n    end.\n\n  Definition contrel' (w : World) (vr' : ∀ w' : World, w' ≤ w → PTRel) : PCRel :=\n   fun τ Cs Cu => ∀ w' (fw : w' ≤ w) ts tu, vr' w' fw τ ts tu → Obs w' (S.pctx_app ts Cs) (U.pctx_app tu Cu).\n\n  Definition termrel' (w : World) (vr' : ∀ w' : World, w' ≤ w → PTRel) : PTRel :=\n    fun τ ts tu => ∀ Cs Cu, S.ECtx Cs → U.ECtx Cu → contrel' w vr' τ Cs Cu → Obs w (S.pctx_app ts Cs) (U.pctx_app tu Cu).\n\n  Definition valrel' (w : World) (ind : ∀ w' : World, w' < w → PTRel) : PTRel :=\n    fun τ ts tu =>\n      OfType τ ts tu ∧\n      let latervr : PTRel := fun τ ts tu => ∀ w' (fw : w' < w), ind w' fw τ ts tu in\n      let laterlatervr : ∀ w' (fw : w' < w) w'' (fw' : w'' ≤ w'), PTRel := fun w' fw w'' fw' => ind w'' (lt_le fw fw') in\n      let vrunit : S.Tm → U.UTm → Prop := fun ts tu => ts = S.unit ∧ tu = U.unit in\n      let vrbool : S.Tm → U.UTm → Prop := fun ts tu => (ts = S.true ∧ tu = U.true) ∨ (ts = S.false ∧ tu = U.false) in\n      let vrprod : PTy → PTy → S.Tm → U.UTm → Prop :=\n          fun τ₁ τ₂ =>\n            prod_rel (latervr τ₁) (latervr τ₂) in\n      let vrsum : PTy → PTy → S.Tm → U.UTm → Prop :=\n          fun τ₁ τ₂ =>\n            sum_rel (latervr τ₁) (latervr τ₂) in\n      let vrarr : PTy → PTy → S.Tm → U.UTm → Prop :=\n          fun τ₁ τ₂ ts tu =>\n            ∀ w' (fw : w' < w),\n              arr_rel\n                (ind w' fw τ₁)\n                (termrel' w' (laterlatervr w' fw) τ₂)\n                ts tu\n      in\n      match τ with\n        | ptunit => vrunit ts tu\n        | ptbool => vrbool ts tu\n        | ptprod τ₁ τ₂ => vrprod τ₁ τ₂ ts tu\n        | ptsum τ₁ τ₂ => vrsum τ₁ τ₂ ts tu\n        | ptarr τ₁ τ₂ => vrarr τ₁ τ₂ ts tu\n        | pEmulDV n p => match n with\n                           | 0 => ts = S.unit ∧ p = imprecise\n                           | S n' => (ts = unkUVal (S n') ∧ p = imprecise) ∨\n                                     exists ts',\n                                       (ts = inUnit n' ts' ∧ vrunit ts' tu) ∨\n                                       (ts = inBool n' ts' ∧ vrbool ts' tu) ∨\n                                       (ts = inProd n' ts' ∧ vrprod (pEmulDV n' p) (pEmulDV n' p) ts' tu ∧\n                                        OfTypeUtlc (ptprod (pEmulDV n' p) (pEmulDV n' p)) tu) ∨\n                                       (ts = inSum n' ts' ∧ vrsum (pEmulDV n' p) (pEmulDV n' p) ts' tu ∧ \n                                        OfTypeUtlc (ptsum (pEmulDV n' p) (pEmulDV n' p)) tu) ∨\n                                       (ts = inArr n' ts' ∧ vrarr (pEmulDV n' p) (pEmulDV n' p) ts' tu ∧ \n                                        OfTypeUtlc (ptarr (pEmulDV n' p) (pEmulDV n' p)) tu)\n                         end\n      end.\n\n  Definition valrel (w : World) (τ : PTy)(t₁ : S.Tm) (t₂ : U.UTm) : Prop :=\n    Fix lt_wf (fun w => PTRel) valrel' w τ t₁ t₂.\n\n  Lemma valrel_def_funext w (ind₁ ind₂ : ∀ w', w' < w → PTRel) :\n    (∀ w' (fw : w' < w), ind₁ w' fw = ind₂ w' fw) →\n    valrel' w ind₁ = valrel' w ind₂.\n  Proof.\n    intros.\n    enough (ind₁ = ind₂) as -> by auto.\n    extensionality w'.\n    extensionality fw.\n    trivial.\n  Qed.\n\n  Lemma valrel_fixp : ∀ w, valrel w = valrel' w (fun w _ => valrel w).\n  Proof.\n    refine (Fix_eq lt_wf (fun w => PTRel) valrel' valrel_def_funext).\n  Qed.\n\n  Definition contrel (w : World) : PCRel :=\n    contrel' w (fun w fw => valrel w).\n\n  Definition termrel (w : World) : PTRel :=\n    termrel' w (fun w fw => valrel w).\n\n  Lemma termrel_fixp :\n    ∀ w, termrel w = termrel' w (fun w _ => valrel' w (fun w _ => valrel w)).\n  Proof.\n    unfold termrel.\n    intros w.\n    f_equal.\n    (* Should we avoid functional extensionality? *)\n    extensionality w'.\n    extensionality fw.\n    apply valrel_fixp.\n  Qed.\n\n  Definition envrel (w : World) (Γ : PEnv) (γs : Sub S.Tm) (γu : Sub U.UTm) : Prop :=\n    ∀ i τ, ⟪ i : τ p∈ Γ ⟫ → valrel w τ (γs i) (γu i).\n\n  Definition OpenLRN (n : nat) (Γ : PEnv) (ts : S.Tm) (tu : U.UTm) (τ : PTy) : Prop :=\n    ⟪ repEmulCtx Γ ⊢ ts : repEmul τ ⟫ ∧\n    ⟨ pdom Γ ⊢ tu ⟩ ∧\n    ∀ w, lev w ≤ n → ∀ γs γu, envrel w Γ γs γu → termrel w τ (ts [ γs ]) (tu [ γu ]).\n\n  Definition OpenLR (Γ : PEnv) (ts : S.Tm) (tu : U.UTm) (τ : PTy) : Prop :=\n    ∀ n, OpenLRN n Γ ts tu τ.\n\n  Definition OpenLRCtxN (n : nat) (Cs : S.PCtx) (Cu : U.PCtx) (Γ' : PEnv) (τ' : PTy) (Γ : PEnv) (τ : PTy) : Prop :=\n    ⟪ ⊢ Cs : repEmulCtx Γ' , repEmul τ' → repEmulCtx Γ , repEmul τ ⟫ ∧\n    ∀ ts tu, OpenLRN n Γ' ts tu τ' -> OpenLRN n Γ (S.pctx_app ts Cs) (U.pctx_app tu Cu) τ.\n\n  Definition OpenLRCtx (Cs : S.PCtx) (Cu : U.PCtx) (Γ' : PEnv) (τ' : PTy) (Γ : PEnv) (τ : PTy) : Prop :=\n    ⟪ ⊢ Cs : repEmulCtx Γ' , repEmul τ' → repEmulCtx Γ' , repEmul τ ⟫ ∧\n    ∀ ts tu, OpenLR Γ' ts tu τ' → OpenLR Γ (S.pctx_app ts Cs) (U.pctx_app tu Cu) τ.\n\nEnd LogicalRelation.\n\nArguments termrel d w τ t₁ t₂ : simpl never.\nArguments valrel d w τ t₁ t₂ : simpl never.\nArguments valrel' d w ind !τ !t₁ !t₂ /.\n\nNotation \"⟪ Γ ⊩ ts ⟦ d , n ⟧ tu : τ ⟫\" := (OpenLRN d n Γ ts tu τ)\n  (at level 0, ts at level 98,\n   d at level 98, n at level 98,\n   tu at level 98,\n   Γ at level 98, τ at level 98,\n   format \"⟪ Γ ⊩  ts ⟦ d , n ⟧ tu  :  τ  ⟫\").\n\nNotation \"⟪ Γ ⊩ ts ⟦ d ⟧ tu : τ ⟫\" := (OpenLR d Γ ts tu τ)\n  (at level 0, ts at level 98,\n   d at level 98, tu at level 98,\n   Γ at level 98, τ at level 98,\n   format \"⟪ Γ ⊩  ts ⟦ d ⟧ tu  :  τ  ⟫\").\n\nNotation \"⟪ ⊩ Cs ⟦ d , n ⟧ Cu : Γ₀ , τ₀ → Γ , τ ⟫\" := (OpenLRCtxN d n Cs Cu Γ₀ τ₀ Γ τ)\n  (at level 0, Cs at level 98,\n   d at level 98, n at level 98,\n   Cu at level 98,\n   Γ₀ at level 98, τ₀ at level 98,\n   Γ at level 98, τ at level 98,\n   format \"⟪  ⊩  Cs ⟦ d , n ⟧ Cu  :  Γ₀ ,  τ₀  →  Γ ,  τ  ⟫\").\n\nNotation \"⟪ ⊩ Cs ⟦ d ⟧ Cu : Γ₀ , τ₀ → Γ , τ ⟫\" := (OpenLRCtx d Cs Cu Γ₀ τ₀ Γ τ)\n  (at level 0, Cs at level 98,\n   d at level 98, Cu at level 98,\n   Γ₀ at level 98, τ₀ at level 98,\n   Γ at level 98, τ at level 98,\n   format \"⟪  ⊩  Cs ⟦ d ⟧ Cu  :  Γ₀ ,  τ₀  →  Γ ,  τ  ⟫\").\n\nSection TermRelZero.\n  Definition termreli₀ d dfc w τ ts tu :=\n    (∃ vs vu, clos_refl_trans_1n S.Tm S.eval ts vs ∧ U.ctxevalStar tu vu ∧\n              valrel d w τ vs vu) ∨\n    (forall Cs Cu, S.ECtx Cs → U.ECtx Cu → Obs d (lateri dfc w) (S.pctx_app ts Cs) (U.pctx_app tu Cu)).\n\n  Arguments termreli₀ d dfc w τ ts tu : simpl never.\n\n  Definition termrel₀ d w τ ts tu :=\n    termreli₀ d 0 w τ ts tu.\n  \n  Arguments termrel₀ d w τ ts tu : simpl never.\n\nEnd TermRelZero.", "meta": {"author": "dominiquedevriese", "repo": "facomp-stlc-coq", "sha": "77043e68813d3a7ed8926802191638f063de1544", "save_path": "github-repos/coq/dominiquedevriese-facomp-stlc-coq", "path": "github-repos/coq/dominiquedevriese-facomp-stlc-coq/facomp-stlc-coq-77043e68813d3a7ed8926802191638f063de1544/LogRel/LR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.26391194477348145}}
{"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'). exfalso; omega.\n generalize (Max.le_max_l i0 n); intro. exfalso. 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 exfalso.\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. exfalso.\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": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/examples/cont/model.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982315512488, "lm_q2_score": 0.40733340004593016, "lm_q1q2_score": 0.26386985620151093}}
{"text": "Require Import Heaps.\nRequire SepExpr Expr.\nRequire Import Provers.\nRequire Import EquivDec.\nRequire Import List.\n    Require Import ReifySepExpr.\n    Require ExprUnify.\nRequire SepCancel.\n\nSet Implicit Arguments.\n\nModule SepExprTests (B : Heap) (ST : SepTheoryX.SepTheoryX with Module H := B).\n  Module Sep := SepExpr.Make ST.\n  Module Reify := ReifySepExpr Sep.\n  Module SH := SepHeap.Make Sep.\n  Module CANCEL := SepCancel.Make ExprUnify.UNIFIER SH.\n\n  (** Just a test separation logic predicate **)\n  Section Tests.\n    Variable f : forall a b, nat -> ST.hprop a b nil.\n    Variable h : forall a b, nat -> ST.hprop a b nil.\n    Variable i : forall a b, nat -> ST.hprop a b nil.\n    Variable g : bool -> nat -> nat -> nat.\n\n    Ltac isConst e :=\n      match e with\n        | true => true\n        | false => true\n        | O => true\n        | S ?e => isConst e\n        | _ => false\n      end.\n\n    Fixpoint all a b (f : nat -> ST.hprop a b nil) (n : nat) : ST.hprop a b nil :=\n      match n with\n        | 0 => f 0\n        | S n => ST.star (f (S n)) (all f n)\n      end.\n\n    Fixpoint allb a b (f : nat -> ST.hprop a b nil) (n m : nat) : ST.hprop a b nil :=\n      match n with\n        | 0 => f m\n        | S n => ST.star (f (m - S n)) (allb f n m)\n      end.\n\n    Theorem asdf : forall x y : nat, EqNat.beq_nat x y = true -> x = y.\n    Admitted.\n\n    Definition nat_type : Expr.type :=\n      {| Expr.Impl := nat \n       ; Expr.Eqb  := EqNat.beq_nat\n       ; Expr.Eqb_correct := asdf\n       |}.\n\n    Fixpoint star_all a b (f : nat -> ST.hprop a b nil) (n : nat) : ST.hprop a b nil :=\n      match n with\n        | 0 => f 0\n        | S n => ST.star (f (S n)) (star_all f n)\n      end.\n\n    Definition N := 20.\n    Definition M := 20.\n\n    Variables pc st : Type.\n\n    Definition try_it_out {ts} (pcV stV : Expr.tvar) (preds : CANCEL.SE.predicates ts pcV stV) (l r : Sep.sexpr ts pcV stV) : \n      (SH.SHeap ts pcV stV * SH.SHeap ts pcV stV * ExprUnify.UNIFIER.Subst ts) :=\n      let l := SH.hash l in\n      let r := SH.hash r in\n      @CANCEL.sepCancel ts pcV stV preds (ReflexivityProver.reflexivityProver) 1 tt (snd l) (snd r) (ExprUnify.UNIFIER.Subst_empty _).      \n\n\n    Theorem apply_it ts pcT stT funcs (preds : CANCEL.SE.predicates ts pcT stT) l r cs : \n      (let '(l',r',_) := @try_it_out ts pcT stT preds l r in\n       @ST.himp (Expr.tvarD ts pcT) (Expr.tvarD ts stT) cs \n         (@Sep.sexprD ts pcT stT funcs preds nil nil (SH.sheapD l')) (@Sep.sexprD ts pcT stT funcs preds nil nil (SH.sheapD r'))) ->\n      @ST.himp (Expr.tvarD ts pcT) (Expr.tvarD ts stT) cs \n        (@Sep.sexprD ts pcT stT funcs preds nil nil l) (@Sep.sexprD ts pcT stT funcs preds nil nil r).\n    Proof.\n    Admitted.\n\n    Ltac go :=\n      match goal with\n        | [ |- ST.himp _ ?L ?R ] =>\n          let Ts := constr:(Reflect.Tcons pc (Reflect.Tcons st Reflect.Tnil)) in\n          Reify.collectTypes_sexpr ltac:(isConst) L Ts ltac:(fun Ts =>\n          Reify.collectTypes_sexpr ltac:(isConst) R Ts ltac:(fun Ts =>\n          let types := ReifyExpr.extend_all_types Ts (nat_type :: @nil Expr.type) in\n          let uvars := eval simpl in (@nil _ : Expr.env types) in\n          let gvars := uvars in\n          let vars := eval simpl in (@nil Expr.tvar) in\n          (** build the funcs **)\n          let funcs := constr:(@nil (Expr.signature types)) in\n          let pcT := constr:(Expr.tvType 1) in\n          let stT := constr:(Expr.tvType 2) in\n          (** build the base sfunctions **)\n          let preds := constr:(@nil (Sep.predicate types pcT stT)) in\n          Reify.reify_sexpr ltac:(isConst) L types funcs pcT stT preds uvars vars ltac:(fun uvars funcs preds L =>\n          Reify.reify_sexpr ltac:(isConst) R types funcs pcT stT preds uvars vars ltac:(fun uvars funcs preds R =>\n            simple apply (@apply_it types pcT stT funcs preds L R); compute\n          ))))\n      end.\n\n    Goal let N := 1 in\n      forall c, @ST.himp pc st c \n      (ST.star (allb (@h pc st) N N) (allb (@f pc st) N N))\n      (ST.star (all (@f pc st) N) (all (@h pc st) N)).\n    Proof.\n      simpl; intros.\n      Time go. reflexivity.\n    Time Qed.\n\n    Goal let N := 5 in\n      forall c, @ST.himp pc st c \n      (ST.star (allb (@h pc st) N N) (allb (@f pc st) N N))\n      (ST.star (all (@f pc st) N) (all (@h pc st) N)).\n    Proof.\n      simpl; intros.\n      Time go. reflexivity.\n    Time Qed.\n\n    Goal let N := 10 in\n      forall c, @ST.himp pc st c \n      (ST.star (allb (@h pc st) N N) (allb (@f pc st) N N))\n      (ST.star (all (@f pc st) N) (all (@h pc st) N)).\n    Proof.\n      simpl; intros.\n      Time go. reflexivity.\n    Time Qed.\n\n    Goal let N := 15 in\n      forall c, @ST.himp pc st c \n      (ST.star (allb (@h pc st) N N) (allb (@f pc st) N N))\n      (ST.star (all (@f pc st) N) (all (@h pc st) N)).\n    Proof.\n      simpl; intros.\n      Time go. reflexivity.\n    Time Qed.\n\n    Goal let N := 20 in\n      forall c, @ST.himp pc st c \n      (ST.star (allb (@h pc st) N N) (allb (@f pc st) N N))\n      (ST.star (all (@f pc st) N) (all (@h pc st) N)).\n    Proof.\n      simpl; intros.\n      Time go. reflexivity.\n    Time Qed.\n\n(*\n    Goal forall c, @ST.himp pc st c \n      (ST.star (allb (@h pc st) N N) (allb (@f pc st) M M))\n      (ST.star (all (@f pc st) M) (all (@h pc st) N)).\n      unfold N, M; simpl all; simpl allb; intros.\n      Time go. reflexivity.\n      Time Qed.\n*)\n\n(*\n\n\n    Goal forall c, @ST.himp pc st c \n      (ST.star (allb (@h pc st) N N) (allb (@f pc st) M M))\n      (ST.star (all (@f pc st) M) (all (@h pc st) N)).\n      unfold N, M; simpl all; simpl allb; intros.\n      Time ltac_canceler.\n    Time Qed.\n      \n    \n\n\n\n\n\nTime Sep.sep isConst (nat_type :: nil). reflexivity.\n\n\n    Goal forall a b c x y, @ST.himp a b c (f _ _ (g y (x + x) 1)) (f _ _ 1).\n      sep.\n    Abort.\n\n    Theorem t1 : forall a b c, @ST.himp a b c (f _ _ 0) (f _ _ 0).\n      sep.\n    Qed.\n\n    Theorem t2 : forall a b c, \n      @ST.himp a b c (ST.star (star_all_back (@h a b) 15 15) (star_all_back (@f a b) 15 15))\n                     (ST.star (star_all (@f a b) 15) (star_all (@h a b) 15)).\n      sep.\n    Qed.\n\n    Theorem t3 : forall a b c, @ST.himp a b c \n      (ST.star (f _ _ 2) (f _ _ 1))\n      (f _ _ 1).\n      sep.\n    Abort.\n\n    Theorem t4 : forall a b c, @ST.himp a b c \n      (ST.ex (fun y : nat => ST.ex (fun x : bool => ST.star (f _ _ (g x 1 2)) (f _ _ 1) )))\n      (f _ _ 1).\n      sep.\n    Abort.\n\n    Theorem t5 : forall a b c, @ST.himp a b c \n      (ST.ex (fun y : nat => f _ _ y))\n      (f _ _ 1).\n      sep.\n    Abort.\n\n    Theorem t6 : forall a b c, @ST.himp a b c \n      (f _ _ 1)\n      (ST.ex (fun y : nat => f _ _ y)).\n      sep.\n    Qed.\n\n    Theorem t7 : forall a b c, @ST.himp a b c \n      (ST.star (f _ _ (g true 0 1)) (f _ _ (g true 1 2)))\n      (ST.ex (fun y : nat => ST.star (f _ _ (g true 0 y)) (ST.ex (fun z : nat => f _ _ (g true 1 z))))).\n      sep.\n    Qed.\n\n    Theorem t8 : forall a b c, @ST.himp a b c \n      (ST.star (f _ _ (g true 0 1)) (f _ _ (g true 1 2)))\n      (ST.ex (fun y : nat => ST.star (f _ _ (g true 1 y)) (ST.ex (fun z : nat => f _ _ (g true 0 z))))).\n      sep.\n    Qed.\n\n\n    (** ** Test use of transitivity prover in cancellation *)\n\n    Theorem t9 : forall a b c x y, x = y\n      -> @ST.himp a b c  (f _ _ x) (f _ _ y).\n      sep.\n    Qed.\n\n    Theorem t10 : forall a b c x y, x = y\n      -> @ST.himp a b c  (f _ _ y) (f _ _ x).\n      sep.\n    Qed.\n\n    Theorem t11 : forall a b c x y z, x = y\n      -> x = z\n      -> @ST.himp a b c  (f _ _ x) (f _ _ y).\n      sep.\n    Qed.\n\n    Theorem t12 : forall a b c x y u v, x = y\n      -> u = v\n      -> @ST.himp a b c  (ST.star (f _ _ x) (f _ _ v)) (ST.star (f _ _ y) (f _ _ u)).\n      sep.\n    Qed.\n\n    Theorem t13 : forall a b c x y z u v, x = y\n      -> z = y\n      -> u = v\n      -> @ST.himp a b c  (ST.star (f _ _ x) (f _ _ v)) (ST.star (f _ _ z) (f _ _ u)).\n      sep.\n    Qed.\n*)\n\n  End Tests.\n\nEnd SepExprTests.\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/benchmarks/MicroBenchReflect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.26386985066212765}}
{"text": "Require Import maps.\nRequire Import patterns.\n\n(* This module defines a zipper over patterns to\n   allow moving terms of interest to the front by reflection\n   rather than by assembling large proof terms.\n *)\n\nInductive pat_context {Key Elt : Type} : Type :=\n    Top\n  | LeftOf (p : MapPattern Key Elt) (rest : pat_context)\n  | RightOf (p : MapPattern Key Elt) (rest : pat_context)\n  .\n\nFixpoint close {Key Elt} pat ctx : MapPattern Key Elt :=\n  match ctx with\n    | Top => pat\n    | LeftOf p ctx' => close (pat :* p)%pattern ctx'\n    | RightOf p ctx' => close (p :* pat)%pattern ctx'\n  end.\n\nFixpoint close_empty {Key Elt} ctx : MapPattern Key Elt :=\n  match ctx with\n    | Top => mapEmpty%pattern\n    | LeftOf p ctx' => close p ctx'\n    | RightOf p ctx' => close p ctx'\n  end.\n\nLemma lifting : forall {Key Elt} ctx (p : MapPattern Key Elt),\n  PatEquiv (close p ctx) (p :* close_empty ctx).\ninduction ctx;simpl;intros.\nrewrite patEquivUnit. reflexivity.\nrewrite 2 IHctx, patEquivAssoc; reflexivity.\nrewrite 2 IHctx, patEquivAssoc, patEquivCommAssoc; reflexivity.\nQed.\n\n(* Search through a MapPattern pat for\n   the given term target, adding the context\n   passed through onto context ctx,\n   and ending on success by calling the\n   continuation k with the pattern found and\n   the constructed context.\n *)\nLtac quote_zipper target pat ctx k :=\n  first [unify target pat;k pat ctx\n   |  match pat with\n      | (?l :* ?r)%pattern =>\n          first [let ctx' := constr:(LeftOf r ctx) in\n                 quote_zipper target l ctx' k\n                |let ctx' := constr:(RightOf l ctx) in\n                 quote_zipper target r ctx' k\n                ]  \n      | (asP ?h ?P)%pattern =>\n          unify target P;k pat ctx\n  end].\n\n(*\nLemma lift_constraint : forall {Key Elt} (h : Map Key Elt) ctx P,\n  h |= close (constraint P) ctx <-> (P /\\ h |= close_empty ctx).\nintros.\nrewrite lifting.\n(* now extract the P *)\nTransparent satisfies.\nsimpl.\nOpaque satisfies.\nfirstorder.\nrevert H0;apply pats_good. equate_maps.\neexists;eexists. firstorder (eauto || equate_maps).\nQed.\n *)", "meta": {"author": "Formal-Systems-Laboratory", "repo": "coinduction", "sha": "1031da11c4a4523ea9b7347036b6bdabc7620e1d", "save_path": "github-repos/coq/Formal-Systems-Laboratory-coinduction", "path": "github-repos/coq/Formal-Systems-Laboratory-coinduction/coinduction-1031da11c4a4523ea9b7347036b6bdabc7620e1d/coinduction-proofs/common/zipper_patterns.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.2638512725916295}}
{"text": "(*Tests from testcases folder. 3 SAT (7,8,9) and 1 IMPL (11) fail to run \nbecause Coq runs out of memory*)\nAdd LoadPath \"..\".\nRequire Import msl.msl_standard.\nRequire Import share_dec_base.\nRequire Import share_equation_system.\nRequire Import share_simplifier.\nRequire Import share_solver.\nRequire Import fbool_solver.\nRequire Import share_solver_with_partition.\n\nModule Tester.\n\n Module es := Equation_system sv_nat Share_Domain.\n Module esf := System_Features sv_nat es.\n Module bf := Bool_formula sv_nat.\n Module bsf := BF_solver sv_nat bf.\n Import es.\n Module solver := Solver_with_partition sv_nat es bf bsf.\n Import solver.\n\n Definition a1 : var := 0.\n Definition a2 : var := 1.\n Definition a3 : var := 2.\n Definition a4 : var := 3.\n Definition a5 : var := 4.\n Definition a6 : var := 5.\n Definition a7 : var := 6.\n Definition a8 : var := 7.\n Definition a9 : var := 8.\n Definition a10 : var := 9.\n Definition a11 : var := 10.\n Definition a12 : var := 11.\n Definition a13 : var := 12.\n Definition a14 : var := 13.\n Definition a15 : var := 14.\n Definition a16 : var := 15.\n Definition a17 : var := 16.\n Definition a18 : var := 17.\n Definition a19 : var := 18.\n Definition a20 : var := 19.\n Definition a21 : var := 20.\n Definition a : var := 21.\n Definition b : var := 22.\n Definition c : var := 23.\n Definition d : var := 24.\n Definition ses1 :=Sat_equation_system (nil) (nil) ((Vobject a1,Vobject a2,Vobject a3)::(Vobject a2,Vobject a3,Vobject a4)::(Vobject a3,Vobject a4,Vobject a5)::(Vobject a4,Vobject a5,Vobject a6)::(Vobject a5,Vobject a6,Vobject a7)::(Vobject a6,Vobject a7,Vobject a8)::(Vobject a7,Vobject a8,Vobject a9)::(Vobject a8,Vobject a9,Vobject a10)::(Vobject a9,Vobject a10,Vobject a11)::(Vobject a10,Vobject a11,Vobject a12)::(Vobject a11,Vobject a12,Vobject a13)::(Vobject a12,Vobject a13,Vobject a14)::(Vobject a13,Vobject a14,Vobject a15)::(Vobject a14,Vobject a15,Vobject a16)::(Vobject a15,Vobject a16,Vobject a17)::(Vobject a16,Vobject a17,Vobject a18)::(Vobject a17,Vobject a18,Vobject a19)::(Vobject a18,Vobject a19,Vobject a20)::nil).\n Definition ses2 :=Sat_equation_system (nil) (nil) ((Vobject a1,Vobject a2,Vobject a3)::(Vobject a2,Vobject a3,Vobject a4)::(Vobject a3,Vobject a4,Vobject a5)::(Vobject a4,Vobject a5,Vobject a6)::(Vobject a5,Vobject a6,Vobject a7)::(Vobject a6,Vobject a7,Vobject a8)::(Vobject a7,Vobject a8,Vobject a9)::(Vobject a8,Vobject a9,Vobject a10)::(Vobject a9,Vobject a10,Vobject a11)::(Vobject a10,Vobject a11,Vobject a12)::(Vobject a11,Vobject a12,Vobject a13)::(Vobject a12,Vobject a13,Vobject a14)::(Vobject a13,Vobject a14,Vobject a15)::(Vobject a14,Vobject a15,Vobject a16)::(Vobject a15,Vobject a16,Vobject a17)::(Vobject a16,Vobject a17,Vobject a18)::(Vobject a17,Vobject a18,Vobject a19)::(Vobject a18,Vobject a19,Vobject a20)::(Vobject a19,Vobject a20,Cobject (Share.top))::nil).\n Definition ses3 :=Sat_equation_system (nil) (nil) ((Vobject a1,Vobject a2,Vobject a3)::(Vobject a2,Vobject a3,Vobject a4)::(Vobject a3,Vobject a4,Vobject a5)::(Vobject a4,Vobject a5,Vobject a6)::(Vobject a5,Vobject a6,Vobject a7)::(Vobject a6,Vobject a7,Vobject a8)::(Vobject a7,Vobject a8,Vobject a9)::(Vobject a8,Vobject a9,Vobject a10)::(Vobject a9,Vobject a10,Vobject a11)::(Vobject a10,Vobject a11,Vobject a12)::(Vobject a11,Vobject a12,Vobject a13)::(Vobject a12,Vobject a13,Vobject a14)::(Vobject a13,Vobject a14,Vobject a15)::(Vobject a14,Vobject a15,Vobject a16)::(Vobject a15,Vobject a16,Vobject a17)::(Vobject a16,Vobject a17,Vobject a18)::(Vobject a17,Vobject a18,Vobject a19)::(Vobject a18,Vobject a19,Vobject a20)::(Vobject a19,Vobject a20,Cobject (Share.recompose (Share.top,Share.bot)))::nil).\n Definition ses4 :=Sat_equation_system (nil) (nil) ((Vobject a1,Vobject a2,Vobject a3)::(Vobject a3,Vobject a4,Vobject a5)::(Vobject a5,Vobject a6,Vobject a7)::(Vobject a7,Vobject a8,Vobject a9)::(Vobject a9,Vobject a10,Vobject a11)::(Vobject a11,Vobject a12,Vobject a13)::(Vobject a13,Vobject a14,Vobject a15)::(Vobject a15,Vobject a16,Vobject a17)::(Vobject a17,Vobject a18,Vobject a19)::(Vobject a19,Vobject a20,Vobject a21)::nil).\n Definition ses5 :=Sat_equation_system (nil) (nil) ((Vobject a1,Vobject a2,Vobject a3)::(Vobject a3,Vobject a4,Vobject a5)::(Vobject a5,Vobject a6,Vobject a7)::(Vobject a7,Vobject a8,Vobject a9)::(Vobject a9,Vobject a10,Vobject a11)::(Vobject a11,Vobject a12,Vobject a13)::(Vobject a13,Vobject a14,Vobject a15)::(Vobject a15,Vobject a16,Vobject a17)::(Vobject a17,Vobject a18,Vobject a19)::(Vobject a19,Vobject a20,Cobject (Share.top))::nil).\n Definition ses6 :=Sat_equation_system (nil) (nil) ((Vobject a1,Vobject a2,Vobject a3)::(Vobject a3,Vobject a4,Vobject a5)::(Vobject a5,Vobject a6,Vobject a7)::(Vobject a7,Vobject a8,Vobject a9)::(Vobject a9,Vobject a10,Vobject a11)::(Vobject a11,Vobject a12,Vobject a13)::(Vobject a13,Vobject a14,Vobject a15)::(Vobject a15,Vobject a16,Vobject a17)::(Vobject a17,Vobject a18,Vobject a19)::(Vobject a19,Vobject a20,Cobject (Share.recompose (Share.bot,Share.top)))::nil).\n (*\n Definition ses7 :=Sat_equation_system (nil) (nil) ((Vobject a1,Vobject a2,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))))))))))))))))::nil).\n Definition ses8 :=Sat_equation_system (nil) (nil) ((Vobject a1,Vobject a2,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))))))))))))))))::(Vobject a2,Vobject a3,Cobject (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.top,Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot)))::nil).\n Definition ses9 :=Sat_equation_system (nil) (nil) ((Vobject a1,Vobject a2,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))))))))))))))))::(Vobject a2,Vobject a3,Cobject (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.top,Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot)))::(Vobject a1,Cobject (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.top,Share.bot),Share.recompose (Share.bot,Share.top)),Share.recompose (Share.recompose (Share.top,Share.bot),Share.recompose (Share.top,Share.bot))),Share.recompose (Share.recompose (Share.recompose (Share.top,Share.bot),Share.recompose (Share.top,Share.bot)),Share.recompose (Share.recompose (Share.bot,Share.top),Share.recompose (Share.bot,Share.top))))),Vobject a3)::nil).\n *)\n Definition ses10 :=Sat_equation_system (nil) ((Vobject a1,Vobject a4)::(Vobject a2,Vobject a5)::(Vobject a3,Vobject a6)::(Vobject a7,Cobject (Share.top))::(Vobject a8,Cobject (Share.recompose (Share.recompose (Share.top,Share.bot),Share.bot)))::(Vobject a9,Cobject (Share.recompose (Share.recompose (Share.bot,Share.top),Share.top)))::nil) ((Vobject a1,Vobject a2,Vobject a7)::(Vobject a2,Vobject a3,Vobject a8)::(Vobject a3,Vobject a1,Vobject a9)::(Vobject a4,Vobject a5,Cobject (Share.top))::(Cobject (Share.top),Vobject a3,Vobject a7)::(Cobject (Share.recompose (Share.recompose (Share.recompose (Share.top,Share.bot),Share.bot),Share.bot)),Cobject (Share.recompose (Share.bot,Share.top)),Vobject a10)::(Vobject a11,Cobject (Share.recompose (Share.top,Share.bot)),Cobject (Share.top))::(Cobject (Share.top),Vobject a12,Vobject a7)::(Cobject (Share.recompose (Share.top,Share.bot)),Cobject (Share.recompose (Share.bot,Share.top)),Cobject (Share.top))::nil).\n Definition ses11 :=Sat_equation_system (nil) ((Vobject a1,Vobject a4)::(Vobject a2,Vobject a5)::(Vobject a3,Vobject a6)::(Vobject a7,Cobject (Share.top))::(Vobject a8,Cobject (Share.recompose (Share.recompose (Share.top,Share.bot),Share.bot)))::(Vobject a9,Cobject (Share.recompose (Share.recompose (Share.bot,Share.top),Share.top)))::nil) ((Vobject a1,Vobject a2,Vobject a7)::(Vobject a2,Vobject a3,Vobject a8)::(Vobject a3,Vobject a1,Vobject a9)::(Vobject a4,Vobject a5,Cobject (Share.top))::(Cobject (Share.top),Vobject a3,Vobject a7)::(Cobject (Share.recompose (Share.recompose (Share.recompose (Share.top,Share.bot),Share.bot),Share.bot)),Cobject (Share.recompose (Share.bot,Share.top)),Vobject a10)::(Vobject a11,Cobject (Share.recompose (Share.top,Share.bot)),Cobject (Share.top))::(Cobject (Share.top),Vobject a12,Vobject a7)::(Cobject (Share.recompose (Share.top,Share.bot)),Cobject (Share.recompose (Share.bot,Share.top)),Cobject (Share.top))::(Vobject a5,Vobject a6,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top)))))::nil).\n Definition ses12 :=Sat_equation_system (nil) ((Vobject a1,Vobject a2)::(Vobject a2,Vobject a3)::(Vobject a3,Vobject a4)::(Vobject a4,Vobject a5)::(Vobject a5,Vobject a6)::(Vobject a6,Vobject a7)::(Vobject a7,Vobject a8)::(Vobject a8,Vobject a9)::(Vobject a9,Vobject a10)::(Vobject a10,Vobject a11)::(Vobject a11,Vobject a12)::(Vobject a12,Vobject a13)::(Vobject a13,Vobject a14)::(Vobject a14,Vobject a15)::(Vobject a15,Vobject a16)::(Vobject a16,Vobject a17)::(Vobject a17,Vobject a18)::(Vobject a18,Vobject a19)::(Vobject a19,Vobject a20)::nil) (nil).\n\n Definition ses13 :=Sat_equation_system (nil) ((Vobject a1,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top)))))))))))::(Vobject a2,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.top,Share.bot)))))))))))::(Vobject a3,Cobject (Share.top))::(Vobject a6,Cobject (Share.recompose (Share.recompose (Share.recompose (Share.top,Share.bot),Share.recompose (Share.top,Share.bot)),Share.recompose (Share.recompose (Share.bot,Share.top),Share.recompose (Share.bot,Share.top)))))::(Vobject a7,Cobject (Share.recompose (Share.top,Share.bot)))::(Vobject a8,Cobject (Share.top))::(Vobject a9,Cobject (Share.top))::(Vobject a10,Cobject (Share.top))::(Vobject a11,Cobject (Share.top))::(Vobject a12,Cobject (Share.top))::(Vobject a13,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top)))))))))))::(Vobject a14,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top)))))))))))::(Vobject a15,Cobject (Share.top))::(Vobject a17,Cobject (Share.top))::(Vobject a18,Cobject (Share.top))::(Vobject a19,Cobject (Share.top))::(Vobject a20,Cobject (Share.top))::nil) (nil).\n Definition ses14 :=Sat_equation_system (nil) ((Vobject a4,Vobject a5)::(Vobject a8,Vobject a9)::(Vobject a10,Vobject a11)::(Vobject a11,Vobject a12)::(Vobject a13,Vobject a14)::(Vobject a1,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top)))))))))))::(Vobject a2,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.top,Share.bot)))))))))))::(Vobject a3,Cobject (Share.top))::(Vobject a6,Cobject (Share.recompose (Share.recompose (Share.recompose (Share.top,Share.bot),Share.recompose (Share.top,Share.bot)),Share.recompose (Share.recompose (Share.bot,Share.top),Share.recompose (Share.bot,Share.top)))))::(Vobject a7,Cobject (Share.recompose (Share.top,Share.bot)))::(Vobject a8,Cobject (Share.top))::(Vobject a9,Cobject (Share.top))::(Vobject a10,Cobject (Share.top))::(Vobject a11,Cobject (Share.top))::(Vobject a12,Cobject (Share.top))::(Vobject a13,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top)))))))))))::(Vobject a14,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top)))))))))))::(Vobject a15,Cobject (Share.top))::(Vobject a17,Cobject (Share.top))::(Vobject a18,Cobject (Share.top))::(Vobject a19,Cobject (Share.top))::(Vobject a20,Cobject (Share.top))::nil) (nil).\n Definition ses15 :=Sat_equation_system (nil) ((Vobject a1,Vobject a2)::(Vobject a4,Vobject a5)::(Vobject a8,Vobject a9)::(Vobject a10,Vobject a11)::(Vobject a11,Vobject a12)::(Vobject a13,Vobject a14)::(Vobject a1,Vobject a20)::(Vobject a1,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top)))))))))))::(Vobject a2,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.top,Share.bot)))))))))))::(Vobject a3,Cobject (Share.top))::(Vobject a6,Cobject (Share.recompose (Share.recompose (Share.recompose (Share.top,Share.bot),Share.recompose (Share.top,Share.bot)),Share.recompose (Share.recompose (Share.bot,Share.top),Share.recompose (Share.bot,Share.top)))))::(Vobject a7,Cobject (Share.recompose (Share.top,Share.bot)))::(Vobject a8,Cobject (Share.top))::(Vobject a9,Cobject (Share.top))::(Vobject a10,Cobject (Share.top))::(Vobject a11,Cobject (Share.top))::(Vobject a12,Cobject (Share.top))::(Vobject a13,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top)))))))))))::(Vobject a14,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top)))))))))))::(Vobject a15,Cobject (Share.top))::(Vobject a17,Cobject (Share.top))::(Vobject a18,Cobject (Share.top))::(Vobject a19,Cobject (Share.top))::(Vobject a20,Cobject (Share.top))::nil) (nil).\n Definition ses16 :=Sat_equation_system (nil) ((Vobject a1,Cobject (Share.top))::(Vobject a2,Cobject (Share.top))::(Vobject a3,Cobject (Share.top))::(Vobject a4,Cobject (Share.top))::(Vobject a5,Cobject (Share.top))::(Vobject a6,Cobject (Share.top))::(Vobject a7,Cobject (Share.top))::(Vobject a8,Cobject (Share.top))::(Vobject a9,Cobject (Share.top))::(Vobject a1,Cobject (Share.recompose (Share.bot,Share.top)))::nil) (nil).\n Definition ses17 :=Sat_equation_system (nil) (nil) (nil).\n Definition is1 :=(Impl_equation_system (nil) (nil) (nil) ((Vobject a1,Vobject a2,Vobject a3)::nil),Impl_equation_system (nil) (nil) (nil) ((Vobject a1,Vobject a2,Vobject a3)::nil)).\n Definition is2 :=(Impl_equation_system (nil) (nil) ((Vobject a1,Vobject a2)::nil) ((Vobject a1,Vobject a2,Vobject a3)::nil),Impl_equation_system (nil) (nil) (nil) (nil)).\n Definition is3 :=(Impl_equation_system (nil) (nil) ((Vobject a1,Vobject a2)::nil) ((Vobject a1,Vobject a2,Vobject a3)::nil),Impl_equation_system (nil) (nil) ((Vobject a3,Cobject (Share.top))::nil) (nil)).\n Definition is4 :=(Impl_equation_system (nil) (nil) (nil) ((Vobject a1,Vobject a2,Cobject (Share.top))::(Vobject a2,Vobject a3,Cobject (Share.recompose (Share.top,Share.bot)))::(Vobject a1,Vobject a3,Cobject (Share.recompose (Share.bot,Share.top)))::nil),Impl_equation_system (nil) (nil) ((Vobject a1,Cobject (Share.recompose (Share.bot,Share.top)))::(Vobject a2,Cobject (Share.recompose (Share.top,Share.bot)))::nil) (nil)).\n Definition is5 :=(Impl_equation_system (nil) (nil) (nil) (nil),Impl_equation_system (nil) (nil) ((Vobject a1,Vobject a1)::(Vobject a2,Vobject a2)::(Vobject a3,Vobject a3)::(Vobject a4,Vobject a4)::(Vobject a5,Vobject a5)::(Vobject a6,Vobject a6)::(Vobject a7,Vobject a7)::(Vobject a8,Vobject a8)::(Vobject a9,Vobject a9)::(Vobject a10,Vobject a10)::nil) ((Cobject (Share.recompose (Share.top,Share.bot)),Cobject (Share.recompose (Share.bot,Share.top)),Cobject (Share.top))::nil)).\n Definition is6 :=(Impl_equation_system (nil) (nil) (nil) (nil),Impl_equation_system (a11::nil) (nil) ((Vobject a1,Vobject a1)::(Vobject a2,Vobject a2)::(Vobject a3,Vobject a3)::(Vobject a4,Vobject a4)::(Vobject a5,Vobject a5)::(Vobject a6,Vobject a6)::(Vobject a7,Vobject a7)::(Vobject a8,Vobject a8)::(Vobject a9,Vobject a9)::(Vobject a10,Vobject a10)::(Vobject a11,Cobject (Share.top))::nil) ((Cobject (Share.recompose (Share.top,Share.bot)),Cobject (Share.recompose (Share.bot,Share.top)),Cobject (Share.top))::nil)).\n Definition is7 :=(Impl_equation_system (nil) (nil) ((Vobject a1,Vobject a2)::(Vobject a3,Vobject a4)::(Vobject a5,Vobject a6)::(Vobject a1,Cobject (Share.recompose (Share.bot,Share.top)))::(Vobject a3,Cobject (Share.recompose (Share.top,Share.bot)))::nil) ((Vobject a1,Vobject a3,Cobject (Share.top))::(Vobject a5,Vobject a6,Vobject a7)::nil),Impl_equation_system (nil) (nil) (nil) (nil)).\n Definition is8 :=(Impl_equation_system (nil) (nil) ((Vobject a1,Vobject a2)::(Vobject a3,Vobject a4)::(Vobject a5,Vobject a6)::(Vobject a1,Cobject (Share.recompose (Share.bot,Share.top)))::(Vobject a3,Cobject (Share.recompose (Share.top,Share.bot)))::nil) ((Vobject a1,Vobject a3,Cobject (Share.top))::(Vobject a5,Vobject a6,Vobject a7)::(Vobject a1,Vobject a1,Vobject a2)::nil),Impl_equation_system (nil) (nil) (nil) ((Vobject a8,Vobject a9,Vobject a10)::nil)).\n Definition is9 :=(Impl_equation_system (nil) (nil) ((Vobject a1,Vobject a2)::(Vobject a3,Vobject a4)::(Vobject a5,Vobject a6)::(Vobject a1,Cobject (Share.recompose (Share.bot,Share.top)))::(Vobject a3,Cobject (Share.recompose (Share.top,Share.bot)))::nil) ((Vobject a1,Vobject a3,Cobject (Share.top))::(Vobject a5,Vobject a6,Vobject a7)::nil),Impl_equation_system (nil) (nil) ((Vobject a3,Cobject (Share.recompose (Share.top,Share.bot)))::nil) ((Vobject a4,Vobject a5,Vobject a3)::nil)).\n Definition is10 :=(Impl_equation_system (nil) (nil) ((Vobject a1,Vobject a2)::(Vobject a3,Vobject a4)::(Vobject a5,Vobject a6)::(Vobject a1,Cobject (Share.recompose (Share.bot,Share.top)))::(Vobject a3,Cobject (Share.recompose (Share.top,Share.bot)))::nil) ((Vobject a1,Vobject a3,Cobject (Share.top))::(Vobject a3,Vobject a4,Vobject a5)::(Vobject a5,Vobject a6,Vobject a7)::nil),Impl_equation_system (nil) (nil) ((Vobject a10,Vobject a11)::(Vobject a8,Cobject (Share.recompose (Share.top,Share.bot)))::nil) ((Vobject a8,Vobject a9,Vobject a10)::nil)).\n (*\n Definition is11 :=(Impl_equation_system (nil) (nil) (nil) ((Vobject a1,Vobject a2,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))))))))))))))))::nil),Impl_equation_system (nil) (nil) ((Vobject a2,Cobject (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.top,Share.bot),Share.top),Share.top),Share.top),Share.top),Share.top),Share.top),Share.top),Share.top),Share.top),Share.top),Share.top),Share.top),Share.top),Share.top),Share.top),Share.top)))::nil) (nil)).\n *)\n Definition is12 :=(Impl_equation_system (nil) (nil) ((Vobject a1,Vobject a3)::(Vobject a2,Vobject a3)::nil) ((Vobject a1,Vobject a2,Cobject (Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.bot,Share.top))))))))))))))))))::nil),Impl_equation_system (nil) (nil) ((Vobject a2,Cobject (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.top,Share.bot),Share.top),Share.top),Share.top),Share.top),Share.top),Share.top),Share.top),Share.top),Share.top),Share.top),Share.top),Share.top),Share.top),Share.top),Share.top),Share.top)))::nil) (nil)).\n Definition is13 :=(Impl_equation_system (nil) (nil) ((Vobject a1,Vobject a3)::nil) ((Vobject a1,Vobject a2,Cobject (Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.bot,Share.top))))))))))))))))))::(Vobject a3,Vobject a3,Vobject a3)::nil),Impl_equation_system (nil) (nil) ((Vobject a2,Cobject (Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.top,Share.recompose (Share.bot,Share.top))))))))))))))))))::nil) (nil)).\n Definition is14 :=(Impl_equation_system (nil) (nil) (nil) (nil),Impl_equation_system (nil) (nil) (nil) (nil)).\n Definition ses18 :=Sat_equation_system (nil) (nil) ((Vobject a,Vobject b,Cobject (Share.top))::(Vobject c,Vobject b,Cobject (Share.recompose (Share.top,Share.bot)))::(Vobject c,Vobject a,Cobject (Share.top))::nil).\n Definition ses19 :=Sat_equation_system (a::nil) ((Vobject a,Vobject a)::(Vobject a,Cobject (Share.top))::nil) ((Vobject a,Vobject a,Vobject a)::nil).\n Definition ses20 :=Sat_equation_system (a::nil) ((Vobject a,Vobject a)::(Vobject a,Cobject (Share.bot))::nil) ((Vobject a,Vobject a,Vobject a)::nil).\n Definition ses21 :=Sat_equation_system (a ::nil) (nil) ((Vobject a,Vobject b,Cobject (Share.top))::nil).\n Definition ses22 :=Sat_equation_system (a ::nil) (nil) ((Vobject a,Vobject b,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))))::nil).\n Definition ses23 :=Sat_equation_system (a ::nil) (nil) ((Vobject a,Vobject b,Cobject (Share.top))::(Vobject a,Vobject c,Cobject (Share.top))::(Vobject b,Vobject c,Cobject (Share.top))::nil).\n Definition ses24 :=Sat_equation_system (a ::nil) (nil) ((Vobject a,Vobject b,Cobject (Share.top))::(Vobject a,Vobject c,Cobject (Share.top))::(Vobject b,Vobject c,Cobject (Share.top))::(Vobject a,Vobject a,Vobject a)::nil).\n Definition ses25 :=Sat_equation_system (a ::nil) (nil) ((Vobject a,Vobject b,Cobject (Share.top))::(Vobject a,Vobject c,Cobject (Share.top))::(Vobject b,Vobject c,Cobject (Share.top))::(Vobject a,Vobject b,Vobject c)::nil).\n Definition ses26 :=Sat_equation_system (a1 ::nil) (nil) ((Vobject a1,Vobject a2,Cobject (Share.top))::(Vobject a3,Vobject a4,Vobject a1)::(Vobject a5,Vobject a6,Vobject a3)::(Vobject a7,Vobject a8,Vobject a5)::(Vobject a9,Vobject a10,Vobject a7)::(Vobject a11,Vobject a12,Vobject a9)::(Vobject a13,Vobject a14,Vobject a11)::(Vobject a15,Vobject a16,Vobject a13)::nil).\n Definition ses27 :=Sat_equation_system (a1 ::nil) ((Vobject a1,Vobject a16)::nil) ((Vobject a1,Vobject a2,Cobject (Share.top))::(Vobject a3,Vobject a4,Vobject a1)::(Vobject a5,Vobject a6,Vobject a3)::(Vobject a7,Vobject a8,Vobject a5)::(Vobject a9,Vobject a10,Vobject a7)::(Vobject a11,Vobject a12,Vobject a9)::(Vobject a13,Vobject a14,Vobject a11)::(Vobject a15,Vobject a16,Vobject a13)::nil).\n Definition ses28 :=Sat_equation_system (a1 ::nil) ((Vobject a1,Vobject a3)::(Vobject a2,Vobject a4)::(Vobject a5,Cobject (Share.top))::nil) ((Vobject a1,Vobject a4,Vobject a5)::(Vobject a2,Vobject a3,Vobject a6)::nil).\n Definition ses29 :=Sat_equation_system (a1 ::nil) ((Vobject a1,Vobject a2)::(Vobject a3,Cobject (Share.bot))::(Vobject a4,Cobject (Share.top))::(Vobject a5,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top)))))::nil) ((Vobject a1,Vobject a5,Vobject a6)::(Vobject a2,Vobject a7,Vobject a3)::nil).\n Definition ses30 :=Sat_equation_system (a1::nil) ((Vobject a1,Vobject a2)::(Vobject a3,Cobject (Share.bot))::(Vobject a4,Cobject (Share.top))::(Vobject a5,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top)))))::nil) ((Vobject a1,Vobject a5,Vobject a6)::(Vobject a2,Vobject a7,Vobject a3)::nil).\n Definition ses31 :=Sat_equation_system (nil) ((Vobject a1,Vobject a2)::(Vobject a3,Cobject (Share.bot))::(Vobject a4,Cobject (Share.top))::(Vobject a5,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top)))))::nil) ((Vobject a1,Vobject a5,Vobject a6)::(Vobject a2,Vobject a7,Vobject a3)::nil).\n Definition ses32 :=Sat_equation_system (a1::nil) (nil) ((Vobject a1,Vobject a2,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))))))))::(Vobject a1,Vobject a3,Cobject (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.top,Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot)))::nil).\n Definition ses33 :=Sat_equation_system (nil) (nil) ((Vobject a1,Vobject a2,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))))))))::(Vobject a1,Vobject a3,Cobject (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.top,Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot)))::nil).\n Definition ses34 :=Sat_equation_system (a1::nil) ((Vobject a1,Vobject a2)::(Vobject a2,Vobject a3)::(Vobject a3,Vobject a4)::(Vobject a4,Vobject a5)::(Vobject a5,Vobject a6)::(Vobject a6,Vobject a7)::(Vobject a7,Vobject a8)::nil) (nil).\n Definition ses35 :=Sat_equation_system (a1::nil) ((Vobject a1,Vobject a2)::(Vobject a2,Vobject a3)::(Vobject a3,Vobject a4)::(Vobject a4,Vobject a5)::(Vobject a5,Vobject a6)::(Vobject a6,Vobject a7)::(Vobject a7,Vobject a8)::nil) ((Vobject a1,Vobject a4,Vobject a8)::nil).\n Definition ses36 :=Sat_equation_system (nil) (nil) ((Vobject a1,Vobject a2,Cobject (Share.top))::(Vobject a2,Vobject a3,Cobject (Share.recompose (Share.bot,Share.top)))::(Vobject a3,Vobject a4,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))::(Vobject a4,Vobject a5,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top)))))::(Vobject a5,Vobject a6,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))))::(Vobject a6,Vobject a7,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top)))))))::(Vobject a7,Vobject a8,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))))))::nil).\n Definition ses37 :=Sat_equation_system (a1 ::nil) (nil) ((Vobject a1,Vobject a2,Cobject (Share.top))::(Vobject a2,Vobject a3,Cobject (Share.recompose (Share.bot,Share.top)))::(Vobject a3,Vobject a4,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))::(Vobject a4,Vobject a5,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top)))))::(Vobject a5,Vobject a6,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))))::(Vobject a6,Vobject a7,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top)))))))::(Vobject a7,Vobject a8,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))))))::nil).\n Definition ses38 :=Sat_equation_system (a1 ::nil) ((Vobject a1,Vobject a8)::nil) ((Vobject a1,Vobject a2,Cobject (Share.top))::(Vobject a2,Vobject a3,Cobject (Share.recompose (Share.bot,Share.top)))::(Vobject a3,Vobject a4,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))::(Vobject a4,Vobject a5,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top)))))::(Vobject a5,Vobject a6,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))))::(Vobject a6,Vobject a7,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top)))))))::(Vobject a7,Vobject a8,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))))))::nil).\n Definition ses39 :=Sat_equation_system (nil) (nil) ((Vobject a1,Vobject a2,Cobject (Share.top))::(Vobject a2,Vobject a3,Cobject (Share.recompose (Share.top,Share.bot)))::(Vobject a3,Vobject a4,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))::nil).\n Definition ses40 :=Sat_equation_system (a1 ::nil) (nil) ((Vobject a1,Vobject a2,Cobject (Share.top))::(Vobject a2,Vobject a3,Cobject (Share.recompose (Share.top,Share.bot)))::(Vobject a3,Vobject a4,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))::nil).\n Definition ses41 :=Sat_equation_system (a1 ::nil) (nil) ((Vobject a1,Vobject a2,Cobject (Share.top))::(Vobject a2,Vobject a3,Cobject (Share.recompose (Share.top,Share.bot)))::(Vobject a3,Vobject a4,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))::nil).\n Definition ses42 :=Sat_equation_system (nil) (nil) ((Vobject a1,Vobject a1,Vobject a1)::(Vobject a2,Vobject a2,Vobject a2)::(Vobject a1,Vobject a2,Vobject a3)::nil).\n Definition ses43 :=Sat_equation_system (a1 ::nil) (nil) ((Vobject a1,Vobject a1,Vobject a1)::(Vobject a2,Vobject a2,Vobject a2)::(Vobject a1,Vobject a2,Vobject a3)::nil).\n Definition ses44 :=Sat_equation_system (a ::nil) ((Vobject a,Vobject d)::(Vobject b,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))::nil) ((Vobject b,Vobject d,Vobject c)::(Vobject a,Vobject b,Vobject c)::nil).\n Definition ses45 :=Sat_equation_system (a ::nil) ((Vobject a,Vobject d)::(Vobject b,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))::nil) ((Vobject b,Vobject d,Vobject c)::(Vobject a,Vobject b,Vobject c)::(Vobject a,Vobject c,Vobject b)::nil).\n Definition ses46 :=Sat_equation_system (nil) ((Vobject a,Vobject b)::(Vobject c,Vobject a)::(Vobject d,Vobject b)::(Vobject c,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))))::(Vobject d,Cobject (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.top,Share.bot),Share.bot),Share.bot),Share.bot)))::nil) ((Vobject a,Vobject a,Vobject b)::(Vobject c,Vobject d,Vobject a)::nil).\n Definition ses47 :=Sat_equation_system (a ::nil) ((Vobject a,Vobject b)::(Vobject c,Vobject a)::(Vobject d,Vobject b)::(Vobject c,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))))::(Vobject d,Cobject (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.top,Share.bot),Share.bot),Share.bot),Share.bot)))::nil) ((Vobject a,Vobject a,Vobject b)::(Vobject c,Vobject d,Vobject a)::nil).\n Definition ses48 :=Sat_equation_system (a ::nil) ((Vobject a,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top)))))))))::(Vobject b,Cobject (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.top,Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot)))::(Vobject c,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top)))))))))::(Vobject d,Cobject (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.top,Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot)))::nil) (nil).\n Definition ses49 :=Sat_equation_system (a ::nil) ((Vobject a,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top)))))))))::(Vobject b,Cobject (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.top,Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot)))::(Vobject c,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top)))))))))::(Vobject d,Cobject (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.top,Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot),Share.bot)))::nil) ((Vobject a,Vobject b,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top)))))))))))::(Vobject c,Vobject d,Cobject (Share.top))::nil).\n Definition ses50 :=Sat_equation_system (a1 ::nil) ((Vobject a1,Vobject a2)::(Vobject a3,Vobject a4)::(Vobject a5,Vobject a6)::(Vobject a7,Vobject a8)::nil) ((Vobject a1,Vobject a3,Vobject a5)::(Vobject a2,Vobject a4,Vobject a6)::nil).\n Definition ses51 :=Sat_equation_system (a1 ::nil) ((Vobject a1,Vobject a2)::(Vobject a3,Vobject a4)::(Vobject a5,Vobject a6)::(Vobject a7,Vobject a8)::nil) ((Vobject a1,Vobject a3,Vobject a5)::(Vobject a2,Vobject a4,Vobject a6)::(Vobject a7,Vobject a8,Vobject a1)::nil).\n Definition ses52 :=Sat_equation_system (a1 ::nil) ((Vobject a1,Vobject a2)::(Vobject a3,Vobject a4)::(Vobject a5,Vobject a6)::(Vobject a7,Vobject a8)::nil) ((Vobject a1,Vobject a3,Vobject a5)::(Vobject a2,Vobject a4,Vobject a6)::(Vobject a7,Vobject a8,Vobject a8)::nil).\n Definition ses53 :=Sat_equation_system (a1 ::nil) ((Vobject a1,Vobject a2)::(Vobject a3,Vobject a4)::(Vobject a5,Vobject a6)::(Vobject a7,Vobject a8)::nil) ((Vobject a1,Vobject a3,Vobject a5)::(Vobject a2,Vobject a4,Vobject a6)::(Vobject a7,Vobject a8,Vobject a8)::nil).\n Definition is15 :=(Impl_equation_system (nil) (a::nil) (nil) ((Vobject a,Vobject a,Vobject a)::nil),Impl_equation_system (nil) (nil) (nil) ((Vobject a1,Vobject a2,Vobject a3)::nil)).\n Definition is16 :=(Impl_equation_system (nil) (a1 ::nil) ((Vobject a9,Cobject (Share.recompose (Share.bot,Share.top)))::nil) ((Vobject a1,Vobject a2,Vobject a9)::(Vobject a3,Vobject a4,Vobject a1)::(Vobject a5,Vobject a6,Vobject a3)::(Vobject a7,Vobject a8,Vobject a5)::nil),Impl_equation_system (nil) (a9::nil) (nil) ((Vobject a1,Vobject a2,Cobject (Share.recompose (Share.bot,Share.top)))::nil)).\n Definition is17 :=(Impl_equation_system (nil) (a1::nil) (nil) (nil),Impl_equation_system (nil) (a1::nil) (nil) (nil)).\n Definition is18 :=(Impl_equation_system (nil) (a1::nil) (nil) (nil),Impl_equation_system (nil) (a2::nil) (nil) (nil)).\n Definition is19 :=(Impl_equation_system (nil) (a1::nil) (nil) ((Vobject a1,Vobject a2,Vobject a3)::nil),Impl_equation_system (nil) (a3::nil) (nil) (nil)).\n Definition is20 :=(Impl_equation_system (nil) (a1::nil) (nil) ((Vobject a1,Vobject a2,Vobject a3)::nil),Impl_equation_system (nil) (a2::nil) (nil) (nil)).\n Definition is21 :=(Impl_equation_system (nil) (a1::nil) (nil) ((Vobject a1,Vobject a2,Vobject a3)::(Vobject a3,Vobject a4,Vobject a5)::(Vobject a5,Vobject a6,Vobject a7)::(Vobject a7,Vobject a8,Vobject a9)::(Vobject a9,Vobject a10,Vobject a11)::(Vobject a11,Vobject a12,Vobject a13)::(Vobject a13,Vobject a14,Vobject a15)::nil),Impl_equation_system (nil) (a15::nil) (nil) (nil)).\n Definition is22 :=(Impl_equation_system (nil) (a1::nil) (nil) ((Vobject a1,Vobject a2,Vobject a3)::(Vobject a3,Vobject a4,Vobject a5)::(Vobject a5,Vobject a6,Vobject a7)::(Vobject a7,Vobject a8,Vobject a9)::(Vobject a9,Vobject a10,Vobject a11)::(Vobject a11,Vobject a12,Vobject a13)::(Vobject a13,Vobject a14,Vobject a15)::nil),Impl_equation_system (nil) (a14::nil) (nil) (nil)).\n Definition is23 :=(Impl_equation_system (nil) (nil) (nil) ((Vobject a1,Vobject a1,Vobject a1)::(Vobject a2,Vobject a2,Vobject a2)::(Vobject a1,Vobject a2,Vobject a3)::nil),Impl_equation_system (nil) (nil) ((Vobject a3,Cobject (Share.bot))::nil) (nil)).\n Definition is24 :=(Impl_equation_system (nil) (nil) (nil) ((Vobject a1,Vobject a1,Vobject a1)::(Vobject a2,Vobject a2,Vobject a2)::(Vobject a1,Vobject a2,Vobject a3)::nil),Impl_equation_system (nil) (a3::nil) (nil) (nil)).\n Definition is25 :=(Impl_equation_system (nil) (nil) ((Vobject a,Cobject (Share.bot))::nil) (nil),Impl_equation_system (nil) (a::nil) (nil) (nil)).\n Definition is26 :=(Impl_equation_system (nil) (a::nil) ((Vobject a,Cobject (Share.bot))::nil) (nil),Impl_equation_system (nil) (a::nil) (nil) (nil)).\n Definition is27 :=(Impl_equation_system (nil) (nil) (nil) ((Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))),Vobject a,Vobject b)::nil),Impl_equation_system (nil) (a::nil) (nil) (nil)).\n Definition is28 :=(Impl_equation_system (nil) (nil) (nil) ((Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))),Vobject a,Vobject b)::nil),Impl_equation_system (nil) (b::nil) (nil) (nil)).\n Definition is29 :=(Impl_equation_system (nil) (a9::nil) (nil) ((Vobject a1,Vobject a2,Vobject a3)::(Vobject a3,Vobject a4,Vobject a5)::(Vobject a5,Vobject a6,Vobject a7)::(Vobject a7,Vobject a8,Vobject a9)::nil),Impl_equation_system (nil) (a1::nil) (nil) (nil)).\n Definition is30 :=(Impl_equation_system (nil) (a1::nil) (nil) ((Vobject a1,Vobject a2,Vobject a3)::(Vobject a3,Vobject a4,Vobject a5)::(Vobject a5,Vobject a6,Vobject a7)::(Vobject a7,Vobject a8,Vobject a9)::nil),Impl_equation_system (nil) (a9::nil) (nil) (nil)).\n Definition is31 :=(Impl_equation_system (nil) (a9::nil) (nil) ((Vobject a1,Vobject a2,Vobject a3)::(Vobject a3,Vobject a4,Vobject a5)::(Vobject a5,Vobject a6,Vobject a7)::(Vobject a7,Vobject a8,Vobject a9)::(Vobject a8,Vobject a8,Vobject a8)::(Vobject a6,Vobject a6,Vobject a6)::(Vobject a4,Vobject a4,Vobject a4)::(Vobject a2,Vobject a2,Vobject a2)::nil),Impl_equation_system (nil) (a1::nil) (nil) (nil)).\n Definition is32 :=(Impl_equation_system (nil) (a::nil) (nil) ((Vobject a,Vobject a,Vobject a)::nil),Impl_equation_system (nil) (a1 ::nil) ((Vobject a5,Vobject a6)::(Vobject a2,Vobject a4)::(Vobject a4,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top)))))::nil) ((Vobject a1,Vobject a3,Vobject a8)::(Vobject a2,Vobject a8,Vobject a4)::nil)).\n Definition is33 :=(Impl_equation_system (nil) (nil) (nil) ((Vobject a,Vobject a,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))))))))::nil),Impl_equation_system (nil) (a::nil) (nil) (nil)).\n Definition is34 :=(Impl_equation_system (nil) (nil) (nil) ((Vobject a,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))))))),Vobject a)::nil),Impl_equation_system (nil) (a::nil) (nil) (nil)).\n Definition is35 :=(Impl_equation_system (nil) (nil) (nil) ((Cobject (Share.recompose (Share.bot,Share.top)),Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.top,Share.bot))))),Vobject a)::nil),Impl_equation_system (nil) (a::nil) (nil) (nil)).\n Definition is36 :=(Impl_equation_system (nil) (nil) (nil) (nil),Impl_equation_system (nil) (a ::nil) ((Vobject a,Vobject c)::(Vobject a,Cobject (Share.top))::(Vobject b,Cobject (Share.top))::nil) ((Vobject a,Vobject b,Vobject c)::nil)).\n Definition is37 :=(Impl_equation_system (nil) (a ::nil) ((Vobject a,Cobject (Share.recompose (Share.top,Share.bot)))::(Vobject b,Cobject (Share.recompose (Share.bot,Share.top)))::nil) ((Vobject a,Vobject b,Vobject c)::nil),Impl_equation_system (nil) (c::nil) ((Vobject c,Cobject (Share.top))::nil) (nil)).\n Definition is38 :=(Impl_equation_system (nil) (a ::nil) ((Vobject a,Cobject (Share.recompose (Share.top,Share.bot)))::(Vobject b,Cobject (Share.recompose (Share.bot,Share.top)))::nil) ((Vobject a,Vobject b,Vobject c)::nil),Impl_equation_system (nil) (c::nil) ((Vobject c,Cobject (Share.top))::nil) ((Vobject a,Vobject b,Vobject a)::nil)).\n Definition is39 :=(Impl_equation_system (nil) (a ::nil) ((Vobject a,Cobject (Share.recompose (Share.top,Share.bot)))::(Vobject b,Cobject (Share.recompose (Share.bot,Share.top)))::nil) ((Vobject a,Vobject b,Vobject c)::nil),Impl_equation_system (nil) (c::nil) ((Vobject c,Cobject (Share.top))::nil) ((Vobject a,Vobject b,Vobject c)::nil)).\n Definition is40 :=(Impl_equation_system (nil) (a1::nil) ((Vobject a1,Vobject a2)::nil) (nil),Impl_equation_system (nil) (a2::nil) (nil) (nil)).\n Definition is41 :=(Impl_equation_system (nil) (nil) (nil) ((Vobject a1,Vobject a2,Cobject (Share.top))::(Vobject a3,Vobject a4,Vobject a1)::(Vobject a5,Vobject a6,Vobject a3)::(Vobject a7,Vobject a8,Vobject a5)::nil),Impl_equation_system (nil) (a1 ::nil) (nil) (nil)).\n Definition is42 :=(Impl_equation_system (nil) (a8::nil) (nil) ((Vobject a1,Vobject a2,Cobject (Share.top))::(Vobject a3,Vobject a4,Vobject a1)::(Vobject a5,Vobject a6,Vobject a3)::(Vobject a7,Vobject a8,Vobject a5)::nil),Impl_equation_system (nil) (a5 ::nil) (nil) (nil)).\n Definition is43 :=(Impl_equation_system (nil) (a8::nil) (nil) ((Vobject a1,Vobject a2,Cobject (Share.top))::(Vobject a3,Vobject a4,Vobject a1)::(Vobject a5,Vobject a6,Vobject a3)::(Vobject a7,Vobject a8,Vobject a5)::nil),Impl_equation_system (nil) (a2::nil) (nil) (nil)).\n Definition is44 :=(Impl_equation_system (nil) (a1 ::nil) (nil) ((Vobject a2,Vobject a2,Vobject a1)::nil),Impl_equation_system (nil) (a2 ::nil) (nil) (nil)).\n Definition is45 :=(Impl_equation_system (nil) (a1::nil) (nil) ((Vobject a2,Vobject a3,Vobject a1)::nil),Impl_equation_system (nil) (a2::nil) (nil) (nil)).\n Definition is46 :=(Impl_equation_system (nil) (nil) (nil) ((Vobject a1,Vobject a2,Vobject a3)::(Vobject a3,Vobject a2,Vobject a5)::(Vobject a3,Vobject a5,Vobject a2)::(Vobject a1,Vobject a4,Vobject a6)::(Vobject a5,Vobject a3,Vobject a8)::nil),Impl_equation_system (nil) (a1::nil) (nil) (nil)).\n Definition is47 :=(Impl_equation_system (nil) (nil) (nil) ((Cobject (Share.top),Cobject (Share.top),Cobject (Share.top))::nil),Impl_equation_system (nil) (a1 ::nil) ((Vobject a1,Vobject a8)::(Vobject a1,Cobject (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.top,Share.bot),Share.bot),Share.bot),Share.bot)))::(Vobject a8,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))))::nil) ((Vobject a3,Vobject a4,Vobject a5)::nil)).\n Definition is48 :=(Impl_equation_system (nil) (nil) (nil) ((Cobject (Share.recompose (Share.bot,Share.top)),Cobject (Share.recompose (Share.top,Share.bot)),Cobject (Share.top))::nil),Impl_equation_system (nil) (a1 ::nil) ((Vobject a1,Vobject a8)::(Vobject a1,Cobject (Share.recompose (Share.recompose (Share.recompose (Share.recompose (Share.top,Share.bot),Share.bot),Share.bot),Share.bot)))::(Vobject a8,Cobject (Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.recompose (Share.bot,Share.top))))))::nil) ((Vobject a3,Vobject a4,Vobject a5)::nil)).\n Definition is49 :=(Impl_equation_system (nil) (nil) (nil) ((Cobject (Share.recompose (Share.bot,Share.top)),Cobject (Share.recompose (Share.top,Share.bot)),Cobject (Share.top))::nil),Impl_equation_system (nil) (nil) (nil) ((Cobject (Share.recompose (Share.recompose (Share.bot,Share.top),Share.recompose (Share.bot,Share.top))),Cobject (Share.recompose (Share.recompose (Share.top,Share.bot),Share.recompose (Share.top,Share.bot))),Cobject (Share.top))::nil)).\n\n Definition l := \n (ses1::ses2::ses3::ses4::ses5::ses6::(*ses7::ses8::ses9::*)ses10::\n  ses11::ses12::ses13::ses14::ses15::ses16::ses17::ses18::ses19::ses20::\n  ses21::ses22::ses23::ses24::ses25::ses26::ses27::ses28::ses29::ses30::\n  ses31::ses32::ses33::ses34::ses35::ses36::ses37::ses38::ses39::ses40::\n  ses41::ses42::ses43::ses44::ses45::ses46::ses47::ses48::ses49::ses50::\n  ses51::ses52::ses53::nil).\n (*\n Time Eval compute in (map SATsolver l).\n *)\n (*16.1s*)\n\n Definition l' :=\n (\n is1::is2::is3::is4::is5::is6::is7::is8::is9::is10::\n (*is11::*)is12::is13::is14::is15::is16::is17::is18::is19::is20::\n is21::is22::is23::is24::is25::is26::is27::is28::is29::is30::\n is31::is32::is33::is34::is35::is36::is37::is38::is39::is40::\n is41::is42::is43::is44::is45::is46::is47::is48::is49::nil\n ).\n (*\n Time Eval compute in (map IMPLsolver l').\n *)\n (*8.9s*)\n\nEnd Tester.\n\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/test/coq_tests.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.2638512725916295}}
{"text": "(*\nCopyright © 2009 Valentin Blot\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis proof and associated documentation files (the \"Proof\"), to deal in\nthe Proof without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Proof, and to permit persons to whom the Proof is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Proof.\n\nTHE PROOF IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE PROOF OR THE USE OR OTHER DEALINGS IN THE PROOF.\n*)\nRequire Import CPoly_Degree.\nRequire Import CRing_Homomorphisms.\nRequire Import CoRN.model.ordfields.Qordfield.\nRequire Import CauchySeq.\nRequire Import Q_in_CReals.\n\nRequire Import CPoly_Euclid RingClass CRingClass.\nRequire Import Q_can nat_Q_lists RX_deg RX_div QX_root_loc.\n\nSection Z_Q.\n\nLet QX := cpoly_cring Q_as_CRing.\nAdd Ring q_r : (r_rt (Ring:=CRing_is_Ring Q_as_CRing)).\nAdd Ring qx_r : (r_rt (Ring:=CRing_is_Ring (cpoly_cring Q_as_CRing))).\n\nLet QX_dec := RX_dec Q_as_CRing Q_dec.\nLet QX_deg := RX_deg Q_as_CRing Q_dec.\n\nFixpoint QX_test_list (P : QX) (l : list Q_as_CRing) : option Q_as_CRing :=\n  match l with\n    | nil => None\n    | cons q l => match Q_dec (P ! q) [0] with inl _ => Some q | inr _ => QX_test_list P l end\n  end.\n\nLemma QX_test_list_spec_none : forall P l, QX_test_list P l = None ->\n        forall q : Q_as_CRing, In q l -> P ! q [#] [0].\nProof.\n induction l.\n  intros; contradiction.\n unfold QX_test_list.\n case (Q_dec P ! a [0]).\n  intros; discriminate.\n fold (QX_test_list P l).\n intros Hap Hnone q.\n simpl (In q (a::l)).\n case (Q_dec a q).\n  intros Haq Hin Hval.\n  destruct Hap.\n  rewrite -> Haq; assumption.\n intros.\n apply IHl.\n  assumption.\n destruct H.\n  destruct c; rewrite H; reflexivity.\n assumption.\nQed.\n\nLemma QX_test_list_spec_some : forall P l x, QX_test_list P l = Some x ->\n        P ! x [=] [0].\nProof.\n induction l.\n  intros; discriminate.\n unfold QX_test_list.\n fold (QX_test_list P l).\n case (Q_dec P ! a [0]); [|intro; assumption].\n intros.\n injection H; intro.\n rewrite <- H0; assumption.\nQed.\n\nLet P0 (P : QX) := nth_coeff 0 (QX_ZX.qx2zx P).\nLet Pn (P : QX) := nth_coeff (QX_deg P) (QX_ZX.qx2zx P).\n\nDefinition QX_find_root (P : QX) : option Q_as_CRing :=\n    match Q_dec (P ! [0]) [0] with inl _ => Some [0] | inr _ => QX_test_list P (list_Q (P0 P) (Pn P)) end.\n\nLemma QX_find_root_spec_none : forall P, QX_find_root P = None -> forall q : Q_as_CRing, P ! q [#] [0].\nProof.\n intro P; unfold QX_find_root.\n case (Q_dec P ! [0] [0]).\n  intros; discriminate.\n intros Hap Hnone q.\n assert (forall x y : Q_as_CRing, {x = y} + {x <> y}).\n  clear; intros x y.\n  destruct x; destruct y; simpl.\n  case (Z.eq_dec Qnum Qnum0); case (Z.eq_dec Qden Qden0); intros H1 H2.\n     left; f_equal; [assumption|injection H1; tauto].\n    right; intro H3; injection H3; intros; destruct H1; f_equal; assumption.\n   right; intro H3; injection H3; intros; destruct H2; assumption.\n  right; intro H3; injection H3; intros; destruct H2; assumption.\n destruct (In_dec X (Q_can q) (list_Q (P0 P) (Pn P))).\n  intro H; rewrite -> (Q_can_spec q) in H; revert H.\n  apply (QX_test_list_spec_none _ _ Hnone _ i).\n intro Hval; apply n.\n apply QX_root_loc; assumption.\nQed.\n\nLemma QX_find_root_spec_some : forall P x, QX_find_root P = Some x -> P ! x [=] [0].\nProof.\n intros P x; unfold QX_find_root.\n case (Q_dec P ! [0] [0]).\n  intros H1 H2; injection H2; intro H3; rewrite <- H3; assumption.\n intro Hap; apply QX_test_list_spec_some.\nQed.\n\nLemma QX_integral : forall p q : QX, p [#] [0] -> q [#] [0] -> p[*]q [#] [0].\nProof.\n intros p q Hp Hq.\n apply (nth_coeff_strext _ (QX_deg p + QX_deg q)).\n simpl (nth_coeff (QX_deg p + QX_deg q) ([0]:QX)).\n cut (degree (QX_deg p + QX_deg q) (p[*]q)).\n  intro H; apply H.\n apply (degree_mult Q_as_CField).\n  apply RX_deg_spec; assumption.\n apply RX_deg_spec; assumption.\nQed.\n\nLemma QX_deg_mult : forall p q, p [#] [0] -> q [#] [0] ->\n           QX_deg (p[*]q) = QX_deg p + QX_deg q.\nProof.\n intros p q Hp Hq.\n set (RX_deg_spec _ Q_dec _ Hp).\n set (RX_deg_spec _ Q_dec _ Hq).\n set (degree_mult Q_as_CField _ _ _ _ d d0).\n fold QX_deg in d1.\n apply (degree_inj _ (p[*]q)); [|assumption].\n apply RX_deg_spec.\n apply QX_integral; assumption.\nQed.\n\nLemma QX_div_deg0 : forall (p : QX) (a : Q_as_CRing),\n              QX_deg p <> 0 -> RX_div _ p a [#] [0].\nProof.\n intros p a Hdeg.\n case (QX_dec (RX_div _ p a) [0]); [|tauto].\n intro Heq; destruct Hdeg; revert Heq.\n unfold RX_div.\n destruct (cpoly_div p (_X_monic _ a)) as [[q r] _ [s [d s0]]].\n unfold fst, snd in *.\n intro Hq.\n rewrite -> Hq in s.\n assert (H : p [=] r); [rewrite -> s; unfold cg_minus; unfold QX; ring|].\n unfold QX_deg; rewrite (RX_deg_wd _ Q_dec _ _ H); fold QX_deg.\n destruct (_X_monic _ a).\n destruct (degree_le_zero _ _ (d _ H1)).\n unfold QX_deg; rewrite (RX_deg_wd _ Q_dec _ _ s1).\n rewrite RX_deg_c_; reflexivity.\nQed.\n\nLemma QX_div_deg : forall (p : QX) (a : Q_as_CRing),\n          QX_deg p <> 0 -> QX_deg p = S (QX_deg (RX_div _ p a)).\nProof.\n intros p a Hdeg.\n case_eq (QX_deg p).\n  intro; destruct Hdeg; assumption.\n intros n Heq.\n f_equal.\n revert Heq.\n unfold QX_deg; rewrite (RX_deg_wd _ Q_dec _ _ (RX_div_spec _ p a)).\n rewrite RX_deg_sum.\n  rewrite max_comm.\n  rewrite -> QX_deg_mult.\n    unfold QX_deg; rewrite RX_deg_minus.\n     rewrite RX_deg_c_, RX_deg_x_, RX_deg_c_; fold QX_deg.\n     simpl; rewrite plus_comm; simpl.\n     intro H; injection H; symmetry; assumption.\n    rewrite RX_deg_x_, RX_deg_c_; discriminate.\n   apply QX_div_deg0; assumption.\n  right; left; discriminate.\n rewrite RX_deg_c_.\n rewrite -> QX_deg_mult.\n   unfold QX_deg; rewrite RX_deg_minus.\n    rewrite RX_deg_x_, RX_deg_c_.\n    rewrite plus_comm; discriminate.\n   rewrite RX_deg_x_, RX_deg_c_; discriminate.\n  apply QX_div_deg0; assumption.\n right; left; discriminate.\nQed.\n\nFixpoint QX_extract_roots_rec (n : nat) (P : QX) :=\n  match n with\n    | O => P\n    | S n =>\n      match QX_find_root P with\n        | None => P\n        | Some x => QX_extract_roots_rec n (RX_div _ P x)\n      end\n  end.\n\nDefinition QX_extract_roots (P : QX) := QX_extract_roots_rec (QX_deg P) P.\n\nLemma QX_extract_roots_spec_rat : forall P a,\n       P [#] [0] -> (QX_extract_roots P) ! a [#] [0].\nProof.\n unfold QX_extract_roots.\n intros P a; remember (QX_deg P) as n; revert P Heqn.\n induction n.\n  intros P Hdeg Hap; unfold QX_extract_roots_rec.\n  destruct (RX_deg_spec _ Q_dec _ Hap).\n  fold QX_deg in d; rewrite <- Hdeg in d.\n  destruct (degree_le_zero _ _ d).\n  case (Q_dec P ! a [0]); [|tauto].\n  intro Heq; destruct (ap_imp_neq _ _ _ Hap); clear Hap; revert Heq.\n  rewrite -> s, c_apply; intro H; rewrite -> H; split; [reflexivity|apply I].\n unfold QX_extract_roots_rec.\n intros P Hdeg Hap.\n case_eq (QX_find_root P).\n  intros x Hsome; fold (QX_extract_roots_rec n (RX_div _ P x)).\n  apply IHn.\n   apply eq_add_S.\n   rewrite <- QX_div_deg; [assumption|].\n   rewrite <- Hdeg; discriminate.\n  case (QX_dec (RX_div _ P x) [0]); [|tauto].\n  intro Heq; apply QX_div_deg0.\n  rewrite <- Hdeg; discriminate.\n intro; apply QX_find_root_spec_none; assumption.\nQed.\n\nDefinition inj_Q_fun := Build_CSetoid_fun _ _ _ (inj_Q_strext IR).\nLemma inj_Q_pres_plus : fun_pres_plus _ _ inj_Q_fun.\nProof. intros x y; apply inj_Q_plus. Qed.\nLemma inj_Q_pres_unit : fun_pres_unit _ _ inj_Q_fun.\nProof. apply inj_Q_One. Qed.\nLemma inj_Q_pres_mult : fun_pres_mult _ _ inj_Q_fun.\nProof. intros x y; apply inj_Q_mult. Qed.\nDefinition inj_Q_rh := Build_RingHom _ _ inj_Q_fun inj_Q_pres_plus inj_Q_pres_mult inj_Q_pres_unit.\nDefinition inj_QX_rh := cpoly_map inj_Q_rh.\n\nLemma QX_extract_roots_spec_nrat : forall (P : QX) (x : IR),\n      (forall y : Q_as_CRing, x [~=] (inj_Q_rh y)) ->\n         (inj_QX_rh P) ! x [=] [0] -> (inj_QX_rh (QX_extract_roots P)) ! x [=] [0].\nProof.\n intros P x Hx; unfold QX_extract_roots.\n remember (QX_deg P) as n; revert P Heqn; induction n.\n  intros; unfold QX_extract_roots_rec; assumption.\n intros P Hdeg Hval; unfold QX_extract_roots_rec; fold (QX_extract_roots_rec).\n case_eq (QX_find_root P); [|intro; assumption].\n intros y Hsome.\n apply IHn.\n  apply eq_add_S.\n  rewrite Hdeg; apply QX_div_deg.\n  rewrite <- Hdeg; discriminate.\n clear IHn; revert Hval.\n rewrite -> (RX_div_spec _ P y) at 1.\n rewrite -> rh_pres_plus.\n rewrite -> rh_pres_mult.\n rewrite -> rh_pres_minus.\n rewrite -> (cpoly_map_X _ _ inj_Q_rh).\n rewrite -> (cpoly_map_C _ _ inj_Q_rh).\n rewrite -> (cpoly_map_C _ _ inj_Q_rh).\n rewrite -> plus_apply.\n rewrite -> mult_apply.\n rewrite -> minus_apply.\n rewrite -> x_apply.\n rewrite -> c_apply.\n rewrite -> c_apply.\n rewrite -> (QX_find_root_spec_some _ _ Hsome).\n rewrite -> rh_pres_zero.\n rewrite -> cm_rht_unit.\n rewrite -> mult_commutes.\n set (H := Hx y); revert H; generalize (RX_div Q_as_CRing P y).\n clear; intros P Hap Heq.\n apply (mult_eq_zero IR (x[-]inj_Q_rh y)); [|assumption].\n intro; apply Hap.\n apply cg_inv_unique_2; assumption.\nQed.\n\nEnd Z_Q.\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/liouville/QX_extract_roots.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2638190910332891}}
{"text": "(** * Lan and Colimit **)\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nGeneralizable All Variables.\n\nSet Primitive Projections.\nSet Universe Polymorphism.\n\nRequire Import COC.Base.Main COC.Cons.Terminal COC.Limit.Colimit COC.KanExt.Lan.\n\nProgram Definition colimit_from_lan\n        (C D: Category)\n        (F: C --> D)\n        (lan: Lan F (ToOne C))\n  : Colimit F :=\n  [Colimit [Cocone by (lanN lan) to (lanF lan tt)]\n    by `(lanU lan (S:=constant_functor One D (c: Cocone F)) [i :=> c i] tt) ].\nNext Obligation.\n  rewrite (natrans_naturality (IsNatrans:=lanN lan)); simpl.\n  now rewrite (fmap_id (F:=lanF lan) tt), cat_comp_id_cod.\nQed.\nNext Obligation.\n  now rewrite cocone_commute, cat_comp_id_cod.\nQed.\nNext Obligation.\n  generalize (lan_universality (IsLan:=lan)(S:=[* in One |-> c in D])); simpl.\n  intros H; apply H.\n\n  generalize (lan_uniqueness (IsLan:=lan)(S:=[* in One |-> c in D])); simpl.\n  intros Huniq; eapply (Huniq _ [x :=> match x with\n                                       | tt => u\n                                       end\n                                   from (lanF lan) to [* in One |-> c in D]]); simpl.\n  now apply H.\n  Grab Existential Variables.\n  split.\n  intros [] [] []; simpl.\n  now rewrite (fmap_id (F:=lanF lan)), cat_comp_id_dom, cat_comp_id_cod.\nQed.\n\nProgram Definition lan_from_colimit\n        (C D: Category)\n        (F: C --> D)\n        (colim: Colimit F)\n  : Lan F (ToOne C) :=\n  [Lan by (fun S (e: F ==> (S \\o ToOne C)) =>\n           [ x :=> match x with\n                   | tt => colimit_univ colim [Cocone by e to S tt]\n                   end])\n   with [Functor by f :-> Id colim], [ c in C :=> colim c]].\nNext Obligation.\n  now rewrite cat_comp_id_dom.\nQed.\nNext Obligation.\n  now rewrite cocone_commute, cat_comp_id_cod.\nQed.\nNext Obligation.\n  rewrite (natrans_naturality (IsNatrans:=e)); simpl.\n  now rewrite (fmap_id (F:=S) tt), cat_comp_id_cod.\nQed.\nNext Obligation.\n  destruct X, Y, f.\n  now rewrite cat_comp_id_dom, (fmap_id (F:=S) tt), cat_comp_id_cod.\nQed.\nNext Obligation.\n  generalize (colimit_universality (IsColimit:=colim)); simpl.\n  intros H; apply (H [Cocone by e to S tt] X).\n  destruct X.\n  generalize (colimit_uniqueness (IsColimit:=colim)); intros Huniq.\n  now apply (Huniq [Cocone by e to S tt]), H.\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/LanColimit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2638190910332891}}
{"text": "Require Import\n        Coq.Structures.OrderedTypeEx\n        Coq.Structures.OrderedType\n        Coq.FSets.FMapAVL\n        Coq.Strings.Ascii.\n\nRequire Import\n        Fiat.BinEncoders.Env.Common.Specs\n        Fiat.BinEncoders.Env.Common.Sig\n        Fiat.BinEncoders.Env.Common.Compose.\n\nRequire Import\n        Fiat.BinEncoders.Env.BinLib.Core\n        Fiat.BinEncoders.Env.BinLib.FixInt\n        Fiat.BinEncoders.Env.BinLib.Char\n        Fiat.BinEncoders.Env.BinLib.Bool\n        Fiat.BinEncoders.Env.BinLib.Enum\n        Fiat.BinEncoders.Env.Lib.FixList\n        Fiat.BinEncoders.Env.Lib.IList\n        Fiat.BinEncoders.Env.Lib.SteppingCacheList.\n\nSet Implicit Arguments.\n\nModule list_as_OT (O : OrderedType) <: OrderedType.\n  (* http://www.ensiie.fr/~robillard/Graph_Library/ *)\n  Import O.\n  Module Import OP := OrderedTypeFacts O.\n\n  Definition t := list O.t.\n  Definition eq := eqlistA O.eq.\n\n  Inductive lt_ : t -> t -> Prop :=\n  | ltnil : forall a l, lt_ nil (a :: l)\n  | ltcons : forall a l a' l', O.lt a a' -> lt_ (a :: l) (a' :: l')\n  | lt_tail : forall a a' l l', O.eq a a' -> lt_ l l' -> lt_ (a :: l) (a' :: l').\n\n  Definition lt := lt_.\n\n  Lemma eq_dec : forall l l', {eq l l'} + {~eq l l'}.\n  Proof.\n    unfold eq; induction l; intros.\n    destruct l'. left. abstract intuition.\n    right. abstract (intro; inversion H).\n    destruct l'. right. abstract (intro; inversion H).\n    destruct (IHl l').\n    destruct (O.eq_dec a t0). left. abstract (constructor; auto).\n    right. abstract (intro; elim n; inversion H; auto).\n    right. abstract (intro; elim n; inversion H; auto).\n  Defined.\n\n  Lemma eq_refl : forall x, eq x x.\n  Proof.\n    unfold eq; induction x; intros. auto.\n    constructor; auto.\n  Qed.\n\n  Lemma eq_sym : forall x y, eq x y -> eq y x.\n  Proof.\n    unfold eq; induction x; intros.\n    inversion H; auto.\n    destruct y. inversion H.\n    inversion H. subst.\n    constructor. auto. auto.\n  Qed.\n\n  Lemma eq_trans : forall x y z, eq x y -> eq y z -> eq x z.\n  Proof.\n    induction x; unfold eq; intros.\n    inversion H. subst. inversion H0. subst. auto.\n    destruct y. inversion H.\n    destruct z. inversion H0.\n    constructor. inversion H; inversion H0; subst.\n    eapply O.eq_trans; eauto.\n    eapply IHx; inversion H; inversion H0; subst; eauto.\n  Qed.\n\n  Lemma lt_trans : forall x y z, lt x y -> lt y z -> lt x z.\n  Proof.\n    induction x; unfold lt; intros.\n    inversion H; subst.\n    inversion H0; subst.\n    constructor.\n    constructor.\n    inversion H; subst.\n    inversion H0; subst.\n    constructor. eapply O.lt_trans; eauto.\n    inversion H0; subst.\n    constructor.\n    rewrite <-H3. auto.\n    constructor.\n    rewrite <-H3. auto.\n    inversion H0; subst.\n    constructor.\n    rewrite H3. auto.\n    apply lt_tail. rewrite H3. auto. eapply IHx; eauto.\n  Qed.\n\n  Lemma lt_not_eq : forall x y, lt x y -> ~eq x y.\n  Proof.\n    induction x; unfold lt, eq; intros; intro.\n    inversion H; subst.\n    inversion H0.\n    destruct y. inversion H0.\n    inversion H0; subst.\n    inversion H; subst.\n    elim (O.lt_not_eq H2 H4).\n    eapply IHx; eauto.\n  Qed.\n\n  Lemma compare : forall x y, Compare lt eq x y.\n  Proof.\n    induction x; intros.\n    destruct y.\n    apply EQ. apply eq_refl.\n    apply LT. constructor.\n    destruct y. apply GT. constructor.\n    destruct (O.compare a t0).\n    apply LT. constructor. auto.\n    destruct (IHx y).\n    apply LT. apply lt_tail; auto.\n    apply EQ. constructor; auto.\n    apply GT. apply lt_tail; auto.\n    apply GT. constructor. auto.\n  Defined.\nEnd list_as_OT.\n\nModule Type OrderedTypeWithP (O : OrderedType).\n  Parameter P : O.t -> Prop.\nEnd OrderedTypeWithP.\n\nModule sig_as_OT (O : OrderedType) (O' : OrderedTypeWithP O) <: OrderedType.\n  Import O.\n  Module Import OP := OrderedTypeFacts O.\n\n  Definition t := sig O'.P.\n  Definition eq (t1 t2 : t) := O.eq (proj1_sig t1) (proj1_sig t2).\n  Definition lt (t1 t2 : t) := O.lt (proj1_sig t1) (proj1_sig t2).\n\n  Lemma eq_dec : forall l l', {eq l l'} + {~eq l l'}.\n  Proof. intros; destruct l; destruct l'; apply O.eq_dec. Defined.\n\n  Lemma eq_refl : forall x, eq x x.\n  Proof. intros; destruct x; apply O.eq_refl. Qed.\n\n  Lemma eq_sym : forall x y, eq x y -> eq y x.\n  Proof. intros; destruct x; destruct y; unfold eq in *; apply O.eq_sym; eauto. Qed.\n\n  Lemma eq_trans : forall x y z, eq x y -> eq y z -> eq x z.\n  Proof. intros; destruct x; destruct y; destruct z; unfold eq in *; eapply eq_trans; eauto. Qed.\n\n  Lemma lt_trans : forall x y z, lt x y -> lt y z -> lt x z.\n  Proof. intros; destruct x; destruct y; destruct z; unfold lt in *; eapply lt_trans; eauto. Qed.\n\n  Lemma lt_not_eq : forall x y, lt x y -> ~eq x y.\n  Proof. intros; destruct x; destruct y; apply O.lt_not_eq; eauto. Qed.\n\n  Lemma compare : forall x y, Compare lt eq x y.\n  Proof.\n    intros; destruct x; destruct y.\n    unfold lt, eq.\n    destruct (O.compare x x0) eqn: eq; [ eapply LT | eapply EQ | eapply GT ]; eauto.\n  Defined.\nEnd sig_as_OT.\n\nModule ascii_as_OT <: OrderedType.\n  Definition t := ascii.\n  Definition eq (c1 c2 : t) := N_of_ascii c1 = N_of_ascii c2.\n  Definition lt (c1 c2 : t) := N.lt (N_of_ascii c1) (N_of_ascii c2).\n\n  Lemma eq_dec : forall l l', {eq l l'} + {~eq l l'}.\n  Proof. unfold eq. intros.\n         destruct (N.eqb (N_of_ascii l) (N_of_ascii l')) eqn: eq.\n         - left. abstract (rewrite <- N.eqb_eq; eauto).\n         - right. abstract (rewrite <- N.eqb_neq; eauto).  Defined.\n\n  Lemma eq_refl : forall x, eq x x.\n  Proof. reflexivity. Qed.\n\n  Lemma eq_sym : forall x y, eq x y -> eq y x.\n  Proof. intros. symmetry. eauto. Qed.\n\n  Lemma eq_trans : forall x y z, eq x y -> eq y z -> eq x z.\n  Proof. intros. unfold eq in *. rewrite H. rewrite H0. eauto. Qed.\n\n  Lemma lt_trans : forall x y z, lt x y -> lt y z -> lt x z.\n  Proof. intros. unfold lt in *. eapply N.lt_trans; eauto. Qed.\n\n  Lemma lt_not_eq : forall x y, lt x y -> ~eq x y.\n  Proof. intros. unfold eq, lt in *. intro.\n         rewrite <- N.compare_lt_iff in H.\n         rewrite <- N.compare_eq_iff in H0.\n         congruence. Qed.\n\n  Lemma compare : forall x y, Compare lt eq x y.\n  Proof.\n    intros. unfold lt, eq.\n    destruct (N.compare (N_of_ascii x) (N_of_ascii y)) eqn: eq.\n    - eapply EQ. abstract (rewrite <- N.compare_eq_iff; eauto).\n    - eapply LT. abstract (rewrite <- N.compare_lt_iff; eauto).\n    - eapply GT. abstract (rewrite <- N.compare_gt_iff; eauto).\n  Defined.\nEnd ascii_as_OT.\n\nRecord word_t :=\n  { word : { l : list ascii | length l < exp2_nat 6 } }.\nDefinition position_t := uint 14.\n\nModule list_ascii_as_OT := list_as_OT ascii_as_OT.\nModule list_ascii_as_OT_with_P <: OrderedTypeWithP list_ascii_as_OT.\n  Definition P (l : list ascii) := length l < exp2_nat 6.\nEnd list_ascii_as_OT_with_P.\n\nModule word_as_OT := sig_as_OT list_ascii_as_OT list_ascii_as_OT_with_P.\n\nModule N_as_OT_with_P <: OrderedTypeWithP N_as_OT.\n  Definition P (n : N) := (n < exp2 14)%N.\nEnd N_as_OT_with_P.\n\nModule position_as_OT := sig_as_OT N_as_OT N_as_OT_with_P.\n\nModule word_t_as_OT <: OrderedType.\n  Import word_as_OT.\n\n  Definition t := word_t.\n  Definition eq (a b : word_t) := eq a.(word) b.(word).\n  Definition lt (a b : word_t) := lt a.(word) b.(word).\n\n  Lemma eq_dec : forall l l', {eq l l'} + {~eq l l'}.\n  Proof.\n    destruct l; destruct l'; apply eq_dec.  Defined.\n\n  Lemma eq_refl : forall x, eq x x.\n  Proof.\n    destruct x; apply eq_refl.  Qed.\n\n  Lemma eq_sym : forall x y, eq x y -> eq y x.\n  Proof.\n    destruct x; destruct y; apply eq_sym.  Qed.\n\n  Lemma eq_trans : forall x y z, eq x y -> eq y z -> eq x z.\n  Proof.\n    destruct x; destruct y; destruct z; apply eq_trans.  Qed.\n\n  Lemma lt_trans : forall x y z, lt x y -> lt y z -> lt x z.\n  Proof.\n    destruct x; destruct y; destruct z; apply lt_trans.  Qed.\n\n  Lemma lt_not_eq : forall x y, lt x y -> ~eq x y.\n  Proof.\n    destruct x; destruct y; apply lt_not_eq.  Qed.\n\n  Lemma compare : forall x y, Compare lt eq x y.\n  Proof.\n    destruct x; destruct y.\n    refine (match compare word0 word1 with\n            | LT _ => LT _\n            | EQ _ => EQ _\n            | GT _ => GT _\n            end); unfold lt, eq; eauto.  Defined.\nEnd word_t_as_OT.\n\nModule list_word_t_as_OT := list_as_OT word_t_as_OT.\n\nModule EMap := FMapAVL.Make(list_word_t_as_OT).\nModule DMap := FMapAVL.Make(position_as_OT).\n\nDefinition EMapT := EMap.t position_t.\nDefinition DMapT := DMap.t (list word_t).\n\nRecord CacheT :=\n  { eMap : EMapT;\n    dMap : DMapT;\n    offs : N }.\n\nInstance cache : Cache :=\n  {| CacheEncode := CacheT;\n     CacheDecode := CacheT;\n     Equiv := fun x y => x = y /\\\n                         forall p q, EMap.MapsTo p q x.(eMap) <-> DMap.MapsTo q p x.(dMap) |}.\n\nInstance cacheAddN : CacheAdd cache N :=\n  {| addE := fun c n => {| eMap := c.(eMap);\n                           dMap := c.(dMap);\n                           offs := c.(offs) + n |};\n     addD := fun c n => {| eMap := c.(eMap);\n                           dMap := c.(dMap);\n                           offs := c.(offs) + n |} |}.\nProof. abstract (simpl; intuition; subst; eauto).  Defined.\n\nRequire Import Coq.FSets.FMapFacts.\nModule EMapFacts := WFacts_fun (list_word_t_as_OT) (EMap).\nModule DMapFacts := WFacts_fun (position_as_OT) (DMap).\n\nLemma cacheAddPair' :\n  forall (ce : CacheEncode) (cd : CacheDecode) (t : EMap.key * DMap.key),\n   Equiv ce cd ->\n   Equiv\n     (let (l, p) := t in\n      if EMap.mem (elt:=position_t) l (eMap ce) || DMap.mem (elt:=list word_t) p (dMap ce)\n      then ce\n      else {| eMap := EMap.add l p (eMap ce); dMap := DMap.add p l (dMap ce); offs := offs ce |})\n     (let (l, p) := t in\n      if EMap.mem (elt:=position_t) l (eMap cd) || DMap.mem (elt:=list word_t) p (dMap cd)\n      then cd\n      else {| eMap := EMap.add l p (eMap cd); dMap := DMap.add p l (dMap cd); offs := offs cd |}).\nProof.\n  Local Hint Resolve EMap.E.eq_refl.\n  simpl; intuition; simpl in *; subst; eauto.\n  - destruct (EMap.mem a (eMap cd)) eqn: eq1; destruct (DMap.mem b (dMap cd)) eqn: eq2;\n      simpl in *; try apply H1; eauto.\n    rewrite EMapFacts.add_mapsto_iff in H.\n    rewrite DMapFacts.add_mapsto_iff.\n    inversion H. clear H. intuition.\n    left. subst. assert (a = p).\n    { clear -H; generalize dependent p; induction a; intuition.\n      inversion H; eauto.\n      destruct p; inversion H; subst; clear H.\n      erewrite IHa; eauto; f_equal.\n      clear -H3. destruct a. destruct w. simpl in *.\n      destruct word0 eqn: ?. simpl in *. destruct word1 eqn: ?. simpl in *.\n      f_equal. erewrite <- sig_equivalence.\n      clear -H3; generalize dependent x0; induction x; intuition.\n      inversion H3; eauto.\n      destruct x0; inversion H3; subst; clear H3.\n      erewrite IHx; eauto; f_equal.\n      apply f_equal with (f:=ascii_of_N) in H2. rewrite !ascii_N_embedding in H2. eauto. }\n    intuition eauto.\n    right. intuition. apply H1 in H4. clear - eq2 H4 H0.\n    destruct b eqn: ?. destruct q eqn: ?. erewrite sig_equivalence with (P:=N_as_OT_with_P.P) (n_pf:=p0) (m_pf:=l) in H0.\n    simpl in H0. erewrite <- Heqk in H0. unfold N_as_OT_with_P.P in *. rewrite <- Heqp1 in H0.\n    subst. inversion H0. subst. clear H0. rewrite DMapFacts.mem_find_b in eq2.\n    rewrite DMapFacts.find_mapsto_iff in H4.\n    erewrite (proj1 (sig_equivalence _ ((fun n : N => (n < exp2 14)%N)) x0 x0 p0 l) eq_refl) in eq2.\n    unfold EMap.key, list_ascii_as_OT_with_P.P in *. erewrite H4 in eq2. congruence.\n    apply H1. eauto.\n  - destruct (EMap.mem a (eMap cd)) eqn: eq1; destruct (DMap.mem b (dMap cd)) eqn: eq2;\n      simpl in *; try apply H1; eauto.\n    rewrite DMapFacts.add_mapsto_iff in H.\n    rewrite EMapFacts.add_mapsto_iff.\n    inversion H.\n    { clear H. intuition.\n      left. subst. assert (b = q).\n      { clear -H. destruct b eqn: ?. destruct q eqn: ?.\n        simpl in H. unfold N_as_OT_with_P.P. apply sig_equivalence. eauto. }\n      intuition eauto. }\n    { right. intuition. apply H1 in H4. clear - eq1 H4 H0.\n      rewrite EMapFacts.mem_find_b in eq1.\n      assert (a = p).\n      { clear -H0; generalize dependent p; induction a; intuition.\n        inversion H0; eauto.\n        destruct p; inversion H0; subst; clear H0.\n        erewrite IHa; eauto; f_equal.\n        clear -H3. destruct a. destruct w.\n        destruct word0 eqn: ?. destruct word1 eqn: ?. simpl in *.\n        f_equal. erewrite <- sig_equivalence.\n        clear -H3; generalize dependent x0; induction x; intuition.\n        inversion H3; eauto.\n        destruct x0; inversion H3; subst; clear H3.\n        erewrite IHx; eauto; f_equal.\n        apply f_equal with (f:=ascii_of_N) in H2. rewrite !ascii_N_embedding in H2. eauto. }\n      subst. rewrite EMapFacts.find_mapsto_iff in H4.\n      rewrite H4 in eq1. congruence.\n      apply H1. eauto. }\n  Grab Existential Variables.\n  simpl in *. omega.\n  simpl in *. omega.\n  simpl in *. omega.\n  simpl in *. omega.  Qed.\n\nInstance cacheAddPair : CacheAdd cache (list word_t * position_t) :=\n  {| addE := fun c (b : _ * _) => let (l, p) := b\n                                  in if EMap.mem l c.(eMap) || DMap.mem p c.(dMap)\n                                     then c\n                                     else {| eMap := EMap.add l p c.(eMap);\n                                             dMap := DMap.add p l c.(dMap);\n                                             offs := c.(offs) |};\n     addD := fun c (b : _ * _) => let (l, p) := b\n                                  in if EMap.mem l c.(eMap) || DMap.mem p c.(dMap)\n                                     then c\n                                     else {| eMap := EMap.add l p c.(eMap);\n                                             dMap := DMap.add p l c.(dMap);\n                                             offs := c.(offs) |} |}.\nProof. eapply cacheAddPair'.  Qed.\n\nDefinition get_position (n : N) : position_t.\n  refine (if position_as_OT.OP.lt_dec n (exp2 14)\n          then exist _ n _\n          else exist _ 0%N _).\n  abstract eauto.\n  abstract (rewrite <- N.compare_lt_iff; eauto).\nDefined.\n\nInstance cachePeek : CachePeek cache position_t :=\n  {| peekE := fun c => get_position (N.div c.(offs) 8);\n     peekD := fun c => get_position (N.div c.(offs) 8) |}.\nProof.\n  abstract (unfold Equiv;\n  intuition;\n  destruct ce; destruct cd; simpl in *;\n  inversion H; inversion H0; eauto).\nDefined.\n\nInstance cacheGet : CacheGet cache (list word_t) position_t :=\n  {| getE := fun c l => EMap.find l c.(eMap);\n     getD := fun c p => DMap.find p c.(dMap) |}.\nProof.\n  abstract (\n  simpl; intuition; subst; [\n  apply DMap.find_1; apply EMap.find_2 in H; apply H1; eauto |\n  apply EMap.find_1; apply DMap.find_2 in H; apply H1; eauto ]).\nDefined.", "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/DnsMap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.26381909103328904}}
{"text": "Add LoadPath \"PLC\".\nAdd LoadPath \"../metatheory\".\nRequire PLC_ott.\nRequire PLC_inf.\nRequire Export STLC_other.\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 => PLC_ott.fv_term x) in\n  constr:(A \\u B \\u C \\u D1 \\u D2).\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  (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.\nHint Constructors erase.\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.\nQed.\nHint Resolve erase_subst.\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.\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 (H0 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.\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 H5; 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.\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.\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.\nQed.\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.\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.\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/STLC/STLC_sim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118493816806, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.26381908329370785}}
{"text": "Require Import Coq.ZArith.ZArith Coq.micromega.Lia.\nRequire Import QArith.QArith_base QArith.Qround Crypto.Util.QUtil.\nRequire Import Crypto.ArithmeticCPS.BaseConversion.\nRequire Import Crypto.ArithmeticCPS.Core.\nRequire Import Crypto.ArithmeticCPS.ModOps.\nRequire Import Crypto.Arithmetic.Partition.\nRequire Import Crypto.ArithmeticCPS.Saturated.\nRequire Import Crypto.Util.CPSUtil.\nRequire Import Crypto.Util.CPSNotations.\nRequire Import Crypto.Util.Decidable.\nRequire Import Crypto.Util.ListUtil.\nRequire Import Crypto.Util.Prod.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nRequire Import Crypto.Util.Tactics.DestructHead.\nRequire Import Crypto.Util.ZUtil.EquivModulo.\nRequire Import Crypto.Util.ZUtil.Opp.\nRequire Import Crypto.Util.ZUtil.Tactics.DivModToQuotRem.\nRequire Import Crypto.Util.ZUtil.Tactics.PeelLe.\nRequire Import Crypto.Util.ZUtil.Tactics.RewriteModSmall.\nRequire Import Crypto.Util.ZUtil.Tactics.PullPush.Modulo.\n\nRequire Import Crypto.Util.Notations.\nLocal Open Scope Z_scope.\n\nImport CPSBindNotations.\nLocal Open Scope cps_scope.\n\n(* TODO: rename this module? (Should it be, e.g., [Rows.freeze]?) *)\nModule Freeze (Import RT : Runtime).\n  Module Import Deps.\n    Module Rows := Rows RT.\n  End Deps.\n  Section Freeze.\n    Context (weight : nat -> Z).\n\n    Definition freeze_cps n mask (m p:list Z) : ~> list Z :=\n      (p_carry <- Rows.sub_cps weight n p m;\n         let '(p, carry) := p_carry in\n         r_carry <- Rows.conditional_add_cps weight n mask (-carry)%RT p m;\n           let '(r, carry) := r_carry in\n           return r).\n  End Freeze.\nEnd Freeze.\n\nModule FreezeModOps (Import RT : Runtime).\n  Module Import Deps.\n    Module Export Positional := Positional RT.\n    Module Export Freeze := Freeze RT.\n    Module BaseConversion := BaseConversion RT.\n    Module Export Core.\n      Module Associational := ArithmeticCPS.Core.Associational RT.\n    End Core.\n  End Deps.\n  Section mod_ops.\n  Local Coercion Z.of_nat : nat >-> Z.\n  Local Coercion QArith_base.inject_Z : Z >-> Q.\n  (* Design constraints:\n     - inputs must be [Z] (b/c reification does not support Q)\n     - internal structure must not match on the arguments (b/c reification does not support [positive]) *)\n  Context (limbwidth_num limbwidth_den : Z)\n          (limbwidth_good : 0 < limbwidth_den <= limbwidth_num)\n          (s : Z)\n          (c : list (Z*Z))\n          (n : nat)\n          (bitwidth : Z)\n          (m_enc : list Z)\n          (Hn_nz : n <> 0%nat).\n  Local Notation bytes_weight := (@weight 8 1).\n  Local Notation weight := (@weight limbwidth_num limbwidth_den).\n  Let m := (s - Associational.eval c).\n\n  Context (Hs : s = weight n).\n  Context (c_small : 0 < Associational.eval c < weight n)\n          (m_enc_bounded : List.map (BinInt.Z.land (Z.ones bitwidth)) m_enc = m_enc)\n          (m_enc_correct : Positional.eval weight n m_enc = m)\n          (Hm_enc_len : length m_enc = n).\n\n  Definition bytes_n\n    := Eval cbv [Qceiling Qdiv inject_Z Qfloor Qmult Qopp Qnum Qden Qinv Pos.mul]\n      in Z.to_nat (Qceiling (Z.log2_up (weight n) / 8)).\n\n  Definition to_bytes_cps (v : list Z) : ~> _\n    := BaseConversion.convert_bases_cps weight bytes_weight n bytes_n v.\n\n  Definition from_bytes_cps (v : list Z) : ~> _\n    := BaseConversion.convert_bases_cps bytes_weight weight bytes_n n v.\n\n  Definition freeze_to_bytesmod_cps (f : list Z) : ~> list Z\n    := (f <- freeze_cps weight n (Z.ones bitwidth) m_enc f; to_bytes_cps f).\n\n  Definition to_bytesmod_cps (f : list Z) : ~> list Z\n    := to_bytes_cps f.\n  Definition to_bytesmod (f : list Z) : list Z := to_bytesmod_cps f _ id.\n\n  Definition from_bytesmod_cps (f : list Z) : ~> list Z\n    := from_bytes_cps f.\n  Definition from_bytesmod (f : list Z) : list Z := from_bytesmod_cps f _ id.\n  End mod_ops.\nEnd FreezeModOps.\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/Freeze.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.359364145160102, "lm_q1q2_score": 0.26381623622982275}}
{"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 T : Universe, ((wd_ P Q /\\ (wd_ T Z /\\ (wd_ B Cprime /\\ (wd_ Cprime Dprimeprime /\\ (wd_ B Dprimeprime /\\ (wd_ A B /\\ (wd_ B C /\\ (wd_ A C /\\ (wd_ Cprime Pprimeprime /\\ (wd_ B Pprime /\\ (wd_ Dprime B /\\ (wd_ T B /\\ (wd_ B Pprimeprime /\\ (wd_ B Z /\\ (wd_ Cprime C /\\ (wd_ A Dprime /\\ (wd_ Pprime Cprime /\\ (col_ A B T /\\ (col_ B T Pprimeprime /\\ (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_0572.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.3593641382989649, "lm_q1q2_score": 0.2638162311929281}}
{"text": "Require Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.Sorting.Permutation.\nRequire Import SGX.State.\nImport Coq.Lists.List.ListNotations.\n\nSection SGX_FS.\n\n  Definition Fid : Set := nat.\n\n  Definition Did : Set := nat.\n\n  Definition Pgid : Set := nat.\n\n  Definition Memid : Set := nat.\n\n  Record Permission :=\n    {\n      readable: bool;\n      writable: bool;\n      executable: bool;\n    }.\n\n  Record Meta :=\n    {\n      permission : Permission;\n      size : nat;\n    }.\n\n  Inductive Tree := Fnode: Fid -> Tree | Dnode: Did -> list Tree -> Tree.\n\n  Section TREE_IND2.\n\n    Variable P: Tree -> Prop.\n    Variable tree_ind' : forall (t: Tree), P t.\n    Variable tree_ind2_Hdir: forall did treeL,\n        Forall P treeL -> P (Dnode did treeL).\n\n    Fixpoint tree_ind2_list (treeL: list Tree) (did: Did): P (Dnode did treeL).\n      apply tree_ind2_Hdir. induction treeL.\n      - constructor.\n      - constructor.\n        + apply tree_ind'.\n        + apply IHtreeL.\n    Defined.\n\n  End TREE_IND2.\n\n  Fixpoint tree_ind2 (P: Tree -> Prop)\n           (Hfile: forall fid, P (Fnode fid))\n           (Hdir: forall did treeL,\n               Forall P treeL -> P (Dnode did treeL))\n           (t: Tree) {struct t} : P t.\n    refine\n      match t with\n      | Fnode fid => _\n      | Dnode did treeL => _\n      end.\n    - apply Hfile.\n    - specialize (tree_ind2 P Hfile Hdir). apply tree_ind2_list.\n      + apply tree_ind2.\n      + apply Hdir.\n  Defined.\n\n  Definition Byte : Set := Ascii.ascii.\n\n  Definition Page := list Byte.\n\n  Fixpoint byte_list_to_string (l: list Byte) : string :=\n    match l with\n    | nil => EmptyString\n    | a :: l' => String a (byte_list_to_string l')\n    end.\n\n  Fixpoint string_to_byte_list (s: string): list Byte :=\n    match s with\n    | EmptyString => nil\n    | String a s' => a :: string_to_byte_list s'\n    end.\n\n  Check (Dnode 2 [Fnode 5 ; Fnode 6; Dnode 5 []]).\n\n  Record FData :=\n    {\n      nameF : string;\n      metaF : Meta;\n      pageIdsF : list Pgid;\n    }.\n\n  Record DData :=\n    {\n      nameD : string;\n      metaD : Permission;\n    }.\n\n  (* Parameter oh : list Fid. *)\n\n  Definition Path := list string.\n\n  Inductive ErrCode :=\n  | eSucc\n  | eBadF\n  | eInval\n  | eIsDir\n  | eNameTooLong\n  | eNFile\n  | eNoEnt\n  | eNoSpc\n  | eNotEmpty\n  | eBadPage\n  | eBadName\n  | eNoDir\n  | eExists\n  | eAcces\n  | eNotDir\n  | eMapFailed.\n\n  Inductive MmapMode :=\n  | mapAnon\n  | mapFile\n  | mapShared\n  | mapPrivate.\n\n  Definition MmapedMemory := list Page.\n\n  Open Scope string_scope.\n\n  Record FileSystem : Set :=\n    {\n      layout : Tree;\n      open_handles : list (Fid * nat);\n      virtual_memory : list Page;\n      f_map : Fid -> FData;\n      d_map : Did -> DData;\n      fnode_ctr: nat;\n      dnode_ctr: nat;\n      mmap_handles : list (Memid * nat * Permission);\n      mmap_memory : MmapedMemory;\n    }.\n\n  Definition memory_upper_bound : nat := Z.to_nat 65536%Z.\n\n  Inductive LogCommand: Set :=\n    Call_VRead : Fid -> nat -> (string * ErrCode) -> LogCommand\n  | Call_VWrite : Fid -> string -> nat -> ErrCode -> LogCommand\n  | Call_VOpen: Path -> string -> ErrCode -> LogCommand\n  | Call_VClose: Fid -> ErrCode -> LogCommand\n  | Call_VLSeek: Fid -> nat -> ErrCode -> LogCommand\n  | Call_VMkdir: Path -> string -> Permission -> ErrCode -> LogCommand\n  | Call_VRmdir: Path -> ErrCode -> LogCommand\n  | Call_MKFS: string -> LogCommand\n  | Call_VCreate: Path -> string -> Permission -> ErrCode -> LogCommand\n  | Call_VChmod: Path -> Permission -> ErrCode -> LogCommand\n  | Call_VReadDir: Path -> ErrCode -> LogCommand\n  | Call_VStat: Fid -> ErrCode -> LogCommand\n  | Call_VTruncate: Fid -> nat -> string -> ErrCode -> LogCommand\n  | Call_VRemove: Path -> string -> ErrCode -> LogCommand\n  | Call_AllocMem: MmapedMemory -> nat -> list Memid -> LogCommand\n  | Call_DeallocMem: MmapedMemory -> Memid -> nat -> bool -> LogCommand.\n\n  Definition FSState := (FileSystem * list LogCommand)%type.\n\n  Definition trivialFS : FSState :=\n    (Build_FileSystem\n       (Fnode O) nil nil\n       (fun _ => Build_FData EmptyString\n                             (Build_Meta (Build_Permission false false false) O) nil)\n       (fun _ => Build_DData EmptyString (Build_Permission false false false)) O 1 nil nil,\n     nil).\n\n  Definition mkfs (disk_name: string) : FSState :=\n    (Build_FileSystem\n       (Dnode O nil) nil nil\n       (fun _ => Build_FData EmptyString\n                             (Build_Meta (Build_Permission false false false) O) nil)\n       (fun did => if Nat.eq_dec did O\n                   then Build_DData disk_name (Build_Permission true true true)\n                   else Build_DData EmptyString\n                                    (Build_Permission false false false)) O 1 nil nil,\n     Call_MKFS disk_name :: nil).\n\n  Definition getOpenHandles: State FSState (list (Fid * nat)) :=\n    fun x => ((@open_handles (fst x)), x).\n\n  Definition putOpenHandles: list (Fid * nat) -> State FSState unit :=\n    fun oh x =>\n      let (fs, logs) := x in\n      (tt, (Build_FileSystem\n              fs.(layout) oh fs.(virtual_memory) fs.(f_map)\n              fs.(d_map) fs.(fnode_ctr) fs.(dnode_ctr)\n              fs.(mmap_handles) fs.(mmap_memory), logs)).\n\n  Definition putVirtualMemory: list Page -> State FSState unit :=\n    fun vm x =>\n      let (fs, logs) := x in\n      (tt, (Build_FileSystem fs.(layout) fs.(open_handles) vm\n            fs.(f_map) fs.(d_map) fs.(fnode_ctr) fs.(dnode_ctr)\n            fs.(mmap_handles) fs.(mmap_memory), logs)).\n\n  Definition putFMap: (Fid -> FData) -> State FSState unit :=\n    fun fmap x =>\n      let (fs, logs) := x in\n      (tt, (Build_FileSystem fs.(layout) fs.(open_handles) fs.(virtual_memory)\n            fmap fs.(d_map) fs.(fnode_ctr) fs.(dnode_ctr)\n            fs.(mmap_handles) fs.(mmap_memory), logs)).\n\n  Definition putLayout: Tree -> State FSState unit :=\n    fun tree x =>\n      let (fs, logs) := x in\n      (tt, (Build_FileSystem tree fs.(open_handles) fs.(virtual_memory)\n            fs.(f_map) fs.(d_map) fs.(fnode_ctr) fs.(dnode_ctr)\n            fs.(mmap_handles) fs.(mmap_memory), logs)).\n\n  Definition putMmapHandles: list (Memid * nat * Permission) -> State FSState unit :=\n    fun h x =>\n      let (fs, logs) := x in\n      (tt, (Build_FileSystem fs.(layout) fs.(open_handles) fs.(virtual_memory)\n            fs.(f_map) fs.(d_map) fs.(fnode_ctr) fs.(dnode_ctr)\n            h fs.(mmap_memory), logs)).\n\n  Definition putMmapMemory: MmapedMemory -> State FSState unit :=\n    fun m x =>\n      let (fs, logs) := x in\n      (tt, (Build_FileSystem fs.(layout) fs.(open_handles) fs.(virtual_memory)\n            fs.(f_map) fs.(d_map) fs.(fnode_ctr) fs.(dnode_ctr)\n            fs.(mmap_handles) m, logs)).\n\n  Definition getTree: State FSState Tree := fun x => ((fst x).(layout), x).\n  Definition getFS: State FSState FileSystem := fun x => (fst x, x).\n  Definition getFMap: State FSState (Fid -> FData) := fun x => ((fst x).(f_map), x).\n\n  Definition externalCall {s: Type}:\n    (s -> LogCommand) -> (nat -> s) -> State FSState s :=\n    fun cmd f state => let (fs, logs) := state in\n                       let v := f (length logs) in (v, (fs, cmd v :: logs)).\n\n  Definition testExternalCall: State FSState nat :=\n    do n3 <- externalCall (Call_VClose 4) (fun x => eSucc);\n      do ss <- get;\n      return_ (length (snd ss)).\n\n  Compute (testExternalCall trivialFS).\n\n  Definition psize := Z.to_nat 4000%Z.\n  Definition block_size := Z.to_nat 4096%Z.\n\n  Parameter v_read: Fid -> nat -> nat -> (string * ErrCode).\n  Parameter v_write: Fid -> string -> nat -> nat -> ErrCode.\n  Parameter v_lseek : Fid -> nat -> nat -> ErrCode.\n  Parameter v_close: Fid -> nat -> ErrCode.\n  Parameter v_open: Path -> string -> nat -> ErrCode.\n  (* Definition v_open (a: Path) (b: string) (c: nat) := eSucc. *)\n  Parameter v_create: Path -> string -> Permission -> nat -> ErrCode.\n  Parameter v_chmod: Path -> Permission -> nat -> ErrCode.\n  Parameter v_remove: Path -> string -> nat -> ErrCode.\n  (* Definition v_create (a: Path) (b: string) (c: Permission) (d: nat) := eSucc. *)\n  Parameter v_mkdir: Path -> string -> Permission -> nat -> ErrCode.\n  Parameter v_rmdir: Path -> nat -> ErrCode.\n  Parameter v_readdir: Path -> nat -> ErrCode.\n  Parameter v_stat: Fid -> nat -> ErrCode.\n  Parameter v_truncate: Fid -> nat -> string -> nat -> ErrCode.\n  Parameter decrypt_page: string -> string.\n  Parameter encrypt_page : string -> string.\n  Parameter verify_page: string -> bool.\n  Parameter extract_page : string -> string.\n  Parameter truncate_page: string -> nat -> nat -> string.\n  Parameter allocate_memory: MmapedMemory -> nat -> nat -> list Memid.\n  Parameter deallocate_memory: MmapedMemory -> Memid -> nat -> nat -> bool.\n\n  (* TODO *)\n  (*   1. Add counter to v_func *)\n  (*   2. Record returned value in log *)\n  (*   3. Define a clearner externalCall.                                      *)\n\n  Definition isNotSucc (err: ErrCode) : {err <> eSucc} + {err = eSucc}.\n  Proof. destruct err; [right; auto | left; intro s; inversion s..]. Defined.\n\n  Fixpoint replace_handler (fid: Fid) (pos: nat) (lst: list (Fid * nat)) :=\n    match lst with\n    | nil => nil\n    | (id, p) :: rest => if (Nat.eq_dec fid id)\n                         then (id, pos) :: rest\n                         else (id, p) :: replace_handler fid pos rest\n    end.\n\n  Definition pos_to_vpage (pos: nat) : nat := pos / psize.\n\n  Definition pos_to_vlen (pos: nat) (len : nat) : nat :=\n    ((pos + len)/psize - (pos / psize) + 1) * block_size.\n\n  (* TODO: pos + len should <= the total size of the file, the same as seek *)\n\n  Definition fs_parameter (n: nat): Type :=\n    match n with\n    |  O => Fid * nat\n    |  1 => Path * string\n    |  2 => Fid\n    |  3 => Fid * string * nat\n    |  4 => Fid * nat\n    |  5 => Path * string * Permission\n    |  6 => Path * string * Permission\n    |  7 => Path\n    |  8 => Path * string\n    |  9 => Path * Permission\n    | 10 => Path\n    | 11 => Fid\n    | 12 => Fid * nat\n    | _ => unit\n    end.\n\n  Definition fs_result (n: nat) : Type :=\n    match n with\n    |  O => string * ErrCode\n    |  1 => Fid * ErrCode\n    |  2 => ErrCode\n    |  3 => ErrCode\n    |  4 => ErrCode\n    |  5 => ErrCode\n    |  6 => ErrCode\n    |  7 => ErrCode\n    |  8 => ErrCode\n    |  9 => ErrCode\n    | 10 => list string * ErrCode\n    | 11 => string * Permission *nat * list Pgid * ErrCode\n    | 12 => ErrCode\n    | _ => unit\n    end.\n\n  Definition fs_read (arg : fs_parameter O) : State FSState (fs_result O) :=\n    let (fId, len) := arg in\n    do oh <- getOpenHandles;\n      let opos := find (fun x => Nat.eqb (fst x) fId) oh in\n      match opos with\n      | None => return_ (\"\", eBadF)\n      | Some (_, pos) =>\n        do fmap <- getFMap;\n        if le_dec (fmap fId).(metaF).(size) (pos + len)\n        then return_ (\"\", eInval)\n        else do err <- externalCall (Call_VLSeek fId (pos_to_vpage pos))\n                (v_lseek fId (pos_to_vpage pos));\n             if (isNotSucc err)\n             then return_ (\"\", err)\n             else\n               let new_len := pos_to_vlen pos len in\n               do readR <- externalCall (Call_VRead fId new_len) (v_read fId new_len);\n               let (str, err) := readR in\n               if (isNotSucc err)\n               then return_ (\"\", err)\n               else\n                 let new_str := decrypt_page str in\n                 if (verify_page new_str)\n                 then\n                   let extracted_str := extract_page new_str in\n                   let truncated_str := truncate_page extracted_str pos (pos + len) in\n                   let new_open_handles := replace_handler fId (pos + len) oh in\n                   putOpenHandles new_open_handles >>\n                                  return_ (truncated_str, eSucc)\n                 else return_ (\"\", eBadPage)\n      end.\n\n  Definition DData_eqb (dd: DData) (dname: string) : bool :=\n    if (string_dec dd.(nameD) dname) then true else false.\n\n  Definition root_eq (dmap: Did -> DData) (tree: Tree) (dname : string) : bool :=\n    match tree with\n    | Fnode _ => false\n    | Dnode d _ => DData_eqb (dmap d) dname\n    end.\n\n  Fixpoint findDir (dmap: Did -> DData) (tree : Tree) (p: Path) : option Tree :=\n    match tree with\n    | Fnode _ => None\n    | Dnode did li =>\n      match p with\n      | nil => Some tree\n      | d :: rest => match find (fun x => root_eq dmap x d) li with\n                     | None => None\n                     | Some t => findDir dmap t rest\n                     end\n      end\n    end.\n\n  Definition sampleTree := Dnode 0 [Dnode 1 []; Dnode 2 [Dnode 4 [Fnode 4; Dnode 5 [];\n  Dnode 6 []; Dnode 7 [Dnode 8 [Dnode 9 []; Fnode 1; Fnode 2; Fnode 3]]]]; Dnode 3 []].\n\n  (* Compute (findDir sampleTree [2; 4; 7; 8]). *)\n\n  Fixpoint collectBareFids (li : list Tree) : list Fid :=\n    match li with\n    | nil => nil\n    | Fnode id :: rest => id :: collectBareFids rest\n    | Dnode _ _ :: rest => collectBareFids rest\n    end.\n\n  Fixpoint collectDids (t: Tree) : list Did :=\n    match t with\n    | Fnode _ => nil\n    | Dnode did l => did :: flat_map collectDids l\n    end.\n\n  Fixpoint collectFids (t: Tree) : list Fid :=\n    match t with\n    | Fnode id => id :: nil\n    | Dnode _ l => flat_map collectFids l\n    end.\n\n  Definition treeName\n             (fmap: Fid -> FData) (dmap: Did -> DData) (tree: Tree) : string :=\n    match tree with\n    | Fnode fId => (fmap fId).(nameF)\n    | Dnode did _ => (dmap did).(nameD)\n    end.\n\n  Inductive NoDupNameTree: (Fid -> FData) -> (Did -> DData) -> Tree -> Prop :=\n  | File_NDNT: forall fmap dmap fId, NoDupNameTree fmap dmap (Fnode fId)\n  | Dir_NDNT: forall fmap dmap root treeL,\n      Forall (NoDupNameTree fmap dmap) treeL ->\n      NoDup (map (treeName fmap dmap) treeL) ->\n      NoDupNameTree fmap dmap (Dnode root treeL).\n\n  Definition isDir (t : Tree) : Prop := exists d l, t = Dnode d l.\n\n  Definition pad_size (len: nat): nat :=\n    let q := len / block_size in\n    if Nat.eq_dec (len mod block_size) O then q else S q.\n\n  Definition Disjoint (h1 h2: (Memid * nat * Permission)): Prop :=\n    match h1 with\n    | ((s1, len1), _) => match h2 with\n                         | ((s2, len2), _) => s1 + pad_size len1 <= s2 \\/\n                                              s2 + pad_size len2 <= s1\n                         end\n    end.\n\n  Inductive NoOverlap: list (Memid * nat * Permission) -> Prop :=\n  | NoOverlap_nil: NoOverlap nil\n  | NoOverlap_cons: forall x l, (forall y, In y l -> Disjoint x y) ->\n                                NoOverlap l -> NoOverlap (x :: l).\n\n  Definition NotNullHandles (x: (Memid * nat * Permission)) : Prop :=\n    match x with | (_, len, _) => len <> O end.\n\n  Definition NoNull (l: list (Memid * nat * Permission)): Prop :=\n    Forall NotNullHandles l.\n\n  Definition good_file_system (fs: FileSystem) : Prop :=\n    NoDupNameTree fs.(f_map) fs.(d_map) fs.(layout) /\\\n    NoDup (collectDids fs.(layout)) /\\\n    NoDup (collectFids fs.(layout)) /\\\n    (forall el, In el (collectDids fs.(layout)) -> fs.(dnode_ctr) > el) /\\\n    (forall el, In el (collectFids fs.(layout)) -> fs.(fnode_ctr) > el) /\\\n    NoDup (map fst fs.(open_handles)) /\\\n    isDir fs.(layout) /\\\n    (forall fId1 fId2 pgId1 pgId2,\n        fId1 <> fId2 ->\n        In pgId1 (fs.(f_map) fId1).(pageIdsF) ->\n        In pgId2 (fs.(f_map) fId2).(pageIdsF) -> pgId1 <> pgId2) /\\\n    (forall fId pgId, In pgId (fs.(f_map) fId).(pageIdsF) ->\n                      pgId < memory_upper_bound) /\\ NoOverlap (mmap_handles fs) /\\\n    (forall mem, In mem (mmap_memory fs) -> length mem = block_size) /\\\n    NoNull (mmap_handles fs).\n\n  Compute (collectBareFids [Dnode 9 []; Fnode 1; Fnode 2; Fnode 3]).\n\n  Compute (collectDids sampleTree).\n\n  Compute (collectFids sampleTree).\n\n  Definition findFids (dmap: Did -> DData) (tree: Tree) (p: Path) : list Fid :=\n    match findDir dmap tree p with\n    | None => []\n    | Some (Fnode _) => []\n    | Some (Dnode d li) => collectBareFids li\n    end.\n\n  Definition fdata_eqb (fd: FData) (fname: string) : bool :=\n    if (string_dec fd.(nameF) fname) then true else false.\n\n  Definition findMatchedFid (fs: FileSystem) (p: Path) (fname: string) : option Fid :=\n    find (fun x => fdata_eqb (fs.(f_map) x) fname) (findFids fs.(d_map) fs.(layout) p).\n\n  Section FileInTree.\n    Context (fmap : Fid -> FData).\n    Context (dmap : Did -> DData).\n\n    Inductive file_in_fnode: string -> Tree -> Prop :=\n      FIF: forall fname fId, (fmap fId).(nameF) = fname ->\n                             file_in_fnode fname (Fnode fId).\n\n    Inductive file_in_tree: Path -> string -> Tree -> Prop :=\n    | Empty_path_in_dnode: forall root fname treeL,\n        Exists (file_in_fnode fname) treeL -> file_in_tree [] fname (Dnode root treeL)\n    | Cons_path_in_dnode: forall root fname dname dlist treeL,\n        (exists did treeL',\n            In (Dnode did treeL') treeL /\\\n            (dmap did).(nameD) = dname /\\\n            file_in_tree dlist fname (Dnode did treeL')) ->\n        file_in_tree (dname :: dlist) fname (Dnode root treeL).\n\n    Inductive file_in_tree_with_id: Path -> string -> Tree -> Fid -> Prop :=\n    | Empty_path_fitwi: forall root fname treeL id,\n        In (Fnode id) treeL -> (fmap id).(nameF) = fname ->\n        file_in_tree_with_id [] fname (Dnode root treeL) id\n    | Cons_path_fitwi: forall root fname dname dlist treeL id,\n        (exists did treeL',\n            In (Dnode did treeL') treeL /\\\n            (dmap did).(nameD) = dname /\\\n            file_in_tree_with_id dlist fname (Dnode did treeL') id) ->\n        file_in_tree_with_id (dname :: dlist) fname (Dnode root treeL) id.\n\n  End FileInTree.\n\n  Definition testDmap (did: Did) :=\n    match did with\n    | O => Build_DData \"0\" (Build_Permission false false false)\n    | S O => Build_DData \"1\" (Build_Permission false false false)\n    | S (S O) => Build_DData \"2\" (Build_Permission false false false)\n    | S (S (S O)) => Build_DData \"3\" (Build_Permission false false false)\n    | S (S (S (S O))) => Build_DData \"4\" (Build_Permission false false false)\n    | _ => Build_DData \"5\" (Build_Permission false false false)\n    end.\n\n  Goal file_in_tree (fun _ => Build_FData \"file\"\n       (Build_Meta (Build_Permission false false false) O) nil) testDmap\n       [\"2\" ; \"4\"] \"file\" sampleTree.\n  Proof.\n    unfold sampleTree. constructor. exists 2, ([Dnode 4 [Fnode 4; Dnode 5 [];\n    Dnode 6 []; Dnode 7 [Dnode 8 [Dnode 9 []; Fnode 1; Fnode 2; Fnode 3]]]]). split.\n    - right. left. auto.\n    - split.\n      + constructor; auto.\n      + constructor. exists 4, [Fnode 4; Dnode 5 []; Dnode 6 []; Dnode 7 [Dnode 8\n        [Dnode 9 []; Fnode 1; Fnode 2; Fnode 3]]]. split. 1: left; auto.\n        split; constructor; auto. apply Exists_cons_hd. constructor. simpl. auto.\n  Qed.\n\n  Axiom truncate_page_length: forall str n1 n2,\n      n1 <= n2 -> String.length (truncate_page str n1 n2) = n2 - n1.\n\n  Definition fs_open (arg: fs_parameter 1) : State FSState (fs_result 1) :=\n    let (path, fname) := arg in\n    do fs <- getFS;\n      match findMatchedFid fs path fname with\n      | None => return_ (0, eBadF)\n      | Some fId =>\n        let opos := find (fun x => Nat.eqb (fst x) fId) fs.(open_handles) in\n        match opos with\n        | Some _ => return_ (fId, eBadF)\n        | None =>\n          do err <- externalCall (Call_VOpen path fname) (v_open path fname);\n            match err with\n            | eSucc => putOpenHandles ((fId, 0) :: fs.(open_handles)) >>\n                                      return_ (fId, eSucc)\n            | _ => return_ (fId, err)\n            end\n        end\n      end.\n\n  (* Compute (fs_open (\"root\" :: nil) \"\" (mkfs \"root\")). *)\n\n  Definition prod_dec {A B: Type} (a_dec: forall x y: A, {x = y} + {x <> y})\n             (b_dec: forall x y: B, {x = y} + {x <> y}) (n m: (A * B)) : {n = m} + {n <> m}.\n  Proof.\n    destruct n as [na nb]. destruct m as [ma mb]. destruct (a_dec na ma).\n    - subst. destruct (b_dec nb mb).\n      + subst. left; auto.\n      + right. intro. apply n. inversion H. auto.\n    - right. intro. apply n. inversion H. auto.\n  Defined.\n\n  Definition fs_close (fId: fs_parameter 2): State FSState (fs_result 2) :=\n    do oh <- getOpenHandles;\n      let opos := find (fun x => Nat.eqb (fst x) fId) oh in\n      match opos with\n      | None => return_ eBadF\n      | Some t =>\n        do err <- externalCall (Call_VClose fId) (v_close fId);\n          match err with\n          | eSucc =>\n            putOpenHandles (remove (prod_dec Nat.eq_dec Nat.eq_dec) t oh) >>\n                           return_ eSucc\n          | _ => return_ err\n          end\n      end.\n\n  Definition counter (fs: FSState) := length (snd fs).\n\n  Definition openhandleFS (fs: FSState) := @open_handles (fst fs).\n  Definition layoutFS (fs: FSState) := @layout (fst fs).\n  Definition vmFS (fs: FSState) := @virtual_memory (fst fs).\n  Definition fMapFS (fs: FSState) := @f_map (fst fs).\n  Definition dMapFS (fs: FSState) := @d_map (fst fs).\n  Definition fCntFS (fs: FSState) := @fnode_ctr (fst fs).\n  Definition dCntFS (fs: FSState) := @dnode_ctr (fst fs).\n  Definition logFS (fs: FSState) := snd fs.\n  Definition fsFS (fs: FSState) := fst fs.\n  Definition memHandleFS (fs: FSState) := @mmap_handles (fst fs).\n  Definition memoryFS (fs: FSState) := @mmap_memory (fst fs).\n\n  Definition f_map_append_page (fmap: Fid -> FData) (fId : Fid)\n             (page : Pgid) : (Fid -> FData) :=\n    fun id : Fid =>\n      if Nat.eq_dec id fId\n      then let fd := fmap fId in\n           Build_FData fd.(nameF) fd.(metaF) (fd.(pageIdsF) ++ (page :: nil))\n      else fmap id.\n\n  Parameter get_next_free_vpg: (Fid -> FData) -> Pgid.\n\n  Axiom get_next_free_vpg_axiom: forall (fmap: Fid -> FData) (fId: Fid),\n      ~ In (get_next_free_vpg fmap) (fmap fId).(pageIdsF) /\\\n      get_next_free_vpg fmap <= memory_upper_bound.\n\n  Fixpoint upd_nth {A: Type} (l: list A) (n: nat) (v: A) :=\n    match l with\n    | nil => nil\n    | a :: l' => match n with\n                 | O => v :: l'\n                 | S m => a :: upd_nth l' m v\n                 end\n    end.\n\n  Compute upd_nth [1; 2; 3; 4; 5] 2 1000.\n\n  Definition inputOrder (i1 i2 : string) := String.length i1 < String.length i2.\n\n  Lemma inputOrder_wf': forall len i, String.length i <= len -> Acc inputOrder i.\n  Proof.\n    induction len; intros; constructor; intros;\n      unfold inputOrder in * |-; [exfalso | apply IHlen]; intuition.\n  Qed.\n\n  Lemma inputOrder_wf : well_founded inputOrder.\n  Proof. red; intro; eapply inputOrder_wf'; eauto. Defined.\n\n  Lemma substring_length: forall n m s, String.length (substring n m s) <= m.\n  Proof.\n    intros. revert n m. induction s; intros; simpl.\n    - destruct n. destruct m. auto. simpl. intuition. simpl. intuition.\n    - destruct n. destruct m; simpl. auto. intuition. intuition.\n  Qed.\n\n  Lemma help_write_to_vm: forall (buf0 : string) (pos0 : nat),\n      buf0 <> \"\" ->\n      S (String.length\n           (substring (psize - pos0 mod psize)\n                      (String.length buf0 - (psize - pos0 mod psize)) buf0)) <=\n      String.length buf0.\n  Proof.\n    intros. rename H into n. assert (pos0 mod psize < psize) by\n        (apply Nat.mod_upper_bound; unfold psize; compute; intuition).\n    assert (0 < psize - pos0 mod psize) by omega.\n    remember (psize - pos0 mod psize) as i. clear Heqi H.\n    pose proof (substring_length i (String.length buf0 - i) buf0).\n    transitivity (S (String.length buf0 - i)). 1: intuition.\n    remember (String.length buf0) as l. assert (0 < l). destruct buf0.\n    1: exfalso; auto. simpl in Heql. intuition.\n    clear H Heql. omega.\n  Qed.\n\n  Fixpoint override {A: Type} (l: list A) (pos: nat) (l' : list A) : list A :=\n    match l with\n    | nil => match pos with\n             | O => l'\n             | S _ => nil\n             end\n    | a :: rl => match pos with\n                 | O => match l' with\n                        | nil => l\n                        | b :: rl' => b :: override rl O rl'\n                        end\n                 | S m => a :: override rl m l'\n                 end\n    end.\n\n  Compute override [] 0 [5; 6; 7].\n\n  Compute override [1; 2; 3; 4] 1 [5; 6].\n\n  Definition write_to_virtual_memory : string -> nat -> Fid -> (Fid -> FData) -> list Page -> sum (list Page * (Fid -> FData)) ErrCode.\n    refine (\n        Fix inputOrder_wf (fun _ => nat -> Fid -> (Fid -> FData) -> list Page -> sum (list Page * (Fid -> FData)) ErrCode)\n            (fun (buf: string) (write_to_vm: forall buf', inputOrder buf' buf -> nat -> Fid -> (Fid -> FData) -> list Page -> sum (list Page * (Fid -> FData)) ErrCode) (pos: nat) (fId: Fid) (fmap: Fid -> FData) (vm: list Page) =>\n               if string_dec buf EmptyString\n               then inl (vm, fmap)\n               else let len := String.length buf in\n                    let new_vm := vm in\n                    let new_map := fmap in\n                    let pg_offset := pos mod psize in\n                    let pgn := if Nat.eq_dec pg_offset O then pos / psize + 1 else pos / psize in\n                    let vpg := nth pgn (fmap fId).(pageIdsF) memory_upper_bound in\n                    let vpg_ret :=\n                        if Bool.bool_dec (andb (Nat.eqb vpg memory_upper_bound) (Nat.eqb pg_offset O)) true\n                        then (get_next_free_vpg new_map, true) else (vpg, false) in\n                    let vpg := fst vpg_ret in\n                    if Nat.eq_dec vpg memory_upper_bound\n                    then inr eNoSpc\n                    else if le_dec memory_upper_bound vpg\n                         then inr eInval\n                         else let new_map := if Sumbool.sumbool_of_bool (snd vpg_ret)\n                                             then f_map_append_page new_map fId vpg\n                                             else new_map in\n                              let curr_page_cont := nth vpg new_vm nil in\n                              let b1 := substring 0 (psize - pg_offset) buf in\n                              let buf := substring (psize - pg_offset) (len - (psize - pg_offset)) buf in\n                              let new_curr_pg_cont := override curr_page_cont pg_offset (string_to_byte_list b1) in\n                              let new_vm := upd_nth new_vm vpg new_curr_pg_cont in\n                              let pos := pos + psize - pg_offset in\n                              write_to_vm buf _ pos fId new_map new_vm)\n      ).\n    hnf. subst buf. subst len. subst pg_offset. clear -n. apply help_write_to_vm. apply n.\n  Defined.\n\n  Fixpoint getSublist {A: Type} (n m: nat) (l: list A) : list A :=\n    match n with\n    | 0 =>\n      match m with\n      | 0 => nil\n      | S m' =>\n        match l with\n        | nil => l\n        | c :: s' => c :: getSublist 0 m' s'\n        end\n      end\n    | S n' => match l with\n              | nil => l\n              | _ :: s' => getSublist n' m s'\n              end\n    end.\n\n  Definition get_write_pages (fId: Fid) (fmap: Fid -> FData) (vm: list Page) (pos: nat) (len: nat): list Pgid :=\n    let end_pos := if Nat.eq_dec ((pos + len) mod psize) O\n                   then (pos + len) / psize\n                   else (pos + len) / psize + 1 in\n    let start_pos := pos / psize in\n    getSublist start_pos (end_pos - start_pos + 1) (fmap fId).(pageIdsF).\n\n  Definition get_vmpg_no (page_no : nat) (fId: Fid) (fmap : Fid -> FData) : nat :=\n    nth  page_no (fmap fId).(pageIdsF) memory_upper_bound.\n\n  Definition change_f_map_pages\n             (fmap: Fid -> FData) (fId : Fid) (pages : list Pgid) : (Fid -> FData) :=\n    fun id : Fid => if Nat.eq_dec id fId\n                    then let fd := fmap fId in Build_FData fd.(nameF) fd.(metaF) pages\n                    else fmap id.\n\n  Definition change_f_map_size\n             (fmap: Fid -> FData) (fId : Fid) (new_size : nat) : (Fid -> FData) :=\n    fun id : Fid => if Nat.eq_dec id fId\n                    then let fd := fmap fId in Build_FData fd.(nameF) (Build_Meta fd.(metaF).(permission) new_size) fd.(pageIdsF)\n                    else fmap id.\n\n  Definition change_f_map_permission\n             (fmap: Fid -> FData) (fId : Fid) (p : Permission) : (Fid -> FData) :=\n    fun id : Fid => if Nat.eq_dec id fId\n                    then let fd := fmap fId in Build_FData fd.(nameF) (Build_Meta p fd.(metaF).(size)) fd.(pageIdsF)\n                    else fmap id.\n\n  Definition change_f_map\n             (fmap: Fid -> FData) (fId : Fid) (fdata: FData) : (Fid -> FData) :=\n    fun id : Fid => if Nat.eq_dec id fId then fdata else fmap id.\n\n  Definition get_new_size (fId: Fid) (fmap: Fid -> FData) (new_vm: list Page): nat :=\n    fold_right\n      Init.Nat.add O (map (fun n => length(nth n new_vm nil)) (fmap fId).(pageIdsF)).\n\n  Definition get_encrypted_buf (pages: list Pgid) (new_vm: list Page) : string :=\n    encrypt_page\n      (byte_list_to_string (concat (map (fun n => nth n new_vm nil) pages))).\n\n  Local Open Scope bool_scope.\n\n  Definition fs_write (arg: fs_parameter 3) : State FSState (fs_result 3) :=\n    let (fidBuf, pos) := arg in\n    let (fId, buf) := fidBuf in\n    do fs <- getFS;\n      let opos := find (fun x => Nat.eqb (fst x) fId) fs.(open_handles) in\n      match opos with\n      | None => return_ eBadF\n      | Some _ =>\n        let fsize := (fs.(f_map) fId).(metaF).(size) in\n        if (Nat.leb fsize pos) && ((negb (Nat.eqb pos O)) || (negb (Nat.eqb fsize O)))\n        then return_ eInval\n        else match write_to_virtual_memory buf pos fId fs.(f_map) fs.(virtual_memory) with\n             | inr err => return_ err\n             | inl (new_vm, new_f_map) =>\n               let len := String.length buf in\n               let pages := get_write_pages fId new_f_map new_vm pos len in\n               let encrypted_pages := get_encrypted_buf pages new_vm in\n               do err <- externalCall (Call_VLSeek fId (pos_to_vpage pos)) (v_lseek fId (pos_to_vpage pos));\n                 if (isNotSucc err)\n                 then return_ err\n                 else\n                   let new_len := pos_to_vlen pos len in\n                   do err <- externalCall (Call_VWrite fId encrypted_pages new_len) (v_write fId encrypted_pages new_len);\n                     if (isNotSucc err)\n                     then return_ err\n                     else\n                       let new_open_handles := replace_handler fId (pos + len) fs.(open_handles) in\n                       putOpenHandles new_open_handles >>\n                                      putVirtualMemory new_vm >>\n                                      putFMap (change_f_map_size new_f_map fId (max (new_f_map fId).(metaF).(size) (pos + len))) >>\n                                      return_ eSucc\n             end\n      end.\n\n  (* max (new_f_map fId).(metaF).(size) (pos + len) *)\n\n  Definition size_changed (fId: Fid) (fs postFS: FSState) (pos len: nat): Prop :=\n    ((fMapFS postFS) fId).(metaF).(size) = max (((fMapFS fs) fId).(metaF).(size)) (pos + len).\n\n  Definition fs_seek (arg: fs_parameter 4) : State FSState (fs_result 4) :=\n    let (fId, pos) := arg in\n    do fs <- getFS;\n      let opos := find (fun x => Nat.eqb (fst x) fId) fs.(open_handles) in\n      match opos with\n      | None => return_ eBadF\n      | Some _ =>\n        let fsize := (fs.(f_map) fId).(metaF).(size) in\n        if (Nat.leb fsize pos) && ((negb (Nat.eqb pos O)) || (negb (Nat.eqb fsize O)))\n        then return_ eInval\n        else\n          do err <- externalCall (Call_VLSeek fId (pos_to_vpage pos)) (v_lseek fId (pos_to_vpage pos));\n          if (isNotSucc err)\n          then return_ err\n          else let new_open_handles := replace_handler fId pos fs.(open_handles) in\n               putOpenHandles new_open_handles >>\n                              return_ eSucc\n      end.\n\n  Fixpoint addFnodeToTree (tree: Tree) (did: Did) (fId: Fid) : Tree :=\n    match tree with\n    | Fnode _ => tree\n    | Dnode did' li => if Nat.eq_dec did did'\n                       then Dnode did (Fnode fId :: li)\n                       else Dnode did' (map (fun t => addFnodeToTree t did fId) li)\n    end.\n\n  Compute (addFnodeToTree (addFnodeToTree (addFnodeToTree (addFnodeToTree sampleTree 9 5) 8 6) 0 7) 1 8).\n\n  Definition get_next_free_fid : State FSState Fid :=\n    fun x =>\n      let (fs, logs) := x in\n      (fs.(fnode_ctr), (Build_FileSystem fs.(layout) fs.(open_handles)\n       fs.(virtual_memory) fs.(f_map) fs.(d_map) (fs.(fnode_ctr) + 1)\n       fs.(dnode_ctr) fs.(mmap_handles) fs.(mmap_memory), logs)).\n\n  Definition fs_create (arg: fs_parameter 5) : State FSState (fs_result 5) :=\n    let (pf, p) := arg in\n    let (path, fname) := pf in\n    if string_dec fname EmptyString\n    then return_ eBadName\n    else\n      do fs <- getFS;\n      match findMatchedFid fs path fname with\n      | Some _ => return_ eExists\n      | None => match findDir fs.(d_map) fs.(layout) (app path (fname :: nil)) with\n                | Some _ => return_ eIsDir\n                | None => let parentdir := findDir fs.(d_map) fs.(layout) path in\n                          match parentdir with\n                          | None => return_ eNoDir\n                          | Some tr => match tr with\n                                       | Fnode _ => return_ eBadF\n                                       | Dnode did li =>\n                                         if bool_eq ((fs.(d_map) did).(metaD).(writable)) false\n                                         then return_ eAcces\n                                         else\n                                           do err <- externalCall (Call_VCreate path fname p) (v_create path fname p);\n                                           if (isNotSucc err)\n                                           then return_ err\n                                           else do newFId <- get_next_free_fid;\n                                           let newFData := Build_FData fname (Build_Meta p O) nil in\n                                           putFMap (change_f_map (fs.(f_map)) newFId newFData) >>\n                                                   putLayout (addFnodeToTree fs.(layout) did newFId) >>\n                                                   return_ eSucc\n                                       end\n                          end\n                end\n      end.\n\n  Definition get_next_free_did : State FSState Did :=\n    fun x =>\n      let (fs, logs) := x in\n      (fs.(dnode_ctr), (Build_FileSystem fs.(layout) fs.(open_handles)\n       fs.(virtual_memory) fs.(f_map) fs.(d_map) fs.(fnode_ctr)\n       (fs.(dnode_ctr) + 1) fs.(mmap_handles) fs.(mmap_memory), logs)).\n\n  Definition putDMap: (Did -> DData) -> State FSState unit :=\n    fun dmap x =>\n      let (fs, logs) := x in\n      (tt, (Build_FileSystem fs.(layout) fs.(open_handles) fs.(virtual_memory)\n            fs.(f_map) dmap fs.(fnode_ctr) fs.(dnode_ctr) fs.(mmap_handles)\n            fs.(mmap_memory), logs)).\n\n  Definition change_d_map (dmap: Did -> DData) (dId : Did) (ddata: DData) : (Did -> DData) :=\n    fun id : Did => if Nat.eq_dec id dId then ddata else dmap id.\n\n  Definition change_d_map_permission (dmap: Did -> DData) (dId : Did) (p: Permission) : (Did -> DData) :=\n    fun id : Did => if Nat.eq_dec id dId\n                    then let dd := dmap id in (Build_DData dd.(nameD) p)\n                    else dmap id.\n\n  Fixpoint addDidToTree (tree: Tree) (did: Did) (child_did: Did) : Tree :=\n    match tree with\n    | Fnode _ => tree\n    | Dnode did' li => if Nat.eq_dec did did'\n                       then Dnode did (Dnode child_did nil :: li)\n                       else Dnode did' (map (fun t => addDidToTree t did child_did) li)\n    end.\n\n  Definition fs_mkdir (arg: fs_parameter 6): State FSState (fs_result 6) :=\n    let (pd, p) := arg in\n    let (path, dname) := pd in\n    if string_dec dname EmptyString\n    then return_ eBadName\n    else\n      do fs <- getFS;\n      match findMatchedFid fs path dname with\n      | Some _ => return_ eNotDir\n      | None => match findDir fs.(d_map) fs.(layout) (app path (dname :: nil)) with\n                | Some _ => return_ eExists\n                | None => let parentdir := findDir fs.(d_map) fs.(layout) path in\n                          match parentdir with\n                          | None => return_ eNoEnt\n                          | Some tr => match tr with\n                                       | Fnode _ => return_ eBadF\n                                       | Dnode did li =>\n                                         if bool_eq ((fs.(d_map) did).(metaD).(writable)) false\n                                         then return_ eAcces\n                                         else\n                                           do err <- externalCall (Call_VMkdir path dname p) (v_mkdir path dname p);\n                                           if (isNotSucc err)\n                                           then return_ err\n                                           else do newDid <- get_next_free_did;\n                                           let newDData := Build_DData dname p in\n                                           putDMap (change_d_map (fs.(d_map)) newDid newDData) >>\n                                                   putLayout (addDidToTree fs.(layout) did newDid) >>\n                                                   return_ eSucc\n                                       end\n                          end\n                end\n      end.\n\n  Compute (fst (mkfs \"root\")).(layout).\n\n  Compute let fss := (mkfs \"root\") in let fs := fst fss in findDir fs.(d_map) fs.(layout) [].\n\n  Fixpoint removeDirFromList (trees: list Tree) (did: Did) : list Tree :=\n    match trees with\n    | nil => nil\n    | (Dnode did' _) as x :: l => if Nat.eq_dec did' did then removeDirFromList l did else x :: removeDirFromList l did\n    | x :: l => x :: removeDirFromList l did\n    end.\n\n  Fixpoint removeDirFromTree (tree: Tree) (parentDid : Did) (did: Did) : Tree :=\n    match tree with\n    | Fnode _ => tree\n    | Dnode did' li => if Nat.eq_dec parentDid did'\n                       then Dnode did' (removeDirFromList li did)\n                       else Dnode did' (map (fun t => removeDirFromTree t parentDid did) li)\n    end.\n\n  Definition fs_rmdir (path: fs_parameter 7) : State FSState (fs_result 7) :=\n    match path with\n    | nil => return_ eInval\n    | _ => do fs <- getFS;\n             match findDir fs.(d_map) fs.(layout) path with\n             | None => return_ eNoEnt\n             | Some (Fnode _) => return_ eNoEnt\n             | Some (Dnode did l) =>\n               match l with\n               | x :: l' => return_ eNotEmpty\n               | nil => match findDir fs.(d_map) fs.(layout) (removelast path) with\n                        | None => return_ eNoEnt\n                        | Some (Fnode _) => return_ eNoEnt\n                        | Some (Dnode parentId l') =>\n                          match (fs.(d_map) parentId).(metaD).(writable) with\n                          | false => return_ eAcces\n                          | true =>\n                            do err <- externalCall (Call_VRmdir path) (v_rmdir path);\n                              (if isNotSucc err\n                               then return_ err\n                               else putDMap (change_d_map fs.(d_map) did (Build_DData EmptyString (Build_Permission false false false))) >>\n                                            putLayout (removeDirFromTree fs.(layout) parentId did) >>\n                                            return_ eSucc)\n                          end\n                        end\n               end\n             end\n    end.\n\n  Fixpoint removeFnodeFromList (trees : list Tree) (fId : Fid) : list Tree :=\n    match trees with\n    | nil => nil\n    | Fnode f as x :: l => if Nat.eq_dec f fId\n                           then removeFnodeFromList l fId\n                           else x :: removeFnodeFromList l fId\n    | x :: l => x :: removeFnodeFromList l fId\n    end.\n\n  Fixpoint removeFnodeFromTree (tree: Tree) (did: Did) (fId: Fid) : Tree :=\n    match tree with\n    | Fnode _ => tree\n    | Dnode did' li => if Nat.eq_dec did did'\n                       then Dnode did (removeFnodeFromList li fId)\n                       else Dnode did' (map (fun t => removeFnodeFromTree t did fId) li)\n    end.\n\n  Definition fs_remove (arg: fs_parameter 8): State FSState (fs_result 8) :=\n    let (path, fname) := arg in\n    if string_dec fname \"\"\n    then return_ eBadName\n    else\n      do fs <- getFS;\n      match findMatchedFid fs path fname with\n      | None => return_ eNoEnt\n      | Some fId =>\n        match findDir (d_map fs) (layout fs) path with\n        | None => return_ eNotDir\n        | Some (Fnode _) => return_ eBadF\n        | Some (Dnode did _) =>\n          if bool_eq (writable (metaD (d_map fs did))) false\n          then return_ eAcces\n          else\n            do err <-\n               externalCall (Call_VRemove path fname) (v_remove path fname);\n            (if isNotSucc err\n             then return_ err\n             else\n               (putFMap (change_f_map (f_map fs) fId (Build_FData EmptyString (Build_Meta (Build_Permission false false false) O) nil))) >>\n                                                                                                                                         putLayout (removeFnodeFromTree (layout fs) did fId) >>\n                                                                                                                                         return_ eSucc)\n        end\n      end.\n\n  Definition foot (l: Path) : string := last l EmptyString.\n\n  Definition fs_chmod (arg: fs_parameter 9) : State FSState (fs_result 9) :=\n    let (path, p) := arg in\n    do fs <- getFS;\n      let flag := match findDir fs.(d_map) fs.(layout) path with\n                  | Some (Fnode _) => None\n                  | Some (Dnode did _) => Some (true, did)\n                  | None => match path with\n                            | nil => None\n                            | _ => match findMatchedFid fs (removelast path) (foot path) with\n                                   | None => None\n                                   | Some fId => Some (false, fId)\n                                   end\n                            end\n                  end in\n      match flag with\n      | None => return_ eNoEnt\n      | Some (x, id) =>\n        do err <- externalCall (Call_VChmod path p) (v_chmod path p);\n          (if isNotSucc err\n           then return_ err\n           else match x with\n                | true => putDMap (change_d_map_permission fs.(d_map) id p) >> return_ eSucc\n                | false => putFMap (change_f_map_permission fs.(f_map) id p) >> return_ eSucc\n                end)\n      end.\n\n  Definition fs_readdir (path: fs_parameter 10) : State FSState (fs_result 10) :=\n    do fs <- getFS;\n      match findDir fs.(d_map) fs.(layout) path with\n      | None => return_ (nil, eBadF)\n      | Some (Fnode _) => return_ (nil, eBadF)\n      | Some (Dnode did l) =>\n        do err <- externalCall (Call_VReadDir path) (v_readdir path);\n          (if isNotSucc err\n           then return_ (nil, err)\n           else return_ (map (treeName fs.(f_map) fs.(d_map)) l, eSucc))\n      end.\n\n  Definition ttf : Permission := Build_Permission true true false.\n  Definition fff : Permission := Build_Permission false false false.\n\n  Definition fs_fstat (fId: fs_parameter 11): State FSState (fs_result 11) :=\n    do fs <- getFS;\n      do oh <- getOpenHandles;\n      let opos := find (fun x => Nat.eqb (fst x) fId) oh in\n      match opos with\n      | None => return_ ((EmptyString, fff, O, nil), eBadF)\n      | Some (_, pos) =>\n        do err <- externalCall (Call_VStat fId) (v_stat fId);\n          (if isNotSucc err\n           then return_ ((EmptyString, fff, O, nil), err)\n           else let fd := fs.(f_map) fId in\n                return_ ((fd.(nameF), fd.(metaF).(permission), fd.(metaF).(size), fd.(pageIdsF)), eSucc))\n      end.\n\n  (* TODO: check the pointer in open handles *)\n\n  Definition fs_truncate (arg: fs_parameter 12): State FSState (fs_result 12) :=\n    let (fId, len) := arg in\n    do fs <- getFS;\n      match find (fun x : nat * nat => Nat.eqb (fst x) fId) (open_handles fs) with\n      | None => return_ eBadF\n      | Some _ =>\n        let fsize := size (metaF (f_map fs fId)) in\n        if (fsize <? len) && (negb (Nat.eqb len 0) || negb (Nat.eqb fsize 0))\n        then return_ eInval\n        else if (Nat.eqb fsize len)\n             then return_ eSucc\n             else let new_last_page := if Nat.eq_dec (len mod psize) O then len / psize else len / psize + 1 in\n                  let last_page_content := encrypt_page (truncate_page (byte_list_to_string\n                                                                          (nth (nth new_last_page (fs.(f_map) fId).(pageIdsF) O) fs.(virtual_memory) nil)) O (len mod psize)) in\n                  let ext_write_pos := len / psize * block_size in\n                  do err <- externalCall (Call_VTruncate fId ext_write_pos last_page_content) (v_truncate fId ext_write_pos last_page_content);\n                  (if isNotSucc err\n                   then return_ err\n                   else putFMap (change_f_map_pages (change_f_map_size fs.(f_map) fId len) fId (getSublist O new_last_page (fs.(f_map) fId).(pageIdsF))) >>\n                                return_ eSucc)\n      end.\n\n  Lemma mmap_mode_eq_dec: forall m1 m2: MmapMode, {m1 = m2} + {~ m1 = m2}.\n  Proof. intros. destruct m1, m2; try (left; easy); try (right; easy). Qed.\n\n  Fixpoint check_if_continuous (addrs: list Memid) : bool :=\n    match addrs with\n    | nil => true\n    | n :: l' => match l' with\n                 | nil => true\n                 | m :: l'' => if Nat.eq_dec m (S n)\n                               then check_if_continuous l'\n                               else false\n                 end\n    end.\n\n  Compute (check_if_continuous [2; 3; 4; 5; 6; 7]).\n\n  Compute (check_if_continuous [2; 3; 4; 5; 6; 8]).\n\n  Definition check_size (addr_len total_len: nat): bool :=\n    if Nat.eq_dec addr_len O\n    then false\n    else if ge_dec (addr_len * block_size) total_len\n         then if lt_dec ((pred addr_len) * block_size) total_len\n              then true\n              else false\n         else false.\n\n  Compute (check_size O 5).\n  Compute (check_size 1 4000).\n\n  Fixpoint check_range (addrs: list Memid) (len: nat): bool :=\n    match addrs with\n    | nil => true\n    | x :: l => if lt_dec x len\n                then check_range l len\n                else false\n    end.\n\n  Compute (check_range [1;2;3;4;5] 6).\n  Compute (check_range [1;2;3;4;5] 5).\n\n  Definition write_zeroes (addrs: list Memid) (mem: MmapedMemory) : MmapedMemory :=\n    match addrs with\n    | nil => mem\n    | x :: _ => let len := length addrs in\n                app (app (firstn x mem) (repeat (repeat Ascii.zero block_size) len))\n                    (skipn (x + len) mem)\n    end.\n\n  Definition interval_between (n start len: nat) : bool :=\n    if le_dec start n then if lt_dec n (start + len) then true else false else false.\n\n  Definition interval_overlap (s1 len1 s2 len2: nat): bool :=\n    interval_between s1 s2 len2 || interval_between s2 s1 len1.\n\n  Fixpoint check_overlap (start: Memid) (addrs_len: nat)\n           (handles: list (Memid * nat * Permission)): bool :=\n    match handles with\n    | nil => false\n    | ((s2, t_len), _) :: l =>\n      if interval_overlap start addrs_len s2 (pad_size t_len)\n      then true\n      else check_overlap start addrs_len l\n    end.\n\n  Definition mmap (len: nat) (perm: Permission) (flag: MmapMode):\n    State FSState (Memid * ErrCode):=\n    do fs <- getFS;\n      if mmap_mode_eq_dec flag mapAnon\n      then let mem := mmap_memory fs in\n           do mmap_address <- externalCall (Call_AllocMem mem len)\n              (allocate_memory mem len);\n             let addrs_len := length mmap_address in\n             let head_addr := hd O mmap_address in\n             if check_if_continuous mmap_address &&\n                check_size addrs_len len &&\n                check_range mmap_address (length mem) &&\n                negb (check_overlap head_addr addrs_len (mmap_handles fs))\n             then putMmapMemory (write_zeroes mmap_address mem) >>\n                  putMmapHandles ((head_addr, len, perm) :: (mmap_handles fs)) >>\n                  return_ (head_addr, eSucc)\n           else return_ (O, eMapFailed)\n      else return_ (O, eMapFailed).\n\n  Definition neqMmapHandle (mid: Memid) (len: nat)\n             (h: Memid * nat * Permission) : bool :=\n    match h with | (s, lens, _) => negb (Nat.eqb mid s) || negb (Nat.eqb len lens) end.\n\n  Definition munmap (mid: Memid) (len: nat): State FSState ErrCode :=\n    do fs <- getFS;\n      if forallb (neqMmapHandle mid len) (mmap_handles fs)\n      then return_ eInval\n      else let mem := mmap_memory fs in\n           do succ <- externalCall (Call_DeallocMem mem mid len)\n              (deallocate_memory mem mid len);\n             if succ\n             then putMmapHandles (filter (neqMmapHandle mid len) (mmap_handles fs)) >>\n                  return_ eSucc\n             else return_ eInval.\n\n  Definition newFS1 : FSState := snd (fs_create ([], \"foo.txt\", ttf) (mkfs \"root\")).\n\n  (* Compute (fs_create [] \"bar.txt\" ttf newFS1). *)\n\n  Lemma find_Fid_In: forall (l: list (Fid * nat)) fId p,\n      find (fun x : nat * nat => Nat.eqb (fst x) fId) l = Some p -> In fId (map fst l).\n  Proof.\n    induction l; intros; simpl in *. 1: inversion H.\n    destruct (Nat.eqb (@fst nat nat a) fId) eqn: ?; [left | right].\n    - rewrite Nat.eqb_eq in Heqb. auto.\n    - apply (IHl _ p); auto.\n  Qed.\n\n  Lemma find_Fid_In': forall (l: list (Fid * nat)) fId p,\n      find (fun x : nat * nat => Nat.eqb (fst x) fId) l = Some p -> In p l /\\ fst p = fId.\n  Proof.\n    induction l; intros; simpl in *. 1: inversion H.\n    destruct (Nat.eqb (@fst nat nat a) fId) eqn: ?.\n    - inversion H. subst a. rewrite Nat.eqb_eq in Heqb. intuition.\n    - specialize (IHl _ _ H). intuition.\n  Qed.\n\n  Lemma find_Fid_None: forall (l : list (Fid * nat)) fId,\n      In fId (map fst l) -> find (fun x  => Nat.eqb (fst x) fId) l = None -> False.\n  Proof.\n    induction l; intros; simpl in *; auto.\n    destruct (Nat.eqb (@fst nat nat a) fId) eqn: ?. 1: inversion H0. destruct H.\n    - rewrite Nat.eqb_neq in Heqb. auto.\n    - apply (IHl fId); auto.\n  Qed.\n\n  Lemma fs_close_not_found: forall fId (fs: FSState) err postFS,\n      ~ In fId (map fst (openhandleFS fs)) -> (err, postFS) = (fs_close fId fs) ->\n      postFS = fs /\\ err = eBadF.\n  Proof.\n    intros. destruct fs. unfold fs_close in H0. destruct f eqn:?. simpl in H0.\n    destruct (find (fun x : nat * nat => Nat.eqb (fst x) fId) open_handles0) eqn:?.\n    - exfalso. clear H0. unfold openhandleFS in H. unfold open_handles in H.\n      simpl in H. apply H. apply (find_Fid_In _ _ p); auto.\n    - inversion H0. auto.\n  Qed.\n\n  Ltac rm_if := match goal with | [ |- context [if ?A then _ else _]] =>\n                                  destruct A; auto end.\n\n  Ltac rm_if_eqn := match goal with | [ |- context [if ?A then _ else _]] =>\n                                      destruct A eqn: ?; auto end.\n\n  Ltac rm_hif := match goal with |[_ : context [if ?A then _ else _] |- _ ] =>\n                                  destruct A end.\n\n  Ltac rm_hif_eqn H := match goal with |[H : context [if ?A then _ else _] |- _ ] =>\n                                        destruct A eqn:? end.\n\n  Ltac rm_hmatch := match goal with\n                    |[_ : context [match ?A with | _ => _ end] |- _ ] =>\n                     destruct A eqn:? end.\n\n  Lemma find_Fid_remove: forall (l: list (Fid * nat)) p fId,\n      NoDup (map fst l) -> find (fun x : nat * nat => Nat.eqb (fst x) fId) l = Some p ->\n      ~ In fId (map fst (remove (prod_dec Nat.eq_dec Nat.eq_dec) p l)).\n  Proof.\n    induction l; intros; simpl in *. 1: inversion H0. rm_hmatch.\n    - inversion H0. subst a. clear H0. rewrite Nat.eqb_eq in Heqb. rm_if.\n      rewrite NoDup_cons_iff in H. destruct H. subst fId. intro. apply H. clear -H1.\n      induction l; simpl in *; auto. rm_hif.\n      + subst. left; auto.\n      + simpl in H1. destruct H1; [left | right; apply IHl]; auto.\n    - rewrite NoDup_cons_iff in H. destruct H. specialize (IHl _ _ H1 H0).\n      rm_if. simpl map. intro; apply IHl. simpl in H2. destruct H2; auto.\n      subst fId. exfalso. rewrite Nat.eqb_neq in Heqb. apply Heqb; auto.\n  Qed.\n\n  Lemma remove_not_in {A: Type} (eq_dec : forall x y : A, {x = y} + {x <> y}):\n    forall l x, ~ In x l -> remove eq_dec x l = l.\n  Proof.\n    induction l; intros; simpl; auto. destruct (eq_dec x a). subst.\n    exfalso; apply H, in_eq. f_equal. apply IHl. intro; apply H. apply in_cons. auto.\n  Qed.\n\n  Lemma find_Fid_Permutation: forall (l: list (Fid * nat)) p fId,\n      NoDup (map fst l) -> find (fun x : nat * nat => Nat.eqb (fst x) fId) l = Some p ->\n      Permutation (map fst l)\n                  (fId :: map fst (remove (prod_dec Nat.eq_dec Nat.eq_dec) p l)).\n  Proof.\n    induction l; intros; simpl in *. 1: inversion H0. rm_hmatch.\n    - inversion H0. subst a. clear H0. rewrite Nat.eqb_eq in Heqb. rm_if.\n      2: exfalso; apply n; reflexivity. unfold Fid in *. rewrite Heqb. constructor.\n      rewrite NoDup_cons_iff in H. destruct H.\n      assert (~ In p l) by (intro; apply H; apply (in_map fst) in H1; assumption).\n      pose proof (remove_not_in (prod_dec Nat.eq_dec Nat.eq_dec) _ _ H1).\n      rewrite H2. reflexivity.\n    - rewrite NoDup_cons_iff in H. destruct H. specialize (IHl _ _ H1 H0). rm_if.\n      + exfalso. apply Nat.eqb_neq in Heqb. apply find_Fid_In' in H0.\n        destruct H0. subst p. auto.\n      + simpl.\n        transitivity (fst a :: fId ::\n                          map fst (remove (prod_dec Nat.eq_dec Nat.eq_dec) p l)).\n        2: constructor. constructor. assumption.\n  Qed.\n\n  (* We need a stronger condition for open_handles *)\n  Lemma fs_close_found: forall fId (fs: FSState) err postFS,\n      NoDup (map fst (openhandleFS fs)) ->\n      In fId (map fst (openhandleFS fs)) ->\n      v_close fId (counter fs) = eSucc ->\n      (err, postFS) = (fs_close fId fs) ->\n      (~ In fId (map fst (openhandleFS postFS))) /\\\n      layoutFS fs = layoutFS postFS /\\\n      vmFS fs = vmFS postFS /\\\n      fMapFS fs = fMapFS postFS /\\\n      dMapFS fs = dMapFS postFS /\\\n      err = eSucc.\n  Proof.\n    intros. destruct fs. unfold counter, openhandleFS,\n                         layoutFS, vmFS, fMapFS, dMapFS in *.\n    simpl in *. rename H2 into Heqp. unfold fs_close in Heqp.\n    destruct f eqn:?. simpl in *.\n    destruct (find (fun x : nat * nat => Nat.eqb (fst x) fId) open_handles0) eqn:?.\n    - unfold externalCall in Heqp.\n      destruct (v_close fId (Datatypes.length l)) eqn: ?; [|inversion H1..].\n      unfold putOpenHandles in Heqp. inversion Heqp. split; [|intuition]. simpl.\n      apply find_Fid_remove; auto.\n    - exfalso. apply (find_Fid_None open_handles0 fId); auto.\n  Qed.\n\n  Lemma fs_close_failed: forall fId (fs: FSState) v_err err postFS,\n      In fId (map fst (openhandleFS fs)) ->\n      v_err = v_close fId (counter fs) -> v_err <> eSucc ->\n      (err, postFS) = fs_close fId fs -> err = v_err /\\ fst fs = fst postFS.\n  Proof.\n    intros. destruct fs. rename H2 into Heqp. unfold fs_close in Heqp. simpl in *.\n    destruct (find (fun x : nat * nat => Nat.eqb (fst x) fId) f.(open_handles)) eqn:?.\n    - unfold externalCall in Heqp. unfold counter in H0.\n      simpl in H0. destruct postFS. simpl.\n      destruct (v_close fId (Datatypes.length l)) eqn:? ;\n        [exfalso; intuition| subst v_err; inversion Heqp; auto..].\n    - exfalso. destruct f eqn:? . unfold openhandleFS in H. unfold open_handles in *.\n      simpl in *. apply (find_Fid_None open_handles0 fId); auto.\n  Qed.\n\n  Lemma fs_close_ok: forall fId (fs: FSState) err postFS,\n       good_file_system (fsFS fs) ->\n      (err, postFS) = fs_close fId fs ->\n      (~ In fId (map fst (openhandleFS fs)) /\\ postFS = fs /\\ err = eBadF) \\/\n      (In fId (map fst (openhandleFS fs)) /\\ (~ In fId (map fst (openhandleFS postFS)))\n       /\\ (Permutation (map fst (openhandleFS fs))\n                       (fId :: map fst (openhandleFS postFS))) /\\\n       layoutFS fs = layoutFS postFS /\\ vmFS fs = vmFS postFS /\\\n       fMapFS fs = fMapFS postFS /\\ dMapFS fs = dMapFS postFS /\\ err = eSucc /\\\n       fnode_ctr (fsFS fs) = fnode_ctr (fsFS postFS) /\\\n       dnode_ctr (fsFS fs) = dnode_ctr (fsFS postFS) /\\\n       mmap_handles (fsFS fs) = mmap_handles (fsFS postFS) /\\\n       mmap_memory (fsFS fs) = mmap_memory (fsFS postFS) /\\\n       logFS postFS = Call_VClose fId eSucc :: logFS fs) \\/\n      (In fId (map fst (openhandleFS fs)) /\\ err <> eSucc /\\ fst fs = fst postFS /\\\n       logFS postFS = Call_VClose fId err :: logFS fs).\n  Proof.\n    intros. unfold fs_close in H0. simpl in H0. rm_hmatch.\n    - right. pose proof Heqo. apply find_Fid_In in Heqo. destruct fs.\n      simpl in H0. rm_hmatch; [|right; inversion H0; simpl; intuition; inversion H2..].\n      left. simpl in H0. inversion H0.\n      unfold openhandleFS, layoutFS, vmFS, fMapFS, dMapFS, logFS. simpl.\n      split; [|split; [|split; [|split; [|split; [|split; [|split;[|split]]]]]]]; auto.\n      * apply find_Fid_remove; auto. destruct H. intuition.\n      * simpl fst in H1. destruct H as [_ [_ [_ [_ [_ [? _]]]]]]. simpl in *.\n        apply find_Fid_Permutation; assumption.\n    - left. inversion H0. intuition. eapply find_Fid_None; eauto.\n  Qed.\n\n  Lemma fs_read_not_found: forall fId len (fs: FSState) err buf postFS,\n      ~ In fId (map fst (openhandleFS fs)) ->\n      (buf, err, postFS) = (fs_read (fId, len) fs) -> postFS = fs /\\ err = eBadF.\n  Proof.\n    intros. destruct fs. unfold fs_read in H0. destruct f eqn:?. simpl in H0.\n    destruct (find (fun x : nat * nat => Nat.eqb (fst x) fId) open_handles0) eqn:?.\n    - exfalso. clear H0. unfold openhandleFS in H. unfold open_handles in H.\n      simpl in H. apply H. apply (find_Fid_In _ _ p); auto.\n    - inversion H0. auto.\n  Qed.\n\n  Lemma replace_handler_preserve_fst: forall l fId pos,\n      map fst (replace_handler fId pos l) = map fst l.\n  Proof.\n    induction l; intros; simpl; auto. destruct a.\n    destruct (Nat.eq_dec fId f); simpl; auto. f_equal. apply IHl.\n  Qed.\n\n  Lemma replace_handler_replaces: forall l fId pos1 pos2,\n      In (fId, pos1) l -> In (fId, pos2) (replace_handler fId pos2 l).\n  Proof.\n    induction l; intros; simpl; auto. destruct a. simpl in H. destruct H.\n    - inversion H. subst f. subst n. destruct (Nat.eq_dec fId fId).\n      2: exfalso; apply n; auto. left; auto.\n    - destruct (Nat.eq_dec fId f). 1: subst f; left; auto. right.\n      apply (IHl _ pos1); auto.\n  Qed.\n\n  Lemma In_find_fId_the_same: forall (l: list (Fid * nat)) fId p1 p2,\n      NoDup (map fst l) -> In (fId, p1) l -> In (fId, p2) l -> p1 = p2.\n  Proof.\n    induction l; intros; simpl in *. 1: exfalso; auto. destruct H0, H1.\n    - rewrite H1 in H0. inversion H0; auto.\n    - subst a. simpl in H. apply (in_map fst) in H1. simpl in H1.\n      rewrite NoDup_cons_iff in H. destruct H. exfalso; auto.\n    - subst a. simpl in H. apply (in_map fst) in H0. simpl in H0.\n      rewrite NoDup_cons_iff in H. destruct H. exfalso; auto.\n    - simpl in H. apply NoDup_cons_iff in H. destruct H. apply (IHl fId); auto.\n  Qed.\n\n  Lemma fs_read_ok: forall fId len (fs: FSState) err buf postFS,\n      (buf, err, postFS) = (fs_read (fId, len) fs) ->\n      NoDup (map fst (openhandleFS fs)) ->\n      (~ In fId (map fst (openhandleFS fs)) /\\ postFS = fs /\\ err = eBadF) \\/\n      (exists pos, In (fId, pos) (openhandleFS fs) /\\ (pos + len) >= (fMapFS fs fId).(metaF).(size) /\\\n                   postFS = fs /\\ err = eInval) \\/\n      (In fId (map fst (openhandleFS fs)) /\\ buf = \"\" /\\ err <> eSucc /\\\n       fsFS postFS = fsFS fs /\\\n       exists p1 p2 vlseek_ret,\n         hd_error (logFS postFS) = Some (Call_VLSeek p1 p2 vlseek_ret) /\\\n         err = vlseek_ret /\\\n         logFS postFS = Call_VLSeek p1 p2 vlseek_ret :: logFS fs) \\/\n      (In fId (map fst (openhandleFS fs)) /\\ buf = \"\" /\\ fsFS postFS = fsFS fs /\\\n       exists vread_ret p1 p2,\n         err = snd vread_ret /\\\n         hd_error (logFS postFS) = Some (Call_VRead p1 p2 vread_ret) /\\\n         snd vread_ret <> eSucc /\\\n         exists p3 p4, logFS postFS =\n                       Call_VRead p1 p2 vread_ret ::\n                                  Call_VLSeek p3 p4 eSucc :: logFS fs) \\/\n      (In fId (map fst (openhandleFS fs)) /\\ buf = \"\" /\\ fsFS postFS = fsFS fs /\\\n       err = eBadPage /\\\n       exists vread_ret p1 p2,\n         hd_error (logFS postFS) = Some (Call_VRead p1 p2 vread_ret) /\\\n         snd vread_ret = eSucc /\\\n         exists p3 p4,\n           logFS postFS = Call_VRead p1 p2 vread_ret ::\n                                     Call_VLSeek p3 p4 eSucc :: logFS fs) \\/\n      (In fId (map fst (openhandleFS fs)) /\\ err = eSucc /\\ String.length buf = len /\\\n       layoutFS fs = layoutFS postFS /\\ vmFS fs = vmFS postFS /\\\n       fMapFS fs = fMapFS postFS /\\\n       dMapFS fs = dMapFS postFS /\\\n       fnode_ctr (fsFS fs) = fnode_ctr (fsFS postFS) /\\\n       dnode_ctr (fsFS fs) = dnode_ctr (fsFS postFS) /\\\n       mmap_handles (fsFS fs) = mmap_handles (fsFS postFS) /\\\n       mmap_memory (fsFS fs) = mmap_memory (fsFS postFS) /\\\n       map fst (openhandleFS postFS) = map fst (openhandleFS fs) /\\\n       (forall pos, In (fId, pos) (openhandleFS fs) ->\n                    In (fId, pos + len) (openhandleFS postFS)) /\\\n       exists vread_ret p1 p2,\n         hd_error (logFS postFS) = Some (Call_VRead p1 p2 vread_ret) /\\\n         snd vread_ret = eSucc /\\\n         exists p3 p4, logFS postFS = Call_VRead p1 p2 vread_ret ::\n                                                 Call_VLSeek p3 p4 eSucc :: logFS fs).\n  Proof.\n    intros. destruct (in_dec Nat.eq_dec fId (map fst (openhandleFS fs))).\n    - right. pose proof H. unfold fs_read in H1. simpl in H1. rm_hmatch.\n      + destruct p as [? pos]. destruct fs. simpl in H1. rm_hif.\n        * left. exists pos. inversion H1. intuition. apply find_Fid_In' in Heqo.\n          destruct Heqo. simpl in H6. subst n. auto.\n        * right. simpl in H1. rm_hif.\n          -- left. inversion H1. simpl. split; [|split; [|split; [|split]]]; auto.\n          exists fId, (pos_to_vpage pos),\n          (v_lseek fId (pos_to_vpage pos) (Datatypes.length l)). intuition.\n          -- simpl in H1. right.\n             destruct (v_read fId (pos_to_vlen pos len) (S (Datatypes.length l))) as\n                 [str errR]. destruct (isNotSucc errR) eqn: ?.\n             ++ left. inversion H1. simpl in *. split; [|split; [|split]]; auto.\n                exists (str, errR), fId, (pos_to_vlen pos len). simpl.\n                split; [|split; [|split]]; auto. exists fId, (pos_to_vpage pos).\n                rewrite <- e. auto.\n             ++ right. destruct (verify_page (decrypt_page str)).\n                ** right. simpl in H1. inversion H1. destruct f. simpl.\n                   unfold openhandleFS, layoutFS, vmFS, fMapFS, dMapFS, logFS, snd.\n                   simpl.\n                   split; [|split; [|split; [|split; split; [|split; [|split; [|split; [|split; [|split; [|split; [|split; [|split]]]]]]]]]]]; auto.\n                   --- rewrite truncate_page_length; intuition.\n                   --- simpl. rewrite replace_handler_preserve_fst; auto.\n                   --- unfold open_handles in *. unfold openhandleFS in *. simpl in *.\n                       intros. clear -Heqo H0 H2. apply find_some in Heqo.\n                       destruct Heqo. rewrite Nat.eqb_eq in H1. simpl in H1. subst n.\n                       assert (pos = pos0) by (eapply In_find_fId_the_same; eauto).\n                       subst pos0. apply (replace_handler_replaces _ _ pos); auto.\n                   --- exists (str, errR), fId, (pos_to_vlen pos len).\n                       split; [|split]; auto. rewrite e.\n                       exists fId, (pos_to_vpage pos); auto.\n                ** left. inversion H1. simpl in *.\n                   split; [|split; [|split; [|split]]]; auto.\n                   exists (str, errR), fId, (pos_to_vlen pos len). simpl.\n                   split; [|split]; auto. exists fId, (pos_to_vpage pos). rewrite e. auto.\n      + exfalso. unfold openhandleFS in i. destruct fs. destruct f.\n        unfold open_handles in *. simpl in *. eapply find_Fid_None; eauto.\n    - left. split; auto. eapply fs_read_not_found; eauto.\n  Qed.\n\n  Lemma collectBareFids_app: forall l1 l2,\n      collectBareFids (l1 ++ l2) = (collectBareFids l1 ++ collectBareFids l2)%list.\n  Proof.\n    induction l1; intros; simpl; auto. destruct a. 2: apply IHl1.\n    simpl. rewrite IHl1. auto.\n  Qed.\n\n  Lemma find_app_not_in: forall {A} (f: A -> bool) l1 l2,\n      (forall x, In x l1 -> f x = false) -> find f (l1 ++ l2) = find f l2.\n  Proof.\n    intros. induction l1; simpl; auto. destruct (f a) eqn: ?.\n    - assert (In a (a :: l1)) by (simpl; intuition). specialize (H a H0).\n      rewrite H in Heqb. inversion Heqb.\n    - apply IHl1. intros. apply H. simpl; intuition.\n  Qed.\n\n  Lemma findFids_the_same: forall fmap dmap d l d' l' dname path,\n      NoDupNameTree fmap dmap (Dnode d l) -> In (Dnode d' l') l ->\n      nameD (dmap d') = dname ->\n      findFids dmap (Dnode d' l') path = findFids dmap (Dnode d l) (dname :: path).\n  Proof.\n    intros. unfold findFids.\n    cut (findDir dmap (Dnode d' l') path = findDir dmap (Dnode d l) (dname :: path)).\n    1: intro S; rewrite S; auto. simpl.\n    cut (find (fun x : Tree => root_eq dmap x dname) l = Some (Dnode d' l')).\n    1: intro S; rewrite S; auto. inversion H. clear -H0 H1 H7. apply in_split in H0.\n    destruct H0 as [l1 [l2 ?]]. subst l. rewrite find_app_not_in.\n    - simpl. unfold DData_eqb. rewrite H1. destruct (string_dec dname dname); auto.\n      exfalso; apply n; auto.\n    - rewrite map_app, map_cons in H7. apply NoDup_remove_2 in H7.\n      unfold treeName in H7 at 1. rewrite H1 in H7. rewrite in_app_iff in H7.\n      intros. unfold root_eq. destruct x; auto. unfold DData_eqb. rm_if. exfalso.\n      apply H7. left. apply in_split in H. destruct H as [l3 [l4 ?]]. clear H7.\n      subst l1. rewrite map_app, map_cons.\n      rewrite in_app_iff. right. left. unfold treeName. auto.\n  Qed.\n\n  Lemma file_in_tree_with_id_eq: forall fmap dmap name tree path,\n      file_in_tree fmap dmap path name tree <->\n      exists fid, file_in_tree_with_id fmap dmap path name tree fid.\n  Proof.\n    intros fmap dmap name. induction tree using tree_ind2; intros.\n    1: split; intros; [|destruct H]; inversion H. rewrite Forall_forall in H.\n    destruct path.\n    - split; intro; [|destruct H0 as [fId ?]]; inversion H0; subst.\n      + rewrite Exists_exists in H4. destruct H4. destruct H1. inversion H2.\n        subst. exists fId. constructor; auto.\n      + constructor. rewrite Exists_exists. exists (Fnode fId).\n        split; auto. constructor; auto.\n    - split; intro; [|destruct H0 as [fId ?]]; inversion H0;\n        subst; [|rename H7 into H4]; destruct H4 as [did' [treeL' [? [? ?]]]].\n      + rewrite H in H3; auto. destruct H3 as [fId ?]. exists fId. constructor.\n        exists did', treeL'. intuition.\n      + constructor. exists did', treeL'. intuition. rewrite H; auto. exists fId; auto.\n  Qed.\n\n  Lemma file_in_tree_none : forall fs path fname,\n      NoDupNameTree (f_map fs) (d_map fs) (layout fs) ->\n      findMatchedFid fs path fname = None ->\n      ~ file_in_tree (f_map fs) (d_map fs) path fname (layout fs).\n  Proof.\n    intros fs. unfold findMatchedFid. remember (layout fs). clear Heqt. revert fs.\n    induction t using tree_ind2; repeat intro. 1: inversion H1. destruct path.\n    - inversion H2. subst fname0 root treeL0. rewrite Exists_exists in H6.\n      destruct H6 as [? [? ?]]. inversion H4. subst fname0 x.\n      pose proof (find_none _ _ H1 fId). simpl in H6. unfold fdata_eqb in H6.\n      rewrite H5 in H6.\n      assert (In fId (findFids (d_map fs) (Dnode did treeL) [])). {\n        unfold findFids. simpl. apply in_split in H3. destruct H3 as [l1 [l2 ?]].\n        rewrite H3. rewrite collectBareFids_app. simpl.\n        rewrite in_app_iff. right. left. auto.\n      } specialize (H6 H7). rm_hif; intuition.\n    - inversion H2. subst s dlist fname0 root treeL0.\n      destruct H6 as [did' [treeL' [? [? ?]]]]. rewrite Forall_forall in H.\n      specialize (H _ H3 fs path fname). apply H; auto.\n      + inversion H0. rewrite Forall_forall in H10. apply H10; auto.\n      + rewrite <- H1. f_equal. apply findFids_the_same with (fmap := f_map fs); auto.\n  Qed.\n\n  Lemma file_in_tree_with_id_none : forall fs path fname id,\n      NoDupNameTree (f_map fs) (d_map fs) (layout fs) ->\n      findMatchedFid fs path fname = None ->\n      ~ file_in_tree_with_id (f_map fs) (d_map fs) path fname (layout fs) id.\n  Proof.\n    intros. apply (file_in_tree_none fs path fname) in H0; auto.\n    intro; apply H0. rewrite file_in_tree_with_id_eq. exists id; auto.\n  Qed.\n\n  Lemma collectBareFids_In: forall id l, In id (collectBareFids l) -> In (Fnode id) l.\n  Proof.\n    intros. induction l; simpl in *; auto.\n    destruct a; [simpl in H; destruct H; [subst f; left | right; apply IHl] |\n                 right; apply IHl]; auto.\n  Qed.\n\n  Lemma file_in_tree_with_id_some : forall fs path fname id,\n      NoDupNameTree (f_map fs) (d_map fs) (layout fs) ->\n      findMatchedFid fs path fname = Some id ->\n      file_in_tree_with_id (f_map fs) (d_map fs) path fname (layout fs) id.\n  Proof.\n    intros fs. unfold findMatchedFid. remember (layout fs). clear Heqt.\n    revert fs. induction t using tree_ind2; intros.\n    - assert (findFids (d_map fs) (Fnode fid) path = []) by\n          (unfold findFids; destruct path; simpl; auto).\n      rewrite H1 in H0. simpl in H0. inversion H0.\n    - destruct path; pose proof H1; apply find_some in H1; destruct H1;\n        unfold fdata_eqb in H3; rm_hif; inversion H3; unfold findFids in H1;\n          simpl in H1; constructor; auto.\n      + apply collectBareFids_In; auto.\n      + destruct (find (fun x : Tree => root_eq (d_map fs) x s) treeL) eqn:? .\n        2: inversion H1. apply find_some in Heqo. destruct Heqo.\n        unfold root_eq in H5. destruct t.\n        1: inversion H5. unfold DData_eqb in H5. rm_hif. 2: inversion H5. clear H3 H5.\n        exists d, l. intuition. rewrite Forall_forall in H. apply H; auto.\n        * inversion H0. rewrite Forall_forall in H8. apply H8; auto.\n        * rewrite <- H2. f_equal.\n          apply findFids_the_same with (fmap := f_map fs); auto.\n  Qed.\n\n  Lemma file_in_tree_some : forall fs path fname id,\n      NoDupNameTree (f_map fs) (d_map fs) (layout fs) ->\n      findMatchedFid fs path fname = Some id ->\n      file_in_tree (f_map fs) (d_map fs) path fname (layout fs).\n  Proof.\n    intros. pose proof (file_in_tree_with_id_some fs _ _ _ H H0).\n    rewrite file_in_tree_with_id_eq. exists id; auto.\n  Qed.\n\n  Lemma fs_open_ok: forall path fname fs fId err postFS,\n      (fId, err, postFS) = (fs_open (path, fname) fs) ->\n      NoDup (map fst (openhandleFS fs)) ->\n      NoDupNameTree (fMapFS fs) (dMapFS fs) (layoutFS fs) ->\n      (~ file_in_tree (fMapFS fs) (dMapFS fs) path fname (layoutFS fs) /\\\n       fId = O /\\ err = eBadF /\\ fs = postFS) \\/\n      (file_in_tree (fMapFS fs) (dMapFS fs) path fname (layoutFS fs) /\\\n       In fId (map fst (openhandleFS fs)) /\\ err = eBadF /\\ fs = postFS) \\/\n      (file_in_tree (fMapFS fs) (dMapFS fs) path fname (layoutFS fs) /\\\n       ~ In fId (map fst (openhandleFS fs)) /\\ fst fs = fst postFS /\\ err <> eSucc /\\\n       (exists p errR,\n           hd_error (logFS postFS) = Some (Call_VOpen path p errR) /\\\n           err = errR /\\ logFS postFS = Call_VOpen path p errR :: logFS fs)) \\/\n      (file_in_tree (fMapFS fs) (dMapFS fs) path fname (layoutFS fs) /\\\n       ~ In fId (map fst (openhandleFS fs)) /\\ err = eSucc /\\\n       layoutFS fs = layoutFS postFS /\\ vmFS fs = vmFS postFS /\\\n       fMapFS fs = fMapFS postFS /\\ dMapFS fs = dMapFS postFS /\\\n       fnode_ctr (fsFS fs) = fnode_ctr (fsFS postFS) /\\\n       dnode_ctr (fsFS fs) = dnode_ctr (fsFS postFS) /\\\n       mmap_handles (fsFS fs) = mmap_handles (fsFS postFS) /\\\n       mmap_memory (fsFS fs) = mmap_memory (fsFS postFS) /\\\n       openhandleFS postFS = (fId, 0) :: openhandleFS fs /\\\n       NoDup (map fst (openhandleFS postFS)) /\\\n       (hd_error (logFS postFS) = Some (Call_VOpen path fname eSucc) /\\\n        logFS postFS = Call_VOpen path fname eSucc :: logFS fs)).\n  Proof.\n    intros. unfold fs_open in H. simpl in H.\n    destruct (findMatchedFid (fst fs) path fname) eqn: ?.\n    - right; rm_hmatch.\n      + left. inversion H. split; [|split; [|split]]; auto.\n        * eapply file_in_tree_some; eauto.\n        * eapply find_Fid_In; eauto.\n      + right. destruct fs. simpl in H.\n        assert (file_in_tree (fMapFS (f0, l)) (dMapFS (f0, l))\n                             path fname (layoutFS (f0, l))) by\n            (eapply file_in_tree_some; eauto).\n        assert (~ In fId (map fst (openhandleFS (f0, l)))). {\n          intro. destruct f0. unfold openhandleFS in *. simpl in *.\n          assert (f = fId) by (destruct (v_open path fname (Datatypes.length l)); inversion H; auto). subst f. eapply find_Fid_None; eauto.\n        } simpl. destruct (v_open path fname (Datatypes.length l)) eqn:? ;\n                   [right; split; [|split]; auto |\n                    left; split; [|split]; auto; inversion H; simpl;\n                    intuition; [inversion H4 | exists fname, err; subst err; auto]..].\n        simpl in H. inversion H. destruct f0.\n        unfold openhandleFS, layoutFS, vmFS, fMapFS, dMapFS, logFS, snd in *.\n        simpl in *. intuition. constructor; [subst f; intro; apply H3 |]; auto.\n    - left. inversion H. intuition. eapply file_in_tree_none; eauto.\n  Qed.\n\n  Lemma f_map_append_page_preserve: forall fmap fId page id,\n      id <> fId -> fmap id = f_map_append_page fmap fId page id.\n  Proof. intros. unfold f_map_append_page. rm_if. exfalso; auto. Qed.\n\n  Lemma write_to_virtual_memory_unfold:\n    forall (buf: string) (pos: nat) (fId: Fid) (fmap: Fid -> FData) (vm: list Page),\n      write_to_virtual_memory buf pos fId fmap vm =\n      if string_dec buf EmptyString\n      then inl (vm, fmap)\n      else let len := String.length buf in\n           let new_vm := vm in\n           let new_map := fmap in\n           let pg_offset := pos mod psize in\n           let pgn := if Nat.eq_dec pg_offset O then pos / psize + 1 else pos / psize in\n           let vpg := nth pgn (fmap fId).(pageIdsF) memory_upper_bound in\n           let vpg_ret := if Bool.bool_dec (andb (Nat.eqb vpg memory_upper_bound) (Nat.eqb pg_offset O)) true then (get_next_free_vpg new_map, true) else (vpg, false) in\n           let vpg := fst vpg_ret in\n           if Nat.eq_dec vpg memory_upper_bound\n           then inr eNoSpc\n           else if le_dec memory_upper_bound vpg\n                then inr eInval\n                else let new_map := if Sumbool.sumbool_of_bool (snd vpg_ret) then f_map_append_page new_map fId vpg else new_map in\n                     let curr_page_cont := nth vpg new_vm nil in\n                     let b1 := substring 0 (psize - pg_offset) buf in\n                     let buf := substring (psize - pg_offset) (len - (psize - pg_offset)) buf in\n                     let new_curr_pg_cont := override curr_page_cont pg_offset (string_to_byte_list b1) in\n                     let new_vm := upd_nth new_vm vpg new_curr_pg_cont in\n                     let pos := pos + psize - pg_offset in\n                     write_to_virtual_memory buf pos fId new_map new_vm.\n  Proof.\n    intros. unfold write_to_virtual_memory at 1. rewrite Fix_eq. 1: rm_if.\n    intros; assert (f = g) by (extensionality y; extensionality p; auto); subst; auto.\n  Qed.\n\n  Lemma write_to_virtual_memory_err: forall a b c d e f,\n      write_to_virtual_memory a b c d e = inr f -> f = eNoSpc \\/ f = eInval.\n  Proof.\n    intros a. remember (String.length a). assert (String.length a <= n) by omega.\n    clear Heqn. revert a H. induction n; intros.\n    - destruct a. rewrite write_to_virtual_memory_unfold in H0.\n      destruct (string_dec \"\" \"\"); [inversion H0 | exfalso; apply n; auto].\n      simpl in H. exfalso; omega.\n    - rewrite write_to_virtual_memory_unfold in H0. destruct (string_dec a \"\").\n      1: inversion H0. cbv zeta in H0. rm_hif. 1: inversion H0; left; auto.\n      rm_hif. 1: inversion H0; right; auto. apply IHn in H0; auto.\n      transitivity (String.length a - (psize - b mod psize)).\n      1: apply substring_length.\n      clear -H. cut (0 < psize - b mod psize). 1: intros; omega.\n      cut (b mod psize < psize). 1: intros; omega. apply Nat.mod_upper_bound.\n      compute; omega.\n  Qed.\n\n  Lemma write_to_virtual_memory_fmap:\n    forall (buf: string) (pos: nat) (fId: Fid) (fmap: Fid -> FData)\n           (vm: list Page) new_fmap new_vm,\n      write_to_virtual_memory buf pos fId fmap vm = inl (new_vm, new_fmap) ->\n      forall id, id <> fId -> fmap id = new_fmap id.\n  Proof.\n    intros buf. remember (String.length buf).\n    assert (String.length buf <= n) by omega; clear Heqn.\n    revert buf H. induction n; intros.\n    - destruct buf. 2: simpl in H; exfalso; omega.\n      rewrite write_to_virtual_memory_unfold in H0. rm_hif. inversion H0.\n      subst; auto. exfalso; apply n; auto.\n    - rewrite write_to_virtual_memory_unfold in H0. rm_hif.\n      1: inversion H0; subst; auto. cbv zeta in H0. rm_hif. 1: inversion H0. rm_hif.\n      1: inversion H0. apply IHn with (id := id) in H0; auto.\n      + rm_hif; auto. rewrite <- H0. clear -H1. apply f_map_append_page_preserve; auto.\n      + transitivity (String.length buf - (psize - pos mod psize)).\n        1: apply substring_length. clear -H. cut (0 < psize - pos mod psize).\n        1: intros; omega. cut (pos mod psize < psize). 1: intros; omega.\n        apply Nat.mod_upper_bound. compute; omega.\n  Qed.\n\n  Lemma fs_seek_ok: forall (fId: Fid) (pos: nat) (fs postFS: FSState) (err: ErrCode),\n      (err, postFS) = fs_seek (fId, pos) fs ->\n      (~ In fId (map fst (openhandleFS fs)) /\\ postFS = fs /\\ err = eBadF) \\/\n      (In fId (map fst (openhandleFS fs)) /\\ pos >= ((fMapFS fs) fId).(metaF).(size) /\\\n       (pos <> O \\/ ((fMapFS fs) fId).(metaF).(size) <> O) /\\\n       postFS = fs /\\ err = eInval) \\/\n      (In fId (map fst (openhandleFS fs)) /\\ err <> eSucc /\\ fsFS postFS = fsFS fs /\\\n       exists p1 p2 vlseek_ret,\n         err = vlseek_ret /\\\n         logFS postFS = Call_VLSeek p1 p2 vlseek_ret :: logFS fs) \\/\n      (In fId (map fst (openhandleFS fs)) /\\ err = eSucc /\\\n       layoutFS fs = layoutFS postFS /\\ vmFS fs = vmFS postFS /\\\n       fMapFS fs = fMapFS postFS /\\ dMapFS fs = dMapFS postFS /\\\n       fnode_ctr (fsFS fs) = fnode_ctr (fsFS postFS) /\\\n       dnode_ctr (fsFS fs) = dnode_ctr (fsFS postFS) /\\\n       mmap_handles (fsFS fs) = mmap_handles (fsFS postFS) /\\\n       mmap_memory (fsFS fs) = mmap_memory (fsFS postFS) /\\\n       map fst (openhandleFS postFS) = map fst (openhandleFS fs) /\\\n       (forall cursor, In (fId, cursor) (openhandleFS fs) ->\n                       In (fId, pos) (openhandleFS postFS)) /\\\n       exists p3 p4, logFS postFS = Call_VLSeek p3 p4 eSucc :: logFS fs).\n  Proof.\n    intros. unfold fs_seek in H. simpl in H. rm_hif_eqn H.\n    - right. rm_hif_eqn H.\n      + left. unfold fMapFS. split. 1: eapply find_Fid_In; eauto. inversion H.\n        apply andb_prop in Heqb. destruct Heqb. apply leb_complete in H0. split; auto.\n        apply Bool.orb_prop in H3. rewrite !Bool.negb_true_iff in H3.\n        destruct H3; apply beq_nat_false in H3; intuition.\n      + right. destruct fs. simpl in H. rm_hif.\n        * left. split. 1: eapply find_Fid_In; eauto. inversion H. intuition.\n          simpl. exists fId, (pos_to_vpage pos), err. subst err. intuition.\n        * right. split. 1: eapply find_Fid_In; eauto. inversion H.\n          unfold openhandleFS, layoutFS, vmFS, fMapFS, dMapFS, logFS, snd in *.\n          simpl in *. intuition.\n          -- apply replace_handler_preserve_fst.\n          -- apply replace_handler_replaces with cursor; auto.\n          -- exists fId, (pos_to_vpage pos). rewrite e. auto.\n    - left. inversion H. intuition. eapply find_Fid_None; eauto.\n  Qed.\n\n  Lemma change_f_map_size_preserve_name: forall fmap fId new_size id,\n      nameF (fmap id) = nameF (change_f_map_size fmap fId new_size id).\n  Proof. intros. unfold change_f_map_size. rm_if. subst. simpl; auto. Qed.\n\n  Lemma f_map_append_page_preserve_name: forall fmap fId page id,\n      nameF (fmap id) = nameF (f_map_append_page fmap fId page id).\n  Proof. intros. unfold f_map_append_page. rm_if. subst. simpl; auto. Qed.\n\n  Lemma write_to_virtual_memory_fmap_preserve_name:\n    forall (buf: string) (pos: nat) (fId: Fid) (fmap: Fid -> FData)\n           (vm: list Page) new_fmap new_vm id,\n      write_to_virtual_memory buf pos fId fmap vm = inl (new_vm, new_fmap) ->\n      nameF (fmap id) = nameF (new_fmap id).\n  Proof.\n    intros buf. remember (String.length buf).\n    assert (String.length buf <= n) by omega; clear Heqn.\n    revert buf H. induction n; intros.\n    - destruct buf. 2: simpl in H; exfalso; omega.\n      rewrite write_to_virtual_memory_unfold in H0. rm_hif.\n      inversion H0; auto. exfalso; apply n; auto.\n    - rewrite write_to_virtual_memory_unfold in H0. rm_hif.\n      1: inversion H0; subst; auto. cbv zeta in H0. rm_hif.\n      1: inversion H0. rm_hif. 1: inversion H0. apply IHn with (id := id) in H0; auto.\n      + rm_hif; auto. rewrite <- H0. rewrite <- f_map_append_page_preserve_name. auto.\n      + transitivity (String.length buf - (psize - pos mod psize)).\n        1: apply substring_length. clear -H. cut (0 < psize - pos mod psize).\n        1: intros; omega. cut (pos mod psize < psize). 1: intros; omega.\n        apply Nat.mod_upper_bound. compute; omega.\n  Qed.\n\n  Lemma change_f_map_size_preserve_permission: forall fmap fId new_size id,\n      permission (metaF (fmap id)) =\n      permission (metaF (change_f_map_size fmap fId new_size id)).\n  Proof. intros. unfold change_f_map_size. rm_if. subst. simpl; auto. Qed.\n\n  Lemma f_map_append_page_preserve_meta: forall fmap fId page id,\n      metaF (fmap id) = metaF (f_map_append_page fmap fId page id).\n  Proof. intros. unfold f_map_append_page. rm_if. subst. simpl; auto. Qed.\n\n  Lemma write_to_virtual_memory_fmap_preserve_meta:\n    forall (buf: string) (pos: nat) (fId: Fid) (fmap: Fid -> FData)\n           (vm: list Page) new_fmap new_vm id,\n      write_to_virtual_memory buf pos fId fmap vm = inl (new_vm, new_fmap) ->\n      metaF (fmap id) = metaF (new_fmap id).\n  Proof.\n    intros buf. remember (String.length buf).\n    assert (String.length buf <= n) by omega; clear Heqn.\n    revert buf H. induction n; intros.\n    - destruct buf. 2: simpl in H; exfalso; omega.\n      rewrite write_to_virtual_memory_unfold in H0. rm_hif.\n      inversion H0; auto. exfalso; apply n; auto.\n    - rewrite write_to_virtual_memory_unfold in H0. rm_hif.\n      1: inversion H0; subst; auto. cbv zeta in H0. rm_hif.\n      1: inversion H0. rm_hif. 1: inversion H0. apply IHn with (id := id) in H0; auto.\n      + rm_hif; auto. rewrite <- H0. rewrite <- f_map_append_page_preserve_meta. auto.\n      + transitivity (String.length buf - (psize - pos mod psize)).\n        1: apply substring_length. clear -H. cut (0 < psize - pos mod psize).\n        1: intros; omega. cut (pos mod psize < psize). 1: intros; omega.\n        apply Nat.mod_upper_bound. compute; omega.\n  Qed.\n\n  Lemma preserve_fname_NoDupNameTree:\n    forall fmap1 fmap2 dmap tree,\n      (forall fId, nameF (fmap1 fId) = nameF (fmap2 fId)) ->\n      NoDupNameTree fmap1 dmap tree -> NoDupNameTree fmap2 dmap tree.\n  Proof.\n    intros. induction tree using tree_ind2; constructor; inversion H0; subst.\n    - rewrite Forall_forall in *; intros. apply H1; auto.\n    - cut (map (treeName fmap1 dmap) treeL = map (treeName fmap2 dmap) treeL).\n      1: intros S; rewrite <- S; auto.\n      apply map_ext_in. intros. destruct a; simpl; [rewrite H|]; auto.\n  Qed.\n\n  Lemma preserve_dname_NoDupNameTree:\n    forall fmap dmap1 dmap2 tree,\n      (forall dId, nameD (dmap1 dId) = nameD (dmap2 dId)) ->\n      NoDupNameTree fmap dmap1 tree -> NoDupNameTree fmap dmap2 tree.\n  Proof.\n    intros. induction tree using tree_ind2; constructor; inversion H0; subst.\n    - rewrite Forall_forall in *; intros. apply H1; auto.\n    - cut (map (treeName fmap dmap1) treeL = map (treeName fmap dmap2) treeL).\n      1: intros S; rewrite <- S; auto.\n      apply map_ext_in. intros. destruct a; simpl; [|rewrite H]; auto.\n  Qed.\n\n  Lemma change_f_map_size_preserve_pgid: forall fmap fId new_size id,\n      pageIdsF (change_f_map_size fmap fId new_size id) = pageIdsF (fmap id).\n  Proof. intros. unfold change_f_map_size. rm_if. subst. simpl; auto. Qed.\n\n  Lemma write_to_virtual_memory_pageIds:\n    forall (buf: string) (pos: nat) (fId: Fid)\n           (fmap: Fid -> FData) (vm: list Page) new_fmap new_vm,\n      write_to_virtual_memory buf pos fId fmap vm = inl (new_vm, new_fmap) ->\n      forall pgId, In pgId (pageIdsF (new_fmap fId)) ->\n                   In pgId (pageIdsF (fmap fId)) \\/\n                   (pgId < memory_upper_bound /\\\n                    forall fId2, fId <> fId2 -> ~ In pgId (pageIdsF (new_fmap fId2))).\n  Proof.\n    intros buf. remember (String.length buf).\n    assert (String.length buf <= n) by omega; clear Heqn.\n    revert buf H. induction n; intros.\n    - destruct buf. 2: simpl in H; exfalso; omega.\n      rewrite write_to_virtual_memory_unfold in H0. rm_hif.\n      2: exfalso; auto. inversion H0; subst. left; auto.\n    - rewrite write_to_virtual_memory_unfold in H0. rm_hif.\n      1: inversion H0; subst; left; auto. cbv zeta in H0.\n      remember (if Nat.eq_dec (pos mod psize) 0 then pos / psize + 1 else pos / psize)\n        as pgn. remember (nth pgn (pageIdsF (fmap fId)) memory_upper_bound) as vpg.\n      remember (if Bool.bool_dec\n                     ((Nat.eqb vpg memory_upper_bound) && (Nat.eqb (pos mod psize) O)) true then\n                  (get_next_free_vpg fmap, true) else (vpg, false)) as vpg_ret.\n      do 2 (rm_hif; [inversion H0|]).\n      pose proof (write_to_virtual_memory_fmap _ _ _ _ _ _ _ H0).\n      apply IHn with (pgId := pgId) in H0; auto.\n      + destruct H0. 2: right; auto. rm_hif. 2: left; auto. rm_hif; subst vpg_ret.\n        2: simpl in e; inversion e. simpl in H0. unfold f_map_append_page in H0.\n        rm_hif. 2: exfalso; apply n3; auto. simpl in H0. rewrite in_app_iff in H0.\n        destruct H0. 1: left; auto. simpl in H0. destruct H0.\n        2: exfalso; auto. simpl in H2. right.\n        pose proof (get_next_free_vpg_axiom fmap). subst pgId. split.\n        * destruct (H3 fId); simpl in n1; omega.\n        * intros. simpl in n0. rewrite <- H2; auto. unfold f_map_append_page. rm_if.\n          destruct (H3 fId2). auto.\n      + transitivity (String.length buf - (psize - pos mod psize)).\n        1: apply substring_length. clear -H. cut (0 < psize - pos mod psize).\n        1: intros; omega. cut (pos mod psize < psize). 1: intros; omega.\n        apply Nat.mod_upper_bound. compute; omega.\n  Qed.\n\n  Lemma fs_write_ok: forall (fId : Fid) (buf : string) (pos: nat)\n                            (fs : FSState) (err : ErrCode) (postFS : FSState),\n      (err, postFS) = fs_write (fId, buf, pos) fs -> good_file_system (fsFS fs) ->\n      (~ In fId (map fst (openhandleFS fs)) /\\ postFS = fs /\\ err = eBadF) \\/\n      (In fId (map fst (openhandleFS fs)) /\\ postFS = fs /\\ (err = eNoSpc \\/\n                                                             err = eInval)) \\/\n      (In fId (map fst (openhandleFS fs)) /\\ err <> eSucc /\\ fsFS postFS = fsFS fs /\\\n       exists p1 p2 vlseek_ret,\n         hd_error (logFS postFS) = Some (Call_VLSeek p1 p2 vlseek_ret) /\\\n         err = vlseek_ret /\\\n         logFS postFS = Call_VLSeek p1 p2 vlseek_ret :: logFS fs) \\/\n      (In fId (map fst (openhandleFS fs)) /\\ fsFS postFS = fsFS fs /\\\n       exists vwrite_ret p1 p2 p3,\n         err = vwrite_ret /\\ hd_error (logFS postFS) =\n                             Some (Call_VWrite p1 p2 p3 vwrite_ret) /\\\n         vwrite_ret <> eSucc /\\\n         exists p4 p5,\n           logFS postFS = Call_VWrite p1 p2 p3 vwrite_ret ::\n                                      Call_VLSeek p4 p5 eSucc :: logFS fs) \\/\n      (In fId (map fst (openhandleFS fs)) /\\ layoutFS fs = layoutFS postFS /\\\n       dMapFS fs = dMapFS postFS /\\\n       mmap_handles (fsFS fs) = mmap_handles (fsFS postFS) /\\\n       mmap_memory (fsFS fs) = mmap_memory (fsFS postFS) /\\\n       map fst (openhandleFS postFS) = map fst (openhandleFS fs) /\\\n       In (fId, pos + (String.length buf)) (openhandleFS postFS) /\\\n       (forall id, id <> fId -> (fMapFS fs) id = (fMapFS postFS) id) /\\\n       (((fMapFS fs) fId).(nameF) = ((fMapFS postFS) fId).(nameF)) /\\\n       (((fMapFS fs) fId).(metaF).(permission) =\n        ((fMapFS postFS) fId).(metaF).(permission)) /\\\n       size_changed fId fs postFS pos (String.length buf) /\\\n       (exists p1 p2 p3,\n           err = eSucc /\\\n           hd_error (logFS postFS) = Some (Call_VWrite p1 p2 p3 eSucc) /\\\n           exists p4 p5,\n             logFS postFS = Call_VWrite p1 p2 p3 eSucc ::\n                                        Call_VLSeek p4 p5 eSucc :: logFS fs) /\\\n       good_file_system (fsFS postFS)).\n  Proof.\n    intros. unfold fs_write in H. simpl in H. rm_hif_eqn H.\n    - right. rm_hif_eqn H.\n      1: left; split; [eapply find_Fid_In; eauto | inversion H; intuition]. simpl in H.\n      rm_hmatch.\n      + right. destruct p0 as [new_vm new_f_map]. destruct fs. simpl in H. rm_hif.\n        * left. split. 1: eapply find_Fid_In; eauto. inversion H. simpl. intuition.\n          exists fId, (pos_to_vpage pos),\n          (v_lseek fId (pos_to_vpage pos) (Datatypes.length l)). intuition.\n        * right. remember (get_encrypted_buf (get_write_pages fId new_f_map new_vm pos (String.length buf)) new_vm) as encrypted_buf. simpl in H. rm_hif.\n          -- left. split. 1: eapply find_Fid_In; eauto. inversion H. simpl. intuition.\n             exists err, fId, encrypted_buf, (pos_to_vlen pos (String.length buf)).\n             rewrite H2. intuition. exists fId, (pos_to_vpage pos).\n             rewrite e; intuition.\n          -- simpl in H. right. split. 1: eapply find_Fid_In; eauto.\n             simpl in H. inversion H.\n             unfold openhandleFS, layoutFS, vmFS, fMapFS, dMapFS, logFS, snd in *.\n             simpl in *. intuition.\n             ++ apply replace_handler_preserve_fst.\n             ++ apply find_some in Heqo. destruct Heqo. rewrite Nat.eqb_eq in H4.\n                destruct p. simpl in H4. subst n.\n                eapply replace_handler_replaces; eauto.\n             ++ unfold change_f_map_size. destruct (Nat.eq_dec id fId).\n                1: exfalso; auto. unfold change_f_map_pages.\n                destruct (Nat.eq_dec id fId); [exfalso |]; auto.\n                eapply write_to_virtual_memory_fmap; eauto.\n             ++ rewrite <- change_f_map_size_preserve_name.\n                eapply write_to_virtual_memory_fmap_preserve_name. eauto.\n             ++ rewrite <- change_f_map_size_preserve_permission.\n                erewrite write_to_virtual_memory_fmap_preserve_meta; eauto.\n             ++ unfold size_changed. unfold fMapFS. simpl.\n                unfold change_f_map_size. rm_if. 2: exfalso; apply n; auto. simpl.\n                erewrite <- write_to_virtual_memory_fmap_preserve_meta; eauto.\n             ++ clear H H3. rewrite e0.\n                exists fId, encrypted_buf, (pos_to_vlen pos (String.length buf)).\n                intuition. rewrite e. exists fId, (pos_to_vpage pos). auto.\n             ++ clear H H3. destruct H0 as [? [? [? [? [? [? [? [? ?]]]]]]]].\n                pose proof (write_to_virtual_memory_pageIds _ _ _ _ _ _ _ Heqs).\n                pose proof (write_to_virtual_memory_fmap _ _ _ _ _ _ _ Heqs).\n                split; [|split; [|split; [|split; [|split; [|split; [|split; [|split]]]]]]]; intuition; simpl.\n                ** apply preserve_fname_NoDupNameTree with new_f_map.\n                   1: intros; apply change_f_map_size_preserve_name.\n                   apply preserve_fname_NoDupNameTree with (f_map f).\n                   1: intros; eapply write_to_virtual_memory_fmap_preserve_name; eauto.\n                   auto.\n                ** rewrite replace_handler_preserve_fst. auto.\n                ** simpl in *. rewrite change_f_map_size_preserve_pgid in *.\n                   subst pgId2. destruct (Nat.eq_dec fId1 fId); [subst fId1|];\n                                  destruct (Nat.eq_dec fId2 fId); [exfalso; auto|..].\n                   --- rewrite <- H10 in H16; auto. specialize (H9 _ H15).\n                       destruct H9 as [? | [? ?]]. 1: eapply H7; eauto.\n                       eapply H17; eauto. rewrite <- H10; auto.\n                   --- subst fId. rewrite <- H10 in H15; auto. specialize (H9 _ H16).\n                       destruct H9 as [? | [? ?]]. 1: eapply H7; eauto.\n                       eapply H17; eauto. rewrite <- H10; auto.\n                   --- rewrite <- H10 in H16, H15; auto.\n                       specialize (H7 fId1 fId2 pgId1 pgId1). apply H7; auto.\n                ** simpl in *. rewrite change_f_map_size_preserve_pgid in *.\n                   destruct (Nat.eq_dec fId0 fId).\n                   2: rewrite <- H10 in H13; auto; eapply H11; eauto. subst fId0.\n                   specialize (H9 _ H13). destruct H9 as [? | [? ?]]; auto.\n                   eapply H11; eauto.\n      + inversion H. left. split; [eapply find_Fid_In; eauto | split]; auto.\n        eapply write_to_virtual_memory_err; eauto.\n    - left. inversion H. intuition. eapply find_Fid_None; eauto.\n  Qed.\n\n  Inductive path_in_tree (dmap: Did -> DData) : Path -> Tree -> Prop :=\n  | Empty_path_in: forall root treeL, path_in_tree dmap [] (Dnode root treeL)\n  | Cons_path_in: forall root dname dlist treeL,\n      (exists did treeL', In (Dnode did treeL') treeL /\\\n                          (dmap did).(nameD) = dname /\\\n                          path_in_tree dmap dlist (Dnode did treeL')) ->\n      path_in_tree dmap (dname :: dlist) (Dnode root treeL).\n\n  Inductive path_in_tree_with_id (dmap: Did -> DData) : Path -> Tree -> Did -> Prop :=\n  | Empty_piwi: forall root treeL, path_in_tree_with_id dmap [] (Dnode root treeL) root\n  | Cons_piwi: forall root dname dlist treeL d,\n      (exists did treeL', In (Dnode did treeL') treeL /\\\n                          (dmap did).(nameD) = dname /\\\n                          path_in_tree_with_id dmap dlist (Dnode did treeL') d) ->\n      path_in_tree_with_id dmap (dname :: dlist) (Dnode root treeL) d.\n\n  Lemma path_in_tree_with_id_some : forall dmap d l tree path,\n      findDir dmap tree path = Some (Dnode d l) ->\n      path_in_tree_with_id dmap path tree d.\n  Proof.\n    intros dmap d l. induction tree using tree_ind2; intros.\n    1: destruct path; simpl in H; inversion H. destruct path.\n    1: simpl in H0; inversion H0; constructor. constructor.\n    simpl in H0. destruct (find (fun x : Tree => root_eq dmap x s) treeL) eqn: ?.\n    2: inversion H0. apply find_some in Heqo. destruct Heqo. unfold root_eq in H2.\n    destruct t. 1: inversion H2. exists d0, l0. unfold DData_eqb in H2. rm_hif.\n    2: inversion H2. clear H2. split; [|split]; auto. rewrite Forall_forall in H.\n    specialize (H _ H1 path). apply H; auto.\n  Qed.\n\n  Lemma findDir_not_fnode: forall dmap tree p i, findDir dmap tree p <> Some (Fnode i).\n  Proof.\n    intros dmap tree. induction tree using tree_ind2; repeat intro.\n    1: destruct p; simpl in H; inversion H. destruct p; simpl in H0. 1: inversion H0.\n    destruct (find (fun x : Tree => root_eq dmap x s) treeL) eqn: ?. 2: inversion H0.\n    apply find_some in Heqo. destruct Heqo. rewrite Forall_forall in H.\n    specialize (H _ H1). apply H in H0. auto.\n  Qed.\n\n  Lemma path_in_tree_with_id_eq: forall dmap path tree,\n      path_in_tree dmap path tree <->\n      exists id, path_in_tree_with_id dmap path tree id.\n  Proof.\n    intros. revert path. induction tree using tree_ind2; intros.\n    1: split; intro; [|destruct H]; inversion H.\n    destruct path. 1: split; intro; [exists did |]; constructor.\n    rewrite Forall_forall in H.\n    split; intro; [|destruct H0 as [id ?]]; inversion H0; subst; [|rename H6 into H2];\n      destruct H2 as [did' [treeL' [? [? ?]]]];\n      [rewrite H in H3; auto; destruct H3 as [id ?]; exists id|];\n      constructor; exists did', treeL'; intuition. rewrite H; auto. exists id; auto.\n  Qed.\n\n  Lemma path_in_tree_some : forall dmap tree path t,\n      findDir dmap tree path = Some t -> path_in_tree dmap path tree.\n  Proof.\n    intros. destruct t. 1: exfalso; eapply findDir_not_fnode; eauto.\n    apply path_in_tree_with_id_some in H. rewrite path_in_tree_with_id_eq.\n    exists d; auto.\n  Qed.\n\n  Lemma path_in_tree_none : forall fs path,\n      NoDupNameTree (fMapFS fs) (dMapFS fs) (layoutFS fs) ->\n      findDir (dMapFS fs) (layoutFS fs) path = None ->\n      ~ path_in_tree (dMapFS fs) path (layoutFS fs).\n  Proof.\n    intros fs. destruct fs. unfold fMapFS, dMapFS, layoutFS. simpl. clear l.\n    remember (layout f). clear Heqt. revert f.\n    induction t using tree_ind2; intros. 1: intro; inversion H1.\n    destruct path; simpl in H1. 1: inversion H1.\n    rm_hmatch; intro; inversion H2; subst; destruct H4 as [did' [treeL' [? [? ?]]]].\n    - apply in_split in H3. destruct H3 as [l1 [l2 ?]]. subst treeL.\n      rewrite find_app_not_in in Heqo.\n      + simpl in Heqo. unfold DData_eqb in Heqo.\n        destruct (string_dec (nameD (d_map f did')) s); auto.\n        inversion Heqo. subst. rewrite Forall_forall in H.\n        assert (In (Dnode did' treeL') (l1 ++ Dnode did' treeL' :: l2)) by\n            (rewrite in_app_iff; right; simpl; left; auto).\n        specialize (H _ H3). revert H5. apply H; auto.\n        inversion H0. rewrite Forall_forall in H9. apply H9; auto.\n      + intros. unfold root_eq. destruct x; auto. unfold DData_eqb. rm_if; auto.\n        inversion H0. rewrite map_app in H11. rewrite map_cons in H11.\n        unfold treeName in H11 at 2. apply NoDup_remove_2 in H11. exfalso. apply H11.\n        rewrite in_app_iff. left. apply in_split in H3. destruct H3 as [l3 [l4 ?]].\n        subst l1. rewrite map_app, map_cons.\n        rewrite in_app_iff. right. simpl. left. rewrite H4; auto.\n    - apply find_none with (x := Dnode did' treeL') in Heqo; auto.\n      unfold root_eq, DData_eqb in Heqo. rm_hif. 1: inversion Heqo. auto.\n  Qed.\n\n  Lemma path_in_tree_with_id_none: forall fs path id,\n      NoDupNameTree (fMapFS fs) (dMapFS fs) (layoutFS fs) ->\n      findDir (dMapFS fs) (layoutFS fs) path = None ->\n      ~ path_in_tree_with_id (dMapFS fs) path (layoutFS fs) id.\n  Proof.\n    intros. intro.\n    assert (exists d, path_in_tree_with_id (dMapFS fs) path (layoutFS fs) d) by\n        (exists id; auto). rewrite <- path_in_tree_with_id_eq in H2.\n    revert H2. apply path_in_tree_none; auto.\n  Qed.\n\n  Lemma NoDup_app_r: forall {A : Type} (l1 l2 : list A), NoDup (l1 ++ l2) -> NoDup l2.\n  Proof.\n    induction l1; simpl; intros; auto. apply NoDup_cons_iff in H.\n    apply IHl1. intuition.\n  Qed.\n\n  Lemma NoDup_app_l: forall {A : Type} (l1 l2 : list A), NoDup (l1 ++ l2) -> NoDup l1.\n  Proof.\n    intros A l1 l2. revert l1. induction l2; intros. rewrite app_nil_r in H. apply H.\n    apply NoDup_remove_1 in H. apply IHl2. apply H.\n  Qed.\n\n  Lemma NoDup_app_not_in_r: forall {A : Type} (l1 l2 : list A),\n      NoDup (l1 ++ l2) -> forall y, In y l1 -> ~ In y l2.\n  Proof.\n    induction l1; intros. 1: inversion H0. rewrite <- app_comm_cons in H.\n    apply in_inv in H0. destruct H0.\n    - subst. rewrite NoDup_cons_iff in H. destruct H. intro. apply H.\n      apply in_or_app. right. apply H1.\n    - rewrite NoDup_cons_iff in H. destruct H. apply IHl1; auto.\n  Qed.\n\n  Lemma NoDup_app_not_in_l: forall {A : Type} (l2 l1 : list A),\n      NoDup (l1 ++ l2) -> forall y, In y l2 -> ~ In y l1.\n  Proof.\n    induction l2; intros. 1: inversion H0. apply in_inv in H0. destruct H0.\n    - subst. apply NoDup_remove_2 in H. intro; apply H. apply in_or_app. left; auto.\n    - apply NoDup_remove_1 in H. apply IHl2; auto.\n  Qed.\n\n  Lemma subtree_nodup: forall t d l,\n      In t l -> NoDup (collectDids (Dnode d l)) -> NoDup (collectDids t).\n  Proof.\n    intros. induction l. 1: inversion H. simpl in H. simpl in H0. destruct H.\n    - subst a. rewrite NoDup_cons_iff in H0. destruct H0.\n      apply NoDup_app_l in H0. auto.\n    - apply IHl; auto. simpl. rewrite NoDup_cons_iff in H0. destruct H0. constructor.\n      + intro; apply H0. rewrite in_app_iff. right; auto.\n      + apply NoDup_app_r in H1. auto.\n  Qed.\n\n  Lemma subtree_did_in_merge: forall t l d,\n      In d (collectDids t) -> In t l -> In d (flat_map collectDids l).\n  Proof. intros. rewrite in_flat_map. exists t. intuition. Qed.\n\n  Lemma path_in_tree_collectDids: forall dmap path t d,\n      path_in_tree_with_id dmap path t d -> In d (collectDids t).\n  Proof.\n    intros. revert t path H. induction t using tree_ind2; intros.\n    1: inversion H. destruct path; inversion H0; subst. 1: simpl; left; auto.\n    destruct H6 as [did' [treeL' [? [? ?]]]]. simpl. right.\n    rewrite Forall_forall in H. specialize (H _ H1 _ H3).\n    eapply subtree_did_in_merge; eauto.\n  Qed.\n\n  Lemma flat_map_collectDids: forall l1 l2 t,\n      flat_map collectDids (l1 ++ t :: l2) =\n      (flat_map collectDids l1 ++ collectDids t ++ flat_map collectDids l2)%list.\n  Proof.\n    intros. rewrite flat_map_concat_map, map_app, map_cons,\n            concat_app, concat_cons, <- !flat_map_concat_map; auto.\n  Qed.\n\n  Lemma path_in_tree_nonempty_neq: forall dmap path did treeL d,\n      path <> nil -> NoDup (collectDids (Dnode did treeL)) ->\n      path_in_tree_with_id dmap path (Dnode did treeL) d -> d <> did.\n  Proof.\n    intros. destruct path. 1: exfalso; auto. inversion H1. subst.\n    destruct H7 as [did' [treeL' [? [? ?]]]]. apply path_in_tree_collectDids in H4.\n    apply in_split in H2. destruct H2 as [l1 [l2 ?]]. simpl in H0. subst treeL.\n    rewrite flat_map_collectDids in H0. rewrite NoDup_cons_iff in H0.\n    destruct H0. intro. subst did. apply H0. rewrite !in_app_iff. right; left; auto.\n  Qed.\n\n  Lemma addDidToTree_in_tree: forall dmap d cnt dname p tree path,\n      ~ In cnt (collectDids tree) -> NoDup (collectDids tree) ->\n      path_in_tree_with_id dmap path tree d ->\n      path_in_tree_with_id (change_d_map dmap cnt (Build_DData dname p))\n                           (path ++ [dname])%list (addDidToTree tree d cnt) cnt.\n  Proof.\n    intros. revert path H H0 H1. induction tree using tree_ind2; intros.\n    1: inversion H1. destruct path; inversion H2; subst.\n    - simpl. rm_if. 2: exfalso; auto. constructor. exists cnt, nil.\n      split; [|split]; [simpl; left | unfold change_d_map; rm_if; exfalso |\n                        constructor]; auto.\n    - destruct H8 as [did' [treeL' [? [? ?]]]]. simpl. rm_if.\n      + exfalso. revert e. eapply (path_in_tree_nonempty_neq dmap (s :: path)); eauto.\n        intro. inversion H6.\n      + constructor. rewrite Forall_forall in H. specialize (H _ H3).\n        assert (~ In cnt (collectDids (Dnode did' treeL'))) by\n            (intro; apply H0; simpl; right;\n             apply subtree_did_in_merge with (t := Dnode did' treeL'); auto).\n        assert (NoDup (collectDids (Dnode did' treeL'))) by\n            (apply subtree_nodup with (t := Dnode did' treeL') in H1; auto).\n        specialize (H _ H6 H7 H5).\n        simpl in H. pose proof H3.\n        apply (in_map (fun t : Tree => addDidToTree t d cnt)) in H3.\n        simpl in H3. destruct (Nat.eq_dec d did').\n        * subst d. exists did', (Dnode cnt [] :: treeL').\n          split; [|split; [unfold change_d_map|]]; auto.\n          rm_if. simpl in H0. subst. exfalso. apply H0. right.\n          apply subtree_did_in_merge with (t := Dnode cnt treeL'); auto.\n          apply path_in_tree_collectDids in H5; auto.\n        * exists did', (map (fun t : Tree => addDidToTree t d cnt) treeL').\n          split; [|split; [unfold change_d_map|]]; auto.\n          rm_if. simpl in H0. subst. exfalso. apply H0. right.\n          apply subtree_did_in_merge with (t := Dnode cnt treeL'); auto.\n          simpl. left; auto.\n  Qed.\n\n  Lemma treeName_eq_treeL: forall fmap dmap cnt d treeL,\n      ~ In cnt (flat_map collectDids treeL) ->\n      map (treeName fmap dmap) treeL =\n      map (treeName fmap (change_d_map dmap cnt d)) treeL.\n  Proof.\n    intros. apply map_ext_in. intros. unfold change_d_map.\n    destruct a; simpl; auto. rm_if. subst.\n    exfalso. apply H. apply (subtree_did_in_merge (Dnode cnt l)); simpl; intuition.\n  Qed.\n\n  Lemma change_d_map_NoDupNameTree: forall fmap dmap cnt d t,\n      ~ In cnt (collectDids t) -> NoDupNameTree fmap dmap t ->\n      NoDupNameTree fmap (change_d_map dmap cnt d) t.\n  Proof.\n    intros fmap dmap cnt d. induction t using tree_ind2; intros; constructor.\n    - rewrite Forall_forall in *. intros. apply H; auto.\n      + intro. apply H0. simpl. right. apply subtree_did_in_merge with (t := x); auto.\n      + inversion H1. subst. rewrite Forall_forall in H7. apply H7; auto.\n    - inversion H1. subst.\n      assert (map (treeName fmap dmap) treeL =\n              map (treeName fmap (change_d_map dmap cnt d)) treeL). {\n        apply map_ext_in. intros. unfold change_d_map.\n        destruct a; simpl; auto. rm_if. exfalso. apply H0.\n        simpl. right. rewrite in_flat_map. subst d0.\n        exists (Dnode cnt l). split; simpl; intuition.\n      } rewrite <- H2. auto.\n  Qed.\n\n  Lemma addDidToTree_the_same: forall d cnt tree,\n      ~ In d (collectDids tree) -> addDidToTree tree d cnt = tree.\n  Proof.\n    intros. induction tree using tree_ind2; simpl; auto. rm_if.\n    1: subst; exfalso; apply H; simpl; left; auto.\n    rewrite Forall_forall in H0. f_equal. simpl in H.\n    assert (treeL = map id treeL) by\n        (clear; induction treeL; simpl; [|rewrite IHtreeL at 1]; auto).\n    rewrite H1 at 2. clear H1. apply map_ext_in. intros. unfold id. apply H0; auto.\n    intro. apply H. right. apply (subtree_did_in_merge a); auto.\n  Qed.\n\n  Lemma addDidToTree_the_same_list: forall d cnt l,\n      ~ In d (flat_map collectDids l) -> map (fun t => addDidToTree t d cnt) l = l.\n  Proof.\n    intros. assert (l = map id l) by\n        (clear; induction l; simpl; [|rewrite IHl at 1]; auto).\n    rewrite H0 at 2; clear H0. apply map_ext_in. unfold id. intros.\n    apply addDidToTree_the_same. intro; apply H. apply (subtree_did_in_merge a); auto.\n  Qed.\n\n  Lemma addDidToTree_map_the_same: forall l1 l2 did' treeL' d cnt,\n      NoDup (flat_map collectDids (l1 ++ Dnode did' treeL' :: l2)) ->\n      In d (collectDids (Dnode did' treeL')) ->\n      map (fun t : Tree => addDidToTree t d cnt) (l1 ++ Dnode did' treeL' :: l2) =\n      (l1 ++ (addDidToTree (Dnode did' treeL') d cnt) :: l2)%list.\n  Proof.\n    intros; rewrite map_app, map_cons. rewrite flat_map_collectDids in H.\n    f_equal; [|f_equal]; apply addDidToTree_the_same_list.\n    - apply NoDup_app_not_in_l with (y := d) in H; auto. apply in_or_app. left; auto.\n    - apply NoDup_app_r in H. apply NoDup_app_not_in_r with (y := d) in H; auto.\n  Qed.\n\n  Lemma addDidToTree_NoDupNameTree: forall fmap dmap dname cnt d p tree path,\n      ~ file_in_tree fmap dmap path dname tree ->\n      ~ path_in_tree dmap (path ++ [dname])%list tree ->\n      path_in_tree_with_id dmap path tree d -> ~ In cnt (collectDids tree) ->\n      NoDupNameTree fmap dmap tree -> NoDup (collectDids tree) ->\n      NoDupNameTree fmap (change_d_map dmap cnt {| nameD := dname; metaD := p |})\n                    (addDidToTree tree d cnt).\n  Proof.\n    intros fmap dmap dname cnt d p. induction tree using tree_ind2; intros.\n    1: inversion H1. destruct path; inversion H2; subst.\n    - simpl in *. rm_if. 2: exfalso; auto. clear e H. constructor.\n      + rewrite Forall_forall. intros. simpl in H. destruct H.\n        * subst x. constructor. 1: apply Forall_nil. simpl. constructor.\n        * inversion H4. subst. rewrite Forall_forall in H10. specialize (H10 _ H).\n          apply change_d_map_NoDupNameTree; auto. intro. apply H3. right.\n          apply (subtree_did_in_merge x); auto.\n      + simpl. unfold change_d_map at 1. rm_if. 2: exfalso; auto. simpl. clear e.\n        rewrite <- treeName_eq_treeL. 2: intro; apply H3; right; auto. constructor.\n        2: inversion H4; auto. intro. rewrite in_map_iff in H.\n        destruct H as [x [? ?]]. destruct x.\n        * apply H0. constructor. rewrite Exists_exists. exists (Fnode f).\n          split; auto. constructor. simpl in H. auto.\n        * apply H1. constructor. exists d0, l. simpl in H. intuition. constructor.\n    - destruct H11 as [did' [treeL' [? [? ?]]]]. simpl. rm_if.\n      + exfalso. revert e. eapply path_in_tree_nonempty_neq; eauto.\n        intro. inversion H9.\n      + assert (NoDupNameTree fmap\n                              (change_d_map dmap cnt {| nameD := dname; metaD := p |})\n                              (addDidToTree (Dnode did' treeL') d cnt)). {\n          rewrite Forall_forall in H. apply H with (path := path); try intro; auto.\n          - apply H0; constructor; exists did', treeL'; intuition.\n          - apply H1; simpl; constructor; exists did', treeL'; intuition.\n          - apply H3; simpl; right.\n            apply (subtree_did_in_merge (Dnode did' treeL')); auto.\n          - inversion H4. subst. rewrite Forall_forall in H13. apply H13. auto.\n          - apply (subtree_nodup _ _ _ H6 H5).\n        } clear H. apply in_split in H6. destruct H6 as [l1 [l2 ?]]. subst treeL.\n        apply path_in_tree_collectDids in H8.\n        rewrite addDidToTree_map_the_same; auto.\n        2: simpl in H5; rewrite NoDup_cons_iff in H5; destruct H5; auto.\n        inversion H4. subst. constructor.\n        * rewrite Forall_forall in *. intros. simpl in H3.\n          rewrite flat_map_collectDids in H3. rewrite in_app_iff in H.\n          destruct H; [|apply in_inv in H; destruct H];\n            [apply change_d_map_NoDupNameTree | subst x |\n             apply change_d_map_NoDupNameTree ]; auto.\n          -- intro. apply H3. right. rewrite in_app_iff.\n             left. apply (subtree_did_in_merge x); auto.\n          -- apply H12. rewrite in_app_iff. left; auto.\n          -- intro. apply H3. right. do 2 (rewrite in_app_iff; right).\n             apply (subtree_did_in_merge x); auto.\n          -- apply H12. rewrite in_app_iff. right. simpl. right; auto.\n        * rewrite map_app, map_cons in *. simpl in H13. simpl in H3.\n          rewrite flat_map_collectDids in H3.\n          assert (treeName fmap\n                           (change_d_map dmap cnt {| nameD := dname; metaD := p |})\n                           (addDidToTree (Dnode did' treeL') d cnt) =\n                  nameD (dmap did')). {\n            simpl. rm_if; [subst d|]; simpl; unfold change_d_map; rm_if;\n                     exfalso; apply H3; subst; right; rewrite !in_app_iff;\n                       right; left; simpl; left; auto.\n          } rewrite H; clear H.\n          rewrite <- !treeName_eq_treeL; auto; intro;\n            apply H3; right; rewrite !in_app_iff; [right; right | left]; auto.\n  Qed.\n\n  Lemma addDidToTree_Permutation: forall dmap cnt d tree path,\n      NoDup (collectDids tree) -> path_in_tree_with_id dmap path tree d ->\n      ~ In cnt (collectDids tree) ->\n      Permutation (cnt :: collectDids tree) (collectDids (addDidToTree tree d cnt)).\n  Proof.\n    intros dmap cnt d. induction tree using tree_ind2; intros; simpl. 1: inversion H0.\n    rewrite Forall_forall in H. rm_if. 1: subst; simpl in *; constructor.\n    simpl. destruct path; inversion H1; subst. 1: exfalso; apply n; auto.\n    destruct H8 as [did' [treeL' [? [? ?]]]]. pose proof H5. rename H6 into HS.\n    apply Permutation_trans with (did :: cnt :: flat_map collectDids treeL);\n      constructor. apply in_split in H3. destruct H3 as [l1 [l2 ?]]. subst treeL.\n    apply path_in_tree_collectDids in H5. simpl in H0. rewrite NoDup_cons_iff in H0.\n    destruct H0. rewrite addDidToTree_map_the_same; auto.\n    rewrite !flat_map_collectDids, app_comm_cons, !app_assoc.\n    apply Permutation_app_tail. rewrite <- app_comm_cons.\n    apply Permutation_trans with\n        (flat_map collectDids l1 ++ cnt :: collectDids (Dnode did' treeL'))%list.\n    1: apply Permutation_middle.\n    apply Permutation_app_head. apply H with (path := path); auto.\n    - rewrite in_app_iff. right; simpl; left; auto.\n    - rewrite flat_map_collectDids in H3. apply NoDup_app_r, NoDup_app_l in H3; auto.\n    - intro; apply H2. simpl. right.\n      rewrite flat_map_collectDids, in_app_iff. right. simpl in *. intuition.\n  Qed.\n\n  Lemma addDidToTree_the_same_Fids: forall (tree : Tree) (d: Did) (cnt : nat),\n      collectFids (addDidToTree tree d cnt) = collectFids tree.\n  Proof.\n    induction tree using tree_ind2; intros; simpl; auto.\n    rm_if. simpl. rewrite Forall_forall in H.\n    rewrite !flat_map_concat_map. f_equal. rewrite map_map.\n    apply map_ext_in. intros. apply H; auto.\n  Qed.\n\n  Lemma DnodeIsDir: forall d l, isDir (Dnode d l).\n  Proof. intros; exists d, l; auto. Qed.\n\n  Lemma fs_mkdir_ok: forall (path: Path) (dname: string) (p: Permission)\n                            (fs: FSState) (err: ErrCode) (postFS: FSState),\n      good_file_system (fsFS fs) -> (err, postFS) = fs_mkdir (path, dname, p) fs ->\n      (dname = EmptyString /\\ err = eBadName /\\ postFS = fs) \\/\n      (file_in_tree (fMapFS fs) (dMapFS fs) path dname (layoutFS fs) /\\\n       err = eNotDir /\\ fs = postFS) \\/\n      (path_in_tree (dMapFS fs) (path ++ [dname])%list (layoutFS fs) /\\\n       err = eExists /\\ fs = postFS) \\/\n      (~ path_in_tree (dMapFS fs) path (layoutFS fs) /\\ err = eNoEnt /\\ fs = postFS) \\/\n      ((exists did, path_in_tree_with_id (dMapFS fs) path (layoutFS fs) did /\\\n                    ((dMapFS fs) did).(metaD).(writable) = false) /\\ err = eAcces /\\\n       fs = postFS) \\/\n      ((exists did, path_in_tree_with_id (dMapFS fs) path (layoutFS fs) did /\\\n                    ((dMapFS fs) did).(metaD).(writable) = true) /\\ err <> eSucc /\\\n       fsFS fs = fsFS postFS /\\\n       exists vmkdir_err,\n         err = vmkdir_err /\\\n         logFS postFS = Call_VMkdir path dname p vmkdir_err :: logFS fs) \\/\n      ((exists did, path_in_tree_with_id (dMapFS fs) path (layoutFS fs) did /\\\n                    ((dMapFS fs) did).(metaD).(writable) = true) /\\\n       err = eSucc /\\ dCntFS postFS = dCntFS fs + 1 /\\\n       (forall d, d <> dCntFS fs -> dMapFS fs d = dMapFS postFS d) /\\\n       dMapFS postFS (dCntFS fs) = Build_DData dname p /\\\n       path_in_tree_with_id (dMapFS postFS)\n                            (path ++ [dname])%list (layoutFS postFS) (dCntFS fs) /\\\n       good_file_system (fsFS postFS) /\\\n       logFS postFS = Call_VMkdir path dname p eSucc :: logFS fs).\n  Proof.\n    intros. unfold fs_mkdir in H0. rm_hif. 1: left; inversion H0; intuition.\n    simpl in H0. right. destruct (findMatchedFid (fst fs) path dname) eqn:? .\n    - left. apply file_in_tree_some in Heqo; auto. 1: inversion H0; intuition.\n      unfold fMapFS, dMapFS, layoutFS. destruct H. unfold fsFS in H. auto.\n    - right. destruct (findDir (d_map (fst fs)) (layout (fst fs))\n                               (path ++ [dname])%list) eqn: ?.\n      + apply path_in_tree_some in Heqo0; auto. inversion H0. intuition.\n      + right. destruct (findDir (d_map (fst fs)) (layout (fst fs)) path) eqn: ?.\n        * destruct t. 1: apply findDir_not_fnode in Heqo1; exfalso; auto.\n          apply path_in_tree_with_id_some in Heqo1. right. rm_hif_eqn H0.\n          -- left. split; [exists d; apply bool_eq_ok in Heqb | inversion H0];\n                     intuition.\n          -- right. unfold bool_eq in Heqb. rm_hif_eqn Heqb. 2: inversion Heqb.\n             clear Heqb. destruct fs. simpl in H0. rm_hif.\n             ++ left. split; [exists d | inversion H0]; intuition. exists err.\n                subst err. intuition.\n             ++ right. split; [exists d; intuition |]. simpl in H0. inversion H0.\n                unfold dMapFS, layoutFS, dCntFS, logFS. simpl. rewrite e.\n                simpl in H. destruct H as [? [? [? [? [? [? [? [? ?]]]]]]]].\n                intuition; assert (HS: ~ In (dnode_ctr f) (collectDids (layout f))) by\n                    (intro S; apply H5 in S; intuition);\n                [unfold change_d_map; rm_if; exfalso; auto.. | | ].\n                ** unfold dMapFS, layoutFS in Heqo1. simpl in Heqo1.\n                   apply addDidToTree_in_tree; auto.\n                ** apply file_in_tree_none in Heqo; auto.\n                   apply path_in_tree_none in Heqo0; auto.\n                   unfold fMapFS, dMapFS, layoutFS in *. simpl in *.\n                   pose proof (addDidToTree_Permutation _ _ _ _ _ H1 Heqo1 HS).\n                   split;\n                     [|split; [|split;\n                                [|split; [|split; [|split; [|split]]]]]]; simpl; auto.\n                   --- apply addDidToTree_NoDupNameTree with (path := path); auto.\n                   --- apply (Permutation_NoDup H13). constructor; auto.\n                   --- rewrite addDidToTree_the_same_Fids; auto.\n                   --- intros. apply Permutation_sym in H13.\n                       apply (Permutation_in el H13) in H15.\n                       simpl in H15. specialize (H5 el). destruct H15; intuition.\n                   --- intros. rewrite addDidToTree_the_same_Fids in H15.\n                       apply H6; auto.\n                   --- unfold isDir in *. destruct H8 as [dd [ll ?]].\n                       rewrite H8. simpl. rm_if; apply DnodeIsDir.\n        * simpl in H; destruct H as [? [? [? [? [? [? ?]]]]]].\n          apply path_in_tree_none in Heqo1; auto. inversion H0. left. auto.\n  Qed.\n\n  Lemma findDir_file_in_tree: forall fmap dmap d l fId name tree path,\n      findDir dmap tree path = Some (Dnode d l) -> nameF (fmap fId) = name ->\n      In (Fnode fId) l -> file_in_tree fmap dmap path name tree.\n  Proof.\n    intros fmap dmap d l fId name. induction tree using tree_ind2; intros;\n                                     destruct path; simpl in H; [inversion H.. | |].\n    - simpl in H0. inversion H0. subst. constructor. rewrite Exists_exists.\n      exists (Fnode fId). intuition. constructor. auto.\n    - simpl in H0. constructor.\n      destruct (find (fun x : Tree => root_eq dmap x s) treeL) eqn:? .\n      2: inversion H0. apply find_some in Heqo. destruct Heqo.\n      unfold root_eq, DData_eqb in H4. destruct t. 1: inversion H4. rm_hif.\n      2: inversion H4. clear H4. exists d0, l0. intuition.\n      rewrite Forall_forall in H. apply H; intuition.\n  Qed.\n\n  Lemma findDir_path_in_tree: forall dmap d l dId ld name tree path,\n      findDir dmap tree path = Some (Dnode d l) -> nameD (dmap dId) = name ->\n      In (Dnode dId ld) l -> path_in_tree dmap (path ++ [name])%list tree.\n  Proof.\n    intros dmap d l dId ld name.\n    induction tree using tree_ind2; intros; destruct path;\n      simpl in H; [inversion H.. | |]; simpl in *.\n    - inversion H0. subst. constructor. exists dId, ld. intuition. constructor.\n    - constructor. destruct (find (fun x : Tree => root_eq dmap x s) treeL) eqn:? .\n      2: inversion H0. apply find_some in Heqo. destruct Heqo.\n      unfold root_eq, DData_eqb in H4. destruct t. 1: inversion H4. rm_hif.\n      2: inversion H4. clear H4. exists d0, l0. intuition.\n      rewrite Forall_forall in H. apply H; intuition.\n  Qed.\n\n  Lemma same_name_the_same_tree: forall fmap dmap treeL d l did' treeL',\n      nameD (dmap did') = nameD (dmap d) -> NoDup (map (treeName fmap dmap) treeL) ->\n      In (Dnode d l) treeL -> In (Dnode did' treeL') treeL ->\n      Dnode d l = Dnode did' treeL'.\n  Proof.\n    intros. apply in_split in H1. destruct H1 as [l1 [l2 ?]]. subst treeL.\n    rewrite in_app_iff in H2. simpl in H2.\n    destruct H2 as [? | [? | ?]]; auto; exfalso; apply in_split in H1;\n      destruct H1 as [l3 [l4 ?]].\n    - subst l1. rewrite <- app_assoc in H0. rewrite map_app in H0.\n      apply NoDup_app_r in H0. rewrite <- app_comm_cons in H0.\n      rewrite map_cons in H0. simpl in H0.\n      rewrite NoDup_cons_iff in H0. destruct H0 as [? _].\n      rewrite map_app, map_cons in H0. apply H0. rewrite in_app_iff.\n      right. simpl. left; auto.\n    - subst l2. rewrite map_app in H0. apply NoDup_app_r in H0.\n      rewrite map_cons, NoDup_cons_iff in H0. simpl in H0. destruct H0 as [? _].\n      apply H0. rewrite map_app, map_cons, in_app_iff. right. simpl. left; auto.\n  Qed.\n\n  Lemma path_in_tree_treeName: forall fmap dmap d l name tree path,\n      NoDupNameTree fmap dmap tree -> findDir dmap tree path = Some (Dnode d l) ->\n      path_in_tree dmap (path ++ [name])%list tree ->\n      In name (map (treeName fmap dmap) l).\n  Proof.\n    intros fmap dmap d l name. induction tree using tree_ind2; intros.\n    1: inversion H1. destruct path; simpl in *; inversion H2; subst.\n    - inversion H1. subst. destruct H4 as [did' [treeL [? [? ?]]]].\n      rewrite in_map_iff. exists (Dnode did' treeL). simpl. intuition.\n    - destruct (find (fun x : Tree => root_eq dmap x s) treeL) eqn: ?.\n      2: inversion H1. rewrite Forall_forall in H.\n      destruct H4 as [did' [treeL' [? [? ?]]]].\n      apply find_some in Heqo. destruct Heqo. unfold root_eq, DData_eqb in H7.\n      destruct t. 1: inversion H7. rm_hif. 2: inversion H7. clear H7.\n      inversion H0. subst. assert (Dnode d0 l0 = Dnode did' treeL') by\n          (eapply same_name_the_same_tree; eauto). inversion H7. subst.\n      eapply H; eauto. rewrite Forall_forall in H11. apply H11; auto.\n  Qed.\n\n  Lemma file_in_tree_treeName: forall fmap dmap d l name tree path,\n      NoDupNameTree fmap dmap tree -> findDir dmap tree path = Some (Dnode d l) ->\n      file_in_tree fmap dmap path name tree -> In name (map (treeName fmap dmap) l).\n  Proof.\n    intros fmap dmap d l name.\n    induction tree using tree_ind2; intros; destruct path; simpl in H0;\n      [inversion H0.. | |]; simpl in *; rewrite Forall_forall in H.\n    - inversion H1; subst. inversion H2. subst. rewrite Exists_exists in H6.\n      destruct H6 as [x [? ?]]. destruct x; inversion H4. rewrite in_map_iff.\n      exists (Fnode f). simpl. intuition.\n    - destruct (find (fun x : Tree => root_eq dmap x s) treeL) eqn:? .\n      2: inversion H1. apply find_some in Heqo. destruct Heqo.\n      unfold root_eq, DData_eqb in H4. destruct t.\n      1: inversion H4. rm_hif. 2: inversion H4. clear H4. inversion H2.\n      subst. destruct H7 as [did' [treeL' [? [? ?]]]]. inversion H0; subst.\n      assert (Dnode d0 l0 = Dnode did' treeL') by\n          (eapply same_name_the_same_tree; eauto). inversion H7. subst.\n      eapply H; eauto. rewrite Forall_forall in H11. apply H11; auto.\n  Qed.\n\n  Lemma fs_readdir_ok: forall (path: Path) (fs: FSState)\n                              (result: list string) (err: ErrCode) (postFS: FSState),\n      good_file_system (fsFS fs) -> (result, err, postFS) = fs_readdir path fs ->\n      (~ path_in_tree (dMapFS fs) path (layoutFS fs) /\\ result = nil /\\ err = eBadF /\\\n       postFS = fs) \\/\n      (path_in_tree (dMapFS fs) path (layoutFS fs) /\\ result = nil /\\ err <> eSucc /\\\n       fsFS fs = fsFS postFS /\\ logFS postFS = Call_VReadDir path err :: logFS fs) \\/\n      (path_in_tree (dMapFS fs) path (layoutFS fs)/\\ err = eSucc /\\\n       fsFS fs = fsFS postFS /\\ logFS postFS = Call_VReadDir path eSucc :: logFS fs /\\\n       forall name, In name result <->\n                    path_in_tree (dMapFS fs) (path ++ [name])%list (layoutFS fs) \\/\n                    file_in_tree (fMapFS fs) (dMapFS fs) path name (layoutFS fs)).\n  Proof.\n    intros. unfold fs_readdir in H0. simpl in H0.\n    destruct (findDir (d_map (fst fs)) (layout (fst fs)) path) eqn:? .\n    - destruct t. 1: exfalso; revert Heqo; apply findDir_not_fnode.\n      destruct fs. simpl in H0. rm_hif.\n      + right. left. simpl. apply path_in_tree_some in Heqo. inversion H0; intuition.\n      + right; right. inversion H0. subst; simpl. rewrite e. clear H0 e.\n        intuition; [apply path_in_tree_some in Heqo; auto |\n                    unfold dMapFS, fMapFS, layoutFS; simpl in *..].\n        * rewrite in_map_iff in H0. destruct H0 as [t [? ?]].\n          destruct t; simpl in H0; [right | left].\n          -- eapply findDir_file_in_tree; eauto.\n          -- eapply findDir_path_in_tree; eauto.\n        * destruct H as [? [? [? ?]]]; eapply path_in_tree_treeName; eauto.\n        * unfold dMapFS, fMapFS, layoutFS in H1. simpl in H1.\n          destruct H as [? [? [? ?]]]. eapply file_in_tree_treeName; eauto.\n    - apply path_in_tree_none in Heqo. 2: destruct H as [? [? [? ?]]]; auto.\n      left. inversion H0; intuition.\n  Qed.\n\n  Lemma fs_fstat_ok: forall (id : Fid) (fs: FSState) (name: string)\n                            (permsn: Permission) (fsize: nat) (pageIds : list Pgid)\n                            (err: ErrCode) (postFS: FSState),\n      (name, permsn, fsize, pageIds, err, postFS) = fs_fstat id fs ->\n      (~ In id (map fst (openhandleFS fs)) /\\ postFS = fs /\\ err = eBadF /\\\n       name = EmptyString /\\ permsn = fff /\\ fsize = O /\\ pageIds = nil) \\/\n      (In id (map fst (openhandleFS fs)) /\\ fsFS postFS = fsFS fs /\\ err <> eSucc /\\\n       name = EmptyString /\\ permsn = fff /\\ fsize = O /\\ pageIds = nil /\\\n       logFS postFS = Call_VStat id err :: logFS fs) \\/\n      (In id (map fst (openhandleFS fs)) /\\ fsFS postFS = fsFS fs /\\ err = eSucc /\\\n       name = ((fMapFS fs) id).(nameF) /\\\n       permsn = ((fMapFS fs) id).(metaF).(permission) /\\\n       fsize = ((fMapFS fs) id).(metaF).(size) /\\\n       pageIds = ((fMapFS fs) id).(pageIdsF) /\\\n       logFS postFS = Call_VStat id eSucc :: logFS fs).\n  Proof.\n    intros. unfold fs_fstat in H. simpl in H.\n    destruct (find (fun x : nat * nat => Nat.eqb (fst x) id) (open_handles (fst fs))) eqn:? .\n    - destruct fs. simpl in *. destruct p. simpl in H. rm_hif; inversion H; right.\n      + left. simpl. intuition. eapply find_Fid_In; eauto.\n      + right. unfold openhandleFS, fMapFS, logFS. simpl. rewrite e.\n        intuition. eapply find_Fid_In; eauto.\n    - left. inversion H. intuition. eapply find_Fid_None; eauto.\n  Qed.\n\n  Lemma fs_chmod_ok: forall (path: Path) (p: Permission) (fs: FSState)\n                            (err: ErrCode) (postFS: FSState),\n      good_file_system (fsFS fs) -> (err, postFS) = fs_chmod (path, p) fs ->\n      (~ path_in_tree (dMapFS fs) path (layoutFS fs) /\\\n       ~ file_in_tree (fMapFS fs) (dMapFS fs) (removelast path)\n         (foot path) (layoutFS fs) /\\ path <> nil /\\ err = eNoEnt /\\ postFS = fs) \\/\n      ((exists id,\n           path_in_tree_with_id (dMapFS fs) path (layoutFS fs) id \\/\n           (path <> nil /\\\n            file_in_tree_with_id (fMapFS fs) (dMapFS fs)\n                                 (removelast path) (foot path) (layoutFS fs) id)) /\\\n       fsFS fs = fsFS postFS /\\ err <> eSucc /\\\n       logFS postFS = Call_VChmod path p err :: logFS fs) \\/\n      ((exists id, path_in_tree_with_id (dMapFS fs) path (layoutFS fs) id /\\\n                   (dMapFS postFS id).(metaD) = p /\\\n                   (dMapFS postFS id).(nameD) = (dMapFS fs id).(nameD) /\\\n                   forall did, did <> id -> dMapFS postFS did = dMapFS fs did) /\\\n       layoutFS fs = layoutFS postFS /\\ openhandleFS fs = openhandleFS postFS /\\\n       vmFS fs = vmFS postFS /\\ fMapFS fs = fMapFS postFS /\\\n       fCntFS fs = fCntFS postFS /\\ dCntFS fs = dCntFS postFS /\\\n       mmap_handles (fsFS fs) = mmap_handles (fsFS postFS) /\\\n       mmap_memory (fsFS fs) = mmap_memory (fsFS postFS) /\\\n       err = eSucc /\\ logFS postFS = Call_VChmod path p eSucc :: logFS fs) \\/\n      ((exists id,\n           file_in_tree_with_id (fMapFS fs) (dMapFS fs)\n                                (removelast path) (foot path) (layoutFS fs) id /\\\n           (fMapFS postFS id).(metaF).(permission) = p /\\\n           (fMapFS postFS id).(nameF) = (fMapFS fs id).(nameF) /\\\n           (fMapFS postFS id).(pageIdsF) = (fMapFS fs id).(pageIdsF) /\\\n           (fMapFS postFS id).(metaF).(size) = (fMapFS fs id).(metaF).(size) /\\\n           forall did, did <> id -> fMapFS postFS did = fMapFS fs did) /\\\n       path <> nil /\\ layoutFS fs = layoutFS postFS /\\\n       openhandleFS fs = openhandleFS postFS /\\ vmFS fs = vmFS postFS /\\\n       dMapFS fs = dMapFS postFS /\\ fCntFS fs = fCntFS postFS /\\\n       dCntFS fs = dCntFS postFS /\\ err = eSucc /\\\n       mmap_handles (fsFS fs) = mmap_handles (fsFS postFS) /\\\n       mmap_memory (fsFS fs) = mmap_memory (fsFS postFS) /\\\n       logFS postFS = Call_VChmod path p eSucc :: logFS fs).\n  Proof.\n    intros. unfold fs_chmod in H0. simpl in H0.\n    destruct (findDir (d_map (fst fs)) (layout (fst fs)) path) eqn: ?.\n    - destruct t. 1: exfalso; revert Heqo; apply findDir_not_fnode. destruct fs.\n      unfold fsFS, logFS, dMapFS, layoutFS, openhandleFS, vmFS, fMapFS, fCntFS, dCntFS.\n      simpl in *. apply path_in_tree_with_id_some in Heqo. rm_hif.\n      + right. left. inversion H0. simpl. intuition. exists d. left; auto.\n      + right. right. left. simpl in H0. inversion H0. simpl. rewrite e. intuition.\n        exists d. split; auto. unfold change_d_map_permission.\n        destruct (Nat.eq_dec d d). 2: exfalso; apply n; auto. simpl. intuition. rm_if.\n        exfalso. auto.\n    - destruct path eqn:? .\n      + exfalso. simpl in Heqo. destruct (layout (fst fs)) eqn:? . 2: inversion Heqo.\n        destruct H as [? [? [? [? [? [? [? [? ?]]]]]]]]. unfold isDir, fsFS in H6.\n        destruct H6 as [? [? ?]]. rewrite H6 in Heqt. inversion Heqt.\n      + assert (path <> nil) by (rewrite Heqp0; intro; inversion H1).\n        rewrite <- Heqp0 in *. clear s p0 Heqp0.\n        destruct (findMatchedFid (fst fs) (removelast path) (foot path)) eqn:? .\n        * destruct fs. unfold fsFS, logFS, dMapFS, layoutFS, openhandleFS, vmFS,\n                       fMapFS, fCntFS, dCntFS. simpl in *.\n          apply file_in_tree_with_id_some in Heqo0. 2: destruct H; auto. rm_hif.\n          -- right. left. inversion H0. simpl. intuition. exists f. intuition.\n          -- do 3 right. simpl in H0. inversion H0. simpl. rewrite e. intuition.\n             exists f. split; auto. unfold change_f_map_permission. rm_if.\n             2: exfalso; apply n; auto. simpl. intuition. rm_if. exfalso; intuition.\n        * left. destruct H. apply path_in_tree_none in Heqo; auto.\n          apply file_in_tree_none in Heqo0; auto. inversion H0. intuition.\n  Qed.\n\n  Lemma getSublist_length {A}: forall n m (l: list A), length (getSublist n m l) <= m.\n  Proof.\n    intros; revert n m. induction l; intros; simpl.\n    1: destruct n; destruct m; simpl; intuition. destruct n.\n    2: apply IHl. destruct m; simpl; intuition.\n  Qed.\n\n  Lemma getSublist_prefix {A}: forall m (l: list A), exists l',\n        l = (getSublist 0 m l ++ l')%list.\n  Proof.\n    intros; revert m. induction l; intros; simpl.\n    - exists []. destruct m; simpl; auto.\n    - destruct m.\n      + exists (a :: l). simpl; auto.\n      + destruct (IHl m) as [l' ?]. exists l'. rewrite H at 1. simpl; auto.\n  Qed.\n\n  Opaque psize block_size.\n\n  Lemma fs_truncate_ok:\n    forall (fId : Fid) (len : nat) (fs: FSState) (err: ErrCode) (postFS : FSState),\n      good_file_system (fsFS fs) -> (err, postFS) = fs_truncate (fId, len) fs ->\n      (~ In fId (map fst (openhandleFS fs)) /\\ postFS = fs /\\ err = eBadF) \\/\n      (In fId (map fst (openhandleFS fs)) /\\ postFS = fs /\\ err = eInval) \\/\n      (In fId (map fst (openhandleFS fs)) /\\ postFS = fs /\\\n       (fMapFS fs fId).(metaF).(size) = len /\\ err = eSucc) \\/\n      (In fId (map fst (openhandleFS fs)) /\\ err <> eSucc /\\ fsFS fs = fsFS postFS /\\\n       exists pos content,\n         logFS postFS = Call_VTruncate fId pos content err :: logFS fs) \\/\n      (In fId (map fst (openhandleFS fs)) /\\ err = eSucc /\\\n       layoutFS fs = layoutFS postFS /\\ openhandleFS fs = openhandleFS postFS /\\\n       vmFS fs = vmFS postFS /\\ dMapFS fs = dMapFS postFS /\\\n       fCntFS fs = fCntFS postFS /\\ dCntFS fs = dCntFS postFS /\\\n       mmap_handles (fsFS fs) = mmap_handles (fsFS postFS) /\\\n       mmap_memory (fsFS fs) = mmap_memory (fsFS postFS) /\\\n       (fMapFS postFS fId).(nameF) = (fMapFS fs fId).(nameF) /\\\n       (fMapFS postFS fId).(metaF).(permission) =\n       (fMapFS fs fId).(metaF).(permission) /\\\n       (fMapFS postFS fId).(metaF).(size) = len /\\\n       length ((fMapFS postFS fId).(pageIdsF)) <= len / psize + 1 /\\\n       (forall id, id <> fId -> fMapFS postFS id = fMapFS fs id) /\\\n       (exists l, (fMapFS fs fId).(pageIdsF) =\n                  ((fMapFS postFS fId).(pageIdsF) ++ l)%list)).\n  Proof.\n    intros. unfold fs_truncate in H0. simpl in H0.\n    remember (if Nat.eq_dec (len mod psize) 0 then len / psize else len / psize + 1).\n    remember (len / psize * block_size).\n    remember (encrypt_page\n                (truncate_page\n                   (byte_list_to_string (nth (nth n (pageIdsF (f_map (fst fs) fId)) 0)\n                                             (virtual_memory (fst fs)) [])) 0\n                   (len mod psize))).\n    destruct (find (fun x : nat * nat => Nat.eqb (fst x) fId) (open_handles (fst fs))) eqn:? .\n    - apply find_Fid_In in Heqo. right. rm_hif.\n      + left. inversion H0; auto.\n      + destruct fs. simpl in H0. right. rm_hmatch.\n        * left. apply beq_nat_true in Heqb. inversion H0. intuition.\n        * simpl in H0. right. rm_hif.\n          -- left. inversion H0. simpl. intuition. exists n0, s. auto.\n          -- right. simpl in H0. inversion H0.\n             unfold fsFS, logFS, dMapFS, layoutFS, openhandleFS, vmFS, fMapFS, fCntFS,\n             dCntFS, change_f_map_size, change_f_map_pages. simpl in *.\n             do 8 (split; auto). destruct (Nat.eq_dec fId fId). 2: exfalso; intuition.\n             simpl. intuition.\n             ++ transitivity n. 1: apply getSublist_length. subst n. rm_if; intuition.\n             ++ destruct (Nat.eq_dec id fId); intuition.\n             ++ apply getSublist_prefix.\n    - inversion H0. left. intuition. apply find_Fid_None in H1; auto.\n  Qed.\n\n  Transparent psize block_size.\n\n  Lemma addFnodeToTree_in_tree: forall fmap dmap d cnt fname meta pgids tree path,\n      NoDup (collectDids tree) -> path_in_tree_with_id dmap path tree d ->\n      file_in_tree_with_id (change_f_map fmap cnt (Build_FData fname meta pgids))\n                           dmap path fname (addFnodeToTree tree d cnt) cnt.\n  Proof.\n    intros. revert path H H0. induction tree using tree_ind2; intros.\n    1: inversion H0. destruct path; inversion H1; subst.\n    - simpl. rm_if. 2: exfalso; auto.\n      constructor; [simpl; left | unfold change_f_map; rm_if; exfalso]; auto.\n    - destruct H7 as [did' [treeL' [? [? ?]]]]. simpl. rm_if.\n      + exfalso. revert e. eapply path_in_tree_nonempty_neq; eauto. intro.\n        inversion H5.\n      + constructor. rewrite Forall_forall in H. specialize (H _ H2).\n        assert (NoDup (collectDids (Dnode did' treeL'))) by\n            (apply subtree_nodup with (t := Dnode did' treeL') in H0; auto).\n        specialize (H _ H5 H4).\n        simpl in H. apply (in_map (fun t : Tree => addFnodeToTree t d cnt)) in H2.\n        simpl in H2. destruct (Nat.eq_dec d did').\n        * subst d. exists did', (Fnode cnt :: treeL'). split; [|split]; auto.\n        * exists did', (map (fun t : Tree => addFnodeToTree t d cnt) treeL').\n          split; [|split]; auto.\n  Qed.\n\n  Lemma addFnodeToTree_the_same_dids: forall tree d cnt,\n      collectDids (addFnodeToTree tree d cnt) = collectDids tree.\n  Proof.\n    induction tree using tree_ind2; intros; simpl; auto.\n    rm_if; [subst |]; simpl; auto. f_equal. rewrite !flat_map_concat_map.\n    f_equal. rewrite map_map. apply map_ext_in.\n    intros. rewrite Forall_forall in H. apply H; auto.\n  Qed.\n\n  Lemma addFnodeToTree_the_same: forall d cnt tree,\n      ~ In d (collectDids tree) -> addFnodeToTree tree d cnt = tree.\n  Proof.\n    intros. induction tree using tree_ind2; simpl; auto. rm_if.\n    1: subst; exfalso; apply H; simpl; left; auto.\n    rewrite Forall_forall in H0. f_equal. simpl in H. assert (treeL = map id treeL) by\n        (clear; induction treeL; simpl; [|rewrite IHtreeL at 1]; auto).\n    rewrite H1 at 2. clear H1. apply map_ext_in. intros. unfold id. apply H0; auto.\n    intro. apply H. right. apply (subtree_did_in_merge a); auto.\n  Qed.\n\n  Lemma addFnodeToTree_the_same_list: forall d cnt l,\n      ~ In d (flat_map collectDids l) -> map (fun t => addFnodeToTree t d cnt) l = l.\n  Proof.\n    intros. assert (l = map id l) by\n        (clear; induction l; simpl; [|rewrite IHl at 1]; auto).\n    rewrite H0 at 2; clear H0. apply map_ext_in. unfold id. intros.\n    apply addFnodeToTree_the_same. intro; apply H.\n    apply (subtree_did_in_merge a); auto.\n  Qed.\n\n  Lemma addFnodeToTree_map_the_same:\n    forall (l1 l2 : list Tree) (did' : Did) (treeL' : list Tree) (d cnt : Did),\n      NoDup (flat_map collectDids (l1 ++ Dnode did' treeL' :: l2)) ->\n      In d (collectDids (Dnode did' treeL')) ->\n      map (fun t : Tree => addFnodeToTree t d cnt) (l1 ++ Dnode did' treeL' :: l2) =\n      (l1 ++ addFnodeToTree (Dnode did' treeL') d cnt :: l2)%list.\n  Proof.\n    intros; rewrite map_app, map_cons. rewrite flat_map_collectDids in H.\n    f_equal; [|f_equal]; apply addFnodeToTree_the_same_list.\n    - apply NoDup_app_not_in_l with (y := d) in H; auto. apply in_or_app. left; auto.\n    - apply NoDup_app_r in H. apply NoDup_app_not_in_r with (y := d) in H; auto.\n  Qed.\n\n  Lemma flat_map_collectFids: forall l1 l2 t,\n      flat_map collectFids (l1 ++ t :: l2) =\n      (flat_map collectFids l1 ++ collectFids t ++ flat_map collectFids l2)%list.\n  Proof.\n    intros. rewrite flat_map_concat_map, map_app, map_cons,\n            concat_app, concat_cons, <- !flat_map_concat_map; auto.\n  Qed.\n\n  Lemma addFnodeToTree_Permutation: forall dmap cnt d tree path,\n      NoDup (collectDids tree) -> path_in_tree_with_id dmap path tree d ->\n      ~ In cnt (collectFids tree) ->\n      Permutation (cnt :: collectFids tree) (collectFids (addFnodeToTree tree d cnt)).\n  Proof.\n    intros dmap cnt d. induction tree using tree_ind2; intros; simpl. 1: inversion H0.\n    rewrite Forall_forall in H. rm_if. simpl. destruct path; inversion H1; subst.\n    1: exfalso; apply n; auto. destruct H8 as [did' [treeL' [? [? ?]]]].\n    pose proof H5. rename H6 into HS. apply in_split in H3. destruct H3 as [l1 [l2 ?]].\n    subst treeL. apply path_in_tree_collectDids in H5. simpl in H0.\n    rewrite NoDup_cons_iff in H0. destruct H0.\n    rewrite !addFnodeToTree_map_the_same; auto.\n    rewrite !flat_map_collectFids, app_comm_cons, !app_assoc.\n    apply Permutation_app_tail. rewrite <- app_comm_cons.\n    apply Permutation_trans with\n        (flat_map collectFids l1 ++ cnt :: collectFids (Dnode did' treeL'))%list.\n    1: apply Permutation_middle. apply Permutation_app_head.\n    apply H with (path := path); auto.\n    - rewrite in_app_iff. right; simpl; left; auto.\n    - rewrite flat_map_collectDids in H3. apply NoDup_app_r, NoDup_app_l in H3; auto.\n    - intro; apply H2. simpl. rewrite flat_map_collectFids, in_app_iff.\n      right. simpl in *. intuition.\n  Qed.\n\n  Lemma change_f_map_NoDupNameTree: forall fmap dmap cnt d t,\n      ~ In cnt (collectFids t) -> NoDupNameTree fmap dmap t ->\n      NoDupNameTree (change_f_map fmap cnt d) dmap t.\n  Proof.\n    intros fmap dmap cnt d. induction t using tree_ind2; intros; constructor.\n    - rewrite Forall_forall in *. intros. apply H; auto.\n      + intro. apply H0. simpl. rewrite in_flat_map. exists x; intuition.\n      + inversion H1. subst. rewrite Forall_forall in H7. apply H7; auto.\n    - inversion H1. subst.\n      assert (map (treeName fmap dmap) treeL =\n              map (treeName (change_f_map fmap cnt d) dmap) treeL). {\n        apply map_ext_in. intros. unfold change_f_map. destruct a; simpl; auto. rm_if.\n        exfalso. apply H0. simpl. rewrite in_flat_map. subst f.\n        exists (Fnode cnt). split; simpl; intuition.\n      } rewrite <- H2. auto.\n  Qed.\n\n  Lemma treeName_eq_treeL': forall fmap dmap cnt d treeL,\n      ~ In cnt (flat_map collectFids treeL) ->\n      map (treeName fmap dmap) treeL =\n      map (treeName (change_f_map fmap cnt d) dmap) treeL.\n  Proof.\n    intros. apply map_ext_in. intros. unfold change_f_map. destruct a; simpl; auto.\n    rm_if. subst. exfalso. apply H. rewrite in_flat_map. exists (Fnode cnt).\n    simpl; auto.\n  Qed.\n\n  Lemma addFnodeToTree_NoDupNameTree:\n    forall fmap dmap fname cnt d meta pgids tree path,\n      ~ file_in_tree fmap dmap path fname tree ->\n      ~ path_in_tree dmap (path ++ [fname])%list tree ->\n      path_in_tree_with_id dmap path tree d -> ~ In cnt (collectFids tree) ->\n      NoDupNameTree fmap dmap tree -> NoDup (collectDids tree) ->\n      NoDupNameTree (change_f_map fmap cnt (Build_FData fname meta pgids)) dmap\n                    (addFnodeToTree tree d cnt).\n  Proof.\n    intros fmap dmap fname cnt d meta pgids. induction tree using tree_ind2; intros.\n    1: inversion H1. destruct path; inversion H2; subst.\n    - simpl in *. rm_if. 2: exfalso; auto. clear e H. constructor.\n      + rewrite Forall_forall. intros. simpl in H. destruct H. 1: subst x; constructor.\n        inversion H4. subst. rewrite Forall_forall in H10. specialize (H10 _ H).\n        apply change_f_map_NoDupNameTree; auto. intro. apply H3. rewrite in_flat_map.\n        exists x; auto.\n      + simpl. unfold change_f_map at 1. rm_if. 2: exfalso; auto. simpl. clear e.\n        rewrite <- treeName_eq_treeL'; auto. constructor. 2: inversion H4; auto.\n        intro. rewrite in_map_iff in H. destruct H as [x [? ?]]. destruct x.\n        * apply H0. constructor. rewrite Exists_exists. exists (Fnode f). split; auto.\n          constructor. simpl in H. auto.\n        * apply H1. constructor. exists d0, l. simpl in H. intuition. constructor.\n    - destruct H11 as [did' [treeL' [? [? ?]]]]. simpl. rm_if.\n      + exfalso. revert e. eapply path_in_tree_nonempty_neq; eauto.\n        intro. inversion H9.\n      + assert (NoDupNameTree (change_f_map fmap cnt (Build_FData fname meta pgids))\n                              dmap (addFnodeToTree (Dnode did' treeL') d cnt)). {\n          rewrite Forall_forall in H. apply H with (path := path); try intro; auto.\n          - apply H0; constructor; exists did', treeL'; intuition.\n          - apply H1; simpl; constructor; exists did', treeL'; intuition.\n          - apply H3; simpl. rewrite in_flat_map. exists (Dnode did' treeL'); auto.\n          - inversion H4. subst. rewrite Forall_forall in H13. apply H13. auto.\n          - apply (subtree_nodup _ _ _ H6 H5).\n        } clear H. apply in_split in H6. destruct H6 as [l1 [l2 ?]]. subst treeL.\n        apply path_in_tree_collectDids in H8.\n        rewrite addFnodeToTree_map_the_same; auto. inversion H4. subst.\n        2: simpl in H5; rewrite NoDup_cons_iff in H5; destruct H5; auto. constructor.\n        * rewrite Forall_forall in *. intros. simpl in H3.\n          rewrite flat_map_collectFids in H3. rewrite in_app_iff in H.\n          destruct H; [|apply in_inv in H; destruct H];\n            [apply change_f_map_NoDupNameTree | subst x |\n             apply change_f_map_NoDupNameTree ]; auto.\n          -- intro. apply H3. rewrite in_app_iff. left. rewrite in_flat_map.\n             exists x; auto.\n          -- apply H12. rewrite in_app_iff. left; auto.\n          -- intro. apply H3. do 2 (rewrite in_app_iff; right). rewrite in_flat_map.\n             exists x; auto.\n          -- apply H12. rewrite in_app_iff. right. simpl. right; auto.\n        * rewrite map_app, map_cons in *. simpl in H13. simpl in H3.\n          rewrite flat_map_collectFids in H3.\n          assert (treeName (change_f_map fmap cnt (Build_FData fname meta pgids))\n                           dmap (addFnodeToTree (Dnode did' treeL') d cnt) =\n                  nameD (dmap did')) by (simpl; rm_if; subst d; simpl; auto).\n          rewrite H; clear H. rewrite <- !treeName_eq_treeL'; auto; intro; apply H3;\n                                rewrite !in_app_iff; [right; right | left]; auto.\n  Qed.\n\n  Lemma fs_create_ok: forall (path : Path) (fname : string) (p : Permission)\n                             (fs : FSState) (err : ErrCode) (postFS : FSState),\n      good_file_system (fsFS fs) -> (err, postFS) = fs_create (path, fname, p) fs ->\n      (fname = EmptyString /\\ err = eBadName /\\ postFS = fs) \\/\n      (file_in_tree (fMapFS fs) (dMapFS fs) path fname (layoutFS fs) /\\\n       err = eExists /\\ fs = postFS) \\/\n      (path_in_tree (dMapFS fs) (path ++ [fname])%list (layoutFS fs) /\\\n       err = eIsDir /\\ fs = postFS) \\/\n      (~ path_in_tree (dMapFS fs) path (layoutFS fs) /\\ err = eNoDir /\\ fs = postFS) \\/\n      ((exists did, path_in_tree_with_id (dMapFS fs) path (layoutFS fs) did /\\\n                    ((dMapFS fs) did).(metaD).(writable) = false) /\\ err = eAcces /\\\n       fs = postFS) \\/\n      ((exists did, path_in_tree_with_id (dMapFS fs) path (layoutFS fs) did /\\\n                    ((dMapFS fs) did).(metaD).(writable) = true) /\\\n       err <> eSucc /\\ fsFS fs = fsFS postFS /\\\n       logFS postFS = Call_VCreate path fname p err :: logFS fs) \\/\n      ((exists did, path_in_tree_with_id (dMapFS fs) path (layoutFS fs) did /\\\n                    ((dMapFS fs) did).(metaD).(writable) = true) /\\ err = eSucc /\\\n       logFS postFS = Call_VCreate path fname p eSucc :: logFS fs /\\\n       openhandleFS fs = openhandleFS postFS /\\ vmFS fs = vmFS postFS /\\\n       dMapFS fs = dMapFS postFS /\\ fCntFS fs + 1 = fCntFS postFS /\\\n       dCntFS fs = dCntFS postFS /\\\n       mmap_handles (fsFS fs) = mmap_handles (fsFS postFS) /\\\n       mmap_memory (fsFS fs) = mmap_memory (fsFS postFS) /\\\n       fMapFS postFS (fCntFS fs) = Build_FData fname (Build_Meta p O) nil /\\\n       (forall id, id <> fCntFS fs -> fMapFS fs id = fMapFS postFS id) /\\\n       file_in_tree_with_id (fMapFS postFS) (dMapFS postFS) path fname\n                            (layoutFS postFS) (fCntFS fs) /\\\n       good_file_system (fsFS postFS)).\n  Proof.\n    intros. unfold fs_create in H0. simpl in H0. rm_hif.\n    - left; inversion H0; intuition.\n    - right. destruct H. unfold fsFS in *. rm_hmatch.\n      + left; apply file_in_tree_some in Heqo; inversion H0; auto.\n      + right. rm_hmatch.\n        * left. apply path_in_tree_some in Heqo0. inversion H0; auto.\n        * right. apply file_in_tree_none in Heqo; auto.\n          apply path_in_tree_none in Heqo0; auto. rm_hmatch.\n          -- right. destruct t. 1: exfalso; revert Heqo1; apply findDir_not_fnode.\n             apply path_in_tree_with_id_some in Heqo1. rm_hmatch.\n             ++ left. apply bool_eq_ok in Heqb. inversion H0. intuition.\n                exists d. intuition.\n             ++ right. destruct fs. simpl in H0. unfold bool_eq in Heqb.\n                destruct (writable (metaD (d_map (fst (f, l0)) d))) eqn:? .\n                2: simpl in Heqb; inversion Heqb. rm_hif.\n                ** left. simpl. inversion H0. intuition. exists d. intuition.\n                ** right. simpl in H0. unfold logFS, openhandleFS, vmFS, dMapFS,\n                                       fCntFS, dCntFS, fMapFS, fsFS, layoutFS in *.\n                   inversion H0; simpl. rewrite e.\n                   intuition; [exists d; intuition | unfold change_f_map; rm_if;\n                                                     exfalso; intuition.. | |].\n                   --- apply addFnodeToTree_in_tree; auto.\n                   --- simpl in *.\n                       assert (~ In (fnode_ctr f) (collectFids (layout f))) by\n                           (intro S; apply H6 in S; intuition).\n                       pose proof (addFnodeToTree_Permutation _ _ _ _ _ H2 Heqo1 H13).\n                       split; [|split; [|split; [|split; [|split; [|split; [|split; [|split;[|split;[|split]]]]]]]]]; simpl; auto.\n                       +++ apply addFnodeToTree_NoDupNameTree with (path := path);\n                             auto.\n                       +++ rewrite addFnodeToTree_the_same_dids. auto.\n                       +++ apply (Permutation_NoDup H15). constructor; auto.\n                       +++ intros. rewrite addFnodeToTree_the_same_dids in H16.\n                           apply H5; auto.\n                       +++ intros. apply Permutation_sym in H15.\n                           apply (Permutation_in el H15) in H16. simpl in H16.\n                           specialize (H6 el). destruct H16; intuition.\n                       +++ unfold isDir in H8. destruct H8 as [dd [ll ?]]. rewrite H8.\n                           simpl. rm_if; apply DnodeIsDir.\n                       +++ intros. unfold change_f_map in H18, H17.\n                           rm_hif; rm_hif; simpl in *; [exfalso; auto..|]. intro.\n                           apply (H9 fId1 fId2 pgId1 pgId2); auto.\n                       +++ intros. unfold change_f_map in H16. rm_hif; simpl in H16.\n                           1: exfalso; auto. eapply H10; eauto.\n          -- left. apply path_in_tree_none in Heqo1; auto. inversion H0; auto.\n  Qed.\n\n  Lemma path_in_tree_removelast: forall dmap tree path,\n      path_in_tree dmap path tree -> path_in_tree dmap (removelast path) tree.\n  Proof.\n    intro. induction tree using tree_ind2; intros. 1: inversion H.\n    rewrite Forall_forall in H. destruct path. 1: simpl; auto. inversion H0. subst.\n    destruct H2 as [did' [treeL' [? [? ?]]]]. simpl. destruct path eqn:? .\n    constructor. rewrite <- Heql in *. clear s0 l Heql. constructor.\n    exists did', treeL'. specialize (H _ H1 _ H3). intuition.\n  Qed.\n\n  Lemma removeDirFromList_app:\n    forall l1 l2 did, removeDirFromList (l1 ++ l2) did =\n                      (removeDirFromList l1 did ++ removeDirFromList l2 did)%list.\n  Proof.\n    induction l1; intros; simpl; auto. destruct a.\n    - simpl. f_equal. apply IHl1.\n    - destruct (Nat.eq_dec d did); simpl; [|f_equal]; apply IHl1.\n  Qed.\n\n  Lemma removeDirFromList_the_same: forall did l,\n      ~ In did (flat_map collectDids l) -> removeDirFromList l did = l.\n  Proof.\n    intros. induction l; simpl; auto. destruct a.\n    - f_equal. apply IHl. simpl in H. auto.\n    - simpl in H. rm_if. 1: exfalso; apply H; left; auto. f_equal.\n      apply IHl. intro; apply H; right. rewrite in_app_iff. right; auto.\n  Qed.\n\n  Lemma removeDirFromTree_the_same: forall d cnt tree,\n      ~ In d (collectDids tree) -> removeDirFromTree tree d cnt = tree.\n  Proof.\n    intros. induction tree using tree_ind2; simpl; auto.\n    rewrite Forall_forall in H0. rm_if.\n    - exfalso. subst. apply H. simpl. left; auto.\n    - f_equal. assert (treeL = map id treeL) by\n          (clear; induction treeL; simpl; [|rewrite IHtreeL at 1]; auto).\n      rewrite H1 at 2.\n      apply map_ext_in. intros. apply H0; auto. unfold id. intro. apply H.\n      simpl. right. apply (subtree_did_in_merge a); auto.\n  Qed.\n\n  Lemma removeDirFromTree_the_same_list: forall d cnt l,\n      ~ In d (flat_map collectDids l) ->\n      map (fun t => removeDirFromTree t d cnt) l = l.\n  Proof.\n    intros. assert (l = map id l) by\n        (clear; induction l; simpl; [|rewrite IHl at 1]; auto).\n    rewrite H0 at 2; clear H0. apply map_ext_in. unfold id. intros.\n    apply removeDirFromTree_the_same. intro; apply H.\n    apply (subtree_did_in_merge a); auto.\n  Qed.\n\n  Lemma removeDirFromTree_map_the_same: forall tl1 tl2 did' treeL' d cnt,\n      NoDup (flat_map collectDids (tl1 ++ Dnode did' treeL' :: tl2)) ->\n      In d (collectDids (Dnode did' treeL')) ->\n      map (fun t : Tree => removeDirFromTree t d cnt)\n          (tl1 ++ Dnode did' treeL' :: tl2) =\n      (tl1 ++ removeDirFromTree (Dnode did' treeL') d cnt :: tl2)%list.\n  Proof.\n    intros. rewrite flat_map_collectDids in H. rewrite map_app, map_cons.\n    rewrite !removeDirFromTree_the_same_list; auto.\n    - apply NoDup_app_r in H. apply NoDup_app_not_in_r with (y := d) in H; auto.\n    - apply NoDup_app_not_in_l with (y := d) in H; auto. rewrite in_app_iff.\n      left; auto.\n  Qed.\n\n  Lemma removeDirFromTree_not_in_tree:\n    forall (fmap : Fid -> FData) (dmap : Did -> DData)\n           (d cnt : Did) (da : DData) (dname: string) (tree : Tree) (path : Path),\n      NoDup (collectDids tree) -> NoDupNameTree fmap dmap tree ->\n      path_in_tree_with_id dmap path tree d ->\n      path_in_tree_with_id dmap (path ++ [dname])%list tree cnt ->\n      ~ path_in_tree (change_d_map dmap cnt da)\n        (path ++ [dname])%list (removeDirFromTree tree d cnt).\n  Proof.\n    intros fmap dmap d cnt da dname. induction tree using tree_ind2; intros.\n    1: inversion H1. rewrite Forall_forall in H.\n    destruct path; simpl in *; inversion H2; subst.\n    - rm_if. clear e. inversion H3. subst. destruct H9 as [did' [treeL' [? [? ?]]]].\n      inversion H6. subst. apply in_split in H4. destruct H4 as [l1 [l2 ?]].\n      subst treeL. rewrite NoDup_cons_iff in H0. destruct H0.\n      rewrite flat_map_collectDids in H4. simpl in H4. apply NoDup_remove_2 in H4.\n      rewrite removeDirFromList_app. simpl. rm_if. clear e.\n      assert (~ In cnt (flat_map collectDids l1)) by\n          (intro; apply H4; rewrite in_app_iff; left; auto).\n      assert (~ In cnt (flat_map collectDids l2)) by\n          (intro; apply H4; rewrite !in_app_iff; right; right; auto).\n      rewrite !removeDirFromList_the_same; auto. intro. inversion H8. subst.\n      destruct H10 as [cnt' [l [? [? ?]]]]. inversion H1. subst.\n      rewrite map_app, map_cons in H17. simpl in H17. apply NoDup_remove_2 in H17.\n      rewrite <- map_app in H17. remember (l1 ++ l2)%list as ll.\n      assert (~ In cnt (flat_map collectDids ll)). {\n        subst ll. rewrite flat_map_concat_map, map_app, concat_app,\n                  <- !flat_map_concat_map. intro. rewrite in_app_iff in H12.\n        destruct H12; [apply H5 | apply H7]; auto.\n      } unfold change_d_map in H10. rm_hif.\n      + subst cnt'. apply H12.\n        apply subtree_did_in_merge with (t := Dnode cnt l); auto. simpl. left; auto.\n      + apply in_split in H9. destruct H9 as [l3 [l4 ?]]. rewrite H9 in H17.\n        apply H17. rewrite map_app, map_cons. simpl. rewrite in_app_iff. right.\n        simpl. left; auto.\n    - destruct H9 as [did' [treeL' [? [? ?]]]]. rm_if.\n      + exfalso. revert e. eapply path_in_tree_nonempty_neq; eauto.\n        intro. inversion H7.\n      + inversion H3. subst. destruct H12 as [d0 [l0 [? [? ?]]]]. inversion H1. subst.\n        assert (Dnode did' treeL' = Dnode d0 l0) by\n            (eapply same_name_the_same_tree; eauto). inversion H9. subst d0 l0.\n        clear H7 H5 H9. specialize (H _ H4 path). intro.\n        inversion H5; subst. clear H2 H3 H5.\n        destruct H9 as [d2 [l2 [? [? ?]]]]. unfold change_d_map in H3.\n        rewrite NoDup_cons_iff in H0.\n        destruct H0. apply in_split in H4. destruct H4 as [tl1 [tl2 ?]]. subst treeL.\n        rewrite removeDirFromTree_map_the_same in H2; auto.\n        2: apply path_in_tree_collectDids in H6; auto.\n        rewrite flat_map_collectDids in H7.\n        assert (NoDup (collectDids (Dnode did' treeL'))) by\n            (apply NoDup_app_r, NoDup_app_l in H7; auto).\n        rewrite Forall_forall in H13.\n        assert (NoDupNameTree fmap dmap (Dnode did' treeL')) by\n            (apply H13; rewrite in_app_iff; right; simpl; left; auto).\n        specialize (H H4 H9 H6 H8).\n        rewrite in_app_iff in H2. Opaque removeDirFromTree. simpl in H2.\n        Transparent removeDirFromTree.\n        assert (removeDirFromTree (Dnode did' treeL') d cnt = Dnode d2 l2 \\/\n                In (Dnode d2 l2) (tl1 ++ tl2)) by\n            (destruct H2 as [? | [? | ?]]; intuition). clear H2.\n        destruct H10. 1: rewrite <- H2 in *; apply H; auto. clear H. rm_hif.\n        * subst d2. clear -H2 H8 H7. apply path_in_tree_collectDids in H8.\n          pose proof H7. apply NoDup_app_not_in_l with (y := cnt) in H7.\n          2: rewrite in_app_iff; left; auto.\n          apply NoDup_app_r, NoDup_app_not_in_r with (y := cnt) in H; auto.\n          assert (~ In cnt (flat_map collectDids (tl1 ++ tl2))). {\n            rewrite flat_map_concat_map, map_app, concat_app,\n            <- !flat_map_concat_map. intro. rewrite in_app_iff in H0.\n            destruct H0; auto.\n          } remember (tl1 ++ tl2)%list as tl. clear Heqtl H7 H. apply in_split in H2.\n          destruct H2 as [tl3 [tl4 ?]]. subst tl. apply H0.\n          rewrite flat_map_collectDids.\n          rewrite !in_app_iff. right; left; simpl; left; auto.\n        * clear -H14 H3 H2. rewrite map_app, map_cons in H14.\n          simpl in H14. apply NoDup_remove_2 in H14. rewrite <- map_app in H14.\n          remember (tl1 ++ tl2)%list as tl. clear tl1 tl2 Heqtl.\n          apply in_split in H2. destruct H2 as [tl1 [tl2 ?]]. subst tl. apply H14.\n          rewrite map_app, map_cons. simpl. rewrite in_app_iff. simpl. intuition.\n  Qed.\n\n  Lemma findDir_path_in_tree_with_id : forall fmap dmap d tree path,\n      NoDupNameTree fmap dmap tree -> path_in_tree_with_id dmap path tree d ->\n      exists l, findDir dmap tree path = Some (Dnode d l).\n  Proof.\n    intros fmap dmap d. induction tree using tree_ind2; intros. 1: inversion H0.\n    rewrite Forall_forall in H. destruct path; inversion H1; subst; simpl.\n    1: (exists treeL; auto). destruct H7 as [did' [treeL' [? [? ?]]]].\n    destruct (find (fun x : Tree => root_eq dmap x s) treeL) eqn:? .\n    - destruct t. 1: exfalso; apply find_some in Heqo; destruct Heqo;\n                    unfold root_eq in H6; inversion H6.\n      apply find_some in Heqo. destruct Heqo. unfold root_eq, DData_eqb in H6.\n      rm_hif. 2: inversion H6. rewrite <- H3 in e. inversion H0; subst.\n      assert (Dnode did' treeL' = Dnode d0 l) by\n          (eapply same_name_the_same_tree; eauto). inversion H3. subst. apply H; auto.\n      rewrite Forall_forall in H11. apply H11; auto.\n    - apply find_none with (x := Dnode did' treeL') in Heqo; auto. exfalso.\n      unfold root_eq, DData_eqb in Heqo. rm_hif; intuition.\n  Qed.\n\n  Definition empty_directory fmap dmap tree path : Prop :=\n    path_in_tree dmap path tree /\\\n    forall name, ~ path_in_tree dmap (path ++ [name])%list tree /\\\n                 ~ file_in_tree fmap dmap path name tree.\n\n  Definition empty_directory_with_id fmap dmap tree path d : Prop :=\n    path_in_tree_with_id dmap path tree d /\\\n    forall name, ~ path_in_tree dmap (path ++ [name])%list tree /\\\n                 ~ file_in_tree fmap dmap path name tree.\n\n  Lemma findDir_empty_directory_with_id: forall fmap dmap d tree path,\n      NoDupNameTree fmap dmap tree -> findDir dmap tree path = Some (Dnode d nil) ->\n      empty_directory_with_id fmap dmap tree path d.\n  Proof.\n    intros. split. apply path_in_tree_with_id_some in H0; auto.\n    revert tree path H H0. induction tree using tree_ind2; intros.\n    1: destruct path; simpl in H0; inversion H0. destruct path; simpl in H1.\n    - inversion H1. subst. simpl.\n      split; intro; inversion H2; subst;\n        [destruct H4 as [? [? [? ?]]] |\n         rewrite Exists_exists in H6; destruct H6 as [? [? ?]]]; inversion H3.\n    - rewrite Forall_forall in H. rm_hmatch. 2: inversion H1. destruct t.\n      1: exfalso; apply find_some in Heqo; destruct Heqo;\n        unfold root_eq in H3; inversion H3.\n      apply find_some in Heqo. destruct Heqo. unfold root_eq, DData_eqb in H3. rm_hif.\n      2: inversion H3. simpl. inversion H0. subst. rewrite Forall_forall in H8.\n      split; intro; inversion H4; subst; [|rename H10 into H6];\n        destruct H6 as [did' [treeL' [? [? ?]]]];\n        assert (Dnode d0 l = Dnode did' treeL') by\n            (eapply same_name_the_same_tree; eauto); inversion H10; subst; clear H10;\n          specialize (H _ H2 path (H8 _ H2) H1 name); destruct H; auto.\n  Qed.\n\n  Lemma removeDirFromTree_the_same_Fids: forall fmap dmap tree path name pid d,\n      NoDup (collectDids tree) -> NoDupNameTree fmap dmap tree ->\n      path_in_tree_with_id dmap path tree pid ->\n      empty_directory_with_id fmap dmap tree (path ++ [name])%list d ->\n      collectFids (removeDirFromTree tree pid d) = collectFids tree.\n  Proof.\n    intros fmap dmap tree path name pid d; revert tree path.\n    induction tree using tree_ind2; intros; simpl; auto. rm_if.\n    - simpl. subst did. destruct path.\n      + simpl in *. destruct H3. inversion H3; subst.\n        destruct H10 as [did' [treeL' [? [? ?]]]]. inversion H7; subst.\n        destruct treeL'.\n        * apply in_split in H5. destruct H5 as [l1 [l2 ?]]. subst treeL.\n          rewrite removeDirFromList_app. simpl. rm_if. 2: exfalso; auto. clear e.\n          apply NoDup_cons_iff in H0. destruct H0. rewrite flat_map_collectDids in H5.\n          simpl in H5. apply NoDup_remove_2 in H5. rewrite flat_map_collectFids.\n          simpl. rewrite !removeDirFromList_the_same;\n                   [|intro; apply H5; rewrite in_app_iff; intuition..].\n          rewrite flat_map_concat_map, map_app, concat_app,\n          <- !flat_map_concat_map; auto.\n        * exfalso. destruct t.\n          -- destruct (H4 (fmap f).(nameF)). apply H8. constructor.\n             exists d, (Fnode f :: treeL'). intuition. constructor.\n             rewrite Exists_exists. exists (Fnode f). simpl. intuition.\n             constructor; auto.\n          -- destruct (H4 (dmap d0).(nameD)). apply H6. constructor.\n             exists d, (Dnode d0 l :: treeL'). intuition. constructor. exists d0, l.\n             intuition. constructor.\n      + exfalso. apply path_in_tree_nonempty_neq in H2; auto. intro; inversion H4.\n    - destruct path; inversion H2; subst. 1: exfalso; auto.\n      destruct H9 as [did' [treeL' [? [? ?]]]]. clear H2. destruct H3. simpl in *.\n      inversion H2; subst. destruct H12 as [dd [ll [? [? ?]]]]. inversion H1; subst.\n      assert (Dnode did' treeL' = Dnode dd ll) by\n          (eapply same_name_the_same_tree; eauto). inversion H9. subst dd ll. clear H9.\n      rewrite NoDup_cons_iff in H0. destruct H0. apply in_split in H5.\n      destruct H5 as [l1 [l2 ?]]. subst treeL.\n      rewrite removeDirFromTree_map_the_same; auto.\n      2: apply path_in_tree_collectDids in H6; auto.\n      rewrite Forall_forall in H. rewrite !flat_map_collectFids.\n      rewrite H with (path := path); auto.\n      + rewrite flat_map_collectDids in H9.\n        apply NoDup_app_r, NoDup_app_l in H9; auto.\n      + rewrite Forall_forall in H13. apply H13. auto.\n      + split; auto. intros. specialize (H3 name0). destruct H3.\n        split; intro; [apply H3 | apply H5]; constructor;\n          exists did', treeL'; intuition.\n  Qed.\n\n  Lemma removeDirFromTree_Permutation: forall fmap dmap tree path name pid d,\n      NoDup (collectDids tree) -> NoDupNameTree fmap dmap tree ->\n      path_in_tree_with_id dmap path tree pid ->\n      empty_directory_with_id fmap dmap tree (path ++ [name])%list d ->\n      Permutation (d :: collectDids (removeDirFromTree tree pid d)) (collectDids tree).\n  Proof.\n    intros fmap dmap tree path name pid d; revert tree path.\n    induction tree using tree_ind2; intros; simpl; auto.\n    1: inversion H1. rm_if; simpl.\n    - apply Permutation_trans with\n          (did :: d :: flat_map collectDids (removeDirFromList treeL d)); constructor.\n      subst did. destruct path.\n      + simpl in *. destruct H3. inversion H3; subst.\n        destruct H10 as [did' [treeL' [? [? ?]]]]. inversion H7; subst.\n        destruct treeL'.\n        * apply in_split in H5. destruct H5 as [l1 [l2 ?]]. subst treeL.\n          rewrite removeDirFromList_app. simpl. rm_if. 2: exfalso; auto. clear e.\n          apply NoDup_cons_iff in H0. destruct H0. rewrite flat_map_collectDids in H5.\n          simpl in H5. apply NoDup_remove_2 in H5. rewrite flat_map_collectDids.\n          simpl. rewrite !removeDirFromList_the_same;\n                   [|intro; apply H5; rewrite in_app_iff; intuition..].\n          rewrite flat_map_concat_map, map_app, concat_app, <- !flat_map_concat_map.\n          apply Permutation_cons_app. auto.\n        * exfalso. destruct t.\n          -- destruct (H4 (fmap f).(nameF)). apply H8. constructor.\n             exists d, (Fnode f :: treeL'). intuition. constructor.\n             rewrite Exists_exists. exists (Fnode f). simpl. intuition.\n             constructor; auto.\n          -- destruct (H4 (dmap d0).(nameD)). apply H6. constructor.\n             exists d, (Dnode d0 l :: treeL'). intuition. constructor. exists d0, l.\n             intuition. constructor.\n      + exfalso. apply path_in_tree_nonempty_neq in H2; auto. intro; inversion H4.\n    - apply Permutation_trans with\n          (did :: d :: flat_map collectDids\n               (map (fun t : Tree => removeDirFromTree t pid d) treeL)); constructor.\n      destruct path; inversion H2; subst. 1: exfalso; auto.\n      destruct H9 as [did' [treeL' [? [? ?]]]]. clear H2. destruct H3. simpl in *.\n      inversion H2; subst. destruct H12 as [dd [ll [? [? ?]]]]. inversion H1; subst.\n      assert (Dnode did' treeL' = Dnode dd ll) by\n          (eapply same_name_the_same_tree; eauto). inversion H9. subst dd ll. clear H9.\n      rewrite NoDup_cons_iff in H0. destruct H0. apply in_split in H5.\n      destruct H5 as [l1 [l2 ?]]. subst treeL.\n      rewrite removeDirFromTree_map_the_same; auto.\n      2: apply path_in_tree_collectDids in H6; auto.\n      rewrite Forall_forall in H. rewrite !flat_map_collectDids.\n      transitivity\n        (flat_map collectDids l1 ++\n                  d :: collectDids (removeDirFromTree (Dnode did' treeL') pid d) ++\n                  flat_map collectDids l2)%list. 1: apply Permutation_cons_app; auto.\n      apply Permutation_app_head. rewrite app_comm_cons. apply Permutation_app_tail.\n      rewrite H with (path := path); auto.\n      + rewrite flat_map_collectDids in H9.\n        apply NoDup_app_r, NoDup_app_l in H9; auto.\n      + rewrite Forall_forall in H13. apply H13. auto.\n      + split; auto. intros. specialize (H3 name0). destruct H3.\n        split; intro; [apply H3 | apply H5]; constructor;\n          exists did', treeL'; intuition.\n  Qed.\n\n  Lemma removeDirFromTree_NoDupNameTree:\n    forall (fmap : Fid -> FData) (dmap : Did -> DData) (d cnt : Did)\n           (da : DData) (dname: string) (tree : Tree) (path : Path),\n      NoDup (collectDids tree) -> NoDupNameTree fmap dmap tree ->\n      path_in_tree_with_id dmap path tree d ->\n      path_in_tree_with_id dmap (path ++ [dname])%list tree cnt ->\n      NoDupNameTree fmap (change_d_map dmap cnt da) (removeDirFromTree tree d cnt).\n  Proof.\n    intros fmap dmap d cnt da dname. induction tree using tree_ind2; intros.\n    1: inversion H1. rewrite Forall_forall in H.\n    destruct path; simpl in *; inversion H2; subst.\n    - rm_if. 2: exfalso; auto. clear e. inversion H3. subst.\n      destruct H9 as [did' [treeL' [? [? ?]]]].\n      inversion H6. subst. apply in_split in H4. destruct H4 as [l1 [l2 ?]].\n      subst treeL. rewrite NoDup_cons_iff in H0. destruct H0.\n      rewrite flat_map_collectDids in H4. simpl in H4. apply NoDup_remove_2 in H4.\n      rewrite removeDirFromList_app. simpl. rm_if. 2: exfalso; auto. clear e.\n      assert (~ In cnt (flat_map collectDids l1)) by\n          (intro; apply H4; rewrite in_app_iff; left; auto).\n      assert (~ In cnt (flat_map collectDids l2)) by\n          (intro; apply H4; rewrite !in_app_iff; right; right; auto).\n      rewrite !removeDirFromList_the_same; auto.\n      assert (~ In cnt (flat_map collectDids (l1 ++ l2))). {\n        rewrite flat_map_concat_map, map_app, concat_app,\n        <- !flat_map_concat_map. intro. rewrite in_app_iff in H8.\n        destruct H8; [apply H5 | apply H7]; auto.\n      } clear -H1 H8. inversion H1. subst. constructor.\n      + rewrite Forall_forall in *. intros. apply change_d_map_NoDupNameTree.\n        * intro. apply H8; apply subtree_did_in_merge with x; auto.\n        * apply H4. rewrite in_app_iff in *. simpl. intuition.\n      + rewrite <- treeName_eq_treeL; auto. rewrite map_app in *.\n        rewrite map_cons in H5. apply NoDup_remove_1 in H5; auto.\n    - destruct H9 as [did' [treeL' [? [? ?]]]]. rm_if.\n      + exfalso. revert e. eapply path_in_tree_nonempty_neq; eauto.\n        intro. inversion H7.\n      + inversion H3. subst. destruct H12 as [d0 [l0 [? [? ?]]]]. inversion H1. subst.\n        assert (Dnode did' treeL' = Dnode d0 l0) by\n            (eapply same_name_the_same_tree; eauto). inversion H9. subst d0 l0.\n        clear H7 H5 H9. specialize (H _ H4 path). rewrite NoDup_cons_iff in H0.\n        destruct H0. apply in_split in H4. destruct H4 as [tl1 [tl2 ?]]. subst treeL.\n        rewrite removeDirFromTree_map_the_same; auto.\n        2: apply path_in_tree_collectDids in H6; auto.\n        rewrite flat_map_collectDids in H5.\n        assert (NoDup (collectDids (Dnode did' treeL'))) by\n            (apply NoDup_app_r, NoDup_app_l in H5; auto).\n        rewrite Forall_forall in H13.\n        assert (NoDupNameTree fmap dmap (Dnode did' treeL')) by\n            (apply H13; rewrite in_app_iff; right; simpl; left; auto).\n        specialize (H H4 H7 H6 H8). assert (HS: did' <> cnt) by\n            (apply path_in_tree_nonempty_neq in H8; auto; intro s;\n             destruct path; inversion s).\n        apply path_in_tree_collectDids in H8.\n        assert (~ In cnt (flat_map collectDids tl1)). {\n          apply NoDup_app_not_in_l with (y := cnt) in H5; auto.\n          rewrite in_app_iff. left; auto.\n        } assert (~ In cnt (flat_map collectDids tl2)). {\n          apply NoDup_app_r, NoDup_app_not_in_r with (y := cnt) in H5; auto.\n        } constructor.\n        * rewrite Forall_forall. intros. rewrite in_app_iff in H11.\n          Opaque removeDirFromTree. simpl in H11. Transparent removeDirFromTree.\n          assert (removeDirFromTree (Dnode did' treeL') d cnt = x \\/ In x (tl1 ++ tl2))\n            by (destruct H11 as [? | [? | ?]]; intuition). clear H11.\n          destruct H12. 1: rewrite <- H11 in *; auto. apply change_d_map_NoDupNameTree.\n          -- intro. rewrite in_app_iff in H11.\n             destruct H11; [apply H9 | apply H10]; eapply subtree_did_in_merge; eauto.\n          -- apply H13. rewrite in_app_iff in *. simpl. intuition.\n        * rewrite map_app, map_cons in *. rewrite <- !treeName_eq_treeL; auto.\n          simpl in *; rm_if; simpl; unfold change_d_map; rm_if; exfalso; auto.\n  Qed.\n\n  Lemma fs_rmdir_ok: forall (path : Path) (fs : FSState) (err : ErrCode)\n                            (postFS : FSState),\n      good_file_system (fsFS fs) -> (err, postFS) = fs_rmdir path fs ->\n      (path = nil /\\ err = eInval /\\ postFS = fs) \\/\n      (path <> nil /\\ ~ path_in_tree (dMapFS fs) path (layoutFS fs) /\\\n       err = eNoEnt /\\ postFS = fs) \\/\n      (path <> nil /\\\n       (exists name, path_in_tree (dMapFS fs) (path ++ [name])%list (layoutFS fs) \\/\n                     file_in_tree (fMapFS fs) (dMapFS fs) path name (layoutFS fs)) /\\\n       err = eNotEmpty /\\ postFS = fs) \\/\n      (path <> nil /\\\n       (exists pid, path_in_tree_with_id\n                      (dMapFS fs) (removelast path) (layoutFS fs) pid /\\\n                    (dMapFS fs pid).(metaD).(writable) = false) /\\\n       path_in_tree (dMapFS fs) path (layoutFS fs) /\\ err = eAcces /\\ postFS = fs) \\/\n      (path <> nil /\\ path_in_tree (dMapFS fs) path (layoutFS fs) /\\\n       (exists pid, path_in_tree_with_id\n                      (dMapFS fs) (removelast path) (layoutFS fs) pid /\\\n                    (dMapFS fs pid).(metaD).(writable) = true) /\\ err <> eSucc /\\\n       fsFS postFS = fsFS fs /\\ logFS postFS = Call_VRmdir path err :: logFS fs) \\/\n      ((exists did,\n           empty_directory_with_id (fMapFS fs) (dMapFS fs) (layoutFS fs) path did /\\\n           dMapFS postFS did = Build_DData \"\" fff /\\\n           forall d, d <> did -> dMapFS postFS d = dMapFS fs d) /\\\n       (exists pid, path_in_tree_with_id\n                      (dMapFS fs) (removelast path) (layoutFS fs) pid /\\\n                    (dMapFS fs pid).(metaD).(writable) = true) /\\ err = eSucc /\\\n       logFS postFS = Call_VRmdir path eSucc :: logFS fs /\\\n       openhandleFS fs = openhandleFS postFS /\\ vmFS fs = vmFS postFS /\\\n       fMapFS fs = fMapFS postFS /\\ fCntFS fs = fCntFS postFS /\\\n       dCntFS fs = dCntFS postFS /\\ path <> nil /\\\n       mmap_handles (fsFS fs) = mmap_handles (fsFS postFS) /\\\n       mmap_memory (fsFS fs) = mmap_memory (fsFS postFS) /\\\n       ~ path_in_tree (dMapFS postFS) path (layoutFS postFS) /\\\n       good_file_system (fsFS postFS)).\n  Proof.\n    intros. unfold fs_rmdir in H0. simpl in H0. destruct path eqn:? .\n    1: left; inversion H0; auto. right.\n    assert (path <> nil) by (rewrite Heqp; intro S; inversion S).\n    rewrite <- Heqp in *. clear s p Heqp. rm_hmatch.\n    - right. destruct t. 1: exfalso; revert Heqo; apply findDir_not_fnode. destruct l.\n      pose proof Heqo. rename H2 into HS.\n      + right. apply path_in_tree_with_id_some in Heqo.\n        assert (path_in_tree (d_map (fst fs)) path (layout (fst fs))). {\n          rewrite path_in_tree_with_id_eq. exists d; auto.\n        } rm_hmatch.\n        * destruct t. 1: exfalso; revert Heqo0; apply findDir_not_fnode.\n          apply path_in_tree_with_id_some in Heqo0. rm_hmatch.\n          -- right. destruct fs. simpl in H0.\n             unfold fMapFS, dMapFS, layoutFS. simpl. rm_hif.\n             ++ left. inversion H0. simpl in *. intuition. exists d0; intuition.\n             ++ right. simpl in *. inversion H0. subst postFS. simpl. rewrite e.\n                assert (HQ: empty_directory_with_id\n                              (f_map f) (d_map f) (layout f) path d) by\n                    (destruct H; apply findDir_empty_directory_with_id; auto).\n                clear H0. apply app_removelast_last with (d := EmptyString) in H1.\n                remember (removelast path) as p. remember (last path \"\") as a.\n                clear Heqa Heqp. subst path. intuition.\n                ** exists d. intuition; unfold change_d_map; rm_if; exfalso; auto.\n                ** exists d0; intuition.\n                ** destruct p; inversion H0.\n                ** revert H0. destruct H as [? [? ?]].\n                   eapply removeDirFromTree_not_in_tree; eauto.\n                ** destruct H as [? [? [? [? [? [? [? [? ?]]]]]]]].\n                   split; [|split; [|split; [|split; [|split; [|split; [|split]]]]]];\n                     simpl; auto.\n                   --- eapply removeDirFromTree_NoDupNameTree; eauto.\n                   --- pose proof (removeDirFromTree_Permutation\n                                     _ _ _ _ _ _ _ H0 H Heqo0 HQ).\n                       symmetry in H10. apply Permutation_NoDup in H10; auto.\n                       rewrite NoDup_cons_iff in H10. destruct H10; auto.\n                   --- erewrite removeDirFromTree_the_same_Fids; eauto.\n                   --- pose proof (removeDirFromTree_Permutation\n                                     _ _ _ _ _ _ _ H0 H Heqo0 HQ). intros.\n                       apply Permutation_in with (x := el) in H10; auto.\n                       simpl. right; auto.\n                   --- erewrite removeDirFromTree_the_same_Fids; eauto.\n                   --- unfold isDir in H7. destruct H7 as [dd [ll ?]]. rewrite H7.\n                       simpl. rm_if; apply DnodeIsDir.\n          -- left. inversion H0. intuition. exists d0. intuition.\n        * destruct H. apply path_in_tree_none in Heqo0; auto.\n          apply path_in_tree_removelast in H2. exfalso; intuition.\n      + left. inversion H0. intuition. destruct t.\n        * exists (fMapFS fs f).(nameF). right.\n          apply (findDir_file_in_tree _ _ d (Fnode f :: l) f); auto. simpl; left; auto.\n        * exists (dMapFS fs d0).(nameD). left.\n          apply (findDir_path_in_tree _ d (Dnode d0 l0 :: l) d0 l0); simpl; intuition.\n    - left. destruct H. apply path_in_tree_none in Heqo; auto. inversion H0; auto.\n  Qed.\n\n  Lemma file_in_tree_path_in_tree:\n    forall fmap dmap fname tree path,\n      file_in_tree fmap dmap path fname tree -> path_in_tree dmap path tree.\n  Proof.\n    intros fmap dmap fname. induction tree using tree_ind2; intros. 1: inversion H.\n    rewrite Forall_forall in H. destruct path. 1: constructor.\n    inversion H0; subst. destruct H4 as [did' [treeL' [? [? ?]]]].\n    constructor. exists did', treeL'. intuition.\n  Qed.\n\n  Lemma removeFnodeFromList_app: forall l1 l2 fid,\n      removeFnodeFromList (l1 ++ l2) fid =\n      (removeFnodeFromList l1 fid ++ removeFnodeFromList l2 fid)%list.\n  Proof.\n    induction l1; intros; simpl; auto. destruct a.\n    - rm_if. simpl. rewrite IHl1. auto.\n    - simpl. f_equal. apply IHl1.\n  Qed.\n\n  Lemma removeFnodeFromList_the_same: forall fid l,\n      ~ In fid (flat_map collectFids l) -> removeFnodeFromList l fid = l.\n  Proof.\n    intros. induction l; simpl; auto. destruct a.\n    - rm_if. 1: exfalso; subst; apply H; simpl; left; auto. f_equal. apply IHl.\n      intro. apply H. simpl. right; auto.\n    - f_equal. apply IHl. intro; apply H; simpl. rewrite in_app_iff. right; auto.\n  Qed.\n\n  Lemma removeFnodeFromTree_the_same: forall d fId tree,\n      ~ In fId (collectFids tree) -> removeFnodeFromTree tree d fId = tree.\n  Proof.\n    intros. induction tree using tree_ind2; simpl; auto.\n    rewrite Forall_forall in H0. rm_if.\n    - subst. f_equal. apply removeFnodeFromList_the_same. simpl in H. auto.\n    - f_equal. assert (treeL = map id treeL) by\n          (clear; induction treeL; simpl; [|rewrite IHtreeL at 1]; auto).\n      rewrite H1 at 2. apply map_ext_in. intros. apply H0; auto. unfold id. intro.\n      apply H. simpl. rewrite in_flat_map. exists a. intuition.\n  Qed.\n\n  Lemma removeFnodeFromTree_the_same_list: forall d fId l,\n      ~ In fId (flat_map collectFids l) ->\n      map (fun t => removeFnodeFromTree t d fId) l = l.\n  Proof.\n    intros. assert (l = map id l) by\n        (clear; induction l; simpl; [|rewrite IHl at 1]; auto).\n    rewrite H0 at 2; clear H0. apply map_ext_in. unfold id. intros.\n    apply removeFnodeFromTree_the_same. intro; apply H.\n    rewrite in_flat_map; exists a; intuition.\n  Qed.\n\n  Lemma removeFnodeFromTree_map_the_same: forall tl1 tl2 did' treeL' d fId,\n      NoDup (flat_map collectFids (tl1 ++ Dnode did' treeL' :: tl2)) ->\n      In fId (collectFids (Dnode did' treeL')) ->\n      map (fun t : Tree => removeFnodeFromTree t d fId)\n          (tl1 ++ Dnode did' treeL' :: tl2) =\n      (tl1 ++ removeFnodeFromTree (Dnode did' treeL') d fId :: tl2)%list.\n  Proof.\n    intros. rewrite flat_map_collectFids in H. rewrite map_app, map_cons.\n    rewrite !removeFnodeFromTree_the_same_list; auto.\n    - apply NoDup_app_r in H. apply NoDup_app_not_in_r with (y := fId) in H; auto.\n    - apply NoDup_app_not_in_l with (y := fId) in H; auto. rewrite in_app_iff.\n      left; auto.\n  Qed.\n\n  Lemma file_in_tree_collectFids: forall fmap dmap path name t d,\n      file_in_tree_with_id fmap dmap path name t d -> In d (collectFids t).\n  Proof.\n    intros. revert t path H. induction t using tree_ind2; intros. 1: inversion H.\n    destruct path; inversion H0; subst.\n    - simpl. rewrite in_flat_map. exists (Fnode d). simpl. intuition.\n    - destruct H7 as [did' [treeL' [? [? ?]]]]. simpl. rewrite Forall_forall in H.\n      rewrite in_flat_map. specialize (H _ H1 _ H3). exists (Dnode did' treeL').\n      intuition.\n  Qed.\n\n  Lemma removeFnodeFromTree_not_in_tree:\n    forall fmap dmap d fId fa fname tree path,\n      NoDup (collectFids tree) -> NoDup (collectDids tree) ->\n      NoDupNameTree fmap dmap tree -> path_in_tree_with_id dmap path tree d ->\n      file_in_tree_with_id fmap dmap path fname tree fId ->\n      ~ file_in_tree (change_f_map fmap fId fa) dmap\n        path fname (removeFnodeFromTree tree d fId).\n  Proof.\n    intros fmap dmap d fId fa fname. induction tree using tree_ind2; intros.\n    1: inversion H2. rewrite Forall_forall in H.\n    destruct path; simpl in *; inversion H3; subst.\n    - rm_if. clear e. inversion H4. subst. apply in_split in H7.\n      destruct H7 as [l1 [l2 ?]]. subst treeL. rewrite flat_map_collectFids in H0.\n      simpl in H0. apply NoDup_remove_2 in H0.\n      rewrite removeFnodeFromList_app. simpl. rm_if. clear e.\n      rewrite !removeFnodeFromList_the_same;\n        [|intro; apply H0; rewrite in_app_iff; intuition ..].\n      clear H. intro. inversion H. subst. rewrite Exists_exists in H8.\n      destruct H8 as [x [? ?]]. inversion H6. subst. inversion H2. subst.\n      rewrite map_app, map_cons in H13. simpl in H13. apply NoDup_remove_2 in H13.\n      rewrite <- map_app in H13. clear -H0 H7 H13 H5.\n      rewrite !flat_map_concat_map, <- concat_app, <- map_app,\n      <- flat_map_concat_map in H0. remember (l1 ++ l2)%list as ll. clear l1 l2 Heqll.\n      apply in_split in H5. destruct H5 as [l1 [l2 ?]].\n      subst ll. unfold change_f_map in H7. rm_hif.\n      * subst. rewrite flat_map_collectFids in H0. simpl in H0. apply H0.\n        rewrite in_app_iff. simpl. right; left; auto.\n      * apply H13. rewrite map_app, map_cons. simpl. rewrite in_app_iff. simpl.\n        right; left; auto.\n    - destruct H10 as [did' [treeL' [? [? ?]]]]. rm_if.\n      + exfalso. revert e. eapply path_in_tree_nonempty_neq; eauto.\n        intro. inversion H8.\n      + inversion H4. subst. destruct H14 as [d0 [l0 [? [? ?]]]]. inversion H2. subst.\n        assert (Dnode did' treeL' = Dnode d0 l0) by\n            (eapply same_name_the_same_tree; eauto). inversion H10. subst d0 l0.\n        clear H8 H6 H10. intro. inversion H6. subst. clear H3 H4 H6.\n        destruct H12 as [dd [ll [? [? ?]]]]. rewrite NoDup_cons_iff in H1. destruct H1.\n        specialize (H _ H5 path). apply in_split in H5. destruct H5 as [l1 [l2 ?]].\n        subst treeL. rewrite removeFnodeFromTree_map_the_same in H3; auto.\n        2: apply file_in_tree_collectFids in H9; auto. rewrite in_app_iff in H3.\n        Opaque removeFnodeFromTree. simpl in H3. Transparent removeFnodeFromTree.\n        assert (removeFnodeFromTree (Dnode did' treeL') d fId = Dnode dd ll \\/\n                In (Dnode dd ll) (l1 ++ l2)) by\n            (destruct H3 as [? | [? | ?]]; intuition). clear H3. destruct H5.\n        * rewrite H3 in H. apply H; auto.\n          -- clear -H0. rewrite flat_map_collectFids in H0.\n             apply NoDup_app_r, NoDup_app_l in H0; auto.\n          -- clear -H8. rewrite flat_map_collectDids in H8.\n             apply NoDup_app_r, NoDup_app_l in H8; auto.\n          -- rewrite Forall_forall in H14. apply H14. rewrite in_app_iff. simpl.\n             right; left; auto.\n        * clear -H15 H4 H3. rewrite map_app, map_cons in H15.\n          simpl in H15. apply NoDup_remove_2 in H15. rewrite <- map_app in H15.\n          remember (l1 ++ l2)%list as tl. clear l1 l2 Heqtl.\n          apply in_split in H3. destruct H3 as [tl1 [tl2 ?]]. subst tl. apply H15.\n          rewrite map_app, map_cons. simpl. rewrite in_app_iff. simpl. intuition.\n  Qed.\n\n  Lemma removeFnodeFromTree_the_same_Dids: forall tree d fId,\n      collectDids (removeFnodeFromTree tree d fId) = collectDids tree.\n  Proof.\n    induction tree using tree_ind2; intros; simpl; auto.\n    rewrite Forall_forall in H. rm_if; simpl.\n    - subst. f_equal. clear. induction treeL; simpl; auto. destruct a. 1: rm_if.\n      simpl. f_equal. f_equal. auto.\n    - f_equal. rewrite !flat_map_concat_map, map_map. f_equal. apply map_ext_in. auto.\n  Qed.\n\n  Lemma removeFnodeFromTree_Permutation:\n    forall fmap dmap d fId fname tree path,\n      NoDup (collectFids tree) -> NoDup (collectDids tree) ->\n      NoDupNameTree fmap dmap tree -> path_in_tree_with_id dmap path tree d ->\n      file_in_tree_with_id fmap dmap path fname tree fId ->\n      Permutation (fId :: collectFids (removeFnodeFromTree tree d fId))\n                  (collectFids tree).\n  Proof.\n    intros fmap dmap d fId fname. induction tree using tree_ind2; intros.\n    1: inversion H2. rewrite Forall_forall in H.\n    destruct path; simpl in *; inversion H3; subst.\n    - rm_if. 2: exfalso; auto. clear e. inversion H4. subst. apply in_split in H7.\n      destruct H7 as [l1 [l2 ?]]. subst treeL. rewrite flat_map_collectFids in H0.\n      simpl in H0. apply NoDup_remove_2 in H0. rewrite removeFnodeFromList_app. simpl.\n      rm_if. 2: exfalso; auto. rewrite !removeFnodeFromList_the_same;\n                                 [|intro; apply H0; rewrite in_app_iff; intuition ..].\n      clear H. rewrite flat_map_collectFids. simpl. rewrite flat_map_concat_map at 1.\n      rewrite map_app, concat_app, <- !flat_map_concat_map. apply Permutation_middle.\n    - destruct H10 as [did' [treeL' [? [? ?]]]]. rm_if.\n      + exfalso. revert e. eapply path_in_tree_nonempty_neq; eauto.\n        intro. inversion H8.\n      + inversion H4. subst. destruct H14 as [d0 [l0 [? [? ?]]]]. inversion H2. subst.\n        assert (Dnode did' treeL' = Dnode d0 l0) by\n            (eapply same_name_the_same_tree; eauto). inversion H10. subst d0 l0.\n        clear H8 H6 H10. rewrite NoDup_cons_iff in H1. destruct H1.\n        specialize (H _ H5 path). apply in_split in H5. destruct H5 as [l1 [l2 ?]].\n        subst treeL. rewrite removeFnodeFromTree_map_the_same; auto.\n        2: apply file_in_tree_collectFids in H9; auto.\n        Opaque removeFnodeFromTree. simpl. Transparent removeFnodeFromTree.\n        rewrite !flat_map_collectFids. rewrite app_comm_cons. rewrite !app_assoc.\n        apply Permutation_app_tail. rewrite <- app_comm_cons.\n        remember (collectFids (removeFnodeFromTree (Dnode did' treeL') d fId)) as l3.\n        transitivity (flat_map collectFids l1 ++ fId :: l3)%list.\n        1: apply Permutation_middle. apply Permutation_app_head. apply H; auto.\n        * clear -H0. rewrite flat_map_collectFids in H0.\n          apply NoDup_app_r, NoDup_app_l in H0; auto.\n        * clear -H6. rewrite flat_map_collectDids in H6.\n          apply NoDup_app_r, NoDup_app_l in H6; auto.\n        * rewrite Forall_forall in H14. apply H14. rewrite in_app_iff. simpl.\n          right; left; auto.\n  Qed.\n\n  Lemma removeFnodeFromTree_NoDupNameTree:\n    forall fmap dmap d fId fa fname tree path,\n      NoDup (collectFids tree) -> NoDup (collectDids tree) ->\n      NoDupNameTree fmap dmap tree -> path_in_tree_with_id dmap path tree d ->\n      file_in_tree_with_id fmap dmap path fname tree fId ->\n      NoDupNameTree (change_f_map fmap fId fa) dmap (removeFnodeFromTree tree d fId).\n  Proof.\n    intros fmap dmap d fId fa fname. induction tree using tree_ind2; intros.\n    1: inversion H2. rewrite Forall_forall in H.\n    destruct path; simpl in *; inversion H3; subst.\n    - rm_if. 2: exfalso; auto. clear e. inversion H4. subst. apply in_split in H7.\n      destruct H7 as [l1 [l2 ?]]. subst treeL. rewrite flat_map_collectFids in H0.\n      simpl in H0. apply NoDup_remove_2 in H0.\n      rewrite removeFnodeFromList_app. simpl. rm_if. 2: exfalso; auto. clear e.\n      rewrite !removeFnodeFromList_the_same;\n        [|intro; apply H0; rewrite in_app_iff; intuition ..]. clear H.\n      inversion H2. subst. rewrite !flat_map_concat_map, <- concat_app, <- map_app,\n                           <- flat_map_concat_map in H0. constructor.\n      + rewrite Forall_forall in *. intros. apply change_f_map_NoDupNameTree.\n        * intro. apply H0. rewrite in_flat_map. exists x; auto.\n        * apply H8. rewrite in_app_iff in *. simpl. intuition.\n      + rewrite <- treeName_eq_treeL'; auto. rewrite map_app in *. simpl in H9.\n        apply NoDup_remove_1 in H9. auto.\n    - destruct H10 as [did' [treeL' [? [? ?]]]]. rm_if.\n      + exfalso. revert e. eapply path_in_tree_nonempty_neq; eauto.\n        intro. inversion H8.\n      + inversion H4. subst. destruct H14 as [d0 [l0 [? [? ?]]]]. inversion H2. subst.\n        assert (Dnode did' treeL' = Dnode d0 l0) by\n            (eapply same_name_the_same_tree; eauto). inversion H10. subst d0 l0.\n        clear H8 H6 H10. rewrite NoDup_cons_iff in H1. destruct H1.\n        specialize (H _ H5 path). apply in_split in H5. destruct H5 as [l1 [l2 ?]].\n        pose proof H9. rename H8 into HS. apply file_in_tree_collectFids in H9.\n        subst treeL. rewrite removeFnodeFromTree_map_the_same; auto.\n        rewrite flat_map_collectFids in H0.\n        assert (~ In fId (flat_map collectFids l1)). {\n          apply NoDup_app_not_in_l with (y := fId) in H0; auto.\n          rewrite in_app_iff; intuition.\n        } assert (~ In fId (flat_map collectFids l2)). {\n          apply NoDup_app_r, NoDup_app_not_in_r with (y := fId) in H0; auto.\n        } constructor.\n        * rewrite Forall_forall in *. intros. rewrite in_app_iff in H10.\n          Opaque removeFnodeFromTree. simpl in H10. Transparent removeFnodeFromTree.\n          assert (removeFnodeFromTree (Dnode did' treeL') d fId = x \\/\n                  In x (l1 ++ l2)) by (destruct H10 as [? | [? | ?]]; intuition).\n          clear H10. destruct H11.\n          -- subst x. apply H; auto.\n             ++ clear -H0. apply NoDup_app_r, NoDup_app_l in H0; auto.\n             ++ clear -H6. rewrite flat_map_collectDids in H6.\n                apply NoDup_app_r, NoDup_app_l in H6; auto.\n             ++ apply H14. rewrite in_app_iff. simpl. right; left; auto.\n          -- apply change_f_map_NoDupNameTree.\n             ++ intro. rewrite in_app_iff in H10.\n                destruct H10; [apply H5 | apply H8];\n                  rewrite in_flat_map; exists x; intuition.\n             ++ apply H14. rewrite in_app_iff in *. simpl; intuition.\n        * rewrite map_app, map_cons in *. rewrite <- !treeName_eq_treeL'; auto.\n          simpl in *; rm_if; subst d; simpl; auto.\n  Qed.\n\n  Lemma fs_remove_ok: forall (path : Path) (fname : string)\n                             (fs : FSState) (err : ErrCode) (postFS : FSState),\n      good_file_system (fsFS fs) -> (err, postFS) = fs_remove (path, fname) fs ->\n      (fname = EmptyString /\\ err = eBadName /\\ postFS = fs) \\/\n      (~ file_in_tree (fMapFS fs) (dMapFS fs) path fname (layoutFS fs) /\\\n       err = eNoEnt /\\ fs = postFS) \\/\n      (file_in_tree (fMapFS fs) (dMapFS fs) path fname (layoutFS fs) /\\\n       (exists did, path_in_tree_with_id (dMapFS fs) path (layoutFS fs) did /\\\n                    ((dMapFS fs) did).(metaD).(writable) = false) /\\\n       err = eAcces /\\ fs = postFS) \\/\n      (file_in_tree (fMapFS fs) (dMapFS fs) path fname (layoutFS fs) /\\\n       (exists did, path_in_tree_with_id (dMapFS fs) path (layoutFS fs) did /\\\n                    ((dMapFS fs) did).(metaD).(writable) = true) /\\\n       err <> eSucc /\\ fsFS fs = fsFS postFS /\\\n       logFS postFS = Call_VRemove path fname err :: logFS fs) \\/\n      ((exists fId, file_in_tree_with_id (fMapFS fs) (dMapFS fs)\n                                         path fname (layoutFS fs) fId /\\\n                    fMapFS postFS fId = Build_FData \"\" (Build_Meta fff O) nil /\\\n                    (forall id, id <> fId -> fMapFS fs id = fMapFS postFS id)) /\\\n       (exists did, path_in_tree_with_id (dMapFS fs) path (layoutFS fs) did /\\\n                    ((dMapFS fs) did).(metaD).(writable) = true) /\\ err = eSucc /\\\n       logFS postFS = Call_VRemove path fname eSucc :: logFS fs /\\\n       openhandleFS fs = openhandleFS postFS /\\ vmFS fs = vmFS postFS /\\\n       dMapFS fs = dMapFS postFS /\\ fCntFS fs = fCntFS postFS /\\\n       dCntFS fs = dCntFS postFS /\\\n       mmap_handles (fsFS fs) = mmap_handles (fsFS postFS) /\\\n       mmap_memory (fsFS fs) = mmap_memory (fsFS postFS) /\\\n       ~ file_in_tree (fMapFS postFS) (dMapFS postFS) path fname (layoutFS postFS) /\\\n       good_file_system (fsFS postFS)).\n  Proof.\n    intros. unfold fs_remove in H0. rm_hif. 1: left; inversion H0; auto.\n    right. simpl in H0. destruct H as [? [? [? [? [? [? ?]]]]]]. rm_hmatch.\n    - right. apply file_in_tree_with_id_some in Heqo; auto.\n      assert (file_in_tree (fMapFS fs) (dMapFS fs) path fname (layoutFS fs)) by\n          (rewrite file_in_tree_with_id_eq; exists f; auto). rm_hmatch.\n      + destruct t. 1: exfalso; revert Heqo0; apply findDir_not_fnode.\n        apply path_in_tree_with_id_some in Heqo0. rm_hmatch.\n        * left. apply bool_eq_ok in Heqb. inversion H0. intuition.\n          exists d. intuition.\n        * right. destruct fs. simpl in H0. unfold bool_eq in Heqb. simpl in *.\n          destruct (writable (metaD (d_map f0 d))) eqn: ?. 2: inversion Heqb. rm_hif.\n          -- left. inversion H0. subst. simpl. intuition. exists d. intuition.\n          -- right. simpl in H0.\n             remember {| nameF := \"\";\n                         metaF := {| permission :=\n                                       {| readable := false;\n                                          writable := false;\n                                          executable := false |}; size := 0 |};\n                         pageIdsF := [] |} as fd.\n             inversion H0. unfold fMapFS, dMapFS, layoutFS, fsFS, logFS,\n                           openhandleFS, vmFS, fCntFS, dCntFS in *. simpl in *.\n             subst postFS. clear H0. rewrite e. intuition.\n             ++ exists f. unfold change_f_map. intuition; rm_if; exfalso; auto.\n             ++ exists d. intuition.\n             ++ revert H12. apply removeFnodeFromTree_not_in_tree; auto.\n             ++ pose proof (removeFnodeFromTree_Permutation\n                              _ _ _ _ _ _ _ H2 H1 H Heqo0 Heqo).\n                split; [|split; [|split; [|split; [|split; [|split; [|split; [|split;[|split;[|split]]]]]]]]]; simpl; auto.\n                ** eapply removeFnodeFromTree_NoDupNameTree; eauto.\n                ** rewrite removeFnodeFromTree_the_same_Dids; auto.\n                ** symmetry in H12. apply (Permutation_NoDup H12) in H2.\n                   rewrite NoDup_cons_iff in H2. destruct H2; auto.\n                ** intros. rewrite removeFnodeFromTree_the_same_Dids in H14; auto.\n                ** intros. apply Permutation_in with (x := el) in H12; auto. simpl.\n                   intuition.\n                ** unfold isDir in H0. destruct H0 as [dd [ll ?]]. rewrite H0.\n                   simpl. rm_if; apply DnodeIsDir.\n                ** intros. unfold change_f_map in H16, H15. subst fd.\n                   do 2 rm_hif; simpl in *; [exfalso; auto..|]. intro.\n                   apply (H6 fId1 fId2 pgId1 pgId2); auto.\n                ** intros. unfold change_f_map in H14. subst fd. rm_hif; simpl in *.\n                   --- exfalso; auto.\n                   --- eapply H8; eauto.\n      + exfalso. apply path_in_tree_none in Heqo0; auto. apply Heqo0.\n        eapply file_in_tree_path_in_tree; eauto.\n    - left. apply file_in_tree_none in Heqo; auto. inversion H0. intuition.\n  Qed.\n\n  Inductive Sequential: list Memid -> Prop :=\n  | Seq_nil: Sequential nil\n  | Seq_one: forall m, Sequential [m]\n  | Seq_cons: forall m l, Sequential (S m :: l) -> Sequential (m :: S m :: l).\n\n  Lemma check_if_continuous_ok: forall l,\n      check_if_continuous l = true <-> Sequential l.\n  Proof.\n    intros. induction l; simpl. 1: split; intros; [constructor | easy]. destruct l.\n    - split; intros; [constructor | easy].\n    - rm_if; split; intros; try easy.\n      + subst m. constructor. rewrite <- IHl. easy.\n      + inversion H. subst. rewrite IHl. easy.\n      + inversion H. subst. easy.\n  Qed.\n\n  Lemma check_size_ok: forall len1 len2,\n      check_size len1 len2 = true <-> len1 <> 0 /\\ len1 = pad_size len2.\n  Proof.\n    intros. unfold check_size. rm_if.\n    - split; intros; [| destruct H]; easy.\n    - assert (HS: block_size <> 0) by (compute; intro HS'; inversion HS').\n      assert (HT: 0 < block_size) by (compute; omega). rm_if.\n      + rm_if; split; intros; try easy.\n        * split; auto. destruct len1. 1: easy. simpl in l. unfold pad_size. rm_if.\n          -- rewrite <- Nat.div_exact in e; auto. rewrite Nat.mul_comm in e.\n             rewrite e in g, l. rewrite <- Nat.mul_lt_mono_pos_r in l; auto.\n             unfold ge in g. rewrite <- Nat.mul_le_mono_pos_r in g; auto. omega.\n          -- f_equal. unfold ge in g. rewrite Nat.le_lteq in g. destruct g.\n             ++ rewrite Nat.mul_succ_l in H0.\n                rewrite (S_pred_pos block_size) in H0 at 2; auto.\n                rewrite Nat.add_succ_r in H0. apply lt_n_Sm_le in H0.\n                apply Nat.div_le_mono with (c := block_size) in H0; auto.\n                rewrite Nat.div_add_l in H0; auto. apply Nat.lt_le_incl in l.\n                rewrite (Nat.div_small (pred block_size)) in H0.\n                2: compute; apply le_n.\n                apply Nat.div_le_mono with (c := block_size) in l; auto.\n                rewrite Nat.div_mul in l; auto. omega.\n             ++ exfalso. apply n0. rewrite Nat.mod_divides; auto. exists (S len1).\n                rewrite Nat.mul_comm. easy.\n        * destruct H. destruct len1. 1: easy. simpl Init.Nat.pred in n0.\n          apply not_lt in n0. unfold pad_size in H0. clear n H g. unfold ge in n0.\n          rm_hif.\n          -- apply Nat.div_le_mono with (c := block_size) in n0; auto.\n             rewrite Nat.div_mul in n0; auto. omega.\n          -- Opaque block_size. inversion H0. clear H0. Transparent block_size.\n             exfalso. destruct len1.\n             ++ assert (len2 = O) by omega. subst. apply n, Nat.mod_0_l; auto.\n             ++ rewrite Nat.le_lteq in n0. destruct n0.\n                ** rewrite Nat.mul_succ_l in H.\n                   rewrite (S_pred_pos block_size) in H at 2; auto.\n                   rewrite Nat.add_succ_r in H. apply lt_n_Sm_le in H.\n                   apply Nat.div_le_mono with (c := block_size) in H; auto.\n                   rewrite Nat.div_add_l in H; auto.\n                   rewrite (Nat.div_small (pred block_size)) in H.\n                   2: compute; apply le_n. omega.\n                ** apply n. rewrite Nat.mod_divides; auto. exists (S len1).\n                   rewrite Nat.mul_comm. easy.\n      + split; intros. 1: easy. destruct H. subst. exfalso. apply n0.\n        unfold pad_size. rm_if.\n        * rewrite <- Nat.div_exact in e; auto.\n          rewrite Nat.mul_comm. rewrite <- e. omega.\n        * unfold ge. rewrite Nat.mul_comm. apply Nat.lt_le_incl.\n          apply Nat.mul_succ_div_gt; auto.\n  Qed.\n\n  Lemma check_range_ok: forall l u, check_range l u = true <->\n                                    forall i, In i l -> i < u.\n  Proof.\n    intros. induction l; simpl; split; intros; try easy.\n    - rm_hif. 2: easy. destruct H0. 1: subst; easy. rewrite IHl in H. apply H; auto.\n    - rm_if. rewrite IHl; intros; apply H; right; easy.\n  Qed.\n\n  Lemma pad_size_neq_O: forall len, len <> 0 <-> pad_size len <> 0.\n  Proof.\n    intros. assert (HS: block_size <> 0) by (compute; intro HS; inversion HS).\n    split; intros.\n    - unfold pad_size. rm_if. rewrite <- Nat.div_exact in e; auto.\n      remember (len / block_size). destruct n; auto.\n    - unfold pad_size in H. rm_hif.\n      + rewrite <- Nat.div_exact in e; auto. remember (len / block_size). rewrite e.\n        intro. pose proof (Nat.mul_eq_0_r _ _ H0 HS). auto.\n      + destruct len; auto.\n  Qed.\n\n  Opaque pad_size.\n\n  Lemma interval_between_ok: forall n start len,\n      interval_between n start len = false <-> n < start \\/ start + len <= n.\n  Proof.\n    intros. unfold interval_between. rm_if; [rm_if |]; split; intros; try easy; omega.\n  Qed.\n\n  Transparent pad_size.\n\n  Lemma interval_overlap_ok: forall s1 len1 s2 len2,\n      len1 <> O -> len2 <> O ->\n      interval_overlap s1 (pad_size len1) s2 (pad_size len2) = false <->\n      forall p1 p2, Disjoint (s1, len1, p1) (s2, len2, p2).\n  Proof.\n    intros. simpl. unfold interval_overlap. rewrite Bool.orb_false_iff.\n    rewrite !interval_between_ok. split; intros.\n    - destruct H1. destruct H1, H2; omega.\n    - specialize (H1 ttf ttf). split.\n      + destruct H1; [left | right]; auto. rewrite pad_size_neq_O in H. omega.\n      + destruct H1; [right | left]; auto. rewrite pad_size_neq_O in H0. omega.\n  Qed.\n\n  Lemma NoNull_cons_inv: forall x l, NoNull (x :: l) -> NoNull l.\n  Proof.\n    intros. unfold NoNull in *. rewrite Forall_forall in *.\n    intros. apply H. right; auto.\n  Qed.\n\n  Lemma check_overlap_ok: forall s len h,\n      len <> 0 -> NoNull h ->\n      check_overlap s (pad_size len) h = false <->\n      forall p i, In i h -> Disjoint (s, len, p) i.\n  Proof.\n    intros. induction h; simpl; split; intros; try easy; destruct a as [[s1 len1] ?].\n    - destruct i as [[s2 len2] ?]. rm_hif_eqn H. 1: inversion H1. destruct H2.\n      + inversion H2. subst. rewrite interval_overlap_ok in Heqb; auto.\n        * specialize (Heqb p p). red in Heqb. easy.\n        * red in H0. rewrite Forall_forall in H0. red in H0.\n          specialize (H0 (s2, len2, p1) (in_eq _ _)). simpl in H0. easy.\n      + rewrite IHh in H1.\n        * specialize (H1 p _ H2). simpl in H1. easy.\n        * apply NoNull_cons_inv in H0. easy.\n    - rm_if_eqn.\n      + rewrite <- Bool.not_false_iff_true in Heqb. exfalso. apply Heqb.\n        rewrite interval_overlap_ok; auto.\n        * intros. simpl. specialize (H1 p1 (s1, len1, p) (or_introl eq_refl)).\n          simpl in H1. easy.\n        * red in H0. rewrite Forall_forall in H0. specialize (H0 _ (in_eq _ _)).\n          red in H0. easy.\n      + rewrite IHh.\n        * intros. specialize (H1 p i (or_intror H2)). unfold Disjoint. easy.\n        * apply NoNull_cons_inv in H0. easy.\n  Qed.\n\n  Lemma Sequential_In: forall h l,\n      Sequential l -> hd_error l = Some h ->\n      forall i, In i l <-> h <= i < h + length l.\n  Proof.\n    intros ? ?. revert h. induction l; intros; simpl. 1: split; intros; omega.\n    simpl in H0. inversion H0. subst. clear H0. destruct l. 1: simpl; omega.\n    inversion H. subst. rewrite (IHl (S h)); simpl; auto. omega.\n  Qed.\n\n  Lemma write_zeroes_length: forall addrs mem,\n      (forall i, In i addrs -> i < length mem) -> Sequential addrs ->\n      length (write_zeroes addrs mem) = length mem.\n  Proof.\n    intros. unfold write_zeroes. destruct addrs. 1: easy. rewrite !app_length.\n    rewrite firstn_length_le. 2: apply Nat.lt_le_incl, H; left; easy.\n    rewrite repeat_length. assert (hd_error (n :: addrs) = Some n) by easy.\n    pose proof (firstn_skipn (n + length (n :: addrs)) mem).\n    rewrite <- H2 at 2. rewrite app_length. f_equal.\n    rewrite firstn_length_le; auto. clear H2. simpl.\n    assert (In (n + length addrs) (n :: addrs)). {\n      rewrite (Sequential_In n); auto. simpl. split; try omega.\n      rewrite <- Nat.add_lt_mono_l. apply Nat.lt_succ_diag_r. }\n    apply H in H2. omega.\n  Qed.\n\n  Lemma write_zeroes_In: forall addrs mem,\n      (forall i, In i addrs -> i < length mem) -> Sequential addrs ->\n      forall i, In i addrs -> nth i (write_zeroes addrs mem) nil =\n                              repeat Ascii.zero block_size.\n  Proof.\n    intros. unfold write_zeroes. destruct addrs. 1: inversion H1.\n    rewrite (Sequential_In n) in H1; auto.\n    assert (length (firstn n mem) = n) by\n        (rewrite firstn_length_le; [omega | apply Nat.lt_le_incl, H; left; easy]).\n    rewrite <- app_assoc, app_nth2; rewrite H2. 2: omega. rewrite app_nth1.\n    - remember (repeat Ascii.zero block_size).\n      assert (i - n < length (n :: addrs)) by (unfold Memid in H1; omega).\n      pose proof (@nth_In _ (i - n) (repeat l (length (n :: addrs))) nil).\n      rewrite repeat_length in H4. apply H4 in H3. clear H4. apply repeat_spec in H3.\n      easy.\n    - rewrite repeat_length. omega.\n  Qed.\n\n  Lemma mmap_ok: forall len perm flag fs mid err postFS,\n      (mid, err, postFS) = mmap len perm flag fs -> NoNull (memHandleFS fs) ->\n      (flag <> mapAnon /\\ postFS = fs /\\ err = eMapFailed) \\/\n      (flag = mapAnon /\\\n       exists p1 p2 addrs,\n         hd_error (logFS postFS) = Some (Call_AllocMem p1 p2 addrs) /\\\n         ((Sequential addrs /\\ length addrs <> 0 /\\ length addrs = pad_size len /\\\n           (forall i, In i addrs -> i < length (memoryFS fs)) /\\\n           (forall p i, In i (memHandleFS fs) -> Disjoint (mid, len, p) i) /\\\n           hd_error addrs = Some mid /\\ layoutFS fs = layoutFS postFS /\\\n           openhandleFS fs = openhandleFS postFS /\\ vmFS fs = vmFS postFS /\\\n           fMapFS fs = fMapFS postFS /\\ dMapFS fs = dMapFS postFS /\\\n           fnode_ctr (fsFS fs) = fnode_ctr (fsFS postFS) /\\\n           dnode_ctr (fsFS fs) = dnode_ctr (fsFS postFS) /\\\n           memHandleFS postFS = (mid, len, perm) :: memHandleFS fs /\\\n           length (memoryFS postFS) = length (memoryFS fs) /\\ err = eSucc /\\\n           (forall i, In i addrs -> nth i (memoryFS postFS) nil =\n                                    repeat Ascii.zero block_size) /\\\n           (forall m, In m (memoryFS postFS) -> In m (memoryFS fs) \\/\n                                                m = repeat Ascii.zero block_size)) \\/\n          (err = eMapFailed /\\ fsFS postFS = fsFS fs))).\n  Proof.\n    intros. unfold mmap in H. simpl in H. rm_hif.\n    - right. destruct fs as [fs ?]. simpl in H. unfold memHandleFS in H0.\n      remember (allocate_memory (mmap_memory fs) len (length l)) as addrs. split; auto.\n      exists (mmap_memory fs), len, addrs. rm_hif_eqn H; simpl in H, H0.\n      + apply andb_prop in Heqb. destruct Heqb. apply andb_prop in H1. destruct H1.\n        apply andb_prop in H1. destruct H1. rewrite Bool.negb_true_iff in H2.\n        rewrite check_if_continuous_ok in H1. rewrite check_size_ok in H4. destruct H4.\n        rewrite check_range_ok in H3. rewrite H5 in H2.\n        rewrite check_overlap_ok in H2; auto.\n        * inversion H. Opaque repeat. subst postFS.\n          unfold logFS, openhandleFS, vmFS, dMapFS,\n          fCntFS, dCntFS, fMapFS, fsFS, layoutFS, memHandleFS, memoryFS in *.\n          simpl. split; auto. left. intuition.\n          -- apply (H2 p) in H6. red in H6. easy.\n          -- destruct addrs. 1: simpl in H4; exfalso; apply H4; easy. simpl; easy.\n          -- apply write_zeroes_length; auto.\n          -- apply write_zeroes_In; auto.\n          -- unfold write_zeroes in H6. destruct addrs; auto. apply in_app_or in H6.\n             destruct H6; [apply in_app_or in H6; destruct H6 | ].\n             ++ left. rewrite <- (firstn_skipn m0), in_app_iff. left; easy.\n             ++ right. apply repeat_spec in H6. easy.\n             ++ left.\n                rewrite <- (firstn_skipn (m0 + length (m0 :: addrs))), in_app_iff.\n                right; easy.\n        * rewrite H5, <- pad_size_neq_O in H4. easy.\n      + inversion H. split; auto.\n    - left. inversion H. easy.\n  Qed.\n\n  Definition neqMmapHandle_false: forall mid len s lens p,\n      neqMmapHandle mid len (s, lens, p) = false <-> mid = s /\\ len = lens.\n  Proof.\n    intros. unfold neqMmapHandle.\n    rewrite Bool.orb_false_iff, !Bool.negb_false_iff, !Nat.eqb_eq. easy.\n  Qed.\n\n  Definition neqMmapHandle_true: forall mid len s lens p,\n      neqMmapHandle mid len (s, lens, p) = true <-> mid <> s \\/ len <> lens.\n  Proof.\n    intros. unfold neqMmapHandle.\n    rewrite Bool.orb_true_iff, !Bool.negb_true_iff, !Nat.eqb_neq. easy.\n  Qed.\n\n  Lemma forallb_exists: forall {A : Type} (f : A -> bool) (l : list A),\n      forallb f l = false <-> (exists x : A, In x l /\\ f x = false).\n  Proof.\n    intros. induction l; simpl.\n    - split; intros; try easy. destruct H as [? [? ?]]. easy.\n    - rewrite Bool.andb_false_iff. split; intros.\n      + destruct H. 1: (exists a; split; auto). rewrite IHl in H.\n        destruct H as [x [? ?]]. exists x. split; auto.\n      + destruct H as [x [[? | ?] ?]].\n        * subst. left; auto.\n        * right. rewrite IHl. exists x. split; auto.\n  Qed.\n\n  Lemma filter_perm: forall {A: Type} (f g: A -> bool) l,\n      (forall x, In x l -> f x = negb (g x)) ->\n      Permutation l (filter f l ++ filter g l).\n  Proof.\n    intros. induction l. 1: easy. simpl. pose proof (H a (or_introl eq_refl)).\n    assert (forall x : A, In x l -> f x = negb (g x)) by\n        (intros; apply H; right; easy). specialize (IHl H1). clear H1.\n    destruct (g a) eqn:?H; simpl in H0; rewrite H0.\n    - apply Permutation_cons_app; auto.\n    - apply Permutation_cons; auto.\n  Qed.\n\n  Lemma filter_perm': forall {A: Type} (f: A -> bool) l,\n      Permutation l (filter (fun x => negb (f x)) l ++ filter f l).\n  Proof. intros. apply filter_perm. intros; easy. Qed.\n\n  Lemma NoOverlap_cons_inv: forall x l, NoOverlap (x :: l) -> NoOverlap l.\n  Proof. intros. inversion H. easy. Qed.\n\n  Lemma NoOverlap_NoDup: forall l, NoOverlap l -> NoNull l -> NoDup l.\n  Proof.\n    induction l; intros; constructor.\n    - inversion H. subst. intro. specialize (H3 _ H1). destruct a as [[s len] p].\n      red in H3. red in H0. rewrite Forall_forall in H0. specialize (H0 _ (in_eq _ _)).\n      red in H0. rewrite pad_size_neq_O in H0. destruct H3; omega.\n    - apply IHl.\n      + eapply NoOverlap_cons_inv; eauto.\n      + eapply NoNull_cons_inv; eauto.\n  Qed.\n\n  Lemma filter_nil: forall {A: Type} (f: A -> bool) l,\n      filter f l = nil <-> forall i, In i l -> f i = false.\n  Proof.\n    intros. induction l.\n    - split; intros. 1: inversion H0. simpl. easy.\n    - split; intros.\n      + simpl in H. rm_hif_eqn H. 1: inversion H. simpl in H0. destruct H0.\n        1: subst; auto. apply IHl; auto.\n      + simpl. rm_if_eqn.\n        * specialize (H _ (in_eq _ _)). rewrite H in Heqb. inversion Heqb.\n        * rewrite IHl. intros. apply H. simpl. right; easy.\n  Qed.\n\n  Lemma NoNull_head: forall mid len pa l,\n      NoNull ((mid, len, pa) :: l) -> len <> O.\n  Proof.\n    intros. unfold NoNull in H. rewrite Forall_forall in H.\n    pose proof (H _ (in_eq _ _)). red in H0. easy.\n  Qed.\n\n  Lemma NoOverlap_NoNull_neq: forall mid len perm l,\n      NoOverlap l -> NoNull l -> In (mid, len, perm) l ->\n      filter (fun x => negb (neqMmapHandle mid len x)) l = [(mid, len, perm)].\n  Proof.\n    do 3 intro. induction l; intros. 1: inversion H1. simpl in H1. destruct H1.\n    - subst. simpl. rm_if_eqn.\n      + f_equal. rewrite filter_nil. intros. rewrite Bool.negb_false_iff.\n        destruct i as [[si leni] p]. rewrite neqMmapHandle_true.\n        inversion H. subst. specialize (H4 _ H1). simpl in H4. left.\n        unfold NoNull in H0. rewrite Forall_forall in H0.\n        pose proof (H0 _ (in_eq _ _)). simpl in H2.\n        specialize (H0 _ (in_cons _ _ _ H1)). simpl in H0.\n        rewrite pad_size_neq_O in H0, H2. destruct H4; omega.\n      + rewrite Bool.negb_false_iff, Bool.orb_true_iff, !Bool.negb_true_iff,\n        !Nat.eqb_neq in Heqb. exfalso. destruct Heqb; apply H1; easy.\n    - simpl. rm_if_eqn.\n      + exfalso. rewrite Bool.negb_true_iff in Heqb. destruct a as [[sa lena] pa].\n        rewrite neqMmapHandle_false in Heqb. destruct Heqb. subst sa lena.\n        inversion H. subst. specialize (H4 _ H1). red in H4. apply NoNull_head in H0.\n        rewrite pad_size_neq_O in H0. destruct H4; omega.\n      + apply IHl; auto; [eapply NoOverlap_cons_inv | eapply NoNull_cons_inv]; eauto.\n  Qed.\n\n  Lemma munmap_ok: forall mid len err fs postFS,\n      (err, postFS) = munmap mid len fs ->\n      NoOverlap (memHandleFS fs) -> NoNull (memHandleFS fs) ->\n      ((forall perm, ~ In (mid, len, perm) (memHandleFS fs)) /\\\n       err = eInval /\\ postFS = fs) \\/\n      (exists perm p1 p2 p3 succ,\n          In (mid, len, perm) (memHandleFS fs) /\\\n          hd_error (logFS postFS) = Some (Call_DeallocMem p1 p2 p3 succ) /\\\n          ((succ = false /\\ err = eInval /\\ fsFS postFS = fsFS fs) \\/\n           (succ = true /\\ err = eSucc /\\ layoutFS fs = layoutFS postFS /\\\n            openhandleFS fs = openhandleFS postFS /\\ vmFS fs = vmFS postFS /\\\n            fMapFS fs = fMapFS postFS /\\ dMapFS fs = dMapFS postFS /\\\n            fnode_ctr (fsFS fs) = fnode_ctr (fsFS postFS) /\\\n            dnode_ctr (fsFS fs) = dnode_ctr (fsFS postFS) /\\\n            memoryFS postFS = memoryFS fs /\\\n            Permutation ((mid, len, perm) :: memHandleFS postFS) (memHandleFS fs)))).\n  Proof.\n    intros. unfold munmap in H. simpl in H. rm_hif_eqn H.\n    - rewrite forallb_forall in Heqb. left. inversion H. subst. split; auto.\n      unfold memHandleFS. repeat intro. apply Heqb in H2. unfold neqMmapHandle in H2.\n      rewrite Bool.orb_true_iff, !Bool.negb_true_iff, !Nat.eqb_neq in H2.\n      destruct H2; apply H2; easy.\n    - right. destruct fs as [fs ?]. simpl in H. rewrite forallb_exists in Heqb.\n      destruct Heqb as [[[? ?] perm] [? ?]]. simpl in H2.\n      rewrite neqMmapHandle_false in H3. destruct H3. subst m n.\n      remember (deallocate_memory (mmap_memory fs) mid len (length l)) as succ.\n      exists perm, (mmap_memory fs), mid, len, succ. unfold memHandleFS in *.\n      simpl in *. split; auto. rm_hif_eqn H.\n      + simpl in H. inversion H. simpl. split; auto. right. subst postFS.\n        unfold logFS, openhandleFS, vmFS, dMapFS,\n        fCntFS, dCntFS, fMapFS, fsFS, layoutFS, memHandleFS, memoryFS in *. simpl.\n        intuition. pose proof (filter_perm' (neqMmapHandle mid len) (mmap_handles fs)).\n        rewrite (NoOverlap_NoNull_neq mid len perm) in H3; auto. simpl in H3. easy.\n      + inversion H. simpl. split; auto.\n  Qed.\n\n  (* page ids unique among all files *)\n  (* file size match page ids *)\n\n\n  (* create_dir stats readdir truncate chmod *)\n  (* path + name -> does not exists *)\n  (* path is valid *)\n  (* permission path has write *)\n  (* external call succeed *)\n  (* preserve tree dmap properties *)\n\n  Corollary fs_read_safty: forall arg result fs postFS,\n      good_file_system (fsFS fs) -> (result, postFS) = fs_read arg fs ->\n      good_file_system (fsFS postFS).\n  Proof.\n    intros arg result. destruct arg as [fId len]. destruct result as [buf err].\n    intros. pose proof H. destruct H as [_ [_ [_ [_ [_ [? _]]]]]].\n    pose proof (fs_read_ok _ _ _ _ _ _ H0 H). destruct H2 as [?|[?|[?|[?|[?|?]]]]].\n    - destruct H2 as [? [? ?]]. subst fs. auto.\n    - destruct H2 as [? [? [? [? ?]]]]. subst fs. auto.\n    - destruct H2 as [? [? [? [? ?]]]]. rewrite H5. auto.\n    - destruct H2 as [? [? [? _]]]. rewrite H4. auto.\n    - destruct H2 as [? [? [? _]]]. rewrite H4. auto.\n    - destruct H2 as [? [? [? [? [? [? [? [? [? [? [? [? [? ?]]]]]]]]]]]]].\n      unfold layoutFS, vmFS, fMapFS, dMapFS, fsFS, openhandleFS in *. hnf.\n      rewrite <- H5, <- H7, <- H8, <- H9, <- H10, <- H11, <- H12, H13.\n      destruct H1 as [? [? [? [? [? [? [? [? ?]]]]]]]]. split; intuition.\n  Qed.\n\n  Corollary fs_open_safty: forall arg result fs postFS,\n      good_file_system (fsFS fs) -> (result, postFS) = fs_open arg fs ->\n      good_file_system (fsFS postFS).\n  Proof.\n    intros arg result. destruct arg as [path fname]. destruct result as [fId err].\n    intros. pose proof H. destruct H as [? [_ [_ [_ [_ [? _]]]]]].\n    pose proof (fs_open_ok _ _ _ _ _ _ H0 H2 H). destruct H3 as [?|[?|[?|?]]].\n    - destruct H3 as [_ [_ [_ ?]]]. subst fs; auto.\n    - destruct H3 as [_ [_ [_ ?]]]. subst fs; auto.\n    - destruct H3 as [_ [_ [? _]]]. unfold fsFS. rewrite <- H3; auto.\n    - destruct H3 as [? [? [? [? [? [? [? [? [? [? [? [? [? _]]]]]]]]]]]]].\n      clear H H2. hnf. destruct H1 as [? [? [? [? [? [? [? [? ?]]]]]]]].\n      unfold fsFS, layoutFS, vmFS, fMapFS, dMapFS, openhandleFS in *.\n      rewrite <- H6, <- H8, <- H9, <- H10, <- H11, <- H12, <- H13. intuition.\n  Qed.\n\n  Corollary fs_close_safty: forall arg result fs postFS,\n      good_file_system (fsFS fs) -> (result, postFS) = fs_close arg fs ->\n      good_file_system (fsFS postFS).\n  Proof.\n    intros. pose proof (fs_close_ok _ _ _ _ H H0). destruct H1 as [?|[?|?]].\n    - destruct H1 as [_ [? _]]. subst fs; assumption.\n    - destruct H1 as [? [? [? [? [? [? [? [? [? [? [? [? _]]]]]]]]]]]].\n      destruct H as [? [? [? [? [? [? [? [? ?]]]]]]]]. hnf.\n      unfold fsFS, layoutFS, vmFS, fMapFS, dMapFS, openhandleFS in *.\n      rewrite <- H4, <- H6, <- H7, <- H9, <- H10, <- H11, <- H12. intuition.\n      pose proof (Permutation_NoDup H3 H17). rewrite NoDup_cons_iff in H23.\n      destruct H23; assumption.\n    - destruct H1 as [_ [_ [? _]]]. unfold fsFS. rewrite <- H1; assumption.\n  Qed.\n\n  Corollary fs_write_safty: forall arg result fs postFS,\n      good_file_system (fsFS fs) -> (result, postFS) = fs_write arg fs ->\n      good_file_system (fsFS postFS).\n  Proof.\n    intros. destruct arg as [[fId buf] pos]. rename result into err.\n    pose proof (fs_write_ok _ _ _ _ _ _ H0 H). destruct H1 as [?|[?|[?|[?|?]]]].\n    - destruct H1 as [_ [? _]]. subst fs; assumption.\n    - destruct H1 as [_ [? _]]. subst fs; assumption.\n    - destruct H1 as [_ [_ [? _]]]. rewrite H1; assumption.\n    - destruct H1 as [_ [? _]]. rewrite H1; assumption.\n    - intuition.\n  Qed.\n\n  Corollary fs_seek_safty: forall arg result fs postFS,\n      good_file_system (fsFS fs) -> (result, postFS) = fs_seek arg fs ->\n      good_file_system (fsFS postFS).\n  Proof.\n    intros. destruct arg as [fId pos]. rename result into err.\n    pose proof (fs_seek_ok _ _ _ _ _ H0). destruct H1 as [?|[?|[?|?]]].\n    - destruct H1 as [_ [? _]]. subst fs; assumption.\n    - destruct H1 as [_ [_ [_ [? _]]]]. subst fs; assumption.\n    - destruct H1 as [_ [_ [? _]]]. rewrite H1; assumption.\n    - destruct H1 as [? [? [? [? [? [? [? [? [? [? [? _]]]]]]]]]]].\n      destruct H as [? [? [? [? [? [? [? [? ?]]]]]]]]. hnf.\n      unfold fsFS, layoutFS, vmFS, fMapFS, dMapFS, openhandleFS in *.\n      rewrite <- H3, <- H5, <- H6, <- H7, <- H8, <- H9, <- H10, H11. intuition.\n  Qed.\n\n  Corollary fs_create_safty: forall arg result fs postFS,\n      good_file_system (fsFS fs) -> (result, postFS) = fs_create arg fs ->\n      good_file_system (fsFS postFS).\n  Proof.\n    intros. destruct arg as [[path fname] p]. rename result into err.\n    pose proof (fs_create_ok _ _ _ _ _ _ H H0).\n    destruct H1 as [? | [? | [? | [? | [? | [? | ?]]]]]];\n      [destruct H1 as [_ [_ ?]]; subst fs; assumption.. |\n       destruct H1 as [_ [_ [? _]]]; rewrite <- H1; assumption |\n       intuition].\n  Qed.\n\n  Corollary fs_mkdir_safty: forall arg result fs postFS,\n      good_file_system (fsFS fs) -> (result, postFS) = fs_mkdir arg fs ->\n      good_file_system (fsFS postFS).\n  Proof.\n    intros. destruct arg as [[path dname] p]. rename result into err.\n    pose proof (fs_mkdir_ok _ _ _ _ _ _ H H0).\n    destruct H1 as [? | [? | [? | [? | [? | [? | ?]]]]]];\n      [destruct H1 as [_ [_ ?]]; subst fs; assumption.. |\n       destruct H1 as [_ [_ [? _]]]; rewrite <- H1; assumption |\n       intuition].\n  Qed.\n\n  Corollary fs_rmdir_safty: forall arg result fs postFS,\n      good_file_system (fsFS fs) -> (result, postFS) = fs_rmdir arg fs ->\n      good_file_system (fsFS postFS).\n  Proof.\n    intros. rename arg into path. rename result into err.\n    pose proof (fs_rmdir_ok _ _ _ _ H H0).\n    destruct H1 as [? | [? | [? | [? | [? | ?]]]]].\n    - destruct H1 as [_ [_ ?]]; subst fs; assumption.\n    - destruct H1 as [_ [_ [_ ?]]]; subst fs; assumption.\n    - destruct H1 as [_ [_ [_ ?]]]; subst fs; assumption.\n    - destruct H1 as [_ [_ [_ [_ ?]]]]; subst fs; assumption.\n    - destruct H1 as [_ [_ [_ [_ [? _]]]]]. rewrite H1; assumption.\n    - intuition.\n  Qed.\n\n  Corollary fs_remove_safty: forall arg result fs postFS,\n      good_file_system (fsFS fs) -> (result, postFS) = fs_remove arg fs ->\n      good_file_system (fsFS postFS).\n  Proof.\n    intros. destruct arg as [path fname]. rename result into err.\n    pose proof (fs_remove_ok _ _ _ _ _ H H0).\n    destruct H1 as [? | [? | [? | [? | ?]]]].\n    - destruct H1 as [_ [_ ?]]; subst fs; assumption.\n    - destruct H1 as [_ [_ ?]]; subst fs; assumption.\n    - destruct H1 as [_ [_ [_ ?]]]; subst fs; assumption.\n    - destruct H1 as [_ [_ [_ [? _]]]]. rewrite <- H1; assumption.\n    - intuition.\n  Qed.\n\n  Corollary fs_chmod_safty: forall arg result fs postFS,\n      good_file_system (fsFS fs) -> (result, postFS) = fs_chmod arg fs ->\n      good_file_system (fsFS postFS).\n  Proof.\n    intros. destruct arg as [path p]. rename result into err.\n    pose proof (fs_chmod_ok _ _ _ _ _ H H0).\n    destruct H1 as [? | [? | [? | ?]]].\n    - destruct H1 as [_ [_ [_ [_ ?]]]]; subst fs; assumption.\n    - destruct H1 as [_ [? _]]. rewrite <- H1; assumption.\n    - destruct H1 as [? [? [? [? [? [? [? [? [? _]]]]]]]]].\n      destruct H as [? [? [? [? [? [? [? [? ?]]]]]]]]. hnf.\n      unfold fsFS, layoutFS, vmFS, fMapFS, dMapFS, openhandleFS, fCntFS, dCntFS in *.\n      rewrite <- H2, <- H3, <- H5, <- H6, <- H7, <- H8, <- H9. intuition.\n      apply preserve_dname_NoDupNameTree with (d_map (fst fs)). 2: assumption. intros.\n      destruct H1 as [dId' [_ [_ [? ?]]]]. destruct (Nat.eq_dec dId dId').\n      + subst dId'. intuition.\n      + rewrite H20; auto.\n    - destruct H1 as [? [? [? [? [? [? [? [? [_ [? [? _]]]]]]]]]]].\n      destruct H as [? [? [? [? [? [? [? [? ?]]]]]]]]. hnf.\n      unfold fsFS, layoutFS, vmFS, fMapFS, dMapFS, openhandleFS, fCntFS, dCntFS in *.\n      destruct H1 as [fId' [? [? [? [? [? ?]]]]]].\n      assert (forall id, pageIdsF (f_map (fst postFS) id) =\n                         pageIdsF (f_map (fst fs) id)) by\n          (intros; destruct (Nat.eq_dec id fId'); [subst id | rewrite H23]; auto).\n      rewrite <- H3, <- H4, <- H6, <- H7, <- H8, <- H9, <- H10. intuition.\n      + apply preserve_fname_NoDupNameTree with (f_map (fst fs)). 2: assumption.\n        intros. destruct (Nat.eq_dec fId fId'); [subst fId | rewrite H23]; auto.\n      + rewrite H24 in H30, H29. eapply H17; eauto.\n      + rewrite H24 in H27. eapply H25; eauto.\n  Qed.\n\n  Corollary fs_readdir_safty: forall arg result fs postFS,\n      good_file_system (fsFS fs) -> (result, postFS) = fs_readdir arg fs ->\n      good_file_system (fsFS postFS).\n  Proof.\n    intros. rename arg into path. destruct result as [result err].\n    pose proof (fs_readdir_ok _ _ _ _ _ H H0). destruct H1 as [? | [? | ?]].\n    - destruct H1 as [_ [_ [_ ?]]]; subst fs; assumption.\n    - destruct H1 as [_ [_ [_ [? _]]]]. rewrite <- H1; assumption.\n    - destruct H1 as [_ [_ [? _]]]. rewrite <- H1; assumption.\n  Qed.\n\n  Corollary fs_fstat_safty: forall arg result fs postFS,\n      good_file_system (fsFS fs) -> (result, postFS) = fs_fstat arg fs ->\n      good_file_system (fsFS postFS).\n  Proof.\n    intros. rename arg into id.\n    destruct result as [[[[name permsn] fsize] pageIds] err].\n    pose proof (fs_fstat_ok _ _ _ _ _ _ _ _ H0);\n      destruct H1 as [? | [? | ?]]; destruct H1 as [_ [? _]];\n        [subst fs | rewrite H1..]; assumption.\n  Qed.\n\n  Corollary fs_truncate_safty: forall arg result fs postFS,\n      good_file_system (fsFS fs) -> (result, postFS) = fs_truncate arg fs ->\n      good_file_system (fsFS postFS).\n  Proof.\n    intros. destruct arg as [fId len]. rename result into err.\n    pose proof (fs_truncate_ok _ _ _ _ _ H H0).\n    destruct H1 as [? | [? | [? | [? | ?]]]].\n    - destruct H1 as [_ [? _]]; subst fs; assumption.\n    - destruct H1 as [_ [? _]]; subst fs; assumption.\n    - destruct H1 as [_ [? _]]; subst fs; assumption.\n    - destruct H1 as [_ [_ [? _]]]. rewrite <- H1; assumption.\n    - destruct H1 as [? [? [? [? [? [? [? [? [? [? [? [? [? ?]]]]]]]]]]]]].\n      destruct H as [? [? [? [? [? [? [? [? ?]]]]]]]]. hnf.\n      unfold fsFS, layoutFS, vmFS, fMapFS, dMapFS, openhandleFS, fCntFS, dCntFS in *.\n      rewrite <- H3, <- H4, <- H6, <- H7, <- H8, <- H9, <- H10. intuition.\n      + apply preserve_fname_NoDupNameTree with (f_map (fst fs)); auto. intro id'.\n        destruct (Nat.eq_dec id' fId); [subst id' | rewrite H24]; intuition.\n      + destruct (Nat.eq_dec fId1 fId), (Nat.eq_dec fId2 fId).\n        * rewrite <- e in e0. apply H26. intuition.\n        * subst fId. clear n. revert H31. apply (H21 fId1 fId2); auto.\n          -- destruct H27 as [l ?]. rewrite H27, in_app_iff. left; auto.\n          -- rewrite <- H24; auto.\n        * subst fId. clear n. revert H31. apply (H21 fId1 fId2); auto.\n          -- rewrite <- H24; auto.\n          -- destruct H27 as [l ?]. rewrite H27, in_app_iff. left; auto.\n        * revert H31. apply (H21 fId1 fId2); auto; rewrite <- H24; auto.\n      + destruct (Nat.eq_dec fId0 fId).\n        * subst fId0. destruct H27 as [l ?]. apply (H23 fId pgId).\n          rewrite H27, in_app_iff. left; auto.\n        * apply (H23 fId0 pgId). rewrite <- H24; auto.\n  Qed.\n\n  Corollary mmap_safty: forall len perm flag fs result postFS,\n      good_file_system (fsFS fs) -> (result, postFS) = mmap len perm flag fs ->\n      good_file_system (fsFS postFS).\n  Proof.\n    intros. destruct result as [mid err]. pose proof H.\n    destruct H as [? [? [? [? [? [? [? [? [? [? [? ?]]]]]]]]]]].\n    pose proof (mmap_ok _ _ _ _ _ _ _ H0 H12).\n    destruct H13 as [? | ?]. 1: destruct H13 as [_ [? _]]; subst fs; easy.\n    destruct H13 as [? [p1 [p2 [addrs [? [? | ?]]]]]].\n    2: destruct H15 as [_ ?]; rewrite H15; easy. hnf.\n    destruct H15 as [? [? [? [? [? [? [? [? [? [? [? [? [? [? [? [? ?]]]]]]]]]]]]]]]].\n    unfold fsFS, layoutFS, vmFS, fMapFS, dMapFS, openhandleFS, fCntFS,\n    dCntFS, memHandleFS in *.\n    rewrite <- H21, <- H22, <- H24, <- H25, <- H26, <- H27, H28. intuition.\n    - constructor; auto.\n    - apply H33 in H31. destruct H31; auto. rewrite H31. apply repeat_length.\n    - unfold NoNull in *. rewrite Forall_forall in *. intros. simpl in H31.\n      destruct H31; auto. subst x. red. rewrite pad_size_neq_O. rewrite <- H17. easy.\n  Qed.\n\n  Close Scope string_scope.\n\n  Lemma Disjoint_comm: forall a b, Disjoint a b <-> Disjoint b a.\n  Proof.\n    intros. destruct a as [[s1 l1] p1]. destruct b as [[s2 l2] p2]. simpl. intuition.\n  Qed.\n\n  Lemma NoOverlap_double_cons: forall l a1 a2,\n      NoOverlap (a1 :: a2 :: l) -> NoOverlap (a2 :: a1 :: l).\n  Proof.\n    intros. inversion H. subst. inversion H3. subst. constructor.\n    - intros. simpl in H0. destruct H0. 2: apply H4; easy. subst y.\n      rewrite Disjoint_comm. apply H2. left; easy.\n    - constructor; auto. intros. apply H2. right; easy.\n  Qed.\n\n  Lemma NoOverlap_double_cons_iff: forall l a1 a2,\n      NoOverlap (a1 :: a2 :: l) <-> NoOverlap (a2 :: a1 :: l).\n  Proof. intros; split; intros; apply NoOverlap_double_cons; easy. Qed.\n\n  Lemma NoOverlap_cons_app: forall l1 l2 a,\n      NoOverlap (a :: l1 ++ l2) <-> NoOverlap (l1 ++ a :: l2).\n  Proof.\n    induction l1; intros; simpl. 1: easy. rewrite NoOverlap_double_cons_iff.\n    split; intros; inversion H; subst; constructor; intros.\n    - apply H2. rewrite in_app_iff in H0. simpl in *. rewrite in_app_iff. intuition.\n    - rewrite <- IHl1. easy.\n    - apply H2. rewrite in_app_iff. simpl in *. rewrite in_app_iff in H0. intuition.\n    - rewrite IHl1. easy.\n  Qed.\n\n  Lemma NoOverlap_perm: forall l1 l2,\n      Permutation l1 l2 -> NoOverlap l1 -> NoOverlap l2.\n  Proof.\n    induction l1. intros.\n    - destruct l2. 1: constructor. apply Permutation_length in H. simpl in H. omega.\n    - intros. assert (In a l2) by (apply (Permutation_in _ H); left; easy).\n      apply in_split in H1. destruct H1 as [li1 [li2 ?]]. subst l2.\n      rewrite <- NoOverlap_cons_app. apply Permutation_cons_app_inv in H. constructor.\n      + intros. inversion H0. subst. apply H4. symmetry in H.\n        apply (Permutation_in _ H). easy.\n      + apply IHl1; auto. inversion H0. auto.\n  Qed.\n\n  Lemma NoNull_perm: forall l1 l2, Permutation l1 l2 -> NoNull l1 -> NoNull l2.\n  Proof.\n    intros. unfold NoNull in *. rewrite Forall_forall in *. intros. apply H0.\n    symmetry in H. eapply Permutation_in; eauto.\n  Qed.\n\n  Corollary munmap_safty: forall mid len err fs postFS,\n      good_file_system (fsFS fs) -> (err, postFS) = munmap mid len fs ->\n      good_file_system (fsFS postFS).\n  Proof.\n    intros. pose proof H.\n    destruct H as [? [? [? [? [? [? [? [? [? [? [? ?]]]]]]]]]]].\n    pose proof (munmap_ok _ _ _ _ _ H0 H10 H12).\n    destruct H13 as [[_ [_ ?]] | ?]. 1: subst; easy. hnf.\n    destruct H13 as [perm [p1 [p2 [p3 [succ [? [? [[_ [_ ?]]| ?]]]]]]]].\n    1: rewrite H15; easy. destruct H15 as [? [? [? [? [? [? [? [? [? [? ?]]]]]]]]]].\n    unfold fsFS, layoutFS, vmFS, fMapFS, dMapFS, openhandleFS, fCntFS,\n    dCntFS, memHandleFS, memoryFS in *. symmetry in H25.\n    rewrite <- H17, <- H18, <- H20, <- H21, <- H22, <- H23, H24. intuition.\n    - apply NoOverlap_perm in H25; auto. inversion H25. easy.\n    - apply NoNull_perm in H25; auto. apply NoNull_cons_inv in H25. easy.\n  Qed.\n\n  Definition fs_functions:\n    list {n : nat & fs_parameter n -> State FSState (fs_result n)} :=\n    [existT _ O fs_read  ; existT _  1 fs_open    ; existT _  2 fs_close  ;\n     existT _ 3 fs_write ; existT _  4 fs_seek    ; existT _  5 fs_create ;\n     existT _ 6 fs_mkdir ; existT _  7 fs_rmdir   ; existT _  8 fs_remove ;\n     existT _ 9 fs_chmod ; existT _ 10 fs_readdir ; existT _ 11 fs_fstat  ;\n     existT _ 12 fs_truncate].\n\n  Theorem function_safty: forall v fs postFS arg result,\n      In v fs_functions -> (result, postFS) = (projT2 v) arg fs ->\n      good_file_system (fsFS fs) -> good_file_system (fsFS postFS).\n  Proof.\n    intros. unfold fs_functions in H. simpl in H.\n    destruct H as [?|[?|[?|[?|[?|[?|[?|[?|[?|[?|[?|[?|[?|?]]]]]]]]]]]]];\n      [subst v; simpl in *.. | exfalso; assumption].\n    - eapply fs_read_safty; eauto.\n    - eapply fs_open_safty; eauto.\n    - eapply fs_close_safty; eauto.\n    - eapply fs_write_safty; eauto.\n    - eapply fs_seek_safty; eauto.\n    - eapply fs_create_safty; eauto.\n    - eapply fs_mkdir_safty; eauto.\n    - eapply fs_rmdir_safty; eauto.\n    - eapply fs_remove_safty; eauto.\n    - eapply fs_chmod_safty; eauto.\n    - eapply fs_readdir_safty; eauto.\n    - eapply fs_fstat_safty; eauto.\n    - eapply fs_truncate_safty; eauto.\n  Qed.\n\n  Fixpoint fs_compose (l: list {n : nat & ((fs_parameter n -> State FSState (fs_result n)) * (fs_parameter n))%type}) (input: FSState) : FSState :=\n    match l with\n    | nil => input\n    | f :: l' => let (result, postFS) := (fst (projT2 f)) (snd (projT2 f)) input in\n                 fs_compose l' postFS\n    end.\n\n  Corollary composition_safty: forall l input,\n      (forall v, In v l -> In (existT _ (projT1 v) (fst (projT2 v))) fs_functions) ->\n      good_file_system (fsFS input) ->\n      good_file_system (fsFS (fs_compose l input)).\n  Proof.\n    induction l; intros; simpl; auto.\n    assert (In a (a :: l)) by (simpl; left; reflexivity). pose proof (H _ H1).\n    destruct a as [n [v va]]. unfold fst, snd, projT1, projT2 in H2 |- *. clear H1.\n    remember (v va input). destruct p as [? ?].\n    pose proof (function_safty _ _ _ _ _ H2 Heqp H0). apply IHl; auto. clear H2.\n    intros. apply H. simpl. right. auto.\n  Qed.\n\n  Lemma good_file_system_mkfs: forall name, good_file_system (fsFS (mkfs name)).\n  Proof.\n    intros. unfold mkfs. hnf. simpl.\n    split; [|split; [|split; [|split; [|split; [|split; [|split;[|split;[|split;[|split;[|split]]]]]]]]]]; intros; try easy.\n    - constructor; simpl. 1: rewrite Forall_forall; intros; inversion H. constructor.\n    - constructor; [intro S; inversion S | constructor].\n    - constructor.\n    - intros. destruct H; intuition.\n    - constructor.\n    - hnf. exists O, []. reflexivity.\n    - constructor.\n    - red. easy.\n  Qed.\n\n  Corollary composition_mkfs_safty: forall l name,\n      (forall v, In v l -> In (existT _ (projT1 v) (fst (projT2 v))) fs_functions) ->\n      good_file_system (fsFS (fs_compose l (mkfs name))).\n  Proof. intros. apply composition_safty; auto. apply good_file_system_mkfs. Qed.\n\n  Parameter fs_rename : Path -> FData -> Path -> FData -> ErrCode.\n  Parameter fs_flush : Fid -> ErrCode.\n\nEnd SGX_FS.\n", "meta": {"author": "shwetasshinde24", "repo": "BesFS", "sha": "2cc7081b1b910ca890f8399563f9bc5dceebc293", "save_path": "github-repos/coq/shwetasshinde24-BesFS", "path": "github-repos/coq/shwetasshinde24-BesFS/BesFS-2cc7081b1b910ca890f8399563f9bc5dceebc293/coq/SGX_FS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.263799459950905}}
{"text": "\nRequire Import Undecidability.Synthetic.Definitions Undecidability.Synthetic.Undecidability.\n\nFrom Undecidability.FOL\n     Require Import Semantics.Tarski.FullFacts Semantics.Tarski.FullSoundness.\nFrom Undecidability.FOL.Sets.Models\n     Require Import Aczel_CE Aczel_TD ZF_model HF_model.\n\nFrom Undecidability.FOL.Undecidability.Reductions\n     Require Import ZF_to_HF PCPb_to_HF PCPb_to_HFD PCPb_to_ZFeq PCPb_to_ZF PCPb_to_ZFD.\n\nRequire Import Undecidability.FOL.Sets.ZF.\n\nFrom Undecidability.PCP\n     Require Import PCP PCP_undec Util.PCP_facts Reductions.PCPb_iff_dPCPb.\nOpen Scope sem.\n\n(* Semantic entailment in full ZF restricted to extensional models *)\n\nTheorem PCPb_entailment_ZF :\n  (exists V (M : interp V), extensional M /\\ standard M /\\ forall rho psi, ZF psi -> rho ⊨ psi) -> reduction solvable PCPb entailment_ZF.\nProof.\n  intros H. intros B. apply PCP_ZF. apply H.\nQed.\n\nTheorem undecidable_entailment_ZF :\n  (exists V (M : interp V), extensional M /\\ standard M /\\ forall rho psi, ZF psi -> rho ⊨ psi) -> undecidable entailment_ZF.\nProof.\n  intros H. apply (undecidability_from_reducibility PCPb_undec). exists solvable. now apply PCPb_entailment_ZF.\nQed.\n\nCorollary undecidable_model_entailment_ZF :\n  Aczel_CE.CE -> TD -> undecidable entailment_ZF.\nProof.\n  intros H1 H2. now apply undecidable_entailment_ZF, normaliser_model.\nQed.\n\n(* Semantic entailment in Z restricted to extensional models *)\n\nTheorem PCPb_entailment_Z :\n  (exists V (M : interp V), extensional M /\\ standard M /\\ forall rho psi, Z psi -> rho ⊨ psi) -> reduction solvable PCPb entailment_Z.\nProof.\n  intros H. intros B. apply PCP_Z. apply H.\nQed.\n\nTheorem undecidable_entailment_Z :\n  (exists V (M : interp V), extensional M /\\ standard M /\\ forall rho psi, Z psi -> rho ⊨ psi) -> undecidable entailment_Z.\nProof.\n  intros H. apply (undecidability_from_reducibility PCPb_undec). exists solvable. now apply PCPb_entailment_Z.\nQed.\n\nCorollary undecidable_model_entailment_Z :\n  Aczel_CE.CE -> undecidable entailment_Z.\nProof.\n  intros H. now apply undecidable_entailment_Z, extensionality_model.\nQed.\n\n(* Semantic entailment in ZF' restricted to extensional models *)\n\nTheorem PCPb_entailment_ZF' :\n  (exists V (M : interp V), extensional M /\\ standard M /\\ forall rho psi, In psi ZF' -> rho ⊨ psi) -> reduction solvable PCPb entailment_ZF'.\nProof.\n  intros H. intros B. apply PCP_ZF'. apply H.\nQed.\n\nTheorem undecidable_entailment_ZF' :\n  (exists V (M : interp V), extensional M /\\ standard M /\\ forall rho psi, In psi ZF' -> rho ⊨ psi) -> undecidable entailment_ZF'.\nProof.\n  intros H. apply (undecidability_from_reducibility PCPb_undec). exists solvable. now apply PCPb_entailment_ZF'.\nQed.\n\nCorollary undecidable_model_entailment_ZF' :\n  Aczel_CE.CE -> undecidable entailment_ZF'.\nProof.\n  intros H. apply undecidable_entailment_ZF'.\n  destruct extensionality_model as (V & M & H1 & H2 & H3); trivial.\n  exists V, M. eauto using Z.\nQed.\n\n(* Semantic entailment in ZFeq' allowing intensional models *)\n\nTheorem PCPb_entailment_ZFeq' :\n  PCPb ⪯ entailment_ZFeq'.\nProof.\n  exists solvable. intros B. split; intros H.\n  - eapply PCP_ZFD, soundness in H. intros D M rho H'. apply H, H'.\n  - now apply PCP_ZFeq'; try apply intensional_model.\nQed.\n\nTheorem undecidable_entailment_ZFeq' :\n  undecidable entailment_ZFeq'.\nProof.\n  apply (undecidability_from_reducibility PCPb_undec), PCPb_entailment_ZFeq'.\nQed.\n\n(* Semantic entailment in HF restricted to extensional models *)\n\nTheorem undecidable_entailment_HF' :\n  Aczel_CE.CE -> undecidable entailment_HF.\nProof.\n  intros ce. apply (undecidability_from_reducibility (undecidable_model_entailment_ZF' ce)).\n  exists add_om. intros phi. apply reduction_entailment.\nQed.\n\nTheorem undecidable_entailment_HF :\n  undecidable entailment_HF.\nProof.\n  apply (undecidability_from_reducibility PCPb_undec).\n  exists PCPb_to_HF.solvable. intros phi. apply PCP_HF. apply HF_model.\nQed.\n\nTheorem undecidable_entailment_HFN :\n  undecidable entailment_HFN.\nProof.\n  apply (undecidability_from_reducibility PCPb_undec).\n  exists PCPb_to_HF.solvable. intros phi. rewrite PCPb_iff_dPCPb. split; intros H.\n  - destruct H as [s H]. intros M HM rho H1 H2. eapply PCP_HF1; eauto.\n    intros sigma psi Hp. apply H2. now right.\n  - destruct HFN_model as (M & H1 & H2 & H3 & H4).\n    specialize (H M H1 (fun _ => @i_func _ _ _ _ eset Vector.nil) H2 H4).\n    apply PCP_HF2 in H as [s Hs]; trivial. now exists s.\n    intros sigma psi Hp. apply H4. now right.                                             \nQed.\n\n(* Intuitionistic deduction in full ZFeq *)\n\nTheorem PCPb_deduction_ZF :\n  (exists V (M : interp V), extensional M /\\ standard M /\\ forall rho psi, ZF psi -> rho ⊨ psi) -> reduction solvable PCPb deduction_ZF.\nProof.\n  intros (V & M & H1 & H2 & H3).\n  intros B. split.\n  - intros H % (@PCP_ZFD intu). exists ZFeq'. split; eauto using ZFeq.\n  - intros H'. specialize (tsoundness H'). clear H'. intros H'.\n    apply PCPb_iff_dPCPb. eapply PCP_ZF2; eauto using ZF.\n    apply (H' V M (fun _ => ∅)). intros psi [].\n    + apply extensional_eq; eauto using ZF.\n    + apply H3. constructor 2.\n    + apply H3. constructor 3.\nQed.\n\nTheorem undecidable_deduction_ZF :\n  (exists V (M : interp V), extensional M /\\ standard M /\\ forall rho psi, ZF psi -> rho ⊨ psi) -> undecidable deduction_ZF.\nProof.\n   intros H. apply (undecidability_from_reducibility PCPb_undec). exists solvable. now apply PCPb_deduction_ZF.\nQed.\n\nCorollary undecidable_model_deduction_ZF :\n  Aczel_CE.CE -> TD -> undecidable deduction_ZF.\nProof.\n  intros H1 H2. now apply undecidable_deduction_ZF, normaliser_model.\nQed.\n\n(* Intuitionistic deduction in ZFeq *)\n\nTheorem PCPb_deduction_Z :\n  (exists V (M : interp V), extensional M /\\ standard M /\\ forall rho psi, Z psi -> rho ⊨ psi) -> reduction solvable PCPb deduction_Z.\nProof.\n  intros (V & M & H1 & H2 & H3).\n  intros B. split.\n  - intros H % (@PCP_ZFD intu). exists ZFeq'. split; eauto using Zeq.\n  - intros H'. specialize (tsoundness H'). clear H'. intros H'.\n    apply PCPb_iff_dPCPb. eapply PCP_ZF2; eauto using Z.\n    apply (H' V M (fun _ => ∅)). intros psi [].\n    + apply extensional_eq; eauto using Z.\n    + apply H3. constructor 2.\nQed.\n\nTheorem undecidable_deduction_Z :\n  (exists V (M : interp V), extensional M /\\ standard M /\\ forall rho psi, Z psi -> rho ⊨ psi) -> undecidable deduction_Z.\nProof.\n   intros H. apply (undecidability_from_reducibility PCPb_undec). exists solvable. now apply PCPb_deduction_Z.\nQed.\n\nCorollary undecidable_model_deduction_Z :\n  Aczel_CE.CE -> undecidable deduction_Z.\nProof.\n  intros H. now apply undecidable_deduction_Z, extensionality_model.\nQed.\n\n(* Intuitionistic deduction in ZFeq' *)\n\nTheorem PCPb_deduction_ZF' :\n  PCPb ⪯ deduction_ZF'.\nProof.\n  exists solvable. intros B. split; try apply PCP_ZFD.\n  intros H' % soundness. apply PCP_ZFeq'; try apply intensional_model.\n  intros D M rho H. apply H', H.\nQed.\n\nCorollary undecidable_deduction_ZF' :\n  undecidable deduction_ZF'.\nProof.\n  apply (undecidability_from_reducibility PCPb_undec), PCPb_deduction_ZF'.\nQed.\n\n(* Intuitionistic deduction in HFeq *)\n\nTheorem undecidable_deduction_HF :\n  undecidable deduction_HF.\nProof.\n  apply (undecidability_from_reducibility undecidable_deduction_ZF').\n  exists add_om. intros phi. apply reduction_deduction.\nQed.\n\nTheorem undecidable_deduction_HFN :\n  undecidable deduction_HFN.\nProof.\n  apply (undecidability_from_reducibility PCPb_undec).\n  exists PCPb_to_HF.solvable. intros B. split.\n  - intros H. eapply Weak. try apply PCP_HFD; auto. intros phi Hp. firstorder.\n  - intros H % soundness. destruct HFN_model as (M & H1 & H2 & H3 & H4).\n    specialize (H M H1 (fun _ => @i_func _ _ _ _ eset Vector.nil)).\n    eapply PCPb_iff_dPCPb, PCP_HF2; try apply H; trivial.\n    + intros rho phi Hp. apply H4. now right.\n    + intros phi [<-|[<-|[<-|[<-|Hp]]]]; try now apply H4.\n      all: cbn; setoid_rewrite H2; congruence.\nQed.\n\n\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/FOL/Undecidability/ZF_undec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.263799459950905}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nRequire Import Coq.Classes.RelationClasses.\n\nFrom Fairness Require Import\n  ITreeLib WFLibLarge FairBeh SelectBeh.\n\nFrom Fairness Require Import Axioms.\n\nSet Implicit Arguments.\n\nSection EXTRACT.\n\n  Variable id: ID.\n\n  (** match between raw_tr and tr *)\n  Variant _raw_spin\n          (raw_spin: forall (R: Type), (@RawTr.t id R) -> Prop)\n          R\n    :\n    (@RawTr.t id R) -> Prop :=\n    | raw_spin_silent\n        (silent: silentE) tl\n        (TL: raw_spin _ tl)\n      :\n      _raw_spin raw_spin (RawTr.cons (inl silent) tl)\n  .\n\n  Definition raw_spin: forall (R: Type), RawTr.t -> Prop := paco2 _raw_spin bot2.\n\n  Lemma raw_spin_mon: monotone2 _raw_spin.\n  Proof.\n    ii. inv IN. econs; eauto.\n  Qed.\n\n\n  Inductive _extract_tr\n            (extract_tr: forall (R: Type), RawTr.t -> Tr.t -> Prop)\n            R\n    :\n    (@RawTr.t id R) -> Tr.t -> Prop :=\n  | extract_tr_done\n      retv\n    :\n    _extract_tr extract_tr (RawTr.done retv) (Tr.done retv)\n  | extract_tr_spin\n      raw\n      (RSPIN: raw_spin raw)\n    :\n    _extract_tr extract_tr raw (Tr.spin)\n  | extract_tr_ub\n    :\n    _extract_tr extract_tr (RawTr.ub) (Tr.ub)\n  | extract_tr_nb\n    :\n    _extract_tr extract_tr (RawTr.nb) (Tr.nb)\n  | extract_tr_obs\n      (obs: obsE) raw_tl tr_tl\n      (TL: extract_tr _ raw_tl tr_tl)\n    :\n    _extract_tr extract_tr (RawTr.cons (inr obs) raw_tl) (Tr.cons obs tr_tl)\n  | extract_tr_silent\n      (silent: silentE) raw_tl tr_tl\n      (TL: _extract_tr extract_tr raw_tl tr_tl)\n    :\n    _extract_tr extract_tr (RawTr.cons (inl silent) raw_tl) tr_tl\n  .\n\n  Definition extract_tr: forall (R: Type), RawTr.t -> Tr.t -> Prop := paco3 _extract_tr bot3.\n\n  Lemma extract_tr_ind\n        (extract_tr : forall R : Type, RawTr.t -> Tr.t -> Prop) (R : Type) (P: RawTr.t -> Tr.t -> Prop)\n        (DONE: forall retv : R, P (RawTr.done retv) (Tr.done retv))\n        (SPIN: forall (raw : RawTr.t) (RSPIN: raw_spin raw), P raw Tr.spin)\n        (UB: P RawTr.ub Tr.ub)\n        (NB: P RawTr.nb Tr.nb)\n        (OBS: forall (obs : obsE) (raw_tl : RawTr.t) (tr_tl : Tr.t) (TL: extract_tr R raw_tl tr_tl),\n            P (RawTr.cons (inr obs) raw_tl) (Tr.cons obs tr_tl))\n        (SILENT: forall (silent : silentE) (raw_tl : RawTr.t) (tr_tl : Tr.t)\n                   (STEP: _extract_tr extract_tr raw_tl tr_tl) (IH: P raw_tl tr_tl),\n            P (RawTr.cons (inl silent) raw_tl) tr_tl)\n    :\n    forall raw_tr tr, (_extract_tr extract_tr raw_tr tr) -> P raw_tr tr.\n  Proof.\n    fix IH 3; i.\n    inv H; eauto.\n  Qed.\n\n  Lemma extract_tr_mon: monotone3 _extract_tr.\n  Proof.\n    ii. induction IN using extract_tr_ind; econs; eauto.\n  Qed.\n\n  Local Hint Constructors _raw_spin: core.\n  Local Hint Unfold raw_spin: core.\n  Local Hint Resolve raw_spin_mon: paco.\n  Local Hint Constructors _extract_tr: core.\n  Local Hint Unfold extract_tr: core.\n  Local Hint Resolve extract_tr_mon: paco.\n\n  Lemma extract_tr_ind2\n        (R : Type) (P: RawTr.t -> Tr.t -> Prop)\n        (DONE: forall retv : R, P (RawTr.done retv) (Tr.done retv))\n        (SPIN: forall (raw : RawTr.t) (RSPIN: raw_spin raw), P raw Tr.spin)\n        (UB: P RawTr.ub Tr.ub)\n        (NB: P RawTr.nb Tr.nb)\n        (OBS: forall (obs : obsE) (raw_tl : RawTr.t) (tr_tl : Tr.t) (TL: extract_tr raw_tl tr_tl),\n            P (RawTr.cons (inr obs) raw_tl) (Tr.cons obs tr_tl))\n        (SILENT: forall (silent : silentE) (raw_tl : RawTr.t) (tr_tl : Tr.t)\n                   (STEP: extract_tr raw_tl tr_tl) (IH: P raw_tl tr_tl),\n            P (RawTr.cons (inl silent) raw_tl) tr_tl)\n    :\n    forall raw_tr tr, (extract_tr raw_tr tr) -> P raw_tr tr.\n  Proof.\n    i. punfold H. induction H using extract_tr_ind; eauto.\n    pclearbot. eapply OBS. eauto.\n  Qed.\n\n  Variant extract_tr_indC\n          (extract_tr: forall (R: Type), RawTr.t -> Tr.t -> Prop)\n          R\n    :\n    (@RawTr.t id R) -> Tr.t -> Prop :=\n    | extract_tr_indC_done\n        retv\n      :\n      extract_tr_indC extract_tr (RawTr.done retv) (Tr.done retv)\n    | extract_tr_indC_spin\n        raw\n        (RSPIN: raw_spin raw)\n      :\n      extract_tr_indC extract_tr raw (Tr.spin)\n    | extract_tr_indC_ub\n      :\n      extract_tr_indC extract_tr (RawTr.ub) (Tr.ub)\n    | extract_tr_indC_nb\n      :\n      extract_tr_indC extract_tr (RawTr.nb) (Tr.nb)\n    | extract_tr_indC_obs\n        (obs: obsE) raw_tl tr_tl\n        (TL: extract_tr _ raw_tl tr_tl)\n      :\n      extract_tr_indC extract_tr (RawTr.cons (inr obs) raw_tl) (Tr.cons obs tr_tl)\n    | extract_tr_indC_silent\n        (silent: silentE) raw_tl tr_tl\n        (TL: extract_tr _ raw_tl tr_tl)\n      :\n      extract_tr_indC extract_tr (RawTr.cons (inl silent) raw_tl) tr_tl\n  .\n\n  Lemma extract_tr_indC_mon: monotone3 extract_tr_indC.\n  Proof. ii. inv IN; econs; eauto. Qed.\n\n  Local Hint Resolve extract_tr_indC_mon: paco.\n\n  Lemma extract_tr_indC_wrespectful: wrespectful3 _extract_tr extract_tr_indC.\n  Proof.\n    econs; eauto with paco.\n    i. inv PR; eauto.\n    { econs; eauto. eapply rclo3_base. eauto. }\n    { econs; eauto. eapply extract_tr_mon; eauto. i. eapply rclo3_base. auto. }\n  Qed.\n\n  Lemma extract_tr_indC_spec: extract_tr_indC <4= gupaco3 _extract_tr (cpn3 _extract_tr).\n  Proof. i. eapply wrespect3_uclo; eauto with paco. eapply extract_tr_indC_wrespectful. Qed.\n\n  Lemma extract_eq_done\n        R (tr: @Tr.t R) retv\n        (EXTRACT: extract_tr (RawTr.done retv) tr)\n    :\n    tr = Tr.done retv.\n  Proof.\n    punfold EXTRACT. inv EXTRACT; eauto. punfold RSPIN. inv RSPIN.\n  Qed.\n\n  Lemma extract_eq_ub\n        R (tr: @Tr.t R)\n        (EXTRACT: extract_tr RawTr.ub tr)\n    :\n    tr = Tr.ub.\n  Proof.\n    punfold EXTRACT. inv EXTRACT; eauto. punfold RSPIN. inv RSPIN.\n  Qed.\n\n  Lemma extract_eq_nb\n        R (tr: @Tr.t R)\n        (EXTRACT: extract_tr RawTr.nb tr)\n    :\n    tr = Tr.nb.\n  Proof.\n    punfold EXTRACT. inv EXTRACT; eauto. punfold RSPIN. inv RSPIN.\n  Qed.\n\n  Lemma extract_tr_raw_spin\n        R (tr: @Tr.t R) raw\n        (EXT: extract_tr raw tr)\n        (RS: raw_spin raw)\n    :\n    tr = Tr.spin.\n  Proof.\n    revert RS. induction EXT using extract_tr_ind2; i; eauto.\n    { punfold RS; inv RS. }\n    { punfold RS; inv RS. }\n    { punfold RS; inv RS. }\n    { punfold RS; inv RS. }\n    { punfold RS; inv RS. pclearbot. eauto. }\n  Qed.\n\n  Lemma extract_tr_inj_tr\n        R (tr1 tr2: @Tr.t R) raw\n        (EXT1: extract_tr raw tr1)\n        (EXT2: extract_tr raw tr2)\n    :\n    Tr.eq tr1 tr2.\n  Proof.\n    revert_until R. pcofix CIH; i.\n    depgen tr2. induction EXT1 using extract_tr_ind2; i.\n    { punfold EXT2. inv EXT2; eauto. punfold RSPIN. inv RSPIN. }\n    { punfold EXT2. inv EXT2; eauto. all: try (punfold RSPIN; inv RSPIN).\n      pclearbot. eapply paco3_fold in TL. hexploit extract_tr_raw_spin; eauto.\n      i; clarify. eauto using Tr.eq_equiv.\n    }\n    { punfold EXT2. inv EXT2; eauto. punfold RSPIN. inv RSPIN. }\n    { punfold EXT2. inv EXT2; eauto. punfold RSPIN. inv RSPIN. }\n    { punfold EXT2. inv EXT2; eauto. punfold RSPIN. inv RSPIN.\n      pclearbot. pfold. econs. right; eauto.\n    }\n    { punfold EXT2. inv EXT2; eauto. punfold RSPIN. inv RSPIN.\n      pclearbot. eauto.\n    }\n  Qed.\n\nEnd EXTRACT.\n#[export] Hint Constructors _raw_spin: core.\n#[export] Hint Unfold raw_spin: core.\n#[export] Hint Resolve raw_spin_mon: paco.\n#[export] Hint Resolve cpn2_wcompat: paco.\n#[export] Hint Constructors _extract_tr: core.\n#[export] Hint Unfold extract_tr: core.\n#[export] Hint Resolve extract_tr_mon: paco.\n#[export] Hint Resolve cpn3_wcompat: paco.\n\n\n\nSection ExtractTr.\n\n  Variable id: ID.\n\n  (** observer of the raw trace **)\n  Inductive observe_raw_first\n          R\n    :\n    (@RawTr.t id R) -> (prod (option obsE) RawTr.t) -> Prop :=\n    | observe_raw_first_done\n        retv\n      :\n      observe_raw_first (RawTr.done retv) (None, (RawTr.done retv))\n    | observe_raw_first_ub\n      :\n      observe_raw_first RawTr.ub (None, RawTr.ub)\n    | observe_raw_first_nb\n      :\n      observe_raw_first RawTr.nb (None, RawTr.nb)\n    | observe_raw_first_obs\n        (obs: obsE) tl\n      :\n      observe_raw_first (RawTr.cons (inr obs) tl) (Some obs, tl)\n    | observe_raw_first_silent\n        (silent: silentE) obs tl tl0\n        (STEP: observe_raw_first tl (obs, tl0))\n      :\n      observe_raw_first (RawTr.cons (inl silent) tl) (obs, tl0)\n  .\n\n  Definition observe_raw_prop {R}\n             (raw: @RawTr.t id R)\n             (obstl: option (prod (option obsE) RawTr.t)): Prop :=\n    match obstl with\n    | None => raw_spin raw\n    | Some obstl0 => observe_raw_first raw obstl0\n    end.\n\n  Lemma inhabited_observe_raw R: inhabited (option (prod (option obsE) (@RawTr.t id R))).\n  Proof.\n    econs. exact None.\n  Qed.\n\n  Definition observe_raw {R} (raw: (@RawTr.t id R)): option (prod (option obsE) RawTr.t) :=\n    epsilon (@inhabited_observe_raw R) (observe_raw_prop raw).\n\n\n  (** properties **)\n  (* helper lemmas *)\n  Lemma spin_no_obs\n        R (raw: @RawTr.t id R)\n        (SPIN: raw_spin raw)\n    :\n    forall ev tl, ~ observe_raw_first raw (ev, tl).\n  Proof.\n    ii. revert SPIN. induction H; i; ss; clarify.\n    - punfold SPIN. inv SPIN.\n    - punfold SPIN. inv SPIN.\n    - punfold SPIN. inv SPIN.\n    - punfold SPIN. inv SPIN.\n    - eapply IHobserve_raw_first; clear IHobserve_raw_first.\n      punfold SPIN. inv SPIN. pclearbot. auto.\n  Qed.\n\n  Lemma no_obs_spin\n        R (raw: @RawTr.t id R)\n        (NOOBS: forall ev tl, ~ observe_raw_first raw (ev, tl))\n    :\n    raw_spin raw.\n  Proof.\n    revert_until R. pcofix CIH; i. destruct raw.\n    - exfalso. eapply NOOBS. econs.\n    - exfalso. eapply NOOBS. econs.\n    - exfalso. eapply NOOBS. econs.\n    - destruct hd as [silent | obs].\n      2:{ exfalso. eapply NOOBS. econs. }\n      pfold. econs. right. eapply CIH. ii. eapply NOOBS.\n      econs 5. eauto.\n  Qed.\n\n  Lemma spin_iff_no_obs\n        R (raw: @RawTr.t id R)\n    :\n    (raw_spin raw) <-> (forall ev tl, ~ observe_raw_first raw (ev, tl)).\n  Proof.\n    esplits. split; i. eapply spin_no_obs; eauto. eapply no_obs_spin; eauto.\n  Qed.\n\n  Lemma observe_raw_first_inj\n        R (raw: @RawTr.t id R) obstl1 obstl2\n        (ORP1: observe_raw_first raw obstl1)\n        (ORP2: observe_raw_first raw obstl2)\n    :\n    obstl1 = obstl2.\n  Proof.\n    depgen obstl2. induction ORP1; i.\n    - inv ORP2; eauto.\n    - inv ORP2; eauto.\n    - inv ORP2; eauto.\n    - inv ORP2; eauto.\n    - inv ORP2; eauto.\n  Qed.\n\n  Lemma observe_raw_inj\n        R (raw: @RawTr.t id R) obstl1 obstl2\n        (ORP1: observe_raw_prop raw obstl1)\n        (ORP2: observe_raw_prop raw obstl2)\n    :\n    obstl1 = obstl2.\n  Proof.\n    destruct obstl1 as [(obs1, tl1) | ]; ss.\n    2:{ destruct obstl2 as [(obs2, tl2) | ]; ss.\n        rewrite spin_iff_no_obs in ORP1. eapply ORP1 in ORP2. clarify.\n    }\n    destruct obstl2 as [(obs2, tl2) | ]; ss.\n    2:{ rewrite spin_iff_no_obs in ORP2. eapply ORP2 in ORP1. clarify. }\n    f_equal. eapply observe_raw_first_inj; eauto.\n  Qed.\n\n\n  Theorem observe_raw_prop_impl_observe_raw\n          R (raw: @RawTr.t id R) obstl\n          (ORP: observe_raw_prop raw obstl)\n    :\n    observe_raw raw = obstl.\n  Proof.\n    eapply observe_raw_inj. 2: eauto.\n    unfold observe_raw, epsilon. eapply Epsilon.epsilon_spec. eauto.\n  Qed.\n\n  Lemma observe_raw_prop_false\n        R (raw: @RawTr.t id R) ev tl\n    :\n    ~ observe_raw_prop raw (Some (None, RawTr.cons ev tl)).\n  Proof.\n    ii. ss. remember (None, RawTr.cons ev tl) as obstl. revert Heqobstl. revert ev tl. rename H into ORF.\n    induction ORF; i; ss. clarify. eapply IHORF. eauto.\n  Qed.\n\n  (** observe_raw reductions **)\n  Lemma observe_raw_spin\n        R (raw: @RawTr.t id R)\n        (SPIN: raw_spin raw)\n    :\n    observe_raw raw = None.\n  Proof.\n    eapply observe_raw_prop_impl_observe_raw. ss.\n  Qed.\n\n  Lemma raw_spin_observe\n        R (raw: @RawTr.t id R)\n        (NONE: observe_raw raw = None)\n    :\n    raw_spin raw.\n  Proof.\n    eapply spin_iff_no_obs. ii.\n    assert (SOME: ~ observe_raw raw = Some (ev, tl)).\n    { ii. clarify. }\n    eapply SOME. eapply observe_raw_prop_impl_observe_raw. ss.\n  Qed.\n\n  Lemma observe_raw_done\n        R (retv: R)\n    :\n    observe_raw (RawTr.done retv) = Some (None, RawTr.done retv).\n  Proof.\n    eapply observe_raw_prop_impl_observe_raw. ss. econs.\n  Qed.\n\n  Lemma observe_raw_ub\n        R\n    :\n    observe_raw (R:=R) (RawTr.ub) = Some (None, RawTr.ub).\n  Proof.\n    eapply observe_raw_prop_impl_observe_raw. ss. econs.\n  Qed.\n\n  Lemma observe_raw_nb\n        R\n    :\n    observe_raw (R:=R) (RawTr.nb) = Some (None, RawTr.nb).\n  Proof.\n    eapply observe_raw_prop_impl_observe_raw. ss. econs.\n  Qed.\n\n  Lemma observe_raw_obs\n        R obs (tl: @RawTr.t id R)\n    :\n    observe_raw (RawTr.cons (inr obs) tl) = Some (Some obs, tl).\n  Proof.\n    eapply observe_raw_prop_impl_observe_raw. ss. econs.\n  Qed.\n\n\n  Lemma observe_first_some_inj\n        R (raw: @RawTr.t id R) obstl1 obstl2\n        (SOME: observe_raw raw = Some obstl1)\n        (ORF: observe_raw_first raw obstl2)\n    :\n    obstl1 = obstl2.\n  Proof.\n    assert (A: observe_raw_prop raw (Some obstl2)). ss.\n    apply observe_raw_prop_impl_observe_raw in A. rewrite SOME in A. clarify.\n  Qed.\n\n  Lemma observe_first_some\n        R (raw: @RawTr.t id R) obstl\n        (SOME: observe_raw raw = Some obstl)\n    :\n    observe_raw_first raw obstl.\n  Proof.\n    assert (NOTSPIN: ~ raw_spin raw).\n    { ii. eapply observe_raw_spin in H. clarify. }\n    rewrite spin_iff_no_obs in NOTSPIN.\n    assert (TEMP: ~ (forall obstl, ~ observe_raw_first raw obstl)).\n    { ii. eapply NOTSPIN. i. eauto. }\n    eapply Classical_Pred_Type.not_all_not_ex in TEMP. des.\n    replace obstl with n; eauto. symmetry. eapply observe_first_some_inj; eauto.\n  Qed.\n\n  Theorem observe_raw_spec\n          R (raw: @RawTr.t id R)\n    :\n    observe_raw_prop raw (observe_raw raw).\n  Proof.\n    destruct (observe_raw raw) eqn:EQ.\n    - ss. eapply observe_first_some; eauto.\n    - ss. eapply raw_spin_observe; eauto.\n  Qed.\n\n  Lemma observe_raw_silent\n        R (tl: @RawTr.t id R) silent\n    :\n    observe_raw (RawTr.cons (inl silent) tl) = observe_raw tl.\n  Proof.\n    eapply observe_raw_prop_impl_observe_raw. destruct (observe_raw tl) eqn:EQ.\n    2:{ ss. pfold. econs. left. eapply raw_spin_observe; eauto. }\n    ss. destruct p as [obs tl0]. hexploit observe_first_some; eauto. i.\n    econs. auto.\n  Qed.\n\n\n\n  (** raw trace to normal trace **)\n  CoFixpoint raw2tr {R} (raw: @RawTr.t id R): (@Tr.t R) :=\n    match observe_raw raw with\n    | None => Tr.spin\n    | Some (None, RawTr.done retv) => Tr.done retv\n    | Some (None, RawTr.ub) => Tr.ub\n    | Some (None, RawTr.nb) => Tr.nb\n    | Some (None, RawTr.cons _ _) => Tr.ub\n    | Some (Some obs, tl) => Tr.cons obs (raw2tr tl)\n    end.\n\n  (** reduction lemmas **)\n  Lemma raw2tr_red_done\n        R (retv: R)\n    :\n    (raw2tr (RawTr.done retv)) = (Tr.done retv).\n  Proof.\n    replace (raw2tr (RawTr.done retv)) with (Tr.ob (raw2tr (RawTr.done retv))).\n    2:{ symmetry. apply Tr.ob_eq. }\n    ss. rewrite observe_raw_done. ss.\n  Qed.\n\n  Lemma raw2tr_red_ub\n        R\n    :\n    (raw2tr (R:=R) RawTr.ub) = Tr.ub.\n  Proof.\n    replace (raw2tr RawTr.ub) with (Tr.ob (R:=R) (raw2tr RawTr.ub)).\n    2:{ symmetry. apply Tr.ob_eq. }\n    ss. rewrite observe_raw_ub. ss.\n  Qed.\n\n  Lemma raw2tr_red_nb\n        R\n    :\n    (raw2tr (R:=R) RawTr.nb) = Tr.nb.\n  Proof.\n    replace (raw2tr RawTr.nb) with (Tr.ob (R:=R) (raw2tr RawTr.nb)).\n    2:{ symmetry. apply Tr.ob_eq. }\n    ss. rewrite observe_raw_nb. ss.\n  Qed.\n\n  Lemma raw2tr_red_obs\n        R obs tl\n    :\n    (raw2tr (RawTr.cons (inr obs) tl)) = (Tr.cons (R:=R) obs (raw2tr tl)).\n  Proof.\n    match goal with | |- ?lhs = _ => replace lhs with (Tr.ob lhs) end.\n    2:{ symmetry. apply Tr.ob_eq. }\n    ss. rewrite observe_raw_obs. ss.\n  Qed.\n\n  Lemma raw2tr_red_spin\n        R (raw: @RawTr.t id R)\n        (SPIN: raw_spin raw)\n    :\n    (raw2tr raw) = Tr.spin.\n  Proof.\n    match goal with | |- ?lhs = _ => replace lhs with (Tr.ob lhs) end.\n    2:{ symmetry. apply Tr.ob_eq. }\n    ss. rewrite observe_raw_spin; eauto.\n  Qed.\n\n  Lemma raw2tr_red_silent\n        R silent tl\n    :\n    (raw2tr (RawTr.cons (inl silent) tl)) = (raw2tr (R:=R) tl).\n  Proof.\n    match goal with | |- ?lhs = ?rhs => replace lhs with (Tr.ob lhs); [replace rhs with (Tr.ob rhs) |] end.\n    2:{ symmetry. apply Tr.ob_eq. }\n    2:{ symmetry. apply Tr.ob_eq. }\n    ss. rewrite observe_raw_silent. ss.\n  Qed.\n\n  Theorem raw2tr_extract\n          R (raw: @RawTr.t id R)\n    :\n    extract_tr raw (raw2tr raw).\n  Proof.\n    revert_until R. pcofix CIH. i.\n    destruct raw.\n    { rewrite raw2tr_red_done. pfold. econs. }\n    { rewrite raw2tr_red_ub. pfold. econs. }\n    { rewrite raw2tr_red_nb. pfold. econs. }\n    destruct hd as [silent | obs].\n    2:{ rewrite raw2tr_red_obs. pfold. econs. right. eauto. }\n    destruct (observe_raw (RawTr.cons (inl silent) raw)) eqn:EQ.\n    2:{ eapply raw_spin_observe in EQ. rewrite raw2tr_red_spin; eauto. }\n    rename p into obstl.\n    remember (RawTr.cons (inl silent) raw) as raw0. clear Heqraw0. clear silent raw.\n    pose (observe_raw_spec) as ORS. specialize (ORS R raw0). rewrite EQ in ORS. ss.\n    clear EQ. induction ORS; ss.\n    { rewrite raw2tr_red_done. pfold. econs. }\n    { rewrite raw2tr_red_ub. pfold. econs. }\n    { rewrite raw2tr_red_nb. pfold. econs. }\n    { rewrite raw2tr_red_obs. pfold. econs. right. eauto. }\n    pfold. econs. punfold IHORS. remember (raw2tr tl) as tr. depgen silent. depgen tl0. revert Heqtr. depgen obs.\n    induction IHORS using (@extract_tr_ind); i.\n    { rewrite raw2tr_red_silent. rewrite raw2tr_red_done. econs. }\n    { exfalso. eapply spin_iff_no_obs in RSPIN. eauto. }\n    { rewrite raw2tr_red_silent. rewrite raw2tr_red_ub. econs. }\n    { rewrite raw2tr_red_silent. rewrite raw2tr_red_nb. econs. }\n    { rewrite raw2tr_red_silent. rewrite raw2tr_red_obs. econs. right. auto. }\n    econs 6. rewrite raw2tr_red_silent. eapply IHIHORS; eauto.\n    - rewrite raw2tr_red_silent in Heqtr. auto.\n    - instantiate (1:=tl0). instantiate (1:=obs). inv ORS. auto.\n  Qed.\n\nEnd ExtractTr.\n\n\n\nSection ExtractRaw.\n\n  Variable id: ID.\n  Variable wf: WF.\n  Variable wf0: T wf.\n  Variable R: Type.\n\n  Definition st_tr_im := ((@state id R) * (@Tr.t R) * (imap id wf))%type.\n\n  (** observer of the state, needs trace for obs return value information **)\n  Inductive observe_state_trace\n    :\n    st_tr_im -> (prod (list rawE) st_tr_im) -> Prop :=\n  | observe_state_trace_ret\n      (retv: R) im\n    :\n    observe_state_trace (Ret retv, Tr.done retv, im)\n                        ([], (Ret retv, Tr.done retv, im))\n  | observe_state_trace_obs\n      fn args ktr rv tl im\n    :\n    observe_state_trace (Vis (Observe fn args) ktr, Tr.cons (obsE_syscall fn args rv) tl, im)\n                        ([inr (obsE_syscall fn args rv)], (ktr rv, tl, im))\n  | observe_state_trace_tau\n      itr tr im evs sti\n      (NNB: tr <> Tr.nb)\n      (SPIN: tr = Tr.spin -> (Beh.diverge_index im itr /\\ evs = [] /\\ sti = (itr, tr, im)))\n      (CONT: tr <> Tr.spin -> observe_state_trace (itr, tr, im) (evs, sti))\n      (CONT: tr <> Tr.spin -> Beh.of_state im itr tr)\n    :\n    observe_state_trace (Tau itr, tr, im)\n                        ((inl silentE_tau) :: evs, sti)\n  | observe_state_trace_choose\n      X ktr x tr im evs sti\n      (NNB: tr <> Tr.nb)\n      (SPIN: tr = Tr.spin -> (Beh.diverge_index im (ktr x) /\\ evs = [] /\\ sti = (ktr x, tr, im)))\n      (CONT: tr <> Tr.spin -> observe_state_trace (ktr x, tr, im) (evs, sti))\n      (BEH: tr <> Tr.spin -> Beh.of_state im (ktr x) tr)\n    :\n    observe_state_trace (Vis (Choose X) ktr, tr, im)\n                        ((inl silentE_tau) :: evs, sti)\n  | observe_state_trace_fair\n      fm ktr tr im evs sti im0\n      (NNB: tr <> Tr.nb)\n      (SPIN: tr = Tr.spin -> (Beh.diverge_index im0 (ktr tt) /\\ evs = [] /\\ sti = (ktr tt, tr, im0)))\n      (CONT: tr <> Tr.spin -> observe_state_trace (ktr tt, tr, im0) (evs, sti))\n      (CONT: tr <> Tr.spin -> Beh.of_state im0 (ktr tt) tr)\n      (FAIR: fair_update im im0 fm)\n    :\n    observe_state_trace (Vis (Fair fm) ktr, tr, im)\n                        ((inl (silentE_fair fm)) :: evs, sti)\n  | observe_state_trace_ub\n      ktr tr im\n    :\n    observe_state_trace (Vis Undefined ktr, tr, im)\n                        ([], (Vis Undefined ktr, tr, im))\n  | observe_state_trace_nb\n      itr im\n    :\n    observe_state_trace (itr, Tr.nb, im)\n                        ([], (itr, Tr.nb, im))\n  .\n\n\n  Definition observe_state_prop (sti: st_tr_im) (rawsti: (prod (list rawE) st_tr_im)): Prop :=\n    (let '(st, tr, im) := sti in (Beh.of_state im st tr)) -> observe_state_trace sti rawsti.\n\n  Definition itree_loop R: (@state id R) :=\n    @ITree.iter _ R unit (fun x: unit => Ret (inl x)) tt.\n\n  Lemma inhabited_observe_state: inhabited (prod (list (@rawE id)) st_tr_im).\n  Proof.\n    econs. econs. exact []. econs. econs. exact (itree_loop R). exact Tr.ub. exact (fun _ => wf0).\n  Qed.\n\n  Definition observe_state (sti: st_tr_im): (prod (list rawE) st_tr_im) :=\n    epsilon inhabited_observe_state (observe_state_prop sti).\n\n\n  (** properties **)\n  Lemma beh_implies_spin\n        (im: imap id wf) (st: @state _ R)\n        (BEH: Beh.of_state im st Tr.spin)\n    :\n    Beh.diverge_index im st.\n  Proof.\n    revert_until R. pcofix CIH; i. remember Tr.spin as tr. revert Heqtr.\n    induction BEH using (@Beh.of_state_ind2); i; clarify; ss; eauto.\n    { eapply paco3_mon; eauto. ss. }\n    { pfold. econs. right. eauto. }\n    { pfold. econs. right. eauto. }\n    { pfold. econs. right. eauto. eauto. }\n  Qed.\n\n  Lemma observe_state_trace_exists\n        (st: @state _ R) (tr: Tr.t) (im: imap id wf)\n        (BEH: Beh.of_state im st tr)\n    :\n    exists rawsti, observe_state_trace (st, tr, im) rawsti.\n  Proof.\n    induction BEH using (@Beh.of_state_ind2).\n    - eexists. econs.\n    - punfold H. inv H.\n      + pclearbot. eexists. econs; i; ss; eauto.\n      + pclearbot. eexists. econs; i; ss; eauto.\n      + pclearbot. eexists. econs; i; ss; eauto.\n      + pclearbot. eexists. econs; i; ss; eauto.\n    - eexists. econs.\n    - eexists. econs.\n    - destruct (classic (tr = Tr.nb)) as [NB | NNB]; clarify; ss.\n      + eexists. econs 7.\n      + destruct (classic (tr = Tr.spin)) as [SPIN | NSPIN]; clarify; ss.\n        * des. eexists. econs; i; ss; clarify. splits; eauto. eapply beh_implies_spin; eauto.\n        * des. destruct rawsti. eexists. econs; i; ss; clarify; eauto.\n    - destruct (classic (tr = Tr.nb)) as [NB | NNB]; clarify; ss.\n      + eexists. econs 7.\n      + destruct (classic (tr = Tr.spin)) as [SPIN | NSPIN]; clarify; ss.\n        * des. eexists. econs; i; ss; clarify. splits; eauto. eapply beh_implies_spin; eauto.\n        * des. destruct rawsti. rr in IHBEH. eexists. econs; i; ss; clarify; eauto.\n    - destruct (classic (tr = Tr.nb)) as [NB | NNB]; clarify; ss.\n      + eexists. econs 7.\n      + destruct (classic (tr = Tr.spin)) as [SPIN | NSPIN]; clarify; ss.\n        * des. eexists. econs; i; ss; clarify. splits; eauto. eapply beh_implies_spin; eauto. eauto.\n        * des. destruct rawsti. rr in IHBEH. eexists. econs; i; ss; clarify; eauto.\n    - eexists. econs; eauto.\n  Qed.\n\n  Lemma observe_state_exists\n        (st: @state _ R) (tr: Tr.t) (im: imap id wf)\n    :\n    exists rawsti, observe_state_prop (st, tr, im) rawsti.\n  Proof.\n    destruct (classic (Beh.of_state im st tr)) as [BEH | NBEH].\n    - hexploit observe_state_trace_exists; eauto. i. des. eexists. ii. eauto.\n    - eexists. ii. clarify.\n      Unshelve. exact ([], (itree_loop R, Tr.ub, fun _ => wf0)).\n  Qed.\n\n  (** (state, trace, imap) to raw trace **)\n  CoFixpoint raw_spin_trace: @RawTr.t id R :=\n    RawTr.cons (R:=R) (inl silentE_tau) raw_spin_trace.\n\n  Lemma raw_spin_trace_ob\n    :\n    raw_spin_trace = (@RawTr.ob _ R raw_spin_trace).\n  Proof.\n    apply RawTr.ob_eq.\n  Qed.\n\n  Lemma raw_spin_trace_red\n    :\n    raw_spin_trace = RawTr.cons (inl silentE_tau) raw_spin_trace.\n  Proof.\n    rewrite raw_spin_trace_ob at 1. ss.\n  Qed.\n\n  Lemma raw_spin_trace_spec\n    :\n    @raw_spin _ R raw_spin_trace.\n  Proof.\n    pcofix CIH. rewrite raw_spin_trace_ob. pfold. econs. right. eapply CIH.\n  Qed.\n\n\n  CoFixpoint tr2raw (tr: Tr.t): RawTr.t :=\n    match tr with\n    | Tr.done retv => RawTr.done retv\n    | Tr.spin => raw_spin_trace\n    | Tr.ub => RawTr.ub\n    | Tr.nb => RawTr.nb\n    | Tr.cons hd tl => RawTr.cons (inr hd) (tr2raw tl)\n    end.\n\n  Lemma tr2raw_red_ret\n        retv\n    :\n    tr2raw (Tr.done retv) = RawTr.done retv.\n  Proof.\n    match goal with | |- ?lhs = _ => replace lhs with (RawTr.ob lhs) end.\n    2:{ symmetry. apply RawTr.ob_eq. }\n    ss.\n  Qed.\n\n  Lemma tr2raw_red_spin\n    :\n    tr2raw Tr.spin = raw_spin_trace.\n  Proof.\n    match goal with | |- ?lhs = _ => replace lhs with (RawTr.ob lhs) end.\n    2:{ symmetry. apply RawTr.ob_eq. }\n    rewrite raw_spin_trace_red. ss.\n  Qed.\n\n  Lemma tr2raw_red_ub\n    :\n    tr2raw Tr.ub = RawTr.ub.\n  Proof.\n    match goal with | |- ?lhs = _ => replace lhs with (RawTr.ob lhs) end.\n    2:{ symmetry. apply RawTr.ob_eq. }\n    ss.\n  Qed.\n\n  Lemma tr2raw_red_nb\n    :\n    tr2raw Tr.nb = RawTr.nb.\n  Proof.\n    match goal with | |- ?lhs = _ => replace lhs with (RawTr.ob lhs) end.\n    2:{ symmetry. apply RawTr.ob_eq. }\n    ss.\n  Qed.\n\n  Lemma tr2raw_red_cons\n        hd tl\n    :\n    tr2raw (Tr.cons hd tl) = RawTr.cons (inr hd) (tr2raw tl).\n  Proof.\n    match goal with | |- ?lhs = _ => replace lhs with (RawTr.ob lhs) end.\n    2:{ symmetry. apply RawTr.ob_eq. }\n    ss.\n  Qed.\n\n  Lemma extract_tr_tr2raw\n        tr\n    :\n    extract_tr (tr2raw tr) tr.\n  Proof.\n    revert_until wf0. pcofix CIH; i.\n    replace (tr2raw tr) with (RawTr.ob (tr2raw tr)).\n    2:{ symmetry. apply RawTr.ob_eq. }\n    ss. destruct tr eqn:TR; clarify.\n    { pfold; econs. }\n    { rewrite raw_spin_trace_red. pfold. econs.\n      rewrite <- raw_spin_trace_red. apply raw_spin_trace_spec. }\n    { pfold; econs. }\n    { pfold; econs. }\n    { pfold; econs. eauto. }\n  Qed.\n\n\n  CoFixpoint _sti2raw (evs: list rawE) (sti: st_tr_im): (@RawTr.t id R) :=\n    match evs with\n    | hd :: tl => RawTr.cons hd (_sti2raw tl sti)\n    | [] =>\n        match observe_state sti with\n        | (evs, (Ret _, Tr.done retv, _)) => RawTr.app evs (RawTr.done retv)\n        | (evs, (_, Tr.nb, _)) => RawTr.app evs RawTr.nb\n        | (evs, (Vis Undefined _, tr, _)) => RawTr.app evs (tr2raw tr)\n        | (hd :: tl, sti0) => RawTr.cons hd (_sti2raw tl sti0)\n        | (evs, _) => RawTr.app evs RawTr.ub\n        end\n    end.\n\n  Definition sti2raw (sti: st_tr_im): (@RawTr.t id R) := _sti2raw [] sti.\n\n\n  (** observe_state reduction lemmas **)\n  Lemma observe_state_ret\n        (im: imap id wf) (retv: R)\n    :\n    observe_state (Ret retv, Tr.done retv, im) = ([], (Ret retv, Tr.done retv, im)).\n  Proof.\n    unfold observe_state, epsilon. unfold Epsilon.epsilon. unfold proj1_sig. des_ifs.\n    rename x into rawsti. clear Heq.\n    hexploit (observe_state_exists). intros OSP. eapply o in OSP; clear o.\n    unfold observe_state_prop in OSP. hexploit OSP; clear OSP; eauto.\n    i. inv H. eauto.\n  Qed.\n\n  Lemma observe_state_obs\n        (im: imap id wf) fn args rv tl ktr\n        (BEH: Beh.of_state im (ktr rv) tl)\n    :\n    observe_state (Vis (Observe fn args) ktr, Tr.cons (obsE_syscall fn args rv) tl, im) =\n      ([inr (obsE_syscall fn args rv)], (ktr rv, tl, im)).\n  Proof.\n    unfold observe_state, epsilon. unfold Epsilon.epsilon. unfold proj1_sig. des_ifs.\n    rename x into rawsti. clear Heq.\n    hexploit (observe_state_exists). intros OSP. eapply o in OSP; clear o.\n    unfold observe_state_prop in OSP. hexploit OSP; clear OSP; eauto.\n    { pfold. econs. eauto. }\n    i. inv H. eapply inj_pair2 in H3. clarify.\n  Qed.\n\n  Lemma observe_state_tau\n        (im: imap id wf) itr tr\n        (BEH: Beh.of_state im (Tau itr) tr)\n        (NNB: tr <> Tr.nb)\n        (NSPIN: tr <> Tr.spin)\n    :\n    (Beh.of_state im itr tr) /\\\n      (exists evs sti, (observe_state_trace (itr, tr, im) (evs, sti)) /\\\n                    (observe_state (Tau itr, tr, im) = ((inl silentE_tau) :: evs, sti))).\n  Proof.\n    unfold observe_state, epsilon. unfold Epsilon.epsilon. unfold proj1_sig. des_ifs.\n    rename x into rawsttr. clear Heq.\n    hexploit (observe_state_exists). intros OSP. eapply o in OSP; clear o.\n    unfold observe_state_prop in OSP. hexploit OSP; clear OSP; eauto.\n    i. inv H; ss; eauto. hexploit CONT; eauto; i. des. esplits; eauto.\n  Qed.\n\n  Lemma observe_state_tau_spin\n        (im: imap id wf) itr tr\n        (BEH: Beh.of_state im (Tau itr) tr)\n        (NNB: tr <> Tr.nb)\n        (SPIN: tr = Tr.spin)\n    :\n    (Beh.diverge_index im itr) /\\\n      observe_state (Tau itr, tr, im) = ([inl silentE_tau], (itr, tr, im)).\n  Proof.\n    unfold observe_state, epsilon. unfold Epsilon.epsilon. unfold proj1_sig. des_ifs.\n    rename x into rawsttr. clear Heq.\n    hexploit (observe_state_exists). intros OSP. eapply o in OSP; clear o.\n    unfold observe_state_prop in OSP. hexploit OSP; clear OSP; eauto.\n    i. inv H; ss; eauto. hexploit SPIN; ss; i. des; clarify.\n  Qed.\n\n  Lemma observe_state_choose\n        (im: imap id wf) tr X ktr\n        (BEH: Beh.of_state im (Vis (Choose X) ktr) tr)\n        (NNB: tr <> Tr.nb)\n        (NSPIN: tr <> Tr.spin)\n    :\n    exists (x: X),\n      (Beh.of_state im (ktr x) tr) /\\\n        (exists evs sti,\n            (observe_state_trace (ktr x, tr, im) (evs, sti)) /\\\n              (observe_state (Vis (Choose X) ktr, tr, im) = ((inl silentE_tau) :: evs, sti))).\n  Proof.\n    unfold observe_state, epsilon. unfold Epsilon.epsilon. unfold proj1_sig. des_ifs.\n    rename x into rawsttr. clear Heq.\n    hexploit (observe_state_exists). intros OSP. eapply o in OSP; clear o.\n    unfold observe_state_prop in OSP. hexploit OSP; clear OSP; eauto.\n    i. inv H; clarify. eapply inj_pair2 in H0. clarify. hexploit CONT; eauto; i. des. esplits; eauto.\n  Qed.\n\n  Lemma observe_state_choose_spin\n        (im: imap id wf) tr X ktr\n        (BEH: Beh.of_state im (Vis (Choose X) ktr) tr)\n        (NNB: tr <> Tr.nb)\n        (SPIN: tr = Tr.spin)\n    :\n    exists (x: X),\n      (Beh.diverge_index im (ktr x)) /\\\n        (observe_state (Vis (Choose X) ktr, tr, im) = ([inl silentE_tau], (ktr x, tr, im))).\n  Proof.\n    unfold observe_state, epsilon. unfold Epsilon.epsilon. unfold proj1_sig. des_ifs.\n    rename x into rawsttr. clear Heq.\n    hexploit (observe_state_exists). intros OSP. eapply o in OSP; clear o.\n    unfold observe_state_prop in OSP. hexploit OSP; clear OSP; eauto.\n    i. inv H; clarify. eapply inj_pair2 in H0. clarify. hexploit SPIN; eauto; i. des. clarify. eauto.\n  Qed.\n\n  Lemma observe_state_fair\n        (im: imap id wf) tr fm ktr\n        (BEH: Beh.of_state im (Vis (Fair fm) ktr) tr)\n        (NNB: tr <> Tr.nb)\n        (NSPIN: tr <> Tr.spin)\n    :\n    exists (im0: imap id wf),\n      (fair_update im im0 fm) /\\ (Beh.of_state im0 (ktr tt) tr) /\\\n        (exists evs sti,\n            (observe_state_trace (ktr tt, tr, im0) (evs, sti)) /\\\n              (observe_state (Vis (Fair fm) ktr, tr, im) = ((inl (silentE_fair fm)) :: evs, sti))).\n  Proof.\n    unfold observe_state, epsilon. unfold Epsilon.epsilon. unfold proj1_sig. des_ifs.\n    rename x into rawsttr. clear Heq.\n    hexploit (observe_state_exists). intros OSP. eapply o in OSP; clear o.\n    unfold observe_state_prop in OSP. hexploit OSP; clear OSP; eauto.\n    i. inv H; ss; eauto. eapply inj_pair2 in H2. clarify. hexploit CONT; eauto; i. des. esplits; eauto.\n  Qed.\n\n  Lemma observe_state_fair_spin\n        (im: imap id wf) tr fm ktr\n        (BEH: Beh.of_state im (Vis (Fair fm) ktr) tr)\n        (NNB: tr <> Tr.nb)\n        (NSPIN: tr = Tr.spin)\n    :\n    exists (im0: imap id wf),\n      (fair_update im im0 fm) /\\\n        (Beh.diverge_index im0 (ktr tt)) /\\\n        (observe_state (Vis (Fair fm) ktr, tr, im) = ([inl (silentE_fair fm)], (ktr tt, tr, im0))).\n  Proof.\n    unfold observe_state, epsilon. unfold Epsilon.epsilon. unfold proj1_sig. des_ifs.\n    rename x into rawsttr. clear Heq.\n    hexploit (observe_state_exists). intros OSP. eapply o in OSP; clear o.\n    unfold observe_state_prop in OSP. hexploit OSP; clear OSP; eauto.\n    i. inv H; ss; eauto. eapply inj_pair2 in H2. clarify. hexploit SPIN; eauto; i. des. clarify. esplits; eauto.\n  Qed.\n\n  Lemma observe_state_ub\n        (im: imap id wf) tr ktr\n    :\n    observe_state (Vis Undefined ktr, tr, im) = ([], (Vis Undefined ktr, tr, im)).\n  Proof.\n    unfold observe_state, epsilon. unfold Epsilon.epsilon. unfold proj1_sig. des_ifs.\n    rename x into rawsttr. clear Heq.\n    hexploit (observe_state_exists). intros OSP. eapply o in OSP; clear o.\n    unfold observe_state_prop in OSP. hexploit OSP; clear OSP; eauto.\n    i. inv H; eauto. eapply inj_pair2 in H1. clarify.\n  Qed.\n\n  Lemma observe_state_nb\n        (im: imap id wf) itr\n    :\n    observe_state (itr, Tr.nb, im) = ([], (itr, Tr.nb, im)).\n  Proof.\n    unfold observe_state, epsilon. unfold Epsilon.epsilon. unfold proj1_sig. des_ifs.\n    rename x into rawsttr. clear Heq.\n    hexploit (observe_state_exists). intros OSP. eapply o in OSP; clear o.\n    unfold observe_state_prop in OSP. hexploit OSP; clear OSP; eauto.\n    i. inv H; clarify.\n  Qed.\n\n  Lemma observe_state_spin_div\n        (im: imap id wf) itr\n        (DIV: @Beh.diverge_index _ _ R im itr)\n    :\n    observe_state_trace (itr, Tr.spin, im) (observe_state (itr, Tr.spin, im)).\n  Proof.\n    punfold DIV. inv DIV.\n    - pclearbot. hexploit observe_state_tau_spin; ss. 2:ss.\n      2:{ i. des. setoid_rewrite H0; clear H0. econs; ss. }\n      pfold. econs; eauto. pfold. econs; eauto.\n    - pclearbot. hexploit observe_state_choose_spin; ss. 2: ss.\n      2:{ i. des. setoid_rewrite H0; clear H0. econs; eauto; ss. }\n      pfold. econs; eauto. pfold. econs; eauto.\n    - pclearbot. hexploit observe_state_fair_spin; ss. 2: ss.\n      2:{ i. des. setoid_rewrite H1; clear H1. econs; eauto; ss. }\n      pfold. econs; eauto. pfold. econs; eauto.\n    - rewrite observe_state_ub. econs; eauto.\n  Qed.\n\n  Lemma observe_state_spin\n        (im: imap id wf) itr\n        (BEH: @Beh.of_state _ _ R im itr Tr.spin)\n    :\n    observe_state_trace (itr, Tr.spin, im) (observe_state (itr, Tr.spin, im)).\n  Proof.\n    remember Tr.spin as tr. revert Heqtr. induction BEH using @Beh.of_state_ind2; i; ss.\n    - eapply observe_state_spin_div; eauto.\n    - clarify. hexploit observe_state_tau_spin; ss. 2: ss.\n      2:{ i. des. setoid_rewrite H0; clear H0. econs; ss. }\n      pfold. econs 5. punfold BEH.\n    - clarify. hexploit observe_state_choose_spin; ss. 2: ss.\n      2:{ i. des. setoid_rewrite H0; clear H0. econs; ss. i. splits; eauto. }\n      pfold. econs 6. punfold BEH.\n    - clarify. hexploit observe_state_fair_spin; ss. 2: ss.\n      2:{ i. des. setoid_rewrite H1; clear H1. econs; ss; eauto. }\n      pfold. econs 7; eauto. punfold BEH.\n    - clarify. rewrite observe_state_ub. econs.\n  Qed.\n\n  Theorem observe_state_spec\n          (sti: st_tr_im)\n    :\n    observe_state_prop sti (observe_state sti).\n  Proof.\n    destruct sti as [[st tr] im]. ii. rename H into BEH.\n    ides st.\n    - punfold BEH. inv BEH.\n      + rewrite observe_state_ret. econs.\n      + punfold SPIN. inv SPIN.\n      + rewrite observe_state_nb. econs.\n    - destruct (classic (tr = Tr.nb)) as [NB | NNB]; clarify.\n      { rewrite observe_state_nb. econs. }\n      destruct (classic (tr = Tr.spin)) as [SPIN | NSPIN]; clarify.\n      { eapply observe_state_spin; eauto. }\n      hexploit observe_state_tau; ss.\n      4:{ i; des. setoid_rewrite H1; clear H1. econs; ss. }\n      all: eauto.\n    - destruct e.\n      + destruct (classic (tr = Tr.nb)) as [NB | NNB]; clarify.\n        { rewrite observe_state_nb. econs. }\n        destruct (classic (tr = Tr.spin)) as [SPIN | NSPIN]; clarify.\n        { eapply observe_state_spin; eauto. }\n        hexploit observe_state_choose; ss.\n        4:{ i; des. setoid_rewrite H1; clear H1. econs; ss. all: eauto. }\n        all: eauto.\n      + destruct (classic (tr = Tr.nb)) as [NB | NNB]; clarify.\n        { rewrite observe_state_nb. econs. }\n        destruct (classic (tr = Tr.spin)) as [SPIN | NSPIN]; clarify.\n        { eapply observe_state_spin; eauto. }\n        hexploit observe_state_fair; ss.\n        4:{ i; des. setoid_rewrite H2; clear H2. econs; ss. all: eauto. }\n        all: eauto.\n      + destruct (classic (tr = Tr.nb)) as [NB | NNB]; clarify.\n        { rewrite observe_state_nb. econs. }\n        destruct (classic (tr = Tr.spin)) as [SPIN | NSPIN]; clarify.\n        { eapply observe_state_spin; eauto. }\n        punfold BEH. inv BEH; ss. eapply inj_pair2 in H3. clarify. pclearbot.\n        rewrite observe_state_obs; eauto. econs.\n      + rewrite observe_state_ub. econs.\n  Qed.\n\n  Lemma observe_state_trace_preserves\n        st0 tr0 im0 evs st1 tr1 im1\n        (BEH: Beh.of_state im0 st0 tr0)\n        (OST: observe_state_trace (st0, tr0, im0) (evs, (st1, tr1, im1)))\n    :\n    Beh.of_state im1 st1 tr1.\n  Proof.\n    remember (st0, tr0, im0) as sti0. remember (evs, (st1, tr1, im1)) as esti1.\n    move OST before wf0. revert_until OST.\n    induction OST; i; ss; clarify.\n    { punfold BEH. inv BEH. eapply inj_pair2 in H3. clarify. pclearbot. eauto. }\n    { destruct (classic (tr0 = Tr.spin)) as [TRS | TRNS]; clarify.\n      { hexploit SPIN; eauto. i; des; clarify. pfold. econs. eauto. }\n      eapply H. ss. 2,3: eauto. eauto.\n    }\n    { destruct (classic (tr0 = Tr.spin)) as [TRS | TRNS]; clarify.\n      { hexploit SPIN; eauto. i; des; clarify. pfold. econs. eauto. }\n      eapply H. ss. 2,3: eauto. eauto.\n    }\n    { destruct (classic (tr0 = Tr.spin)) as [TRS | TRNS]; clarify.\n      { hexploit SPIN; eauto. i; des; clarify. pfold. econs. eauto. }\n      eapply H. ss. 2,3: eauto. eauto.\n    }\n  Qed.\n\n\n  (** sti2raw reduction lemmas **)\n  Lemma _sti2raw_red_evs\n        (evs: list rawE) (sti: st_tr_im)\n    :\n    _sti2raw evs sti = RawTr.app evs (sti2raw sti).\n  Proof.\n    revert sti. induction evs; i. ss.\n    match goal with | |- ?lhs = _ => replace lhs with (RawTr.ob lhs) end.\n    2:{ symmetry. apply RawTr.ob_eq. }\n    ss. f_equal. eauto.\n  Qed.\n\n  Lemma sti2raw_red_ret\n        (im: imap id wf) (retv: R)\n    :\n    sti2raw (Ret retv, Tr.done retv, im) = RawTr.done retv.\n  Proof.\n    match goal with | |- ?lhs = _ => replace lhs with (RawTr.ob lhs) end.\n    2:{ symmetry. apply RawTr.ob_eq. }\n    ss. rewrite observe_state_ret. ss.\n  Qed.\n\n  Lemma sti2raw_red_nb\n        (im: imap id wf) (st: @state _ R)\n    :\n    sti2raw (st, Tr.nb, im) = RawTr.nb.\n  Proof.\n    match goal with | |- ?lhs = _ => replace lhs with (RawTr.ob lhs) end.\n    2:{ symmetry. apply RawTr.ob_eq. }\n    ss. rewrite observe_state_nb. ss. des_ifs.\n  Qed.\n\n  Lemma sti2raw_red_ub\n        (im: imap id wf) ktr tr\n        (NNB: tr <> Tr.nb)\n    :\n    sti2raw (Vis Undefined ktr, tr, im) = tr2raw tr.\n  Proof.\n    match goal with | |- ?lhs = _ => replace lhs with (RawTr.ob lhs) end.\n    2:{ symmetry. apply RawTr.ob_eq. }\n    ss. rewrite observe_state_ub. ss.\n    match goal with | |- _ = ?rhs => replace rhs with (RawTr.ob rhs) end.\n    2:{ symmetry. apply RawTr.ob_eq. }\n    ss. des_ifs.\n  Qed.\n\n  Ltac ireplace H := symmetry in H; apply simpobs in H; apply bisim_is_eq in H; rewrite H; clarify.\n\n  Lemma sti2raw_red_aux\n        st0 tr0 im0 ev evs\n        (BEH: Beh.of_state im0 st0 tr0)\n    :\n    match\n      match _observe st0 with\n      | RetF _ =>\n          match tr0 with\n          | Tr.done retv => RawTr.cons ev (RawTr.app evs (RawTr.done retv))\n          | Tr.nb => RawTr.cons ev (RawTr.app evs RawTr.nb)\n          | _ => RawTr.cons ev (_sti2raw evs (st0, tr0, im0))\n          end\n      | VisF Undefined _ =>\n          match tr0 with\n          | Tr.nb => RawTr.cons ev (RawTr.app evs RawTr.nb)\n          | _ => RawTr.cons ev (RawTr.app evs (tr2raw tr0))\n          end\n      | _ =>\n          match tr0 with\n          | Tr.nb => RawTr.cons ev (RawTr.app evs RawTr.nb)\n          | _ => RawTr.cons ev (_sti2raw evs (st0, tr0, im0))\n          end\n      end\n    with\n    | RawTr.done retv => RawTr.done retv\n    | RawTr.ub => RawTr.ub\n    | RawTr.nb => RawTr.nb\n    | RawTr.cons ev tl => RawTr.cons ev tl\n    end = RawTr.cons ev (RawTr.app evs (sti2raw (st0, tr0, im0))).\n  Proof.\n    destruct (_observe st0) eqn:EQ.\n    - ireplace EQ. destruct tr0 eqn:TR; ss; clarify.\n      + punfold BEH. inv BEH. rewrite sti2raw_red_ret. ss.\n      + punfold BEH. inv BEH. punfold SPIN. inv SPIN.\n      + punfold BEH. inv BEH.\n      + rewrite sti2raw_red_nb. ss.\n      + punfold BEH. inv BEH.\n    - ireplace EQ. destruct tr0 eqn:TR; ss; clarify.\n      + rewrite _sti2raw_red_evs. ss.\n      + rewrite _sti2raw_red_evs. ss.\n      + rewrite _sti2raw_red_evs. ss.\n      + rewrite sti2raw_red_nb. ss.\n      + rewrite _sti2raw_red_evs. ss.\n    - ireplace EQ. destruct e eqn:EV; ss; clarify.\n      { destruct tr0 eqn:TR; ss; clarify.\n        - rewrite _sti2raw_red_evs. ss.\n        - rewrite _sti2raw_red_evs. ss.\n        - rewrite _sti2raw_red_evs. ss.\n        - rewrite sti2raw_red_nb. ss.\n        - rewrite _sti2raw_red_evs. ss.\n      }\n      { destruct tr0 eqn:TR; ss; clarify.\n        - rewrite _sti2raw_red_evs. ss.\n        - rewrite _sti2raw_red_evs. ss.\n        - rewrite _sti2raw_red_evs. ss.\n        - rewrite sti2raw_red_nb. ss.\n        - rewrite _sti2raw_red_evs. ss.\n      }\n      { destruct tr0 eqn:TR; ss; clarify.\n        - rewrite _sti2raw_red_evs. ss.\n        - rewrite _sti2raw_red_evs. ss.\n        - rewrite _sti2raw_red_evs. ss.\n        - rewrite sti2raw_red_nb. ss.\n        - rewrite _sti2raw_red_evs. ss.\n      }\n      { destruct tr0 eqn:TR; ss; clarify.\n        - rewrite sti2raw_red_ub; ss.\n        - rewrite sti2raw_red_ub; ss.\n        - rewrite sti2raw_red_ub; ss.\n        - rewrite sti2raw_red_nb. ss.\n        - rewrite sti2raw_red_ub; ss.\n      }\n  Qed.\n\n  Lemma sti2raw_red_aux2\n        st0 tr0 im0 ev\n        (BEH: Beh.of_state im0 st0 tr0)\n    :\n    match\n      match _observe st0 with\n      | RetF _ =>\n          match tr0 with\n          | Tr.done retv => RawTr.cons ev (RawTr.done retv)\n          | Tr.nb => RawTr.cons ev RawTr.nb\n          | _ => RawTr.cons ev (sti2raw (st0, tr0, im0))\n          end\n      | VisF Undefined _ =>\n          match tr0 with\n          | Tr.nb => RawTr.cons ev RawTr.nb\n          | _ => RawTr.cons ev (tr2raw tr0)\n          end\n      | _ =>\n          match tr0 with\n          | Tr.nb => RawTr.cons ev RawTr.nb\n          | _ => RawTr.cons ev (sti2raw (st0, tr0, im0))\n          end\n      end\n    with\n    | RawTr.done retv => RawTr.done retv\n    | RawTr.ub => RawTr.ub\n    | RawTr.nb => RawTr.nb\n    | RawTr.cons ev tl => RawTr.cons ev tl\n    end = RawTr.cons ev (sti2raw (st0, tr0, im0)).\n  Proof.\n    hexploit sti2raw_red_aux; eauto. i. instantiate (1:=[]) in H. ss. eauto.\n  Qed.\n\n  Lemma sti2raw_red_obs\n        (im: imap id wf) fn args rv tl ktr\n        (BEH: Beh.of_state im (ktr rv) tl)\n    :\n    sti2raw (Vis (Observe fn args) ktr, Tr.cons (obsE_syscall fn args rv) tl, im) =\n      RawTr.cons (inr (obsE_syscall fn args rv)) (sti2raw (ktr rv, tl, im)).\n  Proof.\n    match goal with | |- ?lhs = _ => replace lhs with (RawTr.ob lhs) end.\n    2:{ symmetry. apply RawTr.ob_eq. }\n    ss. rewrite observe_state_obs; eauto.\n    eapply sti2raw_red_aux; eauto.\n  Qed.\n\n  Lemma sti2raw_red_tau\n        (im: imap id wf) itr tr\n        (BEH: Beh.of_state im (Tau itr) tr)\n        (NNB: tr <> Tr.nb)\n        (NSPIN: tr <> Tr.spin)\n    :\n    (Beh.of_state im itr tr) /\\\n      exists evs sti,\n        observe_state_trace (itr, tr, im) (evs, sti) /\\\n          (sti2raw (Tau itr, tr, im) =\n             RawTr.app ((inl silentE_tau) :: evs) (sti2raw sti)).\n  Proof.\n    hexploit observe_state_tau; eauto. i. des. split; eauto. esplits; eauto.\n    match goal with | |- ?lhs = _ => replace lhs with (RawTr.ob lhs) end.\n    2:{ symmetry. apply RawTr.ob_eq. }\n    ss. rewrite H1; clear H1. destruct sti as [[st0 tr0] im0].\n    ss. eapply sti2raw_red_aux. eapply observe_state_trace_preserves; eauto.\n  Qed.\n\n  Lemma sti2raw_red_tau_spin\n        (im: imap id wf) itr tr\n        (BEH: Beh.of_state im (Tau itr) tr)\n        (NNB: tr <> Tr.nb)\n        (SPIN: tr = Tr.spin)\n    :\n    (Beh.diverge_index im itr) /\\\n      (sti2raw (Tau itr, tr, im) =\n         RawTr.cons (inl silentE_tau) (sti2raw (itr, tr, im))).\n  Proof.\n    hexploit observe_state_tau_spin; eauto. i. des. split; eauto.\n    match goal with | |- ?lhs = _ => replace lhs with (RawTr.ob lhs) end.\n    2:{ symmetry. apply RawTr.ob_eq. }\n    ss. rewrite H0; clear H0.\n    ss. eapply sti2raw_red_aux2. clarify. pfold. econs. eauto.\n  Qed.\n\n  Lemma sti2raw_red_choose\n        (im: imap id wf) tr X ktr\n        (BEH: Beh.of_state im (Vis (Choose X) ktr) tr)\n        (NNB: tr <> Tr.nb)\n        (NSPIN: tr <> Tr.spin)\n    :\n    exists x,\n      (Beh.of_state im (ktr x) tr) /\\\n        exists evs sti,\n          observe_state_trace (ktr x, tr, im) (evs, sti) /\\\n            (sti2raw (Vis (Choose X) ktr, tr, im) =\n               RawTr.app ((inl silentE_tau) :: evs) (sti2raw sti)).\n  Proof.\n    hexploit observe_state_choose; eauto. i. des. esplits; eauto.\n    match goal with | |- ?lhs = _ => replace lhs with (RawTr.ob lhs) end.\n    2:{ symmetry. apply RawTr.ob_eq. }\n    ss. rewrite H1; clear H1. destruct sti as [[st0 tr0] im0].\n    ss. eapply sti2raw_red_aux. eapply observe_state_trace_preserves; eauto.\n  Qed.\n\n  Lemma sti2raw_red_choose_spin\n        (im: imap id wf) tr X ktr\n        (BEH: Beh.of_state im (Vis (Choose X) ktr) tr)\n        (NNB: tr <> Tr.nb)\n        (SPIN: tr = Tr.spin)\n    :\n    exists x,\n      (Beh.diverge_index im (ktr x)) /\\\n        (sti2raw (Vis (Choose X) ktr, tr, im) =\n           RawTr.cons (inl silentE_tau) (sti2raw (ktr x, tr, im))).\n  Proof.\n    hexploit observe_state_choose_spin; eauto. i. des. esplits; eauto.\n    match goal with | |- ?lhs = _ => replace lhs with (RawTr.ob lhs) end.\n    2:{ symmetry. apply RawTr.ob_eq. }\n    ss. rewrite H0; clear H0.\n    ss. eapply sti2raw_red_aux2. clarify. pfold. econs; eauto.\n  Qed.\n\n  Lemma sti2raw_red_fair\n        (im: imap id wf) tr fm ktr\n        (BEH: Beh.of_state im (Vis (Fair fm) ktr) tr)\n        (NNB: tr <> Tr.nb)\n        (NSPIN: tr <> Tr.spin)\n    :\n    exists (im0: imap id wf),\n      (fair_update im im0 fm) /\\\n        (Beh.of_state im0 (ktr tt) tr) /\\\n        exists evs sti,\n          observe_state_trace (ktr tt, tr, im0) (evs, sti) /\\\n            (sti2raw (Vis (Fair fm) ktr, tr, im) =\n               RawTr.app ((inl (silentE_fair fm)) :: evs) (sti2raw sti)).\n  Proof.\n    hexploit observe_state_fair; eauto. i. des. esplits; eauto.\n    match goal with | |- ?lhs = _ => replace lhs with (RawTr.ob lhs) end.\n    2:{ symmetry. apply RawTr.ob_eq. }\n    ss. rewrite H2; clear H2. destruct sti as [[st0 tr0] im1].\n    ss. eapply sti2raw_red_aux. eapply observe_state_trace_preserves; eauto.\n  Qed.\n\n  Lemma sti2raw_red_fair_spin\n        (im: imap id wf) tr fm ktr\n        (BEH: Beh.of_state im (Vis (Fair fm) ktr) tr)\n        (NNB: tr <> Tr.nb)\n        (SPIN: tr = Tr.spin)\n    :\n    exists (im0: imap id wf),\n      (fair_update im im0 fm) /\\\n        (Beh.diverge_index im0 (ktr tt)) /\\\n        (sti2raw (Vis (Fair fm) ktr, tr, im) =\n           RawTr.cons (inl (silentE_fair fm)) (sti2raw (ktr tt, tr, im0))).\n  Proof.\n    hexploit observe_state_fair_spin; eauto. i. des. esplits; eauto.\n    match goal with | |- ?lhs = _ => replace lhs with (RawTr.ob lhs) end.\n    2:{ symmetry. apply RawTr.ob_eq. }\n    ss. rewrite H1; clear H1.\n    ss. eapply sti2raw_red_aux2. clarify. pfold. econs; eauto.\n  Qed.\n\n\n\n  Lemma sti2raw_exists\n        st0 tr0 im0\n        (BEH: Beh.of_state im0 st0 tr0)\n    :\n    exists evs st1 tr1 im1,\n      (sti2raw (st0, tr0, im0) = RawTr.app evs (sti2raw (st1, tr1, im1))) /\\\n        (observe_state_trace (st0, tr0, im0) (evs, (st1, tr1, im1))).\n  Proof.\n    induction BEH using @Beh.of_state_ind2.\n    { exists []. ss. esplits; eauto. econs. }\n    { punfold H. inv H.\n      { pclearbot. hexploit sti2raw_red_tau_spin.\n        4:{ i; des. rewrite H0; clear H0.\n            match goal with | |- exists _ _ _ _, (RawTr.cons ?ev _ = _) /\\ _ => exists [ev] end.\n            ss. esplits; eauto. econs; ss. }\n        all: ss. pfold. econs. pfold; econs; eauto.\n      }\n      { pclearbot. hexploit sti2raw_red_choose_spin.\n        4:{ i; des. rewrite H0; clear H0.\n            match goal with | |- exists _ _ _ _, (RawTr.cons ?ev _ = _) /\\ _ => exists [ev] end.\n            ss. esplits; eauto. econs; ss. i; eauto. }\n        all: ss. pfold. econs. pfold; econs; eauto.\n      }\n      { pclearbot. hexploit sti2raw_red_fair_spin.\n        4:{ i; des. rewrite H1; clear H1.\n            match goal with | |- exists _ _ _ _, (RawTr.cons ?ev _ = _) /\\ _ => exists [ev] end.\n            ss. esplits; eauto. econs; ss; eauto. }\n        all: ss. pfold. econs. pfold; econs; eauto.\n      }\n      { hexploit sti2raw_red_ub.\n        2:{ i; des. eexists. exists (Vis Undefined ktr), (Tr.spin), (imap0).\n            rewrite ! H. instantiate (1:=[]). ss. split; eauto. econs. }\n        all: ss. }\n    }\n    { exists []. ss. esplits; eauto. econs. }\n    { rewrite sti2raw_red_obs; eauto. exists [inr (obsE_syscall fn args rv)]. ss.\n      esplits; eauto. econs. }\n    { destruct (classic (tr = Tr.nb)) as [NB | NNB]; clarify.\n      { des. exists []. ss. esplits; eauto. econs. }\n      destruct (classic (tr = Tr.spin)) as [TRS | TRNS]; clarify.\n      { des. hexploit sti2raw_red_tau_spin.\n        4:{ i; des. rewrite H0; clear H0. exists [inl silentE_tau]. ss. esplits; eauto. econs; ss. }\n        all: ss. eapply Beh.beh_tau0; eauto. }\n      des. hexploit sti2raw_red_tau.\n      4:{ i; des. rewrite H1; clear H1. destruct sti as [[st0 tr0] im0]. esplits; eauto.\n          econs; ss. }\n      all: ss. eapply Beh.beh_tau0; eauto.\n    }\n    { destruct (classic (tr = Tr.nb)) as [NB | NNB]; clarify.\n      { des. exists []. ss. esplits; eauto. econs. }\n      destruct (classic (tr = Tr.spin)) as [TRS | TRNS]; clarify.\n      { des. hexploit sti2raw_red_choose_spin.\n        4:{ i; des. rewrite H0; clear H0. exists [inl silentE_tau]. ss. esplits; eauto. econs; ss.\n            i; splits; eauto. }\n        all: ss. eapply Beh.beh_choose0; eauto. }\n      des. hexploit sti2raw_red_choose.\n      4:{ i; des. rewrite H1; clear H1. destruct sti as [[st0 tr0] im0]. esplits; eauto.\n          econs; ss; eauto. }\n      all: ss. eapply Beh.beh_choose0; eauto.\n    }\n    { destruct (classic (tr = Tr.nb)) as [NB | NNB]; clarify.\n      { des. exists []. ss. esplits; eauto. econs. }\n      destruct (classic (tr = Tr.spin)) as [TRS | TRNS]; clarify.\n      { des. hexploit sti2raw_red_fair_spin.\n        4:{ i; des. rewrite H1; clear H1. exists [inl (silentE_fair fmap)]. ss. esplits; eauto.\n            econs; ss; eauto. }\n        all: ss. eapply Beh.beh_fair; eauto. }\n      des. hexploit sti2raw_red_fair.\n      4:{ i; des. rewrite H2; clear H2. destruct sti as [[nst ntr] nim]. esplits; eauto.\n          econs; ss; eauto. }\n      all: ss. eapply Beh.beh_fair; eauto.\n    }\n    { destruct (classic (tr = Tr.nb)) as [NB | NNB]; clarify.\n      { des. exists []. ss. esplits; eauto. econs. }\n      hexploit sti2raw_red_ub.\n      2:{ i; des. exists [], (Vis Undefined ktr), tr, imap0. rewrite ! H. ss. split; eauto. econs. }\n      all: ss.\n    }\n  Qed.\n\n  Lemma sti2raw_raw_beh_spin\n        (im: imap id wf) st\n        (DIV: Beh.diverge_index im st)\n    :\n    RawBeh.of_state (R:=R) st (sti2raw (st, Tr.spin, im)).\n  Proof.\n    revert_until wf0. pcofix CIH. i. punfold DIV. inv DIV.\n    - pclearbot. hexploit sti2raw_red_tau_spin.\n      4:{ i; des. rewrite H0; clear H0. pfold. econs. eauto. }\n      2,3: ss. pfold. econs. pfold. econs. eauto.\n    - pclearbot. hexploit sti2raw_red_choose_spin.\n      4:{ i; des. rewrite H0; clear H0. pfold. econs. eauto. }\n      2,3: ss. pfold. econs. pfold. econs. eauto.\n    - pclearbot. hexploit sti2raw_red_fair_spin.\n      4:{ i; des. rewrite H1; clear H1. pfold. econs. eauto. }\n      2,3: ss. pfold. econs. pfold. econs; eauto.\n    - hexploit sti2raw_red_ub.\n      2:{ i; des. rewrite H; clear H. pfold. econs. }\n      all: ss.\n  Qed.\n\n  Theorem sti2raw_raw_beh\n          (im0: imap id wf) st0 tr0\n          (BEH: Beh.of_state im0 st0 tr0)\n    :\n    RawBeh.of_state (R:=R) st0 (sti2raw (st0, tr0, im0)).\n  Proof.\n    revert_until wf0. pcofix CIH; i.\n    hexploit sti2raw_exists; eauto. i. des. rewrite H; clear H. rename H0 into OST.\n    remember (st0, tr0, im0) as sti0. remember (evs, (st1, tr1, im1)) as esti1.\n    move OST before CIH. revert_until OST. induction OST; i; ss; clarify.\n    { ss. rewrite sti2raw_red_ret. pfold. econs. }\n    { ss. pfold. econs. punfold BEH. inv BEH. eapply inj_pair2 in H3; clarify.\n      pclearbot. eauto. }\n    { destruct (classic (tr0 = Tr.spin)) as [TRS | TRNS]; clarify.\n      { hexploit SPIN; clear SPIN; eauto. i; des; clarify. ss.\n        pfold. econs. right; eapply CIH. pfold. econs; eauto. }\n      clear SPIN. ss. pfold. econs. left. eapply H; eauto.\n    }\n    { destruct (classic (tr0 = Tr.spin)) as [TRS | TRNS]; clarify.\n      { hexploit SPIN; clear SPIN; eauto. i; des; clarify. ss.\n        pfold. econs. right; eapply CIH. pfold. econs; eauto. }\n      clear SPIN. ss. pfold. econs. left. eapply H; eauto.\n    }\n    { destruct (classic (tr0 = Tr.spin)) as [TRS | TRNS]; clarify.\n      { hexploit SPIN; clear SPIN; eauto. i; des; clarify. ss.\n        pfold. econs. right; eapply CIH. pfold. econs; eauto. }\n      clear SPIN. ss. pfold. econs. left. eapply H; eauto.\n    }\n    { ss. pfold. econs. }\n    { ss. rewrite sti2raw_red_nb. pfold. econs. }\n  Qed.\n\n\n\n  Lemma sti2raw_raw_spin\n        itr im\n        (DIV: @Beh.diverge_index _ wf R im itr)\n    :\n    raw_spin (sti2raw (itr, Tr.spin, im)).\n  Proof.\n    revert_until wf0. pcofix CIH; i. punfold DIV. inv DIV.\n    - pclearbot. hexploit sti2raw_red_tau_spin.\n      4:{ i; des. rewrite H0; clear H0. pfold. econs. eauto. }\n      all: ss. pfold. econs. pfold. econs. eauto.\n    - pclearbot. hexploit sti2raw_red_choose_spin.\n      4:{ i; des. rewrite H0; clear H0. pfold. econs. eauto. }\n      all: ss. pfold. econs. pfold. econs. eauto.\n    - pclearbot. hexploit sti2raw_red_fair_spin.\n      4:{ i; des. rewrite H1; clear H1. pfold. econs. eauto. }\n      all: ss. pfold. econs. pfold. econs; eauto.\n    - hexploit sti2raw_red_ub.\n      2:{ i; des. rewrite H; clear H. rewrite tr2raw_red_spin.\n          eapply paco2_mon. eapply raw_spin_trace_spec. ss. }\n      all: ss.\n  Qed.\n\n  Lemma sti2raw_extract_spin\n        st im\n        (DIV: @Beh.diverge_index _ wf R im st)\n    :\n    extract_tr (sti2raw (st, Tr.spin, im)) Tr.spin.\n  Proof.\n    punfold DIV. inv DIV.\n    - pclearbot. hexploit sti2raw_red_tau_spin.\n      4:{ i; des. rewrite H0; clear H0. pfold. econs. pfold. econs.\n          left. eapply sti2raw_raw_spin; eauto. }\n      all: ss. pfold. econs. pfold. econs; eauto.\n    - pclearbot. hexploit sti2raw_red_choose_spin.\n      4:{ i; des. rewrite H0; clear H0. pfold. econs. pfold. econs.\n          left. eapply sti2raw_raw_spin; eauto. }\n      all: ss. pfold. econs. pfold. econs; eauto.\n    - pclearbot. hexploit sti2raw_red_fair_spin.\n      4:{ i; des. rewrite H1; clear H1. pfold. econs. pfold. econs.\n          left. eapply sti2raw_raw_spin; eauto. }\n      all: ss. pfold. econs. pfold. econs; eauto.\n    - hexploit sti2raw_red_ub.\n      2:{ i; des. rewrite H; clear H. rewrite tr2raw_red_spin.\n          pfold. econs. eapply raw_spin_trace_spec. }\n      all: ss.\n  Qed.\n\n  Theorem sti2raw_extract\n          st0 tr0 im0\n          (BEH: Beh.of_state im0 st0 tr0)\n    :\n    extract_tr (sti2raw (st0, tr0, im0)) tr0.\n  Proof.\n    ginit. revert_until wf0. gcofix CIH. i.\n    destruct (classic (tr0 = Tr.spin)) as [TRS | TRNS]; clarify.\n    { gfinal. right. eapply paco3_mon. eapply sti2raw_extract_spin.\n      eapply beh_implies_spin; eauto. ss. }\n    hexploit sti2raw_exists; eauto. i; des. rewrite H; clear H. rename H0 into OST.\n    remember (st0, tr0, im0) as sti0. remember (evs, (st1, tr1, im1)) as esti1.\n    move OST before CIH. revert_until OST. induction OST; i; ss; clarify.\n    { ss. rewrite sti2raw_red_ret. guclo extract_tr_indC_spec. econs. }\n    { punfold BEH. inv BEH. eapply inj_pair2 in H3. clarify. ss. pclearbot.\n      gfinal. right. pfold. econs. eauto. }\n    { ss. guclo extract_tr_indC_spec. econs. eauto. }\n    { ss. guclo extract_tr_indC_spec. econs. eauto. }\n    { ss. guclo extract_tr_indC_spec. econs. eauto. }\n    { ss. gfinal. right.\n      destruct (classic (tr0 = Tr.nb)) as [NB | NNB]; clarify.\n      { rewrite sti2raw_red_nb. eauto. }\n      rewrite sti2raw_red_ub; ss. eapply paco3_mon. eapply extract_tr_tr2raw. ss.\n    }\n    { ss. gfinal. right. rewrite sti2raw_red_nb. eauto. }\n  Qed.\n\nEnd ExtractRaw.\n\n\n\nSection FAIR.\n\n  Variable id: ID.\n  Variable wf: WF.\n  Variable wf0: T wf.\n  Variable R: Type.\n\n  Lemma raw_spin_trace_fair\n        im\n    :\n    RawTr.fair_ord (id:=id) (wf:=wf) im (raw_spin_trace id R).\n  Proof.\n    revert_until R. pcofix CIH; i. rewrite raw_spin_trace_red.\n    pfold. econs; eauto.\n  Qed.\n\n  Lemma tr2raw_fair\n        im tr\n    :\n    RawTr.fair_ord (wf:=wf) (R:=R) im (tr2raw id tr).\n  Proof.\n    revert_until R. pcofix CIH; i. replace (tr2raw id tr) with (RawTr.ob (tr2raw id tr)).\n    2:{ symmetry. apply RawTr.ob_eq. }\n    ss. destruct tr eqn:TR; clarify.\n    { pfold. econs. }\n    { rewrite raw_spin_trace_red. pfold. econs. left.\n      eapply paco3_mon. eapply raw_spin_trace_fair. ss. }\n    { pfold; econs. }\n    { pfold; econs. }\n    { pfold. econs; eauto. }\n  Qed.\n\n  Theorem sti2raw_preserves_fairness\n          (st: @state _ R) (im: imap id wf) tr\n          (BEH: Beh.of_state im st tr)\n    :\n    RawTr.is_fair_ord wf (sti2raw wf0 (st, tr, im)).\n  Proof.\n    rr. exists im. revert_until R. pcofix CIH; i.\n    hexploit sti2raw_exists; eauto. i. des. rewrite H; clear H. rename H0 into OST.\n    remember (st, tr, im) as sti. remember (evs, (st1, tr1, im1)) as esti1.\n    move OST before CIH. revert_until OST. induction OST; i; ss; clarify; ss.\n    { rewrite @sti2raw_red_ret. pfold. econs. }\n    { punfold BEH. inv BEH. eapply inj_pair2 in H3; clarify. pclearbot. pfold. econs; eauto. }\n    { destruct (classic (tr0 = Tr.spin)) as [TRS | TRNS]; clarify.\n      { hexploit SPIN; clear SPIN; eauto. i; des; clarify. ss.\n        pfold. econs. right; eapply CIH. pfold. econs; eauto. }\n      clear SPIN. pfold. econs; eauto.\n    }\n    { destruct (classic (tr0 = Tr.spin)) as [TRS | TRNS]; clarify.\n      { hexploit SPIN; clear SPIN; eauto. i; des; clarify. ss.\n        pfold. econs. right; eapply CIH. pfold. econs; eauto. }\n      clear SPIN. pfold. econs; eauto.\n    }\n    { destruct (classic (tr0 = Tr.spin)) as [TRS | TRNS]; clarify.\n      { hexploit SPIN; clear SPIN; eauto. i; des; clarify. ss.\n        pfold. econs; eauto. right; eapply CIH. pfold. econs; eauto. }\n      clear SPIN. pfold. econs; eauto.\n    }\n    { destruct (classic (tr0 = Tr.nb)) as [NB | NNB]; clarify.\n      { rewrite @sti2raw_red_nb. pfold; econs. }\n      rewrite @sti2raw_red_ub; eauto. eapply paco3_mon. eapply tr2raw_fair. ss.\n    }\n    { rewrite @sti2raw_red_nb. pfold; econs. }\n  Qed.\n\n  Lemma fair_spin_diverge_index\n        st im raw\n        (RSPIN: raw_spin raw)\n        (BEH: RawBeh.of_state st raw)\n        (FAIR: RawTr.fair_ord im raw)\n    :\n    Beh.diverge_index (id:=id) (wf:=wf) (R:=R) im st.\n  Proof.\n    revert_until R. pcofix CIH; i. punfold BEH. inv BEH.\n    { punfold RSPIN. inv RSPIN. }\n    { punfold RSPIN. inv RSPIN. }\n    { punfold RSPIN. inv RSPIN. }\n    { punfold RSPIN. inv RSPIN. punfold FAIR. inv FAIR. pclearbot. rr in TL1. des; ss.\n      pfold. econs; eauto. }\n    { punfold RSPIN. inv RSPIN. punfold FAIR. inv FAIR. pclearbot. rr in TL1. des; ss.\n      pfold. econs; eauto. }\n    { punfold RSPIN. inv RSPIN. punfold FAIR. inv FAIR. pclearbot. rr in TL1. des; ss.\n      pfold. econs; eauto. }\n    { pfold. econs. }\n  Qed.\n\n  Lemma rawbeh_extract_is_beh_fix\n        (st: state (R:=R)) (raw: RawTr.t (R:=R)) tr (im: imap id wf)\n        (BEH0: RawBeh.of_state st raw)\n        (FAIR: RawTr.fair_ord im raw)\n        (EXT: extract_tr raw tr)\n    :\n    Beh.of_state im st tr.\n  Proof.\n    ginit. revert_until R. gcofix CIH; i.\n    move EXT before CIH. revert_until EXT. induction EXT using @extract_tr_ind2; i.\n    { punfold BEH0. inv BEH0.\n      { guclo Beh.of_state_indC_spec. econs. }\n      { guclo Beh.of_state_indC_spec. econs. }\n    }\n    { guclo Beh.of_state_indC_spec. econs. eapply fair_spin_diverge_index; eauto. }\n    { punfold BEH0. inv BEH0. guclo Beh.of_state_indC_spec. econs. }\n    { guclo Beh.of_state_indC_spec. econs. }\n    { punfold BEH0. inv BEH0.\n      { pclearbot. gfinal. right. pfold. econs. right. eapply CIH. eauto. all: eauto.\n        punfold FAIR. inv FAIR. pclearbot. eauto. }\n      { guclo Beh.of_state_indC_spec. econs. }\n    }\n    { punfold BEH0. inv BEH0.\n      { punfold FAIR. inv FAIR. pclearbot. guclo Beh.of_state_indC_spec. econs; eauto. }\n      { punfold FAIR. inv FAIR. pclearbot. guclo Beh.of_state_indC_spec. econs; eauto. }\n      { punfold FAIR. inv FAIR. pclearbot. guclo Beh.of_state_indC_spec. econs; eauto. }\n      { guclo Beh.of_state_indC_spec. econs. }\n    }\n  Qed.\n\n  Theorem rawbeh_extract_is_beh\n          (st: state (R:=R)) (raw: RawTr.t (R:=R)) tr\n          (BEH: RawBeh.of_state_fair_ord (wf:=wf) st raw)\n          (EXT: extract_tr raw tr)\n    :\n    exists (im: imap id wf), Beh.of_state im st tr.\n  Proof.\n    rr in BEH. des. rr in FAIR. des.\n    hexploit rawbeh_extract_is_beh_fix; eauto.\n  Qed.\n\nEnd FAIR.\n\n\n\nSection EQUIV.\n\n  Variable id: ID.\n  Variable wf: WF.\n  Variable wf0: T wf.\n  Variable R: Type.\n\n  Theorem IndexBeh_implies_SelectBeh\n          (st: state (R:=R)) (tr: Tr.t (R:=R))\n          (BEH: exists (im: imap id wf), Beh.of_state im st tr)\n    :\n    exists raw, (<<EXTRACT: extract_tr raw tr>>) /\\ (<<BEH: RawBeh.of_state_fair_ord (wf:=wf) st raw>>).\n  Proof.\n    des. exists (sti2raw wf0 (st, tr, im)). splits. eapply sti2raw_extract; eauto.\n    rr. splits. eapply sti2raw_raw_beh; eauto. eapply sti2raw_preserves_fairness; eauto.\n  Qed.\n\n  Lemma SelectBeh_implies_IndexBeh_fix\n        (st: state (R:=R)) (raw: RawTr.t (R:=R)) (im: imap id wf)\n        (BEH: RawBeh.of_state st raw)\n        (FAIR: RawTr.fair_ord im raw)\n    :\n    exists tr, (<<EXTRACT: extract_tr raw tr>>) /\\ (<<BEH: Beh.of_state im st tr>>).\n  Proof.\n    exists (raw2tr raw). splits. eapply raw2tr_extract.\n    eapply rawbeh_extract_is_beh_fix; eauto. eapply raw2tr_extract.\n  Qed.\n\n  Theorem SelectBeh_implies_IndexBeh\n          (st: state (R:=R)) (raw: RawTr.t (R:=R))\n          (BEH: RawBeh.of_state_fair_ord (wf:=wf) st raw)\n    :\n    exists tr, (<<EXTRACT: extract_tr raw tr>>) /\\ (exists (im: imap id wf), <<BEH: Beh.of_state im st tr>>).\n  Proof.\n    exists (raw2tr raw). splits. eapply raw2tr_extract.\n    eapply rawbeh_extract_is_beh; eauto. eapply raw2tr_extract.\n  Qed.\n\nEnd EQUIV.\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/BehEquiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.263799459950905}}
{"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.\nRequire Import Classical_Prop.\nFrom CoqCat Require Import racy.\nFrom CoqCat Require Import valid.\nFrom CoqCat Require Import covering.\nImport OEEvt.\nSet Implicit Arguments.\n\nModule Rmw (A:Archi) (dp:Dp).\n\nModule ABasic := Basic A dp.\n\nModule ARes <: Archi.\nParameter ppo : Event_struct -> Rln Event.\nHypothesis ppo_valid : forall E, rel_incl (ppo E) (po_iico E).\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.\nParameter inter : bool.\nParameter intra : bool.\nDefinition ppo_sub E :=\n  fun e1 => fun e2 => A.ppo E e1 e2 /\\ ~(ppo E e1 e2).\n\nInductive wAB_Wa (E:Event_struct) (fenced:Rln Event) : Event -> Event -> Prop :=\n  | wBaseW : forall e1 e2, (*events E e1 -> events E e2 ->*)\n      fenced e1 e2 (*/\\ (writes E e1)*) -> wAB_Wa E fenced e1 e2.\nDefinition abc E (X:Execution_witness) := wAB_Wa E (po_iico E).\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.\ninversion Hxy.\nsplit; auto.\napply ABasic.po_iico_domain_in_events with y; auto.\napply ABasic.po_iico_range_in_events with x; auto.\nQed.\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.\napply trc_step; right; auto.\nQed.\n(*Lemma 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.\nunfold abc; intros E X s x y Hwf Hrfwf; split; intro Hxy.\n  destruct Hxy as [Hxy ?]; destruct Hxy; destruct H; split.\n    apply ABasic.po_rr; auto.\n\n  split; inversion Hxy.\n    apply wBaseW; apply ABasic.po_rr_bak with (fun w => (exists e, rf X w e /\\ s e /\\ ~ s w ) \\/ init w) final s; auto.\n    apply ABasic.po_rr_bak_s with E (fun w => (exists e, rf X w e /\\ s e /\\ ~ s w ) \\/ init w) final; auto.\nQed.*)\n\nParameter stars : Event_struct -> set Event.\nEnd ARes.\n\nImport ARes.\nModule AResBasic := Basic ARes dp.\nImport AResBasic.\nModule AResWmm := Wmm ARes dp.\nImport AResWmm.\nModule An <: Archi.\nDefinition ppo := A.ppo.\nLemma ppo_valid : forall E, rel_incl (ppo E) (po_iico E).\n  apply A.ppo_valid.\nQed.\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.\nDefinition inter := A.inter.\nDefinition intra := A.intra.\nDefinition abc (E:Event_struct) (X:Execution_witness) : Rln Event :=\n  fun e1 => fun e2 => False.\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.\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.\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.\nEnd An.\nModule AnWmm := Wmm An dp.\nModule Wk := (*Hierarchy.*)Weaker An ARes dp.\nModule VA := Valid An dp.\nImport VA. Import VA.ScAx.\nModule Covering := Covering ARes An dp.\nImport Covering.\n\nAxiom excluded_middle : forall (A:Prop), A \\/ ~A.\n\nDefinition atom (E:Event_struct) (X:Execution_witness) (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                  ~(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\nInductive rmw (E:Event_struct) (X:Execution_witness) (r w:Event) (l:Location) : Prop :=\n  | Atom : atom E X r w l -> rmw E X r w l\n  | Loop : (exists r', po_iico E r r' /\\ loc r = loc r' /\\ atom E X r' w l) -> rmw E X r w l.\n\nDefinition rrmw (E:Event_struct) (X:Execution_witness) : Prop :=\n  forall r, (exists w, Wk.rf_sub X w r) ->\n    (exists w, rmw E X r w (*l*) (loc r) /\\ forall e, po_iico E r e -> po_iico E w e).\n\nModule R := Racy ARes A dp.\nImport R.\nImport Wk.\nImport ARes.\nImport AResBasic.\nImport AResWmm.\nModule SN <: R.SafetyNet.\nDefinition fragile X r :=\n  exists w, rf_sub X w r.\nDefinition competing E X :=\n  rel_union (ppo_sub E) (fun e1 e2 => A.ppo E e1 e2 /\\ fragile X e1).\n(*Definition competing E X :=\n  rel_union (ppo_sub E) (rel_seq (rf_sub X) (A.ppo E)). *)\n\nDefinition sx E X :=\n  rel_union (ppo_sub E) (fun e1 e2 => A.ppo E e1 e2 /\\ fragile X e1). (*(rel_seq (rf_sub X) (A.ppo E)).*)\nHypothesis s_ac : forall E X, AC X (sx E X).\n\nDefinition po_Wr E :=\n  fun e1 => fun e2 => po_iico E e1 e2 /\\ writes E e2.\nDefinition po_Wl E :=\n  fun e1 => fun e2 => po_iico E e1 e2 /\\ writes E e1.\nDefinition po_WW E :=\n  fun e1 => fun e2 => po_iico E e1 e2 /\\ (writes E e1 /\\ writes E e2).\n\nDefinition pio_Wr E :=\n  fun e1 => fun e2 => pio E e1 e2 /\\ writes E e2.\nDefinition pio_Wl E :=\n  fun e1 => fun e2 => pio E e1 e2 /\\ writes E e1.\nDefinition pio_WW E :=\n  fun e1 => fun e2 => pio E e1 e2 /\\ (writes E e1 /\\ writes E e2).\n\nLemma po_Wr_Wl_implies_po_WW :\n  forall E x y z,\n  well_formed_event_structure E ->\n  (po_Wl E) x y /\\ (po_Wr E) y z ->\n  (po_WW E) x z.\nProof.\nintros E x y z Hwf [[Hxy Hwx] [Hyz Hwz]].\nsplit; [|split]; auto.\napply po_trans with y; auto.\nQed.\n\nLemma pio_Wr_Wl_implies_pio_WW :\n  forall E x y z,\n  well_formed_event_structure E ->\n  (pio_Wl E) x y /\\ (pio_Wr E) y z ->\n  (pio_WW E) x z.\nProof.\nintros E x y z Hwf [[Hxy Hwx] [Hyz Hwz]].\nsplit; [|split]; auto.\nsplit; destruct Hxy; destruct Hyz;\n[|apply po_trans with y; auto].\n  rewrite H; auto.\nQed.\n\nDefinition hbd (E:Event_struct) (X:Execution_witness) : Rln Event :=\n  fun e1 => fun e2 => com E X e1 e2 /\\ proc_of e1 <> proc_of e2.\n\n(*Definition ppo_Wl E :=\n  fun e1 => fun e2 => A.ppo E e1 e2 /\\ writes E e1.*)\nDefinition ghb_po_Wl E X :=\n  fun e1 => fun e2 => AResWmm.ghb E X e1 e2 /\\ po_iico E e1 e2 /\\ writes E e1.\n\nLemma fno_rf_seq_po_implies_ws_seq_po :\n  forall E X,\n  well_formed_event_structure E ->\n  valid_execution E X -> rrmw E X ->\n  rel_incl (rel_seq (rf_sub X) (A.ppo E)) (rel_seq (ws X) (po_Wl E)).\nProof.\nunfold rrmw;\nintros E X Hwf Hv Hfno w e [r [Hrfs Hppo]].\ngeneralize Hv; intro Hva.\ndestruct_valid Hv.\nassert (rf X w r) as Hrf.\n  destruct Hrfs; apply mrf2_in_rf; auto.\ngeneralize (ran_rf_is_read E X w r Hrf_cands Hrf); intro Hrr.\nassert (reads E r) as Hreads.\n  split; auto.\n  eapply (ran_rf_in_events); auto.\n    split; auto. apply Hrf.\n  destruct Hrr as [l [v Haction_r]].\n  assert (loc r = l) as Hl.\n    unfold loc; rewrite Haction_r; auto.\n    assert (exists w, rf_sub X w r) as Hrrf.\n    exists w; auto.\n  generalize (Hfno r Hrrf); intros [wr [Hrmw Haf]].\n  inversion Hrmw as [Himm | Hult].\n\n  (*rmw r w*)\n  destruct_atom Himm.\n  exists wr.\nassert (ws X w wr \\/ ws X wr w) as Hor.\n  destruct_lin (Hws_tot (loc r)).\n  assert (w <> wr) as Hdiff.\n    generalize (excluded_middle (w <> wr)); intro Hor.\n    inversion Hor; auto.\n\n      assert (w = wr) as Heq.\n        apply NNPP; auto.\n    assert (tc (rel_union (com E X) (pio_llh E)) r r) as Hcy.\n      rewrite <- Heq in Hporw.\n      apply trc_ind with w; apply trc_step; [right; split; auto | left; left; left; auto].\n      apply sym_eq; apply rf_implies_same_loc2 with E X; auto.\n        split; split; auto.\n        split; auto.\n        rewrite Heq; intros [? [? [? [? Hrwr]]]];\n        destruct Hw as [? [? [?  Hwwr]]];\n        rewrite Hrwr in Hwwr; inversion Hwwr.\n    unfold acyclic in Hsp; unfold not in Hsp; assert False as Ht.\n      apply (Hsp r Hcy). inversion Ht.\n\n  assert (In _ (writes_to_same_loc_l (events E) (loc r)) w) as Hew.\n    split.\n      eapply (dom_rf_in_events); auto.\n        split; auto. apply Hrf.\n        eapply rf_implies_same_loc;\n          [apply Hva | apply Hrf | unfold read_from; exists v; auto].\n    rewrite Hl; auto.\n  assert (In _ (writes_to_same_loc_l (events E) (loc r)) wr) as Hewr.\n    split; destruct Hw as [Hevw [lw [vw Hacw]]]; auto; exists vw; auto.\n    rewrite <- Hlw; unfold loc; rewrite Hacw; auto.\n\n  generalize (Htot w wr Hdiff Hew Hewr); intro Hor.\n  inversion Hor as [Hwwr | Hwrw].\n    left; destruct Hwwr; auto.\n    right; destruct Hwrw; auto.\n  inversion Hor as [Hy | Hn]; split; auto.\n      split; [ | auto]. apply Haf; apply A.ppo_valid; auto.\n\n      assert (fr E X r wr) as Hfr.\n        split.\n          apply po_iico_domain_in_events with e; auto.\n        apply A.ppo_valid; auto.\n          split.\n            apply po_iico_range_in_events with r; auto.\n            exists w; split; auto.\n            assert (tc (rel_union (com E X) (pio_llh E)) w w) as Hc.\n              apply trc_ind with r.\n                apply trc_step; left; left; left; auto.\n                apply trc_ind with wr; apply trc_step.\n                  right; split; auto.\n                  split; auto.\n                  intros [? [? [? [? Hrwr]]]];\n                  destruct Hw as [? [? [? Hwwr]]];\n                  rewrite Hrwr in Hwwr; inversion Hwwr.\n                  left; right; auto.\n            assert False as Htriv.\n              apply (Hsp w Hc). inversion Htriv.\n\n    destruct Hfr as [Her [Hewr [ew [Hrfr Hwsr]]]].\n    generalize (Hrf_uni r w ew Hrf Hrfr); intro Heq.\n      rewrite <- Heq in Hwsr.\n    assert (ws X w w) as Hcy.\n      apply ws_trans with E wr; auto; split; auto.\n    generalize (ws_cy E X w Hws_tot Hws_cands); intro Hc.\n    contradiction.\n\n      assert (po_iico E r e) as Hpo.\n        apply A.ppo_valid; auto.\n      split; auto.\n\n(*succes ultimately*)\n\ndestruct Hult as [r' [Hporr' [Heq_loc Hatom]]].\n  destruct_atom Hatom.\n  assert (po_iico E r' e \\/ po_iico E e r') as Horpor'e.\n    assert (po_iico E r e) as Hpore.\n      apply A.ppo_valid; auto.\n    assert (In _ (events E) r) as Her.\n      apply po_iico_domain_in_events with e; auto.\n    assert (In _ (events E) r') as Her'.\n      apply po_iico_domain_in_events with wr; auto.\n    assert (In _ (events E) e) as Hee.\n      apply po_iico_range_in_events with r; auto.\n    generalize (po_implies_same_proc Hwf Her Hee Hpore); intro Hpre.\n    generalize (po_implies_same_proc Hwf Her Her' Hporr'); intro Hprr'.\n    assert (proc_of e = proc_of r') as Hper'.\n      rewrite <- Hpre; rewrite Hprr'; auto.\n    apply (same_proc_implies_po); auto.\n  inversion Horpor'e as [Haft | Hbef].\n\n(*e after r' in po*)\n\n exists wr.\nassert (ws X w wr \\/ ws X wr w) as Hor.\n  destruct_lin (Hws_tot l).\n  assert (w <> wr) as Hdiff.\n    generalize (excluded_middle (w <> wr)); intro Hor.\n    inversion Hor; auto.\n\n      assert (w = wr) as Heq.\n        apply NNPP; auto.\n    assert (tc (rel_union (com E X) (pio_llh E)) r r) as Hcy.\n      rewrite <- Heq in Hporw.\n      apply trc_ind with w; apply trc_step; [right; split; auto | left; left; left; auto].\n      apply sym_eq; apply rf_implies_same_loc2 with E X; auto.\n        split; split; auto.\n       split.\n       apply po_trans with r'; auto.\n       rewrite Heq; intros [? [? [? [? Hrwr]]]];\n       destruct Hw as [? [? [? Hwwr]]]; rewrite Hrwr in Hwwr; inversion Hwwr.\n    unfold acyclic in Hsp; unfold not in Hsp; assert False as Ht.\n      apply (Hsp r Hcy). inversion Ht.\n\n  assert (In _ (writes_to_same_loc_l (events E) l) w) as Hew.\n    split.\n      eapply (dom_rf_in_events); auto.\n        split; auto. apply Hrf.\n        eapply rf_implies_same_loc;\n          [apply Hva | apply Hrf | unfold read_from; exists v; auto].\n  assert (In _ (writes_to_same_loc_l (events E) l) wr) as Hewr.\n    split; destruct Hw as [Hevw [lw [vw Hacw]]]; auto; exists vw; auto.\n    rewrite <- Hl; rewrite <- Hlw; unfold loc; rewrite Hacw; auto.\n\n  generalize (Htot w wr Hdiff Hew Hewr); intro Hor.\n  inversion Hor as [Hwwr | Hwrw].\n    left; destruct Hwwr; auto.\n    right; destruct Hwrw; auto.\n  inversion Hor as [Hy | Hn]; split; auto.\n      assert (po_iico E r e) as Hpo.\n        apply A.ppo_valid; auto.\n      split; auto.\n\n      assert (fr E X r wr) as Hfr.\n        split.\n      assert (po_iico E r e) as Hpo.\n        apply A.ppo_valid; auto.\n          apply po_iico_domain_in_events with e; destruct Hpo; auto.\n            apply po_trans with r'; auto.\n            apply po_trans with r'; auto.\n          split.\n            apply po_iico_range_in_events with r'; auto.\n            exists w; split; auto.\n            assert (tc (rel_union (com E X) (pio_llh E)) w w) as Hc.\n              apply trc_ind with r.\n                apply trc_step; left; left; left; auto.\n                apply trc_ind with wr; apply trc_step.\n                  right; split; auto.\n                 split; auto.\n                  apply po_trans with r'; auto.\n                  intros [? [? [? [? Hrwr]]]];\n                  destruct Hw as [? [? [? Hwwr]]];\n                  rewrite Hwwr in Hrwr; inversion Hrwr.\n                  left; right; auto.\n            assert False as Htriv.\n              apply (Hsp w Hc). inversion Htriv.\n\n    destruct Hfr as [Her [Hewr [ew [Hrfr Hwsr]]]].\n    generalize (Hrf_uni r w ew Hrf Hrfr); intro Heq.\n      rewrite <- Heq in Hwsr.\n    assert (ws X w w) as Hcy.\n      apply ws_trans with E wr; auto; split; auto.\n    generalize (ws_cy E X w Hws_tot Hws_cands); intro Hc.\n    contradiction.\n\n      assert (po_iico E r e) as Hpo.\n        apply A.ppo_valid; auto.\n     split; auto.\n\n   (*e before r' in po*)\n   assert (po_iico E e wr) as Hpoc.\n     apply po_trans with r'; auto.\n     generalize (A.ppo_valid Hppo); intro Hpo.\n     generalize (Haf e Hpo); intro Hc.\n   assert (po_iico E e e) as Hcy.\n     apply po_trans with wr; auto.\n   generalize (po_ac Hwf Hcy); intro Ht; inversion Ht.\nQed.\n\nLemma fr_po :\n  forall E X x y,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  reads E x ->\n  writes E y ->\n  po_iico E x y ->\n  loc x = loc y ->\n  fr E X x y.\nProof.\nintros E X x y Hwf Hv Hrx Hwy Hpo Hl.\ngeneralize Hv; intro Hva.\ndestruct_valid Hv; generalize (Hrf_init x Hrx);\n  intros [wx [Horx Hrfx]].\n  split; [|split; [|exists wx; split]]; auto.\n  apply ran_rf_in_events with X wx; auto.\n    split; auto.\n  apply po_iico_range_in_events with x; auto.\n  generalize (Hws_tot (loc x)); intro Hlin;\n  destruct_lin Hlin.\n  generalize (excluded_middle (wx <> y)); intro Hord;\n  inversion Hord as [Hdiff | Hnd].\n    assert (In _ (writes_to_same_loc_l (events E) (loc x)) wx) as Hewx.\n      split; auto.\n  (*apply dom_rf_in_events with X x; auto.\n    split; auto.*)\n\n      apply rf_implies_same_loc with E X x; auto.\n      destruct Hrx as [? [? [v Hrx]]]; exists v; auto.\n      unfold loc; rewrite Hrx; auto.\n    assert (In _ (writes_to_same_loc_l (events E) (loc x)) y) as Hey.\n      destruct Hwy as [? [? [v Hwy]]]; split; auto.\n      exists v; rewrite Hl; unfold loc; rewrite Hwy; auto.\n    generalize (Htot wx y Hdiff Hewx Hey); intro Hor;\n    inversion Hor as [Hwxy | Hywx].\n    destruct Hwxy; auto.\n    destruct Hywx as [Hywx ?].\n    assert False as Htriv.\n      assert (tc (rel_union (com E X) (pio_llh E)) wx wx) as Hcy.\n        apply trc_ind with x;\n        [apply trc_step; left; left; left |\n         apply trc_ind with y; apply trc_step;\n           [right; split; [|split] | left; right]]; auto.\n        intros [? [? [? [? Hry]]]]; destruct Hwy as [? [? [? Hwy]]];\n        rewrite Hwy in Hry; inversion Hry.\n      unfold acyclic in Hsp; apply (Hsp wx Hcy).\n      inversion Htriv.\n\n  assert (wx = y) as Heq.\n    apply NNPP; auto.\n\n    assert False as Htriv.\n      assert (tc (rel_union (com E X) (pio_llh E)) wx wx) as Hcy.\n        apply trc_ind with x;\n        [apply trc_step; left; left; left |\n         subst; apply trc_step; right; split; [|split]]; auto.\n        intros [? [? [? [? Hry]]]]; destruct Hwy as [? [? [? Hwy]]];\n        rewrite Hwy in Hry; inversion Hry.\n      unfold acyclic in Hsp; apply (Hsp wx Hcy).\n      inversion Htriv.\nQed.\n\nLemma rmw_in_fr :\n  forall E X x y l,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  reads E x ->\n  rmw E X x y l ->\n  fr E X x y.\nProof.\nintros E X x y l Hwf Hv Hrx Hrmw.\ninversion Hrmw.\n  destruct_atom H.\n  apply fr_po; auto.\n  subst; auto.\n\n  destruct H as [r [Hpo_xr [Hl Hatom]]].\n  destruct_atom Hatom.\n  assert (po_iico E x y) as Hpo.\n    apply po_trans with r; auto.\n  apply fr_po; auto. subst; rewrite Hl; auto.\nQed.\n\nLemma sx_in_ghb :\n  forall E X,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  rrmw E X ->\n  rel_incl (sx E X) (tc (AResWmm.ghb E X)).\nProof.\nintros E X Hwf Hv Hrrmw x y Hxy.\n  inversion Hxy as [Hppo | Hrf].\n   apply trc_step; apply AResBasic.ab_in_ghb; unfold abc; apply wBaseW; auto.\n   destruct Hppo; apply A.ppo_valid; auto.\n  destruct Hrf as [Hppo ?].\n   apply trc_step; apply AResBasic.ab_in_ghb; unfold abc; apply wBaseW; auto.\n   apply A.ppo_valid; auto.\nQed.\n\n(*generalize (excluded_middle (writes E x)); intro Hor;\ninversion Hor as [Hwx | Hnwx].\n  inversion Hxy; [apply trc_step|].\n    apply AResBasic.ab_in_ghb;\n    unfold abc; apply wBaseW;\n    destruct H. apply A.ppo_valid; auto.\n    generalize (fno_rf_seq_po_implies_ws_seq_po Hwf Hv Hrrmw);\n    intro Hincl.\n    destruct H as [Hppoxy [z Hzx]].\n   apply trc_step; apply AResBasic.ab_in_ghb; unfold abc; apply wBaseW; auto.\n   apply A.ppo_valid; auto.\n\n    assert (rel_seq (ws X) (po_Wl E) x y) as Hin.\n      apply Hincl; auto.\n    destruct Hin as [z [Hws Hpo]].\n      apply trc_ind with z; apply trc_step;\n      [apply ws_in_ghb |\n       apply AResBasic.ab_in_ghb; unfold abc; apply wBaseW; destruct Hpo]; auto.\n\n  inversion Hxy as [Hppo | Hrf].\n   apply trc_step; apply AResBasic.ab_in_ghb; unfold abc; apply wBaseW; auto.\n   destruct Hppo; apply A.ppo_valid; auto.\n\n    destruct Hrf as [z [[Hmrf2 ?] ?]].\n    assert (rf X x z) as Hrf.\n      apply mrf2_in_rf; auto.\n    assert (writes E x) as Hc.\n      split.\n        apply dom_rf_in_events with X z; auto; destruct_valid Hv; split; auto.\n        apply dom_rf_is_write with E X z; auto; destruct_valid Hv; auto.\n    contradiction.\nQed.*)\n\nSet Implicit Arguments.\nLemma tc_tc :\n  forall A (r: Rln A),\n  rel_incl (tc (tc r)) (tc r).\nProof.\nintros A r x y Hxy.\ninduction Hxy; auto.\napply trc_ind with z; auto.\nQed.\nUnset Implicit Arguments.\n\nHypothesis rmwt :\n  forall E X, rrmw E X.\n\nLemma sx_ghb :\n  forall E X,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  acyclic (rel_union (sx E X) (AResWmm.ghb E X)).\nProof.\nintros E X Hwf Hv.\napply incl_ac with (tc (AResWmm.ghb E X)).\n  intros x y Hxy; inversion Hxy; auto.\n    apply sx_in_ghb; auto.\n      apply rmwt.\n    apply trc_step; auto.\n  destruct_valid Hv; auto.\n  unfold acyclic; unfold acyclic in Hvalid; intros x Hx.\n  assert (tc (ghb E X) x x) as Htc.\n    apply tc_tc; auto.\n  apply (Hvalid x Htc).\nQed.\n\nDefinition s E X := sx E X.\nDefinition cns E X :=\n  fun e1 => fun e2 => competing E X e1 e2 /\\ ~ (s E X e1 e2 \\/ s E X e2 e1).\n\nLemma s_ghb :\n  forall E X,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  acyclic (rel_union (s E X) (AResWmm.ghb E X)).\nProof.\napply sx_ghb.\nQed.\n\nDefinition convoluted_wf :=\n  forall E X Y x y,\n  competing E X x y ->\n  ~ (s E X x y \\/ s 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 /\\ ~ (s E Y x y \\/ s E Y y x).\n\nLemma convoluted_prop_stable :\n  convoluted_wf.\n(*  forall E X Y x y,\n  competing E X x y ->\n  ~ (s E X x y \\/ s 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 /\\ ~ (s E Y x y \\/ s E Y y x).*)\nProof.\nintros E X Y x y Hxy Hnxy Hrf Hws.\nunfold competing in Hxy; unfold SN.s in Hxy.\nunfold SN.s in Hnxy; unfold SN.sx in Hnxy.\nassert (rel_union (ppo_sub E)\n          (fun e1 e2 : Event => A.ppo E e1 e2 /\\ fragile X e1) x y \\/\n        rel_union (ppo_sub E)\n          (fun e1 e2 : Event => A.ppo E e1 e2 /\\ fragile X e1) y x) as Hc.\n  left; auto.\ncontradiction.\nQed.\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 Hwfrf Hc; inversion Hc as [Hppo | Hrf].\n  destruct Hppo; split;\n    [change (events E x) with (In _ (events E) x);\n     apply ABasic.po_iico_domain_in_events with y |\n     change (events E y) with (In _ (events E) y);\n     apply A2Basic.po_iico_range_in_events with x]; auto;\n    apply A.ppo_valid; auto.\n  destruct Hrf as [Hppo Hrf]; split;\n  [change (events E x) with (In _ (events E) x);\n    destruct Hrf as (*[? [[? ?] ?]]*) [z Hrf]|\n   change (events E y) with (In _ (events E) y);\n   apply A2Basic.po_iico_range_in_events with (*z*) x; auto; apply A.ppo_valid]; auto.\n    destruct Hrf as [? ?];\n   apply A2Basic.ran_rf_in_events with X z; auto.\n   apply mrf2_in_rf; 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 E X x y 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  A1Wmm.valid_execution E X ->\n  ~ (exists z, competing E X z z).\nProof.\nintros E X Hwf Hv1 [z Hc].\n  assert (  write_serialization_well_formed (events E) (ws X) /\\\n  rfmaps_well_formed E (events E) (rf X) ) as Hs.\n    destruct_valid Hv1; split; split; auto.\n  inversion Hc.\n  destruct H as [Hz ?]; generalize (A.ppo_valid Hz); intro Hcy.\n  apply (A2Basic.po_ac Hwf Hcy).\n (* destruct H as [z' [Hzz' Hz'z]].\n  assert (po_iico E z' z) as Hpo.\n    apply A2.ppo_valid; auto.\n  generalize (rfs_seq_po_in_u Hs Hzz' Hpo); intro Hpio.\n  assert (tc (rel_union (hb E X) (pio_llh E)) z z) as Hcy.\n    apply trc_ind with z'; apply trc_step; [left | right]; auto.\n    left; left; destruct Hzz'; apply mrf_in_rf; auto.\n  destruct_valid Hv1; apply (Hsp z Hcy).  *)\n destruct H as [Hzz ?].\n generalize (A.ppo_valid Hzz).\n apply A2Basic.po_ac; auto.\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 E X Hwf Hv1 Hc).\nQed.\nLemma competing_not_po :\n  forall E X x y,\n  well_formed_event_structure E ->\n  A1Wmm.valid_execution E X ->\n  competing E X x y -> ~ (po_iico E y x).\nProof.\nintros E X x y Hwf Hv1 Hc Hyx.\n  assert (  write_serialization_well_formed (events E) (ws X) /\\\n  rfmaps_well_formed E (events E) (rf X) ) as Hs.\n    destruct_valid Hv1; split; split; auto.\n  inversion Hc.\n  destruct H as [Hz ?]; generalize (A.ppo_valid Hz); intro Hxy.\n  assert (po_iico E x x) as Hcy.\n    apply A2Basic.po_trans with y; auto.\n  apply (A2Basic.po_ac Hwf Hcy).\n(*    destruct H as [z' [Hzz' Hz'z]].\n  assert (po_iico E z' x) as Hpo. *)\n\n    destruct H as [Hxy ?].\n    assert (po_iico E x y) as Hpo.\n    (*apply A2nBasic.po_trans with y; auto.*)\n    apply A.ppo_valid; auto.\n    assert (po_iico E x x) as Hxx.\n      apply A2nBasic.po_trans with y; auto.\n    generalize Hxx; apply A2nBasic.po_ac; 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 E X x y 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 E X x y z z 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 E X x y 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 E X 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 E X x y Hwf Hv e e Htc); intro He.\ndestruct He as [e' [[[Hee' ?] ?] He'e]].\ngeneralize (competing_not_po E X e e' 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  ~ (s E X x y \\/ s E X y x) ->\n  (exists Y, AnWmm.valid_execution E Y /\\\n  competing E Y x y /\\ ~ (s E Y x y \\/ s 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.\n    apply (Hcwf E X Y x y); auto.\nQed.\n\nLemma prop_stable :\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  ~ (s E X x y \\/ s E X y x) ->\n  (exists Y, AnWmm.valid_execution E Y /\\\n  competing E Y x y /\\ ~ (s E Y x y \\/ s E Y y x))).\nProof.\napply convoluted_wf_implies_wf.\napply convoluted_prop_stable.\nQed.\n\nLemma s_ppo_in_po :\n  forall E X x y,\n  well_formed_event_structure E ->\n  tc (rel_union (s E X) (A2n.ppo E)) x y ->\n  po_iico E x y.\nProof.\nunfold s; unfold sx;\nintros E X x y Hwf Hxy.\ninduction Hxy.\n  inversion H.\n    inversion H0;\n      destruct H1; apply A.ppo_valid; auto.\n      apply A2n.ppo_valid; auto.\n    apply po_trans with z; auto.\nQed.\n\nLemma s_ppo2 :\n  forall E X,\n  well_formed_event_structure E ->\n  acyclic (rel_union (s E X) (A2n.ppo E)).\nProof.\nintros E X Hwf x Hx.\nassert (po_iico E x x) as Hc.\n  apply s_ppo_in_po with X; auto.\n  apply (po_ac Hwf Hc).\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).\nDefinition covering s :=\n  forall E X, well_formed_event_structure E ->\n    A1Wmm.valid_execution E X ->\n    covered E X s -> acyclic (A2nWmm.ghb E X).\n\nEnd SN.\n\n(*Import R.\nModule BG := R.BarriersGuarantee SN.\nModule AWmm := Wmm A dp.\n\nLemma rrmw_prop :\n  (forall E X, rrmw E X) ->\n  (forall E X, AnWmm.valid_execution E X -> BG.Bars.covered E X BG.Bars.s).\nProof.\nintros Hrrmw E X Hv.\nunfold BG.Bars.covered.\nintros x y Hxy.\ninversion Hxy; left; [left | right]; auto.\nQed.\n\nLemma rmw_guarantee :\n  (forall E X, rrmw E X) ->\n  (forall E X, well_formed_event_structure E ->\n   (AResWmm.valid_execution E X <-> AnWmm.valid_execution E X)).\nProof.\nintro Hrrmw.\napply BG.barriers_guarantee.\napply rrmw_prop; auto.\nQed.\n\nLemma rmw_equiv :\n  (forall E X, rrmw E X) ->\n  (forall E X, well_formed_event_structure E ->\n   (AResWmm.valid_execution E X <-> AnWmm.valid_execution E X)).\nProof.\nintros Hrrmw E X.\n  apply rmw_guarantee; auto.\nQed.*)\n\nEnd Rmw.\n", "meta": {"author": "herd", "repo": "CoqCat", "sha": "e9afddbfe4cd17de335596454b8e9de0dd8ce5c2", "save_path": "github-repos/coq/herd-CoqCat", "path": "github-repos/coq/herd-CoqCat/CoqCat-e9afddbfe4cd17de335596454b8e9de0dd8ce5c2/rmw.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.263799459950905}}
{"text": "(******************************************************************************)\n(** * Definition of the ARMv8.3 memory model                                  *)\n(* a fragment of the full model                                                *)\n(* (omitting dmb.st, LDAR, and isb that are not used in compiled programs)    *)\n(******************************************************************************)\nFrom hahn Require Import Hahn.\nFrom imm Require Import Events.\nRequire Import Execution_m.\n(* Require Import Execution_eco. *)\n\nSet Implicit Arguments.\nRemove Hints plus_n_O.\n\nSection Arm_mixed.\n\nVariable G : execution_m.\n\nNotation \"'E'\" := G.(acts_set).\nNotation \"'acts'\" := G.(acts).\nNotation \"'lab'\" := G.(lab).\nNotation \"'sb'\" := G.(sb).\nNotation \"'rfb'\" := G.(rfb).\nNotation \"'cob'\" := G.(cob).\nNotation \"'rf'\" := G.(rf).\nNotation \"'co'\" := G.(co).\nNotation \"'rf_on'\" := G.(rf_on).\nNotation \"'cob_on'\" := G.(cob_on).\nNotation \"'rmw'\" := G.(rmw).\nNotation \"'data'\" := G.(data).\nNotation \"'addr'\" := G.(addr).\nNotation \"'ctrl'\" := G.(ctrl).\nNotation \"'deps'\" := G.(deps).\n\n(* Notation \"'eco'\" := G.(eco). *)\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)).\nNotation \"'RW'\" := (R ∪₁ W).\nNotation \"'FR'\" := (F ∪₁ R).\nNotation \"'FW'\" := (F ∪₁ W).\nNotation \"'W_ex'\" := (W_ex G).\n\nNotation \"'L'\" := (W ∩₁ (fun a => is_true (is_rel lab a))).\nNotation \"'Q'\" := (R ∩₁ (fun a => is_true (is_acq lab a))).\nNotation \"'A'\" := (R ∩₁ (fun a => is_true (is_sc  lab a))).\n\nNotation \"'F^ld'\" := (F ∩₁ (fun a => is_true (is_acq lab a))).\nNotation \"'F^sy'\" := (F ∩₁ (fun a => is_true (is_rel lab a))).\n\n(******************************************************************************)\n(** ** Derived relations  *)\n(******************************************************************************)\n\nDefinition fr_on n := (rf_on n) ^{-1} ⨾ (cob_on n).\nDefinition fr x y := exists n, fr_on n x y.\n\nDefinition rfe := rf \\ sb.\nDefinition coe := co \\ sb.\nDefinition fre := fr \\ sb.\nDefinition rfi := rf ∩ sb.\nDefinition coi := co ∩ sb.\nDefinition fri := fr ∩ sb.\n\n(* ca? *)\nDefinition ca := fr ∪ co.\n\n(* Observed-by *)\nDefinition obs := rfe ∪ coe ∪ fre.\n\n(* Dependency-ordered-before *)\nDefinition dob :=\n   (addr ∪ data) ⨾ rfi^?\n ∪ (ctrl ∪ data) ⨾ ⦗W⦘ ⨾ coi^?\n ∪ addr ⨾ sb ⨾ ⦗W⦘.\n\n(* Atomic-ordered-before *)\nDefinition aob :=\n  rmw ∪ ⦗W_ex⦘ ⨾ rfi ⨾ ⦗Q⦘.\n\n(* Barrier-ordered-before *)\nDefinition bob :=\n    sb ⨾ ⦗F^sy⦘ ⨾ sb\n  ∪ ⦗R⦘ ⨾ sb ⨾ ⦗F^ld⦘ ⨾ sb\n  ∪ ⦗Q⦘ ⨾ sb\n  ∪ sb ⨾ ⦗L⦘ ⨾ coi^?\n  ∪ ⦗L⦘ ⨾ sb ⨾ ⦗A⦘.\n\nDefinition ob := obs ∪ dob ∪ aob ∪ bob.\n\nDefinition polocb n x y := sb x y /\\ overlap_on G n x y.\n\n(******************************************************************************)\n(** ** Consistency *)\n(******************************************************************************)\n\nDefinition rmw_atomicity := rmw ∩ (fre ⨾ coe) ⊆ ∅₂.\n\n(* internal visibility *)\nDefinition sc_per_loc := forall n, acyclic (polocb n ∪ fr_on n ∪ cob_on n ∪ rf_on n).\n\nImplicit Type WF : Wf_m G.\nImplicit Type COMP : complete G.\nImplicit Type ATOM : rmw_atomicity.\nImplicit Type SC_PER_LOC : sc_per_loc.\n\nDefinition ArmConsistent_m :=\n  ⟪ WF : Wf_m G ⟫ /\\\n  ⟪ COMP : complete G ⟫ /\\\n  ⟪ SC_PER_LOC: sc_per_loc ⟫ /\\\n  ⟪ POWER_ATOMICITY : rmw_atomicity ⟫ /\\\n  ⟪ SCA : irreflexive (rf⨾fr) ⟫ /\\\n  ⟪ ACYC : acyclic ob ⟫.\n\nImplicit Type CON : ArmConsistent_m.\n\n\n(******************************************************************************)\n(** ** Additional derived relations to simlify our proofs *)\n(******************************************************************************)\n\nDefinition obs' := rfe ∪ co ∪ fr.\n\nDefinition bob' :=\n    bob ∪ ⦗R⦘ ⨾ sb ⨾ ⦗F^ld⦘ \n        ∪ sb ⨾ ⦗F^sy⦘ \n        ∪ ⦗F^ld ∪₁ F^sy⦘ ⨾ sb.\n\nLemma rfe_E x y :\n  Wf_m G -> rfe x y -> E x /\\ E y.\nProof.\n  intros WF H.\n  destruct H.\n  apply rf_E.\n  apply WF.\n  apply H.\nQed.\n\nLemma co_E x y :\n  Wf_m G -> co x y -> E x /\\ E y.\nProof.\n  intros WF H.\n  apply WF in H.\n  destruct H as [x_ [[H11 H12] [y_ [H21 [H221 H222]]]]].\n  rewrite H221 in H222.\n  split; easy.\nQed.\n\nLemma coe_E x y :\n  Wf_m G -> coe x y -> E x /\\ E y.\nProof.\n  intros WF H.\n  destruct H.\n  apply co_E.\n  apply WF.\n  apply H.\nQed.\n\nLemma fr_E x y :\n  Wf_m G -> fr x y -> E x /\\ E y.\nProof.\n  intros WF H.\n  destruct H as [n H].\n  unfold fr_on in H.\n  destruct H as [z [H1 H2]].\n  unfold \"⁻¹\" in H1.\n  apply rf_on_rf in H1.\n  apply cob_on_co in H2.\n  apply co_E in H2.\n  apply rf_E in H1.\n  split. apply H1. apply H2.\n  apply WF. apply WF.\nQed.\n\nLemma fre_E x y :\n  Wf_m G -> fre x y -> E x /\\ E y.\nProof.\n  intros WF H.\n  destruct H.\n  apply fr_E; assumption.\nQed.\n\nLemma obs_E x y :\n  Wf_m G -> obs x y -> E x /\\ E y.\nProof.\n  intros WF H.\n  destruct H as [[H|H]|H].\n  - apply rfe_E; assumption.\n  - apply coe_E; assumption.\n  - apply fre_E; assumption.\nQed.\n\nEnd Arm_mixed.\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/arm_mixed/Arm_mixed.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2637804825250882}}
{"text": "(**\nThis file is part of the Flocq formalization of floating-point\narithmetic in Coq: http://flocq.gforge.inria.fr/\n\nCopyright (C) 2010-2011 Sylvie Boldo\n#<br />#\nCopyright (C) 2010-2011 Guillaume Melquiond\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 3 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nCOPYING file for more details.\n*)\n\n(** * Fixed-point format *)\nRequire Import Fcore_Raux.\nRequire Import Fcore_defs.\nRequire Import Fcore_rnd.\nRequire Import Fcore_generic_fmt.\nRequire Import Fcore_rnd_ne.\n\nSection RND_FIX.\n\nVariable beta : radix.\n\nNotation bpow := (bpow beta).\n\nVariable emin : Z.\n\n(* fixed-point format with exponent emin *)\nDefinition FIX_format (x : R) :=\n  exists f : float beta,\n  x = F2R f /\\ (Fexp f = emin)%Z.\n\nDefinition FIX_exp (e : Z) := emin.\n\n(** Properties of the FIX format *)\n\nGlobal Instance FIX_exp_valid : Valid_exp FIX_exp.\nProof.\nintros k.\nunfold FIX_exp.\nsplit ; intros H.\nnow apply Zlt_le_weak.\nsplit.\napply Zle_refl.\nnow intros _ _.\nQed.\n\nTheorem generic_format_FIX :\n  forall x, FIX_format x -> generic_format beta FIX_exp x.\nProof.\nintros x ((xm, xe), (Hx1, Hx2)).\nrewrite Hx1.\nnow apply generic_format_canonic.\nQed.\n\nTheorem FIX_format_generic :\n  forall x, generic_format beta FIX_exp x -> FIX_format x.\nProof.\nintros x H.\nrewrite H.\neexists ; repeat split.\nQed.\n\nTheorem FIX_format_satisfies_any :\n  satisfies_any FIX_format.\nProof.\nrefine (satisfies_any_eq _ _ _ (generic_format_satisfies_any beta FIX_exp)).\nintros x.\nsplit.\napply FIX_format_generic.\napply generic_format_FIX.\nQed.\n\nGlobal Instance FIX_exp_monotone : Monotone_exp FIX_exp.\nProof.\nintros ex ey H.\napply Zle_refl.\nQed.\n\nEnd RND_FIX.\n", "meta": {"author": "jeremyjohnston", "repo": "javascript-vm", "sha": "eb4b20f46d36c8342f0f012cd38500ca6dab3e1a", "save_path": "github-repos/coq/jeremyjohnston-javascript-vm", "path": "github-repos/coq/jeremyjohnston-javascript-vm/javascript-vm-eb4b20f46d36c8342f0f012cd38500ca6dab3e1a/Resources/Tools/flocq-2.1.0/src/Core/Fcore_FIX.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203340678568, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.26375473611718575}}
{"text": "(** An example of ATM program. *)\nRequire Import Coq.NArith.NArith.\nRequire Import Io.All.\nRequire Import ListString.All.\n\nImport C.Notations.\n\nModule Command.\n  Inductive t :=\n  | GetLogin\n  | GetPassword\n  | CheckAuthorization (login : LString.t) (password : LString.t)\n  | GetWithdrawAmount\n  | DoWithdraw (amount : N)\n  | GiveMoney (amount : N)\n  | DisplayError (message : LString.t).\n\n  Definition answer (c : t) : Type :=\n    match c with\n    | GetLogin => LString.t\n    | GetPassword => LString.t\n    | CheckAuthorization _ _ => bool\n    | GetWithdrawAmount => N\n    | DoWithdraw _ => bool\n    | GiveMoney _ => bool\n    | DisplayError _ => unit\n    end.\nEnd Command.\n\nDefinition E : Effect.t :=\n  Effect.New Command.t Command.answer.\n\nDefinition main : C.t E unit :=\n  let! login := call E Command.GetLogin in\n  let! password := call E Command.GetPassword in\n  let! is_authorized := call E (Command.CheckAuthorization login password) in\n  if is_authorized then\n    let! amount := call E Command.GetWithdrawAmount in\n    let! is_withdraw_ok := call E (Command.DoWithdraw amount) in\n    if is_withdraw_ok then\n      let! is_money_ok := call E (Command.GiveMoney amount) in\n      if is_money_ok then\n        ret tt\n      else\n        call E (Command.DisplayError (LString.s \"Cannot give you the money.\"))\n    else\n      call E (Command.DisplayError (LString.s \"Cannot withdraw the money.\"))\n  else\n    call E (Command.DisplayError (LString.s \"Wrong password.\")).\n\nModule Run.\n  Import Io.Run.\n\n  Definition main_ok (login password : LString.t) (amount : N) : Run.t main tt.\n    eapply Let; [apply (Call (E := E) Command.GetLogin login) |].\n    eapply Let; [apply (Call (E := E) Command.GetPassword password) |].\n    eapply Let;\n      [apply (Call (E := E) (Command.CheckAuthorization login password) true) |].\n    eapply Let; [apply (Call (E := E) Command.GetWithdrawAmount amount) |].\n    eapply Let; [apply (Call (E := E) (Command.DoWithdraw amount) true) |].\n    eapply Let; [apply (Call (E := E) (Command.GiveMoney amount) true) |].\n    apply Ret.\n  Defined.\nEnd Run.\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/Atm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2637547361171857}}
{"text": "(* This file is generated by Why3's Coq driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire BuiltIn.\nRequire HighOrd.\nRequire int.Int.\nRequire int.Abs.\nRequire int.EuclideanDivision.\nRequire list.List.\nRequire list.Length.\nRequire list.Mem.\nRequire map.Map.\nRequire bool.Bool.\nRequire list.Append.\n\n(* Why3 assumption *)\nDefinition unit := unit.\n\nAxiom qtmark : Type.\nParameter qtmark_WhyType : WhyType qtmark.\nExisting Instance qtmark_WhyType.\n\nAxiom map : forall (a:Type) (b:Type), Type.\nParameter map_WhyType : forall (a:Type) {a_WT:WhyType a}\n  (b:Type) {b_WT:WhyType b}, WhyType (map a b).\nExisting Instance map_WhyType.\n\nParameter get: forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  (map a b) -> a -> b.\n\nParameter set: forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  (map a b) -> a -> b -> (map a b).\n\nAxiom Select_eq : forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  forall (m:(map a b)), forall (a1:a) (a2:a), forall (b1:b), (a1 = a2) ->\n  ((get (set m a1 b1) a2) = b1).\n\nAxiom Select_neq : forall {a:Type} {a_WT:WhyType a}\n  {b:Type} {b_WT:WhyType b}, forall (m:(map a b)), forall (a1:a) (a2:a),\n  forall (b1:b), (~ (a1 = a2)) -> ((get (set m a1 b1) a2) = (get m a2)).\n\n(* Why3 assumption *)\nInductive id :=\n  | Id : Z -> id.\nAxiom id_WhyType : WhyType id.\nExisting Instance id_WhyType.\n\n(* Why3 assumption *)\nDefinition state := (map id Z).\n\n(* Why3 assumption *)\nInductive aexpr :=\n  | Anum : Z -> aexpr\n  | Avar : id -> aexpr\n  | Aadd : aexpr -> aexpr -> aexpr\n  | Asub : aexpr -> aexpr -> aexpr\n  | Amul : aexpr -> aexpr -> aexpr.\nAxiom aexpr_WhyType : WhyType aexpr.\nExisting Instance aexpr_WhyType.\n\n(* Why3 assumption *)\nInductive bexpr :=\n  | Btrue : bexpr\n  | Bfalse : bexpr\n  | Band : bexpr -> bexpr -> bexpr\n  | Bnot : bexpr -> bexpr\n  | Beq : aexpr -> aexpr -> bexpr\n  | Ble : aexpr -> aexpr -> bexpr.\nAxiom bexpr_WhyType : WhyType bexpr.\nExisting Instance bexpr_WhyType.\n\n(* Why3 assumption *)\nInductive com :=\n  | Cskip : com\n  | Cassign : id -> aexpr -> com\n  | Cseq : com -> com -> com\n  | Cif : bexpr -> com -> com -> com\n  | Cwhile : bexpr -> com -> com.\nAxiom com_WhyType : WhyType com.\nExisting Instance com_WhyType.\n\n(* Why3 assumption *)\nFixpoint aeval (st:(map id Z)) (e:aexpr) {struct e}: Z :=\n  match e with\n  | (Anum n) => n\n  | (Avar x) => (get st x)\n  | (Aadd e1 e2) => ((aeval st e1) + (aeval st e2))%Z\n  | (Asub e1 e2) => ((aeval st e1) - (aeval st e2))%Z\n  | (Amul e1 e2) => ((aeval st e1) * (aeval st e2))%Z\n  end.\n\nParameter beval: (map id Z) -> bexpr -> bool.\n\nAxiom beval_def : forall (st:(map id Z)) (b:bexpr),\n  (match b with\n  | Btrue => True\n  | Bfalse => False\n  | (Bnot b') => ((Init.Datatypes.negb (beval st b')) = true)\n  | (Band b1 b2) => ((Init.Datatypes.andb (beval st b1) (beval st\n      b2)) = true)\n  | (Beq a1 a2) => ((aeval st a1) = (aeval st a2))\n  | (Ble a1 a2) => ((aeval st a1) <= (aeval st a2))%Z\n  end -> ((beval st b) = true)) /\\\n  ((~ match b with\n  | Btrue => True\n  | Bfalse => False\n  | (Bnot b') => ((Init.Datatypes.negb (beval st b')) = true)\n  | (Band b1 b2) => ((Init.Datatypes.andb (beval st b1) (beval st\n      b2)) = true)\n  | (Beq a1 a2) => ((aeval st a1) = (aeval st a2))\n  | (Ble a1 a2) => ((aeval st a1) <= (aeval st a2))%Z\n  end) -> ((beval st b) = false)).\n\n(* Why3 assumption *)\nInductive ceval: (map id Z) -> com -> (map id Z) -> Prop :=\n  | E_Skip : forall (m:(map id Z)), (ceval m Cskip m)\n  | E_Ass : forall (m:(map id Z)) (a:aexpr) (x:id), (ceval m (Cassign x a)\n      (set m x (aeval m a)))\n  | E_Seq : forall (cmd1:com) (cmd2:com) (m0:(map id Z)) (m1:(map id Z))\n      (m2:(map id Z)), (ceval m0 cmd1 m1) -> ((ceval m1 cmd2 m2) -> (ceval m0\n      (Cseq cmd1 cmd2) m2))\n  | E_IfTrue : forall (m0:(map id Z)) (m1:(map id Z)) (cond:bexpr) (cmd1:com)\n      (cmd2:com), ((beval m0 cond) = true) -> ((ceval m0 cmd1 m1) -> (ceval\n      m0 (Cif cond cmd1 cmd2) m1))\n  | E_IfFalse : forall (m0:(map id Z)) (m1:(map id Z)) (cond:bexpr)\n      (cmd1:com) (cmd2:com), (~ ((beval m0 cond) = true)) -> ((ceval m0 cmd2\n      m1) -> (ceval m0 (Cif cond cmd1 cmd2) m1))\n  | E_WhileEnd : forall (cond:bexpr) (m:(map id Z)) (body:com), (~ ((beval m\n      cond) = true)) -> (ceval m (Cwhile cond body) m)\n  | E_WhileLoop : forall (mi:(map id Z)) (mj:(map id Z)) (mf:(map id Z))\n      (cond:bexpr) (body:com), ((beval mi cond) = true) -> ((ceval mi body\n      mj) -> ((ceval mj (Cwhile cond body) mf) -> (ceval mi (Cwhile cond\n      body) mf))).\n\nAxiom ceval_deterministic_aux : forall (c:com) (mi:(map id Z)) (mf1:(map id\n  Z)), (ceval mi c mf1) -> forall (mf2:(map id Z)), (ceval mi c mf2) ->\n  (mf1 = mf2).\n\nAxiom ceval_deterministic : forall (c:com) (mi:(map id Z)) (mf1:(map id Z))\n  (mf2:(map id Z)), (ceval mi c mf1) -> ((ceval mi c mf2) -> (mf1 = mf2)).\n\n(* Why3 assumption *)\nDefinition pos := Z.\n\n(* Why3 assumption *)\nDefinition stack := (list Z).\n\n(* Why3 assumption *)\nInductive machine_state :=\n  | VMS : Z -> (list Z) -> (map id Z) -> machine_state.\nAxiom machine_state_WhyType : WhyType machine_state.\nExisting Instance machine_state_WhyType.\n\n(* Why3 assumption *)\nDefinition ofs := Z.\n\n(* Why3 assumption *)\nInductive instr :=\n  | Iconst : Z -> instr\n  | Ivar : id -> instr\n  | Isetvar : id -> instr\n  | Ibranch : Z -> instr\n  | Iadd : instr\n  | Isub : instr\n  | Imul : instr\n  | Ibeq : Z -> instr\n  | Ibne : Z -> instr\n  | Ible : Z -> instr\n  | Ibgt : Z -> instr\n  | Ihalt : instr.\nAxiom instr_WhyType : WhyType instr.\nExisting Instance instr_WhyType.\n\n(* Why3 assumption *)\nDefinition code := (list instr).\n\n(* Why3 assumption *)\nInductive codeseq_at: (list instr) -> Z -> (list instr) -> Prop :=\n  | codeseq_at_intro : forall (c1:(list instr)) (c2:(list instr))\n      (c3:(list instr)), (codeseq_at\n      (Init.Datatypes.app (Init.Datatypes.app c1 c2) c3)\n      (list.Length.length c1) c2).\n\nAxiom codeseq_at_app_right : forall (c:(list instr)) (c1:(list instr))\n  (c2:(list instr)) (p:Z), (codeseq_at c p (Init.Datatypes.app c1 c2)) ->\n  (codeseq_at c (p + (list.Length.length c1))%Z c2).\n\nAxiom codeseq_at_app_left : forall (c:(list instr)) (c1:(list instr))\n  (c2:(list instr)) (p:Z), (codeseq_at c p (Init.Datatypes.app c1 c2)) ->\n  (codeseq_at c p c1).\n\n(* Why3 assumption *)\nDefinition iconst (n:Z): (list instr) :=\n  (Init.Datatypes.cons (Iconst n) Init.Datatypes.nil).\n\n(* Why3 assumption *)\nDefinition ivar (x:id): (list instr) :=\n  (Init.Datatypes.cons (Ivar x) Init.Datatypes.nil).\n\n(* Why3 assumption *)\nDefinition isetvar (x:id): (list instr) :=\n  (Init.Datatypes.cons (Isetvar x) Init.Datatypes.nil).\n\n(* Why3 assumption *)\nDefinition ibeq (ofs1:Z): (list instr) :=\n  (Init.Datatypes.cons (Ibeq ofs1) Init.Datatypes.nil).\n\n(* Why3 assumption *)\nDefinition ible (ofs1:Z): (list instr) :=\n  (Init.Datatypes.cons (Ible ofs1) Init.Datatypes.nil).\n\n(* Why3 assumption *)\nDefinition ibne (ofs1:Z): (list instr) :=\n  (Init.Datatypes.cons (Ibne ofs1) Init.Datatypes.nil).\n\n(* Why3 assumption *)\nDefinition ibgt (ofs1:Z): (list instr) :=\n  (Init.Datatypes.cons (Ibgt ofs1) Init.Datatypes.nil).\n\n(* Why3 assumption *)\nDefinition ibranch (ofs1:Z): (list instr) :=\n  (Init.Datatypes.cons (Ibranch ofs1) Init.Datatypes.nil).\n\n(* Why3 assumption *)\nInductive transition: (list instr) -> machine_state -> machine_state ->\n  Prop :=\n  | trans_const : forall (c:(list instr)) (p:Z) (n:Z), (codeseq_at c p\n      (iconst n)) -> forall (s:(list Z)) (m:(map id Z)), (transition c (VMS p\n      s m) (VMS (p + 1%Z)%Z (Init.Datatypes.cons n s) m))\n  | trans_var : forall (c:(list instr)) (p:Z) (x:id), (codeseq_at c p\n      (ivar x)) -> forall (s:(list Z)) (m:(map id Z)), (transition c (VMS p s\n      m) (VMS (p + 1%Z)%Z (Init.Datatypes.cons (get m x) s) m))\n  | trans_set_var : forall (c:(list instr)) (p:Z) (x:id), (codeseq_at c p\n      (isetvar x)) -> forall (n:Z) (s:(list Z)) (m:(map id Z)), (transition c\n      (VMS p (Init.Datatypes.cons n s) m) (VMS (p + 1%Z)%Z s (set m x n)))\n  | trans_add : forall (c:(list instr)) (p:Z), (codeseq_at c p\n      (Init.Datatypes.cons Iadd Init.Datatypes.nil)) -> forall (n1:Z) (n2:Z)\n      (s:(list Z)) (m:(map id Z)), (transition c (VMS p\n      (Init.Datatypes.cons n2 (Init.Datatypes.cons n1 s)) m) (VMS (p + 1%Z)%Z\n      (Init.Datatypes.cons (n1 + n2)%Z s) m))\n  | trans_sub : forall (c:(list instr)) (p:Z), (codeseq_at c p\n      (Init.Datatypes.cons Isub Init.Datatypes.nil)) -> forall (n1:Z) (n2:Z)\n      (s:(list Z)) (m:(map id Z)), (transition c (VMS p\n      (Init.Datatypes.cons n2 (Init.Datatypes.cons n1 s)) m) (VMS (p + 1%Z)%Z\n      (Init.Datatypes.cons (n1 - n2)%Z s) m))\n  | trans_mul : forall (c:(list instr)) (p:Z), (codeseq_at c p\n      (Init.Datatypes.cons Imul Init.Datatypes.nil)) -> forall (n1:Z) (n2:Z)\n      (s:(list Z)) (m:(map id Z)), (transition c (VMS p\n      (Init.Datatypes.cons n2 (Init.Datatypes.cons n1 s)) m) (VMS (p + 1%Z)%Z\n      (Init.Datatypes.cons (n1 * n2)%Z s) m))\n  | trans_beq : forall (c:(list instr)) (p1:Z) (ofs1:Z), (codeseq_at c p1\n      (ibeq ofs1)) -> forall (s:(list Z)) (m:(map id Z)) (n1:Z) (n2:Z),\n      (n1 = n2) -> (transition c (VMS p1\n      (Init.Datatypes.cons n2 (Init.Datatypes.cons n1 s)) m)\n      (VMS ((p1 + 1%Z)%Z + ofs1)%Z s m))\n  | trans_beq1 : forall (c:(list instr)) (p1:Z) (ofs1:Z), (codeseq_at c p1\n      (ibeq ofs1)) -> forall (s:(list Z)) (m:(map id Z)) (n1:Z) (n2:Z),\n      (~ (n1 = n2)) -> (transition c (VMS p1\n      (Init.Datatypes.cons n2 (Init.Datatypes.cons n1 s)) m)\n      (VMS (p1 + 1%Z)%Z s m))\n  | trans_bne : forall (c:(list instr)) (p1:Z) (ofs1:Z), (codeseq_at c p1\n      (ibne ofs1)) -> forall (s:(list Z)) (m:(map id Z)) (n1:Z) (n2:Z),\n      (n1 = n2) -> (transition c (VMS p1\n      (Init.Datatypes.cons n2 (Init.Datatypes.cons n1 s)) m)\n      (VMS (p1 + 1%Z)%Z s m))\n  | trans_bne1 : forall (c:(list instr)) (p1:Z) (ofs1:Z), (codeseq_at c p1\n      (ibne ofs1)) -> forall (s:(list Z)) (m:(map id Z)) (n1:Z) (n2:Z),\n      (~ (n1 = n2)) -> (transition c (VMS p1\n      (Init.Datatypes.cons n2 (Init.Datatypes.cons n1 s)) m)\n      (VMS ((p1 + 1%Z)%Z + ofs1)%Z s m))\n  | trans_ble : forall (c:(list instr)) (p1:Z) (ofs1:Z), (codeseq_at c p1\n      (ible ofs1)) -> forall (s:(list Z)) (m:(map id Z)) (n1:Z) (n2:Z),\n      (n1 <= n2)%Z -> (transition c (VMS p1\n      (Init.Datatypes.cons n2 (Init.Datatypes.cons n1 s)) m)\n      (VMS ((p1 + 1%Z)%Z + ofs1)%Z s m))\n  | trans_ble1 : forall (c:(list instr)) (p1:Z) (ofs1:Z), (codeseq_at c p1\n      (ible ofs1)) -> forall (s:(list Z)) (m:(map id Z)) (n1:Z) (n2:Z),\n      (~ (n1 <= n2)%Z) -> (transition c (VMS p1\n      (Init.Datatypes.cons n2 (Init.Datatypes.cons n1 s)) m)\n      (VMS (p1 + 1%Z)%Z s m))\n  | trans_bgt : forall (c:(list instr)) (p1:Z) (ofs1:Z), (codeseq_at c p1\n      (ibgt ofs1)) -> forall (s:(list Z)) (m:(map id Z)) (n1:Z) (n2:Z),\n      (n1 <= n2)%Z -> (transition c (VMS p1\n      (Init.Datatypes.cons n2 (Init.Datatypes.cons n1 s)) m)\n      (VMS (p1 + 1%Z)%Z s m))\n  | trans_bgt1 : forall (c:(list instr)) (p1:Z) (ofs1:Z), (codeseq_at c p1\n      (ibgt ofs1)) -> forall (s:(list Z)) (m:(map id Z)) (n1:Z) (n2:Z),\n      (~ (n1 <= n2)%Z) -> (transition c (VMS p1\n      (Init.Datatypes.cons n2 (Init.Datatypes.cons n1 s)) m)\n      (VMS ((p1 + 1%Z)%Z + ofs1)%Z s m))\n  | trans_branch : forall (c:(list instr)) (p:Z) (ofs1:Z), (codeseq_at c p\n      (ibranch ofs1)) -> forall (s:(list Z)) (m:(map id Z)), (transition c\n      (VMS p s m) (VMS ((p + 1%Z)%Z + ofs1)%Z s m)).\n\n(* Why3 assumption *)\nInductive transition_star: (list instr) -> machine_state -> machine_state ->\n  Prop :=\n  | Refl : forall (p:(list instr)) (x:machine_state), (transition_star p x x)\n  | Step : forall (p:(list instr)) (x:machine_state) (y:machine_state)\n      (z:machine_state), (transition p x y) -> ((transition_star p y z) ->\n      (transition_star p x z)).\n\nAxiom transition_star_one : forall (p:(list instr)) (s1:machine_state)\n  (s2:machine_state), (transition p s1 s2) -> (transition_star p s1 s2).\n\nAxiom transition_star_transitive : forall (p:(list instr)) (s1:machine_state)\n  (s2:machine_state) (s3:machine_state), (transition_star p s1 s2) ->\n  ((transition_star p s2 s3) -> (transition_star p s1 s3)).\n\n(* Why3 assumption *)\nDefinition vm_terminates (c:(list instr)) (mi:(map id Z)) (mf:(map id\n  Z)): Prop := exists p:Z, (codeseq_at c p\n  (Init.Datatypes.cons Ihalt Init.Datatypes.nil)) /\\ (transition_star c\n  (VMS 0%Z Init.Datatypes.nil mi) (VMS p Init.Datatypes.nil mf)).\n\n(* Why3 assumption *)\nDefinition fst {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b} (p:(a*\n  b)%type): a := match p with\n  | (x, _) => x\n  end.\n\n(* Why3 assumption *)\nDefinition snd {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b} (p:(a*\n  b)%type): b := match p with\n  | (_, y) => y\n  end.\n\n(* Why3 assumption *)\nDefinition pred := (machine_state -> bool).\n\n(* Why3 assumption *)\nDefinition rel := (machine_state -> (machine_state -> bool)).\n\n(* Why3 assumption *)\nDefinition pre (a:Type) := (a -> (Z -> (machine_state -> bool))).\n\n(* Why3 assumption *)\nDefinition post (a:Type) := (a -> (Z -> (machine_state -> (machine_state ->\n  bool)))).\n\n(* Why3 assumption *)\nInductive hl\n  (a:Type) :=\n  | mk_hl : (list instr) -> (a -> (Z -> (machine_state -> bool))) -> (a ->\n      (Z -> (machine_state -> (machine_state -> bool)))) -> hl a.\nAxiom hl_WhyType : forall (a:Type) {a_WT:WhyType a}, WhyType (hl a).\nExisting Instance hl_WhyType.\nImplicit Arguments mk_hl [[a]].\n\n(* Why3 assumption *)\nDefinition post1 {a:Type} {a_WT:WhyType a} (v:(hl a)): (a -> (Z ->\n  (machine_state -> (machine_state -> bool)))) :=\n  match v with\n  | (mk_hl x x1 x2) => x2\n  end.\n\n(* Why3 assumption *)\nDefinition pre1 {a:Type} {a_WT:WhyType a} (v:(hl a)): (a -> (Z ->\n  (machine_state -> bool))) := match v with\n  | (mk_hl x x1 x2) => x1\n  end.\n\n(* Why3 assumption *)\nDefinition code1 {a:Type} {a_WT:WhyType a} (v:(hl a)): (list instr) :=\n  match v with\n  | (mk_hl x x1 x2) => x\n  end.\n\n(* Why3 assumption *)\nDefinition wp_trans (a:Type) := (a -> (Z -> ((machine_state -> bool) ->\n  (machine_state -> bool)))).\n\n(* Why3 assumption *)\nInductive wp\n  (a:Type) :=\n  | mk_wp : (list instr) -> (a -> (Z -> ((machine_state -> bool) ->\n      (machine_state -> bool)))) -> wp a.\nAxiom wp_WhyType : forall (a:Type) {a_WT:WhyType a}, WhyType (wp a).\nExisting Instance wp_WhyType.\nImplicit Arguments mk_wp [[a]].\n\n(* Why3 assumption *)\nDefinition wp1 {a:Type} {a_WT:WhyType a} (v:(wp a)): (a -> (Z ->\n  ((machine_state -> bool) -> (machine_state -> bool)))) :=\n  match v with\n  | (mk_wp x x1) => x1\n  end.\n\n(* Why3 assumption *)\nDefinition wcode {a:Type} {a_WT:WhyType a} (v:(wp a)): (list instr) :=\n  match v with\n  | (mk_wp x x1) => x\n  end.\n\n(* Why3 assumption *)\nDefinition contextual_irrelevance (c:(list instr)) (p:Z) (ms1:machine_state)\n  (ms2:machine_state): Prop := forall (c_glob:(list instr)), (codeseq_at\n  c_glob p c) -> (transition_star c_glob ms1 ms2).\n\n(* Why3 assumption *)\nDefinition hl_correctness {a:Type} {a_WT:WhyType a} (cs:(hl a)): Prop :=\n  forall (x:a) (p:Z) (ms:machine_state), (((((pre1 cs) x) p) ms) = true) ->\n  exists ms':machine_state, ((((((post1 cs) x) p) ms) ms') = true) /\\\n  (contextual_irrelevance (code1 cs) p ms ms').\n\n(* Why3 assumption *)\nDefinition wp_correctness {a:Type} {a_WT:WhyType a} (code2:(wp a)): Prop :=\n  forall (x:a) (p:Z) (post2:(machine_state -> bool)) (ms:machine_state),\n  ((((((wp1 code2) x) p) post2) ms) = true) -> exists ms':machine_state,\n  ((post2 ms') = true) /\\ (contextual_irrelevance (wcode code2) p ms ms').\n\n(* Why3 assumption *)\nDefinition seq_wp {a:Type} {a_WT:WhyType a} (l1:Z) (w1:(a -> (Z ->\n  ((machine_state -> bool) -> (machine_state -> bool))))) (w2:((a*\n  machine_state)%type -> (Z -> ((machine_state -> bool) -> (machine_state ->\n  bool))))): (a -> (Z -> ((machine_state -> bool) -> (machine_state ->\n  bool)))) := fun (x:a) (p:Z) (q:(machine_state -> bool))\n  (ms:machine_state) => ((((w1 x) p) (((w2 (x, ms)) (p + l1)%Z) q)) ms).\n\nAxiom seq_wp_lemma : forall {a:Type} {a_WT:WhyType a}, forall (l1:Z)\n  (w1:(a -> (Z -> ((machine_state -> bool) -> (machine_state -> bool)))))\n  (w2:((a* machine_state)%type -> (Z -> ((machine_state -> bool) ->\n  (machine_state -> bool))))) (x:a) (p:Z) (q:(machine_state -> bool))\n  (ms:machine_state), ((((((seq_wp l1 w1 w2) x) p) q) ms) = ((((w1 x) p)\n  (((w2 (x, ms)) (p + l1)%Z) q)) ms)).\n\nParameter fork_wp: forall {a:Type} {a_WT:WhyType a}, (a -> (Z ->\n  ((machine_state -> bool) -> (machine_state -> bool)))) -> (a -> (Z ->\n  (machine_state -> bool))) -> (a -> (Z -> ((machine_state -> bool) ->\n  (machine_state -> bool)))).\n\nAxiom fork_wp_def : forall {a:Type} {a_WT:WhyType a}, forall (w:(a -> (Z ->\n  ((machine_state -> bool) -> (machine_state -> bool))))) (cond:(a -> (Z ->\n  (machine_state -> bool)))) (x:a) (p:Z) (q:(machine_state -> bool))\n  (ms:machine_state), ((((((fork_wp w cond) x) p) q) ms) = true) <->\n  (((~ ((((cond x) p) ms) = true)) -> ((q ms) = true)) /\\ (((((cond x) p)\n  ms) = true) -> (((((w x) p) q) ms) = true))).\n\nAxiom fork_wp_lemma : forall {a:Type} {a_WT:WhyType a}, forall (w:(a -> (Z ->\n  ((machine_state -> bool) -> (machine_state -> bool))))) (cond:(a -> (Z ->\n  (machine_state -> bool)))) (x:a) (p:Z) (q:(machine_state -> bool))\n  (ms:machine_state), ((((((fork_wp w cond) x) p) q) ms) = true) <->\n  (((~ ((((cond x) p) ms) = true)) -> ((q ms) = true)) /\\ (((((cond x) p)\n  ms) = true) -> (((((w x) p) q) ms) = true))).\n\nParameter towp_wp: forall {a:Type} {a_WT:WhyType a}, (a -> (Z ->\n  (machine_state -> bool))) -> (a -> (Z -> (machine_state ->\n  (machine_state -> bool)))) -> (a -> (Z -> ((machine_state -> bool) ->\n  (machine_state -> bool)))).\n\nAxiom towp_wp_def : forall {a:Type} {a_WT:WhyType a}, forall (pr:(a -> (Z ->\n  (machine_state -> bool)))) (ps:(a -> (Z -> (machine_state ->\n  (machine_state -> bool))))) (x:a) (p:Z) (q:(machine_state -> bool))\n  (ms:machine_state), ((((((towp_wp pr ps) x) p) q) ms) = true) <-> (((((pr\n  x) p) ms) = true) /\\ forall (ms':machine_state), (((((ps x) p) ms)\n  ms') = true) -> ((q ms') = true)).\n\nAxiom towp_wp_lemma : forall {a:Type} {a_WT:WhyType a}, forall (pr:(a ->\n  (Z -> (machine_state -> bool)))) (ps:(a -> (Z -> (machine_state ->\n  (machine_state -> bool))))) (x:a) (p:Z) (q:(machine_state -> bool))\n  (ms:machine_state), ((((((towp_wp pr ps) x) p) q) ms) = true) <-> (((((pr\n  x) p) ms) = true) /\\ forall (ms':machine_state), (((((ps x) p) ms)\n  ms') = true) -> ((q ms') = true)).\n\nParameter trivial_pre: forall {a:Type} {a_WT:WhyType a}, (a -> (Z ->\n  (machine_state -> bool))).\n\nAxiom trivial_pre_def : forall {a:Type} {a_WT:WhyType a}, forall (us:a) (p:Z)\n  (ms:machine_state), (((((trivial_pre : (a -> (Z -> (machine_state ->\n  bool)))) us) p) ms) = true) <-> match ms with\n  | (VMS p' _ _) => (p = p')\n  end.\n\n(* Why3 assumption *)\nInductive acc {a:Type} {a_WT:WhyType a}: (a -> (a -> bool)) -> a -> Prop :=\n  | Acc : forall (r:(a -> (a -> bool))) (x:a), (forall (y:a), (((r y)\n      x) = true) -> (acc r y)) -> (acc r x).\n\nParameter loop_progress: forall {a:Type} {a_WT:WhyType a}, (a -> (Z ->\n  (machine_state -> bool))) -> (a -> (Z -> (machine_state -> bool))) -> (a ->\n  (Z -> (machine_state -> (machine_state -> bool)))) -> (a -> (Z ->\n  (machine_state -> (machine_state -> bool)))).\n\nAxiom loop_progress_def : forall {a:Type} {a_WT:WhyType a}, forall (inv:(a ->\n  (Z -> (machine_state -> bool)))) (post2:(a -> (Z -> (machine_state ->\n  bool)))) (var:(a -> (Z -> (machine_state -> (machine_state -> bool)))))\n  (x:a) (p:Z) (ms:machine_state) (ms':machine_state), ((((((loop_progress inv\n  post2 var) x) p) ms) ms') = true) <-> ((((((inv x) p) ms') = true) /\\\n  (((((var x) p) ms') ms) = true)) \\/ ((((post2 x) p) ms') = true)).\n\n(* Why3 assumption *)\nDefinition forget_old {a:Type} {a_WT:WhyType a} (post2:(a -> (Z ->\n  (machine_state -> bool)))): (a -> (Z -> (machine_state -> (machine_state ->\n  bool)))) := fun (x:a) (p:Z) (us:machine_state) => ((post2 x) p).\n\nParameter ifun_post: forall {a:Type} {a_WT:WhyType a}, (machine_state ->\n  machine_state) -> (a -> (Z -> (machine_state -> (machine_state -> bool)))).\n\nAxiom ifun_post_def : forall {a:Type} {a_WT:WhyType a},\n  forall (f:(machine_state -> machine_state)) (us:a) (us1:Z)\n  (ms:machine_state) (ms':machine_state), ((((((ifun_post f: (a -> (Z ->\n  (machine_state -> (machine_state -> bool))))) us) us1) ms) ms') = true) <->\n  (ms' = (f ms)).\n\nParameter iconst_post: forall {a:Type} {a_WT:WhyType a}, Z -> (a -> (Z ->\n  (machine_state -> (machine_state -> bool)))).\n\nAxiom iconst_post_def : forall {a:Type} {a_WT:WhyType a}, forall (n:Z) (us:a)\n  (p:Z) (ms:machine_state) (ms':machine_state), ((((((iconst_post n: (a ->\n  (Z -> (machine_state -> (machine_state -> bool))))) us) p) ms)\n  ms') = true) <-> forall (s:(list Z)) (m:(map id Z)), (ms = (VMS p s m)) ->\n  (ms' = (VMS (p + 1%Z)%Z (Init.Datatypes.cons n s) m)).\n\n(* Why3 assumption *)\nDefinition iconst_fun (n:Z): (machine_state -> machine_state) :=\n  fun (ms:machine_state) =>\n  match ms with\n  | (VMS p s m) => (VMS (p + 1%Z)%Z (Init.Datatypes.cons n s) m)\n  end.\n\nParameter ivar_post: forall {a:Type} {a_WT:WhyType a}, id -> (a -> (Z ->\n  (machine_state -> (machine_state -> bool)))).\n\nAxiom ivar_post_def : forall {a:Type} {a_WT:WhyType a}, forall (x:id) (us:a)\n  (p:Z) (ms:machine_state) (ms':machine_state), ((((((ivar_post x: (a ->\n  (Z -> (machine_state -> (machine_state -> bool))))) us) p) ms)\n  ms') = true) <-> forall (s:(list Z)) (m:(map id Z)), (ms = (VMS p s m)) ->\n  (ms' = (VMS (p + 1%Z)%Z (Init.Datatypes.cons (get m x) s) m)).\n\n(* Why3 assumption *)\nDefinition ivar_fun (x:id): (machine_state -> machine_state) :=\n  fun (ms:machine_state) =>\n  match ms with\n  | (VMS p s m) => (VMS (p + 1%Z)%Z (Init.Datatypes.cons (get m x) s) m)\n  end.\n\n(* Why3 assumption *)\nDefinition binop := (Z -> (Z -> Z)).\n\nParameter ibinop_pre: forall {a:Type} {a_WT:WhyType a}, (a -> (Z ->\n  (machine_state -> bool))).\n\nAxiom ibinop_pre_def : forall {a:Type} {a_WT:WhyType a}, forall (us:a) (p:Z)\n  (ms:machine_state), (((((ibinop_pre : (a -> (Z -> (machine_state ->\n  bool)))) us) p) ms) = true) <-> exists n1:Z, exists n2:Z,\n  exists s:(list Z), exists m:(map id Z), (ms = (VMS p\n  (Init.Datatypes.cons n2 (Init.Datatypes.cons n1 s)) m)).\n\nParameter ibinop_post: forall {a:Type} {a_WT:WhyType a}, (Z -> (Z -> Z)) ->\n  (a -> (Z -> (machine_state -> (machine_state -> bool)))).\n\nAxiom ibinop_post_def : forall {a:Type} {a_WT:WhyType a}, forall (op:(Z ->\n  (Z -> Z))) (us:a) (p:Z) (ms:machine_state) (ms':machine_state),\n  ((((((ibinop_post op: (a -> (Z -> (machine_state -> (machine_state ->\n  bool))))) us) p) ms) ms') = true) <-> forall (n1:Z) (n2:Z) (s:(list Z))\n  (m:(map id Z)), (ms = (VMS p\n  (Init.Datatypes.cons n2 (Init.Datatypes.cons n1 s)) m)) ->\n  (ms' = (VMS (p + 1%Z)%Z (Init.Datatypes.cons ((op n1) n2) s) m)).\n\n(* Why3 assumption *)\nDefinition ibinop_fun (op:(Z -> (Z -> Z))): (machine_state ->\n  machine_state) := fun (ms:machine_state) =>\n  match ms with\n  | (VMS p (Init.Datatypes.cons n2 (Init.Datatypes.cons n1 s)) m) =>\n      (VMS (p + 1%Z)%Z (Init.Datatypes.cons ((op n1) n2) s) m)\n  | _ => ms\n  end.\n\n(* Why3 assumption *)\nDefinition plus: (Z -> (Z -> Z)) := fun (x:Z) (y:Z) => (x + y)%Z.\n\n(* Why3 assumption *)\nDefinition sub: (Z -> (Z -> Z)) := fun (x:Z) (y:Z) => (x - y)%Z.\n\n(* Why3 assumption *)\nDefinition mul: (Z -> (Z -> Z)) := fun (x:Z) (y:Z) => (x * y)%Z.\n\nParameter inil_post: forall {a:Type} {a_WT:WhyType a}, (a -> (Z ->\n  (machine_state -> (machine_state -> bool)))).\n\nAxiom inil_post_def : forall {a:Type} {a_WT:WhyType a}, forall (us:a) (us1:Z)\n  (ms:machine_state) (ms':machine_state), ((((((inil_post : (a -> (Z ->\n  (machine_state -> (machine_state -> bool))))) us) us1) ms) ms') = true) <->\n  (ms = ms').\n\nParameter ibranch_post: forall {a:Type} {a_WT:WhyType a}, Z -> (a -> (Z ->\n  (machine_state -> (machine_state -> bool)))).\n\nAxiom ibranch_post_def : forall {a:Type} {a_WT:WhyType a}, forall (ofs1:Z)\n  (us:a) (p:Z) (ms:machine_state) (ms':machine_state),\n  ((((((ibranch_post ofs1: (a -> (Z -> (machine_state -> (machine_state ->\n  bool))))) us) p) ms) ms') = true) <-> forall (s:(list Z)) (m:(map id Z)),\n  (ms = (VMS p s m)) -> (ms' = (VMS ((p + 1%Z)%Z + ofs1)%Z s m)).\n\n(* Why3 assumption *)\nDefinition ibranch_fun (ofs1:Z): (machine_state -> machine_state) :=\n  fun (ms:machine_state) =>\n  match ms with\n  | (VMS p s m) => (VMS ((p + 1%Z)%Z + ofs1)%Z s m)\n  end.\n\n(* Why3 assumption *)\nDefinition cond := (Z -> (Z -> bool)).\n\nParameter icjump_post: forall {a:Type} {a_WT:WhyType a}, (Z -> (Z ->\n  bool)) -> Z -> (a -> (Z -> (machine_state -> (machine_state -> bool)))).\n\nAxiom icjump_post_def : forall {a:Type} {a_WT:WhyType a}, forall (cond1:(Z ->\n  (Z -> bool))) (ofs1:Z) (us:a) (p:Z) (ms:machine_state) (ms':machine_state),\n  ((((((icjump_post cond1 ofs1: (a -> (Z -> (machine_state ->\n  (machine_state -> bool))))) us) p) ms) ms') = true) <-> forall (n1:Z)\n  (n2:Z) (s:(list Z)) (m:(map id Z)), (ms = (VMS p\n  (Init.Datatypes.cons n2 (Init.Datatypes.cons n1 s)) m)) -> (((((cond1 n1)\n  n2) = true) -> (ms' = (VMS ((p + ofs1)%Z + 1%Z)%Z s m))) /\\ ((~ (((cond1\n  n1) n2) = true)) -> (ms' = (VMS (p + 1%Z)%Z s m)))).\n\nParameter icjump_fun: (Z -> (Z -> bool)) -> Z -> (machine_state ->\n  machine_state).\n\nAxiom icjump_fun_def : forall (cond1:(Z -> (Z -> bool))) (ofs1:Z)\n  (ms:machine_state),\n  match ms with\n  | (VMS p (Init.Datatypes.cons n2 (Init.Datatypes.cons n1 s)) m) =>\n      ((((cond1 n1) n2) = true) -> (((icjump_fun cond1 ofs1)\n      ms) = (VMS ((p + ofs1)%Z + 1%Z)%Z s m))) /\\ ((~ (((cond1 n1)\n      n2) = true)) -> (((icjump_fun cond1 ofs1) ms) = (VMS (p + 1%Z)%Z s m)))\n  | _ => (((icjump_fun cond1 ofs1) ms) = ms)\n  end.\n\nParameter beq: (Z -> (Z -> bool)).\n\nAxiom beq_def : forall (x:Z) (y:Z), (((beq x) y) = true) <-> (x = y).\n\nParameter bne: (Z -> (Z -> bool)).\n\nAxiom bne_def : forall (x:Z) (y:Z), (((bne x) y) = true) <-> ~ (x = y).\n\nParameter ble: (Z -> (Z -> bool)).\n\nAxiom ble_def : forall (x:Z) (y:Z), (((ble x) y) = true) <-> (x <= y)%Z.\n\nParameter bgt: (Z -> (Z -> bool)).\n\nAxiom bgt_def : forall (x:Z) (y:Z), (((bgt x) y) = true) <-> (y < x)%Z.\n\nParameter isetvar_pre: forall {a:Type} {a_WT:WhyType a}, (a -> (Z ->\n  (machine_state -> bool))).\n\nAxiom isetvar_pre_def : forall {a:Type} {a_WT:WhyType a}, forall (us:a) (p:Z)\n  (ms:machine_state), (((((isetvar_pre : (a -> (Z -> (machine_state ->\n  bool)))) us) p) ms) = true) <-> exists n:Z, exists s:(list Z),\n  exists m:(map id Z), (ms = (VMS p (Init.Datatypes.cons n s) m)).\n\nParameter isetvar_post: forall {a:Type} {a_WT:WhyType a}, id -> (a -> (Z ->\n  (machine_state -> (machine_state -> bool)))).\n\nAxiom isetvar_post_def : forall {a:Type} {a_WT:WhyType a}, forall (x:id)\n  (us:a) (p:Z) (ms:machine_state) (ms':machine_state),\n  ((((((isetvar_post x: (a -> (Z -> (machine_state -> (machine_state ->\n  bool))))) us) p) ms) ms') = true) <-> forall (s:(list Z)) (n:Z) (m:(map id\n  Z)), (ms = (VMS p (Init.Datatypes.cons n s) m)) -> (ms' = (VMS (p + 1%Z)%Z\n  s (set m x n))).\n\n(* Why3 assumption *)\nDefinition isetvar_fun (x:id): (machine_state -> machine_state) :=\n  fun (ms:machine_state) =>\n  match ms with\n  | (VMS p (Init.Datatypes.cons n s) m) => (VMS (p + 1%Z)%Z s (set m x n))\n  | _ => ms\n  end.\n\nParameter aexpr_post: forall {a:Type} {a_WT:WhyType a}, aexpr -> Z -> (a ->\n  (Z -> (machine_state -> (machine_state -> bool)))).\n\nAxiom aexpr_post_def : forall {a:Type} {a_WT:WhyType a}, forall (a1:aexpr)\n  (len:Z) (us:a) (p:Z) (ms:machine_state) (ms':machine_state),\n  ((((((aexpr_post a1 len: (a -> (Z -> (machine_state -> (machine_state ->\n  bool))))) us) p) ms) ms') = true) <->\n  match ms with\n  | (VMS _ s m) => (ms' = (VMS (p + len)%Z (Init.Datatypes.cons (aeval m\n      a1) s) m))\n  end.\n\nParameter bexpr_post: forall {a:Type} {a_WT:WhyType a}, bexpr -> bool -> Z ->\n  Z -> (a -> (Z -> (machine_state -> (machine_state -> bool)))).\n\nAxiom bexpr_post_def : forall {a:Type} {a_WT:WhyType a}, forall (b:bexpr)\n  (cond1:bool) (out_t:Z) (out_f:Z) (us:a) (p:Z) (ms:machine_state)\n  (ms':machine_state), (((((((bexpr_post b cond1 out_t out_f: (a -> (Z ->\n  (machine_state -> (machine_state -> bool))))) us) p) ms) ms') = true) ->\n  match ms with\n  | (VMS _ s m) => (((beval m b) = cond1) -> (ms' = (VMS (p + out_t)%Z s\n      m))) /\\ ((~ ((beval m b) = cond1)) -> (ms' = (VMS (p + out_f)%Z s m)))\n  end) /\\\n  (match ms with\n  | (VMS _ s m) => (((beval m b) = cond1) /\\ (ms' = (VMS (p + out_t)%Z s\n      m))) \\/ ((~ ((beval m b) = cond1)) /\\ (ms' = (VMS (p + out_f)%Z s m)))\n  end -> ((((((bexpr_post b cond1 out_t out_f: (a -> (Z -> (machine_state ->\n  (machine_state -> bool))))) us) p) ms) ms') = true)).\n\nParameter exec_cond: forall {a:Type} {a_WT:WhyType a}, bexpr -> bool -> (a ->\n  (Z -> (machine_state -> bool))).\n\nAxiom exec_cond_def : forall {a:Type} {a_WT:WhyType a}, forall (b1:bexpr)\n  (cond1:bool) (us:a) (us1:Z) (ms:machine_state), (((((exec_cond b1\n  cond1: (a -> (Z -> (machine_state -> bool)))) us) us1) ms) = true) <->\n  match ms with\n  | (VMS _ _ m) => ((beval m b1) = cond1)\n  end.\n\nParameter com_pre: forall {a:Type} {a_WT:WhyType a}, com -> (a -> (Z ->\n  (machine_state -> bool))).\n\nAxiom com_pre_def : forall {a:Type} {a_WT:WhyType a}, forall (cmd:com) (us:a)\n  (p:Z) (ms:machine_state), (((((com_pre cmd: (a -> (Z -> (machine_state ->\n  bool)))) us) p) ms) = true) <->\n  match ms with\n  | (VMS p' _ m) => (p = p') /\\ exists m':(map id Z), (ceval m cmd m')\n  end.\n\nParameter com_post: forall {a:Type} {a_WT:WhyType a}, com -> Z -> (a -> (Z ->\n  (machine_state -> (machine_state -> bool)))).\n\nAxiom com_post_def : forall {a:Type} {a_WT:WhyType a}, forall (cmd:com)\n  (len:Z) (us:a) (us1:Z) (ms:machine_state) (ms':machine_state),\n  ((((((com_post cmd len: (a -> (Z -> (machine_state -> (machine_state ->\n  bool))))) us) us1) ms) ms') = true) <->\n  match ms with\n  | (VMS p s m) =>\n      match ms' with\n      | (VMS p' s' m') => (p' = (p + len)%Z) /\\ ((s' = s) /\\ (ceval m cmd\n          m'))\n      end\n  end.\n\nParameter exec_cond_old: forall {a:Type} {a_WT:WhyType a}, bexpr -> bool ->\n  ((a* machine_state)%type -> (Z -> (machine_state -> bool))).\n\nAxiom exec_cond_old_def : forall {a:Type} {a_WT:WhyType a}, forall (b1:bexpr)\n  (cond1:bool) (x:(a* machine_state)%type) (us:Z) (us1:machine_state),\n  (((((exec_cond_old b1 cond1: ((a* machine_state)%type -> (Z ->\n  (machine_state -> bool)))) x) us) us1) = true) <->\n  match (snd x) with\n  | (VMS _ _ m) => ((beval m b1) = cond1)\n  end.\n\nParameter loop_invariant: forall {a:Type} {a_WT:WhyType a}, com -> ((a*\n  machine_state)%type -> (Z -> (machine_state -> bool))).\n\nAxiom loop_invariant_def : forall {a:Type} {a_WT:WhyType a}, forall (c:com)\n  (x:(a* machine_state)%type) (p:Z) (msi:machine_state),\n  (((((loop_invariant c: ((a* machine_state)%type -> (Z -> (machine_state ->\n  bool)))) x) p) msi) = true) <->\n  match (snd x) with\n  | (VMS _ s0 m0) =>\n      match msi with\n      | (VMS pi si mi) => (pi = p) /\\ ((s0 = si) /\\ exists mf:(map id Z),\n          (ceval m0 c mf) /\\ (ceval mi c mf))\n      end\n  end.\n\nParameter loop_post: forall {a:Type} {a_WT:WhyType a}, com -> Z -> ((a*\n  machine_state)%type -> (Z -> (machine_state -> bool))).\n\nAxiom loop_post_def : forall {a:Type} {a_WT:WhyType a}, forall (c:com)\n  (len:Z) (x:(a* machine_state)%type) (p:Z) (msf:machine_state),\n  (((((loop_post c len: ((a* machine_state)%type -> (Z -> (machine_state ->\n  bool)))) x) p) msf) = true) <->\n  match (snd x) with\n  | (VMS _ s0 m0) =>\n      match msf with\n      | (VMS pf sf mf) => (pf = (p + len)%Z) /\\ ((s0 = sf) /\\ (ceval m0 c\n          mf))\n      end\n  end.\n\nParameter loop_variant: forall {a:Type} {a_WT:WhyType a}, com -> bexpr ->\n  (a -> (Z -> (machine_state -> (machine_state -> bool)))).\n\nAxiom loop_variant_def : forall {a:Type} {a_WT:WhyType a}, forall (c:com)\n  (test:bexpr) (us:a) (us1:Z) (msj:machine_state) (msi:machine_state),\n  ((((((loop_variant c test: (a -> (Z -> (machine_state -> (machine_state ->\n  bool))))) us) us1) msj) msi) = true) <->\n  match msj with\n  | (VMS pj sj mj) =>\n      match msi with\n      | (VMS pi si mi) => (pj = pi) /\\ ((sj = si) /\\ ((ceval mi c mj) /\\\n          ((beval mi test) = true)))\n      end\n  end.\n\nRequire Import Why3.\nLtac ae := why3 \"Alt-Ergo,0.99.1,\".\nLtac cvc := why3 \"CVC4,1.4,\".\n\n(* Why3 goal *)\nTheorem WP_parameter_compile_com : forall {a:Type} {a_WT:WhyType a},\n  forall (cmd:com), forall (x:bexpr) (x1:com), (cmd = (Cwhile x x1)) ->\n  forall (code_body:(list instr)) (code_body1:(((a* machine_state)%type*\n  machine_state)%type -> (Z -> (machine_state -> bool)))) (code_body2:(((a*\n  machine_state)%type* machine_state)%type -> (Z -> (machine_state ->\n  (machine_state -> bool))))), let code_body3 := (mk_hl code_body code_body1\n  code_body2) in ((((code_body1 = (com_pre x1: (((a* machine_state)%type*\n  machine_state)%type -> (Z -> (machine_state -> bool))))) /\\ (hl_correctness\n  code_body3)) /\\ (code_body2 = (com_post x1\n  (list.Length.length code_body): (((a* machine_state)%type*\n  machine_state)%type -> (Z -> (machine_state -> (machine_state ->\n  bool))))))) -> let body_length :=\n  ((list.Length.length code_body) + 1%Z)%Z in forall (code_test:(list instr))\n  (code_test1:((a* machine_state)%type -> (Z -> (machine_state -> bool))))\n  (code_test2:((a* machine_state)%type -> (Z -> (machine_state ->\n  (machine_state -> bool))))), let code_test3 := (mk_hl code_test code_test1\n  code_test2) in ((((code_test1 = (trivial_pre : ((a* machine_state)%type ->\n  (Z -> (machine_state -> bool))))) /\\ (hl_correctness code_test3)) /\\\n  (code_test2 = (bexpr_post x false\n  ((list.Length.length code_test) + body_length)%Z\n  (list.Length.length code_test): ((a* machine_state)%type -> (Z ->\n  (machine_state -> (machine_state -> bool))))))) -> let ofs1 :=\n  ((list.Length.length code_test) + body_length)%Z in forall (o:(list instr))\n  (o1:((((a* machine_state)%type* machine_state)%type* machine_state)%type ->\n  (Z -> (machine_state -> bool)))) (o2:((((a* machine_state)%type*\n  machine_state)%type* machine_state)%type -> (Z -> (machine_state ->\n  (machine_state -> bool))))), let o3 := (mk_hl o o1 o2) in\n  ((((o1 = (trivial_pre : ((((a* machine_state)%type* machine_state)%type*\n  machine_state)%type -> (Z -> (machine_state -> bool))))) /\\\n  (o2 = (ibranch_post (-ofs1)%Z: ((((a* machine_state)%type*\n  machine_state)%type* machine_state)%type -> (Z -> (machine_state ->\n  (machine_state -> bool))))))) /\\ (((list.Length.length o) = 1%Z) /\\\n  (hl_correctness o3))) -> ((hl_correctness o3) -> forall (o4:(list instr))\n  (o5:((((a* machine_state)%type* machine_state)%type* machine_state)%type ->\n  (Z -> ((machine_state -> bool) -> (machine_state -> bool))))), let o6 :=\n  (mk_wp o4 o5) in ((((list.Length.length o4) = (list.Length.length o)) /\\\n  ((o5 = (towp_wp o1 o2)) /\\ (wp_correctness o6))) -> ((hl_correctness\n  code_body3) -> forall (o7:(list instr)) (o8:(((a* machine_state)%type*\n  machine_state)%type -> (Z -> ((machine_state -> bool) -> (machine_state ->\n  bool))))), let o9 := (mk_wp o7 o8) in\n  ((((list.Length.length o7) = (list.Length.length code_body)) /\\\n  ((o8 = (towp_wp code_body1 code_body2)) /\\ (wp_correctness o9))) ->\n  (((wp_correctness o9) /\\ (wp_correctness o6)) -> forall (o10:(list instr))\n  (o11:(((a* machine_state)%type* machine_state)%type -> (Z ->\n  ((machine_state -> bool) -> (machine_state -> bool))))), let o12 :=\n  (mk_wp o10 o11) in\n  ((((list.Length.length o10) = ((list.Length.length o7) + (list.Length.length o4))%Z) /\\\n  ((o11 = (seq_wp (list.Length.length o7) o8 o5)) /\\ (wp_correctness\n  o12))) -> ((wp_correctness o12) -> forall (o13:(list instr)) (o14:(((a*\n  machine_state)%type* machine_state)%type -> (Z -> ((machine_state ->\n  bool) -> (machine_state -> bool))))), let o15 := (mk_wp o13 o14) in\n  (((o14 = (fork_wp o11 (exec_cond x true: (((a* machine_state)%type*\n  machine_state)%type -> (Z -> (machine_state -> bool)))))) /\\\n  (((list.Length.length o13) = (list.Length.length o10)) /\\ (wp_correctness\n  o15))) -> ((hl_correctness code_test3) -> forall (o16:(list instr))\n  (o17:((a* machine_state)%type -> (Z -> ((machine_state -> bool) ->\n  (machine_state -> bool))))), let o18 := (mk_wp o16 o17) in\n  ((((list.Length.length o16) = (list.Length.length code_test)) /\\\n  ((o17 = (towp_wp code_test1 code_test2)) /\\ (wp_correctness o18))) ->\n  (((wp_correctness o18) /\\ (wp_correctness o15)) ->\n  forall (wp_while:(list instr)) (wp_while1:((a* machine_state)%type -> (Z ->\n  ((machine_state -> bool) -> (machine_state -> bool))))), let wp_while2 :=\n  (mk_wp wp_while wp_while1) in\n  ((((list.Length.length wp_while) = ((list.Length.length o16) + (list.Length.length o13))%Z) /\\\n  ((wp_while1 = (seq_wp (list.Length.length o16) o17 o14)) /\\ (wp_correctness\n  wp_while2))) -> let inv := (loop_invariant cmd: ((a* machine_state)%type ->\n  (Z -> (machine_state -> bool)))) in let var := (loop_variant x1 x: ((a*\n  machine_state)%type -> (Z -> (machine_state -> (machine_state ->\n  bool))))) in let o19 := (loop_progress inv (loop_post cmd ofs1: ((a*\n  machine_state)%type -> (Z -> (machine_state -> bool)))) var) in\n  (((wp_correctness wp_while2) /\\ forall (x2:(a* machine_state)%type) (p:Z)\n  (ms:machine_state), ((((inv x2) p) ms) = true) -> (((((wp_while1 x2) p)\n  (((o19 x2) p) ms)) ms) = true)) -> forall (hl_while:(list instr))\n  (hl_while1:((a* machine_state)%type -> (Z -> (machine_state -> bool))))\n  (hl_while2:((a* machine_state)%type -> (Z -> (machine_state ->\n  (machine_state -> bool))))), (((hl_while1 = inv) /\\ (hl_while2 = o19)) /\\\n  (((list.Length.length hl_while) = (list.Length.length wp_while)) /\\\n  (hl_correctness (mk_hl hl_while hl_while1 hl_while2)))) -> forall (x2:(a*\n  machine_state)%type) (p:Z) (ms:machine_state), ((((inv x2) p)\n  ms) = true) -> (acc ((var x2) p) ms))))))))))))))))).\n(* Why3 intros a a_WT cmd x x1 h1 code_body code_body1 code_body2 code_body3\n        ((h2,h3),h4) body_length code_test code_test1 code_test2 code_test3\n        ((h5,h6),h7) ofs1 o o1 o2 o3 ((h8,h9),(h10,h11)) h12 o4 o5 o6\n        (h13,(h14,h15)) h16 o7 o8 o9 (h17,(h18,h19)) (h20,h21) o10 o11 o12\n        (h22,(h23,h24)) h25 o13 o14 o15 (h26,(h27,h28)) h29 o16 o17 o18\n        (h30,(h31,h32)) (h33,h34) wp_while wp_while1 wp_while2\n        (h35,(h36,h37)) inv var o19 (h38,h39) hl_while hl_while1 hl_while2\n        ((h40,h41),(h42,h43)) x2 p ms h44. *)\nintros a a_WT cmd x x1 h1 code_body code_body1 code_body2 code_body3\n((h2,h3),h4) body_length code_test code_test1 code_test2 code_test3\n((h5,h6),h7) ofs o o1 o2 o3 ((h8,h9),(h10,h11)) h12 o4 o5 o6 (h13,(h14,h15))\nh16 o7 o8 o9 (h17,(h18,h19)) (h20,h21) o10 o11 o12 (h22,(h23,h24)) h25 o13\no14 o15 (h26,(h27,h28)) h29 o16 o17 o18 (h30,(h31,h32)) (h33,h34) wp_while\nwp_while1 wp_while2 (h35,(h36,h37)) inv var o19 (h38,h39) hl_while hl_while1\nhl_while2 ((h40,h41),(h42,h43)) x2 p ms h44.\napply loop_invariant_def in h44.\ndestruct x2.\ndestruct m.\ndestruct ms.\nsimpl in *.\ndestruct h44.\ndestruct H0.\ndestruct H1 as [mf [ P T]].\ninduction T; try discriminate.\napply Acc.\nintros.\napply loop_variant_def in H2.\nexfalso. cvc.\napply Acc.\nintros.\nreplace y with (VMS z0 l0 mj).\napply IHT2; trivial. \napply loop_variant_def in H2.\ndestruct y.\nassert (body = x1) by ae.\nassert (m0 = mj).\neapply ceval_deterministic.\n2: exact T1.\nae. ae.\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/double_wp/compiler/compiler_Compile_com_WP_parameter_compile_com_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2637547361171857}}
{"text": "(* Distributed under the terms of the MIT license. *)\nFrom Coq Require Import ssreflect ssrbool.\nFrom MetaCoq.Template Require Import config utils 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    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    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    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    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    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": "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/PCUICCumulProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.26371455871844895}}
{"text": "From iris.heap_lang Require Export lifting notation.\nSet Default Proof Using \"Type\".\n\n(** Specification for a clairvoyant coin. A clairvoyant coin predicts all the\nvalues that it will *non-deterministically* choose throughout the execution of\nthe program. This can be seen in the spec. The predicate [coin c bs] expresses\nthat [bs] is the list of all the values of the coin in the future. Note that\nthe [read_coin] operation returns the head of [bs] and that the [toss_coin]\noperation takes the [tail] of [bs]. *)\nRecord clairvoyant_coin_spec `{!heapG Σ} := ClairvoyantCoinSpec {\n  (* -- operations -- *)\n  new_coin: val;\n  read_coin: val;\n  toss_coin: val;\n  (* -- predicates -- *)\n  coin (c : val) (bs : list bool) : iProp Σ;\n  (* -- predicate properties -- *)\n  coin_exclusive c b1 b2 : coin c b1 -∗ coin c b2 -∗ False;\n  (* -- operation specs -- *)\n  new_coin_spec :\n    {{{ True }}}\n        new_coin #()\n    {{{ c bs, RET c ; coin c bs  }}};\n  read_coin_spec c bs:\n    {{{ coin c bs }}}\n        read_coin c\n    {{{ b bs', RET #b ; ⌜bs = b :: bs'⌝ ∗ coin c bs }}};\n  toss_coin_spec c bs:\n    {{{ coin c bs }}}\n        toss_coin c\n    {{{ b bs', RET #(); ⌜bs = b :: bs'⌝ ∗ coin c bs' }}};\n}.\nArguments clairvoyant_coin_spec _ {_}.\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/proph/clairvoyant_coin_spec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631556226292, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.26371454638446795}}
{"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.BiGraph.\nRequire Import CertiGraph.graph.MathGraph.\nRequire Import CertiGraph.graph.FiniteGraph.\nRequire Import CertiGraph.msl_application.Graph.\nRequire Import CertiGraph.msl_application.GraphBi.\nRequire Import CertiGraph.msl_application.GraphBi_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\nInstance 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_BI.\n\n  Context {pSGG_Bi: pPointwiseGraph_Graph_Bi}.\n  Context {sSGG_Bi: sPointwiseGraph_Graph_Bi bool unit}.\n\n  Existing Instances maGraph biGraph 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_Bi 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 (biGraph 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 (biGraph 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 (biGraph 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 (biGraph 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 (biGraph 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 (biGraph g1)); auto.\n        + apply (@left_sound _ _ _ _ _ _ g1 (biGraph 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 (biGraph 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 (biGraph g1)) in H; auto.\n      - apply (@right_valid _ _ _ _ _ _ g2 (biGraph 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 (biGraph g1) x); auto.\n      - rewrite (@right_sound _ _ _ _ _ _ g1 (biGraph g1) x); auto.\n      - apply (@right_valid _ _ _ _ _ _ g2 (biGraph g2) x); auto.\n      - rewrite (@right_sound _ _ _ _ _ _ g2 (biGraph 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 (biGraph g1)); auto.\n        * apply (@left_sound _ _ _ _ _ _ g1 (biGraph 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 (biGraph 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 (biGraph 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 (biGraph 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 (biGraph 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 (biGraph 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 (biGraph g)); auto.\n        * split; [|intuition]. apply (@right_valid _ _ _ _ _ _ g (biGraph 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_BI.\n", "meta": {"author": "anshumanmohan", "repo": "CertiDPK", "sha": "28afacefb162a27e74d744095229d9e4541e3d79", "save_path": "github-repos/coq/anshumanmohan-CertiDPK", "path": "github-repos/coq/anshumanmohan-CertiDPK/CertiDPK-28afacefb162a27e74d744095229d9e4541e3d79/data_structure/spatial_graph_dispose_bi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2636846817109188}}
{"text": "From Vellvm Require Import\n     CFG\n     LLVMAst\n     TopLevel\n     TopLevelRefinements\n     DynamicTypes.\n\nFrom ITree Require Import\n     ITree.\n\nFrom Coq Require Export\n     Relations.\n\nImport R.\n\nDefinition transformation := mcfg dtyp -> mcfg dtyp.\nAbout refine_mcfg.\nAbout refine_mcfg.\nDefinition transformation_correct (T: transformation): Prop :=\n  forall dt entry args intrinsics m, refine_mcfg dt entry args intrinsics m (T m).\n\n\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/Transformations/Transformation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2636846758921486}}
{"text": "Require Import Coq.Lists.List.\nImport ListNotations.\nRequire Import Coq.Strings.String.\nRequire Import StructTact.StructTactics.\nRequire Import Omega.\nRequire Import Coq.Logic.Eqdep_dec.\nRequire Import Equations.Equations.\n\nRequire Import CakeSem.Utils.\nRequire Import FFI.\nRequire Import CakeSem.Namespace.\nRequire Import CakeSem.CakeAST.\nRequire Import CakeSem.SemanticsAux.\nRequire Import CakeSem.Evaluate.\n\nRequire Import BasisPlus.\nRequire Import BasisEvaluated.\n\n(* Definition init_env : sem_env val := empty_sem_env. *)\n(* Definition init_store := empty_store val. *)\n(* Parameter init_ffi_st : ffi_state nat. *)\n(* Definition init_state := Build_state 0 init_store init_ffi_st 0 0. *)\n\nTheorem evaluate_decs_Dmod : forall (fuel : nat) (mn : modN) (st st' : state nat) (env env' : sem_env val) (ds : list dec),\n    evaluate_decs fuel st env ds = (st', Rval env') ->\n    evaluate_decs fuel st env [Dmod mn ds] = (st', Rval {| sev := nsLift mn (sev env'); sec := nsLift mn (sec env') |}).\nProof.\n  intros.\n  simp evaluate_decs.\n  rewrite H.\n  reflexivity.\nQed.\n\nTheorem evaluate_decs_Dlocal : forall (fuel : nat) (st st' st'' : state nat) (env env' env'' : sem_env val) (ds1 ds2 : list dec),\n    evaluate_decs fuel st env ds1 = (st', Rval env') ->\n    evaluate_decs fuel st' (extend_dec_env env' env) ds2 = (st'', Rval env'') ->\n    evaluate_decs fuel st env [Dlocal ds1 ds2] = (st'', Rval env'').\nProof.\n  intros.\n  simp evaluate_decs.\n  rewrite H.\n  simpl.\n  rewrite H0.\n  reflexivity.\nQed.\n\nTheorem extend_empty_r : forall V (env : sem_env V),\n    extend_dec_env env {| sev := nsEmpty; sec := nsEmpty |} = env.\nProof.\n  intros.\n  destruct env.\n  unfold extend_dec_env.\n  unfold nsAppend.\n  simpl.\n  unfold nsEmpty.\n  repeat rewrite app_nil_r.\n  reflexivity.\nQed.\n\nTheorem extend_empty_l : forall V (env : sem_env V),\n    extend_dec_env {| sev := nsEmpty; sec := nsEmpty |} env = env.\nProof.\n  intros.\n  destruct env.\n  unfold extend_dec_env.\n  unfold nsAppend.\n  reflexivity.\nQed.\n\n\n\nTheorem evaluate_0_26_correct :\n  evaluate_decs 100 init_state init_env prog_0_26 =\n  (st_0_26, Rval env_0_26).\nProof.\n  reflexivity.\nQed.\n\nTheorem evaluate_0_27_correct :\n  evaluate_decs 100 init_state init_env (prog_0_26 ++ [dec_def_27]) =\n  (st_0_26, Rval env_27).\nProof.\n  reflexivity.\nQed.\n\nTheorem evaluate_0_29_correct :\n  evaluate_decs 100 init_state init_env (prog_0_26 ++ [dec_def_27; dec_def_28; dec_def_29]) =\n  (st_0_26, Rval env_28_29).\nProof.\n  reflexivity.\nQed.\n\n(* Theorem evaluate_0_30_correct : *)\n(*   evaluate_decs 100 init_state init_env (prog_0_26 ++ [dec_def_27; dec_def_28; dec_def_29; dec_def_30]) = *)\n(*   (st_0_26, Rval env_30). *)\n(* Proof. *)\n(*   reflexivity. *)\n(* Qed. *)\n\nLtac evaluate_decs_one :=\n  match goal with\n  | [|- evaluate_decs _ _ _ [?def] = (_, Rval _)] =>\n    unfold def;\n    match goal with\n    | [|- evaluate_decs _ _ _ [Dmod _ _] = (_, Rval _)]   => erewrite evaluate_decs_Dmod\n    | [|- evaluate_decs _ _ _ [Dlocal _ _] = (_, Rval _)] => erewrite evaluate_decs_Dlocal\n    | [|- evaluate_decs _ _ _ [_] = (_, Rval _)] => simp evaluate_decs\n    end; try reflexivity\n  end.\n\nLtac evaluate_decs_noapp :=\n  match goal with\n  | [|- evaluate_decs _ _ _ [] = (_, Rval _)] => simp evaluate_decs; reflexivity\n  | [|- evaluate_decs _ _ _ [_] = (_, Rval _)] => evaluate_decs_one\n  | [|- evaluate_decs _ _ _ (?def::_) = (_, Rval _)] =>\n    eapply evaluate_decs_cons'; [evaluate_decs_one | unfold extend_dec_env; simpl]\n  end.\n\nTransparent evaluate_decs.\nEval compute in evaluate_decs 100 init_state init_env prog.\n\nTheorem evaluate_30 : exists env st,\n    evaluate_decs 100 st_0_26 env_28_29 [dec_def_30; dec_def_31] =\n    (st, Rval env).\nProof.\n  econstructor; econstructor.\n\n  Transparent evaluate_decs.\n\n\n  evaluate_decs_noapp.\n  evaluate_decs_noapp.\n  evaluate_decs_noapp.\n  evaluate_decs_noapp.\n  evaluate_decs_noapp.\n  evaluate_decs_noapp.\n  evaluate_decs_noapp.\n  evaluate_decs_noapp.\n  evaluate_decs_noapp.\n  evaluate_decs_noapp.\n  evaluate_decs_noapp.\n  evaluate_decs_noapp.\n  evaluate_decs_noapp.\n  evaluate_decs_noapp.\n  (* HERE *)\n  evaluate_decs_noapp.\n  evaluate_decs_noapp.\n  evaluate_decs_noapp.\n  evaluate_decs_noapp.\n  evaluate_decs_noapp.\n  evaluate_decs_noapp.\n  evaluate_decs_noapp.\n  evaluate_decs_noapp.\n  evaluate_decs_noapp.\n  evaluate_decs_noapp.\n  evaluate_decs_noapp.\n  evaluate_decs_noapp.\n  evaluate_decs_noapp.\n  eapply evaluate_decs_cons'.\n\n  + unfold dec_def_30;\n      erewrite evaluate_decs_Dmod; [reflexivity | simpl].\n\n  eapply evaluate_decs_cons'.\n  unfold dec_def_30_0;\n    simp evaluate_decs; simpl;\n      reflexivity.\n  rewrite extend_empty_l.\n\n  eapply evaluate_decs_cons'.\n  unfold dec_def_30_1;\n    simp evaluate_decs; simpl;\n      reflexivity.\n  unfold extend_dec_env.\n      simpl.\n\n  eapply evaluate_decs_cons'.\n  unfold dec_def_30_2.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  eapply evaluate_decs_cons'.\n  unfold dec_def_30_3.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  eapply evaluate_decs_cons'.\n  unfold dec_def_30_4.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  eapply evaluate_decs_cons'.\n  unfold dec_def_30_5.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  eapply evaluate_decs_cons'.\n  unfold dec_def_30_6.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  eapply evaluate_decs_cons'.\n  unfold dec_def_30_7.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  eapply evaluate_decs_cons'.\n  unfold dec_def_30_8.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  eapply evaluate_decs_cons'.\n  unfold dec_def_30_9.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  unfold dec_def_30_10.\n  erewrite evaluate_decs_Dlocal.\n  reflexivity.\n\n  unfold dec_def_30_10_0.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  eapply evaluate_decs_cons'.\n  unfold dec_def_30_10_1.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  eapply evaluate_decs_cons'.\n  unfold dec_def_30_10_2.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  unfold dec_def_30_10_3.\n  erewrite evaluate_decs_Dlocal.\n  reflexivity.\n\n  unfold dec_def_30_10_3_0.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  eapply evaluate_decs_cons'.\n  unfold dec_def_30_10_3_1.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  unfold dec_def_30_10_3_2.\n  erewrite evaluate_decs_Dlocal.\n  reflexivity.\n\n  unfold dec_def_30_10_3_2_0.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  eapply evaluate_decs_cons'.\n  unfold dec_def_30_10_3_2_1.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  unfold dec_def_30_10_3_2_2.\n  erewrite evaluate_decs_Dlocal.\n  reflexivity.\n\n  unfold dec_def_30_10_3_2_2_0.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  eapply evaluate_decs_cons'.\n  unfold dec_def_30_10_3_2_2_1.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  unfold dec_def_30_10_3_2_2_2.\n  erewrite evaluate_decs_Dlocal.\n  reflexivity.\n\n  unfold dec_def_30_10_3_2_2_2_0.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  eapply evaluate_decs_cons'.\n  unfold dec_def_30_10_3_2_2_2_1.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  unfold dec_def_30_10_3_2_2_2_2.\n  erewrite evaluate_decs_Dlocal.\n  reflexivity.\n\n  unfold dec_def_30_10_3_2_2_2_2_0.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  eapply evaluate_decs_cons'.\n  unfold dec_def_30_10_3_2_2_2_2_1.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  eapply evaluate_decs_cons'.\n  unfold dec_def_30_10_3_2_2_2_2_2.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  eapply evaluate_decs_cons'.\n  unfold dec_def_30_10_3_2_2_2_2_3.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  eapply evaluate_decs_cons'.\n  unfold dec_def_30_10_3_2_2_2_2_4.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  unfold dec_def_30_10_3_2_2_2_2_5.\n  erewrite evaluate_decs_Dlocal.\n  reflexivity.\n\n  unfold dec_def_30_10_3_2_2_2_2_5_0.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  eapply evaluate_decs_cons'.\n  unfold dec_def_30_10_3_2_2_2_2_5_1.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  eapply evaluate_decs_cons'.\n  unfold dec_def_30_10_3_2_2_2_2_5_2.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  eapply evaluate_decs_cons'.\n  unfold dec_def_30_10_3_2_2_2_2_5_3.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  eapply evaluate_decs_cons'.\n  unfold dec_def_30_10_3_2_2_2_2_5_4.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  eapply evaluate_decs_cons'.\n  unfold dec_def_30_10_3_2_2_2_2_5_5.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  unfold dec_def_30_10_3_2_2_2_2_5_6.\n  erewrite evaluate_decs_Dlocal.\n  reflexivity.\n\n  unfold dec_def_30_10_3_2_2_2_2_5_6_0.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env.\n  simpl.\n\n  unfold dec_def_30_10_3_2_2_2_2_5_6_1.\n  simp evaluate_decs; simpl.\n  reflexivity.\n  unfold extend_dec_env at 1.\n  simpl.\n\nQed.\n\n(* Theorem evaluate_0_26 : exists env st, *)\n(*     evaluate_decs 100 init_state init_env prog_0_26 = *)\n(*     (st, Rval env). *)\n(* Proof. *)\n(*   econstructor. econstructor. *)\n(*   unfold prog_0_26. *)\n(*   unfold init_state. *)\n(*   unfold init_env. *)\n(*   unfold empty_sem_env. *)\n(*   unfold nsEmpty. *)\n(*   simpl. *)\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_0. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_1. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_2. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_3. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_4. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_5. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_6. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_7. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_8. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_9. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_10. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_11. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_12. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_13. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_14. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_15. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_16. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_17. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_18. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_19. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_20. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_21. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_22. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_23. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_24. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_25. (* Runtime Module (5 subdefs) *) *)\n(*   erewrite evaluate_decs_Dmod. *)\n(*   reflexivity. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_25_0. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_25_1. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_25_2. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_25_3. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_25_4. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_25_5. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   simp evaluate_decs; simpl. *)\n\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_26. (* Option module *) *)\n(*   erewrite evaluate_decs_Dmod. *)\n(*   reflexivity. *)\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_26_0. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_26_1. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_26_2. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_26_3. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_26_4. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_26_5. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_26_6. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_26_7. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_26_8. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_26_9. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_26_10. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold state_update_next_type_stamp. *)\n(*   simpl. *)\n\n(*   unfold dec_def_26_11. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(* Qed. *)\n\n(* Theorem evaluate_27 : exists env st, *)\n(*     evaluate_decs 100 st_0_26 env_0_26 [dec_def_27] = *)\n(*     (st, Rval env). *)\n(*   econstructor. econstructor. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27. *)\n(*   eapply evaluate_decs_Dmod. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_0. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_1. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   simpl. *)\n\n(*   unfold dec_def_27_2. (* First Dlocal *) *)\n(*   erewrite evaluate_decs_Dlocal. *)\n(*   reflexivity. *)\n\n(*   unfold dec_def_27_2_0. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   unfold build_rec_env. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_1. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   unfold dec_def_27_2_2. *)\n(*   erewrite evaluate_decs_Dlocal. *)\n(*   reflexivity. *)\n\n(*   unfold dec_def_27_2_2_0. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; simpl. *)\n(*   unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_1. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_2. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_3. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_4. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_5. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_6. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_7. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_8. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_9. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_10. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; simpl. *)\n(*   unfold nsBind. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_11. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_12. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_13. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_14. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env. *)\n(*   simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15. *)\n(*   erewrite evaluate_decs_Dlocal. *)\n(*   reflexivity. *)\n\n(*   unfold dec_def_27_2_2_15_0. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_1. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_2. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_3. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_4. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_5. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   unfold dec_def_27_2_2_15_6. *)\n(*   erewrite evaluate_decs_Dlocal. *)\n(*   reflexivity. *)\n(*   unfold dec_def_27_2_2_15_6_0. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_6_1. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_6_2. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   unfold dec_def_27_2_2_15_6_3. *)\n(*   erewrite evaluate_decs_Dlocal. *)\n(*   reflexivity. *)\n(*   unfold dec_def_27_2_2_15_6_3_0. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_6_3_1. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_6_3_2. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_6_3_3. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_6_3_4. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_6_3_5. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_6_3_6. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_6_3_7. *)\n(*   erewrite evaluate_decs_Dlocal. *)\n(*   reflexivity. *)\n\n(*   unfold dec_def_27_2_2_15_6_3_7_0. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_6_3_7_1. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_6_3_7_2. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_6_3_7_3. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_6_3_7_4. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_6_3_7_5. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_6_3_7_6. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_6_3_7_7. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_6_3_7_8. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_6_3_7_9. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_6_3_7_10. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_6_3_7_11. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_6_3_7_12. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_6_3_7_13. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_6_3_7_14. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_6_3_7_15. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_6_3_7_16. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   unfold dec_def_27_2_2_15_6_3_7_17. *)\n\n(*   erewrite evaluate_decs_Dlocal. *)\n(*   reflexivity. *)\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_27_2_2_15_6_3_7_17_0. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   unfold dec_def_27_2_2_15_6_3_7_17_1. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   unfold dec_def_27_2_2_15_6_3_7_17_2. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env at 1. *)\n(*   simpl. *)\n\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n\n(*   unfold extend_dec_env at 1. *)\n(*   simpl. *)\n\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(* Qed. *)\n\n(* Theorem evaluate_28_29 : exists env st, *)\n(*     evaluate_decs 100 st_0_26 env_27 [dec_def_28; dec_def_29] = *)\n(*     (st, Rval env). *)\n(*   econstructor. econstructor. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_28. (* AList Module *) *)\n(*   erewrite evaluate_decs_Dmod. *)\n(*   reflexivity. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_28_0. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_28_1. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_28_2. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_28_3. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_28_4. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_28_5. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_29. (* Vector module *) *)\n(*   erewrite evaluate_decs_Dmod. *)\n(*   reflexivity. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_29_0. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_29_1. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_29_2. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_29_3. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_29_4. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   unfold dec_def_29_5. *)\n(*   erewrite evaluate_decs_Dlocal. *)\n(*   reflexivity. *)\n\n(*   unfold dec_def_29_5_0. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_29_5_1. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_29_5_2. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_29_5_3. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_29_5_4. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_29_5_5. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   unfold dec_def_29_5_6. *)\n(*   erewrite evaluate_decs_Dlocal. *)\n(*   reflexivity. *)\n(*   unfold dec_def_29_5_6_0. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_29_5_6_1. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   unfold dec_def_29_5_6_2. *)\n(*   erewrite evaluate_decs_Dlocal. *)\n(*   reflexivity. *)\n(*   unfold dec_def_29_5_6_2_0. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_29_5_6_2_1. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   unfold dec_def_29_5_6_2_2. *)\n(*   erewrite evaluate_decs_Dlocal. *)\n(*   reflexivity. *)\n(*   unfold dec_def_29_5_6_2_2_0. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_29_5_6_2_2_1. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   unfold dec_def_29_5_6_2_2_2. *)\n(*   erewrite evaluate_decs_Dlocal. *)\n(*   reflexivity. *)\n(*   unfold dec_def_29_5_6_2_2_2_0. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_29_5_6_2_2_2_1. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   unfold dec_def_29_5_6_2_2_2_2. *)\n(*   erewrite evaluate_decs_Dlocal. *)\n(*   reflexivity. *)\n\n(*   unfold dec_def_29_5_6_2_2_2_2_0. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_29_5_6_2_2_2_2_1. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   unfold dec_def_29_5_6_2_2_2_2_2. *)\n(*   erewrite evaluate_decs_Dlocal. *)\n(*   reflexivity. *)\n\n(*   unfold dec_def_29_5_6_2_2_2_2_2_0. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_29_5_6_2_2_2_2_2_1. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   unfold dec_def_29_5_6_2_2_2_2_2_2. *)\n(*   erewrite evaluate_decs_Dlocal. *)\n(*   reflexivity. *)\n\n(*   unfold dec_def_29_5_6_2_2_2_2_2_2_0. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_29_5_6_2_2_2_2_2_2_1. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   unfold dec_def_29_5_6_2_2_2_2_2_2_2. *)\n(*   erewrite evaluate_decs_Dlocal. *)\n(*   reflexivity. *)\n\n(*   unfold dec_def_29_5_6_2_2_2_2_2_2_2_0. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   eapply evaluate_decs_cons'. *)\n(*   unfold dec_def_29_5_6_2_2_2_2_2_2_2_1. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   unfold dec_def_29_5_6_2_2_2_2_2_2_2_2. *)\n(*   erewrite evaluate_decs_Dlocal. *)\n(*   reflexivity. *)\n\n(*   unfold dec_def_29_5_6_2_2_2_2_2_2_2_2_0. *)\n(*   simp evaluate_decs; simpl. *)\n(*   unfold build_rec_env; unfold nsBind; simpl. *)\n(*   reflexivity. *)\n(*   unfold extend_dec_env; simpl. *)\n\n(*   unfold dec_def_29_5_6_2_2_2_2_2_2_2_2_1. *)\n(*   simp evaluate_decs; simpl. *)\n(*   reflexivity. *)\n(*   (* ENDS HERE *) *)\n(* Qed. *)\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/BasisRed/EvaluateExperiments.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2636582616897836}}
{"text": "\nRequire Import Axioms.\nRequire Import Tactics.\nRequire Import Sigma.\nRequire Import Equality.\nRequire Import Relation.\nRequire Import Syntax.\nRequire Import Ofe.\nRequire Import Uniform.\nRequire Import Spaces.\nRequire Import Dynamic.\nRequire Import Hygiene.\nRequire Import Equivalence.\nRequire Import Urelsp.\nRequire Import Intensional.\nRequire Import Ordinal.\nRequire Import Candidate.\nRequire Import Ceiling.\nRequire Import Truncate.\nRequire Import MapTerm.\nRequire Import Extend.\nRequire Import Extend.\nRequire Export SemanticsProperty.\n\n\n(* Disoriented rel *)\n\nDefinition srel {object} (s : bool) (A : @urel object) i m n :=\n  if s then\n    rel A i m n\n  else\n    rel A i n m.\n\n\nLemma srel_closed :\n  forall object s (A : urel object) i m n,\n    srel s A i m n\n    -> hygiene clo m /\\ hygiene clo n.\nProof.\nintros object s A i m n H.\ndestruct s; so (urel_closed _#5 H) as (? & ?); auto.\nQed.\n\n\nLemma srel_equiv :\n  forall object s (A : urel object) i m m' n n',\n    hygiene clo m'\n    -> hygiene clo n'\n    -> equiv m m'\n    -> equiv n n'\n    -> srel s A i m n\n    -> srel s A i m' n'.\nProof.\nintros object s A i m m' n n' H H0 H1 H2 H3.\ndestruct s; eapply urel_equiv; eauto.\nQed.\n\n\nLemma srel_zigzag :\n  forall object s (R : urel object) i m n p q,\n    srel s R i m n\n    -> srel s R i p n\n    -> srel s R i p q\n    -> srel s R i m q.\nProof.\nintros object s R i m n p q Hmn Hpn Hpq.\ndestruct s; cbn in *; eapply urel_zigzag; eauto.\napply (urel_zigzag _#4 p n); auto.\nQed.\n\n\nLemma srel_downward :\n  forall object s A i m n,\n    @srel object s A (S i) m n\n    -> srel s A i m n.\nProof.\nintros object s A i m n H.\ndestruct s; apply urel_downward; auto.\nQed.\n\n\nLemma srel_downward_leq :\n  forall object s A i j m n,\n    i <= j\n    -> @srel object s A j m n\n    -> srel s A i m n.\nProof.\nintros object s A i m n H.\ndestruct s; apply urel_downward_leq; auto.\nQed.\n\n\nLemma srel_ceiling_intro :\n  forall w s i (A : wurel w) j m n,\n    j < i\n    -> srel s A j m n\n    -> srel s (ceiling i A) j m n.\nProof.\nintros w s i A j m n Hji Hrel.\ndestruct s; cbn; cbn in Hrel; auto.\nQed.\n\n\nLemma srel_ceiling_elim :\n  forall w s i (A : wurel w) j m n,\n    srel s (ceiling i A) j m n\n    -> srel s A j m n.\nProof.\nintros w s i A j m n Hrel.\ndestruct s; cbn; cbn in Hrel; destruct Hrel; auto.\nQed.\n\n\nLemma surel_updown :\n  forall v w s (A : wurel v) i m p,\n    v <<= w\n    -> srel s A i m p\n    -> srel s (extend_urel v w A) i (map_term (extend v w) m) (map_term (extend v w) p).\nProof.\nintros v w s A i m p Hvw H.\ndestruct s; apply urel_updown; auto.\nQed.\n\n\nDefinition surelspinj {object} (s : bool) (A : urel object) i m p \n  : srel s A i m p -> car (urelsp A)\n  :=\n  match s\n    as s\n    return srel s A i m p -> car (urelsp A)\n  with\n  | true => fun Hmp => urelspinj A i m p Hmp\n  | false => fun Hmp => urelspinj A i p m Hmp\n  end.\n\n\nLemma surelspinj_equal :\n  forall object s (A : urel object) i m m' p p' H H',\n    srel s A i m p'\n    -> surelspinj s A i m p H = surelspinj s A i m' p' H'.\nProof.\nintros object s A i m m' p p' Hmp Hmp' H.\ndestruct s; apply urelspinj_equal; auto.\neapply urel_zigzag; eauto.\nQed.\n\n\nLemma surelspinj_equal_impl :\n  forall object s (A : urel object) i m m' p p' (H : srel s A i m p) (H' : srel s A i m' p'),\n    surelspinj s A i m p H = surelspinj s A i m' p' H'\n    -> srel s A i m p'.\nProof.\nintros object s A i m m' p p' Hmp Hmp' Heq.\ndestruct s.\n  {\n  apply (urelspinj_equal_impl _#7 Hmp Hmp'); auto.\n  }\n\n  {\n  cbn in * |- *.\n  so (urelspinj_equal_impl _#9 Heq).\n  eapply urel_zigzag; eauto.\n  }\nQed.\n\n\nLemma proj_ceiling_surelspinj :\n  forall w i j s (A : wurel w) m p Hpos Hmp Hmp',\n    proj_ceiling (S i) Hpos A (surelspinj s A j m p Hmp)\n    =\n    surelspinj s (ceiling (S i) A) (min j i) m p Hmp'.\nProof.\nintros w i j s A m p Hpos Hmp Hmp'.\ndestruct s; cbn; erewrite -> proj_ceiling_urelspinj; eauto.\nQed.\n\n\nLemma extend_srel :\n  forall v w s A i m p,\n    srel s (extend_urel v w A) i m p\n    <->\n    srel s A i (map_term (extend w v) m) (map_term (extend w v) p).\nProof.\nintros v w s A i m p.\ndestruct s; cbn; split; auto.\nQed.\n\n\nLemma extend_surelspinj :\n  forall v w (h : v <<= w) s (A : wurel v) i m p Hmp Hmp',\n    extend_urelsp h A (surelspinj s A i m p Hmp)\n    =\n    surelspinj s (extend_urel v w A) i (map_term (extend v w) m) (map_term (extend v w) p) Hmp'.\nProof.\nintros v w h s A i m p Hmp Hmp'.\ndestruct s; apply extend_urelspinj.\nQed.\n\n\n(* Equality *)\n\nDefinition equal_property w (s : bool) (A : wurel w) m n : nat -> Prop :=\n  fun i =>\n    exists p,\n      srel s A i m p\n      /\\ srel s A i n p.\n\n\nLemma equal_property_downward :\n  forall w s A m n i,\n    equal_property w s A m n (S i)\n    -> equal_property w s A m n i.\nProof.\nintros w s A m n i H.\ndestruct H as (p & Hmp & Hnp).\nexists p; auto using srel_downward.\nQed.\n\n\n(* Using a nat instead of a nats will cause trouble if I ever want to make iurels complete. *)\n\nDefinition equal_urel (w : ordinal) (s : bool) (i : nat) (A : wurel w) (m n : wterm w) : wurel w :=\n  property_urel\n    (fun j =>\n       exists p,\n         srel s A j m p\n         /\\ srel s A j n p)\n    w i\n    (equal_property_downward w s A m n).\n\n\nLemma equal_urel_equal :\n  forall w s i A m m' n n' p q,\n    srel s A i m p\n    -> srel s A i m' p\n    -> srel s A i n q\n    -> srel s A i n' q\n    -> equal_urel w s i A m n = equal_urel w s i A m' n'.\nProof.\nintros w s i A m m' n n' p q Hmp Hmp' Hnq Hnq'.\nunfold equal_urel.\napply property_urel_extensionality; auto.\nintros j Hj.\ncbn in Hj.\nassert (j <= i) as Hj' by omega.\nsplit.\n  {\n  intros (r & Hmr & Hnr).\n  exists r.\n  split.\n    {\n    apply (srel_zigzag _#5 p m); eauto using srel_downward_leq.\n    }\n\n    {\n    apply (srel_zigzag _#5 q n); eauto using srel_downward_leq.\n    }\n  }\n\n  {\n  intros (r & Hmr & Hnr).\n  exists r.\n  split.\n    {\n    apply (srel_zigzag _#5 p m'); eauto using srel_downward_leq.\n    }\n\n    {\n    apply (srel_zigzag _#5 q n'); eauto using srel_downward_leq.\n    }\n  }\nQed.\n\n\nLemma extend_equal_urel :\n  forall v w s i A m n,\n    v <<= w\n    -> extend_urel v w (equal_urel v s i A m n)\n       =\n       equal_urel w s i (extend_urel v w A) (map_term (extend v w) m) (map_term (extend v w) n).\nProof.\nintros v w s i A m n Hle.\nunfold equal_urel.\nrewrite -> extend_property; auto.\napply property_urel_extensionality; auto.\nintros j Hj.\nsplit.\n  {\n  intros (r & Hmr & Hnr).\n  exists (map_term (extend v w) r).\n  rewrite -> !extend_srel.\n  rewrite -> !extend_term_cancel; auto.\n  }\n\n  {\n  intros (r & Hmr & Hnr).\n  exists (map_term (extend w v) r).\n  rewrite -> extend_srel in Hmr, Hnr.\n  rewrite -> !extend_term_cancel in Hmr, Hnr; auto.\n  }\nQed.\n\n\nDefinition iuequal (w : ordinal) (s : bool) (i : nat) (A : wiurel w) (m n p q : wterm w)\n  (Hmp : srel s (den A) i m p) (Hnq : srel s (den A) i n q)\n  : wiurel w\n  :=\n  (equal_urel w s i (den A) m n,\n   meta_pair (meta_iurel A)\n     (meta_pair \n        (meta_term (den A) (surelspinj s (den A) i m p Hmp))\n        (meta_term (den A) (surelspinj s (den A) i n q Hnq)))).\n     \n\n(* Trivial, but helpful to control rewriting. *)\nLemma den_iuequal :\n  forall w s i A m n p q Hmp Hnq,\n    den (iuequal w s i A m n p q Hmp Hnq) = equal_urel w s i (den A) m n.\nProof.\nauto.\nQed.\n\n\nLemma iuequal_equal :\n  forall w s i A m m' n n' p p' q q' Hmp Hmp' Hnq Hnq',\n    srel s (den A) i m p'\n    -> srel s (den A) i n q'\n    -> iuequal w s i A m n p q Hmp Hnq = iuequal w s i A m' n' p' q' Hmp' Hnq'.\nProof.\nintros w s i A m m' n n' p p' q q' Hmp Hmp' Hnq Hnq' Hmp'' Hnq''.\nunfold iuequal.\nf_equal.\n  {\n  eapply equal_urel_equal; eauto.\n  }\nf_equal.\nf_equal.\n  {\n  f_equal.\n  apply surelspinj_equal.\n  eapply srel_zigzag; eauto.\n  }\n\n  {\n  f_equal.\n  apply surelspinj_equal.\n  eapply srel_zigzag; eauto.\n  }\nQed.\n\n\nLemma iuequal_equal' :\n  forall w s i A A' m m' n n' p p' q q' Hmp Hmp' Hnq Hnq',\n    A = A'\n    -> srel s (den A) i m p'\n    -> srel s (den A) i n q'\n    -> iuequal w s i A m n p q Hmp Hnq = iuequal w s i A' m' n' p' q' Hmp' Hnq'.\nProof.\nintros w s i A A' m m' n n' p p' q q' Hmp Hmp' Hnq Hnq' Heq Hmp'' Hnq''.\nsubst A'.\napply iuequal_equal; auto.\nQed.\n\n\nLemma iuequal_inj :\n  forall w s i A A' m m' n n' p p' q q' Hmp Hmp' Hnq Hnq',\n    iuequal w s i A m n p q Hmp Hnq = iuequal w s i A' m' n' p' q' Hmp' Hnq'\n    -> A = A'\n       /\\ srel s (den A) i m p'\n       /\\ srel s (den A) i n q'.\nProof.\nintros w s i A A' m m' n n' p p' q q' Hmp Hmp' Hnq Hnq' Heq.\nunfold iuequal in Heq.\nso (f_equal snd Heq) as Heq'.\ncbn in Heq'.\nso (meta_pair_inj _#5 Heq') as (Heq1 & Heq23).\nclear Heq Heq'.\nso (meta_iurel_inj _#3 Heq1); subst A'.\nso (meta_pair_inj _#5 Heq23) as (Heq2 & Heq3).\nclear Heq1 Heq23.\nso (meta_term_inj _#5 Heq2) as H.\ninjectionT H.\nintro Heqmp.\nso (meta_term_inj _#5 Heq3) as H.\ninjectionT H.\nintro Heqnq.\nclear Heq2 Heq3.\ndo2 2 split; eauto using surelspinj_equal_impl.\nQed.    \n\n\nLemma iutruncate_iuequal :\n  forall w j s i A m n p q Hmp Hnq Hmp' Hnq',\n    iutruncate (S j) (iuequal w s i A m n p q Hmp Hnq)\n    =\n    iuequal w s (min i j) (iutruncate (S j) A) m n p q Hmp' Hnq'.\nProof.\nintros w j s i A m n p q Hmp Hnq Hmp' Hnq'.\nunfold iuequal, iutruncate.\ndestruct A as (A & meta).\nunfold den.\ncbn [fst snd].\nf_equal.\n  {\n  unfold equal_urel.\n  cbn [fst].\n  rewrite -> ceiling_property.\n  apply property_urel_extensionality.\n    {\n    reflexivity.\n    }\n  intros k Hk.\n  so (Nat.min_glb_r _#3 Hk) as Hkj.\n  split.\n    {\n    intros (r & Hmr & Hnr).\n    exists r.\n    split; apply srel_ceiling_intro; auto; omega.\n    }\n\n    {\n    intros (r & Hmr & Hnr).\n    exists r.\n    eauto using srel_ceiling_elim.\n    }\n  }\n\n  {\n  assert (S j > 0) as Hpos by omega.\n  rewrite -> !meta_truncate_pair; auto.\n  rewrite -> !(meta_truncate_term _#4 Hpos).\n  rewrite -> meta_truncate_iurel; auto.\n  f_equal.\n  f_equal.\n    {\n    f_equal.\n    apply proj_ceiling_surelspinj.\n    }\n\n    {\n    f_equal.\n    apply proj_ceiling_surelspinj.\n    }\n  }\nQed.\n\n\nLemma extend_iuequal :\n  forall v w (h : v <<= w) s i A m n p q Hmp Hmp' Hnq Hnq',\n    extend_iurel h (iuequal v s i A m n p q Hmp Hnq)\n    =\n    iuequal w s i (extend_iurel h A)\n      (map_term (extend v w) m)\n      (map_term (extend v w) n)\n      (map_term (extend v w) p)\n      (map_term (extend v w) q)\n      Hmp' Hnq'.\nProof.\nintros v w h s i A m n p q Hmp Hmp' Hnq Hnq'.\nunfold iuequal, extend_iurel.\ncbn.\nf_equal.\n  {\n  apply extend_equal_urel; auto.\n  }\n\n  {\n  rewrite -> !extend_meta_pair.\n  rewrite -> extend_meta_iurel.\n  rewrite -> !extend_meta_term.\n  f_equal.\n  f_equal.\n    {\n    f_equal.\n    apply extend_surelspinj.\n    }\n\n    {\n    f_equal.\n    assert (srel s (extend_urel v w (den A)) i (map_term (extend v w) n) (map_term (extend v w) q)) as Hnq''.\n      {\n      fold (extend_urel v w).\n      rewrite -> extend_srel.\n      rewrite -> !extend_term_cancel; auto.\n      }\n    rewrite -> (extend_surelspinj _#9 Hnq'').\n    apply surelspinj_equal; auto.\n    }\n  }\nQed.\n\n\nLemma extend_iuequal' :\n  forall v w (h : v <<= w) s i A m n p q Hmp Hnq,\n    extend_iurel h (iuequal v s i A m n p q Hmp Hnq)\n    =\n    iuequal w s i (extend_iurel h A)\n      (map_term (extend v w) m)\n      (map_term (extend v w) n)\n      (map_term (extend v w) p)\n      (map_term (extend v w) q)\n      (surel_updown _#7 h Hmp)\n      (surel_updown _#7 h Hnq).\nProof.\nintros v w h s i A m n p q Hmp Hnq.\napply extend_iuequal.\nQed.\n\n\nLemma srel_swap :\n  forall object s (A : urel object) i m n,\n    srel s A i m n \n    -> srel (negb s) A i n m.\nProof.\nintros object s A i m n H.\ndestruct s; auto.\nQed.\n\n\nLemma srel_unswap :\n  forall object s (A : urel object) i m n,\n    srel (negb s) A i n m\n    -> srel s A i m n.\nProof.\nintros object s A i m n H.\ndestruct s; auto.\nQed.\n\n\nLemma surelspinj_swap :\n  forall object s (A : urel object) i m p Hmp Hpm,\n    surelspinj s A i m p Hmp\n    =\n    surelspinj (negb s) A i p m Hpm.\nProof.\nintros object s A i m p Hmp Hpm.\ndestruct s; cbn.\n  {\n  f_equal.\n  apply proof_irrelevance.\n  }\n\n  {\n  f_equal.\n  apply proof_irrelevance.\n  }\nQed.\n\n\nLemma iuequal_swap :\n  forall w s i A m n p q Hmp Hnq,\n    iuequal w s i A m n p q Hmp Hnq\n    =\n    iuequal w (negb s) i A p q m n (srel_swap _#6 Hmp) (srel_swap _#6 Hnq).\nProof.\nintros w s i A m n p q Hmp Hnq.\nunfold iuequal.\nf_equal.\n  {\n  apply property_urel_extensionality; auto.\n  intros j Hj.\n  cbn in Hj.\n  assert (j <= i) as Hj' by omega.\n  split.\n    {\n    intros (r & Hmr & Hnr).\n    exists m; split; apply srel_swap.\n      {\n      exact (srel_downward_leq _#7 Hj' Hmp).\n      }\n\n      {\n      refine (srel_zigzag _#8 Hmr Hnr _).\n      exact (srel_downward_leq _#7 Hj' Hnq).\n      }\n    }\n\n    {\n    intros (r & Hpr & Hqr).\n    so (srel_unswap _#6 Hpr) as Hrp.\n    so (srel_unswap _#6 Hqr) as Hrq.\n    exists p.\n    split.\n      {\n      exact (srel_downward_leq _#7 Hj' Hmp).\n      }\n\n      {\n      refine (srel_zigzag _#8 _ Hrq Hrp).\n      exact (srel_downward_leq _#7 Hj' Hnq).\n      }\n    }\n  }\n\n  {\n  f_equal.\n  f_equal.\n    {\n    f_equal.\n    apply surelspinj_swap.\n    }\n\n    {\n    f_equal.\n    apply surelspinj_swap.\n    }\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/SemanticsEqual.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2635479345662772}}
{"text": "From Equations Require Import Equations.\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nRequire Export SystemFR.ErasedTypeRefine.\nRequire Export SystemFR.ErasedArrow.\nRequire Export SystemFR.ErasedTypeApplication.\n\nRequire Export SystemFR.ReducibilityEquivalent.\n\nOpaque reducible_values.\nOpaque makeFresh.\n\nDefinition type_open T1 T2 : tree :=\n  T_exists T2 (shift_open 0 T1 (lvar 0 term_var)).\n\n(*\nDefinition equivalent_terms_at (theta: interpretation) T 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  forall C,\n    (forall v, reducible_values theta v T ->\n          div_reducible theta (open 0 C v) T_top) ->\n    is_erased_term C ->\n    wf C 1 ->\n    pfv C term_var = nil ->\n    scbv_normalizing (open 0 C t1) <-> scbv_normalizing (open 0 C t2).\n*)\n(*\nLemma singleton_identity:\n  is_singleton [] []\n    (notype_lambda (lvar 0 term_var))\n    (T_arrow T_nat (singleton (lvar 0 term_var))).\nProof.\n  unfold is_singleton;\n    repeat step || simp_red;\n    t_closer.\n\n  - unfold reduces_to; steps; t_closer.\n    exists a; repeat step || simp_red || rewrite open_none by auto; t_closer.\n    + exists uu; repeat step || simp_red; eauto using equivalent_refl.\n\n    + apply star_one.\n      constructor; t_closer.\n\n  - unfold equivalent_terms_at;\n      repeat step;\n      t_closer.\n*)\n\nDefinition sub_singleton tvars gamma v T : Prop :=\n  forall theta l v',\n    valid_interpretation theta ->\n    satisfies (reducible_values theta) gamma l  ->\n    support theta = tvars ->\n    reducible_values theta v' (psubstitute T l term_var) ->\n    equivalent_terms v' (psubstitute v l term_var).\n\nLemma reducibility_open_equivalent2:\n  forall T t1 t2 ρ t,\n    [ ρ ⊨ t : open 0 T t1 ] ->\n    valid_interpretation ρ ->\n    is_erased_type T ->\n    wf T 1 ->\n    pfv T term_var = nil ->\n    [ t1 ≡ t2 ] ->\n    [ ρ ⊨ t : open 0 T t2 ].\nProof.\n  eauto using reducibility_open_equivalent, reducible_values_exprs.\nQed.\n\nLemma open_subtype_type_application:\n  forall tvars gamma A B C c,\n    wf A 0 ->\n    wf B 1 ->\n    wf C 0 ->\n    wf c 0 ->\n    is_erased_term c ->\n    is_erased_type A ->\n    is_erased_type B ->\n    is_erased_type C ->\n    subset (fv A) (support gamma) ->\n    subset (fv B) (support gamma) ->\n    subset (fv C) (support gamma) ->\n    subset (fv c) (support gamma) ->\n    sub_singleton tvars gamma c C ->\n    [ tvars; gamma ⊨ C <: A ] ->\n    [ tvars; gamma ⊨ type_application (T_arrow A B) C <: open 0 B c ].\nProof.\n  unfold open_subtype;\n    repeat step || simp_red ||\n           (rewrite open_none in * by eauto with wf) ||\n           (rewrite (open_none v) in * by t_closer) ||\n           (rewrite (open_none (psubstitute C l term_var) 1) in * by eauto with wf).\n\n  apply reducible_expr_value; t_closer.\n\n  eapply reducibility_equivalent2; try eassumption;\n    repeat step ||\n           apply wf_open || apply wf_subst ||\n           apply is_erased_type_open || apply subst_erased_type;\n    t_closer.\n\n  - apply fv_nils2; eauto with fv.\n    eapply subset_transitive; eauto using fv_open;\n      repeat step || sets;\n      t_closer.\n\n  - t_substitutions.\n    apply reducibility_open_equivalent2 with a0;\n      repeat step || apply_any; t_closer.\nQed.\n\nLemma sub_singleton_value:\n  forall v T,\n    closed_value v ->\n    sub_singleton [] [] v (T_singleton T v).\nProof.\n  unfold sub_singleton;\n    repeat step || simp_red ||\n           (rewrite open_none in * by t_closer) ||\n           (rewrite shift_nothing2 in * by t_closer).\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/ErasedTypeReduction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.26354308100230517}}
{"text": "From mathcomp Require Import ssreflect ssrfun.\nRequire Import all_ntrvw.\nImport Morphisms.\nRequire Import FunctionalExtensionality.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nModule dictionary.\n  Record mixin_of Q A (conv: Q ->> A) :=\n    Mixin {\n        answers_unique: conv \\is_singlevalued;\n        }.\n\n  Record class_of (I: Type) :=\n    Class {\n        M: interview.struc_of I;\n        mixin: mixin_of (conversation (interview.Pack M));\n        }.\n\n  Structure type :=\n    Pack {I; struc : class_of I}.\nEnd dictionary.\n\nSection dictionaries.\n  Local Notation dictionary:= dictionary.type.\n  Local Coercion dictionary.struc: dictionary >-> dictionary.class_of.\n  Local Coercion dictionary.mixin: dictionary.class_of >-> dictionary.mixin_of.\n  Local Coercion dictionary.M: dictionary.class_of >-> interview.struc_of.\n  Local Notation description := conversation.\n  Local Notation \"a '\\is_answer_to' q 'in' D\" := (description D q a) (at level 2).\n  Local Notation \"a \\is_answer_to q\" := (a \\is_answer_to  q in _) (at level 2).\n\n  Lemma answers_unique (D: dictionary): (description D) \\is_singlevalued.\n  Proof. by case: D => A [Q []]. Qed.\n\n  Local Notation answer_unique := answers_unique.\n\n  Definition lift_ntrvw (I: interview) (sing: (conversation I) \\is_singlevalued): dictionary:=\n    dictionary.Pack (dictionary.Class (dictionary.Mixin sing)).\n\n  Lemma id_sing S: (@mf_id S) \\is_singlevalued.\n  Proof. exact/F2MF_sing. Qed.\n  Definition id_dictionary (S: Type): dictionary := @lift_ntrvw (id_interview S) (@id_sing S).\n  Definition get_ntrvw (D: dictionary):= interview.Pack (interview.Struc (dictionary.M D)).\n\n  Context  (D D': dictionary).\n  Local Coercion get_ntrvw: dictionary >-> interview.\n  \n  Lemma prod_conv_sing: (prod_conv D D') \\is_singlevalued.\n  Proof. exact/fprd_sing/answer_unique/answer_unique. Qed.\n  \n  Definition prod_dictionary_mixin : dictionary.mixin_of (prod_conv D D'):=\n    dictionary.Mixin prod_conv_sing.\n\n  Canonical prod_dictionary_struc:= dictionary.Class prod_dictionary_mixin.\n  Canonical prod_dictionary:= dictionary.Pack prod_dictionary_struc.\n\n  Lemma sum_conv_sing: (sum_conv D D') \\is_singlevalued.\n  Proof. exact/fsum_sing/answer_unique/answer_unique. Qed.\n\n  Definition sum_dictionary_mixin: dictionary.mixin_of (sum_conv D D'):=\n    dictionary.Mixin sum_conv_sing.\n  \n  Canonical sum_dictionary_struc:= dictionary.Class sum_dictionary_mixin.\n  Canonical sum_dictionary:= dictionary.Pack sum_dictionary_struc.\n\n  Lemma map_sing S T (f: S ->> T): f \\is_singlevalued -> (mf_map f) \\is_singlevalued.\n  Proof.\n    move => sing L K K'.\n    elim : L K K' => [ | q L ih]; first by case => //; case.    \n    case => // a K; case => // a' K' /=[fqa lst] [fqa' lst'].\n    rewrite (sing q a a' fqa fqa'); f_equal.\n    exact/ih.\n  Qed.\n  \n  Lemma list_conv_sing: (list_conv D) \\is_singlevalued.\n  Proof. exact/map_sing/answers_unique. Qed.\n\n  Definition list_dictionary_mixin: dictionary.mixin_of (list_conv D):=\n    dictionary.Mixin list_conv_sing.\n\n  Canonical list_dictionary_struc:= dictionary.Class list_dictionary_mixin.\n  Canonical list_dictionary:= dictionary.Pack list_dictionary_struc.\n\n  Lemma rlzr_spec F f: F \\realizes (f: get_ntrvw D ->> get_ntrvw D')\n                       <-> ((conversation D') \\o F) \\tightens (f \\o (conversation D)).\n  Proof.\n    split => [Frf | tight].\n    apply split_tight => q [a' [[a [aaq faa']] subs]].\n    - have [[q' Fqq'] prp]:= Frf q a aaq (subs a aaq).\n      have [d' [d'aq' fad']]:= prp q' Fqq'.\n      exists d'; split => [ | r' Fqr']; first by exists q'.\n      by have [e' [e'aq' fae']]:= prp r' Fqr'; exists e'.\n    move => d' [[q' [Fqq' d'aq']] subs'].\n    split => [ | d daq]; last exact/subs.\n    - have [d'' [d''aq' fad'']]:= rlzr_val Frf aaq (subs a aaq) Fqq'.\n      by exists a; split => //; rewrite (answers_unique d'aq' d''aq').\n    move => q a aaq [a' faa'].\n    have qfd: q \\from dom (f \\o (conversation D)).\n    - exists a'; split => [ | d daq]; first by exists a.\n      by exists a'; rewrite (answer_unique daq aaq).\n    split => [ | q' Fqq'].\n    - by have [ | d' [[q' [Fqq' d'aq']] subs]]:= (tight_dom tight) q; last by exists q'.\n    have [d' [[z' [Fqz' d'az']] subs]]:= (tight_dom tight) q qfd; have [e' e'aq']:= subs q' Fqq'.\n    have [ | [d [daq fdd']] subs']:= (tight_val tight qfd) e'; first by split; first by exists q'.\n    by exists e'; rewrite (answers_unique aaq daq); first split.\n  Qed.\nEnd dictionaries.\nNotation dictionary:= dictionary.type.\nCoercion dictionary.struc: dictionary >-> dictionary.class_of.\nCoercion dictionary.mixin: dictionary.class_of >-> dictionary.mixin_of.\nCoercion get_ntrvw: dictionary >-> interview.\nNotation description := conversation.\nNotation \"a '\\is_answer_to' q 'in' D\" := (description D q a) (at level 2).\nNotation \"a \\is_answer_to q\" := (a \\is_answer_to  q in _) (at level 2).\nNotation answer_unique := answers_unique.\n\nSection mf_realizer.\n  Context (D: dictionary) (I: interview).\n\n  Lemma rlzr_F2MF_eq F (f g: answers I -> answers D):\n    F \\realizes (F2MF f) -> F \\realizes (F2MF g) -> f =1 g.\n  Proof.\n    move => rlzr rlzr' a.\n    have [q arq]:= conv_sur a.\n    have [ | Fq FqFq]:= rlzr_dom rlzr arq; first exact/F2MF_dom.\n    have [ | fa [farFq ->]]:= rlzr_val rlzr arq _ FqFq; first exact/F2MF_dom.\n    have [ | ga [garFq ->]]:= rlzr_val rlzr' arq _ FqFq; first exact/F2MF_dom.\n    by rewrite (@answers_unique D Fq fa ga).\n  Qed.\n\n  Lemma rlzr_sur: (@mf_rlzr D I) \\is_cototal.\n  Proof.\n    move => f.\n    exists (make_mf (fun q Fq => forall a, a \\is_response_to q -> exists fa, fa \\is_response_to Fq /\\ f a fa)).\n    move => q a qna [fa fafa]; split => [ | Fq FqFq]; last by have [a' []]:= FqFq a qna; exists a'.\n    have [Fq Fqnfa]:= conv_sur fa; exists Fq => a' qna'.\n    by exists fa; split => //; rewrite (@answers_unique D q a' a).\n  Qed.\n\n  Definition rlzrs_interview_mixin:= interview.Mixin rlzr_sur.\n  Canonical rlzrs_interview_struc:= interview.Struc rlzrs_interview_mixin.\n  Canonical rlzrs_interview:= interview.Pack rlzrs_interview_struc.\n  End mf_realizer.", "meta": {"author": "FlorianSteinberg", "repo": "rlzrs", "sha": "5009572f2e22e7a0d31ab8937baf5c9dbb302d6d", "save_path": "github-repos/coq/FlorianSteinberg-rlzrs", "path": "github-repos/coq/FlorianSteinberg-rlzrs/rlzrs-5009572f2e22e7a0d31ab8937baf5c9dbb302d6d/dict.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2635430741248024}}
{"text": "Require Import Coq.Arith.Wf_nat.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Program.Equality.\n\nRequire Export Metalib.Metatheory.\nRequire Export Metalib.LibLNgen.\n\nRequire Export Definitions.\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 varref_ind' := Induction for varref Sort Prop.\n\nDefinition varref_mutind :=\n  fun H1 H2 H3 =>\n  varref_ind' H1 H2 H3.\n\nScheme varref_rec' := Induction for varref Sort Set.\n\nDefinition varref_mutrec :=\n  fun H1 H2 H3 =>\n  varref_rec' H1 H2 H3.\n\nScheme typ_ind' := Induction for typ Sort Prop\n  with dec_ind' := Induction for dec Sort Prop.\n\nDefinition typ_dec_mutind :=\n  fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 =>\n  (conj (typ_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11)\n  (dec_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11)).\n\nScheme typ_rec' := Induction for typ Sort Set\n  with dec_rec' := Induction for dec Sort Set.\n\nDefinition typ_dec_mutrec :=\n  fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 =>\n  (pair (typ_rec' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11)\n  (dec_rec' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11)).\n\nScheme def_ind' := Induction for def Sort Prop\n  with defs_ind' := Induction for defs Sort Prop\n  with val_ind' := Induction for val Sort Prop\n  with trm_ind' := Induction for trm Sort Prop.\n\nDefinition def_defs_val_trm_mutind :=\n  fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15 =>\n  (conj (def_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15)\n  ((conj (defs_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15)\n  ((conj (val_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15)\n  (trm_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15)))))).\n\nScheme def_rec' := Induction for def Sort Set\n  with defs_rec' := Induction for defs Sort Set\n  with val_rec' := Induction for val Sort Set\n  with trm_rec' := Induction for trm Sort Set.\n\nDefinition def_defs_val_trm_mutrec :=\n  fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15 =>\n  (pair ((pair ((pair (def_rec' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15)\n  (defs_rec' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15)))\n  (val_rec' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15)))\n  (trm_rec' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15)).\n\n\n(* *********************************************************************** *)\n(** * Close *)\n\nFixpoint close_varref_wrt_varref_rec (n1 : nat) (x1 : termvar) (v1 : varref) {struct v1} : varref :=\n  match v1 with\n    | var_termvar_f x2 => if (x1 == x2) then (var_termvar_b n1) else (var_termvar_f x2)\n    | var_termvar_b n2 => if (lt_ge_dec n2 n1) then (var_termvar_b n2) else (var_termvar_b (S n2))\n  end.\n\nDefinition close_varref_wrt_varref x1 v1 := close_varref_wrt_varref_rec 0 x1 v1.\n\nFixpoint close_typ_wrt_varref_rec (n1 : nat) (x1 : termvar) (T1 : typ) {struct T1} : typ :=\n  match T1 with\n    | typ_all T2 T3 => typ_all (close_typ_wrt_varref_rec n1 x1 T2) (close_typ_wrt_varref_rec (S n1) x1 T3)\n    | typ_bnd T2 => typ_bnd (close_typ_wrt_varref_rec (S n1) x1 T2)\n    | typ_dec dec1 => typ_dec (close_dec_wrt_varref_rec n1 x1 dec1)\n    | typ_sel v1 A1 => typ_sel (close_varref_wrt_varref_rec n1 x1 v1) A1\n    | typ_and T2 T3 => typ_and (close_typ_wrt_varref_rec n1 x1 T2) (close_typ_wrt_varref_rec n1 x1 T3)\n    | typ_top => typ_top\n    | typ_bot => typ_bot\n  end\n\nwith close_dec_wrt_varref_rec (n1 : nat) (x1 : termvar) (dec1 : dec) {struct dec1} : dec :=\n  match dec1 with\n    | dec_trm a1 T1 => dec_trm a1 (close_typ_wrt_varref_rec n1 x1 T1)\n    | dec_typ A1 T1 T2 => dec_typ A1 (close_typ_wrt_varref_rec n1 x1 T1) (close_typ_wrt_varref_rec n1 x1 T2)\n  end.\n\nDefinition close_typ_wrt_varref x1 T1 := close_typ_wrt_varref_rec 0 x1 T1.\n\nDefinition close_dec_wrt_varref x1 dec1 := close_dec_wrt_varref_rec 0 x1 dec1.\n\nFixpoint close_def_wrt_varref_rec (n1 : nat) (x1 : termvar) (d1 : def) {struct d1} : def :=\n  match d1 with\n    | def_trm a1 t1 => def_trm a1 (close_trm_wrt_varref_rec n1 x1 t1)\n    | def_typ A1 T1 => def_typ A1 (close_typ_wrt_varref_rec n1 x1 T1)\n  end\n\nwith close_defs_wrt_varref_rec (n1 : nat) (x1 : termvar) (defs1 : defs) {struct defs1} : defs :=\n  match defs1 with\n    | defs_nil => defs_nil\n    | defs_cons d1 defs2 => defs_cons (close_def_wrt_varref_rec n1 x1 d1) (close_defs_wrt_varref_rec n1 x1 defs2)\n  end\n\nwith close_val_wrt_varref_rec (n1 : nat) (x1 : termvar) (val1 : val) {struct val1} : val :=\n  match val1 with\n    | val_new T1 defs1 => val_new (close_typ_wrt_varref_rec n1 x1 T1) (close_defs_wrt_varref_rec (S n1) x1 defs1)\n    | val_lambda T1 t1 => val_lambda (close_typ_wrt_varref_rec n1 x1 T1) (close_trm_wrt_varref_rec (S n1) x1 t1)\n  end\n\nwith close_trm_wrt_varref_rec (n1 : nat) (x1 : termvar) (t1 : trm) {struct t1} : trm :=\n  match t1 with\n    | trm_var v1 => trm_var (close_varref_wrt_varref_rec n1 x1 v1)\n    | trm_val val1 => trm_val (close_val_wrt_varref_rec n1 x1 val1)\n    | trm_sel v1 a1 => trm_sel (close_varref_wrt_varref_rec n1 x1 v1) a1\n    | trm_app v1 v2 => trm_app (close_varref_wrt_varref_rec n1 x1 v1) (close_varref_wrt_varref_rec n1 x1 v2)\n    | trm_let t2 t3 => trm_let (close_trm_wrt_varref_rec n1 x1 t2) (close_trm_wrt_varref_rec (S n1) x1 t3)\n  end.\n\nDefinition close_def_wrt_varref x1 d1 := close_def_wrt_varref_rec 0 x1 d1.\n\nDefinition close_defs_wrt_varref x1 defs1 := close_defs_wrt_varref_rec 0 x1 defs1.\n\nDefinition close_val_wrt_varref x1 val1 := close_val_wrt_varref_rec 0 x1 val1.\n\nDefinition close_trm_wrt_varref x1 t1 := close_trm_wrt_varref_rec 0 x1 t1.\n\n\n(* *********************************************************************** *)\n(** * Size *)\n\nFixpoint size_varref (v1 : varref) {struct v1} : nat :=\n  match v1 with\n    | var_termvar_f x1 => 1\n    | var_termvar_b n1 => 1\n  end.\n\nFixpoint size_typ (T1 : typ) {struct T1} : nat :=\n  match T1 with\n    | typ_all T2 T3 => 1 + (size_typ T2) + (size_typ T3)\n    | typ_bnd T2 => 1 + (size_typ T2)\n    | typ_dec dec1 => 1 + (size_dec dec1)\n    | typ_sel v1 A1 => 1 + (size_varref v1)\n    | typ_and T2 T3 => 1 + (size_typ T2) + (size_typ T3)\n    | typ_top => 1\n    | typ_bot => 1\n  end\n\nwith size_dec (dec1 : dec) {struct dec1} : nat :=\n  match dec1 with\n    | dec_trm a1 T1 => 1 + (size_typ T1)\n    | dec_typ A1 T1 T2 => 1 + (size_typ T1) + (size_typ T2)\n  end.\n\nFixpoint size_def (d1 : def) {struct d1} : nat :=\n  match d1 with\n    | def_trm a1 t1 => 1 + (size_trm t1)\n    | def_typ A1 T1 => 1 + (size_typ T1)\n  end\n\nwith size_defs (defs1 : defs) {struct defs1} : nat :=\n  match defs1 with\n    | defs_nil => 1\n    | defs_cons d1 defs2 => 1 + (size_def d1) + (size_defs defs2)\n  end\n\nwith size_val (val1 : val) {struct val1} : nat :=\n  match val1 with\n    | val_new T1 defs1 => 1 + (size_typ T1) + (size_defs defs1)\n    | val_lambda T1 t1 => 1 + (size_typ T1) + (size_trm t1)\n  end\n\nwith size_trm (t1 : trm) {struct t1} : nat :=\n  match t1 with\n    | trm_var v1 => 1 + (size_varref v1)\n    | trm_val val1 => 1 + (size_val val1)\n    | trm_sel v1 a1 => 1 + (size_varref v1)\n    | trm_app v1 v2 => 1 + (size_varref v1) + (size_varref v2)\n    | trm_let t2 t3 => 1 + (size_trm t2) + (size_trm t3)\n  end.\n\n\n(* *********************************************************************** *)\n(** * Degree *)\n\n(** These define only an upper bound, not a strict upper bound. *)\n\nInductive degree_varref_wrt_varref : nat -> varref -> Prop :=\n  | degree_wrt_varref_var_termvar_f : forall n1 x1,\n    degree_varref_wrt_varref n1 (var_termvar_f x1)\n  | degree_wrt_varref_var_termvar_b : forall n1 n2,\n    lt n2 n1 ->\n    degree_varref_wrt_varref n1 (var_termvar_b n2).\n\nScheme degree_varref_wrt_varref_ind' := Induction for degree_varref_wrt_varref Sort Prop.\n\nDefinition degree_varref_wrt_varref_mutind :=\n  fun H1 H2 H3 =>\n  degree_varref_wrt_varref_ind' H1 H2 H3.\n\nHint Constructors degree_varref_wrt_varref : core lngen.\n\nInductive degree_typ_wrt_varref : nat -> typ -> Prop :=\n  | degree_wrt_varref_typ_all : forall n1 T1 T2,\n    degree_typ_wrt_varref n1 T1 ->\n    degree_typ_wrt_varref (S n1) T2 ->\n    degree_typ_wrt_varref n1 (typ_all T1 T2)\n  | degree_wrt_varref_typ_bnd : forall n1 T1,\n    degree_typ_wrt_varref (S n1) T1 ->\n    degree_typ_wrt_varref n1 (typ_bnd T1)\n  | degree_wrt_varref_typ_dec : forall n1 dec1,\n    degree_dec_wrt_varref n1 dec1 ->\n    degree_typ_wrt_varref n1 (typ_dec dec1)\n  | degree_wrt_varref_typ_sel : forall n1 v1 A1,\n    degree_varref_wrt_varref n1 v1 ->\n    degree_typ_wrt_varref n1 (typ_sel v1 A1)\n  | degree_wrt_varref_typ_and : forall n1 T1 T2,\n    degree_typ_wrt_varref n1 T1 ->\n    degree_typ_wrt_varref n1 T2 ->\n    degree_typ_wrt_varref n1 (typ_and T1 T2)\n  | degree_wrt_varref_typ_top : forall n1,\n    degree_typ_wrt_varref n1 (typ_top)\n  | degree_wrt_varref_typ_bot : forall n1,\n    degree_typ_wrt_varref n1 (typ_bot)\n\nwith degree_dec_wrt_varref : nat -> dec -> Prop :=\n  | degree_wrt_varref_dec_trm : forall n1 a1 T1,\n    degree_typ_wrt_varref n1 T1 ->\n    degree_dec_wrt_varref n1 (dec_trm a1 T1)\n  | degree_wrt_varref_dec_typ : forall n1 A1 T1 T2,\n    degree_typ_wrt_varref n1 T1 ->\n    degree_typ_wrt_varref n1 T2 ->\n    degree_dec_wrt_varref n1 (dec_typ A1 T1 T2).\n\nScheme degree_typ_wrt_varref_ind' := Induction for degree_typ_wrt_varref Sort Prop\n  with degree_dec_wrt_varref_ind' := Induction for degree_dec_wrt_varref Sort Prop.\n\nDefinition degree_typ_wrt_varref_degree_dec_wrt_varref_mutind :=\n  fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 =>\n  (conj (degree_typ_wrt_varref_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11)\n  (degree_dec_wrt_varref_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11)).\n\nHint Constructors degree_typ_wrt_varref : core lngen.\n\nHint Constructors degree_dec_wrt_varref : core lngen.\n\nInductive degree_def_wrt_varref : nat -> def -> Prop :=\n  | degree_wrt_varref_def_trm : forall n1 a1 t1,\n    degree_trm_wrt_varref n1 t1 ->\n    degree_def_wrt_varref n1 (def_trm a1 t1)\n  | degree_wrt_varref_def_typ : forall n1 A1 T1,\n    degree_typ_wrt_varref n1 T1 ->\n    degree_def_wrt_varref n1 (def_typ A1 T1)\n\nwith degree_defs_wrt_varref : nat -> defs -> Prop :=\n  | degree_wrt_varref_defs_nil : forall n1,\n    degree_defs_wrt_varref n1 (defs_nil)\n  | degree_wrt_varref_defs_cons : forall n1 d1 defs1,\n    degree_def_wrt_varref n1 d1 ->\n    degree_defs_wrt_varref n1 defs1 ->\n    degree_defs_wrt_varref n1 (defs_cons d1 defs1)\n\nwith degree_val_wrt_varref : nat -> val -> Prop :=\n  | degree_wrt_varref_val_new : forall n1 T1 defs1,\n    degree_typ_wrt_varref n1 T1 ->\n    degree_defs_wrt_varref (S n1) defs1 ->\n    degree_val_wrt_varref n1 (val_new T1 defs1)\n  | degree_wrt_varref_val_lambda : forall n1 T1 t1,\n    degree_typ_wrt_varref n1 T1 ->\n    degree_trm_wrt_varref (S n1) t1 ->\n    degree_val_wrt_varref n1 (val_lambda T1 t1)\n\nwith degree_trm_wrt_varref : nat -> trm -> Prop :=\n  | degree_wrt_varref_trm_var : forall n1 v1,\n    degree_varref_wrt_varref n1 v1 ->\n    degree_trm_wrt_varref n1 (trm_var v1)\n  | degree_wrt_varref_trm_val : forall n1 val1,\n    degree_val_wrt_varref n1 val1 ->\n    degree_trm_wrt_varref n1 (trm_val val1)\n  | degree_wrt_varref_trm_sel : forall n1 v1 a1,\n    degree_varref_wrt_varref n1 v1 ->\n    degree_trm_wrt_varref n1 (trm_sel v1 a1)\n  | degree_wrt_varref_trm_app : forall n1 v1 v2,\n    degree_varref_wrt_varref n1 v1 ->\n    degree_varref_wrt_varref n1 v2 ->\n    degree_trm_wrt_varref n1 (trm_app v1 v2)\n  | degree_wrt_varref_trm_let : forall n1 t1 t2,\n    degree_trm_wrt_varref n1 t1 ->\n    degree_trm_wrt_varref (S n1) t2 ->\n    degree_trm_wrt_varref n1 (trm_let t1 t2).\n\nScheme degree_def_wrt_varref_ind' := Induction for degree_def_wrt_varref Sort Prop\n  with degree_defs_wrt_varref_ind' := Induction for degree_defs_wrt_varref Sort Prop\n  with degree_val_wrt_varref_ind' := Induction for degree_val_wrt_varref Sort Prop\n  with degree_trm_wrt_varref_ind' := Induction for degree_trm_wrt_varref Sort Prop.\n\nDefinition degree_def_wrt_varref_degree_defs_wrt_varref_degree_val_wrt_varref_degree_trm_wrt_varref_mutind :=\n  fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15 =>\n  (conj (degree_def_wrt_varref_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15)\n  ((conj (degree_defs_wrt_varref_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15)\n  ((conj (degree_val_wrt_varref_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15)\n  (degree_trm_wrt_varref_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15)))))).\n\nHint Constructors degree_def_wrt_varref : core lngen.\n\nHint Constructors degree_defs_wrt_varref : core lngen.\n\nHint Constructors degree_val_wrt_varref : core lngen.\n\nHint Constructors degree_trm_wrt_varref : core lngen.\n\n\n(* *********************************************************************** *)\n(** * Local closure (version in [Set], induction principles) *)\n\nInductive lc_set_varref : varref -> Set :=\n  | lc_set_var_termvar_f : forall x1,\n    lc_set_varref (var_termvar_f x1).\n\nScheme lc_varref_ind' := Induction for lc_varref Sort Prop.\n\nDefinition lc_varref_mutind :=\n  fun H1 H2 =>\n  lc_varref_ind' H1 H2.\n\nScheme lc_set_varref_ind' := Induction for lc_set_varref Sort Prop.\n\nDefinition lc_set_varref_mutind :=\n  fun H1 H2 =>\n  lc_set_varref_ind' H1 H2.\n\nScheme lc_set_varref_rec' := Induction for lc_set_varref Sort Set.\n\nDefinition lc_set_varref_mutrec :=\n  fun H1 H2 =>\n  lc_set_varref_rec' H1 H2.\n\nHint Constructors lc_varref : core lngen.\n\nHint Constructors lc_set_varref : core lngen.\n\nInductive lc_set_typ : typ -> Set :=\n  | lc_set_typ_all : forall T1 T2,\n    lc_set_typ T1 ->\n    (forall x1 : termvar, lc_set_typ (open_typ_wrt_varref T2 (var_termvar_f x1))) ->\n    lc_set_typ (typ_all T1 T2)\n  | lc_set_typ_bnd : forall T1,\n    (forall x1 : termvar, lc_set_typ (open_typ_wrt_varref T1 (var_termvar_f x1))) ->\n    lc_set_typ (typ_bnd T1)\n  | lc_set_typ_dec : forall dec1,\n    lc_set_dec dec1 ->\n    lc_set_typ (typ_dec dec1)\n  | lc_set_typ_sel : forall v1 A1,\n    lc_set_varref v1 ->\n    lc_set_typ (typ_sel v1 A1)\n  | lc_set_typ_and : forall T1 T2,\n    lc_set_typ T1 ->\n    lc_set_typ T2 ->\n    lc_set_typ (typ_and T1 T2)\n  | lc_set_typ_top :\n    lc_set_typ (typ_top)\n  | lc_set_typ_bot :\n    lc_set_typ (typ_bot)\n\nwith lc_set_dec : dec -> Set :=\n  | lc_set_dec_trm : forall a1 T1,\n    lc_set_typ T1 ->\n    lc_set_dec (dec_trm a1 T1)\n  | lc_set_dec_typ : forall A1 T1 T2,\n    lc_set_typ T1 ->\n    lc_set_typ T2 ->\n    lc_set_dec (dec_typ A1 T1 T2).\n\nScheme lc_typ_ind' := Induction for lc_typ Sort Prop\n  with lc_dec_ind' := Induction for lc_dec Sort Prop.\n\nDefinition lc_typ_lc_dec_mutind :=\n  fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 =>\n  (conj (lc_typ_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11)\n  (lc_dec_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11)).\n\nScheme lc_set_typ_ind' := Induction for lc_set_typ Sort Prop\n  with lc_set_dec_ind' := Induction for lc_set_dec Sort Prop.\n\nDefinition lc_set_typ_lc_set_dec_mutind :=\n  fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 =>\n  (conj (lc_set_typ_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11)\n  (lc_set_dec_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11)).\n\nScheme lc_set_typ_rec' := Induction for lc_set_typ Sort Set\n  with lc_set_dec_rec' := Induction for lc_set_dec Sort Set.\n\nDefinition lc_set_typ_lc_set_dec_mutrec :=\n  fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 =>\n  (pair (lc_set_typ_rec' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11)\n  (lc_set_dec_rec' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11)).\n\nHint Constructors lc_typ : core lngen.\n\nHint Constructors lc_dec : core lngen.\n\nHint Constructors lc_set_typ : core lngen.\n\nHint Constructors lc_set_dec : core lngen.\n\nInductive lc_set_def : def -> Set :=\n  | lc_set_def_trm : forall a1 t1,\n    lc_set_trm t1 ->\n    lc_set_def (def_trm a1 t1)\n  | lc_set_def_typ : forall A1 T1,\n    lc_set_typ T1 ->\n    lc_set_def (def_typ A1 T1)\n\nwith lc_set_defs : defs -> Set :=\n  | lc_set_defs_nil :\n    lc_set_defs (defs_nil)\n  | lc_set_defs_cons : forall d1 defs1,\n    lc_set_def d1 ->\n    lc_set_defs defs1 ->\n    lc_set_defs (defs_cons d1 defs1)\n\nwith lc_set_val : val -> Set :=\n  | lc_set_val_new : forall T1 defs1,\n    lc_set_typ T1 ->\n    (forall x1 : termvar, lc_set_defs (open_defs_wrt_varref defs1 (var_termvar_f x1))) ->\n    lc_set_val (val_new T1 defs1)\n  | lc_set_val_lambda : forall T1 t1,\n    lc_set_typ T1 ->\n    (forall x1 : termvar, lc_set_trm (open_trm_wrt_varref t1 (var_termvar_f x1))) ->\n    lc_set_val (val_lambda T1 t1)\n\nwith lc_set_trm : trm -> Set :=\n  | lc_set_trm_var : forall v1,\n    lc_set_varref v1 ->\n    lc_set_trm (trm_var v1)\n  | lc_set_trm_val : forall val1,\n    lc_set_val val1 ->\n    lc_set_trm (trm_val val1)\n  | lc_set_trm_sel : forall v1 a1,\n    lc_set_varref v1 ->\n    lc_set_trm (trm_sel v1 a1)\n  | lc_set_trm_app : forall v1 v2,\n    lc_set_varref v1 ->\n    lc_set_varref v2 ->\n    lc_set_trm (trm_app v1 v2)\n  | lc_set_trm_let : forall t1 t2,\n    lc_set_trm t1 ->\n    (forall x1 : termvar, lc_set_trm (open_trm_wrt_varref t2 (var_termvar_f x1))) ->\n    lc_set_trm (trm_let t1 t2).\n\nScheme lc_def_ind' := Induction for lc_def Sort Prop\n  with lc_defs_ind' := Induction for lc_defs Sort Prop\n  with lc_val_ind' := Induction for lc_val Sort Prop\n  with lc_trm_ind' := Induction for lc_trm Sort Prop.\n\nDefinition lc_def_lc_defs_lc_val_lc_trm_mutind :=\n  fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15 =>\n  (conj (lc_def_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15)\n  ((conj (lc_defs_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15)\n  ((conj (lc_val_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15)\n  (lc_trm_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15)))))).\n\nScheme lc_set_def_ind' := Induction for lc_set_def Sort Prop\n  with lc_set_defs_ind' := Induction for lc_set_defs Sort Prop\n  with lc_set_val_ind' := Induction for lc_set_val Sort Prop\n  with lc_set_trm_ind' := Induction for lc_set_trm Sort Prop.\n\nDefinition lc_set_def_lc_set_defs_lc_set_val_lc_set_trm_mutind :=\n  fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15 =>\n  (conj (lc_set_def_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15)\n  ((conj (lc_set_defs_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15)\n  ((conj (lc_set_val_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15)\n  (lc_set_trm_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15)))))).\n\nScheme lc_set_def_rec' := Induction for lc_set_def Sort Set\n  with lc_set_defs_rec' := Induction for lc_set_defs Sort Set\n  with lc_set_val_rec' := Induction for lc_set_val Sort Set\n  with lc_set_trm_rec' := Induction for lc_set_trm Sort Set.\n\nDefinition lc_set_def_lc_set_defs_lc_set_val_lc_set_trm_mutrec :=\n  fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15 =>\n  (pair ((pair ((pair (lc_set_def_rec' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15)\n  (lc_set_defs_rec' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15)))\n  (lc_set_val_rec' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15)))\n  (lc_set_trm_rec' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15)).\n\nHint Constructors lc_def : core lngen.\n\nHint Constructors lc_defs : core lngen.\n\nHint Constructors lc_val : core lngen.\n\nHint Constructors lc_trm : core lngen.\n\nHint Constructors lc_set_def : core lngen.\n\nHint Constructors lc_set_defs : core lngen.\n\nHint Constructors lc_set_val : core lngen.\n\nHint Constructors lc_set_trm : core lngen.\n\n\n(* *********************************************************************** *)\n(** * Body *)\n\nDefinition body_varref_wrt_varref v1 := forall x1, lc_varref (open_varref_wrt_varref v1 (var_termvar_f x1)).\n\nHint Unfold body_varref_wrt_varref.\n\nDefinition body_typ_wrt_varref T1 := forall x1, lc_typ (open_typ_wrt_varref T1 (var_termvar_f x1)).\n\nDefinition body_dec_wrt_varref dec1 := forall x1, lc_dec (open_dec_wrt_varref dec1 (var_termvar_f x1)).\n\nHint Unfold body_typ_wrt_varref.\n\nHint Unfold body_dec_wrt_varref.\n\nDefinition body_def_wrt_varref d1 := forall x1, lc_def (open_def_wrt_varref d1 (var_termvar_f x1)).\n\nDefinition body_defs_wrt_varref defs1 := forall x1, lc_defs (open_defs_wrt_varref defs1 (var_termvar_f x1)).\n\nDefinition body_val_wrt_varref val1 := forall x1, lc_val (open_val_wrt_varref val1 (var_termvar_f x1)).\n\nDefinition body_trm_wrt_varref t1 := forall x1, lc_trm (open_trm_wrt_varref t1 (var_termvar_f x1)).\n\nHint Unfold body_def_wrt_varref.\n\nHint Unfold body_defs_wrt_varref.\n\nHint Unfold body_val_wrt_varref.\n\nHint Unfold body_trm_wrt_varref.\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_varref_min_mutual :\n(forall v1, 1 <= size_varref v1).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma size_varref_min :\nforall v1, 1 <= size_varref v1.\nProof.\npose proof size_varref_min_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_varref_min : lngen.\n\n(* begin hide *)\n\nLemma size_typ_min_size_dec_min_mutual :\n(forall T1, 1 <= size_typ T1) /\\\n(forall dec1, 1 <= size_dec dec1).\nProof.\napply_mutual_ind typ_dec_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_size_dec_min_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_typ_min : lngen.\n\nLemma size_dec_min :\nforall dec1, 1 <= size_dec dec1.\nProof.\npose proof size_typ_min_size_dec_min_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_dec_min : lngen.\n\n(* begin hide *)\n\nLemma size_def_min_size_defs_min_size_val_min_size_trm_min_mutual :\n(forall d1, 1 <= size_def d1) /\\\n(forall defs1, 1 <= size_defs defs1) /\\\n(forall val1, 1 <= size_val val1) /\\\n(forall t1, 1 <= size_trm t1).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma size_def_min :\nforall d1, 1 <= size_def d1.\nProof.\npose proof size_def_min_size_defs_min_size_val_min_size_trm_min_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_def_min : lngen.\n\nLemma size_defs_min :\nforall defs1, 1 <= size_defs defs1.\nProof.\npose proof size_def_min_size_defs_min_size_val_min_size_trm_min_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_defs_min : lngen.\n\nLemma size_val_min :\nforall val1, 1 <= size_val val1.\nProof.\npose proof size_def_min_size_defs_min_size_val_min_size_trm_min_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_val_min : lngen.\n\nLemma size_trm_min :\nforall t1, 1 <= size_trm t1.\nProof.\npose proof size_def_min_size_defs_min_size_val_min_size_trm_min_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_trm_min : lngen.\n\n(* begin hide *)\n\nLemma size_varref_close_varref_wrt_varref_rec_mutual :\n(forall v1 x1 n1,\n  size_varref (close_varref_wrt_varref_rec n1 x1 v1) = size_varref v1).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_varref_close_varref_wrt_varref_rec :\nforall v1 x1 n1,\n  size_varref (close_varref_wrt_varref_rec n1 x1 v1) = size_varref v1.\nProof.\npose proof size_varref_close_varref_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_varref_close_varref_wrt_varref_rec : lngen.\nHint Rewrite size_varref_close_varref_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_typ_close_typ_wrt_varref_rec_size_dec_close_dec_wrt_varref_rec_mutual :\n(forall T1 x1 n1,\n  size_typ (close_typ_wrt_varref_rec n1 x1 T1) = size_typ T1) /\\\n(forall dec1 x1 n1,\n  size_dec (close_dec_wrt_varref_rec n1 x1 dec1) = size_dec dec1).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_typ_close_typ_wrt_varref_rec :\nforall T1 x1 n1,\n  size_typ (close_typ_wrt_varref_rec n1 x1 T1) = size_typ T1.\nProof.\npose proof size_typ_close_typ_wrt_varref_rec_size_dec_close_dec_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_typ_close_typ_wrt_varref_rec : lngen.\nHint Rewrite size_typ_close_typ_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_dec_close_dec_wrt_varref_rec :\nforall dec1 x1 n1,\n  size_dec (close_dec_wrt_varref_rec n1 x1 dec1) = size_dec dec1.\nProof.\npose proof size_typ_close_typ_wrt_varref_rec_size_dec_close_dec_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_dec_close_dec_wrt_varref_rec : lngen.\nHint Rewrite size_dec_close_dec_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_def_close_def_wrt_varref_rec_size_defs_close_defs_wrt_varref_rec_size_val_close_val_wrt_varref_rec_size_trm_close_trm_wrt_varref_rec_mutual :\n(forall d1 x1 n1,\n  size_def (close_def_wrt_varref_rec n1 x1 d1) = size_def d1) /\\\n(forall defs1 x1 n1,\n  size_defs (close_defs_wrt_varref_rec n1 x1 defs1) = size_defs defs1) /\\\n(forall val1 x1 n1,\n  size_val (close_val_wrt_varref_rec n1 x1 val1) = size_val val1) /\\\n(forall t1 x1 n1,\n  size_trm (close_trm_wrt_varref_rec n1 x1 t1) = size_trm t1).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_def_close_def_wrt_varref_rec :\nforall d1 x1 n1,\n  size_def (close_def_wrt_varref_rec n1 x1 d1) = size_def d1.\nProof.\npose proof size_def_close_def_wrt_varref_rec_size_defs_close_defs_wrt_varref_rec_size_val_close_val_wrt_varref_rec_size_trm_close_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_def_close_def_wrt_varref_rec : lngen.\nHint Rewrite size_def_close_def_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_defs_close_defs_wrt_varref_rec :\nforall defs1 x1 n1,\n  size_defs (close_defs_wrt_varref_rec n1 x1 defs1) = size_defs defs1.\nProof.\npose proof size_def_close_def_wrt_varref_rec_size_defs_close_defs_wrt_varref_rec_size_val_close_val_wrt_varref_rec_size_trm_close_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_defs_close_defs_wrt_varref_rec : lngen.\nHint Rewrite size_defs_close_defs_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_val_close_val_wrt_varref_rec :\nforall val1 x1 n1,\n  size_val (close_val_wrt_varref_rec n1 x1 val1) = size_val val1.\nProof.\npose proof size_def_close_def_wrt_varref_rec_size_defs_close_defs_wrt_varref_rec_size_val_close_val_wrt_varref_rec_size_trm_close_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_val_close_val_wrt_varref_rec : lngen.\nHint Rewrite size_val_close_val_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_trm_close_trm_wrt_varref_rec :\nforall t1 x1 n1,\n  size_trm (close_trm_wrt_varref_rec n1 x1 t1) = size_trm t1.\nProof.\npose proof size_def_close_def_wrt_varref_rec_size_defs_close_defs_wrt_varref_rec_size_val_close_val_wrt_varref_rec_size_trm_close_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_trm_close_trm_wrt_varref_rec : lngen.\nHint Rewrite size_trm_close_trm_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\nLemma size_varref_close_varref_wrt_varref :\nforall v1 x1,\n  size_varref (close_varref_wrt_varref x1 v1) = size_varref v1.\nProof.\nunfold close_varref_wrt_varref; default_simp.\nQed.\n\nHint Resolve size_varref_close_varref_wrt_varref : lngen.\nHint Rewrite size_varref_close_varref_wrt_varref using solve [auto] : lngen.\n\nLemma size_typ_close_typ_wrt_varref :\nforall T1 x1,\n  size_typ (close_typ_wrt_varref x1 T1) = size_typ T1.\nProof.\nunfold close_typ_wrt_varref; default_simp.\nQed.\n\nHint Resolve size_typ_close_typ_wrt_varref : lngen.\nHint Rewrite size_typ_close_typ_wrt_varref using solve [auto] : lngen.\n\nLemma size_dec_close_dec_wrt_varref :\nforall dec1 x1,\n  size_dec (close_dec_wrt_varref x1 dec1) = size_dec dec1.\nProof.\nunfold close_dec_wrt_varref; default_simp.\nQed.\n\nHint Resolve size_dec_close_dec_wrt_varref : lngen.\nHint Rewrite size_dec_close_dec_wrt_varref using solve [auto] : lngen.\n\nLemma size_def_close_def_wrt_varref :\nforall d1 x1,\n  size_def (close_def_wrt_varref x1 d1) = size_def d1.\nProof.\nunfold close_def_wrt_varref; default_simp.\nQed.\n\nHint Resolve size_def_close_def_wrt_varref : lngen.\nHint Rewrite size_def_close_def_wrt_varref using solve [auto] : lngen.\n\nLemma size_defs_close_defs_wrt_varref :\nforall defs1 x1,\n  size_defs (close_defs_wrt_varref x1 defs1) = size_defs defs1.\nProof.\nunfold close_defs_wrt_varref; default_simp.\nQed.\n\nHint Resolve size_defs_close_defs_wrt_varref : lngen.\nHint Rewrite size_defs_close_defs_wrt_varref using solve [auto] : lngen.\n\nLemma size_val_close_val_wrt_varref :\nforall val1 x1,\n  size_val (close_val_wrt_varref x1 val1) = size_val val1.\nProof.\nunfold close_val_wrt_varref; default_simp.\nQed.\n\nHint Resolve size_val_close_val_wrt_varref : lngen.\nHint Rewrite size_val_close_val_wrt_varref using solve [auto] : lngen.\n\nLemma size_trm_close_trm_wrt_varref :\nforall t1 x1,\n  size_trm (close_trm_wrt_varref x1 t1) = size_trm t1.\nProof.\nunfold close_trm_wrt_varref; default_simp.\nQed.\n\nHint Resolve size_trm_close_trm_wrt_varref : lngen.\nHint Rewrite size_trm_close_trm_wrt_varref using solve [auto] : lngen.\n\n(* begin hide *)\n\nLemma size_varref_open_varref_wrt_varref_rec_mutual :\n(forall v1 v2 n1,\n  size_varref v1 <= size_varref (open_varref_wrt_varref_rec n1 v2 v1)).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_varref_open_varref_wrt_varref_rec :\nforall v1 v2 n1,\n  size_varref v1 <= size_varref (open_varref_wrt_varref_rec n1 v2 v1).\nProof.\npose proof size_varref_open_varref_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_varref_open_varref_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_typ_open_typ_wrt_varref_rec_size_dec_open_dec_wrt_varref_rec_mutual :\n(forall T1 v1 n1,\n  size_typ T1 <= size_typ (open_typ_wrt_varref_rec n1 v1 T1)) /\\\n(forall dec1 v1 n1,\n  size_dec dec1 <= size_dec (open_dec_wrt_varref_rec n1 v1 dec1)).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_typ_open_typ_wrt_varref_rec :\nforall T1 v1 n1,\n  size_typ T1 <= size_typ (open_typ_wrt_varref_rec n1 v1 T1).\nProof.\npose proof size_typ_open_typ_wrt_varref_rec_size_dec_open_dec_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_typ_open_typ_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_dec_open_dec_wrt_varref_rec :\nforall dec1 v1 n1,\n  size_dec dec1 <= size_dec (open_dec_wrt_varref_rec n1 v1 dec1).\nProof.\npose proof size_typ_open_typ_wrt_varref_rec_size_dec_open_dec_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_dec_open_dec_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_def_open_def_wrt_varref_rec_size_defs_open_defs_wrt_varref_rec_size_val_open_val_wrt_varref_rec_size_trm_open_trm_wrt_varref_rec_mutual :\n(forall d1 v1 n1,\n  size_def d1 <= size_def (open_def_wrt_varref_rec n1 v1 d1)) /\\\n(forall defs1 v1 n1,\n  size_defs defs1 <= size_defs (open_defs_wrt_varref_rec n1 v1 defs1)) /\\\n(forall val1 v1 n1,\n  size_val val1 <= size_val (open_val_wrt_varref_rec n1 v1 val1)) /\\\n(forall t1 v1 n1,\n  size_trm t1 <= size_trm (open_trm_wrt_varref_rec n1 v1 t1)).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_def_open_def_wrt_varref_rec :\nforall d1 v1 n1,\n  size_def d1 <= size_def (open_def_wrt_varref_rec n1 v1 d1).\nProof.\npose proof size_def_open_def_wrt_varref_rec_size_defs_open_defs_wrt_varref_rec_size_val_open_val_wrt_varref_rec_size_trm_open_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_def_open_def_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_defs_open_defs_wrt_varref_rec :\nforall defs1 v1 n1,\n  size_defs defs1 <= size_defs (open_defs_wrt_varref_rec n1 v1 defs1).\nProof.\npose proof size_def_open_def_wrt_varref_rec_size_defs_open_defs_wrt_varref_rec_size_val_open_val_wrt_varref_rec_size_trm_open_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_defs_open_defs_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_val_open_val_wrt_varref_rec :\nforall val1 v1 n1,\n  size_val val1 <= size_val (open_val_wrt_varref_rec n1 v1 val1).\nProof.\npose proof size_def_open_def_wrt_varref_rec_size_defs_open_defs_wrt_varref_rec_size_val_open_val_wrt_varref_rec_size_trm_open_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_val_open_val_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_trm_open_trm_wrt_varref_rec :\nforall t1 v1 n1,\n  size_trm t1 <= size_trm (open_trm_wrt_varref_rec n1 v1 t1).\nProof.\npose proof size_def_open_def_wrt_varref_rec_size_defs_open_defs_wrt_varref_rec_size_val_open_val_wrt_varref_rec_size_trm_open_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_trm_open_trm_wrt_varref_rec : lngen.\n\n(* end hide *)\n\nLemma size_varref_open_varref_wrt_varref :\nforall v1 v2,\n  size_varref v1 <= size_varref (open_varref_wrt_varref v1 v2).\nProof.\nunfold open_varref_wrt_varref; default_simp.\nQed.\n\nHint Resolve size_varref_open_varref_wrt_varref : lngen.\n\nLemma size_typ_open_typ_wrt_varref :\nforall T1 v1,\n  size_typ T1 <= size_typ (open_typ_wrt_varref T1 v1).\nProof.\nunfold open_typ_wrt_varref; default_simp.\nQed.\n\nHint Resolve size_typ_open_typ_wrt_varref : lngen.\n\nLemma size_dec_open_dec_wrt_varref :\nforall dec1 v1,\n  size_dec dec1 <= size_dec (open_dec_wrt_varref dec1 v1).\nProof.\nunfold open_dec_wrt_varref; default_simp.\nQed.\n\nHint Resolve size_dec_open_dec_wrt_varref : lngen.\n\nLemma size_def_open_def_wrt_varref :\nforall d1 v1,\n  size_def d1 <= size_def (open_def_wrt_varref d1 v1).\nProof.\nunfold open_def_wrt_varref; default_simp.\nQed.\n\nHint Resolve size_def_open_def_wrt_varref : lngen.\n\nLemma size_defs_open_defs_wrt_varref :\nforall defs1 v1,\n  size_defs defs1 <= size_defs (open_defs_wrt_varref defs1 v1).\nProof.\nunfold open_defs_wrt_varref; default_simp.\nQed.\n\nHint Resolve size_defs_open_defs_wrt_varref : lngen.\n\nLemma size_val_open_val_wrt_varref :\nforall val1 v1,\n  size_val val1 <= size_val (open_val_wrt_varref val1 v1).\nProof.\nunfold open_val_wrt_varref; default_simp.\nQed.\n\nHint Resolve size_val_open_val_wrt_varref : lngen.\n\nLemma size_trm_open_trm_wrt_varref :\nforall t1 v1,\n  size_trm t1 <= size_trm (open_trm_wrt_varref t1 v1).\nProof.\nunfold open_trm_wrt_varref; default_simp.\nQed.\n\nHint Resolve size_trm_open_trm_wrt_varref : lngen.\n\n(* begin hide *)\n\nLemma size_varref_open_varref_wrt_varref_rec_var_mutual :\n(forall v1 x1 n1,\n  size_varref (open_varref_wrt_varref_rec n1 (var_termvar_f x1) v1) = size_varref v1).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_varref_open_varref_wrt_varref_rec_var :\nforall v1 x1 n1,\n  size_varref (open_varref_wrt_varref_rec n1 (var_termvar_f x1) v1) = size_varref v1.\nProof.\npose proof size_varref_open_varref_wrt_varref_rec_var_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_varref_open_varref_wrt_varref_rec_var : lngen.\nHint Rewrite size_varref_open_varref_wrt_varref_rec_var using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_typ_open_typ_wrt_varref_rec_var_size_dec_open_dec_wrt_varref_rec_var_mutual :\n(forall T1 x1 n1,\n  size_typ (open_typ_wrt_varref_rec n1 (var_termvar_f x1) T1) = size_typ T1) /\\\n(forall dec1 x1 n1,\n  size_dec (open_dec_wrt_varref_rec n1 (var_termvar_f x1) dec1) = size_dec dec1).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_typ_open_typ_wrt_varref_rec_var :\nforall T1 x1 n1,\n  size_typ (open_typ_wrt_varref_rec n1 (var_termvar_f x1) T1) = size_typ T1.\nProof.\npose proof size_typ_open_typ_wrt_varref_rec_var_size_dec_open_dec_wrt_varref_rec_var_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_typ_open_typ_wrt_varref_rec_var : lngen.\nHint Rewrite size_typ_open_typ_wrt_varref_rec_var using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_dec_open_dec_wrt_varref_rec_var :\nforall dec1 x1 n1,\n  size_dec (open_dec_wrt_varref_rec n1 (var_termvar_f x1) dec1) = size_dec dec1.\nProof.\npose proof size_typ_open_typ_wrt_varref_rec_var_size_dec_open_dec_wrt_varref_rec_var_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_dec_open_dec_wrt_varref_rec_var : lngen.\nHint Rewrite size_dec_open_dec_wrt_varref_rec_var using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_def_open_def_wrt_varref_rec_var_size_defs_open_defs_wrt_varref_rec_var_size_val_open_val_wrt_varref_rec_var_size_trm_open_trm_wrt_varref_rec_var_mutual :\n(forall d1 x1 n1,\n  size_def (open_def_wrt_varref_rec n1 (var_termvar_f x1) d1) = size_def d1) /\\\n(forall defs1 x1 n1,\n  size_defs (open_defs_wrt_varref_rec n1 (var_termvar_f x1) defs1) = size_defs defs1) /\\\n(forall val1 x1 n1,\n  size_val (open_val_wrt_varref_rec n1 (var_termvar_f x1) val1) = size_val val1) /\\\n(forall t1 x1 n1,\n  size_trm (open_trm_wrt_varref_rec n1 (var_termvar_f x1) t1) = size_trm t1).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_def_open_def_wrt_varref_rec_var :\nforall d1 x1 n1,\n  size_def (open_def_wrt_varref_rec n1 (var_termvar_f x1) d1) = size_def d1.\nProof.\npose proof size_def_open_def_wrt_varref_rec_var_size_defs_open_defs_wrt_varref_rec_var_size_val_open_val_wrt_varref_rec_var_size_trm_open_trm_wrt_varref_rec_var_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_def_open_def_wrt_varref_rec_var : lngen.\nHint Rewrite size_def_open_def_wrt_varref_rec_var using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_defs_open_defs_wrt_varref_rec_var :\nforall defs1 x1 n1,\n  size_defs (open_defs_wrt_varref_rec n1 (var_termvar_f x1) defs1) = size_defs defs1.\nProof.\npose proof size_def_open_def_wrt_varref_rec_var_size_defs_open_defs_wrt_varref_rec_var_size_val_open_val_wrt_varref_rec_var_size_trm_open_trm_wrt_varref_rec_var_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_defs_open_defs_wrt_varref_rec_var : lngen.\nHint Rewrite size_defs_open_defs_wrt_varref_rec_var using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_val_open_val_wrt_varref_rec_var :\nforall val1 x1 n1,\n  size_val (open_val_wrt_varref_rec n1 (var_termvar_f x1) val1) = size_val val1.\nProof.\npose proof size_def_open_def_wrt_varref_rec_var_size_defs_open_defs_wrt_varref_rec_var_size_val_open_val_wrt_varref_rec_var_size_trm_open_trm_wrt_varref_rec_var_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_val_open_val_wrt_varref_rec_var : lngen.\nHint Rewrite size_val_open_val_wrt_varref_rec_var using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_trm_open_trm_wrt_varref_rec_var :\nforall t1 x1 n1,\n  size_trm (open_trm_wrt_varref_rec n1 (var_termvar_f x1) t1) = size_trm t1.\nProof.\npose proof size_def_open_def_wrt_varref_rec_var_size_defs_open_defs_wrt_varref_rec_var_size_val_open_val_wrt_varref_rec_var_size_trm_open_trm_wrt_varref_rec_var_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_trm_open_trm_wrt_varref_rec_var : lngen.\nHint Rewrite size_trm_open_trm_wrt_varref_rec_var using solve [auto] : lngen.\n\n(* end hide *)\n\nLemma size_varref_open_varref_wrt_varref_var :\nforall v1 x1,\n  size_varref (open_varref_wrt_varref v1 (var_termvar_f x1)) = size_varref v1.\nProof.\nunfold open_varref_wrt_varref; default_simp.\nQed.\n\nHint Resolve size_varref_open_varref_wrt_varref_var : lngen.\nHint Rewrite size_varref_open_varref_wrt_varref_var using solve [auto] : lngen.\n\nLemma size_typ_open_typ_wrt_varref_var :\nforall T1 x1,\n  size_typ (open_typ_wrt_varref T1 (var_termvar_f x1)) = size_typ T1.\nProof.\nunfold open_typ_wrt_varref; default_simp.\nQed.\n\nHint Resolve size_typ_open_typ_wrt_varref_var : lngen.\nHint Rewrite size_typ_open_typ_wrt_varref_var using solve [auto] : lngen.\n\nLemma size_dec_open_dec_wrt_varref_var :\nforall dec1 x1,\n  size_dec (open_dec_wrt_varref dec1 (var_termvar_f x1)) = size_dec dec1.\nProof.\nunfold open_dec_wrt_varref; default_simp.\nQed.\n\nHint Resolve size_dec_open_dec_wrt_varref_var : lngen.\nHint Rewrite size_dec_open_dec_wrt_varref_var using solve [auto] : lngen.\n\nLemma size_def_open_def_wrt_varref_var :\nforall d1 x1,\n  size_def (open_def_wrt_varref d1 (var_termvar_f x1)) = size_def d1.\nProof.\nunfold open_def_wrt_varref; default_simp.\nQed.\n\nHint Resolve size_def_open_def_wrt_varref_var : lngen.\nHint Rewrite size_def_open_def_wrt_varref_var using solve [auto] : lngen.\n\nLemma size_defs_open_defs_wrt_varref_var :\nforall defs1 x1,\n  size_defs (open_defs_wrt_varref defs1 (var_termvar_f x1)) = size_defs defs1.\nProof.\nunfold open_defs_wrt_varref; default_simp.\nQed.\n\nHint Resolve size_defs_open_defs_wrt_varref_var : lngen.\nHint Rewrite size_defs_open_defs_wrt_varref_var using solve [auto] : lngen.\n\nLemma size_val_open_val_wrt_varref_var :\nforall val1 x1,\n  size_val (open_val_wrt_varref val1 (var_termvar_f x1)) = size_val val1.\nProof.\nunfold open_val_wrt_varref; default_simp.\nQed.\n\nHint Resolve size_val_open_val_wrt_varref_var : lngen.\nHint Rewrite size_val_open_val_wrt_varref_var using solve [auto] : lngen.\n\nLemma size_trm_open_trm_wrt_varref_var :\nforall t1 x1,\n  size_trm (open_trm_wrt_varref t1 (var_termvar_f x1)) = size_trm t1.\nProof.\nunfold open_trm_wrt_varref; default_simp.\nQed.\n\nHint Resolve size_trm_open_trm_wrt_varref_var : lngen.\nHint Rewrite size_trm_open_trm_wrt_varref_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_varref_wrt_varref_S_mutual :\n(forall n1 v1,\n  degree_varref_wrt_varref n1 v1 ->\n  degree_varref_wrt_varref (S n1) v1).\nProof.\napply_mutual_ind degree_varref_wrt_varref_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma degree_varref_wrt_varref_S :\nforall n1 v1,\n  degree_varref_wrt_varref n1 v1 ->\n  degree_varref_wrt_varref (S n1) v1.\nProof.\npose proof degree_varref_wrt_varref_S_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_varref_wrt_varref_S : lngen.\n\n(* begin hide *)\n\nLemma degree_typ_wrt_varref_S_degree_dec_wrt_varref_S_mutual :\n(forall n1 T1,\n  degree_typ_wrt_varref n1 T1 ->\n  degree_typ_wrt_varref (S n1) T1) /\\\n(forall n1 dec1,\n  degree_dec_wrt_varref n1 dec1 ->\n  degree_dec_wrt_varref (S n1) dec1).\nProof.\napply_mutual_ind degree_typ_wrt_varref_degree_dec_wrt_varref_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma degree_typ_wrt_varref_S :\nforall n1 T1,\n  degree_typ_wrt_varref n1 T1 ->\n  degree_typ_wrt_varref (S n1) T1.\nProof.\npose proof degree_typ_wrt_varref_S_degree_dec_wrt_varref_S_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_typ_wrt_varref_S : lngen.\n\nLemma degree_dec_wrt_varref_S :\nforall n1 dec1,\n  degree_dec_wrt_varref n1 dec1 ->\n  degree_dec_wrt_varref (S n1) dec1.\nProof.\npose proof degree_typ_wrt_varref_S_degree_dec_wrt_varref_S_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_dec_wrt_varref_S : lngen.\n\n(* begin hide *)\n\nLemma degree_def_wrt_varref_S_degree_defs_wrt_varref_S_degree_val_wrt_varref_S_degree_trm_wrt_varref_S_mutual :\n(forall n1 d1,\n  degree_def_wrt_varref n1 d1 ->\n  degree_def_wrt_varref (S n1) d1) /\\\n(forall n1 defs1,\n  degree_defs_wrt_varref n1 defs1 ->\n  degree_defs_wrt_varref (S n1) defs1) /\\\n(forall n1 val1,\n  degree_val_wrt_varref n1 val1 ->\n  degree_val_wrt_varref (S n1) val1) /\\\n(forall n1 t1,\n  degree_trm_wrt_varref n1 t1 ->\n  degree_trm_wrt_varref (S n1) t1).\nProof.\napply_mutual_ind degree_def_wrt_varref_degree_defs_wrt_varref_degree_val_wrt_varref_degree_trm_wrt_varref_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma degree_def_wrt_varref_S :\nforall n1 d1,\n  degree_def_wrt_varref n1 d1 ->\n  degree_def_wrt_varref (S n1) d1.\nProof.\npose proof degree_def_wrt_varref_S_degree_defs_wrt_varref_S_degree_val_wrt_varref_S_degree_trm_wrt_varref_S_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_def_wrt_varref_S : lngen.\n\nLemma degree_defs_wrt_varref_S :\nforall n1 defs1,\n  degree_defs_wrt_varref n1 defs1 ->\n  degree_defs_wrt_varref (S n1) defs1.\nProof.\npose proof degree_def_wrt_varref_S_degree_defs_wrt_varref_S_degree_val_wrt_varref_S_degree_trm_wrt_varref_S_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_defs_wrt_varref_S : lngen.\n\nLemma degree_val_wrt_varref_S :\nforall n1 val1,\n  degree_val_wrt_varref n1 val1 ->\n  degree_val_wrt_varref (S n1) val1.\nProof.\npose proof degree_def_wrt_varref_S_degree_defs_wrt_varref_S_degree_val_wrt_varref_S_degree_trm_wrt_varref_S_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_val_wrt_varref_S : lngen.\n\nLemma degree_trm_wrt_varref_S :\nforall n1 t1,\n  degree_trm_wrt_varref n1 t1 ->\n  degree_trm_wrt_varref (S n1) t1.\nProof.\npose proof degree_def_wrt_varref_S_degree_defs_wrt_varref_S_degree_val_wrt_varref_S_degree_trm_wrt_varref_S_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_trm_wrt_varref_S : lngen.\n\nLemma degree_varref_wrt_varref_O :\nforall n1 v1,\n  degree_varref_wrt_varref O v1 ->\n  degree_varref_wrt_varref n1 v1.\nProof.\ninduction n1; default_simp.\nQed.\n\nHint Resolve degree_varref_wrt_varref_O : lngen.\n\nLemma degree_typ_wrt_varref_O :\nforall n1 T1,\n  degree_typ_wrt_varref O T1 ->\n  degree_typ_wrt_varref n1 T1.\nProof.\ninduction n1; default_simp.\nQed.\n\nHint Resolve degree_typ_wrt_varref_O : lngen.\n\nLemma degree_dec_wrt_varref_O :\nforall n1 dec1,\n  degree_dec_wrt_varref O dec1 ->\n  degree_dec_wrt_varref n1 dec1.\nProof.\ninduction n1; default_simp.\nQed.\n\nHint Resolve degree_dec_wrt_varref_O : lngen.\n\nLemma degree_def_wrt_varref_O :\nforall n1 d1,\n  degree_def_wrt_varref O d1 ->\n  degree_def_wrt_varref n1 d1.\nProof.\ninduction n1; default_simp.\nQed.\n\nHint Resolve degree_def_wrt_varref_O : lngen.\n\nLemma degree_defs_wrt_varref_O :\nforall n1 defs1,\n  degree_defs_wrt_varref O defs1 ->\n  degree_defs_wrt_varref n1 defs1.\nProof.\ninduction n1; default_simp.\nQed.\n\nHint Resolve degree_defs_wrt_varref_O : lngen.\n\nLemma degree_val_wrt_varref_O :\nforall n1 val1,\n  degree_val_wrt_varref O val1 ->\n  degree_val_wrt_varref n1 val1.\nProof.\ninduction n1; default_simp.\nQed.\n\nHint Resolve degree_val_wrt_varref_O : lngen.\n\nLemma degree_trm_wrt_varref_O :\nforall n1 t1,\n  degree_trm_wrt_varref O t1 ->\n  degree_trm_wrt_varref n1 t1.\nProof.\ninduction n1; default_simp.\nQed.\n\nHint Resolve degree_trm_wrt_varref_O : lngen.\n\n(* begin hide *)\n\nLemma degree_varref_wrt_varref_close_varref_wrt_varref_rec_mutual :\n(forall v1 x1 n1,\n  degree_varref_wrt_varref n1 v1 ->\n  degree_varref_wrt_varref (S n1) (close_varref_wrt_varref_rec n1 x1 v1)).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_varref_wrt_varref_close_varref_wrt_varref_rec :\nforall v1 x1 n1,\n  degree_varref_wrt_varref n1 v1 ->\n  degree_varref_wrt_varref (S n1) (close_varref_wrt_varref_rec n1 x1 v1).\nProof.\npose proof degree_varref_wrt_varref_close_varref_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_varref_wrt_varref_close_varref_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_typ_wrt_varref_close_typ_wrt_varref_rec_degree_dec_wrt_varref_close_dec_wrt_varref_rec_mutual :\n(forall T1 x1 n1,\n  degree_typ_wrt_varref n1 T1 ->\n  degree_typ_wrt_varref (S n1) (close_typ_wrt_varref_rec n1 x1 T1)) /\\\n(forall dec1 x1 n1,\n  degree_dec_wrt_varref n1 dec1 ->\n  degree_dec_wrt_varref (S n1) (close_dec_wrt_varref_rec n1 x1 dec1)).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_typ_wrt_varref_close_typ_wrt_varref_rec :\nforall T1 x1 n1,\n  degree_typ_wrt_varref n1 T1 ->\n  degree_typ_wrt_varref (S n1) (close_typ_wrt_varref_rec n1 x1 T1).\nProof.\npose proof degree_typ_wrt_varref_close_typ_wrt_varref_rec_degree_dec_wrt_varref_close_dec_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_typ_wrt_varref_close_typ_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_dec_wrt_varref_close_dec_wrt_varref_rec :\nforall dec1 x1 n1,\n  degree_dec_wrt_varref n1 dec1 ->\n  degree_dec_wrt_varref (S n1) (close_dec_wrt_varref_rec n1 x1 dec1).\nProof.\npose proof degree_typ_wrt_varref_close_typ_wrt_varref_rec_degree_dec_wrt_varref_close_dec_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_dec_wrt_varref_close_dec_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_def_wrt_varref_close_def_wrt_varref_rec_degree_defs_wrt_varref_close_defs_wrt_varref_rec_degree_val_wrt_varref_close_val_wrt_varref_rec_degree_trm_wrt_varref_close_trm_wrt_varref_rec_mutual :\n(forall d1 x1 n1,\n  degree_def_wrt_varref n1 d1 ->\n  degree_def_wrt_varref (S n1) (close_def_wrt_varref_rec n1 x1 d1)) /\\\n(forall defs1 x1 n1,\n  degree_defs_wrt_varref n1 defs1 ->\n  degree_defs_wrt_varref (S n1) (close_defs_wrt_varref_rec n1 x1 defs1)) /\\\n(forall val1 x1 n1,\n  degree_val_wrt_varref n1 val1 ->\n  degree_val_wrt_varref (S n1) (close_val_wrt_varref_rec n1 x1 val1)) /\\\n(forall t1 x1 n1,\n  degree_trm_wrt_varref n1 t1 ->\n  degree_trm_wrt_varref (S n1) (close_trm_wrt_varref_rec n1 x1 t1)).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_def_wrt_varref_close_def_wrt_varref_rec :\nforall d1 x1 n1,\n  degree_def_wrt_varref n1 d1 ->\n  degree_def_wrt_varref (S n1) (close_def_wrt_varref_rec n1 x1 d1).\nProof.\npose proof degree_def_wrt_varref_close_def_wrt_varref_rec_degree_defs_wrt_varref_close_defs_wrt_varref_rec_degree_val_wrt_varref_close_val_wrt_varref_rec_degree_trm_wrt_varref_close_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_def_wrt_varref_close_def_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_defs_wrt_varref_close_defs_wrt_varref_rec :\nforall defs1 x1 n1,\n  degree_defs_wrt_varref n1 defs1 ->\n  degree_defs_wrt_varref (S n1) (close_defs_wrt_varref_rec n1 x1 defs1).\nProof.\npose proof degree_def_wrt_varref_close_def_wrt_varref_rec_degree_defs_wrt_varref_close_defs_wrt_varref_rec_degree_val_wrt_varref_close_val_wrt_varref_rec_degree_trm_wrt_varref_close_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_defs_wrt_varref_close_defs_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_val_wrt_varref_close_val_wrt_varref_rec :\nforall val1 x1 n1,\n  degree_val_wrt_varref n1 val1 ->\n  degree_val_wrt_varref (S n1) (close_val_wrt_varref_rec n1 x1 val1).\nProof.\npose proof degree_def_wrt_varref_close_def_wrt_varref_rec_degree_defs_wrt_varref_close_defs_wrt_varref_rec_degree_val_wrt_varref_close_val_wrt_varref_rec_degree_trm_wrt_varref_close_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_val_wrt_varref_close_val_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_trm_wrt_varref_close_trm_wrt_varref_rec :\nforall t1 x1 n1,\n  degree_trm_wrt_varref n1 t1 ->\n  degree_trm_wrt_varref (S n1) (close_trm_wrt_varref_rec n1 x1 t1).\nProof.\npose proof degree_def_wrt_varref_close_def_wrt_varref_rec_degree_defs_wrt_varref_close_defs_wrt_varref_rec_degree_val_wrt_varref_close_val_wrt_varref_rec_degree_trm_wrt_varref_close_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_trm_wrt_varref_close_trm_wrt_varref_rec : lngen.\n\n(* end hide *)\n\nLemma degree_varref_wrt_varref_close_varref_wrt_varref :\nforall v1 x1,\n  degree_varref_wrt_varref 0 v1 ->\n  degree_varref_wrt_varref 1 (close_varref_wrt_varref x1 v1).\nProof.\nunfold close_varref_wrt_varref; default_simp.\nQed.\n\nHint Resolve degree_varref_wrt_varref_close_varref_wrt_varref : lngen.\n\nLemma degree_typ_wrt_varref_close_typ_wrt_varref :\nforall T1 x1,\n  degree_typ_wrt_varref 0 T1 ->\n  degree_typ_wrt_varref 1 (close_typ_wrt_varref x1 T1).\nProof.\nunfold close_typ_wrt_varref; default_simp.\nQed.\n\nHint Resolve degree_typ_wrt_varref_close_typ_wrt_varref : lngen.\n\nLemma degree_dec_wrt_varref_close_dec_wrt_varref :\nforall dec1 x1,\n  degree_dec_wrt_varref 0 dec1 ->\n  degree_dec_wrt_varref 1 (close_dec_wrt_varref x1 dec1).\nProof.\nunfold close_dec_wrt_varref; default_simp.\nQed.\n\nHint Resolve degree_dec_wrt_varref_close_dec_wrt_varref : lngen.\n\nLemma degree_def_wrt_varref_close_def_wrt_varref :\nforall d1 x1,\n  degree_def_wrt_varref 0 d1 ->\n  degree_def_wrt_varref 1 (close_def_wrt_varref x1 d1).\nProof.\nunfold close_def_wrt_varref; default_simp.\nQed.\n\nHint Resolve degree_def_wrt_varref_close_def_wrt_varref : lngen.\n\nLemma degree_defs_wrt_varref_close_defs_wrt_varref :\nforall defs1 x1,\n  degree_defs_wrt_varref 0 defs1 ->\n  degree_defs_wrt_varref 1 (close_defs_wrt_varref x1 defs1).\nProof.\nunfold close_defs_wrt_varref; default_simp.\nQed.\n\nHint Resolve degree_defs_wrt_varref_close_defs_wrt_varref : lngen.\n\nLemma degree_val_wrt_varref_close_val_wrt_varref :\nforall val1 x1,\n  degree_val_wrt_varref 0 val1 ->\n  degree_val_wrt_varref 1 (close_val_wrt_varref x1 val1).\nProof.\nunfold close_val_wrt_varref; default_simp.\nQed.\n\nHint Resolve degree_val_wrt_varref_close_val_wrt_varref : lngen.\n\nLemma degree_trm_wrt_varref_close_trm_wrt_varref :\nforall t1 x1,\n  degree_trm_wrt_varref 0 t1 ->\n  degree_trm_wrt_varref 1 (close_trm_wrt_varref x1 t1).\nProof.\nunfold close_trm_wrt_varref; default_simp.\nQed.\n\nHint Resolve degree_trm_wrt_varref_close_trm_wrt_varref : lngen.\n\n(* begin hide *)\n\nLemma degree_varref_wrt_varref_close_varref_wrt_varref_rec_inv_mutual :\n(forall v1 x1 n1,\n  degree_varref_wrt_varref (S n1) (close_varref_wrt_varref_rec n1 x1 v1) ->\n  degree_varref_wrt_varref n1 v1).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp; eauto with lngen.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_varref_wrt_varref_close_varref_wrt_varref_rec_inv :\nforall v1 x1 n1,\n  degree_varref_wrt_varref (S n1) (close_varref_wrt_varref_rec n1 x1 v1) ->\n  degree_varref_wrt_varref n1 v1.\nProof.\npose proof degree_varref_wrt_varref_close_varref_wrt_varref_rec_inv_mutual as H; intuition eauto.\nQed.\n\nHint Immediate degree_varref_wrt_varref_close_varref_wrt_varref_rec_inv : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_typ_wrt_varref_close_typ_wrt_varref_rec_inv_degree_dec_wrt_varref_close_dec_wrt_varref_rec_inv_mutual :\n(forall T1 x1 n1,\n  degree_typ_wrt_varref (S n1) (close_typ_wrt_varref_rec n1 x1 T1) ->\n  degree_typ_wrt_varref n1 T1) /\\\n(forall dec1 x1 n1,\n  degree_dec_wrt_varref (S n1) (close_dec_wrt_varref_rec n1 x1 dec1) ->\n  degree_dec_wrt_varref n1 dec1).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp; eauto with lngen.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_typ_wrt_varref_close_typ_wrt_varref_rec_inv :\nforall T1 x1 n1,\n  degree_typ_wrt_varref (S n1) (close_typ_wrt_varref_rec n1 x1 T1) ->\n  degree_typ_wrt_varref n1 T1.\nProof.\npose proof degree_typ_wrt_varref_close_typ_wrt_varref_rec_inv_degree_dec_wrt_varref_close_dec_wrt_varref_rec_inv_mutual as H; intuition eauto.\nQed.\n\nHint Immediate degree_typ_wrt_varref_close_typ_wrt_varref_rec_inv : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_dec_wrt_varref_close_dec_wrt_varref_rec_inv :\nforall dec1 x1 n1,\n  degree_dec_wrt_varref (S n1) (close_dec_wrt_varref_rec n1 x1 dec1) ->\n  degree_dec_wrt_varref n1 dec1.\nProof.\npose proof degree_typ_wrt_varref_close_typ_wrt_varref_rec_inv_degree_dec_wrt_varref_close_dec_wrt_varref_rec_inv_mutual as H; intuition eauto.\nQed.\n\nHint Immediate degree_dec_wrt_varref_close_dec_wrt_varref_rec_inv : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_def_wrt_varref_close_def_wrt_varref_rec_inv_degree_defs_wrt_varref_close_defs_wrt_varref_rec_inv_degree_val_wrt_varref_close_val_wrt_varref_rec_inv_degree_trm_wrt_varref_close_trm_wrt_varref_rec_inv_mutual :\n(forall d1 x1 n1,\n  degree_def_wrt_varref (S n1) (close_def_wrt_varref_rec n1 x1 d1) ->\n  degree_def_wrt_varref n1 d1) /\\\n(forall defs1 x1 n1,\n  degree_defs_wrt_varref (S n1) (close_defs_wrt_varref_rec n1 x1 defs1) ->\n  degree_defs_wrt_varref n1 defs1) /\\\n(forall val1 x1 n1,\n  degree_val_wrt_varref (S n1) (close_val_wrt_varref_rec n1 x1 val1) ->\n  degree_val_wrt_varref n1 val1) /\\\n(forall t1 x1 n1,\n  degree_trm_wrt_varref (S n1) (close_trm_wrt_varref_rec n1 x1 t1) ->\n  degree_trm_wrt_varref n1 t1).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp; eauto with lngen.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_def_wrt_varref_close_def_wrt_varref_rec_inv :\nforall d1 x1 n1,\n  degree_def_wrt_varref (S n1) (close_def_wrt_varref_rec n1 x1 d1) ->\n  degree_def_wrt_varref n1 d1.\nProof.\npose proof degree_def_wrt_varref_close_def_wrt_varref_rec_inv_degree_defs_wrt_varref_close_defs_wrt_varref_rec_inv_degree_val_wrt_varref_close_val_wrt_varref_rec_inv_degree_trm_wrt_varref_close_trm_wrt_varref_rec_inv_mutual as H; intuition eauto.\nQed.\n\nHint Immediate degree_def_wrt_varref_close_def_wrt_varref_rec_inv : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_defs_wrt_varref_close_defs_wrt_varref_rec_inv :\nforall defs1 x1 n1,\n  degree_defs_wrt_varref (S n1) (close_defs_wrt_varref_rec n1 x1 defs1) ->\n  degree_defs_wrt_varref n1 defs1.\nProof.\npose proof degree_def_wrt_varref_close_def_wrt_varref_rec_inv_degree_defs_wrt_varref_close_defs_wrt_varref_rec_inv_degree_val_wrt_varref_close_val_wrt_varref_rec_inv_degree_trm_wrt_varref_close_trm_wrt_varref_rec_inv_mutual as H; intuition eauto.\nQed.\n\nHint Immediate degree_defs_wrt_varref_close_defs_wrt_varref_rec_inv : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_val_wrt_varref_close_val_wrt_varref_rec_inv :\nforall val1 x1 n1,\n  degree_val_wrt_varref (S n1) (close_val_wrt_varref_rec n1 x1 val1) ->\n  degree_val_wrt_varref n1 val1.\nProof.\npose proof degree_def_wrt_varref_close_def_wrt_varref_rec_inv_degree_defs_wrt_varref_close_defs_wrt_varref_rec_inv_degree_val_wrt_varref_close_val_wrt_varref_rec_inv_degree_trm_wrt_varref_close_trm_wrt_varref_rec_inv_mutual as H; intuition eauto.\nQed.\n\nHint Immediate degree_val_wrt_varref_close_val_wrt_varref_rec_inv : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_trm_wrt_varref_close_trm_wrt_varref_rec_inv :\nforall t1 x1 n1,\n  degree_trm_wrt_varref (S n1) (close_trm_wrt_varref_rec n1 x1 t1) ->\n  degree_trm_wrt_varref n1 t1.\nProof.\npose proof degree_def_wrt_varref_close_def_wrt_varref_rec_inv_degree_defs_wrt_varref_close_defs_wrt_varref_rec_inv_degree_val_wrt_varref_close_val_wrt_varref_rec_inv_degree_trm_wrt_varref_close_trm_wrt_varref_rec_inv_mutual as H; intuition eauto.\nQed.\n\nHint Immediate degree_trm_wrt_varref_close_trm_wrt_varref_rec_inv : lngen.\n\n(* end hide *)\n\nLemma degree_varref_wrt_varref_close_varref_wrt_varref_inv :\nforall v1 x1,\n  degree_varref_wrt_varref 1 (close_varref_wrt_varref x1 v1) ->\n  degree_varref_wrt_varref 0 v1.\nProof.\nunfold close_varref_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate degree_varref_wrt_varref_close_varref_wrt_varref_inv : lngen.\n\nLemma degree_typ_wrt_varref_close_typ_wrt_varref_inv :\nforall T1 x1,\n  degree_typ_wrt_varref 1 (close_typ_wrt_varref x1 T1) ->\n  degree_typ_wrt_varref 0 T1.\nProof.\nunfold close_typ_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate degree_typ_wrt_varref_close_typ_wrt_varref_inv : lngen.\n\nLemma degree_dec_wrt_varref_close_dec_wrt_varref_inv :\nforall dec1 x1,\n  degree_dec_wrt_varref 1 (close_dec_wrt_varref x1 dec1) ->\n  degree_dec_wrt_varref 0 dec1.\nProof.\nunfold close_dec_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate degree_dec_wrt_varref_close_dec_wrt_varref_inv : lngen.\n\nLemma degree_def_wrt_varref_close_def_wrt_varref_inv :\nforall d1 x1,\n  degree_def_wrt_varref 1 (close_def_wrt_varref x1 d1) ->\n  degree_def_wrt_varref 0 d1.\nProof.\nunfold close_def_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate degree_def_wrt_varref_close_def_wrt_varref_inv : lngen.\n\nLemma degree_defs_wrt_varref_close_defs_wrt_varref_inv :\nforall defs1 x1,\n  degree_defs_wrt_varref 1 (close_defs_wrt_varref x1 defs1) ->\n  degree_defs_wrt_varref 0 defs1.\nProof.\nunfold close_defs_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate degree_defs_wrt_varref_close_defs_wrt_varref_inv : lngen.\n\nLemma degree_val_wrt_varref_close_val_wrt_varref_inv :\nforall val1 x1,\n  degree_val_wrt_varref 1 (close_val_wrt_varref x1 val1) ->\n  degree_val_wrt_varref 0 val1.\nProof.\nunfold close_val_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate degree_val_wrt_varref_close_val_wrt_varref_inv : lngen.\n\nLemma degree_trm_wrt_varref_close_trm_wrt_varref_inv :\nforall t1 x1,\n  degree_trm_wrt_varref 1 (close_trm_wrt_varref x1 t1) ->\n  degree_trm_wrt_varref 0 t1.\nProof.\nunfold close_trm_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate degree_trm_wrt_varref_close_trm_wrt_varref_inv : lngen.\n\n(* begin hide *)\n\nLemma degree_varref_wrt_varref_open_varref_wrt_varref_rec_mutual :\n(forall v1 v2 n1,\n  degree_varref_wrt_varref (S n1) v1 ->\n  degree_varref_wrt_varref n1 v2 ->\n  degree_varref_wrt_varref n1 (open_varref_wrt_varref_rec n1 v2 v1)).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_varref_wrt_varref_open_varref_wrt_varref_rec :\nforall v1 v2 n1,\n  degree_varref_wrt_varref (S n1) v1 ->\n  degree_varref_wrt_varref n1 v2 ->\n  degree_varref_wrt_varref n1 (open_varref_wrt_varref_rec n1 v2 v1).\nProof.\npose proof degree_varref_wrt_varref_open_varref_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_varref_wrt_varref_open_varref_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_typ_wrt_varref_open_typ_wrt_varref_rec_degree_dec_wrt_varref_open_dec_wrt_varref_rec_mutual :\n(forall T1 v1 n1,\n  degree_typ_wrt_varref (S n1) T1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  degree_typ_wrt_varref n1 (open_typ_wrt_varref_rec n1 v1 T1)) /\\\n(forall dec1 v1 n1,\n  degree_dec_wrt_varref (S n1) dec1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  degree_dec_wrt_varref n1 (open_dec_wrt_varref_rec n1 v1 dec1)).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_typ_wrt_varref_open_typ_wrt_varref_rec :\nforall T1 v1 n1,\n  degree_typ_wrt_varref (S n1) T1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  degree_typ_wrt_varref n1 (open_typ_wrt_varref_rec n1 v1 T1).\nProof.\npose proof degree_typ_wrt_varref_open_typ_wrt_varref_rec_degree_dec_wrt_varref_open_dec_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_typ_wrt_varref_open_typ_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_dec_wrt_varref_open_dec_wrt_varref_rec :\nforall dec1 v1 n1,\n  degree_dec_wrt_varref (S n1) dec1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  degree_dec_wrt_varref n1 (open_dec_wrt_varref_rec n1 v1 dec1).\nProof.\npose proof degree_typ_wrt_varref_open_typ_wrt_varref_rec_degree_dec_wrt_varref_open_dec_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_dec_wrt_varref_open_dec_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_def_wrt_varref_open_def_wrt_varref_rec_degree_defs_wrt_varref_open_defs_wrt_varref_rec_degree_val_wrt_varref_open_val_wrt_varref_rec_degree_trm_wrt_varref_open_trm_wrt_varref_rec_mutual :\n(forall d1 v1 n1,\n  degree_def_wrt_varref (S n1) d1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  degree_def_wrt_varref n1 (open_def_wrt_varref_rec n1 v1 d1)) /\\\n(forall defs1 v1 n1,\n  degree_defs_wrt_varref (S n1) defs1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  degree_defs_wrt_varref n1 (open_defs_wrt_varref_rec n1 v1 defs1)) /\\\n(forall val1 v1 n1,\n  degree_val_wrt_varref (S n1) val1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  degree_val_wrt_varref n1 (open_val_wrt_varref_rec n1 v1 val1)) /\\\n(forall t1 v1 n1,\n  degree_trm_wrt_varref (S n1) t1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  degree_trm_wrt_varref n1 (open_trm_wrt_varref_rec n1 v1 t1)).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_def_wrt_varref_open_def_wrt_varref_rec :\nforall d1 v1 n1,\n  degree_def_wrt_varref (S n1) d1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  degree_def_wrt_varref n1 (open_def_wrt_varref_rec n1 v1 d1).\nProof.\npose proof degree_def_wrt_varref_open_def_wrt_varref_rec_degree_defs_wrt_varref_open_defs_wrt_varref_rec_degree_val_wrt_varref_open_val_wrt_varref_rec_degree_trm_wrt_varref_open_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_def_wrt_varref_open_def_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_defs_wrt_varref_open_defs_wrt_varref_rec :\nforall defs1 v1 n1,\n  degree_defs_wrt_varref (S n1) defs1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  degree_defs_wrt_varref n1 (open_defs_wrt_varref_rec n1 v1 defs1).\nProof.\npose proof degree_def_wrt_varref_open_def_wrt_varref_rec_degree_defs_wrt_varref_open_defs_wrt_varref_rec_degree_val_wrt_varref_open_val_wrt_varref_rec_degree_trm_wrt_varref_open_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_defs_wrt_varref_open_defs_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_val_wrt_varref_open_val_wrt_varref_rec :\nforall val1 v1 n1,\n  degree_val_wrt_varref (S n1) val1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  degree_val_wrt_varref n1 (open_val_wrt_varref_rec n1 v1 val1).\nProof.\npose proof degree_def_wrt_varref_open_def_wrt_varref_rec_degree_defs_wrt_varref_open_defs_wrt_varref_rec_degree_val_wrt_varref_open_val_wrt_varref_rec_degree_trm_wrt_varref_open_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_val_wrt_varref_open_val_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_trm_wrt_varref_open_trm_wrt_varref_rec :\nforall t1 v1 n1,\n  degree_trm_wrt_varref (S n1) t1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  degree_trm_wrt_varref n1 (open_trm_wrt_varref_rec n1 v1 t1).\nProof.\npose proof degree_def_wrt_varref_open_def_wrt_varref_rec_degree_defs_wrt_varref_open_defs_wrt_varref_rec_degree_val_wrt_varref_open_val_wrt_varref_rec_degree_trm_wrt_varref_open_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_trm_wrt_varref_open_trm_wrt_varref_rec : lngen.\n\n(* end hide *)\n\nLemma degree_varref_wrt_varref_open_varref_wrt_varref :\nforall v1 v2,\n  degree_varref_wrt_varref 1 v1 ->\n  degree_varref_wrt_varref 0 v2 ->\n  degree_varref_wrt_varref 0 (open_varref_wrt_varref v1 v2).\nProof.\nunfold open_varref_wrt_varref; default_simp.\nQed.\n\nHint Resolve degree_varref_wrt_varref_open_varref_wrt_varref : lngen.\n\nLemma degree_typ_wrt_varref_open_typ_wrt_varref :\nforall T1 v1,\n  degree_typ_wrt_varref 1 T1 ->\n  degree_varref_wrt_varref 0 v1 ->\n  degree_typ_wrt_varref 0 (open_typ_wrt_varref T1 v1).\nProof.\nunfold open_typ_wrt_varref; default_simp.\nQed.\n\nHint Resolve degree_typ_wrt_varref_open_typ_wrt_varref : lngen.\n\nLemma degree_dec_wrt_varref_open_dec_wrt_varref :\nforall dec1 v1,\n  degree_dec_wrt_varref 1 dec1 ->\n  degree_varref_wrt_varref 0 v1 ->\n  degree_dec_wrt_varref 0 (open_dec_wrt_varref dec1 v1).\nProof.\nunfold open_dec_wrt_varref; default_simp.\nQed.\n\nHint Resolve degree_dec_wrt_varref_open_dec_wrt_varref : lngen.\n\nLemma degree_def_wrt_varref_open_def_wrt_varref :\nforall d1 v1,\n  degree_def_wrt_varref 1 d1 ->\n  degree_varref_wrt_varref 0 v1 ->\n  degree_def_wrt_varref 0 (open_def_wrt_varref d1 v1).\nProof.\nunfold open_def_wrt_varref; default_simp.\nQed.\n\nHint Resolve degree_def_wrt_varref_open_def_wrt_varref : lngen.\n\nLemma degree_defs_wrt_varref_open_defs_wrt_varref :\nforall defs1 v1,\n  degree_defs_wrt_varref 1 defs1 ->\n  degree_varref_wrt_varref 0 v1 ->\n  degree_defs_wrt_varref 0 (open_defs_wrt_varref defs1 v1).\nProof.\nunfold open_defs_wrt_varref; default_simp.\nQed.\n\nHint Resolve degree_defs_wrt_varref_open_defs_wrt_varref : lngen.\n\nLemma degree_val_wrt_varref_open_val_wrt_varref :\nforall val1 v1,\n  degree_val_wrt_varref 1 val1 ->\n  degree_varref_wrt_varref 0 v1 ->\n  degree_val_wrt_varref 0 (open_val_wrt_varref val1 v1).\nProof.\nunfold open_val_wrt_varref; default_simp.\nQed.\n\nHint Resolve degree_val_wrt_varref_open_val_wrt_varref : lngen.\n\nLemma degree_trm_wrt_varref_open_trm_wrt_varref :\nforall t1 v1,\n  degree_trm_wrt_varref 1 t1 ->\n  degree_varref_wrt_varref 0 v1 ->\n  degree_trm_wrt_varref 0 (open_trm_wrt_varref t1 v1).\nProof.\nunfold open_trm_wrt_varref; default_simp.\nQed.\n\nHint Resolve degree_trm_wrt_varref_open_trm_wrt_varref : lngen.\n\n(* begin hide *)\n\nLemma degree_varref_wrt_varref_open_varref_wrt_varref_rec_inv_mutual :\n(forall v1 v2 n1,\n  degree_varref_wrt_varref n1 (open_varref_wrt_varref_rec n1 v2 v1) ->\n  degree_varref_wrt_varref (S n1) v1).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp; eauto with lngen.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_varref_wrt_varref_open_varref_wrt_varref_rec_inv :\nforall v1 v2 n1,\n  degree_varref_wrt_varref n1 (open_varref_wrt_varref_rec n1 v2 v1) ->\n  degree_varref_wrt_varref (S n1) v1.\nProof.\npose proof degree_varref_wrt_varref_open_varref_wrt_varref_rec_inv_mutual as H; intuition eauto.\nQed.\n\nHint Immediate degree_varref_wrt_varref_open_varref_wrt_varref_rec_inv : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_typ_wrt_varref_open_typ_wrt_varref_rec_inv_degree_dec_wrt_varref_open_dec_wrt_varref_rec_inv_mutual :\n(forall T1 v1 n1,\n  degree_typ_wrt_varref n1 (open_typ_wrt_varref_rec n1 v1 T1) ->\n  degree_typ_wrt_varref (S n1) T1) /\\\n(forall dec1 v1 n1,\n  degree_dec_wrt_varref n1 (open_dec_wrt_varref_rec n1 v1 dec1) ->\n  degree_dec_wrt_varref (S n1) dec1).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp; eauto with lngen.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_typ_wrt_varref_open_typ_wrt_varref_rec_inv :\nforall T1 v1 n1,\n  degree_typ_wrt_varref n1 (open_typ_wrt_varref_rec n1 v1 T1) ->\n  degree_typ_wrt_varref (S n1) T1.\nProof.\npose proof degree_typ_wrt_varref_open_typ_wrt_varref_rec_inv_degree_dec_wrt_varref_open_dec_wrt_varref_rec_inv_mutual as H; intuition eauto.\nQed.\n\nHint Immediate degree_typ_wrt_varref_open_typ_wrt_varref_rec_inv : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_dec_wrt_varref_open_dec_wrt_varref_rec_inv :\nforall dec1 v1 n1,\n  degree_dec_wrt_varref n1 (open_dec_wrt_varref_rec n1 v1 dec1) ->\n  degree_dec_wrt_varref (S n1) dec1.\nProof.\npose proof degree_typ_wrt_varref_open_typ_wrt_varref_rec_inv_degree_dec_wrt_varref_open_dec_wrt_varref_rec_inv_mutual as H; intuition eauto.\nQed.\n\nHint Immediate degree_dec_wrt_varref_open_dec_wrt_varref_rec_inv : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_def_wrt_varref_open_def_wrt_varref_rec_inv_degree_defs_wrt_varref_open_defs_wrt_varref_rec_inv_degree_val_wrt_varref_open_val_wrt_varref_rec_inv_degree_trm_wrt_varref_open_trm_wrt_varref_rec_inv_mutual :\n(forall d1 v1 n1,\n  degree_def_wrt_varref n1 (open_def_wrt_varref_rec n1 v1 d1) ->\n  degree_def_wrt_varref (S n1) d1) /\\\n(forall defs1 v1 n1,\n  degree_defs_wrt_varref n1 (open_defs_wrt_varref_rec n1 v1 defs1) ->\n  degree_defs_wrt_varref (S n1) defs1) /\\\n(forall val1 v1 n1,\n  degree_val_wrt_varref n1 (open_val_wrt_varref_rec n1 v1 val1) ->\n  degree_val_wrt_varref (S n1) val1) /\\\n(forall t1 v1 n1,\n  degree_trm_wrt_varref n1 (open_trm_wrt_varref_rec n1 v1 t1) ->\n  degree_trm_wrt_varref (S n1) t1).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp; eauto with lngen.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_def_wrt_varref_open_def_wrt_varref_rec_inv :\nforall d1 v1 n1,\n  degree_def_wrt_varref n1 (open_def_wrt_varref_rec n1 v1 d1) ->\n  degree_def_wrt_varref (S n1) d1.\nProof.\npose proof degree_def_wrt_varref_open_def_wrt_varref_rec_inv_degree_defs_wrt_varref_open_defs_wrt_varref_rec_inv_degree_val_wrt_varref_open_val_wrt_varref_rec_inv_degree_trm_wrt_varref_open_trm_wrt_varref_rec_inv_mutual as H; intuition eauto.\nQed.\n\nHint Immediate degree_def_wrt_varref_open_def_wrt_varref_rec_inv : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_defs_wrt_varref_open_defs_wrt_varref_rec_inv :\nforall defs1 v1 n1,\n  degree_defs_wrt_varref n1 (open_defs_wrt_varref_rec n1 v1 defs1) ->\n  degree_defs_wrt_varref (S n1) defs1.\nProof.\npose proof degree_def_wrt_varref_open_def_wrt_varref_rec_inv_degree_defs_wrt_varref_open_defs_wrt_varref_rec_inv_degree_val_wrt_varref_open_val_wrt_varref_rec_inv_degree_trm_wrt_varref_open_trm_wrt_varref_rec_inv_mutual as H; intuition eauto.\nQed.\n\nHint Immediate degree_defs_wrt_varref_open_defs_wrt_varref_rec_inv : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_val_wrt_varref_open_val_wrt_varref_rec_inv :\nforall val1 v1 n1,\n  degree_val_wrt_varref n1 (open_val_wrt_varref_rec n1 v1 val1) ->\n  degree_val_wrt_varref (S n1) val1.\nProof.\npose proof degree_def_wrt_varref_open_def_wrt_varref_rec_inv_degree_defs_wrt_varref_open_defs_wrt_varref_rec_inv_degree_val_wrt_varref_open_val_wrt_varref_rec_inv_degree_trm_wrt_varref_open_trm_wrt_varref_rec_inv_mutual as H; intuition eauto.\nQed.\n\nHint Immediate degree_val_wrt_varref_open_val_wrt_varref_rec_inv : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_trm_wrt_varref_open_trm_wrt_varref_rec_inv :\nforall t1 v1 n1,\n  degree_trm_wrt_varref n1 (open_trm_wrt_varref_rec n1 v1 t1) ->\n  degree_trm_wrt_varref (S n1) t1.\nProof.\npose proof degree_def_wrt_varref_open_def_wrt_varref_rec_inv_degree_defs_wrt_varref_open_defs_wrt_varref_rec_inv_degree_val_wrt_varref_open_val_wrt_varref_rec_inv_degree_trm_wrt_varref_open_trm_wrt_varref_rec_inv_mutual as H; intuition eauto.\nQed.\n\nHint Immediate degree_trm_wrt_varref_open_trm_wrt_varref_rec_inv : lngen.\n\n(* end hide *)\n\nLemma degree_varref_wrt_varref_open_varref_wrt_varref_inv :\nforall v1 v2,\n  degree_varref_wrt_varref 0 (open_varref_wrt_varref v1 v2) ->\n  degree_varref_wrt_varref 1 v1.\nProof.\nunfold open_varref_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate degree_varref_wrt_varref_open_varref_wrt_varref_inv : lngen.\n\nLemma degree_typ_wrt_varref_open_typ_wrt_varref_inv :\nforall T1 v1,\n  degree_typ_wrt_varref 0 (open_typ_wrt_varref T1 v1) ->\n  degree_typ_wrt_varref 1 T1.\nProof.\nunfold open_typ_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate degree_typ_wrt_varref_open_typ_wrt_varref_inv : lngen.\n\nLemma degree_dec_wrt_varref_open_dec_wrt_varref_inv :\nforall dec1 v1,\n  degree_dec_wrt_varref 0 (open_dec_wrt_varref dec1 v1) ->\n  degree_dec_wrt_varref 1 dec1.\nProof.\nunfold open_dec_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate degree_dec_wrt_varref_open_dec_wrt_varref_inv : lngen.\n\nLemma degree_def_wrt_varref_open_def_wrt_varref_inv :\nforall d1 v1,\n  degree_def_wrt_varref 0 (open_def_wrt_varref d1 v1) ->\n  degree_def_wrt_varref 1 d1.\nProof.\nunfold open_def_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate degree_def_wrt_varref_open_def_wrt_varref_inv : lngen.\n\nLemma degree_defs_wrt_varref_open_defs_wrt_varref_inv :\nforall defs1 v1,\n  degree_defs_wrt_varref 0 (open_defs_wrt_varref defs1 v1) ->\n  degree_defs_wrt_varref 1 defs1.\nProof.\nunfold open_defs_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate degree_defs_wrt_varref_open_defs_wrt_varref_inv : lngen.\n\nLemma degree_val_wrt_varref_open_val_wrt_varref_inv :\nforall val1 v1,\n  degree_val_wrt_varref 0 (open_val_wrt_varref val1 v1) ->\n  degree_val_wrt_varref 1 val1.\nProof.\nunfold open_val_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate degree_val_wrt_varref_open_val_wrt_varref_inv : lngen.\n\nLemma degree_trm_wrt_varref_open_trm_wrt_varref_inv :\nforall t1 v1,\n  degree_trm_wrt_varref 0 (open_trm_wrt_varref t1 v1) ->\n  degree_trm_wrt_varref 1 t1.\nProof.\nunfold open_trm_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate degree_trm_wrt_varref_open_trm_wrt_varref_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_varref_wrt_varref_rec_inj_mutual :\n(forall v1 v2 x1 n1,\n  close_varref_wrt_varref_rec n1 x1 v1 = close_varref_wrt_varref_rec n1 x1 v2 ->\n  v1 = v2).\nProof.\napply_mutual_ind varref_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_varref_wrt_varref_rec_inj :\nforall v1 v2 x1 n1,\n  close_varref_wrt_varref_rec n1 x1 v1 = close_varref_wrt_varref_rec n1 x1 v2 ->\n  v1 = v2.\nProof.\npose proof close_varref_wrt_varref_rec_inj_mutual as H; intuition eauto.\nQed.\n\nHint Immediate close_varref_wrt_varref_rec_inj : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_typ_wrt_varref_rec_inj_close_dec_wrt_varref_rec_inj_mutual :\n(forall T1 T2 x1 n1,\n  close_typ_wrt_varref_rec n1 x1 T1 = close_typ_wrt_varref_rec n1 x1 T2 ->\n  T1 = T2) /\\\n(forall dec1 dec2 x1 n1,\n  close_dec_wrt_varref_rec n1 x1 dec1 = close_dec_wrt_varref_rec n1 x1 dec2 ->\n  dec1 = dec2).\nProof.\napply_mutual_ind typ_dec_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_typ_wrt_varref_rec_inj :\nforall T1 T2 x1 n1,\n  close_typ_wrt_varref_rec n1 x1 T1 = close_typ_wrt_varref_rec n1 x1 T2 ->\n  T1 = T2.\nProof.\npose proof close_typ_wrt_varref_rec_inj_close_dec_wrt_varref_rec_inj_mutual as H; intuition eauto.\nQed.\n\nHint Immediate close_typ_wrt_varref_rec_inj : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_dec_wrt_varref_rec_inj :\nforall dec1 dec2 x1 n1,\n  close_dec_wrt_varref_rec n1 x1 dec1 = close_dec_wrt_varref_rec n1 x1 dec2 ->\n  dec1 = dec2.\nProof.\npose proof close_typ_wrt_varref_rec_inj_close_dec_wrt_varref_rec_inj_mutual as H; intuition eauto.\nQed.\n\nHint Immediate close_dec_wrt_varref_rec_inj : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_def_wrt_varref_rec_inj_close_defs_wrt_varref_rec_inj_close_val_wrt_varref_rec_inj_close_trm_wrt_varref_rec_inj_mutual :\n(forall d1 d2 x1 n1,\n  close_def_wrt_varref_rec n1 x1 d1 = close_def_wrt_varref_rec n1 x1 d2 ->\n  d1 = d2) /\\\n(forall defs1 defs2 x1 n1,\n  close_defs_wrt_varref_rec n1 x1 defs1 = close_defs_wrt_varref_rec n1 x1 defs2 ->\n  defs1 = defs2) /\\\n(forall val1 val2 x1 n1,\n  close_val_wrt_varref_rec n1 x1 val1 = close_val_wrt_varref_rec n1 x1 val2 ->\n  val1 = val2) /\\\n(forall t1 t2 x1 n1,\n  close_trm_wrt_varref_rec n1 x1 t1 = close_trm_wrt_varref_rec n1 x1 t2 ->\n  t1 = t2).\nProof.\napply_mutual_ind def_defs_val_trm_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_def_wrt_varref_rec_inj :\nforall d1 d2 x1 n1,\n  close_def_wrt_varref_rec n1 x1 d1 = close_def_wrt_varref_rec n1 x1 d2 ->\n  d1 = d2.\nProof.\npose proof close_def_wrt_varref_rec_inj_close_defs_wrt_varref_rec_inj_close_val_wrt_varref_rec_inj_close_trm_wrt_varref_rec_inj_mutual as H; intuition eauto.\nQed.\n\nHint Immediate close_def_wrt_varref_rec_inj : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_defs_wrt_varref_rec_inj :\nforall defs1 defs2 x1 n1,\n  close_defs_wrt_varref_rec n1 x1 defs1 = close_defs_wrt_varref_rec n1 x1 defs2 ->\n  defs1 = defs2.\nProof.\npose proof close_def_wrt_varref_rec_inj_close_defs_wrt_varref_rec_inj_close_val_wrt_varref_rec_inj_close_trm_wrt_varref_rec_inj_mutual as H; intuition eauto.\nQed.\n\nHint Immediate close_defs_wrt_varref_rec_inj : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_val_wrt_varref_rec_inj :\nforall val1 val2 x1 n1,\n  close_val_wrt_varref_rec n1 x1 val1 = close_val_wrt_varref_rec n1 x1 val2 ->\n  val1 = val2.\nProof.\npose proof close_def_wrt_varref_rec_inj_close_defs_wrt_varref_rec_inj_close_val_wrt_varref_rec_inj_close_trm_wrt_varref_rec_inj_mutual as H; intuition eauto.\nQed.\n\nHint Immediate close_val_wrt_varref_rec_inj : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_trm_wrt_varref_rec_inj :\nforall t1 t2 x1 n1,\n  close_trm_wrt_varref_rec n1 x1 t1 = close_trm_wrt_varref_rec n1 x1 t2 ->\n  t1 = t2.\nProof.\npose proof close_def_wrt_varref_rec_inj_close_defs_wrt_varref_rec_inj_close_val_wrt_varref_rec_inj_close_trm_wrt_varref_rec_inj_mutual as H; intuition eauto.\nQed.\n\nHint Immediate close_trm_wrt_varref_rec_inj : lngen.\n\n(* end hide *)\n\nLemma close_varref_wrt_varref_inj :\nforall v1 v2 x1,\n  close_varref_wrt_varref x1 v1 = close_varref_wrt_varref x1 v2 ->\n  v1 = v2.\nProof.\nunfold close_varref_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate close_varref_wrt_varref_inj : lngen.\n\nLemma close_typ_wrt_varref_inj :\nforall T1 T2 x1,\n  close_typ_wrt_varref x1 T1 = close_typ_wrt_varref x1 T2 ->\n  T1 = T2.\nProof.\nunfold close_typ_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate close_typ_wrt_varref_inj : lngen.\n\nLemma close_dec_wrt_varref_inj :\nforall dec1 dec2 x1,\n  close_dec_wrt_varref x1 dec1 = close_dec_wrt_varref x1 dec2 ->\n  dec1 = dec2.\nProof.\nunfold close_dec_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate close_dec_wrt_varref_inj : lngen.\n\nLemma close_def_wrt_varref_inj :\nforall d1 d2 x1,\n  close_def_wrt_varref x1 d1 = close_def_wrt_varref x1 d2 ->\n  d1 = d2.\nProof.\nunfold close_def_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate close_def_wrt_varref_inj : lngen.\n\nLemma close_defs_wrt_varref_inj :\nforall defs1 defs2 x1,\n  close_defs_wrt_varref x1 defs1 = close_defs_wrt_varref x1 defs2 ->\n  defs1 = defs2.\nProof.\nunfold close_defs_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate close_defs_wrt_varref_inj : lngen.\n\nLemma close_val_wrt_varref_inj :\nforall val1 val2 x1,\n  close_val_wrt_varref x1 val1 = close_val_wrt_varref x1 val2 ->\n  val1 = val2.\nProof.\nunfold close_val_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate close_val_wrt_varref_inj : lngen.\n\nLemma close_trm_wrt_varref_inj :\nforall t1 t2 x1,\n  close_trm_wrt_varref x1 t1 = close_trm_wrt_varref x1 t2 ->\n  t1 = t2.\nProof.\nunfold close_trm_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate close_trm_wrt_varref_inj : lngen.\n\n(* begin hide *)\n\nLemma close_varref_wrt_varref_rec_open_varref_wrt_varref_rec_mutual :\n(forall v1 x1 n1,\n  x1 `notin` fv_varref v1 ->\n  close_varref_wrt_varref_rec n1 x1 (open_varref_wrt_varref_rec n1 (var_termvar_f x1) v1) = v1).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_varref_wrt_varref_rec_open_varref_wrt_varref_rec :\nforall v1 x1 n1,\n  x1 `notin` fv_varref v1 ->\n  close_varref_wrt_varref_rec n1 x1 (open_varref_wrt_varref_rec n1 (var_termvar_f x1) v1) = v1.\nProof.\npose proof close_varref_wrt_varref_rec_open_varref_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve close_varref_wrt_varref_rec_open_varref_wrt_varref_rec : lngen.\nHint Rewrite close_varref_wrt_varref_rec_open_varref_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_typ_wrt_varref_rec_open_typ_wrt_varref_rec_close_dec_wrt_varref_rec_open_dec_wrt_varref_rec_mutual :\n(forall T1 x1 n1,\n  x1 `notin` fv_typ T1 ->\n  close_typ_wrt_varref_rec n1 x1 (open_typ_wrt_varref_rec n1 (var_termvar_f x1) T1) = T1) /\\\n(forall dec1 x1 n1,\n  x1 `notin` fv_dec dec1 ->\n  close_dec_wrt_varref_rec n1 x1 (open_dec_wrt_varref_rec n1 (var_termvar_f x1) dec1) = dec1).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_typ_wrt_varref_rec_open_typ_wrt_varref_rec :\nforall T1 x1 n1,\n  x1 `notin` fv_typ T1 ->\n  close_typ_wrt_varref_rec n1 x1 (open_typ_wrt_varref_rec n1 (var_termvar_f x1) T1) = T1.\nProof.\npose proof close_typ_wrt_varref_rec_open_typ_wrt_varref_rec_close_dec_wrt_varref_rec_open_dec_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve close_typ_wrt_varref_rec_open_typ_wrt_varref_rec : lngen.\nHint Rewrite close_typ_wrt_varref_rec_open_typ_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_dec_wrt_varref_rec_open_dec_wrt_varref_rec :\nforall dec1 x1 n1,\n  x1 `notin` fv_dec dec1 ->\n  close_dec_wrt_varref_rec n1 x1 (open_dec_wrt_varref_rec n1 (var_termvar_f x1) dec1) = dec1.\nProof.\npose proof close_typ_wrt_varref_rec_open_typ_wrt_varref_rec_close_dec_wrt_varref_rec_open_dec_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve close_dec_wrt_varref_rec_open_dec_wrt_varref_rec : lngen.\nHint Rewrite close_dec_wrt_varref_rec_open_dec_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_def_wrt_varref_rec_open_def_wrt_varref_rec_close_defs_wrt_varref_rec_open_defs_wrt_varref_rec_close_val_wrt_varref_rec_open_val_wrt_varref_rec_close_trm_wrt_varref_rec_open_trm_wrt_varref_rec_mutual :\n(forall d1 x1 n1,\n  x1 `notin` fv_def d1 ->\n  close_def_wrt_varref_rec n1 x1 (open_def_wrt_varref_rec n1 (var_termvar_f x1) d1) = d1) /\\\n(forall defs1 x1 n1,\n  x1 `notin` fv_defs defs1 ->\n  close_defs_wrt_varref_rec n1 x1 (open_defs_wrt_varref_rec n1 (var_termvar_f x1) defs1) = defs1) /\\\n(forall val1 x1 n1,\n  x1 `notin` fv_val val1 ->\n  close_val_wrt_varref_rec n1 x1 (open_val_wrt_varref_rec n1 (var_termvar_f x1) val1) = val1) /\\\n(forall t1 x1 n1,\n  x1 `notin` fv_trm t1 ->\n  close_trm_wrt_varref_rec n1 x1 (open_trm_wrt_varref_rec n1 (var_termvar_f x1) t1) = t1).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_def_wrt_varref_rec_open_def_wrt_varref_rec :\nforall d1 x1 n1,\n  x1 `notin` fv_def d1 ->\n  close_def_wrt_varref_rec n1 x1 (open_def_wrt_varref_rec n1 (var_termvar_f x1) d1) = d1.\nProof.\npose proof close_def_wrt_varref_rec_open_def_wrt_varref_rec_close_defs_wrt_varref_rec_open_defs_wrt_varref_rec_close_val_wrt_varref_rec_open_val_wrt_varref_rec_close_trm_wrt_varref_rec_open_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve close_def_wrt_varref_rec_open_def_wrt_varref_rec : lngen.\nHint Rewrite close_def_wrt_varref_rec_open_def_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_defs_wrt_varref_rec_open_defs_wrt_varref_rec :\nforall defs1 x1 n1,\n  x1 `notin` fv_defs defs1 ->\n  close_defs_wrt_varref_rec n1 x1 (open_defs_wrt_varref_rec n1 (var_termvar_f x1) defs1) = defs1.\nProof.\npose proof close_def_wrt_varref_rec_open_def_wrt_varref_rec_close_defs_wrt_varref_rec_open_defs_wrt_varref_rec_close_val_wrt_varref_rec_open_val_wrt_varref_rec_close_trm_wrt_varref_rec_open_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve close_defs_wrt_varref_rec_open_defs_wrt_varref_rec : lngen.\nHint Rewrite close_defs_wrt_varref_rec_open_defs_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_val_wrt_varref_rec_open_val_wrt_varref_rec :\nforall val1 x1 n1,\n  x1 `notin` fv_val val1 ->\n  close_val_wrt_varref_rec n1 x1 (open_val_wrt_varref_rec n1 (var_termvar_f x1) val1) = val1.\nProof.\npose proof close_def_wrt_varref_rec_open_def_wrt_varref_rec_close_defs_wrt_varref_rec_open_defs_wrt_varref_rec_close_val_wrt_varref_rec_open_val_wrt_varref_rec_close_trm_wrt_varref_rec_open_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve close_val_wrt_varref_rec_open_val_wrt_varref_rec : lngen.\nHint Rewrite close_val_wrt_varref_rec_open_val_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_trm_wrt_varref_rec_open_trm_wrt_varref_rec :\nforall t1 x1 n1,\n  x1 `notin` fv_trm t1 ->\n  close_trm_wrt_varref_rec n1 x1 (open_trm_wrt_varref_rec n1 (var_termvar_f x1) t1) = t1.\nProof.\npose proof close_def_wrt_varref_rec_open_def_wrt_varref_rec_close_defs_wrt_varref_rec_open_defs_wrt_varref_rec_close_val_wrt_varref_rec_open_val_wrt_varref_rec_close_trm_wrt_varref_rec_open_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve close_trm_wrt_varref_rec_open_trm_wrt_varref_rec : lngen.\nHint Rewrite close_trm_wrt_varref_rec_open_trm_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\nLemma close_varref_wrt_varref_open_varref_wrt_varref :\nforall v1 x1,\n  x1 `notin` fv_varref v1 ->\n  close_varref_wrt_varref x1 (open_varref_wrt_varref v1 (var_termvar_f x1)) = v1.\nProof.\nunfold close_varref_wrt_varref; unfold open_varref_wrt_varref; default_simp.\nQed.\n\nHint Resolve close_varref_wrt_varref_open_varref_wrt_varref : lngen.\nHint Rewrite close_varref_wrt_varref_open_varref_wrt_varref using solve [auto] : lngen.\n\nLemma close_typ_wrt_varref_open_typ_wrt_varref :\nforall T1 x1,\n  x1 `notin` fv_typ T1 ->\n  close_typ_wrt_varref x1 (open_typ_wrt_varref T1 (var_termvar_f x1)) = T1.\nProof.\nunfold close_typ_wrt_varref; unfold open_typ_wrt_varref; default_simp.\nQed.\n\nHint Resolve close_typ_wrt_varref_open_typ_wrt_varref : lngen.\nHint Rewrite close_typ_wrt_varref_open_typ_wrt_varref using solve [auto] : lngen.\n\nLemma close_dec_wrt_varref_open_dec_wrt_varref :\nforall dec1 x1,\n  x1 `notin` fv_dec dec1 ->\n  close_dec_wrt_varref x1 (open_dec_wrt_varref dec1 (var_termvar_f x1)) = dec1.\nProof.\nunfold close_dec_wrt_varref; unfold open_dec_wrt_varref; default_simp.\nQed.\n\nHint Resolve close_dec_wrt_varref_open_dec_wrt_varref : lngen.\nHint Rewrite close_dec_wrt_varref_open_dec_wrt_varref using solve [auto] : lngen.\n\nLemma close_def_wrt_varref_open_def_wrt_varref :\nforall d1 x1,\n  x1 `notin` fv_def d1 ->\n  close_def_wrt_varref x1 (open_def_wrt_varref d1 (var_termvar_f x1)) = d1.\nProof.\nunfold close_def_wrt_varref; unfold open_def_wrt_varref; default_simp.\nQed.\n\nHint Resolve close_def_wrt_varref_open_def_wrt_varref : lngen.\nHint Rewrite close_def_wrt_varref_open_def_wrt_varref using solve [auto] : lngen.\n\nLemma close_defs_wrt_varref_open_defs_wrt_varref :\nforall defs1 x1,\n  x1 `notin` fv_defs defs1 ->\n  close_defs_wrt_varref x1 (open_defs_wrt_varref defs1 (var_termvar_f x1)) = defs1.\nProof.\nunfold close_defs_wrt_varref; unfold open_defs_wrt_varref; default_simp.\nQed.\n\nHint Resolve close_defs_wrt_varref_open_defs_wrt_varref : lngen.\nHint Rewrite close_defs_wrt_varref_open_defs_wrt_varref using solve [auto] : lngen.\n\nLemma close_val_wrt_varref_open_val_wrt_varref :\nforall val1 x1,\n  x1 `notin` fv_val val1 ->\n  close_val_wrt_varref x1 (open_val_wrt_varref val1 (var_termvar_f x1)) = val1.\nProof.\nunfold close_val_wrt_varref; unfold open_val_wrt_varref; default_simp.\nQed.\n\nHint Resolve close_val_wrt_varref_open_val_wrt_varref : lngen.\nHint Rewrite close_val_wrt_varref_open_val_wrt_varref using solve [auto] : lngen.\n\nLemma close_trm_wrt_varref_open_trm_wrt_varref :\nforall t1 x1,\n  x1 `notin` fv_trm t1 ->\n  close_trm_wrt_varref x1 (open_trm_wrt_varref t1 (var_termvar_f x1)) = t1.\nProof.\nunfold close_trm_wrt_varref; unfold open_trm_wrt_varref; default_simp.\nQed.\n\nHint Resolve close_trm_wrt_varref_open_trm_wrt_varref : lngen.\nHint Rewrite close_trm_wrt_varref_open_trm_wrt_varref using solve [auto] : lngen.\n\n(* begin hide *)\n\nLemma open_varref_wrt_varref_rec_close_varref_wrt_varref_rec_mutual :\n(forall v1 x1 n1,\n  open_varref_wrt_varref_rec n1 (var_termvar_f x1) (close_varref_wrt_varref_rec n1 x1 v1) = v1).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_varref_wrt_varref_rec_close_varref_wrt_varref_rec :\nforall v1 x1 n1,\n  open_varref_wrt_varref_rec n1 (var_termvar_f x1) (close_varref_wrt_varref_rec n1 x1 v1) = v1.\nProof.\npose proof open_varref_wrt_varref_rec_close_varref_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve open_varref_wrt_varref_rec_close_varref_wrt_varref_rec : lngen.\nHint Rewrite open_varref_wrt_varref_rec_close_varref_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_typ_wrt_varref_rec_close_typ_wrt_varref_rec_open_dec_wrt_varref_rec_close_dec_wrt_varref_rec_mutual :\n(forall T1 x1 n1,\n  open_typ_wrt_varref_rec n1 (var_termvar_f x1) (close_typ_wrt_varref_rec n1 x1 T1) = T1) /\\\n(forall dec1 x1 n1,\n  open_dec_wrt_varref_rec n1 (var_termvar_f x1) (close_dec_wrt_varref_rec n1 x1 dec1) = dec1).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_typ_wrt_varref_rec_close_typ_wrt_varref_rec :\nforall T1 x1 n1,\n  open_typ_wrt_varref_rec n1 (var_termvar_f x1) (close_typ_wrt_varref_rec n1 x1 T1) = T1.\nProof.\npose proof open_typ_wrt_varref_rec_close_typ_wrt_varref_rec_open_dec_wrt_varref_rec_close_dec_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve open_typ_wrt_varref_rec_close_typ_wrt_varref_rec : lngen.\nHint Rewrite open_typ_wrt_varref_rec_close_typ_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_dec_wrt_varref_rec_close_dec_wrt_varref_rec :\nforall dec1 x1 n1,\n  open_dec_wrt_varref_rec n1 (var_termvar_f x1) (close_dec_wrt_varref_rec n1 x1 dec1) = dec1.\nProof.\npose proof open_typ_wrt_varref_rec_close_typ_wrt_varref_rec_open_dec_wrt_varref_rec_close_dec_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve open_dec_wrt_varref_rec_close_dec_wrt_varref_rec : lngen.\nHint Rewrite open_dec_wrt_varref_rec_close_dec_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_def_wrt_varref_rec_close_def_wrt_varref_rec_open_defs_wrt_varref_rec_close_defs_wrt_varref_rec_open_val_wrt_varref_rec_close_val_wrt_varref_rec_open_trm_wrt_varref_rec_close_trm_wrt_varref_rec_mutual :\n(forall d1 x1 n1,\n  open_def_wrt_varref_rec n1 (var_termvar_f x1) (close_def_wrt_varref_rec n1 x1 d1) = d1) /\\\n(forall defs1 x1 n1,\n  open_defs_wrt_varref_rec n1 (var_termvar_f x1) (close_defs_wrt_varref_rec n1 x1 defs1) = defs1) /\\\n(forall val1 x1 n1,\n  open_val_wrt_varref_rec n1 (var_termvar_f x1) (close_val_wrt_varref_rec n1 x1 val1) = val1) /\\\n(forall t1 x1 n1,\n  open_trm_wrt_varref_rec n1 (var_termvar_f x1) (close_trm_wrt_varref_rec n1 x1 t1) = t1).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_def_wrt_varref_rec_close_def_wrt_varref_rec :\nforall d1 x1 n1,\n  open_def_wrt_varref_rec n1 (var_termvar_f x1) (close_def_wrt_varref_rec n1 x1 d1) = d1.\nProof.\npose proof open_def_wrt_varref_rec_close_def_wrt_varref_rec_open_defs_wrt_varref_rec_close_defs_wrt_varref_rec_open_val_wrt_varref_rec_close_val_wrt_varref_rec_open_trm_wrt_varref_rec_close_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve open_def_wrt_varref_rec_close_def_wrt_varref_rec : lngen.\nHint Rewrite open_def_wrt_varref_rec_close_def_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_defs_wrt_varref_rec_close_defs_wrt_varref_rec :\nforall defs1 x1 n1,\n  open_defs_wrt_varref_rec n1 (var_termvar_f x1) (close_defs_wrt_varref_rec n1 x1 defs1) = defs1.\nProof.\npose proof open_def_wrt_varref_rec_close_def_wrt_varref_rec_open_defs_wrt_varref_rec_close_defs_wrt_varref_rec_open_val_wrt_varref_rec_close_val_wrt_varref_rec_open_trm_wrt_varref_rec_close_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve open_defs_wrt_varref_rec_close_defs_wrt_varref_rec : lngen.\nHint Rewrite open_defs_wrt_varref_rec_close_defs_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_val_wrt_varref_rec_close_val_wrt_varref_rec :\nforall val1 x1 n1,\n  open_val_wrt_varref_rec n1 (var_termvar_f x1) (close_val_wrt_varref_rec n1 x1 val1) = val1.\nProof.\npose proof open_def_wrt_varref_rec_close_def_wrt_varref_rec_open_defs_wrt_varref_rec_close_defs_wrt_varref_rec_open_val_wrt_varref_rec_close_val_wrt_varref_rec_open_trm_wrt_varref_rec_close_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve open_val_wrt_varref_rec_close_val_wrt_varref_rec : lngen.\nHint Rewrite open_val_wrt_varref_rec_close_val_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_trm_wrt_varref_rec_close_trm_wrt_varref_rec :\nforall t1 x1 n1,\n  open_trm_wrt_varref_rec n1 (var_termvar_f x1) (close_trm_wrt_varref_rec n1 x1 t1) = t1.\nProof.\npose proof open_def_wrt_varref_rec_close_def_wrt_varref_rec_open_defs_wrt_varref_rec_close_defs_wrt_varref_rec_open_val_wrt_varref_rec_close_val_wrt_varref_rec_open_trm_wrt_varref_rec_close_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve open_trm_wrt_varref_rec_close_trm_wrt_varref_rec : lngen.\nHint Rewrite open_trm_wrt_varref_rec_close_trm_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\nLemma open_varref_wrt_varref_close_varref_wrt_varref :\nforall v1 x1,\n  open_varref_wrt_varref (close_varref_wrt_varref x1 v1) (var_termvar_f x1) = v1.\nProof.\nunfold close_varref_wrt_varref; unfold open_varref_wrt_varref; default_simp.\nQed.\n\nHint Resolve open_varref_wrt_varref_close_varref_wrt_varref : lngen.\nHint Rewrite open_varref_wrt_varref_close_varref_wrt_varref using solve [auto] : lngen.\n\nLemma open_typ_wrt_varref_close_typ_wrt_varref :\nforall T1 x1,\n  open_typ_wrt_varref (close_typ_wrt_varref x1 T1) (var_termvar_f x1) = T1.\nProof.\nunfold close_typ_wrt_varref; unfold open_typ_wrt_varref; default_simp.\nQed.\n\nHint Resolve open_typ_wrt_varref_close_typ_wrt_varref : lngen.\nHint Rewrite open_typ_wrt_varref_close_typ_wrt_varref using solve [auto] : lngen.\n\nLemma open_dec_wrt_varref_close_dec_wrt_varref :\nforall dec1 x1,\n  open_dec_wrt_varref (close_dec_wrt_varref x1 dec1) (var_termvar_f x1) = dec1.\nProof.\nunfold close_dec_wrt_varref; unfold open_dec_wrt_varref; default_simp.\nQed.\n\nHint Resolve open_dec_wrt_varref_close_dec_wrt_varref : lngen.\nHint Rewrite open_dec_wrt_varref_close_dec_wrt_varref using solve [auto] : lngen.\n\nLemma open_def_wrt_varref_close_def_wrt_varref :\nforall d1 x1,\n  open_def_wrt_varref (close_def_wrt_varref x1 d1) (var_termvar_f x1) = d1.\nProof.\nunfold close_def_wrt_varref; unfold open_def_wrt_varref; default_simp.\nQed.\n\nHint Resolve open_def_wrt_varref_close_def_wrt_varref : lngen.\nHint Rewrite open_def_wrt_varref_close_def_wrt_varref using solve [auto] : lngen.\n\nLemma open_defs_wrt_varref_close_defs_wrt_varref :\nforall defs1 x1,\n  open_defs_wrt_varref (close_defs_wrt_varref x1 defs1) (var_termvar_f x1) = defs1.\nProof.\nunfold close_defs_wrt_varref; unfold open_defs_wrt_varref; default_simp.\nQed.\n\nHint Resolve open_defs_wrt_varref_close_defs_wrt_varref : lngen.\nHint Rewrite open_defs_wrt_varref_close_defs_wrt_varref using solve [auto] : lngen.\n\nLemma open_val_wrt_varref_close_val_wrt_varref :\nforall val1 x1,\n  open_val_wrt_varref (close_val_wrt_varref x1 val1) (var_termvar_f x1) = val1.\nProof.\nunfold close_val_wrt_varref; unfold open_val_wrt_varref; default_simp.\nQed.\n\nHint Resolve open_val_wrt_varref_close_val_wrt_varref : lngen.\nHint Rewrite open_val_wrt_varref_close_val_wrt_varref using solve [auto] : lngen.\n\nLemma open_trm_wrt_varref_close_trm_wrt_varref :\nforall t1 x1,\n  open_trm_wrt_varref (close_trm_wrt_varref x1 t1) (var_termvar_f x1) = t1.\nProof.\nunfold close_trm_wrt_varref; unfold open_trm_wrt_varref; default_simp.\nQed.\n\nHint Resolve open_trm_wrt_varref_close_trm_wrt_varref : lngen.\nHint Rewrite open_trm_wrt_varref_close_trm_wrt_varref using solve [auto] : lngen.\n\n(* begin hide *)\n\nLemma open_varref_wrt_varref_rec_inj_mutual :\n(forall v2 v1 x1 n1,\n  x1 `notin` fv_varref v2 ->\n  x1 `notin` fv_varref v1 ->\n  open_varref_wrt_varref_rec n1 (var_termvar_f x1) v2 = open_varref_wrt_varref_rec n1 (var_termvar_f x1) v1 ->\n  v2 = v1).\nProof.\napply_mutual_ind varref_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_varref_wrt_varref_rec_inj :\nforall v2 v1 x1 n1,\n  x1 `notin` fv_varref v2 ->\n  x1 `notin` fv_varref v1 ->\n  open_varref_wrt_varref_rec n1 (var_termvar_f x1) v2 = open_varref_wrt_varref_rec n1 (var_termvar_f x1) v1 ->\n  v2 = v1.\nProof.\npose proof open_varref_wrt_varref_rec_inj_mutual as H; intuition eauto.\nQed.\n\nHint Immediate open_varref_wrt_varref_rec_inj : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_typ_wrt_varref_rec_inj_open_dec_wrt_varref_rec_inj_mutual :\n(forall T2 T1 x1 n1,\n  x1 `notin` fv_typ T2 ->\n  x1 `notin` fv_typ T1 ->\n  open_typ_wrt_varref_rec n1 (var_termvar_f x1) T2 = open_typ_wrt_varref_rec n1 (var_termvar_f x1) T1 ->\n  T2 = T1) /\\\n(forall dec2 dec1 x1 n1,\n  x1 `notin` fv_dec dec2 ->\n  x1 `notin` fv_dec dec1 ->\n  open_dec_wrt_varref_rec n1 (var_termvar_f x1) dec2 = open_dec_wrt_varref_rec n1 (var_termvar_f x1) dec1 ->\n  dec2 = dec1).\nProof.\napply_mutual_ind typ_dec_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_typ_wrt_varref_rec_inj :\nforall T2 T1 x1 n1,\n  x1 `notin` fv_typ T2 ->\n  x1 `notin` fv_typ T1 ->\n  open_typ_wrt_varref_rec n1 (var_termvar_f x1) T2 = open_typ_wrt_varref_rec n1 (var_termvar_f x1) T1 ->\n  T2 = T1.\nProof.\npose proof open_typ_wrt_varref_rec_inj_open_dec_wrt_varref_rec_inj_mutual as H; intuition eauto.\nQed.\n\nHint Immediate open_typ_wrt_varref_rec_inj : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_dec_wrt_varref_rec_inj :\nforall dec2 dec1 x1 n1,\n  x1 `notin` fv_dec dec2 ->\n  x1 `notin` fv_dec dec1 ->\n  open_dec_wrt_varref_rec n1 (var_termvar_f x1) dec2 = open_dec_wrt_varref_rec n1 (var_termvar_f x1) dec1 ->\n  dec2 = dec1.\nProof.\npose proof open_typ_wrt_varref_rec_inj_open_dec_wrt_varref_rec_inj_mutual as H; intuition eauto.\nQed.\n\nHint Immediate open_dec_wrt_varref_rec_inj : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_def_wrt_varref_rec_inj_open_defs_wrt_varref_rec_inj_open_val_wrt_varref_rec_inj_open_trm_wrt_varref_rec_inj_mutual :\n(forall d2 d1 x1 n1,\n  x1 `notin` fv_def d2 ->\n  x1 `notin` fv_def d1 ->\n  open_def_wrt_varref_rec n1 (var_termvar_f x1) d2 = open_def_wrt_varref_rec n1 (var_termvar_f x1) d1 ->\n  d2 = d1) /\\\n(forall defs2 defs1 x1 n1,\n  x1 `notin` fv_defs defs2 ->\n  x1 `notin` fv_defs defs1 ->\n  open_defs_wrt_varref_rec n1 (var_termvar_f x1) defs2 = open_defs_wrt_varref_rec n1 (var_termvar_f x1) defs1 ->\n  defs2 = defs1) /\\\n(forall val2 val1 x1 n1,\n  x1 `notin` fv_val val2 ->\n  x1 `notin` fv_val val1 ->\n  open_val_wrt_varref_rec n1 (var_termvar_f x1) val2 = open_val_wrt_varref_rec n1 (var_termvar_f x1) val1 ->\n  val2 = val1) /\\\n(forall t2 t1 x1 n1,\n  x1 `notin` fv_trm t2 ->\n  x1 `notin` fv_trm t1 ->\n  open_trm_wrt_varref_rec n1 (var_termvar_f x1) t2 = open_trm_wrt_varref_rec n1 (var_termvar_f x1) t1 ->\n  t2 = t1).\nProof.\napply_mutual_ind def_defs_val_trm_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_def_wrt_varref_rec_inj :\nforall d2 d1 x1 n1,\n  x1 `notin` fv_def d2 ->\n  x1 `notin` fv_def d1 ->\n  open_def_wrt_varref_rec n1 (var_termvar_f x1) d2 = open_def_wrt_varref_rec n1 (var_termvar_f x1) d1 ->\n  d2 = d1.\nProof.\npose proof open_def_wrt_varref_rec_inj_open_defs_wrt_varref_rec_inj_open_val_wrt_varref_rec_inj_open_trm_wrt_varref_rec_inj_mutual as H; intuition eauto.\nQed.\n\nHint Immediate open_def_wrt_varref_rec_inj : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_defs_wrt_varref_rec_inj :\nforall defs2 defs1 x1 n1,\n  x1 `notin` fv_defs defs2 ->\n  x1 `notin` fv_defs defs1 ->\n  open_defs_wrt_varref_rec n1 (var_termvar_f x1) defs2 = open_defs_wrt_varref_rec n1 (var_termvar_f x1) defs1 ->\n  defs2 = defs1.\nProof.\npose proof open_def_wrt_varref_rec_inj_open_defs_wrt_varref_rec_inj_open_val_wrt_varref_rec_inj_open_trm_wrt_varref_rec_inj_mutual as H; intuition eauto.\nQed.\n\nHint Immediate open_defs_wrt_varref_rec_inj : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_val_wrt_varref_rec_inj :\nforall val2 val1 x1 n1,\n  x1 `notin` fv_val val2 ->\n  x1 `notin` fv_val val1 ->\n  open_val_wrt_varref_rec n1 (var_termvar_f x1) val2 = open_val_wrt_varref_rec n1 (var_termvar_f x1) val1 ->\n  val2 = val1.\nProof.\npose proof open_def_wrt_varref_rec_inj_open_defs_wrt_varref_rec_inj_open_val_wrt_varref_rec_inj_open_trm_wrt_varref_rec_inj_mutual as H; intuition eauto.\nQed.\n\nHint Immediate open_val_wrt_varref_rec_inj : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_trm_wrt_varref_rec_inj :\nforall t2 t1 x1 n1,\n  x1 `notin` fv_trm t2 ->\n  x1 `notin` fv_trm t1 ->\n  open_trm_wrt_varref_rec n1 (var_termvar_f x1) t2 = open_trm_wrt_varref_rec n1 (var_termvar_f x1) t1 ->\n  t2 = t1.\nProof.\npose proof open_def_wrt_varref_rec_inj_open_defs_wrt_varref_rec_inj_open_val_wrt_varref_rec_inj_open_trm_wrt_varref_rec_inj_mutual as H; intuition eauto.\nQed.\n\nHint Immediate open_trm_wrt_varref_rec_inj : lngen.\n\n(* end hide *)\n\nLemma open_varref_wrt_varref_inj :\nforall v2 v1 x1,\n  x1 `notin` fv_varref v2 ->\n  x1 `notin` fv_varref v1 ->\n  open_varref_wrt_varref v2 (var_termvar_f x1) = open_varref_wrt_varref v1 (var_termvar_f x1) ->\n  v2 = v1.\nProof.\nunfold open_varref_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate open_varref_wrt_varref_inj : lngen.\n\nLemma open_typ_wrt_varref_inj :\nforall T2 T1 x1,\n  x1 `notin` fv_typ T2 ->\n  x1 `notin` fv_typ T1 ->\n  open_typ_wrt_varref T2 (var_termvar_f x1) = open_typ_wrt_varref T1 (var_termvar_f x1) ->\n  T2 = T1.\nProof.\nunfold open_typ_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate open_typ_wrt_varref_inj : lngen.\n\nLemma open_dec_wrt_varref_inj :\nforall dec2 dec1 x1,\n  x1 `notin` fv_dec dec2 ->\n  x1 `notin` fv_dec dec1 ->\n  open_dec_wrt_varref dec2 (var_termvar_f x1) = open_dec_wrt_varref dec1 (var_termvar_f x1) ->\n  dec2 = dec1.\nProof.\nunfold open_dec_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate open_dec_wrt_varref_inj : lngen.\n\nLemma open_def_wrt_varref_inj :\nforall d2 d1 x1,\n  x1 `notin` fv_def d2 ->\n  x1 `notin` fv_def d1 ->\n  open_def_wrt_varref d2 (var_termvar_f x1) = open_def_wrt_varref d1 (var_termvar_f x1) ->\n  d2 = d1.\nProof.\nunfold open_def_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate open_def_wrt_varref_inj : lngen.\n\nLemma open_defs_wrt_varref_inj :\nforall defs2 defs1 x1,\n  x1 `notin` fv_defs defs2 ->\n  x1 `notin` fv_defs defs1 ->\n  open_defs_wrt_varref defs2 (var_termvar_f x1) = open_defs_wrt_varref defs1 (var_termvar_f x1) ->\n  defs2 = defs1.\nProof.\nunfold open_defs_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate open_defs_wrt_varref_inj : lngen.\n\nLemma open_val_wrt_varref_inj :\nforall val2 val1 x1,\n  x1 `notin` fv_val val2 ->\n  x1 `notin` fv_val val1 ->\n  open_val_wrt_varref val2 (var_termvar_f x1) = open_val_wrt_varref val1 (var_termvar_f x1) ->\n  val2 = val1.\nProof.\nunfold open_val_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate open_val_wrt_varref_inj : lngen.\n\nLemma open_trm_wrt_varref_inj :\nforall t2 t1 x1,\n  x1 `notin` fv_trm t2 ->\n  x1 `notin` fv_trm t1 ->\n  open_trm_wrt_varref t2 (var_termvar_f x1) = open_trm_wrt_varref t1 (var_termvar_f x1) ->\n  t2 = t1.\nProof.\nunfold open_trm_wrt_varref; eauto with lngen.\nQed.\n\nHint Immediate open_trm_wrt_varref_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_varref_wrt_varref_of_lc_varref_mutual :\n(forall v1,\n  lc_varref v1 ->\n  degree_varref_wrt_varref 0 v1).\nProof.\napply_mutual_ind lc_varref_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_varref_wrt_varref_of_lc_varref :\nforall v1,\n  lc_varref v1 ->\n  degree_varref_wrt_varref 0 v1.\nProof.\npose proof degree_varref_wrt_varref_of_lc_varref_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_varref_wrt_varref_of_lc_varref : lngen.\n\n(* begin hide *)\n\nLemma degree_typ_wrt_varref_of_lc_typ_degree_dec_wrt_varref_of_lc_dec_mutual :\n(forall T1,\n  lc_typ T1 ->\n  degree_typ_wrt_varref 0 T1) /\\\n(forall dec1,\n  lc_dec dec1 ->\n  degree_dec_wrt_varref 0 dec1).\nProof.\napply_mutual_ind lc_typ_lc_dec_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_typ_wrt_varref_of_lc_typ :\nforall T1,\n  lc_typ T1 ->\n  degree_typ_wrt_varref 0 T1.\nProof.\npose proof degree_typ_wrt_varref_of_lc_typ_degree_dec_wrt_varref_of_lc_dec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_typ_wrt_varref_of_lc_typ : lngen.\n\nLemma degree_dec_wrt_varref_of_lc_dec :\nforall dec1,\n  lc_dec dec1 ->\n  degree_dec_wrt_varref 0 dec1.\nProof.\npose proof degree_typ_wrt_varref_of_lc_typ_degree_dec_wrt_varref_of_lc_dec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_dec_wrt_varref_of_lc_dec : lngen.\n\n(* begin hide *)\n\nLemma degree_def_wrt_varref_of_lc_def_degree_defs_wrt_varref_of_lc_defs_degree_val_wrt_varref_of_lc_val_degree_trm_wrt_varref_of_lc_trm_mutual :\n(forall d1,\n  lc_def d1 ->\n  degree_def_wrt_varref 0 d1) /\\\n(forall defs1,\n  lc_defs defs1 ->\n  degree_defs_wrt_varref 0 defs1) /\\\n(forall val1,\n  lc_val val1 ->\n  degree_val_wrt_varref 0 val1) /\\\n(forall t1,\n  lc_trm t1 ->\n  degree_trm_wrt_varref 0 t1).\nProof.\napply_mutual_ind lc_def_lc_defs_lc_val_lc_trm_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_def_wrt_varref_of_lc_def :\nforall d1,\n  lc_def d1 ->\n  degree_def_wrt_varref 0 d1.\nProof.\npose proof degree_def_wrt_varref_of_lc_def_degree_defs_wrt_varref_of_lc_defs_degree_val_wrt_varref_of_lc_val_degree_trm_wrt_varref_of_lc_trm_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_def_wrt_varref_of_lc_def : lngen.\n\nLemma degree_defs_wrt_varref_of_lc_defs :\nforall defs1,\n  lc_defs defs1 ->\n  degree_defs_wrt_varref 0 defs1.\nProof.\npose proof degree_def_wrt_varref_of_lc_def_degree_defs_wrt_varref_of_lc_defs_degree_val_wrt_varref_of_lc_val_degree_trm_wrt_varref_of_lc_trm_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_defs_wrt_varref_of_lc_defs : lngen.\n\nLemma degree_val_wrt_varref_of_lc_val :\nforall val1,\n  lc_val val1 ->\n  degree_val_wrt_varref 0 val1.\nProof.\npose proof degree_def_wrt_varref_of_lc_def_degree_defs_wrt_varref_of_lc_defs_degree_val_wrt_varref_of_lc_val_degree_trm_wrt_varref_of_lc_trm_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_val_wrt_varref_of_lc_val : lngen.\n\nLemma degree_trm_wrt_varref_of_lc_trm :\nforall t1,\n  lc_trm t1 ->\n  degree_trm_wrt_varref 0 t1.\nProof.\npose proof degree_def_wrt_varref_of_lc_def_degree_defs_wrt_varref_of_lc_defs_degree_val_wrt_varref_of_lc_val_degree_trm_wrt_varref_of_lc_trm_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_trm_wrt_varref_of_lc_trm : lngen.\n\n(* begin hide *)\n\nLemma lc_varref_of_degree_size_mutual :\nforall i1,\n(forall v1,\n  size_varref v1 = i1 ->\n  degree_varref_wrt_varref 0 v1 ->\n  lc_varref v1).\nProof.\nintros i1; pattern i1; apply lt_wf_rec;\nclear i1; intros i1 H1;\napply_mutual_ind varref_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_varref_of_degree :\nforall v1,\n  degree_varref_wrt_varref 0 v1 ->\n  lc_varref v1.\nProof.\nintros v1; intros;\npose proof (lc_varref_of_degree_size_mutual (size_varref v1));\nintuition eauto.\nQed.\n\nHint Resolve lc_varref_of_degree : lngen.\n\n(* begin hide *)\n\nLemma lc_typ_of_degree_lc_dec_of_degree_size_mutual :\nforall i1,\n(forall T1,\n  size_typ T1 = i1 ->\n  degree_typ_wrt_varref 0 T1 ->\n  lc_typ T1) /\\\n(forall dec1,\n  size_dec dec1 = i1 ->\n  degree_dec_wrt_varref 0 dec1 ->\n  lc_dec dec1).\nProof.\nintros i1; pattern i1; apply lt_wf_rec;\nclear i1; intros i1 H1;\napply_mutual_ind typ_dec_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_typ_of_degree :\nforall T1,\n  degree_typ_wrt_varref 0 T1 ->\n  lc_typ T1.\nProof.\nintros T1; intros;\npose proof (lc_typ_of_degree_lc_dec_of_degree_size_mutual (size_typ T1));\nintuition eauto.\nQed.\n\nHint Resolve lc_typ_of_degree : lngen.\n\nLemma lc_dec_of_degree :\nforall dec1,\n  degree_dec_wrt_varref 0 dec1 ->\n  lc_dec dec1.\nProof.\nintros dec1; intros;\npose proof (lc_typ_of_degree_lc_dec_of_degree_size_mutual (size_dec dec1));\nintuition eauto.\nQed.\n\nHint Resolve lc_dec_of_degree : lngen.\n\n(* begin hide *)\n\nLemma lc_def_of_degree_lc_defs_of_degree_lc_val_of_degree_lc_trm_of_degree_size_mutual :\nforall i1,\n(forall d1,\n  size_def d1 = i1 ->\n  degree_def_wrt_varref 0 d1 ->\n  lc_def d1) /\\\n(forall defs1,\n  size_defs defs1 = i1 ->\n  degree_defs_wrt_varref 0 defs1 ->\n  lc_defs defs1) /\\\n(forall val1,\n  size_val val1 = i1 ->\n  degree_val_wrt_varref 0 val1 ->\n  lc_val val1) /\\\n(forall t1,\n  size_trm t1 = i1 ->\n  degree_trm_wrt_varref 0 t1 ->\n  lc_trm t1).\nProof.\nintros i1; pattern i1; apply lt_wf_rec;\nclear i1; intros i1 H1;\napply_mutual_ind def_defs_val_trm_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_def_of_degree :\nforall d1,\n  degree_def_wrt_varref 0 d1 ->\n  lc_def d1.\nProof.\nintros d1; intros;\npose proof (lc_def_of_degree_lc_defs_of_degree_lc_val_of_degree_lc_trm_of_degree_size_mutual (size_def d1));\nintuition eauto.\nQed.\n\nHint Resolve lc_def_of_degree : lngen.\n\nLemma lc_defs_of_degree :\nforall defs1,\n  degree_defs_wrt_varref 0 defs1 ->\n  lc_defs defs1.\nProof.\nintros defs1; intros;\npose proof (lc_def_of_degree_lc_defs_of_degree_lc_val_of_degree_lc_trm_of_degree_size_mutual (size_defs defs1));\nintuition eauto.\nQed.\n\nHint Resolve lc_defs_of_degree : lngen.\n\nLemma lc_val_of_degree :\nforall val1,\n  degree_val_wrt_varref 0 val1 ->\n  lc_val val1.\nProof.\nintros val1; intros;\npose proof (lc_def_of_degree_lc_defs_of_degree_lc_val_of_degree_lc_trm_of_degree_size_mutual (size_val val1));\nintuition eauto.\nQed.\n\nHint Resolve lc_val_of_degree : lngen.\n\nLemma lc_trm_of_degree :\nforall t1,\n  degree_trm_wrt_varref 0 t1 ->\n  lc_trm t1.\nProof.\nintros t1; intros;\npose proof (lc_def_of_degree_lc_defs_of_degree_lc_val_of_degree_lc_trm_of_degree_size_mutual (size_trm t1));\nintuition eauto.\nQed.\n\nHint Resolve lc_trm_of_degree : lngen.\n\nLtac varref_lc_exists_tac :=\n  repeat (match goal with\n            | H : _ |- _ =>\n              let J1 := fresh in pose proof H as J1; apply degree_varref_wrt_varref_of_lc_varref in J1; clear H\n          end).\n\nLtac typ_dec_lc_exists_tac :=\n  repeat (match goal with\n            | H : _ |- _ =>\n              let J1 := fresh in pose proof H as J1; apply degree_typ_wrt_varref_of_lc_typ in J1; clear H\n            | H : _ |- _ =>\n              let J1 := fresh in pose proof H as J1; apply degree_dec_wrt_varref_of_lc_dec in J1; clear H\n          end).\n\nLtac def_defs_val_trm_lc_exists_tac :=\n  repeat (match goal with\n            | H : _ |- _ =>\n              let J1 := fresh in pose proof H as J1; apply degree_def_wrt_varref_of_lc_def in J1; clear H\n            | H : _ |- _ =>\n              let J1 := fresh in pose proof H as J1; apply degree_defs_wrt_varref_of_lc_defs in J1; clear H\n            | H : _ |- _ =>\n              let J1 := fresh in pose proof H as J1; apply degree_val_wrt_varref_of_lc_val in J1; clear H\n            | H : _ |- _ =>\n              let J1 := fresh in pose proof H as J1; apply degree_trm_wrt_varref_of_lc_trm in J1; clear H\n          end).\n\nLemma lc_typ_all_exists :\nforall x1 T1 T2,\n  lc_typ T1 ->\n  lc_typ (open_typ_wrt_varref T2 (var_termvar_f x1)) ->\n  lc_typ (typ_all T1 T2).\nProof.\nintros; typ_dec_lc_exists_tac; eauto with lngen.\nQed.\n\nLemma lc_typ_bnd_exists :\nforall x1 T1,\n  lc_typ (open_typ_wrt_varref T1 (var_termvar_f x1)) ->\n  lc_typ (typ_bnd T1).\nProof.\nintros; typ_dec_lc_exists_tac; eauto with lngen.\nQed.\n\nLemma lc_val_new_exists :\nforall x1 T1 defs1,\n  lc_typ T1 ->\n  lc_defs (open_defs_wrt_varref defs1 (var_termvar_f x1)) ->\n  lc_val (val_new T1 defs1).\nProof.\nintros; def_defs_val_trm_lc_exists_tac; eauto with lngen.\nQed.\n\nLemma lc_val_lambda_exists :\nforall x1 T1 t1,\n  lc_typ T1 ->\n  lc_trm (open_trm_wrt_varref t1 (var_termvar_f x1)) ->\n  lc_val (val_lambda T1 t1).\nProof.\nintros; def_defs_val_trm_lc_exists_tac; eauto with lngen.\nQed.\n\nLemma lc_trm_let_exists :\nforall x1 t1 t2,\n  lc_trm t1 ->\n  lc_trm (open_trm_wrt_varref t2 (var_termvar_f x1)) ->\n  lc_trm (trm_let t1 t2).\nProof.\nintros; def_defs_val_trm_lc_exists_tac; eauto with lngen.\nQed.\n\nHint Extern 1 (lc_typ (typ_all _ _)) =>\n  let x1 := fresh in\n  pick_fresh x1;\n  apply (lc_typ_all_exists x1).\n\nHint Extern 1 (lc_typ (typ_bnd _)) =>\n  let x1 := fresh in\n  pick_fresh x1;\n  apply (lc_typ_bnd_exists x1).\n\nHint Extern 1 (lc_val (val_new _ _)) =>\n  let x1 := fresh in\n  pick_fresh x1;\n  apply (lc_val_new_exists x1).\n\nHint Extern 1 (lc_val (val_lambda _ _)) =>\n  let x1 := fresh in\n  pick_fresh x1;\n  apply (lc_val_lambda_exists x1).\n\nHint Extern 1 (lc_trm (trm_let _ _)) =>\n  let x1 := fresh in\n  pick_fresh x1;\n  apply (lc_trm_let_exists x1).\n\nLemma lc_body_varref_wrt_varref :\nforall v1 v2,\n  body_varref_wrt_varref v1 ->\n  lc_varref v2 ->\n  lc_varref (open_varref_wrt_varref v1 v2).\nProof.\nunfold body_varref_wrt_varref;\ndefault_simp;\nlet x1 := fresh \"x\" in\npick_fresh x1;\nspecialize_all x1;\nvarref_lc_exists_tac;\neauto with lngen.\nQed.\n\nHint Resolve lc_body_varref_wrt_varref : lngen.\n\nLemma lc_body_typ_wrt_varref :\nforall T1 v1,\n  body_typ_wrt_varref T1 ->\n  lc_varref v1 ->\n  lc_typ (open_typ_wrt_varref T1 v1).\nProof.\nunfold body_typ_wrt_varref;\ndefault_simp;\nlet x1 := fresh \"x\" in\npick_fresh x1;\nspecialize_all x1;\ntyp_dec_lc_exists_tac;\neauto with lngen.\nQed.\n\nHint Resolve lc_body_typ_wrt_varref : lngen.\n\nLemma lc_body_dec_wrt_varref :\nforall dec1 v1,\n  body_dec_wrt_varref dec1 ->\n  lc_varref v1 ->\n  lc_dec (open_dec_wrt_varref dec1 v1).\nProof.\nunfold body_dec_wrt_varref;\ndefault_simp;\nlet x1 := fresh \"x\" in\npick_fresh x1;\nspecialize_all x1;\ntyp_dec_lc_exists_tac;\neauto with lngen.\nQed.\n\nHint Resolve lc_body_dec_wrt_varref : lngen.\n\nLemma lc_body_def_wrt_varref :\nforall d1 v1,\n  body_def_wrt_varref d1 ->\n  lc_varref v1 ->\n  lc_def (open_def_wrt_varref d1 v1).\nProof.\nunfold body_def_wrt_varref;\ndefault_simp;\nlet x1 := fresh \"x\" in\npick_fresh x1;\nspecialize_all x1;\ndef_defs_val_trm_lc_exists_tac;\neauto with lngen.\nQed.\n\nHint Resolve lc_body_def_wrt_varref : lngen.\n\nLemma lc_body_defs_wrt_varref :\nforall defs1 v1,\n  body_defs_wrt_varref defs1 ->\n  lc_varref v1 ->\n  lc_defs (open_defs_wrt_varref defs1 v1).\nProof.\nunfold body_defs_wrt_varref;\ndefault_simp;\nlet x1 := fresh \"x\" in\npick_fresh x1;\nspecialize_all x1;\ndef_defs_val_trm_lc_exists_tac;\neauto with lngen.\nQed.\n\nHint Resolve lc_body_defs_wrt_varref : lngen.\n\nLemma lc_body_val_wrt_varref :\nforall val1 v1,\n  body_val_wrt_varref val1 ->\n  lc_varref v1 ->\n  lc_val (open_val_wrt_varref val1 v1).\nProof.\nunfold body_val_wrt_varref;\ndefault_simp;\nlet x1 := fresh \"x\" in\npick_fresh x1;\nspecialize_all x1;\ndef_defs_val_trm_lc_exists_tac;\neauto with lngen.\nQed.\n\nHint Resolve lc_body_val_wrt_varref : lngen.\n\nLemma lc_body_trm_wrt_varref :\nforall t1 v1,\n  body_trm_wrt_varref t1 ->\n  lc_varref v1 ->\n  lc_trm (open_trm_wrt_varref t1 v1).\nProof.\nunfold body_trm_wrt_varref;\ndefault_simp;\nlet x1 := fresh \"x\" in\npick_fresh x1;\nspecialize_all x1;\ndef_defs_val_trm_lc_exists_tac;\neauto with lngen.\nQed.\n\nHint Resolve lc_body_trm_wrt_varref : lngen.\n\nLemma lc_body_typ_all_2 :\nforall T1 T2,\n  lc_typ (typ_all T1 T2) ->\n  body_typ_wrt_varref T2.\nProof.\ndefault_simp.\nQed.\n\nHint Resolve lc_body_typ_all_2 : lngen.\n\nLemma lc_body_typ_bnd_1 :\nforall T1,\n  lc_typ (typ_bnd T1) ->\n  body_typ_wrt_varref T1.\nProof.\ndefault_simp.\nQed.\n\nHint Resolve lc_body_typ_bnd_1 : lngen.\n\nLemma lc_body_val_new_2 :\nforall T1 defs1,\n  lc_val (val_new T1 defs1) ->\n  body_defs_wrt_varref defs1.\nProof.\ndefault_simp.\nQed.\n\nHint Resolve lc_body_val_new_2 : lngen.\n\nLemma lc_body_val_lambda_2 :\nforall T1 t1,\n  lc_val (val_lambda T1 t1) ->\n  body_trm_wrt_varref t1.\nProof.\ndefault_simp.\nQed.\n\nHint Resolve lc_body_val_lambda_2 : lngen.\n\nLemma lc_body_trm_let_2 :\nforall t1 t2,\n  lc_trm (trm_let t1 t2) ->\n  body_trm_wrt_varref t2.\nProof.\ndefault_simp.\nQed.\n\nHint Resolve lc_body_trm_let_2 : lngen.\n\n(* begin hide *)\n\nLemma lc_varref_unique_mutual :\n(forall v1 (proof2 proof3 : lc_varref v1), proof2 = proof3).\nProof.\napply_mutual_ind lc_varref_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_varref_unique :\nforall v1 (proof2 proof3 : lc_varref v1), proof2 = proof3.\nProof.\npose proof lc_varref_unique_mutual as H; intuition eauto.\nQed.\n\nHint Resolve lc_varref_unique : lngen.\n\n(* begin hide *)\n\nLemma lc_typ_unique_lc_dec_unique_mutual :\n(forall T1 (proof2 proof3 : lc_typ T1), proof2 = proof3) /\\\n(forall dec1 (proof2 proof3 : lc_dec dec1), proof2 = proof3).\nProof.\napply_mutual_ind lc_typ_lc_dec_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_typ_unique :\nforall T1 (proof2 proof3 : lc_typ T1), proof2 = proof3.\nProof.\npose proof lc_typ_unique_lc_dec_unique_mutual as H; intuition eauto.\nQed.\n\nHint Resolve lc_typ_unique : lngen.\n\nLemma lc_dec_unique :\nforall dec1 (proof2 proof3 : lc_dec dec1), proof2 = proof3.\nProof.\npose proof lc_typ_unique_lc_dec_unique_mutual as H; intuition eauto.\nQed.\n\nHint Resolve lc_dec_unique : lngen.\n\n(* begin hide *)\n\nLemma lc_def_unique_lc_defs_unique_lc_val_unique_lc_trm_unique_mutual :\n(forall d1 (proof2 proof3 : lc_def d1), proof2 = proof3) /\\\n(forall defs1 (proof2 proof3 : lc_defs defs1), proof2 = proof3) /\\\n(forall val1 (proof2 proof3 : lc_val val1), proof2 = proof3) /\\\n(forall t1 (proof2 proof3 : lc_trm t1), proof2 = proof3).\nProof.\napply_mutual_ind lc_def_lc_defs_lc_val_lc_trm_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_def_unique :\nforall d1 (proof2 proof3 : lc_def d1), proof2 = proof3.\nProof.\npose proof lc_def_unique_lc_defs_unique_lc_val_unique_lc_trm_unique_mutual as H; intuition eauto.\nQed.\n\nHint Resolve lc_def_unique : lngen.\n\nLemma lc_defs_unique :\nforall defs1 (proof2 proof3 : lc_defs defs1), proof2 = proof3.\nProof.\npose proof lc_def_unique_lc_defs_unique_lc_val_unique_lc_trm_unique_mutual as H; intuition eauto.\nQed.\n\nHint Resolve lc_defs_unique : lngen.\n\nLemma lc_val_unique :\nforall val1 (proof2 proof3 : lc_val val1), proof2 = proof3.\nProof.\npose proof lc_def_unique_lc_defs_unique_lc_val_unique_lc_trm_unique_mutual as H; intuition eauto.\nQed.\n\nHint Resolve lc_val_unique : lngen.\n\nLemma lc_trm_unique :\nforall t1 (proof2 proof3 : lc_trm t1), proof2 = proof3.\nProof.\npose proof lc_def_unique_lc_defs_unique_lc_val_unique_lc_trm_unique_mutual as H; intuition eauto.\nQed.\n\nHint Resolve lc_trm_unique : lngen.\n\n(* begin hide *)\n\nLemma lc_varref_of_lc_set_varref_mutual :\n(forall v1, lc_set_varref v1 -> lc_varref v1).\nProof.\napply_mutual_ind lc_set_varref_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma lc_varref_of_lc_set_varref :\nforall v1, lc_set_varref v1 -> lc_varref v1.\nProof.\npose proof lc_varref_of_lc_set_varref_mutual as H; intuition eauto.\nQed.\n\nHint Resolve lc_varref_of_lc_set_varref : lngen.\n\n(* begin hide *)\n\nLemma lc_typ_of_lc_set_typ_lc_dec_of_lc_set_dec_mutual :\n(forall T1, lc_set_typ T1 -> lc_typ T1) /\\\n(forall dec1, lc_set_dec dec1 -> lc_dec dec1).\nProof.\napply_mutual_ind lc_set_typ_lc_set_dec_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma lc_typ_of_lc_set_typ :\nforall T1, lc_set_typ T1 -> lc_typ T1.\nProof.\npose proof lc_typ_of_lc_set_typ_lc_dec_of_lc_set_dec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve lc_typ_of_lc_set_typ : lngen.\n\nLemma lc_dec_of_lc_set_dec :\nforall dec1, lc_set_dec dec1 -> lc_dec dec1.\nProof.\npose proof lc_typ_of_lc_set_typ_lc_dec_of_lc_set_dec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve lc_dec_of_lc_set_dec : lngen.\n\n(* begin hide *)\n\nLemma lc_def_of_lc_set_def_lc_defs_of_lc_set_defs_lc_val_of_lc_set_val_lc_trm_of_lc_set_trm_mutual :\n(forall d1, lc_set_def d1 -> lc_def d1) /\\\n(forall defs1, lc_set_defs defs1 -> lc_defs defs1) /\\\n(forall val1, lc_set_val val1 -> lc_val val1) /\\\n(forall t1, lc_set_trm t1 -> lc_trm t1).\nProof.\napply_mutual_ind lc_set_def_lc_set_defs_lc_set_val_lc_set_trm_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma lc_def_of_lc_set_def :\nforall d1, lc_set_def d1 -> lc_def d1.\nProof.\npose proof lc_def_of_lc_set_def_lc_defs_of_lc_set_defs_lc_val_of_lc_set_val_lc_trm_of_lc_set_trm_mutual as H; intuition eauto.\nQed.\n\nHint Resolve lc_def_of_lc_set_def : lngen.\n\nLemma lc_defs_of_lc_set_defs :\nforall defs1, lc_set_defs defs1 -> lc_defs defs1.\nProof.\npose proof lc_def_of_lc_set_def_lc_defs_of_lc_set_defs_lc_val_of_lc_set_val_lc_trm_of_lc_set_trm_mutual as H; intuition eauto.\nQed.\n\nHint Resolve lc_defs_of_lc_set_defs : lngen.\n\nLemma lc_val_of_lc_set_val :\nforall val1, lc_set_val val1 -> lc_val val1.\nProof.\npose proof lc_def_of_lc_set_def_lc_defs_of_lc_set_defs_lc_val_of_lc_set_val_lc_trm_of_lc_set_trm_mutual as H; intuition eauto.\nQed.\n\nHint Resolve lc_val_of_lc_set_val : lngen.\n\nLemma lc_trm_of_lc_set_trm :\nforall t1, lc_set_trm t1 -> lc_trm t1.\nProof.\npose proof lc_def_of_lc_set_def_lc_defs_of_lc_set_defs_lc_val_of_lc_set_val_lc_trm_of_lc_set_trm_mutual as H; intuition eauto.\nQed.\n\nHint Resolve lc_trm_of_lc_set_trm : lngen.\n\n(* begin hide *)\n\nLemma lc_set_varref_of_lc_varref_size_mutual :\nforall i1,\n(forall v1,\n  size_varref v1 = i1 ->\n  lc_varref v1 ->\n  lc_set_varref v1).\nProof.\nintros i1; pattern i1; apply lt_wf_rec;\nclear i1; intros i1 H1;\napply_mutual_ind varref_mutrec;\ndefault_simp;\ntry solve [assert False by default_simp; tauto];\n(* non-trivial cases *)\nconstructor; default_simp;\ntry first [apply lc_set_varref_of_lc_varref];\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_varref_of_lc_varref :\nforall v1,\n  lc_varref v1 ->\n  lc_set_varref v1.\nProof.\nintros v1; intros;\npose proof (lc_set_varref_of_lc_varref_size_mutual (size_varref v1));\nintuition eauto.\nQed.\n\nHint Resolve lc_set_varref_of_lc_varref : lngen.\n\n(* begin hide *)\n\nLemma lc_set_typ_of_lc_typ_lc_set_dec_of_lc_dec_size_mutual :\nforall i1,\n(forall T1,\n  size_typ T1 = i1 ->\n  lc_typ T1 ->\n  lc_set_typ T1) *\n(forall dec1,\n  size_dec dec1 = i1 ->\n  lc_dec dec1 ->\n  lc_set_dec dec1).\nProof.\nintros i1; pattern i1; apply lt_wf_rec;\nclear i1; intros i1 H1;\napply_mutual_ind typ_dec_mutrec;\ndefault_simp;\ntry solve [assert False by default_simp; tauto];\n(* non-trivial cases *)\nconstructor; default_simp;\ntry first [apply lc_set_typ_of_lc_typ\n | apply lc_set_dec_of_lc_dec\n | apply lc_set_varref_of_lc_varref\n | apply lc_set_typ_of_lc_typ\n | apply lc_set_dec_of_lc_dec\n | apply lc_set_varref_of_lc_varref];\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_typ_of_lc_typ :\nforall T1,\n  lc_typ T1 ->\n  lc_set_typ T1.\nProof.\nintros T1; intros;\npose proof (lc_set_typ_of_lc_typ_lc_set_dec_of_lc_dec_size_mutual (size_typ T1));\nintuition eauto.\nQed.\n\nHint Resolve lc_set_typ_of_lc_typ : lngen.\n\nLemma lc_set_dec_of_lc_dec :\nforall dec1,\n  lc_dec dec1 ->\n  lc_set_dec dec1.\nProof.\nintros dec1; intros;\npose proof (lc_set_typ_of_lc_typ_lc_set_dec_of_lc_dec_size_mutual (size_dec dec1));\nintuition eauto.\nQed.\n\nHint Resolve lc_set_dec_of_lc_dec : lngen.\n\n(* begin hide *)\n\nLemma lc_set_def_of_lc_def_lc_set_defs_of_lc_defs_lc_set_val_of_lc_val_lc_set_trm_of_lc_trm_size_mutual :\nforall i1,\n(forall d1,\n  size_def d1 = i1 ->\n  lc_def d1 ->\n  lc_set_def d1) *\n(forall defs1,\n  size_defs defs1 = i1 ->\n  lc_defs defs1 ->\n  lc_set_defs defs1) *\n(forall val1,\n  size_val val1 = i1 ->\n  lc_val val1 ->\n  lc_set_val val1) *\n(forall t1,\n  size_trm t1 = i1 ->\n  lc_trm t1 ->\n  lc_set_trm t1).\nProof.\nintros i1; pattern i1; apply lt_wf_rec;\nclear i1; intros i1 H1;\napply_mutual_ind def_defs_val_trm_mutrec;\ndefault_simp;\ntry solve [assert False by default_simp; tauto];\n(* non-trivial cases *)\nconstructor; default_simp;\ntry first [apply lc_set_typ_of_lc_typ\n | apply lc_set_def_of_lc_def\n | apply lc_set_dec_of_lc_dec\n | apply lc_set_defs_of_lc_defs\n | apply lc_set_trm_of_lc_trm\n | apply lc_set_varref_of_lc_varref\n | apply lc_set_val_of_lc_val\n | apply lc_set_typ_of_lc_typ\n | apply lc_set_def_of_lc_def\n | apply lc_set_dec_of_lc_dec\n | apply lc_set_defs_of_lc_defs\n | apply lc_set_trm_of_lc_trm\n | apply lc_set_varref_of_lc_varref\n | apply lc_set_val_of_lc_val\n | apply lc_set_typ_of_lc_typ\n | apply lc_set_def_of_lc_def\n | apply lc_set_dec_of_lc_dec\n | apply lc_set_defs_of_lc_defs\n | apply lc_set_trm_of_lc_trm\n | apply lc_set_varref_of_lc_varref\n | apply lc_set_val_of_lc_val\n | apply lc_set_typ_of_lc_typ\n | apply lc_set_def_of_lc_def\n | apply lc_set_dec_of_lc_dec\n | apply lc_set_defs_of_lc_defs\n | apply lc_set_trm_of_lc_trm\n | apply lc_set_varref_of_lc_varref\n | apply lc_set_val_of_lc_val];\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_def_of_lc_def :\nforall d1,\n  lc_def d1 ->\n  lc_set_def d1.\nProof.\nintros d1; intros;\npose proof (lc_set_def_of_lc_def_lc_set_defs_of_lc_defs_lc_set_val_of_lc_val_lc_set_trm_of_lc_trm_size_mutual (size_def d1));\nintuition eauto.\nQed.\n\nHint Resolve lc_set_def_of_lc_def : lngen.\n\nLemma lc_set_defs_of_lc_defs :\nforall defs1,\n  lc_defs defs1 ->\n  lc_set_defs defs1.\nProof.\nintros defs1; intros;\npose proof (lc_set_def_of_lc_def_lc_set_defs_of_lc_defs_lc_set_val_of_lc_val_lc_set_trm_of_lc_trm_size_mutual (size_defs defs1));\nintuition eauto.\nQed.\n\nHint Resolve lc_set_defs_of_lc_defs : lngen.\n\nLemma lc_set_val_of_lc_val :\nforall val1,\n  lc_val val1 ->\n  lc_set_val val1.\nProof.\nintros val1; intros;\npose proof (lc_set_def_of_lc_def_lc_set_defs_of_lc_defs_lc_set_val_of_lc_val_lc_set_trm_of_lc_trm_size_mutual (size_val val1));\nintuition eauto.\nQed.\n\nHint Resolve lc_set_val_of_lc_val : lngen.\n\nLemma lc_set_trm_of_lc_trm :\nforall t1,\n  lc_trm t1 ->\n  lc_set_trm t1.\nProof.\nintros t1; intros;\npose proof (lc_set_def_of_lc_def_lc_set_defs_of_lc_defs_lc_set_val_of_lc_val_lc_set_trm_of_lc_trm_size_mutual (size_trm t1));\nintuition eauto.\nQed.\n\nHint Resolve lc_set_trm_of_lc_trm : 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_varref_wrt_varref_rec_degree_varref_wrt_varref_mutual :\n(forall v1 x1 n1,\n  degree_varref_wrt_varref n1 v1 ->\n  x1 `notin` fv_varref v1 ->\n  close_varref_wrt_varref_rec n1 x1 v1 = v1).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_varref_wrt_varref_rec_degree_varref_wrt_varref :\nforall v1 x1 n1,\n  degree_varref_wrt_varref n1 v1 ->\n  x1 `notin` fv_varref v1 ->\n  close_varref_wrt_varref_rec n1 x1 v1 = v1.\nProof.\npose proof close_varref_wrt_varref_rec_degree_varref_wrt_varref_mutual as H; intuition eauto.\nQed.\n\nHint Resolve close_varref_wrt_varref_rec_degree_varref_wrt_varref : lngen.\nHint Rewrite close_varref_wrt_varref_rec_degree_varref_wrt_varref using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_typ_wrt_varref_rec_degree_typ_wrt_varref_close_dec_wrt_varref_rec_degree_dec_wrt_varref_mutual :\n(forall T1 x1 n1,\n  degree_typ_wrt_varref n1 T1 ->\n  x1 `notin` fv_typ T1 ->\n  close_typ_wrt_varref_rec n1 x1 T1 = T1) /\\\n(forall dec1 x1 n1,\n  degree_dec_wrt_varref n1 dec1 ->\n  x1 `notin` fv_dec dec1 ->\n  close_dec_wrt_varref_rec n1 x1 dec1 = dec1).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_typ_wrt_varref_rec_degree_typ_wrt_varref :\nforall T1 x1 n1,\n  degree_typ_wrt_varref n1 T1 ->\n  x1 `notin` fv_typ T1 ->\n  close_typ_wrt_varref_rec n1 x1 T1 = T1.\nProof.\npose proof close_typ_wrt_varref_rec_degree_typ_wrt_varref_close_dec_wrt_varref_rec_degree_dec_wrt_varref_mutual as H; intuition eauto.\nQed.\n\nHint Resolve close_typ_wrt_varref_rec_degree_typ_wrt_varref : lngen.\nHint Rewrite close_typ_wrt_varref_rec_degree_typ_wrt_varref using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_dec_wrt_varref_rec_degree_dec_wrt_varref :\nforall dec1 x1 n1,\n  degree_dec_wrt_varref n1 dec1 ->\n  x1 `notin` fv_dec dec1 ->\n  close_dec_wrt_varref_rec n1 x1 dec1 = dec1.\nProof.\npose proof close_typ_wrt_varref_rec_degree_typ_wrt_varref_close_dec_wrt_varref_rec_degree_dec_wrt_varref_mutual as H; intuition eauto.\nQed.\n\nHint Resolve close_dec_wrt_varref_rec_degree_dec_wrt_varref : lngen.\nHint Rewrite close_dec_wrt_varref_rec_degree_dec_wrt_varref using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_def_wrt_varref_rec_degree_def_wrt_varref_close_defs_wrt_varref_rec_degree_defs_wrt_varref_close_val_wrt_varref_rec_degree_val_wrt_varref_close_trm_wrt_varref_rec_degree_trm_wrt_varref_mutual :\n(forall d1 x1 n1,\n  degree_def_wrt_varref n1 d1 ->\n  x1 `notin` fv_def d1 ->\n  close_def_wrt_varref_rec n1 x1 d1 = d1) /\\\n(forall defs1 x1 n1,\n  degree_defs_wrt_varref n1 defs1 ->\n  x1 `notin` fv_defs defs1 ->\n  close_defs_wrt_varref_rec n1 x1 defs1 = defs1) /\\\n(forall val1 x1 n1,\n  degree_val_wrt_varref n1 val1 ->\n  x1 `notin` fv_val val1 ->\n  close_val_wrt_varref_rec n1 x1 val1 = val1) /\\\n(forall t1 x1 n1,\n  degree_trm_wrt_varref n1 t1 ->\n  x1 `notin` fv_trm t1 ->\n  close_trm_wrt_varref_rec n1 x1 t1 = t1).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_def_wrt_varref_rec_degree_def_wrt_varref :\nforall d1 x1 n1,\n  degree_def_wrt_varref n1 d1 ->\n  x1 `notin` fv_def d1 ->\n  close_def_wrt_varref_rec n1 x1 d1 = d1.\nProof.\npose proof close_def_wrt_varref_rec_degree_def_wrt_varref_close_defs_wrt_varref_rec_degree_defs_wrt_varref_close_val_wrt_varref_rec_degree_val_wrt_varref_close_trm_wrt_varref_rec_degree_trm_wrt_varref_mutual as H; intuition eauto.\nQed.\n\nHint Resolve close_def_wrt_varref_rec_degree_def_wrt_varref : lngen.\nHint Rewrite close_def_wrt_varref_rec_degree_def_wrt_varref using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_defs_wrt_varref_rec_degree_defs_wrt_varref :\nforall defs1 x1 n1,\n  degree_defs_wrt_varref n1 defs1 ->\n  x1 `notin` fv_defs defs1 ->\n  close_defs_wrt_varref_rec n1 x1 defs1 = defs1.\nProof.\npose proof close_def_wrt_varref_rec_degree_def_wrt_varref_close_defs_wrt_varref_rec_degree_defs_wrt_varref_close_val_wrt_varref_rec_degree_val_wrt_varref_close_trm_wrt_varref_rec_degree_trm_wrt_varref_mutual as H; intuition eauto.\nQed.\n\nHint Resolve close_defs_wrt_varref_rec_degree_defs_wrt_varref : lngen.\nHint Rewrite close_defs_wrt_varref_rec_degree_defs_wrt_varref using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_val_wrt_varref_rec_degree_val_wrt_varref :\nforall val1 x1 n1,\n  degree_val_wrt_varref n1 val1 ->\n  x1 `notin` fv_val val1 ->\n  close_val_wrt_varref_rec n1 x1 val1 = val1.\nProof.\npose proof close_def_wrt_varref_rec_degree_def_wrt_varref_close_defs_wrt_varref_rec_degree_defs_wrt_varref_close_val_wrt_varref_rec_degree_val_wrt_varref_close_trm_wrt_varref_rec_degree_trm_wrt_varref_mutual as H; intuition eauto.\nQed.\n\nHint Resolve close_val_wrt_varref_rec_degree_val_wrt_varref : lngen.\nHint Rewrite close_val_wrt_varref_rec_degree_val_wrt_varref using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_trm_wrt_varref_rec_degree_trm_wrt_varref :\nforall t1 x1 n1,\n  degree_trm_wrt_varref n1 t1 ->\n  x1 `notin` fv_trm t1 ->\n  close_trm_wrt_varref_rec n1 x1 t1 = t1.\nProof.\npose proof close_def_wrt_varref_rec_degree_def_wrt_varref_close_defs_wrt_varref_rec_degree_defs_wrt_varref_close_val_wrt_varref_rec_degree_val_wrt_varref_close_trm_wrt_varref_rec_degree_trm_wrt_varref_mutual as H; intuition eauto.\nQed.\n\nHint Resolve close_trm_wrt_varref_rec_degree_trm_wrt_varref : lngen.\nHint Rewrite close_trm_wrt_varref_rec_degree_trm_wrt_varref using solve [auto] : lngen.\n\n(* end hide *)\n\nLemma close_varref_wrt_varref_lc_varref :\nforall v1 x1,\n  lc_varref v1 ->\n  x1 `notin` fv_varref v1 ->\n  close_varref_wrt_varref x1 v1 = v1.\nProof.\nunfold close_varref_wrt_varref; default_simp.\nQed.\n\nHint Resolve close_varref_wrt_varref_lc_varref : lngen.\nHint Rewrite close_varref_wrt_varref_lc_varref using solve [auto] : lngen.\n\nLemma close_typ_wrt_varref_lc_typ :\nforall T1 x1,\n  lc_typ T1 ->\n  x1 `notin` fv_typ T1 ->\n  close_typ_wrt_varref x1 T1 = T1.\nProof.\nunfold close_typ_wrt_varref; default_simp.\nQed.\n\nHint Resolve close_typ_wrt_varref_lc_typ : lngen.\nHint Rewrite close_typ_wrt_varref_lc_typ using solve [auto] : lngen.\n\nLemma close_dec_wrt_varref_lc_dec :\nforall dec1 x1,\n  lc_dec dec1 ->\n  x1 `notin` fv_dec dec1 ->\n  close_dec_wrt_varref x1 dec1 = dec1.\nProof.\nunfold close_dec_wrt_varref; default_simp.\nQed.\n\nHint Resolve close_dec_wrt_varref_lc_dec : lngen.\nHint Rewrite close_dec_wrt_varref_lc_dec using solve [auto] : lngen.\n\nLemma close_def_wrt_varref_lc_def :\nforall d1 x1,\n  lc_def d1 ->\n  x1 `notin` fv_def d1 ->\n  close_def_wrt_varref x1 d1 = d1.\nProof.\nunfold close_def_wrt_varref; default_simp.\nQed.\n\nHint Resolve close_def_wrt_varref_lc_def : lngen.\nHint Rewrite close_def_wrt_varref_lc_def using solve [auto] : lngen.\n\nLemma close_defs_wrt_varref_lc_defs :\nforall defs1 x1,\n  lc_defs defs1 ->\n  x1 `notin` fv_defs defs1 ->\n  close_defs_wrt_varref x1 defs1 = defs1.\nProof.\nunfold close_defs_wrt_varref; default_simp.\nQed.\n\nHint Resolve close_defs_wrt_varref_lc_defs : lngen.\nHint Rewrite close_defs_wrt_varref_lc_defs using solve [auto] : lngen.\n\nLemma close_val_wrt_varref_lc_val :\nforall val1 x1,\n  lc_val val1 ->\n  x1 `notin` fv_val val1 ->\n  close_val_wrt_varref x1 val1 = val1.\nProof.\nunfold close_val_wrt_varref; default_simp.\nQed.\n\nHint Resolve close_val_wrt_varref_lc_val : lngen.\nHint Rewrite close_val_wrt_varref_lc_val using solve [auto] : lngen.\n\nLemma close_trm_wrt_varref_lc_trm :\nforall t1 x1,\n  lc_trm t1 ->\n  x1 `notin` fv_trm t1 ->\n  close_trm_wrt_varref x1 t1 = t1.\nProof.\nunfold close_trm_wrt_varref; default_simp.\nQed.\n\nHint Resolve close_trm_wrt_varref_lc_trm : lngen.\nHint Rewrite close_trm_wrt_varref_lc_trm using solve [auto] : lngen.\n\n(* begin hide *)\n\nLemma open_varref_wrt_varref_rec_degree_varref_wrt_varref_mutual :\n(forall v2 v1 n1,\n  degree_varref_wrt_varref n1 v2 ->\n  open_varref_wrt_varref_rec n1 v1 v2 = v2).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_varref_wrt_varref_rec_degree_varref_wrt_varref :\nforall v2 v1 n1,\n  degree_varref_wrt_varref n1 v2 ->\n  open_varref_wrt_varref_rec n1 v1 v2 = v2.\nProof.\npose proof open_varref_wrt_varref_rec_degree_varref_wrt_varref_mutual as H; intuition eauto.\nQed.\n\nHint Resolve open_varref_wrt_varref_rec_degree_varref_wrt_varref : lngen.\nHint Rewrite open_varref_wrt_varref_rec_degree_varref_wrt_varref using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_typ_wrt_varref_rec_degree_typ_wrt_varref_open_dec_wrt_varref_rec_degree_dec_wrt_varref_mutual :\n(forall T1 v1 n1,\n  degree_typ_wrt_varref n1 T1 ->\n  open_typ_wrt_varref_rec n1 v1 T1 = T1) /\\\n(forall dec1 v1 n1,\n  degree_dec_wrt_varref n1 dec1 ->\n  open_dec_wrt_varref_rec n1 v1 dec1 = dec1).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_typ_wrt_varref_rec_degree_typ_wrt_varref :\nforall T1 v1 n1,\n  degree_typ_wrt_varref n1 T1 ->\n  open_typ_wrt_varref_rec n1 v1 T1 = T1.\nProof.\npose proof open_typ_wrt_varref_rec_degree_typ_wrt_varref_open_dec_wrt_varref_rec_degree_dec_wrt_varref_mutual as H; intuition eauto.\nQed.\n\nHint Resolve open_typ_wrt_varref_rec_degree_typ_wrt_varref : lngen.\nHint Rewrite open_typ_wrt_varref_rec_degree_typ_wrt_varref using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_dec_wrt_varref_rec_degree_dec_wrt_varref :\nforall dec1 v1 n1,\n  degree_dec_wrt_varref n1 dec1 ->\n  open_dec_wrt_varref_rec n1 v1 dec1 = dec1.\nProof.\npose proof open_typ_wrt_varref_rec_degree_typ_wrt_varref_open_dec_wrt_varref_rec_degree_dec_wrt_varref_mutual as H; intuition eauto.\nQed.\n\nHint Resolve open_dec_wrt_varref_rec_degree_dec_wrt_varref : lngen.\nHint Rewrite open_dec_wrt_varref_rec_degree_dec_wrt_varref using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_def_wrt_varref_rec_degree_def_wrt_varref_open_defs_wrt_varref_rec_degree_defs_wrt_varref_open_val_wrt_varref_rec_degree_val_wrt_varref_open_trm_wrt_varref_rec_degree_trm_wrt_varref_mutual :\n(forall d1 v1 n1,\n  degree_def_wrt_varref n1 d1 ->\n  open_def_wrt_varref_rec n1 v1 d1 = d1) /\\\n(forall defs1 v1 n1,\n  degree_defs_wrt_varref n1 defs1 ->\n  open_defs_wrt_varref_rec n1 v1 defs1 = defs1) /\\\n(forall val1 v1 n1,\n  degree_val_wrt_varref n1 val1 ->\n  open_val_wrt_varref_rec n1 v1 val1 = val1) /\\\n(forall t1 v1 n1,\n  degree_trm_wrt_varref n1 t1 ->\n  open_trm_wrt_varref_rec n1 v1 t1 = t1).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_def_wrt_varref_rec_degree_def_wrt_varref :\nforall d1 v1 n1,\n  degree_def_wrt_varref n1 d1 ->\n  open_def_wrt_varref_rec n1 v1 d1 = d1.\nProof.\npose proof open_def_wrt_varref_rec_degree_def_wrt_varref_open_defs_wrt_varref_rec_degree_defs_wrt_varref_open_val_wrt_varref_rec_degree_val_wrt_varref_open_trm_wrt_varref_rec_degree_trm_wrt_varref_mutual as H; intuition eauto.\nQed.\n\nHint Resolve open_def_wrt_varref_rec_degree_def_wrt_varref : lngen.\nHint Rewrite open_def_wrt_varref_rec_degree_def_wrt_varref using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_defs_wrt_varref_rec_degree_defs_wrt_varref :\nforall defs1 v1 n1,\n  degree_defs_wrt_varref n1 defs1 ->\n  open_defs_wrt_varref_rec n1 v1 defs1 = defs1.\nProof.\npose proof open_def_wrt_varref_rec_degree_def_wrt_varref_open_defs_wrt_varref_rec_degree_defs_wrt_varref_open_val_wrt_varref_rec_degree_val_wrt_varref_open_trm_wrt_varref_rec_degree_trm_wrt_varref_mutual as H; intuition eauto.\nQed.\n\nHint Resolve open_defs_wrt_varref_rec_degree_defs_wrt_varref : lngen.\nHint Rewrite open_defs_wrt_varref_rec_degree_defs_wrt_varref using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_val_wrt_varref_rec_degree_val_wrt_varref :\nforall val1 v1 n1,\n  degree_val_wrt_varref n1 val1 ->\n  open_val_wrt_varref_rec n1 v1 val1 = val1.\nProof.\npose proof open_def_wrt_varref_rec_degree_def_wrt_varref_open_defs_wrt_varref_rec_degree_defs_wrt_varref_open_val_wrt_varref_rec_degree_val_wrt_varref_open_trm_wrt_varref_rec_degree_trm_wrt_varref_mutual as H; intuition eauto.\nQed.\n\nHint Resolve open_val_wrt_varref_rec_degree_val_wrt_varref : lngen.\nHint Rewrite open_val_wrt_varref_rec_degree_val_wrt_varref using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_trm_wrt_varref_rec_degree_trm_wrt_varref :\nforall t1 v1 n1,\n  degree_trm_wrt_varref n1 t1 ->\n  open_trm_wrt_varref_rec n1 v1 t1 = t1.\nProof.\npose proof open_def_wrt_varref_rec_degree_def_wrt_varref_open_defs_wrt_varref_rec_degree_defs_wrt_varref_open_val_wrt_varref_rec_degree_val_wrt_varref_open_trm_wrt_varref_rec_degree_trm_wrt_varref_mutual as H; intuition eauto.\nQed.\n\nHint Resolve open_trm_wrt_varref_rec_degree_trm_wrt_varref : lngen.\nHint Rewrite open_trm_wrt_varref_rec_degree_trm_wrt_varref using solve [auto] : lngen.\n\n(* end hide *)\n\nLemma open_varref_wrt_varref_lc_varref :\nforall v2 v1,\n  lc_varref v2 ->\n  open_varref_wrt_varref v2 v1 = v2.\nProof.\nunfold open_varref_wrt_varref; default_simp.\nQed.\n\nHint Resolve open_varref_wrt_varref_lc_varref : lngen.\nHint Rewrite open_varref_wrt_varref_lc_varref using solve [auto] : lngen.\n\nLemma open_typ_wrt_varref_lc_typ :\nforall T1 v1,\n  lc_typ T1 ->\n  open_typ_wrt_varref T1 v1 = T1.\nProof.\nunfold open_typ_wrt_varref; default_simp.\nQed.\n\nHint Resolve open_typ_wrt_varref_lc_typ : lngen.\nHint Rewrite open_typ_wrt_varref_lc_typ using solve [auto] : lngen.\n\nLemma open_dec_wrt_varref_lc_dec :\nforall dec1 v1,\n  lc_dec dec1 ->\n  open_dec_wrt_varref dec1 v1 = dec1.\nProof.\nunfold open_dec_wrt_varref; default_simp.\nQed.\n\nHint Resolve open_dec_wrt_varref_lc_dec : lngen.\nHint Rewrite open_dec_wrt_varref_lc_dec using solve [auto] : lngen.\n\nLemma open_def_wrt_varref_lc_def :\nforall d1 v1,\n  lc_def d1 ->\n  open_def_wrt_varref d1 v1 = d1.\nProof.\nunfold open_def_wrt_varref; default_simp.\nQed.\n\nHint Resolve open_def_wrt_varref_lc_def : lngen.\nHint Rewrite open_def_wrt_varref_lc_def using solve [auto] : lngen.\n\nLemma open_defs_wrt_varref_lc_defs :\nforall defs1 v1,\n  lc_defs defs1 ->\n  open_defs_wrt_varref defs1 v1 = defs1.\nProof.\nunfold open_defs_wrt_varref; default_simp.\nQed.\n\nHint Resolve open_defs_wrt_varref_lc_defs : lngen.\nHint Rewrite open_defs_wrt_varref_lc_defs using solve [auto] : lngen.\n\nLemma open_val_wrt_varref_lc_val :\nforall val1 v1,\n  lc_val val1 ->\n  open_val_wrt_varref val1 v1 = val1.\nProof.\nunfold open_val_wrt_varref; default_simp.\nQed.\n\nHint Resolve open_val_wrt_varref_lc_val : lngen.\nHint Rewrite open_val_wrt_varref_lc_val using solve [auto] : lngen.\n\nLemma open_trm_wrt_varref_lc_trm :\nforall t1 v1,\n  lc_trm t1 ->\n  open_trm_wrt_varref t1 v1 = t1.\nProof.\nunfold open_trm_wrt_varref; default_simp.\nQed.\n\nHint Resolve open_trm_wrt_varref_lc_trm : lngen.\nHint Rewrite open_trm_wrt_varref_lc_trm 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_varref_close_varref_wrt_varref_rec_mutual :\n(forall v1 x1 n1,\n  fv_varref (close_varref_wrt_varref_rec n1 x1 v1) [=] remove x1 (fv_varref v1)).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_varref_close_varref_wrt_varref_rec :\nforall v1 x1 n1,\n  fv_varref (close_varref_wrt_varref_rec n1 x1 v1) [=] remove x1 (fv_varref v1).\nProof.\npose proof fv_varref_close_varref_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_varref_close_varref_wrt_varref_rec : lngen.\nHint Rewrite fv_varref_close_varref_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_typ_close_typ_wrt_varref_rec_fv_dec_close_dec_wrt_varref_rec_mutual :\n(forall T1 x1 n1,\n  fv_typ (close_typ_wrt_varref_rec n1 x1 T1) [=] remove x1 (fv_typ T1)) /\\\n(forall dec1 x1 n1,\n  fv_dec (close_dec_wrt_varref_rec n1 x1 dec1) [=] remove x1 (fv_dec dec1)).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_typ_close_typ_wrt_varref_rec :\nforall T1 x1 n1,\n  fv_typ (close_typ_wrt_varref_rec n1 x1 T1) [=] remove x1 (fv_typ T1).\nProof.\npose proof fv_typ_close_typ_wrt_varref_rec_fv_dec_close_dec_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_typ_close_typ_wrt_varref_rec : lngen.\nHint Rewrite fv_typ_close_typ_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_dec_close_dec_wrt_varref_rec :\nforall dec1 x1 n1,\n  fv_dec (close_dec_wrt_varref_rec n1 x1 dec1) [=] remove x1 (fv_dec dec1).\nProof.\npose proof fv_typ_close_typ_wrt_varref_rec_fv_dec_close_dec_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_dec_close_dec_wrt_varref_rec : lngen.\nHint Rewrite fv_dec_close_dec_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_def_close_def_wrt_varref_rec_fv_defs_close_defs_wrt_varref_rec_fv_val_close_val_wrt_varref_rec_fv_trm_close_trm_wrt_varref_rec_mutual :\n(forall d1 x1 n1,\n  fv_def (close_def_wrt_varref_rec n1 x1 d1) [=] remove x1 (fv_def d1)) /\\\n(forall defs1 x1 n1,\n  fv_defs (close_defs_wrt_varref_rec n1 x1 defs1) [=] remove x1 (fv_defs defs1)) /\\\n(forall val1 x1 n1,\n  fv_val (close_val_wrt_varref_rec n1 x1 val1) [=] remove x1 (fv_val val1)) /\\\n(forall t1 x1 n1,\n  fv_trm (close_trm_wrt_varref_rec n1 x1 t1) [=] remove x1 (fv_trm t1)).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_def_close_def_wrt_varref_rec :\nforall d1 x1 n1,\n  fv_def (close_def_wrt_varref_rec n1 x1 d1) [=] remove x1 (fv_def d1).\nProof.\npose proof fv_def_close_def_wrt_varref_rec_fv_defs_close_defs_wrt_varref_rec_fv_val_close_val_wrt_varref_rec_fv_trm_close_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_def_close_def_wrt_varref_rec : lngen.\nHint Rewrite fv_def_close_def_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_defs_close_defs_wrt_varref_rec :\nforall defs1 x1 n1,\n  fv_defs (close_defs_wrt_varref_rec n1 x1 defs1) [=] remove x1 (fv_defs defs1).\nProof.\npose proof fv_def_close_def_wrt_varref_rec_fv_defs_close_defs_wrt_varref_rec_fv_val_close_val_wrt_varref_rec_fv_trm_close_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_defs_close_defs_wrt_varref_rec : lngen.\nHint Rewrite fv_defs_close_defs_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_val_close_val_wrt_varref_rec :\nforall val1 x1 n1,\n  fv_val (close_val_wrt_varref_rec n1 x1 val1) [=] remove x1 (fv_val val1).\nProof.\npose proof fv_def_close_def_wrt_varref_rec_fv_defs_close_defs_wrt_varref_rec_fv_val_close_val_wrt_varref_rec_fv_trm_close_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_val_close_val_wrt_varref_rec : lngen.\nHint Rewrite fv_val_close_val_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_trm_close_trm_wrt_varref_rec :\nforall t1 x1 n1,\n  fv_trm (close_trm_wrt_varref_rec n1 x1 t1) [=] remove x1 (fv_trm t1).\nProof.\npose proof fv_def_close_def_wrt_varref_rec_fv_defs_close_defs_wrt_varref_rec_fv_val_close_val_wrt_varref_rec_fv_trm_close_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_trm_close_trm_wrt_varref_rec : lngen.\nHint Rewrite fv_trm_close_trm_wrt_varref_rec using solve [auto] : lngen.\n\n(* end hide *)\n\nLemma fv_varref_close_varref_wrt_varref :\nforall v1 x1,\n  fv_varref (close_varref_wrt_varref x1 v1) [=] remove x1 (fv_varref v1).\nProof.\nunfold close_varref_wrt_varref; default_simp.\nQed.\n\nHint Resolve fv_varref_close_varref_wrt_varref : lngen.\nHint Rewrite fv_varref_close_varref_wrt_varref using solve [auto] : lngen.\n\nLemma fv_typ_close_typ_wrt_varref :\nforall T1 x1,\n  fv_typ (close_typ_wrt_varref x1 T1) [=] remove x1 (fv_typ T1).\nProof.\nunfold close_typ_wrt_varref; default_simp.\nQed.\n\nHint Resolve fv_typ_close_typ_wrt_varref : lngen.\nHint Rewrite fv_typ_close_typ_wrt_varref using solve [auto] : lngen.\n\nLemma fv_dec_close_dec_wrt_varref :\nforall dec1 x1,\n  fv_dec (close_dec_wrt_varref x1 dec1) [=] remove x1 (fv_dec dec1).\nProof.\nunfold close_dec_wrt_varref; default_simp.\nQed.\n\nHint Resolve fv_dec_close_dec_wrt_varref : lngen.\nHint Rewrite fv_dec_close_dec_wrt_varref using solve [auto] : lngen.\n\nLemma fv_def_close_def_wrt_varref :\nforall d1 x1,\n  fv_def (close_def_wrt_varref x1 d1) [=] remove x1 (fv_def d1).\nProof.\nunfold close_def_wrt_varref; default_simp.\nQed.\n\nHint Resolve fv_def_close_def_wrt_varref : lngen.\nHint Rewrite fv_def_close_def_wrt_varref using solve [auto] : lngen.\n\nLemma fv_defs_close_defs_wrt_varref :\nforall defs1 x1,\n  fv_defs (close_defs_wrt_varref x1 defs1) [=] remove x1 (fv_defs defs1).\nProof.\nunfold close_defs_wrt_varref; default_simp.\nQed.\n\nHint Resolve fv_defs_close_defs_wrt_varref : lngen.\nHint Rewrite fv_defs_close_defs_wrt_varref using solve [auto] : lngen.\n\nLemma fv_val_close_val_wrt_varref :\nforall val1 x1,\n  fv_val (close_val_wrt_varref x1 val1) [=] remove x1 (fv_val val1).\nProof.\nunfold close_val_wrt_varref; default_simp.\nQed.\n\nHint Resolve fv_val_close_val_wrt_varref : lngen.\nHint Rewrite fv_val_close_val_wrt_varref using solve [auto] : lngen.\n\nLemma fv_trm_close_trm_wrt_varref :\nforall t1 x1,\n  fv_trm (close_trm_wrt_varref x1 t1) [=] remove x1 (fv_trm t1).\nProof.\nunfold close_trm_wrt_varref; default_simp.\nQed.\n\nHint Resolve fv_trm_close_trm_wrt_varref : lngen.\nHint Rewrite fv_trm_close_trm_wrt_varref using solve [auto] : lngen.\n\n(* begin hide *)\n\nLemma fv_varref_open_varref_wrt_varref_rec_lower_mutual :\n(forall v1 v2 n1,\n  fv_varref v1 [<=] fv_varref (open_varref_wrt_varref_rec n1 v2 v1)).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_varref_open_varref_wrt_varref_rec_lower :\nforall v1 v2 n1,\n  fv_varref v1 [<=] fv_varref (open_varref_wrt_varref_rec n1 v2 v1).\nProof.\npose proof fv_varref_open_varref_wrt_varref_rec_lower_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_varref_open_varref_wrt_varref_rec_lower : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_typ_open_typ_wrt_varref_rec_lower_fv_dec_open_dec_wrt_varref_rec_lower_mutual :\n(forall T1 v1 n1,\n  fv_typ T1 [<=] fv_typ (open_typ_wrt_varref_rec n1 v1 T1)) /\\\n(forall dec1 v1 n1,\n  fv_dec dec1 [<=] fv_dec (open_dec_wrt_varref_rec n1 v1 dec1)).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_typ_open_typ_wrt_varref_rec_lower :\nforall T1 v1 n1,\n  fv_typ T1 [<=] fv_typ (open_typ_wrt_varref_rec n1 v1 T1).\nProof.\npose proof fv_typ_open_typ_wrt_varref_rec_lower_fv_dec_open_dec_wrt_varref_rec_lower_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_typ_open_typ_wrt_varref_rec_lower : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_dec_open_dec_wrt_varref_rec_lower :\nforall dec1 v1 n1,\n  fv_dec dec1 [<=] fv_dec (open_dec_wrt_varref_rec n1 v1 dec1).\nProof.\npose proof fv_typ_open_typ_wrt_varref_rec_lower_fv_dec_open_dec_wrt_varref_rec_lower_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_dec_open_dec_wrt_varref_rec_lower : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_def_open_def_wrt_varref_rec_lower_fv_defs_open_defs_wrt_varref_rec_lower_fv_val_open_val_wrt_varref_rec_lower_fv_trm_open_trm_wrt_varref_rec_lower_mutual :\n(forall d1 v1 n1,\n  fv_def d1 [<=] fv_def (open_def_wrt_varref_rec n1 v1 d1)) /\\\n(forall defs1 v1 n1,\n  fv_defs defs1 [<=] fv_defs (open_defs_wrt_varref_rec n1 v1 defs1)) /\\\n(forall val1 v1 n1,\n  fv_val val1 [<=] fv_val (open_val_wrt_varref_rec n1 v1 val1)) /\\\n(forall t1 v1 n1,\n  fv_trm t1 [<=] fv_trm (open_trm_wrt_varref_rec n1 v1 t1)).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_def_open_def_wrt_varref_rec_lower :\nforall d1 v1 n1,\n  fv_def d1 [<=] fv_def (open_def_wrt_varref_rec n1 v1 d1).\nProof.\npose proof fv_def_open_def_wrt_varref_rec_lower_fv_defs_open_defs_wrt_varref_rec_lower_fv_val_open_val_wrt_varref_rec_lower_fv_trm_open_trm_wrt_varref_rec_lower_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_def_open_def_wrt_varref_rec_lower : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_defs_open_defs_wrt_varref_rec_lower :\nforall defs1 v1 n1,\n  fv_defs defs1 [<=] fv_defs (open_defs_wrt_varref_rec n1 v1 defs1).\nProof.\npose proof fv_def_open_def_wrt_varref_rec_lower_fv_defs_open_defs_wrt_varref_rec_lower_fv_val_open_val_wrt_varref_rec_lower_fv_trm_open_trm_wrt_varref_rec_lower_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_defs_open_defs_wrt_varref_rec_lower : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_val_open_val_wrt_varref_rec_lower :\nforall val1 v1 n1,\n  fv_val val1 [<=] fv_val (open_val_wrt_varref_rec n1 v1 val1).\nProof.\npose proof fv_def_open_def_wrt_varref_rec_lower_fv_defs_open_defs_wrt_varref_rec_lower_fv_val_open_val_wrt_varref_rec_lower_fv_trm_open_trm_wrt_varref_rec_lower_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_val_open_val_wrt_varref_rec_lower : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_trm_open_trm_wrt_varref_rec_lower :\nforall t1 v1 n1,\n  fv_trm t1 [<=] fv_trm (open_trm_wrt_varref_rec n1 v1 t1).\nProof.\npose proof fv_def_open_def_wrt_varref_rec_lower_fv_defs_open_defs_wrt_varref_rec_lower_fv_val_open_val_wrt_varref_rec_lower_fv_trm_open_trm_wrt_varref_rec_lower_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_trm_open_trm_wrt_varref_rec_lower : lngen.\n\n(* end hide *)\n\nLemma fv_varref_open_varref_wrt_varref_lower :\nforall v1 v2,\n  fv_varref v1 [<=] fv_varref (open_varref_wrt_varref v1 v2).\nProof.\nunfold open_varref_wrt_varref; default_simp.\nQed.\n\nHint Resolve fv_varref_open_varref_wrt_varref_lower : lngen.\n\nLemma fv_typ_open_typ_wrt_varref_lower :\nforall T1 v1,\n  fv_typ T1 [<=] fv_typ (open_typ_wrt_varref T1 v1).\nProof.\nunfold open_typ_wrt_varref; default_simp.\nQed.\n\nHint Resolve fv_typ_open_typ_wrt_varref_lower : lngen.\n\nLemma fv_dec_open_dec_wrt_varref_lower :\nforall dec1 v1,\n  fv_dec dec1 [<=] fv_dec (open_dec_wrt_varref dec1 v1).\nProof.\nunfold open_dec_wrt_varref; default_simp.\nQed.\n\nHint Resolve fv_dec_open_dec_wrt_varref_lower : lngen.\n\nLemma fv_def_open_def_wrt_varref_lower :\nforall d1 v1,\n  fv_def d1 [<=] fv_def (open_def_wrt_varref d1 v1).\nProof.\nunfold open_def_wrt_varref; default_simp.\nQed.\n\nHint Resolve fv_def_open_def_wrt_varref_lower : lngen.\n\nLemma fv_defs_open_defs_wrt_varref_lower :\nforall defs1 v1,\n  fv_defs defs1 [<=] fv_defs (open_defs_wrt_varref defs1 v1).\nProof.\nunfold open_defs_wrt_varref; default_simp.\nQed.\n\nHint Resolve fv_defs_open_defs_wrt_varref_lower : lngen.\n\nLemma fv_val_open_val_wrt_varref_lower :\nforall val1 v1,\n  fv_val val1 [<=] fv_val (open_val_wrt_varref val1 v1).\nProof.\nunfold open_val_wrt_varref; default_simp.\nQed.\n\nHint Resolve fv_val_open_val_wrt_varref_lower : lngen.\n\nLemma fv_trm_open_trm_wrt_varref_lower :\nforall t1 v1,\n  fv_trm t1 [<=] fv_trm (open_trm_wrt_varref t1 v1).\nProof.\nunfold open_trm_wrt_varref; default_simp.\nQed.\n\nHint Resolve fv_trm_open_trm_wrt_varref_lower : lngen.\n\n(* begin hide *)\n\nLemma fv_varref_open_varref_wrt_varref_rec_upper_mutual :\n(forall v1 v2 n1,\n  fv_varref (open_varref_wrt_varref_rec n1 v2 v1) [<=] fv_varref v2 `union` fv_varref v1).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_varref_open_varref_wrt_varref_rec_upper :\nforall v1 v2 n1,\n  fv_varref (open_varref_wrt_varref_rec n1 v2 v1) [<=] fv_varref v2 `union` fv_varref v1.\nProof.\npose proof fv_varref_open_varref_wrt_varref_rec_upper_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_varref_open_varref_wrt_varref_rec_upper : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_typ_open_typ_wrt_varref_rec_upper_fv_dec_open_dec_wrt_varref_rec_upper_mutual :\n(forall T1 v1 n1,\n  fv_typ (open_typ_wrt_varref_rec n1 v1 T1) [<=] fv_varref v1 `union` fv_typ T1) /\\\n(forall dec1 v1 n1,\n  fv_dec (open_dec_wrt_varref_rec n1 v1 dec1) [<=] fv_varref v1 `union` fv_dec dec1).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_typ_open_typ_wrt_varref_rec_upper :\nforall T1 v1 n1,\n  fv_typ (open_typ_wrt_varref_rec n1 v1 T1) [<=] fv_varref v1 `union` fv_typ T1.\nProof.\npose proof fv_typ_open_typ_wrt_varref_rec_upper_fv_dec_open_dec_wrt_varref_rec_upper_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_typ_open_typ_wrt_varref_rec_upper : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_dec_open_dec_wrt_varref_rec_upper :\nforall dec1 v1 n1,\n  fv_dec (open_dec_wrt_varref_rec n1 v1 dec1) [<=] fv_varref v1 `union` fv_dec dec1.\nProof.\npose proof fv_typ_open_typ_wrt_varref_rec_upper_fv_dec_open_dec_wrt_varref_rec_upper_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_dec_open_dec_wrt_varref_rec_upper : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_def_open_def_wrt_varref_rec_upper_fv_defs_open_defs_wrt_varref_rec_upper_fv_val_open_val_wrt_varref_rec_upper_fv_trm_open_trm_wrt_varref_rec_upper_mutual :\n(forall d1 v1 n1,\n  fv_def (open_def_wrt_varref_rec n1 v1 d1) [<=] fv_varref v1 `union` fv_def d1) /\\\n(forall defs1 v1 n1,\n  fv_defs (open_defs_wrt_varref_rec n1 v1 defs1) [<=] fv_varref v1 `union` fv_defs defs1) /\\\n(forall val1 v1 n1,\n  fv_val (open_val_wrt_varref_rec n1 v1 val1) [<=] fv_varref v1 `union` fv_val val1) /\\\n(forall t1 v1 n1,\n  fv_trm (open_trm_wrt_varref_rec n1 v1 t1) [<=] fv_varref v1 `union` fv_trm t1).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_def_open_def_wrt_varref_rec_upper :\nforall d1 v1 n1,\n  fv_def (open_def_wrt_varref_rec n1 v1 d1) [<=] fv_varref v1 `union` fv_def d1.\nProof.\npose proof fv_def_open_def_wrt_varref_rec_upper_fv_defs_open_defs_wrt_varref_rec_upper_fv_val_open_val_wrt_varref_rec_upper_fv_trm_open_trm_wrt_varref_rec_upper_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_def_open_def_wrt_varref_rec_upper : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_defs_open_defs_wrt_varref_rec_upper :\nforall defs1 v1 n1,\n  fv_defs (open_defs_wrt_varref_rec n1 v1 defs1) [<=] fv_varref v1 `union` fv_defs defs1.\nProof.\npose proof fv_def_open_def_wrt_varref_rec_upper_fv_defs_open_defs_wrt_varref_rec_upper_fv_val_open_val_wrt_varref_rec_upper_fv_trm_open_trm_wrt_varref_rec_upper_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_defs_open_defs_wrt_varref_rec_upper : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_val_open_val_wrt_varref_rec_upper :\nforall val1 v1 n1,\n  fv_val (open_val_wrt_varref_rec n1 v1 val1) [<=] fv_varref v1 `union` fv_val val1.\nProof.\npose proof fv_def_open_def_wrt_varref_rec_upper_fv_defs_open_defs_wrt_varref_rec_upper_fv_val_open_val_wrt_varref_rec_upper_fv_trm_open_trm_wrt_varref_rec_upper_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_val_open_val_wrt_varref_rec_upper : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_trm_open_trm_wrt_varref_rec_upper :\nforall t1 v1 n1,\n  fv_trm (open_trm_wrt_varref_rec n1 v1 t1) [<=] fv_varref v1 `union` fv_trm t1.\nProof.\npose proof fv_def_open_def_wrt_varref_rec_upper_fv_defs_open_defs_wrt_varref_rec_upper_fv_val_open_val_wrt_varref_rec_upper_fv_trm_open_trm_wrt_varref_rec_upper_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_trm_open_trm_wrt_varref_rec_upper : lngen.\n\n(* end hide *)\n\nLemma fv_varref_open_varref_wrt_varref_upper :\nforall v1 v2,\n  fv_varref (open_varref_wrt_varref v1 v2) [<=] fv_varref v2 `union` fv_varref v1.\nProof.\nunfold open_varref_wrt_varref; default_simp.\nQed.\n\nHint Resolve fv_varref_open_varref_wrt_varref_upper : lngen.\n\nLemma fv_typ_open_typ_wrt_varref_upper :\nforall T1 v1,\n  fv_typ (open_typ_wrt_varref T1 v1) [<=] fv_varref v1 `union` fv_typ T1.\nProof.\nunfold open_typ_wrt_varref; default_simp.\nQed.\n\nHint Resolve fv_typ_open_typ_wrt_varref_upper : lngen.\n\nLemma fv_dec_open_dec_wrt_varref_upper :\nforall dec1 v1,\n  fv_dec (open_dec_wrt_varref dec1 v1) [<=] fv_varref v1 `union` fv_dec dec1.\nProof.\nunfold open_dec_wrt_varref; default_simp.\nQed.\n\nHint Resolve fv_dec_open_dec_wrt_varref_upper : lngen.\n\nLemma fv_def_open_def_wrt_varref_upper :\nforall d1 v1,\n  fv_def (open_def_wrt_varref d1 v1) [<=] fv_varref v1 `union` fv_def d1.\nProof.\nunfold open_def_wrt_varref; default_simp.\nQed.\n\nHint Resolve fv_def_open_def_wrt_varref_upper : lngen.\n\nLemma fv_defs_open_defs_wrt_varref_upper :\nforall defs1 v1,\n  fv_defs (open_defs_wrt_varref defs1 v1) [<=] fv_varref v1 `union` fv_defs defs1.\nProof.\nunfold open_defs_wrt_varref; default_simp.\nQed.\n\nHint Resolve fv_defs_open_defs_wrt_varref_upper : lngen.\n\nLemma fv_val_open_val_wrt_varref_upper :\nforall val1 v1,\n  fv_val (open_val_wrt_varref val1 v1) [<=] fv_varref v1 `union` fv_val val1.\nProof.\nunfold open_val_wrt_varref; default_simp.\nQed.\n\nHint Resolve fv_val_open_val_wrt_varref_upper : lngen.\n\nLemma fv_trm_open_trm_wrt_varref_upper :\nforall t1 v1,\n  fv_trm (open_trm_wrt_varref t1 v1) [<=] fv_varref v1 `union` fv_trm t1.\nProof.\nunfold open_trm_wrt_varref; default_simp.\nQed.\n\nHint Resolve fv_trm_open_trm_wrt_varref_upper : lngen.\n\n(* begin hide *)\n\nLemma fv_varref_subst_varref_fresh_mutual :\n(forall v1 v2 x1,\n  x1 `notin` fv_varref v1 ->\n  fv_varref (subst_varref v2 x1 v1) [=] fv_varref v1).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\nLemma fv_varref_subst_varref_fresh :\nforall v1 v2 x1,\n  x1 `notin` fv_varref v1 ->\n  fv_varref (subst_varref v2 x1 v1) [=] fv_varref v1.\nProof.\npose proof fv_varref_subst_varref_fresh_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_varref_subst_varref_fresh : lngen.\nHint Rewrite fv_varref_subst_varref_fresh using solve [auto] : lngen.\n\n(* begin hide *)\n\nLemma fv_typ_subst_typ_fresh_fv_dec_subst_dec_fresh_mutual :\n(forall T1 v1 x1,\n  x1 `notin` fv_typ T1 ->\n  fv_typ (subst_typ v1 x1 T1) [=] fv_typ T1) /\\\n(forall dec1 v1 x1,\n  x1 `notin` fv_dec dec1 ->\n  fv_dec (subst_dec v1 x1 dec1) [=] fv_dec dec1).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\nLemma fv_typ_subst_typ_fresh :\nforall T1 v1 x1,\n  x1 `notin` fv_typ T1 ->\n  fv_typ (subst_typ v1 x1 T1) [=] fv_typ T1.\nProof.\npose proof fv_typ_subst_typ_fresh_fv_dec_subst_dec_fresh_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_typ_subst_typ_fresh : lngen.\nHint Rewrite fv_typ_subst_typ_fresh using solve [auto] : lngen.\n\nLemma fv_dec_subst_dec_fresh :\nforall dec1 v1 x1,\n  x1 `notin` fv_dec dec1 ->\n  fv_dec (subst_dec v1 x1 dec1) [=] fv_dec dec1.\nProof.\npose proof fv_typ_subst_typ_fresh_fv_dec_subst_dec_fresh_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_dec_subst_dec_fresh : lngen.\nHint Rewrite fv_dec_subst_dec_fresh using solve [auto] : lngen.\n\n(* begin hide *)\n\nLemma fv_def_subst_def_fresh_fv_defs_subst_defs_fresh_fv_val_subst_val_fresh_fv_trm_subst_trm_fresh_mutual :\n(forall d1 v1 x1,\n  x1 `notin` fv_def d1 ->\n  fv_def (subst_def v1 x1 d1) [=] fv_def d1) /\\\n(forall defs1 v1 x1,\n  x1 `notin` fv_defs defs1 ->\n  fv_defs (subst_defs v1 x1 defs1) [=] fv_defs defs1) /\\\n(forall val1 v1 x1,\n  x1 `notin` fv_val val1 ->\n  fv_val (subst_val v1 x1 val1) [=] fv_val val1) /\\\n(forall t1 v1 x1,\n  x1 `notin` fv_trm t1 ->\n  fv_trm (subst_trm v1 x1 t1) [=] fv_trm t1).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\nLemma fv_def_subst_def_fresh :\nforall d1 v1 x1,\n  x1 `notin` fv_def d1 ->\n  fv_def (subst_def v1 x1 d1) [=] fv_def d1.\nProof.\npose proof fv_def_subst_def_fresh_fv_defs_subst_defs_fresh_fv_val_subst_val_fresh_fv_trm_subst_trm_fresh_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_def_subst_def_fresh : lngen.\nHint Rewrite fv_def_subst_def_fresh using solve [auto] : lngen.\n\nLemma fv_defs_subst_defs_fresh :\nforall defs1 v1 x1,\n  x1 `notin` fv_defs defs1 ->\n  fv_defs (subst_defs v1 x1 defs1) [=] fv_defs defs1.\nProof.\npose proof fv_def_subst_def_fresh_fv_defs_subst_defs_fresh_fv_val_subst_val_fresh_fv_trm_subst_trm_fresh_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_defs_subst_defs_fresh : lngen.\nHint Rewrite fv_defs_subst_defs_fresh using solve [auto] : lngen.\n\nLemma fv_val_subst_val_fresh :\nforall val1 v1 x1,\n  x1 `notin` fv_val val1 ->\n  fv_val (subst_val v1 x1 val1) [=] fv_val val1.\nProof.\npose proof fv_def_subst_def_fresh_fv_defs_subst_defs_fresh_fv_val_subst_val_fresh_fv_trm_subst_trm_fresh_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_val_subst_val_fresh : lngen.\nHint Rewrite fv_val_subst_val_fresh using solve [auto] : lngen.\n\nLemma fv_trm_subst_trm_fresh :\nforall t1 v1 x1,\n  x1 `notin` fv_trm t1 ->\n  fv_trm (subst_trm v1 x1 t1) [=] fv_trm t1.\nProof.\npose proof fv_def_subst_def_fresh_fv_defs_subst_defs_fresh_fv_val_subst_val_fresh_fv_trm_subst_trm_fresh_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_trm_subst_trm_fresh : lngen.\nHint Rewrite fv_trm_subst_trm_fresh using solve [auto] : lngen.\n\n(* begin hide *)\n\nLemma fv_varref_subst_varref_lower_mutual :\n(forall v1 v2 x1,\n  remove x1 (fv_varref v1) [<=] fv_varref (subst_varref v2 x1 v1)).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\nLemma fv_varref_subst_varref_lower :\nforall v1 v2 x1,\n  remove x1 (fv_varref v1) [<=] fv_varref (subst_varref v2 x1 v1).\nProof.\npose proof fv_varref_subst_varref_lower_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_varref_subst_varref_lower : lngen.\n\n(* begin hide *)\n\nLemma fv_typ_subst_typ_lower_fv_dec_subst_dec_lower_mutual :\n(forall T1 v1 x1,\n  remove x1 (fv_typ T1) [<=] fv_typ (subst_typ v1 x1 T1)) /\\\n(forall dec1 v1 x1,\n  remove x1 (fv_dec dec1) [<=] fv_dec (subst_dec v1 x1 dec1)).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\nLemma fv_typ_subst_typ_lower :\nforall T1 v1 x1,\n  remove x1 (fv_typ T1) [<=] fv_typ (subst_typ v1 x1 T1).\nProof.\npose proof fv_typ_subst_typ_lower_fv_dec_subst_dec_lower_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_typ_subst_typ_lower : lngen.\n\nLemma fv_dec_subst_dec_lower :\nforall dec1 v1 x1,\n  remove x1 (fv_dec dec1) [<=] fv_dec (subst_dec v1 x1 dec1).\nProof.\npose proof fv_typ_subst_typ_lower_fv_dec_subst_dec_lower_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_dec_subst_dec_lower : lngen.\n\n(* begin hide *)\n\nLemma fv_def_subst_def_lower_fv_defs_subst_defs_lower_fv_val_subst_val_lower_fv_trm_subst_trm_lower_mutual :\n(forall d1 v1 x1,\n  remove x1 (fv_def d1) [<=] fv_def (subst_def v1 x1 d1)) /\\\n(forall defs1 v1 x1,\n  remove x1 (fv_defs defs1) [<=] fv_defs (subst_defs v1 x1 defs1)) /\\\n(forall val1 v1 x1,\n  remove x1 (fv_val val1) [<=] fv_val (subst_val v1 x1 val1)) /\\\n(forall t1 v1 x1,\n  remove x1 (fv_trm t1) [<=] fv_trm (subst_trm v1 x1 t1)).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\nLemma fv_def_subst_def_lower :\nforall d1 v1 x1,\n  remove x1 (fv_def d1) [<=] fv_def (subst_def v1 x1 d1).\nProof.\npose proof fv_def_subst_def_lower_fv_defs_subst_defs_lower_fv_val_subst_val_lower_fv_trm_subst_trm_lower_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_def_subst_def_lower : lngen.\n\nLemma fv_defs_subst_defs_lower :\nforall defs1 v1 x1,\n  remove x1 (fv_defs defs1) [<=] fv_defs (subst_defs v1 x1 defs1).\nProof.\npose proof fv_def_subst_def_lower_fv_defs_subst_defs_lower_fv_val_subst_val_lower_fv_trm_subst_trm_lower_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_defs_subst_defs_lower : lngen.\n\nLemma fv_val_subst_val_lower :\nforall val1 v1 x1,\n  remove x1 (fv_val val1) [<=] fv_val (subst_val v1 x1 val1).\nProof.\npose proof fv_def_subst_def_lower_fv_defs_subst_defs_lower_fv_val_subst_val_lower_fv_trm_subst_trm_lower_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_val_subst_val_lower : lngen.\n\nLemma fv_trm_subst_trm_lower :\nforall t1 v1 x1,\n  remove x1 (fv_trm t1) [<=] fv_trm (subst_trm v1 x1 t1).\nProof.\npose proof fv_def_subst_def_lower_fv_defs_subst_defs_lower_fv_val_subst_val_lower_fv_trm_subst_trm_lower_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_trm_subst_trm_lower : lngen.\n\n(* begin hide *)\n\nLemma fv_varref_subst_varref_notin_mutual :\n(forall v1 v2 x1 x2,\n  x2 `notin` fv_varref v1 ->\n  x2 `notin` fv_varref v2 ->\n  x2 `notin` fv_varref (subst_varref v2 x1 v1)).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\nLemma fv_varref_subst_varref_notin :\nforall v1 v2 x1 x2,\n  x2 `notin` fv_varref v1 ->\n  x2 `notin` fv_varref v2 ->\n  x2 `notin` fv_varref (subst_varref v2 x1 v1).\nProof.\npose proof fv_varref_subst_varref_notin_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_varref_subst_varref_notin : lngen.\n\n(* begin hide *)\n\nLemma fv_typ_subst_typ_notin_fv_dec_subst_dec_notin_mutual :\n(forall T1 v1 x1 x2,\n  x2 `notin` fv_typ T1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 `notin` fv_typ (subst_typ v1 x1 T1)) /\\\n(forall dec1 v1 x1 x2,\n  x2 `notin` fv_dec dec1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 `notin` fv_dec (subst_dec v1 x1 dec1)).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\nLemma fv_typ_subst_typ_notin :\nforall T1 v1 x1 x2,\n  x2 `notin` fv_typ T1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 `notin` fv_typ (subst_typ v1 x1 T1).\nProof.\npose proof fv_typ_subst_typ_notin_fv_dec_subst_dec_notin_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_typ_subst_typ_notin : lngen.\n\nLemma fv_dec_subst_dec_notin :\nforall dec1 v1 x1 x2,\n  x2 `notin` fv_dec dec1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 `notin` fv_dec (subst_dec v1 x1 dec1).\nProof.\npose proof fv_typ_subst_typ_notin_fv_dec_subst_dec_notin_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_dec_subst_dec_notin : lngen.\n\n(* begin hide *)\n\nLemma fv_def_subst_def_notin_fv_defs_subst_defs_notin_fv_val_subst_val_notin_fv_trm_subst_trm_notin_mutual :\n(forall d1 v1 x1 x2,\n  x2 `notin` fv_def d1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 `notin` fv_def (subst_def v1 x1 d1)) /\\\n(forall defs1 v1 x1 x2,\n  x2 `notin` fv_defs defs1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 `notin` fv_defs (subst_defs v1 x1 defs1)) /\\\n(forall val1 v1 x1 x2,\n  x2 `notin` fv_val val1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 `notin` fv_val (subst_val v1 x1 val1)) /\\\n(forall t1 v1 x1 x2,\n  x2 `notin` fv_trm t1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 `notin` fv_trm (subst_trm v1 x1 t1)).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\nLemma fv_def_subst_def_notin :\nforall d1 v1 x1 x2,\n  x2 `notin` fv_def d1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 `notin` fv_def (subst_def v1 x1 d1).\nProof.\npose proof fv_def_subst_def_notin_fv_defs_subst_defs_notin_fv_val_subst_val_notin_fv_trm_subst_trm_notin_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_def_subst_def_notin : lngen.\n\nLemma fv_defs_subst_defs_notin :\nforall defs1 v1 x1 x2,\n  x2 `notin` fv_defs defs1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 `notin` fv_defs (subst_defs v1 x1 defs1).\nProof.\npose proof fv_def_subst_def_notin_fv_defs_subst_defs_notin_fv_val_subst_val_notin_fv_trm_subst_trm_notin_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_defs_subst_defs_notin : lngen.\n\nLemma fv_val_subst_val_notin :\nforall val1 v1 x1 x2,\n  x2 `notin` fv_val val1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 `notin` fv_val (subst_val v1 x1 val1).\nProof.\npose proof fv_def_subst_def_notin_fv_defs_subst_defs_notin_fv_val_subst_val_notin_fv_trm_subst_trm_notin_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_val_subst_val_notin : lngen.\n\nLemma fv_trm_subst_trm_notin :\nforall t1 v1 x1 x2,\n  x2 `notin` fv_trm t1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 `notin` fv_trm (subst_trm v1 x1 t1).\nProof.\npose proof fv_def_subst_def_notin_fv_defs_subst_defs_notin_fv_val_subst_val_notin_fv_trm_subst_trm_notin_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_trm_subst_trm_notin : lngen.\n\n(* begin hide *)\n\nLemma fv_varref_subst_varref_upper_mutual :\n(forall v1 v2 x1,\n  fv_varref (subst_varref v2 x1 v1) [<=] fv_varref v2 `union` remove x1 (fv_varref v1)).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\nLemma fv_varref_subst_varref_upper :\nforall v1 v2 x1,\n  fv_varref (subst_varref v2 x1 v1) [<=] fv_varref v2 `union` remove x1 (fv_varref v1).\nProof.\npose proof fv_varref_subst_varref_upper_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_varref_subst_varref_upper : lngen.\n\n(* begin hide *)\n\nLemma fv_typ_subst_typ_upper_fv_dec_subst_dec_upper_mutual :\n(forall T1 v1 x1,\n  fv_typ (subst_typ v1 x1 T1) [<=] fv_varref v1 `union` remove x1 (fv_typ T1)) /\\\n(forall dec1 v1 x1,\n  fv_dec (subst_dec v1 x1 dec1) [<=] fv_varref v1 `union` remove x1 (fv_dec dec1)).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\nLemma fv_typ_subst_typ_upper :\nforall T1 v1 x1,\n  fv_typ (subst_typ v1 x1 T1) [<=] fv_varref v1 `union` remove x1 (fv_typ T1).\nProof.\npose proof fv_typ_subst_typ_upper_fv_dec_subst_dec_upper_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_typ_subst_typ_upper : lngen.\n\nLemma fv_dec_subst_dec_upper :\nforall dec1 v1 x1,\n  fv_dec (subst_dec v1 x1 dec1) [<=] fv_varref v1 `union` remove x1 (fv_dec dec1).\nProof.\npose proof fv_typ_subst_typ_upper_fv_dec_subst_dec_upper_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_dec_subst_dec_upper : lngen.\n\n(* begin hide *)\n\nLemma fv_def_subst_def_upper_fv_defs_subst_defs_upper_fv_val_subst_val_upper_fv_trm_subst_trm_upper_mutual :\n(forall d1 v1 x1,\n  fv_def (subst_def v1 x1 d1) [<=] fv_varref v1 `union` remove x1 (fv_def d1)) /\\\n(forall defs1 v1 x1,\n  fv_defs (subst_defs v1 x1 defs1) [<=] fv_varref v1 `union` remove x1 (fv_defs defs1)) /\\\n(forall val1 v1 x1,\n  fv_val (subst_val v1 x1 val1) [<=] fv_varref v1 `union` remove x1 (fv_val val1)) /\\\n(forall t1 v1 x1,\n  fv_trm (subst_trm v1 x1 t1) [<=] fv_varref v1 `union` remove x1 (fv_trm t1)).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\nLemma fv_def_subst_def_upper :\nforall d1 v1 x1,\n  fv_def (subst_def v1 x1 d1) [<=] fv_varref v1 `union` remove x1 (fv_def d1).\nProof.\npose proof fv_def_subst_def_upper_fv_defs_subst_defs_upper_fv_val_subst_val_upper_fv_trm_subst_trm_upper_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_def_subst_def_upper : lngen.\n\nLemma fv_defs_subst_defs_upper :\nforall defs1 v1 x1,\n  fv_defs (subst_defs v1 x1 defs1) [<=] fv_varref v1 `union` remove x1 (fv_defs defs1).\nProof.\npose proof fv_def_subst_def_upper_fv_defs_subst_defs_upper_fv_val_subst_val_upper_fv_trm_subst_trm_upper_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_defs_subst_defs_upper : lngen.\n\nLemma fv_val_subst_val_upper :\nforall val1 v1 x1,\n  fv_val (subst_val v1 x1 val1) [<=] fv_varref v1 `union` remove x1 (fv_val val1).\nProof.\npose proof fv_def_subst_def_upper_fv_defs_subst_defs_upper_fv_val_subst_val_upper_fv_trm_subst_trm_upper_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_val_subst_val_upper : lngen.\n\nLemma fv_trm_subst_trm_upper :\nforall t1 v1 x1,\n  fv_trm (subst_trm v1 x1 t1) [<=] fv_varref v1 `union` remove x1 (fv_trm t1).\nProof.\npose proof fv_def_subst_def_upper_fv_defs_subst_defs_upper_fv_val_subst_val_upper_fv_trm_subst_trm_upper_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_trm_subst_trm_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_varref_close_varref_wrt_varref_rec_mutual :\n(forall v2 v1 x1 x2 n1,\n  degree_varref_wrt_varref n1 v1 ->\n  x1 <> x2 ->\n  x2 `notin` fv_varref v1 ->\n  subst_varref v1 x1 (close_varref_wrt_varref_rec n1 x2 v2) = close_varref_wrt_varref_rec n1 x2 (subst_varref v1 x1 v2)).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_varref_close_varref_wrt_varref_rec :\nforall v2 v1 x1 x2 n1,\n  degree_varref_wrt_varref n1 v1 ->\n  x1 <> x2 ->\n  x2 `notin` fv_varref v1 ->\n  subst_varref v1 x1 (close_varref_wrt_varref_rec n1 x2 v2) = close_varref_wrt_varref_rec n1 x2 (subst_varref v1 x1 v2).\nProof.\npose proof subst_varref_close_varref_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_varref_close_varref_wrt_varref_rec : lngen.\n\n(* begin hide *)\n\nLemma subst_typ_close_typ_wrt_varref_rec_subst_dec_close_dec_wrt_varref_rec_mutual :\n(forall T1 v1 x1 x2 n1,\n  degree_varref_wrt_varref n1 v1 ->\n  x1 <> x2 ->\n  x2 `notin` fv_varref v1 ->\n  subst_typ v1 x1 (close_typ_wrt_varref_rec n1 x2 T1) = close_typ_wrt_varref_rec n1 x2 (subst_typ v1 x1 T1)) /\\\n(forall dec1 v1 x1 x2 n1,\n  degree_varref_wrt_varref n1 v1 ->\n  x1 <> x2 ->\n  x2 `notin` fv_varref v1 ->\n  subst_dec v1 x1 (close_dec_wrt_varref_rec n1 x2 dec1) = close_dec_wrt_varref_rec n1 x2 (subst_dec v1 x1 dec1)).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_typ_close_typ_wrt_varref_rec :\nforall T1 v1 x1 x2 n1,\n  degree_varref_wrt_varref n1 v1 ->\n  x1 <> x2 ->\n  x2 `notin` fv_varref v1 ->\n  subst_typ v1 x1 (close_typ_wrt_varref_rec n1 x2 T1) = close_typ_wrt_varref_rec n1 x2 (subst_typ v1 x1 T1).\nProof.\npose proof subst_typ_close_typ_wrt_varref_rec_subst_dec_close_dec_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_typ_close_typ_wrt_varref_rec : lngen.\n\nLemma subst_dec_close_dec_wrt_varref_rec :\nforall dec1 v1 x1 x2 n1,\n  degree_varref_wrt_varref n1 v1 ->\n  x1 <> x2 ->\n  x2 `notin` fv_varref v1 ->\n  subst_dec v1 x1 (close_dec_wrt_varref_rec n1 x2 dec1) = close_dec_wrt_varref_rec n1 x2 (subst_dec v1 x1 dec1).\nProof.\npose proof subst_typ_close_typ_wrt_varref_rec_subst_dec_close_dec_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_dec_close_dec_wrt_varref_rec : lngen.\n\n(* begin hide *)\n\nLemma subst_def_close_def_wrt_varref_rec_subst_defs_close_defs_wrt_varref_rec_subst_val_close_val_wrt_varref_rec_subst_trm_close_trm_wrt_varref_rec_mutual :\n(forall d1 v1 x1 x2 n1,\n  degree_varref_wrt_varref n1 v1 ->\n  x1 <> x2 ->\n  x2 `notin` fv_varref v1 ->\n  subst_def v1 x1 (close_def_wrt_varref_rec n1 x2 d1) = close_def_wrt_varref_rec n1 x2 (subst_def v1 x1 d1)) /\\\n(forall defs1 v1 x1 x2 n1,\n  degree_varref_wrt_varref n1 v1 ->\n  x1 <> x2 ->\n  x2 `notin` fv_varref v1 ->\n  subst_defs v1 x1 (close_defs_wrt_varref_rec n1 x2 defs1) = close_defs_wrt_varref_rec n1 x2 (subst_defs v1 x1 defs1)) /\\\n(forall val1 v1 x1 x2 n1,\n  degree_varref_wrt_varref n1 v1 ->\n  x1 <> x2 ->\n  x2 `notin` fv_varref v1 ->\n  subst_val v1 x1 (close_val_wrt_varref_rec n1 x2 val1) = close_val_wrt_varref_rec n1 x2 (subst_val v1 x1 val1)) /\\\n(forall t1 v1 x1 x2 n1,\n  degree_varref_wrt_varref n1 v1 ->\n  x1 <> x2 ->\n  x2 `notin` fv_varref v1 ->\n  subst_trm v1 x1 (close_trm_wrt_varref_rec n1 x2 t1) = close_trm_wrt_varref_rec n1 x2 (subst_trm v1 x1 t1)).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_def_close_def_wrt_varref_rec :\nforall d1 v1 x1 x2 n1,\n  degree_varref_wrt_varref n1 v1 ->\n  x1 <> x2 ->\n  x2 `notin` fv_varref v1 ->\n  subst_def v1 x1 (close_def_wrt_varref_rec n1 x2 d1) = close_def_wrt_varref_rec n1 x2 (subst_def v1 x1 d1).\nProof.\npose proof subst_def_close_def_wrt_varref_rec_subst_defs_close_defs_wrt_varref_rec_subst_val_close_val_wrt_varref_rec_subst_trm_close_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_def_close_def_wrt_varref_rec : lngen.\n\nLemma subst_defs_close_defs_wrt_varref_rec :\nforall defs1 v1 x1 x2 n1,\n  degree_varref_wrt_varref n1 v1 ->\n  x1 <> x2 ->\n  x2 `notin` fv_varref v1 ->\n  subst_defs v1 x1 (close_defs_wrt_varref_rec n1 x2 defs1) = close_defs_wrt_varref_rec n1 x2 (subst_defs v1 x1 defs1).\nProof.\npose proof subst_def_close_def_wrt_varref_rec_subst_defs_close_defs_wrt_varref_rec_subst_val_close_val_wrt_varref_rec_subst_trm_close_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_defs_close_defs_wrt_varref_rec : lngen.\n\nLemma subst_val_close_val_wrt_varref_rec :\nforall val1 v1 x1 x2 n1,\n  degree_varref_wrt_varref n1 v1 ->\n  x1 <> x2 ->\n  x2 `notin` fv_varref v1 ->\n  subst_val v1 x1 (close_val_wrt_varref_rec n1 x2 val1) = close_val_wrt_varref_rec n1 x2 (subst_val v1 x1 val1).\nProof.\npose proof subst_def_close_def_wrt_varref_rec_subst_defs_close_defs_wrt_varref_rec_subst_val_close_val_wrt_varref_rec_subst_trm_close_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_val_close_val_wrt_varref_rec : lngen.\n\nLemma subst_trm_close_trm_wrt_varref_rec :\nforall t1 v1 x1 x2 n1,\n  degree_varref_wrt_varref n1 v1 ->\n  x1 <> x2 ->\n  x2 `notin` fv_varref v1 ->\n  subst_trm v1 x1 (close_trm_wrt_varref_rec n1 x2 t1) = close_trm_wrt_varref_rec n1 x2 (subst_trm v1 x1 t1).\nProof.\npose proof subst_def_close_def_wrt_varref_rec_subst_defs_close_defs_wrt_varref_rec_subst_val_close_val_wrt_varref_rec_subst_trm_close_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_trm_close_trm_wrt_varref_rec : lngen.\n\nLemma subst_varref_close_varref_wrt_varref :\nforall v2 v1 x1 x2,\n  lc_varref v1 ->  x1 <> x2 ->\n  x2 `notin` fv_varref v1 ->\n  subst_varref v1 x1 (close_varref_wrt_varref x2 v2) = close_varref_wrt_varref x2 (subst_varref v1 x1 v2).\nProof.\nunfold close_varref_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_varref_close_varref_wrt_varref : lngen.\n\nLemma subst_typ_close_typ_wrt_varref :\nforall T1 v1 x1 x2,\n  lc_varref v1 ->  x1 <> x2 ->\n  x2 `notin` fv_varref v1 ->\n  subst_typ v1 x1 (close_typ_wrt_varref x2 T1) = close_typ_wrt_varref x2 (subst_typ v1 x1 T1).\nProof.\nunfold close_typ_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_typ_close_typ_wrt_varref : lngen.\n\nLemma subst_dec_close_dec_wrt_varref :\nforall dec1 v1 x1 x2,\n  lc_varref v1 ->  x1 <> x2 ->\n  x2 `notin` fv_varref v1 ->\n  subst_dec v1 x1 (close_dec_wrt_varref x2 dec1) = close_dec_wrt_varref x2 (subst_dec v1 x1 dec1).\nProof.\nunfold close_dec_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_dec_close_dec_wrt_varref : lngen.\n\nLemma subst_def_close_def_wrt_varref :\nforall d1 v1 x1 x2,\n  lc_varref v1 ->  x1 <> x2 ->\n  x2 `notin` fv_varref v1 ->\n  subst_def v1 x1 (close_def_wrt_varref x2 d1) = close_def_wrt_varref x2 (subst_def v1 x1 d1).\nProof.\nunfold close_def_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_def_close_def_wrt_varref : lngen.\n\nLemma subst_defs_close_defs_wrt_varref :\nforall defs1 v1 x1 x2,\n  lc_varref v1 ->  x1 <> x2 ->\n  x2 `notin` fv_varref v1 ->\n  subst_defs v1 x1 (close_defs_wrt_varref x2 defs1) = close_defs_wrt_varref x2 (subst_defs v1 x1 defs1).\nProof.\nunfold close_defs_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_defs_close_defs_wrt_varref : lngen.\n\nLemma subst_val_close_val_wrt_varref :\nforall val1 v1 x1 x2,\n  lc_varref v1 ->  x1 <> x2 ->\n  x2 `notin` fv_varref v1 ->\n  subst_val v1 x1 (close_val_wrt_varref x2 val1) = close_val_wrt_varref x2 (subst_val v1 x1 val1).\nProof.\nunfold close_val_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_val_close_val_wrt_varref : lngen.\n\nLemma subst_trm_close_trm_wrt_varref :\nforall t1 v1 x1 x2,\n  lc_varref v1 ->  x1 <> x2 ->\n  x2 `notin` fv_varref v1 ->\n  subst_trm v1 x1 (close_trm_wrt_varref x2 t1) = close_trm_wrt_varref x2 (subst_trm v1 x1 t1).\nProof.\nunfold close_trm_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_trm_close_trm_wrt_varref : lngen.\n\n(* begin hide *)\n\nLemma subst_varref_degree_varref_wrt_varref_mutual :\n(forall v1 v2 x1 n1,\n  degree_varref_wrt_varref n1 v1 ->\n  degree_varref_wrt_varref n1 v2 ->\n  degree_varref_wrt_varref n1 (subst_varref v2 x1 v1)).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_varref_degree_varref_wrt_varref :\nforall v1 v2 x1 n1,\n  degree_varref_wrt_varref n1 v1 ->\n  degree_varref_wrt_varref n1 v2 ->\n  degree_varref_wrt_varref n1 (subst_varref v2 x1 v1).\nProof.\npose proof subst_varref_degree_varref_wrt_varref_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_varref_degree_varref_wrt_varref : lngen.\n\n(* begin hide *)\n\nLemma subst_typ_degree_typ_wrt_varref_subst_dec_degree_dec_wrt_varref_mutual :\n(forall T1 v1 x1 n1,\n  degree_typ_wrt_varref n1 T1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  degree_typ_wrt_varref n1 (subst_typ v1 x1 T1)) /\\\n(forall dec1 v1 x1 n1,\n  degree_dec_wrt_varref n1 dec1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  degree_dec_wrt_varref n1 (subst_dec v1 x1 dec1)).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_typ_degree_typ_wrt_varref :\nforall T1 v1 x1 n1,\n  degree_typ_wrt_varref n1 T1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  degree_typ_wrt_varref n1 (subst_typ v1 x1 T1).\nProof.\npose proof subst_typ_degree_typ_wrt_varref_subst_dec_degree_dec_wrt_varref_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_typ_degree_typ_wrt_varref : lngen.\n\nLemma subst_dec_degree_dec_wrt_varref :\nforall dec1 v1 x1 n1,\n  degree_dec_wrt_varref n1 dec1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  degree_dec_wrt_varref n1 (subst_dec v1 x1 dec1).\nProof.\npose proof subst_typ_degree_typ_wrt_varref_subst_dec_degree_dec_wrt_varref_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_dec_degree_dec_wrt_varref : lngen.\n\n(* begin hide *)\n\nLemma subst_def_degree_def_wrt_varref_subst_defs_degree_defs_wrt_varref_subst_val_degree_val_wrt_varref_subst_trm_degree_trm_wrt_varref_mutual :\n(forall d1 v1 x1 n1,\n  degree_def_wrt_varref n1 d1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  degree_def_wrt_varref n1 (subst_def v1 x1 d1)) /\\\n(forall defs1 v1 x1 n1,\n  degree_defs_wrt_varref n1 defs1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  degree_defs_wrt_varref n1 (subst_defs v1 x1 defs1)) /\\\n(forall val1 v1 x1 n1,\n  degree_val_wrt_varref n1 val1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  degree_val_wrt_varref n1 (subst_val v1 x1 val1)) /\\\n(forall t1 v1 x1 n1,\n  degree_trm_wrt_varref n1 t1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  degree_trm_wrt_varref n1 (subst_trm v1 x1 t1)).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_def_degree_def_wrt_varref :\nforall d1 v1 x1 n1,\n  degree_def_wrt_varref n1 d1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  degree_def_wrt_varref n1 (subst_def v1 x1 d1).\nProof.\npose proof subst_def_degree_def_wrt_varref_subst_defs_degree_defs_wrt_varref_subst_val_degree_val_wrt_varref_subst_trm_degree_trm_wrt_varref_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_def_degree_def_wrt_varref : lngen.\n\nLemma subst_defs_degree_defs_wrt_varref :\nforall defs1 v1 x1 n1,\n  degree_defs_wrt_varref n1 defs1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  degree_defs_wrt_varref n1 (subst_defs v1 x1 defs1).\nProof.\npose proof subst_def_degree_def_wrt_varref_subst_defs_degree_defs_wrt_varref_subst_val_degree_val_wrt_varref_subst_trm_degree_trm_wrt_varref_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_defs_degree_defs_wrt_varref : lngen.\n\nLemma subst_val_degree_val_wrt_varref :\nforall val1 v1 x1 n1,\n  degree_val_wrt_varref n1 val1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  degree_val_wrt_varref n1 (subst_val v1 x1 val1).\nProof.\npose proof subst_def_degree_def_wrt_varref_subst_defs_degree_defs_wrt_varref_subst_val_degree_val_wrt_varref_subst_trm_degree_trm_wrt_varref_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_val_degree_val_wrt_varref : lngen.\n\nLemma subst_trm_degree_trm_wrt_varref :\nforall t1 v1 x1 n1,\n  degree_trm_wrt_varref n1 t1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  degree_trm_wrt_varref n1 (subst_trm v1 x1 t1).\nProof.\npose proof subst_def_degree_def_wrt_varref_subst_defs_degree_defs_wrt_varref_subst_val_degree_val_wrt_varref_subst_trm_degree_trm_wrt_varref_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_trm_degree_trm_wrt_varref : lngen.\n\n(* begin hide *)\n\nLemma subst_varref_fresh_eq_mutual :\n(forall v2 v1 x1,\n  x1 `notin` fv_varref v2 ->\n  subst_varref v1 x1 v2 = v2).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_varref_fresh_eq :\nforall v2 v1 x1,\n  x1 `notin` fv_varref v2 ->\n  subst_varref v1 x1 v2 = v2.\nProof.\npose proof subst_varref_fresh_eq_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_varref_fresh_eq : lngen.\nHint Rewrite subst_varref_fresh_eq using solve [auto] : lngen.\n\n(* begin hide *)\n\nLemma subst_typ_fresh_eq_subst_dec_fresh_eq_mutual :\n(forall T1 v1 x1,\n  x1 `notin` fv_typ T1 ->\n  subst_typ v1 x1 T1 = T1) /\\\n(forall dec1 v1 x1,\n  x1 `notin` fv_dec dec1 ->\n  subst_dec v1 x1 dec1 = dec1).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_typ_fresh_eq :\nforall T1 v1 x1,\n  x1 `notin` fv_typ T1 ->\n  subst_typ v1 x1 T1 = T1.\nProof.\npose proof subst_typ_fresh_eq_subst_dec_fresh_eq_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_typ_fresh_eq : lngen.\nHint Rewrite subst_typ_fresh_eq using solve [auto] : lngen.\n\nLemma subst_dec_fresh_eq :\nforall dec1 v1 x1,\n  x1 `notin` fv_dec dec1 ->\n  subst_dec v1 x1 dec1 = dec1.\nProof.\npose proof subst_typ_fresh_eq_subst_dec_fresh_eq_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_dec_fresh_eq : lngen.\nHint Rewrite subst_dec_fresh_eq using solve [auto] : lngen.\n\n(* begin hide *)\n\nLemma subst_def_fresh_eq_subst_defs_fresh_eq_subst_val_fresh_eq_subst_trm_fresh_eq_mutual :\n(forall d1 v1 x1,\n  x1 `notin` fv_def d1 ->\n  subst_def v1 x1 d1 = d1) /\\\n(forall defs1 v1 x1,\n  x1 `notin` fv_defs defs1 ->\n  subst_defs v1 x1 defs1 = defs1) /\\\n(forall val1 v1 x1,\n  x1 `notin` fv_val val1 ->\n  subst_val v1 x1 val1 = val1) /\\\n(forall t1 v1 x1,\n  x1 `notin` fv_trm t1 ->\n  subst_trm v1 x1 t1 = t1).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_def_fresh_eq :\nforall d1 v1 x1,\n  x1 `notin` fv_def d1 ->\n  subst_def v1 x1 d1 = d1.\nProof.\npose proof subst_def_fresh_eq_subst_defs_fresh_eq_subst_val_fresh_eq_subst_trm_fresh_eq_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_def_fresh_eq : lngen.\nHint Rewrite subst_def_fresh_eq using solve [auto] : lngen.\n\nLemma subst_defs_fresh_eq :\nforall defs1 v1 x1,\n  x1 `notin` fv_defs defs1 ->\n  subst_defs v1 x1 defs1 = defs1.\nProof.\npose proof subst_def_fresh_eq_subst_defs_fresh_eq_subst_val_fresh_eq_subst_trm_fresh_eq_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_defs_fresh_eq : lngen.\nHint Rewrite subst_defs_fresh_eq using solve [auto] : lngen.\n\nLemma subst_val_fresh_eq :\nforall val1 v1 x1,\n  x1 `notin` fv_val val1 ->\n  subst_val v1 x1 val1 = val1.\nProof.\npose proof subst_def_fresh_eq_subst_defs_fresh_eq_subst_val_fresh_eq_subst_trm_fresh_eq_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_val_fresh_eq : lngen.\nHint Rewrite subst_val_fresh_eq using solve [auto] : lngen.\n\nLemma subst_trm_fresh_eq :\nforall t1 v1 x1,\n  x1 `notin` fv_trm t1 ->\n  subst_trm v1 x1 t1 = t1.\nProof.\npose proof subst_def_fresh_eq_subst_defs_fresh_eq_subst_val_fresh_eq_subst_trm_fresh_eq_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_trm_fresh_eq : lngen.\nHint Rewrite subst_trm_fresh_eq using solve [auto] : lngen.\n\n(* begin hide *)\n\nLemma subst_varref_fresh_same_mutual :\n(forall v2 v1 x1,\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_varref (subst_varref v1 x1 v2)).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_varref_fresh_same :\nforall v2 v1 x1,\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_varref (subst_varref v1 x1 v2).\nProof.\npose proof subst_varref_fresh_same_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_varref_fresh_same : lngen.\n\n(* begin hide *)\n\nLemma subst_typ_fresh_same_subst_dec_fresh_same_mutual :\n(forall T1 v1 x1,\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_typ (subst_typ v1 x1 T1)) /\\\n(forall dec1 v1 x1,\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_dec (subst_dec v1 x1 dec1)).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_typ_fresh_same :\nforall T1 v1 x1,\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_typ (subst_typ v1 x1 T1).\nProof.\npose proof subst_typ_fresh_same_subst_dec_fresh_same_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_typ_fresh_same : lngen.\n\nLemma subst_dec_fresh_same :\nforall dec1 v1 x1,\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_dec (subst_dec v1 x1 dec1).\nProof.\npose proof subst_typ_fresh_same_subst_dec_fresh_same_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_dec_fresh_same : lngen.\n\n(* begin hide *)\n\nLemma subst_def_fresh_same_subst_defs_fresh_same_subst_val_fresh_same_subst_trm_fresh_same_mutual :\n(forall d1 v1 x1,\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_def (subst_def v1 x1 d1)) /\\\n(forall defs1 v1 x1,\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_defs (subst_defs v1 x1 defs1)) /\\\n(forall val1 v1 x1,\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_val (subst_val v1 x1 val1)) /\\\n(forall t1 v1 x1,\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_trm (subst_trm v1 x1 t1)).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_def_fresh_same :\nforall d1 v1 x1,\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_def (subst_def v1 x1 d1).\nProof.\npose proof subst_def_fresh_same_subst_defs_fresh_same_subst_val_fresh_same_subst_trm_fresh_same_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_def_fresh_same : lngen.\n\nLemma subst_defs_fresh_same :\nforall defs1 v1 x1,\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_defs (subst_defs v1 x1 defs1).\nProof.\npose proof subst_def_fresh_same_subst_defs_fresh_same_subst_val_fresh_same_subst_trm_fresh_same_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_defs_fresh_same : lngen.\n\nLemma subst_val_fresh_same :\nforall val1 v1 x1,\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_val (subst_val v1 x1 val1).\nProof.\npose proof subst_def_fresh_same_subst_defs_fresh_same_subst_val_fresh_same_subst_trm_fresh_same_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_val_fresh_same : lngen.\n\nLemma subst_trm_fresh_same :\nforall t1 v1 x1,\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_trm (subst_trm v1 x1 t1).\nProof.\npose proof subst_def_fresh_same_subst_defs_fresh_same_subst_val_fresh_same_subst_trm_fresh_same_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_trm_fresh_same : lngen.\n\n(* begin hide *)\n\nLemma subst_varref_fresh_mutual :\n(forall v2 v1 x1 x2,\n  x1 `notin` fv_varref v2 ->\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_varref (subst_varref v1 x2 v2)).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_varref_fresh :\nforall v2 v1 x1 x2,\n  x1 `notin` fv_varref v2 ->\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_varref (subst_varref v1 x2 v2).\nProof.\npose proof subst_varref_fresh_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_varref_fresh : lngen.\n\n(* begin hide *)\n\nLemma subst_typ_fresh_subst_dec_fresh_mutual :\n(forall T1 v1 x1 x2,\n  x1 `notin` fv_typ T1 ->\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_typ (subst_typ v1 x2 T1)) /\\\n(forall dec1 v1 x1 x2,\n  x1 `notin` fv_dec dec1 ->\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_dec (subst_dec v1 x2 dec1)).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_typ_fresh :\nforall T1 v1 x1 x2,\n  x1 `notin` fv_typ T1 ->\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_typ (subst_typ v1 x2 T1).\nProof.\npose proof subst_typ_fresh_subst_dec_fresh_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_typ_fresh : lngen.\n\nLemma subst_dec_fresh :\nforall dec1 v1 x1 x2,\n  x1 `notin` fv_dec dec1 ->\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_dec (subst_dec v1 x2 dec1).\nProof.\npose proof subst_typ_fresh_subst_dec_fresh_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_dec_fresh : lngen.\n\n(* begin hide *)\n\nLemma subst_def_fresh_subst_defs_fresh_subst_val_fresh_subst_trm_fresh_mutual :\n(forall d1 v1 x1 x2,\n  x1 `notin` fv_def d1 ->\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_def (subst_def v1 x2 d1)) /\\\n(forall defs1 v1 x1 x2,\n  x1 `notin` fv_defs defs1 ->\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_defs (subst_defs v1 x2 defs1)) /\\\n(forall val1 v1 x1 x2,\n  x1 `notin` fv_val val1 ->\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_val (subst_val v1 x2 val1)) /\\\n(forall t1 v1 x1 x2,\n  x1 `notin` fv_trm t1 ->\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_trm (subst_trm v1 x2 t1)).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_def_fresh :\nforall d1 v1 x1 x2,\n  x1 `notin` fv_def d1 ->\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_def (subst_def v1 x2 d1).\nProof.\npose proof subst_def_fresh_subst_defs_fresh_subst_val_fresh_subst_trm_fresh_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_def_fresh : lngen.\n\nLemma subst_defs_fresh :\nforall defs1 v1 x1 x2,\n  x1 `notin` fv_defs defs1 ->\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_defs (subst_defs v1 x2 defs1).\nProof.\npose proof subst_def_fresh_subst_defs_fresh_subst_val_fresh_subst_trm_fresh_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_defs_fresh : lngen.\n\nLemma subst_val_fresh :\nforall val1 v1 x1 x2,\n  x1 `notin` fv_val val1 ->\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_val (subst_val v1 x2 val1).\nProof.\npose proof subst_def_fresh_subst_defs_fresh_subst_val_fresh_subst_trm_fresh_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_val_fresh : lngen.\n\nLemma subst_trm_fresh :\nforall t1 v1 x1 x2,\n  x1 `notin` fv_trm t1 ->\n  x1 `notin` fv_varref v1 ->\n  x1 `notin` fv_trm (subst_trm v1 x2 t1).\nProof.\npose proof subst_def_fresh_subst_defs_fresh_subst_val_fresh_subst_trm_fresh_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_trm_fresh : lngen.\n\nLemma subst_varref_lc_varref :\nforall v1 v2 x1,\n  lc_varref v1 ->\n  lc_varref v2 ->\n  lc_varref (subst_varref v2 x1 v1).\nProof.\ndefault_simp.\nQed.\n\nHint Resolve subst_varref_lc_varref : lngen.\n\nLemma subst_typ_lc_typ :\nforall T1 v1 x1,\n  lc_typ T1 ->\n  lc_varref v1 ->\n  lc_typ (subst_typ v1 x1 T1).\nProof.\ndefault_simp.\nQed.\n\nHint Resolve subst_typ_lc_typ : lngen.\n\nLemma subst_dec_lc_dec :\nforall dec1 v1 x1,\n  lc_dec dec1 ->\n  lc_varref v1 ->\n  lc_dec (subst_dec v1 x1 dec1).\nProof.\ndefault_simp.\nQed.\n\nHint Resolve subst_dec_lc_dec : lngen.\n\nLemma subst_def_lc_def :\nforall d1 v1 x1,\n  lc_def d1 ->\n  lc_varref v1 ->\n  lc_def (subst_def v1 x1 d1).\nProof.\ndefault_simp.\nQed.\n\nHint Resolve subst_def_lc_def : lngen.\n\nLemma subst_defs_lc_defs :\nforall defs1 v1 x1,\n  lc_defs defs1 ->\n  lc_varref v1 ->\n  lc_defs (subst_defs v1 x1 defs1).\nProof.\ndefault_simp.\nQed.\n\nHint Resolve subst_defs_lc_defs : lngen.\n\nLemma subst_val_lc_val :\nforall val1 v1 x1,\n  lc_val val1 ->\n  lc_varref v1 ->\n  lc_val (subst_val v1 x1 val1).\nProof.\ndefault_simp.\nQed.\n\nHint Resolve subst_val_lc_val : lngen.\n\nLemma subst_trm_lc_trm :\nforall t1 v1 x1,\n  lc_trm t1 ->\n  lc_varref v1 ->\n  lc_trm (subst_trm v1 x1 t1).\nProof.\ndefault_simp.\nQed.\n\nHint Resolve subst_trm_lc_trm : lngen.\n\n(* begin hide *)\n\nLemma subst_varref_open_varref_wrt_varref_rec_mutual :\n(forall v3 v1 v2 x1 n1,\n  lc_varref v1 ->\n  subst_varref v1 x1 (open_varref_wrt_varref_rec n1 v2 v3) = open_varref_wrt_varref_rec n1 (subst_varref v1 x1 v2) (subst_varref v1 x1 v3)).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_varref_open_varref_wrt_varref_rec :\nforall v3 v1 v2 x1 n1,\n  lc_varref v1 ->\n  subst_varref v1 x1 (open_varref_wrt_varref_rec n1 v2 v3) = open_varref_wrt_varref_rec n1 (subst_varref v1 x1 v2) (subst_varref v1 x1 v3).\nProof.\npose proof subst_varref_open_varref_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_varref_open_varref_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_typ_open_typ_wrt_varref_rec_subst_dec_open_dec_wrt_varref_rec_mutual :\n(forall T1 v1 v2 x1 n1,\n  lc_varref v1 ->\n  subst_typ v1 x1 (open_typ_wrt_varref_rec n1 v2 T1) = open_typ_wrt_varref_rec n1 (subst_varref v1 x1 v2) (subst_typ v1 x1 T1)) /\\\n(forall dec1 v1 v2 x1 n1,\n  lc_varref v1 ->\n  subst_dec v1 x1 (open_dec_wrt_varref_rec n1 v2 dec1) = open_dec_wrt_varref_rec n1 (subst_varref v1 x1 v2) (subst_dec v1 x1 dec1)).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_typ_open_typ_wrt_varref_rec :\nforall T1 v1 v2 x1 n1,\n  lc_varref v1 ->\n  subst_typ v1 x1 (open_typ_wrt_varref_rec n1 v2 T1) = open_typ_wrt_varref_rec n1 (subst_varref v1 x1 v2) (subst_typ v1 x1 T1).\nProof.\npose proof subst_typ_open_typ_wrt_varref_rec_subst_dec_open_dec_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_typ_open_typ_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_dec_open_dec_wrt_varref_rec :\nforall dec1 v1 v2 x1 n1,\n  lc_varref v1 ->\n  subst_dec v1 x1 (open_dec_wrt_varref_rec n1 v2 dec1) = open_dec_wrt_varref_rec n1 (subst_varref v1 x1 v2) (subst_dec v1 x1 dec1).\nProof.\npose proof subst_typ_open_typ_wrt_varref_rec_subst_dec_open_dec_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_dec_open_dec_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_def_open_def_wrt_varref_rec_subst_defs_open_defs_wrt_varref_rec_subst_val_open_val_wrt_varref_rec_subst_trm_open_trm_wrt_varref_rec_mutual :\n(forall d1 v1 v2 x1 n1,\n  lc_varref v1 ->\n  subst_def v1 x1 (open_def_wrt_varref_rec n1 v2 d1) = open_def_wrt_varref_rec n1 (subst_varref v1 x1 v2) (subst_def v1 x1 d1)) /\\\n(forall defs1 v1 v2 x1 n1,\n  lc_varref v1 ->\n  subst_defs v1 x1 (open_defs_wrt_varref_rec n1 v2 defs1) = open_defs_wrt_varref_rec n1 (subst_varref v1 x1 v2) (subst_defs v1 x1 defs1)) /\\\n(forall val1 v1 v2 x1 n1,\n  lc_varref v1 ->\n  subst_val v1 x1 (open_val_wrt_varref_rec n1 v2 val1) = open_val_wrt_varref_rec n1 (subst_varref v1 x1 v2) (subst_val v1 x1 val1)) /\\\n(forall t1 v1 v2 x1 n1,\n  lc_varref v1 ->\n  subst_trm v1 x1 (open_trm_wrt_varref_rec n1 v2 t1) = open_trm_wrt_varref_rec n1 (subst_varref v1 x1 v2) (subst_trm v1 x1 t1)).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_def_open_def_wrt_varref_rec :\nforall d1 v1 v2 x1 n1,\n  lc_varref v1 ->\n  subst_def v1 x1 (open_def_wrt_varref_rec n1 v2 d1) = open_def_wrt_varref_rec n1 (subst_varref v1 x1 v2) (subst_def v1 x1 d1).\nProof.\npose proof subst_def_open_def_wrt_varref_rec_subst_defs_open_defs_wrt_varref_rec_subst_val_open_val_wrt_varref_rec_subst_trm_open_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_def_open_def_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_defs_open_defs_wrt_varref_rec :\nforall defs1 v1 v2 x1 n1,\n  lc_varref v1 ->\n  subst_defs v1 x1 (open_defs_wrt_varref_rec n1 v2 defs1) = open_defs_wrt_varref_rec n1 (subst_varref v1 x1 v2) (subst_defs v1 x1 defs1).\nProof.\npose proof subst_def_open_def_wrt_varref_rec_subst_defs_open_defs_wrt_varref_rec_subst_val_open_val_wrt_varref_rec_subst_trm_open_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_defs_open_defs_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_val_open_val_wrt_varref_rec :\nforall val1 v1 v2 x1 n1,\n  lc_varref v1 ->\n  subst_val v1 x1 (open_val_wrt_varref_rec n1 v2 val1) = open_val_wrt_varref_rec n1 (subst_varref v1 x1 v2) (subst_val v1 x1 val1).\nProof.\npose proof subst_def_open_def_wrt_varref_rec_subst_defs_open_defs_wrt_varref_rec_subst_val_open_val_wrt_varref_rec_subst_trm_open_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_val_open_val_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_trm_open_trm_wrt_varref_rec :\nforall t1 v1 v2 x1 n1,\n  lc_varref v1 ->\n  subst_trm v1 x1 (open_trm_wrt_varref_rec n1 v2 t1) = open_trm_wrt_varref_rec n1 (subst_varref v1 x1 v2) (subst_trm v1 x1 t1).\nProof.\npose proof subst_def_open_def_wrt_varref_rec_subst_defs_open_defs_wrt_varref_rec_subst_val_open_val_wrt_varref_rec_subst_trm_open_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_trm_open_trm_wrt_varref_rec : lngen.\n\n(* end hide *)\n\nLemma subst_varref_open_varref_wrt_varref :\nforall v3 v1 v2 x1,\n  lc_varref v1 ->\n  subst_varref v1 x1 (open_varref_wrt_varref v3 v2) = open_varref_wrt_varref (subst_varref v1 x1 v3) (subst_varref v1 x1 v2).\nProof.\nunfold open_varref_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_varref_open_varref_wrt_varref : lngen.\n\nLemma subst_typ_open_typ_wrt_varref :\nforall T1 v1 v2 x1,\n  lc_varref v1 ->\n  subst_typ v1 x1 (open_typ_wrt_varref T1 v2) = open_typ_wrt_varref (subst_typ v1 x1 T1) (subst_varref v1 x1 v2).\nProof.\nunfold open_typ_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_typ_open_typ_wrt_varref : lngen.\n\nLemma subst_dec_open_dec_wrt_varref :\nforall dec1 v1 v2 x1,\n  lc_varref v1 ->\n  subst_dec v1 x1 (open_dec_wrt_varref dec1 v2) = open_dec_wrt_varref (subst_dec v1 x1 dec1) (subst_varref v1 x1 v2).\nProof.\nunfold open_dec_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_dec_open_dec_wrt_varref : lngen.\n\nLemma subst_def_open_def_wrt_varref :\nforall d1 v1 v2 x1,\n  lc_varref v1 ->\n  subst_def v1 x1 (open_def_wrt_varref d1 v2) = open_def_wrt_varref (subst_def v1 x1 d1) (subst_varref v1 x1 v2).\nProof.\nunfold open_def_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_def_open_def_wrt_varref : lngen.\n\nLemma subst_defs_open_defs_wrt_varref :\nforall defs1 v1 v2 x1,\n  lc_varref v1 ->\n  subst_defs v1 x1 (open_defs_wrt_varref defs1 v2) = open_defs_wrt_varref (subst_defs v1 x1 defs1) (subst_varref v1 x1 v2).\nProof.\nunfold open_defs_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_defs_open_defs_wrt_varref : lngen.\n\nLemma subst_val_open_val_wrt_varref :\nforall val1 v1 v2 x1,\n  lc_varref v1 ->\n  subst_val v1 x1 (open_val_wrt_varref val1 v2) = open_val_wrt_varref (subst_val v1 x1 val1) (subst_varref v1 x1 v2).\nProof.\nunfold open_val_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_val_open_val_wrt_varref : lngen.\n\nLemma subst_trm_open_trm_wrt_varref :\nforall t1 v1 v2 x1,\n  lc_varref v1 ->\n  subst_trm v1 x1 (open_trm_wrt_varref t1 v2) = open_trm_wrt_varref (subst_trm v1 x1 t1) (subst_varref v1 x1 v2).\nProof.\nunfold open_trm_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_trm_open_trm_wrt_varref : lngen.\n\nLemma subst_varref_open_varref_wrt_varref_var :\nforall v2 v1 x1 x2,\n  x1 <> x2 ->\n  lc_varref v1 ->\n  open_varref_wrt_varref (subst_varref v1 x1 v2) (var_termvar_f x2) = subst_varref v1 x1 (open_varref_wrt_varref v2 (var_termvar_f x2)).\nProof.\nintros; rewrite subst_varref_open_varref_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_varref_open_varref_wrt_varref_var : lngen.\n\nLemma subst_typ_open_typ_wrt_varref_var :\nforall T1 v1 x1 x2,\n  x1 <> x2 ->\n  lc_varref v1 ->\n  open_typ_wrt_varref (subst_typ v1 x1 T1) (var_termvar_f x2) = subst_typ v1 x1 (open_typ_wrt_varref T1 (var_termvar_f x2)).\nProof.\nintros; rewrite subst_typ_open_typ_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_typ_open_typ_wrt_varref_var : lngen.\n\nLemma subst_dec_open_dec_wrt_varref_var :\nforall dec1 v1 x1 x2,\n  x1 <> x2 ->\n  lc_varref v1 ->\n  open_dec_wrt_varref (subst_dec v1 x1 dec1) (var_termvar_f x2) = subst_dec v1 x1 (open_dec_wrt_varref dec1 (var_termvar_f x2)).\nProof.\nintros; rewrite subst_dec_open_dec_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_dec_open_dec_wrt_varref_var : lngen.\n\nLemma subst_def_open_def_wrt_varref_var :\nforall d1 v1 x1 x2,\n  x1 <> x2 ->\n  lc_varref v1 ->\n  open_def_wrt_varref (subst_def v1 x1 d1) (var_termvar_f x2) = subst_def v1 x1 (open_def_wrt_varref d1 (var_termvar_f x2)).\nProof.\nintros; rewrite subst_def_open_def_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_def_open_def_wrt_varref_var : lngen.\n\nLemma subst_defs_open_defs_wrt_varref_var :\nforall defs1 v1 x1 x2,\n  x1 <> x2 ->\n  lc_varref v1 ->\n  open_defs_wrt_varref (subst_defs v1 x1 defs1) (var_termvar_f x2) = subst_defs v1 x1 (open_defs_wrt_varref defs1 (var_termvar_f x2)).\nProof.\nintros; rewrite subst_defs_open_defs_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_defs_open_defs_wrt_varref_var : lngen.\n\nLemma subst_val_open_val_wrt_varref_var :\nforall val1 v1 x1 x2,\n  x1 <> x2 ->\n  lc_varref v1 ->\n  open_val_wrt_varref (subst_val v1 x1 val1) (var_termvar_f x2) = subst_val v1 x1 (open_val_wrt_varref val1 (var_termvar_f x2)).\nProof.\nintros; rewrite subst_val_open_val_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_val_open_val_wrt_varref_var : lngen.\n\nLemma subst_trm_open_trm_wrt_varref_var :\nforall t1 v1 x1 x2,\n  x1 <> x2 ->\n  lc_varref v1 ->\n  open_trm_wrt_varref (subst_trm v1 x1 t1) (var_termvar_f x2) = subst_trm v1 x1 (open_trm_wrt_varref t1 (var_termvar_f x2)).\nProof.\nintros; rewrite subst_trm_open_trm_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_trm_open_trm_wrt_varref_var : lngen.\n\n(* begin hide *)\n\nLemma subst_varref_spec_rec_mutual :\n(forall v1 v2 x1 n1,\n  subst_varref v2 x1 v1 = open_varref_wrt_varref_rec n1 v2 (close_varref_wrt_varref_rec n1 x1 v1)).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_varref_spec_rec :\nforall v1 v2 x1 n1,\n  subst_varref v2 x1 v1 = open_varref_wrt_varref_rec n1 v2 (close_varref_wrt_varref_rec n1 x1 v1).\nProof.\npose proof subst_varref_spec_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_varref_spec_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_typ_spec_rec_subst_dec_spec_rec_mutual :\n(forall T1 v1 x1 n1,\n  subst_typ v1 x1 T1 = open_typ_wrt_varref_rec n1 v1 (close_typ_wrt_varref_rec n1 x1 T1)) /\\\n(forall dec1 v1 x1 n1,\n  subst_dec v1 x1 dec1 = open_dec_wrt_varref_rec n1 v1 (close_dec_wrt_varref_rec n1 x1 dec1)).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_typ_spec_rec :\nforall T1 v1 x1 n1,\n  subst_typ v1 x1 T1 = open_typ_wrt_varref_rec n1 v1 (close_typ_wrt_varref_rec n1 x1 T1).\nProof.\npose proof subst_typ_spec_rec_subst_dec_spec_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_typ_spec_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_dec_spec_rec :\nforall dec1 v1 x1 n1,\n  subst_dec v1 x1 dec1 = open_dec_wrt_varref_rec n1 v1 (close_dec_wrt_varref_rec n1 x1 dec1).\nProof.\npose proof subst_typ_spec_rec_subst_dec_spec_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_dec_spec_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_def_spec_rec_subst_defs_spec_rec_subst_val_spec_rec_subst_trm_spec_rec_mutual :\n(forall d1 v1 x1 n1,\n  subst_def v1 x1 d1 = open_def_wrt_varref_rec n1 v1 (close_def_wrt_varref_rec n1 x1 d1)) /\\\n(forall defs1 v1 x1 n1,\n  subst_defs v1 x1 defs1 = open_defs_wrt_varref_rec n1 v1 (close_defs_wrt_varref_rec n1 x1 defs1)) /\\\n(forall val1 v1 x1 n1,\n  subst_val v1 x1 val1 = open_val_wrt_varref_rec n1 v1 (close_val_wrt_varref_rec n1 x1 val1)) /\\\n(forall t1 v1 x1 n1,\n  subst_trm v1 x1 t1 = open_trm_wrt_varref_rec n1 v1 (close_trm_wrt_varref_rec n1 x1 t1)).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_def_spec_rec :\nforall d1 v1 x1 n1,\n  subst_def v1 x1 d1 = open_def_wrt_varref_rec n1 v1 (close_def_wrt_varref_rec n1 x1 d1).\nProof.\npose proof subst_def_spec_rec_subst_defs_spec_rec_subst_val_spec_rec_subst_trm_spec_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_def_spec_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_defs_spec_rec :\nforall defs1 v1 x1 n1,\n  subst_defs v1 x1 defs1 = open_defs_wrt_varref_rec n1 v1 (close_defs_wrt_varref_rec n1 x1 defs1).\nProof.\npose proof subst_def_spec_rec_subst_defs_spec_rec_subst_val_spec_rec_subst_trm_spec_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_defs_spec_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_val_spec_rec :\nforall val1 v1 x1 n1,\n  subst_val v1 x1 val1 = open_val_wrt_varref_rec n1 v1 (close_val_wrt_varref_rec n1 x1 val1).\nProof.\npose proof subst_def_spec_rec_subst_defs_spec_rec_subst_val_spec_rec_subst_trm_spec_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_val_spec_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_trm_spec_rec :\nforall t1 v1 x1 n1,\n  subst_trm v1 x1 t1 = open_trm_wrt_varref_rec n1 v1 (close_trm_wrt_varref_rec n1 x1 t1).\nProof.\npose proof subst_def_spec_rec_subst_defs_spec_rec_subst_val_spec_rec_subst_trm_spec_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_trm_spec_rec : lngen.\n\n(* end hide *)\n\nLemma subst_varref_spec :\nforall v1 v2 x1,\n  subst_varref v2 x1 v1 = open_varref_wrt_varref (close_varref_wrt_varref x1 v1) v2.\nProof.\nunfold close_varref_wrt_varref; unfold open_varref_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_varref_spec : lngen.\n\nLemma subst_typ_spec :\nforall T1 v1 x1,\n  subst_typ v1 x1 T1 = open_typ_wrt_varref (close_typ_wrt_varref x1 T1) v1.\nProof.\nunfold close_typ_wrt_varref; unfold open_typ_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_typ_spec : lngen.\n\nLemma subst_dec_spec :\nforall dec1 v1 x1,\n  subst_dec v1 x1 dec1 = open_dec_wrt_varref (close_dec_wrt_varref x1 dec1) v1.\nProof.\nunfold close_dec_wrt_varref; unfold open_dec_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_dec_spec : lngen.\n\nLemma subst_def_spec :\nforall d1 v1 x1,\n  subst_def v1 x1 d1 = open_def_wrt_varref (close_def_wrt_varref x1 d1) v1.\nProof.\nunfold close_def_wrt_varref; unfold open_def_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_def_spec : lngen.\n\nLemma subst_defs_spec :\nforall defs1 v1 x1,\n  subst_defs v1 x1 defs1 = open_defs_wrt_varref (close_defs_wrt_varref x1 defs1) v1.\nProof.\nunfold close_defs_wrt_varref; unfold open_defs_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_defs_spec : lngen.\n\nLemma subst_val_spec :\nforall val1 v1 x1,\n  subst_val v1 x1 val1 = open_val_wrt_varref (close_val_wrt_varref x1 val1) v1.\nProof.\nunfold close_val_wrt_varref; unfold open_val_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_val_spec : lngen.\n\nLemma subst_trm_spec :\nforall t1 v1 x1,\n  subst_trm v1 x1 t1 = open_trm_wrt_varref (close_trm_wrt_varref x1 t1) v1.\nProof.\nunfold close_trm_wrt_varref; unfold open_trm_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_trm_spec : lngen.\n\n(* begin hide *)\n\nLemma subst_varref_subst_varref_mutual :\n(forall v1 v2 v3 x2 x1,\n  x2 `notin` fv_varref v2 ->\n  x2 <> x1 ->\n  subst_varref v2 x1 (subst_varref v3 x2 v1) = subst_varref (subst_varref v2 x1 v3) x2 (subst_varref v2 x1 v1)).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_varref_subst_varref :\nforall v1 v2 v3 x2 x1,\n  x2 `notin` fv_varref v2 ->\n  x2 <> x1 ->\n  subst_varref v2 x1 (subst_varref v3 x2 v1) = subst_varref (subst_varref v2 x1 v3) x2 (subst_varref v2 x1 v1).\nProof.\npose proof subst_varref_subst_varref_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_varref_subst_varref : lngen.\n\n(* begin hide *)\n\nLemma subst_typ_subst_typ_subst_dec_subst_dec_mutual :\n(forall T1 v1 v2 x2 x1,\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  subst_typ v1 x1 (subst_typ v2 x2 T1) = subst_typ (subst_varref v1 x1 v2) x2 (subst_typ v1 x1 T1)) /\\\n(forall dec1 v1 v2 x2 x1,\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  subst_dec v1 x1 (subst_dec v2 x2 dec1) = subst_dec (subst_varref v1 x1 v2) x2 (subst_dec v1 x1 dec1)).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_typ_subst_typ :\nforall T1 v1 v2 x2 x1,\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  subst_typ v1 x1 (subst_typ v2 x2 T1) = subst_typ (subst_varref v1 x1 v2) x2 (subst_typ v1 x1 T1).\nProof.\npose proof subst_typ_subst_typ_subst_dec_subst_dec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_typ_subst_typ : lngen.\n\nLemma subst_dec_subst_dec :\nforall dec1 v1 v2 x2 x1,\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  subst_dec v1 x1 (subst_dec v2 x2 dec1) = subst_dec (subst_varref v1 x1 v2) x2 (subst_dec v1 x1 dec1).\nProof.\npose proof subst_typ_subst_typ_subst_dec_subst_dec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_dec_subst_dec : lngen.\n\n(* begin hide *)\n\nLemma subst_def_subst_def_subst_defs_subst_defs_subst_val_subst_val_subst_trm_subst_trm_mutual :\n(forall d1 v1 v2 x2 x1,\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  subst_def v1 x1 (subst_def v2 x2 d1) = subst_def (subst_varref v1 x1 v2) x2 (subst_def v1 x1 d1)) /\\\n(forall defs1 v1 v2 x2 x1,\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  subst_defs v1 x1 (subst_defs v2 x2 defs1) = subst_defs (subst_varref v1 x1 v2) x2 (subst_defs v1 x1 defs1)) /\\\n(forall val1 v1 v2 x2 x1,\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  subst_val v1 x1 (subst_val v2 x2 val1) = subst_val (subst_varref v1 x1 v2) x2 (subst_val v1 x1 val1)) /\\\n(forall t1 v1 v2 x2 x1,\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  subst_trm v1 x1 (subst_trm v2 x2 t1) = subst_trm (subst_varref v1 x1 v2) x2 (subst_trm v1 x1 t1)).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_def_subst_def :\nforall d1 v1 v2 x2 x1,\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  subst_def v1 x1 (subst_def v2 x2 d1) = subst_def (subst_varref v1 x1 v2) x2 (subst_def v1 x1 d1).\nProof.\npose proof subst_def_subst_def_subst_defs_subst_defs_subst_val_subst_val_subst_trm_subst_trm_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_def_subst_def : lngen.\n\nLemma subst_defs_subst_defs :\nforall defs1 v1 v2 x2 x1,\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  subst_defs v1 x1 (subst_defs v2 x2 defs1) = subst_defs (subst_varref v1 x1 v2) x2 (subst_defs v1 x1 defs1).\nProof.\npose proof subst_def_subst_def_subst_defs_subst_defs_subst_val_subst_val_subst_trm_subst_trm_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_defs_subst_defs : lngen.\n\nLemma subst_val_subst_val :\nforall val1 v1 v2 x2 x1,\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  subst_val v1 x1 (subst_val v2 x2 val1) = subst_val (subst_varref v1 x1 v2) x2 (subst_val v1 x1 val1).\nProof.\npose proof subst_def_subst_def_subst_defs_subst_defs_subst_val_subst_val_subst_trm_subst_trm_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_val_subst_val : lngen.\n\nLemma subst_trm_subst_trm :\nforall t1 v1 v2 x2 x1,\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  subst_trm v1 x1 (subst_trm v2 x2 t1) = subst_trm (subst_varref v1 x1 v2) x2 (subst_trm v1 x1 t1).\nProof.\npose proof subst_def_subst_def_subst_defs_subst_defs_subst_val_subst_val_subst_trm_subst_trm_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_trm_subst_trm : lngen.\n\n(* begin hide *)\n\nLemma subst_varref_close_varref_wrt_varref_rec_open_varref_wrt_varref_rec_mutual :\n(forall v2 v1 x1 x2 n1,\n  x2 `notin` fv_varref v2 ->\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  subst_varref v1 x1 v2 = close_varref_wrt_varref_rec n1 x2 (subst_varref v1 x1 (open_varref_wrt_varref_rec n1 (var_termvar_f x2) v2))).\nProof.\napply_mutual_ind varref_mutrec;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_varref_close_varref_wrt_varref_rec_open_varref_wrt_varref_rec :\nforall v2 v1 x1 x2 n1,\n  x2 `notin` fv_varref v2 ->\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  subst_varref v1 x1 v2 = close_varref_wrt_varref_rec n1 x2 (subst_varref v1 x1 (open_varref_wrt_varref_rec n1 (var_termvar_f x2) v2)).\nProof.\npose proof subst_varref_close_varref_wrt_varref_rec_open_varref_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_varref_close_varref_wrt_varref_rec_open_varref_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_typ_close_typ_wrt_varref_rec_open_typ_wrt_varref_rec_subst_dec_close_dec_wrt_varref_rec_open_dec_wrt_varref_rec_mutual :\n(forall T1 v1 x1 x2 n1,\n  x2 `notin` fv_typ T1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  subst_typ v1 x1 T1 = close_typ_wrt_varref_rec n1 x2 (subst_typ v1 x1 (open_typ_wrt_varref_rec n1 (var_termvar_f x2) T1))) *\n(forall dec1 v1 x1 x2 n1,\n  x2 `notin` fv_dec dec1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  subst_dec v1 x1 dec1 = close_dec_wrt_varref_rec n1 x2 (subst_dec v1 x1 (open_dec_wrt_varref_rec n1 (var_termvar_f x2) dec1))).\nProof.\napply_mutual_ind typ_dec_mutrec;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_typ_close_typ_wrt_varref_rec_open_typ_wrt_varref_rec :\nforall T1 v1 x1 x2 n1,\n  x2 `notin` fv_typ T1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  subst_typ v1 x1 T1 = close_typ_wrt_varref_rec n1 x2 (subst_typ v1 x1 (open_typ_wrt_varref_rec n1 (var_termvar_f x2) T1)).\nProof.\npose proof subst_typ_close_typ_wrt_varref_rec_open_typ_wrt_varref_rec_subst_dec_close_dec_wrt_varref_rec_open_dec_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_typ_close_typ_wrt_varref_rec_open_typ_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_dec_close_dec_wrt_varref_rec_open_dec_wrt_varref_rec :\nforall dec1 v1 x1 x2 n1,\n  x2 `notin` fv_dec dec1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  subst_dec v1 x1 dec1 = close_dec_wrt_varref_rec n1 x2 (subst_dec v1 x1 (open_dec_wrt_varref_rec n1 (var_termvar_f x2) dec1)).\nProof.\npose proof subst_typ_close_typ_wrt_varref_rec_open_typ_wrt_varref_rec_subst_dec_close_dec_wrt_varref_rec_open_dec_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_dec_close_dec_wrt_varref_rec_open_dec_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_def_close_def_wrt_varref_rec_open_def_wrt_varref_rec_subst_defs_close_defs_wrt_varref_rec_open_defs_wrt_varref_rec_subst_val_close_val_wrt_varref_rec_open_val_wrt_varref_rec_subst_trm_close_trm_wrt_varref_rec_open_trm_wrt_varref_rec_mutual :\n(forall d1 v1 x1 x2 n1,\n  x2 `notin` fv_def d1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  subst_def v1 x1 d1 = close_def_wrt_varref_rec n1 x2 (subst_def v1 x1 (open_def_wrt_varref_rec n1 (var_termvar_f x2) d1))) *\n(forall defs1 v1 x1 x2 n1,\n  x2 `notin` fv_defs defs1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  subst_defs v1 x1 defs1 = close_defs_wrt_varref_rec n1 x2 (subst_defs v1 x1 (open_defs_wrt_varref_rec n1 (var_termvar_f x2) defs1))) *\n(forall val1 v1 x1 x2 n1,\n  x2 `notin` fv_val val1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  subst_val v1 x1 val1 = close_val_wrt_varref_rec n1 x2 (subst_val v1 x1 (open_val_wrt_varref_rec n1 (var_termvar_f x2) val1))) *\n(forall t1 v1 x1 x2 n1,\n  x2 `notin` fv_trm t1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  subst_trm v1 x1 t1 = close_trm_wrt_varref_rec n1 x2 (subst_trm v1 x1 (open_trm_wrt_varref_rec n1 (var_termvar_f x2) t1))).\nProof.\napply_mutual_ind def_defs_val_trm_mutrec;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_def_close_def_wrt_varref_rec_open_def_wrt_varref_rec :\nforall d1 v1 x1 x2 n1,\n  x2 `notin` fv_def d1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  subst_def v1 x1 d1 = close_def_wrt_varref_rec n1 x2 (subst_def v1 x1 (open_def_wrt_varref_rec n1 (var_termvar_f x2) d1)).\nProof.\npose proof subst_def_close_def_wrt_varref_rec_open_def_wrt_varref_rec_subst_defs_close_defs_wrt_varref_rec_open_defs_wrt_varref_rec_subst_val_close_val_wrt_varref_rec_open_val_wrt_varref_rec_subst_trm_close_trm_wrt_varref_rec_open_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_def_close_def_wrt_varref_rec_open_def_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_defs_close_defs_wrt_varref_rec_open_defs_wrt_varref_rec :\nforall defs1 v1 x1 x2 n1,\n  x2 `notin` fv_defs defs1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  subst_defs v1 x1 defs1 = close_defs_wrt_varref_rec n1 x2 (subst_defs v1 x1 (open_defs_wrt_varref_rec n1 (var_termvar_f x2) defs1)).\nProof.\npose proof subst_def_close_def_wrt_varref_rec_open_def_wrt_varref_rec_subst_defs_close_defs_wrt_varref_rec_open_defs_wrt_varref_rec_subst_val_close_val_wrt_varref_rec_open_val_wrt_varref_rec_subst_trm_close_trm_wrt_varref_rec_open_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_defs_close_defs_wrt_varref_rec_open_defs_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_val_close_val_wrt_varref_rec_open_val_wrt_varref_rec :\nforall val1 v1 x1 x2 n1,\n  x2 `notin` fv_val val1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  subst_val v1 x1 val1 = close_val_wrt_varref_rec n1 x2 (subst_val v1 x1 (open_val_wrt_varref_rec n1 (var_termvar_f x2) val1)).\nProof.\npose proof subst_def_close_def_wrt_varref_rec_open_def_wrt_varref_rec_subst_defs_close_defs_wrt_varref_rec_open_defs_wrt_varref_rec_subst_val_close_val_wrt_varref_rec_open_val_wrt_varref_rec_subst_trm_close_trm_wrt_varref_rec_open_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_val_close_val_wrt_varref_rec_open_val_wrt_varref_rec : lngen.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_trm_close_trm_wrt_varref_rec_open_trm_wrt_varref_rec :\nforall t1 v1 x1 x2 n1,\n  x2 `notin` fv_trm t1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  degree_varref_wrt_varref n1 v1 ->\n  subst_trm v1 x1 t1 = close_trm_wrt_varref_rec n1 x2 (subst_trm v1 x1 (open_trm_wrt_varref_rec n1 (var_termvar_f x2) t1)).\nProof.\npose proof subst_def_close_def_wrt_varref_rec_open_def_wrt_varref_rec_subst_defs_close_defs_wrt_varref_rec_open_defs_wrt_varref_rec_subst_val_close_val_wrt_varref_rec_open_val_wrt_varref_rec_subst_trm_close_trm_wrt_varref_rec_open_trm_wrt_varref_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_trm_close_trm_wrt_varref_rec_open_trm_wrt_varref_rec : lngen.\n\n(* end hide *)\n\nLemma subst_varref_close_varref_wrt_varref_open_varref_wrt_varref :\nforall v2 v1 x1 x2,\n  x2 `notin` fv_varref v2 ->\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  lc_varref v1 ->\n  subst_varref v1 x1 v2 = close_varref_wrt_varref x2 (subst_varref v1 x1 (open_varref_wrt_varref v2 (var_termvar_f x2))).\nProof.\nunfold close_varref_wrt_varref; unfold open_varref_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_varref_close_varref_wrt_varref_open_varref_wrt_varref : lngen.\n\nLemma subst_typ_close_typ_wrt_varref_open_typ_wrt_varref :\nforall T1 v1 x1 x2,\n  x2 `notin` fv_typ T1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  lc_varref v1 ->\n  subst_typ v1 x1 T1 = close_typ_wrt_varref x2 (subst_typ v1 x1 (open_typ_wrt_varref T1 (var_termvar_f x2))).\nProof.\nunfold close_typ_wrt_varref; unfold open_typ_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_typ_close_typ_wrt_varref_open_typ_wrt_varref : lngen.\n\nLemma subst_dec_close_dec_wrt_varref_open_dec_wrt_varref :\nforall dec1 v1 x1 x2,\n  x2 `notin` fv_dec dec1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  lc_varref v1 ->\n  subst_dec v1 x1 dec1 = close_dec_wrt_varref x2 (subst_dec v1 x1 (open_dec_wrt_varref dec1 (var_termvar_f x2))).\nProof.\nunfold close_dec_wrt_varref; unfold open_dec_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_dec_close_dec_wrt_varref_open_dec_wrt_varref : lngen.\n\nLemma subst_def_close_def_wrt_varref_open_def_wrt_varref :\nforall d1 v1 x1 x2,\n  x2 `notin` fv_def d1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  lc_varref v1 ->\n  subst_def v1 x1 d1 = close_def_wrt_varref x2 (subst_def v1 x1 (open_def_wrt_varref d1 (var_termvar_f x2))).\nProof.\nunfold close_def_wrt_varref; unfold open_def_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_def_close_def_wrt_varref_open_def_wrt_varref : lngen.\n\nLemma subst_defs_close_defs_wrt_varref_open_defs_wrt_varref :\nforall defs1 v1 x1 x2,\n  x2 `notin` fv_defs defs1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  lc_varref v1 ->\n  subst_defs v1 x1 defs1 = close_defs_wrt_varref x2 (subst_defs v1 x1 (open_defs_wrt_varref defs1 (var_termvar_f x2))).\nProof.\nunfold close_defs_wrt_varref; unfold open_defs_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_defs_close_defs_wrt_varref_open_defs_wrt_varref : lngen.\n\nLemma subst_val_close_val_wrt_varref_open_val_wrt_varref :\nforall val1 v1 x1 x2,\n  x2 `notin` fv_val val1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  lc_varref v1 ->\n  subst_val v1 x1 val1 = close_val_wrt_varref x2 (subst_val v1 x1 (open_val_wrt_varref val1 (var_termvar_f x2))).\nProof.\nunfold close_val_wrt_varref; unfold open_val_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_val_close_val_wrt_varref_open_val_wrt_varref : lngen.\n\nLemma subst_trm_close_trm_wrt_varref_open_trm_wrt_varref :\nforall t1 v1 x1 x2,\n  x2 `notin` fv_trm t1 ->\n  x2 `notin` fv_varref v1 ->\n  x2 <> x1 ->\n  lc_varref v1 ->\n  subst_trm v1 x1 t1 = close_trm_wrt_varref x2 (subst_trm v1 x1 (open_trm_wrt_varref t1 (var_termvar_f x2))).\nProof.\nunfold close_trm_wrt_varref; unfold open_trm_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_trm_close_trm_wrt_varref_open_trm_wrt_varref : lngen.\n\nLemma subst_typ_typ_all :\nforall x2 T1 T2 v1 x1,\n  lc_varref v1 ->\n  x2 `notin` fv_varref v1 `union` fv_typ T2 `union` singleton x1 ->\n  subst_typ v1 x1 (typ_all T1 T2) = typ_all (subst_typ v1 x1 T1) (close_typ_wrt_varref x2 (subst_typ v1 x1 (open_typ_wrt_varref T2 (var_termvar_f x2)))).\nProof.\ndefault_simp.\nQed.\n\nHint Resolve subst_typ_typ_all : lngen.\n\nLemma subst_typ_typ_bnd :\nforall x2 T1 v1 x1,\n  lc_varref v1 ->\n  x2 `notin` fv_varref v1 `union` fv_typ T1 `union` singleton x1 ->\n  subst_typ v1 x1 (typ_bnd T1) = typ_bnd (close_typ_wrt_varref x2 (subst_typ v1 x1 (open_typ_wrt_varref T1 (var_termvar_f x2)))).\nProof.\ndefault_simp.\nQed.\n\nHint Resolve subst_typ_typ_bnd : lngen.\n\nLemma subst_val_val_new :\nforall x2 T1 defs1 v1 x1,\n  lc_varref v1 ->\n  x2 `notin` fv_varref v1 `union` fv_defs defs1 `union` singleton x1 ->\n  subst_val v1 x1 (val_new T1 defs1) = val_new (subst_typ v1 x1 T1) (close_defs_wrt_varref x2 (subst_defs v1 x1 (open_defs_wrt_varref defs1 (var_termvar_f x2)))).\nProof.\ndefault_simp.\nQed.\n\nHint Resolve subst_val_val_new : lngen.\n\nLemma subst_val_val_lambda :\nforall x2 T1 t1 v1 x1,\n  lc_varref v1 ->\n  x2 `notin` fv_varref v1 `union` fv_trm t1 `union` singleton x1 ->\n  subst_val v1 x1 (val_lambda T1 t1) = val_lambda (subst_typ v1 x1 T1) (close_trm_wrt_varref x2 (subst_trm v1 x1 (open_trm_wrt_varref t1 (var_termvar_f x2)))).\nProof.\ndefault_simp.\nQed.\n\nHint Resolve subst_val_val_lambda : lngen.\n\nLemma subst_trm_trm_let :\nforall x2 t1 t2 v1 x1,\n  lc_varref v1 ->\n  x2 `notin` fv_varref v1 `union` fv_trm t2 `union` singleton x1 ->\n  subst_trm v1 x1 (trm_let t1 t2) = trm_let (subst_trm v1 x1 t1) (close_trm_wrt_varref x2 (subst_trm v1 x1 (open_trm_wrt_varref t2 (var_termvar_f x2)))).\nProof.\ndefault_simp.\nQed.\n\nHint Resolve subst_trm_trm_let : lngen.\n\n(* begin hide *)\n\nLemma subst_varref_intro_rec_mutual :\n(forall v1 x1 v2 n1,\n  x1 `notin` fv_varref v1 ->\n  open_varref_wrt_varref_rec n1 v2 v1 = subst_varref v2 x1 (open_varref_wrt_varref_rec n1 (var_termvar_f x1) v1)).\nProof.\napply_mutual_ind varref_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_varref_intro_rec :\nforall v1 x1 v2 n1,\n  x1 `notin` fv_varref v1 ->\n  open_varref_wrt_varref_rec n1 v2 v1 = subst_varref v2 x1 (open_varref_wrt_varref_rec n1 (var_termvar_f x1) v1).\nProof.\npose proof subst_varref_intro_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_varref_intro_rec : lngen.\nHint Rewrite subst_varref_intro_rec using solve [auto] : lngen.\n\n(* begin hide *)\n\nLemma subst_typ_intro_rec_subst_dec_intro_rec_mutual :\n(forall T1 x1 v1 n1,\n  x1 `notin` fv_typ T1 ->\n  open_typ_wrt_varref_rec n1 v1 T1 = subst_typ v1 x1 (open_typ_wrt_varref_rec n1 (var_termvar_f x1) T1)) /\\\n(forall dec1 x1 v1 n1,\n  x1 `notin` fv_dec dec1 ->\n  open_dec_wrt_varref_rec n1 v1 dec1 = subst_dec v1 x1 (open_dec_wrt_varref_rec n1 (var_termvar_f x1) dec1)).\nProof.\napply_mutual_ind typ_dec_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_typ_intro_rec :\nforall T1 x1 v1 n1,\n  x1 `notin` fv_typ T1 ->\n  open_typ_wrt_varref_rec n1 v1 T1 = subst_typ v1 x1 (open_typ_wrt_varref_rec n1 (var_termvar_f x1) T1).\nProof.\npose proof subst_typ_intro_rec_subst_dec_intro_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_typ_intro_rec : lngen.\nHint Rewrite subst_typ_intro_rec using solve [auto] : lngen.\n\nLemma subst_dec_intro_rec :\nforall dec1 x1 v1 n1,\n  x1 `notin` fv_dec dec1 ->\n  open_dec_wrt_varref_rec n1 v1 dec1 = subst_dec v1 x1 (open_dec_wrt_varref_rec n1 (var_termvar_f x1) dec1).\nProof.\npose proof subst_typ_intro_rec_subst_dec_intro_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_dec_intro_rec : lngen.\nHint Rewrite subst_dec_intro_rec using solve [auto] : lngen.\n\n(* begin hide *)\n\nLemma subst_def_intro_rec_subst_defs_intro_rec_subst_val_intro_rec_subst_trm_intro_rec_mutual :\n(forall d1 x1 v1 n1,\n  x1 `notin` fv_def d1 ->\n  open_def_wrt_varref_rec n1 v1 d1 = subst_def v1 x1 (open_def_wrt_varref_rec n1 (var_termvar_f x1) d1)) /\\\n(forall defs1 x1 v1 n1,\n  x1 `notin` fv_defs defs1 ->\n  open_defs_wrt_varref_rec n1 v1 defs1 = subst_defs v1 x1 (open_defs_wrt_varref_rec n1 (var_termvar_f x1) defs1)) /\\\n(forall val1 x1 v1 n1,\n  x1 `notin` fv_val val1 ->\n  open_val_wrt_varref_rec n1 v1 val1 = subst_val v1 x1 (open_val_wrt_varref_rec n1 (var_termvar_f x1) val1)) /\\\n(forall t1 x1 v1 n1,\n  x1 `notin` fv_trm t1 ->\n  open_trm_wrt_varref_rec n1 v1 t1 = subst_trm v1 x1 (open_trm_wrt_varref_rec n1 (var_termvar_f x1) t1)).\nProof.\napply_mutual_ind def_defs_val_trm_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_def_intro_rec :\nforall d1 x1 v1 n1,\n  x1 `notin` fv_def d1 ->\n  open_def_wrt_varref_rec n1 v1 d1 = subst_def v1 x1 (open_def_wrt_varref_rec n1 (var_termvar_f x1) d1).\nProof.\npose proof subst_def_intro_rec_subst_defs_intro_rec_subst_val_intro_rec_subst_trm_intro_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_def_intro_rec : lngen.\nHint Rewrite subst_def_intro_rec using solve [auto] : lngen.\n\nLemma subst_defs_intro_rec :\nforall defs1 x1 v1 n1,\n  x1 `notin` fv_defs defs1 ->\n  open_defs_wrt_varref_rec n1 v1 defs1 = subst_defs v1 x1 (open_defs_wrt_varref_rec n1 (var_termvar_f x1) defs1).\nProof.\npose proof subst_def_intro_rec_subst_defs_intro_rec_subst_val_intro_rec_subst_trm_intro_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_defs_intro_rec : lngen.\nHint Rewrite subst_defs_intro_rec using solve [auto] : lngen.\n\nLemma subst_val_intro_rec :\nforall val1 x1 v1 n1,\n  x1 `notin` fv_val val1 ->\n  open_val_wrt_varref_rec n1 v1 val1 = subst_val v1 x1 (open_val_wrt_varref_rec n1 (var_termvar_f x1) val1).\nProof.\npose proof subst_def_intro_rec_subst_defs_intro_rec_subst_val_intro_rec_subst_trm_intro_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_val_intro_rec : lngen.\nHint Rewrite subst_val_intro_rec using solve [auto] : lngen.\n\nLemma subst_trm_intro_rec :\nforall t1 x1 v1 n1,\n  x1 `notin` fv_trm t1 ->\n  open_trm_wrt_varref_rec n1 v1 t1 = subst_trm v1 x1 (open_trm_wrt_varref_rec n1 (var_termvar_f x1) t1).\nProof.\npose proof subst_def_intro_rec_subst_defs_intro_rec_subst_val_intro_rec_subst_trm_intro_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_trm_intro_rec : lngen.\nHint Rewrite subst_trm_intro_rec using solve [auto] : lngen.\n\nLemma subst_varref_intro :\nforall x1 v1 v2,\n  x1 `notin` fv_varref v1 ->\n  open_varref_wrt_varref v1 v2 = subst_varref v2 x1 (open_varref_wrt_varref v1 (var_termvar_f x1)).\nProof.\nunfold open_varref_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_varref_intro : lngen.\n\nLemma subst_typ_intro :\nforall x1 T1 v1,\n  x1 `notin` fv_typ T1 ->\n  open_typ_wrt_varref T1 v1 = subst_typ v1 x1 (open_typ_wrt_varref T1 (var_termvar_f x1)).\nProof.\nunfold open_typ_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_typ_intro : lngen.\n\nLemma subst_dec_intro :\nforall x1 dec1 v1,\n  x1 `notin` fv_dec dec1 ->\n  open_dec_wrt_varref dec1 v1 = subst_dec v1 x1 (open_dec_wrt_varref dec1 (var_termvar_f x1)).\nProof.\nunfold open_dec_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_dec_intro : lngen.\n\nLemma subst_def_intro :\nforall x1 d1 v1,\n  x1 `notin` fv_def d1 ->\n  open_def_wrt_varref d1 v1 = subst_def v1 x1 (open_def_wrt_varref d1 (var_termvar_f x1)).\nProof.\nunfold open_def_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_def_intro : lngen.\n\nLemma subst_defs_intro :\nforall x1 defs1 v1,\n  x1 `notin` fv_defs defs1 ->\n  open_defs_wrt_varref defs1 v1 = subst_defs v1 x1 (open_defs_wrt_varref defs1 (var_termvar_f x1)).\nProof.\nunfold open_defs_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_defs_intro : lngen.\n\nLemma subst_val_intro :\nforall x1 val1 v1,\n  x1 `notin` fv_val val1 ->\n  open_val_wrt_varref val1 v1 = subst_val v1 x1 (open_val_wrt_varref val1 (var_termvar_f x1)).\nProof.\nunfold open_val_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_val_intro : lngen.\n\nLemma subst_trm_intro :\nforall x1 t1 v1,\n  x1 `notin` fv_trm t1 ->\n  open_trm_wrt_varref t1 v1 = subst_trm v1 x1 (open_trm_wrt_varref t1 (var_termvar_f x1)).\nProof.\nunfold open_trm_wrt_varref; default_simp.\nQed.\n\nHint Resolve subst_trm_intro : lngen.\n\n\n(* *********************************************************************** *)\n(** * \"Restore\" tactics *)\n\nLtac default_auto ::= auto; tauto.\nLtac default_autorewrite ::= fail.\n", "meta": {"author": "jqyu", "repo": "dot-ott", "sha": "baa8e9cb0e25a008896d6c4287404ccfa150a6c4", "save_path": "github-repos/coq/jqyu-dot-ott", "path": "github-repos/coq/jqyu-dot-ott/dot-ott-baa8e9cb0e25a008896d6c4287404ccfa150a6c4/Infrastructure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2635430672472995}}
{"text": "(* Just reexport Iris mdoule *)\nFrom iris.base_logic Require Export lib.ghost_map.\n\n(* Add some Perennial-specific stuff *)\nFrom iris.proofmode Require Import tactics.\nFrom Perennial.algebra Require Import own_discrete atleast.\nFrom Perennial.Helpers Require Import Map.\n\nSet Default Proof Using \"Type\".\n\nSection lemmas.\n  Context `{ghost_mapG Σ K V}.\n  Implicit Types (k : K) (v : V) (dq : dfrac) (q : Qp) (m : gmap K V).\n\n  Lemma ghost_map_elem_big_exist γ m :\n    ([∗ map] l↦_ ∈ m, ∃ v', l ↪[γ] v') -∗\n    ∃ m', ⌜dom m' = dom m⌝ ∗\n          [∗ map] l↦v ∈ m', l ↪[γ] v.\n  Proof.\n    induction m as [|l v m] using map_ind.\n    - rewrite big_sepM_empty.\n      iIntros \"_\". iExists ∅.\n      iSplit; first done.\n      rewrite big_sepM_empty; done.\n    - rewrite big_sepM_insert //.\n      iIntros \"[Hl Hm]\".\n      iDestruct \"Hl\" as (v') \"Hl\".\n      iDestruct (IHm with \"Hm\") as (m0 Hdom) \"Hm\".\n      iExists (<[l:=v']> m0).\n      iSplit.\n      + iPureIntro.\n        rewrite !dom_insert_L. congruence.\n      + rewrite big_sepM_insert; [ by iFrame | ].\n        apply not_elem_of_dom.\n        apply not_elem_of_dom in H1.\n        congruence.\n  Qed.\n\n  Lemma ghost_map_update_big_exist {γ m} m1 :\n    ghost_map_auth γ 1 m -∗\n    ( [∗ map] l↦v ∈ m1, ∃ v', l ↪[γ] v' ) ==∗\n      ghost_map_auth γ 1 (m1 ∪ m) ∗\n      ( [∗ map] l↦v ∈ m1, l ↪[γ] v ).\n  Proof.\n    iIntros \"Hauth Hm0\".\n    iDestruct (ghost_map_elem_big_exist with \"Hm0\") as (m0 Hdom) \"Hm0\".\n    iMod (ghost_map_update_big with \"Hauth Hm0\") as \"[$ Hm]\"; auto.\n  Qed.\n\n\n  Global Instance ghost_map_auth_discrete γ q m : Discretizable (ghost_map_auth γ q m).\n  Proof. rewrite ghost_map.ghost_map_auth_unseal. apply _. Qed.\n\n  Global Instance ghost_map_auth_abs_timeless γ q m : AbsolutelyTimeless (ghost_map_auth γ q m).\n  Proof. rewrite ghost_map.ghost_map_auth_unseal. apply _. Qed.\n\n  Global Instance ghost_map_elem_discrete γ dq k v : Discretizable (k ↪[γ]{dq} v).\n  Proof. rewrite ghost_map.ghost_map_elem_unseal. apply _. Qed.\n\n  Global Instance ghost_map_elem_abs_timeless γ dq k v : AbsolutelyTimeless (k ↪[γ]{dq} v).\n  Proof. rewrite ghost_map.ghost_map_elem_unseal. apply _. Qed.\n\nEnd lemmas.\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/ghost_map.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2635430672472995}}
{"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(* A solver for unification constraints. *)\n\nRequire Import Recdef Coqlib Maps Errors.\n\nLocal Open Scope nat_scope.\nLocal Open Scope error_monad_scope.\n\n(** This module provides a solver for sets of unification constraints of the\n  following kinds: [T(x) = base-type] or [T(x) = T(y)].\n  The unknowns are the types [T(x)] of every identifier [x]. *)\n\n(** The interface for base types. *)\n\nModule Type TYPE_ALGEBRA.\n\nParameter t: Type.\nParameter eq: forall (x y: t), {x=y} + {x<>y}.\nParameter default: t.\n\nEnd TYPE_ALGEBRA.\n\n(** The constraint solver. *)\n\nModule UniSolver (T: TYPE_ALGEBRA).\n\n(* The current set of constraints is represented by a record with two components:\n- [te_typ]: a partial map from variables to types\n- [te_equ]: a list of pairs [(x,y)] of variables, indicating that\n  the type of [x] must be equal to the type of [y].\n*)\n\nDefinition constraint : Type := (positive * positive)%type.\n\nRecord typenv : Type := Typenv {\n  te_typ: PTree.t T.t;       (**r mapping var -> typ *)\n  te_equ: list constraint    (**r additional equality constraints *)\n}.\n\nDefinition initial : typenv := {| te_typ := PTree.empty _; te_equ := nil |}.\n\n(** Add the constraint [T(x) = ty]. *)\n\nDefinition set (e: typenv) (x: positive) (ty: T.t) : res typenv :=\n  match e.(te_typ)!x with\n  | None =>\n      OK {| te_typ := PTree.set x ty e.(te_typ);\n            te_equ := e.(te_equ) |}\n  | Some ty' =>\n      if T.eq ty ty'\n      then OK e\n      else Error (MSG \"bad definition/use of variable \" :: POS x :: nil)\n  end.\n\nFixpoint set_list (e: typenv) (rl: list positive) (tyl: list T.t) {struct rl}: res typenv :=\n  match rl, tyl with\n  | nil, nil => OK e\n  | r1::rs, ty1::tys => do e1 <- set e r1 ty1; set_list e1 rs tys\n  | _, _ => Error (msg \"arity mismatch\")\n  end.\n\n(** Add the constraint [T(x) = T(y)].\n    The boolean result is [true] if the types of [x] or [y] could be\n    made more precise.  Otherwise, [te_typ] does not change and\n    [false] is returned. *)\n\nDefinition move (e: typenv) (r1 r2: positive) : res (bool * typenv) :=\n  if peq r1 r2 then OK (false, e) else\n  match e.(te_typ)!r1, e.(te_typ)!r2 with\n  | None, None =>\n      OK (false, {| te_typ := e.(te_typ); te_equ := (r1, r2) :: e.(te_equ) |})\n  | Some ty1, None =>\n      OK (true, {| te_typ := PTree.set r2 ty1 e.(te_typ); te_equ := e.(te_equ) |})\n  | None, Some ty2 =>\n      OK (true, {| te_typ := PTree.set r1 ty2 e.(te_typ); te_equ := e.(te_equ) |})\n  | Some ty1, Some ty2 =>\n      if T.eq ty1 ty2\n      then OK (false, e)\n      else Error(MSG \"ill-typed move from \" :: POS r1 :: MSG \" to \" :: POS r2 :: nil)\n  end.\n\n(** Solve the remaining subtyping constraints by iteration. *)\n\nFixpoint solve_rec (e: typenv) (changed: bool) (q: list constraint) : res (typenv * bool) :=\n  match q with\n  | nil =>\n      OK (e, changed)\n  | (r1, r2) :: q' =>\n      do (changed1, e1) <- move e r1 r2; solve_rec e1 (changed || changed1) q'\n  end.\n\n(** Measuring the state *)\n\nLemma move_shape:\n  forall e r1 r2 changed e',\n  move e r1 r2 = OK (changed, e') ->\n  (e'.(te_equ) = e.(te_equ) \\/ e'.(te_equ) = (r1, r2) :: e.(te_equ))\n  /\\ (changed = true -> e'.(te_equ) = e.(te_equ)).\nProof.\n  unfold move; intros.\n  destruct (peq r1 r2). inv H. auto.\n  destruct e.(te_typ)!r1 as [ty1|]; destruct e.(te_typ)!r2 as [ty2|]; inv H; simpl.\n  destruct (T.eq ty1 ty2); inv H1. auto.\n  auto.\n  auto.\n  split. auto. intros. discriminate.\nQed.\n\nLemma length_move:\n  forall e r1 r2 changed e',\n  move e r1 r2 = OK (changed, e') ->\n  length e'.(te_equ) + (if changed then 1 else 0) <= S(length e.(te_equ)).\nProof.\n  unfold move; intros.\n  destruct (peq r1 r2). inv H. omega.\n  destruct e.(te_typ)!r1 as [ty1|]; destruct e.(te_typ)!r2 as [ty2|]; inv H; simpl.\n  destruct (T.eq ty1 ty2); inv H1. omega.\n  omega.\n  omega.\n  omega.\nQed.\n\nLemma length_solve_rec:\n  forall q e ch e' ch',\n  solve_rec e ch q = OK (e', ch') ->\n  length e'.(te_equ) + (if ch' && negb ch then 1 else 0) <= length e.(te_equ) + length q.\nProof.\n  induction q; simpl; intros.\n- inv H. replace (ch' && negb ch') with false. omega. destruct ch'; auto.\n- destruct a as [r1 r2]; monadInv H. rename x0 into e0. rename x into ch0.\n  exploit IHq; eauto. intros A.\n  exploit length_move; eauto. intros B.\n  set (X := (if ch' && negb (ch || ch0) then 1 else 0)) in *.\n  set (Y := (if ch0 then 1 else 0)) in *.\n  set (Z := (if ch' && negb ch then 1 else 0)) in *.\n  cut (Z <= X + Y). intros. omega.\n  unfold X, Y, Z. destruct ch'; destruct ch; destruct ch0; simpl; auto.\nQed.\n\nDefinition weight_typenv (e: typenv) : nat := length e.(te_equ).\n\n\n(** Iterative solving of the remaining constraints *)\n\nFunction solve_constraints (e: typenv) {measure weight_typenv e}: res typenv :=\n  match solve_rec {| te_typ := e.(te_typ); te_equ := nil |} false e.(te_equ) with\n  | OK(e', false) => OK e                   (**r no more changes, fixpoint reached *)\n  | OK(e', true)  => solve_constraints e'   (**r one more iteration *)\n  | Error msg => Error msg\n  end.\nProof.\n  intros. exploit length_solve_rec; eauto. simpl. intros.\n  unfold weight_typenv. omega.\nQed.\n\nDefinition typassign := positive -> T.t.\n\nDefinition makeassign (e: typenv) : typassign :=\n  fun x => match e.(te_typ)!x with Some ty => ty | None => T.default end.\n\nDefinition solve (e: typenv) : res typassign :=\n  do e' <- solve_constraints e; OK(makeassign e').\n\n(** What it means to be a solution *)\n\nDefinition satisf (te: typassign) (e: typenv) : Prop :=\n   (forall x ty, e.(te_typ)!x = Some ty -> te x = ty)\n/\\ (forall x y, In (x, y) e.(te_equ) -> te x = te y).\n\nLemma satisf_initial: forall te, satisf te initial.\nProof.\n  unfold initial; intros; split; simpl; intros.\n  rewrite PTree.gempty in H; discriminate.\n  contradiction.\nQed.\n\n(** Soundness proof *)\n\nLemma set_incr:\n  forall te x ty e e', set e x ty = OK e' -> satisf te e' -> satisf te e.\nProof.\n  unfold set; intros. destruct (te_typ e)!x as [ty'|] eqn:E.\n- destruct (T.eq ty ty'); inv H. auto.\n- inv H. destruct H0 as [A B]; simpl in *. red; split; intros; auto.\n  apply A. rewrite PTree.gso by congruence. auto.\nQed.\n\nHint Resolve set_incr: ty.\n\nLemma set_sound:\n  forall te x ty e e', set e x ty = OK e' -> satisf te e' -> te x = ty.\nProof.\n  unfold set; intros. destruct H0 as [P Q].\n  destruct (te_typ e)!x as [ty'|] eqn:E.\n- destruct (T.eq ty ty'); inv H. eauto.\n- inv H. simpl in P. apply P. apply PTree.gss.\nQed.\n\nLemma set_list_incr:\n  forall te xl tyl e e', set_list e xl tyl = OK e' -> satisf te e' -> satisf te e.\nProof.\n  induction xl; destruct tyl; simpl; intros; monadInv H; eauto with ty.\nQed.\n\nHint Resolve set_list_incr: ty.\n\nLemma set_list_sound:\n  forall te xl tyl e e', set_list e xl tyl = OK e' -> satisf te e' -> map te xl = tyl.\nProof.\n  induction xl; destruct tyl; simpl; intros; monadInv H.\n  auto.\n  f_equal. eapply set_sound; eauto with ty. eauto.\nQed.\n\nLemma move_incr:\n  forall te e r1 r2 e' changed,\n  move e r1 r2 = OK(changed, e') -> satisf te e' -> satisf te e.\nProof.\n  unfold move; intros. destruct H0 as [P Q].\n  destruct (peq r1 r2). inv H; split; auto.\n  destruct (te_typ e)!r1 as [ty1|] eqn:E1;\n  destruct (te_typ e)!r2 as [ty2|] eqn:E2.\n- destruct (T.eq ty1 ty2); inv H. split; auto.\n- inv H; simpl in *; split; auto. intros. apply P.\n  rewrite PTree.gso by congruence. auto.\n- inv H; simpl in *; split; auto. intros. apply P.\n  rewrite PTree.gso by congruence. auto.\n- inv H; simpl in *; split; auto.\nQed.\n\nHint Resolve move_incr: ty.\n\nLemma move_sound:\n  forall te e r1 r2 e' changed,\n  move e r1 r2 = OK(changed, e') -> satisf te e' -> te r1 = te r2.\nProof.\n  unfold move; intros. destruct H0 as [P Q].\n  destruct (peq r1 r2). congruence.\n  destruct (te_typ e)!r1 as [ty1|] eqn:E1;\n  destruct (te_typ e)!r2 as [ty2|] eqn:E2.\n- destruct (T.eq ty1 ty2); inv H. erewrite ! P by eauto. auto.\n- inv H; simpl in *. rewrite (P r1 ty1). rewrite (P r2 ty1). auto.\n  apply PTree.gss. rewrite PTree.gso by congruence. auto.\n- inv H; simpl in *. rewrite (P r1 ty2). rewrite (P r2 ty2). auto.\n  rewrite PTree.gso by congruence. auto. apply PTree.gss.\n- inv H; simpl in *. apply Q; auto.\nQed.\n\nLemma solve_rec_incr:\n  forall te q e changed e' changed',\n  solve_rec e changed q = OK(e', changed') -> satisf te e' -> satisf te e.\nProof.\n  induction q; simpl; intros.\n- inv H. auto.\n- destruct a as [r1 r2]; monadInv H. eauto with ty.\nQed.\n\nLemma solve_rec_sound:\n  forall te r1 r2 q e changed e' changed',\n  solve_rec e changed q = OK(e', changed') -> In (r1, r2) q -> satisf te e' ->\n  te r1 = te r2.\nProof.\n  induction q; simpl; intros.\n- contradiction.\n- destruct a as [r3 r4]; monadInv H. destruct H0.\n  + inv H. eapply move_sound; eauto. eapply solve_rec_incr; eauto.\n  + eapply IHq; eauto with ty.\nQed.\n\nLemma move_false:\n  forall e r1 r2 e',\n  move e r1 r2 = OK(false, e') ->\n  te_typ e' = te_typ e /\\ makeassign e r1 = makeassign e r2.\nProof.\n  unfold move; intros.\n  destruct (peq r1 r2). inv H. split; auto.\n  unfold makeassign;\n  destruct (te_typ e)!r1 as [ty1|] eqn:E1;\n  destruct (te_typ e)!r2 as [ty2|] eqn:E2.\n- destruct (T.eq ty1 ty2); inv H. auto.\n- discriminate.\n- discriminate.\n- inv H. split; auto.\nQed.\n\nLemma solve_rec_false:\n  forall r1 r2 q e changed e',\n  solve_rec e changed q = OK(e', false) ->\n  changed = false /\\\n  (In (r1, r2) q -> makeassign e r1 = makeassign e r2).\nProof.\n  induction q; simpl; intros.\n- inv H. tauto.\n- destruct a as [r3 r4]; monadInv H.\n  exploit IHq; eauto. intros [P Q].\n  destruct changed; try discriminate. destruct x; try discriminate.\n  exploit move_false; eauto. intros [U V].\n  split. auto. intros [A|A]. inv A. auto. exploit Q; auto.\n  unfold makeassign; rewrite U; auto.\nQed.\n\nLemma solve_constraints_incr:\n  forall te e e', solve_constraints e = OK e' -> satisf te e' -> satisf te e.\nProof.\n  intros te e; functional induction (solve_constraints e); intros.\n- inv H. auto.\n- exploit solve_rec_incr; eauto. intros [A B].\n  split; auto. intros; eapply solve_rec_sound; eauto.\n- discriminate.\nQed.\n\nLemma solve_constraints_sound:\n  forall e e', solve_constraints e = OK e' -> satisf (makeassign e') e'.\nProof.\n  intros e0; functional induction (solve_constraints e0); intros.\n- inv H. split; intros.\n  unfold makeassign; rewrite H. split; auto with ty.\n  exploit solve_rec_false. eauto. intros [A B]. eapply B; eauto.\n- eauto.\n- discriminate.\nQed.\n\nTheorem solve_sound:\n  forall e te, solve e = OK te -> satisf te e.\nProof.\n  unfold solve; intros. monadInv H.\n  eapply solve_constraints_incr. eauto. eapply solve_constraints_sound; eauto.\nQed.\n\n(** Completeness proof *)\n\nLemma set_complete:\n  forall te e x ty,\n  satisf te e -> te x = ty -> exists e', set e x ty = OK e' /\\ satisf te e'.\nProof.\n  unfold set; intros. generalize H; intros [P Q].\n  destruct (te_typ e)!x as [ty1|] eqn:E.\n- replace ty1 with ty. rewrite dec_eq_true. exists e; auto.\n  exploit P; eauto. congruence.\n- econstructor; split; eauto. split; simpl; intros; auto.\n  rewrite PTree.gsspec in H1. destruct (peq x0 x). congruence. eauto.\nQed.\n\nLemma set_list_complete:\n  forall te xl tyl e,\n  satisf te e -> map te xl = tyl ->\n  exists e', set_list e xl tyl = OK e' /\\ satisf te e'.\nProof.\n  induction xl; intros; inv H0; simpl.\n  econstructor; eauto.\n  exploit (set_complete te e a (te a)); auto. intros (e1 & P & Q).\n  exploit (IHxl (map te xl) e1); auto. intros (e2 & U & V).\n  exists e2; split; auto. rewrite P; auto.\nQed.\n\nLemma move_complete:\n  forall te e r1 r2,\n  satisf te e -> te r1 = te r2 ->\n  exists changed e', move e r1 r2 = OK(changed, e') /\\ satisf te e'.\nProof.\n  unfold move; intros. elim H; intros P Q.\n  assert (Q': forall x y, In (x, y) ((r1, r2) :: te_equ e) -> te x = te y).\n  { intros. destruct H1; auto. congruence. }\n  destruct (peq r1 r2). econstructor; econstructor; eauto.\n  destruct (te_typ e)!r1 as [ty1|] eqn:E1;\n  destruct (te_typ e)!r2 as [ty2|] eqn:E2.\n- replace ty2 with ty1. rewrite dec_eq_true. econstructor; econstructor; eauto.\n  exploit (P r1); eauto. exploit (P r2); eauto. congruence.\n- econstructor; econstructor; split; eauto.\n  split; simpl; intros; auto. rewrite PTree.gsspec in H1. destruct (peq x r2).\n  inv H1. rewrite <- H0. eauto.\n  eauto.\n- econstructor; econstructor; split; eauto.\n  split; simpl; intros; auto. rewrite PTree.gsspec in H1. destruct (peq x r1).\n  inv H1. rewrite H0. eauto.\n  eauto.\n- econstructor; econstructor; split; eauto.\n  split; eauto.\nQed.\n\nLemma solve_rec_complete:\n  forall te q e changed,\n  satisf te e ->\n  (forall r1 r2, In (r1, r2) q -> te r1 = te r2) ->\n  exists e' changed', solve_rec e changed q = OK(e', changed') /\\ satisf te e'.\nProof.\n  induction q; simpl; intros.\n- econstructor; econstructor; eauto.\n- destruct a as [r1 r2].\n  exploit (move_complete te e r1 r2); auto. intros (changed1 & e1 & A & B).\n  exploit (IHq e1 (changed || changed1)); auto. intros (e' & changed' & C & D).\n  exists e'; exists changed'. rewrite A; simpl; rewrite C; auto.\nQed.\n\nLemma solve_constraints_complete:\n  forall te e, satisf te e -> exists e', solve_constraints e = OK e' /\\ satisf te e'.\nProof.\n  intros te e. functional induction (solve_constraints e); intros.\n- exists e; auto.\n- exploit (solve_rec_complete te (te_equ e) {| te_typ := te_typ e; te_equ := nil |} false).\n  destruct H; split; auto. simpl; tauto.\n  destruct H; auto.\n  intros (e1 & changed1 & P & Q).\n  apply IHr. congruence.\n- exploit (solve_rec_complete te (te_equ e) {| te_typ := te_typ e; te_equ := nil |} false).\n  destruct H; split; auto. simpl; tauto.\n  destruct H; auto.\n  intros (e1 & changed1 & P & Q).\n  congruence.\nQed.\n\nLemma solve_complete:\n  forall te e, satisf te e -> exists te', solve e = OK te'.\nProof.\n  intros. unfold solve.\n  destruct (solve_constraints_complete te e H) as (e' & P & Q).\n  econstructor. rewrite P. simpl. eauto.\nQed.\n\nEnd UniSolver.\n\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/compcert_new/common/Unityping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.26352969228783424}}
{"text": "Welcome to Coq ciosx:/builds/workspace/coq-8.5pl3-macos,(detached from 2290dbb) (2290dbb9c95b63e693ced647731623e64297f5c8)\n\nCoq < Section UseAuto002.\n\nCoq < Require Import Arith Classical.\n[Loading ML file z_syntax_plugin.cmxs ... done]\n[Loading ML file quote_plugin.cmxs ... done]\n[Loading ML file newring_plugin.cmxs ... done]\n<W> Grammar extension: in [tactic:simple_tactic], some rule has been masked\n<W> Grammar extension: in [tactic:simple_tactic], some rule has been masked\n<W> Grammar extension: in [tactic:simple_tactic], some rule has been masked\n<W> Grammar extension: in [tactic:simple_tactic], some rule has been masked\n<W> Grammar extension: in [tactic:simple_tactic], some rule has been masked\n\nCoq < Goal 2 + 3 = 5.\n1 subgoal\n  \n  ============================\n  2 + 3 = 5\n\nUnnamed_thm < info_auto.\nDebug: (* info auto : *)\nDebug:  apply @eq_refl.\nNo more subgoals.\n\nUnnamed_thm < Qed.\ninfo_auto.\n\nQed.\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/foundations/useauto002.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2635296922878342}}
{"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 ZArith.\nImport ListNotations.\n\nFrom compcert.cfrontend Require Csyntax Ctypes Cop.\nFrom compcert.common Require Values.\nFrom compcert.lib Require Import Integers.\n\n\nModule MyList.\n\n  Definition t := list int64.\n  Definition index_s32 (l: t) (idx: int): int64 := \n    match List.nth_error l (Z.to_nat (Int.unsigned idx)) with\n    | Some i => i\n    | None => Integers.Int64.zero\n    end.\n  Definition index_nat (l: t) (idx: nat): int64 := \n    List.nth idx l Integers.Int64.zero.\n\nEnd MyList.\n\n(** length of MyList should be a extern variable? *)\n\nDefinition MyListType := MyList.t.\nDefinition MyListIndexs32 := MyList.index_s32.\nDefinition MyListIndexnat := MyList.index_nat.\n\nDefinition default_list: MyListType :=  [].", "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/comm/List64.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.26348251969804043}}
{"text": "(**\nThis file is part of the Flocq formalization of floating-point\narithmetic in Coq: http://flocq.gforge.inria.fr/\n\nCopyright (C) 2009-2018 Sylvie Boldo\n#<br />#\nCopyright (C) 2009-2018 Guillaume Melquiond\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 3 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nCOPYING file for more details.\n*)\n\n(** * Fixed-point format *)\nRequire Import Raux Defs Round_pred Generic_fmt Ulp Round_NE.\n\nSection RND_FIX.\n\nVariable beta : radix.\n\nNotation bpow := (bpow beta).\n\nVariable emin : Z.\n\nInductive FIX_format (x : R) : Prop :=\n  FIX_spec (f : float beta) :\n    x = F2R f -> (Fexp f = emin)%Z -> FIX_format x.\n\nDefinition FIX_exp (e : Z) := emin.\n\n(** Properties of the FIX format *)\n\nGlobal Instance FIX_exp_valid : Valid_exp FIX_exp.\nProof.\nintros k.\nunfold FIX_exp.\nsplit ; intros H.\nnow apply Zlt_le_weak.\nsplit.\napply Z.le_refl.\nnow intros _ _.\nQed.\n\nTheorem generic_format_FIX :\n  forall x, FIX_format x -> generic_format beta FIX_exp x.\nProof.\nintros x [[xm xe] Hx1 Hx2].\nrewrite Hx1.\nnow apply generic_format_canonical.\nQed.\n\nTheorem FIX_format_generic :\n  forall x, generic_format beta FIX_exp x -> FIX_format x.\nProof.\nintros x H.\nrewrite H.\neexists ; repeat split.\nQed.\n\nTheorem FIX_format_satisfies_any :\n  satisfies_any FIX_format.\nProof.\nrefine (satisfies_any_eq _ _ _ (generic_format_satisfies_any beta FIX_exp)).\nintros x.\nsplit.\napply FIX_format_generic.\napply generic_format_FIX.\nQed.\n\nGlobal Instance FIX_exp_monotone : Monotone_exp FIX_exp.\nProof.\nintros ex ey H.\napply Z.le_refl.\nQed.\n\nTheorem ulp_FIX :\n  forall x, ulp beta FIX_exp x = bpow emin.\nProof.\nintros x; unfold ulp.\ncase Req_bool_spec; intros Zx.\ncase (negligible_exp_spec FIX_exp).\nintros T; specialize (T (emin-1)%Z); contradict T.\nunfold FIX_exp; omega.\nintros n _; reflexivity.\nreflexivity.\nQed.\n\nEnd RND_FIX.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/compcert_new/flocq/Core/FIX.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.263482513122497}}
{"text": "(***\n * Oqarina\n * Copyright 2021 Carnegie Mellon University.\n *\n * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING\n * INSTITUTE MATERIAL IS FURNISHED ON AN \"AS-IS\" BASIS. CARNEGIE MELLON\n * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR\n * IMPLIED, AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF\n * FITNESS FOR PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS\n * OBTAINED FROM USE OF THE MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT\n * MAKE ANY WARRANTY OF ANY KIND WITH RESPECT TO FREEDOM FROM PATENT,\n * TRADEMARK, OR COPYRIGHT INFRINGEMENT.\n *\n * Released under a BSD (SEI)-style license, please see license.txt or\n * contact permission@sei.cmu.edu for full terms.\n *\n * [DISTRIBUTION STATEMENT A] This material has been approved for public\n * release and unlimited distribution.  Please see Copyright notice for\n * non-US Government use and distribution.\n *\n * This Software includes and/or makes use of the following Third-Party\n * Software subject to its own license:\n *\n * 1. Coq theorem prover (https://github.com/coq/coq/blob/master/LICENSE)\n * Copyright 2021 INRIA.\n *\n * 2. Coq JSON (https://github.com/liyishuai/coq-json/blob/comrade/LICENSE)\n * Copyright 2021 Yishuai Li.\n *\n * DM21-0762\n***)\n\n(*| .. coq:: none |*)\n\n(** Coq Library *)\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Strings.String.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.Lists.List.\nImport ListNotations.\nRequire Import Coq.Logic.Decidable.\n\n(** Oqarina library *)\nRequire Import Oqarina.AADL.Kernel.categories.\nRequire Import Oqarina.core.identifiers.\nRequire Import Oqarina.coq_utils.utils.\n(* end hide *)\n\n#[local] Open Scope Z_scope.\n#[local] Open Scope string_scope.\n(*| .. coq:: |*)\n\n(*|\n\nProperties\n==========\n\n|*)\n\nDefinition INT := Z.\nDefinition REAL := Z.\n\n(*+ Property Types *)\n\n(* should we use this? *)\nInductive enumeration_literal :=\n| EnumLiteral (name : identifier).\n\nDefinition enumeration_type :=\n  list identifier.\n(* !!! unique identifiers *)\n\nInductive unit_literal :=\n| BaseUnit (name : identifier)\n| DerivedUnit (name : identifier) (base: identifier) (factor: nat).\n\nDefinition units_type :=\n  list unit_literal.\n(* !!! unique identifiers, derived/base unit consistency, factor int or real *)\n\nInductive int_range_constraint :=\n  IRC (min max : INT).\n\nInductive real_range_constraint :=\n  RRC (rmin rmax : REAL).\n\nInductive range_constraint :=\n| C_IntRange (irc : int_range_constraint)\n| C_RealRange (rrc : real_range_constraint).\n\nInductive property_type :=\n(* Predeclared types are constructors for performance *)\n| aadlboolean | aadlstring | aadlinteger | aadlreal\n| PT_Enumeration (literals : list identifier)\n| PT_Units (units : units_type)\n| PT_Number (p : property_type) (* must be aadlinteger or aadlreal *)\n            (range: option range_constraint)\n            (units: option property_type)\n| PT_Range (p : property_type) (* must be numeric *)\n| PT_Classifier (* TBD *)\n| PT_Reference\n| PT_Record (fields: list field_decl)\n| PT_List (of: property_type) (* not allowed in named types in AADL2 (why???) *)\n| PT_TypeRef (qname : ps_qname)\nwith field_decl :=\n| FieldDecl (name: identifier) (type: property_type).\n\nLemma unit_literal_eq_dec : eq_dec unit_literal.\nProof.\n  unfold eq_dec.\n  decide equality ;\n   apply identifier_eq_dec ||\n   apply PeanoNat.Nat.eq_dec.\nQed.\n\nLemma units_type_eq_dec : eq_dec units_type.\nProof.\n  unfold eq_dec.\n  apply list_eq_dec.\n  apply unit_literal_eq_dec.\nQed.\n\nLemma int_range_constraint_eq_dec (a b : int_range_constraint): {a=b}+{a<>b}.\nProof.\n  decide equality;\n  apply Z.eq_dec.\nQed.\n\nLemma real_range_constraint_eq_dec (a b : real_range_constraint): {a=b}+{a<>b}.\nProof.\n  decide equality;\n  apply Z.eq_dec.\nQed.\n\nLemma range_constraint_eq_dec (a b : range_constraint): {a=b}+{a<>b}.\nProof.\n  decide equality.\n  apply int_range_constraint_eq_dec.\n  apply real_range_constraint_eq_dec.\nQed.\n\nLocal Hint Resolve units_type_eq_dec identifier_eq_dec range_constraint_eq_dec:core.\n\nLemma property_type_eq_dec (a b : property_type) : {a=b}+{a<>b}\n  with field_decl_eq_dec (a b : field_decl): {a=b}+{a<>b}.\nProof.\n  (* proof for property_type *)\n  repeat decide equality.\n\n  (* proof for field_decl_eq *)\n  decide equality.\nQed.\n\n(*! Examples *)\n\nCheck PT_TypeRef (PSQN \"ps\" \"pt\") : property_type.\nCheck aadlboolean : property_type.\nCheck PT_Units [BaseUnit (Id \"m\"); DerivedUnit (Id \"cm\") (Id \"m\") 100] : property_type.\nCheck PT_Number aadlinteger None None : property_type.\nCheck PT_Range aadlinteger : property_type.\n\nDefinition is_numeric_predef (p : property_type) : bool :=\n  match p with\n  | aadlinteger | aadlreal => true\n  | _ => false\n  end.\n\nInductive is_numeric_predefR : property_type -> Prop :=\n| Predef_Int : is_numeric_predefR aadlinteger\n| Predef_Real : is_numeric_predefR aadlstring.\n\nDefinition property_type_wf (t : property_type) : bool :=\n  match t with\n  | PT_Number p _ _ => is_numeric_predef p\n  | PT_Range p => is_numeric_predef p\n  (* !!! add more *)\n  | _ => true\n  end.\n\n(*+ Property Expressions and Values *)\n\nInductive property_value :=\n| PV_Bool (b : bool)\n| PV_String (s : string)\n| PV_Int (n : Z)\n| PV_Real (r : REAL)\n| PV_IntU (n : Z) (unit : property_value)\n| PV_RealU (r : REAL) (unit : property_value)\n| PV_Enum (i : identifier)\n| PV_Unit (i : identifier)\n| PV_IntRange (min max : property_value)\n| PV_RealRange (min max : property_value)\n| PV_IntRangeD (min max : property_value) (delta : property_value)\n| PV_RealRangeD (min max : property_value) (delta : property_value)\n| PV_PropertyRef (qname : ps_qname) (* ref to property or constant *)\n| PV_Classifier (* TBD *)\n| PV_ModelRef (path : list identifier)\n| PV_Record (fields : list field_value)\n| PV_List (elements: list property_value)\n| PV_Computed (function : string)\nwith field_value :=\n| FieldVal (name : identifier) (value : property_value).\n\nLocal Hint Resolve bool_dec string_dec Z.eq_dec ps_qname_eq_dec: core.\n\nLemma property_value_eq_dec (a b : property_value) : {a=b}+{a<>b}\nwith field_value_eq_dec (a b : field_value) : {a=b}+{a<>b}.\nProof.\n  decide equality;\n  apply list_eq_dec; auto || auto.\n\n  decide equality.\nDefined.\n\n(*+ Property Sets *)\n\nInductive property_set_declaration :=\n| PropertyTypeDecl (name : identifier) (type : property_type)\n| PropertyConstantDecl (name : identifier) (type: property_type)\n                       (value: property_value)\n| PropertyDecl (name : identifier) (type: property_type)\n               (default: option property_value)\n               (appliesTo : list AppliesToCategory).\n\nNotation \"s ':type' t\" := (PropertyTypeDecl (Id s) t) (at level 75).\nNotation \"s ':const' t '=>' v\" := (PropertyConstantDecl (Id s) t v)\n                                   (at level 75, t at next level).\nNotation \"s ':prop' t '=>' d 'applies' a\" :=\n  (PropertyDecl (Id s) t d a)\n    (at level 75, t at next level, d at next level, a at next level ).\n\nDefinition Applicable_ComponentCategory (p : property_set_declaration) :=\n  match p with\n  | PropertyDecl _ _ _ lcat => lcat\n  | _ => nil\n  end.\n\n(** Property Association *)\n\n(** %\\begin{definition}[Property association]\nA property association binds a property value to a property type.\n  \\end{definition} %\n\n*)\n\nRecord property_association := {\n    P : ps_qname;\n    PV : property_value }.\n\nLemma property_association_eq_dec (a b : property_association): {a=b}+{a<>b}.\nProof.\n  decide equality.\n  apply property_value_eq_dec.\nDefined.\n\n(** AADL Property set *)\n\nInductive property_set :=\n| PropertySet (name : identifier) (declarations : list property_set_declaration).\n\nDefinition property_set_name (ps : property_set) :=\n  match ps with\n  | PropertySet name _ => name\n  end .\n\nDefinition property_sets := list property_set.\n", "meta": {"author": "Oqarina", "repo": "oqarina", "sha": "5a5ea65688188e462b20d30ee4e5eba08285f629", "save_path": "github-repos/coq/Oqarina-oqarina", "path": "github-repos/coq/Oqarina-oqarina/oqarina-5a5ea65688188e462b20d30ee4e5eba08285f629/src/AADL/Kernel/properties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.263482513122497}}
{"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 *)\nSet Implicit Arguments.\n\nRequire Import Morphisms.\nRequire Import vgtac.\nRequire Import Monad.\nRequire Import DLat DPow.\n\nModule Type FOLDABLE (A : KEY).\n\nAxiom t : Type.\n\nAxiom empty : t.\n\nAxiom mem : A.t -> t -> bool.\n\nAxiom empty_1 : forall e, mem e empty = false.\n\nAxiom add : A.t -> t -> t.\n\nAxiom mem_add_1 : forall l1 l2 s (Hl : A.eq l1 l2), mem l1 (add l2 s) = true.\n\nAxiom mem_add_2 :\n  forall l1 l2 s (Hl : not (A.eq l1 l2)), mem l1 (add l2 s) = mem l1 s.\n\nAxiom fold : forall T (f : A.t -> T -> T) (s : t) (init : T), T.\n\nAxiom fold_1 :\n  forall (T : Type) (P : T -> Prop) f e s (Hmem : mem e s = true)\n     (He : forall (x : T), P (f e x))\n     (Hf_mono : forall e' (x : T) (Hx : P x), P (f e' x))\n     (Hf_eq : forall e1 e2 (He1 : A.eq e1 e2) (x : T) (He1 : P (f e1 x)),\n         P (f e2 x))\n     (x : T),\n    P (fold f s x).\n\nAxiom fold_3  :\n  forall (T : Type) (P : T -> Prop) f s\n     (Hf_mono : forall e x (He : mem e s = true) (Hx : P x), P (f e x))\n     (x : T) (Hx : P x),\n    P (fold f s x).\n\nAxiom fold2_1 :\n  forall T (P : T -> T -> Prop) (P_trans : forall x y z, P x y -> P y z -> P x z)\n         f f' i\n         (Hf_ext : forall e x, P x (f e x))\n         (Hff' : forall e x1 x2 (Hi : P i x1) (Hx : P x1 x2),\n                   P (f e x1) (f' e x2))\n         s (x1 x2 : T) (Hi : P i x1) (Hx : P x1 x2),\n    P (fold f s x1) (fold f' s x2).\n\nEnd FOLDABLE.\n\nModule SetMap (K1 : KEY) (A : FOLDABLE K1) (K2 : KEY) (B : FOLDABLE K2).\n\nDefinition map f s := A.fold (fun e acc => B.add (f e) acc) s B.empty.\n\nLemma map_1 :\n  forall f s e (Hf: Proper (K1.eq ==> K2.eq) f) (Hmem : A.mem e s = true),\n    B.mem (f e) (map f s) = true.\nProof.\ni. unfold map. eapply A.fold_1.\n- apply Hmem.\n- i. apply B.mem_add_1. apply K2.eq_refl.\n- i. elim (K2.eq_dec (f e) (f e')); i.\n  + by apply B.mem_add_1.\n  + rewrite B.mem_add_2; by auto.\n- i. elim (K2.eq_dec (f e) (f e2)); i.\n  + apply B.mem_add_1. by auto.\n  + rewrite B.mem_add_2; [|by auto].\n    rewrite B.mem_add_2 in He0; [by auto|].\n    intro. elim b. apply K2.eq_trans with (f e1); [by auto|by apply Hf].\nQed.\n\nLemma map_diff :\n  forall f s e (Hf : forall e', ~ K2.eq e (f e')), B.mem e (map f s) = false.\nProof.\ni. unfold map. eapply A.fold_3; [|by apply B.empty_1].\ni. rewrite B.mem_add_2; [by auto|].\nintro Hinv. eapply Hf. by apply Hinv.\nQed.\n\nEnd SetMap.\n\nModule BigJoin (K : KEY) (A : FOLDABLE K) (B : LAT).\n\n(* Set comprehension style 1\n\nbig_join { f e x | e \\in s }\n\n- Type of f is (Foldable.elt -> T.t -> T.t)\n- T is a lattice module\n*)\n\nDefinition big_join f s x :=\n  A.fold (fun s acc => B.join acc (f s x)) s x.\n\nLemma big_join_1' :\n  forall f e s x (Ha : A.mem e s = true)\n         (Hf: Proper (K.eq ==> B.eq ==> B.eq) f),\n    B.le (f e x) (A.fold (fun s acc => B.join acc (f s x)) s x).\nProof.\ni. unfold big_join.\napply A.fold_1 with e.\n- by apply Ha.\n- i; by apply B.join_right.\n- i; eapply B.le_trans; [by apply Hx|by apply B.join_left].\n- i. eapply B.le_trans; [by apply He0|].\n  apply B.join_le; [apply B.le_refl; by apply B.eq_refl|].\n  apply B.le_refl. apply Hf; [by apply He1|by apply B.eq_refl].\nQed.\n\nLemma big_join_1 :\n  forall f e s x (Ha : A.mem e s = true)\n         (Hf: Proper (K.eq ==> B.eq ==> B.eq) f),\n    B.le (f e x) (big_join f s x).\nProof. by apply big_join_1'. Qed.\n\nDefinition weak_big_join (f : K.t -> B.t -> B.t) s x := A.fold f s x.\n\nLemma weak_big_join_1' :\n  forall f e s x (Ha : A.mem e s = true)\n         (Hf_mono: Proper (K.eq ==> B.le ==> B.le) f)\n         (Hf_ext: forall e x, B.le x (f e x)),\n    B.le (f e x) (A.fold f s x).\nProof.\ni. eapply B.le_trans; [apply big_join_1; [by apply Ha|]|].\n- intros k1 k2 Hk v1 v2 Hv. apply B.le_antisym.\n  + apply Hf_mono; by auto using B.le_refl.\n  + apply Hf_mono; by auto using K.eq_sym, B.le_refl, B.eq_sym.\n- unfold big_join. eapply A.fold2_1.\n  + by apply B.le_trans.\n  + i. by apply B.join_left.\n  + i. apply B.join_lub.\n    * eapply B.le_trans; [by apply Hx|].\n      eapply B.le_trans; [by apply Hf_ext|].\n      apply Hf_mono; [by apply K.eq_refl|apply B.le_refl; by apply B.eq_refl].\n    * apply Hf_mono; [by apply K.eq_refl|].\n      eapply B.le_trans; [by apply Hi|by apply Hx].\n  + apply B.le_refl; by apply B.eq_refl.\n  + apply B.le_refl; by apply B.eq_refl.\nQed.\n\nLemma weak_big_join_1 :\n  forall f e s x (Ha : A.mem e s = true)\n         (Hf_mono: Proper (K.eq ==> B.le ==> B.le) f)\n         (Hf_ext: forall e x, B.le x (f e x)),\n    B.le (f e x) (weak_big_join f s x).\nProof. by apply weak_big_join_1'. Qed.\n\nEnd BigJoin.\n\nModule BigJoinM (Import M : Monad) (K : KEY) (A : FOLDABLE K) (B : LAT).\n\n(* Set comprehension style 1\n\nbig_join { f e x | e \\in s }\n\n- Type of f is (Foldable.elt -> T.t -> M.m T.t)\n- T is a lattice module\n*)\n\nDefinition big_join f s x :=\n  let f' s acc :=\n      do acc' <- acc;\n      do v <- f s x;\n      ret (B.join acc' v) in\n  A.fold f' s (ret x).\n\nDefinition weak_big_join (f : K.t -> B.t -> m B.t) s x :=\n  let f' s acc :=\n      do acc' <- acc;\n      f s acc' in\n  A.fold f' s x.\n\nSection Locs.\n\nLemma b_equiv : zb_equiv B.eq.\nProof.\nconstructor.\n- intro. by apply B.eq_refl.\n- intros x y. by apply B.eq_sym.\n- intros x y z. by apply B.eq_trans.\nQed.\n\nDefinition eq_refl := zb_equiv_refl (eq_equiv b_equiv).\n\nDefinition eq_sym := zb_equiv_sym (eq_equiv b_equiv).\n\nDefinition eq_trans := zb_equiv_trans (eq_equiv b_equiv).\n\nLemma b_order : zb_order B.eq B.le.\nProof.\nconstructor.\n- intro. by apply B.le_refl.\n- intros x y. by apply B.le_antisym.\n- intros x y z. by apply B.le_trans.\nQed.\n\nDefinition le_refl := zb_order_refl (le_order b_equiv b_order).\n\nDefinition le_antisym := zb_order_antisym (le_order b_equiv b_order).\n\nDefinition le_trans := zb_order_trans (le_order b_equiv b_order).\n\nLemma big_join_1' :\n  forall f e s x (Ha : A.mem e s = true)\n         (Hf : Proper (K.eq ==> B.le ==> le b_order) f),\n    let f' s acc :=\n        do acc' <- acc;\n        do v <- f s x;\n        ret (B.join acc' v) in\n    le b_order (f e x) (A.fold f' s (ret x)).\nProof.\ni. apply A.fold_1 with e.\n- by apply Ha.\n- unfold f'. i.\n  apply le_1; i.\n  apply le_2; i.\n  apply ret_mono.\n  apply B.join_right.\n- i. eapply le_trans; [by apply Hx|].\n  unfold f'.\n  apply le_2; i.\n  apply le_1; i.\n  apply ret_mono.\n  apply B.join_left.\n- i. eapply le_trans; [by apply He0|].\n  unfold f'.\n  eapply bind_mono; [ apply le_refl; apply eq_refl |].\n  intros v1 v2 Hv.\n  eapply bind_mono\n  ; [eapply Hf; [by apply He1|apply B.le_refl; by apply B.eq_refl]|].\n  intros v1' v2' Hv'.\n  apply ret_mono.\n  apply B.join_lub.\n  + eapply B.le_trans; [by apply Hv|by apply B.join_left].\n  + eapply B.le_trans; [by apply Hv'|by apply B.join_right].\nQed.\n\nLemma big_join_1 :\n  forall f e s x (Ha : A.mem e s = true)\n         (Hf : Proper (K.eq ==> B.le ==> le b_order) f),\n    le b_order (f e x) (big_join f s x).\nProof. by apply big_join_1'. Qed.\n\nLemma weak_big_join_1' :\n  forall f e s x (Ha : A.mem e s = true)\n         (Hf_mono : Proper (K.eq ==> B.le ==> le b_order) f)\n         (Hf_ext : forall e x, le b_order (ret x) (f e x)),\n    let f' s acc :=\n        do acc' <- acc;\n        f s acc' in\n    le b_order (f e x) (A.fold f' s (ret x)).\nProof.\ni. eapply le_trans; [apply big_join_1; [by apply Ha|by apply Hf_mono]|].\nunfold big_join. eapply A.fold2_1.\n- by apply le_trans.\n- i. apply le_2; i.\n  apply le_1; i.\n  apply ret_mono.\n  apply B.join_left.\n- unfold f'. i. apply le_3.\n  + apply le_trans with x2; [by auto|].\n    apply le_2. by apply Hf_ext.\n  + i. apply le_3.\n    * eapply le_trans; [apply le_refl; by apply left_unit|].\n      eapply bind_mono; [eapply le_trans; [by apply Hi|by apply Hx]|].\n      apply Hf_mono. by apply K.eq_refl.\n    * i. apply ret_join_lub; [by auto|by auto|by apply B.join_lub].\n- apply le_refl; apply eq_refl.\n- apply le_refl; apply eq_refl.\nQed.\n\nLemma weak_big_join_1 :\n  forall f e s x (Ha : A.mem e s = true)\n         (Hf_mono : Proper (K.eq ==> B.le ==> le b_order) f)\n         (Hf_ext : forall e x, le b_order (ret x) (f e x)),\n    le b_order (f e x) (weak_big_join f s (ret x)).\nProof. by apply weak_big_join_1'. Qed.\n\nEnd Locs.\n\nEnd BigJoinM.\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/Fold.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.26348251312249693}}
{"text": "Require Import Coq.omega.Omega.\nRequire Import Platform.Thread Platform.Arrays8 Platform.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": "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/Echo3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.26348250654695343}}
{"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.\n\nSection OBJ_VMM.\n\n  (** primitve: set the value of n-th page table's i-th first level entry*)\n  (** Since the page table is statically allocated, the contents of the first level page table can be calculated by their index*)\n  (** primitve: returns the contents of the n-th page table with the fisrt level index i and second level index vadr *)    \n  Definition PDE_Arg (n i: Z) : bool :=\n    if zle_lt 0 n num_proc then\n      if zle_le 0 i (PDX Int.max_unsigned) then\n        true\n      else false\n    else false.\n\n  Function setPDEU_spec (n i pi: Z) (adt: RData): option RData :=\n    match (ikern adt, ihost adt, init adt, ipt adt, PDE_Arg n i) with\n      | (true, true, true, true, true) =>\n        if zeq n (PT adt) then None\n        else\n          if zlt_lt 0 pi (nps adt) then\n            match ZMap.get pi (pperm adt) with\n              | PGAlloc  =>\n                let pt':= ZMap.set i (PDEValid pi (ZMap.init PTEUndef)) (ZMap.get n (ptpool adt)) in\n                Some adt {HP: FlatMem.free_page pi (HP adt)}\n                     {pperm: ZMap.set pi (PGHide (PGPMap n i)) (pperm adt)}\n                     {ptpool: ZMap.set n pt' (ptpool adt)}\n              | _ => None\n            end\n          else None\n      |_ => None\n    end.\n\n  Function rmvPDE_spec (n i: Z) (adt: RData): option RData :=\n    match (ikern adt, ihost adt, init adt, ipt adt, PDE_Arg n i) with\n      | (true, true, true, true, true) =>\n        let pt':= ZMap.set i PDEUnPresent (ZMap.get n (ptpool adt)) in\n        if (if (zeq n (PT adt)) then\n              if (pg adt) then true\n              else false\n            else false) then None\n        else\n          match ZMap.get i (ZMap.get n (ptpool adt)) with\n            | PDEValid pi _ =>\n              match ZMap.get pi (pperm adt) with\n                | PGHide (PGPMap _ _)  =>\n                  Some adt {pperm: ZMap.set pi PGAlloc (pperm adt)}\n                       {ptpool: ZMap.set n pt' (ptpool adt)}\n                | _ => None\n              end\n            | _ => Some adt {ptpool: ZMap.set n pt' (ptpool adt)}\n          end\n      |_ => None\n    end.\n\n  Definition PTE_Arg (n i vadr: Z): bool :=\n    if PDE_Arg n i then\n      if zle_le 0 vadr (PTX Int.max_unsigned) then\n        true\n      else false\n    else false.\n\n  Function getPTE_spec (n i vadr: Z) (adt: RData) : option Z :=\n    match (ikern adt, ihost adt, init adt, ipt adt, PTE_Arg n i vadr) with\n      | (true, true, true, true, true) =>\n        let pt:= ZMap.get n (ptpool adt) in\n        match ZMap.get i pt with\n          | PDEValid _ pdt =>\n            match ZMap.get vadr pdt with\n              | PTEValid padr p => \n                Some (padr * PgSize + PermtoZ p)\n              | PTEUnPresent => Some 0\n              | _ => None\n            end\n          | _ => None\n        end\n      | _ => None\n    end.\n\n  Function setPTE_spec (n i vadr padr perm: Z) (adt: RData) : option RData :=\n    match (ikern adt, ihost adt, init adt, ipt adt, PTE_Arg n i vadr, ZtoPerm perm) with\n      | (true, true, true, true, true, Some p) =>\n        if zeq n (PT adt) then None\n        else\n          if zlt_lt 0 padr (nps adt) then\n            let pt:= ZMap.get n (ptpool adt) in\n            match ZMap.get i pt with\n              | PDEValid pi pdt =>\n                let pdt':= ZMap.set vadr (PTEValid padr p) pdt in\n                let pt' := ZMap.set i (PDEValid pi pdt') pt in\n                Some adt {ptpool: ZMap.set n pt' (ptpool adt)}\n              | _ => None\n            end\n          else None\n      | _ => None\n    end.\n\nEnd OBJ_VMM.", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/objects/ObjVMMDef.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185944046238982, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.2634293333136543}}
{"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 -> bool -> ty\n  | TInterface : interface_id -> bool -> ty\n  | TUnit : ty.\n\nDefinition nullable (t : ty) :=\n  match t with\n  | TClass c _ => TClass c true\n  | TInterface i _ => TInterface i true\n  | TUnit => TUnit\n  end.\n\nHint Unfold nullable.\n\nInductive isNullable : ty -> Prop :=\n  | Nullable_Class :\n      forall c,\n        isNullable (TClass c true)\n  | Nullable_Interface :\n      forall i,\n        isNullable (TInterface i true)\n  | Nullable_TUnit :\n        isNullable TUnit.\n\nHint Constructors isNullable.\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.\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].\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.\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    | _ => 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    | _ => 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 n i fs ms,\n        classLookup P c = Some (Cls c i fs ms) ->\n        methodSigs P (TClass c n) (extractSigs ms)\n  | MSigs_Interface :\n      forall i n msigs,\n        interfaceLookup P i = Some (Interface i msigs) ->\n        methodSigs P (TInterface i n) msigs\n  | MSigs_ExtInterface :\n      forall i i1 i2 n n1 n2 msigs1 msigs2,\n        interfaceLookup P i = Some (ExtInterface i i1 i2) ->\n        methodSigs P (TInterface i1 n1) msigs1 ->\n        methodSigs P (TInterface i2 n2) msigs2 ->\n        methodSigs P (TInterface i n) (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/nullable/Syntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.26342842038870634}}
{"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 : core\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  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": "scuellar", "repo": "narcissus_errors", "sha": "8c547389030165e8620b43bb38ad87b9b65e5471", "save_path": "github-repos/coq/scuellar-narcissus_errors", "path": "github-repos/coq/scuellar-narcissus_errors/narcissus_errors-8c547389030165e8620b43bb38ad87b9b65e5471/src/QueryStructure/Implementation/Constraints/ConstraintChecksRefinements.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.26342842038870634}}
{"text": "Require Import Kami.AllNotations.\nRequire Import StdLibKami.RegArray.Ifc.\n\nSection Spec.\n  Context {ifcParams : Ifc.Params}.\n  Local Notation Idx := (Bit (Nat.log2_up size)).\n  Local Definition arrayName := (name ++ \".list\")%string.\n    \n  Local Open Scope kami_expr.\n  Local Open Scope kami_action.\n  \n  Local Definition read ty (idx: ty Idx) : ActionT ty k :=\n    Read array: (Array size k) <- arrayName;\n    Ret (#array @[ #idx]).\n\n  Local Definition write ty (writeRq : ty (WriteRq (Nat.log2_up size) k)): ActionT ty Void :=\n    Read array: (Array size k) <- arrayName;\n    Write arrayName: (Array size k) <- #array @[ #writeRq @% \"addr\" <- #writeRq @% \"data\" ];\n    Retv.\n  \n  Local Definition regs : list RegInitT := makeModule_regs (Register arrayName : (Array size k) <- Default)%kami.\n\n  Definition spec : Ifc :=\n    {|\n      Ifc.regs := regs;\n      Ifc.regFiles := nil;\n      Ifc.read := read;\n      Ifc.write := write\n    |}.\n\nEnd Spec.\n", "meta": {"author": "sifive", "repo": "StdLibKami", "sha": "01d3dffcec9d8bfc4f864b940974396ffe817314", "save_path": "github-repos/coq/sifive-StdLibKami", "path": "github-repos/coq/sifive-StdLibKami/StdLibKami-01d3dffcec9d8bfc4f864b940974396ffe817314/RegArray/Spec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2633723575031474}}
{"text": "Require Export concurrency.paco.src.paconotation concurrency.paco.src.pacotac concurrency.paco.src.pacodef.\nSet Implicit Arguments.\n\n(** ** Type Class for acc, mult, fold and unfold\n*)\n\nClass paco_class (A : Prop) :=\n{ pacoacctyp: Type\n; pacoacc : pacoacctyp\n; pacomulttyp: Type\n; pacomult : pacomulttyp\n; pacofoldtyp: Type\n; pacofold : pacofoldtyp\n; pacounfoldtyp: Type\n; pacounfold : pacounfoldtyp\n}.\n\nDefinition get_paco_cls {A} {cls: paco_class A} (a: A) := cls.\n\nCreate HintDb paco.\n\nLtac paco_class TGT method :=\n  let typ := fresh \"_typ_\" in let lem := fresh \"_lem_\" in\n  let TMP := fresh \"_tmp_\" in let X := fresh \"_X_\" in\n  let CLS := fresh \"_CLS_\" in\n  evar (typ: Type); evar (lem: typ);\n  assert(TMP: TGT -> True) by (\n    intros X; set (CLS := method _ (get_paco_cls X));\n    repeat red in CLS; clear X; revert lem;\n    match goal with [CLS := ?v |-_] => instantiate (1:= v) end;\n    clear CLS; exact I);\n  clear TMP; unfold typ in *; clear typ; revert lem.\n\n(** ** pfold tactic\n  - [pfold]\n*)\n\nLtac pfold := let x := fresh \"_x_\" in\n  repeat red;\n  match goal with [|- ?G] => paco_class G (@pacofold) end;\n  intro x; match goal with [x:=?lem|-_] => clear x; eapply lem end.\n\n(** ** punfold tactic\n  - [punfold H]\n*)\n\nLtac punfold H := let x := fresh \"_x_\" in\n  repeat red in H;\n  let G := type of H in paco_class G (@pacounfold);\n  intro x; match goal with [x:=?lem|-_] => clear x; eapply lem in H end;\n  eauto with paco.\n\n(** ** pmult tactic\n  - [pmult]\n*)\n\nLtac pmult := let x := fresh \"_x_\" in\n  repeat red;\n  match goal with [|- ?G] => paco_class G (@pacomult) end;\n  intro x; match goal with [x:=?lem|-_] => clear x; eapply lem end.\n\n(** ** pcofix tactic\n  - [pcofix CIH [with r]]\n*)\n\nTactic Notation \"pcofix\" ident(CIH) \"with\" ident(r) :=\n  let x := fresh \"_x_\" in\n  generalize _paco_mark_cons; repeat intro; repeat red;\n  match goal with [|- ?G] =>\n  paco_class G (@pacoacc); intro x;\n  match goal with [x:=?lem|-_] => clear x;\n    paco_revert_hyp _paco_mark;\n    pcofix CIH using lem with r\n  end end.\n\nTactic Notation \"pcofix\" ident(CIH) := pcofix CIH with r.\n\n(** ** [pclearbot] simplifies all hypotheses of the form [upaco{n} gf bot{n}] to [paco{n} gf bot{n}].\n*)\n\nLtac pclearbot :=\n  let X := fresh \"_X\" in\n  repeat match goal with\n  | [H: appcontext[pacoid] |- _] => red in H; destruct H as [H|X]; [|contradiction X]\n  end.\n\n(** ** [pdestruct H] and [pinversion H]\n*)\n\nLtac pdestruct H := punfold H; destruct H; pclearbot.\n\nLtac pinversion H := punfold H; inversion H; pclearbot.\n\n(** ** pmonauto tactic\n  - [pmonauto]\n*)\n\nLtac pmonauto :=\n  let IN := fresh \"IN\" in try (repeat intro; destruct IN; eauto; fail).\n\n(** Tactics for Internal Use Only *)\n\nLtac paco_cofix_auto :=\n  cofix; repeat intro;\n  match goal with [H: _ |- _] => destruct H end; econstructor;\n  try (match goal with [H: _|-_] => apply H end); intros;\n  lazymatch goal with [PR: _ |- _] => match goal with [H: _ |- _] => apply H in PR end end;\n  repeat match goal with [ H : _ \\/ _ |- _] => destruct H end; first [eauto; fail|eauto 10].\n\nLtac paco_revert :=\n  match goal with [H: _ |- _] => revert H end.\n\nNotation \"p <_paco_0= q\" :=\n  (forall (PR: p : Prop), q : Prop)\n  (at level 50, no associativity).\n\nNotation \"p <_paco_1= q\" :=\n  (forall _paco_x0 (PR: p _paco_x0 : Prop), q _paco_x0 : Prop)\n  (at level 50, no associativity).\n\nNotation \"p <_paco_2= q\" :=\n  (forall _paco_x0 _paco_x1 (PR: p _paco_x0 _paco_x1 : Prop), q _paco_x0 _paco_x1 : Prop)\n  (at level 50, no associativity).\n\nNotation \"p <_paco_3= q\" :=\n  (forall _paco_x0 _paco_x1 _paco_x2 (PR: p _paco_x0 _paco_x1 _paco_x2 : Prop), q _paco_x0 _paco_x1 _paco_x2 : Prop)\n  (at level 50, no associativity).\n\nNotation \"p <_paco_4= q\" :=\n  (forall _paco_x0 _paco_x1 _paco_x2 _paco_x3 (PR: p _paco_x0 _paco_x1 _paco_x2 _paco_x3 : Prop), q _paco_x0 _paco_x1 _paco_x2 _paco_x3 : Prop)\n  (at level 50, no associativity).\n\nNotation \"p <_paco_5= q\" :=\n  (forall _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 (PR: p _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 : Prop), q _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 : Prop)\n  (at level 50, no associativity).\n\nNotation \"p <_paco_6= q\" :=\n  (forall _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 (PR: p _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 : Prop), q _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 : Prop)\n  (at level 50, no associativity).\n\nNotation \"p <_paco_7= q\" :=\n  (forall _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 (PR: p _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 : Prop), q _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 : Prop)\n  (at level 50, no associativity).\n\nNotation \"p <_paco_8= q\" :=\n  (forall _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 _paco_x7 (PR: p _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 _paco_x7 : Prop), q _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 _paco_x7 : Prop)\n  (at level 50, no associativity).\n\nNotation \"p <_paco_9= q\" :=\n  (forall _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 _paco_x7 _paco_x8 (PR: p _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 _paco_x7 _paco_x8 : Prop), q _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 _paco_x7 _paco_x8 : Prop)\n  (at level 50, no associativity).\n\nNotation \"p <_paco_10= q\" :=\n  (forall _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 _paco_x7 _paco_x8 _paco_x9 (PR: p _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 _paco_x7 _paco_x8 _paco_x9 : Prop), q _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 _paco_x7 _paco_x8 _paco_x9 : Prop)\n  (at level 50, no associativity).\n\nNotation \"p <_paco_11= q\" :=\n  (forall _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 _paco_x7 _paco_x8 _paco_x9 _paco_x10 (PR: p _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 _paco_x7 _paco_x8 _paco_x9 _paco_x10 : Prop), q _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 _paco_x7 _paco_x8 _paco_x9 _paco_x10 : Prop)\n  (at level 50, no associativity).\n\nNotation \"p <_paco_12= q\" :=\n  (forall _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 _paco_x7 _paco_x8 _paco_x9 _paco_x10 _paco_x11 (PR: p _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 _paco_x7 _paco_x8 _paco_x9 _paco_x10 _paco_x11 : Prop), q _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 _paco_x7 _paco_x8 _paco_x9 _paco_x10 _paco_x11 : Prop)\n  (at level 50, no associativity).\n\nNotation \"p <_paco_13= q\" :=\n  (forall _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 _paco_x7 _paco_x8 _paco_x9 _paco_x10 _paco_x11 _paco_x12 (PR: p _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 _paco_x7 _paco_x8 _paco_x9 _paco_x10 _paco_x11 _paco_x12 : Prop), q _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 _paco_x7 _paco_x8 _paco_x9 _paco_x10 _paco_x11 _paco_x12 : Prop)\n  (at level 50, no associativity).\n\nNotation \"p <_paco_14= q\" :=\n  (forall _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 _paco_x7 _paco_x8 _paco_x9 _paco_x10 _paco_x11 _paco_x12 _paco_x13 (PR: p _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 _paco_x7 _paco_x8 _paco_x9 _paco_x10 _paco_x11 _paco_x12 _paco_x13 : Prop), q _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 _paco_x7 _paco_x8 _paco_x9 _paco_x10 _paco_x11 _paco_x12 _paco_x13 : Prop)\n  (at level 50, no associativity).\n\nNotation \"p <_paco_15= q\" :=\n  (forall _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 _paco_x7 _paco_x8 _paco_x9 _paco_x10 _paco_x11 _paco_x12 _paco_x13 _paco_x14 (PR: p _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 _paco_x7 _paco_x8 _paco_x9 _paco_x10 _paco_x11 _paco_x12 _paco_x13 _paco_x14 : Prop), q _paco_x0 _paco_x1 _paco_x2 _paco_x3 _paco_x4 _paco_x5 _paco_x6 _paco_x7 _paco_x8 _paco_x9 _paco_x10 _paco_x11 _paco_x12 _paco_x13 _paco_x14 : Prop)\n  (at level 50, no associativity).\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/pacotacuser.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.2633690980128591}}
{"text": "(** * Intuitionistic sequent calculus LJT *)\n\nSet Implicit Arguments.\n\n(* Require Import decidable_IN. *)\nRequire Import associations.\nRequire Import associations_extra.\nRequire Import language_syntax.\nRequire Import variable_sets.\nRequire Import substitution_wellformedness.\nRequire Import sublist.\nRequire Import fresh_name.\nRequire Import renaming.\n\n\n(** For the presentation of predicate logic, we adopt sequent calculus\n   to represent proofs. The advantage of such an approach is that\n   it has an easy-to-define notion of normal form (it is merely\n   the absence of the cut rule). A disadvantage is that it is less\n   natural than the so-called natural deduction.\n\n   The Gentzen-style sequent calculus [LJT] is obtained from the\n   intuitionistic sequent calculus [LJ] by restricting the use of\n   the left introduction rules of the implication and the universal\n   quantification.\n\n   Herbelin and Mints showed that there is a one-to-one correspondence\n   between cut-free proofs in [LJT] and normal lambda-terms.\n   This implies that LJT is a Curry-Howard-de Bruijn-style proof system. *)\n\nReserved Notation \"Ga |- A\" (at level 70).\nReserved Notation \"Ga ;; A |- C\" (at level 70, A at next level).\n\n\n(** ** Prove and Well-Formedness *)\n\nInductive prove : context -> fml -> Type :=\n  | ProofCont : forall (A C: fml) (Ga : context), \n    IN_ctx A Ga -> Ga ;; A |- C -> Ga |- C\n\n  | ProofImplyR : forall B C Ga, \n    B :: Ga |- C -> Ga |- B --> C\n\n  | ProofForallR : forall y (B : fml) Ga (a : name),\n    a # op_c (B :: Ga) ->\n    Ga |- open B y (Par a) -> \n    Ga |- (Forall y B)\n\n  where \"Ga |- A\" := (prove Ga A)\n\nwith prove_stoup : context -> fml -> fml -> Type :=\n  | ProofAxiom Ga C: wf_c Ga -> wf C -> Ga ;; C |- C\n\n  | ProofImplyL Ga D : forall B C, \n    Ga |- B -> Ga ;; C |- D -> Ga ;; (B --> C) |- D\n\n  | ProofForallL Ga C : forall y (u : trm) (B : fml), \n    wf_t u ->\n    Ga ;; open B y u |- C ->\n    Ga ;; Forall y B |- C\n\n  where \" Ga ;; B |- A \" := (prove_stoup Ga B A).\n\nNotation \"Ga |- A\" := (prove Ga A) (at level 70).\nNotation \"Ga ;; A |- C\" := (prove_stoup Ga A C) (at level 70, A at next level).\n\n(** REMARKS:\n\n   - All the formulae occurring in derivations are well-formed.\n     This is possible because we can primarily focus on [formula = pformula nil].\n\n   - The so-called [Exists-Fresh] style of quantification is used for the right\n     universal quantification. *)\n\nLemma wf_prove : \n  forall Ga A, \n    Ga |- A -> wf_c Ga /\\ wf A\n\n    with wf_prove_stoup : \n  forall Ga A B, \n    Ga ;; A |- B -> wf_c Ga /\\ (wf A /\\ wf B).\nProof.\n  (* wf_prove *)\n  - induction 1.\n    + cut (wf_c Ga /\\ wf A /\\ wf C); auto; tauto.\n    + destruct IHprove as [H0 H1].  \n      inversion H0; split; auto; auto using wImply. \n    + destruct IHprove; split; eauto using wForall.\n\n  (* wf_prove_stoup *)\n  - induction 1; auto.\n    + destruct IHprove_stoup as [H1 H2]; destruct H2 as [H2 H3]; \n      repeat split; try apply wImply; auto. \n      destruct (wf_prove Ga B p); auto. \n\n    + repeat (split; try tauto); apply open_forall_wf with (u := u); \n      tauto.\nDefined.\n\nHint Resolve wf_prove wf_prove_stoup.\nHint Rewrite wf_prove wf_prove_stoup.\n\n(** ** Weakening *)\n\n(** Simple structural induction on derication does not work.\n\n   - This is a well-known issue about the [Exists-Fresh] style of quantification.\n\n   - The [Exists-Fresh] style of quantification provides too _weak_ an induction principle.\n\n   - We suggest a solution to that issue using simultaneous [renaming].\n\n   - No alpha-conversion is necessary. *)\n\n(** Generalized Weakening Lemma  *)\n\nLemma weakening_gen : forall Ga De A eta,\n  sub_ctx_pre Ga De -> \n  wf_c De ->\n  Ga |- A ->\n  rename_c eta De |- rename eta A\n\nwith weakening_stoup_gen : forall Ga De A C eta,\n  sub_ctx_pre Ga De ->\n  wf_c De ->\n  Ga ;; A |- C ->\n  rename_c eta De ;; rename eta A |- rename eta C.\nProof.\n  - destruct 3; simpl. \n    + apply ProofCont with (rename eta A).\n      * apply rename_IN_ctx; auto with datatypes. \n      * apply weakening_stoup_gen with Ga; assumption.\n    + apply ProofImplyR.\n      change (rename_c eta (B :: De) |- rename eta C);\n      apply weakening_gen with (B :: Ga); auto.\n      * auto using sub_cons_3.\n      * apply wf_prove in H1; destruct H1 as [HL HR]. apply wCons; auto. \n        apply wf_c_wf with (B :: Ga); auto with datatypes. \n    + set (a0 := new\n                   ((a::nil) ++ op_c De ++ op B ++\n                             op_c (rename_c eta De) ++ \n                             op (Forall y (rename eta B)) ++\n                             dom eta ++ image eta ++\n                             op (Forall y B) ++ op_c Ga)).\n\n      simpl in n; destruct_notin.\n      assert (a0 <> a).\n      * contradict H4; subst; apply IN_eq.\n      * { rewrite <- context_rename_fresh with (a:=a)(a0:=a0); auto.\n          set (De0 := rename_c ((a,a0) :: nil) De).\n          rewrite <- rename_fresh with (a:=a0)(a0:= eta ** a); auto.\n          apply ProofForallR with a0. \n          - simpl ; apply notIN_app_2; try assumption;\n            [ apply notIN_op_rename | apply notIN_op_rename_c]\n            ; congruence.\n          - rewrite <- rename_c_fresh with (a:=a) (a0:=a0); auto.\n            + rewrite <- rename_fresh with (a:=a) (a0:=a0); auto.\n              set (eta0:= (a, a0) :: (a0, eta ** a) :: eta). unfold open.\n              assert (HH :  ((y, (Par a0)):: nil)= (rename_a eta0 ((y, Par a) :: nil))).\n            subst eta0; simpl; case_var; subst; auto; intuition.\n            {rewrite HH. rewrite <- rename_subst.\n             - apply weakening_gen with Ga; auto. \n               + apply sub_ctx_fresh_cst; assumption. \n               + apply (rename_wf_c ((a, a0) :: nil) H0).\n             - apply wf_fml_sub_name. apply open_forall_wf with (u:= Par a). \n               destruct (@wf_prove Ga (open B y (Par a)) H1); auto. \n            }\n            + subst De0; change a0 with (nil ** a0); \n              apply notIN_op_rename_c; auto; tauto.\n        }\n\n  (* stoup part  *)\n  - destruct 3.\n    + apply ProofAxiom.\n      * apply rename_wf_c; assumption.  \n      * apply rename_wf_f; assumption. \n\n    + apply ProofImplyL; eauto. \n    + simpl; apply ProofForallL with (u:=(rename_t eta u)).\n      * auto using rename_wf_t. \n      * { unfold open;\n          replace ((y, (rename_t eta u)) :: nil) \n                      with (rename_a eta ((y,  u) :: nil)).  \n          - rewrite <- rename_subst; eauto. change (dom ((y, u) :: nil)) with (y:: nil). \n            apply wf_fml_sub_name; apply open_forall_wf with u. \n            destruct (@wf_prove_stoup Ga (open B y u) C H1); tauto.\n          - tauto.\n        }\nDefined.\n\nLemma weakening : forall Ga De A,\n  sub_ctx_pre Ga De -> \n  wf_c De ->\n  Ga |- A ->\n  De |- A.\nProof.\n  intros.\n  rewrite <- (rename_c_nil De); rewrite <- (rename_nil A).\n  apply weakening_gen with Ga; auto.\nDefined.\n\nLemma weakening_stoup : forall Ga De A C,\n    sub_ctx_pre Ga De ->\n    wf_c De ->\n    Ga ;; A |- C ->\n    De ;; A |- C.\nProof.\n  intros.\n  rewrite <- (rename_c_nil De).\n  rewrite <- (rename_nil A);\n  rewrite <- (rename_nil C).\n  eauto using weakening_stoup_gen.\nDefined.\n\n(** Renaming Lemma *)\n\nLemma renaming_lamma : forall Ga A eta,\n  Ga |- A ->\n  rename_c eta Ga |- rename eta A.\nProof.\n  intros. apply weakening_gen with Ga; auto. \n  apply (@wf_prove Ga A); assumption.\nDefined.\n\nLemma renaming_stoup : forall Ga A C eta,\n  Ga ;; A |- C ->\n  rename_c eta Ga ;; rename eta A |- rename eta C.\nProof.\n  intros; apply weakening_stoup_gen with Ga; \n  auto; unfold sublist; apply (@wf_prove_stoup Ga A C H); auto.\nDefined.\n\n", "meta": {"author": "liganega", "repo": "bind", "sha": "5d4d215d82b8bd4d2c8ab91c0f629af93ee6b7e9", "save_path": "github-repos/coq/liganega-bind", "path": "github-repos/coq/liganega-bind/bind-5d4d215d82b8bd4d2c8ab91c0f629af93ee6b7e9/named/with_p/SYLJT_and_weakening.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.26336909801285907}}
{"text": "(** This file contains generic functions for manipulating,\n ** (i.e. substituting and finding) unification variables\n **)\nRequire Import Coq.omega.Omega.\nRequire Import ExtLib.Core.RelDec.\nRequire Import ExtLib.Data.ListNth.\nRequire Import ExtLib.Data.HList.\nRequire Import ExtLib.Tactics.\nRequire Import MirrorCore.Util.Forwardy.\nRequire Import MirrorCore.Util.Nat.\nRequire Import MirrorCore.Util.Compat.\nRequire Import MirrorCore.Lambda.ExprLift.\nRequire Import MirrorCore.Lambda.ExprDFacts.\nRequire Import MirrorCore.Lambda.ExprD.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nRequire Import Coq.Logic.FunctionalExtensionality.\n\nSection substitute.\n  Variable typ : Set.\n  Variable func : Set.\n\n  Section subst'.\n    Variable lookupU : uvar -> forall t, (expr typ func -> t) -> t -> t.\n    Variable lookupV : var -> forall t, (expr typ func -> t) -> t -> t.\n\n    Fixpoint subst' (lift_by : nat) (e : expr typ func)\n    : expr typ func :=\n      match e with\n        | Var v => match lt_rem v lift_by with\n                     | None => Var v\n                     | Some diff =>\n                       lookupV diff (lift 0 lift_by) e\n                   end\n        | Inj _ => e\n        | UVar u => lookupU u (lift 0 lift_by) e\n        | App l r => App (subst' lift_by l) (subst' lift_by r)\n        | Abs t e => Abs t (subst' (S lift_by) e)\n      end.\n  End subst'.\n\n  Definition subst\n             (lookupU : uvar -> forall t, (expr typ func -> t) -> t -> t)\n             (lookupV : var -> forall t, (expr typ func -> t) -> t -> t)\n             (under : nat) (e : expr typ func)\n  : expr typ func :=\n    subst' lookupU lookupV under e.\n\n  Variable RType_typ : RType typ.\n  Variable Typ2_Fun : Typ2 _ 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\n(*\n  Theorem lift_0 : forall (e : expr typ func) u, Lift.lift u 0 e = e.\n  Proof.\n    induction e; simpl; intros; Cases.rewrite_all_goal; auto.\n    consider (v ?[ lt ] u); auto.\n  Qed.\n*)\n\n  Definition Natural {T} (f : forall t, (T -> t) -> t -> t) : Prop :=\n       (exists v, forall t ret none, f t ret none = ret v)\n    \\/ (forall t ret none, f t ret none = none).\n\n  Lemma typeof_expr_subst'\n  : forall (lookupU lookupV : nat -> forall t, (expr _ _ -> t) -> t -> t) tus tus' tvs tvs'\n      (HNU : forall n, Natural (lookupU n))\n      (HNV : forall n, Natural (lookupV n))\n      (HlookupV : forall v e t,\n         nth_error tvs v = Some t ->\n         typeof_expr tus tvs e = Some t ->\n         typeof_expr tus' tvs' (lookupV v _ (fun x => x) e) = Some t)\n      (HlookupU : forall u e t,\n         nth_error tus u = Some t ->\n         typeof_expr tus tvs e = Some t ->\n         typeof_expr tus' tvs' (lookupU u _ (fun x => x) e) = Some t)\n      e y tvex,\n      typeof_expr tus (tvex ++ tvs) e = Some y ->\n      typeof_expr tus' (tvex ++ tvs')\n                     (subst' lookupU lookupV (length tvex) e) = Some y.\n  Proof.\n    induction e; simpl; intros; eauto.\n    { generalize (lt_rem_sound (length tvex) v).\n      destruct (lt_rem v (length tvex)); intros.\n      { destruct H0; subst.\n        specialize (HlookupV (v - length tvex)).\n        destruct (HNV (v - length tvex)).\n        { destruct H1.\n          revert HlookupV.\n          setoid_rewrite H1.\n          intros.\n          etransitivity; [ eapply (@typeof_expr_lift _ _ _ _ _ tus' x nil tvex tvs') | ].\n          simpl.\n          rewrite nth_error_app_R in H; eauto.\n          eapply H2; eauto.\n          instantiate (1 := Var (v - length tvex)).\n          eauto. }\n        { generalize (HlookupV (Var (v - length tvex)) y). setoid_rewrite H1.\n          simpl. intros.\n          rewrite nth_error_app_R in H; eauto.\n          rewrite nth_error_app_R; eauto. } }\n      { rewrite nth_error_app_L in H; auto.\n        simpl. rewrite nth_error_app_L; auto. } }\n    { forwardy.\n      erewrite IHe1; eauto.\n      erewrite IHe2; eauto. }\n    { forwardy.\n      inv_all; subst.\n      specialize (IHe y0 (t :: tvex)); simpl in IHe.\n      rewrite IHe; auto. }\n    { generalize (HlookupU u).\n      destruct (HNU u) as [ [ ? ? ] | ? ]; setoid_rewrite H0.\n      { etransitivity.\n        eapply (@typeof_expr_lift _ _ _ _ _ tus' _ nil tvex tvs').\n        simpl. eapply H1; eauto.\n        instantiate (1 := UVar u). assumption. }\n      { simpl. intros.\n        specialize (H1 (UVar u) y). auto. } }\n  Qed.\n\n  Theorem lambda_exprD_subst'\n  : forall lookupU lookupV tus tvs tus' tvs' P\n      (HNU : forall u, Natural (lookupU u)) (HNV : forall v, Natural (lookupV v))\n      (HlookupV : forall t e v vD vD_orig,\n         nth_error_get_hlist_nth _ tvs v = Some (@existT _ _ t vD) ->\n         lambda_exprD tus tvs t e = Some vD_orig ->\n         exists vD',\n           lambda_exprD tus' tvs' t (lookupV v _ (fun x => x) e) = Some vD' /\\\n           forall us vs us' vs',\n             P us vs us' vs' ->\n             vD_orig us vs = vD vs ->\n             vD vs = vD' us' vs')\n      (HlookupU : forall t e v vD vD_orig,\n         nth_error_get_hlist_nth _ tus v = Some (@existT _ _ t vD) ->\n         lambda_exprD tus tvs t e = Some vD_orig ->\n         exists vD',\n           lambda_exprD tus' tvs' t (lookupU v _ (fun x => x) e) = Some vD' /\\\n           forall us vs us' vs',\n             P us vs us' vs' ->\n             vD_orig us vs = vD us ->\n             vD us = vD' us' vs'),\n      forall e tvex (t : typ) eD,\n        lambda_exprD tus (tvex ++ tvs) t e = Some eD ->\n        exists eD',\n          lambda_exprD tus' (tvex ++ tvs') t (subst' lookupU lookupV (length tvex) e) = Some eD' /\\\n          forall us vs us' vs' vex,\n            P us vs us' vs' ->\n            eD us (hlist_app vex vs) = eD' us' (hlist_app vex vs').\n  Proof.\n    induction e; simpl; intros.\n    { generalize (lt_rem_sound (length tvex) v).\n      destruct (lt_rem v (length tvex)).\n      { destruct 1.\n        destruct (HNV n) as [ [ ? ? ] | ? ].\n        { generalize (HlookupV t (Var n) n); clear HlookupU HlookupV.\n          autorewrite with exprD_rw in *; simpl in *.\n          subst.\n          forwardy.\n          eapply nth_error_get_hlist_nth_appR in H0; eauto.\n          simpl in *. forward_reason; inv_all; subst.\n          Cases.rewrite_all_goal.\n          destruct y.\n          intro XXX; specialize (XXX _ _ eq_refl eq_refl).\n          forward_reason.\n          generalize (lambda_exprD_lift tus' x nil tvex tvs' x0).\n          simpl. rewrite H3. intros; forwardy.\n          eexists; split; [ eassumption | ].\n          intros.\n          etransitivity; [ | eapply (H7 us' Hnil vex vs') ].\n          rewrite H4.\n          eapply H5; eauto. }\n        { generalize (HlookupV t (Var n) n); clear HlookupU HlookupV.\n          autorewrite with exprD_rw in *; simpl in *.\n          subst.\n          forwardy.\n          generalize H0.\n          eapply nth_error_get_hlist_nth_appR in H0; eauto.\n          simpl in *. forward_reason; inv_all; subst.\n          Cases.rewrite_all_goal.\n          destruct y.\n          intro.\n          intro XXX; specialize (XXX _ _ eq_refl eq_refl).\n          forward_reason.\n          generalize (lambda_exprD_lift tus' (Var (v - length tvex)) nil tvex tvs' x).\n          simpl. rewrite H5. intros; forwardy.\n          cutrewrite (v - length tvex + length tvex = v) in H7; [ | omega ].\n          eexists; split; [ eassumption | ].\n          intros.\n          etransitivity; [ | eapply (H8 us' Hnil vex vs') ].\n          rewrite H4.\n          eapply H6; eauto. } }\n      { intros.\n        autorewrite with exprD_rw in *; simpl in *.\n        forwardy.\n        generalize (@nth_error_get_hlist_nth_appL _ typD tvs' _ _ H0).\n        generalize (@nth_error_get_hlist_nth_appL _ typD tvs _ _ H0).\n        clear H0.\n        intros; forward_reason; inv_all; subst.\n        revert H4 H0. Cases.rewrite_all_goal.\n        destruct x0; destruct x1; simpl in *.\n        intros; inv_all; subst.\n        Cases.rewrite_all_goal.\n        eexists; split; [ reflexivity | ].\n        simpl. intros.\n        Cases.rewrite_all_goal. reflexivity. } }\n    { autorewrite with exprD_rw in *; simpl in *.\n      forwardy.\n      rewrite H. eexists; split; [ reflexivity | ].\n      inv_all; subst.\n      reflexivity. }\n    { autorewrite with exprD_rw in *; simpl in *.\n      forwardy.\n      inv_all; subst.\n      eapply IHe1 in H0; clear IHe1.\n      eapply IHe2 in H1; clear IHe2.\n      forward_reason.\n      rewrite typeof_expr_subst' with (tvs := tvs) (tus := tus) (y := y); eauto.\n      { rewrite H1; clear H1.\n        rewrite H0; clear H0.\n        eexists; split; [ reflexivity | ].\n        unfold AbsAppI.exprT_App; intros; autorewrite_with_eq_rw.\n        erewrite H2; eauto. erewrite H3; eauto. }\n      { intros.\n        assert (exists vD,\n                  lambda_exprD tus tvs t0 e = Some vD)\n          by (eapply ExprFacts.typeof_expr_lambda_exprD; eauto).\n        destruct H6.\n        consider (nth_error_get_hlist_nth typD tvs v); intros.\n        { destruct s.\n          assert (x2 = t0).\n          { eapply nth_error_get_hlist_nth_Some in H7. destruct H7.\n            clear - H4 x3. simpl in *. congruence. }\n          subst.\n          eapply HlookupV with (v := v) in H6; eauto.\n          forward_reason. eapply ExprFacts.lambda_exprD_typeof_expr.\n          eauto. }\n        { clear - H4 H7; exfalso.\n          eapply nth_error_get_hlist_nth_None in H7. congruence. } }\n      { intros.\n        assert (exists vD,\n                  lambda_exprD tus tvs t0 e = Some vD)\n          by (eapply ExprFacts.lambda_exprD_typeof_expr; eauto).\n        destruct H6.\n        consider (nth_error_get_hlist_nth typD tus u); intros.\n        { destruct s.\n          assert (x2 = t0).\n          { eapply nth_error_get_hlist_nth_Some in H7. destruct H7.\n            clear - H4 x3. simpl in *. congruence. }\n          subst.\n          eapply HlookupU with (v := u) in H6; eauto.\n          forward_reason. eapply ExprFacts.lambda_exprD_typeof_expr.\n          eauto. }\n        { clear - H4 H7; exfalso.\n          eapply nth_error_get_hlist_nth_None in H7. congruence. } } }\n    { autorewrite with exprD_rw in *; simpl in *.\n      match goal with\n        | H : appcontext [ @typ2_match _ _ _ _ _ ?Y ] |- _ =>\n          let H := fresh in\n          destruct (@typ2_match_case _ _ _ _ _ Y) as [ [ ? [ ? [ ? H ] ] ] | H ];\n            ( try rewrite H in * )\n      end; clear H0.\n      { unfold Relim in *. red in x1; subst.\n        destruct (eq_sym (typ2_cast x x0)).\n        forward.\n        eapply IHe with (tvex := t :: tvex) in H0.\n        forward_reason. simpl in *.\n        rewrite H0.\n        eexists; split; [ reflexivity | ].\n        inv_all; subst.\n        intros. eapply functional_extensionality.\n        intros.\n        eapply (H2 us vs us' vs' (Hcons (Rcast_val r x2) vex)); assumption. }\n      { congruence. } }\n    { generalize (HlookupU t (UVar u) u); clear HlookupU HlookupV.\n      autorewrite with exprD_rw in *; simpl in *.\n      forwardy.\n      inv_all; subst.\n      rewrite H. rewrite H0.\n      intro HlookupU.\n      destruct y.\n      specialize (HlookupU _ _ eq_refl eq_refl).\n      forward_reason.\n      destruct (HNU u).\n      { forward_reason.\n        rewrite H3 in H1.\n        specialize (H3 _ (lift 0 (length tvex)) (UVar u)).\n        rewrite H3.\n        generalize (lambda_exprD_lift tus' x1 nil tvex tvs' x); simpl.\n        rewrite H1. intros.\n        forwardy.\n        eexists; split; [ eassumption | ].\n        intros. etransitivity; [ eapply H2 | ]; eauto.\n        eapply (H5 us' Hnil vex vs'). }\n      { rewrite H3 in *.\n        revert H1. autorewrite with exprD_rw; simpl.\n        intros. forward.\n        eexists; split; [ reflexivity | ].\n        inv_all; subst; intros.\n        eapply H2; eauto. } }\n  Qed.\n\n  Theorem lambda_exprD_subst\n  : forall tus tvs tus' tvs' lookupU lookupV P (e : expr typ func) (t : typ),\n      (forall u, Natural (lookupU u)) -> (forall v, Natural (lookupV v)) ->\n      (forall t e v vD vD_orig,\n         nth_error_get_hlist_nth _ tvs v = Some (@existT _ _ t vD) ->\n         lambda_exprD tus tvs t e = Some vD_orig ->\n         exists vD',\n           lambda_exprD tus' tvs' t (lookupV v _ (fun x => x) e) = Some vD' /\\\n           forall us vs us' vs',\n             P us vs us' vs' ->\n             vD_orig us vs = vD vs ->\n             vD vs = vD' us' vs') ->\n      (forall t e v vD vD_orig,\n         nth_error_get_hlist_nth _ tus v = Some (@existT _ _ t vD) ->\n         lambda_exprD tus tvs t e = Some vD_orig ->\n         exists vD',\n           lambda_exprD tus' tvs' t (lookupU v _ (fun x => x) e) = Some vD' /\\\n           forall us vs us' vs',\n             P us vs us' vs' ->\n             vD_orig us vs = vD us ->\n             vD us = vD' us' vs') ->\n      forall tvx eD,\n        lambda_exprD tus (tvx ++ tvs) t e = Some eD ->\n      exists eD',\n        lambda_exprD tus' (tvx ++ tvs') t (subst lookupU lookupV (length tvx) e) = Some eD' /\\\n        forall us vs us' vs' vx,\n          P us vs us' vs' ->\n          eD us (hlist_app vx vs) = eD' us' (hlist_app vx vs').\n  Proof.\n    intros.\n    eapply (@lambda_exprD_subst' lookupU lookupV tus tvs tus' tvs' P)\n      with (tvex := tvx) in H1; eauto.\n  Qed.\n\n  Definition mentions (uv : nat + nat) (e : expr typ func) : bool :=\n    match uv with\n      | inl u => _mentionsU u e\n      | inr v => _mentionsV v e\n    end.\n\n  Lemma mentions_App\n  : forall uv e1 e2,\n      mentions uv (App e1 e2) =\n      orb (mentions uv e1) (mentions uv e2).\n  Proof. destruct uv; reflexivity. Qed.\n\n  Definition lift_uv (uv : nat + nat) (n : nat) : nat + nat :=\n    match uv with\n      | inl u => inl u\n      | inr v => inr (v + n)\n    end.\n\n  Lemma mentions_Abs\n  : forall e uv t,\n      mentions uv (Abs t e) = match uv with\n                                | inl u => mentions (inl u) e\n                                | inr v => mentions (inr (S v)) e\n                              end.\n  Proof.\n    destruct uv; simpl; auto.\n  Qed.\n\n  Lemma mentions_Inj : forall x f, mentions x (Inj f) = false.\n    destruct x; reflexivity.\n  Qed.\n\n  Lemma mentionsV_lift\n  : forall n n0 (x : expr typ func) z,\n      _mentionsV (z + n0 + n) (lift z n x) = _mentionsV (z + n0) x.\n  Proof.\n    induction x; simpl; intros; auto.\n    { consider (v ?[ lt ] z).\n      { intros.\n        match goal with\n          | |- ?X = ?Y =>\n            consider X; consider Y; auto; try solve [ intros; exfalso ; omega ]\n        end. }\n      { intros.\n        match goal with\n          | |- ?X = ?Y =>\n            consider X; consider Y; auto; try solve [ intros; exfalso ; omega ]\n        end. intros.\n        rewrite NPeano.Nat.add_cancel_r in H1. exfalso; auto. } }\n    { rewrite IHx1. rewrite IHx2. reflexivity. }\n    { specialize (IHx (S z)). apply IHx. }\n  Qed.\n\n  Lemma or_rearrange : forall (A B C D : Prop),\n                         (A \\/ B) \\/ C \\/ D <->\n                         (A \\/ C) \\/ (B \\/ D).\n  Proof. clear; intuition. Qed.\n  Lemma or_iff : forall A B C D : Prop,\n                   (A <-> B) -> (C <-> D) ->\n                   ((A \\/ C) <-> (B \\/ D)).\n  Proof. clear. intuition. Qed.\n  Lemma exists_or : forall (T : Type) (P Q : T -> Prop),\n                      ((exists x : T, P x) \\/ (exists x : T, Q x)) <->\n                      (exists x, P x \\/ Q x).\n  Proof. clear. intuition; forward_reason; eauto.\n         destruct H. left; eauto. right; eauto.\n  Qed.\n  Lemma exists_iff : forall (T : Type) (P Q : T -> Prop),\n                       (forall x, P x <-> Q x) ->\n                       ((exists x, P x) <-> (exists y, Q y)).\n  Proof. clear. intuition; forward_reason; intuition eauto.\n         eapply H in H0; eauto. eapply H in H0; eauto.\n  Qed.\n  Lemma or_factor : forall A B C : Prop,\n                      ((A /\\ B) \\/ (A /\\ C)) <-> A /\\ (B \\/ C).\n  Proof. clear. intuition. Qed.\n\n  Lemma false_eq_true_False : false = true <-> False.\n  Proof. intuition. Qed.\n  Lemma False_and : forall A, (False /\\ A) <-> False.\n  Proof. intuition. Qed.\n  Lemma False_or : forall A, (False \\/ A) <-> A.\n  Proof. intuition. Qed.\n\nEnd substitute.\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/ExprSubstitute.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2633690907148242}}
{"text": "(* (c) Copyright 2006-2016 Microsoft Corporation and Inria.                  *)\n(* Distributed under the terms of CeCILL-B.                                  *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq path.\nFrom mathcomp Require Import choice fintype div tuple finfun bigop prime order.\nFrom mathcomp Require Import ssralg ssrnum finset fingroup morphism perm.\nFrom mathcomp Require Import automorphism quotient action zmodp cyclic center.\nFrom mathcomp Require Import gproduct commutator gseries nilpotent pgroup.\nFrom mathcomp Require Import sylow maximal frobenius matrix mxalgebra.\nFrom mathcomp Require Import mxrepresentation vector algC classfun character.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport Order.TTheory GroupScope GRing.Theory Num.Theory.\nLocal Open Scope ring_scope.\n\n(******************************************************************************)\n(* This file contains the definitions and properties of inertia groups:       *)\n(*   (phi ^ y)%CF == the y-conjugate of phi : 'CF(G), i.e., the class         *)\n(*                   function mapping x ^ y to phi x provided y normalises G. *)\n(*                   We take (phi ^ y)%CF = phi when y \\notin 'N(G).          *)\n(*  (phi ^: G)%CF == the sequence of all distinct conjugates of phi : 'CF(H)  *)\n(*                   by all y in G.                                           *)\n(*        'I[phi] == the inertia group of phi : CF(H), i.e., the set of y     *)\n(*                   such that (phi ^ y)%CF = phi AND H :^ y = y.             *)\n(*      'I_G[phi] == the inertia group of phi in G, i.e., G :&: 'I[phi].      *)\n(* conjg_Iirr i y == the index j : Iirr G such that ('chi_i ^ y)%CF = 'chi_j. *)\n(* cfclass_Iirr G i == the image of G under conjg_Iirr i, i.e., the set of j  *)\n(*                   such that 'chi_j \\in ('chi_i ^: G)%CF.                   *)\n(*   mul_Iirr i j == the index k such that 'chi_j * 'chi_i = 'chi[G]_k,       *)\n(*                   or 0 if 'chi_j * 'chi_i is reducible.                    *)\n(* mul_mod_Iirr i j := mul_Iirr i (mod_Iirr j), for j : Iirr (G / H).         *)\n(******************************************************************************)\n\nReserved Notation \"''I[' phi ]\"\n  (at level 8, format \"''I[' phi ]\").\nReserved Notation \"''I_' G [ phi ]\"\n  (at level 8, G at level 2, format \"''I_' G [ phi ]\").\n\nSection ConjDef.\n\nVariables (gT : finGroupType) (B : {set gT}) (y : gT) (phi : 'CF(B)).\nLocal Notation G := <<B>>.\n\nFact cfConjg_subproof :\n  is_class_fun G [ffun x => phi (if y \\in 'N(G) then x ^ y^-1 else x)].\nProof.\napply: intro_class_fun => [x z _ Gz | x notGx].\n  have [nGy | _] := ifP; last by rewrite cfunJgen.\n  by rewrite -conjgM conjgC conjgM cfunJgen // memJ_norm ?groupV.\nby rewrite cfun0gen //; case: ifP => // nGy; rewrite memJ_norm ?groupV.\nQed.\nDefinition cfConjg := Cfun 1 cfConjg_subproof.\n\nEnd ConjDef.\n\nPrenex Implicits cfConjg.\nNotation \"f ^ y\" := (cfConjg y f) : cfun_scope.\n\nSection Conj.\n\nVariables (gT : finGroupType) (G : {group gT}).\nImplicit Type phi : 'CF(G).\n\nLemma cfConjgE phi y x : y \\in 'N(G) -> (phi ^ y)%CF x = phi (x ^ y^-1)%g.\nProof. by rewrite cfunElock genGid => ->. Qed.\n\nLemma cfConjgEJ phi y x : y \\in 'N(G) -> (phi ^ y)%CF (x ^ y) = phi x.\nProof. by move/cfConjgE->; rewrite conjgK. Qed.\n\nLemma cfConjgEout phi y : y \\notin 'N(G) -> (phi ^ y = phi)%CF.\nProof.\nby move/negbTE=> notNy; apply/cfunP=> x; rewrite !cfunElock genGid notNy.\nQed.\n\nLemma cfConjgEin phi y (nGy : y \\in 'N(G)) :\n  (phi ^ y)%CF = cfIsom (norm_conj_isom nGy) phi.\nProof.\napply/cfun_inP=> x Gx.\nby rewrite cfConjgE // -{2}[x](conjgKV y) cfIsomE ?memJ_norm ?groupV.\nQed.\n\nLemma cfConjgMnorm phi :\n  {in 'N(G) &, forall y z, phi ^ (y * z) = (phi ^ y) ^ z}%CF.\nProof.\nmove=> y z nGy nGz.\nby apply/cfunP=> x; rewrite !cfConjgE ?groupM // invMg conjgM.\nQed.\n\nLemma cfConjg_id phi y : y \\in G -> (phi ^ y)%CF = phi.\nProof.\nmove=> Gy; apply/cfunP=> x; have nGy := subsetP (normG G) y Gy.\nby rewrite -(cfunJ _ _ Gy) cfConjgEJ.\nQed.\n\n(* Isaacs' 6.1.b *)\nLemma cfConjgM L phi :\n  G <| L -> {in L &, forall y z, phi ^ (y * z) = (phi ^ y) ^ z}%CF.\nProof. by case/andP=> _ /subsetP nGL; apply: sub_in2 (cfConjgMnorm phi). Qed.\n\nLemma cfConjgJ1 phi : (phi ^ 1)%CF = phi.\nProof. by apply/cfunP=> x; rewrite cfConjgE ?group1 // invg1 conjg1. Qed.\n\nLemma cfConjgK y : cancel (cfConjg y) (cfConjg y^-1 : 'CF(G) -> 'CF(G)).\nProof.\nmove=> phi; apply/cfunP=> x; rewrite !cfunElock groupV /=.\nby case: ifP => -> //; rewrite conjgKV.\nQed.\n\nLemma cfConjgKV y : cancel (cfConjg y^-1) (cfConjg y : 'CF(G) -> 'CF(G)).\nProof. by move=> phi /=; rewrite -{1}[y]invgK cfConjgK. Qed.\n\nLemma cfConjg1 phi y : (phi ^ y)%CF 1%g = phi 1%g.\nProof. by rewrite cfunElock conj1g if_same. Qed.\n\nFact cfConjg_is_linear y : linear (cfConjg y : 'CF(G) -> 'CF(G)).\nProof. by move=> a phi psi; apply/cfunP=> x; rewrite !cfunElock. Qed.\nCanonical cfConjg_additive y := Additive (cfConjg_is_linear y).\nCanonical cfConjg_linear y := AddLinear (cfConjg_is_linear y).\n\nLemma cfConjg_cfuniJ A y : y \\in 'N(G) -> ('1_A ^ y)%CF = '1_(A :^ y) :> 'CF(G).\nProof.\nmove=> nGy; apply/cfunP=> x; rewrite !cfunElock genGid nGy -sub_conjgV.\nby rewrite -class_lcoset -class_rcoset norm_rlcoset ?memJ_norm ?groupV.\nQed.\n\nLemma cfConjg_cfuni A y : y \\in 'N(A) -> ('1_A ^ y)%CF = '1_A :> 'CF(G).\nProof.\nby have [/cfConjg_cfuniJ-> /normP-> | /cfConjgEout] := boolP (y \\in 'N(G)).\nQed.\n\nLemma cfConjg_cfun1 y : (1 ^ y)%CF = 1 :> 'CF(G).\nProof.\nby rewrite -cfuniG; have [/cfConjg_cfuni|/cfConjgEout] := boolP (y \\in 'N(G)).\nQed.\n\nFact cfConjg_is_multiplicative y : multiplicative (cfConjg y : _ -> 'CF(G)).\nProof.\nsplit=> [phi psi|]; last exact: cfConjg_cfun1.\nby apply/cfunP=> x; rewrite !cfunElock.\nQed.\nCanonical cfConjg_rmorphism y := AddRMorphism (cfConjg_is_multiplicative y).\nCanonical cfConjg_lrmorphism y := [lrmorphism of cfConjg y].\n\nLemma cfConjg_eq1 phi y : ((phi ^ y)%CF == 1) = (phi == 1).\nProof. by apply: rmorph_eq1; apply: can_inj (cfConjgK y). Qed.\n\nLemma cfAutConjg phi u y : cfAut u (phi ^ y) = (cfAut u phi ^ y)%CF.\nProof. by apply/cfunP=> x; rewrite !cfunElock. Qed.\n\nLemma conj_cfConjg phi y : (phi ^ y)^*%CF = (phi^* ^ y)%CF.\nProof. exact: cfAutConjg. Qed.\n\nLemma cfker_conjg phi y : y \\in 'N(G) -> cfker (phi ^ y) = cfker phi :^ y.\nProof.\nmove=> nGy; rewrite cfConjgEin // cfker_isom.\nby rewrite morphim_conj (setIidPr (cfker_sub _)).\nQed.\n\nLemma cfDetConjg phi y : cfDet (phi ^ y) = (cfDet phi ^ y)%CF.\nProof.\nhave [nGy | not_nGy] := boolP (y \\in 'N(G)); last by rewrite !cfConjgEout.\nby rewrite !cfConjgEin cfDetIsom.\nQed.\n\nEnd Conj.\n\nSection Inertia.\n\nVariable gT : finGroupType.\n\nDefinition inertia (B : {set gT}) (phi : 'CF(B)) :=\n  [set y in 'N(B) | (phi ^ y)%CF == phi].\n\nLocal Notation \"''I[' phi ]\" := (inertia phi) : group_scope.\nLocal Notation \"''I_' G [ phi ]\" := (G%g :&: 'I[phi]) : group_scope.\n\nFact group_set_inertia (H : {group gT}) phi : group_set 'I[phi : 'CF(H)].\nProof.\napply/group_setP; split; first by rewrite inE group1 /= cfConjgJ1.\nmove=> y z /setIdP[nHy /eqP n_phi_y] /setIdP[nHz n_phi_z].\nby rewrite inE groupM //= cfConjgMnorm ?n_phi_y.\nQed.\nCanonical inertia_group H phi := Group (@group_set_inertia H phi).\n\nLocal Notation \"''I[' phi ]\" := (inertia_group phi) : Group_scope.\nLocal Notation \"''I_' G [ phi ]\" := (G :&: 'I[phi])%G : Group_scope.\n\nVariables G H : {group gT}.\nImplicit Type phi : 'CF(H).\n\nLemma inertiaJ phi y : y \\in 'I[phi] -> (phi ^ y)%CF = phi.\nProof. by case/setIdP=> _ /eqP->. Qed.\n\nLemma inertia_valJ phi x y : y \\in 'I[phi] -> phi (x ^ y)%g = phi x.\nProof. by case/setIdP=> nHy /eqP {1}<-; rewrite cfConjgEJ. Qed.\n\n(* To disambiguate basic inclucion lemma names we capitalize Inertia for      *)\n(* lemmas concerning the localized inertia group 'I_G[phi].                   *)\nLemma Inertia_sub phi : 'I_G[phi] \\subset G.\nProof. exact: subsetIl. Qed.\n\nLemma norm_inertia phi : 'I[phi] \\subset 'N(H).\nProof. by rewrite ['I[_]]setIdE subsetIl. Qed.\n\nLemma sub_inertia phi : H \\subset 'I[phi].\nProof.\nby apply/subsetP=> y Hy; rewrite inE cfConjg_id ?(subsetP (normG H)) /=.\nQed.\n\nLemma normal_inertia phi : H <| 'I[phi].\nProof. by rewrite /normal sub_inertia norm_inertia. Qed.\n\nLemma sub_Inertia phi : H \\subset G -> H \\subset 'I_G[phi].\nProof. by rewrite subsetI sub_inertia andbT. Qed.\n\nLemma norm_Inertia phi : 'I_G[phi] \\subset 'N(H).\nProof. by rewrite setIC subIset ?norm_inertia. Qed.\n\nLemma normal_Inertia phi : H \\subset G -> H <| 'I_G[phi].\nProof. by rewrite /normal norm_Inertia andbT; apply: sub_Inertia. Qed.\n\nLemma cfConjg_eqE phi :\n    H <| G ->\n  {in G &, forall y z, (phi ^ y == phi ^ z)%CF = (z \\in 'I_G[phi] :* y)}.\nProof.\ncase/andP=> _ nHG y z Gy; rewrite -{1 2}[z](mulgKV y) groupMr // mem_rcoset.\nmove: {z}(z * _)%g => z Gz; rewrite 2!inE Gz cfConjgMnorm ?(subsetP nHG) //=.\nby rewrite eq_sym (can_eq (cfConjgK y)).\nQed.\n\nLemma cent_sub_inertia phi : 'C(H) \\subset 'I[phi].\nProof.\napply/subsetP=> y cHy; have nHy := subsetP (cent_sub H) y cHy.\nrewrite inE nHy; apply/eqP/cfun_inP=> x Hx; rewrite cfConjgE //.\nby rewrite /conjg invgK mulgA (centP cHy) ?mulgK.\nQed.\n\nLemma cent_sub_Inertia phi : 'C_G(H) \\subset 'I_G[phi].\nProof. exact: setIS (cent_sub_inertia phi). Qed.\n\nLemma center_sub_Inertia phi : H \\subset G -> 'Z(G) \\subset 'I_G[phi].\nProof.\nby move/centS=> sHG; rewrite setIS // (subset_trans sHG) // cent_sub_inertia.\nQed.\n\nLemma conjg_inertia phi y : y \\in 'N(H) -> 'I[phi] :^ y = 'I[phi ^ y].\nProof.\nmove=> nHy; apply/setP=> z; rewrite !['I[_]]setIdE conjIg conjGid // !in_setI.\napply/andb_id2l=> nHz; rewrite mem_conjg !inE.\nby rewrite !cfConjgMnorm ?in_group ?(can2_eq (cfConjgKV y) (cfConjgK y)) ?invgK.\nQed.\n\nLemma inertia0 : 'I[0 : 'CF(H)] = 'N(H).\nProof. by apply/setP=> x; rewrite !inE linear0 eqxx andbT. Qed.\n\nLemma inertia_add phi psi : 'I[phi] :&: 'I[psi] \\subset 'I[phi + psi].\nProof.\nrewrite !['I[_]]setIdE -setIIr setIS //.\nby apply/subsetP=> x /[!(inE, linearD)]/= /andP[/eqP-> /eqP->].\nQed.\n\nLemma inertia_sum I r (P : pred I) (Phi : I -> 'CF(H)) :\n  'N(H) :&: \\bigcap_(i <- r | P i) 'I[Phi i]\n     \\subset 'I[\\sum_(i <- r | P i) Phi i].\nProof.\nelim/big_rec2: _ => [|i K psi Pi sK_Ipsi]; first by rewrite setIT inertia0.\nby rewrite setICA; apply: subset_trans (setIS _ sK_Ipsi) (inertia_add _ _).\nQed.\n\nLemma inertia_scale a phi : 'I[phi] \\subset 'I[a *: phi].\nProof.\napply/subsetP=> x /setIdP[nHx /eqP Iphi_x].\nby rewrite inE nHx linearZ /= Iphi_x.\nQed.\n\nLemma inertia_scale_nz a phi : a != 0 -> 'I[a *: phi] = 'I[phi].\nProof.\nmove=> nz_a; apply/eqP.\nby rewrite eqEsubset -{2}(scalerK nz_a phi) !inertia_scale.\nQed.\n\nLemma inertia_opp phi : 'I[- phi] = 'I[phi].\nProof. by rewrite -scaleN1r inertia_scale_nz // oppr_eq0 oner_eq0. Qed.\n\nLemma inertia1 : 'I[1 : 'CF(H)] = 'N(H).\nProof. by apply/setP=> x; rewrite inE rmorph1 eqxx andbT. Qed.\n\nLemma Inertia1 : H <| G -> 'I_G[1 : 'CF(H)] = G.\nProof. by rewrite inertia1 => /normal_norm/setIidPl. Qed.\n\nLemma inertia_mul phi psi : 'I[phi] :&: 'I[psi] \\subset 'I[phi * psi].\nProof.\nrewrite !['I[_]]setIdE -setIIr setIS //.\nby apply/subsetP=> x /[!(inE, rmorphM)]/= /andP[/eqP-> /eqP->].\nQed.\n\nLemma inertia_prod I r (P : pred I) (Phi : I -> 'CF(H)) :\n  'N(H) :&: \\bigcap_(i <- r | P i) 'I[Phi i]\n     \\subset 'I[\\prod_(i <- r | P i) Phi i].\nProof.\nelim/big_rec2: _ => [|i K psi Pi sK_psi]; first by rewrite inertia1 setIT.\nby rewrite setICA; apply: subset_trans (setIS _ sK_psi) (inertia_mul _ _).\nQed.\n\nLemma inertia_injective (chi : 'CF(H)) :\n  {in H &, injective chi} -> 'I[chi] = 'C(H).\nProof.\nmove=> inj_chi; apply/eqP; rewrite eqEsubset cent_sub_inertia andbT.\napply/subsetP=> y Ichi_y; have /setIdP[nHy _] := Ichi_y.\napply/centP=> x Hx; apply/esym/commgP/conjg_fixP.\nby apply/inj_chi; rewrite ?memJ_norm ?(inertia_valJ _ Ichi_y).\nQed.\n\nLemma inertia_irr_prime p i :\n  #|H| = p -> prime p -> i != 0 -> 'I['chi[H]_i] = 'C(H).\nProof. by move=> <- pr_H /(irr_prime_injP pr_H); apply: inertia_injective. Qed.\n\nLemma inertia_irr0 : 'I['chi[H]_0] = 'N(H).\nProof. by rewrite irr0 inertia1. Qed.\n\n(* Isaacs' 6.1.c *)\nLemma cfConjg_iso y : isometry (cfConjg y : 'CF(H) -> 'CF(H)).\nProof.\nmove=> phi psi; congr (_ * _).\nhave [nHy | not_nHy] := boolP (y \\in 'N(H)); last by rewrite !cfConjgEout.\nrewrite (reindex_astabs 'J y) ?astabsJ //=.\nby apply: eq_bigr=> x _; rewrite !cfConjgEJ.\nQed.\n \n(* Isaacs' 6.1.d *)\nLemma cfdot_Res_conjg psi phi y :\n  y \\in G -> '['Res[H, G] psi, phi ^ y] = '['Res[H] psi, phi].\nProof.\nmove=> Gy; rewrite -(cfConjg_iso y _ phi); congr '[_, _]; apply/cfunP=> x.\nrewrite !cfunElock !genGid; case nHy: (y \\in 'N(H)) => //.\nby rewrite !(fun_if psi) cfunJ ?memJ_norm ?groupV.\nQed.\n\n(* Isaac's 6.1.e *)\nLemma cfConjg_char (chi : 'CF(H)) y :\n  chi \\is a character -> (chi ^ y)%CF \\is a character.\nProof.\nhave [nHy Nchi | /cfConjgEout-> //] := boolP (y \\in 'N(H)).\nby rewrite cfConjgEin cfIsom_char.\nQed.\n\nLemma cfConjg_lin_char (chi : 'CF(H)) y :\n  chi \\is a linear_char -> (chi ^ y)%CF \\is a linear_char.\nProof. by case/andP=> Nchi chi1; rewrite qualifE cfConjg1 cfConjg_char. Qed.\n\nLemma cfConjg_irr y chi : chi \\in irr H -> (chi ^ y)%CF \\in irr H.\nProof. by rewrite !irrEchar cfConjg_iso => /andP[/cfConjg_char->]. Qed.\n \nDefinition conjg_Iirr i y := cfIirr ('chi[H]_i ^ y)%CF.\n\nLemma conjg_IirrE i y : 'chi_(conjg_Iirr i y) = ('chi_i ^ y)%CF.\nProof. by rewrite cfIirrE ?cfConjg_irr ?mem_irr. Qed.\n\nLemma conjg_IirrK y : cancel (conjg_Iirr^~ y) (conjg_Iirr^~ y^-1%g).\nProof. by move=> i; apply/irr_inj; rewrite !conjg_IirrE cfConjgK. Qed.\n\nLemma conjg_IirrKV y : cancel (conjg_Iirr^~ y^-1%g) (conjg_Iirr^~ y).\nProof. by rewrite -{2}[y]invgK; apply: conjg_IirrK. Qed.\n\nLemma conjg_Iirr_inj y : injective (conjg_Iirr^~ y).\nProof. exact: can_inj (conjg_IirrK y). Qed.\n\nLemma conjg_Iirr_eq0 i y : (conjg_Iirr i y == 0) = (i == 0).\nProof. by rewrite -!irr_eq1 conjg_IirrE cfConjg_eq1. Qed.\n\nLemma conjg_Iirr0 x : conjg_Iirr 0 x = 0.\nProof. by apply/eqP; rewrite conjg_Iirr_eq0. Qed.\n\nLemma cfdot_irr_conjg i y :\n  H <| G -> y \\in G -> '['chi_i, 'chi_i ^ y]_H = (y \\in 'I_G['chi_i])%:R.\nProof.\nmove=> nsHG Gy; rewrite -conjg_IirrE cfdot_irr -(inj_eq irr_inj) conjg_IirrE.\nby rewrite -{1}['chi_i]cfConjgJ1 cfConjg_eqE ?mulg1.\nQed.\n\nDefinition cfclass (A : {set gT}) (phi : 'CF(A)) (B : {set gT}) :=\n  [seq (phi ^ repr Tx)%CF | Tx in rcosets 'I_B[phi] B].\n\nLocal Notation \"phi ^: G\" := (cfclass phi G) : cfun_scope.\n\nLemma size_cfclass i : size ('chi[H]_i ^: G)%CF = #|G : 'I_G['chi_i]|.\nProof. by rewrite size_map -cardE. Qed.\n\nLemma cfclassP (A : {group gT}) phi psi :\n  reflect (exists2 y, y \\in A & psi = phi ^ y)%CF (psi \\in phi ^: A)%CF.\nProof.\napply: (iffP imageP) => [[_ /rcosetsP[y Ay ->] ->] | [y Ay ->]].\n  by case: repr_rcosetP => z /setIdP[Az _]; exists (z * y)%g; rewrite ?groupM.\nwithout loss nHy: y Ay / y \\in 'N(H).\n  have [nHy | /cfConjgEout->] := boolP (y \\in 'N(H)); first exact.\n  by move/(_ 1%g); rewrite !group1 !cfConjgJ1; apply.\nexists ('I_A[phi] :* y); first by rewrite -rcosetE imset_f.\ncase: repr_rcosetP => z /setIP[_ /setIdP[nHz /eqP Tz]].\nby rewrite cfConjgMnorm ?Tz.\nQed.\n\nLemma cfclassInorm phi : (phi ^: 'N_G(H) =i phi ^: G)%CF.\nProof.\nmove=> xi; apply/cfclassP/cfclassP=> [[x /setIP[Gx _] ->] | [x Gx ->]].\n  by exists x.\nhave [Nx | /cfConjgEout-> //] := boolP (x \\in 'N(H)).\n  by exists x; first apply/setIP.\nby exists 1%g; rewrite ?group1 ?cfConjgJ1.\nQed.\n\nLemma cfclass_refl phi : phi \\in (phi ^: G)%CF.\nProof. by apply/cfclassP; exists 1%g => //; rewrite cfConjgJ1. Qed.\n\nLemma cfclass_transr phi psi :\n  (psi \\in phi ^: G)%CF -> (phi ^: G =i psi ^: G)%CF.\nProof.\nrewrite -cfclassInorm; case/cfclassP=> x Gx -> xi; rewrite -!cfclassInorm.\nhave nHN: {subset 'N_G(H) <= 'N(H)} by apply/subsetP; apply: subsetIr.\napply/cfclassP/cfclassP=> [[y Gy ->] | [y Gy ->]].\n  by exists (x^-1 * y)%g; rewrite -?cfConjgMnorm ?groupM ?groupV ?nHN // mulKVg.\nby exists (x * y)%g; rewrite -?cfConjgMnorm ?groupM ?nHN.\nQed.\n\nLemma cfclass_sym phi psi : (psi \\in phi ^: G)%CF = (phi \\in psi ^: G)%CF.\nProof. by apply/idP/idP=> /cfclass_transr <-; apply: cfclass_refl. Qed.\n\nLemma cfclass_uniq phi : H <| G -> uniq (phi ^: G)%CF.\nProof.\nmove=> nsHG; rewrite map_inj_in_uniq ?enum_uniq // => Ty Tz; rewrite !mem_enum.\nmove=> {Ty}/rcosetsP[y Gy ->] {Tz}/rcosetsP[z Gz ->] /eqP.\ncase: repr_rcosetP => u Iphi_u; case: repr_rcosetP => v Iphi_v.\nhave [[Gu _] [Gv _]] := (setIdP Iphi_u, setIdP Iphi_v).\nrewrite cfConjg_eqE ?groupM // => /rcoset_eqP.\nby rewrite !rcosetM (rcoset_id Iphi_v) (rcoset_id Iphi_u).\nQed.\n\nLemma cfclass_invariant phi : G \\subset 'I[phi] -> (phi ^: G)%CF = phi.\nProof.\nmove/setIidPl=> IGphi; rewrite /cfclass IGphi // rcosets_id.\nby rewrite /(image _ _) enum_set1 /= repr_group cfConjgJ1.\nQed.\n\nLemma cfclass1 : H <| G -> (1 ^: G)%CF = [:: 1 : 'CF(H)].\nProof. by move/normal_norm=> nHG; rewrite cfclass_invariant ?inertia1.  Qed.\n\nDefinition cfclass_Iirr (A : {set gT}) i := conjg_Iirr i @: A.\n\nLemma cfclass_IirrE i j :\n  (j \\in cfclass_Iirr G i) = ('chi_j \\in 'chi_i ^: G)%CF.\nProof.\napply/imsetP/cfclassP=> [[y Gy ->] | [y]]; exists y; rewrite ?conjg_IirrE //.\nby apply: irr_inj; rewrite conjg_IirrE.\nQed.\n\nLemma eq_cfclass_IirrE i j :\n  (cfclass_Iirr G j == cfclass_Iirr G i) = (j \\in cfclass_Iirr G i).\nProof.\napply/eqP/idP=> [<- | iGj]; first by rewrite cfclass_IirrE cfclass_refl.\nby apply/setP=> k; rewrite !cfclass_IirrE in iGj *; apply/esym/cfclass_transr.\nQed.\n\nLemma im_cfclass_Iirr i :\n  H <| G -> perm_eq [seq 'chi_j | j in cfclass_Iirr G i] ('chi_i ^: G)%CF.\nProof.\nmove=> nsHG; have UchiG := cfclass_uniq 'chi_i nsHG.\napply: uniq_perm; rewrite ?(map_inj_uniq irr_inj) ?enum_uniq // => phi.\napply/imageP/idP=> [[j iGj ->] | /cfclassP[y]]; first by rewrite -cfclass_IirrE.\nby exists (conjg_Iirr i y); rewrite ?imset_f ?conjg_IirrE.\nQed.\n\nLemma card_cfclass_Iirr i : H <| G -> #|cfclass_Iirr G i| = #|G : 'I_G['chi_i]|.\nProof.\nmove=> nsHG; rewrite -size_cfclass -(perm_size (im_cfclass_Iirr i nsHG)).\nby rewrite size_map -cardE.\nQed.\n\nLemma reindex_cfclass R idx (op : Monoid.com_law idx) (F : 'CF(H) -> R) i :\n     H <| G ->\n  \\big[op/idx]_(chi <- ('chi_i ^: G)%CF) F chi\n     = \\big[op/idx]_(j | 'chi_j \\in ('chi_i ^: G)%CF) F 'chi_j.\nProof.\nmove/im_cfclass_Iirr/(perm_big _) <-; rewrite big_image /=.\nby apply: eq_bigl => j; rewrite cfclass_IirrE.\nQed.\n\nLemma cfResInd j:\n    H <| G ->\n  'Res[H] ('Ind[G] 'chi_j) = #|H|%:R^-1 *: (\\sum_(y in G) 'chi_j ^ y)%CF.\nProof.\ncase/andP=> [sHG /subsetP nHG].\nrewrite (reindex_inj invg_inj); apply/cfun_inP=> x Hx.\nrewrite cfResE // cfIndE // ?cfunE ?sum_cfunE; congr (_ * _).\nby apply: eq_big => [y | y Gy]; rewrite ?cfConjgE ?groupV ?invgK ?nHG.\nQed.\n\n(* This is Isaacs, Theorem (6.2) *)\nLemma Clifford_Res_sum_cfclass i j :\n     H <| G -> j \\in irr_constt ('Res[H, G] 'chi_i) ->\n  'Res[H] 'chi_i =\n     '['Res[H] 'chi_i, 'chi_j] *: (\\sum_(chi <- ('chi_j ^: G)%CF) chi).\nProof.\nmove=> nsHG chiHj; have [sHG /subsetP nHG] := andP nsHG.\nrewrite reindex_cfclass //= big_mkcond.\nrewrite {1}['Res _]cfun_sum_cfdot linear_sum /=; apply: eq_bigr => k _.\nhave [[y Gy ->] | ] := altP (cfclassP _ _ _); first by rewrite cfdot_Res_conjg.\napply: contraNeq; rewrite scaler0 scaler_eq0 orbC => /norP[_ chiHk].\nhave{chiHk chiHj}: '['Res[H] ('Ind[G] 'chi_j), 'chi_k] != 0.\n  rewrite !inE !cfdot_Res_l in chiHj chiHk *.\n  apply: contraNneq chiHk; rewrite cfdot_sum_irr => /psumr_eq0P/(_ i isT)/eqP.\n  rewrite -cfdotC cfdotC mulf_eq0 conjC_eq0 (negbTE chiHj) /= => -> // i1.\n  by rewrite -cfdotC Cnat_ge0 // rpredM ?Cnat_cfdot_char ?cfInd_char ?irr_char.\nrewrite cfResInd // cfdotZl mulf_eq0 cfdot_suml => /norP[_].\napply: contraR => chiGk'j; rewrite big1 // => x Gx; apply: contraNeq chiGk'j.\nrewrite -conjg_IirrE cfdot_irr pnatr_eq0; case: (_ =P k) => // <- _.\nby rewrite conjg_IirrE; apply/cfclassP; exists x.\nQed.\n\nLemma cfRes_Ind_invariant psi :\n  H <| G -> G \\subset 'I[psi] -> 'Res ('Ind[G, H] psi) = #|G : H|%:R *: psi.\nProof.\ncase/andP=> sHG _ /subsetP IGpsi; apply/cfun_inP=> x Hx.\nrewrite cfResE ?cfIndE ?natf_indexg // cfunE -mulrA mulrCA; congr (_ * _).\nby rewrite mulr_natl -sumr_const; apply: eq_bigr => y /IGpsi/inertia_valJ->.\nQed.\n\n(* This is Isaacs, Corollary (6.7). *)\nCorollary constt0_Res_cfker i : \n  H <| G -> 0 \\in irr_constt ('Res[H] 'chi[G]_i) -> H \\subset cfker 'chi[G]_i.\nProof.\nmove=> nsHG /(Clifford_Res_sum_cfclass nsHG); have [sHG nHG] := andP nsHG.\nrewrite irr0 cfdot_Res_l cfclass1 // big_seq1 cfInd_cfun1 //.\nrewrite cfdotZr conjC_nat => def_chiH.\napply/subsetP=> x Hx; rewrite cfkerEirr inE -!(cfResE _ sHG) //.\nby rewrite def_chiH !cfunE cfun11 cfun1E Hx.\nQed.\n\n(* This is Isaacs, Lemma (6.8). *)\nLemma dvdn_constt_Res1_irr1 i j : \n    H <| G -> j \\in irr_constt ('Res[H, G] 'chi_i) ->\n  exists n, 'chi_i 1%g = n%:R * 'chi_j 1%g.\nProof.\nmove=> nsHG chiHj; have [sHG nHG] := andP nsHG; rewrite -(cfResE _ sHG) //.\nrewrite {1}(Clifford_Res_sum_cfclass nsHG chiHj) cfunE sum_cfunE.\nhave /CnatP[n ->]: '['Res[H] 'chi_i, 'chi_j] \\in Cnat.\n  by rewrite Cnat_cfdot_char ?cfRes_char ?irr_char.\nexists (n * size ('chi_j ^: G)%CF)%N; rewrite natrM -mulrA; congr (_ * _).\nrewrite mulr_natl -[size _]card_ord big_tnth -sumr_const; apply: eq_bigr => k _.\nby have /cfclassP[y Gy ->]:=  mem_tnth k (in_tuple _); rewrite cfConjg1.\nQed.\n\nLemma cfclass_Ind phi psi :\n  H <| G -> psi \\in (phi ^: G)%CF -> 'Ind[G] phi = 'Ind[G] psi.\nProof.\nmove=> nsHG /cfclassP[y Gy ->]; have [sHG /subsetP nHG] := andP nsHG.\napply/cfun_inP=> x Hx; rewrite !cfIndE //; congr (_ * _).\nrewrite (reindex_acts 'R _ (groupVr Gy)) ?astabsR //=.\nby apply: eq_bigr => z Gz; rewrite conjgM cfConjgE ?nHG.\nQed.\n\nEnd Inertia.\n\nArguments inertia {gT B%g} phi%CF.\nArguments cfclass {gT A%g} phi%CF B%g.\nArguments conjg_Iirr_inj {gT H} y [i1 i2] : rename.\n\nNotation \"''I[' phi ] \" := (inertia phi) : group_scope.\nNotation \"''I[' phi ] \" := (inertia_group phi) : Group_scope.\nNotation \"''I_' G [ phi ] \" := (G%g :&: 'I[phi]) : group_scope.\nNotation \"''I_' G [ phi ] \" := (G :&: 'I[phi])%G : Group_scope.\nNotation \"phi ^: G\" := (cfclass phi G) : cfun_scope.\n\nSection ConjRestrict.\n\nVariables (gT : finGroupType) (G H K : {group gT}).\n\nLemma cfConjgRes_norm phi y :\n  y \\in 'N(K) -> y \\in 'N(H) -> ('Res[K, H] phi ^ y)%CF = 'Res (phi ^ y)%CF.\nProof.\nmove=> nKy nHy; have [sKH | not_sKH] := boolP (K \\subset H); last first.\n  by rewrite !cfResEout // linearZ rmorph1 cfConjg1.\nby apply/cfun_inP=> x Kx; rewrite !(cfConjgE, cfResE) ?memJ_norm ?groupV.\nQed.\n\nLemma cfConjgRes phi y :\n  H <| G -> K <| G -> y \\in G -> ('Res[K, H] phi ^ y)%CF = 'Res (phi ^ y)%CF.\nProof.\nmove=> /andP[_ nHG] /andP[_ nKG] Gy.\nby rewrite cfConjgRes_norm ?(subsetP nHG) ?(subsetP nKG).\nQed.\n\nLemma sub_inertia_Res phi :\n  G \\subset 'N(K) -> 'I_G[phi] \\subset 'I_G['Res[K, H] phi].\nProof.\nmove=> nKG; apply/subsetP=> y /setIP[Gy /setIdP[nHy /eqP Iphi_y]].\nby rewrite 2!inE Gy cfConjgRes_norm ?(subsetP nKG) ?Iphi_y /=.\nQed.\n\nLemma cfConjgInd_norm phi y :\n  y \\in 'N(K) -> y \\in 'N(H) -> ('Ind[H, K] phi ^ y)%CF = 'Ind (phi ^ y)%CF.\nProof.\nmove=> nKy nHy; have [sKH | not_sKH] := boolP (K \\subset H).\n  by rewrite !cfConjgEin (cfIndIsom (norm_conj_isom nHy)).\nrewrite !cfIndEout // linearZ -(cfConjg_iso y) rmorph1 /=; congr (_ *: _).\nby rewrite cfConjg_cfuni ?norm1 ?inE.\nQed.\n\nLemma cfConjgInd phi y :\n  H <| G -> K <| G -> y \\in G -> ('Ind[H, K] phi ^ y)%CF = 'Ind (phi ^ y)%CF.\nProof.\nmove=> /andP[_ nHG] /andP[_ nKG] Gy.\nby rewrite cfConjgInd_norm ?(subsetP nHG) ?(subsetP nKG).\nQed.\n\nLemma sub_inertia_Ind phi :\n  G \\subset 'N(H) -> 'I_G[phi] \\subset 'I_G['Ind[H, K] phi].\nProof.\nmove=> nHG; apply/subsetP=> y /setIP[Gy /setIdP[nKy /eqP Iphi_y]].\nby rewrite 2!inE Gy cfConjgInd_norm ?(subsetP nHG) ?Iphi_y /=.\nQed.\n\nEnd ConjRestrict.\n\nSection MoreInertia.\n\nVariables (gT : finGroupType) (G H : {group gT}) (i : Iirr H).\nLet T := 'I_G['chi_i].\n\nLemma inertia_id : 'I_T['chi_i] = T. Proof. by rewrite -setIA setIid. Qed.\n\nLemma cfclass_inertia : ('chi[H]_i ^: T)%CF = [:: 'chi_i].\nProof.\nrewrite /cfclass inertia_id rcosets_id /(image _ _) enum_set1 /=.\nby rewrite repr_group cfConjgJ1.\nQed.\n\nEnd MoreInertia.\n\nSection ConjMorph.\n\nVariables (aT rT : finGroupType) (D G H : {group aT}) (f : {morphism D >-> rT}).\n\nLemma cfConjgMorph (phi : 'CF(f @* H)) y :\n  y \\in D -> y \\in 'N(H) -> (cfMorph phi ^ y)%CF = cfMorph (phi ^ f y).\nProof.\nmove=> Dy nHy; have [sHD | not_sHD] := boolP (H \\subset D); last first.\n  by rewrite !cfMorphEout // linearZ rmorph1 cfConjg1.\napply/cfun_inP=> x Gx; rewrite !(cfConjgE, cfMorphE) ?memJ_norm ?groupV //.\n  by rewrite morphJ ?morphV ?groupV // (subsetP sHD).\nby rewrite (subsetP (morphim_norm _ _)) ?mem_morphim.\nQed.\n\nLemma inertia_morph_pre (phi : 'CF(f @* H)) :\n  H <| G -> G \\subset D -> 'I_G[cfMorph phi] = G :&: f @*^-1 'I_(f @* G)[phi].\nProof.\ncase/andP=> sHG nHG sGD; have sHD := subset_trans sHG sGD.\napply/setP=> y; rewrite !in_setI; apply: andb_id2l => Gy.\nhave [Dy nHy] := (subsetP sGD y Gy, subsetP nHG y Gy).\nrewrite Dy inE nHy 4!inE mem_morphim // -morphimJ ?(normP nHy) // subxx /=.\nrewrite cfConjgMorph //; apply/eqP/eqP=> [Iphi_y | -> //].\nby apply/cfun_inP=> _ /morphimP[x Dx Hx ->]; rewrite -!cfMorphE ?Iphi_y.\nQed.\n\nLemma inertia_morph_im (phi : 'CF(f @* H)) :\n  H <| G -> G \\subset D -> f @* 'I_G[cfMorph phi] = 'I_(f @* G)[phi].\nProof.\nmove=> nsHG sGD; rewrite inertia_morph_pre // morphim_setIpre.\nby rewrite (setIidPr _) ?Inertia_sub.\nQed.\n\nVariables (R S : {group rT}).\nVariables (g : {morphism G >-> rT}) (h : {morphism H >-> rT}).\nHypotheses (isoG : isom G R g) (isoH : isom H S h).\nHypotheses (eq_hg : {in H, h =1 g}) (sHG : H \\subset G).\n\n(* This does not depend on the (isoG : isom G R g) assumption. *)\nLemma cfConjgIsom phi y :\n  y \\in G -> y \\in 'N(H) -> (cfIsom isoH phi ^ g y)%CF = cfIsom isoH (phi ^ y).\nProof.\nmove=> Gy nHy; have [_ defS] := isomP isoH.\nrewrite morphimEdom (eq_in_imset eq_hg) -morphimEsub // in defS.\napply/cfun_inP=> gx; rewrite -{1}defS => /morphimP[x Gx Hx ->] {gx}.\nrewrite cfConjgE; last by rewrite -defS inE -morphimJ ?(normP nHy).\nby rewrite -morphV -?morphJ -?eq_hg ?cfIsomE ?cfConjgE ?memJ_norm ?groupV.\nQed.\n\nLemma inertia_isom phi : 'I_R[cfIsom isoH phi] = g @* 'I_G[phi].\nProof.\nhave [[_ defS] [injg <-]] := (isomP isoH, isomP isoG).\nrewrite morphimEdom (eq_in_imset eq_hg) -morphimEsub // in defS.\nrewrite /inertia !setIdE morphimIdom setIA -{1}defS -injm_norm ?injmI //.\napply/setP=> gy /[!inE]; apply: andb_id2l => /morphimP[y Gy nHy ->] {gy}.\nrewrite cfConjgIsom // -sub1set -morphim_set1 // injmSK ?sub1set //= inE.\napply/eqP/eqP=> [Iphi_y | -> //].\nby apply/cfun_inP=> x Hx; rewrite -!(cfIsomE isoH) ?Iphi_y.\nQed.\n\nEnd ConjMorph.\n\nSection ConjQuotient.\n\nVariables gT : finGroupType.\nImplicit Types G H K : {group gT}.\n\nLemma cfConjgMod_norm H K (phi : 'CF(H / K)) y :\n  y \\in 'N(K) -> y \\in 'N(H) -> ((phi %% K) ^ y)%CF = (phi ^ coset K y %% K)%CF.\nProof. exact: cfConjgMorph. Qed.\n\nLemma cfConjgMod G H K (phi : 'CF(H / K)) y :\n    H <| G -> K <| G -> y \\in G ->\n  ((phi %% K) ^ y)%CF = (phi ^ coset K y %% K)%CF.\nProof.\nmove=> /andP[_ nHG] /andP[_ nKG] Gy.\nby rewrite cfConjgMod_norm ?(subsetP nHG) ?(subsetP nKG).\nQed.\n\nLemma cfConjgQuo_norm H K (phi : 'CF(H)) y :\n  y \\in 'N(K) -> y \\in 'N(H) -> ((phi / K) ^ coset K y)%CF = (phi ^ y / K)%CF.\nProof.\nmove=> nKy nHy; have keryK: (K \\subset cfker (phi ^ y)) = (K \\subset cfker phi).\n  by rewrite cfker_conjg // -{1}(normP nKy) conjSg.\nhave [kerK | not_kerK] := boolP (K \\subset cfker phi); last first.\n  by rewrite !cfQuoEout ?linearZ ?rmorph1 ?cfConjg1 ?keryK.\napply/cfun_inP=> _ /morphimP[x nKx Hx ->].\nhave nHyb: coset K y \\in 'N(H / K) by rewrite inE -morphimJ ?(normP nHy).\nrewrite !(cfConjgE, cfQuoEnorm) ?keryK // ?in_setI ?Hx //.\nrewrite -morphV -?morphJ ?groupV // cfQuoEnorm //.\nby rewrite inE memJ_norm ?Hx ?groupJ ?groupV.\nQed.\n\nLemma cfConjgQuo G H K (phi : 'CF(H)) y :\n    H <| G -> K <| G -> y \\in G ->\n  ((phi / K) ^ coset K y)%CF = (phi ^ y / K)%CF.\nProof.\nmove=> /andP[_ nHG] /andP[_ nKG] Gy.\nby rewrite cfConjgQuo_norm ?(subsetP nHG) ?(subsetP nKG).\nQed.\n\nLemma inertia_mod_pre G H K (phi : 'CF(H / K)) :\n  H <| G -> K <| G -> 'I_G[phi %% K] = G :&: coset K @*^-1 'I_(G / K)[phi].\nProof. by move=> nsHG /andP[_]; apply: inertia_morph_pre. Qed.\n\nLemma inertia_mod_quo G H K (phi : 'CF(H / K)) :\n  H <| G -> K <| G -> ('I_G[phi %% K] / K)%g = 'I_(G / K)[phi].\nProof. by move=> nsHG /andP[_]; apply: inertia_morph_im. Qed.\n\nLemma inertia_quo G H K (phi : 'CF(H)) :\n    H <| G -> K <| G -> K \\subset cfker phi ->\n  'I_(G / K)[phi / K] = ('I_G[phi] / K)%g.\nProof.\nmove=> nsHG nsKG kerK; rewrite -inertia_mod_quo ?cfQuoK //.\nby rewrite (normalS _ (normal_sub nsHG)) // (subset_trans _ (cfker_sub phi)).\nQed.\n\nEnd ConjQuotient.\n\nSection InertiaSdprod.\n\nVariables (gT : finGroupType) (K H G : {group gT}).\n\nHypothesis defG : K ><| H = G.\n\nLemma cfConjgSdprod phi y :\n    y \\in 'N(K) -> y \\in 'N(H) ->\n  (cfSdprod defG phi ^ y = cfSdprod defG (phi ^ y))%CF.\nProof.\nmove=> nKy nHy.\nhave nGy: y \\in 'N(G) by rewrite -sub1set -(sdprodW defG) normsM ?sub1set.\nrewrite -{2}[phi](cfSdprodK defG) cfConjgRes_norm // cfRes_sdprodK //.\nby rewrite cfker_conjg // -{1}(normP nKy) conjSg cfker_sdprod.\nQed.\n\nLemma inertia_sdprod (L : {group gT}) phi :\n  L \\subset 'N(K) -> L \\subset 'N(H) -> 'I_L[cfSdprod defG phi] = 'I_L[phi].\nProof.\nmove=> nKL nHL; have nGL: L \\subset 'N(G) by rewrite -(sdprodW defG) normsM.\napply/setP=> z; rewrite !in_setI ![z \\in 'I[_]]inE; apply: andb_id2l => Lz.\nrewrite cfConjgSdprod ?(subsetP nKL) ?(subsetP nHL) ?(subsetP nGL) //=.\nby rewrite (can_eq (cfSdprodK defG)).\nQed.\n\nEnd InertiaSdprod.\n\nSection InertiaDprod.\n\nVariables (gT : finGroupType) (G K H : {group gT}).\nImplicit Type L : {group gT}.\nHypothesis KxH : K \\x H = G.\n\nLemma cfConjgDprodl phi y :\n    y \\in 'N(K) -> y \\in 'N(H) ->\n  (cfDprodl KxH phi ^ y = cfDprodl KxH (phi ^ y))%CF.\nProof. by move=> nKy nHy; apply: cfConjgSdprod. Qed.\n\nLemma cfConjgDprodr psi y :\n    y \\in 'N(K) -> y \\in 'N(H) ->\n  (cfDprodr KxH psi ^ y = cfDprodr KxH (psi ^ y))%CF.\nProof. by move=> nKy nHy; apply: cfConjgSdprod. Qed.\n\nLemma cfConjgDprod phi psi y :\n    y \\in 'N(K) -> y \\in 'N(H) ->\n  (cfDprod KxH phi psi ^ y = cfDprod KxH (phi ^ y) (psi ^ y))%CF.\nProof. by move=> nKy nHy; rewrite rmorphM /= cfConjgDprodl ?cfConjgDprodr. Qed.\n\nLemma inertia_dprodl L phi :\n  L \\subset 'N(K) -> L \\subset 'N(H) -> 'I_L[cfDprodl KxH phi] = 'I_L[phi].\nProof. by move=> nKL nHL; apply: inertia_sdprod. Qed.\n\nLemma inertia_dprodr L psi :\n  L \\subset 'N(K) -> L \\subset 'N(H) -> 'I_L[cfDprodr KxH psi] = 'I_L[psi].\nProof. by move=> nKL nHL; apply: inertia_sdprod. Qed.\n\nLemma inertia_dprod L (phi : 'CF(K)) (psi : 'CF(H)) :\n    L \\subset 'N(K) -> L \\subset 'N(H) -> phi 1%g != 0 -> psi 1%g != 0 -> \n  'I_L[cfDprod KxH phi psi] = 'I_L[phi] :&: 'I_L[psi].\nProof.\nmove=> nKL nHL nz_phi nz_psi; apply/eqP; rewrite eqEsubset subsetI.\nrewrite -{1}(inertia_scale_nz psi nz_phi) -{1}(inertia_scale_nz phi nz_psi).\nrewrite -(cfDprod_Resl KxH) -(cfDprod_Resr KxH) !sub_inertia_Res //=.\nby rewrite -inertia_dprodl -?inertia_dprodr // -setIIr setIS ?inertia_mul.\nQed.\n\nLemma inertia_dprod_irr L i j :\n    L \\subset 'N(K) -> L \\subset 'N(H) ->\n  'I_L[cfDprod KxH 'chi_i 'chi_j] = 'I_L['chi_i] :&: 'I_L['chi_j].\nProof. by move=> nKL nHL; rewrite inertia_dprod ?irr1_neq0. Qed.\n\nEnd InertiaDprod.\n\nSection InertiaBigdprod.\n\nVariables (gT : finGroupType) (I : finType) (P : pred I).\nVariables (A : I -> {group gT}) (G : {group gT}).\nImplicit Type L : {group gT}.\nHypothesis defG : \\big[dprod/1%g]_(i | P i) A i = G.\n\nSection ConjBig.\n\nVariable y : gT.\nHypothesis nAy: forall i, P i -> y \\in 'N(A i).\n\nLemma cfConjgBigdprodi i (phi : 'CF(A i)) :\n   (cfBigdprodi defG phi ^ y = cfBigdprodi defG (phi ^ y))%CF.\nProof.\nrewrite cfConjgDprodl; try by case: ifP => [/nAy// | _]; rewrite norm1 inE.\n  congr (cfDprodl _ _); case: ifP => [Pi | _].\n    by rewrite cfConjgRes_norm ?nAy.\n  by apply/cfun_inP=> _ /set1P->; rewrite !(cfRes1, cfConjg1).\nrewrite -sub1set norms_gen ?norms_bigcup // sub1set.\nby apply/bigcapP=> j /andP[/nAy].\nQed.\n\nLemma cfConjgBigdprod phi :\n  (cfBigdprod defG phi ^ y = cfBigdprod defG (fun i => phi i ^ y))%CF.\nProof.\nby rewrite rmorph_prod /=; apply: eq_bigr => i _; apply: cfConjgBigdprodi.\nQed.\n\nEnd ConjBig.\n\nSection InertiaBig.\n\nVariable L : {group gT}.\nHypothesis nAL : forall i, P i -> L \\subset 'N(A i).\n\nLemma inertia_bigdprodi i (phi : 'CF(A i)) :\n  P i -> 'I_L[cfBigdprodi defG phi] = 'I_L[phi].\nProof.\nmove=> Pi; rewrite inertia_dprodl ?Pi ?cfRes_id ?nAL //.\nby apply/norms_gen/norms_bigcup/bigcapsP=> j /andP[/nAL].\nQed.\n\nLemma inertia_bigdprod phi (Phi := cfBigdprod defG phi) :\n  Phi 1%g != 0 -> 'I_L[Phi] = L :&: \\bigcap_(i | P i) 'I_L[phi i].\nProof.\nmove=> nz_Phi; apply/eqP; rewrite eqEsubset; apply/andP; split.\n  rewrite subsetI Inertia_sub; apply/bigcapsP=> i Pi.\n  have [] := cfBigdprodK nz_Phi Pi; move: (_ / _) => a nz_a <-.\n  by rewrite inertia_scale_nz ?sub_inertia_Res //= ?nAL.\nrewrite subsetI subsetIl; apply: subset_trans (inertia_prod _ _ _).\napply: setISS.\n  by rewrite -(bigdprodWY defG) norms_gen ?norms_bigcup //; apply/bigcapsP.\napply/bigcapsP=> i Pi; rewrite (bigcap_min i) //.\nby rewrite -inertia_bigdprodi ?subsetIr.\nQed.\n\nLemma inertia_bigdprod_irr Iphi (phi := fun i => 'chi_(Iphi i)) :\n  'I_L[cfBigdprod defG phi] = L :&: \\bigcap_(i | P i) 'I_L[phi i].\nProof.\nrewrite inertia_bigdprod // -[cfBigdprod _ _]cfIirrE ?irr1_neq0 //.\nby apply: cfBigdprod_irr => i _; apply: mem_irr.\nQed.\n\nEnd InertiaBig.\n\nEnd InertiaBigdprod.\n\nSection ConsttInertiaBijection.\n\nVariables (gT : finGroupType) (H G : {group gT}) (t : Iirr H).\nHypothesis nsHG : H <| G.\n\nLocal Notation theta := 'chi_t.\nLocal Notation T := 'I_G[theta]%G.\nLocal Notation \"` 'T'\" := 'I_(gval G)[theta]\n  (at level 0, format \"` 'T'\") : group_scope.\n\nLet calA := irr_constt ('Ind[T] theta).\nLet calB := irr_constt ('Ind[G] theta).\nLocal Notation AtoB := (Ind_Iirr G).\n\n(* This is Isaacs, Theorem (6.11). *)\nTheorem constt_Inertia_bijection :\n [/\\ (*a*) {in calA, forall s, 'Ind[G] 'chi_s \\in irr G},\n     (*b*) {in calA &, injective (Ind_Iirr G)},\n           Ind_Iirr G @: calA =i calB,\n     (*c*) {in calA, forall s (psi := 'chi_s) (chi := 'Ind[G] psi),\n             [predI irr_constt ('Res chi) & calA] =i pred1 s}\n   & (*d*) {in calA, forall s (psi := 'chi_s) (chi := 'Ind[G] psi),\n             '['Res psi, theta] = '['Res chi, theta]}].\nProof.\nhave [sHG sTG]: H \\subset G /\\ T \\subset G by rewrite subsetIl normal_sub.\nhave nsHT : H <| T := normal_Inertia theta sHG; have sHT := normal_sub nsHT.\nhave AtoB_P s (psi := 'chi_s) (chi := 'Ind[G] psi): s \\in calA ->\n  [/\\ chi \\in irr G, AtoB s \\in calB & '['Res psi, theta] = '['Res chi, theta]].\n- rewrite !constt_Ind_Res => sHt; have [r sGr] := constt_cfInd_irr s sTG.\n  have rTs: s \\in irr_constt ('Res[T] 'chi_r) by rewrite -constt_Ind_Res.\n  have NrT: 'Res[T] 'chi_r \\is a character by rewrite cfRes_char ?irr_char.\n  have rHt: t \\in irr_constt ('Res[H] 'chi_r).\n    by have:= constt_Res_trans NrT rTs sHt; rewrite cfResRes.\n  pose e := '['Res[H] 'chi_r, theta]; set f := '['Res[H] psi, theta].\n  have DrH: 'Res[H] 'chi_r = e *: \\sum_(xi <- (theta ^: G)%CF) xi.\n    exact: Clifford_Res_sum_cfclass.\n  have DpsiH: 'Res[H] psi = f *: theta.\n    rewrite (Clifford_Res_sum_cfclass nsHT sHt).\n    by rewrite cfclass_invariant ?subsetIr ?big_seq1.\n  have ub_chi_r: 'chi_r 1%g <= chi 1%g ?= iff ('chi_r == chi).\n    have Nchi: chi \\is a character by rewrite cfInd_char ?irr_char.\n    have [chi1 Nchi1->] := constt_charP _ Nchi sGr.\n    rewrite addrC cfunE -leif_subLR subrr eq_sym -subr_eq0 addrK.\n    by split; rewrite ?char1_ge0 // eq_sym char1_eq0.\n  have lb_chi_r: chi 1%g <= 'chi_r 1%g ?= iff (f == e).\n    rewrite cfInd1 // -(cfRes1 H) DpsiH -(cfRes1 H 'chi_r) DrH !cfunE sum_cfunE.\n    rewrite (eq_big_seq (fun _ => theta 1%g)) => [|i]; last first.\n      by case/cfclassP=> y _ ->; rewrite cfConjg1.\n    rewrite reindex_cfclass //= sumr_const -(eq_card (cfclass_IirrE _ _)).\n    rewrite mulr_natl mulrnAr card_cfclass_Iirr //.\n    rewrite (mono_leif (ler_pmuln2r (indexg_gt0 G T))).\n    rewrite (mono_leif (ler_pmul2r (irr1_gt0 t))); apply: leif_eq.\n    by rewrite /e -(cfResRes _ sHT) ?cfdot_Res_ge_constt.\n  have [_ /esym] := leif_trans ub_chi_r lb_chi_r; rewrite eqxx.\n  by case/andP=> /eqP Dchi /eqP->; rewrite cfIirrE -/chi -?Dchi ?mem_irr.\nhave part_c: {in calA, forall s (chi := 'Ind[G] 'chi_s),\n  [predI irr_constt ('Res[T] chi) & calA] =i pred1 s}.\n- move=> s As chi s1; have [irr_chi _ /eqP Dchi_theta] := AtoB_P s As.\n  have chiTs: s \\in irr_constt ('Res[T] chi).\n    by rewrite irr_consttE cfdot_Res_l irrWnorm ?oner_eq0.\n  apply/andP/eqP=> [[/= chiTs1 As1] | -> //].\n  apply: contraTeq Dchi_theta => s's1; rewrite lt_eqF // -/chi.\n  have [|phi Nphi DchiT] := constt_charP _ _ chiTs.\n    by rewrite cfRes_char ?cfInd_char ?irr_char.\n  have [|phi1 Nphi1 Dphi] := constt_charP s1 Nphi _.\n    rewrite irr_consttE -(canLR (addKr _) DchiT) addrC cfdotBl cfdot_irr.\n    by rewrite mulrb ifN_eqC ?subr0.\n  rewrite -(cfResRes chi sHT sTG) DchiT Dphi !rmorphD !cfdotDl /=.\n  rewrite -ltr_subl_addl subrr ltr_paddr ?lt_def //;\n    rewrite Cnat_ge0 ?Cnat_cfdot_char ?cfRes_char ?irr_char //.\n  by rewrite andbT -irr_consttE -constt_Ind_Res.\ndo [split=> //; try by move=> s /AtoB_P[]] => [s1 s2 As1 As2 | r].\n  have [[irr_s1G _ _] [irr_s2G _ _]] := (AtoB_P _ As1, AtoB_P _ As2).\n  move/(congr1 (tnth (irr G))); rewrite !cfIirrE // => eq_s12_G.\n  apply/eqP; rewrite -[_ == _]part_c // inE /= As1 -eq_s12_G.\n  by rewrite -As1 [_ && _]part_c // inE /=.\napply/imsetP/idP=> [[s /AtoB_P[_ BsG _] -> //] | Br].\nhave /exists_inP[s rTs As]: [exists s in irr_constt ('Res 'chi_r), s \\in calA].\n  rewrite -negb_forall_in; apply: contra Br => /eqfun_inP => o_tT_rT.\n  rewrite -(cfIndInd _ sTG sHT) -cfdot_Res_r ['Res _]cfun_sum_constt.\n  by rewrite cfdot_sumr big1 // => i rTi; rewrite cfdotZr o_tT_rT ?mulr0.\nexists s => //; have [/irrP[r1 DsG] _ _] := AtoB_P s As.\nby apply/eqP; rewrite /AtoB -constt_Ind_Res DsG irrK constt_irr in rTs *.\nQed.\n\nEnd ConsttInertiaBijection.\n\nSection ExtendInvariantIrr.\n\nVariable gT : finGroupType.\nImplicit Types G H K L M N : {group gT}.\n\nSection ConsttIndExtendible.\n\nVariables (G N : {group gT}) (t : Iirr N) (c : Iirr G).\nLet theta := 'chi_t.\nLet chi := 'chi_c.\n\nDefinition mul_Iirr b := cfIirr ('chi_b * chi).\nDefinition mul_mod_Iirr (b : Iirr (G / N)) := mul_Iirr (mod_Iirr b).\n\nHypotheses (nsNG : N <| G) (cNt : 'Res[N] chi = theta).\nLet sNG : N \\subset G. Proof. exact: normal_sub. Qed.\nLet nNG : G \\subset 'N(N). Proof. exact: normal_norm. Qed.\n\nLemma extendible_irr_invariant : G \\subset 'I[theta].\nProof.\napply/subsetP=> y Gy; have nNy := subsetP nNG y Gy.\nrewrite inE nNy; apply/eqP/cfun_inP=> x Nx; rewrite cfConjgE // -cNt.\nby rewrite !cfResE ?memJ_norm ?cfunJ ?groupV.\nQed.\nLet IGtheta := extendible_irr_invariant.\n\n(* This is Isaacs, Theorem (6.16) *)\nTheorem constt_Ind_mul_ext f (phi := 'chi_f) (psi := phi * theta) :\n  G \\subset 'I[phi] -> psi \\in irr N ->\n  let calS := irr_constt ('Ind phi) in\n  [/\\ {in calS, forall b, 'chi_b * chi \\in irr G},\n      {in calS &, injective mul_Iirr},\n      irr_constt ('Ind psi) =i [seq mul_Iirr b | b in calS]\n    & 'Ind psi = \\sum_(b in calS) '['Ind phi, 'chi_b] *: 'chi_(mul_Iirr b)].\nProof.\nmove=> IGphi irr_psi calS.\nhave IGpsi: G \\subset 'I[psi].\n  by rewrite (subset_trans _ (inertia_mul _ _)) // subsetI IGphi.\npose e b := '['Ind[G] phi, 'chi_b]; pose d b g := '['chi_b * chi, 'chi_g * chi].\nhave Ne b: e b \\in Cnat by rewrite Cnat_cfdot_char ?cfInd_char ?irr_char.\nhave egt0 b: b \\in calS -> e b > 0 by rewrite Cnat_gt0.\nhave DphiG: 'Ind phi = \\sum_(b in calS) e b *: 'chi_b := cfun_sum_constt _.\nhave DpsiG: 'Ind psi = \\sum_(b in calS) e b *: 'chi_b * chi.\n  by rewrite /psi -cNt cfIndM // DphiG mulr_suml.\npose d_delta := [forall b in calS, forall g in calS, d b g == (b == g)%:R].\nhave charMchi b: 'chi_b * chi \\is a character by rewrite rpredM ?irr_char.\nhave [_]: '['Ind[G] phi] <= '['Ind[G] psi] ?= iff d_delta.\n  pose sum_delta := \\sum_(b in calS) e b * \\sum_(g in calS) e g * (b == g)%:R.\n  pose sum_d := \\sum_(b in calS) e b * \\sum_(g in calS) e g * d b g.\n  have ->: '['Ind[G] phi] = sum_delta.\n    rewrite DphiG cfdot_suml; apply: eq_bigr => b _; rewrite cfdotZl cfdot_sumr.\n    by congr (_ * _); apply: eq_bigr => g; rewrite cfdotZr cfdot_irr conj_Cnat.\n  have ->: '['Ind[G] psi] = sum_d.\n    rewrite DpsiG cfdot_suml; apply: eq_bigr => b _.\n    rewrite -scalerAl cfdotZl cfdot_sumr; congr (_ * _).\n    by apply: eq_bigr => g _; rewrite -scalerAl cfdotZr conj_Cnat.\n  have eMmono := mono_leif (ler_pmul2l (egt0 _ _)).\n  apply: leif_sum => b /eMmono->; apply: leif_sum => g /eMmono->.\n  split; last exact: eq_sym.\n  have /CnatP[n Dd]: d b g \\in Cnat by rewrite Cnat_cfdot_char.\n  have [Db | _] := eqP; rewrite Dd leC_nat // -ltC_nat -Dd Db cfnorm_gt0.\n  by rewrite -char1_eq0 // cfunE mulf_neq0 ?irr1_neq0.\nrewrite -!cfdot_Res_l ?cfRes_Ind_invariant // !cfdotZl cfnorm_irr irrWnorm //.\nrewrite eqxx => /esym/forall_inP/(_ _ _)/eqfun_inP; rewrite /d /= => Dd.\nhave irrMchi: {in calS, forall b, 'chi_b * chi \\in irr G}.\n  by move=> b Sb; rewrite /= irrEchar charMchi Dd ?eqxx.\nhave injMchi: {in calS &, injective mul_Iirr}.\n  move=> b g Sb Sg /(congr1 (fun s => '['chi_s, 'chi_(mul_Iirr g)]))/eqP.\n  by rewrite cfnorm_irr !cfIirrE ?irrMchi ?Dd // pnatr_eq1; case: (b =P g).\nhave{DpsiG} ->: 'Ind psi = \\sum_(b in calS) e b *: 'chi_(mul_Iirr b).\n  by rewrite DpsiG; apply: eq_bigr => b Sb; rewrite -scalerAl cfIirrE ?irrMchi.\nsplit=> // i; rewrite irr_consttE cfdot_suml;\napply/idP/idP=> [|/imageP[b Sb ->]].\n  apply: contraR => N'i; rewrite big1 // => b Sb.\n  rewrite cfdotZl cfdot_irr mulrb ifN_eqC ?mulr0 //.\n  by apply: contraNneq N'i => ->; apply: image_f.\nrewrite gt_eqF // (bigD1 b) //= cfdotZl cfnorm_irr mulr1 ltr_paddr ?egt0 //.\napply: sumr_ge0 => g /andP[Sg _]; rewrite cfdotZl cfdot_irr.\nby rewrite mulr_ge0 ?ler0n ?Cnat_ge0.\nQed.\n\n(* This is Isaacs, Corollary (6.17) (due to Gallagher). *)\nCorollary constt_Ind_ext :\n  [/\\ forall b : Iirr (G / N), 'chi_(mod_Iirr b) * chi \\in irr G,\n      injective mul_mod_Iirr,\n      irr_constt ('Ind theta) =i codom mul_mod_Iirr\n    & 'Ind theta = \\sum_b 'chi_b 1%g *: 'chi_(mul_mod_Iirr b)].\nProof.\nhave IHchi0: G \\subset 'I['chi[N]_0] by rewrite inertia_irr0.\nhave [] := constt_Ind_mul_ext IHchi0; rewrite irr0 ?mul1r ?mem_irr //.\nset psiG := 'Ind 1 => irrMchi injMchi constt_theta {2}->.\nhave dot_psiG b: '[psiG, 'chi_(mod_Iirr b)] = 'chi[G / N]_b 1%g.\n  rewrite mod_IirrE // -cfdot_Res_r cfRes_sub_ker ?cfker_mod //.\n  by rewrite cfdotZr cfnorm1 mulr1 conj_Cnat ?cfMod1 ?Cnat_irr1.\nhave mem_psiG (b : Iirr (G / N)): mod_Iirr b \\in irr_constt psiG.\n  by rewrite irr_consttE dot_psiG irr1_neq0.\nhave constt_psiG b: (b \\in irr_constt psiG) = (N \\subset cfker 'chi_b).\n  apply/idP/idP=> [psiGb | /quo_IirrK <- //].\n  by rewrite constt0_Res_cfker // -constt_Ind_Res irr0.\nsplit=> [b | b g /injMchi/(can_inj (mod_IirrK nsNG))-> // | b0 | ].\n- exact: irrMchi.\n- rewrite constt_theta.\n  apply/imageP/imageP=> [][b psiGb ->]; last by exists (mod_Iirr b).\n  by exists (quo_Iirr N b) => //; rewrite /mul_mod_Iirr quo_IirrK -?constt_psiG.\nrewrite (reindex_onto _ _ (in1W (mod_IirrK nsNG))) /=.\napply/esym/eq_big => b; first by rewrite constt_psiG quo_IirrKeq.\nby rewrite -dot_psiG /mul_mod_Iirr => /eqP->.\nQed.\n\nEnd ConsttIndExtendible.\n\n(* This is Isaacs, Theorem (6.19). *)\nTheorem invariant_chief_irr_cases G K L s (theta := 'chi[K]_s) :\n    chief_factor G L K -> abelian (K / L) -> G \\subset 'I[theta] ->\n  let t := #|K : L| in\n  [\\/ 'Res[L] theta \\in irr L,\n      exists2 e, exists p, 'Res[L] theta = e%:R *: 'chi_p & (e ^ 2)%N = t\n   |  exists2 p, injective p & 'Res[L] theta = \\sum_(i < t) 'chi_(p i)].\nProof.\ncase/andP=> /maxgroupP[/andP[ltLK nLG] maxL] nsKG abKbar IGtheta t.\nhave [sKG nKG] := andP nsKG; have sLG := subset_trans (proper_sub ltLK) sKG.\nhave nsLG: L <| G by apply/andP.\nhave nsLK := normalS (proper_sub ltLK) sKG nsLG; have [sLK nLK] := andP nsLK.\nhave [p0 sLp0] := constt_cfRes_irr L s; rewrite -/theta in sLp0.\npose phi := 'chi_p0; pose T := 'I_G[phi].\nhave sTG: T \\subset G := subsetIl G _.\nhave /eqP mulKT: (K * T)%g == G.\n  rewrite eqEcard mulG_subG sKG sTG -LagrangeMr -indexgI -(Lagrange sTG) /= -/T.\n  rewrite mulnC leq_mul // setIA (setIidPl sKG) -!size_cfclass // -/phi.\n  rewrite uniq_leq_size ?cfclass_uniq // => _ /cfclassP[x Gx ->].\n  have: conjg_Iirr p0 x \\in irr_constt ('Res theta).\n    have /inertiaJ <-: x \\in 'I[theta] := subsetP IGtheta x Gx.\n    by rewrite -(cfConjgRes _ nsKG) // irr_consttE conjg_IirrE // cfConjg_iso.\n  apply: contraR; rewrite -conjg_IirrE // => not_sLp0x.\n  rewrite (Clifford_Res_sum_cfclass nsLK sLp0) cfdotZl cfdot_suml.\n  rewrite big1_seq ?mulr0 // => _ /cfclassP[y Ky ->]; rewrite -conjg_IirrE //.\n  rewrite cfdot_irr mulrb ifN_eq ?(contraNneq _ not_sLp0x) // => <-.\n  by rewrite conjg_IirrE //; apply/cfclassP; exists y.\nhave nsKT_G: K :&: T <| G.\n  rewrite /normal subIset ?sKG // -mulKT setIA (setIidPl sKG) mulG_subG.\n  rewrite normsIG // sub_der1_norm ?subsetIl //.\n  exact: subset_trans (der1_min nLK abKbar) (sub_Inertia _ sLK).\nhave [e DthL]: exists e, 'Res theta = e%:R *: \\sum_(xi <- (phi ^: K)%CF) xi.\n  rewrite (Clifford_Res_sum_cfclass nsLK sLp0) -/phi; set e := '[_, _].\n  by exists (truncC e); rewrite truncCK ?Cnat_cfdot_char ?cfRes_char ?irr_char.\nhave [defKT | ltKT_K] := eqVneq (K :&: T) K; last first.\n  have defKT: K :&: T = L.\n    apply: maxL; last by rewrite subsetI sLK sub_Inertia.\n    by rewrite normal_norm // properEneq ltKT_K subsetIl.\n  have t_cast: size (phi ^: K)%CF = t.\n    by rewrite size_cfclass //= -{2}(setIidPl sKG) -setIA defKT.\n  pose phiKt := Tuple (introT eqP t_cast); pose p i := cfIirr (tnth phiKt i).\n  have pK i: 'chi_(p i) = (phi ^: K)%CF`_i.\n    rewrite cfIirrE; first by rewrite (tnth_nth 0).\n    by have /cfclassP[y _ ->] := mem_tnth i phiKt; rewrite cfConjg_irr ?mem_irr.\n  constructor 3; exists p => [i j /(congr1 (tnth (irr L)))/eqP| ].\n    by apply: contraTeq; rewrite !pK !nth_uniq ?t_cast ?cfclass_uniq.\n  have{} DthL: 'Res theta = e%:R *: \\sum_(i < t) (phi ^: K)%CF`_i.\n    by rewrite DthL (big_nth 0) big_mkord t_cast.\n  suffices /eqP e1: e == 1%N by rewrite DthL e1 scale1r; apply: eq_bigr.\n  have Dth1: theta 1%g = e%:R * t%:R * phi 1%g.\n    rewrite -[t]card_ord -mulrA -(cfRes1 L) DthL cfunE; congr (_ * _).\n    rewrite mulr_natl -sumr_const sum_cfunE -t_cast; apply: eq_bigr => i _.\n    by have /cfclassP[y _ ->] := mem_nth 0 (valP i); rewrite cfConjg1.\n  rewrite eqn_leq lt0n (contraNneq _ (irr1_neq0 s)); last first.\n    by rewrite Dth1 => ->; rewrite !mul0r.\n  rewrite -leC_nat -(ler_pmul2r (gt0CiG K L)) -/t -(ler_pmul2r (irr1_gt0 p0)).\n  rewrite mul1r -Dth1 -cfInd1 //.\n  by rewrite char1_ge_constt ?cfInd_char ?irr_char ?constt_Ind_Res.\nhave IKphi: 'I_K[phi] = K by rewrite -{1}(setIidPl sKG) -setIA.\nhave{} DthL: 'Res[L] theta = e%:R *: phi.\n  by rewrite DthL -[rhs in (_ ^: rhs)%CF]IKphi cfclass_inertia big_seq1.\npose mmLth := @mul_mod_Iirr K L s.\nhave linKbar := char_abelianP _ abKbar.\nhave LmodL i: ('chi_i %% L)%CF \\is a linear_char := cfMod_lin_char (linKbar i).\nhave mmLthE i: 'chi_(mmLth i) = ('chi_i %% L)%CF * theta.\n  by rewrite cfIirrE ?mod_IirrE // mul_lin_irr ?mem_irr.\nhave mmLthL i: 'Res[L] 'chi_(mmLth i) = 'Res[L] theta.\n  rewrite mmLthE rmorphM /= cfRes_sub_ker ?cfker_mod ?lin_char1 //.\n  by rewrite scale1r mul1r.\nhave [inj_Mphi | /injectivePn[i [j i'j eq_mm_ij]]] := boolP (injectiveb mmLth).\n  suffices /eqP e1: e == 1%N by constructor 1; rewrite DthL e1 scale1r mem_irr.\n  rewrite eqn_leq lt0n (contraNneq _ (irr1_neq0 s)); last first.\n    by rewrite -(cfRes1 L) DthL cfunE => ->; rewrite !mul0r.\n  rewrite -leq_sqr -leC_nat natrX -(ler_pmul2r (irr1_gt0 p0)) -mulrA mul1r.\n  have ->: e%:R * 'chi_p0 1%g = 'Res[L] theta 1%g by rewrite DthL cfunE.\n  rewrite cfRes1 -(ler_pmul2l (gt0CiG K L)) -cfInd1 // -/phi.\n  rewrite -card_quotient // -card_Iirr_abelian // mulr_natl.\n  rewrite ['Ind phi]cfun_sum_cfdot sum_cfunE (bigID [in codom mmLth]) /=.\n  rewrite ler_paddr ?sumr_ge0 // => [i _|].\n    by rewrite char1_ge0 ?rpredZ_Cnat ?Cnat_cfdot_char ?cfInd_char ?irr_char.\n  rewrite -big_uniq //= big_image -sumr_const ler_sum // => i _.\n  rewrite cfunE -[in leRHS](cfRes1 L) -cfdot_Res_r mmLthL cfRes1.\n  by rewrite DthL cfdotZr rmorph_nat cfnorm_irr mulr1.\nconstructor 2; exists e; first by exists p0.\npose mu := (('chi_i / 'chi_j)%R %% L)%CF; pose U := cfker mu.\nhave lin_mu: mu \\is a linear_char by rewrite cfMod_lin_char ?rpred_div.\nhave Uj := lin_char_unitr (linKbar j).\nhave ltUK: U \\proper K.\n  rewrite /proper cfker_sub /U; have /irrP[k Dmu] := lin_char_irr lin_mu.\n  rewrite Dmu subGcfker -irr_eq1 -Dmu cfMod_eq1 //.\n  by rewrite (can2_eq (divrK Uj) (mulrK Uj)) mul1r (inj_eq irr_inj).\nsuffices: theta \\in 'CF(K, L).\n  rewrite -cfnorm_Res_leif // DthL cfnormZ !cfnorm_irr !mulr1 normr_nat.\n  by rewrite -natrX eqC_nat => /eqP.\nhave <-: gcore U G = L.\n  apply: maxL; last by rewrite sub_gcore ?cfker_mod.\n  by rewrite gcore_norm (sub_proper_trans (gcore_sub _ _)).\napply/cfun_onP=> x; apply: contraNeq => nz_th_x.\napply/bigcapP=> y /(subsetP IGtheta)/setIdP[nKy /eqP th_y].\napply: contraR nz_th_x; rewrite mem_conjg -{}th_y cfConjgE {nKy}//.\nmove: {x y}(x ^ _) => x U'x; have [Kx | /cfun0-> //] := boolP (x \\in K).\nhave /eqP := congr1 (fun k => (('chi_j %% L)%CF^-1 * 'chi_k) x) eq_mm_ij.\nrewrite -rmorphV // !mmLthE !mulrA -!rmorphM mulVr //= rmorph1 !cfunE.\nrewrite (mulrC _^-1) -/mu -subr_eq0 -mulrBl cfun1E Kx mulf_eq0 => /orP[]//.\nrewrite mulrb subr_eq0 -(lin_char1 lin_mu) [_ == _](contraNF _ U'x) //.\nby rewrite /U cfkerEchar ?lin_charW // inE Kx.\nQed.\n\n(* This is Isaacs, Corollary (6.19). *)\nCorollary cfRes_prime_irr_cases G N s p (chi := 'chi[G]_s) :\n    N <| G -> #|G : N| = p -> prime p ->\n  [\\/ 'Res[N] chi \\in irr N\n   |  exists2 c, injective c & 'Res[N] chi = \\sum_(i < p) 'chi_(c i)].\nProof.\nmove=> /andP[sNG nNG] iGN pr_p.\nhave chiefGN: chief_factor G N G.\n  apply/andP; split=> //; apply/maxgroupP.\n  split=> [|M /andP[/andP[sMG ltMG] _] sNM].\n    by rewrite /proper sNG -indexg_gt1 iGN prime_gt1.\n  apply/esym/eqP; rewrite eqEsubset sNM -indexg_eq1 /= eq_sym.\n  rewrite -(eqn_pmul2l (indexg_gt0 G M)) muln1 Lagrange_index // iGN.\n  by apply/eqP/prime_nt_dvdP; rewrite ?indexg_eq1 // -iGN indexgS.\nhave abGbar: abelian (G / N).\n  by rewrite cyclic_abelian ?prime_cyclic ?card_quotient ?iGN.\nhave IGchi: G \\subset 'I[chi] by apply: sub_inertia.\nhave [] := invariant_chief_irr_cases chiefGN abGbar IGchi; first by left.\n  case=> e _ /(congr1 (fun m => odd (logn p m)))/eqP/idPn[].\n  by rewrite lognX mul2n odd_double iGN logn_prime // eqxx.\nby rewrite iGN; right.\nQed.\n\n(* This is Isaacs, Corollary (6.20). *)\nCorollary prime_invariant_irr_extendible G N s p :\n    N <| G -> #|G : N| = p -> prime p -> G \\subset 'I['chi_s] ->\n  {t | 'Res[N, G] 'chi_t = 'chi_s}.\nProof.\nmove=> nsNG iGN pr_p IGchi.\nhave [t sGt] := constt_cfInd_irr s (normal_sub nsNG); exists t.\nhave [e DtN]: exists e, 'Res 'chi_t = e%:R *: 'chi_s.\n  rewrite constt_Ind_Res in sGt.\n  rewrite (Clifford_Res_sum_cfclass nsNG sGt); set e := '[_, _].\n  rewrite cfclass_invariant // big_seq1.\n  by exists (truncC e); rewrite truncCK ?Cnat_cfdot_char ?cfRes_char ?irr_char.\nhave [/irrWnorm/eqP | [c injc DtNc]] := cfRes_prime_irr_cases t nsNG iGN pr_p.\n  rewrite DtN cfnormZ cfnorm_irr normr_nat mulr1 -natrX pnatr_eq1.\n  by rewrite muln_eq1 andbb => /eqP->; rewrite scale1r.\nhave nz_e: e != 0%N.\n  have: 'Res[N] 'chi_t != 0 by rewrite cfRes_eq0 // ?irr_char ?irr_neq0.\n  by rewrite DtN; apply: contraNneq => ->; rewrite scale0r.\nhave [i s'ci]: exists i, c i != s.\n  pose i0 := Ordinal (prime_gt0 pr_p); pose i1 := Ordinal (prime_gt1 pr_p).\n  have [<- | ] := eqVneq (c i0) s; last by exists i0.\n  by exists i1; rewrite (inj_eq injc).\nhave /esym/eqP/idPn[] := congr1 (cfdotr 'chi_(c i)) DtNc; rewrite {1}DtN /=.\nrewrite cfdot_suml cfdotZl cfdot_irr mulrb ifN_eqC // mulr0.\nrewrite (bigD1 i) //= cfnorm_irr big1 ?addr0 ?oner_eq0 // => j i'j.\nby rewrite cfdot_irr mulrb ifN_eq ?(inj_eq injc).\nQed.\n\n(* This is Isaacs, Lemma (6.24). *)\nLemma extend_to_cfdet G N s c0 u :\n    let theta := 'chi_s in let lambda := cfDet theta in let mu := 'chi_u in\n    N <| G -> coprime #|G : N| (truncC (theta 1%g)) ->\n    'Res[N, G] 'chi_c0 = theta -> 'Res[N, G] mu = lambda ->\n  exists2 c, 'Res 'chi_c = theta /\\ cfDet 'chi_c = mu\n          & forall c1, 'Res 'chi_c1 = theta -> cfDet 'chi_c1 = mu -> c1 = c.\nProof.\nmove=> theta lambda mu nsNG; set e := #|G : N|; set f := truncC _.\nset eta := 'chi_c0 => co_e_f etaNth muNlam; have [sNG nNG] := andP nsNG.\nhave fE: f%:R = theta 1%g by rewrite truncCK ?Cnat_irr1.\npose nu := cfDet eta; have lin_nu: nu \\is a linear_char := cfDet_lin_char _.\nhave nuNlam: 'Res nu = lambda by rewrite -cfDetRes ?irr_char ?etaNth.\nhave lin_lam: lambda \\is a linear_char := cfDet_lin_char _.\nhave lin_mu: mu \\is a linear_char.\n  by have:= lin_lam; rewrite -muNlam; apply: cfRes_lin_lin; apply: irr_char.\nhave [Unu Ulam] := (lin_char_unitr lin_nu, lin_char_unitr lin_lam).\npose alpha := mu / nu.\nhave alphaN_1: 'Res[N] alpha = 1 by rewrite rmorph_div //= muNlam nuNlam divrr.\nhave lin_alpha: alpha \\is a linear_char by apply: rpred_div.\nhave alpha_e: alpha ^+ e = 1.\n  have kerNalpha: N \\subset cfker alpha.\n    by rewrite -subsetIidl -cfker_Res ?lin_charW // alphaN_1 cfker_cfun1.\n  apply/eqP; rewrite -(cfQuoK nsNG kerNalpha) -rmorphX cfMod_eq1 //.\n  rewrite -dvdn_cforder /e -card_quotient //.\n  by rewrite cforder_lin_char_dvdG ?cfQuo_lin_char.\nhave det_alphaXeta b: cfDet (alpha ^+ b * eta) = alpha ^+ (b * f) * nu.\n  by rewrite cfDet_mul_lin ?rpredX ?irr_char // -exprM -(cfRes1 N) etaNth.\nhave [b bf_mod_e]: exists b, b * f = 1 %[mod e].\n  rewrite -(chinese_modl co_e_f 1 0) /chinese !mul0n addn0 !mul1n mulnC.\n  by exists (egcdn f e).1.\nhave alpha_bf: alpha ^+ (b * f) = alpha.\n  by rewrite -(expr_mod _ alpha_e) bf_mod_e expr_mod.\nhave /irrP[c Dc]: alpha ^+ b * eta \\in irr G.\n  by rewrite mul_lin_irr ?rpredX ?mem_irr.\nhave chiN: 'Res 'chi_c = theta.\n  by rewrite -Dc rmorphM rmorphX /= alphaN_1 expr1n mul1r.\nhave det_chi: cfDet 'chi_c = mu by rewrite -Dc det_alphaXeta alpha_bf divrK.\nexists c => // c2 c2Nth det_c2_mu; apply: irr_inj.\nhave [irrMc _ imMc _] := constt_Ind_ext nsNG chiN.\nhave /codomP[s2 Dc2]: c2 \\in codom (@mul_mod_Iirr G N c).\n  by rewrite -imMc constt_Ind_Res c2Nth constt_irr ?inE.\nhave{} Dc2: 'chi_c2 = ('chi_s2 %% N)%CF * 'chi_c.\n  by rewrite Dc2 cfIirrE // mod_IirrE.\nhave s2_lin: 'chi_s2 \\is a linear_char.\n  rewrite qualifE irr_char; apply/eqP/(mulIf (irr1_neq0 c)).\n  rewrite mul1r -[in RHS](cfRes1 N) chiN -c2Nth cfRes1.\n  by rewrite Dc2 cfunE cfMod1.\nhave s2Xf_1: 'chi_s2 ^+ f = 1.\n  apply/(can_inj (cfModK nsNG))/(mulIr (lin_char_unitr lin_mu))/esym.\n  rewrite rmorph1 rmorphX /= mul1r -{1}det_c2_mu Dc2 -det_chi.\n  by rewrite cfDet_mul_lin ?cfMod_lin_char ?irr_char // -(cfRes1 N) chiN.\nsuffices /eqP s2_1: 'chi_s2 == 1 by rewrite Dc2 s2_1 rmorph1 mul1r.\nrewrite -['chi_s2]expr1 -dvdn_cforder -(eqnP co_e_f) dvdn_gcd.\nby rewrite /e -card_quotient ?cforder_lin_char_dvdG //= dvdn_cforder s2Xf_1.\nQed.\n\n(* This is Isaacs, Theorem (6.25). *)\nTheorem solvable_irr_extendible_from_det G N s (theta := 'chi[N]_s) :\n    N <| G -> solvable (G / N) ->\n    G \\subset 'I[theta] -> coprime #|G : N| (truncC (theta 1%g)) ->\n  [exists c, 'Res 'chi[G]_c == theta]\n    = [exists u, 'Res 'chi[G]_u == cfDet theta].\nProof.\nset e := #|G : N|; set f := truncC _ => nsNG solG IGtheta co_e_f.\napply/exists_eqP/exists_eqP=> [[c cNth] | [u uNdth]].\n  have /lin_char_irr/irrP[u Du] := cfDet_lin_char 'chi_c.\n  by exists u; rewrite -Du -cfDetRes ?irr_char ?cNth.\nmove: {2}e.+1 (ltnSn e) => m.\nelim: m => // m IHm in G u e nsNG solG IGtheta co_e_f uNdth *.\nrewrite ltnS => le_e; have [sNG nNG] := andP nsNG.\nhave [<- | ltNG] := eqsVneq N G; first by exists s; rewrite cfRes_id.\nhave [G0 maxG0 sNG0]: {G0 | maxnormal (gval G0) G G & N \\subset G0}.\n  by apply: maxgroup_exists; rewrite properEneq ltNG sNG.\nhave [/andP[ltG0G nG0G] maxG0_P] := maxgroupP maxG0.\nset mu := 'chi_u in uNdth; have lin_mu: mu \\is a linear_char.\n  by rewrite qualifE irr_char -(cfRes1 N) uNdth /= lin_char1 ?cfDet_lin_char.\nhave sG0G := proper_sub ltG0G; have nsNG0 := normalS sNG0 sG0G nsNG.\nhave nsG0G: G0 <| G by apply/andP.\nhave /lin_char_irr/irrP[u0 Du0] := cfRes_lin_char G0 lin_mu.\nhave u0Ndth: 'Res 'chi_u0 = cfDet theta by rewrite -Du0 cfResRes.\nhave IG0theta: G0 \\subset 'I[theta].\n  by rewrite (subset_trans sG0G) // -IGtheta subsetIr.\nhave coG0f: coprime #|G0 : N| f by rewrite (coprime_dvdl _ co_e_f) ?indexSg.\nhave{m IHm le_e} [c0 c0Ns]: exists c0, 'Res 'chi[G0]_c0 = theta.\n  have solG0: solvable (G0 / N) := solvableS (quotientS N sG0G) solG.\n  apply: IHm nsNG0 solG0 IG0theta coG0f u0Ndth (leq_trans _ le_e).\n  by rewrite -(ltn_pmul2l (cardG_gt0 N)) !Lagrange ?proper_card.\nhave{c0 c0Ns} [c0 [c0Ns dc0_u0] Uc0] := extend_to_cfdet nsNG0 coG0f c0Ns u0Ndth.\nhave IGc0: G \\subset 'I['chi_c0].\n  apply/subsetP=> x Gx; rewrite inE (subsetP nG0G) //= -conjg_IirrE.\n  apply/eqP; congr 'chi__; apply: Uc0; rewrite conjg_IirrE.\n    by rewrite -(cfConjgRes _ nsG0G nsNG) // c0Ns inertiaJ ?(subsetP IGtheta).\n  by rewrite cfDetConjg dc0_u0 -Du0 (cfConjgRes _ _ nsG0G) // cfConjg_id.\nhave prG0G: prime #|G : G0|.\n  have [h injh im_h] := third_isom sNG0 nsNG nsG0G.\n  rewrite -card_quotient // -im_h // card_injm //.\n  rewrite simple_sol_prime 1?quotient_sol //.\n  by rewrite /simple -(injm_minnormal injh) // im_h // maxnormal_minnormal.\nhave [t tG0c0] := prime_invariant_irr_extendible nsG0G (erefl _) prG0G IGc0.\nby exists t; rewrite /theta -c0Ns -tG0c0 cfResRes.\nQed.\n\n(* This is Isaacs, Theorem (6.26). *)\nTheorem extend_linear_char_from_Sylow G N (lambda : 'CF(N)) :\n    N <| G -> lambda \\is a linear_char -> G \\subset 'I[lambda] ->\n    (forall p, p \\in \\pi('o(lambda)%CF) ->\n       exists2 Hp : {group gT},\n         [/\\ N \\subset Hp, Hp \\subset G & p.-Sylow(G / N) (Hp / N)%g]\n       & exists u, 'Res 'chi[Hp]_u = lambda) ->\n  exists u, 'Res[N, G] 'chi_u = lambda.\nProof.\nset m := 'o(lambda)%CF => nsNG lam_lin IGlam p_ext_lam.\nhave [sNG nNG] := andP nsNG; have linN := @cfRes_lin_lin _ _ N.\nwlog [p p_lam]: lambda @m lam_lin IGlam p_ext_lam /\n  exists p : nat, \\pi(m) =i (p : nat_pred).\n- move=> IHp; have [linG [cf [inj_cf _ lin_cf onto_cf]]] := lin_char_group N.\n  case=> cf1 cfM cfX _ cf_order; have [lam cf_lam] := onto_cf _ lam_lin.\n  pose mu p := cf lam.`_p; pose pi_m p := p \\in \\pi(m).\n  have Dm: m = #[lam] by rewrite /m cfDet_order_lin // cf_lam cf_order.\n  have Dlambda: lambda = \\prod_(p < m.+1 | pi_m p) mu p.\n    rewrite -(big_morph cf cfM cf1) big_mkcond cf_lam /pi_m Dm; congr (cf _).\n    rewrite -{1}[lam]prod_constt big_mkord; apply: eq_bigr => p _.\n    by case: ifPn => // p'lam; apply/constt1P; rewrite /p_elt p'natEpi.\n  have lin_mu p: mu p \\is a linear_char by rewrite /mu cfX -cf_lam rpredX.\n  suffices /fin_all_exists [u uNlam] (p : 'I_m.+1):\n    exists u, pi_m p -> 'Res[N, G] 'chi_u = mu p.\n  - pose nu := \\prod_(p < m.+1 | pi_m p) 'chi_(u p).\n    have lin_nu: nu \\is a linear_char.\n      by apply: rpred_prod => p m_p; rewrite linN ?irr_char ?uNlam.\n    have /irrP[u1 Dnu] := lin_char_irr lin_nu.\n    by exists u1; rewrite Dlambda -Dnu rmorph_prod; apply: eq_bigr.\n  have [m_p | _] := boolP (pi_m p); last by exists 0.\n  have o_mu: \\pi('o(mu p)%CF) =i (p : nat_pred).\n    rewrite cfDet_order_lin // cf_order orderE /=.\n    have [|pr_p _ [k ->]] := pgroup_pdiv (p_elt_constt p lam).\n      by rewrite cycle_eq1 (sameP eqP constt1P) /p_elt p'natEpi // negbK -Dm.\n    by move=> q; rewrite pi_of_exp // pi_of_prime.\n  have IGmu: G \\subset 'I[mu p].\n    rewrite (subset_trans IGlam) // /mu cfX -cf_lam.\n    elim: (chinese _ _ _ _) => [|k IHk]; first by rewrite inertia1 norm_inertia.\n    by rewrite exprS (subset_trans _ (inertia_mul _ _)) // subsetIidl.\n  have [q||u] := IHp _ (lin_mu p) IGmu; [ | by exists p | by exists u].\n  rewrite o_mu => /eqnP-> {q}.\n  have [Hp sylHp [u uNlam]] := p_ext_lam p m_p; exists Hp => //.\n  rewrite /mu cfX -cf_lam -uNlam -rmorphX /=; set nu := _ ^+ _.\n  have /lin_char_irr/irrP[v ->]: nu \\is a linear_char; last by exists v.\n  by rewrite rpredX // linN ?irr_char ?uNlam.\nhave pi_m_p: p \\in \\pi(m) by rewrite p_lam !inE.\nhave [pr_p mgt0]: prime p /\\ (m > 0)%N.\n  by have:= pi_m_p; rewrite mem_primes => /and3P[].\nhave p_m: p.-nat m by rewrite -(eq_pnat _ p_lam) pnat_pi.\nhave{p_ext_lam} [H [sNH sHG sylHbar] [v vNlam]] := p_ext_lam p pi_m_p.\nhave co_p_GH: coprime p #|G : H|.\n  rewrite -(index_quotient_eq _ sHG nNG) ?subIset ?sNH ?orbT //.\n  by rewrite (pnat_coprime (pnat_id pr_p)) //; have [] := and3P sylHbar.\nhave lin_v: 'chi_v \\is a linear_char by rewrite linN ?irr_char ?vNlam.\npose nuG := 'Ind[G] 'chi_v.\nhave [c vGc co_p_f]: exists2 c, c \\in irr_constt nuG & ~~ (p %| 'chi_c 1%g)%C.\n  apply/exists_inP; rewrite -negb_forall_in.\n  apply: contraL co_p_GH => /forall_inP p_dv_v1.\n  rewrite prime_coprime // negbK -dvdC_nat -[rhs in (_ %| rhs)%C]mulr1.\n  rewrite -(lin_char1 lin_v) -cfInd1 // ['Ind _]cfun_sum_constt /=.\n  rewrite sum_cfunE rpred_sum // => i /p_dv_v1 p_dv_chi1i.\n  rewrite cfunE dvdC_mull // rpred_Cnat //.\n  by rewrite Cnat_cfdot_char ?cfInd_char ?irr_char.\npose f := truncC ('chi_c 1%g); pose b := (egcdn f m).1.\nhave fK: f%:R = 'chi_c 1%g by rewrite truncCK ?Cnat_irr1.\nhave fb_mod_m: f * b = 1 %[mod m].\n  have co_m_f: coprime m f.\n    by rewrite (pnat_coprime p_m) ?p'natE // -dvdC_nat CdivE fK.\n  by rewrite -(chinese_modl co_m_f 1 0) /chinese !mul0n addn0 mul1n.\nhave /irrP[s Dlam] := lin_char_irr lam_lin.\nhave cHv: v \\in irr_constt ('Res[H] 'chi_c) by rewrite -constt_Ind_Res.\nhave{cHv} cNs: s \\in irr_constt ('Res[N] 'chi_c).\n  rewrite -(cfResRes _ sNH) ?(constt_Res_trans _ cHv) ?cfRes_char ?irr_char //.\n  by rewrite vNlam Dlam constt_irr !inE.\nhave DcN: 'Res[N] 'chi_c = lambda *+ f.\n  have:= Clifford_Res_sum_cfclass nsNG cNs.\n  rewrite cfclass_invariant -Dlam // big_seq1 Dlam => DcN.\n  have:= cfRes1 N 'chi_c; rewrite DcN cfunE -Dlam lin_char1 // mulr1 => ->.\n  by rewrite -scaler_nat fK.\nhave /lin_char_irr/irrP[d Dd]: cfDet 'chi_c ^+ b \\is a linear_char.\n  by rewrite rpredX // cfDet_lin_char.\nexists d; rewrite -{}Dd rmorphX /= -cfDetRes ?irr_char // DcN.\nrewrite cfDetMn ?lin_charW // -exprM cfDet_id //.\nrewrite -(expr_mod _ (exp_cforder _)) -cfDet_order_lin // -/m.\nby rewrite fb_mod_m /m cfDet_order_lin // expr_mod ?exp_cforder.\nQed.\n\n(* This is Isaacs, Corollary (6.27). *)\nCorollary extend_coprime_linear_char G N (lambda : 'CF(N)) :\n    N <| G -> lambda \\is a linear_char -> G \\subset 'I[lambda] ->\n    coprime #|G : N| 'o(lambda)%CF ->\n  exists u, [/\\ 'Res 'chi[G]_u = lambda, 'o('chi_u)%CF = 'o(lambda)%CF\n              & forall v,\n                  'Res 'chi_v = lambda -> coprime #|G : N| 'o('chi_v)%CF ->\n                v = u].\nProof.\nset e := #|G : N| => nsNG lam_lin IGlam co_e_lam; have [sNG nNG] := andP nsNG.\nhave [p lam_p | v vNlam] := extend_linear_char_from_Sylow nsNG lam_lin IGlam.\n  exists N; last first.\n    by have /irrP[u ->] := lin_char_irr lam_lin; exists u; rewrite cfRes_id.\n  split=> //; rewrite trivg_quotient /pHall sub1G pgroup1 indexg1.\n  rewrite card_quotient //= -/e (pi'_p'nat _ lam_p) //.\n  rewrite -coprime_pi' ?indexg_gt0 1?coprime_sym //.\n  by have:= lam_p; rewrite mem_primes => /and3P[].\nset nu := 'chi_v in vNlam.\nhave lin_nu: nu \\is a linear_char.\n  by rewrite (@cfRes_lin_lin _ _ N) ?vNlam ?irr_char.\nhave [b be_mod_lam]: exists b, b * e = 1 %[mod 'o(lambda)%CF].\n  rewrite -(chinese_modr co_e_lam 0 1) /chinese !mul0n !mul1n mulnC.\n  by set b := _.1; exists b.\nhave /irrP[u Du]: nu ^+ (b * e) \\in irr G by rewrite lin_char_irr ?rpredX.\nexists u; set mu := 'chi_u in Du *.\nhave uNlam: 'Res mu = lambda.\n  rewrite cfDet_order_lin // in be_mod_lam.\n  rewrite -Du rmorphX /= vNlam -(expr_mod _ (exp_cforder _)) //.\n  by rewrite be_mod_lam expr_mod ?exp_cforder.\nhave lin_mu: mu \\is a linear_char by rewrite -Du rpredX.\nhave o_mu: ('o(mu) = 'o(lambda))%CF.\n  have dv_o_lam_mu: 'o(lambda)%CF %| 'o(mu)%CF.\n    by rewrite !cfDet_order_lin // -uNlam cforder_Res.\n  have kerNnu_olam: N \\subset cfker (nu ^+ 'o(lambda)%CF).\n    rewrite -subsetIidl -cfker_Res ?rpredX ?irr_char //.\n    by rewrite rmorphX /= vNlam cfDet_order_lin // exp_cforder cfker_cfun1.\n  apply/eqP; rewrite eqn_dvd dv_o_lam_mu andbT cfDet_order_lin //.\n  rewrite dvdn_cforder -Du exprAC -dvdn_cforder dvdn_mull //.\n  rewrite -(cfQuoK nsNG kerNnu_olam) cforder_mod // /e -card_quotient //.\n  by rewrite cforder_lin_char_dvdG ?cfQuo_lin_char ?rpredX.\nsplit=> // t tNlam co_e_t.\nhave lin_t: 'chi_t \\is a linear_char.\n  by rewrite (@cfRes_lin_lin _ _ N) ?tNlam ?irr_char.\nhave Ut := lin_char_unitr lin_t.\nhave kerN_mu_t: N \\subset cfker (mu / 'chi_t)%R.\n  rewrite -subsetIidl -cfker_Res ?lin_charW ?rpred_div ?rmorph_div //.\n  by rewrite /= uNlam tNlam divrr ?lin_char_unitr ?cfker_cfun1.\nhave co_e_mu_t: coprime e #[(mu / 'chi_t)%R]%CF.\n  suffices dv_o_mu_t: #[(mu / 'chi_t)%R]%CF %| 'o(mu)%CF * 'o('chi_t)%CF.\n    by rewrite (coprime_dvdr dv_o_mu_t) // coprimeMr o_mu co_e_lam.\n  rewrite !cfDet_order_lin //; apply/dvdn_cforderP=> x Gx.\n  rewrite invr_lin_char // !cfunE exprMn -rmorphX {2}mulnC.\n  by rewrite !(dvdn_cforderP _) ?conjC1 ?mulr1 // dvdn_mulr.\nhave /eqP mu_t_1: mu / 'chi_t == 1.\n  rewrite -(dvdn_cforder (_ / _)%R 1) -(eqnP co_e_mu_t) dvdn_gcd dvdnn andbT.\n  rewrite -(cfQuoK nsNG kerN_mu_t) cforder_mod // /e -card_quotient //.\n  by rewrite cforder_lin_char_dvdG ?cfQuo_lin_char ?rpred_div.\nby apply: irr_inj; rewrite -['chi_t]mul1r -mu_t_1 divrK.\nQed.\n\n(* This is Isaacs, Corollary (6.28). *)\nCorollary extend_solvable_coprime_irr G N t (theta := 'chi[N]_t) :\n    N <| G -> solvable (G / N) -> G \\subset 'I[theta] ->\n    coprime #|G : N| ('o(theta)%CF * truncC (theta 1%g)) ->\n  exists c, [/\\ 'Res 'chi[G]_c = theta, 'o('chi_c)%CF = 'o(theta)%CF\n              & forall d,\n                  'Res 'chi_d = theta -> coprime #|G : N| 'o('chi_d)%CF ->\n                d = c].\nProof.\nset e := #|G : N|; set f := truncC _ => nsNG solG IGtheta.\nrewrite coprimeMr => /andP[co_e_th co_e_f].\nhave [sNG nNG] := andP nsNG; pose lambda := cfDet theta.\nhave lin_lam: lambda \\is a linear_char := cfDet_lin_char theta.\nhave IGlam: G \\subset 'I[lambda].\n  apply/subsetP=> y /(subsetP IGtheta)/setIdP[nNy /eqP th_y].\n  by rewrite inE nNy /= -cfDetConjg th_y.\nhave co_e_lam: coprime e 'o(lambda)%CF by rewrite cfDet_order_lin.\nhave [//|u [uNlam o_u Uu]] := extend_coprime_linear_char nsNG lin_lam IGlam.\nhave /exists_eqP[c cNth]: [exists c, 'Res 'chi[G]_c == theta].\n  rewrite solvable_irr_extendible_from_det //.\n  by apply/exists_eqP; exists u.\nhave{c cNth} [c [cNth det_c] Uc] := extend_to_cfdet nsNG co_e_f cNth uNlam.\nhave lin_u: 'chi_u \\is a linear_char by rewrite -det_c cfDet_lin_char.\nexists c; split=> // [|c0 c0Nth co_e_c0].\n  by rewrite !cfDet_order_lin // -det_c in o_u.\nhave lin_u0: cfDet 'chi_c0 \\is a linear_char := cfDet_lin_char 'chi_c0.\nhave /irrP[u0 Du0] := lin_char_irr lin_u0.\nhave co_e_u0: coprime e 'o('chi_u0)%CF by rewrite -Du0 cfDet_order_lin.\nhave eq_u0u: u0 = u by apply: Uu; rewrite // -Du0 -cfDetRes ?irr_char ?c0Nth.\nby apply: Uc; rewrite // Du0 eq_u0u.\nQed.\n\nEnd ExtendInvariantIrr.\n\nSection Frobenius.\n\nVariables (gT : finGroupType) (G K : {group gT}).\n\n(* Because he only defines Frobenius groups in chapter 7, Isaacs does not     *)\n(* state these theorems using the Frobenius property.                         *)\nHypothesis frobGK : [Frobenius G with kernel K].\n\n(* This is Isaacs, Theorem 6.34(a1). *)\nTheorem inertia_Frobenius_ker i : i != 0 -> 'I_G['chi[K]_i] = K.\nProof.\nhave [_ _ nsKG regK] := Frobenius_kerP frobGK; have [sKG nKG] := andP nsKG.\nmove=> nzi; apply/eqP; rewrite eqEsubset sub_Inertia // andbT.\napply/subsetP=> x /setIP[Gx /setIdP[nKx /eqP x_stab_i]].\nhave actIirrK: is_action G (@conjg_Iirr _ K).\n  split=> [y j k eq_jk | j y z Gy Gz].\n    by apply/irr_inj/(can_inj (cfConjgK y)); rewrite -!conjg_IirrE eq_jk.\n  by apply: irr_inj; rewrite !conjg_IirrE (cfConjgM _ nsKG).\npose ito := Action actIirrK; pose cto := ('Js \\ (subsetT G))%act.\nhave acts_Js : [acts G, on classes K | 'Js].\n  apply/subsetP=> y Gy; have nKy := subsetP nKG y Gy.\n  rewrite !inE; apply/subsetP=> _ /imsetP[z Gz ->] /[!inE]/=.\n  rewrite -class_rcoset norm_rlcoset // class_lcoset.\n  by apply: imset_f; rewrite memJ_norm.\nhave acts_cto : [acts G, on classes K | cto] by rewrite astabs_ract subsetIidl.\npose m := #|'Fix_(classes K | cto)[x]|.\nhave def_m: #|'Fix_ito[x]| = m.\n  apply: card_afix_irr_classes => // j y _ Ky /imsetP[_ /imsetP[z Kz ->] ->].\n  by rewrite conjg_IirrE cfConjgEJ // cfunJ.\nhave: (m != 1)%N.\n  rewrite -def_m (cardD1 (0 : Iirr K)) (cardD1 i) !(inE, sub1set) /=.\n  by rewrite conjg_Iirr0 nzi eqxx -(inj_eq irr_inj) conjg_IirrE x_stab_i eqxx.\napply: contraR => notKx; apply/cards1P; exists 1%g; apply/esym/eqP.\nrewrite eqEsubset !(sub1set, inE) classes1 /= conjs1g eqxx /=.\napply/subsetP=> _ /setIP[/imsetP[y Ky ->] /afix1P /= cyKx].\nhave /imsetP[z Kz def_yx]: y ^ x \\in y ^: K.\n  by rewrite -cyKx; apply: imset_f; apply: class_refl.\nrewrite inE classG_eq1; apply: contraR notKx => nty.\nrewrite -(groupMr x (groupVr Kz)).\napply: (subsetP (regK y _)); first exact/setD1P.\nrewrite !inE groupMl // groupV (subsetP sKG) //=.\nby rewrite conjg_set1 conjgM def_yx conjgK.\nQed.\n\n(* This is Isaacs, Theorem 6.34(a2) *)\nTheorem irr_induced_Frobenius_ker i : i != 0 -> 'Ind[G, K] 'chi_i \\in irr G.\nProof.\nmove/inertia_Frobenius_ker/group_inj=> defK.\nhave [_ _ nsKG _] := Frobenius_kerP frobGK.\nhave [] := constt_Inertia_bijection i nsKG; rewrite defK cfInd_id => -> //.\nby rewrite constt_irr !inE.\nQed.\n\n(* This is Isaacs, Theorem 6.34(b) *)\nTheorem Frobenius_Ind_irrP j :\n  reflect (exists2 i, i != 0 & 'chi_j = 'Ind[G, K] 'chi_i)\n          (~~ (K \\subset cfker 'chi_j)).\nProof.\nhave [_ _ nsKG _] := Frobenius_kerP frobGK; have [sKG nKG] := andP nsKG.\napply: (iffP idP) => [not_chijK1 | [i nzi ->]]; last first.\n  by rewrite cfker_Ind_irr ?sub_gcore // subGcfker.\nhave /neq0_has_constt[i chijKi]: 'Res[K] 'chi_j != 0 by apply: Res_irr_neq0.\nhave nz_i: i != 0.\n  by apply: contraNneq not_chijK1 => i0; rewrite constt0_Res_cfker // -i0.\nhave /irrP[k def_chik] := irr_induced_Frobenius_ker nz_i.\nhave: '['chi_j, 'chi_k] != 0 by rewrite -def_chik -cfdot_Res_l.\nby rewrite cfdot_irr pnatr_eq0; case: (j =P k) => // ->; exists i.\nQed.\n\nEnd Frobenius.\n", "meta": {"author": "math-comp", "repo": "math-comp", "sha": "e39f9173b484f2e8e7f69f746a619dcc8f3abc1b", "save_path": "github-repos/coq/math-comp-math-comp", "path": "github-repos/coq/math-comp-math-comp/math-comp-e39f9173b484f2e8e7f69f746a619dcc8f3abc1b/mathcomp/character/inertia.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2632429811913614}}
{"text": "Require Import ZArith.\nRequire Import Instructions.\n\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice fintype.\n\nRequire Import Utils Labels Memory Machine.\n\nImport LabelEqType.\n\nOpen Scope bool.\n\n(* Indistinguishability type class *)\nClass Indist (A : Type) : Type := {\n  indist : Label -> A -> A -> bool;\n\n  indistxx : forall obs, reflexive (indist obs);\n  indist_sym : forall obs, symmetric (indist obs)\n}.\n\nArguments indistxx {_ _} [obs] _.\nArguments indist_sym {_ _} [obs] _ _.\n\n#[refine] Instance oindist {T : Type} `{Indist T} : Indist (option T) := {\n  indist obs x1 x2 :=\n    match x1, x2 with\n    | None, None => true\n    | Some x1, Some x2 => indist obs x1 x2\n    | _, _ => false\n    end;\n  }.\nProof.\n- abstract by move => obs [x|//=]; rewrite indistxx.\n- abstract by move => obs [x|//=] [y|//=]; rewrite indist_sym.\nDefined.\n\n#[refine] Instance indistList {A : Type} `{Indist A} : Indist (list A) :=\n{|\n  indist lab l1 l2 :=\n    (size l1 == size l2) && all (fun p => indist lab p.1 p.2) (zip l1 l2)\n|}.\nProof.\n- abstract by move => obs; elim => [|x l IH] //=; rewrite indistxx IH.\n- abstract by move => obs; elim => [|x1 l1 IH] [|x2 l2] //=;\n  rewrite !eqSS !(andbC (indist _ _ _)) !andbA IH indist_sym.\nDefined.\n\nLemma indist_cons {A} `{Indist A} obs x1 l1 x2 l2 :\n  indist obs (x1 :: l1) (x2 :: l2) =\n  indist obs x1 x2 && indist obs l1 l2.\nProof. by rewrite {1 3}/indist /= eqSS; bool_congr. Qed.\n\n(* Indistinguishability of Values.\n   - Ignores the label (called only on unlabeled things)\n   - Just syntactic equality thanks to the per-stamp-level allocator!\n*)\n\n#[refine] Instance indistValue : Indist Value :=\n{|\n  indist _lab v1 v2 := v1 == v2\n|}.\nProof.\n- abstract by move => _; exact: eqxx.\n- abstract by move=> _; exact: eq_sym.\nDefined.\n\n(* Indistinguishability of Atoms.\n   - The labels have to be equal (observable labels)\n   - If the labels are equal then:\n     * If they are both less than the observability level then\n       the values must be indistinguishable\n     * Else if they are not lower, the label equality suffices\n*)\n\n#[refine] Instance indistAtom : Indist Atom :=\n{|\n  indist lab a1 a2 :=\n    let '(Atm v1 l1) := a1 in\n    let '(Atm v2 l2) := a2 in\n    (l1 == l2)\n    && (isHigh l1 lab || indist lab v1 v2)\n|}.\nProof.\n- abstract by move => obs [v l]; rewrite eqxx indistxx orbT.\n- abstract by move=> obs [v1 l1] [v2 l2]; rewrite eq_sym indist_sym;\n  case: eqP=> [->|] //=.\nDefined.\n\n#[refine] Instance indistFrame : Indist frame :=\n{|\n  indist lab f1 f2 :=\n    let '(Fr l1 vs1) := f1 in\n    let '(Fr l2 vs2) := f2 in\n    (* CH: this part is basically the same as indistinguishability of values;\n           try to remove this duplication at some point *)\n    (l1 == l2) && (isHigh l1 lab || indist lab vs1 vs2)\n|}.\nProof.\n- abstract by move => obs [l vs]; rewrite !eqxx indistxx orbT /=.\n- abstract by move=> obs [v1 l1] [v2 l2]; rewrite eq_sym indist_sym;\n  case: eqP=> [->|] //=.\nDefined.\n\n(* Indistinguishability of memories\n   - Get all corresponding memory frames\n   - Make sure they are indistinguishable\n   - Get all pairs that have been allocated in low contexts.\n*)\n\nDefinition blocks_stamped_below (lab : Label) (m : memory) : seq mframe :=\n  get_blocks (allThingsBelow lab) m.\n\nDefinition indistMemAsym lab m1 m2 :=\n  all (fun b =>\n         indist lab (get_memframe m1 b) (get_memframe m2 b))\n      (blocks_stamped_below lab m1).\n\n#[refine] Instance indistMem : Indist memory :=\n{|\n  indist lab m1 m2 :=\n    indistMemAsym lab m1 m2 && indistMemAsym lab m2 m1\n|}.\nProof.\n- abstract by move=> obs m; rewrite andbb /indistMemAsym;\n  apply/allP=> b b_in; rewrite indistxx.\n- abstract by move=> obs m1 m2; rewrite andbC.\nDefined.\n\nLemma indistMemP lab m1 m2 :\n  (forall b, isLow (stamp b) lab ->\n             get_memframe m1 b || get_memframe m2 b ->\n             indist lab (get_memframe m1 b) (get_memframe m2 b)) ->\n  indist lab m1 m2.\nProof.\nmove=> H; apply/andP; split; apply/allP=> b;\nrewrite /blocks_stamped_below -get_blocks_spec /allThingsBelow\n        mem_filter all_labels_correct andbT => /andP [Pb get_b];\nmove: (H b Pb); rewrite get_b ?orbT => /(_ erefl)=> //.\nby rewrite indist_sym.\nQed.\n\n(* Indistinguishability of stack frames (pointwise)\n     * The returning pc's must be equal\n     * The saved registers must be indistinguishable\n     * The returning register must be the same\n     * The returning labels must be equal\n*)\n\n#[refine] Instance indistStackFrame : Indist StackFrame :=\n{|\n  indist lab sf1 sf2 :=\n    match sf1, sf2 with\n      | SF p1 regs1 r1 l1, SF p2 regs2 r2 l2 =>\n        (isLow (pc_lab p1) lab || isLow (pc_lab p2) lab) ==>\n        [&& p1 == p2,\n            indist lab regs1 regs2,\n            r1 == r2 :> Z & l1 == l2]\n    end\n|}.\nProof.\n- abstract by move=> obs [ra rs rr rl]; rewrite !eqxx indistxx /= implybT.\n- abstract by move=> obs [ra1 rs1 rr1 rl1] [ra2 rs2 rr2 rl2];\n  rewrite orbC (eq_sym ra1) indist_sym (eq_sym rr1) (eq_sym rl1).\nDefined.\n\n#[refine] Instance indistStack : Indist Stack :=\n{|\n  indist lab s1 s2 :=\n    indist lab (unStack s1) (unStack s2)\n|}.\nProof.\n- abstract by move=> obs s; rewrite indistxx.\n- abstract by move=> obs s1 s2; exact: indist_sym.\nDefined.\n\n#[refine] Instance indistImems : Indist imem :=\n{|\n  indist _lab imem1 imem2 := imem1 == imem2 :> seq (@Instr Label)\n|}.\n\nProof.\n- abstract by move => _ r; exact: eqxx.\n- abstract by move => _ ??; exact: eq_sym.\nDefined.\n\nDefinition cropTop lab stk :=\n  let lowsf sf :=\n      let: SF (PAtm _ lab') _ _ _ := sf in flows lab' lab in\n  drop (find lowsf stk) stk.\n\nLemma cropTop_cons lab sf stk :\n  cropTop lab (sf :: stk) =\n  if (let: SF (PAtm _ lab') _ _ _ := sf in flows lab' lab) then\n    sf :: stk\n  else cropTop lab stk.\nProof.\ncase: sf=> [[ra ral] rs rr rl] /=.\nby rewrite /cropTop /=; case: ifP.\nQed.\n\nLemma indist_cropTop lab stk1 stk2 :\n  indist lab stk1 stk2 ->\n  indist lab (cropTop lab stk1) (cropTop lab stk2).\nProof.\nelim: stk1 stk2=> [|[[ra1 ral1] rs1 rr1 rl1] stk1 IH]\n                  [|[[ra2 ral2] rs2 rr2 rl2] stk2] //.\nrewrite indist_cons !cropTop_cons {1}/indist (lock (@indist)) /=.\nhave [l /=|/norP [/negbTE -> /negbTE ->]] := boolP (_ || _) => /andP [ind_sf ind_stk].\n  case/and4P: ind_sf (ind_sf) l => [/eqP [<- <-] _ _ _] ind_sf.\n  rewrite orbb => l; rewrite l /=.\n  move: ind_stk; rewrite -!lock indist_cons => ->.\n  by rewrite /= l andbT.\nby move: ind_stk; rewrite -!lock; apply: IH.\nQed.\n\n#[refine] Instance indistSState : Indist SState :=\n{|\n  indist lab st1 st2 :=\n    [&& indist lab (st_imem st1) (st_imem st2),\n        indist lab (st_mem st1) (st_mem st2) &\n        if isLow ∂(st_pc st1) lab || isLow ∂(st_pc st2) lab then\n          [&& st_pc st1 == st_pc st2,\n              indist lab (st_stack st1) (st_stack st2)\n              & indist lab (st_regs st1) (st_regs st2)]\n        else\n          indist lab (cropTop lab (unStack (st_stack st1)))\n                     (cropTop lab (unStack (st_stack st2)))]\n|}.\n\nProof.\n- abstract by move => obs [imem m stk regs [v l]]; rewrite !indistxx eqxx /=; case: ifP.\n- abstract by rewrite (lock (@indist));\n  move=> obs [im1 m1 st1 rs1 [v1 l1]] [im2 m2 st2 rs2 [v2 l2]] /=;\n  rewrite -!lock (indist_sym im1) (indist_sym m1) orbC (eq_sym)\n          (indist_sym st1) (indist_sym rs1) (indist_sym (drop _ _)).\nDefined.\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/Indist.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.2632429811913614}}
{"text": "Require Import List Common\n        ADT.ADTSig ADT.Core\n        ADTNotation.BuildADTSig ADTNotation.BuildADT\n        Common.ilist ADTNotation.StringBound\n        ADTRefinement.Core ADTRefinement.SetoidMorphisms\n        ADTRefinement.GeneralRefinements\n        ADTRefinement.Refinements.HoneRepresentation\n        ADTRefinement.BuildADTSetoidMorphisms\n        ADTRefinement.Refinements.ADTCache.\n\n(* A generic refinement and honing tactic for adding a cache\n    to the representation of an ADT built from [BuildADT]. *)\n\nSection addCache.\n\n  Variable rep : Type.\n  Variable cacheType : Type.\n\n  Variable cacheSpec : rep -> cacheType -> Prop.\n\n  (* When switching representations, we can always build a default\n     implementation (computation?) for the methods of an ADT with\n     using the old methods. *)\n\n  Definition addCacheToConsDef\n             (Sig : consSig)\n             (oldCons : @consDef rep Sig)\n  : @consDef (@cachedRep rep cacheType) Sig :=\n    {| consBody := addCacheToConstructor cacheSpec (consBody oldCons) |}.\n\n  Definition addCacheToMethDef\n             (Sig : methSig)\n             (oldCons : @methDef rep Sig)\n  : @methDef (@cachedRep rep cacheType) Sig :=\n    {| methBody := addCacheToMethod cacheSpec (methBody oldCons) |}.\n\n  Lemma refine_addCacheTo_BuildADT\n            (consSigs : list consSig)\n            (methSigs : list methSig)\n            (consDefs : ilist (@consDef rep) consSigs)\n            (methDefs : ilist (@methDef rep) methSigs) :\n    refineADT\n      (BuildADT consDefs methDefs)\n      (BuildADT (imap _ addCacheToConsDef consDefs)\n                (imap _ addCacheToMethDef methDefs)).\n  Proof.\n    generalize (refine_addCacheToADT\n                  cacheSpec\n                  (BuildADTSig consSigs methSigs)\n                  (fun idx => getConsDef consDefs idx)\n                  (fun idx => getMethDef methDefs idx)); eauto; intros.\n    econstructor; intros.\n    - simpl Constructors; rewrite <- ith_Bounded_imap.\n      apply refine_addCacheToConstructor.\n    - simpl Methods; rewrite <- ith_Bounded_imap.\n      apply refine_addCacheToMethod.\n  Qed.\n\nEnd addCache.\n\n(* Honing tactic for refining the ADT representation which provides\n   default method and constructor implementations. *)\n\nTactic Notation \"add\" \"cache\" \"with\" \"spec\" constr(cacheSpec') :=\n  eapply SharpenStep;\n  [eapply refine_addCacheTo_BuildADT with (cacheSpec := cacheSpec') |\n   compute [imap addCacheToConsDef addCacheToConstructor\n                 addCacheToMethDef addCacheToMethod]; simpl ].\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/BuildADTRefinements/AddCache.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.2631765570048666}}
{"text": "\nRequire Import VST.floyd.proofauto.\nRequire Import sll_copy.\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 sll_card : Set :=\n    | sll_card_0 : sll_card\n    | sll_card_1 : sll_card -> sll_card.\n\nFixpoint sll (x: val) (s: (list Z)) (self_card: sll_card) {struct self_card} : mpred := match self_card with\n    | sll_card_0  =>  !!((x : val) = nullval) && !!((s : list Z) = ([] : list Z)) && emp\n    | sll_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)) * (sll (nxt : val) (s1 : list Z) (_alpha_513 : sll_card))\nend.\n\n\nDefinition sll_copy_spec :=\n  DECLARE _sll_copy\n   WITH r: val, x: val, s: (list Z), a: sll_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)); (sll (x : val) (s : list Z) (a : sll_card)))\n   POST[ tvoid ]\n   EX y: val,\n   EX b: sll_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)); (sll (x : val) (s : list Z) (a : sll_card)); (sll (y : val) (s : list Z) (b : sll_card))).\n\nLemma sll_x_valid_pointerP x s self_card: sll x s self_card |-- valid_pointer x. Proof. destruct self_card; simpl; entailer;  entailer!; eauto. Qed.\nHint Resolve sll_x_valid_pointerP : valid_pointer.\nLemma sll_local_factsP x s self_card :\n  sll x s self_card|-- !!(((((x : val) = nullval)) -> (self_card = sll_card_0))/\\(((~ ((x : val) = nullval))) -> (exists _alpha_513, self_card = sll_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 sll_local_factsP : saturate_local.\nLemma unfold_sll_card_0  (x: val) (s: (list Z)) : sll x s (sll_card_0 ) =  !!((x : val) = nullval) && !!((s : list Z) = ([] : list Z)) && emp. Proof. auto. Qed.\nLemma unfold_sll_card_1 (_alpha_513 : sll_card) (x: val) (s: (list Z)) : sll x s (sll_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)) * (sll (nxt : val) (s1 : list Z) (_alpha_513 : sll_card)). Proof. auto. Qed.\nDefinition Gprog : funspecs :=\n  ltac:(with_library prog [sll_copy_spec; malloc_spec]).\n\nLemma body_sll_copy : semax_body Vprog Gprog f_sll_copy sll_copy_spec.\nProof.\nstart_function.\nssl_open_context.\nassert_PROP (isptr r). { entailer!. }\ntry rename x into x2.\nforward.\nforward_if.\n\n - {\nassert_PROP (a = sll_card_0) as ssl_card_assert. { entailer!; ssl_dispatch_card. }\nssl_card sll 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 (sll_card_0  : sll_card).\nssl_entailer.\nrewrite (unfold_sll_card_0 ) at 1.\nssl_entailer.\nrewrite (unfold_sll_card_0 ) at 1.\nssl_entailer.\n\n}\n - {\nassert_PROP (exists _alpha_513, a = sll_card_1 _alpha_513) as ssl_card_assert. { entailer!; ssl_dispatch_card. }\nssl_card sll 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 : sll_card)).\nlet ret := fresh vret in Intros ret; destruct ret as [y1 b1].\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 (sll_card_1 (b1 : sll_card) : sll_card).\nssl_entailer.\nrewrite (unfold_sll_card_1 (_alpha_513x2 : sll_card)) at 1.\nExists (vx22 : Z).\nExists (s1x2 : list Z).\nExists (nxtx22 : val).\nssl_entailer.\nrewrite (unfold_sll_card_1 (b1 : sll_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_sll_copy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2631429064391312}}
{"text": "Set Implicit Arguments.\nRequire Import Shared.\nRequire Import JsSyntax JsSyntaxAux JsSyntaxInfos JsCommon JsCommonAux JsPreliminary JsInit.\n\n(**************************************************************)\n(** ** Implicit Types -- copied from JsPreliminary *)\n\nImplicit Type b : bool.\nImplicit Type n : number.\nImplicit Type k : int.\nImplicit Type s : string.\nImplicit Type i : literal.\nImplicit Type l : object_loc.\nImplicit Type w : prim.\nImplicit Type v : value.\nImplicit Type r : ref.\nImplicit Type ty : type.\n\nImplicit Type rt : restype.\nImplicit Type rv : resvalue.\nImplicit Type lab : label.\nImplicit Type labs : label_set.\nImplicit Type R : res.\nImplicit Type o : out.\n\nImplicit Type x : prop_name.\nImplicit Type str : strictness_flag.\nImplicit Type m : mutability.\nImplicit Type Ad : attributes_data.\nImplicit Type Aa : attributes_accessor.\nImplicit Type A : attributes.\nImplicit Type Desc : descriptor.\nImplicit Type D : full_descriptor.\n\nImplicit Type L : env_loc.\nImplicit Type E : env_record.\nImplicit Type Ed : decl_env_record.\nImplicit Type X : lexical_env.\nImplicit Type O : object.\nImplicit Type S : state.\nImplicit Type C : execution_ctx.\nImplicit Type P : object_properties_type.\n\nImplicit Type e : expr.\nImplicit Type p : prog.\nImplicit Type t : stat.\n\nImplicit Type T : Type.\n\n\n(**************************************************************)\n(** ** Structure of This File *)\n\n(*\n  * Definitions of the datatypes used.\n  * Monadic constructors.\n*)\n\n\n(**************************************************************)\n(** ** Some types used by the interpreter *)\n\n(*\n  * [result_some] is the normal result when the computation terminates normally.\n  * [result_not_yet_implemented] means that this result is not implemented yet.\n  * [result_impossible] should not happen and is probably the result of a broken invariant.\n  * [result_bottom] means that the computation taked too long and we run out of fuel.\n*)\n\nInductive resultof T :=\n  | result_some : T -> resultof T\n  | result_not_yet_implemented\n  | result_impossible\n  | result_bottom : state -> resultof T.\n\n  (* We could put any information there.  They can be used to create step by step interpreter. *)\n\nImplicit Arguments result_some [[T]].\nImplicit Arguments result_not_yet_implemented [[T]].\nImplicit Arguments result_impossible [[T]].\nImplicit Arguments result_bottom [[T]].\n\n(* It can be useful to get details on why a stuck is obtained. *)\n(* The cases where [result_impossible] is directly used are the cases\n  where it has been proven impossible to get it under normal condition.\n  See [JsCorrectness.v] for more details. *)\n\nDefinition not_yet_implemented_because {T} s : resultof T := result_not_yet_implemented.\n\nDefinition impossible_because {T} s : resultof T := result_impossible.\n\nDefinition impossible_with_heap_because {T} S s : resultof T := result_impossible.\n\n(* Some special reduction rules does not return a usual triple (called [out] here), but a\n  special value.  The following type is there to encapsulate that. *)\n\nDefinition specres T := resultof (specret T).\n\nDefinition res_out T o : specres T :=\n  result_some (specret_out o).\nImplicit Arguments res_out [[T]].\n\nDefinition res_spec T S a : specres T :=\n  result_some (specret_val S a).\n\n(* [result] is the most common result type, returning an [out] each time. *)\n(* Note that this [out] does not necessarily (and hopefully rarely) aborts. *)\nInductive nothing : Type :=.\nDefinition retn := specret nothing.\nDefinition result := resultof retn.\nDefinition res_ter S R : result := res_out (out_ter S R).\n\nImplicit Type W : result.\n\n(* In the semantics, some rules returns an [out] which actually never\n  carries a result, only an [out_void] of something (or an error).  The\n  following type is there to differentiate those functions from the\n  others. *)\n(* It shall be replaced by a [specres unit]. *)\nDefinition result_void := result.\n\nDefinition res_void S : result_void := res_out (out_void S).\n\n(* Coercion *)\n\nCoercion result_some_out o : resultof out := result_some o.\n\nDefinition out_from_retn (sp : retn) : out :=\n  match sp with\n  | specret_val _ n => nothing_rect _ n\n  | specret_out o => o\n  end.\n\nCoercion out_retn o : retn := specret_out o.\nCoercion result_out o : result := res_out o.\n\nCoercion res_to_res_void (W : result) : result_void := W.\n\n(* Inhabited *)\n\nGlobal Instance result_inhab : forall T, Inhab (resultof T).\nProof. introv. applys prove_Inhab @impossible_because. exact \"Resultof is inhabited\". Qed.\n\n\n(**************************************************************)\n(** ** Helper functions for the interpreter *)\n\nSection InterpreterEliminations.\n\n(**************************************************************)\n(** Generic constructions *)\n\nDefinition get_arg := nth_def undef.\n\nDefinition get_arg_first_and_rest (lv : list value) :=\n (get_arg 0 lv, match lv with\n                 | nil => nil\n                 | _ :: rest => rest\n                end).        \n\nDefinition destr_list (A B : Type) (l : list A) (d : B) f :=\n  match l with\n  | nil => d\n  | cons a _ => f a\n  end.\n\n\n(**************************************************************)\n(** Monadic Constructors *)\n\nDefinition if_empty_label T S R (K : unit -> resultof T) : resultof T :=\n  ifb res_label R = label_empty then K tt\n  else\n    impossible_with_heap_because S \"[if_empty_label] received a normal result with non-empty label.\".\n\nDefinition if_some (A B : Type) (op : option A) (K : A -> resultof B) : resultof B :=\n  match op with\n  | None => impossible_because \"[if_some] called with [None].\"\n  | Some a => K a\n  end.\n\nDefinition if_some_or_default (A B : Type) (o : option B) (d : A) (K : B -> A) : A :=\n  option_case d K o.\n\nDefinition if_result_some (A B : Type) (W : resultof A) (K : A -> resultof B) : resultof B :=\n  match W with\n  | result_some a => K a\n  | result_not_yet_implemented => result_not_yet_implemented\n  | result_impossible => result_impossible\n  | result_bottom S0 => result_bottom S0\n  end.\n\nDefinition if_out_some T W (K : out -> resultof T) : resultof T :=\n  if_result_some W (fun sp => K (out_from_retn sp)).\n\nDefinition throw_result T W : specres T := (* Returns a [res_out], formatted into a [specres T]. *)\n  if_out_some W (fun o => res_out o).\n\nDefinition if_ter T W (K : state -> res -> specres T) : specres T :=\n  if_out_some W (fun o =>\n    match o with\n    | out_ter S0 R => K S0 R\n    | _ => res_out o\n    end).\n\nDefinition if_success_state rv W (K : state -> resvalue -> result) : result :=\n  if_ter W (fun S0 R =>\n    match res_type R with\n    | restype_normal =>\n      if_empty_label S0 R (fun _ =>\n        K S0 (ifb res_value R = resvalue_empty then rv else res_value R))\n    | restype_throw => res_ter S0 R\n    | _ =>\n      res_ter S0 (res_overwrite_value_if_empty rv R)\n    end).\n\nDefinition if_success T W (K : state -> resvalue -> specres T) : specres T :=\n  if_ter W (fun S0 R =>\n    match res_type R with\n    | restype_normal =>\n      if_empty_label S0 R (fun _ =>\n        K S0 (res_value R))\n    | _ =>\n      res_out (out_ter S0 R)\n    end).\n\nDefinition if_void (W : result_void) (K : state -> result) : result :=\n  if_success W (fun S rv =>\n    match rv with\n    | resvalue_empty => K S\n    | _ =>\n      impossible_with_heap_because S \"[if_void called] with non-void result value.\"\n    end).\n\nDefinition if_not_throw W (K : state -> res -> result) : result :=\n  if_ter W (fun S0 R =>\n    match res_type R with\n    | restype_throw => W\n    | _ => K S0 R\n    end).\n\nDefinition if_any_or_throw W (K1 : state -> res -> result)\n    (K2 : state -> value -> result) : result :=\n  if_ter W (fun S R =>\n    match res_type R with\n    | restype_throw =>\n      match res_value R with\n      | resvalue_value v =>\n        if_empty_label S R (fun _ =>\n          K2 S v)\n      | _ =>\n        impossible_with_heap_because S \"[if_any_or_throw] called with a non-value result.\"\n      end\n    | _ => K1 S R\n    end).\n\nDefinition if_success_or_return W (K1 : state -> result) (K2 : state -> resvalue -> result) : result :=\n  if_ter W (fun S R =>\n    match res_type R with\n    | restype_normal =>\n      if_empty_label S R (fun _ => K1 S)\n    | restype_return =>\n      if_empty_label S R (fun _ => K2 S (res_value R))\n    | _ => W\n    end).\n\nDefinition if_break W (K : state -> res -> result) : result :=\n  if_ter W (fun S R =>\n    match res_type R with\n    | restype_break => K S R\n    | _ => res_ter S R\n    end).\n\nDefinition if_value T W (K : state -> value -> specres T) : specres T :=\n  if_success W (fun S rv =>\n    match rv with\n    | resvalue_value v => K S v\n    | _ =>\n      impossible_with_heap_because S \"[if_value] called with non-value.\"\n    end).\n\nDefinition if_bool T W (K : state -> bool -> specres T) : specres T :=\n  if_value W (fun S v =>\n    match v with\n    | prim_bool b => K S b\n    | _ =>\n      impossible_with_heap_because S \"[if_bool] called with non-boolean value.\"\n    end).\n\nDefinition if_object T W (K : state -> object_loc -> specres T) : specres T :=\n  if_value W (fun S v =>\n    match v with\n    | value_object l => K S l\n    | value_prim _ =>\n      impossible_with_heap_because S \"[if_object] called on a primitive.\"\n    end).\n\nDefinition if_string T W (K : state -> string -> specres T) : specres T :=\n  if_value W (fun S v =>\n    match v with\n    | prim_string s => K S s\n    | _ =>\n      impossible_with_heap_because S \"[if_string] called on a non-string value.\"\n    end).\n\nDefinition if_number T W (K : state -> number -> specres T) : specres T :=\n  if_value W (fun S v =>\n    match v with\n    | prim_number n => K S n\n    | _ =>\n      impossible_with_heap_because S \"[if_number] called with non-number value.\"\n    end).\n\nDefinition if_prim T W (K : state -> prim -> specres T) : specres T :=\n  if_value W (fun S v =>\n    match v with\n    | value_prim w => K S w\n    | value_object _ =>\n      impossible_with_heap_because S \"[if_primitive] called on an object.\"\n    end).\n\nDefinition convert_option_attributes : option attributes -> option full_descriptor :=\n  LibOption.map (fun A => A : full_descriptor).\n\nDefinition if_abort (T:Type) o (K : unit -> resultof T) : resultof T :=\n  match o with\n  | out_ter S0 R =>\n    ifb res_type R = restype_normal then\n      impossible_with_heap_because S0 \"[if_abort] received a normal result!\"\n    else K tt\n  | _ => K tt\n  end.\n\nDefinition if_spec (A B : Type) (W : specres A) (K : state -> A -> specres B) : specres B :=\n  if_result_some W (fun sp =>\n    match sp with\n    | specret_val S0 a => K S0 a\n    | specret_out o =>\n      if_abort o (fun _ =>\n        res_out o)\n    end).\n\nEnd InterpreterEliminations.\nImplicit Arguments throw_result [[T]].\n\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/JsInterpreterMonads.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.26314290643913113}}
{"text": "(* Author: Masaki Hara, 2014 *)\n(* Linear Logic Toy for Coq *)\nRequire Import LWeight.\n\n(*************************************************)\n(*        Definition of Linear Type              *)\n(*************************************************)\n\nDelimit Scope LL_scope with LL.\nReserved Notation \"A '-o' B\"\n  (at level 99, right associativity, B at level 200).\nReserved Notation \"A 'o-o' B\"\n  (at level 95, no associativity).\nReserved Notation \"! A\"\n  (at level 30).\nReserved Notation \"'lforall' x .. y , p\"\n  (at level 200, x binder, right associativity,\n   format \"'[' 'lforall'  '/  ' x  ..  y ,  '/  ' p ']'\").\nReserved Notation \"'lexists' x .. y , p\"\n  (at level 200, x binder, right associativity,\n   format \"'[' 'lexists'  '/  ' x  ..  y ,  '/  ' p ']'\").\n\n\nRecord LType{E:LEnv} := {\n  ltype : Type;\n  lweight : ltype -> @LWeight E\n}.\nArguments LType [E].\nArguments Build_LType [E] _ _.\nArguments ltype [E] _%LL.\nArguments lweight [E] [_] _.\n\nCoercion lweight : ltype >-> LWeight.\n\n(* Linear Implication *)\nRecord LFun{E:LEnv} (A B:LType) := {\n  lfun_val : ltype A -> ltype B;\n  lfun_weight : @LWeight E;\n  lfun_weight_eqn :\n    forall x : ltype A,\n      (lfun_weight + lweight x = lweight (lfun_val x))%LWeight\n}.\nArguments LFun [E] A B.\nArguments Build_LFun [E] [A] [B] _ _ _.\nArguments lfun_val [E] [A] [B] _ _.\nArguments lfun_weight [E] [A] [B] _.\nArguments lfun_weight_eqn [E] [A] [B] _ _.\n\nDefinition LImpl{E:LEnv} (A B:LType):LType := {|\n  ltype := LFun A B;\n  lweight := @lfun_weight _ _ _\n|}.\nNotation \"A -o B\" := (LImpl A%LL B%LL) : LL_scope.\nCoercion lfun_val : LFun >-> Funclass.\n\nInstance LImpl_weight_decompose{E:LEnv} (A B:LType)\n    (f : ltype (A -o B)) (x : ltype A)\n    : LWeightCastPlus (lweight (f x)) (lweight f) (lweight x).\nProof.\n  rewrite <-lfun_weight_eqn.\n  auto with typeclass_instances.\nDefined.\n", "meta": {"author": "qnighy", "repo": "LType-Coq", "sha": "dec99f40020271aab5d95daf56acae8ff231aa58", "save_path": "github-repos/coq/qnighy-LType-Coq", "path": "github-repos/coq/qnighy-LType-Coq/LType-Coq-dec99f40020271aab5d95daf56acae8ff231aa58/LType_base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.26314290643913113}}
{"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 cequiv.\n\n\n(* !!MOVE *)\nLemma not_value_like_approx_bot {o} :\n  forall lib (a : @NTerm o),\n    hasvalue_like lib a -> !approx lib a mk_bot.\nProof.\n  introv hv ap.\n  inversion ap as [cc]; subst.\n  unfold close_comput in cc; repnd.\n  unfold hasvalue_like, isvalue_like in hv; exrepnd.\n  repndors.\n\n  - apply iscan_implies in hv0; repndors; exrepnd; subst.\n\n    + pose proof (cc2 c bterms) as h.\n      autodimp h hyp.\n      { split; auto.\n        apply isvalue_iff; dands; auto.\n        apply reduces_to_preserves_program in hv1; auto. }\n      exrepnd.\n      unfold computes_to_value in h1; repnd.\n      apply not_bot_reduces_to_is_value_like in h2; eauto 3 with slow.\n\n    + apply cc4 in hv1; exrepnd.\n      apply not_bot_reduces_to_value_like in hv1; eauto 3 with slow.\n\n  - apply isexc_implies2 in hv0; exrepnd; subst.\n    applydup @reduces_to_preserves_program in hv1; auto.\n    apply isprogram_exception_implies in hv0; exrepnd; subst; fold_terms.\n\n    pose proof (cc3 a0 t) as h.\n    autodimp h hyp.\n    exrepnd.\n    apply not_bot_reduces_to_is_value_like in h0; eauto 3 with slow.\nQed.\n\nLemma not_value_like_approxc_bot {o} :\n  forall lib (a : @CTerm o),\n    hasvalue_likec lib a -> !approxc lib a mkc_bot.\nProof.\n  unfold approxc, hasvalue_likec; introv; destruct_cterms; simpl.\n  apply not_value_like_approx_bot.\nQed.\n\nLemma approxc_alphaeqc_r {o} :\n  forall lib (a b c : @CTerm o),\n    approxc lib a b\n    -> alphaeqc b c\n    -> approxc lib a c.\nProof.\n  introv apr aeq.\n  destruct_cterms; allunfold @approxc; allunfold @alphaeqc; allsimpl.\n  eapply approx_alpha_rw_r_aux;[|exact apr]; auto.\nQed.\n\nLemma approxc_alphaeqc_l {o} :\n  forall lib (a b c : @CTerm o),\n    alphaeqc a b\n    -> approxc lib b c\n    -> approxc lib a c.\nProof.\n  introv aeq apr.\n  destruct_cterms; allunfold @approxc; allunfold @alphaeqc; allsimpl.\n  eapply approx_alpha_rw_l_aux;[|exact apr]; eauto 3 with slow.\nQed.\n\nLemma hasvalue_like_exc {o} :\n  forall lib (a b : @NTerm o),\n    hasvalue_like lib (mk_exception a b).\nProof.\n  introv.\n  unfold hasvalue_like.\n  exists (mk_exception a b); dands; eauto 3 with slow.\nQed.\nHint Resolve hasvalue_like_exc : slow.\n\nLemma hasvalue_likec_exc {o} :\n  forall lib (a b : @CTerm o),\n    hasvalue_likec lib (mkc_exception a b).\nProof.\n  introv; destruct_cterms; unfold hasvalue_likec; simpl; eauto 3 with slow.\nQed.\nHint Resolve hasvalue_likec_exc : slow.\n\nLemma approxc_decomp_axiom0 {o} :\n  forall lib (a : @CTerm o),\n    approxc lib mkc_axiom a\n    <=> computes_to_valc lib a mkc_axiom.\nProof.\n  introv; destruct_cterms; unfold approxc, computes_to_valc; simpl.\n  rw @approx_decomp_axiom0.\n  split; intro h; repnd; dands; eauto 3 with slow.\nQed.\n\nLemma computes_to_valc_exception {o} :\n  forall lib (a e v : @CTerm o),\n    computes_to_valc lib (mkc_exception a e) v -> False.\nProof.\n  introv comp.\n  destruct_cterms; unfold computes_to_valc in comp; allsimpl.\n  apply computes_to_value_exception in comp; sp.\nQed.\n\n(* !!MOVE *)\nLemma approxc_exc_implies_ex {o} :\n  forall lib (n e t : @CTerm o),\n    approxc lib (mkc_exception n e) t\n    -> {a : CTerm\n        & {b : CTerm\n        & reduces_toc lib t (mkc_exception a b)}}.\nProof.\n  introv apr.\n  destruct_cterms.\n  unfold approxc in apr; allsimpl.\n  inversion apr as [cl]; clear apr.\n  unfold close_comput in cl; repnd.\n  pose proof (cl3 x1 x0) as h.\n  autodimp h hyp.\n  { apply reduces_to_symm. }\n  exrepnd.\n  applydup @reduces_to_preserves_program in h0; eauto 3 with slow.\n  allrw @isprogram_exception_iff; repnd.\n  exists (mk_cterm a' h4) (mk_cterm e' h3).\n  unfold reduces_toc; simpl; auto.\nQed.\n\nLemma cover_vars_exception {o} :\n  forall (t u : @NTerm o) s,\n    cover_vars (mk_exception t u) s <=> (cover_vars t s # cover_vars u s).\nProof.\n  introv.\n  allrw @cover_vars_eq.\n  simpl.\n  allrw remove_nvars_nil_l; allrw app_nil_r.\n  allrw subvars_app_l; 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/approx_props2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.26314289963233173}}
{"text": "Require Import\n  Coq.Program.Program\n  Coq.Unicode.Utf8\n  Coq.micromega.Lia\n  Coq.Classes.Morphisms\n  Coq.Relations.Relation_Definitions\n  Coq.Strings.String\n  Coq.Vectors.Vector\n  Coq.Lists.List\n  Coq.Sets.Ensembles\n  Coq.Logic.EqdepFacts.\n\nFrom Equations Require Import Equations.\nRequire Import Equations.Type.EqDec.\nSet Equations With UIP.\n\nSet Universe Polymorphism.\n\nGeneralizable All Variables.\n\nImport ListNotations.\n\nDefinition stream (A : Type) : Type := nat → A.\n\nDefinition result_stream `(S : stream A) (B : A → Type) : Type :=\n  ∀ n : nat, B (S n).\n\nDefinition dep_stream (A : Type) (B : A → Type) : Type :=\n  ∀ S : stream A, result_stream S B.\n\nDefinition Schema : Type := list (string * Type).\n\nInductive Rec : Schema → Type :=\n  | Empty : Rec []\n  | Field name {ty S} : ty → Rec S → Rec ((name, ty) :: S).\n\n(* jww (2022-06-15): Keys are just unique names at the moment *)\nDefinition Table (S : Schema) : Type := list (string * Rec S).\n\nOpen Scope string_scope.\n\nExample same_record :\n  Rec [(\"foo\", nat : Type); (\"bar\", nat : Type); (\"baz\", nat : Type)].\nProof.\n  exact (Field \"foo\" (1 : nat)\n               (Field \"bar\" (2 : nat)\n                      (Field \"baz\" (3 : nat) Empty))).\nQed.\n\nDefinition Database : Type := list (string * { S : Schema & Table S }).\n\nSection Kadena.\n\nClass EqDec (A : Type) := {\n    eq_dec : ∀ x y : A, {x = y} + {x ≠ y}\n}.\n\nFixpoint lookup {k v : Type} `{EqDec k} (i : k) (l : list (k * v)) : option v :=\n  match l with\n  | [] => None\n  | (j, x) :: xs => if eq_dec i j then Some x else lookup i xs\n  end.\n\n(* At the moment all database operations are \"global\" and not constrained to\n   what the capabilities of the contract permit it to see. *)\nInductive Op : Type :=\n  | Noop\n  | Query {a : Type} (q : Database → a)\n  | Update (u : Database → Database).\n\nInductive Result : Op → Type :=\n  | Nothing : Result Noop\n  | Answer {a} {q : Database → a} : a → Result (Query q)\n  | Updated {u} : Result (Update u)\n  (* Any operation might result in an error. *)\n  | Error {o} (msg : string) : Result o.\n\nDefinition Kadena := dep_stream Op Result.\n\nDefinition Contract : Type := list Op * Op.\n\nDefinition Modules : Schema := [ (\"contract\", Contract) ].\n\nDefinition NoopContract : Contract := ([], Noop).\nDefinition NoopModule : Rec Modules := Field \"contract\" NoopContract Empty.\n\nProgram Definition Store : Database :=\n  [ (\"modules\", existT _ Modules [(\"noop\", NoopModule)]) ].\n\nDefinition kda : Kadena.\nProof.\n  repeat intro.\n  induction (S n); constructor.\n  apply q.\n  exact Store.\nDefined.\n\nFixpoint typeof {S : Schema} (r : Rec S) (field : string) : Type :=\n  match r with\n  | Empty => False\n  | @Field name ty _ _ xs =>\n      if name =? field then ty else typeof xs field\n  end.\n\nEquations get {S : Schema} (r : Rec S) (field : string) : typeof r field :=\n  get Empty _ := False_rect _ _;\n  get (Field name x xs) field := if name =? field then x else get xs field.\n\nProgram Definition call_noop_contract (k : Kadena) :=\n  k (λ n, if Nat.eqb n 0\n          then Update (λ _, Store) (* genesis *)\n          else Query (λ db, match lookup \"modules\" db with\n                            | Some (existT _ _ ms) =>\n                                match lookup \"noop\" ms with\n                                | Some r =>\n                                    get r \"contract\"\n                                | None => Error \"failed\"\n                                end\n                            | None => Error \"failed\"\n                            end)) 1.\n\nLemma call_noop_contract_correct :\n  call_noop_contract kda = Answer ().\nProof. reflexivity. Qed.\n\nEnd Kadena.\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/old/Db.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.26299195833427796}}
{"text": "Require Import Events.\nRequire Import TraceModel.\nRequire Import Properties.\nRequire Import CommonST.\nRequire Import Robustdef.\nRequire Import Setoid.\nRequire Import ClassicalExtras.\nRequire Import Logic.ClassicalFacts.\nRequire Import List.\nRequire Import TechnicalLemmas.\nRequire Import Criteria. \n\n(** This file proves that R2rSC can imply RTEP *)\n\n(* Definition two_rRSC : Prop := *)\n(*   forall (r : finpref -> finpref -> Prop) P1 P2 , *)\n(*     ((forall Cs m1 m2, psem (Cs [P1]) m1 -> *)\n(*                   psem (Cs [P2]) m2 -> *)\n(*                    r m1 m2) -> *)\n(*      (forall Ct m1 m2, psem (Ct [P1 ↓]) m1 -> *)\n(*                   psem (Ct [P2 ↓]) m2 -> *)\n(*                   r m1 m2)). *)\n\n\n(** *our assumptions *)\n(**********************************************************)\nHypothesis input_totality_tgt : input_totality tgt.\nHypothesis determinacy_src    : determinacy src.\nHypothesis tgt_sem            : semantics_safety_like tgt.\nHypothesis no_divergence : forall P' t, sem tgt P' t -> ~ diverges t.\n(**********************************************************)\n\nLemma three_continuations_tbd :\n  forall l t, prefix (ftbd l) t ->\n         ( (exists e, t = tstop l e) \\/\n                 (t = tsilent l) \\/\n            (exists e, prefix (ftbd (snoc l e)) t)).\nProof.\n  intros l [] Hpref.\n  + simpl in Hpref. apply list_proper_or_equal in Hpref. destruct Hpref.\n    ++ subst. left. now exists e.\n    ++ right. right. firstorder.  \n  + simpl in Hpref. apply list_proper_or_equal in Hpref. destruct Hpref.\n    ++ subst. right. now left.\n    ++ right. right. firstorder. \n  + generalize dependent s. induction l.\n    ++ right. right. destruct s. now exists e. \n    ++ intros [] Hpref. inversion Hpref. simpl.\n       destruct (IHl s) as [ [ef FALSE] | [ FALSE | [e0 HH] ]]; try now inversion FALSE; auto.\n       now simpl. right. right. exists e0; firstorder.  \nQed.\n\nDefinition myr ( m1 m2 : finpref) : Prop :=\n  (fpr m1 m2) \\/ (fpr m2 m1) \\/\n  (exists l i1 i2, is_input i1 /\\\n               is_input i2 /\\\n               i1 <> i2 /\\\n               fpr (ftbd (snoc l i1)) m1 /\\\n               fpr (ftbd (snoc l i2)) m2).\n\nLemma myr_symmetric : forall m1 m2, myr m1 m2 -> myr m2 m1.\nProof. firstorder. Qed. \n\n(* equivalent version of auXiliary_tstop.\n   ANON one might think to show myXr m1 m2 -> myr m1 m2  \n       and get a shorter proof. \n       Here we re-do the proof to have it independent from Xprefix.v \n*)\nLemma auxiliary_tstop :\n  forall m2 l1 e1 t2, prefix m2 t2 ->\n                  traces_match (tstop l1 e1) t2 -> myr (fstop l1 e1) m2.\nProof.\n  intros m2 l1 e1 t2 prefix2 [Heq | [ll [i1 [i2 [I1 [I2 [Idiff [l_prefix1 l_prefix2]]]]]]]].\n  + rewrite <- Heq in *. destruct (same_ext (fstop l1 e1) m2 (tstop l1 e1)); simpl; auto;\n                          [now left |  right; now left].\n  + destruct m2, t2; simpl in prefix2; simpl in l_prefix1, l_prefix2; try now auto.   \n    ++ inversion prefix2; subst.  \n       right. right. now exists ll, i1, i2.\n    ++ destruct (list_list_same_ext l (snoc ll i2) l0); auto.\n       * destruct (list_proper_or_equal _ _ H) as [HH | [a HH]].        \n         ** subst. right. right. now exists ll, i1, i2.\n         ** apply list_pref_snoc_pref in HH.\n            right. left. simpl. apply (list_list_prefix_trans l (snoc ll i1) l1);auto.\n            apply (list_list_prefix_trans l ll _); auto. now apply snoc_longer. \n       * right. right. now exists ll, i1, i2.  \n    ++ destruct (list_list_same_ext l (snoc ll i2) l0); auto.\n       * destruct (list_proper_or_equal _ _ H) as [HH | [a HH]].        \n         ** subst. right. right. now exists ll, i1, i2.\n         ** apply list_pref_snoc_pref in HH.\n            right. left. simpl. apply (list_list_prefix_trans l (snoc ll i1) l1);auto.\n            apply (list_list_prefix_trans l ll _); auto. now apply snoc_longer. \n       * right. right. now exists ll, i1, i2.\n    ++ destruct (list_stream_same_ext l (snoc ll i2) s); auto.\n       * destruct (list_proper_or_equal _ _ H) as [HH | [a HH]].        \n         ** subst. right. right. now exists ll, i1, i2.\n         ** apply list_pref_snoc_pref in HH.\n            right. left. simpl. apply (list_list_prefix_trans l (snoc ll i1) l1);auto.\n            apply (list_list_prefix_trans l ll _); auto. now apply snoc_longer. \n       * right. right. now exists ll, i1, i2.   \nQed. \n\nLemma auxiliary_ftbd:\n  forall l1 l2 t1 t2, prefix (ftbd l1) t1 -> prefix (ftbd l2) t2 ->\n                  traces_match t1 t2 -> myr (ftbd l1) (ftbd l2).\nProof.\n  intros l1 l2 t1 t2 pref1 pref2 [Heq | [ll [i1 [i2 [I1 [I2 [Idiff [l_prefix1 l_prefix2]]]]]]]].\n  + subst. destruct (same_ext (ftbd l1) (ftbd l2) t2); auto; [now left | right; now left]. \n  + assert (H1: prefix (ftbd (snoc ll i1)) t1).\n    { destruct t1; simpl in *; now auto. }\n    assert (H2 : prefix (ftbd (snoc ll i2)) t2).\n    { destruct t2; simpl in *; now auto. }\n    destruct (same_ext (ftbd l1) (ftbd (snoc ll i1)) t1) as [l1_shorter | l1_longer]; auto. \n    ++ destruct (same_ext (ftbd l2) (ftbd (snoc ll i2)) t2) as [l2_shorter | l2_longer]; auto.\n       destruct (list_proper_or_equal _ _ l1_shorter) as [l1_ll | [a1 l1_ll]]; subst.\n       * destruct (list_proper_or_equal _ _ l2_shorter) as [l2_ll | [a2 l2_ll]]; subst. \n          ** right. right. now exists ll, i1, i2. \n          ** apply list_pref_snoc_pref in l2_ll. right. left. simpl.\n             apply (list_list_prefix_trans l2 ll _); auto. now apply snoc_longer.  \n       * apply list_pref_snoc_pref in l1_ll.\n         destruct (list_proper_or_equal _ _ l2_shorter) as [l2_ll | [a2 l2_ll]]; subst. \n         **  left. simpl. apply (list_list_prefix_trans l1 ll _ ); auto. now apply snoc_longer.  \n         ** apply list_pref_snoc_pref in l2_ll. destruct (list_list_same_ext l1 l2 ll); auto;\n                                                  [now left | right; now left].  \n       * destruct (list_proper_or_equal  _ _ l1_shorter); auto; subst. \n         ** right. right. now exists ll, i1, i2.  \n         ** destruct H as [a H]. apply list_pref_snoc_pref in H. left.\n            simpl. apply (list_list_prefix_trans l1 ll l2); auto.\n            simpl in l2_longer. apply (list_list_prefix_trans ll (snoc ll i2) l2); auto.\n            now apply snoc_longer.  \n    ++ destruct (same_ext (ftbd l2) (ftbd (snoc ll i2)) t2) as [l2_shorter | l2_longer]; auto.\n       * destruct (list_proper_or_equal _ _ l2_shorter) as [l2_ll | [a2 l2_ll]]; subst. \n          ** right. right. now exists ll, i1, i2. \n          ** apply list_pref_snoc_pref in l2_ll. right. left. simpl.\n             apply (list_list_prefix_trans l2 ll _); auto.\n             apply (list_list_prefix_trans ll (snoc ll i1) _); auto. now apply snoc_longer.\n        * right. right. now exists ll, i1, i2.\nQed.   \n    \n\nLemma auxiliary_lemma (t1 t2 : trace) :\n  traces_match t1 t2 ->\n  forall m1 m2, prefix m1 t1 -> prefix m2 t2 -> myr m1 m2.\nProof.\n  intros [Heq | [ll [i1 [i2 [I1 [I2 [Idiff [l_prefix1 l_prefix2]]]]]]]] m1 m2 prefix1 prefix2. \n  - subst. unfold myr. destruct (same_ext m1 m2 t2) as [go_left | go_right_left]; auto. \n  - destruct m1, m2.\n    ++ destruct t1, t2; inversion prefix1; inversion prefix2; subst.\n       right. right. now exists ll, i1, i2.\n    ++ destruct t1; inversion prefix1; subst.  \n       apply (auxiliary_tstop (ftbd l0) l1 e t2); auto.\n       right. now exists ll, i1, i2. \n    ++ destruct t2; inversion prefix2; subst. apply myr_symmetric. \n       apply (auxiliary_tstop (ftbd l) l1 e t1); auto.\n       right. exists ll, i2, i1. repeat (split; try now auto). \n    ++ apply (auxiliary_ftbd l l0 t1 t2); auto. right. now exists ll, i1, i2.  \nQed. \n  \nLemma teq_premises_myXr_holds : forall P1 P2,\n    (forall Cs t, sem src (Cs [P1]) t <-> sem src (Cs [P2]) t) ->\n    (forall Cs m1 m2, psem (Cs [P1]) m1 -> psem (Cs [P2]) m2 ->\n                 myr m1 m2).\nProof.\n  intros P1 P2 H Cs m1 m2 [t1 [pref1 sem1]] [t2 [pref2 sem2]].\n    rewrite (H Cs t1) in sem1.\n   specialize (determinacy_src (Cs[P2]) t1 t2 sem1 sem2). \n   intros Hmatch. now apply (auxiliary_lemma t1 t2).\nQed.\n    \n\nLemma input_tot_consequence (W : prg tgt): forall l i1 i2,\n    is_input i1 -> is_input i2 -> \n    psem W (ftbd (snoc l i1)) -> psem W (ftbd (snoc l i2)).\nProof.\n  intros l i1 i2 Hi1 Hi2 [t [pref_x_t Hsemt]].\n  assert (psem W (ftbd  (snoc l i1))).\n  { simpl in *. now exists t. }\n  now apply (input_totality_tgt W l i1 i2) in H.\nQed.  \n \nLemma t_being_tstop_leads_to_contra (W1 W2 : prg tgt) t l2 e2 \n                                    (sem1 : sem tgt W1 t) (sem2 : sem tgt W2 (tstop l2 e2))\n                                    (nsem12: ~ sem tgt W2 t)\n                                    (xpref_x_t : prefix (ftbd l2) t)\n  : \n    (forall m1 m2, psem W1 m1 -> psem W2 m2 -> myr m1 m2) -> False.\nProof.\n intros twoX. destruct t.\n - simpl in *. destruct (twoX (fstop l e) (fstop l2 e2))\n     as [xpr1 | [xpr2 | [xx [i1 [i2 [Hi1 [Hi2 [Hdiff [Hxpr1 Hxpr2]]]]]]]]].\n   now exists (tstop l e). now exists (tstop l2 e2).\n   + inversion xpr1; subst. contradiction.\n   + inversion xpr2; subst. contradiction.                                \n   + simpl in Hxpr1, Hxpr2.\n     apply (list_list_prefix_trans (snoc xx i2) l2 l Hxpr2) in xpref_x_t.   \n     destruct (list_list_same_ext (snoc xx i1) (snoc xx i2) l) as [F | F]; auto;\n       apply Hdiff; apply (list_snoc_diff xx _ _ ) in F; congruence.\n - now apply (no_divergence W1 (tsilent l)).  \n - simpl in xpref_x_t.\n   destruct (tgt_sem (tstream s) W2 nsem12) as [l [ebad [Hpsem [Hpref Hnpsem]]]]; auto. \n   simpl in Hpref.\n   destruct (twoX (ftbd (snoc l ebad)) (fstop l2 e2))\n     as [xpr1 | [xpr2 | [xx [i1 [i2 [Hi1 [Hi2 [Hdiff [Hxpr1 Hxpr2]]]]]]]]]; auto.  \n   now exists (tstream s). now exists (tstop l2 e2).\n   + simpl in xpr1. apply Hnpsem. now exists (tstop l2 e2).\n   + simpl in *.\n     apply (list_stream_prefix_trans _ _ s) in Hxpr1; auto.  \n     apply (list_stream_prefix_trans _ _ s) in Hxpr2; auto.  \n     destruct (list_stream_same_ext (snoc xx i1) (snoc xx i2) s) as [F | F]; auto;\n     apply Hdiff; apply (list_snoc_diff xx _ _) in F; congruence.         \nQed. \n \n\nLemma violates_xmax  (W1 W2 : prg tgt) t t2 l a aa\n                     (sem1 : sem tgt W1 t) (sem2 : sem tgt W2 t2)\n                     (nsem12: ~ sem tgt W2 t)\n                     (xpref_x_t : prefix (ftbd (snoc l aa)) t)\n                     (x_t2 : prefix (ftbd (snoc l a)) t2)\n                       \n  :\n    (forall m' : finpref, prefix m' t -> psem W2 m' -> fpr m' (ftbd l)) -> \n    (forall m1 m2, psem W1 m1 -> psem W2 m2 ->  myr m1 m2) -> False.\nProof.\n  intros xmax twoX.\n  assert (xsem1 : psem W1 (ftbd (snoc l aa))) by now exists t.\n  assert (xsem2 : psem W2 (ftbd (snoc l a))) by now exists t2.\n  specialize (twoX (ftbd (snoc l aa)) (ftbd (snoc l a)) xsem1 xsem2).\n  destruct twoX as [xpr1 | [xpr2 | matching]].\n  + simpl in xpr1. apply list_snoc_diff in xpr1. subst.\n    specialize (xmax (ftbd (snoc l a)) xpref_x_t xsem2).\n    simpl in xmax. now apply snoc_strictly_longer in xmax. \n  + simpl in xpr2. apply list_snoc_diff in xpr2. subst.\n    specialize (xmax (ftbd (snoc l aa)) xpref_x_t xsem2).\n    simpl in xmax. now apply snoc_strictly_longer in xmax. \n  + destruct matching as [xx [i1 [i2 [Hi1 [Hi2 [Hdiff_is [Hxpr1 Hxpr2 ]]]]]]].\n    simpl in Hxpr1, Hxpr2.  \n    apply (list_snoc_pointwise xx l i1 i2 aa a) in Hxpr2; auto.  \n    destruct Hxpr2 as [H1 H2]. subst.\n    apply (input_tot_consequence W2 l a aa) in xsem2; auto. \n    specialize (xmax (ftbd (snoc l aa)) xpref_x_t xsem2).\n    simpl in xmax. now apply snoc_strictly_longer in xmax. \nQed. \n\nTheorem R2rSP_RTEP : R2rSP -> RTEP.\nProof.\n  rewrite <- R2rSC_R2rSP. rewrite R2rSC_R2rSC'.\n  unfold R2rSC', RTEP.\n  intros twoX P1 P2 Hsrc Ct t.\n  specialize (twoX P1 P2 myr (teq_premises_myXr_holds P1 P2 Hsrc) Ct).\n  split. \n  + intros case1.\n    apply NNPP. intros t_not_sem2.\n    destruct (longest_in_psem tgt_sem (Ct [P2↓]) t t_not_sem2) as [x [xpref_x_t [xsem2_x x_max]]].\n    destruct xsem2_x as [t2 [x_t2 t2_sem2]].\n    destruct x.\n    ++ (* it can only be t2 '=' fstop p e = t *)\n       destruct t, t2; auto.\n       inversion xpref_x_t; inversion x_t2; subst; congruence.  \n    ++ destruct (three_continuations_tbd l t2 x_t2) as [t2stop | [t2silent | t2longer]].\n       +++ destruct t2stop as [e2 Ht2]. rewrite Ht2 in *. \n           now apply (t_being_tstop_leads_to_contra (Ct [P1↓]) (Ct [P2↓]) t l e2).\n       +++ rewrite t2silent in *. \n           now apply (no_divergence (Ct [P2↓]) (tsilent l)).         \n       +++ destruct t2longer as [a t2longer].\n           destruct (three_continuations_tbd l t xpref_x_t) as [ttstop | [ttsilent | ttlonger]].           - destruct ttstop as [e ttstop]. subst. \n             destruct (twoX (fstop l e) (ftbd (snoc l a))) as [xpr1 | [xpr2 | matching]]; auto.\n             now exists (tstop l e). now exists t2. \n             -- simpl in xpr2. now apply snoc_strictly_longer in xpr2. \n             -- destruct matching as [xx [i1 [i2 [Hi1 [Hi2 [Hdiff [Hxpr1 Hxpr2 ]]]]]]].\n                simpl in Hxpr1, Hxpr2. \n                apply (snocs_aux_lemma xx l i2 i1 a); congruence.       \n           - subst. now apply (no_divergence (Ct [P1↓]) (tsilent l)).\n           - destruct ttlonger as [aa ttlonger].\n             now apply (violates_xmax (Ct [P1↓]) (Ct [P2↓]) t t2 l a aa).              \n  + intros case2.\n    apply NNPP. intros t_not_sem1.\n    destruct (longest_in_psem tgt_sem (Ct [P1↓]) t t_not_sem1) as [x [xpref_x_t [xsem1_x x_max]]].\n    destruct xsem1_x as [t1 [x_t1 t1_sem1]].\n    assert (twoX' : forall m1 m2, psem (Ct [P2 ↓]) m1 -> psem (Ct [P1 ↓]) m2 -> myr m1 m2).\n    { intros x1 x2 H H0. apply myr_symmetric. now apply twoX. } \n    destruct x.\n    ++ (* it can only be t2 '=' fstop p e = t *)\n       destruct t, t1; auto.\n       inversion xpref_x_t; inversion x_t1; subst; congruence.  \n    ++ destruct (three_continuations_tbd l t1 x_t1) as [t1stop | [t1silent | t1longer]].\n       +++ destruct t1stop as [e1 Ht1]. rewrite Ht1 in *. \n           now apply (t_being_tstop_leads_to_contra (Ct [P2↓]) (Ct [P1↓]) t l e1).\n       +++ rewrite t1silent in *. \n           now apply (no_divergence (Ct [P1↓]) (tsilent l)).         \n       +++ destruct t1longer as [a t1longer].\n           destruct (three_continuations_tbd l t xpref_x_t) as [ttstop | [ttsilent | ttlonger]].\n           - destruct ttstop as [e ttstop]. subst. \n             destruct (twoX' (fstop l e) (ftbd (snoc l a))) as [xpr1 | [xpr2 | matching]]; auto.\n             now exists (tstop l e). now exists t1. \n             -- simpl in xpr2. now apply snoc_strictly_longer in xpr2. \n             -- destruct matching as [xx [i1 [i2 [Hi1 [Hi2 [Hdiff [Hxpr1 Hxpr2 ]]]]]]].\n                simpl in Hxpr1, Hxpr2. \n                apply (snocs_aux_lemma xx l i2 i1 a); congruence.       \n           - subst. now apply (no_divergence (Ct [P2↓]) (tsilent l)).\n           - destruct ttlonger as [aa ttlonger].\n             now apply (violates_xmax (Ct [P2↓]) (Ct [P1↓]) t t1 l a aa). \nQed.    ", "meta": {"author": "JourneyBeyondFullAbstraction", "repo": "Anonymous", "sha": "db63e973a889738ec3b20453c82307a2857b216b", "save_path": "github-repos/coq/JourneyBeyondFullAbstraction-Anonymous", "path": "github-repos/coq/JourneyBeyondFullAbstraction-Anonymous/Anonymous-db63e973a889738ec3b20453c82307a2857b216b/R2rSP_RTEP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.26299195833427796}}
{"text": "Set Warnings \"-funind-cannot-define-graph\".\nSet Warnings \"-funind\".\n\nRequire Import ssreflect.\nRequire Import Tweetnacl.Libs.Export.\nRequire Import Tweetnacl.Low.Get_abcdef.\nRequire Import Tweetnacl.Low.ScalarMult_gen_small.\nRequire Import Tweetnacl.Gen.AMZubSqSel_List.\nRequire Import Tweetnacl.Gen.ABCDEF.\nRequire Import Tweetnacl.Gen.abstract_fn_rev.\nSection ScalarRec.\n\nOpen Scope Z.\n\nContext {O : Ops (list Z) (list Z) id}.\nContext {OP : @Ops_List O}.\n\nLemma abstract_fn_Zlength : forall m p z a b c d e f x a' b' c' d' e' f',\n  0 <= m ->\n  Zlength a = 16 -> Zlength b = 16 -> Zlength c = 16 ->\n  Zlength d = 16 -> Zlength e = 16 -> Zlength f = 16 -> Zlength x = 16 ->\n  (a',b',c',d',e',f') = (abstract_fn_rev m p z a b c d e f x) -> \n  Zlength a' = 16 \n  /\\ Zlength b' = 16\n   /\\ Zlength c' = 16\n    /\\ Zlength d' = 16\n     /\\ Zlength e' = 16\n      /\\ Zlength f' = 16.\nProof.\n  intros m p z a b c d e f x a' b' c' d' e' f' Hm.\n  gen a' b' c' d' e' f'.\n  gen p z a b c d e f x.\n  gen m.\n  apply (natlike_ind (fun m => forall (p : ℤ) (z a b c d e f x a' b' c' d' e' f' : list ℤ),\nZlength a = 16 ->\nZlength b = 16 ->\nZlength c = 16 ->\nZlength d = 16 ->\nZlength e = 16 ->\nZlength f = 16 ->\nZlength x = 16 ->\n(a', b', c', d', e', f') = abstract_fn_rev m p z a b c d e f x ->\nZlength a' = 16 /\\ Zlength b' = 16 /\\ Zlength c' = 16 /\\ Zlength d' = 16 /\\ Zlength e' = 16 /\\ Zlength f' = 16)).\nmove=> p z a b c d e f x a' b' c' d' e' f'.\nmove=> Ha Hb Hc Hd He Hf Hx.\nrewrite abstract_fn_rev_equation Zle_imp_le_bool ; try omega.\ngo.\nmove=> m Hm IHm.\nmove=> p z a b c d e f x a' b' c' d' e' f'.\nmove=> Ha Hb Hc Hd He Hf Hx.\nchange (Z.succ m) with (m + 1).\nrewrite abstract_fn_rev_equation.\nreplace (m + 1 - 1) with m by omega.\nremember (abstract_fn_rev m p z a b c d e f x) as k.\ndestruct k as (((((a0,b0),c0),d0),e0),f0).\nreplace (m + 1 <=? 0) with false.\n2: symmetry ; apply Z.leb_gt ; omega.\nmove=> Heq;inversion Heq.\nassert(Ht:= IHm p z a b c d e f x a0 b0 c0 d0 e0 f0 Ha Hb Hc Hd He Hf Hx Heqk).\njauto_set.\napply fa_Zlength ; auto.\napply fb_Zlength ; auto.\napply fc_Zlength ; auto.\napply fd_Zlength ; auto.\napply fe_Zlength ; auto.\napply ff_Zlength ; auto.\nQed.\n\nLemma get_a_abstract_fn_Zlength : forall n p z a b c d e f x,\n  0 <= n ->\n  Zlength a = 16 -> Zlength b = 16 -> Zlength c = 16 ->\n  Zlength d = 16 -> Zlength e = 16 -> Zlength f = 16 -> Zlength x = 16 ->\n  Zlength (get_a (abstract_fn_rev n p z a b c d e f x)) = 16.\nProof. intros.\nassert(He: exists a' b' c' d' e' f', (a',b',c',d',e',f') = (abstract_fn_rev n p z a b c d e f x)).\n  remember (abstract_fn_rev n p z a b c d e f x) as k ; destruct k as (((((a0,b0),c0),d0),e0),f0).\n  do 6 eexists ; reflexivity.\ndestruct He as [a' [b' [c' [d' [e' [f' He]]]]]].\nassert(Ht := abstract_fn_Zlength n p z a b c d e f x a' b' c' d' e' f' H H0 H1 H2 H3 H4 H5 H6 He).\nrewrite -He; jauto_set; go.\nQed.\nLemma get_b_abstract_fn_Zlength : forall n p z a b c d e f x,\n  0 <= n ->\n  Zlength a = 16 -> Zlength b = 16 -> Zlength c = 16 ->\n  Zlength d = 16 -> Zlength e = 16 -> Zlength f = 16 -> Zlength x = 16 ->\n  Zlength (get_b (abstract_fn_rev n p z a b c d e f x)) = 16.\nProof. intros.\nassert(He: exists a' b' c' d' e' f', (a',b',c',d',e',f') = (abstract_fn_rev n p z a b c d e f x)).\n  remember (abstract_fn_rev n p z a b c d e f x) as k ; destruct k as (((((a0,b0),c0),d0),e0),f0).\n  do 6 eexists ; reflexivity.\ndestruct He as [a' [b' [c' [d' [e' [f' He]]]]]].\nassert(Ht := abstract_fn_Zlength n p z a b c d e f x a' b' c' d' e' f' H H0 H1 H2 H3 H4 H5 H6 He).\nrewrite -He; jauto_set; go.\nQed.\nLemma get_c_abstract_fn_Zlength : forall n p z a b c d e f x,\n  0 <= n ->\n  Zlength a = 16 -> Zlength b = 16 -> Zlength c = 16 ->\n  Zlength d = 16 -> Zlength e = 16 -> Zlength f = 16 -> Zlength x = 16 ->\n  Zlength (get_c (abstract_fn_rev n p z a b c d e f x)) = 16.\nProof. intros.\nassert(He: exists a' b' c' d' e' f', (a',b',c',d',e',f') = (abstract_fn_rev n p z a b c d e f x)).\n  remember (abstract_fn_rev n p z a b c d e f x) as k ; destruct k as (((((a0,b0),c0),d0),e0),f0).\n  do 6 eexists ; reflexivity.\ndestruct He as [a' [b' [c' [d' [e' [f' He]]]]]].\nassert(Ht := abstract_fn_Zlength n p z a b c d e f x a' b' c' d' e' f' H H0 H1 H2 H3 H4 H5 H6 He).\nrewrite -He; jauto_set; go.\nQed.\nLemma get_d_abstract_fn_Zlength : forall n p z a b c d e f x,\n  0 <= n ->\n  Zlength a = 16 -> Zlength b = 16 -> Zlength c = 16 ->\n  Zlength d = 16 -> Zlength e = 16 -> Zlength f = 16 -> Zlength x = 16 ->\n  Zlength (get_d (abstract_fn_rev n p z a b c d e f x)) = 16.\nProof. intros.\nassert(He: exists a' b' c' d' e' f', (a',b',c',d',e',f') = (abstract_fn_rev n p z a b c d e f x)).\n  remember (abstract_fn_rev n p z a b c d e f x) as k ; destruct k as (((((a0,b0),c0),d0),e0),f0).\n  do 6 eexists ; reflexivity.\ndestruct He as [a' [b' [c' [d' [e' [f' He]]]]]].\nassert(Ht := abstract_fn_Zlength n p z a b c d e f x a' b' c' d' e' f' H H0 H1 H2 H3 H4 H5 H6 He).\nrewrite -He; jauto_set; go.\nQed.\nLemma get_e_abstract_fn_Zlength : forall n p z a b c d e f x,\n  0 <= n ->\n  Zlength a = 16 -> Zlength b = 16 -> Zlength c = 16 ->\n  Zlength d = 16 -> Zlength e = 16 -> Zlength f = 16 -> Zlength x = 16 ->\n  Zlength (get_e (abstract_fn_rev n p z a b c d e f x)) = 16.\nProof. intros.\nassert(He: exists a' b' c' d' e' f', (a',b',c',d',e',f') = (abstract_fn_rev n p z a b c d e f x)).\n  remember (abstract_fn_rev n p z a b c d e f x) as k ; destruct k as (((((a0,b0),c0),d0),e0),f0).\n  do 6 eexists ; reflexivity.\ndestruct He as [a' [b' [c' [d' [e' [f' He]]]]]].\nassert(Ht := abstract_fn_Zlength n p z a b c d e f x a' b' c' d' e' f' H H0 H1 H2 H3 H4 H5 H6 He).\nrewrite -He; jauto_set; go.\nQed.\nLemma get_f_abstract_fn_Zlength : forall n p z a b c d e f x,\n  0 <= n ->\n  Zlength a = 16 -> Zlength b = 16 -> Zlength c = 16 ->\n  Zlength d = 16 -> Zlength e = 16 -> Zlength f = 16 -> Zlength x = 16 ->\n  Zlength (get_f (abstract_fn_rev n p z a b c d e f x)) = 16.\nProof. intros.\nassert(He: exists a' b' c' d' e' f', (a',b',c',d',e',f') = (abstract_fn_rev n p z a b c d e f x)).\n  remember (abstract_fn_rev n p z a b c d e f x) as k ; destruct k as (((((a0,b0),c0),d0),e0),f0).\n  do 6 eexists ; reflexivity.\ndestruct He as [a' [b' [c' [d' [e' [f' He]]]]]].\nassert(Ht := abstract_fn_Zlength n p z a b c d e f x a' b' c' d' e' f' H H0 H1 H2 H3 H4 H5 H6 He).\nrewrite -He; jauto_set; go.\nQed.\n\nLemma abstract_fn_rev_bound : forall n p z a b c d e f x a' b' c' d' e' f',\n  0 <= n ->\n  Zlength a = 16 ->\n  Zlength b = 16 ->\n  Zlength c = 16 ->\n  Zlength d = 16 ->\n  Zlength e = 16 ->\n  Zlength f = 16 ->\n  Zlength x = 16 ->\n    Forall (fun x => -38 <= x < 2^16 + 38) a ->\n    Forall (fun x => -38 <= x < 2^16 + 38) b ->\n    Forall (fun x => -38 <= x < 2^16 + 38) c ->\n    Forall (fun x => -38 <= x < 2^16 + 38) d ->\n    Forall (fun x => 0 <= x < 2^16) x ->\n    (a',b',c',d',e',f') = (abstract_fn_rev n p z a b c d e f x) -> \n    Forall (fun x => -38 <= x < 2^16 + 38) a'\n    /\\ Forall (fun x => -38 <= x < 2^16 + 38) b'\n    /\\ Forall (fun x => -38 <= x < 2^16 + 38) c'\n    /\\ Forall (fun x => -38 <= x < 2^16 + 38) d'.\nProof. intros m p z a b c d e f x a' b' c' d' e' f' Hm.\n  gen a' b' c' d' e' f'.\n  gen p z a b c d e f x.\n  gen m.\n  apply (natlike_ind (fun m => forall (p : ℤ) (z a b c d e f x a' b' c' d' e' f' : list ℤ),\nZlength a = 16 ->\nZlength b = 16 ->\nZlength c = 16 ->\nZlength d = 16 ->\nZlength e = 16 ->\nZlength f = 16 ->\nZlength x = 16 ->\nForall (fun x0 : ℤ => -38 <= x0 < 2 ^ 16 + 38) a ->\nForall (fun x0 : ℤ => -38 <= x0 < 2 ^ 16 + 38) b ->\nForall (fun x0 : ℤ => -38 <= x0 < 2 ^ 16 + 38) c ->\nForall (fun x0 : ℤ => -38 <= x0 < 2 ^ 16 + 38) d ->\nForall (fun x0 : ℤ => 0 <= x0 < 2 ^ 16) x ->\n(a', b', c', d', e', f') = abstract_fn_rev m p z a b c d e f x ->\nForall (fun x0 : ℤ => -38 <= x0 < 2 ^ 16 + 38) a' /\\\nForall (fun x0 : ℤ => -38 <= x0 < 2 ^ 16 + 38) b' /\\\nForall (fun x0 : ℤ => -38 <= x0 < 2 ^ 16 + 38) c' /\\ Forall (fun x0 : ℤ => -38 <= x0 < 2 ^ 16 + 38) d')).\nmove=> p z a b c d e f x a' b' c' d' e' f' (* Hn Hp Hnp*) Ha Hb Hc Hd He Hf Hx \nHaa Hbb Hcc Hdd Hxx.\nrewrite abstract_fn_rev_0 => Hh.\ninv Hh ; go.\nmove => m Hm IHm p z a b c d e f x a' b' c' d' e' f' (* Hn Hp Hnp*) Ha Hb Hc Hd He Hf Hx \nHaa Hbb Hcc Hdd Hxx.\nrewrite abstract_fn_rev_n. 2: omega.\nreplace (Z.succ m - 1) with m.\n2: omega.\nremember (abstract_fn_rev m p z a b c d e f x) as k.\ndestruct k as (((((a0,b0),c0),d0),e0),f0).\nremember (Getbit (p - m) z) as r.\nsimpl => Hh.\ninv Hh.\nassert(Ht:= IHm p z a b c d e f x a0 b0 c0 d0 e0 f0 Ha Hb Hc Hd He Hf Hx Haa Hbb Hcc Hdd Hxx Heqk) ; auto.\nassert(Htt := abstract_fn_Zlength m p z a b c d e f x a0 b0 c0 d0 e0 f0 Hm Ha Hb Hc Hd He Hf Hx Heqk).\njauto_set.\napply fa_bound ; go.\napply fb_bound ; go.\napply fc_bound ; go.\napply fd_bound ; go.\nQed.\n\n\nLemma get_a_abstract_fn_bound : forall n p z a b c d e f x,\n  0 <= n ->\n  Zlength a = 16 ->\n  Zlength b = 16 ->\n  Zlength c = 16 ->\n  Zlength d = 16 ->\n  Zlength e = 16 ->\n  Zlength f = 16 ->\n  Zlength x = 16 ->\n    Forall (fun x => -38 <= x < 2^16 + 38) a ->\n    Forall (fun x => -38 <= x < 2^16 + 38) b ->\n    Forall (fun x => -38 <= x < 2^16 + 38) c ->\n    Forall (fun x => -38 <= x < 2^16 + 38) d ->\n    Forall (fun x => 0 <= x < 2^16) x ->\n    Forall (fun x => -38 <= x < 2^16 + 38) (get_a (abstract_fn_rev n p z a b c d e f x)).\nProof.\nintros.\nassert(He: exists a' b' c' d' e' f', (a',b',c',d',e',f') = (abstract_fn_rev n p z a b c d e f x)).\n  remember (abstract_fn_rev n p z a b c d e f x) as k ; destruct k as (((((a0,b0),c0),d0),e0),f0).\n  do 6 eexists ; reflexivity.\ndestruct He as [a' [b' [c' [d' [e' [f' He]]]]]].\nassert(Ht := abstract_fn_rev_bound n p z a b c d e f x a' b' c' d' e' f' H H0 H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 He).\nrewrite -He; jauto_set; go.\nQed.\nLemma get_b_abstract_fn_bound : forall n p z a b c d e f x,\n  0 <= n ->\n  Zlength a = 16 ->\n  Zlength b = 16 ->\n  Zlength c = 16 ->\n  Zlength d = 16 ->\n  Zlength e = 16 ->\n  Zlength f = 16 ->\n  Zlength x = 16 ->\n    Forall (fun x => -38 <= x < 2^16 + 38) a ->\n    Forall (fun x => -38 <= x < 2^16 + 38) b ->\n    Forall (fun x => -38 <= x < 2^16 + 38) c ->\n    Forall (fun x => -38 <= x < 2^16 + 38) d ->\n    Forall (fun x => 0 <= x < 2^16) x ->\n    Forall (fun x => -38 <= x < 2^16 + 38) (get_b (abstract_fn_rev n p z a b c d e f x)).\nProof.\nintros.\nassert(He: exists a' b' c' d' e' f', (a',b',c',d',e',f') = (abstract_fn_rev n p z a b c d e f x)).\n  remember (abstract_fn_rev n p z a b c d e f x) as k ; destruct k as (((((a0,b0),c0),d0),e0),f0).\n  do 6 eexists ; reflexivity.\ndestruct He as [a' [b' [c' [d' [e' [f' He]]]]]].\nassert(Ht := abstract_fn_rev_bound n p z a b c d e f x a' b' c' d' e' f' H H0 H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 He).\nrewrite -He; jauto_set; go.\nQed.\nLemma get_c_abstract_fn_bound : forall n p z a b c d e f x,\n  0 <= n ->\n  Zlength a = 16 ->\n  Zlength b = 16 ->\n  Zlength c = 16 ->\n  Zlength d = 16 ->\n  Zlength e = 16 ->\n  Zlength f = 16 ->\n  Zlength x = 16 ->\n    Forall (fun x => -38 <= x < 2^16 + 38) a ->\n    Forall (fun x => -38 <= x < 2^16 + 38) b ->\n    Forall (fun x => -38 <= x < 2^16 + 38) c ->\n    Forall (fun x => -38 <= x < 2^16 + 38) d ->\n    Forall (fun x => 0 <= x < 2^16) x ->\n    Forall (fun x => -38 <= x < 2^16 + 38) (get_c (abstract_fn_rev n p z a b c d e f x)).\nProof.\nintros.\nassert(He: exists a' b' c' d' e' f', (a',b',c',d',e',f') = (abstract_fn_rev n p z a b c d e f x)).\n  remember (abstract_fn_rev n p z a b c d e f x) as k ; destruct k as (((((a0,b0),c0),d0),e0),f0).\n  do 6 eexists ; reflexivity.\ndestruct He as [a' [b' [c' [d' [e' [f' He]]]]]].\nassert(Ht := abstract_fn_rev_bound n p z a b c d e f x a' b' c' d' e' f' H H0 H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 He).\nrewrite -He; jauto_set; go.\nQed.\nLemma get_d_abstract_fn_bound : forall n p z a b c d e f x,\n  0 <= n ->\n  Zlength a = 16 ->\n  Zlength b = 16 ->\n  Zlength c = 16 ->\n  Zlength d = 16 ->\n  Zlength e = 16 ->\n  Zlength f = 16 ->\n  Zlength x = 16 ->\n    Forall (fun x => -38 <= x < 2^16 + 38) a ->\n    Forall (fun x => -38 <= x < 2^16 + 38) b ->\n    Forall (fun x => -38 <= x < 2^16 + 38) c ->\n    Forall (fun x => -38 <= x < 2^16 + 38) d ->\n    Forall (fun x => 0 <= x < 2^16) x ->\n    Forall (fun x => -38 <= x < 2^16 + 38) (get_d (abstract_fn_rev n p z a b c d e f x)).\nProof.\nintros.\nassert(He: exists a' b' c' d' e' f', (a',b',c',d',e',f') = (abstract_fn_rev n p z a b c d e f x)).\n  remember (abstract_fn_rev n p z a b c d e f x) as k ; destruct k as (((((a0,b0),c0),d0),e0),f0).\n  do 6 eexists ; reflexivity.\ndestruct He as [a' [b' [c' [d' [e' [f' He]]]]]].\nassert(Ht := abstract_fn_rev_bound n p z a b c d e f x a' b' c' d' e' f' H H0 H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 He).\nrewrite -He; jauto_set; go.\nQed.\n\nClose Scope Z.\n\nEnd ScalarRec.\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/proofs/spec/Low/ScalarMult_rev_fn_gen.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.26299195241612344}}
{"text": "(*  DEC 2.0 language specification.\n   Paolo Torrini  \n   Universite' de Lille - CRIStAL-CNRS\n*)\n\nRequire Import List.\nRequire Import Equality.\nRequire Import Eqdep.\nRequire Import PeanoNat.\nRequire Import Omega.\nRequire Import ProofIrrelevance.\n\nRequire Import AuxLibI1.\nRequire Import TypSpecI1. \nRequire Import ModTypI1. \nRequire Import LangSpecI1. \nRequire Import StaticSemI1.\nRequire Import DynamicSemI1.\nRequire Import WeakenI1.\nRequire Import UniqueTypI1.\nRequire Import DerivDynI1.\nRequire Import TransPrelimI1.\nRequire Import TSoundnessI1.\nRequire Import SReducI1.\nRequire Import DetermI1.\nRequire Import PreReflI1.\n\nImport ListNotations.\n\n\nModule Reflect (IdT: ModTyp) <: ModTyp.\n\nModule PreReflL := PreRefl IdT.\nExport PreReflL.\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\nOpen Scope type_scope.\n\n(*********************************************************************)\n\n\nDefinition ExpTrans3_def (fenv: funEnv) (k1: FEnvWT fenv) (n: nat) :=   \n   fun (ftenv: funTC) (tenv: valTC) (e: Exp) (t: VTyp) \n       (k: ExpTyping ftenv tenv e t) =>   \n          FEnvTyping fenv ftenv ->\n          valTC_Trans tenv ->\n          forall (n1: nat), n1 <= n -> W ->  \n                            (sVTyp t * W) * sigT (fun n2 => n2 <= n1).     \n\nDefinition PrmsTrans3_def (fenv: funEnv) (k1: FEnvWT fenv) (n: nat) :=   \n   fun (ftenv: funTC) (tenv: valTC) (ps: Prms) (pt: PTyp) \n       (k: PrmsTyping ftenv tenv ps pt) =>        \n          FEnvTyping fenv ftenv ->\n          valTC_Trans tenv ->\n          forall (n1: nat), n1 <= n -> W ->  \n                            (PTyp_TRN pt * W) * sigT (fun n2 => n2 <= n1). \n\n\nDefinition Trans_ExpTyping_mut3 (fenv: funEnv) (D: FEnvWT fenv) (n: nat) :=\n  ExpTyping_mut (ExpTrans3_def fenv D n) (PrmsTrans3_def fenv D n). \n\nDefinition Trans_PrmsTyping_mut3 (fenv: funEnv) (D: FEnvWT fenv) (n: nat) :=\n  PrmsTyping_mut (ExpTrans3_def fenv D n) (PrmsTrans3_def fenv D n).\n\n\nLemma ExpTrans_Val (fenv: funEnv) (D: FEnvWT fenv) (n: nat) : \n  forall (ftenv : funTC) (tenv : valTC) (v : Value) \n    (t : VTyp) (v0 : VTyping v t),\n  ExpTrans3_def fenv D n ftenv tenv (Val v) t (Val_Typing ftenv tenv v t v0).\n unfold ExpTrans3_def.\n intros.\n inversion v0; subst.\n split.\n exact (sValue v, X0).\n econstructor 1 with (x := n1).\n auto.\nDefined.\n\n(*********************************************************************)\n\n\n\nLemma ExpTrans_Var (fenv: funEnv) (D: FEnvWT fenv) (n: nat) :\n  forall (ftenv : funTC) (tenv : valTC) (x : StaticSemL.Id) \n    (t : VTyp) (i : IdTyping tenv x t),\n  ExpTrans3_def fenv D n ftenv tenv (Var x) t (Var_Typing ftenv tenv x t i).\n     unfold ExpTrans3_def.\n     intros.\n     eapply ExpDenI2_Var.\n     exact i.\n     exact X.\n     exact X0.\nDefined.\n\nLemma ExpTrans_BindN (fenv: funEnv) (D: FEnvWT fenv) (n: nat) :\n  forall (ftenv : funTC) (tenv : valTC) (e1 e2 : Exp) \n    (t1 t2 : VTyp) (e : ExpTyping ftenv tenv e1 t1),\n  ExpTrans3_def fenv D n ftenv tenv e1 t1 e ->\n  forall e0 : ExpTyping ftenv tenv e2 t2,\n  ExpTrans3_def fenv D n ftenv tenv e2 t2 e0 ->\n  ExpTrans3_def fenv D n ftenv tenv (BindN e1 e2) t2\n    (BindN_Typing ftenv tenv e1 e2 t1 t2 e e0).\n     unfold ExpTrans3_def.\n     intros.\n     rename X2 into X3.\n     rename X1 into X2.\n     rename H into X1.\n     rename H0 into H.\n     specialize (X X1 X2 n1 H X3).\n     destruct X as [p2 X].\n     destruct X as [n2 q2]. \n     destruct p2 as [sv2 s2].\n     assert (n2 <= n) as q3.\n(*     omega. *)\n     eapply le_trans with (m:=n1).\n     exact q2.\n     exact H.\n     specialize (X0 X1 X2 n2 q3 s2).\n     destruct X0 as [p3 X0].\n     destruct X0 as [n3 q4].\n     split.\n     exact p3.\n     econstructor 1 with (x:=n3).\n     (*     omega. *)\n     eapply le_trans with (m:=n2).\n     exact q4.\n     exact q2.\nDefined.\n\nLemma ExpTrans_BindS (fenv: funEnv) (D: FEnvWT fenv) (n: nat) :\n  forall (ftenv : funTC) (tenv tenv' : valTC) (x : StaticSemL.Id)\n    (e1 e2 : Exp) (t1 t2 : VTyp) (m : option VTyp) \n    (m0 : Maybe t1 m) (e : tenv' = (x, t1) :: tenv)\n    (e0 : ExpTyping ftenv tenv e1 t1),\n  ExpTrans3_def fenv D n ftenv tenv e1 t1 e0 ->\n  forall e3 : ExpTyping ftenv tenv' e2 t2,\n  ExpTrans3_def fenv D n ftenv tenv' e2 t2 e3 ->\n  ExpTrans3_def fenv D n ftenv tenv (BindS x m e1 e2) t2\n                (BindS_Typing ftenv tenv tenv' x e1 e2 t1 t2 m m0 e e0 e3).\n     unfold ExpTrans3_def.\n     intros.\n     rename X2 into X3.\n     rename X1 into X2.\n     rename H into X1.\n     rename H0 into H.\n     specialize (X X1 X2 n1 H X3).\n     destruct X as [p2 X].\n     destruct X as [n2 q2]. \n     destruct p2 as [sv1 s2].\n     assert (n2 <= n) as q3.\n(*     omega. *)\n     eapply le_trans with (m:=n1).\n     exact q2.\n     exact H.\n     inversion e; subst.\n     clear H0.     \n     unfold valTC_Trans in *.\n     specialize (X0 X1 (ext_senv tenv X2 x t1 sv1) n2 q3 s2).\n     destruct X0 as [p3 X0].\n     destruct X0 as [n3 q4].\n     split.\n     exact p3.\n     econstructor 1 with (x:=n3).\n     (*     omega. *)\n     eapply le_trans with (m:=n2).\n     exact q4.\n     exact q2.\nDefined.\n  \n\nLemma ExpTrans_BindMS (fenv: funEnv) (D: FEnvWT fenv) (n: nat) :\n  forall (ftenv : funTC) (tenv tenv0 tenv1 : valTC) \n    (env0 : valEnv) (e : Exp) (t : VTyp) (e0 : EnvTyping env0 tenv0)\n    (e1 : tenv1 = tenv0 ++ tenv) (e2 : ExpTyping ftenv tenv1 e t),\n  ExpTrans3_def fenv D n ftenv tenv1 e t e2 ->\n  ExpTrans3_def fenv D n ftenv tenv (BindMS env0 e) t\n    (BindMS_Typing ftenv tenv tenv0 tenv1 env0 e t e0 e1 e2).\n     unfold ExpTrans3_def.\n     intros.\n     rename X1 into X2.\n     rename X0 into X1.\n     rename H into X0.\n     rename H0 into H.\n     specialize (X X0). \n     inversion e1; subst.\n     clear H0.\n     eapply extend_valTC_Trans with (env0:=env0) (tenv0:=tenv0)\n                                    (tenv:= tenv) in e0.\n     specialize (X e0 n1 H X2).\n     exact X.\n     exact X1.\nDefined.     \n     \n\nLemma ExpTrans_IfThenElse (fenv: funEnv) (D: FEnvWT fenv) (n: nat) :\n  forall (ftenv : funTC) (tenv : valTC) (e1 e2 e3 : Exp) \n    (t : VTyp) (e : ExpTyping ftenv tenv e1 Bool),\n  ExpTrans3_def fenv D n ftenv tenv e1 Bool e ->\n  forall e0 : ExpTyping ftenv tenv e2 t,\n  ExpTrans3_def fenv D n ftenv tenv e2 t e0 ->\n  forall e4 : ExpTyping ftenv tenv e3 t,\n  ExpTrans3_def fenv D n ftenv tenv e3 t e4 ->\n  ExpTrans3_def fenv D n ftenv tenv (IfThenElse e1 e2 e3) t\n    (IfThenElse_Typing ftenv tenv e1 e2 e3 t e e0 e4).\n     unfold ExpTrans3_def.\n     intros.\n     rename X3 into X4.\n     rename X2 into X3.\n     rename H into X2.\n     rename H0 into H.\n     specialize (X X2 X3 n1 H X4).\n     destruct X as [p2 X].\n     destruct X as [n2 q2]. \n     destruct p2 as [sv1 s2].\n     assert (n2 <= n) as q3.\n     (* omega. *)\n     eapply le_trans.\n     exact q2.\n     exact H.\n     simpl in sv1.\n     destruct sv1.\n     specialize (X0 X2 X3 n2 q3 s2).\n     destruct X0 as [p3 X0].     \n     destruct X0 as [n3 q4].\n     split.\n     exact p3.\n     econstructor 1 with (x:=n3).\n     (* omega. *)\n     eapply le_trans.\n     exact q4.\n     exact q2.\n     specialize (X1 X2 X3 n2 q3 s2).\n     destruct X1 as [p3 X1].     \n     destruct X1 as [n3 q4].\n     split.\n     exact p3.\n     econstructor 1 with (x:=n3).\n     (* omega. *)\n     eapply le_trans.\n     exact q4.\n     exact q2.\nDefined.\n     \nLemma ExpTrans_Apply0 : \n  forall (fenv: funEnv) (D: FEnvWT fenv)\n         (ftenv : funTC) (tenv : valTC) (x : StaticSemL.Id) \n    (e : Exp) (ps : Prms) (pt : PTyp) (t : VTyp) (p : Pure e)\n    (i : IdFTyping ftenv x (FT pt t)) (p0 : PrmsTyping ftenv tenv ps pt),\n  PrmsTrans3_def fenv D 0 ftenv tenv ps pt p0 ->\n  forall e0 : ExpTyping ftenv tenv e Nat,\n  ExpTrans3_def fenv D 0 ftenv tenv e Nat e0 ->\n  ExpTrans3_def fenv D 0 ftenv tenv (Apply x ps e) t\n                (Apply_Typing ftenv tenv x e ps pt t p i p0 e0).\n     unfold ExpTrans3_def, PrmsTrans3_def.\n     intros.\n     rename X2 into X3.\n     rename X1 into X2.\n     rename H into X1.\n     rename H0 into H.\n     specialize (X0 X1 X2 n1 H X3).\n     destruct X0 as [p2 X0].\n     destruct X0 as [n2 q2]. \n     destruct p2 as [sv1 s2].\n     assert (n2 <= 0) as q3.\n     omega.\n     specialize (X X1 X2 n2 q3 s2).\n     destruct X as [p3 X].     \n     destruct X as [n3 q4].\n     inversion i; subst.\n     eapply (ExtRelVal2 funFTyp ftenv fenv x (FT pt t)) in H1.     \n     destruct H1 as [f H0 H1].\n     destruct f.\n     unfold funFTyp in H1.\n     destruct v.\n     destruct v.\n     simpl in *.\n     inversion H1; subst.\n     split.\n     exact (v,(snd p3)).  \n     econstructor 1 with (x:=n3).\n     omega.\n     exact X1.\nDefined.\n\n     \nLemma ExpTrans_Call0 : \n  forall (fenv: funEnv) (D: FEnvWT fenv)\n         (ftenv : funTC) (tenv : valTC) (x : StaticSemL.Id) \n    (ls : list Exp) (pt : PTyp) (t : VTyp) (i : IdFTyping ftenv x (FT pt t))\n    (p : PrmsTyping ftenv tenv (PS ls) pt),\n  PrmsTrans3_def fenv D 0 ftenv tenv (PS ls) pt p ->\n  ExpTrans3_def fenv D 0 ftenv tenv (Call x (PS ls)) t\n    (Call_Typing ftenv tenv x ls pt t i p).\n     unfold ExpTrans3_def, PrmsTrans3_def.\n     intros.\n     rename X1 into X2.\n     rename X0 into X1.\n     rename H into X0.\n     rename H0 into H.\n     specialize (X X0 X1 n1 H X2).\n     destruct X as [p3 X].     \n     destruct X as [n3 q4].\n     inversion i; subst.\n     eapply (ExtRelVal2 funFTyp ftenv fenv x (FT pt t)) in H1.     \n     destruct H1 as [f H0 H1].\n     destruct f.\n     unfold funFTyp in H1.\n     destruct v.\n     destruct v.\n     simpl in *.\n     inversion H1; subst.\n     split.\n     exact (v,(snd p3)).  \n     econstructor 1 with (x:=n3).\n     omega.\n     exact X0.\nDefined.\n\nLemma ExpTrans_Modify (fenv: funEnv) (D: FEnvWT fenv) (n: nat) :\n  forall (ftenv : funTC) (tenv : valTC) (t1 t2 : VTyp) \n    (XF : XFun t1 t2) (e : Exp) (e0 : ExpTyping ftenv tenv e t1),\n  ExpTrans3_def fenv D n ftenv tenv e t1 e0 ->\n  ExpTrans3_def fenv D n ftenv tenv (Modify t1 t2 XF e) t2\n    (Modify_Typing ftenv tenv t1 t2 XF e e0).\n     unfold ExpTrans3_def.\n     intros.\n     rename X1 into X2.\n     rename X0 into X1.\n     rename H into X0.\n     rename H0 into H.\n     specialize (X X0 X1 n1 H X2).\n     destruct X as [p3 X].     \n     destruct X as [n3 q4].\n     destruct p3 as [sv s3].\n     destruct XF.\n     set (x_mod0 sv s3) as p.\n     subst inpT0.\n     subst outT0.\n     split.\n     exact p.\n     econstructor 1 with (x:=n3).\n     (* omega. *)\n     assumption.\nDefined.     \n\n\nLemma ExpTrans_PrmsNil (fenv: funEnv) (D: FEnvWT fenv) (n: nat) :\n  forall (ftenv : funTC) (tenv : valTC),\n    PrmsTrans3_def fenv D n ftenv tenv (PS []) (PT [])\n                   (PSNil_Typing ftenv tenv).\n     unfold PrmsTrans3_def.\n     intros.\n     split.\n     split.\n     constructor.\n     exact X0.\n     econstructor 1 with (x:=n1).\n     auto.\nDefined.  \n\n\nLemma ExpTrans_Prms (fenv: funEnv) (D: FEnvWT fenv) (n: nat) :\n  forall (ftenv : funTC) (tenv : valTC) (e : Exp) (t : VTyp) \n    (es : list Exp) (ts : list VTyp) (e0 : ExpTyping ftenv tenv e t),\n  ExpTrans3_def fenv D n ftenv tenv e t e0 ->\n  forall p : PrmsTyping ftenv tenv (PS es) (PT ts),\n  PrmsTrans3_def fenv D n ftenv tenv (PS es) (PT ts) p ->\n  PrmsTrans3_def fenv D n ftenv tenv (PS (e :: es)) (PT (t :: ts))\n                 (PSCons_Typing ftenv tenv e t es ts e0 p).\n     unfold ExpTrans3_def, PrmsTrans3_def.\n     intros.\n     rename X2 into X3.\n     rename X1 into X2.\n     rename H into X1.\n     rename H0 into H.\n     specialize (X X1 X2 n1 H X3).\n     destruct X as [p2 X].\n     destruct X as [n2 q2]. \n     destruct p2 as [sv1 s2].\n     assert (n2 <= n) as q3.\n     eapply le_trans.\n     exact q2.\n     exact H.\n     (* omega *)\n     specialize (X0 X1 X2 n2 q3 s2).\n     destruct X0 as [p3 X0].\n     destruct p3 as [svs3 s3].\n     destruct X0 as [n3 q4].\n     split.\n     split.\n     constructor.\n     exact sv1.\n     exact svs3.\n     exact s3.\n     econstructor 1 with (x:=n3).\n     (* omega. *)\n     eapply le_trans.\n     exact q4.\n     exact q2.\nDefined.     \n     \n(*****************************************************************)\n\nLemma ExpTrans_ApplyE (fenv: funEnv) (D: FEnvWT fenv) (n : nat)\n (IHn : forall (ftenv : funTC) (tenv : valTC) (e : Exp) (t : VTyp),\n        ExpTyping ftenv tenv e t ->\n        FEnvTyping fenv ftenv ->\n        valTC_Trans tenv ->\n        forall n1 : nat, n1 <= n -> W -> sVTyp t * W * {n2 : nat & n2 <= n1}) :\n  forall (ftenv : funTC) (tenv : valTC) (x : StaticSemL.Id) \n    (e : Exp) (ps : Prms) (pt : PTyp) (t : VTyp) (p : Pure e)\n    (i : IdFTyping ftenv x (FT pt t)) (p0 : PrmsTyping ftenv tenv ps pt),\n  PrmsTrans3_def fenv D (S n) ftenv tenv ps pt p0 ->\n  forall e0 : ExpTyping ftenv tenv e Nat,\n  ExpTrans3_def fenv D (S n) ftenv tenv e Nat e0 ->\n  ExpTrans3_def fenv D (S n) ftenv tenv (Apply x ps e) t\n    (Apply_Typing ftenv tenv x e ps pt t p i p0 e0).\n     unfold ExpTrans3_def, PrmsTrans3_def.\n     intros.\n     rename X2 into X3.\n     rename X1 into X2.\n     rename H into X1.\n     rename H0 into H.     \n     specialize (X0 X1 X2 n1 H X3).\n     destruct X0 as [p2 X0].\n     destruct X0 as [n2 q2]. \n     destruct p2 as [sv1 s2].\n     assert (n2 <= S n) as q3.\n     omega.\n     specialize (X X1 X2 n2 q3 s2).\n     destruct X as [p3 X].\n     destruct p3 as [svs2 s3].\n     destruct X as [n3 q4].\n     \n     inversion i; subst.\n     eapply (ExtRelVal2 funFTyp ftenv fenv x (FT pt t)) in H1.     \n     destruct H1 as [f H0 H1].\n     generalize D.\n     intro k3.\n     unfold FEnvWT in D.\n     specialize (D ftenv X1 x f H0).\n     unfold FunWT in D.\n     destruct f.\n     unfold funFTyp in H1.\n     destruct v.\n     destruct v.\n     simpl in *.\n     inversion H1; subst.\n     clear H1.\n\n     assert (n3 <= S n) as q5.\n     omega.\n     \n     destruct n3.\n     assert (0 <= n) as q6.\n     omega.\n     \n     specialize (IHn ftenv tenv0 e1 t D X1 svs2 0 q6 s3).\n     destruct IHn as [p4 IH].\n     split.\n     exact p4.\n     destruct IH as [n5 IH].\n     econstructor 1 with (x:=n5).\n     omega.\n\n     assert (n3 <= n) as q6.\n     omega.\n     \n     specialize (IHn ftenv tenv0 e1 t D X1 svs2 n3 q6 s3).\n     destruct IHn as [p4 IH].\n     split.\n     exact p4.\n     destruct IH as [n5 IH].\n     econstructor 1 with (x:=n5).\n     omega.\n\n     exact X1.\nDefined.\n\n\nLemma ExpTrans_ApplyXXX (fenv: funEnv) (D: FEnvWT fenv) (n: nat)\n     (ftenv : funTC) (tenv tenv0 : valTC) (x : StaticSemL.Id)\n           (v: Value) (e: Exp)\n           (t : VTyp) (m: VTyping v t)\n      (i2 : findE fenv x = Some (FC tenv0 v e))     \n      (IHn : FEnvTyping fenv ftenv ->\n          valTC_Trans tenv0 ->\n          forall (n0 : nat),\n          n0 <= n -> W -> sVTyp t * W * {n1 : nat & n1 <= n0}) :\n    forall (e9 : Exp) (ls : list Exp) (pt : PTyp) (p9 : Pure e9)\n           (i1 : IdFTyping ftenv x (FT pt t))\n           (p : PrmsTyping ftenv tenv (PS ls) pt),\n      PrmsTrans3_def fenv D (S n) ftenv tenv (PS ls) pt p ->\n   forall m9 : ExpTyping ftenv tenv e9 Nat,\n   ExpTrans3_def fenv D (S n) ftenv tenv e9 Nat m9 ->\n   ExpTrans3_def fenv D (S n) ftenv tenv (Apply x (PS ls) e9) t\n                 (Apply_Typing ftenv tenv x e9 (PS ls) pt t p9 i1 p m9).\n    unfold ExpTrans3_def, PrmsTrans3_def.\n    intros e9 ls pt p9 i1 p.\n    intros X m9 Y H X0 n1 H0 X1.\n    specialize (Y H X0 n1 H0 X1).\n    \n    destruct Y as [pp9 Y].\n    destruct pp9 as [n10 s9].\n    destruct Y as [n9 q9].\n    simpl in *.\n\n    specialize (X H X0 n1 H0 X1).\n\n    destruct X as [p3 X].\n    destruct p3 as [svs2 s3].\n    destruct X as [n3 q4].\n    simpl in *.\n\n    set (f:=FC tenv0 v e).\n    set (ft:=FT pt t).\n    unfold VTyping in m.\n     \n    generalize i1.\n    intro i3.\n\n    assert (0 <= n1) as qq.\n    intuition.\n    \n    eapply (RelatedByEnv funFTyp fenv ftenv x f ft H i2) in i3.\n    \n    remember (min n3 n10) as n11.\n    \n    destruct n11.\n\n    split.\n    destruct v.\n    destruct v.\n    simpl in m.\n    inversion m; subst.\n    exact (v, s3).\n    econstructor 1 with (x:=0).\n    auto.\n    \n(* case S *)\n    assert (n3 <= S n) as q02a.\n    eapply le_trans.\n    exact q4.\n    exact H0.\n    assert (S n11 <= n3) as q02b.\n    rewrite Heqn11.\n    intuition.\n    assert (S n11 <= S n) as q02.\n    eapply le_trans.\n    exact q02b.\n    exact q02a.\n    assert (n11 <= n) as q2.\n    eapply (le_inject _ _ q02).\n\n    unfold PTyp_TRN in svs2.\n    destruct pt.\n    simpl in i3.\n    inversion i3; subst.\n    \n    specialize (IHn H svs2 n11 q2 s3).\n    \n    destruct IHn as [IH1 IH2].\n\n    split.\n    exact IH1.\n    destruct IH2 as [n4 IH2].\n\n    econstructor 1 with (x:=n4).\n    eapply le_trans.\n    exact IH2.\n    assert (n11 <= n3).\n    eapply (le_decrease _ _ q02b).\n    eapply le_trans.\n    exact H1.\n    exact q4.\nDefined.    \n\nLemma ExpTrans_ApplyX_aux4_0 (fenv: funEnv) (D: FEnvWT fenv) (* n: nat *)\n    (ftenv : funTC) (tenv tenv0 : valTC) (x : Id)\n    (v: Value) (e: Exp)\n    (t : VTyp) (m: valueVTyp v = t)\n    (i2 : findE fenv x = Some (FC tenv0 v e))\n  (e9 : Exp)\n  (ls : list Exp)\n  (pt : PTyp)\n  (i1 : IdFTyping ftenv x (FT pt t))\n  (p : PrmsTyping ftenv tenv (PS ls) pt)\n  (n1 : nat)\n  (svs2 : PTyp_TRN pt)\n  (s3 : W)\n  (n3: nat)\n  (q4 : n3 <= n1)\n  (m9 : ExpTyping ftenv tenv e9 Nat)\n  (n10 : nat)\n  (H : FEnvTyping fenv ftenv)\n  (X0 : valTC_Trans tenv)\n  (X1 : W)\n  (i3 : funFTyp (FC tenv0 v e) = FT pt t)\n  (Heqn11 : 0 = Init.Nat.min n3 n10)\n  :\n  sVTyp t * W * {n2 : nat & n2 <= n1}.\n    \n    split.\n    destruct v.\n    destruct v.\n    simpl in m.\n    inversion m; subst.\n    exact (v, s3).\n    econstructor 1 with (x:=0).\n    intuition.\nDefined.\n\nLemma ExpTrans_ApplyX_aux4 (fenv: funEnv) (D: FEnvWT fenv) (n: nat)\n    (ftenv : funTC) (tenv tenv0 : valTC) (x : Id)\n    (v: Value) (e: Exp)\n    (i2 : findE fenv x = Some (FC tenv0 v e))\n    (n11 : nat)\n    (IHn : sVTyp (valueVTyp v) * W * {n1 : nat & n1 <= n11})\n  (e9 : Exp)  \n  (ls : list Exp)\n  (p : PrmsTyping ftenv tenv (PS ls) (PT (map snd tenv0)))\n  (i : IdFTyping ftenv x (FT (PT (map snd tenv0)) (valueVTyp v)))\n  (n1 : nat)\n  (svs2 : tlist2type (PTyp_ListTrans (PT (map snd tenv0))))\n  (s3 : W)\n  (n3: nat)\n  (q4 : n3 <= n1)\n  (m9 : ExpTyping ftenv tenv e9 Nat)\n  (n10 : nat)\n  (s9 : W)\n  (n9 : nat)\n  (q9 : n9 <= n1)\n  (H : FEnvTyping fenv ftenv)\n  (X0 : valTC_Trans tenv)\n  (H0 : n1 <= S n)\n  (X1 : W)\n  (i3 : FT (PT (map snd tenv0)) (projT1 v) =\n        FT (PT (map snd tenv0)) (valueVTyp v))\n  (Heqn11 : S n11 = Init.Nat.min n3 n10)\n  (q02b : S n11 <= n3)\n  (H3 : projT1 v = valueVTyp v) :\n  sVTyp (projT1 v) * W * {n2 : nat & n2 <= n1}.    \n    \n    destruct IHn as [IH1 IH2].\n\n    split.\n    exact IH1.\n    destruct IH2 as [n4 IH2].\n\n    econstructor 1 with (x:=n4).\n    eapply le_trans.\n    exact IH2.\n    assert (n11 <= n3).\n    eapply (le_decrease _ _ q02b).\n    eapply le_trans.\n    exact H1.\n    exact q4.\nDefined.    \n\n    \nLemma ExpTrans_ApplyX_aux3 (fenv: funEnv) (D: FEnvWT fenv) (n: nat)\n    (ftenv : funTC) (tenv tenv0 : valTC) (x : StaticSemL.Id)\n    (v: Value) (e: Exp)\n    (t : VTyp) (m: valueVTyp v = t)\n    (i2 : findE fenv x = Some (FC tenv0 v e))     \n  (IHn : FEnvTyping fenv ftenv ->\n        valTC_Trans tenv0 ->\n        forall n0 : nat, n0 <= n -> W -> sVTyp t * W * {n1 : nat & n1 <= n0})\n  (e9 : Exp)\n  (ls : list Exp)\n  (pt : PTyp)\n  (i1 : IdFTyping ftenv x (FT pt t))\n  (p : PrmsTyping ftenv tenv (PS ls) pt)\n  (n1 : nat)\n  (svs2 : PTyp_TRN pt)\n  (s3 : W)\n  (n3 : nat)\n  (q4 : n3 <= n1)\n  (m9 : ExpTyping ftenv tenv e9 Nat)\n  (n10 : nat)\n  (s9 : W)\n  (n9 : nat)\n  (q9 : n9 <= n1)\n  (H : FEnvTyping fenv ftenv)\n  (X0 : valTC_Trans tenv)\n  (H0 : n1 <= S n)\n  (X1 : W)\n  (i3 : funFTyp (FC tenv0 v e) = FT pt t) : \n  sVTyp t * W * {n2 : nat & n2 <= n1}.\n    \n    remember (min n3 n10) as n11.\n    \n    destruct n11.\n\n(* case 0 *)\n    eapply (ExpTrans_ApplyX_aux4_0 fenv D ftenv tenv tenv0\n                                x v e t m i2 e9 ls pt i1 p n1\n                                svs2 s3 n3 q4 m9 n10 H X0\n                                X1 i3 Heqn11).\n     \n(* case S *)\n    assert (n3 <= S n) as q02a.\n    eapply le_trans.\n    exact q4.\n    exact H0.\n    assert (S n11 <= n3) as q02b.\n    rewrite Heqn11.\n    intuition.\n    assert (S n11 <= S n) as q02.\n    eapply le_trans.\n    exact q02b.\n    exact q02a.\n    assert (n11 <= n) as q2.\n    eapply (le_inject _ _ q02).\n\n    unfold PTyp_TRN in svs2.\n    destruct pt.\n    simpl in i3.\n    inversion i3; subst.\n    \n    specialize (IHn H svs2 n11 q2 s3).\n\n    eapply (ExpTrans_ApplyX_aux4 fenv D n ftenv tenv tenv0\n                                x v e i2 n11 IHn e9 ls p i1 n1\n                                svs2 s3 n3 q4 m9 n10 s9 n9 q9 \n                                H X0 H0 X1 i3 Heqn11 q02b H3).\nDefined.\n    \n\n\nLemma ExpTrans_ApplyX_aux2 (fenv: funEnv) (D: FEnvWT fenv) (n: nat)\n    (ftenv : funTC) (tenv tenv0 : valTC) (x : StaticSemL.Id)\n    (v: Value) (e: Exp)\n    (t : VTyp) (m: VTyping v t)\n    (i2 : findE fenv x = Some (FC tenv0 v e))     \n  (IHn : FEnvTyping fenv ftenv ->\n        valTC_Trans tenv0 ->\n        forall n0 : nat, n0 <= n -> W -> sVTyp t * W * {n1 : nat & n1 <= n0})\n  (e9 : Exp)\n  (ls : list Exp)\n  (pt : PTyp)\n  (i1 : IdFTyping ftenv x (FT pt t))\n  (p : PrmsTyping ftenv tenv (PS ls) pt)\n  (n1 : nat)\n  (svs2 : PTyp_TRN pt)\n  (s3 : W)\n  (n3 : nat)\n  (q4 : n3 <= n1)\n  (m9 : ExpTyping ftenv tenv e9 Nat)\n  (n10 : nat)\n  (s9 : W)\n  (n9 : nat)\n  (q9 : n9 <= n1)\n  (H : FEnvTyping fenv ftenv)\n  (X0 : valTC_Trans tenv)\n  (H0 : n1 <= S n)\n  (X1 : W) :\n  sVTyp t * W * {n2 : nat & n2 <= n1}.\n    \n    set (f:=FC tenv0 v e).\n    set (ft:=FT pt t).\n    unfold VTyping in m.\n     \n    generalize i1.\n    intro i3.\n\n    assert (0 <= n1) as qq.\n    intuition.\n    \n    eapply (RelatedByEnv funFTyp fenv ftenv x f ft H i2) in i3.\n\n    eapply (ExpTrans_ApplyX_aux3 fenv D n ftenv tenv tenv0\n                         x v e t m i2 IHn e9 ls pt i1 p n1 svs2 s3 n3 q4\n                                 m9 n10 s9 n9 q9 H X0 H0 X1 i3).\nDefined.\n\n\nLemma ExpTrans_ApplyX_aux1 (fenv: funEnv) (D: FEnvWT fenv) (n: nat)\n    (ftenv : funTC) (tenv tenv0 : valTC) (x : StaticSemL.Id)\n    (v: Value) (e: Exp)\n    (t : VTyp) (m: VTyping v t)\n    (i2 : findE fenv x = Some (FC tenv0 v e))     \n  (IHn : FEnvTyping fenv ftenv ->\n        valTC_Trans tenv0 ->\n        forall n0 : nat, n0 <= n -> W -> sVTyp t * W * {n1 : nat & n1 <= n0})\n  (e9: Exp) \n  (ls : list Exp)\n  (pt : PTyp)\n  (i1 : IdFTyping ftenv x (FT pt t))\n  (p : PrmsTyping ftenv tenv (PS ls) pt)\n  (n1 : nat)\n  (X : PTyp_TRN pt * W * {n2 : nat & n2 <= n1})\n  (m9 : ExpTyping ftenv tenv e9 Nat)\n  (n10 : nat)\n  (s9 : W)\n  (n9 : nat)\n  (q9 : n9 <= n1)\n  (H : FEnvTyping fenv ftenv)\n  (X0 : valTC_Trans tenv)\n  (H0 : n1 <= S n)\n  (X1 : W) :\n  sVTyp t * W * {n2 : nat & n2 <= n1}.\n    \n    destruct X as [p3 X].\n    destruct p3 as [svs2 s3].\n    destruct X as [n3 q4].\n    simpl in *.\n\n    eapply (ExpTrans_ApplyX_aux2 fenv D n ftenv tenv tenv0\n                         x v e t m i2 IHn e9 ls pt i1 p n1 svs2 s3 n3 q4\n                                 m9 n10 s9 n9 q9 H X0 H0 X1).\nDefined.\n\n\nLemma ExpTrans_ApplyX_aux0 (fenv : funEnv)\n    (D: FEnvWT fenv) (n: nat)\n    (ftenv : funTC) (tenv tenv0 : valTC) (x : StaticSemL.Id)\n    (v: Value) (e: Exp)\n    (t : VTyp) (m: VTyping v t)\n    (i2 : findE fenv x = Some (FC tenv0 v e))     \n  (IHn : FEnvTyping fenv ftenv ->\n        valTC_Trans tenv0 ->\n        forall n0 : nat, n0 <= n -> W -> sVTyp t * W * {n1 : nat & n1 <= n0})\n  (e9: Exp)\n  (ls : list Exp)\n  (pt : PTyp)\n  (i1 : IdFTyping ftenv x (FT pt t))\n  (p : PrmsTyping ftenv tenv (PS ls) pt)\n  (X : FEnvTyping fenv ftenv ->\n      valTC_Trans tenv ->\n      forall n1 : nat,\n      n1 <= S n ->\n      W -> PTyp_TRN pt * W * {n2 : nat & n2 <= n1})\n  (m9 : ExpTyping ftenv tenv e9 Nat)\n  (n1 : nat)\n  (Y : sVTyp Nat * W * {n2 : nat & n2 <= n1})  \n  (H : FEnvTyping fenv ftenv)\n  (X0 : valTC_Trans tenv)\n  (H0 : n1 <= S n)\n  (X1 : W) :\n  sVTyp t * W * {n2 : nat & n2 <= n1}.\n  \n    destruct Y as [pp9 Y].\n    destruct pp9 as [n10 s9].\n    destruct Y as [n9 q9].\n    simpl in *.\n\n    specialize (X H X0 n1 H0 X1).\n\n    eapply (ExpTrans_ApplyX_aux1 fenv D n ftenv tenv tenv0\n           x v e t m i2 IHn e9 ls pt i1 p n1 X m9 n10 s9 n9 q9 H X0 H0 X1).\nDefined.\n\n\nLemma ExpTrans_ApplyX (fenv: funEnv) (D: FEnvWT fenv) (n: nat)\n     (ftenv : funTC) (tenv tenv0 : valTC) (x : StaticSemL.Id)\n           (v: Value) (e: Exp)\n           (t : VTyp) (m: VTyping v t)\n      (i2 : findE fenv x = Some (FC tenv0 v e))     \n      (IHn : FEnvTyping fenv ftenv ->\n          valTC_Trans tenv0 ->\n          forall (n0 : nat),\n          n0 <= n -> W -> sVTyp t * W * {n1 : nat & n1 <= n0}) :\n    forall (e9 : Exp) (ls : list Exp) (pt : PTyp) (p9 : Pure e9)\n           (i1 : IdFTyping ftenv x (FT pt t))\n           (p : PrmsTyping ftenv tenv (PS ls) pt),\n      PrmsTrans3_def fenv D (S n) ftenv tenv (PS ls) pt p ->\n   forall m9 : ExpTyping ftenv tenv e9 Nat,\n   ExpTrans3_def fenv D (S n) ftenv tenv e9 Nat m9 ->\n   ExpTrans3_def fenv D (S n) ftenv tenv (Apply x (PS ls) e9) t\n                 (Apply_Typing ftenv tenv x e9 (PS ls) pt t p9 i1 p m9).\n    unfold ExpTrans3_def, PrmsTrans3_def.\n    intros e9 ls pt p9 i1 p.\n    intros X m9 Y H X0 n1 H0 X1.\n    specialize (Y H X0 n1 H0 X1).\n\n    eapply (ExpTrans_ApplyX_aux0 fenv D n ftenv tenv tenv0\n           x v e t m i2 IHn e9 ls pt i1 p X m9 n1 Y H X0 H0 X1).\nDefined.\n\n\n(*********************************************************************)\n\nLemma ExpTrans_CallE_old (fenv: funEnv) (D: FEnvWT fenv) (n : nat)\n (IHn : forall (ftenv : funTC) (tenv : valTC) (e : Exp) (t : VTyp),\n        ExpTyping ftenv tenv e t ->\n        FEnvTyping fenv ftenv ->\n        valTC_Trans tenv ->\n        forall n1 : nat, n1 <= n -> W -> sVTyp t * W * {n2 : nat & n2 <= n1}) :\n  forall (ftenv : funTC) (tenv : valTC) (x : StaticSemL.Id) \n    (ls : list Exp) (pt : PTyp) (t : VTyp) (i : IdFTyping ftenv x (FT pt t))\n    (p : PrmsTyping ftenv tenv (PS ls) pt),\n  PrmsTrans3_def fenv D (S n) ftenv tenv (PS ls) pt p ->\n  ExpTrans3_def fenv D (S n) ftenv tenv (Call x (PS ls)) t\n    (Call_Typing ftenv tenv x ls pt t i p).\n     unfold ExpTrans3_def, PrmsTrans3_def.\n     intros.\n     rename X1 into X2.\n     rename X0 into X1.\n     rename H into X0.\n     rename H0 into H.\n     specialize (X X0 X1 n1 H X2).\n     destruct X as [p3 X].\n     destruct p3 as [svs2 s3].\n     destruct X as [n3 q4].\n     \n     inversion i; subst.\n     eapply (ExtRelVal2 funFTyp ftenv fenv x (FT pt t)) in H1.     \n     destruct H1 as [f H0 H1].\n     generalize D.\n     intro k3.\n     unfold FEnvWT in D.\n     specialize (D ftenv X0 x f H0).\n     unfold FunWT in D.\n     destruct f.\n     unfold funFTyp in H1.\n     destruct v.\n     destruct v.\n     simpl in *.\n     inversion H1; subst.\n     clear H1.\n\n     assert (n3 <= S n) as q5.\n     omega.\n     \n     destruct n3.\n     assert (0 <= n) as q6.\n     omega.\n     \n     specialize (IHn ftenv tenv0 e t D X0 svs2 0 q6 s3).\n     destruct IHn as [p4 IH].\n     split.\n     exact p4.\n     destruct IH as [n5 IH].\n     econstructor 1 with (x:=n5).\n     omega.\n\n     assert (n3 <= n) as q6.\n     omega.\n     \n     specialize (IHn ftenv tenv0 e t D X0 svs2 n3 q6 s3).\n     destruct IHn as [p4 IH].\n     split.\n     exact p4.\n     destruct IH as [n5 IH].\n     econstructor 1 with (x:=n5).\n     omega.\n\n     exact X0.\nDefined.\n\n\nLemma ExpTrans_CallX_aux4 (fenv: funEnv) (D: FEnvWT fenv) (n: nat)\n    (ftenv : funTC) (tenv tenv0 : valTC) (x : Id)\n           (v: Value) (e: Exp)\n           (i2 : findE fenv x = Some (FC tenv0 v e))\n           (n3 : nat)\n  (IHn : sVTyp (valueVTyp v) * W * {n1 : nat & n1 <= n3})           \n  (ls : list Exp)\n  (p : PrmsTyping ftenv tenv (PS ls) (PT (map snd tenv0)))\n  (i : IdFTyping ftenv x (FT (PT (map snd tenv0)) (valueVTyp v)))\n  (n1 : nat)\n  (svs2 : tlist2type (PTyp_ListTrans (PT (map snd tenv0))))\n  (s3 : W)\n  (q4 : S n3 <= n1)\n  (H : FEnvTyping fenv ftenv)\n  (X0 : valTC_Trans tenv)\n  (H0 : n1 <= S n)\n  (X1 : W)\n  (i3 : FT (PT (map snd tenv0)) (projT1 v) =\n        FT (PT (map snd tenv0)) (valueVTyp v))\n  (q2 : n3 <= n)\n  (H3 : projT1 v = valueVTyp v) :\n  sVTyp (projT1 v) * W * {n2 : nat & n2 <= n1}.    \n    destruct IHn as [IH1 IH2].\n\n    split.\n    exact IH1.\n    destruct IH2 as [n4 IH2].\n\n    econstructor 1 with (x:=n4).\n    eapply le_trans.\n    exact IH2.\n    eapply (le_decrease _ _ q4).\nDefined.    \n\n\nLemma ExpTrans_CallX_aux4_0 (fenv: funEnv) (D: FEnvWT fenv) \n    (ftenv : funTC) (tenv tenv0 : valTC) (x : Id)\n           (v: Value) (e: Exp)\n           (t : VTyp) (m: valueVTyp v = t)\n  (i2 : findE fenv x = Some (FC tenv0 v e))\n  (ls : list Exp)\n  (pt : PTyp)\n  (i : IdFTyping ftenv x (FT pt t))\n  (p : PrmsTyping ftenv tenv (PS ls) pt)\n  (n1 : nat)\n  (svs2 : PTyp_TRN pt)\n  (s3 : W)\n  (q4 : 0 <= n1)\n  (H : FEnvTyping fenv ftenv)\n  (X0 : valTC_Trans tenv)\n  (X1 : W)\n  (i3 : funFTyp (FC tenv0 v e) = FT pt t) :\n  sVTyp t * W * {n2 : nat & n2 <= n1}.\n    split.\n    destruct v.\n    destruct v.\n    simpl in m.\n    inversion m; subst.\n    exact (v, s3).\n    econstructor 1 with (x:=0).\n    auto.\nDefined.\n\n\nLemma ExpTrans_CallX_aux3 (fenv: funEnv) (D: FEnvWT fenv) (n: nat)\n    (ftenv : funTC) (tenv tenv0 : valTC) (x : StaticSemL.Id)\n           (v: Value) (e: Exp)\n           (t : VTyp) (m: valueVTyp v = t)\n      (i2 : findE fenv x = Some (FC tenv0 v e))     \n  (IHn : FEnvTyping fenv ftenv ->\n        valTC_Trans tenv0 ->\n        forall n0 : nat, n0 <= n -> W -> sVTyp t * W * {n1 : nat & n1 <= n0})\n  (ls : list Exp)\n  (pt : PTyp)\n  (i : IdFTyping ftenv x (FT pt t))\n  (p : PrmsTyping ftenv tenv (PS ls) pt)\n  (n1 : nat)\n  (svs2 : PTyp_TRN pt)\n  (s3 : W)\n  (n3 : nat)\n  (q4 : n3 <= n1)\n  (H : FEnvTyping fenv ftenv)\n  (X0 : valTC_Trans tenv)\n  (H0 : n1 <= S n)\n  (X1 : W)\n  (i3 : funFTyp (FC tenv0 v e) = FT pt t) : \n  sVTyp t * W * {n2 : nat & n2 <= n1}.\n    destruct n3.\n\n(* case 0 *)\n    eapply (ExpTrans_CallX_aux4_0 fenv D ftenv tenv tenv0\n                                x v e t m i2 ls pt i p n1\n                                svs2 s3 q4 H X0 X1 i3).\n   \n(* case S *)\n    assert (S n3 <= S n) as q02.\n    eapply le_trans.\n    exact q4.\n    exact H0.\n    assert (n3 <= n) as q2.\n    eapply (le_inject _ _ q02).\n\n    unfold PTyp_TRN in svs2.\n    destruct pt.\n    simpl in i3.\n    inversion i3; subst.\n    \n    specialize (IHn H svs2 n3 q2 s3).\n    eapply (ExpTrans_CallX_aux4 fenv D n ftenv tenv tenv0\n                                x v e i2 n3 IHn ls p i n1\n                                svs2 s3 q4 H X0 H0 X1 i3 q2 H3).\nDefined.\n\n\nLemma ExpTrans_CallX_aux2 (fenv: funEnv) (D: FEnvWT fenv) (n: nat)\n    (ftenv : funTC) (tenv tenv0 : valTC) (x : StaticSemL.Id)\n           (v: Value) (e: Exp)\n           (t : VTyp) (m: VTyping v t)\n      (i2 : findE fenv x = Some (FC tenv0 v e))     \n  (IHn : FEnvTyping fenv ftenv ->\n        valTC_Trans tenv0 ->\n        forall n0 : nat, n0 <= n -> W -> sVTyp t * W * {n1 : nat & n1 <= n0})\n  (ls : list Exp)\n  (pt : PTyp)\n  (i : IdFTyping ftenv x (FT pt t))\n  (p : PrmsTyping ftenv tenv (PS ls) pt)\n  (n1 : nat)\n  (svs2 : PTyp_TRN pt)\n  (s3 : W)\n  (n3 : nat)\n  (q4 : n3 <= n1)\n  (H : FEnvTyping fenv ftenv)\n  (X0 : valTC_Trans tenv)\n  (H0 : n1 <= S n)\n  (X1 : W) :\n  sVTyp t * W * {n2 : nat & n2 <= n1}.\n    set (f:=FC tenv0 v e).\n    set (ft:=FT pt t).\n    unfold VTyping in m.\n     \n    generalize i.\n    intro i3.\n\n    eapply (RelatedByEnv funFTyp fenv ftenv x f ft H i2) in i3.\n    eapply (ExpTrans_CallX_aux3 fenv D n ftenv tenv tenv0\n                                x v e t m i2 IHn ls pt i p n1\n                                svs2 s3 n3 q4 H X0 H0 X1 i3).\nDefined.\n\n\n\nLemma ExpTrans_CallX_aux1 (fenv: funEnv) (D: FEnvWT fenv) (n: nat)\n    (ftenv : funTC) (tenv tenv0 : valTC) (x : StaticSemL.Id)\n           (v: Value) (e: Exp)\n           (t : VTyp) (m: VTyping v t)\n      (i2 : findE fenv x = Some (FC tenv0 v e))     \n  (IHn : FEnvTyping fenv ftenv ->\n        valTC_Trans tenv0 ->\n        forall n0 : nat, n0 <= n -> W -> sVTyp t * W * {n1 : nat & n1 <= n0})\n  (ls : list Exp)\n  (pt : PTyp)\n  (i : IdFTyping ftenv x (FT pt t))\n  (p : PrmsTyping ftenv tenv (PS ls) pt)\n  (n1 : nat)\n  (X : PTyp_TRN pt * W * {n2 : nat & n2 <= n1})\n  (H : FEnvTyping fenv ftenv)\n  (X0 : valTC_Trans tenv)\n  (H0 : n1 <= S n)\n  (X1 : W) :\n  sVTyp t * W * {n2 : nat & n2 <= n1}.\n    destruct X as [p3 X].\n    destruct p3 as [svs2 s3].\n    destruct X as [n3 q4].\n    simpl in *.\n    eapply (ExpTrans_CallX_aux2 fenv D n ftenv tenv tenv0\n                                x v e t m i2 IHn ls pt i p n1\n                                svs2 s3 n3 q4 H X0 H0 X1).\nDefined.\n\n\nLemma ExpTrans_CallX : forall (fenv: funEnv) (D: FEnvWT fenv) (n: nat),\n    forall (ftenv : funTC) (tenv tenv0 : valTC) (x : StaticSemL.Id)\n           (v: Value) (e: Exp)\n           (t : VTyp) (m: VTyping v t)\n      (i2 : findE fenv x = Some (FC tenv0 v e))     \n      (IHn : FEnvTyping fenv ftenv ->\n          valTC_Trans tenv0 ->\n          forall (n0 : nat),\n          n0 <= n -> W -> sVTyp t * W * {n1 : nat & n1 <= n0}),\n    forall (ls : list Exp) (pt : PTyp) \n           (i : IdFTyping ftenv x (FT pt t))\n    (p : PrmsTyping ftenv tenv (PS ls) pt),\n  PrmsTrans3_def fenv D (S n) ftenv tenv (PS ls) pt p ->\n  ExpTrans3_def fenv D (S n) ftenv tenv (Call x (PS ls)) t\n    (Call_Typing ftenv tenv x ls pt t i p).\n    unfold ExpTrans3_def, PrmsTrans3_def.\n    intros.\n    specialize (X H X0 n1 H0 X1).\n    eapply (ExpTrans_CallX_aux1 fenv D n ftenv tenv tenv0\n           x v e t m i2 IHn ls pt i p n1 X H X0 H0 X1).\nDefined.\n\n\nLemma ExpTrans_CallX0_aux1 (fenv : funEnv)\n  (D : FEnvWT fenv)\n  (ftenv : funTC)\n  (tenv tenv0 : valTC)\n  (x : Id)\n  (v : Value)\n  (e : Exp)\n  (t : VTyp)\n  (m : VTyping v t)\n  (i2 : findE fenv x = Some (FC tenv0 v e))\n  (ls : list Exp)\n  (pt : PTyp)\n  (i : IdFTyping ftenv x (FT pt t))\n  (p : PrmsTyping ftenv tenv (PS ls) pt)\n  (n1 : nat)\n  (X : PTyp_TRN pt * W * {n2 : nat & n2 <= n1})\n  (H : FEnvTyping fenv ftenv)\n  (X0 : valTC_Trans tenv)\n  (H0 : n1 <= 0)\n  (X1 : W) :\n  sVTyp t * W * {n2 : nat & n2 <= n1}.\n\n    destruct X as [p3 X].\n    destruct p3 as [svs2 s3].\n    destruct X as [n3 q4].\n    simpl in *.\n\n    set (f:=FC tenv0 v e).\n    set (ft:=FT pt t).\n    unfold VTyping in m.\n     \n    generalize i.\n    intro i3.\n\n    assert (0 <= n1) as qq.\n    intuition.\n    \n    eapply (RelatedByEnv funFTyp fenv ftenv x f ft H i2) in i3.\n    \n    eapply (ExpTrans_CallX_aux4_0 fenv D ftenv tenv tenv0\n                                x v e t m i2 ls pt i p n1\n                                svs2 s3 qq H X0 X1 i3).\nDefined.\n\nLemma ExpTrans_CallX0 : forall (fenv: funEnv) (D: FEnvWT fenv),\n    forall (ftenv : funTC) (tenv tenv0 : valTC) (x : StaticSemL.Id)\n           (v: Value) (e: Exp)\n           (t : VTyp) (m: VTyping v t)\n      (i2 : findE fenv x = Some (FC tenv0 v e)),      \n    forall (ls : list Exp) (pt : PTyp) \n           (i : IdFTyping ftenv x (FT pt t))\n    (p : PrmsTyping ftenv tenv (PS ls) pt),\n  PrmsTrans3_def fenv D 0 ftenv tenv (PS ls) pt p ->\n  ExpTrans3_def fenv D 0 ftenv tenv (Call x (PS ls)) t\n    (Call_Typing ftenv tenv x ls pt t i p).\n    unfold ExpTrans3_def, PrmsTrans3_def.\n    intros.\n    specialize (X H X0 n1 H0 X1).\n\n    eapply (ExpTrans_CallX0_aux1 fenv D ftenv tenv tenv0 x v e t m i2\n                                 ls pt i p n1 X H X0 H0 X1).\nDefined.\n\n\nLemma Convert_Trans_Call (fenv: funEnv) (D: FEnvWT fenv) (n: nat) :\n  (forall (ftenv : funTC) (tenv tenv0 : valTC) (x : StaticSemL.Id)\n           (v: Value) (e: Exp)\n           (t : VTyp) (m: VTyping v t)\n      (i2 : findE fenv x = Some (FC tenv0 v e))     \n      (IHn : FEnvTyping fenv ftenv ->\n          valTC_Trans tenv0 ->\n          forall (n0 : nat),\n          n0 <= n -> W -> sVTyp t * W * {n1 : nat & n1 <= n0}),\n    forall (ls : list Exp) (pt : PTyp) \n           (i : IdFTyping ftenv x (FT pt t))\n    (p : PrmsTyping ftenv tenv (PS ls) pt),\n  PrmsTrans3_def fenv D (S n) ftenv tenv (PS ls) pt p ->\n  ExpTrans3_def fenv D (S n) ftenv tenv (Call x (PS ls)) t\n                (Call_Typing ftenv tenv x ls pt t i p)) -> \n  (forall (IHn : forall (ftenv : funTC) (tenv : valTC) (e : Exp) (t : VTyp),\n        ExpTyping ftenv tenv e t ->\n        FEnvTyping fenv ftenv ->\n        valTC_Trans tenv ->\n        forall n1 : nat, n1 <= n -> W -> sVTyp t * W * {n2 : nat & n2 <= n1})\n    (ftenv : funTC) (tenv : valTC) (x : StaticSemL.Id) \n    (ls : list Exp) (pt : PTyp) (t : VTyp) (i : IdFTyping ftenv x (FT pt t))\n    (p : PrmsTyping ftenv tenv (PS ls) pt),\n  PrmsTrans3_def fenv D (S n) ftenv tenv (PS ls) pt p ->\n  ExpTrans3_def fenv D (S n) ftenv tenv (Call x (PS ls)) t\n                (Call_Typing ftenv tenv x ls pt t i p)).\n  intros.\n  generalize i.\n  intro i2.\n  unfold IdFTyping in i.\n  unfold EnvrAssign in i.\n\n  unfold ExpTrans3_def.\n  intros.\n\n  eapply ExtRelVal2 with (f:=funFTyp) (venv:=fenv) in i.\n  destruct i as [f m d].\n  Focus 2.\n  assumption.\n  \n  generalize D.\n  intro D1.\n  unfold FEnvWT in D1.\n  specialize (D1 ftenv H x f m).\n  unfold FunWT in D1.\n\n  destruct f.\n  simpl in d.\n  inversion d; subst.\n  set (t:= projT1 v).\n  \n  assert ((forall (ftenv : funTC) (tenv : valTC) (e : Exp) (t : VTyp),\n        ExpTyping ftenv tenv e t ->\n        FEnvTyping fenv ftenv ->\n        valTC_Trans tenv ->\n        forall n1 : nat, n1 <= n -> W -> sVTyp t * W * {n2 : nat & n2 <= n1})\n          ->\n         (FEnvTyping fenv ftenv ->\n       valTC_Trans tenv0 ->\n       forall n0 : nat, n0 <= n -> W -> sVTyp t * W * {n1 : nat & n1 <= n0}))\n    as IHc.\n\n  intros.\n  subst t.\n  specialize (X3 ftenv tenv0 e (projT1 v) D1 H X4 n0 H2 X5).\n  exact X3.\n\n  specialize (X ftenv tenv tenv0 x v e (projT1 v) eq_refl m (IHc IHn)\n                ls (PT (map snd tenv0)) i2 p X0).\n  eapply X.\n  assumption.\n  assumption.\n  assumption.\n  exact X2.\nDefined.\n\nLemma Convert_Trans_Call0 (fenv: funEnv) (D: FEnvWT fenv) :\n  (forall (ftenv : funTC) (tenv tenv0 : valTC) (x : StaticSemL.Id)\n           (v: Value) (e: Exp)\n           (t : VTyp) (m: VTyping v t)\n      (i2 : findE fenv x = Some (FC tenv0 v e)),      \n    forall (ls : list Exp) (pt : PTyp) \n           (i : IdFTyping ftenv x (FT pt t))\n    (p : PrmsTyping ftenv tenv (PS ls) pt),\n  PrmsTrans3_def fenv D 0 ftenv tenv (PS ls) pt p ->\n  ExpTrans3_def fenv D 0 ftenv tenv (Call x (PS ls)) t\n                (Call_Typing ftenv tenv x ls pt t i p)) ->\n  (forall (ftenv : funTC) (tenv : valTC) (x : StaticSemL.Id) \n    (ls : list Exp) (pt : PTyp) (t : VTyp) (i : IdFTyping ftenv x (FT pt t))\n    (p : PrmsTyping ftenv tenv (PS ls) pt),\n  PrmsTrans3_def fenv D 0 ftenv tenv (PS ls) pt p ->\n  ExpTrans3_def fenv D 0 ftenv tenv (Call x (PS ls)) t\n    (Call_Typing ftenv tenv x ls pt t i p)).\n  intros.\n  generalize i.\n  intro i2.\n  unfold IdFTyping in i.\n  unfold EnvrAssign in i.\n\n  unfold ExpTrans3_def.\n  intros.\n\n  eapply ExtRelVal2 with (f:=funFTyp) (venv:=fenv) in i.\n  destruct i as [f m d].\n  Focus 2.\n  assumption.\n  \n  generalize D.\n  intro D1.\n  unfold FEnvWT in D1.\n  specialize (D1 ftenv H x f m).\n  unfold FunWT in D1.\n\n  destruct f.\n  simpl in d.\n  inversion d; subst.\n  set (t:= projT1 v).\n  \n  intros.\n  subst t.\n\n  specialize (X ftenv tenv tenv0 x v e (projT1 v) eq_refl m \n                ls (PT (map snd tenv0)) i2 p X0).\n  eapply X.\n  assumption.\n  assumption.\n  assumption.\n  exact X2.\nDefined.\n  \n\n\nLemma Prms2ExpIH (fenv: funEnv) (D: FEnvWT fenv) (n : nat)  \n (IHn : forall (ftenv : funTC) (tenv : valTC) (ps : Prms) (pt : PTyp),\n        PrmsTyping ftenv tenv ps pt ->\n        FEnvTyping fenv ftenv ->\n        valTC_Trans tenv ->\n        forall n1 : nat,\n        n1 <= n -> W -> PTyp_TRN pt * W * {n2 : nat & n2 <= n1}) :\n  forall (ftenv : funTC) (tenv : valTC) (e : Exp) (t : VTyp),\n  ExpTyping ftenv tenv e t ->\n  FEnvTyping fenv ftenv ->\n  valTC_Trans tenv ->\n  forall n1 : nat, n1 <= n -> W -> sVTyp t * W * {n2 : nat & n2 <= n1}.\nProof.\n  intros.\n  set (ps := PS [e]).\n  set (pt := PT [t]).\n  assert (PrmsTyping ftenv tenv  ps pt) as X4.\n  constructor.\n  assumption.\n  constructor.\n  specialize  (IHn ftenv tenv ps pt X4 H X0 n1 H0 X1). \n  destruct IHn as [p1 c].\n  destruct p1 as [sps w].\n  simpl in sps.\n  unfold PTyp_TRN in sps.\n  simpl in sps.\n  exact (fst sps, w, c).\nDefined.  \n\n\n(*********************** main ****************************************)\n\nProgram Fixpoint ExpTransB (fenv: funEnv) (D: FEnvWT fenv) (n: nat)\n        (ftenv: funTC) (tenv: valTC) (e: Exp) (t: VTyp) \n        (k: ExpTyping ftenv tenv e t) :\n               FEnvTyping fenv ftenv ->  \n               valTC_Trans tenv ->\n          forall (n1: nat), n1 <= n -> W ->\n                      (sVTyp t * W) * sigT (fun n2 => n2 <= n1) := _    \nwith PrmsTransB (fenv: funEnv) (D: FEnvWT fenv) (n: nat)\n       (ftenv: funTC) (tenv: valTC) (ps: Prms) (pt: PTyp) \n       (k: PrmsTyping ftenv tenv ps pt) :              \n              FEnvTyping fenv ftenv ->\n              valTC_Trans tenv ->\n          forall (n1: nat), n1 <= n -> W ->\n                     (PTyp_TRN pt * W) * sigT (fun n2 => n2 <= n1) := _.        \nNext Obligation.\n   intros fenv D n.\n   induction n.\n   eapply (Trans_ExpTyping_mut3 fenv D 0).   \n   - eapply (ExpTrans_Val fenv D 0).\n   - eapply (ExpTrans_Var fenv D 0).\n   - eapply (ExpTrans_BindN fenv D 0).\n   - eapply (ExpTrans_BindS fenv D 0).\n   - eapply (ExpTrans_BindMS fenv D 0).\n   - eapply (ExpTrans_IfThenElse fenv D 0).\n   - eapply (ExpTrans_Apply0 fenv D).\n   - eapply (Convert_Trans_Call0 fenv D (ExpTrans_CallX0 fenv D)). \n   - eapply (ExpTrans_Modify fenv D 0).\n   - eapply (ExpTrans_PrmsNil fenv D 0).\n   - eapply (ExpTrans_Prms fenv D 0).\n   - eapply (Trans_ExpTyping_mut3 fenv D (S n)).   \n     * eapply (ExpTrans_Val fenv D (S n)).\n     * eapply (ExpTrans_Var fenv D (S n)).\n     * eapply (ExpTrans_BindN fenv D (S n)).\n     * eapply (ExpTrans_BindS fenv D (S n)). \n     * eapply (ExpTrans_BindMS fenv D (S n)).\n     * eapply (ExpTrans_IfThenElse fenv D (S n)).\n     * eapply (ExpTrans_ApplyE fenv D n).\n       assumption.\n     * eapply (Convert_Trans_Call fenv D n (ExpTrans_CallX fenv D n)).\n       assumption.\n     * eapply (ExpTrans_Modify fenv D (S n)).\n     * eapply (ExpTrans_PrmsNil fenv D (S n)).\n     * eapply (ExpTrans_Prms fenv D (S n)). \nDefined.   \n       \nNext Obligation.\n   intros fenv D n.\n   induction n.\n   eapply (Trans_PrmsTyping_mut3 fenv D 0).   \n   - eapply (ExpTrans_Val fenv D 0).\n   - eapply (ExpTrans_Var fenv D 0).\n   - eapply (ExpTrans_BindN fenv D 0).\n   - eapply (ExpTrans_BindS fenv D 0).\n   - eapply (ExpTrans_BindMS fenv D 0).\n   - eapply (ExpTrans_IfThenElse fenv D 0).\n   - eapply (ExpTrans_Apply0 fenv D).\n   - eapply (Convert_Trans_Call0 fenv D (ExpTrans_CallX0 fenv D)). \n   - eapply (ExpTrans_Modify fenv D 0).\n   - eapply (ExpTrans_PrmsNil fenv D 0).\n   - eapply (ExpTrans_Prms fenv D 0).\n   - eapply (Trans_PrmsTyping_mut3 fenv D (S n)).   \n     * eapply (ExpTrans_Val fenv D (S n)).\n     * eapply (ExpTrans_Var fenv D (S n)).\n     * eapply (ExpTrans_BindN fenv D (S n)).\n     * eapply (ExpTrans_BindS fenv D (S n)). \n     * eapply (ExpTrans_BindMS fenv D (S n)).\n     * eapply (ExpTrans_IfThenElse fenv D (S n)).\n     * eapply (ExpTrans_ApplyE fenv D n).\n       eapply (Prms2ExpIH fenv D).\n       assumption.\n     * eapply (Convert_Trans_Call fenv D n (ExpTrans_CallX fenv D n)).\n       eapply (Prms2ExpIH fenv D).\n       assumption.\n     * eapply (ExpTrans_Modify fenv D (S n)).\n     * eapply (ExpTrans_PrmsNil fenv D (S n)).\n     * eapply (ExpTrans_Prms fenv D (S n)). \nDefined.   \n\n\nLemma ExpTransA (fenv: funEnv) (D: FEnvWT fenv) (n: nat) :\n  forall (ftenv: funTC) (tenv: valTC) (e: Exp) (t: VTyp) \n        (k: ExpTyping ftenv tenv e t),   \n               FEnvTyping fenv ftenv ->  \n               valTC_Trans tenv ->\n          forall (n1: nat), n1 <= n -> W ->\n                      (sVTyp t * W) * sigT (fun n2 => n2 <= n1).\nProof.\n   induction n.\n   eapply (Trans_ExpTyping_mut3 fenv D 0).   \n   - eapply (ExpTrans_Val fenv D 0).\n   - eapply (ExpTrans_Var fenv D 0).\n   - eapply (ExpTrans_BindN fenv D 0).\n   - eapply (ExpTrans_BindS fenv D 0).\n   - eapply (ExpTrans_BindMS fenv D 0).\n   - eapply (ExpTrans_IfThenElse fenv D 0).\n   - eapply (ExpTrans_Apply0 fenv D).\n   - eapply (Convert_Trans_Call0 fenv D (ExpTrans_CallX0 fenv D)).  \n   - eapply (ExpTrans_Modify fenv D 0).\n   - eapply (ExpTrans_PrmsNil fenv D 0).\n   - eapply (ExpTrans_Prms fenv D 0).\n   - eapply (Trans_ExpTyping_mut3 fenv D (S n)).   \n     * eapply (ExpTrans_Val fenv D (S n)).\n     * eapply (ExpTrans_Var fenv D (S n)).\n     * eapply (ExpTrans_BindN fenv D (S n)).\n     * eapply (ExpTrans_BindS fenv D (S n)). \n     * eapply (ExpTrans_BindMS fenv D (S n)).\n     * eapply (ExpTrans_IfThenElse fenv D (S n)).\n     * eapply (ExpTrans_ApplyE fenv D n).\n       assumption.\n     * eapply (Convert_Trans_Call fenv D n (ExpTrans_CallX fenv D n)).\n       assumption.\n     * eapply (ExpTrans_Modify fenv D (S n)).\n     * eapply (ExpTrans_PrmsNil fenv D (S n)).\n     * eapply (ExpTrans_Prms fenv D (S n)). \nDefined.   \n\nLemma PrmsTransA (fenv: funEnv) (D: FEnvWT fenv) (n: nat) :\n  forall (ftenv: funTC) (tenv: valTC) (ps: Prms) (pt: PTyp) \n       (k: PrmsTyping ftenv tenv ps pt),   \n              FEnvTyping fenv ftenv ->\n              valTC_Trans tenv ->\n          forall (n1: nat), n1 <= n -> W ->\n                     (PTyp_TRN pt * W) * sigT (fun n2 => n2 <= n1).        \n   induction n.\n   eapply (Trans_PrmsTyping_mut3 fenv D 0).   \n   - eapply (ExpTrans_Val fenv D 0).\n   - eapply (ExpTrans_Var fenv D 0).\n   - eapply (ExpTrans_BindN fenv D 0).\n   - eapply (ExpTrans_BindS fenv D 0).\n   - eapply (ExpTrans_BindMS fenv D 0).\n   - eapply (ExpTrans_IfThenElse fenv D 0).\n   - eapply (ExpTrans_Apply0 fenv D).\n   - eapply (Convert_Trans_Call0 fenv D (ExpTrans_CallX0 fenv D)).  \n   - eapply (ExpTrans_Modify fenv D 0).\n   - eapply (ExpTrans_PrmsNil fenv D 0).\n   - eapply (ExpTrans_Prms fenv D 0).\n   - eapply (Trans_PrmsTyping_mut3 fenv D (S n)).   \n     * eapply (ExpTrans_Val fenv D (S n)).\n     * eapply (ExpTrans_Var fenv D (S n)).\n     * eapply (ExpTrans_BindN fenv D (S n)).\n     * eapply (ExpTrans_BindS fenv D (S n)). \n     * eapply (ExpTrans_BindMS fenv D (S n)).\n     * eapply (ExpTrans_IfThenElse fenv D (S n)).\n     * eapply (ExpTrans_ApplyE fenv D n).\n       eapply (Prms2ExpIH fenv D).\n       assumption.\n     * eapply (Convert_Trans_Call fenv D n (ExpTrans_CallX fenv D n)).\n       eapply (Prms2ExpIH fenv D).\n       assumption.\n     * eapply (ExpTrans_Modify fenv D (S n)).\n     * eapply (ExpTrans_PrmsNil fenv D (S n)).\n     * eapply (ExpTrans_Prms fenv D (S n)). \nDefined.   \n\n\nEnd Reflect.\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/ReflectI1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2629919524161234}}
{"text": "From hahn Require Import Hahn.\nRequire Import PromisingLib.\n\nFrom imm Require Import Events Execution.\nFrom imm Require Import ProgToExecution.\nFrom imm Require Import ProgToExecutionProperties.\nRequire Import PromiseLTS.\n\nSet Implicit Arguments.\n\nInductive sim_mode := sim_normal | sim_certification.\n  \nDefinition sim_state_helper G smode thread\n           (state state' : Language.state (thread_lts thread)) : Prop :=\n  ⟪ STEPS : (step thread)＊ state state' ⟫ /\\\n  ⟪ TERMINAL : smode = sim_normal -> is_terminal state' ⟫ /\\\n  ⟪ TEH  : thread_restricted_execution G thread state'.(ProgToExecution.G) ⟫.\n\nDefinition sim_state G smode (C : actid -> Prop) thread\n           (state : Language.state (thread_lts thread)) : Prop :=\n  ⟪ PCOV : forall index , C (ThreadEvent thread index) <-> index < state.(eindex)⟫ /\\\n  exists state', sim_state_helper G smode state state'.\n\nLemma sim_state_other_thread_step G\n      (C C' : actid -> Prop) smode thread (state : Language.state (thread_lts thread))\n      (CINCL : C ⊆₁ C')\n      (COVSTEP : forall a, tid a = thread -> C' a -> C a)\n      (SIMSTATE: sim_state G smode C state) :\n  sim_state G smode C' state.\nProof using.\n  cdes SIMSTATE.\n  red. splits; eauto.\n  ins. split; ins.\n  { apply PCOV. apply COVSTEP; eauto. }\n  apply CINCL. by apply PCOV.\nQed.\n\nNotation \"'Tid_' t\" := (fun x => tid x = t) (at level 1).\nNotation \"'NTid_' t\" := (fun x => tid x <> t) (at level 1).\n\nLemma sim_state_set_tid_eq G mode thread s s' state\n      (EQ : s ∩₁ Tid_ thread ≡₁ s' ∩₁ Tid_ thread):\n  @sim_state G mode s thread state <->\n  @sim_state G mode s' thread state.\nProof using.\n  split; intros AA. \n  all: red; splits; [|by apply AA].\n  all: ins; split; intros BB.\n  1,3: by apply AA; apply EQ.\n  all: by apply EQ; split; auto; apply AA.\nQed.\n\nLemma sim_state_set_eq G mode thread s s' state\n      (EQ : s ≡₁ s'):\n  @sim_state G mode s thread state <->\n  @sim_state G mode s' thread state.\nProof using. apply sim_state_set_tid_eq. by rewrite EQ. 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/SimState.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2629919464979688}}
{"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 CombineOp.\nRequire Import CSE.\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 -> equation_holds valu ge sp m v rhs.\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  exploit get_sound; eauto. unfold equation_holds. simpl. intro EQ; inv EQ. \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  exploit get_sound; eauto. unfold equation_holds. simpl. intro EQ; inv EQ. \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  exploit get_sound; eauto. unfold equation_holds. simpl. intro EQ; inv EQ. \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  exploit get_sound; eauto. unfold equation_holds. simpl. intro EQ; inv EQ. \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  exploit get_sound; eauto. unfold equation_holds; simpl; intro EQ. FuncInv.\n  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  exploit get_sound; eauto. unfold equation_holds; simpl; intros. FuncInv.\n  rewrite <- H1. rewrite Val.add_assoc. auto.\n(* addimm - subimm *)\nOpaque Val.sub.\n  exploit get_sound; eauto. unfold equation_holds; simpl; intros. FuncInv.\n  rewrite <- H1. change (Vint (Int.add m0 n)) with (Val.add (Vint m0) (Vint n)).\n  rewrite Val.sub_add_l. auto.\n(* subimm - addimm *)\n  exploit get_sound; eauto. unfold equation_holds; simpl; intros. FuncInv.\n  rewrite <- H1.\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  exploit get_sound; eauto. unfold equation_holds; simpl; intros. FuncInv.\n  rewrite <- H1. rewrite Val.and_assoc. auto.\n(* orimm - orimm *)\n  exploit get_sound; eauto. unfold equation_holds; simpl; intros. FuncInv.\n  rewrite <- H1. rewrite Val.or_assoc. auto.\n(* xorimm - xorimm *)\n  exploit get_sound; eauto. unfold equation_holds; simpl; intros. FuncInv.\n  rewrite <- H1. rewrite Val.xor_assoc. auto.\n(* cmp *)\n  simpl. decEq; decEq. eapply combine_cond_sound; eauto.\nQed.\n\nEnd COMBINE.\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/arm/CombineOpproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.26294015561824474}}
{"text": "(* En este archivo se demuestra que la ejecución de\n*  la acción revokeDel preserva los invariantes del sistema *)\nRequire Export Exec.\nRequire Export Implementacion.\nRequire Export AuxFunsCorrect.\nRequire Import Classical.\nRequire Import Estado.\nRequire Import DefBasicas.\nRequire Import Semantica.\nRequire Import Operaciones.\nRequire Import ErrorManagement.\nRequire Import Maps.\nRequire Import Tacticas.\nRequire Import MyList.\nRequire Import ListAuxFuns.\nRequire Import ValidStateLemmas.\nRequire Import SameEnvLemmas.\nRequire Import Semantica.\n\nSection RevokeDelInv.\n\n    \nLemma RevokeDelIsInvariant : forall (s s':System) (sValid:validstate s) (ic:iCmp) (cp:CProvider) (u:uri) (pt:PType) , pre_revokeDel ic cp u pt s -> post_revokeDel ic cp u pt s s' -> validstate s'.\nProof.\n    intros.\n    unfold validstate.\n    unfold pre_revokeDel in H.\n    unfold post_revokeDel in H0.\n    destruct H0 as [verifeid H0].\n    destruct_conj H0.\n    \n    unfold allCmpDifferent.\n    split.\n    intros.\n    \n    \n    apply (inAppS'InAppS a1 s) in H14;auto.\n    apply (inAppS'InAppS a2 s) in H16;auto.\n    apply (inAppSameCmpId s sValid c1 c2 a1 a2);auto.\n    \n    \n    unfold notRepeatedCmps.\n    split.\n    intros.\n    apply (inAppS'InAppS a1 s) in H14;auto.\n    apply (inAppS'InAppS a2 s) in H16;auto.\n    apply (inAppSameCmp s sValid c a1 a2);auto.\n    \n    \n    unfold notCPrunning.\n    split.\n    rewrite <-H12.\n    destructVS sValid.\n    auto.\n    \n    \n    split.\n    unfold delTmpRun.\n    intros.\n    specialize (H1 ic0 cp0 u0 pt0 H14).\n    destruct H1.\n    destruct H1.\n    destructVS sValid.\n    destruct (delTmpRunVS ic0 cp0 u0 x);auto.\n    split.\n    destruct H17.\n    exists x0.\n    apply (inAppS'InAppS x0 s);auto.\n    destruct H18.\n    destruct H18.\n    destruct H18.\n    exists x0,x1.\n    split.\n    apply (inAppS'InAppS x1 s);auto.\n    rewrite<-H12;auto.\n    \n    split.\n    apply (cmpRunAppInsS' s);auto.\n    \n    split.\n    apply (resContAppInstS' s);auto.\n    \n    split.\n    apply (consistencyUnchanged s);auto.\n    \n    unfold notDupApp.\n    split.\n    rewrite <- H8.\n    rewrite<-H9.\n    destructVS sValid.\n    auto.\n    \n    unfold notDupSysApp.\n    split.\n    rewrite <-H8.\n    destructVS sValid.\n    auto.\n    \n    \n    split.\n    apply (notDupPermS' s);auto.\n    \n    unfold allMapsCorrect.\n    split.\n    rewrite <-H8, <-H10, <-H11, <- H12, <-H13.\n    repeat (split;auto; try mapcorrect sValid).\n    \n    \n    split.\n    apply (grantedPermsExistS' s);auto.\n\n    unfold noDupSentIntents.\n    rewrite<- H15.\n    destructVS sValid.\n    auto.\nQed.\n\n\n\nEnd RevokeDelInv.\n\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/RevokeDelIsInvariant.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.26294014911576163}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import RBT.Verif.verif_rbt_toolbox.\nRequire Import RBT.Verif.rbt.\nRequire Import Coq.Init.Tauto.\n\nRequire Import RBT.Verif.RBtree_Type.\nRequire Import RBT.Verif.RBtree_Definition.\nRequire Import RBT.Verif.Half_Tree.\nRequire Import RBT.Verif.relation_map.\nRequire Import RBT.Verif.Abstract.\nRequire Import RBT.Verif.general_split.\nRequire Import RBT.Verif.Insert.\nRequire Import RBT.Verif.lookup.\nRequire Import RBT.Verif.SegmentChange.\nRequire Import RBT.Verif.Delete.\nRequire Import RBT.Verif.Delete_check.\n\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\n(** Notations.\n\n    To further simplify notations in VST, we customize some notations\n    here.\n*)\n\nDefinition t_struct_rbtree := Tstruct _tree noattr.\n\n(** Environment setting.\n\n    Here, we instantiate a red-black tree for the C implementation. \n    Keys, values and tags are all set to Z. And related properties\n    are also set to those about Z.\n*)\n\nInstance Reb_Z : Reb Z := {\n  Equal_bool x y := Z.eqb x y\n}.\n\nInstance Rlt_Z : Rlt Z := {\n  lt_prop x y := Z.lt x y\n}.\n\nInstance Rltb_Z : Rltb Z := {\n  lt_bool x y := Z.ltb x y\n}.\n\nInstance Transitive_Z : Transitive Z.\n  unfold Transitive.\n  unfold lt_prop in *. simpl in *. apply Z.lt_trans.\nDefined.\n\nInstance Asymmetric_Z : Asymmetric Z.\n  unfold Asymmetric.\n  unfold lt_prop in *. simpl in *. apply Z.lt_asymm.\nDefined.\n\nInstance Complete_Z : Complete Z.\n  unfold Complete.\n  unfold lt_prop in *. simpl in *. \n  intros. lia.\nDefined.\n\nInstance TotalOrder_Z : TotalOrder Z.\n  apply Build_TotalOrder.\n  - apply Transitive_Z.\n  - apply Asymmetric_Z.\n  - apply Complete_Z.\nDefined.\n\nLemma Rb_spec_Z: @Rb_spec Z Reb_Z.\nProof. \n  unfold Rb_spec.\n  simpl. intros.\n  symmetry. apply Z.eqb_eq.\nQed.\n\nLemma Rltb_spec_Z: @Rltb_spec Z Rlt_Z Rltb_Z.\nProof.\n  unfold Rltb_spec.\n  simpl. intros. \n  symmetry. apply Z.ltb_lt.\nQed.\n\nLemma Rlt_R_Z: @Rlt_R Z Rlt_Z.\nProof. \n  unfold Rlt_R.\n  intros. \n  simpl. \n  unfold iff; split.\n  - intros. destruct H as [H H']. lia.\n  - intros. split; lia.\nQed.\n\nLemma lte_complete_Z: forall x y, (@lte_prop Z Rlt_Z x y) \\/ (@lte_prop Z Rlt_Z y x).\nProof.\n  intros. unfold lte_prop.\n  simpl.\n  lia.\nQed.\n\nProgram Instance C_RBT : RBtree_setting := {\n  Key := Z;\n  Value := Z;\n  Tag := Z;\n\n  KRb := Reb_Z;\n  VRb := Reb_Z;\n  LKR := Rlt_Z;\n  LKRb := Rltb_Z;\n\n  f v t := v + t;\n  Optt t1 t2 := t1 + t2;\n\n  default := 0\n}.\nNext Obligation.\n  unfold Rb_spec. \n  intros. split; intros.\n  - rewrite Z.eqb_eq. auto.\n  - rewrite <- Z.eqb_eq. auto.\nQed.\nNext Obligation.\n  unfold Rltb_spec.\n  intros. split; intros.\n  - rewrite Z.ltb_lt. auto.\n  - rewrite <- Z.ltb_lt. auto.\nQed.\nNext Obligation.\n  unfold Rlt_R.\n  intros. split; intros.\n  - destruct H. rewrite Z.nlt_ge in H, H0. \n    lia.\n  - split; intro; subst y; pose proof (Z.lt_irrefl x); auto.\nQed.\nNext Obligation.\n  lia.\nQed.\nNext Obligation.\n  lia.\nQed.\n(* Next Obligation. \n  lia.\nQed. *)\nNext Obligation. \n  exists (k - 1)%Z. lia.\nQed.\nNext Obligation. \n  exists (k + 1)%Z. lia.\nQed.\nProgram Instance C_RBT_comm : RBtree_with_tag_comm  := {}.\nNext Obligation. \n  lia.\nQed.\n\n(** Use Z to represent color. *)\nDefinition RED_COLOR : Z := 1.\nDefinition BLACK_COLOR : Z := 0.\n\nDefinition Col2Z (c : color) : Z :=  \n  match c with\n  | Red   => RED_COLOR\n  | Black => BLACK_COLOR\n  end.\n\nDefinition get_color_tree (t: RBtree) : Z :=\n  match t with  \n  | T c t1 k v tag t2 => Col2Z c\n  | E => -1\n  end.\n\nDefinition turn_left (h : Half_tree) : Prop :=\n  let '(va, c, k, v, tg, oppo) := h in va = false.\n\nDefinition tag_default (h : Half_tree) : Prop :=\n  let '(va, c, k, v, tg, oppo) := h in tg = default.\n\n(* turn the result of the functional lookup to the C one *)\nDefinition Lookup2Z (x : Key) (t : RBtree) : Z :=\n  match lookup x t with\n  | None => 0%Z\n  | Some v  => v\n  end.\n\n(* reverse the two arguments of complete_tree *)\nDefinition complete_tree_revarg (p : RBtree * (list Half_tree)) :=\n  complete_tree (snd p) (fst p).\n\n(** Representation predicates. \n\n    To describe red-black trees in memory, we need to define representation \n    predicates. In this part, we define predicates for both trees and partial \n    trees, with basic separating conjunctions. \n*)\n\n(** For red-black trees. *)\nFixpoint rbtree_rep (t : RBtree) (p p_par : val) : mpred :=\n  match t with\n  | T c lch k v tg rch => \n    !! (Int.min_signed <= k <= Int.max_signed /\\ \n      is_pointer_or_null p_par) &&\n    EX p_lch : val, EX p_rch : val, \n    data_at Tsh t_struct_rbtree \n      (Vint (Int.repr (Col2Z c)), \n        (Vint (Int.repr k), \n          (Vint (Int.repr v), \n            (Vint (Int.repr tg), \n              (p_lch, (p_rch, p_par)))))) p\n    * rbtree_rep lch p_lch p * rbtree_rep rch p_rch p\n  | E => !! (p = nullval /\\ is_pointer_or_null p_par) && emp \n  end.\n\n(** For treeboxes. *)\nDefinition treebox_rep (t : RBtree) (b p_par : val) :=\n  EX p : val, data_at Tsh (tptr t_struct_rbtree) p b * rbtree_rep t p p_par.\n\n(** For partial trees. *)\nFixpoint partial_tree_rep (t : list Half_tree) (p_root p p_par p_top : val) : mpred :=\n  match t with\n  | [] => !! (p = p_root /\\ p_par = p_top) && emp\n  | (va, c, k, v, tg, sib) :: l  =>\n    EX p_gpar: val, EX p_sib : val, \n        !! (Int.min_signed <= k <= Int.max_signed) &&\n        rbtree_rep sib p_sib p_par *\n        partial_tree_rep l p_root p_par p_gpar p_top *\n        data_at Tsh t_struct_rbtree\n        (Vint (Int.repr (Col2Z c)), \n          (Vint (Int.repr k), \n            (Vint (Int.repr v), \n              (Vint (Int.repr tg), \n                ((if va then p_sib else p), \n                ((if va then p else p_sib), p_gpar)))))) p_par\n  end.\n\n(** For partial treeboxes. *)\nFixpoint partial_treebox_rep (t : list Half_tree) (root b p_par p_top : val) : mpred :=\n  match t with\n  | [] => !! (p_par = p_top /\\ root = b /\\ is_pointer_or_null root) && emp \n  | (va, c, k, v, tg, sib) :: l  =>\n    EX p_gpar: val, EX p_sib : val, EX b_par : val,\n      !! (Int.min_signed <= k <= Int.max_signed) &&\n      !! (b = \n        if va \n        then (field_address t_struct_rbtree [StructField _right] p_par)\n        else (field_address t_struct_rbtree [StructField _left] p_par)) &&\n      rbtree_rep sib p_sib p_par *\n      field_at Tsh t_struct_rbtree [StructField _color] (Vint (Int.repr (Col2Z c))) p_par *\n      field_at Tsh t_struct_rbtree [StructField _key] (Vint (Int.repr k)) p_par *\n      field_at Tsh t_struct_rbtree [StructField _value] (Vint (Int.repr v)) p_par *\n      field_at Tsh t_struct_rbtree [StructField _tag] (Vint (Int.repr tg)) p_par *\n      (if va\n       then (field_at Tsh t_struct_rbtree [StructField _left] p_sib p_par)\n       else (field_at Tsh t_struct_rbtree [StructField _right] p_sib p_par)) *\n      field_at Tsh t_struct_rbtree [StructField _par] p_gpar p_par *\n      data_at Tsh (tptr t_struct_rbtree) p_par b_par *\n      partial_treebox_rep l root b_par p_gpar p_top\n  end.\n\n(** Function specifications. \n\n    In this part, we write specifications for C functions. \n    Each specification contains three parts: \n    1.  What abstract objects are given for this function. \n        (WITH section)\n    2.  Precondition (PRE section)\n    3.  Postcondition (POST section)\n*)\n\n(* mallocN *)\nDefinition mallocN_spec :=\n DECLARE _mallocN\n  WITH n : Z\n  PRE [ tint ]\n     PROP (4 <= n <= Int.max_unsigned)\n     PARAMS (Vint (Int.repr n))\n     SEP ()\n  POST [ tptr tvoid ]\n     EX v : val,\n     PROP (malloc_compatible n v)\n     RETURN (v)\n     SEP (memory_block Tsh n v).\n\n(* freeN *)\nDefinition freeN_spec :=\n DECLARE _freeN\n  WITH p : val , n : Z\n  PRE [ tptr tvoid , tint]\n      PROP() \n      PARAMS (p; Vint (Int.repr n))\n      SEP (memory_block Tsh n p)\n  POST [ tvoid ]\n    PROP () RETURN () SEP ().\n\n(* treebox_new *)\nDefinition treebox_new_spec :=\n DECLARE _treebox_new\n  WITH u : unit\n  PRE  [  ]\n       PROP() PARAMS() SEP ()\n  POST [ tptr (tptr t_struct_rbtree) ]\n    EX v : val,\n    PROP()\n    RETURN (v)\n    SEP (data_at Tsh (tptr t_struct_rbtree) nullval v).\n\n(* treebox_free *)\nDefinition treebox_free_spec :=\n DECLARE _treebox_free\n  WITH t : RBtree, b : val\n  PRE  [ tptr (tptr t_struct_rbtree) ]\n       PROP() PARAMS(b) SEP (treebox_rep t b nullval)\n  POST [ Tvoid ]\n    PROP()\n    RETURN ()\n    SEP (emp).\n\n(* tree_free *)\nDefinition tree_free_spec :=\n DECLARE _tree_free\n  WITH t : RBtree, p : val, p_par : val\n  PRE  [ tptr t_struct_rbtree ]\n    PROP() \n    PARAMS (p) \n    SEP (rbtree_rep t p p_par)\n  POST [ Tvoid ]\n    PROP()\n    RETURN ()\n    SEP (emp).\n\n(* Optt *)\nDefinition Optt_spec :=\n DECLARE _Optt\n  WITH t1 : Tag, t2 : Tag\n  PRE [ tuint , tuint ]\n    PROP () \n    PARAMS (Vint (Int.repr t1); Vint (Int.repr t2))\n    SEP ()\n  POST [ tuint ]\n     PROP ()\n     RETURN (Vint (Int.repr (Optt t1 t2))) \n     SEP ().\n\n(* Opvt *)\nDefinition Opvt_spec :=\n DECLARE _Opvt\n  WITH v : Value, tg : Tag\n  PRE [ tuint , tuint ]\n    PROP () \n    PARAMS (Vint (Int.repr v); Vint (Int.repr tg))\n    SEP ()\n  POST [ tuint ]\n     PROP ()\n     RETURN (Vint (Int.repr (f v tg)))\n     SEP ().\n\n(** Left rotation. \n\n    Here is a diagram to illustrating the given tree:\n\n       l                          r\n      / \\                        / \\\n     /   \\                      /   \\\n    a     r        --->        l     c\n         / \\                  / \\\n        /   \\                /   \\\n       b    c               a    b\n\n*)\nDefinition left_rotate_spec :=\n DECLARE _left_rotate\n  WITH \n    col_l : color, key_l : Key, value_l : Value, tag_l : Tag, pl_par : val, \n    col_r : color, key_r : Key, value_r : Value, tag_r : Tag,\n    ta : RBtree, tb : RBtree, tc : RBtree, \n    pl : val, pr : val, pa : val, pb : val, pc : val\n  PRE [ tptr t_struct_rbtree ]\n    PROP (Int.min_signed <= key_l <= Int.max_signed; \n          is_pointer_or_null pl_par) \n    PARAMS (pl) \n    SEP (data_at Tsh t_struct_rbtree \n            (Vint (Int.repr (Col2Z col_l)), \n              (Vint (Int.repr key_l),\n                (Vint (Int.repr value_l), \n                  (Vint (Int.repr tag_l),\n                    (pa, (pr, pl_par)))))) pl;\n         data_at Tsh t_struct_rbtree \n            (Vint (Int.repr (Col2Z col_r)), \n              (Vint (Int.repr key_r),\n                (Vint (Int.repr value_r), \n                  (Vint (Int.repr tag_r),\n                    (pb, (pc, pl)))))) pr;\n         rbtree_rep ta pa pl;\n         rbtree_rep tb pb pr;\n         rbtree_rep tc pc pr)\n  POST [ tptr t_struct_rbtree ] \n    PROP ()\n    RETURN (pr)\n    SEP (data_at Tsh t_struct_rbtree \n            (Vint (Int.repr (Col2Z col_r)), \n              (Vint (Int.repr key_r),\n                (Vint (Int.repr value_r), \n                  (Vint (Int.repr tag_r),\n                    (pl, (pc, pl_par)))))) pr;\n         data_at Tsh t_struct_rbtree \n            (Vint (Int.repr (Col2Z col_l)), \n              (Vint (Int.repr key_l),\n                (Vint (Int.repr value_l), \n                  (Vint (Int.repr tag_l),\n                    (pa, (pb, pr)))))) pl;\n         rbtree_rep ta pa pl;\n         rbtree_rep tb pb pl;\n         rbtree_rep tc pc pr).\n\n(** A wrapper for left_rotate, considering that rotation may change the root. *)\nDefinition left_rotate_wrap_spec :=\n DECLARE _left_rotate_wrap\n  WITH \n    col_l : color, key_l : Key, value_l : Value, tag_l : Tag, pl_par : val, \n    col_r : color, key_r : Key, value_r : Value, tag_r : Tag,  \n    ta : RBtree, tb : RBtree, tc : RBtree, \n    pl : val, pr : val, pa : val, pb : val, pc : val, \n    root : val, p_root : val, ls : list Half_tree\n  PRE  [ tptr t_struct_rbtree, tptr (tptr t_struct_rbtree) ]\n    PROP (Int.min_signed <= key_l <= Int.max_signed; \n          is_pointer_or_null pl_par) \n    PARAMS (pl; root) \n    SEP (data_at Tsh t_struct_rbtree \n            (Vint (Int.repr (Col2Z col_l)), \n              (Vint (Int.repr key_l),\n                (Vint (Int.repr value_l), \n                  (Vint (Int.repr tag_l),\n                    (pa, (pr, pl_par)))))) pl;\n         data_at Tsh t_struct_rbtree \n            (Vint (Int.repr (Col2Z col_r)), \n              (Vint (Int.repr key_r),\n                (Vint (Int.repr value_r), \n                  (Vint (Int.repr tag_r),\n                    (pb, (pc, pl)))))) pr;\n         rbtree_rep ta pa pl;\n         rbtree_rep tb pb pr;\n         rbtree_rep tc pc pr;\n         partial_tree_rep ls p_root pl pl_par nullval; \n         data_at Tsh (tptr t_struct_rbtree) p_root root)\n  POST [ Tvoid ]\n    EX p_root_new : val, \n    PROP (p_root_new = match ls with nil => pr | _ => p_root end)\n    RETURN ()\n    SEP (data_at Tsh t_struct_rbtree \n            (Vint (Int.repr (Col2Z col_r)), \n              (Vint (Int.repr key_r),\n                (Vint (Int.repr value_r), \n                  (Vint (Int.repr tag_r),\n                    (pl, (pc, pl_par)))))) pr;\n         data_at Tsh t_struct_rbtree \n            (Vint (Int.repr (Col2Z col_l)), \n              (Vint (Int.repr key_l),\n                (Vint (Int.repr value_l), \n                  (Vint (Int.repr tag_l),\n                    (pa, (pb, pr)))))) pl;\n         rbtree_rep ta pa pl;\n         rbtree_rep tb pb pl;\n         rbtree_rep tc pc pr; \n         partial_tree_rep ls p_root_new pr pl_par nullval;\n         data_at Tsh (tptr t_struct_rbtree) p_root_new root).\n\n(** Right rotation. \n\n    Here is a diagram illustrating the given tree:\n\n          r                          l\n         / \\                        / \\\n        /   \\                      /   \\\n       l    c         --->        a    r\n      / \\                             / \\\n     /   \\                           /   \\\n    a    b                          b    c\n\n*)\nDefinition right_rotate_spec :=\n DECLARE _right_rotate\n  WITH \n    col_l : color, key_l : Key, value_l : Value, tag_l : Tag, \n    col_r : color, key_r : Key, value_r : Value, tag_r : Tag, pr_par : val, \n    ta : RBtree, tb : RBtree, tc : RBtree, \n    pl : val, pr : val, pa : val, pb : val, pc : val\n  PRE  [ tptr t_struct_rbtree ]\n    PROP (Int.min_signed <= key_r <= Int.max_signed;\n          is_pointer_or_null pr_par)\n    PARAMS (pr) \n    SEP (data_at Tsh t_struct_rbtree \n            (Vint (Int.repr (Col2Z col_r)), \n              (Vint (Int.repr key_r),\n                (Vint (Int.repr value_r), \n                  (Vint (Int.repr tag_r),\n                    (pl, (pc, pr_par)))))) pr;\n         data_at Tsh t_struct_rbtree \n            (Vint (Int.repr (Col2Z col_l)), \n              (Vint (Int.repr key_l),\n                (Vint (Int.repr value_l), \n                  (Vint (Int.repr tag_l),\n                    (pa, (pb, pr)))))) pl;\n         rbtree_rep ta pa pl;\n         rbtree_rep tb pb pl;\n         rbtree_rep tc pc pr)\n  POST [ tptr t_struct_rbtree ]\n    PROP ()\n    RETURN (pl)\n    SEP (data_at Tsh t_struct_rbtree \n            (Vint (Int.repr (Col2Z col_l)), \n              (Vint (Int.repr key_l),\n                (Vint (Int.repr value_l), \n                  (Vint (Int.repr tag_l),\n                    (pa, (pr, pr_par)))))) pl;\n         data_at Tsh t_struct_rbtree \n            (Vint (Int.repr (Col2Z col_r)), \n              (Vint (Int.repr key_r),\n                (Vint (Int.repr value_r), \n                  (Vint (Int.repr tag_r),\n                    (pb, (pc, pl)))))) pr;\n         rbtree_rep ta pa pl;\n         rbtree_rep tb pb pr;\n         rbtree_rep tc pc pr).\n\n(** A wrapper for right_rotate, considering that rotation may change the root. *)\nDefinition right_rotate_wrap_spec :=\n DECLARE _right_rotate_wrap\n  WITH \n    col_l : color, key_l : Key, value_l : Value, tag_l : Tag, \n    col_r : color, key_r : Key, value_r : Value, tag_r : Tag, pr_par : val, \n    ta : RBtree, tb : RBtree, tc : RBtree, \n    pl : val, pr : val, pa : val, pb : val, pc : val, \n    root : val, p_root : val, ls : list Half_tree\n  PRE  [ tptr t_struct_rbtree, tptr (tptr t_struct_rbtree) ]\n    PROP (Int.min_signed <= key_r <= Int.max_signed;\n          is_pointer_or_null pr_par)\n    PARAMS (pr; root) \n    SEP (data_at Tsh t_struct_rbtree \n            (Vint (Int.repr (Col2Z col_r)), \n              (Vint (Int.repr key_r),\n                (Vint (Int.repr value_r), \n                  (Vint (Int.repr tag_r),\n                    (pl, (pc, pr_par)))))) pr;\n         data_at Tsh t_struct_rbtree \n            (Vint (Int.repr (Col2Z col_l)), \n              (Vint (Int.repr key_l),\n                (Vint (Int.repr value_l), \n                  (Vint (Int.repr tag_l),\n                    (pa, (pb, pr)))))) pl;\n         rbtree_rep ta pa pl;\n         rbtree_rep tb pb pl;\n         rbtree_rep tc pc pr; \n         partial_tree_rep ls p_root pr pr_par nullval;\n         data_at Tsh (tptr t_struct_rbtree) p_root root)\n  POST [ Tvoid ]\n    EX p_root_new : val, \n    PROP (p_root_new = match ls with nil => pl | _ => p_root end)\n    RETURN ()\n    SEP (data_at Tsh t_struct_rbtree \n            (Vint (Int.repr (Col2Z col_l)), \n              (Vint (Int.repr key_l),\n                (Vint (Int.repr value_l), \n                  (Vint (Int.repr tag_l),\n                    (pa, (pr, pr_par)))))) pl;\n         data_at Tsh t_struct_rbtree \n            (Vint (Int.repr (Col2Z col_r)), \n              (Vint (Int.repr key_r),\n                (Vint (Int.repr value_r), \n                  (Vint (Int.repr tag_r),\n                    (pb, (pc, pl)))))) pr;\n         rbtree_rep ta pa pl;\n         rbtree_rep tb pb pr;\n         rbtree_rep tc pc pr; \n         partial_tree_rep ls p_root_new pl pr_par nullval;\n         data_at Tsh (tptr t_struct_rbtree) p_root_new root).\n\n(* tag_tree_t *)\nDefinition tag_tree_t_spec :=\n DECLARE _tag_tree_t\n  WITH t : RBtree, tg : Tag, p : val, p_par : val\n  PRE  [ tptr (Tstruct _tree noattr), tuint ]\n    PROP () \n    PARAMS (p; Vint (Int.repr tg)) \n    SEP (rbtree_rep t p p_par)\n  POST [ Tvoid ]\n    PROP ()\n    RETURN ()\n    SEP (rbtree_rep (tag_tree_t tg t) p p_par).\n\n(* pushdown *)\nDefinition pushdown_spec :=\n DECLARE _pushdown\n  WITH \n    c : color, k : Key, v : Value, tg : Tag, \n    p_lch : val, p_rch : val, p_par : val, p : val,\n    (* first is the information about the tree *)\n    lch : RBtree, rch : RBtree\n  PRE  [ tptr t_struct_rbtree ]\n    PROP () \n    PARAMS (p) \n    SEP (data_at Tsh t_struct_rbtree\n          (Vint (Int.repr (Col2Z c)),\n          (Vint (Int.repr k),\n          (Vint (Int.repr v),\n          (Vint (Int.repr tg),\n          (p_lch, (p_rch, p_par)))))) p;\n        rbtree_rep lch p_lch p;\n        rbtree_rep rch p_rch p)\n  POST [ Tvoid ]\n    PROP ()\n    RETURN ()\n    SEP (data_at Tsh t_struct_rbtree\n          (Vint (Int.repr (Col2Z c)),\n          (Vint (Int.repr k),\n          (Vint (Int.repr (f v tg)),\n          (Vint (Int.repr default),\n          (p_lch, (p_rch, p_par)))))) p;\n        rbtree_rep (tag_tree_t tg lch) p_lch p;\n        rbtree_rep (tag_tree_t tg rch) p_rch p).\n\n(* make_black *)\nDefinition make_black_spec :=\n DECLARE _make_black\n  WITH t : RBtree, root : val\n  PRE  [ tptr (tptr t_struct_rbtree) ]\n    PROP () \n    PARAMS (root) \n    SEP (treebox_rep t root nullval)\n  POST [ Tvoid ]\n    PROP ()\n    RETURN ()\n    SEP (treebox_rep (makeBlack t) root nullval). \n\n(* get_color *)\nDefinition get_color_spec :=\n DECLARE _get_color\n  WITH t : RBtree, p : val, p_par: val\n  PRE  [ tptr t_struct_rbtree ]\n    PROP () \n    PARAMS (p) \n    SEP (rbtree_rep t p p_par)\n  POST [ tint ]\n    PROP ()\n    RETURN (Vint (Int.repr (get_color_tree t)))\n    SEP (rbtree_rep t p p_par). \n\n(* update *)\nDefinition update_spec :=\n  DECLARE _update\n  WITH root : val, t : RBtree, tg : Tag, targ_lo : Key, targ_hi : Key\n  PRE  [ tptr (tptr (Tstruct _tree noattr)), tuint, tint, tint ]\n    PROP (Int.min_signed <= targ_lo <= Int.max_signed;\n          Int.min_signed <= targ_hi <= Int.max_signed) \n    PARAMS (root; Vint (Int.repr tg); Vint (Int.repr targ_lo);\n            Vint (Int.repr targ_hi)) \n    SEP (treebox_rep t root nullval)\n  POST [ Tvoid ]\n    PROP ()\n    RETURN ()\n    SEP (treebox_rep (change_segment' targ_lo targ_hi tg t \n      Int.min_signed Int.max_signed) root nullval). \n\n(* update_aux *)\nDefinition update_aux_spec :=\n  DECLARE _update_aux\n  WITH p : val, p_par : val, t : RBtree, tg : Tag, \n      targ_lo : Key, targ_hi : Key, lo : Key, hi : Key\n  PRE  [ tptr (Tstruct _tree noattr), tuint, tint, tint, \n    tint, tint ]\n    PROP (Int.min_signed <= targ_lo <= Int.max_signed;\n          Int.min_signed <= targ_hi <= Int.max_signed; \n          Int.min_signed <= lo <= Int.max_signed;\n          Int.min_signed <= hi <= Int.max_signed;\n          targ_lo <= targ_hi) \n    PARAMS (p; Vint (Int.repr tg); \n            Vint (Int.repr lo);\n            Vint (Int.repr hi);\n            Vint (Int.repr targ_lo);\n            Vint (Int.repr targ_hi)) \n    SEP (rbtree_rep t p p_par)\n  POST [ Tvoid ]\n    PROP ()\n    RETURN ()\n    SEP (rbtree_rep (change_segment' targ_lo targ_hi tg t lo hi) p p_par).\n\n(* tree_minimum *)\nDefinition tree_minimum_spec :=\n DECLARE _tree_minimum\n  WITH t : RBtree, b: val, p_par: val\n  PRE  [ tptr (tptr t_struct_rbtree) ]\n    PROP (t <> Empty) \n    PARAMS (b) \n    SEP (treebox_rep t b p_par)\n  POST [ tptr (tptr t_struct_rbtree) ]\n    EX min_b : val, \n    EX min_p_par : val, \n    EX min_ls : list Half_tree,\n    EX min_tree_c : color, \n    EX min_tree_k : Key, \n    EX min_tree_v : Value, \n    EX min_tree_sib : RBtree, \n    PROP (Up_split (minimum_split default t nil) =\n       (min_ls, T min_tree_c Empty min_tree_k min_tree_v default min_tree_sib); \n       Forall turn_left min_ls; \n       Forall tag_default min_ls)\n    RETURN (min_b)\n    SEP (treebox_rep (T min_tree_c Empty min_tree_k min_tree_v default min_tree_sib) min_b min_p_par; \n      partial_treebox_rep min_ls b min_b min_p_par p_par). \n\n(** Rebalance after insertion.\n\n    Both its input and output are sets of treeboxes and \n    partial treeboxes.\n*)\nDefinition insert_balance_spec :=\n  DECLARE _insert_balance\n  WITH t_initial: RBtree, \n      root: val,\n      p_par_initial: val,\n      b_initial: val, \n      ls_initial: list Half_tree\n  PRE  [ tptr (tptr t_struct_rbtree), \n      tptr (tptr t_struct_rbtree) ]\n    PROP (t_initial <> Empty)\n    PARAMS (b_initial; root) \n    SEP (treebox_rep t_initial b_initial p_par_initial; \n      partial_treebox_rep ls_initial root b_initial \n        p_par_initial nullval)\n  POST [ Tvoid ]\n    EX t_balanced: RBtree, \n    EX ls_balanced: list Half_tree, \n    EX b_balanced: val, \n    EX p_par_balanced: val,\n    PROP ((ls_balanced, t_balanced) = balance' ls_initial t_initial)\n    RETURN ()\n    SEP (treebox_rep t_balanced b_balanced p_par_balanced; \n        partial_treebox_rep ls_balanced root b_balanced \n          p_par_balanced nullval).\n\n(** Rebalance after deletion.\n\n    This is much like that of insertion.\n*)\nDefinition delete_balance_spec :=\n  DECLARE _delete_balance\n  WITH t_initial: RBtree, \n      root: val,\n      p_initial : val, \n      p_par_initial : val,\n      b_initial: val, \n      ls_initial: list Half_tree\n  PRE  [ tptr t_struct_rbtree, \n      tptr t_struct_rbtree,\n      tptr (tptr t_struct_rbtree) ]\n    PROP (delete_check t_initial ls_initial Black = true)    \n    PARAMS (p_initial; p_par_initial; root) \n    SEP (rbtree_rep t_initial p_initial p_par_initial;\n      data_at Tsh (tptr t_struct_rbtree) p_initial b_initial;\n      partial_treebox_rep ls_initial root b_initial p_par_initial nullval)\n  POST [ Tvoid ]\n    EX t_balanced: RBtree, \n    EX ls_balanced: list Half_tree, \n    EX b_balanced: val, \n    EX p_par_balanced: val,\n    PROP (complete_tree_revarg (t_balanced, ls_balanced) = \n      complete_tree_revarg (delete_balance t_initial ls_initial Black))\n    RETURN ()\n    SEP (treebox_rep t_balanced b_balanced p_par_balanced; \n        partial_treebox_rep ls_balanced root b_balanced p_par_balanced nullval).\n\n(* insert *)\nDefinition insert_spec :=\n DECLARE _insert\n  WITH t : RBtree, root : val, x : Key, v : Value\n  PRE  [ tptr (tptr t_struct_rbtree), tint, tuint ]\n    PROP (Int.min_signed <= x <= Int.max_signed) \n    PARAMS (root; Vint (Int.repr x); Vint (Int.repr v))\n    SEP (treebox_rep t root nullval)\n  POST [ Tvoid ]\n    EX t_complete : RBtree, \n    PROP (insert x v t t_complete)\n    RETURN ()\n    SEP (treebox_rep t_complete root nullval).\n\n(* delete *)\nDefinition delete_spec :=\n DECLARE _delete\n  WITH t : RBtree, root : val, x : Key\n  PRE  [ tptr (tptr t_struct_rbtree), tint ]\n    PROP (Int.min_signed <= x <= Int.max_signed; \n      let '(ls, base, co) := delete_with_no_balance x t\n      in (delete_check base ls co = true))\n    PARAMS (root; Vint (Int.repr x))\n    SEP (treebox_rep t root nullval)\n  POST [ Tvoid ]\n    EX t_complete : RBtree, \n    PROP ()\n    RETURN ()\n    SEP (treebox_rep (delete x t) root nullval).\n\n(* lookup *)\nDefinition lookup_spec :=\n DECLARE _lookup\n  WITH t : RBtree, x : Key, p : val, p_par : val\n  PRE  [ tptr t_struct_rbtree, tint ]\n    PROP (Int.min_signed <= x <= Int.max_signed; \n      is_pointer_or_null p_par) \n    PARAMS (p; Vint (Int.repr x)) \n    SEP (rbtree_rep t p p_par)\n  POST [ tuint ]\n    PROP ()\n    RETURN (Vint (Int.repr (Lookup2Z x t)))\n    SEP (rbtree_rep t p p_par).\n\n(* all functions of the program *)\nDefinition Gprog : funspecs :=\n  ltac:(with_library prog [\n    mallocN_spec;           (* vacuous truth! *)\n    freeN_spec;             (* vacuous truth! *)\n    Optt_spec;              (* OK! *)\n    Opvt_spec;              (* OK! *)\n    treebox_new_spec;       (* OK! *)\n    tree_free_spec;         (* OK! *)\n    treebox_free_spec;      (* OK! *)\n    left_rotate_spec;       (* OK! *)\n    right_rotate_spec;      (* OK! *)\n    left_rotate_wrap_spec;  (* OK! *)\n    right_rotate_wrap_spec; (* OK! *)\n    tag_tree_t_spec;        (* OK! *)\n    insert_spec;            (* OK! *)\n    make_black_spec;        (* OK! *)\n    get_color_spec;         (* OK! *)\n    insert_balance_spec;    (* OK! *)\n    lookup_spec;            (* OK! *)\n    update_aux_spec;        (* OK! *)\n    update_spec;            (* OK! *) \n    pushdown_spec;          (* OK! *)\n    tree_minimum_spec;      (* OK! *)\n    delete_balance_spec;    (* OK! *)\n    delete_spec             (* OK! *)\n  ]).\n\nDefinition treemap_rep (mp: relate_map) (b: val) :=\n  EX t: RBtree, !! (SearchTree' Int.min_signed t Int.max_signed /\\ \n    Abs t mp /\\ is_redblack t) && treebox_rep t b nullval. \n\nDefinition abs_treebox_new_spec :=\n DECLARE _treebox_new\n  WITH u : unit\n  PRE  [  ]\n       PROP() PARAMS() SEP ()\n  POST [ tptr (tptr t_struct_rbtree) ]\n    EX b : val,\n    PROP ()\n    RETURN (b)\n    SEP (treemap_rep relate_default b).\n\nLemma subsume_treebox_new : funspec_sub (snd treebox_new_spec) (snd abs_treebox_new_spec).\nProof.\n  do_funspec_sub.\n  clear H.\n  Exists emp.\n  entailer!.\n  intros.\n  Exists (eval_id ret_temp x).\n  unfold treemap_rep.\n  Exists Empty.\n  entailer!.\n  - split; try split.\n    + apply ST_E. apply minsigned_lt_maxsigned.\n    + exact Abs_E.\n    + unfold is_redblack. split.\n      * apply IsRB_co_leaf.\n      * exists O. apply IsRB_dep_em.\n  - unfold treebox_rep.\n    Exists nullval.\n    simpl rbtree_rep.\n    entailer!.\nQed.\n\nDefinition abs_treebox_free_spec :=\n DECLARE _treebox_free\n  WITH mp: relate_map, b: val\n  PRE  [ tptr (tptr t_struct_rbtree) ]\n       PROP() PARAMS(b) SEP (treemap_rep mp b)\n  POST [ Tvoid ]\n    PROP()\n    RETURN()\n    SEP (emp).\n\nLemma subsume_treebox_free : funspec_sub (snd treebox_free_spec) (snd abs_treebox_free_spec).\nProof.\n  do_funspec_sub.\n  destruct w as [mp b].\n  clear H.\n  simpl. normalize.\n  unfold treemap_rep.\n  Intros t. \n  Exists (t, b) emp.\n  entailer!.\nQed.\n\n(* insert *)\nDefinition abs_insert_spec :=\n DECLARE _insert\n  WITH mp: relate_map, x: Key, v: Value, b: val\n  PRE  [ tptr (tptr t_struct_rbtree), tint, tuint ]\n    PROP (Int.min_signed < x < Int.max_signed) \n    PARAMS (b; Vint (Int.repr x); Vint (Int.repr v))\n    SEP (treemap_rep mp b)\n  POST [ Tvoid ]\n    PROP ()\n    RETURN ()\n    SEP (treemap_rep (v_update x v mp) b).\n\nLemma subsume_insert : funspec_sub (snd insert_spec) (snd abs_insert_spec).\nProof.\n  do_funspec_sub.\n  destruct w as [[[mp x] v] b].\n  clear H.\n  simpl. normalize.\n  unfold treemap_rep.\n  Intros t.\n  unfold treebox_rep.\n  Intros p.\n  Exists (t, b, x, v) emp.\n  entailer!.\n  2: { Exists p. entailer!. }\n  intros. \n  Exists x1 x2.\n  entailer!.\n  split; try split.\n  - assert (SearchTree t). { eapply ST_intro; try eassumption. }\n    pose proof insert_st t x v x1 H9 H7.\n    eapply insert_st'; eauto.\n  - assert (SearchTree t). { eapply ST_intro;try eassumption. }\n    apply (insert_relate t x v mp x1 H9 H2 H7).\n  - eapply insert_redblack. \n    + apply H3.\n    + apply H7.\nQed.\n\n(* delete *)\nDefinition abs_delete_spec :=\n DECLARE _delete\n  WITH mp: relate_map, b: val, x: Key\n  PRE  [ tptr (tptr t_struct_rbtree), tint ]\n    PROP (Int.min_signed < x < Int.max_signed)\n    PARAMS (b; Vint (Int.repr x))\n    SEP (treemap_rep mp b)\n  POST [ Tvoid ]\n    EX t_complete : RBtree, \n    PROP ()\n    RETURN ()\n    SEP (treemap_rep (k_delete x mp) b).\n\nLemma subsume_delete : funspec_sub (snd delete_spec) (snd abs_delete_spec).\nProof.\n  do_funspec_sub.\n  destruct w as [[mp b] k].\n  assert (exists (kk : Key), k = kk). { exists k. auto. }\n  (* to avoid type alias issues *)\n  destruct H0 as [kk H0].\n  subst k.\n  rename kk into k.  \n  clear H.\n  unfold treemap_rep.\n  Intros t.\n  unfold treebox_rep.\n  Intros p.\n  simpl.\n  normalize.\n  Exists (t, b, k) emp.\n  remember (delete_with_no_balance k t) as pp1.\n  destruct pp1 as [[ls base] co].\n  entailer!.\n  2: { Exists p. entailer!. }\n  split.\n  2: {\n    destruct co.\n    - destruct base; destruct ls; auto.\n    - assert (SearchTree t). { eapply ST_intro;try eassumption. }\n      pose proof delete_with_no_balance_st k t base ls Black H6 Heqpp1.\n      do 3  destruct H7.\n      pose proof delete_dep_with_nobalance k t ls base H6 H3 Heqpp1.\n      destruct H9. destruct H9. destruct H9.\n      pose proof delete_co_with_nobalance k t ls base H6 H3 Heqpp1.\n      destruct H11.\n      pose proof delete_check_Black ls base x x0 x1 x2.\n      eapply H13;try eassumption. \n  }\n  intros.\n  Intros x.\n  Exists (delete k t).\n  Exists x.\n  entailer!.\n  split; try split.\n  - assert (SearchTree t). { eapply ST_intro;try eassumption. }\n    pose proof delete_st k t H8.\n    eapply delete_st';eauto.\n  - apply delete_relate; auto.\n    econstructor. apply H1.\n  - eapply (delete_redblack k ). \n    + econstructor. apply H1.\n    + apply H3.\n    + auto.\nQed.\n\n(* segment_update *)\nDefinition abs_update_spec :=\n  DECLARE _update\n  WITH root: val, mp: relate_map, tg: Tag, targ_lo: Key, targ_hi: Key\n  PRE  [ tptr (tptr t_struct_rbtree), tuint, tint, tint ]\n    PROP (Int.min_signed <= targ_lo <= Int.max_signed;\n          Int.min_signed <= targ_hi <= Int.max_signed) \n    PARAMS (root; Vint (Int.repr tg); Vint (Int.repr targ_lo);\n            Vint (Int.repr targ_hi)) \n    SEP (treemap_rep mp root)\n  POST [ Tvoid ]\n    PROP ()\n    RETURN ()\n    SEP (treemap_rep (segment_update targ_lo targ_hi tg mp) root).\n\nLemma subsume_update : funspec_sub (snd update_spec) (snd abs_update_spec).\nProof.\n  do_funspec_sub.\n  destruct w as [[[[root mp] tg] targ_lo] targ_hi].\n  clear H.\n  simpl. normalize.\n  unfold treemap_rep.\n  Intros t.\n  unfold treebox_rep.\n  Intros p.\n  Exists (root, t, tg, targ_lo, targ_hi) emp.\n  entailer!.\n  2: { Exists p. entailer!. }\n  intros.\n  assert (Ha : exists (a : Key), a = targ_lo). { exists targ_lo . auto. }\n  destruct Ha as [a Ha]. subst targ_lo. rename a into targ_lo.\n  assert (Ha : exists (a : Key), a = targ_hi). { exists targ_hi . auto. }\n  destruct Ha as [a Ha]. subst targ_hi. rename a into targ_hi.\n  remember (change_segment' targ_lo targ_hi tg t Int.min_signed Int.max_signed) as t_res.\n  Exists t_res.\n  assert (Hfinal : change_segment targ_lo targ_hi tg t t_res).\n  { subst t_res. econstructor; auto. }\n  Exists x0.\n  entailer!.\n  split; try split.\n  - apply segment_st_pre. auto.\n  - apply segement_abs; assumption.\n  - eapply segement_keep. \n    3: { apply Hfinal. }\n    + econstructor. apply H3.\n    + apply H5.\nQed.\n\n(** Simple lemmas about representation predicates.\n\n    The following lemmas are proved to help automation of VST.\n    They will not appear frequently in the proof. Also, considering\n    newer versions of VST, we explicitly export them to hint database.\n*)\n\nLemma rbtree_rep_saturate_local:\n   forall t p p_par, rbtree_rep t p p_par |-- !! is_pointer_or_null p.\nProof.\n  destruct t; simpl; intros.\n  entailer!.\n  Intros pa pb. entailer!.\nQed.\n(* #[export] *)Hint Resolve rbtree_rep_saturate_local: saturate_local.\n\nLemma rbtree_rep_saturate_local_parent:\n   forall t p p_par, rbtree_rep t p p_par |-- !! is_pointer_or_null p_par.\nProof.\n  destruct t; simpl; intros.\n  entailer!.\n  Intros pa pb. entailer!.\nQed.\n(* #[export] *)Hint Resolve rbtree_rep_saturate_local_parent: saturate_local.\n\nLemma rbtree_rep_valid_pointer:\n  forall t p p_par, rbtree_rep t p p_par |-- valid_pointer p.\nProof.\n  intros.\n  destruct t. \n  - simpl. entailer!.\n  - simpl; normalize; auto with valid_pointer.\nQed.\n(* #[export] *)Hint Resolve rbtree_rep_valid_pointer: valid_pointer.\n\nLemma treebox_rep_saturate_local:\n  forall t b p_par, treebox_rep t b p_par |-- \n    !! field_compatible (tptr t_struct_rbtree) [] b.\nProof.\n  intros.\n  unfold treebox_rep.\n  Intros p.\n  entailer!.\nQed.\n(* #[export] *)Hint Resolve treebox_rep_saturate_local: saturate_local.\n\nLemma treebox_rep_saturate_local':\n   forall t b p_par, treebox_rep t b p_par |-- !! is_pointer_or_null b.\nProof.\n  intros.\n  unfold treebox_rep.\n  Intros p.\n  entailer!.\nQed.\n(* #[export] *)Hint Resolve treebox_rep_saturate_local': saturate_local.\n\nLemma treebox_rep_saturate_local_parent:\n  forall t b p_par, treebox_rep t b p_par |-- \n    !! (is_pointer_or_null p_par).\nProof.\n  intros.\n  unfold treebox_rep.\n  Intros p.\n  entailer!.\nQed.\n(* #[export] *)Hint Resolve treebox_rep_saturate_local_parent: saturate_local.\n\nLemma treebox_rep_valid_pointer:\n   forall t b p_par, treebox_rep t b p_par |-- valid_pointer b.\nProof.\n  intros.\n  unfold treebox_rep.\n  Intros p.\n  entailer!.\nQed.\n(* #[export] *)Hint Resolve treebox_rep_valid_pointer: valid_pointer.\n\nLemma partial_tree_rep_saturate_local_parent:\n  forall ls root p p_par, \n    partial_tree_rep ls root p p_par nullval |-- \n      !! is_pointer_or_null p_par.\nProof.\n  intros.\n  destruct ls.\n  - simpl. entailer!.\n  - destruct h as [[[[[va c] k] v] tg] sib].\n    destruct va; simpl; normalize; auto with valid_pointer; entailer!.\nQed.\n(* #[export] *)Hint Resolve partial_tree_rep_saturate_local_parent: saturate_local.\n\nLemma partial_tree_rep_saturate_local_parent_ptop:\n  forall ls root p p_par p_top,\n    is_pointer_or_null p_top ->\n    partial_tree_rep ls root p p_par p_top |-- \n      !! is_pointer_or_null p_par.\nProof.\n  intros.\n  destruct ls.\n  - simpl. entailer!.\n  - destruct h as [[[[[va c] k] v] tg] sib].\n    destruct va; simpl; normalize; auto with valid_pointer; entailer!.\nQed.\n(* #[export] *)Hint Resolve partial_tree_rep_saturate_local_parent_ptop: saturate_local.\n\nLemma partial_tree_rep_valid_pointer_parent:\n  forall ls root p p_par, \n    partial_tree_rep ls root p p_par nullval |-- valid_pointer p_par.\nProof.\n  intros.\n  destruct ls.\n  - simpl. entailer!.\n  - destruct h as [[[[[va c] k] v] tg] sib].\n    destruct va; simpl; normalize; auto with valid_pointer; entailer!.\nQed.\n(* #[export] *)Hint Resolve partial_tree_rep_valid_pointer_parent: valid_pointer.\n\nLemma partial_treebox_rep_saturate_local_parent:\n  forall ls root b p_par, \n    partial_treebox_rep ls root b p_par nullval |-- \n      !! is_pointer_or_null p_par.\nProof.\n  intros.\n  destruct ls.\n  - simpl. entailer!.\n  - destruct ls; destruct h as [[[[[va c] k] v] tg] sib];\n    destruct va; simpl; normalize; auto with valid_pointer; entailer!.\nQed.\n(* #[export] *)Hint Resolve partial_treebox_rep_saturate_local_parent: saturate_local.\n\nLemma partial_treebox_rep_saturate_local_parent_ptop:\n  forall ls root b p_par p_top, \n    is_pointer_or_null p_top ->\n    partial_treebox_rep ls root b p_par p_top |-- \n      !! is_pointer_or_null p_par.\nProof.\n  intros.\n  destruct ls.\n  - simpl. entailer!.\n  - destruct ls; destruct h as [[[[[va c] k] v] tg] sib];\n    destruct va; simpl; normalize; auto with valid_pointer; entailer!.\nQed.\n(* #[export] *)Hint Resolve partial_treebox_rep_saturate_local_parent_ptop: saturate_local.\n\nLemma partial_treebox_rep_valid_pointer_parent:\n  forall ls root b p_par,\n    partial_treebox_rep ls root b p_par nullval |-- valid_pointer p_par.\nProof.\n  intros.\n  destruct ls.\n  - simpl partial_treebox_rep. entailer!.\n  - destruct h as [[[[[va c] k] v] tg] sib].\n    simpl.\n    destruct va; Intros p_gpar p_sib b_par; Intros;\n      rewrite field_at_data_at'; entailer!.\nQed.\n(* #[export] *)Hint Resolve partial_treebox_rep_valid_pointer_parent: valid_pointer.\n\n(** This lemma is only useful for the current definition. \n    For further use, we may need share accounting. *)\nLemma field_color_valid_pointer:\n  forall c p, \n    field_at Tsh t_struct_rbtree [StructField _color] (Vint (Int.repr (Col2Z c))) p\n    |-- valid_pointer p.\nProof.\n  intros.\n  rewrite field_at_data_at'.\n  entailer!.\nQed.\n(* #[export] *)Hint Resolve field_color_valid_pointer: valid_pointer.\n\nLtac aggregate_solve :=\n  try (repeat sep_apply rbtree_rep_saturate_local; Intros; entailer!);\n  try (repeat sep_apply rbtree_rep_saturate_local_parent; Intros; entailer!);\n  try (repeat sep_apply partial_tree_rep_saturate_local_parent; Intros; entailer!);\n  try (repeat sep_apply partial_tree_rep_saturate_local_parent_ptop; Intros; entailer!);\n  try (repeat sep_apply partial_treebox_rep_saturate_local_parent; Intros; entailer!);\n  try (repeat sep_apply partial_treebox_rep_saturate_local_parent_ptop; Intros; entailer!).\n\n(** Other lemmas about representation predicates.\n\n    The following lemmas are about intrinsic properties of\n    those predicates. They will be useful in our proof.\n*)\n\nLocal Open Scope logic.\n\nLemma rbtree_rep_nullval : forall (t: RBtree) p_par, \n  rbtree_rep t nullval p_par |-- !! (t = Empty) && !! (is_pointer_or_null p_par) && emp.\nProof.\n  intros. \n  destruct t.\n  - simpl. entailer!.\n  - simpl rbtree_rep. Intros. Intros p_lch p_rch.\n    entailer!.\n    assert_PROP(False) by entailer!.\n    contradiction. \nQed.\n\nLemma data_at_rbtree_nullval : forall h, \n  data_at Tsh t_struct_rbtree h nullval |-- !! False.\nProof.\n  intros.\n  entailer!.\nQed.\n\nLemma partialtreebox_backward : \n  forall ls va c k v tg sib root b p_par p_top,\n  !! (is_pointer_or_null b) &&\n  partial_treebox_rep (ls ++ [(va, c, k, v, tg, sib)]) root b p_par p_top |--\n    EX p : val, EX p_sib : val, \n    !! (Int.min_signed <= k <= Int.max_signed) &&\n    rbtree_rep sib p_sib p *\n    field_at Tsh t_struct_rbtree [StructField _color] (Vint (Int.repr (Col2Z c))) p *\n    field_at Tsh t_struct_rbtree [StructField _key] (Vint (Int.repr k)) p *\n    field_at Tsh t_struct_rbtree [StructField _value] (Vint (Int.repr v)) p *\n    field_at Tsh t_struct_rbtree [StructField _tag] (Vint (Int.repr tg)) p *\n    (if va\n     then (field_at Tsh t_struct_rbtree [StructField _left] p_sib p)\n     else (field_at Tsh t_struct_rbtree [StructField _right] p_sib p)) *\n    field_at Tsh t_struct_rbtree [StructField _par] p_top p *\n    data_at Tsh (tptr t_struct_rbtree) p root *\n    (if va\n     then (partial_treebox_rep ls (field_address t_struct_rbtree [StructField _right] p) b p_par p)\n     else (partial_treebox_rep ls (field_address t_struct_rbtree [StructField _left] p) b p_par p)).\nProof.\n  intros.\n  revert b p_par.\n  induction ls; intros.\n  - simpl app.\n    simpl partial_treebox_rep.\n    Intros p_gpar p_sib b_par.\n    destruct va; Intros; subst; Exists p_par p_sib; entailer!. \n  - destruct a as [[[[[va' c'] k'] v'] tg'] sib'].\n    simpl partial_treebox_rep.\n    Intros p_gpar p_sib b_par.\n    destruct va'; \n      assert_PROP (is_pointer_or_null b_par) by entailer!; \n      sep_apply IHls; try assumption;\n      Intros p p_sib0;\n      destruct va;\n        Exists p p_sib0;\n        Exists p_gpar p_sib b_par;\n        entailer!.\nQed.\n(** This also shows that in a partial treebox,\n    if b with the least height satisfies is_pointer_or_null, \n    then all the other b's will also satisfy it.\n*)\n\nLemma general_split_tag :\n  forall t lbool rbool t_tree hft_list, \n  general_split lbool rbool t t_tree hft_list =\n  general_split lbool rbool default (tag_tree_t t t_tree) hft_list.  \nProof.\n  intros. \n  destruct t_tree.\n  - simpl. reflexivity.\n  - simpl.\n    destruct lbool eqn:E.\n    + do 5 f_equal.\n      lia.\n    + destruct rbool eqn:E'.\n      * do 5 f_equal. lia.\n      * do 5 f_equal.\nQed.\n\n(* several lemmas about colors *)\nLemma col_not_0: forall col, Int.repr (Col2Z col) <> Int.repr 0 -> col = Red.\nProof.\n  intros. \n  destruct col; [ auto | simpl Col2Z in *; unfold BLACK_COLOR in *; contradiction ].\nQed.\n\nLemma col_not_1: forall col, Int.repr (Col2Z col) <> Int.repr 1 -> col = Black.\nProof.\n  intros.\n  destruct col; [ simpl Col2Z in *; unfold RED_COLOR in *; contradiction | auto ].\nQed.\n\nLemma col_is_black: forall col, Int.repr (Col2Z col) = Int.repr 0 -> col = Black.\nProof.\n  intros. destruct col; [ discriminate | auto ].\nQed.\n\nLemma col_is_red: forall col, Int.repr (Col2Z col) = Int.repr 1 -> col = Red.\nProof.\n  intros. destruct col; [ auto | discriminate ].\nQed.\n\n(* a small tactic used to determine color and to substitution *)\nLtac color_replace :=\n  match goal with\n  | x : Int.repr (Col2Z ?c) = Int.repr 0 |- _ => \n    try (apply col_is_black in x; subst c)\n  | x : Int.repr (Col2Z ?c) = Int.repr 1 |- _ => \n    try (apply col_is_red in x; subst c)\n  | x : Int.repr (Col2Z ?c) <> Int.repr 0 |- _ =>\n    try (apply col_not_0 in x; subst c)\n  | x : Int.repr (Col2Z ?c) <> Int.repr 1 |- _ =>\n    try (apply col_not_1 in x; subst c)\n  end.\n\n(** Reconstruction lemma for treeboxes and partial treeboxes. \n\n    We can apply it to reconstruct a tree from a treebox and\n    a partial treebox. Here, a treebox is unfolded so that the \n    the premise becomes weaker. \n*)\nLemma reconstruction_lemma_box : \n  forall ls t (p p_par root b : val), \n  data_at Tsh (tptr t_struct_rbtree) p b * rbtree_rep t p p_par *\n    partial_treebox_rep ls root b p_par nullval\n  |-- treebox_rep (complete_tree ls t) root nullval.\nProof.\n  intros ls.\n  induction ls as [ | a ls' IH ]; intros.\n  - simpl.\n    Intros.\n    unfold treebox_rep.\n    Exists p.\n    subst p_par. subst b.\n    entailer!.\n  - destruct a as [[[[[va c] k] v] tg] sib].\n    simpl partial_treebox_rep.\n    Intros p_gpar p_sib b_par.\n    pose proof (IH (T c \n      (if va then sib else t) \n        k v tg (if va then t else sib))\n        p_par p_gpar root b_par) as HIH.\n    clear IH.\n    apply derives_trans with (Q:=\n      (data_at Tsh (tptr t_struct_rbtree) p_par b_par *\n      rbtree_rep (T c (if va then sib else t) \n        k v tg (if va then t else sib)) p_par p_gpar *\n      partial_treebox_rep ls' root b_par p_gpar nullval)).\n    {\n      simpl rbtree_rep.\n      Exists (if va then p_sib else p) (if va then p else p_sib).\n      unfold_data_at (data_at _ _ _ p_par).\n      destruct va; Intros; entailer!.\n    }\n    {\n      sep_apply HIH.\n      destruct va; simpl complete_tree; \n      apply derives_refl.\n    }\nQed.\n\n(** Reconstruction lemma for subtrees and partial trees. *) \nLemma reconstruction_lemma : \n  forall ls t root p p_par p_top, \n  !! (is_pointer_or_null p_top) &&\n    rbtree_rep t p p_par * partial_tree_rep ls root p p_par p_top\n  |-- rbtree_rep (complete_tree ls t) root p_top.\nProof.\n  intros ls.\n  induction ls as [ | a ls' IH ]; intros.\n  - simpl.\n    Intros.\n    entailer!.\n  - destruct a as [[[[[va c] k] v] tg] sib].\n    simpl partial_tree_rep.\n    Intros p_gpar p_sib.\n    simpl complete_tree.\n    specialize IH with (t := \n      (if va \n        then (T c sib k v tg t) \n        else (T c t k v tg sib))) (p:=p_par) (p_par:=p_gpar).\n    cancel.\n    destruct va; \n      eapply derives_trans; try apply IH;\n      entailer!;\n      simpl rbtree_rep;\n      [ Exists p_sib p | Exists p p_sib ];\n      entailer!.\nQed.\n\n(** Equivalence Lemma (with box -> without box). *)\nLemma equivalence_box_nobox : \n  forall ls p b root p_par p_top,\n  !! (is_pointer_or_null p_top) &&\n    data_at Tsh (tptr t_struct_rbtree) p b *\n    partial_treebox_rep ls root b p_par p_top\n  |-- EX p_root, partial_tree_rep ls p_root p p_par p_top *\n      data_at Tsh (tptr t_struct_rbtree) p_root root.\nProof.\n  intros ls.\n  induction ls as [ | a ls' IH ]; intros.\n  - simpl. Exists p. entailer.\n  - destruct a as [[[[[va c] k] v] tg] sib].\n    simpl.\n    Intros p_gpar p_sib b_par.\n    destruct va;\n      sep_apply (IH p_par); try auto;\n      Intros p_root;\n      Exists p_root p_gpar p_sib;\n      unfold_data_at (data_at _ _ _ p_par);\n      entailer!.\nQed.\n\n(** Equivalence Lemma (without box -> with box). *)\nLemma equivalence_nobox_box : \n  forall ls p root p_par p_root p_top,\n  !! (is_pointer_or_null p_top) &&\n    data_at Tsh (tptr t_struct_rbtree) p_root root * \n    partial_tree_rep ls p_root p p_par p_top\n  |-- EX b, data_at Tsh (tptr t_struct_rbtree) p b *\n    partial_treebox_rep ls root b p_par p_top.\nProof.\n  intros ls.\n  induction ls as [ | a ls' IH ]; intros.\n  - simpl. \n    Exists root.\n    entailer!.\n  - destruct a as [[[[[va c] k] v] tg] sib].\n    simpl.\n    Intros p_gpar p_sib.\n    Exists (\n      if va\n      then (field_address t_struct_rbtree [StructField _right] p_par)\n      else (field_address t_struct_rbtree [StructField _left] p_par)).\n    Exists p_gpar p_sib.\n    sep_apply IH; try auto.\n    Intros b_par. Exists b_par. \n    unfold_data_at (data_at _ _ _ p_par).\n    destruct va; entailer!.\nQed.\n\n(** Corollaries of equivalence lemmas, with p_top specified to be nullval. *)\nLemma equivalence_box_nobox' : \n  forall ls p b root p_par,\n    data_at Tsh (tptr t_struct_rbtree) p b *\n    partial_treebox_rep ls root b p_par nullval\n  |-- EX p_root, partial_tree_rep ls p_root p p_par nullval *\n      data_at Tsh (tptr t_struct_rbtree) p_root root.\nProof.\n  intros. sep_apply equivalence_box_nobox; auto.\nQed.\n\nLemma equivalence_nobox_box' : \n  forall ls p root p_par p_root,\n    data_at Tsh (tptr t_struct_rbtree) p_root root * \n    partial_tree_rep ls p_root p p_par nullval\n  |-- EX b, data_at Tsh (tptr t_struct_rbtree) p b *\n    partial_treebox_rep ls root b p_par nullval.\nProof.\n  intros. sep_apply equivalence_nobox_box; auto.\nQed.\n\n(*\nLemma delete_lemma : forall ls root b p_par,\n  partial_treebox_rep ls root b p_par nullval *\n  data_at Tsh (tptr t_struct_rbtree) nullval b\n  |-- treeroot_rep (complete_tree ls Empty) root.\nProof.\n  intros.\n  pose proof (insert_lemma ls Empty).\n  specialize (H nullval p_par root b).\n  unfold treeroot_rep, treebox_rep in *.\n  eapply derives_trans; [ | apply H].\n  simpl rbtree_rep.\n  entailer!.\nQed.\n*)\n\nLemma delete_balance_t_color : \n  forall t va_f c_f k_f v_f tg_f sib ls,\n  get_color_tree t <> Col2Z Red -> \n  delete_balance t ((va_f, c_f, k_f, v_f, tg_f, sib) :: ls) Black =\n  match sib with\n  | Empty => (t, ((va_f, c_f, k_f, v_f, tg_f, sib) :: ls))\n  | T Red wl wk wv wt wr => \n    match (CaseOne_sol t (va_f, c_f, k_f, v_f, tg_f, sib) false) with\n    | (ts, true) => (ts, ls)\n    | (ts, false) => delete_balance ts ls Black\n    end\n  | T Black wl wk wv wt wr => \n    match (CaseTTF_sol t (va_f, c_f, k_f, v_f, tg_f, sib) false) with\n    | (ts, true) => (ts, ls)\n    | (ts, false) => delete_balance ts ls Black\n    end\n  end.\nProof.\n  intros.\n  destruct t; [ reflexivity | ].\n  destruct c; [ simpl in H; contradiction | reflexivity ].\nQed.\n\nLemma match_color : forall {A : Type} (t : RBtree) (res1 res2 : A), \n  get_color_tree t <> Col2Z Red -> \n  match t with\n  | T Red _ _ _ _ _ => res1\n  | _ => res2\n  end = res2.\nProof.\n  intros.\n  destruct t; [ reflexivity | ].\n  destruct c; [ simpl in H; contradiction | reflexivity ].\nQed.\n\nLemma tag_tree_t_empty :\n  forall t tg, tag_tree_t tg t = Empty <-> t = Empty.\nProof.\n  intros.\n  destruct t; split; intros; try reflexivity; try discriminate.\nQed.\n\nLtac quick_replace_offset_val p :=\n  try replace (offset_val 16 p)\n    with (field_address t_struct_rbtree [StructField _left] p)\n    by (unfold field_address; simpl;\n    rewrite if_true by auto with field_compatible; auto);\n  try replace (offset_val 20 p)\n    with (field_address t_struct_rbtree [StructField _right] p)\n    by (unfold field_address; simpl;\n    rewrite if_true by auto with field_compatible; auto).\n\n(** Gather isolate fields into on data_at. *)\nLemma field_at_gather_right : \n  forall p c k v tg p_lch p_rch p_par, \n  data_at Tsh (tptr t_struct_rbtree) p_rch\n    (field_address t_struct_rbtree [StructField _right] p) *\n  field_at Tsh t_struct_rbtree [StructField _color] (Vint (Int.repr (Col2Z c))) p *\n  field_at Tsh t_struct_rbtree [StructField _key] (Vint (Int.repr k)) p *\n  field_at Tsh t_struct_rbtree [StructField _value] (Vint (Int.repr v)) p *\n  field_at Tsh t_struct_rbtree [StructField _tag] (Vint (Int.repr tg)) p *\n  field_at Tsh t_struct_rbtree [StructField _left] p_lch p *\n  field_at Tsh t_struct_rbtree [StructField _par] p_par p |--\n  data_at Tsh t_struct_rbtree\n    (Vint (Int.repr (Col2Z c)),\n    (Vint (Int.repr k),\n    (Vint (Int.repr v), (Vint (Int.repr tg), (p_lch, (p_rch, p_par)))))) p.\nProof.\n  intros. unfold_data_at (data_at _ _ _ p). entailer!.\nQed.\n\nLemma field_at_gather_left : \n  forall p c k v tg p_lch p_rch p_par, \n  data_at Tsh (tptr t_struct_rbtree) p_lch\n    (field_address t_struct_rbtree [StructField _left] p) *\n  field_at Tsh t_struct_rbtree [StructField _color] (Vint (Int.repr (Col2Z c))) p *\n  field_at Tsh t_struct_rbtree [StructField _key] (Vint (Int.repr k)) p *\n  field_at Tsh t_struct_rbtree [StructField _value] (Vint (Int.repr v)) p *\n  field_at Tsh t_struct_rbtree [StructField _tag] (Vint (Int.repr tg)) p *\n  field_at Tsh t_struct_rbtree [StructField _right] p_rch p *\n  field_at Tsh t_struct_rbtree [StructField _par] p_par p |--\n  data_at Tsh t_struct_rbtree\n    (Vint (Int.repr (Col2Z c)),\n    (Vint (Int.repr k),\n    (Vint (Int.repr v), (Vint (Int.repr tg), (p_lch, (p_rch, p_par)))))) p.\nProof.\n  intros. unfold_data_at (data_at _ _ _ p). entailer!.\nQed.\n\nLemma partialtreebox_link : \n  forall ls1 ls2 root b1 b2 p1 p2 p_top, \n  partial_treebox_rep ls1 b1 b2 p2 p1 *\n  partial_treebox_rep ls2 root b1 p1 p_top |--\n  partial_treebox_rep (ls1 ++ ls2) root b2 p2 p_top.\nProof.\n  intros ls1.\n  induction ls1 as [ | a ls1' IH ]; intros.\n  - simpl partial_treebox_rep.\n    entailer!.\n  - destruct a as [[[[[va c] k] v] tg] sib].\n    simpl partial_treebox_rep at 1.\n    Intros p_gpar p_sib b_par.\n    subst b2.\n    sep_apply IH.\n    simpl partial_treebox_rep.\n    Exists p_gpar p_sib b_par.\n    destruct va; Intros; entailer!.\nQed.\n\nLemma case_solve_not_null : forall t hft, \n  get_color_tree t <> Col2Z Red ->\n  CaseTTF_check t hft = true ->\n  let (ts, br) := CaseTTF_sol t hft false in\n  ts <> Empty.\nProof.\n  intros.\n  destruct hft as [[[[[va_f c_f] k_f] v_f] tg_f] oppo].\n  unfold CaseTTF_check in H0.\n  unfold CaseTTF_sol.\n  destruct va_f.\n  + destruct oppo; [ simpl in H; discriminate | ].\n    destruct c; [ simpl in H; discriminate | ].\n    destruct oppo1.\n    * destruct oppo2; [ simpl in H; discriminate | ].\n      destruct c; [ | simpl in H; discriminate ].\n      apply (case4_solve_not_null _ _ H0).\n    * destruct c.\n      - destruct oppo2; [ apply (case4_solve_not_null _ _ H0) | ].\n        destruct c; [ apply (case4_solve_not_null _ _ H0) | ].\n        apply (case4_solve_not_null _ _ H0).\n      - destruct oppo2; [ simpl in H; discriminate | ].\n        destruct c; [ apply (case4_solve_not_null _ _ H0) | ].\n        apply (case2_solve_not_null _ _ H0).\n  + destruct oppo; [ simpl in H; discriminate | ].\n    destruct c; [ simpl in H; discriminate | ].\n    destruct oppo1.\n    * destruct oppo2; [ simpl in H; discriminate | ].\n      destruct c; [ | simpl in H; discriminate ].\n      apply (case4_solve_not_null _ _ H0).\n    * destruct c.\n      - destruct oppo2; [ apply (case4_solve_not_null _ _ H0) | ].\n        destruct c; [ apply (case4_solve_not_null _ _ H0) | ].\n        apply (case4_solve_not_null _ _ H0).\n      - destruct oppo2; [ simpl in H; discriminate | ].\n        destruct c; [ apply (case4_solve_not_null _ _ H0) | ].\n        apply (case2_solve_not_null _ _ H0).\nQed.\n\nLemma case_one_true : forall s pb pc p pv pt wc wl wk wv wt wr, \n  get_color_tree s <> Col2Z Red ->\n  CaseOne_check s (pb, pc, p, pv, pt, T wc wl wk wv wt wr) = true ->\n  let (ts, br) := (CaseTTF_sol s (pb, Red, p, pv, default, tag_tree_t wt \n    (if pb then wr else wl)) false) in\n  match br with\n  | true => CaseOne_sol s (pb, pc, p, pv, pt, T wc wl wk wv wt wr) false = \n      (T Black (if pb then (tag_tree_t wt wl) else ts) wk (f wv wt) pt \n        (if pb then ts else (tag_tree_t wt wr)), true)\n  | false =>\n    (get_color_tree ts = Col2Z Red /\\\n    CaseOne_sol s (pb, pc, p, pv, pt, T wc wl wk wv wt wr) false = \n      (T Black (if pb then (tag_tree_t wt wl) else (makeBlack ts)) wk (f wv wt) pt \n        (if pb then (makeBlack ts) else (tag_tree_t wt wr)), true))\n    \\/\n    (CaseTTF_check ts\n    (pb, Black, wk, f wv wt, pt, tag_tree_t wt (if pb then wl else wr)) = true /\\\n    get_color_tree (tag_tree_t wt (if pb then wl else wr)) = Col2Z Black /\\\n    get_color_tree ts = Col2Z Black /\\\n      CaseOne_sol s (pb, pc, p, pv, pt, T wc wl wk wv wt wr) false = \n        CaseTTF_sol ts (pb, Black, wk, f wv wt, pt, tag_tree_t wt \n          (if pb then wl else wr)) false)\n  end.\nProof.\n  assert (HLemma : forall (b res : bool), \n    (if b then res else false) = true <-> b = true /\\ res = true)\n    by (intros; destruct b; destruct res; tauto). \n  intros. unfold CaseOne_check in H0.\n  destruct pb.\n  - destruct wc; [ | discriminate ].\n    rewrite HLemma in H0.\n    destruct H0 as [H0_copy H0].\n    remember (CaseTTF_sol s (true, Red, p, pv, default, tag_tree_t wt wr) false) as br_ts.\n    destruct br_ts as [ts br].\n    destruct br.\n    { \n      unfold CaseOne_sol. rewrite <- Heqbr_ts.\n      reflexivity.\n    }\n    destruct ts.\n    + apply case_solve_not_null in H0_copy; [ | assumption ].\n      rewrite <- Heqbr_ts in H0_copy.\n      contradiction.\n    + destruct c.\n      * left. split.\n        --  reflexivity.\n        --  unfold CaseOne_sol. rewrite <- Heqbr_ts.\n            reflexivity. \n      * right. split; [ exact H0 | ]. \n        destruct wl; [ simpl in H0; discriminate | ].\n        destruct c; [ simpl in H0; discriminate | ].\n        do 2 split; [ reflexivity | ].\n        unfold CaseOne_sol. rewrite <- Heqbr_ts.\n        reflexivity. \n  - destruct wc; [ | discriminate ].\n    rewrite HLemma in H0.\n    destruct H0 as [H0_copy H0].\n    remember (CaseTTF_sol s (false, Red, p, pv, default, tag_tree_t wt wl) false) as br_ts.\n    destruct br_ts as [ts br].\n    destruct br.\n    { \n      unfold CaseOne_sol. rewrite <- Heqbr_ts.\n      reflexivity.\n    }\n    destruct ts.\n    + apply case_solve_not_null in H0_copy; [ | assumption ].\n      rewrite <- Heqbr_ts in H0_copy.\n      contradiction.\n    + destruct c.\n      * left. split.\n        --  reflexivity.\n        --  unfold CaseOne_sol. rewrite <- Heqbr_ts.\n            reflexivity. \n      * right. split; [ exact H0 | ]. \n        destruct wr; [ simpl in H0; discriminate | ].\n        destruct c; [ simpl in H0; discriminate | ].\n        do 2 split; [ reflexivity | ].\n        unfold CaseOne_sol. rewrite <- Heqbr_ts.\n        reflexivity. \nQed.\n\nLemma if_else_then_true : forall (b res : bool), \n  (if b then res else false) = true <-> b = true /\\ res = true.\nProof.\n  intros. destruct b; destruct res; tauto.\nQed. \n\nDefinition get_tag (t : RBtree) : Tag := \n  match t with\n  | Empty => default\n  | T _ _ _ _ t0 _ => t0\n  end.\n\nDefinition f_partial (ov : option Value) (t0 : Tag) : option Value :=\n  match ov with\n  | Some v => Some (f v t0)\n  | None => None\n  end.\n\nLocal Open Scope Z.\n\n(* TODO: this will be removed in newer version of Coq (e.g. 8.13.0)\n    when its lia is stronger *)\nDefinition tri_div (a b c : bool) : Prop := \n  if a then b = false /\\ c = false\n  else if b then c = false\n            else c = true.\n\nLemma tri_div_Z : forall (k x : Z), \n  tri_div (k <? x) (x <? k) (k =? x).\nProof.\n  intros.\n  unfold tri_div.\n  destruct (k <? x) eqn:E.\n  - rewrite Z.ltb_lt in E.\n    split.\n    + assert (k <= x) by lia.\n      rewrite Zaux.Zlt_bool_false; auto.\n    + rewrite Z.eqb_neq.\n      lia.\n  - destruct (x <? k) eqn:E'.\n    + rewrite Z.ltb_lt in E'.\n      rewrite Z.eqb_neq.\n      lia.\n    + rewrite Z.eqb_eq.\n      rewrite Z.ltb_ge in E, E'.\n      lia.\nQed.\n\nLtac nonempty_tree t :=\n  destruct t; simpl rbtree_rep; [ Intros; contradiction | ].\n\nLtac empty_tree t :=\n  sep_apply rbtree_rep_nullval; Intros; subst t.\n\nLtac nonempty_data := \n  sep_apply data_at_rbtree_nullval; Intros; contradiction.\n\nLemma partial_tree_par_nullval : \n  forall ls p_root p p_top, \n    partial_tree_rep ls p_root p nullval p_top |-- \n      !! (ls = nil) && !! (p_root = p) && !! (p_top = nullval) && emp.\nProof.\n  intros.\n  destruct ls; [ simpl partial_tree_rep; entailer! | ].\n  destruct h as [[[[[va c] k] v] tg] sib].\n  simpl partial_tree_rep.\n  Intros pa pb.\n  nonempty_data.\nQed.\n\nLtac empty_partialtree ls := \n  sep_apply (partial_tree_par_nullval ls); Intros; subst ls.\n\nLtac nonempty_partialtree ls :=\n  destruct ls; simpl partial_tree_rep; [ Intros; contradiction | ].\n\nLemma rbtree_shareptr_false :\n  forall (p : val) sib c k v tg (p_lch p_rch p_par p_par' : val), \n    data_at Tsh t_struct_rbtree\n      (Vint (Int.repr (Col2Z c)),\n      (Vint (Int.repr k),\n      (Vint (Int.repr v),\n      (Vint (Int.repr tg), (p_lch, (p_rch, p_par)))))) p *\n    rbtree_rep sib p p_par' |-- !! False.\nProof.\n  intros.\n  destruct sib.\n  - simpl rbtree_rep. Intros.\n    subst p.\n    assert_PROP (False). { entailer!. }\n    contradiction.\n  - simpl rbtree_rep. \n    Intros p_lch0 p_rch0.\n    sep_apply data_at_conflict; [ apply sepalg_Tsh | ].\n    sep_apply FF_local_facts.\n    Intros.\n    contradiction.\nQed.\n\nLtac common_pointer_solve p t :=\n  sep_apply (rbtree_shareptr_false p t); Intros; contradiction.\n\nLemma col_repr_empty : \n  forall t, Int.repr (get_color_tree t) = Int.repr (-1) <->\n    t = Empty.\nProof.\n  intros. split. \n  - destruct t; intros.\n    + auto. \n    + destruct c; simpl in H; try discriminate. \n  - intros. subst t. auto.\nQed.\n\nLtac nonempty_tree_bycol t := \n  destruct t; [ simpl get_color_tree in *; discriminate | ].\n\nTheorem body_update_aux: \n  semax_body Vprog Gprog f_update_aux update_aux_spec.\nProof.\n  start_function.\n  rename H3 into Hini.\n  assert (Htarglohi : targ_hi <? targ_lo = false).\n  {\n    destruct Hini.\n    - unfold lt_prop, Rlt_Z in H3. arith_bool.\n      pose proof (tri_div_Z targ_lo targ_hi).\n      unfold tri_div in H4.\n      rewrite H3 in H4.\n      destruct H4. auto.\n    - rewrite H3. apply Z.ltb_irrefl.\n  }\n  forward_if_wrp.           (* if (t == NULL) *)\n  {\n    subst p. empty_tree t. \n    forward.\n    simpl. \n    repeat rewrite Tauto.if_same. \n    simpl rbtree_rep.\n    entailer!.\n  }\n  (* t <> Empty *)\n  nonempty_tree t.\n  forward_if_wrp.           (* if (l > targ_r) *)\n  { \n    forward.\n    arith_bool.\n    simpl change_segment'.\n    rewrite H4.\n    simpl. rewrite Tauto.if_same.\n    simpl rbtree_rep.\n    Exists p_lch p_rch.\n    entailer!.\n  }\n  (* targ_hi >= lo *)\n  forward_if_wrp.           (* if (r < targ_l) *)\n  { \n    forward.\n    arith_bool.\n    simpl change_segment'.\n    rewrite H5, orb_true_r.\n    simpl. rewrite Tauto.if_same.\n    simpl rbtree_rep.\n    Exists p_lch p_rch.\n    entailer!.\n  }\n  (* hi >= targ_lo *)\n  forward_if (temp _t'4 \n    (Val.of_bool ((targ_lo <=? lo) && (hi <=? targ_hi)))).\n  {\n    forward.\n    entailer!.\n    apply f_equal.\n    arith_bool.\n    repeat rewrite Z.leb_antisym.\n    rewrite H6.\n    simpl.\n    apply f_equal.\n    unfold Int.lt.\n    repeat (rewrite Int.signed_repr; [| assumption ]).\n    apply zlt_bool_1.\n  }\n  {\n    forward.\n    entailer!.\n    arith_bool.\n    repeat rewrite Z.leb_antisym.\n    rewrite H6.\n    simpl.\n    reflexivity.\n  }\n  forward_if_wrp.           (* if (l >= targ_l && r <= targ_r) *)\n  {\n    (* inner *)\n    simpl rbtree_rep.\n    Intros p_lch p_rch.\n    forward.\n    forward_call (t2, tg).\n    forward.                  (* t->tag = Optt(t->tag, tg); *)\n    forward.\n    simpl change_segment'.\n    apply andb_prop in H6.\n    destruct H6.\n    arith_bool.\n    simpl.\n    unfold lte_bool, lt_bool.\n    simpl.\n    rewrite H4, H5.\n    repeat rewrite arith_bool_1.\n    rewrite H6, H11.\n    simpl.\n    rewrite Htarglohi.\n    simpl rbtree_rep.\n    Exists p_lch p_rch.\n    rewrite Z.add_comm.\n    entailer!.\n  }\n  {\n    simpl rbtree_rep.\n    Intros p_lch p_rch.\n    forward.\n    forward_if (temp _t'3\n      (Val.of_bool ((targ_lo <=? k) && (k <=? targ_hi)))).\n    {\n      forward.\n      forward.\n      entailer!.\n      apply f_equal.\n      arith_bool.\n      repeat rewrite Z.leb_antisym.\n      rewrite H8.\n      simpl.\n      apply f_equal.\n      unfold Int.lt.\n      repeat (rewrite Int.signed_repr; [| assumption ]).\n      apply zlt_bool_1.\n    }\n    { \n      forward.\n      entailer!.\n      arith_bool.\n      repeat rewrite Z.leb_antisym.\n      rewrite H8.\n      simpl.\n      reflexivity.\n    }\n    deadvars!.\n    forward_if        (* if (targ_l <= t->key && t->key <= targ_r) *)\n    (PROP ( )\n    LOCAL (temp _t'3 (Val.of_bool ((targ_lo <=? k) && (k <=? targ_hi)));\n    temp _t p; temp _tg (Vint (Int.repr tg)); temp _l (Vint (Int.repr lo));\n    temp _r (Vint (Int.repr hi)); temp _targ_l (Vint (Int.repr targ_lo));\n    temp _targ_r (Vint (Int.repr targ_hi)))\n    SEP (data_at Tsh t_struct_rbtree\n          (Vint (Int.repr (Col2Z c)),\n          (Vint (Int.repr k),\n          (Vint (Int.repr (if ((targ_lo <=? k) && (k <=? targ_hi))%bool then f v tg else v)), \n          (Vint (Int.repr t2), (p_lch, (p_rch, p_par)))))) p;\n    rbtree_rep t1 p_lch p; rbtree_rep t3 p_rch p)).\n    {\n      (* tag the root *)\n      forward.\n      forward_call (v, tg).\n      forward.\n      rewrite H8.\n      simpl f.\n      entailer!.\n    }\n    {\n      forward.\n      rewrite H8.\n      entailer!.\n    }\n    arith_bool.\n    forward; try aggregate_solve.\n    forward.\n    forward_call (p_lch, p, t1, tg, targ_lo, targ_hi, lo, k).\n    forward; try aggregate_solve.\n    forward.\n    forward_call (p_rch, p, t3, tg, targ_lo, targ_hi, k, hi).\n    entailer!.\n    unfold lte_bool. \n    rewrite H4, H5.\n    simpl.\n    rewrite Htarglohi.\n    repeat rewrite arith_bool_1.\n    rewrite H6.\n    simpl.\n    Exists p_lch p_rch.\n    entailer!.\n  }\nQed.\n\nTheorem body_update: \n  semax_body Vprog Gprog f_update update_spec.\nProof.\n  start_function.\n  forward_if (lte_prop targ_lo targ_hi /\\ targ_lo <= targ_hi).\n  {\n    forward.\n    arith_bool.\n    unfold change_segment', lt_bool. simpl.\n    destruct t; rewrite H1; entailer.\n  }\n  {\n    forward.\n    entailer!.\n    unfold lte_prop.\n    unfold lt_prop.\n    simpl.\n    lia.\n  }\n  Intros.\n  destruct t; unfold treebox_rep; Intros p; simpl rbtree_rep.\n  {\n    Intros. subst p.\n    forward.\n    forward_call (nullval, nullval, Empty, tg, targ_lo, targ_hi, Int.min_signed, Int.max_signed).\n    {\n      simpl rbtree_rep.\n      entailer!.\n    }\n    { repeat (split; try auto; try rep_lia). }\n    entailer!.\n    Exists nullval.\n    repeat rewrite Tauto.if_same.\n    rewrite change_Empty.\n    entailer!.\n  }\n  {\n    Intros p_lch p_rch.\n    forward.\n    forward_call (p, nullval, (T c t1 k v t2 t3), tg, targ_lo, targ_hi, Int.min_signed, Int.max_signed).\n    {\n      simpl rbtree_rep.\n      Exists p_lch p_rch.\n      entailer!.\n    }\n    { repeat (split; try auto; try rep_lia). }\n    entailer!.\n    Exists p.\n    simpl change_segment' at 1.\n    entailer!.\n  }\nQed.\n\nTheorem body_tree_minimum: semax_body Vprog Gprog f_tree_minimum tree_minimum_spec.\nProof. \n  start_function.\n  forward_loop\n  (EX t' : RBtree, \n    EX ls : list Half_tree, \n    EX p_par' : val,\n    EX b' : val, \n    PROP (Up_split (minimum_split default t nil) = \n      Up_split (minimum_split default t' ls); \n      Forall turn_left ls; \n      Forall tag_default ls;\n      t' <> Empty)\n    LOCAL (temp _t b')\n    SEP (treebox_rep t' b' p_par';\n    partial_treebox_rep ls b b' p_par' p_par)).\n  {\n    Exists t (@nil Half_tree) p_par b.\n    entailer!.\n    simpl partial_treebox_rep.\n    entailer!.\n  }\n  { \n    Intros t' ls p_par' b'.\n    nonempty_tree t'.\n    unfold treebox_rep.\n    Intros p.\n    simpl rbtree_rep.\n    Intros p_lch p_rch.\n    forward.              (* tmp = *t; *)\n    forward_call (c, k, v, t0, p_lch, p_rch, p_par', p, t'1, t'2).\n                          (* pushdown(tmp); *)\n    forward; try aggregate_solve.\n    forward_if_wrp.\n    { \n      subst p_lch.\n      remember (tag_tree_t t0 t'1) as lch.\n      empty_tree lch.\n      rewrite tag_tree_t_empty in H5.\n      subst t'1.\n      forward.            (* return; *)\n      Exists b' p_par' ls c k (v + t0) (tag_tree_t t0 t'2).\n      entailer!.\n      - rewrite H0.\n        simpl.\n        strip_0.\n        reflexivity.\n      - unfold treebox_rep.\n        Exists p.\n        simpl rbtree_rep.\n        Exists nullval p_rch.\n        entailer!.\n    }\n    {\n      destruct t'1 eqn:Et'1.\n      { \n        simpl rbtree_rep at 1.\n        Intros. contradiction.\n      }\n      forward.            (* t = &(tmp->left); *)\n      Exists (tag_tree_t t0 t'1)\n        ((false, c, k, (v + t0), default, (tag_tree_t t0 t'2)) :: ls).\n      Exists p (offset_val 16 p).\n      entailer!.\n      - split; [ | split; [ | split ] ]; try apply Forall_cons; try assumption.\n        * rewrite H0.\n          unfold minimum_split.\n          simpl.\n          strip_0.\n          do 7 f_equal.\n          lia.\n        * unfold turn_left.\n          reflexivity.\n        * unfold tag_default.\n          reflexivity.\n        * intro; discriminate.\n      - simpl rbtree_rep.\n        Intros p_lch0 p_rch0.\n        unfold treebox_rep.\n        Exists p_lch.\n        simpl rbtree_rep.\n        Exists p_lch0 p_rch0.\n        simpl partial_treebox_rep.\n        Exists p_par' p_rch b'.\n        entailer!;\n        quick_replace_offset_val p; try auto.\n        unfold_data_at (data_at _ _ _ p).\n        entailer!.\n    }\n  }\nQed.\n\nTheorem body_delete_balance: \n  semax_body Vprog Gprog f_delete_balance delete_balance_spec.\nProof. \n  start_function.\n  sep_apply equivalence_box_nobox; try auto.\n  Intros p_root.\n  forward_loop\n  (EX t : RBtree, \n  EX ls : list Half_tree, \n  EX p : val, \n  EX p_par : val,\n  EX p_root' : val, \n  PROP (delete_check t ls Black = true /\\\n    complete_tree_revarg (delete_balance t_initial ls_initial Black)\n   = complete_tree_revarg (delete_balance t ls Black))\n  LOCAL (temp _root root; temp _p p; temp _p_par p_par)\n  SEP (rbtree_rep t p p_par;\n    partial_tree_rep ls p_root' p p_par nullval;\n    data_at Tsh (tptr t_struct_rbtree) p_root' root)).\n  {\n    Exists t_initial.\n    Exists ls_initial.\n    Exists p_initial p_par_initial p_root.\n    entailer!.\n  }\n  {\n    Intros t ls p p_par p_root'.\n    forward_if (p_par <> nullval); try pointer_destructor.\n    { (* if p_fa is nullptr, then return directly *)\n      subst p_par.\n      empty_partialtree ls.\n      forward.                      (* *root = p; *)\n      forward.                      (* return; *)\n\n      simpl in H1.\n      rewrite H1.\n      Exists t (@nil Half_tree).\n      Exists root nullval.\n      simpl partial_treebox_rep.\n      unfold treebox_rep.\n      Exists p.\n      entailer!.\n    }\n    {\n      forward.\n      entailer!. \n    }\n    nonempty_partialtree ls.\n    destruct h as [[[[[va c] k] v] tg] sib].\n    Intros p_gpar p_sib.\n    forward_call (t, p, p_par).     (* getting color *)\n    forward_if (get_color_tree t <> Col2Z Red); try pointer_destructor.\n                                    (* if (get_color(p) == RED) *)\n    { (* the color of t is red *)\n      nonempty_tree_bycol t.\n      simpl rbtree_rep.\n      Intros p_lch p_rch.\n      forward.                      (* p->color = BLACK; *)\n      forward.                      (* return; *)\n\n      simpl in H4.\n      color_replace.\n      rewrite H1.\n      Exists (T Black t1 k0 v0 t2 t3) ((va, c, k, v, tg, sib) :: ls).\n\n      simpl delete_balance.\n      simpl partial_tree_rep.\n      Exists (if va then (offset_val 20 p_par) else (offset_val 16 p_par)).\n      Exists p_par.\n      simpl partial_treebox_rep.\n      Exists p_gpar p_sib.\n      sep_apply equivalence_nobox_box'.\n      Intros b_par.\n      Exists b_par.\n      unfold treebox_rep.\n      Exists p.\n      simpl rbtree_rep.\n      Exists p_lch p_rch.\n      destruct va;\n        try assert_PROP (field_compatible t_struct_rbtree [StructField _right] p_par)\n          by entailer!;\n        try assert_PROP (field_compatible t_struct_rbtree [StructField _left] p_par)\n          by entailer!;\n        quick_replace_offset_val p_par;\n        unfold_data_at (data_at _ _ _ p_par);\n        entailer!.\n    }\n    {\n      forward.\n      entailer!.\n      rewrite H9 in H4.\n      simpl Col2Z in H4.\n      unfold RED_COLOR in H4.\n      contradiction.\n    }\n    Intros.\n    rewrite delete_balance_t_color in H1; [ | assumption ].\n    destruct sib.\n    (* show sib <> Empty *)\n    { simpl in H0. rewrite (match_color _ _ _ H4) in H0. discriminate. }\n    simpl rbtree_rep.\n    Intros p_sib_lch p_sib_rch.\n\n    forward.\n    { destruct va; aggregate_solve. }\n    forward_if_wrp.                 (* if (p == p_fa->left) *)\n    { destruct va; aggregate_solve. }\n    { (* p is the left child of p_fa *)\n      destruct va.\n      {\n        subst p_sib.\n        common_pointer_solve p t.\n      }\n      forward.                      (* p_sib = p_fa->right; *)\n      forward.\n      forward_if          (* if (p_sib->color == RED) *)\n      (EX ls_changed : list Half_tree, \n        EX p_changed : val, \n        EX p_gpar_changed : val, \n        EX p_sib_changed : val, \n        EX c_changed : color, \n        EX tg_changed : Tag, \n        EX k_sib : Key, \n        EX v_sib : Value, \n        EX tg_sib : Tag, \n        EX lch_sib : RBtree, \n        EX rch_sib : RBtree, \n        EX p_sib_lch : val, \n        EX p_sib_rch : val, \n        EX p_root' : val, \n        let hft := (false, c_changed, k, v, tg_changed, \n              (T Black lch_sib k_sib v_sib tg_sib rch_sib)) in\n        let (ts, br) := (CaseTTF_sol t hft false) in\n        PROP (\n          (if br then true else delete_check ts\n            ls_changed Black) = true;\n          CaseTTF_check t hft = true;\n          complete_tree_revarg (delete_balance t_initial ls_initial Black)\n          = complete_tree_revarg (match (CaseTTF_sol t hft false) with\n            | (ts, true) => (ts, ls_changed)\n            | (ts, false) => delete_balance ts ls_changed Black\n            end); \n            Int.min_signed <= k_sib <= Int.max_signed; \n            is_pointer_or_null p_gpar_changed)\n        LOCAL (temp _root root; temp _p p; temp _p_par p_par; \n          temp _p_sib p_sib_changed)\n        SEP (rbtree_rep t p_changed p_par;\n          rbtree_rep lch_sib p_sib_lch p_sib_changed;\n          rbtree_rep rch_sib p_sib_rch p_sib_changed;\n          data_at Tsh t_struct_rbtree\n          (Vint (Int.repr BLACK_COLOR),\n          (Vint (Int.repr k_sib),\n          (Vint (Int.repr v_sib),\n          (Vint (Int.repr tg_sib), (p_sib_lch, (p_sib_rch, p_par)))))) p_sib_changed;\n          data_at Tsh t_struct_rbtree\n          (Vint (Int.repr (Col2Z c_changed)),\n          (Vint (Int.repr k),\n          (Vint (Int.repr v), (Vint (Int.repr tg_changed), \n            (p_changed, (p_sib_changed, p_gpar_changed))))))\n          p_par;\n          partial_tree_rep ls_changed p_root' p_par p_gpar_changed nullval;\n          data_at Tsh (tptr t_struct_rbtree) p_root' root))%assert; try pointer_destructor.\n      (** Note that here, _p should be p_changed, though this will not affect the \n          following proof. *)\n      {\n        color_replace.\n        (* show CaseOne_check is true *)\n        assert (Hcaseone: (CaseOne_check t\n             (false, c, k, v, tg, T Red sib1 k0 v0 t0 sib2)) = true).\n        {\n          remember (CaseOne_check t\n             (false, c, k, v, tg, T Red sib1 k0 v0 t0 sib2)) as bb.\n          destruct bb.\n          - reflexivity.\n          - unfold delete_check in H0. rewrite <- Heqbb in H0.\n            rewrite (match_color _ _ _ H4) in H0.\n            discriminate.\n        }\n        apply case_one_true in Hcaseone; [ | assumption ].\n        assert (Hcasettf: (CaseTTF_check t\n             (false, Red, k, v, default, tag_tree_t t0 sib1)) = true).\n        {\n          simpl in H0. rewrite (match_color _ _ _ H4) in H0.\n          rewrite if_else_then_true in H0. destruct H0 as [H0 _].\n          rewrite if_else_then_true in H0. destruct H0 as [H0 _].\n          exact H0.\n        }\n        pose proof Hcasettf as Hcopyttf.\n        apply (case_solve_not_null _ _ H4) in Hcasettf.\n        (* a critical conclusion *)\n        assert (Hfinal:\n          complete_tree_revarg (delete_balance t_initial ls_initial Black) = \n          complete_tree_revarg (match (CaseTTF_sol t\n             (false, Red, k, v, default, tag_tree_t t0 sib1) false) with\n          | (ts, true) => (ts, ((false, Black, k0, f v0 t0, tg, tag_tree_t t0 sib2) :: ls))\n          | (ts, false) =>\n            delete_balance ts\n            ((false, Black, k0, f v0 t0, tg, tag_tree_t t0 sib2) :: ls)\n            Black\n          end)).\n        {\n          rewrite H1.\n          remember (CaseTTF_sol t (false, Red, k, v, default, tag_tree_t t0 sib1) false)\n            as br_ts.\n          destruct br_ts as [t_t br].\n          destruct br.\n          {\n            rewrite Hcaseone.\n            reflexivity.\n          }\n          destruct t_t; [ contradiction | ].\n          destruct Hcaseone as [Hcaseone | Hcaseone]; destruct Hcaseone as [Hco1 Hco2]. \n          - rewrite Hco2.\n            simpl delete_balance. \n            destruct c0; unfold complete_tree_revarg; simpl complete_tree; \n            [ reflexivity | simpl in Hco1; discriminate ].\n          - destruct Hco2 as [Hco2 Hco3]. \n            destruct Hco3 as [Hco3 Hco4].\n            destruct c0; [ discriminate | ].\n            remember (tag_tree_t t0 sib2) as t_t.\n            destruct t_t.\n            * discriminate Hco2.\n            * destruct c0; [ discriminate Hco2 | ].\n              rewrite Hco4.\n              reflexivity.\n        }\n        forward_call (Red, k0, v0, t0, p_sib_lch, p_sib_rch, p_par, p_sib, \n          sib1, sib2).    (* pushdown(p_sib); *)\n        forward.\n        forward.          (* p_sib->tag = p_par->tag; *)\n        forward.          (* p_par->tag = DEFAULT_TAG; *)\n        forward.          (* p_sib->color = p_fa->color; *)\n        forward.          (* p_fa->color = RED; *)\n        assert_PROP (is_pointer_or_null p_gpar) as PNp_gpar by entailer!. \n        forward_call      (* left_rotate_wrap(p_par, root); *)\n        (Red, k, v, default, p_gpar,\n          Black, k0, (f v0 t0), tg, \n          t, (tag_tree_t t0 sib1), (tag_tree_t t0 sib2), \n          p_par, p_sib, p, p_sib_lch, p_sib_rch, \n          root, p_root', ls).\n        Intros p_root_new.\n        forward. try aggregate_solve.          (* p_sib = p_fa->right; *)\n        nonempty_tree_bycol sib1.\n        destruct c0.\n        { simpl in Hcopyttf. discriminate Hcopyttf. }\n        simpl rbtree_rep.\n        Intros p_sib_lch_lch p_sib_lch_rch.\n\n        Exists ((false, Black, k0, f v0 t0, tg, tag_tree_t t0 sib2)\n          :: ls).\n        Exists p p_sib p_sib_lch.\n        Exists Red default k1 v1 (t0 + t1) sib1_1 sib1_2.\n        Exists p_sib_lch_lch p_sib_lch_rch.\n        Exists p_root_new.\n        simpl tag_tree_t in *.\n        remember (CaseTTF_sol t (false, Red, k, v, default, \n          T Black sib1_1 k1 v1 (t0 + t1) sib1_2) false) as t_t.\n        destruct t_t as [ts br].\n        entailer!.\n        {\n          destruct br; auto.\n          destruct ts.\n          - contradiction.\n          - destruct Hcaseone as [Hcaseone | Hcaseone]; destruct Hcaseone as [Hco1 Hco2]. \n            + simpl in Hco1. destruct c0; [ | discriminate Hco1 ].\n              simpl. reflexivity.\n            + destruct Hco2 as [Hco2 Hco3].\n              remember (tag_tree_t t0 sib2) as t_t.\n              destruct t_t.\n              * discriminate Hco1.\n              * destruct c1; [ discriminate Hco1 | ].\n                destruct Hco3 as [Hco3 Hco4].\n                destruct c0; [ discriminate Hco3 | ].\n                unfold delete_check.\n                rewrite Hco1.\n                unfold delete_check in H0.\n                rewrite (match_color _ _ _ H4) in H0.\n                rewrite if_else_then_true in H0.\n                destruct H0 as [H0 Hco5].\n                rewrite <- Hco4.\n                rewrite Hco5.\n                auto.\n        }\n        simpl partial_tree_rep.\n        Exists p_gpar p_sib_rch.\n        entailer!.\n      }\n      {\n        forward.\n        color_replace.\n        Exists ls.\n        Exists p p_gpar p_sib.\n        Exists c tg k0 v0 t0 sib1 sib2.\n        Exists p_sib_lch p_sib_rch.\n        Exists p_root'.\n        remember (CaseTTF_sol t (false, c, k, v, tg, T Black sib1 k0 v0 t0 sib2) false) as t_t.\n        destruct t_t as [ts br].\n        entailer!.\n        unfold delete_check in H0.\n        rewrite (match_color _ _ _ H4) in H0.\n        rewrite if_else_then_true in H0.\n        destruct H0 as [H00 H0].\n        rewrite <- Heqt_t in H0.\n        destruct br; [ split; auto | split; assumption ].\n      }\n\n      (* clear all the useless variables and hypothesis *)\n      clear H6.\n      clear p_root'.\n      Intros ls_ p_ p_gpar_ p_sib_.\n      Intros c_ tg_ k_ v_ t0_ sib1_ sib2_.\n      Intros p_sib_lch_ p_sib_rch_.\n      Intros p_root'.\n      remember (CaseTTF_sol t (false, c_, k, v, tg_, T Black sib1_ k_ v_ t0_ sib2_) false) as t_t.\n      destruct t_t as [ts br].\n\n      (* Case 2 *)\n      forward; try aggregate_solve.\n      forward_call (sib1_, p_sib_lch_, p_sib_).\n      forward_if (temp _t'4 \n        (Val.of_bool \n          ((negb (Int.eq (Int.repr (get_color_tree sib1_)) (Int.repr 1))) &&\n          (negb (Int.eq (Int.repr (get_color_tree sib2_)) (Int.repr 1)))))); try pointer_destructor.\n      {\n        forward; try aggregate_solve.\n        forward_call (sib2_, p_sib_rch_, p_sib_).\n        forward.\n        entailer!.\n        apply f_equal.\n        destruct sib1_.\n        - simpl get_color_tree. \n          unfold Int.eq, zeq. simpl. reflexivity.\n        - destruct c1; try contradiction.\n          simpl get_color_tree.\n          unfold Int.eq, zeq. simpl. reflexivity.\n      }\n      {\n        forward.\n        nonempty_tree_bycol sib1_.\n        simpl get_color_tree in *.\n        color_replace.\n        entailer!.\n      }\n      forward_if_wrp.\n        (* if (get_color(p_sib->left) != RED && get_color(p_sib->right) != RED) *)\n      {\n        assert (Hleftnotred : get_color_tree sib1_ <> Col2Z Red).\n        {\n          intro. rewrite H11 in H10.\n          unfold Int.eq, zeq in H10. simpl in H10.\n          discriminate. \n        }\n        assert (Hrightnotred : get_color_tree sib2_ <> Col2Z Red).\n        {\n          intro. rewrite H11 in H10.\n          unfold Int.eq, zeq in H10. simpl in H10.\n          rewrite andb_false_r in H10.\n          discriminate. \n        }\n        forward.        (* p_sib->color = RED; *)\n        forward.        (* p = p_fa; *)\n        forward.        (* p_fa = p->fa; *)\n        destruct sib1_; destruct sib2_;\n        simpl rbtree_rep;\n        simpl in H1; simpl in H0.\n        {\n          Intros.\n          Exists (T c_ t k v tg_ (T Red Empty k_ v_ t0_ Empty)) ls_.\n          Exists p_par p_gpar_ p_root'.\n          entailer!.\n          {\n            simpl in Heqt_t.\n            inversion Heqt_t.\n            destruct br; [ discriminate | ].\n            (* Case 2, so br = false *)\n            rewrite <- H12.\n            split; assumption.\n          }\n          simpl rbtree_rep.\n          Exists p_. Exists p_sib_.\n          Exists nullval nullval.\n          entailer!.\n        }\n        {\n          simpl get_color_tree in *.\n          destruct c1; [ contradiction | simpl in H0; discriminate ].\n        }\n        {\n          simpl get_color_tree in *.\n          destruct c1; [ contradiction | simpl in H0; discriminate ].\n        }\n        {\n          simpl get_color_tree in *.\n          destruct c1; [ contradiction | ].\n          destruct c2; [ contradiction | ].\n          Intros p_sib_lch_lch p_sib_lch_rch.\n          Intros p_sib_rch_lch p_sib_rch_rch.\n          Exists (T c_ t k v tg_\n            (T Red (T Black sib1_1 k1 v1 t1 sib1_2) k_ v_ t0_\n              (T Black sib2_1 k2 v2 t2 sib2_2))) ls_.\n          Exists p_par p_gpar_ p_root'.\n          entailer!.\n          {\n            simpl in Heqt_t.\n            inversion Heqt_t.\n            destruct br; [ discriminate | ].\n            (* Case 2, so br = false *)\n            rewrite <- H24.\n            split; assumption.\n          }\n          simpl rbtree_rep.\n          Exists p_ p_sib_. entailer!.\n          Exists p_sib_lch_ p_sib_rch_. entailer!.\n          Exists p_sib_rch_lch. Exists p_sib_lch_lch.\n          Exists p_sib_lch_rch. Exists p_sib_rch_rch.\n          entailer!.\n        }\n      }\n      {\n        forward; try aggregate_solve.\n        forward_call (sib2_, p_sib_rch_, p_sib_).\n        apply semax_if_seq.\n        (** Here is a trade-off: we use semax_if_seq to avoid giving tedious\n            post-condition. *)\n        forward_if_wrp.   (* if (get_color(p_sib->right) != RED) *)\n        {\n          (* Case 3 *)\n          rewrite <- negb_orb in H10.\n          rewrite negb_false_iff in H10.\n          apply orb_prop in H10.\n          destruct H10 as [H10 | H10]; apply int_eq_e in H10; [ | contradiction ].\n          destruct sib1_; [ simpl in H10; discriminate | ].\n          simpl in H10.\n          color_replace.\n          simpl rbtree_rep.\n          Intros p_sib_lch_lch p_sib_lch_rch.\n          forward.\n          forward_call (Red, k1, v1, t1, p_sib_lch_lch, p_sib_lch_rch, \n            p_sib_, p_sib_lch_, sib1_1, sib1_2).\n                          (* pushdown(p_sib->left); *)\n          forward.\n          forward.\n          forward.    (* p_sib->left->tag = p_sib->tag; *)\n          forward.    (* p_sib->tag = DEFAULT_TAG; *)\n          forward.\n          forward.    (* p_sib->left->color = BLACK; *)\n          forward.    (* p_sib->color = RED; *)\n          forward_call\n          (Black, k1, (f v1 t1), t0_, \n            Red, k_, v_, default, p_par, \n            (tag_tree_t t1 sib1_1), (tag_tree_t t1 sib1_2), sib2_, \n            p_sib_lch_, p_sib_, p_sib_lch_lch, p_sib_lch_rch, p_sib_rch_, \n            root, p_root', (true, c_, k, v, tg_, t) :: ls_).\n          {\n            simpl partial_tree_rep.\n            Exists p_gpar_ p_.\n            entailer!.\n          }\n          Intros p_root_new.\n          subst p_root_new.\n          simpl partial_tree_rep.\n          clear PNp_gpar_ p_gpar_ p_.\n          Intros p_gpar_ p_.\n          forward.    (* p_sib = p_fa->right; *)\n\n          assert_PROP (is_pointer_or_null p_sib_lch_) as PNp_sib_lch_ by entailer!.\n          forward_call (Black, k1, (f v1 t1), t0_, p_sib_lch_lch, p_sib_, \n            p_par, p_sib_lch_, (tag_tree_t t1 sib1_1), \n            (T Red (tag_tree_t t1 sib1_2) k_ v_ default sib2_)).\n                      (* pushdown(p_sib); *)\n          {\n            simpl rbtree_rep.\n            Exists p_sib_lch_rch p_sib_rch_.\n            entailer!.\n          }\n          simpl rbtree_rep.\n          Intros p_lch p_rch.\n          forward.\n          forward.    (* p_sib->tag = p_fa->tag; *)\n          forward.    (* p_fa->tag = DEFAULT_TAG; *)\n          forward.\n          forward.    (* p_sib->color = p_fa->color; *)\n          forward.    (* p_fa->color = BLACK; *)\n          forward.\n          forward.    (* p_sib->right->color = BLACK; *)\n          assert_PROP (is_pointer_or_null p_gpar_) as PNp_gpar_ by entailer!.\n          forward_call\n          (Black, k, v, default, p_gpar_, \n            c_, k1, (f (f v1 t1) t0_), tg_, \n            t, (tag_tree_t t0_ (tag_tree_t t1 sib1_1)), \n              (T Black (tag_tree_t t1 sib1_2) k_ v_ (t0_ + 0) sib2_), \n            p_par, p_sib_lch_, p_, p_sib_lch_lch, p_sib_, \n            root, p_root', ls_).\n                      (* left_rotate_wrap(p_fa, root); *)\n          {\n            simpl rbtree_rep.\n            Exists p_lch p_rch.\n            entailer!.\n          }\n          Intros p_root_new.\n          simpl rbtree_rep.\n          clear p_lch p_rch.\n          Intros p_lch p_rch.\n          forward.    (* return ; *)\n\n          simpl tag_tree_t in *.\n          simpl in Heqt_t.\n          assert (Htsbr : (ts, br) = \n             (T c_ (T Black t k v 0 (tag_tree_t t0_ (tag_tree_t t1 sib1_1))) k1 \n               (v1 + t1 + t0_) tg_ (T Black (tag_tree_t t1 sib1_2) k_ v_ (t0_ + 0) sib2_), true)).\n          {\n            destruct sib2_.\n            - assumption.\n            - simpl in *. color_replace. assumption.\n          }\n          inversion Htsbr. clear Htsbr.\n          subst br.\n          Exists ts.\n          Exists ls_.\n          sep_apply equivalence_nobox_box'.\n          Intros b.\n          Exists b p_gpar_.\n          entailer!.\n          unfold treebox_rep.\n          Exists p_sib_lch_.\n          simpl rbtree_rep.\n          Exists p_par p_sib_. entailer!.\n          Exists p_lch. Exists p_.\n          Exists p_sib_lch_lch. Exists p_rch.\n          entailer!.\n        }\n        {\n        (* Case 4 *)\n          nonempty_tree_bycol sib2_.\n          simpl in H11.\n          color_replace.\n          simpl rbtree_rep.\n          Intros p_sib_rch_lch p_sib_rch_rch.\n          forward_call (Black, k_, v_, t0_, p_sib_lch_, p_sib_rch_,\n            p_par, p_sib_, sib1_, \n            (T Red sib2_1 k1 v1 t1 sib2_2)).\n                      (* pushdown(p_sib); *)\n          {\n            simpl rbtree_rep.\n            Exists p_sib_rch_lch p_sib_rch_rch.\n            entailer!.\n          }\n          simpl rbtree_rep.\n          clear p_sib_rch_lch p_sib_rch_rch.\n          Intros p_sib_rch_lch p_sib_rch_rch.\n          forward.\n          forward.    (* p_sib->tag = p_fa->tag; *)\n          forward.    (* p_fa->tag = DEFAULT_TAG; *)\n          forward.\n          forward.    (* p_sib->color = p_fa->color; *)\n          forward.    (* p_fa->color = BLACK; *)\n          forward.\n          forward.    (* p_sib->right->color = BLACK; *)\n          forward_call\n          (Black, k, v, default, p_gpar_, \n            c_, k_, (f v_ t0_), tg_, \n            t, (tag_tree_t t0_ sib1_), \n              (T Black sib2_1 k1 v1 (t0_ + t1) sib2_2), \n            p_par, p_sib_, p_, p_sib_lch_, p_sib_rch_, \n            root, p_root', ls_).\n                      (* left_rotate_wrap(p_fa, root); *)\n          {\n            simpl rbtree_rep.\n            Exists p_sib_rch_lch p_sib_rch_rch.\n            entailer!.\n          }\n          Intros p_root_new.\n          simpl rbtree_rep.\n          Intros p_lch p_rch.\n          forward.    (* return ; *)\n\n          simpl in Heqt_t.\n          assert (Htsbr : (ts, br) = \n            (T c_ (T Black t k v 0 (tag_tree_t t0_ sib1_)) k_ (v_ + t0_) tg_\n                (T Black sib2_1 k1 v1 (t0_ + t1) sib2_2), true)).\n          {\n            destruct sib1_; simpl in Heqt_t.\n            - assumption.\n            - destruct c1; assumption.\n          }\n          inversion Htsbr. clear Htsbr.\n          subst br.\n          Exists ts.\n          Exists ls_.\n          sep_apply equivalence_nobox_box'.\n          Intros b.\n          Exists b p_gpar_.\n          entailer!.\n          unfold treebox_rep.\n          Exists p_sib_.\n          simpl rbtree_rep.\n          Exists p_par p_sib_rch_. entailer!.\n          Exists p_lch. Exists p_.\n          Exists p_sib_lch_. Exists p_rch.\n          entailer!.\n        }\n      }\n    }\n    { (* p is the right child of p_fa *)\n      destruct va; [ | contradiction ].\n      forward.            (* p_sib = p_fa->right; *)\n      forward.\n      forward_if          (* if (p_sib->color == RED) *)\n      (EX ls_changed : list Half_tree, \n        EX p_changed : val, \n        EX p_gpar_changed : val, \n        EX p_sib_changed : val, \n        EX c_changed : color, \n        EX tg_changed : Tag, \n        EX k_sib : Key, \n        EX v_sib : Value, \n        EX tg_sib : Tag, \n        EX lch_sib : RBtree, \n        EX rch_sib : RBtree, \n        EX p_sib_lch : val, \n        EX p_sib_rch : val, \n        EX p_root' : val, \n        let hft := (true, c_changed, k, v, tg_changed, \n              (T Black lch_sib k_sib v_sib tg_sib rch_sib)) in\n        let (ts, br) := (CaseTTF_sol t hft false) in\n        PROP (\n          (if br then true else delete_check ts\n          ls_changed Black) = true;\n          CaseTTF_check t hft = true;\n          complete_tree_revarg (delete_balance t_initial ls_initial Black)\n          = complete_tree_revarg (match (CaseTTF_sol t hft false) with\n            | (ts, true) => (ts, ls_changed)\n            | (ts, false) => delete_balance ts ls_changed Black\n            end); \n            Int.min_signed <= k_sib <= Int.max_signed; \n            is_pointer_or_null p_gpar_changed)\n        LOCAL (temp _root root; temp _p p; temp _p_par p_par; \n          temp _p_sib p_sib_changed)\n        SEP (rbtree_rep t p_changed p_par;\n          rbtree_rep lch_sib p_sib_lch p_sib_changed;\n          rbtree_rep rch_sib p_sib_rch p_sib_changed;\n          data_at Tsh t_struct_rbtree\n          (Vint (Int.repr BLACK_COLOR),\n          (Vint (Int.repr k_sib),\n          (Vint (Int.repr v_sib),\n          (Vint (Int.repr tg_sib), (p_sib_lch, (p_sib_rch, p_par)))))) p_sib_changed;\n          data_at Tsh t_struct_rbtree\n          (Vint (Int.repr (Col2Z c_changed)),\n          (Vint (Int.repr k),\n          (Vint (Int.repr v), (Vint (Int.repr tg_changed), \n            (p_sib_changed, (p_changed, p_gpar_changed))))))\n          p_par;\n          partial_tree_rep ls_changed p_root' p_par p_gpar_changed nullval;\n          data_at Tsh (tptr t_struct_rbtree) p_root' root))%assert; try pointer_destructor.\n      (** Note that here, _p should be p_changed, though this will not affect the \n          following proof. *)\n      {\n        color_replace.\n        (* show CaseOne_check is true *)\n        assert (Hcaseone: (CaseOne_check t\n             (true, c, k, v, tg, T Red sib1 k0 v0 t0 sib2)) = true).\n        {\n          remember (CaseOne_check t\n             (true, c, k, v, tg, T Red sib1 k0 v0 t0 sib2)) as bb.\n          destruct bb.\n          - reflexivity.\n          - unfold delete_check in H0. rewrite <- Heqbb in H0.\n            rewrite (match_color _ _ _ H4) in H0.\n            discriminate.\n        }\n        apply case_one_true in Hcaseone; [ | assumption ].\n        assert (Hcasettf: (CaseTTF_check t\n             (true, Red, k, v, default, tag_tree_t t0 sib2)) = true).\n        {\n          simpl in H0. rewrite (match_color _ _ _ H4) in H0.\n          rewrite if_else_then_true in H0. destruct H0 as [H0 _].\n          rewrite if_else_then_true in H0. destruct H0 as [H0 _].\n          exact H0.\n        }\n        pose proof Hcasettf as Hcopyttf.\n        apply (case_solve_not_null _ _ H4) in Hcasettf.\n        (* a critical conclusion *)\n        assert (Hfinal:\n          complete_tree_revarg (delete_balance t_initial ls_initial Black) = \n          complete_tree_revarg (match (CaseTTF_sol t\n             (true, Red, k, v, default, tag_tree_t t0 sib2) false) with\n          | (ts, true) => (ts, ((true, Black, k0, f v0 t0, tg, tag_tree_t t0 sib1) :: ls))\n          | (ts, false) =>\n            delete_balance ts\n            ((true, Black, k0, f v0 t0, tg, tag_tree_t t0 sib1) :: ls)\n            Black\n          end)).\n        {\n          rewrite H1.\n          remember (CaseTTF_sol t (true, Red,  k, v, default, tag_tree_t t0 sib2) false)\n            as br_ts.\n          destruct br_ts as [t_t br].\n          destruct br.\n          {\n            rewrite Hcaseone.\n            reflexivity.\n          }\n          destruct t_t; [ contradiction | ].\n          destruct Hcaseone as [Hcaseone | Hcaseone]; destruct Hcaseone as [Hco1 Hco2]. \n          - rewrite Hco2.\n            simpl delete_balance. \n            destruct c0; unfold complete_tree_revarg; simpl complete_tree; \n            [ reflexivity | simpl in Hco1; discriminate ].\n            - destruct Hco2 as [Hco2 Hco3]. \n            destruct Hco3 as [Hco3 Hco4].\n            destruct c0; [ discriminate | ].\n            remember (tag_tree_t t0 sib1) as t_t.\n            destruct t_t.\n            * discriminate Hco2.\n            * destruct c0; [ discriminate Hco2 | ].\n              rewrite Hco4.\n              reflexivity.\n        }\n        forward_call (Red, k0, v0, t0, p_sib_lch, p_sib_rch, p_par, p_sib, \n          sib1, sib2).  (* pushdown(p_sib); *)\n        forward.\n        forward.          (* p_sib->tag = p_fa->tag; *)\n        forward.          (* p_fa->tag = DEFAULT_TAG; *)\n        forward.          (* p_sib->color = p_fa->color; *)\n        forward.          (* p_fa->color = RED; *)\n        assert_PROP (is_pointer_or_null p_gpar) as PNp_gpar by entailer!. \n        forward_call      (* right_rotate_wrap(p_fa, root); *)\n        (Black, k0, (f v0 t0), tg, \n          Red, k, v, default, p_gpar,\n          (tag_tree_t t0 sib1), (tag_tree_t t0 sib2), t, \n          p_sib, p_par, p_sib_lch, p_sib_rch, p, \n          root, p_root', ls).\n        Intros p_root_new.\n        forward. try aggregate_solve.         (* p_sib = p_fa->left; *)\n        nonempty_tree_bycol sib2.\n        destruct c0.\n        { simpl in Hcopyttf. discriminate Hcopyttf. }\n        simpl rbtree_rep.\n        Intros p_sib_rch_lch p_sib_rch_rch.\n\n        Exists ((true, Black, k0, f v0 t0, tg, tag_tree_t t0 sib1)\n          :: ls).\n        Exists p p_sib p_sib_rch.\n        Exists Red default k1 v1 (t0 + t1) sib2_1 sib2_2.\n        Exists p_sib_rch_lch p_sib_rch_rch.\n        Exists p_root_new.\n        simpl tag_tree_t in *.\n        remember (CaseTTF_sol t (true, Red, k, v, default, \n          T Black sib2_1 k1 v1 (t0 + t1) sib2_2) false) as t_t.\n        destruct t_t as [ts br].\n        entailer!.\n        {\n          destruct br; auto.\n          destruct ts.\n          - contradiction.\n          - destruct Hcaseone as [Hcaseone | Hcaseone]; destruct Hcaseone as [Hco1 Hco2]. \n            + simpl in Hco1. destruct c0; [ | discriminate Hco1 ].\n              simpl. reflexivity.\n            + destruct Hco2 as [Hco2 Hco3].\n              remember (tag_tree_t t0 sib1) as t_t.\n              destruct t_t.\n              * discriminate Hco1.\n              * destruct c1; [ discriminate Hco1 | ].\n                destruct Hco3 as [Hco3 Hco4].\n                destruct c0; [ discriminate Hco3 | ].\n                unfold delete_check.\n                rewrite Hco1.\n                unfold delete_check in H0.\n                rewrite (match_color _ _ _ H4) in H0.\n                rewrite if_else_then_true in H0.\n                destruct H0 as [H0 Hco5].\n                rewrite <- Hco4.\n                rewrite Hco5.\n                auto.\n        }\n        simpl partial_tree_rep.\n        Exists p_gpar p_sib_lch.\n        entailer!.\n      }\n      {\n        forward.\n        color_replace.\n        Exists ls.\n        Exists p p_gpar p_sib.\n        Exists c tg k0 v0 t0 sib1 sib2.\n        Exists p_sib_lch p_sib_rch.\n        Exists p_root'.\n        remember (CaseTTF_sol t (true, c, k, v, tg, \n          T Black sib1 k0 v0 t0 sib2) false) as t_t.\n        destruct t_t as [ts br].\n        entailer!.\n        unfold delete_check in H0.\n        rewrite (match_color _ _ _ H4) in H0.\n        rewrite if_else_then_true in H0.\n        destruct H0 as [H00 H0].\n        rewrite <- Heqt_t in H0.\n        destruct br; [ split; auto | split; assumption ].\n      }\n\n      (* clear all the useless variables and hypothesis *)\n      clear H6.\n      clear p_root'.\n      Intros ls_ p_ p_gpar_ p_sib_.\n      Intros c_ tg_ k_ v_ t0_ sib1_ sib2_.\n      Intros p_sib_lch_ p_sib_rch_.\n      Intros p_root'.\n      remember (CaseTTF_sol t (true, c_, k, v, tg_, \n        T Black sib1_ k_ v_ t0_ sib2_) false) as t_t.\n      destruct t_t as [ts br].\n\n      (* Case 2 *)\n      forward; try aggregate_solve.\n      forward_call (sib1_, p_sib_lch_, p_sib_).\n      forward_if (temp _t'8\n        (Val.of_bool \n          ((negb (Int.eq (Int.repr (get_color_tree sib1_)) (Int.repr 1))) &&\n          (negb (Int.eq (Int.repr (get_color_tree sib2_)) (Int.repr 1)))))); try pointer_destructor.\n      {\n        forward; try aggregate_solve.\n        forward_call (sib2_, p_sib_rch_, p_sib_).\n        forward.\n        entailer!.\n        apply f_equal.\n        destruct sib1_.\n        - simpl get_color_tree. \n          unfold Int.eq, zeq. simpl. reflexivity.\n        - destruct c1; try contradiction.\n          simpl get_color_tree.\n          unfold Int.eq, zeq. simpl. reflexivity.\n      }\n      {\n        forward.\n        nonempty_tree_bycol sib1_.\n        simpl get_color_tree in *.\n        color_replace.\n        entailer!.\n      }\n      forward_if_wrp.\n        (* if (get_color(p_sib->left) != RED && get_color(p_sib->right) != RED) *)\n      {\n        assert (Hleftnotred : get_color_tree sib1_ <> Col2Z Red).\n        {\n          intro. rewrite H11 in H10.\n          unfold Int.eq, zeq in H10. simpl in H10.\n          discriminate. \n        }\n        assert (Hrightnotred : get_color_tree sib2_ <> Col2Z Red).\n        {\n          intro. rewrite H11 in H10.\n          unfold Int.eq, zeq in H10. simpl in H10.\n          rewrite andb_false_r in H10.\n          discriminate. \n        }\n        forward.        (* p_sib->color = RED; *)\n        forward.        (* p = p_fa; *)\n        forward.        (* p_fa = p->fa; *)\n        destruct sib1_; destruct sib2_;\n        simpl rbtree_rep;\n        simpl in H1; simpl in H0.\n        {\n          Intros.\n          Exists (T c_ (T Red Empty k_ v_ t0_ Empty) k v tg_ t) ls_.\n          Exists p_par p_gpar_ p_root'.\n          entailer!.\n          {\n            simpl in Heqt_t.\n            inversion Heqt_t.\n            destruct br; [ discriminate | ].\n            (* Case 2, so br = false *)\n            rewrite <- H12.\n            split; assumption.\n          }\n          simpl rbtree_rep.\n          Exists p_sib_. Exists p_.\n          Exists nullval nullval.\n          entailer!.\n        }\n        {\n          simpl get_color_tree in *.\n          destruct c1; [ contradiction | simpl in H0; discriminate ].\n        }\n        {\n          simpl get_color_tree in *.\n          destruct c1; [ contradiction | simpl in H0; discriminate ].\n        }\n        {\n          simpl get_color_tree in *.\n          destruct c1; [ contradiction | ].\n          destruct c2; [ contradiction | ].\n          Intros p_sib_lch_lch p_sib_lch_rch.\n          Intros p_sib_rch_lch p_sib_rch_rch.\n          Exists (T c_ (T Red (T Black sib1_1 k1 v1 t1 sib1_2) k_ v_ t0_\n                (T Black sib2_1 k2 v2 t2 sib2_2)) k v tg_ t) ls_.\n          Exists p_par p_gpar_ p_root'.\n          entailer!.\n          {\n            simpl in Heqt_t.\n            inversion Heqt_t.\n            destruct br; [ discriminate | ].\n            (* Case 2, so br = false *)\n            rewrite <- H24.\n            split; assumption.\n          }\n          simpl rbtree_rep.\n          Exists p_sib_ p_. entailer!.\n          Exists p_sib_lch_ p_sib_rch_. entailer!.\n          Exists p_sib_rch_lch. Exists p_sib_lch_lch.\n          Exists p_sib_lch_rch. Exists p_sib_rch_rch.\n          entailer!.\n        }\n      }\n      {\n        forward; try aggregate_solve.\n        forward_call (sib1_, p_sib_lch_, p_sib_).\n        apply semax_if_seq.\n        (** Here is a trade-off: we use semax_if_seq to avoid giving tedious\n            post-condition. *)\n        forward_if_wrp.   (* if (get_color(p_sib->left) != RED) *)\n        {\n          (* Case 3 *)\n          rewrite <- negb_orb in H10.\n          rewrite negb_false_iff in H10.\n          apply orb_prop in H10.\n          destruct H10 as [H10 | H10]; apply int_eq_e in H10; [ contradiction | ].\n          destruct sib2_; [ simpl in H10; discriminate | ].\n          simpl in H10.\n          color_replace.\n          simpl rbtree_rep.\n          Intros p_sib_rch_lch p_sib_rch_rch.\n          forward.\n          forward_call (Red, k1, v1, t1, p_sib_rch_lch, p_sib_rch_rch, \n            p_sib_, p_sib_rch_, sib2_1, sib2_2).\n                          (* pushdown(p_sib->right); *)\n          forward.\n          forward.\n          forward.    (* p_sib->right->tag = p_sib->tag; *)\n          forward.    (* p_sib->tag = DEFAULT_TAG; *)\n          forward.\n          forward.    (* p_sib->right->color = BLACK; *)\n          forward.    (* p_sib->color = RED; *)\n          forward_call\n          (Red, k_, v_, default, p_par, \n            Black, k1, (f v1 t1), t0_, \n            sib1_, (tag_tree_t t1 sib2_1), (tag_tree_t t1 sib2_2), \n            p_sib_, p_sib_rch_, p_sib_lch_, p_sib_rch_lch, p_sib_rch_rch, \n            root, p_root', (false, c_, k, v, tg_, t) :: ls_).\n                      (* left_rotate_wrap(p_sib, root); *)\n          {\n            simpl partial_tree_rep.\n            Exists p_gpar_ p_.\n            entailer!.\n          }\n          Intros p_root_new.\n          subst p_root_new.\n          simpl partial_tree_rep.\n          clear PNp_gpar_ p_gpar_ p_.\n          Intros p_gpar_ p_.\n          forward.    (* p_sib = p_fa->left; *)\n\n          assert_PROP (is_pointer_or_null p_sib_rch_) as PNp_sib_rch_ by entailer!.\n          forward_call (Black, k1, (f v1 t1), t0_, p_sib_, p_sib_rch_rch, \n            p_par, p_sib_rch_, (T Red sib1_ k_ v_ default (tag_tree_t t1 sib2_1)), \n            (tag_tree_t t1 sib2_2)).\n                      (* pushdown(p_sib); *)\n          {\n            simpl rbtree_rep.\n            Exists p_sib_lch_ p_sib_rch_lch.\n            entailer!.\n          }\n          simpl rbtree_rep.\n          Intros p_lch p_rch.\n          forward.\n          forward.    (* p_sib->tag = p_fa->tag; *)\n          forward.    (* p_fa->tag = DEFAULT_TAG; *)\n          forward.\n          forward.    (* p_sib->color = p_fa->color; *)\n          forward.    (* p_fa->color = BLACK; *)\n          forward.\n          forward.    (* p_sib->left->color = BLACK; *)\n          assert_PROP (is_pointer_or_null p_gpar_) as PNp_gpar_ by entailer!.\n          forward_call\n          (c_, k1, (f (f v1 t1) t0_), tg_, \n            Black, k, v, default, p_gpar_, \n            (T Black sib1_ k_ v_ (t0_ + 0) (tag_tree_t t1 sib2_1)), \n              (tag_tree_t t0_ (tag_tree_t t1 sib2_2)), t, \n            p_sib_rch_, p_par, p_sib_, p_sib_rch_rch, p_, \n            root, p_root', ls_).\n                      (* right_rotate_wrap(p_fa, root); *)\n          {\n            simpl rbtree_rep.\n            Exists p_lch p_rch.\n            entailer!.\n          }\n          Intros p_root_new.\n          simpl rbtree_rep.\n          clear p_lch p_rch.\n          Intros p_lch p_rch.\n          forward.    (* return ; *)\n\n          simpl tag_tree_t in *.\n          simpl in Heqt_t.\n          assert (Htsbr : (ts, br) = \n            (T c_ (T Black sib1_ k_ v_ (t0_ + 0) (tag_tree_t t1 sib2_1)) k1\n            (v1 + t1 + t0_) tg_ (T Black (tag_tree_t t0_ (tag_tree_t t1 sib2_2)) k v 0 t), true)).\n          {\n            destruct sib1_.\n            - assumption.\n            - simpl in *. color_replace. assumption.\n          }\n          inversion Htsbr. clear Htsbr.\n          subst br.\n          Exists ts.\n          Exists ls_.\n          sep_apply equivalence_nobox_box'.\n          Intros b.\n          Exists b p_gpar_.\n          entailer!.\n          unfold treebox_rep.\n          Exists p_sib_rch_.\n          simpl rbtree_rep.\n          Exists p_sib_ p_par. entailer!.\n          Exists p_sib_rch_rch. Exists p_lch. \n          Exists p_rch. Exists p_.\n          entailer!.\n        }\n        {\n        (* Case 4 *)\n          nonempty_tree_bycol sib1_.\n          simpl in H11.\n          color_replace.\n          simpl rbtree_rep.\n          Intros p_sib_lch_lch p_sib_lch_rch.\n          forward_call (Black, k_, v_, t0_, p_sib_lch_, p_sib_rch_,\n          p_par, p_sib_, (T Red sib1_1 k1 v1 t1 sib1_2), sib2_).\n                      (* pushdown(p_sib); *)\n          {\n            simpl rbtree_rep.\n            Exists p_sib_lch_lch p_sib_lch_rch.\n            entailer!.\n          }\n          simpl rbtree_rep.\n          clear p_sib_lch_lch p_sib_lch_rch.\n          Intros p_sib_lch_lch p_sib_lch_rch.\n          forward.\n          forward.    (* p_sib->tag = p_fa->tag; *)\n          forward.    (* p_fa->tag = DEFAULT_TAG; *)\n          forward.\n          forward.    (* p_sib->color = p_fa->color; *)\n          forward.    (* p_fa->color = BLACK; *)\n          forward.\n          forward.    (* p_sib->right->color = BLACK; *)\n          forward_call\n          (c_, k_, (f v_ t0_), tg_, \n            Black, k, v, default, p_gpar_, \n            (T Black sib1_1 k1 v1 (t0_ + t1) sib1_2), \n              (tag_tree_t t0_ sib2_), t, \n            p_sib_, p_par, p_sib_lch_, p_sib_rch_, p_, \n            root, p_root', ls_).\n                      (* left_rotate_wrap(p_fa, root); *)\n          {\n            simpl rbtree_rep.\n            Exists p_sib_lch_lch p_sib_lch_rch.\n            entailer!. \n          }\n          Intros p_root_new.\n          simpl rbtree_rep.\n          Intros p_lch p_rch.\n          forward.    (* return ; *)\n\n          simpl in Heqt_t.\n          inversion Heqt_t. clear Heqt_t.\n          subst br.\n          Exists ts.\n          Exists ls_.\n          sep_apply equivalence_nobox_box'.\n          Intros b.\n          Exists b p_gpar_.\n          entailer!.\n          unfold treebox_rep.\n          Exists p_sib_.\n          simpl rbtree_rep.\n          Exists p_sib_lch_ p_par. entailer!.\n          Exists p_sib_rch_. Exists p_lch. \n          Exists p_rch. Exists p_.\n          entailer!.\n        }\n      }\n    }\n  }\nQed.\n\nLemma delete_balance_red : forall t hft_list, \n  delete_balance t hft_list Red = (t, hft_list).\nProof.\n  intros.\n  destruct hft_list; reflexivity.\nQed.\n\nTheorem body_delete: semax_body Vprog Gprog f_delete delete_spec.\nProof. \n  start_function.\n  forward.          (* root = t; *)\n  unfold treebox_rep.\n  Intros p_root.\n  forward_loop\n  (EX t' : RBtree, \n  EX ls : list Half_tree, \n  EX p_par : val,\n  EX b : val, \n  PROP (delete_split x default t' ls = \n    delete_split x default t nil)\n  LOCAL (temp _x (Vint (Int.repr x)); \n        temp _t b; temp _root root) \n  SEP (partial_treebox_rep ls root b p_par nullval;\n      treebox_rep t' b p_par))\n  break:\n  (EX t_final : RBtree, \n  EX ls_final : list Half_tree, \n  EX color_final : color, \n  EX p_final : val, \n  EX p_par_final : val,\n  EX b_final : val,  \n  PROP ((ls_final, t_final, color_final) = \n    delete_with_no_balance x t)\n  LOCAL (temp _x (Vint (Int.repr x)); \n        temp _original_color (Vint (Int.repr (Col2Z color_final)));\n        temp _final_p p_final;\n        temp _final_p_par p_par_final;\n        temp _root root) \n  SEP (partial_treebox_rep ls_final root b_final p_par_final nullval;\n      data_at Tsh (tptr t_struct_rbtree) p_final b_final; \n      rbtree_rep t_final p_final p_par_final)).\n  (* almost the same as insertion... until tree_minimum *)\n  {\n    Exists t.\n    Exists (@nil Half_tree).\n    Exists nullval.\n    Exists root.\n    unfold treebox_rep.\n    Exists p_root.\n    entailer!.\n    simpl partial_treebox_rep.\n    entailer!.\n  } \n  { \n    Intros t' ls p_par b.\n    unfold treebox_rep.\n    Intros p.\n    forward; try aggregate_solve.          (* p = *t; *)\n    forward_if_wrp.\n    { (* if the target does not exist *)\n      subst p.\n      assert_PROP (t' = Empty) as Htempty by (sep_apply rbtree_rep_nullval; entailer).\n      forward_call (complete_tree ls Empty, root).\n      {\n        sep_apply reconstruction_lemma_box.\n        subst t'.\n        entailer!.\n      }\n      forward.        (* return; *)\n      unfold delete.\n      unfold delete_into_base_half. \n      unfold delete_with_no_balance in *.\n      rewrite <- H1 in H0.\n      unfold delete_split, insert_split in *. \n      simpl general_split in *.\n      simpl in H0.\n      rewrite <- H1.\n      simpl.\n      rewrite delete_balance_red.\n      unfold treebox_rep.\n      Intros p.\n      Exists p.\n      entailer!.\n    }\n    { (* in searching for the target *)\n      nonempty_tree t'.\n      Intros p_lch p_rch.\n      forward.        (* y = p->key; *)\n      forward_call (c, k, v, t0, p_lch, p_rch, p_par, p, t'1, t'2).\n                      (* pushdown(p); *)\n      forward_if_wrp.\n      { (* x < y *)\n        forward.      (* t = &(p->left); *)\n        Exists (tag_tree_t t0 t'1). \n        Exists ((false, c, k, v + t0, 0, tag_tree_t t0 t'2) :: ls).\n        unfold treebox_rep.\n        Exists p (offset_val 16 p).\n        entailer!.\n        {\n          rewrite <- H1.\n          unfold delete_split, insert_split.\n          simpl.\n          strip_0.\n          arith_bool.\n          rewrite H4.\n          symmetry.\n          apply general_split_tag. \n        }\n        Exists p_lch.\n        simpl partial_treebox_rep.\n        Exists p_par p_rch b.\n        quick_replace_offset_val p.\n        unfold_data_at (data_at _ _ _ p).\n        entailer!.\n      }\n      {\n        forward_if_wrp.\n        { (* x > y *)\n          forward.      (* t = &(p->left); *)\n          Exists (tag_tree_t t0 t'2). \n          Exists ((true, c, k, v + t0, 0, tag_tree_t t0 t'1) :: ls).\n          unfold treebox_rep.\n          Exists p (offset_val 20 p).\n          entailer!.\n          {\n            rewrite <- H1.\n            unfold delete_split, insert_split.\n            simpl.\n            strip_0.\n            arith_bool.\n            rewrite H4, H5.\n            symmetry.\n            apply general_split_tag. \n          }\n          Exists p_rch.\n          simpl partial_treebox_rep.\n          Exists p_par p_lch b.\n          quick_replace_offset_val p.\n          unfold_data_at (data_at _ _ _ p).\n          entailer!.\n        }\n        { (* now at the delete point *)\n          assert (k = x) by lia.\n          arith_bool.\n          unfold delete_with_no_balance in H0.\n          unfold delete_split at 1 in H1.\n          unfold insert_split at 1 in H1.\n          simpl general_split at 1 in H1.\n          rewrite H5 in H1.\n          rewrite H4 in H1.\n          rewrite <- H1 in H0.\n          simpl delete_root in H0.\n          simpl.\n          forward.      (* original_color = p->color; *)\n          forward; try aggregate_solve.\n          forward_if\n            (p_lch = nullval \\/ p_rch = nullval); try pointer_destructor.\n                        (* if (p->left != NULL) *)\n          {\n            nonempty_tree t'1.\n            Intros p_lch_lch p_lch_rch.\n            forward; try aggregate_solve.\n            forward_if_wrp.\n            {\n              nonempty_tree t'2.\n              Intros p_rch_lch p_rch_rch.\n              assert_PROP (field_compatible t_struct_rbtree [StructField _right] p)\n                as FCP_right by entailer!.\n              forward_call ((T c1 t'2_1 k1 v1 (t0 + t2) t'2_2), (offset_val 20 p), p).\n                            (* tmp = tree_minimum(&(p->right)); *)\n              2: { intro. discriminate. }\n              { \n                unfold treebox_rep.\n                Exists p_rch.\n                quick_replace_offset_val p.\n                unfold_data_at (data_at _ _ _ p).\n                entailer!.\n                simpl rbtree_rep.\n                Exists p_rch_lch p_rch_rch.\n                entailer!.\n              }\n              Intros vret.\n              destruct vret as [[[[[[min_b min_p_par] min_ls] min_c] min_k] min_v] min_sib].\n              simpl fst in *.\n              simpl snd in *.\n              unfold treebox_rep.\n              Intros min_p.\n              simpl rbtree_rep.\n              Intros min_p_lch min_p_rch.\n              subst min_p_lch.\n              forward.      (* targ = *tmp; *)\n              forward.      (* original_color = targ->color; *)\n              forward.\n              forward.      (* targ->left = p->left; *)\n              forward.\n              forward.      (* p->left->fa = targ; *)\n              forward.\n              forward.      (* targ->color = p->color; *)\n              forward.\n              apply semax_if_seq.\n              (** Here, since the post-condition can be very complex, \n                  we apply semax_if_seq. *)\n              forward_if_wrp.\n              {\n                (** In this case, min_ls must be empty. *)\n                destruct min_ls; simpl partial_treebox_rep.\n                - Intros. subst p. entailer!.\n                - destruct h as [[[[[va ?] ?] ?] ?] ?].\n                  simpl.\n                  Intros p_gpar p_sib b_par.\n                  destruct va; entailer!.\n              }\n              {\n                destruct min_ls.\n                2: {\n                  destruct h as [[[[[va ?] ?] ?] ?] ?].\n                  simpl.\n                  Intros p_gpar p_sib b_par.\n                  destruct va;\n                    sep_apply field_at_conflict; try apply sepalg_Tsh;\n                    sep_apply FF_local_facts;\n                    Intros;\n                    contradiction.\n                }\n                simpl partial_treebox_rep.\n                Intros.\n                subst min_b.\n                forward; try aggregate_solve.\n                forward.    (* final_p = targ->right; *)\n                forward.    (* final_p_par = targ; *)\n                forward.    (* targ->fa = p->fa; *)\n                forward.    (* *t = targ; *)\n                forward_call (p, sizeof t_struct_rbtree).\n                            (* freeN(p, sizeof *p); *)\n                {\n                  quick_replace_offset_val p.\n                  sep_apply field_at_gather_right.\n                  entailer!.\n                  rewrite memory_block_data_at_ by auto.\n                  cancel.\n                }\n                forward.    (* break; *)\n\n                simpl app in H0.\n                unfold delete_with_no_balance.\n                rewrite <- H1.\n                simpl delete_root.\n                replace (0 + t0 + t2) with (t0 + t2) by lia.\n                simpl default in *.\n                rewrite H11.\n                simpl app.\n                Exists min_sib.\n                Exists ((true, c, min_k, min_v, 0, T c0 t'1_1 k0 v0 (0 + t0 + t1)%Z t'1_2) :: ls).\n                Exists min_c.\n                Exists min_p_rch.\n                Exists min_p.\n                Exists (offset_val 20 min_p).\n                entailer!.\n                simpl partial_treebox_rep.\n                Exists p_par p_lch b.\n                Exists p_lch_lch p_lch_rch.\n                quick_replace_offset_val min_p.\n                unfold_data_at (data_at _ _ _ min_p).\n                entailer!.\n              }\n              {\n                destruct min_ls.\n                {\n                  simpl partial_treebox_rep.\n                  Intros.\n                  contradiction.\n                }\n                forward; try aggregate_solve.\n                forward_if\n                (PROP ( )\n                 LOCAL (temp _t'17 min_p_rch; temp _t'13 min_p_par;\n                 temp _t'20 (Vint (Int.repr (Col2Z c))); \n                 temp _t'21 p_lch; temp _t'22 p_lch;\n                 temp _original_color (Vint (Int.repr (Col2Z min_c)));\n                 temp _targ min_p; temp _tmp min_b; temp _t'11 p_rch;\n                 temp _t'10 p_lch; temp _y (Vint (Int.repr k)); \n                 temp _p p; temp _x (Vint (Int.repr x)); \n                 temp _t b; temp _root root)\n                 SEP (data_at Tsh (tptr t_struct_rbtree) min_p min_b;\n                 data_at Tsh t_struct_rbtree\n                   (Vint (Int.repr (Col2Z c)),\n                   (Vint (Int.repr min_k),\n                   (Vint (Int.repr min_v),\n                   (Vint (Int.repr 0), (p_lch, (min_p_rch, min_p_par))))))\n                   min_p; emp; rbtree_rep min_sib min_p_rch min_p_par;\n                 partial_treebox_rep (h :: min_ls) (offset_val 20 p) min_b\n                   min_p_par p;\n                 field_at Tsh t_struct_rbtree [StructField _color]\n                   (Vint (Int.repr (Col2Z c))) p;\n                 field_at Tsh t_struct_rbtree [StructField _key]\n                   (Vint (Int.repr k)) p;\n                 field_at Tsh t_struct_rbtree [StructField _value]\n                   (Vint (Int.repr (v + t0))) p;\n                 field_at Tsh t_struct_rbtree [StructField _tag]\n                   (Vint (Int.repr 0)) p;\n                 field_at Tsh t_struct_rbtree [StructField _left] p_lch p;\n                 field_at Tsh t_struct_rbtree [StructField _par] p_par p;\n                 data_at Tsh t_struct_rbtree\n                   (Vint (Int.repr (Col2Z c0)),\n                   (Vint (Int.repr k0),\n                   (Vint (Int.repr v0),\n                   (Vint (Int.repr (t0 + t1)),\n                   (p_lch_lch, (p_lch_rch, min_p)))))) p_lch;\n                 rbtree_rep t'1_1 p_lch_lch p_lch;\n                 rbtree_rep t'1_2 p_lch_rch p_lch;\n                 partial_treebox_rep ls root b p_par nullval;\n                 data_at Tsh (tptr t_struct_rbtree) p b)); try pointer_destructor.\n                {\n                  nonempty_tree min_sib.\n                  Intros min_p_rch_lch min_p_rch_rch.\n                  forward.\n                  forward.\n                  forward.    (* targ->right->fa = targ->fa; *)\n                  entailer!.\n                  simpl rbtree_rep.\n                  Exists min_p_rch_lch min_p_rch_rch.\n                  entailer!.\n                }\n                {\n                  subst min_p_rch.\n                  empty_tree min_sib.\n                  forward.\n                  simpl rbtree_rep.\n                  entailer!.\n                }\n                forward.\n                forward.      (* *tmp = targ->right; *)\n                pose proof (list_cons_app min_ls h) as Hlistcons.\n                destruct Hlistcons as [ls2 [a Hlistcons]].\n                destruct a as [[[[[va' c'] k'] v'] tg'] sib'].\n                pose proof H12 as Hturnleftcopy.\n                rewrite Hlistcons in Hturnleftcopy.\n                rewrite Forall_app in Hturnleftcopy.\n                destruct Hturnleftcopy as [_ Hturnleftcopy].\n                inversion Hturnleftcopy.\n                unfold turn_left in H18.\n                subst va'.\n                clear x0 l H19 H16 H17.\n                (* remove temporary things generated by inversion *)\n                rewrite Hlistcons.\n                pose proof (partialtreebox_backward ls2 false c' k' v' tg' \n                  sib' (offset_val 20 p) min_b min_p_par p) as Hparback.\n                assert_PROP (is_pointer_or_null min_b) as PNmin_b by entailer!.\n                sep_apply Hparback; [ assumption | ].\n                clear Hparback.\n                Intros p_rch' p_rch_rch'. \n                quick_replace_offset_val p.\n                Intros.\n                sep_apply (field_at_gather_right p).\n                forward.\n                forward.      (* targ->right = p->right; *)\n                forward.\n                forward.      (* p->right->fa = targ; *)\n                forward.      (* final_p = *tmp; *)\n                forward.      (* final_p_par = targ->fa; *)\n                forward.\n                forward.      (* targ->fa = p->fa; *)\n                forward.      (* *t = targ; *)\n                forward_call (p, sizeof t_struct_rbtree).\n                              (* freeN(p, sizeof *p); *)\n                {\n                  entailer!.\n                  rewrite memory_block_data_at_ by auto.\n                  cancel.\n                }\n                forward.      (* break; *)\n\n                simpl app in H0.\n                unfold delete_with_no_balance.\n                rewrite <- H1.\n                simpl delete_root.\n                replace (0 + t0 + t2) with (t0 + t2) by lia.\n                simpl default in *.\n                rewrite H11.\n                simpl app.\n                Exists min_sib.\n                Exists ((h :: min_ls) ++ (true, c, min_k, min_v, 0, \n                  T c0 t'1_1 k0 v0 (0 + t0 + t1)%Z t'1_2) :: ls).\n                Exists min_c.\n                Exists min_p_rch.\n                Exists min_p_par.\n                Exists min_b.\n                entailer!.\n                eapply derives_trans.\n                2: {\n                  apply partialtreebox_link with (b1:=(offset_val 20 min_p)) (p1:=min_p).\n                }\n                rewrite Hlistcons.\n                simpl partial_treebox_rep.\n                Exists p_par p_lch b.\n                Exists p_lch_lch p_lch_rch.\n                quick_replace_offset_val min_p.\n                unfold_data_at (data_at _ _ _ min_p).\n                entailer!.\n                eapply derives_trans.\n                2: {\n                  apply partialtreebox_link with (b1:=\n                    (field_address t_struct_rbtree [StructField _left] p_rch')) (p1:=p_rch').\n                }\n                simpl partial_treebox_rep.\n                Exists min_p p_rch_rch' (field_address t_struct_rbtree [StructField _right] min_p).\n                entailer!.\n              }\n            }\n            {\n              forward.\n              entailer!.\n              simpl rbtree_rep.\n              Exists p_lch_lch p_lch_rch.\n              entailer!. \n            }\n          }\n          {\n            forward.\n            entailer!.\n          }\n          Intros.\n          forward.\n          apply semax_if_seq.\n          forward_if_wrp.\n          {\n            destruct H7; [ contradiction | ].\n            subst p_rch.\n            remember (tag_tree_t t0 t'2) as tagt'2.\n            empty_tree tagt'2.\n            rewrite tag_tree_t_empty in H7.\n            subst t'2.\n            nonempty_tree t'1.\n            Intros p_lch_lch p_lch_rch. \n            forward.\n            forward.          (* *t = p->left; *)\n            forward.\n            forward.\n            forward.          (* p->left->fa = p->fa; *)\n            forward.          (* final_p = *t; *)\n            forward.          (* final_p_par = p->fa; *)\n            forward_call (p, sizeof t_struct_rbtree).\n                              (* freeN(p, sizeof *p); *)\n            {\n              entailer!.\n              rewrite memory_block_data_at_ by auto.\n              cancel.\n            }\n            forward.      (* break; *)\n\n            simpl in H0.\n            unfold delete_with_no_balance.\n            rewrite <- H1.\n            simpl delete_root.\n            Exists (T c0 t'1_1 k0 v0 (0 + (0 + t0 + t1))%Z t'1_2).\n            Exists ls.\n            Exists c.\n            Exists p_lch.\n            Exists p_par.\n            Exists b.\n            entailer!.\n            simpl rbtree_rep.\n            Exists p_lch_lch p_lch_rch.\n            entailer!.\n          }\n          {\n            subst p_lch.\n            remember (tag_tree_t t0 t'1) as tagt'1.\n            empty_tree tagt'1.\n            rewrite tag_tree_t_empty in H8.\n            subst t'1.\n            forward; try aggregate_solve.\n            apply semax_if_seq.\n            forward_if_wrp.\n            {\n              nonempty_tree t'2.\n              Intros p_rch_lch p_rch_rch. \n              forward.\n              forward.        (* *t = p->right; *)\n              forward.\n              forward.\n              forward.        (* p->right->fa = p->fa; *)\n              forward.        (* final_p = *t; *)\n              forward.        (* final_p_par = p->fa; *)\n              forward_call (p, sizeof t_struct_rbtree).\n                              (* freeN(p, sizeof *p); *)\n              {\n                entailer!.\n                rewrite memory_block_data_at_ by auto.\n                cancel.\n              }\n              forward.      (* break; *)\n\n              simpl in H0.\n              unfold delete_with_no_balance.\n              rewrite <- H1.\n              simpl delete_root.\n              Exists (T c0 t'2_1 k0 v0 (0 + (0 + t0 + t1))%Z t'2_2).\n              Exists ls.\n              Exists c.\n              Exists p_rch.\n              Exists p_par.\n              Exists b.\n              entailer!.\n              simpl rbtree_rep.\n              Exists p_rch_lch p_rch_rch. \n              entailer!.\n            }\n            {\n              subst p_rch.\n              remember (tag_tree_t t0 t'2) as tagt'2.\n              empty_tree tagt'2.\n              rewrite tag_tree_t_empty in H8.\n              subst t'2.\n              forward.        (* *t = NULL; *)\n              forward.        (* final_p = *t; *)\n              forward.        (* final_p_par = p->fa; *)\n              forward_call (p, sizeof t_struct_rbtree).\n                              (* freeN(p, sizeof *p); *)\n              {\n                entailer!.\n                rewrite memory_block_data_at_ by auto.\n                cancel.\n              }\n              forward.      (* break; *)\n\n              simpl in H0.\n              unfold delete_with_no_balance.\n              rewrite <- H1.\n              simpl delete_root.\n              Exists Empty.\n              Exists ls.\n              Exists c.\n              Exists nullval.\n              Exists p_par.\n              Exists b.\n              entailer!.\n              simpl rbtree_rep.\n              entailer!.\n            }\n          }\n        }\n      }\n    }\n  }\n  Intros t_final ls_final color_final p_final p_par_final b_final.\n  rewrite <- H1 in H0.\n  forward_if\n  (EX t_balanced : RBtree, \n   EX ls_balanced : list Half_tree,\n   EX b_balanced : val, \n   EX p_par_balanced : val,\n   EX p_balanced : val,\n  (PROP (complete_tree_revarg (t_balanced, ls_balanced) =\n     complete_tree_revarg (delete_balance t_final ls_final color_final))\n   LOCAL (temp _x (Vint (Int.repr x));\n   temp _original_color (Vint (Int.repr (Col2Z color_final))); temp _final_p p_final;\n   temp _final_p_par p_par_final; temp _root root)\n   SEP (partial_treebox_rep ls_balanced root b_balanced p_par_balanced nullval;\n   data_at Tsh (tptr t_struct_rbtree) p_balanced b_balanced; \n   rbtree_rep t_balanced p_balanced p_par_balanced))); try pointer_destructor.\n  {\n    color_replace.\n    forward_call (t_final, root, p_final, p_par_final, b_final, ls_final).\n                            (* delete_balance(final_p, final_p_par, root); *)\n    Intros vret.\n    destruct vret as [[[t_balanced ls_balanced] b_balanced] p_par_balanced].\n    simpl fst in *.\n    simpl snd in *.\n    unfold treebox_rep.\n    Intros p_balanced.\n    Exists t_balanced ls_balanced b_balanced p_par_balanced p_balanced.\n    entailer!.\n  }\n  {\n    forward.\n    Exists t_final ls_final b_final p_par_final p_final.\n    entailer!.\n    color_replace.\n    rewrite delete_balance_red.\n    reflexivity. \n  }\n  Intros t_balanced ls_balanced b_balanced p_par_balanced p_balanced.\n  forward_call ((complete_tree ls_balanced t_balanced), root).\n  {\n    sep_apply reconstruction_lemma_box.\n    entailer!.\n  }\n  Exists (makeBlack (complete_tree ls_balanced t_balanced)).\n  entailer!.\n  unfold treebox_rep.\n  Intros p.\n  Exists p.\n  entailer!.\n  unfold delete.\n  unfold delete_into_base_half.\n  rewrite <- H1.\n  remember (delete_balance t_final ls_final color_final) as bs_hf.\n  destruct bs_hf as [base half].\n  unfold complete_tree_revarg in H2.\n  simpl in H2.\n  rewrite H2.\n  entailer!.\nQed.\n\n(* proof for insert_balance *)\nTheorem body_insert_balance: \n  semax_body Vprog Gprog f_insert_balance insert_balance_spec.\nProof.\n  start_function.\n  unfold treebox_rep.\n  Intros p_initial.\n  forward; try aggregate_solve.\n  sep_apply equivalence_box_nobox'.\n  Intros p_root.\n  (*\n  destruct t_initial as [ | c lch k v tg rch] eqn:Et_initial; [ contradiction | ].\n  simpl rbtree_rep.\n  Intros p_lch p_rch.\n  *)\n  forward_loop\n  (EX t : RBtree, \n  EX ls : list Half_tree, \n  EX p : val, \n  EX p_par : val,\n  PROP (t <> Empty; balance' ls_initial t_initial = balance' ls t)\n  LOCAL (temp _root root; temp _p p)\n  SEP (rbtree_rep t p p_par *\n    partial_tree_rep ls p_root p p_par nullval;\n    data_at Tsh (tptr t_struct_rbtree) p_root root)).\n  {\n    Exists t_initial.\n    Exists ls_initial.\n    Exists p_initial p_par_initial.\n    entailer!.\n  }\n  {\n    Intros t ls p p_par.\n    destruct t as [ | c lch k v tg rch] eqn:Et; [ contradiction | ].\n    simpl rbtree_rep.\n    Intros p_lch p_rch.\n    forward.            (* p_par = (p -> par); *)\n    forward_if_wrp.         (* if (p_par == NULL) *)\n    {\n      subst p_par.\n      empty_partialtree ls.\n      forward.          (* return; *)\n      Exists (T c lch k v tg rch).\n      Exists (@nil Half_tree).\n      Exists root nullval. \n      unfold treebox_rep.\n      Exists p.\n      simpl partial_treebox_rep.\n      rewrite H1.\n      simpl balance' at 1.\n      simpl rbtree_rep.\n      Exists p_lch p_rch.\n      entailer!.\n    }\n    {\n      (* second branch: p_par is not NULL *)\n      nonempty_partialtree ls.\n      destruct h as [[[[[va c_p] k_p] v_p] tg_p] sib].\n      Intros p_gpar p_sib.\n      forward.        (* p_gfa = p_fa->fa; *)\n      forward_if_wrp.     (* if (p_gfa == NULL) *)\n      {\n        subst p_gpar.\n        empty_partialtree ls.\n        (* p_gfa is null, then return *)\n        forward.      (* return ; *)\n        Exists (T c lch k v tg rch).\n        Exists ((va, c_p, k_p, v_p, tg_p, sib) :: nil).\n        rewrite H1.\n        simpl balance' at 1.\n        simpl partial_tree_rep.\n        destruct va;\n          [Exists (field_address t_struct_rbtree [StructField _right] p_par) p_par |\n          Exists (field_address t_struct_rbtree [StructField _left] p_par) p_par];\n          unfold treebox_rep;\n          Exists p;\n          simpl rbtree_rep;\n          Exists p_lch p_rch;\n          simpl partial_treebox_rep;\n          Exists nullval p_sib root;\n          unfold_data_at (data_at _ _ _ p_par);\n          entailer!.\n      }\n      {\n        nonempty_partialtree ls.\n        destruct h as [[[[[va_p c_g] k_g] v_g] tg_g] sib_p].\n        assert_PROP (is_pointer_or_null p_gpar) as PNp_gpar by entailer!.\n        Intros p_ggpar p_par_sib.\n        forward.\n        forward_if_wrp.           (* if (p_fa->color == BLACK) *)\n        {\n          (* there is no need to go upward *)\n          color_replace.\n          forward.    (* return ; *)\n          Exists (T c lch k v tg rch).\n          Exists ((va, Black, k_p, v_p, tg_p, sib)\n            :: (va_p, c_g, k_g, v_g, tg_g, sib_p) :: ls).\n          sep_apply equivalence_nobox_box'.\n          Intros b_par.\n          destruct va;\n            [ Exists (field_address t_struct_rbtree [StructField _right] p_par) p_par |\n              Exists (field_address t_struct_rbtree [StructField _left] p_par) p_par ];\n            rewrite H1;\n            unfold treebox_rep;\n            Exists p;\n            simpl rbtree_rep;\n            Exists p_lch p_rch;\n            simpl partial_treebox_rep;\n            Exists p_gpar p_sib;\n            destruct va_p;\n              [ Exists (field_address t_struct_rbtree [StructField _right] p_gpar) |\n                Exists (field_address t_struct_rbtree [StructField _left] p_gpar) |\n                Exists (field_address t_struct_rbtree [StructField _right] p_gpar) |\n                Exists (field_address t_struct_rbtree [StructField _left] p_gpar) ];\n              Exists p_ggpar p_par_sib b_par;\n              unfold_data_at (data_at _ _ _ p_par);\n              unfold_data_at (data_at _ _ _ p_gpar);\n              entailer!.\n        }\n        {\n          (* otherwise go upward *)\n          assert_PROP (tc_val (tptr t_struct_rbtree)\n            (if va then p_sib else p)) as H_p1.\n          { destruct va; aggregate_solve. }\n          assert_PROP (tc_val (tptr t_struct_rbtree)\n            (if va then p else p_sib)) as H_p2.\n          { destruct va; aggregate_solve. }\n          assert_PROP (tc_val (tptr t_struct_rbtree)\n            (if va_p then p_par_sib else p_par)) as H_p3.\n          { destruct va_p; aggregate_solve. }\n          assert_PROP (tc_val (tptr t_struct_rbtree)\n            (if va_p then p_par else p_par_sib)) as H_p4.\n          { destruct va_p; aggregate_solve. }\n          (** All the conclusions above are auxiliary. *)\n\n          forward.\n          forward_if_wrp.       (* if (p == p_fa->left) *)\n          { destruct va; entailer!. }\n          {\n            destruct va.\n            {\n              (* eliminate the case *)\n              subst p_sib.\n              common_pointer_solve p sib.\n            }\n            forward.\n            forward_if_wrp.     (* if (p_fa == p_gfa->left) *)\n            { destruct va_p; entailer!. }\n            {\n              destruct va_p.\n              {\n                subst p_par_sib.\n                common_pointer_solve p_par sib_p.\n              }\n              forward.\n              forward_call (sib_p, p_par_sib, p_gpar).\n              color_replace.\n              forward_if_wrp.     (* if (get_color(p_gfa->right) != RED) *)\n              {\n                (* perform rotations *)\n                forward.          (* p_gfa->color = RED; *)\n                forward.          (* p_fa->color = BLACK; *)\n                assert_PROP (is_pointer_or_null p_ggpar) as PNp_ggpar by entailer!.\n                forward_call \n                (Black, k_p, v_p, tg_p, \n                  Red, k_g, v_g, tg_g, p_ggpar, \n                  (T c lch k v tg rch), sib, sib_p,  \n                  p_par, p_gpar, p, p_sib, p_par_sib, \n                  root, p_root, ls).\n                { simpl rbtree_rep. Exists p_lch p_rch. entailer!. }\n                Intros p_root_new.\n                forward.        (* return; *)\n                Exists (T Black (T c lch k v tg rch) k_p v_p tg_p\n                  (T Red sib k_g v_g tg_g sib_p)).\n                sep_apply equivalence_nobox_box'.\n                Intros b_par.\n                Exists ls b_par p_ggpar.\n                entailer!.\n                {\n                  rewrite H1. destruct sib_p.\n                  - simpl balance'. reflexivity.\n                  - simpl get_color_tree in *. color_replace. \n                    simpl balance'. reflexivity.\n                }\n                unfold treebox_rep.\n                Exists p_par.\n                simpl rbtree_rep at 1.\n                Intros p_lch0 p_rch0.\n                simpl rbtree_rep.\n                Exists p p_gpar.\n                Exists p_sib p_par_sib.\n                Exists p_lch0 p_rch0.\n                entailer!.\n              }\n              {\n                nonempty_tree_bycol sib_p.\n                simpl in H7.\n                color_replace.\n                simpl rbtree_rep.\n                Intros p_par_sib_lch p_par_sib_rch.\n                forward.          (* p_fa->color = BLACK; *)\n                forward.\n                forward.          (* p_gfa->left->color = BLACK; *)\n                forward.          (* p_gfa->color = RED; *)\n                forward.          (* p = p_gfa; *)\n                simpl balance' in H1.\n                Exists \n                (T Red (T Black (T c lch k v tg rch) k_p v_p tg_p sib)\n                  k_g v_g tg_g (T Black sib_p1 k0 v0 t0 sib_p2)).\n                Exists ls.\n                Exists p_gpar p_ggpar.\n                simpl rbtree_rep.\n                Exists p_par p_par_sib.\n                Exists p_par_sib_lch p.\n                Exists p_par_sib_rch p_sib.\n                Exists p_lch p_rch.\n                entailer!.\n                discriminate.\n              }\n            }\n            {\n              destruct va_p; [ | contradiction ].\n              forward.\n              forward_call (sib_p, p_par_sib, p_gpar).\n              forward_if_wrp. \n              {\n                forward.          (* p_gfa->color = RED; *)\n                forward.          (* p_fa->color = BLACK; *)\n                forward_call\n                (Black, k, v, tg, \n                  c_p, k_p, v_p, tg_p, p_gpar, \n                  lch, rch, sib, \n                  p, p_par, p_lch, p_rch, p_sib). \n                forward.\n                assert_PROP (is_pointer_or_null p_ggpar) as PNp_ggpar by entailer!.\n                forward_call \n                (Red, k_g, v_g, tg_g, p_ggpar, \n                  Black, k, v, tg,  \n                  sib_p, lch, (T c_p rch k_p v_p tg_p sib), \n                  p_gpar, p, p_par_sib, p_lch, p_par, \n                  root, p_root, ls). \n                { simpl rbtree_rep. Exists p_rch p_sib. entailer!. }\n                Intros p_root_new.\n                forward.        (* return; *)\n                Exists (T Black (T Red sib_p k_g v_g tg_g lch) k v tg\n                  (T Red rch k_p v_p tg_p sib)).\n                sep_apply equivalence_nobox_box'.\n                Intros b_par.\n                Exists ls b_par p_ggpar.\n                entailer!.\n                color_replace.\n                {\n                  rewrite H1. destruct sib_p.\n                  - simpl balance'. reflexivity.\n                  - simpl get_color_tree in *. color_replace. \n                    simpl balance'. reflexivity.\n                }\n                unfold treebox_rep.\n                Exists p.\n                simpl rbtree_rep.\n                Intros p_lch0 p_rch0.\n                Exists p_gpar p_par.\n                entailer!.\n                Exists p_lch0. Exists p_par_sib.\n                Exists p_lch. Exists p_rch0.\n                color_replace.\n                entailer!.\n              }\n              {\n                (* otherwise change color and push up *)\n                nonempty_tree_bycol sib_p.\n                simpl in H7, H10.\n                color_replace.\n                simpl rbtree_rep.\n                Intros p_par_sib_lch p_par_sib_rch.\n                forward.          (* p_fa->color = BLACK; *)\n                forward.\n                forward.          (* p_gfa->right->color = BLACK; *)\n                forward.          (* p_gfa->color = RED; *)\n                forward.          (* p = p_gfa; *)\n                simpl balance' in H1.\n                Exists \n                (T Red (T Black sib_p1 k0 v0 t0 sib_p2) k_g v_g\n                  tg_g (T Black (T c lch k v tg rch) k_p v_p tg_p sib)).\n                Exists ls.\n                Exists p_gpar p_ggpar.\n                simpl rbtree_rep.\n                Exists p_par_sib p_par.\n                Exists p p_par_sib_lch.\n                Exists p_sib p_par_sib_rch.\n                Exists p_lch p_rch.\n                entailer!.\n                color_replace.\n                rewrite H1.\n                split; [ intro; discriminate | auto ].\n              }\n            }\n          }\n          {\n            destruct va; [ | contradiction ].\n            forward.\n            forward_if_wrp.     (* if (p_fa == p_gfa->left) *)\n            { destruct va_p; entailer!. }\n            {\n              destruct va_p. \n              {\n                subst p_par_sib.\n                common_pointer_solve p_par sib_p.\n              }\n              forward.\n              forward_call (sib_p, p_par_sib, p_gpar).\n              forward_if_wrp. \n              {\n                forward.          (* p_gfa->color = RED; *)\n                forward.          (* p_fa->color = BLACK; *)\n                forward_call\n                (c_p, k_p, v_p, tg_p, p_gpar, \n                  Black, k, v, tg, \n                  sib, lch, rch,\n                  p_par, p, p_sib, p_lch, p_rch).\n                forward.\n                assert_PROP (is_pointer_or_null p_ggpar) as PNp_ggpar by entailer!.\n                forward_call \n                (Black, k, v, tg, \n                  Red, k_g, v_g, tg_g, p_ggpar, \n                  (T c_p sib k_p v_p tg_p lch), rch, sib_p,\n                  p, p_gpar, p_par, p_rch, p_par_sib, \n                  root, p_root, ls).\n                {\n                  simpl rbtree_rep.\n                  Exists p_sib p_lch.\n                  entailer!.\n                }\n                Intros p_root_new.\n                forward.          (* return; *)\n                Exists (T Black (T Red sib k_p v_p tg_p lch) \n                    k v tg (T Red rch k_g v_g tg_g sib_p)).\n                sep_apply equivalence_nobox_box'.\n                Intros b_par.\n                Exists ls b_par p_ggpar.\n                color_replace.\n                entailer!.\n                {\n                  rewrite H1. destruct sib_p.\n                  - simpl balance'. reflexivity.\n                  - simpl get_color_tree in *. color_replace. \n                    simpl balance'. reflexivity.\n                }\n                unfold treebox_rep.\n                Exists p.\n                simpl rbtree_rep.\n                Intros p_lch0 p_rch0.\n                Exists p_par p_gpar.\n                entailer!.\n                Exists p_rch. Exists p_lch0.\n                Exists p_rch0. Exists p_par_sib.\n                entailer!.\n              }\n              {\n                (* otherwise change color and push up *)\n                nonempty_tree_bycol sib_p.\n                simpl in H7, H10.\n                color_replace.\n                simpl rbtree_rep.\n                Intros p_par_sib_lch p_par_sib_rch.\n                forward.          (* p_fa->color = BLACK; *)\n                forward.\n                forward.          (* p_gfa->right->color = BLACK; *)\n                forward.          (* p_gfa->color = RED; *)\n                forward.          (* p = p_gfa; *)\n                Exists \n                (T Red (T Black sib k_p v_p tg_p (T c lch k v tg rch))\n                  k_g v_g tg_g (T Black sib_p1 k0 v0 t0 sib_p2)).\n                Exists ls.\n                Exists p_gpar p_ggpar.\n                simpl rbtree_rep.\n                Exists p_par p_par_sib.\n                Exists p_par_sib_lch p_sib. \n                Exists p_par_sib_rch p.\n                Exists p_lch p_rch.\n                entailer!.\n                simpl balance' in H1.\n                color_replace.\n                rewrite H1.\n                split; [ intro; discriminate | auto ].\n              }\n            }\n            {\n              destruct va_p; [| contradiction ].\n              forward.\n              forward_call (sib_p, p_par_sib, p_gpar).\n              color_replace.\n              forward_if_wrp.         (* if (get_color(p_gfa->left) != RED) *)\n              {\n                forward.          (* p_gfa->color = RED; *)\n                forward.          (* p_fa->color = BLACK; *)\n                assert_PROP (is_pointer_or_null p_ggpar) as PNp_ggpar by entailer!.\n                forward_call \n                (Red, k_g, v_g, tg_g, p_ggpar, \n                  Black, k_p, v_p, tg_p, \n                  sib_p, sib, (T c lch k v tg rch), \n                  p_gpar, p_par, p_par_sib, p_sib, p, \n                  root, p_root, ls).\n                {   \n                  simpl rbtree_rep.\n                  Exists p_lch p_rch.\n                  entailer!.\n                }\n                Intros p_root_new.\n                forward.        (* return; *)\n                Exists (T Black (T Red sib_p k_g v_g tg_g sib)\n                      k_p v_p tg_p (T c lch k v tg rch)).\n                sep_apply equivalence_nobox_box'.\n                Intros b_par.\n                Exists ls b_par p_ggpar.\n                entailer!.\n                {\n                  rewrite H1. destruct sib_p.\n                  - simpl balance'. reflexivity.\n                  - simpl get_color_tree in *. color_replace. \n                    simpl balance'. reflexivity.\n                }\n                unfold treebox_rep.\n                Exists p_par.\n                simpl rbtree_rep.\n                Intros p_lch0 p_rch0.\n                Exists p_gpar p.\n                entailer!.\n                Exists p_lch0. Exists p_par_sib.\n                Exists p_sib. Exists p_rch0.\n                entailer!.\n              }\n              {\n                nonempty_tree_bycol sib_p.\n                simpl in H7.\n                color_replace.\n                simpl rbtree_rep.\n                Intros p_par_sib_lch p_par_sib_rch.\n                forward.          (* p_fa->color = BLACK; *)\n                forward.\n                forward.          (* p_gfa->left->color = BLACK; *)\n                forward.          (* p_gfa->color = RED; *)\n                forward.          (* p = p_gfa; *)\n                simpl balance' in H1.\n                Exists \n                (T Red (T Black sib_p1 k0 v0 t0 sib_p2) k_g v_g tg_g\n                  (T Black sib k_p v_p tg_p (T c lch k v tg rch))).\n                Exists ls.\n                Exists p_gpar p_ggpar.\n                simpl rbtree_rep.\n                Exists p_par_sib p_par.\n                Exists p_sib p_par_sib_lch.\n                Exists p p_par_sib_rch.\n                Exists p_lch p_rch.\n                entailer!. \n                discriminate.\n              }\n            }\n          }\n        }\n      }\n    }\n  }\nQed.\n\nTheorem body_insert: semax_body Vprog Gprog f_insert insert_spec.\nProof.\n  start_function.\n  forward.          (* root = t; *)\n  forward.          (* last_node = NULL; *)\n  forward_loop \n  (EX t' : RBtree, \n  EX ls : list Half_tree, \n  EX p_par : val,\n  EX b : val, \n  PROP (let (ist_h, ist_b) := insert_split x default t' ls in \n    insert' x v t = (ist_h, insert_root x v ist_b))\n  LOCAL (temp _last_node p_par; \n        temp _x (Vint (Int.repr x)); \n        temp _value (Vint (Int.repr v)); \n        temp _t b; temp _root root) \n  SEP (partial_treebox_rep ls root b p_par nullval;\n      treebox_rep t' b p_par))\n  break: \n  (EX t' : RBtree, \n  EX ls : list Half_tree, \n  EX p_par : val,\n  EX p : val, \n  EX b : val, \n  PROP (t' <> Empty; insert' x v t = (ls, t'))\n  LOCAL (temp _last_node p_par; \n        temp _x (Vint (Int.repr x)); \n        temp _value (Vint (Int.repr v)); \n        temp _t b; temp _root root;\n        temp _p p)\n  SEP (partial_treebox_rep ls root b p_par nullval;\n      data_at Tsh (tptr t_struct_rbtree) p b;\n      rbtree_rep t' p p_par)).\n  {\n    Exists t.\n    Exists (@nil Half_tree).\n    Exists nullval.\n    Exists root.\n    unfold treebox_rep.\n    Intros p_root.\n    Exists p_root.\n    entailer!.\n    - unfold insert'.\n      remember (insert_split x default t []) as hb.\n      destruct hb as [h' b'].\n      reflexivity.\n    - simpl partial_treebox_rep.\n      entailer!.\n  } \n  { \n    Intros t' ls p_par b.\n    unfold treebox_rep.\n    Intros p.\n    forward; try aggregate_solve.          (* p = *t; *)\n    forward_if_wrp.                   (* if (p = NULL) *)\n    {\n      subst p.\n      empty_tree t'.\n      simpl in H0.\n      (* first branch: arrive at the insert point *)\n      forward_call (sizeof t_struct_rbtree).\n      { 1: simpl; rep_omega. }\n      Intros vret.\n      rewrite memory_block_data_at_ by auto.\n      forward.        (* p->color = RED; *)\n      simpl.\n      forward.        (* p->key = x; *)\n      forward.        (* p->value = value; *)\n      forward.        (* p->tag = DEFAULT_TAG; *)\n      forward.        (* p->left = NULL; *)\n      forward.        (* p->right = NULL;  *)\n      forward.        (* p->fa = last_node; *)\n      forward.        (* *t = p; *)\n      forward.        (* break; *)\n      Exists (T Red Empty x v default Empty).\n      Exists ls p_par vret b.\n      entailer!; try discriminate.\n      simpl rbtree_rep. \n      Exists nullval nullval.\n      entailer!. \n    }\n    {\n      nonempty_tree t'.\n      Intros p_lch p_rch.\n      forward.            (* int y = p->key; *)\n      forward_call (c, k, v0, t0, p_lch, p_rch, p_par, p, t'1, t'2).\n                          (* pushdown(p); *)\n      forward_if_wrp.\n      { \n        (* if x is already in the tree *)\n        subst x.\n        forward.                      (* p->value = value; *)\n        forward.                      (* break; *)\n        Exists (T c (tag_tree_t t0 t'1) k v default (tag_tree_t t0 t'2)).\n        Exists ls p_par p b.\n        entailer!.\n        {\n          split; [ intro; discriminate | ].\n          unfold insert_split in H0.\n          simpl in H0.\n          assert (Hkkrefl: (k <? k) = false) by apply Z.ltb_irrefl.\n          rewrite Hkkrefl in H0.\n          rewrite H0.\n          auto.\n        }\n        {\n          simpl rbtree_rep. \n          Exists p_lch p_rch.\n          entailer!.\n        }\n      }\n      { \n        forward.          (* last_node = p; *)\n        (* otherwise move down the tree *)\n        forward_if_wrp.       (* determine whether x < y or not *)\n        { \n          (* x < k *)\n          forward.        (* t = &(p->left); *)\n          Exists (tag_tree_t t0 t'1). \n          Exists ((false, c, k, v0 + t0, 0, tag_tree_t t0 t'2) :: ls).\n          unfold treebox_rep.\n          Exists p (offset_val 16 p).\n          entailer!.\n          { \n            unfold insert_split, lt_bool in *.\n            rewrite <- Z.ltb_lt in H4.\n            simpl general_split in *.\n            try rewrite H4 in *.\n            rewrite general_split_tag in H0.\n            strip_0.\n            auto.\n          }\n          Exists p_lch.\n          simpl partial_treebox_rep.\n          Exists p_par p_rch b.\n          quick_replace_offset_val p.\n          unfold_data_at (data_at _ _ _ p).\n          entailer!.\n        }\n        { \n          (* x > k, symmetric case *)\n          forward.        (* t = &(p->p->right); *)\n          Exists (tag_tree_t t0 t'2). \n          Exists ((true, c, k, v0 + t0, 0, tag_tree_t t0 t'1) :: ls).\n          unfold treebox_rep.\n          Exists p (offset_val 20 p).\n          entailer!.\n          { \n            unfold insert_split, lt_bool in *.\n            simpl general_split in *.\n            assert (k < x) by lia. \n            assert (x <? k = false).\n            { rewrite Z.ltb_nlt. lia. }\n            rewrite <- Z.ltb_lt in H10.\n            try rewrite H10, H11 in *.\n            rewrite general_split_tag in H0.\n            strip_0.\n            auto.\n          }\n          Exists p_rch.\n          simpl partial_treebox_rep.\n          Exists p_par p_lch b.\n          quick_replace_offset_val p.\n          unfold_data_at (data_at _ _ _ p).\n          entailer!.\n        }\n      }\n    }\n  }\n  Intros t' ls p_par p b.\n  nonempty_tree t'.\n  simpl rbtree_rep.\n  Intros p_lch p_rch.\n  forward.\n  apply semax_if_seq.\n  forward_if.                   (* if (p->color == RED) *)\n  {\n    color_replace.\n    forward_call ((T Red t'1 k v0 t0 t'2), root, p_par, b, ls).\n    {\n      unfold treebox_rep.\n      Exists p.\n      simpl rbtree_rep.\n      Exists p_lch p_rch.\n      entailer!.\n    }\n    {\n      Intros vret.\n      destruct vret as [[[t_balanced ls_balanced] b_balanced] p_par_balanced].\n      simpl fst in *. simpl snd in *.\n      unfold treebox_rep.\n      Intros p_balanced.\n      sep_apply reconstruction_lemma_box.\n      remember (complete_tree ls_balanced t_balanced) as t_res.\n      forward_call (t_res, root).\n      Exists (makeBlack t_res).\n      entailer!.\n      eapply Insert.insert_intro.\n      - rewrite <- H1. auto.\n      - left. split; [ unfold Red_tree | ]; auto.\n    }\n  }\n  {\n    color_replace.\n    remember (T Black t'1 k v0 t0 t'2) as t'.\n    forward_call ((complete_tree ls t'), root).\n    {\n      instantiate (Frame := nil).\n      subst Frame.\n      normalize. \n      eapply derives_trans. \n      2: { apply reconstruction_lemma_box with (p:=p) (p_par:=p_par) (b:=b). }\n      subst t'.\n      simpl rbtree_rep.\n      Exists p_lch p_rch.\n      entailer!.\n    }\n    Exists (makeBlack (complete_tree ls t')).\n    entailer!.\n    eapply Insert.insert_intro.\n    - rewrite <- H1. auto.\n    - right. split; [ unfold Black_tree | ]; auto.\n  }\nQed.\n\n(* proof for free_tree *)\nTheorem body_tree_free: semax_body Vprog Gprog f_tree_free tree_free_spec.\nProof.\n  start_function.\n  forward_if (PROP()LOCAL()SEP()).\n  + destruct t; simpl rbtree_rep.\n      1: Intros. contradiction.\n    Intros pa pb.\n    forward; try aggregate_solve.\n    forward; try aggregate_solve.\n    forward_call (p, sizeof t_struct_rbtree).\n    {\n      entailer!.\n      rewrite memory_block_data_at_ by auto.\n      cancel.\n    }\n    forward_call (t1, pa, p).\n    forward_call (t3, pb, p).\n    entailer!.\n  + forward.\n    subst.\n    entailer!.\n    simpl; normalize.\n    destruct t.\n    - unfold rbtree_rep.\n      entailer!.\n    - simpl rbtree_rep. \n      Intros. Intros p_lch p_rch.\n      entailer!. destruct H0. inversion H0.\n  + entailer!. \nQed.\n\n(* proof for treebox_free *)\nTheorem body_treebox_free: semax_body Vprog Gprog f_treebox_free treebox_free_spec.\nProof.\n  start_function.\n  unfold treebox_rep.\n  Intros p.\n  forward; try aggregate_solve.\n  forward_call (t, p, nullval).\n  forward_call (b, sizeof (tptr t_struct_rbtree)).\n  entailer!.\n  rewrite memory_block_data_at_ by auto.\n  cancel.\n  forward.\nQed.\n\n(* proof for Optt *)\nTheorem body_Optt: semax_body Vprog Gprog f_Optt Optt_spec.\nProof.\n  start_function.\n  forward.\nQed.\n\n(* proof for Opvt *)\nTheorem body_Opvt: semax_body Vprog Gprog f_Opvt Opvt_spec.\nProof.\n  start_function.\n  forward.\nQed.\n\n(* proof for tag_tree_t *)\nTheorem body_tag_tree_t: semax_body Vprog Gprog f_tag_tree_t tag_tree_t_spec.\nProof.\n  start_function.\n  forward_if_wrp.           (* if (x != NULL) *)\n  {\n    nonempty_tree t.\n    Intros p_lch p_rch.\n    forward.                (* _t'2 = (_x -> _tag); *)\n    forward_call (t2, tg).  (* _t'1 = _Optt(_t'2, _tag); *)\n    forward.                (* (_x -> _tag) = _t'1; *)\n    simpl rbtree_rep.\n    Exists p_lch p_rch.\n    assert (Hcommu: t2 + tg = tg + t2) by lia.\n    rewrite Hcommu.\n    entailer!.\n  }\n  {\n    forward.\n    subst p.\n    empty_tree t.\n    simpl rbtree_rep. \n    entailer!.\n  }\nQed.\n\n(* proof for get_color *)\nTheorem body_get_color: \n  semax_body Vprog Gprog f_get_color get_color_spec.\nProof.\n  start_function.\n  forward_if_wrp.\n  {\n    subst p.\n    empty_tree t.\n    forward.\n    simpl rbtree_rep.\n    entailer!.\n  }\n  {\n    nonempty_tree t.\n    Intros p_lch p_rch.\n    forward.\n    forward.\n    simpl rbtree_rep.\n    Exists p_lch p_rch.\n    entailer!.\n  }\nQed.\n\nLemma treebox_rep_nullval : forall (t: RBtree) p_par, \n  treebox_rep t nullval p_par |-- !! False.\nProof.\n  intros. unfold treebox_rep. Intros p. assert_PROP (False) by entailer!. contradiction.\nQed.\n\nLtac empty_treebox t := \n  sep_apply (treebox_rep_nullval t); Intros; contradiction.\n\n(* proof for make_black *)\nTheorem body_make_black : semax_body Vprog Gprog f_make_black make_black_spec.\nProof.\n  start_function.\n  forward_if_wrp.\n  {\n    subst root.\n    empty_treebox t.\n  }\n  {\n    unfold treebox_rep.\n    Intros p.\n    forward; try aggregate_solve.\n    forward_if.\n    {\n      subst p.\n      empty_tree t.\n      forward.\n      unfold treebox_rep.\n      Exists nullval.\n      simpl rbtree_rep.\n      entailer!.\n    }\n    {\n      nonempty_tree t.\n      Intros p_lch p_rch.\n      forward.\n      entailer!.\n      unfold treebox_rep.\n      simpl rbtree_rep.\n      Exists p p_lch p_rch.\n      entailer!.\n    }\n  }\nQed.\n\n\nTheorem body_lookup: semax_body Vprog Gprog f_lookup lookup_spec.\nProof.\n  start_function.\n  forward.                    (* res = 0; *)\n  forward_loop\n  (EX t' : RBtree, EX ls' : list Half_tree, \n   EX p' : val, EX p_par' : val, \n   EX acc_tag : Tag, \n   PROP (is_pointer_or_null p_par'; \n    lookup x t = f_partial (lookup x t') acc_tag;\n    complete_tree ls' t' = t)\n   LOCAL (temp _res (Vint (Int.repr acc_tag)); temp _p p'; temp _x (Vint (Int.repr x)))\n   SEP (rbtree_rep t' p' p_par'; \n    partial_tree_rep ls' p p' p_par' p_par))%assert.\n  {\n    Exists t (@nil Half_tree) p p_par.\n    Exists default.\n    simpl partial_tree_rep.\n    entailer!.\n    remember (lookup x t) as final_res.\n    destruct final_res.\n    - simpl. f_equal. lia.\n    - simpl. reflexivity.\n  }\n  {\n    Intros t' ls' p' p_par' acc_tag.\n    (* res' need to be accumulated with tags *)\n    (* if (p == NULL) *)\n    forward_if (p' <> nullval); try pointer_destructor.\n    {\n      forward.\n      assert_PROP (t' = Empty) by (sep_apply rbtree_rep_nullval; Intros; entailer).\n      sep_apply reconstruction_lemma; auto.\n      unfold Lookup2Z. rewrite H1.\n      subst t'. simpl. entailer!.\n    }\n    {\n      forward. entailer!.\n    }\n    Intros. nonempty_tree t'.\n    Intros p_lch p_rch.\n    forward.\n    forward_call (acc_tag, t0).\n    forward.\n    forward.\n    pose proof (tri_div_Z k x) as Htridiv.\n    unfold tri_div in Htridiv.\n    forward_if.\n    {\n      forward; try aggregate_solve.\n      Exists t'2 ((true, c, k, v, t0, t'1) :: ls').\n      Exists p_rch p'.\n      Exists (Optt acc_tag t0).\n      entailer!.\n      - rewrite H1.\n        simpl lookup.\n        rewrite <- Z.ltb_lt in H5.\n        rewrite H5 in Htridiv.\n        destruct Htridiv.\n        rewrite H2, H5.\n        simpl Optt.\n        remember (lookup x t'2) as partial_res.\n        destruct partial_res.\n        + simpl. f_equal. lia.\n        + simpl. auto.\n      - simpl.\n        Exists p_par' p_lch.\n        entailer!.\n    }\n    {\n      apply Z.ge_le in H5.\n      apply Zle_not_lt in H5.\n      rewrite <- Z.ltb_nlt in H5.\n      rewrite H5 in Htridiv.\n      forward.\n      forward_if_wrp.\n      {\n        rewrite <- Z.ltb_lt in H6.\n        rewrite H6 in Htridiv.\n        forward; try aggregate_solve.\n        Exists t'1 ((false, c, k, v, t0, t'2) :: ls').\n        Exists p_lch p'.\n        Exists (Optt acc_tag t0).\n        entailer!.\n        - rewrite H1.\n          simpl lookup.\n          rewrite H5, H6.\n          simpl Optt.\n          remember (lookup x t'1) as partial_res.\n          destruct partial_res.\n          + simpl. f_equal. lia.\n          + simpl. auto.\n        - simpl.\n          Exists p_par' p_rch.\n          entailer!.\n      }\n      {\n        apply Z.ge_le in H6.\n        apply Zle_not_lt in H6.\n        rewrite <- Z.ltb_nlt in H6.\n        rewrite H6 in Htridiv.\n        forward.\n        forward_call (v, (Optt acc_tag t0)).\n        forward.\n        entailer!.\n        - do 2 f_equal.\n          unfold Lookup2Z.\n          rewrite H1.\n          simpl lookup.\n          rewrite H5, H6.\n          simpl.\n          lia.\n        - pose proof reconstruction_lemma.\n          specialize H2 with (p:=p') (p_par:=p_par').\n          eapply derives_trans.\n          2: { apply H2. }\n          entailer!.\n          simpl rbtree_rep.\n          Exists p_lch p_rch.\n          entailer!.\n      }\n    }\n  }\nQed.\n\n(* proof for left_rotate *)\nTheorem body_left_rotate : semax_body Vprog Gprog f_left_rotate left_rotate_spec.\nProof.\n  start_function.\n  forward.    (* r = l->right; *)\n  forward; try aggregate_solve.    (* mid = r->left; *)\n  forward.    (* l->right = mid; *)  \n  forward.\n  forward.    (* r->left = l; *)\n  forward.    (* r->par = l->par; *)\n  forward.    (* l->par = r; *)\n  apply semax_if_seq.\n  forward_if; try pointer_destructor.\n  {\n    nonempty_tree tb.\n    Intros pb_lch pb_rch.\n    forward.  (* mid->par = l; *)\n    forward.  (* return r; *)\n    simpl rbtree_rep. \n    Exists pb_lch pb_rch.\n    entailer!. \n  }\n  {\n    subst pb. empty_tree tb.\n    forward.\n    simpl rbtree_rep. \n    entailer!.\n  }\nQed.\n\n(* proof for right rotate; it has the same proof script as above *)\nTheorem body_right_rotate : semax_body Vprog Gprog f_right_rotate right_rotate_spec.\nProof.\n  start_function.\n  forward.    (* l = r->left; *)\n  forward; try aggregate_solve.    (* mid = l->right; *)\n  forward.    (* r->left = mid; *)  \n  forward.    (* l->right = r; *)\n  forward.\n  forward.    (* r->par = l->par; *)\n  forward.    (* l->par = r; *)\n  apply semax_if_seq.\n  forward_if; try pointer_destructor.\n  {\n    nonempty_tree tb.\n    Intros pb_lch pb_rch.\n    forward.  (* mid->par = r; *)\n    forward.  (* return l; *)\n    simpl rbtree_rep. \n    Exists pb_lch pb_rch.\n    entailer!. \n  }\n  {\n    subst pb. empty_tree tb.\n    forward.\n    simpl rbtree_rep. \n    entailer!.\n  }\nQed. \n\nTheorem body_pushdown: semax_body Vprog Gprog f_pushdown pushdown_spec.\nProof.\n  start_function.\n  forward.\n  forward.\n  forward_call (v, tg).             (* p->value = Opvt(p->value, p->tag); *)\n  forward.\n  forward; try aggregate_solve.\n  forward.\n  forward_call (lch, tg, p_lch, p). (* tag_tree_t(p->left, p->tag); *)\n  forward; try aggregate_solve.\n  forward.\n  forward_call (rch, tg, p_rch, p). (* tag_tree_t(p->right, p->tag); *)\n  forward.                          (* p->tag = DEFAULT_TAG; *)\n  entailer!.\nQed.\n\n(* proof for treebox_new *)\n(* copied from verif_bst.v *)\nTheorem body_treebox_new: semax_body Vprog Gprog f_treebox_new treebox_new_spec.\nProof.\n  start_function.\n  forward_call (sizeof (tptr t_struct_rbtree)).\n  { simpl sizeof; computable. }\n  Intros p.\n  rewrite memory_block_data_at_ by auto.\n  forward.\n  forward.\n  Exists p. entailer!.\nQed.\n\n\n(* proof for left_rotate_wrap *)\nTheorem body_left_rotate_wrap:\n  semax_body Vprog Gprog f_left_rotate_wrap left_rotate_wrap_spec.\nProof.\n  start_function.\n  forward.\n  forward_if_wrp.                     (* if (l->par == NULL) *)\n  { (* l is the root *)\n    subst pl_par.\n    empty_partialtree ls.\n    forward_call \n    (col_l, key_l, value_l, tag_l, nullval, \n      col_r, key_r, value_r, tag_r, \n      ta, tb, tc, \n      pl, pr, pa, pb, pc).\n    forward.                      (* *root = left_rotate(l); *)\n    Exists pr.\n    simpl partial_tree_rep.\n    entailer!.\n  }\n  {\n    forward.\n    nonempty_partialtree ls.\n    destruct h as [[[[[va c] k] v] tg] sib].\n    Intros pl_gpar pl_sib.\n    forward.\n    { destruct va; aggregate_solve. }\n    forward_if_wrp.\n    { destruct va; aggregate_solve. }\n    {\n      (* l is the left branch *)\n      destruct va.\n      { (* verify that l is on the left *)\n        subst pl_sib.\n        common_pointer_solve pl sib.\n      }\n      forward_call \n      (col_l, key_l, value_l, tag_l, pl_par, \n        col_r, key_r, value_r, tag_r, \n        ta, tb, tc, \n        pl, pr, pa, pb, pc).\n      forward.                    (* l_fa->left = left_rotate(l); *)\n      Exists p_root.\n      simpl partial_tree_rep.\n      entailer!.\n      Exists pl_gpar pl_sib.\n      entailer!.\n    }\n    {\n      (* l is the right branch *)\n      destruct va; [ | contradiction ].\n      forward_call \n      (col_l, key_l, value_l, tag_l, pl_par, \n        col_r, key_r, value_r, tag_r, \n        ta, tb, tc, \n        pl, pr, pa, pb, pc).\n      forward.                    (* l_fa->right = left_rotate(l); *)\n      Exists p_root.\n      simpl partial_tree_rep.\n      entailer!.\n      Exists pl_gpar pl_sib.\n      entailer!.\n    }\n  }\nQed.\n\n(* proof for right_rotate_wrap *)\nTheorem body_right_rotate_wrap:\n  semax_body Vprog Gprog f_right_rotate_wrap right_rotate_wrap_spec.\nProof.\n  start_function.\n  forward.\n  forward_if_wrp.                     (* if (r->par == NULL) *)\n  { (* r is the root *) \n    subst pr_par.\n    empty_partialtree ls.\n    forward_call \n    (col_l, key_l, value_l, tag_l, \n      col_r, key_r, value_r, tag_r, nullval, \n      ta, tb, tc, \n      pl, pr, pa, pb, pc).\n    forward.                      (* *root = right_rotate(r); *)\n    Exists pl.\n    simpl partial_tree_rep.\n    entailer!.\n  }\n  {\n    forward.\n    nonempty_partialtree ls.\n    destruct h as [[[[[va c] k] v] tg] sib].\n    Intros pr_gpar pr_sib.\n    forward.\n    { destruct va; aggregate_solve. }\n    forward_if_wrp.\n    { destruct va; aggregate_solve. }\n    {\n      (* r is the left branch *)\n      destruct va.\n      { (* verify that r is on the left *)\n        subst pr_sib.\n        common_pointer_solve pr sib.\n      }\n      forward_call \n      (col_l, key_l, value_l, tag_l, \n        col_r, key_r, value_r, tag_r, pr_par, \n        ta, tb, tc, \n        pl, pr, pa, pb, pc).\n      forward.                    (* r_fa->left = right_rotate(r); *)\n      Exists p_root.\n      simpl partial_tree_rep.\n      entailer!.\n      Exists pr_gpar pr_sib.\n      entailer!.\n    }\n    {\n      (* r is the right branch *)\n      destruct va; [ | contradiction ].\n      forward_call \n      (col_l, key_l, value_l, tag_l, \n        col_r, key_r, value_r, tag_r, pr_par, \n        ta, tb, tc, \n        pl, pr, pa, pb, pc).\n      forward.                    (* r_fa->right = right_rotate(r); *)\n      Exists p_root.\n      simpl partial_tree_rep.\n      entailer!.\n      Exists pr_gpar pr_sib.\n      entailer!.\n    }\n  }\nQed.", "meta": {"author": "maoliyuan", "repo": "avltree-verification", "sha": "1258e9bd5fa7d849ba8b387978bca41d56c64c9a", "save_path": "github-repos/coq/maoliyuan-avltree-verification", "path": "github-repos/coq/maoliyuan-avltree-verification/avltree-verification-1258e9bd5fa7d849ba8b387978bca41d56c64c9a/Verif/verif_rbt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.26294014261327847}}
{"text": "Require Import Bool Arith List Omega.\nRequire Import OrderedType OrderedTypeEx.\nRequire FMapList.\nRequire FMapFacts.\nImport ListNotations.\n\n(*************************************************************)\n(* get us some maps *)\n\nModule NatMap := FMapList.Make Nat_as_OT.\nModule NatMapFacts := FMapFacts.WFacts_fun Nat_as_OT NatMap.\n\n(*************************************************************)\n(* Data block model *)\n\n(*\n * A data block is either a user block (which we identify\n * by a file number, file block number, and generation number) or\n * a FS metadata block, which is a value of some type T\n * defined by the FS.\n *\n * XXX: how do we want to do this parameterization? I suspect what\n * I've put here for the moment is going to suck.\n *)\n\nSection DataBlocks.\n\nInductive DataBlock : Type :=\n(*\n| UserData: forall (userfilenum fileblocknum generation : nat), DataBlock\n| FSData: forall T : Type, forall metadata : T, DataBlock\n*)\n| DNat (n:nat)\n.\n\n(*\n * A block table is a map from block addresses (nats) to data.\n *)\nDefinition BlockTable : Type := NatMap.t DataBlock.\n\nEnd DataBlocks.\n\n(*************************************************************)\n(* Cache model *)\n\nSection Cache.\n\n(*\n * We have two caches: a disk cache (on the disk) and an OS-level\n * buffer cache. These are both write-back but have different\n * behavior, reflecting the real-world behavior of these abstractions.\n *\n * Both caches are modeled using maps containing pending writes. (We\n * don't bother to model the read behavior of caches as we aren't\n * interested in trying to model performance.)\n *\n * The disk cache is a list of maps; a new entry is pushed on the list\n * when a write ordering barrier is issued. Therefore, more than one\n * value for any given block may be kept on file, but only with a\n * write barrier in between. I'm assuming that sending a disk new data\n * for a block still pending will overwrite the old version in the cache\n * if there's no write barrier prohibiting such combining.\n *\n * (XXX: do we need to make sure not to write the same block on both\n * sides of a write barrier to keep the disk from screwing up?)\n *\n * The OS cache is one map, but there's a lot more machinery to access\n * it.\n *\n * The complete cache has both cache layers and a platter, which\n * represents what's actually on the physical media.\n *)\n\nDefinition RawCache : Type := BlockTable.\n\nDefinition DiskPlatter : Type := BlockTable.\nDefinition DiskCache : Type := list RawCache.\nDefinition OSCache : Type := RawCache.\n\nInductive Cache : Type :=\n| cache : forall (oc : OSCache) (dc : DiskCache) (dp : DiskPlatter), Cache\n.\n\n\n\n(*\n * Operations on DiskPlatter.\n *\n * DiskPlatter_empty is a totally empty platter.\n *)\n\nDefinition DiskPlatter_empty := NatMap.empty DataBlock.\n\nDefinition DiskPlatter_read (plat : DiskPlatter) (bn : nat) :=\n   NatMap.find bn plat.\n\nDefinition DiskPlatter_write (plat : DiskPlatter) (bn : nat) (data : DataBlock):=\n   NatMap.add bn data plat.\n\n(*\n * Operations on RawCache.\n *\n * RawCache_empty is the empty cache.\n *\n * RawCache_read reads the value for the indicated block, if any.\n *\n * RawCache_write inserts a new block value into the cache,\n * overwriting any value that already exists.\n *\n * RawCache_sync transfers all the blocks to the platter (passed in)\n * and returns a new platter. It does not return a new RawCache; use\n * RawCache_empty.\n *)\n\nDefinition RawCache_empty := NatMap.empty DataBlock.\n\nDefinition RawCache_read (rc : RawCache) (bn : nat) :=\n   NatMap.find bn rc.\n\nDefinition RawCache_write (rc : RawCache) (bn : nat) (data : DataBlock) :=\n   NatMap.add bn data rc.\n\nDefinition RawCache_sync (rc : RawCache) (plat : DiskPlatter) :=\n   NatMap.fold (fun bn data plat =>\n                   DiskPlatter_write plat bn data) rc plat.\n\n\n(*\n * Operations on DiskCache.\n *\n * DiskCache_empty is the empty cache.\n *\n * DiskCache_read reads the latest value for the indicated block.\n *\n * DiskCache_write inserts a new block value into the cache.\n *\n * DiskCache_writebarrier issues a write barrier.\n *\n * DiskCache_sync transfers all blocks to the platter, obeying the\n * write barriers. It returns a new DiskPlatter. It does not return\n * a new DiskCache; use DiskCache_empty.\n *)\n\nDefinition DiskCache_empty := [] : list RawCache.\n\nFunction DiskCache_read (dc : DiskCache) (bn : nat) :=\n   match dc with\n   | [] => None\n   | rc :: more =>\n        match RawCache_read rc bn with\n        | None => DiskCache_read more bn\n        | Some data => Some data\n        end\n   end.\n\nFunction DiskCache_write (dc : DiskCache) (bn : nat) (data : DataBlock) :=\n   match dc with\n   | [] => [RawCache_write RawCache_empty bn data]\n   | rc :: more => (RawCache_write rc bn data) :: more\n   end.\n\nFunction DiskCache_writebarrier (dc : DiskCache) :=\n   RawCache_empty :: dc.\n\nFunction DiskCache_sync (dc : DiskCache) (plat : DiskPlatter) :=\n   match dc with\n   | [] => plat\n   | rc :: more =>\n        RawCache_sync rc (DiskCache_sync more plat)\n   end.\n\n(*\n * Operations on OSCache.\n *\n * OSCache_empty is the empty cache.\n * OSCache_read reads the value for the indicated block, if any.\n * OSCache_write inserts a new block value into the cache.\n *\n * (more TBD)\n *)\n\nDefinition OSCache_empty := RawCache_empty.\nDefinition OSCache_read := RawCache_read.\nDefinition OSCache_write := RawCache_write.\n\n(*\n * Operations on the whole cache.\n *\n * Cache_boot generates an empty cache attached to the given platter.\n * Cache_read reads the value for the indicated block.\n * Cache_write inserts a new block value and does not flush it.\n *\n * (more tbd)\n *)\n\nFunction Cache_boot (plat : DiskPlatter) :=\n   cache OSCache_empty DiskCache_empty plat.\n\nFunction Cache_read (c : Cache) (bn : nat) :=\n   match c with\n   | cache oc dc plat => \n        match OSCache_read oc bn with\n        | Some data => Some data\n        | None =>\n             match DiskCache_read dc bn with\n             | Some data => Some data\n             | None =>\n                  DiskPlatter_read plat bn\n             end\n        end\n   end.\n\nFunction Cache_write (c : Cache) (bn : nat) (data : DataBlock) :=\n   match c with\n   | cache oc dc plat =>\n        let oc' := OSCache_write oc bn data in\n        cache oc' dc plat\n   end.\n\nEnd Cache.\n\nSection CacheFacts.\n\n(*\n * Lemmas about caches.\n *)\n\n(*\n * Reading returns the latest write.\n *)\n\nLocal Hint Unfold RawCache_write RawCache_read.\nLocal Hint Unfold DiskPlatter_read DiskPlatter_write.\nLocal Hint Unfold OSCache_read OSCache_write.\nLocal Hint Resolve NatMapFacts.add_eq_o.\n\n\nLemma RawCache_read_nonstale:\n   forall rc bn data,\n      RawCache_read (RawCache_write rc bn data) bn = Some data.\nProof.\n  autounfold; auto.\nQed.\n\nHint Rewrite RawCache_read_nonstale : cache.\nLocal Hint Resolve  RawCache_read_nonstale.\n\nLemma DiskPlatter_read_nonstale:\n   forall plat bn data,\n      DiskPlatter_read (DiskPlatter_write plat bn data) bn = Some data.\nProof.\n   autounfold; auto.\nQed.\n\nLemma DiskCache_read_nonstale:\n   forall dc bn data,\n      DiskCache_read (DiskCache_write dc bn data) bn = Some data.\nProof.\n   intros.\n   destruct dc; simpl; autorewrite with cache; auto.\nQed.\n\nLemma OSCache_read_nonstale:\n   forall oc bn data,\n      OSCache_read (OSCache_write oc bn data) bn = Some data.\nProof.\n   auto.\nQed.\n\nHint Rewrite OSCache_read_nonstale : cache.\n\nLemma Cache_read_nonstale:\n   forall c bn data,\n      Cache_read (Cache_write c bn data) bn = Some data.\nProof.\n   destruct c; intros; simpl; autorewrite with cache; auto.\nQed.\n\n(*\n * Writing something else doesn't affect reads.\n *)\n\nHint Rewrite NatMapFacts.add_neq_o : cache.\n\nLemma RawCache_read_noninterfere:\n   forall rc bn1 bn2 data,\n      bn1 <> bn2 ->\n      RawCache_read (RawCache_write rc bn1 data) bn2 = RawCache_read rc bn2.\nProof.\n   intros; autounfold; autorewrite with cache; auto.\nQed.\n\nLemma DiskPlatter_read_noninterfere:\n   forall plat bn1 bn2 data,\n      bn1 <> bn2 ->\n      DiskPlatter_read (DiskPlatter_write plat bn1 data) bn2 = DiskPlatter_read plat bn2.\nProof.\n   intros; autounfold; autorewrite with cache; auto.\nQed.\n\nHint Rewrite RawCache_read_noninterfere : cache.\nLocal Hint Resolve RawCache_read_noninterfere.\n\nLemma DiskCache_read_noninterfere:\n   forall dc bn1 bn2 data,\n      bn1 <> bn2 ->\n      DiskCache_read (DiskCache_write dc bn1 data) bn2 = DiskCache_read dc bn2.\nProof.\n   intros; destruct dc; simpl; autorewrite with cache; auto.\nQed.\n\nLemma OSCache_read_noninterfere:\n   forall oc bn1 bn2 data,\n      bn1 <> bn2 ->\n      OSCache_read (OSCache_write oc bn1 data) bn2 = OSCache_read oc bn2.\nProof.\n   auto.\nQed.\n\nLemma Cache_read_noninterfere:\n   forall c bn1 bn2 data,\n      bn1 <> bn2 ->\n      Cache_read (Cache_write c bn1 data) bn2 = Cache_read c bn2.\nProof.\n   intros; destruct c; simpl; autorewrite with cache; auto.\nQed.\n\n(*\n * A write barrier doesn't affect what you read.\n *)\nLemma DiskCache_read_writebarrier:\n   forall dc bn,\n      DiskCache_read (DiskCache_writebarrier dc) bn = DiskCache_read dc bn.\nProof.\n   auto.\nQed.\n\nEnd CacheFacts.\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/stuff/cache.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2628652388610782}}
{"text": "\nRequire Import Axioms.\nRequire Import Tactics.\nRequire Import Sigma.\nRequire Import Equality.\nRequire Import Relation.\nRequire Import Syntax.\nRequire Import Ofe.\nRequire Import Uniform.\nRequire Import Spaces.\nRequire Import Dynamic.\nRequire Import Hygiene.\nRequire Import Equivalence.\nRequire Import Urelsp.\nRequire Import Intensional.\nRequire Import Ordinal.\nRequire Import Candidate.\nRequire Import Ceiling.\nRequire Import Truncate.\nRequire Import MapTerm.\nRequire Import Extend.\nRequire Import Standard.\nRequire Import Equivalences.\nRequire Import ExtendTruncate.\nRequire Import SemanticsProperty.\n\n\n\nLocal Ltac prove_hygiene :=\n  repeat (first [ apply hygiene_shift_permit\n                | apply hygiene_sumbool\n                | apply hygiene_auto; cbn [row_rect nat_rect]; repeat2 split; auto\n                ]);\n  eauto using hygiene_weaken, clo_min, hygiene_shift', hygiene_subst1;\n  try (apply hygiene_var; cbn; auto; done).\n\n\n(* We could define this using set types, but it is much less messy to avoid dependent types. *)\n\nLemma squash_downward :\n  forall w (A : wurel w) i,\n    (exists m p, rel A (S i) m p)\n    -> (exists m p, rel A i m p).\nProof.\nintros w A i H.\ndestruct H as (m & p & H).\nexists m, p.\napply urel_downward; auto.\nQed.\n\n\nDefinition squash_urel\n  (w : ordinal) (A : wurel w) (i : nat)\n  :=\n  property_urel (fun j => exists m p, rel A j m p) w i (squash_downward w A).\n\n\nLemma ceiling_squash :\n  forall w A n i,\n    ceiling (S n) (squash_urel w A i)\n    =\n    squash_urel w A (min i n).\nProof.\nintros w A n i.\napply ceiling_property.\nQed.\n\n\nLemma ceiling_squash_inner :\n  forall w A i j,\n    j < i\n    -> squash_urel w A j = squash_urel w (ceiling i A) j.\nProof.\nintros w A i j Hji.\nunfold squash_urel.\napply property_urel_extensionality; auto.\nintros k Hk.\nsplit.\n  {\n  intros (m & p & H).\n  exists m, p.\n  split; auto.\n  omega.\n  }\n\n  {\n  intros (m & p & H).\n  exists m, p.\n  destruct H.\n  auto.\n  }\nQed.\n\n\nLemma ceiling_squash_both :\n  forall w A n i,\n    n <= i\n    -> squash_urel w (ceiling (S n) A) n\n       =\n       ceiling (S n) (squash_urel w A i).\nProof.\nintros w A n i Hle.\nrewrite -> ceiling_squash.\nrewrite -> Nat.min_r; auto.\nsymmetry.\napply ceiling_squash_inner.\nomega.\nQed.\n\n\nDefinition embed_ceiling_squash_ne w (n i : nat) (A : wurel w) (h : n <= i) :\n  urelsp (squash_urel w (ceiling (S n) A) n) -n> urelsp (squash_urel w A i)\n  :=\n  nearrow_compose\n    (embed_ceiling_ne (S n) (squash_urel w A i))\n    (transport_ne (ceiling_squash_both w A n i h) urelsp).\n\n\nLemma extend_squash :\n  forall v w A i,\n    v <<= w\n    -> extend_urel v w (squash_urel v A i)\n      =\n      squash_urel w (extend_urel v w A) i.\nProof.\nintros v w A i Hle.\nunfold squash_urel.\nrewrite -> extend_property; auto.\napply urel_extensionality.\ncbn.\nf_equal.\nfextensionality 1.\nintro j.\npextensionality.\n  {\n  intros (m & p & H).\n  exists (map_term (extend v w) m).\n  exists (map_term (extend v w) p).\n  rewrite -> !extend_term_cancel; auto.\n  }\n\n  {\n  intros (m & p & H).\n  exists (map_term (extend w v) m).\n  exists (map_term (extend w v) p).\n  auto.\n  }\nQed.\n\n\nLemma squash_intro :\n  forall w (A : wurel w) i j m p,\n    j <= i\n    -> rel A j m p\n    -> rel (squash_urel w A i) j triv triv.\nProof.\nintros w A i j m p Hj Hmp.\ndo2 5 split; eauto using star_refl; try prove_hygiene.\nQed.\n\n\nDefinition guard_action\n  (w : ordinal) i (A : wurel w) (B : urelsp_car (squash_urel w A i) -> wurel w)\n  : nat -> relation (wterm w)\n  :=\n  fun i' m n =>\n    exists (Hi' : i' <= i),\n      hygiene clo m\n      /\\ hygiene clo n\n      /\\ forall j p q (Hj : j <= i') (Hrel : rel A j p q),\n            rel (B (urelspinj (squash_urel w A i) j triv triv (squash_intro _#6 (le_trans _#3 Hj Hi') Hrel))) j m n.\n\n\nLemma guard_uniform :\n  forall w i A B, uniform _ (guard_action w i A B).\nProof.\nintros w i A B.\ndo2 3 split.\n\n(* closed *)\n{\nintros i' m n H.\ndecompose H; auto.\n}\n\n(* equiv *)\n{\nintros i' m m' n n' Hclm' Hcln' Hm Hn H.\ndecompose H.\nintros Hi' Hclm Hcln Hact.\nexists Hi'.\ndo2 2 split; auto.\nintros j p q Hj Hpq.\nso (Hact _#3 Hj Hpq) as H.\neapply urel_equiv; eauto.\n}\n\n(* zigzag *)\n{\nintros i' m n p q Hmn Hpn Hpq.\ndestruct Hmn as (Hi' & Hclm & _ & Hmn).\ndestruct Hpn as (H & _ & _ & Hpn).\nso (proof_irrelevance _ Hi' H); subst H.\ndestruct Hpq as (H & _ & Hclq & Hpq).\nso (proof_irrelevance _ Hi' H); subst H.\nexists Hi'.\ndo2 2 split; auto.\nintros j r t Hj Hrt.\nso (Hmn _#3 Hj Hrt) as H1.\nso (Hpn _#3 Hj Hrt) as H2.\nso (Hpq _#3 Hj Hrt) as H3.\neapply urel_zigzag; eauto.\n}\n\n(* downward *)\n{\nintros i' m n Hmn.\ndecompose Hmn.\nintros Hi' Hclm Hcln Hact.\nassert (i' <= i) as Hle by omega.\nexists Hle.\ndo2 2 split; eauto.\nintros j p q Hj Hpq.\nassert (j <= S i') as Hj' by omega.\nso (Hact _#3 Hj' Hpq) as H.\nforce_exact H; clear H.\nf_equal.\nf_equal.\napply urelspinj_equal.\neapply squash_intro; eauto.\nomega.\n}\nQed.\n\n\nDefinition guard_urel w i A B :=\n  mk_urel (guard_action w i A B) (guard_uniform _ _ _ _).\n\n\nLemma ceiling_guard :\n  forall n w i (A : wurel w) (B : car (urelsp (squash_urel w A i)) -> car (wurel_ofe w)) (h : n <= i),\n    nonexpansive B\n    -> ceiling (S n) (guard_urel w i A B)\n       =\n       guard_urel w n (ceiling (S n) A)\n         (fun C => ceiling (S n) (B (embed_ceiling (S n) (squash_urel w A i)\n                                       (transport (ceiling_squash_both w A n i h) urelsp_car C)))).\nProof.\nintros n w i A B h Hne.\napply urel_extensionality.\nfextensionality 3.\nintros j m p.\ncbn.\npextensionality.\n  {\n  intros (Hj_n & H).\n  decompose H.\n  intros Hji Hclm Hclp Hact.\n  assert (j <= n) as Hjn by omega.\n  exists Hjn.\n  do2 2 split; auto.\n  intros k q r Hk Hqr.\n  destruct Hqr as (Hk_n & Hqr).\n  cbn.\n  split; [omega |].\n  so (Hact k q r Hk Hqr) as Hmp.\n  force_exact Hmp.\n  f_equal.\n  f_equal.\n  erewrite -> transport_urelspinj.\nUnshelve.\n  2:{\n    exact (conj Hk_n (squash_intro _#6 (le_trans _#3 Hk Hji) Hqr)).\n    }\n  rewrite -> embed_ceiling_urelspinj.\n  reflexivity.\n  }\n\n  {\n  intros H.\n  decompose H.\n  intros Hjn Hclm Hclp Hact.\n  split; [omega |].\n  assert (j <= i) as Hji by omega.\n  exists Hji.\n  do2 2 split; auto.\n  intros k q r Hk Hqr.\n  assert (k < S n) as Hk_n by omega.\n  so (Hact k q r Hk (conj Hk_n Hqr)) as Hmp.\n  destruct Hmp as (_ & Hmp).\n  force_exact Hmp.\n  f_equal.\n  f_equal.\n  erewrite -> transport_urelspinj.\nUnshelve.\n  2:{\n    exact (conj Hk_n (squash_intro _#6 (le_trans _#3 Hk Hji) Hqr)).\n    }\n  rewrite -> embed_ceiling_urelspinj.\n  reflexivity.\n  }\nQed.\n\n\nLemma extend_guard :\n  forall v w (h : v <<= w) i A B,\n    extend_urel v w (guard_urel v i A B)\n    =\n    guard_urel w i (extend_urel v w A)\n      (fun C => extend_urel v w \n                  (B (deextend_urelsp h (squash_urel v A i)\n                        (transport (eqsymm (extend_squash v w A i h)) urelsp_car C)))).\nProof.\nintros v w h i A B.\napply urel_extensionality.\nfextensionality 3.\nintros j m p.\ncbn.\npextensionality.\n  {\n  intro H.\n  decompose H.\n  intros Hj Hclm Hcln Hact.\n  exists Hj.\n  do2 2 split; eauto using map_hygiene_conv.\n  intros k n q Hk Hnq.\n  so (Hact _#3 Hk Hnq) as H.\n  cbn.\n  force_exact H; clear H.\n  f_equal.\n  f_equal.\n  assert (rel (extend_urel v w (squash_urel v A i)) k triv triv) as Htriv.\n    {\n    eapply squash_intro; try omega.\n    exact Hnq.\n    }\n  rewrite -> (transport_urelspinj _#3 (eqsymm (extend_squash v w A i h)) _#4 Htriv).\n  rewrite -> deextend_urelsp_urelspinj.\n  apply urelspinj_equal.\n  exact Htriv.\n  }\n\n  {\n  intro H.\n  decompose H.\n  intros Hj Hclm Hcln Hact.\n  exists Hj.\n  do2 2 split; eauto using map_hygiene.\n  intros k n q Hk Hnq.\n  assert (rel (extend_urel v w A) k (map_term (extend v w) n) (map_term (extend v w) q)) as Hnq'.\n    {\n    cbn.\n    rewrite -> !extend_term_cancel; auto.\n    }\n  so (Hact k (map_term (extend v w) n) (map_term (extend v w) q) Hk Hnq') as H.\n  cbn in H.\n  force_exact H; clear H.\n  f_equal.\n  f_equal.\n  assert (rel (extend_urel v w (squash_urel v A i)) k triv triv) as Htriv.\n    {\n    eapply squash_intro; try omega.\n    exact Hnq.\n    }\n  rewrite -> (transport_urelspinj _#3 (eqsymm (extend_squash v w A i h)) _#4 Htriv).\n  rewrite -> deextend_urelsp_urelspinj.\n  apply urelspinj_equal.\n  exact Htriv.\n  }\nQed.\n\n\nLemma maximum_element :\n  forall (P : nat -> Prop),\n    (exists i, forall k, P k -> k < i)\n    -> (forall i, ~ P i) \\/ (exists i, P i /\\ (forall j, P j -> j <= i)).\nProof.\nintros P (i & Hi).\nrevert Hi.\ninduct i.\n\n(* 0 *)\n{\nintro Hi.\nleft.\nintros j Hj.\nso (Hi j Hj).\nomega.\n}\n\n(* S *)\n{\nintros i IH Hi.\nso (excluded_middle (P i)) as [Hyes | Hno].  (* EXCLUDED MIDDLE *)\n  {\n  right.\n  exists i.\n  split; auto.\n  intros j Hj.\n  so (Hi j Hj).\n  omega.\n  }\n\n  {\n  apply IH.\n  intros k Hk.\n  so (eq_nat_dec i k) as [Heq | Hneq].\n    {\n    subst k.\n    contradiction.\n    }\n\n    {\n    so (Hi k Hk) as H.\n    omega.\n    }\n  }\n}\nQed.\n\n\nLemma unguard_prop :\n  forall (T : ofe) w (A : wurel w) i (B : urelsp (squash_urel w A i) -n> T) (x : car T),\n    exists (y : car T),\n      forall j m p (Hj : j <= i) (Hmp : rel A j m p),\n        dist (S j) y (pi1 B (urelspinj (squash_urel w A i) j triv triv (squash_intro _#6 Hj Hmp))).\nProof.\nintros T w A i B x.\nexploit (maximum_element (fun j => j <= i /\\ exists m p, rel A j m p)) as H.\n  {\n  exists (S i).\n  intros k (H & _).\n  omega.\n  }\ndestruct H as [Hnone | Hsome].\n  {\n  exists x.\n  intros j m p Hj Hmp.\n  exfalso.\n  refine (Hnone j _).\n  eauto.\n  }\n\n  {\n  destruct Hsome as (j & (Hji & m & p & Hmp) & Hmax).\n  exists (pi1 B (urelspinj (squash_urel w A i) j triv triv (squash_intro _#6 Hji Hmp))).\n  intros k n q Hk Hnq.\n  exploit (Hmax k) as Hkj; eauto.\n  apply (pi2 B).\n  apply dist_symm.\n  apply urelspinj_dist; auto.\n  }\nQed.\n\n\nLemma unguard_prop_unique :\n  forall w (A : wurel w) i (B : urelsp (squash_urel w A i) -n> wiurel_ofe w),\n    exists! (x : car (wiurel_ofe w)),\n      (forall j, \n         (forall k m p, k <= i -> rel A k m p -> k < j)\n         -> x = iutruncate j x)\n      /\\\n      (forall j m p (Hj : j <= i) (Hmp : rel A j m p),\n         dist (S j) x (pi1 B (urelspinj (squash_urel w A i) j triv triv (squash_intro _#6 Hj Hmp)))).\nProof.\nintros w A i B.\nexploit (maximum_element (fun j => j <= i /\\ exists m p, rel A j m p)) as H.\n  {\n  exists (S i).\n  intros k (H & _).\n  omega.\n  }\ndestruct H as [Hnone | Hsome].\n  {\n  exists (iubase empty_urel).\n  split.\n    {\n    split.\n      {\n      intros j Hj.\n      rewrite -> iutruncate_iubase.\n      rewrite -> ceiling_empty_urel.\n      reflexivity.\n      }\n\n      {\n      intros j m p Hj Hmp.\n      exfalso.\n      refine (Hnone j _).\n      eauto.\n      }\n    }\n\n    {\n    intros y (Hy & _).\n    exploit (Hy 0) as Heq.\n      {\n      intros k m p Hki Hmp.\n      exfalso.\n      refine (Hnone 0 _).\n      split; [omega |].\n      exists m, p.\n      apply (urel_downward_leq _#3 k); auto.\n      omega.\n      }\n\n      {\n      rewrite -> Heq.\n      symmetry.\n      apply iutruncate_zero.\n      }\n    }\n  }\n\n  {\n  destruct Hsome as (j & (Hji & m & p & Hmp) & Hbound).\n  exists (iutruncate (S j) (pi1 B (urelspinj (squash_urel w A i) j triv triv (squash_intro _#6 Hji Hmp)))).\n  split.\n    {\n    split.\n      {\n      intros k Hk.\n      rewrite -> iutruncate_combine.\n      so (Hk j m p Hji Hmp) as Hjk.\n      rewrite -> Nat.min_r; auto.\n      }\n\n      {\n      intros k n q Hk Hnq.\n      exploit (Hbound k) as Hkj; eauto.\n      eapply dist_trans.\n        {\n        apply (dist_downward_leq _ _ (S j)); [omega |].\n        apply iutruncate_near.\n        }\n        \n        {\n        apply (pi2 B).\n        apply dist_symm.\n        apply urelspinj_dist; auto.\n        }\n      }\n    }\n\n    {\n    intros y (Htrunc & Hdist).\n    exploit (Htrunc (S j)) as Heq.\n      {\n      intros k n q Hki Hnq.\n      cut (k <= j); [omega |].\n      apply Hbound; eauto.\n      }\n    rewrite -> Heq.\n    apply iutruncate_collapse.\n    apply dist_symm.\n    apply Hdist.\n    }\n  }\nQed.\n\n\nLemma unguard :\n  forall w (A : wurel w) i (B : urelsp (squash_urel w A i) -n> wiurel_ofe w),\n    existsT (x : car (wiurel_ofe w)),\n      (forall j, \n         (forall k m p, k <= i -> rel A k m p -> k < j)\n         -> x = iutruncate j x)\n      /\\\n      (forall j m p (Hj : j <= i) (Hmp : rel A j m p),\n         dist (S j) x (pi1 B (urelspinj (squash_urel w A i) j triv triv (squash_intro _#6 Hj Hmp)))).\nProof.\nintros w A i B.\nexact (description _ _ (unguard_prop_unique w A i B)).\nQed.\n\n\nLemma iutruncate_unguard :\n  forall n w i A B (h : n <= i),\n    iutruncate (S n) (pi1 (unguard w A i B))\n    =\n    pi1 (unguard w (ceiling (S n) A) n\n           (nearrow_compose \n              (nearrow_compose (iutruncate_ne (S n)) B)\n              (embed_ceiling_squash_ne w n i A h))).\nProof.\nintros n w i A B h.\nset (X := unguard w A i B).\ndestruct X as (C & HtruncC & HC).\nmatch goal with\n| |- _ = pi1 ?Y => set (X := Y)\nend.\ndestruct X as (D & HtruncD & HD).\ncbn [pi1].\nexploit (maximum_element (fun j => exists m p, j <= i /\\ rel A j m p)) as H.\n  {\n  exists (S i).\n  intros k (_ & _ & H & _).\n  omega.\n  }\ndestruct H as [Hnone | Hsome].\n  {\n  clear HC HD.\n  exploit (HtruncC 0) as HeqC.\n    {\n    intros k m p Hk Hmp.\n    exfalso.\n    refine (Hnone k _).\n    eauto.\n    }\n  exploit (HtruncD 0) as HeqD.\n    {\n    intros k m p Hk Hmp.\n    destruct Hmp as (_ & Hmp).\n    exfalso.\n    refine (Hnone k _).\n    exists m, p.\n    split; auto.\n    omega.\n    }\n  rewrite -> HeqC, -> HeqD.\n  rewrite -> iutruncate_combine.\n  rewrite -> Nat.min_r; [| omega].\n  rewrite -> !iutruncate_zero.\n  reflexivity.\n  }\n\n  {\n  destruct Hsome as (j & (m & p & Hji & Hmp) & Hmax).\n  exploit (HtruncC (S j)) as HeqC.\n    {\n    intros k q r Hk Hqr.\n    cut (k <= j); [omega |].\n    apply Hmax; eauto.\n    }\n  exploit (HtruncD (min (S n) (S j))) as HeqD.\n    {\n    intros k q r Hk Hqr.\n    destruct Hqr as (_ & Hqr).\n    rewrite <- Nat.succ_min_distr.\n    apply le_lt_n_Sm.\n    apply Nat.min_glb; auto.\n    apply Hmax.\n    exists q, r.\n    split; auto.\n    omega.\n    }\n  rewrite -> HeqC, -> HeqD.\n  clear HeqC HeqD.\n  cbn [snd iutruncate].\n  rewrite -> iutruncate_combine.\n  clear Hji Hmax.\n  rewrite <- Nat.succ_min_distr.\n  so (Nat.le_min_l n j) as Hkn.\n  set (k := min n j) in Hkn |- *.\n  assert (rel A k m p) as Hmp'.\n    {\n    so (Nat.le_min_r n j).\n    eapply urel_downward_leq; eauto.\n    }\n  clearbody k.\n  clear j Hmp.\n  rename Hmp' into Hmp.\n  apply iutruncate_collapse.\n  assert (rel (ceiling (S n) A) k m p) as Hmpn.\n    {\n    split; auto.\n    omega.\n    }\n  eapply dist_trans.\n    {\n    apply (HC k m p (le_trans _#3 Hkn h) Hmp).\n    }\n  apply dist_symm.\n  eapply dist_trans.\n    {\n    apply (HD k m p Hkn Hmpn).\n    }\n  cbn -[dist].\n  eapply dist_trans.\n    {\n    apply (dist_downward_leq _ _ (S n)); [omega |].\n    apply iutruncate_near.\n    }\n  apply (pi2 B).\n  assert (k < S n) as Hkn' by omega.\n  assert (rel (squash_urel w A i) k triv triv) as Htriv.\n    {\n    eapply squash_intro; eauto.\n    omega.\n    }\n  erewrite -> transport_urelspinj.\nUnshelve.\n  2:{\n    exact (conj Hkn' Htriv).\n    }\n  rewrite -> embed_ceiling_urelspinj.\n  apply urelspinj_dist.\n  auto.\n  }\nQed.\n\n\nLemma extend_unguard :\n  forall v w (h : v <<= w) i A B,\n    extend_iurel h (pi1 (unguard v A i B))\n    =\n    pi1 (unguard w (extend_urel v w A) i\n           (nearrow_compose\n              (extend_iurel_ne h)\n              (nearrow_compose B\n                 (nearrow_compose \n                    (deextend_urelsp_ne h (squash_urel v A i))\n                    (transport_ne (eqsymm (extend_squash v w A i h)) urelsp))))).\nProof.\nintros v w h i A B.\nset (X := unguard v A i B).\ndestruct X as (C & HtruncC & HC).\nmatch goal with\n| |- _ = pi1 ?Y => set (X := Y)\nend.\ndestruct X as (D & HtruncD & HD).\ncbn.\nexploit (maximum_element (fun j => exists m p, j <= i /\\ rel A j m p)) as H.\n  {\n  exists (S i).\n  intros k (_ & _ & H & _).\n  omega.\n  }\ndestruct H as [Hnone | Hsome].\n  {\n  clear HC HD.\n  exploit (HtruncC 0) as HeqC.\n    {\n    intros k m p Hk Hmp.\n    exfalso.\n    refine (Hnone k _).\n    eauto.\n    }\n  exploit (HtruncD 0) as HeqD.\n    {\n    intros k m p Hk Hmp.\n    cbn in Hmp.\n    exfalso.\n    refine (Hnone k _).\n    exists (map_term (extend w v) m), (map_term (extend w v) p).\n    split; auto.\n    }\n  rewrite -> HeqC, -> HeqD.\n  rewrite -> !iutruncate_zero.\n  cbn.\n  rewrite -> extend_iubase.\n  rewrite -> extend_empty_urel; auto.\n  }\n\n  {\n  destruct Hsome as (j & (m & p & Hji & Hmp) & Hmax).\n  exploit (HtruncC (S j)) as HeqC.\n    {\n    intros k q r Hk Hqr.\n    cut (k <= j); [omega |].\n    apply Hmax; eauto.\n    }\n  exploit (HtruncD (S j)) as HeqD.\n    {\n    intros k q r Hk Hqr.\n    cbn in Hqr.\n    apply le_lt_n_Sm.\n    apply Hmax.\n    do 2 eexists.\n    eauto.\n    }\n  rewrite -> HeqC, -> HeqD.\n  clear HeqC HeqD.\n  rewrite <- iutruncate_extend_iurel.\n  apply iutruncate_collapse.\n  assert (rel (extend_urel v w A) j (map_term (extend v w) m) (map_term (extend v w) p)) as Hmp'.\n    {\n    cbn.\n    rewrite -> !extend_term_cancel; auto.\n    }\n  eapply dist_trans.\n  2:{\n    eapply dist_symm.\n    so (HD j (map_term (extend v w) m) (map_term (extend v w) p) Hji Hmp') as H.\n    exact H.\n    }\n  apply extend_iurel_nonexpansive.\n  eapply dist_trans.\n    {\n    so (HC j m p Hji Hmp) as H.\n    exact H.\n    }\n  apply dist_refl'.\n  cbn.\n  f_equal.\n  erewrite -> (transport_urelspinj _#3 (eqsymm (extend_squash v w A i h))).\nUnshelve.\n  2:{\n    eapply squash_intro; eauto.\n    }\n  rewrite -> deextend_urelsp_urelspinj.\n  reflexivity.\n  }\nQed.\n\n\nDefinition iuguard (w : ordinal) i (A : wiurel w) (B : urelsp (squash_urel w (den A) i) -n> wiurel_ofe w) : wiurel w\n  :=\n  (guard_urel w i (den A) (fun C => den (pi1 B C)),\n   snd (pi1 (unguard w (den A) i B))).\n\n\nLemma iutruncate_iuguard :\n  forall n w i (A : wiurel w) (B : urelsp (squash_urel w (den A) i) -n> wiurel_ofe w) (h : n <= i),\n    iutruncate (S n) (iuguard w i A B)\n    =\n    iuguard w n\n      (iutruncate (S n) A)\n      (nearrow_compose\n         (nearrow_compose (iutruncate_ne (S n)) B)\n         (embed_ceiling_squash_ne w n i (den A) h)).\nProof.\nintros n w i A B h.\nunfold iuguard.\nunfold iutruncate.\ncbn [den fst snd].\nf_equal.\n  {\n  rewrite -> (ceiling_guard _#5 h); auto.\n  exact (pi2 (nearrow_compose den_ne B)).\n  }\n\n  {\n  exact (f_equal snd (iutruncate_unguard n w i (den A) B h)).\n  }\nQed.\n\n\nLemma extend_iuguard :\n  forall v w (h : v <<= w) i A B,\n    extend_iurel h (iuguard v i A B)\n    =\n    iuguard w i (extend_iurel h A)\n      (nearrow_compose (extend_iurel_ne h)\n         (nearrow_compose B\n            (nearrow_compose\n               (deextend_urelsp_ne h (squash_urel v (den A) i))\n               (transport_ne (eqsymm (extend_squash v w (den A) i h)) urelsp)))).\nProof.\nintros v w h i A B.\nunfold iuguard, extend_iurel.\ncbn.\nf_equal.  (* Why slow? *)\n  {\n  rewrite -> (extend_guard _ _ h).\n  reflexivity.\n  }\n\n  {\n  exact (f_equal snd (extend_unguard _ _ h i (den A) B)).\n  }\nQed.\n\n\nLemma guard_urel_satisfied_eq :\n  forall w \n    (A : wurel w) \n    i \n    (B : car (urelsp (squash_urel w A i)) -> car (wurel_ofe w))\n    j m p\n    (Hj : j <= i)\n    (Hmp : rel A j m p),\n      nonexpansive B\n      -> ceiling (S j) (B (urelspinj _#4 (squash_intro _#6 Hj Hmp)))\n         = \n         ceiling (S j) (guard_urel w i A B).\n\nProof.\nintros w A i B j m p Hj Hmp Hne.\napply urel_extensionality.\nfextensionality 3.\nintros k n q.\ncbn.\npextensionality.\n  {\n  intros (Hk & Hnq).\n  split; auto.\n  assert (k <= i) as Hki by omega.\n  exists Hki.\n  so (urel_closed _#5 Hnq) as (Hcln & Hclq).\n  do2 2 split; auto.\n  intros l r t Hl Hrt.\n  eapply rel_from_dist.\n  2:{\n    apply (urel_downward_leq _#3 k); eauto.\n    }\n  apply Hne.\n  apply dist_symm.\n  apply urelspinj_dist.\n  omega.\n  }\n\n  {\n  intros (Hk & Hnq).\n  split; auto.\n  destruct Hnq as (Hki & _ & _ & Hact).\n  assert (k <= j) as Hkj by omega.\n  so (urel_downward_leq _#6 Hkj Hmp) as Hmp'.\n  so (Hact k m p (le_refl _) Hmp') as Hnq.\n  eapply rel_from_dist; eauto.\n  apply Hne.\n  apply urelspinj_dist; auto.\n  }\nQed.\n\n\nLemma iuguard_satisfied_eq :\n  forall w\n    (A : wiurel w)\n    i\n    (B : urelsp (squash_urel w (den A) i) -n> wiurel_ofe w)\n    j m p\n    (Hj : j <= i)\n    (Hmp : rel (den A) j m p),\n      iutruncate (S j) (pi1 B (urelspinj _#4 (squash_intro _#6 Hj Hmp)))\n      =\n      iutruncate (S j) (iuguard w i A B).\nProof.\nintros w A i B j m p Hj Hmp.\nunfold iutruncate, iuguard.\ncbn [fst snd].\nf_equal.\n  {\n  eapply (guard_urel_satisfied_eq _#3 (fun C => den (pi1 B C))).\n  apply compose_ne_ne.\n    {\n    apply den_nonexpansive.\n    }\n\n    {\n    exact (pi2 B).\n    }\n  }\n\n  {\n  apply meta_truncate_collapse.\n  apply dist_prod_snd.\n  set (X := unguard w (den A) i B).\n  destruct X as (C & Htrunc & HC).\n  cbn [pi1].\n  apply dist_symm.\n  auto.\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/SemanticsGuard.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.4035668537353745, "lm_q1q2_score": 0.2628652333985102}}
{"text": "From Coq Require Import Bool String List BinPos Compare_dec Lia Arith.\nFrom Equations Require Import Equations.\nFrom Translation Require Import util Sorts SAst SLiftSubst SCommon Equality.\n\nReserved Notation \" Σ ;;; Γ '|-x' t : T \" (at level 50, Γ, t, T at next level).\nReserved Notation \" Σ ;;; Γ '|-x' t ≡ u : T \" (at level 50, Γ, t, u, T at next level).\n\nOpen Scope s_scope.\n\nSection XTyping.\n\nContext `{Sort_notion : Sorts.notion}.\n\nInductive typing (Σ : sglobal_context) (Γ : scontext) : sterm -> sterm -> Type :=\n| type_Rel n :\n    forall A,\n      nth_error Γ n = Some A ->\n      Σ ;;; Γ |-x (sRel n) : lift0 (S n) A\n\n| type_Sort s :\n    Σ ;;; Γ |-x (sSort s) : sSort (succ s)\n\n| type_Prod n t b s1 s2 :\n    Σ ;;; Γ |-x t : sSort s1 ->\n    Σ ;;; Γ ,, t |-x b : sSort s2 ->\n    Σ ;;; Γ |-x (sProd n t b) : sSort (Sorts.prod_sort s1 s2)\n\n| type_Lambda n n' t b s1 s2 bty :\n    Σ ;;; Γ |-x t : sSort s1 ->\n    Σ ;;; Γ ,, t |-x bty : sSort s2 ->\n    Σ ;;; Γ ,, t |-x b : bty ->\n    Σ ;;; Γ |-x (sLambda n t bty b) : sProd n' t bty\n\n| type_App n s1 s2 t A B u :\n    Σ ;;; Γ |-x A : sSort s1 ->\n    Σ ;;; Γ ,, A |-x B : sSort s2 ->\n    Σ ;;; Γ |-x t : sProd n A B ->\n    Σ ;;; Γ |-x u : A ->\n    Σ ;;; Γ |-x (sApp t A B u) : B{ 0 := u }\n\n| type_Sum n t b s1 s2 :\n    Σ ;;; Γ |-x t : sSort s1 ->\n    Σ ;;; Γ ,, t |-x b : sSort s2 ->\n    Σ ;;; Γ |-x (sSum n t b) : sSort (Sorts.sum_sort s1 s2)\n\n| type_Pair n A B u v s1 s2 :\n    Σ ;;; Γ |-x A : sSort s1 ->\n    Σ ;;; Γ ,, A |-x B : sSort s2 ->\n    Σ ;;; Γ |-x u : A ->\n    Σ ;;; Γ |-x v : B{ 0 := u } ->\n    Σ ;;; Γ |-x sPair A B u v : sSum n A B\n\n| type_Pi1 n A B s1 s2 p :\n    Σ ;;; Γ |-x p : sSum n A B ->\n    Σ ;;; Γ |-x A : sSort s1 ->\n    Σ ;;; Γ ,, A |-x B : sSort s2 ->\n    Σ ;;; Γ |-x sPi1 A B p : A\n\n| type_Pi2 n A B s1 s2 p :\n    Σ ;;; Γ |-x p : sSum n A B ->\n    Σ ;;; Γ |-x A : sSort s1 ->\n    Σ ;;; Γ ,, A |-x B : sSort s2 ->\n    Σ ;;; Γ |-x sPi2 A B p : B{ 0 := sPi1 A B p }\n\n| type_Eq s A u v :\n    Σ ;;; Γ |-x A : sSort s ->\n    Σ ;;; Γ |-x u : A ->\n    Σ ;;; Γ |-x v : A ->\n    Σ ;;; Γ |-x sEq A u v : sSort (Sorts.eq_sort s)\n\n| type_Refl s A u :\n    Σ ;;; Γ |-x A : sSort s ->\n    Σ ;;; Γ |-x u : A ->\n    Σ ;;; Γ |-x sRefl A u : sEq A u u\n\n| type_Ax id ty :\n    lookup_glob Σ id = Some ty ->\n    Σ ;;; Γ |-x sAx id : ty\n\n| type_conv t A B s :\n    Σ ;;; Γ |-x t : A ->\n    Σ ;;; Γ |-x B : sSort s ->\n    Σ ;;; Γ |-x A ≡ B : sSort s ->\n    Σ ;;; Γ |-x t : B\n\nwhere \" Σ ;;; Γ '|-x' t : T \" := (@typing Σ Γ t T) : x_scope\n\nwith eq_term (Σ : sglobal_context) (Γ : scontext) : sterm -> sterm -> sterm -> Type :=\n| eq_reflexivity u A :\n    Σ ;;; Γ |-x u : A ->\n    Σ ;;; Γ |-x u ≡ u : A\n\n| eq_symmetry u v A :\n    Σ ;;; Γ |-x u ≡ v : A ->\n    Σ ;;; Γ |-x v ≡ u : A\n\n| eq_transitivity u v w A :\n    Σ ;;; Γ |-x u ≡ v : A ->\n    Σ ;;; Γ |-x v ≡ w : A ->\n    Σ ;;; Γ |-x u ≡ w : A\n\n| eq_beta s1 s2 n A B t u :\n    Σ ;;; Γ |-x A : sSort s1 ->\n    Σ ;;; Γ ,, A |-x B : sSort s2 ->\n    Σ ;;; Γ ,, A |-x t : B ->\n    Σ ;;; Γ |-x u : A ->\n    Σ ;;; Γ |-x sApp (sLambda n A B t) A B u ≡ t{ 0 := u } : B{ 0 := u }\n\n| eq_conv s T1 T2 t1 t2 :\n    Σ ;;; Γ |-x t1 ≡ t2 : T1 ->\n    Σ ;;; Γ |-x T1 ≡ T2 : sSort s ->\n    Σ ;;; Γ |-x t1 ≡ t2 : T2\n\n| cong_Prod n1 n2 A1 A2 B1 B2 s1 s2 :\n    Σ ;;; Γ |-x A1 ≡ A2 : sSort s1 ->\n    Σ ;;; Γ ,, A1 |-x B1 ≡ B2 : sSort s2 ->\n    Σ ;;; Γ ,, A1 |-x B1 : sSort s2 ->\n    Σ ;;; Γ ,, A2 |-x B2 : sSort s2 ->\n    Σ ;;; Γ |-x (sProd n1 A1 B1) ≡ (sProd n2 A2 B2) :\n               sSort (Sorts.prod_sort s1 s2)\n\n| cong_Lambda n1 n2 n' A1 A2 B1 B2 t1 t2 s1 s2 :\n    Σ ;;; Γ |-x A1 ≡ A2 : sSort s1 ->\n    Σ ;;; Γ ,, A1 |-x B1 ≡ B2 : sSort s2 ->\n    Σ ;;; Γ ,, A1 |-x t1 ≡ t2 : B1 ->\n    Σ ;;; Γ ,, A1 |-x B1 : sSort s2 ->\n    Σ ;;; Γ ,, A2 |-x B2 : sSort s2 ->\n    Σ ;;; Γ ,, A1 |-x t1 : B1 ->\n    Σ ;;; Γ ,, A2 |-x t2 : B2 ->\n    Σ ;;; Γ |-x (sLambda n1 A1 B1 t1) ≡ (sLambda n2 A2 B2 t2) : sProd n' A1 B1\n\n| cong_App n1 n2 s1 s2 t1 t2 A1 A2 B1 B2 u1 u2 :\n    Σ ;;; Γ |-x A1 ≡ A2 : sSort s1 ->\n    Σ ;;; Γ ,, A1 |-x B1 ≡ B2 : sSort s2 ->\n    Σ ;;; Γ |-x t1 ≡ t2 : sProd n1 A1 B1 ->\n    Σ ;;; Γ |-x u1 ≡ u2 : A1 ->\n    Σ ;;; Γ ,, A1 |-x B1 : sSort s2 ->\n    Σ ;;; Γ ,, A2 |-x B2 : sSort s2 ->\n    Σ ;;; Γ |-x t1 : sProd n1 A1 B1 ->\n    Σ ;;; Γ |-x t2 : sProd n2 A2 B2 ->\n    Σ ;;; Γ |-x u1 : A1 ->\n    Σ ;;; Γ |-x u2 : A2 ->\n    Σ ;;; Γ |-x (sApp t1 A1 B1 u1) ≡ (sApp t2 A2 B2 u2) : B1{ 0 := u1 }\n\n| cong_Sum n1 n2 A1 A2 B1 B2 s1 s2 :\n    Σ ;;; Γ |-x A1 ≡ A2 : sSort s1 ->\n    Σ ;;; Γ ,, A1 |-x B1 ≡ B2 : sSort s2 ->\n    Σ ;;; Γ ,, A1 |-x B1 : sSort s2 ->\n    Σ ;;; Γ ,, A2 |-x B2 : sSort s2 ->\n    Σ ;;; Γ |-x (sSum n1 A1 B1) ≡ (sSum n2 A2 B2) : sSort (Sorts.sum_sort s1 s2)\n\n| cong_Pair n A1 A2 B1 B2 u1 u2 v1 v2 s1 s2 :\n    Σ ;;; Γ |-x A1 ≡ A2 : sSort s1 ->\n    Σ ;;; Γ ,, A1 |-x B1 ≡ B2 : sSort s2 ->\n    Σ ;;; Γ |-x u1 ≡ u2 : A1 ->\n    Σ ;;; Γ |-x v1 ≡ v2 : B1{ 0 := u1 } ->\n    Σ ;;; Γ ,, A1 |-x B1 : sSort s2 ->\n    Σ ;;; Γ ,, A2 |-x B2 : sSort s2 ->\n    Σ ;;; Γ |-x u1 : A1 ->\n    Σ ;;; Γ |-x u2 : A2 ->\n    Σ ;;; Γ |-x v1 : B1{ 0 := u1 } ->\n    Σ ;;; Γ |-x v2 : B2{ 0 := u2 } ->\n    Σ ;;; Γ |-x sPair A1 B1 u1 v1 ≡ sPair A2 B2 u2 v2 : sSum n A1 B1\n\n| cong_Pi1 nx ny A1 A2 B1 B2 s1 s2 p1 p2 :\n    Σ ;;; Γ |-x p1 ≡ p2 : sSum nx A1 B1 ->\n    Σ ;;; Γ |-x A1 ≡ A2 : sSort s1 ->\n    Σ ;;; Γ ,, A1 |-x B1 ≡ B2 : sSort s2 ->\n    Σ ;;; Γ ,, A1 |-x B1 : sSort s2 ->\n    Σ ;;; Γ ,, A2 |-x B2 : sSort s2 ->\n    Σ ;;; Γ |-x p1 : sSum nx A1 B1 ->\n    Σ ;;; Γ |-x p2 : sSum ny A2 B2 ->\n    Σ ;;; Γ |-x sPi1 A1 B1 p1 ≡ sPi1 A2 B2 p2 : A1\n\n| cong_Pi2 nx ny A1 A2 B1 B2 s1 s2 p1 p2 :\n    Σ ;;; Γ |-x p1 ≡ p2 : sSum nx A1 B1 ->\n    Σ ;;; Γ |-x A1 ≡ A2 : sSort s1 ->\n    Σ ;;; Γ ,, A1 |-x B1 ≡ B2 : sSort s2 ->\n    Σ ;;; Γ ,, A1 |-x B1 : sSort s2 ->\n    Σ ;;; Γ ,, A2 |-x B2 : sSort s2 ->\n    Σ ;;; Γ |-x p1 : sSum nx A1 B1 ->\n    Σ ;;; Γ |-x p2 : sSum ny A2 B2 ->\n    Σ ;;; Γ |-x sPi2 A1 B1 p1 ≡ sPi2 A2 B2 p2 : B1{ 0 := sPi1 A1 B1 p1 }\n\n| cong_Eq s A1 A2 u1 u2 v1 v2 :\n    Σ ;;; Γ |-x A1 ≡ A2 : sSort s ->\n    Σ ;;; Γ |-x u1 ≡ u2 : A1 ->\n    Σ ;;; Γ |-x v1 ≡ v2 : A1 ->\n    Σ ;;; Γ |-x sEq A1 u1 v1 ≡ sEq A2 u2 v2 : sSort (Sorts.eq_sort s)\n\n| cong_Refl s A1 A2 u1 u2 :\n    Σ ;;; Γ |-x A1 ≡ A2 : sSort s ->\n    Σ ;;; Γ |-x u1 ≡ u2 : A1 ->\n    Σ ;;; Γ |-x sRefl A1 u1 ≡ sRefl A2 u2 : sEq A1 u1 u1\n\n| reflection A u v e :\n    Σ ;;; Γ |-x e : sEq A u v ->\n    Σ ;;; Γ |-x u ≡ v : A\n\n| eq_alpha u v A :\n    nl u = nl v ->\n    Σ ;;; Γ |-x u : A ->\n    Σ ;;; Γ |-x u ≡ v : A\n\nwhere \" Σ ;;; Γ '|-x' t ≡ u : T \" := (@eq_term Σ Γ t u T) : x_scope.\n\nDelimit Scope x_scope with x.\n\nOpen Scope x_scope.\n\nInductive wf (Σ : sglobal_context) : scontext -> Type :=\n| wf_nil :\n    wf Σ nil\n\n| wf_snoc Γ A s :\n    wf Σ Γ ->\n    Σ ;;; Γ |-x A : sSort s ->\n    wf Σ (Γ ,, A).\n\nDerive Signature for typing.\nDerive Signature for wf.\nDerive Signature for eq_term.\n\nEnd XTyping.\n\nNotation \" Σ ;;; Γ '|-x' t : T \" :=\n  (@typing _ Σ Γ t T) (at level 50, Γ, t, T at next level) : x_scope.\nNotation \" Σ ;;; Γ '|-x' t ≡ u : T \" :=\n  (@eq_term _ Σ Γ t u T) (at level 50, Γ, t, u, T at next level) : x_scope.", "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/XTyping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2627767931151938}}
{"text": "(*\nClass NormalImperativeProgrammingLanguage (Imp: ImperativeProgrammingLanguage): Type := {\n  Ssequence: cmd -> cmd -> cmd;\n  Sskip: cmd;\n  neq_Sskip_Ssequence: forall c1 c2, Sskip <> Ssequence c1 c2\n}.\n\nClass SmallStepSemantics (Imp: ImperativeProgrammingLanguage) (MD: Model): Type := {\n  state := model;\n  exceptional_state: Type;\n  step: cmd * state -> cmd * state + exceptional_state -> Prop\n}.\n\nDefinition fmap_sum_left {A1 A2 B: Type} (f: A1 -> A2) (x: A1 + B): A2 + B :=\n  match x with\n  | inl a => inl (f a)\n  | inr b => inr b\n  end.\n\nDefinition fmap_Sseq {Imp: ImperativeProgrammingLanguage} {nImp: NormalImperativeProgrammingLanguage Imp} {MD: Model} {sss: SmallStepSemantics Imp MD} (mcs: cmd * state + exceptional_state) (c0: cmd) :=\n  fmap_sum_left (fun cs: cmd * state => let (c, s) := cs in (Ssequence c c0, s)) mcs.\n\nDefinition fmap_pair_cmd {Imp: ImperativeProgrammingLanguage} {nImp: NormalImperativeProgrammingLanguage Imp} {MD: Model} {sss: SmallStepSemantics Imp MD} (ms: state + exceptional_state) (c: cmd) :=\n  fmap_sum_left (pair c) ms.\n\nClass NormalSmallStepSemantics (Imp: ImperativeProgrammingLanguage) {nImp: NormalImperativeProgrammingLanguage Imp} (MD: Model) (sss: SmallStepSemantics Imp MD): Type := {\n  step_Ssequence1: forall c1 c2 s1 mcs2,\n    c2 <> Sskip ->\n    ((exists mcs1, step (c1, s1) mcs1 /\\ mcs2 = fmap_Sseq mcs1 c2) <->\n     step (Ssequence c1 c2, s1) mcs2);\n  step_Ssequence2: forall c s mcs,\n    step (c, s) mcs <->\n    step (Ssequence Sskip c, s) mcs;\n  step_progress: forall c s, c = Sskip <-> exists mcs, step (c, s) mcs\n}.\n\nInductive iter_step {Imp: ImperativeProgrammingLanguage} {nImp: NormalImperativeProgrammingLanguage Imp} {MD: Model} {sss: SmallStepSemantics Imp MD}: cmd * state + exceptional_state -> cmd * state + exceptional_state -> Prop :=\n| iter_step_refl: forall mcs, iter_step mcs mcs\n| iter_step_step: forall cs mcs1 mcs2, step cs mcs1 -> iter_step mcs1 mcs2 -> iter_step (inl cs) mcs2.\n\nDefinition access {Imp: ImperativeProgrammingLanguage} {nImp: NormalImperativeProgrammingLanguage Imp} {MD: Model} {sss: SmallStepSemantics Imp MD} (ms_init: state + exceptional_state) (c: cmd) (ms_end: state + exceptional_state): Prop :=\n  iter_step (fmap_pair_cmd ms_init c) (fmap_pair_cmd ms_end Sskip).\n*)\n(*\nLemma exception_go_nowhere: forall e c ms,\n  access (inr e) c ms <->\n  ms = inr e.\nProof.\n  intros.\n  split; intros.\n  + hnf in H.\n    remember (fmap_pair_cmd (inr e) c) as mcs1 eqn:?H.\n    remember (fmap_pair_cmd ms Sskip) as mcs2 eqn:?H.\n    induction H.\n    - subst.\n      destruct ms; inversion H1.\n      subst; auto.\n    - subst.\n      inversion H0.\n  + subst.\n    hnf.\n    simpl.\n    apply iter_step_refl.\nQed.\n\nLemma aux_sequence_sound: forall c1 c2 ms1 ms3,\n  access ms1 (Ssequence c1 c2) ms3 ->\n  exists ms2,\n  access ms1 c1 ms2 /\\ access ms2 c2 ms3.\nProof.\n  intros.\n  destruct ms1 as [s1 | e1].\n  Focus 2. {\n    exists (inr e1).\n    rewrite exception_go_nowhere in H.\n    subst.\n    split; rewrite exception_go_nowhere; auto.\n  } Unfocus.\n  unfold access in H.\n  remember (fmap_pair_cmd (inl s1) (Ssequence c1 c2)) as mcs1 eqn:?H.\n  remember (fmap_pair_cmd ms3 Sskip) as mcs2 eqn:?H.\n  revert c1 H0.\n  induction H; intros; subst.\n  + destruct ms3 as [s3 | e3]; inversion H0.\n    apply neq_Sskip_Ssequence in H1; contradiction.\n  + rename IHiter_step into IH.\n    specialize (IH eq_refl).\n    inversion H2; subst; clear H2.\n*)(*\nLemma hoare_sequence_sound: forall c1 c2 P Q R,\n  triple_valid guard P c1 Q ->\n  triple_valid guard Q c2 R ->\n  triple_valid guard P (Ssequence c1 c2) R.\nProof.\n  intros.\n  hnf; intros.\n  unfold access in H1.\n  remember (fmap_pair_cmd (inl s_pre) (Ssequence c1 c2)) as mcs1 eqn:?H.\n  remember (fmap_pair_cmd ms_post Sskip) as mcs2 eqn:?H.\n  revert P c1 H H2 H3.\n  induction H1; intros; subst.\n  + destruct ms_post as [s_post | e]; [| inversion H3].\n    inversion H3; clear H3.\n    apply neq_Sskip_Ssequence in H4; contradiction.\n  + rename IHiter_step into IH.\n    specialize (IH eq_refl).\nAbort.\n\n*)", "meta": {"author": "QinxiangCao", "repo": "UnifySL", "sha": "cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d", "save_path": "github-repos/coq/QinxiangCao-UnifySL", "path": "github-repos/coq/QinxiangCao-UnifySL/UnifySL-cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d/HoareLogic/UnusedProofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2627767882488757}}
{"text": "Generalizable All Variables.\nSet Implicit Arguments.\nRequire Export setoid ring ZArith.\n\nDeclare Scope real_scope.\nDelimit Scope real_scope with R.\nOpen Scope setoid_scope.\nOpen Scope ring_scope.\nOpen Scope real_scope.\nOpen Scope Z_scope.\n\nDefinition comparison_eq a b :=\n  match a, b with\n  | Eq, Eq => True\n  | Lt, Lt => True\n  | Gt, Gt => True\n  | _, _ => False\n  end.\n#[global] Hint Unfold comparison_eq : eq.\nProgram Canonical Structure comparisonS :=\n  [ ==: comparison_eq ].\nNext Obligation.\n  split; intros x; case x; try (intros y; case y);\n  simpl; intuition.\nDefined.\n\nClass IsR (Rt : Field) (comp : Dymap Rt Rt comparison)\n          (up : Rt -> Z) (IZR : Z -> Rt) :=\n{\n  Rlt_asym : forall a b : Rt, (comp a b == Lt) == (comp b a == Gt);\n  Rlt_trans : Transitive (fun a b => comp a b == Lt);\n  Radd_lt_compat : forall a b c : Rt, (comp b c == Lt) -> (comp (a + b) (a + c) == Lt);\n  Rmul_lt_compat : forall (a : fucar Rt) (b c : Rt), (comp b c == Lt) -> (comp (a * b) (a * c) == Lt);\n  archimed : forall a : Rt, IZR (up r) /\\ IZR (up r) - r <= 1;\n  complete : forall E : {ens Rt}, \n}.\n\nStructure R := {\n  rcar :> Field;\n  compr : Dymap rcar rcar comparison;\n  Rup : rcar -> Z\n\n}.\n\n\n\n\nNotation \"$ x\" := (proj1_sig x)\n  (at level 35, right associativity, format \"$ x\") : real_scope.\n\nClass IsR (Rt : Set) (R0 R1 : Rt) (Req Rlt : Rt -> Rt -> Prop)\n          (Rplus Rmult : Rt -> Rt -> Rt) (Ropp : Rt -> Rt)\n          (Rinv : {r : Rt | Rlt R0 r} -> {r : Rt | Rlt R0 r})\n          (Rup : Rt -> Z) :=\n{\n  Req_equiv :> Equivalence Req;\n  Rplus_comm : forall a b, Req (Rplus a b) (Rplus b a);\n  Rplus_assoc : forall a b c, Req (Rplus a (Rplus b c)) (Rplus (Rplus a b) c);\n  Rplus_opp_r : forall a, Req (Rplus a (Ropp a)) R0;\n  Rplus_0_l : forall a, Req (Rplus R0 a) a;\n  Rmult_comm : forall a b, Req (Rmult a b) (Rmult b a);\n  Rmult_assoc : forall a b c, Req (Rmult a (Rmult b c)) (Rmult (Rmult a b) c);\n  Rinv_l : forall a, Req (Rmult ($(Rinv a)) ($a)) R1;\n  Rmult_1_l : forall a, Req (Rmult R1 a) a;\n  mulRDr : forall a b c, Req (Rmult a (Rplus b c)) (Rplus (Rmult a b) (Rmult a c));\n\n  Rtotord : forall a b, Rlt a b \\/ Req a b \\/ Rlt b a;\n  Rlt_asym : forall a b, Rlt a b -> ~ Rlt b a; \n  Rlt_trans :> Transitive Rlt;\n  Rplus_lt_compat_l : forall a b c, Rlt b c -> Rlt (Rplus a b) (Rplus a c);\n  Rmult_lt_compat_l : forall a b c, Rlt a R0 -> Rlt b c -> Rlt (Rmult a b) (Rmult a c)\n\n  archimed : \n}.\n\n\n\nStructure R : Set := {\n  Rcarrier :> Set;\n  R0 : Rcarrier;\n  R1 : Rcarrier;\n  Req : Rcarrier -> Rcarrier -> Prop;\n  Rlt : Rcarrier -> Rcarrier -> Prop;\n  Rplus : Rcarrier -> Rcarrier -> Rcarrier;\n  Rmult : Rcarrier -> Rcarrier -> Rcarrier;\n  Ropp : Rcarrier -> Rcarrier;\n  Rinv : {r : Rcarrier | Rlt R0 r} -> Rcarrier;\n  Rup : Rcarrier -> Z\n}.\n\n\n(* RをInductiveに定義すると、四則演算で作れる数しか\n   実数として認めないことになる *)\nInductive Runit : Set :=\n| R1 : Runit\n| Rinv : Runit -> Runit\n| Rmulu : Runit -> Runit -> Runit\n| \n.\n\nInductive R : Set :=\n| R\n\nInductive R : Set :=\n| R0 : R\n| R1 : R\n| Rplus : R -> R -> R\n| Rmult : R -> R -> R\n| Ropp : R -> R\n| Rinv : {r : R | Rlt R0 r} -> R\nwith Rlt : R -> R -> Prop :=\n| Rlt_trans : forall a b c, R_lt a b -> R_lt b c -> R_lt a c\n| Rplus_lt_compat_l : forall a b c, R_lt b c -> R_lt (a + b) (a + c)\n| Rmult_lt_compat_l : forall a b c, R_lt a R0 -> R_lt b c -> R_lt (a * b) (a * c)\n.\n\nNotation \"a + b\" := (Rplus a b) : real_scope.\nNotation \"a * b\" := (Rmult a b) : real_scope.\nNotation \"- r\" := (Ropp r) : real_scope.\nNotation \"/ r\" := (Rinv r) : real_scope.\n\nInductive R_eq : R -> R -> Prop :=\n| R_eq_refl : forall a, R_eq a a\n| R_eq_sym : forall a b, R_eq a b -> R_eq b a\n| R_eq_trans : forall a b c, R_eq a b -> R_eq b c -> R_eq a c\n| Rplus_comm : forall a b, R_eq (a + b) (b + a)\n| Rplus_assoc : forall a b c, R_eq (a + (b + c)) (a + b + c)\n| Rplus_opp_r : forall a, R_eq (a + -a) R0\n| Rplus_0_l : forall a, R_eq (R0 + a) a\n| Rmult_comm : forall a b, R_eq (a * b) (b * a)\n| Rmult_assoc : forall a b c, R_eq (a * (b * c)) (a * b * c)\n| Rmult_1_l : forall a, R_eq (R1 * a) a\n| mulRDr : forall a b c, R_eq (a * (b + c)) (a * b + a * c)\n.\n\n\n\nInductive R_lt : R -> R -> Prop :=\n(* | totord : forall a b, R_lt b a \\/ R_eq a b \\/ R_lt a b *)\n(* | Rlt_asym : forall a b, (~ R_lt b a) -> R_lt a b *)\n| Rlt_trans : forall a b c, R_lt a b -> R_lt b c -> R_lt a c\n| Rplus_lt_compat_l : forall a b c, R_lt b c -> R_lt (a + b) (a + c)\n| Rmult_lt_compat_l : forall a b c, R_lt a R0 -> R_lt b c -> R_lt (a * b) (a * c)\n.", "meta": {"author": "elle-et-noire", "repo": "algtop", "sha": "e1101a19c604f2c6211fcfa1fb9c23a6ac12ecc0", "save_path": "github-repos/coq/elle-et-noire-algtop", "path": "github-repos/coq/elle-et-noire-algtop/algtop-e1101a19c604f2c6211fcfa1fb9c23a6ac12ecc0/theories/R.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.26277657384104597}}
{"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 Cover.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import Progress.\nRequire Import APromiseConsistent.\nFrom PromisingLib Require Import Loc.\n\nRequire Import APF.\nRequire Import Race.\nRequire Import Behavior.\nRequire Import SimMemory.\nRequire Import yjtac.\nRequire Import Program.\nRequire Import Cell.\nRequire Import Time.\nRequire Import PredStep.\nRequire Import ReorderPromises2.\n\nRequire Import Pred.\nRequire Import AMemory.\nRequire Import ALocal.\nRequire Import AThread.\nRequire Import APredStep.\nRequire Import ADRF_PF0.\nRequire Import ADRF_PF1.\nRequire Import ADRF_PF2.\nRequire Import ADRF_PF3.\nRequire Import ADRF_PF4.\nRequire Import ADRF_PF5.\nRequire Import AMapping.\n\nSet Implicit Arguments.\n\nLemma forget_config_terminal c_src c_tgt\n      (SIM: forget_config c_src c_tgt)\n      (TERMINAL: Configuration.is_terminal c_tgt)\n  :\n    Configuration.is_terminal c_src.\nProof.\n  inv SIM. ii. specialize (THS tid). rewrite FIND in *.\n  unfold option_rel in THS. des_ifs. inv THS. split; auto.\n  eapply TERMINAL; eauto.\nQed.\n\nLemma sim_pf_all_adequacy c_src c_tgt\n      (SIM: sim_pf_all c_src c_tgt)\n  :\n    behaviors Configuration.step c_tgt <1=\n    behaviors APFConfiguration.step c_src.\nProof.\n  i. ginduction PR; i.\n  - inv SIM. inv SIM0. econs 1. eapply forget_config_terminal; eauto.\n  - exploit sim_pf_step; eauto. i. des; clarify.\n    + inv STEP0. econs 2; eauto. econs 3; eauto.\n    + inv STEP0. econs 2; eauto.\n  - exploit sim_pf_step; eauto. i. des; clarify.\n    + inv STEP0. econs 3; eauto.\n    + inv STEP0. econs 3; eauto.\n    + inv STEP0. econs 3; eauto.\n  - exploit sim_pf_step; eauto. i. des; clarify.\n    + inv STEP0.\n      * econs 3; eauto.\n      * econs 4; eauto. econs 3; eauto.\n    + inv STEP0.\n      * eauto.\n      * econs 4; eauto.\nQed.\n\nTheorem drf_apf s\n        (RACEFREE: pf_racefree APFConfiguration.step (Configuration.init s))\n  :\n    behaviors Configuration.step (Configuration.init s) <1=\n    behaviors APFConfiguration.step (Configuration.init s).\nProof.\n  eapply sim_pf_all_adequacy.\n  eapply sim_pf_init; auto.\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/drf/ADRF_PF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573377, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.26277656131678323}}
{"text": "From iris.proofmode Require Import proofmode.\nFrom stdpp Require Import sets list.\nFrom cap_machine Require Import addr_reg region.\n\nClass DisjointList A := disjoint_list : list A → Prop.\n#[export] Hint Mode DisjointList ! : typeclass_instances.\nInstance: Params (@disjoint_list) 2 := {}.\nNotation \"## Xs\" := (disjoint_list Xs) (at level 20, format \"##  Xs\") : stdpp_scope.\nNotation \"##@{ A } Xs\" :=\n  (@disjoint_list A _ Xs) (at level 20, only parsing) : stdpp_scope.\n\nSection disjoint_list.\n  Variable A: Type.\n  Context `{Disjoint A, Union A, Empty A}.\n  Implicit Types X : A.\n\n  Inductive disjoint_list_default : DisjointList A :=\n    | disjoint_nil_2 : ##@{A} []\n    | disjoint_cons_2 (X : A) (Xs : list A) : X ## ⋃ Xs → ## Xs → ## (X :: Xs).\n  Global Existing Instance disjoint_list_default.\n\n  Lemma disjoint_list_nil  : ##@{A} [] ↔ True.\n  Proof. split; constructor. Qed.\n  Lemma disjoint_list_cons X Xs : ## (X :: Xs) ↔ X ## ⋃ Xs ∧ ## Xs.\n  Proof.\n    split; [inversion_clear 1; auto |].\n    intros [??]. constructor; auto.\n  Qed.\nEnd disjoint_list.\n\nLemma disjoint_mono_l A C `{ElemOf A C} (X Y Z: C) : X ⊆ Y → Y ## Z → X ## Z.\nProof. intros * HXY. rewrite !elem_of_disjoint. eauto. Qed.\n\nLemma disjoint_mono_r A C `{ElemOf A C} (X Y Z: C) : X ⊆ Y → Z ## Y → Z ## X.\nProof. intros * HXY. rewrite !elem_of_disjoint. eauto. Qed.\n\nDefinition ByReflexivity (P: Prop) :=\n  P.\n#[export] Hint Extern 1 (ByReflexivity _) => reflexivity : disj_regions.\n\nDefinition AddrRegionRange (l: list Addr) (b e: Addr) :=\n  ∀ a, a ∈ l → (b <= a)%a ∧ (a < e)%a.\n\nLemma AddrRegionRange_singleton a :\n  ByReflexivity (eqb_addr a top = false) →\n  AddrRegionRange [a] a (a^+1)%a.\nProof.\n  unfold ByReflexivity. cbn. intros ?%Z.eqb_neq.\n  intros a' ->%elem_of_list_singleton. solve_addr.\nQed.\n#[export] Hint Resolve AddrRegionRange_singleton : disj_regions.\n\nLemma AddrRegionRange_region_addrs b e :\n  AddrRegionRange (finz.seq_between b e) b e.\nProof.\n  intros a ?%elem_of_finz_seq_between. solve_addr.\nQed.\n#[export] Hint Resolve AddrRegionRange_region_addrs : disj_regions.\n\nDefinition AddrRegionsRange (ll: list (list Addr)) (b e: Addr) :=\n  ∀ l a, l ∈ ll → a ∈ l → (b <= a)%a ∧ (a < e)%a.\n\nLemma AddrRegionsRange_single l b e :\n  AddrRegionRange l b e →\n  AddrRegionsRange [l] b e.\nProof.\n  intros Hl l' a ->%elem_of_list_singleton ?%Hl. solve_addr.\nQed.\n#[export] Hint Resolve AddrRegionsRange_single | 1 : disj_regions.\n\nLemma AddrRegionsRange_cons l ll b e b' e' :\n  AddrRegionRange l b e →\n  AddrRegionsRange ll b' e' →\n  AddrRegionsRange (l :: ll) (finz.min b b') (finz.max e e').\nProof.\n  intros Hl Hll l' a [->|H]%elem_of_cons.\n  - intros ?%Hl. solve_addr.\n  - intros ?%Hll; auto. solve_addr.\nQed.\n#[export] Hint Resolve AddrRegionsRange_cons | 10 : disj_regions.\n\nInstance Empty_list {A}: Empty (list A). exact []. Defined.\nInstance Union_list {A}: Union (list A). exact app. Defined.\nInstance Singleton_list {A}: Singleton A (list A). exact (λ a, [a]). Defined.\n\nLemma addr_range_union_incl_range (ll: list (list Addr)) (b e: Addr):\n  AddrRegionsRange ll b e →\n  ⋃ ll ⊆ finz.seq_between b e.\nProof.\n  revert b e. induction ll as [| l ll].\n  - intros. cbn. unfold subseteq, list_subseteq. unfold empty, Empty_list.\n    inversion 1.\n  - intros b e HInd. cbn. unfold union, Union_list, subseteq, list_subseteq.\n    intros x. intros [Hx|Hx]%elem_of_app.\n    + specialize (HInd l x ltac:(constructor) Hx). apply elem_of_finz_seq_between.\n      solve_addr.\n    + assert (HI: AddrRegionsRange ll b e).\n      { intros ? ? ? ?. eapply HInd. apply elem_of_list_further; eassumption.\n        auto. }\n      specialize (IHll _ _ HI).\n      rewrite elem_of_subseteq in IHll.\n      by apply IHll.\nQed.\n\nLemma AddrRegionRange_iff_incl_region_addrs l b e :\n  AddrRegionRange l b e ↔ (l ⊆ finz.seq_between b e).\nProof.\n  unfold AddrRegionRange, subseteq, list_subseteq.\n  split.\n  - intros H **. rewrite elem_of_finz_seq_between. by apply H.\n  - intros H **. apply elem_of_finz_seq_between. by apply H.\nQed.\n\nLemma addr_range_disj_union_empty (l: list Addr) :\n  l ## ⋃ [].\nProof.\n  cbn. unfold empty, Empty_list, disjoint.\n  unfold set_disjoint_instance. intros * ? ?%elem_of_nil. auto.\nQed.\n#[export] Hint Resolve addr_range_disj_union_empty | 1 : disj_regions.\n\nLemma addr_range_disj_range_union (l: list Addr) ll b e b' e':\n  AddrRegionRange l b e →\n  AddrRegionsRange ll b' e' →\n  ByReflexivity ((e <=? b') || (e' <=? b) = true)%a →\n  l ## ⋃ ll.\nProof.\n  intros Hl Hll. unfold ByReflexivity.\n  rewrite orb_true_iff !Z.leb_le.\n  intros.\n  rewrite AddrRegionRange_iff_incl_region_addrs in Hl.\n  eapply disjoint_mono_l; eauto.\n  eapply disjoint_mono_r. eapply addr_range_union_incl_range; eauto.\n  unfold disjoint.\n  intro. rewrite !elem_of_finz_seq_between. solve_addr.\nQed.\n#[export] Hint Resolve addr_range_disj_range_union | 10 : disj_regions.\n\nLemma addr_disjoint_list_empty : ## ([]: list (list Addr)).\nProof. constructor. Qed.\n#[export] Hint Resolve addr_disjoint_list_empty : disj_regions.\n\nLemma addr_disjoint_list_cons (l: list Addr) ll :\n  l ## ⋃ ll →\n  ## ll →\n  ## (l :: ll).\nProof. intros. rewrite disjoint_list_cons; auto. Qed.\n#[export] Hint Resolve addr_disjoint_list_cons : disj_regions.\n\nLtac disj_regions :=\n  once (typeclasses eauto with disj_regions).\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/disjoint_regions_tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.26271163403753856}}
{"text": "(**\nCoLoR, a Coq library on rewriting and termination.\nSee the COPYRIGHTS and LICENSE files.\n\n- Adam Koprowski, 2006-04-27\n\nConstructing terms.\n*)\n\nSet Implicit Arguments.\n\nFrom CoLoR Require Import RelExtras ListExtras LogicUtil.\nFrom CoLoR Require TermsActiveEnv.\nFrom Coq Require Import Lia.\n\nModule TermsBuilding (Sig : TermsSig.Signature).\n\n  Module Export TAE := TermsActiveEnv.TermsActiveEnv Sig.\n\n  Record appCond : Type := {\n     appL: Term;\n     appR: Term;\n     eqEnv: env appL = env appR;\n     typArr: isArrowType (type appL);\n     typOk: type_left (type appL) = type appR\n  }.\n\n  Definition buildApp : appCond -> Term.\n\n  Proof.\n    intro t; inversion t as [L R eq_env typ_arr typ_ok].\n    destruct L as [?? typeL typingL]; destruct R as [??? typingR]; simpl in *.\n    rewrite eq_env in typingL.\n    destruct typeL; try contr; simpl in *.\n    rewrite typ_ok in typingL.\n    exact (buildT (TApp typingL typingR)).\n  Defined.\n\n  Lemma buildApp_isApp : forall a, isApp (buildApp a).\n\n  Proof.\n    intros; destruct a; term_type_inv appL0; term_type_inv appR0.\n  Qed.\n\n  Lemma buildApp_Lok : forall a, appBodyL (buildApp_isApp a) = a.(appL).\n\n  Proof.\n    destruct a; destruct appR0; term_type_inv appL0.\n  Qed.\n\n  Lemma buildApp_Rok : forall a, appBodyR (buildApp_isApp a) = a.(appR).\n\n  Proof.\n    destruct a; destruct appR0; term_type_inv appL0.\n  Qed.\n\n  Lemma buildApp_preterm : forall a,\n    term (buildApp a) = term a.(appL) @@ term a.(appR).\n\n  Proof.\n    destruct a; destruct appR0; term_type_inv appL0.\n  Qed.\n\n  Lemma buildApp_env_l : forall a, env (buildApp a) = env a.(appL).\n\n  Proof.\n    destruct a; destruct appR0; term_type_inv appL0.\n  Qed.\n\n  Lemma buildApp_type : forall a,\n    type (buildApp a) = type_right (type a.(appL)).\n\n  Proof.\n    destruct a; destruct appR0; term_type_inv appL0.\n  Qed.\n\n  Record absCond : Type := {\n    absB: Term;\n    absT: SimpleType;\n    envNotEmpty: env absB |= 0 := absT\n  }.\n  \n  Definition buildAbs : absCond -> Term.\n\n  Proof.\n    intro t; inversion t as [aBody aType envCond].\n    destruct aBody as [env ?? typing]; simpl in *; destruct env.\n    try_solve.\n    destruct o.\n    exact (buildT (TAbs typing)).\n    try_solve.\n  Defined.\n\n  Lemma buildAbs_isAbs: forall a, isAbs (buildAbs a).\n  Proof.\n    destruct a as [[env ???] ??]; destruct env.\n    try_solve.\n    destruct o; try_solve.\n  Qed.\n\n  Lemma buildAbs_absBody : forall a, absBody (buildAbs_isAbs a) = a.(absB).\n\n  Proof.\n    destruct a as [[env ???] ??]; destruct env.\n    try_solve.\n    destruct o; try_solve.\n  Qed.\n\n  Lemma buildAbs_absType : forall a, absType (buildAbs_isAbs a) = a.(absT).\n\n  Proof.\n    destruct a as [[env ???] ??]; destruct env.\n    try_solve.\n    destruct o; try_solve.\n    unfold VarD in * .\n    inversion envNotEmpty0; trivial.\n  Qed.\n\n  Lemma buildAbs_env : forall a, env (buildAbs a) = tail (env a.(absB)).\n\n  Proof.\n    destruct a as [[env ???] ??]; destruct env.\n    try_solve.\n    destruct o; try_solve.\n  Qed.\n\n  Definition buildVar : forall A x, (copy x None ++ A [#] EmptyEnv) |- %x := A.\n\n  Proof.\n    constructor; unfold VarD.\n    rewrite nth_app_right; autorewrite with datatypes using try lia.\n    replace (x - x) with 0; trivial.\n    lia.\n  Defined.\n\n  Lemma buildVar_minimal : forall A x, envMinimal (buildT (buildVar A x)).\n\n  Proof.\n    intros; unfold envMinimal; trivial.\n  Qed.\n\nEnd TermsBuilding.\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/TermsBuilding.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.262696024503923}}
{"text": "From iris.program_logic Require Export weakestpre hoare.\nFrom iris.heap_lang Require Export lang.\nFrom iris.algebra Require Import excl agree csum.\nFrom iris.heap_lang Require Import assert proofmode notation.\nFrom iris.proofmode Require Import tactics.\nSet Default Proof Using \"Type\".\n\nDefinition one_shot_example : val := λ: <>,\n  let: \"x\" := ref NONE in (\n  (* tryset *) (λ: \"n\",\n    CAS \"x\" NONE (SOME \"n\")),\n  (* check  *) (λ: <>,\n    let: \"y\" := !\"x\" in λ: <>,\n    match: \"y\" with\n      NONE => #()\n    | SOME \"n\" =>\n       match: !\"x\" with\n         NONE => assert: #false\n       | SOME \"m\" => assert: \"n\" = \"m\"\n       end\n    end)).\n\nDefinition one_shotR := csumR (exclR unitC) (agreeR ZC).\nDefinition Pending : one_shotR := Cinl (Excl ()).\nDefinition Shot (n : Z) : one_shotR := Cinr (to_agree n).\n\nClass one_shotG Σ := { one_shot_inG :> inG Σ one_shotR }.\nDefinition one_shotΣ : gFunctors := #[GFunctor one_shotR].\nInstance subG_one_shotΣ {Σ} : subG one_shotΣ Σ → one_shotG Σ.\nProof. solve_inG. Qed.\n\nSection proof.\nLocal Set Default Proof Using \"Type*\".\nContext `{!heapG Σ, !one_shotG Σ}.\n\nDefinition one_shot_inv (γ : gname) (l : loc) : iProp Σ :=\n  (l ↦ NONEV ∗ own γ Pending ∨ ∃ n : Z, l ↦ SOMEV #n ∗ own γ (Shot n))%I.\n\nLemma wp_one_shot (Φ : val → iProp Σ) :\n  (∀ f1 f2 : val,\n    (∀ n : Z, □ WP f1 #n {{ w, ⌜w = #true⌝ ∨ ⌜w = #false⌝ }}) ∗\n    □ WP f2 #() {{ g, □ WP g #() {{ _, True }} }} -∗ Φ (f1,f2)%V)\n  ⊢ WP one_shot_example #() {{ Φ }}.\nProof.\n  iIntros \"Hf /=\". pose proof (nroot .@ \"N\") as N.\n  rewrite -wp_fupd /one_shot_example /=. wp_seq. wp_alloc l as \"Hl\". wp_let.\n  iMod (own_alloc Pending) as (γ) \"Hγ\"; first done.\n  iMod (inv_alloc N _ (one_shot_inv γ l) with \"[Hl Hγ]\") as \"#HN\".\n  { iNext. iLeft. by iSplitL \"Hl\". }\n  iModIntro. iApply \"Hf\"; iSplit.\n  - iIntros (n) \"!#\". wp_let.\n    iInv N as \">[[Hl Hγ]|H]\"; last iDestruct \"H\" as (m) \"[Hl Hγ]\".\n    + iMod (own_update with \"Hγ\") as \"Hγ\".\n      { by apply cmra_update_exclusive with (y:=Shot n). }\n      wp_cas_suc. iSplitL; last eauto.\n      iModIntro. iNext; iRight; iExists n; by iFrame.\n    + wp_cas_fail. iSplitL; last eauto.\n      rewrite /one_shot_inv; eauto 10.\n  - iIntros \"!# /=\". wp_seq. wp_bind (! _)%E.\n    iInv N as \">Hγ\".\n    iAssert (∃ v, l ↦ v ∗ ((⌜v = NONEV⌝ ∗ own γ Pending) ∨\n       ∃ n : Z, ⌜v = SOMEV #n⌝ ∗ own γ (Shot n)))%I with \"[Hγ]\" as \"Hv\".\n    { iDestruct \"Hγ\" as \"[[Hl Hγ]|Hl]\"; last iDestruct \"Hl\" as (m) \"[Hl Hγ]\".\n      + iExists NONEV. iFrame. eauto.\n      + iExists (SOMEV #m). iFrame. eauto. }\n    iDestruct \"Hv\" as (v) \"[Hl Hv]\". wp_load.\n    iAssert (one_shot_inv γ l ∗ (⌜v = NONEV⌝ ∨ ∃ n : Z,\n      ⌜v = SOMEV #n⌝ ∗ own γ (Shot n)))%I with \"[Hl Hv]\" as \"[Hinv #Hv]\".\n    { iDestruct \"Hv\" as \"[[% ?]|Hv]\"; last iDestruct \"Hv\" as (m) \"[% ?]\"; subst.\n      + Show. iSplit. iLeft; by iSplitL \"Hl\". eauto.\n      + iSplit. iRight; iExists m; by iSplitL \"Hl\". eauto. }\n    iSplitL \"Hinv\"; first by eauto.\n    iModIntro. wp_let. iIntros \"!#\". wp_seq.\n    iDestruct \"Hv\" as \"[%|Hv]\"; last iDestruct \"Hv\" as (m) \"[% Hγ']\"; subst.\n    { by wp_match. }\n    wp_match. wp_bind (! _)%E.\n    iInv N as \"[[Hl >Hγ]|H]\"; last iDestruct \"H\" as (m') \"[Hl Hγ]\".\n    { by iDestruct (own_valid_2 with \"Hγ Hγ'\") as %?. }\n    wp_load. Show.\n    iDestruct (own_valid_2 with \"Hγ Hγ'\") as %?%agree_op_invL'; subst.\n    iModIntro. iSplitL \"Hl\".\n    { iNext; iRight; by eauto. }\n    wp_match. iApply wp_assert.\n    wp_op. by case_bool_decide.\nQed.\n\nLemma ht_one_shot (Φ : val → iProp Σ) :\n  {{ True }} one_shot_example #()\n    {{ ff,\n      (∀ n : Z, {{ True }} Fst ff #n {{ w, ⌜w = #true⌝ ∨ ⌜w = #false⌝ }}) ∗\n      {{ True }} Snd ff #() {{ g, {{ True }} g #() {{ _, True }} }}\n    }}.\nProof.\n  iIntros \"!# _\". iApply wp_one_shot. iIntros (f1 f2) \"[#Hf1 #Hf2]\"; iSplit.\n  - iIntros (n) \"!# _\". wp_proj. iApply \"Hf1\".\n  - iIntros \"!# _\". wp_proj.\n    iApply (wp_wand with \"Hf2\"). by iIntros (v) \"#? !# _\".\nQed.\nEnd proof.\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/tests/one_shot.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.3738758297482025, "lm_q1q2_score": 0.26265900813168475}}
{"text": "Require Import Category.Lib.\nRequire Import Category.Theory.Category.\nRequire Import Category.Theory.Functor.\nRequire Import Category.Structure.Terminal.\nRequire Import Category.Instance.Cat.\n\nGeneralizable All Variables.\n\nProgram Definition _1@{o h p} : Category@{o h p} := {|\n  obj     := poly_unit@{o};\n  hom     := fun _ _ => poly_unit@{h};\n  homset  := Morphism_equality@{o h p};\n  id      := fun _ => ttt;\n  compose := fun _ _ _ _ _ => ttt\n|}.\nNext Obligation.\n  now destruct f.\nQed.\nNext Obligation.\n  now destruct f.\nQed.\n\nNotation \"1\" := _1 : category_scope.\n\nNotation \"one[ C ]\" := (@one Cat _ C)\n  (at level 9, format \"one[ C ]\") : object_scope.\n\n#[export]\nProgram Instance Erase `(C : Category) : C ⟶ 1 := {\n  fobj := fun _ => ttt;\n  fmap := fun _ _ _ => id\n}.\n\n#[export]\nProgram Instance Cat_Terminal : @Terminal Cat := {\n  terminal_obj := _1;\n  one := Erase\n}.\nNext Obligation.\n  constructive; auto; try exact ttt.\n  destruct (fmap[f] f0); auto.\nQed.\n", "meta": {"author": "jwiegley", "repo": "category-theory", "sha": "5376e32a4eeace4a84674820083bc2985a2a593f", "save_path": "github-repos/coq/jwiegley-category-theory", "path": "github-repos/coq/jwiegley-category-theory/category-theory-5376e32a4eeace4a84674820083bc2985a2a593f/Instance/One.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2626143108409547}}
{"text": "Require 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.i2list\n        Fiat.Common.DecideableEnsembles\n        Fiat.Common.IterateBoundedIndex\n        Fiat.Computation\n        Fiat.Narcissus.Common.Specs\n        Fiat.Narcissus.Common.ComposeOpt\n        Fiat.Narcissus.Formats.SumTypeOpt\n        Fiat.Narcissus.BinLib.AlignedByteString\n        Fiat.Narcissus.BinLib.AlignedDecoders\n        Fiat.Narcissus.BinLib.AlignWord\n        Fiat.Narcissus.BinLib.AlignedEncodeMonad\n        Fiat.Narcissus.BinLib.AlignedDecodeMonad.\n\nRequire Import\n        Bedrock.Word.\n\nSection AlignedSumType.\n\n  Context {cache : Cache}.\n  Context {cacheAddNat : CacheAdd cache nat}.\n\n  Definition align_format_sumtype\n             {m : nat}\n             {types : t Type m}\n             (align_encoders_n :\n                ilist2.ilist2 (B := fun T : Type => T -> CacheFormat -> nat) types)\n             (align_encoders_v :\n                i2list (B := fun T : Type => T -> CacheFormat -> nat)\n                       (fun (T : Type) (n : _) => forall t ce, Vector.t (word 8) (n t ce)) align_encoders_n)\n             (align_encoders_ce :\n                ilist (B := (fun T : Type => T -> CacheFormat -> CacheFormat)) types)\n             (st : SumType types)\n             (ce : CacheFormat)\n    := (existT _ _ (i2th align_encoders_v (SumType_index types st) (SumType_proj types st) ce),\n        ith align_encoders_ce (SumType_index types st) (SumType_proj types st) ce).\n\n  Lemma align_format_sumtype_OK'\n        {m : nat}\n        {types : t Type m}\n        (align_encoders_n :\n           ilist2.ilist2 (B := fun T : Type => T -> CacheFormat -> nat) types)\n        (align_encoders_v :\n           i2list (B := fun T : Type => T -> CacheFormat -> nat)\n                  (fun (T : Type) (n : _) => forall t ce, Vector.t (word 8) (n t ce)) align_encoders_n)\n        (align_encoders_ce :\n           ilist (B := (fun T : Type => T -> CacheFormat -> CacheFormat)) types)\n        (formatrs :\n           ilist (B := (fun T : Type => T -> @CacheFormat cache -> Comp (ByteString * (CacheFormat)))) types)\n        (formatrs_OK : forall idx t (ce : CacheFormat),\n            refine (ith formatrs idx t ce)\n                   (ret (build_aligned_ByteString (i2th align_encoders_v idx t ce),\n                         ith align_encoders_ce idx t ce)))\n    : forall (st : SumType types)\n             (ce : CacheFormat),\n      refine (format_SumType types formatrs st ce)\n             (ret (build_aligned_ByteString (projT2 (fst (align_format_sumtype\n                                                            align_encoders_n\n                                                            align_encoders_v\n                                                            align_encoders_ce st ce))),\n                   (snd (align_format_sumtype align_encoders_n\n                                                            align_encoders_v\n                                                            align_encoders_ce st ce)))).\n  Proof.\n    intros; unfold format_SumType, align_format_sumtype.\n    rewrite formatrs_OK; reflexivity.\n  Qed.\n\n  Corollary align_format_sumtype_OK\n            {m : nat}\n            {types : t Type m}\n            (align_encoders_n :\n               ilist2.ilist2 (B := fun T : Type => T -> CacheFormat -> nat) types)\n            (align_encoders_v :\n               i2list (B := fun T : Type => T -> CacheFormat -> nat)\n                      (fun (T : Type) (n : _) => forall t ce, Vector.t (word 8) (n t ce)) align_encoders_n)\n            (align_encoders_ce :\n               ilist (B := (fun T : Type => T -> CacheFormat -> CacheFormat)) types)\n            (formatrs :\n               ilist (B := (fun T : Type => T -> @CacheFormat cache -> Comp (ByteString * (CacheFormat)))) types)\n            (formatrs_OK : Iterate_Ensemble_BoundedIndex (fun idx => forall t (ce : CacheFormat),\n                                                              refine (ith formatrs idx t ce)\n                                                                         (ret (build_aligned_ByteString (i2th align_encoders_v idx t ce),\n                                                                               ith align_encoders_ce idx t ce))))\n    : forall (st : SumType types)\n             (ce : CacheFormat),\n      refine (format_SumType types formatrs st ce)\n             (ret (build_aligned_ByteString (projT2 (fst (align_format_sumtype align_encoders_n\n                                                                               align_encoders_v\n                                                                               align_encoders_ce st ce))),\n                   (snd (align_format_sumtype align_encoders_n\n                                              align_encoders_v\n                                              align_encoders_ce st ce)))).\n  Proof.\n    intros; eapply align_format_sumtype_OK'; intros.\n    eapply Iterate_Ensemble_BoundedIndex_equiv in formatrs_OK.\n    apply formatrs_OK.\n  Qed.\n\n  Lemma align_format_sumtype_OK_inv'\n        {m : nat}\n        {types : t Type m}\n        (A_OKs : SumType types -> Prop)\n        (align_encoders_n :\n               ilist2.ilist2 (B := fun T : Type => T -> CacheFormat -> nat) types)\n            (align_encoders_v :\n               i2list (B := fun T : Type => T -> CacheFormat -> nat)\n                      (fun (T : Type) (n : _) => forall t ce, Vector.t (word 8) (n t ce)) align_encoders_n)\n            (align_encoders_ce :\n               ilist (B := (fun T : Type => T -> CacheFormat -> CacheFormat)) types)\n        (encoders :\n           ilist (B := (fun T : Type => T -> CacheFormat -> Comp (ByteString * (CacheFormat)))) types)\n        (encoders_OK : forall idx t (ce : CacheFormat),\n            A_OKs (inj_SumType _ idx t)\n            -> refine (ith encoders idx t ce)\n                      (ret (build_aligned_ByteString (i2th align_encoders_v idx t ce),\n                            ith align_encoders_ce idx t ce)))\n    : forall (st : SumType types)\n             (ce : CacheFormat),\n      A_OKs st\n      -> refine (format_SumType types encoders st ce)\n                (ret (build_aligned_ByteString (projT2 (fst (align_format_sumtype align_encoders_n\n                                                                               align_encoders_v\n                                                                               align_encoders_ce st ce))),\n                      (snd (align_format_sumtype align_encoders_n\n                                                 align_encoders_v\n                                                 align_encoders_ce st ce)))).\n  Proof.\n    intros; unfold format_SumType, align_format_sumtype.\n    rewrite encoders_OK; eauto.\n    reflexivity.\n    rewrite inj_SumType_proj_inverse; eauto.\n  Qed.\n\n  Corollary align_format_sumtype_OK_inv\n            {m : nat}\n            {types : t Type m}\n            (A_OKs : SumType types -> Prop)\n            (align_encoders_n :\n               ilist2.ilist2 (B := fun T : Type => T -> CacheFormat -> nat) types)\n            (align_encoders_v :\n               i2list (B := fun T : Type => T -> CacheFormat -> nat)\n                      (fun (T : Type) (n : _) => forall t ce, Vector.t (word 8) (n t ce)) align_encoders_n)\n            (align_encoders_ce :\n               ilist (B := (fun T : Type => T -> CacheFormat -> CacheFormat)) types)\n            (encoders :\n               ilist (B := (fun T : Type => T -> CacheFormat -> Comp (ByteString * (CacheFormat)))) types)\n            (encoders_OK : Iterate_Ensemble_BoundedIndex\n                             (fun idx => forall t (ce : CacheFormat),\n                                  A_OKs (inj_SumType _ idx t)\n                                  -> refine (ith encoders idx t ce)\n                                            (ret (build_aligned_ByteString (i2th align_encoders_v idx t ce),\n                                                  ith align_encoders_ce idx t ce))))\n    : forall (st : SumType types)\n             (ce : CacheFormat),\n      A_OKs st\n      -> refine (format_SumType types encoders st ce)\n                (ret (build_aligned_ByteString (projT2 (fst (align_format_sumtype align_encoders_n\n                                                                               align_encoders_v\n                                                                               align_encoders_ce st ce))),\n                      (snd (align_format_sumtype align_encoders_n\n                                                 align_encoders_v\n                                                 align_encoders_ce st ce)))).\n  Proof.\n    intros; eapply align_format_sumtype_OK_inv'; intros.\n    eapply Iterate_Ensemble_BoundedIndex_equiv in encoders_OK.\n    apply encoders_OK; eauto.\n    eauto.\n  Qed.\n\n  Lemma AlignedFormatSumTypeDoneC\n            {m : nat}\n            {types : t Type m}\n            (A_OKs_l : ilist (B := fun T : Type => T -> Prop) types)\n            (A_OKs : SumType types -> Prop := fun st => ith A_OKs_l (SumType_index _ st) (SumType_proj _ st))\n            (align_encoders_n :\n               ilist2.ilist2 (B := fun T : Type => T -> CacheFormat -> nat) types)\n            (align_encoders_v :\n               i2list (B := fun T : Type => T -> CacheFormat -> nat)\n                      (fun (T : Type) (n : _) => forall t ce, Vector.t (word 8) (n t ce)) align_encoders_n)\n            (align_encoders_ce :\n               ilist (B := (fun T : Type => T -> CacheFormat -> CacheFormat)) types)\n            (encoders :\n               ilist (B := (fun T : Type => T -> CacheFormat -> Comp (ByteString * (CacheFormat)))) types)\n            (encoders_OK : Iterate_Ensemble_BoundedIndex\n                             (fun idx => forall t (ce : CacheFormat),\n                                  A_OKs (inj_SumType _ idx t)\n                                  -> refine (ith encoders idx t ce)\n                                            (ret (build_aligned_ByteString (i2th align_encoders_v idx t ce),\n                                                  ith align_encoders_ce idx t ce))))\n    : forall (st : SumType types)\n             (ce : CacheFormat),\n      A_OKs st\n      -> refine (((format_SumType types encoders st) DoneC) ce)\n                (ret (build_aligned_ByteString (projT2 (fst (align_format_sumtype align_encoders_n\n                                                                                  align_encoders_v\n                                                                                  align_encoders_ce st ce))),\n                      (snd (align_format_sumtype align_encoders_n\n                                                 align_encoders_v\n                                                 align_encoders_ce st ce)))).\n  Proof.\n    intros.\n    etransitivity.\n    eapply AlignedFormatDoneC.\n    rewrite (align_format_sumtype_OK_inv A_OKs); try eassumption.\n    instantiate (2 := fun ce => fst (align_format_sumtype align_encoders_n align_encoders_v align_encoders_ce st ce)).\n    instantiate (1 := fun ce => snd (align_format_sumtype align_encoders_n align_encoders_v align_encoders_ce st ce)).\n    simpl; reflexivity.\n    simpl; reflexivity.\n  Qed.\n\n  Definition AlignedEncodeSumType\n             {m : nat}\n             {types : t Type m}\n             (aligned_encoders :\n                  ilist (B := fun T : Type => forall sz, AlignedEncodeM (S := T) sz) types)\n    : forall sz, AlignedEncodeM (S := SumType types) sz :=\n    fun sz v idx st env => ith aligned_encoders (SumType_index types st) sz v idx (SumType_proj types st) env.\n\n  Lemma CorrectAlignedEncoderForFormatSumType'\n            {m : nat}\n            {types : t Type m}\n            (formats : ilist types)\n            (aligned_encoders :\n                  ilist (B := fun T : Type => forall sz, AlignedEncodeM (S := T) sz) types)\n            (encoders_OK :\n               forall idx,\n                 CorrectAlignedEncoder (ith formats idx) (ith aligned_encoders idx))\n    : CorrectAlignedEncoder (format_SumType types formats)\n                            (AlignedEncodeSumType aligned_encoders).\n  Proof.\n    unfold CorrectAlignedEncoder; intros.\n    eexists (fun st => projT1 (encoders_OK (SumType_index types st)) (SumType_proj types st)).\n    split; [ | split]; intros.\n    - pose proof (projT2 (encoders_OK (SumType_index types s))); simpl in *; destruct H.\n      specialize (H (SumType_proj types s) env); intuition.\n    - pose proof (projT2 (encoders_OK (SumType_index types s))); simpl in *; destruct H0.\n      specialize (H0 (SumType_proj types s) env); intuition.\n      specialize (H0 (SumType_proj types s) env); intuition eauto.\n    - unfold EncodeMEquivAlignedEncodeM; intros.\n      pose proof (projT2 (encoders_OK (SumType_index types s))); simpl in *; destruct H.\n      unfold EncodeMEquivAlignedEncodeM in H0; intuition eauto;\n        specialize (H2 env (SumType_proj types s) idx); intuition eauto;\n          specialize (H2 t env' _ v); specialize (H5 t env'); eauto.\n  Qed.\n\n  Lemma CorrectAlignedEncoderForFormatSumType\n            {m : nat}\n            {types : t Type m}\n            (formats : ilist types)\n            (aligned_encoders :\n                  ilist (B := fun T : Type => forall sz, AlignedEncodeM (S := T) sz) types)\n            (encoders_OK :\n               Iterate_Dep_Type_BoundedIndex\n                 (fun idx =>\n                 CorrectAlignedEncoder (ith formats idx) (ith aligned_encoders idx)))\n    : CorrectAlignedEncoder (format_SumType types formats)\n                            (AlignedEncodeSumType aligned_encoders).\n  Proof.\n    intros; eapply CorrectAlignedEncoderForFormatSumType'.\n    eapply Lookup_Iterate_Dep_Type; eauto.\n  Qed.\n\n  Definition SumTypeAlignedDecodeM {n m}\n           {types : Vector.t Type (S n)}\n           (aligned_decoders :\n              ilist (B := fun T => forall n, AlignedDecodeM T n) types)\n           (idx : Fin.t (S n))\n    : AlignedDecodeM (SumType types) m :=\n    (fun v idx' cd => `(i, bs, cd') <- (ith aligned_decoders idx _ v idx' cd);\n     Ok (inj_SumType types idx i, bs, cd')).\n\n  Lemma AlignedDecodeSumTypeM {C : Type}\n        {n}\n        {types : Vector.t Type (S n)}\n        (decoders : ilist (B := fun T => ByteString -> CacheDecode -> Hopefully (T * ByteString * CacheDecode)) types)\n        (aligned_decoders :\n           ilist (B := fun T => forall n, AlignedDecodeM T n) types)\n        (idx : Fin.t (S n))\n    : forall (t : SumType types -> DecodeM (C * _) ByteString)\n             (t' : SumType types -> forall {numBytes}, AlignedDecodeM C numBytes),\n      (Iterate_Ensemble_BoundedIndex (fun idx =>\n                                        DecodeMEquivAlignedDecodeM (ith decoders idx) (ith aligned_decoders idx)))\n      -> (forall b, DecodeMEquivAlignedDecodeM (t b) (@t' b))\n      -> DecodeMEquivAlignedDecodeM\n           (fun v cd => `(l, bs, cd') <- decode_SumType types decoders idx v cd;\n                          t l bs cd')\n           (fun numBytes => l <- SumTypeAlignedDecodeM aligned_decoders idx;\n                            t' l)%AlignedDecodeM%list.\n  Proof.\n    intros.\n    eapply Bind_DecodeMEquivAlignedDecodeM; eauto.\n    apply (proj1 (Iterate_Ensemble_BoundedIndex_equiv _)) with (idx0 := idx) in H.\n    unfold decode_SumType, SumTypeAlignedDecodeM.\n    eapply DecodeMEquivAlignedDecodeM_trans; simpl; intros.\n    eapply Bind_DecodeMEquivAlignedDecodeM; eauto.\n    2: { simpl. destruct (ith decoders idx b cd) as [((?&?)&?)|]; eauto; simpl.\n         constructor; left. \n         higher_order_reflexivity. }\n    2: simpl; unfold AlignedDecodeMEquiv; simpl; intros.\n    intros.\n    eapply DecodeMEquivAlignedDecodeM_trans; simpl; intros.\n    eapply Return_DecodeMEquivAlignedDecodeM.\n    higher_order_reflexivity.\n    apply AlignedDecodeMEquiv_refl.\n    unfold BindAlignedDecodeM, DecodeBindOpt2, BindOpt.\n    destruct (ith aligned_decoders idx n0 v idx0 c); simpl; eauto.\n    destruct p as [ [? ?] ?]; reflexivity.\n  Qed.\n\nEnd AlignedSumType.\n\nArguments align_format_sumtype : simpl never.\nArguments SumType_proj : simpl never.\nArguments SumType_index : simpl never.\n", "meta": {"author": "scuellar", "repo": "narcissus_errors", "sha": "8c547389030165e8620b43bb38ad87b9b65e5471", "save_path": "github-repos/coq/scuellar-narcissus_errors", "path": "github-repos/coq/scuellar-narcissus_errors/narcissus_errors-8c547389030165e8620b43bb38ad87b9b65e5471/src/Narcissus/BinLib/AlignedSumType.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757645879592641, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2626143006904203}}
{"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 A B C Aprime Bprime Cprime O X Y M : Universe, ((wd_ B O /\\ (wd_ A O /\\ (wd_ C O /\\ (wd_ Bprime O /\\ (wd_ Aprime O /\\ (wd_ Cprime O /\\ (wd_ X Y /\\ (wd_ A Aprime /\\ (wd_ A M /\\ (wd_ Aprime X /\\ (wd_ A B /\\ (wd_ Aprime B /\\ (wd_ Bprime A /\\ (wd_ Bprime B /\\ (wd_ Aprime Cprime /\\ (wd_ Aprime Bprime /\\ (wd_ A Cprime /\\ (wd_ B C /\\ (wd_ Bprime Cprime /\\ (wd_ A C /\\ (wd_ Aprime C /\\ (wd_ C Cprime /\\ (col_ O A Aprime /\\ (col_ O B Bprime /\\ (col_ O C Cprime /\\ (col_ A X Y /\\ (col_ Aprime X Y /\\ (col_ M X Y /\\ col_ M O C)))))))))))))))))))))))))))) -> col_ Aprime X A)).\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_1006.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.26249688716336883}}
{"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(*          Refinement proof for MALInit layer                         *)\n(*                                                                     *)\n(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)\n(*                                                                     *)\n(*          Yale Flint Group                                           *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** This file provide the contextual refinement proof between MBoot layer and MALInit layer*)\nRequire Import BootGenDef.\nRequire Import BootGenLemma.\nRequire Import BootGenAccessorDef.\nRequire Import GuestAccessIntelRef0.\n\n(** * Definition of the refinement relation*)\nSection Refinement.\n\n  Section WITHMEM.\n\n    Context `{Hstencil: Stencil}.\n    Context `{Hmem: Mem.MemoryModel}.\n    Context `{Hmwd: UseMemWithData mem}.\n\n    Ltac pattern2_refinement_simpl:=  \n      pattern2_refinement_simpl' (@relate_AbData).\n\n    Notation hStore := (fun F V => exec_storeex1 (flatmem_store := flatmem_store') (F:=F) (V:=V)).\n\n    Notation lStore := (fun F V => exec_storeex0 (F:=F) (V:=V)).\n\n    Require Import XOmega.\n    Require Import HostAccess0.\n    Require Import HostAccess1.\n    Require Import LoadStoreGeneral.\n\n    Opaque align_chunk Z.mul Z.div Z.sub. \n\n    Lemma exec_flatmem_store_correct0:\n      forall {F V: Type} (ge2: Genv.t F V) (s: stencil) ι (m1 m2 m1': mem) rs1 rs2 rs1' (d1 d1': HDATAOps) d2 r chunk n ds,\n        exec_flatmem_store (flatmem_store:= flatmem_store') chunk (m1, d1) n rs1 r ds =\n        Next rs1' (m1', d1') ->\n        MatchPrimcallStates (one_crel (CompatRelOps0:= rel_ops) HDATAOps LDATAOps) s ι rs1 m1 d1 rs2 m2 d2 ->\n        stencil_matches s ge2 ->\n        0<= n <= adr_max - size_chunk chunk ->\n        (align_chunk chunk | n) ->\n        exists rs2' m2' d2',\n          Asm.exec_store (mem:= mwd LDATAOps) ge2 chunk (m2, d2)\n                         (Addrmode None None (inr (FlatMem_LOC, Int.repr n)))\n                         rs2 r ds = Next rs2' (m2', d2') /\\\n          MatchPrimcallStates (one_crel (CompatRelOps0:= rel_ops) HDATAOps LDATAOps) s ι rs1' m1' d1' rs2' m2' d2'.\n    Proof.\n      intros. inv H0. pose proof match_extcall_states as Hmatch_ext.\n      inv match_extcall_states.\n      inv match_match. inv H0.\n      pose proof H3 as Hmatch.\n      unfold Asm.exec_store. simpl.\n      assert (Hsym': Genv.find_symbol ge2 FlatMem_LOC = Some b).\n      {\n        inv H1. congruence.\n      }\n      unfold symbol_offset. rewrite Hsym'. simpl.\n      Opaque Z.sub.\n      lift_trivial.\n      repeat rewrite Int.add_zero.\n      unfold exec_flatmem_store in *.\n      assert (HOS1: n + size_chunk chunk <= adr_max).\n      {\n        revert H2; clear; intros.\n        Transparent Z.sub.\n        omega.\n      }\n      assert (HOS2: n >= 0) by omega.\n      pose proof (size_chunk_pos chunk) as HOS3.\n      rewrite Int.unsigned_repr; [|rewrite_omega].\n      subdestruct.\n      exploit (flatmem_store_correct0 (rs1 r) (rs2 r)); eauto.\n      intros (m2' & Hstore & Hmatch_ext').\n      rewrite Hstore. unfold set; simpl. inv H.\n      refine_split'; eauto 1.\n      constructor; eauto.\n      val_inject_simpl.\n    Qed.\n\n    Opaque Z.sub.\n\n    Lemma store_correct:\n      store_accessor_sim_def HDATAOps LDATAOps (one_crel HDATAOps LDATAOps) hStore lStore.\n    Proof.\n      unfold store_accessor_sim_def. intros.\n      pose proof H2 as Hmatch.\n      inv H2. inv match_extcall_states.\n\n      unfold exec_storeex1 in *. \n      unfold exec_storeex0. \n      unfold exec_host_store0, exec_host_store1 in *.\n      unfold exec_host_store_snd0.\n      inv H4.\n      exploit (eval_addrmode_correct ge1 ge2 a); eauto. simpl; intros HW.\n      simpl in *; revert H1.\n      inv match_related. subrewrite''. intros HLoad.\n      destruct (eval_addrmode ge1 a rs1) eqn: H1; contra_inv.\n      - (* addr is Vint*)\n        inv HW. \n        destruct (ihost d2) eqn: HPH; contra_inv.\n        destruct (pg d2) eqn: HPE; contra_inv.        \n        + (* host *)\n          destruct (CR3 d2); contra_inv.\n          destruct (Genv.find_symbol ge1 b) eqn:Hsymol; contra_inv.\n          assert (HFB: Genv.find_symbol ge2 b = Some b0).\n          {\n            inv H. inv H0. congruence.\n          }\n          rewrite HFB. \n          revert HLoad. lift_trivial. intros HLoad.\n          exploit (stencil_find_symbol_inject (ge:= ge1)); eauto. intros HF0.\n          destruct (Mem.load Mint32 m1 b0 (Int.unsigned (Int.repr (Int.unsigned ofs + PDX (Int.unsigned i) * 4))))\n                   eqn: HLD; contra_inv.\n          exploit Mem.load_inject; eauto.\n          rewrite Z.add_0_r; intros [v1[HLD1 HVAL]].\n          rewrite HLD1. clear HLD HLD1.\n          destruct v; contra_inv. inv HVAL.\n          inv match_match. inv H2.\n          assert (HFB': Genv.find_symbol ge2 FlatMem_LOC = Some b1).\n          {\n            inv H. inv H0. congruence.\n          }\n          rewrite HFB'.\n          destruct (FlatMem.load Mint32 (HP d1)\n                                 (Int.unsigned i0 / 4096 * 4096 + PTX (Int.unsigned i) * 4))\n                   eqn: HLD; contra_inv.\n          pose proof (PTX_Addr_range i0 i) as HPTX_Range.\n          pose proof (PTX_Addr_divide i0 i) as HPTX_Divide.\n          exploit flatmem_load_correct0; eauto.\n          simpl; lift_trivial.\n          intros (v' & HLD' & HVAL). inv HVAL.\n          pose proof (PTX_Addr_range' i0 i) as HPTX_Range'.\n          rewrite Int.unsigned_repr; trivial.\n          rewrite HLD'.\n          destruct (zle (Int.unsigned i mod 4096) (4096 - size_chunk chunk)); contra_inv.\n          destruct (Zdivide_dec (align_chunk chunk) (Int.unsigned i mod 4096)\n                                (Memdata.align_chunk_pos chunk)); contra_inv.\n          pose proof (PTADDR_range (Int.unsigned i) i1 chunk l) as HOS1.\n          pose proof (PTADDR_divide (Int.unsigned i) i1 chunk d) as HOS2.\n          subdestruct.\n          * eapply exec_flatmem_store_correct0; eauto 1.\n          * eapply exec_flatmem_store_correct0; eauto 1.\n          * eapply pagefault_correct; eauto.\n        + eapply guest_intel_correct1; eauto.\n          unfold GuestAccessIntel1.store_accessor1, GuestAccessIntel0.store_accessor0. \n          intros. subdestruct.\n          eapply exec_flatmem_store_correct0; eauto 1.\n          * eapply PTADDR_range; assumption.\n          * eapply PTADDR_divide; assumption.  \n\n      - (* adr is (b,ofs) *)\n        inv HW; subdestruct; eapply storel_correct; eauto.\n    Qed.\n\n  End WITHMEM.\n\nEnd Refinement.", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/mm/BootGenAccessor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.26242636629463023}}
{"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 ASTExtra.\nRequire Import Constant.\n\nRequire Import liblayers.compat.CompatGenSem.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import CommonTactic.\nRequire Import RefinementTactic.\nRequire Import Observation.\n\nSection OBJ_FLATMEM.\n\n  Local Open Scope Z_scope.\n\n  (** primitve: store to the heap*)\n  Function flatmem_store' (adt: RData) (chunk: memory_chunk) (addr: Z) (v: val): option RData :=\n    Some adt {HP: FlatMem.store chunk (HP adt) addr v}.\n\n  Function flatmem_store (adt: RData) (chunk: memory_chunk) (addr: Z) (v: val): option RData :=\n    match ZMap.get (PageI addr) (pperm adt) with\n      | PGAlloc => Some adt {HP: FlatMem.store chunk (HP adt) addr v}\n      | _ => None\n    end.\n  \n  (** primitve: store to the heap*)\n  Function fstore'_spec (addr v: Z) (adt: RData): option RData :=\n    match (ikern adt, ihost adt) with\n      | (true, true) => \n        if zle_lt 0 addr adr_low then\n          flatmem_store' adt Mint32 (addr * 4) (Vint (Int.repr v))\n        else None\n      | _ => None\n    end.\n\n  Function fstore0_spec (addr v: Z) (adt: RData): option RData :=\n    match (ikern adt, ihost adt) with\n      | (true, true) => \n        if zle_lt 0 addr adr_low then\n          flatmem_store adt Mint32 (addr * 4) (Vint (Int.repr v))\n        else None\n      | _ => None\n    end.\n\n  Function fstore_spec (addr v: Z) (adt: RData): option RData :=\n    match (ikern adt, ihost adt, ipt adt) with\n      | (true, true, true) => \n        if zle_lt 0 addr adr_low then\n          flatmem_store adt Mint32 (addr * 4) (Vint (Int.repr v))\n        else None\n      | _ => None\n    end.\n\n  Function fload'_spec (addr: Z) (adt: RData): option Z :=\n    match (ikern adt, ihost adt) with\n      | (true, true) => \n        if zle_lt 0 addr adr_low then\n          match FlatMem.load Mint32 (HP adt) (addr * 4) with\n            | Vint n => Some (Int.unsigned n)\n            | _ => None\n          end\n        else None\n      | _ => None\n    end.\n\n  Function fload_spec (addr: Z) (adt: RData): option Z :=\n    match (ikern adt, ihost adt, ipt adt) with\n      | (true, true, true) => \n        if zle_lt 0 addr adr_low then\n          match (ZMap.get (PageI (addr * 4)) (pperm adt),\n                 FlatMem.load Mint32 (HP adt) (addr * 4)) with\n            | (PGAlloc, Vint n) => Some (Int.unsigned n)\n            | _ => None\n          end\n        else None\n      | _ => None\n    end.\n\n  Fixpoint flatmem_copy_aux (n: nat) (from to: Z) (h: flatmem) :=\n    match n with\n      | O => Some h\n      | S n' =>\n        match FlatMem.load Mint32 h from with\n          | Vint v => \n            flatmem_copy_aux n' (from + 4) (to + 4)  (FlatMem.store Mint32 h to (Vint v))\n          | _ => None\n        end\n    end.\n\n  Section COPY_INV.\n\n    Lemma PageI_monotonic:\n      forall a b,\n        a <= b ->\n        PageI a <= PageI b.\n    Proof.\n      unfold PageI.\n      intros. eapply Z_div_le; eauto.\n      omega.\n    Qed.\n\n    Lemma PageI_range:\n      forall a b c,\n        a <= b <= c->\n        PageI a = PageI c ->\n        PageI b = PageI a.\n    Proof.\n      intros.\n      assert (HR1: PageI a <= PageI b) by (eapply PageI_monotonic; try omega).\n      assert (HR2: PageI b <= PageI c) by (eapply PageI_monotonic; try omega).\n      omega.\n    Qed.\n\n    Lemma to_range:\n      forall to n,\n        to <= to + 4 <= to + Z.of_nat (S (n + 1)) * 4 - 4.\n    Proof.\n      intros.\n      erewrite Nat2Z.inj_succ.\n      replace ((n + 1)%nat) with (S n) by omega. \n      erewrite Nat2Z.inj_succ.\n      pose proof (Nat2Z.is_nonneg n).\n      omega.\n    Qed.\n\n    Lemma to_mod_le:\n      forall to,\n        (4 | to) ->\n        to mod 4096 <= 4092.\n    Proof.\n      intros.\n      destruct H as (i & He).\n      subst.\n      change 4096 with (4 * 1024) in *.\n      replace (i * 4) with (4 * i) by omega.\n      rewrite Zmult_mod_distr_l in *.\n      assert (i mod 1024 < 1024).\n      {\n        eapply Z_mod_lt. omega.\n      }        \n      omega.\n    Qed.\n\n    Lemma to_add_divide:\n      forall to,\n        (4 | to) ->\n        (4 | to + 4).\n    Proof.\n      intros.\n      destruct H as (i & He).\n      subst.\n      exists (i + 1). omega.\n    Qed.\n\n    Lemma PageI_eq:\n      forall to n,\n        PageI to = PageI (to + Z.of_nat (S (n + 1)) * 4 - 4) ->\n        PageI (to + 4) = PageI (to + 4 + Z.of_nat (n + 1) * 4 - 4).\n    Proof.\n      intros. \n      rewrite Nat2Z.inj_succ in H.\n      replace ((n + 1)%nat) with (S n) in * by omega.\n      rewrite Nat2Z.inj_succ in *.\n      pose proof (Nat2Z.is_nonneg n).      \n      erewrite (PageI_range to (to + 4 + Z.succ (Z.of_nat n) * 4 - 4)); eauto.\n      erewrite (PageI_range to (to + 4)); eauto.\n      omega.\n      omega.\n    Qed.\n\n    Lemma dirty_ppage_gss_copy_plus:\n      forall n h h' pp from to,\n        ZMap.get (PageI to) pp = PGAlloc ->\n        (4 | to) ->\n        PageI to = PageI (to + (Z.of_nat (n + 1)) * 4 - 4) ->\n        dirty_ppage pp h ->\n        flatmem_copy_aux (n + 1) from to h = Some h' ->\n        dirty_ppage pp h'.\n    Proof.\n      intros until n.\n      induction n.\n      - simpl; intros. \n        subdestruct. inv H3.\n        eapply dirty_ppage_store_unmaped'; eauto.\n        eapply to_mod_le; eauto.\n      - simpl; intros. subdestruct.\n        eapply (IHn (FlatMem.store Mint32 h to (Vint i)));\n          try eapply H3.        \n        + erewrite PageI_range; eauto.\n          eapply to_range.\n        + apply to_add_divide; eauto.\n        + eapply PageI_eq; eauto.\n        + eapply dirty_ppage_store_unmaped'; eauto.\n          eapply to_mod_le; eauto.\n    Qed.\n\n    Lemma PageI_divide':\n      forall to n,\n        (4096 | to) ->\n        1 <= n <= 1024 ->\n        PageI to = PageI (to + n * 4 - 4).\n    Proof.\n      intros. destruct H as (i & He). subst.\n      unfold PageI.\n      assert (4096 > 0) by omega.\n      replace (i * 4096 + n * 4 - 4)\n      with (n * 4 - 4 + i * 4096) by omega.\n      rewrite Z_div_plus; trivial.\n      rewrite Z_div_mult; trivial.\n      rewrite Zdiv_small; trivial.\n      omega.\n    Qed.\n\n    Lemma PageI_divide:\n      forall to n,\n        (4096 | to) ->\n        Z.of_nat (n + 1) <= 1024 ->\n        PageI to = PageI (to + Z.of_nat (n + 1) * 4 - 4).\n    Proof.\n      intros. eapply PageI_divide'; eauto. \n      replace ((n + 1)%nat) with (S n) in * by omega.\n      rewrite Nat2Z.inj_succ in *.\n      pose proof (Nat2Z.is_nonneg n).      \n      omega.\n    Qed.\n\n    Lemma dirty_ppage_gss_copy':\n      forall n h h' pp from to,\n        ZMap.get (PageI to) pp = PGAlloc ->\n        (PgSize | to)  ->\n        Z.of_nat n <= one_k ->\n        dirty_ppage pp h ->\n        flatmem_copy_aux n from to h = Some h' ->\n        dirty_ppage pp h'.\n    Proof.\n      destruct n; intros.\n      - simpl in *. inv H3. assumption.\n      - replace (S n) with ((n + 1)%nat) in * by omega.\n        eapply dirty_ppage_gss_copy_plus; eauto.\n        destruct H0 as (i & He).\n        exists (i * 1024).\n        subst. omega.\n        eapply PageI_divide; eauto.\n    Qed.\n\n    Lemma dirty_ppage_gss_copy:\n      forall n h h' pp from to,\n        flatmem_copy_aux (Z.to_nat n) from to h = Some h' ->\n        ZMap.get (PageI to) pp = PGAlloc ->\n        (PgSize | to)  ->\n        0 <= n <= one_k ->\n        dirty_ppage pp h ->\n        dirty_ppage pp h'.\n    Proof.\n      intros.\n      eapply dirty_ppage_gss_copy'; eauto.\n      rewrite Z2Nat.id; try omega.\n    Qed.\n\n  End COPY_INV.\n\n  Function flatmem_copy'_spec (count: Z) (from to: Z) (adt: RData) :=\n    match (ikern adt, ihost adt) with\n      | (true, true) => \n        if zle_lt 0 to adr_low then\n          if zle_lt 0 from adr_low then\n            if zle_le 0 count one_k then\n              if Zdivide_dec PgSize to HPS then\n                if Zdivide_dec PgSize from HPS then\n                  match flatmem_copy_aux (Z.to_nat count) from to (HP adt) with\n                    | Some h => Some adt {HP: h}\n                    | _ => None\n                  end\n                else None\n              else None\n            else None\n          else None\n        else None\n      | _ => None\n    end.\n\n  Function flatmem_copy0_spec (count: Z) (from to: Z) (adt: RData) :=\n    match (ikern adt, ihost adt) with\n      | (true, true) => \n        if zle_lt 0 to adr_low then\n          if zle_lt 0 from adr_low then\n            if zle_le 0 count one_k then\n              if Zdivide_dec PgSize to HPS then\n                if Zdivide_dec PgSize from HPS then\n                  \n                  match (ZMap.get (PageI from) (pperm adt), ZMap.get (PageI to) (pperm adt)) with\n                    | (PGAlloc, PGAlloc) => \n                      match flatmem_copy_aux (Z.to_nat count) from to (HP adt) with\n                        | Some h => Some adt {HP: h}\n                        | _ => None\n                      end\n                    | _ => None\n                  end\n                else None\n              else None\n            else None\n          else None\n        else None\n      | _ => None\n    end.\n \n  Function flatmem_copy_spec (count: Z) (from to: Z) (adt: RData) :=\n    match (ikern adt, ihost adt, ipt adt) with\n      | (true, true, true) => \n        if zle_lt 0 to adr_low then\n          if zle_lt 0 from adr_low then\n            if zle_le 0 count one_k then\n              if Zdivide_dec PgSize to HPS then\n                if Zdivide_dec PgSize from HPS then\n                  \n                  match (ZMap.get (PageI from) (pperm adt), ZMap.get (PageI to) (pperm adt)) with\n                    | (PGAlloc, PGAlloc) => \n                      match flatmem_copy_aux (Z.to_nat count) from to (HP adt) with\n                        | Some h => Some adt {HP: h}\n                        | _ => None\n                      end\n                    | _ => None\n                  end\n                else None\n              else None\n            else None\n          else None\n        else None\n      | _ => None\n    end.\n\nEnd OBJ_FLATMEM.\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\n  Section FSTORE'_SIM.\n\n    Context {re2: relate_impl_HP}.\n  \n    Lemma flatmem_store'_exists:\n      forall s hadt ladt hadt' t addr v v' f,\n        flatmem_store' hadt t addr v = Some hadt'\n        -> relate_AbData s f hadt ladt\n        -> val_inject f v v'\n        -> exists ladt',\n             flatmem_store' ladt t addr v' = Some ladt'\n             /\\ relate_AbData s f hadt' ladt'.\n    Proof.\n      unfold flatmem_store'. intros.\n      revert H. subrewrite. inv HQ.\n      refine_split'; eauto.\n      eapply relate_impl_HP_update; eauto.\n      eapply (FlatMem.store_mapped_inj f); trivial.\n      eapply relate_impl_HP_eq; eauto. assumption.\n    Qed.\n\n    Context {re1: relate_impl_iflags}.\n\n    Lemma fstore'_exist:\n      forall s habd habd' labd i v f,\n        fstore'_spec i v habd = Some habd'\n        -> relate_AbData s f habd labd\n        -> exists labd', fstore'_spec i v labd = Some labd' \n                         /\\ relate_AbData s f habd' labd'.\n    Proof.\n      unfold fstore'_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.         \n      revert H. subrewrite. \n      subdestruct. eapply flatmem_store'_exists; eauto.\n    Qed.\n\n    Context {mt1: match_impl_HP}.\n\n    Lemma fstore'_match:\n      forall s d d' m i v f,\n        fstore'_spec i v d = Some d'\n        -> match_AbData s d m f\n        -> match_AbData s d' m f.\n    Proof.\n      unfold fstore'_spec, flatmem_store'; intros. subdestruct.\n      inv H. eapply match_impl_HP_update. assumption.\n    Qed.\n\n    Context {inv: PreservesInvariants (HD:= data) fstore'_spec}.\n    Context {inv0: PreservesInvariants (HD:= data0) fstore'_spec}.\n\n    Lemma fstore'_sim :\n      forall id,\n        sim (crel RData RData) (id ↦ gensem fstore'_spec)\n            (id ↦ gensem fstore'_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl (@match_AbData). intros.\n      exploit fstore'_exist; eauto 1; intros [labd' [HP HM]].\n      match_external_states_simpl.\n      eapply fstore'_match; eauto.\n    Qed.\n\n  End FSTORE'_SIM.\n\n  Section FSTORE0_SIM.\n\n    Context {re1: relate_impl_HP}.\n    Context {re2: relate_impl_pperm}.\n\n    Lemma flatmem_store_exists:\n      forall s hadt ladt hadt' t addr v v' f,\n        flatmem_store hadt t addr v = Some hadt'\n        -> relate_AbData s f hadt ladt\n        -> val_inject f v v'\n        -> exists ladt',\n             flatmem_store ladt t addr v' = Some ladt'\n             /\\ relate_AbData s f hadt' ladt'.\n    Proof.\n      unfold flatmem_store. intros.\n      exploit relate_impl_pperm_eq; eauto. intros. \n      revert H. subrewrite. subdestruct. inv HQ.\n      refine_split'; eauto.\n      eapply relate_impl_HP_update; eauto.\n      eapply (FlatMem.store_mapped_inj f); trivial.\n      eapply relate_impl_HP_eq; eauto. assumption.\n    Qed.\n\n    Context {re3: relate_impl_iflags}.\n\n    Lemma fstore0_exist:\n      forall s habd habd' labd i v f,\n        fstore0_spec i v habd = Some habd'\n        -> relate_AbData s f habd labd\n        -> exists labd', fstore0_spec i v labd = Some labd' \n                         /\\ relate_AbData s f habd' labd'.\n    Proof.\n      unfold fstore0_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.\n      revert H. subrewrite. \n      subdestruct. eapply flatmem_store_exists; eauto.\n    Qed.\n\n    Context {mt1: match_impl_HP}.\n\n    Lemma flatmem_store_match:\n      forall s d d' m i v t f,\n        flatmem_store d t i v = Some d'\n        -> match_AbData s d m f\n        -> match_AbData s d' m f.\n    Proof.\n      unfold flatmem_store; intros. subdestruct.\n      inv H. eapply match_impl_HP_update. assumption.\n    Qed.\n\n    Lemma fstore0_match:\n      forall s d d' m i v f,\n        fstore0_spec i v d = Some d'\n        -> match_AbData s d m f\n        -> match_AbData s d' m f.\n    Proof.\n      unfold fstore0_spec, flatmem_store; intros. subdestruct.\n      inv H. eapply match_impl_HP_update. assumption.\n    Qed.\n\n    Context {inv: PreservesInvariants (HD:= data) fstore0_spec}.\n    Context {inv0: PreservesInvariants (HD:= data0) fstore0_spec}.\n\n    Lemma fstore0_sim :\n      forall id,\n        sim (crel RData RData) (id ↦ gensem fstore0_spec)\n            (id ↦ gensem fstore0_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl (@match_AbData). intros.\n      exploit fstore0_exist; eauto 1; intros [labd' [HP HM]].\n      match_external_states_simpl.\n      eapply fstore0_match; eauto.\n    Qed.\n\n  End FSTORE0_SIM.\n\n  Section FSTORE_SIM.\n\n    Context {re1: relate_impl_HP}.\n    Context {re2: relate_impl_pperm}.\n    Context {re3: relate_impl_iflags}.\n    Context {re4: relate_impl_ipt}.\n\n    Lemma fstore_exist:\n      forall s habd habd' labd i v f,\n        fstore_spec i v habd = Some habd'\n        -> relate_AbData s f habd labd\n        -> exists labd', fstore_spec i v labd = Some labd' \n                         /\\ relate_AbData s f habd' labd'.\n    Proof.\n      unfold fstore_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.         \n      exploit relate_impl_ipt_eq; eauto. intros.\n      revert H. subrewrite. \n      subdestruct. eapply flatmem_store_exists; eauto.\n    Qed.\n\n    Context {mt1: match_impl_HP}.\n\n    Lemma fstore_match:\n      forall s d d' m i v f,\n        fstore_spec i v d = Some d'\n        -> match_AbData s d m f\n        -> match_AbData s d' m f.\n    Proof.\n      unfold fstore_spec, flatmem_store; intros. subdestruct.\n      inv H. eapply match_impl_HP_update. assumption.\n    Qed.\n\n    Context {inv: PreservesInvariants (HD:= data) fstore_spec}.\n    Context {inv0: PreservesInvariants (HD:= data0) fstore_spec}.\n\n    Lemma fstore_sim :\n      forall id,\n        sim (crel RData RData) (id ↦ gensem fstore_spec)\n            (id ↦ gensem fstore_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl (@match_AbData). intros.\n      exploit fstore_exist; eauto 1; intros [labd' [HP HM]].\n      match_external_states_simpl.\n      eapply fstore_match; eauto.\n    Qed.\n\n  End FSTORE_SIM.\n\n  Section FLOAD'_SIM.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2: relate_impl_HP}.\n\n    Lemma fload'_exist:\n      forall s habd labd i z f,\n        fload'_spec i habd = Some z\n        -> relate_AbData s f habd labd\n        -> fload'_spec i labd = Some z.\n    Proof.\n      unfold fload'_spec; intros.\n      exploit relate_impl_iflags_eq; eauto.\n      inversion 1. \n      pose proof (relate_impl_HP_eq _ _ _ _ H0) as Hre.\n      specialize (FlatMem.load_inj _ _ Mint32 (i * 4) _ f Hre refl_equal).\n      revert H. subrewrite.\n      subdestruct. intros (v2 & HLD & HVAL).\n      rewrite HLD. inv HVAL. assumption.\n    Qed.\n\n    Lemma fload'_sim :\n      forall id,\n        sim (crel RData RData) (id ↦ gensem fload'_spec) (id ↦ gensem fload'_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl (@match_AbData).\n      match_external_states_simpl. \n      erewrite fload'_exist; eauto.\n      reflexivity.\n    Qed.\n\n  End FLOAD'_SIM.\n\n  Section FLOAD_SIM.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2: relate_impl_HP}.\n    Context {re3: relate_impl_ipt}.\n    Context {re4: relate_impl_pperm}.\n\n    Lemma fload_exist:\n      forall s habd labd i z f,\n        fload_spec i habd = Some z\n        -> relate_AbData s f habd labd\n        -> fload_spec i labd = Some z.\n    Proof.\n      unfold fload_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1. \n      exploit relate_impl_ipt_eq; eauto.  \n      exploit relate_impl_pperm_eq; eauto. intros. \n      pose proof (relate_impl_HP_eq _ _ _ _ H0) as Hre.\n      specialize (FlatMem.load_inj _ _ Mint32 (i * 4) _ f Hre refl_equal).\n      revert H. subrewrite.\n      subdestruct. intros (v2 & HLD & HVAL).\n      rewrite HLD. inv HVAL. assumption.\n    Qed.\n\n    Lemma fload_sim :\n      forall id,\n        sim (crel RData RData) (id ↦ gensem fload_spec) (id ↦ gensem fload_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl (@match_AbData).\n      match_external_states_simpl. \n      erewrite fload_exist; eauto.\n      reflexivity.\n    Qed.\n\n  End FLOAD_SIM.\n\n  Section MEM_COPY_AUX_SIM.\n\n    Context {re1: relate_impl_HP}.\n  \n    Lemma flatmem_copy_aux_exists:\n      forall n hh hh' lh from to (f: meminj),\n        flatmem_copy_aux n from to hh = Some hh' ->\n        FlatMem.flatmem_inj hh lh ->\n        exists lh',\n          flatmem_copy_aux n from to lh = Some lh'\n          /\\ FlatMem.flatmem_inj hh' lh'.\n    Proof.\n      induction n.\n      - simpl. intros. inv H.\n        refine_split'; trivial.\n      - intros. simpl in *.\n        subdestruct.\n        specialize (FlatMem.load_inj _ _ Mint32 from _ f H0 Hdestruct).\n        intros (v' & HLD & HVA).\n        rewrite HLD. inv HVA.\n        set (hh0:= FlatMem.store Mint32 hh to (Vint i)) in *.\n        set (lh0:=FlatMem.store Mint32 lh to (Vint i)).\n        assert (HF_INJ: FlatMem.flatmem_inj hh0 lh0).\n        {\n          subst hh0 lh0.\n          eapply (FlatMem.store_mapped_inj f); eauto.\n        }\n        exploit IHn; eauto.\n    Qed.\n\n  End MEM_COPY_AUX_SIM.\n\n  Section MEM_COPY'_SIM.\n\n    Context {re1: relate_impl_HP}.\n    Context {re3: relate_impl_iflags}.\n\n    Lemma flatmem_copy'_exist:\n      forall s habd habd' labd i from to f,\n        flatmem_copy'_spec i from to habd = Some habd'\n        -> relate_AbData s f habd labd\n        -> exists labd', flatmem_copy'_spec i from to labd = Some labd' \n                         /\\ relate_AbData s f habd' labd'.\n    Proof.\n      unfold flatmem_copy'_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.         \n      revert H. subrewrite. \n      subdestruct. inv HQ.\n      exploit flatmem_copy_aux_exists; eauto.\n      eapply relate_impl_HP_eq; eauto.\n      intros (lh' & HCopy' & Hinj).\n      rewrite HCopy'. refine_split'; trivial.\n      eapply relate_impl_HP_update; eauto.\n    Qed.\n\n    Context {mt1: match_impl_HP}.\n\n    Lemma flatmem_copy'_match:\n      forall s d d' m i from to f,\n        flatmem_copy'_spec i from to d = Some d'\n        -> match_AbData s d m f\n        -> match_AbData s d' m f.\n    Proof.\n      unfold flatmem_copy'_spec; intros. subdestruct.\n      inv H. eapply match_impl_HP_update. assumption.\n    Qed.\n\n    (* This simulation proof is not necessary*)\n    Context {inv: PreservesInvariants (HD:= data) flatmem_copy'_spec}.\n    Context {inv0: PreservesInvariants (HD:= data0) flatmem_copy'_spec}.\n\n    Lemma flatmem_copy'_sim :\n      forall id,\n        sim (crel RData RData) (id ↦ gensem flatmem_copy'_spec)\n            (id ↦ gensem flatmem_copy'_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl (@match_AbData). intros.\n      exploit flatmem_copy'_exist; eauto 1; intros [labd' [HP HM]].\n      match_external_states_simpl.\n      eapply flatmem_copy'_match; eauto.\n    Qed.\n\n  End MEM_COPY'_SIM.\n\n  Section MEM_COPY0_SIM.\n\n    Context {re1: relate_impl_HP}.\n    Context {re2: relate_impl_pperm}.\n    Context {re3: relate_impl_iflags}.\n\n    Lemma flatmem_copy0_exist:\n      forall s habd habd' labd i from to f,\n        flatmem_copy0_spec i from to habd = Some habd'\n        -> relate_AbData s f habd labd\n        -> exists labd', flatmem_copy0_spec i from to labd = Some labd' \n                         /\\ relate_AbData s f habd' labd'.\n    Proof.\n      unfold flatmem_copy0_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.         \n      exploit relate_impl_pperm_eq; eauto. intros. \n      revert H. subrewrite. \n      subdestruct. inv HQ.\n      exploit flatmem_copy_aux_exists; eauto.\n      eapply relate_impl_HP_eq; eauto.\n      intros (lh' & HCopy0 & Hinj).\n      rewrite HCopy0. refine_split'; trivial.\n      eapply relate_impl_HP_update; eauto.\n    Qed.\n\n    Context {mt1: match_impl_HP}.\n\n    Lemma flatmem_copy0_match:\n      forall s d d' m i from to f,\n        flatmem_copy0_spec i from to d = Some d'\n        -> match_AbData s d m f\n        -> match_AbData s d' m f.\n    Proof.\n      unfold flatmem_copy0_spec; intros. subdestruct.\n      inv H. eapply match_impl_HP_update. assumption.\n    Qed.\n\n    (* This simulation proof is not necessary*)\n    Context {inv: PreservesInvariants (HD:= data) flatmem_copy0_spec}.\n    Context {inv0: PreservesInvariants (HD:= data0) flatmem_copy0_spec}.\n\n    Lemma flatmem_copy0_sim :\n      forall id,\n        sim (crel RData RData) (id ↦ gensem flatmem_copy0_spec)\n            (id ↦ gensem flatmem_copy0_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl (@match_AbData). intros.\n      exploit flatmem_copy0_exist; eauto 1; intros [labd' [HP HM]].\n      match_external_states_simpl.\n      eapply flatmem_copy0_match; eauto.\n    Qed.\n\n  End MEM_COPY0_SIM.\n\n  Section MEM_COPY_SIM.\n\n    Context {re1: relate_impl_HP}.\n    Context {re2: relate_impl_pperm}.\n    Context {re3: relate_impl_iflags}.\n    Context {re4: relate_impl_ipt}.\n\n    Lemma flatmem_copy_exist:\n      forall s habd habd' labd i from to f,\n        flatmem_copy_spec i from to habd = Some habd'\n        -> relate_AbData s f habd labd\n        -> exists labd', flatmem_copy_spec i from to labd = Some labd' \n                         /\\ relate_AbData s f habd' labd'.\n    Proof.\n      unfold flatmem_copy_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.         \n      exploit relate_impl_pperm_eq; eauto. intros. \n      exploit relate_impl_ipt_eq; eauto. intros.\n      revert H. subrewrite. \n      subdestruct. inv HQ.\n      exploit flatmem_copy_aux_exists; eauto.\n      eapply relate_impl_HP_eq; eauto.\n      intros (lh' & HCopy & Hinj).\n      rewrite HCopy. refine_split'; trivial.\n      eapply relate_impl_HP_update; eauto.\n    Qed.\n\n    Context {mt1: match_impl_HP}.\n\n    Lemma flatmem_copy_match:\n      forall s d d' m i from to f,\n        flatmem_copy_spec i from to d = Some d'\n        -> match_AbData s d m f\n        -> match_AbData s d' m f.\n    Proof.\n      unfold flatmem_copy_spec; intros. subdestruct.\n      inv H. eapply match_impl_HP_update. assumption.\n    Qed.\n\n    (* This simulation proof is not necessary*)\n    Context {inv: PreservesInvariants (HD:= data) flatmem_copy_spec}.\n    Context {inv0: PreservesInvariants (HD:= data0) flatmem_copy_spec}.\n\n    Lemma flatmem_copy_sim :\n      forall id,\n        sim (crel RData RData) (id ↦ gensem flatmem_copy_spec)\n            (id ↦ gensem flatmem_copy_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl (@match_AbData). intros.\n      exploit flatmem_copy_exist; eauto 1; intros [labd' [HP HM]].\n      match_external_states_simpl.\n      eapply flatmem_copy_match; eauto.\n    Qed.\n\n  End MEM_COPY_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/ObjFlatMem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.26241440302004443}}
{"text": "(* TLC in Coq\n *\n * Module: tlc.semantics.constructor\n * Purpose: Contains the semantics for constructors.\n *)\n\nRequire Import mathcomp.ssreflect.ssreflect.\nRequire Import mathcomp.ssreflect.ssrnat.\nRequire Import tlc.syntax.constructor.\n\n(* Determine the arity of a constructor *)\nDefinition constructor_arity c :=\n  match c with\n  (* Unit *)\n  | CUnit => 0\n  (* Maybe *)\n  | CNone => 0\n  | CSome => 1\n  (* Either *)\n  | CLeft => 1\n  | CRight => 1\n  (* Pair *)\n  | CPair => 2\n  (* Boolean *)\n  | CFalse => 0\n  | CTrue => 0\n  (* Natural *)\n  | CZero => 0\n  | CSucc => 1\n  (* List *)\n  | CNil => 0\n  | CCons => 2\n  (* Orientation *)\n  | CRequest => 0\n  | CIndication => 0\n  | CPeriodic => 0\n  (* PeriodicEvent *)\n  | CPE => 0\n  (* FLRequest *)\n  | CFLSend => 2\n  (* FLIndication *)\n  | CFLDeliver => 2\n  (* SLRequest *)\n  | CSLSend => 2\n  (* SLIndication *)\n  | CSLDeliver => 2\n  (* PLRequest *)\n  | CPLSend => 2\n  (* PLIndication *)\n  | CPLDeliver => 2\n  end.\n", "meta": {"author": "jzgriffin", "repo": "tlc", "sha": "58919b43a5a1db887237dbeee812664147d657d4", "save_path": "github-repos/coq/jzgriffin-tlc", "path": "github-repos/coq/jzgriffin-tlc/tlc-58919b43a5a1db887237dbeee812664147d657d4/tlc/semantics/constructor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.2624082731687133}}
{"text": "Require Export RecTypes.SpecTypes.\nRequire Export RecTypes.InstTy.\nRequire Export RecTypes.LemmasTypes.\n(* Require Import StlcFix.SpecScoping. *)\n(* Require Import StlcFix.LemmasScoping. *)\n(* Require Import StlcFix.DecideEval. *)\nRequire Import UValIE.UVal.\nRequire Import LogRelIE.PseudoType.\nRequire Import LogRelIE.LemmasPseudoType.\nRequire Import LogRelIE.LR.\nRequire Import LogRelIE.LemmasLR.\nRequire Import LogRelIE.LemmasIntro.\nRequire Import Lia.\nRequire Import Db.Lemmas.\n\nRequire Import StlcIso.SpecEvaluation.\nRequire Import StlcIso.SpecSyntax.\nRequire Import StlcIso.SpecTyping.\nRequire Import StlcIso.SpecAnnot.\nRequire Import StlcIso.LemmasTyping.\nRequire Import StlcIso.LemmasEvaluation.\nRequire Import StlcIso.CanForm.\nRequire Import StlcIso.SpecEquivalent.\nRequire Import StlcIso.Size.\n\nRequire Import StlcEqui.SpecEvaluation.\nRequire Import StlcEqui.SpecSyntax.\nRequire Import StlcEqui.SpecTyping.\nRequire Import StlcEqui.SpecAnnot.\nRequire Import StlcEqui.LemmasTyping.\nRequire Import StlcEqui.LemmasEvaluation.\nRequire Import StlcEqui.CanForm.\nRequire Import StlcEqui.SpecEquivalent.\nRequire Import StlcEqui.Size.\n\nModule I.\n  Include RecTypes.SpecTypes.\n  Include RecTypes.InstTy.\n  Include RecTypes.LemmasTypes.\n\n  Include StlcIso.SpecEvaluation.\n  Include StlcIso.SpecSyntax.\n  Include StlcIso.SpecTyping.\n  Include StlcIso.SpecAnnot.\n  Include StlcIso.LemmasTyping.\n  Include StlcIso.LemmasEvaluation.\n  Include StlcIso.CanForm.\n  Include StlcIso.Size.\nEnd I.\n\nModule E.\n  Include RecTypes.SpecTypes.\n  Include RecTypes.InstTy.\n  Include RecTypes.LemmasTypes.\n\n  Include StlcEqui.SpecEvaluation.\n  Include StlcEqui.SpecSyntax.\n  Include StlcEqui.SpecTyping.\n  Include StlcEqui.SpecAnnot.\n  Include StlcEqui.LemmasTyping.\n  Include StlcEqui.LemmasEvaluation.\n  Include StlcEqui.CanForm.\n  Include StlcEqui.Size.\nEnd E.\n\nFixpoint compie (t : I.Tm) : E.Tm :=\n  match t with\n    | I.var x => E.var x\n    | I.abs τ t => E.abs τ (compie t)\n    | I.app t1 t2 => E.app (compie t1) (compie t2)\n    | I.unit => E.unit\n    | I.true => E.true\n    | I.false => E.false\n    | I.ite t1 t2 t3 => E.ite (compie t1) (compie t2) (compie t3)\n    | I.pair t1 t2 => E.pair (compie t1) (compie t2)\n    | I.proj₁ t => E.proj₁ (compie t)\n    | I.proj₂ t => E.proj₂ (compie t)\n    | I.inl t => E.inl (compie t)\n    | I.inr t => E.inr (compie t)\n    | I.caseof t1 t2 t3 => E.caseof (compie t1) (compie t2) (compie t3)\n    | I.seq t1 t2 => E.seq (compie t1) (compie t2)\n    | I.fold_ t => compie t\n    | I.unfold_ t => compie t\n  end.\n\nFixpoint compie_annot (t : I.TmA) : E.TmA :=\n  match t with\n    | I.ia_var x => E.ea_var x\n    | I.ia_abs τ₁ τ₂ t => E.ea_abs τ₁ τ₂ (compie_annot t)\n    | I.ia_app τ₁ τ₂ t1 t2 => E.ea_app τ₁ τ₂ (compie_annot t1) (compie_annot t2)\n    | I.ia_unit => E.ea_unit\n    | I.ia_true => E.ea_true\n    | I.ia_false => E.ea_false\n    | I.ia_ite τ t1 t2 t3 => E.ea_ite τ (compie_annot t1) (compie_annot t2) (compie_annot t3)\n    | I.ia_pair τ₁ τ₂ t1 t2 => E.ea_pair τ₁ τ₂ (compie_annot t1) (compie_annot t2)\n    | I.ia_proj₁ τ₁ τ₂ t => E.ea_proj₁ τ₁ τ₂ (compie_annot t)\n    | I.ia_proj₂ τ₁ τ₂ t => E.ea_proj₂ τ₁ τ₂ (compie_annot t)\n    | I.ia_inl τ₁ τ₂ t => E.ea_inl τ₁ τ₂ (compie_annot t)\n    | I.ia_inr τ₁ τ₂ t => E.ea_inr τ₁ τ₂ (compie_annot t)\n    | I.ia_caseof τ₁ τ₂ τ t1 t2 t3 => E.ea_caseof τ₁ τ₂ τ (compie_annot t1) (compie_annot t2) (compie_annot t3)\n    | I.ia_seq τ t₁ t₂ => E.ea_seq (τ) (compie_annot t₁) (compie_annot t₂)\n    | I.ia_fold_ τ t => E.ea_coerce τ[beta1 (trec τ)] (compie_annot t)\n    | I.ia_unfold_ τ t => E.ea_coerce (trec τ) (compie_annot t)\n  end.\n\n(* The two compiler definitions are the same modulo type annotations. *)\nLemma compie_compie_annot {t} :\n  compie (I.eraseAnnot t) = E.eraseAnnot (compie_annot t).\nProof.\n  induction t; cbn; f_equal; try assumption; try reflexivity.\nQed.\n\nFixpoint compie_pctx_annot (C : I.PCtxA) : E.PCtxA :=\n  match C with\n  | I.ia_phole => E.ea_phole\n  | I.ia_pabs τ₁ τ₂ C => E.ea_pabs τ₁ τ₂ (compie_pctx_annot C)\n  | I.ia_papp₁ τ₁ τ₂ C t => E.ea_papp₁ τ₁ τ₂ (compie_pctx_annot C) (compie_annot t)\n  | I.ia_papp₂ τ₁ τ₂ t C => E.ea_papp₂ τ₁ τ₂ (compie_annot t) (compie_pctx_annot C)\n  | I.ia_pite₁ τ C t₂ t₃ => E.ea_pite₁ τ (compie_pctx_annot C) (compie_annot t₂) (compie_annot t₃)\n  | I.ia_pite₂ τ t₁ C t₃ => E.ea_pite₂ τ (compie_annot t₁) (compie_pctx_annot C) (compie_annot t₃)\n  | I.ia_pite₃ τ t₁ t₂ C => E.ea_pite₃ τ (compie_annot t₁) (compie_annot t₂) (compie_pctx_annot C)\n  | I.ia_ppair₁ τ₁ τ₂ C t => E.ea_ppair₁ τ₁ τ₂ (compie_pctx_annot C) (compie_annot t)\n  | I.ia_ppair₂ τ₁ τ₂ t C => E.ea_ppair₂ τ₁ τ₂ (compie_annot t) (compie_pctx_annot C)\n  | I.ia_pproj₁ τ₁ τ₂ C => E.ea_pproj₁ τ₁ τ₂ (compie_pctx_annot C)\n  | I.ia_pproj₂ τ₁ τ₂ C => E.ea_pproj₂ τ₁ τ₂ (compie_pctx_annot C)\n  | I.ia_pinl τ₁ τ₂ C => E.ea_pinl τ₁ τ₂ (compie_pctx_annot C)\n  | I.ia_pinr τ₁ τ₂ C => E.ea_pinr τ₁ τ₂ (compie_pctx_annot C)\n  | I.ia_pcaseof₁ τ₁ τ₂ τ C t₂ t₃ => E.ea_pcaseof₁ τ₁ τ₂ τ (compie_pctx_annot C) (compie_annot t₂) (compie_annot t₃)\n  | I.ia_pcaseof₂ τ₁ τ₂ τ t₁ C t₃ => E.ea_pcaseof₂ τ₁ τ₂ τ (compie_annot t₁) (compie_pctx_annot C) (compie_annot t₃)\n  | I.ia_pcaseof₃ τ₁ τ₂ τ t₁ t₂ C => E.ea_pcaseof₃ τ₁ τ₂ τ (compie_annot t₁) (compie_annot t₂) (compie_pctx_annot C)\n  | I.ia_pseq₁ τ C t₂ => E.ea_pseq₁ τ (compie_pctx_annot C) (compie_annot t₂)\n  | I.ia_pseq₂ τ t₁ C => E.ea_pseq₂ τ (compie_annot t₁) (compie_pctx_annot C)\n  | I.ia_pfold τ C => E.ea_pcoerce (τ[beta1 (trec τ)]) (compie_pctx_annot C)\n  | I.ia_punfold τ C => E.ea_pcoerce (trec τ) (compie_pctx_annot C)\n  end.\n\nLemma smoke_test_compiler :\n  (compie_annot I.ia_unit) = E.ea_unit.\nProof.\n  simpl. reflexivity.\nQed.\n\nLemma compie_typing_works {Γ t τ} :\n  ⟪ Γ i⊢ t : τ ⟫ →\n  ⟪ Γ e⊢ compie t : τ ⟫.\nProof.\n  induction 1; I.crushTyping; E.crushTyping; eauto using I.AnnotTyping, E.AnnotTyping;\n    inversion H0 as (cl & cr);\n    inversion cr; subst;\n    econstructor;\n    [| | | | apply tyeq_symm | | |];\n    try apply ty_eq_unfoldrec;\n    try assumption;\n    eauto using ValidTy_unfold_trec, tyeq_refl.\nQed.\n\nLemma compie_annot_typing_works {Γ t τ} :\n  ⟪ Γ ia⊢ t : τ ⟫ →\n  ⟪ Γ ea⊢ compie_annot t : τ ⟫.\nProof.\n  induction 1; I.crushTyping; E.crushTyping; eauto using I.AnnotTyping, E.AnnotTyping;\n    inversion H0 as (cl & cr);\n    inversion cr; subst;\n    econstructor;\n    [| | | | apply tyeq_symm | | |];\n    try apply ty_eq_unfoldrec;\n    try assumption;\n    eauto using ValidTy_unfold_trec, tyeq_refl.\nQed.\n\nLemma compie_pctx_annot_typing_works {C Γ Γ' τ τ'} :\n  ⟪ ia⊢ C : Γ, τ → Γ', τ' ⟫ →\n  ⟪ ea⊢ compie_pctx_annot C : Γ, τ →\n  Γ', τ' ⟫.\nProof.\n  induction 1; eauto using PCtxTypingAnnot, compie_typing_works.\n  - eapply compie_annot_typing_works in H1.\n    eauto using PCtxTypingAnnot, compie_typing_works.\n  - eapply compie_annot_typing_works in H1.\n    eauto using PCtxTypingAnnot, compie_typing_works.\n  - eapply compie_annot_typing_works in H0, H1.\n    eauto using PCtxTypingAnnot, compie_typing_works.\n  - eapply compie_annot_typing_works in H, H1.\n    eauto using PCtxTypingAnnot, compie_typing_works.\n  - eapply compie_annot_typing_works in H, H0.\n    eauto using PCtxTypingAnnot, compie_typing_works.\n  - eapply compie_annot_typing_works in H0.\n    eauto using PCtxTypingAnnot, compie_typing_works.\n  - eapply compie_annot_typing_works in H.\n    eauto using PCtxTypingAnnot, compie_typing_works.\n  - eapply compie_annot_typing_works in H0, H1.\n    eauto using PCtxTypingAnnot, compie_typing_works.\n  - eapply compie_annot_typing_works in H, H1.\n    eauto using PCtxTypingAnnot, compie_typing_works.\n  - eapply compie_annot_typing_works in H, H0.\n    eauto using PCtxTypingAnnot, compie_typing_works.\n  - eauto using PCtxTypingAnnot, compie_typing_works.\n    cbn.\n    econstructor.\n    apply ty_eq_unfoldrec.\n    crushValidTy.\n    exact IHPCtxTypingAnnot.\n    apply ValidTy_unfold_trec.\n    apply ValidTy_rec.\n    assert (0 ≤ 1) as H' by lia.\n    eapply (WsTy_mono H').\n    crushValidTy.\n    crushValidTy.\n    apply ValidTy_rec.\n    assert (0 ≤ 1) as H' by lia.\n    eapply (WsTy_mono H').\n    crushValidTy.\n    crushValidTy.\n  - cbn.\n    econstructor.\n    apply tyeq_symm.\n    apply ty_eq_unfoldrec.\n    crushValidTy.\n    exact IHPCtxTypingAnnot.\n    assumption.\n    now apply ValidTy_unfold_trec.\n  - eapply compie_annot_typing_works in H0.\n    eauto using PCtxTypingAnnot, compie_typing_works.\n  - eapply compie_annot_typing_works in H.\n    eauto using PCtxTypingAnnot, compie_typing_works.\nQed.\n\nLocal Ltac crush :=\n  cbn in * |- ;\n  repeat\n    (cbn;\n     repeat crushLRMatch2;\n     try assumption;\n     crushOfType;\n     I.crushTyping;\n     E.crushTyping;\n     repeat crushValidPTyMatch;\n     repeat crushValidTyMatch2;\n     repeat crushRepEmulEmbed;\n     repeat I.crushStlcSyntaxMatchH;\n     repeat E.crushStlcSyntaxMatchH;\n     subst); try lia; auto.\n\nSection CompatibilityLemmas.\n\n  Lemma compat_lambda {Γ τ' ts d n τ} {tu : E.Tm}:\n    ValidPEnv Γ -> ValidPTy τ' -> ValidPTy τ ->\n    ⟪ Γ p▻ τ' ⊩ ts ⟦ d , n ⟧ tu : τ ⟫ →\n    ⟪ Γ ⊩ (I.abs (repEmul τ') ts) ⟦ d , n ⟧ (E.abs (isToEq τ') tu) : ptarr τ' τ ⟫.\n  Proof.\n    intros vΓ vτ' vτ.\n    repeat (try crushLRMatch; crush).\n    - eauto using I.wtSub_up, envrel_implies_WtSub_iso.\n    - eauto using E.wtSub_up, envrel_implies_WtSub_equi.\n    - repeat eexists; try reflexivity.\n      intros w' fw vs vu szvu vr.\n      rewrite -> ?ap_comp.\n      apply H3; crush.\n  Qed.\n\n  Lemma compat_lambda_embed {Γ τ' ts d n tu τ} :\n    ValidPEnv Γ -> ValidTy τ' -> ValidPTy τ ->\n    ⟪ Γ p▻ embed τ' ⊩ ts ⟦ d , n ⟧ tu : τ ⟫ →\n    ⟪ Γ ⊩ (I.abs τ' ts) ⟦ d , n ⟧ (E.abs (isToEq (embed τ')) tu) : ptarr (embed τ') τ ⟫.\n  Proof.\n    intros vΓ vτ' vτ.\n    rewrite <- (repEmul_embed_leftinv τ') at 2.\n    apply compat_lambda; crush.\n  Qed.\n\n  Lemma compat_lambda_embed' {Γ τ' ts d n tu τ} :\n    ValidPEnv Γ -> ValidTy τ' -> ValidPTy τ ->\n    ⟪ Γ p▻ embed τ' ⊩ ts ⟦ d , n ⟧ tu : τ ⟫ →\n    ⟪ Γ ⊩ (I.abs τ' ts) ⟦ d , n ⟧ (E.abs τ' tu) : ptarr (embed τ') τ ⟫.\n  Proof.\n    rewrite <-(isToEq_embed_leftinv τ') at 4.\n    now apply compat_lambda_embed.\n  Qed.\n\n  Lemma compat_unit {Γ d n} :\n    ⟪ Γ ⊩ I.unit ⟦ d , n ⟧ E.unit : ptunit ⟫.\n  Proof.\n    repeat (try crushLRMatch; crush).\n  Qed.\n\n  Lemma compat_true {Γ d n} :\n    ⟪ Γ ⊩ I.true ⟦ d , n ⟧ E.true : ptbool ⟫.\n  Proof.\n    repeat (try crushLRMatch; crush).\n  Qed.\n\n  Lemma compat_false {Γ d n} :\n    ⟪ Γ ⊩ I.false ⟦ d , n ⟧ E.false : ptbool ⟫.\n  Proof.\n    repeat (try crushLRMatch; crush).\n  Qed.\n\n  Lemma compat_pair {Γ d n ts₁ tu₁ τ₁ ts₂ tu₂ τ₂} :\n    ValidPEnv Γ -> ValidPTy τ₁ -> ValidPTy τ₂ ->\n    ⟪ Γ ⊩ ts₁ ⟦ d , n ⟧ tu₁ : τ₁ ⟫ →\n    ⟪ Γ ⊩ ts₂ ⟦ d , n ⟧ tu₂ : τ₂ ⟫ →\n    ⟪ Γ ⊩ I.pair ts₁ ts₂ ⟦ d , n ⟧ E.pair tu₁ tu₂ : ptprod τ₁ τ₂ ⟫.\n  Proof.\n    repeat (try crushLRMatch; crush).\n    apply termrel_pair; crush.\n    refine (H7 w' _ _ _ _); unfold lev in *; try lia.\n    eauto using envrel_mono.\n  Qed.\n\n  Lemma compat_app {Γ d n ts₁ tu₁ τ₁ ts₂ tu₂ τ₂} :\n    ValidPEnv Γ -> ValidPTy τ₁ -> ValidPTy τ₂ ->\n    ⟪ Γ ⊩ ts₁ ⟦ d , n ⟧ tu₁ : ptarr τ₁ τ₂ ⟫ →\n    ⟪ Γ ⊩ ts₂ ⟦ d , n ⟧ tu₂ : τ₁ ⟫ →\n    ⟪ Γ ⊩ I.app ts₁ ts₂ ⟦ d , n ⟧ E.app tu₁ tu₂ : τ₂ ⟫.\n  Proof.\n    intros vΓ vτ₁ vτ₂.\n    repeat (try crushLRMatch; crush).\n    refine (termrel_app vτ₁ _ _ _); crush.\n    refine (H4 _ _ _ _ _); crush.\n  Qed.\n\n  Lemma compat_inl {Γ d n ts tu τ₁ τ₂} :\n    ValidPTy τ₁ -> ValidPTy τ₂ ->\n    ⟪ Γ ⊩ ts ⟦ d , n ⟧ tu : τ₁ ⟫ →\n    ⟪ Γ ⊩ I.inl ts ⟦ d , n ⟧ E.inl tu : ptsum τ₁ τ₂ ⟫.\n  Proof.\n    repeat (try crushLRMatch; crush).\n    eapply termrel_inl; crush.\n  Qed.\n\n  Lemma compat_inr {Γ d n ts tu τ₁ τ₂} :\n    ValidPTy τ₁ -> ValidPTy τ₂ ->\n    ⟪ Γ ⊩ ts ⟦ d , n ⟧ tu : τ₂ ⟫ →\n    ⟪ Γ ⊩ I.inr ts ⟦ d , n ⟧ E.inr tu : ptsum τ₁ τ₂ ⟫.\n  Proof.\n    repeat (try crushLRMatch; crush).\n    refine (termrel_inr _ _ _); crush.\n  Qed.\n\n  Lemma compat_seq {Γ d n ts₁ tu₁ ts₂ tu₂ τ₂} :\n    ValidPEnv Γ -> ValidPTy τ₂ ->\n    ⟪ Γ ⊩ ts₁ ⟦ d , n ⟧ tu₁ : ptunit ⟫ →\n    ⟪ Γ ⊩ ts₂ ⟦ d , n ⟧ tu₂ : τ₂ ⟫ →\n    ⟪ Γ ⊩ I.seq ts₁ ts₂ ⟦ d , n ⟧ E.seq tu₁ tu₂ : τ₂ ⟫.\n  Proof.\n    repeat (try crushLRMatch; crush).\n    apply termrel_seq; crush.\n    refine (H6 w' _ _ _ _); crush.\n  Qed.\n\n  Lemma compat_proj₂ {Γ d n ts tu τ₁ τ₂} :\n    ValidPTy τ₁ -> ValidPTy τ₂ ->\n    ⟪ Γ ⊩ ts ⟦ d , n ⟧ tu : ptprod τ₁ τ₂ ⟫ →\n    ⟪ Γ ⊩ I.proj₂ ts ⟦ d , n ⟧ E.proj₂ tu : τ₂ ⟫.\n  Proof.\n    intros vτ₁ vτ₂.\n    repeat (try crushLRMatch; crush).\n    refine (termrel_proj₂ vτ₁ _ _); crush.\n  Qed.\n\n  Lemma compat_proj₁ {Γ d n ts tu τ₁ τ₂} :\n    ValidPTy τ₁ -> ValidPTy τ₂ ->\n    ⟪ Γ ⊩ ts ⟦ d , n ⟧ tu : ptprod τ₁ τ₂ ⟫ →\n    ⟪ Γ ⊩ I.proj₁ ts ⟦ d , n ⟧ E.proj₁ tu : τ₁ ⟫.\n  Proof.\n    repeat (try crushLRMatch; crush).\n    refine (termrel_proj₁ _ _ _); crush.\n  Qed.\n\n  Lemma compat_ite {Γ d n ts₁ tu₁ ts₂ tu₂ ts₃ tu₃ τ} :\n    ValidPEnv Γ ->\n    ⟪ Γ ⊩ ts₁ ⟦ d , n ⟧ tu₁ : ptbool ⟫ →\n    ⟪ Γ ⊩ ts₂ ⟦ d , n ⟧ tu₂ : τ ⟫ →\n    ⟪ Γ ⊩ ts₃ ⟦ d , n ⟧ tu₃ : τ ⟫ →\n    ⟪ Γ ⊩ I.ite ts₁ ts₂ ts₃ ⟦ d , n ⟧ E.ite tu₁ tu₂ tu₃ : τ ⟫.\n  Proof.\n    repeat (try crushLRMatch; crush).\n    apply termrel_ite; crush.\n    - refine (H8 w' _ _ _ _); crush.\n    - refine (H6 w' _ _ _ _); crush.\n  Qed.\n\n  Lemma compat_caseof {Γ d n ts₁ tu₁ ts₂ tu₂ ts₃ tu₃ τ₁ τ₂ τ} :\n    ValidPEnv Γ ->\n    ValidPTy τ₁ -> ValidPTy τ₂ ->\n    ⟪ Γ ⊩ ts₁ ⟦ d , n ⟧ tu₁ : ptsum τ₁ τ₂ ⟫ →\n    ⟪ Γ p▻ τ₁ ⊩ ts₂ ⟦ d , n ⟧ tu₂ : τ ⟫ →\n    ⟪ Γ p▻ τ₂ ⊩ ts₃ ⟦ d , n ⟧ tu₃ : τ ⟫ →\n    ⟪ Γ ⊩ I.caseof ts₁ ts₂ ts₃ ⟦ d , n ⟧ E.caseof tu₁ tu₂ tu₃ : τ ⟫.\n  Proof.\n    intros vΓ vτ₁ vτ₂ rel₁ rel₂ rel₃.\n    split; [|split].\n    - unfold OpenLRN in *.\n      crush.\n    - unfold OpenLRN in *.\n      crush.\n    - intros.\n      simpl.\n      refine (termrel_caseof vτ₁ _ _ _ _);\n        repeat (try crushLRMatch; crush);\n        rewrite -> ?ap_comp.\n      + refine (H8 w' _ _ _ _); crush.\n      + refine (H5 w' _ _ _ _); crush.\n  Qed.\n\n  Lemma compat_unfold_ {Γ d n ts tu τ} :\n    ValidPTy (ptrec τ) ->\n    ⟪ Γ ⊩ ts ⟦ d , n ⟧ tu : ptrec τ ⟫ →\n    ⟪ Γ ⊩ I.unfold_ ts ⟦ d , n ⟧ tu : τ [beta1 (ptrec τ)] ⟫.\n  Proof.\n    repeat (try crushLRMatch; crush).\n    - rewrite repEmul_sub.\n      replace (beta1 (ptrec τ) >-> repEmul) with (beta1 (trec (repEmul τ))) by (extensionality i; destruct i; now cbn).\n      eapply I.WtUnfold; crushValidTy; eauto using repEmul_preserves_ws, repEmul_preserves_contr.\n    - refine (E.WtEq _ _ _ _ H2).\n      eapply EqMuL.\n      enough ⟨ beta1 (ptrec τ) : 1 => 0 ⟩ as wsbμτ.\n      rewrite (isToEq_sub H wsbμτ).\n      replace (beta1 (ptrec τ) >-> isToEq) with (beta1 (trec (isToEq τ))) by (extensionality i; destruct i; now cbn).\n      now eapply tyeq_refl.\n      refine (wsSub_sub_beta1 _ _ _).\n      now constructor.\n      eauto using ValidTy_rec, isToEq_preserves_ws, isToEq_preserves_contr.\n      eapply ValidPTy_implies_ValidTy_isToEq, ValidPTy_unfold_trec; crush.\n    - eapply termrel_unfold_; crush.\n  Qed.\n\n  Lemma compat_fold_ {Γ d n ts tu τ} :\n    ValidPTy (ptrec τ) ->\n    ⟪ Γ ⊩ ts ⟦ d , n ⟧ tu : τ [beta1 (ptrec τ)] ⟫ →\n    ⟪ Γ ⊩ I.fold_ ts ⟦ d , n ⟧ tu : ptrec τ ⟫.\n  Proof.\n    repeat (try crushLRMatch; crush).\n    - rewrite repEmul_sub in H0.\n      now replace (beta1 (ptrec τ) >-> repEmul) with (beta1 (trec (repEmul τ))) in H0 by (extensionality i; destruct i; now cbn).\n    - eapply (ValidPTy_implies_ValidTy_repEmul (τ := ptrec τ)).\n      crush.\n    - refine (E.WtEq _ _ _ _ H2).\n      eapply EqMuR.\n      enough ⟨ beta1 (ptrec τ) : 1 => 0 ⟩ as wsbμτ.\n      rewrite (isToEq_sub H wsbμτ).\n      replace (beta1 (ptrec τ) >-> isToEq) with (beta1 (trec (isToEq τ))) by (extensionality i; destruct i; now cbn).\n      now eapply tyeq_refl.\n      refine (wsSub_sub_beta1 _ _ _).\n      now constructor.\n      eapply ValidPTy_implies_ValidTy_isToEq, ValidPTy_unfold_trec; crush.\n      eapply (ValidPTy_implies_ValidTy_isToEq (τ := ptrec τ)); crush.\n    - eapply termrel_fold_; crush.\n  Qed.\n\n  Ltac crushCompatMatch :=\n    match goal with\n    | [ |- ⟪ _ ⊩ I.abs _ _ ⟦ _ , _ ⟧ E.abs _ _ : _ ⟫ ] => eapply compat_lambda_embed'\n    | [ |- ⟪ _ ⊩ I.app _ _ ⟦ _ , _ ⟧ E.app _ _ : _ ⟫ ] => eapply compat_app\n    | [ |- ⟪ _ ⊩ I.seq _ _ ⟦ _ , _ ⟧ E.seq _ _ : _ ⟫ ] => eapply compat_seq\n    | [ |- ⟪ _ ⊩ I.var _ ⟦ _ , _ ⟧ E.var _ : _ ⟫ ] => eapply compat_var\n    | [ |- ⟪ _ ⊩ I.inl _ ⟦ _ , _ ⟧ E.inl _ : _ ⟫ ] => eapply compat_inl\n    | [ |- ⟪ _ ⊩ I.inr _ ⟦ _ , _ ⟧ E.inr _ : _ ⟫ ] => eapply compat_inr\n    | [ |- ⟪ _ ⊩ I.proj₁ _ ⟦ _ , _ ⟧ E.proj₁ _ : _ ⟫ ] => eapply compat_proj₁\n    | [ |- ⟪ _ ⊩ I.proj₂ _ ⟦ _ , _ ⟧ E.proj₂ _ : _ ⟫ ] => eapply compat_proj₂\n    | [ |- ⟪ _ ⊩ I.unit ⟦ _ , _ ⟧ E.unit : _ ⟫ ] => eapply compat_unit\n    | [ |- ⟪ _ ⊩ I.true ⟦ _ , _ ⟧ E.true : _ ⟫ ] => eapply compat_true\n    | [ |- ⟪ _ ⊩ I.false ⟦ _ , _ ⟧ E.false : _ ⟫ ] => eapply compat_false\n    | [ |- ⟪ _ ⊩ I.pair _ _ ⟦ _ , _ ⟧ E.pair _ _ : _ ⟫ ] => eapply compat_pair\n    | [ |- ⟪ _ ⊩ I.ite _ _ _ ⟦ _ , _ ⟧ E.ite _ _ _ : _ ⟫ ] => eapply compat_ite\n    | [ |- ⟪ _ ⊩ I.caseof _ _ _ ⟦ _ , _ ⟧ E.caseof _ _ _ : _ ⟫ ] => eapply compat_caseof\n    | [ |- ⟪ _ ⊩ I.unfold_ _ ⟦ _ , _ ⟧ _ : _ ⟫ ] => eapply compat_unfold_\n    | [ |- ⟪ _ ⊩ I.fold_ _ ⟦ _ , _ ⟧ _ : _ ⟫ ] => eapply compat_fold_\n    end.\n\n  Ltac tryValidTyFromTyping :=\n    try match goal with\n    | [ H : ⟪ _ i⊢ _ : ?τ ⟫ |- ValidTy ?τ ] => refine (I.typed_terms_are_valid _ _ _ H)\n    | [ H : ⟪ _ ia⊢ _ : ?τ ⟫ |- ValidTy ?τ ] => refine (I.typed_terms_are_valid _ _ _ (I.eraseAnnotT H))\n    end.\n\nLocal Ltac crush2 :=\n  cbn in * |- ;\n  repeat\n    (cbn;\n     tryValidTyFromTyping;\n     try crushCompatMatch;\n     try crushLRMatch2;\n     try assumption;\n     crushOfType;\n     I.crushTyping;\n     E.crushTyping;\n     try crushValidPTyMatch;\n     try crushValidTyMatch2;\n     try crushRepEmulEmbed;\n     try I.crushStlcSyntaxMatchH;\n     try E.crushStlcSyntaxMatchH;\n     subst); try lia; auto.\n\n  Lemma compie_correct {Γ d n ts τ} :\n    ValidEnv Γ -> ValidTy τ ->\n    ⟪ Γ i⊢ ts : τ ⟫ →\n    ⟪ embedCtx Γ ⊩ ts ⟦ d , n ⟧ compie ts : embed τ ⟫.\n  Proof.\n    intros vΓ vτ.\n    induction 1;\n      cbn;\n      rewrite ?compiler_is_isToEq_embed, ?eraseAnnot_ufix;\n      crush2;\n      auto using embedCtx_works with ptyvalid.\n    2: eapply IHTyping1; crush2.\n    2: eapply IHTyping2; crush2.\n    3: eapply IHTyping; crush2.\n    4: eapply IHTyping; crush2.\n    all: repeat (crushValidPTyMatch; tryValidTyFromTyping; try assumption).\n    - eapply I.ValidTy_invert_prod.\n      eauto using I.typed_terms_are_valid.\n    - refine (proj1 (I.ValidTy_invert_prod _)).\n      eauto using I.typed_terms_are_valid.\n    - replace (embed (τ[beta1 (trec τ)])) with (embed τ) [beta1 (ptrec (embed τ))] in IHTyping.\n      eapply IHTyping; crush.\n      enough (beta1 (trec τ) >-> embed = beta1 (ptrec (embed τ))) as <-.\n      now rewrite embed_sub.\n      extensionality i; destruct i; now cbn.\n    - replace (embed (τ[beta1 (trec τ)])) with (embed τ) [beta1 (ptrec (embed τ))].\n      eapply compat_unfold_; crush.\n      enough (beta1 (trec τ) >-> embed = beta1 (ptrec (embed τ))) as <-.\n      now rewrite embed_sub.\n      extensionality i; destruct i; now cbn.\n  Qed.\n\n  Lemma compie_correct' {Γ d n ts τ τ'} :\n    ValidEnv Γ -> ValidTy τ ->\n    ⟪ Γ i⊢ ts : τ ⟫ →\n    τ' = embed τ ->\n    ⟪ embedCtx Γ ⊩ ts ⟦ d , n ⟧ compie ts : τ' ⟫.\n  Proof.\n    intros; subst; now eapply compie_correct.\n  Qed.\n\n  Lemma compie_annot_correct {Γ d n ts τ} :\n    ValidEnv Γ -> ValidTy τ ->\n    ⟪ Γ ia⊢ ts : τ ⟫ →\n    ⟪ embedCtx Γ ⊩ I.eraseAnnot ts ⟦ d , n ⟧ E.eraseAnnot (compie_annot ts) : embed τ ⟫.\n  Proof.\n    intros vΓ vτ.\n    induction 1;\n      cbn.\n    - eapply compat_var, embedCtx_works; crush.\n    - eapply compat_lambda_embed'; crush.\n    - pose proof (I.typed_terms_are_valid _ _ vΓ (I.eraseAnnotT H)).\n      pose proof (I.typed_terms_are_valid _ _ vΓ (I.eraseAnnotT H0)).\n      eapply compat_app; crush; now crushValidPTyMatch.\n    - eapply compat_unit; crush.\n    - eapply compat_true; crush.\n    - eapply compat_false; crush.\n    - eapply compat_ite; crush.\n    - eapply compat_pair; crush.\n    - pose proof (I.typed_terms_are_valid _ _ vΓ (I.eraseAnnotT H)).\n      eapply compat_proj₁; crush.\n      crush.\n    - pose proof (I.typed_terms_are_valid _ _ vΓ (I.eraseAnnotT H)).\n      eapply compat_proj₂; crush.\n      crush.\n    - eapply compat_inl; crush.\n    - eapply compat_inr; crush.\n    - eapply compat_caseof; crush.\n      crush.\n      crush.\n    - eapply compat_fold_; crush.\n      rewrite embed_sub in IHAnnotTyping.\n      enough ((beta1 (trec τ) >-> embed) = (beta1 (ptrec (embed τ)))) as <-.\n      eapply IHAnnotTyping; crush.\n      extensionality i; destruct i; now cbn.\n    - rewrite embed_sub.\n      enough ((beta1 (trec τ) >-> embed) = (beta1 (ptrec (embed τ)))) as ->.\n      eapply compat_unfold_; crush.\n      extensionality i; destruct i; now cbn.\n    - eapply compat_seq; crush.\n  Qed.\n\n  Lemma compie_ctx_correct {Γ Γ' d n C τ τ'} :\n    ValidEnv Γ -> ValidEnv Γ' -> ValidTy τ -> ValidTy τ' ->\n    ⟪ ia⊢ C : Γ , τ → Γ' , τ'⟫ →\n    ⟪ ⊩ I.eraseAnnot_pctx C ⟦ d , n ⟧ eraseAnnot_pctx (compie_pctx_annot C) : embedCtx Γ , embed τ → embedCtx Γ' , embed τ' ⟫.\n  Proof.\n    intros vΓ vΓ' vτ vτ' ty; unfold OpenLRCtxN; split; [|split].\n    - rewrite ?repEmul_embed_leftinv in *.\n      rewrite ?repEmulCtx_embedCtx_leftinv in *.\n      now eapply I.eraseAnnot_pctxT.\n    - rewrite ?isToEqCtx_embedCtx_leftinv.\n      rewrite ?isToEq_embed_leftinv.\n      now eapply E.eraseAnnot_pctxT, compie_pctx_annot_typing_works.\n    - induction ty; intros ts tu trel; cbn.\n      + crush.\n      + eapply compat_lambda_embed'; crush.\n      + pose proof (I.typed_terms_are_valid _ _ vΓ' (I.eraseAnnotT H0)).\n        eapply compat_app; crush.\n        crush.\n        eapply compie_annot_correct; crush.\n      + pose proof (I.typed_terms_are_valid _ _ vΓ' (I.eraseAnnotT H1)).\n        eapply compat_app; crush.\n        crush.\n        change (embed τ₁ p⇒ embed τ₂) with (embed (tarr τ₁ τ₂)).\n        eapply compie_annot_correct; crush.\n      + eapply compat_ite; crush.\n        eapply compie_annot_correct; crush.\n        eapply compie_annot_correct; crush.\n      + eapply compat_ite; crush.\n        change ptbool with (embed tbool).\n        eapply compie_annot_correct; crush.\n        eapply compie_annot_correct; crush.\n      + eapply compat_ite; crush.\n        change ptbool with (embed tbool).\n        eapply compie_annot_correct; crush.\n        eapply compie_annot_correct; crush.\n      + eapply compat_pair; crush.\n        eapply compie_annot_correct; crush.\n      + eapply compat_pair; crush.\n        eapply compie_annot_correct; crush.\n      + eapply compat_proj₁; crush.\n        crush.\n      + eapply compat_proj₂; crush.\n        crush.\n      + eapply compat_inl; crush.\n      + eapply compat_inr; crush.\n      + eapply compat_caseof; crush.\n        crush. crush.\n        change (embedCtx Γ0 p▻ embed τ₁) with (embedCtx (evar Γ0 τ₁)).\n        eapply compie_annot_correct; crush.\n        change (embedCtx Γ0 p▻ embed τ₂) with (embedCtx (evar Γ0 τ₂)).\n        eapply compie_annot_correct; crush.\n      + eapply (compat_caseof (τ₂ := embed τ₂)); crush.\n        crush.\n        change (embed τ₁ p⊎ embed τ₂) with (embed (tsum τ₁ τ₂)).\n        eapply compie_annot_correct; crush.\n        change (embedCtx Γ0 p▻ embed τ₂) with (embedCtx (evar Γ0 τ₂)).\n        eapply compie_annot_correct; crush.\n      + eapply (compat_caseof (τ₁ := embed τ₁)); crush.\n        crush.\n        change (embed τ₁ p⊎ embed τ₂) with (embed (tsum τ₁ τ₂)).\n        eapply compie_annot_correct; crush.\n        change (embedCtx Γ0 p▻ embed τ₁) with (embedCtx (evar Γ0 τ₁)).\n        eapply compie_annot_correct; crush.\n      + eapply compat_fold_; crush.\n        rewrite embed_sub in IHty.\n        replace (beta1 (trec τ0) >-> embed) with (beta1 (ptrec (embed τ0))) in IHty.\n        eapply IHty; crush.\n        extensionality i; destruct i; now cbn.\n      + rewrite embed_sub.\n        replace (beta1 (trec τ0) >-> embed) with (beta1 (ptrec (embed τ0))).\n        eapply compat_unfold_; crush.\n        extensionality i; destruct i; now cbn.\n      + eapply compat_seq; crush.\n        eapply compie_annot_correct; crush.\n      + eapply compat_seq; crush.\n        change ptunit with (embed tunit).\n        eapply compie_annot_correct; crush.\n    Qed.\n\nEnd CompatibilityLemmas.\n\nLemma equivalenceReflection {Γ t₁ t₂ τ} :\n  ValidEnv Γ -> ValidTy τ ->\n  ⟪ Γ i⊢ t₁ : τ ⟫ →\n  ⟪ Γ i⊢ t₂ : τ ⟫ →\n  ⟪ Γ e⊢ compie t₁ ≃ compie t₂ : τ ⟫ →\n  ⟪ Γ i⊢ t₁ ≃ t₂ : τ ⟫.\nProof.\n  revert t₁ t₂ τ.\n  enough (∀ {t₁ t₂} τ,\n             ValidEnv Γ -> ValidTy τ ->\n            ⟪ Γ i⊢ t₁ : τ ⟫ →\n            ⟪ Γ i⊢ t₂ : τ ⟫ →\n            ⟪ Γ e⊢ compie t₁ ≃ compie t₂ : τ ⟫ →\n            ∀ C τ', ⟪ ia⊢ C : Γ , τ → I.empty, τ' ⟫ →\n                    I.Terminating (I.pctx_app t₁ (I.eraseAnnot_pctx C)) → I.Terminating (I.pctx_app t₂ (I.eraseAnnot_pctx C))) as Hltor.\n  { intros t₁ t₂ τ vΓ vτ ty1 ty2 eq C τ'.\n    assert (⟪ Γ e⊢ compie t₂ ≃ compie t₁ : τ ⟫) by (now apply E.pctx_equiv_symm).\n    split;\n      now refine (Hltor _ _ τ _ _ _ _ _ C τ' _).\n  }\n\n  intros t₁ t₂ τ vΓ vτ ty1 ty2 eq C τ' tyC term.\n  assert (ValidTy τ') as vτ'.\n  { eapply (I.typed_terms_are_valid _ _ ValidEnv_nil).\n    eapply (I.pctxtyping_app ty1).\n    eapply (I.eraseAnnot_pctxT tyC).\n  }\n\n  destruct (I.Terminating_TermHor term) as [n termN]; clear term.\n\n  assert (⟪ embedCtx Γ ⊩ t₁ ⟦ dir_lt , S n ⟧ compie t₁ : embed τ ⟫) as lrt₁ by exact (compie_correct vΓ vτ ty1).\n\n  assert (⟪ ⊩ (I.eraseAnnot_pctx C) ⟦ dir_lt , S n ⟧ E.eraseAnnot_pctx (compie_pctx_annot C) : embedCtx Γ , embed τ → pempty , embed τ' ⟫) as lrC_lt\n      by apply (compie_ctx_correct vΓ ValidEnv_nil vτ vτ' tyC).\n\n  apply lrC_lt in lrt₁.\n\n  assert (E.Terminating (E.pctx_app (compie t₁) (E.eraseAnnot_pctx (compie_pctx_annot C))))\n    as termu₁.\n  { apply (adequacy_lt lrt₁ termN).\n    lia.\n  }\n\n  assert (E.Terminating (E.pctx_app (compie t₂) (E.eraseAnnot_pctx (compie_pctx_annot C)))).\n  { eapply (eq _ _ vτ'); try assumption.\n    now eapply compie_pctx_annot_typing_works.\n  }\n\n  destruct (E.Terminating_TermHor H) as [n' termN']; clear H.\n\n  assert (⟪ ⊩ I.eraseAnnot_pctx C ⟦ dir_gt , S n' ⟧ E.eraseAnnot_pctx (compie_pctx_annot C) : embedCtx Γ , embed τ → pempty , embed τ' ⟫) as lrC_gt\n    by (apply (compie_ctx_correct vΓ ValidEnv_nil vτ vτ' tyC)).\n\n  assert (⟪ embedCtx Γ ⊩ t₂ ⟦ dir_gt , S n' ⟧ compie t₂ : embed τ ⟫) as lrt₂ by exact (compie_correct vΓ vτ ty2).\n\n  apply lrC_gt in lrt₂.\n\n  apply (adequacy_gt lrt₂ termN'); lia.\nQed.\n\nLemma equivalenceReflectionEmpty {t₁ t₂ τ} :\n  ValidTy τ ->\n  ⟪ I.empty i⊢ t₁ : τ ⟫ →\n  ⟪ I.empty i⊢ t₂ : τ ⟫ →\n  ⟪ E.empty e⊢ compie t₁ ≃ compie t₂ : τ ⟫ →\n  ⟪ I.empty i⊢ t₁ ≃ t₂ : τ ⟫.\nProof.\n  apply @equivalenceReflection; crushValidTy.\nQed.\n\nPrint Assumptions equivalenceReflectionEmpty.\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/CompilerIE/Compiler.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2624082661398747}}
{"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.cms.ConModel.\nRequire Import ProD3.examples.cms.common.\nRequire Import ProD3.examples.cms.ModelRepr.\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\"; \"cm2_ds\"; \"win_1\"].\n\nDefinition Win_fundef :=\n  ltac:(get_fd [\"Cm2CountMinSketchWin\"; \"apply\"] ge).\n\nDefinition Win_noop_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD None [p]\n    WITH (f : frame) (is : listn Z num_rows)\n      (_ : Forall (fun i => 0 <= i < num_slots) (`is)),\n      PRE\n        (ARG [ValBaseStruct\n               [(\"api\", P4Bit 8 NOOP);\n                (\"index_1\", P4Bit index_w (Znth 0 (`is)));\n                (\"index_2\", P4Bit index_w (Znth 1 (`is)));\n                (\"index_3\", P4Bit index_w (Znth 2 (`is)));\n                (\"index_4\", P4Bit index_w (Znth 3 (`is)));\n                (\"index_5\", P4Bit index_w (Znth 4 (`is)));\n                (\"rw_1\", P4Bit_ value_w);\n                (\"rw_2\", P4Bit_ value_w);\n                (\"rw_3\", P4Bit_ value_w);\n                (\"rw_4\", P4Bit_ value_w);\n                (\"rw_5\", P4Bit_ value_w)\n               ]\n             ]\n        (MEM []\n        (EXT [frame_repr p rows f])))\n      POST\n        (ARG_RET [ValBaseStruct\n               [(\"api\", P4Bit 8 NOOP);\n                (\"index_1\", P4Bit index_w (Znth 0 (`is)));\n                (\"index_2\", P4Bit index_w (Znth 1 (`is)));\n                (\"index_3\", P4Bit index_w (Znth 2 (`is)));\n                (\"index_4\", P4Bit index_w (Znth 3 (`is)));\n                (\"index_5\", P4Bit index_w (Znth 4 (`is)));\n                (\"rw_1\", P4Bit_ value_w);\n                (\"rw_2\", P4Bit_ value_w);\n                (\"rw_3\", P4Bit_ value_w);\n                (\"rw_4\", P4Bit_ value_w);\n                (\"rw_5\", P4Bit_ value_w)\n               ]\n        ] ValBaseNull\n        (MEM []\n        (EXT [frame_repr p rows f]))).\n\nLemma Win_noop_body :\n  func_sound ge Win_fundef nil Win_noop_spec.\nProof.\nAdmitted.\n\nDefinition Win_insert_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD None [p]\n    WITH (f : frame) (is : listn Z num_rows)\n      (_ : Forall (fun i => 0 <= i < num_slots) (`is)),\n      PRE\n        (ARG [ValBaseStruct\n               [(\"api\", P4Bit 8 INSERT);\n                (\"index_1\", P4Bit index_w (Znth 0 (`is)));\n                (\"index_2\", P4Bit index_w (Znth 1 (`is)));\n                (\"index_3\", P4Bit index_w (Znth 2 (`is)));\n                (\"index_4\", P4Bit index_w (Znth 3 (`is)));\n                (\"index_5\", P4Bit index_w (Znth 4 (`is)));\n                (\"rw_1\", P4Bit_ value_w);\n                (\"rw_2\", P4Bit_ value_w);\n                (\"rw_3\", P4Bit_ value_w);\n                (\"rw_4\", P4Bit_ value_w);\n                (\"rw_5\", P4Bit_ value_w)\n               ]\n             ]\n        (MEM []\n        (EXT [frame_repr p rows f])))\n      POST\n        (ARG_RET [ValBaseStruct\n               [(\"api\", P4Bit 8 INSERT);\n                (\"index_1\", P4Bit index_w (Znth 0 (`is)));\n                (\"index_2\", P4Bit index_w (Znth 1 (`is)));\n                (\"index_3\", P4Bit index_w (Znth 2 (`is)));\n                (\"index_4\", P4Bit index_w (Znth 3 (`is)));\n                (\"index_5\", P4Bit index_w (Znth 4 (`is)));\n                (\"rw_1\", P4Bit_ value_w);\n                (\"rw_2\", P4Bit_ value_w);\n                (\"rw_3\", P4Bit_ value_w);\n                (\"rw_4\", P4Bit_ value_w);\n                (\"rw_5\", P4Bit_ value_w)\n               ]\n        ] ValBaseNull\n        (MEM []\n        (EXT [frame_repr p rows (frame_insert f is)]))).\n\nLemma Win_insert_body :\n  func_sound ge Win_fundef nil Win_insert_spec.\nProof.\nAdmitted.\n\nDefinition Win_query_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD None [p]\n    WITH (f : frame) (is : listn Z num_rows)\n      (_ : Forall (fun i => 0 <= i < num_slots) (`is)),\n      PRE\n        (ARG [ValBaseStruct\n               [(\"api\", P4Bit 8 QUERY);\n                (\"index_1\", P4Bit index_w (Znth 0 (`is)));\n                (\"index_2\", P4Bit index_w (Znth 1 (`is)));\n                (\"index_3\", P4Bit index_w (Znth 2 (`is)));\n                (\"index_4\", P4Bit index_w (Znth 3 (`is)));\n                (\"index_5\", P4Bit index_w (Znth 4 (`is)));\n                (\"rw_1\", P4Bit_ value_w);\n                (\"rw_2\", P4Bit_ value_w);\n                (\"rw_3\", P4Bit_ value_w);\n                (\"rw_4\", P4Bit_ value_w);\n                (\"rw_5\", P4Bit_ value_w)\n               ]\n             ]\n        (MEM []\n        (EXT [frame_repr p rows f])))\n      POST\n        (ARG_RET [ValBaseStruct\n               [(\"api\", P4Bit 8 QUERY);\n                (\"index_1\", P4Bit index_w (Znth 0 (`is)));\n                (\"index_2\", P4Bit index_w (Znth 1 (`is)));\n                (\"index_3\", P4Bit index_w (Znth 2 (`is)));\n                (\"index_4\", P4Bit index_w (Znth 3 (`is)));\n                (\"index_5\", P4Bit index_w (Znth 4 (`is)));\n                (\"rw_1\", P4Bit value_w (Z.min (frame_query f (`is)) (2 ^ 32 - 1)));\n                (\"rw_2\", P4Bit_ value_w);\n                (\"rw_3\", P4Bit_ value_w);\n                (\"rw_4\", P4Bit_ value_w);\n                (\"rw_5\", P4Bit_ value_w)\n               ]\n        ] ValBaseNull\n        (MEM []\n        (EXT [frame_repr p rows f]))).\n\nLemma Win_query_body :\n  func_sound ge Win_fundef nil Win_query_spec.\nProof.\nAdmitted.\n\nDefinition Win_clear_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD None [p]\n    WITH (f : frame) (is : listn Z num_rows)\n      (_ : Forall (fun i => 0 <= i < num_slots) (`is)),\n      PRE\n        (ARG [ValBaseStruct\n               [(\"api\", P4Bit 8 CLEAR);\n                (\"index_1\", P4Bit index_w (Znth 0 (`is)));\n                (\"index_2\", P4Bit index_w (Znth 1 (`is)));\n                (\"index_3\", P4Bit index_w (Znth 2 (`is)));\n                (\"index_4\", P4Bit index_w (Znth 3 (`is)));\n                (\"index_5\", P4Bit index_w (Znth 4 (`is)));\n                (\"rw_1\", P4Bit_ value_w);\n                (\"rw_2\", P4Bit_ value_w);\n                (\"rw_3\", P4Bit_ value_w);\n                (\"rw_4\", P4Bit_ value_w);\n                (\"rw_5\", P4Bit_ value_w)\n               ]\n             ]\n        (MEM []\n        (EXT [frame_repr p rows f])))\n      POST\n        (ARG_RET [ValBaseStruct\n               [(\"api\", P4Bit 8 CLEAR);\n                (\"index_1\", P4Bit index_w (Znth 0 (`is)));\n                (\"index_2\", P4Bit index_w (Znth 1 (`is)));\n                (\"index_3\", P4Bit index_w (Znth 2 (`is)));\n                (\"index_4\", P4Bit index_w (Znth 3 (`is)));\n                (\"index_5\", P4Bit index_w (Znth 4 (`is)));\n                (\"rw_1\", P4Bit value_w 0);\n                (\"rw_2\", P4Bit_ value_w);\n                (\"rw_3\", P4Bit_ value_w);\n                (\"rw_4\", P4Bit_ value_w);\n                (\"rw_5\", P4Bit_ value_w)\n               ]\n        ] ValBaseNull\n        (MEM []\n        (EXT [frame_repr p rows (frame_clear f is)]))).\n\nLemma Win_clear_body :\n  func_sound ge Win_fundef nil Win_clear_spec.\nProof.\nAdmitted.\n\n#[export] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply Win_noop_body) : func_specs.\n\nDefinition Win_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD None [p]\n    WITH (op : Z) (f : frame) (is : listn Z num_rows)\n      (_ : In op [NOOP; CLEAR; INSERT; QUERY])\n      (_ : Forall (fun i => 0 <= i < num_slots) (`is)),\n      PRE\n        (ARG [ValBaseStruct\n               [(\"api\", P4Bit 8 op);\n                (\"index_1\", P4Bit index_w (Znth 0 (`is)));\n                (\"index_2\", P4Bit index_w (Znth 1 (`is)));\n                (\"index_3\", P4Bit index_w (Znth 2 (`is)));\n                (\"index_4\", P4Bit index_w (Znth 3 (`is)));\n                (\"index_5\", P4Bit index_w (Znth 4 (`is)));\n                (\"rw_1\", P4Bit_ value_w);\n                (\"rw_2\", P4Bit_ value_w);\n                (\"rw_3\", P4Bit_ value_w);\n                (\"rw_4\", P4Bit_ value_w);\n                (\"rw_5\", P4Bit_ value_w)\n               ]\n             ]\n        (MEM []\n        (EXT [frame_repr p rows f])))\n      POST\n        (ARG_RET [\n          if op =? NOOP then\n             ValBaseStruct\n               [(\"api\", P4Bit 8 NOOP);\n                (\"index_1\", P4Bit index_w (Znth 0 (`is)));\n                (\"index_2\", P4Bit index_w (Znth 1 (`is)));\n                (\"index_3\", P4Bit index_w (Znth 2 (`is)));\n                (\"index_4\", P4Bit index_w (Znth 3 (`is)));\n                (\"index_5\", P4Bit index_w (Znth 4 (`is)));\n                (\"rw_1\", P4Bit_ value_w);\n                (\"rw_2\", P4Bit_ value_w);\n                (\"rw_3\", P4Bit_ value_w);\n                (\"rw_4\", P4Bit_ value_w);\n                (\"rw_5\", P4Bit_ value_w)\n               ]\n          else if op =? CLEAR then\n             ValBaseStruct\n               [(\"api\", P4Bit 8 CLEAR);\n                (\"index_1\", P4Bit index_w (Znth 0 (`is)));\n                (\"index_2\", P4Bit index_w (Znth 1 (`is)));\n                (\"index_3\", P4Bit index_w (Znth 2 (`is)));\n                (\"index_4\", P4Bit index_w (Znth 3 (`is)));\n                (\"index_5\", P4Bit index_w (Znth 4 (`is)));\n                (\"rw_1\", P4Bit value_w 0);\n                (\"rw_2\", P4Bit_ value_w);\n                (\"rw_3\", P4Bit_ value_w);\n                (\"rw_4\", P4Bit_ value_w);\n                (\"rw_5\", P4Bit_ value_w)\n               ]\n          else if op =? INSERT then\n             ValBaseStruct\n               [(\"api\", P4Bit 8 INSERT);\n                (\"index_1\", P4Bit index_w (Znth 0 (`is)));\n                (\"index_2\", P4Bit index_w (Znth 1 (`is)));\n                (\"index_3\", P4Bit index_w (Znth 2 (`is)));\n                (\"index_4\", P4Bit index_w (Znth 3 (`is)));\n                (\"index_5\", P4Bit index_w (Znth 4 (`is)));\n                (\"rw_1\", P4Bit_ value_w);\n                (\"rw_2\", P4Bit_ value_w);\n                (\"rw_3\", P4Bit_ value_w);\n                (\"rw_4\", P4Bit_ value_w);\n                (\"rw_5\", P4Bit_ value_w)\n               ]\n          else\n             ValBaseStruct\n               [(\"api\", P4Bit 8 QUERY);\n                (\"index_1\", P4Bit index_w (Znth 0 (`is)));\n                (\"index_2\", P4Bit index_w (Znth 1 (`is)));\n                (\"index_3\", P4Bit index_w (Znth 2 (`is)));\n                (\"index_4\", P4Bit index_w (Znth 3 (`is)));\n                (\"index_5\", P4Bit index_w (Znth 4 (`is)));\n                (\"rw_1\", P4Bit value_w (Z.min (frame_query f (`is)) (2 ^ 32 - 1)));\n                (\"rw_2\", P4Bit_ value_w);\n                (\"rw_3\", P4Bit_ value_w);\n                (\"rw_4\", P4Bit_ value_w);\n                (\"rw_5\", P4Bit_ value_w)\n               ]\n        ] ValBaseNull\n        (MEM []\n        (EXT [frame_repr p rows (\n          if op =? NOOP then\n            f\n          else if op =? CLEAR then\n            frame_clear f is\n          else if op =? INSERT then\n            frame_insert f is\n          else\n            f\n        )]))).\n\nLemma Win_body :\n  func_sound ge Win_fundef nil Win_spec.\nProof.\n  intros_fs_bind.\n  split; only 2 : solve_modifies.\n  intros_fsh_bind.\n  destruct H.\n  { subst.\n    apply Win_noop_body; auto.\n  }\n  destruct H.\n  { subst.\n    apply Win_clear_body; auto.\n  }\n  destruct H.\n  { subst.\n    apply Win_insert_body; auto.\n  }\n  destruct H.\n  { subst.\n    apply Win_query_body; auto.\n  }\n  destruct H.\nQed.\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/cms/verif_Win_lazy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2624082661398747}}
{"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\nRequire Export atoms2.\nRequire Export computation_seq.\nRequire Export continuity_defs.\n(*Require Export list.  (* why?? *)*)\n\n\nInductive differ2 {o} (b : nat) : @NTerm o -> @NTerm o -> Type :=\n| differ2_force_int :\n    forall t1 t2 v,\n      differ2 b t1 t2\n      -> differ2 b (force_int_bound v b t1 (mk_vbot v)) (force_int t2)\n| differ2_var :\n    forall v, differ2 b (mk_var v) (mk_var v)\n| differ2_sterm :\n    forall f, differ2 b (sterm f) (sterm f)\n| differ2_oterm :\n    forall op bs1 bs2,\n      length bs1 = length bs2\n      -> (forall b1 b2, LIn (b1,b2) (combine bs1 bs2) -> differ2_b b b1 b2)\n      -> differ2 b (oterm op bs1) (oterm op bs2)\nwith differ2_b {o} (b : nat) : @BTerm o -> @BTerm o -> Type :=\n     | differ2_bterm :\n         forall vs t1 t2,\n           differ2 b t1 t2\n           -> differ2_b b (bterm vs t1) (bterm vs t2).\nHint Constructors differ2 differ2_b.\n\nDefinition differ2_alpha {o} b (t1 t2 : @NTerm o) :=\n  {u1 : NTerm\n   & {u2 : NTerm\n      & alpha_eq t1 u1\n      # alpha_eq t2 u2\n      # differ2 b u1 u2}}.\n\nDefinition differ2_implies_differ2_alpha {o} :\n  forall b (t1 t2 : @NTerm o),\n    differ2 b t1 t2 -> differ2_alpha b t1 t2.\nProof.\n  introv d.\n  exists t1 t2; auto.\nQed.\nHint Resolve differ2_implies_differ2_alpha : slow.\n\nInductive differ2_subs {o} b : @Sub o -> @Sub o -> Type :=\n| dsub_nil : differ2_subs b [] []\n| dsub_cons :\n    forall v t1 t2 sub1 sub2,\n      differ2 b t1 t2\n      -> differ2_subs b sub1 sub2\n      -> differ2_subs b ((v,t1) :: sub1) ((v,t2) :: sub2).\nHint Constructors differ2_subs.\n\nDefinition differ2_bterms {o} b (bs1 bs2 : list (@BTerm o)) :=\n  br_bterms (differ2_b b) bs1 bs2.\n\nLemma differ2_subs_sub_find_some {o} :\n  forall b (sub1 sub2 : @Sub o) v t,\n    differ2_subs b sub1 sub2\n    -> sub_find sub1 v = Some t\n    -> {u : NTerm & sub_find sub2 v = Some u # differ2 b t u}.\nProof.\n  induction sub1; destruct sub2; introv d f; allsimpl; tcsp;\n  inversion d; subst.\n  boolvar; cpx.\n  eexists; eauto.\nQed.\n\nLemma differ2_subs_sub_find_none {o} :\n  forall b (sub1 sub2 : @Sub o) v,\n    differ2_subs b sub1 sub2\n    -> sub_find sub1 v = None\n    -> sub_find sub2 v = None.\nProof.\n  induction sub1; destruct sub2; introv d f; allsimpl; tcsp;\n  inversion d; subst.\n  boolvar; cpx.\nQed.\n\nLemma differ2_subs_filter {o} :\n  forall b (sub1 sub2 : @Sub o) l,\n    differ2_subs b sub1 sub2\n    -> differ2_subs b (sub_filter sub1 l) (sub_filter sub2 l).\nProof.\n  induction sub1; destruct sub2; introv d; allsimpl; inversion d; auto.\n  boolvar; sp.\nQed.\n\nLemma differ2_lsubst_aux {o} :\n  forall b (t1 t2 : @NTerm o) sub1 sub2,\n    differ2 b t1 t2\n    -> differ2_subs b sub1 sub2\n    -> disjoint (bound_vars t1) (sub_free_vars sub1)\n    -> disjoint (bound_vars t2) (sub_free_vars sub2)\n    -> differ2 b (lsubst_aux t1 sub1) (lsubst_aux t2 sub2).\nProof.\n  nterm_ind t1 as [v|f ind|op bs ind] Case;\n  introv dt ds disj1 disj2; allsimpl; auto.\n\n  - Case \"vterm\".\n    inversion dt; subst; allsimpl.\n    remember (sub_find sub1 v) as f1; symmetry in Heqf1; destruct f1.\n\n    + applydup (differ2_subs_sub_find_some b sub1 sub2) in Heqf1; auto.\n      exrepnd; allrw; auto.\n\n    + applydup (differ2_subs_sub_find_none b sub1 sub2) in Heqf1; auto.\n      allrw; auto.\n\n  - Case \"sterm\".\n    inversion dt; subst; allsimpl; auto.\n\n  - Case \"oterm\".\n    inversion dt as [|?|?|? ? ? len imp]; subst; allsimpl.\n\n    + allrw @sub_filter_nil_r.\n      allrw app_nil_r.\n      allrw disjoint_app_l; allrw disjoint_cons_l; allrw disjoint_app_l; repnd; GC.\n      repeat (rw @sub_find_sub_filter; simpl; tcsp).\n      fold_terms.\n      apply differ2_force_int.\n\n      apply (ind t1 []); auto.\n\n    + apply differ2_oterm; allrw map_length; auto.\n\n      introv i.\n      rw <- @map_combine in i.\n      rw in_map_iff in i; exrepnd; cpx; allsimpl.\n      applydup imp in i1.\n      destruct a0 as [l1 t1].\n      destruct a as [l2 t2].\n      applydup in_combine in i1; repnd.\n      allsimpl.\n      inversion i0 as [? ? ? d]; subst; clear i0.\n      constructor.\n      apply (ind t1 l2); auto.\n\n      * apply differ2_subs_filter; auto.\n\n      * pose proof (subvars_sub_free_vars_sub_filter sub1 l2) as sv.\n        disj_flat_map.\n        allsimpl; allrw disjoint_app_l; repnd.\n        eapply subvars_disjoint_r; eauto.\n\n      * pose proof (subvars_sub_free_vars_sub_filter sub2 l2) as sv.\n        disj_flat_map.\n        allsimpl; allrw disjoint_app_l; repnd.\n        eapply subvars_disjoint_r; eauto.\nQed.\n\nLemma differ2_refl {o} :\n  forall b (t : @NTerm o),\n    differ2 b t t.\nProof.\n  nterm_ind t as [v|f ind|op bs ind] Case; auto.\n\n  Case \"oterm\".\n  apply differ2_oterm; auto.\n  introv i.\n  rw in_combine_same in i; repnd; subst.\n  destruct b2 as [l t].\n  constructor.\n  eapply ind; eauto.\nQed.\nHint Resolve differ2_refl : slow.\n\nLemma differ2_subs_refl {o} :\n  forall b (sub : @Sub o),\n    differ2_subs b sub sub.\nProof.\n  induction sub; auto.\n  destruct a.\n  constructor; eauto 3 with slow.\nQed.\nHint Resolve differ2_subs_refl : slow.\n\nLemma differ2_change_bound_vars {o} :\n  forall b vs (t1 t2 : @NTerm o),\n    differ2 b t1 t2\n    -> {u1 : NTerm\n        & {u2 : NTerm\n           & differ2 b u1 u2\n           # alpha_eq t1 u1\n           # alpha_eq t2 u2\n           # disjoint (bound_vars u1) vs\n           # disjoint (bound_vars u2) vs}}.\nProof.\n  nterm_ind t1 as [v|f ind|op bs ind] Case; introv d; auto.\n\n  - Case \"vterm\".\n    inversion d; subst.\n    exists (@mk_var o v) (@mk_var o v); simpl; dands; eauto 3 with slow.\n\n  - Case \"sterm\".\n    inversion d; subst; clear d.\n    exists (sterm f) (sterm f); simpl; dands; auto.\n\n  - Case \"oterm\".\n    inversion d as [? ? ? d1|?|?|? ? ? len imp]; subst; simphyps; cpx; ginv; clear d.\n\n    + pose proof (ex_fresh_var vs) as h; exrepnd.\n      pose proof (ind t1 []) as h; repeat (autodimp h hyp).\n      pose proof (h t0 d1) as k; clear h; exrepnd.\n\n      fold_terms.\n\n      exists\n        (mk_cbv u1 v0 (less_bound b (mk_var v0) (mk_vbot v0)))\n        (force_int u2); dands; auto.\n\n      * apply differ2_force_int; auto.\n\n      * apply alpha_eq_force_int_bound; simpl; tcsp;\n        allrw remove_nvars_eq; allsimpl; tcsp; eauto 3 with slow.\n\n      * apply alpha_eq_force_int; auto.\n\n      * simpl; allrw app_nil_r.\n        rw disjoint_app_l; rw disjoint_cons_l; dands; eauto 3 with slow.\n        rw disjoint_singleton_l; auto.\n\n      * simpl; allrw app_nil_r; eauto 3 with slow.\n\n    + assert ({bs' : list BTerm\n               & {bs2' : list BTerm\n                  & alpha_eq_bterms bs bs'\n                  # alpha_eq_bterms bs2 bs2'\n                  # differ2_bterms b bs' bs2'\n                  # disjoint (flat_map bound_vars_bterm bs') vs\n                  # disjoint (flat_map bound_vars_bterm bs2') vs}}) as h.\n\n      { revert dependent bs2.\n        induction bs; destruct bs2; introv len imp; allsimpl; ginv.\n        - exists ([] : list (@BTerm o)) ([] : list (@BTerm o));\n            dands; simpl; eauto 3 with slow; try (apply br_bterms_nil).\n        - cpx.\n          destruct a as [l1 t1].\n          destruct b0 as [l2 t2].\n          pose proof (imp (bterm l1 t1) (bterm l2 t2)) as h; autodimp h hyp.\n          inversion h as [? ? ? d1]; subst; clear h.\n          pose proof (ind t1 l2) as h; autodimp h hyp.\n          pose proof (h t2 d1) as k; clear h.\n          exrepnd.\n\n          autodimp IHbs hyp.\n          { introv i d; eapply ind; eauto. }\n          pose proof (IHbs bs2) as k.\n          repeat (autodimp k hyp).\n          exrepnd.\n\n          pose proof (fresh_vars\n                        (length l2)\n                        (vs\n                           ++ l2\n                           ++ all_vars t1\n                           ++ all_vars t2\n                           ++ all_vars u1\n                           ++ all_vars u2\n                        )) as fv; exrepnd.\n          allrw disjoint_app_r; repnd.\n\n          exists ((bterm lvn (lsubst_aux u1 (var_ren l2 lvn))) :: bs')\n                 ((bterm lvn (lsubst_aux u2 (var_ren l2 lvn))) :: bs2');\n            dands; simpl;\n            try (apply br_bterms_cons);\n            try (apply alpha_eq_bterm_congr);\n            tcsp.\n          { apply alpha_bterm_change_aux; eauto 3 with slow.\n            allrw disjoint_app_l; dands; eauto 3 with slow. }\n          { apply alpha_bterm_change_aux; eauto 3 with slow.\n            allrw disjoint_app_l; dands; eauto 3 with slow. }\n          { apply differ2_bterm.\n            apply differ2_lsubst_aux; eauto 3 with slow;\n            rw @sub_free_vars_var_ren; eauto 3 with slow. }\n          { allrw disjoint_app_l; dands; eauto 3 with slow.\n            pose proof (subvars_bound_vars_lsubst_aux\n                          u1 (var_ren l2 lvn)) as sv.\n            eapply subvars_disjoint_l;[exact sv|].\n            apply disjoint_app_l; dands; auto.\n            rw @sub_bound_vars_var_ren; auto. }\n          { allrw disjoint_app_l; dands; eauto 3 with slow.\n            pose proof (subvars_bound_vars_lsubst_aux\n                          u2 (var_ren l2 lvn)) as sv.\n            eapply subvars_disjoint_l;[exact sv|].\n            apply disjoint_app_l; dands; auto.\n            rw @sub_bound_vars_var_ren; auto. }\n      }\n\n      exrepnd.\n      allunfold @alpha_eq_bterms.\n      allunfold @differ2_bterms.\n      allunfold @br_bterms.\n      allunfold @br_list; repnd.\n      exists (oterm op bs') (oterm op bs2'); dands; eauto 3 with slow.\n\n      * apply alpha_eq_oterm_combine; dands; auto.\n\n      * apply alpha_eq_oterm_combine; dands; auto.\nQed.\n\nLemma differ2_subst {o} :\n  forall b (t1 t2 : @NTerm o) sub1 sub2,\n    differ2 b t1 t2\n    -> differ2_subs b sub1 sub2\n    -> differ2_alpha b (lsubst t1 sub1) (lsubst t2 sub2).\nProof.\n  introv dt ds.\n\n  pose proof (unfold_lsubst sub1 t1) as h; exrepnd.\n  pose proof (unfold_lsubst sub2 t2) as k; exrepnd.\n  rw h0; rw k0.\n\n  pose proof (differ2_change_bound_vars\n                b (sub_free_vars sub1 ++ sub_free_vars sub2)\n                t1 t2 dt) as d; exrepnd.\n  allrw disjoint_app_r; repnd.\n\n  exists (lsubst_aux u1 sub1) (lsubst_aux u2 sub2); dands; auto.\n\n  - apply lsubst_aux_alpha_congr2; eauto 3 with slow.\n\n  - apply lsubst_aux_alpha_congr2; eauto 3 with slow.\n\n  - apply differ2_lsubst_aux; auto.\nQed.\nHint Resolve differ2_subst : slow.\n\nDefinition differ2_sk {o} b (sk1 sk2 : @sosub_kind o) :=\n  differ2_b b (sk2bterm sk1) (sk2bterm sk2).\n\nInductive differ2_sosubs {o} b : @SOSub o -> @SOSub o -> Type :=\n| dsosub2_nil : differ2_sosubs b [] []\n| dsosub2_cons :\n    forall v sk1 sk2 sub1 sub2,\n      differ2_sk b sk1 sk2\n      -> differ2_sosubs b sub1 sub2\n      -> differ2_sosubs b ((v,sk1) :: sub1) ((v,sk2) :: sub2).\nHint Constructors differ2_sosubs.\n\nLemma differ2_bterms_implies_eq_map_num_bvars {o} :\n  forall b (bs1 bs2 : list (@BTerm o)),\n    differ2_bterms b bs1 bs2\n    -> map num_bvars bs1 = map num_bvars bs2.\nProof.\n  induction bs1; destruct bs2; introv d; allsimpl; auto;\n  allunfold @differ2_bterms; allunfold @br_bterms; allunfold @br_list;\n  allsimpl; repnd; cpx.\n  pose proof (d a b0) as h; autodimp h hyp.\n  inversion h; subst.\n  f_equal.\n  unfold num_bvars; simpl; auto.\nQed.\n\nLemma differ2_bterms_cons {o} :\n  forall b (b1 b2 : @BTerm o) bs1 bs2,\n    differ2_bterms b (b1 :: bs1) (b2 :: bs2)\n    <=> (differ2_b b b1 b2 # differ2_bterms b bs1 bs2).\nProof.\n  unfold differ2_bterms; introv.\n  rw @br_bterms_cons_iff; sp.\nQed.\n\nLemma differ2_mk_abs_substs {o} :\n  forall b (bs1 bs2 : list (@BTerm o)) vars,\n    differ2_bterms b bs1 bs2\n    -> length vars = length bs1\n    -> differ2_sosubs b (mk_abs_subst vars bs1) (mk_abs_subst vars bs2).\nProof.\n  induction bs1; destruct bs2; destruct vars; introv d m; allsimpl; cpx; tcsp.\n  - provefalse.\n    apply differ2_bterms_implies_eq_map_num_bvars in d; allsimpl; cpx.\n  - apply differ2_bterms_cons in d; repnd.\n    destruct s, a, b0.\n    inversion d0; subst.\n    boolvar; auto.\nQed.\n\nLemma differ2_b_change_bound_vars {o} :\n  forall b vs (b1 b2 : @BTerm o),\n    differ2_b b b1 b2\n    -> {u1 : BTerm\n        & {u2 : BTerm\n           & differ2_b b u1 u2\n           # alpha_eq_bterm b1 u1\n           # alpha_eq_bterm b2 u2\n           # disjoint (bound_vars_bterm u1) vs\n           # disjoint (bound_vars_bterm u2) vs}}.\nProof.\n  introv d.\n  pose proof (differ2_change_bound_vars\n                b vs (oterm Exc [b1]) (oterm Exc [b2])) as h.\n  autodimp h hyp.\n  - apply differ2_oterm; simpl; auto.\n    introv i; dorn i; tcsp; cpx.\n  - exrepnd.\n    inversion h2 as [|?|? ? ? len1 imp1]; subst; allsimpl; cpx.\n    inversion h3 as [|?|? ? ? len2 imp2]; subst; allsimpl; cpx.\n    pose proof (imp1 0) as k1; autodimp k1 hyp; allsimpl; clear imp1.\n    pose proof (imp2 0) as k2; autodimp k2 hyp; allsimpl; clear imp2.\n    allunfold @selectbt; allsimpl.\n    allrw app_nil_r.\n    exists x x0; dands; auto.\n    inversion h0 as [|?|?|? ? ? ? i]; subst; allsimpl; GC.\n    apply i; sp.\nQed.\n\nLemma differ2_sk_change_bound_vars {o} :\n  forall b vs (sk1 sk2 : @sosub_kind o),\n    differ2_sk b sk1 sk2\n    -> {u1 : sosub_kind\n        & {u2 : sosub_kind\n           & differ2_sk b u1 u2\n           # alphaeq_sk sk1 u1\n           # alphaeq_sk sk2 u2\n           # disjoint (bound_vars_sk u1) vs\n           # disjoint (bound_vars_sk u2) vs}}.\nProof.\n  introv d.\n  unfold differ2_sk in d.\n  apply (differ2_b_change_bound_vars b vs) in d; exrepnd; allsimpl.\n  exists (bterm2sk u1) (bterm2sk u2).\n  destruct u1, u2, sk1, sk2; allsimpl; dands; auto;\n  apply alphaeq_sk_iff_alphaeq_bterm2; simpl; auto.\nQed.\n\nLemma differ2_sosubs_change_bound_vars {o} :\n  forall b vs (sub1 sub2 : @SOSub o),\n    differ2_sosubs b sub1 sub2\n    -> {sub1' : SOSub\n        & {sub2' : SOSub\n           & differ2_sosubs b sub1' sub2'\n           # alphaeq_sosub sub1 sub1'\n           # alphaeq_sosub sub2 sub2'\n           # disjoint (bound_vars_sosub sub1') vs\n           # disjoint (bound_vars_sosub sub2') vs}}.\nProof.\n  induction sub1; destruct sub2; introv d.\n  - exists ([] : @SOSub o) ([] : @SOSub o); dands; simpl; tcsp.\n  - inversion d.\n  - inversion d.\n  - inversion d as [|? ? ? ? ? dsk dso]; subst; clear d.\n    apply IHsub1 in dso; exrepnd.\n    apply (differ2_sk_change_bound_vars b vs) in dsk; exrepnd.\n    exists ((v,u1) :: sub1') ((v,u2) :: sub2'); dands; simpl; auto;\n    allrw disjoint_app_l; dands; eauto 3 with slow.\nQed.\n\nLemma sosub_find_some_if_differ2_sosubs {o} :\n  forall b (sub1 sub2 : @SOSub o) v sk,\n    differ2_sosubs b sub1 sub2\n    -> sosub_find sub1 v = Some sk\n    -> {sk' : sosub_kind & differ2_sk b sk sk' # sosub_find sub2 v = Some sk'}.\nProof.\n  induction sub1; destruct sub2; introv aeq sf; allsimpl; tcsp.\n  - inversion aeq.\n  - destruct a, p; destruct s, s0.\n    inversion aeq as [|? ? ? ? ? dsk dso]; subst; clear aeq.\n    boolvar; subst; cpx; tcsp.\n    + eexists; dands; eauto.\n    + inversion dsk; subst; tcsp.\n    + inversion dsk; subst; tcsp.\nQed.\n\nLemma sosub_find_none_if_differ2_sosubs {o} :\n  forall b (sub1 sub2 : @SOSub o) v,\n    differ2_sosubs b sub1 sub2\n    -> sosub_find sub1 v = None\n    -> sosub_find sub2 v = None.\nProof.\n  induction sub1; destruct sub2; introv aeq sf; allsimpl; tcsp.\n  - inversion aeq.\n  - destruct a, p; destruct s, s0.\n    inversion aeq as [|? ? ? ? ? dsk dso]; subst; clear aeq.\n    boolvar; subst; cpx; tcsp.\n    inversion dsk; subst; tcsp.\nQed.\n\nLemma differ2_subs_combine {o} :\n  forall b (ts1 ts2 : list (@NTerm o)) vs,\n    length ts1 = length ts2\n    -> (forall t1 t2,\n          LIn (t1,t2) (combine ts1 ts2)\n          -> differ2 b t1 t2)\n    -> differ2_subs b (combine vs ts1) (combine vs ts2).\nProof.\n  induction ts1; destruct ts2; destruct vs; introv len imp; allsimpl; cpx; tcsp.\nQed.\n\nLemma differ2_apply_list {o} :\n  forall b (ts1 ts2 : list (@NTerm o)) t1 t2,\n    differ2 b t1 t2\n    -> length ts1 = length ts2\n    -> (forall x y, LIn (x,y) (combine ts1 ts2) -> differ2 b x y)\n    -> differ2 b (apply_list t1 ts1) (apply_list t2 ts2).\nProof.\n  induction ts1; destruct ts2; introv d l i; allsimpl; cpx.\n  apply IHts1; auto.\n  apply differ2_oterm; simpl; auto.\n  introv k.\n  dorn k;[|dorn k]; cpx; constructor; auto.\nQed.\n\nLemma differ2_sosub_filter {o} :\n  forall b (sub1 sub2 : @SOSub o) vs,\n    differ2_sosubs b sub1 sub2\n    -> differ2_sosubs b (sosub_filter sub1 vs) (sosub_filter sub2 vs).\nProof.\n  induction sub1; destruct sub2; introv d;\n  inversion d as [|? ? ? ? ? dsk dso]; subst; auto.\n  destruct sk1, sk2; allsimpl.\n  inversion dsk; subst.\n  boolvar; tcsp.\nQed.\nHint Resolve differ2_sosub_filter : slow.\n\nLemma differ2_sosub_aux {o} :\n  forall b (t : @SOTerm o) sub1 sub2,\n    differ2_sosubs b sub1 sub2\n    -> disjoint (fo_bound_vars t) (free_vars_sosub sub1)\n    -> disjoint (free_vars_sosub sub1) (bound_vars_sosub sub1)\n    -> disjoint (all_fo_vars t) (bound_vars_sosub sub1)\n    -> disjoint (fo_bound_vars t) (free_vars_sosub sub2)\n    -> disjoint (free_vars_sosub sub2) (bound_vars_sosub sub2)\n    -> disjoint (all_fo_vars t) (bound_vars_sosub sub2)\n    -> cover_so_vars t sub1\n    -> cover_so_vars t sub2\n    -> differ2 b (sosub_aux sub1 t) (sosub_aux sub2 t).\nProof.\n  soterm_ind t as [v ts ind| |op bs ind] Case;\n  introv ds disj1 disj2 disj3 disj4 disj5 disj6 cov1 cov2; allsimpl; auto.\n\n  - Case \"sovar\".\n    allrw @cover_so_vars_sovar; repnd.\n    allrw disjoint_cons_l; repnd.\n    remember (sosub_find sub1 (v, length ts)) as f1; symmetry in Heqf1.\n    destruct f1.\n\n    + applydup (sosub_find_some_if_differ2_sosubs b sub1 sub2) in Heqf1; auto.\n      exrepnd.\n      rw Heqf2.\n      destruct s as [l1 t1].\n      destruct sk' as [l2 t2].\n      inversion Heqf0; subst.\n      apply differ2_lsubst_aux; auto.\n\n      * apply differ2_subs_combine; allrw map_length; 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; allsimpl.\n        disj_flat_map.\n        apply ind; auto.\n\n      * apply sosub_find_some in Heqf1; repnd.\n        rw @sub_free_vars_combine; allrw map_length; auto.\n        rw flat_map_map; unfold compose.\n        eapply disjoint_bound_vars_prop3; eauto 3 with slow.\n        eapply subvars_disjoint_r;[|apply disjoint_sym;eauto].\n        apply subvars_flat_map2; introv i.\n        apply fovars_subvars_all_fo_vars.\n\n      * apply sosub_find_some in Heqf2; repnd.\n        rw @sub_free_vars_combine; allrw map_length; auto.\n        rw flat_map_map; unfold compose.\n        eapply disjoint_bound_vars_prop3; eauto 3 with slow.\n        eapply subvars_disjoint_r;[|apply disjoint_sym;eauto].\n        apply subvars_flat_map2; introv i.\n        apply fovars_subvars_all_fo_vars.\n\n    + applydup (sosub_find_none_if_differ2_sosubs b sub1 sub2) in Heqf1; auto.\n      rw Heqf0.\n      apply differ2_apply_list; allrw map_length; auto.\n      introv i.\n      rw <- @map_combine in i; rw in_map_iff in i; exrepnd; cpx.\n      apply in_combine_same in i1; repnd; subst; allsimpl.\n      disj_flat_map.\n      apply ind; auto.\n\n  - Case \"soterm\".\n    allrw @cover_so_vars_soterm.\n    apply differ2_oterm; allrw map_length; auto.\n    introv i.\n    rw <- @map_combine in i; rw in_map_iff in i; exrepnd; cpx.\n    apply in_combine_same in i1; repnd; subst; allsimpl.\n    destruct a as [l t].\n    disj_flat_map.\n    allsimpl; allrw disjoint_app_l; repnd.\n    constructor.\n    eapply ind; eauto 3 with slow.\n\n    + pose proof (subvars_free_vars_sosub_sosub_filter sub1 (vars2sovars l)) as sv.\n      eapply subvars_disjoint_r;[exact sv|]; auto.\n\n    + pose proof (subvars_free_vars_sosub_sosub_filter sub1 (vars2sovars l)) as sv1.\n      pose proof (subvars_bound_vars_sosub_filter sub1 (vars2sovars l)) as sv2.\n      eapply subvars_disjoint_r;[exact sv2|]; auto.\n      eapply subvars_disjoint_l;[exact sv1|]; auto.\n\n    + pose proof (subvars_bound_vars_sosub_filter sub1 (vars2sovars l)) as sv1.\n      eapply subvars_disjoint_r;[exact sv1|]; auto.\n\n    + pose proof (subvars_free_vars_sosub_sosub_filter sub2 (vars2sovars l)) as sv1.\n      eapply subvars_disjoint_r;[exact sv1|]; auto.\n\n    + pose proof (subvars_free_vars_sosub_sosub_filter sub2 (vars2sovars l)) as sv1.\n      pose proof (subvars_bound_vars_sosub_filter sub2 (vars2sovars l)) as sv2.\n      eapply subvars_disjoint_r;[exact sv2|]; auto.\n      eapply subvars_disjoint_l;[exact sv1|]; auto.\n\n    + pose proof (subvars_bound_vars_sosub_filter sub2 (vars2sovars l)) as sv1.\n      eapply subvars_disjoint_r;[exact sv1|]; auto.\n\n    + discover.\n      apply cover_so_vars_sosub_filter; auto.\n\n    + discover.\n      apply cover_so_vars_sosub_filter; auto.\nQed.\n\nLemma differ2_sosub {o} :\n  forall b (t : @SOTerm o) (sub1 sub2 : SOSub),\n    differ2_sosubs b sub1 sub2\n    -> cover_so_vars t sub1\n    -> cover_so_vars t sub2\n    -> differ2_alpha b (sosub sub1 t) (sosub sub2 t).\nProof.\n  introv d c1 c2.\n  pose proof (unfold_sosub sub1 t) as h.\n  destruct h as [sub1' h]; destruct h as [t1 h]; repnd; rw h.\n  pose proof (unfold_sosub sub2 t) as k.\n  destruct k as [sub2' k]; destruct k as [t2 k]; repnd; rw k.\n\n  pose proof (differ2_sosubs_change_bound_vars\n                b\n                (all_fo_vars t1\n                             ++ all_fo_vars t2\n                             ++ free_vars_sosub sub1\n                             ++ free_vars_sosub sub2\n                )\n                sub1 sub2\n                d) as e.\n  destruct e as [sub1'' e]; destruct e as [sub2'' e]; repnd.\n\n  pose proof (fo_change_bvars_alpha_spec\n                (free_vars_sosub sub1''\n                                 ++ free_vars_sosub sub2''\n                                 ++ bound_vars_sosub sub1''\n                                 ++ bound_vars_sosub sub2''\n                )\n                t) as q.\n  revert q.\n  fo_change t0; simpl; intro q; repnd; GC.\n\n  allrw disjoint_app_l; allrw disjoint_app_r; repnd.\n\n  assert (so_alphaeq t1 t0) as a1 by eauto 3 with slow.\n  assert (so_alphaeq t2 t0) as a2 by eauto 3 with slow.\n\n  pose proof (fovars_subvars_all_fo_vars t1) as sv1.\n  pose proof (fovars_subvars_all_fo_vars t2) as sv2.\n  pose proof (alphaeq_sosub_preserves_free_vars sub1 sub1'') as ev1; autodimp ev1 hyp.\n  pose proof (alphaeq_sosub_preserves_free_vars sub2 sub2'') as ev2; autodimp ev2 hyp.\n  pose proof (fovars_subvars_all_fo_vars t0) as sv3.\n  pose proof (all_fo_vars_eqvars t0) as ev3.\n  pose proof (all_fo_vars_eqvars t1) as ev4.\n  pose proof (so_alphaeq_preserves_free_vars t1 t0 a1) as efv1.\n  pose proof (so_alphaeq_preserves_free_vars t2 t0 a2) as efv2.\n  applydup eqvars_app_r_implies_subvars in ev4 as ev; destruct ev as [ev5 ev6].\n\n  assert (disjoint (fo_bound_vars t0) (free_vars_sosub sub1'')\n          # disjoint (free_vars_sosub sub1'') (bound_vars_sosub sub1'')\n          # disjoint (all_fo_vars t0) (bound_vars_sosub sub1'')\n          # disjoint (fo_bound_vars t0) (free_vars_sosub sub2'')\n          # disjoint (free_vars_sosub sub2'') (bound_vars_sosub sub2'')\n          # disjoint (all_fo_vars t0) (bound_vars_sosub sub2'')) as disj.\n\n  { dands; eauto 3 with slow.\n    - rw <- ev1; eauto 3 with slow.\n    - eapply eqvars_disjoint;[apply eqvars_sym; exact ev3|].\n      apply disjoint_app_l; dands; eauto 3 with slow.\n      rw <- efv1.\n      eapply subvars_disjoint_l;[exact ev6|]; eauto 3 with slow.\n    - rw <- ev2; eauto 3 with slow.\n    - eapply eqvars_disjoint;[apply eqvars_sym; exact ev3|].\n      apply disjoint_app_l; dands; eauto 3 with slow.\n      rw <- efv1.\n      eapply subvars_disjoint_l;[exact ev6|]; eauto 3 with slow. }\n\n  repnd.\n\n  pose proof (sosub_aux_alpha_congr2\n                t1 t0 sub1' sub1'') as aeq1.\n  repeat (autodimp aeq1 hyp); eauto 3 with slow.\n\n  { rw disjoint_app_r; dands; eauto 3 with slow. }\n\n  { rw disjoint_app_r; dands; eauto 3 with slow. }\n\n  pose proof (sosub_aux_alpha_congr2\n                t2 t0 sub2' sub2'') as aeq2.\n  repeat (autodimp aeq2 hyp); eauto 3 with slow.\n\n  { rw disjoint_app_r; dands; eauto 3 with slow. }\n\n  { rw disjoint_app_r; dands; eauto 3 with slow. }\n\n  exists (sosub_aux sub1'' t0) (sosub_aux sub2'' t0); dands;\n  try (apply alphaeq_eq; complete auto).\n\n  apply differ2_sosub_aux; auto.\n\n  { apply (cover_so_vars_if_alphaeq_sosub t0 sub1 sub1''); auto.\n    apply (cover_so_vars_if_so_alphaeq t t0 sub1); auto. }\n\n  { apply (cover_so_vars_if_alphaeq_sosub t0 sub2 sub2''); auto.\n    apply (cover_so_vars_if_so_alphaeq t t0 sub2); auto. }\nQed.\n\nLemma differ2_mk_instance {o} :\n  forall b (t : @SOTerm o) vars bs1 bs2,\n    matching_bterms vars bs1\n    -> matching_bterms vars bs2\n    -> socovered t vars\n    -> socovered t vars\n    -> differ2_bterms b bs1 bs2\n    -> differ2_alpha b (mk_instance vars bs1 t) (mk_instance vars bs2 t).\nProof.\n  introv m1 m2 sc1 sc2 dbs.\n  unfold mk_instance.\n  applydup @matching_bterms_implies_eq_length in m1.\n  applydup (@differ2_mk_abs_substs o b bs1 bs2 vars) in dbs; auto.\n\n  apply differ2_sosub; auto;\n  apply socovered_implies_cover_so_vars; auto.\nQed.\n\nLemma implies_differ2_alpha_force_int {o} :\n  forall v b (t1 t2 : @NTerm o),\n    differ2_alpha b t1 t2\n    -> differ2_alpha b (force_int_bound v b t1 (mk_vbot v)) (force_int t2).\nProof.\n  introv d.\n  unfold differ2_alpha in d; exrepnd.\n  exists (force_int_bound v b u1 (mk_vbot v)) (force_int u2); dands.\n  - apply alpha_eq_force_int_bound; allsimpl; tcsp;\n    allrw remove_nvars_eq; sp.\n  - apply alpha_eq_force_int; auto.\n  - apply differ2_force_int; auto.\nQed.\n\nLemma differ2_alpha_mk_atom_eq {o} :\n  forall b (a1 a2 b1 b2 c1 c2 d1 d2 : @NTerm o),\n    differ2_alpha b a1 a2\n    -> differ2_alpha b b1 b2\n    -> differ2_alpha b c1 c2\n    -> differ2_alpha b d1 d2\n    -> differ2_alpha b (mk_atom_eq a1 b1 c1 d1) (mk_atom_eq a2 b2 c2 d2).\nProof.\n  introv da1 da2 da3 da4.\n  allunfold @differ2_alpha; exrepnd.\n  exists (mk_atom_eq u6 u4 u0 u1) (mk_atom_eq u7 u5 u3 u2); dands; auto.\n  - apply alpha_eq_oterm_combine; simpl; dands; auto.\n    introv i; repndors; cpx; auto; apply alphaeqbt_nilv2; auto.\n  - apply alpha_eq_oterm_combine; simpl; dands; auto.\n    introv i; repndors; cpx; auto; apply alphaeqbt_nilv2; auto.\n  - constructor; simpl; auto.\n    introv i; repndors; cpx; constructor; auto.\nQed.\n\nLemma differ2_alpha_mk_eapply {o} :\n  forall b (a1 a2 b1 b2 : @NTerm o),\n    differ2_alpha b a1 a2\n    -> differ2_alpha b b1 b2\n    -> differ2_alpha b (mk_eapply a1 b1) (mk_eapply a2 b2).\nProof.\n  introv da1 da2.\n  allunfold @differ2_alpha; exrepnd.\n  exists (mk_eapply u0 u1) (mk_eapply u3 u2); dands; auto.\n  - apply alpha_eq_oterm_combine; simpl; dands; auto.\n    introv i; repndors; cpx; auto; apply alphaeqbt_nilv2; auto.\n  - apply alpha_eq_oterm_combine; simpl; dands; auto.\n    introv i; repndors; cpx; auto; apply alphaeqbt_nilv2; auto.\n  - constructor; simpl; auto.\n    introv i; repndors; cpx; constructor; auto.\nQed.\n\nLemma differ2_alpha_mk_exception {o} :\n  forall b (a1 a2 b1 b2 : @NTerm o),\n    differ2_alpha b a1 a2\n    -> differ2_alpha b b1 b2\n    -> differ2_alpha b (mk_exception a1 b1) (mk_exception a2 b2).\nProof.\n  introv da1 da2.\n  allunfold @differ2_alpha; exrepnd.\n  exists (mk_exception u0 u1) (mk_exception u3 u2); dands; auto.\n  - apply alpha_eq_oterm_combine; simpl; dands; auto.\n    introv i; repndors; cpx; auto; apply alphaeqbt_nilv2; auto.\n  - apply alpha_eq_oterm_combine; simpl; dands; auto.\n    introv i; repndors; cpx; auto; apply alphaeqbt_nilv2; auto.\n  - constructor; simpl; auto.\n    introv i; repndors; cpx; constructor; auto.\nQed.\n\nLemma differ2_preserves_isvalue_like {o} :\n  forall b (t1 t2 : @NTerm o),\n    differ2 b t1 t2\n    -> isvalue_like t1\n    -> isvalue_like t2.\nProof.\n  introv d ivl.\n  allunfold @isvalue_like; exrepnd.\n  repndors;[left|right].\n  - apply iscan_implies in ivl; repndors; exrepnd; subst;\n    inversion d; subst; eauto 3 with slow.\n  - apply isexc_implies2 in ivl; exrepnd; subst.\n    inversion d; subst; eauto 3 with slow.\nQed.\n\nDefinition differ2_b_alpha {o} (b : nat) (b1 b2 : @BTerm o) :=\n  {u1 : BTerm\n   & {u2 : BTerm\n      & alpha_eq_bterm b1 u1\n      # alpha_eq_bterm b2 u2\n      # differ2_b b u1 u2}}.\n\nDefinition differ2_bs_alpha {o} b (bs1 bs2 : list (@BTerm o)) :=\n  br_bterms (differ2_b_alpha b) bs1 bs2.\n\nLemma differ2_bterms_nil {o} :\n  forall b, @differ2_bterms o b [] [].\nProof.\n  unfold differ2_bterms, br_bterms, br_list; simpl; sp.\nQed.\nHint Resolve differ2_bterms_nil : slow.\n\nLemma differ2_bterms_cons_if {o} :\n  forall b (b1 b2 : @BTerm o) bs1 bs2,\n    differ2_b b b1 b2\n    -> differ2_bterms b bs1 bs2\n    -> differ2_bterms b (b1 :: bs1) (b2 :: bs2).\nProof.\n  introv d1 d2; apply differ2_bterms_cons; sp.\nQed.\nHint Resolve differ2_bterms_cons_if : slow.\n\nLemma implies_differ2_alpha_oterm {o} :\n  forall b op (bs1 bs2 : list (@BTerm o)),\n    differ2_bs_alpha b bs1 bs2\n    -> differ2_alpha b (oterm op bs1) (oterm op bs2).\nProof.\n  introv diff.\n  unfold differ2_bs_alpha, br_bterms, br_list in diff; repnd.\n\n  assert {bs1' : list BTerm\n          & {bs2' : list BTerm\n          & alpha_eq_bterms bs1 bs1'\n          # alpha_eq_bterms bs2 bs2'\n          # differ2_bterms b bs1' bs2'}} as hbs.\n  { revert dependent bs2.\n    induction bs1; introv len imp; destruct bs2; allsimpl; cpx; GC.\n    - exists ([] : list (@BTerm o)) ([] : list (@BTerm o)); dands; eauto 3 with slow.\n    - pose proof (imp a b0) as h; autodimp h hyp.\n      pose proof (IHbs1 bs2) as k; repeat (autodimp k hyp).\n      exrepnd.\n      unfold differ2_b_alpha in h; exrepnd.\n      exists (u1 :: bs1') (u2 :: bs2'); dands; eauto 3 with slow. }\n\n  exrepnd.\n  applydup @alpha_eq_bterms_implies_same_length in hbs0.\n  applydup @alpha_eq_bterms_implies_same_length in hbs2.\n  exists (oterm op bs1') (oterm op bs2'); dands; auto.\n\n  - apply alpha_eq_oterm_combine; dands; tcsp.\n    introv i; apply hbs0; auto.\n\n  - apply alpha_eq_oterm_combine; dands; tcsp.\n    introv i; apply hbs2; auto.\n\n  - constructor; try omega.\n    introv i; apply hbs1; auto.\nQed.\n\nLemma differ2_alpha_pushdown_fresh_isvalue_like {o} :\n  forall b v (t1 t2 : @NTerm o),\n    isvalue_like t1\n    -> differ2 b t1 t2\n    -> differ2_alpha b (pushdown_fresh v t1) (pushdown_fresh v t2).\nProof.\n  introv ivl d.\n  destruct t1 as [v1|f1|op1 bs1].\n  - inversion d; allsimpl; subst; allsimpl; eauto 3 with slow.\n  - inversion d; subst; clear d; allsimpl; eauto 3 with slow.\n  - inversion d as [? ? d1 d2|?|?|? ? ? len imp d1]; subst; allsimpl; fold_terms; clear d.\n    + unfold isvalue_like in ivl; repndors; inversion ivl.\n    + apply implies_differ2_alpha_oterm.\n      unfold differ2_bs_alpha, br_bterms, br_list.\n      allrw @length_mk_fresh_bterms; dands; auto.\n      introv i.\n      unfold mk_fresh_bterms in i; allrw <- @map_combine; allrw in_map_iff; exrepnd; cpx; allsimpl.\n      applydup imp in i1.\n      destruct a0 as [l1 t1].\n      destruct a as [l2 t2].\n      inversion i0 as [? ? ? d]; subst; clear i0.\n      simpl.\n      unfold maybe_new_var; boolvar.\n\n      * pose proof (ex_fresh_var (all_vars t1 ++ all_vars t2)) as fv; exrepnd.\n        allrw in_app_iff; allrw not_over_or; repnd.\n        exists (bterm l2 (mk_fresh v0 t1)) (bterm l2 (mk_fresh v0 t2)).\n        dands; auto.\n\n        { apply alpha_eq_bterm_congr.\n          apply (implies_alpha_eq_mk_fresh_sub v0); allrw in_app_iff; tcsp.\n          repeat (rw @lsubst_trivial3); allsimpl; auto.\n          - introv i; repndors; tcsp; cpx; allsimpl; allrw disjoint_singleton_l.\n            dands; auto.\n          - introv i; repndors; tcsp; cpx; allsimpl; allrw disjoint_singleton_l.\n            dands; auto.\n            apply newvar_prop. }\n\n        { apply alpha_eq_bterm_congr.\n          apply (implies_alpha_eq_mk_fresh_sub v0); allrw in_app_iff; tcsp.\n          repeat (rw @lsubst_trivial3); allsimpl; auto.\n          - introv i; repndors; tcsp; cpx; allsimpl; allrw disjoint_singleton_l.\n            dands; auto.\n          - introv i; repndors; tcsp; cpx; allsimpl; allrw disjoint_singleton_l.\n            dands; auto.\n            apply newvar_prop. }\n\n        { constructor; constructor; simpl; auto.\n          introv i; repndors; cpx. }\n\n      * exists (bterm l2 (mk_fresh v t1)) (bterm l2 (mk_fresh v t2)).\n        dands; auto.\n        constructor; constructor; auto.\n        introv i; allsimpl; repndors; cpx.\nQed.\n\nLemma differ2_preserves_isnoncan_like {o} :\n  forall (b : nat) (t1 t2 : @NTerm o),\n    differ2 b t1 t2\n    -> isnoncan_like t1\n    -> isnoncan_like t2.\nProof.\n  introv d isn.\n  allunfold @isnoncan_like; exrepnd.\n  repndors;[left|right].\n  - apply isnoncan_implies in isn; exrepnd; subst.\n    inversion d; subst; eauto with slow.\n    unfold force_int, mk_add; eauto with slow.\n  - apply isabs_implies in isn; exrepnd; subst.\n    inversion d; subst; eauto with slow.\nQed.\n\nLemma alphaeq_preserves_hasvalue_like {o} :\n  forall lib (t1 t2 : @NTerm o),\n    nt_wf t1\n    -> alpha_eq t1 t2\n    -> hasvalue_like lib t1\n    -> hasvalue_like lib t2.\nProof.\n  introv wf aeq hv.\n  allunfold @hasvalue_like; exrepnd.\n  eapply reduces_to_alpha in hv1;[|auto|exact aeq]; exrepnd.\n  exists t2'; dands; auto.\n  apply alpha_eq_preserves_isvalue_like in hv2; auto.\nQed.\n\nLemma hasvalue_like_ren_utokens {o} :\n  forall lib (t : @NTerm o) ren,\n    nt_wf t\n    -> no_repeats (range_utok_ren ren)\n    -> disjoint (range_utok_ren ren) (diff (get_patom_deq o) (dom_utok_ren ren) (get_utokens t))\n    -> hasvalue_like lib t\n    -> hasvalue_like lib (ren_utokens ren t).\nProof.\n  introv wf norep disj hvl.\n  allunfold @hasvalue_like; exrepnd.\n  apply (reduces_to_ren_utokens _ _ _ ren) in hvl1; auto.\n  exists (ren_utokens ren v); dands; eauto with slow.\nQed.\n\nLemma differ2_alpha_l {o} :\n  forall b (t1 t2 t3 : @NTerm o),\n    alpha_eq t1 t2\n    -> differ2_alpha b t2 t3\n    -> differ2_alpha b t1 t3.\nProof.\n  introv aeq d.\n  allunfold @differ2_alpha; exrepnd.\n  exists u1 u2; dands; eauto with slow.\nQed.\n\nLemma differ2_alpha_r {o} :\n  forall b (t1 t2 t3 : @NTerm o),\n    differ2_alpha b t1 t2\n    -> alpha_eq t2 t3\n    -> differ2_alpha b t1 t3.\nProof.\n  introv aeq d.\n  allunfold @differ2_alpha; exrepnd.\n  exists u1 u2; dands; eauto with slow.\nQed.\n\nLemma differ2_alpha_mk_fresh {o} :\n  forall b v (t1 t2 : @NTerm o),\n    differ2_alpha b t1 t2\n    -> differ2_alpha b (mk_fresh v t1) (mk_fresh v t2).\nProof.\n  introv d.\n  allunfold @differ2_alpha; exrepnd.\n  exists (mk_fresh v u1) (mk_fresh v u2); dands;\n  try (apply implies_alpha_eq_mk_fresh; eauto with slow).\n  constructor; simpl; auto; introv i; repndors; cpx.\nQed.\n\nLemma differ2_alpha_mk_lam {o} :\n  forall b v (t1 t2 : @NTerm o),\n    differ2_alpha b t1 t2\n    -> differ2_alpha b (mk_lam v t1) (mk_lam v t2).\nProof.\n  introv d.\n  allunfold @differ2_alpha; exrepnd.\n  exists (mk_lam v u1) (mk_lam v u2); dands;\n  try (apply implies_alpha_eq_mk_lam; eauto with slow).\n  constructor; simpl; auto; introv i; repndors; cpx.\nQed.\n\nLemma differ2_subst_utokens_aux {o} :\n  forall b (t1 t2 : @NTerm o) sub,\n    disjoint (bound_vars t1) (free_vars_utok_sub sub)\n    -> disjoint (bound_vars t2) (free_vars_utok_sub sub)\n    -> differ2 b t1 t2\n    -> differ2 b (subst_utokens_aux t1 sub) (subst_utokens_aux t2 sub).\nProof.\n  nterm_ind t1 as [v1|f1 ind1|op1 bs1 ind1] Case; introv disj1 disj2 d; auto.\n\n  - Case \"vterm\".\n    inversion d; subst; allsimpl; eauto with slow.\n\n  - Case \"sterm\".\n    inversion d; subst; clear d; allsimpl; auto.\n\n  - Case \"oterm\".\n    inversion d as [? ? ? d1|?|?|? ? ? len1 imp1]; subst; clear d.\n\n    + allsimpl; allrw app_nil_r; fold_terms.\n      allrw disjoint_app_l; allrw disjoint_cons_l; repnd.\n      constructor.\n\n      pose proof (ind1 t1 []) as q; autodimp q hyp.\n\n    + allrw @subst_utokens_aux_oterm; allsimpl.\n      remember (get_utok op1) as guo1; symmetry in Heqguo1; destruct guo1.\n\n      * unfold subst_utok.\n        remember (utok_sub_find sub g) as sf; symmetry in Heqsf; destruct sf; eauto 3 with slow.\n        constructor; allrw map_length; auto.\n        introv i; allrw <- @map_combine; allrw in_map_iff; exrepnd; cpx; allsimpl.\n        applydup imp1 in i1; applydup in_combine in i1; repnd.\n        disj_flat_map.\n        destruct a0 as [l1 u1].\n        destruct a as [l2 u2].\n        allsimpl; allrw disjoint_app_l; repnd.\n        inversion i0 as [? ? ? d1]; subst; clear i0.\n        constructor.\n\n        pose proof (ind1 u1 l2) as q; autodimp q hyp.\n\n      * constructor; allrw map_length; auto.\n        introv i; allrw <- @map_combine; allrw in_map_iff; exrepnd; cpx; allsimpl.\n        applydup imp1 in i1; applydup in_combine in i1; repnd.\n        disj_flat_map.\n        destruct a0 as [l1 u1].\n        destruct a as [l2 u2].\n        allsimpl; allrw disjoint_app_l; repnd.\n        inversion i0 as [? ? ? d1]; subst; clear i0.\n        constructor.\n\n        pose proof (ind1 u1 l2) as q; autodimp q hyp.\nQed.\n\nLemma differ2_alpha_subst_utokens {o} :\n  forall b (t1 t2 : @NTerm o) sub,\n    differ2_alpha b t1 t2\n    -> differ2_alpha b (subst_utokens t1 sub) (subst_utokens t2 sub).\nProof.\n  introv d.\n  unfold differ2_alpha in d; exrepnd.\n\n  eapply differ2_alpha_l;[eapply alpha_eq_subst_utokens_same;exact d0|].\n  eapply differ2_alpha_r;[|apply alpha_eq_sym;eapply alpha_eq_subst_utokens_same;exact d2].\n  clear dependent t1.\n  clear dependent t2.\n\n  pose proof (differ2_change_bound_vars\n                b (free_vars_utok_sub sub)\n                u1 u2 d1) as d; exrepnd.\n  rename u0 into t1.\n  rename u3 into t2.\n\n  eapply differ2_alpha_l;[eapply alpha_eq_subst_utokens_same;exact d3|].\n  eapply differ2_alpha_r;[|apply alpha_eq_sym;eapply alpha_eq_subst_utokens_same;exact d4].\n  clear dependent u1.\n  clear dependent u2.\n\n  pose proof (unfold_subst_utokens sub t1) as h; exrepnd.\n  pose proof (unfold_subst_utokens sub t2) as k; exrepnd.\n  rename t' into u1.\n  rename t'0 into u2.\n  rw h0; rw k0.\n\n  eapply differ2_alpha_l;[apply (alpha_eq_subst_utokens_aux u1 t1 sub sub); eauto 3 with slow|].\n  eapply differ2_alpha_r;[|apply alpha_eq_sym;apply (alpha_eq_subst_utokens_aux u2 t2 sub sub); eauto with slow].\n\n  apply differ2_implies_differ2_alpha.\n  apply differ2_subst_utokens_aux; auto.\nQed.\n\nLemma differ2_preserves_iscan {o} :\n  forall b (t1 t2 : @NTerm o),\n    differ2 b t1 t2\n    -> iscan t1\n    -> iscan t2.\nProof.\n  introv diff isc.\n  apply iscan_implies in isc; repndors; exrepnd; subst;\n  inversion diff; subst; simpl; auto.\nQed.\n\nLemma differ2_exception_implies {o} :\n  forall b (a e t : @NTerm o),\n    differ2 b (mk_exception a e) t\n    -> {a' : NTerm\n        & {e' : NTerm\n        & t = mk_exception a' e'\n        # differ2 b a a'\n        # differ2 b e e' }}.\nProof.\n  introv d.\n  inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; cpx; clear d; allsimpl.\n\n  pose proof (imp (nobnd a) x) as d1; autodimp d1 hyp.\n  pose proof (imp (nobnd e) y) as d2; autodimp d2 hyp.\n  clear imp.\n\n  inversion d1 as [? ? ? d3]; subst; clear d1.\n  inversion d2 as [? ? ? d4]; subst; clear d2.\n  fold_terms.\n\n  eexists; eexists; dands; eauto.\nQed.\n\nLemma differ2_lam_implies {o} :\n  forall b v a (t : @NTerm o),\n    differ2 b (mk_lam v a) t\n    -> {a' : NTerm\n        & t = mk_lam v a'\n        # differ2 b a a' }.\nProof.\n  introv d.\n  inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; cpx; clear d; allsimpl.\n\n  pose proof (imp (bterm [v] a) x) as d1; autodimp d1 hyp.\n  clear imp.\n\n  inversion d1 as [? ? ? d2]; subst; clear d1.\n  fold_terms.\n\n  eexists; eexists; dands; eauto.\nQed.\n\nLemma comp_force_int_step2 {o} :\n  forall lib (t1 t2 : @NTerm o) b u,\n    wf_term t1\n    -> wf_term t2\n    -> differ2 b t1 t2\n    -> compute_step lib t1 = csuccess u\n    -> hasvalue_like lib u\n    -> {t : NTerm\n        & {u' : NTerm\n           & reduces_to lib t2 t\n           # reduces_to lib u u'\n           # differ2_alpha b u' t}}.\nProof.\n  nterm_ind1s t1 as [v|f ind|op bs ind] Case; introv wt1 wt2 d comp hv; auto.\n\n  - Case \"vterm\".\n     simpl.\n     inversion d; subst; allsimpl; ginv.\n\n  - Case \"sterm\".\n    csunf comp; allsimpl; ginv.\n    inversion d; subst; clear d; allsimpl.\n    exists (sterm f) (sterm f); dands; eauto 3 with slow.\n\n  - Case \"oterm\".\n    dopid op as [can|ncan|mrk|abs] SCase; ginv.\n\n    + SCase \"Can\".\n      csunf comp; inversion d; subst.\n      allsimpl; ginv.\n      exists (oterm (Can can) bs2) (oterm (Can can) bs); dands; eauto 3 with slow.\n\n    + SCase \"NCan\".\n      destruct bs as [|b1 bs];\n        try (complete (allsimpl; ginv));[].\n\n      destruct b1 as [l1 t1].\n      destruct l1; try (complete (simpl in comp; ginv)).\n\n      {\n      destruct t1 as [v1|f1|op1 bs1].\n\n      * destruct t2 as [v2|f2|op2 bs2]; try (complete (inversion d));[].\n\n        inversion d as [? ? ? ? d1|?|?|? ? ? len imp]; subst; simphyps; cpx; ginv.\n\n      * destruct t2 as [v2|f2|op2 bs2]; try (complete (inversion d));[].\n        csunf comp; allsimpl.\n        dopid_noncan ncan SSCase; allsimpl; ginv.\n\n        { SSCase \"NApply\".\n          apply compute_step_seq_apply_success in comp; exrepnd; subst; allsimpl.\n          inversion d as [? ? ? ? d1|?|?|? ? ? len imp]; subst; simphyps; cpx; ginv; clear d.\n          allsimpl.\n\n          pose proof (imp (nobnd (sterm f1)) x) as d1; autodimp d1 hyp.\n          pose proof (imp (nobnd arg) y) as d2; autodimp d2 hyp.\n          clear imp.\n\n          inversion d1 as [? ? ? d3]; subst; clear d1.\n          inversion d2 as [? ? ? d4]; subst; clear d2.\n          inversion d3; subst; clear d3.\n          fold_terms.\n\n          exists (mk_eapply (sterm f1) t0) (mk_eapply (sterm f1) arg); dands; eauto 3 with slow.\n          apply differ2_implies_differ2_alpha.\n          apply differ2_oterm; simpl; auto.\n          introv j; repndors; cpx; constructor; auto.\n        }\n\n        { SSCase \"NEApply\".\n          apply compute_step_eapply_success in comp; exrepnd; subst; allsimpl.\n          inversion d as [? ? ? ? d1|?|?|? ? ? len imp]; subst; simphyps; cpx; ginv; clear d.\n          rw @wf_term_eq in wt1; rw @nt_wf_eapply_iff in wt1; exrepnd; allunfold @nobnd; ginv.\n          simpl in len; cpx.\n          simpl in imp.\n\n          pose proof (imp (nobnd (sterm f1)) x) as d1; autodimp d1 hyp.\n          pose proof (imp (nobnd b0) y) as d2; autodimp d2 hyp.\n          clear imp.\n\n          inversion d1 as [? ? ? d3]; subst; clear d1.\n          inversion d2 as [? ? ? d4]; subst; clear d2.\n          inversion d3; subst; clear d3.\n          fold_terms.\n\n          repndors; exrepnd; subst.\n\n          - apply compute_step_eapply2_success in comp1; repnd; GC.\n            repndors; exrepnd; subst; ginv; allsimpl; GC.\n            inversion d4 as [?|?|?|? ? ? len1 imp1]; subst; allsimpl;\n            clear d4; cpx; clear imp1; fold_terms.\n\n            exists (f n) (f n); dands; eauto 3 with slow.\n            apply reduces_to_if_step.\n            csunf; simpl.\n            dcwf h; simpl; boolvar; try omega.\n            rw @Znat.Nat2Z.id; auto.\n\n          - apply isexc_implies2 in comp0; exrepnd; subst.\n            inversion d4 as [?|?|?|? ? ? len1 imp1]; subst; allsimpl; clear d4.\n            exists (oterm Exc bs2) (oterm Exc l); dands; eauto 3 with slow.\n\n          - pose proof (ind b0 b0 []) as h; clear ind.\n            repeat (autodimp h hyp); eauto 3 with slow.\n            allrw <- @wf_eapply_iff; repnd.\n            pose proof (h t0 b x) as ih; clear h.\n            applydup @preserve_nt_wf_compute_step in comp1; auto.\n            repeat (autodimp ih hyp); eauto 3 with slow.\n            { apply hasvalue_like_eapply_sterm_implies in hv; auto. }\n            exrepnd.\n\n            exists (mk_eapply (sterm f1) t) (mk_eapply (sterm f1) u'); dands; eauto 3 with slow.\n            { apply implies_eapply_red_aux; eauto 3 with slow. }\n            { apply implies_eapply_red_aux; eauto 3 with slow. }\n            { apply differ2_alpha_mk_eapply; eauto 3 with slow. }\n        }\n\n        { SSCase \"NFix\".\n          apply compute_step_fix_success in comp; repnd; subst; allsimpl.\n          inversion d as [? ? ? ? d1|?|?|? ? ? len imp]; subst; simphyps; cpx; ginv; clear d; allsimpl.\n\n          pose proof (imp (nobnd (sterm f1)) x) as d1; autodimp d1 hyp.\n          clear imp.\n\n          inversion d1 as [? ? ? d2]; subst; clear d1.\n          inversion d2; subst; clear d2.\n          fold_terms.\n\n          exists (mk_apply (sterm f1) (mk_fix (sterm f1)))\n                 (mk_apply (sterm f1) (mk_fix (sterm f1))).\n          dands; eauto 3 with slow.\n        }\n\n        { SSCase \"NCbv\".\n          apply compute_step_cbv_success in comp; exrepnd; subst; allsimpl.\n          inversion d as [? ? ? d1|?|? xxx|? ? ? len imp]; subst; simphyps; cpx; ginv; clear d; allsimpl; fold_terms.\n\n          - inversion d1; subst; clear d1.\n            apply hasvalue_like_subst_less_bound_seq in hv; sp.\n\n          - pose proof (imp (nobnd (sterm f1)) x0) as d1; autodimp d1 hyp.\n            pose proof (imp (bterm [v] x) y) as d2; autodimp d2 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? d3]; subst; clear d1.\n            inversion d3; subst; clear d3.\n            inversion d2 as [? ? ? d4]; subst; clear d2.\n            fold_terms.\n\n            exists (subst t2 v (sterm f1))\n                   (subst x v (sterm f1)).\n            dands; eauto 3 with slow.\n            apply differ2_subst; auto.\n        }\n\n        { SSCase \"NTryCatch\".\n          apply compute_step_try_success in comp; exrepnd; subst; allsimpl.\n          inversion d as [? ? ? d1|?|? xxx|? ? ? len imp]; subst; simphyps; cpx; ginv; clear d; allsimpl; fold_terms.\n\n          pose proof (imp (nobnd (sterm f1)) x0) as d1; autodimp d1 hyp.\n          pose proof (imp (nobnd a) y) as d2; autodimp d2 hyp.\n          pose proof (imp (bterm [v] x) z) as d3; autodimp d3 hyp.\n          clear imp.\n\n          inversion d1 as [? ? ? d4]; subst; clear d1.\n          inversion d4; subst; clear d4.\n          inversion d2 as [? ? ? d4]; subst; clear d2.\n          inversion d3 as [? ? ? d5]; subst; clear d3.\n          fold_terms.\n\n          exists (mk_atom_eq t2 t2 (sterm f1) mk_bot)\n                 (mk_atom_eq a a (sterm f1) mk_bot).\n          dands; eauto 3 with slow.\n          apply differ2_alpha_mk_atom_eq; eauto 3 with slow.\n        }\n\n        { SSCase \"NCanTest\".\n          apply compute_step_seq_can_test_success in comp; exrepnd; subst; allsimpl.\n          inversion d as [? ? ? d1|?|? xxx|? ? ? len imp]; subst; simphyps; cpx; ginv; clear d; allsimpl; fold_terms.\n\n          pose proof (imp (nobnd (sterm f1)) x) as d1; autodimp d1 hyp.\n          pose proof (imp (nobnd a) y) as d2; autodimp d2 hyp.\n          pose proof (imp (nobnd b0) z) as d3; autodimp d3 hyp.\n          clear imp.\n\n          inversion d1 as [? ? ? d4]; subst; clear d1.\n          inversion d4; subst; clear d4.\n          inversion d2 as [? ? ? d4]; subst; clear d2.\n          inversion d3 as [? ? ? d5]; subst; clear d3.\n          fold_terms.\n\n          exists t0 b0.\n          dands; eauto 3 with slow.\n        }\n\n      * (* Now destruct op2 *)\n        dopid op1 as [can1|ncan1|exc1|abs1] SSCase; ginv.\n\n        { SSCase \"Can\".\n\n          (* Because the principal argument is canonical we can destruct ncan *)\n          dopid_noncan ncan SSSCase.\n\n          - SSSCase \"NApply\".\n            csunf comp; allsimpl.\n            apply compute_step_apply_success in comp; repndors; exrepnd; subst; allsimpl.\n\n            { inversion d as [?|?|?|? ? ? len imp]; subst; allsimpl; clear d.\n              destruct bs2; allsimpl; cpx.\n              destruct bs2; allsimpl; cpx.\n              destruct bs2; allsimpl; cpx.\n              GC.\n\n              pose proof (imp (bterm [] (oterm (Can NLambda) [bterm [v] b0])) b1) as d1.\n              autodimp d1 hyp.\n              pose proof (imp (bterm [] arg) b2) as d2.\n              autodimp d2 hyp.\n              clear imp.\n\n              inversion d1 as [? ? ? d3]; subst; clear d1.\n              inversion d2 as [? ? ? d4]; subst; clear d2.\n\n              inversion d3 as [?|?|?|? ? ? len1 imp1]; subst; allsimpl; clear d3.\n              destruct bs2; allsimpl; cpx.\n              destruct bs2; allsimpl; cpx.\n              GC.\n\n              pose proof (imp1 (bterm [v] b0) b1) as d1.\n              autodimp d1 hyp.\n              clear imp1.\n\n              inversion d1 as [? ? ? d2]; subst; clear d1.\n\n              exists (subst t2 v t0) (subst b0 v arg); dands; eauto 3 with slow.\n\n              apply differ2_subst; auto.\n            }\n\n            { inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; clear d; cpx.\n              allsimpl; fold_terms.\n\n              pose proof (imp (nobnd (mk_nseq f)) x) as d1; autodimp d1 hyp.\n              pose proof (imp (nobnd arg) y) as d2; autodimp d2 hyp.\n              clear imp.\n\n              inversion d1 as [? ? ? d3]; subst; clear d1.\n              inversion d2 as [? ? ? d4]; subst; clear d2.\n\n              inversion d3 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; clear d3.\n              cpx.\n              clear imp1.\n              fold_terms.\n\n              exists (mk_eapply (mk_nseq f) t0) (mk_eapply (mk_nseq f) arg); dands; eauto 3 with slow.\n              apply differ2_implies_differ2_alpha.\n              apply differ2_oterm; simpl; auto.\n              introv j; repndors; cpx; repeat (constructor; auto).\n              simpl; tcsp.\n            }\n\n          - SSSCase \"NEApply\".\n            csunf comp; allsimpl.\n            apply compute_step_eapply_success in comp; exrepnd; subst.\n            rw @wf_term_eq in wt1; rw @nt_wf_eapply_iff in wt1; exrepnd; allunfold @nobnd; ginv.\n\n            inversion d as [? ? ? ? d1|?|?|? ? ? len imp]; subst; clear d.\n            simpl in len; cpx; simpl in imp.\n\n            pose proof (imp (nobnd (oterm (Can can1) bs1)) x) as d1; autodimp d1 hyp.\n            pose proof (imp (nobnd b0) y) as d2; autodimp d2 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? d3]; subst; clear d1.\n            inversion d2 as [? ? ? d4]; subst; clear d2.\n            fold_terms.\n            allrw <- @wf_eapply_iff; repnd.\n            apply eapply_wf_def_oterm_implies in comp2; exrepnd; ginv; fold_terms.\n            destruct comp2 as [comp2|comp2]; exrepnd; ginv; fold_terms.\n\n            { apply differ2_lam_implies in d3; exrepnd; subst; fold_terms.\n\n              repndors; exrepnd; subst.\n\n              + apply compute_step_eapply2_success in comp1; repnd; GC.\n                repndors; exrepnd; subst; ginv; allsimpl; GC.\n                allunfold @apply_bterm; allsimpl; allrw @fold_subst.\n\n                exists (subst a' v0 t0) (subst b1 v0 b0); dands; eauto 3 with slow.\n                { apply eapply_lam_can_implies.\n                  apply differ2_preserves_iscan in d4; auto.\n                  unfold computes_to_can; dands; eauto 3 with slow. }\n                { apply differ2_subst; auto. }\n\n              + apply wf_isexc_implies in comp0; auto; exrepnd; subst; allsimpl.\n                apply differ2_exception_implies in d4; exrepnd; subst.\n                exists (mk_exception a'0 e') (mk_exception a e); dands; eauto 3 with slow.\n                apply differ2_alpha_mk_exception; eauto 3 with slow.\n\n              + pose proof (ind b0 b0 []) as h; clear ind.\n                repeat (autodimp h hyp); eauto 3 with slow.\n                pose proof (h t0 b x) as ih; clear h.\n                applydup @preserve_nt_wf_compute_step in comp1; auto.\n                repeat (autodimp ih hyp); eauto 3 with slow.\n                { apply hasvalue_like_eapply_lam_implies in hv; auto. }\n                exrepnd.\n\n                exists (mk_eapply (mk_lam v a') t1) (mk_eapply (mk_lam v t) u'); dands; eauto 3 with slow.\n                { apply implies_eapply_red_aux; eauto 3 with slow. }\n                { apply implies_eapply_red_aux; eauto 3 with slow. }\n                { apply differ2_alpha_mk_eapply; eauto 3 with slow.\n                  apply differ2_alpha_mk_lam; eauto 3 with slow. }\n            }\n\n            { inversion d3 as [|?|?|? ? ? len imp]; subst; simphyps; clear d3.\n              clear imp.\n              allsimpl; cpx; allsimpl; fold_terms.\n              repndors; exrepnd; subst; allsimpl.\n\n              - destruct b0 as [v|f|op bs]; ginv;[].\n                dopid op as [can|ncan|exc|abs] SSSSCase; ginv;[].\n                destruct can; ginv;[].\n                destruct bs; allsimpl; ginv; GC.\n                boolvar; ginv; try omega; fold_terms.\n                inversion d4 as [|?|?|? ? ? len imp]; subst; simphyps; clear d4.\n                allsimpl; cpx; fold_terms; allsimpl.\n                clear imp.\n\n                exists (@mk_nat o (s (Z.to_nat z))) (@mk_nat o (s (Z.to_nat z))); dands; eauto 3 with slow.\n                apply reduces_to_if_step; csunf; simpl; dcwf h; simpl.\n                boolvar; try omega; auto.\n\n              - apply wf_isexc_implies in comp0; auto; exrepnd; subst; allsimpl.\n                apply differ2_exception_implies in d4; exrepnd; subst.\n                exists (mk_exception a' e') (mk_exception a e); dands; eauto 3 with slow.\n                apply differ2_alpha_mk_exception; eauto 3 with slow.\n\n              - pose proof (ind b0 b0 []) as h; clear ind.\n                repeat (autodimp h hyp); eauto 3 with slow.\n                pose proof (h t0 b x) as ih; clear h.\n                applydup @preserve_nt_wf_compute_step in comp1; auto.\n                allsimpl; autorewrite with slow in *.\n                repeat (autodimp ih hyp); eauto 3 with slow.\n                { apply hasvalue_like_eapply_nseq_implies in hv; auto. }\n                exrepnd.\n\n                exists (mk_eapply (mk_nseq s) t) (mk_eapply (mk_nseq s) u'); dands; eauto 3 with slow.\n                { apply implies_eapply_red_aux; eauto 3 with slow. }\n                { apply implies_eapply_red_aux; eauto 3 with slow. }\n                { apply differ2_alpha_mk_eapply; eauto 3 with slow. }\n            }\n\n(*          - SSSCase \"NApseq\".\n            csunf comp; allsimpl.\n            apply compute_step_apseq_success in comp; exrepnd; subst.\n            fold_terms.\n\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; clear d; cpx.\n            allsimpl.\n            pose proof (imp (nobnd (mk_nat n0)) x) as d1; autodimp d1 hyp; clear imp.\n            inversion d1 as [? ? ? d2]; subst; clear d1.\n            inversion d2 as [|?|?|? ? ? len1 imp1]; allsimpl; cpx; clear d2.\n            clear imp1; fold_terms.\n\n            exists (@mk_nat o (n n0)) (@mk_nat o (n n0)); dands; eauto 3 with slow.\n            apply reduces_to_if_step; csunf; simpl.\n            rw @Znat.Nat2Z.id.\n            boolvar; try omega; auto. *)\n\n          - SSSCase \"NFix\".\n            csunf comp; allsimpl.\n            apply compute_step_fix_success in comp; exrepnd; subst; allsimpl.\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; clear d.\n            destruct bs2; allsimpl; cpx.\n            destruct bs2; allsimpl; cpx.\n            GC.\n\n            pose proof (imp (bterm [] (oterm (Can can1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? d2]; subst; clear d1.\n\n            inversion d2 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; clear d2.\n\n            exists (mk_apply\n                      (oterm (Can can1) bs2)\n                      (oterm (NCan NFix) [bterm [] (oterm (Can can1) bs2)]))\n                   (mk_apply (oterm (Can can1) bs1)\n                             (oterm (NCan NFix) [bterm [] (oterm (Can can1) bs1)])).\n            dands; eauto 3 with slow.\n\n            apply differ2_implies_differ2_alpha.\n            apply differ2_oterm; simpl; auto.\n            introv j.\n\n            dorn j; cpx.\n\n            { constructor.\n              apply differ2_oterm; simpl; auto. }\n\n            { dorn j; cpx.\n              constructor.\n              apply differ2_oterm; allsimpl; auto.\n              introv j.\n              dorn j; cpx. }\n\n          - SSSCase \"NSpread\".\n            csunf comp; allsimpl.\n            apply compute_step_spread_success in comp; exrepnd; subst; allsimpl.\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; clear d.\n            destruct bs2; allsimpl; cpx.\n            destruct bs2; allsimpl; cpx.\n            destruct bs2; allsimpl; cpx.\n            GC.\n\n            pose proof (imp (bterm [] (oterm (Can NPair) [nobnd a, nobnd b0])) b1) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [va,vb] arg) b2) as d2.\n            autodimp d2 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? d3]; subst; clear d1.\n            inversion d2 as [? ? ? d4]; subst; clear d2.\n\n            inversion d3 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; clear d3.\n            destruct bs2; allsimpl; cpx.\n            destruct bs2; allsimpl; cpx.\n            destruct bs2; allsimpl; cpx.\n            GC.\n\n            pose proof (imp1 (nobnd a) b1) as d1.\n            autodimp d1 hyp.\n            pose proof (imp1 (nobnd b0) b2) as d2.\n            autodimp d2 hyp.\n            clear imp1.\n\n            inversion d1 as [? ? ? d5]; subst; clear d1.\n            inversion d2 as [? ? ? d6]; subst; clear d2.\n\n            exists (lsubst t0 [(va,t2),(vb,t3)])\n                   (lsubst arg [(va,a),(vb,b0)]); dands; eauto 4 with slow.\n\n          - SSSCase \"NDsup\".\n            csunf comp; allsimpl.\n            apply compute_step_dsup_success in comp; exrepnd; subst; allsimpl.\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; clear d.\n            destruct bs2; allsimpl; cpx.\n            destruct bs2; allsimpl; cpx.\n            destruct bs2; allsimpl; cpx.\n            GC.\n\n            pose proof (imp (bterm [] (oterm (Can NSup) [nobnd a, nobnd b0])) b1) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [va,vb] arg) b2) as d2.\n            autodimp d2 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? d3]; subst; clear d1.\n            inversion d2 as [? ? ? d4]; subst; clear d2.\n\n            inversion d3 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; clear d3.\n            destruct bs2; allsimpl; cpx.\n            destruct bs2; allsimpl; cpx.\n            destruct bs2; allsimpl; cpx.\n            GC.\n\n            pose proof (imp1 (nobnd a) b1) as d1.\n            autodimp d1 hyp.\n            pose proof (imp1 (nobnd b0) b2) as d2.\n            autodimp d2 hyp.\n            clear imp1.\n\n            inversion d1 as [? ? ? d5]; subst; clear d1.\n            inversion d2 as [? ? ? d6]; subst; clear d2.\n\n            exists (lsubst t0 [(va,t2),(vb,t3)])\n                   (lsubst arg [(va,a),(vb,b0)]); dands; eauto 4 with slow.\n\n          - SSSCase \"NDecide\".\n            csunf comp; allsimpl.\n            apply compute_step_decide_success in comp; exrepnd; subst; allsimpl.\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; clear d.\n            destruct bs2; allsimpl; cpx.\n            destruct bs2; allsimpl; cpx.\n            destruct bs2; allsimpl; cpx.\n            destruct bs2; allsimpl; cpx.\n            GC.\n\n            pose proof (imp (bterm [] (oterm (Can can1) [nobnd d0])) b0) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [v1] t1) b1) as d2.\n            autodimp d2 hyp.\n            pose proof (imp (bterm [v2] t0) b2) as d3.\n            autodimp d3 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? d4]; subst; clear d1.\n            inversion d2 as [? ? ? d5]; subst; clear d2.\n            inversion d3 as [? ? ? d6]; subst; clear d3.\n\n            inversion d4 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; clear d4.\n            destruct bs2; allsimpl; cpx.\n            destruct bs2; allsimpl; cpx.\n            GC.\n\n            pose proof (imp1 (nobnd d0) b0) as d1.\n            autodimp d1 hyp.\n            clear imp1.\n\n            inversion d1 as [? ? ? d2]; subst; clear d1.\n\n            dorn comp0; repnd; subst.\n\n            + exists (subst t4 v1 t3)\n                     (subst t1 v1 d0);\n                dands; eauto 3 with slow.\n\n              apply differ2_subst; auto.\n\n            + exists (subst t5 v2 t3)\n                     (subst t0 v2 d0);\n                dands; eauto 3 with slow.\n\n              apply differ2_subst; auto.\n\n          - SSSCase \"NCbv\".\n            csunf comp; allsimpl.\n            apply compute_step_cbv_success in comp; exrepnd; subst; allsimpl.\n            inversion d as [? ? ? d1|?|?|? ? ? len imp]; subst; allsimpl; clear d.\n\n            + inversion d1 as [|?|?|? ? ? len imp]; subst; allsimpl; clear d1.\n\n              apply hasvalue_like_subst_less_bound in hv; exrepnd; subst.\n\n              allsimpl; cpx; GC.\n              exists (@mk_integer o z) (@mk_integer o z); dands; eauto 3 with slow.\n\n              * apply reduces_to_if_step; simpl.\n                csunf; simpl.\n                dcwf h; allsimpl.\n                unfold compute_step_arith; simpl.\n                allrw <- Zplus_0_r_reverse; auto.\n\n              * unfold subst, lsubst; simpl; boolvar; GC; allrw not_over_or; repndors; repnd; tcsp; GC.\n                simpl; fold_terms.\n                destruct (Z_lt_le_dec z 0) as [h|h].\n\n                { apply (reduces_to_if_split2\n                           _ _\n                           (mk_less (mk_minus (mk_integer z)) (mk_nat b) (mk_integer z) (mk_vbot v)));\n                  [ csunf; simpl; boolvar; tcsp; omega|].\n\n                  apply (reduces_to_if_split2\n                           _ _\n                           (mk_less (mk_integer (- z)) (mk_nat b) (mk_integer z) (mk_vbot v)));\n                    auto.\n                  apply reduces_to_if_step; simpl.\n                  csunf; simpl.\n                  dcwf q; allsimpl.\n                  unfold compute_step_comp; simpl; boolvar; tcsp; try omega.\n                  provefalse.\n                  pose proof (abs_of_neg2 z b); sp; try omega.\n                }\n\n                { apply (reduces_to_if_split2\n                           _ _\n                           (mk_less (mk_integer z) (mk_nat b) (mk_integer z) (mk_vbot v)));\n                  [ csunf; simpl; boolvar; tcsp; omega|].\n\n                  apply reduces_to_if_step; simpl.\n                  csunf; simpl.\n                  dcwf q; allsimpl.\n                  unfold compute_step_comp; simpl; boolvar; tcsp; try omega.\n                  provefalse.\n                  pose proof (abs_of_pos2 z b); sp; try omega.\n                }\n\n            + destruct bs2; allsimpl; cpx.\n              destruct bs2; allsimpl; cpx.\n              destruct bs2; allsimpl; cpx.\n              GC.\n\n              pose proof (imp (bterm [] (oterm (Can can1) bs1)) b0) as d1.\n              autodimp d1 hyp.\n              pose proof (imp (bterm [v] x) b1) as d2.\n              autodimp d2 hyp.\n              clear imp.\n\n              inversion d1 as [? ? ? d3]; subst; clear d1.\n              inversion d2 as [? ? ? d4]; subst; clear d2.\n\n              inversion d3 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; clear d3.\n\n              exists (subst t0 v (oterm (Can can1) bs2))\n                     (subst x v (oterm (Can can1) bs1));\n                dands; eauto 3 with slow.\n\n              apply differ2_subst; auto.\n\n          - SSSCase \"NSleep\".\n            csunf comp; allsimpl.\n            apply compute_step_sleep_success in comp; exrepnd; subst.\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; clear d; cpx; allsimpl; GC.\n\n            pose proof (imp (bterm [] (oterm (Can (Nint z)) [])) x) as d1.\n            autodimp d1 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? d2]; subst; clear d1.\n\n            inversion d2 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; clear d2; cpx.\n            clear imp1.\n\n            exists (@mk_axiom o) (@mk_axiom o); dands; eauto 3 with slow.\n\n          - SSSCase \"NTUni\".\n            csunf comp; allsimpl.\n            apply compute_step_tuni_success in comp; exrepnd; subst.\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; clear d; cpx; allsimpl; GC.\n\n            pose proof (imp (bterm [] (oterm (Can (Nint (Z.of_nat n))) [])) x) as d1.\n            autodimp d1 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? d2]; subst; clear d1.\n\n            inversion d2 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; clear d2; cpx.\n            clear imp1.\n\n            exists (@mk_uni o n) (@mk_uni o n); dands; eauto 3 with slow.\n\n            apply reduces_to_if_step; simpl.\n            csunf; simpl; unfold compute_step_tuni; simpl; boolvar; tcsp; try omega.\n            rw Znat.Nat2Z.id; auto.\n\n          - SSSCase \"NMinus\".\n            csunf comp; allsimpl.\n            apply compute_step_minus_success in comp; exrepnd; subst; allsimpl; GC.\n\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; clear d; cpx; allsimpl; GC.\n\n            pose proof (imp (bterm [] (oterm (Can (Nint z)) [])) x) as d1.\n            autodimp d1 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? d2]; subst; clear d1.\n\n            inversion d2 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; clear d2; cpx.\n            clear imp1.\n\n            exists (@mk_integer o (- z)) (@mk_integer o (- z)); dands; eauto 3 with slow.\n\n          - SSSCase \"NFresh\".\n            csunf comp; ginv.\n\n          - SSSCase \"NTryCatch\".\n            csunf comp; allsimpl.\n            apply compute_step_try_success in comp; exrepnd; subst; allsimpl; GC.\n\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; clear d; cpx; allsimpl; GC.\n\n            pose proof (imp (bterm [] (oterm (Can can1) bs1)) x0) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [] a) y) as d2.\n            autodimp d2 hyp.\n            pose proof (imp (bterm [v] x) z) as d3.\n            autodimp d3 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? d4]; subst; clear d1.\n            inversion d2 as [? ? ? d5]; subst; clear d2.\n            inversion d3 as [? ? ? d6]; subst; clear d3.\n\n            inversion d4 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; clear d4; cpx.\n\n            exists (mk_atom_eq t0 t0 (oterm (Can can1) bs2) mk_bot)\n                   (mk_atom_eq a a (oterm (Can can1) bs1) mk_bot);\n              dands; eauto 3 with slow.\n\n            apply differ2_implies_differ2_alpha.\n            constructor; simpl; auto.\n            introv i; repndors; ginv; tcsp; constructor; eauto 3 with slow.\n\n          - SSSCase \"NParallel\".\n            csunf comp; allsimpl.\n            apply compute_step_parallel_success in comp; subst; allsimpl.\n            inversion d as [|?|?|? ? ? len imp]; allsimpl; subst; clear d.\n            destruct bs2; allsimpl; cpx.\n            pose proof (imp (bterm [] (oterm (Can can1) bs1)) b0) as d.\n            autodimp d hyp.\n            inversion d as [? ? ? d1]; subst; clear d.\n            inversion d1 as [|?|?|? ? ? len' imp']; subst; clear d1.\n            exists (@mk_axiom o) (@mk_axiom o); dands; eauto with slow.\n\n          - SSSCase \"NCompOp\".\n            destruct bs; try (complete (csunf comp; allsimpl; dcwf h));[].\n            destruct b0 as [l t].\n            destruct l; destruct t as [v|f|op bs2]; try (complete (csunf comp; allsimpl; dcwf h));[].\n\n            inversion d as [? ? ? ? d1|?|?|? ? ? len imp]; subst; clear d.\n            simpl in len.\n\n            destruct bs3; simpl in len; cpx.\n            destruct bs3; simpl in len; cpx.\n            simpl in imp.\n\n            pose proof (imp (bterm [] (oterm (Can can1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [] (oterm op bs2)) b1) as d2.\n            autodimp d2 hyp.\n\n            inversion d1 as [? ? ? d3]; subst; clear d1.\n            inversion d2 as [? ? ? d4]; subst; clear d2.\n\n            inversion d3 as [|?|?|? ? ? len1 imp1]; subst; clear d3; cpx.\n\n            dopid op as [can3|ncan3|exc3|abs3] SSSSCase.\n\n            + SSSSCase \"Can\".\n              csunf comp; simpl in comp.\n              dcwf h.\n\n              inversion d4 as [|?|?|? ? ? len2 imp2]; subst; clear d4; cpx.\n\n              apply compute_step_compop_success_can_can in comp.\n              exrepnd; subst.\n\n              allsimpl; cpx; allsimpl; GC.\n              clear imp1.\n\n              pose proof (imp (nobnd t1) x) as d1.\n              autodimp d1 hyp.\n              pose proof (imp (nobnd t2) y) as d2.\n              autodimp d2 hyp.\n              clear imp.\n\n              inversion d1 as [? ? ? d3]; subst; clear d1.\n              inversion d2 as [? ? ? d4]; subst; clear d2.\n\n              repndors; exrepnd; subst.\n\n              * allapply @get_param_from_cop_pki; subst; allsimpl.\n                exists (if Z_lt_le_dec n1 n2 then t3 else t4)\n                       (if Z_lt_le_dec n1 n2 then t1 else t2);\n                  dands; eauto 3 with slow.\n                boolvar; eauto 3 with slow.\n\n              * allrw @get_param_from_cop_some; subst; allsimpl.\n                exists (if param_kind_deq pk1 pk2 then t3 else t4)\n                       (if param_kind_deq pk1 pk2 then t1 else t2);\n                  dands; eauto 3 with slow.\n                { apply reduces_to_if_step; csunf; simpl.\n                  dcwf h; allsimpl.\n                  unfold compute_step_comp; simpl; allrw @get_param_from_cop_pk2can; auto. }\n                boolvar; eauto 3 with slow.\n\n            + SSSSCase \"NCan\".\n              rw @compute_step_ncompop_ncan2 in comp.\n              dcwf h.\n              remember (compute_step lib (oterm (NCan ncan3) bs2)) as comp1;\n                symmetry in Heqcomp1.\n              destruct comp1; ginv.\n\n              pose proof (ind (oterm (NCan ncan3) bs2) (oterm (NCan ncan3) bs2) []) as h; clear ind.\n              repeat (autodimp h hyp; tcsp); eauto 3 with slow.\n\n              pose proof (h t0 b n) as k; clear h.\n              repeat (autodimp k hyp).\n\n              { apply wf_oterm_iff in wt1; allsimpl; repnd.\n                pose proof (wt1 (bterm [] (oterm (NCan ncan3) bs2))) as h; autodimp h hyp. }\n\n              { apply wf_oterm_iff in wt2; allsimpl; repnd.\n                pose proof (wt2 (bterm [] t0)) as h; autodimp h hyp. }\n\n              { apply if_hasvalue_like_ncompop_can1 in hv; auto. }\n\n              exrepnd.\n\n              exists (oterm (NCan (NCompOp c))\n                            (bterm [] (oterm (Can can1) bs4)\n                                   :: bterm [] t\n                                   :: bs3))\n                     (oterm (NCan (NCompOp c))\n                            (bterm [] (oterm (Can can1) bs1)\n                                   :: bterm [] u'\n                                   :: bs)).\n              dands; eauto 3 with slow.\n\n              * apply reduce_to_prinargs_comp2; eauto 3 with slow; sp.\n                apply co_wf_def_implies_iswfpk.\n                eapply co_wf_def_len_implies;[|eauto]; auto.\n\n              * apply reduce_to_prinargs_comp2; eauto 3 with slow; sp.\n\n              * unfold differ2_alpha in k1; exrepnd.\n                exists (oterm (NCan (NCompOp c))\n                              (bterm [] (oterm (Can can1) bs1)\n                                     :: bterm [] u1\n                                     :: bs))\n                       (oterm (NCan (NCompOp c))\n                              (bterm [] (oterm (Can can1) bs4)\n                                     :: bterm [] u2\n                                     :: bs3)).\n                dands.\n\n                { prove_alpha_eq4.\n                  introv j; destruct n0;[|destruct n0]; try omega; cpx.\n                  apply alphaeqbt_nilv2; auto. }\n\n                { prove_alpha_eq4.\n                  introv j; destruct n0;[|destruct n0]; try omega; cpx.\n                  apply alphaeqbt_nilv2; auto. }\n\n                { apply differ2_oterm; simpl; auto.\n                  introv j; dorn j; cpx.\n                  dorn j; cpx. }\n\n            + SSSSCase \"Exc\".\n              csunf comp; allsimpl; ginv.\n              dcwf h; allsimpl; ginv.\n              inversion d4 as [|?|?|? ? ? len2 imp2]; subst; clear d4; cpx.\n              exists (oterm Exc bs5) (oterm Exc bs2); dands; eauto 3 with slow.\n              eapply reduces_to_if_step; csunf; simpl; dcwf h.\n\n            + SSSSCase \"Abs\".\n              csunf comp; allsimpl.\n              dcwf h; allsimpl.\n              unfold on_success in comp; csunf comp; allsimpl.\n              remember (compute_step_lib lib abs3 bs2) as comp1.\n              symmetry in Heqcomp1; destruct comp1; ginv.\n              apply compute_step_lib_success in Heqcomp1; exrepnd; subst.\n\n              inversion d4 as [|?|?|? ? ? len2 imp2]; subst; simphyps; clear d4.\n\n              assert (differ2_bterms b bs2 bs5) as dbs.\n              { unfold differ2_bterms, br_bterms, br_list; auto. }\n\n              pose proof (found_entry_change_bs abs3 oa2 vars rhs lib bs2 correct bs5) as fe2.\n              repeat (autodimp fe2 hyp).\n\n              { apply differ2_bterms_implies_eq_map_num_bvars in dbs; auto. }\n\n              exists (oterm (NCan (NCompOp c))\n                            (bterm [] (oterm (Can can1) bs4)\n                                   :: bterm [] (mk_instance vars bs5 rhs)\n                                   :: bs3))\n              (oterm (NCan (NCompOp c))\n                     (bterm [] (oterm (Can can1) bs1)\n                            :: bterm [] (mk_instance vars bs2 rhs)\n                            :: bs)).\n\n             dands; eauto 3 with slow.\n\n             * apply reduces_to_if_step.\n               csunf; simpl.\n               dcwf h.\n               unfold on_success; csunf; simpl.\n               applydup @compute_step_lib_if_found_entry in fe2.\n               rw fe0; auto.\n\n             * pose proof (differ2_mk_instance b rhs vars bs2 bs5) as h.\n               repeat (autodimp h hyp).\n               { allapply @found_entry_implies_matching_entry.\n                 allunfold @matching_entry; sp. }\n               { allapply @found_entry_implies_matching_entry.\n                 allunfold @matching_entry; sp. }\n               { allunfold @correct_abs; sp. }\n               { allunfold @correct_abs; sp. }\n               unfold differ2_alpha in h.\n               exrepnd.\n\n               exists\n                 (oterm (NCan (NCompOp c))\n                        (bterm [] (oterm (Can can1) bs1)\n                               :: bterm [] u1\n                               :: bs))\n                 (oterm (NCan (NCompOp c))\n                        (bterm [] (oterm (Can can1) bs4)\n                               :: bterm [] u2\n                               :: bs3)).\n               dands.\n\n               { prove_alpha_eq4.\n                 introv j; destruct n;[|destruct n]; try omega; cpx.\n                 apply alphaeqbt_nilv2; auto. }\n\n               { prove_alpha_eq4.\n                 introv j; destruct n;[|destruct n]; try omega; cpx.\n                 apply alphaeqbt_nilv2; auto. }\n\n               { apply differ2_oterm; allsimpl; auto.\n                 introv j; dorn j; cpx.\n                 dorn j; cpx. }\n\n          - SSSCase \"NArithOp\".\n            destruct bs; try (complete (csunf comp; allsimpl; dcwf h));[].\n            destruct b0 as [l t].\n            destruct l; destruct t as [v|f|op bs2]; try (complete (csunf comp; allsimpl; dcwf h));[].\n\n            inversion d as [? ? ? ? d1|?|?|? ? ? len imp]; subst; clear d.\n            simpl in len.\n\n            destruct bs3; simpl in len; cpx.\n            destruct bs3; simpl in len; cpx.\n            simpl in imp.\n\n            pose proof (imp (bterm [] (oterm (Can can1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [] (oterm op bs2)) b1) as d2.\n            autodimp d2 hyp.\n\n            inversion d1 as [? ? ? d3]; subst; clear d1.\n            inversion d2 as [? ? ? d4]; subst; clear d2.\n\n            inversion d3 as [|?|?|? ? ? len1 imp1]; subst; clear d3; cpx.\n\n            dopid op as [can3|ncan3|exc3|abs3] SSSSCase.\n\n            + SSSSCase \"Can\".\n              csunf comp; simpl in comp.\n              dcwf h; allsimpl.\n\n              inversion d4 as [|?|?|? ? ? len2 imp2]; subst; clear d4; cpx.\n\n              apply compute_step_arithop_success_can_can in comp.\n              exrepnd; subst.\n              allsimpl; cpx.\n              clear imp1 imp2 imp.\n\n              allapply @get_param_from_cop_pki; subst; allsimpl; GC.\n\n              exists (@oterm o (Can (Nint (get_arith_op a n1 n2))) [])\n                     (@oterm o (Can (Nint (get_arith_op a n1 n2))) []);\n                dands; eauto 3 with slow.\n\n            + SSSSCase \"NCan\".\n              rw @compute_step_narithop_ncan2 in comp.\n              dcwf h; allsimpl;[].\n              remember (compute_step lib (oterm (NCan ncan3) bs2)) as comp1;\n                symmetry in Heqcomp1.\n              destruct comp1; ginv.\n\n              pose proof (ind (oterm (NCan ncan3) bs2) (oterm (NCan ncan3) bs2) []) as h; clear ind.\n              repeat (autodimp h hyp; tcsp); eauto 3 with slow.\n\n              pose proof (h t0 b n) as k; clear h.\n              repeat (autodimp k hyp).\n\n              { apply wf_oterm_iff in wt1; allsimpl; repnd.\n                pose proof (wt1 (bterm [] (oterm (NCan ncan3) bs2))) as h; autodimp h hyp. }\n\n              { apply wf_oterm_iff in wt2; allsimpl; repnd.\n                pose proof (wt2 (bterm [] t0)) as h; autodimp h hyp. }\n\n              { apply if_hasvalue_like_arithop_can1 in hv; auto. }\n\n              exrepnd.\n\n              exists (oterm (NCan (NArithOp a))\n                            (bterm [] (oterm (Can can1) bs4)\n                                   :: bterm [] t\n                                   :: bs3))\n                     (oterm (NCan (NArithOp a))\n                            (bterm [] (oterm (Can can1) bs1)\n                                   :: bterm [] u'\n                                   :: bs)).\n              dands; eauto 3 with slow.\n\n              * apply reduce_to_prinargs_arith2; eauto 3 with slow; sp.\n                allunfold @ca_wf_def; exrepnd; subst; allsimpl; cpx.\n                fold_terms; eauto 3 with slow.\n\n              * apply reduce_to_prinargs_arith2; eauto 3 with slow; sp.\n\n              * unfold differ2_alpha in k1; exrepnd.\n                exists (oterm (NCan (NArithOp a))\n                              (bterm [] (oterm (Can can1) bs1)\n                                     :: bterm [] u1\n                                     :: bs))\n                       (oterm (NCan (NArithOp a))\n                              (bterm [] (oterm (Can can1) bs4)\n                                     :: bterm [] u2\n                                     :: bs3)).\n                dands.\n\n                { prove_alpha_eq4.\n                  introv j; destruct n0;[|destruct n0]; try omega; cpx.\n                  apply alphaeqbt_nilv2; auto. }\n\n                { prove_alpha_eq4.\n                  introv j; destruct n0;[|destruct n0]; try omega; cpx.\n                  apply alphaeqbt_nilv2; auto. }\n\n                { apply differ2_oterm; simpl; auto.\n                  introv j; dorn j; cpx.\n                  dorn j; cpx. }\n\n            + SSSSCase \"Exc\".\n              csunf comp; allsimpl; ginv.\n              dcwf h; allsimpl; ginv.\n              inversion d4 as [|?|?|? ? ? len2 imp2]; subst; clear d4; cpx.\n              exists (oterm Exc bs5) (oterm Exc bs2); dands; eauto 3 with slow;[].\n              apply reduces_to_if_step; csunf; simpl; dcwf h.\n\n            + SSSSCase \"Abs\".\n              csunf comp; allsimpl.\n              dcwf h; allsimpl.\n              unfold on_success in comp; csunf comp; allsimpl.\n              remember (compute_step_lib lib abs3 bs2) as comp1.\n              symmetry in Heqcomp1; destruct comp1; ginv.\n              apply compute_step_lib_success in Heqcomp1; exrepnd; subst.\n\n              inversion d4 as [|?|?|? ? ? len2 imp2]; subst; simphyps; clear d4.\n\n              assert (differ2_bterms b bs2 bs5) as dbs.\n              { unfold differ2_bterms, br_bterms, br_list; auto. }\n\n              pose proof (found_entry_change_bs abs3 oa2 vars rhs lib bs2 correct bs5) as fe2.\n              repeat (autodimp fe2 hyp).\n\n              { apply differ2_bterms_implies_eq_map_num_bvars in dbs; auto. }\n\n              exists (oterm (NCan (NArithOp a))\n                            (bterm [] (oterm (Can can1) bs4)\n                                   :: bterm [] (mk_instance vars bs5 rhs)\n                                   :: bs3))\n              (oterm (NCan (NArithOp a))\n                     (bterm [] (oterm (Can can1) bs1)\n                            :: bterm [] (mk_instance vars bs2 rhs)\n                            :: bs)).\n\n             dands; eauto 3 with slow.\n\n             * apply reduces_to_if_step.\n               csunf; simpl; unfold on_success; csunf; simpl.\n               dcwf h; allsimpl.\n               applydup @compute_step_lib_if_found_entry in fe2.\n               rw fe0; auto.\n\n             * pose proof (differ2_mk_instance b rhs vars bs2 bs5) as h.\n               repeat (autodimp h hyp).\n               { allapply @found_entry_implies_matching_entry.\n                 allunfold @matching_entry; sp. }\n               { allapply @found_entry_implies_matching_entry.\n                 allunfold @matching_entry; sp. }\n               { allunfold @correct_abs; sp. }\n               { allunfold @correct_abs; sp. }\n               unfold differ2_alpha in h.\n               exrepnd.\n\n               exists\n                 (oterm (NCan (NArithOp a))\n                        (bterm [] (oterm (Can can1) bs1)\n                               :: bterm [] u1\n                               :: bs))\n                 (oterm (NCan (NArithOp a))\n                        (bterm [] (oterm (Can can1) bs4)\n                               :: bterm [] u2\n                               :: bs3)).\n               dands.\n\n               { prove_alpha_eq4.\n                 introv j; destruct n;[|destruct n]; try omega; cpx.\n                 apply alphaeqbt_nilv2; auto. }\n\n               { prove_alpha_eq4.\n                 introv j; destruct n;[|destruct n]; try omega; cpx.\n                 apply alphaeqbt_nilv2; auto. }\n\n               { apply differ2_oterm; allsimpl; auto.\n                 introv j; dorn j; cpx.\n                 dorn j; cpx. }\n\n          - SSSCase \"NCanTest\".\n            csunf comp; allsimpl.\n            apply compute_step_can_test_success in comp; exrepnd; subst; allsimpl.\n            inversion d as [|?|?|? ? ? len imp]; subst; allsimpl; clear d.\n            destruct bs2; allsimpl; cpx.\n            destruct bs2; allsimpl; cpx.\n            destruct bs2; allsimpl; cpx.\n            cpx; GC.\n\n            pose proof (imp (bterm [] (oterm (Can can1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [] arg2nt) b1) as d2.\n            autodimp d2 hyp.\n            pose proof (imp (bterm [] arg3nt) b2) as d3.\n            autodimp d3 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? d4]; subst; clear d1.\n            inversion d2 as [? ? ? d5]; subst; clear d2.\n            inversion d3 as [? ? ? d6]; subst; clear d3.\n\n            inversion d4 as [|?|?|? ? ? len1 imp1]; subst; allsimpl; clear d4.\n\n            exists (if canonical_form_test_for c can1 then t0 else t3)\n                   (if canonical_form_test_for c can1 then arg2nt else arg3nt).\n            dands; eauto 3 with slow.\n            destruct (canonical_form_test_for c can1); eauto 3 with slow.\n        }\n\n        { SSCase \"NCan\".\n          rw @compute_step_ncan_ncan in comp.\n          remember (compute_step lib (oterm (NCan ncan1) bs1)) as comp1;\n            symmetry in Heqcomp1.\n          destruct comp1; ginv.\n\n          inversion d as [? ? ? d1|?|?|? ? ? len imp]; subst; clear d.\n\n          - pose proof (ind (oterm (NCan ncan1) bs1) (oterm (NCan ncan1) bs1) []) as h.\n            repeat (autodimp h hyp; tcsp); eauto 3 with slow.\n\n            allrw <- @wf_cbv_iff; repnd.\n            allrw @wf_term_force_int.\n\n            pose proof (h t0 b n) as k; clear h.\n            repeat (autodimp k hyp).\n\n            { apply if_hasvalue_like_force_int_bound in hv; exrepnd; eauto 3 with slow.\n              unfold hasvalue_like.\n              exists u; dands; eauto 3 with slow. }\n\n            exrepnd.\n\n            exists (force_int t) (force_int_bound v b u' (mk_vbot v)); dands; eauto 3 with slow.\n\n            { apply reduces_to_prinarg; auto. }\n\n            { apply reduces_to_prinarg; auto. }\n\n            { apply implies_differ2_alpha_force_int; auto. }\n\n          - simpl in len.\n            destruct bs2; simpl in len; cpx.\n            simpl in imp.\n            pose proof (imp (bterm [] (oterm (NCan ncan1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            inversion d1 as [? ? ? d2]; subst; clear d1.\n\n            pose proof (ind (oterm (NCan ncan1) bs1) (oterm (NCan ncan1) bs1) []) as h.\n            repeat (autodimp h hyp; tcsp); eauto 3 with slow.\n            pose proof (h t2 b n) as k; clear h.\n            repeat (autodimp k hyp).\n\n            { apply wf_oterm_iff in wt1; allsimpl; repnd.\n              pose proof (wt1 (bterm [] (oterm (NCan ncan1) bs1))) as h; autodimp h hyp. }\n\n            { apply wf_oterm_iff in wt2; allsimpl; repnd.\n              pose proof (wt2 (bterm [] t2)) as h; autodimp h hyp. }\n\n            { apply if_hasvalue_like_ncan_primarg in hv; auto. }\n\n            exrepnd.\n\n            exists (oterm (NCan ncan) (bterm [] t :: bs2))\n                   (oterm (NCan ncan) (bterm [] u' :: bs));\n              dands; eauto 3 with slow.\n\n            { apply reduces_to_prinarg; auto. }\n\n            { apply reduces_to_prinarg; auto. }\n\n            { unfold differ2_alpha in k1; exrepnd.\n              exists (oterm (NCan ncan) (bterm [] u1 :: bs))\n                     (oterm (NCan ncan) (bterm [] u2 :: bs2));\n                dands.\n\n              - prove_alpha_eq4.\n                introv j; destruct n0; eauto 3 with slow.\n\n              - prove_alpha_eq4.\n                introv j; destruct n0; eauto 3 with slow.\n\n              - apply differ2_oterm; simpl; auto.\n                introv j; dorn j; cpx.\n            }\n        }\n\n        { SSCase \"Exc\".\n          csunf comp; simpl in comp.\n          apply compute_step_catch_success in comp.\n          dorn comp; exrepnd; subst.\n\n          - inversion d as [? ? ? d1|?|?|? ? ? len imp]; subst; clear d.\n            allsimpl.\n            destruct bs2; allsimpl; cpx.\n            cpx; allsimpl.\n            allrw app_nil_r; allrw in_app_iff; allrw not_over_or; repnd.\n\n            pose proof (imp (bterm [] (oterm Exc [bterm [] a', bterm [] e])) b1) as d1.\n            autodimp d1 hyp.\n            pose proof (imp (bterm [] a) x) as d2.\n            autodimp d2 hyp.\n            pose proof (imp (bterm [v] b0) y) as d3.\n            autodimp d3 hyp.\n            clear imp.\n\n            inversion d1 as [? ? ? d4]; subst; clear d1.\n            inversion d2 as [? ? ? d5]; subst; clear d2.\n            inversion d3 as [? ? ? d6]; subst; clear d3.\n\n            inversion d4 as [? ? ? d1|?|?|? ? ? len1 imp1]; subst; clear d4.\n            allsimpl; cpx.\n            allsimpl.\n            pose proof (imp1 (bterm [] a') x) as d1; autodimp d1 hyp.\n            pose proof (imp1 (bterm [] e) y) as d2; autodimp d2 hyp.\n            clear imp1.\n            inversion d1 as [? ? ? d3]; subst; clear d1.\n            inversion d2 as [? ? ? d4]; subst; clear d2.\n            allsimpl.\n\n            exists (mk_atom_eq t0 t2 (subst t3 v t4) (mk_exception t2 t4))\n                   (mk_atom_eq a a' (subst b0 v e) (mk_exception a' e));\n              dands; eauto 3 with slow.\n\n            apply differ2_alpha_mk_atom_eq; eauto 3 with slow.\n\n            { apply differ2_subst; auto. }\n\n            { apply differ2_alpha_mk_exception; eauto 3 with slow. }\n\n          - inversion d as [? ? ? d1|?|?|? ? ? len imp]; subst; clear d.\n            allsimpl.\n\n            + inversion d1 as [|?|?|? ? ? len imp]; subst; clear d1.\n              exists (oterm Exc bs2) (oterm Exc bs1).\n              dands; eauto 3 with slow.\n\n            + allsimpl.\n              destruct bs2; allsimpl; cpx.\n\n              pose proof (imp (bterm [] (oterm Exc bs1)) b0) as d1.\n              autodimp d1 hyp.\n              inversion d1 as [? ? ? d2]; subst; clear d1.\n              inversion d2 as [|?|?|? ? ? len1 imp1]; subst; clear d2.\n\n              allsimpl.\n              allrw in_app_iff; allrw not_over_or; repnd.\n              exists (oterm Exc bs3) (oterm Exc bs1).\n              dands; eauto 3 with slow.\n\n              apply reduces_to_if_step; simpl.\n              csunf; simpl; unfold compute_step_catch; destruct ncan; tcsp.\n        }\n\n        { SSCase \"Abs\".\n          csunf comp; allsimpl.\n          unfold on_success in comp; csunf comp; allsimpl.\n          remember (compute_step_lib lib abs1 bs1) as comp1;\n            symmetry in Heqcomp1.\n          destruct comp1; ginv.\n\n          inversion d as [? ? ? d1|?|?|? ? ? len imp]; subst; clear d.\n\n          - pose proof (ind (oterm (Abs abs1) bs1) (oterm (Abs abs1) bs1) []) as h.\n            repeat (autodimp h hyp; tcsp); eauto 3 with slow.\n\n            allrw <- @wf_cbv_iff; repnd.\n            allrw @wf_term_force_int.\n            applydup @wf_compute_step_lib in Heqcomp1; eauto 3 with slow.\n\n            pose proof (h t0 b n) as k; clear h.\n            repeat (autodimp k hyp).\n\n            { apply if_hasvalue_like_force_int_bound in hv; exrepnd; eauto 3 with slow.\n              unfold hasvalue_like.\n              exists u; dands; eauto 3 with slow. }\n\n            exrepnd.\n\n            exists (force_int t) (force_int_bound v b u' (mk_vbot v)); dands; eauto 3 with slow.\n\n            { apply reduces_to_prinarg; auto. }\n\n            { apply reduces_to_prinarg; auto. }\n\n            { apply implies_differ2_alpha_force_int; auto. }\n\n          - simpl in len.\n            destruct bs2; simpl in len; cpx.\n            simpl in imp.\n            pose proof (imp (bterm [] (oterm (Abs abs1) bs1)) b0) as d1.\n            autodimp d1 hyp.\n            inversion d1 as [? ? ? d2]; subst; clear d1.\n\n            pose proof (ind (oterm (Abs abs1) bs1) (oterm (Abs abs1) bs1) []) as h.\n            repeat (autodimp h hyp; tcsp); eauto 3 with slow.\n            pose proof (h t2 b n) as k; clear h.\n            repeat (autodimp k hyp).\n\n            { apply wf_oterm_iff in wt1; allsimpl; repnd.\n              pose proof (wt1 (bterm [] (oterm (Abs abs1) bs1))) as h; autodimp h hyp. }\n\n            { apply wf_oterm_iff in wt2; allsimpl; repnd.\n              pose proof (wt2 (bterm [] t2)) as h; autodimp h hyp. }\n\n            { apply if_hasvalue_like_ncan_primarg in hv; auto. }\n\n            exrepnd.\n\n            exists (oterm (NCan ncan) (bterm [] t :: bs2))\n                   (oterm (NCan ncan) (bterm [] u' :: bs));\n              dands; eauto 3 with slow.\n\n            { apply reduces_to_prinarg; auto. }\n\n            { apply reduces_to_prinarg; auto. }\n\n            { unfold differ2_alpha in k1; exrepnd.\n              exists (oterm (NCan ncan) (bterm [] u1 :: bs))\n                     (oterm (NCan ncan) (bterm [] u2 :: bs2));\n                dands.\n\n              - prove_alpha_eq4.\n                introv j; destruct n0; eauto 3 with slow.\n\n              - prove_alpha_eq4.\n                introv j; destruct n0; eauto 3 with slow.\n\n              - apply differ2_oterm; simpl; auto.\n                introv j; dorn j; cpx.\n            }\n        }\n      }\n\n      { (* fresh case *)\n        csunf comp; allsimpl.\n        apply compute_step_fresh_success in comp; repnd; subst; allsimpl.\n\n        inversion d as [|?|?|? ? ? len1 imp1]; subst; clear d.\n        allsimpl; cpx; allsimpl.\n        pose proof (imp1 (bterm [n] t1) x) as d1; autodimp d1 hyp.\n        clear imp1.\n        inversion d1 as [? ? ? d2]; subst; clear d1.\n\n        repndors; exrepnd; subst; fold_terms.\n\n        - inversion d2; subst.\n          exists (@mk_fresh o n (mk_var n)) (@mk_fresh o n (mk_var n)).\n          dands; eauto 3 with slow.\n\n        - applydup @differ2_preserves_isvalue_like in d2; auto.\n          exists (pushdown_fresh n t2) (pushdown_fresh n t1); dands; eauto 3 with slow.\n          { apply reduces_to_if_step.\n            apply compute_step_fresh_if_isvalue_like; auto. }\n          { apply differ2_alpha_pushdown_fresh_isvalue_like; auto. }\n\n        - applydup @differ2_preserves_isnoncan_like in d2; auto;[].\n          allrw app_nil_r.\n\n          pose proof (fresh_atom o (get_utokens t1 ++ get_utokens t2)) as fa; exrepnd.\n          allrw in_app_iff; allrw not_over_or; repnd.\n          rename x0 into a.\n\n          pose proof (compute_step_subst_utoken lib t1 x [(n,mk_utoken (get_fresh_atom t1))]) as comp'.\n          allrw @get_utokens_sub_cons; allrw @get_utokens_sub_nil; allsimpl.\n          allrw disjoint_singleton_l.\n          allrw @wf_fresh_iff.\n          repeat (autodimp comp' hyp); try (apply get_fresh_atom_prop); eauto 3 with slow.\n          { apply nr_ut_sub_cons; eauto with slow.\n            intro j; apply get_fresh_atom_prop. }\n          exrepnd.\n          pose proof (comp'0 [(n,mk_utoken a)]) as comp''; clear comp'0.\n          allsimpl.\n          allrw @get_utokens_sub_cons; allrw @get_utokens_sub_nil; allsimpl.\n          allrw disjoint_singleton_l.\n          repeat (autodimp comp'' hyp); exrepnd.\n\n          pose proof (differ2_subst b t1 t2 [(n, mk_utoken a)] [(n, mk_utoken a)]) as daeq.\n          repeat (autodimp daeq hyp); eauto with slow.\n          unfold differ2_alpha in daeq; exrepnd.\n\n          pose proof (compute_step_alpha lib (lsubst t1 [(n, mk_utoken a)]) u1 s) as comp'''.\n          repeat (autodimp comp''' hyp); exrepnd.\n          { apply nt_wf_subst; eauto 3 with slow. }\n          rename t2' into s'.\n\n          assert (wf_term x) as wfx.\n          { eapply compute_step_preserves_wf;[exact comp2|].\n            allrw @wf_fresh_iff.\n            apply wf_term_subst; eauto with slow. }\n\n          assert (!LIn n (free_vars x)) as ninx.\n          { intro i; apply compute_step_preserves in comp2; repnd;\n            try (apply nt_wf_subst; eauto 3 with slow).\n            rw subvars_prop in comp0; apply comp0 in i; clear comp0.\n            apply eqset_free_vars_disjoint in i; allsimpl.\n            allrw in_app_iff; allrw in_remove_nvars; allsimpl; boolvar; allsimpl; tcsp. }\n\n          applydup @alphaeq_preserves_wf_term in daeq0; auto;\n          [|apply lsubst_preserves_wf_term; eauto 3 with slow];[].\n          applydup @alphaeq_preserves_wf_term in daeq2; auto;\n          [|apply lsubst_preserves_wf_term; eauto 3 with slow];[].\n          applydup @compute_step_preserves_wf in comp'''1; auto;[].\n          applydup @alphaeq_preserves_wf_term_inv in comp'''0; auto;[].\n\n          pose proof (ind t1 u1 [n]) as q; clear ind.\n          repeat (autodimp q hyp).\n          { apply alpha_eq_preserves_osize in daeq0; rw <- daeq0; allrw @fold_subst.\n            rw @simple_osize_subst; eauto 3 with slow. }\n          pose proof (q u2 b s') as ih; clear q.\n          repeat (autodimp ih hyp); fold_terms.\n          { eapply alphaeq_preserves_hasvalue_like;[|exact comp'''0|]; eauto 3 with slow.\n            eapply alphaeq_preserves_hasvalue_like;[|apply alpha_eq_sym;exact comp''0|]; eauto 3 with slow.\n            pose proof (hasvalue_like_ren_utokens\n                          lib\n                          (lsubst w [(n, mk_utoken (get_fresh_atom t1))])\n                          [(get_fresh_atom t1,a)]) as hvl.\n            allsimpl.\n            allrw disjoint_singleton_l; allrw in_remove.\n            repeat (autodimp hvl hyp); eauto 3 with slow.\n            { intro k; repnd.\n              apply get_utokens_lsubst_subset in k; unfold get_utokens_sub in k; allsimpl.\n              allrw in_app_iff; allsimpl; repndors; tcsp. }\n            { eapply alphaeq_preserves_hasvalue_like;[|exact comp'1|]; eauto 3 with slow.\n              apply (hasvalue_like_fresh_implies lib (get_fresh_atom t1)) in hv; auto;\n              [|apply wf_subst_utokens; eauto 3 with slow\n               |intro i; apply get_utokens_subst_utokens_subset in i; allsimpl;\n                unfold get_utokens_utok_ren in i; allsimpl; allrw app_nil_r;\n                rw in_remove in i; repnd;\n                apply compute_step_preserves_utokens in comp2; eauto 3 with slow; apply comp2 in i;\n                apply get_utokens_subst in i; allsimpl; boolvar; tcsp].\n              pose proof (simple_subst_subst_utokens_aeq x (get_fresh_atom t1) n) as h.\n              repeat (autodimp h hyp).\n              eapply alphaeq_preserves_hasvalue_like in h;[exact h| |]; eauto 3 with slow.\n              apply nt_wf_subst; eauto 3 with slow.\n              apply nt_wf_eq; apply wf_subst_utokens; eauto 3 with slow.\n            }\n            rw @lsubst_ren_utokens in hvl; allsimpl; fold_terms.\n            unfold ren_atom in hvl; allsimpl; boolvar; tcsp.\n            rw @ren_utokens_trivial in hvl; simpl; auto.\n            apply disjoint_singleton_l; intro i; apply comp'4 in i; apply get_fresh_atom_prop in i; sp.\n          }\n          exrepnd.\n\n          pose proof (reduces_to_alpha lib u2 (lsubst t2 [(n, mk_utoken a)]) t) as r1.\n          repeat (autodimp r1 hyp); eauto with slow.\n          exrepnd.\n\n          pose proof (reduces_to_change_utok_sub\n                        lib t2 t2' [(n,mk_utoken a)] [(n,mk_utoken (get_fresh_atom t2))]) as r1'.\n          allrw @get_utokens_sub_cons; allrw @get_utokens_sub_nil; allsimpl.\n          allrw disjoint_singleton_l.\n          repeat (autodimp r1' hyp); try (apply get_fresh_atom_prop); eauto 3 with slow.\n          { apply nr_ut_sub_cons; eauto with slow.\n            intro j; apply get_fresh_atom_prop. }\n          exrepnd.\n          allrw disjoint_singleton_l.\n          fold_terms; allrw @fold_subst.\n\n          pose proof (reduces_to_fresh lib t2 s0 n) as q; simpl in q.\n          repeat (autodimp q hyp).\n          exrepnd.\n\n          (* 1st exists *)\n          exists (mk_fresh n z).\n\n          assert (!LIn a (get_utokens w)) as niaw.\n          { intro k; apply comp'4 in k; sp. }\n\n          pose proof (alpha_eq_subst_utokens\n                        x (subst w n (mk_utoken (get_fresh_atom t1)))\n                        [(get_fresh_atom t1, mk_var n)]\n                        [(get_fresh_atom t1, mk_var n)]) as aeqs.\n          repeat (autodimp aeqs hyp); eauto 3 with slow.\n          pose proof (simple_alphaeq_subst_utokens_subst\n                        w n (get_fresh_atom t1)) as aeqs1.\n          autodimp aeqs1 hyp.\n          eapply alpha_eq_trans in aeqs1;[|exact aeqs]; clear aeqs.\n\n          pose proof (reduces_to_alpha lib s' (subst w n (mk_utoken a)) u') as raeq.\n          repeat (autodimp raeq hyp); eauto 3 with slow; exrepnd;[].\n          rename t2'0 into u''.\n\n          assert (wf_term w) as wfw.\n          { allrw @wf_fresh_iff.\n            apply compute_step_preserves_wf in comp2;\n              [|apply wf_term_subst;eauto with slow].\n            apply alphaeq_preserves_wf_term in comp'1; auto.\n            apply lsubst_wf_term in comp'1; auto.\n          }\n\n          pose proof (reduces_to_fresh2 lib w u'' n a) as rf.\n          repeat (autodimp rf hyp); exrepnd.\n\n          pose proof (reduces_to_alpha\n                        lib\n                        (mk_fresh n w)\n                        (mk_fresh n (subst_utokens x [(get_fresh_atom t1, mk_var n)]))\n                        (mk_fresh n z0)) as r'.\n          repeat (autodimp r' hyp); eauto 3 with slow.\n          { apply nt_wf_fresh; eauto 3 with slow. }\n          { apply implies_alpha_eq_mk_fresh; eauto with slow. }\n          exrepnd.\n          rename t2'0 into f'.\n\n          (* 2nd exists *)\n          exists f'; dands; auto.\n          eapply differ2_alpha_l;[apply alpha_eq_sym; exact r'0|].\n          apply differ2_alpha_mk_fresh.\n          eapply differ2_alpha_l;[exact rf0|].\n          eapply differ2_alpha_r;[|apply alpha_eq_sym; exact q0].\n          eapply differ2_alpha_l;[apply alpha_eq_sym;apply alpha_eq_subst_utokens_same;exact raeq0|].\n          eapply differ2_alpha_r;[|apply alpha_eq_sym;apply alpha_eq_subst_utokens_same;exact r1'1].\n\n          pose proof (simple_alphaeq_subst_utokens_subst w0 n (get_fresh_atom t2)) as aeqsu.\n          autodimp aeqsu hyp.\n          { intro j; apply r1'4 in j; apply get_fresh_atom_prop in j; sp. }\n\n          eapply differ2_alpha_r;[|apply alpha_eq_sym;exact aeqsu];clear aeqsu.\n\n          apply (alpha_eq_subst_utokens_same _ _ [(a, mk_var n)]) in r1'0.\n          pose proof (simple_alphaeq_subst_utokens_subst w0 n a) as aeqsu.\n          autodimp aeqsu hyp.\n\n          eapply differ2_alpha_r;[|exact aeqsu];clear aeqsu.\n          eapply differ2_alpha_r;[|exact r1'0].\n          eapply differ2_alpha_r;[|apply alpha_eq_subst_utokens_same; exact r0].\n          apply differ2_alpha_subst_utokens; auto.\n      }\n\n    + SCase \"Exc\".\n      csunf comp; allsimpl; ginv.\n      inversion d as [? ? ? d1|?|?|? ? ? len imp]; subst; clear d.\n      exists (oterm Exc bs2) (oterm Exc bs).\n      dands; eauto 3 with slow.\n\n    + SCase \"Abs\".\n      inversion d as [? ? ? d1|?|?|? ? ? len imp]; subst; clear d.\n      csunf comp; allsimpl.\n      apply compute_step_lib_success in comp; exrepnd; subst.\n\n      assert (differ2_bterms b bs bs2) as dbs.\n      { unfold differ2_bterms, br_bterms, br_list; auto. }\n\n      pose proof (found_entry_change_bs abs oa2 vars rhs lib bs correct bs2) as fe2.\n      repeat (autodimp fe2 hyp).\n\n      { apply differ2_bterms_implies_eq_map_num_bvars in dbs; auto. }\n\n      exists (mk_instance vars bs2 rhs) (mk_instance vars bs rhs).\n\n      dands; eauto 3 with slow.\n\n      * apply reduces_to_if_step.\n        csunf; simpl; unfold on_success.\n        applydup @compute_step_lib_if_found_entry in fe2.\n        rw fe0; auto.\n\n      * pose proof (differ2_mk_instance b rhs vars bs bs2) as h.\n        repeat (autodimp h hyp).\n        { allapply @found_entry_implies_matching_entry.\n          allunfold @matching_entry; sp. }\n        { allapply @found_entry_implies_matching_entry.\n          allunfold @matching_entry; sp. }\n        { allunfold @correct_abs; sp. }\n        { allunfold @correct_abs; sp. }\nQed.\n\nLemma comp_force_int2 {o} :\n  forall lib (t1 t2 : @NTerm o) b z,\n    wf_term t1\n    -> wf_term t2\n    -> differ2 b t1 t2\n    -> reduces_to lib t1 (mk_integer z)\n    -> reduces_to lib t2 (mk_integer z).\nProof.\n  introv w1 w2 d comp.\n  unfold reduces_to in comp; exrepnd.\n  revert dependent t2.\n  revert dependent t1.\n  induction k as [n ind] using comp_ind_type; introv w1 r w2 d.\n  destruct n as [|k]; allsimpl.\n\n  - allrw @reduces_in_atmost_k_steps_0; subst.\n    inversion d as [|?|?|? ? ? len imp]; subst; clear d.\n    allsimpl; cpx; eauto 3 with slow.\n\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n\n    pose proof (comp_force_int_step2 lib t1 t2 b u) as h.\n    repeat (autodimp h hyp).\n\n    { unfold hasvalue_like.\n      exists (@mk_integer o z); dands; eauto 3 with slow; tcsp. }\n\n    exrepnd.\n\n    pose proof (reduces_in_atmost_k_steps_if_reduces_to\n                  lib k u u' (mk_integer z)) as h'.\n    repeat (autodimp h' hyp).\n    { left; sp. }\n    exrepnd.\n\n    unfold differ2_alpha in h1; exrepnd.\n\n    applydup @preserve_nt_wf_compute_step in r1; eauto 3 with slow.\n    applydup @reduces_to_preserves_wf in h2; eauto 3 with slow.\n    applydup @reduces_to_preserves_wf in h0; eauto 3 with slow.\n    applydup @alphaeq_preserves_wf_term in h4; eauto 3 with slow.\n\n    pose proof (reduces_in_atmost_k_steps_alpha\n                  lib u' u1) as h''.\n    repeat (autodimp h'' hyp); eauto 3 with slow.\n\n    pose proof (h'' k' (mk_integer z)) as h'''; clear h''.\n    autodimp h''' hyp; exrepnd.\n    inversion h'''0 as [|?|? ? ? ? x]; subst; allsimpl; cpx;\n    clear x h'''0.\n    fold_terms.\n\n    pose proof (ind k') as h.\n    autodimp h hyp;[omega|].\n    pose proof (h u1) as r; clear h.\n    repeat (autodimp r hyp); eauto 3 with slow.\n\n    pose proof (r u2) as h; clear r; repeat (autodimp h hyp); eauto 3 with slow.\n\n    pose proof (reduces_to_steps_alpha lib u2 t (mk_integer z)) as r.\n    repeat (autodimp r hyp); eauto 3 with slow.\n    exrepnd.\n    inversion r3; subst; allsimpl; cpx; fold_terms.\n    eapply reduces_to_trans; eauto.\nQed.\n\nLemma old_differ_app_F2 {o} :\n  forall (F g : @NTerm o) v x b,\n    differ2\n      b\n      (mk_apply F (mk_lam x (mk_apply g (force_int_bound v b (mk_var x) (mk_vbot v)))))\n      (mk_apply F (mk_lam x (mk_apply g (force_int (mk_var x))))).\nProof.\n  introv.\n  constructor; simpl; auto.\n  introv i; dorn i;[|dorn i]; cpx.\n  - constructor; eauto 3 with slow.\n  - constructor; constructor; simpl; auto.\n    introv i; dorn i; cpx.\n    constructor; constructor; simpl; auto.\n    introv i; dorn i;[|dorn i]; cpx; auto.\n    + constructor; eauto 3 with slow.\n    + constructor; constructor; auto.\nQed.\n\nLemma differ_app_F2 {o} :\n  forall (F g : @NTerm o) x b,\n    differ2\n      b\n      (force_int_bound_F x b F g (mk_vbot x))\n      (force_int_F x F g).\nProof.\n  introv.\n  constructor; simpl; auto.\n  introv i; dorn i;[|dorn i]; cpx.\n  - constructor; eauto 3 with slow.\n  - constructor; constructor; simpl; auto.\n    introv i; dorn i; cpx.\n    constructor; constructor; simpl; auto.\n    introv i; dorn i;[|dorn i]; cpx; auto.\n    + constructor; eauto 3 with slow.\n    + constructor; constructor; simpl; auto.\n      introv i; dorn i;[|dorn i]; cpx; auto.\n      * constructor; eauto 3 with slow.\n      * constructor; constructor.\nQed.\n\n(*\n\n  F (\\x.let x:=(x+0) in f(x)) -> z\n  =>\n  exists b.\n    F (\\x.let x:=(let v:=x in if |v|<b then v else e) in f(x)) -> z\n\n*)\nLemma comp_force_int_app_F2 {o} :\n  forall lib (F g : @NTerm o) x z b,\n    wf_term F\n    -> wf_term g\n    -> reduces_to\n         lib\n         (force_int_bound_F x b F g (mk_vbot x))\n         (mk_integer z)\n    -> reduces_to\n         lib\n         (force_int_F x F g)\n         (mk_integer z).\nProof.\n  introv wF wg r.\n  eapply (comp_force_int2 _ _ _ b);[|idtac|idtac|apply r];\n  try (apply differ_app_F2); eauto 4 with slow.\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/continuity2_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.2624082591110362}}
{"text": "From Velus Require Import Common.\nFrom Velus Require Import Operators.\nFrom Velus Require Import CoreExpr.CESyntax.\nFrom Velus Require Import Stc.StcSyntax.\nFrom Velus Require Import Stc.StcIsSystem.\nFrom Velus Require Import Clocks.\n\nFrom Coq Require Import List.\nImport List.ListNotations.\nOpen Scope list_scope.\n\nModule Type STCORDERED\n       (Import Ids   : IDS)\n       (Import Op    : OPERATORS)\n       (Import CESyn : CESYNTAX        Op)\n       (Import Syn   : STCSYNTAX   Ids Op CESyn)\n       (Import Syst  : STCISSYSTEM Ids Op CESyn Syn).\n\n  Inductive Ordered_systems: program -> Prop :=\n  | Ordered_nil:\n      Ordered_systems []\n  | Ordered_cons:\n      forall s P,\n        Ordered_systems P ->\n        Forall (fun xb =>\n                  snd xb <> s.(s_name)\n                  /\\ exists s' P', find_system (snd xb) P = Some (s', P'))\n               s.(s_subs) ->\n        Forall (fun s' => s.(s_name) <> s'.(s_name))%type P ->\n        Ordered_systems (s :: P).\n\n  Remark Ordered_systems_split:\n    forall P1 s P,\n      Ordered_systems (P1 ++ s :: P) ->\n      Forall (fun xb =>\n                  find_system (snd xb) P1 = None\n                  /\\ snd xb <> s.(s_name)\n                  /\\ exists s' P', find_system (snd xb) P = Some (s', P'))\n             s.(s_subs).\n  Proof.\n    induction P1; inversion_clear 1 as [|?? Ord]; apply Forall_Forall; auto.\n    - apply Forall_forall; auto.\n    - apply IHP1 in Ord; apply Forall_forall; intros.\n      eapply Forall_forall in Ord as (?&?&(s' &?& Find)); eauto.\n      rewrite find_system_other; auto.\n      pose proof Find as Find'; apply find_system_name in Find'.\n      apply find_system_In in Find.\n      assert (In s' (P1 ++ s :: P)) as Hin\n          by (apply in_app; right; right; auto).\n      eapply Forall_forall in Hin; eauto.\n      congruence.\n    - apply IHP1 in Ord; apply Forall_forall; intros.\n      eapply Forall_forall in Ord as (?&?&?); eauto.\n  Qed.\n\n  Lemma Ordered_systems_append:\n    forall P P',\n      Ordered_systems (P ++ P') ->\n      Ordered_systems P'.\n  Proof.\n    induction P; [intuition|].\n    intros * HnPP.\n    apply IHP; inversion_clear HnPP; assumption.\n  Qed.\n\n  Lemma Ordered_systems_find_In_systems:\n    forall P b s P',\n      Ordered_systems P ->\n      find_system b P = Some (s, P') ->\n      forall x b,\n        In (x, b) s.(s_subs) ->\n        exists s P'', find_system b P' = Some (s, P'').\n  Proof.\n    induction P as [|system]; try now inversion 2.\n    intros * Ord Find ?? Hin.\n    inv Ord.\n    simpl in Find.\n    destruct (ident_eqb (s_name system) b) eqn: E; eauto.\n    inv Find.\n    eapply Forall_forall in Hin; eauto.\n    destruct Hin; eauto.\n  Qed.\n\n  Lemma Ordered_systems_find_system:\n    forall P b s P',\n      Ordered_systems P ->\n      find_system b P = Some (s, P') ->\n      Ordered_systems P'.\n  Proof.\n    induction P as [|system]; try now inversion 2.\n    intros * Ord Find.\n    inv Ord.\n    simpl in Find.\n    destruct (ident_eqb (s_name system) b) eqn: E; eauto.\n    inv Find; auto.\n  Qed.\n Lemma find_system_later_not_Is_system_in:\n    forall f s P s' P',\n      Ordered_systems (s :: P) ->\n      find_system f P = Some (s', P') ->\n      ~ Is_system_in s.(s_name) s'.(s_tcs).\n  Proof.\n    intros * Hord Hfind Hini.\n    apply find_system_app in Hfind as (?& E &?); rewrite E, app_comm_cons in Hord.\n    pose proof Hord as Hord'; inversion_clear Hord' as [|??? Sub Hnin]; clear Sub.\n    apply Ordered_systems_split in Hord.\n    apply calls_resets_of_Is_system_in in Hini.\n    apply s_subs_in_tcs, in_map_iff in Hini as (?&?& Hin).\n    eapply Forall_forall in Hin; eauto; destruct Hin as (?&?&?&?& Find); simpl in Find.\n    apply Forall_app_weaken in Hnin; inversion_clear Hnin as [|??? Hnin'].\n    pose proof Find as Find'; apply find_system_name in Find'.\n    apply find_system_In in Find.\n    eapply Forall_forall in Find; eauto.\n    congruence.\n  Qed.\n\n  Lemma find_system_not_Is_system_in:\n    forall f s P P',\n      Ordered_systems P ->\n      find_system f P = Some (s, P') ->\n      ~ Is_system_in s.(s_name) s.(s_tcs).\n  Proof.\n    intros * Hord Hfind Hini.\n    apply find_system_app in Hfind as (?& E &?); rewrite E in Hord.\n    apply Ordered_systems_split in Hord.\n    apply calls_resets_of_Is_system_in in Hini.\n    apply s_subs_in_tcs, in_map_iff in Hini as (?&?& Hin).\n    eapply Forall_forall in Hin; eauto; destruct Hin as (?&?&?); auto.\n  Qed.\n\nEnd STCORDERED.\n\nModule StcOrderedFun\n       (Ids   : IDS)\n       (Op    : OPERATORS)\n       (CESyn : CESYNTAX        Op)\n       (Syn   : STCSYNTAX   Ids Op CESyn)\n       (Syst  : STCISSYSTEM Ids Op CESyn Syn)\n<: STCORDERED Ids Op CESyn Syn Syst.\n  Include STCORDERED Ids Op CESyn Syn Syst.\nEnd StcOrderedFun.\n", "meta": {"author": "INRIA", "repo": "velus", "sha": "116a88bc71f3608ff43ed967895743e8b9a340e0", "save_path": "github-repos/coq/INRIA-velus", "path": "github-repos/coq/INRIA-velus/velus-116a88bc71f3608ff43ed967895743e8b9a340e0/src/Stc/StcOrdered.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.26236750062085035}}
{"text": "(*===========================================================================\n  Definition of Hoare triple for arbitrary code-like data\n  For store assertions P and Q and \"code\" c, we write\n     basic P c Q\n  to mean\n     for any addresses i and j that point to code c,\n     if   it's safe to run from EIP=j with assertion Q\n     then it's safe to run from EIP=i with assertion P\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.\n\nSection Basic.\n  Context {T} `{MI: MemIs T}.\n\n  (** Basic block of position-independent code *)\n  Definition basic P (c:T) Q : spec :=\n    Forall i j:DWORD,\n    (safe @ (EIP ~= j ** Q) -->> safe @ (EIP ~= i ** P)) <@ (i -- j :-> c).\n  Global Strategy 10000 [basic].\n\n  (* Experimental: multiple alternative exits *)\n  Fixpoint otherExits (Qs: seq (DWORD * SPred)) : spec :=\n  if Qs is (i,Q)::Qs'\n  then |> safe @ (EIP ~= i ** Q) //\\\\ otherExits Qs'\n  else ltrue.\n\n  Definition multiexit P (c:T) Q Qs : spec :=\n    Forall i j:DWORD,\n    ((safe @ (EIP ~= j ** Q) //\\\\ otherExits Qs) -->> safe @ (EIP ~= i ** P)) <@ (i -- j :-> c).\n\n  (* Push spec through basic *)\n  Lemma spec_at_basic P c Q R :\n    basic P c Q @ R -|- basic (P ** R) c (Q ** R).\n  Proof.\n    rewrite /basic.\n    autorewrite with push_at. cancel1 => i.\n    autorewrite with push_at. cancel1 => j.\n    autorewrite with push_at. rewrite !sepSPA. reflexivity.\n  Qed.\n\n  (* Frame rule for Hoare triples *)\n  Lemma basic_frame R S P c Q :\n    S |-- basic P c Q ->\n    S |-- basic (P ** R) c (Q ** R).\n  Proof. by rewrite <-spec_at_basic, <-spec_frame. Qed.\n\n  (* Rule of consequence *)\n  Lemma basic_roc P' Q' S P c Q:\n    P |-- P' ->\n    Q' |-- Q ->\n    S |-- basic P' c Q' ->\n    S |-- basic P c Q.\n  Proof.\n    move=> HP HQ H. rewrite /basic in H.\n    setoid_rewrite <-HP in H. setoid_rewrite ->HQ in H. apply H.\n  Qed.\n\n  (* Morphisms for triples *)\n  Global Instance basic_entails_m:\n    Proper (lentails --> eq ==> lentails ++> lentails) basic.\n  Proof.\n    move => P P' HP c _ <- Q Q' HQ. apply: basic_roc; try eassumption.\n    done.\n  Qed.\n\n  Global Instance basic_equiv_m:\n    Proper (lequiv ==> eq ==> lequiv ==> lequiv) basic.\n  Proof.\n    move => P P' HP c _ <- Q Q' HQ. rewrite {1}/basic.\n    setoid_rewrite HQ. setoid_rewrite HP. reflexivity.\n  Qed.\n\n  (* Special case of consequence for precondition *)\n  Lemma basic_roc_pre P' S P c Q:\n    P |-- P' ->\n    S |-- basic P' c Q ->\n    S |-- basic P c Q.\n  Proof. move=> HP H. by rewrite ->HP. Qed.\n\n  (* Special case of consequence for postcondition *)\n  Lemma basic_roc_post Q' S P c Q:\n    Q' |-- Q ->\n    S |-- basic P c Q' ->\n    S |-- basic P c Q.\n  Proof. move=> HQ H. by rewrite <-HQ. Qed.\n\n  Lemma basic_exists A S P c Q:\n    (forall a:A, S |-- basic (P a) c Q) ->\n    S |-- basic (lexists P) c Q.\n  Proof. rewrite /basic => H. specintros => i j a. eforalls H. simple apply H. Qed.\n\n  Global Instance AtEx_basic P c Q : AtEx (basic P c Q).\n  Proof. rewrite /basic. apply _. Qed.\n\n  Lemma basic_basic_context R S' P' Q' S P c Q:\n    S' |-- basic P' c Q' ->\n    S |-- S' ->\n    P |-- P' ** R ->\n    Q' ** R |-- Q ->\n    S |-- basic P c Q.\n  Proof. move=> Hc HS HP HQ. rewrite ->HS, ->HP, <-HQ. exact: basic_frame. Qed.\n\n  (* Combine rule of consequence and frame *)\n  Lemma basic_basic R P' Q' S P c Q:\n    |-- basic P' c Q' ->\n    P |-- P' ** R ->\n    Q' ** R |-- Q ->\n    S |-- basic P c Q.\n  Proof.\n    move=> Hc HP HQ. apply: basic_basic_context; try eassumption. done.\n  Qed.\nEnd Basic.\n\nHint Rewrite @spec_at_basic : push_at.\n\nHint Unfold basic : specapply.\n\nModule Export Existentials_basic.\n  Import Existentials.\n\n  Lemma pq_basic {M} {HM: MemIs M} t c Q:\n    match find t with\n    | Some (mkf _ f) =>\n        PullQuant (basic (eval t) c Q) (fun a => basic (f a) c Q)\n    | None => True\n    end.\n  Proof.\n    move: (@find_correct_pull t). case: (find t) => [[A f]|]; last done.\n    red. move=> Heval. rewrite ->Heval.\n    apply basic_exists => a. by apply lforallL with a.\n  Qed.\n\n  Hint Extern 0 (PullQuant (@basic ?M ?HM ?P ?c ?Q) _) =>\n    let t := quote_term P in\n    apply (@pq_basic M HM t c Q) : pullquant.\n\nEnd Existentials_basic.\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/basic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2622494570337112}}
{"text": "Require Import Leapfrog.Benchmarks.ProofHeader.\nRequire Import Leapfrog.Benchmarks.SelfComparison.\n\nDeclare ML Module \"mirrorsolve\".\nSetSMTSolver \"cvc4\".\nSetSMTLang \"BV\".\n\nModule Positive.\n  Lemma equiv_read_undef:\n    lang_equiv_state\n        (P4A.interp ReadUndef.aut)\n        (P4A.interp ReadUndef.aut)\n        ReadUndef.ParseEth\n        ReadUndef.ParseEth.\n  Proof.\n    solve_lang_equiv_state_axiom ReadUndef.state_eqdec ReadUndef.state_eqdec false.\n  Time Qed.\nEnd Positive.\n\nModule Negative.\n  Lemma equiv_read_undef:\n    lang_equiv_state\n        (P4A.interp ReadUndefIncorrect.aut)\n        (P4A.interp ReadUndefIncorrect.aut)\n        ReadUndefIncorrect.ParseEth\n        ReadUndefIncorrect.ParseEth.\n  Proof.\n    Fail solve_lang_equiv_state_axiom ReadUndefIncorrect.state_eqdec ReadUndefIncorrect.state_eqdec false.\n  Time Abort.\nEnd Negative.\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/SelfComparisonProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2622252341202301}}
{"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 realm_activate_ops_spec (rd: Pointer) (adt: RData) : option RData :=\n    rely (peq (base rd) buffer_loc);\n    when gidx == ((buffer (priv adt)) @ (offset rd));\n    let gn := (gs (share adt)) @ gidx in\n    rely (g_tag (ginfo gn)) =? GRANULE_STATE_RD;\n    rely prop_dec (glock gn = Some CPU_ID);\n    if g_measurement_algo (gnorm gn) =? MEASUREMENT_ALGO_SHA256 then\n      if measure_finish (g_measurement_ctx (gnorm gn)) =? 0 then\n        let g' := gn {gnorm: (gnorm gn) {g_measurement: 0} {g_realm_state: REALM_STATE_ACTIVE}} in\n        Some adt {share: (share adt) {gs: (gs (share adt)) # gidx == g'}}\n      else None\n    else\n      let g' := gn {gnorm: (gnorm gn) {g_realm_state: REALM_STATE_ACTIVE}} in\n      Some adt {share: (share adt) {gs: (gs (share adt)) # gidx == g'}}.\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/RmiOps/Specs/realm_activate_ops.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160664, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2622252341202301}}
{"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.stlc_mu Require Export lang.\nFrom fae_gtlc_mu.cast_calculus Require Import types_notations.\nFrom fae_gtlc_mu.cast_calculus Require Export types.\n\nSection compat_cast_star_tau.\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_star_tau:\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 (factorDown_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    iIntros (ei' K' v v' fs) \"(#Hfs & #Hvv' & #Hei' & Hv')\".\n    rewrite /back_cast_ar /𝓕c /𝓕. rewrite factorization_subst_rewrite. fold (𝓕 pC1). fold (𝓕 pC2).\n    fold (𝓕c pC1 fs). fold (𝓕c pC2 fs). rewrite /factorization.\n    iDestruct \"Hfs\" as \"[% Hfs']\"; iAssert (rel_cast_functions A fs) with \"[Hfs']\" as \"Hfs\". iSplit; done. iClear \"Hfs'\".\n    (** implementation *)\n    iApply wp_pure_step_later; try auto. apply pure_fact_down; auto. done. by eauto; eexists. simpl. done. iNext.\n    (** specification *)\n    iMod ((step_lam _ ei' K') with \"[Hv']\") as \"Hv'\"; auto. asimpl.\n    (** first IH *)\n    rewrite 𝓕c_rewrite.\n    iApply (wp_bind [CastCtx _ _]). iApply (wp_wand with \"[-]\").\n    iApply (IHpC1 ei' (AppRCtx _ :: K') with \"[Hv']\"); auto.\n    (** .... *)\n    iIntros (w) \"blaa\".  iDestruct \"blaa\" as (w') \"[Hw' #Hww']\".\n    simpl. rewrite -𝓕c_rewrite.\n    (** second IH *)\n    iApply (wp_wand with \"[-]\").\n    iApply (IHpC2 ei' K' with \"[Hw']\"); auto.\n    auto.\n  Qed.\n\nEnd compat_cast_star_tau.\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/star_tau.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878414043816, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2622252281041141}}
{"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\nSet Implicit Arguments.\n\nHint Constructors Thread.program_step.\nHint Constructors Thread.step.\n\n\nInductive union {A} {E} (step: E -> A -> A -> Prop) (c1 c2: A) : Prop :=\n| step_evt_intro e\n    (USTEP: step e c1 c2)\n.\nHint Constructors union.\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_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\n\nDefinition mem_sub (cmp: Loc.t -> Time.t -> option View.t -> option View.t -> Prop) (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 loctmeq (l: Loc.t) (t: Time.t) (r1 r2: option View.t) : Prop := r1 = r2.\nHint Unfold loctmeq.\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\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_loc.\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/DRFBase.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.26216657436983726}}
{"text": "Require Import floyd.proofauto.\nLocal Open Scope logic.\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.\nRequire Import veric.expr_lemmas3.\n\nOpaque Snuffle20. Opaque Snuffle.Snuffle. Opaque prepare_data.\nOpaque fcore_result.\n\nLemma L32_spec_ok: semax_body SalsaVarSpecs SalsaFunSpecs\n       f_L32 L32_spec.\nProof.\nstart_function.\nTime forward. (*8.8*)\nTime entailer!. (*0.8*)\nassert (W: Int.zwordsize = 32). reflexivity.\nassert (U: Int.unsigned Int.iwordsize=32). reflexivity. simpl.\nremember (Int.ltu c Int.iwordsize) as d. symmetry in Heqd.\ndestruct d; simpl.\n{ clear Heqd.\n  remember (Int.ltu (Int.sub (Int.repr 32) c) Int.iwordsize) as z. symmetry in Heqz.\n  destruct z.\n  - simpl; split; trivial. split. 2: split; trivial.\n    apply ltu_inv in Heqz. unfold Int.sub in *.\n    rewrite (Int.unsigned_repr 32) in *; try (rewrite int_max_unsigned_eq; omega).\n    rewrite Int.unsigned_repr in Heqz. 2: rewrite int_max_unsigned_eq; omega.\n    unfold Int.rol, Int.shl, Int.shru. rewrite or_repr.\n    rewrite Z.mod_small, W; simpl; try omega.\n    rewrite Int.unsigned_repr. 2: rewrite int_max_unsigned_eq; omega.\n    rewrite Int.and_mone. trivial.\n  - apply ltu_false_inv in Heqz. rewrite U in *.\n    unfold Int.sub in Heqz.\n    rewrite (Int.unsigned_repr 32), Int.unsigned_repr in Heqz. omega.\n    rewrite int_max_unsigned_eq; omega.\n    rewrite int_max_unsigned_eq; omega. }\n{ apply ltu_false_inv in Heqd. rewrite U in *. omega. }\nTime Qed. (*0.9*)\n\nLemma ld32_spec_ok: semax_body SalsaVarSpecs SalsaFunSpecs\n       f_ld32 ld32_spec.\nProof.\nstart_function.\ndestruct B as (((b0, b1), b2), b3). simpl.\nspecialize Byte_max_unsigned_Int_max_unsigned; intros BND.\nassert (RNG3:= Byte.unsigned_range_2 b3).\nassert (RNG2:= Byte.unsigned_range_2 b2).\nassert (RNG1:= Byte.unsigned_range_2 b1).\nassert (RNG0:= Byte.unsigned_range_2 b0).\nTime forward. (*1.8*)\nTime entailer!; omega. (*1.1*)\nTime forward. (*2*)\nTime entailer!; omega. (*1.1*)\nTime forward. (*1.1*)\nTime forward. (*2.2*)\nTime entailer!; omega. (*1.3*)\nTime forward. (*1.5*)\ndrop_LOCAL 1%nat.\nTime forward.\nTime entailer!; omega. (*1.3*)\nTime forward. (*5.2*)\nTime entailer!.\n  assert (WS: Int.zwordsize = 32). reflexivity.\n  assert (TP: two_p 8 = Byte.max_unsigned + 1). reflexivity.\n  assert (BMU: Byte.max_unsigned = 255). reflexivity. simpl.\n  repeat rewrite Int.shifted_or_is_add; try repeat rewrite Int.unsigned_repr; try omega.\n  f_equal. f_equal. simpl.\n    rewrite Z.mul_add_distr_r.\n    rewrite (Zmult_comm (Z.pow_pos 2 8)).\n    rewrite (Zmult_comm (Z.pow_pos 2 16)).\n    rewrite (Zmult_comm (Z.pow_pos 2 24)).\n    simpl. repeat rewrite <- two_power_pos_correct.\n    rewrite Z.mul_add_distr_r.\n    rewrite Z.mul_add_distr_r.\n    repeat rewrite <- Z.mul_assoc.\n    rewrite <- Z.add_assoc. rewrite <- Z.add_assoc. rewrite Z.add_comm. f_equal.\n    rewrite Z.add_comm. f_equal. rewrite Z.add_comm. f_equal.\n  rewrite TP, BMU, Z.mul_add_distr_l, int_max_unsigned_eq. omega.\n  rewrite TP, BMU, Z.mul_add_distr_l, int_max_unsigned_eq. omega.\n  rewrite TP, BMU, Z.mul_add_distr_l, int_max_unsigned_eq. omega.\nTime Qed. (*6.7*)\n\nFixpoint lendian (l:list byte): Z :=\n  match l with\n    nil => 0\n  | h::t => Byte.unsigned h + 2^8 * lendian t\n  end.\n\nLemma lendian4 b0 b1 b2 b3: littleendian (b0,b1,b2,b3) = Int.repr(lendian [b0;b1;b2;b3]).\nProof. simpl. rewrite Zplus_0_r. \nrewrite ! Z.mul_add_distr_l, ! (Z.mul_assoc _ (2^8)), <- ! Z.add_assoc; reflexivity.\nQed.\n\nLemma lendian_nil: lendian [] = 0. Proof. reflexivity. Qed.\nLemma lendian_singleton b: lendian [b] = Byte.unsigned b. Proof. simpl; omega. Qed.\n\nLemma lendian_app: forall l1 l2, lendian (l1++l2) =\n   lendian l1 + 2^(8*Zlength l1) * lendian l2.\nProof.\ninduction l1; intros.\n+ rewrite Zlength_nil; simpl; omega.  \n+ simpl. rewrite IHl1. rewrite Zlength_cons; clear IHl1.\n  rewrite ! Z.mul_add_distr_l, <- ! Z.add_assoc, Z.mul_assoc, Z.pow_pos_fold.\n  f_equal. f_equal. \n  rewrite <- Zpower_exp, <- Zmult_succ_r_reverse, Z.add_comm; trivial. omega.\n  specialize (Zlength_nonneg l1); omega. \nQed.\n\nLemma lendian_range: forall l, 0 <= lendian l < 2^(8*Zlength l).\nProof. induction l; simpl; intros.\n+ omega.\n+ rewrite Zlength_cons. destruct (Byte.unsigned_range a).\n  assert (Z.pow_pos 2 8 = 256) by reflexivity.\n  split. rewrite H1. apply Z.add_nonneg_nonneg; trivial; omega.\n  rewrite <- Zmult_succ_r_reverse, Z.pow_add_r; [| specialize (Zlength_nonneg l); omega | omega ].\n  rewrite Z.mul_comm. change (Z.pow_pos 2 8) with (2^8).\n  assert (Byte.unsigned a + lendian l * 2 ^ 8 < Byte.modulus + lendian l * 2 ^ 8). omega.\n  eapply Z.lt_le_trans. apply H2. clear H2 H0. change Byte.modulus with 256.\n  change (2^8) with 256. specialize (Z.mul_add_distr_r 1 (lendian l) 256). rewrite Z.mul_1_l.\n  intros X; rewrite <- X; clear X. apply Zmult_le_compat_r; omega.\nQed.\n\nDefinition bendian l: Z := lendian (rev l).\nLemma bendian_nil: bendian [] = 0. Proof. reflexivity. Qed.\nLemma bendian_singleton b: bendian [b] = Byte.unsigned b. Proof. unfold bendian. simpl; omega. Qed.\n\nLemma bendian_app l1 l2: bendian (l1++l2) = bendian l2 + 2^(8*Zlength l2) * bendian l1.\nProof. unfold bendian. rewrite rev_app_distr, lendian_app, Zlength_rev; trivial. Qed.\n\nLemma bendian_range l: 0 <= bendian l < 2^(8*Zlength l).\nProof. unfold bendian. specialize (lendian_range (rev l)). rewrite Zlength_rev; trivial. Qed.\n\nLemma Zlor_2powpos_add a b (n:positive) (B: 0<=b <Z.pow_pos 2 n):\n      a * Z.pow_pos 2 n + b = Z.lor (a * Z.pow_pos 2 n) b.\nProof. apply Byte.equal_same_bits; intros.\n  rewrite Z.lor_spec. apply Byte.Z_add_is_or; trivial.\n  intros. rewrite Z.pow_pos_fold in *.\n  destruct (zlt j (Z.pos n)).\n  + rewrite Z.mul_pow2_bits_low; simpl; trivial.\n  + rewrite <- (positive_nat_Z n) in g, B.\n    erewrite (Byte.Ztestbit_above _ b), andb_false_r. trivial. 2: eassumption.\n    rewrite two_power_nat_equiv. apply B.\nQed. \n\nLemma Byte_unsigned_range_32 b: 0 <= Byte.unsigned b <= Int.max_unsigned.\nProof. destruct (Byte.unsigned_range_2 b). specialize Byte_Int_max_unsigned; omega. Qed.\n\nLemma Byte_unsigned_range_64 b: 0 <= Byte.unsigned b <= Int64.max_unsigned.\nProof. destruct (Byte.unsigned_range_2 b).\n  unfold Int64.max_unsigned; simpl.\n  unfold Byte.max_unsigned in H0; simpl in H0; omega.\nQed. \n\nAxiom myadmit: False.\n\nLemma dl64_spec_ok: semax_body SalsaVarSpecs SalsaFunSpecs\n       f_dl64 dl64_spec.\nProof.\nstart_function.\ndestruct B as (((b0, b1), b2), b3).\ndestruct C as (((c0, c1), c2), c3).\nunfold QuadByte2ValList; simpl. \nforward. simpl. rewrite Int.signed_repr.\n2: rewrite int_min_signed_eq, int_max_signed_eq; omega.\n\nforward_for_simple_bound 8 (EX i:Z, \n  (PROP  ()\n   LOCAL (temp _x x; temp _u (Vlong (Int64.repr (bendian (sublist 0 i [b0;b1;b2;b3;c0;c1;c2;c3])))))\n   SEP (data_at Tsh (tarray tuchar 8)\n          (map Vint (map Int.repr (map Byte.unsigned \n            [b0;b1;b2;b3;c0;c1;c2;c3]))) x))).\n1: solve [ entailer! ]. \n{ rename H into I.\n  forward. \n  + entailer!.\n    apply zero_ext_range'. change Int.zwordsize with 32; omega.\n  + forward. entailer!. exfalso. (*tc_error tulong int*) apply myadmit.\n    entailer!. clear H1 H0 H. f_equal. rewrite <- (sublist_rejoin 0 i (i+1)).\n    2: omega. 2: rewrite ! Zlength_cons, Zlength_nil; omega.\n    rewrite pure_lemmas.sublist_singleton with (d:=Byte.zero).\n    2: rewrite ! Zlength_cons, Zlength_nil; omega.\n    simpl.\n    unfold Int64.or. rewrite Int64.shl_mul_two_p, (Int64.unsigned_repr 8).\n    2: unfold Int64.max_unsigned; simpl; omega.\n    replace (Znth i\n                 [Byte.unsigned b0; Byte.unsigned b1; Byte.unsigned b2; Byte.unsigned b3; \n                 Byte.unsigned c0; Byte.unsigned c1; Byte.unsigned c2; Byte.unsigned c3] 0) \n       with (Byte.unsigned (Znth i [b0; b1; b2; b3; c0; c1; c2; c3] Byte.zero)).\n    2: erewrite <- (Znth_map' Byte.unsigned) with (d:= Z.zero); [ reflexivity | apply I ].\n    rewrite zero_ext_inrange.\n    2: rewrite Int.unsigned_repr; [ apply Byte.unsigned_range_2 | apply Byte_unsigned_range_32 ].\n    rewrite Int.unsigned_repr. 2: apply Byte_unsigned_range_32.\n    rewrite Int64.unsigned_repr. 2: apply Byte_unsigned_range_64.\n    change (two_p 8) with 256. \n    rewrite bendian_app, bendian_singleton. simpl.\n    unfold Int64.mul.\n    rewrite (Int64.unsigned_repr 256). 2: unfold Int64.max_unsigned; simpl; omega.\n    rewrite Zplus_comm, Zmult_comm, Zlor_2powpos_add. 2: apply Byte.unsigned_range.\n    f_equal. f_equal. remember (bendian (sublist 0 i [b0; b1; b2; b3; c0; c1; c2; c3])) as q.\n    specialize (Int64.shifted_or_is_add  (Int64.repr q) Int64.zero 8).\n    change (two_p 8) with 256. rewrite Int64.unsigned_zero, Z.add_0_r.\n    intros X; rewrite <- X, Int64.or_zero; clear X.\n     2: replace Int64.zwordsize with 64 by reflexivity; omega. 2: omega.\n    rewrite Int64.shl_mul_two_p, (Int64.unsigned_repr 8).\n    2: unfold Int64.max_unsigned; simpl; omega.\n    unfold Int64.mul.\n    assert (Q: 0 <= q < 2^56).\n    { specialize (bendian_range (sublist 0 i [b0; b1; b2; b3; c0; c1; c2; c3])).             \n      rewrite Zlength_sublist, Zminus_0_r, <- Heqq. intros. \n      assert (2^(8 * i) <= 2^56) by (apply Z.pow_le_mono_r; omega). omega.\n      omega. change (Zlength [b0; b1; b2; b3; c0; c1; c2; c3]) with 8; omega. }\n    change (2^56) with 72057594037927936 in Q.\n    change (two_p 8) with 256. change (Z.pow_pos 2 8) with 256. \n    rewrite (Int64.unsigned_repr 256).\n    2: unfold Int64.max_unsigned; simpl; omega.\n    rewrite (Int64.unsigned_repr q).\n    2: unfold Int64.max_unsigned; simpl; omega.\n    rewrite Int64.unsigned_repr; trivial.\n    unfold Int64.max_unsigned; simpl; omega. }\nforward. apply prop_right.\nclear H H0. \nunfold bendian. simpl. \nrewrite ! Z.mul_add_distr_l, ! (Z.mul_assoc _ (Z.pow_pos 2 8)),\n        <- ! Z.add_assoc, ! Z.mul_0_r, Z.add_0_r.\nreflexivity.\nQed.\n\nLemma div_bound u n (N:1<n): 0 <= Int.unsigned u / n <= Int.max_unsigned.\nProof.\ndestruct (Int.unsigned_range u).\nsplit. apply Z_div_pos; try omega. \nassert (Int.unsigned u / n <Int.modulus).\n2: unfold Int.max_unsigned; omega.\napply Z.div_lt_upper_bound; try omega.\nspecialize (Z.mul_lt_mono_nonneg 1 n (Int.unsigned u) (Int.modulus)).\nrewrite Z.mul_1_l. intros Q; apply Q; trivial.\nQed. \n\nLemma ST32_spec_ok: semax_body SalsaVarSpecs SalsaFunSpecs\n       f_st32 st32_spec.\nProof. \nstart_function. \nremember (littleendian_invert u) as U. destruct U as [[[u0 u1] u2] u3].\n\nTime forward_for_simple_bound 4 (EX i:Z,\n  (PROP  ()\n   LOCAL (temp _x x; temp _u (Vint (iterShr8 u (Z.to_nat i))))\n   SEP (data_at Tsh (tarray tuchar 4) \n              (sublist 0 i (map Vint (map Int.repr (map Byte.unsigned ([u0;u1;u2;u3])))) ++ \n               list_repeat (Z.to_nat(4-i)) Vundef)\n                x))).\n{ entailer!. }\n{ rename H into I.\n  Time assert_PROP (field_compatible (Tarray tuchar 4 noattr) [] x /\\ isptr x)\n       as FC_ptrX by solve [entailer!]. (*2.3*)\n  destruct FC_ptrX as [FC ptrX].\n  Time forward. (*3.2*)\n  Time forward. (*0.8*)\n  rewrite Z.add_comm, Z2Nat.inj_add; try omega.\n  Time entailer!. (*1.5*)\n  unfold upd_Znth.\n  autorewrite with sublist.\n  rewrite field_at_data_at. simpl. unfold field_address. simpl.\n  if_tac. 2: solve [contradiction].\n  replace (4 - (1 + i)) with (4-i-1) by omega.\n  rewrite isptr_offset_val_zero; trivial. clear H.\n  apply data_at_ext. rewrite Zplus_comm.\n        assert (ZW: Int.zwordsize = 32) by reflexivity.\n        assert (EIGHT: Int.unsigned (Int.repr 8) = 8). apply Int.unsigned_repr. rewrite int_max_unsigned_eq; omega.\n        inv HeqU. clear - ZW EIGHT I.\n        destruct (zeq i 0); subst; simpl. f_equal. f_equal.\n        { rewrite Byte.unsigned_repr.\n            rewrite (Fcore_Zaux.Zmod_mod_mult _ (2^8) (2^8)). 2: cbv; trivial. 2: cbv; intros; discriminate.\n            rewrite (Fcore_Zaux.Zmod_mod_mult _ (2^16) (2^8)). 2: cbv; trivial. 2: cbv; intros; discriminate.\n            rewrite <- (Int.zero_ext_mod 8).\n              rewrite Int.repr_unsigned; trivial.\n              rewrite ZW; omega.\n          assert (0 <= ((Int.unsigned u mod Z.pow_pos 2 24) mod Z.pow_pos 2 16) mod Z.pow_pos 2 8 < Byte.modulus).\n            apply Z_mod_lt. cbv; trivial.\n            unfold Byte.max_unsigned. omega. }\n        destruct (zeq i 1); subst; simpl. f_equal. f_equal. f_equal.\n        { rewrite Byte.unsigned_repr.\n          Focus 2. assert (0 <= (Int.unsigned u mod Z.pow_pos 2 24) mod Z.pow_pos 2 16 / Z.pow_pos 2 8 < Byte.modulus).\n                   Focus 2. unfold Byte.max_unsigned. omega.\n                   split. apply Z_div_pos. cbv; trivial. apply Z_mod_lt. cbv; trivial.\n                   apply Zdiv_lt_upper_bound. cbv; trivial. apply Z_mod_lt. cbv; trivial.\n          apply Int.same_bits_eq. rewrite ZW; intros.\n          rewrite Int.bits_zero_ext, Int.testbit_repr; try apply H.\n          rewrite (Z.div_pow2_bits _ 8); try omega.\n          rewrite (Int.Ztestbit_mod_two_p 16); try omega.\n          rewrite (Int.Ztestbit_mod_two_p 24); try omega.\n          rewrite Int.bits_shru; try omega. rewrite EIGHT, ZW. (* Ztest_Inttest.*)\n          remember (zlt i 8). \n          destruct s. repeat rewrite zlt_true. trivial. omega. omega. omega.\n          rewrite zlt_false. trivial. omega. }\n        destruct (zeq i 2); subst; simpl. f_equal. f_equal. f_equal.\n          f_equal.\n        { rewrite Byte.unsigned_repr.\n          Focus 2. assert (0 <= Int.unsigned u mod Z.pow_pos 2 24 / Z.pow_pos 2 16 < Byte.modulus).\n                   2: unfold Byte.max_unsigned; omega.\n                   split. apply Z_div_pos. cbv; trivial. apply Z_mod_lt. cbv; trivial.\n                   apply Zdiv_lt_upper_bound. cbv; trivial. apply Z_mod_lt. cbv; trivial.\n          apply Int.same_bits_eq. rewrite ZW; intros.\n          rewrite Int.bits_zero_ext, Int.testbit_repr; try apply H.\n          rewrite Int.bits_shru; try omega. rewrite EIGHT, ZW.\n          rewrite (Z.div_pow2_bits _ 16); try omega.\n          rewrite (Int.Ztestbit_mod_two_p 24); try omega.\n          (*rewrite Ztest_Inttest.*)\n          remember (zlt i 8). \n          destruct s. repeat rewrite zlt_true. rewrite Int.bits_shru, EIGHT, ZW.\n              rewrite zlt_true. rewrite <- Z.add_assoc. reflexivity. omega. omega. omega. omega.\n          rewrite zlt_false. trivial. omega. }\n        destruct (zeq i 3); subst; simpl.\n        + f_equal. f_equal. f_equal. f_equal.\n          f_equal.\n          rewrite Byte.unsigned_repr.  \n          Focus 2. assert (0 <= Int.unsigned u / Z.pow_pos 2 24 < Byte.modulus).\n                   2: unfold Byte.max_unsigned; omega.\n                   split. apply Z_div_pos. cbv; trivial. apply Int.unsigned_range. \n                   apply Zdiv_lt_upper_bound. cbv; trivial. apply Int.unsigned_range. \n          rewrite ! Int.shru_div_two_p.\n          rewrite (Int.unsigned_repr 8); [| cbv; split; congruence ].\n          rewrite (Int.unsigned_repr (Int.unsigned u / two_p 8)), Zdiv.Zdiv_Zdiv; [ | cbv; congruence | cbv; congruence | ] .\n          2: apply div_bound; cbv; trivial.\n          replace (two_p 8 * two_p 8)%Z with (two_p 16) by reflexivity.\n          rewrite (Int.unsigned_repr (Int.unsigned u / two_p 16)), Zdiv.Zdiv_Zdiv; [ | cbv; congruence | cbv; congruence | ] .\n          2: apply div_bound; cbv; trivial.\n          replace (two_p 16 * two_p 8)%Z with (two_p 24) by reflexivity.\n          apply zero_ext_inrange.\n          rewrite (Int.unsigned_repr (Int.unsigned u / Z.pow_pos 2 24)).\n          2: apply div_bound; cbv; trivial. \n          assert (Int.unsigned u / Z.pow_pos 2 24 < two_p 8). 2: omega.\n          apply Z.div_lt_upper_bound; trivial. apply Int.unsigned_range.\n        + omega. \n }\n forward. \nTime Qed. (*4.9*) \n\nFixpoint iter64Shr8 (u : int64) (n : nat) {struct n} : int64 :=\n  match n with\n  | 0%nat => u\n  | S n' => Int64.shru (iter64Shr8 u n') (Int64.repr 8)\n  end.\n\nDefinition iter64Shr8' (u : int64) (n : nat): int64 := \n   Int64.shru u (Int64.mul (Int64.repr 8) (Int64.repr (Z.of_nat n))).\n\nLemma iter64: forall n u (N: Z.of_nat n < 8), \n      iter64Shr8 u n = iter64Shr8' u n.\nProof. unfold iter64Shr8'.\n  assert (W: Int64.iwordsize = Int64.repr 64) by reflexivity.\n  induction n; simpl; intros.\n+ rewrite Int64.mul_zero, Int64.shru_zero; trivial.\n+ rewrite Zpos_P_of_succ_nat in *.\n  rewrite IHn, Int64.shru_shru, Int64.mul_commut; clear IHn.\n  - f_equal.\n    specialize (Int64.mul_add_distr_l (Int64.repr (Z.of_nat n)) Int64.one (Int64.repr 8)).\n    rewrite (Int64.mul_commut Int64.one), Int64.mul_one.\n    intros X; rewrite <- X, Int64.mul_commut, Int64.add_unsigned; clear X.\n    f_equal. f_equal. unfold Int64.one.\n    rewrite 2 Int64.unsigned_repr; try reflexivity.   \n    unfold Int64.max_unsigned; simpl; omega.\n    unfold Int64.max_unsigned; simpl; omega.\n - rewrite W, Int64.mul_signed, 2 Int64.signed_repr.\n   unfold Int64.ltu. rewrite (Int64.unsigned_repr 64), if_true; trivial.\n   rewrite Int64.unsigned_repr. omega.\n   unfold Int64.max_unsigned; simpl; omega.\n   unfold Int64.max_unsigned; simpl; omega.\n   unfold Int64.min_signed, Int64.max_signed; simpl; omega.\n   unfold Int64.min_signed, Int64.max_signed; simpl; omega.\n - rewrite W. unfold Int64.ltu. rewrite if_true; trivial.\n - rewrite W. unfold Int64.ltu. rewrite Int64.mul_signed, Int64.add_signed, if_true; trivial.\n   rewrite (Int64.signed_repr 8). \n   2: unfold Int64.min_signed, Int64.max_signed; simpl; omega.\n   rewrite (Int64.signed_repr (Z.of_nat n)).   \n   2: unfold Int64.min_signed, Int64.max_signed; simpl; omega.\n   rewrite Int64.signed_repr. \n   2: unfold Int64.min_signed, Int64.max_signed; simpl; omega.\n   rewrite 2 Int64.unsigned_repr. omega.\n   unfold Int64.max_unsigned; simpl; omega.\n   unfold Int64.max_unsigned; simpl; omega.\n - omega.\nQed. \n\nLemma unsigned_repr' z (Q: 0 <= z < Byte.modulus): Byte.unsigned (Byte.repr z) = z.\nProof. apply Byte.unsigned_repr. unfold Byte.max_unsigned. omega. Qed.\n\nLemma shru_shru x n m (NM:Int64.unsigned n + Int64.unsigned m <= Int64.max_unsigned): \n      Int64.shru (Int64.shru x n) m = Int64.shru x (Int64.add n m).\nProof. rewrite 3 Int64.shru_div_two_p. f_equal.\nspecialize (Int64.unsigned_range n).\nspecialize (Int64.unsigned_range m).\nspecialize (Int64.unsigned_range x). intros X M N.\nrewrite Int64.unsigned_repr, Zdiv_Zdiv, <- two_p_is_exp, Int64.add_unsigned, \nInt64.unsigned_repr; trivial; try apply two_p_gt_ZERO; try omega.\nsplit. apply Z_div_pos; trivial. apply two_p_gt_ZERO; try omega. omega.\nassert (Int64.unsigned x / two_p (Int64.unsigned n) < Int64.max_unsigned +1). 2: omega.\nspecialize (two_p_gt_ZERO (Int64.unsigned n)); intros A.\napply Z.div_lt_upper_bound. omega. eapply Z.lt_le_trans. apply X.\nunfold Int64.max_unsigned. replace (Int64.modulus - 1 + 1) with Int64.modulus by omega.\nspecialize (Zmult_le_compat_l 1 (two_p (Int64.unsigned n)) Int64.modulus).\nrewrite Z.mul_1_r, Z.mul_comm. intros Y; apply Y; omega.\nQed. \n(*\nLemma TS64_spec_ok: semax_body SalsaVarSpecs SalsaFunSpecs\n       f_ts64 ts64_spec.\nProof. \nstart_function. \nremember (bigendian64_invert u) as U. \ndestruct U as [B C]. destruct B as [[[b3 b2] b1] b0].\ndestruct C as [[[c3 c2] c1] c0]. (* unfold littleendian64_invert in HeqU. simpl in HeqU.*)\n(*unfold Sfor. forward. forward_seq.*)\n(*Parameter Data: Z -> list val.*)\n(*assert_PROP (isptr x) by entailer!. rename H into isptrX.*)\nTime forward_for_simple_bound 8 (EX i:Z, \n  (PROP  ()\n   LOCAL (temp _x x; temp _u (Vlong (iter64Shr8 u (Z.to_nat i))))\n   SEP (data_at Tsh (tarray tuchar 8) \n              (list_repeat (Z.to_nat(8-i)) Vundef ++\n               sublist (8-i) 8 (map Vint (map Int.repr (map Byte.unsigned ([b3;b2;b1;b0;c3;c2;c1;c0])))))\n                x))).\n{ entailer!. } 2: solve [forward].\n{ rename H into I.\n  Time assert_PROP (field_compatible (Tarray tuchar 8 noattr) [] x /\\ isptr x) \n       as FC_ptrX by solve [entailer!]. \n  destruct FC_ptrX as [FC ptrX].x\nDefinition typecheck_expr := \nfix\ntypecheck_expr (CS : compspecs) (Delta : tycontext) (e : expr) {struct e} :\n  tc_assert :=\n  let tcr := typecheck_expr CS Delta in\n  match e with\n  | Econst_int _ Tvoid => tc_FF (invalid_expression e)\n  | Econst_int _ (Tint I8 _ _) => tc_FF (invalid_expression e)\n  | Econst_int _ (Tint I16 _ _) => tc_FF (invalid_expression e)\n  | Econst_int _ (Tint I32 _ _) => tc_TT\n  | Econst_int _ (Tint IBool _ _) => tc_FF (invalid_expression e)\n  | Econst_int _ (Tlong _ _) => tc_FF (invalid_expression e)\n  | Econst_int _ (Tfloat _ _) => tc_FF (invalid_expression e)\n  | Econst_int _ (Tpointer _ _) => tc_FF (invalid_expression e)\n  | Econst_int _ (Tarray _ _ _) => tc_FF (invalid_expression e)\n  | Econst_int _ (Tfunction _ _ _) => tc_FF (invalid_expression e)\n  | Econst_int _ (Tstruct _ _) => tc_FF (invalid_expression e)\n  | Econst_int _ (Tunion _ _) => tc_FF (invalid_expression e)\n  | Econst_float _ Tvoid => tc_FF (invalid_expression e)\n  | Econst_float _ (Tint _ _ _) => tc_FF (invalid_expression e)\n  | Econst_float _ (Tlong _ _) => tc_FF (invalid_expression e)\n  | Econst_float _ (Tfloat F32 _) => tc_FF (invalid_expression e)\n  | Econst_float _ (Tfloat F64 _) => tc_TT\n  | Econst_float _ (Tpointer _ _) => tc_FF (invalid_expression e)\n  | Econst_float _ (Tarray _ _ _) => tc_FF (invalid_expression e)\n  | Econst_float _ (Tfunction _ _ _) => tc_FF (invalid_expression e)\n  | Econst_float _ (Tstruct _ _) => tc_FF (invalid_expression e)\n  | Econst_float _ (Tunion _ _) => tc_FF (invalid_expression e)\n  | Econst_single _ Tvoid => tc_FF (invalid_expression e)\n  | Econst_single _ (Tint _ _ _) => tc_FF (invalid_expression e)\n  | Econst_single _ (Tlong _ _) => tc_FF (invalid_expression e)\n  | Econst_single _ (Tfloat F32 _) => tc_TT\n  | Econst_single _ (Tfloat F64 _) => tc_FF (invalid_expression e)\n  | Econst_single _ (Tpointer _ _) => tc_FF (invalid_expression e)\n  | Econst_single _ (Tarray _ _ _) => tc_FF (invalid_expression e)\n  | Econst_single _ (Tfunction _ _ _) => tc_FF (invalid_expression e)\n  | Econst_single _ (Tstruct _ _) => tc_FF (invalid_expression e)\n  | Econst_single _ (Tunion _ _) => tc_FF (invalid_expression e)\n  | Econst_long _ _ => tc_FF (invalid_expression e)\n  | Evar id ty =>\n      match access_mode ty with\n      | By_value _ => tc_FF (deref_byvalue ty)\n      | By_reference =>\n          match get_var_type Delta id with\n          | Some ty' =>\n              tc_bool (eqb_type ty ty') (mismatch_context_type ty ty')\n          | None => tc_FF (var_not_in_tycontext Delta id)\n          end\n      | By_copy => tc_FF (deref_byvalue ty)\n      | By_nothing => tc_FF (deref_byvalue ty)\n      end\n  | Etempvar id ty =>\n      match (temp_types Delta) ! id with\n      | Some ty' =>\n          if\n           (is_neutral_cast (fst ty') ty || same_base_type (fst ty') ty)%bool\n          then if snd ty' then tc_TT else tc_initialized id ty\n          else tc_FF (mismatch_context_type ty (fst ty'))\n      | None => tc_FF (var_not_in_tycontext Delta id)\n      end\n  | Ederef a ty =>\n      match access_mode ty with\n      | By_value _ => tc_FF (deref_byvalue ty)\n      | By_reference =>\n          tc_andp\n            (tc_andp (typecheck_expr CS Delta a)\n               (tc_bool (is_pointer_type (typeof a)) (op_result_type e)))\n            (tc_isptr a)\n      | By_copy => tc_FF (deref_byvalue ty)\n      | By_nothing => tc_FF (deref_byvalue ty)\n      end\n  | Eaddrof a ty =>\n      tc_andp (typecheck_lvalue CS Delta a)\n        (tc_bool (is_pointer_type ty) (op_result_type e))\n  | Eunop op a ty => tc_andp (isUnOpResultType op a ty) (tcr a)\n  | Ebinop op a1 a2 ty =>\n      tc_andp (tc_andp (isBinOpResultType op a1 a2 ty) (tcr a1)) (tcr a2)\n  | Ecast a ty => tc_andp (tcr a) (isCastResultType (typeof a) ty a)\n  | Efield a i ty =>\n      match access_mode ty with\n      | By_value _ => tc_FF (deref_byvalue ty)\n      | By_reference =>\n          tc_andp (typecheck_lvalue CS Delta a)\n            match typeof a with\n            | Tvoid => tc_FF (invalid_field_access e)\n            | Tint _ _ _ => tc_FF (invalid_field_access e)\n            | Tlong _ _ => tc_FF (invalid_field_access e)\n            | Tfloat _ _ => tc_FF (invalid_field_access e)\n            | Tpointer _ _ => tc_FF (invalid_field_access e)\n            | Tarray _ _ _ => tc_FF (invalid_field_access e)\n            | Tfunction _ _ _ => tc_FF (invalid_field_access e)\n            | Tstruct id _ =>\n                match cenv_cs ! id with\n                | Some co =>\n                    match Ctypes.field_offset cenv_cs i (co_members co) with\n                    | Errors.OK _ => tc_TT\n                    | Errors.Error _ => tc_FF (invalid_struct_field i id)\n                    end\n                | None => tc_FF (invalid_composite_name id)\n                end\n            | Tunion id _ =>\n                match cenv_cs ! id with\n                | Some _ => tc_TT\n                | None => tc_FF (invalid_composite_name id)\n                end\n            end\n      | By_copy => tc_FF (deref_byvalue ty)\n      | By_nothing => tc_FF (deref_byvalue ty)\n      end\n  | Esizeof ty t =>\n      tc_andp (tc_bool (complete_type cenv_cs ty) (invalid_expression e))\n        (tc_bool (eqb_type t (Tint I32 Unsigned noattr))\n           (invalid_expression e))\n  | Ealignof ty t =>\n      tc_andp (tc_bool (complete_type cenv_cs ty) (invalid_expression e))\n        (tc_bool (eqb_type t (Tint I32 Unsigned noattr))\n           (invalid_expression e))\n  end\nwith\ntypecheck_lvalue (CS : compspecs) (Delta : tycontext) (e : expr) {struct e} :\n  tc_assert :=\n  match e with\n  | Econst_int _ _ => tc_FF (invalid_lvalue e)\n  | Econst_float _ _ => tc_FF (invalid_lvalue e)\n  | Econst_single _ _ => tc_FF (invalid_lvalue e)\n  | Econst_long _ _ => tc_FF (invalid_lvalue e)\n  | Evar id ty =>\n      match get_var_type Delta id with\n      | Some ty' => tc_bool (eqb_type ty ty') (mismatch_context_type ty ty')\n      | None => tc_FF (var_not_in_tycontext Delta id)\n      end\n  | Etempvar _ _ => tc_FF (invalid_lvalue e)\n  | Ederef a _ =>\n      tc_andp\n        (tc_andp (typecheck_expr CS Delta a)\n           (tc_bool (is_pointer_type (typeof a)) (op_result_type e)))\n        (tc_isptr a)\n  | Eaddrof _ _ => tc_FF (invalid_lvalue e)\n  | Eunop _ _ _ => tc_FF (invalid_lvalue e)\n  | Ebinop _ _ _ _ => tc_FF (invalid_lvalue e)\n  | Ecast _ _ => tc_FF (invalid_lvalue e)\n  | Efield a i _ =>\n      tc_andp (typecheck_lvalue CS Delta a)\n        match typeof a with\n        | Tvoid => tc_FF (invalid_field_access e)\n        | Tint _ _ _ => tc_FF (invalid_field_access e)\n        | Tlong _ _ => tc_FF (invalid_field_access e)\n        | Tfloat _ _ => tc_FF (invalid_field_access e)\n        | Tpointer _ _ => tc_FF (invalid_field_access e)\n        | Tarray _ _ _ => tc_FF (invalid_field_access e)\n        | Tfunction _ _ _ => tc_FF (invalid_field_access e)\n        | Tstruct id _ =>\n            match cenv_cs ! id with\n            | Some co =>\n                match Ctypes.field_offset cenv_cs i (co_members co) with\n                | Errors.OK _ => tc_TT\n                | Errors.Error _ => tc_FF (invalid_struct_field i id)\n                end\n            | None => tc_FF (invalid_composite_name id)\n            end\n        | Tunion id _ =>\n            match cenv_cs ! id with\n            | Some _ => tc_TT\n            | None => tc_FF (invalid_composite_name id)\n            end\n        end\n  | Esizeof _ _ => tc_FF (invalid_lvalue e)\n  | Ealignof _ _ => tc_FF (invalid_lvalue e)\n  end.\n\nset (e1:=(Ederef\n           (Ebinop Oadd (Etempvar _x (tptr tuchar))\n              (Ebinop Osub (Econst_int (Int.repr 7) tint) \n                 (Etempvar _i tint) tint) (tptr tuchar)) tuchar)).\nset (e2:=(Ecast (Etempvar _u tulong) tuchar)).\nassert (XX: typeof e1 = tuchar) by reflexivity.\nset (TC:=tc_expr Delta (Ecast e2 tuchar)). cbv in TC. simpl in TC.\nEval compute in (tc_expr Delta (Ecast e2 tuchar)).\n  Time forward. apply andp_right. apply andp_right. solve [entailer!]. entailer. \n        admit. (*!! typecheck_error (invalid_cast_result tuchar tuchar)*)\n        solve [entailer!]. \n  Time forward. entailer. admit. (*another tc_error*)  \n  rewrite Z.add_comm, Z2Nat.inj_add; try omega.\n  Time entailer!. (*1.5*)\n  unfold upd_Znth. clear H.\n  autorewrite with sublist.\n  replace (8 - (1 + i)) with (7-i) by omega. \n  replace (7 - i + 1) with (8-i) by omega.\n  replace (i+(8-i)) with 8 by omega.\n  rewrite field_at_data_at. simpl. unfold field_address. simpl.\n  if_tac. 2: solve [contradiction].\n  rewrite isptr_offset_val_zero; [| trivial]. clear H.\n  apply data_at_ext. f_equal.\n  rewrite <- (sublist_rejoin (7-i) (7-i+1) 8). 2: omega. 2: unfold Zlength; simpl; omega.\n  rewrite pure_lemmas.sublist_singleton with (d:=Vundef); simpl.\n  2: unfold Zlength; simpl; omega.\n  replace (7 - i + 1) with (8-i) by omega. f_equal.\n  rewrite iter64; try rewrite Z2Nat.id; try omega. unfold iter64Shr8', Int64.shru. \n  rewrite Int64.mul_signed.\n  rewrite 2 Int64.signed_repr; try rewrite Z2Nat.id; try unfold Int64.min_signed, Int64.max_signed; simpl; try omega.\n  rewrite (Int64.unsigned_repr (8 * i)).\n  2: unfold Int64.max_unsigned; simpl; omega.\n  specialize (Int64.unsigned_range u); specialize (Z.pow_pos_nonneg 2 (8*i)); intros NN U.\n  rewrite Int64.unsigned_repr.\n  Focus 2. rewrite Z.shiftr_div_pow2 by omega.\n           split. apply Z_div_pos; omega. \n           assert (Int64.unsigned u / 2 ^ (8 * i) < Int64.modulus).\n           2: solve [unfold Int64.max_unsigned; omega].\n           apply Zdiv_lt_upper_bound. omega.\n           assert (Int64.modulus <= Int64.modulus * 2 ^ (8 * i)). 2: omega.\n           apply Z.le_mul_diag_r; omega.\n  assert (ADD16: Int64.add (Int64.repr 8) (Int64.repr 8)\n         = Int64.repr 16) by reflexivity.\n  assert (ADD24: Int64.add (Int64.repr 8) (Int64.add (Int64.repr 8) (Int64.repr 8))\n         = Int64.repr 24) by reflexivity.\n  assert (ADD32: Int64.add (Int64.repr 8) (Int64.add (Int64.repr 8) (Int64.add (Int64.repr 8) (Int64.repr 8)))\n         = Int64.repr 32) by reflexivity.\n  assert (ADD40: Int64.add (Int64.repr 8)\n                       (Int64.add (Int64.repr 8) (Int64.add (Int64.repr 8) (Int64.add (Int64.repr 8) (Int64.repr 8))))\n         = Int64.repr 40) by reflexivity.\n  assert (ADD48: Int64.add (Int64.repr 8)\n                 (Int64.add (Int64.repr 8)\n                    (Int64.add (Int64.repr 8)\n                       (Int64.add (Int64.repr 8) (Int64.add (Int64.repr 8) (Int64.repr 8)))))\n          = Int64.repr 48) by reflexivity.\n  assert (ADD56: Int64.add (Int64.repr 8)\n                 (Int64.add (Int64.repr 8)\n                    (Int64.add (Int64.repr 8)\n                       (Int64.add (Int64.repr 8) (Int64.add (Int64.repr 8) (Int64.add (Int64.repr 8) (Int64.repr 8))))))\n         = Int64.repr 56) by reflexivity.\n  assert (UBND: forall n m, Pos.add m n=64%positive -> 0 <= Int64.unsigned u / Z.pow_pos 2 n < Z.pow_pos 2 m).\n  { intros. \n    destruct (Int64.unsigned_range u).\n    split. apply Z_div_pos; trivial. specialize (Fcore_Zaux.Zpower_pos_gt_0 2 n); omega.\n    apply Zdiv_lt_upper_bound; trivial. specialize (Fcore_Zaux.Zpower_pos_gt_0 2 n); omega.\n    rewrite <- Zpower_pos_is_exp, H.\n    change Int64.modulus with (Z.pow_pos 2 64) in H1; trivial. }(*\n  assert (B1: 0 <= Int64.unsigned u / Z.pow_pos 2 56 <= Byte.max_unsigned).\n  { destruct (UBND 56 8)%positive. reflexivity.\n    replace Byte.max_unsigned with (Z.pow_pos 2 8 -1). omega. reflexivity. }*) \n  assert (UNS_B_I64: Byte.max_unsigned <= Int64.max_unsigned) by (cbv; congruence). \n  assert (UNS_B_I: Byte.max_unsigned <= Int.max_unsigned) by (cbv; congruence).\n  destruct (zeq i 0).\n  { subst i; simpl in *. unfold Znth; simpl.\n    unfold bigendian64_invert in HeqU; inv HeqU.\n    rewrite Z.shiftr_0_r. unfold \n  destruct (zeq i 7).\n  { subst; simpl in *. unfold Znth; simpl.\n    (*specialize (UBND 56 8)%positive. rewrite Z.pow_pos_fold in UBND.*)\n    rewrite ! shru_shru, ADD56.\n    + rewrite Int64.shru_div_two_p, (Int64.unsigned_repr 56), two_p_correct.\n      2: unfold Int64.max_unsigned; simpl; omega.\n      rewrite Int64.unsigned_repr.\n      * rewrite zero_ext_inrange. f_equal; f_equal.\n        - unfold bigendian64_invert in HeqU; inv HeqU.\n          rewrite Byte.unsigned_repr. reflexivity. change Byte.max_unsigned with (Z.pow_pos 2 8 -1).\n          specialize (UBND 56 8 (eq_refl _))%positive; omega.\n        - rewrite Int.unsigned_repr, two_p_equiv. specialize (UBND 56 8 (eq_refl _))%positive.\n          rewrite ! Z.pow_pos_fold in UBND. omega.\n          specialize (UBND 56 8 (eq_refl _))%positive.\n          rewrite ! Z.pow_pos_fold in UBND.\n          assert (2^8 < Int.max_unsigned) by (cbv; trivial). omega.\n       * specialize (UBND 56 8 (eq_refl _))%positive.\n         rewrite ! Z.pow_pos_fold in UBND.\n         assert (2^8 < Int64.max_unsigned) by (cbv; trivial). omega.\n    + rewrite ADD48. rewrite 2 Int64.unsigned_repr; unfold Int64.max_unsigned; simpl; omega.\n    + rewrite ADD40. rewrite 2 Int64.unsigned_repr; unfold Int64.max_unsigned; simpl; omega.\n    + rewrite ADD32. rewrite 2 Int64.unsigned_repr; unfold Int64.max_unsigned; simpl; omega.\n    + rewrite ADD24. rewrite 2 Int64.unsigned_repr; unfold Int64.max_unsigned; simpl; omega.\n    + rewrite ADD16. rewrite 2 Int64.unsigned_repr; unfold Int64.max_unsigned; simpl; omega.\n    + rewrite ! Int64.unsigned_repr; unfold Int64.max_unsigned; simpl; omega. }\n  destruct (zeq i 0).\n  { subst; simpl in *. unfold Znth; simpl. f_equal.\n    unfold bigendian64_invert in HeqU; inv HeqU. simpl.\n        rewrite Byte.unsigned_repr.\n            rewrite (Fcore_Zaux.Zmod_mod_mult _ (2^8) (2^8)). 2: cbv; trivial. 2: cbv; intros; discriminate.\n            rewrite (Fcore_Zaux.Zmod_mod_mult _ (2^16) (2^8)). 2: cbv; trivial. 2: cbv; intros; discriminate.\n            rewrite (Fcore_Zaux.Zmod_mod_mult _ (2^24) (2^8)). 2: cbv; trivial. 2: cbv; intros; discriminate.\n            rewrite (Fcore_Zaux.Zmod_mod_mult _ (2^32) (2^8)). 2: cbv; trivial. 2: cbv; intros; discriminate.\n            rewrite (Fcore_Zaux.Zmod_mod_mult _ (2^40) (2^8)). 2: cbv; trivial. 2: cbv; intros; discriminate.\n            rewrite (Fcore_Zaux.Zmod_mod_mult _ (2^48) (2^8)). 2: cbv; trivial. 2: cbv; intros; discriminate.\n           unfold Int.zero_ext. apply Int.eqm_samerepr. apply Int.eqm_same_bits. change Int.zwordsize with 32; intros.\n           rewrite Int.Zzero_ext_spec. destruct (zlt i 8); subst; simpl. \n           + destruct (zeq i 0); subst; simpl. remember u as uu. destruct uu; simpl.\n             rewrite Int.unsigned_repr. unfold Z.odd. unfold Int64.unsigned, Int64.intval. simpl. \n              remember (Int.unsigned (Int.repr (Int64.unsigned u))). destruct z.\n               Int.eqm. apply Int.testbit \nspecialize (Int.zero_ext_mod 8).\n            Check Int64.zero_ext_mod. Require Import compcert.lib.Integers.\n  intros. specialize (Int.equal_same_bits (Int.unsigned (Int.zero_ext 8 (Int.repr (Int64.unsigned u)))) (Int.unsigned (Int.repr (Int64.unsigned u mod 2 ^ 8)))). intros.\n  unfold Int.zero_ext in *.\n  \n  rewrite Ztestbit_mod_two_p; auto.\n  fold (testbit (zero_ext n x) i).\n  destruct (zlt i zwordsize).\n  rewrite bits_zero_ext; auto.\n  rewrite bits_above. rewrite zlt_false; auto. omega. omega.\n  omega.\nQed.\n\n\n              rewrite Int.repr_unsigned; trivial.\n              rewrite ZW; omega.\n          assert (0 <= ((Int.unsigned u mod Z.pow_pos 2 24) mod Z.pow_pos 2 16) mod Z.pow_pos 2 8 < Byte.modulus).\n            apply Z_mod_lt. cbv; trivial. \n            unfold Byte.max_unsigned. omega. }\n  destruct (zeq i 6).\n  { subst; simpl in *. unfold Znth; simpl.\n    (*assert ((56 <= 56)%positive) by apply Pos.le_refl.\n    specialize (B1 _ H); clear H. rewrite Z.pow_pos_fold in B1.*)\n    rewrite ! shru_shru, ADD48.\n    + rewrite Int64.shru_div_two_p, (Int64.unsigned_repr 48), two_p_correct.\n      2: unfold Int64.max_unsigned; simpl; omega.\n      assert (QQ:= (UBND 48 16 (eq_refl _))%positive).\n      rewrite ! Z.pow_pos_fold in QQ.\n      rewrite Int64.unsigned_repr.\n      Focus 2. assert (2 ^ 16 < Int64.max_unsigned) by (cbv; trivial). omega. f_equal; f_equal.\n      unfold bigendian64_invert in HeqU; inv HeqU. simpl.\n      destruct (Int64.unsigned_range u).\n      destruct (zlt (Int64.unsigned u) (Z.pow_pos 2 56)).\n      - rewrite Zmod_small by omega. rewrite ! Z.pow_pos_fold.\n        assert (0<= Int64.unsigned u / 2 ^ 48 < 2^8).\n        { split; try omega. apply Zdiv_lt_upper_bound; trivial. }\n        (*rewrite Int.unsigned_repr. 2: change Byte.max_unsigned with (2^8-1) in UNS_B_I; omega.*)\n        rewrite Byte.unsigned_repr. 2: change Byte.max_unsigned with (2^8-1); omega.\n        rewrite zero_ext_inrange; trivial.\n        rewrite Int.unsigned_repr. 2: change Byte.max_unsigned with (2^8-1) in UNS_B_I; omega.\n        change (two_p 8) with (2^8); omega.\n      - specialize (Fcore_Zaux.Zdiv_mod_mult (Int64.unsigned u) (Z.pow_pos 2 48) (Z.pow_pos 2 8)); intros.\n        change ((Z.pow_pos 2 48 * Z.pow_pos 2 8)%Z) with (Z.pow_pos 2 56) in H1.\n        rewrite H1. rewrite Byte.unsigned_repr. Focus 2. destruct (Z_mod_lt (Int64.unsigned u / Z.pow_pos 2 48) (Z.pow_pos 2 8)). cbv; trivial.\n              change Byte.max_unsigned with (Z.pow_pos 2 8 -1). omega.\n        unfold Int.zero_ext.\n clear - H1; rewrite int_max_unsigned_eq; split; try omega. specialize (Fcore_Zaux.Zpower_pos_gt_0 2 n); omega.\n    rewrite <- Zpower_pos_is_exp, H.\n    change Int64.modulus with (Z.pow_pos 2 64) in H1; trivial.\n        \n      rewrite (Zdiv_small (Int64.unsigned u mod Z.pow_pos 2 56)).\n      Focus 2. specialize (Zmod_unique (Int64.unsigned u) (Z.pow_pos 2 56)); intros.\n      rewrite Int.unsigned_repr.\n      Focus 2. assert (2 ^ 16 < Int64.max_unsigned) by (cbv; trivial). omega.\n      unfold Int.zero_ext. f_equal. f_equal.\n      apply Byte.equal_same_bits; intros. rewrite Int.Zzero_ext_spec by omega.\n      unfold bigendian64_invert in HeqU; inv HeqU. simpl.\nspecialize (Zmod_recombine (Int64.unsigned u) (Z.pow_pos 2 8) (Z.pow_pos 2 48)). intros.\nreplace (Z.pow_pos 2 8 * Z.pow_pos 2 48)%Z with (Z.pow_pos 2 56) in H0.\n      rewrite H0.\n      destruct (zlt i 8).\n      rewrite <- (Byte.testbit_repr (Byte.unsigned b2)), Byte.repr_unsigned. unfold Byte.testbit.\n      rewrite if_true. by omega.\n      rewrite Int64.unsigned_repr.\n      unfold Int.zero_ext. rewrite Int.unsigned_repr.\n \n unfold Int.zero_ext. f_equal. f_equal.\n      rewrite Int64.unsigned_repr by omega.\n      rewrite zero_ext_inrange. f_equal; f_equal.\n      - unfold bigendian64_invert in HeqU; inv HeqU.\n        rewrite Byte.unsigned_repr. reflexivity. rewrite Z.pow_pos_fold. omega.\n      - rewrite Int.unsigned_repr. apply B1. omega.\n    + rewrite ADD48. rewrite 2 Int64.unsigned_repr; unfold Int64.max_unsigned; simpl; omega.\n    + rewrite ADD40. rewrite 2 Int64.unsigned_repr; unfold Int64.max_unsigned; simpl; omega.\n    + rewrite ADD32. rewrite 2 Int64.unsigned_repr; unfold Int64.max_unsigned; simpl; omega.\n    + rewrite ADD24. rewrite 2 Int64.unsigned_repr; unfold Int64.max_unsigned; simpl; omega.\n    + rewrite ADD16. rewrite 2 Int64.unsigned_repr; unfold Int64.max_unsigned; simpl; omega.\n    + rewrite ! Int64.unsigned_repr; unfold Int64.max_unsigned; simpl; omega. }\n\n    + rewrite ! Int64.add_unsigned. rewrite ! Int64.unsigned_repr; simpl; unfold Int64.max_unsigned; simpl; try omega.\n    + } \n    rewrite two_p_correct. rewrite Z.pow_pos_fold in B1. omega.\n    unfold Int64.max_unsigned; simpl; omega.\n    rewrite Int64.shru_div_two_p.  UNSB_I64.  <- two_power_nat_two_p. omega. apply B1; apply  Pos.le_refl. cbv. omega. admit.  admit.  admit.  admit.  admit.\n    admit.  admit.  admit.  admit.  admit. }\n  destruct (zeq i 6).\n  { subst; simpl in *. unfold Znth; simpl.\n    rewrite ! shru_shru. \n    replace (Int64.add (Int64.repr 8)\n                 (Int64.add (Int64.repr 8)\n                    (Int64.add (Int64.repr 8)\n                       (Int64.add (Int64.repr 8) (Int64.add (Int64.repr 8) (Int64.repr 8))))))\n    with (Int64.repr 48) by reflexivity.\n    rewrite zero_ext_inrange. f_equal; f_equal.\n    unfold bigendian64_invert in HeqU; inv HeqU.\n    rewrite Int64.shru_div_two_p.\n    rewrite (Int64.unsigned_repr 48).\n    rewrite Int64.unsigned_repr.\n    rewrite Byte.unsigned_repr.x\n    specialize (Fcore_Zaux.Zdiv_mod_mult (Int64.unsigned u) (Z.pow_pos 2 8) (Z.pow_pos 2 48) ). intros.\n    replace (Z.pow_pos 2 8 * Z.pow_pos 2 48)%Z with (Z.pow_pos 2 56) in H by reflexivity.\n    rewrite H.\n    specialize (Fcore_Zaux.Zdiv_mod_mult). (Int64.unsigned u) (Z.pow_pos 2 40) (Z.pow_pos 2 8)). intros.\n    replace (Z.pow_pos 2 40 * Z.pow_pos 2 8)%Z with (Z.pow_pos 2 48) in H0 by reflexivity.\n\n intros.\n    replace (Z.pow_pos 2 48 * Z.pow_pos 2 8)%Z with (Z.pow_pos 2 56) in H by reflexivity.\n    rewrite H.  reflexivity. admit.  admit.  admit.  admit.  admit.\n    admit.  admit.  admit.  admit.  admit. }\n      \n    unfold Int64.shru.  simpl. ! Int64.add_unsigned. (Int64.unsigned_repr 8).\n    \n\n rewrite if_false by omega.\n\n  unfold Znth; simpl. \n  rewrite if_false by omega. destruct (Int64.unsigned_range_2 u).\n  unfold bigendian64_invert in HeqU. inv HeqU. \n  assert (BMU: Byte.max_unsigned = 255) by reflexivity.\n  assert (I64MU: Int64.max_unsigned = Z.pow 2 64 -1) by reflexivity.\n  rewrite iter64. 2: rewrite Z2Nat.id; omega. \n  unfold iter64Shr8'. rewrite Z2Nat.id; try omega. \n  rewrite Int64.mul_signed.\n  rewrite 2 Int64.signed_repr; try (unfold Int64.min_signed, Int64.max_signed; simpl; omega).\n  rewrite Int64.shru_div_two_p, (Int64.unsigned_repr (8 * i)). 2: unfold Int64.max_unsigned; simpl; omega.\n  assert (GT:= two_p_gt_ZERO (8*i)).\n  assert (BND1: 0 <= Int64.unsigned u / Z.pow_pos 2 56 < Byte.modulus).\n  { split. apply Z_div_pos; trivial. cbv; trivial.\n           apply Z.div_lt_upper_bound. cbv; trivial. simpl in *. omega. } \n(*  assert (BND1: 0 <= Int64.unsigned u / Z.pow_pos 2 56 < Byte.max_unsigned).\n  { split. apply Z_div_pos; trivial. cbv; trivial.\n           assert (Int64.unsigned u / Z.pow_pos 2 56 < Byte.modulus). 2: unfold Byte.max_unsigned; omega.\n           apply Z.div_lt_upper_bound. cbv; trivial. simpl in *. omega. }*)\n  (*assert (BND1: 0 <= Int64.unsigned u / Z.pow_pos 2 56 < Byte.modulus).\n  { split. apply Z_div_pos; trivial. cbv; trivial.\n           apply Z.div_lt_upper_bound. cbv; trivial. simpl in *. omega. }*)\n  rewrite unsigned_repr'; trivial.\n(*  rewrite Int64.unsigned_repr.\n  Focus 2. split. apply Z_div_pos; trivial. omega. \n           apply Z.div_le_upper_bound. omega. \n           eapply Z.le_trans; eauto. \n           specialize (Zmult_le_compat_r 1 (two_p (8 * i)) Int64.max_unsigned). simpl.\n           intros Q; apply Q; omega.*)\n  rewrite unsigned_repr'.\n  Focus 2. split.  apply Z_div_pos; trivial. cbv; trivial. apply Z_mod_lt. cbv; trivial. \n           apply Z.div_lt_upper_bound. cbv; trivial.\n           eapply Z.lt_le_trans. apply Z_mod_lt. cbv; trivial. cbv; congruence.\n  rewrite unsigned_repr'.\n  Focus 2. split.  apply Z_div_pos; trivial. cbv; trivial. apply Z_mod_lt. cbv; trivial. \n           apply Z.div_lt_upper_bound. cbv; trivial.\n           eapply Z.lt_le_trans. apply Z_mod_lt. cbv; trivial. cbv; congruence.\n  rewrite unsigned_repr'.\n  Focus 2. split.  apply Z_div_pos; trivial. cbv; trivial. apply Z_mod_lt. cbv; trivial. \n           apply Z.div_lt_upper_bound. cbv; trivial.\n           eapply Z.lt_le_trans. apply Z_mod_lt. cbv; trivial. cbv; congruence.\n  rewrite unsigned_repr'.\n  Focus 2. split.  apply Z_div_pos; trivial. cbv; trivial. apply Z_mod_lt. cbv; trivial. \n           apply Z.div_lt_upper_bound. cbv; trivial.\n           eapply Z.lt_le_trans. apply Z_mod_lt. cbv; trivial. cbv; congruence.\n  rewrite unsigned_repr'.\n  Focus 2. split.  apply Z_div_pos; trivial. cbv; trivial. apply Z_mod_lt. cbv; trivial. \n           apply Z.div_lt_upper_bound. cbv; trivial.\n           eapply Z.lt_le_trans. apply Z_mod_lt. cbv; trivial. cbv; congruence.\n  rewrite unsigned_repr'.\n  Focus 2. split.  apply Z_div_pos; trivial. cbv; trivial. apply Z_mod_lt. cbv; trivial. \n           apply Z.div_lt_upper_bound. cbv; trivial.\n           eapply Z.lt_le_trans. apply Z_mod_lt. cbv; trivial. cbv; congruence.\n  rewrite unsigned_repr'.\n  Focus 2. split.  apply Z_mod_lt. cbv; trivial. apply Z_mod_lt. cbv; trivial.\n  assert (BND: 0 <= Int64.unsigned u / Z.pow_pos 2 56 <= Byte.max_unsigned).\n  { unfold Byte.max_unsigned; omega. }\n  assert (IMU: Int.max_unsigned = 4294967295) by reflexivity.\n  destruct (zeq i 7).\n  { subst; simpl in *. rewrite two_power_pos_correct, zero_ext_inrange.\n    + rewrite Int64.unsigned_repr; trivial.\n      split. apply Z_div_pos; trivial. cbv; trivial. \n           apply Z.div_le_upper_bound. cbv; trivial. \n           eapply Z.le_trans; eauto.\n    + rewrite Int.unsigned_repr, Int64.unsigned_repr. apply BND. omega. \n      rewrite Int64.unsigned_repr. omega. omega. } \n  destruct (zeq i 6).\n  { subst; simpl in *. rewrite two_power_pos_correct, zero_ext_inrange.\n       specialize (Fcore_Zaux.Zdiv_mod_mult (Int64.unsigned u) (Z.pow_pos 2 48) (Z.pow_pos 2 8)).\n       rewrite <- Zpower_pos_is_exp. intros Q.\n       replace (Z.pow_pos 2 (48 + 8)) with (Z.pow_pos 2 56) in Q by reflexivity.\n       rewrite Q. rewrite Zmod_small; trivial. f_equal. f_equal.  simpl. reflexivity.\n    rewrite Int.unsigned_repr; simpl in *; omega. }\n\n omega.\n    replace Byte.modulus with (two_p 8) in BND1 unfold Byte.modulus in BND1. simpl in *. cbv. unfold Int.zero_ext. rewrite Int.unsigned_repr. \n           apply Z.div_lt_upper_bound. cbv; trivial.\n           eapply Z.lt_le_trans. apply Z_mod_lt. cbv; trivial. cbv; congruence.\n  . omega. cbv. \n           specialize (Zmult_le_compat_r 1 (two_p (8 * i)) Int64.max_unsigned). simpl.\n           intros Q; apply Q; omega.\n  rewrite zero_ext_inrange. \n  Focus 2. rewrite Int.unsigned_repr.\n           assert (Int64.unsigned u / two_p (8 * i) < two_p 8). 2: omega.\n           apply Z.div_lt_upper_bound. omega.\n           assert (Int64.max_unsigned < two_p (8 * i) * two_p 8). 2: omega.\n           rewrite 2 two_p_equiv, Z.pow_mul_r, I64MU; try omega.\n           specialize (Zpower_exp (2^8) i 1); rewrite Z.pow_1_r.\n           intros Q; rewrite <- Q. simpl. omega. simpl.\n              simpl in *. omega. split. apply Z_div_pos; trivial. cbv; trivial.\n           assert (Int64.unsigned u / Z.pow_pos 2 56 < Byte.modulus). 2: unfold Byte.max_unsigned; omega.\n           apply Z.div_lt_upper_bound. cbv; trivial. simpl in *. omega.\n \n  destruct (zeq i 7). { subst. simpl in *. rewrite zero_ext_inrange. rewrite Byte.unsigned_repr. reflexivity.\n  { split. apply Z_div_pos; trivial. cbv; trivial.\n           assert (Int64.unsigned u / Z.pow_pos 2 56 < Byte.modulus). 2: unfold Byte.max_unsigned; omega.\n           apply Z.div_lt_upper_bound. cbv; trivial. simpl. omega. } \n           eapply Z.le_trans; eauto. rewrite I64MU. simpl. clear. cbv. omega. \n           unfold omega.  simpl. omega.  Zdiv_interval_2.\n  destruct (zeq i 0); subst; simpl. rewrite Byte.unsigned_repr. admit.\n  + f_equal. rewrite iter64. 2: rewrite Z2Nat.id; omega.\n    unfold iter64Shr8'. rewrite Z2Nat.id; try omega.  \n    unfold Int64.mul. rewrite 2 Int64.unsigned_repr.\n    2: unfold Int64.max_unsigned; simpl; omega.\n    2: unfold Int64.max_unsigned; simpl; omega.\n    rewrite Int64.shru_div_two_p.\n    rewrite (Int64.unsigned_repr (8 * i)), two_p_equiv.\n    2: unfold Int64.max_unsigned; simpl; omega. \n    assert (X: 0 < 2 ^ (8 * i)) by (apply Z.pow_pos_nonneg; omega).\n    destruct (Int64.unsigned_range_2 u).\n    assert (T: 0 <= Int64.unsigned u / 2 ^ (8 * i) <= 255).\n    { split. apply Z_div_pos. omega. omega. \n       apply Zdiv_le_upper_bound; trivial. eapply Z.le_trans. apply H0.       \n       unfold Int64.max_unsigned. rewrite Int64.modulus_power. \n       replace (two_p Int64.zwordsize) with (2^64) by reflexivity.\n       assert (2 ^ 64 < 255 * 2 ^ (8 * i)). 2: omega.\n       specialize (Zmult_le_compat_l 1 (2 ^ (8 * i)) Int64.max_unsigned).\n       rewrite Z.mul_1_r. intros Y; apply Y. omega. unfold Int64.max_unsigned; simpl; omega. }   \n    \n    assert (Q: 0 <= Int64.unsigned u / 2 ^ (8 * i) <= Int64.max_unsigned).\n    { split. apply Z_div_pos. omega. omega. \n       apply Zdiv_le_upper_bound; trivial. eapply Z.le_trans. apply H0.\n       specialize (Zmult_le_compat_l 1 (2 ^ (8 * i)) Int64.max_unsigned).\n       rewrite Z.mul_1_r. intros Y; apply Y. omega. unfold Int64.max_unsigned; simpl; omega. }   \n    rewrite Int64.unsigned_repr; trivial.  \n    rewrite zero_ext_inrange. f_equal. admit.\n    rewrite Int.unsigned_repr. replace (two_p 8 - 1) with 255 by reflexivity.\n  replace (1 + (7 - i)) with (8-i) by omega. replace (i + (8 - i)) with 8 by omega.\n  destruct (zeq i 0).\n  { subst; unfold sublist;  simpl. unfold littleendian64_invert in HeqU.\n    inv HeqU. \n  rewrite <- app_comm_cons. (sublist_app1 _ 0 i). 2: omega. 2: rewrite Zlength_sublist. omega.\n  rewrite <- app_assoc.\n        assert (ZW: Int.zwordsize = 32) by reflexivity.\n        assert (EIGHT: Int.unsigned (Int.repr 8) = 8). apply Int.unsigned_repr. rewrite int_max_unsigned_eq; omega.\n        inv HeqU. clear - ZW EIGHT I. simpl.\n        destruct (zeq i 0); subst; simpl. f_equal. f_equal.\n        { rewrite Byte.unsigned_repr.              \n            rewrite (Fcore_Zaux.Zmod_mod_mult _ (2^8) (2^8)). 2: cbv; trivial. 2: cbv; intros; discriminate.\n            rewrite (Fcore_Zaux.Zmod_mod_mult _ (2^16) (2^8)). 2: cbv; trivial. 2: cbv; intros; discriminate.\n            rewrite <- (Int.zero_ext_mod 8).\n              rewrite Int.repr_unsigned; trivial.\n              rewrite ZW; omega.\n          assert (0 <= ((Int.unsigned u mod Z.pow_pos 2 24) mod Z.pow_pos 2 16) mod Z.pow_pos 2 8 < Byte.modulus).\n            apply Z_mod_lt. cbv; trivial. \n            unfold Byte.max_unsigned. omega. }\n        destruct (zeq i 1); subst; simpl. f_equal. f_equal. f_equal.\n        { rewrite Byte.unsigned_repr.  \n          Focus 2. assert (0 <= (Int.unsigned u mod Z.pow_pos 2 24) mod Z.pow_pos 2 16 / Z.pow_pos 2 8 < Byte.modulus).\n                   Focus 2. unfold Byte.max_unsigned. omega.\n                   split. apply Z_div_pos. cbv; trivial. apply Z_mod_lt. cbv; trivial.\n                   apply Zdiv_lt_upper_bound. cbv; trivial. apply Z_mod_lt. cbv; trivial.\n          apply Int.same_bits_eq. rewrite ZW; intros.\n          rewrite Int.bits_zero_ext, Int.testbit_repr; try apply H. \n          rewrite (Z.div_pow2_bits _ 8); try omega.\n          rewrite (Int.Ztestbit_mod_two_p 16); try omega.\n          rewrite (Int.Ztestbit_mod_two_p 24); try omega.\n          rewrite Int.bits_shru; try omega. rewrite EIGHT, ZW, Ztest_Inttest.\n          remember (zlt i 8). \n          destruct s. repeat rewrite zlt_true. trivial. omega. omega. omega.\n          rewrite zlt_false. trivial. omega. }\n        destruct (zeq i 2); subst; simpl. f_equal. f_equal. f_equal.\n          f_equal.\n        { rewrite Byte.unsigned_repr.  \n          Focus 2. assert (0 <= Int.unsigned u mod Z.pow_pos 2 24 / Z.pow_pos 2 16 < Byte.modulus).\n                   2: unfold Byte.max_unsigned; omega.\n                   split. apply Z_div_pos. cbv; trivial. apply Z_mod_lt. cbv; trivial.\n                   apply Zdiv_lt_upper_bound. cbv; trivial. apply Z_mod_lt. cbv; trivial.\n          apply Int.same_bits_eq. rewrite ZW; intros.\n          rewrite Int.bits_zero_ext, Int.testbit_repr; try apply H. \n          rewrite Int.bits_shru; try omega. rewrite EIGHT, ZW.\n          rewrite (Z.div_pow2_bits _ 16); try omega.\n          rewrite (Int.Ztestbit_mod_two_p 24); try omega.\n          rewrite Ztest_Inttest.\n          remember (zlt i 8). \n          destruct s. repeat rewrite zlt_true. rewrite Int.bits_shru, EIGHT, ZW.\n              rewrite zlt_true. rewrite <- Z.add_assoc. reflexivity. omega. omega. omega. omega.\n          rewrite zlt_false. trivial. omega. }\n        destruct (zeq i 3); subst; simpl. f_equal. f_equal. f_equal. f_equal.\n          f_equal.\n        { rewrite Byte.unsigned_repr.  \n          Focus 2. assert (0 <= Int.unsigned u / Z.pow_pos 2 24 < Byte.modulus).\n                   2: unfold Byte.max_unsigned; omega.\n                   split. apply Z_div_pos. cbv; trivial. apply Int.unsigned_range. \n                   apply Zdiv_lt_upper_bound. cbv; trivial. apply Int.unsigned_range. \n          apply Int.same_bits_eq. rewrite ZW; intros.\n          rewrite Int.bits_zero_ext, Int.testbit_repr; try apply H. \n          rewrite Int.bits_shru; try omega. rewrite EIGHT, ZW.\n          rewrite (Z.div_pow2_bits _ 24); try omega.\n          rewrite Ztest_Inttest.\n          remember (zlt i 8). \n          destruct s. rewrite zlt_true. rewrite Int.bits_shru, EIGHT, ZW.\n              rewrite zlt_true. rewrite Int.bits_shru, EIGHT, ZW. \n              rewrite zlt_true. repeat rewrite <- Z.add_assoc. reflexivity. omega. omega. omega. omega. omega.\n          rewrite Int.bits_above. trivial. omega. }\n        omega. }\n  Time forward. (*1.6*)\nTime Qed. (*4.9*) \n\n unfold data_at_, field_at_.\n  rewrite field_at_data_at. \n  rewrite field_address_offset by auto with field_compatible. simpl.\n  rewrite isptr_offset_val_zero. apply data_at_ext. unfold default_val. simpl. unfold tarray. simpl.   destruct tv. reflexivity. cancel. rewrite unfold field_address; simpl. normalize. cancel. }\n\nforward_for (EX z:_, \n  (PROP (0<= z <= 7 )\n   LOCAL (temp _i (Vint (Int.repr z)); temp _x x; \n          temp _u (Vlong u))\n   SEP (data_at Tsh (tarray tuchar 8) (Data z) x))). \n{ Exists 7. entailer!. admit. (*Data 7 = list_repeat 8 Vundef*) }\n\neapply semax_for with (A:=Z)(v:= fun a => Val.of_bool (negb (Int.lt (Int.repr a) (Int.repr 0)))).\n solve [ reflexivity].\n intros. solve [entailer!].\n intros. entailer!. \n{ intros i. simpl. normalize. rename H into I0. rename H0 into I7.\n  apply negb_true_iff in I0. (* apply lt_repr_false in I0. \n   2: red; unfold Int.min_signed, Int.max_signed; simpl. 2: split; try omega. Focus 2.\n   2: red; unfold Int.min_signed, Int.max_signed; simpl; omega.*)\n\n forward.\n  { apply andp_right. 2: solve [entailer].\n    apply andp_right. solve [entailer!].\n    entailer. admit. (*typecheck_error (invalid_cast_result tuchar tuchar)*) }\n\n  forward. entailer. simpl. admit. (*typecheck_error\n         (arg_type\n            (Ebinop Oshr (Etempvar _u tulong) (Econst_int (Int.repr 8) tint)\n               tulong))*)\n\n  \n  unfold arg_type.\n go_lower. entailer!. Search invalid_cast_result. unfold invalid_cast_result. typecheck_error. simpl.  simpl. destruct (zlt   \n{ apply extract_exists_pre. intros i. Intros. rename H into I.\n  \n cancel. Focus 2. eapply semax_for with (A:=Z).\n  reflexivity.\nLtac forward_for_simple_bound n Pre ::=\n  check_Delta;\n repeat match goal with |-\n      semax _ _ (Ssequence (Ssequence (Ssequence _ _) _) _) _ =>\n      apply -> seq_assoc; abbreviate_semax\n end. (*\n first [ \n    match type of n with\n      ?t => first [ unify t Z | elimtype (Type_of_bound_in_forward_for_should_be_Z_but_is t)]\n    end;\n    match type of Pre with\n      ?t => first [unify t (environ -> mpred); fail 1 | elimtype (Type_of_invariant_in_forward_for_should_be_environ_arrow_mpred_but_is t)]\n    end\n  | simple eapply semax_seq'; \n    [forward_for_simple_bound' n Pre \n    | cbv beta; simpl update_tycon; abbreviate_semax  ]\n  | eapply semax_post_flipped'; \n     [forward_for_simple_bound' n Pre \n     | ]\n  ].*)\n\nTime forward_for_simple_bound 8 (EX i:Z, \n  (PROP  ()\n   LOCAL (temp _x x; temp _u (Vlong (iter64Shr8 u (Z.to_nat i))))\n   SEP (data_at Tsh (tarray tuchar 8) \n              (sublist 0 i (map Vint (map Int.repr (map Byte.unsigned ([w0;w1;w2;w3;u0;u1;u2;u3])))) ++ \n               list_repeat (Z.to_nat(8-i)) Vundef)\n                x))).\n{ entailer!. }\n{ rename H into I.\n  Time assert_PROP (field_compatible (Tarray tuchar 4 noattr) [] x /\\ isptr x) \n       as FC_ptrX by solve [entailer!]. (*2.3*)\n  destruct FC_ptrX as [FC ptrX].\n  Time forward. (*3.2*)\n  Time forward. (*0.8*)  \n  rewrite Z.add_comm, Z2Nat.inj_add; try omega.\n  Time entailer!. (*1.5*)\n  unfold upd_Znth.\n  autorewrite with sublist. \n  rewrite field_at_data_at. simpl. unfold field_address. simpl.\n  if_tac. 2: solve [contradiction].\n  replace (4 - (1 + i)) with (4-i-1) by omega.\n  rewrite isptr_offset_val_zero; trivial. clear H.\n  apply data_at_ext. rewrite Zplus_comm.\n        assert (ZW: Int.zwordsize = 32) by reflexivity.\n        assert (EIGHT: Int.unsigned (Int.repr 8) = 8). apply Int.unsigned_repr. rewrite int_max_unsigned_eq; omega.\n        inv HeqU. clear - ZW EIGHT I.\n        destruct (zeq i 0); subst; simpl. f_equal. f_equal.\n        { rewrite Byte.unsigned_repr.              \n            rewrite (Fcore_Zaux.Zmod_mod_mult _ (2^8) (2^8)). 2: cbv; trivial. 2: cbv; intros; discriminate.\n            rewrite (Fcore_Zaux.Zmod_mod_mult _ (2^16) (2^8)). 2: cbv; trivial. 2: cbv; intros; discriminate.\n            rewrite <- (Int.zero_ext_mod 8).\n              rewrite Int.repr_unsigned; trivial.\n              rewrite ZW; omega.\n          assert (0 <= ((Int.unsigned u mod Z.pow_pos 2 24) mod Z.pow_pos 2 16) mod Z.pow_pos 2 8 < Byte.modulus).\n            apply Z_mod_lt. cbv; trivial. \n            unfold Byte.max_unsigned. omega. }\n        destruct (zeq i 1); subst; simpl. f_equal. f_equal. f_equal.\n        { rewrite Byte.unsigned_repr.  \n          Focus 2. assert (0 <= (Int.unsigned u mod Z.pow_pos 2 24) mod Z.pow_pos 2 16 / Z.pow_pos 2 8 < Byte.modulus).\n                   Focus 2. unfold Byte.max_unsigned. omega.\n                   split. apply Z_div_pos. cbv; trivial. apply Z_mod_lt. cbv; trivial.\n                   apply Zdiv_lt_upper_bound. cbv; trivial. apply Z_mod_lt. cbv; trivial.\n          apply Int.same_bits_eq. rewrite ZW; intros.\n          rewrite Int.bits_zero_ext, Int.testbit_repr; try apply H. \n          rewrite (Z.div_pow2_bits _ 8); try omega.\n          rewrite (Int.Ztestbit_mod_two_p 16); try omega.\n          rewrite (Int.Ztestbit_mod_two_p 24); try omega.\n          rewrite Int.bits_shru; try omega. rewrite EIGHT, ZW, Ztest_Inttest.\n          remember (zlt i 8). \n          destruct s. repeat rewrite zlt_true. trivial. omega. omega. omega.\n          rewrite zlt_false. trivial. omega. }\n        destruct (zeq i 2); subst; simpl. f_equal. f_equal. f_equal.\n          f_equal.\n        { rewrite Byte.unsigned_repr.  \n          Focus 2. assert (0 <= Int.unsigned u mod Z.pow_pos 2 24 / Z.pow_pos 2 16 < Byte.modulus).\n                   2: unfold Byte.max_unsigned; omega.\n                   split. apply Z_div_pos. cbv; trivial. apply Z_mod_lt. cbv; trivial.\n                   apply Zdiv_lt_upper_bound. cbv; trivial. apply Z_mod_lt. cbv; trivial.\n          apply Int.same_bits_eq. rewrite ZW; intros.\n          rewrite Int.bits_zero_ext, Int.testbit_repr; try apply H. \n          rewrite Int.bits_shru; try omega. rewrite EIGHT, ZW.\n          rewrite (Z.div_pow2_bits _ 16); try omega.\n          rewrite (Int.Ztestbit_mod_two_p 24); try omega.\n          rewrite Ztest_Inttest.\n          remember (zlt i 8). \n          destruct s. repeat rewrite zlt_true. rewrite Int.bits_shru, EIGHT, ZW.\n              rewrite zlt_true. rewrite <- Z.add_assoc. reflexivity. omega. omega. omega. omega.\n          rewrite zlt_false. trivial. omega. }\n        destruct (zeq i 3); subst; simpl. f_equal. f_equal. f_equal. f_equal.\n          f_equal.\n        { rewrite Byte.unsigned_repr.  \n          Focus 2. assert (0 <= Int.unsigned u / Z.pow_pos 2 24 < Byte.modulus).\n                   2: unfold Byte.max_unsigned; omega.\n                   split. apply Z_div_pos. cbv; trivial. apply Int.unsigned_range. \n                   apply Zdiv_lt_upper_bound. cbv; trivial. apply Int.unsigned_range. \n          apply Int.same_bits_eq. rewrite ZW; intros.\n          rewrite Int.bits_zero_ext, Int.testbit_repr; try apply H. \n          rewrite Int.bits_shru; try omega. rewrite EIGHT, ZW.\n          rewrite (Z.div_pow2_bits _ 24); try omega.\n          rewrite Ztest_Inttest.\n          remember (zlt i 8). \n          destruct s. rewrite zlt_true. rewrite Int.bits_shru, EIGHT, ZW.\n              rewrite zlt_true. rewrite Int.bits_shru, EIGHT, ZW. \n              rewrite zlt_true. repeat rewrite <- Z.add_assoc. reflexivity. omega. omega. omega. omega. omega.\n          rewrite Int.bits_above. trivial. omega. }\n        omega. }\n  Time forward. (*1.6*)\nTime Qed. (*4.9*) \n*)\n\n(*\nDefinition L32_specZ :=\n  DECLARE _L32\n   WITH x : int, c: int\n   PRE [ _x OF tuint, _c OF tint ]\n      PROP () (*c=Int.zero doesn't seem to satisfy spec???*)\n      LOCAL (temp _x (Vint x); temp _c (Vint Int.zero))\n      SEP ()\n  POST [ tuint ]\n     PROP (True)\n     LOCAL ()\n     SEP ().\n\nDefinition LDZFunSpecs : funspecs :=\n  L32_specZ::nil.\n\nLemma L32_specZ_ok: semax_body SalsaVarSpecs LDZFunSpecs\n       f_L32 L32_specZ.\nProof.\nstart_function.\nname x' _x.\nname c' _c.\nforward. entailer. apply prop_right.\nassert (W: Int.zwordsize = 32). reflexivity.\nassert (U: Int.unsigned Int.iwordsize=32). reflexivity.\n(*remember (Int.eq c' Int.zero) as z.\n  destruct z. apply binop_lemmas.int_eq_true in Heqz. subst. simpl. *)\nremember (Int.ltu (Int.repr 32) Int.iwordsize) as d. symmetry in Heqd.\ndestruct d; simpl.\nFocus 2. apply ltu_false_inv in Heqd. rewrite U in *. rewrite Int.unsigned_repr in Heqd. 2: rewrite int_max_unsigned_eq; omega.\nclear Heqd. split; trivial.\nremember (Int.ltu (Int.sub (Int.repr 32) c') Int.iwordsize) as z. symmetry in Heqz.\ndestruct z.\nFocus 2. apply ltu_false_inv in Heqz. rewrite U in *.\n         unfold Int.sub in Heqz.\n         rewrite (Int.unsigned_repr 32) in Heqz.\n           rewrite Int.unsigned_repr in Heqz. omega. rewrite int_max_unsigned_eq; omega.\n           rewrite int_max_unsigned_eq; omega.\nsimpl; split; trivial. split; trivial.\napply ltu_inv in Heqz. unfold Int.sub in *.\n  rewrite (Int.unsigned_repr 32) in *; try (rewrite int_max_unsigned_eq; omega).\n  rewrite Int.unsigned_repr in Heqz. 2: rewrite int_max_unsigned_eq; omega.\n  unfold Int.rol, Int.shl, Int.shru. rewrite or_repr.\n  assert (Int.unsigned c' mod Int.zwordsize = Int.unsigned c').\n    apply Zmod_small. rewrite W; omega.\n  rewrite H0, W. f_equal. f_equal. f_equal.\n  rewrite Int.unsigned_repr. 2: rewrite int_max_unsigned_eq; omega.\n  rewrite Int.and_mone. trivial.\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/tweetnacl20140427/verif_ld_st.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.26215625787836283}}
{"text": "(************************************************\n *          Row Subtyping - Inversion           *\n *                 Leo White                    *\n ************************************************)\n\nSet Implicit Arguments.\nRequire Import Arith.\nRequire Import LibLN Utilities Cofinite Disjoint Definitions\n        Opening FreeVars Environments Subst Wellformedness\n        Weakening Substitution Kinding Subtyping.\n\n(* ****************************************************** *)\n(** Unfolding recursive equations *)\n\nLemma type_equal_eqn_subst :\n  forall v E1 E2 Q1 Q2 Q3 T1 T2 K T1' T2' K',\n    type_equal v E1 E2 (Q1 ++ (T1, T2, K) :: Q2) Q3 T1' T2' K' ->\n    type_equal v E1 E2 (Q1 ++ Q2) Q3 T1 T2 K ->\n    type_environment_extension E1 E2 ->\n    type_equal v E1 E2 (Q1 ++ Q2) Q3 T1' T2' K'.\nProof.\n  introv Hte1 Hte2 He.\n  remember (Q1 ++ (T1, T2, K) :: Q2)%list as Q12.\n  generalize dependent Q1.\n  induction Hte1; introv HeqQ12 Hte2; subst;\n    auto using type_equal_weakening_eqn_rec_cons;\n    try solve\n      [constructor;\n       match goal with\n       | IH :\n           type_environment_extension (E1 & E2) empty ->\n           (forall Q,\n            ((?Tl, ?Tr, ?Klr)\n               :: ?Q1 ++ ?Q2 ++ (T1, T2, K) :: ?Q3)%list =\n            (Q ++ (T1, T2, K) :: ?Q3)%list ->\n            type_equal _ _ _ (Q ++ ?Q3) nil T1 T2 K ->\n            type_equal _ _ _ (Q ++ ?Q3) nil ?Ta ?Tb _),\n         Ht : type_equal _ _ _ (?Q2 ++ ?Q3) ?Q1 T1 T2 K\n         |- type_equal _ _ _\n              ((?Tl, ?Tr, ?Klr) :: (?Q1 ++ ?Q2 ++ ?Q3))%list nil\n              ?Ta ?Tb _ =>\n         rewrite List.app_comm_cons;\n         rewrite List.app_assoc;\n         apply IH;\n           try rewrite <- List.app_assoc;\n           try rewrite <- List.app_comm_cons; auto;\n         apply type_equal_weakening_eqn_cons;\n         apply type_equal_eqn_extend_nil;\n         apply type_equal_extend_empty; auto\n       | _ => auto\n       end].\n  - eauto.\n  - eauto.\n  - eapply in_qenv_middle_inv; try eassumption;\n      intros; subst; auto.    \n  - apply type_equal_transitive with T3;\n      auto using type_equal_weakening_eqn_rec_cons.\nQed.\n\nLemma type_equal_eqn_rec_subst :\n  forall v E1 E2 Q1 Q2 Q3 T1 T2 K T1' T2' K',\n    type_equal v E1 E2 Q1 (Q2 ++ (T1, T2, K) :: Q3) T1' T2' K' ->\n    type_equal v E1 E2 Q1 (Q2 ++ Q3) T1 T2 K ->\n    type_environment_extension E1 E2 ->\n    type_equal v E1 E2 Q1 (Q2 ++ Q3) T1' T2' K'.\nProof.\n  introv Hte1 Hte2 He.\n  remember (Q2 ++ (T1, T2, K) :: Q3)%list as Q23.\n  generalize dependent Q2.\n  induction Hte1; introv HeqQ2 Hte2; subst; auto;\n    try solve\n        [constructor;\n         match goal with\n         | IH : type_environment_extension E1 E2 ->\n                (forall Q : list (typ * typ * knd),\n                  ((?Tl, ?Tr, ?Klr)\n                     :: ?Q2 ++ (T1, T2, K) :: ?Q3)%list\n                  = (Q ++ (T1, T2, K) :: ?Q3)%list ->\n                  type_equal _ _ _ ?Q1 (Q ++ ?Q3) _ _ _ ->\n                  type_equal _ _ _ ?Q1 (Q ++ ?Q3) ?Ta ?Tb _)\n           |- type_equal _ _ _ ?Q1\n                ((?Tl, ?Tr, ?Klr) :: \n                  (?Q2 ++ ?Q3)%list) ?Ta ?Tb _ =>\n                 rewrite List.app_comm_cons;\n                 apply IH; auto;\n                 rewrite <- List.app_comm_cons;\n                 apply type_equal_weakening_eqn_rec_cons; auto\n         | _ =>\n           auto;\n           solve\n             [rewrite <- List.app_assoc;\n              rewrite List.app_comm_cons;\n              apply type_equal_eqn_subst\n                with (T1 := T1) (T2 := T2) (K := K);\n                [> rewrite List.app_comm_cons;\n                   rewrite List.app_assoc; auto\n                | apply type_equal_eqn_extend_nil;\n                  apply type_equal_weakening_eqn_rec_cons;\n                  apply type_equal_eqn_extend;\n                  apply type_equal_extend_empty; auto\n                | auto]]\n         end].\n  - eauto.\n  - eauto.\n  - apply type_equal_transitive with T3.\n    + rewrite List.app_comm_cons.\n      apply IHHte1_1; auto.\n      rewrite <- List.app_comm_cons.\n      apply type_equal_weakening_eqn_rec_cons; auto.\n    + rewrite List.app_comm_cons.\n      apply IHHte1_2; auto.\n      rewrite <- List.app_comm_cons.\n      apply type_equal_weakening_eqn_rec_cons; auto.\nQed.\n\nInductive type_equal_eqn_subs\n  : version -> tenv -> tenv -> qenv -> Prop :=\n| type_equal_eqn_subs_nil : forall v E1 E2,\n    type_equal_eqn_subs v E1 E2 nil\n| type_equal_eqn_subs_cons : forall v E1 E2 Q T1 T2 K,\n    type_equal_eqn_subs v E1 E2 Q ->\n    type_equal v E1 E2 nil nil T1 T2 K ->\n    type_equal_eqn_subs v E1 E2 ((T1, T2, K) :: Q).\n\nHint Constructors type_equal_eqn_subs.\n\nLemma type_equal_eqn_subst_subs :\n  forall v E1 E2 Q T1 T2 K,\n    type_equal v (E1 & E2) empty Q nil T1 T2 K ->\n    type_equal_eqn_subs v E1 E2 Q ->\n    type_environment_extension E1 E2 ->\n    type_equal v (E1 & E2) empty nil nil T1 T2 K.\nProof.\n  introv Hte Hes He.\n  induction Hes; auto.\n  assert (type_equal v E1 E2 nil nil T0 T3 K0)\n    as Hte2 by assumption.\n  apply type_equal_extend_empty in Hte2; auto.\n  apply type_equal_weakening_eqn_nils\n    with (Q1 := Q) (Q2 := nil) in Hte2.\n  rewrite <- List.app_nil_l\n    with (l := ((T0, T3, K0) :: Q)%list) in Hte.\n  apply type_equal_eqn_subst\n    with (T1 := T0) (T2 := T3) (K := K0) in Hte; auto.\nQed.  \n\nLemma type_equal_eqn_rec_subst_subs :\n  forall v E1 E2 Q T1 T2 K,\n    type_equal v E1 E2 nil Q T1 T2 K ->\n    type_equal_eqn_subs v E1 E2 Q ->\n    type_environment_extension E1 E2 ->\n    type_equal v E1 E2 nil nil T1 T2 K.\nProof.\n  introv Hte Hes He.\n  induction Hes; auto.\n  assert (type_equal v E1 E2 nil nil T0 T3 K0)\n    as Hte2 by assumption.\n  apply type_equal_weakening_eqn_nils\n    with (Q1 := nil) (Q2 := Q) in Hte2.\n  rewrite <- List.app_nil_l\n    with (l := ((T0, T3, K0) :: Q)%list) in Hte.\n  apply type_equal_eqn_rec_subst\n    with (T1 := T0) (T2 := T3) (K := K0) in Hte; auto.\nQed.\n\n(* ****************************************************** *)\n(** Useful lemmas *)\n\nLemma subtype_equal_bot : forall v E1 E2 T1 T2 K,\n    type_equal v E1 E2 nil nil T1 (typ_bot K) K ->\n    subtype v E1 E2 nil nil T2 T1 K ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    type_equal v E1 E2 nil nil T2 (typ_bot K) K.\nProof.\n  introv Hte Hs He1 He2.\n  pose subtype_bot as Hs2.\n  unfold subtype in *.\n  rewrite Hs.\n  rewrite Hte.\n  rewrite type_equal_meet_commutative by auto with kinding.\n  rewrite <- Hs2 by auto with kinding wellformed.\n  treflexivity.\nQed.\n\nLemma subtype_equal_top : forall v E1 E2 T1 T2 K,\n    type_equal v E1 E2 nil nil T1 (typ_top K) K ->\n    subtype v E1 E2 nil nil T1 T2 K ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    type_equal v E1 E2 nil nil T2 (typ_top K) K.\nProof.\n  introv Hte Hs He1 He2.\n  pose (@subtype_top v E1 E2 T2 K) as Hs2.\n  rewrite subtype_dual in Hs by auto.\n  rewrite subtype_dual in Hs2 by auto.\n  rewrite Hs.\n  rewrite Hte.\n  rewrite type_equal_join_commutative by auto with kinding.\n  rewrite <- Hs2 by auto with kinding wellformed.\n  treflexivity.\nQed.\n\nLemma subtype_join_bot_l : forall v E1 E2 T1 T2 T3 K,\n  subtype v E1 E2 nil nil T1 T3 K ->\n  type_equal v E1 E2 nil nil T2 (typ_bot K) K ->\n  valid_tenv v E1 ->\n  valid_tenv_extension v E1 E2 ->\n  subtype v E1 E2 nil nil (typ_join T1 T2) T3 K.\nProof.\n  introv Hs Hte He1 He2.\n  rewrite <- Hs.\n  rewrite Hte.\n  rewrite type_equal_join_identity by auto with kinding.\n  sreflexivity.\nQed.\n\nLemma subtype_meet_top_r : forall v E1 E2 T1 T2 T3 K,\n  subtype v E1 E2 nil nil T1 T2 K ->\n  type_equal v E1 E2 nil nil T3 (typ_top K) K ->\n  valid_tenv v E1 ->\n  valid_tenv_extension v E1 E2 ->\n  subtype v E1 E2 nil nil T1 (typ_meet T2 T3) K.\nProof.\n  introv Hs Hte He1 He2.\n  rewrite Hs.\n  rewrite Hte.\n  rewrite type_equal_meet_identity by auto with kinding.\n  sreflexivity.\nQed.\n\nLemma type_equal_eqn_subs_apply :\n  forall v E1 E2 E3 Q T1 T2 K T1' T2' K',\n    type_equal v (E1 & E2 & E3) empty\n      ((T1, T2, K) :: Q ++ nil)%list nil T1' T2' K' ->\n    type_equal v E1 (E2 & E3) nil Q T1 T2 K ->\n    type_equal_eqn_subs v E1 (E2 & E3) Q ->\n    type_environment (E1 & E2) ->\n    type_environment_extension (E1 & E2) E3 ->\n    type_equal v (E1 & E2 & E3) empty nil nil T1' T2' K'.\nProof.\n  introv Hte1 Hte2 Hes He1 He2.\n  rewrite List.app_nil_r in Hte1.\n  assert (type_environment_extension E1 (E2 & E3))\n    by auto using type_environment_extension_extend,\n         type_environment_extend_inv.\n  apply type_equal_extend_empty in Hte2; auto.\n  rewrite concat_assoc in Hte2.\n  apply type_equal_eqn_extend_nil in Hte2.\n  rewrite List.app_nil_r in Hte2.\n  rewrite <- List.app_nil_l\n    with (l := ((T1, T2, K) :: Q)%list) in Hte1.\n  apply type_equal_eqn_subst\n    with (T1 := T1) (T2 := T2) (K := K) in Hte1; auto.\n  rewrite <- concat_assoc.\n  apply type_equal_eqn_subst_subs with (Q := Q);\n    try rewrite concat_assoc; auto.  \nQed.\n\nLemma type_equal_eqn_subs_push : forall v E1 E2 E3 Q T1 T2 K,\n    type_equal_eqn_subs v E1 (E2 & E3) Q ->\n    type_equal v E1 (E2 & E3) nil Q T1 T2 K ->\n    type_environment (E1 & E2) ->\n    type_environment_extension (E1 & E2) E3 ->\n    type_equal_eqn_subs v E1 (E2 & E3) ((T1, T2, K) :: Q).\nProof.\n  introv Hes Hte He1 He2.\n  apply type_equal_eqn_rec_subst_subs in Hte;\n    auto using type_environment_extension_extend,\n      type_environment_extend_inv.\nQed.\n\n(* *************************************************************** *)\n(** Covariant subtyping inversions *)\n\n(* Type representing covariant (and invariant) contexts *)\nInductive covariant_context : Type :=\n  | ctx_variant : covariant_context\n  | ctx_arrow_left_row : covariant_context\n  | ctx_arrow_right : covariant_context\n  | ctx_ref_co : covariant_context\n  | ctx_prod_left : covariant_context\n  | ctx_prod_right : covariant_context\n  | ctx_constructor : nat -> cset -> covariant_context\n  | ctx_unit : covariant_context.\n  \nDefinition cov_input_kind z :=\n  match z with\n  | ctx_variant => knd_row_all\n  | ctx_arrow_left_row => knd_type\n  | ctx_arrow_right => knd_type\n  | ctx_ref_co => knd_type\n  | ctx_prod_left => knd_type\n  | ctx_prod_right => knd_type\n  | ctx_constructor _ _ => knd_type\n  | ctx_unit => knd_type\n  end.\n\nDefinition cov_output_kind z :=\n  match z with\n  | ctx_variant => knd_type\n  | ctx_arrow_left_row => knd_type\n  | ctx_arrow_right => knd_type\n  | ctx_ref_co => knd_type\n  | ctx_prod_left => knd_type\n  | ctx_prod_right => knd_type\n  | ctx_constructor _ cs => knd_row cs\n  | ctx_unit => knd_type\n  end.\n\nInductive valid_covariant_context : covariant_context -> Prop :=\n  | valid_ctx_variant : valid_covariant_context ctx_variant\n  | valid_ctx_arrow_left_row :\n      valid_covariant_context ctx_arrow_left_row\n  | valid_ctx_arrow_right : valid_covariant_context ctx_arrow_right\n  | valid_ctx_ref_co : valid_covariant_context ctx_ref_co\n  | valid_ctx_prod_left : valid_covariant_context ctx_prod_left\n  | valid_ctx_prod_right : valid_covariant_context ctx_prod_right\n  | valid_ctx_constructor : forall c cs,\n      CSet.In c cs ->\n      valid_covariant_context (ctx_constructor c cs)\n  | valid_ctx_unit : valid_covariant_context ctx_unit.\n\nHint Constructors valid_covariant_context.\n\nInductive covariant_inv :\n  covariant_context -> bool -> version -> tenv -> tenv ->\n  typ -> typ -> Prop :=\n  | covariant_inv_meet : forall z s v E1 E2 T1 T2 T3,\n      covariant_inv z s v E1 E2 T1 T2 ->\n      covariant_inv z s v E1 E2 T1 T3 ->\n      covariant_inv z s v E1 E2 T1 (typ_meet T2 T3)\n  | covariant_inv_join : forall z s1 s2 s3 v E1 E2 T1 T2 T3 T4 T5,\n      covariant_inv z s1 v E1 E2 T2 T4 ->\n      covariant_inv z s2 v E1 E2 T3 T5 ->\n      type_equal v (E1 & E2) empty nil nil T1\n                 (typ_join T2 T3) (cov_input_kind z) ->\n      s3 = orb s1 s2 ->\n      covariant_inv z s3 v E1 E2 T1 (typ_join T4 T5)\n  | covariant_inv_top : forall z s v E1 E2 K2 T1,\n      covariant_inv z s v E1 E2 T1 (typ_top K2)\n  | covariant_inv_var : forall z s v E1 E2 X T1 T2 T3,\n      binds X (Rng T2 T3 (cov_output_kind z)) E1 ->\n      covariant_inv z s v E1 E2 T1 T2 ->\n      covariant_inv z s v E1 E2 T1 (typ_fvar X)\n  | covariant_inv_variant : forall s v E1 E2 T1 T2,\n      subtype v (E1 & E2) empty nil nil T1 T2 knd_row_all ->\n      covariant_inv ctx_variant s v E1 E2 T1 (typ_variant T2)\n  | covariant_inv_arrow_left : forall s E1 E2 T1 T2 T3,\n      subtype version_row_subtyping (E1 & E2) empty nil nil\n        T1 T2 knd_type ->\n      covariant_inv ctx_arrow_left_row s version_row_subtyping\n        E1 E2 T1 (typ_arrow T2 T3)\n  | covariant_inv_arrow_right : forall s v E1 E2 T1 T2 T3,\n      subtype v (E1 & E2) empty nil nil T1 T3 knd_type ->\n      covariant_inv ctx_arrow_right s v E1 E2 T1 (typ_arrow T2 T3)\n  | covariant_inv_ref : forall s v E1 E2 T1 T2,\n      subtype v (E1 & E2) empty nil nil T1 T2 knd_type ->\n      covariant_inv ctx_ref_co s v E1 E2 T1 (typ_ref T2)\n  | covariant_inv_prod_left : forall s v E1 E2 T1 T2 T3,\n      subtype v (E1 & E2) empty nil nil T1 T2 knd_type ->\n      covariant_inv ctx_prod_left s v E1 E2 T1 (typ_prod T2 T3)\n  | covariant_inv_prod_right : forall s v E1 E2 T1 T2 T3,\n      subtype v (E1 & E2) empty nil nil T1 T3 knd_type ->\n      covariant_inv ctx_prod_right s v E1 E2 T1 (typ_prod T2 T3)\n  | covariant_inv_or_l : forall c s v E1 E2 cs1 cs2 cs3 T1 T2 T3,\n      covariant_inv (ctx_constructor c cs1) s v E1 E2 T1 T2 ->\n      CSet.In c cs1 ->\n      covariant_inv (ctx_constructor c cs3) s\n        v E1 E2 T1 (typ_or cs1 cs2 T2 T3)\n  | covariant_inv_or_r : forall c s v E1 E2 cs1 cs2 cs3 T1 T2 T3,\n      covariant_inv (ctx_constructor c cs2) s v E1 E2 T1 T3 ->\n      CSet.In c cs2 ->\n      covariant_inv (ctx_constructor c cs3) s\n        v E1 E2 T1 (typ_or cs1 cs2 T2 T3)\n  | covariant_inv_proj : forall c s v E1 E2 cs1 cs2 T1 T2,\n      covariant_inv (ctx_constructor c cs1) s v E1 E2 T1 T2 ->\n      covariant_inv (ctx_constructor c cs2) s\n        v E1 E2 T1 (typ_proj cs1 cs2 T2)\n  | covariant_inv_constructor : forall c cs s v E1 E2 T1 T2,\n      subtype v (E1 & E2) empty nil nil T1 T2 knd_type ->\n      covariant_inv (ctx_constructor c cs) s\n        v E1 E2 T1 (typ_constructor c T2)\n  | covariant_inv_unit : forall s v E1 E2 T1,\n      covariant_inv ctx_unit s v E1 E2 T1 typ_unit\n  | covariant_inv_mu : forall z s v E1 E2 T1 T2 K,\n      covariant_inv z s v E1 E2 T1\n        (typ_open T2 ((typ_mu K T2) :: nil)) ->\n      K = cov_output_kind z ->\n      covariant_inv z s v E1 E2 T1 (typ_mu K T2)\n  | covariant_inv_bot : forall z v E1 E2 T1 T2,\n      type_equal v (E1 & E2) empty nil nil T1\n        (typ_bot (cov_input_kind z)) (cov_input_kind z) ->\n      covariant_inv z false v E1 E2 T1 T2.\n\nHint Constructors covariant_inv.\n\nLemma covariant_inv_meet_inv : forall z s v E1 E2 T1 T2 T3 (P : Prop),\n    covariant_inv z s v E1 E2 T1 (typ_meet T2 T3) ->\n    (s = false ->\n     type_equal v (E1 & E2) empty nil nil T1\n       (typ_bot (cov_input_kind z)) (cov_input_kind z) ->\n     P) ->\n    (covariant_inv z s v E1 E2 T1 T2 ->\n     covariant_inv z s v E1 E2 T1 T3 ->\n     P) ->\n    P.\nProof.\n  introv Hc Hp1 Hp2.\n  inversion Hc; auto.\nQed.\n\nLemma covariant_inv_join_inv :\n  forall z s1 v E1 E2 T1 T2 T3 (P : Prop),\n    covariant_inv z s1 v E1 E2 T1 (typ_join T2 T3) ->\n    (s1 = false ->\n     type_equal v (E1 & E2) empty nil nil T1\n       (typ_bot (cov_input_kind z)) (cov_input_kind z) ->\n     P) ->\n    (forall s2 s3 T4 T5,\n        covariant_inv z s2 v E1 E2 T4 T2 ->\n        covariant_inv z s3 v E1 E2 T5 T3 ->\n        type_equal v (E1 & E2) empty nil nil T1\n                   (typ_join T4 T5) (cov_input_kind z) ->\n        s1 = orb s2 s3 ->\n        P) ->\n    P.\nProof.\n  introv Hc Hp1 Hp2.\n  inversion Hc; eauto.\nQed.\n\nLemma covariant_inv_var_inv : forall z s v E1 E2 X T1 (P : Prop),\n    covariant_inv z s v E1 E2 T1 (typ_fvar X) ->\n    (s = false ->\n     type_equal v (E1 & E2) empty nil nil T1\n       (typ_bot (cov_input_kind z)) (cov_input_kind z) ->\n     P) ->\n    (forall T2 T3,\n        binds X (Rng T2 T3 (cov_output_kind z)) E1 ->\n        covariant_inv z s v E1 E2 T1 T2 ->\n        P) ->\n    P.\nProof.\n  introv Hc Hp1 Hp2.\n  inversion Hc; eauto.\nQed.\n\nLemma covariant_inv_variant_inv : forall z s v E1 E2 T1 T2 (P : Prop),\n    covariant_inv z s v E1 E2 T1 (typ_variant T2) ->\n    (s = false ->\n     type_equal v (E1 & E2) empty nil nil T1\n       (typ_bot (cov_input_kind z)) (cov_input_kind z) ->\n     P) ->\n    (z = ctx_variant ->\n     subtype v (E1 & E2) empty nil nil T1 T2 knd_row_all ->\n     P) ->\n    P.\nProof.\n  introv Hc Hp1 Hp2.\n  inversion Hc; auto.\nQed.\n\nLemma covariant_inv_arrow_inv : forall z s v E1 E2 T1 T2 T3 (P : Prop),\n    covariant_inv z s v E1 E2 T1 (typ_arrow T2 T3) ->\n    (s = false ->\n     type_equal v (E1 & E2) empty nil nil T1\n       (typ_bot (cov_input_kind z)) (cov_input_kind z) ->\n     P) ->\n    (z = ctx_arrow_left_row ->\n     v = version_row_subtyping ->\n     subtype v (E1 & E2) empty nil nil T1 T2 knd_type ->\n     P) ->\n    (z = ctx_arrow_right ->\n     subtype v (E1 & E2) empty nil nil T1 T3 knd_type ->\n     P) ->\n    P.\nProof.\n  introv Hc Hp1 Hp2 Hp3.\n  inversion Hc; subst; auto.\nQed.\n\nLemma covariant_inv_ref_inv : forall z s v E1 E2 T1 T2 (P : Prop),\n    covariant_inv z s v E1 E2 T1 (typ_ref T2) ->\n    (s = false ->\n     type_equal v (E1 & E2) empty nil nil T1\n       (typ_bot (cov_input_kind z)) (cov_input_kind z) ->\n     P) ->\n    (z = ctx_ref_co ->\n     subtype v (E1 & E2) empty nil nil T1 T2 knd_type ->\n     P) ->\n    P.\nProof.\n  introv Hc Hp1 Hp2.\n  inversion Hc; auto.\nQed.\n\nLemma covariant_inv_prod_inv : forall z s v E1 E2 T1 T2 T3 (P : Prop),\n    covariant_inv z s v E1 E2 T1 (typ_prod T2 T3) ->\n    (s = false ->\n     type_equal v (E1 & E2) empty nil nil T1\n       (typ_bot (cov_input_kind z)) (cov_input_kind z) ->\n     P) ->\n    (z = ctx_prod_left ->\n     subtype v (E1 & E2) empty nil nil T1 T2 knd_type ->\n     P) ->\n    (z = ctx_prod_right ->\n     subtype v (E1 & E2) empty nil nil T1 T3 knd_type ->\n     P) ->\n    P.\nProof.\n  introv Hc Hp1 Hp2 Hp3.\n  inversion Hc; auto.\nQed.\n\nLemma covariant_inv_or_inv :\n  forall z s v E1 E2 cs1 cs2 T1 T2 T3 (P : Prop),\n    covariant_inv z s v E1 E2 T1 (typ_or cs1 cs2 T2 T3) ->\n    (s = false ->\n     type_equal v (E1 & E2) empty nil nil T1\n       (typ_bot (cov_input_kind z)) (cov_input_kind z) ->\n     P) ->\n    (forall c cs3,\n        z = ctx_constructor c cs3 ->\n        covariant_inv (ctx_constructor c cs1) s v E1 E2 T1 T2 ->\n        CSet.In c cs1 ->\n        P) ->\n    (forall c cs3,\n        z = ctx_constructor c cs3 ->\n        covariant_inv (ctx_constructor c cs2) s v E1 E2 T1 T3 ->\n        CSet.In c cs2 ->\n        P) ->\n    P.\nProof.\n  introv Hc Hp1 Hp2 Hp3.\n  inversion Hc; eauto.\nQed.\n\nLemma covariant_inv_proj_inv :\n  forall z s v E1 E2 cs1 cs2 T1 T2 (P : Prop),\n    covariant_inv z s v E1 E2 T1 (typ_proj cs1 cs2 T2) ->\n    (s = false ->\n     type_equal v (E1 & E2) empty nil nil T1\n       (typ_bot (cov_input_kind z)) (cov_input_kind z) ->\n     P) ->\n    (forall c,\n        z = ctx_constructor c cs2 ->\n        covariant_inv (ctx_constructor c cs1) s v E1 E2 T1 T2 ->\n        P) ->\n    P.\nProof.\n  introv Hc Hp1 Hp2.\n  inversion Hc; subst; eauto.  \nQed.\n\nLemma covariant_inv_constructor_inv :\n  forall z s v E1 E2 c T1 T2 (P : Prop),\n    covariant_inv z s v E1 E2 T1 (typ_constructor c T2) ->\n    (s = false ->\n     type_equal v (E1 & E2) empty nil nil T1\n       (typ_bot (cov_input_kind z)) (cov_input_kind z) ->\n     P) ->\n    (forall cs,\n        z = ctx_constructor c cs ->\n        subtype v (E1 & E2) empty nil nil T1 T2 knd_type ->\n        P) ->\n    P.\nProof.\n  introv Hc Hp1 Hp2.\n  inversion Hc; subst; eauto.\nQed.\n\nLemma covariant_inv_unit_inv :\n  forall z s v E1 E2 T1 (P : Prop),\n    covariant_inv z s v E1 E2 T1 typ_unit ->\n    (s = false ->\n     type_equal v (E1 & E2) empty nil nil T1\n       (typ_bot (cov_input_kind z)) (cov_input_kind z) ->\n     P) ->\n    (z = ctx_unit -> P) ->\n    P.\nProof.\n  introv Hc Hp1 Hp2.\n  inversion Hc; subst; eauto.\nQed.\n\nLemma covariant_inv_mu_inv :\n  forall z s v E1 E2 T1 T2 K (P : Prop),\n    covariant_inv z s v E1 E2 T1 (typ_mu K T2) ->\n    (s = false ->\n     type_equal v (E1 & E2) empty nil nil T1\n       (typ_bot (cov_input_kind z)) (cov_input_kind z) ->\n     P) ->\n    (K = cov_output_kind z ->\n     covariant_inv z s v E1 E2 T1\n        (typ_open T2 ((typ_mu K T2) :: nil)) ->\n     P) ->\n    P.\nProof.\n  introv Hc Hp1 Hp2.\n  inversion Hc; subst; eauto.\nQed.\n\nLemma covariant_inv_bot_inv :\n  forall z s v E1 E2 T1 K (P : Prop),\n    covariant_inv z s v E1 E2 T1 (typ_bot K) ->\n    (s = false ->\n     type_equal v (E1 & E2) empty nil nil T1\n       (typ_bot (cov_input_kind z)) (cov_input_kind z) ->\n     P) ->\n    P.\nProof.\n  introv Hc Hp1.\n  inversion Hc; subst; eauto.\nQed.\n\nLtac invert_ctx_constructor_equalities :=\n  repeat match goal with\n  | Heq : ctx_constructor _ _ = ctx_constructor _ _ |- _ =>\n    inversion Heq; clear Heq\n  end.\n\nLtac discriminate_ctx_prod_mismatches :=\n  try match goal with\n  | Heq : ctx_prod_left = ctx_prod_right |- _ =>\n    discriminate Heq\n  | Heq : ctx_prod_right = ctx_prod_left |- _ =>\n    discriminate Heq\n  end.\n\nLtac discriminate_cov_ctx_arrow_mismatches :=\n  try match goal with\n  | Heq : ctx_arrow_left_row = ctx_arrow_right |- _ =>\n    discriminate Heq\n  | Heq : ctx_arrow_right = ctx_arrow_left_row |- _ =>\n    discriminate Heq\n  end.\n\nLtac discriminate_version :=\n  try match goal with\n  | Heq : version_full_subtyping = version_row_subtyping |- _ =>\n    discriminate Heq\n  | Heq : version_row_subtyping = version_full_subtyping |- _ =>\n    discriminate Heq\n  end.\n\nLtac equate_multiple_bindings :=\n  repeat match goal with\n  | Hb1 : binds ?X (Rng ?T1 ?T2 ?K1) ?E,\n    Hb2 : binds ?X (Rng ?T3 ?T4 ?K2) ?E |- _ =>\n    let Heq := fresh \"Heq\" in\n    assert (Heq := binds_functional Hb1 Hb2);\n    inversion Heq; subst; clear Heq; clear Hb2\n  | Hb1 : binds ?X (Rng ?T1 ?T2 ?K1) ?E1,\n    Hb2 : binds ?X (Rng ?T3 ?T4 ?K2) (?E1 & ?E2) |- _ =>\n    let He := fresh \"He\" in\n    assert (type_environment (E1 & E2)) as He\n      by auto with wellformed;\n    let Heq := fresh \"Heq\" in\n    assert (Heq := binds_functional\n                     (binds_tenv_weakening_l Hb1 He) Hb2);\n    inversion Heq; subst; clear He; clear Heq; clear Hb2\n  | Hb1 : binds ?X (Rng ?T1 ?T2 ?K1) ?E1,\n    Hb2 : binds ?X (Rng ?T3 ?T4 ?K2) (?E1 & ?E2 & ?E3)\n    |- _ =>\n    let He := fresh \"He\" in\n    assert (type_environment (E1 & E2 & E3)) as He\n      by auto with wellformed;\n    let Heq := fresh \"Heq\" in\n    assert (Heq := binds_functional\n                     (binds_tenv_weakening_l2 Hb1 He) Hb2);\n    inversion Heq; subst; clear He; clear Heq; clear Hb2\n  end.\n\nLtac invert_covariant_inv :=\n  repeat match goal with\n  | H : covariant_inv _ _ _ _ _ _ (typ_constructor _ _) |- _ =>\n    apply (covariant_inv_constructor_inv H); clear H; intros;\n    invert_ctx_constructor_equalities; subst\n  | H : covariant_inv _ _ _ _ _ _ (typ_or _ _ _ _) |- _ =>\n    apply (covariant_inv_or_inv H); clear H; intros;\n    invert_ctx_constructor_equalities; subst\n  | H : covariant_inv _ _ _ _ _ _ (typ_proj _ _ _) |- _ =>\n    apply (covariant_inv_proj_inv H); clear H; intros;\n    invert_ctx_constructor_equalities; subst\n  | H : covariant_inv _ _ _ _ _ _ (typ_variant _) |- _ =>\n    apply (covariant_inv_variant_inv H); clear H; intros\n  | H : covariant_inv _ _ _ _ _ _ (typ_arrow _ _) |- _ =>\n    apply (covariant_inv_arrow_inv H); clear H; intros;\n    subst; discriminate_cov_ctx_arrow_mismatches;\n    discriminate_version\n  | H : covariant_inv _ _ _ _ _ _ (typ_ref _) |- _ =>\n    apply (covariant_inv_ref_inv H); clear H; intros\n  | H : covariant_inv _ _ _ _ _ _ (typ_prod _ _) |- _ =>\n    apply (covariant_inv_prod_inv H); clear H; intros;\n    subst; discriminate_ctx_prod_mismatches\n  | H : covariant_inv _ _ _ _ _ _ typ_unit |- _ =>\n    apply (covariant_inv_unit_inv H); clear H; intros\n  | H : covariant_inv _ _ _ _ _ _ (typ_mu _ _) |- _ =>\n    apply (covariant_inv_mu_inv H); clear H; intros\n  | H : covariant_inv _ _ _ _ _ _ (typ_fvar _) |- _ =>\n    apply (covariant_inv_var_inv H); clear H; intros;\n    equate_multiple_bindings\n  | H : covariant_inv _ _ _ _ _ _ (typ_bot _) |- _ =>\n    apply (covariant_inv_bot_inv H); clear H; intros\n  | H : covariant_inv _ _ _ _ _ _ (typ_meet _ _) |- _ =>\n    apply (covariant_inv_meet_inv H); clear H; intros\n  | H : covariant_inv _ _ _ _ _ _ (typ_join _ _) |- _ =>\n    apply (covariant_inv_join_inv H); clear H; intros\n  end.\n\nLtac choose_covariant_inv_join_type z Td T :=\n  match T with\n  | typ_meet ?T1 ?T2 =>\n    let T1' := choose_covariant_inv_join_type z Td T1 in\n    let T2' := choose_covariant_inv_join_type z Td T2 in\n    constr:(typ_meet T1' T2')\n  | typ_join ?T1 ?T2 =>\n    let T1' := choose_covariant_inv_join_type z Td T1 in\n    let T2' := choose_covariant_inv_join_type z Td T2 in\n    constr:(typ_join T1' T2')\n  | typ_or ?cs1 ?cs2 ?T1 ?T2 =>\n    match z with\n    | ctx_constructor ?c _ =>\n      match goal with\n      | Hin : CSet.In c cs1 |- _ =>\n        choose_covariant_inv_join_type z Td T1\n      | Hin : CSet.In c cs2 |- _ =>\n        choose_covariant_inv_join_type z Td T2\n      end\n    end\n  | typ_proj _ _ ?T1 =>\n    choose_covariant_inv_join_type z Td T1\n  | typ_variant ?T1 => constr:(typ_meet Td T1)\n  | typ_constructor _ ?T1 => constr:(typ_meet Td T1)\n  | typ_ref ?T1 => constr:(typ_meet Td T1)\n  | typ_arrow ?T1 ?T2 =>\n    match z with\n    | ctx_arrow_left_row => constr:(typ_meet Td T1)\n    | ctx_arrow_right => constr:(typ_meet Td T2)\n    end\n  | typ_prod ?T1 ?T2 =>\n    match z with\n    | ctx_prod_left => constr:(typ_meet Td T1)\n    | ctx_prod_right => constr:(typ_meet Td T2)\n    end\n  | typ_unit => constr:(Td)\n  | typ_bot (cov_output_kind ?z) => constr:(typ_bot (cov_input_kind z))\n  | _ =>\n    match goal with\n    | H1 : covariant_inv _ _ _ _ _ ?Tt1 T,\n      H2 : covariant_inv _ _ _ _ _ ?Tt2 T\n      |- _ => constr:(typ_join Tt1 Tt2)\n    | H : covariant_inv _ _ _ _ _ ?Tt T |- _ =>\n      constr:(Tt)\n    | Hte : type_equal _ _ _ nil nil ?Tb (typ_bot _) _ |- _ =>\n      constr:(Tb)\n    end\n  end.\n\nLtac choose_covariant_inv_join_bool z sd T :=\n  match T with\n  | typ_meet ?T1 ?T2 =>\n    let s1 := choose_covariant_inv_join_bool z sd T1 in\n    let s2 := choose_covariant_inv_join_bool z sd T2 in\n    constr:(andb s1 s2)\n  | typ_join ?T1 ?T2 =>\n    let s1 := choose_covariant_inv_join_bool z sd T1 in\n    let s2 := choose_covariant_inv_join_bool z sd T2 in\n    constr:(orb s1 s2)\n  | typ_or ?cs1 ?cs2 ?T1 ?T2 =>\n    match z with\n    | ctx_constructor ?c _ =>\n      match goal with\n      | Hin : CSet.In c cs1 |- _ =>\n        choose_covariant_inv_join_bool z sd T1\n      | Hin : CSet.In c cs2 |- _ =>\n        choose_covariant_inv_join_bool z sd T2\n      end\n    end\n  | typ_proj _ _ ?T1 =>\n    choose_covariant_inv_join_bool z sd T1\n  | typ_variant _ => constr:(sd)\n  | typ_constructor _ _ => constr:(sd)\n  | typ_ref _ => constr:(sd)\n  | typ_arrow _ _ => constr:(sd)\n  | typ_prod _ _ => constr:(sd)\n  | typ_unit => constr:(sd)\n  | typ_bot (cov_output_kind ?z) => constr:(false)\n  | _ =>\n    match goal with\n    | H1 : covariant_inv _ ?s1 _ _ _ _ T,\n      H2 : covariant_inv _ ?s2 _ _ _ _ T\n      |- _ => constr:(orb s1 s2)\n    | H : covariant_inv _ ?s _ _ _ _ T |- _ => constr:(s)\n    | Hte : type_equal _ _ _ nil nil ?Tb (typ_bot _) _ |- _ =>\n      constr:(false)\n    end\n  end.\n\nLtac construct_covariant_inv_bot :=\n  try match goal with\n  | |- covariant_inv _ _ _ _ _ (typ_bot _) _ =>\n    apply covariant_inv_bot;\n    treflexivity\n  | |- covariant_inv _ (?s && false) _ _ _\n         (typ_meet _ (typ_bot _)) _ =>\n    try replace (andb s false) with false by ring;\n    apply covariant_inv_bot;\n    rewrite type_equal_meet_annihilation_r\n      by auto with wellformed;\n    treflexivity\n  | |- covariant_inv _ _ _ _ _ ?Tt _ =>\n    match goal with\n    | H : type_equal _ _ _ nil nil Tt (typ_bot _) _ |- _ =>\n      apply covariant_inv_bot;\n      apply H\n    | H: type_equal _ _ _ nil nil Tt (typ_join ?Ttl ?Ttr) _,\n      Hl : type_equal _ _ _ nil nil ?Ttl (typ_bot _) _,\n      Hr : type_equal _ _ _ nil nil ?Ttr (typ_bot _) _ |- _ =>\n      apply covariant_inv_bot;\n      rewrite H;\n      rewrite Hl;\n      rewrite Hr;\n      rewrite type_equal_join_identity by auto with kinding;\n      treflexivity\n    end\n  end.\n\nLtac construct_covariant_inv :=\n  construct_covariant_inv_bot;\n  repeat match goal with\n  | |- covariant_inv ?z _ _ _ _ ?Tt (typ_or ?csl ?csr ?Tl ?Tr) =>\n    match goal with\n    | H : covariant_inv _ _ _ _ _ Tt ?Ts |- _ =>\n      match Tl with\n      | context[Ts] =>\n        match Tr with\n        | context[Ts] =>\n          match z with\n          | ctx_constructor ?c ?cs =>\n            destruct (CSet.In_dec c csl);\n            [> apply covariant_inv_or_l\n            | apply covariant_inv_or_r]\n          end\n        | _ => apply covariant_inv_or_l\n        end\n      | _ =>\n        match Tr with\n        | context[Ts] => apply covariant_inv_or_r\n        end\n      end\n    | _ =>\n      match z with\n      | ctx_constructor ?c ?cs =>\n        destruct (CSet.In_dec c csl);\n        [> apply covariant_inv_or_l | apply covariant_inv_or_r]\n      end     \n    end\n  | |- covariant_inv ?z ?s _ _ _ ?Tt (typ_join ?Ts1 ?Ts2) =>\n    let s1' := choose_covariant_inv_join_bool z s Ts1 in\n    let s2' := choose_covariant_inv_join_bool z s Ts2 in\n    let T1' := choose_covariant_inv_join_type z Tt Ts1 in\n    let T2' := choose_covariant_inv_join_type z Tt Ts2 in\n    apply covariant_inv_join\n      with (s1 := s1') (s2 := s2') (T2 := T1') (T3 := T2')\n  | |- covariant_inv _ _ _ _ _ _ (typ_top _) =>\n    apply covariant_inv_top\n  | |- covariant_inv _ _ _ _ _ _ (typ_meet _ _) =>\n    apply covariant_inv_meet\n  | |- covariant_inv _ _ _ _ _ _ (typ_proj _ _ _) =>\n    apply covariant_inv_proj\n  | |- covariant_inv _ _ _ _ _ _ (typ_variant _) =>\n    apply covariant_inv_variant\n  | |- covariant_inv _ _ _ _ _ _ (typ_constructor _ _) =>\n    apply covariant_inv_constructor\n  | |- covariant_inv ctx_arrow_left_row _ _ _ _ _ (typ_arrow _ _) =>\n    apply covariant_inv_arrow_left\n  | |- covariant_inv ctx_arrow_right _ _ _ _ _ (typ_arrow _ _) =>\n    apply covariant_inv_arrow_right\n  | |- covariant_inv ctx_prod_left _ _ _ _ _ (typ_prod _ _) =>\n    apply covariant_inv_prod_left\n  | |- covariant_inv ctx_prod_right _ _ _ _ _ (typ_prod _ _) =>\n    apply covariant_inv_prod_right\n  | |- covariant_inv _ _ _ _ _ _ (typ_ref _) =>\n    apply covariant_inv_ref\n  | |- covariant_inv _ _ _ _ _ _ (typ_mu _ _) =>\n    apply covariant_inv_mu\n  | Hb : binds ?X (Rng ?Tl ?Tu _) _\n    |- covariant_inv _ _ _ _ _ _ (typ_fvar ?X) =>\n    apply covariant_inv_var with (T2 := Tl) (T3 := Tu)\n  end;\n  try assumption;\n  construct_covariant_inv_bot.\n\nLemma covariant_inv_sub : forall z s1 s2 v E1 E2 K1 T1 T2 T3,\n    covariant_inv z s1 v E1 E2 T1 T2 ->\n    subtype v (E1 & E2) empty nil nil T3 T1 K1 ->\n    leb s2 s1 ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    K1 = cov_input_kind z ->\n    covariant_inv z s2 v E1 E2 T3 T2.\nProof.\n  introv Hi Hs Hb He1 He2 Heq.\n  generalize dependent T3.\n  generalize dependent s2.\n  subst.\n  induction Hi; introv Hb Hs; subst; eauto.\n  - apply covariant_inv_join\n      with (s1 := andb s0 s1) (s2 := andb s0 s2)\n           (T2 := typ_meet T0 T2) (T3 := typ_meet T0 T3); auto.\n    + eauto using subtype_lower_bound_r,\n        type_environment_extend, leb_lower_bound_r\n          with kinding wellformed.\n    + eauto using subtype_lower_bound_r,\n        type_environment_extend, leb_lower_bound_r\n          with kinding wellformed.\n    + unfold subtype in Hs.\n      rewrite Hs at 1.\n      subst_equal T1.\n      rewrite type_equal_meet_distribution by auto with kinding.\n      treflexivity.\n    + unfold leb in Hb.\n      rewrite Hb at 1.\n      rewrite andb_orb_distribution.\n      reflexivity.      \n  - apply covariant_inv_variant;\n      eauto using subtype_transitive, valid_tenv_extend.\n  - apply covariant_inv_arrow_left;\n      eauto using subtype_transitive, valid_tenv_extend.\n  - apply covariant_inv_arrow_right;\n      eauto using subtype_transitive, valid_tenv_extend.\n  - apply covariant_inv_ref;\n      eauto using subtype_transitive, valid_tenv_extend.\n  - apply covariant_inv_prod_left;\n      eauto using subtype_transitive, valid_tenv_extend.\n  - apply covariant_inv_prod_right;\n      eauto using subtype_transitive, valid_tenv_extend.\n  - apply covariant_inv_constructor;\n      eauto using subtype_transitive, valid_tenv_extend.\n  - rewrite leb_false with (b := s2) by assumption.\n    eauto using subtype_equal_bot, valid_tenv_extend.\nQed.\n\nInstance covariant_inv_eq_morph_impl\n  (z : covariant_context) (s : bool) (v : version)\n  (E1 : tenv) (E2 : tenv)\n  `{ He1 : valid_tenv v E1 }\n  `{ He2 : valid_tenv_extension v E1 E2 }\n  : Morphisms.Proper\n      (type_equal' v (E1 & E2) empty nil nil (cov_input_kind z) ==>\n       eq ==> Basics.impl)\n      (covariant_inv z s v E1 E2) | 3\n  := { }.\n  unfold Morphisms.respectful.\n  intros T1 T1' Hte T2' T2 Heq Hi.\n  rewrite <- Heq.\n  apply covariant_inv_sub\n    with (s1 := s) (K1 := cov_input_kind z) (T1 := T1);\n    auto using leb_refl.\n  rewrite Hte.\n  sreflexivity.\nQed.\n\nInstance covariant_inv_eq_morph_flip_impl\n  (z : covariant_context) (s : bool) (v : version)\n  (E1 : tenv) (E2 : tenv)\n  `{ He1 : valid_tenv v E1 }\n  `{ He2 : valid_tenv_extension v E1 E2 }\n  : Morphisms.Proper\n      (type_equal' v (E1 & E2) empty nil nil (cov_input_kind z) ==>\n       eq ==> Basics.flip Basics.impl)\n      (covariant_inv z s v E1 E2) | 3\n  := { }.\n  unfold Morphisms.respectful.\n  intros T1 T1' Hte T2' T2 Heq Hi.\n  rewrite Heq.\n  apply covariant_inv_sub\n    with (s1 := s) (K1 := cov_input_kind z) (T1 := T1');\n    auto using leb_refl.\n  rewrite Hte.\n  sreflexivity.\nQed.\n\nInstance covariant_inv_sub_morph_impl\n  (z : covariant_context) (s : bool) (v : version)\n  (E1 : tenv) (E2 : tenv)\n  `{ He1 : valid_tenv v E1 }\n  `{ He2 : valid_tenv_extension v E1 E2 }\n  : Morphisms.Proper\n      (subtype' v (E1 & E2) empty nil nil (cov_input_kind z) ==>\n       eq ==> Basics.flip Basics.impl)\n      (covariant_inv z s v E1 E2) | 3\n  := { }.\n  unfold Morphisms.respectful.\n  intros T1 T1' Hte T2' T2 Heq Hi.\n  rewrite Heq.\n  apply covariant_inv_sub\n    with (s1 := s) (K1 := cov_input_kind z) (T1 := T1');\n    auto using leb_refl.\nQed.\n\nLemma covariant_inv_upper_bound : forall z s1 s2 v E1 E2 T1 T2 T3,\n    covariant_inv z s1 v E1 E2 T1 T3 ->\n    covariant_inv z s2 v E1 E2 T2 T3 ->\n    kinding (E1 & E2) empty T1 (cov_input_kind z) ->\n    kinding (E1 & E2) empty T2 (cov_input_kind z) ->\n    kinding E1 E2 T3 (cov_output_kind z) ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    covariant_inv z (orb s1 s2) v E1 E2 (typ_join T1 T2) T3.\nProof.\n  introv Hi1 Hi2 Hk1 Hk2 Hk3 He1 He2.\n  generalize dependent T2.\n  generalize dependent s2.\n  induction Hi1; introv Hi2 Hk2; invert_covariant_inv; subst;\n    auto using subtype_least_upper_bound, subtype_join_bot_l,\n      valid_tenv_extend with kinding.\n  - apply covariant_inv_join\n      with (s1 := s1) (s2 := s2) (T2 := T2) (T3 := T3);\n      try ring_simplify; auto.\n    subst_equal T0.\n    rewrite type_equal_join_identity by auto with kinding.\n    assumption.\n  - apply covariant_inv_join\n      with (s1 := orb s1 s4) (s2 := orb s2 s5)\n        (T2 := typ_join T2 T6) (T3 := typ_join T3 T7);\n          try ring_simplify; auto with kinding.\n    subst_equal T1.\n    subst_equal T0.\n    rewrite <- type_equal_join_associative by auto with kinding.\n    rewrite type_equal_join_associative\n      with (T1 := T3) by auto with kinding.\n    rewrite type_equal_join_commutative\n      with (T1 := T3) by auto with kinding.\n    rewrite <- type_equal_join_associative by auto with kinding.\n    rewrite type_equal_join_associative by auto with kinding.\n    treflexivity.\n  - eauto using kinding_from_valid_tenv_lower with wellformed.\n  - eauto using kinding_from_valid_tenv_lower with wellformed.\n  - inversion Hk3; subst.\n    assert (not (CSet.In c0 cs1)) by csetdec.\n    contradiction.\n  - inversion Hk3; subst.\n    assert (not (CSet.In c0 cs1)) by csetdec.\n    contradiction.\n  - subst_equal T0.\n    rewrite type_equal_join_identity by auto with kinding.\n    replace (orb s false) with s by ring.\n    auto.\n  - auto using kinding_unroll with wellformed.\n  - subst_equal T1.\n    rewrite type_equal_join_commutative by auto with kinding.\n    rewrite type_equal_join_identity by auto with kinding.\n    assumption.\nQed.\n\nLtac invert_kindings_cov :=\n  repeat\n    match goal with\n    | Hz : valid_covariant_context (ctx_constructor _ _) |- _ =>\n      inversion Hz; subst; clear Hz\n    | H : kinding _ _ (typ_or _ _ _ _) _ |- _ =>\n      inversion H; subst; clear H\n    | H : kinding _ _ (typ_proj _ _ _) _ |- _ =>\n      inversion H; subst; clear H\n    | H : kinding _ _ (typ_join _ _) _ |- _ =>\n      inversion H; subst; clear H\n    | H : kinding _ _ (typ_bot _) _ |- _ =>\n      inversion H; subst; clear H\n    | H : kinding _ _ (typ_mu _ _) _ |- _ =>\n      inversion H; subst; clear H\n    end;\n  match goal with\n  | HeqK : knd_row ?cs1 = cov_output_kind (ctx_constructor ?c ?cs2) |- _ =>\n    inversion Heq; subst\n  | HeqK : knd_row ?cs1 = cov_output_kind ?z |- _ =>\n    destruct z; try discriminate;\n    inversion HeqK; subst\n  | _ => idtac\n  end.\n\nLtac unroll_recursive_eqns :=\n  repeat match goal with\n  | Hte1 : type_equal _ (?E1 & ?E2 & ?E3) empty\n            ((?Tl, ?Tr, ?Klr) :: (?Q ++ nil)%list) nil\n            _ _ _,\n    Hte2 : type_equal _ ?E1 (?E2 & ?E3)\n             nil ?Q ?Tl ?Tr ?Klr |- _ =>\n    apply type_equal_eqn_subs_apply in Hte1;\n      auto with wellformed\n  end.    \n\nLtac solve_covariant_inv_side_conditions :=\n  try match goal with\n  | |- type_equal _ _ _ _ _ ?T ?T _ =>\n    treflexivity\n  | |- subtype _ _ _ nil nil (typ_meet ?T1 ?T2) ?T1 _ =>\n    auto using subtype_lower_bound_l with kinding wellformed\n  | |- subtype _ _ _ nil nil (typ_meet ?T1 ?T2) ?T2 _ =>\n    auto using subtype_lower_bound_r with kinding wellformed\n  | Hs1 : subtype _ _ _ nil nil ?T1 ?T2 _,\n    Hs2 : subtype _ _ _ nil nil ?T1 ?T3 _\n    |- subtype _ _ _ nil nil ?T1 (typ_meet ?T2 ?T3) _ =>\n    apply subtype_greatest_lower_bound;\n    auto using valid_tenv_extend\n  | |- @eq bool ?s1 ?s2 =>\n    try ring;\n    repeat match goal with\n    | s : bool |- _ => destruct s\n    end; solve [auto]\n  | Hs : subtype _ _ _ nil nil ?T1 (typ_meet ?T2 ?T3) _\n    |- subtype _ _ _ nil nil ?T1 ?T2 _ =>\n    rewrite Hs;\n    apply subtype_lower_bound_l;\n    auto with kinding wellformed\n  | Hs : subtype _ _ _ nil nil ?T1 (typ_meet ?T2 ?T3) _\n    |- subtype _ _ _ nil nil ?T1 ?T3 _ =>\n    rewrite Hs;\n    apply subtype_lower_bound_r;\n    auto with kinding wellformed\n  | Hs : subtype _ _ _ nil nil ?T1 (typ_join ?T2 ?T3) _ |-\n    type_equal _ _ _ nil nil ?T1\n      (typ_join (typ_meet ?T1 ?T2) (typ_meet ?T1 ?T3)) _ =>\n    rewrite <- type_equal_meet_distribution\n      by auto with kinding;\n    auto\n  | Hte1 : type_equal _ _ _ nil nil ?T1 (typ_join ?T2 ?T3) _,\n    Hte2 : type_equal _ _ _ nil nil ?T3 (typ_bot _) _,\n    Hs : subtype _ _ _ nil nil ?T2 ?T4 _\n    |- subtype _ _ _ nil nil ?T1 (typ_join ?T4 _) _ =>\n    rewrite Hte1;\n    rewrite Hte2;\n    rewrite type_equal_join_identity\n      by auto with kinding;\n    rewrite <- subtype_upper_bound_l\n      by auto with kinding wellformed;\n    rewrite Hs;\n    sreflexivity\n  | Hte1 : type_equal _ _ _ nil nil ?T1 (typ_join ?T2 ?T3) _,\n    Hte2 : type_equal _ _ _ nil nil ?T2 (typ_bot _) _,\n    Hs : subtype _ _ _ nil nil ?T3 ?T4 _\n    |- subtype _ _ _ nil nil ?T1 (typ_join _ ?T4) _ =>\n    rewrite Hte1;\n    rewrite Hte2;\n    rewrite type_equal_join_commutative\n      by auto with kinding;\n    rewrite type_equal_join_identity\n      by auto with kinding;\n    rewrite <- subtype_upper_bound_r\n      by auto with kinding wellformed;\n    rewrite Hs;\n    sreflexivity\n  | Hte : type_equal _ _ _ nil nil ?T1 (typ_join ?T2 ?T3) _,\n    Hs1 : subtype _ _ _ nil nil ?T2 ?T4 _,\n    Hs2 : subtype _ _ _ nil nil ?T3 ?T5 _\n    |- subtype _ _ _ nil nil ?T1 (typ_join ?T4 ?T5) _ =>\n    rewrite Hte;\n    apply subtype_least_upper_bound;\n      try rewrite Hs1; try rewrite Hs2;\n      auto using valid_tenv_extend,\n        subtype_upper_bound_l, subtype_upper_bound_r\n          with kinding wellformed\n  | Hte : type_equal _ _ _ nil nil ?T1 ?T2 _,\n    Hs : subtype _ _ _ nil nil ?T3 ?T1 _\n    |- subtype _ _ _ nil nil ?T3 ?T2 _ =>\n    rewrite Hs;\n    rewrite Hte;\n    sreflexivity\n  | Hte : type_equal _ _ _ nil nil ?T1 ?T2 _,\n    Hs : subtype _ _ _ nil nil ?T3 ?T2 _\n    |- subtype _ _ _ nil nil ?T3 ?T1 _ =>\n    rewrite Hs;\n    rewrite Hte;\n    sreflexivity\n  | Hi : covariant_inv ?z ?s _ _ _ ?Tsl ?Tt |-\n    covariant_inv _ _ _ _ _ (typ_meet ?Tsl _) ?Tt =>\n    apply covariant_inv_sub\n      with (s1 := s) (K1 := cov_input_kind z) (T1 := Tsl);\n      auto using subtype_lower_bound_l, leb_lower_bound_l\n        with kinding wellformed\n  | Hi : covariant_inv ?z ?s _ _ _ ?Tsr ?Tt |-\n    covariant_inv _ _ _ _ _ (typ_meet _ ?Tsr) ?Tt =>\n    apply covariant_inv_sub\n      with (s1 := s) (K1 := cov_input_kind z) (T1 := Tsr);\n      auto using subtype_lower_bound_r, leb_lower_bound_r\n        with kinding wellformed\n  | Hi : covariant_inv _ ?s1 _ _ _ ?Tsl ?Tt,\n    Hte1 : type_equal _ _ _ nil nil ?Ts (typ_join ?Tsl ?Tsr) _,\n    Hte2 : type_equal _ _ _ nil nil ?Tsr (typ_bot _) _ |-\n    covariant_inv _ ?s2  _ _ _ ?Ts ?Tt =>\n    rewrite Hte1;\n    rewrite Hte2;\n    rewrite type_equal_join_identity by auto with kinding;\n    replace s2 with s1 by ring;\n    assumption\n  | Hi : covariant_inv _ ?s1 _ _ _ ?Tsr ?Tt,\n    Hte1 : type_equal _ _ _ nil nil ?Ts (typ_join ?Tsl ?Tsr) _,\n    Hte2 : type_equal _ _ _ nil nil ?Tsl (typ_bot _) _ |-\n    covariant_inv _ ?s2  _ _ _ ?Ts ?Tt =>\n    rewrite Hte1;\n    rewrite Hte2;\n    rewrite type_equal_join_commutative by auto with kinding;\n    rewrite type_equal_join_identity by auto with kinding;\n    replace s2 with s1 by ring;\n    assumption\n  | Hil : covariant_inv _ ?s1 _ _ _ ?Tsl ?Tt,\n    Hir : covariant_inv _ ?s2 _ _ _ ?Tsr ?Tt,\n    Hte : type_equal _ _ _ nil nil ?Ts (typ_join ?Tsl ?Tsr) _ |-\n    covariant_inv _ (orb ?s1 ?s2) _ _ _ ?Ts ?Tt =>\n    rewrite Hte;\n    apply covariant_inv_upper_bound;\n    auto with kinding wellformed\n  | Hil : covariant_inv _ ?s1 _ _ _ ?Tsl ?Tt,\n    Hir : covariant_inv _ ?s2 _ _ _ ?Tsr ?Tt\n    |- covariant_inv _ (orb ?s1 ?s2) _ _ _\n                     (typ_join ?Tsl ?Tsr) ?Tt =>\n    apply covariant_inv_upper_bound;\n    auto with kinding wellformed\n  | H1 : CSet.In ?c ?cs1,\n    H2 : ~ CSet.In ?c ?cs1 |- _ =>\n    contradiction\n  | Hk : kinding _ _ (typ_or ?cs1 ?cs2 _ _) _,\n    H1 : CSet.In ?c ?cs1,\n    H2 : CSet.In ?c ?cs2 |- _ =>\n    inversion Hk; subst;\n    assert (~ CSet.In c cs1) by csetdec;\n    contradiction\n  | Hk : kinding _ _ (typ_or ?cs _ (typ_or _ _ _ _) _) _\n    |- CSet.In _ ?cs =>\n    inversion Hk; subst;\n    match goal with\n    | Hk' : kinding _ _ (typ_or _ _ _ _) (knd_row cs) |- _ =>\n      inversion Hk'; subst;\n      csetdec\n    end\n  | |- cov_output_kind ?z = cov_output_kind ?z =>\n    reflexivity\n  | |- CSet.In _ _ =>\n    invert_kindings_cov;\n    csetdec\n  | Hin : in_qenv nil _ _ _ |- _ =>\n    inversion Hin\n  end.\n\nLemma type_equal_core_covariant_inv_l :\n  forall z s v E1 E2 T1 T2 T3,\n    covariant_inv z s v E1 E2 T1 T2 ->\n    type_equal_core v T2 T3 ->\n    valid_covariant_context z ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    kinding (E1 & E2) empty T1 (cov_input_kind z) ->\n    kinding E1 E2 T2 (cov_output_kind z) ->\n    kinding E1 E2 T3 (cov_output_kind z) ->\n    covariant_inv z s v E1 E2 T1 T3.\nProof.\n  introv Hi Hte Hz He1 He2 Hk1 Hk2 Hk3.\n  destruct Hte; invert_covariant_inv; subst;\n    construct_covariant_inv; solve_covariant_inv_side_conditions.\n  - invert_kindings_cov.\n    construct_covariant_inv; solve_covariant_inv_side_conditions.\n  - invert_kindings_cov.\n    construct_covariant_inv; solve_covariant_inv_side_conditions.\n  - invert_kindings_cov.\n    assert (not (CSet.In c0 cs2)) by csetdec.\n    contradiction.\n  - invert_kindings_cov.\n    assert (not (CSet.In c0 cs1)) by csetdec.\n    contradiction.\n  - rewrite <- type_equal_meet_distribution by auto with kinding.\n    subst_equal T1 at 2.\n    rewrite <- type_equal_meet_idempotent\n      by auto with kinding wellformed.\n    subst_equal T1.\n    treflexivity.\n  - subst_equal T1.\n    rewrite type_equal_join_commutative by auto with kinding.\n    treflexivity.\n  - rewrite <- type_equal_join_associative by auto with kinding.\n    rewrite <- type_equal_join_idempotent\n      by auto with kinding wellformed.\n    subst_equal T1.\n    treflexivity.\n  - subst_equal T1.\n    subst_equal T5.\n    rewrite type_equal_join_associative by auto with kinding.\n    treflexivity.\nQed.\n\nLemma type_equal_core_covariant_inv_r :\n  forall z s v E1 E2 T1 T2 T3,\n    covariant_inv z s v E1 E2 T1 T2 ->\n    type_equal_core v T3 T2 ->\n    valid_covariant_context z ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    kinding (E1 & E2) empty T1 (cov_input_kind z) ->\n    kinding E1 E2 T2 (cov_output_kind z) ->\n    kinding E1 E2 T3 (cov_output_kind z) ->\n    covariant_inv z s v E1 E2 T1 T3.\nProof.\n  introv Hi Hte Hz He1 He2 Hk1 Hk2 Hk3.\n  destruct Hte; invert_covariant_inv; subst;\n    construct_covariant_inv; solve_covariant_inv_side_conditions.\n  - invert_kindings_cov.\n    construct_covariant_inv; solve_covariant_inv_side_conditions.\n  - invert_kindings_cov.\n    construct_covariant_inv; solve_covariant_inv_side_conditions.\n  - invert_kindings_cov.\n    construct_covariant_inv; solve_covariant_inv_side_conditions.\n  - invert_kindings_cov.\n    construct_covariant_inv; solve_covariant_inv_side_conditions.\n  - apply covariant_inv_join\n      with (s1 := s) (s2 := false)\n           (T2 := T1) (T3 := typ_bot (cov_input_kind z));\n      construct_covariant_inv;\n      solve_covariant_inv_side_conditions.\n    rewrite type_equal_join_identity\n      by auto with kinding wellformed.\n    treflexivity.\n  - subst_equal T1.\n    rewrite type_equal_join_commutative by auto with kinding.\n    treflexivity.\n  - subst_equal T4.\n    rewrite type_equal_join_commutative by auto with kinding.\n    rewrite type_equal_join_identity by auto with kinding.\n    subst_equal T1.\n    subst_equal T4.\n    treflexivity.\n  - subst_equal T1.\n    subst_equal T4.\n    rewrite type_equal_join_associative by auto with kinding.\n    treflexivity.\n  - invert_kindings_cov.\n    construct_covariant_inv; solve_covariant_inv_side_conditions.\n    rewrite type_equal_join_identity\n      by auto with kinding wellformed.\n    treflexivity.\n  - apply covariant_inv_join\n      with (s1 := s) (s2 := false)\n           (T2 := T1) (T3 := typ_bot (cov_input_kind z));\n      construct_covariant_inv;\n      solve_covariant_inv_side_conditions.\n    rewrite type_equal_join_identity\n      by auto with kinding wellformed.\n    treflexivity.\n  - apply covariant_inv_bot.\n    subst_equal T1.\n    rewrite type_equal_meet_annihilation_l\n      by auto with kinding wellformed.\n    treflexivity.\n  - rewrite type_equal_join_distribution\n      by auto with kinding.\n    subst_equal <- T1.\n    subst_equal T1 at 3.\n    rewrite type_equal_meet_annihilation_r\n      by auto with kinding wellformed.\n    subst_equal T1.\n    treflexivity.\n  - rewrite <- type_equal_join_associative\n      by auto with kinding.\n    rewrite type_equal_join_distribution\n      by auto with kinding.\n    subst_equal <- T1.\n    rewrite type_equal_join_distribution\n      by auto with kinding.\n    rewrite type_equal_join_commutative\n      with (T1 := T6) (T2 := T5)\n      by auto with kinding.\n    rewrite type_equal_join_associative\n      by auto with kinding.\n    subst_equal <- T1.\n    rewrite H2 at 2.\n    rewrite type_equal_join_associative\n      by auto with kinding.\n    rewrite <- type_equal_join_idempotent\n      by auto with kinding wellformed.\n    subst_equal <- T1.\n    rewrite type_equal_meet_absorption\n      by auto with kinding.\n    invert_kindings_cov.\n    treflexivity.\n  - invert_kindings_cov.\n    easy.\nQed.\n\nLemma type_equal_covariant_inv' :\n  forall z s v E1 E2 E3 Q2 T1 T2 T3,\n    type_equal v E1 (E2 & E3) nil Q2 T2 T3 (cov_output_kind z) ->\n    type_equal_eqn_subs v E1 (E2 & E3) Q2 ->\n    kinding (E1 & E2 & E3) empty T1 (cov_input_kind z) ->\n    kinding (E1 & E2) E3 T2 (cov_output_kind z) ->\n    kinding (E1 & E2) E3 T3 (cov_output_kind z) ->\n    valid_covariant_context z ->\n    valid_tenv v (E1 & E2) ->\n    valid_tenv_extension v (E1 & E2) E3 ->\n    (forall z s X T4 T5 T6,\n        binds X (Rng T5 T6 (cov_output_kind z)) E1 ->\n        valid_covariant_context z ->\n        kinding (E1 & E2 & E3) empty T4 (cov_input_kind z) ->\n        covariant_inv z s v (E1 & E2) E3 T4 T5 ->\n        covariant_inv z s v (E1 & E2) E3 T4 T6) ->\n    covariant_inv z s v (E1 & E2) E3 T1 T2 <->\n    covariant_inv z s v (E1 & E2) E3 T1 T3.\nProof.\n  introv Hte Hes Hk1 Hk2 Hk3 Hz He1 He2 Hb.\n  remember (cov_output_kind z) as K.\n  remember (E2 & E3) as E23.\n  remember Hte as Hte2 eqn:Heq.\n  clear Heq.\n  remember nil as Q1 in Hte at 1.\n  generalize dependent z.\n  generalize dependent s.\n  generalize dependent T1.\n  induction Hte; introv Heq Hk1 Hz; subst;\n    autorewrite with rew_env_concat in *;\n    split; introv Hi; invert_covariant_inv; subst;\n      construct_covariant_inv;\n      unroll_recursive_eqns;\n      solve_covariant_inv_side_conditions.\n  - apply binds_tenv_weakening_l; auto with wellformed.\n  - apply binds_tenv_weakening_l; auto with wellformed.\n  - eauto.\n  - apply binds_tenv_weakening_l; auto with wellformed.\n  - rewrite <- IHHte1;\n      auto using type_equal_eqn_subs_push\n        with kinding wellformed.\n  - rewrite <- IHHte2; \n      auto using type_equal_eqn_subs_push\n        with kinding wellformed.\n  - rewrite IHHte1; \n      auto using type_equal_eqn_subs_push\n        with kinding wellformed.\n  - rewrite IHHte2; \n      auto using type_equal_eqn_subs_push\n        with kinding wellformed.\n  - rewrite <- IHHte\n      by (auto using type_equal_eqn_subs_push with wellformed;\n          invert_kindings_cov;\n          auto with kinding); auto.\n  - rewrite IHHte\n      by (auto using type_equal_eqn_subs_push with wellformed;\n          invert_kindings_cov;\n          auto with kinding); auto.\n  - rewrite <- IHHte1;\n      auto using type_equal_eqn_subs_push\n        with kinding wellformed.\n  - rewrite <- IHHte2;\n      auto using type_equal_eqn_subs_push\n        with kinding wellformed.\n  - rewrite IHHte1;\n      auto using type_equal_eqn_subs_push\n        with kinding wellformed.\n  - rewrite IHHte2;\n      auto using type_equal_eqn_subs_push\n        with kinding wellformed.\n  - apply covariant_inv_join\n      with (s1 := s2) (s2 := s3) (T2 := T4) (T3 := T5);\n      solve_covariant_inv_side_conditions; auto.\n    + rewrite <- IHHte1;\n        auto using type_equal_eqn_subs_push\n          with kinding wellformed.\n    + rewrite <- IHHte2;\n        auto using type_equal_eqn_subs_push\n          with kinding wellformed.\n  - apply covariant_inv_join\n      with (s1 := s2) (s2 := s3) (T2 := T4) (T3 := T5);\n      solve_covariant_inv_side_conditions; auto.\n    + rewrite IHHte1;\n        auto using type_equal_eqn_subs_push\n          with kinding wellformed.\n    + rewrite IHHte2;\n        auto using type_equal_eqn_subs_push\n          with kinding wellformed.\n  - apply type_equal_core_covariant_inv_l with T1; auto.\n  - apply type_equal_core_covariant_inv_r with T1'; auto.\n  - rewrite IHHte;\n      auto using type_equal_eqn_subs_push\n        with wellformed.\n  - rewrite <- IHHte;\n      auto using type_equal_eqn_subs_push\n        with wellformed.\n  - apply type_equal_extend in Hte1 as Hte1';\n      auto using type_environment_extend_inv with wellformed.\n    rewrite <- IHHte2;\n      auto using type_equal_eqn_subs_push\n        with kinding wellformed.\n    rewrite <- IHHte1;\n      auto using type_equal_eqn_subs_push\n        with kinding wellformed.\n  - apply type_equal_extend in Hte1 as Hte1';\n      auto using type_environment_extend_inv with wellformed.\n    rewrite IHHte1;\n      auto using type_equal_eqn_subs_push\n        with kinding wellformed.\n    rewrite IHHte2;\n      auto using type_equal_eqn_subs_push\n        with kinding wellformed.\nQed.\n\nLemma subtype_covariant_inv' : forall z s v E1 E2 E3 T1 T2 T3,\n    subtype v E1 (E2 & E3) nil nil T2 T3 (cov_output_kind z) ->\n    kinding (E1 & E2 & E3) empty T1 (cov_input_kind z) ->\n    kinding (E1 & E2) E3 T2 (cov_output_kind z) ->\n    kinding (E1 & E2) E3 T3 (cov_output_kind z) ->\n    valid_covariant_context z ->\n    valid_tenv v (E1 & E2)->\n    valid_tenv_extension v (E1 & E2) E3 ->\n    (forall z s X T4 T5 T6,\n        binds X (Rng T5 T6 (cov_output_kind z)) E1 ->\n        valid_covariant_context z ->\n        kinding (E1 & E2 & E3) empty T4 (cov_input_kind z) ->\n        covariant_inv z s v (E1 & E2) E3 T4 T5 ->\n        covariant_inv z s v (E1 & E2) E3 T4 T6) ->\n    covariant_inv z s v (E1 & E2) E3 T1 T2 ->\n    covariant_inv z s v (E1 & E2) E3 T1 T3.\nProof.\n  introv Hs Hk1 Hk2 Hk3 Hz He1 He2 Hb Hi.\n  unfold subtype in Hs.\n  assert (covariant_inv z s v (E1 & E2) E3\n            T1 (typ_meet T2 T3)) as Hi2\n    by (rewrite type_equal_covariant_inv' with (T3 := T2);\n        try symmetry; auto).\n  inversion Hi2; subst; auto.\nQed.\n\nLemma valid_tenv_rec_covariant_inv : forall v E1 E2 E3,\n    valid_tenv_rec v empty E1 (E2 & E3) ->\n    valid_tenv v (E1 & E2) ->\n    valid_tenv_extension v (E1 & E2) E3 ->\n    (forall z s X T1 T2 T3,\n        binds X (Rng T2 T3 (cov_output_kind z)) E1 ->\n        valid_covariant_context z ->\n        kinding (E1 & E2 & E3) empty T1 (cov_input_kind z) ->\n        covariant_inv z s v (E1 & E2) E3 T1 T2 ->\n        covariant_inv z s v (E1 & E2) E3 T1 T3).\nProof.\n  introv He1 He2 He3.\n  remember empty as E0.\n  remember (E2 & E3) as E23.\n  generalize dependent E2.\n  induction He1; introv Heq He2 He3 Hb Hz Hk Hi; subst.\n  - exfalso; eauto using binds_empty_inv.\n  - destruct (binds_push_inv Hb) as [[? ?]|[Hx Hbnd2]]; subst;\n      autorewrite with rew_env_concat in *.\n    + assert (valid_range v E2\n                (X ~ Rng T2 T3 (cov_output_kind z) & E4 & E3)\n                (Rng T2 T3 (cov_output_kind z))) as Hr by auto.\n      inversion Hr; subst.\n      rewrite <- concat_assoc with (E := E2).\n      apply subtype_covariant_inv' with T2;\n        try solve [autorewrite with rew_env_concat; eauto];\n        try solve\n            [apply kinding_extend; auto;\n             apply type_environment_extend_inv;\n               autorewrite with rew_env_concat;\n               auto with wellformed].\n      apply IHHe1; autorewrite with rew_env_concat; auto.\n    + rewrite <- concat_assoc with (E := E2).\n      eapply IHHe1; autorewrite with rew_env_concat; eauto.\nQed.\n\nLemma type_equal_covariant_inv :\n  forall z s v E1 E2 T1 T2 T3,\n    type_equal v E1 E2 nil nil T2 T3 (cov_output_kind z) ->\n    kinding (E1 & E2) empty T1 (cov_input_kind z) ->\n    valid_covariant_context z ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    covariant_inv z s v E1 E2 T1 T2 <->\n    covariant_inv z s v E1 E2 T1 T3.\nProof.\n  introv Hte Hk Hz He1 He2.\n  replace E1 with (E1 & empty) by apply concat_empty_r.\n  apply type_equal_covariant_inv' with (Q2 := nil);\n    autorewrite with rew_env_concat; auto with kinding.\n  introv Hb' Hz' Hk' Hi'.\n  rewrite <- concat_empty_r with (E := E1).\n  eapply valid_tenv_rec_covariant_inv;\n    autorewrite with rew_env_concat; eauto.\n  rewrite <- concat_empty_r with (E := E2).\n  apply valid_tenv_rec_weakening_rec_r;\n    autorewrite with rew_env_concat;\n    try fold (type_environment E1);\n    auto with wellformed.\nQed.\n\nLemma subtype_covariant_inv :\n  forall z s v E1 E2 T1 T2 T3,\n    subtype v E1 E2 nil nil T2 T3 (cov_output_kind z) ->\n    kinding (E1 & E2) empty T1 (cov_input_kind z) ->\n    valid_covariant_context z ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    covariant_inv z s v E1 E2 T1 T2 ->\n    covariant_inv z s v E1 E2 T1 T3.\nProof.\n  introv Hs Hk Hz He1 He2 Hi.\n  unfold subtype in Hs.\n  assert (covariant_inv z s v E1 E2 T1 (typ_meet T2 T3)) as Hi2\n    by (rewrite type_equal_covariant_inv with (T3 := T2);\n        try symmetry; auto).\n  inversion Hi2; subst; auto.\nQed.\n\nLemma invert_subtype_variant : forall v E1 E2 T1 T2,\n    subtype v E1 E2 nil nil\n      (typ_variant T1) (typ_variant T2) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    subtype v (E1 & E2) empty nil nil T1 T2 knd_row_all.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_variant true v E1 E2 T1 (typ_variant T1))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_variant true v E1 E2 T1 (typ_variant T2))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi; subst; auto.\nQed.\n\nLemma invert_subtype_arrow_left_row_covariant : forall E1 E2 T1 T2 T3 T4,\n    subtype version_row_subtyping E1 E2 nil nil\n      (typ_arrow T1 T2) (typ_arrow T3 T4) knd_type ->\n    valid_tenv version_row_subtyping E1 ->\n    valid_tenv_extension version_row_subtyping E1 E2 ->\n    subtype version_row_subtyping (E1 & E2) empty nil nil\n      T1 T3 knd_type.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_arrow_left_row true version_row_subtyping\n            E1 E2 T1 (typ_arrow T1 T2))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_arrow_left_row true version_row_subtyping\n            E1 E2 T1 (typ_arrow T3 T4))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi; subst; auto.\nQed.\n\nLemma invert_subtype_arrow_right : forall v E1 E2 T1 T2 T3 T4,\n    subtype v E1 E2 nil nil\n      (typ_arrow T1 T2) (typ_arrow T3 T4) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    subtype v (E1 & E2) empty nil nil T2 T4 knd_type.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_arrow_right true v E1 E2\n                      T2 (typ_arrow T1 T2))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_arrow_right true v E1 E2\n                      T2 (typ_arrow T3 T4))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi; subst; auto.\nQed.\n\nLemma invert_subtype_ref_covariant : forall v E1 E2 T1 T2,\n    subtype v E1 E2 nil nil (typ_ref T1) (typ_ref T2) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    subtype v (E1 & E2) empty nil nil T1 T2 knd_type.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_ref_co true v E1 E2 T1 (typ_ref T1))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_ref_co true v E1 E2 T1 (typ_ref T2))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi; subst; auto.\nQed.\n\nLemma invert_subtype_prod_left : forall v E1 E2 T1 T2 T3 T4,\n    subtype v E1 E2 nil nil\n      (typ_prod T1 T2) (typ_prod T3 T4) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    subtype v (E1 & E2) empty nil nil T1 T3 knd_type.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_prod_left true v E1 E2\n                      T1 (typ_prod T1 T2))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_prod_left true v E1 E2\n                      T1 (typ_prod T3 T4))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi; subst; auto.\nQed.\n\nLemma invert_subtype_prod_right : forall v E1 E2 T1 T2 T3 T4,\n    subtype v E1 E2 nil nil\n      (typ_prod T1 T2) (typ_prod T3 T4) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    subtype v (E1 & E2) empty nil nil T2 T4 knd_type.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_prod_right true v E1 E2\n                      T2 (typ_prod T1 T2))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_prod_right true v E1 E2\n                      T2 (typ_prod T3 T4))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi; subst; auto.\nQed.\n\nLemma invert_subtype_constructor : forall v c cs E1 E2 T1 T2,\n    subtype v E1 E2 nil nil (typ_constructor c T1)\n      (typ_constructor c T2) (knd_row cs)->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    subtype v (E1 & E2) empty nil nil T1 T2 knd_type.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv (ctx_constructor c cs) true v E1 E2\n            T1 (typ_constructor c T1))\n    by auto using subtype_refl with kinding wellformed.\n  assert (kinding E1 E2 (typ_constructor c T1) (knd_row cs)) as Hk\n      by auto with kinding.\n  inversion Hk; subst.\n  assert (covariant_inv (ctx_constructor c (CSet.singleton c))\n            true v E1 E2 T1 (typ_constructor c T2))\n    as Hi by eauto using subtype_covariant_inv with kinding csetdec.\n  inversion Hi; subst; auto.\nQed.\n\n(* *************************************************************** *)\n(** Impossible subtyping inversions *)\n\nLemma invert_subtype_variant_arrow : forall v E1 E2 T1 T2 T3,\n    subtype v E1 E2 nil nil\n      (typ_variant T1) (typ_arrow T2 T3) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_variant true v E1 E2 T1 (typ_variant T1))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_variant true v E1 E2 T1 (typ_arrow T2 T3))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_variant_ref : forall v E1 E2 T1 T2,\n    subtype v E1 E2 nil nil\n      (typ_variant T1) (typ_ref T2) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_variant true v E1 E2 T1 (typ_variant T1))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_variant true v E1 E2 T1 (typ_ref T2))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_variant_unit : forall v E1 E2 T1,\n    subtype v E1 E2 nil nil\n      (typ_variant T1) typ_unit knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_variant true v E1 E2 T1 (typ_variant T1))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_variant true v E1 E2 T1 typ_unit)\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_variant_prod : forall v E1 E2 T1 T2 T3,\n    subtype v E1 E2  nil nil\n      (typ_variant T1) (typ_prod T2 T3) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_variant true v E1 E2 T1 (typ_variant T1))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_variant true v E1 E2 T1 (typ_prod T2 T3))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_variant_bot : forall v E1 E2 T1,\n    subtype v E1 E2 nil nil (typ_variant T1) (typ_bot knd_type) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_variant true v E1 E2 T1 (typ_variant T1))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_variant true v E1 E2 T1 (typ_bot knd_type))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_arrow_variant : forall v E1 E2 T1 T2 T3,\n    subtype v E1 E2 nil nil (typ_arrow T1 T2) (typ_variant T3) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_arrow_right true v E1 E2\n                      T2 (typ_arrow T1 T2))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_arrow_right true v E1 E2\n                        T2 (typ_variant T3))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_arrow_ref : forall v E1 E2 T1 T2 T3,\n    subtype v E1 E2 nil nil (typ_arrow T1 T2) (typ_ref T3) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_arrow_right true v E1 E2\n                      T2 (typ_arrow T1 T2))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_arrow_right true v E1 E2\n                        T2 (typ_ref T3))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_arrow_unit : forall v E1 E2 T1 T2,\n    subtype v E1 E2 nil nil (typ_arrow T1 T2) typ_unit knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_arrow_right true v E1 E2\n                      T2 (typ_arrow T1 T2))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_arrow_right true v E1 E2\n                        T2 typ_unit)\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_arrow_prod : forall v E1 E2 T1 T2 T3 T4,\n    subtype v E1 E2 nil nil (typ_arrow T1 T2) (typ_prod T3 T4) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_arrow_right true v E1 E2\n                      T2 (typ_arrow T1 T2))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_arrow_right true v E1 E2\n                        T2 (typ_prod T3 T4))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_arrow_bot : forall v E1 E2 T1 T2,\n    subtype v E1 E2 nil nil (typ_arrow T1 T2) (typ_bot knd_type) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_arrow_right true v E1 E2\n                      T2 (typ_arrow T1 T2))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_arrow_right true v E1 E2\n                        T2 (typ_bot knd_type))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_ref_variant : forall v E1 E2 T1 T2,\n    subtype v E1 E2 nil nil (typ_ref T1) (typ_variant T2) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_ref_co true v E1 E2 T1 (typ_ref T1))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_ref_co true v E1 E2 T1 (typ_variant T2))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_ref_arrow : forall v E1 E2 T1 T2 T3,\n    subtype v E1 E2 nil nil (typ_ref T1) (typ_arrow T2 T3) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_ref_co true v E1 E2 T1 (typ_ref T1))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_ref_co true v E1 E2 T1 (typ_arrow T2 T3))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_ref_unit : forall v E1 E2 T1,\n    subtype v E1 E2 nil nil (typ_ref T1) typ_unit knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_ref_co true v E1 E2 T1 (typ_ref T1))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_ref_co true v E1 E2 T1 typ_unit)\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_ref_prod : forall v E1 E2 T1 T2 T3,\n    subtype v E1 E2 nil nil (typ_ref T1) (typ_prod T2 T3) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_ref_co true v E1 E2 T1 (typ_ref T1))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_ref_co true v E1 E2 T1 (typ_prod T2 T3))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_ref_bot : forall v E1 E2 T1,\n    subtype v E1 E2 nil nil (typ_ref T1) (typ_bot knd_type) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_ref_co true v E1 E2 T1 (typ_ref T1))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_ref_co true v E1 E2 T1 (typ_bot knd_type))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_unit_variant : forall v E1 E2 T1,\n    subtype v E1 E2 nil nil typ_unit (typ_variant T1) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_unit true v E1 E2 typ_unit typ_unit)\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_unit true v E1 E2\n                        typ_unit (typ_variant T1))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_unit_arrow : forall v E1 E2 T1 T2,\n    subtype v E1 E2 nil nil typ_unit (typ_arrow T1 T2) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_unit true v E1 E2 typ_unit typ_unit)\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_unit true v E1 E2\n                        typ_unit (typ_arrow T1 T2))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_unit_ref : forall v E1 E2 T1,\n    subtype v E1 E2 nil nil typ_unit (typ_ref T1) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_unit true v E1 E2 typ_unit typ_unit)\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_unit true v E1 E2 typ_unit (typ_ref T1))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_unit_prod : forall v E1 E2 T1 T2,\n    subtype v E1 E2 nil nil typ_unit (typ_prod T1 T2) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_unit true v E1 E2 typ_unit typ_unit)\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_unit true v E1 E2\n                        typ_unit (typ_prod T1 T2))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_unit_bot : forall v E1 E2,\n    subtype v E1 E2 nil nil typ_unit (typ_bot knd_type) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_unit true v E1 E2 typ_unit typ_unit)\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_unit true v E1 E2\n                        typ_unit (typ_bot knd_type))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_prod_variant : forall v E1 E2 T1 T2 T3,\n    subtype v E1 E2 nil nil (typ_prod T1 T2) (typ_variant T3) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_prod_left true v E1 E2\n                      T1 (typ_prod T1 T2))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_prod_left true v E1 E2\n                      T1 (typ_variant T3))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_prod_arrow : forall v E1 E2 T1 T2 T3 T4,\n    subtype v E1 E2 nil nil (typ_prod T1 T2) (typ_arrow T3 T4) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_prod_left true v E1 E2\n                      T1 (typ_prod T1 T2))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_prod_left true v E1 E2\n                      T1 (typ_arrow T3 T4))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_prod_ref : forall v E1 E2 T1 T2 T3,\n    subtype v E1 E2 nil nil (typ_prod T1 T2) (typ_ref T3) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_prod_left true v E1 E2\n                      T1 (typ_prod T1 T2))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_prod_left true v E1 E2\n                      T1 (typ_ref T3))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_prod_unit : forall v E1 E2 T1 T2,\n    subtype v E1 E2 nil nil (typ_prod T1 T2) typ_unit knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_prod_left true v E1 E2\n                      T1 (typ_prod T1 T2))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_prod_left true v E1 E2\n                      T1 typ_unit)\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_prod_bot : forall v E1 E2 T1 T2,\n    subtype v E1 E2 nil nil (typ_prod T1 T2) (typ_bot knd_type) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_prod_left true v E1 E2\n                      T1 (typ_prod T1 T2))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_prod_left true v E1 E2\n                      T1 (typ_bot knd_type))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_constructor_bot : forall v c cs E1 E2 T1,\n    subtype v E1 E2 nil nil (typ_constructor c T1)\n      (typ_bot (knd_row cs)) (knd_row cs) ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv (ctx_constructor c cs) true v\n            E1 E2 T1 (typ_constructor c T1))\n    by auto using subtype_refl with kinding wellformed.\n  assert (kinding E1 E2 (typ_constructor c T1) (knd_row cs)) as Hk\n      by auto with kinding.\n  inversion Hk; subst.\n  assert (covariant_inv (ctx_constructor c (CSet.singleton c))\n             true v E1 E2 T1 (typ_bot (knd_row (CSet.singleton c))))\n    as Hi by eauto using subtype_covariant_inv with kinding csetdec.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_top_variant : forall v E1 E2 T1,\n    subtype v E1 E2 nil nil (typ_top knd_type) (typ_variant T1) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_unit true v E1 E2\n                      typ_unit (typ_top knd_type))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_unit true v E1 E2\n                      typ_unit (typ_variant T1))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_top_arrow : forall v E1 E2 T1 T2,\n    subtype v E1 E2 nil nil (typ_top knd_type) (typ_arrow T1 T2) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_unit true v E1 E2\n                      typ_unit (typ_top knd_type))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_unit true v E1 E2\n                      typ_unit (typ_arrow T1 T2))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_top_ref : forall v E1 E2 T1,\n    subtype v E1 E2 nil nil (typ_top knd_type) (typ_ref T1) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_unit true v E1 E2\n                      typ_unit (typ_top knd_type))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_unit true v E1 E2\n                      typ_unit (typ_ref T1))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_top_unit : forall v E1 E2,\n    subtype v E1 E2 nil nil (typ_top knd_type) typ_unit knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_ref_co true v E1 E2\n                      typ_unit (typ_top knd_type))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_ref_co true v E1 E2\n                      typ_unit typ_unit)\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_top_prod : forall v E1 E2 T1 T2,\n    subtype v E1 E2 nil nil (typ_top knd_type) (typ_prod T1 T2) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  assert (covariant_inv ctx_unit true v E1 E2\n                      typ_unit (typ_top knd_type))\n    by auto using subtype_refl with kinding wellformed.\n  assert (covariant_inv ctx_unit true v E1 E2\n                      typ_unit (typ_prod T1 T2))\n    as Hi by eauto using subtype_covariant_inv with kinding.\n  inversion Hi.\nQed.\n\nLemma invert_subtype_top_bot : forall v E1 E2 K,\n    subtype v E1 E2 nil nil (typ_top K) (typ_bot K) K ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    False.\nProof.\n  introv Hs He1 He2.\n  destruct K as [| cs].\n  - assert (covariant_inv ctx_unit true v E1 E2\n                      typ_unit (typ_top knd_type))\n      by auto using subtype_refl with kinding wellformed.\n    assert (covariant_inv ctx_unit true v E1 E2\n                      typ_unit (typ_bot knd_type))\n      as Hi by eauto using subtype_covariant_inv with kinding.\n    inversion Hi.\n  - assert (kind (knd_row cs)) as Hknd by auto with wellformed.\n    inversion Hknd; subst.\n    assert (CSet.Nonempty cs) as Hne by assumption.\n    destruct Hne as [c ?].\n    assert (covariant_inv (ctx_constructor c cs) true v E1 E2\n                      typ_unit (typ_top (knd_row cs)))\n      by auto using subtype_refl with kinding wellformed.\n    assert (covariant_inv (ctx_constructor c cs) true v E1 E2\n                      typ_unit (typ_bot (knd_row cs)))\n      as Hi by eauto using subtype_covariant_inv with kinding.\n    inversion Hi.\nQed.\n\n(* *************************************************************** *)\n(** Contravariant subtyping inversions *)\n\n(* Type representing contravariant (and invariant) contexts *)\nInductive contravariant_context : Type :=\n  | ctx_arrow_left : contravariant_context\n  | ctx_arrow_right_row : contravariant_context\n  | ctx_ref_contra : contravariant_context\n  | ctx_prod_left_row : contravariant_context\n  | ctx_prod_right_row : contravariant_context\n  | ctx_constructor_row : nat -> cset -> contravariant_context.\n  \nDefinition con_input_kind z :=\n  match z with\n  | ctx_arrow_left => knd_type\n  | ctx_arrow_right_row => knd_type\n  | ctx_ref_contra => knd_type\n  | ctx_prod_left_row => knd_type\n  | ctx_prod_right_row => knd_type\n  | ctx_constructor_row _ _ => knd_type\n  end.\n\nDefinition con_output_kind z :=\n  match z with\n  | ctx_arrow_left => knd_type\n  | ctx_arrow_right_row => knd_type\n  | ctx_ref_contra => knd_type\n  | ctx_prod_left_row => knd_type\n  | ctx_prod_right_row => knd_type\n  | ctx_constructor_row _ cs => knd_row cs\n  end.\n\nInductive valid_contravariant_context : contravariant_context -> Prop :=\n  | valid_ctx_arrow_left :\n      valid_contravariant_context ctx_arrow_left\n  | valid_ctx_arrow_right_row :\n      valid_contravariant_context ctx_arrow_right_row\n  | valid_ctx_ref_contra : valid_contravariant_context ctx_ref_contra\n  | valid_ctx_prod_left_row :\n      valid_contravariant_context ctx_prod_left_row\n  | valid_ctx_prod_right_row :\n      valid_contravariant_context ctx_prod_right_row\n  | valid_ctx_constructor_row : forall c cs,\n      CSet.In c cs ->\n      valid_contravariant_context (ctx_constructor_row c cs).\n\nHint Constructors valid_contravariant_context.\n\nInductive contravariant_inv :\n  contravariant_context -> bool -> version -> tenv -> tenv ->\n  typ -> typ -> Prop :=\n  | contravariant_inv_meet : forall z s v E1 E2 T1 T2 T3,\n      contravariant_inv z s v E1 E2 T1 T2 ->\n      contravariant_inv z s v E1 E2 T1 T3 ->\n      contravariant_inv z s v E1 E2 T1 (typ_meet T2 T3)\n  | contravariant_inv_join : forall z s1 s2 s3 v E1 E2 T1 T2 T3 T4 T5,\n      contravariant_inv z s1 v E1 E2 T2 T4 ->\n      contravariant_inv z s2 v E1 E2 T3 T5 ->\n      type_equal v (E1 & E2) empty nil nil T1\n                 (typ_meet T2 T3) (con_input_kind z) ->\n      s3 = orb s1 s2 ->\n      contravariant_inv z s3 v E1 E2 T1 (typ_join T4 T5)\n  | contravariant_inv_top : forall z s v E1 E2 K2 T1,\n      contravariant_inv z s v E1 E2 T1 (typ_top K2)\n  | contravariant_inv_var : forall z s v E1 E2 X T1 T2 T3,\n      binds X (Rng T2 T3 (con_output_kind z)) E1 ->\n      contravariant_inv z s v E1 E2 T1 T2 ->\n      contravariant_inv z s v E1 E2 T1 (typ_fvar X)\n  | contravariant_inv_arrow_left : forall s v E1 E2 T1 T2 T3,\n      subtype v (E1 & E2) empty nil nil T2 T1 knd_type ->\n      contravariant_inv ctx_arrow_left s v\n        E1 E2 T1 (typ_arrow T2 T3)\n  | contravariant_inv_arrow_right : forall s E1 E2 T1 T2 T3,\n      subtype version_row_subtyping (E1 & E2) empty nil nil\n        T3 T1 knd_type ->\n      contravariant_inv ctx_arrow_right_row s version_row_subtyping\n        E1 E2 T1 (typ_arrow T2 T3)\n  | contravariant_inv_ref : forall s v E1 E2 T1 T2,\n      subtype v (E1 & E2) empty nil nil T2 T1 knd_type ->\n      contravariant_inv ctx_ref_contra s v E1 E2 T1 (typ_ref T2)\n  | contravariant_inv_prod_left : forall s E1 E2 T1 T2 T3,\n      subtype version_row_subtyping (E1 & E2) empty nil nil\n        T2 T1 knd_type ->\n      contravariant_inv ctx_prod_left_row s version_row_subtyping\n        E1 E2 T1 (typ_prod T2 T3)\n  | contravariant_inv_prod_right : forall s E1 E2 T1 T2 T3,\n      subtype version_row_subtyping (E1 & E2) empty nil nil\n        T3 T1 knd_type ->\n      contravariant_inv ctx_prod_right_row s version_row_subtyping\n        E1 E2 T1 (typ_prod T2 T3)\n  | contravariant_inv_or_l : forall c s v E1 E2 cs1 cs2 cs3 T1 T2 T3,\n      contravariant_inv (ctx_constructor_row c cs1) s v E1 E2 T1 T2 ->\n      CSet.In c cs1 ->\n      contravariant_inv (ctx_constructor_row c cs3) s\n        v E1 E2 T1 (typ_or cs1 cs2 T2 T3)\n  | contravariant_inv_or_r : forall c s v E1 E2 cs1 cs2 cs3 T1 T2 T3,\n      contravariant_inv (ctx_constructor_row c cs2) s v E1 E2 T1 T3 ->\n      CSet.In c cs2 ->\n      contravariant_inv (ctx_constructor_row c cs3) s\n        v E1 E2 T1 (typ_or cs1 cs2 T2 T3)\n  | contravariant_inv_proj : forall c s v E1 E2 cs1 cs2 T1 T2,\n      contravariant_inv (ctx_constructor_row c cs1) s v E1 E2 T1 T2 ->\n      contravariant_inv (ctx_constructor_row c cs2) s\n        v E1 E2 T1 (typ_proj cs1 cs2 T2)\n  | contravariant_inv_constructor : forall c cs s E1 E2 T1 T2,\n      subtype version_row_subtyping (E1 & E2) empty nil nil\n        T2 T1 knd_type ->\n      contravariant_inv (ctx_constructor_row c cs) s\n        version_row_subtyping E1 E2 T1 (typ_constructor c T2)\n  | contravariant_inv_mu : forall z s v E1 E2 T1 T2 K,\n      contravariant_inv z s v E1 E2 T1\n        (typ_open T2 ((typ_mu K T2) :: nil)) ->\n      K = con_output_kind z ->\n      contravariant_inv z s v E1 E2 T1 (typ_mu K T2)\n  | contravariant_inv_bot : forall z v E1 E2 T1 T2,\n      type_equal v (E1 & E2) empty nil nil\n        T1 (typ_top (con_input_kind z)) (con_input_kind z) ->\n      contravariant_inv z false v E1 E2 T1 T2.\n\nHint Constructors contravariant_inv.\n\nLemma contravariant_inv_meet_inv :\n  forall z s v E1 E2 T1 T2 T3 (P : Prop),\n    contravariant_inv z s v E1 E2 T1 (typ_meet T2 T3) ->\n    (s = false ->\n     type_equal v (E1 & E2) empty nil nil T1\n       (typ_top (con_input_kind z)) (con_input_kind z) ->\n     P) ->\n    (contravariant_inv z s v E1 E2 T1 T2 ->\n     contravariant_inv z s v E1 E2 T1 T3 ->\n     P) ->\n    P.\nProof.\n  introv Hc Hp1 Hp2.\n  inversion Hc; auto.\nQed.\n\nLemma contravariant_inv_join_inv :\n  forall z s1 v E1 E2 T1 T2 T3 (P : Prop),\n    contravariant_inv z s1 v E1 E2 T1 (typ_join T2 T3) ->\n    (s1 = false ->\n     type_equal v (E1 & E2) empty nil nil T1\n       (typ_top (con_input_kind z)) (con_input_kind z) ->\n     P) ->\n    (forall s2 s3 T4 T5,\n        contravariant_inv z s2 v E1 E2 T4 T2 ->\n        contravariant_inv z s3 v E1 E2 T5 T3 ->\n        type_equal v (E1 & E2) empty nil nil T1\n                   (typ_meet T4 T5) (con_input_kind z) ->\n        s1 = orb s2 s3 ->\n        P) ->\n    P.\nProof.\n  introv Hc Hp1 Hp2.\n  inversion Hc; eauto.\nQed.\n\nLemma contravariant_inv_var_inv : forall z s v E1 E2 X T1 (P : Prop),\n    contravariant_inv z s v E1 E2 T1 (typ_fvar X) ->\n    (s = false ->\n     type_equal v (E1 & E2) empty nil nil T1\n       (typ_top (con_input_kind z)) (con_input_kind z) ->\n     P) ->\n    (forall T2 T3,\n        binds X (Rng T2 T3 (con_output_kind z)) E1 ->\n        contravariant_inv z s v E1 E2 T1 T2 ->\n        P) ->\n    P.\nProof.\n  introv Hc Hp1 Hp2.\n  inversion Hc; eauto.\nQed.\n\nLemma contravariant_inv_variant_inv : forall z s v E1 E2 T1 T2 (P : Prop),\n    contravariant_inv z s v E1 E2 T1 (typ_variant T2) ->\n    (s = false ->\n     type_equal v (E1 & E2) empty nil nil T1\n       (typ_top (con_input_kind z)) (con_input_kind z) ->\n     P) ->\n    P.\nProof.\n  introv Hc Hp.\n  inversion Hc; auto.\nQed.\n\nLemma contravariant_inv_arrow_inv : forall z s v E1 E2 T1 T2 T3 (P : Prop),\n    contravariant_inv z s v E1 E2 T1 (typ_arrow T2 T3) ->\n    (s = false ->\n     type_equal v (E1 & E2) empty nil nil T1\n       (typ_top (con_input_kind z)) (con_input_kind z) ->\n     P) ->\n    (z = ctx_arrow_left ->\n     subtype v (E1 & E2) empty nil nil T2 T1 knd_type ->\n     P) ->\n    (z = ctx_arrow_right_row ->\n     v = version_row_subtyping ->\n     subtype v (E1 & E2) empty nil nil T3 T1 knd_type ->\n     P) ->\n    P.\nProof.\n  introv Hc Hp1 Hp2 Hp3.\n  inversion Hc; subst; auto.\nQed.\n\nLemma contravariant_inv_ref_inv : forall z s v E1 E2 T1 T2 (P : Prop),\n    contravariant_inv z s v E1 E2 T1 (typ_ref T2) ->\n    (s = false ->\n     type_equal v (E1 & E2) empty nil nil T1\n       (typ_top (con_input_kind z)) (con_input_kind z) ->\n     P) ->\n    (z = ctx_ref_contra ->\n     subtype v (E1 & E2) empty nil nil T2 T1 knd_type ->\n     P) ->\n    P.\nProof.\n  introv Hc Hp1 Hp2.\n  inversion Hc; auto.\nQed.\n\nLemma contravariant_inv_prod_inv : forall z s v E1 E2 T1 T2 T3 (P : Prop),\n    contravariant_inv z s v E1 E2 T1 (typ_prod T2 T3) ->\n    (s = false ->\n     type_equal v (E1 & E2) empty nil nil T1\n       (typ_top (con_input_kind z)) (con_input_kind z) ->\n     P) ->\n    (z = ctx_prod_left_row ->\n     v = version_row_subtyping ->\n     subtype v (E1 & E2) empty nil nil T2 T1 knd_type ->\n     P) ->\n    (z = ctx_prod_right_row ->\n     v = version_row_subtyping ->\n     subtype v (E1 & E2) empty nil nil T3 T1 knd_type ->\n     P) ->\n    P.\nProof.\n  introv Hc Hp1 Hp2 Hp3.\n  inversion Hc; subst; auto.\nQed.\n\nLemma contravariant_inv_or_inv :\n  forall z s v E1 E2 cs1 cs2 T1 T2 T3 (P : Prop),\n    contravariant_inv z s v E1 E2 T1 (typ_or cs1 cs2 T2 T3) ->\n    (s = false ->\n     type_equal v (E1 & E2) empty nil nil T1\n       (typ_top (con_input_kind z)) (con_input_kind z) ->\n     P) ->\n    (forall c cs3,\n        z = ctx_constructor_row c cs3 ->\n        contravariant_inv (ctx_constructor_row c cs1) s v E1 E2 T1 T2 ->\n        CSet.In c cs1 ->\n        P) ->\n    (forall c cs3,\n        z = ctx_constructor_row c cs3 ->\n        contravariant_inv (ctx_constructor_row c cs2) s v E1 E2 T1 T3 ->\n        CSet.In c cs2 ->\n        P) ->\n    P.\nProof.\n  introv Hc Hp1 Hp2 Hp3.\n  inversion Hc; eauto.\nQed.\n\nLemma contravariant_inv_proj_inv :\n  forall z s v E1 E2 cs1 cs2 T1 T2 (P : Prop),\n    contravariant_inv z s v E1 E2 T1 (typ_proj cs1 cs2 T2) ->\n    (s = false ->\n     type_equal v (E1 & E2) empty nil nil T1\n       (typ_top (con_input_kind z)) (con_input_kind z) ->\n     P) ->\n    (forall c,\n        z = ctx_constructor_row c cs2 ->\n        contravariant_inv (ctx_constructor_row c cs1) s v E1 E2 T1 T2 ->\n        P) ->\n    P.\nProof.\n  introv Hc Hp1 Hp2.\n  inversion Hc; subst; eauto.  \nQed.\n\nLemma contravariant_inv_constructor_inv :\n  forall z s v E1 E2 c T1 T2 (P : Prop),\n    contravariant_inv z s v E1 E2 T1 (typ_constructor c T2) ->\n    (s = false ->\n     type_equal v (E1 & E2) empty nil nil T1\n       (typ_top (con_input_kind z)) (con_input_kind z) ->\n     P) ->\n    (forall cs,\n        z = ctx_constructor_row c cs ->\n        v = version_row_subtyping ->\n        subtype v (E1 & E2) empty nil nil T2 T1 knd_type ->\n        P) ->\n    P.\nProof.\n  introv Hc Hp1 Hp2.\n  inversion Hc; subst; eauto.\nQed.\n\nLemma contravariant_inv_mu_inv :\n  forall z s v E1 E2 T1 T2 K (P : Prop),\n    contravariant_inv z s v E1 E2 T1 (typ_mu K T2) ->\n    (s = false ->\n     type_equal v (E1 & E2) empty nil nil T1\n       (typ_top (con_input_kind z)) (con_input_kind z) ->\n     P) ->\n    (K = con_output_kind z ->\n     contravariant_inv z s v E1 E2 T1\n        (typ_open T2 ((typ_mu K T2) :: nil)) ->\n     P) ->\n    P.\nProof.\n  introv Hc Hp1 Hp2.\n  inversion Hc; subst; eauto.\nQed.\n\nLemma contravariant_inv_bot_inv :\n  forall z s v E1 E2 T1 K (P : Prop),\n    contravariant_inv z s v E1 E2 T1 (typ_bot K) ->\n    (s = false ->\n     type_equal v (E1 & E2) empty nil nil T1\n       (typ_top (con_input_kind z)) (con_input_kind z) ->\n     P) ->\n    P.\nProof.\n  introv Hc Hp1.\n  inversion Hc; subst; eauto.\nQed.\n\nLtac invert_ctx_constructor_row_equalities :=\n  repeat match goal with\n  | Heq : ctx_constructor_row _ _ = ctx_constructor_row _ _ |- _ =>\n    inversion Heq; clear Heq\n  end.\n\nLtac discriminate_ctx_prod_row_mismatches :=\n  try match goal with\n  | Heq : ctx_prod_left_row = ctx_prod_right_row |- _ =>\n    discriminate Heq\n  | Heq : ctx_prod_right_row = ctx_prod_left_row |- _ =>\n    discriminate Heq\n  end.\n\nLtac discriminate_con_ctx_arrow_mismatches :=\n  try match goal with\n  | Heq : ctx_arrow_left = ctx_arrow_right_row |- _ =>\n    discriminate Heq\n  | Heq : ctx_arrow_right_row = ctx_arrow_left |- _ =>\n    discriminate Heq\n  end.\n\nLtac invert_contravariant_inv :=\n  repeat match goal with\n  | H : contravariant_inv _ _ _ _ _ _ (typ_constructor _ _) |- _ =>\n    apply (contravariant_inv_constructor_inv H); clear H; intros;\n    invert_ctx_constructor_row_equalities; subst;\n    discriminate_version\n  | H : contravariant_inv _ _ _ _ _ _ (typ_or _ _ _ _) |- _ =>\n    apply (contravariant_inv_or_inv H); clear H; intros;\n    invert_ctx_constructor_row_equalities; subst\n  | H : contravariant_inv _ _ _ _ _ _ (typ_proj _ _ _) |- _ =>\n    apply (contravariant_inv_proj_inv H); clear H; intros;\n    invert_ctx_constructor_row_equalities; subst\n  | H : contravariant_inv _ _ _ _ _ _ (typ_variant _) |- _ =>\n    apply (contravariant_inv_variant_inv H); clear H; intros;\n    subst; discriminate_version\n  | H : contravariant_inv _ _ _ _ _ _ (typ_arrow _ _) |- _ =>\n    apply (contravariant_inv_arrow_inv H); clear H; intros;\n    subst; discriminate_con_ctx_arrow_mismatches;\n    discriminate_version\n  | H : contravariant_inv _ _ _ _ _ _ (typ_ref _) |- _ =>\n    apply (contravariant_inv_ref_inv H); clear H; intros\n  | H : contravariant_inv _ _ _ _ _ _ (typ_prod _ _) |- _ =>\n    apply (contravariant_inv_prod_inv H); clear H; intros;\n    subst; discriminate_ctx_prod_row_mismatches;\n    discriminate_version\n  | H : contravariant_inv _ _ _ _ _ _ (typ_mu _ _) |- _ =>\n    apply (contravariant_inv_mu_inv H); clear H; intros\n  | H : contravariant_inv _ _ _ _ _ _ (typ_fvar _) |- _ =>\n    apply (contravariant_inv_var_inv H); clear H; intros;\n    equate_multiple_bindings\n  | H : contravariant_inv _ _ _ _ _ _ (typ_bot _) |- _ =>\n    apply (contravariant_inv_bot_inv H); clear H; intros\n  | H : contravariant_inv _ _ _ _ _ _ (typ_meet _ _) |- _ =>\n    apply (contravariant_inv_meet_inv H); clear H; intros\n  | H : contravariant_inv _ _ _ _ _ _ (typ_join _ _) |- _ =>\n    apply (contravariant_inv_join_inv H); clear H; intros\n  end.\n\nLtac choose_contravariant_inv_join_type z Td T :=\n  match T with\n  | typ_meet ?T1 ?T2 =>\n    let T1' := choose_contravariant_inv_join_type z Td T1 in\n    let T2' := choose_contravariant_inv_join_type z Td T2 in\n    constr:(typ_join T1' T2')\n  | typ_join ?T1 ?T2 =>\n    let T1' := choose_contravariant_inv_join_type z Td T1 in\n    let T2' := choose_contravariant_inv_join_type z Td T2 in\n    constr:(typ_meet T1' T2')\n  | typ_or ?cs1 ?cs2 ?T1 ?T2 =>\n    match z with\n    | ctx_constructor_row ?c _ =>\n      match goal with\n      | Hin : CSet.In c cs1 |- _ =>\n        choose_contravariant_inv_join_type z Td T1\n      | Hin : CSet.In c cs2 |- _ =>\n        choose_contravariant_inv_join_type z Td T2\n      end\n    end\n  | typ_proj _ _ ?T1 =>\n    choose_contravariant_inv_join_type z Td T1\n  | typ_variant ?T1 => constr:(typ_join Td T1)\n  | typ_constructor _ ?T1 => constr:(typ_join Td T1)\n  | typ_ref ?T1 => constr:(typ_join Td T1)\n  | typ_arrow ?T1 ?T2 =>\n    match z with\n    | ctx_arrow_left => constr:(typ_join Td T1)\n    | ctx_arrow_right_row => constr:(typ_join Td T2)\n    end\n  | typ_prod ?T1 ?T2 =>\n    match z with\n    | ctx_prod_left_row => constr:(typ_join Td T1)\n    | ctx_prod_right_row => constr:(typ_join Td T2)\n    end\n  | typ_bot (con_output_kind ?z) => constr:(typ_top (con_input_kind z))\n  | typ_fvar ?X =>\n      match goal with\n      | Hb : binds X (Rng _ ?Tu _) _,\n        Hi : contravariant_inv _ _ _ _ _ ?Tt ?Tu\n        |- _ => constr:(Tt)\n      end\n  | _ =>\n    match goal with\n    | H1 : contravariant_inv _ _ _ _ _ ?Tt1 T,\n      H2 : contravariant_inv _ _ _ _ _ ?Tt2 T\n      |- _ => constr:(typ_meet Tt1 Tt2)\n    | H : contravariant_inv _ _ _ _ _ ?Tt T |- _ =>\n      constr:(Tt)\n    | Hte : type_equal _ _ _ nil nil ?Tb (typ_top _) _ |- _ =>\n      constr:(Tb)\n    end\n  end.\n\nLtac choose_contravariant_inv_join_bool z sd T :=\n  match T with\n  | typ_meet ?T1 ?T2 =>\n    let s1 := choose_contravariant_inv_join_bool z sd T1 in\n    let s2 := choose_contravariant_inv_join_bool z sd T2 in\n    constr:(andb s1 s2)\n  | typ_join ?T1 ?T2 =>\n    let s1 := choose_contravariant_inv_join_bool z sd T1 in\n    let s2 := choose_contravariant_inv_join_bool z sd T2 in\n    constr:(orb s1 s2)\n  | typ_or ?cs1 ?cs2 ?T1 ?T2 =>\n    match z with\n    | ctx_constructor_row ?c _ =>\n      match goal with\n      | Hin : CSet.In c cs1 |- _ =>\n        choose_contravariant_inv_join_bool z sd T1\n      | Hin : CSet.In c cs2 |- _ =>\n        choose_contravariant_inv_join_bool z sd T2\n      end\n    end\n  | typ_proj _ _ ?T1 =>\n    choose_contravariant_inv_join_bool z sd T1\n  | typ_variant _ => constr:(sd)\n  | typ_constructor _ _ => constr:(sd)\n  | typ_ref _ => constr:(sd)\n  | typ_arrow _ _ => constr:(sd)\n  | typ_prod _ _ => constr:(sd)\n  | typ_bot (con_output_kind ?z) => constr:(false)\n  | typ_fvar ?X =>\n      match goal with\n      | Hb : binds X (Rng _ ?Tu _) _,\n        Hi : contravariant_inv _ ?s _ _ _ _ ?Tu\n        |- _ => constr:(s)\n      end\n  | _ =>\n    match goal with\n    | H1 : contravariant_inv _ ?s1 _ _ _ _ T,\n      H2 : contravariant_inv _ ?s2 _ _ _ _ T\n      |- _ => constr:(orb s1 s2)\n    | H : contravariant_inv _ ?s _ _ _ _ T |- _ => constr:(s)\n    | Hte : type_equal _ _ _ nil nil ?Tb (typ_top _) _ |- _ =>\n      constr:(false)\n    end\n  end.\n\nLtac construct_contravariant_inv_bot :=\n  try match goal with\n  | |- contravariant_inv _ _ _ _ _ (typ_top _) _ =>\n    apply contravariant_inv_bot;\n    treflexivity\n  | |- contravariant_inv _ (?s && false) _ _ _\n         (typ_join _ (typ_top _)) _ =>\n    try replace (andb s false) with false by ring;\n    apply contravariant_inv_bot;\n    rewrite type_equal_join_annihilation_r\n      by auto with wellformed;\n    treflexivity\n  | |- contravariant_inv _ _ _ _ _ ?Tt _ =>\n    match goal with\n    | H : type_equal _ _ _ nil nil Tt (typ_top _) _ |- _ =>\n      apply contravariant_inv_bot;\n      apply H\n    | H: type_equal _ _ _ nil nil Tt (typ_meet ?Ttl ?Ttr) _,\n      Hl : type_equal _ _ _ nil nil ?Ttl (typ_top _) _,\n      Hr : type_equal _ _ _ nil nil ?Ttr (typ_top _) _ |- _ =>\n      apply contravariant_inv_bot;\n      rewrite H;\n      rewrite Hl;\n      rewrite Hr;\n      rewrite type_equal_meet_identity by auto with kinding;\n      treflexivity\n    end\n  end.\n\nLtac construct_contravariant_inv :=\n  construct_contravariant_inv_bot;\n  repeat match goal with\n  | |- contravariant_inv ?z _ _ _ _ ?Tt (typ_or ?csl ?csr ?Tl ?Tr) =>\n    match goal with\n    | H : contravariant_inv _ _ _ _ _ Tt ?Ts |- _ =>\n      match Tl with\n      | context[Ts] =>\n        match Tr with\n        | context[Ts] =>\n          match z with\n          | ctx_constructor_row ?c ?cs =>\n            destruct (CSet.In_dec c csl);\n            [> apply contravariant_inv_or_l\n            | apply contravariant_inv_or_r]\n          end\n        | _ => apply contravariant_inv_or_l\n        end\n      | _ =>\n        match Tr with\n        | context[Ts] => apply contravariant_inv_or_r\n        end\n      end\n    | _ =>\n      match z with\n      | ctx_constructor_row ?c ?cs =>\n        destruct (CSet.In_dec c csl);\n        [> apply contravariant_inv_or_l | apply contravariant_inv_or_r]\n      end     \n    end\n  | |- contravariant_inv ?z ?s _ _ _ ?Tt (typ_join ?Ts1 ?Ts2) =>\n    let s1' := choose_contravariant_inv_join_bool z s Ts1 in\n    let s2' := choose_contravariant_inv_join_bool z s Ts2 in\n    let T1' := choose_contravariant_inv_join_type z Tt Ts1 in\n    let T2' := choose_contravariant_inv_join_type z Tt Ts2 in\n    apply contravariant_inv_join\n      with (s1 := s1') (s2 := s2') (T2 := T1') (T3 := T2')\n  | |- contravariant_inv _ _ _ _ _ _ (typ_top _) =>\n    apply contravariant_inv_top\n  | |- contravariant_inv _ _ _ _ _ _ (typ_meet _ _) =>\n    apply contravariant_inv_meet\n  | |- contravariant_inv _ _ _ _ _ _ (typ_proj _ _ _) =>\n    apply contravariant_inv_proj\n  | |- contravariant_inv _ _ _ _ _ _ (typ_constructor _ _) =>\n    apply contravariant_inv_constructor\n  | |- contravariant_inv ctx_arrow_left _ _ _ _ _ (typ_arrow _ _) =>\n    apply contravariant_inv_arrow_left\n  | |- contravariant_inv ctx_arrow_right_row _ _ _ _ _ (typ_arrow _ _) =>\n    apply contravariant_inv_arrow_right\n  | |- contravariant_inv ctx_prod_left_row _ _ _ _ _ (typ_prod _ _) =>\n    apply contravariant_inv_prod_left\n  | |- contravariant_inv ctx_prod_right_row _ _ _ _ _ (typ_prod _ _) =>\n    apply contravariant_inv_prod_right\n  | |- contravariant_inv _ _ _ _ _ _ (typ_ref _) =>\n    apply contravariant_inv_ref\n  | |- contravariant_inv _ _ _ _ _ _ (typ_mu _ _) =>\n    apply contravariant_inv_mu\n  | Hb : binds ?X (Rng ?Tl ?Tu _) _\n    |- contravariant_inv _ _ _ _ _ _ (typ_fvar ?X) =>\n    apply contravariant_inv_var with (T2 := Tl) (T3 := Tu)\n  end;\n  try assumption;\n  construct_contravariant_inv_bot.\n\nLemma contravariant_inv_sub : forall z s1 s2 v E1 E2 K1 T1 T2 T3,\n    contravariant_inv z s1 v E1 E2 T1 T2 ->\n    subtype v (E1 & E2) empty nil nil T1 T3 K1 ->\n    leb s2 s1 ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    K1 = con_input_kind z ->\n    contravariant_inv z s2 v E1 E2 T3 T2.\nProof.\n  introv Hi Hs Hb He1 He2 Heq.\n  generalize dependent T3.\n  generalize dependent s2.\n  subst.\n  induction Hi; introv Hb Hs; subst; eauto.\n  - apply contravariant_inv_join\n      with (s1 := andb s0 s1) (s2 := andb s0 s2)\n           (T2 := typ_join T0 T2) (T3 := typ_join T0 T3); auto.\n    + eauto using subtype_upper_bound_r,\n        type_environment_extend, leb_lower_bound_r\n          with kinding wellformed.\n    + eauto using subtype_upper_bound_r,\n        type_environment_extend, leb_lower_bound_r\n          with kinding wellformed.\n    + rewrite subtype_dual in Hs by auto using valid_tenv_extend.\n      rewrite Hs at 1.\n      subst_equal T1.\n      rewrite type_equal_join_distribution by auto with kinding.\n      treflexivity.\n    + unfold leb in Hb.\n      rewrite Hb at 1.\n      rewrite andb_orb_distribution.\n      reflexivity.\n  - apply contravariant_inv_arrow_left;\n      eauto using subtype_transitive, valid_tenv_extend.\n  - apply contravariant_inv_arrow_right;\n      eauto using subtype_transitive, valid_tenv_extend.\n  - apply contravariant_inv_ref;\n      eauto using subtype_transitive, valid_tenv_extend.\n  - apply contravariant_inv_prod_left;\n      eauto using subtype_transitive, valid_tenv_extend.\n  - apply contravariant_inv_prod_right;\n      eauto using subtype_transitive, valid_tenv_extend.\n  - apply contravariant_inv_constructor;\n      eauto using subtype_transitive, valid_tenv_extend.\n  - rewrite leb_false with (b := s2) by assumption.\n    eauto using subtype_equal_top, valid_tenv_extend.\nQed.\n\nInstance contravariant_inv_eq_morph_impl\n  (z : contravariant_context) (s : bool) (v : version)\n  (E1 : tenv) (E2 : tenv)\n  `{ He1 : valid_tenv v E1 }\n  `{ He2 : valid_tenv_extension v E1 E2 }\n  : Morphisms.Proper\n      (type_equal' v (E1 & E2) empty nil nil (con_input_kind z) ==>\n       eq ==> Basics.impl)\n      (contravariant_inv z s v E1 E2) | 3\n  := { }.\n  unfold Morphisms.respectful.\n  intros T1 T1' Hte T2' T2 Heq Hi.\n  rewrite <- Heq.\n  apply contravariant_inv_sub\n    with (s1 := s) (K1 := con_input_kind z) (T1 := T1);\n    auto using leb_refl.\n  rewrite Hte.\n  sreflexivity.\nQed.\n\nInstance contravariant_inv_eq_morph_flip_impl\n  (z : contravariant_context) (s : bool) (v : version)\n  (E1 : tenv) (E2 : tenv)\n  `{ He1 : valid_tenv v E1 }\n  `{ He2 : valid_tenv_extension v E1 E2 }\n  : Morphisms.Proper\n      (type_equal' v (E1 & E2) empty nil nil (con_input_kind z) ==>\n       eq ==> Basics.flip Basics.impl)\n      (contravariant_inv z s v E1 E2) | 3\n  := { }.\n  unfold Morphisms.respectful.\n  intros T1 T1' Hte T2' T2 Heq Hi.\n  rewrite Heq.\n  apply contravariant_inv_sub\n    with (s1 := s) (K1 := con_input_kind z) (T1 := T1');\n    auto using leb_refl.\n  rewrite Hte.\n  sreflexivity.\nQed.\n\nInstance contravariant_inv_sub_morph_impl\n  (z : contravariant_context) (s : bool) (v : version)\n  (E1 : tenv) (E2 : tenv)\n  `{ He1 : valid_tenv v E1 }\n  `{ He2 : valid_tenv_extension v E1 E2 }\n  : Morphisms.Proper\n      (subtype' v (E1 & E2) empty nil nil (con_input_kind z) ==>\n       eq ==> Basics.impl)\n      (contravariant_inv z s v E1 E2) | 3\n  := { }.\n  unfold Morphisms.respectful.\n  intros T1 T1' Hte T2' T2 Heq Hi.\n  rewrite <- Heq.\n  apply contravariant_inv_sub\n    with (s1 := s) (K1 := con_input_kind z) (T1 := T1);\n    auto using leb_refl.\nQed.\n\nLemma contravariant_inv_lower_bound : forall z s1 s2 v E1 E2 T1 T2 T3,\n    contravariant_inv z s1 v E1 E2 T1 T3 ->\n    contravariant_inv z s2 v E1 E2 T2 T3 ->\n    kinding (E1 & E2) empty T1 (con_input_kind z) ->\n    kinding (E1 & E2) empty T2 (con_input_kind z) ->\n    kinding E1 E2 T3 (con_output_kind z) ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    contravariant_inv z (orb s1 s2) v E1 E2 (typ_meet T1 T2) T3.\nProof.\n  introv Hi1 Hi2 Hk1 Hk2 Hk3 He1 He2.\n  generalize dependent T2.\n  generalize dependent s2.\n  induction Hi1; introv Hi2 Hk2; invert_contravariant_inv; subst;\n    auto using subtype_greatest_lower_bound, subtype_meet_top_r,\n      valid_tenv_extend with kinding.\n  - apply contravariant_inv_join\n      with (s1 := s1) (s2 := s2) (T2 := T2) (T3 := T3);\n      try ring_simplify; auto.\n    subst_equal T0.\n    rewrite type_equal_meet_identity by auto with kinding.\n    assumption.\n  - apply contravariant_inv_join\n      with (s1 := orb s1 s4) (s2 := orb s2 s5)\n        (T2 := typ_meet T2 T6) (T3 := typ_meet T3 T7);\n          try ring_simplify; auto with kinding.\n    subst_equal T1.\n    subst_equal T0.\n    rewrite <- type_equal_meet_associative by auto with kinding.\n    rewrite type_equal_meet_associative\n      with (T1 := T3) by auto with kinding.\n    rewrite type_equal_meet_commutative\n      with (T1 := T3) by auto with kinding.\n    rewrite <- type_equal_meet_associative by auto with kinding.\n    rewrite type_equal_meet_associative by auto with kinding.\n    treflexivity.\n  - eauto using kinding_from_valid_tenv_lower with wellformed.\n  - eauto using kinding_from_valid_tenv_lower with wellformed.\n  - inversion Hk3; subst.\n    assert (not (CSet.In c0 cs1)) by csetdec.\n    contradiction.\n  - inversion Hk3; subst.\n    assert (not (CSet.In c0 cs1)) by csetdec.\n    contradiction.\n  - subst_equal T0.\n    rewrite type_equal_meet_identity by auto with kinding.\n    replace (orb s false) with s by ring.\n    auto.\n  - auto using kinding_unroll with wellformed.\n  - subst_equal T1.\n    rewrite type_equal_meet_commutative by auto with kinding.\n    rewrite type_equal_meet_identity by auto with kinding.\n    assumption.\nQed.\n\nLtac invert_kindings_con :=\n  repeat\n    match goal with\n    | Hz : valid_contravariant_context (ctx_constructor_row _ _) |- _ =>\n      inversion Hz; subst; clear Hz\n    | H : kinding _ _ (typ_or _ _ _ _) _ |- _ =>\n      inversion H; subst; clear H\n    | H : kinding _ _ (typ_proj _ _ _) _ |- _ =>\n      inversion H; subst; clear H\n    | H : kinding _ _ (typ_join _ _) _ |- _ =>\n      inversion H; subst; clear H\n    | H : kinding _ _ (typ_bot _) _ |- _ =>\n      inversion H; subst; clear H\n    | H : kinding _ _ (typ_mu _ _) _ |- _ =>\n      inversion H; subst; clear H\n    end;\n  match goal with\n  | HeqK : knd_row ?cs1 = con_output_kind (ctx_constructor_row ?c ?cs2) |- _ =>\n    inversion HeqK; subst\n  | HeqK : knd_row ?cs1 = con_output_kind ?z |- _ =>\n    destruct z; try discriminate;\n    inversion HeqK; subst\n  | _ => idtac\n  end.\n\nLtac solve_contravariant_inv_side_conditions :=\n  try match goal with\n  | |- type_equal _ _ _ _ _ ?T ?T _ =>\n    treflexivity\n  | |- subtype _ _ _ nil nil ?T1 (typ_join ?T1 ?T2) _ =>\n    auto using subtype_upper_bound_l with kinding wellformed\n  | |- subtype _ _ _ nil nil ?T2 (typ_join ?T1 ?T2) _ =>\n    auto using subtype_upper_bound_r with kinding wellformed\n  | Hs1 : subtype _ _ _ nil nil ?T1 ?T3 _,\n    Hs2 : subtype _ _ _ nil nil ?T2 ?T3 _\n    |- subtype _ _ _ nil nil (typ_join ?T1 ?T2) ?T3 _ =>\n    apply subtype_least_upper_bound;\n    auto using valid_tenv_extend\n  | |- @eq bool ?s1 ?s2 =>\n    try ring;\n    repeat match goal with\n    | s : bool |- _ => destruct s\n    end; solve [auto]\n  | Hs : subtype _ _ _ nil nil (typ_join ?T1 ?T2) ?T3 _\n    |- subtype _ _ _ nil nil ?T1 ?T3 _ =>\n    rewrite <- Hs;\n    apply subtype_upper_bound_l;\n    auto with kinding wellformed\n  | Hs : subtype _ _ _ nil nil (typ_join ?T1 ?T2) ?T3 _\n    |- subtype _ _ _ nil nil ?T2 ?T3 _ =>\n    rewrite <- Hs;\n    apply subtype_upper_bound_r;\n    auto with kinding wellformed\n  | Hs : subtype _ _ _ nil nil (typ_meet ?T2 ?T3) ?T1 _ |-\n    type_equal _ _ _ nil nil ?T1\n      (typ_meet (typ_join ?T1 ?T2) (typ_join ?T1 ?T3)) _ =>\n    rewrite <- type_equal_join_distribution\n      by auto with kinding;\n    rewrite subtype_dual in Hs;\n    auto using valid_tenv_extend\n  | Hte1 : type_equal _ _ _ nil nil ?T1 (typ_meet ?T2 ?T3) _,\n    Hte2 : type_equal _ _ _ nil nil ?T3 (typ_top _) _,\n    Hs : subtype _ _ _ nil nil ?T4 ?T2 _\n    |- subtype _ _ _ nil nil (typ_meet ?T4 _) ?T1 _ =>\n    rewrite Hte1;\n    rewrite Hte2;\n    rewrite type_equal_meet_identity\n      by auto with kinding;\n    rewrite <- Hs;\n    rewrite subtype_lower_bound_l\n      by auto with kinding wellformed;\n    sreflexivity\n  | Hte1 : type_equal _ _ _ nil nil ?T1 (typ_meet ?T2 ?T3) _,\n    Hte2 : type_equal _ _ _ nil nil ?T2 (typ_top ?K) _,\n    Hs : subtype _ _ _ nil nil ?T4 ?T3 _\n    |- subtype _ _ _ nil nil (typ_meet _ ?T4) ?T1 _ =>\n    rewrite Hte1;\n    rewrite Hte2;\n    rewrite type_equal_meet_commutative\n      with (T1 := typ_top K) by auto with kinding;\n    rewrite type_equal_meet_identity\n      by auto with kinding;\n    rewrite <- Hs;\n    rewrite subtype_lower_bound_r\n      by auto with kinding wellformed;\n    sreflexivity\n  | Hte : type_equal _ _ _ nil nil ?T1 (typ_meet ?T2 ?T3) _,\n    Hs1 : subtype _ _ _ nil nil ?T4 ?T2 _,\n    Hs2 : subtype _ _ _ nil nil ?T5 ?T3 _\n    |- subtype _ _ _ nil nil (typ_meet ?T4 ?T5) ?T1 _ =>\n    rewrite Hte;\n    apply subtype_greatest_lower_bound;\n      try rewrite <- Hs1; try rewrite <- Hs2;\n      auto using valid_tenv_extend,\n        subtype_lower_bound_l, subtype_lower_bound_r\n          with kinding wellformed\n  | Hte : type_equal _ _ _ nil nil ?T1 ?T2 _,\n    Hs : subtype _ _ _ nil nil ?T1 ?T3 _\n    |- subtype _ _ _ nil nil ?T2 ?T3 _ =>\n    rewrite <- Hs;\n    rewrite Hte;\n    sreflexivity\n  | Hte : type_equal _ _ _ nil nil ?T1 ?T2 _,\n    Hs : subtype _ _ _ nil nil ?T2 ?T3 _\n    |- subtype _ _ _ nil nil ?T1 ?T3 _ =>\n    rewrite <- Hs;\n    rewrite Hte;\n    sreflexivity\n  | Hi : contravariant_inv ?z ?s _ _ _ ?Tsl ?Tt |-\n    contravariant_inv _ _ _ _ _ (typ_join ?Tsl _) ?Tt =>\n    apply contravariant_inv_sub\n      with (s1 := s) (K1 := con_input_kind z) (T1 := Tsl);\n      auto using subtype_upper_bound_l, leb_lower_bound_l\n        with kinding wellformed\n  | Hi : contravariant_inv ?z ?s _ _ _ ?Tsr ?Tt |-\n    contravariant_inv _ _ _ _ _ (typ_join _ ?Tsr) ?Tt =>\n    apply contravariant_inv_sub\n      with (s1 := s) (K1 := con_input_kind z) (T1 := Tsr);\n      auto using subtype_upper_bound_r, leb_lower_bound_r\n        with kinding wellformed\n  | Hi : contravariant_inv _ ?s1 _ _ _ ?Tsl ?Tt,\n    Hte1 : type_equal _ _ _ nil nil ?Ts (typ_meet ?Tsl ?Tsr) _,\n    Hte2 : type_equal _ _ _ nil nil ?Tsr (typ_top _) _ |-\n    contravariant_inv _ ?s2  _ _ _ ?Ts ?Tt =>\n    rewrite Hte1;\n    rewrite Hte2;\n    rewrite type_equal_meet_identity by auto with kinding;\n    replace s2 with s1 by ring;\n    assumption\n  | Hi : contravariant_inv _ ?s1 _ _ _ ?Tsr ?Tt,\n    Hte1 : type_equal _ _ _ nil nil ?Ts (typ_meet ?Tsl ?Tsr) _,\n    Hte2 : type_equal _ _ _ nil nil ?Tsl (typ_top _) _ |-\n    contravariant_inv _ ?s2  _ _ _ ?Ts ?Tt =>\n    rewrite Hte1;\n    rewrite Hte2;\n    rewrite type_equal_meet_commutative by auto with kinding;\n    rewrite type_equal_meet_identity by auto with kinding;\n    replace s2 with s1 by ring;\n    assumption\n  | Hil : contravariant_inv _ ?s1 _ _ _ ?Tsl ?Tt,\n    Hir : contravariant_inv _ ?s2 _ _ _ ?Tsr ?Tt,\n    Hte : type_equal _ _ _ nil nil ?Ts (typ_meet ?Tsl ?Tsr) _ |-\n    contravariant_inv _ (orb ?s1 ?s2) _ _ _ ?Ts ?Tt =>\n    rewrite Hte;\n    apply contravariant_inv_lower_bound;\n    auto with kinding wellformed\n  | Hil : contravariant_inv _ ?s1 _ _ _ ?Tsl ?Tt,\n    Hir : contravariant_inv _ ?s2 _ _ _ ?Tsr ?Tt\n    |- contravariant_inv _ (orb ?s1 ?s2) _ _ _\n                     (typ_meet ?Tsl ?Tsr) ?Tt =>\n    apply contravariant_inv_lower_bound;\n    auto with kinding wellformed\n  | H1 : CSet.In ?c ?cs1,\n    H2 : ~ CSet.In ?c ?cs1 |- _ =>\n    contradiction\n  | Hk : kinding _ _ (typ_or ?cs1 ?cs2 _ _) _,\n    H1 : CSet.In ?c ?cs1,\n    H2 : CSet.In ?c ?cs2 |- _ =>\n    inversion Hk; subst;\n    assert (~ CSet.In c cs1) by csetdec;\n    contradiction\n  | Hk : kinding _ _ (typ_or ?cs _ (typ_or _ _ _ _) _) _\n    |- CSet.In _ ?cs =>\n    inversion Hk; subst;\n    match goal with\n    | Hk' : kinding _ _ (typ_or _ _ _ _) (knd_row cs) |- _ =>\n      inversion Hk'; subst;\n      csetdec\n    end\n  | |- con_output_kind ?z = con_output_kind ?z =>\n    reflexivity\n  | |- CSet.In _ _ =>\n    invert_kindings_con;\n    csetdec\n  | Hin : in_qenv nil _ _ _ |- _ =>\n    inversion Hin\n  end.\n\nLemma type_equal_core_contravariant_inv_l :\n  forall z s v E1 E2 T1 T2 T3,\n    contravariant_inv z s v E1 E2 T1 T2 ->\n    type_equal_core v T2 T3 ->\n    valid_contravariant_context z ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    kinding (E1 & E2) empty T1 (con_input_kind z) ->\n    kinding E1 E2 T2 (con_output_kind z) ->\n    kinding E1 E2 T3 (con_output_kind z) ->\n    contravariant_inv z s v E1 E2 T1 T3.\nProof.\n  introv Hi Hte Hz He1 He2 Hk1 Hk2 Hk3.\n  destruct Hte; invert_contravariant_inv; subst;\n    construct_contravariant_inv; solve_contravariant_inv_side_conditions.\n  - invert_kindings_con.\n    construct_contravariant_inv; solve_contravariant_inv_side_conditions.\n  - invert_kindings_con.\n    construct_contravariant_inv; solve_contravariant_inv_side_conditions.\n  - invert_kindings_con.\n    assert (not (CSet.In c0 cs2)) by csetdec.\n    contradiction.\n  - invert_kindings_con.\n    assert (not (CSet.In c0 cs1)) by csetdec.\n    contradiction.\n  - rewrite <- type_equal_join_distribution by auto with kinding.\n    subst_equal T1 at 2.\n    rewrite <- type_equal_join_idempotent\n      by auto with kinding wellformed.\n    subst_equal T1.\n    treflexivity.\n  - subst_equal T1.\n    rewrite type_equal_meet_commutative by auto with kinding.\n    treflexivity.\n  - rewrite <- type_equal_meet_associative at 1\n      by auto with kinding.\n    rewrite <- type_equal_meet_idempotent\n      by auto with kinding wellformed.\n    subst_equal T1.\n    treflexivity.\n  - subst_equal T1.\n    subst_equal T5.\n    rewrite type_equal_meet_associative by auto with kinding.\n    treflexivity.\nQed.\n\nLemma type_equal_core_contravariant_inv_r :\n  forall z s v E1 E2 T1 T2 T3,\n    contravariant_inv z s v E1 E2 T1 T2 ->\n    type_equal_core v T3 T2 ->\n    valid_contravariant_context z ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    kinding (E1 & E2) empty T1 (con_input_kind z) ->\n    kinding E1 E2 T2 (con_output_kind z) ->\n    kinding E1 E2 T3 (con_output_kind z) ->\n    contravariant_inv z s v E1 E2 T1 T3.\nProof.\n  introv Hi Hte Hz He1 He2 Hk1 Hk2 Hk3.\n  destruct Hte; invert_contravariant_inv; subst;\n    construct_contravariant_inv; solve_contravariant_inv_side_conditions.\n  - invert_kindings_con.\n    construct_contravariant_inv; solve_contravariant_inv_side_conditions.\n  - invert_kindings_con.\n    construct_contravariant_inv; solve_contravariant_inv_side_conditions.\n  - invert_kindings_con.\n    construct_contravariant_inv; solve_contravariant_inv_side_conditions.\n  - invert_kindings_con.\n    construct_contravariant_inv; solve_contravariant_inv_side_conditions.\n  - apply contravariant_inv_join\n      with (s1 := s) (s2 := false)\n           (T2 := T1) (T3 := typ_top (con_input_kind z));\n      construct_contravariant_inv;\n      solve_contravariant_inv_side_conditions.\n    rewrite type_equal_meet_identity\n      by auto with kinding wellformed.\n    treflexivity.\n  - subst_equal T1.\n    rewrite type_equal_meet_commutative by auto with kinding.\n    treflexivity.\n  - subst_equal T4.\n    rewrite type_equal_meet_commutative by auto with kinding.\n    rewrite type_equal_meet_identity by auto with kinding.\n    subst_equal T1.\n    subst_equal T4.\n    treflexivity.\n  - subst_equal T1.\n    subst_equal T4.\n    rewrite type_equal_meet_associative by auto with kinding.\n    treflexivity.\n  - invert_kindings_con.\n    construct_contravariant_inv; solve_contravariant_inv_side_conditions.\n    rewrite type_equal_meet_identity\n      by auto with kinding wellformed.\n    treflexivity.\n  - apply contravariant_inv_join\n      with (s1 := s) (s2 := false)\n           (T2 := T1) (T3 := typ_top (con_input_kind z));\n      construct_contravariant_inv;\n      solve_contravariant_inv_side_conditions.\n    rewrite type_equal_meet_identity\n      by auto with kinding wellformed.\n    treflexivity.\n  - apply contravariant_inv_bot.\n    subst_equal T1.\n    rewrite type_equal_join_annihilation_l\n      by auto with kinding wellformed.\n    treflexivity.\n  - rewrite type_equal_meet_distribution\n      by auto with kinding.\n    subst_equal <- T1.\n    subst_equal T1 at 3.\n    rewrite type_equal_join_annihilation_r\n      by auto with kinding wellformed.\n    subst_equal T1.\n    treflexivity.\n  - rewrite <- type_equal_meet_associative\n      by auto with kinding.\n    rewrite type_equal_meet_distribution\n      by auto with kinding.\n    subst_equal <- T1.\n    rewrite type_equal_meet_distribution\n      by auto with kinding.\n    rewrite type_equal_meet_commutative\n      with (T1 := T6) (T2 := T5)\n      by auto with kinding.\n    rewrite type_equal_meet_associative\n      by auto with kinding.\n    subst_equal <- T1.\n    rewrite H2 at 2.\n    rewrite type_equal_meet_associative\n      by auto with kinding.\n    rewrite <- type_equal_meet_idempotent\n      by auto with kinding wellformed.\n    subst_equal <- T1.\n    rewrite type_equal_join_absorption\n      by auto with kinding.\n    treflexivity.\n  - invert_kindings_con.\n    easy.\nQed.\n\nLemma type_equal_contravariant_inv' :\n  forall z s v E1 E2 E3 Q2 T1 T2 T3,\n    type_equal v E1 (E2 & E3) nil Q2 T2 T3 (con_output_kind z) ->\n    type_equal_eqn_subs v E1 (E2 & E3) Q2 ->\n    kinding (E1 & E2 & E3) empty T1 (con_input_kind z) ->\n    kinding (E1 & E2) E3 T2 (con_output_kind z) ->\n    kinding (E1 & E2) E3 T3 (con_output_kind z) ->\n    valid_contravariant_context z ->\n    valid_tenv v (E1 & E2) ->\n    valid_tenv_extension v (E1 & E2) E3 ->\n    (forall z s X T4 T5 T6,\n        binds X (Rng T5 T6 (con_output_kind z)) E1 ->\n        valid_contravariant_context z ->\n        kinding (E1 & E2 & E3) empty T4 (con_input_kind z) ->\n        contravariant_inv z s v (E1 & E2) E3 T4 T5 ->\n        contravariant_inv z s v (E1 & E2) E3 T4 T6) ->\n    contravariant_inv z s v (E1 & E2) E3 T1 T2 <->\n    contravariant_inv z s v (E1 & E2) E3 T1 T3.\nProof.\n  introv Hte Hes Hk1 Hk2 Hk3 Hz He1 He2 Hb.\n  remember (con_output_kind z) as K.\n  remember (E2 & E3) as E23.\n  remember Hte as Hte2 eqn:Heq.\n  clear Heq.\n  remember nil as Q1 in Hte at 1.\n  generalize dependent z.\n  generalize dependent s.\n  generalize dependent T1.\n  induction Hte; introv Heq Hk1 Hz; subst;\n    autorewrite with rew_env_concat in *;\n    split; introv Hi; invert_contravariant_inv; subst;\n      construct_contravariant_inv;\n      unroll_recursive_eqns;\n      solve_contravariant_inv_side_conditions.\n  - apply binds_tenv_weakening_l; auto with wellformed.\n  - apply binds_tenv_weakening_l; auto with wellformed.\n  - eauto.\n  - apply binds_tenv_weakening_l; auto with wellformed.\n  - rewrite <- IHHte1;\n      auto using type_equal_eqn_subs_push\n        with kinding wellformed.\n  - rewrite <- IHHte2;\n      auto using type_equal_eqn_subs_push\n        with kinding wellformed.\n  - rewrite IHHte1;\n      auto using type_equal_eqn_subs_push\n        with kinding wellformed.\n  - rewrite IHHte2;\n      auto using type_equal_eqn_subs_push\n        with kinding wellformed.\n  - rewrite <- IHHte\n      by (auto using type_equal_eqn_subs_push with wellformed;\n          invert_kindings_con; auto with kinding); auto.\n  - rewrite IHHte\n      by (auto using type_equal_eqn_subs_push with wellformed;\n          invert_kindings_con; auto with kinding); auto.\n  - rewrite <- IHHte1;\n      auto using type_equal_eqn_subs_push\n        with kinding wellformed.\n  - rewrite <- IHHte2;\n      auto using type_equal_eqn_subs_push\n        with kinding wellformed.\n  - rewrite IHHte1;\n      auto using type_equal_eqn_subs_push\n        with kinding wellformed.\n  - rewrite IHHte2;\n      auto using type_equal_eqn_subs_push\n        with kinding wellformed.\n  - apply contravariant_inv_join\n      with (s1 := s2) (s2 := s3) (T2 := T4) (T3 := T5);\n      solve_contravariant_inv_side_conditions; auto.\n    + rewrite <- IHHte1;\n        auto using type_equal_eqn_subs_push\n          with kinding wellformed.\n    + rewrite <- IHHte2;\n        auto using type_equal_eqn_subs_push\n          with kinding wellformed.\n  - apply contravariant_inv_join\n      with (s1 := s2) (s2 := s3) (T2 := T4) (T3 := T5);\n      solve_contravariant_inv_side_conditions; auto.\n    + rewrite IHHte1;\n        auto using type_equal_eqn_subs_push\n          with kinding wellformed.\n    + rewrite IHHte2;\n        auto using type_equal_eqn_subs_push\n          with kinding wellformed.\n  - apply type_equal_core_contravariant_inv_l with T1; auto.\n  - apply type_equal_core_contravariant_inv_r with T1'; auto.\n  - rewrite IHHte;\n      auto using type_equal_eqn_subs_push\n        with wellformed.\n  - rewrite <- IHHte;\n      auto using type_equal_eqn_subs_push\n        with wellformed.\n  - apply type_equal_extend in Hte1 as Hte1';\n      auto using type_environment_extend_inv with wellformed.\n    rewrite <- IHHte2;\n        auto using type_equal_eqn_subs_push\n          with kinding wellformed.\n    rewrite <- IHHte1;\n      auto using type_equal_eqn_subs_push\n        with kinding wellformed.\n  - apply type_equal_extend in Hte1 as Hte1';\n      auto using type_environment_extend_inv with wellformed.\n    rewrite IHHte1;\n        auto using type_equal_eqn_subs_push\n          with kinding wellformed.\n    rewrite IHHte2;\n      auto using type_equal_eqn_subs_push\n        with kinding wellformed.\nQed.\n\nLemma subtype_contravariant_inv' : forall z s v E1 E2 E3 T1 T2 T3,\n    subtype v E1 (E2 & E3) nil nil T2 T3 (con_output_kind z) ->\n    kinding (E1 & E2 & E3) empty T1 (con_input_kind z) ->\n    kinding (E1 & E2) E3 T2 (con_output_kind z) ->\n    kinding (E1 & E2) E3 T3 (con_output_kind z) ->\n    valid_contravariant_context z ->\n    valid_tenv v (E1 & E2)->\n    valid_tenv_extension v (E1 & E2) E3 ->\n    (forall z s X T4 T5 T6,\n        binds X (Rng T5 T6 (con_output_kind z)) E1 ->\n        valid_contravariant_context z ->\n        kinding (E1 & E2 & E3) empty T4 (con_input_kind z) ->\n        contravariant_inv z s v (E1 & E2) E3 T4 T5 ->\n        contravariant_inv z s v (E1 & E2) E3 T4 T6) ->\n    contravariant_inv z s v (E1 & E2) E3 T1 T2 ->\n    contravariant_inv z s v (E1 & E2) E3 T1 T3.\nProof.\n  introv Hs Hk1 Hk2 Hk3 Hz He1 He2 Hb Hi.\n  unfold subtype in Hs.\n  assert (contravariant_inv z s v (E1 & E2) E3\n            T1 (typ_meet T2 T3)) as Hi2\n    by (rewrite type_equal_contravariant_inv' with (T3 := T2);\n        try symmetry; auto).\n  inversion Hi2; subst; auto.\nQed.\n\nLemma valid_tenv_rec_contravariant_inv : forall v E1 E2 E3,\n    valid_tenv_rec v empty E1 (E2 & E3) ->\n    valid_tenv v (E1 & E2) ->\n    valid_tenv_extension v (E1 & E2) E3 ->\n    (forall z s X T1 T2 T3,\n        binds X (Rng T2 T3 (con_output_kind z)) E1 ->\n        valid_contravariant_context z ->\n        kinding (E1 & E2 & E3) empty T1 (con_input_kind z) ->\n        contravariant_inv z s v (E1 & E2) E3 T1 T2 ->\n        contravariant_inv z s v (E1 & E2) E3 T1 T3).\nProof.\n  introv He1 He2 He3.\n  remember empty as E0.\n  remember (E2 & E3) as E23.\n  generalize dependent E2.\n  induction He1; introv Heq He2 He3 Hb Hz Hk Hi; subst.\n  - exfalso; eauto using binds_empty_inv.\n  - destruct (binds_push_inv Hb) as [[? ?]|[Hx Hbnd2]]; subst;\n      autorewrite with rew_env_concat in *.\n    + assert (valid_range v E2\n                (X ~ Rng T2 T3 (con_output_kind z) & E4 & E3)\n                (Rng T2 T3 (con_output_kind z))) as Hr by auto.\n      inversion Hr; subst.\n      rewrite <- concat_assoc with (E := E2).\n      apply subtype_contravariant_inv' with T2;\n        try solve [autorewrite with rew_env_concat; eauto];\n        try solve\n            [apply kinding_extend; auto;\n             apply type_environment_extend_inv;\n               autorewrite with rew_env_concat;\n               auto with wellformed].\n      apply IHHe1; autorewrite with rew_env_concat; auto.\n    + rewrite <- concat_assoc with (E := E2).\n      eapply IHHe1; autorewrite with rew_env_concat; eauto.\nQed.\n\nLemma type_equal_contravariant_inv :\n  forall z s v E1 E2 T1 T2 T3,\n    type_equal v E1 E2 nil nil T2 T3 (con_output_kind z) ->\n    kinding (E1 & E2) empty T1 (con_input_kind z) ->\n    valid_contravariant_context z ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    contravariant_inv z s v E1 E2 T1 T2 <->\n    contravariant_inv z s v E1 E2 T1 T3.\nProof.\n  introv Hte Hk Hz He1 He2.\n  replace E1 with (E1 & empty) by apply concat_empty_r.\n  apply type_equal_contravariant_inv' with (Q2 := nil);\n    autorewrite with rew_env_concat; auto with kinding.\n  introv Hb' Hz' Hk' Hi'.\n  rewrite <- concat_empty_r with (E := E1).\n  eapply valid_tenv_rec_contravariant_inv;\n    autorewrite with rew_env_concat; eauto.\n  rewrite <- concat_empty_r with (E := E2).\n  apply valid_tenv_rec_weakening_rec_r;\n    autorewrite with rew_env_concat;\n    try fold (type_environment E1);\n    auto with wellformed.\nQed.\n\nLemma subtype_contravariant_inv :\n  forall z s v E1 E2 T1 T2 T3,\n    subtype v E1 E2 nil nil T2 T3 (con_output_kind z) ->\n    kinding (E1 & E2) empty T1 (con_input_kind z) ->\n    valid_contravariant_context z ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    contravariant_inv z s v E1 E2 T1 T2 ->\n    contravariant_inv z s v E1 E2 T1 T3.\nProof.\n  introv Hs Hk Hz He1 He2 Hi.\n  unfold subtype in Hs.\n  assert (contravariant_inv z s v E1 E2\n            T1 (typ_meet T2 T3)) as Hi2\n    by (rewrite type_equal_contravariant_inv with (T3 := T2);\n          try symmetry; auto).\n  inversion Hi2; subst; auto.\nQed.\n\nLemma invert_subtype_arrow_left : forall v E1 E2 T1 T2 T3 T4,\n    subtype v E1 E2 nil nil\n      (typ_arrow T1 T2) (typ_arrow T3 T4) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    subtype v (E1 & E2) empty nil nil T3 T1 knd_type.\nProof.\n  introv Hs He1 He2.\n  assert (contravariant_inv ctx_arrow_left true v E1 E2\n                      T1 (typ_arrow T1 T2))\n    by auto using subtype_refl with kinding wellformed.\n  assert (contravariant_inv ctx_arrow_left true v E1 E2\n                      T1 (typ_arrow T3 T4))\n    as Hi by eauto using subtype_contravariant_inv with kinding.\n  inversion Hi; subst; auto.\nQed.\n\nLemma invert_subtype_arrow_right_row_contravariant :\n  forall E1 E2 T1 T2 T3 T4,\n    subtype version_row_subtyping E1 E2 nil nil\n      (typ_arrow T1 T2) (typ_arrow T3 T4) knd_type ->\n    valid_tenv version_row_subtyping E1 ->\n    valid_tenv_extension version_row_subtyping E1 E2 ->\n    subtype version_row_subtyping (E1 & E2) empty nil nil\n      T4 T2 knd_type.\nProof.\n  introv Hs He1 He2.\n  assert (contravariant_inv ctx_arrow_right_row true\n            version_row_subtyping E1 E2 T2 (typ_arrow T1 T2))\n    by auto using subtype_refl with kinding wellformed.\n  assert (contravariant_inv ctx_arrow_right_row true\n            version_row_subtyping E1 E2 T2 (typ_arrow T3 T4))\n    as Hi by eauto using subtype_contravariant_inv with kinding.\n  inversion Hi; subst; auto.\nQed.\n\nLemma invert_subtype_ref_contravariant : forall v E1 E2 T1 T2,\n    subtype v E1 E2 nil nil (typ_ref T1) (typ_ref T2) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    subtype v (E1 & E2) empty nil nil T2 T1 knd_type.\nProof.\n  introv Hs He1 He2.\n  assert (contravariant_inv ctx_ref_contra true v E1 E2 T1 (typ_ref T1))\n    by auto using subtype_refl with kinding wellformed.\n  assert (contravariant_inv ctx_ref_contra true v E1 E2 T1 (typ_ref T2))\n    as Hi by eauto using subtype_contravariant_inv with kinding.\n  inversion Hi; subst; auto.\nQed.\n\nLemma invert_subtype_prod_left_row_contravariant :\n  forall E1 E2 T1 T2 T3 T4,\n    subtype version_row_subtyping E1 E2 nil nil\n      (typ_prod T1 T2) (typ_prod T3 T4) knd_type ->\n    valid_tenv version_row_subtyping E1 ->\n    valid_tenv_extension version_row_subtyping E1 E2 ->\n    subtype version_row_subtyping (E1 & E2) empty nil nil\n      T3 T1 knd_type.\nProof.\n  introv Hs He1 He2.\n  assert (contravariant_inv ctx_prod_left_row true\n            version_row_subtyping E1 E2 T1 (typ_prod T1 T2))\n    by auto using subtype_refl with kinding wellformed.\n  assert (contravariant_inv ctx_prod_left_row true\n            version_row_subtyping E1 E2 T1 (typ_prod T3 T4))\n    as Hi by eauto using subtype_contravariant_inv with kinding.\n  inversion Hi; subst; auto.\nQed.\n\nLemma invert_subtype_prod_right_row_contravariant :\n  forall E1 E2 T1 T2 T3 T4,\n    subtype version_row_subtyping E1 E2 nil nil\n      (typ_prod T1 T2) (typ_prod T3 T4) knd_type ->\n    valid_tenv version_row_subtyping E1 ->\n    valid_tenv_extension version_row_subtyping E1 E2 ->\n    subtype version_row_subtyping (E1 & E2) empty nil nil\n      T4 T2 knd_type.\nProof.\n  introv Hs He1 He2.\n  assert (contravariant_inv ctx_prod_right_row true\n            version_row_subtyping E1 E2 T2 (typ_prod T1 T2))\n    by auto using subtype_refl with kinding wellformed.\n  assert (contravariant_inv ctx_prod_right_row true\n            version_row_subtyping E1 E2 T2 (typ_prod T3 T4))\n    as Hi by eauto using subtype_contravariant_inv with kinding.\n  inversion Hi; subst; auto.\nQed.\n\nLemma invert_subtype_constructor_row_contravariant :\n  forall c cs E1 E2 T1 T2,\n    subtype version_row_subtyping E1 E2 nil nil\n      (typ_constructor c T1) (typ_constructor c T2) (knd_row cs)->\n    valid_tenv version_row_subtyping E1 ->\n    valid_tenv_extension version_row_subtyping E1 E2 ->\n    subtype version_row_subtyping (E1 & E2) empty nil nil\n      T2 T1 knd_type.\nProof.\n  introv Hs He1 He2.\n  assert (contravariant_inv (ctx_constructor_row c cs) true\n           version_row_subtyping E1 E2 T1 (typ_constructor c T1))\n    by auto using subtype_refl with kinding wellformed.\n  assert (kinding E1 E2 (typ_constructor c T1) (knd_row cs)) as Hk\n      by auto with kinding.\n  inversion Hk; subst.\n  assert (contravariant_inv (ctx_constructor_row c (CSet.singleton c))\n            true version_row_subtyping E1 E2 T1 (typ_constructor c T2))\n    as Hi by eauto using subtype_contravariant_inv with kinding csetdec.\n  inversion Hi; subst; auto.\nQed.\n\n(* *************************************************************** *)\n(** Invariant subtyping inversions *)\n\nLemma invert_subtype_arrow_left_row : forall E1 E2 T1 T2 T3 T4,\n    subtype version_row_subtyping E1 E2 nil nil\n      (typ_arrow T1 T2) (typ_arrow T3 T4) knd_type ->\n    valid_tenv version_row_subtyping E1 ->\n    valid_tenv_extension version_row_subtyping E1 E2 ->\n    type_equal version_row_subtyping (E1 & E2) empty nil nil\n      T1 T3 knd_type.\nProof.\n  introv Hs He1 He2.\n  apply subtype_antisymmetric;\n    eauto using valid_tenv_extend,\n      invert_subtype_arrow_left_row_covariant,\n      invert_subtype_arrow_left.\nQed.\n\nLemma invert_subtype_arrow_right_row :\n  forall E1 E2 T1 T2 T3 T4,\n    subtype version_row_subtyping E1 E2 nil nil\n      (typ_arrow T1 T2) (typ_arrow T3 T4) knd_type ->\n    valid_tenv version_row_subtyping E1 ->\n    valid_tenv_extension version_row_subtyping E1 E2 ->\n    type_equal version_row_subtyping (E1 & E2) empty nil nil\n      T2 T4 knd_type.\nProof.\n  introv Hs He1 He2.\n  apply subtype_antisymmetric;\n    eauto using valid_tenv_extend,\n      invert_subtype_arrow_right,\n      invert_subtype_arrow_right_row_contravariant.\nQed.\n\nLemma invert_subtype_ref : forall v E1 E2 T1 T2,\n    subtype v E1 E2 nil nil (typ_ref T1) (typ_ref T2) knd_type ->\n    valid_tenv v E1 ->\n    valid_tenv_extension v E1 E2 ->\n    type_equal v (E1 & E2) empty nil nil T1 T2 knd_type.\nProof.\n  introv Hs He1 He2.\n  apply subtype_antisymmetric;\n    eauto using valid_tenv_extend,\n      invert_subtype_ref_covariant,\n      invert_subtype_ref_contravariant.\nQed.\n\nLemma invert_subtype_prod_left_row :\n  forall E1 E2 T1 T2 T3 T4,\n    subtype version_row_subtyping E1 E2 nil nil\n      (typ_prod T1 T2) (typ_prod T3 T4) knd_type ->\n    valid_tenv version_row_subtyping E1 ->\n    valid_tenv_extension version_row_subtyping E1 E2 ->\n    type_equal version_row_subtyping (E1 & E2) empty nil nil\n      T1 T3 knd_type.\nProof.\n  introv Hs He1 He2.\n  apply subtype_antisymmetric;\n    eauto using valid_tenv_extend,\n      invert_subtype_prod_left,\n      invert_subtype_prod_left_row_contravariant.\nQed.\n\nLemma invert_subtype_prod_right_row :\n  forall E1 E2 T1 T2 T3 T4,\n    subtype version_row_subtyping E1 E2 nil nil\n      (typ_prod T1 T2) (typ_prod T3 T4) knd_type ->\n    valid_tenv version_row_subtyping E1 ->\n    valid_tenv_extension version_row_subtyping E1 E2 ->\n    type_equal version_row_subtyping (E1 & E2) empty nil nil\n      T2 T4 knd_type.\nProof.\n  introv Hs He1 He2.\n  apply subtype_antisymmetric;\n    eauto using valid_tenv_extend,\n      invert_subtype_prod_right,\n      invert_subtype_prod_right_row_contravariant.\nQed.\n\nLemma invert_subtype_constructor_row :\n  forall c cs E1 E2 T1 T2,\n    subtype version_row_subtyping E1 E2 nil nil\n      (typ_constructor c T1) (typ_constructor c T2) (knd_row cs)->\n    valid_tenv version_row_subtyping E1 ->\n    valid_tenv_extension version_row_subtyping E1 E2 ->\n    type_equal version_row_subtyping (E1 & E2) empty nil nil\n      T1 T2 knd_type.\nProof.\n  introv Hs He1 He2.\n  apply subtype_antisymmetric;\n    eauto using valid_tenv_extend,\n      invert_subtype_constructor,\n      invert_subtype_constructor_row_contravariant.\nQed.\n", "meta": {"author": "lpw25", "repo": "row-subtyping", "sha": "b7e1d328387066600cf171fdd51c6eac5c06466e", "save_path": "github-repos/coq/lpw25-row-subtyping", "path": "github-repos/coq/lpw25-row-subtyping/row-subtyping-b7e1d328387066600cf171fdd51c6eac5c06466e/proof/Inversion.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.26209522802950946}}
{"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 PowerPC 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  | 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, v1::v2::nil => add v1 v2\n  | Aglobal s ofs, nil => Ptr (Gl s ofs)\n  | Abased s ofs, v1::nil => add (Ptr (Gl s ofs)) v1\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  | Oaddrsymbol id ofs, nil => Ptr (Gl id ofs)\n  | Oaddrstack ofs, nil => Ptr (Stk ofs)\n  | Ocast8signed, v1 :: nil => sign_ext 8 v1\n  | Ocast16signed, v1 :: nil => sign_ext 16 v1\n  | Oadd, v1::v2::nil => add v1 v2\n  | Oaddimm n, v1::nil => add v1 (I n)\n  | Oaddsymbol id ofs, v1::nil => add (Ptr (Gl id ofs)) v1\n  | Osub, v1::v2::nil => sub v1 v2\n  | Osubimm n, v1::nil => sub (I n) v1\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  | 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  | Onand, v1::v2::nil => notint(and v1 v2)\n  | Onor, v1::v2::nil => notint(or v1 v2)\n  | Onxor, v1::v2::nil => notint(xor v1 v2)\n  | Oandc, v1::v2::nil => and v1 (notint v2)\n  | Oorc, v1::v2::nil => or v1 (notint v2)\n  | Oshl, v1::v2::nil => shl v1 v2\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  | Orolm amount mask, v1::nil => rolm v1 amount mask\n  | Oroli amount mask, v1::v2::nil => or (and v1 (I (Int.not mask))) (rolm v2 amount mask)\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  | Ofloatofwords, v1::v2::nil => floatofwords v1 v2\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  rewrite Int.add_zero_l; eauto with va.\n  fold (Val.sub (Vint i) x). auto with va.\n  apply floatofwords_sound; auto. \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/powerpc/ValueAOp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.26209522802950946}}
{"text": "(*\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *)\nFrom stdpp Require Import base strings gmap stringmap fin_maps.\nFrom iris.base_logic Require Import upred derived.\nFrom iris.base_logic.lib Require Import iprop own.\nFrom iris.algebra Require Import ofe cmra gmap_view.\nFrom iris.proofmode Require Import tactics.\n\nFrom shack Require Import lang progdef subtype ok.\nFrom shack Require Import eval heap modality interp typing.\n\nSection proofs.\n  (* assume a given set of class definitions and their SDT annotations. *)\n  Context `{SDTCVS: SDTClassVarianceSpec}.\n\n  (* Iris semantic context *)\n  Context `{!sem_heapGS Θ}.\n  Notation γ := sem_heap_name.\n\n  Notation \"X ≡≡ Y\" := (∀ (w: value), X w ∗-∗ Y w)%I (at level 50, no associativity).\n\n  Lemma interp_local_tys_update Σthis Σ v Γ Ω ty val :\n    interp_local_tys Σthis Σ Γ Ω -∗\n    interp_type ty Σthis Σ val -∗\n    interp_local_tys Σthis Σ (<[v:=ty]>Γ) (<[v:=val]>Ω).\n  Proof.\n    iIntros \"#[Hthis Hi] #?\".\n    iSplit; first done.\n    iIntros (v' ty') \"H\".\n    rewrite lookup_insert_Some.\n    iDestruct \"H\" as %[[<- <-]|[??]].\n    - iExists _. rewrite lookup_insert. by iSplit.\n    - rewrite lookup_insert_ne; last done. by iApply \"Hi\".\n  Qed.\n\n  (* heap models relation; the semantic heap does\n     not appear because it is hidden in iProp  *)\n  (* Helper defintion to state that fields are correctly modeled *)\n  Definition heap_models_fields\n    (iFs: gmapO string (sem_typeO Θ)) (vs: stringmap value) : iProp Θ :=\n    ⌜dom vs ≡ dom iFs⌝  ∗\n    ∀ f (iF: sem_typeO Θ),\n    iFs !! f ≡ Some iF -∗ ∃ v, (⌜vs !! f = Some v⌝ ∗ iF v).\n\n  Definition heap_models (h : heap) : iProp Θ :=\n    ∃ (sh: gmap loc (prodO tagO (laterO (gmapO string (sem_typeO Θ))))),\n    own γ (gmap_view_auth (DfracOwn 1) sh) ∗ ⌜dom sh = dom h⌝ ∗\n    □ ∀ (ℓ : loc) (t : tag) (vs : stringmap value),\n    ⌜h !! ℓ = Some (t, vs)⌝ -∗\n    ∃ (iFs : gmapO string (sem_typeO Θ)),\n    sh !! ℓ ≡ Some (t, Next iFs) ∗ ▷ heap_models_fields iFs vs.\n\n  (* TODO: try to refactor them up like before *)\n  Lemma heap_models_update_pub Δ Σ h l t1 vs exact_ t σ  f fty orig v:\n    map_Forall (λ _cname, wf_cdef_parent) pdefs →\n    map_Forall (λ _cname, wf_cdef_fields) pdefs →\n    map_Forall (λ _cname, wf_cdef_fields_bounded) pdefs →\n    map_Forall (λ _ : string, wf_cdef_fields_wf) pdefs →\n    map_Forall (λ _cname, wf_field_mono) pdefs →\n    map_Forall (λ _ : string, wf_cdef_mono) pdefs →\n    map_Forall (λ _ : string, wf_cdef_constraints_wf) pdefs →\n    Forall wf_constraint Δ →\n    wf_ty (ClassT exact_ t σ) →\n    h !! l = Some (t1, vs) →\n    has_field f t Public fty orig →\n    is_true exact_ ∨ no_this fty →\n    ∀ t0 Σt0,\n    let Σthis0 := interp_exact_tag interp_type t0 Σt0 in\n    □ interp_env_as_mixed Σt0 -∗\n    □ interp_env_as_mixed Σ -∗\n    □ Σinterp Σthis0 Σ Δ -∗\n    interp_type (ClassT exact_ t σ) Σthis0 Σ (LocV l) -∗\n    interp_type (subst_fty exact_ t σ fty) Σthis0 Σ v -∗\n    heap_models h -∗\n    heap_models (<[l:=(t1, <[f:=v]> vs)]> h).\n  Proof.\n    move => ???????? hwf hheap hf hex.\n    move => t0 Σt0 Σthis0.\n    iIntros \"#hΣt0 #hΣ #hΣΔ #hrecv #hv Hh\".\n    assert (hh : ∃ tdef, pdefs !! t = Some tdef ∧\n      length σ = length tdef.(generics)).\n    { apply wf_tyI in hwf as (? & ? & ? & ?).\n      by eauto.\n    }\n    destruct hh as (tdef & htdef & hlenσ).\n    destruct exact_.\n    - (* Public access on exact type *)\n      rewrite interp_exact_tag_unfold interp_exact_tag_unseal /interp_exact_tag_def /=.\n      iDestruct \"hrecv\" as (? tdef' fields ifields hpure) \"(#hconstr & #hfields & hl)\".\n      destruct hpure as ([= <-] & htdef' & hfields & hdomfields); simplify_eq.\n      iDestruct \"Hh\" as (sh) \"(hown & %hdom & #h)\".\n      iExists sh.\n      iDestruct (sem_heap_own_valid_2 with \"hown hl\") as \"#Hv\".\n      iSplitL \"hown\"; first by iFrame.\n      iSplitR.\n      { iPureIntro.\n        by rewrite hdom dom_insert_lookup_L.\n      }\n      iModIntro.\n      iIntros (l'' t'' vs'') \"%Heq\".\n      rewrite lookup_insert_Some in Heq.\n      destruct Heq as [[<- [= <- <-]] | [hne hl]]; last first.\n      { iApply \"h\".\n        by iPureIntro.\n      }\n      iSpecialize (\"h\" $! l t1 vs with \"[//]\").\n      iDestruct \"h\" as (iFs) \"[#hsh hmodels]\".\n      iExists iFs; iSplit; first done.\n      iRewrite \"Hv\" in \"hsh\".\n      rewrite !option_equivI prod_equivI /=.\n      iDestruct \"hsh\" as \"[%ht #hifs]\".\n      fold_leibniz; subst.\n      iSpecialize (\"hfields\" $! f Public fty orig hf).\n      rewrite later_equivI.\n      iNext.\n      iDestruct \"hfields\" as (iF) \"(#hiF & #hiff)\".\n      iAssert (⌜is_Some (iFs !! f)⌝)%I as \"%hiFs\".\n      { iRewrite -\"hifs\".\n        by iRewrite \"hiF\".\n      }\n      rewrite /heap_models_fields.\n      iDestruct \"hmodels\" as \"[%hdomv #hmodfs]\".\n      iSplit.\n      { iPureIntro.\n        by rewrite -hdomv dom_insert_lookup // -elem_of_dom hdomv elem_of_dom.\n      }\n      iIntros (f' iF') \"#hf'\".\n      destruct (decide (f = f')) as [-> | hne]; last first.\n      { rewrite lookup_insert_ne //.\n        by iApply \"hmodfs\".\n      }\n      rewrite lookup_insert.\n      iExists v; iSplitR; first done.\n      iRewrite -\"hifs\" in \"hf'\".\n      iRewrite \"hiF\" in \"hf'\".\n      rewrite !option_equivI discrete_fun_equivI.\n      iSpecialize (\"hf'\" $! v).\n      iRewrite -\"hf'\".\n      iApply \"hiff\".\n      rewrite interp_type_subst; last first.\n      { apply bounded_subst_this; last by (constructor; by apply bounded_gen_targs).\n        apply has_field_bounded in hf => //.\n        destruct hf as (def' & hdef' & hfty).\n        apply wf_tyI in hwf as (? & ? & hlen & ?); simplify_eq.\n        by rewrite hlen.\n      }\n      iClear \"hconstr hiF hiff hl hifs hmodfs hf' Hv\".\n      rewrite /subst_gen hlenσ.\n      rewrite (interp_type_no_this _ _ _ Σthis0 interp_nothing); first done.\n      apply subst_this_has_no_this => /=.\n      apply forallb_True.\n      by apply gen_targs_has_no_this.\n    - (* property doesn't have `this` *)\n      case: hex => // hnothis.\n      rewrite interp_tag_unfold interp_tag_equiv //; last first.\n      { by rewrite /interp_list fmap_length. }\n      rewrite /interp_tag_alt /=.\n      iDestruct \"hrecv\" as (? t2 tdef' t2def σin Σt2 fields ifields hpure)\n        \"(#hΣt2 & #hconstr & #hinst & #hfields & hl)\".\n      destruct hpure as ([= <-] & htdef' & ht2def & hlenΣt2 & hin & hfields & hdomfields); simplify_eq.\n      iDestruct \"Hh\" as (sh) \"(hown & %hdom & #h)\".\n      iExists sh.\n      iDestruct (sem_heap_own_valid_2 with \"hown hl\") as \"#Hv\".\n      iSplitL \"hown\"; first by iFrame.\n      iSplitR.\n      { iPureIntro.\n        by rewrite hdom dom_insert_lookup_L.\n      }\n      iModIntro.\n      iIntros (l'' t'' vs'') \"%Heq\".\n      rewrite lookup_insert_Some in Heq.\n      destruct Heq as [[<- [= <- <-]] | [hne hl]]; last first.\n      { iApply \"h\".\n        by iPureIntro.\n      }\n      iSpecialize (\"h\" $! l t1 vs with \"[//]\").\n      iDestruct \"h\" as (iFs) \"[#hsh hmodels]\".\n      iExists iFs; iSplit; first done.\n      iRewrite \"Hv\" in \"hsh\".\n      rewrite !option_equivI prod_equivI /=.\n      iDestruct \"hsh\" as \"[%ht #hifs]\".\n      fold_leibniz; subst.\n      (* NEW *)\n      assert (hfield2 : has_field f t1 Public (subst_ty σin fty) orig)\n      by (by eapply has_field_inherits_using).\n      iSpecialize (\"hfields\" $! f Public (subst_ty σin fty) orig hfield2).\n      (* NEW *)\n      rewrite later_equivI.\n      iNext.\n      iDestruct \"hfields\" as (iF) \"(#hiF & #hiff)\".\n      iAssert (⌜is_Some (iFs !! f)⌝)%I as \"%hiFs\".\n      { iRewrite -\"hifs\".\n        by iRewrite \"hiF\".\n      }\n      rewrite /heap_models_fields.\n      iDestruct \"hmodels\" as \"[%hdomv #hmodfs]\".\n      iSplit.\n      { iPureIntro.\n        by rewrite -hdomv dom_insert_lookup // -elem_of_dom hdomv elem_of_dom.\n      }\n      iIntros (f' iF') \"#hf'\".\n      destruct (decide (f = f')) as [-> | hne]; last first.\n      { rewrite lookup_insert_ne //.\n        by iApply \"hmodfs\".\n      }\n      rewrite lookup_insert.\n      iExists v; iSplitR; first done.\n      iRewrite -\"hifs\" in \"hf'\".\n      iRewrite \"hiF\" in \"hf'\".\n      rewrite !option_equivI discrete_fun_equivI.\n      iSpecialize (\"hf'\" $! v).\n      iRewrite -\"hf'\".\n      rewrite interp_type_subst; last first.\n      { apply bounded_subst_this; last by (constructor; by apply bounded_gen_targs).\n        apply has_field_bounded in hf => //.\n        destruct hf as (def' & hdef' & hfty).\n        apply wf_tyI in hwf as (? & ? & hlen & ?); simplify_eq.\n        by rewrite hlen.\n      }\n      iApply \"hiff\".\n      iClear \"hconstr hiF hiff hl hifs hmodfs hf' Hv\".\n      (* NEW *)\n      rewrite /subst_gen -hlenΣt2.\n      iAssert (\n        interp_type (subst_ty σin fty) (interp_exact_tag interp_type t1 Σt2) Σt2 v -∗\n        interp_type\n          (subst_this (ClassT true t1 (gen_targs (length Σt2))) (subst_ty σin fty)) interp_nothing Σt2 v)%I as \"HH\".\n      { iIntros \"HH\".\n        by rewrite -(interp_type_subst_this _ _ interp_nothing).\n      }\n      iApply \"HH\"; iClear \"HH\".\n      rewrite subst_this_no_this_id; last done.\n      rewrite (interp_type_no_this _ _ _ Σthis0 (interp_exact_tag interp_type t1 Σt2)); last done.\n      iDestruct (neg_interp_variance with \"hinst\") as \"hinst2\".\n      iDestruct (interp_with_mono with \"hinst2 hv\") as \"hv2\" => //.\n      { apply has_field_mono in hf => //.\n        destruct hf as (? & ? & []); by simplify_eq.\n      }\n      { by apply has_field_wf in hf. }\n      assert (heq:\n        interp_list interp_nothing Σt2 σin ≡\n        interp_list (interp_exact_tag interp_type t1 Σt2) Σt2 σin).\n      { apply interp_list_no_this.\n        apply inherits_using_wf in hin => //.\n        by destruct hin as (? & ? & ? & ? & ?).\n      }\n      rewrite (interp_type_equivI _ _ _ heq).\n      rewrite interp_type_subst; first done.\n      apply has_field_bounded in hf => //.\n      destruct hf as (? & ? & hf); simplify_eq.\n      apply inherits_using_wf in hin => //.\n      destruct hin as (? & ? & ? & hwfσin & ?); simplify_eq.\n      apply wf_tyI in hwfσin as (? & ? & hlen & ?); simplify_eq.\n      by rewrite hlen.\n  Qed.\n\n  Lemma heap_models_update_priv Δ Σ h l t1 C σ0 cdef vs f fty v:\n    map_Forall (λ _cname, wf_cdef_parent) pdefs →\n    map_Forall (λ _cname, wf_cdef_fields) pdefs →\n    map_Forall (λ _cname, wf_cdef_fields_bounded) pdefs →\n    map_Forall (λ _ : string, wf_cdef_fields_wf) pdefs →\n    map_Forall (λ _cname, wf_field_mono) pdefs →\n    map_Forall (λ _ : string, wf_cdef_mono) pdefs →\n    map_Forall (λ _ : string, wf_cdef_constraints_wf) pdefs →\n    Forall wf_constraint Δ →\n    h !! l = Some (t1, vs) →\n    (* TODO: maybe turn this one into a has_field to share more proof ? *)\n    pdefs !! C = Some cdef →\n    cdef.(classfields) !! f = Some (Private, fty) →\n    ∀ t0 Σt0 tdef0,\n    pdefs !! t0 = Some tdef0 →\n    inherits_using t0 C σ0 →\n    length Σt0 = length tdef0.(generics) →\n    length Σ ≥ length cdef.(generics) →\n    let Σthis0 := interp_exact_tag interp_type t0 Σt0 in\n    ⌜interp_list interp_nothing Σt0 σ0 ≡ take (length cdef.(generics)) Σ⌝ -∗\n    □ interp_env_as_mixed Σt0 -∗\n    □ interp_env_as_mixed Σ -∗\n    □ Σinterp Σthis0 Σ Δ -∗\n    Σthis0 (LocV l) -∗\n    interp_type fty Σthis0 Σ v -∗\n    heap_models h -∗\n    heap_models (<[l:=(t1, <[f:=v]> vs)]> h).\n  Proof.\n    move => ?? hwfb ????? hheap hcdef hf.\n    move => t0 Σt0 tdef0 hdef0 hin hlenΣt0 hge Σthis0.\n    iIntros \"%heqΣ #hΣt0 #hΣ #hΣΔ #hrecv #hv Hh\".\n    rewrite {2}/Σthis0 interp_exact_tag_unseal /interp_exact_tag_def /=.\n    iDestruct \"hrecv\" as (? tdef' fields ifields hpure) \"(#hconstr & #hfields & hl)\".\n    destruct hpure as ([= <-] & htdef' & hfields & hdomfields); simplify_eq.\n    iDestruct \"Hh\" as (sh) \"(hown & %hdom & #h)\".\n    iExists sh.\n    iDestruct (sem_heap_own_valid_2 with \"hown hl\") as \"#Hv\".\n    iSplitL \"hown\"; first by iFrame.\n    iSplitR.\n    { iPureIntro.\n      by rewrite hdom dom_insert_lookup_L.\n    }\n    iModIntro.\n    iIntros (l'' t'' vs'') \"%Heq\".\n    rewrite lookup_insert_Some in Heq.\n    destruct Heq as [[<- [= <- <-]] | [hne hl]]; last first.\n    { iApply \"h\".\n      by iPureIntro.\n    }\n    iSpecialize (\"h\" $! l t1 vs with \"[//]\").\n    iDestruct \"h\" as (iFs) \"[#hsh hmodels]\".\n    iExists iFs; iSplit; first done.\n    iRewrite \"Hv\" in \"hsh\".\n    rewrite !option_equivI prod_equivI /=.\n    iDestruct \"hsh\" as \"[%ht #hifs]\".\n    fold_leibniz; subst.\n    assert (hf0: has_field f t1 Private (subst_ty σ0 fty) C).\n    { eapply has_field_inherits_using => //.\n      change Private with (Private, fty).1.\n      by eapply HasField.\n    }\n    iSpecialize (\"hfields\" $! f Private _ C hf0).\n    rewrite later_equivI.\n    iNext.\n    iDestruct \"hfields\" as (iF) \"(#hiF & #hiff)\".\n    iAssert (⌜is_Some (iFs !! f)⌝)%I as \"%hiFs\".\n    { iRewrite -\"hifs\".\n      by iRewrite \"hiF\".\n    }\n    rewrite /heap_models_fields.\n    iDestruct \"hmodels\" as \"[%hdomv #hmodfs]\".\n    iSplit.\n    { iPureIntro.\n      by rewrite -hdomv dom_insert_lookup // -elem_of_dom hdomv elem_of_dom.\n    }\n    iIntros (f' iF') \"#hf'\".\n    destruct (decide (f = f')) as [-> | hne]; last first.\n    { rewrite lookup_insert_ne //.\n      by iApply \"hmodfs\".\n    }\n    rewrite lookup_insert.\n    iExists v; iSplitR; first done.\n    iRewrite -\"hifs\" in \"hf'\".\n    iRewrite \"hiF\" in \"hf'\".\n    rewrite !option_equivI discrete_fun_equivI.\n    iSpecialize (\"hf'\" $! v).\n    iRewrite -\"hf'\".\n    iApply \"hiff\".\n    (* NEW *)\n    rewrite /subst_gen -hlenΣt0.\n    iAssert (\n      interp_type (subst_ty σ0 fty) (interp_exact_tag interp_type t1 Σt0) Σt0 v -∗\n      interp_type\n        (subst_this (ClassT true t1 (gen_targs (length Σt0))) (subst_ty σ0 fty)) interp_nothing Σt0 v)%I as \"HH\".\n    { iIntros \"HH\".\n      by rewrite -(interp_type_subst_this _ _ interp_nothing).\n    }\n    iApply \"HH\"; iClear \"HH\".\n    iClear \"hconstr hiF hiff hl hifs hmodfs hf' Hv\".\n    apply inherits_using_wf in hin => //.\n    destruct hin as (? & ? & ? & hwf & ?); simplify_eq.\n    rewrite -(interp_type_take fty _ Σ (length cdef.(generics))); first last.\n    { done. }\n    { apply hwfb in hcdef.\n      by apply hcdef in hf.\n    }\n    rewrite (interp_type_equivI _ (take (length cdef.(generics)) Σ) (interp_list interp_nothing Σt0 σ0)); last done.\n    rewrite interp_type_subst; last first.\n    { assert (h0 := hcdef).\n      apply hwfb in h0.\n      apply h0 in hf.\n      apply wf_tyI in hwf as (? & ? & hlen & ?); simplify_eq.\n      by rewrite hlen.\n    }\n    assert (heq_ : interp_list interp_nothing Σt0 σ0 ≡ interp_list Σthis0 Σt0 σ0).\n    { by apply interp_list_no_this. }\n    by rewrite (interp_type_equivI _ _ _ heq_).\n  Qed.\n\n  (* This is dynamic related. Once a [| dynamic |] is open,\n   * we want to use facts about the Σt and Σdyn to show that\n   * Σt models the SDT constraints of the runtime type.\n   *)\n  (* Show that Σt |= Δt ∧ Δsdt^t *)\n  Lemma Σt_models_sdt t A tdef adef σ Σthis  (Σt ΣA: list (interp Θ)):\n    wf_cdefs →\n    pdefs !! t = Some tdef →\n    pdefs !! A = Some adef →\n    length Σt = length tdef.(generics) →\n    length ΣA = length adef.(generics) →\n    inherits_using t A σ →\n    □ interp_as_mixed Σthis -∗\n    □iForall3 interp_variance adef.(generics) (interp_list Σthis Σt σ) ΣA -∗\n    □ interp_env_as_mixed ΣA -∗\n    □ Σinterp Σthis ΣA adef.(constraints) -∗\n    □ Σinterp Σthis ΣA (Δsdt A) -∗\n    □ interp_env_as_mixed Σt -∗\n    □ Σinterp Σthis Σt tdef.(constraints) -∗\n    □ Σinterp Σthis Σt (Δsdt t).\n  Proof.\n    move => wfpdefs htdef hadef hlt htA hin.\n    iIntros \"#hΣthis #hF #hmA #hΣΔA #hΣΔsdtA #hmt #ΣΔt\".\n    assert (hh: Forall wf_ty σ ∧ length adef.(generics) = length σ).\n    { apply inherits_using_wf in hin; try (by apply wfpdefs).\n      destruct hin as (?&?&?&hh&?).\n      split; first by apply wf_ty_classI in hh.\n      apply wf_tyI in hh as (? & ? & ? & ?); by simplify_eq.\n    }\n    destruct hh as [hwfσ hl].\n    assert (hwfc: Forall wf_constraint tdef.(constraints)) by by apply wf_constraints_wf in htdef.\n    pose (Δsdt_A := subst_constraints σ (Δsdt A)).\n    iAssert (□ Σinterp Σthis Σt Δsdt_A)%I as \"#hΣt_sdt_A\".\n    { iAssert (interp_env_as_mixed (interp_list Σthis Σt σ)) as \"hmixed0\".\n      { iIntros (k phi hk w) \"hphi\".\n        apply list_lookup_fmap_inv in hk as [ty0 [-> hty0]].\n        rewrite -(interp_type_unfold _ Σt MixedT w).\n        iApply (submixed_is_inclusion_aux _ Σt ty0 w) => //.\n        rewrite Forall_lookup in hwfσ.\n        by apply hwfσ in hty0.\n      }\n      iAssert (□ Σinterp Σthis (interp_list Σthis Σt σ) adef.(constraints))%I as \"#hΣ0\".\n      { iModIntro.\n        apply inherits_using_ok in hin => //; try by apply wfpdefs.\n        destruct hin as (? & ? & hok); simplify_eq.\n        apply ok_tyI in hok as (? & ? & ? & hok); simplify_eq.\n        iIntros (i c hc w) \"#h\".\n        assert (hb : bounded_constraint (length σ) c).\n        { apply wf_constraints_bounded in hadef => //.\n          rewrite /wf_cdef_constraints_bounded Forall_lookup in hadef.\n          apply hadef in hc.\n          by rewrite -hl.\n        }\n        destruct hb as [].\n        assert (hwf: wf_ty (subst_ty σ c.1)).\n        { apply wf_ty_subst => //.\n          apply wf_constraints_wf in hadef => //.\n          rewrite /wf_cdef_constraints_wf Forall_lookup in hadef.\n          apply hadef in hc.\n          by destruct hc.\n        }\n        apply hok in hc.\n        rewrite -!interp_type_subst //.\n        iApply (subtype_is_inclusion tdef.(constraints)) => //; by apply wfpdefs.\n      }\n      iModIntro; iIntros (i c0 hc w) \"#h\".\n      apply list_lookup_fmap_inv in hc as [c [-> hc]] => /=.\n      assert (hbc : bounded_constraint (length σ) c).\n      { rewrite -hl.\n        by eapply Δsdt_bounded in hc.\n      }\n      destruct hbc as [].\n      rewrite !interp_type_subst //.\n      destruct wfpdefs.\n      by iApply ((Δsdt_variance_interp _ _ _ _ _\n        wf_mono wf_parent wf_constraints_no_this wf_constraints_bounded\n        wf_constraints_wf wf_fields_wf hadef)\n      with \"hΣthis hmixed0 hmA hF hΣ0 hΣΔA hΣΔsdtA\").\n    }\n    iAssert (□ Σinterp Σthis Σt (constraints tdef ++ Δsdt_A))%I as \"#hconstr_\".\n    { iModIntro.\n      by iApply Σinterp_app.\n    }\n    iModIntro.\n    assert (hnewcond: Δentails Aware (tdef.(constraints) ++ Δsdt_A) (Δsdt t)).\n    { apply inherits_using_extends_dyn in hin => //; try by apply wfpdefs.\n      destruct hin as (? & ? & hwf); simplify_eq.\n      move => k c hc.\n      by apply hwf with k.\n    }\n    assert (Forall wf_constraint Δsdt_A).\n    { rewrite Forall_lookup => k c hc.\n      apply list_lookup_fmap_inv in hc as [c0 [-> hc]].\n      apply Δsdt_wf in hc as [].\n      split; by apply wf_ty_subst.\n    }\n    assert (hwf_ : Forall wf_constraint (tdef.(constraints) ++ Δsdt_A)).\n    { apply Forall_app; by split.  }\n    assert (hwfΔ0: Forall wf_constraint (Δsdt t)).\n    { rewrite Forall_lookup; by apply Δsdt_wf. }\n    iIntros (i c hc w) \"#h\".\n    assert (h0 := hc).\n    apply hnewcond in h0.\n    assert (wf_ty c.1).\n    { rewrite Forall_lookup in hwfΔ0.\n      by apply hwfΔ0 in hc as [].\n    }\n    iApply (subtype_is_inclusion with \"hΣthis hmt hconstr_ h\") => //; by apply wfpdefs.\n  Qed.\nEnd proofs.\n", "meta": {"author": "facebookresearch", "repo": "shack", "sha": "e51cfcd3e72a0941feb337f9e152f6c429f3af63", "save_path": "github-repos/coq/facebookresearch-shack", "path": "github-repos/coq/facebookresearch-shack/shack-e51cfcd3e72a0941feb337f9e152f6c429f3af63/theories/soundness/defs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2620952218420959}}
{"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.rcb.spec Require Import base.\nFrom aneris.examples.rcb.model Require Export model_lsec.\n\nSection Local_history_valid.\n  Context `{!anerisG Mdl Σ, !RCB_params}.\n\n  Definition RCBM_lhst_ext (s : gset local_event) :=\n    ∀ e e', e ∈ s → e' ∈ s → le_time e = le_time e' → e = e'.\n\n  Definition RCBM_lhst_times (s : gset local_event) :=\n    ∀ e, e ∈ s → length e.(le_time) = length RCB_addresses.\n\n  Definition RCBM_lhst_origs (i : nat) (s : gset local_event) :=\n    (∀ e, e ∈ s → e.(le_orig) < length RCB_addresses).\n\n  Definition RCBM_lhst_lsec_valid (i : nat) (s : gset local_event) :=\n    (∀ j, j < length RCB_addresses → RCBM_lsec_valid i j s).\n\n  Definition RCBM_lhst_seqids (s : gset local_event) :=\n    ∀ e, e ∈ s → e.(le_seqid) <= size s.\n\n  Record RCBM_lhst_valid (i : nat) (s : gset local_event) : Prop := {\n    RCBM_LHV_bound_at: i < length RCB_addresses;\n    RCBM_LHV_times: RCBM_lhst_times s;\n    RCBM_LHV_ext: RCBM_lhst_ext s;\n    RCBM_LHV_origs: RCBM_lhst_origs i s;\n    RCBM_LHV_secs_valid: RCBM_lhst_lsec_valid i s;\n    RCBM_LHV_seqids: RCBM_lhst_seqids s;\n  }.\n\n  Global Arguments RCBM_LHV_bound_at {_ _} _.\n  Global Arguments RCBM_LHV_times {_ _} _.\n  Global Arguments RCBM_LHV_ext {_ _} _.\n  Global Arguments RCBM_LHV_origs {_ _} _.\n  Global Arguments RCBM_LHV_secs_valid {_ _} _.\n  Global Arguments RCBM_LHV_seqids {_ _} _.\n\n  Lemma in_lhs_time_component e k i s :\n    RCBM_lhst_valid i s →\n    k < length RCB_addresses →\n    e ∈ s →\n    is_Some (e.(le_time) !! k).\n  Proof.\n    intros ???; eapply lookup_lt_is_Some_2; erewrite RCBM_LHV_times; eauto.\n  Qed.\n\n  Lemma RCBM_lsec_empty i s:\n    RCBM_lhst_valid i s →\n    ∀ j', j' < length RCB_addresses →\n          RCBM_lsec j' s = ∅ ↔ ∀ e, e ∈ s → e.(le_time) !! j' = Some 0.\n  Proof.\n    intros Hvli j' Hj'lt.\n    split.\n    - intros Hjs e Hes.\n      pose proof (in_lsec_orig e s Hes) as Hesec.\n      pose proof (RCBM_LHV_origs Hvli e Hes) as Heorig.\n      destruct (lookup_lt_is_Some_2 (le_time e) j') as [k Hk].\n      { rewrite (RCBM_LHV_times Hvli) //. }\n      rewrite Hk.\n      destruct (decide (j' = e.(le_orig))) as [->|].\n      { by rewrite Hjs in Hesec. }\n      pose proof (RCBM_LHV_secs_valid Hvli e.(le_orig) Heorig) as Hesecvl.\n      destruct (decide (i = e.(le_orig))) as [->|].\n      { pose proof (RCBM_LSV_caus_refl Hesecvl j' e Hj'lt) as Hvlrefl.\n        rewrite Hk /= in Hvlrefl.\n        rewrite RCBM_lsec_latest_in_frame_empty in Hvlrefl; last done.\n        apply Hvlrefl; auto. }\n      pose proof (RCBM_LSV_caus Hesecvl j' e Hj'lt) as Hvlirrefl.\n      rewrite Hk /= in Hvlirrefl.\n      rewrite RCBM_lsec_latest_in_frame_empty in Hvlirrefl; last done.\n      f_equal; symmetry; apply le_n_0_eq.\n      apply Hvlirrefl; auto.\n    - destruct (decide (RCBM_lsec j' s = ∅)) as [|Hne]; first done.\n      apply set_choose_L in Hne as [x Hx].\n      pose proof (RCBM_LHV_secs_valid Hvli j' Hj'lt) as Hesecvl.\n      intros He.\n      pose proof (in_lsec_in_lhst _ _ _ Hx) as Hxs.\n      apply He in Hxs.\n      destruct (RCBM_LSV_strongly_complete (RCBM_LHV_times Hvli) Hj'lt Hesecvl 0)\n        as [_ []]; eauto with lia.\n  Qed.\n\n  Definition lsec_sup (j : nat) (s: gset local_event) : nat :=\n    nat_sup (omap (λ e, e.(le_time) !! j) (elements (RCBM_lsec j s))).\n\n  Lemma lsec_sup_empty j : lsec_sup j ∅ = 0.\n  Proof. by rewrite /lsec_sup RCBM_lsec_of_empty elements_empty /=. Qed.\n\n  Lemma elem_of_lsec_lsec_sup_length e i j s :\n    RCBM_lhst_valid i s →\n    j < length RCB_addresses →\n    e ∈ RCBM_lsec j s → length (elements (RCBM_lsec j s)) = lsec_sup j s.\n  Proof.\n    intros Hvl Hj He.\n    assert (∃ e', e' ∈ RCBM_lsec j s ∧\n                  (e'.(le_time) !! j = Some (lsec_sup j s))) as\n        (e' & He'1 & He'2).\n    { assert\n        (lsec_sup j s ∈ (omap (λ e, e.(le_time) !! j)\n                              (elements (RCBM_lsec j s)))) as Hsup.\n      { edestruct (in_lhs_time_component e j) as [p Hp];\n          eauto using in_lsec_in_lhst.\n        eapply (nat_sup_elem_of p).\n        apply elem_of_list_omap.\n          by exists e; split; first apply elem_of_elements. }\n      apply elem_of_list_omap in Hsup as (?&?%elem_of_elements&?); eauto. }\n    apply Nat.le_antisymm.\n    - edestruct le_lt_dec as [Hle|Hlt]; first exact Hle.\n      destruct (RCBM_LSV_comp (RCBM_LHV_secs_valid Hvl j Hj) (S (lsec_sup j s))) as\n          (e'' & He''1 & He''2); first lia.\n      assert (S (lsec_sup j s) ≤ lsec_sup j s); last lia.\n      apply nat_sup_UB.\n      apply elem_of_list_omap.\n        by eexists; split; first apply elem_of_elements.\n    - apply (RCBM_LSV_strongly_complete\n               (RCBM_LHV_times Hvl) Hj (RCBM_LHV_secs_valid Hvl j Hj)); eauto.\n  Qed.\n\nLemma lsec_lsup_length i j s :\n    RCBM_lhst_valid i s →\n    j < length RCB_addresses →\n    length (elements (RCBM_lsec j s)) = lsec_sup j s.\n  Proof.\n    intros Hvl Hj.\n    destruct (decide (RCBM_lsec j s ≡ ∅)) as [Hempty| Hex].\n    - rewrite /lsec_sup. simplify_eq. rewrite Hempty. set_solver.\n    - apply set_choose in Hex as (e' & He').\n      eapply (elem_of_lsec_lsec_sup_length e'); eauto.\n  Qed.\n\n  Lemma RCBM_lsec_causality_lemma i s e p q r :\n    r < length RCB_addresses →\n    RCBM_lhst_valid i s →\n    e ∈ s →\n    0 < p →\n    p ≤ q →\n    e.(le_time) !! r = Some q →\n    ∃ e', e' ∈ RCBM_lsec r s ∧ e'.(le_time) !! r = Some p.\n  Proof.\n    intros Hr His He Hp Hpq Herq.\n    destruct (decide (r = e.(le_orig))) as [Heq|Hreor].\n    { apply (RCBM_LSV_comp (RCBM_LHV_secs_valid His r Hr)).\n      split; first lia.\n      apply (Nat.le_trans _ q); first done.\n      apply (RCBM_LSV_strongly_complete\n               (RCBM_LHV_times His) Hr (RCBM_LHV_secs_valid His r Hr)).\n      exists e; split; last done.\n        by rewrite Heq; apply in_lsec_orig. }\n    assert (RCBM_lsec r s ≠ ∅) as Hrs.\n    { rewrite (RCBM_lsec_empty i); auto.\n      intros Hz.\n      specialize (Hz e He); rewrite Herq in Hz; simplify_eq; lia. }\n    assert (∃ e' p', e' ∈ RCBM_lsec r s ∧ e'.(le_time) !! r = Some p')\n      as (e' & p' & He' & Hp').\n    { apply set_choose_L in Hrs as (e' & He').\n      edestruct (in_lhs_time_component e') as [p' Hp'];\n        eauto using in_lsec_in_lhst. }\n    assert (1 ≤ p').\n    { eapply RCBM_LSV_strongly_complete; [|done| |by eauto].\n      - by eapply RCBM_LHV_times; eauto.\n      - by eapply RCBM_LHV_secs_valid; eauto. }\n    assert (p' ≤ lsec_sup r s).\n    { apply nat_sup_UB.\n      apply elem_of_list_omap.\n      exists e'; split; first apply elem_of_elements; eauto. }\n    destruct (decide (p <= lsec_sup r s)).\n    - assert (1 ≤ p ∧ p <= strings.length (elements (RCBM_lsec r s)))\n        as Hpbounds.\n      { split; first lia.\n        erewrite elem_of_lsec_lsec_sup_length; eauto with lia. }\n      apply (RCBM_LSV_comp (RCBM_LHV_secs_valid His r Hr)); eauto.\n    - assert (lsec_sup r s < p) as HpSup by lia.\n      assert (q <= lsec_sup r s); last lia.\n      pose proof (RCBM_LHV_origs His e He) as Helsec.\n      pose proof (RCBM_LSV_caus (RCBM_LHV_secs_valid His e.(le_orig) Helsec)\n                               r e Hr Hreor) as Hq.\n      rewrite Herq /= in Hq.\n      etrans; first by apply Hq, in_lsec_orig.\n      apply nat_sup_mono.\n      intros a; rewrite !elem_of_list_omap;\n        intros (?&[? ?]%elem_of_list_filter&?); eauto.\n  Qed.\n\n  Lemma empty_lhst_valid i :\n    i < length RCB_addresses →\n    RCBM_lhst_valid i ∅.\n  Proof.\n    split; [done|done|done|done| |done].\n    intros ? ?; apply sections_empty_valid; done.\n  Qed.\n\nEnd Local_history_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/rcb/model/model_lhst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2620952218420959}}
{"text": "(*\n * Vericert: Verified high-level synthesis.\n * Copyright (C) 2020 Yann Herklotz <yann@yannherklotz.com>\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 <https://www.gnu.org/licenses/>.\n *)\n\n(* begin hide *)\nFrom Coq Require Import ZArith.ZArith FSets.FMapPositive Lia.\nFrom compcert Require Export lib.Integers common.Values.\nFrom vericert Require Import Vericertlib.\n(* end hide *)\n\n(** * Value\n\nA [value] is a bitvector with a specific size. We are using the implementation\nof the bitvector by mit-plv/bbv, because it has many theorems that we can reuse.\nHowever, we need to wrap it with an [Inductive] so that we can specify and match\non the size of the [value]. This is necessary so that we can easily store\n[value]s of different sizes in a list or in a map.\n\nUsing the default [word], this would not be possible, as the size is part of the type. *)\n\n(* Definition value : Type := val.\n\n(** ** Value conversions\n\nVarious conversions to different number types such as [N], [Z], [positive] and\n[int], where the last one is a theory of integers of powers of 2 in CompCert. *)\n\nDefinition valueToNat (v : value) : nat :=\n  match v with\n  | value_bool b => Nat.b2n b\n  | value_int i => Z.to_nat (Int.unsigned i)\n  | value_int64 i => Z.to_nat (Int64.unsigned i)\n  end.\n\nDefinition natToValue (n : nat) : value :=\n  value_int (Int.repr (Z.of_nat n)).\n\nDefinition natToValue64 (n : nat) : value :=\n  value_int64 (Int64.repr (Z.of_nat n)).\n\nDefinition valueToN (v : value) : N :=\n  match v with\n  | value_bool b => N.b2n b\n  | value_int i => Z.to_N (Int.unsigned i)\n  | value_int64 i => Z.to_N (Int64.unsigned i)\n  end.\n\nDefinition NToValue (n : N) : value :=\n  value_int (Int.repr (Z.of_N n)).\n\nDefinition NToValue64 (n : N) : value :=\n  value_int64 (Int64.repr (Z.of_N n)).\n\nDefinition ZToValue (z : Z) : value :=\n  value_int (Int.repr z).\n\nDefinition ZToValue64 (z : Z) : value :=\n  value_int64 (Int64.repr z).\n\nDefinition valueToZ (v : value) : Z :=\n  match v with\n  | value_bool b => Z.b2z b\n  | value_int i => Int.signed i\n  | value_int64 i => Int64.signed i\n  end.\n\nDefinition uvalueToZ (v : value) : Z :=\n  match v with\n  | value_bool b => Z.b2z b\n  | value_int i => Int.unsigned i\n  | value_int64 i => Int64.unsigned i\n  end.\n\nDefinition posToValue (p : positive) : value :=\n  value_int (Int.repr (Z.pos p)).\n\nDefinition posToValue64 (p : positive) : value :=\n  value_int64 (Int64.repr (Z.pos p)).\n\nDefinition valueToPos (v : value) : positive :=\n  match v with\n  | value_bool b => 1%positive\n  | value_int i => Z.to_pos (Int.unsigned i)\n  | value_int64 i => Z.to_pos (Int64.unsigned i)\n  end.\n\nDefinition intToValue (i : Integers.int) : value := value_int i.\n\nDefinition int64ToValue (i : Integers.int64) : value := value_int64 i.\n\nDefinition valueToInt (v : value) : Integers.int :=\n  match v with\n  | value_bool b => Int.repr (if b then 1 else 0)\n  | value_int i => i\n  | value_int64 i => Int.repr (Int64.unsigned i)\n  end.\n\n(*Definition ptrToValue (i : ptrofs) : value :=\n  value_int (Ptrofs.to_int i).\n\nDefinition valueToPtr (i : value) : Integers.ptrofs :=\n  Ptrofs.of_int i.\n\nDefinition valToValue (v : Values.val) : option value :=\n  match v with\n  | Values.Vint i => Some (intToValue i)\n  | Values.Vint64 i => Some (intToValue i)\n  | Values.Vptr b off => Some (ptrToValue off)\n  | Values.Vundef => Some (ZToValue 0%Z)\n  | _ => None\n  end.\n\n(** Convert a [value] to a [bool], so that choices can be made based on the\nresult. This is also because comparison operators will give back [value] instead\nof [bool], so if they are in a condition, they will have to be converted before\nthey can be used. *)\n\nDefinition valueToBool (v : value) : bool :=\n  if Z.eqb (uvalueToZ v) 0 then false else true.\n\nDefinition boolToValue (b : bool) : value :=\n  natToValue (if b then 1 else 0).\n\n(** ** Arithmetic operations *)\n\nDefinition unify_word (sz1 sz2 : nat) (w1 : word sz2): sz1 = sz2 -> word sz1.\nintros; subst; assumption. Defined.\n\nLemma unify_word_unfold :\n  forall sz w,\n  unify_word sz sz w eq_refl = w.\nProof. auto. Qed.\n\nInductive val_value_lessdef: val -> value -> Prop :=\n| val_value_lessdef_int:\n    forall i v',\n    i = valueToInt v' ->\n    val_value_lessdef (Vint i) v'\n| val_value_lessdef_ptr:\n    forall b off v',\n    off = valueToPtr v' ->\n    val_value_lessdef (Vptr b off) v'\n| lessdef_undef: forall v, val_value_lessdef Vundef v.\n\nInductive opt_val_value_lessdef: option val -> value -> Prop :=\n| opt_lessdef_some:\n    forall v v', val_value_lessdef v v' -> opt_val_value_lessdef (Some v) v'\n| opt_lessdef_none: forall v, opt_val_value_lessdef None v.\n\nLemma valueToZ_ZToValue :\n  forall z,\n  (Int.min_signed <= z <= Int.max_signed)%Z ->\n  valueToZ (ZToValue z) = z.\nProof. auto using Int.signed_repr. Qed.\n\nLemma uvalueToZ_ZToValue :\n  forall z,\n  (0 <= z <= Int.max_unsigned)%Z ->\n  uvalueToZ (ZToValue z) = z.\nProof. auto using Int.unsigned_repr. Qed.\n\nLemma valueToPos_posToValue :\n  forall v,\n  0 <= Z.pos v <= Int.max_unsigned ->\n  valueToPos (posToValue v) = v.\nProof.\n  unfold valueToPos, posToValue.\n  intros. rewrite Int.unsigned_repr.\n  apply Pos2Z.id. assumption.\nQed.\n\nLemma valueToInt_intToValue :\n  forall v,\n  valueToInt (intToValue v) = v.\nProof. auto. Qed.\n\nLemma valToValue_lessdef :\n  forall v v',\n    valToValue v = Some v' ->\n    val_value_lessdef v v'.\nProof.\n  intros.\n  destruct v; try discriminate; constructor.\n  unfold valToValue in H. inversion H.\n  unfold valueToInt. unfold intToValue in H1. auto.\n  inv H. symmetry. unfold valueToPtr, ptrToValue. apply Ptrofs.of_int_to_int. trivial.\nQed.\n\nLtac simplify_val := repeat (simplify; unfold uvalueToZ, valueToPtr, Ptrofs.of_int, valueToInt, intToValue,\n                                       ptrToValue in *)\n\n(*Ltac crush_val := simplify_val; try discriminate; try congruence; try lia; liapp; try assumption.*)\n*)\n", "meta": {"author": "ymherklotz", "repo": "vericert", "sha": "c3de945fa463aa9a2ad0804eb8f67e40f585eb3a", "save_path": "github-repos/coq/ymherklotz-vericert", "path": "github-repos/coq/ymherklotz-vericert/vericert-c3de945fa463aa9a2ad0804eb8f67e40f585eb3a/src/hls/ValueVal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2620890340207818}}
{"text": "(**\n\nThis file describes the representation of modeling language.\n\nAuthor: Bowen Zhang.\n\nDate : 2021.07.24\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(*---------- the block primitive operations ----------*)\nInductive bval : Type :=\n  | bval_create : bval\n  | bval_append : bval  \n  | bval_get : bval\n  | bval_delete : bval\n  | bval_bsize : bval.\n\n(*---------- the file primitive operations ----------*)\nInductive fval : Type :=\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  (* some aux file operation *)\n  | fval_buffer: fval\n  | fval_buffer_list : fval\n  | fval_rev_blist : 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_list_rev : prim    (*reverse a list*)\n  | val_list_app : prim.   (*append a 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_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\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 \"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\n(* ########################### The Evaluation Rules ########################### *)\nOpen Scope liblist_scope.\n\nInductive eval : heap -> trm -> heap -> val -> Prop :=\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_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  (*--------- 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_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  (*------------ 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\n(*----------- block prim operations -----------*)\n\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_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\n\n\n\n(*==============================================================*)\n(* ############ Notations of the language (to improve the readability) #################### *)\nModule NotationForTrm.\n\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 \"'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\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 \"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 \"'()\" := val_unit : trm_scope.\n\nEnd NotationForTrm.", "meta": {"author": "PKUTCS-CBS", "repo": "CBSVerifi", "sha": "2a71f58046fd77a9d13a4ab567417248eac34c43", "save_path": "github-repos/coq/PKUTCS-CBS-CBSVerifi", "path": "github-repos/coq/PKUTCS-CBS-CBSVerifi/CBSVerifi-2a71f58046fd77a9d13a4ab567417248eac34c43/Language.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2620890270608427}}
{"text": "Set Implicit Arguments.\n\nRequire Import Bedrock.Platform.Cito.GoodModuleDec.\n\nSection TopSection.\n\n  Notation MName := SyntaxModule.Name.\n  Notation FName := SyntaxFunc.Name.\n  Notation Funcs := SyntaxModule.Functions.\n\n  Require Import Bedrock.Platform.Cito.IsGoodModule.\n  Require Import Bedrock.Platform.Cito.GoodModule.\n\n  Require Import Bedrock.Platform.Cito.ListFacts4.\n  Require Import Coq.Lists.List.\n\n  Require Import Coq.Bool.Bool.\n  Require Import Bedrock.Platform.Cito.GeneralTactics.\n  Require Import Bedrock.Platform.Cito.GeneralTactics2.\n\n  Require Import Coq.Program.Basics.\n  Require Import Bedrock.Platform.Cito.GoodFunc.\n\n  Require Import Bedrock.Platform.Cito.WellFormed.\n\n  Lemma is_good_size_sound : forall n, is_good_size n = true -> goodSize n.\n    intros.\n    unfold is_good_size in *.\n    Local Open Scope N_scope.\n    destruct (ZArith_dec.Dcompare_inf (N.of_nat n ?= Npow2 32)) as [ [Hc | Hc] | Hc ]; rewrite Hc in *.\n    discriminate.\n    eapply N.compare_lt_iff in Hc; eauto.\n    discriminate.\n  Qed.\n\n  Hint Constructors args_not_too_long.\n\n  Lemma is_arg_len_ok_sound : forall s, is_arg_len_ok s = true -> wellformed s.\n    unfold wellformed.\n    induction s; simpl; intuition eauto.\n    eapply andb_true_iff in H; openhyp; eauto.\n    eapply andb_true_iff in H; openhyp; eauto.\n    econstructor.\n    eapply is_good_size_sound; eauto.\n  Qed.\n  Require Import Bedrock.Platform.Cito.ListFacts3.\n  Require Import Bedrock.Platform.Cito.NoUninitDecFacts.\n\n  Lemma is_good_func_sound : forall f, is_good_func f = true -> GoodFunc f.\n    unfold is_good_func.\n    intros.\n    repeat (eapply andb_true_iff in H; openhyp).\n    econstructor.\n    eauto.\n    split.\n    eapply is_no_uninited_sound; eauto.\n    split.\n    eapply is_arg_len_ok_sound; eauto.\n    eapply is_good_size_sound; eauto.\n  Qed.\n\n  Lemma is_good_funcs_sound : forall ls, is_good_funcs (map Core ls) = true -> Forall (compose GoodFunc Core) ls.\n    intros.\n    unfold is_good_funcs in *.\n    eapply Forall_forall.\n    intros.\n    eapply forallb_forall in H.\n    2 : eapply in_map; eauto.\n    unfold compose.\n    eapply is_good_func_sound; eauto.\n  Qed.\n  Require Import Bedrock.Platform.Cito.NameDecoration.\n\n  Lemma is_good_module_sound : forall m, is_good_module m = true -> IsGoodModule m.\n    intros.\n    unfold is_good_module in *.\n    destruct m; simpl in *.\n    eapply andb_true_iff in H.\n    openhyp.\n    eapply andb_true_iff in H.\n    openhyp.\n    econstructor; simpl.\n    eapply is_good_module_name_sound; eauto.\n    split.\n    eapply is_good_funcs_sound; eauto.\n    eapply is_no_dup_sound; eauto.\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/GoodModuleDecFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2620890270608427}}
{"text": "Require Import Ensembles.\nRequire Import syntax.\nRequire Import infrastructure.\nRequire Import infrastructure_props.\nRequire Import dom_list.\nRequire Import analysis.\nRequire Import typings.\nRequire Import typings_props.\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 Lattice.\nRequire Import Floats.\nRequire Import AST.\nRequire Import Maps.\nRequire Import opsem.\nRequire Import opsem_props.\nRequire Import opsem_wf.\n\n(************************************************************)\n(* This file proves that the dynamic value of a pure definition is invariant \n   in the scope the definition dominates. *)\n\nModule OpsemDom. Section OpsemDom.\n\nContext `{GVsSig : GenericValues}.\n\nExport Opsem.\nExport OpsemProps.\nImport AtomSet.\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).\nNotation \"vidxs @@ vidxss\" := (in_list_gvs vidxs vidxss)\n  (at level 43, right associativity).\n\n(* A predicate that checks purity: Select/GEP are impure because of \n   non-deterministics *)\nDefinition pure_cmd (c:cmd) : Prop :=\nmatch c with\n| insn_bop _ _ _ _ _\n| insn_fbop _ _ _ _ _\n| insn_extractvalue _ _ _ _ _\n| insn_insertvalue _ _ _ _ _ _\n| insn_trunc _ _ _ _ _\n| insn_ext _ _ _ _ _\n| insn_cast _ _ _ _ _\n| insn_icmp _ _ _ _ _\n| insn_fcmp _ _ _ _ _ => True\n| _ => False\nend.\n\n(* Check if gv is the semantics value of the command c. *)\nDefinition eval_rhs TD gl (lc:GVsMap) (c:cmd) (gv:GVs) : Prop :=\nmatch c with\n| insn_bop _ bop0 sz v1 v2 => BOP TD lc gl bop0 sz v1 v2 = Some gv\n| insn_fbop _ fbop fp v1 v2 => FBOP TD lc gl fbop fp v1 v2  = Some gv\n| insn_extractvalue id t v idxs _ =>\n    exists gv0, getOperandValue TD v lc gl = Some gv0 /\\\n                extractGenericValue TD t gv0 idxs = Some gv\n| insn_insertvalue _ t v t' v' idxs =>\n    exists gv1, exists gv2,\n      getOperandValue TD v lc gl = Some gv1 /\\\n      getOperandValue TD v' lc gl = Some gv2 /\\\n      insertGenericValue TD t gv1 idxs t' gv2 = Some gv\n| insn_trunc _ truncop t1 v1 t2 => TRUNC TD lc gl truncop t1 v1 t2 = Some gv\n| insn_ext _ extop t1 v1 t2 => EXT TD lc gl extop t1 v1 t2 = Some gv\n| insn_cast _ castop t1 v1 t2 => CAST TD lc gl castop t1 v1 t2 = Some gv\n| insn_icmp _ cond0 t v1 v2 => ICMP TD lc gl cond0 t v1 v2 = Some gv\n| insn_fcmp _ fcond fp v1 v2 => FCMP TD lc gl fcond fp v1 v2 = Some gv\n| _ => ~ pure_cmd c\nend.\n\n(* ids0 includes the definitions that strictly dominate the current program\n   counter. For any definition in ids0 that is defined by a command, the\n   dynamic value of the definition equals the result of the command; \n   and the command is defined in a reachable block. *)\nDefinition wf_GVs TD gl (f:fdef) (lc:GVsMap) (id1:id) (gvs1:GVs) : Prop :=\nforall c1,\n  lookupInsnViaIDFromFdef f id1 = Some (insn_cmd c1) ->\n  (eval_rhs TD gl lc c1 gvs1 /\\\n   forall b1, cmdInFdefBlockB c1 f b1 = true -> isReachableFromEntry f b1).\n\nDefinition wf_defs TD gl (f:fdef) (lc:GVsMap)(ids0:list atom) : Prop :=\nforall id0 gvs0,\n  In id0 ids0 ->\n  lookupAL _ lc id0 = Some gvs0 ->\n  wf_GVs TD gl f lc id0 gvs0.\n\nDefinition wf_ExecutionContext TD gl (ps:list product) (ec:ExecutionContext)\n  : Prop :=\nlet '(mkEC f b cs tmn lc als) := ec in\nmatch cs with\n| nil =>\n    match inscope_of_tmn f b tmn with\n    | Some ids => wf_defs TD gl f lc ids\n    | None => False\n    end\n| c::_ =>\n    match inscope_of_cmd f b c with\n    | Some ids => wf_defs TD gl f lc ids\n    | None => False\n    end\nend.\n\nFixpoint wf_ECStack TD gl (ps:list product) (ecs:ECStack) : Prop :=\nmatch ecs with\n| nil => True\n| ec::ecs' =>\n    wf_ExecutionContext TD gl ps ec /\\ wf_ECStack TD gl ps ecs'\nend.\n\nDefinition wf_State (cfg:Config) (S:State) : Prop :=\nlet '(mkCfg s (los, nts) ps gl _ ) := cfg in\nlet '(mkState ecs _) := S in\nwf_ECStack (los,nts) gl ps ecs.\n\n(* Properties of eval_rhs *)\nRequire Import Maps.\n\nLemma eval_rhs_updateValuesForNewBlock : forall TD gl c lc gv rs,\n  (forall i, i `in` dom rs -> ~ In i (getCmdOperands c)) ->\n  (eval_rhs TD gl (updateValuesForNewBlock rs lc) c gv <->\n   eval_rhs TD gl lc c gv).\nProof.\n  induction rs; simpl; intros.\n    split; auto.\n\nLtac eru_tac1 :=\nlet foo a i1 i2 rs H :=\n  destruct (id_dec a i1); subst; try solve [\n    assert (i1 `in` add i1 (dom rs)) as IN; auto;\n    apply H in IN; contradict IN; auto |\n\n    rewrite <- lookupAL_updateAddAL_neq; auto;\n    destruct (id_dec a i2); subst; try solve [\n      assert (i2 `in` add i2 (dom rs)) as IN; auto;\n      apply H in IN; contradict IN; auto |\n  \n      rewrite <- lookupAL_updateAddAL_neq; auto\n    ]\n  ] in\nmatch goal with\n| rs : list (atom * GVs),\n  H : forall i : atom, i `in` add ?a (dom ?rs) -> ~ (?i1 = i \\/ ?i2 = i \\/ False)\n  |- _ =>\n  match goal with\n  | |- _ <-> match lookupAL _ _ ?i1 with\n             | ret _ =>\n               match lookupAL _ _ ?i2 with\n               | ret _ => _\n               | merror => _\n               end\n             | merror => _\n             end = _ => foo a i1 i2 rs H\n  | |- _ <-> (exists _ : _, exists _ : _,\n             lookupAL _ _ ?i1 = ret _ /\\ lookupAL _ _ ?i2 = ret _ /\\ _) =>\n      foo a i1 i2 rs H\n  end\nend.\n\nLtac eru_tac2 :=\nlet foo a i1 rs H :=\n  destruct (id_dec a i1); subst; try solve [\n    assert (i1 `in` add i1 (dom rs)) as IN; auto;\n    apply H in IN; contradict IN; auto |\n    rewrite <- lookupAL_updateAddAL_neq; auto\n  ] in\nmatch goal with\n| rs : list (atom * GVs),\n  H : forall i : atom, i `in` add ?a (dom ?rs) -> ~ (?i1 = i \\/ False)\n  |- _ =>\n  match goal with\n  | |- _ <-> match lookupAL _ _ ?i1 with\n             | ret _ =>\n               match const2GV _ _ _ with\n               | ret _ => _\n               | merror => _\n               end\n             | merror => _\n             end = _ => foo a i1 rs H\n  | |- _ <-> (exists _ : _, exists _ : _,\n             lookupAL _ _ ?i1 = ret _ /\\ const2GV _ _ _ = ret _ /\\ _) =>\n      foo a i1 rs H\n  end\nend.\n\nLtac eru_tac3 :=\nlet foo a i1 rs H :=\n  destruct (id_dec a i1); subst; try solve [\n    assert (i1 `in` add i1 (dom rs)) as IN; auto;\n    apply H in IN; contradict IN; auto |\n    rewrite <- lookupAL_updateAddAL_neq; auto\n  ] in\nmatch goal with\n| rs : list (atom * GVs),\n  H : forall i : atom, i `in` add ?a (dom ?rs) -> ~ (?i1 = i \\/ False)\n  |- _ =>\n  match goal with\n  | |- _ <-> match const2GV _ _ _ with\n             | ret _ =>\n               match lookupAL _ _ ?i1 with\n               | ret _ => _\n               | merror => _\n               end\n             | merror => _\n             end = _ => foo a i1 rs H\n  | |- _ <-> (exists _ : _, exists _ : _,\n             const2GV _ _ _ = ret _ /\\ lookupAL _ _ ?i1 = ret _ /\\ _) =>\n      foo a i1 rs H\n  end\nend.\n\nLtac eru_tac4 :=\nlet foo a i1 rs H :=\n  destruct (id_dec a i1); subst; try solve [\n    assert (i1 `in` add i1 (dom rs)) as IN; auto;\n    apply H in IN; contradict IN; auto |\n    rewrite <- lookupAL_updateAddAL_neq; auto\n  ] in\nmatch goal with\n| rs : list (atom * GVs),\n  H : forall i : atom, i `in` add ?a (dom ?rs) -> ~ (?i1 = i \\/ False)\n  |- _ =>\n  match goal with\n  | |- _ <-> match lookupAL _ _ ?i1 with\n             | ret _ => _\n             | merror => _\n             end = _ => foo a i1 rs H\n  | |- _ <-> (exists _ : _, lookupAL _ _ ?i1 = ret _ /\\ _) => foo a i1 rs H\n  end\nend.\n\n    destruct a as [a g].\n    destruct c as [i0 b s0 v v0|i0 f0 f1 v v0|i0 t v l2|i0 t v t0 v0 l2|\n                   i0 t v ?|i0 t v|i0 t v ?|i0 t v ?|i0 t v v0 ?|i0 i1 t v l2|\n                   i0 t t0 v t1|i0 e t v t0|i0 c t v t0|i0 c t v v0|\n                   i0 f0 f1 v v0|i0 v t v0 v1|i0 n c t v p]; simpl;\n      unfold BOP, FBOP, TRUNC, EXT, ICMP, FCMP, CAST; try solve [ \n        auto |\n        destruct v as [i1|c1]; destruct v0 as [i2|c2]; simpl in *;\n          try solve [auto | eru_tac1 | eru_tac2 | eru_tac3] |\n        destruct v as [i1|c1]; simpl in *; try solve [auto | eru_tac4]\n      ].\nQed.\n\nLemma eval_rhs_updateAddAL : forall TD gl id1 gvs1 lc gv c,\n  ~ In id1 (getCmdOperands c) ->\n  (eval_rhs TD gl (@updateAddAL GVs lc id1 gvs1) c gv <->\n   eval_rhs TD gl lc c gv).\nProof.\n  destruct c as [i0 b s0 v v0|i0 f0 f1 v v0|i0 t v l2|i0 t v t0 v0 l2|\n                 i0 t v ?|i0 t v|i0 t v ?|i0 t v ?|i0 t v v0 ?|i0 i1 t v l2|\n                 i0 t t0 v t1|i0 e t v t0|i0 c t v t0|i0 c t v v0|\n                 i0 f0 f1 v v0|i0 v t v0 v1|i0 n c t v p]; \n    simpl; intros; try solve [split; auto].\n    unfold BOP.\n    destruct v as [i1|c1]; destruct v0 as [i2|c2]; simpl in *; try solve [split; auto].\n      destruct (id_dec id1 i1); subst.\n        contradict H; auto.\n        rewrite <- lookupAL_updateAddAL_neq; auto.\n        destruct (id_dec id1 i2); subst.\n          contradict H; auto.\n          rewrite <- lookupAL_updateAddAL_neq; try solve [auto | split; auto].\n      destruct (id_dec id1 i1); subst.\n        contradict H; auto.\n        rewrite <- lookupAL_updateAddAL_neq; try solve [auto | split; auto].\n      destruct (id_dec id1 i2); subst.\n        contradict H; auto.\n        rewrite <- lookupAL_updateAddAL_neq; try solve [auto | split; auto].\n\n    unfold FBOP.\n    destruct v as [i1|c1]; destruct v0 as [i2|c2]; simpl in *; try solve [split; auto].\n      destruct (id_dec id1 i1); subst.\n        contradict H; auto.\n        rewrite <- lookupAL_updateAddAL_neq; auto.\n        destruct (id_dec id1 i2); subst.\n          contradict H; auto.\n          rewrite <- lookupAL_updateAddAL_neq; try solve [auto | split; auto].\n      destruct (id_dec id1 i1); subst.\n        contradict H; auto.\n        rewrite <- lookupAL_updateAddAL_neq; try solve [auto | split; auto].\n      destruct (id_dec id1 i2); subst.\n        contradict H; auto.\n        rewrite <- lookupAL_updateAddAL_neq; try solve [auto | split; auto].\n\n    destruct v as [i1|c1]; simpl in *; try solve [split; auto].\n      destruct (id_dec id1 i1); subst.\n        contradict H; auto.\n        rewrite <- lookupAL_updateAddAL_neq; auto.\n        split; auto.\n\n    destruct v as [i1|c1]; destruct v0 as [i2|c2]; simpl in *; try solve [split; auto].\n      destruct (id_dec id1 i1); subst.\n        contradict H; auto.\n        rewrite <- lookupAL_updateAddAL_neq; auto.\n        destruct (id_dec id1 i2); subst.\n          contradict H; auto.\n          rewrite <- lookupAL_updateAddAL_neq; try solve [auto | split; auto].\n      destruct (id_dec id1 i1); subst.\n        contradict H; auto.\n        rewrite <- lookupAL_updateAddAL_neq; try solve [auto | split; auto].\n      destruct (id_dec id1 i2); subst.\n        contradict H; auto.\n        rewrite <- lookupAL_updateAddAL_neq; try solve [auto | split; auto].\n\n    unfold TRUNC.\n    destruct v as [i1|c1]; simpl in *; try solve [split; auto].\n      destruct (id_dec id1 i1); subst.\n        contradict H; auto.\n        rewrite <- lookupAL_updateAddAL_neq; auto.\n        split; auto.\n\n    unfold EXT.\n    destruct v as [i1|c1]; simpl in *; try solve [split; auto].\n      destruct (id_dec id1 i1); subst.\n        contradict H; auto.\n        rewrite <- lookupAL_updateAddAL_neq; auto.\n        split; auto.\n\n    unfold CAST.\n    destruct v as [i1|c1]; simpl in *; try solve [split; auto].\n      destruct (id_dec id1 i1); subst.\n        contradict H; auto.\n        rewrite <- lookupAL_updateAddAL_neq; auto.\n        split; auto.\n\n    unfold ICMP.\n    destruct v as [i1|c1]; destruct v0 as [i2|c2]; simpl in *; try solve [split; auto].\n      destruct (id_dec id1 i1); subst.\n        contradict H; auto.\n        rewrite <- lookupAL_updateAddAL_neq; auto.\n        destruct (id_dec id1 i2); subst.\n          contradict H; auto.\n          rewrite <- lookupAL_updateAddAL_neq; try solve [auto | split; auto].\n      destruct (id_dec id1 i1); subst.\n        contradict H; auto.\n        rewrite <- lookupAL_updateAddAL_neq; try solve [auto | split; auto].\n      destruct (id_dec id1 i2); subst.\n        contradict H; auto.\n        rewrite <- lookupAL_updateAddAL_neq; try solve [auto | split; auto].\n\n    unfold FCMP.\n    destruct v as [i1|c1]; destruct v0 as [i2|c2]; simpl in *; try solve [split; auto].\n      destruct (id_dec id1 i1); subst.\n        contradict H; auto.\n        rewrite <- lookupAL_updateAddAL_neq; auto.\n        destruct (id_dec id1 i2); subst.\n          contradict H; auto.\n          rewrite <- lookupAL_updateAddAL_neq; try solve [auto | split; auto].\n      destruct (id_dec id1 i1); subst.\n        contradict H; auto.\n        rewrite <- lookupAL_updateAddAL_neq; try solve [auto | split; auto].\n      destruct (id_dec id1 i2); subst.\n        contradict H; auto.\n        rewrite <- lookupAL_updateAddAL_neq; try solve [auto | split; auto].\nQed.\n\nLemma impure_cmd__eval_rhs: forall TD gl lc c gv3,\n  ~ pure_cmd c -> eval_rhs TD gl lc c gv3.\nProof.\n  destruct c; simpl; intros; try solve [auto | contradict H; auto].\nQed.\n\n(* Properties of wf_GVs *)\nLemma getIncomingValuesForBlockFromPHINodes_spec1 : forall TD S M f  \n    gl lc id1 l3 cs tmn ps lc' gvs b,\n  Some lc' = getIncomingValuesForBlockFromPHINodes TD ps b gl lc ->\n  In id1 (getPhiNodesIDs ps) ->\n  Some (stmts_intro ps cs tmn) = lookupBlockViaLabelFromFdef f l3 ->\n  wf_fdef S M f -> uniqFdef f ->\n  lookupAL _ lc' id1 = Some gvs ->\n  wf_GVs TD gl f lc id1 gvs.\nProof.\n  intros. intros c1 Hin. eapply phinode_isnt_cmd in H1; eauto. inv H1.\nQed.\n\nLemma state_tmn_typing : forall TD S M f l1 ps1 cs1 tmn1 defs id1 lc gv gl,\n  isReachableFromEntry f (l1, stmts_intro ps1 cs1 tmn1) ->\n  wf_insn S M f (l1, stmts_intro ps1 cs1 tmn1) (insn_terminator tmn1) ->\n  Some defs = inscope_of_tmn f (l1, stmts_intro ps1 cs1 tmn1) tmn1 ->\n  wf_defs TD gl f lc defs ->\n  wf_fdef S M f -> uniqFdef f ->\n  In id1 (getInsnOperands (insn_terminator tmn1)) ->\n  lookupAL _ lc id1 = Some gv ->\n  wf_GVs TD gl f lc id1 gv /\\ In id1 defs.\nProof.\n  intros TD S M f l1 ps1 cs1 tmn1 defs id1 lc gv gl Hreach HwfInstr \n    Hinscope HwfDefs HwfF HuniqF HinOps Hlkup.\n  apply wf_insn__wf_insn_base in HwfInstr;\n    try solve [unfold isPhiNode; simpl; auto].\n  inv HwfInstr. find_wf_operand_list. subst. find_wf_operand_by_id.\n\n  assert (In id1 defs) as Hin.\n    eapply terminator_operands__in_scope; eauto.\n  auto.\nQed.\n\nLemma state_cmd_typing : forall S M f b c defs id1 lc gv TD gl,\n  NoDup (getStmtsLocs (snd b)) ->\n  isReachableFromEntry f b ->\n  wf_insn S M f b (insn_cmd c) ->\n  Some defs = inscope_of_cmd f b c ->\n  wf_defs TD gl f lc defs ->\n  wf_fdef S M f -> uniqFdef f ->\n  In id1 (getInsnOperands (insn_cmd c)) ->\n  lookupAL _ lc id1 = Some gv ->\n  wf_GVs TD gl f lc id1 gv /\\ In id1 defs.\nProof.\n  intros S M f b c defs id1 lc gv TD gl Hnodup Hreach HwfInstr Hinscope \n    HwfDefs HwfF HuniqF HinOps Hlkup.\n  apply wf_insn__wf_insn_base in HwfInstr;\n    try solve [unfold isPhiNode; simpl; auto].\n  inv HwfInstr. find_wf_operand_list. subst. find_wf_operand_by_id.\n\n  assert (In id1 defs) as Hin.\n    eapply cmd_operands__in_scope; eauto.\n  auto.\nQed.\n\nLemma uniqFdef__lookupInsnViaIDFromBlocks : forall bs1 id1 c1 c2,\n  lookupInsnViaIDFromBlocks bs1 id1 = ret insn_cmd c1 ->\n  lookupInsnViaIDFromBlocks bs1 id1 = ret insn_cmd c2 ->\n  c1 = c2.\nProof. congruence. Qed.\n\nLtac OP__wf_gvs :=\nintros;\nmatch goal with\n| F1: fdef, Huniq: uniqFdef ?F1, id1:id, \n  Hin: blockInFdefB\n          (?l3,\n          stmts_intro ?ps1 (?cs1' ++ ?c0 :: ?cs1) ?tmn1)\n          ?F1 = true\n |- _ =>\n  destruct F1 as [fh1 bs1];\n  assert (lookupInsnViaIDFromBlocks bs1 id1 =\n    Some (insn_cmd c0)) as Hlk1; try solve\n    [apply uniqF__uniqBlocks in Huniq; inv Huniq;\n     eapply InBlocksB__lookupInsnViaIDFromBlocks; eauto];\n  intros c1 Hlkc1;\n  assert (c1 = c0) as EQ; try solve\n    [eapply uniqFdef__lookupInsnViaIDFromBlocks in Hlk1; eauto];\n  subst;\n  split; try solve [\n    auto |\n    intros b1 H;\n    assert ((l3, stmts_intro ps1 (cs1' ++ c0 :: cs1) tmn1) = b1) as EQ;\n      try solve \n        [eapply blockInFdefB__cmdInFdefBlockB__eqBlock; eauto using in_middle];\n    subst; auto\n  ]\nend.\n\nLemma BOP__wf_gvs : forall\n  (F1 : fdef) (v : value) (v0 : value) lc\n  (id1 : id) (bop0 : bop) gvs3 TD sz0 gl\n  (H11 : BOP TD lc gl bop0 sz0 v v0 = ret gvs3)\n  (Huniq : uniqFdef F1) l3 ps1 cs1' cs1 tmn1\n  (Hreach: isReachableFromEntry F1\n    (l3, stmts_intro ps1 (cs1' ++ insn_bop id1 bop0 sz0 v v0 :: cs1) tmn1))\n  (Hin : blockInFdefB\n           (l3, stmts_intro ps1 (cs1' ++ insn_bop id1 bop0 sz0 v v0 :: cs1) tmn1)\n           F1 = true),\n  wf_GVs TD gl F1 lc id1 gvs3.\nProof. OP__wf_gvs. Qed.\n\nLemma FBOP__wf_gvs : forall\n  (F1 : fdef) (v : value) (v0 : value) lc\n  (id1 : id) (fbop0 : fbop) gvs3 TD fp0 gl\n  (H11 : FBOP TD lc gl fbop0 fp0 v v0 = ret gvs3)\n  (Huniq : uniqFdef F1) l3 ps1 cs1' cs1 tmn1\n  (Hreach: isReachableFromEntry F1\n    (l3, stmts_intro ps1 (cs1' ++ insn_fbop id1 fbop0 fp0 v v0 :: cs1) tmn1))\n  (Hin : blockInFdefB\n           (l3, stmts_intro ps1 (cs1' ++ insn_fbop id1 fbop0 fp0 v v0 :: cs1) tmn1)\n           F1 = true),\n  wf_GVs TD gl F1 lc id1 gvs3.\nProof. OP__wf_gvs. Qed.\n\nLemma extractvalue__wf_gvs : forall\n  (F1 : fdef) (v : value) lc\n  id1 t idxs gv TD gl gv0\n  (J1 : getOperandValue TD v lc gl = Some gv0)\n  (J2 : extractGenericValue TD t gv0 idxs = Some gv)\n  (Huniq : uniqFdef F1) l3 ps1 cs1' cs1 tmn1 t'\n  (Hreach: isReachableFromEntry F1\n    (l3, stmts_intro ps1 (cs1' ++ insn_extractvalue id1 t v idxs t' :: cs1) tmn1))\n  (Hin : blockInFdefB\n          (l3, stmts_intro ps1 \n            (cs1' ++ insn_extractvalue id1 t v idxs t' :: cs1) tmn1)\n          F1 = true),\n  wf_GVs TD gl F1 lc id1 gv.\nProof. \n  OP__wf_gvs.\n    simpl. exists gv0. split; auto.\nQed.\n\nLemma insertvalue__wf_gvs : forall\n  (F1 : fdef) (v v' : value) lc\n  id1 t t' idxs gv1 gv2 TD gl gv0\n  (J1 : getOperandValue TD v lc gl = Some gv1)\n  (J2 : getOperandValue TD v' lc gl = Some gv2)\n  (J3 : insertGenericValue TD t gv1 idxs t' gv2 = Some gv0)\n  (Huniq : uniqFdef F1) l3 ps1 cs1' cs1 tmn1\n  (Hreach: isReachableFromEntry F1\n    (l3, stmts_intro ps1 (cs1' ++ insn_insertvalue id1 t v t' v' idxs :: cs1)\n      tmn1))\n  (Hin : blockInFdefB\n          (l3, stmts_intro ps1\n            (cs1' ++ insn_insertvalue id1 t v t' v' idxs :: cs1) tmn1)\n          F1 = true),\n  wf_GVs TD gl F1 lc id1 gv0.\nProof. \n  OP__wf_gvs.\n    simpl. exists gv1. exists gv2. split; auto.\nQed.\n\nLemma TRUNC__wf_gvs : forall\n  (F1 : fdef) truncop0 t1 v1 t2 lc\n  (id1 : id) gvs TD gl\n  (H11 : TRUNC TD lc gl truncop0 t1 v1 t2 = Some gvs)\n  (Huniq : uniqFdef F1) l3 ps1 cs1' cs1 tmn1\n  (Hreach: isReachableFromEntry F1\n    (l3, stmts_intro ps1 (cs1' ++ insn_trunc id1 truncop0 t1 v1 t2 :: cs1) tmn1))\n  (Hin : blockInFdefB\n           (l3, stmts_intro ps1 (cs1' ++ insn_trunc id1 truncop0 t1 v1 t2 :: cs1)\n             tmn1) F1 = true),\n  wf_GVs TD gl F1 lc id1 gvs.\nProof. OP__wf_gvs. Qed.\n\nLemma EXT__wf_gvs : forall\n  (F1 : fdef) extop0 t1 v1 t2 lc\n  (id1 : id) gvs TD gl\n  (H11 : EXT TD lc gl extop0 t1 v1 t2 = Some gvs)\n  (Huniq : uniqFdef F1) l3 ps1 cs1' cs1 tmn1\n  (Hreach: isReachableFromEntry F1\n    (l3, stmts_intro ps1 (cs1' ++ insn_ext id1 extop0 t1 v1 t2 :: cs1) tmn1))\n  (Hin : blockInFdefB\n           (l3, stmts_intro ps1 (cs1' ++ insn_ext id1 extop0 t1 v1 t2 :: cs1)\n             tmn1) F1 = true),\n  wf_GVs TD gl F1 lc id1 gvs.\nProof. OP__wf_gvs. Qed.\n\nLemma CAST__wf_gvs : forall\n  (F1 : fdef) castop0 t1 v1 t2 lc\n  (id1 : id) gvs TD gl\n  (H11 : CAST TD lc gl castop0 t1 v1 t2 = Some gvs)\n  (Huniq : uniqFdef F1) l3 ps1 cs1' cs1 tmn1\n  (Hreach: isReachableFromEntry F1\n    (l3, stmts_intro ps1 (cs1' ++ insn_cast id1 castop0 t1 v1 t2 :: cs1) tmn1))\n  (Hin : blockInFdefB\n           (l3, stmts_intro ps1 (cs1' ++ insn_cast id1 castop0 t1 v1 t2 :: cs1)\n             tmn1) F1 = true),\n  wf_GVs TD gl F1 lc id1 gvs.\nProof. OP__wf_gvs. Qed.\n\nLemma ICMP__wf_gvs : forall\n  (F1 : fdef) (v : value) (v0 : value) lc\n  (id1 : id) (cnd0 : cond) gvs3 TD t0 gl\n  (H11 : ICMP TD lc gl cnd0 t0 v v0 = ret gvs3)\n  (Huniq : uniqFdef F1) l3 ps1 cs1' cs1 tmn1\n  (Hreach: isReachableFromEntry F1\n    (l3, stmts_intro ps1 (cs1' ++ insn_icmp id1 cnd0 t0 v v0 :: cs1) tmn1))\n  (Hin : blockInFdefB\n           (l3, stmts_intro ps1 (cs1' ++ insn_icmp id1 cnd0 t0 v v0 :: cs1) tmn1)\n           F1 = true),\n  wf_GVs TD gl F1 lc id1 gvs3.\nProof. OP__wf_gvs. Qed.\n\nLemma FCMP__wf_gvs : forall\n  (F1 : fdef) (v1 v2 : value) lc\n  (id1 : id) fcond0 fp0 gvs3 TD gl\n  (H11 : FCMP TD lc gl fcond0 fp0 v1 v2 = ret gvs3)\n  (Huniq : uniqFdef F1) l3 ps1 cs1' cs1 tmn1\n  (Hreach: isReachableFromEntry F1\n    (l3, stmts_intro ps1 (cs1' ++ insn_fcmp id1 fcond0 fp0 v1 v2 :: cs1) tmn1))\n  (Hin : blockInFdefB\n           (l3, stmts_intro ps1 (cs1' ++ insn_fcmp id1 fcond0 fp0 v1 v2 :: cs1)\n           tmn1) F1 = true),\n  wf_GVs TD gl F1 lc id1 gvs3.\nProof. OP__wf_gvs. Qed.\n\nDefinition wf_impure_id (f:fdef) (id1:id) : Prop :=\nforall c1,\n  lookupInsnViaIDFromFdef f id1 = Some (insn_cmd c1) ->\n  (forall b1, cmdInFdefBlockB c1 f b1 = true -> isReachableFromEntry f b1).\n\nLemma wf_impure_id__wf_gvs: forall F c TD gl lc gv b,\n  uniqFdef F -> wf_impure_id F (getCmdLoc c) -> ~ pure_cmd c ->\n  cmdInBlockB c b -> blockInFdefB b F ->\n  wf_GVs TD gl F lc (getCmdLoc c) gv.\nProof.\n  intros. intros x Hlkx.\n  assert (c = x) as EQ. \n    destruct b as [? []].\n    simpl in H2.\n    apply IngetCmdsIDs__lookupCmdViaIDFromFdef with (c1:=c) in H3; auto.\n      congruence.\n      apply InCmdsB_in; auto.\n  subst.\n  split.\n    apply impure_cmd__eval_rhs; auto.\n    unfold wf_impure_id in H0. eauto.\nQed.\n\n(* Properties of wf_defs *)\nLemma wf_defs_eq : forall ids2 ids1 TD gl F' lc',\n  set_eq ids1 ids2 ->\n  wf_defs TD gl F' lc' ids1 ->\n  wf_defs TD gl F' lc' ids2.\nProof.\n  intros.\n  intros id2 gvs1 Hin Hlk.\n  destruct H as [J1 J2]. eauto.\nQed.\n\nLemma wf_defs_br_aux : forall TD gl S M lc l' ps' cs' lc' F tmn' b\n  (Hreach : isReachableFromEntry F b)\n  (Hreach': isReachableFromEntry F (l', stmts_intro ps' cs' tmn'))\n  (Hlkup : Some (stmts_intro ps' cs' tmn') = lookupBlockViaLabelFromFdef F l')\n  (Hswitch : switchToNewBasicBlock TD (l', stmts_intro ps' cs' tmn') b gl lc =\n    ret lc')\n  (t : list atom)\n  (Hwfdfs : wf_defs TD gl F lc t)\n  (ids0' : list atom)\n  (HwfF : wf_fdef S M F) (HuniqF: uniqFdef F)\n  (contents' : ListSet.set atom)\n  (Heqdefs' : contents' = AlgDom.sdom F l')\n  (Hinscope : (fold_left (inscope_of_block F l') contents'\n    (ret (getPhiNodesIDs ps' ++ getArgsIDsOfFdef F)) = ret ids0'))\n  (Hinc : incl (ListSet.set_diff eq_atom_dec ids0' (getPhiNodesIDs ps')) t),\n  wf_defs TD gl F lc' ids0'.\nProof.\n  intros.\n  unfold switchToNewBasicBlock in Hswitch. simpl in Hswitch.\n  intros id1 gvs Hid1 Hlk.\n  remember (getIncomingValuesForBlockFromPHINodes TD ps' b gl lc) as R1.\n  destruct R1 as [rs|]; inv Hswitch.\n  destruct (In_dec eq_atom_dec id1 (getPhiNodesIDs ps')) as [Hin | Hnotin].\n  Case \"id1 in ps'\".\n    apply updateValuesForNewBlock_spec6 in Hlk; auto.\n      eapply getIncomingValuesForBlockFromPHINodes_spec1 with (gvs:=gvs) in HeqR1;\n        eauto.\n      intros c1 Hlkc1. eapply phinode_isnt_cmd in Hlkup; eauto. inv Hlkup.\n\n      eapply getIncomingValuesForBlockFromPHINodes_spec6 in HeqR1; eauto.\n\n  Case \"id1 notin ps'\".\n    assert (Hnotin' := Hnotin).\n    apply ListSet.set_diff_intro with (x:=ids0')(Aeq_dec:=eq_atom_dec) in Hnotin;\n      auto.\n    apply Hinc in Hnotin. assert (HeqR1':=HeqR1).\n    eapply getIncomingValuesForBlockFromPHINodes_spec8 in HeqR1; eauto.\n    eapply updateValuesForNewBlock_spec7 in Hlk; eauto.\n    apply Hwfdfs in Hlk; auto.\n      intros c1 Hlkc1.\n      assert (~ In id1 (getArgsIDsOfFdef F)) as Hnotina.\n        apply getInsnLoc__notin__getArgsIDs' in Hlkc1; auto.\n      destruct (@Hlk c1) as [Hlkc1' Hreach'']; auto.\n      split; auto.\n      apply eval_rhs_updateValuesForNewBlock; auto.\n         intros i0 Hin.\n         destruct (in_dec id_dec i0 (getCmdOperands c1)); auto.\n           elimtype False.\n           eapply operands_of_cmd__cannot_be__phis_that_cmd_doms; intuition eauto.\n             apply in_app_or in H as []; auto.\n             eapply getIncomingValuesForBlockFromPHINodes_spec7 in HeqR1'; eauto.\n             \nQed.\n\nLemma inscope_of_tmn_br_aux : forall S M F l3 ps cs tmn ids0 ps' cs' tmn'\n  l0 lc lc' gl TD (Hreach : isReachableFromEntry F (l3, stmts_intro ps cs tmn)),\nwf_fdef S M F -> uniqFdef F ->\nblockInFdefB (l3, stmts_intro ps cs tmn) F = true ->\nIn l0 (successors_terminator tmn) ->\nSome ids0 = inscope_of_tmn F (l3, stmts_intro ps cs tmn) tmn ->\nSome (stmts_intro ps' cs' tmn') = lookupBlockViaLabelFromFdef F l0 ->\nswitchToNewBasicBlock TD (l0, stmts_intro ps' cs' tmn')\n  (l3, stmts_intro ps cs tmn) gl lc = Some lc' ->\nwf_defs TD gl F lc ids0 ->\nexists ids0',\n  match cs' with\n  | nil => Some ids0' = inscope_of_tmn F (l0, stmts_intro ps' cs' tmn') tmn'\n  | c'::_ => Some ids0' = inscope_of_cmd F (l0, stmts_intro ps' cs' tmn') c'\n  end /\\\n  incl (ListSet.set_diff eq_atom_dec ids0' (getPhiNodesIDs ps')) ids0 /\\\n  wf_defs TD gl F lc' ids0'.\nProof.\n  intros S M F l3 ps cs tmn ids0 ps' cs' tmn' l0 lc lc' gl TD Hreach\n    HwfF HuniqF HBinF Hsucc Hinscope Hlkup Hswitch Hwfdfs.\n  symmetry in Hlkup.\n  assert (J:=Hlkup).\n  apply lookupBlockViaLabelFromFdef_inv in J; auto.\n  unfold inscope_of_tmn in Hinscope.\n  unfold inscope_of_tmn. unfold inscope_of_cmd, inscope_of_id.\n  destruct F as [fh bs].\n\n  assert (incl (AlgDom.sdom (fdef_intro fh bs) l0)\n    (l3::(AlgDom.sdom (fdef_intro fh bs) l3))) as Hsub.\n    clear - HBinF Hsucc HuniqF HwfF.\n    eapply dom_successors; eauto.\n\n  assert (isReachableFromEntry (fdef_intro fh bs) (l0, stmts_intro ps' nil tmn'))\n    as Hreach'.\n    eapply isReachableFromEntry_successors in Hlkup; eauto.\n\n  assert (J1:=AlgDom.sdom_in_bound fh bs l0).\n  destruct fh as [f t i0 a v].\n  apply fold_left__bound_blocks with (init:=getPhiNodesIDs ps' ++\n      getCmdsIDs nil ++ getArgsIDs a)(bs:=bs)(l0:=l0)\n      (fh:=fheader_intro f t i0 a v) in J1; auto.\n  destruct J1 as [r J1].\n  exists r. \n\n  assert (incl (ListSet.set_diff eq_atom_dec r (getPhiNodesIDs ps')) ids0)\n    as Jinc.\n    clear - Hinscope J1 Hsub HBinF HuniqF.\n    eapply inscope_of_tmn__inscope_of_cmd_at_beginning in J1; eauto. \n\n  destruct cs'.\n  Case \"cs'=nil\".\n    simpl.\n    split; auto.\n    split; auto.\n      subst. simpl in J1. simpl_env in J1.\n      eapply wf_defs_br_aux in Hswitch; intuition eauto.\n\n  Case \"cs'<>nil\".\n    assert (~ In (getCmdLoc c) (getPhiNodesIDs ps')) as Hnotin.\n      apply uniqFdef__uniqBlockLocs in J; auto.\n      simpl in J. \n      eapply NoDup_disjoint in J; simpl; eauto.\n    rewrite init_scope_spec1; auto.\n    unfold cmds_dominates_cmd. simpl.\n    destruct (eq_atom_dec (getCmdLoc c) (getCmdLoc c)) as [_ | n];\n      try solve [contradict n; auto].\n    split; auto.\n    split; auto.\n      subst. eapply wf_defs_br_aux in Hswitch; intuition eauto.\nQed.\n\nLemma inscope_of_tmn_br_uncond : forall S M F l3 ps cs ids0 ps' cs' tmn' \n  l0 lc lc' bid TD gl,\nisReachableFromEntry F (l3, stmts_intro ps cs (insn_br_uncond bid l0)) ->\nwf_fdef S M F -> uniqFdef F ->\nblockInFdefB (l3, stmts_intro ps cs (insn_br_uncond bid l0)) F = true ->\nSome ids0 = inscope_of_tmn F (l3, stmts_intro ps cs (insn_br_uncond bid l0))\n  (insn_br_uncond bid l0) ->\nSome (stmts_intro ps' cs' tmn') = lookupBlockViaLabelFromFdef F l0 ->\nswitchToNewBasicBlock TD (l0, stmts_intro ps' cs' tmn')\n  (l3, stmts_intro ps cs (insn_br_uncond bid l0)) gl lc = Some lc' ->\nwf_defs TD gl F lc ids0 ->\nexists ids0',\n  match cs' with\n  | nil => Some ids0' = inscope_of_tmn F (l0, stmts_intro ps' cs' tmn') tmn'\n  | c'::_ => Some ids0' = inscope_of_cmd F (l0, stmts_intro ps' cs' tmn') c'\n  end /\\\n  incl (ListSet.set_diff eq_atom_dec ids0' (getPhiNodesIDs ps')) ids0 /\\\n  wf_defs TD gl F lc' ids0'.\nProof.\n  intros.\n  eapply inscope_of_tmn_br_aux; eauto.\n  simpl. auto.\nQed.\n\nLemma inscope_of_tmn_br : forall S M F l0 ps cs bid l1 l2 ids0 ps' cs' \n  tmn' Cond c lc lc' gl TD,\nisReachableFromEntry F (l0, stmts_intro ps cs (insn_br bid Cond l1 l2)) ->\nwf_fdef S M F -> uniqFdef F ->\nblockInFdefB (l0, stmts_intro ps cs (insn_br bid Cond l1 l2)) F = true ->\nSome ids0 = inscope_of_tmn F (l0, stmts_intro ps cs (insn_br bid Cond l1 l2))\n  (insn_br bid Cond l1 l2) ->\nSome (stmts_intro ps' cs' tmn') =\n       (if isGVZero TD c\n        then lookupBlockViaLabelFromFdef F l2\n        else lookupBlockViaLabelFromFdef F l1) ->\nswitchToNewBasicBlock TD (if isGVZero TD c then l2 else l1, \n                          stmts_intro ps' cs' tmn')\n  (l0, stmts_intro ps cs (insn_br bid Cond l1 l2)) gl lc = Some lc' ->\nwf_defs TD gl F lc ids0 ->\nexists ids0',\n  match cs' with\n  | nil => Some ids0' = inscope_of_tmn F (if isGVZero TD c then l2 else l1, \n                                          stmts_intro ps' cs' tmn') tmn'\n  | c'::_ => Some ids0' = inscope_of_cmd F (if isGVZero TD c then l2 else l1,\n                                            stmts_intro ps' cs' tmn') c'\n  end /\\\n  incl (ListSet.set_diff eq_atom_dec ids0' (getPhiNodesIDs ps')) ids0 /\\\n  wf_defs TD gl F lc' ids0'.\nProof.\n  intros.\n  remember (isGVZero TD c) as R.\n  destruct R; eapply inscope_of_tmn_br_aux; eauto; simpl; auto.\nQed.\n\nLemma wf_defs_updateAddAL : forall S M g1 lc' ids1 ids2 F1 B1 l3 ps1 \n  cs tmn1 c TD gl (HinCs: In c cs)\n  (Hreach: isReachableFromEntry F1 (l3, stmts_intro ps1 cs tmn1))\n  (HBinF1: blockInFdefB (l3, stmts_intro ps1 cs tmn1) F1 = true)\n  (HBinF2: blockInFdefB B1 F1 = true)\n  (HwfF1 : wf_fdef S M F1) (HuniqF:uniqFdef F1) \n  (HcInB : cmdInBlockB c B1 = true)\n  (Hinscope : ret ids1 = inscope_of_id F1 B1 (getCmdLoc c)),\n  wf_defs TD gl F1 lc' ids1 ->\n  set_eq (getCmdLoc c::ids1) ids2 ->\n  wf_GVs TD gl F1 lc' (getCmdLoc c) g1 ->\n  wf_defs TD gl F1 (updateAddAL _ lc' (getCmdLoc c) g1) ids2.\nProof.\n  intros S M g1 lc' ids1 ids2 F1 B1 l3 ps1 cs tmn1 c TD gl HinCs Hreach \n    HBinF1 HBinF2 HwfF1 HuniqF HcInB HInscope HwfDefs Heq Hwfgvs.\n  intros id1 gvs1 Hin Hlk.\n  destruct Heq as [Hinc1 Hinc2].\n  apply Hinc2 in Hin.\n  simpl in Hin.\n  intros c1 Hlkc1.\n  assert (id1 = getCmdLoc c1) as EQ.\n    apply lookupInsnViaIDFromFdef__eqid in Hlkc1. simpl in Hlkc1. auto.\n  subst.\n  assert (J:=Hlkc1).\n  eapply wf_fdef__wf_insn_base in J; eauto.\n  destruct J as [b1 HwfI].\n  inv HwfI.\n  destruct (eq_dec (getCmdLoc c) (getCmdLoc c1)).\n  Case \"1\".\n    rewrite e in *.\n    rewrite lookupAL_updateAddAL_eq in Hlk; auto.\n    find_wf_operand_list. subst.\n    inv Hlk.\n    destruct (@Hwfgvs c1) as [Heval Hreach']; auto.\n    split; auto.\n    apply eval_rhs_updateAddAL; auto.\n      eapply cmd_doesnt_use_self; eauto.\n\n  Case \"2\".\n    destruct Hin as [Eq | Hin]; try solve [contradict n; auto].\n    rewrite <- lookupAL_updateAddAL_neq in Hlk; auto.\n    find_wf_operand_list. subst.\n    assert (Hlk':=Hlk).\n    apply HwfDefs in Hlk; auto.\n    destruct (@Hlk c1) as [Heval Hreach']; auto.\n    split; auto.\n    apply eval_rhs_updateAddAL; auto.\n      eapply cmd_doesnt_use_nondom_operands; eauto.\nQed.\n\n(*********************************************)\n(** * Preservation *)\n\nLtac destruct_wf :=\nmatch goal with\n| Hwfcfg: OpsemPP.wf_Config ?cfg, Hwfpp1: OpsemPP.wf_State ?cfg _ |- _ =>\n  destruct Hwfcfg as [_ [_ [HwfSystem HmInS]]];\n  destruct Hwfpp1 as\n    [_ [[Hreach1 [HBinF1 [HFinPs1 [_ [_ [l3 [ps3 [cs3' Heq1]]]]]]]]\n     [_ HwfCall]]]; subst\nend.\n\nLemma preservation_pure_cmd_updated_case : forall\n  (F : fdef)\n  (B : block)\n  (lc : GVsMap)\n  (gv3 : GVs)\n  (cs : list cmd)\n  (tmn : terminator)\n  id0 c0 los nts gl Mem0 als EC fs Ps S\n  (Hid : Some id0 = getCmdID c0) (Hpure : pure_cmd c0)\n  (Hwfgv : wf_GVs (los, nts) gl F lc id0 gv3) St Cfg\n  (Hcfg: Cfg = {| CurSystem := S;\n                CurTargetData := (los, nts);\n                CurProducts := Ps;\n                Globals := gl;\n                FunTable := fs |})\n  (Hst: St = {| ECS := {| CurFunction := F;\n                            CurBB := B;\n                            CurCmds := c0 :: cs;\n                            Terminator := tmn;\n                            Locals := lc;\n                            Allocas := als |} :: EC;\n                  Mem := Mem0 |})\n   (Hwfcfg : OpsemPP.wf_Config Cfg) (Hwfpp1 : OpsemPP.wf_State Cfg St)\n   (HwfS1 : wf_State Cfg St),\n   wf_State Cfg\n     {|\n     ECS := {|\n            CurFunction := F;\n            CurBB := B;\n            CurCmds := cs;\n            Terminator := tmn;\n            Locals := updateAddAL GVs lc id0 gv3;\n            Allocas := als |} :: EC;\n     Mem := Mem0 |}.\nProof.\n  intros. subst. destruct_wf.\n  destruct HwfS1 as [Hinscope1 HwfEC]; subst. \n  unfold wf_ExecutionContext in *.\n  remember (inscope_of_cmd F (l3, stmts_intro ps3 (cs3' ++ c0 :: cs) tmn) c0)\n    as R1.\n  assert (HeqR1':=HeqR1).\n  unfold inscope_of_cmd, inscope_of_id in HeqR1'.\n  assert (uniqFdef F) as HuniqF.\n    eapply wf_system__uniqFdef; eauto.\n  destruct R1; try solve [inversion Hinscope1]. \n  repeat (split; try solve [auto | congruence]).\n      assert (Hid':=Hid).\n      symmetry in Hid.\n      apply getCmdLoc_getCmdID in Hid.\n      subst. unfold wf_ExecutionContext in *.\n      assert (cmdInBlockB c0 (l3, stmts_intro ps3 (cs3' ++ c0 :: cs) tmn) = true)\n        as Hin.\n        simpl. apply In_InCmdsB. apply in_middle.\n      assert (NoDup (getStmtsLocs (stmts_intro ps3 (cs3' ++ c0 :: cs) tmn))) \n        as Hnotin.\n        eapply wf_system__uniq_block with (f:=F) in HwfSystem; eauto.\n      destruct cs; simpl_env in *.\n      Case \"1.1.1\".\n        apply inscope_of_cmd_tmn in HeqR1; auto.\n        destruct HeqR1 as [ids2 [J1 J2]].\n        rewrite <- J1.\n        assert (In c0 (cs3' ++ [c0])) as HinCs.\n          apply in_or_app. right. simpl. auto.\n        assert (Hwfc := HBinF1).\n        eapply wf_system__wf_cmd with (c:=c0) in Hwfc;\n          eauto.\n        rewrite <- Hid' in J2.\n        assert (HwfF:=HFinPs1). eapply wf_system__wf_fdef in HwfF; eauto.\n        eapply wf_defs_updateAddAL; eauto.\n\n      Case \"1.1.2\".\n        apply inscope_of_cmd_cmd in HeqR1; auto.\n        destruct HeqR1 as [ids2 [J1 J2]].\n        rewrite <- J1.\n        assert (In c0 (cs3' ++ [c0] ++ [c] ++ cs)) as HinCs.\n          apply in_or_app. right. simpl. auto.\n        assert (Hwfc := HBinF1).\n        eapply wf_system__wf_cmd with (c:=c0) in Hwfc;\n          eauto.\n        rewrite <- Hid' in J2.\n        assert (HwfF:=HFinPs1). eapply wf_system__wf_fdef in HwfF; eauto.\n        eapply wf_defs_updateAddAL; eauto.\nQed.\n\nLemma preservation_cmd_non_updated_case : forall\n  (S : system)\n  (los : layouts)\n  (nts : namedts)\n  (Ps : list product)\n  (F : fdef)\n  (B : block)\n  (lc : GVsMap)\n  (gl : GVMap)\n  (fs : GVMap)\n  (EC : list ExecutionContext)\n  (cs : list cmd)\n  (tmn : terminator)\n  (Mem0 : mem)\n  (als : list mblock)\n  c0\n  (Hid : getCmdID c0 = None) St Cfg\n  (Hcfg: Cfg = {| CurSystem := S;\n                CurTargetData := (los, nts);\n                CurProducts := Ps;\n                Globals := gl;\n                FunTable := fs |})\n  (Hst: St = {| ECS := {| CurFunction := F;\n                            CurBB := B;\n                            CurCmds := c0 :: cs;\n                            Terminator := tmn;\n                            Locals := lc;\n                            Allocas := als |} :: EC;\n                  Mem := Mem0 |})\n  (Hwfcfg : OpsemPP.wf_Config Cfg) (Hwfpp1 : OpsemPP.wf_State Cfg St)\n  (HwfS1 : wf_State Cfg St),\n  wf_State Cfg\n     {|\n     ECS := {|\n            CurFunction := F;\n            CurBB := B;\n            CurCmds := cs;\n            Terminator := tmn;\n            Locals := lc;\n            Allocas := als |} :: EC;\n     Mem := Mem0 |}.\nProof.\n  intros. subst. destruct_wf.\n  destruct HwfS1 as [Hinscope1 HwfEC]; subst. \n  unfold wf_ExecutionContext in *.\n  remember (inscope_of_cmd F (l3, stmts_intro ps3 (cs3' ++ c0 :: cs) tmn) c0)\n    as R1.\n  destruct R1; try solve [inversion Hinscope1].\n  repeat (split; try solve [auto | congruence]).\n      assert (NoDup (getStmtsLocs (stmts_intro ps3 (cs3' ++ c0 :: cs) tmn))) \n        as Hnotin.\n        eapply wf_system__uniq_block with (f:=F) in HwfSystem; eauto.\n      unfold wf_ExecutionContext in *.\n      destruct cs; simpl_env in *.\n      Case \"1.1.1\".\n        apply inscope_of_cmd_tmn in HeqR1; auto.\n        destruct HeqR1 as [ids2 [J1 J2]].\n        rewrite <- J1.\n        assert (In c0 (cs3' ++ [c0])) as HinCs.\n          apply in_or_app. right. simpl. auto.\n        assert (Hwfc := HBinF1).\n        eapply wf_system__wf_cmd with (c:=c0) in Hwfc;\n          eauto.\n        rewrite Hid in J2.\n        eapply wf_defs_eq; eauto.\n\n      Case \"1.1.2\".\n        apply inscope_of_cmd_cmd in HeqR1; auto.\n        destruct HeqR1 as [ids2 [J1 J2]].\n        rewrite <- J1.\n        assert (In c0 (cs3' ++ [c0] ++ [c] ++ cs)) as HinCs.\n          apply in_or_app. right. simpl. auto.\n        assert (Hwfc := HBinF1).\n        eapply wf_system__wf_cmd with (c:=c0) in Hwfc;\n          eauto.\n        rewrite Hid in J2.\n        eapply wf_defs_eq ; eauto.\nQed.\n\nLemma preservation_dbCall_case : forall fid fa rt la va lb gvs los\n  nts s lc Ps gl\n  (Huniq: uniqFdef (fdef_intro (fheader_intro fa rt fid la va) lb))\n  (HwfF: wf_fdef s (module_intro los nts Ps) \n    (fdef_intro (fheader_intro fa rt fid la va) lb))\n  (Hinit : initLocals (los,nts) la gvs = Some lc),\n  wf_defs (los,nts) gl (fdef_intro (fheader_intro fa rt fid la va) lb) lc\n    (getArgsIDs la).\nProof.\n  intros.\n  assert (incl nil (bound_blocks lb)) as J.\n    intros x J. inv J.\n  intros id1 gvs1 Hin Hlklc.\n  intros x Hlkx. \n  contradict Hin.\n    apply getInsnLoc__notin__getArgsIDs' in Hlkx; auto.\nQed.\n\nLemma preservation_impure_cmd_updated_case : forall\n  (F : fdef)\n  (B : block)\n  (lc : GVsMap)\n  (gv3 : GVs)\n  (cs : list cmd)\n  (tmn : terminator)\n  id0 c0 los nts gl Mem0 als EC fs Ps S\n  (Hid : Some id0 = getCmdID c0) (Hinpure: ~ pure_cmd c0)\n  (Hwfgv : wf_impure_id F id0) St Cfg\n  (Hcfg: Cfg = {| CurSystem := S;\n                CurTargetData := (los, nts);\n                CurProducts := Ps;\n                Globals := gl;\n                FunTable := fs |})\n  (Hst: St = {| ECS := {| CurFunction := F;\n                            CurBB := B;\n                            CurCmds := c0 :: cs;\n                            Terminator := tmn;\n                            Locals := lc;\n                            Allocas := als |} :: EC;\n                  Mem := Mem0 |})\n  (Hwfcfg : OpsemPP.wf_Config Cfg) (Hwfpp1 : OpsemPP.wf_State Cfg St)\n  (HwfS1 : wf_State Cfg St),\n   wf_State Cfg\n     {|\n     ECS := {|\n            CurFunction := F;\n            CurBB := B;\n            CurCmds := cs;\n            Terminator := tmn;\n            Locals := updateAddAL GVs lc id0 gv3;\n            Allocas := als |} :: EC;\n     Mem := Mem0 |}.\nProof.\n  intros. subst. destruct_wf.\n  destruct HwfS1 as [Hinscope1 HwfEC]; subst. \n  unfold wf_ExecutionContext in *.\n  remember (inscope_of_cmd F (l3, stmts_intro ps3 (cs3' ++ c0 :: cs) tmn) c0)\n    as R1.\n  assert (HeqR1':=HeqR1).\n  unfold inscope_of_cmd, inscope_of_id in HeqR1'.\n  assert (uniqFdef F) as HuniqF.\n    eapply wf_system__uniqFdef; eauto.\n  destruct R1; try solve [inversion Hinscope1].\n  repeat (split; try solve [auto | congruence]).\n      assert (Hid':=Hid).\n      symmetry in Hid.\n      apply getCmdLoc_getCmdID in Hid.\n      subst. unfold wf_ExecutionContext in *.\n      assert (cmdInBlockB c0 (l3, stmts_intro ps3 (cs3' ++ c0 :: cs) tmn) = true)\n        as Hin.\n        simpl. apply In_InCmdsB. apply in_middle.\n      assert (NoDup (getStmtsLocs (stmts_intro ps3 (cs3' ++ c0 :: cs) tmn))) \n        as Hnotin.\n        eapply wf_system__uniq_block with (f:=F) in HwfSystem; eauto.\n      destruct cs; simpl_env in *.\n      Case \"1.1.1\".\n        apply inscope_of_cmd_tmn in HeqR1; auto.\n        destruct HeqR1 as [ids2 [J1 J2]].\n        rewrite <- J1.\n        assert (In c0 (cs3' ++ [c0])) as HinCs.\n          apply in_or_app. right. simpl. auto.\n        assert (Hwfc := HBinF1).\n        eapply wf_system__wf_cmd with (c:=c0) in Hwfc;\n          eauto.\n        rewrite <- Hid' in J2.\n        assert (HwfF:=HFinPs1). eapply wf_system__wf_fdef in HwfF; eauto.\n        eapply wf_defs_updateAddAL; eauto.\n          eapply wf_impure_id__wf_gvs; eauto.\n\n      Case \"1.1.2\".\n        apply inscope_of_cmd_cmd in HeqR1; auto.\n        destruct HeqR1 as [ids2 [J1 J2]].\n        rewrite <- J1.\n        assert (In c0 (cs3' ++ [c0] ++ [c] ++ cs)) as HinCs.\n          apply in_or_app. right. simpl. auto.\n        assert (Hwfc := HBinF1).\n        eapply wf_system__wf_cmd with (c:=c0) in Hwfc;\n          eauto.\n        rewrite <- Hid' in J2.\n        assert (HwfF:=HFinPs1). eapply wf_system__wf_fdef in HwfF; eauto.\n        eapply wf_defs_updateAddAL; eauto.\n          eapply wf_impure_id__wf_gvs; eauto.\nQed.\n\nLemma isReachableFromEntry_helper : forall F l1 ps1 cs1 c1 cs2 tmn1 c0 b1,\n  uniqFdef F ->\n  isReachableFromEntry F (l1, stmts_intro ps1 (cs1++c1::cs2) tmn1) ->\n  blockInFdefB (l1, stmts_intro ps1 (cs1++c1::cs2) tmn1) F = true ->\n  lookupInsnViaIDFromFdef F (getCmdLoc c1) = ret insn_cmd c0 ->\n  cmdInFdefBlockB c0 F b1 = true ->\n  isReachableFromEntry F b1.\nProof.\n  intros. \n  assert (b1 = (l1, stmts_intro ps1 (cs1++c1::cs2) tmn1)) as EQ.\n    unfold cmdInFdefBlockB in H3.\n    bdestruct H3 as J1 J2.\n    apply lookupInsnViaIDFromFdef__eqid in H2. simpl in H2.\n    apply cmdInBlockB__inGetBlockLocs in J1. rewrite H2 in J1.\n    eapply block_eq2 with (id1:=getCmdLoc c1); eauto.\n      simpl. apply in_or_app. right. apply in_or_app. left.\n      apply InGetCmdsLocs_middle.\n  subst. auto.\nQed.\n\nLtac preservation_pure_case_tac :=\nmatch goal with\n| HwfS1: wf_State _ _ |- _ =>\n  eapply preservation_pure_cmd_updated_case in HwfS1; simpl; eauto;\n               simpl; auto; \n  destruct_wf;\n  match goal with\n  | HwfSystem: wf_system _ |- _ =>\n    assert (HuniqF := HwfSystem);\n    eapply wf_system__uniqFdef in HuniqF; eauto\n  end\nend.\n\nLtac preservation_impure_case_tac :=\nmatch goal with\n| HwfS1: wf_State _ _ |- _ =>\n  eapply preservation_impure_cmd_updated_case in HwfS1; simpl; eauto;\n               simpl; auto; \n  destruct_wf;\n  match goal with\n  | HwfSystem: wf_system _,\n    HFinPs1 : InProductsB _ _ = true |- _ =>\n    assert (HuniqF := HwfSystem);\n    eapply wf_system__uniqFdef in HuniqF; eauto;\n    intros c0 Hlkc0 b1 J; eapply wf_system__uniqFdef in HFinPs1; eauto;\n    eapply isReachableFromEntry_helper; eauto\n  end\nend.\n\nLemma preservation : forall cfg S1 S2 tr \n  (Hwfcfg : OpsemPP.wf_Config cfg) (Hwfpp1 : OpsemPP.wf_State cfg S1),\n  sInsn cfg S1 S2 tr -> wf_State cfg S1 -> wf_State cfg S2.\nProof.\n  intros cfg S1 S2 tr Hwfcfg Hwfpp1 HsInsn HwfS1.\n  (sInsn_cases (induction HsInsn) Case); destruct TD as [los nts].\nFocus.\nCase \"sReturn\".\n  destruct Hwfcfg as [Hwftd [Hwfg [HwfSystem HmInS]]].\n  destruct Hwfpp1 as\n    [Hnonempty [\n     [Hreach1 [HBinF1 [HFinPs1 [Hwflc1 [_ [l1 [ps1 [cs1' Heq1]]]]]]]]\n     [\n       [\n         [Hreach2 [HBinF2 [HFinPs2 [Hwflc2 [_ [l2 [ps2 [cs2' Heq2]]]]]]]]\n         [_ HwfCall]\n       ]\n       HwfCall'\n     ]\n    ]]; subst.\n  destruct HwfS1 as [Hinscope1 [Hinscope2 HwfEC]]; subst.\n  unfold wf_ExecutionContext in *.\n  remember (inscope_of_cmd F' (l2, stmts_intro ps2 (cs2' ++ c' :: cs') tmn') c')\n    as R2.\n  destruct R2; try solve [inversion Hinscope2].\n  remember (inscope_of_tmn F\n             (l1, stmts_intro ps1 (cs1' ++ nil)(insn_return rid RetTy Result))\n             (insn_return rid RetTy Result)) as R1.\n  destruct R1; try solve [inversion Hinscope1].\n  split; auto.\n  SCase \"1\".\n    unfold wf_ExecutionContext.\n    remember (getCmdID c') as R.\n    destruct c' as [ | | | | | | | | | | | | | | | | i0 n c rt va v p]; \n      try solve [inversion H].\n    assert (In (insn_call i0 n c rt va v p)\n      (cs2'++[insn_call i0 n c rt va v p] ++ cs')) as HinCs.\n      apply in_or_app. right. simpl. auto.\n    assert (Hwfc := HBinF2).\n    eapply wf_system__wf_cmd with (c:=insn_call i0 n c rt va v p) in Hwfc; \n      eauto.\n    assert (wf_fdef S (module_intro los nts Ps) F') as HwfF.\n      eapply wf_system__wf_fdef; eauto.\n    assert (uniqFdef F') as HuniqF.\n      eapply wf_system__uniqFdef; eauto.\n\n    SSCase \"1.1\".\n      assert (NoDup (getStmtsLocs \n                       (stmts_intro ps2\n                          (cs2' ++ insn_call i0 n c rt va v p :: cs') tmn'))) \n        as Hnotin.\n        eapply wf_system__uniq_block with (f:=F') in HwfSystem; eauto.\n      destruct cs'; simpl_env in *.\n      SSSCase \"1.1.1\".\n        assert (HeqR2':=HeqR2).\n        apply inscope_of_cmd_tmn in HeqR2; auto.\n        destruct HeqR2 as [ids2 [J1 J2]].\n        rewrite <- J1.\n        unfold returnUpdateLocals in H1. simpl in H1.\n        remember (getOperandValue (los,nts) Result lc gl) as R1.\n        destruct R1; try solve [inv H1].\n        destruct R.\n          destruct n; inv HeqR.\n          remember (GVsSig.(lift_op1) (fit_gv (los, nts) rt) g rt) as R2.\n          destruct R2; inv H1.\n          change i0 with\n            (getCmdLoc (insn_call i0 false c rt va v p)); auto.\n          eapply wf_defs_updateAddAL; eauto 1.\n            simpl. apply In_InCmdsB. apply in_middle.\n            eapply wf_impure_id__wf_gvs; eauto.\n              simpl. intros c0 Hlkc0. intros b1 J.\n              clear - Hreach2 J HuniqF Hlkc0 HBinF2.\n              eapply isReachableFromEntry_helper; eauto.\n\n              simpl. apply In_InCmdsB. solve_in_list.\n\n          destruct n; inv HeqR. inv H1.\n          simpl in J2.\n          eapply wf_defs_eq; eauto.\n\n      SSSCase \"1.1.2\".\n        assert (HeqR2':=HeqR2).\n        apply inscope_of_cmd_cmd in HeqR2; auto.\n        destruct HeqR2 as [ids2 [J1 J2]].\n        rewrite <- J1.\n        unfold returnUpdateLocals in H1. simpl in H1.\n        remember (getOperandValue (los,nts) Result lc gl) as R1.\n        destruct R1; try solve [inv H1].\n        destruct R.\n          destruct n; inv HeqR.\n          remember (GVsSig.(lift_op1) (fit_gv (los, nts) rt) g rt) as R2.\n          destruct R2; inv H1.\n          inv Hwfc. uniq_result.\n          change i0 with\n            (getCmdLoc (insn_call i0 false c rt va v\n              (List.map\n                 (fun p : typ * attributes * value =>\n                   let '(typ_', attr, value_'') := p in\n                    (typ_', attr, value_''))\n                 typ'_attributes'_value''_list))); auto.\n          eapply wf_defs_updateAddAL; eauto 2.\n            simpl. apply In_InCmdsB. apply in_middle.\n            eapply wf_impure_id__wf_gvs; eauto.\n              simpl. intros c1 Hlkc1. intros b1 J.\n              clear - Hreach2 J HuniqF Hlkc1 HBinF2.\n              eapply isReachableFromEntry_helper with (cs2:=[c0]++cs')\n                (cs1:=cs2')(c1:=insn_call i0 false c rt va v\n                     (List.map\n                        (fun p : typ * attributes * value =>\n                          let '(typ_', attr, value_'') := p in\n                            (typ_', attr, value_''))\n                        typ'_attributes'_value''_list)) in Hreach2;\n                 eauto.\n\n              simpl. apply In_InCmdsB. solve_in_list.\n\n          destruct n; inv HeqR. inv H1.\n          simpl in J2.\n          eapply wf_defs_eq; eauto.\n\nFocus.\nCase \"sReturnVoid\".\n  destruct Hwfcfg as [Hwftd [Hwfg [HwfSystem HmInS]]].\n  destruct Hwfpp1 as\n    [Hnonempty [\n     [Hreach1 [HBinF1 [HFinPs1 [Hwflc1 [_ [l1 [ps1 [cs1' Heq1]]]]]]]]\n     [\n       [\n         [Hreach2 [HBinF2 [HFinPs2 [Hwflc2 [_ [l2 [ps2 [cs2' Heq2]]]]]]]]\n         [_ HwfCall]\n       ]\n       HwfCall'\n     ]\n    ]]; subst.\n  destruct HwfS1 as [Hinscope1 [Hinscope2 HwfEC]]; subst.\n  unfold wf_ExecutionContext in *.\n  remember (inscope_of_cmd F' (l2, stmts_intro ps2 (cs2' ++ c' :: cs') tmn') c')\n    as R2.\n  destruct R2; try solve [inversion Hinscope2].\n  remember (inscope_of_tmn F\n             (l1, stmts_intro ps1 (cs1' ++ nil)(insn_return_void rid))\n             (insn_return_void rid)) as R1.\n  destruct R1; try solve [inversion Hinscope1].\n  split; auto.\n  SCase \"1\".\n    unfold wf_ExecutionContext.\n    SSCase \"1.1\".\n      apply HwfCall' in HBinF1. simpl in HBinF1.\n      assert (NoDup (getStmtsLocs \n                       (stmts_intro ps2 (cs2' ++ c' :: cs') tmn'))) \n        as Hnotin.\n        eapply wf_system__uniq_block with (f:=F') in HwfSystem; eauto.\n      destruct cs'; simpl_env in *.\n      SSSCase \"1.1.1\".\n        clear - HeqR2 Hinscope2 H HwfCall' HBinF1 Hnotin H1.\n        apply inscope_of_cmd_tmn in HeqR2; auto.\n        destruct HeqR2 as [ids2 [J1 J2]].\n        rewrite <- J1.\n        remember (getCmdID c') as R.\n        destruct_cmd c'; try solve [inversion H].\n        destruct n; inversion H1.\n        simpl in HeqR. subst R.\n        eapply wf_defs_eq; eauto.\n\n      SSSCase \"1.1.2\".\n        clear - HeqR2 Hinscope2 H HwfCall' HBinF1 Hnotin H1.\n        apply inscope_of_cmd_cmd in HeqR2; auto.\n        destruct HeqR2 as [ids2 [J1 J2]].\n        rewrite <- J1.\n        remember (getCmdID c') as R.\n        destruct_cmd c'; try solve [inversion H].\n        destruct n; inversion H1.\n        simpl in HeqR. subst R.\n        eapply wf_defs_eq; eauto.\n\nCase \"sBranch\".\n  destruct Hwfcfg as [_ [_ [HwfSystem HmInS]]].\n  destruct Hwfpp1 as\n    [_ [[Hreach1 [HBinF1 [HFinPs1 [_ [_ [l3 [ps3 [cs3' Heq1]]]]]]]]\n     [_ HwfCall]]]; subst.\n  destruct HwfS1 as [Hinscope1 HwfEC]; subst. \n  unfold wf_ExecutionContext in *.\n  remember (inscope_of_tmn F\n             (l3, stmts_intro ps3 (cs3' ++ nil)(insn_br bid Cond l1 l2))\n             (insn_br bid Cond l1 l2)) as R1.\n  destruct R1; try solve [inversion Hinscope1].\n  split; auto.\n    assert (HwfF := HwfSystem).\n    eapply wf_system__wf_fdef with (f:=F) in HwfF; eauto.\n    assert (HuniqF := HwfSystem).\n    eapply wf_system__uniqFdef with (f:=F) in HuniqF; eauto.\n    unfold wf_ExecutionContext.\n    clear - H2 HeqR1 H1 Hinscope1 HBinF1 HwfF HuniqF Hreach1.\n    eapply inscope_of_tmn_br in HeqR1; eauto.\n    destruct HeqR1 as [ids0' [HeqR1 [J1 J2]]].\n    destruct cs'; rewrite <- HeqR1; auto.\n\nFocus.\nCase \"sBranch_uncond\".\n  destruct Hwfcfg as [_ [_ [HwfSystem HmInS]]].\n  destruct Hwfpp1 as\n    [_ [[Hreach1 [HBinF1 [HFinPs1 [_ [_ [l3 [ps3 [cs3' Heq1]]]]]]]]\n     [_ HwfCall]]]; subst.\n  destruct HwfS1 as [Hinscope1 HwfEC]; subst. \n  unfold wf_ExecutionContext in *.\n  remember (inscope_of_tmn F\n             (l3, stmts_intro ps3 (cs3' ++ nil)(insn_br_uncond bid l0))\n             (insn_br_uncond bid l0)) as R1.\n  destruct R1; try solve [inversion Hinscope1].\n  split; auto.\n    assert (HwfF := HwfSystem).\n    eapply wf_system__wf_fdef with (f:=F) in HwfF; eauto.\n    assert (HuniqF := HwfSystem).\n    eapply wf_system__uniqFdef with (f:=F) in HuniqF; eauto.\n    unfold wf_ExecutionContext.\n    clear - H0 HeqR1 Hinscope1 H HBinF1 HwfF HuniqF Hreach1.\n    assert (Hwds := HeqR1).\n    eapply inscope_of_tmn_br_uncond with (cs':=cs')(ps':=ps')\n      (tmn':=tmn') in HeqR1; eauto.\n    destruct HeqR1 as [ids0' [HeqR1 [J1 J2]]].\n    destruct cs'; rewrite <- HeqR1; auto.\n\nCase \"sBop\". \n  preservation_pure_case_tac.\n  eapply BOP__wf_gvs; eauto.\nCase \"sFBop\". preservation_pure_case_tac.\n  eapply FBOP__wf_gvs; eauto.\nCase \"sExtractValue\". preservation_pure_case_tac.\n  eapply extractvalue__wf_gvs; eauto.\nCase \"sInsertValue\". preservation_pure_case_tac.\n  eapply insertvalue__wf_gvs in H1; eauto.\nCase \"sMalloc\".  abstract preservation_impure_case_tac.\nCase \"sFree\". eapply preservation_cmd_non_updated_case in HwfS1; simpl; eauto.\n    simpl; auto.\nCase \"sAlloca\". abstract preservation_impure_case_tac.\nCase \"sLoad\".  abstract preservation_impure_case_tac.\nCase \"sStore\". eapply preservation_cmd_non_updated_case in HwfS1; simpl; eauto;\n    simpl; auto.\nCase \"sGEP\".\n  assert (J:=Hwfpp1). assert (Hwfcfg':=Hwfcfg).\n  destruct_wf.\n  assert (J:=HBinF1).\n  eapply wf_system__wf_cmd with (c:=insn_gep id0 inbounds0 t v idxs t') in HBinF1;\n    eauto using in_middle.\n  inv HBinF1; eauto.\n  eapply preservation_impure_cmd_updated_case in HwfS1; \n    try solve [simpl; auto]; eauto.\n  assert (HuniqF := HwfSystem).\n  eapply wf_system__uniqFdef with (f:=F) in HuniqF; eauto.\n  destruct F as [fh1 bs1].\n  assert (lookupInsnViaIDFromBlocks bs1 id0 =\n    Some (insn_cmd (insn_gep id0 inbounds0 t v idxs t'))) as Hlk1.\n    apply uniqF__uniqBlocks in HuniqF. inv HuniqF.\n    eapply InBlocksB__lookupInsnViaIDFromBlocks; eauto.\n  intros c1 Hlkc1 b1 Hin.\n  assert (c1 = insn_gep id0 inbounds0 t v idxs t') as EQ.\n    eapply uniqFdef__lookupInsnViaIDFromBlocks in Hlk1; eauto.\n  subst.\n  assert ((l3, stmts_intro ps3 (cs3' ++ insn_gep id0 inbounds0 t v idxs t':: cs)\n    tmn) = b1) as EQ.\n    eapply blockInFdefB__cmdInFdefBlockB__eqBlock; eauto using in_middle.\n  subst. auto.\n\nCase \"sTrunc\". preservation_pure_case_tac.\n  eapply TRUNC__wf_gvs; eauto.\n\nCase \"sExt\". preservation_pure_case_tac.\n  eapply EXT__wf_gvs; eauto.\n\nCase \"sCast\". preservation_pure_case_tac.\n  eapply CAST__wf_gvs; eauto.\n\nCase \"sIcmp\". preservation_pure_case_tac. \n  eapply ICMP__wf_gvs; eauto.\n\nCase \"sFcmp\". preservation_pure_case_tac. \n  eapply FCMP__wf_gvs; eauto.\n\nCase \"sSelect\".\n  assert (J:=Hwfpp1). assert (Hwfcfg':=Hwfcfg).\n  destruct_wf.\n  assert (J:=HBinF1).\n  eapply wf_system__wf_cmd with (c:=insn_select id0 v0 t v1 v2) in HBinF1;\n    eauto using in_middle.\n  inv HBinF1; eauto.\n  assert (wf_impure_id F id0) as W.\n    assert (HuniqF := HwfSystem).\n    eapply wf_system__uniqFdef with (f:=F) in HuniqF; eauto.\n    destruct F as [fh1 bs1].\n    assert (lookupInsnViaIDFromBlocks bs1 id0 =\n      Some (insn_cmd (insn_select id0 v0 t v1 v2))) as Hlk1.\n      apply uniqF__uniqBlocks in HuniqF. inv HuniqF.\n      eapply InBlocksB__lookupInsnViaIDFromBlocks; eauto.\n    intros c1 Hlkc1 b1 Hin.\n    assert (c1 = insn_select id0 v0 t v1 v2) as EQ.\n    eapply uniqFdef__lookupInsnViaIDFromBlocks in Hlk1; eauto.\n    subst.\n    assert ((l3, stmts_intro ps3 (cs3' ++ insn_select id0 v0 t v1 v2 :: cs)\n      tmn) = b1) as EQ.\n      eapply blockInFdefB__cmdInFdefBlockB__eqBlock; eauto using in_middle.\n    subst. auto.\n  destruct (isGVZero (los, nts) c);\n    eapply preservation_impure_cmd_updated_case in HwfS1; \n      try solve [simpl; auto]; eauto.\n\nFocus.\nCase \"sCall\".\n  destruct_wf.\n  assert (InProductsB (product_fdef (fdef_intro\n    (fheader_intro fa rt fid la va) lb)) Ps = true) as HFinPs'.\n    apply lookupFdefViaPtr_inversion in H1.\n    destruct H1 as [fn [H11 H12]].\n    eapply lookupFdefViaIDFromProducts_inv; eauto.\n  split; auto.\n  SCase \"1\".\n    assert (uniqFdef (fdef_intro (fheader_intro fa rt fid la va) lb)) as Huniq.\n      eapply wf_system__uniqFdef; eauto.\n    assert (wf_fdef S (module_intro los nts Ps) \n      (fdef_intro (fheader_intro fa rt fid la va) lb)) as HwfF.\n      eapply wf_system__wf_fdef; eauto.\n\n    assert (ps'=nil) as EQ.\n      eapply entryBlock_has_no_phinodes with (s:=S); eauto.        \n    subst. unfold wf_ExecutionContext.\n    apply AlgDom.dom_entrypoint in H2.\n    destruct cs'.\n      unfold inscope_of_tmn.\n      rewrite H2. simpl.\n      eapply preservation_dbCall_case; eauto.\n\n      unfold inscope_of_cmd, inscope_of_id.\n      rewrite init_scope_spec1; auto.\n      rewrite H2. simpl.\n      destruct (eq_atom_dec (getCmdLoc c) (getCmdLoc c)) as [|n];\n        try solve [contradict n; auto].\n      eapply preservation_dbCall_case; eauto.\n\nCase \"sExCall\".\n  match goal with\n  | H6: exCallUpdateLocals _ _ _ _ _ _ = _ |- _ => \n      unfold exCallUpdateLocals in H6 end.\n  destruct noret0.\n    match goal with | H6: Some _ = Some _ |- _ => inv H6 end.\n    eapply preservation_cmd_non_updated_case in HwfS1; \n      try solve [simpl; auto]; eauto.\n\n    match goal with\n    | H6: match _ with\n          | Some _ => _ \n          | None => _\n          end = _ |- _ =>\n      destruct oresult; tinv H6;\n      remember (fit_gv (los, nts) rt1 g) as R;\n      destruct R; inv H6\n    end.\n    abstract preservation_impure_case_tac.\nQed.\n\nEnd OpsemDom. End OpsemDom.\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_dom.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2618902893123936}}
{"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 PBFTprepares_like_of_new_views_are_received.\n\n\nSection PBFT_A_1_5.\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 prepared_info2request_data_equal_prepare_like2request_data_implies :\n    forall pi pl,\n      prepared_info2request_data pi = prepare_like2request_data pl\n      -> prepared_info2seq pi = prepare_like2seq pl\n         /\\ prepared_info2view pi = prepare_like2view pl\n         /\\ prepared_info2digest pi = prepare_like2digest pl.\n  Proof.\n    introv e.\n    destruct pi, pl as [p|p], p, b, prepared_info_pre_prepare, b; simpl in *;\n      unfold prepared_info2request_data in *; simpl in *; ginv; tcsp.\n  Qed.\n\n  (* Invariant A.1.5 in PBFT PhD p.148 *)\n  Lemma PBFT_A_1_5 :\n    forall (eo : EventOrdering) (e : Event),\n      AXIOM_authenticated_messages_were_sent_or_byz_usys eo PBFTsys\n      -> AXIOM_PBFTcorrect_keys eo\n      -> AXIOM_exists_at_most_f_faulty [e] F\n      ->\n      forall (nv      : NewView)\n             (p_info1 : PreparedInfo)\n             (p_info2 : PreparedInfo)\n             (slf     : Rep)\n             (state   : PBFTstate),\n        loc e = PBFTreplica slf\n        -> state_sm_on_event (PBFTreplicaSM slf) e = Some state\n        -> new_view_in_log nv (view_change_state state)\n        -> In p_info1 (mergeP (new_view2cert nv))\n        -> In p_info2 (mergeP (new_view2cert nv))\n        -> info_is_prepared p_info1 = true\n        -> info_is_prepared p_info2 = true\n        -> prepared_info2view p_info1 = prepared_info2view p_info2\n        -> prepared_info2seq p_info1 = prepared_info2seq p_info2\n        -> prepared_info2digest p_info1 = prepared_info2digest p_info2.\n  Proof.\n    introv sentbyz ckeys fbyz;\n      introv eqloc eqst in_nv in_e1 in_e2;\n      introv ip1 ip2 eqv eqs.\n\n    destruct (PBFTdigestdeq (prepared_info2digest p_info1) (prepared_info2digest p_info2)); auto;[].\n    assert False; tcsp.\n\n    assert (well_formed_log (log state)) as wf by eauto 2 with pbft;[].\n\n    eapply prepared_as_pbft_knows_rd in ip1; try (exact eqst); try (exact in_nv); auto.\n    eapply prepared_as_pbft_knows_rd in ip2; try (exact eqst); try (exact in_nv); auto.\n\n    pose proof (local_knows_in_intersection1\n                  e\n                  (2 * F + 1)\n                  (prepared_info2request_data p_info1)\n                  (prepared_info2request_data p_info2)\n                  one_pre_prepare\n                  [e]\n                  F) as q.\n    repeat (autodimp q hyp); simpl; eauto 3 with pbft;\n      try (complete (unfold num_replicas; try omega));[].\n    exrepnd; unfold lak_data2owner in *; simpl in *; unfold pbft_pl_data2loc in *.\n\n    apply (prepares_like_of_new_views_are_received0 _ _ _ correct) in q3; auto;[].\n    apply (prepares_like_of_new_views_are_received0 _ _ _ correct) in q4; auto;[].\n    destruct q3 as [e1 kna]; repnd.\n    destruct q4 as [e2 knb]; repnd.\n\n    apply pbft_knows_prepare_like_propagates in kna; allrw; eauto 3 with eo pbft;[].\n    apply pbft_knows_prepare_like_propagates in knb; allrw; eauto 3 with eo pbft;[].\n\n    destruct kna as [e'1 kna]; repnd.\n    destruct knb as [e'2 knb]; repnd.\n\n    apply prepared_info2request_data_equal_prepare_like2request_data_implies in q5; repnd.\n    apply prepared_info2request_data_equal_prepare_like2request_data_implies in q6; repnd.\n    pose proof (two_know_own_prepare_like eo e'1 e'2 d1 d2) as z.\n    repeat (autodimp z hyp); eauto 2 with pbft; try congruence.\n  Qed.\n\nEnd PBFT_A_1_5.\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_5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.41111086923216805, "lm_q1q2_score": 0.261890283646489}}
{"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 PBFT_A_1_4.\nRequire Export PBFT_A_1_9.\n\n\nSection PBFT_A_1_10.\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  Context { pbft_hash_axioms : PBFThash_axioms  }.\n\n\n  Definition more_than_F_have_prepared_before\n             (eo : EventOrdering)\n             (e  : Event)\n             (R  : list Rep)\n             (v  : View)\n             (n  : SeqNum)\n             (d  : PBFTdigest) :=\n    no_repeats R\n    /\\ F < length R\n    /\\\n    forall (k : Rep),\n      In k R\n      ->\n      exists (e' : Event) (st' : PBFTstate),\n        e' ≼ e\n        /\\ loc e' = PBFTreplica k\n        /\\ state_sm_on_event (PBFTreplicaSM k) e' = Some st'\n        /\\ prepared (request_data v n d) st' = true.\n\n  Lemma more_than_F_have_prepared_before_implies :\n    forall (eo : EventOrdering) (e : Event) R v n d,\n      more_than_F_have_prepared_before eo e R v n d\n      -> more_than_F_have_prepared eo R v n d.\n  Proof.\n    introv moreThanF.\n    unfold more_than_F_have_prepared, more_than_F_have_prepared_before in *.\n    repnd; dands; auto.\n    introv i.\n    applydup moreThanF in i; exrepnd.\n    eexists; eexists; dands; eauto.\n  Qed.\n  Hint Resolve more_than_F_have_prepared_before_implies : pbft.\n\n  Lemma A_1_10_lt :\n    forall (eo    : EventOrdering)\n           (e1 e2 : Event)\n           (R1 R2 : list Rep)\n           (n     : SeqNum)\n           (v1 v2 : View)\n           (d1 d2 : PBFTdigest),\n      authenticated_messages_were_sent_or_byz_usys eo PBFTsys\n      -> PBFTcorrect_keys eo\n      -> v1 < v2\n      -> exists_at_most_f_faulty [e2] F\n      -> nodes_have_correct_traces_before R1 [e2]\n      -> more_than_F_have_prepared_before eo e1 R1 v1 n d1\n      -> more_than_F_have_prepared_before eo e2 R2 v2 n d2\n      -> d1 = d2.\n  Proof.\n    introv sendbyz corkeys ltv atmost ctraces moreThanF1 moreThanF2.\n\n    unfold more_than_F_have_prepared in moreThanF2.\n    destruct moreThanF2 as [norep2 [len2 moreThanF2]].\n\n    destruct (PBFTdigestdeq d1 d2); auto.\n    assert False; tcsp;[].\n\n    pose proof (there_is_one_good_guy_before eo R2 [e2]) as h.\n    repeat (autodimp h hyp); try omega;[].\n    exrepnd.\n    pose proof (moreThanF2 good) as prep; autodimp prep hyp.\n    exrepnd.\n\n    pose proof (PBFT_A_1_9 eo) as q; repeat (autodimp q hyp).\n    pose proof (q R1 v1 n d1) as q; autodimp q hyp; eauto 3 with pbft;[].\n    pose proof (q e' good st') as q.\n    repeat (autodimp q hyp); eauto 3 with pbft eo;[].\n\n    unfold prepared in prep1.\n    eapply prepared_implies2 in prep1;[|eauto 3 with pbft].\n    exrepnd.\n    destruct pp, b; simpl in *; ginv; simpl in *.\n    unfold pre_prepare2digest in *; simpl in *.\n    fold (mk_pre_prepare v2 n d a) in *.\n\n    hide_hyp prep1.\n\n    pose proof (h0 e2) as h0; autodimp h0 hyp.\n\n    pose proof (q v2 d a (requests2digest d)) as q.\n    repeat (autodimp q hyp); eauto 3 with pbft eo.\n  Qed.\n\n  Lemma A_1_10 :\n    forall (eo    : EventOrdering)\n           (e1 e2 : Event)\n           (R1 R2 : list Rep)\n           (n     : SeqNum)\n           (v1 v2 : View)\n           (d1 d2 : PBFTdigest),\n      authenticated_messages_were_sent_or_byz_usys eo PBFTsys\n      -> PBFTcorrect_keys eo\n      -> exists_at_most_f_faulty [e1,e2] F\n      -> nodes_have_correct_traces_before R1 [e2]\n      -> nodes_have_correct_traces_before R2 [e1]\n      -> more_than_F_have_prepared_before eo e1 R1 v1 n d1\n      -> more_than_F_have_prepared_before eo e2 R2 v2 n d2\n      -> d1 = d2.\n  Proof.\n    introv sendbyz corkeys atmost ctraces1 ctraces2 moreThanF1 moreThanF2.\n\n    destruct (lt_dec v1 v2) as [e|e].\n\n    { eapply A_1_10_lt; try exact moreThanF1; try exact moreThanF2; eauto 3 with pbft eo. }\n\n    destruct (lt_dec v2 v1) as [f|f].\n\n    { symmetry; eapply A_1_10_lt; eauto; eauto 3 with pbft eo. }\n\n    assert (v1 = v2) as xx by (apply equal_nats_implies_equal_views; omega).\n    subst.\n    clear e f.\n\n    destruct moreThanF1 as [norep1 [len1 moreThanF1]].\n    destruct moreThanF2 as [norep2 [len2 moreThanF2]].\n\n    pose proof (there_is_one_good_guy_before eo R1 [e1,e2]) as h.\n    pose proof (there_is_one_good_guy_before eo R2 [e1,e2]) as q.\n    repeat (autodimp h hyp); try omega;[].\n    repeat (autodimp q hyp); try omega;[].\n    exrepnd.\n\n    applydup moreThanF1 in h1; exrepnd.\n    applydup moreThanF2 in q1; exrepnd.\n\n    pose proof (h0 e1) as h0; simpl in h0; autodimp h0 hyp; auto.\n    pose proof (q0 e2) as q0; simpl in q0; autodimp q0 hyp; auto.\n\n    eapply A_1_4; try (exact h2); try (exact q2); try (exact h5); try (exact q5);\n      auto; allrw; eauto 3 with pbft eo.\n  Qed.\n\nEnd PBFT_A_1_10.\n\n\nHint Resolve more_than_F_have_prepared_before_implies : 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_10.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.26189028364648886}}
{"text": "Require Import ssreflect ssrfun ssrbool .\n\nFrom Modules Require Import HomotopicalEquality FunctionalRelation InhabitRelation lib PreSyntaxOnlyContr WfSyntaxBrunerieOnlyContr gtype decl omegagroupoids.\nSet Bullet Behavior \"Strict Subproofs\".\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\nLocal Notation \"⟦ X ⟧V\" := (dTm (w_va X)).\n\nSection TypeDecl.\n  Variable (T: Type).\n  Variable (fibT: Fib T).\n\n  Definition typDecl   : Decl.\n    unshelve refine\n             (\n               {| dC := fun Γ (wΓ : Γ ⊢ ) => C_TY (fC_C (semC fibT wΓ));\n                  dTy := fun Γ A (wΓ : Γ ⊢ ) (wA : Γ ⊢ A)\n                           (γ : C_TY (fC_C (semC fibT wΓ))) =>\n                           G_of_T\n                             (T_TY (fT_T (semT fibT wΓ wA)) (transport _ γ));\n                  dTm :=\n                    fun Γ A t (wΓ : Γ ⊢ ) \n                      (wt : Γ ⊢ t : A) (wA : Γ ⊢ A) (γ : C_TY (fC_C (semC fibT wΓ))) =>\n                      t_t\n                        (transport2 _ _ (ft_t (semt fibT wΓ wA wt)))\n                        (transport _ γ);\n\n                  dS := fun Γ Δ σ (wσ : Γ ⊢ σ ⇒ Δ) (wΓ : Γ ⊢ ) (wΔ : Δ ⊢ ) =>\n                           S (transport2 _ _ (fS_S (semS fibT wΓ wΔ wσ) )) \n                  |}\n               ).\n    - apply:eqf_CC_TC.\n    - apply:eqf_tC_TC.\n    - apply:eqf_tT_TT.\n    - apply:eqf_SC1_CC.\n    - apply:JMeq_from_eq.\n      apply:eqf_SC2_CC.\nDefined.\n\nEnd TypeDecl.\n\n\n\n(*\n    \n\n\n-- needed\n\n-- définitionnel\n    ⟦_⟧S-β1  : ∀{Γ}{γ : ⟦ Γ ⟧C} \n             → ⟦ • ⟧S γ ≡ coerce ⟦_⟧C-β1 tt\n\n    ⟦_⟧S-β2  : ∀{Γ Δ}{A : Ty Δ}{δ : Γ ⇒ Δ}{γ : ⟦ Γ ⟧C}\n             {a : Tm (A [ δ ]T)} → ((⟦ δ , a ⟧S )γ )\n             ≡ coerce (⟦_⟧C-β2) ((⟦ δ ⟧S γ) ,,\n             subst ∣_∣ (semSb-T A δ γ) (⟦ a ⟧tm γ))\n             -- needed\n(* inutile car déjà compris dans sb non ? *)\n    semWk-T  : ∀ {Γ A B}(γ : ⟦ Γ ⟧C)(v : ∣ ⟦ B ⟧T γ ∣)\n             → ⟦ A +T B ⟧T (coerce ⟦_⟧C-β2 (γ ,, v)) ≡ \n             ⟦ A ⟧T γ\n  \n\n    semWk-S  : ∀ {Γ Δ B}{γ : ⟦ Γ ⟧C}{v : ∣ ⟦ B ⟧T γ ∣}\n             → (δ : Γ ⇒ Δ) → ⟦ δ +S B ⟧S \n             (coerce ⟦_⟧C-β2 (γ ,, v)) ≡ ⟦ δ ⟧S γ\n\n-- needed\n    semWk-tm : ∀ {Γ A B}(γ : ⟦ Γ ⟧C)(v : ∣ ⟦ B ⟧T γ ∣)\n             → (a : Tm A) → subst ∣_∣ (semWk-T γ v) \n               (⟦ a +tm B ⟧tm (coerce ⟦_⟧C-β2 (γ ,, v))) \n                 ≡ (⟦ a ⟧tm γ)\n(* intuile *)\n    ⟦coh⟧  : ∀{Θ} → isContr Θ → (A : Ty Θ) \n→ (θ : ⟦ Θ ⟧C) → ∣ ⟦ A ⟧T θ ∣\n*)\n\n\n\n(* TODO : utiliser cette tactique pour simplifier la preuve de sem* qui construit la fonction\nvérifiant la relation fonctionelle *)\n    Ltac clear_rc :=\n      match goal with\n        | x : rC ?U, x' : rC ?U |- _  =>\n          have e : x = x' by apply:rl_hpC;\n          (eassumption || (apply:rl_t_Cη;eassumption) ||(apply:rl_T_Cη; eassumption))\n        | x : rT ?U, x' : rT ?U |- _  =>\n          have e : x = x' by apply:π_eq_pTη;apply:rl_hpT; \n          (eassumption || (apply:rl_t_Tη;eassumption) ||(apply:rl_V_Tη; eassumption))\n        | x : rtm ?U, x' : rtm ?U |- _  =>\n          have e : x = x' by apply:π_eq_ptη;apply:rl_hpt; eassumption\n        | x : rS ?U ?V, x' : rS ?U ?V |- _  =>\n          have e : x = x' by apply:π_eq_pSη;apply:rl_hpS; eassumption\n      end.\nLtac clear_jmsigma' := clear_jmsigma.\n\nLemma type_is_omega (T : Type) (fibT : Fib T) : isOmegaGroupoid (G_of_T T) (typDecl fibT).\n  unshelve econstructor.\n  - (* the coherence *)\n    move => Γ A wΓ wA γ.\n    apply coh_in_ctx.\n  - reflexivity.\n  - move => Γ A u wΓ wA wu.\n    cbn -[semt semT semC].\n    move:(semC _ _) => fΓe.\n    move:(semC _ _) => fΓ.\n    move:(semT _ _ _) => fA.\n    move:(semt _ _ _ _) => fu.\n    move/fC_r:(fΓe).\n    inversion 1.\n    subst.\n    repeat clear_hprop; repeat (clear_jmsigma; subst).\n    \n    rewrite /extΣ_G /=.\n    destruct fu,fΓ,fA => /=.\n    repeat (clear_rc; subst).\n    repeat (erewrite (uip _ erefl);cbn).\n    reflexivity.\n  - move => Γ wΓ .\n    cbn -[semt semT semC].\n    move:(semC _ _ ) => fΓ.\n    move:(semT _ _ _) => fstar.\n    move/fT_r:(fstar).\n    inversion 1; subst; repeat clear_hprop; repeat (clear_jmsigma; subst).\n    move => γ.\n    destruct fΓ,fstar; simpl in *.\n    repeat (clear_rc; subst).\n    reflexivity.\n  - move => Γ A t u wΓ wA wt wu .\n    cbn -[semt semT semC].\n    move:(semC _ _) => fΓ.\n    move:(semT _ _ _) => far.\n    move:(semT _ _ _) => fA.\n    move:(semt _ _ _ _) => ft.\n    move:(semt _ _ _ _) => fu.\n    move => γ.\n    move/fT_r:(far).\n    inversion 1; subst; repeat clear_hprop; repeat (clear_jmsigma; subst).\n    destruct fΓ,far,fA,ft,fu; simpl in *; repeat (clear_rc; subst).\n    repeat (erewrite (uip _ erefl);cbn).\n    reflexivity.\n  - intros.\n    move:δ .\n    cbn -[semt semT semC].\n    move:(semC _ _) => fΓ.\n    move:(semC _ _) => fΔ.\n    move:(semT _ _ _) => fAσ.\n    move:(semT _ _ _) => fA.\n    move:(semt _ _ _ _) => fcoh.\n    move:(semS _ _ _ _) => fσ.\n    move/(ft_r):(fcoh) => I.\n    inversion I; subst; repeat clear_hprop; repeat (clear_jmsigma'; subst).\n    destruct fΓ,fΔ,fAσ,fA,fcoh,fσ ; simpl in *.\n    repeat (move:(e in transport e) => /= ?; subst => /=;\n    repeat (clear_jmsigma'; subst)).\n    cbn.\n    repeat (move:(e in transport e) => /= e; (destruct e || subst) => /=).\n    repeat (move:(e in transport2 e) => /= e; (destruct e || subst) => /=).\n    repeat (\n      move:(e in JMeq_eq e) => /= e; have e' := JMeq_eq e ; destruct e';\n      repeat (erewrite (uip _ erefl);cbn);\n      clear e).\n\n    repeat (clear_rc; subst).\n    intro; apply:JMeq_refl.\n  - cbn -[semt semT semC].\n    move:(semC _ _) => fastar.\n    move:(semT _ _ _) => fstar.\n    move:(semt _ _ _ _) => fvstar.\n    move/(ft_r):(fvstar).\n    inversion 1; subst; repeat clear_hprop; repeat (clear_jmsigma; subst).\n    inversion X; subst; repeat clear_hprop; repeat (clear_jmsigma; subst).\n    destruct fstar,fastar,fvstar; simpl in *.\n    move => γ.\n     repeat (clear_rc; subst).\n    simpl in *.\n    (* TODO : adapter clear_jmsigma avec ça*)\n    repeat (apply JM_projT2,JMeq_eq in H0; simpl in H0).\n    subst.\n    repeat (apply JM_projT2,JMeq_eq in H1; simpl in H1).\n    subst.\n    repeat (erewrite (uip _ erefl);cbn).\n    set e := (e in transport e).\n    exact (JMeq_transport γ e).\n  - move => Γ A u wΓ wA wu wAe.\n    cbn -[semT semC semt] in *.\n    move:(semC _ _) => fΓe.\n    move:(semC _ _) => fΓ.\n    move:(semT _ _ _) => fA.\n    move:(semT _ _ _) => fAe.\n    move:(semt _ _ _ _) => fu.\n    move:(semt _ _ _ _) => fv1.\n    move/(ft_r):(fv1) => I.\n    inversion I; subst; repeat clear_hprop; repeat (clear_jmsigma; subst).\n    inversion X; subst; repeat clear_hprop; repeat (clear_jmsigma; subst).\n    destruct fΓe,fΓ,fA,fAe,fv1,fu; simpl in *.\n    repeat (clear_rc; subst).\n    cbn.\n    intros.\n    cbn.\n    repeat (erewrite (uip _ erefl);cbn).\n    move:(eqf_tC_TC _ _) => /= e.\n    move:(eqf_tT_TT _ _) => /= e'.\n    destruct e.\n    cbn.\n    move:(JMeq_eq _).\n    have e'' := JMeq_eq e'.\n    subst.\n    move => h.\n    move:sa sf H.\n    repeat (erewrite (uip _ erefl);cbn).\n    intros.\n    have H' := JMeq_eq H.\n    cbn.\n    subst.\n    (* clear H'. *)\n     repeat (apply JM_projT2,JMeq_eq in H10; simpl in H10).\n     repeat clear_hprop; repeat (clear_jmsigma; subst).\n     apply:JMeq_refl.\n  - move => Γ A u wΓ wA wu wAe wue.\n    cbn -[semT semC semt semS].\n    move :(semC _ _) => fΓe.\n    move :(semC _ _) => fΓ.\n    move :(semT _ _ _) => fA.\n    move :(semT _ _ _) => fAe.\n    move :(semt _ _ _ _) => fu.\n    move :(semt _ _ _ _) => fv0.\n    move/(ft_r):(fv0) => I.\n    inversion I; subst; repeat clear_hprop; repeat (clear_jmsigma; subst).\n    inversion X; subst; repeat clear_hprop; repeat (clear_jmsigma; subst).\n    destruct fΓe,fΓ,fA,fAe,fv0,fu; simpl in *.\n    repeat (clear_rc; subst).\n    cbn.\n    intros.\n    cbn.\n    repeat (erewrite (uip _ erefl);cbn).\n    move:(eqf_tC_TC _ _) => /= e.\n    move:(eqf_tT_TT _ _) => /= e'.\n    destruct e.\n    cbn.\n    move:(JMeq_eq _).\n    have e'' := JMeq_eq e'.\n    subst.\n    move => h.\n    move:sa sf H.\n    repeat (erewrite (uip _ erefl);cbn).\n    intros.\n    have H' := JMeq_eq H.\n    cbn.\n    subst.\n    (* clear H'. *)\n     repeat (apply JM_projT2,JMeq_eq in H10; simpl in H10).\n     repeat clear_hprop; repeat (clear_jmsigma; subst).\n     apply:JMeq_refl.\n  - move =>  Γ A u B x wΓ wA wu wB wBe wx.\n    cbn -[semT semC semt semS].\n    move :(semC _ _) => fΓe.\n    move :(semC _ _) => fΓ.\n    move :(semT _ _ _) => fA.\n    move :(semT _ _ _) => fBe.\n    move :(semT _ _ _) => fB.\n    move :(semt _ _ _ _) => fu.\n    move :(semt _ _ _ _) => fvwk.\n    move :(semt _ _ _ _) => fx.\n    move/(ft_r):(fvwk) => I.\n    inversion I; subst; repeat clear_hprop; repeat (clear_jmsigma; subst).\n    inversion X; subst; repeat clear_hprop; repeat (clear_jmsigma; subst).\n    destruct fΓe,fΓ,fA,fBe,fB, fx,fvwk,fu; simpl in *.\n    subst.\n    repeat (clear_jmsigma'; subst).\n    repeat (clear_rc; subst).\n    repeat (erewrite (uip _ erefl);cbn).\n    move:(eqf_tC_TC _ _) => /= e.\n    destruct e => /=.\n    move:(eqf_tT_TT _ _) => /= e.\n    have e' := JMeq_eq e.\n    destruct e'.\n    repeat (erewrite (uip _ erefl);cbn).\n    intros.\n    have e' := JMeq_eq H.\n    rewrite e' /=.\n    apply:JMeq_from_eq.\n    f_equal.\n    apply:π_eq_ptη.\n    apply:rl_hpt; try eassumption.\n    constructor.\n    assumption.\n  - move => Γ t wΓ wt.\n    cbn -[semT semC semt semS].\n    move :(semC _ _) => fΓ.\n    move :(semC _ _) => fast.\n    move :(semT _ _ _) => fst.\n    move :(semt _ _ _ _) => ft.\n    move :(semS _ _ _ _) => ftost.\n    move/(fS_r):(ftost) => I.\n    inversion I; subst; repeat clear_hprop; repeat (clear_jmsigma'; subst).\n    destruct fΓ,fast,fst,ft,ftost;  simpl in *.\n    subst.\n    repeat (clear_jmsigma'; subst).\n    repeat (clear_rc; subst).\n    repeat (erewrite (uip _ erefl);cbn).\n    move:( eqf_SC2_CC _ _) => /= e.\n    subst.\n    repeat (erewrite (uip _ erefl);cbn).\n    move => γ.\n    have e : ft_T = r_rl_star fibT .\n    {\n      apply:π_eq_pTη.\n    apply:rl_hpT; try eassumption.\n    by constructor.\n      }\n    subst.\n    apply:JMeq_from_eq.\n    f_equal.\n    apply:π_eq_ptη.\n    apply:rl_hpt; try eassumption.\n  - move => Δ Γ A u σ a f \n             wΓ wA wu wAσ wuσ wΔ wσ wa wf .\n    cbn -[semT semC semt semS].\n    move :(semC _ _) => fΔ.\n    move :(semC _ _) => fΓ.\n    move :(semC _ _) => fΓe.\n    move :(semT _ _ _) => fA.\n    move :(semT _ _ _) => fAσ.\n    move :(semT _ _ _) => far.\n    move :(semt _ _ _ _) => fu.\n    move :(semt _ _ _ _) => fa.\n    move :(semt _ _ _ _) => ff.\n    move :(semS _ _ _  _) => fσ.\n    move :(semS _ _ _  _) => fσe.\n    move/(fS_r):(fσe) => I.\n    (* why sσ is not rl ? *)\n    remember (mkpS (fS_S fσe)) as fσe' eqn:efσ'.\n    inversion I; subst; repeat clear_hprop; repeat (clear_jmsigma'; subst).\n    destruct fΔ,fΓ,fΓe, fA,fAσ,far,fu,fa,ff,fσ,fσe;  simpl in *.\n    (* c'es tplus propre de faire comme ça que de bourriner \n        avec clear_rc et et d'utiliser uip ensuite\n     *)\n    repeat (move:(e in transport e) => /= ?; subst => /=;\n    repeat (clear_jmsigma'; subst)).\n    repeat (move:(e in transport2 e) => /= ?; subst => /=;\n    repeat (clear_jmsigma'; subst)).\n    repeat (move:(e in JMeq_from_eq e) => /= ?;\n    subst => /=; repeat (erewrite (uip _ erefl);cbn)).\n    repeat (\n    move:(e in JMeq_eq e) => /= e; have e' := JMeq_eq e ; destruct e';\n    repeat (erewrite (uip _ erefl);cbn);\n    clear e).\n    case:H0 => ? ?;subst.\n    intro h.\n    repeat (clear_jmsigma'; subst).\n    move => γ sa' suσ sf'.\n    repeat (clear_rc; subst).\n    (* ft_T1 *)\n    inversion fT_r1.\n    subst; repeat clear_hprop; repeat (clear_jmsigma'; subst).\n    repeat (clear_rc; subst).\n    (* move => ee; have ee' := JMeq_eq ee. *)\n    (* h *)\n    (* move/(@JMeq_eq _ _ _) => e. *)\n    have h:sA0 = r_sbT sσ ft_T.\n    {\n      apply:π_eq_pTη.\n      apply:rl_hpT; try eassumption.\n      (apply:tp_rT1; first by reflexivity); last first.\n      apply:rl_sbT.\n      exact:X1.\n      eassumption.\n      reflexivity.\n      }\n    subst.\n    have h:su0 = r_sbt sσ ft_t.\n    {\n      apply:π_eq_ptη.\n      apply:rl_hpt; try eassumption.\n      (apply:tp_rTm1; first by reflexivity); last first.\n      apply:rl_sbt.\n      exact:X2.\n      eassumption.\n      reflexivity.\n      }\n    subst.\n    move/(@JMeq_eq _ _ _) => e.\n    subst.\n    move/(@JMeq_eq _ _ _) => e.\n    move/(@JMeq_eq _ _ _) => ee.\n    subst.\n    cbn.\n    simpl in *.\n      try (match goal with\n        | x : rtm ?U, x' : rtm ?U |- _  => \n          have e : x = x' by apply:π_eq_ptη;apply:rl_hpt; eassumption\n      end).\n      (* TODO : comprendre pourquoi clear_rc ne marche pas *)\n      have ea : sa = ft_t0 by apply:π_eq_ptη; apply:rl_hpt; eassumption.\n      subst.\n      (* TODO : comprendre pourquoi clear_rc ne marche pas *)\n      apply:JMeq_from_eq.\n      f_equal.\n      f_equal.\n      apply:π_eq_ptη.\n      apply:rl_hpt;eassumption.\nQed.", "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/TypesAreOmegaGroupoids/TypesAreOmegaGroupoids.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.26189028364648886}}
{"text": "(** * Testcases for the 'reals' database\nAuthors: \n    - Jim Portegies\nCreation date: 30 Oct 2021\n\nTestcases for (in)equality chains.\n--------------------------------------------------------------------------------\n\nThis file is part of Waterproof-lib.\n\nWaterproof-lib is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nWaterproof-lib is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with Waterproof-lib.  If not, see <https://www.gnu.org/licenses/>.\n*)\n\n(* Tests for (in)equality chains and the reals database *)\n\n\nRequire Import Waterproof.populate_database.waterproof_reals.\nRequire Import Waterproof.populate_database.waterproof_core.\n(* Require Import Waterproof.populate_database.all_databases.*)\nRequire Import Waterproof.definitions.inequality_chains.\n\nRequire Import Reals.\n(** TODO: eventuall rely on the reals database above *)\nOpen Scope R_scope.\n(* Test 0: check if notations work. *)\n\nGoal (& 3 < 4 <= 5).\nauto with waterproof_core reals.\nQed.\n\nGoal (& 3 = 3 = 3).\nauto with waterproof_core reals.\nQed.\nOpen Scope R_scope.\n(* Test 1: check if terms of a subset can be coerced to terms of the underlying set (here: [R]). *)\nGoal forall x : R, (& x < 5 = 2 + 3) -> (x < 5).\nintro x.\nintro H.\nauto with reals.\nQed.", "meta": {"author": "impermeable", "repo": "coq-waterproof", "sha": "a32bad4e44fedb4038065d2b55660cd967c2d1fd", "save_path": "github-repos/coq/impermeable-coq-waterproof", "path": "github-repos/coq/impermeable-coq-waterproof/coq-waterproof-a32bad4e44fedb4038065d2b55660cd967c2d1fd/waterproof/test/test_databases/test_reals_database.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.2618379106627909}}
{"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.\n\n(* Why3 assumption *)\nDefinition unit  := unit.\n\n(* Why3 assumption *)\nInductive ref (a:Type) {a_WT:WhyType a} :=\n  | mk_ref : a -> ref a.\nAxiom ref_WhyType : forall (a:Type) {a_WT:WhyType a}, WhyType (ref a).\nExisting Instance ref_WhyType.\nImplicit Arguments mk_ref [[a] [a_WT]].\n\n(* Why3 assumption *)\nDefinition contents {a:Type} {a_WT:WhyType a}(v:(ref a)): a :=\n  match v with\n  | (mk_ref x) => x\n  end.\n\nAxiom set : forall (a:Type) {a_WT:WhyType a}, Type.\nParameter set_WhyType : forall (a:Type) {a_WT:WhyType a}, WhyType (set a).\nExisting Instance set_WhyType.\n\nParameter mem: forall {a:Type} {a_WT:WhyType a}, a -> (set a) -> Prop.\n\n(* Why3 assumption *)\nDefinition infix_eqeq {a:Type} {a_WT:WhyType a}(s1:(set a)) (s2:(set\n  a)): Prop := forall (x:a), (mem x s1) <-> (mem x s2).\n\nAxiom extensionality : forall {a:Type} {a_WT:WhyType a}, forall (s1:(set a))\n  (s2:(set a)), (infix_eqeq s1 s2) -> (s1 = s2).\n\n(* Why3 assumption *)\nDefinition subset {a:Type} {a_WT:WhyType a}(s1:(set a)) (s2:(set a)): Prop :=\n  forall (x:a), (mem x s1) -> (mem x s2).\n\nAxiom subset_refl : forall {a:Type} {a_WT:WhyType a}, forall (s:(set a)),\n  (subset s s).\n\nAxiom subset_trans : forall {a:Type} {a_WT:WhyType a}, forall (s1:(set a))\n  (s2:(set a)) (s3:(set a)), (subset s1 s2) -> ((subset s2 s3) -> (subset s1\n  s3)).\n\nParameter empty: forall {a:Type} {a_WT:WhyType a}, (set a).\n\n(* Why3 assumption *)\nDefinition is_empty {a:Type} {a_WT:WhyType a}(s:(set a)): Prop :=\n  forall (x:a), ~ (mem x s).\n\nAxiom empty_def1 : forall {a:Type} {a_WT:WhyType a}, (is_empty (empty :(set\n  a))).\n\nAxiom mem_empty : forall {a:Type} {a_WT:WhyType a}, forall (x:a), ~ (mem x\n  (empty :(set a))).\n\nParameter add: forall {a:Type} {a_WT:WhyType a}, a -> (set a) -> (set a).\n\nAxiom add_def1 : forall {a:Type} {a_WT:WhyType a}, forall (x:a) (y:a),\n  forall (s:(set a)), (mem x (add y s)) <-> ((x = y) \\/ (mem x s)).\n\nParameter remove: forall {a:Type} {a_WT:WhyType a}, a -> (set a) -> (set a).\n\nAxiom remove_def1 : forall {a:Type} {a_WT:WhyType a}, forall (x:a) (y:a)\n  (s:(set a)), (mem x (remove y s)) <-> ((~ (x = y)) /\\ (mem x s)).\n\nAxiom subset_remove : forall {a:Type} {a_WT:WhyType a}, forall (x:a) (s:(set\n  a)), (subset (remove x s) s).\n\nParameter union: forall {a:Type} {a_WT:WhyType a}, (set a) -> (set a) -> (set\n  a).\n\nAxiom union_def1 : forall {a:Type} {a_WT:WhyType a}, forall (s1:(set a))\n  (s2:(set a)) (x:a), (mem x (union s1 s2)) <-> ((mem x s1) \\/ (mem x s2)).\n\nParameter inter: forall {a:Type} {a_WT:WhyType a}, (set a) -> (set a) -> (set\n  a).\n\nAxiom inter_def1 : forall {a:Type} {a_WT:WhyType a}, forall (s1:(set a))\n  (s2:(set a)) (x:a), (mem x (inter s1 s2)) <-> ((mem x s1) /\\ (mem x s2)).\n\nParameter diff: forall {a:Type} {a_WT:WhyType a}, (set a) -> (set a) -> (set\n  a).\n\nAxiom diff_def1 : forall {a:Type} {a_WT:WhyType a}, forall (s1:(set a))\n  (s2:(set a)) (x:a), (mem x (diff s1 s2)) <-> ((mem x s1) /\\ ~ (mem x s2)).\n\nAxiom subset_diff : forall {a:Type} {a_WT:WhyType a}, forall (s1:(set a))\n  (s2:(set a)), (subset (diff s1 s2) s1).\n\nParameter choose: forall {a:Type} {a_WT:WhyType a}, (set a) -> a.\n\nAxiom choose_def : forall {a:Type} {a_WT:WhyType a}, forall (s:(set a)),\n  (~ (is_empty s)) -> (mem (choose s) s).\n\nParameter cardinal: forall {a:Type} {a_WT:WhyType a}, (set a) -> Z.\n\nAxiom cardinal_nonneg : forall {a:Type} {a_WT:WhyType a}, forall (s:(set a)),\n  (0%Z <= (cardinal s))%Z.\n\nAxiom cardinal_empty : forall {a:Type} {a_WT:WhyType a}, forall (s:(set a)),\n  ((cardinal s) = 0%Z) <-> (is_empty s).\n\nAxiom cardinal_add : forall {a:Type} {a_WT:WhyType a}, forall (x:a),\n  forall (s:(set a)), (~ (mem x s)) -> ((cardinal (add x\n  s)) = (1%Z + (cardinal s))%Z).\n\nAxiom cardinal_remove : forall {a:Type} {a_WT:WhyType a}, forall (x:a),\n  forall (s:(set a)), (mem x s) -> ((cardinal s) = (1%Z + (cardinal (remove x\n  s)))%Z).\n\nAxiom cardinal_subset : forall {a:Type} {a_WT:WhyType a}, forall (s1:(set a))\n  (s2:(set a)), (subset s1 s2) -> ((cardinal s1) <= (cardinal s2))%Z.\n\nAxiom cardinal1 : forall {a:Type} {a_WT:WhyType a}, forall (s:(set a)),\n  ((cardinal s) = 1%Z) -> forall (x:a), (mem x s) -> (x = (choose s)).\n\nAxiom map : forall (a:Type) {a_WT:WhyType a} (b:Type) {b_WT:WhyType b}, Type.\nParameter map_WhyType : forall (a:Type) {a_WT:WhyType a}\n  (b:Type) {b_WT:WhyType b}, WhyType (map a b).\nExisting Instance map_WhyType.\n\nParameter get: forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  (map a b) -> a -> b.\n\nParameter set1: forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  (map a b) -> a -> b -> (map a b).\n\nAxiom Select_eq : forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  forall (m:(map a b)), forall (a1:a) (a2:a), forall (b1:b), (a1 = a2) ->\n  ((get (set1 m a1 b1) a2) = b1).\n\nAxiom Select_neq : forall {a:Type} {a_WT:WhyType a}\n  {b:Type} {b_WT:WhyType b}, forall (m:(map a b)), forall (a1:a) (a2:a),\n  forall (b1:b), (~ (a1 = a2)) -> ((get (set1 m a1 b1) a2) = (get m a2)).\n\nParameter const: forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  b -> (map a b).\n\nAxiom Const : forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},\n  forall (b1:b) (a1:a), ((get (const b1:(map a b)) a1) = b1).\n\nAxiom vertex : Type.\nParameter vertex_WhyType : WhyType vertex.\nExisting Instance vertex_WhyType.\n\nParameter v: (set vertex).\n\nParameter g_succ: vertex -> (set vertex).\n\nAxiom G_succ_sound : forall (x:vertex), (subset (g_succ x) v).\n\nParameter weight: vertex -> vertex -> Z.\n\nAxiom Weight_nonneg : forall (x:vertex) (y:vertex), (0%Z <= (weight x y))%Z.\n\n(* Why3 assumption *)\nDefinition min(m:vertex) (q:(set vertex)) (d:(map vertex Z)): Prop := (mem m\n  q) /\\ forall (x:vertex), (mem x q) -> ((get d m) <= (get d x))%Z.\n\n(* Why3 assumption *)\nInductive path : vertex -> vertex -> Z -> Prop :=\n  | Path_nil : forall (x:vertex), (path x x 0%Z)\n  | Path_cons : forall (x:vertex) (y:vertex) (z:vertex), forall (d:Z),\n      (path x y d) -> ((mem z (g_succ y)) -> (path x z (d + (weight y z))%Z)).\n\n(* Why3 goal *)\nTheorem Length_nonneg : forall (x:vertex) (y:vertex), forall (d:Z), (path x y\n  d) -> (0%Z <= d)%Z.\ninduction 1; try omega.\ngeneralize (Weight_nonneg y z); omega.\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/dijkstra/dijkstra_DijkstraShortestPath_Length_nonneg_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2618379106627909}}
{"text": "Require Import Clight.\nRequire Import Ctypes.\nRequire Import VST.veric.expr.\nRequire Import mc_reify.clight_expr_eq.\nRequire Import compcert.common.AST.\nRequire Import ExtLib.Core.RelDec.\n\nInstance RelDec_ctype_beq: RelDec (@eq type) := { rel_dec := eqb_type }.\n\nInstance RelDec_Correct_ctype_beq : RelDec_Correct RelDec_ctype_beq.\nProof.\n  constructor.\n  unfold rel_dec; simpl.\n  exact eqb_type_spec.\nQed.\n\nInstance RelDec_list_ctype_beq: RelDec (@eq (list type)) := List.RelDec_eq_list RelDec_ctype_beq.\nInstance RelDec_Correct_list_ctype_beq: RelDec_Correct RelDec_list_ctype_beq :=\n  List.RelDec_Correct_eq_list RelDec_Correct_ctype_beq.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/mc_reify/list_ctype_eq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.26183791066279083}}
{"text": "(* Profiler_types: the types used by the profiler functions *)\n\nRequire Export specIR.\n\n(* The different kinds of Optimizations passes the profiler wishes to make *)\nInductive optim_wish : Type :=\n| AS_INS: list expr -> label -> optim_wish\n| AS_INS_DELAY: list expr -> label -> optim_wish\n| CST_PROP: optim_wish\n| INLINE: label -> optim_wish\n| LOWER: optim_wish.\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/profiler_types.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.26183791066279083}}
{"text": "Add LoadPath \".\" as Top0.\nRequire Import Top0.Definitions.\nRequire Import Top0.Heap.\nRequire Import Top0.Keys.\nRequire Import Top0.Nameless.\nRequire Import Coq.Program.Equality.\nRequire Import Coq.Sets.Ensembles.\n\n(* Use these as constructors inside \"Inductive Phi\" *)\nAxiom Phi_Seq_Nil_L : forall phi, Phi_Seq Phi_Nil phi = phi.\nAxiom Phi_Seq_Nil_R : forall phi, Phi_Seq phi Phi_Nil = phi.\nAxiom Phi_Par_Nil_R : forall phi, Phi_Par phi Phi_Nil = phi.\nAxiom Phi_Par_Nil_L : forall phi, Phi_Par Phi_Nil phi = phi.\n\n (* both ec' and ee' and evaluated with the same context, but twice: inside Bs_Mu_App and BS_EffApp*)\nAxiom MuAppAndEffAppShareArgument:\n forall h'' env rho ef env' rho' f x ec' ee' ea aheap v eff facts1 aacts1 bacts1, \n   (forall fheap h' bacts facts v' aacts, \n      (h'', env, rho, ef) ⇓ (fheap, Cls (env', rho', Mu f x ec' ee'), facts) ->\n      (fheap, env, rho, ea) ⇓ (aheap, v, aacts) ->\n      (aheap, update_rec_E (f, Cls (env', rho', Mu f x ec' ee')) (x, v) env', rho', ec') ⇓ (h', v', bacts) ->\n      (h'', env, rho, Mu_App ef ea) ⇓ (h', v', Phi_Seq (Phi_Seq facts aacts)bacts)) -> \n   (* above is the definition of the type constructor BS_Mu_App *)\n   (h'', env, rho, Eff_App ef ea) ⇓ (h'', eff, Phi_Seq (Phi_Seq facts1 aacts1) bacts1) ->\n   (aheap, update_rec_E (f, Cls (env', rho', Mu f x ec' ee')) (x, v) env', rho', ee') ⇓ (h'', eff, bacts1). \n  \n(* Assuming that MuAppIncludesEffectShareArgument is a \"specification\", this prove the necessary goal *)\nLemma EvaluationEffectFromEffApp:\n forall h'' env rho ef env' rho' f x ec' ee' ea aheap v eff facts1 aacts1 bacts1,\n   (h'', env, rho, Eff_App ef ea) ⇓ (h'', eff, Phi_Seq (Phi_Seq facts1 aacts1) bacts1) ->\n   (aheap, update_rec_E (f, Cls (env', rho', Mu f x ec' ee')) (x, v) env', rho', ee') ⇓ (h'', eff, bacts1).\nProof.\n  intros.\n  inversion H using MuAppAndEffAppShareArgument.\n  intros. econstructor; eauto.\nQed. \n\n(* Inside \"BigStep\" we still don't use \"E.Equal\" to pass around heaps. \n   We need to resort to Coq equality when doing the proof for PairPar *)  \nAxiom ReadOnlyWalkSameHeap:\n  forall acts_mu1 acts_mu2 h same_h,\n    ReadOnlyPhi (Phi_Par acts_mu1 acts_mu2) ->\n    (Phi_Par acts_mu1 acts_mu2, h) ==>* (Phi_Nil, same_h) ->\n    (*H.Equal h same_h.*)\n    h = same_h.\n\n(* Induction principle for TcHeap when we know that previous heaps are \n   consistent and the new ones are non-overlapping. *)\nAxiom UnionTcHeap:\n  forall hp hp' ef1 ea1 ef2 ea2 theta1 theta2 v1 v2 acts_eff1 acts_eff2 env rho\n         heap heap_mu1 heap_mu2 heap_eff1 heap_eff2 sttym sttya acts_mu1 acts_mu2,\n    (heap, env, rho, Eff_App ef1 ea1) ⇓ (heap_eff1, Eff theta1, acts_eff1) ->\n    (heap, env, rho, Eff_App ef2 ea2) ⇓ (heap_eff2, Eff theta2, acts_eff2) ->\n    Disjointness theta1 theta2 /\\ ~ Conflictness theta1 theta2 ->\n    (heap, env, rho, Mu_App ef1 ea1) ⇓ (heap_mu1, v1, acts_mu1) ->\n    (heap, env, rho, Mu_App ef2 ea2) ⇓ (heap_mu2, v2, acts_mu2) ->\n    (Phi_Par acts_mu1 acts_mu2, hp) ==>* (Phi_Nil, hp') ->\n    TcHeap (heap_mu1, sttym) ->\n    TcHeap (heap_mu2, sttya) ->\n    TcHeap (hp', Functional_Map_Union sttya sttym).\n\n\nLemma TcValExtended_1 :\n  forall stty sttya sttyb v rho ty,\n    (forall (l : ST.key) (t' : tau),\n       ST.find (elt:=tau) l stty = Some t' -> ST.find (elt:=tau) l sttya = Some t' ) ->\n    (forall (l : ST.key) (t' : tau),\n       ST.find (elt:=tau) l stty = Some t' -> ST.find (elt:=tau) l sttyb = Some t' ) ->\n    TcVal (sttya, v, subst_rho rho ty) ->\n    TcVal (Functional_Map_Union sttya sttyb, v, subst_rho rho ty).\nProof.\n  intros stty sttya sttyb v rho ty H1 H2 H3.  \n  generalize dependent sttyb. \n  generalize dependent stty.\n  dependent induction H3; intros; try (solve [rewrite <- x; econstructor]).\n  - rewrite <- x. econstructor; eauto.\n    admit.\n  - rewrite <- x. econstructor; eauto.\n    admit.\n  - rewrite <- x. econstructor.\n    + (* goal is TcVal (Functional_Map_Union sttya sttyb, v1, ty1) *)\n      (* but IH is TcVal (Functional_Map_Union sttya0 sttyb, v, subst_rho rho ty) *)\n      admit.\n    + admit.  \nAdmitted. \n\nAxiom TcValExtended_2 :\n  forall stty sttya sttyb v rho ty,\n    (forall (l : ST.key) (t' : tau),\n       ST.find (elt:=tau) l stty = Some t' -> ST.find (elt:=tau) l sttya = Some t' ) ->\n    (forall (l : ST.key) (t' : tau),\n       ST.find (elt:=tau) l stty = Some t' -> ST.find (elt:=tau) l sttyb = Some t' ) ->\n    TcVal (sttyb, v, subst_rho rho ty) ->\n    TcVal (Functional_Map_Union sttya sttyb, v, subst_rho rho ty).\n\nAxiom UnionStoreTyping:\n  forall l sttya sttym t', \n    ST.find (elt:=tau) l sttya = Some t' -> \n    ST.find (elt:=tau) l sttym = Some t' ->\n    ST.find (elt:=tau) l (Functional_Map_Union sttya sttym) = Some t'.\n\nRequire Import Coq.Logic.FunctionalExtensionality.\nAxiom subst_rho_eps_aux_1 :\n forall rho rho' n x e e1 sa sa',\n   lc_type_eps e ->\n   lc_type_sa sa' ->\n   (fold_subst_eps rho e1) = (fold_subst_eps rho' (closing_rgn_in_eps2 n x e)) ->\n   fold_subst_sa rho sa = fold_subst_sa rho' (closing_rgn_in_sa2 n x sa') /\\ e1 sa /\\ e sa'.\n", "meta": {"author": "esmifro", "repo": "SurfaceEffects", "sha": "3450e4b771de4062ab73ee20947adf3f9de579ba", "save_path": "github-repos/coq/esmifro-SurfaceEffects", "path": "github-repos/coq/esmifro-SurfaceEffects/SurfaceEffects-3450e4b771de4062ab73ee20947adf3f9de579ba/Axioms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2618379031031892}}
{"text": "Require Import Raft.\nRequire Import RaftRefinementInterface.\n\nSection OneLeaderLogPerTerm.\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 one_leaderLog_per_term (net : 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  (* convenience *)\n  Definition one_leaderLog_per_term_log (net : 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      ll = ll'.\n\n  (* convenience *)\n  Definition one_leaderLog_per_term_host (net : 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'.\n\n\n  Class one_leaderLog_per_term_interface : Prop :=\n    {\n      one_leaderLog_per_term_invariant :\n        forall net,\n          refined_raft_intermediate_reachable net ->\n          one_leaderLog_per_term net;\n      one_leaderLog_per_term_log_invariant :\n        forall net,\n          refined_raft_intermediate_reachable net ->\n          one_leaderLog_per_term_log net;\n      one_leaderLog_per_term_host_invariant :\n        forall net,\n          refined_raft_intermediate_reachable net ->\n          one_leaderLog_per_term_host net\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/OneLeaderLogPerTermInterface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2618345415160807}}
{"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.\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.\n\nRequire Import Cover.\nRequire Import MemorySplit.\nRequire Import MemoryMerge.\nRequire Import FulfillStep.\nRequire Import MemoryProps.\n\nRequire Import LowerMemory.\nRequire Import JoinedView.\n\nRequire Import MaxView.\nRequire Import Delayed.\n\nRequire Import Lia.\n\nRequire Import JoinedView.\nRequire Import SeqLift.\nRequire Import Sequential.\n\n\nRecord sim_tview\n       (f: Mapping.ts)\n       (flag_src: Loc.t -> bool)\n       (rel_vers: Loc.t -> version)\n       (tvw_src: TView.t) (tvw_tgt: TView.t)\n  :\n    Prop :=\n  sim_tview_intro {\n      sim_tview_rel: forall loc,\n        sim_view (fun loc0 => loc0 <> loc) f (rel_vers loc) (tvw_src.(TView.rel) loc) (tvw_tgt.(TView.rel) loc);\n      sim_tview_cur: sim_view (fun loc => flag_src loc = false) f (Mapping.vers f) tvw_src.(TView.cur) tvw_tgt.(TView.cur);\n      sim_tview_acq: sim_view (fun loc => flag_src loc = false) f (Mapping.vers f) tvw_src.(TView.acq) tvw_tgt.(TView.acq);\n      rel_vers_wf: forall loc, version_wf f (rel_vers loc);\n    }.\n\nLemma sim_tview_mon_latest f0 f1 flag_src rel_vers tvw_src tvw_tgt\n      (SIM: sim_tview f0 flag_src rel_vers tvw_src tvw_tgt)\n      (LE: Mapping.les f0 f1)\n      (WF0: Mapping.wfs f0)\n      (WF1: Mapping.wfs f1)\n  :\n    sim_tview f1 flag_src rel_vers tvw_src tvw_tgt.\nProof.\n  econs.\n  { i. erewrite <- sim_view_mon_mapping; [eapply SIM|..]; eauto. eapply SIM. }\n  { eapply sim_view_mon_latest; eauto. eapply SIM. }\n  { eapply sim_view_mon_latest; eauto. eapply SIM. }\n  { i. eapply version_wf_mapping_mon; eauto. eapply SIM. }\nQed.\n\nLemma sim_tview_tgt_mon f flag_src rel_vers tvw_src tvw_tgt0 tvw_tgt1\n      (SIM: sim_tview f flag_src rel_vers tvw_src tvw_tgt0)\n      (TVIEW: TView.le tvw_tgt0 tvw_tgt1)\n  :\n    sim_tview f flag_src rel_vers tvw_src tvw_tgt1.\nProof.\n  econs.\n  { i. eapply sim_view_mon_tgt.\n    { eapply SIM. }\n    { eapply TVIEW. }\n  }\n  { eapply sim_view_mon_tgt.\n    { eapply SIM. }\n    { eapply TVIEW. }\n  }\n  { eapply sim_view_mon_tgt.\n    { eapply SIM. }\n    { eapply TVIEW. }\n  }\n  { eapply SIM. }\nQed.\n\nVariant sim_local\n        (f: Mapping.ts) (vers: versions)\n        (srctm: Loc.t -> Time.t)\n        (flag_src: Loc.t -> bool)\n        (flag_tgt: Loc.t -> bool)\n  :\n    Local.t -> Local.t -> Prop :=\n| sim_local_intro\n    tvw_src tvw_tgt prom_src prom_tgt rel_vers\n    (TVIEW: sim_tview f flag_src rel_vers tvw_src tvw_tgt)\n    (PROMISES: sim_promises srctm flag_src flag_tgt f vers prom_src prom_tgt)\n    (RELVERS: wf_release_vers vers prom_tgt rel_vers)\n    (FLAGSRC: forall loc (FLAG: flag_src loc = true),\n        (<<RLX: tvw_src.(TView.cur).(View.rlx) loc = tvw_src.(TView.cur).(View.pln) loc>>))\n    (SRCTM: forall loc, srctm loc = tvw_src.(TView.cur).(View.rlx) loc)\n  :\n    sim_local\n      f vers srctm flag_src flag_tgt\n      (Local.mk tvw_src prom_src)\n      (Local.mk tvw_tgt prom_tgt)\n.\n\nLemma sim_local_tgt_mon f vers srctm flag_src flag_tgt lc_src lc_tgt0 lc_tgt1\n      (SIM: sim_local f vers srctm flag_src flag_tgt lc_src lc_tgt0)\n      (PROM: lc_tgt0.(Local.promises) = lc_tgt1.(Local.promises))\n      (TVIEW: TView.le lc_tgt0.(Local.tview) lc_tgt1.(Local.tview))\n  :\n    sim_local f vers srctm flag_src flag_tgt lc_src lc_tgt1.\nProof.\n  inv SIM. destruct lc_tgt1. ss. clarify. econs; eauto.\n  eapply sim_tview_tgt_mon; eauto.\nQed.\n\nLemma sim_local_consistent f vers srctm flag_src flag_tgt lc_src lc_tgt\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n      (SIM: sim_local f vers srctm flag_src flag_tgt lc_src lc_tgt)\n      (WF: Mapping.wfs f)\n  :\n    Local.promise_consistent lc_src.\nProof.\n  inv SIM. ii. ss.\n  hexploit sim_promises_get_if; eauto. i. des.\n  { eapply sim_timestamp_lt.\n    { eapply sim_view_rlx.\n      { eapply sim_tview_cur. eauto. }\n      { ss. destruct (flag_src loc) eqn:FLAG; auto.\n        erewrite sim_promises_none in PROMISE; eauto; ss.\n      }\n    }\n    { eauto. }\n    { eapply CONSISTENT; eauto. inv MSG0; ss. }\n    { eauto. }\n    { eapply mapping_latest_wf_loc. }\n  }\n  { rewrite SRCTM in *. auto. }\nQed.\n\nLemma sim_local_consistent_ex f vers flag_src flag_tgt lc_src lc_tgt\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n      (SIM: exists srctm, sim_local f vers srctm flag_src flag_tgt lc_src lc_tgt)\n      (WF: Mapping.wfs f)\n  :\n    Local.promise_consistent lc_src.\nProof.\n  des. eapply sim_local_consistent; eauto.\nQed.\n\nLemma sim_local_racy f vers srctm flag_src flag_tgt lc_src lc_tgt mem_src mem_tgt loc to ord\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n      (MEM: sim_memory srctm flag_src f vers mem_src mem_tgt)\n      (SIM: sim_local f vers srctm flag_src flag_tgt lc_src lc_tgt)\n      (WF: Mapping.wfs f)\n      (RACY: Local.is_racy lc_tgt mem_tgt loc to ord)\n      (FLAGSRC: flag_src loc = false)\n      (FLAGTGT: flag_tgt loc = false)\n  :\n    exists to_src, Local.is_racy lc_src mem_src loc to_src ord.\nProof.\n  inv RACY. hexploit sim_memory_get; eauto. i. des.\n  exists to_src. econs; eauto.\n  { inv SIM. ss.\n    destruct (Memory.get loc to_src prom_src) eqn:EQ; ss.\n    destruct p. hexploit sim_promises_get_if; eauto. i. des; ss; clarify.\n    eapply sim_timestamp_exact_unique in TO; eauto; clarify.\n  }\n  { unfold TView.racy_view in *. eapply sim_timestamp_lt; eauto.\n    { inv SIM. ss. eapply TVIEW. auto. }\n    { eapply mapping_latest_wf_loc. }\n  }\n  { inv MSG; ss. }\n  { i. hexploit MSG2; auto. i. inv MSG; ss. }\nQed.\n\nVariant max_value_src (loc: Loc.t) (v: option Const.t)\n        (mem: Memory.t)\n  :\n    forall (lc: Local.t), Prop :=\n| max_value_src_intro\n    tvw prom\n    (MAX: forall v0 (VAL: v = Some v0),\n        exists released,\n          (<<MAX: max_readable\n                    mem\n                    prom\n                    loc\n                    (tvw.(TView.cur).(View.pln) loc)\n                    v0 released>>))\n    (NONMAX: forall (VAL: v = None),\n        forall val released,\n          ~ max_readable mem prom loc (tvw.(TView.cur).(View.pln) loc) val released)\n  :\n    max_value_src loc v mem (Local.mk tvw prom)\n.\n\nDefinition max_values_src (vs: Loc.t -> option Const.t)\n           (mem: Memory.t) (lc: Local.t): Prop :=\n  forall loc, max_value_src loc (vs loc) mem lc.\n\nVariant max_value_tgt (loc: Loc.t) (v: option Const.t)\n        (mem: Memory.t)\n  :\n    forall (lc: Local.t), Prop :=\n| max_value_tgt_intro\n    tvw prom\n    (MAX: forall v0 (VAL: v = Some v0),\n        exists released,\n          (<<MAX: max_readable\n                    mem\n                    prom\n                    loc\n                    (tvw.(TView.cur).(View.pln) loc)\n                    v0 released>>))\n  :\n    max_value_tgt loc v mem (Local.mk tvw prom)\n.\n\nDefinition max_values_tgt (vs: Loc.t -> option Const.t)\n           (mem: Memory.t) (lc: Local.t): Prop :=\n  forall loc, max_value_tgt loc (vs loc) mem lc.\n\nLemma max_value_tgt_mon loc v mem lc0 lc1\n      (MAXTGT: max_value_tgt loc v mem lc0)\n      (PROM: lc0.(Local.promises) = lc1.(Local.promises))\n      (TVIEW: TView.le lc0.(Local.tview) lc1.(Local.tview))\n      (LOCAL: Local.wf lc1 mem)\n      (CONSISTENT: Local.promise_consistent lc1)\n  :\n  max_value_tgt loc v mem lc1.\nProof.\n  inv MAXTGT. ss. subst. destruct lc1. econs. i.\n  hexploit MAX; eauto. i. des. ss.\n  hexploit max_readable_view_mon; eauto.\nQed.\n\nLemma max_values_tgt_mon vs mem lc0 lc1\n      (MAXTGT: max_values_tgt vs mem lc0)\n      (PROM: lc0.(Local.promises) = lc1.(Local.promises))\n      (TVIEW: TView.le lc0.(Local.tview) lc1.(Local.tview))\n      (LOCAL: Local.wf lc1 mem)\n      (CONSISTENT: Local.promise_consistent lc1)\n  :\n    max_values_tgt vs mem lc1.\nProof.\n  ii. eapply max_value_tgt_mon; eauto.\nQed.\n\nDefinition reserved_space_empty (f: Mapping.ts) (flag_src: Loc.t -> bool)\n           (prom_tgt: Memory.t) (mem_src: Memory.t): Prop :=\n  forall loc to_tgt from_tgt\n         (GETTGT: Memory.get loc to_tgt prom_tgt = Some (from_tgt, Message.reserve))\n         (FLAG: flag_src loc = true),\n  exists to_src from_src,\n    (<<FROM: sim_timestamp_exact (f loc) (f loc).(Mapping.ver) from_src from_tgt>>) /\\\n    (<<TO: sim_timestamp_exact (f loc) (f loc).(Mapping.ver) to_src to_tgt>>) /\\\n    (<<DISJOINT: forall from to msg\n                        (GETSRC: Memory.get loc to mem_src = Some (from, msg)),\n        Interval.disjoint (from_src, to_src) (from, to)>>).\n\nLemma reserved_space_empty_mon_strong f0 f1 flag_src prom_tgt mem_src\n      (RESERVED: reserved_space_empty f0 flag_src prom_tgt mem_src)\n      (MAPLE: Mapping.les_strong f0 f1)\n      (MAPWF0: Mapping.wfs f0)\n      (MAPWF1: Mapping.wfs f1)\n  :\n    reserved_space_empty f1 flag_src prom_tgt mem_src.\nProof.\n  ii. exploit RESERVED; eauto. i. des. esplits; eauto.\n  { eapply sim_timestamp_exact_mon_strong; eauto. }\n  { eapply sim_timestamp_exact_mon_strong; eauto. }\nQed.\n\nLemma reserved_space_empty_reserve_decr f flag_src prom_tgt0 prom_tgt1 mem_src\n      (RESERVED: reserved_space_empty f flag_src prom_tgt0 mem_src)\n      (DECR: forall loc to from\n                    (GET: Memory.get loc to prom_tgt1 = Some (from, Message.reserve))\n                    (FLAG: flag_src loc = true),\n          Memory.get loc to prom_tgt0 = Some (from, Message.reserve))\n  :\n    reserved_space_empty f flag_src prom_tgt1 mem_src.\nProof.\n  ii. exploit RESERVED; eauto.\nQed.\n\nLemma memory_write_reserve_same prom0 mem0 loc from to msg prom1 mem1 kind\n      (WRITE: Memory.write prom0 mem0 loc from to msg prom1 mem1 kind)\n  :\n    forall loc to from\n           (GET: Memory.get loc to prom1 = Some (from, Message.reserve)),\n      Memory.get loc to prom0 = Some (from, Message.reserve).\nProof.\n  inv WRITE. i. erewrite Memory.remove_o in GET; eauto.\n  inv PROMISE.\n  { i. erewrite Memory.add_o in GET; eauto. des_ifs. }\n  { i. erewrite Memory.split_o in GET; eauto. des_ifs. }\n  { i. erewrite Memory.lower_o in GET; eauto. des_ifs. }\n  { i. erewrite Memory.remove_o in GET; eauto. des_ifs. }\nQed.\n\nLemma memory_write_reserve_same_rev prom0 mem0 loc from to msg prom1 mem1 kind\n      (WRITE: Memory.write prom0 mem0 loc from to msg prom1 mem1 kind)\n      (MSG: msg <> Message.reserve)\n  :\n    forall loc to from\n           (GET: Memory.get loc to prom0 = Some (from, Message.reserve)),\n      Memory.get loc to prom1 = Some (from, Message.reserve).\nProof.\n  inv WRITE. i. erewrite Memory.remove_o; eauto. inv PROMISE.\n  { i. erewrite Memory.add_o; eauto. des_ifs.\n    ss. des; clarify. eapply Memory.add_get0 in PROMISES. des; clarify.\n  }\n  { i. erewrite Memory.split_o; eauto. des_ifs.\n    { ss. des; clarify. eapply Memory.split_get0 in PROMISES. des; clarify. }\n    { ss. des; clarify. eapply Memory.split_get0 in PROMISES. des; clarify. }\n  }\n  { i. erewrite Memory.lower_o; eauto. des_ifs.\n    ss. des; clarify. eapply Memory.lower_get0 in PROMISES. des; clarify. inv MSG_LE; ss.\n  }\n  { des_ifs. }\nQed.\n\nLemma memory_write_na_reserve_same prom0 mem0 loc ts from to val prom1 mem1 kind kinds msgs\n      (WRITE: Memory.write_na ts prom0 mem0 loc from to val prom1 mem1 kinds msgs kind)\n  :\n    forall loc to from\n           (GET: Memory.get loc to prom1 = Some (from, Message.reserve)),\n      Memory.get loc to prom0 = Some (from, Message.reserve).\nProof.\n  induction WRITE.\n  { eapply memory_write_reserve_same; eauto. }\n  { i. eapply IHWRITE in GET.\n    eapply memory_write_reserve_same; eauto.\n  }\nQed.\n\nLemma memory_write_na_reserve_same_rev prom0 mem0 loc ts from to val prom1 mem1 kind kinds msgs\n      (WRITE: Memory.write_na ts prom0 mem0 loc from to val prom1 mem1 kinds msgs kind)\n  :\n    forall loc to from\n           (GET: Memory.get loc to prom0 = Some (from, Message.reserve)),\n      Memory.get loc to prom1 = Some (from, Message.reserve).\nProof.\n  induction WRITE.\n  { eapply memory_write_reserve_same_rev; eauto; ss. }\n  { i. eapply IHWRITE.\n    eapply memory_write_reserve_same_rev; eauto; ss.\n    unguard. des; clarify.\n  }\nQed.\n\nLemma reserved_space_empty_covered_decr f flag_src prom_tgt mem_src0 mem_src1\n      (RESERVED: reserved_space_empty f flag_src prom_tgt mem_src0)\n      (DECR: forall loc ts (FLAG: flag_src loc = true) (COVER: covered loc ts mem_src1), covered loc ts mem_src0)\n  :\n    reserved_space_empty f flag_src prom_tgt mem_src1.\nProof.\n  ii. exploit RESERVED; eauto. i. des. esplits; eauto.\n  ii. exploit DECR; eauto.\n  { econs; eauto. }\n  intros x0. inv x0. eapply DISJOINT; eauto.\nQed.\n\nLemma reserved_space_empty_unchanged_loc\n      f flag_src prom_tgt mem_src0 mem_src1\n      (RESERVED: reserved_space_empty f flag_src prom_tgt mem_src0)\n      (UNCH: forall loc (FLAG: flag_src loc = true), unchanged_loc_memory loc mem_src0 mem_src1)\n  :\n    reserved_space_empty f flag_src prom_tgt mem_src1.\nProof.\n  ii. exploit RESERVED; eauto. i. des. esplits; eauto.\n  ii. hexploit UNCH; eauto. i. inv H. rewrite UNCH0 in GETSRC; eauto.\n  eapply DISJOINT; eauto.\nQed.\n\nLemma reserved_space_empty_add f flag_src prom_tgt mem_src0 mem_src1\n      loc from to msg\n      (RESERVED: reserved_space_empty f flag_src prom_tgt mem_src0)\n      (ADD: Memory.add mem_src0 loc from to msg mem_src1)\n      (TOP: top_time from (f loc))\n  :\n    reserved_space_empty f flag_src prom_tgt mem_src1.\nProof.\n  ii. exploit RESERVED; eauto. i. des. esplits; eauto.\n  i. erewrite Memory.add_o in GETSRC; eauto. des_ifs; eauto.\n  ss. des; clarify. eapply interval_le_disjoint.\n  eapply TOP in TO. left. auto.\nQed.\n\nLemma cancel_future_memory_le loc prom0 mem0 prom1 mem1\n      (CANCEL: cancel_future_memory loc prom0 mem0 prom1 mem1)\n  :\n    Memory.le prom1 prom0.\nProof.\n  induction CANCEL.\n  { refl. }\n  etrans; eauto. inv CANCEL. eapply remove_le; eauto.\nQed.\n\nLemma cancel_future_memory_get loc prom0 mem0 prom1 mem1\n      (CANCEL: cancel_future_memory loc prom0 mem0 prom1 mem1)\n  :\n    forall to,\n      Memory.get loc to mem1 =\n      match Memory.get loc to mem0 with\n      | None => None\n      | Some (from, msg) =>\n        match Memory.get loc to prom0 with\n        | None => Some (from, msg)\n        | Some _ =>\n          match Memory.get loc to prom1 with\n          | None => None\n          | Some _ => Some (from, msg)\n          end\n        end\n      end.\nProof.\n  induction CANCEL.\n  { i. des_ifs. }\n  i. inv CANCEL. rewrite IHCANCEL.\n  erewrite (@Memory.remove_o mem1); eauto.\n  erewrite (@Memory.remove_o prom1); eauto. des_ifs.\n  { ss. des; clarify. destruct p0.\n    eapply cancel_future_memory_le in Heq2; eauto.\n    eapply Memory.remove_get0 in PROMISES. des; clarify.\n  }\n  { ss. des; clarify.\n    eapply Memory.remove_get0 in PROMISES. des; clarify.\n  }\nQed.\n\nLemma cancel_future_memory_memory_le loc prom0 mem0 prom1 mem1\n      (CANCEL: cancel_future_memory loc prom0 mem0 prom1 mem1)\n      (MLE: Memory.le prom0 mem0)\n  :\n    Memory.le prom1 mem1.\nProof.\n  revert MLE. induction CANCEL; auto. i. eapply IHCANCEL.\n  eapply promise_memory_le; eauto.\nQed.\n\nLemma reserved_space_empty_fulfilled_memory f srctm vers\n      flag_src0 flag_src1 flag_tgt prom_tgt mem_src0 mem_src1\n      loc prom_src0 prom_src1\n      (RESERVED: reserved_space_empty f flag_src0 prom_tgt mem_src0)\n      (CANCEL: cancel_future_memory loc prom_src0 mem_src0 prom_src1 mem_src1)\n      (PROMISE: sim_promises srctm flag_src0 flag_tgt f vers prom_src0 prom_tgt)\n      (MLE: Memory.le prom_src0 mem_src0)\n      (NONE: forall from to msg\n                    (GET: Memory.get loc to prom_src1 = Some (from, msg)),\n          msg <> Message.reserve)\n      (FLAGS: forall loc0 (FLAG: flag_src1 loc0 = true), flag_src0 loc0 = true \\/ loc0 = loc)\n  :\n    reserved_space_empty f flag_src1 prom_tgt mem_src1.\nProof.\n  destruct (flag_src0 loc) eqn:EQ.\n  { revert RESERVED. clear MLE NONE PROMISE. induction CANCEL; auto.\n    { ii. exploit RESERVED; eauto. exploit FLAGS; eauto. i. des; clarify. }\n    i. eapply IHCANCEL.\n    inv CANCEL. eapply reserved_space_empty_covered_decr; eauto.\n    i. eapply remove_covered in COVER; eauto. des; eauto.\n  }\n  { ii. hexploit cancel_future_memory_memory_le; eauto. intros MLE1.\n    destruct (Loc.eq_dec loc0 loc).\n    { subst. hexploit sim_promises_get; eauto. i. des. esplits; eauto.\n      i. hexploit GET; eauto. i. des. dup GET0. eapply MLE in GET0.\n      dup GETSRC. erewrite cancel_future_memory_get in GETSRC; eauto. des_ifs.\n      { hexploit Memory.get_disjoint.\n        { eapply GET0. }\n        { eapply Heq. }\n        i. des; clarify. exfalso.\n        destruct p0. dup Heq1. eapply MLE1 in Heq1. clarify.\n        inv MSG. eapply NONE in Heq2; eauto.\n      }\n      { hexploit Memory.get_disjoint.\n        { eapply GET0. }\n        { eapply Heq. }\n        i. des; clarify.\n      }\n    }\n    { exploit RESERVED; eauto.\n      { eapply FLAGS in FLAG. des; clarify. }\n      i. des. esplits; eauto.\n      i. eapply cancel_future_unchanged_loc in CANCEL; eauto. des.\n      inv MEM. rewrite UNCH in GETSRC. eauto.\n    }\n  }\nQed.\n\nVariant sim_thread\n        (f: Mapping.ts) (vers: versions)\n        (flag_src: Loc.t -> bool)\n        (flag_tgt: Loc.t -> bool)\n        (vs_src: Loc.t -> option Const.t)\n        (vs_tgt: Loc.t -> option Const.t)\n        mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt: Prop :=\n| sim_thread_intro\n    srctm\n    (SC: sim_timemap (fun _ => True) f (Mapping.vers f) sc_src sc_tgt)\n    (MEM: sim_memory srctm flag_src f vers mem_src mem_tgt)\n    (LOCAL: sim_local f vers srctm flag_src flag_tgt lc_src lc_tgt)\n    (MAXSRC: max_values_src vs_src mem_src lc_src)\n    (MAXTGT: max_values_tgt vs_tgt mem_tgt lc_tgt)\n    (PERM: forall loc, option_rel (fun _ _ => True) (vs_src loc) (vs_tgt loc))\n    (FIN: __guard__(exists dom, (<<DOM: forall loc, (flag_src loc = true) <-> (List.In loc dom)>>)))\n    (VERSIONED: versioned_memory vers mem_tgt)\n    (SIMCLOSED: sim_closed_memory f mem_src)\n    (MAXTIMES: forall loc (FLAG: flag_src loc = true),\n        srctm loc = Memory.max_ts loc mem_src)\n    (RESERVED: reserved_space_empty f flag_src lc_tgt.(Local.promises) mem_src)\n    (FINALIZED: promise_finalized f lc_src.(Local.promises) mem_tgt)\n.\n\nLemma max_value_src_exists loc mem lc\n  :\n    exists v,\n      (<<MAX: max_value_src loc v mem lc>>).\nProof.\n  destruct (classic (exists val released, max_readable mem lc.(Local.promises) loc (View.pln (TView.cur lc.(Local.tview)) loc) val released)).\n  { des. exists (Some val). splits. destruct lc. econs; ss.\n    i. clarify. esplits; eauto.\n  }\n  { exists None. splits. destruct lc. econs; ss.\n    ii. eapply H. eauto.\n  }\nQed.\n\nLemma max_values_src_exists mem lc\n  :\n    exists vs,\n      (<<MAX: max_values_src vs mem lc>>).\nProof.\n  eapply (choice (fun loc v => max_value_src loc v mem lc)).\n  i. eapply max_value_src_exists.\nQed.\n\nLemma max_value_src_inj loc mem lc v0 v1\n      (MAX0: max_value_src loc v0 mem lc)\n      (MAX1: max_value_src loc v1 mem lc)\n  :\n    v0 = v1.\nProof.\n  inv MAX0. inv MAX1. destruct v0, v1; auto.\n  { hexploit MAX; eauto. hexploit MAX0; eauto. i. des.\n    f_equal. eapply max_readable_inj; eauto.\n  }\n  { exfalso. hexploit MAX; eauto. i. des. eapply NONMAX0; eauto. }\n  { exfalso. hexploit MAX0; eauto. i. des. eapply NONMAX; eauto. }\nQed.\n\nLemma max_value_src_mon loc v mem lc0 lc1\n      (MAXSRC: max_value_src loc (Some v) mem lc0)\n      (PROM: lc0.(Local.promises) = lc1.(Local.promises))\n      (TVIEW: TView.le lc0.(Local.tview) lc1.(Local.tview))\n      (LOCAL: Local.wf lc1 mem)\n      (CONSISTENT: Local.promise_consistent lc1)\n  :\n    max_value_src loc (Some v) mem lc1.\nProof.\n  inv MAXSRC. ss. subst. destruct lc1. econs; ss.\n  i. clarify.\n  hexploit MAX; eauto. i. des. esplits.\n  hexploit max_readable_view_mon; eauto.\nQed.\n\nLemma race_non_max_readable mem prom tvw loc to\n      (MAX: Local.is_racy (Local.mk tvw prom) mem loc to Ordering.na)\n  :\n    forall val released, ~ max_readable mem prom loc (tvw.(TView.cur).(View.pln) loc) val released.\nProof.\n  ii. inv H. inv MAX.\n  eapply MAX0 in RACE; eauto. ss. clarify.\nQed.\n\nLemma sim_memory_src_flag_max_concrete\n      f vers srctm flag_src\n      mem_src mem_tgt\n      (SIM: sim_memory srctm flag_src f vers mem_src mem_tgt)\n      loc\n      (FLAG: flag_src loc = true)\n      (CLOSED: exists from msg, Memory.get loc (srctm loc) mem_src = Some (from, msg))\n  :\n    Memory.max_ts loc mem_src = srctm loc.\nProof.\n  des. hexploit Memory.max_ts_spec.\n  { eapply CLOSED. }\n  i. des. eapply TimeFacts.antisym; eauto.\n  hexploit sim_memory_top; eauto. intros TOP.\n  hexploit sim_memory_sound.\n  { eauto. }\n  { eapply GET. }\n  i. des.\n  { eapply TOP in TO. left. eapply TimeFacts.le_lt_lt; eauto. }\n  { clarify. }\nQed.\n\nLemma max_value_src_flag_none f vers srctm flag_src flag_tgt lc_src lc_tgt mem_src mem_tgt loc\n      (MEM: sim_memory srctm flag_src f vers mem_src mem_tgt)\n      (LOCAL: sim_local f vers srctm flag_src flag_tgt lc_src lc_tgt)\n      (MAX: max_value_src loc None mem_src lc_src)\n      (LOCALWF: Local.wf lc_src mem_src)\n      (WF: Mapping.wfs f)\n  :\n    flag_src loc = false.\nProof.\n  destruct (flag_src loc) eqn:FLAG; auto. exfalso.\n  inv LOCAL. hexploit FLAGSRC; eauto. i. des. subst.\n  inv LOCALWF. inv TVIEW_CLOSED.\n  inv CUR. exploit RLX; eauto. i. des. ss.\n  inv MAX. hexploit NONMAX; eauto. ii. eapply H0. econs.\n  { rewrite <- H. eauto. }\n  { inv PROMISES. eapply NONE; eauto. }\n  { i. hexploit sim_memory_src_flag_max_concrete; eauto.\n    { rewrite SRCTM. eauto. }\n    i. eapply Memory.max_ts_spec in GET. des.\n    rewrite H1 in MAX. exfalso.\n    eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n    { eapply TS. }\n    { rewrite <- H. rewrite <- SRCTM. eauto. }\n  }\nQed.\n\nLemma promise_max_readable\n      prom0 mem0 loc from to msg prom1 mem1 kind tvw\n      (PROMISE: Memory.promise prom0 mem0 loc from to msg prom1 mem1 kind)\n  :\n  forall val0 released0,\n    max_readable mem0 prom0 loc tvw val0 released0 <-> max_readable mem1 prom1 loc tvw val0 released0.\nProof.\n  i. split.\n  { intros MAX. inv MAX.\n    hexploit unchangable_promise.\n    { eauto. }\n    { econs; eauto. }\n    i. inv H. ss. econs; eauto.\n    i. inv PROMISE.\n    { erewrite Memory.add_o; eauto.\n      erewrite (@Memory.add_o mem1 mem0) in GET1; eauto. des_ifs.\n      eapply MAX0; eauto.\n    }\n    { erewrite Memory.split_o; eauto.\n      erewrite (@Memory.split_o mem1 mem0) in GET1; eauto. des_ifs.\n      eapply MAX0; eauto.\n    }\n    { erewrite Memory.lower_o; eauto.\n      erewrite (@Memory.lower_o mem1 mem0) in GET1; eauto. des_ifs.\n      eapply MAX0; eauto.\n    }\n    { erewrite Memory.remove_o; eauto.\n      erewrite (@Memory.remove_o mem1 mem0) in GET1; eauto. des_ifs.\n      eapply MAX0; eauto.\n    }\n  }\n  { i. inv H. inv PROMISE.\n    { erewrite Memory.add_o in GET; eauto.\n      erewrite Memory.add_o in NONE; eauto. des_ifs.\n      econs; eauto. i.\n      hexploit MAX; eauto.\n      { eapply Memory.add_get1; eauto. }\n      i. erewrite Memory.add_o in H; eauto.\n      des_ifs. ss. des; clarify.\n      eapply Memory.add_get0 in MEM. des; clarify.\n    }\n    { erewrite Memory.split_o in GET; eauto.\n      erewrite Memory.split_o in NONE; eauto. des_ifs.\n      econs; eauto. i.\n      hexploit Memory.split_o; [eapply MEM|]. i.\n      rewrite GET0 in H. des_ifs.\n      { ss. des; clarify. eapply Memory.split_get0 in MEM. des; clarify. }\n      { ss. des; clarify. eapply Memory.split_get0 in PROMISES.\n        eapply Memory.split_get0 in MEM. des; clarify.\n      }\n      { ss. des; clarify. hexploit MAX; eauto. i.\n        erewrite Memory.split_o in H0; eauto.\n        des_ifs; ss; des; clarify.\n      }\n    }\n    { erewrite Memory.lower_o in GET; eauto.\n      erewrite Memory.lower_o in NONE; eauto. des_ifs.\n      econs; eauto. i.\n      hexploit Memory.lower_o; [eapply MEM|]. i.\n      rewrite GET0 in H. des_ifs.\n      { ss. des; clarify. eapply Memory.lower_get0 in MEM. des; clarify.\n        eapply Memory.lower_get0 in PROMISES. des; eauto.\n      }\n      { ss. des; clarify. hexploit MAX; eauto. i.\n        erewrite Memory.lower_o in H0; eauto.\n        des_ifs; ss; des; clarify.\n      }\n    }\n    { erewrite Memory.remove_o in GET; eauto.\n      erewrite Memory.remove_o in NONE; eauto. des_ifs.\n      econs; eauto. i.\n      hexploit Memory.remove_o; [eapply MEM|]. i.\n      rewrite GET0 in H. des_ifs.\n      { ss. des; clarify. eapply Memory.remove_get0 in MEM. des; clarify. }\n      { ss. des; clarify. hexploit MAX; eauto. i.\n        erewrite Memory.remove_o in H0; eauto.\n        des_ifs; ss; des; clarify.\n      }\n    }\n  }\nQed.\n\nLemma promise_max_values_src\n      lc0 mem0 loc from to msg lc1 mem1 kind vs\n      (PROMISE: Local.promise_step lc0 mem0 loc from to msg lc1 mem1 kind)\n      (MAX: max_values_src vs mem0 lc0)\n  :\n  max_values_src vs mem1 lc1.\nProof.\n  inv PROMISE. ii. specialize (MAX loc0). inv MAX.\n  destruct (Loc.eq_dec loc0 loc); subst.\n  { econs.\n    { i. hexploit MAX0; eauto. i. des. esplits. ss.\n      erewrite <- promise_max_readable; eauto.\n    }\n    { i. hexploit NONMAX; eauto. ii. eapply H. ss.\n      erewrite promise_max_readable; eauto.\n    }\n  }\n  { eapply promise_unchanged_loc in PROMISE0; eauto. des.\n    econs.\n    { i. hexploit MAX0; eauto. i. des. esplits. ss.\n      erewrite <- unchanged_loc_max_readable; eauto.\n    }\n    { i. hexploit NONMAX; eauto. ii. eapply H. ss.\n      erewrite unchanged_loc_max_readable; eauto.\n    }\n  }\nQed.\n\nLemma promise_step_max_values_src\n      lang st0 st1 pf e lc0 lc1 sc0 sc1 mem0 mem1 vs\n      (PROMISE: Thread.promise_step pf e (Thread.mk lang st0 lc0 sc0 mem0) (Thread.mk _ st1 lc1 sc1 mem1))\n      (MAX: max_values_src vs mem0 lc0)\n  :\n  max_values_src vs mem1 lc1.\nProof.\n  inv PROMISE. eapply promise_max_values_src; eauto.\nQed.\n\nRequire Import Pred.\n\nLemma promise_steps_max_values_src\n      lang st0 st1 lc0 lc1 sc0 sc1 mem0 mem1 vs\n      (PROMISE: rtc (tau (@pred_step is_promise _)) (Thread.mk lang st0 lc0 sc0 mem0) (Thread.mk _ st1 lc1 sc1 mem1))\n      (MAX: max_values_src vs mem0 lc0)\n  :\n  max_values_src vs mem1 lc1.\nProof.\n  remember (Thread.mk lang st0 lc0 sc0 mem0).\n  remember (Thread.mk lang st1 lc1 sc1 mem1).\n  revert st0 st1 lc0 lc1 sc0 sc1 mem0 mem1 Heqt Heqt0 MAX. induction PROMISE; i; clarify.\n  inv H. inv TSTEP. inv STEP. inv STEP0; [|inv STEP; inv LOCAL; ss].\n  destruct y. eapply promise_step_max_values_src in STEP; eauto.\nQed.\n\nLemma no_flag_max_value_same f vers srctm flag_src flag_tgt lc_src lc_tgt mem_src mem_tgt loc v_src\n      (MEM: sim_memory srctm flag_src f vers mem_src mem_tgt)\n      (LOCAL: sim_local f vers srctm flag_src flag_tgt lc_src lc_tgt)\n      (FLAGSRC: flag_src loc = false)\n      (FLAGTGT: flag_tgt loc = false)\n      (MAX: max_value_src loc (Some v_src) mem_src lc_src)\n      (LOCALWF: Local.wf lc_tgt mem_tgt)\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n      (WF: Mapping.wfs f)\n  :\n  exists v_tgt,\n    (<<MAX: max_value_tgt loc (Some v_tgt) mem_tgt lc_tgt>>) /\\ (<<VAL: Const.le v_tgt v_src>>).\nProof.\n  inv MAX. destruct lc_tgt. i. clarify.\n  hexploit MAX0; eauto. i. des.\n  assert (exists val released, max_readable mem_tgt promises loc (View.pln (TView.cur tview) loc) val released).\n  { apply NNPP. ii. hexploit non_max_readable_race.\n    { ii. eapply H; eauto. }\n    { eauto. }\n    { eauto. }\n    { i. des. eapply sim_local_racy in H0; eauto. des.\n      eapply race_non_max_readable in H0; eauto. }\n  }\n  des. exists val. esplits.\n  { econs; eauto. i. clarify. esplits; eauto. }\n  inv H. hexploit sim_memory_get; eauto; ss. i. des.\n  hexploit sim_timestamp_le.\n  2:{ eapply TO. }\n  2:{ refl. }\n  { inv LOCAL. eapply TVIEW; ss. }\n  { eauto. }\n  { eapply mapping_latest_wf_loc. }\n  i. inv MAX. inv H.\n  { hexploit MAX2; eauto.\n    { inv MSG; ss. }\n    i. inv LOCAL. hexploit sim_promises_get_if; eauto.\n    i. des.\n    2:{ rewrite FLAGTGT in *; ss. }\n    eapply sim_timestamp_exact_unique in TO; eauto.\n    2:{ eapply mapping_latest_wf_loc. }\n    subst. clarify.\n  }\n  { inv H0. clarify. esplits; eauto. inv MSG; auto. }\nQed.\n\nLemma sim_thread_tgt_read_na\n      f vers flag_src flag_tgt vs_src vs_tgt\n      mem_src mem_tgt lc_src lc_tgt0 sc_src sc_tgt\n      loc to_tgt val_tgt vw_tgt lc_tgt1\n      (READ: Local.read_step lc_tgt0 mem_tgt loc to_tgt val_tgt vw_tgt Ordering.na lc_tgt1)\n      (SIM: sim_thread\n              f vers flag_src flag_tgt vs_src vs_tgt\n              mem_src mem_tgt lc_src lc_tgt0 sc_src sc_tgt)\n      (CONSISTENT: Local.promise_consistent lc_tgt1)\n      (LOCAL: Local.wf lc_tgt0 mem_tgt)\n      (MEM: Memory.closed mem_tgt)\n  :\n    (<<SIM: sim_thread\n              f vers flag_src flag_tgt vs_src vs_tgt\n              mem_src mem_tgt lc_src lc_tgt1 sc_src sc_tgt>>) /\\\n    (<<VAL: forall val (VALS: vs_tgt loc = Some val), Const.le val_tgt val>>).\nProof.\n  hexploit Local.read_step_future; eauto.\n  i. des. splits.\n  { inv SIM. econs; eauto.\n    { eapply sim_local_tgt_mon; eauto.\n      { inv READ; ss. }\n    }\n    { eapply max_values_tgt_mon; eauto.\n      { inv READ; ss. }\n    }\n    { inv READ. ss. }\n  }\n  { i. inv SIM. specialize (MAXTGT loc). inv MAXTGT.\n    hexploit MAX; eauto. i. des.\n    hexploit max_readable_read_only; eauto.\n    i. des; auto.\n  }\nQed.\n\nLemma sim_thread_tgt_read_na_racy\n      f vers flag_src flag_tgt vs_src vs_tgt\n      mem_src mem_tgt lc_src lc_tgt0 sc_src sc_tgt\n      loc to val_tgt ord\n      (READ: Local.racy_read_step lc_tgt0 mem_tgt loc to val_tgt ord)\n      (SIM: sim_thread\n              f vers flag_src flag_tgt vs_src vs_tgt\n              mem_src mem_tgt lc_src lc_tgt0 sc_src sc_tgt)\n      (LOCAL: Local.wf lc_tgt0 mem_tgt)\n  :\n    vs_tgt loc = None.\nProof.\n  destruct (vs_tgt loc) eqn:VAL; auto.\n  inv SIM. specialize (MAXTGT loc). inv MAXTGT. hexploit MAX; eauto. i. des.\n  exfalso. eapply max_readable_not_read_race; eauto.\n  Unshelve.\nQed.\n\nLemma sim_thread_src_read_na\n      f vers flag_src flag_tgt vs_src vs_tgt\n      mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt\n      loc val_src val\n      (SIM: sim_thread\n              f vers flag_src flag_tgt vs_src vs_tgt\n              mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt)\n      (VALS: vs_src loc = Some val)\n      (VAL: Const.le val_src val)\n      (LOCAL: Local.wf lc_src mem_src)\n  :\n    exists to vw,\n      Local.read_step lc_src mem_src loc to val_src vw Ordering.na lc_src.\nProof.\n  inv SIM. specialize (MAXSRC loc). inv MAXSRC. hexploit MAX; eauto. i. des.\n  hexploit max_readable_read.\n  { eauto. }\n  { eauto. }\n  { eauto. }\n  { instantiate (1:=val_src). auto. }\n  i. des. esplits; eauto.\nQed.\n\nLemma sim_thread_src_read_na_racy\n      f vers flag_src flag_tgt vs_src vs_tgt\n      mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt\n      loc val_src\n      (SIM: sim_thread\n              f vers flag_src flag_tgt vs_src vs_tgt\n              mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt)\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n      (LOCAL: Local.wf lc_src mem_src)\n      (VALS: vs_src loc = None)\n      (WF: Mapping.wfs f)\n  :\n    exists to_src, Local.racy_read_step lc_src mem_src loc to_src val_src Ordering.na.\nProof.\n  inv SIM. specialize (MAXSRC loc). inv MAXSRC.\n  hexploit non_max_readable_read; eauto.\n  eapply sim_local_consistent; eauto.\nQed.\n\nLemma sim_thread_tgt_write_na_racy\n      f vers flag_src flag_tgt vs_src vs_tgt\n      mem_src mem_tgt lc_src lc_tgt0 sc_src sc_tgt\n      loc to\n      (WRITE: Local.racy_write_step lc_tgt0 mem_tgt loc to Ordering.na)\n      (SIM: sim_thread\n              f vers flag_src flag_tgt vs_src vs_tgt\n              mem_src mem_tgt lc_src lc_tgt0 sc_src sc_tgt)\n      (LOCAL: Local.wf lc_tgt0 mem_tgt)\n  :\n    vs_tgt loc = None.\nProof.\n  destruct (vs_tgt loc) eqn:VAL; auto.\n  inv SIM. specialize (MAXTGT loc). inv MAXTGT. hexploit MAX; eauto. i. des.\n  exfalso. eapply max_readable_not_write_race; eauto.\nQed.\n\nLemma sim_thread_src_write_na_racy\n      f vers flag_src flag_tgt vs_src vs_tgt\n      mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt\n      loc\n      (SIM: sim_thread\n              f vers flag_src flag_tgt vs_src vs_tgt\n              mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt)\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n      (LOCAL: Local.wf lc_src mem_src)\n      (VALS: vs_src loc = None)\n      (WF: Mapping.wfs f)\n  :\n    exists to_src, Local.racy_write_step lc_src mem_src loc to_src Ordering.na.\nProof.\n  inv SIM. specialize (MAXSRC loc). inv MAXSRC.\n  hexploit non_max_readable_write; eauto.\n  eapply sim_local_consistent; eauto.\nQed.\n\nLemma local_write_step_write_na_step\n      lc0 sc0 mem0 loc from to val releasedm released lc1 sc1 mem1 kind\n      (WRITE: Local.write_step lc0 sc0 mem0 loc from to val releasedm released Ordering.na lc1 sc1 mem1 kind)\n  :\n    Local.write_na_step lc0 sc0 mem0 loc from to val Ordering.na lc1 sc1 mem1 [] [] kind.\nProof.\n  inv WRITE. econs; eauto. econs.\n  { eapply WRITABLE. }\n  exact WRITE0.\nQed.\n\nLemma sim_thread_tgt_flag_up\n      f vers flag_src flag_tgt vs_src vs_tgt mem_src0 mem_tgt lc_src0 lc_tgt sc_src sc_tgt loc\n      (SIM: sim_thread\n              f vers flag_src flag_tgt vs_src vs_tgt\n              mem_src0 mem_tgt lc_src0 lc_tgt sc_src sc_tgt)\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n      (LOCAL: Local.wf lc_src0 mem_src0)\n      (MEM: Memory.closed mem_src0)\n      (SC: Memory.closed_timemap sc_src mem_src0)\n      (WF: Mapping.wfs f)\n      lang st\n  :\n    exists mem_src1 lc_src1,\n      (<<STEPS: rtc (@Thread.tau_step _)\n                    (Thread.mk lang st lc_src0 sc_src mem_src0)\n                    (Thread.mk _ st lc_src1 sc_src mem_src1)>>) /\\\n      (<<NONE: forall to from val released (GET: Memory.get loc to lc_src1.(Local.promises) = Some (from, Message.concrete val released)),\n          released = None>>) /\\\n      (<<SIM: sim_thread\n                f vers flag_src (fun loc0 => if Loc.eq_dec loc0 loc\n                                             then true\n                                             else flag_tgt loc0)\n                vs_src vs_tgt\n                mem_src1 mem_tgt lc_src1 lc_tgt sc_src sc_tgt>>) /\\\n      (<<SPACE: space_future_memory (unchangable mem_tgt lc_tgt.(Local.promises)) f mem_src0 f mem_src1>>)\n.\nProof.\n  inv SIM. dup LOCAL0. inv LOCAL0.\n  hexploit tgt_flag_up_sim_promises.\n  { eauto. }\n  { eauto. }\n  { eapply sim_local_consistent in CONSISTENT; eauto.\n    i. rewrite SRCTM. eapply CONSISTENT; eauto.\n  }\n  { eapply LOCAL. }\n  { eapply MEM. }\n  { auto. }\n  i. des. esplits; [eapply STEPS|..].\n  { i. ss. eapply NONE; eauto. }\n  { econs; auto.\n    { eauto. }\n    { econs; eauto. }\n    { ii. hexploit (MAXSRC loc0). i. inv H. econs.\n      { i. hexploit MAX; eauto. i. des. esplits. eapply VALS; eauto. }\n      { i. hexploit NONMAX; eauto. ii. eapply H. eapply VALS; eauto. }\n    }\n    { eapply sim_closed_memory_future; eauto.\n      eapply Thread.rtc_tau_step_future in STEPS; eauto.\n      ss. des. eapply Memory.future_future_weak; eauto.\n    }\n    { i. rewrite MAXTS. auto. }\n    { eapply reserved_space_empty_covered_decr; eauto.\n      i. eapply COVERED; eauto.\n    }\n  }\n  { eapply space_future_covered_decr. i. eapply COVERED; eauto. }\nQed.\n\nLemma lower_write_memory_le prom0 mem0 loc from to msg prom1 mem1 kind\n      (WRITE: Memory.write prom0 mem0 loc from to msg prom1 mem1 kind)\n      (KIND: Memory.op_kind_is_lower kind)\n  :\n    Memory.le prom1 prom0.\nProof.\n  destruct kind; ss. inv WRITE. inv PROMISE. ii.\n  erewrite Memory.remove_o in LHS; eauto.\n  erewrite Memory.lower_o in LHS; eauto. des_ifs.\nQed.\n\nLemma na_write_max_readable\n      mem0 prom0 loc ts val_old released\n      prom1 mem1 msgs kinds kind from to val_new\n      (MAX: max_readable mem0 prom0 loc ts val_old released)\n      (WRITE: Memory.write_na ts prom0 mem0 loc from to val_new prom1 mem1 msgs kinds kind)\n      (LOWER: mem1 = mem0)\n  :\n    max_readable mem1 prom1 loc to val_new None.\nProof.\n  hexploit write_na_lower_memory_lower; eauto. i. des.\n  destruct MAX.\n  remember (Message.concrete val_old released) as msg_old. clear Heqmsg_old.\n  revert from0 msg_old GET NONE MAX KINDS KIND. induction WRITE.\n  { i. destruct kind; ss. inv WRITE. inv PROMISE.\n    hexploit lower_same_same; [apply PROMISES|]. i. subst.\n    hexploit lower_same_same; [apply MEM|]. i. subst.\n    econs.\n    { eapply Memory.lower_get0; eauto. }\n    { erewrite Memory.remove_o; eauto. des_ifs. ss. des; clarify. }\n    { i. erewrite Memory.remove_o; eauto. des_ifs.\n      { ss. des; clarify. exfalso. eapply Time.lt_strorder; eauto. }\n      { eapply MAX; eauto. }\n    }\n  }\n  { i. inv KINDS. destruct kind'; ss. clarify.\n    inv WRITE_EX. inv PROMISE.\n    hexploit lower_same_same; [apply PROMISES|]. i. subst.\n    hexploit lower_same_same; [apply MEM|]. i. subst.\n    eapply IHWRITE; auto.\n    { eapply Memory.lower_get0; eauto. }\n    { erewrite Memory.remove_o; eauto. des_ifs. ss. des; clarify. }\n    { i. erewrite Memory.remove_o; eauto. des_ifs.\n      { ss. des; clarify. exfalso. eapply Time.lt_strorder; eauto. }\n      { eapply MAX; eauto. }\n    }\n  }\nQed.\n\nLemma na_write_step_max_readable\n      mem0 lc0 loc ts val_old released ord\n      lc1 mem1 msgs kinds kind sc0 sc1 from to val_new\n      (MAX: max_readable mem0 lc0.(Local.promises) loc ts val_old released)\n      (TS: lc0.(Local.tview).(TView.cur).(View.pln) loc = ts)\n      (WRITE: Local.write_na_step lc0 sc0 mem0 loc from to val_new ord lc1 sc1 mem1\n                                  msgs kinds kind)\n      (LOWER: mem1 = mem0)\n      (WF: Local.wf lc0 mem0)\n  :\n    max_readable mem1 lc1.(Local.promises) loc (lc1.(Local.tview).(TView.cur).(View.pln) loc) val_new None.\nProof.\n  inv WRITE. ss.\n  exploit na_write_max_readable.\n  { eauto. }\n  { eapply ts_le_memory_write_na.\n    { eauto. }\n    { eapply WF. }\n  }\n  { auto. }\n  i.\n  match goal with\n  | |- _ ?vw _ _ => replace vw with to\n  end; auto.\n  unfold TimeMap.join.\n  replace ((TimeMap.singleton loc to) loc) with to.\n  2:{ unfold TimeMap.singleton. setoid_rewrite LocFun.add_spec. des_ifs. }\n  symmetry. eapply TimeFacts.le_join_r.\n  etrans.\n  2:{ left. eapply write_na_ts_lt; eauto. }\n  eapply WF.\nQed.\n\nLemma write_promise_reserve_same\n      prom0 mem0 loc from to msg prom1 mem1 kind\n      loc0 to0 from0\n      (WRITE: Memory.write prom0 mem0 loc from to msg prom1 mem1 kind)\n      (RESERVE: Memory.get loc0 to0 prom0 = Some (from0, Message.reserve))\n      (MSG: msg <> Message.reserve)\n  :\n  Memory.get loc0 to0 prom1 = Some (from0, Message.reserve).\nProof.\n  inv WRITE. erewrite Memory.remove_o; eauto. inv PROMISE.\n  { erewrite Memory.add_o; eauto. des_ifs. ss. des; clarify.\n    eapply Memory.add_get0 in PROMISES. des; clarify. }\n  { erewrite Memory.split_o; eauto. des_ifs.\n    { ss. des; clarify. eapply Memory.split_get0 in PROMISES. des; clarify. }\n    { ss. des; clarify. eapply Memory.split_get0 in PROMISES. des; clarify. }\n  }\n  { erewrite Memory.lower_o; eauto. des_ifs. ss. des; clarify.\n    eapply Memory.lower_get0 in PROMISES. des; clarify. inv MSG_LE; ss. }\n  { ss. }\nQed.\n\nLemma write_na_promise_reserve_same\n      ts prom0 mem0 loc from to val prom1 mem1 msgs kinds kind\n      loc0 to0 from0\n      (WRITE: Memory.write_na ts prom0 mem0 loc from to val prom1 mem1 msgs kinds kind)\n      (RESERVE: Memory.get loc0 to0 prom0 = Some (from0, Message.reserve))\n  :\n  Memory.get loc0 to0 prom1 = Some (from0, Message.reserve).\nProof.\n  revert loc0 to0 from0 RESERVE. induction WRITE.\n  { i. eapply write_promise_reserve_same; eauto. ss. }\n  { i. eapply IHWRITE. eapply write_promise_reserve_same; eauto.\n    unguard. des; clarify.\n  }\nQed.\n\nLemma sim_thread_tgt_write_na_aux\n      f vers flag_src flag_tgt vs_src vs_tgt\n      mem_src mem_tgt0 lc_src lc_tgt0 sc_src sc_tgt0\n      loc from to val_old val_new lc_tgt1 sc_tgt1 mem_tgt1 ord msgs kinds kind\n      (WRITE: Local.write_na_step lc_tgt0 sc_tgt0 mem_tgt0 loc from to val_new ord lc_tgt1 sc_tgt1 mem_tgt1 msgs kinds kind)\n      (LOWER: mem_tgt1 = mem_tgt0)\n      (SIM: sim_thread\n              f vers flag_src flag_tgt vs_src vs_tgt\n              mem_src mem_tgt0 lc_src lc_tgt0 sc_src sc_tgt0)\n      (VAL: vs_tgt loc = Some val_old)\n      (FLAG: flag_tgt loc = true)\n      (CONSISTENT: Local.promise_consistent lc_tgt1)\n      (LOCAL: Local.wf lc_tgt0 mem_tgt0)\n      (MEM: Memory.closed mem_tgt0)\n      (WF: Mapping.wfs f)\n  :\n    (<<SIM: sim_thread\n              f vers flag_src flag_tgt vs_src (fun loc0 => if Loc.eq_dec loc0 loc then Some val_new else vs_tgt loc0)\n              mem_src mem_tgt1 lc_src lc_tgt1 sc_src sc_tgt1>>) /\\\n    (<<ORD: ord = Ordering.na>>) /\\\n    (<<SC: sc_tgt1 = sc_tgt0>>)\n.\nProof.\n  subst. hexploit write_na_step_lower_memory_lower; eauto. i. des.\n  assert ((<<MLE: Memory.le lc_tgt1.(Local.promises) lc_tgt0.(Local.promises)>>) /\\\n          (<<OTHERS: forall loc0 (NEQ: loc0 <> loc) to,\n              Memory.get loc0 to lc_tgt1.(Local.promises)\n              =\n              Memory.get loc0 to lc_tgt0.(Local.promises)>>)).\n  { inv WRITE. ss.\n    revert KINDS KIND. clear CONSISTENT. induction WRITE0; i.\n    { splits.\n      { eapply lower_write_memory_le; eauto. destruct kind; ss. }\n      { i. inv WRITE. destruct kind; ss. inv PROMISE.\n        erewrite (@Memory.remove_o promises2); eauto.\n        erewrite (@Memory.lower_o promises0); eauto.\n        des_ifs. des; clarify.\n      }\n    }\n    { inv KINDS. splits.\n      { transitivity promises'.\n        { eapply IHWRITE0; eauto. }\n        { eapply lower_write_memory_le; eauto. destruct kind'; ss. }\n      }\n      { i. inv WRITE_EX. destruct kind'; ss. inv PROMISE.\n        transitivity (Memory.get loc0 to0 promises').\n        { eapply IHWRITE0; eauto. }\n        { erewrite (@Memory.remove_o promises'); eauto.\n          erewrite (@Memory.lower_o promises0); eauto.\n          des_ifs. des; clarify.\n        }\n      }\n    }\n  }\n  hexploit sim_local_consistent_ex.\n  { eapply PromiseConsistent.write_na_step_promise_consistent; eauto. }\n  { inv SIM. eauto. }\n  { auto. }\n  intros CONSSRC. des. splits.\n  2:{ inv WRITE. destruct ord; ss. }\n  2:{ inv WRITE. auto. }\n  inv SIM. econs; auto.\n  { inv WRITE. auto. }\n  { eauto. }\n  { inv WRITE. inv LOCAL0. econs; ss; auto.\n    { eapply sim_tview_tgt_mon; eauto.\n      eapply TViewFacts.write_tview_incr. eapply LOCAL.\n    }\n    { econs.\n      { i. eapply MLE in GET. hexploit sim_promises_get; eauto.\n        i. des. esplits; eauto.\n      }\n      { i. destruct (Loc.eq_dec loc0 loc).\n        { subst. destruct (classic (msg_src = Message.reserve)).\n          { subst. hexploit sim_promises_get_if; eauto. i. des; ss.\n            left. inv MSG. esplits; eauto.\n            eapply write_na_promise_reserve_same; eauto.\n          }\n          { right. esplits; eauto.\n            { rewrite SRCTM. eapply CONSSRC; eauto. }\n            { i. subst. eapply sim_promises_nonsynch_loc in GET; eauto; ss.\n              rewrite FLAG. ss.\n            }\n          }\n        }\n        { hexploit sim_promises_get_if; eauto. i. des.\n          { left. esplits; eauto. rewrite OTHERS; eauto. }\n          { right. esplits; eauto. }\n        }\n      }\n      { i. eapply sim_promises_none; eauto. }\n    }\n    { inv RELVERS. econs. i. eapply MLE in GET. eauto. }\n  }\n  { ii. des_ifs.\n    { specialize (MAXTGT loc). inv MAXTGT.\n      hexploit MAX; eauto. i. des.\n      hexploit na_write_step_max_readable.\n      { instantiate (5:=Local.mk _ _). eapply MAX0. }\n      all: ss; eauto.\n      i. destruct lc_tgt1. ss. econs. i. clarify.\n      esplits; eauto.\n    }\n    { inv WRITE. ss. specialize (MAXTGT loc0). inv MAXTGT. econs; eauto.\n      i. ss. hexploit MAX; eauto. i. des. esplits; eauto.\n      match goal with\n      | |- _ ?vw _ _ => replace vw with (tvw.(TView.cur).(View.pln) loc0)\n      end.\n      { inv MAX0. econs; eauto.\n        { rewrite OTHERS; eauto. }\n        { i. rewrite OTHERS; eauto. }\n      }\n      { symmetry. eapply TimeFacts.le_join_l. unfold TimeMap.singleton.\n        setoid_rewrite LocFun.add_spec_neq; auto. eapply Time.bot_spec.\n      }\n    }\n  }\n  { i. des_ifs. specialize (PERM loc).\n    rewrite VAL in PERM. unfold option_rel in *. des_ifs.\n  }\n  { eapply reserved_space_empty_reserve_decr; eauto. }\nQed.\n\nLemma sim_thread_tgt_write_na\n      f vers flag_src flag_tgt vs_src vs_tgt\n      mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src sc_tgt0\n      loc from to val_old val_new lc_tgt1 sc_tgt1 mem_tgt1 ord msgs kinds kind\n      (WRITE: Local.write_na_step lc_tgt0 sc_tgt0 mem_tgt0 loc from to val_new ord lc_tgt1 sc_tgt1 mem_tgt1 msgs kinds kind)\n      (LOWER: mem_tgt1 = mem_tgt0)\n      (SIM: sim_thread\n              f vers flag_src flag_tgt vs_src vs_tgt\n              mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src sc_tgt0)\n      (VAL: vs_tgt loc = Some val_old)\n      (CONSISTENT: Local.promise_consistent lc_tgt1)\n      (LOCALSRC: Local.wf lc_src0 mem_src0)\n      (LOCALTGT: Local.wf lc_tgt0 mem_tgt0)\n      (MEMSRC: Memory.closed mem_src0)\n      (MEMTGT: Memory.closed mem_tgt0)\n      (SCSRC: Memory.closed_timemap sc_src mem_src0)\n      (WF: Mapping.wfs f)\n      lang st\n  :\n    exists mem_src1 lc_src1,\n      (<<STEPS: rtc (@Thread.tau_step _)\n                    (Thread.mk lang st lc_src0 sc_src mem_src0)\n                    (Thread.mk _ st lc_src1 sc_src mem_src1)>>) /\\\n      (<<SIM: sim_thread\n                f vers flag_src\n                (fun loc0 => if Loc.eq_dec loc0 loc then true else flag_tgt loc0)\n                vs_src\n                (fun loc0 => if Loc.eq_dec loc0 loc then Some val_new else vs_tgt loc0)\n                mem_src1 mem_tgt1 lc_src1 lc_tgt1 sc_src sc_tgt1>>) /\\\n      (<<ORD: ord = Ordering.na>>) /\\\n      (<<SC: sc_tgt1 = sc_tgt0>>) /\\\n      (<<SPACE: space_future_memory (unchangable mem_tgt0 lc_tgt0.(Local.promises)) f mem_src0 f mem_src1>>)\n.\nProof.\n  hexploit sim_thread_tgt_flag_up; eauto.\n  { eapply PromiseConsistent.write_na_step_promise_consistent; eauto. }\n  i. des.\n  hexploit sim_thread_tgt_write_na_aux; eauto.\n  { ss. des_ifs. }\n  i. des. esplits; eauto.\nQed.\n\nLemma reserve_future_steps prom0 mem0 prom1 mem1\n      (FUTURE: reserve_future_memory prom0 mem0 prom1 mem1)\n      tvw sc lang st\n  :\n    rtc (@Thread.tau_step _)\n        (Thread.mk lang st (Local.mk tvw prom0) sc mem0)\n        (Thread.mk _ st (Local.mk tvw prom1) sc mem1).\nProof.\n  induction FUTURE.\n  { refl. }\n  econs; [|eauto]. econs.\n  { econs. econs 1. econs; eauto. }\n  { ss. }\nQed.\n\nLemma cap_max_readable mem cap prom loc ts val released\n      (CAP: Memory.cap mem cap)\n      (MLE: Memory.le prom mem)\n      (MEM: Memory.closed mem)\n  :\n    max_readable mem prom loc ts val released\n    <->\n    max_readable cap prom loc ts val released.\nProof.\n  split.\n  { i. inv H. econs; eauto.\n    { eapply Memory.cap_le; [..|eauto]; eauto. refl. }\n    { i. eapply Memory.cap_inv in GET0; eauto. des; clarify.\n      eapply MAX in GET0; eauto.\n    }\n  }\n  { i. inv H. eapply Memory.cap_inv in GET; eauto. des; clarify.\n    econs; eauto. i. eapply MAX; eauto.\n    eapply Memory.cap_le; [..|eauto]; eauto. refl.\n  }\nQed.\n\nLemma cap_max_values_src vs mem cap lc\n      (MAX: max_values_src vs mem lc)\n      (CAP: Memory.cap mem cap)\n      (LOCAL: Local.wf lc mem)\n      (MEM: Memory.closed mem)\n  :\n    max_values_src vs cap lc.\nProof.\n  ii. specialize (MAX loc). inv MAX. econs.\n  { i. hexploit MAX0; eauto. i. des. esplits; eauto.\n    erewrite <- cap_max_readable; eauto. eapply LOCAL.\n  }\n  { i. hexploit NONMAX; eauto. ii. eapply H.\n    erewrite cap_max_readable; eauto. eapply LOCAL.\n  }\nQed.\n\nLemma cap_max_values_tgt vs mem cap lc\n      (MAX: max_values_tgt vs mem lc)\n      (CAP: Memory.cap mem cap)\n      (LOCAL: Local.wf lc mem)\n      (MEM: Memory.closed mem)\n  :\n    max_values_tgt vs cap lc.\nProof.\n  ii. specialize (MAX loc). inv MAX. econs.\n  i. hexploit MAX0; eauto. i. des. esplits; eauto.\n  erewrite <- cap_max_readable; eauto. eapply LOCAL.\nQed.\n\nLemma sim_promises_preserve\n      srctm prom_src prom_tgt flag_src flag_tgt f0 f1 vers mem\n      (SIM: sim_promises srctm flag_src flag_tgt f0 vers prom_src prom_tgt)\n      (MAPLE: Mapping.les f0 f1)\n      (PRESERVE: forall loc to from msg\n                        (GET: Memory.get loc to mem = Some (from, msg))\n                        ts fts\n                        (TS: Time.le ts to)\n                        (MAP: sim_timestamp_exact (f0 loc) (f0 loc).(Mapping.ver) fts ts),\n          sim_timestamp_exact (f1 loc) (f1 loc).(Mapping.ver) fts ts)\n      (MLE: Memory.le prom_tgt mem)\n      (WF: Mapping.wfs f0)\n      (VERS: versions_wf f0 vers)\n  :\n    sim_promises srctm flag_src flag_tgt f1 vers prom_src prom_tgt.\nProof.\n  econs.\n  { i. hexploit sim_promises_get; eauto. i. des. esplits.\n    { eapply PRESERVE; eauto. eapply memory_get_ts_le; eauto. }\n    { eapply PRESERVE; eauto. refl. }\n    { auto. }\n    { i. hexploit GET0; eauto. i. des. esplits; eauto.\n      erewrite <- sim_message_max_mon_mapping; eauto.\n    }\n  }\n  { i. hexploit sim_promises_get_if; eauto. i. des.\n    { left. esplits.\n      { eapply PRESERVE; eauto. refl. }\n      { eauto. }\n    }\n    { right. esplits; eauto. }\n  }\n  { i. eapply sim_promises_none; eauto. }\nQed.\n\nLemma sim_thread_cap\n      f0 vers flag_tgt vs_src vs_tgt\n      mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt\n      cap_src cap_tgt\n      (SIM: sim_thread\n              f0 vers (fun _ => false) flag_tgt vs_src vs_tgt\n              mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt)\n      (CAPSRC: Memory.cap mem_src cap_src)\n      (CAPTGT: Memory.cap mem_tgt cap_tgt)\n      (WF: Mapping.wfs f0)\n      (VERS: versions_wf f0 vers)\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  :\n    exists f1,\n      (<<MAPLE: Mapping.les f0 f1>>) /\\\n      (<<MAPWF: Mapping.wfs f1>>) /\\\n      (<<SIM: sim_thread\n                f1 vers (fun _ => false) flag_tgt vs_src vs_tgt\n                cap_src cap_tgt lc_src lc_tgt sc_src sc_tgt>>) /\\\n      (<<VERS: versions_wf f1 vers>>)\n.\nProof.\n  inv SIM. hexploit cap_sim_memory; eauto. i. des. esplits; eauto.\n  2:{ eapply versions_wf_mapping_mon; eauto. }\n  econs; eauto.\n  { eapply sim_timemap_mon_latest; eauto. }\n  { inv LOCAL. econs; eauto.\n    { eapply sim_tview_mon_latest; eauto. }\n    { eapply sim_promises_preserve; eauto. eapply LOCALTGT. }\n  }\n  { eapply cap_max_values_src; eauto. }\n  { eapply cap_max_values_tgt; eauto. }\n  { eapply versioned_memory_cap; eauto. }\n  { i. ss. }\n  { ss. }\n  { ii. exploit FINALIZED; eauto. i. des. esplits; eauto.\n    { eapply PRESERVE; eauto. refl. }\n    { eapply Memory.cap_le; eauto. refl. }\n  }\nQed.\n\nLemma sim_readable L f vw_src vw_tgt loc to_src to_tgt released_src released_tgt ord\n      (READABLE: TView.readable vw_tgt loc to_tgt released_tgt ord)\n      (SIM: sim_view L f (Mapping.vers f) vw_src vw_tgt)\n      (TO: sim_timestamp_exact (f loc) (f loc).(Mapping.ver) to_src to_tgt)\n      (WF: Mapping.wfs f)\n      (LOC: L loc)\n  :\n    TView.readable vw_src loc to_src released_src ord.\nProof.\n  inv READABLE. econs.\n  { eapply sim_timestamp_le.\n    { eapply SIM. auto. }\n    { eauto. }\n    { eauto. }\n    { eauto. }\n    { eapply mapping_latest_wf_loc. }\n  }\n  { i. eapply sim_timestamp_le.\n    { eapply SIM. auto. }\n    { eauto. }\n    { eauto. }\n    { eauto. }\n    { eapply mapping_latest_wf_loc. }\n  }\nQed.\n\nLemma sim_writable L f vw_src vw_tgt loc to_src to_tgt sc_src sc_tgt ord\n      (WRITABLE: TView.writable vw_tgt sc_tgt loc to_tgt ord)\n      (SIM: sim_view L f (Mapping.vers f) vw_src vw_tgt)\n      (TO: sim_timestamp_exact (f loc) (f loc).(Mapping.ver) to_src to_tgt)\n      (WF: Mapping.wfs f)\n      (LOC: L loc)\n  :\n    TView.writable vw_src sc_src loc to_src ord.\nProof.\n  inv WRITABLE. econs.\n  eapply sim_timestamp_lt.\n  { eapply SIM. auto. }\n  { eauto. }\n  { eauto. }\n  { eauto. }\n  { eapply mapping_latest_wf_loc. }\nQed.\n\nLemma semi_sim_timemap_join loc f v to_src to_tgt tm_src tm_tgt\n      (SIM: sim_timemap (fun loc0 => loc0 <> loc) f v tm_src tm_tgt)\n      (TS: sim_timestamp (f loc) (v loc) to_src to_tgt)\n      (LESRC: time_le_timemap loc to_src tm_src)\n      (LETGT: time_le_timemap loc to_tgt tm_tgt)\n      (WF: Mapping.wfs f)\n      (VER: version_wf f v)\n  :\n    sim_timemap (fun _ => True) f v (TimeMap.join (TimeMap.singleton loc to_src) tm_src) (TimeMap.join (TimeMap.singleton loc to_tgt) tm_tgt).\nProof.\n  ii. destruct (Loc.eq_dec l loc).\n  { subst. unfold TimeMap.join.\n    repeat rewrite TimeFacts.le_join_l.\n    { eapply sim_timemap_singleton; ss. }\n    { unfold TimeMap.singleton. setoid_rewrite LocFun.add_spec_eq.\n      eapply LETGT. }\n    { unfold TimeMap.singleton. setoid_rewrite LocFun.add_spec_eq.\n      eapply LESRC. }\n  }\n  { eapply sim_timestamp_join; eauto.\n    unfold TimeMap.singleton. setoid_rewrite LocFun.add_spec_neq; eauto.\n    eapply sim_timestamp_bot; eauto.\n  }\nQed.\n\nLemma semi_sim_view_join loc f v to_src to_tgt vw_src vw_tgt\n      (SIM: sim_view (fun loc0 => loc0 <> loc) f v vw_src vw_tgt)\n      (TS: sim_timestamp (f loc) (v loc) to_src to_tgt)\n      (LESRC: time_le_view loc to_src vw_src)\n      (LETGT: time_le_view loc to_tgt vw_tgt)\n      (WF: Mapping.wfs f)\n      (VER: version_wf f v)\n  :\n    sim_view (fun _ => True) f v (View.join (View.singleton_ur loc to_src) vw_src) (View.join (View.singleton_ur loc to_tgt) vw_tgt).\nProof.\n  econs.\n  { eapply semi_sim_timemap_join; eauto.\n    { eapply SIM. }\n    { eapply LESRC. }\n    { eapply LETGT. }\n  }\n  { eapply semi_sim_timemap_join; eauto.\n    { eapply SIM. }\n    { eapply LESRC. }\n    { eapply LETGT. }\n  }\nQed.\n\nLemma semi_sim_opt_view_join loc f v to_src to_tgt released_src released_tgt\n      (SIM: sim_opt_view (fun loc0 => loc0 <> loc) f (Some v) released_src released_tgt)\n      (TS: sim_timestamp (f loc) (v loc) to_src to_tgt)\n      (LESRC: time_le_opt_view loc to_src released_src)\n      (LETGT: time_le_opt_view loc to_tgt released_tgt)\n      (WF: Mapping.wfs f)\n      (VER: version_wf f v)\n  :\n    sim_view (fun _ => True) f v (View.join (View.singleton_ur loc to_src) (View.unwrap released_src)) (View.join (View.singleton_ur loc to_tgt) (View.unwrap released_tgt)).\nProof.\n  inv SIM; ss.\n  { inv LESRC. inv LETGT. eapply semi_sim_view_join; eauto. }\n  { eapply sim_view_join; eauto.\n    { eapply sim_view_singleton_ur; eauto. }\n    { eapply sim_view_bot; eauto. }\n  }\nQed.\n\nLemma sim_opt_view_mon_opt_ver L f v0 v1 vw_src vw_tgt\n      (SIM: sim_opt_view L f v0 vw_src vw_tgt)\n      (VER: forall v0' (VER: v0 = Some v0'),\n          exists v1', (<<VER: v1 = Some v1'>>) /\\(<<VERLE: version_le v0' v1'>>))\n      (WF: Mapping.wfs f)\n      (VERWF: opt_version_wf f v1)\n  :\n    sim_opt_view L f v1 vw_src vw_tgt.\nProof.\n  destruct v0.\n  { hexploit VER; eauto. i. des. clarify.\n    eapply sim_opt_view_mon_ver; eauto.\n  }\n  { inv SIM. econs. }\nQed.\n\nLemma sim_read_tview f flag_src rel_vers tvw_src tvw_tgt v\n      loc to_src released_src ord to_tgt released_tgt\n      (SIM: sim_tview f flag_src rel_vers tvw_src tvw_tgt)\n      (TO: sim_timestamp_exact (f loc) (f loc).(Mapping.ver) to_src to_tgt)\n      (CLOSED: Mapping.closed (f loc) (Mapping.vers f loc) to_src)\n      (RELEASED: sim_opt_view (fun loc0 => loc0 <> loc) f v released_src released_tgt)\n      (WF: Mapping.wfs f)\n      (VERWF: opt_version_wf f v)\n      (LESRC: time_le_opt_view loc to_src released_src)\n      (LETGT: time_le_opt_view loc to_tgt released_tgt)\n  :\n    sim_tview f flag_src rel_vers (TView.read_tview tvw_src loc to_src released_src ord) (TView.read_tview tvw_tgt loc to_tgt released_tgt ord).\nProof.\n  pose proof (mapping_latest_wf f).\n  assert (TM: sim_timestamp (f loc) (Mapping.vers f loc) to_src to_tgt).\n  { eapply sim_timestamp_exact_sim; eauto. }\n  assert (JOIN: sim_view (fun loc0 => flag_src loc0 = false) f (Mapping.vers f)\n                         (View.join (View.singleton_ur loc to_src) (View.unwrap released_src))\n                         (View.join (View.singleton_ur loc to_tgt) (View.unwrap released_tgt))).\n  { eapply sim_view_mon_locs.\n    { eapply semi_sim_opt_view_join; eauto.\n      eapply sim_opt_view_mon_opt_ver; eauto.\n      i. clarify. splits; eauto.\n    }\n    { ss. }\n  }\n  econs.\n  { eapply SIM. }\n  { ss. rewrite View.join_assoc. rewrite View.join_assoc.\n    eapply sim_view_join; eauto.\n    { eapply SIM. }\n    unfold View.singleton_ur_if. des_ifs.\n    { eapply sim_view_join; eauto.\n      { eapply sim_view_singleton_ur; eauto. }\n      { eapply sim_view_bot; eauto. }\n    }\n    { destruct ord; ss. }\n    { eapply sim_view_join; eauto.\n      { eapply sim_view_singleton_rw; eauto. }\n      { eapply sim_view_bot; eauto. }\n    }\n  }\n  { ss. rewrite View.join_assoc. rewrite View.join_assoc.\n    eapply sim_view_join; eauto.\n    { eapply SIM. }\n    unfold View.singleton_ur_if. des_ifs.\n    { eapply sim_view_join; eauto.\n      { eapply sim_view_singleton_rw; eauto. }\n      { eapply sim_view_bot; eauto. }\n    }\n  }\n  { i. eapply SIM. }\nQed.\n\nLemma sim_write_tview_normal f flag_src rel_vers tvw_src tvw_tgt sc_src sc_tgt\n      loc to_src ord to_tgt\n      (SIM: sim_tview f flag_src rel_vers tvw_src tvw_tgt)\n      (TO: sim_timestamp_exact (f loc) (f loc).(Mapping.ver) to_src to_tgt)\n      (ORD: ~ Ordering.le Ordering.acqrel ord)\n      (CLOSED: Mapping.closed (f loc) (Mapping.vers f loc) to_src)\n      (WF: Mapping.wfs f)\n  :\n    sim_tview f flag_src rel_vers (TView.write_tview tvw_src sc_src loc to_src ord) (TView.write_tview tvw_tgt sc_tgt loc to_tgt ord).\nProof.\n  pose proof (mapping_latest_wf f).\n  assert (TM: sim_timestamp (f loc) (Mapping.vers f loc) to_src to_tgt).\n  { eapply sim_timestamp_exact_sim; eauto. }\n  assert (JOIN: sim_view (fun loc0 => flag_src loc0 = false) f (Mapping.vers f)\n                         (View.singleton_ur loc to_src)\n                         (View.singleton_ur loc to_tgt)).\n  { apply sim_view_singleton_ur; eauto. }\n  econs; ss.\n  { ii. setoid_rewrite LocFun.add_spec. des_ifs.\n    { eapply sim_view_join; eauto.\n      { eapply SIM. }\n      { apply sim_view_singleton_ur; eauto; ss. eapply SIM. }\n      { eapply SIM. }\n    }\n    { eapply SIM. }\n  }\n  { eapply sim_view_join; eauto. eapply SIM. }\n  { eapply sim_view_join; eauto. eapply SIM. }\n  { eapply SIM. }\nQed.\n\nLemma sim_write_tview_release f flag_src rel_vers tvw_src tvw_tgt sc_src sc_tgt\n      loc to_src ord to_tgt\n      (SIM: sim_tview f flag_src rel_vers tvw_src tvw_tgt)\n      (TO: sim_timestamp (f loc) (f loc).(Mapping.ver) to_src to_tgt)\n      (FLAG: forall loc, flag_src loc = false)\n      (WF: Mapping.wfs f)\n  :\n    sim_tview f flag_src (fun loc0 => if Loc.eq_dec loc0 loc then (Mapping.vers f) else rel_vers loc0) (TView.write_tview tvw_src sc_src loc to_src ord) (TView.write_tview tvw_tgt sc_tgt loc to_tgt ord).\nProof.\n  pose proof (mapping_latest_wf f).\n  assert (JOIN: forall L, sim_view L f (Mapping.vers f)\n                                   (View.singleton_ur loc to_src)\n                                   (View.singleton_ur loc to_tgt)).\n  { i. apply sim_view_singleton_ur; eauto. }\n  econs; ss.\n  { ii. setoid_rewrite LocFun.add_spec. des_ifs.\n    { eapply sim_view_join; eauto.\n      { eapply sim_view_mon_locs.\n        { eapply SIM. }\n        { i. ss. }\n      }\n    }\n    { eapply sim_view_join; eauto.\n      { eapply sim_view_mon_ver; auto.\n        { eapply SIM. }\n        { eapply version_le_version_wf. eapply SIM. }\n      }\n    }\n    { eapply SIM. }\n  }\n  { eapply sim_view_join; eauto. eapply SIM. }\n  { eapply sim_view_join; eauto. eapply SIM. }\n  { i. des_ifs. eapply SIM. }\nQed.\n\nLemma sim_read_fence_tview f flag_src rel_vers tvw_src tvw_tgt\n      ord\n      (SIM: sim_tview f flag_src rel_vers tvw_src tvw_tgt)\n      (WF: Mapping.wfs f)\n  :\n    sim_tview f flag_src rel_vers (TView.read_fence_tview tvw_src ord) (TView.read_fence_tview tvw_tgt ord).\nProof.\n  pose proof (mapping_latest_wf f).\n  econs; ss.\n  { eapply SIM. }\n  { des_ifs.\n    { eapply SIM. }\n    { eapply SIM. }\n  }\n  { eapply SIM. }\n  { eapply SIM. }\nQed.\n\nLemma sim_write_fence_tview_normal f flag_src rel_vers tvw_src tvw_tgt sc_src sc_tgt\n      ord\n      (SIM: sim_tview f flag_src rel_vers tvw_src tvw_tgt)\n      (ORD: ~ Ordering.le Ordering.acqrel ord)\n      (WF: Mapping.wfs f)\n  :\n    sim_tview f flag_src rel_vers (TView.write_fence_tview tvw_src sc_src ord) (TView.write_fence_tview tvw_tgt sc_tgt ord).\nProof.\n  pose proof (mapping_latest_wf f).\n  econs; ss.\n  { des_ifs. eapply SIM. }\n  { des_ifs.\n    { destruct ord; ss. }\n    { eapply SIM. }\n  }\n  { des_ifs.\n    { destruct ord; ss. }\n    { rewrite ! View.join_bot_r. eapply SIM. }\n  }\n  { eapply SIM. }\nQed.\n\nLemma sim_write_fence_tview_release f flag_src rel_vers tvw_src tvw_tgt sc_src sc_tgt\n      ord\n      (SIM: sim_tview f flag_src rel_vers tvw_src tvw_tgt)\n      (SC: sim_timemap (fun _ => True) f (Mapping.vers f) sc_src sc_tgt)\n      (FLAG: forall loc, flag_src loc = false)\n      (WF: Mapping.wfs f)\n  :\n    sim_tview f flag_src (fun _ => Mapping.vers f) (TView.write_fence_tview tvw_src sc_src ord) (TView.write_fence_tview tvw_tgt sc_tgt ord).\nProof.\n  pose proof (mapping_latest_wf f).\n  assert (JOIN: forall L, sim_timemap L f (Mapping.vers f)\n                                      (TView.write_fence_sc tvw_src sc_src ord)\n                                      (TView.write_fence_sc tvw_tgt sc_tgt ord)).\n  { i. unfold TView.write_fence_sc. des_ifs.\n    { eapply sim_timemap_join; eauto.\n      { eapply sim_timemap_mon_locs; eauto. ss. }\n      { eapply sim_timemap_mon_locs.\n        { eapply SIM. }\n        { ss. }\n      }\n    }\n    { eapply sim_timemap_mon_locs; eauto. ss. }\n  }\n  econs; ss.\n  { des_ifs.\n    { i. eapply sim_view_mon_locs.\n      { eapply SIM. }\n      { ss. }\n    }\n    { i. eapply sim_view_mon_locs.\n      { eapply sim_view_mon_ver; auto.\n        { eapply SIM. }\n        { eapply version_le_version_wf. eapply SIM. }\n      }\n      { ss. }\n    }\n  }\n  { des_ifs. eapply SIM. }\n  { eapply sim_view_join; auto.\n    { eapply SIM. }\n    { des_ifs. eapply sim_view_bot; auto. }\n  }\nQed.\n\nLemma sim_write_fence_sc f flag_src rel_vers tvw_src tvw_tgt sc_src sc_tgt\n      ord\n      (SIM: sim_tview f flag_src rel_vers tvw_src tvw_tgt)\n      (SC: sim_timemap (fun loc => flag_src loc = false) f (Mapping.vers f) sc_src sc_tgt)\n      (WF: Mapping.wfs f)\n  :\n    sim_timemap (fun loc => flag_src loc = false) f (Mapping.vers f) (TView.write_fence_sc tvw_src sc_src ord) (TView.write_fence_sc tvw_tgt sc_tgt ord).\nProof.\n  pose proof (mapping_latest_wf f).\n  unfold TView.write_fence_sc. des_ifs. eapply sim_timemap_join; auto.\n  eapply SIM.\nQed.\n\nLemma sim_write_released_normal f flag_src rel_vers tvw_src tvw_tgt sc_src sc_tgt\n      loc to_src ord to_tgt released_src released_tgt v\n      (SIM: sim_tview f flag_src rel_vers tvw_src tvw_tgt)\n      (RELEASED: sim_opt_view (fun loc0 => loc0 <> loc) f v released_src released_tgt)\n      (ORD: ~ Ordering.le Ordering.acqrel ord)\n      (VER: Ordering.le Ordering.relaxed ord -> opt_version_le (Some (rel_vers loc)) v)\n      (WF: Mapping.wfs f)\n      (VERWF: opt_version_wf f v)\n  :\n    sim_opt_view (fun loc0 => loc0 <> loc) f v\n                 (TView.write_released tvw_src sc_src loc to_src released_src ord)\n                 (TView.write_released tvw_tgt sc_tgt loc to_tgt released_tgt ord).\nProof.\n  pose proof (mapping_latest_wf f).\n  unfold TView.write_released. des_ifs.\n  { destruct v; ss. econs.\n    eapply sim_view_join; auto.\n    { eapply sim_opt_view_unwrap; eauto. i. clarify. }\n    { ss. setoid_rewrite LocFun.add_spec_eq. des_ifs.\n      eapply sim_view_join; auto.\n      { eapply sim_view_mon_ver; eauto. eapply SIM. }\n      { eapply sim_view_singleton_ur; auto; ss. }\n    }\n  }\n  { econs. }\nQed.\n\nLemma sim_write_released_release f flag_src rel_vers tvw_src tvw_tgt sc_src sc_tgt\n      loc to_src ord to_tgt released_src released_tgt v\n      (SIM: sim_tview f flag_src rel_vers tvw_src tvw_tgt)\n      (TO: sim_timestamp_exact (f loc) (f loc).(Mapping.ver) to_src to_tgt)\n      (RELEASED: sim_opt_view (fun loc0 => loc0 <> loc) f v released_src released_tgt)\n      (VERWF: opt_version_wf f v)\n      (FLAG: forall loc, flag_src loc = false)\n      (CLOSED: Mapping.closed (f loc) (Mapping.vers f loc) to_src)\n      (WF: Mapping.wfs f)\n  :\n    sim_opt_view (fun loc0 => loc0 <> loc) f (Some (Mapping.vers f))\n                 (TView.write_released tvw_src sc_src loc to_src released_src ord)\n                 (TView.write_released tvw_tgt sc_tgt loc to_tgt released_tgt ord).\nProof.\n  pose proof (mapping_latest_wf f).\n  unfold TView.write_released. des_ifs; econs.\n  eapply sim_view_join; auto.\n  { eapply sim_opt_view_unwrap; eauto. i. clarify. }\n  { ss. setoid_rewrite LocFun.add_spec_eq. des_ifs.\n    { eapply sim_view_join; auto.\n      { eapply sim_view_mon_locs; eauto.\n        { eapply SIM. }\n        { i. ss. }\n      }\n      { eapply sim_view_singleton_ur; auto; ss. }\n    }\n    { eapply sim_view_join; auto.\n      { eapply sim_view_mon_ver; auto.\n        { eapply SIM. }\n        { eapply version_le_version_wf. eapply SIM. }\n      }\n      { eapply sim_view_singleton_ur; auto; ss. }\n    }\n  }\nQed.\n\nLemma sim_src_na_write_tview f flag_src rel_vers tvw_src tvw_tgt\n      sc loc to\n      (SIM: sim_tview f flag_src rel_vers tvw_src tvw_tgt)\n      (WF: Mapping.wfs f)\n  :\n    sim_tview f (fun loc0 => if Loc.eq_dec loc0 loc then Some to else flag_src loc0) rel_vers (TView.write_tview tvw_src sc loc to Ordering.na) tvw_tgt.\nProof.\n  pose proof (mapping_latest_wf f).\n  econs; ss.\n  { i. des_ifs. econs.\n    { ii. setoid_rewrite LocFun.add_spec; auto. des_ifs; ss.\n      { unfold TimeMap.join.\n        erewrite timemap_singleton_neq; auto.\n        erewrite TimeFacts.le_join_l; auto.\n        { eapply SIM; auto. }\n        { eapply Time.bot_spec. }\n      }\n      { eapply SIM; auto. }\n    }\n    { ii. setoid_rewrite LocFun.add_spec; auto. des_ifs; ss.\n      { unfold TimeMap.join.\n        erewrite timemap_singleton_neq; auto.\n        erewrite TimeFacts.le_join_l; auto.\n        { eapply SIM; auto. }\n        { eapply Time.bot_spec. }\n      }\n      { eapply SIM; auto. }\n    }\n  }\n  { i. econs.\n    { ii. des_ifs. ss.\n      unfold TimeMap.join.\n      erewrite timemap_singleton_neq; auto.\n      erewrite TimeFacts.le_join_l; auto.\n      { eapply SIM; auto. }\n      { eapply Time.bot_spec. }\n    }\n    { ii. des_ifs. ss.\n      unfold TimeMap.join.\n      erewrite timemap_singleton_neq; auto.\n      erewrite TimeFacts.le_join_l; auto.\n      { eapply SIM; auto. }\n      { eapply Time.bot_spec. }\n    }\n  }\n  { econs.\n    { ii. des_ifs. ss. unfold TimeMap.join.\n      erewrite timemap_singleton_neq; auto.\n      erewrite TimeFacts.le_join_l; auto.\n      { eapply SIM; auto. }\n      { eapply Time.bot_spec. }\n    }\n    { ii. des_ifs. ss. unfold TimeMap.join.\n      erewrite timemap_singleton_neq; auto.\n      erewrite TimeFacts.le_join_l; auto.\n      { eapply SIM; auto. }\n      { eapply Time.bot_spec. }\n    }\n  }\n  { eapply SIM. }\nQed.\n\nLemma cancel_future_memory_decr loc prom0 mem0 prom1 mem1\n      (FUTURE: cancel_future_memory loc prom0 mem0 prom1 mem1)\n  :\n  Memory.le mem1 mem0.\nProof.\n  induction FUTURE; auto.\n  { refl. }\n  { etrans; eauto. inv CANCEL. eapply remove_le; eauto. }\nQed.\n\nLemma space_future_memory_trans_memory\n      msgs mem0 mem1 mem2 f\n      (FUTURE0: space_future_memory msgs f mem0 f mem1)\n      (FUTURE1: space_future_memory msgs f mem1 f mem2)\n      (MAPWF0: Mapping.wfs f)\n  :\n    space_future_memory msgs f mem0 f mem2.\nProof.\n  eapply space_future_memory_trans; eauto.\n  { refl. }\n  { refl. }\n  Qed.\n\nLemma unchanged_loc_max_ts mem0 mem1 loc\n      (UNCH: unchanged_loc_memory loc mem0 mem1)\n      (INHABITED: Memory.inhabited mem0)\n  :\n    Memory.max_ts loc mem0 = Memory.max_ts loc mem1.\nProof.\n  specialize (INHABITED loc). eapply TimeFacts.antisym.\n  { eapply Memory.max_ts_spec in INHABITED. des.\n    inv UNCH. rewrite <- UNCH0 in GET.\n    eapply Memory.max_ts_spec in GET. des. auto.\n  }\n  { inv UNCH. rewrite <- UNCH0 in INHABITED.\n    eapply Memory.max_ts_spec in INHABITED. des.\n    rewrite UNCH0 in GET.\n    eapply Memory.max_ts_spec in GET. des. auto.\n  }\nQed.\n\nLemma sim_thread_src_write_na\n      f vers flag_src flag_tgt vs_src vs_tgt\n      mem_src0 mem_tgt lc_src0 lc_tgt sc_src sc_tgt\n      loc val_old val_new\n      (SIM: sim_thread\n              f vers flag_src flag_tgt vs_src vs_tgt\n              mem_src0 mem_tgt lc_src0 lc_tgt sc_src sc_tgt)\n      (VAL: vs_src loc = Some val_old)\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n      (LOCALSRC: Local.wf lc_src0 mem_src0)\n      (LOCALTGT: Local.wf lc_tgt mem_tgt)\n      (MEMSRC: Memory.closed mem_src0)\n      (MEMTGT: Memory.closed mem_tgt)\n      (SCSRC: Memory.closed_timemap sc_src mem_src0)\n      (WF: Mapping.wfs f)\n      lang st\n  :\n    exists mem_src1 mem_src2 lc_src1 lc_src2 from to msgs kinds kind,\n      (<<STEPS: rtc (@Thread.tau_step _)\n                    (Thread.mk lang st lc_src0 sc_src mem_src0)\n                    (Thread.mk _ st lc_src1 sc_src mem_src1)>>) /\\\n      (<<WRITE: Local.write_na_step lc_src1 sc_src mem_src1 loc from to val_new Ordering.na lc_src2 sc_src mem_src2 msgs kinds kind>>) /\\\n      (<<SIM: sim_thread\n                f vers\n                (fun loc0 => if Loc.eq_dec loc0 loc then true else flag_src loc0)\n                (fun loc0 => if Loc.eq_dec loc0 loc then true else flag_tgt loc0)\n                (fun loc0 => if Loc.eq_dec loc0 loc then Some val_new else vs_src loc0)\n                vs_tgt\n                mem_src2 mem_tgt lc_src2 lc_tgt sc_src sc_tgt>>) /\\\n        (<<SPACE: space_future_memory (unchangable mem_tgt lc_tgt.(Local.promises)) f mem_src0 f mem_src2>>)\n.\nProof.\n  hexploit sim_thread_tgt_flag_up; eauto.\n  instantiate (1:=loc). clear SIM. i. des.\n  inv SIM. hexploit (MAXSRC loc). i.\n  inv H. hexploit MAX; eauto. i. des.\n  hexploit top_time_exists.\n  { eauto. }\n  i. des.\n  hexploit Thread.rtc_tau_step_future; eauto. i. ss. des.\n  hexploit max_readable_na_write_step.\n  { eauto. }\n  { eauto. }\n  { eauto. }\n  { eauto. }\n  { eauto. }\n  { eapply sim_local_consistent; eauto. }\n  { instantiate (1:=top). left. eapply TS. }\n  { eapply Time.incr_spec. }\n  { eapply Time.incr_spec. }\n  i. des.\n  hexploit reserve_future_steps.\n  { eapply cancel_future_reserve_future; eauto. }\n  i. des.\n  hexploit Thread.rtc_tau_step_future; eauto. i. ss. des.\n  subst. hexploit src_cancels_sim_promises; eauto.\n  { eapply WF2. }\n  i. des.\n  hexploit Local.write_na_step_future; eauto. i. des.\n  assert (RLX: View.rlx (TView.cur tvw1) loc = Time.incr (Time.incr top)).\n  { eapply TimeFacts.antisym.\n    { rewrite <- MAXTS. inv WF1. ss.\n      inv TVIEW_CLOSED. inv CUR. exploit RLX; eauto. intros x. des.\n      eapply Memory.max_ts_spec in x. des. eauto.\n    }\n    { rewrite <- VIEW. inv WF1. ss. inv TVIEW_WF. eapply CUR. }\n  }\n  assert (OTHERRLX: forall loc0 (NEQ: loc0 <> loc),\n             View.rlx (TView.cur tvw1) loc0 = View.rlx (TView.cur tvw) loc0).\n  { i. inv WRITE. clarify. ss.\n    eapply TimeFacts.le_join_l. unfold TimeMap.singleton.\n    setoid_rewrite LocFun.add_spec_neq; auto. eapply Time.bot_spec.\n  }\n  assert (OTHERPLN: forall loc0 (NEQ: loc0 <> loc),\n             View.pln (TView.cur tvw1) loc0 = View.pln (TView.cur tvw) loc0).\n  { i. inv WRITE. clarify. ss.\n    eapply TimeFacts.le_join_l. unfold TimeMap.singleton.\n    setoid_rewrite LocFun.add_spec_neq; auto. eapply Time.bot_spec.\n  }\n  assert (FLAGTOP: flag_src loc = true -> Time.le (srctm loc) top).\n  { i. etransitivity; [|left; eapply TS].\n    inv LOCAL. hexploit FLAGSRC; eauto. i. des. subst.\n    inv WF2. ss. inv TVIEW_CLOSED. inv CUR.\n    exploit RLX0. intros x. des. rewrite SRCTM.\n    eapply Memory.max_ts_spec in x. des. eauto.\n  }\n  esplits.\n  { etrans; eauto. }\n  { eauto. }\n  { econs; auto.\n    { eapply add_src_sim_memory; eauto. i. clarify. }\n    { dup LOCAL. ss. inv LOCAL0. econs.\n      { inv WRITE. clarify. ss.\n        eapply sim_src_na_write_tview; eauto.\n      }\n      { eapply src_writtten_sim_promises.\n        { eapply src_fulfill_sim_promises; eauto. }\n        { des_ifs. }\n        { i. des_ifs. }\n      }\n      { eauto. }\n      { i. des_ifs.\n        { rewrite VIEW. rewrite RLX. auto. }\n        { hexploit FLAGSRC; eauto. i. des.\n          rewrite OTHERRLX; auto. rewrite OTHERPLN; auto.\n        }\n      }\n      { i. des_ifs. rewrite OTHERRLX; auto. }\n    }\n    { ii. specialize (MAXSRC loc0). inv MAXSRC. des_ifs.\n      { econs; ss. i. clarify. rewrite VIEW. eauto. }\n      { econs; ss.\n        { i. hexploit MAX2; eauto. i. des.\n          rewrite OTHERPLN; auto. esplits.\n          erewrite unchanged_loc_max_readable; eauto.\n          { econs. i. rewrite PROMISES. des_ifs. }\n          { symmetry. etrans.\n            { eapply cancel_future_unchanged_loc in RESERVE; eauto. des; eauto.  }\n            { etrans.\n              { eapply add_unchanged_loc; eauto. }\n              { eapply add_unchanged_loc; eauto. }\n            }\n          }\n        }\n        { i. hexploit NONMAX0; eauto. i.\n          rewrite OTHERPLN; auto.\n          erewrite unchanged_loc_max_readable; eauto.\n          { econs. i. rewrite PROMISES. des_ifs. }\n          { symmetry. etrans.\n            { eapply cancel_future_unchanged_loc in RESERVE; eauto. des; eauto.  }\n            { etrans.\n              { eapply add_unchanged_loc; eauto. }\n              { eapply add_unchanged_loc; eauto. }\n            }\n          }\n        }\n      }\n    }\n    { i. des_ifs. hexploit (PERM loc). i.\n      rewrite VAL in H0. destruct (vs_tgt loc); auto.\n    }\n    { red in FIN. des. exists (loc::dom). ii. split; i.\n      { des. des_ifs; ss; auto. right. eapply DOM. eauto. }\n      { des_ifs; eauto. eapply DOM. ss. des; ss. intuition. }\n    }\n    { eapply sim_closed_memory_future; eauto.\n      eapply Memory.future_future_weak. etrans; eauto.\n    }\n    { i. ss. des_ifs. rewrite MAXTIMES; auto.\n      eapply unchanged_loc_max_ts.\n      2:{ eapply CLOSED2. }\n      etrans.\n      { eapply cancel_future_unchanged_loc in RESERVE; eauto. des; eauto. }\n      etrans.\n      { eapply add_unchanged_loc; eauto. }\n      { eapply add_unchanged_loc; eauto. }\n    }\n    { inv LOCAL. eapply reserved_space_empty_fulfilled_memory in RESERVE; try exact PROMISES0.\n      { ss. eapply reserved_space_empty_add.\n        { eapply reserved_space_empty_add.\n          { eapply RESERVE. }\n          { eauto. }\n          { eauto. }\n        }\n        { eauto. }\n        { eapply top_time_mon; eauto. left. eapply Time.incr_spec. }\n      }\n      { eauto. }\n      { eapply WF2. }\n      { ii. subst. inv WRITE. ss. clarify.\n        eapply memory_write_na_reserve_same_rev in GET; eauto.\n        rewrite PROMISES in GET. des_ifs.\n      }\n      { i. ss. des_ifs; auto. }\n    }\n    { eapply promise_finalized_promise_decr.\n      { eapply FINALIZED. }\n      i. ss. left. rewrite PROMISES in GETSRC. des_ifs.\n      esplits; eauto.\n    }\n  }\n  { eapply space_future_memory_trans_memory; eauto.\n    eapply space_future_memory_trans_memory; [..|eauto].\n    { eapply space_future_covered_decr.\n      { i. eapply memory_le_covered; [|eauto].\n        eapply cancel_future_memory_decr; eauto.\n      }\n    }\n    eapply space_future_memory_mon_msgs.\n    { eapply add_src_sim_memory_space_future; eauto. }\n    { eapply unchangable_messages_of_memory. }\n  }\nQed.\n\nLemma sim_thread_acquire\n      f vers flag_src flag_tgt vs_src0 vs_tgt0\n      mem_src mem_tgt prom_src prom_tgt tvw_src0 tvw_tgt0 sc_src sc_tgt\n      tvw_src1 tvw_tgt1 rel_vers\n      (SIM: sim_thread\n              f vers flag_src flag_tgt vs_src0 vs_tgt0\n              mem_src mem_tgt (Local.mk tvw_src0 prom_src) (Local.mk tvw_tgt0 prom_tgt) sc_src sc_tgt)\n      (TVIEW: sim_tview f flag_src rel_vers tvw_src1 tvw_tgt1)\n      (CONSISTENT: Local.promise_consistent (Local.mk tvw_tgt1 prom_tgt))\n      (LOCALSRC0: Local.wf (Local.mk tvw_src0 prom_src) mem_src)\n      (LOCALSRC1: Local.wf (Local.mk tvw_src1 prom_src) mem_src)\n      (LOCALTGT0: Local.wf (Local.mk tvw_tgt0 prom_tgt) mem_tgt)\n      (LOCALTGT1: Local.wf (Local.mk tvw_tgt1 prom_tgt) mem_tgt)\n      (MEMSRC: Memory.closed mem_src)\n      (SCSRC: Memory.closed_timemap sc_src mem_src)\n      (WF: Mapping.wfs f)\n      (LESRC: TView.le tvw_src0 tvw_src1)\n      (LETGT: TView.le tvw_tgt0 tvw_tgt1)\n      (RELVERS: wf_release_vers vers prom_tgt rel_vers)\n      (FLAGS: forall loc\n                     (SRC: flag_src loc = false)\n                     (TGT: flag_tgt loc = true),\n          (<<PLN: tvw_src1.(TView.cur).(View.pln) loc = tvw_src0.(TView.cur).(View.pln) loc>>) /\\\n          (<<RLX: tvw_src1.(TView.cur).(View.rlx) loc = tvw_src0.(TView.cur).(View.rlx) loc>>))\n  :\n    exists vs_src1 vs_tgt1,\n      (<<SIM: sim_thread\n                f vers flag_src flag_tgt vs_src1 vs_tgt1\n                mem_src mem_tgt (Local.mk tvw_src1 prom_src) (Local.mk tvw_tgt1 prom_tgt) sc_src sc_tgt>>) /\\\n      (<<VALS: forall loc,\n          ((<<SRC: vs_src1 loc = vs_src0 loc>>) /\\ (<<TGT: vs_tgt1 loc = vs_tgt0 loc>>)) \\/\n          (exists val_src val_tgt,\n              (<<FLAGSRC: flag_src loc = false>>) /\\\n                (<<FLAGTGT: flag_tgt loc = false>>) /\\\n                (<<NONESRC: vs_src0 loc = None>>) /\\ (<<NONETGT: vs_tgt0 loc = None>>) /\\\n                (<<VALSRC: vs_src1 loc = Some val_src>>) /\\ (<<VALTGT: vs_tgt1 loc = Some val_tgt>>) /\\\n                (<<VALLE: Const.le val_tgt val_src>>) /\\\n                (<<TS: Time.lt (tvw_src0.(TView.cur).(View.pln) loc) (tvw_src1.(TView.cur).(View.pln) loc)>>) /\\\n                (<<VALSRC: __guard__(exists from released, Memory.get loc (tvw_src1.(TView.cur).(View.pln) loc) mem_src = Some (from, Message.concrete val_src released))>>) /\\\n                (<<VALTGT: __guard__(exists from released, Memory.get loc (tvw_tgt1.(TView.cur).(View.pln) loc) mem_tgt = Some (from, Message.concrete val_tgt released))>>))>>)\n.\nProof.\n  assert (VIEWEQ: forall loc\n                         (SRC: flag_src loc = true),\n             (<<PLN: tvw_src1.(TView.cur).(View.pln) loc = tvw_src0.(TView.cur).(View.pln) loc>>) /\\\n             (<<RLX: tvw_src1.(TView.cur).(View.rlx) loc = tvw_src0.(TView.cur).(View.rlx) loc>>)).\n  { inv SIM. inv LOCAL. i. hexploit FLAGSRC; eauto. i. des.\n    hexploit sim_memory_src_flag_max_concrete; eauto.\n    { rewrite SRCTM; eauto. inv LOCALSRC0. inv TVIEW_CLOSED. inv CUR.\n      exploit RLX. i. des. eauto.\n    }\n    i. subst.\n    inv LOCALSRC1. inv TVIEW_CLOSED. inv CUR. ss. splits.\n    { eapply TimeFacts.antisym.\n      { hexploit (PLN loc). i. des.\n        eapply Memory.max_ts_spec in H1. des.\n        rewrite H0 in MAX. rewrite SRCTM in MAX. auto. rewrite H in MAX. auto.\n      }\n      { eapply LESRC. }\n    }\n    { eapply TimeFacts.antisym.\n      { hexploit (RLX loc). i. des.\n        eapply Memory.max_ts_spec in H1. des.\n        rewrite H0 in MAX. rewrite SRCTM in MAX. auto.\n      }\n      { eapply LESRC. }\n    }\n  }\n  assert (SIMLOCAL: sim_local f vers tvw_src1.(TView.cur).(View.rlx) flag_src flag_tgt (Local.mk tvw_src1 prom_src) (Local.mk tvw_tgt1 prom_tgt)).\n  { inv SIM. inv LOCAL. econs; eauto.\n    { eapply sim_promises_change_no_flag; eauto. i.\n      rewrite SRCTM. destruct (flag_src loc) eqn:EQ.\n      { eapply VIEWEQ; auto. }\n      { eapply FLAGS; auto. }\n    }\n    { i. hexploit VIEWEQ; eauto. i. des.\n      rewrite PLN. rewrite RLX. eapply FLAGSRC; eauto.\n    }\n  }\n  hexploit (@max_values_src_exists mem_src (Local.mk tvw_src1 prom_src)).\n  i. des. rename vs into vs_src1.\n  assert (VALSRC: forall loc,\n             (<<SRC: vs_src1 loc = vs_src0 loc>>) \\/\n             (exists val,\n                 (<<FLAGSRC: flag_src loc = false>>) /\\\n                 (<<NONESRC: vs_src0 loc = None>>) /\\\n                 (<<VALSRC: vs_src1 loc = Some val>>) /\\\n                 (<<TS: Time.lt (tvw_src0.(TView.cur).(View.pln) loc) (tvw_src1.(TView.cur).(View.pln) loc)>>) /\\\n                 (<<VALSRC: __guard__(exists from released, Memory.get loc (tvw_src1.(TView.cur).(View.pln) loc) mem_src = Some (from, Message.concrete val released))>>))).\n  { inv SIM. i. destruct (vs_src0 loc) eqn:VAL0.\n    { left. eapply max_value_src_inj; eauto.\n      eapply max_value_src_mon.\n      { rewrite <- VAL0. eapply MAXSRC. }\n      { eauto. }\n      { eauto. }\n      { eauto. }\n      { eapply sim_local_consistent; eauto. }\n    }\n    destruct (vs_src1 loc) eqn:VAL1; auto. right.\n    esplits; eauto.\n    { eapply max_value_src_flag_none; eauto.\n      rewrite <- VAL0. auto.\n    }\n    { assert (TS: Time.le (View.pln (TView.cur tvw_src0) loc) (View.pln (TView.cur tvw_src1) loc)).\n      { eapply LESRC. }\n      inv TS; auto. exfalso.\n      specialize (MAXSRC loc). specialize (MAX loc).\n      rewrite VAL0 in MAXSRC. rewrite VAL1 in MAX.\n      inv MAX. inv MAXSRC. hexploit MAX0; eauto. i. des.\n      eapply NONMAX0; eauto. rewrite H. eauto.\n    }\n    { specialize (MAX loc). rewrite VAL1 in MAX.\n      inv MAX. hexploit MAX0; eauto. i. des. inv MAX.\n      red. esplits; eauto.\n    }\n  }\n  assert (MEM: sim_memory (View.rlx (TView.cur tvw_src1)) flag_src f vers mem_src mem_tgt).\n  { inv SIM. inv LOCAL. eapply sim_memory_change_no_flag; eauto.\n    i. rewrite SRCTM. hexploit VIEWEQ; eauto. i. des. rewrite RLX. auto.\n  }\n  hexploit (choice (fun loc v =>\n                      (<<MAXTGT: max_value_tgt loc v mem_tgt (Local.mk tvw_tgt1 prom_tgt)>>) /\\\n                      (((<<SRC: vs_src1 loc = vs_src0 loc>>) /\\ (<<TGT: v = vs_tgt0 loc>>)) \\/\n                         (exists val_src val_tgt,\n                             (<<FLAGSRC: flag_src loc = false>>) /\\\n                               (<<FLAGTGT: flag_tgt loc = false>>) /\\\n                               (<<NONESRC: vs_src0 loc = None>>) /\\ (<<NONETGT: vs_tgt0 loc = None>>) /\\\n                               (<<VALSRC: vs_src1 loc = Some val_src>>) /\\ (<<VALTGT: v = Some val_tgt>>) /\\\n                               (<<VALLE: Const.le val_tgt val_src>>) /\\\n                               (<<TS: Time.lt (tvw_src0.(TView.cur).(View.pln) loc) (tvw_src1.(TView.cur).(View.pln) loc)>>) /\\\n                               (<<VALRC: __guard__(exists from released, Memory.get loc (tvw_src1.(TView.cur).(View.pln) loc) mem_src = Some (from, Message.concrete val_src released))>>) /\\\n                               (<<VALTGT: __guard__(exists from released, Memory.get loc (tvw_tgt1.(TView.cur).(View.pln) loc) mem_tgt = Some (from, Message.concrete val_tgt released))>>))))).\n  { intros loc. hexploit (VALSRC loc). i. des.\n    { exists (vs_tgt0 loc). esplits; auto.\n      { inv SIM. eapply max_value_tgt_mon; eauto. }\n    }\n    { assert (FLAG: flag_tgt loc = false).\n      { destruct (flag_tgt loc) eqn:FLAG; auto.\n        hexploit FLAGS; eauto. i. des. rewrite PLN in TS. timetac.\n      }\n      hexploit no_flag_max_value_same; eauto.\n      { specialize (MAX loc). rewrite VALSRC0 in MAX. eauto. }\n      i. des. exists (Some v_tgt). esplits; auto.\n      right. esplits; eauto.\n      { inv SIM. specialize (PERM loc).\n        rewrite NONESRC in PERM. ss. des_ifs.\n      }\n      { inv MAX0. hexploit MAX1; eauto. i. des.\n        inv MAX0. red. esplits; eauto.\n      }\n    }\n  }\n  clear VALSRC. intros [vs_tgt1 MAXTGT].\n  exists vs_src1, vs_tgt1. splits; auto.\n  { inv SIM. econs.\n    { auto. }\n    { eapply MEM. }\n    { eauto. }\n    { eauto. }\n    { ii. hexploit (MAXTGT loc). i. des; auto. }\n    { i. hexploit (MAXTGT loc). i. des.\n      { rewrite SRC. rewrite TGT. auto. }\n      { rewrite VALSRC. rewrite VALTGT. ss. }\n    }\n    { auto. }\n    { auto. }\n    { auto. }\n    { i. rewrite <- MAXTIMES; auto. inv LOCAL. rewrite SRCTM. eapply VIEWEQ; auto. }\n    { auto. }\n    { auto. }\n  }\n  { i. hexploit (MAXTGT loc). i. des; eauto.\n    right. esplits; eauto.\n  }\nQed.\n\nLemma write_fence_tview_na tvw sc\n  :\n    TView.write_fence_tview tvw sc Ordering.na = tvw.\nProof.\n  unfold TView.write_fence_tview. des_ifs.\n  rewrite View.join_bot_r.\n  destruct tvw; ss.\nQed.\n\nLemma write_fence_sc_na tvw sc\n  :\n    TView.write_fence_sc tvw sc Ordering.na = sc.\nProof.\n  unfold TView.write_fence_sc. des_ifs.\nQed.\n\nLemma read_fence_tview_na tvw\n  :\n    TView.read_fence_tview tvw Ordering.na = tvw.\nProof.\n  unfold TView.read_fence_tview. des_ifs.\n  destruct tvw; ss.\nQed.\n\nLemma fence_step_merge\n      lc0 sc0 ordr ordw lc1 sc1 lc2 sc2\n      (STEP0: Local.fence_step lc0 sc0 ordr Ordering.na lc1 sc1)\n      (STEP1: Local.fence_step lc1 sc1 Ordering.na ordw lc2 sc2)\n  :\n    Local.fence_step lc0 sc0 ordr ordw lc2 sc2.\nProof.\n  inv STEP0. inv STEP1. ss. econs; eauto. f_equal.\n  rewrite write_fence_tview_na. rewrite write_fence_sc_na.\n  rewrite read_fence_tview_na. auto.\nQed.\n\nLemma fence_step_split\n      lc0 sc0 ordr ordw lc2 sc2\n      (STEP: Local.fence_step lc0 sc0 ordr ordw lc2 sc2)\n  :\n    exists lc1 sc1,\n      (<<STEP0: Local.fence_step lc0 sc0 ordr Ordering.na lc1 sc1>>) /\\\n      (<<STEP1: Local.fence_step lc1 sc1 Ordering.na ordw lc2 sc2>>).\nProof.\n  inv STEP. esplits.\n  { econs; ss. }\n  { econs; eauto. ss. f_equal.\n    rewrite write_fence_tview_na. rewrite write_fence_sc_na.\n    rewrite read_fence_tview_na. auto.\n  }\nQed.\n\nDefinition local_read_fence_tview (tview1: TView.t) (sc1: TimeMap.t)\n           (ordr ordw: Ordering.t): TView.t :=\n  let tview2 := TView.read_fence_tview tview1 ordr in\n  let sc2 := TView.write_fence_sc tview2 sc1 ordw in\n  let cur2 :=\n      if Ordering.le Ordering.seqcst ordw\n      then View.mk sc2 sc2\n      else TView.cur tview2 in\n  let acq2 :=\n      View.join\n        (TView.acq tview2)\n        (if Ordering.le Ordering.seqcst ordw\n         then (View.mk sc2 sc2)\n         else View.bot) in\n  TView.mk\n    (tview1.(TView.rel))\n    cur2\n    acq2.\n\nLemma local_read_fence_tview_wf tview sc ordr ordw\n      (WF: TView.wf tview)\n  :\n    TView.wf (local_read_fence_tview tview sc ordr ordw).\nProof.\n  econs; ss; des_ifs; ss; try by (eapply WF).\n  { econs; ss. refl. }\n  { econs; ss. eapply timemap_join_mon; [|refl]. eapply WF. }\n  { rewrite View.join_bot_r. apply WF. }\n  { i. unfold TView.write_fence_sc. des_ifs. econs; ss.\n    { des_ifs.\n      { etrans; [|eapply TimeMap.join_r].\n        transitivity (View.pln (TView.cur tview)); [apply WF|].\n        transitivity (View.rlx (TView.cur tview)); [apply WF|].\n        apply WF.\n      }\n      { etrans; [|eapply TimeMap.join_r].\n        transitivity (View.pln (TView.cur tview)); [apply WF|].\n        apply WF.\n      }\n    }\n    { des_ifs.\n      { etrans; [|eapply TimeMap.join_r].\n        transitivity (View.rlx (TView.cur tview)); [apply WF|].\n        apply WF.\n      }\n      { etrans; [|eapply TimeMap.join_r]. apply WF. }\n    }\n  }\n  { i. transitivity (TView.cur tview); apply WF. }\n  { eapply View.join_r. }\n  { apply View.join_l. }\n  { rewrite View.join_bot_r. apply WF. }\nQed.\n\nLemma local_read_fence_tview_closed mem tview sc ordr ordw\n      (TVIEW: TView.closed tview mem)\n      (SC: Memory.closed_timemap sc mem)\n  :\n    TView.closed (local_read_fence_tview tview sc ordr ordw) mem.\nProof.\n  unfold local_read_fence_tview, TView.write_fence_sc. econs; ss.\n  { eapply TVIEW. }\n  { des_ifs.\n    { econs; ss.\n      { eapply Memory.join_closed_timemap; eauto. eapply TVIEW. }\n      { eapply Memory.join_closed_timemap; eauto. eapply TVIEW. }\n    }\n    { econs; ss.\n      { eapply Memory.join_closed_timemap; eauto. eapply TVIEW. }\n      { eapply Memory.join_closed_timemap; eauto. eapply TVIEW. }\n    }\n    { eapply TVIEW. }\n    { eapply TVIEW. }\n  }\n  { des_ifs.\n    { eapply Memory.join_closed_view.\n      { eapply TVIEW. }\n      econs; ss.\n      { eapply Memory.join_closed_timemap; eauto. eapply TVIEW. }\n      { eapply Memory.join_closed_timemap; eauto. eapply TVIEW. }\n    }\n    { eapply Memory.join_closed_view.\n      { eapply TVIEW. }\n      econs; ss.\n      { eapply Memory.join_closed_timemap; eauto. eapply TVIEW. }\n      { eapply Memory.join_closed_timemap; eauto. eapply TVIEW. }\n    }\n    { rewrite View.join_bot_r. apply TVIEW. }\n  }\nQed.\n\nLemma local_read_fence_tview_incr tview sc ordr ordw\n      (WF: TView.wf tview)\n  :\n    TView.le tview (local_read_fence_tview tview sc ordr ordw).\nProof.\n  econs; ss.\n  { i. refl. }\n  { unfold TView.write_fence_sc. ss. des_ifs.\n    { econs; ss.\n      { etrans; [|eapply TimeMap.join_r].\n        transitivity (View.rlx (TView.cur tview)); apply WF.\n      }\n      { etrans; [|eapply TimeMap.join_r]. apply WF.\n      }\n    }\n    { econs; ss.\n      { etrans; [|eapply TimeMap.join_r]. apply WF. }\n      { eapply TimeMap.join_r. }\n    }\n    { apply WF. }\n    { refl. }\n  }\n  { eapply View.join_l. }\nQed.\n\nDefinition local_write_fence_tview (tview1: TView.t) (ord: Ordering.t): TView.t :=\n  TView.mk\n    (fun loc =>\n       if Ordering.le Ordering.acqrel ord\n       then (TView.cur tview1) else (TView.rel tview1 loc))\n    (TView.cur tview1)\n    (TView.acq tview1)\n.\n\nLemma local_write_fence_tview_wf tview ord\n      (WF: TView.wf tview)\n  :\n    TView.wf (local_write_fence_tview tview ord).\nProof.\n  econs; ss; des_ifs; ss; try by (eapply WF).\n  { i. eapply WF. }\n  { i. refl. }\nQed.\n\nLemma local_write_fence_tview_closed mem tview ord\n      (TVIEW: TView.closed tview mem)\n  :\n    TView.closed (local_write_fence_tview tview ord) mem.\nProof.\n  econs; ss.\n  { i. des_ifs.\n    { eapply TVIEW. }\n    { eapply TVIEW. }\n  }\n  { eapply TVIEW. }\n  { eapply TVIEW. }\nQed.\n\nLemma local_write_fence_tview_incr tview ord\n      (WF: TView.wf tview)\n  :\n    TView.le tview (local_write_fence_tview tview ord).\nProof.\n  econs; ss.\n  { i. des_ifs.\n    { eapply WF. }\n    { refl. }\n  }\n  { refl. }\n  { refl. }\nQed.\n\nDefinition local_write_fence_sc (tview1: TView.t) (sc: TimeMap.t) (ord: Ordering.t): TimeMap.t :=\n  if Ordering.le Ordering.seqcst ord\n  then (TimeMap.join sc (View.rlx (TView.cur tview1)))\n  else sc\n.\n\nLemma local_write_fence_sc_closed mem tview sc ord\n      (TVIEW: TView.closed tview mem)\n      (SC: Memory.closed_timemap sc mem)\n  :\n    Memory.closed_timemap (local_write_fence_sc tview sc ord) mem.\nProof.\n  unfold local_write_fence_sc. des_ifs.\n  eapply Memory.join_closed_timemap; auto. eapply TVIEW.\nQed.\n\nLemma local_write_fence_sc_incr tview sc ord\n  :\n    TimeMap.le sc (local_write_fence_sc tview sc ord).\nProof.\n  unfold local_write_fence_sc. des_ifs.\n  { eapply TimeMap.join_l. }\n  { refl. }\nQed.\n\nLemma timemap_bot_join_l tm\n  :\n    TimeMap.join TimeMap.bot tm = tm.\nProof.\n  eapply TimeMap.le_join_r. eapply TimeMap.bot_spec.\nQed.\n\nLemma timemap_bot_join_r tm\n  :\n    TimeMap.join tm TimeMap.bot = tm.\nProof.\n  eapply TimeMap.le_join_l. eapply TimeMap.bot_spec.\nQed.\n\nLemma read_tview_incr_rlx\n      tvw loc ts vw ord\n      (WF: time_le_opt_view loc ts vw)\n      (READABLE: Time.le (View.pln (TView.cur tvw) loc) ts)\n      (ORD: Ordering.le Ordering.relaxed ord)\n  :\n    View.pln (TView.cur (TView.read_tview tvw loc ts vw ord)) loc = ts.\nProof.\n  unfold TView.read_tview, View.singleton_ur_if in *. ss. des_ifs; ss.\n  { unfold TimeMap.join. rewrite timemap_singleton_eq.\n    rewrite TimeFacts.le_join_l.\n    { apply TimeFacts.le_join_r. auto. }\n    { inv WF; ss.\n      { inv EXACT. unfold time_le_timemap in *. etrans; eauto.\n        eapply Time.join_r.\n      }\n      { eapply Time.bot_spec. }\n    }\n  }\n  { rewrite ! timemap_bot_join_r.\n    unfold TimeMap.join. rewrite timemap_singleton_eq.\n    eapply TimeFacts.le_join_r. auto.\n  }\nQed.\n\nLemma read_tview_pln\n      tvw loc ts vw ord\n      (READABLE: Time.le (View.pln (TView.cur tvw) loc) ts)\n      (ORD: ~ Ordering.le Ordering.relaxed ord)\n  :\n  View.pln (TView.cur (TView.read_tview tvw loc ts vw ord)) loc = View.pln (TView.cur tvw) loc.\nProof.\n  unfold TView.read_tview, View.singleton_ur_if. ss. des_ifs; ss.\n  { destruct ord; ss. }\n  rewrite ! timemap_bot_join_r. auto.\nQed.\n\nVariant local_fence_read_step lc1 sc1 ordr ordw lc2: Prop :=\n| local_fence_read_step_intro\n    (LOCAL: lc2 = Local.mk\n                    (local_read_fence_tview lc1.(Local.tview) sc1 ordr ordw)\n                    (lc1.(Local.promises)))\n    (RELEASE: Ordering.le Ordering.strong_relaxed ordw -> Memory.nonsynch lc1.(Local.promises))\n    (PROMISES: ordw = Ordering.seqcst -> lc1.(Local.promises) = Memory.bot)\n.\n\nLemma local_fence_read_step_future mem lc1 sc1 ordr ordw lc2\n      (STEP: local_fence_read_step lc1 sc1 ordr ordw lc2)\n      (LOCAL: Local.wf lc1 mem)\n      (SC: Memory.closed_timemap sc1 mem)\n  :\n    (<<LOCAL: Local.wf lc2 mem>>) /\\\n    (<<INCR: TView.le lc1.(Local.tview) lc2.(Local.tview)>>).\nProof.\n  inv STEP. splits.\n  { inv LOCAL. econs; ss.\n    { eapply local_read_fence_tview_wf; eauto. }\n    { eapply local_read_fence_tview_closed; eauto. }\n  }\n  { eapply local_read_fence_tview_incr; eauto. eapply LOCAL. }\nQed.\n\nVariant local_fence_write_step lc1 sc1 ord lc2 sc2: Prop :=\n| local_fence_write_step_intro\n    (LOCAL: lc2 = Local.mk\n                    (local_write_fence_tview lc1.(Local.tview) ord)\n                    (lc1.(Local.promises)))\n    (SC: sc2 = local_write_fence_sc lc1.(Local.tview) sc1 ord)\n.\n\nLemma local_fence_write_step_future mem lc1 sc1 ord lc2 sc2\n      (STEP: local_fence_write_step lc1 sc1 ord lc2 sc2)\n      (LOCAL: Local.wf lc1 mem)\n      (SC: Memory.closed_timemap sc1 mem)\n  :\n    (<<LOCAL: Local.wf lc2 mem>>) /\\\n    (<<SC: Memory.closed_timemap sc2 mem>>) /\\\n    (<<INCR: TView.le lc1.(Local.tview) lc2.(Local.tview)>>).\nProof.\n  inv STEP. splits.\n  { inv LOCAL. econs; ss.\n    { eapply local_write_fence_tview_wf; eauto. }\n    { eapply local_write_fence_tview_closed; eauto. }\n  }\n  { eapply local_write_fence_sc_closed; eauto. eapply LOCAL. }\n  { eapply local_write_fence_tview_incr; eauto. eapply LOCAL. }\nQed.\n\nLemma local_fence_tview_merge\n      tvw sc ordr ordw\n      (WF: TView.wf tvw)\n  :\n    local_write_fence_tview (local_read_fence_tview tvw sc ordr ordw) ordw\n    =\n    TView.write_fence_tview (TView.read_fence_tview tvw ordr) sc ordw.\nProof.\n  ss.\nQed.\n\nLemma local_fence_sc_merge\n      tvw sc ordr ordw\n      (WF: TView.wf tvw)\n  :\n    local_write_fence_sc (local_read_fence_tview tvw sc ordr ordw) sc ordw =\n    TView.write_fence_sc (TView.read_fence_tview tvw ordr) sc ordw.\nProof.\n  assert (IDEM: forall tm, TimeMap.join tm tm = tm).\n  { i. apply TimeMap.le_join_l. refl. }\n  Local Transparent Ordering.le.\n  unfold local_write_fence_sc, local_read_fence_tview, TView.read_fence_tview, TView.write_fence_tview, TView.write_fence_sc.\n  destruct ordr eqn:ORDR, ordw eqn:ORDW; ss.\n  { rewrite <- TimeMap.join_assoc. f_equal. auto. }\n  { rewrite <- TimeMap.join_assoc. f_equal. auto. }\n  { rewrite <- TimeMap.join_assoc. f_equal. auto. }\n  { rewrite <- TimeMap.join_assoc. f_equal. auto. }\n  { rewrite <- TimeMap.join_assoc. f_equal. auto. }\n  { rewrite <- TimeMap.join_assoc. f_equal. auto. }\n  Local Opaque Ordering.le.\nQed.\n\nLemma local_fence_step_merge\n      lc0 sc0 ordr lc1 ordw lc2 sc1\n      (STEP0: local_fence_read_step lc0 sc0 ordr ordw lc1)\n      (STEP1: local_fence_write_step lc1 sc0 ordw lc2 sc1)\n      (WF: TView.wf lc0.(Local.tview))\n  :\n    Local.fence_step lc0 sc0 ordr ordw lc2 sc1.\nProof.\n  inv STEP0. inv STEP1. ss. econs; ss.\n  rewrite local_fence_sc_merge; eauto.\nQed.\n\nLemma local_fence_step_split\n      lc0 sc0 ordr ordw lc2 sc1\n      (STEP: Local.fence_step lc0 sc0 ordr ordw lc2 sc1)\n      (WF: TView.wf lc0.(Local.tview))\n  :\n    exists lc1,\n      (<<STEP0: local_fence_read_step lc0 sc0 ordr ordw lc1>>) /\\\n      (<<STEP1: local_fence_write_step lc1 sc0 ordw lc2 sc1>>).\nProof.\n  inv STEP. esplits.\n  { econs; eauto. }\n  { econs; ss. rewrite local_fence_sc_merge; auto. }\nQed.\n\nLemma sim_local_read_fence_tview f flag_src rel_vers tvw_src tvw_tgt sc_src sc_tgt\n      ordr ordw\n      (SIM: sim_tview f flag_src rel_vers tvw_src tvw_tgt)\n      (SC: sim_timemap (fun loc => flag_src loc = false) f (Mapping.vers f) sc_src sc_tgt)\n      (WF: Mapping.wfs f)\n  :\n    sim_tview f flag_src rel_vers (local_read_fence_tview tvw_src sc_src ordr ordw) (local_read_fence_tview tvw_tgt sc_tgt ordr ordw).\nProof.\n  pose proof (mapping_latest_wf f).\n  assert (READ: sim_tview f flag_src rel_vers (TView.read_fence_tview tvw_src ordr) (TView.read_fence_tview tvw_tgt ordr)).\n  { eapply sim_read_fence_tview; eauto. }\n  assert (WRITE: sim_timemap (fun loc => flag_src loc = false) f (Mapping.vers f) (TView.write_fence_sc (TView.read_fence_tview tvw_src ordr) sc_src ordw) (TView.write_fence_sc (TView.read_fence_tview tvw_tgt ordr) sc_tgt ordw)).\n  { eapply sim_write_fence_sc; eauto. }\n  econs; ss.\n  { eapply SIM. }\n  { des_ifs.\n    { eapply SIM. }\n    { eapply SIM. }\n  }\n  { eapply sim_view_join; eauto.\n    { eapply SIM. }\n    { des_ifs. eapply sim_view_bot; eauto. }\n  }\n  { eapply SIM. }\nQed.\n\nLemma sim_local_write_fence_tview_normal f flag_src rel_vers tvw_src tvw_tgt\n      ord\n      (SIM: sim_tview f flag_src rel_vers tvw_src tvw_tgt)\n      (ORD: ~ Ordering.le Ordering.acqrel ord)\n      (WF: Mapping.wfs f)\n  :\n    sim_tview f flag_src rel_vers (local_write_fence_tview tvw_src ord) (local_write_fence_tview tvw_tgt ord).\nProof.\n  pose proof (mapping_latest_wf f).\n  econs; ss.\n  { i. des_ifs. eapply SIM. }\n  { eapply SIM. }\n  { eapply SIM. }\n  { eapply SIM. }\nQed.\n\nLemma sim_local_write_fence_tview_release f flag_src rel_vers tvw_src tvw_tgt\n      ord\n      (SIM: sim_tview f flag_src rel_vers tvw_src tvw_tgt)\n      (FLAG: forall loc, flag_src loc = false)\n      (WF: Mapping.wfs f)\n  :\n    sim_tview f flag_src (fun _ => Mapping.vers f) (local_write_fence_tview tvw_src ord) (local_write_fence_tview tvw_tgt ord).\nProof.\n  pose proof (mapping_latest_wf f).\n  econs; ss.\n  { i. des_ifs.\n    { eapply sim_view_mon_locs.\n      { eapply SIM. }\n      { i. ss. }\n    }\n    { eapply sim_view_mon_ver; auto.\n      { eapply SIM. }\n      { eapply version_le_version_wf. eapply SIM. }\n    }\n  }\n  { eapply SIM. }\n  { eapply SIM. }\nQed.\n\nLemma sim_local_write_fence_sc f flag_src rel_vers tvw_src tvw_tgt sc_src sc_tgt\n      ord\n      (SIM: sim_tview f flag_src rel_vers tvw_src tvw_tgt)\n      (SC: sim_timemap (fun _ => True) f (Mapping.vers f) sc_src sc_tgt)\n      (FLAG: Ordering.le Ordering.seqcst ord -> forall loc, flag_src loc = false)\n      (WF: Mapping.wfs f)\n  :\n    sim_timemap (fun _ => True) f (Mapping.vers f) (local_write_fence_sc tvw_src sc_src ord) (local_write_fence_sc tvw_tgt sc_tgt ord).\nProof.\n  pose proof (mapping_latest_wf f).\n  unfold local_write_fence_sc. des_ifs. eapply sim_timemap_join; auto.\n  eapply sim_timemap_mon_locs.\n  { eapply SIM. }\n  { i. eapply FLAG. auto. }\nQed.\n\nLemma sim_thread_read\n      f vers flag_src flag_tgt vs_src0 vs_tgt0\n      mem_src mem_tgt lc_src0 lc_tgt0 sc_src sc_tgt\n      lc_tgt1 loc to_tgt val_tgt0 released_tgt ord\n      (SIM: sim_thread\n              f vers flag_src flag_tgt vs_src0 vs_tgt0\n              mem_src mem_tgt lc_src0 lc_tgt0 sc_src sc_tgt)\n      (READ: Local.read_step lc_tgt0 mem_tgt loc to_tgt val_tgt0 released_tgt ord lc_tgt1)\n      (CONSISTENT: Local.promise_consistent lc_tgt1)\n      (LOCALSRC: Local.wf lc_src0 mem_src)\n      (LOCALTGT: Local.wf lc_tgt0 mem_tgt)\n      (MEMSRC: Memory.closed mem_src)\n      (MEMTGT: Memory.closed mem_tgt)\n      (SCSRC: Memory.closed_timemap sc_src mem_src)\n      (SCTGT: Memory.closed_timemap sc_tgt mem_tgt)\n      (WF: Mapping.wfs f)\n      (VERS: versions_wf f vers)\n      (FLAGSRC: flag_src loc = false)\n      (FLAGTGT: flag_tgt loc = false)\n      (FLAG: forall loc\n                    (SRC: flag_src loc = false) (TGT: flag_tgt loc = true),\n          ~ Ordering.le Ordering.acqrel ord)\n  :\n    exists val_tgt1 val_src1 to_src released_src lc_src1 vs_src1 vs_tgt1,\n      (<<READ: forall val (VAL: Const.le val val_src1), Local.read_step lc_src0 mem_src loc to_src val released_src ord lc_src1>>) /\\\n      (<<TO: sim_timestamp_exact (f loc) (f loc).(Mapping.ver) to_src to_tgt>>) /\\\n      (<<RELEASED: sim_opt_view (fun loc0 => loc0 <> loc) f (vers loc to_tgt) released_src released_tgt>>) /\\\n      (<<SIM: sim_thread\n                f vers flag_src flag_tgt vs_src1 vs_tgt1\n                mem_src mem_tgt lc_src1 lc_tgt1 sc_src sc_tgt>>) /\\\n      (<<VAL: Const.le val_tgt1 val_src1>>) /\\\n      (<<VALTGT: Const.le val_tgt0 val_tgt1>>) /\\\n      (<<NUPDATESRC: forall val (VAL: vs_src0 loc = Some val), val = val_src1>>) /\\\n      (<<NUPDATETGT: forall val (VAL: vs_tgt0 loc = Some val), val = val_tgt1>>) /\\\n      (<<VALS: forall loc0,\n          ((<<SRC: vs_src1 loc0 = vs_src0 loc0>>) /\\ (<<TGT: vs_tgt1 loc0 = vs_tgt0 loc0>>)) \\/\n          (exists val_src val_tgt,\n              (<<NONESRC: vs_src0 loc0 = None>>) /\\ (<<NONETGT: vs_tgt0 loc0 = None>>) /\\\n              (<<VALSRC: vs_src1 loc0 = Some val_src>>) /\\ (<<VALTGT: vs_tgt1 loc0 = Some val_tgt>>) /\\\n              (<<VALLE: Const.le val_tgt val_src>>) /\\\n              (((<<LOC: loc0 <> loc>>) /\\ (<<ORD: Ordering.le Ordering.acqrel ord>>)) \\/\n               ((<<LOC: loc0 = loc>>) /\\ (<<SRC: val_src = val_src1>>) /\\ (<<TGT: val_tgt = val_tgt1>>))))>>).\nProof.\n  hexploit Local.read_step_future; eauto. i. des.\n  destruct lc_src0 as [tvw_src0 prom_src].\n  destruct lc_tgt0 as [tvw_tgt0 prom_tgt].\n  dup SIM. inv SIM. inv LOCAL. inv READ.\n  hexploit sim_memory_get; eauto; ss. i. des. inv MSG; ss.\n  assert (READSRC: exists tvw_src1, (<<READSRC: forall val (VAL: Const.le val val_src), Local.read_step (Local.mk tvw_src0 prom_src) mem_src loc to_src val vw_src ord (Local.mk tvw_src1 prom_src)>>) /\\\n                                    (<<SIM: sim_tview f flag_src rel_vers tvw_src1 (TView.read_tview tvw_tgt0 loc to_tgt released_tgt ord)>>)).\n  { esplits.\n    { i. econs; eauto.\n      { ss. inv TVIEW. eapply sim_readable; eauto. }\n    }\n    { ss. eapply sim_read_tview; eauto.\n      { rewrite H0. eapply VERS. }\n      { eapply MEMSRC in GET0. des.\n        eapply message_to_time_le_opt_view; eauto.\n      }\n      { eapply MEMTGT in GET. des.\n        eapply message_to_time_le_opt_view; eauto.\n      }\n    }\n  }\n  des. hexploit READSRC0; [refl|..]. intros READSRC.\n  hexploit Local.read_step_future; eauto. i. des. ss.\n  hexploit sim_thread_acquire; eauto.\n  { i. hexploit FLAG; eauto. i.\n    assert (LOC: loc0 <> loc).\n    { ii. subst. rewrite FLAGTGT in TGT. ss. }\n    inv READSRC. ss. inv LC2. splits.\n    { ss. destruct (Ordering.le Ordering.acqrel ord); ss.\n      rewrite timemap_bot_join_r.\n      unfold TimeMap.join.\n      rewrite TimeFacts.le_join_l; auto.\n      destruct (Ordering.le Ordering.relaxed ord); ss.\n      { rewrite timemap_singleton_neq; auto. eapply Time.bot_spec. }\n      { eapply Time.bot_spec. }\n    }\n    { ss. destruct (Ordering.le Ordering.acqrel ord); ss.\n      rewrite timemap_bot_join_r.\n      unfold TimeMap.join.\n      rewrite TimeFacts.le_join_l; auto.\n      destruct (Ordering.le Ordering.relaxed ord); ss.\n      { rewrite timemap_singleton_neq; auto. eapply Time.bot_spec. }\n      { rewrite timemap_singleton_neq; auto. eapply Time.bot_spec. }\n    }\n  }\n  i. des. esplits; eauto.\n  { i. specialize (MAXSRC loc). rewrite VAL1 in MAXSRC. inv MAXSRC.\n    hexploit MAX; eauto. i. des.\n    hexploit max_readable_read_only_aux; eauto.\n    { inv SIM2. eapply sim_local_consistent; eauto. }\n    i. des. subst. inv MAX0.\n    rewrite GET1 in GET0. inv GET0. auto.\n  }\n  { i. specialize (MAXTGT loc). rewrite VAL1 in MAXTGT. inv MAXTGT.\n    hexploit MAX; eauto. i. des.\n    hexploit max_readable_read_only_aux; eauto.\n    i. des. subst. inv MAX0.\n    rewrite GET1 in GET. inv GET. auto.\n  }\n  i. hexploit VALS; eauto. i. des.\n  { left. eauto. }\n  { right. esplits; eauto. destruct (Loc.eq_dec loc0 loc).\n    { assert (ORD: Ordering.le Ordering.relaxed ord).\n      { inv READSRC. inv LC2.\n        eapply NNPP. ii. eapply read_tview_pln in H.\n        { rewrite H in TS. timetac. }\n        { inv READABLE0. ss. }\n      }\n      subst. right. splits; auto.\n      { red in VALSRC0. des.\n        replace (View.pln (TView.cur tvw_src1) loc) with to_src in VALSRC0.\n        { rewrite GET0 in VALSRC0. inv VALSRC0. auto. }\n        symmetry. inv READSRC. inv LC2.\n        ss. eapply read_tview_incr_rlx; eauto.\n        { eapply message_to_time_le_opt_view; eauto.\n          eapply MEMSRC; eauto.\n        }\n        { inv READABLE0. ss. }\n      }\n      { red in VALTGT0. des.\n        replace (View.pln (TView.cur (TView.read_tview tvw_tgt0 loc to_tgt released_tgt ord)) loc) with to_tgt in VALTGT0.\n        { rewrite GET in VALTGT0. inv VALTGT0. auto. }\n        symmetry. eapply read_tview_incr_rlx; eauto.\n        { eapply message_to_time_le_opt_view; eauto.\n          eapply MEMTGT; eauto.\n        }\n        { inv READABLE. ss. }\n      }\n    }\n    { left. inv READSRC. inv LC2. ss.\n      destruct (Ordering.le Ordering.acqrel ord); auto.\n      ss. rewrite timemap_bot_join_r in TS.\n      unfold TimeMap.join in TS. rewrite TimeFacts.le_join_l in TS; auto.\n      { timetac. }\n      { destruct (Ordering.le Ordering.relaxed ord); ss.\n        { rewrite timemap_singleton_neq; auto. eapply Time.bot_spec. }\n        { apply Time.bot_spec. }\n      }\n    }\n  }\nQed.\n\nLemma sim_thread_read_fence_step\n      f vers flag_src flag_tgt vs_src0 vs_tgt0\n      mem_src mem_tgt lc_src0 lc_tgt0 sc_src sc_tgt\n      lc_tgt1 ordr ordw\n      (SIM: sim_thread\n              f vers flag_src flag_tgt vs_src0 vs_tgt0\n              mem_src mem_tgt lc_src0 lc_tgt0 sc_src sc_tgt)\n      (READ: local_fence_read_step lc_tgt0 sc_tgt ordr ordw lc_tgt1)\n      (CONSISTENT: Local.promise_consistent lc_tgt1)\n      (LOCALSRC: Local.wf lc_src0 mem_src)\n      (LOCALTGT: Local.wf lc_tgt0 mem_tgt)\n      (MEMSRC: Memory.closed mem_src)\n      (MEMTGT: Memory.closed mem_tgt)\n      (SCSRC: Memory.closed_timemap sc_src mem_src)\n      (SCTGT: Memory.closed_timemap sc_tgt mem_tgt)\n      (WF: Mapping.wfs f)\n      (VERS: versions_wf f vers)\n      (ACQFLAG: forall loc\n                       (SRC: flag_src loc = false) (TGT: flag_tgt loc = true),\n          ~ Ordering.le Ordering.acqrel ordr)\n      (RELFLAG: forall loc\n                       (SRC: flag_src loc = false) (TGT: flag_tgt loc = true),\n          ~ Ordering.le Ordering.seqcst ordw)\n  :\n    exists lc_src1 vs_src1 vs_tgt1,\n      (<<READ: local_fence_read_step lc_src0 sc_src ordr ordw lc_src1>>) /\\\n      (<<SIM: sim_thread\n                f vers flag_src flag_tgt vs_src1 vs_tgt1\n                mem_src mem_tgt lc_src1 lc_tgt1 sc_src sc_tgt>>) /\\\n      (<<VALS: forall loc0,\n          ((<<SRC: vs_src1 loc0 = vs_src0 loc0>>) /\\ (<<TGT: vs_tgt1 loc0 = vs_tgt0 loc0>>)) \\/\n          (exists val_src val_tgt,\n              (<<NONESRC: vs_src0 loc0 = None>>) /\\ (<<NONETGT: vs_tgt0 loc0 = None>>) /\\\n              (<<VALSRC: vs_src1 loc0 = Some val_src>>) /\\ (<<VALTGT: vs_tgt1 loc0 = Some val_tgt>>) /\\\n              (<<VALLE: Const.le val_tgt val_src>>) /\\\n              (<<ORD: Ordering.le Ordering.acqrel ordr \\/ Ordering.le Ordering.seqcst ordw>>))>>).\nProof.\n  assert (exists lc_src1, (<<READ: local_fence_read_step lc_src0 sc_src ordr ordw lc_src1>>)).\n  { inv READ. inv SIM. inv LOCAL. esplits. econs; eauto.\n    { i. eapply sim_promises_nonsynch; eauto. }\n    { i. subst. ss. eapply sim_promises_bot; eauto. i.\n      destruct (flag_tgt loc) eqn:EQ; auto.\n      exfalso. eapply RELFLAG; eauto.\n    }\n  }\n  des. hexploit local_fence_read_step_future; [eapply READ|..]; eauto. i. des.\n  hexploit local_fence_read_step_future; [eapply READ0|..]; eauto. i. des.\n  destruct lc_src0 as [tvw_src0 prom_src].\n  destruct lc_tgt0 as [tvw_tgt0 prom_tgt].\n  inv READ. inv READ0. ss.\n  dup SIM. inv SIM. inv LOCAL1.\n  assert (VIEW: sim_tview f flag_src rel_vers (local_read_fence_tview tvw_src0 sc_src ordr ordw) (local_read_fence_tview tvw_tgt0 sc_tgt ordr ordw)).\n  { eapply sim_local_read_fence_tview; eauto. eapply sim_timemap_mon_locs; eauto; ss. }\n  hexploit sim_thread_acquire; eauto.\n  { i. hexploit ACQFLAG; eauto. hexploit RELFLAG; eauto. i. ss. des_ifs; ss. }\n  i. des. esplits; eauto.\n  { econs; eauto. }\n  { i. hexploit (VALS loc0). i. des; eauto.\n    right. esplits; eauto. clear - TS.\n    unfold local_read_fence_tview, TView.write_fence_sc, TView.read_fence_tview in TS; ss.\n    des_ifs; auto. timetac.\n  }\nQed.\n\nLemma mapped_msgs_exists_aux f0 f1 vers msgs_tgt prom_tgt loc flag_new\n      mem_src\n      (PROM: exists srctm flag_src flag_tgt prom_src, sim_promises srctm flag_src flag_tgt f0 vers prom_src prom_tgt)\n      (MAPLE: Mapping.le (f0 loc) f1)\n      (MSGS: forall from to msg (IN: List.In (from, to, msg) msgs_tgt), Memory.get loc to prom_tgt = Some (from, msg))\n      (WF0: Mapping.wfs f0)\n      (WF1: Mapping.wf f1)\n      (VERSWF: versions_wf f0 vers)\n      (BOTNONE: Memory.bot_none prom_tgt)\n      (MSGSWF: wf_cell_msgs msgs_tgt)\n      (SIM: sim_closed_memory f0 mem_src)\n\n      ts_tgt ts_src\n      (SIMTIME: sim_timestamp_exact f1 f1.(Mapping.ver) ts_src ts_tgt)\n      (MAX: Time.le (Memory.max_ts loc mem_src) ts_src)\n      (RESERVE: forall from_tgt to_tgt msg_tgt from_src to_src\n                       (GET: Memory.get loc to_tgt prom_tgt = Some (from_tgt, msg_tgt))\n                       (TS: Time.lt from_tgt ts_tgt)\n                       (TO: sim_timestamp_exact (f0 loc) (f0 loc).(Mapping.ver) to_src to_tgt)\n                       (FROM: sim_timestamp_exact (f0 loc) (f0 loc).(Mapping.ver) from_src from_tgt),\n          (<<RESERVE: msg_tgt = Message.reserve>>) /\\\n          (<<TS: Time.lt to_tgt ts_tgt>>) /\\\n          (<<DISJOINT: forall from to msg (GET: Memory.get loc to mem_src = Some (from, msg)),\n              Interval.disjoint (from_src, to_src) (from, to)>>))\n      (SAME: forall to_tgt to_src\n                    (TS: Time.lt to_tgt ts_tgt)\n                    (MAP: sim_timestamp_exact (f0 loc) (f0 loc).(Mapping.ver) to_src to_tgt),\n          sim_timestamp_exact f1 f1.(Mapping.ver) to_src to_tgt)\n  :\n    exists msgs_src,\n      (<<FORALL: List.Forall2\n                   (fun '(from_src, to_src, msg_src) '(from_tgt, to_tgt, msg_tgt) =>\n                      (<<FROM: sim_timestamp_exact f1 f1.(Mapping.ver) from_src from_tgt>>) /\\\n                      (<<TO: sim_timestamp_exact f1 f1.(Mapping.ver) to_src to_tgt>>) /\\\n                      (<<MESSAGE: sim_message_max flag_new loc to_src f0 (vers loc to_tgt) msg_src msg_tgt>>))\n                   msgs_src msgs_tgt>>) /\\\n      (<<DISJOINT: List.Forall\n                     (fun '(from, to, msg) => (__guard__((<<MAX: Time.le (Memory.max_ts loc mem_src) from>>) \\/ (<<RESERVE: msg = Message.reserve>>) /\\ (<<DISJOINT: forall to2 from2 msg2 (GET: Memory.get loc to2 mem_src = Some (from2, msg2)), Interval.disjoint (from, to) (from2, to2)>>))) /\\ (<<TS: Time.lt from to>>) /\\ (<<MSGTO: Memory.message_to msg loc to>>) /\\ (<<WF: Message.wf msg>>) /\\ (<<CLOSED: semi_closed_message msg mem_src loc to>>)) msgs_src>>) /\\\n      (<<MSGSWF: wf_cell_msgs msgs_src>>)\n.\nProof.\n  pose proof mapping_latest_wf_loc as VERWF.\n  revert MSGS MSGSWF. induction msgs_tgt; i.\n  { exists []. splits.\n    { econs. }\n    { econs. }\n    { red. splits; econs. }\n  }\n  des. destruct a as [[from_tgt to_tgt] msg_tgt].\n  hexploit MSGS.\n  { left. eauto. }\n  intros GETTGT. hexploit sim_promises_get; eauto. i. des.\n  hexploit sim_timestamp_exact_mon_exists; [eapply FROM|..]; eauto. i. des.\n  hexploit sim_timestamp_exact_mon_exists; [eapply TO|..]; eauto. i. des.\n  hexploit (@sim_message_max_exists flag_new loc ts_src0 f0 (vers loc to_tgt) msg_tgt); eauto.\n  { i. hexploit VERS; eauto. i. des. esplits; eauto.\n    exploit VERSWF. rewrite VER. ss.\n  }\n  i. des. red in MSGSWF. des. inv DISJOINT. inv MSGSWF0.\n  hexploit IHmsgs_tgt; eauto.\n  { i. eapply MSGS. right. auto. }\n  { red. splits; auto. }\n  i. destruct H1 as [MSGWF TIMEWF]. guardH TIMEWF.\n  des.\n  assert (FROMTO: Time.lt ts_src1 ts_src0).\n  { eapply sim_timestamp_exact_lt; eauto.\n    hexploit memory_get_ts_strong; eauto. i. des; clarify.\n    rewrite BOTNONE in GETTGT. ss.\n  }\n  exists ((ts_src1, ts_src0, msg_src)::msgs_src). splits.\n  { econs; eauto. }\n  { econs; eauto. splits.\n    { destruct (Time.le_lt_dec ts_tgt from_tgt).\n      { left. transitivity ts_src; auto. eapply sim_timestamp_exact_le; eauto. }\n      { right. hexploit RESERVE; eauto. i. des. subst.\n        hexploit (@SAME to_tgt to_src); eauto. i.\n        eapply sim_timestamp_exact_inject in SIM1; eauto. subst.\n        hexploit (@SAME from_tgt from_src); eauto. i.\n        eapply sim_timestamp_exact_inject in SIM0; eauto. subst.\n        splits.\n        { inv MAX0; ss. }\n        { i. eauto. }\n      }\n    }\n    { auto. }\n    { eapply sim_message_max_msg_to; eauto. }\n    { eapply sim_message_max_msg_wf; eauto. }\n    { eapply sim_closed_memory_sim_message; eauto. }\n  }\n  { red in MSGSWF. des. red. splits.\n    { econs; eauto.\n      eapply List.Forall_forall. intros [[from_src0 to_src0] msg_src0] IN.\n      eapply list_Forall2_in2 in IN; eauto. des.\n      destruct b as [[from_tgt0 to_tgt0] msg_tgt0]. des.\n      eapply List.Forall_forall in HD; eauto. ss.\n      eapply sim_timestamp_exact_le; eauto.\n    }\n    { econs; eauto. splits; auto.\n      eapply sim_message_max_msg_wf; eauto.\n    }\n  }\nQed.\n\nLemma messages_times_exists (msgs: list (Time.t * Time.t * Message.t)) (f0: Mapping.t) ts\n      (MAPWF: Mapping.wf f0)\n  :\n    exists (f1: Mapping.t),\n      (<<MAPWF: Mapping.wf f1>>) /\\\n      (<<MAPLE: Mapping.le_strong f0 f1>>) /\\\n      (<<CLOSEDIF: forall to (CLOSED: Mapping.closed f1 f1.(Mapping.ver) to),\n          (<<CLOSED: Mapping.closed f0 f0.(Mapping.ver) to>>) \\/\n          (exists from val released, (<<IN: List.In (from, to, Message.concrete val released) msgs>>)) \\/\n          (<<TS: to = ts>>)>>) /\\\n      (<<CLOSED: List.Forall (fun '(from_src, to_src, msg_src) =>\n                                forall val released (MSG: msg_src = Message.concrete val released),\n                                  Mapping.closed f1 f1.(Mapping.ver) to_src) msgs>>) /\\\n      (<<CLOSEDTS: Mapping.closed f1 f1.(Mapping.ver) ts>>)\n.\nProof.\n  hexploit (@mapping_update_times f0 (fun to => to = ts \\/ exists from val released, List.In (from, to, Message.concrete val released) msgs)).\n  { eauto. }\n  { induction msgs.\n    { exists [ts]. i. des; ss; auto. }\n    { des. destruct a as [[from to] msg]. destruct msg.\n      { exists (to::l). i. ss. des; clarify.\n        { right. eapply IHmsgs. left. auto. }\n        { auto. }\n        { right. eapply IHmsgs. right. eauto. }\n      }\n      { exists l. i. eapply IHmsgs. ss. des; clarify; eauto. }\n      { exists l. i. eapply IHmsgs. ss. des; clarify; eauto. }\n    }\n  }\n  i. des. exists f1. splits; eauto.\n  { i. eapply TIMES in CLOSED. des; auto.\n    right. esplits; eauto.\n  }\n  { eapply List.Forall_forall. intros [[from to] msg] IN. i. subst.\n    eapply TIMES. right. esplits; eauto.\n  }\n  { eapply TIMES. right. left. auto. }\nQed.\n\nLemma mapped_msgs_complete f0 f1 msgs_src msgs_tgt loc vers flag_new\n      (WF1: Mapping.wf f1)\n      (FORALL: List.Forall2\n                 (fun '(from_src, to_src, msg_src) '(from_tgt, to_tgt, msg_tgt) =>\n                    (<<FROM: sim_timestamp_exact f1 f1.(Mapping.ver) from_src from_tgt>>) /\\\n                    (<<TO: sim_timestamp_exact f1 f1.(Mapping.ver) to_src to_tgt>>) /\\\n                    (<<MESSAGE: sim_message_max flag_new loc to_src f0 (vers loc to_tgt) msg_src msg_tgt>>))\n                 msgs_src msgs_tgt)\n      (CLOSED: List.Forall (fun '(from_src, to_src, msg_src) =>\n                              forall val released (MSG: msg_src = Message.concrete val released),\n                                Mapping.closed f1 f1.(Mapping.ver) to_src) msgs_src)\n  :\n    forall to_tgt from_tgt msg_tgt\n           (RESERVE: msg_tgt <> Message.reserve)\n           (GETTGT: List.In (from_tgt, to_tgt, msg_tgt) msgs_tgt),\n    exists to_src from_src msg_src,\n      (<<TO: sim_timestamp_exact f1 f1.(Mapping.ver) to_src to_tgt>>) /\\\n      (<<MSG: sim_message false loc f0 (vers loc to_tgt) msg_src msg_tgt>>) /\\\n      (<<CLOSED: forall val released (MSG: msg_tgt = Message.concrete val released), Mapping.closed f1 f1.(Mapping.ver) to_src>>) /\\\n      (<<IN: List.In (from_src, to_src, msg_src) msgs_src>>).\nProof.\n  i. eapply list_Forall2_in in GETTGT; eauto. des.\n  destruct a as [[from_src to_src] msg_src]. des. esplits; eauto.\n  { eapply sim_message_flag_mon. eapply sim_message_max_sim; eauto. }\n  { i. subst. eapply List.Forall_forall in CLOSED; eauto. ss.\n    inv MESSAGE; eauto.\n  }\nQed.\n\nLemma mapped_msgs_sound f0 f1 msgs_src msgs_tgt loc vers flag_new\n      (WF1: Mapping.wf f1)\n      (FORALL: List.Forall2\n                 (fun '(from_src, to_src, msg_src) '(from_tgt, to_tgt, msg_tgt) =>\n                    (<<FROM: sim_timestamp_exact f1 f1.(Mapping.ver) from_src from_tgt>>) /\\\n                    (<<TO: sim_timestamp_exact f1 f1.(Mapping.ver) to_src to_tgt>>) /\\\n                    (<<MESSAGE: sim_message_max flag_new loc to_src f0 (vers loc to_tgt) msg_src msg_tgt>>))\n                 msgs_src msgs_tgt)\n  :\n    forall to_src from_src msg_src\n           (IN: List.In (from_src, to_src, msg_src) msgs_src),\n    exists to_tgt from_tgt msg_tgt,\n      (<<TO: sim_timestamp_exact f1 f1.(Mapping.ver) to_src to_tgt>>) /\\\n      (<<FROM: sim_timestamp_exact f1 f1.(Mapping.ver) from_src from_tgt>>) /\\\n      (<<GET: List.In (from_tgt, to_tgt, msg_tgt) msgs_tgt>>).\nProof.\n  i. eapply list_Forall2_in2 in IN; eauto. des.\n  destruct b as [[from_tgt to_tgt] msg_tgt]. des. esplits; eauto.\nQed.\n\nLemma mapped_msgs_complete_promise f0 f1 msgs_src msgs_tgt loc vers flag_new\n      (WF1: Mapping.wf f1)\n      (FORALL: List.Forall2\n                 (fun '(from_src, to_src, msg_src) '(from_tgt, to_tgt, msg_tgt) =>\n                    (<<FROM: sim_timestamp_exact f1 f1.(Mapping.ver) from_src from_tgt>>) /\\\n                    (<<TO: sim_timestamp_exact f1 f1.(Mapping.ver) to_src to_tgt>>) /\\\n                    (<<MESSAGE: sim_message_max flag_new loc to_src f0 (vers loc to_tgt) msg_src msg_tgt>>))\n                 msgs_src msgs_tgt)\n      (CLOSED: List.Forall (fun '(from_src, to_src, msg_src) =>\n                              forall val released (MSG: msg_src = Message.concrete val released),\n                                Mapping.closed f1 f1.(Mapping.ver) to_src) msgs_src)\n  :\n    forall to_tgt from_tgt msg_tgt\n           (GETTGT: List.In (from_tgt, to_tgt, msg_tgt) msgs_tgt),\n    exists to_src from_src msg_src,\n      (<<TO: sim_timestamp_exact f1 f1.(Mapping.ver) to_src to_tgt>>) /\\\n      (<<MSG: sim_message_max flag_new loc to_src f0 (vers loc to_tgt) msg_src msg_tgt>>) /\\\n      (<<CLOSED: forall val released (MSG: msg_tgt = Message.concrete val released), Mapping.closed f1 f1.(Mapping.ver) to_src>>) /\\\n      (<<IN: List.In (from_src, to_src, msg_src) msgs_src>>).\nProof.\n  i. eapply list_Forall2_in in GETTGT; eauto. des.\n  destruct a as [[from_src to_src] msg_src]. des. esplits; eauto.\n  eapply List.Forall_forall in CLOSED; eauto. ss.\n  inv MESSAGE; eauto.\nQed.\n\nLemma mapped_msgs_sound_promise f0 f1 msgs_src msgs_tgt loc vers flag_new\n      (WF1: Mapping.wf f1)\n      (FORALL: List.Forall2\n                 (fun '(from_src, to_src, msg_src) '(from_tgt, to_tgt, msg_tgt) =>\n                    (<<FROM: sim_timestamp_exact f1 f1.(Mapping.ver) from_src from_tgt>>) /\\\n                    (<<TO: sim_timestamp_exact f1 f1.(Mapping.ver) to_src to_tgt>>) /\\\n                    (<<MESSAGE: sim_message_max flag_new loc to_src f0 (vers loc to_tgt) msg_src msg_tgt>>))\n                 msgs_src msgs_tgt)\n      (CLOSED: List.Forall (fun '(from_src, to_src, msg_src) =>\n                              forall val released (MSG: msg_src = Message.concrete val released),\n                                Mapping.closed f1 f1.(Mapping.ver) to_src) msgs_src)\n  :\n    forall to_src from_src msg_src\n           (IN: List.In (from_src, to_src, msg_src) msgs_src),\n    exists to_tgt from_tgt msg_tgt,\n      (<<TO: sim_timestamp_exact f1 f1.(Mapping.ver) to_src to_tgt>>) /\\\n      (<<FROM: sim_timestamp_exact f1 f1.(Mapping.ver) from_src from_tgt>>) /\\\n      (<<GET: List.In (from_tgt, to_tgt, msg_tgt) msgs_tgt>>).\nProof.\n  i. eapply list_Forall2_in2 in IN; eauto. des.\n  destruct b as [[from_tgt to_tgt] msg_tgt]. des. esplits; eauto.\nQed.\n\nLemma shited_mapping_space_future_memory srctm flag_src f0 vers mem_src mem_tgt\n      loc f1 ts_src ts_tgt from val released\n      (SIM: sim_memory srctm flag_src f0 vers mem_src mem_tgt)\n      (MAPLE: Mapping.le (f0 loc) f1)\n      (MAPWF0: Mapping.wfs f0)\n      (MAPWF1: Mapping.wf f1)\n      (PRESERVE: forall to_tgt to_src\n                        (TS: Time.lt to_tgt ts_tgt)\n                        (SIM: sim_timestamp_exact (f0 loc) (f0 loc).(Mapping.ver) to_src to_tgt),\n          sim_timestamp_exact f1 f1.(Mapping.ver) to_src to_tgt)\n      (SIMTS: sim_timestamp_exact f1 f1.(Mapping.ver) ts_src ts_tgt)\n      (MAX: ts_src = Memory.max_ts loc mem_src)\n      (GET: Memory.get loc ts_tgt mem_tgt = Some (from, Message.concrete val released))\n  :\n    space_future_memory\n      (Messages.of_memory mem_tgt)\n      f0 mem_src\n      (fun loc0 => if Loc.eq_dec loc0 loc then f1 else f0 loc0) mem_src.\nProof.\n  pose proof mapping_latest_wf_loc as VERWF.\n  econs. i. inv MSGS. destruct (Loc.eq_dec loc0 loc); cycle 1.\n  { eapply sim_timestamp_exact_inject in FROM0; eauto.\n    eapply sim_timestamp_exact_inject in TO0; eauto.\n  }\n  subst. destruct (Time.le_lt_dec to_tgt ts_tgt).\n  { inv l.\n    2:{ inv H. clarify. }\n    hexploit PRESERVE; [|eapply TO0|..]; eauto.\n    i. eapply sim_timestamp_exact_inject in TO1; eauto.\n    hexploit PRESERVE; [|eapply FROM0|..]; eauto.\n    { eapply TimeFacts.le_lt_lt; eauto. eapply memory_get_ts_le; eauto. }\n    i. eapply sim_timestamp_exact_inject in FROM1; eauto.\n  }\n  { hexploit memory_get_from_mon.\n    { eapply GET. }\n    { eapply GET0. }\n    { eauto. }\n    i. exfalso.\n    hexploit sim_timestamp_exact_le; [| |eapply H|..]; eauto. i.\n    inv COVERED. eapply Memory.max_ts_spec in GET1. des.\n    inv ITV0. ss. inv ITV. ss. eapply Time.lt_strorder.\n    eapply TimeFacts.le_lt_lt.\n    { eapply TO. }\n    eapply TimeFacts.le_lt_lt.\n    { eapply MAX. }\n    eapply TimeFacts.le_lt_lt.\n    { eapply H0. }\n    { eapply FROM2. }\n  }\nQed.\n\nLemma added_memory_space_future_memory f loc msgs_src prom_tgt mem_src0 mem_src1 mem_tgt\n      (MAPWF: Mapping.wfs f)\n      (ADDED: added_memory loc msgs_src mem_src0 mem_src1)\n      (SOUND: forall to_src from_src msg_src\n                     (IN: List.In (from_src, to_src, msg_src) msgs_src),\n          exists to_tgt from_tgt msg_tgt,\n            (<<TO: sim_timestamp_exact (f loc) (f loc).(Mapping.ver) to_src to_tgt>>) /\\\n            (<<FROM: sim_timestamp_exact (f loc) (f loc).(Mapping.ver) from_src from_tgt>>) /\\\n            (<<GET: Memory.get loc to_tgt prom_tgt = Some (from_tgt, msg_tgt)>>))\n      (MLE: Memory.le prom_tgt mem_tgt)\n  :\n    space_future_memory\n      (unchangable mem_tgt prom_tgt)\n      f mem_src0\n      f mem_src1.\nProof.\n  pose proof mapping_latest_wf_loc as VERWF.\n  inv ADDED. econs. i.\n  eapply sim_timestamp_exact_inject in FROM0; eauto.\n  eapply sim_timestamp_exact_inject in TO0; eauto. subst. splits; auto.\n  inv COVERED. econs; eauto.\n  destruct (Loc.eq_dec loc0 loc); subst.\n  2:{ rewrite OTHER in GET; eauto. }\n  eapply SOUND0 in GET. des; eauto. exfalso.\n  eapply SOUND in IN. des. inv MSGS.\n  hexploit Memory.get_disjoint.\n  { eapply GET0. }\n  { eapply MLE. eapply GET. }\n  i. des; clarify.\n  hexploit sim_disjoint; [..|eapply H|]; eauto.\nQed.\n\nLemma sim_timemap_shifted (L0 L1: Loc.t -> Prop) f0 f1 tm_src tm_tgt\n      loc ts_src ts_tgt\n      (SIM: sim_timemap L0 f0 (Mapping.vers f0) tm_src tm_tgt)\n      (MAPLE: Mapping.les f0 f1)\n      (MAPWF0: Mapping.wfs f0)\n      (MAPWF1: Mapping.wfs f1)\n      (TS: sim_timestamp_exact (f1 loc) (f1 loc).(Mapping.ver) ts_src ts_tgt)\n      (CLOSED: Mapping.closed (f1 loc) (f1 loc).(Mapping.ver) (tm_src loc))\n      (TMSRC: Time.le (tm_src loc) ts_src)\n      (TMTGT: Time.le ts_tgt (tm_tgt loc))\n      (LOCS: forall loc0 (IN: L1 loc0), L0 loc0 \\/ loc0 = loc)\n  :\n    sim_timemap L1 f1 (Mapping.vers f1) tm_src tm_tgt.\nProof.\n  pose proof mapping_latest_wf_loc as VERWF.\n  ii. eapply LOCS in LOC. des.\n  { eapply sim_timestamp_mon_ver.\n    { erewrite <- sim_timestamp_mon_mapping.\n      { eauto. }\n      { eauto. }\n      { eauto. }\n      { eauto. }\n    }\n    { eapply MAPLE. }\n    { eauto. }\n    { eauto. }\n  }\n  subst. red. esplits; eauto.\nQed.\n\nLemma sim_thread_flag_src_view\n      f vers flag_src flag_tgt vs_src vs_tgt\n      mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt\n      loc\n      (SIM: sim_thread\n              f vers flag_src flag_tgt vs_src vs_tgt\n              mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt)\n      (LOCALSRC: Local.wf lc_src mem_src)\n      (FLAG: flag_src loc = true)\n  :\n    (<<ACQRLX: lc_src.(Local.tview).(TView.acq).(View.rlx) loc = lc_src.(Local.tview).(TView.cur).(View.rlx) loc>>) /\\\n    (<<ACQPLN: lc_src.(Local.tview).(TView.acq).(View.pln) loc = lc_src.(Local.tview).(TView.cur).(View.rlx) loc>>).\nProof.\n  inv SIM. inv LOCAL. ss.\n  hexploit FLAGSRC; eauto. i.\n  hexploit MAXTIMES; eauto. i.\n  rewrite SRCTM in *. des.\n  inv LOCALSRC. inv TVIEW_CLOSED. inv CUR. inv ACQ. ss. splits; auto.\n  { eapply TimeFacts.antisym.\n    { rewrite H0.\n      specialize (RLX0 loc). des. eapply Memory.max_ts_spec in RLX0. des. eauto.\n    }\n    { eapply TVIEW_WF. }\n  }\n  { eapply TimeFacts.antisym.\n    { rewrite H0.\n      specialize (PLN0 loc). des. eapply Memory.max_ts_spec in PLN0. des. eauto.\n    }\n    { rewrite H. eapply TVIEW_WF. }\n  }\nQed.\n\nLemma sim_view_shifted (L0 L1: Loc.t -> Prop) f0 f1 vw_src vw_tgt\n      loc ts_src ts_tgt\n      (SIM: sim_view L0 f0 (Mapping.vers f0) vw_src vw_tgt)\n      (MAPLE: Mapping.les f0 f1)\n      (MAPWF0: Mapping.wfs f0)\n      (MAPWF1: Mapping.wfs f1)\n      (TS: sim_timestamp_exact (f1 loc) (f1 loc).(Mapping.ver) ts_src ts_tgt)\n      (CLOSED: Mapping.closed (f1 loc) (f1 loc).(Mapping.ver) (vw_src.(View.rlx) loc))\n      (TMSRC: Time.le (vw_src.(View.rlx) loc) ts_src)\n      (TMTGT: Time.le ts_tgt (vw_tgt.(View.pln) loc))\n      (LOCS: forall loc0 (IN: L1 loc0), L0 loc0 \\/ loc0 = loc)\n      (VIEWWF: View.wf vw_tgt)\n      (SRCMAX: vw_src.(View.rlx) loc = vw_src.(View.pln) loc)\n  :\n    sim_view L1 f1 (Mapping.vers f1) vw_src vw_tgt.\nProof.\n  econs.\n  { eapply sim_timemap_shifted; eauto.\n    { eapply SIM. }\n    { rewrite <- SRCMAX. auto. }\n    { rewrite <- SRCMAX. auto. }\n  }\n  { eapply sim_timemap_shifted; eauto.\n    { eapply SIM. }\n    { etrans; eauto. eapply VIEWWF. }\n  }\nQed.\n\nLemma sim_tview_shifted flag_src0 flag_src1 f0 f1 rel_vers tvw_src tvw_tgt\n      loc ts_src ts_tgt\n      (SIM: sim_tview f0 flag_src0 rel_vers tvw_src tvw_tgt)\n      (MAPLE: Mapping.les f0 f1)\n      (MAPWF0: Mapping.wfs f0)\n      (MAPWF1: Mapping.wfs f1)\n      (TS: sim_timestamp_exact (f1 loc) (f1 loc).(Mapping.ver) ts_src ts_tgt)\n      (CLOSED: Mapping.closed (f1 loc) (f1 loc).(Mapping.ver) (tvw_src.(TView.cur).(View.rlx) loc))\n      (TMSRC: Time.le (tvw_src.(TView.cur).(View.rlx) loc) ts_src)\n      (TMTGT: Time.le ts_tgt (tvw_tgt.(TView.cur).(View.pln) loc))\n      (LOCS: forall loc0 (IN: flag_src1 loc0 = false), flag_src0 loc0 = false \\/ loc0 = loc)\n      (VIEWWF: TView.wf tvw_tgt)\n      (SRCMAX0: tvw_src.(TView.cur).(View.pln) loc = tvw_src.(TView.cur).(View.rlx) loc)\n      (SRCMAX1: tvw_src.(TView.acq).(View.rlx) loc = tvw_src.(TView.cur).(View.rlx) loc)\n      (SRCMAX2: tvw_src.(TView.acq).(View.pln) loc = tvw_src.(TView.cur).(View.rlx) loc)\n  :\n    sim_tview f1 flag_src1 rel_vers tvw_src tvw_tgt.\nProof.\n  inv SIM. econs.\n  { i. erewrite <- sim_view_mon_mapping; eauto. }\n  { eapply sim_view_shifted; eauto. eapply VIEWWF. }\n  { eapply sim_view_shifted; eauto.\n    { rewrite SRCMAX1. auto. }\n    { rewrite SRCMAX1. auto. }\n    { etrans; eauto. eapply VIEWWF. }\n    { eapply VIEWWF. }\n    { rewrite SRCMAX1. auto. }\n  }\n  { i. eapply version_wf_mapping_mon; eauto. }\nQed.\n\nLemma sim_thread_deflag_match_aux\n      f0 vers flag_src flag_tgt vs_src vs_tgt\n      mem_src0 mem_tgt lc_src0 lc_tgt sc_src sc_tgt\n      loc\n      (SIM: sim_thread\n              f0 vers flag_src flag_tgt vs_src vs_tgt\n              mem_src0 mem_tgt lc_src0 lc_tgt sc_src sc_tgt)\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n      (LOCALSRC: Local.wf lc_src0 mem_src0)\n      (LOCALTGT: Local.wf lc_tgt mem_tgt)\n      (MEMSRC: Memory.closed mem_src0)\n      (MEMTGT: Memory.closed mem_tgt)\n      (SCSRC: Memory.closed_timemap sc_src mem_src0)\n      (SCTGT: Memory.closed_timemap sc_tgt mem_tgt)\n      (WF: Mapping.wfs f0)\n      (VERSWF: versions_wf f0 vers)\n      (FLAG: flag_src loc = true)\n      (VAL: option_rel Const.le (vs_tgt loc) (vs_src loc))\n      lang st\n  :\n    exists lc_src1 mem_src1 f1,\n      (<<STEPS: rtc (tau (@pred_step is_promise _))\n                    (Thread.mk lang st lc_src0 sc_src mem_src0)\n                    (Thread.mk _ st lc_src1 sc_src mem_src1)>>) /\\\n      (<<SIM: sim_thread\n                f1 vers\n                (fun loc0 => if Loc.eq_dec loc0 loc then false else flag_src loc0)\n                (fun loc0 => if Loc.eq_dec loc0 loc then false else flag_tgt loc0)\n                vs_src vs_tgt\n                mem_src1 mem_tgt lc_src1 lc_tgt sc_src sc_tgt>>) /\\\n      (<<WF: Mapping.wfs f1>>) /\\\n      (<<MAPLE: Mapping.les f0 f1>>) /\\\n      (<<UNCH: forall loc0 (NEQ: loc0 <> loc), f1 loc0 = f0 loc0>>) /\\\n      (<<MAPFUTURE: map_future_memory f0 f1 mem_src1>>) /\\\n      (<<SPACE: space_future_memory (unchangable mem_tgt lc_tgt.(Local.promises)) f0 mem_src0 f1 mem_src1>>)\n.\nProof.\n  hexploit sim_thread_flag_src_view; eauto. i. des.\n  inv SIM. hexploit (MAXSRC loc). intros MAXTSSRC.\n  hexploit (MAXTGT loc). intros MAXTSTGT.\n  destruct (vs_src loc) eqn:VSRC; cycle 1.\n  { hexploit max_value_src_flag_none; eauto. i. clarify. }\n  inv MAXTSSRC. hexploit MAX; eauto. i. des.\n  destruct (vs_tgt loc) eqn:VTGT; ss.\n  inv MAXTSTGT. hexploit MAX1; eauto. i. des.\n  assert (TS: srctm loc = View.rlx (TView.cur tvw) loc).\n  { inv LOCAL. auto. }\n  hexploit sim_memory_top; eauto. intros TOP.\n  hexploit (@shifted_mapping_exists (f0 loc) (View.pln (TView.cur tvw0) loc) (srctm loc)); eauto. i. des.\n  hexploit (@wf_cell_msgs_exists (prom0 loc)). intros [msgs_tgt ?]. des.\n  hexploit mapped_msgs_exists_aux.\n  { inv LOCAL. eauto. }\n  { eauto. }\n  { i. eapply COMPLETE. eauto. }\n  { eauto. }\n  { eauto. }\n  { eauto. }\n  { eapply LOCALTGT. }\n  { eauto. }\n  { eauto. }\n  { eapply TS0. }\n  { rewrite MAXTIMES; auto. refl. }\n  { i. inv MAX2. destruct (Time.le_lt_dec (View.pln (TView.cur tvw0) loc) to_tgt).\n    { exfalso. inv l.\n      { hexploit memory_get_from_mon.\n        { eapply GET0. }\n        { eapply LOCALTGT. eapply GET. }\n        { eauto. }\n        i. timetac.\n      }\n      { inv H. rewrite GET in NONE. ss. }\n    }\n    { destruct (classic (msg_tgt = Message.reserve)); cycle 1.\n      { exfalso. exploit CONSISTENT; eauto. intros x. ss. eapply Time.lt_strorder.\n        eapply TimeFacts.lt_le_lt.\n        { eapply x. }\n        { etrans.\n          { left. eapply l. }\n          { eapply LOCALTGT. }\n        }\n      }\n      splits; auto. i. subst.\n      exploit RESERVED; eauto. i. des.\n      eapply sim_timestamp_exact_inject in TO; eauto. subst.\n      eapply sim_timestamp_exact_inject in FROM; eauto. subst.\n      eauto.\n    }\n  }\n  { eauto. }\n  i. des.\n  inv MAX0. inv MAX2. ss.\n  hexploit sim_memory_sound; eauto. i. des.\n  { exfalso. eapply TOP in TO. eapply Time.lt_strorder.\n    eapply TimeFacts.lt_le_lt.\n    { eapply TO. }\n    { inv LOCAL. rewrite SRCTM. rewrite FLAGSRC; auto. }\n  }\n  hexploit NONE1; eauto. i. subst.\n  hexploit (messages_times_exists msgs_src f1); auto. i. des.\n  eapply list_Forall2_impl in FORALL; cycle 1.\n  { i. instantiate (1:= fun '(from_src, to_src, msg_src) '(from_tgt, to_tgt, msg_tgt) =>\n                          (<<FROM: sim_timestamp_exact f2 f2.(Mapping.ver) from_src from_tgt>>) /\\\n                          (<<TO: sim_timestamp_exact f2 f2.(Mapping.ver) to_src to_tgt>>) /\\\n                          (<<MESSAGE: sim_message_max false loc to_src f0 (vers loc to_tgt) msg_src msg_tgt>>)).\n    destruct a as [[from_src to_src] msg_src]. destruct b as [[from_tgt to_tgt] msg_tgt].\n    des. splits; eauto.\n    { eapply sim_timestamp_exact_mon_strong; [..|eauto]; eauto.  }\n    { eapply sim_timestamp_exact_mon_strong; [..|eauto]; eauto.  }\n  }\n  pose proof (mapped_msgs_complete _ _ _ _ _ _ _ MAPWF FORALL CLOSED0) as COMPLETEMEM.\n  pose proof (mapped_msgs_sound _ _ _ _ _ _ _ MAPWF FORALL) as SOUNDMEM.\n  pose proof (mapped_msgs_complete_promise _ _ _ _ _ _ _ MAPWF FORALL) as COMPLETEPROM.\n  pose proof (mapped_msgs_sound_promise _ _ _ _ _ _ _ MAPWF FORALL) as SOUNDPROM.\n  set (f' := fun loc0 => if Loc.eq_dec loc0 loc then f2 else f0 loc0).\n  assert (MAPSLE: Mapping.les f0 f').\n  { unfold f'. ii. condtac; subst.\n    { etrans; eauto. eapply Mapping.le_strong_le; eauto. }\n    { refl. }\n  }\n  assert (MAPSWF: Mapping.wfs f').\n  { unfold f'. ii. condtac; subst; eauto. }\n  hexploit add_promises_latest.\n  { eapply MSGSWF. }\n  { eapply LOCALSRC. }\n  { eapply MEMSRC. }\n  { eauto. }\n  i. des. inv LOCAL.\n  hexploit added_memory_sim_memory; eauto.\n  { rewrite TS. rewrite FLAGSRC; eauto. }\n  {  hexploit sim_memory_get; eauto; ss. i. des.\n     inv MSG; econs; eauto; econs.\n  }\n  { ss. }\n  { i. eapply MAX0 in GETTGT; eauto.\n    eapply COMPLETE in GETTGT. eapply COMPLETEMEM; eauto.\n  }\n  { i. eapply SOUNDMEM in IN. des. esplits; eauto.\n    eapply LOCALTGT. eapply COMPLETE; eauto.\n  }\n  { etrans; eauto. eapply Mapping.le_strong_le; eauto. }\n  { i. eapply sim_timestamp_exact_mon_strong; [|eauto|..]; eauto. }\n  { eapply sim_timestamp_exact_mon_strong; [|eauto|..]; eauto. }\n  { i. eapply CLOSEDIF in CLOSED1. des.\n    { left. eapply CLOSED. auto. }\n    { right. left. eauto. }\n    { subst. right. right. esplits; eauto. }\n  }\n  i. destruct H as [MEM1 ?]. des.\n  esplits.\n  { eapply STEPS. }\n  { econs.\n    { instantiate (1:=f'). eapply sim_timemap_mon_latest; eauto. }\n    { eauto. }\n    { econs.\n      { eapply sim_tview_shifted; eauto.\n        { eapply sim_timestamp_exact_mon_strong; [..|eapply TS0]; eauto.\n          unfold f'. des_ifs.\n        }\n        { unfold f'. des_ifs. rewrite <- SRCTM. auto. }\n        { rewrite <- SRCTM. refl. }\n        { refl. }\n        { i. des_ifs; auto. }\n        { eapply LOCALTGT. }\n        { rewrite FLAGSRC; auto. }\n      }\n      { eapply added_memory_sim_promise_match; eauto.\n        { i. eapply COMPLETE in GETTGT. eapply COMPLETEPROM in GETTGT; eauto. }\n        { i. eapply SOUNDPROM in IN; eauto. des.\n          esplits; eauto. eapply COMPLETE; eauto.\n        }\n        { etrans; eauto. eapply Mapping.le_strong_le; eauto. }\n      }\n      { eauto. }\n      { i. des_ifs. eauto. }\n      { eauto. }\n    }\n    { eapply promise_steps_max_values_src; eauto. }\n    { eauto. }\n    { eauto. }\n    { red in FIN. des.\n      hexploit (list_filter_exists (fun loc0 => loc0 <> loc) dom). i. des.\n      exists l'. splits. i. etrans; [|eapply COMPLETE0]. condtac; subst.\n      { split; i; des; ss. }\n      { split; i.\n        { split; auto. eapply DOM; auto. }\n        { des. eapply DOM; eauto. }\n      }\n    }\n    { eauto. }\n    { eauto. }\n    { i. des_ifs. rewrite MAXTIMES; auto.\n      eapply unchanged_loc_max_ts.\n      { eapply added_memory_unchanged_loc; eauto. }\n      { eapply MEMSRC. }\n    }\n    { ss. ii. unfold f'. des_ifs. hexploit (RESERVED loc0); eauto.\n      i. des. esplits; eauto. i.\n      inv MEM0. rewrite OTHER in GETSRC; eauto.\n    }\n    { unfold f'. ii. ss. inv PROMISES.\n      destruct (Loc.eq_dec loc0 loc); subst.\n      { eapply SOUND in GETSRC. des.\n        { hexploit sim_promises_none; eauto. i. rewrite GET1 in H. ss. }\n        { eapply list_Forall2_in2 in FORALL; eauto. des.\n          destruct b as [[from_tgt to_tgt] msg_tgt]. des.\n          eapply COMPLETE in IN0. eapply LOCALTGT in IN0.\n          esplits; eauto. inv MESSAGE; ss.\n        }\n      }\n      { erewrite OTHER in GETSRC; eauto. }\n    }\n  }\n  { eauto. }\n  { eauto. }\n  { i. unfold f'. des_ifs. }\n  { eauto. }\n  { eapply space_future_memory_trans.\n    { eapply space_future_memory_mon_msgs.\n      { eapply shited_mapping_space_future_memory.\n        { eauto. }\n        { etrans; eauto. eapply Mapping.le_strong_le; eauto. }\n        { eauto. }\n        { eauto. }\n        { i. eapply sim_timestamp_exact_mon_strong; [..|eapply SAME]; eauto. }\n        { eapply sim_timestamp_exact_mon_strong; [..|eauto]; eauto. }\n        { eauto. }\n        { eauto. }\n      }\n      { eapply unchangable_messages_of_memory. }\n    }\n    { eapply added_memory_space_future_memory; eauto.\n      { i. eapply SOUNDPROM in IN; eauto. des. esplits; eauto.\n        { des_ifs; eauto. }\n        { des_ifs; eauto. }\n        { eapply COMPLETE; eauto. }\n      }\n      { eapply LOCALTGT. }\n    }\n    { eauto. }\n    { refl. }\n    { eauto. }\n    { eauto. }\n    { eauto. }\n  }\nQed.\n\nLemma sim_thread_deflag_unmatch_aux\n      f0 vers flag_src flag_tgt vs_src vs_tgt\n      mem_src0 mem_tgt lc_src0 lc_tgt sc_src sc_tgt\n      loc\n      (SIM: sim_thread\n              f0 vers flag_src flag_tgt vs_src vs_tgt\n              mem_src0 mem_tgt lc_src0 lc_tgt sc_src sc_tgt)\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n      (LOCALSRC: Local.wf lc_src0 mem_src0)\n      (LOCALTGT: Local.wf lc_tgt mem_tgt)\n      (MEMSRC: Memory.closed mem_src0)\n      (MEMTGT: Memory.closed mem_tgt)\n      (SCSRC: Memory.closed_timemap sc_src mem_src0)\n      (SCTGT: Memory.closed_timemap sc_tgt mem_tgt)\n      (WF: Mapping.wfs f0)\n      (VERSWF: versions_wf f0 vers)\n      (FLAG: flag_src loc = true)\n      lang st\n  :\n    exists lc_src1 mem_src1 f1 flag,\n      (<<STEPS: rtc (tau (@pred_step is_promise _))\n                    (Thread.mk lang st lc_src0 sc_src mem_src0)\n                    (Thread.mk _ st lc_src1 sc_src mem_src1)>>) /\\\n      (<<SIM: sim_thread\n                f1 vers\n                (fun loc0 => if Loc.eq_dec loc0 loc then false else flag_src loc0)\n                (fun loc0 => if Loc.eq_dec loc0 loc then flag else flag_tgt loc0)\n                vs_src vs_tgt\n                mem_src1 mem_tgt lc_src1 lc_tgt sc_src sc_tgt>>) /\\\n      (<<WF: Mapping.wfs f1>>) /\\\n      (<<MAPLE: Mapping.les f0 f1>>) /\\\n      (<<UNCH: forall loc0 (NEQ: loc0 <> loc), f1 loc0 = f0 loc0>>) /\\\n      (<<MAPFUTURE: map_future_memory f0 f1 mem_src1>>) /\\\n      (<<SPACE: space_future_memory (unchangable mem_tgt lc_tgt.(Local.promises)) f0 mem_src0 f1 mem_src1>>)\n.\nProof.\n  hexploit sim_thread_flag_src_view; eauto. i. des.\n  inv SIM. hexploit (MAXSRC loc). intros MAXTSSRC.\n  hexploit (MAXTGT loc). intros MAXTSTGT.\n  destruct (vs_src loc) eqn:VSRC; cycle 1.\n  { hexploit max_value_src_flag_none; eauto. i. clarify. }\n  inv MAXTSSRC. hexploit MAX; eauto. i. des.\n  destruct (vs_tgt loc) eqn:VTGT; ss.\n  2:{ exfalso. specialize (PERM loc). rewrite VSRC in PERM. rewrite VTGT in PERM. ss. }\n  inv MAXTSTGT. hexploit MAX1; eauto. i. des.\n  assert (TS: srctm loc = View.rlx (TView.cur tvw) loc).\n  { inv LOCAL. auto. }\n  hexploit sim_memory_top; eauto. intros TOP.\n  set (max1 := Time.incr (Memory.max_ts loc mem_src0)).\n  assert (TOP1: top_time max1 (f0 loc)).\n  { unfold max1. eapply top_time_mon; eauto. rewrite MAXTIMES; auto.\n    left. eapply Time.incr_spec.\n  }\n  hexploit Memory.add_exists_max_ts.\n  { instantiate (1:=max1). eapply Time.incr_spec. }\n  { instantiate (1:=Message.concrete t0 None). econs; ss. }\n  intros [mem_src1 ADDMEM].\n  hexploit Memory.add_exists_le.\n  { eapply LOCALSRC. }\n  { eauto. }\n  intros [prom_src1 ADDPROM].\n  hexploit add_src_sim_memory_flag_up; eauto.\n  { rewrite <- MAXTIMES; auto. }\n  { rewrite <- MAXTIMES; auto. refl. }\n  { i. clarify. }\n  intros SIMMEM1.\n  assert (PROMISESTEP: Local.promise_step (Local.mk tvw prom) mem_src0 loc (Memory.max_ts loc mem_src0) max1 (Message.concrete t0 None) (Local.mk tvw prom_src1) mem_src1 Memory.op_kind_add).\n  { econs; eauto. econs; eauto.\n    { econs; eauto. eapply Time.bot_spec. }\n    { i. dup GET. eapply Memory.max_ts_spec in GET. des.\n      eapply memory_get_ts_le in GET0. eapply Time.lt_strorder.\n      eapply TimeFacts.le_lt_lt.\n      { eapply MAX3. }\n      eapply TimeFacts.lt_le_lt.\n      { eapply Time.incr_spec. }\n      { eapply GET0. }\n    }\n  }\n  hexploit Local.promise_step_future; eauto. i. des.\n  hexploit (@shifted_mapping_exists (f0 loc) (View.pln (TView.cur tvw0) loc) max1); eauto.\n  i. des.\n  hexploit (@wf_cell_msgs_exists (prom0 loc)). intros [msgs_tgt ?]. des.\n  hexploit mapped_msgs_exists_aux.\n  { inv LOCAL. eauto. }\n  { eauto. }\n  { i. eapply COMPLETE. eauto. }\n  { eauto. }\n  { eauto. }\n  { eauto. }\n  { eapply LOCALTGT. }\n  { eauto. }\n  { eapply sim_closed_memory_future.\n    { eauto. }\n    { eapply Memory.future_future_weak; eauto. }\n  }\n  { eapply TS0. }\n  { erewrite le_add_max_ts; eauto.\n    { refl. }\n    { left. eapply Time.incr_spec. }\n  }\n  { i. inv MAX2. destruct (Time.le_lt_dec (View.pln (TView.cur tvw0) loc) to_tgt).\n    { exfalso. inv l.\n      { hexploit memory_get_from_mon.\n        { eapply GET0. }\n        { eapply LOCALTGT. eapply GET. }\n        { eauto. }\n        i. timetac.\n      }\n      { inv H. rewrite GET in NONE. ss. }\n    }\n    { destruct (classic (msg_tgt = Message.reserve)); cycle 1.\n      { exfalso. exploit CONSISTENT; eauto. intros x. ss. eapply Time.lt_strorder.\n        eapply TimeFacts.lt_le_lt.\n        { eapply x. }\n        { etrans.\n          { left. eapply l. }\n          { eapply LOCALTGT. }\n        }\n      }\n      splits; auto. i. subst.\n      exploit RESERVED; eauto. i. des.\n      eapply sim_timestamp_exact_inject in TO; eauto. subst.\n      eapply sim_timestamp_exact_inject in FROM; eauto. subst.\n      erewrite Memory.add_o in GET1; eauto. des_ifs.\n      { ss. des; subst. eapply interval_le_disjoint. rewrite <- MAXTIMES; auto.\n        eapply TOP in TO0. left. auto.\n      }\n      { eapply DISJOINT; eauto. }\n    }\n  }\n  { eauto. }\n  i. des.\n  inv MAX0. inv MAX2. ss.\n  hexploit sim_memory_sound; [eapply MEM|..]; eauto. i. des.\n  { exfalso. eapply TOP in TO. eapply Time.lt_strorder.\n    eapply TimeFacts.lt_le_lt.\n    { eapply TO. }\n    { inv LOCAL. rewrite SRCTM. rewrite FLAGSRC; auto. }\n  }\n  hexploit NONE1; eauto. i. subst.\n  hexploit (messages_times_exists ((srctm loc, max1, Message.concrete t0 None)::msgs_src) f1 (srctm loc)); auto. i. des.\n  eapply list_Forall2_impl in FORALL; cycle 1.\n  { i. instantiate (1:= fun '(from_src, to_src, msg_src) '(from_tgt, to_tgt, msg_tgt) =>\n                          (<<FROM: sim_timestamp_exact f2 f2.(Mapping.ver) from_src from_tgt>>) /\\\n                          (<<TO: sim_timestamp_exact f2 f2.(Mapping.ver) to_src to_tgt>>) /\\\n                          (<<MESSAGE: sim_message_max true loc to_src f0 (vers loc to_tgt) msg_src msg_tgt>>)).\n    destruct a as [[from_src to_src] msg_src]. destruct b as [[from_tgt to_tgt] msg_tgt].\n    des. splits; eauto.\n    { eapply sim_timestamp_exact_mon_strong; [..|eauto]; eauto.  }\n    { eapply sim_timestamp_exact_mon_strong; [..|eauto]; eauto.  }\n  }\n  inv CLOSED0. hexploit H1; eauto. intros CLOSEDMAX. clear H1. rename H2 into CLOSED0.\n  pose proof (mapped_msgs_complete _ _ _ _ _ _ _ MAPWF FORALL CLOSED0) as COMPLETEMEM.\n  pose proof (mapped_msgs_sound _ _ _ _ _ _ _ MAPWF FORALL) as SOUNDMEM.\n  pose proof (mapped_msgs_complete_promise _ _ _ _ _ _ _ MAPWF FORALL) as COMPLETEPROM.\n  pose proof (mapped_msgs_sound_promise _ _ _ _ _ _ _ MAPWF FORALL) as SOUNDPROM.\n  set (f' := fun loc0 => if Loc.eq_dec loc0 loc then f2 else f0 loc0).\n  assert (MAPSLE: Mapping.les f0 f').\n  { unfold f'. ii. condtac; subst.\n    { etrans; eauto. eapply Mapping.le_strong_le; eauto. }\n    { refl. }\n  }\n  assert (MAPSWF: Mapping.wfs f').\n  { unfold f'. ii. condtac; subst; eauto. }\n  hexploit add_promises_latest.\n  { eapply MSGSWF. }\n  { eapply WF2. }\n  { eapply CLOSED2. }\n  { eauto.  }\n  i. des. inv LOCAL.\n  hexploit added_memory_sim_memory; eauto.\n  { eapply sim_closed_memory_future; eauto. eapply Memory.future_future_weak; eauto. }\n  { ss. des_ifs. eapply Memory.add_get0; eauto. }\n  { hexploit sim_memory_get; eauto; ss. i. des. inv MSG.\n    { econs; eauto.\n      { refl. }\n      { econs. }\n    }\n    { econs; eauto.\n      { refl. }\n      { econs. }\n    }\n  }\n  { ss. }\n  { i. eapply MAX0 in GETTGT; eauto.\n    eapply COMPLETE in GETTGT. eapply COMPLETEMEM; eauto.\n  }\n  { i. eapply SOUNDMEM in IN. des. esplits; eauto.\n    eapply LOCALTGT. eapply COMPLETE; eauto.\n  }\n  { etrans; eauto. eapply Mapping.le_strong_le; eauto. }\n  { i. eapply sim_timestamp_exact_mon_strong; [|eauto|..]; eauto. }\n  { ss. des_ifs. eapply sim_timestamp_exact_mon_strong; [|eauto|..]; eauto. }\n  { ss. des_ifs. }\n  { i. eapply CLOSEDIF in CLOSED1. des.\n    { left. eapply CLOSED. auto. }\n    { ss. des; clarify.\n      { right. right. left. esplits; eauto. des_ifs. }\n      { right. left. eauto. }\n    }\n    { subst. right. right. right. esplits; eauto.\n      rewrite TS. rewrite FLAGSRC; eauto. eapply Memory.add_get1; eauto.\n    }\n  }\n  i. destruct H as [MEM1 ?]. des.\n  esplits.\n  { econs 2.\n    { econs.\n      { econs.\n        { econs. econs 1. econs 1; eauto. }\n        { ss. }\n      }\n      { ss. }\n    }\n    eapply STEPS.\n  }\n  { econs.\n    { instantiate (1:=f'). eapply sim_timemap_mon_latest; eauto. }\n    { eapply sim_memory_change_no_flag.\n      { eauto. }\n      { instantiate (1:=srctm). i. des_ifs. }\n    }\n    { econs.\n      { eapply sim_tview_shifted; eauto.\n        { eapply sim_timestamp_exact_mon_strong; [..|eapply TS0]; eauto.\n          unfold f'. des_ifs.\n        }\n        { unfold f'. des_ifs. rewrite <- SRCTM. auto. }\n        { rewrite <- SRCTM. rewrite MAXTIMES; auto. left. eapply Time.incr_spec. }\n        { refl. }\n        { i. des_ifs; auto. }\n        { eapply LOCALTGT. }\n        { rewrite FLAGSRC; auto. }\n      }\n      { eapply added_memory_sim_promise_unmatch; eauto.\n        { eapply added_memory_cons; eauto. }\n        { i. eapply COMPLETE in GETTGT. eapply COMPLETEPROM in GETTGT; eauto.\n          des. esplits; eauto. right. eauto.\n        }\n        { i. ss. des.\n          { clarify. esplits.\n            { eapply sim_timestamp_exact_mon_strong; [..|eauto]; eauto. }\n            { right. splits; ss. rewrite MAXTIMES; auto. eapply Time.incr_spec. }\n          }\n          { eapply SOUNDPROM in IN; eauto. des.\n            esplits; eauto. left. esplits; eauto. eapply COMPLETE; eauto.\n          }\n        }\n        { etrans; eauto. eapply Mapping.le_strong_le; eauto. }\n      }\n      { eauto. }\n      { i. des_ifs. eauto. }\n      { eauto. }\n    }\n    { eapply promise_steps_max_values_src; eauto. eapply promise_max_values_src; eauto. }\n    { eauto. }\n    { eauto. }\n    { red in FIN. des.\n      hexploit (list_filter_exists (fun loc0 => loc0 <> loc) dom). i. des.\n      exists l'. splits. i. etrans; [|eapply COMPLETE0]. condtac; subst.\n      { split; i; des; ss. }\n      { split; i.\n        { split; auto. eapply DOM; auto. }\n        { des. eapply DOM; eauto. }\n      }\n    }\n    { eauto. }\n    { eauto. }\n    { i. des_ifs. rewrite MAXTIMES; auto.\n      eapply unchanged_loc_max_ts.\n      { eapply added_memory_unchanged_loc; eauto. eapply added_memory_cons; eauto. }\n      { eapply MEMSRC. }\n    }\n    { ss. ii. unfold f'. des_ifs. hexploit (RESERVED loc0); eauto.\n      i. des. esplits; eauto. i.\n      inv MEM0. rewrite OTHER in GETSRC; eauto.\n      erewrite Memory.add_o in GETSRC; eauto. des_ifs; eauto.\n      ss. des; clarify.\n    }\n    { unfold f'. ii. ss. inv PROMISES.\n      destruct (Loc.eq_dec loc0 loc); subst.\n      { eapply SOUND in GETSRC. des.\n        { erewrite Memory.add_o in GET1; eauto. des_ifs.\n          { ss. des; clarify. esplits.\n            { eapply sim_timestamp_exact_mon_strong; [..|eauto]; eauto. }\n            { eauto. }\n            { ss. }\n          }\n          { hexploit sim_promises_none; eauto. i. rewrite GET1 in H. ss. }\n        }\n        { eapply list_Forall2_in2 in FORALL; eauto. des.\n          destruct b as [[from_tgt to_tgt] msg_tgt]. des.\n          eapply COMPLETE in IN0. eapply LOCALTGT in IN0.\n          esplits; eauto. inv MESSAGE; ss.\n        }\n      }\n      { erewrite OTHER in GETSRC; eauto.\n        erewrite Memory.add_o in GETSRC; eauto. des_ifs; eauto.\n        ss. des; clarify.\n      }\n    }\n  }\n  { eauto. }\n  { eauto. }\n  { i. unfold f'. des_ifs. }\n  { eauto. }\n  { eapply space_future_memory_trans.\n    { eapply space_future_memory_mon_msgs.\n      { eapply space_future_memory_trans.\n        { eapply add_src_sim_memory_space_future_aux; eauto.\n          { rewrite <- MAXTIMES; auto. }\n          { i. rewrite <- MAXTIMES; auto. refl. }\n        }\n        { eapply shited_mapping_space_future_memory.\n          { eauto. }\n          { etrans; eauto. eapply Mapping.le_strong_le; eauto. }\n          { eauto. }\n          { eauto. }\n          { i. eapply sim_timestamp_exact_mon_strong; [..|eapply SAME]; eauto. }\n          { eapply sim_timestamp_exact_mon_strong; [..|eauto]; eauto. }\n          { erewrite le_add_max_ts; eauto. left. eapply Time.incr_spec. }\n          { eauto. }\n        }\n        { refl. }\n        { eauto. }\n        { eauto. }\n        { eauto. }\n        { eauto. }\n      }\n      { eapply unchangable_messages_of_memory. }\n    }\n    { eapply added_memory_space_future_memory; eauto.\n      { i. eapply SOUNDPROM in IN; eauto. des. esplits; eauto.\n        { des_ifs; eauto. }\n        { des_ifs; eauto. }\n        { eapply COMPLETE; eauto. }\n      }\n      { eapply LOCALTGT. }\n    }\n    { eauto. }\n    { refl. }\n    { eauto. }\n    { eauto. }\n    { eauto. }\n  }\nQed.\n\nLemma sim_thread_deflag_match\n      f0 vers flag_src flag_tgt vs_src vs_tgt\n      mem_src0 mem_tgt lc_src0 lc_tgt sc_src sc_tgt\n      loc\n      (SIM: sim_thread\n              f0 vers flag_src flag_tgt vs_src vs_tgt\n              mem_src0 mem_tgt lc_src0 lc_tgt sc_src sc_tgt)\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n      (LOCALSRC: Local.wf lc_src0 mem_src0)\n      (LOCALTGT: Local.wf lc_tgt mem_tgt)\n      (MEMSRC: Memory.closed mem_src0)\n      (MEMTGT: Memory.closed mem_tgt)\n      (SCSRC: Memory.closed_timemap sc_src mem_src0)\n      (SCTGT: Memory.closed_timemap sc_tgt mem_tgt)\n      (WF: Mapping.wfs f0)\n      (VERSWF: versions_wf f0 vers)\n      (FLAG: flag_src loc = false -> flag_tgt loc = false)\n      (VAL: option_rel Const.le (vs_tgt loc) (vs_src loc) \\/ flag_src loc = false)\n      lang st\n  :\n    exists lc_src1 mem_src1 f1,\n      (<<STEPS: rtc (tau (@pred_step is_promise _))\n                    (Thread.mk lang st lc_src0 sc_src mem_src0)\n                    (Thread.mk _ st lc_src1 sc_src mem_src1)>>) /\\\n      (<<SIM: sim_thread\n                f1 vers\n                (fun loc0 => if Loc.eq_dec loc0 loc then false else flag_src loc0)\n                (fun loc0 => if Loc.eq_dec loc0 loc then false else flag_tgt loc0)\n                vs_src vs_tgt\n                mem_src1 mem_tgt lc_src1 lc_tgt sc_src sc_tgt>>) /\\\n      (<<WF: Mapping.wfs f1>>) /\\\n      (<<MAPLE: Mapping.les f0 f1>>) /\\\n      (<<UNCH: forall loc0 (NEQ: loc0 <> loc), f1 loc0 = f0 loc0>>) /\\\n      (<<MAPFUTURE: map_future_memory f0 f1 mem_src1>>) /\\\n      (<<SPACE: space_future_memory (unchangable mem_tgt lc_tgt.(Local.promises)) f0 mem_src0 f1 mem_src1>>)\n.\nProof.\n  destruct (flag_src loc) eqn:EQ.\n  { des; ss. eapply sim_thread_deflag_match_aux; eauto. }\n  { esplits.\n    { refl. }\n    { replace (fun (loc0: Loc.t) => if LocSet.Facts.eq_dec loc0 loc then false else flag_src loc0) with flag_src.\n      2:{ extensionality loc0. des_ifs. }\n      replace (fun (loc0: Loc.t) => if LocSet.Facts.eq_dec loc0 loc then false else flag_tgt loc0) with flag_tgt.\n      2:{ extensionality loc0. des_ifs. eauto. }\n      eauto.\n    }\n    { eauto. }\n    { refl. }\n    { auto. }\n    { eapply map_future_memory_refl. }\n    { eapply space_future_memory_refl; eauto. refl. }\n  }\nQed.\n\nLemma sim_thread_deflag_unmatch\n      f0 vers flag_src flag_tgt vs_src vs_tgt\n      mem_src0 mem_tgt lc_src0 lc_tgt sc_src sc_tgt\n      loc\n      (SIM: sim_thread\n              f0 vers flag_src flag_tgt vs_src vs_tgt\n              mem_src0 mem_tgt lc_src0 lc_tgt sc_src sc_tgt)\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n      (LOCALSRC: Local.wf lc_src0 mem_src0)\n      (LOCALTGT: Local.wf lc_tgt mem_tgt)\n      (MEMSRC: Memory.closed mem_src0)\n      (MEMTGT: Memory.closed mem_tgt)\n      (SCSRC: Memory.closed_timemap sc_src mem_src0)\n      (SCTGT: Memory.closed_timemap sc_tgt mem_tgt)\n      (WF: Mapping.wfs f0)\n      (VERSWF: versions_wf f0 vers)\n      lang st\n  :\n    exists lc_src1 mem_src1 f1 flag,\n      (<<STEPS: rtc (tau (@pred_step is_promise _))\n                    (Thread.mk lang st lc_src0 sc_src mem_src0)\n                    (Thread.mk _ st lc_src1 sc_src mem_src1)>>) /\\\n      (<<SIM: sim_thread\n                f1 vers\n                (fun loc0 => if Loc.eq_dec loc0 loc then false else flag_src loc0)\n                (fun loc0 => if Loc.eq_dec loc0 loc then flag else flag_tgt loc0)\n                vs_src vs_tgt\n                mem_src1 mem_tgt lc_src1 lc_tgt sc_src sc_tgt>>) /\\\n      (<<WF: Mapping.wfs f1>>) /\\\n      (<<MAPLE: Mapping.les f0 f1>>) /\\\n      (<<UNCH: forall loc0 (NEQ: loc0 <> loc), f1 loc0 = f0 loc0>>) /\\\n      (<<MAPFUTURE: map_future_memory f0 f1 mem_src1>>) /\\\n      (<<SPACE: space_future_memory (unchangable mem_tgt lc_tgt.(Local.promises)) f0 mem_src0 f1 mem_src1>>)\n.\nProof.\n  destruct (flag_src loc) eqn:FLAG.\n  { eapply sim_thread_deflag_unmatch_aux; eauto. }\n  { esplits.\n    { refl. }\n    { instantiate (1:=flag_tgt loc).\n      replace (fun (loc0: Loc.t) => if LocSet.Facts.eq_dec loc0 loc then false else flag_src loc0) with flag_src.\n      2:{ extensionality loc0. des_ifs. }\n      replace (fun (loc0: Loc.t) => if LocSet.Facts.eq_dec loc0 loc then flag_tgt loc else flag_tgt loc0) with flag_tgt.\n      2:{ extensionality loc0. des_ifs. }\n      eauto.\n    }\n    { eauto. }\n    { refl. }\n    { auto. }\n    { eapply map_future_memory_refl. }\n    { eapply space_future_memory_refl; eauto. refl. }\n  }\nQed.\n\nLemma sim_thread_deflag_all_aux\n      dom\n  :\n    forall\n      f0 vers flag_src flag_tgt0 vs_src vs_tgt\n      mem_src0 mem_tgt lc_src0 lc_tgt sc_src sc_tgt\n      (D: Loc.t -> Prop)\n      (SIM: sim_thread\n              f0 vers flag_src flag_tgt0 vs_src vs_tgt\n              mem_src0 mem_tgt lc_src0 lc_tgt sc_src sc_tgt)\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n      (LOCALSRC: Local.wf lc_src0 mem_src0)\n      (LOCALTGT: Local.wf lc_tgt mem_tgt)\n      (MEMSRC: Memory.closed mem_src0)\n      (MEMTGT: Memory.closed mem_tgt)\n      (SCSRC: Memory.closed_timemap sc_src mem_src0)\n      (SCTGT: Memory.closed_timemap sc_tgt mem_tgt)\n      (WF: Mapping.wfs f0)\n      (VERSWF: versions_wf f0 vers)\n      (DEBT: forall loc, (<<DEBT: D loc>>) \\/\n                         ((<<FLAG: flag_src loc = false -> flag_tgt0 loc = false>>) /\\\n                          (<<VAL: option_rel Const.le (vs_tgt loc) (vs_src loc) \\/ flag_src loc = false>>)))\n      (FIN: forall loc (FLAG: flag_src loc = true), List.In loc dom)\n      lang st,\n    exists lc_src1 mem_src1 f1 flag_tgt1,\n      (<<STEPS: rtc (tau (@pred_step is_promise _))\n                    (Thread.mk lang st lc_src0 sc_src mem_src0)\n                    (Thread.mk _ st lc_src1 sc_src mem_src1)>>) /\\\n      (<<SIM: sim_thread\n                f1 vers\n                (fun _ => false)\n                flag_tgt1\n                vs_src vs_tgt\n                mem_src1 mem_tgt lc_src1 lc_tgt sc_src sc_tgt>>) /\\\n      (<<WF: Mapping.wfs f1>>) /\\\n      (<<MAPLE: Mapping.les f0 f1>>) /\\\n      (<<FLAG: forall loc, (<<DEBT: D loc>>) \\/ (<<FLAG: flag_tgt1 loc = false>>)>>) /\\\n      (<<UNCH: forall loc (NIN: ~ List.In loc dom), f1 loc = f0 loc>>) /\\\n      (<<MAPFUTURE: map_future_memory f0 f1 mem_src1>>) /\\\n      (<<SPACE: space_future_memory (unchangable mem_tgt lc_tgt.(Local.promises)) f0 mem_src0 f1 mem_src1>>)\n.\nProof.\n  induction dom.\n  { i. assert (FLAG: flag_src = fun _ => false).\n    { extensionality loc. destruct (flag_src loc) eqn:FLAG; auto.\n      hexploit (FIN loc); eauto. ss.\n    }\n    subst. esplits.\n    { refl. }\n    { eauto. }\n    { auto. }\n    { refl. }\n    { i. hexploit DEBT; eauto. i. des; eauto. }\n    { ss. }\n    { eapply map_future_memory_refl. }\n    { eapply space_future_memory_refl; eauto. refl. }\n  }\n  i.\n  cut (exists lc_src1 mem_src1 f1 flag,\n          (<<STEPS: rtc (tau (@pred_step is_promise _))\n                        (Thread.mk lang st lc_src0 sc_src mem_src0)\n                        (Thread.mk _ st lc_src1 sc_src mem_src1)>>) /\\\n          (<<SIM: sim_thread\n                    f1 vers\n                    (fun loc0 => if Loc.eq_dec loc0 a then false else flag_src loc0)\n                    (fun loc0 => if Loc.eq_dec loc0 a then flag else flag_tgt0 loc0)\n                    vs_src vs_tgt\n                    mem_src1 mem_tgt lc_src1 lc_tgt sc_src sc_tgt>>) /\\\n          (<<WF: Mapping.wfs f1>>) /\\\n          (<<MAPLE: Mapping.les f0 f1>>) /\\\n          (<<FLAG: __guard__(flag = false \\/ D a)>>) /\\\n          (<<UNCH: forall loc (NEQ: loc <> a), f1 loc = f0 loc>>) /\\\n          (<<MAPFUTURE: map_future_memory f0 f1 mem_src1>>) /\\\n          (<<SPACE: space_future_memory (unchangable mem_tgt lc_tgt.(Local.promises)) f0 mem_src0 f1 mem_src1>>) /\\\n          (<<VERSWF: versions_wf f1 vers>>)\n      ).\n  { i. des.\n    hexploit Thread.rtc_tau_step_future.\n    { eapply rtc_implies; [|eapply STEPS]. i.\n      inv H. inv TSTEP. econs; eauto.\n    }\n    { eauto. }\n    { eauto. }\n    { eauto. }\n    i. ss. des.\n    hexploit IHdom; eauto.\n    { instantiate (1:=D). i. destruct (classic (D loc)); auto.\n      hexploit (DEBT loc). intros [|]; ss.\n      right. des_ifs. splits; auto.\n      i. red in FLAG. des; ss.\n    }\n    { i. ss. des_ifs.\n      eapply FIN in FLAG0. des; ss. intuition.\n    }\n    i. des. esplits.\n    { etrans; eauto. }\n    { eauto. }\n    { eauto. }\n    { etrans; eauto. }\n    { auto. }\n    { i. rewrite UNCH0; auto. }\n    { eapply map_future_memory_trans; eauto.\n      hexploit Thread.rtc_tau_step_future.\n      { eapply rtc_implies; [|eapply STEPS0].\n        i. inv H. econs; eauto. inv TSTEP. auto.\n      }\n      { eauto. }\n      { eauto. }\n      { eauto. }\n      i. ss. des. eapply Memory.future_future_weak; eauto.\n    }\n    { eapply space_future_memory_trans; eauto. }\n  }\n  hexploit (DEBT a). intros [|[]].\n  { hexploit sim_thread_deflag_unmatch; eauto. i. des.\n    esplits; eauto.\n    { right. eauto. }\n    { eapply versions_wf_mapping_mon; eauto. }\n  }\n  { guardH H0. hexploit sim_thread_deflag_match; eauto. i. des.\n    esplits; eauto.\n    { left. eauto. }\n    { eapply versions_wf_mapping_mon; eauto. }\n  }\nQed.\n\nLemma sim_thread_deflag_all\n      (D: Loc.t -> Prop)\n      f0 vers flag_src flag_tgt0 vs_src vs_tgt\n      mem_src0 mem_tgt lc_src0 lc_tgt sc_src sc_tgt\n      (SIM: sim_thread\n              f0 vers flag_src flag_tgt0 vs_src vs_tgt\n              mem_src0 mem_tgt lc_src0 lc_tgt sc_src sc_tgt)\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n      (LOCALSRC: Local.wf lc_src0 mem_src0)\n      (LOCALTGT: Local.wf lc_tgt mem_tgt)\n      (MEMSRC: Memory.closed mem_src0)\n      (MEMTGT: Memory.closed mem_tgt)\n      (SCSRC: Memory.closed_timemap sc_src mem_src0)\n      (SCTGT: Memory.closed_timemap sc_tgt mem_tgt)\n      (WF: Mapping.wfs f0)\n      (VERSWF: versions_wf f0 vers)\n      (DEBT: forall loc, (<<DEBT: D loc>>) \\/\n                         ((<<FLAG: flag_src loc = false -> flag_tgt0 loc = false>>) /\\\n                          (<<VAL: option_rel Const.le (vs_tgt loc) (vs_src loc) \\/ flag_src loc = false>>)))\n      lang st\n  :\n    exists lc_src1 mem_src1 f1 flag_tgt1,\n      (<<STEPS: rtc (tau (@pred_step is_promise _))\n                    (Thread.mk lang st lc_src0 sc_src mem_src0)\n                    (Thread.mk _ st lc_src1 sc_src mem_src1)>>) /\\\n      (<<SIM: sim_thread\n                f1 vers\n                (fun _ => false)\n                flag_tgt1\n                vs_src vs_tgt\n                mem_src1 mem_tgt lc_src1 lc_tgt sc_src sc_tgt>>) /\\\n      (<<WF: Mapping.wfs f1>>) /\\\n      (<<MAPLE: Mapping.les f0 f1>>) /\\\n      (<<FLAG: forall loc, (<<DEBT: D loc>>) \\/ (<<FLAG: flag_tgt1 loc = false>>)>>) /\\\n      (<<UNCH: forall loc (FLAG: flag_src loc = false), f1 loc = f0 loc>>) /\\\n      (<<MAPFUTURE: map_future_memory f0 f1 mem_src1>>) /\\\n      (<<SPACE: space_future_memory (unchangable mem_tgt lc_tgt.(Local.promises)) f0 mem_src0 f1 mem_src1>>)\n.\nProof.\n  dup SIM. inv SIM. red in FIN. des.\n  hexploit (@sim_thread_deflag_all_aux dom); eauto.\n  { i. eapply DOM. eauto. }\n  i. des. esplits; eauto.\n  { i. eapply UNCH. ii. eapply DOM in H. des. clarify. }\nQed.\n\nLemma local_write_fence_step_promise_step\n      lc0 ordw lc1\n      mem0 loc from to msg lc2 mem1 kind sc0 sc1\n      (PROMISE: Local.promise_step lc0 mem0 loc from to msg lc1 mem1 kind)\n      (FENCE: local_fence_write_step lc1 sc0 ordw lc2 sc1)\n  :\n    exists lc1',\n      (<<FENCE: local_fence_write_step lc0 sc0 ordw lc1' sc1>>) /\\\n      (<<PROMISE: Local.promise_step lc1' mem0 loc from to msg lc2 mem1 kind>>).\nProof.\n  inv FENCE. inv PROMISE. ss. esplits.\n  { econs; eauto. }\n  { econs; eauto; ss. }\nQed.\n\nLemma local_write_fence_step_promise_steps\n      lc0 sc0 ordw lc1\n      mem0 lc2 mem1 sc1\n      lang st\n      (STEPS: rtc (tau (@pred_step is_promise _))\n                  (Thread.mk lang st lc0 sc0 mem0)\n                  (Thread.mk _ st lc1 sc0 mem1))\n      (FENCE: local_fence_write_step lc1 sc0 ordw lc2 sc1)\n  :\n    exists lc1',\n      (<<FENCE: local_fence_write_step lc0 sc0 ordw lc1' sc1>>) /\\\n      (<<STEPS: rtc (tau (@pred_step is_promise _))\n                    (Thread.mk lang st lc1' sc1 mem0)\n                    (Thread.mk _ st lc2 sc1 mem1)>>).\nProof.\n  remember (Thread.mk lang st lc0 sc0 mem0).\n  remember (Thread.mk lang st lc1 sc0 mem1).\n  revert lc0 st lc1 lc2 sc0 sc1 mem0 mem1 Heqt Heqt0 FENCE.\n  induction STEPS; i; clarify.\n  { esplits.\n    { eauto. }\n    { refl. }\n  }\n  { inv H. inv TSTEP. inv STEP.\n    inv STEP0; [inv STEP|inv STEP; inv LOCAL; ss].\n    hexploit IHSTEPS; eauto. i. des.\n    hexploit local_write_fence_step_promise_step; eauto. i. des.\n    esplits; [eauto|]. etrans.\n    { eauto. }\n    { econs; eauto. econs; eauto. econs; eauto.\n      econs; eauto. econs; eauto. econs; eauto.\n    }\n  }\nQed.\n\nLemma promise_step_local_read_step lc0 lc1 lc2 mem0 mem1\n      loc0 loc1 ts val released ord from to msg kind\n      (READ: Local.read_step lc0 mem0 loc0 ts val released ord lc1)\n      (PROMISE: Local.promise_step lc1 mem0 loc1 from to msg lc2 mem1 kind)\n      (CONS: Local.promise_consistent lc2)\n  :\n    exists lc1',\n      (<<PROMISE: Local.promise_step lc0 mem0 loc1 from to msg lc1' mem1 kind>>) /\\\n      (<<READ: Local.read_step lc1' mem1 loc0 ts val released ord lc2>>).\nProof.\n  inv READ. inv PROMISE. esplits.\n  { econs; eauto. }\n  { ss. cut (exists from1, Memory.get loc0 ts mem1 = Some (from1, Message.concrete val' released)).\n    { i. des. econs; eauto. }\n    inv PROMISE0.\n    { esplits. eapply Memory.add_get1; eauto. }\n    { eapply Memory.split_get1 in MEM; eauto. des. eauto. }\n    { erewrite Memory.lower_o; eauto. des_ifs; eauto.\n      exfalso. ss. des; clarify. exploit CONS; eauto.\n      { eapply Memory.lower_get0; eauto. }\n      intros x. ss. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt; [eapply x|].\n      clear x. etrans; [|eapply Time.join_l]. etrans; [|eapply Time.join_r].\n      unfold View.singleton_ur_if. des_ifs; ss.\n      { rewrite timemap_singleton_eq. refl. }\n      { rewrite timemap_singleton_eq. refl. }\n    }\n    { erewrite Memory.remove_o; eauto. des_ifs; eauto.\n      ss. des; clarify. eapply Memory.remove_get0 in MEM. des; clarify.\n    }\n  }\nQed.\n\nLemma rtc_promise_step_promise_consistent\n      lang th1 th2\n      (STEPS: rtc (tau (@pred_step is_promise 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 TSTEP. inv STEP. inv STEP0; [inv STEP|inv STEP; inv LOCAL; ss].\n  eapply PromiseConsistent.promise_step_promise_consistent; eauto.\nQed.\n\nLemma promise_steps_local_read_step lc0 lc1 lc2 mem0 mem1\n      loc ts val released ord\n      lang st0 st1 sc0 sc1\n      (READ: Local.read_step lc0 mem0 loc ts val released ord lc1)\n      (STEPS: rtc (tau (@pred_step is_promise _))\n                  (Thread.mk lang st0 lc1 sc0 mem0)\n                  (Thread.mk _ st1 lc2 sc1 mem1))\n      (CONS: Local.promise_consistent lc2)\n  :\n    exists lc1',\n      (<<STEPS: rtc (tau (@pred_step is_promise _))\n                    (Thread.mk lang st0 lc0 sc0 mem0)\n                    (Thread.mk _ st1 lc1' sc1 mem1)>>) /\\\n      (<<READ: Local.read_step lc1' mem1 loc ts val released ord lc2>>)\n.\nProof.\n  remember (Thread.mk lang st0 lc1 sc0 mem0).\n  remember (Thread.mk lang st1 lc2 sc1 mem1).\n  revert lc0 st0 st1 lc1 lc2 sc0 sc1 mem0 mem1 Heqt Heqt0 READ CONS.\n  induction STEPS; i; clarify.\n  { esplits.\n    { refl. }\n    { eauto. }\n  }\n  { inv H. inv TSTEP. inv STEP.\n    inv STEP0; [inv STEP|inv STEP; inv LOCAL; ss].\n    hexploit promise_step_local_read_step; eauto.\n    { eapply rtc_promise_step_promise_consistent in STEPS; eauto. }\n    i. des. hexploit IHSTEPS; eauto.\n    i. des. esplits; [|eauto].\n    econs 2; [|eauto]. econs; eauto. econs; eauto.\n    econs; eauto. econs; eauto. econs; eauto.\n  }\nQed.\n\nLemma sim_thread_write_fence_step\n      f vers flag_src flag_tgt vs_src0 vs_tgt0\n      mem_src mem_tgt lc_src0 lc_tgt0 sc_src0 sc_tgt0 sc_tgt1\n      lc_tgt1 ordw\n      (SIM: sim_thread\n              f vers flag_src flag_tgt vs_src0 vs_tgt0\n              mem_src mem_tgt lc_src0 lc_tgt0 sc_src0 sc_tgt0)\n      (WRITE: local_fence_write_step lc_tgt0 sc_tgt0 ordw lc_tgt1 sc_tgt1)\n      (CONSISTENT: Local.promise_consistent lc_tgt1)\n      (LOCALSRC: Local.wf lc_src0 mem_src)\n      (LOCALTGT: Local.wf lc_tgt0 mem_tgt)\n      (MEMSRC: Memory.closed mem_src)\n      (MEMTGT: Memory.closed mem_tgt)\n      (SCSRC: Memory.closed_timemap sc_src0 mem_src)\n      (SCTGT: Memory.closed_timemap sc_tgt0 mem_tgt)\n      (WF: Mapping.wfs f)\n      (VERS: versions_wf f vers)\n      (RELFLAG: forall loc (ORD: Ordering.le Ordering.acqrel ordw), flag_src loc = false)\n      (SYNC: forall (ORD: Ordering.le Ordering.acqrel ordw), Memory.nonsynch lc_tgt0.(Local.promises))\n  :\n    exists lc_src1 sc_src1,\n      (<<READ: local_fence_write_step lc_src0 sc_src0 ordw lc_src1 sc_src1>>) /\\\n      (<<SIM: sim_thread\n                f vers flag_src flag_tgt vs_src0 vs_tgt0\n                mem_src mem_tgt lc_src1 lc_tgt1 sc_src1 sc_tgt1>>)\n.\nProof.\n  assert (exists lc_src1 sc_src1, (<<WRITE: local_fence_write_step lc_src0 sc_src0 ordw lc_src1 sc_src1>>)).\n  { esplits. econs; eauto. }\n  des. hexploit local_fence_write_step_future; [eapply WRITE|..]; eauto. i. des.\n  hexploit local_fence_write_step_future; [eapply WRITE0|..]; eauto. i. des.\n  destruct lc_src0 as [tvw_src0 prom_src].\n  destruct lc_tgt0 as [tvw_tgt0 prom_tgt].\n  inv WRITE. inv WRITE0. ss.\n  dup SIM. inv SIM. inv LOCAL1.\n  esplits; eauto.\n  { econs; eauto. }\n  { econs; eauto; ss.\n    { eapply sim_local_write_fence_sc; eauto. i. eapply RELFLAG. destruct ordw; ss. }\n    { destruct (Ordering.le Ordering.acqrel ordw) eqn:ORD.\n      { econs.\n        { eapply sim_local_write_fence_tview_release; eauto. }\n        { eauto. }\n        { econs. i. inv RELVERS. hexploit PROM; eauto. i. des.\n          esplits; eauto. i. eapply SYNC in GET; eauto. subst. ss.\n        }\n        { eauto. }\n        { eauto. }\n      }\n      { econs; eauto. eapply sim_local_write_fence_tview_normal; eauto.\n        rewrite ORD. auto.\n      }\n    }\n    { ii. hexploit (MAXSRC loc). i. inv H. econs; eauto. }\n    { ii. hexploit (MAXTGT loc). i. inv H. econs; eauto. }\n  }\nQed.\n\nLemma local_fence_read_step_promise_consistent\n      lc0 sc ordr ordw lc1\n      (READ: local_fence_read_step lc0 sc ordr ordw lc1)\n      (CONS: Local.promise_consistent lc1)\n      (LOCAL: TView.wf (Local.tview lc0))\n  :\n    Local.promise_consistent lc0.\nProof.\n  inv READ. ii. eapply TimeFacts.le_lt_lt.\n  { eapply local_read_fence_tview_incr. eauto. }\n  eapply CONS; eauto.\nQed.\n\nLemma local_fence_write_step_promise_consistent\n      lc0 sc0 ordw lc1 sc1\n      (WRITE: local_fence_write_step lc0 sc0 ordw lc1 sc1)\n      (CONS: Local.promise_consistent lc1)\n      (LOCAL: TView.wf (Local.tview lc0))\n  :\n    Local.promise_consistent lc0.\nProof.\n  inv WRITE. ii. eapply TimeFacts.le_lt_lt.\n  { eapply local_write_fence_tview_incr. eauto. }\n  eapply CONS; eauto.\nQed.\n\nLemma sim_thread_fence_step_normal\n      f vers flag_src flag_tgt vs_src0 vs_tgt0\n      mem_src mem_tgt lc_src0 lc_tgt0 sc_src0 sc_tgt0 sc_tgt1\n      lc_tgt1 ordr ordw\n      (SIM: sim_thread\n              f vers flag_src flag_tgt vs_src0 vs_tgt0\n              mem_src mem_tgt lc_src0 lc_tgt0 sc_src0 sc_tgt0)\n      (WRITE: Local.fence_step lc_tgt0 sc_tgt0 ordr ordw lc_tgt1 sc_tgt1)\n      (CONSISTENT: Local.promise_consistent lc_tgt1)\n      (LOCALSRC: Local.wf lc_src0 mem_src)\n      (LOCALTGT: Local.wf lc_tgt0 mem_tgt)\n      (MEMSRC: Memory.closed mem_src)\n      (MEMTGT: Memory.closed mem_tgt)\n      (SCSRC: Memory.closed_timemap sc_src0 mem_src)\n      (SCTGT: Memory.closed_timemap sc_tgt0 mem_tgt)\n      (WF: Mapping.wfs f)\n      (VERS: versions_wf f vers)\n      (ACQFLAG: forall loc\n                       (SRC: flag_src loc = false) (TGT: flag_tgt loc = true),\n          ~ Ordering.le Ordering.acqrel ordr)\n      (ORD: ~ Ordering.le Ordering.acqrel ordw)\n  :\n    exists lc_src1 sc_src1 vs_src1 vs_tgt1,\n      (<<READ: Local.fence_step lc_src0 sc_src0 ordr ordw lc_src1 sc_src1>>) /\\\n      (<<SIM: sim_thread\n                f vers flag_src flag_tgt vs_src1 vs_tgt1\n                mem_src mem_tgt lc_src1 lc_tgt1 sc_src1 sc_tgt1>>) /\\\n      (<<VALS: forall loc0,\n          ((<<SRC: vs_src1 loc0 = vs_src0 loc0>>) /\\ (<<TGT: vs_tgt1 loc0 = vs_tgt0 loc0>>)) \\/\n          (exists val_src val_tgt,\n              (<<NONESRC: vs_src0 loc0 = None>>) /\\ (<<NONETGT: vs_tgt0 loc0 = None>>) /\\\n              (<<VALSRC: vs_src1 loc0 = Some val_src>>) /\\ (<<VALTGT: vs_tgt1 loc0 = Some val_tgt>>) /\\\n              (<<VALLE: Const.le val_tgt val_src>>) /\\\n              (<<ORD: Ordering.le Ordering.acqrel ordr \\/ Ordering.le Ordering.seqcst ordw>>))>>).\nProof.\n  hexploit local_fence_step_split; eauto.\n  { eapply LOCALTGT. }\n  i. des.\n  hexploit local_fence_read_step_future; eauto. i. des.\n  hexploit sim_thread_read_fence_step; eauto.\n  { eapply local_fence_write_step_promise_consistent; eauto. eapply LOCAL. }\n  { i. destruct ordw; ss. }\n  i. des.\n  hexploit local_fence_read_step_future; eauto. i. des.\n  hexploit sim_thread_write_fence_step; eauto.\n  { i. destruct ordw; ss. }\n  { i. destruct ordw; ss. }\n  i. des. esplits; eauto.\n  { eapply local_fence_step_merge; eauto. eapply LOCALSRC. }\nQed.\n\nLemma sim_thread_fence_step_release\n      f0 vers flag_src flag_tgt vs_src0 vs_tgt0\n      mem_src mem_tgt lc_src0 lc_tgt0 sc_src0 sc_tgt0 sc_tgt1\n      lc_tgt1 ordr ordw D\n      (SIM: sim_thread\n              f0 vers flag_src flag_tgt vs_src0 vs_tgt0\n              mem_src mem_tgt lc_src0 lc_tgt0 sc_src0 sc_tgt0)\n      (WRITE: Local.fence_step lc_tgt0 sc_tgt0 ordr ordw lc_tgt1 sc_tgt1)\n      (CONSISTENT: Local.promise_consistent lc_tgt1)\n      (LOCALSRC: Local.wf lc_src0 mem_src)\n      (LOCALTGT: Local.wf lc_tgt0 mem_tgt)\n      (MEMSRC: Memory.closed mem_src)\n      (MEMTGT: Memory.closed mem_tgt)\n      (SCSRC: Memory.closed_timemap sc_src0 mem_src)\n      (SCTGT: Memory.closed_timemap sc_tgt0 mem_tgt)\n      (WF: Mapping.wfs f0)\n      (VERS: versions_wf f0 vers)\n      (ACQFLAG: forall loc\n                       (SRC: flag_src loc = false) (TGT: flag_tgt loc = true),\n          ~ Ordering.le Ordering.acqrel ordr)\n      (RELFLAG: forall loc\n                       (SRC: flag_src loc = false) (TGT: flag_tgt loc = true),\n          ~ Ordering.le Ordering.seqcst ordw)\n      (DEBT: forall loc, (<<DEBT: D loc>>) \\/\n                         ((<<FLAG: flag_src loc = false -> flag_tgt loc = false>>) /\\\n                          (<<VAL: option_rel Const.le (vs_tgt0 loc) (vs_src0 loc) \\/ flag_src loc = false>>)))\n      lang st\n  :\n    exists lc_src1 lc_src2 sc_src1 vs_src1 vs_tgt1 f1 flag_tgt1 mem_src1,\n      (<<READ: Local.fence_step lc_src0 sc_src0 ordr ordw lc_src1 sc_src1>>) /\\\n      (<<STEPS: rtc (tau (@pred_step is_promise _))\n                    (Thread.mk lang st lc_src1 sc_src1 mem_src)\n                    (Thread.mk _ st lc_src2 sc_src1 mem_src1)>>) /\\\n      (<<SIM: sim_thread\n                f1 vers (fun _ => false) flag_tgt1 vs_src1 vs_tgt1\n                mem_src1 mem_tgt lc_src2 lc_tgt1 sc_src1 sc_tgt1>>) /\\\n      (<<VALS: forall loc0,\n          ((<<SRC: vs_src1 loc0 = vs_src0 loc0>>) /\\ (<<TGT: vs_tgt1 loc0 = vs_tgt0 loc0>>)) \\/\n          (exists val_src val_tgt,\n              (<<NONESRC: vs_src0 loc0 = None>>) /\\ (<<NONETGT: vs_tgt0 loc0 = None>>) /\\\n              (<<VALSRC: vs_src1 loc0 = Some val_src>>) /\\ (<<VALTGT: vs_tgt1 loc0 = Some val_tgt>>) /\\\n              (<<VALLE: Const.le val_tgt val_src>>) /\\\n              (<<ORD: Ordering.le Ordering.acqrel ordr \\/ Ordering.le Ordering.seqcst ordw>>))>>) /\\\n      (<<WF: Mapping.wfs f1>>) /\\\n      (<<MAPLE: Mapping.les f0 f1>>) /\\\n      (<<VERSWF: versions_wf f1 vers>>) /\\\n      (<<FLAG: forall loc, (<<DEBT: D loc>>) \\/ (<<FLAG: flag_tgt1 loc = false>>)>>) /\\\n      (<<MAPFUTURE: map_future_memory f0 f1 mem_src1>>) /\\\n      (<<SPACE: space_future_memory (unchangable mem_tgt lc_tgt0.(Local.promises)) f0 mem_src f1 mem_src1>>)\n.\nProof.\n  hexploit local_fence_step_split; eauto.\n  { eapply LOCALTGT. }\n  i. des.\n  hexploit local_fence_read_step_future; eauto. i. des.\n  hexploit sim_thread_read_fence_step; eauto.\n  { eapply local_fence_write_step_promise_consistent; eauto. eapply LOCAL. }\n  i. des.\n  hexploit local_fence_read_step_future; eauto. i. des.\n  hexploit sim_thread_deflag_all; eauto.\n  { eapply local_fence_write_step_promise_consistent; eauto. eapply LOCAL. }\n  { i. hexploit (DEBT loc). i. des; eauto. right. esplits; eauto.\n    hexploit (VALS loc). i. des.\n    { rewrite SRC. rewrite TGT. auto. }\n    { left. rewrite VALTGT. rewrite VALSRC. ss. }\n    { left. rewrite VALTGT. rewrite VALSRC. ss. }\n  }\n  i. des. hexploit Thread.rtc_tau_step_future.\n  { eapply rtc_implies; [|eauto]. i. inv H. inv TSTEP. econs; eauto. }\n  { eauto. }\n  { eauto. }\n  { eauto. }\n  i. des.\n  hexploit sim_thread_write_fence_step; eauto.\n  { eapply versions_wf_mapping_mon; eauto. }\n  { i. inv STEP0. ss. eapply RELEASE. destruct ordw; ss. }\n  i. des. hexploit local_write_fence_step_promise_steps; eauto. i. des.\n  esplits.\n  { eapply local_fence_step_merge; eauto. eapply LOCALSRC. }\n  { eauto. }\n  { eauto. }\n  { i. hexploit (VALS loc0). i. des; eauto. }\n  { eauto. }\n  { eauto. }\n  { eapply versions_wf_mapping_mon; eauto. }\n  { eauto. }\n  { eauto. }\n  { inv STEP0. eauto. }\nQed.\n\nLemma write_max_readable_none\n      lc0 sc0 mem0 loc from to val releasedm released ord lc1 sc1 mem1 kind\n      val0 released0\n      (WRITE: Local.write_step lc0 sc0 mem0 loc from to val releasedm released ord lc1 sc1 mem1 kind)\n      (WF: Local.wf lc0 mem0)\n      (MAX: max_readable mem0 lc0.(Local.promises) loc (lc0.(Local.tview).(TView.cur).(View.pln) loc) val0 released0)\n  :\n  max_readable mem1 lc1.(Local.promises) loc (lc1.(Local.tview).(TView.cur).(View.pln) loc) val released.\nProof.\n  hexploit local_write_step_timestamp; eauto. i.\n  destruct lc0, lc1. ss; clarify.\n  inv WRITE. hexploit Memory.write_get2; eauto. i. des. clarify.\n  inv MAX. econs; eauto. i.\n  destruct (Memory.get loc ts' promises2) eqn:EQ.\n  { destruct p. eapply write_promises_le in WRITE0; eauto.\n    { eapply WRITE0 in EQ. clarify. }\n    { eapply WF. }\n  }\n  ss. exfalso.\n  assert (exists from', Memory.get loc ts' mem0 = Some (from', msg)).\n  { inv WRITE0. eapply MemoryFacts.promise_get_inv_diff in GET0; eauto.\n    ii. clarify. timetac.\n  }\n  des. hexploit MAX0; eauto.\n  { eapply TimeFacts.le_lt_lt; eauto. rewrite H1. ss. eapply Time.join_l. }\n  i. inv WRITE0. erewrite Memory.remove_o in EQ; eauto. des_ifs.\n  { ss. des; clarify. timetac. }\n  ss. des; auto. inv PROMISE.\n  { erewrite Memory.add_o in EQ; eauto. des_ifs. }\n  { erewrite Memory.split_o in EQ; eauto. des_ifs. }\n  { erewrite Memory.lower_o in EQ; eauto. des_ifs. }\n  { ss. }\nQed.\n\nLemma writable_message_to tvw sc loc from to releasedm ord\n      (WRITABLE: TView.writable (TView.cur tvw) sc loc to ord)\n      (WF: TView.wf tvw)\n      (TS: Time.lt from to)\n      (MSG: Time.le (View.rlx (View.unwrap releasedm) loc) from)\n  :\n  Time.le (View.rlx (View.unwrap (TView.write_released tvw sc loc to releasedm ord)) loc) to.\nProof.\n  assert (TIME: Time.le (View.rlx (View.unwrap releasedm) loc) to).\n  { etrans; eauto. left. auto. }\n  unfold TView.write_released. ss. des_ifs; ss.\n  { eapply Time.join_spec; auto.\n    setoid_rewrite LocFun.add_spec_eq.\n    eapply Time.join_spec; auto; ss.\n    { left. eapply WRITABLE. }\n    { rewrite timemap_singleton_eq. refl. }\n  }\n  { eapply Time.join_spec; auto.\n    setoid_rewrite LocFun.add_spec_eq.\n    eapply Time.join_spec; auto; ss.\n    { etrans.\n      { eapply WF. }\n      { left. eapply WRITABLE. }\n    }\n    { rewrite timemap_singleton_eq. refl. }\n  }\n  { eapply Time.bot_spec. }\nQed.\n\nLemma sim_thread_write_aux\n      f0 vers0 flag_src flag_tgt vs_src0 vs_tgt0\n      mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0\n      val_tgt val_src releasedm_tgt releasedm_src\n      lc_tgt1 mem_tgt1 loc from_tgt to_tgt to_src from_src\n      released_tgt ord sc_tgt1 kind_tgt\n      (SIM: sim_thread\n              f0 vers0 flag_src flag_tgt vs_src0 vs_tgt0\n              mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0)\n      (WRITE: Local.write_step lc_tgt0 sc_tgt0 mem_tgt0 loc from_tgt to_tgt val_tgt releasedm_tgt released_tgt ord lc_tgt1 sc_tgt1 mem_tgt1 kind_tgt)\n      (RELEASEDM: sim_opt_view (fun loc0 => loc0 <> loc) f0 (vers0 loc from_tgt) releasedm_src releasedm_tgt)\n      (MSGTOSRC: Time.le (View.rlx (View.unwrap releasedm_src) loc) from_src)\n      (TO: sim_timestamp_exact (f0 loc) (f0 loc).(Mapping.ver) to_src to_tgt)\n      (FROM: sim_timestamp_exact (f0 loc) (f0 loc).(Mapping.ver) from_src from_tgt)\n      (CONSISTENT: Local.promise_consistent lc_tgt1)\n      (LOCALSRC: Local.wf lc_src0 mem_src0)\n      (LOCALTGT: Local.wf lc_tgt0 mem_tgt0)\n      (MEMSRC: Memory.closed mem_src0)\n      (MEMTGT: Memory.closed mem_tgt0)\n      (SCSRC: Memory.closed_timemap sc_src0 mem_src0)\n      (SCTGT: Memory.closed_timemap sc_tgt0 mem_tgt0)\n      (WF: Mapping.wfs f0)\n      (VERS: versions_wf f0 vers0)\n      (FLAGSRC: flag_src loc = false)\n      (FLAGTGT: flag_tgt loc = false)\n      (VAL: Const.le val_tgt val_src)\n      (ORD: ~ Ordering.le Ordering.strong_relaxed ord)\n      (WFSRC: View.opt_wf releasedm_src)\n      (WFTGT: View.opt_wf releasedm_tgt)\n      (CLOSEDMSRC: Memory.closed_opt_view releasedm_src mem_src0)\n      (CLOSEDMTGT: Memory.closed_opt_view releasedm_tgt mem_tgt0)\n  :\n  exists f1 vers1 released_src lc_src1 vs_src1 vs_tgt1 mem_src1 sc_src1 kind_src,\n    (<<WRITE: Local.write_step lc_src0 sc_src0 mem_src0 loc from_src to_src val_src releasedm_src released_src ord lc_src1 sc_src1 mem_src1 kind_src>>) /\\\n      (<<SIM: sim_thread\n                f1 vers1 flag_src flag_tgt vs_src1 vs_tgt1\n                mem_src1 mem_tgt1 lc_src1 lc_tgt1 sc_src1 sc_tgt1>>) /\\\n      (<<WF: Mapping.wfs f1>>) /\\\n      (<<MAPLE: Mapping.les_strong f0 f1>>) /\\\n      (<<VERSLE: versions_le vers0 vers1>>) /\\\n      (<<VERSWF: versions_wf f1 vers1>>) /\\\n      (<<VALS: forall loc0,\n          ((<<SRC: vs_src1 loc0 = vs_src0 loc0>>) /\\ (<<TGT: vs_tgt1 loc0 = vs_tgt0 loc0>>) /\\ (<<LOC: loc0 <> loc>>)) \\/\n            ((<<LOC: loc0 = loc>>) /\\\n               ((<<VALSRC: vs_src1 loc0 = Some val_src>> /\\ <<VALTGT: vs_tgt1 loc0 = Some val_tgt>>) \\/\n                  (<<VALSRC0: vs_src0 loc0 = None>> /\\ <<VALTGT0: vs_tgt0 loc0 = None>> /\\ <<VALSRC1: vs_src1 loc0 = None>> /\\ <<VALTGT1: vs_tgt1 loc0 = None>>)))>>) /\\\n      (<<SPACE: space_future_memory (unchangable mem_tgt0 lc_tgt0.(Local.promises)) f0 mem_src0 f1 mem_src1>>).\nProof.\n  hexploit Local.write_step_future; eauto. i. des.\n  destruct lc_src0 as [tvw_src0 prom_src].\n  destruct lc_tgt0 as [tvw_tgt0 prom_tgt].\n  dup SIM. inv SIM. inv LOCAL. dup WRITE. guardH WRITE. inv WRITE. ss.\n  set (msg_src := Message.concrete val_tgt (TView.write_released tvw_tgt0 sc_tgt0 loc to_tgt releasedm_tgt ord)).\n  assert (SIMMSG: sim_message (flag_tgt loc) loc f0 (opt_version_join (vers0 loc from_tgt) (Some (rel_vers loc)))\n                              (Message.concrete val_src (TView.write_released tvw_src0 sc_src0 loc to_src releasedm_src ord))\n                              (Message.concrete val_tgt (TView.write_released tvw_tgt0 sc_tgt0 loc to_tgt releasedm_tgt ord))).\n  { clear WRITE0.\n    replace (opt_version_join (vers0 loc from_tgt) (Some (rel_vers loc))) with\n      (Some (match (vers0 loc from_tgt) with\n             | Some v => version_join v (rel_vers loc)\n             | None => (rel_vers loc)\n             end)).\n    { rewrite FLAGTGT. econs; auto.\n      assert (VERWF: version_wf f0 match vers0 loc from_tgt with\n                                   | Some v => version_join v (rel_vers loc)\n                                   | None => rel_vers loc\n                                   end).\n      { des_ifs; ss.\n        { eapply version_wf_join; eauto.\n          { exploit VERS. rewrite Heq. ss. }\n          { inv TVIEW. auto. }\n        }\n        { inv TVIEW. auto. }\n      }\n      eapply sim_write_released_normal; eauto.\n      { eapply sim_opt_view_mon_ver; eauto.\n        { des_ifs. ss. eapply version_join_l. }\n      }\n      { destruct ord; ss. }\n      { i. ss. des_ifs. eapply version_join_r; eauto. }\n    }\n    { destruct (vers0 loc from_tgt); auto. }\n  }\n  assert (WRITABLE0: TView.writable (TView.cur tvw_src0) sc_src0 loc to_src ord).\n  { eapply sim_writable; eauto.\n    { inv TVIEW. eauto. }\n    { ss. }\n  }\n  hexploit sim_memory_write; eauto.\n  { eapply LOCALSRC. }\n  { inv TVIEW. eauto. }\n  { econs. eapply TViewFacts.write_future0; eauto. eapply LOCALSRC. }\n  { econs; ss. eapply writable_message_to; eauto.\n    { eapply LOCALSRC. }\n    { eapply sim_timestamp_exact_lt; eauto.\n      { eapply MemoryFacts.write_time_lt; eauto. }\n      { eapply mapping_latest_wf_loc. }\n    }\n  }\n  { red. eauto. }\n  i. des.\n  assert (from_src0 = from_src).\n  { eapply sim_timestamp_exact_inject; eauto.\n    eapply sim_timestamp_exact_mon_strong; eauto.\n  }\n  subst.\n  set (tvw_src1 := TView.write_tview tvw_src0 sc_src0 loc to_src ord).\n  set (tvw_tgt1 := TView.write_tview tvw_tgt0 sc_tgt0 loc to_tgt ord).\n  assert (exists released_src,\n             (<<WRITE: Local.write_step (Local.mk tvw_src0 prom_src) sc_src0 mem_src0 loc from_src\n                                        to_src val_src releasedm_src released_src ord (Local.mk tvw_src1 prom_src1) sc_src0 mem_src1 kind_src>>) /\\\n               (<<LOCAL: sim_local f1 vers1 tvw_src1.(TView.cur).(View.rlx) flag_src flag_tgt (Local.mk tvw_src1 prom_src1) (Local.mk (TView.write_tview tvw_tgt0 sc_tgt0 loc to_tgt ord) promises2)>>)).\n  { esplits.\n    { econs; eauto. ss. }\n    { ss. econs.\n      { eapply sim_write_tview_normal; eauto.\n        { eapply sim_tview_mon_latest; eauto. eapply Mapping.les_strong_les; eauto. }\n        { eapply sim_timestamp_exact_mon_strong; eauto. }\n        { destruct ord; ss. }\n      }\n      { eapply sim_promises_change_no_flag; eauto. i. rewrite SRCTM.\n        unfold TimeMap.join. rewrite TimeFacts.le_join_l; auto.\n        rewrite timemap_singleton_neq; auto.\n        { eapply Time.bot_spec. }\n        { ii. subst. rewrite FLAG in *. ss. }\n      }\n      { eauto. }\n      { i. ss. unfold TimeMap.join. rewrite FLAGSRC0; ss. }\n      { ss. }\n    }\n  }\n  des.\n  hexploit max_value_src_exists. i. des.\n  set (vs_src1 := fun loc0 => if Loc.eq_dec loc0 loc then v else vs_src0 loc0).\n  set (vs_tgt1 := fun loc0 => if Loc.eq_dec loc0 loc then match v with\n                                                          | Some _ => Some val_tgt\n                                                          | None => None\n                                                          end else vs_tgt0 loc0).\n  assert (MEM1: sim_memory tvw_src1.(TView.cur).(View.rlx) flag_src f1 vers1 mem_src1 mem_tgt1).\n  { eapply sim_memory_change_no_flag; eauto. i.\n    subst tvw_src1. ss. rewrite SRCTM. eapply TimeFacts.le_join_l.\n    rewrite timemap_singleton_neq; auto.\n    { eapply Time.bot_spec. }\n    { ii. subst. rewrite FLAG in *. ss. }\n  }\n  assert (PLNTS: forall loc0 (NEQ: loc0 <> loc), View.pln (TView.cur tvw_src1) loc0 = View.pln (TView.cur tvw_src0) loc0).\n  { i. ss. unfold TimeMap.join. rewrite timemap_singleton_neq; auto.\n    rewrite TimeFacts.le_join_l; auto. eapply Time.bot_spec.\n  }\n  assert (RLXTS: forall loc0 (NEQ: loc0 <> loc), View.rlx (TView.cur tvw_src1) loc0 = View.rlx (TView.cur tvw_src0) loc0).\n  { i. ss. unfold TimeMap.join. rewrite timemap_singleton_neq; auto.\n    rewrite TimeFacts.le_join_l; auto. eapply Time.bot_spec.\n  }\n  esplits.\n  { eauto. }\n  { econs.\n    { eapply sim_timemap_mon_latest; eauto. eapply Mapping.les_strong_les; eauto. }\n    { eauto. }\n    { eauto. }\n    { instantiate (1:=vs_src1). ii. unfold vs_src1.\n      clear WRITE0. des_ifs.\n      { eauto. }\n      { specialize (MAXSRC loc0). inv MAXSRC. econs.\n        { i. hexploit MAX0; eauto. i. des. esplits; eauto. rewrite PLNTS; eauto.\n          eapply write_unchanged_loc in CANCEL; eauto. des.\n          erewrite <- unchanged_loc_max_readable; eauto.\n        }\n        { rewrite PLNTS; eauto. i. eapply write_unchanged_loc in CANCEL; eauto. des.\n          erewrite <- unchanged_loc_max_readable; eauto.\n        }\n      }\n    }\n    { instantiate (1:=vs_tgt1). ii. unfold vs_tgt1. condtac.\n      { econs. i. destruct v; ss. subst. inv VAL0.\n        hexploit no_flag_max_value_same; eauto.\n        i. des. inv MAX0. hexploit MAX1; auto. i. des.\n        eapply write_max_readable in WRITE0; eauto.\n        des. subst. esplits; eauto.\n      }\n      { assert (TS: View.pln (TView.cur (tvw_tgt1)) loc0 = View.pln (TView.cur tvw_tgt0) loc0).\n        { ss. unfold TimeMap.join. rewrite timemap_singleton_neq; auto.\n          rewrite TimeFacts.le_join_l; auto. eapply Time.bot_spec.\n        }\n        specialize (MAXTGT loc0). inv MAXTGT. econs. i. hexploit MAX0; eauto.\n        i. des. esplits. rewrite TS.\n        eapply write_unchanged_loc in WRITE1; eauto. des.\n        erewrite <- unchanged_loc_max_readable; eauto.\n      }\n    }\n    { unfold vs_src1, vs_tgt1. i. clear WRITE0. des_ifs. }\n    { eauto. }\n    { eauto. }\n    { eauto. }\n    { i. assert (NEQ: loc0 <> loc).\n      { ii. subst. rewrite FLAG in *. ss. }\n      rewrite RLXTS; auto. rewrite <- SRCTM. rewrite MAXTIMES; auto.\n      eapply unchanged_loc_max_ts.\n      2:{ eapply MEMSRC. }\n      eapply write_unchanged_loc in CANCEL; eauto. des. auto.\n    }\n    { ss. eapply reserved_space_empty_mon_strong; eauto.\n      eapply reserved_space_empty_reserve_decr.\n      { eapply reserved_space_empty_covered_decr; eauto.\n        i. inv WRITE. ss. inv LC2. eapply write_unchanged_loc in WRITE2.\n        { des. inv MEM2. inv COVER. erewrite UNCH in GET. econs; eauto. }\n        { ii. subst. rewrite FLAG in *. ss. }\n      }\n      { i. inv WRITE0. ss. inv LC2. eapply write_unchanged_loc in WRITE2.\n        { des. inv PROM0. erewrite UNCH in GET. eauto. }\n        { ii. subst. rewrite FLAG in *. ss. }\n      }\n    }\n    { auto. }\n  }\n  { eauto. }\n  { eauto. }\n  { eauto. }\n  { eauto. }\n  { i. unfold vs_src1, vs_tgt1. clear WRITE0. des_ifs.\n    { right. splits; auto. left. splits; auto. f_equal.\n      inv MAX. hexploit MAX0; eauto. i. des.\n      eapply write_max_readable in WRITE; eauto. des; auto.\n    }\n    { right. splits; auto. right.\n      assert (NONE: vs_src0 loc = None).\n      { destruct (vs_src0 loc) eqn:SOME; auto.\n        specialize (MAXSRC loc). inv MAXSRC. hexploit MAX0; eauto.\n        i. des. eapply write_max_readable_none in WRITE; eauto.\n        inv MAX. exfalso. eapply NONMAX0; eauto.\n      }\n      splits; auto. specialize (PERM loc).\n      rewrite NONE in PERM. destruct (vs_tgt0 loc); ss.\n    }\n    { left. auto. }\n  }\n  { auto. }\nQed.\n\nLemma sim_thread_mapping_add\n      loc ts_tgt\n      f0 vers flag_src flag_tgt vs_src vs_tgt\n      mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt\n      (SIM: sim_thread\n              f0 vers flag_src flag_tgt vs_src vs_tgt\n              mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt)\n      (WF: Mapping.wfs f0)\n      (VERS: versions_wf f0 vers)\n      (FLAG: flag_src loc = false)\n  :\n  exists f1 ts_src,\n      (<<SIM: sim_thread\n                f1 vers flag_src flag_tgt vs_src vs_tgt\n                mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt>>) /\\\n      (<<WF: Mapping.wfs f1>>) /\\\n      (<<MAPLE: Mapping.les_strong f0 f1>>) /\\\n      (<<VERS: versions_wf f1 vers>>) /\\\n      (<<TS: sim_timestamp_exact (f1 loc) (f1 loc).(Mapping.ver) ts_src ts_tgt>>)\n.\nProof.\n  hexploit (@mapping_add (f0 loc) ts_tgt); eauto. i. des.\n  set (f' := (fun loc0 => if Loc.eq_dec loc0 loc then f1 else f0 loc0)).\n  assert (LES: Mapping.les_strong f0 f').\n  { unfold f'. ii. des_ifs. refl. }\n  assert (LE: Mapping.les f0 f').\n  { eapply Mapping.les_strong_les. auto. }\n  assert (WF1: Mapping.wfs f').\n  { unfold f'. ii. des_ifs. }\n  exists f', fts. splits; auto.\n  { inv SIM. econs; eauto.\n    { eapply sim_timemap_mon_latest; eauto. }\n    { eapply sim_memory_mon_strong; eauto.\n      unfold f'. ii. des_ifs.\n    }\n    { inv LOCAL. econs; eauto.\n      { eapply sim_tview_mon_latest; eauto. }\n      { eapply sim_promises_mon_strong; eauto.\n        unfold f'. ii. des_ifs.\n      }\n    }\n    { unfold f'. ii. eapply SIMCLOSED. des_ifs. eapply TIMES. auto. }\n    { eapply reserved_space_empty_mon_strong; eauto. }\n    { eapply promise_finalized_mon_strong; eauto. }\n  }\n  { eapply versions_wf_mapping_mon; eauto. }\n  { unfold f'. des_ifs. }\nQed.\n\nLemma space_future_memory_mon_map msgs f0 f1 f2 mem0 mem1\n      (SPACE: space_future_memory msgs f1 mem0 f2 mem1)\n      (MAP0: Mapping.les_strong f0 f1)\n      (MAP1: Mapping.les f1 f2)\n      (WF0: Mapping.wfs f0)\n      (WF1: Mapping.wfs f1)\n      (WF2: Mapping.wfs f2)\n  :\n  space_future_memory msgs f0 mem0 f2 mem1.\nProof.\n  eapply space_future_memory_trans.\n  2:{ eauto. }\n  { eapply space_future_memory_refl; eauto. }\n  { eapply Mapping.les_strong_les; auto. }\n  { auto. }\n  { auto. }\n  { auto. }\n  { auto. }\nQed.\n\nLemma sim_thread_write_step_normal\n      f0 vers0 flag_src flag_tgt vs_src0 vs_tgt0\n      mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0\n      val_tgt val_src\n      lc_tgt1 mem_tgt1 loc from_tgt to_tgt\n      released_tgt ord sc_tgt1 kind_tgt\n      (SIM: sim_thread\n              f0 vers0 flag_src flag_tgt vs_src0 vs_tgt0\n              mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0)\n      (WRITE: Local.write_step lc_tgt0 sc_tgt0 mem_tgt0 loc from_tgt to_tgt val_tgt None released_tgt ord lc_tgt1 sc_tgt1 mem_tgt1 kind_tgt)\n      (CONSISTENT: Local.promise_consistent lc_tgt1)\n      (LOCALSRC: Local.wf lc_src0 mem_src0)\n      (LOCALTGT: Local.wf lc_tgt0 mem_tgt0)\n      (MEMSRC: Memory.closed mem_src0)\n      (MEMTGT: Memory.closed mem_tgt0)\n      (SCSRC: Memory.closed_timemap sc_src0 mem_src0)\n      (SCTGT: Memory.closed_timemap sc_tgt0 mem_tgt0)\n      (WF: Mapping.wfs f0)\n      (VERS: versions_wf f0 vers0)\n      (FLAGSRC: flag_src loc = false)\n      (FLAGTGT: flag_tgt loc = false)\n      (VAL: Const.le val_tgt val_src)\n      (ORD: ~ Ordering.le Ordering.strong_relaxed ord)\n  :\n  exists f1 vers1 released_src lc_src1 vs_src1 vs_tgt1 mem_src1 sc_src1 kind_src from_src to_src,\n    (<<WRITE: Local.write_step lc_src0 sc_src0 mem_src0 loc from_src to_src val_src None released_src ord lc_src1 sc_src1 mem_src1 kind_src>>) /\\\n      (<<SIM: sim_thread\n                f1 vers1 flag_src flag_tgt vs_src1 vs_tgt1\n                mem_src1 mem_tgt1 lc_src1 lc_tgt1 sc_src1 sc_tgt1>>) /\\\n      (<<WF: Mapping.wfs f1>>) /\\\n      (<<MAPLE: Mapping.les_strong f0 f1>>) /\\\n      (<<VERSLE: versions_le vers0 vers1>>) /\\\n      (<<VERSWF: versions_wf f1 vers1>>) /\\\n      (<<VALS: forall loc0,\n          ((<<SRC: vs_src1 loc0 = vs_src0 loc0>>) /\\ (<<TGT: vs_tgt1 loc0 = vs_tgt0 loc0>>) /\\ (<<LOC: loc0 <> loc>>)) \\/\n            ((<<LOC: loc0 = loc>>) /\\\n               ((<<VALSRC: vs_src1 loc0 = Some val_src>> /\\ <<VALTGT: vs_tgt1 loc0 = Some val_tgt>>) \\/\n                  (<<VALSRC0: vs_src0 loc0 = None>> /\\ <<VALTGT0: vs_tgt0 loc0 = None>> /\\ <<VALSRC1: vs_src1 loc0 = None>> /\\ <<VALTGT1: vs_tgt1 loc0 = None>>)))>>) /\\\n      (<<SPACE: space_future_memory (unchangable mem_tgt0 lc_tgt0.(Local.promises)) f0 mem_src0 f1 mem_src1>>).\nProof.\n  hexploit (@sim_thread_mapping_add loc from_tgt); eauto. i. des.\n  hexploit (@sim_thread_mapping_add loc to_tgt); eauto. i. des.\n  hexploit sim_thread_write_aux; eauto.\n  { econs. }\n  { eapply Time.bot_spec. }\n  { eapply sim_timestamp_exact_mon_strong; [..|eapply TS]; eauto. }\n  i. des. esplits; eauto.\n  { etrans; eauto. etrans; eauto. }\n  { eapply space_future_memory_mon_map; eauto.\n    { etrans; eauto. }\n    { eapply Mapping.les_strong_les; auto. }\n  }\nQed.\n\nLemma sim_thread_write_update_normal\n      f0 vers0 flag_src flag_tgt vs_src0 vs_tgt0\n      mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0\n      val_tgt val_src releasedm_tgt releasedm_src\n      lc_tgt1 mem_tgt1 loc from_tgt to_tgt from_src\n      released_tgt ord sc_tgt1 kind_tgt\n      (SIM: sim_thread\n              f0 vers0 flag_src flag_tgt vs_src0 vs_tgt0\n              mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0)\n      (WRITE: Local.write_step lc_tgt0 sc_tgt0 mem_tgt0 loc from_tgt to_tgt val_tgt releasedm_tgt released_tgt ord lc_tgt1 sc_tgt1 mem_tgt1 kind_tgt)\n      (RELEASEDM: sim_opt_view (fun loc0 => loc0 <> loc) f0 (vers0 loc from_tgt) releasedm_src releasedm_tgt)\n      (MSGTOSRC: Time.le (View.rlx (View.unwrap releasedm_src) loc) from_src)\n      (FROM: sim_timestamp_exact (f0 loc) (f0 loc).(Mapping.ver) from_src from_tgt)\n      (CONSISTENT: Local.promise_consistent lc_tgt1)\n      (LOCALSRC: Local.wf lc_src0 mem_src0)\n      (LOCALTGT: Local.wf lc_tgt0 mem_tgt0)\n      (MEMSRC: Memory.closed mem_src0)\n      (MEMTGT: Memory.closed mem_tgt0)\n      (SCSRC: Memory.closed_timemap sc_src0 mem_src0)\n      (SCTGT: Memory.closed_timemap sc_tgt0 mem_tgt0)\n      (WF: Mapping.wfs f0)\n      (VERS: versions_wf f0 vers0)\n      (FLAGSRC: flag_src loc = false)\n      (FLAGTGT: flag_tgt loc = false)\n      (VAL: Const.le val_tgt val_src)\n      (ORD: ~ Ordering.le Ordering.strong_relaxed ord)\n      (WFSRC: View.opt_wf releasedm_src)\n      (WFTGT: View.opt_wf releasedm_tgt)\n      (CLOSEDMSRC: Memory.closed_opt_view releasedm_src mem_src0)\n      (CLOSEDMTGT: Memory.closed_opt_view releasedm_tgt mem_tgt0)\n  :\n  exists f1 vers1 released_src lc_src1 vs_src1 vs_tgt1 mem_src1 sc_src1 kind_src to_src,\n    (<<WRITE: Local.write_step lc_src0 sc_src0 mem_src0 loc from_src to_src val_src releasedm_src released_src ord lc_src1 sc_src1 mem_src1 kind_src>>) /\\\n      (<<SIM: sim_thread\n                f1 vers1 flag_src flag_tgt vs_src1 vs_tgt1\n                mem_src1 mem_tgt1 lc_src1 lc_tgt1 sc_src1 sc_tgt1>>) /\\\n      (<<WF: Mapping.wfs f1>>) /\\\n      (<<MAPLE: Mapping.les_strong f0 f1>>) /\\\n      (<<VERSLE: versions_le vers0 vers1>>) /\\\n      (<<VERSWF: versions_wf f1 vers1>>) /\\\n      (<<VALS: forall loc0,\n          ((<<SRC: vs_src1 loc0 = vs_src0 loc0>>) /\\ (<<TGT: vs_tgt1 loc0 = vs_tgt0 loc0>>) /\\ (<<LOC: loc0 <> loc>>)) \\/\n            ((<<LOC: loc0 = loc>>) /\\\n               ((<<VALSRC: vs_src1 loc0 = Some val_src>> /\\ <<VALTGT: vs_tgt1 loc0 = Some val_tgt>>) \\/\n                  (<<VALSRC0: vs_src0 loc0 = None>> /\\ <<VALTGT0: vs_tgt0 loc0 = None>> /\\ <<VALSRC1: vs_src1 loc0 = None>> /\\ <<VALTGT1: vs_tgt1 loc0 = None>>)))>>) /\\\n      (<<SPACE: space_future_memory (unchangable mem_tgt0 lc_tgt0.(Local.promises)) f0 mem_src0 f1 mem_src1>>).\nProof.\n  hexploit (@sim_thread_mapping_add loc to_tgt); eauto. i. des.\n  hexploit sim_thread_write_aux; eauto.\n  { erewrite <- sim_opt_view_mon_mapping; eauto.\n    eapply Mapping.les_strong_les; eauto.\n  }\n  { eapply sim_timestamp_exact_mon_strong; [..|eauto]; eauto. }\n  i. des. esplits; eauto.\n  { etrans; eauto. }\n  { eapply space_future_memory_mon_map; eauto.\n    eapply Mapping.les_strong_les; auto.\n  }\nQed.\n\nDefinition local_write_sync_tview (tview1: TView.t) (loc: Loc.t) (ord: Ordering.t): TView.t :=\n  TView.mk\n    (if Ordering.le Ordering.acqrel ord\n     then fun loc0 =>\n            if (Loc.eq_dec loc0 loc)\n            then tview1.(TView.cur)\n            else tview1.(TView.rel) loc0\n     else tview1.(TView.rel))\n    (tview1.(TView.cur))\n    (tview1.(TView.acq)).\n\nLemma local_write_sync_tview_wf tview loc ord\n      (WF: TView.wf tview)\n  :\n  TView.wf (local_write_sync_tview tview loc ord).\nProof.\n  econs; ss; i; des_ifs; try by (eapply WF). refl.\nQed.\n\nLemma local_write_sync_tview_closed mem tview loc ord\n      (TVIEW: TView.closed tview mem)\n  :\n  TView.closed (local_write_sync_tview tview loc ord) mem.\nProof.\n  unfold local_write_sync_tview.\n  econs; i; ss; des_ifs; try by (eapply TVIEW).\nQed.\n\nLemma local_write_sync_tview_incr tview loc ord\n      (WF: TView.wf tview)\n  :\n    TView.le tview (local_write_sync_tview tview loc ord).\nProof.\n  econs; ss.\n  { i. des_ifs.\n    { unfold LocFun.find. des_ifs.\n      { eapply WF. }\n      { refl. }\n    }\n    { refl. }\n  }\n  { refl. }\n  { refl. }\nQed.\n\nVariant local_write_sync_step lc1 loc ord lc2: Prop :=\n| local_write_sync_step_intro\n    (LOCAL: lc2 = Local.mk\n                    (local_write_sync_tview lc1.(Local.tview) loc ord)\n                    (lc1.(Local.promises)))\n    (SYNC: forall (ORD: Ordering.le Ordering.strong_relaxed ord),\n        Memory.nonsynch_loc loc (Local.promises lc1))\n.\n\nDefinition non_sync_ord (ord: Ordering.t): Ordering.t :=\n  if Ordering.le Ordering.relaxed ord then Ordering.relaxed else ord.\n\nLemma local_write_sync_tview_merge tvw loc ord sc to\n  :\n  TView.write_tview (local_write_sync_tview tvw loc ord) sc loc to (non_sync_ord ord) = TView.write_tview tvw sc loc to ord.\nProof.\n  unfold TView.write_tview. f_equal.\n  unfold LocFun.add, LocFun.find. extensionality loc0.\n  ss. des_ifs. destruct ord; ss.\nQed.\n\nLemma local_write_released_merge tvw loc ord sc to releasedm\n  :\n  TView.write_released (local_write_sync_tview tvw loc ord) sc loc to releasedm (non_sync_ord ord) = TView.write_released tvw sc loc to releasedm ord.\nProof.\n  unfold TView.write_released. des_ifs.\n  { f_equal. f_equal. rewrite local_write_sync_tview_merge. auto. }\n  { destruct ord; ss. }\n  { destruct ord; ss. }\nQed.\n\nLemma local_write_step_merge\n      lc0 sc0 mem0 loc from to val releasedm released ord lc1 sc1 mem1 kind lc2\n      (STEP0: local_write_sync_step lc0 loc ord lc1)\n      (STEP1: Local.write_step lc1 sc0 mem0 loc from to val releasedm released (non_sync_ord ord) lc2 sc1 mem1 kind)\n  :\n  Local.write_step lc0 sc0 mem0 loc from to val releasedm released ord lc2 sc1 mem1 kind.\nProof.\n  inv STEP0. inv STEP1. ss. econs; ss; eauto.\n  { eapply local_write_released_merge; eauto. }\n  { inv WRITABLE. econs; eauto. }\n  { f_equal. eapply local_write_sync_tview_merge; auto. }\nQed.\n\nLemma local_write_step_split\n      lc0 sc0 mem0 loc from to val releasedm released ord sc1 mem1 kind lc2\n      (STEP: Local.write_step lc0 sc0 mem0 loc from to val releasedm released ord lc2 sc1 mem1 kind)\n  :\n  exists lc1,\n    (<<STEP0: local_write_sync_step lc0 loc ord lc1>>) /\\\n    (<<STEP1: Local.write_step lc1 sc0 mem0 loc from to val releasedm released (non_sync_ord ord) lc2 sc1 mem1 kind>>).\nProof.\n  inv STEP. esplits.\n  { econs; eauto. }\n  { econs; ss; eauto.\n    { symmetry. apply local_write_released_merge. }\n    { inv WRITABLE. econs; auto. }\n    { destruct ord; ss. }\n    { f_equal. symmetry. apply local_write_sync_tview_merge. }\n  }\nQed.\n\nLemma local_write_sync_step_future lc1 loc ord lc2 mem\n      (STEP: local_write_sync_step lc1 loc ord lc2)\n      (LOCAL: Local.wf lc1 mem)\n  :\n    (<<LOCAL: Local.wf lc2 mem>>) /\\\n    (<<INCR: TView.le lc1.(Local.tview) lc2.(Local.tview)>>).\nProof.\n  inv STEP. splits.\n  { inv LOCAL. econs; ss.\n    { eapply local_write_sync_tview_wf; eauto. }\n    { eapply local_write_sync_tview_closed; eauto. }\n  }\n  { eapply local_write_sync_tview_incr. eapply LOCAL. }\nQed.\n\nLemma sim_write_sync_tview_normal f flag_src rel_vers tvw_src tvw_tgt\n      loc ord\n      (SIM: sim_tview f flag_src rel_vers tvw_src tvw_tgt)\n      (WF: Mapping.wfs f)\n      (ORD: ~ Ordering.le Ordering.strong_relaxed ord)\n  :\n  sim_tview f flag_src rel_vers (local_write_sync_tview tvw_src loc ord) (local_write_sync_tview tvw_tgt loc ord).\nProof.\n  unfold local_write_sync_tview. econs; ss.\n  { des_ifs.\n    { destruct ord; ss. }\n    i. eapply SIM.\n  }\n  { eapply SIM. }\n  { eapply SIM. }\n  { eapply SIM. }\nQed.\n\nLemma sim_write_sync_tview_release f flag_src rel_vers tvw_src tvw_tgt\n      loc ord\n      (SIM: sim_tview f flag_src rel_vers tvw_src tvw_tgt)\n      (FLAG: forall loc, flag_src loc = false)\n      (WF: Mapping.wfs f)\n  :\n  sim_tview f flag_src (fun loc0 => if Loc.eq_dec loc0 loc then (Mapping.vers f) else rel_vers loc0) (local_write_sync_tview tvw_src loc ord) (local_write_sync_tview tvw_tgt loc ord).\nProof.\n  assert (VERLE: forall loc0, version_wf f (rel_vers loc0)).\n  { eapply SIM. }\n  pose proof (mapping_latest_wf f) as VERWF.\n  unfold local_write_sync_tview. econs; ss.\n  { i. des_ifs.\n    { eapply sim_view_mon_locs.\n      { eapply SIM. }\n      i. ss.\n    }\n    { eapply sim_view_mon_ver; [eapply SIM|..]; eauto. eapply VERLE. }\n    { eapply SIM. }\n    { eapply SIM. }\n  }\n  { eapply SIM. }\n  { eapply SIM. }\n  { i. des_ifs. }\nQed.\n\nLemma sim_thread_write_sync_step\n      f vers flag_src flag_tgt vs_src vs_tgt\n      mem_src mem_tgt lc_src0 lc_tgt0 sc_src sc_tgt\n      lc_tgt1 loc ord\n      (SIM: sim_thread\n              f vers flag_src flag_tgt vs_src vs_tgt\n              mem_src mem_tgt lc_src0 lc_tgt0 sc_src sc_tgt)\n      (WRITE: local_write_sync_step lc_tgt0 loc ord lc_tgt1)\n      (CONSISTENT: Local.promise_consistent lc_tgt1)\n      (LOCALSRC: Local.wf lc_src0 mem_src)\n      (LOCALTGT: Local.wf lc_tgt0 mem_tgt)\n      (MEMSRC: Memory.closed mem_src)\n      (MEMTGT: Memory.closed mem_tgt)\n      (SCSRC: Memory.closed_timemap sc_src mem_src)\n      (SCTGT: Memory.closed_timemap sc_tgt mem_tgt)\n      (WF: Mapping.wfs f)\n      (VERS: versions_wf f vers)\n      (RELFLAG: forall loc (ORD: Ordering.le Ordering.strong_relaxed ord), flag_src loc = false)\n  :\n    exists lc_src1,\n      (<<READ: local_write_sync_step lc_src0 loc ord lc_src1>>) /\\\n      (<<SIM: sim_thread\n                f vers flag_src flag_tgt vs_src vs_tgt\n                mem_src mem_tgt lc_src1 lc_tgt1 sc_src sc_tgt>>)\n.\nProof.\n  hexploit local_write_sync_step_future; eauto. i. des.\n  esplits.\n  { econs; eauto. i. inv SIM. inv LOCAL0.\n    eapply sim_promises_nonsynch_loc; eauto. i. inv WRITE. eauto.\n  }\n  inv SIM. inv WRITE. econs; eauto.\n  { inv LOCAL0. ss.\n    destruct (Ordering.le Ordering.strong_relaxed ord) eqn:ORD.\n    { econs.\n      { eapply sim_write_sync_tview_release; eauto. }\n      { eauto. }\n      { inv RELVERS. econs. i. hexploit PROM; eauto.\n        i. des. des_ifs; eauto. esplits; eauto.\n        i. exfalso. subst.\n        eapply SYNC in GET; eauto. ss.\n      }\n      { i. ss. eauto. }\n      { i. ss. }\n    }\n    { econs; eauto. eapply sim_write_sync_tview_normal; eauto.\n      destruct ord; ss.\n    }\n  }\n  { ii. hexploit (MAXSRC loc0). i. inv H. econs; ss. }\n  { eapply max_values_tgt_mon; eauto. }\nQed.\n\nLemma sim_thread_write_step_release\n      f0 vers0 flag_src flag_tgt0 vs_src0 vs_tgt0\n      mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0\n      val_tgt val_src\n      lc_tgt1 mem_tgt1 loc from_tgt to_tgt\n      released_tgt ord sc_tgt1 kind_tgt D\n      (SIM: sim_thread\n              f0 vers0 flag_src flag_tgt0 vs_src0 vs_tgt0\n              mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0)\n      (WRITE: Local.write_step lc_tgt0 sc_tgt0 mem_tgt0 loc from_tgt to_tgt val_tgt None released_tgt ord lc_tgt1 sc_tgt1 mem_tgt1 kind_tgt)\n      (CONSISTENT: Local.promise_consistent lc_tgt1)\n      (LOCALSRC: Local.wf lc_src0 mem_src0)\n      (LOCALTGT: Local.wf lc_tgt0 mem_tgt0)\n      (MEMSRC: Memory.closed mem_src0)\n      (MEMTGT: Memory.closed mem_tgt0)\n      (SCSRC: Memory.closed_timemap sc_src0 mem_src0)\n      (SCTGT: Memory.closed_timemap sc_tgt0 mem_tgt0)\n      (WF: Mapping.wfs f0)\n      (VERS: versions_wf f0 vers0)\n      (FLAGSRC: flag_src loc = false)\n      (FLAGTGT: flag_tgt0 loc = false)\n      (VAL: Const.le val_tgt val_src)\n      (DEBT: forall loc, (<<DEBT: D loc>>) \\/\n                           ((<<FLAG: flag_src loc = false -> flag_tgt0 loc = false>>) /\\\n                            (<<VAL: option_rel Const.le (vs_tgt0 loc) (vs_src0 loc) \\/ flag_src loc = false>>)))\n      lang st\n  :\n  exists f1 vers1 released_src lc_src1 lc_src2 vs_src1 vs_tgt1 mem_src1 mem_src2 sc_src1 kind_src from_src to_src flag_tgt1,\n    (<<STEPS: rtc (tau (@pred_step is_promise _))\n                    (Thread.mk lang st lc_src0 sc_src0 mem_src0)\n                    (Thread.mk _ st lc_src1 sc_src0 mem_src1)>>) /\\\n      (<<WRITE: Local.write_step lc_src1 sc_src0 mem_src1 loc from_src to_src val_src None released_src ord lc_src2 sc_src1 mem_src2 kind_src>>) /\\\n      (<<SIM: sim_thread\n                f1 vers1 (fun _ => false) flag_tgt1 vs_src1 vs_tgt1\n                mem_src2 mem_tgt1 lc_src2 lc_tgt1 sc_src1 sc_tgt1>>) /\\\n      (<<WF: Mapping.wfs f1>>) /\\\n      (<<MAPLE: Mapping.les f0 f1>>) /\\\n      (<<VERSLE: versions_le vers0 vers1>>) /\\\n      (<<VERSWF: versions_wf f1 vers1>>) /\\\n      (<<VALS: forall loc0,\n          ((<<SRC: vs_src1 loc0 = vs_src0 loc0>>) /\\ (<<TGT: vs_tgt1 loc0 = vs_tgt0 loc0>>) /\\ (<<LOC: loc0 <> loc>>)) \\/\n            ((<<LOC: loc0 = loc>>) /\\\n               ((<<VALSRC: vs_src1 loc0 = Some val_src>> /\\ <<VALTGT: vs_tgt1 loc0 = Some val_tgt>>) \\/\n                  (<<VALSRC0: vs_src0 loc0 = None>> /\\ <<VALTGT0: vs_tgt0 loc0 = None>> /\\ <<VALSRC1: vs_src1 loc0 = None>> /\\ <<VALTGT1: vs_tgt1 loc0 = None>>)))>>) /\\\n      (<<FLAG: forall loc, (<<DEBT: D loc>>) \\/ (<<FLAG: flag_tgt1 loc = false>>)>>) /\\\n      (<<MAPFUTURE: map_future_memory f0 f1 mem_src2>>) /\\\n      (<<SPACE: space_future_memory (unchangable mem_tgt0 lc_tgt0.(Local.promises)) f0 mem_src0 f1 mem_src2>>)\n.\nProof.\n  hexploit (@sim_thread_deflag_all (fun loc0 => D loc0 /\\ loc0 <> loc)); eauto.\n  { eapply PromiseConsistent.write_step_promise_consistent; eauto. }\n  { i. hexploit (DEBT loc0). i. des; auto.\n    destruct (Loc.eq_dec loc0 loc); auto. subst. right. splits; auto.\n  }\n  i. des.\n  hexploit local_write_step_split; eauto. i. des.\n  hexploit local_write_sync_step_future; eauto. i. des.\n  hexploit Thread.rtc_tau_step_future.\n  { eapply rtc_implies; [|eauto]. i. inv H. inv TSTEP. econs; eauto. }\n  { eauto. }\n  { eauto. }\n  { eauto. }\n  i. des. ss.\n  hexploit sim_thread_write_sync_step; eauto.\n  { eapply PromiseConsistent.write_step_promise_consistent; eauto. }\n  { eapply versions_wf_mapping_mon; eauto. }\n  i. des.\n  hexploit local_write_sync_step_future; eauto. i. des.\n  hexploit sim_thread_write_step_normal; eauto.\n  { eapply versions_wf_mapping_mon; eauto. }\n  { specialize (FLAG loc). des; ss. }\n  { destruct ord; ss. }\n  i. des. esplits; eauto.\n  { eapply local_write_step_merge; eauto. }\n  { etrans; eauto. eapply Mapping.les_strong_les; eauto. }\n  { i. specialize (FLAG loc0). des; auto. }\n  { eapply map_future_memory_trans; eauto.\n    { eapply map_future_memory_les_strong; eauto. }\n    { eapply Local.write_step_future in WRITE0; eauto. des.\n      eapply Memory.future_future_weak; auto.\n    }\n  }\n  { eapply space_future_memory_trans; eauto.\n    { inv STEP0. auto. }\n    { eapply Mapping.les_strong_les; eauto. }\n  }\nQed.\n\nLemma sim_thread_update_step_normal\n      f0 vers0 flag_src flag_tgt vs_src0 vs_tgt0\n      mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0\n      valr_tgt valw_tgt valw_src\n      lc_tgt1 lc_tgt2 mem_tgt1 loc from_tgt to_tgt releasedm_tgt\n      released_tgt ordr ordw sc_tgt1 kind_tgt\n      (SIM: sim_thread\n              f0 vers0 flag_src flag_tgt vs_src0 vs_tgt0\n              mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0)\n      (READ: Local.read_step lc_tgt0 mem_tgt0 loc from_tgt valr_tgt releasedm_tgt ordr lc_tgt1)\n      (WRITE: Local.write_step lc_tgt1 sc_tgt0 mem_tgt0 loc from_tgt to_tgt valw_tgt releasedm_tgt released_tgt ordw lc_tgt2 sc_tgt1 mem_tgt1 kind_tgt)\n      (CONSISTENT: Local.promise_consistent lc_tgt2)\n      (LOCALSRC: Local.wf lc_src0 mem_src0)\n      (LOCALTGT: Local.wf lc_tgt0 mem_tgt0)\n      (MEMSRC: Memory.closed mem_src0)\n      (MEMTGT: Memory.closed mem_tgt0)\n      (SCSRC: Memory.closed_timemap sc_src0 mem_src0)\n      (SCTGT: Memory.closed_timemap sc_tgt0 mem_tgt0)\n      (WF: Mapping.wfs f0)\n      (VERS: versions_wf f0 vers0)\n      (FLAGSRC: flag_src loc = false)\n      (FLAGTGT: flag_tgt loc = false)\n      (FLAG: forall loc\n                    (SRC: flag_src loc = false) (TGT: flag_tgt loc = true),\n          ~ Ordering.le Ordering.acqrel ordr)\n      (VAL: Const.le valw_tgt valw_src)\n      (ORD: ~ Ordering.le Ordering.strong_relaxed ordw)\n  :\n    exists f1 vers1 val_tgt1 val_src1 from_src to_src releasedm_src released_src mem_src1 lc_src1 lc_src2 vs_src1 vs_tgt1 sc_src1 kind_src,\n      (<<READ: forall val (VAL: Const.le val val_src1), Local.read_step lc_src0 mem_src0 loc from_src val releasedm_src ordr lc_src1>>) /\\\n      (<<WRITE: Local.write_step lc_src1 sc_src0 mem_src0 loc from_src to_src valw_src releasedm_src released_src ordw lc_src2 sc_src1 mem_src1 kind_src>>) /\\\n      (<<WF: Mapping.wfs f1>>) /\\\n      (<<MAPLE: Mapping.les_strong f0 f1>>) /\\\n      (<<VERSLE: versions_le vers0 vers1>>) /\\\n      (<<VERSWF: versions_wf f1 vers1>>) /\\\n      (<<SIM: sim_thread\n                f1 vers1 flag_src flag_tgt vs_src1 vs_tgt1\n                mem_src1 mem_tgt1 lc_src2 lc_tgt2 sc_src1 sc_tgt1>>) /\\\n      (<<VAL: Const.le val_tgt1 val_src1>>) /\\\n      (<<VALTGT: Const.le valr_tgt val_tgt1>>) /\\\n      (<<NUPDATESRC: forall val (VAL: vs_src0 loc = Some val), val = val_src1>>) /\\\n      (<<NUPDATETGT: forall val (VAL: vs_tgt0 loc = Some val), val = val_tgt1>>) /\\\n      (<<VALS: forall loc0 (LOC: loc0 <> loc),\n          ((<<SRC: vs_src1 loc0 = vs_src0 loc0>>) /\\ (<<TGT: vs_tgt1 loc0 = vs_tgt0 loc0>>)) \\/\n          (exists val_src val_tgt,\n              (<<NONESRC: vs_src0 loc0 = None>>) /\\ (<<NONETGT: vs_tgt0 loc0 = None>>) /\\\n              (<<VALSRC: vs_src1 loc0 = Some val_src>>) /\\ (<<VALTGT: vs_tgt1 loc0 = Some val_tgt>>) /\\\n              (<<VALLE: Const.le val_tgt val_src>>) /\\\n              (<<ORD: Ordering.le Ordering.acqrel ordr>>))>>) /\\\n      (<<UPDATED:\n        __guard__(((<<SRC: vs_src1 loc = Some valw_src>>) /\\ (<<TGT: vs_tgt1 loc = Some valw_tgt>>)) \\/\n        ((<<SRCNONE0: vs_src0 loc = None>>) /\\ (<<TGTNONE0: vs_tgt0 loc = None>>) /\\\n         (<<SRCNONE1: vs_src1 loc = None>>) /\\ (<<TGTNONE0: vs_tgt1 loc = None>>)))>>) /\\\n      (<<SPACE: space_future_memory (unchangable mem_tgt0 lc_tgt0.(Local.promises)) f0 mem_src0 f1 mem_src1>>)\n.\nProof.\n  hexploit Local.read_step_future; eauto. i. des.\n  hexploit Local.write_step_future; eauto. i. des. ss.\n  hexploit sim_thread_read; eauto.\n  { eapply PromiseConsistent.write_step_promise_consistent; eauto. }\n  i. des.\n  hexploit READ0.\n  { refl. }\n  intros READSRC.\n  hexploit Local.read_step_future; eauto. i. des.\n  hexploit sim_thread_write_update_normal; eauto.\n  { inv READSRC. eapply MEMSRC in GET. des. inv MSG_TS. ss. }\n  i. des. esplits; eauto.\n  { i. hexploit (VALS loc0). hexploit (VALS0 loc0). i. des; subst; ss.\n    { left. esplits; etrans; eauto. }\n    { right. esplits; eauto.\n      { rewrite SRC. auto. }\n      { rewrite TGT. auto. }\n    }\n  }\n  { red. specialize (VALS loc). specialize (VALS0 loc).\n    des; ss; auto. right. splits; auto.\n    { rewrite <- SRC. auto. }\n    { rewrite <- TGT. auto. }\n  }\n  { inv READ. auto. }\nQed.\n\nLemma sim_thread_update_step_release\n      f0 vers0 flag_src flag_tgt0 vs_src0 vs_tgt0\n      mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0\n      valr_tgt valw_tgt valw_src\n      lc_tgt1 lc_tgt2 mem_tgt1 loc from_tgt to_tgt releasedm_tgt\n      released_tgt ordr ordw sc_tgt1 kind_tgt D\n      (SIM: sim_thread\n              f0 vers0 flag_src flag_tgt0 vs_src0 vs_tgt0\n              mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0)\n      (READ: Local.read_step lc_tgt0 mem_tgt0 loc from_tgt valr_tgt releasedm_tgt ordr lc_tgt1)\n      (WRITE: Local.write_step lc_tgt1 sc_tgt0 mem_tgt0 loc from_tgt to_tgt valw_tgt releasedm_tgt released_tgt ordw lc_tgt2 sc_tgt1 mem_tgt1 kind_tgt)\n      (CONSISTENT: Local.promise_consistent lc_tgt2)\n      (LOCALSRC: Local.wf lc_src0 mem_src0)\n      (LOCALTGT: Local.wf lc_tgt0 mem_tgt0)\n      (MEMSRC: Memory.closed mem_src0)\n      (MEMTGT: Memory.closed mem_tgt0)\n      (SCSRC: Memory.closed_timemap sc_src0 mem_src0)\n      (SCTGT: Memory.closed_timemap sc_tgt0 mem_tgt0)\n      (WF: Mapping.wfs f0)\n      (VERS: versions_wf f0 vers0)\n      (FLAGSRC: flag_src loc = false)\n      (FLAGTGT: flag_tgt0 loc = false)\n      (FLAG: forall loc\n                    (SRC: flag_src loc = false) (TGT: flag_tgt0 loc = true),\n          ~ Ordering.le Ordering.acqrel ordr)\n      (DEBT: forall loc, (<<DEBT: D loc>>) \\/\n                           ((<<FLAG: flag_src loc = false -> flag_tgt0 loc = false>>) /\\\n                            (<<VAL: option_rel Const.le (vs_tgt0 loc) (vs_src0 loc) \\/ flag_src loc = false>>)))\n      (VAL: Const.le valw_tgt valw_src)\n      lang st\n  :\n    exists val_src1 f1 vers1 val_tgt1 from_src to_src releasedm_src released_src mem_src1 mem_src2 lc_src1 lc_src2 lc_src3 vs_src1 vs_tgt1 sc_src1 kind_src flag_tgt1,\n      (<<STEPS: rtc (tau (@pred_step is_promise _))\n                    (Thread.mk lang st lc_src0 sc_src0 mem_src0)\n                    (Thread.mk _ st lc_src1 sc_src0 mem_src1)>>) /\\\n      (<<READ: forall val (VAL: Const.le val val_src1), Local.read_step lc_src1 mem_src1 loc from_src val releasedm_src ordr lc_src2>>) /\\\n      (<<WRITE: Local.write_step lc_src2 sc_src0 mem_src1 loc from_src to_src valw_src releasedm_src released_src ordw lc_src3 sc_src1 mem_src2 kind_src>>) /\\\n      (<<WF: Mapping.wfs f1>>) /\\\n      (<<MAPLE: Mapping.les f0 f1>>) /\\\n      (<<VERSLE: versions_le vers0 vers1>>) /\\\n      (<<VERSWF: versions_wf f1 vers1>>) /\\\n      (<<SIM: sim_thread\n                f1 vers1 (fun _ => false) flag_tgt1 vs_src1 vs_tgt1\n                mem_src2 mem_tgt1 lc_src3 lc_tgt2 sc_src1 sc_tgt1>>) /\\\n      (<<VAL: Const.le val_tgt1 val_src1>>) /\\\n      (<<VALTGT: Const.le valr_tgt val_tgt1>>) /\\\n      (<<NUPDATESRC: forall val (VAL: vs_src0 loc = Some val), val = val_src1>>) /\\\n      (<<NUPDATETGT: forall val (VAL: vs_tgt0 loc = Some val), val = val_tgt1>>) /\\\n      (<<VALS: forall loc0 (LOC: loc0 <> loc),\n          ((<<SRC: vs_src1 loc0 = vs_src0 loc0>>) /\\ (<<TGT: vs_tgt1 loc0 = vs_tgt0 loc0>>)) \\/\n          (exists val_src val_tgt,\n              (<<NONESRC: vs_src0 loc0 = None>>) /\\ (<<NONETGT: vs_tgt0 loc0 = None>>) /\\\n              (<<VALSRC: vs_src1 loc0 = Some val_src>>) /\\ (<<VALTGT: vs_tgt1 loc0 = Some val_tgt>>) /\\\n              (<<VALLE: Const.le val_tgt val_src>>) /\\\n              (<<ORD: Ordering.le Ordering.acqrel ordr>>))>>) /\\\n      (<<UPDATED:\n        __guard__(((<<SRC: vs_src1 loc = Some valw_src>>) /\\ (<<TGT: vs_tgt1 loc = Some valw_tgt>>)) \\/\n        ((<<SRCNONE0: vs_src0 loc = None>>) /\\ (<<TGTNONE0: vs_tgt0 loc = None>>) /\\\n           (<<SRCNONE1: vs_src1 loc = None>>) /\\ (<<TGTNONE0: vs_tgt1 loc = None>>)))>>) /\\\n      (<<FLAG: forall loc, (<<DEBT: D loc>>) \\/ (<<FLAG: flag_tgt1 loc = false>>)>>) /\\\n      (<<MAPFUTURE: map_future_memory f0 f1 mem_src2>>) /\\\n      (<<SPACE: space_future_memory (unchangable mem_tgt0 lc_tgt0.(Local.promises)) f0 mem_src0 f1 mem_src2>>)\n.\nProof.\n  assert (CONSISTENT0: Local.promise_consistent lc_tgt1).\n  { eapply PromiseConsistent.write_step_promise_consistent; eauto. }\n  eapply local_write_step_split in WRITE. des.\n  hexploit Local.read_step_future; eauto. i. des.\n  hexploit local_write_sync_step_future; eauto. i. des.\n  hexploit Local.write_step_future; eauto. i. des. ss.\n  hexploit sim_thread_read; eauto. i. des.\n  hexploit READ0.\n  { refl. }\n  intros READSRC.\n  hexploit Local.read_step_future; eauto. i. des.\n  hexploit (@sim_thread_deflag_all (fun loc0 => D loc0 /\\ loc0 <> loc)); eauto.\n  { i. destruct (Loc.eq_dec loc0 loc).\n    { right. subst. splits; auto. }\n    hexploit (DEBT loc0). i. des; auto. right. splits; auto.\n    hexploit (VALS loc0). i. des.\n    { rewrite SRC. rewrite TGT. auto. }\n    { left. rewrite VALTGT0. rewrite VALSRC. ss. }\n    { left. rewrite VALTGT0. rewrite VALSRC. ss. }\n  }\n  i. des. hexploit Thread.rtc_tau_step_future.\n  { eapply rtc_implies; [|eauto]. i. inv H. inv TSTEP. econs; eauto. }\n  { eauto. }\n  { eauto. }\n  { eauto. }\n  ss. i. des.\n  hexploit sim_thread_write_sync_step; eauto.\n  { eapply PromiseConsistent.write_step_promise_consistent; eauto. }\n  { eapply versions_wf_mapping_mon; eauto. }\n  i. des.\n  hexploit local_write_sync_step_future; eauto. i. des.\n  assert (RELEASEDM: sim_opt_view (fun loc0 => loc0 <> loc) f1 (vers0 loc from_tgt) released_src releasedm_tgt).\n  { erewrite <- sim_opt_view_mon_mapping; eauto. }\n  hexploit sim_thread_write_update_normal; eauto.\n  { instantiate (1:=to_src). inv READSRC. eapply MEMSRC in GET. des. inv MSG_TS. ss. }\n  { rewrite UNCH; auto. }\n  { eapply versions_wf_mapping_mon; eauto. }\n  { specialize (FLAG0 loc). des; ss. }\n  { destruct ordw; ss. }\n  { eapply Memory.future_weak_closed_opt_view; eauto.\n    eapply Memory.future_future_weak; eauto.\n  }\n  i. des.\n  hexploit promise_steps_local_read_step; eauto.\n  { eapply sim_local_consistent_ex.\n    { eapply CONSISTENT0. }\n    { inv SIM1. eauto. }\n    { eauto. }\n  }\n  i. des. exists val_src1. esplits; eauto.\n  { inv READ2. i. econs; eauto. etrans; eauto. }\n  { eapply local_write_step_merge; eauto. }\n  { etrans; eauto. eapply Mapping.les_strong_les; eauto. }\n  { i. hexploit (VALS loc0). hexploit (VALS0 loc0). i. des; subst; ss.\n    { left. esplits; etrans; eauto. }\n    { right. esplits; eauto.\n      { rewrite SRC. auto. }\n      { rewrite TGT. auto. }\n    }\n  }\n  { red. specialize (VALS loc). specialize (VALS0 loc).\n    des; ss; auto. right. splits; auto.\n    { rewrite <- SRC. auto. }\n    { rewrite <- TGT. auto. }\n  }\n  { i. specialize (FLAG0 loc0). des; auto. }\n  { eapply map_future_memory_trans; eauto.\n    { eapply map_future_memory_les_strong; eauto. }\n    { eapply Local.write_step_future in WRITE; eauto.\n      { des. eapply Memory.future_future_weak; auto. }\n      { eapply Memory.future_closed_opt_view; eauto. }\n    }\n  }\n  { eapply space_future_memory_trans.\n    { inv READ. eauto. }\n    { inv READ. inv STEP0. eauto. }\n    { eauto. }\n    { eapply Mapping.les_strong_les; eauto. }\n    { eauto. }\n    { eauto. }\n    { eauto. }\n  }\nQed.\n\nLemma semi_closed_timemap_closed\n      tm mem loc ts\n      (SEMI: semi_closed_timemap tm mem loc ts)\n      (CLOSED: exists from val released, Memory.get loc ts mem = Some (from, Message.concrete val released))\n  :\n  Memory.closed_timemap tm mem.\nProof.\n  ii. exploit SEMI. i. des; eauto.\n  subst. esplits; eauto.\nQed.\n\nLemma semi_closed_view_closed\n      vw mem loc ts\n      (SEMI: semi_closed_view vw mem loc ts)\n      (CLOSED: exists from val released, Memory.get loc ts mem = Some (from, Message.concrete val released))\n  :\n  Memory.closed_view vw mem.\nProof.\n  econs.\n  { eapply semi_closed_timemap_closed; eauto. eapply SEMI. }\n  { eapply semi_closed_timemap_closed; eauto. eapply SEMI. }\nQed.\n\nLemma semi_closed_opt_view_closed\n      vw mem loc ts\n      (SEMI: semi_closed_opt_view vw mem loc ts)\n      (CLOSED: exists from val released, Memory.get loc ts mem = Some (from, Message.concrete val released))\n  :\n  Memory.closed_opt_view vw mem.\nProof.\n  inv SEMI; econs.\n  eapply semi_closed_view_closed; eauto.\nQed.\n\nLemma semi_closed_message_closed\n      msg mem loc ts\n      (SEMI: semi_closed_message msg mem loc ts)\n      (CLOSED: forall val released (MSG: msg = Message.concrete val released),\n        exists from val released, Memory.get loc ts mem = Some (from, Message.concrete val released))\n  :\n  Memory.closed_message msg mem.\nProof.\n  inv SEMI; econs.\n  eapply semi_closed_opt_view_closed; eauto.\nQed.\n\nLemma sim_thread_promise_step\n      f0 vers0 flag_src flag_tgt vs_src vs_tgt\n      mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src sc_tgt\n      lc_tgt1 mem_tgt1 loc from_tgt to_tgt\n      msg_tgt kind_tgt\n      (SIM: sim_thread\n              f0 vers0 flag_src flag_tgt vs_src vs_tgt\n              mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src sc_tgt)\n      (PROMISE: Local.promise_step lc_tgt0 mem_tgt0 loc from_tgt to_tgt msg_tgt lc_tgt1 mem_tgt1 kind_tgt)\n      (CONSISTENT: Local.promise_consistent lc_tgt1)\n      (LOCALSRC: Local.wf lc_src0 mem_src0)\n      (LOCALTGT: Local.wf lc_tgt0 mem_tgt0)\n      (MEMSRC: Memory.closed mem_src0)\n      (MEMTGT: Memory.closed mem_tgt0)\n      (SCSRC: Memory.closed_timemap sc_src mem_src0)\n      (SCTGT: Memory.closed_timemap sc_tgt mem_tgt0)\n      (WF: Mapping.wfs f0)\n      (VERS: versions_wf f0 vers0)\n      (FLAGSRC: flag_src loc = false)\n  :\n  exists f1 vers1 from_src to_src msg_src lc_src1 mem_src1 kind_src,\n    (<<PROMISE: Local.promise_step lc_src0 mem_src0 loc from_src to_src msg_src lc_src1 mem_src1 kind_src>>) /\\\n    (<<SIM: sim_thread\n              f1 vers1 flag_src flag_tgt vs_src vs_tgt\n              mem_src1 mem_tgt1 lc_src1 lc_tgt1 sc_src sc_tgt>>) /\\\n    (<<WF: Mapping.wfs f1>>) /\\\n    (<<MAPLE: Mapping.les_strong f0 f1>>) /\\\n    (<<VERSLE: versions_le vers0 vers1>>) /\\\n    (<<VERSWF: versions_wf f1 vers1>>) /\\\n    (<<SPACE: space_future_memory (unchangable mem_tgt0 lc_tgt0.(Local.promises)) f0 mem_src0 f1 mem_src1>>)\n.\nProof.\n  inv SIM. inv LOCAL. inv PROMISE.\n  hexploit sim_memory_promise; eauto.\n  { eapply LOCALSRC. }\n  { eapply TVIEW. }\n  i. des.\n  assert (MAPLES: Mapping.les f0 f1).\n  { eapply Mapping.les_strong_les; eauto. }\n  esplits; eauto.\n  { econs; eauto. hexploit sim_closed_memory_sim_message; eauto. i.\n    eapply semi_closed_message_closed; eauto. i. subst.\n    eapply Memory.promise_get0 in CANCEL.\n    { des; eauto. }\n    { inv CANCEL; ss. }\n  }\n  { econs; eauto; ss.\n    { eapply sim_timemap_mon_latest; eauto. }\n    { econs; eauto. ss. eapply sim_tview_mon_latest; eauto. }\n    { ii. specialize (MAXSRC loc0). inv MAXSRC.\n      destruct (Loc.eq_dec loc0 loc).\n      { subst. econs.\n        { i. hexploit MAX; eauto. i. des.\n          esplits. erewrite <- promise_max_readable; eauto.\n        }\n        { ii. eapply NONMAX; auto. erewrite promise_max_readable; eauto. }\n      }\n      { eapply promise_unchanged_loc in CANCEL; eauto.\n        des. econs.\n        { i. hexploit MAX; eauto. i. des.\n          esplits. erewrite <- unchanged_loc_max_readable; eauto.\n        }\n        { ii. eapply NONMAX; auto. erewrite unchanged_loc_max_readable; eauto. }\n      }\n    }\n    { ii. specialize (MAXTGT loc0). inv MAXTGT.\n      destruct (Loc.eq_dec loc0 loc).\n      { subst. econs.\n        i. hexploit MAX; eauto. i. des.\n        esplits. erewrite <- promise_max_readable; eauto.\n      }\n      { eapply promise_unchanged_loc in PROMISE0; eauto.\n        des. econs. i. hexploit MAX; eauto. i. des.\n        esplits. erewrite <- unchanged_loc_max_readable; eauto.\n      }\n    }\n    { i. assert (NEQ: loc0 <> loc).\n      { ii. subst. rewrite FLAG in *. ss. }\n      rewrite MAXTIMES; auto. eapply unchanged_loc_max_ts.\n      2:{ eapply MEMSRC. }\n      { eapply promise_unchanged_loc in CANCEL; eauto. des; eauto. }\n    }\n    { eapply reserved_space_empty_mon_strong; eauto.\n      eapply reserved_space_empty_reserve_decr.\n      { eapply reserved_space_empty_covered_decr; eauto.\n        i. eapply promise_unchanged_loc in CANCEL.\n        { des. inv MEM1. inv COVER. erewrite UNCH in GET. econs; eauto. }\n        { ii. subst. rewrite FLAG in *. ss. }\n      }\n      { i. eapply promise_unchanged_loc in PROMISE0.\n        { des. inv PROM0. erewrite UNCH in GET. eauto. }\n        { ii. subst. rewrite FLAG in *. ss. }\n      }\n    }\n  }\nQed.\n\nLemma sim_thread_racy_write_step\n      f vers flag_src flag_tgt vs_src vs_tgt\n      mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt\n      loc to_tgt ord\n      (SIM: sim_thread\n              f vers flag_src flag_tgt vs_src vs_tgt\n              mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt)\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n      (RACE: Local.racy_write_step lc_tgt mem_tgt loc to_tgt ord)\n      (FLAGSRC: flag_src loc = false)\n      (FLAGTGT: flag_tgt loc = false)\n      (WF: Mapping.wfs f)\n  :\n  exists to_src, Local.racy_write_step lc_src mem_src loc to_src ord.\nProof.\n  inv SIM. inv RACE.\n  exploit sim_local_racy; eauto. i. des.\n  esplits. econs; eauto.\n  eapply sim_local_consistent; eauto.\nQed.\n\nLemma sim_thread_racy_update_step\n      f vers flag_src flag_tgt vs_src vs_tgt\n      mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt\n      loc to_tgt ordr ordw\n      (SIM: sim_thread\n              f vers flag_src flag_tgt vs_src vs_tgt\n              mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt)\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n      (RACE: Local.racy_update_step lc_tgt mem_tgt loc to_tgt ordr ordw)\n      (FLAGSRC: flag_src loc = false)\n      (FLAGTGT: flag_tgt loc = false)\n      (WF: Mapping.wfs f)\n  :\n  exists to_src, Local.racy_update_step lc_src mem_src loc to_src ordr ordw.\nProof.\n  inv SIM. inv RACE.\n  { esplits. econs 1; eauto. eapply sim_local_consistent; eauto. }\n  { esplits. econs 2; eauto. eapply sim_local_consistent; eauto. }\n  { exploit sim_local_racy; eauto. i. des.\n    esplits. econs 3; eauto.\n    eapply sim_local_consistent; eauto.\n  }\nQed.\n\nLemma sim_thread_racy_read_step\n      f vers flag_src flag_tgt vs_src vs_tgt\n      mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt\n      loc to_tgt val_tgt ord\n      (SIM: sim_thread\n              f vers flag_src flag_tgt vs_src vs_tgt\n              mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt)\n      (READ: Local.racy_read_step lc_tgt mem_tgt loc to_tgt val_tgt ord)\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n      (WF: Mapping.wfs f)\n      (FLAGSRC: flag_src loc = false)\n      (FLAGTGT: flag_tgt loc = false)\n  :\n    forall val_src,\n      exists to_src, Local.racy_read_step lc_src mem_src loc to_src val_src ord.\nProof.\n  inv SIM. inv READ. inv RACE.\n  exploit sim_local_racy; eauto. i. des.\n  esplits. 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/sequential/SeqLiftStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.26183453613017654}}
{"text": "Require Import GhostSimulations.\nRequire Import Raft.\nRequire Import RaftRefinementInterface.\n\nRequire Import UpdateLemmas.\nLocal Arguments update {_} {_} {_} _ _ _ _ : simpl never.\n\nRequire Import CommonTheorems.\n\nRequire Import LeaderLogsContiguousInterface.\nRequire Import LogMatchingInterface.\n\nSection LeaderLogsContiguous.\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  Context {lmi : log_matching_interface}.\n\n  Ltac update_destruct_hyp :=\n    match goal with\n    | [ _ : context [ update _ ?y _ ?x ] |- _ ] => destruct (name_eq_dec y x)\n    end.\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 handleRequestVoteReply_spec :\n    forall h st h' t v st',\n      st' = handleRequestVoteReply h st h' t v ->\n      log st' = log st /\\\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  Lemma update_elections_data_requestVoteReply_leaderLogs :\n    forall h h' t r st,\n      leaderLogs (update_elections_data_requestVoteReply h h' t r st) =\n      leaderLogs (fst st) \\/\n      leaderLogs (update_elections_data_requestVoteReply h h' t r st) =\n      (currentTerm (snd st), log (snd st)) :: leaderLogs (fst st).\n  Proof using. \n    intros.\n    unfold update_elections_data_requestVoteReply in *.\n    repeat break_match; intuition.\n    simpl in *.\n    match goal with\n      | |- context [handleRequestVoteReply ?h ?s ?h' ?t ?r] =>\n        pose proof handleRequestVoteReply_spec\n             h s h' t r (handleRequestVoteReply h s h' t r)\n    end. intuition; repeat find_rewrite; intuition.\n    congruence.\n  Qed.      \n\n  Theorem lift_log_matching :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      log_matching (deghost net).\n  Proof using lmi rri. \n    intros.\n    eapply lift_prop; eauto using log_matching_invariant.\n  Qed.\n\n  Theorem logs_contiguous :\n    forall net h,\n      refined_raft_intermediate_reachable net ->\n      contiguous_range_exact_lo (log (snd (nwState net h))) 0.\n  Proof using lmi rri. \n    intros.\n    find_apply_lem_hyp lift_log_matching.\n    unfold log_matching, log_matching_hosts in *.\n    intuition.\n    split.\n    - intros.\n      match goal with\n        | H : forall _ _, _ <= _ <= _ -> _ |- _ =>\n          specialize (H h i);\n            conclude H ltac:(simpl; repeat break_match; simpl in *; repeat find_rewrite; simpl in *;omega)\n      end.\n      break_exists_exists; intuition.\n      simpl in *.\n      repeat break_match; simpl in *; repeat find_rewrite; simpl in *; auto.\n    - intros.\n      cut (eIndex e > 0); intros; try omega.\n      cut (In e (log (nwState (deghost net) h))); intros; eauto.\n      simpl in *. repeat break_match. simpl in *. repeat find_rewrite. simpl in *. auto.\n  Qed.\n    \n  \n  Ltac start :=\n    red; unfold leaderLogs_contiguous; intros;\n    subst; simpl in *; find_higher_order_rewrite;\n    update_destruct_hyp; subst; rewrite_update; eauto; simpl in *.\n\n  Lemma leaderLogs_contiguous_init :\n    refined_raft_net_invariant_init leaderLogs_contiguous.\n  Proof using. \n    split; simpl in *; intuition.\n  Qed.\n\n  Lemma leaderLogs_contiguous_client_request :\n    refined_raft_net_invariant_client_request leaderLogs_contiguous.\n  Proof using. \n    start. \n    find_rewrite_lem update_elections_data_client_request_leaderLogs. eauto.\n  Qed.\n\n  Lemma leaderLogs_contiguous_timeout :\n    refined_raft_net_invariant_timeout leaderLogs_contiguous.\n  Proof using. \n    start.\n    find_rewrite_lem update_elections_data_timeout_leaderLogs. eauto.\n  Qed.\n\n  Lemma leaderLogs_contiguous_append_entries :\n    refined_raft_net_invariant_append_entries leaderLogs_contiguous.\n  Proof using. \n    start.\n    find_rewrite_lem update_elections_data_appendEntries_leaderLogs. eauto.\n  Qed.\n\n  Lemma leaderLogs_contiguous_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply leaderLogs_contiguous.\n  Proof using. \n    start. (* and finish *)\n  Qed.\n    \n\n  Lemma leaderLogs_contiguous_request_vote :\n    refined_raft_net_invariant_request_vote leaderLogs_contiguous.\n  Proof using. \n    start.\n    find_rewrite_lem update_elections_data_requestVote_leaderLogs. eauto.\n  Qed.\n\n  Lemma leaderLogs_contiguous_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply leaderLogs_contiguous.\n  Proof using lmi rri. \n    start.\n    match goal with\n      | [ _ : context [ update_elections_data_requestVoteReply ?d ?s ?t ?v ?st ] |- _ ] =>\n        pose proof update_elections_data_requestVoteReply_leaderLogs\n             d s t v st\n    end. intuition; repeat find_rewrite; eauto.\n    simpl in *; break_or_hyp; eauto.\n    find_inversion.\n    eauto using logs_contiguous.\n  Qed.\n\n  Lemma leaderLogs_contiguous_do_leader :\n    refined_raft_net_invariant_do_leader leaderLogs_contiguous.\n  Proof using. \n    start. replace gd with (fst (nwState net h0)) in *; eauto.\n    find_rewrite; reflexivity.\n  Qed.\n\n  Lemma leaderLogs_contiguous_do_generic_server :\n    refined_raft_net_invariant_do_generic_server leaderLogs_contiguous.\n  Proof using. \n    start. replace gd with (fst (nwState net h0)) in *; eauto.\n    find_rewrite; reflexivity.\n  Qed.\n\n  Lemma leaderLogs_contiguous_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset leaderLogs_contiguous.\n  Proof using. \n    red. unfold leaderLogs_contiguous. intros.\n    find_reverse_higher_order_rewrite. eauto.\n  Qed.\n\n  Lemma leaderLogs_contiguous_reboot :\n    refined_raft_net_invariant_reboot leaderLogs_contiguous.\n  Proof using. \n    start. replace gd with (fst (nwState net h0)) in *; eauto.\n    find_rewrite; reflexivity.\n  Qed.\n\n  Lemma leaderLogs_contiguous_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      leaderLogs_contiguous net.\n  Proof using lmi rri. \n    intros.\n    apply refined_raft_net_invariant; auto.\n    - apply leaderLogs_contiguous_init.\n    - apply leaderLogs_contiguous_client_request.\n    - apply leaderLogs_contiguous_timeout.\n    - apply leaderLogs_contiguous_append_entries.\n    - apply leaderLogs_contiguous_append_entries_reply.\n    - apply leaderLogs_contiguous_request_vote.\n    - apply leaderLogs_contiguous_request_vote_reply.\n    - apply leaderLogs_contiguous_do_leader.\n    - apply leaderLogs_contiguous_do_generic_server.\n    - apply leaderLogs_contiguous_state_same_packet_subset.\n    - apply leaderLogs_contiguous_reboot.\n  Qed.\n\n  Instance llci : leaderLogs_contiguous_interface : Prop.\n  Proof.\n    split.\n    exact leaderLogs_contiguous_invariant.\n  Qed.\nEnd LeaderLogsContiguous.", "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/LeaderLogsContiguousProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2618345307442722}}
{"text": "Require Import LibTactics.\nRequire Import Metalib.Metatheory.\n\nRequire Import\n        syntax_ott\n        syntaxb_ott\n        rules_inf\n        rulesb_inf\n        Infrastructure\n        Infrastructure_b\n        Deterministic\n        Typing_b\n        Typing\n        Type_Safety\n        ttyping.\n\nRequire Import List. Import ListNotations.\nRequire Import Arith Omega.\nRequire Import Strings.String.\n\nRequire Import Omega.\n\nLtac size_ind_auto :=\n  ( eapply_first_lt_hyp ;\n    try reflexivity;\n    try omega ;\n    try eauto ).\n\n\n(* aux both *)\n\nLemma nlam_open3: forall e y,\n  nlam e ->\n  nlam (e ^^ e_var_f y).\nProof.\n  introv nl.\n  inverts nl; unfold open_exp_wrt_exp;simpl; eauto.\n  destruct(lt_eq_lt_dec nat 0).\n  inverts* s.\n  eauto.\nQed.\n\nLemma principle_if: forall v A t,\n    value v -> typing nil v Inf3 A t -> principal_type v = A.\nProof.\n     introv H typ.\n     inductions H; inverts* typ; eauto.\nQed.\n\nLemma principle_if2: forall v A t,\n    value v -> ttyping nil v Inf2 A t -> principal_type v = A.\nProof.\n     introv H typ.\n     inductions H; inverts* typ; eauto.\nQed.\n\n\nLemma TypedReduce_walue3: forall v A v' p b,\n    value v -> TypedReduce v p b A (e_exp v') -> walue v'.\nProof with auto.\n introv val red.\n forwards*: Tred_value red.\n forwards*: value_group H.\n inverts* H0. inverts H1. inverts H0. inverts H1.\n inverts* H. inverts* red; try solve[forwards*: abs_nlam].\nQed.\n\n\n\n\nLemma sim_refl: forall A,\n sim A A.\nProof.\n  intros.\n  inductions A; eauto.\nQed.\n\n\nLemma fillb_cast: forall v A p b B,\n  (trm_cast v A p b B) = (fillb (castCtxb A p b B )  v).\nProof.\n  introv.\n  eauto.\nQed.\n\n\nLemma fillb_appl: forall e1 e2,\n  (trm_app e1 e2) = (fillb (appCtxLb e2)  e1).\nProof.\n  introv.\n  eauto.\nQed.\n\n\nLemma fillb_appr: forall e1 e2,\n  (trm_app e1 e2) = (fillb (appCtxRb e1)  e2).\nProof.\n  introv.\n  eauto.\nQed.\n\nParameter label : atom.\n\n(* one *)\n\n\nLemma ttyping_chk: forall G e A t,\n  ttyping G e Inf2 A t ->\n  exists l b B tt, ttyping G e (Chk2 l b tt) B t.\nProof.\n  introv Typ.\n  inductions Typ; eauto; try solve[exists label true; eapply ttyp_sim; eauto;unfold not; intros nt; inverts* nt; inverts H0];\n  try solve[exists label true; exists;eapply ttyp_sim; eauto;unfold not; intros nt; inverts* nt; inverts H1];\n  try solve[exists label true; eapply ttyp_sim; eauto;unfold not; intros nt; inverts* nt; inverts H];\n  try solve[exists label true; eapply ttyp_sim; eauto;unfold not; intros nt; inverts* nt; inverts H2].\n  exists l b. exists.\n  eapply ttyp_abs; eauto.\n  exists l b. exists.\n  pick fresh y and apply ttyp_abs2;eauto.\nQed.\n\n\n\nLemma value_valueb_chk: forall e t A l b tt,\n ttyping nil e (Chk2 l b tt) A t -> value e ->\n valueb t.\nProof.\n  introv typ H. gen A l b tt t.\n  inductions H; intros;\n  try solve[inverts typ;inverts* H4].\n  -\n    forwards*: ttyping_regular_3 typ.\n    inverts typ; eauto.\n    inverts H0. \n    apply valueb_dyn; eauto.\n    inverts H0. \n    eapply valueb_dyn; eauto.\n    inverts* H6.\n  -\n    inverts typ. inverts* H6. \n    forwards*: IHvalue. inverts* H11.\n    forwards*: principle_if2 H7.\n    rewrite H2 in *; inverts* H0.\n  -\n    forwards*: ttyping_regular_3 typ.\n    inverts typ. inverts* H7. \n    forwards*: IHvalue. inverts* H12;\n    try solve[forwards*: abs_nlam].\n    forwards*: principle_if2 H8.\n    rewrite H3 in *; inverts* H0.\nQed.\n\n\n\n\nLemma valueb_value_chk: forall e t A l b tt,\n ttyping nil e (Chk2 l b tt) A t -> valueb t ->\n value e.\nProof.\n  introv typ H. gen A l b tt e.\n  inductions H; intros;\n  try solve[inverts typ;inverts* H4; inverts* H;\n  inverts* H11].\n  -\n    forwards*: ttyping_regular_1 typ.\n    inverts typ; eauto. inverts* H6.\n    inverts* H1; try solve[inverts* H0].\n    inverts* H13.\n  -\n    inverts typ. inverts* H5. \n    forwards*: IHvalueb. inverts* H7.\n    forwards*: principle_if2 H6.\n    inverts* H0. inverts H12.\n  -\n    forwards*: ttyping_regular_1 typ.\n    inverts* typ. inverts* H7.\n    forwards*: IHvalueb.\n    inverts* H9.  \n    forwards*: principle_if2 H8.\n    rewrite <- H3 in *; eauto.\n    inverts H2. \n    eapply value_dyn; eauto.\n    eapply value_dyn; eauto.\n    inverts* H14.\nQed.\n\n\nLemma value_valueb: forall dir e t A,\n ttyping nil e dir A t -> value e ->\n valueb t.\nProof.\n  introv typ H. \n  destruct dir.\n  -\n  forwards*: ttyping_chk typ. lets(ll&bb&tb&tt&typp):H0.\n  forwards*: value_valueb_chk typp.\n  -\n  forwards*: value_valueb_chk typ.\nQed.\n\n\n\nLemma valueb_value: forall dir e t A,\n ttyping nil e dir A t -> valueb t ->\n value e.\nProof.\n  introv typ H. \n  destruct dir.\n  -\n  forwards*: ttyping_chk typ. lets(ll&bb&tb&tt&typp):H0.\n  forwards*: valueb_value_chk typp.\n  -\n  forwards*: valueb_value_chk typ.\nQed.\n\n\n\nDefinition Ttyping_typing G dir e A  := \n   match dir with \n    | Chk2 l b B => Typing G e Chk A \n    | _   => Typing G e Inf A\n   end.\n\nLemma ttyping_typing: forall G dir e  A t,\n ttyping G e dir A t ->\n Ttyping_typing G dir e A.\nProof.\n  introv typ.\n  inductions typ; unfold Ttyping_typing in *; intros; eauto.\n  eapply Typ_app; eauto.\n  inverts* IHtyp2.\n  eapply Typ_app; eauto.\n  inverts* IHtyp2.\nQed.\n\n\nLemma typing_ttyping: forall G e t A B,\n ttyping G e Inf2 A t ->\n Typing G e Inf B ->\n A = B.\nProof.\n  introv typ1 typ2. gen B.\n  inductions typ1;intros; \n  try solve[inductions typ2; eauto].\n  -\n    inverts* typ2.\n    forwards*: binds_unique H0 H4.\n  -\n    inverts typ2.\n    forwards*: IHtyp1_1 H6.\n    inverts* H. inverts* H3.\n  -\n    inverts typ2.\n    forwards*: IHtyp1_1 H6.\n    inverts* H.\n    inverts* H3.\n  -\n      inverts typ2.\n    forwards*: IHtyp1_1 H2.\n    inverts* H0.\nQed.\n\n\n(* one aux*)\n\nLemma tTypedReduce_completeness: forall v t B A t' l b ,\n    ttyping nil v (Chk2 l b B) A t ->\n    valueb t ->\n    bstep (trm_cast t l b B A) (t_term t') ->\n    (exists  n t2 v',  bbsteps t' (t_term t2) n /\\ TypedReduce v l b A (e_exp v') /\\\n    ttyping nil v' Inf2 A t2 /\\ 0<=n <= 1) \\/ (bstep t' (t_blame l b) /\\ (TypedReduce v l b A (e_blame l b))).\nProof.\n    introv typ val red.\n    forwards*: valueb_value val.\n    inductions red; try solve[inverts* H].\n    -\n      destruct E; unfold fillb; inverts x;\n      try forwards*: bstep_not_value red.\n    -\n      inverts* typ. inverts* H5. \n      left. exists*. \n      inverts* H0;try solve[forwards*: abs_nlam].\n    -\n      inverts* typ. \n      left. exists.\n      splits*.\n      left.\n      exists.\n      splits*.\n      forwards*: principle_if2 H6.\n      inverts H0; inverts H1.\n      left.\n      exists. splits*.\n    -\n      inverts* H2. inverts* typ.\n      forwards*: principle_if2 H10.\n      left.\n      exists. splits*.\n      eapply TReduce_anyd.\n      rewrite H2.\n      unfold FLike.\n      splits*.\n      eapply ttyp_anno; eauto.\n    -\n    inverts* H2. \n    inverts H3;inverts* typ; try solve[inverts* H9];\n    try solve[forwards*: abs_nlam];\n    try solve[inverts H11].\n    inverts H4; try solve[inverts* H2].\n    +\n    inverts H11. inverts H6. inverts H11.\n    right. rewrite fillb_cast.\n    rewrite fillb_cast.\n    splits.\n    apply blame_stepb;eauto.\n    simpl.\n    eapply bStep_vanyp;eauto.\n    inverts* H13.\n    unfold not;intros nt;inverts* nt.\n    inverts* H13.\n    eapply TReduce_blame;simpl;eauto.\n    unfold not;intros nt;inverts* nt.\n    +\n    forwards* h1: ttyping_regular_3 H11.\n    inverts H11; try solve[forwards*: abs_nlam]. \n    inverts H17; try solve[forwards*: abs_nlam].\n    inverts h1.  \n    left.\n    exists. splits.\n    eapply sstar_one.\n    rewrite fillb_cast.\n    apply do_stepb;eauto.\n    eapply TReduce_adyn; simpl;eauto.\n    unfold FLike; splits*.\n    eapply ttyp_anno; eauto.\n    omega. omega.\n    inverts h1.  \n    left.\n    exists. splits.\n    eapply sstar_one.\n    rewrite fillb_cast.\n    apply do_stepb;eauto.\n    eapply TReduce_adyn; simpl;eauto.\n    unfold FLike; splits*.\n    eapply ttyp_anno; eauto.\n    omega. omega.\n    +\n    inverts H2.\n    inverts H11.\n    forwards* h1: ttyping_regular_3 H9.\n    inverts val. inverts H12.\n    inverts H9. inverts H13; try solve[].\n    inverts H9.\n    left.\n    exists. splits.\n    eapply sstar_one.\n    rewrite fillb_cast.\n    apply do_stepb;eauto.\n    eapply  TReduce_dyna; simpl;eauto.\n    unfold FLike; splits*.\n    eapply ttyp_anno; eauto.\n    omega.\n    omega.\n    -\n      inverts* typ. \n      inverts H7; try solve[inverts H2;try solve[inverts H14]].\n      +\n      inverts H9; try solve[forwards*: abs_nlam].\n      forwards*: valueb_value H7.\n      forwards*: principle_if2 H7.\n      rewrite <- H3.\n      left.\n      exists. splits*.\n      rewrite H3; auto.\n      +\n      inverts H2;try solve[forwards*: abs_nlam].\n      left.\n      exists.\n      splits*.\n      left.\n      exists.\n      splits*.\nQed.\n\nLemma value_tred_keep3: forall v A l b t,\n ttyping nil (e_anno v l b A) Inf2 A t ->\n value (e_anno v l b A) ->\n TypedReduce v l b A (e_exp (e_anno v l b A)).\nProof.\n introv typ val.\n inverts* val; simpl in *; eauto.\n inverts H1; inverts* H4.\n -\n inverts typ. inverts* H4. inverts* H7.\n -\n inverts typ. inverts* H2. inverts* H5.\n -\n inverts typ. inverts* H2. inverts* H5.\nQed.\n\n\nLemma value_anno:forall v t l b,\n value(e_anno v l b t) ->\n value v.\nProof.\n  introv val.\n  inverts* val.\nQed.\n\n\nLemma val_nlam_wal: forall v,\n value v ->\n nlam v ->\n walue v.\nProof.\n  introv val nl.\n  inductions val; try solve[inverts* nl].\n  -\n  inductions val;eauto.\n  -\n  inductions val;eauto.\nQed.\n\n\nLemma tTypedReduce_nlambda2: forall v t A B v' p b,\n    value v -> ttyping nil v (Chk2 p b B) A t -> TypedReduce v p b A (e_exp v') -> nlam v'.\nProof with auto.\n introv val typ red.\n inductions red; eauto.\nQed.\n\nLemma tTypedReduce_walue2: forall v A B v' t p b,\n    value v -> ttyping nil v (Chk2 p b B) A t -> TypedReduce v p b A (e_exp v') -> walue v'.\nProof with auto.\n introv val typ red.\n forwards*: Tred_value red.\n forwards*: value_group H.\n inverts* H0. inverts H1. inverts H0. inverts H1.\n forwards*: tTypedReduce_nlambda2 red.\n inverts* H0. \nQed.\n\nTheorem typing_elaborate_completeness_gen1: forall l b B e t t' A n,\n  size_exp e + size_term t < n ->\n  ttyping nil e (Chk2 l b B) A t ->\n  bstep t (t_term t') ->\n  (exists e' t'' n, bbsteps t' (t_term t'') n /\\ steps e (e_exp e') /\\ ttyping nil e' (Chk2 l b B) A t''  /\\ 0<=n<=1) \\/\n  exists l b, (bstep t' (t_blame l b)) /\\ steps e (e_blame l b).\nProof.\n  introv sz Typ Red. gen l b B e t t' A.\n  induction n; intros; try omega.\n  lets Red': Red.\n  inductions Red; intros.\n  - clear IHRed.\n     destruct E; unfold fillb in *; simpl in *.\n    +\n    forwards* lc: ttyping_regular_1 Typ.\n    inverts Typ; simpl in *.\n    inverts H5; try solve[inverts H0;inverts* H6]; simpl in *.\n    *\n      forwards*: ttyping_chk H4.\n      lets(ll1&bb1&tb1&tb2&ttyp1):H0.\n      forwards*: IHn Red ttyp1. simpl in *; omega.\n      forwards* lc1:ttyping_regular_3 H7. \n      inverts H1.\n      --\n      lets(vv1&vv2&nn1&rred2&rred1&ttyp2&sz1): H2.\n      inverts lc.\n      forwards*: steps_nlam rred1.\n      unfold not;intros nt. \n      lets (ee& ll & bb&hh1):nt. inverts hh1.\n      forwards*: value_valueb ttyp1; \n      forwards*: bstep_not_value Red.\n      inverts ttyp2;\n      try solve[exfalso; apply H1; eauto].\n      forwards*: ttyping_typing H4; simpl in *.\n      forwards*: preservation_multi_step rred1.\n      forwards*: typing_ttyping H14 H6. \n      subst*.\n      left.\n      exists. splits.\n      apply mmulti_red_app2.\n      auto. apply rred2.\n      apply multi_rred_app2.\n      auto. apply rred1.\n      eapply ttyp_sim; eauto.\n      omega. omega.\n      --\n      lets(ll&bb&rred1&rred2): H2.\n      right. exists.\n      splits.\n      rewrite fillb_appl.\n      apply blame_stepb; auto.\n      apply rred1.\n      inverts lc.\n      apply multi_bblame_app2.\n      auto. auto.\n    *\n      inverts lc.\n      destruct(value_decidable e0); auto.\n      ++\n      lets red: Red.\n      forwards*: value_valueb H4.\n      inverts Red;\n      try solve[\n        destruct E; unfold fillb in *; inverts* H3;\n        forwards*: bstep_not_value H11\n      ];\n      try solve[exfalso; apply H15; eauto].\n      inverts H0; try solve[inverts H4].\n      forwards*: tTypedReduce_completeness red.\n      inverts H0.\n      --\n      inverts H.\n      lets(vv1&vv2&nn1&rred2&rred1&ttyp2&sz1): H11.\n      left.\n      exists. splits.\n      apply mmulti_red_app2.\n      auto.\n      apply rred2.\n      eapply stars_trans.\n      apply stars_one.\n      apply Step_betad; eauto.\n      rewrite fill_app.\n      apply stars_one.\n      apply do_step; eauto.\n      apply Step_annov; eauto.\n      unfold not;intros nt;inverts* nt. inverts H18.\n      unfold fill.\n      eapply ttyp_sim; eauto.\n      omega. omega.\n      --\n      lets(rred1&rred2): H11.\n      right. exists.\n      splits.\n      rewrite fillb_appl.\n      apply blame_stepb; auto.\n      apply rred1.\n      eapply stars_transb.\n      apply stars_one.\n      apply Step_betad;eauto.\n      apply step_b.\n      rewrite fill_appl.\n      eapply blame_step;eauto.\n      eapply Step_annov;eauto.\n      unfold not;intros nt;inverts* nt. inverts H18.\n      ++\n      assert(not (valueb t1)).\n      unfold not;intros nt.\n      forwards*: valueb_value H4.\n      inverts* Red;\n      try solve[ destruct E; unfold fillb in *;\n       inverts* H3].\n       --\n       destruct E; unfold fillb in *;\n       inverts* H3.\n       forwards*: ttyping_chk H4.\n       lets(ll1&bb1&tb1&tb2&ttyp1):H3.\n       forwards*: IHn H11. simpl in *;omega.\n       inverts H5.\n       ---\n       lets(vv1&vv2&nn1&rred2&rred1&ttyp2&sz1): H12.\n       forwards*: ttyping_typing H4;simpl in H12.\n       forwards*: preservation_multi_step rred1.\n       forwards*: steps_nlam rred1.\n       unfold not; intros nt.  lets (ee& ll & bb&hh1):nt. inverts hh1.\n       exfalso; apply H0; eauto.\n       inverts ttyp2; \n       try solve[exfalso; apply H14;eauto].\n       forwards*: typing_ttyping H20.\n       inverts H15.\n       inverts H.\n       left.\n       exists. splits.\n       apply mmulti_red_app2.\n       auto.\n       apply mmulti_red_cast.\n       apply rred2.\n       apply multi_rred_app2. auto.\n       apply rred1.\n       eapply ttyp_sim; eauto.\n       omega. omega.\n       ---\n       lets(ll&bb&rred1&rred2): H12.\n       right. exists.\n       splits.\n       rewrite fillb_appl.\n       apply blame_stepb; auto.\n       rewrite fillb_cast.\n       apply blame_stepb; auto.\n       apply rred1.\n       apply multi_bblame_app2.\n       auto. auto.\n       --\n       inverts H4.\n       inverts H16.\n       forwards*: valueb_value H13.\n       forwards*: principle_if2 H13.\n       rewrite <- H4 in H10.\n       exfalso; apply H0; eauto.\n       forwards*: ttyping_regular_1 H3.\n       exfalso; apply H0; eauto.\n    *\n      forwards*: ttyping_chk H2.\n      lets(ll1&bb1&tb1&tb2&ttyp1):H0.\n      forwards*: IHn Red ttyp1. simpl in *; omega.\n      forwards* lc1:ttyping_regular_3 H6. \n      inverts H1.\n      --\n      lets(vv1&vv2&nn1&rred2&rred1&ttyp2&sz1): H3.\n      inverts lc.\n      forwards*: steps_nlam rred1.\n      unfold not;intros nt.  \n      lets (ee& ll & bb&hh1):nt. inverts hh1.\n      forwards*: value_valueb ttyp1; \n      forwards*: bstep_not_value Red.\n      inverts ttyp2;\n      try solve[exfalso; apply H1; eauto].\n      forwards*: ttyping_typing H2; simpl in *.\n      forwards*: preservation_multi_step rred1.\n      forwards*: typing_ttyping H15 H11. \n      subst*.\n      left.\n      exists. splits.\n      apply mmulti_red_app2.\n      auto. apply rred2.\n      apply multi_rred_appv2.\n      auto. apply rred1.\n      eapply ttyp_sim; eauto.\n      omega. omega.\n      --\n      lets(ll&bb&rred1&rred2): H3.\n      right. exists.\n      splits.\n      rewrite fillb_appl.\n      apply blame_stepb; auto.\n      apply rred1.\n      inverts lc.\n      apply multi_bblame_appv2.\n      auto. auto.\n    +\n     forwards* lc: ttyping_regular_1 Typ.\n     inverts Typ; simpl in *.\n     inverts H5; try solve[inverts H0;inverts* H6]; simpl in *.\n     *\n      inverts lc.\n      inverts H7; try solve[\n        forwards*: value_valueb H13;\n        forwards*: bstep_not_value Red\n      ].\n      destruct(value_decidable e3); auto.\n      ++\n      forwards*: value_valueb H13.\n      forwards*: tTypedReduce_completeness Red.\n      inverts H3.\n      ---\n      lets(vv1&vv2&nn1&rred2&rred1&ttyp2&sz1): H7.\n      inverts H.\n      forwards*: valueb_value H4.\n      forwards*: principle_if2 H4.\n      forwards*: tTypedReduce_walue2 rred1.\n      left.\n      exists. splits.\n      apply mmulti_red_app. auto.\n      apply rred2.\n      apply stars_one.\n      eapply Step_equal; simpl;eauto.\n      eapply ttyp_sim; eauto.\n      omega. omega.\n      ---\n      lets(rred1&rred2): H7.\n      inverts H.\n      forwards* h1: valueb_value H4.\n      forwards* h2: principle_if2 H4.\n      right. exists.\n      splits.\n      rewrite fillb_appr.\n      apply blame_stepb; auto.\n      apply rred1.\n      apply step_b.\n      eapply Step_betap;eauto.\n      ++\n      assert(not(valueb t0)).\n      unfold not;intros nt. forwards*: valueb_value H13.\n      lets red: Red.\n      inverts Red;\n      try solve[destruct E; unfold fill in *; inverts H3;\n      try solve[forwards*: bstep_not_value H7]];\n      try solve[exfalso; apply H1; eauto].\n      destruct E; unfold fill in *; inverts H3; simpl in *.\n      forwards*: IHn H13. simpl in *; omega.\n      inverts H3.\n      ---\n      lets(vv1&vv2&nn1&rred2&rred1&ttyp2&sz1): H7.\n      forwards*: valueb_value H4.\n      inverts* H.\n      inverts H.\n      forwards*: principle_if2 H4.\n      left.\n      exists. splits.\n      apply mmulti_red_app.\n      auto.\n      apply mmulti_red_cast.\n      apply rred2.\n      eapply multi_rred_app.\n      apply H.\n      auto. \n      apply rred1.\n      apply ttyp_sim; eauto.\n      eapply ttyp_app; eauto.\n      forwards*: steps_not_nlam rred1.\n      omega.\n      omega.\n      ---\n      lets(ll&bb&rred1&rred2): H7.\n      inverts H.\n      forwards*: valueb_value H4.\n      forwards* h1: principle_if2 H4.\n       right. exists.\n       splits.\n       rewrite fillb_appr.\n       apply blame_stepb; auto.\n       rewrite fillb_cast.\n       apply blame_stepb; auto.\n       apply rred1.\n       eapply multi_bblame_app; simpl.\n       apply h1.\n       auto. auto.\n    *\n      inverts H. inverts* H1.\n    *\n      inverts H.\n      forwards* h1: valueb_value H2.\n      forwards*: ttyping_chk H6.\n      lets(ll1&bb1&tb1&tb2&ttyp1):H.\n      forwards*: IHn Red. simpl in *. omega.\n      inverts H0.\n      lets(vv1&vv2&nn1&rred2&rred1&ttyp2&sz1): H3.\n      --\n      forwards* h2: steps_nlam rred1.\n      inverts ttyp2; try solve[\n        exfalso; apply h2; eauto\n      ].\n      forwards*: ttyping_typing H6. \n      forwards* h3: preservation_multi_step rred1. \n      forwards*: typing_ttyping H12 h3. \n      subst*.\n      left.\n      exists. splits.\n      apply mmulti_red_app.\n      auto.\n      apply rred2.\n      eapply multi_rred_appv.\n      auto.\n      apply rred1.\n      apply ttyp_sim; eauto.\n      omega.\n      omega.\n      --\n      lets(ll&bb&rred1&rred2): H3.\n      right. exists.\n      splits.\n      rewrite fillb_appr.\n      apply blame_stepb; auto.\n      apply rred1.\n      apply multi_bblame_appv.\n      auto.\n      auto. \n    +\n      forwards* lc: ttyping_regular_3 Typ. inverts lc.\n      inverts Typ;\n      try solve[forwards*: bstep_not_value Red].\n      forwards* lc2: ttyping_regular_1 H6.\n      inverts H6;\n      try solve[inverts* H0; try solve[\n        inverts lc2;\n      forwards*: bstep_not_value Red\n      ]; try solve[inverts H13]].\n      forwards*: IHn H8. simpl in *; omega.\n      inverts H0.\n      lets(vv1&vv2&nn1&rred2&rred1&ttyp2&sz1): H2.\n      --\n      left.\n      exists. splits.\n      apply mmulti_red_cast.\n      apply rred2.\n      apply multi_rred_anno.\n      apply rred1.\n      forwards*: steps_not_nlam rred1. \n      omega. omega.\n      --\n      lets(ll&bb&rred1&rred2): H2.\n      right. exists.\n      splits.\n      rewrite fillb_cast.\n      apply blame_stepb; auto.\n      apply rred1.\n      apply multi_bblame_anno.\n      auto. \n  -\n    forwards lc: ttyping_regular_1 Typ.\n    inverts* Typ; try solve[inverts H1;inverts* H11].\n    inverts H6; try solve[inverts H1;inverts H13].\n    +\n      forwards*: valueb_value H8.\n      inverts* H5.\n      --\n      forwards*: valueb_value H8.\n      forwards*: value_tred_keep3 H2.\n      forwards*: value_anno H2.\n      inverts lc.\n      forwards*: TypedReduce_walue3 H3.\n      left.\n      exists. splits.\n      apply bbstep_refl.\n      eapply stars_trans.\n      apply stars_one.\n      eapply Step_equal; simpl;eauto.\n      apply stars_one.\n      eapply Step_nbeta; simpl;eauto.\n      unfold open_term_wrt_term; simpl.\n      assert((open_term_wrt_term_rec 0 v t0) = (open_term_wrt_term t0 v)); eauto.\n      rewrite H6.\n      forwards*: walue_nlam H5.\n      pick fresh y.\n      forwards*: nlam_open2 y H11 H13.\n      rewrite (subst_exp_intro y); eauto.\n      rewrite (subst_term_intro y); eauto.\n      forwards*: H12 y.\n      eapply ttyp_sim; eauto.\n      eapply ttyp_anno; eauto.\n      eapply ttyping_c_subst_simpl; eauto.\n      forwards*: nlam_open3 y H13.\n      forwards*: nlam_open2 y H11 H17.\n      omega. omega.\n      --\n      forwards*: valueb_value H8.\n      forwards*: value_tred_keep3 H2.\n      forwards*: value_anno H2.\n      inverts lc. \n      forwards*: TypedReduce_walue3 H3.\n      forwards*: nlam_exist H13. inverts H6.\n      inverts H11. inverts H6.\n      unfold open_term_wrt_term; simpl.\n      pick fresh y. \n       forwards*: not_nlam_open (e_anno e2 l1 b0 t_dyn) y H13.\n      left.\n      exists. splits.\n      apply bbstep_refl.\n      eapply stars_trans.\n      apply stars_one.\n      eapply Step_equal;simpl; eauto.\n      apply stars_one.\n      apply Step_nbeta; eauto.\n      assert((open_term_wrt_term_rec 0 v t0) = (open_term_wrt_term t0 v)); eauto.\n      rewrite H11.\n      rewrite (subst_exp_intro y); eauto.\n      rewrite (subst_term_intro y); eauto.\n      forwards*: H12 y.\n      unfold open_term_wrt_term; simpl in *.\n      forwards*: ttyping_c_subst_simpl H14 H8.\n      omega. omega.\n      --\n      inverts H2; try solve[inverts H15].\n      ++\n      forwards*: valueb_value H8.\n      forwards*: value_tred_keep3 H2.\n      forwards*: value_anno H2.\n      inverts lc. inverts H11.\n      forwards*: TypedReduce_walue3 H3.\n      left.\n      exists. splits.\n      apply bbstep_refl.\n      eapply stars_trans.\n      apply stars_one.\n      eapply Step_equal; simpl;eauto.\n      apply stars_one.\n      eapply Step_beta; simpl;eauto.\n      unfold open_term_wrt_term; simpl.\n      assert((open_term_wrt_term_rec 0 v t0) = (open_term_wrt_term t0 v)); eauto.\n      rewrite H11.\n      forwards*: walue_nlam H5.\n      pick fresh y.\n      forwards*: nlam_open2 y H18 H12.\n      rewrite (subst_exp_intro y); eauto.\n      rewrite (subst_term_intro y); eauto.\n      forwards*: H6 y.\n      eapply ttyp_sim; eauto.\n      eapply ttyp_anno; eauto.\n      eapply ttyping_c_subst_simpl; eauto.\n      forwards*: nlam_open3 y H18.\n      forwards*: nlam_open2 y H12 H16.\n      omega. omega.\n      ++\n      forwards*: valueb_value H8.\n      forwards*: value_tred_keep3 H2.\n      forwards*: value_anno H2.\n      inverts lc. inverts H11.\n      forwards*: TypedReduce_walue3 H3.\n      forwards*: nlam_exist H18. \n      inverts H11.\n      inverts H12. inverts H11.\n      unfold open_term_wrt_term; simpl.\n      pick fresh y.\n      forwards*: not_nlam_open (e_anno e2 l1 b0 t_dyn) y H18. \n      left.\n      exists. splits.\n      apply bbstep_refl.\n      eapply stars_trans.\n      apply stars_one.\n      eapply Step_equal;simpl; eauto.\n      apply stars_one.\n      apply Step_beta; eauto.\n      assert((open_term_wrt_term_rec 0 v t0) = (open_term_wrt_term t0 v)); eauto.\n      rewrite H12.\n      rewrite (subst_exp_intro y); eauto.\n      rewrite (subst_term_intro y); eauto.\n      forwards*: H6 y.\n      unfold open_term_wrt_term; simpl in *.\n      forwards*: ttyping_c_subst_simpl H13 H8.\n      omega. omega. \n    +\n      inverts H3.\n      --\n      forwards* h2: valueb_value H7.\n      inverts lc.\n      forwards*: val_nlam_wal h2 H11.\n      left.\n      exists. splits.\n      apply bbstep_refl.\n      apply stars_one.\n      apply Step_nbeta; eauto.\n      unfold open_term_wrt_term; simpl.\n      assert((open_term_wrt_term_rec 0 v t0) = (open_term_wrt_term t0 v)); eauto.\n      rewrite H2.\n      pick fresh y.\n      forwards*: nlam_open2 y H11 H13.\n      rewrite (subst_exp_intro y); eauto.\n      rewrite (subst_term_intro y); eauto.\n      forwards*: H12 y.\n      eapply ttyp_sim; eauto.\n      eapply ttyp_anno; eauto.\n      eapply ttyping_c_subst_simpl; eauto.\n      forwards*: nlam_open3 y H13.\n      forwards*: nlam_open2 y H11 H8.\n      omega. omega.\n      --\n      forwards* h2: valueb_value H7.\n      inverts lc.\n      forwards*: val_nlam_wal h2 H11.\n      forwards* h1: nlam_exist H13. \n      lets (ee& ll & bb&hh1): h1. inverts hh1.\n      unfold open_term_wrt_term; simpl.\n      pick fresh y.\n      forwards*: not_nlam_open e2 y H13.\n      left.\n      exists. splits.\n      apply bbstep_refl.\n      apply stars_one.\n      apply Step_nbeta; eauto.\n      assert((open_term_wrt_term_rec 0 v t0) = (open_term_wrt_term t0 v)); eauto.\n      rewrite H5.\n      rewrite (subst_exp_intro y); eauto.\n      rewrite (subst_term_intro y); eauto.\n      forwards*: H12 y.\n      unfold open_exp_wrt_exp in *.\n      simpl in *.\n      forwards*:ttyping_c_subst_simpl H6 H7.\n      omega. omega.\n      --\n      inverts* H1; try solve[forwards*: abs_nlam].\n      ---\n      inverts lc. inverts H3.\n      forwards* h2: valueb_value H7.\n      forwards*: val_nlam_wal h2 H11.\n      left.\n      exists. splits.\n      apply bbstep_refl.\n      apply stars_one.\n      apply Step_beta; eauto.\n      unfold open_term_wrt_term; simpl.\n      assert((open_term_wrt_term_rec 0 v t0) = (open_term_wrt_term t0 v)); eauto.\n      rewrite H3.\n      pick fresh y.\n      forwards*: nlam_open2 y H11 H18.\n      rewrite (subst_exp_intro y); eauto.\n      rewrite (subst_term_intro y); eauto.\n      forwards*: H5 y.\n      eapply ttyp_sim; eauto.\n      eapply ttyp_anno; eauto.\n      eapply ttyping_c_subst_simpl; eauto.\n      forwards*: nlam_open3 y H18.\n      forwards*: nlam_open2 y H11 H12.\n      omega. omega.\n      ---\n      forwards*: nlam_exist H18. inverts H1.\n      inverts H2. inverts H1.\n      unfold open_term_wrt_term; simpl.\n      pick fresh y.\n      forwards*: not_nlam_open e2 y H18.\n      inverts lc. inverts H4.\n      forwards* h2: valueb_value H7.\n      forwards* h3: val_nlam_wal h2. \n      left.\n      exists. splits.\n      apply bbstep_refl.\n      apply stars_one.\n      apply Step_beta; eauto.\n      assert((open_term_wrt_term_rec 0 v t0) = (open_term_wrt_term t0 v)); eauto.\n      rewrite H2.\n      rewrite (subst_exp_intro y); eauto.\n      rewrite (subst_term_intro y); eauto.\n      forwards*: H5 y.\n      unfold open_exp_wrt_exp in *.\n      simpl in *.\n      forwards*:ttyping_c_subst_simpl H4 H7.\n      omega. omega. \n  -\n   forwards lc: ttyping_regular_1 Typ.\n    inverts Typ. inverts H4;\n    try solve[inverts* H;try solve[forwards*: abs_nlam]].\n    inverts H6. inverts H4; try solve[inverts* H;try solve[forwards*: abs_nlam]].\n    left.\n    exists.\n    splits.\n    apply bbstep_refl.\n    apply stars_one.\n    apply Step_annov; eauto.\n    unfold not;intros nt. inverts nt.\n    inverts* H7.\n    omega. omega.\n  -\n    forwards lc: ttyping_regular_1 Typ.\n    inverts Typ. inverts H6;\n    try solve[inverts* H1;inverts* H7].\n    +\n      inverts H5; try solve[inverts* H1;inverts* H7].\n      inverts H11; try solve[exfalso; apply H15; eauto];\n      try solve[inverts* H1;inverts* H7];\n      try solve[forwards*: abs_nlam].\n      forwards*: valueb_value H8.\n      forwards*: value_anno H1.\n      inverts H. \n      forwards*: valueb_value H6.\n      inverts lc.\n      inverts H6;try solve[inverts* H14];\n      try solve[inverts* H].\n      --\n      forwards*: value_tred_keep3 H1.\n      forwards*: TypedReduce_walue3 H6.\n      inverts H.\n      inverts H13.\n      forwards* h3: val_nlam_wal H18.\n      left.\n      exists. splits.\n      apply bbstep_refl.\n      eapply stars_trans.\n      apply stars_one.\n      eapply Step_equal; simpl;eauto.\n      eapply value_fanno;eauto. reflexivity.\n      apply stars_one.\n      eapply Step_abeta; eauto.\n      eapply walue_fanno;eauto. simpl;reflexivity.\n      simpl; reflexivity.\n      eapply ttyp_sim; eauto.\n      eapply ttyp_anno; eauto.\n      eapply ttyp_sim; eauto.\n      omega. omega.\n      --\n      forwards*: value_tred_keep3 H1.\n      forwards*: TypedReduce_walue3 H5.\n      inverts H.\n      inverts H13.\n      inverts H7. inverts H11.\n      left.\n      exists. splits.\n      apply bbstep_refl.\n      eapply stars_trans.\n      apply stars_one.\n      eapply Step_equal; simpl;eauto.\n      eapply value_fanno;eauto. reflexivity.\n      apply stars_one.\n      eapply Step_abeta; eauto.\n      eapply walue_fanno;eauto. simpl;reflexivity.\n      simpl;reflexivity.\n      eapply ttyp_sim; eauto.\n      eapply ttyp_anno; eauto.\n      eapply ttyp_sim; eauto.\n      omega. omega.\n    +\n      forwards*: valueb_value H3.\n      inverts H. \n      forwards*: valueb_value H7.\n      inverts lc.  \n      inverts H3;try solve[inverts* H17];\n      try solve[inverts* H].\n      --\n      forwards* h2: valueb_value H16.\n      forwards* h3: val_nlam_wal h2.\n      forwards* h4: valueb_value H7.\n      forwards* h5: val_nlam_wal h4.\n      inverts H1.\n      inverts H16; try solve[inverts h3].\n      inverts H19.\n      forwards* h6: principle_if2 H14.\n      rewrite h6 in *. inverts H15.\n      left.\n      exists. splits.\n      apply bbstep_refl.\n      apply stars_one.\n      eapply Step_abeta; eauto.\n      eapply ttyp_sim; eauto.\n      eapply ttyp_anno; eauto.\n      omega. omega.\n      --\n      inverts H1; simpl in *. inverts H16.\n      inverts* H2; try solve[forwards*: abs_nlam].\n  -\n    inverts Typ; try solve[inverts H0;inverts* H6].\n    inverts H5; try solve[inverts* H0;inverts* H6].\n    forwards*: tTypedReduce_completeness H7 Red'.\n    inverts H0.\n    *\n    lets(nn1&tt1&vv1&rred1&rred2&ttyp1&eq1): H1.\n    forwards*: ttyping_regular_1 H7.\n    forwards*: valueb_value H7.\n    forwards*: tTypedReduce_nlambda2 rred2.\n    forwards*: value_decidable (e_anno e0 p b0 t_dyn).\n    inverts H4.\n    +\n    forwards*: value_tred_keep2 rred2. inverts H4.\n    left.\n    exists. splits.\n    apply rred1.\n    apply step_refl.\n    apply ttyp_sim;auto.\n    omega. omega.\n    +\n    left.\n    exists. splits.\n    apply rred1.\n    apply stars_one.\n    apply Step_annov; eauto.\n    apply ttyp_sim; eauto.\n    omega. omega.\n    *\n    lets(rred1&rred2):H1.\n    inverts* rred2.\n    exfalso; apply H0; auto.\n  -\n    inverts Typ; try solve[exfalso; apply H1; auto].\n    inverts H2; try solve[exfalso; apply H0; auto].\n    inverts H8; try solve[\n      inverts H2; try solve[exfalso; apply H1; auto];\n      try solve[forwards*: abs_nlam]\n    ].\n    forwards*: tTypedReduce_completeness Red'.\n    inverts H2.\n    *\n    lets(nn1&tt1&vv1&rred1&rred2&ttyp1&eq1): H3.\n    forwards*: ttyping_regular_1 H13.\n    forwards*: valueb_value H13.\n    forwards*: tTypedReduce_nlambda2 rred2.\n    forwards*: value_decidable (e_anno e0 p b0 t_dyn).\n    inverts H8.\n    +\n    forwards*: value_tred_keep2 rred2. inverts H8.\n    left.\n    exists. splits.\n    apply rred1.\n    apply step_refl.\n    apply ttyp_sim;auto.\n    omega. omega.\n    +\n    left.\n    exists. splits.\n    apply rred1.\n    apply stars_one.\n    apply Step_annov; eauto.\n    apply ttyp_sim; eauto.\n    omega. omega.\n    *\n    lets(rred1&rred2):H3.\n    inverts* rred2.\n    exfalso; apply H2; auto.\n  -\n    inverts Typ; try solve[exfalso; apply H1; auto].\n    inverts H2; try solve[exfalso; apply H0; auto].\n    inverts H8; try solve[\n      inverts H2; try solve[exfalso; apply H1; auto];\n      try solve[forwards*: abs_nlam]\n    ].\n    forwards*: tTypedReduce_completeness Red'.\n    inverts H2.\n    *\n    lets(nn1&tt1&vv1&rred1&rred2&ttyp1&eq1): H3.\n    forwards*: ttyping_regular_1 H13.\n    forwards*: valueb_value H13.\n    forwards*: tTypedReduce_nlambda2 rred2.\n    forwards*: value_decidable (e_anno e0 p b0 (t_arrow A1 B0)).\n    inverts H8.\n    +\n    forwards*: value_tred_keep2 rred2. inverts H8.\n    left.\n    exists. splits.\n    apply rred1.\n    apply step_refl.\n    apply ttyp_sim;auto.\n    omega. omega.\n    +\n    left.\n    exists. splits.\n    apply rred1.\n    apply stars_one.\n    apply Step_annov; eauto.\n    apply ttyp_sim; eauto.\n    omega. omega.\n    *\n    forwards* h2: valueb_value H13.\n    lets(rred1&rred2):H3.\n    lets rred1': rred1.\n    inverts rred1.\n    destruct E; unfold fillb in *; inverts H2.\n    inverts* H9.\n    destruct E; unfold fillb in *; inverts H2;\n    try solve[forwards*: bstep_not_value H14].\n    inverts H13.\n    inverts H14; try solve[exfalso; apply H17; auto].\n    inverts H19; try solve[inverts H2; try solve[forwards*: abs_nlam]].\n    inverts H14.\n    inverts h2.\n    inverts H10; inverts H13.\n    right. \n    exists.\n    splits.\n    apply rred1'.\n    apply step_b.\n    apply Step_annov; eauto.\n    unfold not;intros nt;inverts nt.\n    inverts H20.\n  -\n    inverts Typ; try solve[exfalso; apply H1; auto].\n    inverts H6; try solve[\n      inverts H1; try solve[exfalso; apply H1; auto];\n      try solve[forwards*: abs_nlam]\n    ].\n    forwards*: tTypedReduce_completeness Red'.\n    inverts H1.\n    *\n    lets(nn1&tt1&vv1&rred1&rred2&ttyp1&eq1): H2.\n    forwards*: ttyping_regular_1 H8.\n    inverts H8.\n    forwards*: valueb_value H11.\n    forwards*: tTypedReduce_nlambda2 rred2.\n    forwards*: value_decidable (e_anno e0 p b2 A).\n    inverts H5.\n    +\n    forwards*: value_tred_keep2 rred2. inverts H5.\n    left.\n    exists. splits.\n    apply rred1.\n    apply step_refl.\n    apply ttyp_sim;auto.\n    omega. omega.\n    +\n    left.\n    exists. splits.\n    apply rred1.\n    apply stars_one.\n    apply Step_annov; eauto.\n    apply ttyp_sim; eauto.\n    omega. omega.\n    *\n    forwards* h2: valueb_value H8.\n    lets(rred1&rred2):H2.\n    forwards*: value_decidable (e_anno e0 p b2 A).\n    inverts H1.\n    forwards*: value_tred_keep2 rred2. inverts H1.\n    right. \n    exists.\n    splits.\n    apply rred1.\n    apply step_b.\n    apply Step_annov; eauto.\n  -\n    inverts Typ. inverts H4.\n    inverts H6; try solve[inverts H10].\n    inverts H10; try solve[forwards*: abs_nlam].\n    inverts H; try solve[forwards*: abs_nlam].\n    inverts H1.\n    inverts H; try solve[forwards*: abs_nlam].\n  -\n    inverts Typ. inverts H4.\n    inverts H6; try solve[inverts H10].\n    inverts H10; try solve[forwards*: abs_nlam].\n    inverts H; try solve[forwards*: abs_nlam].\n    inverts H1.\n    inverts H; try solve[forwards*: abs_nlam].\nQed.\n\n\n\n\nTheorem typing_elaborate_completeness_chk: forall l b tt e t t' A ,\n  ttyping nil e (Chk2 l b tt) A t ->\n  bstep t (t_term t') ->\n  (exists e' t'' n, bbsteps t' (t_term t'') n /\\ steps e (e_exp e') /\\ ttyping nil e' (Chk2 l b tt) A t''  /\\ 0<=n<=1) \\/\n  exists l b, (bstep t' (t_blame l b)) /\\ steps e (e_blame l b).\nProof.\n  introv Typ Red. \n  eapply typing_elaborate_completeness_gen1; eauto.\nQed.\n  \n\n\nTheorem typing_elaborate_completeness_dir: forall dir e t t' A ,\n  ttyping nil e dir A t ->\n  bstep t (t_term t') ->\n  (exists e' t'' n, bbsteps t' (t_term t'') n /\\ steps e (e_exp e') /\\ ttyping nil e' dir A t''  /\\ 0<=n<=1) \\/\n  exists l b, (bstep t' (t_blame l b)) /\\ steps e (e_blame l b).\nProof.\n  introv Typ Red. \n  destruct dir.\n  -\n   forwards*: ttyping_chk Typ. \n   inverts H. inverts H0. inverts* H. inverts H0.\n   forwards*: typing_elaborate_completeness_chk Red.\n   inverts H0.\n   *\n   lets(vv1&vv2&nn1&rred1&rred2&ttyp1&sz2): H1.\n   forwards*: ttyping_regular_1 H.\n   destruct(exists_decidable e).\n   inverts H2. inverts H3. inverts H2. \n   forwards*: value_valueb H. forwards*: bstep_not_value Red.\n   forwards*: steps_nlam rred2.\n   inverts* ttyp1; try solve[exfalso; apply H3; eauto].\n   forwards*: ttyping_typing Typ; simpl in *.\n   forwards*: preservation_multi_step rred2.\n   forwards*: typing_ttyping H9 H5.\n   subst*.\n   left. exists*.\n   *\n   lets(ll1&llb& rred1& rred2): H1.\n   right. exists*.\n  -\n  forwards*: typing_elaborate_completeness_chk Red.\nQed.\n\n\n\nDefinition Deterministic_blame_Calculus := forall t r1 r2,\n  bstep t r1 ->\n  bstep t r2 ->\n  r1 = r2.\n\n\n\nTheorem typing_elaborate_completeness1: forall e t t' A n n1 dir,\n  Deterministic_blame_Calculus ->\n  n < n1 ->\n  ttyping nil e dir A t ->\n  bbsteps t (t_term t') n ->\n  valueb t' ->\n  exists e', (steps e (e_exp e')) /\\ ttyping nil e' dir A t' /\\ value e'.\nProof.\n  introv dd sz typ red val. gen t t' A e n.\n  inductions n1; intros; try solve[omega].\n  inverts* red.\n  -\n  forwards*: valueb_value typ.\n  -\n  forwards*: typing_elaborate_completeness_dir H0.\n  inverts* H.\n  +\n  lets(ee1 &ee2&nn2& rred1&rred2&typ1&ssz): H1.\n  inverts H2.\n  *\n  inverts* rred1.\n  forwards*: valueb_value typ1.\n  forwards*: bstep_not_value H2.\n  *\n  destruct nn2.\n  ++\n  inverts* rred1.\n  assert(bbsteps ee2 (t_term t') (1+n)).\n  eapply bbstep_n;eauto.\n  forwards*: IHn1 H.\n  omega.\n  inverts* H2. \n  ++\n  assert(nn2 = 0).\n  omega.\n  rewrite H in *.\n  inverts* rred1.\n  inverts* H8.\n  forwards* h1: dd H3 H7.\n  inverts* h1.\n  forwards*: IHn1 H5.\n  omega.\n  inverts* H2. \n  +\n  inverts* H1.\n  inverts* H.\n  inverts* H1.\n  inverts* H2.\n  forwards*: bstep_not_value H.\n  forwards*: dd H H4.\n  inverts* H1.\nQed.\n\n\nTheorem typing_elaborate_completeness_all1: forall e t t' A n dir,\n  Deterministic_blame_Calculus ->\n  ttyping nil e dir A t ->\n  bbsteps t (t_term t') n ->\n  valueb t' ->\n  exists e', (steps e (e_exp e')) /\\ ttyping nil e' dir A t' /\\ value e'.\nProof.\n  introv dd typ red val.\n  eapply typing_elaborate_completeness1;eauto.\nQed.\n\n\n\n\n(** annother *)\n\nLemma btyping_typing: forall G e t A,\n btyping G t A e ->\n Typing G e Inf A.\nProof.\n  introv typ.\n  inductions typ;eauto.\n  -\n  eapply Typ_anno;eauto.\n  pick fresh x and apply Typ_abs.\n  forwards*: H0 x.\n  inverts* H1.\n  -\n  inverts* IHtyp2; try solve[inverts* typ2].\n  -\n  destruct(lambda_decidable e); eauto.\n  forwards* ha: nlam_exist H0.\n  inverts* ha;inverts* typ. \nQed.\n\n\n\nDefinition typing_typing_aux G dir e A  := \n   match dir with \n    | Chk3 l b => Typing G e Chk A \n    | _   => Typing G e Inf A\n   end.\n\nLemma typing_typing: forall G dir e  A t,\n typing G e dir A t ->\n typing_typing_aux G dir e A.\nProof.\n  introv typ.\n  inductions typ; unfold typing_typing_aux in *; intros; eauto.\n  (* eapply Typ_app; eauto.\n  inverts* IHtyp2.\n  eapply Typ_app; eauto.\n  inverts* IHtyp2. *)\nQed.\n\n\nLemma typing_typing1: forall G e t A B,\n typing G e Inf3 A t ->\n Typing G e Inf B ->\n A = B.\nProof.\n  introv typ1 typ2. gen B.\n  inductions typ1;intros; \n  try solve[inductions typ2; eauto].\n  -\n    inverts* typ2.\n    forwards*: binds_unique H0 H4.\n  -\n    inverts typ2.\n    forwards*: IHtyp1_1 H6.\n    inverts* H. inverts* H3.\n  -\n    inverts typ2.\n    forwards*: IHtyp1_1 H2.\n    inverts* H0.\n  -\n    inverts typ2.\n    forwards*: IHtyp1_1 H6.\n    subst. inverts* H3.\nQed.\n\n\n\n\nLemma value_valueb2: forall e t A,\n btyping nil t A e -> value e ->\n valueb t.\nProof.\n  introv typ val. gen A t.\n  inductions val; intros;\n  try solve[inverts* typ].\n  -\n    forwards*: btyping_regular_1 typ.\n    inverts typ; eauto.\n    inverts* H9.\n    forwards* h1: btyping_typing H6.\n    forwards* h2: principle_inf h1.\n    rewrite h2 in *.\n    congruence. \n  -\n    inverts typ. \n    forwards*: IHval.\n    forwards* h1: btyping_typing H5.\n    forwards* h2: principle_inf h1.\n    rewrite h2 in *; eauto.\nQed.\n\n\nLemma valueb_value2: forall e t A,\n btyping nil t A e -> valueb t ->\n value e.\nProof.\n  introv typ val. gen A e.\n  inductions val; intros;\n  try solve[inverts* typ].\n  - \n    forwards* h1: btyping_regular_3 typ. inverts* typ.\n    inverts* h1.\n  -\n     inverts typ. \n    forwards*: IHval.\n    forwards* h1: btyping_typing H7.\n    forwards* h2: principle_inf h1.\n  -\n     inverts typ. \n    forwards*: IHval.\n    forwards* h1: btyping_typing H8.\n    forwards* h2: principle_inf h1.\n    rewrite <- h2 in *; eauto.\nQed.\n\n\n\n\n\nLemma lc_lcb: forall E e t dir A,\n typing E e dir A t ->\n lc_exp e ->\n lc_term t.\nProof.\n  introv typ H. \n  inductions typ;try solve[inverts* H];eauto. \n  -\n    inverts H1. \n    pick fresh x.\n    forwards*: H.\n  - inverts H1. \n    pick fresh x.\n    forwards*: H.\n  - inverts H1. \n    pick fresh x.\n    forwards*: H.\n  -\n    inverts* H0.\nQed.\n\n\n\nLemma value_valueb1: forall e t A,\n typing nil e Inf3 A t -> value e ->\n valueb t.\nProof.\n  introv typ H. gen t A.\n  inductions H; intros; \n  try solve [inverts* typ].\n  - inverts typ. \n    pick fresh x.\n    forwards*: H6.\n    forwards*: lc_lcb H. \n  - inverts typ.\n    forwards*: value_lc H.\n    forwards*: lc_lcb H1.  \n    inverts* H8. \n    forwards*: IHvalue.\n    forwards*: principle_if H5.\n    rewrite H4 in H0. inverts H0.\n    eapply valueb_fanno; eauto.\n  - inverts typ.\n    forwards*: value_lc H0.\n    forwards*: lc_lcb H8.\n    inverts* H8.\n    inverts* H2.\n    forwards*: IHvalue.\n    forwards*: principle_if H5.\n    rewrite H4 in H.\n    apply valueb_dyn; eauto.\nQed.\n\n\n\nLemma Tred_soundness: forall v t v' p b A,\n  typing nil (e_anno v p b A) Inf3 A t->\n  value v ->\n  TypedReduce v p b A (e_exp v') ->\n  exists t', t ->* (t_term t') /\\ typing nil v' Inf3 A t'.\nProof.\n  introv  Typ val Red. gen t.\n  inductions Red; intros.\n  - inverts Typ.\n    inverts H7. exists*.\n    forwards*: principle_if H3.\n  - inverts Typ.\n    forwards*: value_lc val.\n  - inverts Typ.\n    inverts H5.\n    inverts H1.\n    exists. split.\n    apply star_one.\n    apply bStep_lit; eauto. \n    apply typ_lit; eauto.\n  - \n    inverts Typ. inverts H6.\n    forwards*: value_valueb1 H2.\n    inverts H2. inverts H11.\n    exists* (trm_cast (trm_abs t_dyn t) q b1 (t_arrow t_dyn t_dyn) t_dyn).\n    inverts val. forwards*: principle_if H3. rewrite H1 in *.\n    exists((trm_cast t q b1 A t_dyn)).\n    splits*. \n  - inverts Typ. inverts H6.\n    exists.\n    splits*.\n    forwards*: principle_if H2.\n    rewrite H0 in H.\n    inverts* H.\n    inverts H3.\n    inverts H4.\n    rewrite <- TEMP in H.\n    rewrite <- TEMP in H1.\n    exists. split.\n    apply star_one.\n    apply bStep_anyd; eauto.\n    forwards*: value_valueb1 val.\n    simpl.\n    apply typ_anno; eauto.\n    apply typ_sim; eauto.\n    apply typ_anno; eauto.\n    apply typ_sim; eauto.\n    rewrite <- TEMP in H2. auto.\n    rewrite <- TEMP in H1.\n    exfalso. apply H1. reflexivity.\n  -\n    inverts Typ. inverts H. inverts H1.\n    inverts H3.\n    +\n    forwards* lc: typing_regular_3 H7.\n    inverts H7; try solve[inverts* H4]. \n    inverts* H4.\n    inverts* H14;\n    try solve[exfalso; apply H6; eauto];\n    try solve[exfalso; apply H2; eauto];\n    try solve[inverts* H15].\n    inverts lc. inverts H3.\n    exists.\n    splits.\n    eapply star_trans.\n    apply star_one.\n    apply bStep_dyna; eauto.\n    apply star_one.\n    rewrite fillb_cast.\n    apply do_stepb.\n    auto.\n    apply bStep_vany; auto.\n    forwards*: value_valueb1 val.\n    apply typ_anno; eauto.\n    apply typ_sim; eauto.\n    +\n    exfalso; apply H0; eauto.\n  -\n    inverts Typ. inverts* H5. inverts* H1.\n    forwards*: value_lc val.\n    inverts H.\n    forwards*: lc_lcb H9.\n    inverts* H9.\n    exists. splits.\n    apply star_one.\n    apply bStep_vany; eauto.\n    forwards*: value_valueb1 val. inverts* H0.\n    apply typ_anno; eauto.\n     inverts H12.\n  - \n    inverts Typ. inverts val.\n    inverts H9. inverts H6. inverts H15;\n    try solve[forwards*: abs_nlam].\n    forwards*: principle_if H6.\n    rewrite H2 in H0.\n    rewrite H2 in H5.\n    inverts H. inverts H8.\n    inverts* H9.\n    destruct A0; try solve[inverts H0];\n    try solve[inverts H5]. inverts H5.\n    forwards*: value_valueb1 H7.\n    exists. split.\n    eapply star_trans.\n    apply star_one.\n    eapply bStep_dyna;eauto.\n    eapply star_one.\n    rewrite fillb_cast.\n    apply do_stepb.\n    auto.\n    unfold fillb.\n    apply bStep_vany; eauto.\n    unfold fillb.\n    apply typ_anno; eauto.\n  - inverts Typ. inverts val.\n    inverts H6.\n    inverts H3. inverts H12;\n    try solve[forwards*: abs_nlam].\n    forwards*: principle_if H3.\n    exists. split.\n    apply star_one.\n    rewrite H0. rewrite H0 in H2.\n    apply bStep_vany; eauto.\n    forwards*: value_valueb1 H3.\n    rewrite H0. auto.\nQed.\n\n\n\nLemma soundness_mul_two: forall e t e' A dir ,\n  typing nil e dir A t->\n  step e (e_exp e') ->\n  exists t', t ->* (t_term t') /\\ typing nil e' dir A t' .\nProof.\n  introv Typ Red. gen A t dir.\n  inductions Red; intros.\n  - destruct E; unfold fill in *.\n    + inverts Typ.\n      *\n      forwards*: IHRed H8. inverts H0. inverts H1.\n      exists. split.\n      apply multi_red_app2; eauto.\n      inverts H.\n      forwards*: lc_lcb H3.\n      eapply typ_app; eauto.\n      *\n      inverts H0.\n      forwards*: IHRed H10. inverts H0. inverts H3.\n      exists. split.\n      apply star_trans with (b:= trm_cast (trm_app x t2) l0 b0 A0 A).\n      apply multi_red_cast; auto.\n      apply multi_red_app2; auto.\n      inverts H.\n      forwards*: lc_lcb H5. \n      apply bstep_refl.\n      eapply typ_sim; eauto.\n      forwards*: IHRed H10. inverts H0. inverts H3.\n      exists. split.\n      apply multi_red_cast.\n      apply multi_red_app2.\n      inverts H.\n      forwards*: lc_lcb H5. \n      apply multi_red_cast.\n      apply H0.\n      eapply typ_sim; eauto.\n      *\n      forwards*: IHRed H8. inverts H0. inverts H1.\n      exists. split.\n      apply multi_red_app2.\n      inverts H.\n      forwards*: lc_lcb H3.\n      apply multi_red_cast.\n      apply H0.\n      eapply typ_appd; eauto.\n    + \n      inverts Typ. \n      * inverts H.\n      forwards*: value_valueb1 H4.\n      forwards*: IHRed H9. \n      inverts H0. inverts H1.\n      exists. split.\n      forwards: multi_red_app H H0.\n      apply H1.\n      eapply typ_app; eauto.\n      *\n      inverts H. inverts H0.\n      -- \n      forwards*: value_valueb1 H7.\n      forwards*: IHRed H12. inverts H0. inverts H3.\n      exists. split.\n      apply multi_red_cast.\n      forwards: multi_red_app H H0.\n      apply H3.\n      eapply typ_sim; eauto.\n      --\n      forwards*: principle_if H11.\n      rewrite H in *.\n      inverts* H5.\n      *\n      inverts H. \n      forwards*: principle_if H8.\n      rewrite H in *.\n      inverts* H2.\n    + inverts Typ. \n      * forwards*: IHRed H8. inverts H0. inverts H1.\n        exists. split.\n        apply H0.\n        apply typ_anno; eauto.\n      * inverts H0.\n        forwards*: IHRed H10. inverts H0. inverts H3.\n        exists. split.\n        apply multi_red_cast.\n        apply H0.\n        apply typ_sim;eauto.\n    + inverts Typ.\n      *\n      inverts H0.\n      forwards*: IHRed H5. inverts H0. inverts H3.\n      exists. split.\n      apply multi_red_cast.\n      apply multi_red_app2; eauto.\n      inverts H.\n      forwards*: lc_lcb H6.\n      apply typ_sim;eauto.\n      *\n      inverts H.\n      forwards*: IHRed H2. inverts H. inverts H0.\n      exists. split.\n      apply multi_red_app2; eauto.\n      forwards*: lc_lcb H1.\n      eapply typ_appv;eauto.\n    +\n      inverts Typ.\n      *\n      inverts H0.\n      forwards*: IHRed H7. inverts H0. inverts H3.\n      exists. split.\n      apply multi_red_cast.\n      apply multi_red_app.\n      inverts H.   \n      forwards*: value_valueb1 H6.\n      apply H0.\n      apply typ_sim;eauto.\n      forwards*: step_not_nlam Red.\n      *\n      forwards*: IHRed H4. inverts H0. inverts H1.\n      exists. split.\n      apply multi_red_app.\n      inverts H.   \n      forwards*: value_valueb1 H5.\n      apply H0.\n      forwards*: step_not_nlam Red.\n  - \n    inverts* Typ.\n    + \n      inverts H1.\n      forwards*: value_valueb1 H8.\n      forwards*: value_valueb1 H6.\n      inverts H6.\n      inverts H16; try solve[forwards*: abs_nlam].\n      exists. split.\n      eapply star_trans.\n      apply multi_red_cast.\n      apply star_one.\n      apply bStep_beta; eauto.\n      forwards*: lc_lcb H.\n      apply bstep_refl.\n      apply typ_sim; eauto.\n      apply typ_anno; eauto.\n      pick fresh y.\n      forwards*: H17.\n      rewrite (subst_exp_intro y); auto.\n      rewrite (subst_term_intro y); auto.\n      eapply typing_c_subst_simpl; auto.\n      apply H5. auto.\n    +\n      forwards*: value_valueb1 H3.\n      forwards*: value_valueb1 H5.\n      inverts H3.\n      inverts H14; try solve[forwards*: abs_nlam].\n      exists. split.\n      eapply star_trans.\n      apply star_one.\n      apply bStep_beta; eauto.\n      forwards*: lc_lcb H.\n      apply bstep_refl.\n      apply typ_anno; eauto.\n      pick fresh y.\n      forwards*: H15.\n      rewrite (subst_exp_intro y); auto.\n      rewrite (subst_term_intro y); auto.\n      eapply typing_c_subst_simpl; auto.\n      apply H3. auto.\n  - \n    inverts Typ.\n    assert (typing nil (e_anno v l b A0) Inf3 A0 t).\n    eauto.\n    forwards*: Tred_soundness H0.\n    inverts H2.\n    assert (typing nil (e_anno v l b A1) Inf3 A1 t0).\n    eauto.\n    forwards*: Tred_soundness H0.\n    inverts H5. inverts H6.\n    exists. split.\n    apply multi_red_cast; eauto.\n    apply typ_sim;eauto.\n    forwards*: TypedReduce_nlambda2 H0.\n  - \n    inverts Typ. \n    * \n    inverts H3. inverts H8. inverts H16;\n    try solve[inverts H0]. \n    forwards*: value_valueb1 H7.\n    forwards*: value_valueb1 H10.\n    forwards*: principle_if H7.\n    rewrite H8 in *. subst.\n    inverts H12. \n    exists. split.\n    apply multi_red_cast.\n    apply star_one. \n    apply bStep_abeta; eauto. \n    apply typ_sim; eauto.\n    apply typ_anno; eauto. \n    * \n    inverts H5. inverts H14; try solve[inverts H0]. \n    forwards*: value_valueb1 H7.\n    forwards*: value_valueb1 H5.\n    forwards*: principle_if H5.\n    rewrite H6 in *. subst.\n    inverts H9. \n    exists. split.\n    apply star_one. \n    apply bStep_abeta; eauto. \n    apply typ_anno; eauto.\n  -\n    inverts Typ.\n    +\n    forwards*: principle_if H11. rewrite H3 in H1. inverts H1.\n    assert(typing nil (e_anno v2 l b A) Inf3 A t2).\n    apply typ_anno; auto. \n    forwards*: Tred_soundness H2.\n    destruct H4. destruct H4.\n    forwards*:  TypedReduce_walue2 H2.\n    forwards*: value_valueb1 H11.\n    exists. splits.\n    apply multi_red_app; eauto.\n    eapply typ_appv; eauto.\n    +\n    inverts H3.\n    forwards*: principle_if H13. rewrite H3 in H1. inverts H1.\n    forwards*: value_valueb1 H13.\n    assert(typing nil (e_anno v2 l b A) Inf3 A t2).\n    apply typ_anno; auto. \n    forwards*: Tred_soundness H2.\n    destruct H7. destruct H7.\n    forwards*:  TypedReduce_walue2 H2.\n    exists. splits.\n    apply multi_red_cast.\n    apply multi_red_app; eauto.\n    eapply typ_sim; eauto.\n    forwards*: principle_if H13. rewrite H3 in H1. inverts H1.\n    +\n    forwards*: principle_if H11. rewrite H3 in H1. inverts H1.\n  -\n    inverts Typ; try solve[inverts H9].\n    +\n    inverts H1; try solve[inverts H11].\n    forwards* h1: value_valueb1 H11.\n    exists. splits.\n    eapply bstep_refl.\n    eapply typ_sim; eauto.\n    +\n    forwards* h1: value_valueb1 H9.\n    exists. splits.\n    eapply bstep_refl.\n    eapply typ_app; eauto.\n  -\n    inverts Typ.\n    +\n    inverts H. inverts H4. inverts H6.\n    exists. splits.\n    apply multi_red_cast.\n    apply star_one; eauto.\n    eapply typ_sim; eauto.\n    +\n    inverts H1. inverts H3.\n    exists. splits.\n    apply star_one; eauto.\n    eapply typ_addl; eauto.\n  -\n    inverts Typ.\n    +\n    inverts H. inverts H4. inverts H6.\n    exists. splits.\n    apply multi_red_cast.\n    apply star_one; eauto.\n    eapply typ_sim; eauto.\n    +\n    inverts H1. inverts H3.\n    exists. splits.\n    apply star_one; eauto.\n    eapply typ_lit; eauto.\n  -\n    inverts* Typ.\n    + \n    inverts* H1. \n    inverts* H6; try solve[exfalso; apply H5; eauto].\n    forwards*: value_valueb1 H8.\n    forwards*: lc_lcb H.\n    exists. split.\n    eapply star_trans.\n    rewrite fillb_cast.\n    apply star_one.\n    apply do_stepb;auto. \n    unfold fillb.\n    apply bstep_refl. \n    eapply typ_sim; eauto.\n    apply typ_anno; eauto.\n    pick fresh y.\n    forwards*: H13.\n    rewrite (subst_exp_intro y); auto.\n    rewrite (subst_term_intro y); auto.\n    eapply typing_c_subst_simpl; auto.\n    apply H5. auto.\n  +\n    inverts H3. \n    forwards*: value_valueb1 H5.\n    forwards*: lc_lcb H.\n    exists. split.\n    eapply star_trans.\n    apply star_one.\n    apply bStep_beta;auto.\n    apply bstep_refl. \n    apply typ_anno; eauto.\n    pick fresh y.\n    forwards*: H11.\n    rewrite (subst_exp_intro y); auto.\n    rewrite (subst_term_intro y); auto.\n    eapply typing_c_subst_simpl; auto.\n    apply H3. auto.\nQed.\n\nTheorem soundness: forall e t v1 A,\n  typing nil e Inf3 A t->\n  e ->** (e_exp v1) ->\n  value v1 ->\n  exists t', t ->* (t_term t') /\\ valueb t' /\\ typing nil v1 Inf3 A t' .\nProof.\n  introv typ red val. gen A t.\n  inductions red;intros.\n  -\n  forwards*: value_valueb1 val.\n  -\n  forwards*: soundness_mul_two H.\n  inverts H0. inverts H1.\n  forwards*: IHred H2.\n  inverts* H1. \nQed.\n\n\n\nLemma typedReduce_completeness: forall v t B A t' l b ,\n  btyping nil t B v ->\n  valueb t ->\n  bstep (trm_cast t l b B A) (t_term t') ->\n  (exists  n t2 v',  bbsteps t' (t_term t2) n /\\ TypedReduce v l b A (e_exp v') /\\\n  btyping nil t2 A v' /\\ 0<=n <= 1) \\/ (bstep t' (t_blame l b) /\\ (TypedReduce v l b A (e_blame l b))).\nProof.\n  introv typ val red.\n  forwards* h1: valueb_value2 val.\n  inductions red; try solve[inverts* typ].\n  -\n    destruct E; unfold fillb; inverts x;\n    try forwards*: bstep_not_value red.\n  -\n    inverts* typ; inverts h1.\n    left. \n    exists.\n    splits*.\n  -\n     inverts* typ; inverts h1.\n     left. \n    exists.\n    splits*.\n  -\n    inverts* H2. \n    forwards* h2:btyping_typing typ.\n    forwards*: principle_inf h2.\n    left.\n    exists. splits. \n    apply bbstep_refl.\n    eapply TReduce_anyd.\n    rewrite H2.\n    unfold FLike.\n    splits*.\n    eapply btyp_cast; eauto.\n    omega.\n    omega.\n  -\n    inverts* H2. \n    inverts val;inverts* typ.\n    inverts H2; try solve[inverts H13;inverts* H3].\n    +\n    right. rewrite fillb_cast.\n    rewrite fillb_cast.\n    splits.\n    apply blame_stepb;eauto.\n    simpl.\n    eapply bStep_vanyp;eauto.\n    inverts* H13.\n    unfold not;intros nt;inverts* nt.\n    inverts* H13.\n    eapply TReduce_blame;simpl;eauto.\n    unfold not;intros nt;inverts* nt.\n    +\n    inverts h1.\n    inverts* H13. inverts H8.\n    left.\n    exists. splits.\n    eapply sstar_one.\n    rewrite fillb_cast.\n    apply do_stepb;eauto.\n    eapply TReduce_dyna; simpl;eauto.\n    unfold FLike; splits*.\n    eapply btyp_cast; eauto.\n    omega. omega.\n    +\n    inverts h1.\n    inverts* H13. inverts H3.\n    left.\n    exists. splits.\n    eapply sstar_one.\n    rewrite fillb_cast.\n    apply do_stepb;eauto.\n    eapply TReduce_dyna; simpl;eauto.\n    unfold FLike; splits*.\n    eapply btyp_cast; eauto.\n    omega.\n    omega.\n  -\n    inverts* typ. \n    forwards* h2:btyping_typing H8. \n    forwards*: valueb_value2 H8.\n    forwards* h3: principle_inf h2.\n    rewrite <- h3.\n    destruct(lambda_decidable e).\n    left. exists. splits*.\n    rewrite h3; auto.\n    forwards* h4: nlam_exist.\n    lets (ee& ll & bb&hh1):h4. inverts hh1.\n    inverts* H8.\nQed.\n\n\n\n\nTheorem typing_elaborate_completeness_gen: forall e t t' A n,\n size_exp e + size_term t < n ->\n  btyping nil t A e ->\n  bstep t (t_term t') ->\n  (exists e' t'' n, bbsteps t' (t_term t'') n /\\ steps e (e_exp e') /\\ btyping nil t'' A e' /\\ 0<=n<=1) \\/\n  exists l b, (bstep t' (t_blame l b)) /\\ steps e (e_blame l b).\nProof.\n  introv sz Typ Red. gen e t t' A.\n  induction n; intros; try omega.\n  lets Red': Red.\n  inductions Red; intros.\n  - clear IHRed.\n     destruct E; unfold fillb in *; simpl in *.\n    +\n    forwards h1: btyping_typing Typ.\n    forwards* lc: Typing_regular_1 h1.\n    inverts Typ; simpl in *.\n    inverts h1; simpl in *.\n    forwards* h2: IHn Red H3. simpl in *; omega.\n    inverts H.\n    inverts* h2.\n    *\n    lets(vv1&tt2&nn1&rred2&rred1&typ2&ssz): H.\n    inverts lc.\n    left.\n    exists. splits.\n    eapply mmulti_red_app2.\n    auto.\n    apply rred2.\n    apply multi_rred_appv2.\n    auto. apply rred1.\n    eapply btyp_app; eauto.\n    omega.\n    omega.\n    *\n    lets(ll1&bb1&rred1&rred2):H.\n    right. exists.\n    splits.\n    rewrite fillb_appl.\n    apply blame_stepb;eauto.\n    eapply multi_bblame_appv2;eauto.\n    inverts* lc.\n    +\n    inverts Typ. inverts H.\n    forwards* h1: valueb_value2 H3.\n    forwards* h2: IHn Red H6. simpl in *; omega.\n    inverts h2.\n    *\n    lets(vv1&tt2&nn1&rred2&rred1&typ2&ssz): H.\n    left.\n    exists. splits.\n    eapply mmulti_red_app.\n    auto.\n    apply rred2.\n    apply multi_rred_appv.\n    auto. apply rred1.\n    eapply btyp_app; eauto.\n    omega.\n    omega.\n    *\n    lets(ll1&bb1&rred1&rred2):H.\n    right. exists.\n    splits.\n    rewrite fillb_appr.\n    apply blame_stepb;eauto.\n    eapply multi_bblame_appv;eauto.\n    +\n     forwards* lc: btyping_regular_3 Typ.\n     inverts Typ; simpl in *.\n     inverts lc.\n     forwards* h1: IHn Red H8. simpl in *; omega.\n     inverts h1.\n     lets(vv1&tt2&nn1&rred2&rred1&typ2&ssz): H0.\n     left.\n     exists. splits.\n     apply mmulti_red_cast.\n     apply rred2. \n     apply multi_rred_anno.\n     apply rred1.\n     eapply btyp_cast; eauto.\n     omega.\n     omega.\n     lets(ll1&bb1&rred1&rred2):H0.\n     right. exists.\n     splits.\n     rewrite fillb_cast.\n     apply blame_stepb;eauto.\n     eapply multi_bblame_anno;eauto.\n  -\n    forwards* lc: btyping_regular_3 Typ.\n    inverts Typ. inverts H4.\n    forwards* h1: valueb_value2 H7.\n    inverts lc. inverts H3.\n    forwards* h2: value_group h1.\n    inverts h2.    \n    pick fresh x.\n    forwards* h3: H9 x.\n    left.\n    exists. splits.\n    eapply bbstep_refl.\n    eapply stars_one.\n    eapply Step_beta.\n    auto.\n    auto.\n    rewrite (subst_term_intro x);eauto.\n    rewrite (subst_exp_intro x);eauto.\n    assert((e_anno [x ~> e2] (e ^^ e_var_f x) l0 b A0) = ([x ~> e2](e_anno (e ^^ e_var_f x) l0 b A0))).\n    simpl; reflexivity.\n    rewrite H3 in *.\n    eapply btyping_c_subst_simpl;eauto.\n    omega. omega.\n    lets (ee& ll & bb&hh1):H1. inverts hh1.\n    inverts H7.\n  -\n    inverts Typ.\n    forwards* h1: valueb_value2 H7.\n    forwards*: typedReduce_completeness H7 Red'.\n    inverts H.\n    ++\n    lets(nn1&tt2&vv1&rred2&rred1&typ1&ssz): H0.\n    inverts* H7.\n    inverts* rred1.\n    left.\n    exists. splits.\n    eapply bbstep_refl.\n    apply stars_one.\n    apply Step_annov; eauto.\n    unfold not;intros nt;inverts* nt.\n    auto.\n    omega. omega.\n    ++\n    lets(rred1&rred2):H0.\n    forwards*: bstep_not_value rred1.\n  -\n    inverts Typ. inverts H4.\n    inverts H. \n    forwards* h1: valueb_value2 H12.\n    forwards* h3: valueb_value2 H7.    \n     forwards* h2: value_group h3. \n    inverts h2.\n    +\n    forwards* h4: value_group h1.\n    inverts h4. \n    forwards*: btyping_typing H12.\n    forwards*: principle_inf H3.\n    inverts H13.\n    left.\n    exists. splits.\n    eapply bbstep_refl.\n    eapply stars_one.\n    eapply Step_abeta;eauto.\n    eapply btyp_cast;eauto.\n    omega. omega.\n    lets (ee& ll & bb&hh1):H1. inverts hh1.\n    try solve[inverts H12]. \n    +\n    lets (ee& ll & bb&hh1):H. inverts hh1.\n    inverts* H; try solve[inverts H7].\n  -\n    inverts Typ.\n    forwards* h1: valueb_value2 H8.\n    forwards*: typedReduce_completeness H8 Red'.\n    inverts H0.\n    ++\n    lets(nn1&tt2&vv1&rred2&rred1&typ1&ssz): H1.\n    forwards*: value_decidable (e_anno e0 p b t_dyn).\n    inverts H0.\n    +\n    forwards*: value_tred_keep2 rred1. inverts H0.\n    left.\n    exists. splits.\n    apply rred2.\n    apply step_refl.\n    auto.\n    omega.\n    omega.\n    +\n    left.\n    exists. splits.\n    apply rred2.\n    apply stars_one.\n    apply Step_annov; eauto.\n    auto.\n    omega.\n    omega.\n    ++\n    lets(rred1&rred2):H1.\n    forwards*: bstep_not_value rred1.\n  -\n    inverts Typ.\n    forwards* h1: valueb_value2 H11.\n    forwards*: typedReduce_completeness H11 Red'.\n    inverts H3.\n    ++\n    lets(nn1&tt2&vv1&rred2&rred1&typ1&ssz): H4.\n    forwards* h2: value_decidable (e_anno e0 p b t_dyn).\n    inverts h2.\n    +\n    forwards* h3: value_tred_keep2 rred1. inverts h3.\n    left.\n    exists. splits.\n    apply rred2.\n    apply step_refl.\n    auto.\n    omega.\n    omega.\n    +\n    left.\n    exists. splits.\n    apply rred2.\n    apply stars_one.\n    apply Step_annov; eauto.\n    auto.\n    omega.\n    omega.\n    ++\n    inverts* H2.\n    lets(rred1&rred2):H4.\n    forwards*: bstep_not_value rred1.\n  -\n    inverts Typ.\n    forwards* h1: valueb_value2 H11.\n    forwards*: typedReduce_completeness H11 Red'.\n    inverts H3.\n    ++\n    lets(nn1&tt2&vv1&rred2&rred1&typ1&ssz): H4.\n    forwards* h2: value_decidable (e_anno e0 p b A0).\n    inverts h2.\n    +\n    forwards* h3: value_tred_keep2 rred1. inverts h3.\n    left.\n    exists. splits.\n    apply rred2.\n    apply step_refl.\n    auto.\n    omega.\n    omega.\n    +\n    left.\n    exists. splits.\n    apply rred2.\n    apply stars_one.\n    apply Step_annov; eauto.\n    auto.\n    omega.\n    omega.\n    ++\n    inverts* H2.\n    lets(rred1&rred2):H4.\n    right. exists.\n    splits*.\n    inverts h1;inverts H11.\n    eapply step_b;eauto.\n    eapply Step_annov;eauto.\n    unfold not;intros nt;inverts* nt. inverts H15.\n  -\n    inverts Typ.\n    forwards* h1: valueb_value2 H9.\n    forwards*: typedReduce_completeness H9 Red'.\n    inverts H1.\n    ++\n    lets(nn1&tt2&vv1&rred2&rred1&typ1&ssz): H2.\n    forwards* h2: value_decidable (e_anno e0 p b2 A0).\n    inverts h2.\n    +\n    forwards* h3: value_tred_keep2 rred1. inverts h3.\n    left.\n    exists. splits.\n    apply rred2.\n    apply step_refl.\n    auto.\n    omega.\n    omega.\n    +\n    left.\n    exists. splits.\n    apply rred2.\n    apply stars_one.\n    apply Step_annov; eauto.\n    auto.\n    omega.\n    omega.\n    ++\n    lets(rred1&rred2):H2.\n    forwards*: bstep_not_value rred1.\n  -\n    inverts Typ. inverts H2. inverts* H5.\n    left. exists. splits.\n    eapply bbstep_refl.\n    eapply stars_one;eauto.\n    eapply btyp_addl;eauto.\n    omega. omega.\n  -\n    inverts Typ. inverts H2. inverts* H5.\n    left. exists. splits.\n    eapply bbstep_refl.\n    eapply stars_one;eauto.\n    eapply btyp_lit;eauto.\n    omega. omega.\nQed.\n\n\n\n\nTheorem typing_elaborate_completeness: forall e t t' A n n1,\n  Deterministic_blame_Calculus ->\n  n < n1 ->\n  btyping nil t A e ->\n  bbsteps t (t_term t') n ->\n  valueb t' ->\n  exists e', (steps e (e_exp e')) /\\ btyping nil t' A e' /\\ value e'.\nProof.\n  introv dd sz typ red val. gen t t' A e n.\n  inductions n1; intros; try solve[omega].\n  inverts* red.\n  -\n  forwards*: valueb_value2 typ.\n  -\n  forwards*: typing_elaborate_completeness_gen H0.\n  inverts* H.\n  +\n  lets(ee1 &ee2&nn2& rred1&rred2&typ1&ssz): H1.\n  inverts H2.\n  *\n  inverts* rred1.\n  forwards*: valueb_value2 typ1.\n  forwards*: bstep_not_value H2.\n  *\n  destruct nn2.\n  ++\n  inverts* rred1.\n  assert(bbsteps ee2 (t_term t') (1+n)).\n  eapply bbstep_n;eauto.\n  forwards*: IHn1 H.\n  omega.\n  inverts* H2. \n  ++\n  assert(nn2 = 0).\n  omega.\n  rewrite H in *.\n  inverts* rred1.\n  inverts* H8.\n  forwards* h1: dd H3 H7.\n  inverts* h1.\n  forwards*: IHn1 H5.\n  omega.\n  inverts* H2. \n  +\n  inverts* H1.\n  inverts* H.\n  inverts* H1.\n  inverts* H2.\n  forwards*: bstep_not_value H.\n  forwards*: dd H H4.\n  inverts* H1.\nQed.\n\n\nTheorem ttyping_completeness: forall e t t' A n,\n  Deterministic_blame_Calculus ->\n  btyping nil t A e ->\n  bbsteps t (t_term t') n ->\n  valueb t' ->\n  exists e', (steps e (e_exp e')) /\\ btyping nil t' A e' /\\ value e'.\nProof.\n  introv dd typ red val.\n  eapply typing_elaborate_completeness;eauto.\nQed.\n\n\n\n(* sound2 *)\n\n\nLemma tTypedReduce_soundness2: forall v t A v' l b ,\n  ttyping nil (e_anno v l b A) Inf2 A t ->\n  value v ->\n  TypedReduce v l b A (e_exp v') ->\n  exists t', bsteps t (t_term t')  /\\ ttyping nil v' Inf2 A t'.\nProof.\n  introv  Typ val Red. gen t.\n  inductions Red; intros.\n  - inverts Typ.\n    inverts H4; try solve[forwards*: abs_nlam].\n    +\n    forwards*: principle_if2 H7.\n    +\n    inverts* H7.\n  - inverts Typ.\n    +\n    inverts H3; try solve[forwards*: abs_nlam].\n    forwards*: principle_if2 H6.\n    +\n    inverts* H6.\n  - inverts Typ.\n    inverts H2.\n    inverts H5.\n    exists. split.\n    apply star_one.\n    apply bStep_lit; eauto. \n    apply ttyp_lit; eauto.\n  - \n    inverts Typ. inverts H3.\n    forwards*: value_valueb H6.\n    inverts H6. \n    +\n    inverts* H0.\n    exists. splits.\n    apply star_one.\n    apply bStep_dd; eauto. \n    eapply ttyp_anno;eauto.\n    +\n    exists. splits.\n    apply star_one.\n    apply bStep_dd; eauto. \n    eapply ttyp_anno2;eauto.\n  - inverts Typ. inverts H3; try solve[forwards*: abs_nlam].\n    +\n    forwards*: principle_if2 H6.\n    rewrite H0 in *.\n    inverts* H.\n    inverts H2.\n    forwards*: value_valueb H6.\n    exists. split.\n    apply star_one.\n    apply bStep_anyd; eauto.\n    apply ttyp_anno; eauto.\n    +\n    forwards*: value_valueb H6.\n    inverts* H6; try solve[inverts H11].\n    exists. splits*.\n    exists. splits*.\n  -\n    inverts Typ. inverts H7. inverts* H6;\n    try solve[forwards*: abs_nlam].\n    forwards* lc: ttyping_regular_3 H14.\n    inverts* H14; try solve[inverts H13].\n    +\n    inverts H. inverts H1.\n    inverts lc.\n    exists. splits.\n    eapply star_trans.\n    apply star_one.\n    apply bStep_dyna; auto.\n    apply star_one.\n    rewrite fillb_cast.\n    eapply do_stepb.\n    auto.\n    eapply bStep_vany;eauto.\n    apply ttyp_anno; eauto.\n    eapply ttyp_sim; eauto.\n    apply BA_AB; auto.\n    +\n    inverts H. inverts H1.\n    inverts lc.\n    exists. splits.\n    eapply star_trans.\n    apply star_one.\n    apply bStep_dyna; auto.\n    apply star_one.\n    rewrite fillb_cast.\n    eapply do_stepb.\n    auto.\n    eapply bStep_vany;eauto.\n    apply ttyp_anno; eauto.\n    eapply ttyp_sim; eauto.\n    apply BA_AB; auto.\n  -\n    inverts Typ. inverts* H2. inverts* H5;\n    try solve[forwards*: abs_nlam].\n    inverts* H12; try solve[inverts H11].\n    +\n    exists. splits.\n    apply star_one.\n    apply bStep_vany; eauto.\n    forwards*: value_valueb val. inverts* H.\n    eapply ttyp_anno2; eauto.\n    +\n    exists. splits.\n    apply star_one.\n    apply bStep_vany; eauto.\n    forwards*: value_valueb val. inverts* H.\n    eapply ttyp_anno2; eauto.\n  - \n    inverts Typ. inverts val.\n    inverts H9. inverts H12; try solve[forwards: abs_nlam H1;inverts H2].\n    inverts H14;try solve[forwards: abs_nlam H1;inverts H2] .\n    forwards: principle_if2 H11. auto.\n    rewrite H2 in *.\n    inverts H. inverts H6.\n    inverts H8; try solve[forwards: abs_nlam H1;inverts H2];\n    try solve[exfalso; apply H3; auto].\n    inverts H4; try solve[inverts* H0].\n    rewrite <- TEMP in H0. inverts H0.\n    forwards: value_valueb H11.\n    auto.\n    exists. split.\n    eapply star_trans.\n    apply star_one.\n    apply bStep_dyna.\n    auto. auto. auto. auto.\n    apply star_one.\n    rewrite fillb_cast.\n    apply do_stepb.\n    auto.\n    apply bStep_vany.\n    auto. auto.\n    apply ttyp_anno.\n    eapply ttyp_sim.\n    rewrite <- TEMP in *.\n    auto. auto. auto. auto.\n  - inverts Typ. inverts val.\n    inverts H3.\n    inverts H9; try solve[forwards*: abs_nlam]. \n    inverts H11; try solve[forwards*: abs_nlam].\n    forwards*: principle_if2 H8.\n    rewrite H0 in *.\n    forwards: value_valueb H8.\n    auto.\n    exists. split.\n    apply star_one.\n    apply bStep_vany; eauto.\n    auto.\nQed.\n  \n\n\n\nTheorem typing_elaborate_soundness_chk2: forall l b B e t e' A,\n  ttyping nil e (Chk2 l b B) A t ->\n  step e (e_exp e') ->\n  exists t', bsteps t (t_term t') /\\ ttyping nil e' (Chk2 l b B) A t' .\nProof.\n  introv Typ Red. gen l b B t A.\n  inductions Red; intros.\n  - \n     destruct E; unfold fill in *; simpl in *.\n    +\n    forwards* lc: ttyping_regular_3 Typ.\n    inverts Typ; simpl in *.\n    inverts H5; try solve[inverts H0;inverts* H6]; simpl in *.\n    *\n    forwards*: ttyping_chk H10.\n    lets(ll1&bb1&tb1&tb2&ttyp1):H0.\n    forwards*: IHRed ttyp1. \n    lets(vv1&rred1&ttyp2): H1.\n    forwards*: step_not_nlam Red.\n    inverts ttyp2;\n    try solve[inverts H2].\n    forwards*: ttyping_typing H10; simpl in *.\n    forwards*: preservation Red.\n    forwards*: typing_ttyping H12 H4. \n    subst*.\n    inverts lc.\n    exists. splits.\n    apply multi_red_app2.\n    auto. apply rred1.\n    eapply ttyp_sim; eauto.\n    *\n    forwards*: ttyping_chk H10.\n    lets(ll1&bb1&tb1&tb2&ttyp1):H0.\n    forwards*: IHRed ttyp1. \n    lets(vv1&rred1&ttyp2): H1.\n    forwards*: step_not_nlam Red.\n    inverts ttyp2;\n    try solve[inverts H2].\n    forwards*: ttyping_typing H10; simpl in *.\n    forwards*: preservation Red.\n    forwards*: typing_ttyping H12 H4. \n    subst*.\n    inverts lc.\n    exists. splits.\n    apply multi_red_app2.\n    auto. \n    apply multi_red_cast.\n    apply rred1.\n    eapply ttyp_sim; eauto.\n    +\n     forwards* lc: ttyping_regular_3 Typ.\n     inverts Typ; simpl in *.\n     inverts H5; try solve[inverts H0;inverts* H6]; simpl in *.\n     *\n      inverts lc. inverts H.\n      forwards*: value_valueb H10.\n      forwards* lc2: ttyping_regular_1 H11.\n      inverts lc2.\n      inverts H11; try solve[\n        forwards*: step_not_value Red\n      ].\n      forwards*: IHRed H16. \n      lets(vv1&rred1&ttyp1): H0.\n      exists. splits.\n      apply multi_red_app.\n      auto.\n      apply multi_red_cast. \n      apply rred1.\n      apply ttyp_sim; eauto.\n      eapply ttyp_app; eauto.\n      forwards*: step_not_nlam Red.\n    *\n      inverts lc. inverts H.\n      forwards*:principle_if2 H10.\n      rewrite H in *. inverts H4.\n    +\n    forwards* lc: ttyping_regular_1 Typ. inverts lc.\n    inverts Typ.\n    forwards* lc2: ttyping_regular_3 H6.\n    inverts H6;\n    try solve[\n    forwards*: step_not_value Red\n    ].\n    forwards*: IHRed H11. \n    lets(vv1&rred1&ttyp1): H0.\n    exists. splits.\n    apply multi_red_cast.\n    apply rred1.\n    forwards*: step_not_nlam Red.\n    +\n    inverts H.\n    forwards* lc: ttyping_regular_3 Typ.\n    inverts Typ; simpl in *.\n    inverts H5; try solve[inverts H0;inverts* H6]; simpl in *.\n    *\n    forwards*: ttyping_chk H2.\n    lets(ll1&bb1&tb1&tb2&ttyp1):H.\n    forwards*: IHRed ttyp1. \n    lets(vv1&rred1&ttyp2): H0.\n    forwards*: step_not_nlam Red.\n    inverts ttyp2;\n    try solve[inverts H3].\n    forwards*: ttyping_typing H13; simpl in *.\n    forwards*: ttyping_typing H2; simpl in *.\n    forwards*: preservation Red.\n    forwards*: typing_ttyping H10. \n    subst*.\n    inverts lc.\n    exists. splits.\n    apply multi_red_app2.\n    auto. apply rred1.\n    eapply ttyp_sim; eauto.\n    +\n    inverts H.\n    forwards* lc: ttyping_regular_3 Typ.\n     inverts Typ; simpl in *.\n     inverts H5; try solve[inverts H0;inverts* H6]; simpl in *.\n     *\n      inverts lc.\n      forwards*: value_valueb H2.\n      forwards* lc2: ttyping_regular_1 H4.\n      forwards*: ttyping_chk H4.\n      lets(ll1&bb1&tb1&tb2&ttyp1):H0.\n      forwards*: IHRed ttyp1. \n      lets(vv2&rred2&ttyp2): H7.\n      forwards*: step_not_nlam Red.\n      inverts ttyp2; try solve[forwards*: abs_nlam].\n      forwards*: ttyping_typing H4; simpl in *.\n      forwards*: preservation Red.\n      forwards*: typing_ttyping H16.\n      subst*. \n      exists. splits.\n      apply multi_red_app.\n      auto.\n      apply rred2.\n      apply ttyp_sim; eauto.\n  -\n    inverts Typ. inverts H6. \n    inverts* H3; try solve[forwards*: abs_nlam].\n    forwards*: value_valueb H5.\n    forwards*: value_valueb H16.\n    inverts* H16; try solve[inverts H17].\n    +\n    inverts H2.\n    exists. splits.\n    apply star_one.\n    apply bStep_beta; eauto.\n    pick fresh y.\n    rewrite (subst_exp_intro y); eauto.\n    rewrite (subst_term_intro y); eauto.\n    forwards*: H18 y.\n    simpl in *.\n    eapply ttyp_sim; eauto.\n    eapply ttyp_anno; eauto.\n    eapply ttyping_c_subst_simpl; eauto.\n    forwards*: nlam_open3 y H19.\n    forwards*: nlam_open2 y H7 H3.\n    +\n    forwards* h1: nlam_exist H19.\n    lets (ee& ll & bb&hh1):h1. inverts hh1. \n    pick fresh y.\n    forwards* h2: not_nlam_open v y H19.\n    inverts H2.\n    exists. splits.\n    apply star_one.\n    apply bStep_beta; eauto.\n    unfold open_term_wrt_term; simpl.\n    assert((open_term_wrt_term_rec 0 t2 t) = (open_term_wrt_term t t2)); eauto.\n    rewrite H2.\n    rewrite (subst_exp_intro y); eauto.\n    rewrite (subst_term_intro y); eauto.\n    forwards*: H18 y.\n    unfold open_exp_wrt_exp in *.\n    simpl in *.\n    forwards*:ttyping_c_subst_simpl H3 H5.\n  -\n    inverts Typ. \n    assert(A = B). inverts* H7. subst*.\n    forwards*: tTypedReduce_soundness2 H7.\n    inverts H2. inverts* H3.\n    exists. splits.\n    apply H2.\n    forwards*: TypedReduce_walue3 H0.\n  -\n    inverts Typ. inverts H8.\n    forwards*: value_valueb H5.\n    forwards*: value_valueb H7.\n    inverts H5; try solve[inverts H0].\n    inverts H3. \n    inverts H18; try solve[forwards*: abs_nlam].\n    forwards* h1: principle_if2 H14.\n    rewrite h1 in *. inverts H2.\n    inverts* H17.\n    exists. splits.\n    apply star_one.\n    apply bStep_abeta;eauto.\n    eapply ttyp_sim;eauto.\n    eapply ttyp_anno; eauto.\n  -\n    inverts Typ. inverts H8.\n    +\n    forwards*: value_valueb H13.\n    forwards*: principle_if2 H13.\n    rewrite H4 in *. inverts H1.\n    forwards*: tTypedReduce_soundness2 H14.\n    forwards*: TypedReduce_walue3 H2.\n    inverts H1. inverts* H6.\n    exists. splits.\n    apply multi_red_app.\n    auto. apply H1.\n    eapply ttyp_sim; eauto.\n    +\n    forwards*: principle_if2 H13.\n    rewrite H3 in *. inverts H1.\n  -\n    inverts Typ. inverts* H6. \n    + inverts* H11.\n    +\n    exists. splits.\n    apply bstep_refl.\n    eapply ttyp_sim; eauto.\n  -\n    inverts Typ. inverts H4.\n    inverts H1.\n  -\n    inverts Typ. inverts H4.\n    inverts H1.\n  -\n    inverts Typ. inverts H6. \n    forwards*: value_valueb H3.\n    forwards*: value_valueb H5.\n    inverts* H3; try solve[forwards*: abs_nlam].\n    +\n    inverts H1.\n    exists. splits.\n    apply star_one.\n    apply bStep_beta; eauto.\n    pick fresh y.\n    rewrite (subst_exp_intro y); eauto.\n    rewrite (subst_term_intro y); eauto.\n    forwards*: H15 y.\n    simpl in *.\n    eapply ttyp_sim; eauto.\n    eapply ttyp_anno; eauto.\n    eapply ttyping_c_subst_simpl; eauto.\n    forwards*: nlam_open3 y H16.\n    forwards*: nlam_open2 y H7 H3.\n    +\n    forwards* h1: nlam_exist H16. \n    lets (ee& ll & bb&hh1):h1. inverts hh1.\n    pick fresh y.\n    forwards*: not_nlam_open v y H16.\n    inverts H1.\n    exists. splits.\n    apply star_one.\n    apply bStep_beta; eauto.\n    unfold open_term_wrt_term; simpl.\n    assert((open_term_wrt_term_rec 0 t2 t) = (open_term_wrt_term t t2)); eauto.\n    rewrite H1.\n    rewrite (subst_exp_intro y); eauto.\n    rewrite (subst_term_intro y); eauto.\n    forwards*: H15 y.\n    unfold open_exp_wrt_exp in *.\n    simpl in *.\n    forwards*:ttyping_c_subst_simpl H4 H5.\nQed.\n\n\n\n\nTheorem typing_elaborate_soundness_dir2: forall dir e t e' A ,\n  ttyping nil e dir A t ->\n  step e (e_exp e') ->\n  exists t', bsteps t (t_term t') /\\ ttyping nil e' dir A t' .\nProof.\n  introv Typ Red. \n  destruct dir.\n  -\n   forwards*: ttyping_chk Typ. \n   inverts H. inverts H0. inverts* H. inverts H0.\n   forwards*: typing_elaborate_soundness_chk2 Red.\n   inverts H0. inverts H1.\n   forwards*: step_nlam Red.\n   inverts* H2; try solve[exfalso; apply H1; eauto].\n   forwards*: ttyping_typing Typ; simpl in *.\n   forwards*: preservation Red.\n   forwards*: typing_ttyping H8 H3.\n   subst*.\n  -\n  forwards*: typing_elaborate_soundness_chk2 Red.\nQed.\n\n\n\nTheorem typing_elaborate_soundness2: forall dir e t e' A ,\n  ttyping nil e dir A t ->\n  steps e (e_exp e') ->\n  value e' ->\n  exists t', bsteps t (t_term t') /\\ valueb t' /\\ ttyping nil e' dir A t' .\nProof.\n  introv Typ Red val. gen dir A t.\n  inductions Red; intros;eauto.\n  -\n   forwards*: value_valueb Typ.\n  -\n   forwards*: typing_elaborate_soundness_dir2 H.\n   inverts* H0. inverts H1.\n   forwards*: IHRed H2.\n   lets(vv&rred&vval&ell): H1.\n   exists. splits.\n   eapply star_trans.\n   apply H0. apply rred.\n   auto. auto.\nQed.", "meta": {"author": "YeWenjia", "repo": "TypedDirectedGradualTypingWithBlame", "sha": "99210b5208555d4ea729738ea4a959c59b0646d0", "save_path": "github-repos/coq/YeWenjia-TypedDirectedGradualTypingWithBlame", "path": "github-repos/coq/YeWenjia-TypedDirectedGradualTypingWithBlame/TypedDirectedGradualTypingWithBlame-99210b5208555d4ea729738ea4a959c59b0646d0/JFP-Artifact/\\Bg(label)/coq/soundness_completeness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.26178999985308476}}
{"text": "Add LoadPath \"???\\syntax\".\nAdd LoadPath \"???\\substitution\".\nAdd LoadPath \"???\\type_system\".\nAdd LoadPath \"???\\operational_semantics\".\nAdd LoadPath \"???\\logic\".\nRequire Export type_aux_lemmas operational_semantics.\n\n(* ==================== Substitution Lemma ==================== *)\n\nFixpoint v_subs_out_typesafe Γ v A v_s A_s {struct v}:\n  has_vtype (CtxU Γ A_s) v A -> has_vtype Γ v_s A_s ->\n  has_vtype Γ (v_subs_out v v_s) A\n\nwith c_subs_out_typesafe Γ c C v_s A_s {struct c}:\n  has_ctype (CtxU Γ A_s) c C -> has_vtype Γ v_s A_s ->\n  has_ctype Γ (c_subs_out c v_s) C\n\nwith h_subs_out_typesafe Γ h Σ D v_s A_s {struct h}:\n  has_htype (CtxU Γ A_s) h Σ D -> has_vtype Γ v_s A_s ->\n  has_htype Γ (h_subs_out h v_s) Σ D.\n\nProof.\n{\nintros orig sub. unfold v_subs_out.\nassert (CtxU Γ A_s = ctx_insert Γ 0 A_s) by (destruct Γ; auto).\neapply v_subs_typesafe; eauto. destruct Γ; omega.\n}{\nintros orig sub. unfold c_subs_out.\nassert (CtxU Γ A_s = ctx_insert Γ 0 A_s) by (destruct Γ; auto).\neapply c_subs_typesafe; eauto. destruct Γ; omega.\n}{\nintros orig sub. unfold h_subs_out.\nassert (CtxU Γ A_s = ctx_insert Γ 0 A_s) by (destruct Γ; auto).\neapply h_subs_typesafe; eauto. destruct Γ; omega.\n}\nQed.\n\n(* ==================== Preservation ==================== *)\n\nTheorem preservation Γ c c' C:\n  has_ctype Γ c C -> step c c' -> has_ctype Γ c' C.\nProof.\nintros orig step. revert C orig. \ninduction step; intros C' orig.\nall: try unfold c_subs2_out.\n+ apply shape_prodmatch in orig. destruct orig as [A [B [pair]]].\n  apply shape_pair in pair. destruct pair.\n  eapply c_subs_out_typesafe. eapply c_subs_out_typesafe.\n  all: eauto. inv H0. apply v_shift_typesafe; auto.\n+ apply shape_summatch in orig.\n  destruct orig as [A' [B' [vty [l _]]]].\n  eapply c_subs_out_typesafe. eauto. eapply shape_left in vty. 2: reflexivity.\n  destruct vty. inv H0. inv l. inv H0. \n  apply TypeV; auto. eapply TypeVSubsume; eauto.\n+ apply shape_summatch in orig.\n  destruct orig as [A' [B' [vty [_ r]]]].\n  eapply c_subs_out_typesafe. eauto. eapply shape_right in vty. 2: reflexivity.\n  destruct vty. inv H0. inv r. inv H0. \n  apply TypeV; auto. eapply TypeVSubsume; eauto.\n+ apply shape_listmatch in orig.\n  destruct orig as [A'[_[ty1 _]]]. auto.\n+ apply shape_listmatch in orig. destruct orig as [A[vty[_ ty2]]]. \n  apply shape_cons in vty. destruct vty as [vty vsty].  \n  eapply c_subs_out_typesafe; eauto. eapply c_subs_out_typesafe; eauto.\n  eapply v_shift_typesafe; eauto. inv vty. auto.\n+ apply shape_app in orig. destruct orig.\n  eapply c_subs_out_typesafe; eauto.\n+ eapply shape_letrec_full in orig. 2: reflexivity.\n  destruct orig as [c1ty c2ty].\n  eapply c_subs_out_typesafe; eauto. apply TypeV. inv c1ty.\n  inv H. inv H4. auto. inv c2ty. inv H. auto. \n  apply TypeFun. apply TypeC. \n  - inv c1ty. inv H. auto.\n  - inv c1ty. auto.\n  - eapply TypeLetRec; auto.\n    assert (CtxU (CtxU (CtxU Γ A) A) (TyFun A C) \n      = ctx_insert (CtxU (CtxU Γ A) (TyFun A C)) 2 A)\n    as insertion. { simpl. destruct Γ; auto. }\n    rewrite insertion. apply c_insert_typesafe. auto.\n    inv c2ty. inv H. inv H5. auto.\n+ destruct C' as (A, Σ, E) eqn:e. apply shape_do in orig.\n  destruct orig as [A' [c1ty]].\n  apply TypeC. inv c1ty. 3 : eapply TypeDo. all: eauto. inv H. auto.\n+ destruct C' as (A, Σ, E) eqn:e. apply shape_do in orig.\n  destruct orig as [A' [c1ty]]. eapply c_subs_out_typesafe. eauto.\n  apply shape_ret in c1ty. auto.\n+ destruct C' as (Ac, Σ, E) eqn:e. apply shape_do in orig.\n  destruct orig as [A' [c1ty]]. eapply shape_op_full in c1ty; eauto.\n  destruct c1ty as [vty[cty[Aop[Bop[gets[stya styb]]]]]]. apply TypeC.\n  - inv vty. auto.\n  - inv H. auto.\n  - eapply TypeOp; eauto. \n    eapply TypeC. inv cty. auto. inv H. auto.\n    eapply TypeDo; eauto.\n    assert (CtxU (CtxU Γ B) A' = ctx_insert (CtxU Γ A') 1 B) as same.\n    { simpl. destruct Γ; auto. }\n    rewrite same. apply c_insert_typesafe. auto.\n    inv cty. inv H0. auto.\n+ eapply shape_handle in orig. destruct orig as [C [hty]]. \n  apply TypeC. inv hty. auto. inv hty. inv H1. auto.\n  eapply TypeHandle; eauto.\n+ eapply shape_handle in orig. rename C' into D. destruct orig as [C[hty]].\n  destruct C as (A', Σ, E). eapply shape_handler in hty as hty'. \n  destruct hty' as [Σ'[D'[retty[hcty[r[sta[sty csty]]]]]]]. eapply shape_ret in H.\n  eapply c_subs_out_typesafe; eauto. apply TypeC. \n  - inv H. apply WfCtxU; auto.\n  - inv hty. inv H1. auto.\n  - eapply TypeCSubsume; eauto. inv H.\n    eapply ctx_subtype_ctype; eauto; apply WfCtxU || apply STyCtxU; auto.\n    apply ctx_subtype_refl. auto.\n+ eapply shape_handle in orig. rename C' into D. \n  destruct orig as [C[hty]]. destruct C as (Ac, Σ, E).\n  eapply shape_handler in hty as hty'.\n  destruct hty' as [Σ'[D'[retty[hcty[r[sta[stysig styd]]]]]]].\n  eapply shape_op_full in H0 as opt; eauto.\n  destruct opt as [vty[cty[Aop'[Bop'[gets[stya styb]]]]]].\n  assert (wf_ctx Γ) by (inv hty; auto). \n  apply TypeC; auto. inv hty. inv H3. auto.\n  eapply TypeCSubsume; eauto.\n  assert (wf_vtype Aop) as wfa by (inv vty; auto).\n  assert (wf_vtype Bop) as wfb by (inv cty; inv H2; auto).\n  assert (wf_ctype D') as wfd by (inv hcty; auto).\n  eapply c_subs_out_typesafe; eauto.\n  eapply c_subs_out_typesafe.\n  instantiate (1:= TyFun Bop D').\n  - eapply sig_subtype_get_Some in gets; eauto.\n    destruct gets as [A'[B'[gets']]]. inv H2.\n    eapply ctx_subtype_ctype. eapply case_has_type; eauto.\n    * apply WfCtxU. apply WfCtxU. 3: apply WfTyFun. all: auto.\n    * apply STyCtxU. apply STyCtxU.\n      apply ctx_subtype_refl; auto. auto.\n      eapply vsubtype_trans; eauto.\n      apply STyFun; auto. eapply vsubtype_trans; eauto. \n      apply csubtype_refl. all: auto.\n  - apply v_shift_typesafe; auto.\n    apply TypeV. auto. apply WfTyFun; auto.\n    eapply TypeFun. apply TypeC. apply WfCtxU. all: auto.\n    eapply TypeHandle. 2: eauto.\n    assert (CtxU Γ Bop = ctx_insert Γ 0 Bop) as same.\n    { destruct Γ; simpl; auto. }\n    rewrite same. eapply v_insert_typesafe. 2: auto.\n    apply TypeV. auto. apply WfTyHandler. inv H0. auto. auto.\n    assert (wf_sig Σ') as wfsig by (inv hcty; auto).\n    eapply TypeVSubsume. instantiate (1:=(TyHandler (CTy A Σ' E) D')).\n    * inv H0. inv H3.\n      apply TypeV. auto. apply WfTyHandler; auto. apply WfCTy; auto.\n      inv retty. inv H0. auto.\n      eapply wf_eqs_sig_subtype; eauto. apply TypeHandler; auto.\n    * inv H0. inv H3.\n      apply STyHandler. apply STyCTy; auto.\n      eapply eqs_subtype_refl; eauto.\n      apply csubtype_refl. auto.\nQed.\n\n(* ==================== Progress ==================== *)\n\nTheorem progress c C:\n  has_ctype CtxØ c C ->\n  (exists v, c = Ret v) \\/\n  (exists o A B v c', c = Op o A B v c') \\/\n  (exists c', step c c'). \nProof.\nrevert C. induction c; intros C orig.\n+ left. eauto.\n+ apply shape_absurd in orig. apply shape_empty in orig as shape. \n  destruct shape. subst. apply shape_var_ctx_empty in orig.\n  destruct orig.\n+ right. right. clear IHc.\n  eapply shape_prodmatch in orig. destruct orig as [A [B [vty]]].\n  eapply shape_prod_full in vty as shape. 2: reflexivity.\n  destruct shape.\n  - destruct H0 as [n same]. rewrite same in *.\n    apply shape_var_ctx_empty in vty. destruct vty.\n  - destruct H0 as [v1[v2[same[ty1]]]]. subst.\n    eexists. apply Step_MatchPair.\n+ right. right. clear IHc1 IHc2.\n  eapply shape_summatch in orig. destruct orig as [A [B [vty]]].\n  eapply shape_sum_full in vty as shape. 2: reflexivity.\n  destruct shape. 2: destruct H0.\n  - destruct H0 as [n same]. rewrite same in *.\n    apply shape_var_ctx_empty in vty. destruct vty.\n  - destruct H0 as [v'[A'[B'[same]]]].\n    rewrite same. eexists. apply Step_MatchLeft.\n  - destruct H0 as [v'[A'[B'[same]]]].\n    rewrite same. eexists. apply Step_MatchRight.\n+ right. right.\n  eapply shape_listmatch in orig. destruct orig as [A[vty[cty1 cty2]]].\n  eapply shape_list_full in vty as shape; eauto. destruct shape.\n  destruct H as [n same]. subst. apply shape_var_ctx_empty in vty. destruct vty. \n  destruct H.\n  - exists c1. destruct H. subst. apply Step_MatchNil.\n  - destruct H as [w[ws[same[wty wsty]]]]. subst. \n    eexists. apply Step_MatchCons. \n+ right. right.\n  eapply shape_app_full in orig. 2: reflexivity.\n  destruct orig as [A [fty]]. eapply shape_tyfun_full in fty as ffty.\n  2: reflexivity. destruct ffty.\n  - destruct H0 as [n same]. rewrite same in *.\n    apply shape_var_ctx_empty in fty. destruct fty.\n  - destruct H0 as [x [c [same]]]. subst. eexists. apply Step_AppFun.\n+ right. left. exists o, v, v0, v1, c. auto.\n+ right. right. clear IHc1 IHc2.\n  eexists. apply Step_LetRecStep.\n+ right. right. clear IHc2. destruct C as (A, Σ, E). \n  eapply shape_do in orig. destruct orig as [A' [c1ty]].\n  apply IHc1 in c1ty as IH. clear IHc1. destruct IH as [h1 | [h2 | h3]].\n  - destruct h1. rewrite H0 in *. eexists. apply Step_DoRet.\n  - destruct h2. destruct H0 as [Aop[Bop[v[c same]]]]. rewrite same in *.\n    eexists. apply Step_DoOp.\n  - destruct h3. eexists. apply Step_DoStep. exact H0.\n+ right. right. eapply shape_handle in orig. rename C into D.\n  destruct orig as [C [hty]]. apply IHc in H as H'. clear IHc.\n  destruct C as (A, Σ, E). eapply shape_tyhandler_full in hty as shape.\n  2: reflexivity. destruct shape.\n  { destruct H0 as [n same]. subst.\n    apply shape_var_ctx_empty in hty. contradiction. }\n  destruct H0 as [c_r[h[A'[Σ'[D'[same[crty]]]]]]]. subst.\n  destruct H'. 2: destruct H1.\n  - destruct H1 as [v]. subst. eexists. apply Step_HandleRet.   \n  - destruct H1 as [op[Aop[Bop[v[c']]]]]. subst.\n    destruct H0 as [hcsty[r[stya[sigsty styd]]]].\n    eapply shape_op_full in H; eauto.\n    destruct H as [vty[cty[A_op[B_op[gets _]]]]].\n    eapply sig_subtype_get_Some in gets. 2: exact sigsty.\n    destruct gets as [A''[B''[gets']]].\n    eapply h_has_case in hcsty. 2: exact gets'.\n    destruct hcsty as [c_op finds].\n    eexists. eapply Step_HandleOp. eauto.    \n  - destruct H1 as [c']. eexists. apply Step_HandleStep. exact H1.\nQed.\n", "meta": {"author": "zigaLuksic", "repo": "eeff-formalization", "sha": "df4cc420b116b12bc839bcb9ba0e426bebee333c", "save_path": "github-repos/coq/zigaLuksic-eeff-formalization", "path": "github-repos/coq/zigaLuksic-eeff-formalization/eeff-formalization-df4cc420b116b12bc839bcb9ba0e426bebee333c/type_system/type_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2617899998530847}}
{"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.\n\nSection WithCava.\n  Context {signal} `{Cava signal}.\n\n  (* A top-level multiplier circuit that can be compiled to a top-level\n    SystemVerilog circuit. *)\n  Definition multiplier {aSize bSize: nat}\n                        (ab: signal (Vec Bit aSize) * signal (Vec Bit bSize)):\n                        cava (signal (Vec Bit (aSize + bSize))) :=\n    unsignedMult ab.\n\nEnd WithCava.\n\nDefinition bv2_0  := N2Bv_sized 2  0.\nDefinition bv2_3  := N2Bv_sized 2  3.\nDefinition bv3_0  := N2Bv_sized 3  0.\nDefinition bv3_5  := N2Bv_sized 3  5.\nDefinition bv3_7  := N2Bv_sized 3  7.\nDefinition bv5_15 := N2Bv_sized 5 15.\n\n(* Check 3 * 5 = 30 *)\nExample mult3_5 : multiplier (bv2_3, bv3_5) = bv5_15.\nProof. reflexivity. Qed.\n\n(* Check 3 * 5 = 30 *)\nExample mult3_5_top : multiplier (bv2_3, bv3_5) = bv5_15.\nProof. reflexivity. Qed.\n\n(******************************************************************************)\n(* Generate an unsigned multiplier with 2 and 3 bit inputs and 5-bit result.  *)\n(******************************************************************************)\n\nDefinition mult2_3_5Interface\n  := combinationalInterface \"mult2_3_5\"\n     [mkPort \"a\" (Vec Bit 2); mkPort \"b\" (Vec Bit 3)]\n     [mkPort \"product\" (Vec Bit 5)].\n\nDefinition mult2_3_5Netlist\n  := makeNetlist mult2_3_5Interface multiplier.\n\nDefinition mult2_3_5_tb_inputs\n  := [(bv2_3, bv3_5); (bv2_3, bv3_7); (bv2_0, bv3_0)].\n\nDefinition mult2_3_5_tb_expected_outputs\n  := simulate (Comb multiplier) mult2_3_5_tb_inputs.\n\nDefinition  mult2_3_5_tb\n  := testBench \"mult2_3_5_tb\" mult2_3_5Interface\n     mult2_3_5_tb_inputs mult2_3_5_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/tests/TestMultiply.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.2617899998530847}}
{"text": "From Velus Require Import Common.\nFrom Velus Require Import Operators.\nFrom Velus Require Import CoreExpr.CESyntax.\nFrom Velus Require Import Stc.StcSyntax.\nFrom Velus Require Import Clocks.\n\nFrom Velus Require Import Stc.StcIsVariable.\nFrom Velus Require Import Stc.StcIsLast.\n\nFrom Coq Require Import List.\nImport List.ListNotations.\nOpen Scope list_scope.\n\nModule Type STCISDEFINED\n       (Import Ids   : IDS)\n       (Import Op    : OPERATORS)\n       (Import CESyn : CESYNTAX          Op)\n       (Import Syn   : STCSYNTAX     Ids Op CESyn)\n       (Import Var   : STCISVARIABLE Ids Op CESyn Syn)\n       (Import Last  : STCISLAST     Ids Op CESyn Syn).\n\n  Inductive Is_defined_in_tc: ident -> trconstr -> Prop :=\n  | DefTcDef:\n      forall x ck e,\n        Is_defined_in_tc x (TcDef x ck e)\n  | DefTcNext:\n      forall x ck e,\n        Is_defined_in_tc x (TcNext x ck e)\n  | DefTcCall:\n      forall x i xs ck rst f es,\n        In x xs ->\n        Is_defined_in_tc x (TcCall i xs ck rst f es).\n\n  Definition Is_defined_in (x: ident) (tcs: list trconstr) : Prop :=\n    Exists (Is_defined_in_tc x) tcs.\n\n  Lemma Is_defined_Is_variable_Is_last_in:\n    forall tcs x,\n      Is_defined_in x tcs <->\n      Is_variable_in x tcs \\/ Is_last_in x tcs.\n  Proof.\n    induction tcs; split.\n    - inversion 1.\n    - intros [E|E]; inversion E.\n    - inversion_clear 1 as [?? Def|?? Defs].\n      + inv Def.\n        * left; left; constructor; auto.\n        * right; left; constructor; auto.\n        * left; left; constructor; auto.\n      + apply IHtcs in Defs as [].\n        * left; right; auto.\n        * right; right; auto.\n    - intros [E|E]; inversion_clear E as [?? E'|].\n      + inv E'.\n        * left; constructor.\n        * left; constructor; auto.\n      + right; apply IHtcs; auto.\n      + inv E'; left; constructor.\n      + right; apply IHtcs; auto.\n  Qed.\n\n  Lemma Is_variable_in_tc_Is_defined_in_tc:\n    forall x tc,\n      Is_variable_in_tc x tc ->\n      Is_defined_in_tc x tc.\n  Proof.\n    destruct tc; inversion_clear 1; auto using Is_defined_in_tc.\n  Qed.\n\n  Lemma Is_variable_in_Is_defined_in:\n    forall x tcs,\n      Is_variable_in x tcs ->\n      Is_defined_in x tcs.\n  Proof.\n    induction tcs; inversion_clear 1 as [?? Var|].\n    - inv Var; left; constructor; auto.\n    - right; auto; apply IHtcs; auto.\n  Qed.\n\n  Lemma s_ins_not_def:\n    forall s x,\n      InMembers x s.(s_in) ->\n      ~ Is_defined_in x s.(s_tcs).\n  Proof.\n    intros * Hin Hdef.\n    pose proof (s_nodup s) as Nodup.\n    eapply (NoDup_app_In x) in Nodup.\n    - apply Is_defined_Is_variable_Is_last_in in Hdef as [Var|Last];\n        apply Nodup; rewrite app_assoc, in_app.\n      + apply Is_variable_in_variables in Var; rewrite <-s_vars_out_in_tcs in Var;\n          auto.\n      + apply lasts_of_In in Last; rewrite <-s_lasts_in_tcs in Last; auto.\n    - apply fst_InMembers; auto.\n  Qed.\n\n  Lemma not_Is_defined_in_tc_TcDef:\n    forall y x ck e,\n      ~ Is_defined_in_tc y (TcDef x ck e) -> x <> y.\n  Proof.\n    intros * NIsDef E; subst; apply NIsDef; auto using Is_defined_in_tc.\n  Qed.\n\n  Lemma not_Is_defined_in_tc_TcNext:\n    forall y x ck e,\n      ~ Is_defined_in_tc y (TcNext x ck e) -> x <> y.\n  Proof.\n    intros * NIsDef E; subst; apply NIsDef; auto using Is_defined_in_tc.\n  Qed.\n\n  Lemma not_Is_defined_in_cons:\n    forall x tc tcs,\n      ~ Is_defined_in x (tc :: tcs)\n      <-> ~ Is_defined_in_tc x tc /\\ ~ Is_defined_in x tcs.\n  Proof.\n    split.\n    - intro Hndef; split; intro His_def;\n        eapply Hndef; now constructor.\n    - intros [Hdef_tc Hdef_tcs] Hdef_all.\n      inv Hdef_all; eauto.\n  Qed.\n\n  Definition defined_tc (tc: trconstr): list ident :=\n    match tc with\n    | TcNext x _ _\n    | TcDef x _ _ => [x]\n    | TcCall _ xs _ _ _ _ => xs\n    | TcReset _ _ _ => []\n    end.\n\n  Definition defined := flat_map defined_tc.\n\n  Lemma Is_defined_in_defined_tc:\n    forall x tc,\n      Is_defined_in_tc x tc <-> In x (defined_tc tc).\n  Proof.\n    destruct tc; split; try inversion_clear 1; subst;\n      simpl; auto using Is_defined_in_tc; try contradiction.\n  Qed.\n\n  Lemma Is_defined_in_defined:\n    forall x tcs,\n      Is_defined_in x tcs <-> In x (defined tcs).\n  Proof.\n    unfold defined.\n    induction tcs; simpl.\n    - split; inversion 1.\n    - split; rewrite in_app.\n      + inversion_clear 1.\n        * left; apply Is_defined_in_defined_tc; auto.\n        * right; apply IHtcs; auto.\n      + intros [?|?].\n        * left; apply Is_defined_in_defined_tc; auto.\n        * right; apply IHtcs; auto.\n  Qed.\n\n  Lemma system_output_defined_in_tcs:\n    forall s x,\n      In x (map fst s.(s_out)) ->\n      Is_defined_in x s.(s_tcs).\n  Proof.\n    intros * Ho.\n    cut (In x (map fst s.(s_vars) ++ map fst s.(s_out))).\n    - intro Hvo; apply Is_variable_in_Is_defined_in, Is_variable_in_variables.\n      now rewrite <-s_vars_out_in_tcs.\n    - apply in_or_app; auto.\n  Qed.\n\n  Lemma Is_defined_in_In:\n    forall x tcs,\n      Is_defined_in x tcs ->\n      exists tc, In tc tcs /\\ Is_defined_in_tc x tc.\n  Proof.\n    induction tcs as [|tc]. now inversion 1.\n    inversion_clear 1 as [? ? Hdef|? ? Hex].\n    - exists tc; split; auto with datatypes.\n    - apply Exists_exists in Hex as (tc' & Hin & Hdef).\n      exists tc'; split; auto with datatypes.\n  Qed.\n\n  Lemma s_defined:\n    forall s,\n      Permutation.Permutation (defined (s_tcs s)) (variables (s_tcs s) ++ lasts_of (s_tcs s)).\n  Proof.\n    unfold defined, variables; intro;\n      induction (s_tcs s) as [|[]]; simpl; auto.\n    - now apply Permutation.Permutation_cons_app.\n    - now rewrite <-app_assoc; apply Permutation.Permutation_app_head.\n  Qed.\n\n  Lemma s_nodup_defined:\n    forall s, NoDup (defined (s_tcs s)).\n  Proof.\n    intros; eapply Permutation.Permutation_NoDup.\n    - apply Permutation.Permutation_sym, s_defined.\n    - rewrite <-s_lasts_in_tcs, <-s_vars_out_in_tcs.\n      rewrite <-app_assoc.\n      eapply NoDup_app_weaken.\n      rewrite Permutation.Permutation_app_comm.\n      apply s_nodup.\n  Qed.\n\n  Lemma Is_last_in_not_Is_variable_in:\n    forall tcs x,\n      NoDup (defined tcs) ->\n      Is_last_in x tcs ->\n      ~ Is_variable_in x tcs.\n  Proof.\n    induction tcs; intros * Nodup Last Var;\n      inversion_clear Last as [?? IsLast|];\n      inversion_clear Var as [?? IsVar|?? IsVar_in].\n    - inv IsLast; inv IsVar.\n    - apply Is_variable_in_Is_defined_in in IsVar_in.\n      inv IsLast.\n      simpl in Nodup; inv Nodup.\n      now apply Is_defined_in_defined in IsVar_in.\n    - apply Is_variable_in_tc_Is_defined_in_tc in IsVar.\n      assert (Is_defined_in x tcs) as Hins by (apply Is_defined_Is_variable_Is_last_in; auto).\n      apply Is_defined_in_defined in Hins; apply Is_defined_in_defined_tc in IsVar.\n      simpl in Nodup; eapply NoDup_app_In in Nodup; eauto.\n    - simpl in Nodup; rewrite Permutation.Permutation_app_comm in Nodup;\n        apply NoDup_app_weaken in Nodup.\n      eapply IHtcs; eauto.\n  Qed.\n\n  Lemma defined_app:\n    forall tcs tcs',\n      defined (tcs ++ tcs') = defined tcs ++ defined tcs'.\n  Proof.\n    unfold defined.\n    induction tcs as [|[]]; simpl; intros; auto.\n    - f_equal; auto.\n    - f_equal; auto.\n    - rewrite <-app_assoc; f_equal; auto.\n  Qed.\n\nEnd STCISDEFINED.\n\nModule StcIsDefinedFun\n       (Ids   : IDS)\n       (Op    : OPERATORS)\n       (CESyn : CESYNTAX          Op)\n       (Syn   : STCSYNTAX     Ids Op CESyn)\n       (Var   : STCISVARIABLE Ids Op CESyn Syn)\n       (Last  : STCISLAST     Ids Op CESyn Syn)\n<: STCISDEFINED Ids Op CESyn Syn Var Last.\n  Include STCISDEFINED Ids Op CESyn Syn Var Last.\nEnd StcIsDefinedFun.\n", "meta": {"author": "INRIA", "repo": "velus", "sha": "116a88bc71f3608ff43ed967895743e8b9a340e0", "save_path": "github-repos/coq/INRIA-velus", "path": "github-repos/coq/INRIA-velus/velus-116a88bc71f3608ff43ed967895743e8b9a340e0/src/Stc/StcIsDefined.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.2617899998530847}}
{"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 auth gmap excl list.\nFrom cap_machine Require Export cap_lang iris_extra rules_base.\n\n\nDefinition specN := nroot .@ \"spec\".\n\n(* heap and register CMRA for the specification *)\n(* These need to be notations rather than definitions, as it otherwise causes performance issues *)\nNotation memspecUR :=\n  (gmapUR Addr (prodR fracR (agreeR (leibnizO Word)))).\nNotation regspecUR :=\n  (gmapUR RegName (prodR fracR (agreeR (leibnizO Word)))).\nNotation memreg_specUR := (prodUR regspecUR memspecUR).\n\n(* CMRA for the specification *)\nNotation exprR := (exclR (leibnizO expr)).\nNotation cfgUR := (prodUR (optionUR exprR) memreg_specUR).\n\nDefinition to_spec_map {L V : Type} `{Countable L} : gmap L V -> gmapUR L (prodR fracR (agreeR (leibnizO V))) :=\n  fmap (λ w, (1%Qp, to_agree w)).\n\n(* the CMRA for the specification side *)\nClass cfgSG Σ := CFGSG {\n  cfg_invG :> inG Σ (authR cfgUR);\n  cfg_name : gname\n}.\n\nSection to_spec_map.\n  Context (L V : Type) `{Countable L}.\n  Implicit Types σ : gmap L V.\n\n  Lemma lookup_to_spec_map_None σ l : σ !! l = None → to_spec_map σ !! l = None.\n  Proof. by rewrite /to_spec_map lookup_fmap=> ->. Qed.\n  Lemma to_spec_map_insert l v σ :\n    to_spec_map (<[l:=v]> σ) = <[l:=(1%Qp, to_agree (v:leibnizO V))]> (to_spec_map σ).\n  Proof. by rewrite /to_spec_map fmap_insert. Qed.\n\n  Lemma spec_map_singleton_included σ l q v :\n    {[l := (q, to_agree v)]} ≼ to_spec_map σ → σ !! l = Some v.\n  Proof.\n    rewrite singleton_included_l=> -[[q' av] []].\n    rewrite /to_spec_map lookup_fmap fmap_Some_equiv => -[v' [Hl [/= -> ->]]].\n    move=> /Some_pair_included_total_2 [_] /to_agree_included /leibniz_equiv_iff -> //.\n  Qed.\n\nEnd to_spec_map.\n\nSection definitionsS.\n  Context `{cfgSG Σ, MachineParameters, invGS Σ}.\n\n  Definition memspec_mapsto (a : Addr) (q : Qp) (w : Word) : iProp Σ :=\n    own cfg_name (◯ (ε, (∅,{[ a := (q, to_agree w) ]}))).\n\n  Definition regspec_mapsto (r : RegName) (q : Qp) (w : Word) : iProp Σ :=\n    own cfg_name (◯ (ε, ({[ r := (q, to_agree w) ]},∅))).\n\n  Definition exprspec_mapsto (e : expr) : iProp Σ :=\n    own cfg_name (◯ (Excl' e : optionUR (exclR (leibnizO expr)),(∅,∅))).\n\n  (* The following invariant contains the authoritative view of specification state *)\n  Definition spec_res (e: leibnizO expr) (σ: gmap RegName Word * gmap Addr Word) : iProp Σ :=\n    (own cfg_name (● (Excl' e,(to_spec_map σ.1,to_spec_map σ.2))))%I.\n  Definition spec_inv (ρ : cfg cap_lang) : iProp Σ :=\n    (∃ e σ, spec_res e σ ∗ ⌜rtc erased_step ρ ([e],σ)⌝)%I.\n  Definition spec_ctx : iProp Σ :=\n    (∃ ρ, inv specN (spec_inv ρ))%I.\n\n  Global Instance memspec_mapsto_timeless l q v : Timeless (memspec_mapsto l q v).\n  Proof. apply _. Qed.\n  Global Instance regspec_mapsto_timeless l q v : Timeless (regspec_mapsto l q v).\n  Proof. apply _. Qed.\n  Global Instance spec_ctx_persistent : Persistent spec_ctx.\n  Proof. apply _. Qed.\n\n  Lemma spec_heap_valid e σ a q w :\n    spec_res e σ ∗ memspec_mapsto a q w -∗ ⌜σ.2 !! a = Some w⌝.\n  Proof.\n    iIntros \"(Hown & Ha)\".\n    iDestruct (own_valid_2 with \"Hown Ha\")\n      as %[[_ [_ ?%spec_map_singleton_included]%prod_included]%prod_included _]%auth_both_valid_discrete.\n    auto.\n  Qed.\n\n  Lemma spec_regs_valid e σ r q w :\n    spec_res e σ ∗ regspec_mapsto r q w -∗ ⌜σ.1 !! r = Some w⌝.\n  Proof.\n    iIntros \"(Hown & Ha)\".\n    iDestruct (own_valid_2 with \"Hown Ha\")\n      as %[[_ [?%spec_map_singleton_included _]%prod_included]%prod_included _]%auth_both_valid_discrete.\n    auto.\n  Qed.\n\n  Lemma spec_expr_valid e e' σ :\n    spec_res e σ ∗ exprspec_mapsto e' -∗ ⌜e = e'⌝.\n  Proof.\n    iIntros \"(Hown & Ha)\".\n    iDestruct (own_valid_2 with \"Hown Ha\")\n      as %[[? _]%prod_included _]%auth_both_valid_discrete.\n    assert (e ≡ e') as Heq.\n    { apply symmetry. apply Excl_included. auto. }\n    iPureIntro. apply leibniz_equiv. auto.\n  Qed.\n\n  Lemma regspec_mapsto_agree l q1 q2 v1 v2 : regspec_mapsto l q1 v1 -∗ regspec_mapsto l q2 v2 -∗ ⌜v1 = v2⌝.\n  Proof.\n    iIntros \"Hr1 Hr2\". iCombine \"Hr1 Hr2\" as \"Hr\".\n    rewrite /regspec_mapsto own_valid !uPred.discrete_valid\n            !auth_frag_valid.\n    iDestruct \"Hr\" as %[_ [[_ Hr]%singleton_valid _]].\n    simpl in Hr. apply @to_agree_op_inv_L with (A:=leibnizO Word) in Hr;auto. apply _.\n  Qed.\n  Lemma regspec_mapsto_valid r q v : regspec_mapsto r q v -∗ ✓ q.\n  Proof.\n    rewrite /regspec_mapsto own_valid !uPred.discrete_valid\n            !auth_frag_valid. iPureIntro.\n    intros [_ [[? _]%singleton_valid _]]. auto.\n  Qed.\n  Lemma regspec_mapsto_valid_2 r q1 q2 v1 v2 :\n    regspec_mapsto r q1 v1 -∗ regspec_mapsto r q2 v2 -∗ ✓ (q1 + q2)%Qp.\n  Proof.\n    iIntros \"Hr1 Hr2\".\n    iDestruct (regspec_mapsto_agree with \"Hr1 Hr2\") as %->.\n    iCombine \"Hr1 Hr2\" as \"Hr\".\n    by iApply regspec_mapsto_valid.\n  Qed.\n  Lemma regspec_mapsto_update e (σ : gmap RegName Word * gmap Addr Word) r (w w' : Word) :\n    spec_res e σ -∗ regspec_mapsto r 1 w ==∗ spec_res e (<[r:=w']> σ.1,σ.2) ∗ regspec_mapsto r 1 w'.\n  Proof.\n    iIntros \"Hσ Hr\".\n    iDestruct (spec_regs_valid with \"[$Hσ $Hr]\") as %Hr.\n    rewrite /spec_res /regspec_mapsto.\n    iMod (own_update_2 with \"Hσ Hr\") as \"[Hσ Hr]\".\n    { eapply auth_update, prod_local_update_2,prod_local_update_1.\n      eapply (singleton_local_update (to_spec_map σ.1) r (1%Qp, to_agree w) _ (1%Qp, to_agree w')).\n      by rewrite lookup_fmap Hr. apply exclusive_local_update. done. }\n    iModIntro. iFrame \"Hr\". iFrame. rewrite -fmap_insert. iFrame.\n  Qed.\n\n  Lemma memspec_mapsto_agree l q1 q2 v1 v2 : memspec_mapsto l q1 v1 -∗ memspec_mapsto l q2 v2 -∗ ⌜v1 = v2⌝.\n  Proof.\n    iIntros \"Hr1 Hr2\". iCombine \"Hr1 Hr2\" as \"Hr\".\n    rewrite /regspec_mapsto own_valid !uPred.discrete_valid\n            !auth_frag_valid.\n    iDestruct \"Hr\" as %[_ [_ [_ Hr]%singleton_valid]].\n    simpl in Hr. apply @to_agree_op_inv_L with (A:=leibnizO Word) in Hr;auto. apply _.\n  Qed.\n  Lemma memspec_mapsto_valid r q v : memspec_mapsto r q v -∗ ✓ q.\n  Proof.\n    rewrite /memspec_mapsto own_valid !uPred.discrete_valid\n            !auth_frag_valid. iPureIntro.\n    intros [_ [_ [? _]%singleton_valid]]. auto.\n  Qed.\n  Lemma memspec_mapsto_valid_2 r q1 q2 v1 v2 :\n    memspec_mapsto r q1 v1 -∗ memspec_mapsto r q2 v2 -∗ ✓ (q1 + q2)%Qp.\n  Proof.\n    iIntros \"Hr1 Hr2\".\n    iDestruct (memspec_mapsto_agree with \"Hr1 Hr2\") as %->.\n    iCombine \"Hr1 Hr2\" as \"Hr\".\n    by iApply memspec_mapsto_valid.\n  Qed.\n  Lemma memspec_mapsto_update e (σ : gmap RegName Word * gmap Addr Word) r (w w' : Word) :\n    spec_res e σ -∗ memspec_mapsto r 1 w ==∗ spec_res e (σ.1,<[r:=w']>σ.2) ∗ memspec_mapsto r 1 w'.\n  Proof.\n    iIntros \"Hσ Hr\".\n    iDestruct (spec_heap_valid with \"[$Hσ $Hr]\") as %Hr.\n    rewrite /spec_res /memspec_mapsto.\n    iMod (own_update_2 with \"Hσ Hr\") as \"[Hσ Hr]\".\n    { eapply auth_update, prod_local_update_2,prod_local_update_2.\n      eapply (singleton_local_update (to_spec_map σ.2) r (1%Qp, to_agree w) _ (1%Qp, to_agree w')).\n      by rewrite lookup_fmap Hr. apply exclusive_local_update. done. }\n    iModIntro. iFrame \"Hr\". rewrite -fmap_insert. iFrame.\n  Qed.\n\n  Lemma exprspec_mapsto_update e σ e' :\n    spec_res e σ -∗ exprspec_mapsto e ==∗ spec_res e' σ ∗ exprspec_mapsto e'.\n  Proof.\n    iIntros \"Hσ He\".\n    rewrite /spec_res /exprspec_mapsto.\n    iMod (own_update_2 with \"Hσ He\") as \"[Hσ He]\".\n    { by eapply auth_update, prod_local_update_1, (option_local_update (A:=exprR)),\n      (exclusive_local_update (A:=exprR) _ (Excl e')). }\n    iFrame. done.\n  Qed.\n\nEnd definitionsS.\n#[global] Typeclasses Opaque memspec_mapsto regspec_mapsto exprspec_mapsto.\n\nNotation \"a ↣ₐ{ q } v\" := (memspec_mapsto a q v)\n  (at level 20, q at level 50, format \"a  ↣ₐ{ q }  v\") : bi_scope.\nNotation \"a ↣ₐ v\" := (memspec_mapsto a 1 v) (at level 20) : bi_scope.\nNotation \"r ↣ᵣ{ q } v\" := (regspec_mapsto r q v)\n  (at level 20, q at level 50, format \"r  ↣ᵣ{ q }  v\") : bi_scope.\nNotation \"r ↣ᵣ v\" := (regspec_mapsto r 1 v) (at level 20) : bi_scope.\nNotation \"⤇ e\" := (exprspec_mapsto e) (at level 20) : bi_scope.\n\nLtac iAsimpl :=\n  repeat match goal with\n  | |- context [ (⤇ ?e)%I ] => progress (\n    let e' := fresh in evar (e':expr);\n    assert (e = e') as ->; [simpl; unfold e'; reflexivity|];\n    unfold e'; clear e')\n  | |- context [ WP ?e @ _ {{ _ }}%I ] => progress (\n    let e' := fresh in evar (e':expr);\n    assert (e = e') as ->; [simpl; unfold e'; reflexivity|];\n    unfold e'; clear e')\n         end.\n\nSection cap_lang_spec_resources.\n  Context `{cfgSG Σ, MachineParameters, invGS Σ}.\n\n  (* ------------------------- registers points-to --------------------------------- *)\n\n  Lemma regname_dupl_false r w1 w2 :\n    r ↣ᵣ w1 -∗ r ↣ᵣ w2 -∗ False.\n  Proof.\n    iIntros \"Hr1 Hr2\".\n    iDestruct (regspec_mapsto_valid_2 with \"Hr1 Hr2\") as %?.\n    contradiction.\n  Qed.\n\n  Lemma regname_neq r1 r2 w1 w2 :\n    r1 ↣ᵣ w1 -∗ r2 ↣ᵣ w2 -∗ ⌜ r1 ≠ r2 ⌝.\n  Proof.\n    iIntros \"H1 H2\" (?). subst r1. iApply (regname_dupl_false with \"H1 H2\").\n  Qed.\n\n  Lemma map_of_regs_1 (r1: RegName) (w1: Word) :\n    r1 ↣ᵣ w1 -∗\n    ([∗ map] k↦y ∈ {[r1 := w1]}, k ↣ᵣ y).\n  Proof. by rewrite big_sepM_singleton. Qed.\n\n  Lemma regs_of_map_1 (r1: RegName) (w1: Word) :\n    ([∗ map] k↦y ∈ {[r1 := w1]}, k ↣ᵣ y) -∗\n    r1 ↣ᵣ w1.\n  Proof. by rewrite big_sepM_singleton. Qed.\n\n  Lemma map_of_regs_2 (r1 r2: RegName) (w1 w2: Word) :\n    r1 ↣ᵣ w1 -∗ r2 ↣ᵣ w2 -∗\n    ([∗ map] k↦y ∈ (<[r1:=w1]> (<[r2:=w2]> ∅)), k ↣ᵣ y) ∗ ⌜ r1 ≠ r2 ⌝.\n  Proof.\n    iIntros \"H1 H2\". iPoseProof (regname_neq with \"H1 H2\") as \"%\".\n    rewrite !big_sepM_insert ?big_sepM_empty; eauto.\n    2: by apply lookup_insert_None; split; eauto.\n    iFrame. eauto.\n  Qed.\n\n  Lemma regs_of_map_2 (r1 r2: RegName) (w1 w2: Word) :\n    r1 ≠ r2 →\n    ([∗ map] k↦y ∈ (<[r1:=w1]> (<[r2:=w2]> ∅)), k ↣ᵣ y) -∗\n    r1 ↣ᵣ w1 ∗ r2 ↣ᵣ w2.\n  Proof.\n    iIntros (?) \"Hmap\". rewrite !big_sepM_insert ?big_sepM_empty; eauto.\n    by iDestruct \"Hmap\" as \"(? & ? & _)\"; iFrame.\n    apply lookup_insert_None; split; eauto.\n  Qed.\n\n  Lemma map_of_regs_3 (r1 r2 r3: RegName) (w1 w2 w3: Word) :\n    r1 ↣ᵣ w1 -∗ r2 ↣ᵣ w2 -∗ r3 ↣ᵣ w3 -∗\n    ([∗ map] k↦y ∈ (<[r1:=w1]> (<[r2:=w2]> (<[r3:=w3]> ∅))), k ↣ᵣ y) ∗\n     ⌜ r1 ≠ r2 ∧ r1 ≠ r3 ∧ r2 ≠ r3 ⌝.\n  Proof.\n    iIntros \"H1 H2 H3\".\n    iPoseProof (regname_neq with \"H1 H2\") as \"%\".\n    iPoseProof (regname_neq with \"H1 H3\") as \"%\".\n    iPoseProof (regname_neq with \"H2 H3\") as \"%\".\n    rewrite !big_sepM_insert ?big_sepM_empty; simplify_map_eq; eauto.\n    iFrame. eauto.\n  Qed.\n\n  Lemma regs_of_map_3 (r1 r2 r3: RegName) (w1 w2 w3: Word) :\n    r1 ≠ r2 → r1 ≠ r3 → r2 ≠ r3 →\n    ([∗ map] k↦y ∈ (<[r1:=w1]> (<[r2:=w2]> (<[r3:=w3]> ∅))), k ↣ᵣ y) -∗\n    r1 ↣ᵣ w1 ∗ r2 ↣ᵣ w2 ∗ r3 ↣ᵣ w3.\n  Proof.\n    iIntros (? ? ?) \"Hmap\". rewrite !big_sepM_insert ?big_sepM_empty; simplify_map_eq; eauto.\n    iDestruct \"Hmap\" as \"(? & ? & ? & _)\"; iFrame.\n  Qed.\n\n  Lemma map_of_regs_4 (r1 r2 r3 r4: RegName) (w1 w2 w3 w4: Word) :\n    r1 ↣ᵣ w1 -∗ r2 ↣ᵣ w2 -∗ r3 ↣ᵣ w3 -∗ r4 ↣ᵣ w4 -∗\n    ([∗ map] k↦y ∈ (<[r1:=w1]> (<[r2:=w2]> (<[r3:=w3]> (<[r4:=w4]> ∅)))), k ↣ᵣ y) ∗\n     ⌜ r1 ≠ r2 ∧ r1 ≠ r3 ∧ r1 ≠ r4 ∧ r2 ≠ r3 ∧ r2 ≠ r4 ∧ r3 ≠ r4 ⌝.\n  Proof.\n    iIntros \"H1 H2 H3 H4\".\n    iPoseProof (regname_neq with \"H1 H2\") as \"%\".\n    iPoseProof (regname_neq with \"H1 H3\") as \"%\".\n    iPoseProof (regname_neq with \"H1 H4\") as \"%\".\n    iPoseProof (regname_neq with \"H2 H3\") as \"%\".\n    iPoseProof (regname_neq with \"H2 H4\") as \"%\".\n    iPoseProof (regname_neq with \"H3 H4\") as \"%\".\n    rewrite !big_sepM_insert ?big_sepM_empty; simplify_map_eq; eauto.\n    iFrame. eauto.\n  Qed.\n\n  Lemma regs_of_map_4 (r1 r2 r3 r4: RegName) (w1 w2 w3 w4: Word) :\n    r1 ≠ r2 → r1 ≠ r3 → r1 ≠ r4 → r2 ≠ r3 → r2 ≠ r4 → r3 ≠ r4 →\n    ([∗ map] k↦y ∈ (<[r1:=w1]> (<[r2:=w2]> (<[r3:=w3]> (<[r4:=w4]> ∅)))), k ↣ᵣ y) -∗\n    r1 ↣ᵣ w1 ∗ r2 ↣ᵣ w2 ∗ r3 ↣ᵣ w3 ∗ r4 ↣ᵣ w4.\n  Proof.\n    intros. iIntros \"Hmap\". rewrite !big_sepM_insert ?big_sepM_empty; simplify_map_eq; eauto.\n    iDestruct \"Hmap\" as \"(? & ? & ? & ? & _)\"; iFrame.\n  Qed.\n\n  (* ------------------------- address points-to --------------------------------- *)\n\n  Lemma memMap_resource_2ne (a1 a2 : Addr) (w1 w2 : Word)  :\n    a1 ≠ a2 → ([∗ map] a↦w ∈  <[a1:=w1]> (<[a2:=w2]> ∅), a ↣ₐ w)%I ⊣⊢ a1 ↣ₐ w1 ∗ a2 ↣ₐ w2.\n  Proof.\n    intros.\n    rewrite big_sepM_delete; last by apply lookup_insert.\n    rewrite (big_sepM_delete _ _ a2 w2); rewrite delete_insert; try by rewrite lookup_insert_ne. 2: by rewrite lookup_insert.\n    rewrite delete_insert; auto.\n    iSplit; iIntros \"HH\".\n    - iDestruct \"HH\" as \"[H1 [H2 _ ] ]\".  iFrame.\n    - iDestruct \"HH\" as \"[H1 H2]\". iFrame. done.\n  Qed.\n\n  (* -------------- semantic heap + a map of pointsto: spec side -------------------------- *)\n\n  Lemma memspec_heap_valid_inSepM e σ σ' q l v :\n      σ' !! l = Some v →\n      spec_res e σ -∗\n      ([∗ map] k↦y ∈ σ', memspec_mapsto k q y) -∗\n      ⌜σ.2 !! l = Some v⌝.\n  Proof.\n    intros * Hσ'.\n    rewrite (big_sepM_delete _ σ' l) //. iIntros \"? [? ?]\".\n    iApply (spec_heap_valid with \"[$]\").\n  Qed.\n  Lemma regspec_heap_valid_inSepM e σ σ' q l v :\n      σ' !! l = Some v →\n      spec_res e σ -∗\n      ([∗ map] k↦y ∈ σ', regspec_mapsto k q y) -∗\n      ⌜σ.1 !! l = Some v⌝.\n  Proof.\n    intros * Hσ'.\n    rewrite (big_sepM_delete _ σ' l) //. iIntros \"? [? ?]\".\n    iApply (spec_regs_valid with \"[$]\").\n  Qed.\n\n  Lemma memspec_heap_valid_inSepM' e σ σ' q :\n      spec_res e σ -∗\n      ([∗ map] k↦y ∈ σ', memspec_mapsto k q y) -∗\n      ⌜forall l v, σ' !! l = Some v → σ.2 !! l = Some v⌝.\n  Proof.\n    intros *. iIntros \"? Hmap\" (l v Hσ').\n    rewrite (big_sepM_delete _ σ' l) //. iDestruct \"Hmap\" as \"[? ?]\".\n    iApply (spec_heap_valid with \"[$]\").\n  Qed.\n  Lemma regspec_heap_valid_inSepM' e σ σ' q :\n      spec_res e σ -∗\n      ([∗ map] k↦y ∈ σ', regspec_mapsto k q y) -∗\n      ⌜forall l v, σ' !! l = Some v → σ.1 !! l = Some v⌝.\n  Proof.\n    intros *. iIntros \"? Hmap\" (l v Hσ').\n    rewrite (big_sepM_delete _ σ' l) //. iDestruct \"Hmap\" as \"[? ?]\".\n    iApply (spec_regs_valid with \"[$]\").\n  Qed.\n\n  Lemma memspec_heap_valid_inclSepM e σ σ' q :\n      spec_res e σ -∗\n      ([∗ map] k↦y ∈ σ', memspec_mapsto k q y) -∗\n      ⌜σ' ⊆ σ.2⌝.\n  Proof.\n    intros *. iIntros \"Hσ Hmap\".\n    iDestruct (memspec_heap_valid_inSepM' with \"Hσ Hmap\") as \"#H\".\n    iDestruct \"H\" as %Hincl. iPureIntro. intro l.\n    unfold option_relation.\n    destruct (σ' !! l) eqn:HH'; destruct (σ.2 !! l) eqn:HH; naive_solver.\n  Qed.\n  Lemma regspec_heap_valid_inclSepM e σ σ' q :\n      spec_res e σ -∗\n      ([∗ map] k↦y ∈ σ', regspec_mapsto k q y) -∗\n      ⌜σ' ⊆ σ.1⌝.\n  Proof.\n    intros *. iIntros \"Hσ Hmap\".\n    iDestruct (regspec_heap_valid_inSepM' with \"Hσ Hmap\") as \"#H\".\n    iDestruct \"H\" as %Hincl. iPureIntro. intro l.\n    unfold option_relation.\n    destruct (σ' !! l) eqn:HH'; destruct (σ.1 !! l) eqn:HH; naive_solver.\n  Qed.\n\n  Lemma memspec_heap_valid_allSepM e σ σ' q :\n      (forall l, is_Some (σ' !! l)) →\n      spec_res e σ -∗\n      ([∗ map] k↦y ∈ σ', memspec_mapsto k q y) -∗\n      ⌜ σ.2 = σ' ⌝.\n  Proof.\n    intros * Hσ'. iIntros \"A B\".\n    iAssert (⌜ forall l, σ.2 !! l = σ' !! l ⌝)%I with \"[A B]\" as %HH.\n    { iIntros (l).\n      specialize (Hσ' l). unfold is_Some in Hσ'. destruct Hσ' as [v Hσ'].\n      rewrite Hσ'.\n      eapply (memspec_heap_valid_inSepM e σ σ') in Hσ'.\n      iApply (Hσ' with \"[$]\"). eauto. }\n    iPureIntro. eapply map_leibniz. intro.\n    eapply leibniz_equiv_iff. auto.\n    Unshelve.\n  Qed.\n  Lemma regspec_heap_valid_allSepM e σ σ' q :\n      (forall l, is_Some (σ' !! l)) →\n      spec_res e σ -∗\n      ([∗ map] k↦y ∈ σ', regspec_mapsto k q y) -∗\n      ⌜ σ.1 = σ' ⌝.\n  Proof.\n    intros * Hσ'. iIntros \"A B\".\n    iAssert (⌜ forall l, σ.1 !! l = σ' !! l ⌝)%I with \"[A B]\" as %HH.\n    { iIntros (l).\n      specialize (Hσ' l). unfold is_Some in Hσ'. destruct Hσ' as [v Hσ'].\n      rewrite Hσ'.\n      eapply (regspec_heap_valid_inSepM e σ σ') in Hσ'.\n      iApply (Hσ' with \"[$]\"). eauto. }\n    iPureIntro. eapply map_leibniz. intro.\n    eapply leibniz_equiv_iff. auto.\n    Unshelve.\n  Qed.\n\n  Lemma memspec_v_implies_m_v:\n    ∀ mem0 σ e' (b e a : Addr) (v : Word) q,\n      mem0 !! a = Some v\n      → ([∗ map] a0↦w ∈ mem0, memspec_mapsto a0 q w)\n          -∗ spec_res e' σ -∗ ⌜σ.2 !! a = Some v⌝.\n  Proof.\n    iIntros (mem0 σ e' b e a v q Hmem) \"Hmem Hm\".\n    rewrite (big_sepM_delete _ mem0 a) //.\n    iDestruct \"Hmem\" as \"[H_a Hmem]\".\n    iDestruct (spec_heap_valid with \"[$Hm $H_a]\") as %?; auto.\n  Qed.\n\n  Lemma memspec_heap_update_inSepM e σ σ' l v :\n      is_Some (σ' !! l) →\n      spec_res e σ\n      -∗ ([∗ map] k↦y ∈ σ', memspec_mapsto k 1 y)\n      ==∗ spec_res e (σ.1,<[l:=v]>σ.2)\n          ∗ [∗ map] k↦y ∈ (<[l:=v]> σ'), memspec_mapsto k 1 y.\n  Proof.\n    intros * Hσ'. destruct Hσ'.\n    rewrite (big_sepM_delete _ σ' l) //. iIntros \"Hh [Hl Hmap]\".\n    iMod (memspec_mapsto_update with \"Hh Hl\") as \"[Hh Hl]\". iModIntro.\n    iSplitL \"Hh\"; eauto.\n    rewrite (big_sepM_delete _ (<[l:=v]> σ') l).\n    { rewrite delete_insert_delete. iFrame. }\n    rewrite lookup_insert //.\n  Qed.\n  Lemma regspec_heap_update_inSepM e σ σ' l v :\n      is_Some (σ' !! l) →\n      spec_res e σ\n      -∗ ([∗ map] k↦y ∈ σ', regspec_mapsto k 1 y)\n      ==∗ spec_res e (<[l:=v]> σ.1,σ.2)\n          ∗ [∗ map] k↦y ∈ (<[l:=v]> σ'), regspec_mapsto k 1 y.\n  Proof.\n    intros * Hσ'. destruct Hσ'.\n    rewrite (big_sepM_delete _ σ' l) //. iIntros \"Hh [Hl Hmap]\".\n    iMod (regspec_mapsto_update with \"Hh Hl\") as \"[Hh Hl]\". iModIntro.\n    iSplitL \"Hh\"; eauto.\n    rewrite (big_sepM_delete _ (<[l:=v]> σ') l).\n    { rewrite delete_insert_delete. iFrame. }\n    rewrite lookup_insert //.\n  Qed.\n\n  Lemma spec_memMap_resource_2ne_apply (a1 a2 : Addr) (w1 w2 : Word)  :\n    a1 ↣ₐ w1 -∗ a2 ↣ₐ w2 -∗ ([∗ map] a↦w ∈  <[a1:=w1]> (<[a2:=w2]> ∅), a ↣ₐ w) ∗ ⌜a1 ≠ a2⌝.\n  Proof.\n    iIntros \"Hi Hr2a\".\n    destruct (decide (a1 = a2)).\n    { subst. iDestruct (memspec_mapsto_valid_2 with \"Hi Hr2a\") as %Hne; auto. done. }\n    iSplitL; last by auto.\n    iApply memMap_resource_2ne; auto. iSplitL \"Hi\"; auto.\n  Qed.\n\nEnd cap_lang_spec_resources.\n\n\nSection cap_lang_spec_rules.\n  Context `{cfgSG Σ, MachineParameters, invGS Σ}.\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 spec_step_bind K e σ κ e' σ' :\n    head_step e σ κ e' σ' [] ->\n    erased_step ([fill K e],σ) ([fill K e'],σ').\n  Proof.\n    intros.\n    assert ([fill K e'] = <[0:=fill K e']> [fill K e]) as ->;[auto|].\n    rewrite -(right_id_L [] (++) (<[_:=_]>_)).\n    rewrite -(take_drop_middle [fill K e] 0 (fill K e)) //.\n    eexists. eapply step_atomic; eauto.\n    apply Ectx_step'. eauto.\n  Qed.\n\n  Lemma spec_step_pure E K e e' (P : Prop) n :\n    P -> PureExec P n e e' ->\n    nclose specN ⊆ E →\n    spec_ctx ∗ ⤇ fill K e ={E}=∗ ⤇ fill K e'.\n  Proof.\n    iIntros (HP Hpure Hsub) \"[#Hinv He]\".\n    iDestruct \"Hinv\" as (ρ) \"Hinv\".\n    rewrite /spec_inv /exprspec_mapsto.\n    iInv specN as \">H\" \"Hclose\".\n    iDestruct \"H\" as (c σ) \"[Hcfg Hstep]\".\n    iDestruct \"Hstep\" as %Hstep.\n    iDestruct (own_valid_2 with \"Hcfg He\") as %[[Hincle _]%prod_included Hvalid]%auth_both_valid_discrete;simpl in *.\n    assert ((ectxi_language.fill K e : exprO cap_lang) ≡ c) as Heq;[by apply Excl_included|simplify_eq].\n    iMod (own_update_2 with \"Hcfg He\") as \"[Hcfg He]\".\n    { by eapply auth_update,prod_local_update_1,(option_local_update (A:=exprR)),\n      (exclusive_local_update (A:=exprR) _ (Excl (fill K e'))). }\n    iFrame. iApply \"Hclose\".\n    iNext. iExists (fill K e'),σ. iFrame. iPureIntro.\n    apply rtc_nsteps_1 in Hstep; destruct Hstep as [m Hrtc].\n    specialize (Hpure HP). apply (rtc_nsteps_2 (m + n)).\n    eapply nsteps_trans; eauto. clear -Hpure.\n    revert e e' Hpure. induction n => e e' Hpure.\n    - inversion Hpure. subst. apply nsteps_O.\n    - inversion Hpure;subst. apply IHn in H2.\n      eapply relations.nsteps_l;eauto.\n      inversion H1 as [Hexs Hexd].\n      specialize (Hexs σ). destruct Hexs as [e'' [σ' [efs Hexs]]].\n      specialize (Hexd σ [] e'' σ' efs Hexs); destruct Hexd as [? [? [? ?]]]; subst.\n      simpl in Hexs. apply fill_prim_step with (K:=K) in Hexs.\n      econstructor;auto. eapply step_atomic with (t1:=[]) (t2:=[]);eauto.\n  Qed.\n\n  Lemma do_step_pure E K e e' `{!PureExec True 1 e e'}:\n    nclose specN ⊆ E →\n    spec_ctx ∗ ⤇ fill K e ={E}=∗ ⤇ fill K e'.\n  Proof. by eapply spec_step_pure; last eauto. Qed.\n\nEnd cap_lang_spec_rules.\n\nLtac prim_step_from_exec :=\n    match goal with\n    | H : exec _ _ = ?res |- _ =>\n      exists [];eapply step_atomic with (t1:=[]) (t2:=[]);eauto;\n      econstructor;eauto;constructor;\n      eapply step_exec_instr with (c:=res); try exact; simplify_map_eq;eauto\n    end.\n\nLtac iFailStep fail_type :=\n    iMod (exprspec_mapsto_update _ _ (fill _ (Instr Failed)) with \"Hown Hj\") as \"[Hown Hj]\";\n    iMod (\"Hclose\" with \"[Hown]\") as \"_\";\n    [iNext;iExists _,_;iFrame;iPureIntro;eapply rtc_r;eauto;prim_step_from_exec|];\n    iExists (FailedV),_; iFrame;iModIntro;iFailCore fail_type.\n\n(* FIXME: simplify_map_eq ought to do this but fails *)\n  Ltac simplify_map_eq_alt :=\n    repeat (match goal with\n            | H : context [<[_:=_]> _ !! _] |- _ =>\n              revert H; rewrite lookup_insert_ne;[|done]; intros H\n            end);\n    repeat (match goal with\n            | H : context [<[_:=_]> _ !! _] |- _ =>\n              revert H; rewrite lookup_insert; intros H\n            end); simplify_eq.\n\nSection cap_lang_spec_rules.\n  Context `{cfgSG Σ, MachineParameters, invGS Σ}.\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  (* ----------------------------- Fail and Halt --------------------------------- *)\n\n  Lemma step_halt E K pc_p pc_b pc_e pc_a w :\n    decodeInstrW w = Halt →\n    isCorrectPC (WCap pc_p pc_b pc_e pc_a) →\n    nclose specN ⊆ E →\n\n    spec_ctx ∗ ⤇ fill K (Instr Executable)\n             ∗ PC ↣ᵣ WCap pc_p pc_b pc_e pc_a\n             ∗ pc_a ↣ₐ w\n    ={E}=∗ ⤇ fill K (Instr Halted)\n         ∗ PC ↣ᵣ WCap pc_p pc_b pc_e pc_a ∗ pc_a ↣ₐ w.\n  Proof.\n    intros Hinstr Hvpc Hnclose.\n    iIntros \"(Hinv & Hj & Hpc & Hpca)\".\n    iDestruct \"Hinv\" as (ρ) \"Hinv\". rewrite /spec_inv.\n    iInv specN as \">Hinv'\" \"Hclose\". iDestruct \"Hinv'\" as (e [σr σm]) \"[Hown %] /=\".\n    iDestruct (@spec_regs_valid with \"[$Hown $Hpc]\") as %?.\n    iDestruct (@spec_heap_valid with \"[$Hown $Hpca]\") 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    cbn in Hstep. simplify_eq.\n    iMod (exprspec_mapsto_update _ _ (fill K (Instr Halted)) with \"Hown Hj\") as \"[Hown Hj]\".\n    iMod (\"Hclose\" with \"[Hown]\") as \"_\".\n    { iNext. iExists _,_;iFrame. iPureIntro. eapply rtc_r;eauto. simpl. prim_step_from_exec. }\n    by iFrame.\n  Qed.\n\n  Lemma step_fail E K pc_p pc_b pc_e pc_a w :\n    decodeInstrW w = Fail →\n    isCorrectPC (WCap pc_p pc_b pc_e pc_a) →\n    nclose specN ⊆ E →\n\n    spec_ctx ∗ ⤇ fill K (Instr Executable)\n             ∗ PC ↣ᵣ WCap pc_p pc_b pc_e pc_a\n             ∗ pc_a ↣ₐ w\n    ={E}=∗ ⤇ fill K (Instr Failed)\n         ∗ PC ↣ᵣ WCap pc_p pc_b pc_e pc_a ∗ pc_a ↣ₐ w.\n  Proof.\n    intros Hinstr Hvpc Hnclose.\n    iIntros \"(Hinv & Hj & Hpc & Hpca)\".\n    iDestruct \"Hinv\" as (ρ) \"Hinv\". rewrite /spec_inv.\n    iInv specN as \">Hinv'\" \"Hclose\". iDestruct \"Hinv'\" as (e [σr σm]) \"[Hown %] /=\".\n    iDestruct (@spec_regs_valid with \"[$Hown $Hpc]\") as %?.\n    iDestruct (@spec_heap_valid with \"[$Hown $Hpca]\") 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    cbn in Hstep. simplify_eq.\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. iPureIntro. eapply rtc_r;eauto. simpl. prim_step_from_exec. }\n    by iFrame.\n  Qed.\n\nEnd cap_lang_spec_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_binary/rules_binary_base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.26176484491412694}}
{"text": "(** ** Non unital lBsystems\n\nBy Vladimir Voevodsky, started on Jan. 16, 2015 *)\n\nUnset Automatic Introduction.\n\nRequire Export lBsystems.TS_ST.\nRequire Export lBsystems.STid .\nRequire Export lBsystems.lB0. \n\n\n\n\n(** Conditions TT and TTt *)\n\nDefinition TT_type { BB : lB0system_non_unital } :=\n  T_Tt.TT_type ( @T_ax0 BB ) ( @T_ax1a BB ) ( @T_ax1b BB ) .\n\nDefinition TTt_type { BB : lB0system_non_unital } :=\n  T_Tt.TTt_type ( @T_ax0 BB ) ( @T_ax1a BB ) ( @T_ax1b BB ) ( @Tt_ax1 BB ) .\n\nDefinition TT_TTt_layer ( BB : lB0system_non_unital ) := dirprod ( @TT_type BB ) ( @TTt_type BB ) . \n                   \n\n\n(** Conditions SSt and StSt *)\n\nDefinition SSt_type { BB : lB0system_non_unital } :=\n  S_St.SSt_type ( @S_ax0 BB ) ( @S_ax1a BB ) ( @S_ax1b BB ) ( @St_ax1 BB ) .\n\nDefinition StSt_type { BB : lB0system_non_unital } :=\n  S_St.StSt_type ( @S_ax0 BB ) ( @S_ax1a BB ) ( @S_ax1b BB ) ( @St_ax1 BB ) .\n\nDefinition SSt_StSt_layer ( BB : lB0system_non_unital ) := dirprod ( @SSt_type BB ) ( @StSt_type BB ) . \n\n\n\n(** Conditions TS and TtS *)\n\nDefinition TS_type { BB : lB0system_non_unital } :=\n  TS_ST.TS_type ( @T_ax1b BB ) ( @S_ax0 BB ) ( @S_ax1a BB ) ( @S_ax1b BB ) .\n\nDefinition TtS_type { BB : lB0system_non_unital } :=\n  TS_ST.TtS_type ( @T_ax1b BB ) ( @Tt_ax1 BB )\n                           ( @S_ax0 BB ) ( @S_ax1a BB ) ( @S_ax1b BB ) ( @St_ax1 BB ) .\n\nDefinition TS_TtS_layer ( BB : lB0system_non_unital ) := dirprod ( @TS_type BB ) ( @TtS_type BB ) .\n\n\n\n(** Conditions STt and StTt *)\n\nDefinition STt_type { BB : lB0system_non_unital } :=\n  TS_ST.STt_type ( @T_ax0 BB ) ( @T_ax1a BB ) ( @Tt_ax1 BB ) ( @S_ax1b BB ) . \n\nDefinition StTt_type { BB : lB0system_non_unital } :=\n  TS_ST.StTt_type ( @T_ax0 BB ) ( @T_ax1a BB ) ( @Tt_ax1 BB )  ( @S_ax1b BB ) ( @St_ax1 BB ) .\n\nDefinition ST_StTt_layer ( BB : lB0system_non_unital ) := dirprod ( @STt_type BB ) ( @StTt_type BB ) .\n\n\n\n(** Conditions STid and StTtid *) \n\nDefinition STid_type { BB : lB0system_non_unital } :=\n  STid.STid_type ( @T_ax1b BB ) ( @S_op BB ) . \n\nDefinition StTtid_type { BB : lB0system_non_unital } :=\n  STid.StTtid_type ( @T_ax1b BB ) ( @Tt_ax1 BB ) ( @St_op BB ) .\n\nDefinition STid_layer ( BB : lB0system_non_unital ) := dirprod ( @STid_type BB ) ( @StTtid_type BB ) .\n\n\n\n\n\n(** Complete non-unital lBsystem *)\n\n\nDefinition lB_nu :=\n  total2 ( fun BB : lB0system_non_unital =>\n             dirprod\n               ( dirprod\n                   ( dirprod ( TT_TTt_layer BB ) ( SSt_StSt_layer BB ) )\n                   ( dirprod ( TS_TtS_layer BB ) ( ST_StTt_layer BB ) ) )\n               ( STid_layer BB ) ) . \n                                                             \n                                                             \nDefinition lB_nu_pr1 : lB_nu -> lB0system_non_unital := pr1 .\nCoercion lB_nu_pr1 : lB_nu >-> lB0system_non_unital .\n\n\nDefinition TT { BB : lB_nu } : @TT_type BB := pr1 ( pr1 ( pr1 ( pr1 ( pr2 BB ) ) ) ) .\n\nDefinition TTt { BB : lB_nu } : @TTt_type BB := pr2 ( pr1 ( pr1 ( pr1 ( pr2 BB ) ) ) ) .\n\nDefinition SSt { BB : lB_nu } : @SSt_type BB := pr1 ( pr2 ( pr1 ( pr1 ( pr2 BB ) ) ) ) .\n\nDefinition StSt { BB : lB_nu } : @StSt_type BB := pr2 ( pr2 ( pr1 ( pr1 ( pr2 BB ) ) ) ) . \n\nDefinition TS { BB : lB_nu } : @TS_type BB := pr1 ( pr1 ( pr2 ( pr1 ( pr2 BB ) ) ) ) .  \n\nDefinition TtS { BB : lB_nu } : @TtS_type BB := pr2 ( pr1 ( pr2 ( pr1 ( pr2 BB ) ) ) ) .   \n\nDefinition STt { BB : lB_nu } : @STt_type BB := pr1 ( pr2 ( pr2 ( pr1 ( pr2 BB ) ) ) ) .    \n\nDefinition StTt { BB : lB_nu } : @StTt_type BB := pr2 ( pr2 ( pr2 ( pr1 ( pr2 BB ) ) ) ) . \n\nDefinition STid_ax { BB : lB_nu } : @STid_type BB := pr1 ( pr2 ( pr2 BB ) ) .  \n\nDefinition StTtid { BB : lB_nu } : @StTtid_type BB := pr2 ( pr2 ( pr2 BB ) ) .  \n\n\n\n\n\n(* End of the file lB_non_unital.v *) ", "meta": {"author": "UniMath", "repo": "lBsystems", "sha": "ef6e2d846cdac7ca9ab9966cb219aee1c92d8d83", "save_path": "github-repos/coq/UniMath-lBsystems", "path": "github-repos/coq/UniMath-lBsystems/lBsystems-ef6e2d846cdac7ca9ab9966cb219aee1c92d8d83/lB_non_unital.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2617648385587482}}
{"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.msl.Coqlib2.\n\n(********************* Lemmas and definitions related to mem_step ********)\n\nLemma mem_step_refl m: mem_step m m.\n  apply (mem_step_freelist _ _ nil); trivial.\nQed.\n\nLemma mem_step_free:\n      forall m b lo hi m', Mem.free m b lo hi = Some m' -> mem_step m m'.\nProof.\n intros. eapply (mem_step_freelist _ _ ((b,lo,hi)::nil)).\n simpl. rewrite H; reflexivity.\nQed.\n\nLemma mem_step_store:\n      forall m ch b a v m', Mem.store ch m b a v = Some m' -> mem_step m m'.\nProof.\n intros. eapply mem_step_storebytes. eapply Mem.store_storebytes; eassumption.\nQed.\n\nRecord memstep_preserve (P:mem -> mem -> Prop) :=\n  {\n    preserve_trans: forall m1 m2 m3, P m1 m2 -> P m2 m3 -> P m1 m3;\n    preserve_mem: forall m m', mem_step m m' -> P m m'\n  }.\n\nLemma preserve_refl {P} (HP: memstep_preserve P): forall m, P m m.\nProof. intros. eapply (preserve_mem _ HP). apply mem_step_refl. Qed.\n\nLemma preserve_free {P} (HP: memstep_preserve P):\n      forall m b lo hi m', Mem.free m b lo hi = Some m' -> P m m'.\nProof.\n intros. eapply (preserve_mem _ HP). eapply mem_step_free; eauto. Qed.\n\nTheorem preserve_conj {P Q} (HP:memstep_preserve P) (HQ: memstep_preserve Q):\n        memstep_preserve (fun m m' => P m m' /\\ Q m m').\nProof.\nintros. constructor.\n+ intros. destruct H; destruct H0. split. eapply HP; eauto. eapply HQ; eauto.\n+ intros; split. apply HP; trivial. apply HQ; trivial.\nQed.\n\n(*opposite direction appears not to hold*)\nTheorem preserve_impl {A} (P:A -> mem -> mem -> Prop) (Q:A->Prop):\n        (forall a, Q a -> memstep_preserve (P a)) -> memstep_preserve (fun m m' => forall a, Q a -> P a m m').\nProof.\nintros.\nconstructor; intros.\n+ eapply H; eauto.\n+ apply H; eauto.\nQed.\n\nLemma preserve_exensional {P Q} (HP:memstep_preserve P) (PQ:P=Q): memstep_preserve Q.\nsubst; trivial. Qed.\n\n(*opposite direction appears not to hold*)\nTheorem preserve_univ {A} (P:A -> mem -> mem -> Prop):\n        (forall a, memstep_preserve (P a)) -> memstep_preserve (fun m m' => forall a, P a m m').\nProof. intros.\neapply preserve_exensional.\neapply (@preserve_impl A (fun a m m'=> P a m m') (fun a=>True)).\nintros. apply H. extensionality m. extensionality m'. apply prop_ext. intuition.\nQed.\n\nTheorem mem_forward_preserve: memstep_preserve mem_forward.\nProof.\nconstructor.\n+ apply mem_forward_trans.\n+ intros. induction H.\n  eapply storebytes_forward; eassumption.\n  eapply alloc_forward; eassumption.\n  eapply freelist_forward; eassumption.\n  eapply mem_forward_trans; eassumption.\nQed.\n\nTheorem readonly_preserve b: memstep_preserve (fun m m' => mem_forward m m' /\\ (Mem.valid_block m b -> readonly m b m')).\nProof.\nconstructor.\n+ intros. destruct H; destruct H0.\n  split; intros. eapply mem_forward_trans; eassumption.\n  eapply readonly_trans; eauto. apply H2. apply H. eassumption.\n+ intros; induction H.\n  - split; intros. eapply storebytes_forward; eassumption.\n    eapply storebytes_readonly; eassumption.\n  - intros.\n    split; intros. eapply alloc_forward; eassumption.\n    eapply alloc_readonly; eassumption.\n  - intros.\n    split; intros. eapply freelist_forward; eassumption.\n    eapply freelist_readonly; eassumption.\n  - destruct IHmem_step1; destruct IHmem_step2.\n    split. eapply mem_forward_trans; eassumption.\n    intros. eapply readonly_trans. eauto. apply H4. apply H1; eassumption.\nQed.\n\nTheorem readonly_preserve':\n   memstep_preserve (fun m m' => mem_forward m m' /\\ (forall b, Mem.valid_block m b -> readonly m b m')).\nProof.\neapply preserve_exensional.\neapply preserve_univ; intros. apply (readonly_preserve a).\n  extensionality m. extensionality m'. apply prop_ext.\n  split; intros. split. eapply H. apply xH. intros. eapply (H b). trivial.\n  destruct H. split; eauto.\nQed.\n\nLemma storebytes_unch_loc_unwritable b ofs: forall l m m' (L: Mem.storebytes m b ofs l = Some m'),\n      Mem.unchanged_on (loc_not_writable m) m m'.\nProof.\nintros.\nsplit; intros.\n+ rewrite (Mem.nextblock_storebytes _ _ _ _ _ L); apply Pos.le_refl.\n+ split; intros.\n  eapply Mem.perm_storebytes_1; eassumption.\n  eapply Mem.perm_storebytes_2; eassumption.\n+ rewrite (Mem.storebytes_mem_contents _ _ _ _ _ L).\n  apply Mem.storebytes_range_perm in L.\n  destruct (eq_block b0 b); subst.\n  - destruct (zle ofs ofs0).\n      destruct (zlt ofs0 (ofs + Z.of_nat (length l))).\n        elim H. eapply Mem.perm_max. apply L. omega.\n      rewrite PMap.gss. apply Mem.setN_other. intros. omega.\n    rewrite PMap.gss. apply Mem.setN_other. intros. omega.\n  - rewrite PMap.gso; trivial.\nQed.\n\nLemma unch_on_loc_not_writable_trans m1 m2 m3\n        (Q : Mem.unchanged_on (loc_not_writable m1) m1 m2)\n        (W : Mem.unchanged_on (loc_not_writable m2) m2 m3)\n        (F:mem_forward m1 m2):\n     Mem.unchanged_on (loc_not_writable m1) m1 m3.\nProof.\n  destruct Q as [Q0 Q1 Q2]. destruct W as [W0 W1 W2].\n  split; intros.\n  - eapply Ple_trans; eassumption.\n  - cut (Mem.perm m2 b ofs k p <-> Mem.perm m3 b ofs k p).\n      specialize (Q1 _ _ k p H H0). intuition.\n    apply W1; clear W1. intros N. apply H. apply Q1; trivial. apply F; trivial.\n  -  rewrite W2; clear W2.\n       apply Q2; trivial.\n     intros N; apply H. apply F; trivial. eapply Mem.perm_valid_block; eassumption.\n     apply Q1; trivial. eapply Mem.perm_valid_block; eassumption.\nQed.\n\nTheorem loc_not_writable_preserve:\n   memstep_preserve (fun m m' => mem_forward m m' /\\ Mem.unchanged_on (loc_not_writable m) m m').\nProof.\nconstructor.\n+ intros. destruct H as [F1 Q]; destruct H0 as [F2 W].\n  split; intros. eapply mem_forward_trans; eassumption. clear F2.\n  eapply unch_on_loc_not_writable_trans; eassumption.\n+ intros; induction H.\n  - split; intros. eapply storebytes_forward; eassumption.\n    eapply storebytes_unch_loc_unwritable; eassumption.\n  - split; intros. eapply alloc_forward; eassumption.\n    eapply Mem.alloc_unchanged_on; eassumption.\n  - split; intros. eapply freelist_forward; eassumption.\n    generalize dependent m.\n    induction l; simpl; intros. inv H. apply Mem.unchanged_on_refl.\n    destruct a. destruct p.\n    remember (Mem.free m b z0 z) as w. destruct w; inv H. symmetry in Heqw.\n    eapply unch_on_loc_not_writable_trans.\n      eapply Mem.free_unchanged_on. eassumption.\n        intros i I N. elim N; clear N.\n        eapply Mem.perm_max. eapply Mem.perm_implies. eapply Mem.free_range_perm; eassumption. constructor.\n      apply IHl; eassumption.\n      eapply free_forward; eassumption.\n  - destruct IHmem_step1; destruct IHmem_step2.\n    split. eapply mem_forward_trans; eassumption.\n    intros. clear H H0 H3. eapply unch_on_loc_not_writable_trans; eassumption.\nQed.\n\nLemma freelist_perm: forall l m m' (L : Mem.free_list m l = Some m') b (B: Mem.valid_block m b)\n      ofs (P': Mem.perm m' b ofs Max Nonempty) k p,\n      Mem.perm m b ofs k p <-> Mem.perm m' b ofs k p.\nProof. induction l; simpl; intros.\n+ inv L; split; trivial.\n+ destruct a. destruct p0.\n  remember (Mem.free m b0 z0 z) as w. symmetry in Heqw.\n  destruct w; inv L.\n  specialize (IHl _ _  H0 _ (Mem.valid_block_free_1 _ _ _ _ _ Heqw _ B) _ P' k p).\n  assert (P: Mem.perm m b ofs k p <-> Mem.perm m0 b ofs k p).\n  { clear IHl. destruct (Mem.perm_free_list _ _ _ _ _ _ _ H0 P') as [P ?]; clear H0 P'.\n    destruct (eq_block b0 b); subst.\n    - destruct (zlt ofs z0).\n      * split; intros. apply (Mem.perm_free_1 _ _ _ _ _ Heqw) in H0; eauto.\n        eapply Mem.perm_free_3; eassumption.\n      * destruct (zle z ofs).\n        split; intros. apply (Mem.perm_free_1 _ _ _ _ _ Heqw) in H0; eauto.\n                       eapply Mem.perm_free_3; eassumption.\n        split; intros.\n          eelim (Mem.perm_free_2 _ _ _ _ _ Heqw ofs Max Nonempty); clear Heqw; trivial. omega.\n        eelim (Mem.perm_free_2 _ _ _ _ _ Heqw ofs Max Nonempty); clear Heqw. omega.\n          eapply Mem.perm_implies. eapply Mem.perm_max. eassumption. constructor.\n    - split; intros.\n      * eapply (Mem.perm_free_1 _ _ _ _ _ Heqw); trivial. intuition.\n      * eapply (Mem.perm_free_3 _ _ _ _ _ Heqw); trivial.\n  }\n  intuition.\nQed.\n\nTheorem perm_preserve:\n   memstep_preserve (fun m m' =>  mem_forward m m' /\\ forall b, Mem.valid_block m b -> forall ofs, Mem.perm m' b ofs Max Nonempty ->\n                                  forall k p, Mem.perm m b ofs k p <-> Mem.perm m' b ofs k p).\nProof.\nconstructor.\n+ intros; split. eapply mem_forward_trans. apply H. apply H0.\n  destruct H; destruct H0. intros.\n  assert (M: Mem.perm m1 b ofs k p <-> Mem.perm m2 b ofs k p).\n  - clear H2. apply H1; trivial. apply H0; trivial. apply H; trivial.\n  - clear H1.\n    assert (VB2: Mem.valid_block m2 b). apply H; trivial.\n    destruct (H2 _ VB2 _ H4 k p); destruct M. split; intros; eauto.\n+ intros; induction H.\n  - split; intros. eapply storebytes_forward; eassumption.\n    split; intros. eapply Mem.perm_storebytes_1; eassumption.\n    eapply Mem.perm_storebytes_2; eassumption.\n  - split; intros. eapply alloc_forward; eassumption.\n    split; intros. eapply Mem.perm_alloc_1; eassumption.\n    eapply Mem.perm_alloc_4; try eassumption.\n    intros N; subst b'. elim (Mem.fresh_block_alloc _ _ _ _ _ H H0).\n  - intros; split. eapply freelist_forward; eassumption.\n    apply (freelist_perm _ _ _ H).\n  - clear H H0. destruct IHmem_step1; destruct IHmem_step2.\n    split. eapply mem_forward_trans; eassumption.\n    intros.\n    assert (M: Mem.perm m b ofs k p <-> Mem.perm m'' b ofs k p).\n    * clear H2. apply H0; trivial. apply H1; trivial. apply H; trivial.\n    * clear H0.\n      assert (VB2: Mem.valid_block m'' b). apply H; trivial.\n      destruct (H2 _ VB2 _ H4 k p); destruct M. split; intros; eauto.\nQed.\n\nLemma mem_step_forward m m': mem_step m m' -> mem_forward m m'.\nintros. apply preserve_mem; trivial.\neapply mem_forward_preserve; trivial.\nQed.\n\nLemma freelist_perm_inv: forall l m m' (L : Mem.free_list m l = Some m') b (B: Mem.valid_block m b)\n      ofs k p (P: Mem.perm m b ofs k p),\n      Mem.perm m b ofs Max Freeable \\/ Mem.perm m' b ofs k p.\nProof. induction l; simpl; intros.\n+ inv L. right; trivial.\n+ destruct a. destruct p0.\n  remember (Mem.free m b0 z0 z) as w. symmetry in Heqw.\n  destruct w; inv L.\n  exploit Mem.perm_free_inv; eauto. intros [[HHx HH] | HH]; try subst b0.\n  - left. eapply Mem.perm_max.  eapply Mem.free_range_perm; eassumption.\n  - destruct (IHl _ _  H0 _ (Mem.valid_block_free_1 _ _ _ _ _ Heqw _ B) _ _ _ HH); clear IHl.\n    2: right; trivial.\n    left. eapply Mem.perm_free_3; eauto.\nQed.\n\nTheorem preserves_max_eq_or_free:\n   memstep_preserve (fun m m' =>  mem_forward m m' /\\\n                                  forall b (VB: Mem.valid_block m b) ofs,\n                                   (forall k p, Mem.perm m b ofs k p <-> Mem.perm m' b ofs k p) \\/\n                                   (Mem.perm m b ofs Max Freeable /\\\n                                    Mem.perm_order'' None ((Mem.mem_access m') !! b ofs Max))).\nProof.\nconstructor.\n+ intros; split. eapply mem_forward_trans. apply H. apply H0.\n  destruct H; destruct H0. intros.\n  assert (VB2: Mem.valid_block m2 b). { apply H; trivial. }\n  destruct (H1 _ VB ofs) as [K1 | [K1 L1]]; destruct (H2 _ VB2 ofs) as [K2 | [K2 L2]]; clear H1 H2.\n  - left; intros. specialize (K1 k p); specialize (K2 k p). intuition.\n  - right; split; trivial. apply K1; trivial.\n  - right; split; trivial. simpl in *. specialize (K2 Max).\n    unfold Mem.perm in *.\n    remember ((Mem.mem_access m3) !! b ofs Max) as w; destruct w; trivial.\n    destruct ((Mem.mem_access m2) !! b ofs Max); try contradiction.\n    destruct (K2 p); simpl in *. apply H2. apply perm_refl.\n  - right; split; trivial.\n+ intros; induction H.\n  - split; intros. eapply storebytes_forward; eassumption.\n    left; intros. split; intros.\n    * eapply Mem.perm_storebytes_1; eassumption.\n    * eapply Mem.perm_storebytes_2; eassumption.\n  - split; intros. eapply alloc_forward; eassumption.\n    left; intros. split; intros.\n    * eapply Mem.perm_alloc_1; eassumption.\n    * eapply Mem.perm_alloc_4; try eassumption.\n      intros N; subst. eapply Mem.fresh_block_alloc; eassumption.\n  - split; intros. eapply freelist_forward; eassumption.\n    destruct (Mem.perm_dec m' b ofs Max Nonempty).\n    * left; intros. eapply freelist_perm; eassumption.\n    * destruct (Mem.perm_dec m b ofs Max Freeable); trivial.\n       right; split; trivial. unfold Mem.perm in n; simpl in *.\n       destruct ((Mem.mem_access m') !! b ofs Max); trivial.\n       elim n; clear n. constructor.\n      left; intros.\n      split; intros. 2: eapply perm_freelist; eassumption.\n      exploit freelist_perm_inv; eauto. intros [X | X]; trivial; contradiction.\n  - clear H H0. destruct IHmem_step1; destruct IHmem_step2.\n    split. eapply mem_forward_trans; eassumption.\n    intros.\n    assert (VB2 : Mem.valid_block m'' b). { apply H; trivial. }\n    specialize (H0 _ VB ofs). specialize (H2 _ VB2 ofs).\n    destruct H0 as [K | [K1 K2]]; destruct H2 as [L | [L1 L2]].\n    * left; intros. split; intros. apply L. apply K; trivial.\n      apply K. apply L; trivial.\n    * right. split; trivial. apply K; trivial.\n    * right. split; trivial.\n      clear K1. unfold Mem.perm in *. simpl in *. specialize (L Max).\n      remember ((Mem.mem_access m') !! b ofs Max) as d; destruct d; trivial.\n      destruct ((Mem.mem_access m'') !! b ofs Max); try contradiction.\n      specialize (L p); simpl in *. apply L. apply perm_refl.\n    * right. split; trivial.\nQed.\n\nTheorem mem_step_max_eq_or_free m m' (STEP: mem_step m m') b (VB: Mem.valid_block m b) ofs:\n       (forall k p, Mem.perm m b ofs k p <-> Mem.perm m' b ofs k p) \\/\n       (Mem.perm m b ofs Max Freeable /\\ None = ((Mem.mem_access m') !! b ofs Max)).\nProof. intros.\nexploit preserve_mem. apply preserves_max_eq_or_free. eassumption.\nsimpl; intros [A B]. destruct (B _ VB ofs). left; trivial. right.\n  destruct H; split; trivial.\n  destruct ((Mem.mem_access m') !! b ofs Max); trivial; contradiction.\nQed.\n\nLemma memsem_preserves {C} (s: @MemSem C) P (HP:memstep_preserve P):\n      forall c m c' m', corestep s c m c' m'-> P m m'.\nProof. intros.\n  apply corestep_mem in H.\n  eapply preserve_mem; eassumption.\nQed.\n\nLemma corestep_fwd {C} (s:@MemSem C) c m c' m'\n   (CS:corestep s c m c' m' ): mem_forward m m'.\nProof.\neapply memsem_preserves; try eassumption. apply mem_forward_preserve.\nQed.\n\nLemma corestep_rdonly {C} (s:@MemSem C) c m c' m'\n   (CS:corestep s c m c' m') b (VB:Mem.valid_block m b): readonly m b m'.\nProof.\neapply (memsem_preserves s _ readonly_preserve'); eassumption.\nQed.\n\nLemma mem_step_nextblock:  memstep_preserve (fun m m' => Mem.nextblock m <= Mem.nextblock m')%positive.\nconstructor.\n+ intros. xomega.\n+ induction 1.\n - apply Mem.nextblock_storebytes in H;\n   rewrite H; xomega.\n - apply Mem.nextblock_alloc in H.\n   rewrite H. clear. xomega.\n - apply nextblock_freelist in H.\n   rewrite H; xomega.\n - xomega.\nQed.\n\nLemma mem_step_nextblock':\n  forall m m',\n     mem_step m m' ->\n   (Mem.nextblock m <= Mem.nextblock m')%positive.\nProof. apply mem_step_nextblock. Qed.\n\n(*E-step: Axiomatization of external steps - potentially useful when Memory interface is hardened\nInductive e_step m m' : Prop :=\n    mem_step_estep: mem_step m m' -> e_step m m'\n  | drop_perm_estep: forall b lo hi p,\n      Mem.drop_perm m b lo hi p = Some m' -> e_step m m'\n  | change_cur_estep:\n      (forall b ofs, (Mem.mem_access m) !! b ofs Max = (Mem.mem_access m') !! b ofs Max) ->\n      Mem.unchanged_on (loc_not_writable m) m m' ->\n      (Mem.mem_contents m = Mem.mem_contents m') ->\n      Mem.nextblock m = Mem.nextblock m' -> e_step m m'\n  | estep_trans: forall m'',\n       e_step m m'' -> e_step m'' m' -> e_step m m'.\n\nLemma e_step_refl m: e_step m m.\nProof. apply mem_step_estep. apply mem_step_refl. Qed.\n\nLemma estep_forward m m' (E:e_step m m'): mem_forward m m'.\nProof.\ninduction E.\napply mem_forward_preserve; eassumption.\n+ split; intros.\n    eapply Mem.drop_perm_valid_block_1; eassumption.\n    eapply Mem.perm_drop_4; eassumption.\n+ split; intros.\n  unfold Mem.valid_block in *. rewrite H2 in *; assumption.\n  unfold Mem.perm. rewrite H. apply H4.\n+ eapply mem_forward_trans; eassumption.\nQed.\n\nLemma estep_unch_on_loc_not_writable m m' (E:e_step m m'): Mem.unchanged_on (loc_not_writable m) m m'.\nProof.\ninduction E.\n+ apply loc_not_writable_preserve in H. apply H.\n+ unfold Mem.drop_perm in H.\n  destruct (Mem.range_perm_dec m b lo hi Cur Freeable); inv H; simpl in *.\n  split; simpl; trivial.\n  intros. red in H.\n  unfold Mem.perm; simpl. rewrite PMap.gsspec.\n  destruct (peq b0 b); subst; simpl. 2: intuition.\n  destruct (zle lo ofs); simpl. 2: intuition.\n  destruct (zlt ofs hi); simpl. 2: intuition.\n  elim H. eapply Mem.perm_max. eapply Mem.perm_implies. apply r. omega. constructor.\n+ trivial.\n+ eapply unch_on_loc_not_writable_trans; try eassumption. eapply estep_forward; eassumption.\nQed.\n*)\n(*\nTheorem loadbytes_drop m b lo hi p m' (D:Mem.drop_perm m b lo hi p = Some m'):\n  forall b' ofs,\n  b' <> b \\/ ofs < lo \\/ hi <= ofs \\/ perm_order p Readable ->\n  Mem.loadbytes m' b' ofs 1 = Mem.loadbytes m b' ofs 1.\nProof.\n  intros.\nTransparent Mem.loadbytes.\n  unfold Mem.loadbytes.\n  destruct (Mem.range_perm_dec m b' ofs (ofs + 1) Cur Readable).\n  rewrite pred_dec_true.\n  unfold Mem.drop_perm in D. destruct (Mem.range_perm_dec m b lo hi Cur Freeable); inv D. simpl. auto.\n  red; intros. specialize (Mem.perm_drop_1 _ _ _ _ _ _ D ofs0 Cur); intros.\n    destruct (eq_block b' b); subst.\n      destruct H. eapply Mem.perm_drop_3. eassumption. left; trivial. apply r. trivial.\n      destruct (zlt ofs lo). eapply Mem.perm_drop_3. eassumption. right. omega. apply r. trivial.\n      destruct H. omega.\n      destruct (zle hi ofs). eapply Mem.perm_drop_3. eassumption. right. omega. apply r. trivial.\n      destruct H. omega.\n      eapply Mem.perm_implies. apply H1. omega. trivial.\n   eapply Mem.perm_drop_3. eassumption. left; trivial. apply r. omega.\n\n  destruct (Mem.range_perm_dec m' b' ofs (ofs + 1) Cur Readable); trivial.\n  elim n; clear n. red; intros. eapply Mem.perm_drop_4. eassumption. apply r. trivial.\nQed.\n*)\n\nLemma mem_step_obeys_cur_write:\n  forall m b ofs m',\n    Mem.valid_block m b ->\n   ~ Mem.perm m b ofs Cur Writable ->\n   mem_step m m' ->\n ZMap.get ofs (PMap.get b (Mem.mem_contents m)) =\n ZMap.get ofs (PMap.get b (Mem.mem_contents m')).\nProof.\n intros.\n induction H1.\n* revert m ofs0 H H0 H1; induction bytes; intros.\n Transparent Mem.storebytes.\n unfold Mem.storebytes in H1.\n destruct (Mem.range_perm_dec m b0 ofs0\n         (ofs0 + Z.of_nat (length nil)) Cur Writable);\n  inv H1; simpl.\n destruct (peq b b0). subst b0.\n rewrite PMap.gss. auto.\n rewrite PMap.gso; auto.\n change (a::bytes) with ((a::nil)++bytes) in H1.\n apply Mem.storebytes_split in H1.\n destruct H1 as [m1 [? ?]].\n etransitivity.\n 2: eapply IHbytes; try apply H2.\n clear H2 IHbytes.\n unfold Mem.storebytes in H1.\nOpaque Mem.storebytes.\n destruct (Mem.range_perm_dec m b0 ofs0\n         (ofs0 + Z.of_nat (length (a :: nil))) Cur Writable);\n inv H1; simpl.\n destruct (peq b b0). subst b0.\n rewrite PMap.gss.\n destruct (zeq ofs0 ofs). subst.\n contradiction H0. apply r. simpl. omega.\n rewrite ZMap.gso; auto.\n rewrite PMap.gso; auto.\n clear - H H1.\n eapply Mem.storebytes_valid_block_1; eauto.\n contradict H0. clear - H1 H0.\n eapply Mem.perm_storebytes_2; eauto.\n*\n apply AllocContentsOther with (b':=b) in H1.\n rewrite H1. auto. intro; subst.\n apply Mem.alloc_result in H1; unfold Mem.valid_block in H.\n subst. apply Plt_strict in H; auto.\n*\n revert m H H0 H1; induction l; simpl; intros.\n inv H1; auto.\n destruct a. destruct p.\n destruct (Mem.free m b0 z0 z) eqn:?; inv H1.\n rewrite <- (IHl m0); auto.\n eapply free_contents; eauto.\n intros [? ?]. subst b0. apply H0.\n apply Mem.free_range_perm in Heqo.\n   specialize (Heqo ofs).\n   eapply Mem.perm_implies. apply Heqo. omega. constructor.\n clear - H Heqo.\n unfold Mem.valid_block in *.\n apply Mem.nextblock_free in Heqo. rewrite Heqo.\n auto.\n clear - H0 Heqo.\n contradict H0.\n eapply Mem.perm_free_3; eauto.\n*\n assert (Mem.valid_block m'' b). {\n   apply mem_step_nextblock in H1_.\n   unfold Mem.valid_block in *.\n   eapply Pos.lt_le_trans; eauto.\n }\n erewrite IHmem_step1 by auto. apply IHmem_step2; auto.\n contradict H0.\n clear - H H1_ H0.\n revert H H0; induction H1_; intros.\n eapply Mem.perm_storebytes_2; eauto.\n pose proof (Mem.perm_alloc_inv _ _ _ _ _ H _ _ _ _ H1).\n destruct (eq_block b b'); subst; trivial.\n - pose proof (Mem.alloc_result _ _ _ _ _ H).\n   subst. apply Plt_strict in H0. contradiction.\n - eapply Mem.perm_free_list in H; try apply H1.\n   destruct H; auto.\n - eapply IHH1_1; auto. eapply IHH1_2; eauto.\n   apply mem_step_nextblock in H1_1.\n   unfold Mem.valid_block in *.\n   eapply Pos.lt_le_trans; eauto.\nQed.\n\nLemma ple_load m ch a v\n            (LD: Mem.loadv ch m a = Some v)\n            m1 (PLE: perm_lesseq m m1):\n           Mem.loadv ch m1 a = Some v.\nProof.\nunfold Mem.loadv in *.\ndestruct a; auto.\nTransparent Mem.load.\nunfold Mem.load in *.\nOpaque Mem.load.\ndestruct PLE.\nif_tac in LD; [ | inv LD].\nrewrite if_true.\nrewrite <- LD; clear LD.\nf_equal. f_equal.\ndestruct H.\nrewrite size_chunk_conv in H.\nclear - H perm_le_cont.\nforget (size_chunk_nat ch) as n.\nforget (Ptrofs.unsigned i) as j.\nrevert j H; induction n; intros; simpl; f_equal.\napply perm_le_cont.\napply (H j).\nrewrite inj_S.\nomega.\napply IHn.\nrewrite inj_S in H.\nintros ofs ?; apply H. omega.\nclear - H perm_le_Cur.\ndestruct H; split; auto.\nintros ? ?. specialize (H ofs H1).\nhnf in H|-*.\nspecialize (perm_le_Cur b ofs).\ndestruct ((Mem.mem_access m) !! b ofs Cur); try contradiction.\ndestruct ((Mem.mem_access m1) !! b ofs Cur);\ninv perm_le_Cur; auto; try constructor; try inv H.\nQed.\n\nLemma ple_store:\n  forall ch m v1 v2 m' m1\n   (PLE: perm_lesseq m m1),\n   Mem.storev ch m v1 v2 = Some m' ->\n   exists m1', perm_lesseq m' m1' /\\ Mem.storev ch m1 v1 v2 = Some m1'.\nProof.\nintros.\nunfold Mem.storev in *.\ndestruct v1; try discriminate.\nTransparent Mem.store.\nunfold Mem.store in *.\nOpaque Mem.store.\ndestruct (Mem.valid_access_dec m ch b (Ptrofs.unsigned i)  Writable); inv H.\ndestruct (Mem.valid_access_dec m1 ch b (Ptrofs.unsigned i)\n      Writable).\n*\neexists; split; [ | reflexivity].\ndestruct PLE.\nconstructor; simpl; auto.\nintros. unfold Mem.perm in H. simpl in H.\nforget (Ptrofs.unsigned i) as z.\ndestruct (eq_block b0 b). subst.\nrewrite !PMap.gss.\nforget (encode_val ch v2) as vl.\nassert (z <= ofs < z + Z.of_nat (length vl) \\/ ~ (z <= ofs < z + Z.of_nat (length vl))) by omega.\ndestruct H0.\nclear - H0.\nforget ((Mem.mem_contents m1) !! b) as mA.\nforget ((Mem.mem_contents m) !! b) as mB.\nrevert z mA mB H0; induction vl; intros; simpl.\nsimpl in H0; omega.\nsimpl length in H0; rewrite inj_S in H0.\ndestruct (zeq z ofs).\nsubst ofs.\nrewrite !Mem.setN_outside by omega. rewrite !ZMap.gss; auto.\napply IHvl; omega.\nrewrite !Mem.setN_outside by omega.\napply perm_le_cont. auto.\nrewrite !PMap.gso by auto.\napply perm_le_cont. auto.\n*\ncontradiction n; clear n.\ndestruct PLE.\nunfold Mem.valid_access in *.\ndestruct v; split; auto.\nhnf in H|-*; intros.\nspecialize (H _ H1).\nclear - H perm_le_Cur.\nspecialize (perm_le_Cur b ofs).\nhnf in H|-*.\ndestruct ((Mem.mem_access m) !! b ofs Cur); try contradiction.\ninv H;\ndestruct ((Mem.mem_access m1) !! b ofs Cur);\ninv perm_le_Cur; auto; try constructor; try inv H.\nQed.\n\nLemma free_access_inv m b lo hi m' (FR: Mem.free m b lo hi = Some m') b' ofs k p\n  (P: (Mem.mem_access m') !! b' ofs k = Some p):  (Mem.mem_access m) !! b' ofs k = Some p.\nProof.\napply Mem.free_result in FR; subst. simpl in *.\nrewrite PMap.gsspec in P.\ndestruct (peq b' b); subst; trivial.\ndestruct (zle lo ofs && zlt ofs hi); inv P; trivial.\nQed.\n\nLemma free_access_inv_None m b lo hi m' (FR: Mem.free m b lo hi = Some m') b' ofs k\n  (P: (Mem.mem_access m') !! b' ofs k = None):\n  (b' = b /\\ Z.le lo ofs /\\ Z.lt ofs hi /\\  (Mem.mem_access m) !! b' ofs k = Some Freeable) \\/\n  ((b' <> b \\/ Z.lt ofs lo \\/ Z.le hi ofs) /\\ (Mem.mem_access m) !! b' ofs k = None).\nProof.\nspecialize (Mem.free_result _ _ _ _ _ FR). intros; subst. simpl in *.\nrewrite PMap.gsspec in P.\ndestruct (peq b' b); subst.\n+ remember (zle lo ofs && zlt ofs hi) as q.\n  destruct q; inv P.\n  - left. split; trivial. destruct (zle lo ofs); simpl in *; try discriminate.\n    split; trivial. destruct (zlt ofs hi); simpl in *; try discriminate.\n    split; trivial.\n    assert (RP: Mem.perm m b ofs Cur Freeable). apply (Mem.free_range_perm _ _ _ _ _ FR ofs); omega.\n    destruct k.\n    * eapply Mem.perm_max in RP.\n      unfold Mem.perm in RP. destruct ((Mem.mem_access m) !! b ofs Max); simpl in *; try discriminate.\n      destruct p; simpl in *; try inv RP; simpl; trivial. contradiction.\n    * unfold Mem.perm in RP. destruct ((Mem.mem_access m) !! b ofs Cur); simpl in *; try discriminate.\n      destruct p; simpl in *; try inv RP; simpl; trivial. contradiction.\n  - right; split; trivial. right.\n    destruct (zle lo ofs); destruct (zlt ofs hi); simpl in *; try discriminate; try omega.\n+ right; split; trivial. left; trivial.\nQed.\n\nLemma ple_free: forall m m' b lo hi (FL: Mem.free m b lo hi = Some m') m1 (PLE:perm_lesseq m m1),\n      exists m1', Mem.free m1 b lo hi = Some m1' /\\ perm_lesseq m' m1'.\nProof. intros.\n  specialize (Mem.free_range_perm _ _ _ _ _ FL). intros.\n  assert (RF: Mem.range_perm m1 b lo hi Cur Freeable).\n  { destruct PLE. red; intros.\n    specialize (perm_le_Cur b ofs). specialize (H _ H0). unfold Mem.perm in *.\n    destruct ((Mem.mem_access m) !! b ofs Cur); simpl in *; try contradiction.\n    destruct ((Mem.mem_access m1) !! b ofs Cur); simpl in *; try contradiction.\n    eapply perm_order_trans; eassumption.\n  }\n  destruct (Mem.range_perm_free m1 b lo hi RF) as [mm MM].\n  exists mm; split; trivial.\n  destruct PLE.\n  split; intros.\n  - specialize (perm_le_Cur b0 ofs); clear perm_le_Max perm_le_cont.\n    remember ((Mem.mem_access mm) !! b0 ofs Cur) as q; symmetry in Heqq.\n      destruct q; simpl in *.\n      * rewrite (free_access_inv _ _ _ _ _ MM _ _ _ _ Heqq) in *.\n        remember ((Mem.mem_access m') !! b0 ofs Cur) as w; symmetry in Heqw.\n         destruct w; trivial.\n         rewrite (free_access_inv _ _ _ _ _ FL _ _ _ _ Heqw) in *. simpl in *; trivial.\n      * remember ((Mem.mem_access m') !! b0 ofs Cur) as w; symmetry in Heqw.\n        destruct w; trivial.\n        rewrite (free_access_inv _ _ _ _ _ FL _ _ _ _ Heqw) in *.\n        destruct (free_access_inv_None _ _ _ _ _ MM _ _ _ Heqq).\n        ++ destruct H0 as [? [? [? ?]]]; subst.\n           rewrite (Mem.free_result _ _ _ _ _ FL) in *. simpl in *.\n           rewrite PMap.gss in Heqw.\n           remember (zle lo ofs&& zlt ofs hi ) as t; destruct t; simpl in *; try discriminate.\n           destruct (zle lo ofs); destruct (zlt ofs hi); simpl in *; try discriminate; omega.\n        ++ destruct H0 as [? ?]. rewrite H1 in *; simpl in *; contradiction.\n  - specialize (perm_le_Max b0 ofs); clear perm_le_Cur perm_le_cont.\n    remember ((Mem.mem_access mm) !! b0 ofs Max) as q; symmetry in Heqq.\n      destruct q; simpl in *.\n      * rewrite (free_access_inv _ _ _ _ _ MM _ _ _ _ Heqq) in *.\n        remember ((Mem.mem_access m') !! b0 ofs Max) as w; symmetry in Heqw.\n         destruct w; trivial.\n         rewrite (free_access_inv _ _ _ _ _ FL _ _ _ _ Heqw) in *. simpl in *; trivial.\n      * remember ((Mem.mem_access m') !! b0 ofs Max) as w; symmetry in Heqw.\n        destruct w; trivial.\n        rewrite (free_access_inv _ _ _ _ _ FL _ _ _ _ Heqw) in *.\n        destruct (free_access_inv_None _ _ _ _ _ MM _ _ _ Heqq).\n        ++ destruct H0 as [? [? [? ?]]]; subst.\n           rewrite (Mem.free_result _ _ _ _ _ FL) in *. simpl in *.\n           rewrite PMap.gss in Heqw.\n           remember (zle lo ofs&& zlt ofs hi ) as t; destruct t; simpl in *; try discriminate.\n           destruct (zle lo ofs); destruct (zlt ofs hi); simpl in *; try discriminate; omega.\n        ++ destruct H0 as [? ?]. rewrite H1 in *; simpl in *; contradiction.\n  - rewrite (Mem.free_result _ _ _ _ _ FL). rewrite (Mem.free_result _ _ _ _ _ MM).\n    simpl. apply perm_le_cont. eapply Mem.perm_free_3; eassumption.\n  - rewrite (Mem.free_result _ _ _ _ _ FL). rewrite (Mem.free_result _ _ _ _ _ MM).\n    simpl; trivial.\nQed.\n\nLemma ple_freelist: forall l m m' (FL: Mem.free_list m l = Some m') m1 (PLE:perm_lesseq m m1),\n      exists m1', Mem.free_list m1 l = Some m1' /\\ perm_lesseq m' m1'.\nProof. induction l; simpl; intros.\n+ inv FL;  exists m1; split; trivial.\n+ destruct a as [[b lo] hi]. remember (Mem.free m b lo hi) as q. destruct q; inv FL.\n  symmetry in Heqq.\n  destruct (ple_free _ _ _ _ _ Heqq _ PLE) as [mm [MMF MM]]. rewrite MMF. eauto.\nQed.\n\nLemma ple_storebytes:\n  forall m b ofs bytes m' m1\n   (PLE: perm_lesseq m m1),\n   Mem.storebytes m b ofs bytes = Some m' ->\n   exists m1', perm_lesseq m' m1' /\\ Mem.storebytes m1 b ofs bytes = Some m1'.\nProof.\nintros. Transparent Mem.storebytes. unfold Mem.storebytes in *. Opaque Mem.storebytes.\nremember (Mem.range_perm_dec m b ofs (ofs + Z.of_nat (length bytes)) Cur Writable ) as d.\ndestruct d; inv H.\ndestruct (Mem.range_perm_dec m1 b ofs (ofs + Z.of_nat (length bytes)) Cur Writable).\n+ clear Heqd.\n  eexists; split. 2: reflexivity.\n  destruct PLE.\n  split; intros; simpl.\n  - simpl. apply perm_le_Cur.\n  - simpl. apply perm_le_Max.\n  - simpl in *. rewrite PMap.gsspec. rewrite PMap.gsspec.\n    destruct (peq b0 b); subst.\n    * destruct (zlt ofs0 ofs).\n      ++ rewrite Mem.setN_outside. 2: left; trivial.  rewrite Mem.setN_outside. 2: left; trivial.  apply perm_le_cont. apply H.\n      ++ destruct (zle (ofs+Z.of_nat (length bytes)) ofs0).\n         rewrite Mem.setN_outside. 2: right; xomega.  rewrite Mem.setN_outside. 2: right; xomega.  apply perm_le_cont. apply H.\n         clear - g g0.\n         remember ((Mem.mem_contents m1) !! b) as mA. clear HeqmA.\n         remember ((Mem.mem_contents m) !! b) as mB. clear HeqmB.\n         revert ofs mA mB g g0; induction bytes; intros; simpl.\n         -- simpl in *; omega.\n         -- simpl length in g0; rewrite inj_S in g0.\n            destruct (zeq ofs ofs0).\n            ** subst ofs0. rewrite !Mem.setN_outside by omega. rewrite !ZMap.gss; auto.\n            ** apply IHbytes; omega.\n    * apply perm_le_cont. apply H.\n  - assumption .\n+ elim n; clear - PLE r. destruct PLE.\n  red; intros. specialize (r _ H). specialize (perm_le_Cur b ofs0).\n  unfold Mem.perm in *.\n  destruct ((Mem.mem_access m1) !! b ofs0 Cur).\n  destruct ((Mem.mem_access m) !! b ofs0 Cur). simpl in *. eapply perm_order_trans; eassumption.\n  inv r.\n  destruct ((Mem.mem_access m) !! b ofs0 Cur); inv perm_le_Cur. inv r.\nQed.\n\nLemma ple_loadbytes m b ofs n bytes\n            (LD: Mem.loadbytes m b ofs n = Some bytes)\n            m1 (PLE: perm_lesseq m m1) (N: 0 <= n):\n            Mem.loadbytes m1 b ofs n = Some bytes.\nProof.\nTransparent Mem.loadbytes.\nunfold Mem.loadbytes.\nOpaque Mem.loadbytes.\napply loadbytes_D in LD. destruct LD as [RP1 CONT].\ndestruct PLE.\ndestruct (Mem.range_perm_dec m1 b ofs (ofs + n) Cur Readable).\n+ rewrite CONT; f_equal. eapply Mem.getN_exten.\n  intros. apply perm_le_cont. apply RP1. rewrite nat_of_Z_eq in H; omega.\n+ elim n0; clear - RP1 perm_le_Cur.\n  red; intros. specialize (RP1 _ H). specialize (perm_le_Cur b ofs0).\n  unfold Mem.perm in *.\n  destruct ((Mem.mem_access m1) !! b ofs0 Cur).\n  destruct ((Mem.mem_access m) !! b ofs0 Cur). simpl in *. eapply perm_order_trans; eassumption.\n  inv RP1.\n  destruct ((Mem.mem_access m) !! b ofs0 Cur); inv perm_le_Cur. inv RP1.\nQed.\n\nLemma alloc_access_inv m b lo hi m' (ALLOC: Mem.alloc m lo hi = (m', b)) b' ofs k p\n  (P: (Mem.mem_access m') !! b' ofs k = Some p):\n  (b'=b /\\ Z.le lo ofs /\\ Z.lt ofs hi) \\/\n  (b' <> b /\\ (Mem.mem_access m) !! b' ofs k = Some p).\nProof.\nTransparent Mem.alloc. unfold Mem.alloc in ALLOC. Opaque Mem.alloc. inv ALLOC; simpl in *.\nrewrite PMap.gsspec in P.\ndestruct (peq b' (Mem.nextblock m)); subst; trivial.\n+ left; split; trivial.\n  remember (zle lo ofs && zlt ofs hi) as q. destruct q; inv P; trivial.\n  destruct (zle lo ofs); destruct (zlt ofs hi); simpl in *; try discriminate; omega.\n+ right; split; trivial.\nQed.\n\nLemma alloc_access_inv_None m b lo hi m' (ALLOC: Mem.alloc m lo hi = (m', b)) b' ofs k\n  (P: (Mem.mem_access m') !! b' ofs k = None): (Mem.mem_access m) !! b' ofs k = None.\nProof.\nTransparent Mem.alloc. unfold Mem.alloc in ALLOC. Opaque Mem.alloc. inv ALLOC; simpl in *.\nrewrite PMap.gsspec in P.\ndestruct (peq b' (Mem.nextblock m)); subst; trivial.\napply Mem.nextblock_noaccess. xomega.\nQed.\n\nLemma alloc_inc_perm: forall m lo hi m' b\n      (M: Mem.alloc m lo hi = (m',b)) m1 (PLE: perm_lesseq m m1),\n      exists m1' : mem, Mem.alloc m1 lo hi =(m1',b) /\\ perm_lesseq m' m1'.\nProof. intros.\n  remember (Mem.alloc m1 lo hi). destruct p; symmetry in Heqp.\n  assert (B: b0=b).\n     apply Mem.alloc_result  in M. apply Mem.alloc_result  in Heqp.\n     destruct PLE. rewrite perm_le_nb in *; subst. trivial.\n  subst b0.\n  eexists m0; split; trivial.\n  Transparent Mem.alloc. unfold Mem.alloc in *. Opaque Mem.alloc. inv M; inv Heqp. simpl in *.\n  destruct PLE.\n  split; simpl; intros.\n  + specialize (perm_le_Cur b ofs); clear perm_le_Max perm_le_cont.\n    rewrite perm_le_nb, PMap.gsspec.  rewrite PMap.gsspec.\n    destruct (peq b (Mem.nextblock m1)); subst; trivial.\n    destruct (if zle lo ofs && zlt ofs hi then Some Freeable else None); simpl; trivial. apply perm_refl.\n  + specialize (perm_le_Max b ofs); clear perm_le_Cur perm_le_cont.\n    rewrite perm_le_nb, PMap.gsspec.  rewrite PMap.gsspec.\n    destruct (peq b (Mem.nextblock m1)); subst; trivial.\n    destruct (if zle lo ofs && zlt ofs hi then Some Freeable else None); simpl; trivial. apply perm_refl.\n  + unfold Mem.perm in H; simpl in H.\n    rewrite PMap.gsspec in H.\n    destruct (peq b (Mem.nextblock m)); subst.\n    - rewrite perm_le_nb. do 2 rewrite PMap.gss. trivial.\n    - rewrite PMap.gso; try rewrite H1; trivial. rewrite PMap.gso; trivial. apply perm_le_cont. apply H.\n  + rewrite H1; trivial.\nQed.\n\nLemma perm_lesseq_refl:\n  forall m, perm_lesseq m m.\nProof.\nintros.\n constructor; intros; auto.\n match goal with |- Mem.perm_order'' ?A _ => destruct A; constructor end.\n match goal with |- Mem.perm_order'' ?A _ => destruct A; constructor end.\nQed.\n\n(*************************************************************************)\n\nDefinition corestep_fun {C M : Type} (sem : @CoreSemantics C M) :=\n  forall (m m' m'' : M) c c' c'',\n  corestep sem c m c' m' ->\n  corestep sem c m c'' m'' ->\n  c'=c'' /\\ m'=m''.\n\n(**  Multistepping *)\n\nSection corestepN.\n  Context {C M E:Type} (Sem:@CoreSemantics C M).\n\n  Fixpoint corestepN (n:nat) : C -> M -> C -> M -> Prop :=\n    match n with\n      | O => fun c m c' m' => (c,m) = (c',m')\n      | S k => fun c1 m1 c3 m3 => exists c2, exists m2,\n        corestep Sem c1 m1 c2 m2 /\\\n        corestepN k c2 m2 c3 m3\n    end.\n\n  Lemma corestepN_add : forall n m c1 m1 c3 m3,\n    corestepN (n+m) c1 m1 c3 m3 <->\n    exists c2, exists m2,\n      corestepN n c1 m1 c2 m2 /\\\n      corestepN m 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 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 x1 x2 c3 m3).\n    eauto.\n  Qed.\n\n  Definition corestep_plus c m c' m' :=\n    exists n, corestepN (S n) c m c' m'.\n\n  Definition corestep_star c m c' m' :=\n    exists n, corestepN n c m c' m'.\n\n  Lemma corestep_plus_star : forall c1 c2 m1 m2,\n    corestep_plus c1 m1 c2 m2 -> corestep_star c1 m1 c2 m2.\n  Proof. intros. destruct H as [n1 H1]. eexists. apply H1. Qed.\n\n  Lemma corestep_plus_trans : forall c1 c2 c3 m1 m2 m3,\n    corestep_plus c1 m1 c2 m2 -> corestep_plus c2 m2 c3 m3 ->\n    corestep_plus c1 m1 c3 m3.\n  Proof. intros. destruct H as [n1 H1]. destruct H0 as [n2 H2].\n    destruct (corestepN_add (S n1) (S n2) c1 m1 c3 m3) as [_ H].\n    eexists. apply H. exists c2. exists m2. split; assumption.\n  Qed.\n\n  Lemma corestep_star_plus_trans : forall c1 c2 c3 m1 m2 m3,\n    corestep_star c1 m1 c2 m2 -> corestep_plus c2 m2 c3 m3 ->\n    corestep_plus c1 m1 c3 m3.\n  Proof. intros. destruct H as [n1 H1]. destruct H0 as [n2 H2].\n    destruct (corestepN_add n1 (S n2) 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 corestep_plus_star_trans: forall c1 c2 c3 m1 m2 m3,\n    corestep_plus c1 m1 c2 m2 -> corestep_star c2 m2 c3 m3 ->\n    corestep_plus c1 m1 c3 m3.\n  Proof. intros. destruct H as [n1 H1]. destruct H0 as [n2 H2].\n    destruct (corestepN_add (S n1) n2 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 corestep_star_trans: forall c1 c2 c3 m1 m2 m3,\n    corestep_star c1 m1 c2 m2 -> corestep_star c2 m2 c3 m3 ->\n    corestep_star c1 m1 c3 m3.\n  Proof. intros. destruct H as [n1 H1]. destruct H0 as [n2 H2].\n    destruct (corestepN_add n1 n2 c1 m1 c3 m3) as [_ H].\n    eexists. apply H.  exists c2. exists m2.  split; assumption.\n  Qed.\n\n  Lemma corestep_plus_one: forall c m c' m',\n    corestep  Sem c m c' m' -> corestep_plus c m c' m'.\n  Proof. intros. unfold corestep_plus, corestepN. simpl.\n    exists O. exists c'. exists m'. eauto.\n  Qed.\n\n  Lemma corestep_plus_two: forall c m c' m' c'' m'',\n    corestep  Sem c m c' m' -> corestep  Sem c' m' c'' m'' ->\n    corestep_plus 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 corestep_star_zero: forall c m, corestep_star  c m c m.\n  Proof. intros. exists O. reflexivity. Qed.\n\n  Lemma corestep_star_one: forall c m c' m',\n    corestep  Sem c m c' m' -> corestep_star c m c' m'.\n  Proof. intros.\n    exists (S O). exists c'. exists m'. split; trivial. reflexivity.\n  Qed.\n\n  Lemma corestep_plus_split: forall c m c' m',\n    corestep_plus c m c' m' ->\n    exists c'', exists m'', corestep  Sem c m c'' m'' /\\\n      corestep_star 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 corestepN.\n\nSection memstepN.\n  Context {C:Type} (M:@MemSem C).\n\nLemma corestepN_mem n: forall c m c' m', corestepN M n c m c' m' -> mem_step m m'.\ninduction n; intros; inv H.\n  apply mem_step_refl.\n  destruct H0 as [m'' [CS CSN]]. eapply mem_step_trans.\n  eapply corestep_mem; eassumption.\n  eapply IHn; eassumption.\nQed.\n\nLemma corestep_plus_mem c m c' m' (H:corestep_plus M c m c' m'): mem_step m m'.\ndestruct H as [n H]. eapply corestepN_mem; eassumption. Qed.\n\nLemma corestep_star_mem c m c' m' (H:corestep_star M c m c' m'): mem_step m m'.\ndestruct H as [n H]. eapply corestepN_mem; eassumption. Qed.\n\nLemma memsem_preservesN P (HP: memstep_preserve P)\n      n c m c' m' (H: corestepN M n c m c' m'): P m m'.\napply corestepN_mem in H. apply HP; trivial. Qed.\n\nLemma memsem_preserves_plus P (HP:memstep_preserve P)\n      c m c' m' (H: corestep_plus M c m c' m'): P m m'.\ndestruct H. apply (memsem_preservesN _ HP) in H; trivial. Qed.\n\nLemma memsem_preserves_star P (HP:memstep_preserve P)\n      c m c' m' (H: corestep_star M c m c' m'): P m m'.\ndestruct H. apply (memsem_preservesN _ HP) in H; trivial. Qed.\n\nLemma corestepN_fwd n  c m c' m'\n   (CS:corestepN M n c m c' m'): mem_forward m m'.\nProof.\neapply memsem_preservesN; try eassumption. apply mem_forward_preserve.\nQed.\n\nLemma corestep_plus_fwd c m c' m'\n   (CS:corestep_plus M c m c' m'): mem_forward m m'.\nProof.\ndestruct CS. eapply corestepN_fwd; eassumption.\nQed.\n\nLemma corestep_star_fwd c m c' m'\n   (CS:corestep_star M c m c' m'): mem_forward m m'.\nProof.\ndestruct CS. eapply corestepN_fwd; eassumption.\nQed.\n\nLemma corestepN_rdonly n c m c' m'\n    (CS:corestepN M n c m c' m') b (VB:Mem.valid_block m b): readonly m b m'.\nProof.\neapply (memsem_preservesN _ readonly_preserve'); eassumption.\nQed.\n\nLemma corestep_plus_rdonly c m c' m'\n   (CS:corestep_plus M c m c' m') b (VB:Mem.valid_block m b): readonly m b m'.\nProof.\ndestruct CS. eapply corestepN_rdonly; eassumption.\nQed.\n\nLemma corestep_star_rdonly c m c' m'\n   (CS:corestep_star M c m c' m')b (VB:Mem.valid_block m b): readonly m b m'.\nProof.\ndestruct CS. eapply corestepN_rdonly; eassumption.\nQed.\n\nEnd memstepN.\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/semantics_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.26176483855874816}}
{"text": "Require Import AutoSep.\nRequire Import List.\n\nRequire Import SepHintsUtil.\n\nSet Implicit Arguments.\n\nSection TopSection.\n\n  Definition locals_to_elim (_ : list string) := True.\n\n  Lemma elim_locals : forall vars vs p, locals_to_elim vars -> locals vars vs 0 p ===> p =?> length vars.\n    unfold locals; intros.\n    sepLemma.\n    eapply Himp_trans; [ apply ptsto32m'_in | ].\n    eapply Himp_trans; [ apply ptsto32m'_allocated | ].\n    rewrite length_toArray; apply Himp_refl.\n  Qed.\n\n  Definition hints_elim_locals : TacPackage.\n    prepare elim_locals tt.\n  Defined.\n\nEnd TopSection.", "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/SepHints4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2617648322033695}}
{"text": "From stdpp Require Import tactics.\nFrom iris.bi Require Import bi.\nFrom iris.prelude Require Import options.\n\nSection persistent_pred.\n  Context (A : Type) (PROP : bi).\n\n  (* The domain of semantic types: persistent Iris predicates type A. *)\n  Record persistent_pred := PersPred {\n    pers_pred_car :> A → PROP;\n    pers_pred_persistent x : Persistent (pers_pred_car x)\n  }.\n  Local Arguments PersPred _%I {_}.\n  Global Existing Instances pers_pred_persistent.\n\n  Instance persistent_pred_equiv : Equiv persistent_pred :=\n    λ Φ Φ', ∀ x, Φ x ≡ Φ' x.\n  Instance persistent_pred_dist : Dist persistent_pred :=\n    λ n Φ Φ', ∀ x, Φ x ≡{n}≡ Φ' x.\n  Definition persistent_pred_ofe_mixin : OfeMixin persistent_pred.\n  Proof. by apply (iso_ofe_mixin (pers_pred_car : _ → A -d> _)). Qed.\n  Canonical Structure persistent_predO :=\n    Ofe persistent_pred persistent_pred_ofe_mixin.\n\n  Global Instance persistent_pred_cofe : Cofe persistent_predO.\n  Proof.\n    apply (iso_cofe_subtype' (λ Φ : A -d> PROP, ∀ w, Persistent (Φ w))\n      PersPred pers_pred_car)=> //.\n    - apply _.\n    - apply limit_preserving_forall=> w.\n      by apply bi.limit_preserving_Persistent=> n ??.\n  Qed.\n\n  Global Instance persistent_pred_car_ne n :\n    Proper (dist n ==> (=) ==> dist n)\n      pers_pred_car.\n  Proof. by intros ? ? ? ? ? ->. Qed.\n  Global Instance persistent_pred_car_proper :\n    Proper ((≡) ==> (=) ==> (≡)) pers_pred_car.\n  Proof. by intros ? ? ? ? ? ->. Qed.\n\n  Lemma persistent_pred_ext (f g : persistent_pred) : f ≡ g ↔ ∀ x, f x ≡ g x.\n  Proof. done. Qed.\n\n  Global Instance: Inhabited persistent_pred := populate (PersPred (λ _, True))%I.\n\nEnd persistent_pred.\n\nGlobal Arguments PersPred {_ _} _%I {_}.\nGlobal Arguments pers_pred_car {_ _} !_ _.\nGlobal Instance: Params (@pers_pred_car) 2 := {}.\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/logrel/persistent_pred.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953797290152, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2617566230363206}}
{"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(** NNRC is the named nested relational calculus. It serves as an\nintermediate language to facilitate code generation for non-functional\ntargets. *)\n\n(** NNRC is a thin layer over the core language cNNRC. As cNNRC, NNRC\n  is evaluated within a local environment. *)\n\n(** Additional operators in NNRC can be easily expressed in terms of\n  the core cNNRC, but are useful for optimization purposes. The main\n  such operator is group-by. *)\n\n(** Summary:\n- Language: NNRC (Named Nested Relational Calculus)\n- Based on: \"Polymorphic type inference for the named nested\n  relational calculus.\" Jan Van den Bussche, and Stijn\n  Vansummeren. ACM Transactions on Computational Logic (TOCL) 9.1\n  (2007): 3.\n- translating to NNRC: NRAEnv, cNNRC\n- translating from NNRC: cNNRC, NNRCMR, DNNRC, Java, JavaScript *)\n\nRequire Import String.\nRequire Import List.\nRequire Import Arith.\nRequire Import EquivDec.\nRequire Import Morphisms.\nRequire Import Arith.\nRequire Import Max.\nRequire Import Bool.\nRequire Import Peano_dec.\nRequire Import EquivDec.\nRequire Import Decidable.\nRequire Import Utils.\nRequire Import DataRuntime.\nRequire Import cNNRCRuntime.\n\nSection NNRC.\n  Context {fruntime:foreign_runtime}.\n\n  (** * Abstract Syntax *)\n  \n  (** The full abstract syntax for NNRC is already defined in core cNNRC. *)\n\n  Definition nnrc := nnrc.\n\n  (** * Macros *)\n  \n  (** All the additional operators are defined in terms of the core cNNRC. *)\n  \n  Section Macros.\n    Context {h:brand_relation_t}.\n\n    (** The following macro defines group-by in terms of existing cNNRC expressions. *)\n\n    (** <<e groupby[g,keys] ==\n         let $group0 := e\n         in { $group2 × [ g: ♯flatten({ $group3 = π[keys] ? {$group3} {}\n                            | $group3 ∈ $group0 }) ]\n            | $group2 ∈ ♯distinct({ π[keys]($group1)\n                                  | $group1 ∈ $group0 }) }>>\n     *)\n\n    Definition nnrc_group_by (g:string) (sl:list string) (e:nnrc) : nnrc :=\n      let t0 := \"$group0\"%string in\n      let t1 := \"$group1\"%string in\n      let t2 := \"$group2\"%string in\n      let t3 := \"$group3\"%string in\n      NNRCLet\n        t0 e\n        (NNRCFor t2\n                 (NNRCUnop OpDistinct\n                           (NNRCFor t1 (NNRCVar t0) (NNRCUnop (OpRecProject sl) (NNRCVar t1))))\n                 (NNRCBinop OpRecConcat\n                            (NNRCVar t2)\n                            (NNRCUnop (OpRec g)\n                                      (NNRCUnop OpFlatten\n                                                (NNRCFor t3 (NNRCVar t0)\n                                                         (NNRCIf (NNRCBinop OpEqual\n                                                                            (NNRCUnop (OpRecProject sl)\n                                                                                      (NNRCVar t3))\n                                                                            (NNRCVar t2))\n                                                                 (NNRCUnop OpBag (NNRCVar t3))\n                                                                 (NNRCConst (dcoll nil)))))))).\n\n    (** This definition is equivalent to a nested evaluation group by algorithm. *)\n\n    Lemma nnrc_group_by_correct cenv env\n          (g:string) (sl:list string)\n          (e:nnrc)\n          (incoll:list data):\n      nnrc_core_eval h cenv env e = Some (dcoll incoll) ->\n      nnrc_core_eval h cenv env (nnrc_group_by g sl e) = lift dcoll (group_by_nested_eval_table g sl incoll).\n    Proof.\n      intros.\n      rewrite <- (group_by_table_correct g sl incoll); simpl.\n      rewrite H; trivial.\n    Qed.\n    \n    Lemma nnrc_group_by_correct_some cenv env\n          (g:string) (sl:list string)\n          (e:nnrc)\n          (incoll outcoll:list data):\n      nnrc_core_eval h cenv env e = Some (dcoll incoll) ->\n      group_by_nested_eval_table g sl incoll = Some outcoll -> \n      nnrc_core_eval h cenv env (nnrc_group_by g sl e) = Some (dcoll outcoll).\n    Proof.\n      intros.\n      unfold nnrc_group_by; simpl.\n      rewrite H; simpl; clear H.\n      apply (group_by_table_correct_some g sl incoll outcoll H0).\n    Qed.\n\n    Lemma nnrc_group_by_correct_none cenv env\n          (g:string) (sl:list string)\n          (e:nnrc) :\n      nnrc_core_eval h cenv env e = None ->\n      nnrc_core_eval h cenv env (nnrc_group_by g sl e) = None.\n    Proof.\n      intros.\n      unfold nnrc_group_by; simpl.\n      rewrite H; simpl; clear H.\n      trivial.\n    Qed.\n\n    Lemma nnrc_group_by_correct_some_ncoll cenv env\n          (g:string) (sl:list string)\n          (e:nnrc) d :\n      (forall x, d <> dcoll x) ->\n      nnrc_core_eval h cenv env e = Some d ->\n      nnrc_core_eval h cenv env (nnrc_group_by g sl e) = None.\n    Proof.\n      intros.\n      unfold nnrc_group_by; simpl.\n      rewrite H0; simpl; clear H0.\n      destruct d; simpl; trivial.\n      eelim H; eauto.\n    Qed.\n\n  End Macros.\n\n  (** * Evaluation Semantics *)\n\n  Section Semantics.\n    Context {h:brand_relation_t}.\n    Context {cenv:bindings}.\n\n    Fixpoint nnrc_to_nnrc_base (e:nnrc) : nnrc :=\n      match e with\n      | NNRCGetConstant v => NNRCGetConstant v\n      | NNRCVar v => NNRCVar v\n      | NNRCConst d => NNRCConst d\n      | NNRCBinop b e1 e2 =>\n        NNRCBinop b (nnrc_to_nnrc_base e1) (nnrc_to_nnrc_base e2)\n      | NNRCUnop u e1 =>\n        NNRCUnop u (nnrc_to_nnrc_base e1)\n      | NNRCLet v e1 e2 =>\n        NNRCLet v (nnrc_to_nnrc_base e1) (nnrc_to_nnrc_base e2)\n      | NNRCFor v e1 e2 =>\n        NNRCFor v (nnrc_to_nnrc_base e1) (nnrc_to_nnrc_base e2)\n      | NNRCIf e1 e2 e3 =>\n        NNRCIf (nnrc_to_nnrc_base e1) (nnrc_to_nnrc_base e2) (nnrc_to_nnrc_base e3)\n      | NNRCEither e1 v2 e2 v3 e3 =>\n        NNRCEither (nnrc_to_nnrc_base e1) v2 (nnrc_to_nnrc_base e2) v3 (nnrc_to_nnrc_base e3)\n      | NNRCGroupBy g sl e1 =>\n        nnrc_group_by g sl (nnrc_to_nnrc_base e1)\n      end.\n\n    Definition nnrc_eval (env:bindings) (e:nnrc) : option data :=\n      nnrc_core_eval h cenv env (nnrc_to_nnrc_base e).\n\n    Remark nnrc_to_nnrc_base_eq (e:nnrc):\n      forall env,\n        nnrc_eval env e = nnrc_core_eval h cenv env (nnrc_to_nnrc_base e).\n    Proof.\n      intros; reflexivity.\n    Qed.\n\n    (** Since we rely on cNNRC abstract syntax for the whole NNRC, it is important to check that translating to the core does not reuse the additional operations only present in NNRC. *)\n    \n    Lemma nnrc_to_nnrc_base_is_core (e:nnrc) :\n      nnrcIsCore (nnrc_to_nnrc_base e).\n    Proof.\n      induction e; intros; simpl in *; auto.\n      repeat (split; auto).\n    Qed.\n\n    (** The following function effectively returns an abstract syntax\n    tree with the right type for cNNRC. *)\n    \n    Program Definition nnrc_to_nnrc_core (e:nnrc) : nnrc_core :=\n      nnrc_to_nnrc_base e.\n    Next Obligation.\n      apply nnrc_to_nnrc_base_is_core.\n    Defined.\n\n    (** Additional properties of the translation from NNRC to cNNRC. *)\n    \n    Lemma core_nnrc_to_nnrc_ext_id (e:nnrc) :\n      nnrcIsCore e ->\n      (nnrc_to_nnrc_base e) = e.\n    Proof.\n      intros.\n      induction e; simpl in *.\n      - reflexivity.\n      - reflexivity.\n      - reflexivity.\n      - elim H; intros.\n        rewrite IHe1; auto; rewrite IHe2; auto.\n      - rewrite IHe; auto.\n      - elim H; intros.\n        rewrite IHe1; auto; rewrite IHe2; auto.\n      - elim H; intros.\n        rewrite IHe1; auto; rewrite IHe2; auto.\n      - elim H; intros.\n        elim H1; intros.\n        rewrite IHe1; auto; rewrite IHe2; auto; rewrite IHe3; auto.\n      - elim H; intros.\n        elim H1; intros.\n        rewrite IHe1; auto; rewrite IHe2; auto; rewrite IHe3; auto.\n      - contradiction. (* GroupBy case *)\n    Qed.\n    \n    Lemma core_nnrc_to_nnrc_ext_idempotent (e1 e2:nnrc) :\n      e1 = nnrc_to_nnrc_base e2 ->\n      nnrc_to_nnrc_base e1 = e1.\n    Proof.\n      intros.\n      apply core_nnrc_to_nnrc_ext_id.\n      rewrite H.\n      apply nnrc_to_nnrc_base_is_core.\n    Qed.\n\n    Corollary core_nnrc_to_nnrc_ext_idempotent_corr (e:nnrc) :\n      nnrc_to_nnrc_base (nnrc_to_nnrc_base e) = (nnrc_to_nnrc_base e).\n    Proof.\n      apply (core_nnrc_to_nnrc_ext_idempotent _ e).\n      reflexivity.\n    Qed.\n\n    Remark nnrc_to_nnrc_ext_eq (e:nnrc):\n      nnrcIsCore e ->\n      forall env,\n        nnrc_core_eval h cenv env e = nnrc_eval env e.\n    Proof.\n      intros.\n      unfold nnrc_eval.\n      rewrite core_nnrc_to_nnrc_ext_id.\n      reflexivity.\n      assumption.\n    Qed.\n    \n    (** we are only sensitive to the environment up to lookup *)\n    Global Instance nnrc_eval_lookup_equiv_prop :\n      Proper (lookup_equiv ==> eq ==> eq) nnrc_eval.\n    Proof.\n      generalize nnrc_core_eval_lookup_equiv_prop; intros.\n      unfold Proper, respectful, lookup_equiv in *; intros; subst.\n      unfold nnrc_eval.\n      rewrite (H h cenv x y H0 (nnrc_to_nnrc_base y0) (nnrc_to_nnrc_base y0)).\n      reflexivity.\n      reflexivity.\n    Qed.\n    \n  End Semantics.\n\n  (** * Additional Properties *)\n\n  (** Most of the following properties are useful for shadowing and variable substitution on the full NNRC. *)\n  \n  Section Properties.\n    Context {h:brand_relation_t}.\n    \n    Lemma nnrc_to_nnrc_base_free_vars_same e:\n      nnrc_free_vars e = nnrc_free_vars (nnrc_to_nnrc_base e).\n    Proof.\n      induction e; simpl; try reflexivity.\n      - rewrite IHe1; rewrite IHe2; reflexivity.\n      - assumption.\n      - rewrite IHe1; rewrite IHe2; reflexivity.\n      - rewrite IHe1; rewrite IHe2; reflexivity.\n      - rewrite IHe1; rewrite IHe2; rewrite IHe3; reflexivity.\n      - rewrite IHe1; rewrite IHe2; rewrite IHe3; reflexivity.\n      - rewrite app_nil_r.\n        assumption.\n    Qed.\n\n    Lemma nnrc_to_nnrc_base_bound_vars_impl x e:\n      In x (nnrc_bound_vars e) -> In x (nnrc_bound_vars (nnrc_to_nnrc_base e)).\n    Proof.\n      induction e; simpl; unfold not in *; intros.\n      - auto.\n      - auto.\n      - auto.\n      - intuition.\n        rewrite in_app_iff in H.\n        rewrite in_app_iff.\n        elim H; intros; auto.\n      - intuition.\n      - intuition.\n        rewrite in_app_iff in H0.\n        rewrite in_app_iff.\n        elim H0; intros; auto.\n      - intuition.\n        rewrite in_app_iff in H0.\n        rewrite in_app_iff.\n        elim H0; intros; auto.\n      - rewrite in_app_iff in H.\n        rewrite in_app_iff in H.\n        rewrite in_app_iff.\n        rewrite in_app_iff.\n        elim H; clear H; intros; auto.\n        elim H; clear H; intros; auto.\n      - rewrite in_app_iff in H.\n        rewrite in_app_iff in H.\n        rewrite in_app_iff.\n        rewrite in_app_iff.\n        elim H; clear H; intros; auto.\n        elim H; clear H; intros; auto.\n        elim H; clear H; intros; auto.\n        elim H; clear H; intros; auto.\n        right. right. auto.\n        right. right. auto.\n      - specialize (IHe H).\n        right.\n        rewrite in_app_iff.\n        auto.\n    Qed.\n\n    Lemma nnrc_to_nnrc_base_bound_vars_impl_not x e:\n      ~ In x (nnrc_bound_vars (nnrc_to_nnrc_base e)) -> ~ In x (nnrc_bound_vars e).\n    Proof.\n      unfold not.\n      intros.\n      apply H.\n      apply nnrc_to_nnrc_base_bound_vars_impl.\n      assumption.\n    Qed.\n\n    Definition really_fresh_in_ext sep oldvar avoid e :=\n      really_fresh_in sep oldvar avoid (nnrc_to_nnrc_base e).\n    \n    Lemma really_fresh_from_free_ext sep old avoid (e:nnrc) :\n      ~ In (really_fresh_in_ext sep old avoid e) (nnrc_free_vars (nnrc_to_nnrc_base e)).\n    Proof.\n      unfold really_fresh_in_ext.\n      intros inn1.\n      apply (really_fresh_in_fresh sep old avoid (nnrc_to_nnrc_base e)).\n      repeat rewrite in_app_iff; intuition.\n    Qed.\n\n    Lemma nnrc_to_nnrc_base_subst_comm e1 v1 e2:\n      nnrc_subst (nnrc_to_nnrc_base e1) v1 (nnrc_to_nnrc_base e2) =\n      nnrc_to_nnrc_base (nnrc_subst e1 v1 e2).\n    Proof.\n      induction e1; simpl; try reflexivity.\n      - destruct (equiv_dec v v1); reflexivity.\n      - rewrite IHe1_1; rewrite IHe1_2; reflexivity.\n      - rewrite IHe1; reflexivity.\n      - rewrite IHe1_1.\n        destruct (equiv_dec v v1); try reflexivity.\n        rewrite IHe1_2; reflexivity.\n      - rewrite IHe1_1.\n        destruct (equiv_dec v v1); try reflexivity.\n        rewrite IHe1_2; reflexivity.\n      - rewrite IHe1_1; rewrite IHe1_2; rewrite IHe1_3; reflexivity.\n      - rewrite IHe1_1.\n        destruct (equiv_dec v v1);\n          destruct (equiv_dec v0 v1);\n          try reflexivity.\n        rewrite IHe1_3; reflexivity.\n        rewrite IHe1_2; reflexivity.\n        rewrite IHe1_2; rewrite IHe1_3; reflexivity.\n      - unfold nnrc_group_by.\n        rewrite IHe1.\n        unfold var in *.\n        destruct (equiv_dec \"$group0\"%string v1); try congruence; try reflexivity.\n        destruct (equiv_dec \"$group1\"%string v1); try congruence; try reflexivity.\n        destruct (equiv_dec \"$group2\"%string v1); try congruence; try reflexivity.\n        destruct (equiv_dec \"$group3\"%string v1); try congruence; try reflexivity.\n        destruct (equiv_dec \"$group2\"%string v1); try congruence; try reflexivity.\n        destruct (equiv_dec \"$group3\"%string v1); try congruence; try reflexivity.\n    Qed.\n\n    Lemma nnrc_to_nnrc_base_rename_lazy_comm e v1 v2:\n      nnrc_rename_lazy (nnrc_to_nnrc_base e) v1 v2 =\n      nnrc_to_nnrc_base (nnrc_rename_lazy e v1 v2).\n    Proof.\n      induction e; unfold nnrc_rename_lazy in *; simpl; try reflexivity.\n      - destruct (equiv_dec v1 v2); reflexivity.\n      - destruct (equiv_dec v1 v2); try reflexivity.\n        destruct (equiv_dec v v1); try reflexivity.\n      - destruct (equiv_dec v1 v2); reflexivity.\n      - destruct (equiv_dec v1 v2); try reflexivity.\n        simpl. rewrite <- IHe1; rewrite <- IHe2; reflexivity.\n      - destruct (equiv_dec v1 v2); try reflexivity.\n        simpl. rewrite <- IHe; reflexivity.\n      - destruct (equiv_dec v1 v2); try reflexivity.\n        rewrite IHe1.\n        rewrite <- nnrc_to_nnrc_base_subst_comm; simpl.\n        destruct (equiv_dec v v1); try reflexivity.\n        rewrite <- IHe1; reflexivity.\n        rewrite <- IHe1; rewrite <- IHe2; simpl; reflexivity.\n      - destruct (equiv_dec v1 v2); try reflexivity.\n        rewrite IHe1.\n        rewrite <- nnrc_to_nnrc_base_subst_comm; simpl.\n        destruct (equiv_dec v v1); try reflexivity.\n        rewrite <- IHe1; reflexivity.\n        rewrite <- IHe1; rewrite <- IHe2; simpl; reflexivity.\n      - destruct (equiv_dec v1 v2); try reflexivity.\n        simpl; rewrite <- IHe1; rewrite <- IHe2; rewrite <- IHe3.\n        reflexivity.\n      - destruct (equiv_dec v1 v2); try reflexivity.\n        rewrite IHe1.\n        destruct (equiv_dec v v1); try reflexivity.\n        destruct (equiv_dec v0 v1); try reflexivity.\n        rewrite <- nnrc_to_nnrc_base_subst_comm; simpl.\n        rewrite <- nnrc_to_nnrc_base_subst_comm; simpl.\n        rewrite <- IHe3.\n        reflexivity.\n        destruct (equiv_dec v0 v1); try reflexivity.\n        rewrite <- nnrc_to_nnrc_base_subst_comm; simpl.\n        rewrite <- nnrc_to_nnrc_base_subst_comm; simpl.\n        rewrite <- IHe2.\n        reflexivity.\n        rewrite <- nnrc_to_nnrc_base_subst_comm; simpl.\n        rewrite <- nnrc_to_nnrc_base_subst_comm; simpl.\n        rewrite <- IHe2.\n        rewrite <- IHe3.\n        reflexivity.\n      - simpl.\n        unfold nnrc_group_by.\n        destruct (equiv_dec v1 v2); try reflexivity.\n        rewrite IHe.\n        simpl; unfold nnrc_group_by.\n        unfold var in *.\n        destruct (equiv_dec \"$group0\"%string v1); try congruence; try reflexivity.\n        destruct (equiv_dec \"$group1\"%string v1); try congruence; try reflexivity.\n        destruct (equiv_dec \"$group2\"%string v1); try congruence; try reflexivity.\n        destruct (equiv_dec \"$group3\"%string v1); try congruence; try reflexivity.\n        destruct (equiv_dec \"$group2\"%string v1); try congruence; try reflexivity.\n        destruct (equiv_dec \"$group3\"%string v1); try congruence; try reflexivity.\n    Qed.\n\n    (** Unshadow properties for the full NNRC. *)\n    Lemma unshadow_over_nnrc_ext_idem sep renamer avoid e:\n      (nnrc_to_nnrc_base (unshadow sep renamer avoid (nnrc_to_nnrc_base e))) =\n      (unshadow sep renamer avoid (nnrc_to_nnrc_base e)).\n    Proof.\n      generalize (unshadow_preserve_core sep renamer avoid (nnrc_to_nnrc_base e)); intros.\n      rewrite core_nnrc_to_nnrc_ext_id.\n      reflexivity.\n      apply H.\n      apply nnrc_to_nnrc_base_is_core.\n    Qed.\n\n    Lemma nnrc_eval_cons_subst {cenv} e env v x v' :\n      ~ (In v' (nnrc_free_vars e)) ->\n      ~ (In v' (nnrc_bound_vars e)) ->\n      @nnrc_eval h cenv ((v',x)::env) (nnrc_subst e v (NNRCVar v')) = \n      @nnrc_eval h cenv ((v,x)::env) e.\n    Proof.\n      revert env v x v'.\n      nnrc_cases (induction e) Case; simpl; unfold equiv_dec;\n        unfold nnrc_eval in *; unfold var in *; trivial; intros; simpl.\n      - Case \"NNRCVar\"%string.\n        intuition. destruct (string_eqdec v0 v); simpl; subst; intuition.\n        + match_destr; intuition. simpl. dest_eqdec; intuition.\n          destruct (equiv_dec v v); try congruence.\n        + match_destr; subst; simpl; dest_eqdec; intuition.\n          destruct (equiv_dec v v0); try congruence.\n      - Case \"NNRCBinop\"%string.\n        rewrite nin_app_or in H. f_equal; intuition.\n      - f_equal; intuition.\n      - rewrite nin_app_or in H. rewrite IHe1 by intuition.\n        case_eq (nnrc_core_eval h cenv ((v0, x) :: env) (nnrc_to_nnrc_base e1)); trivial; intros d deq.\n        destruct (string_eqdec v v0); unfold Equivalence.equiv in *; subst; simpl.\n        + generalize (@nnrc_core_eval_remove_duplicate_env _ h cenv nil v0 d nil); \n            simpl; intros rr1; rewrite rr1.\n          destruct (string_eqdec v0 v'); unfold Equivalence.equiv in *; subst.\n          * generalize (@nnrc_core_eval_remove_duplicate_env _ h cenv nil v' d nil); \n              simpl; auto.\n          * generalize (@nnrc_core_eval_remove_free_env _ h cenv ((v0,d)::nil)); \n              simpl; intros rr2; apply rr2. intuition.\n            elim H3. apply remove_in_neq; auto.\n            rewrite nnrc_to_nnrc_base_free_vars_same; auto.\n        + destruct (string_eqdec v v'); unfold Equivalence.equiv in *; subst; [intuition | ].\n          generalize (@nnrc_core_eval_swap_neq _ h cenv nil v d); simpl; intros rr2; \n            repeat rewrite rr2 by trivial.\n          apply IHe2.\n          * intros nin; intuition. elim H2; apply remove_in_neq; auto.\n          * intuition.\n      - rewrite nin_app_or in H. rewrite IHe1 by intuition.\n        case_eq (nnrc_core_eval h cenv ((v0, x) :: env) (nnrc_to_nnrc_base e1)); trivial; intros d deq.\n        destruct d; trivial.\n        f_equal.\n        apply lift_map_ext; intros.\n        destruct (string_eqdec v v0); unfold Equivalence.equiv in *; subst; simpl.\n        + generalize (@nnrc_core_eval_remove_duplicate_env _ h cenv nil v0 x0 nil); \n            simpl; intros rr1; rewrite rr1.\n          destruct (string_eqdec v0 v'); unfold Equivalence.equiv in *; subst.\n          * generalize (@nnrc_core_eval_remove_duplicate_env _ h cenv nil v' x0 nil); \n              simpl; auto.\n          * generalize (@nnrc_core_eval_remove_free_env _ h cenv ((v0,x0)::nil)); \n              simpl; intros rr2; apply rr2. intuition.\n            elim H4. apply remove_in_neq; auto.\n            rewrite nnrc_to_nnrc_base_free_vars_same; auto.\n        + destruct (string_eqdec v v'); unfold Equivalence.equiv in *; subst; [intuition | ].\n          generalize (@nnrc_core_eval_swap_neq _ h cenv nil v x0); simpl; intros rr2; \n            repeat rewrite rr2 by trivial.\n          apply IHe2.\n          * intros nin; intuition. elim H3; apply remove_in_neq; auto.\n          * intuition.\n      - rewrite nin_app_or in H; destruct H as [? HH]; \n          rewrite nin_app_or in HH, H0.\n        rewrite nin_app_or in H0.\n        rewrite IHe1, IHe2, IHe3; intuition.\n      - apply not_or in H0; destruct H0 as [neq1 neq2].\n        apply not_or in neq2; destruct neq2 as [neq2 neq3].\n        repeat rewrite nin_app_or in neq3.\n        repeat rewrite nin_app_or in H.\n        rewrite IHe1 by intuition.\n        repeat rewrite <- remove_in_neq in H by congruence.\n        match_destr. destruct d; trivial.\n        + match_destr; unfold Equivalence.equiv in *; subst.\n          * generalize (@nnrc_core_eval_remove_duplicate_env _ h cenv nil v1 d nil); simpl;\n              intros re2; rewrite re2 by trivial.\n            generalize (@nnrc_core_eval_remove_free_env _ h cenv ((v1,d)::nil)); \n              simpl; intros re3. rewrite re3. intuition.\n            rewrite <- nnrc_to_nnrc_base_free_vars_same; intuition.\n          * generalize (@nnrc_core_eval_swap_neq _ h cenv nil v d); simpl;\n              intros re1; repeat rewrite re1 by trivial.\n            rewrite IHe2; intuition.\n        + match_destr; unfold Equivalence.equiv in *; subst.\n          * generalize (@nnrc_core_eval_remove_duplicate_env _ h cenv nil v1 d nil); simpl;\n              intros re2; rewrite re2 by trivial.\n            generalize (@nnrc_core_eval_remove_free_env _ h cenv ((v1,d)::nil)); \n              simpl; intros re3. rewrite re3. intuition.\n            rewrite <- nnrc_to_nnrc_base_free_vars_same; intuition.\n          * generalize (@nnrc_core_eval_swap_neq _ h cenv nil v0 d); simpl;\n              intros re1; repeat rewrite re1 by trivial.\n            rewrite IHe3; intuition.\n      - rewrite IHe; try assumption.\n        reflexivity.\n    Qed.\n\n  End Properties.\n\n  (** * Toplevel *)\n  \n  (** Top-level evaluation is used externally by the Q*cert\n  compiler. It takes an NNRC expression and a global environment as\n  input. *)\n\n  Section Top.\n    Context (h:brand_relation_t).\n    Definition nnrc_eval_top (q:nnrc) (cenv:bindings) : option data :=\n      @nnrc_eval h (rec_sort cenv) nil q.\n  End Top.\n  \nEnd NNRC.\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/NNRC/Lang/NNRC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.26173846842729204}}
{"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.Relations.Relations.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Coq.Classes.RelationPairs.\nRequire Import Coq.Classes.Morphisms.\n\nRequire Import ExtensionalityAxioms.\nRequire Import Lens.\nRequire Import Functor.\nRequire Import PowersetMonad.\n\n\n(** * Lifting operations *)\n\n(** Because [Mem.MemoryModel] contains so many theorems, we need some\n  systematic way to lift the memory operations along a lens, so that\n  the lifting of the theorems is convenient to automate.\n\n  The signature of most of the memory operations are variations on\n  the theme [mem -> F mem], where [F] is a functor such as [option]\n  or [- × Z]. Using the functor's [fmap] and the lens operations,\n  we can define a generic lifting operator as in the following. *)\n\nClass Lift {S V} π `{πops: LensOps S V π} A B := { lift: A -> B }.\n\nArguments lift {S V} π {πops A B Lift} _.\n\nSection LIFT.\n  Context {S V} `{HSV: Lens S V} `{HF: Functor}.\n\n  Global Instance lens_lift: Lift π (V -> F V) (S -> F S) := {\n    lift f s := fmap (fun v => set π v s) (f (π s))\n  }.\nEnd LIFT.\n\n(** Typeclass resolution needs some help to figure out those functors\n  by unification. *)\n\nSection LIFTINSTANCES.\n  Context {S V} `{HSV: Lens S V}.\n\n  Global Instance lift_const A: Lift π (V -> A) (S -> A) :=\n    lens_lift (F := (fun _ => A)).\n  Global Instance lift_prod A: Lift π (V -> V * A) (S -> S * A) :=\n    lens_lift.\n  Global Instance lift_powerset: Lift π (V -> V -> Prop) (S -> S -> Prop) :=\n    lens_lift (F := (fun X => X -> Prop)).\nEnd LIFTINSTANCES.\n\n\n(** ** The [lift_peel] tactic *)\n\n(** This is the main tactic we use: it lifts a theorem [Hf] of\n  the underlying memory model by \"peeling off\" its structure\n  recursively to prove the lifted goal. The leaf goals are\n  handled with the caller-provided tactic [leaftac]. *)\n\n(* Premises are \"translated\" and used to specialize Hf *)\nLtac lift_peel_intro π recurse Hf x :=\n  intro x;\n  (specialize (Hf x) ||\n   specialize (Hf (π x)) ||\n   (match type of Hf with\n      forall (H: ?T), _ =>\n        let H' := fresh H in\n        assert (H': T) by recurse x;\n        specialize (Hf H');\n        clear H'\n    end));\n  recurse Hf.\n\n(* Existential: we must use [set] to augment any memory state\n  provided by Hf, but we can otherwise just pass everything along *)\nLtac lift_peel_exists π recurse Hf x :=\n  let Hf' := fresh Hf in\n  destruct Hf as [x Hf'];\n  (exists x || eexists (set _ x _));\n  recurse Hf'.\n\n(* Conjunction: split and peel each side independently *)\nLtac lift_peel_conj π recurse Hf :=\n  let Hl := fresh Hf \"l\" in\n  let Hr := fresh Hf \"r\" in\n  destruct Hf as [Hl Hr];\n  split; [recurse Hl | recurse Hr].\n\nLtac lift_peel π Hf leaftac :=\n  let recurse Hf := lift_peel π Hf leaftac in\n  try match goal with\n    | |- forall (x: _), _ =>\n      let x := fresh x in\n      lift_peel_intro π recurse Hf x\n    | |- exists (x: _), _ =>\n      let x := fresh x in\n        lift_peel_exists π recurse Hf x\n    | |- { x: _ | _ } =>\n      let x := fresh x in\n        lift_peel_exists π recurse Hf x\n    | |- _ /\\ _ =>\n      lift_peel_conj π recurse Hf\n    | |- ?T =>\n      leaftac\n  end.\n\n(** Now the goal is to come up with an appropriate leaf tactic which\n  will be able to prove some theorems instanciated with the lifted\n  operations using the original version. *)\n\n\n(** ** Expressing everything in terms of [lift] *)\n\n(** As a first step, in order to be able to apply general theorems\n  about it, we will want to make sure the goal and premises are all\n  stated in terms of [lift]. In order to do this, we use the rule\n  below to make sure that the [simpl] tactic stops whenever [lift] is\n  reached. Then [simpl] allows us to unfold typeclass methods which\n  are defined in terms of lift (the most common case). *)\n\nArguments lift _ _ _ _ _ _ _ _ : simpl never.\n\n(** There are also derived operations (such as [free_list] for\n  instance), which are defined in terms of the typeclass methods.\n  In such cases, we usually want to prove that lifting such operations\n  is equivalent to applying them to a lifted typeclass instance.\n  Then we can rewrite them in terms of [lift] as well. Such proofs are\n  collected into the \"lift\" rewrite database. *)\n\nLtac lift_norm :=\n  repeat progress (simpl in *; autorewrite with lift in *).\n\n(** Unfortunately there is no [Create HintDb] command for rewrite\n  databases, so we have to create it by adding a fake entry. *)\nHint Rewrite injective_projections using fail : lift.\n\n\n(** ** Simplifying occurences of [lift] *)\n\n(** Once everything is stated in terms of lift, futher rewriting rules\n  from the [lift_simpl] database can be applied. In particular, the\n  theorems below try to ensure that the goal and hypotheses are stated\n  in terms of [get] and [same_context] rather than in terms of [lift]. *)\n\nLtac lift_simpl :=\n  repeat progress (lift_norm; autorewrite with lift_simpl in *; lens_simpl).\n\nSection LIFTOPTION.\n  Context {S V} `{HSV: Lens S V}.\n\n  Lemma lift_option_eq_unlift (f: V -> option V) (s s': S):\n    lift π f s = Some s' ->\n    f (π s) = Some (π s').\n  Proof.\n    unfold lift; simpl.\n    intros.\n    destruct (f (π s)); try discriminate.\n    inversion H.\n    autorewrite with lens.\n    reflexivity.\n  Qed.\n\n  Theorem lift_option_eq_same_context (f: V -> option V) (s s': S):\n    lift π f s = Some s' ->\n    same_context π s s'.\n  Proof.\n    unfold lift; simpl.\n    case (f (π s)).\n    * intros ? H; inversion H; subst.\n      symmetry.\n      apply lens_set_same_context.\n    * discriminate.\n  Qed.\n\n  Theorem lift_option_eq_intro (f: V -> option V) (s s': S):\n      same_context π s s' ->\n      f (π s) = Some (π s') ->\n      lift π f s = Some s'.\n  Proof.\n    intros Hc Hv.\n    unfold lift; simpl.\n    rewrite Hv; clear Hv.\n    f_equal.\n    rewrite Hc.\n    apply lens_set_get.\n  Qed.\n\n  Theorem lift_option_eq_iff f s s' `{!Lens π}:\n    lift π f s = Some s' <->\n    f (π s) = Some (π s') /\\ same_context π s s'.\n  Proof.\n    repeat split.\n    - apply lift_option_eq_unlift.\n      assumption.\n    - eapply lift_option_eq_same_context.\n      eassumption.\n    - intros [Hf Hc].\n      eapply lift_option_eq_intro;\n      assumption.\n  Qed.\nEnd LIFTOPTION.\n\nSection LIFTPROD.\n  Context {S V} `{Hgs: Lens S V} {A: Type}.\n\n  Theorem lift_prod_eq_unlift (f: V -> V * A) (s s': S) (a: A):\n    lift π f s = (s', a) ->\n    f (π s) = (π s', a).\n  Proof.\n    unfold lift; simpl.\n    destruct (f (π s)) as [v' a'].\n    intros H.\n    inversion H.\n    autorewrite with lens.\n    reflexivity.\n  Qed.\n\n  Theorem lift_prod_eq_same_context (f: V -> V * A) (s s': S) (a: A):\n    lift π f s = (s', a) ->\n    same_context π s s'.\n  Proof.\n    unfold lift; simpl.\n    destruct (f (π s)).\n    intro H; inversion H; subst.\n    symmetry.\n    apply lens_set_same_context.\n  Qed.\n\n  Theorem lift_prod_eq_intro (f: V -> V * A) (s s': S) (a: A):\n    same_context π s s' ->\n    f (π s) = (π s', a) ->\n    lift π f s = (s', a).\n  Proof.\n    unfold lift; simpl.\n    intros Hc Hv.\n    destruct (f (π s)) as [v'].\n    inversion Hv; subst; clear Hv.\n    rewrite Hc; clear Hc.\n    autorewrite with lens.\n    reflexivity.\n  Qed.\n\n  Theorem lift_prod_eq_iff (f: V -> V * A) (s s': S) (a: A):\n    lift π f s = (s', a) <->\n    f (π s) = (π s', a) /\\ same_context π s s'.\n  Proof.\n    repeat split.\n    - apply lift_prod_eq_unlift.\n      assumption.\n    - eapply lift_prod_eq_same_context.\n      eassumption.\n    - intros [Hf Hc].\n      apply lift_prod_eq_intro;\n      assumption.\n  Qed.\nEnd LIFTPROD.\n\nSection LIFTREL.\n  Context {S V} `{Lens S V}.\n\n  Global Instance lift_relation_unlift (R: relation V):\n    subrelation (lift π R) (R @@ π)%signature.\n  Proof.\n    unfold lift, RelCompFun; simpl.\n    intros s1 s2 Hs.\n    inversion Hs.\n    autorewrite with lens.\n    assumption.\n  Qed.\n\n  Global Instance lift_relation_same_context (R: relation V):\n    subrelation (lift π R) (same_context π).\n  Proof.\n    unfold lift; simpl.\n    intros s1 s2 Hs.\n    inversion Hs.\n    autorewrite with lens.\n    reflexivity.\n  Qed.\n\n  Lemma lift_relation_intro (R: V -> V -> Prop) (s1 s2: S):\n    same_context π s1 s2 ->\n    R (π s1) (π s2) ->\n    lift (Lift := lift_powerset) π R s1 s2.\n  Proof.\n    intros Hc Hv.\n    unfold lift; simpl.\n    replace s2 with (set π (π s2) s1).\n    * change (set π (π s2) s1) with ((fun v => set π v s1) (π s2)).\n      eapply powerset_fmap_intro.\n      assumption.\n    * rewrite Hc.\n      autorewrite with lens.\n      reflexivity.\n  Qed.\n\n  Lemma lift_relation_iff (R: V -> V -> Prop) (s1 s2: S):\n    lift π R s1 s2 <->\n    R (π s1) (π s2) /\\ same_context π s1 s2.\n  Proof.\n    repeat split.\n    - apply lift_relation_unlift.\n      assumption.\n    - eapply lift_relation_same_context.\n      eassumption.\n    - intros [Hv Hc].\n      apply lift_relation_intro;\n      assumption.\n  Qed.\nEnd LIFTREL.\n\nHint Rewrite\n  @lift_option_eq_iff\n  @lift_prod_eq_iff\n  @lift_relation_iff\n  using typeclasses eauto : lift_simpl.\n\n\n(** ** Solving the residual goals *)\n\n(** The rewriting rules above likely leaves us with several conjunctions.\n  We destruct them to make sure that the components are readily available. *)\n\nLtac split_conjuncts :=\n  repeat match goal with\n           | [ H: _ /\\ _ |- _ ] =>\n             let Hl := fresh H \"l\" in\n             let Hr := fresh H \"r\" in\n             destruct H as [Hl Hr]\n         end.\n\n(** Hopefully, the residual goal can then easily be solved with\n  [eauto], given a few hints in the \"lift\" database which we use to\n  solve corner cases. *)\nHint Extern 10 (eq _ _) =>\n  congruence : lift.\n\n(* Use the minimal priority, because we want to use [same_context] as\n  a side-condition for some immediate hints. *)\nHint Extern 0 (same_context _ _ _) =>\n  congruence || reflexivity : lift.\n\n(** As a last resort, we unfold [lift] and try to normalize the\n  result. Hopefully we'll get something easily solvable. *)\nLtac lift_unfold :=\n  repeat progress (lift_simpl; unfold lift in *).\n\n(** We're now ready to define our leaf tactic, and use it in\n  conjunction with [peel] to solve the goals automatically. *)\nLtac lift_auto :=\n  lift_simpl;\n  split_conjuncts;\n  eauto 10 with lift typeclass_instances;\n  lift_unfold;\n  eauto 10 with lift typeclass_instances.\n\n(** The [lift_partial] variant allows for some unsolved leaves. *)\nLtac lift_partial π f :=\n  pose proof f as Hf;\n  lift_peel π Hf lift_auto.\n\n(** The [lift] variant demands 100% success *)\nLtac lift π f :=\n  now lift_partial π f.\n\n\n(** ** Properties of lifted operations *)\n\n(** Lifting commutes with lens composition *)\n\nSection COMPOSE.\n  Existing Instances lens_compose compose_lensops.\n  Context {A B C} (π: A -> B) (ρ: B -> C) `{Hπ: Lens _ _ π} `{Hρ: Lens _ _ ρ}.\n  Context `{HF: Functor}.\n  Context (f: C -> F C).\n\n  Lemma lift_compose:\n    lift (compose ρ π) f = lift π (lift ρ f).\n  Proof.\n    unfold lift.\n    simpl.\n    apply functional_extensionality.\n    intros a.\n    unfold Basics.compose.\n    reflexivity.\n  Qed.\nEnd COMPOSE.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/liblayers/lib/Lift.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.26173846153682745}}
{"text": "Require Import List.\nRequire Import Coq.Lists.ListSet.\nImport ListNotations.\nRequire Import Omega.\nRequire Import Coq.Program.Equality.\n\nRequire Import Stream.\nRequire Import Unify.\nRequire Import MiniKanrenSyntax.\nRequire Import DenotationalSem.\nRequire Import OperationalSem.\n\n\nModule OperationalSemSoundnessAbstr (CS : ConstraintStoreSig).\n\nImport CS.\n\nModule OperationalSemCS := OperationalSemAbstr CS.\n\nImport OperationalSemCS.\n\nLemma answer_correct\n      (s : subst)\n      (cs : constraint_store s)\n      (n : nat)\n      (f : repr_fun)\n      (DSS : [ s , f ])\n      (DSCS : [| s , cs , f |])\n      (st' : state')\n      (st : state)\n      (EV : eval_step st' (Answer s cs n) st) :\n      in_denotational_sem_state' st' f.\nProof.\n  remember (Answer s cs n) as l.\n  induction EV; good_inversion Heql; simpl_existT_cs_same; auto.\n  { assert (DSS_copy := DSS). apply (denotational_sem_uni _ _ _ _ MGU _) in DSS.\n    destruct DSS as [DSS EQ]. constructor; auto.\n    eapply proj1. apply (upd_cs_success_condition _ _ _ _ UPD_CS f). auto. }\n  { specialize (add_constraint_success_condition _ _ _ _ _ ADD_C f). intro ADD_C_COND.\n    specialize (conj DSCS DSS). intro CONJ. apply ADD_C_COND in CONJ.\n    destruct CONJ as [DSCS0 [_ GT_NEQ]].\n    constructor; auto. }\nQed.\n\nLemma next_state_correct\n      (f : repr_fun)\n      (st : state)\n      (DSS : in_denotational_sem_state st f)\n      (st' : state')\n      (WF : well_formed_state' st')\n      (h : label)\n      (EV : eval_step st' h st) :\n      in_denotational_sem_state' st' f.\nProof.\n  induction EV; good_inversion DSS.\n  { good_inversion DSST'; good_inversion DSST'0; simpl_existT_cs_same;\n    constructor; auto. }\n  { good_inversion DSST'. good_inversion DSST'0. simpl_existT_cs_same. auto. }\n  { good_inversion WF. good_inversion DSST'. simpl_existT_cs_same.\n    constructor; auto. econstructor; eauto.\n    intros HIn. apply FV_LT_COUNTER in HIn.\n    { omega. }\n    { reflexivity. } }\n  { good_inversion DSST'. simpl_existT_cs_same. auto. }\n  { auto. }\n  { good_inversion WF. good_inversion DSST'; auto. }\n  { good_inversion DSST'. constructor; auto.\n    simpl_existT_cs_same. eapply answer_correct; eauto. }\n  { good_inversion WF. good_inversion DSST'. auto. }\n  { good_inversion WF. good_inversion DSST'.\n    { good_inversion DSST'0. simpl_existT_cs_same.\n      constructor; auto.\n      eapply answer_correct; eauto. }\n    { good_inversion DSST'0. auto. } }\nQed.\n\nLemma search_correctness_generalized\n      (st   : state)\n      (WF   : well_formed_state st)\n      (f    : repr_fun)\n      (t    : trace)\n      (HOP  : op_sem st t)\n      (HDA  : {| t , f |}) :\n      in_denotational_sem_state st f.\nProof.\n  revert HOP WF. revert st.\n  red in HDA. destruct HDA as [s [cs [n [HInStr [DSS DSCS]]]]].\n  remember (Answer s cs n) as l. induction HInStr.\n  { intros. inversion HOP; clear HOP; subst.\n    constructor. eapply answer_correct; eauto. }\n  { specialize (IHHInStr Heql). intros.\n    inversion HOP; clear HOP; subst.\n    inversion WF; clear WF; subst.\n    specialize (well_formedness_preservation _ _ _ EV wfState).\n    intro wf_st0.\n    specialize (IHHInStr st0 OP wf_st0).\n    constructor. eapply next_state_correct; eauto. }\nQed.\n\nFixpoint first_nats (k : nat) : list nat :=\n  match k with\n  | 0   => []\n  | S n => n :: first_nats n\n  end.\n\nLemma first_nats_less\n      (n k : nat)\n      (H : In n (first_nats k)) :\n      n < k.\nProof.\n  induction k.\n  { inversion H. }\n  { inversion H. { omega. } { apply IHk in H0. omega. } }\nQed.\n\nLemma search_correctness\n      (g   : goal)\n      (k   : nat)\n      (HC  : closed_goal_in_context (first_nats k) g)\n      (f   : repr_fun)\n      (t   : trace)\n      (HOP : op_sem (State (Leaf g empty_subst init_cs k)) t)\n      (HDA : {| t , f |}) :\n      [| g , f |].\nProof.\n  remember (State (Leaf g empty_subst init_cs k)) as st.\n  assert (in_denotational_sem_state st f).\n  { eapply search_correctness_generalized; eauto.\n    subst. constructor. apply well_formed_initial_state; auto. }\n  subst. inversion H. inversion DSST'. auto.\nQed.\n\nEnd OperationalSemSoundnessAbstr.\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/OpSemSoundness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.26173846153682745}}
{"text": "Require Import LibTactics.\nRequire Import Metalib.Metatheory.\nRequire Import syntax_ott\n               rules_inf.\n\nRequire Import List. Import ListNotations.\nRequire Import Strings.String.\n\n\nDefinition irred e : Prop := forall b, ~(step e b).\nDefinition cirred e : Prop := forall b, ~(cstep e b).\n\n\n\nNotation \"Γ ⊢ E ⇒ A\" := (Typing Γ E Inf A) (at level 45).\nNotation \"Γ ⊢ E ⇐ A\" := (Typing Γ E Chk A) (at level 45).\n\n\nNotation \"[ z ~> u ] e\" := (subst_exp u z e) (at level 0).\nNotation \"t ^^ u\"       := (open_exp_wrt_exp t u) (at level 67).\nNotation \"e ^ x\"        := (open_exp_wrt_exp e (e_var_f x)).\n\nNotation \"v ~-> A v'\" := (TypedReduce v A v') (at level 68).\n\nNotation \"t ->* r\" := (steps t r) (at level 68). \n\n\nLemma star_one:\nforall a b, cstep a (Expr b) -> steps a (Expr b).\nProof.\neauto using steps.\nQed.\n\nLemma star_trans:\nforall a b, steps a (Expr b) -> forall c, steps b (Expr c) -> steps a (Expr c).\nProof.\n  introv H.\n  inductions H; eauto using steps.\nQed.\n\n\nHint Resolve star_one star_trans : core.\n\n\n\n\n(** [x # E] to be read x fresh from E captures the fact that\n    x is unbound in E . *)\n\nNotation \"x '#' E\" := (x \\notin (dom E)) (at level 67) : env_scope.\n\nDefinition env := list (atom * exp).\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 : list (var * typ) => dom x) in\n  let D := gather_atoms_with (fun x : exp => fv_exp x) in\n  let E := gather_atoms_with (fun x : ctx => dom x) in\n  let F := gather_atoms_with (fun x : env => dom x) in\n  constr:(A `union` B `union` C `union` D `union` F).\n\n\n\n\nLemma value_lc : forall v,\n    value v -> lc_exp v.\nProof.\n  intros v H.\n  induction* H.\n  eapply lc_e_save.\n  inverts* H. \nQed.\n\n\n\nLemma step_not_value: forall (v:exp),\n    value v -> irred v.\nProof.\n  introv.\n  unfold irred.\n  inductions v; introv H;\n  inverts* H;\n  unfold not;intros.\n  - inverts* H.\n    destruct E; unfold simpl_fill in H0; inverts* H0.\n    destruct E; unfold simpl_fill in H0; inverts* H0.\n    destruct E; unfold simpl_fill in H0; inverts* H0.\n  - inverts* H.\n    destruct E; unfold simpl_fill in H0; inverts* H0.\n    destruct E; unfold simpl_fill in H0; inverts* H0.\n    destruct E; unfold simpl_fill in H0; inverts* H0.\n  - inverts* H.\n    destruct E; unfold simpl_fill in H0; inverts* H0.\n    destruct E; unfold simpl_fill in H0; inverts* H0.\n    destruct E; unfold simpl_fill in H0; inverts* H0.\nQed.\n\nLemma cstep_not_value: forall (v:exp),\n    value v -> cirred v.\nProof.\n  introv.\n  unfold cirred.\n  inductions v; introv H;\n  inverts* H;\n  unfold not;intros.\n  - inverts* H.\n    destruct E; unfold simpl_fill in H0; inverts* H0.\n  - inverts* H.\n    destruct E; unfold simpl_fill in H0; inverts* H0.\n  - inverts* H.\n    destruct E; unfold simpl_fill in H0; inverts* H0.\nQed.\n\n\nLemma multi_red_app : forall v t t',\n    vvalue v -> t ->* (Expr t') -> (e_app v t) ->* (Expr (e_app v t')).\nProof.\n  introv Val Red.\n  inductions Red; eauto.\n  forwards*: IHRed.\n  assert(simpl_wf (sappCtxR v)). eauto.\n  forwards*: cdo_step H1 H.\nQed.\n\nLemma multi_red_app2 : forall t1 t2 t1',\n    lc_exp t2 -> t1 ->* (Expr t1') -> (e_app t1 t2) ->* (Expr (e_app t1' t2)).\nProof.\n  introv Val Red.\n  inductions Red; eauto.\n  assert(simpl_wf (sappCtxL t2)). eauto.\n  forwards*: cdo_step H0 H.\nQed.\n\nLemma multi_red_add : forall v t t',\n    vvalue v -> t ->* (Expr t') -> (e_add v t) ->* (Expr (e_add v t')).\nProof.\n  introv Val Red.\n  inductions Red; eauto.\n  forwards*: IHRed.\n  assert(simpl_wf (saddCtxR v)). eauto.\n  forwards*: cdo_step H1 H.\nQed.\n\nLemma multi_red_add2 : forall t1 t2 t1',\n    lc_exp t2 -> t1 ->* (Expr t1') -> (e_app t1 t2) ->* (Expr (e_app t1' t2)).\nProof.\n  introv Val Red.\n  inductions Red; eauto.\n  assert(simpl_wf (sappCtxL t2)). eauto.\n  forwards*: cdo_step H0 H.\nQed.\n\n\n\n", "meta": {"author": "ecoop2021", "repo": "ecoop2021", "sha": "ac37600a0839fe72d7be26dad40d8293f929c1c2", "save_path": "github-repos/coq/ecoop2021-ecoop2021", "path": "github-repos/coq/ecoop2021-ecoop2021/ecoop2021-ac37600a0839fe72d7be26dad40d8293f929c1c2/coq/Variant/Infrastructure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2617384615368274}}
{"text": "Require Import Coq.omega.Omega.\nRequire Import Bedrock.DepList Platform.AutoSep Platform.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 Coq.Arith.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 Coq.Arith.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 Platform.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": "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/Bootstrap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2617384615368274}}
{"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.\nRequire Export Wf_nat.\nRequire Export Compare_dec.\n\nRequire Import Term_const.\n\nFixpoint div2 (n : nat) : nat :=\n  match n with\n  | S (S p) => S (div2 p)\n  | _ => 0\n  end.\n\nParameter div2_lt : forall x : nat, div2 (S x) < S x.\n\nRecursive Definition log (nat -> nat) lt lt_wf div2_lt\n (forall x : nat,\n  log x = match x with\n          | O => 0\n          | S O => 0\n          | S (S y) => S (log (div2 x))\n          end).\n\nInspect 5.\n(* Pour tester pas-à-pas:\n\nDefinition log_nat :=\n    [log:nat -> nat] [x:nat]\n    (Cases x of\n        O => (0)\n      | (S O) => (O)\n      | (S (S y)) => (S (log (div2 (S (S y)))))\n     end).\n\nL_Terminate log_nat nat lt lt_wf log_term div2_lt.\n\nDefine_from_terminate log nat log_term.\n\nMake_equation log_equation log_nat log log_term\n  (x:nat)(log x)=\n\t(Case (le_gt_dec x (1)) of [h:?] O [h:?] (S (log (div2 x))) end).\n\n\n *)", "meta": {"author": "coq-contribs", "repo": "recursive-definition", "sha": "2f6e9b0ca0dbd1470bff286d0712ec2b8ece6d4f", "save_path": "github-repos/coq/coq-contribs-recursive-definition", "path": "github-repos/coq/coq-contribs-recursive-definition/recursive-definition-2f6e9b0ca0dbd1470bff286d0712ec2b8ece6d4f/data6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.5, "lm_q1q2_score": 0.261710174468162}}
{"text": "Require Import msl.base.\nRequire Import msl.ageable.\nRequire Import msl.sepalg.\nRequire Import msl.sepalg_generators.\nRequire Import msl.age_sepalg.\nRequire Import msl.predicates_hered.\nRequire Import msl.predicates_sl.\nRequire Import msl.subtypes.\n\nLocal Open Scope pred.\n\n\nLemma unfash_derives {A} `{agA : ageable A}:\n  forall {P Q}, (P |-- Q) -> @derives A _ (! P) (! Q).\nProof.\nintros. intros w ?. simpl in *. apply H. auto.\nQed.\n\nLemma subp_sepcon {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A} : forall G P P' Q Q',\n  G |-- P >=> P' ->\n  G |-- Q >=> Q' ->\n  G |-- P * Q >=> P' * Q'.\nProof.\n  pose proof I.\n  repeat intro.\n  specialize (H0 _ H2).\n  specialize (H1 _ H2).\n  clear G H2.\n  destruct H5 as [w1 [w2 [? [? ?]]]].\n  exists w1; exists w2; split; auto.\n  split.\n  eapply H0; auto.\n  assert (level w1 = level a').\n  apply comparable_fashionR.  eapply join_sub_comparable; eauto.\n apply necR_level in H4. omega.\n  eapply H1; auto.\n  assert (level w2 = level a').\n  apply comparable_fashionR. eapply join_sub_comparable; eauto.\n apply necR_level in H4. omega.\nQed.\n\nLemma sub_wand {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A} : forall G P P' Q Q',\n  G |-- P' >=> P ->\n  G |-- Q >=> Q' ->\n  G |-- (P -* Q) >=> (P' -* Q').\nProof.\n  pose proof I.\n  repeat intro.\n  specialize (H0 _ H2); specialize (H1 _ H2); clear G H2; pose (H2:=True).\n  eapply H0 in H8; try apply necR_refl.\n  eapply H1; try apply necR_refl.\n  apply necR_level in H4. apply necR_level in H6. apply join_comparable in H7.\n  apply comparable_fashionR in H7. unfold fashionR in H7. omega.\n  eapply H5; eauto.\n  apply necR_level in H4. apply necR_level in H6.\n   apply join_comparable2 in H7.\n  apply comparable_fashionR in H7. unfold fashionR in H7. omega.\nQed.\n\nLemma find_superprecise {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A}:\n   forall Q, Q |-- EX P:_, P && !(P >=> Q) && !!superprecise (P).\nProof.\nintros.\nintros w ?.\nexists (exactly w).\nsplit; auto.\nsplit; auto.\nhnf; apply necR_refl.\nintros w' ? w'' ? ?.\nhnf in H2.\napply pred_nec_hereditary with w; auto.\ndo 3 red.\napply superprecise_exactly.\nQed.\n\nLemma sepcon_subp' {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A}:\n  forall (P P' Q Q' : pred A) (st: nat),\n    (P >=> P') st ->\n    (Q >=> Q') st ->\n    (P * Q >=> P' * Q') st.\nProof.\n pose proof I.\nintros.\nintros w' ? w'' ? [w1 [w2 [? [? ?]]]].\ndestruct (nec_join4 _ _ _ _ H4 H3) as [w1' [w2' [? [? ?]]]].\nexists w1; exists w2; repeat split; auto.\neapply (H0 w1'); eauto.\nsimpl in *.\nsubst.\nreplace (level w1') with (level w'); auto.\nsymmetry; apply comparable_fashionR; eapply join_comparable; eauto.\neapply (H1 w2'); eauto.\nreplace (level w2') with (level w'); auto.\nsymmetry. apply comparable_fashionR.\neapply join_comparable; eauto.\nQed.\n\nLemma subp_refl'  {A} `{agA : ageable A} :  forall (Q: pred A) (st: nat), (Q >=> Q) st.\nProof.\nintros.\nintros ? ? ? ?; auto.\nQed.\n\nLemma subp_trans' {A} `{agA : ageable A}:\n  forall (B C D: pred A) (w: nat), (B >=> C)%pred w -> (C >=> D)% pred w -> (B >=> D)%pred w.\nProof.\nintros.\nintros w' ? w'' ? ?.\neapply H0; eauto.\neapply H; eauto.\nQed.\n\nLemma andp_subp'  {A} `{agA : ageable A} :\n forall (P P' Q Q': pred A) (w: nat), (P >=> P') w -> (Q >=> Q') w -> (P && Q >=> P' && Q') w.\nProof.\nintros.\nintros w' ? w'' ? [? ?]; split.\neapply H; eauto.\neapply H0; eauto.\nQed.\n\nLemma allp_subp' {A} `{agA : ageable A}: forall T (F G: T -> pred A) (w: nat),\n   (forall x,  (F x >=> G x) w) -> (allp (fun x:T => (F x >=> G x)) w).\nProof.\nintros.\nintro x; apply H; auto.\nQed.\n\n\nLemma pred_eq_e1 {A} `{agA : ageable A}: forall (P Q: pred A) w,\n       ((P <=> Q) w -> (P >=> Q) w).\nProof.\nintros.\nintros w' ? w'' ? ?.\neapply H; eauto.\nQed.\n\nLemma pred_eq_e2 {A} `{agA : ageable A}: forall (P Q: pred A)  w,\n     ((P <=> Q) w -> (Q >=> P) w).\nProof.\nProof.\nintros.\nintros w' ? w'' ? ?.\neapply H; eauto.\nQed.\n\nHint Resolve @sepcon_subp'.\nHint Resolve @subp_refl'.\nHint Resolve @andp_subp'.\nHint Resolve @allp_subp'.\nHint Resolve @derives_subp.\nHint Resolve @pred_eq_e1.\nHint Resolve @pred_eq_e2.\n\n\nLemma allp_imp2_later_e2 {B}{A}{agA: ageable A}:\n   forall (P Q: B -> pred A) (y: B) ,\n      (ALL x:B, |> P x <=> |> Q x) |-- |> Q y >=> |> P y.\nProof.\n  intros.  intros w ?. specialize (H y). apply pred_eq_e2. auto.\nQed.\nLemma allp_imp2_later_e1 {B}{A}{agA: ageable A}:\n   forall (P Q: B -> pred A) (y: B) ,\n      (ALL x:B, |> P x <=> |> Q x) |-- |> P y >=> |> Q y.\nProof.\n  intros.  intros w ?. specialize (H y). apply pred_eq_e1. auto.\nQed.\n\n(*\nLemma subp_later {A} `{agA:  ageable A} (SS: natty A):\n forall (P Q: pred A), |> (P >=> Q) |-- |> P >=> |> Q.\nProof.\nintros.\nrewrite later_fash; auto.\napply fash_derives.\napply axiomK.\nQed.\n*)\n\nLemma extend_unfash {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A} : forall (P: pred nat), boxy extendM (! P).\nProof.\nintros.\napply boxy_i; auto; intros.\nunfold unfash in *.\nsimpl in H. destruct H.\nhnf in H0|-*.\nreplace (level w') with (level w); auto.\napply comparable_fashionR.\neapply join_comparable; eauto.\nQed.\n\nHint Resolve @extend_unfash.\n\nLemma subp_unfash {A} `{Age_alg A}:\n  forall (P Q : pred nat) (n: nat), (P >=> Q) n -> ( ! P >=> ! Q) n.\nProof.\nintros.\nintros w ?. specialize (H0 _ H1).\nintros w' ? ?. apply (H0 _ (necR_level' H2)).\nauto.\nQed.\nHint Resolve @subp_unfash.\n\n\nLemma unfash_sepcon_distrib:\n        forall {T}{agT: ageable T}{JoinT: Join T}{PermT: Perm_alg T}{SepT: Sep_alg T}{AgeT: Age_alg T}\n           (P: pred nat) (Q R: pred T),\n               unfash P && (Q*R) = (unfash P && Q) * (unfash P && R).\nProof.\nintros.\napply pred_ext.\nintros w [? [w1 [w2 [? [? ?]]]]].\nexists w1; exists w2; repeat split; auto.\napply join_level in H0. destruct H0.\nhnf in H|-*. congruence.\napply join_level in H0. destruct H0.\nhnf in H|-*. congruence.\nintros w [w1 [w2 [? [[? ?] [? ?]]]]].\nsplit.\napply join_level in H. destruct H.\nhnf in H0|-*. congruence.\nexists w1; exists w2; repeat split; auto.\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/msl/subtypes_sl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.5, "lm_q1q2_score": 0.261710174468162}}
{"text": "(* Declare ML Module \"plugin\". *)\n\n(*\nDeclare ML Module \"extlib\".\nDeclare ML Module \"reif\".\n\nSection PartialApply.\n\n  Fixpoint funtype (ls : list Type) (r : Type) : Type :=\n    match ls with\n      | nil => r\n      | cons a b => a -> funtype b r\n    end.\n\n  Fixpoint apply_ls (ls : list Type) (T : Type) (R : T -> Type) (V : T)\n    : funtype ls (forall x : T, R x) -> funtype ls (R V) :=\n    match ls with\n      | nil => fun F => F V\n      | cons a b => fun F => fun x : a => apply_ls b T R V (F x)\n    end.\nEnd PartialApply.\n\nRequire Import List.\n\nLtac refl_app cc e :=\n  match e with\n    | (fun _ => _) =>\n      let rec getTypes As :=\n        match As with\n          | tt => constr:(@nil Type)\n          | (?A, ?B) =>\n            match type of A with\n              | _ -> ?TT =>\n                let r := getTypes B in\n                constr:((TT : Type) :: r)\n            end\n        end\n      in\n      let rec papply cc F T Tb Ts As :=\n        match T with\n          | ?T1 -> ?TT =>\n            match Ts with\n              | ?T :: ?T' =>\n                match As with\n                  | (?A, ?A') =>\n                    let cc' f Ts As :=\n                      let Ts' := constr:((T : Type) :: Ts) in\n                      let As' := constr:((A, As)) in\n                      cc f Ts' As'\n                    in\n                    let Tb := constr:((T:Type) :: Tb) in\n                    papply cc' F TT Tb T' A'\n                end\n            end\n          | forall x : ?T1, @?T2 x =>\n            match Ts with\n              | _ :: ?T' =>\n                match As with\n                  | ((fun _ => ?A), ?A') =>\n                    let TT' := eval simpl in (T2 A) in\n                    let f' := eval simpl in (@apply_ls Tb T1 T2 A F) in\n                    papply cc f' TT' Tb T' A'\n                end\n            end\n          | _ =>\n            cc F Ts As\n        end\n      in\n      match e with\n        | fun x => ?F (@?A x) (@?B x) (@?C x) (@?D x) (@?E x) =>\n          let As := constr:((A,(B,(C,(D,(E,tt)))))) in\n          let Ts := getTypes As in\n          let Tf := type of F in\n          let Tb := constr:(@nil Type) in\n          papply cc F Tf Tb Ts As\n        | fun x => ?F (@?A x) (@?B x) (@?C x) (@?D x) =>\n          let As := constr:((A,(B,(C,(D,tt))))) in\n          let Ts := getTypes As in\n          let Tf := type of F in\n          let Tb := constr:(@nil Type) in\n          papply cc F Tf Tb Ts As\n        | fun x => ?F (@?A x) (@?B x) (@?C x) =>\n          let As := constr:((A,(B,(C,tt)))) in\n          let Ts := getTypes As in\n          let Tf := type of F in\n          let Tb := constr:(@nil Type) in\n          papply cc F Tf Tb Ts As\n        | fun x => ?F (@?A x) (@?B x) =>\n          let As := constr:((A,(B,tt))) in\n          let Ts := getTypes As in\n          let Tf := type of F in\n          let Tb := constr:(@nil Type) in\n          papply cc F Tf Tb Ts As\n        | fun x => ?F (@?A x) =>\n          let As := constr:((A,tt)) in\n          let Ts := getTypes As in\n          let Tf := type of F in\n          let Tb := constr:(@nil Type) in\n          papply cc F Tf Tb Ts As\n        | fun x => ?F =>\n          let As := constr:(tt) in\n          let Ts := getTypes As in\n          let Tf := type of F in\n          let Tb := constr:(@nil Type) in\n          papply cc F Tf Tb Ts As\n      end\n    | _ =>\n      let rec refl cc e As :=\n        match e with\n          | ?A ?B =>\n            let Ta := type of A in\n            match Ta with\n              | _ -> ?TT =>\n                let As := constr:((B, As)) in\n                let Tb := type of B in\n                let cc f Ts args :=\n                  let Ts' := constr:(List.app Ts (cons (Tb : Type) nil)) in\n                  cc f Ts' args\n                in\n                refl cc A As\n              | forall x : ?T1, @?T2 x =>\n                let cc f Ts args :=\n                  let Tb  := type of B in\n                  let f'  := eval simpl in (@apply_ls Ts T1 T2 B f) in\n                  cc f' Ts args\n                in\n                refl cc A As\n              end\n          | _ =>\n            let Ts := constr:(@nil Type) in\n            cc e Ts As\n        end\n        in\n        let b := constr:(tt) in\n        refl cc e b\n  end.\n\n\nLtac cc1 x ts args :=\n  idtac \"$$$ plugin\" x ts args.\nLtac cc2 x ts args :=\n  idtac \"$$$ ltac\" x ts args.\n\nDefinition tutu (x : Type) ( y : x ) (s : Type) (z : nat) (z2 : nat) (u : x) := 1.\nGoal tutu bool true nat 3 3  false = 2.\n  match goal with\n      |- ?l = _ =>  refl_app_cps l cc1\n  end.\n  match goal with\n      |- ?l = _ =>  refl_app cc2 l\n  end.\nAbort.\n\nDefinition bar : forall ( x: Type), nat -> forall (y : Type), x -> y -> x := fun _ _ _ e _ => e.\n\nDefinition bar2 : forall ( x: Type), nat -> forall (y : Type), nat -> forall (z : Type),  x -> y -> z -> z. Admitted.\n\nGoal forall a b c d e, bar a b c d e = d.\nintros.\n  match goal with\n      |- ?l = _ => refl_app_cps l cc1\n  end.\n  match goal with\n      |- ?l = _ =>  refl_app cc2 l\n  end.\nAbort.\n\nGoal forall Hx Hy Hz a b c d e, bar2 Hx a Hy b Hz c d e = e.\nintros.\nmatch goal with\n    |- ?l = _ => refl_app_cps l cc1\nend.\nmatch goal with\n    |- ?l = _ =>  refl_app cc2 l\nend.\n\nAbort.\n\n\nGoal (fun x => x + x) = (fun x => 2).\nmatch goal with\n    |- ?l = _ => refl_app_cps l cc1\nend.\nmatch goal with\n    |- ?l = _ =>  refl_app cc2 l\nend.\nAbort.\n\nVariable A B : Type.\nDefinition test1 (stn : A) (sm : B) : B. Admitted.\nGoal  forall a b, test1 a b = b. intros.\nmatch goal with |- ?l = _  => refl_app_cps l cc1 end.\nmatch goal with |- ?l = _  => refl_app cc2 l end.\nAbort.\n\nDefinition test2 : A * B -> B. Admitted.\nGoal  (fun x y => test2 (x, y)) = (fun _ b => b). intros.\nmatch goal with |- ?l = _  => refl_app cc2 l end.\nmatch goal with |- ?l = _  => refl_app_cps l cc1 end.\nAbort.\nRequire Import String.\nRequire Bedrock. Require ReifyExpr.\nDefinition test_dep_0 (n : nat) (arg : bool) := True.\nDefinition test_dep (n : nat) (arg : bool) := n = 0 -> arg = arg.\nGoal True.\nreify_expr (test_dep_0 1 true).\nreify_expr (test_dep 1 true).\nAbort.\n(* Require Bedrock. Require ReifyExpr.  *)\n(* Goal True.  *)\n(* reify_expr (forall (x : bool), x = x).  *)\n(* reify_expr (1). *)\n(* reify_expr (fun (x : nat )=> x).  *)\n(* reify_expr (1 + 3).  *)\n(* reify_expr (1 + 3 = 2 + 2).  *)\n(* reify_expr (not (1 + 3 = 2 + 2)).  *)\n(* reify_expr (not (1 + 3 = 2 + 2)).  *)\n(* reify_expr ((1 + 3 = 2 + 2) -> False).  *)\n(* (* Time reify_expr ((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 +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 +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 +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 +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 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 + 3 = 2 + 2) -> False).  *) *)\n(* reify_expr (fun n => n + n = n + n).  *)\n(* reify_expr (fun x => negb (negb x) = x). *)\n(* Abort.  *)\n(* Require Import Bedrock.SepIL. Import SEP.  *)\n(* Locate SEP.Emp.  *)\n(* Axiom types : list Type.  *)\n(* Axiom pc : Type.  *)\n(* Notation \"a * b\" := (@star pc pc types  a b) (only parsing).  *)\n(* Notation \"0\" := (@emp pc pc types ) (only parsing).  *)\n(* Notation \"'Ex' x , p\" := (@ex pc pc types _ (fun x => p)). *)\n(* Notation \"'Ex' x : T , p\" := (@ex pc pc types T (fun x => p)) . *)\n(* Notation \"[| P |]\" := (@inj pc pc types (@PropX.Inj pc pc types  P )).  *)\n(* Require Import IL.  *)\n(* Variable st : state.  *)\n(* Goal True.  *)\n(* reify_expr (Regs st Rp). *)\n(* reify_sexpr (0 ).  *)\n(* reify_sexpr (0 * 0 * 0).  *)\n(* reify_sexpr ( [| 1 + 1 = 2 |] * 0 * [| 12 = 6 + 6 |] ). *)\n(* reify_sexpr ( [| 1 + 1 = 2 |] * 0 * [| 12 = 6 + 6 |] ).  *)\n(* reify_sexpr ( Ex x, [| x = 1|]).  *)\n(* reify_sexpr ( Ex x, Ex y, Ex z, [| x = y + z|]).  *)\n(* reify_sexpr ( Ex x, [| x = 1|]).  *)\n(* reify_sexpr ( Ex x : bool, Ex y, Ex z, [| (if x then 1 else 2) = y + z|]).  *)\n(* reify_sexpr ( Ex x: bool, [| (if x then true else false) = x|]).  *)\n(* reify_sexpr ( Ex x:bool, Ex y : bool, [| (if x then y else false) = andb x y|]).  *)\n(* reify_sexpr ( Ex x:bool, Ex y : nat, [| (if x then y else y) = y|]).  *)\n(* Fail reify_sexpr (Ex x : (bool -> bool), [| x true = false |]).  *)\n(* evar (x : nat); let s := eval simpl in (Ex y : nat, [|x = y|] * [| S x = S y|]) in reify_sexpr s ; clear x.   *)\n(* Abort.  *)\n\n(* Goal forall P,    *)\n(*        P( Ex x : bool, [|negb (negb x) = false |]). *)\n(* intros.   *)\n(* assert (forall x, false = (x && negb x)%bool). admit.  *)\n(* Require Import Setoid. erewrite H.  *)\n(* match goal with  *)\n(*     |- P ?l =>  *)\n(*       reify_sexpr l *)\n(* end.  *)\n(* Abort.  *)\n\n(* Goal True.  *)\n(* Ltac t f := *)\n(* match f with  *)\n(*   | (fun x => @?B x) => idtac 1 B;  *)\n(*       refl_app ltac:(fun x y z => idtac x y z) B *)\n(*   | (fun x => _) => idtac 2 *)\n(* end.  *)\n\n(* t ((fun x => (if (x : bool) then true else false))).  *)\n(* Abort.  *)\n*)", "meta": {"author": "gmalecha", "repo": "mirror-shard", "sha": "24f34dee2f78de731f4ef398733ff2c1f1551375", "save_path": "github-repos/coq/gmalecha-mirror-shard", "path": "github-repos/coq/gmalecha-mirror-shard/mirror-shard-24f34dee2f78de731f4ef398733ff2c1f1551375/src/reification/example.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.5, "lm_q1q2_score": 0.26171016703392835}}
{"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_Registers.t.\n  Definition DEX_ReturnState := DEX_ReturnVal.\n\n\n  Inductive DEX_NormalStep (p:DEX_Program) : DEX_Method -> DEX_IntraNormalState -> DEX_IntraNormalState  -> Prop :=\n  | nop : forall 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) (pc', regs)\n\n  | const : forall 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) (pc', regs')\n  \n  | move_step_ok : forall 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) (pc', regs')\n\n  | goto_step_ok : forall m pc regs o,\n\n    instructionAt m pc = Some (DEX_Goto o) ->\n\n    DEX_NormalStep p m (pc, regs) ((DEX_OFFSET.jump pc o), regs)\n  \n  | packedswitch_step_ok1 : forall 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, l) ((DEX_OFFSET.jump pc o), l)\n\n  | packedswitch_step_ok2 : forall 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, l) (pc', l)\n  \n  | sparseswitch_step_ok1 : forall 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, l) ((DEX_OFFSET.jump pc o), l)\n\n  | sparseswitch_step_ok2 : forall 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, l) (pc', l)\n\n  | ifcmp_step_jump : forall 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) ((DEX_OFFSET.jump pc o), regs)\n\n  | ifcmp_step_continue : forall 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) (pc', regs)\n\n  | ifz_step_jump : forall 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) ((DEX_OFFSET.jump pc o), regs)\n\n  | ifz_step_continue : forall 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) (pc', regs)\n\n  (** <addlink>ineg</addlink>: Negate [int] *)\n  | ineg_step : forall 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) (pc', regs')\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) (pc', regs')\n\n  (** <addlink>i2b</addlink>: Convert [int] to [byte] *)\n  | i2b_step_ok : forall 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) (pc', regs')\n\n (** <addlink>i2s</addlink>: Convert [int] to [short] *)\n  | i2s_step_ok : forall 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) (pc', regs')\n\n  | ibinop_step_ok : forall 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) (pc', regs')\n\n  | ibinopconst_step_ok : forall 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) (pc', regs')\n.\n\n  Inductive DEX_ReturnStep (p:DEX_Program) : DEX_Method -> DEX_IntraNormalState -> DEX_ReturnState -> Prop :=\n  | void_return : forall 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) (Normal None)\n\n  | vreturn : forall 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 val t ->\n    compat_ValKind_value k val ->\n    Some val = DEX_Registers.get regs rs ->\n\n    DEX_ReturnStep p m (pc, regs) (Normal (Some val))\n.\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\n  Inductive DEX_exec_return (p:DEX_Program) (m:DEX_Method) : DEX_IntraNormalState -> DEX_ReturnState -> Prop :=\n  | exec_return_normal : forall s ov,\n     DEX_ReturnStep p m s (Normal ov) ->\n     DEX_exec_return p m s (Normal ov)\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 \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\n Definition DEX_Reachable P M s s' := \n   exists M',  ClosReflTrans (DEX_ReachableStep P) (M,s) (M',s').", "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_BigStepLoad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.26160827988837737}}
{"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 cap_lang region contiguous.\n\nSection helpers.\n\n  (* ---------------------------- Helper Lemmas --------------------------------------- *)\n\n  Definition isCorrectPC_range p g b e a0 an :=\n    ∀ ai, (a0 <= ai)%a ∧ (ai < an)%a → isCorrectPC (inr (p, g, b, e, ai)).\n\n  Lemma isCorrectPC_inrange p g b (e a0 an a: Addr) :\n    isCorrectPC_range p g b e a0 an →\n    (a0 <= a < an)%Z →\n    isCorrectPC (inr (p, g, b, e, a)).\n  Proof.\n    unfold isCorrectPC_range. move=> /(_ a) HH ?. apply HH. eauto.\n  Qed.\n\n  Lemma isCorrectPC_contiguous_range p g b e a0 an a l :\n    isCorrectPC_range p g b e a0 an →\n    contiguous_between l a0 an →\n    a ∈ l →\n    isCorrectPC (inr (p, g, b, e, a)).\n  Proof.\n    intros Hr Hc Hin.\n    eapply isCorrectPC_inrange; eauto.\n    eapply contiguous_between_middle_bounds'; eauto.\n  Qed.\n\n  Lemma isCorrectPC_range_perm p g b e a0 an :\n    isCorrectPC_range p g b e a0 an →\n    (a0 < an)%a →\n    p = RX ∨ p = RWX ∨ p = RWLX.\n  Proof.\n    intros Hr H0n.\n    assert (isCorrectPC (inr (p, g, b, e, a0))) as HH by (apply Hr; solve_addr).\n    inversion HH; auto.\n  Qed.\n\n  Lemma isCorrectPC_range_npE p g b e a0 an :\n    isCorrectPC_range p g b e a0 an →\n    (a0 < an)%a →\n    p ≠ E.\n  Proof.\n    intros HH1 HH2.\n    destruct (isCorrectPC_range_perm _ _ _ _ _ _ HH1 HH2) as [?| [?|?] ];\n      congruence.\n  Qed.\n\n  Lemma isCorrectPC_range_restrict p g b e a0 an a0' an' :\n    isCorrectPC_range p g b e a0 an →\n    (a0 <= a0')%a ∧ (an' <= an)%a →\n    isCorrectPC_range p g b e a0' an'.\n  Proof.\n    intros HR [? ?] a' [? ?]. apply HR. solve_addr.\n  Qed.\n\n  Lemma isCorrectPC_range_monotone p g b e a0 an a' a'':\n    isCorrectPC_range p g b e a0 an →\n    (a0 <= a')%a → (a'' <= an)%a →\n    isCorrectPC_range p g b e a' a''.\n  Proof.\n    intros. intros a1 [Ha'1 Ha'2]. apply H. solve_addr.\n  Qed.\n\n  Lemma isCorrectPC_range_split :\n    ∀ (p : Perm) (g : Locality) (b e a0 an a_link : Addr),\n      isCorrectPC_range p g b e a0 an\n      → (a0 <= a_link)%a → (a_link <= an)%a →\n      isCorrectPC_range p g b e a0 a_link ∧ isCorrectPC_range p g b e a_link an.\n  Proof.\n    intros * HCorr ??. split; eapply isCorrectPC_range_monotone; eauto; solve_addr.\n  Qed.\n  \n  Lemma pc_range_not_E  pc_p pc_g pc_b pc_e a_first a_last a_tail:\n    isCorrectPC_range pc_p pc_g pc_b pc_e a_first a_last →\n    contiguous_between (a_first :: a_tail) a_first a_last →\n    pc_p ≠ E.\n  Proof.\n    intros Hvpc Hcont.\n    apply isCorrectPC_range_perm in Hvpc as [Heq | [Heq | Heq] ]; subst; auto.\n    apply (contiguous_between_middle_bounds _ 0 a_first) in Hcont as [_ Hlt]; auto.\n  Qed.\n\n  Lemma pc_range_perm  pc_p pc_g pc_b pc_e a_first a_last a_tail:\n    isCorrectPC_range pc_p pc_g pc_b pc_e a_first a_last →\n    contiguous_between (a_first :: a_tail) a_first a_last →\n    pc_p = RX ∨ pc_p = RWX ∨ pc_p = RWLX.\n  Proof.\n    intros Hvpc Hcont.\n    apply isCorrectPC_range_perm in Hvpc as [Heq | [Heq | Heq] ]; subst; auto.\n    apply (contiguous_between_middle_bounds _ 0 a_first) in Hcont as [_ Hlt]; auto.\n  Qed.\n\n  Lemma pc_range_nonO  pc_p pc_g pc_b pc_e a_first a_last a_tail:\n    isCorrectPC_range pc_p pc_g pc_b pc_e a_first a_last →\n    contiguous_between (a_first :: a_tail) a_first a_last →\n    pc_p ≠ O.\n  Proof.\n    intros Hcorr Hcont.\n    assert (pc_p = RX ∨ pc_p = RWX ∨ pc_p = RWLX) as [-> | [-> | ->] ] by (eapply pc_range_perm; eauto); auto.\n  Qed.\n\n  Lemma pc_range_readA  pc_p pc_g pc_b pc_e a_first a_last a_tail:\n    isCorrectPC_range pc_p pc_g pc_b pc_e a_first a_last →\n    contiguous_between (a_first :: a_tail) a_first a_last →\n    readAllowed pc_p = true.\n  Proof.\n    intros Hcorr Hcont.\n    assert (pc_p = RX ∨ pc_p = RWX ∨ pc_p = RWLX) as [-> | [-> | ->] ] by (eapply pc_range_perm; eauto); auto.\n  Qed.\n\nEnd helpers.\n\n(* -------------------------------- LTACS ------------------------------------------- *)\n\n  (* Destructing -parts of- sequences of addresses *)\n  Ltac prep_addr_core list n :=\n    match eval compute in n with\n    | 0 => idtac\n    | _ => destruct list;[done|]; prep_addr_core list (pred n) end.\n\n  Ltac prep_addr_list list Hcont n :=\n    let l := fresh \"l\" in\n    destruct list as [| list l];[done|];\n    apply contiguous_between_cons_inv_first in Hcont as Heq; subst list;\n    prep_addr_core l (pred n).\n\n  Ltac destruct_addr_list list :=\n    let l := fresh \"l\" in\n    destruct list as [| list l];[done|];\n    repeat (destruct l;[done|]); destruct l; [|done].\n\n  Ltac prep_addr_list_full list Hcont :=\n    destruct_addr_list list;\n    apply contiguous_between_cons_inv_first in Hcont as Heq; subst list.\n\n  (* Tactics for single instruction spec application *)\n  Ltac iPrologue_pre :=\n    match goal with\n    | Hlen : length ?a = ?n |- _ =>\n      let a' := fresh \"a\" in\n      destruct a as [| a' a]; inversion Hlen; simpl\n    end.\n\n  Ltac iPrologue prog :=\n    let str_destr := constr:((\"[Hi \" ++ prog ++ \"]\")%string) in\n    iDestruct prog as str_destr;\n    iApply (wp_bind (fill [SeqCtx])).\n\n  Ltac iEpilogue prog :=\n    iNext; iIntros prog; iSimpl;\n    iApply wp_pure_step_later;auto;iNext.\n\n  Ltac iEpilogueLoad z prog :=\n    iNext; iIntros (z) prog; iSimpl;\n    iApply wp_pure_step_later;auto;iNext.\n\n  Ltac iCorrectPC i j :=\n    eapply isCorrectPC_contiguous_range with (a0 := i) (an := j); eauto; [];\n    cbn; solve [ repeat constructor ].\n\n  Ltac iContiguous_next Ha index :=\n    apply contiguous_of_contiguous_between in Ha;\n    generalize (contiguous_spec _ Ha index); auto.\n\n  Lemma lst_lkup_head `{A : Type} hd (tail : list A) :\n    (hd :: tail) !! 0 = Some hd.\n  Proof. done. Qed.\n  Lemma lst_lkup_cons `{A : Type} hd (tail : list A) i:\n    (hd :: tail) !! (i + 1) = tail !! i.\n  Proof. rewrite -plus_n_Sm Nat.add_0_r. rewrite -lookup_tail. simpl. done. Qed.\n  Ltac iContiguous_next_a Ha :=\n    apply contiguous_of_contiguous_between in Ha;\n    eapply (contiguous_spec _ Ha);\n    [repeat first [ by apply lst_lkup_head | erewrite lst_lkup_cons ] | done].\n  Ltac iCorrectPC_a :=\n    match goal with\n    | _ : isCorrectPC_range _ _ _ _ ?i ?j |- _ =>\n      eapply isCorrectPC_contiguous_range with (a0 := i) (an := j); eauto; [];\n      cbn; solve [ repeat constructor ]\n    end.\n\n  Ltac contiguous_between_clean Hcont :=\n    repeat apply contiguous_between_weak in Hcont.\n\n  (* Tactics in case of CPS spec *)\n  Ltac derive_length Hprog Hprog_len :=\n    iDestruct (big_sepL2_length with Hprog) as %Hprog_len; simpl in Hprog_len.\n  Ltac split_program Hprog Hcont a_link :=\n    let str_destr := constr:((\"(Hcode & \" ++ Hprog ++ \" & #Hcontig)\")%string) in\n    let l_code := fresh \"l_code\" in\n    let l_rest := fresh \"l_rest\" in\n    iDestruct (contiguous_between_program_split with Hprog) as (l_code l_rest a_link)  str_destr;[apply Hcont|]; clear Hcont.\n  Ltac split_PC_range Hvpc Hcont_code Hcont a_linka :=\n    let Hvpc_code := fresh \"Hvpc_code\" in\n    let Hvpc_rest := fresh \"Hvpc_rest\" in\n    edestruct isCorrectPC_range_split with (a_link := a_linka) as [Hvpc_code Hvpc_rest];[exact Hvpc| apply (contiguous_between_bounds _ _ _ Hcont_code) | apply (contiguous_between_bounds _ _ _ Hcont)| ..]; clear Hvpc; rename Hvpc_rest into Hvpc.\n\n  Ltac iPrologue_multi Hprog Hcont Hvpc a_link :=\n    split_program Hprog Hcont a_link;\n    let Hcont_code := fresh \"Hcont_code\" in\n    let Hlink := fresh \"Hlink\" in\n    let Hre := fresh \"Hre\" in\n    iDestruct \"Hcontig\" as %(Hcont_code & Hcont & Hre & Hlink);\n    rewrite -> Hre in *; clear Hre;\n    let Hlength_code := fresh \"Hlength_code\" in\n    derive_length \"Hcode\" Hlength_code;\n    rewrite Hlength_code in Hlink; clear Hlength_code;\n    let Hlength := fresh \"Hlength\" in\n    derive_length Hprog Hlength;\n    split_PC_range Hvpc Hcont_code Hcont a_link.\n\n  Tactic Notation \"iEpilogue_multi\" constr(Hprog) hyp_list(Hclear) :=\n    let Hfresh := fresh \"Hfresh\" in\n    assert (Hfresh : True) by auto;\n    iNext; iIntros Hprog; clear Hfresh Hclear.\n\n  Ltac frame_conjunction Hyp :=\n    repeat (iDestruct Hyp as \"[Hi Hprog_done]\"; iFrame \"Hi\"); iFrame; auto.\n\n  (* Adding and removing pointso from a map *)\n\n Ltac extract_pointsto_map regs Hmap rname Hrdom Hreg :=\n    let rval := fresh \"v\"rname in\n    let Hsome := fresh \"Hsome\" in\n    let str_destr := constr:((\"[\" ++ Hreg ++ \" \" ++ Hmap ++ \"]\")%string) in\n    assert (is_Some (regs !! rname)) as [rval Hsome] by (apply Hrdom; repeat constructor);\n    iDestruct (big_sepM_delete _ _ rname with Hmap) as str_destr; first by simplify_map_eq.\n  Ltac solve_insert_dom :=\n  rewrite -(not_elem_of_dom (D := (gset RegName)));\n  match goal with\n  | [ H : dom (gset RegName) _ = _ |- _ ] =>\n    rewrite H end;\n  set_solver+.\n\n  Ltac insert_pointsto_map_dom Hmap Hreg:=\n    let str_destr := constr:((\"[ $\" ++ Hmap ++ \" $\" ++ Hreg ++ \"]\")%string) in\n    iDestruct (big_sepM_insert with str_destr) as Hmap;\n    [(repeat rewrite lookup_insert_ne //;[]); solve_insert_dom | ].\n\n  Ltac insert_pointsto_map_del Hmap Hreg :=\n    let str_destr := constr:((\"[ $\" ++ Hmap ++ \" $\" ++ Hreg ++ \"]\")%string) in\n    iDestruct (big_sepM_insert with str_destr) as Hmap;\n    [by simplify_map_eq | repeat (rewrite -delete_insert_ne //;[]); try rewrite insert_delete].\n\n   Ltac insert_pointsto_map Hmap Hreg :=\n     first [insert_pointsto_map_del Hmap Hreg | insert_pointsto_map_dom Hmap Hreg].\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/stack_macros_helpers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2615984734266611}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.progs.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\nHint 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\nHint 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.\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\nHint 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\nHint 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.\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": "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_append2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.2615984734266611}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*          Andrew W. Appel, 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 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(** Constructions of semi-lattices. *)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import FSets.\n\n(* To avoid useless definitions of inductors in extracted code. *)\nLocal Unset Elimination Schemes.\nLocal Unset Case Analysis Schemes.\n\n(** * Signatures of semi-lattices *)\n\n(** A semi-lattice is a type [t] equipped with an equivalence relation [eq],\n  a boolean equivalence test [beq], a partial order [ge], a smallest element\n  [bot], and an upper bound operation [lub].\n  Note that we do not demand that [lub] computes the least upper bound. *)\n\nModule Type SEMILATTICE.\n\n  Parameter t: Type.\n  Parameter eq: t -> t -> Prop.\n  Axiom eq_refl: forall x, eq x x.\n  Axiom eq_sym: forall x y, eq x y -> eq y x.\n  Axiom eq_trans: forall x y z, eq x y -> eq y z -> eq x z.\n  Parameter beq: t -> t -> bool.\n  Axiom beq_correct: forall x y, beq x y = true -> eq x y.\n  Parameter ge: t -> t -> Prop.\n  Axiom ge_refl: forall x y, eq x y -> ge x y.\n  Axiom ge_trans: forall x y z, ge x y -> ge y z -> ge x z.\n  Parameter bot: t.\n  Axiom ge_bot: forall x, ge x bot.\n  Parameter lub: t -> t -> t.\n  Axiom ge_lub_left: forall x y, ge (lub x y) x.\n  Axiom ge_lub_right: forall x y, ge (lub x y) y.\n\nEnd SEMILATTICE.\n\n(** A semi-lattice ``with top'' is similar, but also has a greatest\n  element [top]. *)\n\nModule Type SEMILATTICE_WITH_TOP.\n\n  Include SEMILATTICE.\n  Parameter top: t.\n  Axiom ge_top: forall x, ge top x.\n\nEnd SEMILATTICE_WITH_TOP.\n\n(** * Semi-lattice over maps *)\n\nSet Implicit Arguments.\n\n(** Given a semi-lattice (without top) [L], the following functor implements\n  a semi-lattice structure over finite maps from positive numbers to [L.t].\n  The default value for these maps is [L.bot].  Bottom elements are not smashed. *)\n\nModule LPMap1(L: SEMILATTICE) <: SEMILATTICE.\n\nDefinition t := PTree.t L.t.\n\nDefinition get (p: positive) (x: t) : L.t :=\n  match x!p with None => L.bot | Some x => x end.\n\nDefinition set (p: positive) (v: L.t) (x: t) : t :=\n  if L.beq v L.bot\n  then PTree.remove p x\n  else PTree.set p v x.\n\nLemma gsspec:\n  forall p v x q,\n  L.eq (get q (set p v x)) (if peq q p then v else get q x).\nProof.\n  intros. unfold set, get.\n  destruct (L.beq v L.bot) eqn:EBOT.\n  rewrite PTree.grspec. unfold PTree.elt_eq. destruct (peq q p).\n  apply L.eq_sym. apply L.beq_correct; auto.\n  apply L.eq_refl.\n  rewrite PTree.gsspec. destruct (peq q p); apply L.eq_refl.\nQed.\n\nDefinition eq (x y: t) : Prop :=\n  forall p, L.eq (get p x) (get p y).\n\nLemma eq_refl: forall x, eq x x.\nProof.\n  unfold eq; intros. apply L.eq_refl.\nQed.\n\nLemma eq_sym: forall x y, eq x y -> eq y x.\nProof.\n  unfold eq; intros. apply L.eq_sym; auto.\nQed.\n\nLemma eq_trans: forall x y z, eq x y -> eq y z -> eq x z.\nProof.\n  unfold eq; intros. eapply L.eq_trans; eauto.\nQed.\n\nDefinition beq (x y: t) : bool := PTree.beq L.beq x y.\n\nLemma beq_correct: forall x y, beq x y = true -> eq x y.\nProof.\n  unfold beq; intros; red; intros. unfold get.\n  rewrite PTree.beq_correct in H. specialize (H p).\n  destruct (x!p); destruct (y!p); intuition.\n  apply L.beq_correct; auto.\n  apply L.eq_refl.\nQed.\n\nDefinition ge (x y: t) : Prop :=\n  forall p, L.ge (get p x) (get p y).\n\nLemma ge_refl: forall x y, eq x y -> ge x y.\nProof.\n  unfold ge, eq; intros. apply L.ge_refl. auto.\nQed.\n\nLemma ge_trans: forall x y z, ge x y -> ge y z -> ge x z.\nProof.\n  unfold ge; intros. apply L.ge_trans with (get p y); auto.\nQed.\n\nDefinition bot : t := PTree.empty _.\n\nLemma get_bot: forall p, get p bot = L.bot.\nProof.\n  intros; reflexivity.\nQed.\n\nLemma ge_bot: forall x, ge x bot.\nProof.\n  unfold ge; intros. rewrite get_bot. apply L.ge_bot.\nQed.\n\n(** Equivalence modulo L.eq *)\n\nDefinition opt_eq (ox oy: option L.t) : Prop :=\n  match ox, oy with\n  | None, None => True\n  | Some x, Some y => L.eq x y\n  | _, _ => False\n  end.\n\nLemma opt_eq_refl: forall ox, opt_eq ox ox.\nProof.\n  intros. unfold opt_eq. destruct ox. apply L.eq_refl. auto.\nQed.\n\nLemma opt_eq_sym: forall ox oy, opt_eq ox oy -> opt_eq oy ox.\nProof.\n  unfold opt_eq. destruct ox; destruct oy; auto. apply L.eq_sym.\nQed.\n\nLemma opt_eq_trans: forall ox oy oz, opt_eq ox oy -> opt_eq oy oz -> opt_eq ox oz.\nProof.\n  unfold opt_eq. destruct ox; destruct oy; destruct oz; intuition.\n  eapply L.eq_trans; eauto.\nQed.\n\nDefinition opt_beq (ox oy: option L.t) : bool :=\n  match ox, oy with\n  | None, None => true\n  | Some x, Some y => L.beq x y\n  | _, _ => false\n  end.\n\nLemma opt_beq_correct:\n  forall ox oy, opt_beq ox oy = true -> opt_eq ox oy.\nProof.\n  unfold opt_beq, opt_eq. destruct ox; destruct oy; try congruence.\n  intros. apply L.beq_correct; auto.\n  auto.\nQed.\n\nLocal Hint Resolve opt_beq_correct opt_eq_refl opt_eq_sym : combine.\n\n(** A [combine] operation over the type [PTree.t L.t] that attempts\n  to share its result with its arguments. *)\n\nSection COMBINE.\n\nVariable f: option L.t -> option L.t -> option L.t.\nHypothesis f_none_none: f None None = None.\n\nInductive changed : Type :=\n  | Same\n  | Same1\n  | Same2\n  | Changed (m: PTree.t L.t).\n\nLet Node_combine_l (l1: PTree.t L.t) (lres: changed) (o1: option L.t)\n                   (r1: PTree.t L.t) (rres: changed) : changed :=\n  let o' := f o1 None in\n  match lres, rres with\n  | Same1, Same1 =>\n      if opt_beq o' o1 then Same1 else Changed (PTree.Node l1 o' r1)\n  | Same1, Changed r' => Changed (PTree.Node l1 o' r')\n  | Changed l', Same1 => Changed (PTree.Node l' o' r1)\n  | Changed l', Changed r' => Changed (PTree.Node l' o' r')\n  | _, _ => Same (**r impossible cases *)\n  end.\n\nLet xcombine_l (m: PTree.t L.t) : changed :=\n  PTree.tree_rec Same1 Node_combine_l m.\n\nLet Node_combine_r (l1: PTree.t L.t) (lres: changed) (o1: option L.t)\n                   (r1: PTree.t L.t) (rres: changed) : changed :=\n  let o' := f None o1 in\n  match lres, rres with\n  | Same2, Same2 =>\n      if opt_beq o' o1 then Same2 else Changed (PTree.Node l1 o' r1)\n  | Same2, Changed r' => Changed (PTree.Node l1 o' r')\n  | Changed l', Same2 => Changed (PTree.Node l' o' r1)\n  | Changed l', Changed r' => Changed (PTree.Node l' o' r')\n  | _, _ => Same (**r impossible cases *)\n  end.\n\nLet xcombine_r (m: PTree.t L.t) : changed :=\n  PTree.tree_rec Same2 Node_combine_r m.\n\nLet Node_combine_2\n             (l1: PTree.t L.t) (o1: option L.t) (r1: PTree.t L.t)\n             (l2: PTree.t L.t) (o2: option L.t) (r2: PTree.t L.t)\n             (lres: changed) (rres: changed) : changed :=\n  let o := f o1 o2 in\n  match lres, rres with\n  | Same, Same =>\n      match opt_beq o o1, opt_beq o o2 with\n      | true, true => Same\n      | true, false => Same1\n      | false, true => Same2\n      | false, false => Changed (PTree.Node l1 o r1)\n      end\n  | Same, Same1\n  | Same1, Same\n  | Same1, Same1 =>\n      if opt_beq o o1 then Same1 else Changed (PTree.Node l1 o r1)\n  | Same, Same2\n  | Same2, Same\n  | Same2, Same2 =>\n      if opt_beq o o2 then Same2 else Changed (PTree.Node l2 o r2)\n  | Same, Changed m2 => Changed (PTree.Node l1 o m2)\n  | Same1, Same2 => Changed (PTree.Node l1 o r2)\n  | Same1, Changed m2 => Changed (PTree.Node l1 o m2)\n  | Same2, Same1 => Changed (PTree.Node l2 o r1)\n  | Same2, Changed m2 => Changed (PTree.Node l2 o m2)\n  | Changed m1, (Same|Same1) => Changed (PTree.Node m1 o r1)\n  | Changed m1, Same2 => Changed (PTree.Node m1 o r2)\n  | Changed m1, Changed m2 => Changed (PTree.Node m1 o m2)\n  end.\n\nDefinition xcombine :=\n  PTree.tree_rec2\n    Same\n    xcombine_r\n    xcombine_l\n    Node_combine_2.\n\nDefinition tree_agree (m1 m2 m: PTree.t L.t) : Prop :=\n  forall i, opt_eq m!i (f m1!i m2!i).\n\nLemma tree_agree_node: forall l1 o1 r1 l2 o2 r2 l o r,\n  tree_agree l1 l2 l -> tree_agree r1 r2 r -> opt_eq (f o1 o2) o ->\n  tree_agree (PTree.Node l1 o1 r1) (PTree.Node l2 o2 r2) (PTree.Node l o r).\nProof.\n  intros; red; intros. rewrite ! PTree.gNode. destruct i; auto using opt_eq_sym.\nQed.\n\nLocal Hint Resolve tree_agree_node : combine.\n\nLemma gxcombine_l: forall m,\n  match xcombine_l m with\n  | Same1 => forall i, opt_eq m!i (f m!i None)\n  | Changed m' => forall i, opt_eq m'!i (f m!i None)\n  | _ => False\n  end.\nProof.\n  unfold xcombine_l. induction m using PTree.tree_ind.\n- simpl; intros. rewrite PTree.gempty, f_none_none. auto.\n- rewrite PTree.unroll_tree_rec by auto.\n  destruct (PTree.tree_rec Same1 Node_combine_l l);\n  destruct (PTree.tree_rec Same1 Node_combine_l r);\n  try contradiction;\n  unfold Node_combine_l;\n  try (intros i; rewrite ! PTree.gNode; destruct i; auto with combine).\n  destruct (opt_beq (f o None) o) eqn:BEQ; intros i; rewrite ! PTree.gNode; destruct i; auto with combine.\nQed.\n\nLemma gxcombine_r: forall m,\n  match xcombine_r m with\n  | Same2 => forall i, opt_eq m!i (f None m!i)\n  | Changed m' => forall i, opt_eq m'!i (f None m!i)\n  | _ => False\n  end.\nProof.\n  unfold xcombine_r. induction m using PTree.tree_ind.\n- simpl; intros. rewrite PTree.gempty, f_none_none. auto.\n- rewrite PTree.unroll_tree_rec by auto.\n  destruct (PTree.tree_rec Same2 Node_combine_r l);\n  destruct (PTree.tree_rec Same2 Node_combine_r r);\n  try contradiction;\n  unfold Node_combine_r;\n  try (intros i; rewrite ! PTree.gNode; destruct i; auto with combine).\n  destruct (opt_beq (f None o) o) eqn:BEQ; intros i; rewrite ! PTree.gNode; destruct i; auto with combine.\nQed.\n\nInductive xcombine_spec (m1 m2: PTree.t L.t) : changed -> Prop :=\n  | XCS_Same:\n      tree_agree m1 m2 m1 -> tree_agree m1 m2 m2 -> xcombine_spec m1 m2 Same\n  | XCS_Same1:\n      tree_agree m1 m2 m1 -> xcombine_spec m1 m2 Same1\n  | XCS_Same2:\n      tree_agree m1 m2 m2 -> xcombine_spec m1 m2 Same2\n  | XCS_Changed: forall m',\n      tree_agree m1 m2 m' -> xcombine_spec m1 m2 (Changed m').\n\nLocal Hint Constructors xcombine_spec : combine.\n\nLemma gxcombine: forall m1 m2, xcombine_spec m1 m2 (xcombine m1 m2).\nProof.\n  Local Opaque opt_eq.\n  unfold xcombine.\n  induction m1 using PTree.tree_ind; induction m2 using PTree.tree_ind; intros.\n- constructor; red; intros; rewrite ! PTree.gEmpty, f_none_none; auto with combine.\n- rewrite PTree.unroll_tree_rec2_EN by auto. set (m2 := PTree.Node l o r).\n  generalize (gxcombine_r m2); destruct (xcombine_r m2); \n  try contradiction; constructor; auto.\n- rewrite PTree.unroll_tree_rec2_NE by auto. set (m1 := PTree.Node l o r).\n  generalize (gxcombine_l m1); destruct (xcombine_l m1); \n  try contradiction; constructor; auto.\n- rewrite PTree.unroll_tree_rec2_NN by auto.\n  clear IHm2 IHm3. specialize (IHm1 l0). specialize (IHm0 r0).\n  inv IHm1; inv IHm0; unfold Node_combine_2; auto with combine;\n  destruct (opt_beq (f o o0) o) eqn:E1; destruct (opt_beq (f o o0) o0) eqn:E2;\n  auto with combine.\nQed.\n\nDefinition combine (m1 m2: PTree.t L.t) : PTree.t L.t :=\n  match xcombine m1 m2 with\n  | Same|Same1 => m1\n  | Same2 => m2\n  | Changed m => m\n  end.\n\nTheorem gcombine:\n  forall m1 m2 i, opt_eq (PTree.get i (combine m1 m2)) (f (PTree.get i m1) (PTree.get i m2)).\nProof.\n  intros. unfold combine. \n  generalize (gxcombine m1 m2); intros XS; inv XS; auto.\nQed.\n\nEnd COMBINE.\n\nDefinition lub (x y: t) : t :=\n  combine\n    (fun a b =>\n       match a, b with\n       | Some u, Some v => Some (L.lub u v)\n       | None, _ => b\n       | _, None => a\n       end)\n    x y.\n\nLemma gcombine_bot:\n  forall f t1 t2 p,\n  f None None = None ->\n  L.eq (get p (combine f t1 t2))\n       (match f t1!p t2!p with Some x => x | None => L.bot end).\nProof.\n  intros. unfold get. generalize (gcombine f H t1 t2 p). unfold opt_eq.\n  destruct ((combine f t1 t2)!p); destruct (f t1!p t2!p).\n  auto. contradiction. contradiction. intros; apply L.eq_refl.\nQed.\n\nLemma ge_lub_left:\n  forall x y, ge (lub x y) x.\nProof.\n  unfold ge, lub; intros.\n  eapply L.ge_trans. apply L.ge_refl. apply gcombine_bot; auto.\n  unfold get. destruct x!p. destruct y!p.\n  apply L.ge_lub_left.\n  apply L.ge_refl. apply L.eq_refl.\n  apply L.ge_bot.\nQed.\n\nLemma ge_lub_right:\n  forall x y, ge (lub x y) y.\nProof.\n  unfold ge, lub; intros.\n  eapply L.ge_trans. apply L.ge_refl. apply gcombine_bot; auto.\n  unfold get. destruct y!p. destruct x!p.\n  apply L.ge_lub_right.\n  apply L.ge_refl. apply L.eq_refl.\n  apply L.ge_bot.\nQed.\n\nEnd LPMap1.\n\n(** Given a semi-lattice with top [L], the following functor implements\n  a semi-lattice-with-top structure over finite maps from positive numbers to [L.t].\n  The default value for these maps is [L.top].  Bottom elements are smashed. *)\n\nModule LPMap(L: SEMILATTICE_WITH_TOP) <: SEMILATTICE_WITH_TOP.\n\nInductive t' : Type :=\n  | Bot: t'\n  | Top_except: PTree.t L.t -> t'.\n\nDefinition t: Type := t'.\n\nDefinition get (p: positive) (x: t) : L.t :=\n  match x with\n  | Bot => L.bot\n  | Top_except m => match m!p with None => L.top | Some x => x end\n  end.\n\nDefinition set (p: positive) (v: L.t) (x: t) : t :=\n  match x with\n  | Bot => Bot\n  | Top_except m =>\n      if L.beq v L.bot\n      then Bot\n      else Top_except (if L.beq v L.top then PTree.remove p m else PTree.set p v m)\n  end.\n\nLemma gsspec:\n  forall p v x q,\n  x <> Bot -> ~L.eq v L.bot ->\n  L.eq (get q (set p v x)) (if peq q p then v else get q x).\nProof.\n  intros. unfold set. destruct x. congruence.\n  destruct (L.beq v L.bot) eqn:EBOT.\n  elim H0. apply L.beq_correct; auto.\n  destruct (L.beq v L.top) eqn:ETOP; simpl.\n  rewrite PTree.grspec. unfold PTree.elt_eq. destruct (peq q p).\n  apply L.eq_sym. apply L.beq_correct; auto.\n  apply L.eq_refl.\n  rewrite PTree.gsspec. destruct (peq q p); apply L.eq_refl.\nQed.\n\nDefinition eq (x y: t) : Prop :=\n  forall p, L.eq (get p x) (get p y).\n\nLemma eq_refl: forall x, eq x x.\nProof.\n  unfold eq; intros. apply L.eq_refl.\nQed.\n\nLemma eq_sym: forall x y, eq x y -> eq y x.\nProof.\n  unfold eq; intros. apply L.eq_sym; auto.\nQed.\n\nLemma eq_trans: forall x y z, eq x y -> eq y z -> eq x z.\nProof.\n  unfold eq; intros. eapply L.eq_trans; eauto.\nQed.\n\nDefinition beq (x y: t) : bool :=\n  match x, y with\n  | Bot, Bot => true\n  | Top_except m, Top_except n => PTree.beq L.beq m n\n  | _, _ => false\n  end.\n\nLemma beq_correct: forall x y, beq x y = true -> eq x y.\nProof.\n  destruct x; destruct y; simpl; intro; try congruence.\n  apply eq_refl.\n  red; intro; simpl.\n  rewrite PTree.beq_correct in H. generalize (H p).\n  destruct (t0!p); destruct (t1!p); intuition.\n  apply L.beq_correct; auto.\n  apply L.eq_refl.\nQed.\n\nDefinition ge (x y: t) : Prop :=\n  forall p, L.ge (get p x) (get p y).\n\nLemma ge_refl: forall x y, eq x y -> ge x y.\nProof.\n  unfold ge, eq; intros. apply L.ge_refl. auto.\nQed.\n\nLemma ge_trans: forall x y z, ge x y -> ge y z -> ge x z.\nProof.\n  unfold ge; intros. apply L.ge_trans with (get p y); auto.\nQed.\n\nDefinition bot := Bot.\n\nLemma get_bot: forall p, get p bot = L.bot.\nProof.\n  unfold bot; intros; simpl. auto.\nQed.\n\nLemma ge_bot: forall x, ge x bot.\nProof.\n  unfold ge; intros. rewrite get_bot. apply L.ge_bot.\nQed.\n\nDefinition top := Top_except (PTree.empty L.t).\n\nLemma get_top: forall p, get p top = L.top.\nProof.\n  unfold top; intros; auto.\nQed.\n\nLemma ge_top: forall x, ge top x.\nProof.\n  unfold ge; intros. rewrite get_top. apply L.ge_top.\nQed.\n\nModule LM := LPMap1(L).\n\nDefinition opt_lub (x y: L.t) : option L.t :=\n  let z := L.lub x y in\n  if L.beq z L.top then None else Some z.\n\nDefinition lub (x y: t) : t :=\n  match x, y with\n  | Bot, _ => y\n  | _, Bot => x\n  | Top_except m, Top_except n =>\n      Top_except\n        (LM.combine\n           (fun a b =>\n              match a, b with\n              | Some u, Some v => opt_lub u v\n              | _, _ => None\n              end)\n           m n)\n  end.\n\nLemma gcombine_top:\n  forall f t1 t2 p,\n  f None None = None ->\n  L.eq (get p (Top_except (LM.combine f t1 t2)))\n       (match f t1!p t2!p with Some x => x | None => L.top end).\nProof.\n  intros. simpl. generalize (LM.gcombine f H t1 t2 p). unfold LM.opt_eq.\n  destruct ((LM.combine f t1 t2)!p); destruct (f t1!p t2!p).\n  auto. contradiction. contradiction. intros; apply L.eq_refl.\nQed.\n\nLemma ge_lub_left:\n  forall x y, ge (lub x y) x.\nProof.\n  unfold ge, lub; intros. destruct x; destruct y.\n  rewrite get_bot. apply L.ge_bot.\n  rewrite get_bot. apply L.ge_bot.\n  apply L.ge_refl. apply L.eq_refl.\n  eapply L.ge_trans. apply L.ge_refl. apply gcombine_top; auto.\n  unfold get. destruct t0!p. destruct t1!p.\n  unfold opt_lub. destruct (L.beq (L.lub t2 t3) L.top) eqn:E.\n  apply L.ge_top. apply L.ge_lub_left.\n  apply L.ge_top.\n  apply L.ge_top.\nQed.\n\nLemma ge_lub_right:\n  forall x y, ge (lub x y) y.\nProof.\n  unfold ge, lub; intros. destruct x; destruct y.\n  rewrite get_bot. apply L.ge_bot.\n  apply L.ge_refl. apply L.eq_refl.\n  rewrite get_bot. apply L.ge_bot.\n  eapply L.ge_trans. apply L.ge_refl. apply gcombine_top; auto.\n  unfold get. destruct t0!p; destruct t1!p.\n  unfold opt_lub. destruct (L.beq (L.lub t2 t3) L.top) eqn:E.\n  apply L.ge_top. apply L.ge_lub_right.\n  apply L.ge_top.\n  apply L.ge_top.\n  apply L.ge_top.\nQed.\n\nEnd LPMap.\n\n(** * Semi-lattice over a set. *)\n\n(** Given a set [S: FSetInterface.S], the following functor\n    implements a semi-lattice over these sets, ordered by inclusion. *)\n\nModule LFSet (S: FSetInterface.WS) <: SEMILATTICE.\n\n  Definition t := S.t.\n\n  Definition eq (x y: t) := S.Equal x y.\n  Definition eq_refl: forall x, eq x x := S.eq_refl.\n  Definition eq_sym: forall x y, eq x y -> eq y x := S.eq_sym.\n  Definition eq_trans: forall x y z, eq x y -> eq y z -> eq x z := S.eq_trans.\n  Definition beq: t -> t -> bool := S.equal.\n  Definition beq_correct: forall x y, beq x y = true -> eq x y := S.equal_2.\n\n  Definition ge (x y: t) := S.Subset y x.\n  Lemma ge_refl: forall x y, eq x y -> ge x y.\n  Proof.\n    unfold eq, ge, S.Equal, S.Subset; intros. firstorder.\n  Qed.\n  Lemma ge_trans: forall x y z, ge x y -> ge y z -> ge x z.\n  Proof.\n    unfold ge, S.Subset; intros. eauto.\n  Qed.\n\n  Definition  bot: t := S.empty.\n  Lemma ge_bot: forall x, ge x bot.\n  Proof.\n    unfold ge, bot, S.Subset; intros. elim (S.empty_1 H).\n  Qed.\n\n  Definition lub: t -> t -> t := S.union.\n\n  Lemma ge_lub_left: forall x y, ge (lub x y) x.\n  Proof.\n    unfold lub, ge, S.Subset; intros. apply S.union_2; auto.\n  Qed.\n\n  Lemma ge_lub_right: forall x y, ge (lub x y) y.\n  Proof.\n    unfold lub, ge, S.Subset; intros. apply S.union_3; auto.\n  Qed.\n\nEnd LFSet.\n\n(** * Flat semi-lattice *)\n\n(** Given a type with decidable equality [X], the following functor\n  returns a semi-lattice structure over [X.t] complemented with\n  a top and a bottom element.  The ordering is the flat ordering\n  [Bot < Inj x < Top]. *)\n\nModule LFlat(X: EQUALITY_TYPE) <: SEMILATTICE_WITH_TOP.\n\nInductive t' : Type :=\n  | Bot: t'\n  | Inj: X.t -> t'\n  | Top: t'.\n\nDefinition t : Type := t'.\n\nDefinition eq (x y: t) := (x = y).\nDefinition eq_refl: forall x, eq x x := (@eq_refl t).\nDefinition eq_sym: forall x y, eq x y -> eq y x := (@eq_sym t).\nDefinition eq_trans: forall x y z, eq x y -> eq y z -> eq x z := (@eq_trans t).\n\nDefinition beq (x y: t) : bool :=\n  match x, y with\n  | Bot, Bot => true\n  | Inj u, Inj v => if X.eq u v then true else false\n  | Top, Top => true\n  | _, _ => false\n  end.\n\nLemma beq_correct: forall x y, beq x y = true -> eq x y.\nProof.\n  unfold eq; destruct x; destruct y; simpl; try congruence; intro.\n  destruct (X.eq t0 t1); congruence.\nQed.\n\nDefinition ge (x y: t) : Prop :=\n  match x, y with\n  | Top, _ => True\n  | _, Bot => True\n  | Inj a, Inj b => a = b\n  | _, _ => False\n  end.\n\nLemma ge_refl: forall x y, eq x y -> ge x y.\nProof.\n  unfold eq, ge; intros; subst y; destruct x; auto.\nQed.\n\nLemma ge_trans: forall x y z, ge x y -> ge y z -> ge x z.\nProof.\n  unfold ge; destruct x; destruct y; try destruct z; intuition.\n  transitivity t1; auto.\nQed.\n\nDefinition bot: t := Bot.\n\nLemma ge_bot: forall x, ge x bot.\nProof.\n  destruct x; simpl; auto.\nQed.\n\nDefinition top: t := Top.\n\nLemma ge_top: forall x, ge top x.\nProof.\n  destruct x; simpl; auto.\nQed.\n\nDefinition lub (x y: t) : t :=\n  match x, y with\n  | Bot, _ => y\n  | _, Bot => x\n  | Top, _ => Top\n  | _, Top => Top\n  | Inj a, Inj b => if X.eq a b then Inj a else Top\n  end.\n\nLemma ge_lub_left: forall x y, ge (lub x y) x.\nProof.\n  destruct x; destruct y; simpl; auto.\n  case (X.eq t0 t1); simpl; auto.\nQed.\n\nLemma ge_lub_right: forall x y, ge (lub x y) y.\nProof.\n  destruct x; destruct y; simpl; auto.\n  case (X.eq t0 t1); simpl; auto.\nQed.\n\nEnd LFlat.\n\n(** * Boolean semi-lattice *)\n\n(** This semi-lattice has only two elements, [bot] and [top], trivially\n  ordered. *)\n\nModule LBoolean <: SEMILATTICE_WITH_TOP.\n\nDefinition t := bool.\n\nDefinition eq (x y: t) := (x = y).\nDefinition eq_refl: forall x, eq x x := (@eq_refl t).\nDefinition eq_sym: forall x y, eq x y -> eq y x := (@eq_sym t).\nDefinition eq_trans: forall x y z, eq x y -> eq y z -> eq x z := (@eq_trans t).\n\nDefinition beq : t -> t -> bool := eqb.\n\nLemma beq_correct: forall x y, beq x y = true -> eq x y.\nProof eqb_prop.\n\nDefinition ge (x y: t) : Prop := x = y \\/ x = true.\n\nLemma ge_refl: forall x y, eq x y -> ge x y.\nProof. unfold ge; tauto. Qed.\n\nLemma ge_trans: forall x y z, ge x y -> ge y z -> ge x z.\nProof. unfold ge; intuition congruence. Qed.\n\nDefinition bot := false.\n\nLemma ge_bot: forall x, ge x bot.\nProof. destruct x; compute; tauto. Qed.\n\nDefinition top := true.\n\nLemma ge_top: forall x, ge top x.\nProof. unfold ge, top; tauto. Qed.\n\nDefinition lub (x y: t) := x || y.\n\nLemma ge_lub_left: forall x y, ge (lub x y) x.\nProof. destruct x; destruct y; compute; tauto. Qed.\n\nLemma ge_lub_right: forall x y, ge (lub x y) y.\nProof. destruct x; destruct y; compute; tauto. Qed.\n\nEnd LBoolean.\n\n(** * Option semi-lattice *)\n\n(** This lattice adds a top element (represented by [None]) to a given\n  semi-lattice (whose elements are injected via [Some]). *)\n\nModule LOption(L: SEMILATTICE) <: SEMILATTICE_WITH_TOP.\n\nDefinition t: Type := option L.t.\n\nDefinition eq (x y: t) : Prop :=\n  match x, y with\n  | None, None => True\n  | Some x1, Some y1 => L.eq x1 y1\n  | _, _ => False\n  end.\n\nLemma eq_refl: forall x, eq x x.\nProof.\n  unfold eq; intros; destruct x. apply L.eq_refl. auto.\nQed.\n\nLemma eq_sym: forall x y, eq x y -> eq y x.\nProof.\n  unfold eq; intros; destruct x; destruct y; auto. apply L.eq_sym; auto.\nQed.\n\nLemma eq_trans: forall x y z, eq x y -> eq y z -> eq x z.\nProof.\n  unfold eq; intros; destruct x; destruct y; destruct z; auto.\n  eapply L.eq_trans; eauto.\n  contradiction.\nQed.\n\nDefinition beq (x y: t) : bool :=\n  match x, y with\n  | None, None => true\n  | Some x1, Some y1 => L.beq x1 y1\n  | _, _ => false\n  end.\n\nLemma beq_correct: forall x y, beq x y = true -> eq x y.\nProof.\n  unfold beq, eq; intros; destruct x; destruct y.\n  apply L.beq_correct; auto.\n  discriminate. discriminate. auto.\nQed.\n\nDefinition ge (x y: t) : Prop :=\n  match x, y with\n  | None, _ => True\n  | _, None => False\n  | Some x1, Some y1 => L.ge x1 y1\n  end.\n\nLemma ge_refl: forall x y, eq x y -> ge x y.\nProof.\n  unfold eq, ge; intros; destruct x; destruct y.\n  apply L.ge_refl; auto.\n  auto. elim H. auto.\nQed.\n\nLemma ge_trans: forall x y z, ge x y -> ge y z -> ge x z.\nProof.\n  unfold ge; intros; destruct x; destruct y; destruct z; auto.\n  eapply L.ge_trans; eauto. contradiction.\nQed.\n\nDefinition bot : t := Some L.bot.\n\nLemma ge_bot: forall x, ge x bot.\nProof.\n  unfold ge, bot; intros. destruct x; auto. apply L.ge_bot.\nQed.\n\nDefinition lub (x y: t) : t :=\n  match x, y with\n  | None, _ => None\n  | _, None => None\n  | Some x1, Some y1 => Some (L.lub x1 y1)\n  end.\n\nLemma ge_lub_left: forall x y, ge (lub x y) x.\nProof.\n  unfold ge, lub; intros; destruct x; destruct y; auto. apply L.ge_lub_left.\nQed.\n\nLemma ge_lub_right: forall x y, ge (lub x y) y.\nProof.\n  unfold ge, lub; intros; destruct x; destruct y; auto. apply L.ge_lub_right.\nQed.\n\nDefinition top : t := None.\n\nLemma ge_top: forall x, ge top x.\nProof.\n  unfold ge, top; intros. auto.\nQed.\n\nEnd LOption.\n", "meta": {"author": "AbsInt", "repo": "CompCert", "sha": "f4ddce910894bf6dbdf83c0642c4b275854b60dd", "save_path": "github-repos/coq/AbsInt-CompCert", "path": "github-repos/coq/AbsInt-CompCert/CompCert-f4ddce910894bf6dbdf83c0642c4b275854b60dd/lib/Lattice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.26145495115824113}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Numbers.BinNums.\nRequire Import Crypto.Reflection.Syntax.\nRequire Import Crypto.Reflection.Named.PositiveContext.\nRequire Import Crypto.Reflection.CountLets.\nRequire Import Crypto.Reflection.Named.NameUtil.\nRequire Import Crypto.Reflection.Named.PositiveContext.Defaults.\nRequire Import Crypto.Util.ListUtil.\nRequire Import Crypto.Util.Option.\nRequire Import Crypto.Util.NatUtil.\nRequire Import Crypto.Util.Tactics.DestructHead.\n\nSection language.\n  Context {base_type_code : Type}\n          {op : flat_type base_type_code -> flat_type base_type_code -> Type}.\n\n  Lemma name_list_unique_map_pos_of_succ_nat_seq a b\n    : name_list_unique (map BinPos.Pos.of_succ_nat (seq a b)).\n  Proof.\n    unfold name_list_unique, oname_list_unique, mname_list_unique.\n    intros k n.\n    rewrite !map_map, firstn_map, skipn_map, firstn_seq, skipn_seq.\n    rewrite !in_map_iff; intros; destruct_head' ex; destruct_head' and; inversion_option; subst.\n    match goal with H : _ |- _ => apply Pnat.SuccNat2Pos.inj in H end; subst.\n    rewrite in_seq in *.\n    omega *.\n  Qed.\n\n  Lemma name_list_unique_default_names_forf {var dummy t e}\n    : name_list_unique (@default_names_forf base_type_code op var dummy t e).\n  Proof. apply name_list_unique_map_pos_of_succ_nat_seq. Qed.\n  Lemma name_list_unique_default_names_for {var dummy t e}\n    : name_list_unique (@default_names_for base_type_code op var dummy t e).\n  Proof. apply name_list_unique_map_pos_of_succ_nat_seq. Qed.\n  Lemma name_list_unique_DefaultNamesFor {t e}\n    : name_list_unique (@DefaultNamesFor base_type_code op t e).\n  Proof. apply name_list_unique_map_pos_of_succ_nat_seq. Qed.\nEnd language.\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/Named/PositiveContext/DefaultsProperties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.26143760118911036}}
{"text": "From iris.program_logic Require Export weakestpre hoare.\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 tactics.\nFrom iris_examples.barrier Require Import proof specification.\nSet Default Proof Using \"Type\".\n\nDefinition one_shotR (Σ : gFunctors) (F : oFunctor) :=\n  csumR (exclR unitO) (agreeR $ laterO $ F (iPrePropO Σ) _).\nDefinition Pending {Σ F} : one_shotR Σ F := Cinl (Excl ()).\nDefinition Shot {Σ} {F : oFunctor} (x : F (iPropO Σ) _) : one_shotR Σ F :=\n  Cinr $ to_agree $ Next $ oFunctor_map F (iProp_fold, iProp_unfold) 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))) ].\nInstance 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 `{!heapG Σ, !barrierG Σ, !spawnG Σ, !oneShotG Σ F}.\nContext (N : namespace).\nLocal Notation X := (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 }} 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]\"); [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 bi.later_equivI /=.\n    rewrite -{2}[x]oFunctor_id -{2}[x']oFunctor_id.\n    assert (HF : oFunctor_map F (cid, cid) ≡ oFunctor_map F (iProp_fold (Σ:=Σ) ◎ 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_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  P -∗\n  {{ P }} fM #() {{ _, ∃ x, Φ x }} -∗\n  (∀ x, {{ Φ1 x }} fW1 #() {{ _, Ψ1 x }}) -∗\n  (∀ x, {{ Φ2 x }} fW2 #() {{ _, Ψ2 x }}) -∗\n  WP client fM fW1 fW2 {{ _, ∃ γ, barrier_res γ Ψ }}.\nProof using All.\n  iIntros \"/= HP #Hf #Hf1 #Hf2\"; rewrite /client.\n  iMod (own_alloc (Pending : one_shotR Σ F)) as (γ) \"Hγ\"; first done.\n  wp_lam. 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_apply (par_spec  (λ _, True)%I workers_post with \"[HP Hs Hγ] [Hr]\").\n  - wp_lam. wp_bind (fM #()). iApply (wp_wand with \"[HP]\"); [by iApply \"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_apply (par_spec (λ _, barrier_res γ Ψ1)%I\n                       (λ _, barrier_res γ Ψ2)%I with \"[H1] [H2]\").\n    + wp_apply (worker_spec with \"H1\"); auto.\n    + wp_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": "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/example_joining_existentials.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2614298886743156}}
{"text": "Set Warnings \"-notation-overridden\".\n\nRequire Import Category.Lib.\nRequire Import Category.Theory.Category.\n\nGeneralizable All Variables.\nSet Primitive Projections.\nSet Universe Polymorphism.\nUnset Transparent Obligations.\n\n(* This is the category with two objects and two parallel arrows between them\n   (and two identity morphisms):\n\n       --- f --->\n     x            y\n       --- g --->\n\n  This is used to build diagrams that identify equalizers. *)\n\nInductive ParObj : Type := ParX | ParY.\n\nInductive ParHom : bool -> ParObj -> ParObj -> Type :=\n  | ParIdX : ParHom true ParX ParX\n  | ParIdY : ParHom true ParY ParY\n  | ParOne : ParHom true ParX ParY\n  | ParTwo : ParHom false ParX ParY.\n\nDefinition ParHom_inv_t : forall b x y, ParHom b x y -> Prop.\nProof.\n  intros [] [] [] f.\n  exact (f = ParIdX).\n  exact (f = ParOne).\n  exact False.          (* Unused, any Prop is ok here *)\n  exact (f = ParIdY).\n  exact False.          (* Unused, any Prop is ok here *)\n  exact (f = ParTwo).\n  exact False.          (* Unused, any Prop is ok here *)\n  exact False.          (* Unused, any Prop is ok here *)\nDefined.\n\nCorollary ParHom_inv b x y f : ParHom_inv_t b x y f.\nProof. destruct f; reflexivity. Qed.\n\nLemma ParHom_Id_false_absurd : ∀ x, ParHom false x x -> False.\nProof. inversion 1. Qed.\n\nLocal Hint Extern 4 =>\n  match goal with\n    [ H : ParHom false ?X ?X |- _ ] =>\n    contradiction (ParHom_Id_false_absurd X H)\n  end : parallel_laws.\n\nLemma ParHom_Y_X_absurd : ∀ b, ParHom b ParY ParX -> False.\nProof. inversion 1. Qed.\n\nLocal Hint Extern 4 =>\n  match goal with\n    [ H : ParHom ?B ParY ParX |- _ ] =>\n    contradiction (ParHom_Y_X_absurd B H)\n  end : parallel_laws.\n\nLocal Ltac reduce :=\n  repeat match goal with\n  | [ H : ParObj |- _ ] => destruct H\n  | [ H : bool   |- _ ] => destruct H\n  end; auto.\n\nSet Transparent Obligations.\n\nProgram Definition Parallel : Category := {|\n  obj     := ParObj;\n  hom     := fun x y => ∃ b : bool, ParHom b x y;\n  (* Any hom that typechecks is valid. *)\n  homset  := fun x y =>\n    {| equiv := fun (f g : ∃ b : bool, ParHom b x y) => ``f = ``g |};\n  id      := fun x => match x with\n    | ParX => (true; ParIdX)\n    | ParY => (true; ParIdY)\n    end;\n  compose := fun x y z (f : ∃ b : bool, ParHom b y z)\n                       (g : ∃ b : bool, ParHom b x y) =>\n    match x, y, z with\n    | ParX, ParX, ParX => (true; ParIdX)\n    | ParY, ParY, ParY => (true; ParIdY)\n    | ParX, ParY, ParY => _\n    | ParX, ParX, ParY => _\n    | _,    _,    _    => _\n    end\n|}.\nNext Obligation. equivalence; reduce. Qed.\nNext Obligation. exact (f; X0). Defined.\nNext Obligation. reduce; intuition. Qed.\nNext Obligation. intuition; discriminate. Qed.\nNext Obligation. intuition; discriminate. Qed.\nNext Obligation. intuition; discriminate. Qed.\nNext Obligation.\n  proper.\n  destruct x, y, z; simpl in *; intuition.\nDefined.\nNext Obligation.\n  destruct x, y; simpl in *;\n  destruct f; intuition.\nQed.\nNext Obligation.\n  destruct x, y; simpl in *;\n  destruct f; intuition.\nQed.\nNext Obligation.\n  destruct x, y, z, w; simpl in *;\n  destruct f; intuition.\nQed.\nNext Obligation.\n  destruct x, y, z, w; simpl in *;\n  destruct f; intuition.\nQed.\n\nRequire Import Category.Theory.Functor.\n\nProgram Definition APair {C : Category} {x y : C} (f g : x ~> y) :\n  Parallel ⟶ C := {|\n  fobj := fun z => match z with\n    | ParX => x\n    | ParY => y\n    end;\n  fmap := fun z w h => match z, w with\n    | ParX, ParX => id[x]\n    | ParY, ParY => id[y]\n    | ParX, ParY =>\n      match ``h with\n      | true  => f\n      | false => g\n      end\n    | ParY, ParX => False_rect _ (ParHom_Y_X_absurd _ (projT2 h))\n    end\n|}.\nNext Obligation. proper; reduce; simpl; intuition. Qed.\nNext Obligation. destruct x0; simpl; cat. Qed.\nNext Obligation.\n  destruct x0, y0, z; simpl; auto with parallel_laws; cat.\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/category-theory/Instance/Parallel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.26142988318615396}}
{"text": "Definition default_foldable {f:Type -> Type}\n  (foldMap : forall m a, forall (S : GHC.Base.Semigroup m) (M : GHC.Base.Monoid m), (a -> m) -> f a -> m)\n  (foldr : forall a b, (a -> b -> b) -> b -> f a -> b):=\n  let foldl : forall b a, (b -> a -> b) -> b -> f a -> b :=\n      (fun b a =>\n         fun f  z t => Data.SemigroupInternal.appEndo\n                    (Data.SemigroupInternal.getDual\n                       (foldMap _ _ _ _ (Coq.Program.Basics.compose\n                                   Data.SemigroupInternal.Mk_Dual\n                                   (Coq.Program.Basics.compose\n                                      Data.SemigroupInternal.Mk_Endo\n                                      (GHC.Base.flip f))) t)) z)\n  in\n  let foldl' : forall b a, (b -> a -> b) -> b -> f a -> b :=\n      (fun {b} {a} =>\n         fun f  z0  xs =>\n           let f' :=  fun  x  k  z => GHC.Base.op_zdzn__ k (f z x)\n           in foldr _ _ f' GHC.Base.id xs z0)\n  in\n  Foldable__Dict_Build\n    f\n    (* fold *)\n    (fun m (S : GHC.Base.Semigroup m) (M : GHC.Base.Monoid m) => foldMap _ _ _ _ GHC.Base.id)\n    (* foldMap *)\n    (@foldMap)\n    (* foldl *)\n    (@foldl)\n    (* foldl' *)\n    (@foldl')\n    (* foldr  *)\n    (@foldr)\n    (* foldr' *)\n    (fun a b f z0 xs =>\n       let f' := fun k  x  z => GHC.Base.op_zdzn__ k (f x z)\n       in\n       @foldl _ _ f' GHC.Base.id xs z0)\n    (* length *)\n    (fun a => @foldl' _ a (fun c  _ => GHC.Num.op_zp__ c (GHC.Num.fromInteger 1))\n                    (GHC.Num.fromInteger 0))\n    (* null *)\n    (fun a => @foldr _ _ (fun arg_61__ arg_62__ => false) true)\n    (* product *)\n    (fun a `{GHC.Num.Num a} =>\n       Coq.Program.Basics.compose Data.SemigroupInternal.getProduct\n                                  (foldMap _ _ _ _ Data.SemigroupInternal.Mk_Product))\n    (* sum *)\n    (fun a `{GHC.Num.Num a} =>\n       Coq.Program.Basics.compose Data.SemigroupInternal.getSum\n                                  (foldMap _ _ _ _ Data.SemigroupInternal.Mk_Sum))\n    (* toList *)\n    (fun a => fun t => GHC.Base.build (fun _ c n => @foldr _ _ c n t)).\n\nDefinition default_foldable_foldMap {f : Type -> Type}\n  (foldMap : forall {m} {a}, forall `{GHC.Base.Monoid m}, (a -> m) -> f a -> m)\n :=\n  let foldr : forall {a} {b}, (a -> b -> b) -> b -> f a -> b :=\n  fun a b f z t =>\n    Data.SemigroupInternal.appEndo\n      (foldMap\n         (Coq.Program.Basics.compose Data.SemigroupInternal.Mk_Endo f) t) z\n  in\n  default_foldable (fun {m}{a} `{GHC.Base.Monoid m} => foldMap) foldr.\n\nDefinition default_foldable_foldr (f : Type -> Type)\n  (foldr : forall {a} {b}, (a -> b -> b) -> b -> f a -> b) :=\n  let foldMap :  forall {m} {a} `{GHC.Base.Monoid m}, (a -> m) -> f a -> m :=\n  fun m a (S : GHC.Base.Semigroup m) (H : GHC.Base.Monoid m) =>\n    fun f => foldr\n            (Coq.Program.Basics.compose GHC.Base.mappend\n                                        f) GHC.Base.mempty\n  in\n  default_foldable foldMap (fun {a} {b} => foldr).\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/base-src/module-edits/Data/Foldable/midamble.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.26142413458647595}}
{"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\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 [ 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 (Memory.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": "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_object.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2613847013368871}}
{"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 _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 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": "riscv", "repo": "sail-riscv", "sha": "56a15cf76a416b9ad51de947607ca2c8879d68d3", "save_path": "github-repos/coq/riscv-sail-riscv", "path": "github-repos/coq/riscv-sail-riscv/sail-riscv-56a15cf76a416b9ad51de947607ca2c8879d68d3/prover_snapshots/coq/duopod/riscv_duopod.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.26138470133688707}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import Coq.Lists.List.\nRequire Import Coq.ZArith.ZArith.\nRequire Import RBTree.AuxiliaryTac.\nRequire Import RBTree.api_spec2.\nRequire Import Coq.Logic.Classical.\nImport ListNotations.\nLocal Open Scope Z.\n\n\nModule insertBalance.\nDefinition insert_balance_spec :=\n  DECLARE _insert_balance\n  WITH t_initial: tree, \n       root: val,\n       p_par_initial: val,\n       b_initial: val, \n       ls_initial: partial_tree\n  PRE [ tptr (tptr t_struct_tree), \n        tptr (tptr t_struct_tree) ]\n    PROP (t_initial <> E)\n    PARAMS (b_initial; root) \n    SEP (treebox_rep t_initial b_initial p_par_initial; \n         partial_treebox_rep ls_initial root b_initial \n           p_par_initial nullval) (* 应当清楚: partial_treebox_rep 记录了以b为根的树的补集的所有值&一阶指针信息, 以及b的二级指针 *)\n  POST [ Tvoid ]\n    EX t_balanced: tree, \n    EX ls_balanced: partial_tree, \n    EX b_balanced: val, \n    EX p_par_balanced: val,\n    PROP ((ls_balanced, t_balanced) = balance' ls_initial t_initial)\n    RETURN ()\n    SEP (treebox_rep t_balanced b_balanced p_par_balanced; \n         partial_treebox_rep ls_balanced root b_balanced \n           p_par_balanced nullval).\n\nDefinition Gprog : funspecs :=\n         ltac:(with_library prog [\n           makeBlack.make_black_spec; getColor1.get_color1_spec; getColor2.get_color2_spec;\n             leftRotate.left_rotate_spec; leftRotateWrap.left_rotate_wrap_spec;\n             rightRotate.right_rotate_spec; rightRotateWrap.right_rotate_wrap_spec;\n             insert_balance_spec ]).\n\nLemma body_insert_balance: semax_body Vprog Gprog\n                                    f_insert_balance insert_balance_spec.\nProof.\n  start_function.\n  unfold treebox_rep.\n  Intros p_initial.\n  destruct t_initial eqn:t_init_fact; [congruence|].\n  (* T t1 n t2 <> E *)\n  expand rbtree_rep.\n  Intros p_init_l p_init_r.\n  forward. (* struct tree * p = *t *)\n  forward_loop (\n    EX t_med: tree,\n    EX ls_med: partial_tree,\n    EX b_med: val,\n    EX p_par_med: val,\n    EX p_med: val,\n      PROP ( t_initial <> E; p_med <> nullval; (*^*)\n             balance' ls_med t_med = balance' ls_initial t_initial )\n      LOCAL (temp _p p_med;(*  temp _t b_med; *) temp _root root)\n      SEP ( data_at Tsh (tptr t_struct_tree) p_med b_med;\n            rbtree_rep t_med p_med p_par_med;\n            partial_treebox_rep ls_med root b_med \n              p_par_med nullval)\n  ).\n  + (* 前条件满足不变量 *)\n    Exists t_initial ls_initial b_initial p_par_initial p_initial.\n    entailer!.\n    expand rbtree_rep.\n    Exists p_init_l p_init_r.\n    entailer!.\n  + Intros tree_med ls_med b_med p_par_med p_med. (* 这些带有\"med\"的变量是循环不变量处<即此处>引入的, 用以和后续引入的变量区分 *)\n    destruct tree_med as [|lch node_med rch] eqn:Etree_med.\n    ++ (* tree_med = [] => p_med=nullval. 与^矛盾*)\n       expand rbtree_rep.\n       assert_PROP False by entailer!.\n       contradiction.\n    ++ (* \"tree_med =  T lch node_med rch\" => p_med<>nullval 保证了\"p_med有非空子树\" *)\n       expand rbtree_rep.\n       Intros p_lch p_rch.\n       forward.  (* p_par = p->par; *)\n       destruct ls_med eqn:Els_med.\n       - (* ls_med = [] => p_par_med = nullval *) (* \"没有父亲 => 矛盾\" *)\n         expand partial_treebox_rep.\n         assert_PROP (p_par_med = nullval) by entailer!.\n         assert_PROP (b_med = root) by entailer!.\n         forward_call(p_par_med, nullval, p_lch, p_rch, node_med, false). (* calculate get_color1(p_par) *)\n         { entailer!. }\n         tauto.\n         forward_if. (* if (get_color(p_par) != RED) *)\n         -- (* get_color(p_par) != RED *)\n            forward.\n            Exists (T lch node_med rch) (@nil half_tree) root nullval.\n            entailer!.\n            unfold partial_treebox_rep, treebox_rep.\n            Exists p_med.\n            entailer!.\n            expand rbtree_rep.\n            Exists p_lch p_rch.\n            entailer!.\n         -- (* get_color(p_par) = RED => contradiction *)\n            assert_PROP False by entailer!.\n            contradiction.\n       - (* \"ls_med = h :: p\" *) (* \"有父亲节点\" *)\n         destruct h as [[L_or_R node_par] Tree_Lsib_Or_Rsib] eqn:Ehalf_par.\n         destruct L_or_R.\n         rename p into part_par.\n         * (* \"ls_med = (L, node_par, tree_lsib) :: part_par\" *) (* \"\"\"p为右子树\"\"\" *)\n           rename Tree_Lsib_Or_Rsib into tree_lsib.\n           remember (T tree_lsib node_par tree_med) as tree_par.\n           expand partial_treebox_rep.\n           Intros p_gpar p_lsib b_par.\n           assert_PROP (p_par_med <> nullval) by entailer!. (* \"p_par_med <> nullval\" *)\n           forward_call(p_par_med, p_gpar, p_lsib, p_med, node_par, true). (* get_color1(p_par) *)\n           { entailer!. (* 满足前条件 *)\n             entailer!.\n             unfold_data_at (data_at _ t_struct_tree _ p_par_med).\n             entailer!. }\n           { split; congruence. }\n           destruct (color_of_node node_par) eqn:Ecolor_par.\n           2: { (* color_par = Black *) (* \"父亲的颜色是黑色, 情况平凡\" *)\n                unfold Col2Z at 1 2.\n                forward_if; (* if (get_color(p_par) != RED) *)\n                   [|assert_PROP False by entailer!; contradiction].\n                forward.  (* return *)\n                Exists (T lch node_med rch) \n                       ((L, node_par, tree_lsib) :: part_par)\n                       (field_address t_struct_tree [StructField _right] p_par_med)\n                       p_par_med.\n                expand treebox_rep.\n                expand partial_treebox_rep.\n                Exists p_med p_gpar p_lsib b_par.\n                expand rbtree_rep.\n                Exists p_lch p_rch.\n                entailer!.\n                { rewrite <- H3.\n                  expand balance'.\n                  rewrite Ecolor_par.\n                  destruct part_par; [auto|].\n                  destruct h as [[? ?] ?]; auto. }\n                unfold_data_at (data_at Tsh t_struct_tree _ p_par_med).\n                entailer!.\n                rewrite Ecolor_par.\n                unfold Col2Z.\n                entailer!.\n               }\n           ** (* \"Ecolor_par : color_of_node node_par = Red\" *) (* \"父亲的颜色是红色\" *)\n              unfold Col2Z at 1 2.\n              forward_if. (* if (get_color(p_par) != RED) *)\n              { congruence. } (* get_color(p_par) != RED => contradiction *)\n              forward. (* p_gpar = p_par->par; *)\n              destruct part_par eqn:Epart_par.\n              *** (* part_par = [] => p_gpar = p_top = nullval *) (* \"没有祖父节点, 情况平凡\" *)\n                  expand partial_treebox_rep.\n                  assert_PROP (p_gpar = nullval) by entailer!.\n                  assert_PROP (b_par = root) by entailer!. \n                  forward_if. (* if (p_gpar == NULL) *)\n                  2: { congruence. }\n                  forward. (* p_gpar = NULL; return! *)\n                  rewrite <- H3.\n                  Exists (T lch node_med rch)\n                         [(L, node_par, tree_lsib)]\n                         (field_address t_struct_tree [StructField _right] p_par_med)\n                         p_par_med. \n                  entailer!.\n                  expand treebox_rep.\n                  Exists p_med.\n                  expand partial_treebox_rep.\n                  Exists nullval p_lsib b_par.\n                  expand rbtree_rep.\n                  Exists p_lch p_rch.\n                  unfold_data_at (data_at _ t_struct_tree _ p_par_med).\n                  rewrite Ecolor_par.\n                  entailer!.\n              *** (* part_par = h0 :: l => p_gpar <> nullval *) (* \"有祖父节点\" *)\n                  destruct h0 as [[L_or_R node_gpar] Tree_Lunc_Or_Runc] eqn:Ehalf_gpar.\n                  destruct L_or_R.\n                  rename l into part_gpar.\n                  +++ (* part_par = (L, node_gpar, Tree_Lunc_Or_Runc) :: part_gpar *) (* \"\"\"p_par为右子树\"\"\" *)\n                      rename Tree_Lunc_Or_Runc into tree_lunc.\n                      remember (T tree_lunc node_gpar tree_par) as tree_gpar.\n                        (* tree_gpar = T tree_lunc node_gpar tree_par *)\n                      expand partial_treebox_rep.\n                      Intros p_ggpar p_lunc b_gpar.\n                      assert_PROP (p_gpar <> nullval) by entailer!. (* \"p_gpar <> nullval\" *)\n                      gather_SEP 5 7 8 9 10 11.\n                      replace_SEP 0 (\n                        data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node node_gpar))),\n                                                   (Vint (Int.repr (key_of_node node_gpar)),\n                                                    (Vint (Int.repr (value_of_node node_gpar)),\n                                                     (p_lunc, (p_par_med, p_ggpar))))) p_gpar\n                      ).\n                      { entailer!.\n                        unfold_data_at (data_at _ t_struct_tree _ p_gpar).\n                        entailer!. }\n                      forward_if. (* if (p_gpar == NULL) *)\n                      { congruence. }\n                      forward. (* calculate p_gpar->left *)\n                      forward_if_wrp. (* if (p_par == p_gpar->left) *)\n                      --- (* p_par == p_gpar->left => p_par = p_lunc => contradiction! *)\n                          destruct tree_lunc as [|tree_lunc_l node_lunc tree_lunc_r] eqn:ETree_lunc.\n                          { expand rbtree_rep.\n                            assert_PROP False by entailer!.\n                            contradiction. }\n                          { expand rbtree_rep. (* tree_lunc = T tree_lunc_l node_lunc tree_lunc_r *)\n                            Intros p_lunc_l p_lunc_r.\n                            assert_PROP False.\n                            { focus_SEP 1. (* 调换位置 *)\n                              sep_apply data_at_conflict; auto.\n                              entailer!. }\n                            contradiction. }\n                      --- (* \"p_par == p_gpar->right\" *)\n                          forward. (* calculate p_gpar->left *)\n                          \n                          destruct tree_lunc as [|tree_lunc_l node_lunc tree_lunc_r] eqn:ETree_lunc.\n                          ++++ (* \"tree_lunc = E\" *)\n                               expand rbtree_rep.\n                               assert_PROP (p_lunc = nullval) by entailer!.\n                               \n(* DECLARE _get_color2\n  WITH t: tree,\n       p: val,\n       p_par: val,\n       b: bool *)\n  (* (b = false <-> p = nullval)  *)                            \n                               \n                               forward_call( (* get_color2(p_gpar->left) *)\n                                 tree_lunc, p_lunc, p_gpar, false\n                               ). \n                               { entailer!. } (* 满足前条件 *)\n                               { tauto. }\n                               forward_if. (* if (get_color2(p_gpar->left) == RED) *)\n                               { contradiction. }\n                               forward. (* p_gpar->color = RED; *)\n                               forward. (* cal p_gpar->right *)\n                               forward_if_wrp. (* if (p == p_par->left) *)\n                               **** (* p = p_par->left => p = p_lisb => contradiction *)\n                                    destruct tree_lsib as [|tree_lsib_l node_lsib tree_lsib_r] eqn:ETree_lsib.\n                                    { expand rbtree_rep.\n                                      assert_PROP False by entailer!.\n                                      contradiction. }\n                                    { expand rbtree_rep.\n                                        Intros p_lunc_l p_lunc_r.\n                                        assert_PROP False. \n                                        { focus_SEP 3. (* 调换位置 *)\n                                          sep_apply data_at_conflict; auto.\n                                          entailer!. }\n                                        contradiction. }\n                               **** (* \"p = p_par->right\" *)\n                                    forward. (* p_par->color = BLACK; *)\n                                    destruct part_gpar eqn:Egpart_par. (* 讨论gpar是否有父亲 目的是确定根节点是不是gpar *)\n                                    +++++ (* part_gpar = [] *) (* gpar 是根节点 *)\n                                          expand partial_treebox_rep.\n                                          assert_PROP (p_ggpar = nullval) by entailer!.\n                                          assert_PROP (b_gpar = root) by entailer!.\n                                          (* call: left_rotate_wrap(p_gpar, root) *)\n                                          forward_call(\n                                            p_gpar, p_par_med, p_ggpar, p_lsib,\n                                            p_lunc, p_med, p_gpar, nullval, \n                                            RedNode node_gpar, BlackNode node_par,\n                                            tree_lunc, tree_med, tree_lsib,\n                                            root, false,\n                                            false, nullval, nullval, node_par, (* 此行无用 *)\n                                            true, E (* 此行无用 *)\n                                          ).\n                                          { entailer!. (* 满足前条件 *)\n                                            expand partial_tree_rep.\n                                            expand rbtree_rep.\n                                            Exists p_lch p_rch.\n                                            entailer!. }\n                                          { repeat split; try tauto; (* 满足前条件 *)\n                                            subst; auto. }\n                                          forward.\n                                          remember (T lch node_med rch) as tree_med.\n                                          Exists (T (T E (RedNode node_gpar) tree_lsib)\n                                                    (BlackNode node_par)\n                                                    tree_med) \n                                                 (@nil half_tree)\n                                                 root nullval.\n                                          rewrite <- H3.\n                                          expand balance'.\n                                          rewrite Ecolor_par.\n                                          unfold l_rotate.\n                                          expand rbtree_rep.\n                                          expand partial_treebox_rep.\n                                          entailer!.\n                                          expand treebox_rep.\n                                          Exists p_par_med.\n                                          entailer!.\n                                          remember (T lch node_med rch) as tree_med.\n                                          expand rbtree_rep.\n                                          Exists p_gpar p_med nullval p_lsib.\n                                          entailer!.\n                                    +++++ (* part_gpar = h1 :: l *) (* gpar 不是根节点 *)\n                                          destruct h1 as [[LR node_ggpar] Tree_ggpl_Or_ggpr] eqn:Ehalf_ggpar.\n                                          assert_PROP (p_ggpar <> nullval). {\n                                            destruct LR; expand partial_treebox_rep; Intros a b c; entailer!. }\n                                          destruct LR; expand partial_treebox_rep;\n                                          Intros p_gggpar p_ggpl_or_r b_ggpar;\n                                          assert_PROP(is_pointer_or_null p_ggpar) by entailer!;\n                                          assert_PROP(is_pointer_or_null p_ggpl_or_r) by entailer!.\n                                          ----\n                                            rename Tree_ggpl_Or_ggpr into tree_ggpl.\n                                            rename p_ggpl_or_r into p_ggpl.\n                                            rewrite partial_treebox_rep''.\n                                            destruct (rev l) eqn:El.\n                                            (* El : rev l = [] *)\n                                            { assert (l = [])by (apply rev_nil_elim in El; auto).\n                                              assert_PROP (p_gggpar = nullval /\\ root = b_ggpar). \n                                              { expand partial_treebox_rep_topdown. entailer!. }\n                                              expand partial_treebox_rep_topdown.\n                                              pose proof classic (p_ggpl <> p_gpar).\n                                              destruct H25.\n                                              destruct H26. \n                                              2:{ assert(p_ggpl = p_gpar) by tauto.\n                                                  destruct tree_ggpl; simpl.\n                                                  { assert_PROP (p_ggpl = nullval) by entailer!.\n                                                    subst. congruence. }\n                                                  Intros a b. subst.\n                                                  assert_PROP False;[|contradiction].\n                                                  focus_SEP 1.\n                                                  sep_apply data_at_conflict;auto.\n                                                  entailer!. }\n                                              (* p_ggpl <> p_gpar *)\n                                              destruct tree_ggpl as[|? ? ?] eqn:Tree.\n                                              -----\n                                                expand rbtree_rep.\n                                                forward_call(\n                                                     p_gpar, p_par_med, p_ggpar, p_lsib,\n                                                     p_lunc, p_med, p_ggpar, nullval, \n                                                     RedNode node_gpar, BlackNode node_par,\n                                                     tree_lunc, tree_med, tree_lsib,\n                                                     root, true,\n                                                     false, p_gggpar, p_ggpl, node_ggpar,\n                                                     true, E).\n                                                { entailer!. expand rbtree_rep.\n                                                  Exists p_lch p_rch; entailer!.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!. }\n                                                { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                forward.\n                                                remember (T lch node_med rch) as tree_med.\n                                                rewrite <- H3.\n                                                Exists (T (T E (RedNode node_gpar) tree_lsib) (BlackNode node_par) tree_med)\n                                                       [(L, node_ggpar, E)]\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                expand balance'.\n                                                rewrite Ecolor_par.\n                                                unfold l_rotate.\n                                                expand rbtree_rep.\n                                                expand partial_treebox_rep.\n                                                Exists nullval nullval b_ggpar.\n                                                expand treebox_rep.\n                                                Exists p_par_med.\n                                                unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                entailer.\n                                                remember (T lch node_med rch) as tree_med.\n                                                expand rbtree_rep.\n                                                Exists p_gpar p_med nullval p_lsib.\n                                                entailer!.\n                                              -----\n                                                rewrite <- Tree.\n                                                forward_call(\n                                                     p_gpar, p_par_med, p_ggpar, p_lsib,\n                                                     p_lunc, p_med, p_ggpar, nullval, \n                                                     RedNode node_gpar, BlackNode node_par,\n                                                     tree_lunc, tree_med, tree_lsib,\n                                                     root, true,\n                                                     false, p_gggpar, p_ggpl, node_ggpar,\n                                                     false, tree_ggpl).\n                                                { entailer!. \n                                                  remember ((T t3 n0 t4)) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  Exists p_lch p_rch; entailer!.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!. }\n                                                { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                forward.\n                                                remember (T lch node_med rch) as tree_med.\n                                                remember (T t3 n0 t4) as tree_ggpl.\n                                                rewrite <- H3.\n                                                Exists (T (T E (RedNode node_gpar) tree_lsib) (BlackNode node_par) tree_med)\n                                                       [(L, node_ggpar, tree_ggpl)]\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                expand balance'.\n                                                rewrite Ecolor_par.\n                                                unfold l_rotate.\n                                                expand rbtree_rep.\n                                                expand partial_treebox_rep.\n                                                Exists nullval p_ggpl b_ggpar.\n                                                expand treebox_rep.\n                                                Exists p_par_med.\n                                                unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                entailer!.\n                                                remember (T lch node_med rch) as tree_med.\n                                                remember (T t3 n0 t4) as tree_ggpl.\n                                                expand rbtree_rep.\n                                                Exists p_gpar p_med nullval p_lsib.\n                                                entailer!.\n                                              }  \n                                          (* El : rev l = h2 :: l0 *)\n                                            { pose proof classic (p_ggpl <> p_gpar).\n                                              destruct H24. \n                                              2:{ assert(p_ggpl = p_gpar) by tauto.\n                                                  destruct tree_ggpl; simpl.\n                                                  { assert_PROP (p_ggpl = nullval) by entailer!.\n                                                    subst. congruence. }\n                                                  Intros a b. subst.\n                                                  assert_PROP False;[|contradiction].\n                                                  focus_SEP 1.\n                                                  sep_apply data_at_conflict;auto.\n                                                  entailer!. }\n                                              destruct h2 as [[LR_ans node_ans] tree_ans_another_child].\n                                              expand partial_treebox_rep_topdown.\n                                              destruct LR_ans. \n                                              -----\n                                                Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpl as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpl = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_gpar, p_par_med, p_ggpar, p_lsib,\n                                                       p_lunc, p_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_par,\n                                                       tree_lunc, tree_med, tree_lsib,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  Exists (T (T E (RedNode node_gpar) tree_lsib)\n                                                          (BlackNode node_par)\n                                                          tree_med) \n                                                       ((L, node_ggpar, E) :: l)\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold l_rotate.\n                                                  expand rbtree_rep.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_med nullval p_lsib.\n                                                  entailer!.\n                                                ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_gpar, p_par_med, p_ggpar, p_lsib,\n                                                       p_lunc, p_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_par,\n                                                       tree_lunc, tree_med, tree_lsib,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       false, tree_ggpl).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  remember (T t3 n0 t4) as tree_ggpl.\n                                                  Exists (T (T E (RedNode node_gpar) tree_lsib)\n                                                          (BlackNode node_par)\n                                                          tree_med) \n                                                       ((L, node_ggpar, tree_ggpl) :: l)\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold l_rotate.\n                                                  expand rbtree_rep.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpl b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  remember (T t3 n0 t4) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_med nullval p_lsib.\n                                                  entailer!.\n                                              -----\n                                                Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpl as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpl = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_gpar, p_par_med, p_ggpar, p_lsib,\n                                                       p_lunc, p_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_par,\n                                                       tree_lunc, tree_med, tree_lsib,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  Exists (T (T E (RedNode node_gpar) tree_lsib)\n                                                          (BlackNode node_par)\n                                                          tree_med) \n                                                       ((L, node_ggpar, E) :: l)\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold l_rotate.\n                                                  expand rbtree_rep.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_med nullval p_lsib.\n                                                  entailer!.\n                                                ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_gpar, p_par_med, p_ggpar, p_lsib,\n                                                       p_lunc, p_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_par,\n                                                       tree_lunc, tree_med, tree_lsib,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       false, tree_ggpl).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  remember (T t3 n0 t4) as tree_ggpl.\n                                                  Exists (T (T E (RedNode node_gpar) tree_lsib)\n                                                          (BlackNode node_par)\n                                                          tree_med) \n                                                       ((L, node_ggpar, tree_ggpl) :: l)\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold l_rotate.\n                                                  expand rbtree_rep.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpl b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  remember (T t3 n0 t4) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_med nullval p_lsib.\n                                                  entailer!.\n                                            }\n                                          ----\n                                            rename Tree_ggpl_Or_ggpr into tree_ggpr.\n                                            rename p_ggpl_or_r into p_ggpr.\n                                            rewrite partial_treebox_rep''.\n                                            destruct (rev l) eqn:El.\n                                            (* El : rev l = [] *)\n                                            { assert (l = [])by (apply rev_nil_elim in El; auto).\n                                              assert_PROP (p_gggpar = nullval /\\ root = b_ggpar). \n                                              { expand partial_treebox_rep_topdown. entailer!. }\n                                              expand partial_treebox_rep_topdown.\n                                              pose proof classic (p_ggpr <> p_gpar).\n                                              destruct H25.\n                                              destruct H26. \n                                              2:{ assert(p_ggpr = p_gpar) by tauto.\n                                                  destruct tree_ggpr; simpl.\n                                                  { assert_PROP (p_ggpr = nullval) by entailer!.\n                                                    subst. congruence. }\n                                                  Intros a b. subst.\n                                                  assert_PROP False;[|contradiction].\n                                                  focus_SEP 1.\n                                                  sep_apply data_at_conflict;auto.\n                                                  entailer!. }\n                                              (* p_ggpr <> p_gpar *)\n                                              destruct tree_ggpr as[|? ? ?] eqn:Tree.\n                                              -----\n                                                expand rbtree_rep.\n                                                forward_call(\n                                                     p_gpar, p_par_med, p_ggpar, p_lsib,\n                                                     p_lunc, p_med, p_ggpar, nullval, \n                                                     RedNode node_gpar, BlackNode node_par,\n                                                     tree_lunc, tree_med, tree_lsib,\n                                                     root, true,\n                                                     true, p_gggpar, p_ggpr, node_ggpar,\n                                                     true, E).\n                                                { entailer!. expand rbtree_rep.\n                                                  Exists p_lch p_rch; entailer!.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!. }\n                                                { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                forward.\n                                                remember (T lch node_med rch) as tree_med.\n                                                rewrite <- H3.\n                                                Exists (T (T E (RedNode node_gpar) tree_lsib) (BlackNode node_par) tree_med)\n                                                       [(R, node_ggpar, E)]\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                expand balance'.\n                                                rewrite Ecolor_par.\n                                                unfold l_rotate.\n                                                expand rbtree_rep.\n                                                expand partial_treebox_rep.\n                                                Exists nullval nullval b_ggpar.\n                                                expand treebox_rep.\n                                                Exists p_par_med.\n                                                unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                entailer.\n                                                remember (T lch node_med rch) as tree_med.\n                                                expand rbtree_rep.\n                                                Exists p_gpar p_med nullval p_lsib.\n                                                entailer!.\n                                              -----\n                                                rewrite <- Tree.\n                                                forward_call(\n                                                     p_gpar, p_par_med, p_ggpar, p_lsib,\n                                                     p_lunc, p_med, p_ggpar, nullval, \n                                                     RedNode node_gpar, BlackNode node_par,\n                                                     tree_lunc, tree_med, tree_lsib,\n                                                     root, true,\n                                                     true, p_gggpar, p_ggpr, node_ggpar,\n                                                     false, tree_ggpr).\n                                                { entailer!. \n                                                  remember ((T t3 n0 t4)) as tree_ggpr.\n                                                  expand rbtree_rep.\n                                                  Exists p_lch p_rch; entailer!.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!. }\n                                                { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                forward.\n                                                remember (T lch node_med rch) as tree_med.\n                                                remember (T t3 n0 t4) as tree_ggpr.\n                                                rewrite <- H3.\n                                                Exists (T (T E (RedNode node_gpar) tree_lsib) (BlackNode node_par) tree_med)\n                                                       [(R, node_ggpar, tree_ggpr)]\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                expand balance'.\n                                                rewrite Ecolor_par.\n                                                unfold l_rotate.\n                                                expand rbtree_rep.\n                                                expand partial_treebox_rep.\n                                                Exists nullval p_ggpr b_ggpar.\n                                                expand treebox_rep.\n                                                Exists p_par_med.\n                                                unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                entailer!.\n                                                remember (T lch node_med rch) as tree_med.\n                                                remember (T t3 n0 t4) as tree_ggpr.\n                                                expand rbtree_rep.\n                                                Exists p_gpar p_med nullval p_lsib.\n                                                entailer!.\n                                              }  \n                                          (* El : rev l = h2 :: l0 *)\n                                            { pose proof classic (p_ggpr <> p_gpar).\n                                              destruct H24. \n                                              2:{ assert(p_ggpr = p_gpar) by tauto.\n                                                  destruct tree_ggpr; simpl.\n                                                  { assert_PROP (p_ggpr = nullval) by entailer!.\n                                                    subst. congruence. }\n                                                  Intros a b. subst.\n                                                  assert_PROP False;[|contradiction].\n                                                  focus_SEP 1.\n                                                  sep_apply data_at_conflict;auto.\n                                                  entailer!. }\n                                              destruct h2 as [[LR_ans node_ans] tree_ans_another_child].\n                                              expand partial_treebox_rep_topdown.\n                                              destruct LR_ans. \n                                              -----\n                                                Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpr as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpr = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_gpar, p_par_med, p_ggpar, p_lsib,\n                                                       p_lunc, p_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_par,\n                                                       tree_lunc, tree_med, tree_lsib,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpr, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  Exists (T (T E (RedNode node_gpar) tree_lsib)\n                                                          (BlackNode node_par)\n                                                          tree_med) \n                                                       ((R, node_ggpar, E) :: l)\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold l_rotate.\n                                                  expand rbtree_rep.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_med nullval p_lsib.\n                                                  entailer!.\n                                                ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_gpar, p_par_med, p_ggpar, p_lsib,\n                                                       p_lunc, p_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_par,\n                                                       tree_lunc, tree_med, tree_lsib,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpr, node_ggpar,\n                                                       false, tree_ggpr).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  remember (T t3 n0 t4) as tree_ggpr.\n                                                  Exists (T (T E (RedNode node_gpar) tree_lsib)\n                                                          (BlackNode node_par)\n                                                          tree_med) \n                                                       ((R, node_ggpar, tree_ggpr) :: l)\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold l_rotate.\n                                                  expand rbtree_rep.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpr b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  remember (T t3 n0 t4) as tree_ggpr.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_med nullval p_lsib.\n                                                  entailer!.\n                                              -----\n                                                Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpr as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpr = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_gpar, p_par_med, p_ggpar, p_lsib,\n                                                       p_lunc, p_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_par,\n                                                       tree_lunc, tree_med, tree_lsib,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpr, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  Exists (T (T E (RedNode node_gpar) tree_lsib)\n                                                          (BlackNode node_par)\n                                                          tree_med) \n                                                       ((R, node_ggpar, E) :: l)\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold l_rotate.\n                                                  expand rbtree_rep.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_med nullval p_lsib.\n                                                  entailer!.\n                                                ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_gpar, p_par_med, p_ggpar, p_lsib,\n                                                       p_lunc, p_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_par,\n                                                       tree_lunc, tree_med, tree_lsib,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpr, node_ggpar,\n                                                       false, tree_ggpr).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  remember (T t3 n0 t4) as tree_ggpr.\n                                                  Exists (T (T E (RedNode node_gpar) tree_lsib)\n                                                          (BlackNode node_par)\n                                                          tree_med) \n                                                       ((R, node_ggpar, tree_ggpr) :: l)\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold l_rotate.\n                                                  expand rbtree_rep.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpr b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  remember (T t3 n0 t4) as tree_ggpr.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_med nullval p_lsib.\n                                                  entailer!.\n                                              }\n                          ++++ (* \"tree_lunc = T tree_lunc_l node_lunc tree_lunc_r\" *)\n                               assert_PROP (p_lunc <> nullval).\n                               { expand rbtree_rep; Intros a b; entailer!. }\n                               destruct (color_of_node node_lunc) eqn: color_lunc.\n                               ---- (* \"lunc is RED\" *)\n(* DECLARE _get_color2\n  WITH t: tree,\n       p: val,\n       p_par: val,\n       b: bool *)\n  (* (b = false <-> p = nullval)  *) \n                                 forward_call( (* get_color2(p_gpar->left) *)\n                                   tree_lunc, p_lunc, p_gpar, true\n                                 ). \n                                 { entailer!. } (* 满足前条件 *)\n                                 { tauto. }\n                                 rewrite ETree_lunc, color_lunc.\n                                 unfold Col2Z at 1. (*  , RED_COLOR, BLACK_COLOR. *)\n                                 forward_if. (* if (get_color2(p_gpar->left) == RED) *)\n                                 2: { assert_PROP False by entailer!; tauto. }\n                                 forward.\n                                 forward.\n                                 expand rbtree_rep.\n                                 Intros p_lunc_l p_lunc_r.\n                                 forward.\n                                 forward.\n                                 forward.\n                                 Exists (T (makeBlack tree_lunc) (RedNode node_gpar)\n                                         (T tree_lsib (BlackNode node_par) tree_med))\n                                   part_gpar\n                                   b_gpar\n                                   p_ggpar\n                                   p_gpar.\n                                 rewrite <- H3.\n                                 expand balance'.\n                                 rewrite Ecolor_par.\n                                 expand rbtree_rep.\n                                 Exists p_lunc p_par_med p_lsib p_med.\n                                 entailer!.\n                                 2:{ unfold makeBlack. expand rbtree_rep. \n                                     Exists p_lunc_l p_lunc_r p_lch p_rch.\n                                     entailer!. } \n                                 simpl (color_of_node node_lunc).\n                                 destruct node_lunc as [a b c].\n                                 assert(a = Red).\n                                 { auto. }\n                                 subst. reflexivity.\n                               ---- (* \"lunc is BLACK\" *)\n                                 forward_call( (* get_color2(p_gpar->left) *)\n                                   tree_lunc, p_lunc, p_gpar, true\n                                 ). \n                                 { entailer!. } (* 满足前条件 *)\n                                 { tauto. }\n                                 rewrite ETree_lunc, color_lunc.\n                                 unfold Col2Z at 1, RED_COLOR, BLACK_COLOR.\n                                 forward_if. (* if (get_color2(p_gpar->left) == RED) *)\n                                 1: { assert_PROP False by entailer!; tauto. }\n                                 forward.\n                                 forward.\n                                 forward_if_wrp. (* if (p == p_par->left) *)\n                                 **** (* p = p_par->left => p = p_lisb => contradiction *)\n                                   destruct tree_lsib as [|tree_lsib_l node_lsib tree_lsib_r] eqn:ETree_lsib.\n                                   { expand rbtree_rep.\n                                     assert_PROP False by entailer!.\n                                     contradiction. }\n                                   { expand rbtree_rep.\n                                     Intros p_lunc_l p_lunc_r p_lsib_l p_lsib_r.\n                                     assert_PROP False. \n                                     { focus_SEP 8. (* 调换位置 *)\n                                       sep_apply data_at_conflict; auto.\n                                       entailer!. }\n                                     contradiction. }\n                                 **** (* \"p = p_par->right\" *)\n                                   forward. (* p_par->color = BLACK; *)\n                                   destruct part_gpar eqn:Egpart_par. (* 讨论gpar是否有父亲 目的是确定根节点是不是gpar *)\n                                   +++++ (* part_gpar = [] *) (* gpar 是根节点 *)\n                                     expand partial_treebox_rep.\n                                     assert_PROP (p_ggpar = nullval) by entailer!.\n                                     assert_PROP (b_gpar = root) by entailer!.\n                                     (* call: left_rotate_wrap(p_gpar, root) *)\n                                     forward_call(\n                                     p_gpar, p_par_med, p_ggpar, p_lsib,\n                                     p_lunc, p_med, p_gpar, nullval, \n                                     RedNode node_gpar, BlackNode node_par,\n                                     tree_lunc, tree_med, tree_lsib,\n                                     root, false,\n                                     false, nullval, nullval, node_par, (* 此行无用 *)\n                                     true, E (* 此行无用 *)\n                                     ).\n                                     { entailer!. (* 满足前条件 *)\n                                       expand partial_tree_rep.\n                                       expand rbtree_rep.\n                                       Exists p_lch p_rch.\n                                       entailer!. }\n                                     { repeat split; try tauto; (* 满足前条件 *)\n                                       subst; auto. }\n                                     forward.\n                                     remember (T lch node_med rch) as tree_med.\n                                     Exists \n                                       (T \n                                         (T \n                                           (T tree_lunc_l node_lunc tree_lunc_r) \n                                           (RedNode node_gpar) tree_lsib)\n                                         (BlackNode node_par)\n                                         tree_med)\n                                               (@nil half_tree)\n                                               root nullval.\n                                     rewrite <- H3.\n                                     expand balance'.\n                                     rewrite Ecolor_par.\n                                     destruct node_lunc as[c_lunc k_lunc v_lunc].\n                                     assert(c_lunc = Black)by auto.\n                                     subst c_lunc.\n                                     unfold l_rotate.\n                                     remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc.\n                                     expand partial_treebox_rep.\n                                     entailer!.\n                                     remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc.\n                                     expand treebox_rep.\n                                     Exists p_par_med.\n                                     entailer!.\n                                     remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc.\n                                     remember (T lch node_med rch) as tree_med.\n                                     expand rbtree_rep.\n                                     Intros p_lunc_l p_lunc_r.\n                                     Exists p_gpar p_med p_lunc p_lsib p_lunc_l p_lunc_r.\n                                     entailer!.\n                                   +++++ (* part_gpar = h1 :: l *) (* gpar 不是根节点 *)\n                                     destruct h1 as [[LR node_ggpar] Tree_ggpl_Or_ggpr] eqn:Ehalf_ggpar.\n                                     assert_PROP (p_ggpar <> nullval).\n                                     { destruct LR; expand partial_treebox_rep; Intros a b c; entailer!. }\n                                     destruct LR; expand partial_treebox_rep;\n                                       Intros p_gggpar p_ggpl_or_r b_ggpar;\n                                       assert_PROP(is_pointer_or_null p_ggpar) by entailer!;\n                                       assert_PROP(is_pointer_or_null p_ggpl_or_r) by entailer!.\n                                     -----\n                                       rename Tree_ggpl_Or_ggpr into tree_ggpl.\n                                       rename p_ggpl_or_r into p_ggpl.\n                                       rewrite partial_treebox_rep''.\n                                       destruct (rev l) eqn:El.\n                                       (* El : rev l = [] *)\n                                       { assert (l = [])by (apply rev_nil_elim in El; auto).\n                                         assert_PROP (p_gggpar = nullval /\\ root = b_ggpar). \n                                         { expand partial_treebox_rep_topdown. entailer!. }\n                                       expand partial_treebox_rep_topdown.\n                                       pose proof classic (p_ggpl <> p_gpar).\n                                       destruct H25.\n                                       destruct H26. \n                                       2:{ assert(p_ggpl = p_gpar) by tauto.\n                                           destruct tree_ggpl; simpl.\n                                           { assert_PROP (p_ggpl = nullval) by entailer!.\n                                             subst. congruence. }\n                                           Intros a b c d. subst.\n                                           assert_PROP False;[|contradiction].\n                                           focus_SEP 3.\n                                           sep_apply data_at_conflict;auto.\n                                           entailer!. }\n                                       (* p_ggpl <> p_gpar *)\n                                       destruct tree_ggpl as[|? ? ?] eqn:Tree.\n                                       *****\n                                         rewrite <- ETree_lunc.\n                                         expand rbtree_rep.\n                                         forward_call(\n                                           p_gpar, p_par_med, p_ggpar, p_lsib,\n                                           p_lunc, p_med, p_ggpar, nullval, \n                                           RedNode node_gpar, BlackNode node_par,\n                                           tree_lunc, tree_med, tree_lsib,\n                                           root, true,\n                                           false, p_gggpar, p_ggpl, node_ggpar,\n                                           true, E).\n                                         { entailer!. expand rbtree_rep.\n                                           Exists p_lch p_rch; entailer!.\n                                           unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                           entailer!. }\n                                         { repeat split; try tauto; subst; auto. intros. congruence. }\n                                         forward.\n                                         remember (T lch node_med rch) as tree_med.\n                                         remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc.\n                                         rewrite <- H3.\n                                         Exists (T (T tree_lunc (RedNode node_gpar) tree_lsib) (BlackNode node_par) tree_med)\n                                                  [(L, node_ggpar, E)]\n                                                  (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                  p_ggpar.\n                                         expand balance'.\n                                         rewrite Ecolor_par.\n                                         rewrite Heqtree_lunc.\n                                         destruct node_lunc as[c_lunc k_lunc v_lunc].\n                                         assert(c_lunc = Black)by auto.\n                                         subst c_lunc.\n                                         unfold l_rotate.\n                                         expand partial_treebox_rep.\n                                         Exists nullval nullval b_ggpar.\n                                         entailer!.\n                                         expand treebox_rep.\n                                         Exists p_par_med.\n                                         unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                         entailer.\n                                         remember (T lch node_med rch) as tree_med.\n                                         expand rbtree_rep. Intros a b.\n                                         Exists p_gpar p_med p_lunc p_lsib a b.\n                                         entailer!.\n                                       *****\n                                         rewrite <- Tree.\n                                         rewrite <- ETree_lunc.\n                                         forward_call(\n                                           p_gpar, p_par_med, p_ggpar, p_lsib,\n                                           p_lunc, p_med, p_ggpar, nullval, \n                                           RedNode node_gpar, BlackNode node_par,\n                                           tree_lunc, tree_med, tree_lsib,\n                                           root, true,\n                                           false, p_gggpar, p_ggpl, node_ggpar,\n                                           false, tree_ggpl).\n                                         { entailer!. \n                                           remember ((T t3 n0 t4)) as tree_ggpl.\n                                           expand rbtree_rep.\n                                           Exists p_lch p_rch; entailer!.\n                                           unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                           entailer!. }\n                                         { repeat split; try tauto; subst; auto. intros. congruence. }\n                                         forward.\n                                         remember (T lch node_med rch) as tree_med.\n                                         remember (T t3 n0 t4) as tree_ggpl.\n                                         remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc.\n                                         rewrite <- H3.\n                                         Exists (T (T tree_lunc (RedNode node_gpar) tree_lsib) (BlackNode node_par) tree_med)\n                                                [(L, node_ggpar, tree_ggpl)]\n                                                (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                p_ggpar.\n                                         expand balance'.\n                                         rewrite Ecolor_par. rewrite Heqtree_lunc.\n                                         destruct node_lunc as[c_lunc k_lunc v_lunc].\n                                         assert(c_lunc = Black)by auto.\n                                         subst c_lunc.\n                                         unfold l_rotate.\n                                         expand partial_treebox_rep.\n                                         Exists nullval p_ggpl b_ggpar. entailer!.\n                                         expand treebox_rep.\n                                         Exists p_par_med.\n                                         unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                         entailer!.\n                                         remember (T lch node_med rch) as tree_med.\n                                         remember (T t3 n0 t4) as tree_ggpl.\n                                         remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc.\n                                         remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc.\n                                         expand rbtree_rep.\n                                         Exists p_gpar p_med p_lunc p_lsib.\n                                         entailer!.\n                                       }\n                                       (* El : rev l = h2 :: l0 *)\n                                       { pose proof classic (p_ggpl <> p_gpar).\n                                         destruct H24. \n                                         2:{ assert(p_ggpl = p_gpar) by tauto.\n                                             destruct tree_ggpl; expand rbtree_rep.\n                                             { assert_PROP (p_ggpl = nullval) by entailer!.\n                                               subst. congruence. }\n                                             Intros a b c d. subst.\n                                             assert_PROP False;[|contradiction].\n                                             focus_SEP 3.\n                                             sep_apply data_at_conflict;auto.\n                                             entailer!. }\n                                         destruct h2 as [[LR_ans node_ans] tree_ans_another_child].\n                                         expand partial_treebox_rep_topdown.\n                                         destruct LR_ans. \n                                         *****\n                                                Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpl as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpl = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_gpar, p_par_med, p_ggpar, p_lsib,\n                                                       p_lunc, p_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_par,\n                                                       tree_lunc, tree_med, tree_lsib,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  try remember (T lch node_med rch) as tree_med.\n                                                  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc.\n                                                  Exists (T (T tree_lunc (RedNode node_gpar) tree_lsib)\n                                                          (BlackNode node_par)\n                                                          tree_med) \n                                                       ((L, node_ggpar, E) :: l)\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_lunc.\n                                                  destruct node_lunc as[c_lunc k_lunc v_lunc].\n                                                  assert(c_lunc = Black)by auto.\n                                                  subst c_lunc.\n                                                  try remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) \n                                                      as node_lunc +\n                                                    remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc.\n                                                  unfold l_rotate.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  try remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) \n                                                      as node_lunc +\n                                                    remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc.\n                                                  expand rbtree_rep.\n                                                  Intros a b.\n                                                  Exists p_gpar p_med p_lunc p_lsib a b.\n                                                  entailer!.\n                                              ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_gpar, p_par_med, p_ggpar, p_lsib,\n                                                       p_lunc, p_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_par,\n                                                       tree_lunc, tree_med, tree_lsib,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       false, tree_ggpl).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  repeat remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) \n                                                      as node_lunc +\n                                                    remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n                                                    remember (T t3 n0 t4) as tree_ggpl.\n                                                  Exists (T (T tree_lunc (RedNode node_gpar) tree_lsib)\n                                                          (BlackNode node_par)\n                                                          tree_med) \n                                                       ((L, node_ggpar, tree_ggpl) :: l)\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_lunc.\n                                                  destruct node_lunc as[c_lunc k_lunc v_lunc].\n                                                  assert(c_lunc = Black)by auto.\n                                                  subst c_lunc.\n                                                  repeat remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) \n                                                      as node_lunc +\n                                                    remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n                                                    remember (T t3 n0 t4) as tree_ggpl.\n                                                  unfold l_rotate.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpl b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  repeat remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) \n                                                      as node_lunc +\n                                                    remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n                                                    remember (T t3 n0 t4) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_med p_lunc p_lsib.\n                                                  entailer!.\n                                             *****\n                                               Intros p_ans_another_child p_ans.\n                                               destruct tree_ggpl as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpl = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_gpar, p_par_med, p_ggpar, p_lsib,\n                                                       p_lunc, p_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_par,\n                                                       tree_lunc, tree_med, tree_lsib,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  try remember (T lch node_med rch) as tree_med.\n                                                  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc.\n                                                  Exists (T (T tree_lunc (RedNode node_gpar) tree_lsib)\n                                                          (BlackNode node_par)\n                                                          tree_med) \n                                                       ((L, node_ggpar, E) :: l)\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_lunc.\n                                                  destruct node_lunc as[c_lunc k_lunc v_lunc].\n                                                  assert(c_lunc = Black)by auto.\n                                                  subst c_lunc.\n                                                  try remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) \n                                                      as node_lunc +\n                                                    remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc.\n                                                  unfold l_rotate.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  try remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) \n                                                      as node_lunc +\n                                                    remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc.\n                                                  expand rbtree_rep.\n                                                  Intros a b.\n                                                  Exists p_gpar p_med p_lunc p_lsib a b.\n                                                  entailer!.\n                                              ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_gpar, p_par_med, p_ggpar, p_lsib,\n                                                       p_lunc, p_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_par,\n                                                       tree_lunc, tree_med, tree_lsib,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       false, tree_ggpl).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  repeat remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) \n                                                      as node_lunc +\n                                                    remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n                                                    remember (T t3 n0 t4) as tree_ggpl.\n                                                  Exists (T (T tree_lunc (RedNode node_gpar) tree_lsib)\n                                                          (BlackNode node_par)\n                                                          tree_med) \n                                                       ((L, node_ggpar, tree_ggpl) :: l)\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_lunc.\n                                                  destruct node_lunc as[c_lunc k_lunc v_lunc].\n                                                  assert(c_lunc = Black)by auto.\n                                                  subst c_lunc.\n                                                  repeat remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) \n                                                      as node_lunc +\n                                                    remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n                                                    remember (T t3 n0 t4) as tree_ggpl.\n                                                  unfold l_rotate.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpl b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  repeat remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) \n                                                      as node_lunc +\n                                                    remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n                                                    remember (T t3 n0 t4) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_med p_lunc p_lsib.\n                                                  entailer!.\n                                                  }\n                                       -----\n                                       rename Tree_ggpl_Or_ggpr into tree_ggpl.\n                                       rename p_ggpl_or_r into p_ggpl.\n                                       rewrite partial_treebox_rep''.\n                                       destruct (rev l) eqn:El.\n                                       (* El : rev l = [] *)\n                                       { assert (l = [])by (apply rev_nil_elim in El; auto).\n                                         assert_PROP (p_gggpar = nullval /\\ root = b_ggpar). \n                                         { expand partial_treebox_rep_topdown. entailer!. }\n                                       expand partial_treebox_rep_topdown.\n                                       pose proof classic (p_ggpl <> p_gpar).\n                                       destruct H25.\n                                       destruct H26. \n                                       2:{ assert(p_ggpl = p_gpar) by tauto.\n                                           destruct tree_ggpl; simpl.\n                                           { assert_PROP (p_ggpl = nullval) by entailer!.\n                                             subst. congruence. }\n                                           Intros a b c d. subst.\n                                           assert_PROP False;[|contradiction].\n                                           focus_SEP 3.\n                                           sep_apply data_at_conflict;auto.\n                                           entailer!. }\n                                       (* p_ggpl <> p_gpar *)\n                                       destruct tree_ggpl as[|? ? ?] eqn:Tree.\n                                       *****\n                                         rewrite <- ETree_lunc.\n                                         expand rbtree_rep.\n                                         forward_call(\n                                           p_gpar, p_par_med, p_ggpar, p_lsib,\n                                           p_lunc, p_med, p_ggpar, nullval, \n                                           RedNode node_gpar, BlackNode node_par,\n                                           tree_lunc, tree_med, tree_lsib,\n                                           root, true,\n                                           true, p_gggpar, p_ggpl, node_ggpar,\n                                           true, E).\n                                         { entailer!. expand rbtree_rep.\n                                           Exists p_lch p_rch; entailer!.\n                                           unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                           entailer!. }\n                                         { repeat split; try tauto; subst; auto. intros. congruence. }\n                                         forward.\n                                         remember (T lch node_med rch) as tree_med.\n                                         remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc.\n                                         rewrite <- H3.\n                                         Exists (T (T tree_lunc (RedNode node_gpar) tree_lsib) (BlackNode node_par) tree_med)\n                                                  [(R, node_ggpar, E)]\n                                                  (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                  p_ggpar.\n                                         expand balance'.\n                                         rewrite Ecolor_par.\n                                         rewrite Heqtree_lunc.\n                                         destruct node_lunc as[c_lunc k_lunc v_lunc].\n                                         assert(c_lunc = Black)by auto.\n                                         subst c_lunc.\n                                         unfold l_rotate.\n                                         expand partial_treebox_rep.\n                                         Exists nullval nullval b_ggpar.\n                                         entailer!.\n                                         expand treebox_rep.\n                                         Exists p_par_med.\n                                         unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                         entailer.\n                                         remember (T lch node_med rch) as tree_med.\n                                         expand rbtree_rep. Intros a b.\n                                         Exists p_gpar p_med p_lunc p_lsib a b.\n                                         entailer!.\n                                       *****\n                                         rewrite <- Tree.\n                                         rewrite <- ETree_lunc.\n                                         forward_call(\n                                           p_gpar, p_par_med, p_ggpar, p_lsib,\n                                           p_lunc, p_med, p_ggpar, nullval, \n                                           RedNode node_gpar, BlackNode node_par,\n                                           tree_lunc, tree_med, tree_lsib,\n                                           root, true,\n                                           true, p_gggpar, p_ggpl, node_ggpar,\n                                           false, tree_ggpl).\n                                         { entailer!. \n                                           remember ((T t3 n0 t4)) as tree_ggpl.\n                                           expand rbtree_rep.\n                                           Exists p_lch p_rch; entailer!.\n                                           unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                           entailer!. }\n                                         { repeat split; try tauto; subst; auto. intros. congruence. }\n                                         forward.\n                                         remember (T lch node_med rch) as tree_med.\n                                         remember (T t3 n0 t4) as tree_ggpl.\n                                         remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc.\n                                         rewrite <- H3.\n                                         Exists (T (T tree_lunc (RedNode node_gpar) tree_lsib) (BlackNode node_par) tree_med)\n                                                [(R, node_ggpar, tree_ggpl)]\n                                                (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                p_ggpar.\n                                         expand balance'.\n                                         rewrite Ecolor_par. rewrite Heqtree_lunc.\n                                         destruct node_lunc as[c_lunc k_lunc v_lunc].\n                                         assert(c_lunc = Black)by auto.\n                                         subst c_lunc.\n                                         unfold l_rotate.\n                                         expand partial_treebox_rep.\n                                         Exists nullval p_ggpl b_ggpar. entailer!.\n                                         expand treebox_rep.\n                                         Exists p_par_med.\n                                         unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                         entailer!.\n                                         remember (T lch node_med rch) as tree_med.\n                                         remember (T t3 n0 t4) as tree_ggpl.\n                                         remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc.\n                                         remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc.\n                                         expand rbtree_rep.\n                                         Exists p_gpar p_med p_lunc p_lsib.\n                                         entailer!.\n                                       }\n                                       (* El : rev l = h2 :: l0 *)\n                                       { pose proof classic (p_ggpl <> p_gpar).\n                                         destruct H24. \n                                         2:{ assert(p_ggpl = p_gpar) by tauto.\n                                             destruct tree_ggpl; expand rbtree_rep.\n                                             { assert_PROP (p_ggpl = nullval) by entailer!.\n                                               subst. congruence. }\n                                             Intros a b c d. subst.\n                                             assert_PROP False;[|contradiction].\n                                             focus_SEP 3.\n                                             sep_apply data_at_conflict;auto.\n                                             entailer!. }\n                                         destruct h2 as [[LR_ans node_ans] tree_ans_another_child].\n                                         expand partial_treebox_rep_topdown.\n                                         destruct LR_ans. \n                                         *****\n                                                Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpl as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpl = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_gpar, p_par_med, p_ggpar, p_lsib,\n                                                       p_lunc, p_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_par,\n                                                       tree_lunc, tree_med, tree_lsib,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpl, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  try remember (T lch node_med rch) as tree_med.\n                                                  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc.\n                                                  Exists (T (T tree_lunc (RedNode node_gpar) tree_lsib)\n                                                          (BlackNode node_par)\n                                                          tree_med) \n                                                       ((R, node_ggpar, E) :: l)\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_lunc.\n                                                  destruct node_lunc as[c_lunc k_lunc v_lunc].\n                                                  assert(c_lunc = Black)by auto.\n                                                  subst c_lunc.\n                                                  try remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) \n                                                      as node_lunc +\n                                                    remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc.\n                                                  unfold l_rotate.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  try remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) \n                                                      as node_lunc +\n                                                    remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc.\n                                                  expand rbtree_rep.\n                                                  Intros a b.\n                                                  Exists p_gpar p_med p_lunc p_lsib a b.\n                                                  entailer!.\n                                              ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_gpar, p_par_med, p_ggpar, p_lsib,\n                                                       p_lunc, p_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_par,\n                                                       tree_lunc, tree_med, tree_lsib,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpl, node_ggpar,\n                                                       false, tree_ggpl).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  repeat remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) \n                                                      as node_lunc +\n                                                    remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n                                                    remember (T t3 n0 t4) as tree_ggpl.\n                                                  Exists (T (T tree_lunc (RedNode node_gpar) tree_lsib)\n                                                          (BlackNode node_par)\n                                                          tree_med) \n                                                       ((R, node_ggpar, tree_ggpl) :: l)\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_lunc.\n                                                  destruct node_lunc as[c_lunc k_lunc v_lunc].\n                                                  assert(c_lunc = Black)by auto.\n                                                  subst c_lunc.\n                                                  repeat remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) \n                                                      as node_lunc +\n                                                    remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n                                                    remember (T t3 n0 t4) as tree_ggpl.\n                                                  unfold l_rotate.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpl b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  repeat remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) \n                                                      as node_lunc +\n                                                    remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n                                                    remember (T t3 n0 t4) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_med p_lunc p_lsib.\n                                                  entailer!.\n                                             *****\n                                               Intros p_ans_another_child p_ans.\n                                               destruct tree_ggpl as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpl = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_gpar, p_par_med, p_ggpar, p_lsib,\n                                                       p_lunc, p_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_par,\n                                                       tree_lunc, tree_med, tree_lsib,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpl, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  try remember (T lch node_med rch) as tree_med.\n                                                  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc.\n                                                  Exists (T (T tree_lunc (RedNode node_gpar) tree_lsib)\n                                                          (BlackNode node_par)\n                                                          tree_med) \n                                                       ((R, node_ggpar, E) :: l)\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_lunc.\n                                                  destruct node_lunc as[c_lunc k_lunc v_lunc].\n                                                  assert(c_lunc = Black)by auto.\n                                                  subst c_lunc.\n                                                  try remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) \n                                                      as node_lunc +\n                                                    remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc.\n                                                  unfold l_rotate.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  try remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) \n                                                      as node_lunc +\n                                                    remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc.\n                                                  expand rbtree_rep.\n                                                  Intros a b.\n                                                  Exists p_gpar p_med p_lunc p_lsib a b.\n                                                  entailer!.\n                                              ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_gpar, p_par_med, p_ggpar, p_lsib,\n                                                       p_lunc, p_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_par,\n                                                       tree_lunc, tree_med, tree_lsib,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpl, node_ggpar,\n                                                       false, tree_ggpl).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  repeat remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) \n                                                      as node_lunc +\n                                                    remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n                                                    remember (T t3 n0 t4) as tree_ggpl.\n                                                  Exists (T (T tree_lunc (RedNode node_gpar) tree_lsib)\n                                                          (BlackNode node_par)\n                                                          tree_med) \n                                                       ((R, node_ggpar, tree_ggpl) :: l)\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_lunc.\n                                                  destruct node_lunc as[c_lunc k_lunc v_lunc].\n                                                  assert(c_lunc = Black)by auto.\n                                                  subst c_lunc.\n                                                  repeat remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) \n                                                      as node_lunc +\n                                                    remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n                                                    remember (T t3 n0 t4) as tree_ggpl.\n                                                  unfold l_rotate.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpl b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  repeat remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) \n                                                      as node_lunc +\n                                                    remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n                                                    remember (T t3 n0 t4) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_med p_lunc p_lsib.\n                                                  entailer!. }\n                  +++ (* Epart_par : part_par = (R, node_gpar, Tree_Lunc_Or_Runc) :: l *)\n                      rename l into part_gpar.\n                      rename Tree_Lunc_Or_Runc into tree_runc.\n                      remember (T tree_runc node_gpar tree_par) as tree_gpar.\n                        (* tree_gpar = T tree_runc node_gpar tree_par *)\n                      expand partial_treebox_rep.\n                      Intros p_ggpar p_runc b_gpar.\n                      assert_PROP (p_gpar <> nullval) by entailer!. (* \"p_gpar <> nullval\" *)\n                      assert_PROP (is_pointer_or_null p_gpar) by entailer!.\n                      gather_SEP 5 7 8 9 10 11.\n                      replace_SEP 0 (\n                        data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node node_gpar))),\n                                                   (Vint (Int.repr (key_of_node node_gpar)),\n                                                    (Vint (Int.repr (value_of_node node_gpar)),\n                                                     (p_par_med, (p_runc, p_ggpar))))) p_gpar\n                      ).\n                      { entailer!.\n                        unfold_data_at (data_at _ t_struct_tree _ p_gpar).\n                        entailer!. }\n                      forward_if. (* if (p_gpar == NULL) *)\n                      { congruence. }\n                      forward. (* calculate p_gpar->left *)\n                      forward_if_wrp. (* if (p_par == p_gpar->left) *)\n                      (* \"p_par == p_gpar->left\" *)\n                          forward. (* calculate p_gpar->right *)\n                          destruct tree_runc as [|tree_runc_l node_runc tree_runc_r] eqn:Etree_runc.\n                          ++++ (* \"tree_runc = E\" *)\n                               expand rbtree_rep.\n                               assert_PROP (p_runc = nullval) by entailer!.\n                               \n(* DECLARE _get_color2\n  WITH t: tree,\n       p: val,\n       p_par: val,\n       b: bool *)\n  (* (b = false <-> p = nullval)  *)                            \n                               \n                               forward_call( (* get_color2(p_gpar->left) *)\n                                 tree_runc, p_runc, p_gpar, false\n                               ). \n                               { entailer!. } (* 满足前条件 *)\n                               { tauto. }\n                               forward_if. (* if (get_color2(p_gpar->right) == RED) *)\n                               { contradiction. }\n                               forward. (* p_gpar->color = RED; *)\n                               forward. (* cal p_gpar->right *)\n                               forward_if_wrp. (* if (p == p_par->right) *)\n                               (* \"p = p_par->right\" *)\n                                    forward. (* p->color = BLACK; *)\n                                    forward_call(\n                                      p_par_med, p_med, p_gpar, p_lch, p_lsib, p_rch,\n                                      node_par, BlackNode node_med,\n                                      tree_lsib, rch, lch\n                                    ).\n                                    { rewrite Ecolor_par.\n                                      unfold Col2Z at 1.\n                                      entailer!. }\n                                    forward.\n                                    destruct part_gpar eqn:Egpart_par. (* 讨论gpar是否有父亲 目的是确定根节点是不是gpar *)\n                                    +++++ (* part_gpar = [] *) (* gpar 是根节点 *)\n                                          expand partial_treebox_rep.\n                                          assert_PROP (p_ggpar = nullval) by entailer!.\n                                          assert_PROP (b_gpar = root) by entailer!.\n                                          (* call: right_rotate_wrap(p_gpar, root) *)\n                                          forward_call(\n                                            p_med, p_gpar, p_ggpar, p_rch,\n                                            p_par_med, p_runc, p_gpar, nullval, \n                                            BlackNode node_med, RedNode node_gpar,\n                                            T tree_lsib node_par lch, tree_runc, rch,\n                                            root, false,\n                                            false, nullval, nullval, node_par, (* 此行无用 *)\n                                            true, E (* 此行无用 *)\n                                          ).\n                                          { entailer!. (* 满足前条件 *)\n                                            expand partial_tree_rep.\n                                            expand rbtree_rep.\n                                            Exists p_lsib p_lch.\n                                            entailer!. }\n                                          { repeat split; try tauto; (* 满足前条件 *)\n                                            subst; auto. }\n                                          forward.\n                                          remember (T tree_lsib node_par lch) as tree_par_new.\n                                          Exists (T (T tree_lsib node_par lch) (BlackNode node_med)\n                                                   (T rch (RedNode node_gpar) E))\n                                                 (@nil half_tree)\n                                                 root nullval.\n                                          rewrite <- H3.\n                                          expand balance'.\n                                          rewrite Ecolor_par.\n                                          unfold l_rotate, r_rotate, makeBlack.\n                                          expand rbtree_rep.\n                                          expand partial_treebox_rep.\n                                          entailer!.\n                                          expand treebox_rep.\n                                          Exists p_med.\n                                          remember (T tree_lsib node_par lch) as tree_par_new.\n                                          expand rbtree_rep.\n                                          Exists p_par_med p_gpar p_rch nullval.\n                                          entailer!.\n                                    +++++ (* part_gpar = h1 :: l *) (* gpar 不是根节点 *)\n                                          destruct h1 as [[LR node_ggpar] Tree_ggpl_Or_ggpr] eqn:Ehalf_ggpar.\n                                          assert_PROP (p_ggpar <> nullval). {\n                                            destruct LR; expand partial_treebox_rep; Intros a b c; entailer!. }\n                                          destruct LR; expand partial_treebox_rep;\n                                          Intros p_gggpar p_ggpl_or_r b_ggpar;\n                                          assert_PROP(is_pointer_or_null p_ggpar) by entailer!;\n                                          assert_PROP(is_pointer_or_null p_ggpl_or_r) by entailer!.\n                                          ----\n                                            rename Tree_ggpl_Or_ggpr into tree_ggpl.\n                                            rename p_ggpl_or_r into p_ggpl.\n                                            rewrite partial_treebox_rep''.\n                                            destruct (rev l) eqn:El.\n                                            (* El : rev l = [] *)\n                                            { assert (l = [])by (apply rev_nil_elim in El; auto).\n                                              assert_PROP (p_gggpar = nullval /\\ root = b_ggpar). \n                                              { expand partial_treebox_rep_topdown. entailer!. }\n                                              expand partial_treebox_rep_topdown.\n                                              pose proof classic (p_ggpl <> p_gpar).\n                                              destruct H27.\n                                              destruct H28. \n                                              2:{ assert(p_ggpl = p_gpar) by tauto.\n                                                  destruct tree_ggpl; simpl.\n                                                  { assert_PROP (p_ggpl = nullval) by entailer!.\n                                                    subst. congruence. }\n                                                  Intros a b. subst.\n                                                  assert_PROP False;[|contradiction].\n                                                  focus_SEP 5.\n                                                  sep_apply data_at_conflict;auto.\n                                                  entailer!. }\n                                              (* p_ggpl <> p_gpar *)\n                                              destruct tree_ggpl as[|? ? ?] eqn:Tree.\n                                              -----\n                                                expand rbtree_rep.\n                                                forward_call(\n                                                  p_med, p_gpar, p_ggpar, p_rch,\n                                                  p_par_med, p_runc, p_ggpar, nullval, \n                                                  BlackNode node_med, RedNode node_gpar,\n                                                  T tree_lsib node_par lch, tree_runc, rch,\n                                                  root, true,\n                                                  false, p_gggpar, p_ggpl, node_ggpar,\n                                                  true, E\n                                                ).\n                                                { entailer!. expand rbtree_rep.\n                                                  Exists p_lsib p_lch; entailer!.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!. }\n                                                { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                forward.\n                                                remember (T tree_lsib node_par lch) as tree_par_new.\n                                                rewrite <- H3.\n                                                Exists (T (T tree_lsib node_par lch) (BlackNode node_med)\n                                                   (T rch (RedNode node_gpar) E))\n                                                       [(L, node_ggpar, E)]\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                expand balance'.\n                                                rewrite Ecolor_par.\n                                                unfold l_rotate, r_rotate, makeBlack.\n                                                expand partial_treebox_rep.\n                                                Exists nullval nullval b_ggpar.\n                                                expand treebox_rep.\n                                                Exists p_med.\n                                                unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                entailer!.\n                                                remember (T tree_lsib node_par lch) as tree_par_new.\n                                                expand rbtree_rep.\n                                                Exists p_par_med p_gpar p_rch nullval.\n                                                entailer!.\n                                              -----\n                                                rewrite <- Tree.\n                                                forward_call(\n                                                  p_med, p_gpar, p_ggpar, p_rch,\n                                                  p_par_med, p_runc, p_ggpar, nullval, \n                                                  BlackNode node_med, RedNode node_gpar,\n                                                  T tree_lsib node_par lch, tree_runc, rch,\n                                                  root, true,\n                                                  false, p_gggpar, p_ggpl, node_ggpar,\n                                                  false, tree_ggpl\n                                                ).\n                                                { entailer!. \n                                                  remember ((T t3 n0 t4)) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  Exists p_lsib p_lch; entailer!. }\n                                                { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                forward.\n                                                remember (T tree_lsib node_par lch) as tree_par_new.\n                                                remember (T t3 n0 t4) as tree_ggpl.\n                                                rewrite <- H3.\n                                                Exists (T (T tree_lsib node_par lch) (BlackNode node_med)\n                                                   (T rch (RedNode node_gpar) E))\n                                                       [(L, node_ggpar, tree_ggpl)]\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                expand balance'.\n                                                rewrite Ecolor_par.\n                                                unfold l_rotate, r_rotate, makeBlack.\n                                                expand partial_treebox_rep.\n                                                Exists nullval p_ggpl b_ggpar.\n                                                expand treebox_rep.\n                                                Exists p_med.\n                                                unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                entailer!.\n                                                remember (T tree_lsib node_par lch) as tree_par_new.\n                                                remember (T t3 n0 t4) as tree_ggpl.\n                                                expand rbtree_rep.\n                                                Exists p_par_med p_gpar p_rch nullval.\n                                                entailer!.\n                                              }  \n                                          (* El : rev l = h2 :: l0 *)\n                                            { pose proof classic (p_ggpl <> p_gpar).\n                                              destruct H26. \n                                              2:{ assert(p_ggpl = p_gpar) by tauto.\n                                                  destruct tree_ggpl; expand rbtree_rep.\n                                                  { assert_PROP (p_ggpl = nullval) by entailer!.\n                                                    subst. congruence. }\n                                                  Intros a b. subst.\n                                                  assert_PROP False;[|contradiction].\n                                                  focus_SEP 5.\n                                                  sep_apply data_at_conflict;auto.\n                                                  entailer!. }\n                                              destruct h2 as [[LR_ans node_ans] tree_ans_another_child].\n                                              expand partial_treebox_rep_topdown.\n                                              destruct LR_ans. \n                                              -----\n                                                Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpl as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpl = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_med, p_gpar, p_ggpar, p_rch,\n                                                       p_par_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_med, RedNode node_gpar,\n                                                       T tree_lsib node_par lch, tree_runc, rch,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lsib p_lch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T tree_lsib node_par lch) as tree_par_new.\n                                                  Exists (T (T tree_lsib node_par lch) (BlackNode node_med)\n                                                         (T rch (RedNode node_gpar) E))\n                                                         ((L, node_ggpar, E) :: l)\n                                                         (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                         p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  rewrite <- Heqtree_par_new.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T tree_lsib node_par lch) as tree_par_new.\n                                                  expand rbtree_rep.\n                                                  Exists p_par_med p_gpar p_rch nullval.\n                                                  entailer!.\n                                                ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_med, p_gpar, p_ggpar, p_rch,\n                                                       p_par_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_med, RedNode node_gpar,\n                                                       T tree_lsib node_par lch, tree_runc, rch,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       false, tree_ggpl).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lsib p_lch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T tree_lsib node_par lch) as tree_par_new.\n                                                  remember (T t3 n0 t4) as tree_ggpl.\n                                                  Exists (T (T tree_lsib node_par lch) (BlackNode node_med)\n                                                           (T rch (RedNode node_gpar) E))\n                                                         ((L, node_ggpar, tree_ggpl) :: l)\n                                                         (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                         p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpl b_ggpar.\n                                                  entailer!.\n                                                  remember (T tree_lsib node_par lch) as tree_par_new.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T tree_lsib node_par lch) as tree_par_new.\n                                                  remember (T t3 n0 t4) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  Exists p_par_med p_gpar p_rch nullval.\n                                                  entailer!.\n                                              -----\n                                                Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpl as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpl = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_med, p_gpar, p_ggpar, p_rch,\n                                                       p_par_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_med, RedNode node_gpar,\n                                                       T tree_lsib node_par lch, tree_runc, rch,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lsib p_lch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T tree_lsib node_par lch) as tree_par_new.\n                                                  Exists (T (T tree_lsib node_par lch) (BlackNode node_med)\n                                                         (T rch (RedNode node_gpar) E))\n                                                         ((L, node_ggpar, E) :: l)\n                                                         (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                         p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  rewrite <- Heqtree_par_new.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T tree_lsib node_par lch) as tree_par_new.\n                                                  expand rbtree_rep.\n                                                  Exists p_par_med p_gpar p_rch nullval.\n                                                  entailer!.\n                                                ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_med, p_gpar, p_ggpar, p_rch,\n                                                       p_par_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_med, RedNode node_gpar,\n                                                       T tree_lsib node_par lch, tree_runc, rch,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       false, tree_ggpl).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lsib p_lch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T tree_lsib node_par lch) as tree_par_new.\n                                                  remember (T t3 n0 t4) as tree_ggpl.\n                                                  Exists (T (T tree_lsib node_par lch) (BlackNode node_med)\n                                                           (T rch (RedNode node_gpar) E))\n                                                         ((L, node_ggpar, tree_ggpl) :: l)\n                                                         (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                         p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpl b_ggpar.\n                                                  entailer!.\n                                                  remember (T tree_lsib node_par lch) as tree_par_new.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T tree_lsib node_par lch) as tree_par_new.\n                                                  remember (T t3 n0 t4) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  Exists p_par_med p_gpar p_rch nullval.\n                                                  entailer!.\n                                            }\n                                          ----\n                                            rename Tree_ggpl_Or_ggpr into tree_ggpr.\n                                            rename p_ggpl_or_r into p_ggpr.\n                                            rewrite partial_treebox_rep''.\n                                            destruct (rev l) eqn:El.\n                                            (* El : rev l = [] *)\n                                            { assert (l = [])by (apply rev_nil_elim in El; auto).\n                                              assert_PROP (p_gggpar = nullval /\\ root = b_ggpar). \n                                              { expand partial_treebox_rep_topdown. entailer!. }\n                                              expand partial_treebox_rep_topdown.\n                                              pose proof classic (p_ggpr <> p_gpar).\n                                              destruct H27.\n                                              destruct H28. \n                                              2:{ assert(p_ggpr = p_gpar) by tauto.\n                                                  destruct tree_ggpr; simpl.\n                                                  { assert_PROP (p_ggpr = nullval) by entailer!.\n                                                    subst. congruence. }\n                                                  Intros a b. subst.\n                                                  assert_PROP False;[|contradiction].\n                                                  focus_SEP 5.\n                                                  sep_apply data_at_conflict;auto.\n                                                  entailer!. }\n                                              (* p_ggpr <> p_gpar *)\n                                              destruct tree_ggpr as[|? ? ?] eqn:Tree.\n                                              -----\n                                                expand rbtree_rep.\n                                                forward_call(\n                                                  p_med, p_gpar, p_ggpar, p_rch,\n                                                  p_par_med, p_runc, p_ggpar, nullval, \n                                                  BlackNode node_med, RedNode node_gpar,\n                                                  T tree_lsib node_par lch, tree_runc, rch,\n                                                  root, true,\n                                                  true, p_gggpar, p_ggpr, node_ggpar,\n                                                  true, E\n                                                ).\n                                                { entailer!. expand rbtree_rep.\n                                                  Exists p_lsib p_lch; entailer!.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!. }\n                                                { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                forward.\n                                                remember (T tree_lsib node_par lch) as tree_par_new.\n                                                rewrite <- H3.\n                                                Exists (T (T tree_lsib node_par lch) (BlackNode node_med)\n                                                   (T rch (RedNode node_gpar) E))\n                                                       [(R, node_ggpar, E)]\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                expand balance'.\n                                                rewrite Ecolor_par.\n                                                unfold l_rotate, r_rotate, makeBlack.\n                                                expand partial_treebox_rep.\n                                                Exists nullval nullval b_ggpar.\n                                                expand treebox_rep.\n                                                Exists p_med.\n                                                unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                entailer!.\n                                                remember (T tree_lsib node_par lch) as tree_par_new.\n                                                expand rbtree_rep.\n                                                Exists p_par_med p_gpar p_rch nullval.\n                                                entailer!.\n                                              -----\n                                                rewrite <- Tree.\n                                                forward_call(\n                                                  p_med, p_gpar, p_ggpar, p_rch,\n                                                  p_par_med, p_runc, p_ggpar, nullval, \n                                                  BlackNode node_med, RedNode node_gpar,\n                                                  T tree_lsib node_par lch, tree_runc, rch,\n                                                  root, true,\n                                                  true, p_gggpar, p_ggpr, node_ggpar,\n                                                  false, tree_ggpr\n                                                ).\n                                                { entailer!. \n                                                  remember ((T t3 n0 t4)) as tree_ggpr.\n                                                  expand rbtree_rep.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  Exists p_lsib p_lch; entailer!. }\n                                                { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                forward.\n                                                remember (T tree_lsib node_par lch) as tree_par_new.\n                                                remember (T t3 n0 t4) as tree_ggpr.\n                                                rewrite <- H3.\n                                                Exists (T (T tree_lsib node_par lch) (BlackNode node_med)\n                                                   (T rch (RedNode node_gpar) E))\n                                                       [(R, node_ggpar, tree_ggpr)]\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                expand balance'.\n                                                rewrite Ecolor_par.\n                                                unfold l_rotate, r_rotate, makeBlack.\n                                                expand partial_treebox_rep.\n                                                Exists nullval p_ggpr b_ggpar.\n                                                expand treebox_rep.\n                                                Exists p_med.\n                                                unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                entailer!.\n                                                remember (T tree_lsib node_par lch) as tree_par_new.\n                                                remember (T t3 n0 t4) as tree_ggpr.\n                                                expand rbtree_rep.\n                                                Exists p_par_med p_gpar p_rch nullval.\n                                                entailer!.\n                                              }  \n                                          (* El : rev l = h2 :: l0 *)\n                                            { pose proof classic (p_ggpr <> p_gpar).\n                                              destruct H26. \n                                              2:{ assert(p_ggpr = p_gpar) by tauto.\n                                                  destruct tree_ggpr; expand rbtree_rep.\n                                                  { assert_PROP (p_ggpr = nullval) by entailer!.\n                                                    subst. congruence. }\n                                                  Intros a b. subst.\n                                                  assert_PROP False;[|contradiction].\n                                                  focus_SEP 5.\n                                                  sep_apply data_at_conflict;auto.\n                                                  entailer!. }\n                                              destruct h2 as [[LR_ans node_ans] tree_ans_another_child].\n                                              expand partial_treebox_rep_topdown.\n                                              destruct LR_ans. \n                                              -----\n                                                Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpr as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpr = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_med, p_gpar, p_ggpar, p_rch,\n                                                       p_par_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_med, RedNode node_gpar,\n                                                       T tree_lsib node_par lch, tree_runc, rch,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpr, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lsib p_lch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T tree_lsib node_par lch) as tree_par_new.\n                                                  Exists (T (T tree_lsib node_par lch) (BlackNode node_med)\n                                                         (T rch (RedNode node_gpar) E))\n                                                         ((R, node_ggpar, E) :: l)\n                                                         (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                         p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  rewrite <- Heqtree_par_new.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T tree_lsib node_par lch) as tree_par_new.\n                                                  expand rbtree_rep.\n                                                  Exists p_par_med p_gpar p_rch nullval.\n                                                  entailer!.\n                                                ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_med, p_gpar, p_ggpar, p_rch,\n                                                       p_par_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_med, RedNode node_gpar,\n                                                       T tree_lsib node_par lch, tree_runc, rch,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpr, node_ggpar,\n                                                       false, tree_ggpr).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lsib p_lch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T tree_lsib node_par lch) as tree_par_new.\n                                                  remember (T t3 n0 t4) as tree_ggpr.\n                                                  Exists (T (T tree_lsib node_par lch) (BlackNode node_med)\n                                                           (T rch (RedNode node_gpar) E))\n                                                         ((R, node_ggpar, tree_ggpr) :: l)\n                                                         (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                         p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpr b_ggpar.\n                                                  entailer!.\n                                                  remember (T tree_lsib node_par lch) as tree_par_new.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T tree_lsib node_par lch) as tree_par_new.\n                                                  remember (T t3 n0 t4) as tree_ggpr.\n                                                  expand rbtree_rep.\n                                                  Exists p_par_med p_gpar p_rch nullval.\n                                                  entailer!.\n                                              -----\n                                                Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpr as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpr = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_med, p_gpar, p_ggpar, p_rch,\n                                                       p_par_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_med, RedNode node_gpar,\n                                                       T tree_lsib node_par lch, tree_runc, rch,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpr, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lsib p_lch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T tree_lsib node_par lch) as tree_par_new.\n                                                  Exists (T (T tree_lsib node_par lch) (BlackNode node_med)\n                                                         (T rch (RedNode node_gpar) E))\n                                                         ((R, node_ggpar, E) :: l)\n                                                         (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                         p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  rewrite <- Heqtree_par_new.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T tree_lsib node_par lch) as tree_par_new.\n                                                  expand rbtree_rep.\n                                                  Exists p_par_med p_gpar p_rch nullval.\n                                                  entailer!.\n                                                ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_med, p_gpar, p_ggpar, p_rch,\n                                                       p_par_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_med, RedNode node_gpar,\n                                                       T tree_lsib node_par lch, tree_runc, rch,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpr, node_ggpar,\n                                                       false, tree_ggpr).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lsib p_lch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T tree_lsib node_par lch) as tree_par_new.\n                                                  remember (T t3 n0 t4) as tree_ggpr.\n                                                  Exists (T (T tree_lsib node_par lch) (BlackNode node_med)\n                                                           (T rch (RedNode node_gpar) E))\n                                                         ((R, node_ggpar, tree_ggpr) :: l)\n                                                         (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                         p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpr b_ggpar.\n                                                  entailer!.\n                                                  remember (T tree_lsib node_par lch) as tree_par_new.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T tree_lsib node_par lch) as tree_par_new.\n                                                  remember (T t3 n0 t4) as tree_ggpr.\n                                                  expand rbtree_rep.\n                                                  Exists p_par_med p_gpar p_rch nullval.\n                                                  entailer!.\n                                            }\n                          ++++ (* \"tree_runc = T tree_runc_l node_runc tree_runc_r\" *)\n                               assert_PROP (p_runc <> nullval).\n                               { expand rbtree_rep; Intros a b; entailer!. }\n                               destruct (color_of_node node_runc) eqn: color_runc.\n                               ---- (* \"lunc is RED\" *)\n(* DECLARE _get_color2\n  WITH t: tree,\n       p: val,\n       p_par: val,\n       b: bool *)\n  (* (b = false <-> p = nullval)  *) \n                                 forward_call( (* get_color2(p_gpar->left) *)\n                                   tree_runc, p_runc, p_gpar, true\n                                 ). \n                                 { entailer!. } (* 满足前条件 *)\n                                 { tauto. }\n                                 rewrite Etree_runc, color_runc.\n                                 unfold Col2Z at 1. (*  , RED_COLOR, BLACK_COLOR. *)\n                                 forward_if. (* if (get_color2(p_gpar->left) == RED) *)\n                                 2: { assert_PROP False by entailer!; tauto. }\n                                 forward.\n                                 forward.\n                                 expand rbtree_rep.\n                                 Intros p_runc_l p_runc_r.\n                                 forward.\n                                 forward.\n                                 forward.\n                                 Exists (T \n                                   (T tree_lsib (BlackNode node_par) tree_med) (RedNode node_gpar)\n                                   (makeBlack tree_runc))\n                                   part_gpar\n                                   b_gpar\n                                   p_ggpar\n                                   p_gpar.\n                                 rewrite <- H3.\n                                 expand balance'.\n                                 rewrite Ecolor_par.\n                                 expand rbtree_rep.\n                                 Exists p_par_med p_runc p_lsib p_med.\n                                 entailer!.\n                                 2:{ unfold makeBlack. expand rbtree_rep. \n                                     Exists p_lch p_rch p_runc_l p_runc_r.\n                                     entailer!. } \n                                 simpl (color_of_node node_runc).\n                                 destruct node_runc as [a b c].\n                                 assert(a = Red).\n                                 { auto. }\n                                 subst. reflexivity.\n                               ---- (* \"lunc is BLACK\" *)\n                                 forward_call( (* get_color2(p_gpar->left) *)\n                                   tree_runc, p_runc, p_gpar, true\n                                 ). \n                                 { entailer!. } (* 满足前条件 *)\n                                 { tauto. }\n                                 rewrite Etree_runc, color_runc.\n                                 unfold Col2Z at 1, RED_COLOR, BLACK_COLOR.\n                                 forward_if. (* if (get_color2(p_gpar->left) == RED) *)\n                                 1: { assert_PROP False by entailer!; tauto. }\n                                 forward.\n                                 forward.\n                                 forward_if_wrp.\n                                 (* \"p = p_par->right\" *)\n                                   forward. (* p_par->color = BLACK; *)\n                                   forward_call(\n                                      p_par_med, p_med, p_gpar, p_lch, p_lsib, p_rch,\n                                      node_par, BlackNode node_med,\n                                      tree_lsib, rch, lch\n                                    ).\n                                    { rewrite Ecolor_par.\n                                      unfold Col2Z at 1.\n                                      entailer!. }\n                                    forward.\n                                   destruct part_gpar eqn:Egpart_par. (* 讨论gpar是否有父亲 目的是确定根节点是不是gpar *)\n                                   +++++ (* part_gpar = [] *) (* gpar 是根节点 *)\n                                     expand partial_treebox_rep.\n                                     assert_PROP (p_ggpar = nullval) by entailer!.\n                                     assert_PROP (b_gpar = root) by entailer!.\n                                     (* call: left_rotate_wrap(p_gpar, root) *)\n                                     forward_call(\n                                            p_med, p_gpar, p_ggpar, p_rch,\n                                            p_par_med, p_runc, p_gpar, nullval, \n                                            BlackNode node_med, RedNode node_gpar,\n                                            T tree_lsib node_par lch, tree_runc, rch,\n                                            root, false,\n                                            false, nullval, nullval, node_par, (* 此行无用 *)\n                                            true, E (* 此行无用 *)\n                                          ).\n                                          { entailer!. (* 满足前条件 *)\n                                            expand partial_tree_rep.\n                                            expand rbtree_rep.\n                                            Exists p_lsib p_lch.\n                                            entailer!. }\n                                          { repeat split; try tauto; (* 满足前条件 *)\n                                            subst; auto. }\n                                          forward.\n                                     remember (T tree_lsib node_par lch) as tree_par_new.\n                                     remember (T tree_runc_l node_runc tree_runc_r) as tree_runc.\n                                     Exists \n                                       (T \n                                         (T tree_lsib node_par lch) (BlackNode node_med)\n                                           (T rch (RedNode node_gpar)\n                                        tree_runc))\n                                       (@nil half_tree)\n                                       root nullval.\n                                     rewrite <- H3.\n                                     expand balance'.\n                                     rewrite Ecolor_par.\n                                     destruct node_runc as[c_lunc k_lunc v_lunc].\n                                     assert(c_lunc = Black)by auto.\n                                     subst c_lunc tree_runc.\n                                     unfold l_rotate, r_rotate, makeBlack.\n                                     remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc.\n                                     expand partial_treebox_rep.\n                                     entailer!.\n                                     remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc.\n                                     expand treebox_rep.\n                                     Exists p_med.\n                                     entailer!.\n                                     remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc.\n                                     remember (T tree_lsib node_par lch) as tree_par_new.\n                                     remember (T tree_runc_l node_runc tree_runc_r) as tree_runc.\n                                     expand rbtree_rep.\n                                     Exists p_par_med p_gpar p_rch p_runc.\n                                     entailer!.\n                                   +++++ (* part_gpar = h1 :: l *) (* gpar 不是根节点 *)\n                                     destruct h1 as [[LR node_ggpar] Tree_ggpl_Or_ggpr] eqn:Ehalf_ggpar.\n                                     assert_PROP (p_ggpar <> nullval).\n                                     { destruct LR; expand partial_treebox_rep; Intros a b c; entailer!. }\n                                     destruct LR; expand partial_treebox_rep;\n                                       Intros p_gggpar p_ggpl_or_r b_ggpar;\n                                       assert_PROP(is_pointer_or_null p_ggpar) by entailer!;\n                                       assert_PROP(is_pointer_or_null p_ggpl_or_r) by entailer!.\n                                     -----\n                                       rename Tree_ggpl_Or_ggpr into tree_ggpl.\n                                       rename p_ggpl_or_r into p_ggpl.\n                                       rewrite partial_treebox_rep''.\n                                       destruct (rev l) eqn:El.\n                                       (* El : rev l = [] *)\n                                       { assert (l = [])by (apply rev_nil_elim in El; auto).\n                                         assert_PROP (p_gggpar = nullval /\\ root = b_ggpar). \n                                         { expand partial_treebox_rep_topdown. entailer!. }\n                                       expand partial_treebox_rep_topdown.\n                                       pose proof classic (p_ggpl <> p_gpar).\n                                       destruct H27.\n                                       destruct H28. \n                                       2:{ assert(p_ggpl = p_gpar) by tauto.\n                                           destruct tree_ggpl; simpl.\n                                           { assert_PROP (p_ggpl = nullval) by entailer!.\n                                             subst. congruence. }\n                                           Intros a b. subst.\n                                           assert_PROP False;[|contradiction].\n                                           focus_SEP 8.\n                                           sep_apply data_at_conflict;auto.\n                                           entailer!. }\n                                       (* p_ggpl <> p_gpar *)\n                                       destruct tree_ggpl as[|? ? ?] eqn:Tree.\n                                       *****\n                                         expand rbtree_rep.\n                                         forward_call(\n                                                  p_med, p_gpar, p_ggpar, p_rch,\n                                                  p_par_med, p_runc, p_ggpar, nullval, \n                                                  BlackNode node_med, RedNode node_gpar,\n                                                  T tree_lsib node_par lch, tree_runc, rch,\n                                                  root, true,\n                                                  false, p_gggpar, p_ggpl, node_ggpar,\n                                                  true, E\n                                                ).\n                                                { entailer!. expand rbtree_rep.\n                                                  Exists p_lsib p_lch; entailer!.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!. }\n                                         { repeat split; try tauto; subst; auto. intros. congruence. }\n                                         forward.\n                                         repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                         rewrite <- H3.\n                                         Exists (T (T tree_lsib node_par lch) (BlackNode node_med)\n                                                   (T rch (RedNode node_gpar) tree_runc))\n                                                       [(L, node_ggpar, E)]\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                         expand balance'.\n                                         rewrite Ecolor_par.\n                                         rewrite Heqtree_runc.\n                                         destruct node_runc as[c_lunc k_lunc v_lunc].\n                                         assert(c_lunc = Black)by auto.\n                                         subst c_lunc.\n                                         unfold l_rotate, r_rotate, makeBlack.\n                                         expand partial_treebox_rep.\n                                         Exists nullval nullval b_ggpar.\n                                         entailer!.\n                                         expand treebox_rep.\n                                         Exists p_med.\n                                         unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                         entailer.\n                                         repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                         expand rbtree_rep.\n                                         Exists p_par_med p_gpar p_rch p_runc.\n                                         entailer!.\n                                       *****\n                                         rewrite <- Tree.\n                                         forward_call(\n                                                  p_med, p_gpar, p_ggpar, p_rch,\n                                                  p_par_med, p_runc, p_ggpar, nullval, \n                                                  BlackNode node_med, RedNode node_gpar,\n                                                  T tree_lsib node_par lch, tree_runc, rch,\n                                                  root, true,\n                                                  false, p_gggpar, p_ggpl, node_ggpar,\n                                                  false, tree_ggpl\n                                                ).\n                                         { entailer!. \n                                           remember ((T t3 n0 t4)) as tree_ggpl.\n                                           expand rbtree_rep.\n                                           unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                           Exists p_lsib p_lch; entailer!. }\n                                         { repeat split; try tauto; subst; auto. intros. congruence. }\n                                         forward. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                         rewrite <- H3.\n                                         Exists (T (T tree_lsib node_par lch) (BlackNode node_med)\n                                                   (T rch (RedNode node_gpar) tree_runc))\n                                                       [(L, node_ggpar, tree_ggpl)]\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                         expand balance'.\n                                         rewrite Ecolor_par. rewrite Heqtree_runc.\n                                         destruct node_runc as[c_lunc k_lunc v_lunc].\n                                         assert(c_lunc = Black)by auto.\n                                         subst c_lunc.\n                                         unfold l_rotate, r_rotate, makeBlack.\n                                         expand partial_treebox_rep.\n                                         Exists nullval p_ggpl b_ggpar.\n                                         entailer!.\n                                         repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                         expand treebox_rep.\n                                         Exists p_med.\n                                         unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                         expand rbtree_rep.\n                                         Exists p_par_med p_gpar p_rch p_runc.\n                                         entailer!.\n                                       }\n                                       (* El : rev l = h2 :: l0 *)\n                                       { pose proof classic (p_ggpl <> p_gpar).\n                                         destruct H26. \n                                         2:{ assert(p_ggpl = p_gpar) by tauto.\n                                                  destruct tree_ggpl; expand rbtree_rep.\n                                                  { assert_PROP (p_ggpl = nullval) by entailer!.\n                                                    subst. congruence. }\n                                                  Intros a b. subst.\n                                                  assert_PROP False;[|contradiction].\n                                                  focus_SEP 8.\n                                                  sep_apply data_at_conflict;auto.\n                                                  entailer!. }\n                                         destruct h2 as [[LR_ans node_ans] tree_ans_another_child].\n                                         expand partial_treebox_rep_topdown.\n                                         destruct LR_ans. \n                                         ++++++\n                                                Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpl as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpl = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_med, p_gpar, p_ggpar, p_rch,\n                                                       p_par_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_med, RedNode node_gpar,\n                                                       T tree_lsib node_par lch, tree_runc, rch,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lsib p_lch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                                  Exists (T (T tree_lsib node_par lch) (BlackNode node_med)\n                                                         (T rch (RedNode node_gpar) tree_runc))\n                                                         ((L, node_ggpar, E) :: l)\n                                                         (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                         p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_runc.\n                                                  destruct node_runc as[c_lunc k_lunc v_lunc].\n                                                  assert(c_lunc = Black)by auto.\n                                                  subst c_lunc.\n                                                  repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  Exists p_par_med p_gpar p_rch p_runc.\n                                                  entailer!.\n                                              ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_med, p_gpar, p_ggpar, p_rch,\n                                                       p_par_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_med, RedNode node_gpar,\n                                                       T tree_lsib node_par lch, tree_runc, rch,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       false, tree_ggpl).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lsib p_lch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                                  Exists (T (T tree_lsib node_par lch) (BlackNode node_med)\n                                                           (T rch (RedNode node_gpar) tree_runc))\n                                                       ((L, node_ggpar, tree_ggpl) :: l)\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_runc.\n                                                  destruct node_runc as[c_lunc k_lunc v_lunc].\n                                                  assert(c_lunc = Black)by auto.\n                                                  subst c_lunc. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpl b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  Exists p_par_med p_gpar p_rch p_runc.\n                                                  entailer!.\n                                           ++++++\n                                               Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpl as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpl = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_med, p_gpar, p_ggpar, p_rch,\n                                                       p_par_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_med, RedNode node_gpar,\n                                                       T tree_lsib node_par lch, tree_runc, rch,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lsib p_lch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                                  Exists (T (T tree_lsib node_par lch) (BlackNode node_med)\n                                                         (T rch (RedNode node_gpar) tree_runc))\n                                                         ((L, node_ggpar, E) :: l)\n                                                         (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                         p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_runc.\n                                                  destruct node_runc as[c_lunc k_lunc v_lunc].\n                                                  assert(c_lunc = Black)by auto.\n                                                  subst c_lunc.\n                                                  repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  Exists p_par_med p_gpar p_rch p_runc.\n                                                  entailer!.\n                                              ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_med, p_gpar, p_ggpar, p_rch,\n                                                       p_par_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_med, RedNode node_gpar,\n                                                       T tree_lsib node_par lch, tree_runc, rch,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       false, tree_ggpl).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lsib p_lch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                                  Exists (T (T tree_lsib node_par lch) (BlackNode node_med)\n                                                           (T rch (RedNode node_gpar) tree_runc))\n                                                       ((L, node_ggpar, tree_ggpl) :: l)\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_runc.\n                                                  destruct node_runc as[c_lunc k_lunc v_lunc].\n                                                  assert(c_lunc = Black)by auto.\n                                                  subst c_lunc. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpl b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  Exists p_par_med p_gpar p_rch p_runc.\n                                                  entailer!.\n                                                  }\n                                       -----\n                                       rename Tree_ggpl_Or_ggpr into tree_ggpr.\n                                       rename p_ggpl_or_r into p_ggpr.\n                                       rewrite partial_treebox_rep''.\n                                       destruct (rev l) eqn:El.\n                                       (* El : rev l = [] *)\n                                       { assert (l = [])by (apply rev_nil_elim in El; auto).\n                                         assert_PROP (p_gggpar = nullval /\\ root = b_ggpar). \n                                         { expand partial_treebox_rep_topdown. entailer!. }\n                                       expand partial_treebox_rep_topdown.\n                                       pose proof classic (p_ggpr <> p_gpar).\n                                       destruct H27.\n                                       destruct H28. \n                                       2:{ assert(p_ggpr = p_gpar) by tauto.\n                                           destruct tree_ggpr; simpl.\n                                           { assert_PROP (p_ggpr = nullval) by entailer!.\n                                             subst. congruence. }\n                                           Intros a b. subst.\n                                           assert_PROP False;[|contradiction].\n                                           focus_SEP 8.\n                                           sep_apply data_at_conflict;auto.\n                                           entailer!. }\n                                       (* p_ggpr <> p_gpar *)\n                                       destruct tree_ggpr as[|? ? ?] eqn:Tree.\n                                       *****\n                                         expand rbtree_rep.\n                                         forward_call(\n                                                  p_med, p_gpar, p_ggpar, p_rch,\n                                                  p_par_med, p_runc, p_ggpar, nullval, \n                                                  BlackNode node_med, RedNode node_gpar,\n                                                  T tree_lsib node_par lch, tree_runc, rch,\n                                                  root, true,\n                                                  true, p_gggpar, p_ggpr, node_ggpar,\n                                                  true, E\n                                                ).\n                                                { entailer!. expand rbtree_rep.\n                                                  Exists p_lsib p_lch; entailer!.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!. }\n                                         { repeat split; try tauto; subst; auto. intros. congruence. }\n                                         forward.\n                                         repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                         rewrite <- H3.\n                                         Exists (T (T tree_lsib node_par lch) (BlackNode node_med)\n                                                   (T rch (RedNode node_gpar) tree_runc))\n                                                       [(R, node_ggpar, E)]\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                         expand balance'.\n                                         rewrite Ecolor_par.\n                                         rewrite Heqtree_runc.\n                                         destruct node_runc as[c_lunc k_lunc v_lunc].\n                                         assert(c_lunc = Black)by auto.\n                                         subst c_lunc.\n                                         unfold l_rotate, r_rotate, makeBlack.\n                                         expand partial_treebox_rep.\n                                         Exists nullval nullval b_ggpar.\n                                         entailer!.\n                                         expand treebox_rep.\n                                         Exists p_med.\n                                         unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                         entailer.\n                                         repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                         expand rbtree_rep.\n                                         Exists p_par_med p_gpar p_rch p_runc.\n                                         entailer!.\n                                       *****\n                                         rewrite <- Tree.\n                                         forward_call(\n                                                  p_med, p_gpar, p_ggpar, p_rch,\n                                                  p_par_med, p_runc, p_ggpar, nullval, \n                                                  BlackNode node_med, RedNode node_gpar,\n                                                  T tree_lsib node_par lch, tree_runc, rch,\n                                                  root, true,\n                                                  true, p_gggpar, p_ggpr, node_ggpar,\n                                                  false, tree_ggpr\n                                                ).\n                                         { entailer!. \n                                           remember ((T t3 n0 t4)) as tree_ggpr.\n                                           expand rbtree_rep.\n                                           unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                           Exists p_lsib p_lch; entailer!. }\n                                         { repeat split; try tauto; subst; auto. intros. congruence. }\n                                         forward. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                         rewrite <- H3.\n                                         Exists (T (T tree_lsib node_par lch) (BlackNode node_med)\n                                                   (T rch (RedNode node_gpar) tree_runc))\n                                                       [(R, node_ggpar, tree_ggpr)]\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                         expand balance'.\n                                         rewrite Ecolor_par. rewrite Heqtree_runc.\n                                         destruct node_runc as[c_lunc k_lunc v_lunc].\n                                         assert(c_lunc = Black)by auto.\n                                         subst c_lunc.\n                                         unfold l_rotate, r_rotate, makeBlack.\n                                         expand partial_treebox_rep.\n                                         Exists nullval p_ggpr b_ggpar.\n                                         entailer!.\n                                         repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                         expand treebox_rep.\n                                         Exists p_med.\n                                         unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                         expand rbtree_rep.\n                                         Exists p_par_med p_gpar p_rch p_runc.\n                                         entailer!.\n                                       }\n                                       (* El : rev l = h2 :: l0 *)\n                                       { pose proof classic (p_ggpr <> p_gpar).\n                                         destruct H26. \n                                         2:{ assert(p_ggpr = p_gpar) by tauto.\n                                                  destruct tree_ggpr; expand rbtree_rep.\n                                                  { assert_PROP (p_ggpr = nullval) by entailer!.\n                                                    subst. congruence. }\n                                                  Intros a b. subst.\n                                                  assert_PROP False;[|contradiction].\n                                                  focus_SEP 8.\n                                                  sep_apply data_at_conflict;auto.\n                                                  entailer!. }\n                                         destruct h2 as [[LR_ans node_ans] tree_ans_another_child].\n                                         expand partial_treebox_rep_topdown.\n                                         destruct LR_ans. \n                                         ++++++\n                                                Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpr as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpr = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_med, p_gpar, p_ggpar, p_rch,\n                                                       p_par_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_med, RedNode node_gpar,\n                                                       T tree_lsib node_par lch, tree_runc, rch,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpr, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lsib p_lch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                                  Exists (T (T tree_lsib node_par lch) (BlackNode node_med)\n                                                         (T rch (RedNode node_gpar) tree_runc))\n                                                         ((R, node_ggpar, E) :: l)\n                                                         (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                         p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_runc.\n                                                  destruct node_runc as[c_lunc k_lunc v_lunc].\n                                                  assert(c_lunc = Black)by auto.\n                                                  subst c_lunc.\n                                                  repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                                  expand rbtree_rep.\n                                                  Exists p_par_med p_gpar p_rch p_runc.\n                                                  entailer!.\n                                              ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_med, p_gpar, p_ggpar, p_rch,\n                                                       p_par_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_med, RedNode node_gpar,\n                                                       T tree_lsib node_par lch, tree_runc, rch,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpr, node_ggpar,\n                                                       false, tree_ggpr).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lsib p_lch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                                  Exists (T (T tree_lsib node_par lch) (BlackNode node_med)\n                                                           (T rch (RedNode node_gpar) tree_runc))\n                                                       ((R, node_ggpar, tree_ggpr) :: l)\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_runc.\n                                                  destruct node_runc as[c_lunc k_lunc v_lunc].\n                                                  assert(c_lunc = Black)by auto.\n                                                  subst c_lunc. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpr b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                                  expand rbtree_rep.\n                                                  Exists p_par_med p_gpar p_rch p_runc.\n                                                  entailer!.\n                                           ++++++\n                                               Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpr as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpr = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_med, p_gpar, p_ggpar, p_rch,\n                                                       p_par_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_med, RedNode node_gpar,\n                                                       T tree_lsib node_par lch, tree_runc, rch,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpr, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lsib p_lch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                                  Exists (T (T tree_lsib node_par lch) (BlackNode node_med)\n                                                         (T rch (RedNode node_gpar) tree_runc))\n                                                         ((R, node_ggpar, E) :: l)\n                                                         (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                         p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_runc.\n                                                  destruct node_runc as[c_lunc k_lunc v_lunc].\n                                                  assert(c_lunc = Black)by auto.\n                                                  subst c_lunc.\n                                                  repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                                  expand rbtree_rep.\n                                                  Exists p_par_med p_gpar p_rch p_runc.\n                                                  entailer!.\n                                              ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_med, p_gpar, p_ggpar, p_rch,\n                                                       p_par_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_med, RedNode node_gpar,\n                                                       T tree_lsib node_par lch, tree_runc, rch,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpr, node_ggpar,\n                                                       false, tree_ggpr).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lsib p_lch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                                  Exists (T (T tree_lsib node_par lch) (BlackNode node_med)\n                                                           (T rch (RedNode node_gpar) tree_runc))\n                                                       ((R, node_ggpar, tree_ggpr) :: l)\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_runc.\n                                                  destruct node_runc as[c_lunc k_lunc v_lunc].\n                                                  assert(c_lunc = Black)by auto.\n                                                  subst c_lunc. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpr b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_runc +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lsib node_par lch) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                                  expand rbtree_rep.\n                                                  Exists p_par_med p_gpar p_rch p_runc.\n                                                  entailer!.\n                                                  }\n* (* Els_med : ls_med = (R, node_par, Tree_Lsib_Or_Rsib) :: p *) (* \"p为左子树\" *)\n  rename Tree_Lsib_Or_Rsib into tree_rsib.\n  rename p into part_par.\n  remember (T tree_med node_par tree_rsib) as tree_par.\n  expand partial_treebox_rep.\n  Intros p_gpar p_rsib b_par.\n  assert_PROP (p_par_med <> nullval) by entailer!.\n  forward_call(p_par_med, p_gpar, p_med, p_rsib, node_par, true). (* get_color1(p_par) *)\n  { entailer!. (* 满足前条件 *)\n    unfold_data_at (data_at _ t_struct_tree _ p_par_med).\n    entailer!. }\n  { split; congruence. }\n  destruct (color_of_node node_par) eqn:Ecolor_par.\n  2: { (* color_par = Black *) (* \"父亲的颜色是黑色, 情况平凡\" *)\n                unfold Col2Z at 1 2.\n                forward_if; (* if (get_color(p_par) != RED) *)\n                   [|assert_PROP False by entailer!; contradiction].\n                forward.  (* return *)\n                Exists (T lch node_med rch) \n                       ((R, node_par, tree_rsib) :: part_par)\n                       (field_address t_struct_tree [StructField _left] p_par_med)\n                       p_par_med.\n                expand treebox_rep.\n                expand partial_treebox_rep.\n                Exists p_med p_gpar p_rsib b_par.\n                expand rbtree_rep.\n                Exists p_lch p_rch.\n                entailer!.\n                { rewrite <- H3.\n                  expand balance'.\n                  rewrite Ecolor_par.\n                  destruct part_par; [auto|].\n                  destruct h as [[? ?] ?]; auto. }\n                unfold_data_at (data_at Tsh t_struct_tree _ p_par_med).\n                entailer!.\n                rewrite Ecolor_par.\n                unfold Col2Z.\n                entailer!.\n     }\n  ** (* \"Ecolor_par : color_of_node node_par = Red\" *) (* \"父亲的颜色是红色\" *)\n              unfold Col2Z at 1 2.\n              forward_if. (* if (get_color(p_par) != RED) *)\n              { congruence. } (* get_color(p_par) != RED => contradiction *)\n              forward. (* p_gpar = p_par->par; *)\n  destruct part_par eqn:Epart_par.\n   *** (* part_par = [] => p_gpar = p_top = nullval *) (* \"没有祖父节点, 情况平凡\" *)\n                  expand partial_treebox_rep.\n                  assert_PROP (p_gpar = nullval) by entailer!.\n                  assert_PROP (b_par = root) by entailer!. \n                  forward_if. (* if (p_gpar == NULL) *)\n                  2: { congruence. }\n                  forward. (* p_gpar = NULL; return! *)\n                  rewrite <- H3.\n                  Exists (T lch node_med rch) \n                         [(R, node_par, tree_rsib)]\n                         (field_address t_struct_tree [StructField _left] p_par_med)\n                          p_par_med.\n                  entailer!.\n                  expand treebox_rep.\n                  Exists p_med.\n                  expand partial_treebox_rep.\n                  Exists nullval p_rsib b_par.\n                  expand rbtree_rep.\n                  Exists p_lch p_rch.\n                  unfold_data_at (data_at _ t_struct_tree _ p_par_med).\n                  rewrite Ecolor_par.\n                  entailer!.\n   *** (* part_par = h0 :: l => p_gpar <> nullval *) (* \"有祖父节点\" *)\n                  destruct h0 as [[L_or_R node_gpar] Tree_Lunc_Or_Runc] eqn:Ehalf_gpar.\n                  destruct L_or_R.\n                  rename l into part_gpar.\n                  +++ (* part_par = (L, node_gpar, Tree_Lunc_Or_Runc) :: part_gpar *) (* \"\"\"p_par为右子树\"\"\" *)\n                      rename Tree_Lunc_Or_Runc into tree_lunc.\n                      remember (T tree_lunc node_gpar tree_par) as tree_gpar.\n                        (* tree_gpar = T tree_lunc node_gpar tree_par *)\n                      expand partial_treebox_rep.\n                      Intros p_ggpar p_lunc b_gpar.\n                      assert_PROP (p_gpar <> nullval) by entailer!. (* \"p_gpar <> nullval\" *)\n                      assert_PROP (is_pointer_or_null p_gpar) by entailer!.\n                      gather_SEP 5 7 8 9 10 11.\n                      replace_SEP 0 (\n                        data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node node_gpar))),\n                                                   (Vint (Int.repr (key_of_node node_gpar)),\n                                                    (Vint (Int.repr (value_of_node node_gpar)),\n                                                     (p_lunc, (p_par_med, p_ggpar))))) p_gpar\n                      ).\n                      { entailer!.\n                        unfold_data_at (data_at _ t_struct_tree _ p_gpar).\n                        entailer!. }\n                     forward_if. (* if (p_gpar == NULL) *)\n                      { congruence. }\n                      forward. (* calculate p_gpar->left *)\n                      forward_if_wrp. (* if (p_par == p_gpar->left) *) \n                     --- (* p_par == p_gpar->left => p_par = p_lunc => contradiction! *)\n                          destruct tree_lunc as [|tree_lunc_l node_lunc tree_lunc_r] eqn:ETree_lunc.\n                          { expand rbtree_rep.\n                            assert_PROP False by entailer!.\n                            contradiction. }\n                          { expand rbtree_rep. (* tree_lunc = T tree_lunc_l node_lunc tree_lunc_r *)\n                            Intros p_lunc_l p_lunc_r.\n                            assert_PROP False.\n                            { focus_SEP 1. (* 调换位置 *)\n                              sep_apply data_at_conflict; auto.\n                              entailer!. }\n                            contradiction. }\n                     --- (* \"p_par == p_gpar->right\" *)\n                          forward. (* calculate p_gpar->left *)\n                          destruct tree_lunc as [|tree_lunc_l node_lunc tree_lunc_r] eqn:ETree_lunc.\n                          ++++ (* \"tree_lunc = E\" *)\n                               expand rbtree_rep.\n                               assert_PROP (p_lunc = nullval) by entailer!.\n                               \n(* DECLARE _get_color2\n  WITH t: tree,\n       p: val,\n       p_par: val,\n       b: bool *)\n  (* (b = false <-> p = nullval)  *)                            \n                               \n                               forward_call( (* get_color2(p_gpar->left) *)\n                                 tree_lunc, p_lunc, p_gpar, false\n                               ). \n                               { entailer!. } (* 满足前条件 *)\n                               { tauto. }\n                               forward_if. (* if (get_color2(p_gpar->left) == RED) *)\n                               { contradiction. }\n                               forward. (* p_gpar->color = RED; *)\n                               forward. (* cal p_gpar->right *)\n                               forward_if_wrp. (* if (p == p_par->left) *)\n                               (*\" p = p_par->left \"*)\n                                    forward. (* p->color = BLACK; *)\n                                    forward_call(\n                                      p_med, p_par_med, p_gpar, p_rch, p_lch, p_rsib,\n                                      BlackNode node_med, node_par,\n                                       lch, tree_rsib, rch\n                                    ).\n                                    { rewrite Ecolor_par.\n                                      unfold Col2Z at 1.\n                                      entailer!. }\n                                    forward.\n                                    destruct part_gpar eqn:Egpart_par. (* 讨论gpar是否有父亲 目的是确定根节点是不是gpar *)\n                                    +++++ (* part_gpar = [] *) (* gpar 是根节点 *)\n                                          expand partial_treebox_rep.\n                                          assert_PROP (p_ggpar = nullval) by entailer!.\n                                          assert_PROP (b_gpar = root) by entailer!.\n                                          (* call: left_rotate_wrap(p_gpar, root) *)\n                                          forward_call(\n                                            p_gpar, p_med, p_ggpar, p_lch,\n                                            p_lunc, p_par_med, p_gpar, nullval, \n                                            RedNode node_gpar, BlackNode node_med,\n                                            tree_lunc, T rch node_par tree_rsib, lch,\n                                            root, false,\n                                            false, nullval, nullval, node_par, (* 此行无用 *)\n                                            true, E (* 此行无用 *)\n                                          ).\n                                          { entailer!. (* 满足前条件 *)\n                                            expand partial_tree_rep.\n                                            expand rbtree_rep.\n                                            Exists p_rch p_rsib.\n                                            entailer!. }\n                                          { repeat split; try tauto; (* 满足前条件 *)\n                                            subst; auto. }\n                                          forward.\n                                          remember (T rch node_par tree_rsib) as tree_par_new.\n                                          Exists (T \n                                                   (T E (RedNode node_gpar) lch) \n                                                   (BlackNode node_med) \n                                                   tree_par_new)\n                                                 (@nil half_tree)\n                                                 root nullval.\n                                          rewrite <- H3.\n                                          expand balance'.\n                                          rewrite Ecolor_par.\n                                          unfold l_rotate, r_rotate, makeBlack.\n                                          expand rbtree_rep.\n                                          expand partial_treebox_rep.\n                                          entailer!.\n                                          expand treebox_rep.\n                                          Exists p_med.\n                                          remember (T rch node_par tree_rsib) as tree_par_new.\n                                          expand rbtree_rep.\n                                          Exists p_gpar p_par_med nullval p_lch.\n                                          entailer!.\n                                    +++++ (* part_gpar = h1 :: l *) (* gpar 不是根节点 *)\n                                          destruct h1 as [[LR node_ggpar] Tree_ggpl_Or_ggpr] eqn:Ehalf_ggpar.\n                                          assert_PROP (p_ggpar <> nullval). {\n                                            destruct LR; expand partial_treebox_rep; Intros a b c; entailer!. }\n                                          destruct LR; expand partial_treebox_rep;\n                                          Intros p_gggpar p_ggpl_or_r b_ggpar;\n                                          assert_PROP(is_pointer_or_null p_ggpar) by entailer!;\n                                          assert_PROP(is_pointer_or_null p_ggpl_or_r) by entailer!.\n                                          ----\n                                            rename Tree_ggpl_Or_ggpr into tree_ggpl.\n                                            rename p_ggpl_or_r into p_ggpl.\n                                            rewrite partial_treebox_rep''.\n                                            destruct (rev l) eqn:El.\n                                            (* El : rev l = [] *)\n                                            { assert (l = [])by (apply rev_nil_elim in El; auto).\n                                              assert_PROP (p_gggpar = nullval /\\ root = b_ggpar). \n                                              { expand partial_treebox_rep_topdown. entailer!. }\n                                              expand partial_treebox_rep_topdown.\n                                              pose proof classic (p_ggpl <> p_gpar).\n                                              destruct H27.\n                                              destruct H28. \n                                              2:{ assert(p_ggpl = p_gpar) by tauto.\n                                                  destruct tree_ggpl; simpl.\n                                                  { assert_PROP (p_ggpl = nullval) by entailer!.\n                                                    subst. congruence. }\n                                                  Intros a b. subst.\n                                                  assert_PROP False;[|contradiction].\n                                                  focus_SEP 5.\n                                                  sep_apply data_at_conflict;auto.\n                                                  entailer!. }\n                                              (* p_ggpl <> p_gpar *)\n                                              destruct tree_ggpl as[|? ? ?] eqn:Tree.\n                                              -----\n                                                expand rbtree_rep.\n                                                forward_call(\n                                                  p_gpar, p_med, p_ggpar, p_lch,\n                                                  p_lunc, p_par_med, p_ggpar, nullval, \n                                                  RedNode node_gpar, BlackNode node_med,\n                                                  tree_lunc, T rch node_par tree_rsib, lch,\n                                                  root, true,\n                                                  false, p_gggpar, p_ggpl, node_ggpar,\n                                                  true, E\n                                                ).\n                                                { entailer!. expand rbtree_rep.\n                                                  Exists p_rch p_rsib; entailer!.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!. }\n                                                { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                forward.\n                                                remember (T rch node_par tree_rsib) as tree_par_new.\n                                                rewrite <- H3.\n                                                Exists (T \n                                                         (T E (RedNode node_gpar) lch) \n                                                         (BlackNode node_med) \n                                                         tree_par_new)\n                                                       [(L, node_ggpar, E)]\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                expand balance'.\n                                                rewrite Ecolor_par.\n                                                unfold l_rotate, r_rotate, makeBlack.\n                                                expand partial_treebox_rep.\n                                                Exists nullval nullval b_ggpar.\n                                                expand treebox_rep.\n                                                Exists p_med.\n                                                unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                entailer!.\n                                                remember (T rch node_par tree_rsib) as tree_par_new.\n                                                expand rbtree_rep.\n                                                Exists p_gpar p_par_med nullval p_lch.\n                                                entailer!.\n                                              -----\n                                                rewrite <- Tree.\n                                                forward_call(\n                                                  p_gpar, p_med, p_ggpar, p_lch,\n                                                  p_lunc, p_par_med, p_ggpar, nullval, \n                                                  RedNode node_gpar, BlackNode node_med,\n                                                  tree_lunc, T rch node_par tree_rsib, lch,\n                                                  root, true,\n                                                  false, p_gggpar, p_ggpl, node_ggpar,\n                                                  false, tree_ggpl\n                                                ).\n                                                { entailer!. \n                                                  remember ((T t3 n0 t4)) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  Exists p_rch p_rsib; entailer!. }\n                                                { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                forward.\n                                                remember (T rch node_par tree_rsib) as tree_par_new.\n                                                remember (T t3 n0 t4) as tree_ggpl.\n                                                rewrite <- H3.\n                                                Exists (T \n                                                         (T E (RedNode node_gpar) lch) \n                                                         (BlackNode node_med) \n                                                         tree_par_new)\n                                                       [(L, node_ggpar, tree_ggpl)]\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                expand balance'.\n                                                rewrite Ecolor_par.\n                                                unfold l_rotate, r_rotate, makeBlack.\n                                                expand partial_treebox_rep.\n                                                Exists nullval p_ggpl b_ggpar.\n                                                expand treebox_rep.\n                                                Exists p_med.\n                                                unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                entailer!.\n                                                remember (T rch node_par tree_rsib) as tree_par_new.\n                                                remember (T t3 n0 t4) as tree_ggpl.\n                                                expand rbtree_rep.\n                                                Exists p_gpar p_par_med nullval p_lch.\n                                                entailer!.\n                                              }\n                                              (* El : rev l = h2 :: l0 *)\n                                            { pose proof classic (p_ggpl <> p_gpar).\n                                              destruct H26. \n                                              2:{ assert(p_ggpl = p_gpar) by tauto.\n                                                  destruct tree_ggpl; expand rbtree_rep.\n                                                  { assert_PROP (p_ggpl = nullval) by entailer!.\n                                                    subst. congruence. }\n                                                  Intros a b. subst.\n                                                  assert_PROP False;[|contradiction].\n                                                  focus_SEP 5.\n                                                  sep_apply data_at_conflict;auto.\n                                                  entailer!. }\n                                              destruct h2 as [[LR_ans node_ans] tree_ans_another_child].\n                                              expand partial_treebox_rep_topdown.\n                                              destruct LR_ans. \n                                              -----\n                                                Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpl as[|] eqn:Tree.\n                                              ------\n                                                assert_PROP(p_ggpl = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_gpar, p_med, p_ggpar, p_lch,\n                                                       p_lunc, p_par_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_med,\n                                                       tree_lunc, T rch node_par tree_rsib, lch,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_rch p_rsib; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T rch node_par tree_rsib) as tree_par_new.\n                                                  Exists (T \n                                                         (T E (RedNode node_gpar) lch) \n                                                         (BlackNode node_med) \n                                                         tree_par_new)\n                                                         ((L, node_ggpar, E) :: l)\n                                                         (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                         p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  rewrite <- Heqtree_par_new.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T rch node_par tree_rsib) as tree_par_new.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_par_med nullval p_lch.\n                                                  entailer!.\n                                                ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_gpar, p_med, p_ggpar, p_lch,\n                                                  p_lunc, p_par_med, p_ans, nullval, \n                                                  RedNode node_gpar, BlackNode node_med,\n                                                  tree_lunc, T rch node_par tree_rsib, lch,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       false, tree_ggpl).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_rch p_rsib; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T rch node_par tree_rsib) as tree_par_new.\n                                                  remember (T t3 n0 t4) as tree_ggpl.\n                                                  Exists (T \n                                                         (T E (RedNode node_gpar) lch) \n                                                         (BlackNode node_med) \n                                                         tree_par_new)\n                                                         ((L, node_ggpar, tree_ggpl) :: l)\n                                                         (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                         p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpl b_ggpar.\n                                                  entailer!.\n                                                  remember (T rch node_par tree_rsib) as tree_par_new.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T rch node_par tree_rsib) as tree_par_new.\n                                                  remember (T t3 n0 t4) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_par_med nullval p_lch.\n                                                  entailer!.\n                                              -----\n                                                Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpl as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpl = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_gpar, p_med, p_ggpar, p_lch,\n                                                  p_lunc, p_par_med, p_ans, nullval, \n                                                  RedNode node_gpar, BlackNode node_med,\n                                                  tree_lunc, T rch node_par tree_rsib, lch,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_rch p_rsib; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T rch node_par tree_rsib) as tree_par_new.\n                                                  Exists (T \n                                                         (T E (RedNode node_gpar) lch) \n                                                         (BlackNode node_med) \n                                                         tree_par_new)\n                                                         ((L, node_ggpar, E) :: l)\n                                                         (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                         p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  rewrite <- Heqtree_par_new.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T rch node_par tree_rsib) as tree_par_new.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_par_med nullval p_lch.\n                                                  entailer!.\n                                                ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_gpar, p_med, p_ggpar, p_lch,\n                                                  p_lunc, p_par_med, p_ans, nullval, \n                                                  RedNode node_gpar, BlackNode node_med,\n                                                  tree_lunc, T rch node_par tree_rsib, lch,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       false, tree_ggpl).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_rch p_rsib; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T rch node_par tree_rsib) as tree_par_new.\n                                                  remember (T t3 n0 t4) as tree_ggpl.\n                                                  Exists (T \n                                                         (T E (RedNode node_gpar) lch) \n                                                         (BlackNode node_med) \n                                                         tree_par_new)\n                                                         ((L, node_ggpar, tree_ggpl) :: l)\n                                                         (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                         p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpl b_ggpar.\n                                                  entailer!.\n                                                  remember (T rch node_par tree_rsib) as tree_par_new.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T rch node_par tree_rsib) as tree_par_new.\n                                                  remember (T t3 n0 t4) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_par_med nullval p_lch.\n                                                  entailer!.\n                                            }\n                                          ----\n                                            rename Tree_ggpl_Or_ggpr into tree_ggpr.\n                                            rename p_ggpl_or_r into p_ggpr.\n                                            rewrite partial_treebox_rep''.\n                                            destruct (rev l) eqn:El.\n                                            (* El : rev l = [] *)\n                                            { assert (l = [])by (apply rev_nil_elim in El; auto).\n                                              assert_PROP (p_gggpar = nullval /\\ root = b_ggpar). \n                                              { expand partial_treebox_rep_topdown. entailer!. }\n                                              expand partial_treebox_rep_topdown.\n                                              pose proof classic (p_ggpr <> p_gpar).\n                                              destruct H27.\n                                              destruct H28. \n                                              2:{ assert(p_ggpr = p_gpar) by tauto.\n                                                  destruct tree_ggpr; simpl.\n                                                  { assert_PROP (p_ggpr = nullval) by entailer!.\n                                                    subst. congruence. }\n                                                  Intros a b. subst.\n                                                  assert_PROP False;[|contradiction].\n                                                  focus_SEP 5.\n                                                  sep_apply data_at_conflict;auto.\n                                                  entailer!. }\n                                              (* p_ggpr <> p_gpar *)\n                                              destruct tree_ggpr as[|? ? ?] eqn:Tree.\n                                              -----\n                                                expand rbtree_rep.\n                                                forward_call(\n                                                  p_gpar, p_med, p_ggpar, p_lch,\n                                                  p_lunc, p_par_med, p_ggpar, nullval, \n                                                  RedNode node_gpar, BlackNode node_med,\n                                                  tree_lunc, T rch node_par tree_rsib, lch,\n                                                  root, true,\n                                                  true, p_gggpar, p_ggpr, node_ggpar,\n                                                  true, E\n                                                ).\n                                                { entailer!. expand rbtree_rep.\n                                                  Exists p_rch p_rsib; entailer!.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!. }\n                                                { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                forward.\n                                                remember (T rch node_par tree_rsib) as tree_par_new.\n                                                rewrite <- H3.\n                                                Exists (T \n                                                         (T E (RedNode node_gpar) lch) \n                                                         (BlackNode node_med) \n                                                         tree_par_new)\n                                                       [(R, node_ggpar, E)]\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                expand balance'.\n                                                rewrite Ecolor_par.\n                                                unfold l_rotate, r_rotate, makeBlack.\n                                                expand partial_treebox_rep.\n                                                Exists nullval nullval b_ggpar.\n                                                expand treebox_rep.\n                                                Exists p_med.\n                                                unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                entailer!.\n                                                remember (T rch node_par tree_rsib) as tree_par_new.\n                                                expand rbtree_rep.\n                                                Exists p_gpar p_par_med nullval p_lch.\n                                                entailer!.\n                                              -----\n                                                rewrite <- Tree.\n                                                forward_call(\n                                                  p_gpar, p_med, p_ggpar, p_lch,\n                                                  p_lunc, p_par_med, p_ggpar, nullval, \n                                                  RedNode node_gpar, BlackNode node_med,\n                                                  tree_lunc, T rch node_par tree_rsib, lch,\n                                                  root, true,\n                                                  true, p_gggpar, p_ggpr, node_ggpar,\n                                                  false, tree_ggpr\n                                                ).\n                                                { entailer!. \n                                                  remember ((T t3 n0 t4)) as tree_ggpr.\n                                                  expand rbtree_rep.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  Exists p_rch p_rsib; entailer!. }\n                                                { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                forward.\n                                                remember (T rch node_par tree_rsib) as tree_par_new.\n                                                remember (T t3 n0 t4) as tree_ggpr.\n                                                rewrite <- H3.\n                                                Exists (T \n                                                         (T E (RedNode node_gpar) lch) \n                                                         (BlackNode node_med) \n                                                         tree_par_new)\n                                                       [(R, node_ggpar, tree_ggpr)]\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                expand balance'.\n                                                rewrite Ecolor_par.\n                                                unfold l_rotate, r_rotate, makeBlack.\n                                                expand partial_treebox_rep.\n                                                Exists nullval p_ggpr b_ggpar.\n                                                expand treebox_rep.\n                                                Exists p_med.\n                                                unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                entailer!.\n                                                remember (T rch node_par tree_rsib) as tree_par_new.\n                                                remember (T t3 n0 t4) as tree_ggpr.\n                                                expand rbtree_rep.\n                                                Exists p_gpar p_par_med nullval p_lch.\n                                                entailer!.\n                                              }  \n                                              (* El : rev l = h2 :: l0 *)\n                                            { pose proof classic (p_ggpr <> p_gpar).\n                                              destruct H26. \n                                              2:{ assert(p_ggpr = p_gpar) by tauto.\n                                                  destruct tree_ggpr; expand rbtree_rep.\n                                                  { assert_PROP (p_ggpr = nullval) by entailer!.\n                                                    subst. congruence. }\n                                                  Intros a b. subst.\n                                                  assert_PROP False;[|contradiction].\n                                                  focus_SEP 5.\n                                                  sep_apply data_at_conflict;auto.\n                                                  entailer!. }\n                                              destruct h2 as [[LR_ans node_ans] tree_ans_another_child].\n                                              expand partial_treebox_rep_topdown.\n                                              destruct LR_ans. \n                                              -----\n                                                Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpr as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpr = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_gpar, p_med, p_ggpar, p_lch,\n                                                       p_lunc, p_par_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_med,\n                                                       tree_lunc, T rch node_par tree_rsib, lch,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpr, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_rch p_rsib; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T rch node_par tree_rsib) as tree_par_new.\n                                                  Exists (T \n                                                         (T E (RedNode node_gpar) lch) \n                                                         (BlackNode node_med) \n                                                         tree_par_new)\n                                                         ((R, node_ggpar, E) :: l)\n                                                         (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                         p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  rewrite <- Heqtree_par_new.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T rch node_par tree_rsib) as tree_par_new.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_par_med nullval p_lch.\n                                                  entailer!.\n                                                ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_gpar, p_med, p_ggpar, p_lch,\n                                                       p_lunc, p_par_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_med,\n                                                       tree_lunc, T rch node_par tree_rsib, lch,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpr, node_ggpar,\n                                                       false, tree_ggpr).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_rch p_rsib; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T rch node_par tree_rsib) as tree_par_new.\n                                                  remember (T t3 n0 t4) as tree_ggpr.\n                                                  Exists (T \n                                                         (T E (RedNode node_gpar) lch) \n                                                         (BlackNode node_med) \n                                                         tree_par_new)\n                                                         ((R, node_ggpar, tree_ggpr) :: l)\n                                                         (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                         p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpr b_ggpar.\n                                                  entailer!.\n                                                  remember (T rch node_par tree_rsib) as tree_par_new.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T rch node_par tree_rsib) as tree_par_new.\n                                                  remember (T t3 n0 t4) as tree_ggpr.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_par_med nullval p_lch.\n                                                  entailer!.\n                                              -----\n                                                Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpr as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpr = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_gpar, p_med, p_ggpar, p_lch,\n                                                       p_lunc, p_par_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_med,\n                                                       tree_lunc, T rch node_par tree_rsib, lch,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpr, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_rch p_rsib; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T rch node_par tree_rsib) as tree_par_new.\n                                                  Exists (T \n                                                         (T E (RedNode node_gpar) lch) \n                                                         (BlackNode node_med) \n                                                         tree_par_new)\n                                                         ((R, node_ggpar, E) :: l)\n                                                         (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                         p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  rewrite <- Heqtree_par_new.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T rch node_par tree_rsib) as tree_par_new.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_par_med nullval p_lch.\n                                                  entailer!.\n                                                ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_gpar, p_med, p_ggpar, p_lch,\n                                                       p_lunc, p_par_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_med,\n                                                       tree_lunc, T rch node_par tree_rsib, lch,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpr, node_ggpar,\n                                                       false, tree_ggpr).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_rch p_rsib; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T rch node_par tree_rsib) as tree_par_new.\n                                                  remember (T t3 n0 t4) as tree_ggpr.\n                                                  Exists (T \n                                                         (T E (RedNode node_gpar) lch) \n                                                         (BlackNode node_med) \n                                                         tree_par_new)\n                                                         ((R, node_ggpar, tree_ggpr) :: l)\n                                                         (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                         p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpr b_ggpar.\n                                                  entailer!.\n                                                  remember (T rch node_par tree_rsib) as tree_par_new.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T rch node_par tree_rsib) as tree_par_new.\n                                                  remember (T t3 n0 t4) as tree_ggpr.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_par_med nullval p_lch.\n                                                  entailer!.\n                                            }\n                            ++++ (* \"tree_lunc = T tree_lunc_l node_lunc tree_lunc_r\" *)\n                               assert_PROP (p_lunc <> nullval).\n                               { expand rbtree_rep; Intros a b; entailer!. }\n                               destruct (color_of_node node_lunc) eqn: color_lunc.\n                               ---- (* \"lunc is RED\" *)\n(* DECLARE _get_color2\n  WITH t: tree,\n       p: val,\n       p_par: val,\n       b: bool *)\n  (* (b = false <-> p = nullval)  *) \n                                 forward_call( (* get_color2(p_gpar->left) *)\n                                   tree_lunc, p_lunc, p_gpar, true\n                                 ). \n                                 { entailer!. } (* 满足前条件 *)\n                                 { tauto. }\n                                 rewrite ETree_lunc, color_lunc.\n                                 unfold Col2Z at 1. (*  , RED_COLOR, BLACK_COLOR. *)\n                                 forward_if. (* if (get_color2(p_gpar->right) == RED) *)\n                                 2: { assert_PROP False by entailer!; tauto. }\n                                 forward.\n                                 forward.\n                                 expand rbtree_rep.\n                                 Intros p_lunc_l p_lunc_r.\n                                 forward.\n                                 forward.\n                                 forward.\n                                 Exists (T (makeBlack tree_lunc) \n                                           (RedNode node_gpar)\n                                           (T tree_med (BlackNode node_par) tree_rsib))\n                                   part_gpar\n                                   b_gpar\n                                   p_ggpar\n                                   p_gpar.\n                                 rewrite <- H3.\n                                 expand balance'.\n                                 rewrite Ecolor_par.\n                                 expand rbtree_rep.\n                                 Exists p_lunc p_par_med p_med p_rsib.\n                                 entailer!.\n                                 2:{ unfold makeBlack. expand rbtree_rep. \n                                     Exists p_lunc_l p_lunc_r p_lch p_rch.\n                                     entailer!. } \n                                 simpl (color_of_node node_lunc).\n                                 destruct node_lunc as [a b c].\n                                 assert(a = Red).\n                                 { auto. }\n                                 subst. reflexivity.\n                               ---- (* \"lunc is BLACK\" *)\n                                 forward_call( (* get_color2(p_gpar->left) *)\n                                   tree_lunc, p_lunc, p_gpar, true\n                                 ). \n                                 { entailer!. } (* 满足前条件 *)\n                                 { tauto. }\n                                 rewrite ETree_lunc, color_lunc.\n                                 unfold Col2Z at 1, RED_COLOR, BLACK_COLOR.\n                                 forward_if. (* if (get_color2(p_gpar->left) == RED) *)\n                                 1: { assert_PROP False by entailer!; tauto. }\n                                 forward.\n                                 forward.\n                                 forward_if_wrp.\n                                 (* \"p = p_par->left\" *)\n                                   forward. (* p_par->color = BLACK; *)\n                                   forward_call(\n                                      p_med, p_par_med, p_gpar, p_rch, p_lch, p_rsib,\n                                      BlackNode node_med, node_par,\n                                       lch, tree_rsib, rch\n                                    ).\n                                    { rewrite Ecolor_par.\n                                      unfold Col2Z at 1.\n                                      entailer!. }\n                                    forward.\n                                   destruct part_gpar eqn:Egpart_par. (* 讨论gpar是否有父亲 目的是确定根节点是不是gpar *)\n                                   +++++ (* part_gpar = [] *) (* gpar 是根节点 *)\n                                     expand partial_treebox_rep.\n                                     assert_PROP (p_ggpar = nullval) by entailer!.\n                                     assert_PROP (b_gpar = root) by entailer!.\n                                     (* call: left_rotate_wrap(p_gpar, root) *)\n                                     forward_call(\n                                            p_gpar, p_med, p_ggpar, p_lch,\n                                            p_lunc, p_par_med, p_gpar, nullval, \n                                            RedNode node_gpar, BlackNode node_med,\n                                            tree_lunc, T rch node_par tree_rsib, lch,\n                                            root, false,\n                                            false, nullval, nullval, node_par, (* 此行无用 *)\n                                            true, E (* 此行无用 *)\n                                          ).\n                                          { entailer!. (* 满足前条件 *)\n                                            expand partial_tree_rep.\n                                            expand rbtree_rep.\n                                            Exists p_rch p_rsib.\n                                            entailer!. }\n                                          { repeat split; try tauto; (* 满足前条件 *)\n                                            subst; auto. }\n                                          forward.\n                                     remember (T rch node_par tree_rsib) as tree_par_new.\n                                     remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc.\n                                     Exists \n                                       (T \n                                                   (T tree_lunc (RedNode node_gpar) lch) \n                                                   (BlackNode node_med) \n                                                   tree_par_new)\n                                       (@nil half_tree)\n                                       root nullval.\n                                     rewrite <- H3.\n                                     expand balance'.\n                                     rewrite Ecolor_par.\n                                     destruct node_lunc as[c_lunc k_lunc v_lunc].\n                                     assert(c_lunc = Black)by auto.\n                                     subst c_lunc tree_lunc.\n                                     unfold l_rotate, r_rotate, makeBlack.\n                                     remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc.\n                                     expand partial_treebox_rep.\n                                     entailer!.\n                                     remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc.\n                                     expand treebox_rep.\n                                     Exists p_med.\n                                     entailer!.\n                                     remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc.\n                                     remember (T rch node_par tree_rsib) as tree_par_new.\n                                     remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc.\n                                     expand rbtree_rep.\n                                     Exists p_gpar p_par_med p_lunc p_lch.\n                                     entailer!.\n                                   +++++ (* part_gpar = h1 :: l *) (* gpar 不是根节点 *)\n                                     destruct h1 as [[LR node_ggpar] Tree_ggpl_Or_ggpr] eqn:Ehalf_ggpar.\n                                     assert_PROP (p_ggpar <> nullval).\n                                     { destruct LR; expand partial_treebox_rep; Intros a b c; entailer!. }\n                                     destruct LR; expand partial_treebox_rep;\n                                       Intros p_gggpar p_ggpl_or_r b_ggpar;\n                                       assert_PROP(is_pointer_or_null p_ggpar) by entailer!;\n                                       assert_PROP(is_pointer_or_null p_ggpl_or_r) by entailer!.\n                                     -----\n                                       rename Tree_ggpl_Or_ggpr into tree_ggpl.\n                                       rename p_ggpl_or_r into p_ggpl.\n                                       rewrite partial_treebox_rep''.\n                                       destruct (rev l) eqn:El.\n                                       (* El : rev l = [] *)\n                                       { assert (l = [])by (apply rev_nil_elim in El; auto).\n                                         assert_PROP (p_gggpar = nullval /\\ root = b_ggpar). \n                                         { expand partial_treebox_rep_topdown. entailer!. }\n                                       expand partial_treebox_rep_topdown.\n                                       pose proof classic (p_ggpl <> p_gpar).\n                                       destruct H27.\n                                       destruct H28. \n                                       2:{ assert(p_ggpl = p_gpar) by tauto.\n                                           destruct tree_ggpl; simpl.\n                                           { assert_PROP (p_ggpl = nullval) by entailer!.\n                                             subst. congruence. }\n                                           Intros a b. subst.\n                                           assert_PROP False;[|contradiction].\n                                           focus_SEP 8.\n                                           sep_apply data_at_conflict;auto.\n                                           entailer!. }\n                                       (* p_ggpl <> p_gpar *)\n                                       destruct tree_ggpl as[|? ? ?] eqn:Tree.\n                                       *****\n                                         expand rbtree_rep.\n                                         forward_call(\n                                                  p_gpar, p_med, p_ggpar, p_lch,\n                                                  p_lunc, p_par_med, p_ggpar, nullval, \n                                                  RedNode node_gpar, BlackNode node_med,\n                                                  tree_lunc, T rch node_par tree_rsib, lch,\n                                                  root, true,\n                                                  false, p_gggpar, p_ggpl, node_ggpar,\n                                                  true, E\n                                                ).\n                                                { entailer!. expand rbtree_rep.\n                                                  Exists p_rch p_rsib; entailer!.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!. }\n                                         { repeat split; try tauto; subst; auto. intros. congruence. }\n                                         forward.\n                                         repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                         rewrite <- H3.\n                                         Exists (T \n                                                         (T tree_lunc (RedNode node_gpar) lch) \n                                                         (BlackNode node_med) \n                                                         tree_par_new)\n                                                       [(L, node_ggpar, E)]\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                         expand balance'.\n                                         rewrite Ecolor_par.\n                                         rewrite Heqtree_lunc.\n                                         destruct node_lunc as[c_lunc k_lunc v_lunc].\n                                         assert(c_lunc = Black)by auto.\n                                         subst c_lunc.\n                                         unfold l_rotate, r_rotate, makeBlack.\n                                         expand partial_treebox_rep.\n                                         Exists nullval nullval b_ggpar.\n                                         entailer!.\n                                         expand treebox_rep.\n                                         Exists p_med.\n                                         unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                         entailer.\n                                         repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                         expand rbtree_rep.\n                                         Exists p_gpar p_par_med p_lunc p_lch.\n                                         entailer!.\n                                       *****\n                                         rewrite <- Tree.\n                                         forward_call(\n                                                  p_gpar, p_med, p_ggpar, p_lch,\n                                                  p_lunc, p_par_med, p_ggpar, nullval, \n                                                  RedNode node_gpar, BlackNode node_med,\n                                                  tree_lunc, T rch node_par tree_rsib, lch,\n                                                  root, true,\n                                                  false, p_gggpar, p_ggpl, node_ggpar,\n                                                  false, tree_ggpl\n                                                ).\n                                         { entailer!. \n                                           remember ((T t3 n0 t4)) as tree_ggpl.\n                                           expand rbtree_rep.\n                                           unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                           Exists p_rch p_rsib; entailer!. }\n                                         { repeat split; try tauto; subst; auto. intros. congruence. }\n                                         forward. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                         rewrite <- H3.\n                                         Exists (T \n                                                         (T tree_lunc (RedNode node_gpar) lch) \n                                                         (BlackNode node_med) \n                                                         tree_par_new)\n                                                       [(L, node_ggpar, tree_ggpl)]\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                         expand balance'.\n                                         rewrite Ecolor_par. rewrite Heqtree_lunc.\n                                         destruct node_lunc as[c_lunc k_lunc v_lunc].\n                                         assert(c_lunc = Black)by auto.\n                                         subst c_lunc.\n                                         unfold l_rotate, r_rotate, makeBlack.\n                                         expand partial_treebox_rep.\n                                         Exists nullval p_ggpl b_ggpar.\n                                         entailer!.\n                                         repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                         expand treebox_rep.\n                                         Exists p_med.\n                                         unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                         expand rbtree_rep.\n                                         Exists p_gpar p_par_med p_lunc p_lch.\n                                         entailer!.\n                                       }\n                                       (* El : rev l = h2 :: l0 *)\n                                       { pose proof classic (p_ggpl <> p_gpar).\n                                         destruct H26. \n                                         2:{ assert(p_ggpl = p_gpar) by tauto.\n                                                  destruct tree_ggpl; expand rbtree_rep.\n                                                  { assert_PROP (p_ggpl = nullval) by entailer!.\n                                                    subst. congruence. }\n                                                  Intros a b. subst.\n                                                  assert_PROP False;[|contradiction].\n                                                  focus_SEP 8.\n                                                  sep_apply data_at_conflict;auto.\n                                                  entailer!. }\n                                         destruct h2 as [[LR_ans node_ans] tree_ans_another_child].\n                                         expand partial_treebox_rep_topdown.\n                                         destruct LR_ans. \n                                         ++++++\n                                                Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpl as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpl = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_gpar, p_med, p_ggpar, p_lch,\n                                                       p_lunc, p_par_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_med,\n                                                       tree_lunc, T rch node_par tree_rsib, lch,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_rch p_rsib; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                                  Exists (T \n                                                         (T tree_lunc (RedNode node_gpar) lch) \n                                                         (BlackNode node_med) \n                                                         tree_par_new)\n                                                         ((L, node_ggpar, E) :: l)\n                                                         (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                         p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_lunc.\n                                                  destruct node_lunc as[c_lunc k_lunc v_lunc].\n                                                  assert(c_lunc = Black)by auto.\n                                                  subst c_lunc.\n                                                  repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_par_med p_lunc p_lch.\n                                                  entailer!.\n                                              ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_gpar, p_med, p_ggpar, p_lch,\n                                                       p_lunc, p_par_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_med,\n                                                       tree_lunc, T rch node_par tree_rsib, lch,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       false, tree_ggpl).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_rch p_rsib; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                                  Exists (T \n                                                         (T tree_lunc (RedNode node_gpar) lch) \n                                                         (BlackNode node_med) \n                                                         tree_par_new)\n                                                       ((L, node_ggpar, tree_ggpl) :: l)\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_lunc.\n                                                  destruct node_lunc as[c_lunc k_lunc v_lunc].\n                                                  assert(c_lunc = Black)by auto.\n                                                  subst c_lunc. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpl b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_par_med p_lunc p_lch.\n                                                  entailer!.\n                                           ++++++\n                                               Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpl as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpl = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_gpar, p_med, p_ggpar, p_lch,\n                                                       p_lunc, p_par_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_med,\n                                                       tree_lunc, T rch node_par tree_rsib, lch,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_rch p_rsib; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                                  Exists (T \n                                                         (T tree_lunc (RedNode node_gpar) lch) \n                                                         (BlackNode node_med) \n                                                         tree_par_new)\n                                                         ((L, node_ggpar, E) :: l)\n                                                         (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                         p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_lunc.\n                                                  destruct node_lunc as[c_lunc k_lunc v_lunc].\n                                                  assert(c_lunc = Black)by auto.\n                                                  subst c_lunc.\n                                                  repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_par_med p_lunc p_lch.\n                                                  entailer!.\n                                              ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_gpar, p_med, p_ggpar, p_lch,\n                                                       p_lunc, p_par_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_med,\n                                                       tree_lunc, T rch node_par tree_rsib, lch,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       false, tree_ggpl).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_rch p_rsib; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                                  Exists (T \n                                                         (T tree_lunc (RedNode node_gpar) lch) \n                                                         (BlackNode node_med) \n                                                         tree_par_new)\n                                                       ((L, node_ggpar, tree_ggpl) :: l)\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_lunc.\n                                                  destruct node_lunc as[c_lunc k_lunc v_lunc].\n                                                  assert(c_lunc = Black)by auto.\n                                                  subst c_lunc. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpl b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_par_med p_lunc p_lch.\n                                                  entailer!.\n                                                  }\n                                       -----\n                                       rename Tree_ggpl_Or_ggpr into tree_ggpr.\n                                       rename p_ggpl_or_r into p_ggpr.\n                                       rewrite partial_treebox_rep''.\n                                       destruct (rev l) eqn:El.\n                                       (* El : rev l = [] *)\n                                       { assert (l = [])by (apply rev_nil_elim in El; auto).\n                                         assert_PROP (p_gggpar = nullval /\\ root = b_ggpar). \n                                         { expand partial_treebox_rep_topdown. entailer!. }\n                                       expand partial_treebox_rep_topdown.\n                                       pose proof classic (p_ggpr <> p_gpar).\n                                       destruct H27.\n                                       destruct H28. \n                                       2:{ assert(p_ggpr = p_gpar) by tauto.\n                                           destruct tree_ggpr; simpl.\n                                           { assert_PROP (p_ggpr = nullval) by entailer!.\n                                             subst. congruence. }\n                                           Intros a b. subst.\n                                           assert_PROP False;[|contradiction].\n                                           focus_SEP 8.\n                                           sep_apply data_at_conflict;auto.\n                                           entailer!. }\n                                       (* p_ggpr <> p_gpar *)\n                                       destruct tree_ggpr as[|? ? ?] eqn:Tree.\n                                       *****\n                                         expand rbtree_rep.\n                                         forward_call(\n                                                  p_gpar, p_med, p_ggpar, p_lch,\n                                                  p_lunc, p_par_med, p_ggpar, nullval, \n                                                  RedNode node_gpar, BlackNode node_med,\n                                                  tree_lunc, T rch node_par tree_rsib, lch,\n                                                  root, true,\n                                                  true, p_gggpar, p_ggpr, node_ggpar,\n                                                  true, E\n                                                ).\n                                                { entailer!. expand rbtree_rep.\n                                                  Exists p_rch p_rsib; entailer!.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!. }\n                                         { repeat split; try tauto; subst; auto. intros. congruence. }\n                                         forward.\n                                         repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                         rewrite <- H3.\n                                         Exists (T \n                                                         (T tree_lunc (RedNode node_gpar) lch) \n                                                         (BlackNode node_med) \n                                                         tree_par_new)\n                                                       [(R, node_ggpar, E)]\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                         expand balance'.\n                                         rewrite Ecolor_par.\n                                         rewrite Heqtree_lunc.\n                                         destruct node_lunc as[c_lunc k_lunc v_lunc].\n                                         assert(c_lunc = Black)by auto.\n                                         subst c_lunc.\n                                         unfold l_rotate, r_rotate, makeBlack.\n                                         expand partial_treebox_rep.\n                                         Exists nullval nullval b_ggpar.\n                                         entailer!.\n                                         expand treebox_rep.\n                                         Exists p_med.\n                                         unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                         entailer.\n                                         repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                         expand rbtree_rep.\n                                         Exists p_gpar p_par_med p_lunc p_lch.\n                                         entailer!.\n                                       *****\n                                         rewrite <- Tree.\n                                         forward_call(\n                                                  p_gpar, p_med, p_ggpar, p_lch,\n                                                  p_lunc, p_par_med, p_ggpar, nullval, \n                                                  RedNode node_gpar, BlackNode node_med,\n                                                  tree_lunc, T rch node_par tree_rsib, lch,\n                                                  root, true,\n                                                  true, p_gggpar, p_ggpr, node_ggpar,\n                                                  false, tree_ggpr\n                                                ).\n                                         { entailer!. \n                                           remember ((T t3 n0 t4)) as tree_ggpr.\n                                           expand rbtree_rep.\n                                           unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                           Exists p_rch p_rsib; entailer!. }\n                                         { repeat split; try tauto; subst; auto. intros. congruence. }\n                                         forward. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                         rewrite <- H3.\n                                         Exists (T \n                                                         (T tree_lunc (RedNode node_gpar) lch) \n                                                         (BlackNode node_med) \n                                                         tree_par_new)\n                                                       [(R, node_ggpar, tree_ggpr)]\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                         expand balance'.\n                                         rewrite Ecolor_par. rewrite Heqtree_lunc.\n                                         destruct node_lunc as[c_lunc k_lunc v_lunc].\n                                         assert(c_lunc = Black)by auto.\n                                         subst c_lunc.\n                                         unfold l_rotate, r_rotate, makeBlack.\n                                         expand partial_treebox_rep.\n                                         Exists nullval p_ggpr b_ggpar.\n                                         entailer!.\n                                         repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                         expand treebox_rep.\n                                         Exists p_med.\n                                         unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                         expand rbtree_rep.\n                                         Exists p_gpar p_par_med p_lunc p_lch.\n                                         entailer!.\n                                       }\n                                       (* El : rev l = h2 :: l0 *)\n                                       { pose proof classic (p_ggpr <> p_gpar).\n                                         destruct H26. \n                                         2:{ assert(p_ggpr = p_gpar) by tauto.\n                                                  destruct tree_ggpr; expand rbtree_rep.\n                                                  { assert_PROP (p_ggpr = nullval) by entailer!.\n                                                    subst. congruence. }\n                                                  Intros a b. subst.\n                                                  assert_PROP False;[|contradiction].\n                                                  focus_SEP 8.\n                                                  sep_apply data_at_conflict;auto.\n                                                  entailer!. }\n                                         destruct h2 as [[LR_ans node_ans] tree_ans_another_child].\n                                         expand partial_treebox_rep_topdown.\n                                         destruct LR_ans. \n                                         ++++++\n                                                Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpr as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpr = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_gpar, p_med, p_ggpar, p_lch,\n                                                       p_lunc, p_par_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_med,\n                                                       tree_lunc, T rch node_par tree_rsib, lch,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpr, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_rch p_rsib; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                                  Exists (T \n                                                         (T tree_lunc (RedNode node_gpar) lch) \n                                                         (BlackNode node_med) \n                                                         tree_par_new)\n                                                         ((R, node_ggpar, E) :: l)\n                                                         (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                         p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_lunc.\n                                                  destruct node_lunc as[c_lunc k_lunc v_lunc].\n                                                  assert(c_lunc = Black)by auto.\n                                                  subst c_lunc.\n                                                  repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_par_med p_lunc p_lch.\n                                                  entailer!.\n                                              ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_gpar, p_med, p_ggpar, p_lch,\n                                                       p_lunc, p_par_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_med,\n                                                       tree_lunc, T rch node_par tree_rsib, lch,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpr, node_ggpar,\n                                                       false, tree_ggpr).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_rch p_rsib; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                                  Exists (T \n                                                         (T tree_lunc (RedNode node_gpar) lch) \n                                                         (BlackNode node_med) \n                                                         tree_par_new)\n                                                       ((R, node_ggpar, tree_ggpr) :: l)\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_lunc.\n                                                  destruct node_lunc as[c_lunc k_lunc v_lunc].\n                                                  assert(c_lunc = Black)by auto.\n                                                  subst c_lunc. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpr b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_par_med p_lunc p_lch.\n                                                  entailer!.\n                                           ++++++\n                                               Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpr as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpr = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_gpar, p_med, p_ggpar, p_lch,\n                                                       p_lunc, p_par_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_med,\n                                                       tree_lunc, T rch node_par tree_rsib, lch,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpr, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_rch p_rsib; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                                  Exists (T \n                                                         (T tree_lunc (RedNode node_gpar) lch) \n                                                         (BlackNode node_med) \n                                                         tree_par_new)\n                                                         ((R, node_ggpar, E) :: l)\n                                                         (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                         p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_lunc.\n                                                  destruct node_lunc as[c_lunc k_lunc v_lunc].\n                                                  assert(c_lunc = Black)by auto.\n                                                  subst c_lunc.\n                                                  repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_par_med p_lunc p_lch.\n                                                  entailer!.\n                                              ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_gpar, p_med, p_ggpar, p_lch,\n                                                       p_lunc, p_par_med, p_ans, nullval, \n                                                       RedNode node_gpar, BlackNode node_med,\n                                                       tree_lunc, T rch node_par tree_rsib, lch,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpr, node_ggpar,\n                                                       false, tree_ggpr).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_rch p_rsib; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                                  Exists (T \n                                                         (T tree_lunc (RedNode node_gpar) lch) \n                                                         (BlackNode node_med) \n                                                         tree_par_new)\n                                                       ((R, node_ggpar, tree_ggpr) :: l)\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_lunc.\n                                                  destruct node_lunc as[c_lunc k_lunc v_lunc].\n                                                  assert(c_lunc = Black)by auto.\n                                                  subst c_lunc. repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                                  unfold l_rotate, r_rotate, makeBlack.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpr b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  repeat\n\t\t\t\t\t\t\t\t\t  remember ({| color_of_node := Black; key_of_node := k_lunc; value_of_node := v_lunc |}) as node_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T rch node_par tree_rsib) as tree_par_new +\n\t\t\t\t\t\t\t\t\t  remember (T tree_lunc_l node_lunc tree_lunc_r) as tree_lunc +\n\t\t\t\t\t\t\t\t\t  remember (T t3 n0 t4) as tree_ggpr.\n                                                  expand rbtree_rep.\n                                                  Exists p_gpar p_par_med p_lunc p_lch.\n                                                  entailer!.\n                                                  }\n+++ rename l into part_gpar. (* part_par = (R, node_gpar, Tree_Lunc_Or_Runc) :: part_gpar *)\n    rename Tree_Lunc_Or_Runc into tree_runc.\n                      remember (T tree_runc node_gpar tree_par) as tree_gpar.\n                        (* tree_gpar = T tree_lunc node_gpar tree_par *)\n                      expand partial_treebox_rep.\n                      Intros p_ggpar p_runc b_gpar.\n                      assert_PROP (p_gpar <> nullval) by entailer!. (* \"p_gpar <> nullval\" *)\n                      gather_SEP 5 7 8 9 10 11.\n                      replace_SEP 0 (\n                        data_at Tsh t_struct_tree (Vint (Int.repr (Col2Z (color_of_node node_gpar))),\n                                                   (Vint (Int.repr (key_of_node node_gpar)),\n                                                    (Vint (Int.repr (value_of_node node_gpar)),\n                                                     (p_par_med, (p_runc, p_ggpar))))) p_gpar\n                      ).\n                      { entailer!.\n                        unfold_data_at (data_at _ t_struct_tree _ p_gpar).\n                        entailer!. }\n                      forward_if. (* if (p_gpar == NULL) *)\n                      { congruence. }\n                      forward. (* calculate p_gpar->left *)\n                      forward_if_wrp. (* \"p_par == p_gpar->left\" *)\n                      forward. (* calculate p_gpar->left *)\n                          destruct tree_runc as [|tree_runc_l node_runc tree_runc_r] eqn:ETree_runc.\n                          ++++ (* \"tree_runc = E\" *)\n                               expand rbtree_rep.\n                               assert_PROP (p_runc = nullval) by entailer!.\n                               \n(* DECLARE _get_color2\n  WITH t: tree,\n       p: val,\n       p_par: val,\n       b: bool *)\n  (* (b = false <-> p = nullval)  *)                            \n                               \n                               forward_call( (* get_color2(p_gpar->left) *)\n                                 tree_runc, p_runc, p_gpar, false\n                               ). \n                               { entailer!. } (* 满足前条件 *)\n                               { tauto. }\n                               forward_if. (* if (get_color2(p_gpar->left) == RED) *)\n                               { contradiction. }\n                               forward. (* p_gpar->color = RED; *)\n                               forward. (* cal p_par->right *)\n                               forward_if_wrp. (* if (p == p_par->right) *)\n                          **** (* p = p_par->right => p = p_rsib => contradiction *)\n                                    destruct tree_rsib as [|tree_rsib_l node_rsib tree_rsib_r] eqn:ETree_rsib.\n                                    { expand rbtree_rep.\n                                      assert_PROP False by entailer!.\n                                      contradiction. }\n                                    { expand rbtree_rep.\n                                        Intros p_runc_l p_runc_r.\n                                        assert_PROP False. \n                                        { focus_SEP 3. (* 调换位置 *)\n                                          sep_apply data_at_conflict; auto.\n                                          entailer!. }\n                                        contradiction. }\n                         **** (* \"p = p_par->right\" *)\n                                    forward. (* p_par->color = BLACK; *)\n                                    destruct part_gpar eqn:Egpart_par. (* 讨论gpar是否有父亲 目的是确定根节点是不是gpar *)\n                                    +++++ (* part_gpar = [] *) (* gpar 是根节点 *)\n                                          expand partial_treebox_rep.\n                                          assert_PROP (p_ggpar = nullval) by entailer!.\n                                          assert_PROP (b_gpar = root) by entailer!.\n                                          (* call: right_rotate_wrap(p_gpar, root) *)\n                                          forward_call(\n                                            p_par_med, p_gpar, p_ggpar, p_rsib,\n                                            p_med, p_runc, p_gpar, nullval, \n                                            BlackNode node_par, RedNode node_gpar,\n                                            tree_med, tree_runc, tree_rsib,\n                                            root, false,\n                                            false, nullval, nullval, node_par, (* 此行无用 *)\n                                            true, E (* 此行无用 *)\n                                          ).\n                                          { entailer!. (* 满足前条件 *)\n                                            expand partial_tree_rep.\n                                            expand rbtree_rep.\n                                            Exists p_lch p_rch.\n                                            entailer!. }\n                                          { repeat split; try tauto; (* 满足前条件 *)\n                                            subst; auto. }\n                                          forward.\n                                          remember (T lch node_med rch) as tree_med.\n                                          Exists (T tree_med (BlackNode node_par) \n                                                   (T tree_rsib (RedNode node_gpar) E))\n                                                 (@nil half_tree)\n                                                 root nullval.\n                                          rewrite <- H3.\n                                          expand balance'.\n                                          rewrite Ecolor_par.\n                                          unfold r_rotate.\n                                          expand rbtree_rep.\n                                          expand partial_treebox_rep.\n                                          entailer!.\n                                          expand treebox_rep.\n                                          Exists p_par_med.\n                                          entailer!.\n                                          remember (T lch node_med rch) as tree_med.\n                                          expand rbtree_rep.\n                                          Exists p_med p_gpar p_rsib nullval.\n                                          entailer!.\n                                        +++++ (* part_gpar = h1 :: l *) (* gpar 不是根节点 *)\n                                          destruct h1 as [[LR node_ggpar] Tree_ggpl_Or_ggpr] eqn:Ehalf_ggpar.\n                                          assert_PROP (p_ggpar <> nullval). {\n                                            destruct LR; expand partial_treebox_rep; Intros a b c; entailer!. }\n                                          destruct LR; expand partial_treebox_rep;\n                                          Intros p_gggpar p_ggpl_or_r b_ggpar;\n                                          assert_PROP(is_pointer_or_null p_ggpar) by entailer!;\n                                          assert_PROP(is_pointer_or_null p_ggpl_or_r) by entailer!.\n                                          ----\n                                            rename Tree_ggpl_Or_ggpr into tree_ggpl.\n                                            rename p_ggpl_or_r into p_ggpl.\n                                            rewrite partial_treebox_rep''.\n                                            destruct (rev l) eqn:El.\n                                            (* El : rev l = [] *)\n                                            { assert (l = [])by (apply rev_nil_elim in El; auto).\n                                              assert_PROP (p_gggpar = nullval /\\ root = b_ggpar). \n                                              { expand partial_treebox_rep_topdown. entailer!. }\n                                              expand partial_treebox_rep_topdown.\n                                              pose proof classic (p_ggpl <> p_gpar).\n                                              destruct H25.\n                                              destruct H26. \n                                              2:{ assert(p_ggpl = p_gpar) by tauto.\n                                                  destruct tree_ggpl; simpl.\n                                                  { assert_PROP (p_ggpl = nullval) by entailer!.\n                                                    subst. congruence. }\n                                                  Intros a b. subst.\n                                                  assert_PROP False;[|contradiction].\n                                                  focus_SEP 1.\n                                                  sep_apply data_at_conflict;auto.\n                                                  entailer!. }\n                                              (* p_ggpl <> p_gpar *)\n                                              destruct tree_ggpl as[|? ? ?] eqn:Tree.\n                                              -----\n                                                expand rbtree_rep.\n                                                forward_call(\n                                                     p_par_med, p_gpar, p_ggpar, p_rsib,\n                                                     p_med, p_runc, p_ggpar, nullval, \n                                                     BlackNode node_par, RedNode node_gpar,\n                                                     tree_med, tree_runc, tree_rsib,\n                                                     root, true,\n                                                     false, p_gggpar, p_ggpl, node_ggpar,\n                                                     true, E).\n                                                { entailer!. expand rbtree_rep.\n                                                  Exists p_lch p_rch; entailer!.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!. }\n                                                { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                forward.\n                                                remember (T lch node_med rch) as tree_med.\n                                                rewrite <- H3.\n                                                Exists (T tree_med (BlackNode node_par) \n                                                   (T tree_rsib (RedNode node_gpar) E))\n                                                       [(L, node_ggpar, E)]\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                expand balance'.\n                                                rewrite Ecolor_par.\n                                                unfold r_rotate.\n                                                expand rbtree_rep.\n                                                expand partial_treebox_rep.\n                                                Exists nullval nullval b_ggpar.\n                                                expand treebox_rep.\n                                                Exists p_par_med.\n                                                unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                entailer.\n                                                remember (T lch node_med rch) as tree_med.\n                                                expand rbtree_rep.\n                                                Exists p_med p_gpar p_rsib nullval.\n                                                entailer!.\n                                              -----\n                                                rewrite <- Tree.\n                                                forward_call(\n                                                     p_par_med, p_gpar, p_ggpar, p_rsib,\n                                                     p_med, p_runc, p_ggpar, nullval, \n                                                     BlackNode node_par, RedNode node_gpar,\n                                                     tree_med, tree_runc, tree_rsib,\n                                                     root, true,\n                                                     false, p_gggpar, p_ggpl, node_ggpar,\n                                                     false, tree_ggpl).\n                                                { entailer!. \n                                                  remember ((T t3 n0 t4)) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  Exists p_lch p_rch; entailer!.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!. }\n                                                { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                forward.\n                                                remember (T lch node_med rch) as tree_med.\n                                                remember (T t3 n0 t4) as tree_ggpl.\n                                                rewrite <- H3.\n                                                Exists (T tree_med (BlackNode node_par) \n                                                   (T tree_rsib (RedNode node_gpar) E))\n                                                       [(L, node_ggpar, tree_ggpl)]\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                expand balance'.\n                                                rewrite Ecolor_par.\n                                                unfold r_rotate.\n                                                expand rbtree_rep.\n                                                expand partial_treebox_rep.\n                                                Exists nullval p_ggpl b_ggpar.\n                                                expand treebox_rep.\n                                                Exists p_par_med.\n                                                unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                entailer!.\n                                                remember (T lch node_med rch) as tree_med.\n                                                remember (T t3 n0 t4) as tree_ggpl.\n                                                expand rbtree_rep.\n                                                Exists p_med p_gpar p_rsib nullval.\n                                                entailer!.\n                                              }  \n                                          (* El : rev l = h2 :: l0 *)\n                                            { pose proof classic (p_ggpl <> p_gpar).\n                                              destruct H24. \n                                              2:{ assert(p_ggpl = p_gpar) by tauto.\n                                                  destruct tree_ggpl; simpl.\n                                                  { assert_PROP (p_ggpl = nullval) by entailer!.\n                                                    subst. congruence. }\n                                                  Intros a b. subst.\n                                                  assert_PROP False;[|contradiction].\n                                                  focus_SEP 1.\n                                                  sep_apply data_at_conflict;auto.\n                                                  entailer!. }\n                                              destruct h2 as [[LR_ans node_ans] tree_ans_another_child].\n                                              expand partial_treebox_rep_topdown.\n                                              destruct LR_ans. \n                                              -----\n                                                Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpl as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpl = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_par_med, p_gpar, p_ggpar, p_rsib,\n                                                       p_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_par, RedNode node_gpar,\n                                                       tree_med, tree_runc, tree_rsib,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  Exists (T tree_med (BlackNode node_par) \n                                                   (T tree_rsib (RedNode node_gpar) E))\n                                                       ((L, node_ggpar, E) :: l)\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold r_rotate.\n                                                  expand rbtree_rep.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  expand rbtree_rep.\n                                                  Exists p_med p_gpar p_rsib nullval.\n                                                  entailer!.\n                                                ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_par_med, p_gpar, p_ggpar, p_rsib,\n                                                       p_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_par, RedNode node_gpar,\n                                                       tree_med, tree_runc, tree_rsib,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       false, tree_ggpl).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  remember (T t3 n0 t4) as tree_ggpl.\n                                                  Exists (T tree_med (BlackNode node_par) \n                                                   (T tree_rsib (RedNode node_gpar) E))\n                                                       ((L, node_ggpar, tree_ggpl) :: l)\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold r_rotate.\n                                                  expand rbtree_rep.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpl b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  remember (T t3 n0 t4) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  Exists p_med p_gpar p_rsib nullval.\n                                                  entailer!.\n                                              -----\n                                                Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpl as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpl = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_par_med, p_gpar, p_ggpar, p_rsib,\n                                                       p_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_par, RedNode node_gpar,\n                                                       tree_med, tree_runc, tree_rsib,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  Exists (T tree_med (BlackNode node_par) \n                                                   (T tree_rsib (RedNode node_gpar) E))\n                                                       ((L, node_ggpar, E) :: l)\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold r_rotate.\n                                                  expand rbtree_rep.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  expand rbtree_rep.\n                                                  Exists p_med p_gpar p_rsib nullval.\n                                                  entailer!.\n                                                ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_par_med, p_gpar, p_ggpar, p_rsib,\n                                                       p_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_par, RedNode node_gpar,\n                                                       tree_med, tree_runc, tree_rsib,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       false, tree_ggpl).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  remember (T t3 n0 t4) as tree_ggpl.\n                                                  Exists (T tree_med (BlackNode node_par) \n                                                   (T tree_rsib (RedNode node_gpar) E))\n                                                       ((L, node_ggpar, tree_ggpl) :: l)\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold r_rotate.\n                                                  expand rbtree_rep.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpl b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  remember (T t3 n0 t4) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  Exists p_med p_gpar p_rsib nullval.\n                                                  entailer!.\n                                            }\n                                          ----\n                                            rename Tree_ggpl_Or_ggpr into tree_ggpr.\n                                            rename p_ggpl_or_r into p_ggpr.\n                                            rewrite partial_treebox_rep''.\n                                            destruct (rev l) eqn:El.\n                                            (* El : rev l = [] *)\n                                            { assert (l = [])by (apply rev_nil_elim in El; auto).\n                                              assert_PROP (p_gggpar = nullval /\\ root = b_ggpar). \n                                              { expand partial_treebox_rep_topdown. entailer!. }\n                                              expand partial_treebox_rep_topdown.\n                                              pose proof classic (p_ggpr <> p_gpar).\n                                              destruct H25.\n                                              destruct H26. \n                                              2:{ assert(p_ggpr = p_gpar) by tauto.\n                                                  destruct tree_ggpr; simpl.\n                                                  { assert_PROP (p_ggpr = nullval) by entailer!.\n                                                    subst. congruence. }\n                                                  Intros a b. subst.\n                                                  assert_PROP False;[|contradiction].\n                                                  focus_SEP 1.\n                                                  sep_apply data_at_conflict;auto.\n                                                  entailer!. }\n                                              (* p_ggpr <> p_gpar *)\n                                              destruct tree_ggpr as[|? ? ?] eqn:Tree.\n                                              -----\n                                                expand rbtree_rep.\n                                                forward_call(\n                                                       p_par_med, p_gpar, p_ggpar, p_rsib,\n                                                       p_med, p_runc, p_ggpar, nullval, \n                                                       BlackNode node_par, RedNode node_gpar,\n                                                       tree_med, tree_runc, tree_rsib,\n                                                     root, true,\n                                                     true, p_gggpar, p_ggpr, node_ggpar,\n                                                     true, E).\n                                                { entailer!. expand rbtree_rep.\n                                                  Exists p_lch p_rch; entailer!.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!. }\n                                                { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                forward.\n                                                remember (T lch node_med rch) as tree_med.\n                                                rewrite <- H3.\n                                                Exists (T tree_med (BlackNode node_par) \n                                                   (T tree_rsib (RedNode node_gpar) E))\n                                                       [(R, node_ggpar, E)]\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                expand balance'.\n                                                rewrite Ecolor_par.\n                                                unfold r_rotate.\n                                                expand rbtree_rep.\n                                                expand partial_treebox_rep.\n                                                Exists nullval nullval b_ggpar.\n                                                expand treebox_rep.\n                                                Exists p_par_med.\n                                                unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                entailer.\n                                                remember (T lch node_med rch) as tree_med.\n                                                expand rbtree_rep.\n                                                Exists p_med p_gpar p_rsib nullval.\n                                                entailer!.\n                                              -----\n                                                rewrite <- Tree.\n                                                forward_call(\n                                                     p_par_med, p_gpar, p_ggpar, p_rsib,\n                                                     p_med, p_runc, p_ggpar, nullval, \n                                                     BlackNode node_par, RedNode node_gpar,\n                                                     tree_med, tree_runc, tree_rsib,\n                                                     root, true,\n                                                     true, p_gggpar, p_ggpr, node_ggpar,\n                                                     false, tree_ggpr).\n                                                { entailer!. \n                                                  remember ((T t3 n0 t4)) as tree_ggpr.\n                                                  expand rbtree_rep.\n                                                  Exists p_lch p_rch; entailer!.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!. }\n                                                { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                forward.\n                                                remember (T lch node_med rch) as tree_med.\n                                                remember (T t3 n0 t4) as tree_ggpr.\n                                                rewrite <- H3.\n                                                Exists (T tree_med (BlackNode node_par) \n                                                   (T tree_rsib (RedNode node_gpar) E))\n                                                       [(R, node_ggpar, tree_ggpr)]\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                expand balance'.\n                                                rewrite Ecolor_par.\n                                                unfold r_rotate.\n                                                expand rbtree_rep.\n                                                expand partial_treebox_rep.\n                                                Exists nullval p_ggpr b_ggpar.\n                                                expand treebox_rep.\n                                                Exists p_par_med.\n                                                unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                entailer!.\n                                                remember (T lch node_med rch) as tree_med.\n                                                remember (T t3 n0 t4) as tree_ggpr.\n                                                expand rbtree_rep.\n                                                Exists p_med p_gpar p_rsib nullval.\n                                                entailer!.\n                                              }  \n                                          (* El : rev l = h2 :: l0 *)\n                                            { pose proof classic (p_ggpr <> p_gpar).\n                                              destruct H24. \n                                              2:{ assert(p_ggpr = p_gpar) by tauto.\n                                                  destruct tree_ggpr; simpl.\n                                                  { assert_PROP (p_ggpr = nullval) by entailer!.\n                                                    subst. congruence. }\n                                                  Intros a b. subst.\n                                                  assert_PROP False;[|contradiction].\n                                                  focus_SEP 1.\n                                                  sep_apply data_at_conflict;auto.\n                                                  entailer!. }\n                                              destruct h2 as [[LR_ans node_ans] tree_ans_another_child].\n                                              expand partial_treebox_rep_topdown.\n                                              destruct LR_ans. \n                                              -----\n                                                Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpr as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpr = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_par_med, p_gpar, p_ggpar, p_rsib,\n                                                       p_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_par, RedNode node_gpar,\n                                                       tree_med, tree_runc, tree_rsib,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpr, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  Exists (T tree_med (BlackNode node_par) \n                                                   (T tree_rsib (RedNode node_gpar) E))\n                                                       ((R, node_ggpar, E) :: l)\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold r_rotate.\n                                                  expand rbtree_rep.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  expand rbtree_rep.\n                                                  Exists p_med p_gpar p_rsib nullval.\n                                                  entailer!.\n                                                ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_par_med, p_gpar, p_ggpar, p_rsib,\n                                                       p_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_par, RedNode node_gpar,\n                                                       tree_med, tree_runc, tree_rsib,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpr, node_ggpar,\n                                                       false, tree_ggpr).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  remember (T t3 n0 t4) as tree_ggpr.\n                                                  Exists (T tree_med (BlackNode node_par) \n                                                   (T tree_rsib (RedNode node_gpar) E))\n                                                       ((R, node_ggpar, tree_ggpr) :: l)\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold r_rotate.\n                                                  expand rbtree_rep.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpr b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  remember (T t3 n0 t4) as tree_ggpr.\n                                                  expand rbtree_rep.\n                                                  Exists p_med p_gpar p_rsib nullval.\n                                                  entailer!.\n                                              -----\n                                                Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpr as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpr = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_par_med, p_gpar, p_ggpar, p_rsib,\n                                                       p_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_par, RedNode node_gpar,\n                                                       tree_med, tree_runc, tree_rsib,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpr, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  Exists (T tree_med (BlackNode node_par) \n                                                   (T tree_rsib (RedNode node_gpar) E))\n                                                       ((R, node_ggpar, E) :: l)\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold r_rotate.\n                                                  expand rbtree_rep.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  expand rbtree_rep.\n                                                  Exists p_med p_gpar p_rsib nullval.\n                                                  entailer!.\n                                                ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_par_med, p_gpar, p_ggpar, p_rsib,\n                                                       p_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_par, RedNode node_gpar,\n                                                       tree_med, tree_runc, tree_rsib,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpr, node_ggpar,\n                                                       false, tree_ggpr).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  remember (T t3 n0 t4) as tree_ggpr.\n                                                  Exists (T tree_med (BlackNode node_par) \n                                                   (T tree_rsib (RedNode node_gpar) E))\n                                                       ((R, node_ggpar, tree_ggpr) :: l)\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par.\n                                                  unfold r_rotate.\n                                                  expand rbtree_rep.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpr b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  remember (T lch node_med rch) as tree_med.\n                                                  remember (T t3 n0 t4) as tree_ggpr.\n                                                  expand rbtree_rep.\n                                                  Exists p_med p_gpar p_rsib nullval.\n                                                  entailer!.\n                                              }\n              ++++ (* \"tree_runc = T tree_runc_l node_runc tree_runc_r\" *)\n                               assert_PROP (p_runc <> nullval).\n                               { expand rbtree_rep; Intros a b; entailer!. }\n                               destruct (color_of_node node_runc) eqn: color_runc.\n                               ---- (* \"runc is RED\" *)\n(* DECLARE _get_color2\n  WITH t: tree,\n       p: val,\n       p_par: val,\n       b: bool *)\n  (* (b = false <-> p = nullval)  *) \n                                 forward_call( (* get_color2(p_gpar->left) *)\n                                   tree_runc, p_runc, p_gpar, true\n                                 ). \n                                 { entailer!. } (* 满足前条件 *)\n                                 { tauto. }\n                                 rewrite ETree_runc, color_runc.\n                                 unfold Col2Z at 1. (*  , RED_COLOR, BLACK_COLOR. *)\n                                 forward_if. (* if (get_color2(p_gpar->left) == RED) *)\n                                 2: { assert_PROP False by entailer!; tauto. }\n                                 forward.\n                                 forward.\n                                 expand rbtree_rep.\n                                 Intros p_runc_l p_runc_r.\n                                 forward.\n                                 forward.\n                                 forward.\n                                 Exists (T (T tree_med (BlackNode node_par) tree_rsib)\n                                        (RedNode node_gpar) (makeBlack tree_runc))\n                                   part_gpar\n                                   b_gpar\n                                   p_ggpar\n                                   p_gpar.\n                                 rewrite <- H3.\n                                 expand balance'.\n                                 rewrite Ecolor_par.\n                                 expand rbtree_rep.\n                                 Exists p_par_med p_runc p_med p_rsib.\n                                 entailer!.\n                                 2:{ unfold makeBlack. expand rbtree_rep. \n                                     Exists p_lch p_rch p_runc_l p_runc_r.\n                                     entailer!. } \n                                 simpl (color_of_node node_runc).\n                                 destruct node_runc as [a b c].\n                                 assert(a = Red).\n                                 { auto. }\n                                 subst. reflexivity.\n                               ---- (* \"lunc is BLACK\" *)\n                                 forward_call( (* get_color2(p_gpar->left) *)\n                                   tree_runc, p_runc, p_gpar, true\n                                 ). \n                                 { entailer!. } (* 满足前条件 *)\n                                 { tauto. }\n                                 rewrite ETree_runc, color_runc.\n                                 unfold Col2Z at 1, RED_COLOR, BLACK_COLOR.\n                                 forward_if. (* if (get_color2(p_gpar->left) == RED) *)\n                                 1: { assert_PROP False by entailer!; tauto. }\n                                 forward.\n                                 forward.\n                                 forward_if_wrp. (* if (p == p_par->right) *)\n                                 **** (* p = p_par->right => p = p_risb => contradiction *)\n                                   destruct tree_rsib as [|tree_rsib_l node_rsib tree_rsib_r] eqn:ETree_lsib.\n                                   { expand rbtree_rep.\n                                     assert_PROP False by entailer!.\n                                     contradiction. }\n                                   { expand rbtree_rep.\n                                     Intros p_runc_l p_runc_r p_rsib_l p_rsib_r.\n                                     assert_PROP False. \n                                     { focus_SEP 8. (* 调换位置 *)\n                                       sep_apply data_at_conflict; auto.\n                                       entailer!. }\n                                     contradiction. }\n                                 **** (* \"p = p_par->right\" *)\n                                   forward. (* p_par->color = BLACK; *)\n                                   destruct part_gpar eqn:Egpart_par. (* 讨论gpar是否有父亲 目的是确定根节点是不是gpar *)\n                                   +++++ (* part_gpar = [] *) (* gpar 是根节点 *)\n                                     expand partial_treebox_rep.\n                                     assert_PROP (p_ggpar = nullval) by entailer!.\n                                     assert_PROP (b_gpar = root) by entailer!.\n                                     (* call: right_rotate_wrap(p_gpar, root) *)\n                                     forward_call(\n                                     p_par_med, p_gpar, p_ggpar, p_rsib,\n                                     p_med, p_runc, p_gpar, nullval, \n                                     BlackNode node_par, RedNode node_gpar,\n                                     tree_med, tree_runc, tree_rsib,\n                                     root, false,\n                                     false, nullval, nullval, node_par, (* 此行无用 *)\n                                     true, E (* 此行无用 *)\n                                     ).\n                                     { entailer!. (* 满足前条件 *)\n                                       expand partial_tree_rep.\n                                       expand rbtree_rep.\n                                       Exists p_lch p_rch.\n                                       entailer!. }\n                                     { repeat split; try tauto; (* 满足前条件 *)\n                                       subst; auto. }\n                                     forward.\n                                     remember (T lch node_med rch) as tree_med.\n                                     Exists \n                                     (T tree_med (BlackNode node_par)\n                                      (T tree_rsib (RedNode node_gpar)\n                                      (T tree_runc_l node_runc tree_runc_r)))\n                                               (@nil half_tree)\n                                               root nullval.\n                                     rewrite <- H3.\n                                     expand balance'.\n                                     rewrite Ecolor_par.\n                                     destruct node_runc as[c_runc k_runc v_runc].\n                                     assert(c_runc = Black)by auto.\n                                     subst c_runc.\n                                     unfold r_rotate.\n                                     remember ({| color_of_node := Black; key_of_node := k_runc; value_of_node := v_runc |}) as node_runc.\n                                     expand partial_treebox_rep.\n                                     entailer!.\n                                     remember ({| color_of_node := Black; key_of_node := k_runc; value_of_node := v_runc |}) as node_runc.\n                                     expand treebox_rep.\n                                     Exists p_par_med.\n                                     entailer!.\n                                     remember ({| color_of_node := Black; key_of_node := k_runc; value_of_node := v_runc |}) as node_runc.\n                                     remember (T lch node_med rch) as tree_med.\n                                     expand rbtree_rep.\n                                     Intros p_runc_l p_runc_r.\n                                     Exists p_med p_gpar p_rsib p_runc p_runc_l p_runc_r.\n                                     entailer!.\n                                   +++++ (* part_gpar = h1 :: l *) (* gpar 不是根节点 *)\n                                     destruct h1 as [[LR node_ggpar] Tree_ggpl_Or_ggpr] eqn:Ehalf_ggpar.\n                                     assert_PROP (p_ggpar <> nullval).\n                                     { destruct LR; expand partial_treebox_rep; Intros a b c; entailer!. }\n                                     destruct LR; expand partial_treebox_rep;\n                                       Intros p_gggpar p_ggpl_or_r b_ggpar;\n                                       assert_PROP(is_pointer_or_null p_ggpar) by entailer!;\n                                       assert_PROP(is_pointer_or_null p_ggpl_or_r) by entailer!.\n                                     -----\n                                       rename Tree_ggpl_Or_ggpr into tree_ggpl.\n                                       rename p_ggpl_or_r into p_ggpl.\n                                       rewrite partial_treebox_rep''.\n                                       destruct (rev l) eqn:El.\n                                       (* El : rev l = [] *)\n                                       { assert (l = [])by (apply rev_nil_elim in El; auto).\n                                         assert_PROP (p_gggpar = nullval /\\ root = b_ggpar). \n                                         { expand partial_treebox_rep_topdown. entailer!. }\n                                       expand partial_treebox_rep_topdown.\n                                       pose proof classic (p_ggpl <> p_gpar).\n                                       destruct H25.\n                                       destruct H26. \n                                       2:{ assert(p_ggpl = p_gpar) by tauto.\n                                           destruct tree_ggpl; simpl.\n                                           { assert_PROP (p_ggpl = nullval) by entailer!.\n                                             subst. congruence. }\n                                           Intros a b c d. subst.\n                                           assert_PROP False;[|contradiction].\n                                           focus_SEP 3.\n                                           sep_apply data_at_conflict;auto.\n                                           entailer!. }\n                                       (* p_ggpl <> p_gpar *)\n                                       destruct tree_ggpl as[|? ? ?] eqn:Tree.\n                                       *****\n                                         rewrite <- ETree_runc.\n                                         expand rbtree_rep.\n                                         forward_call(\n                                           p_par_med, p_gpar, p_ggpar, p_rsib,\n                                           p_med, p_runc, p_ggpar, nullval, \n                                           BlackNode node_par, RedNode node_gpar,\n                                           tree_med, tree_runc, tree_rsib,\n                                           root, true,\n                                           false, p_gggpar, p_ggpl, node_ggpar,\n                                           true, E).\n                                         { entailer!. expand rbtree_rep.\n                                           Exists p_lch p_rch; entailer!.\n                                           unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                           entailer!. }\n                                         { repeat split; try tauto; subst; auto. intros. congruence. }\n                                         forward.\n                                         remember (T lch node_med rch) as tree_med.\n                                         remember (T tree_runc_l node_runc tree_runc_r) as tree_runc.\n                                         rewrite <- H3.\n                                         Exists (T tree_med (BlackNode node_par)\n                                      (T tree_rsib (RedNode node_gpar)\n                                      (T tree_runc_l node_runc tree_runc_r)))\n                                                  [(L, node_ggpar, E)]\n                                                  (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                  p_ggpar.\n                                         expand balance'.\n                                         rewrite Ecolor_par.\n                                         rewrite Heqtree_runc.\n                                         destruct node_runc as[c_runc k_runc v_runc].\n                                         assert(c_runc = Black)by auto.\n                                         subst c_runc.\n                                         unfold r_rotate.\n                                         expand partial_treebox_rep.\n                                         Exists nullval nullval b_ggpar.\n                                         entailer!.\n                                         expand treebox_rep.\n                                         Exists p_par_med.\n                                         unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                         entailer.\n                                         remember (T lch node_med rch) as tree_med.\n                                         expand rbtree_rep. Intros a b.\n                                         Exists p_med p_gpar p_rsib p_runc a b.\n                                         entailer!.\n                                       *****\n                                         rewrite <- Tree.\n                                         rewrite <- ETree_runc.\n                                         forward_call(\n                                           p_par_med, p_gpar, p_ggpar, p_rsib,\n                                           p_med, p_runc, p_ggpar, nullval, \n                                           BlackNode node_par, RedNode node_gpar,\n                                           tree_med, tree_runc, tree_rsib,\n                                           root, true,\n                                           false, p_gggpar, p_ggpl, node_ggpar,\n                                           false, tree_ggpl).\n                                         { entailer!. \n                                           remember ((T t3 n0 t4)) as tree_ggpl.\n                                           expand rbtree_rep.\n                                           Exists p_lch p_rch; entailer!.\n                                           unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                           entailer!. }\n                                         { repeat split; try tauto; subst; auto. intros. congruence. }\n                                         forward.\n                                         remember (T lch node_med rch) as tree_med.\n                                         remember (T t3 n0 t4) as tree_ggpl.\n                                         remember (T tree_runc_l node_runc tree_runc_r) as tree_runc.\n                                         rewrite <- H3.\n                                         Exists (T tree_med (BlackNode node_par)\n                                      (T tree_rsib (RedNode node_gpar)\n                                      (T tree_runc_l node_runc tree_runc_r)))\n                                                [(L, node_ggpar, tree_ggpl)]\n                                                (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                p_ggpar.\n                                         expand balance'.\n                                         rewrite Ecolor_par. rewrite Heqtree_runc.\n                                         destruct node_runc as[c_runc k_runc v_runc].\n                                         assert(c_runc = Black)by auto.\n                                         subst c_runc.\n                                         unfold r_rotate.\n                                         expand partial_treebox_rep.\n                                         Exists nullval p_ggpl b_ggpar. entailer!.\n                                         expand treebox_rep.\n                                         Exists p_par_med.\n                                         unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                         entailer!.\n                                         remember (T lch node_med rch) as tree_med.\n                                         remember (T t3 n0 t4) as tree_ggpl.\n                                         remember ({| color_of_node := Black; key_of_node := k_runc; value_of_node := v_runc |}) as node_runc.\n                                         remember (T tree_runc_l node_runc tree_runc_r) as tree_runc.\n                                         expand rbtree_rep.\n                                         Exists p_med p_gpar p_rsib p_runc.\n                                         entailer!.\n                                       }\n                                       (* El : rev l = h2 :: l0 *)\n                                       { pose proof classic (p_ggpl <> p_gpar).\n                                         destruct H24. \n                                         2:{ assert(p_ggpl = p_gpar) by tauto.\n                                             destruct tree_ggpl; expand rbtree_rep.\n                                             { assert_PROP (p_ggpl = nullval) by entailer!.\n                                               subst. congruence. }\n                                             Intros a b c d. subst.\n                                             assert_PROP False;[|contradiction].\n                                             focus_SEP 3.\n                                             sep_apply data_at_conflict;auto.\n                                             entailer!. }\n                                         destruct h2 as [[LR_ans node_ans] tree_ans_another_child].\n                                         expand partial_treebox_rep_topdown.\n                                         destruct LR_ans. \n                                         *****\n                                                Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpl as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpl = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_par_med, p_gpar, p_ggpar, p_rsib,\n                                                       p_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_par, RedNode node_gpar,\n                                                       tree_med, tree_runc, tree_rsib,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  try remember (T lch node_med rch) as tree_med.\n                                                  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc.\n                                                  Exists (T tree_med (BlackNode node_par)\n                                      (T tree_rsib (RedNode node_gpar)\n                                      (T tree_runc_l node_runc tree_runc_r)))\n                                                       ((L, node_ggpar, E) :: l)\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_runc.\n                                                  destruct node_runc as[c_runc k_runc v_runc].\n                                                  assert(c_runc = Black)by auto.\n                                                  subst c_runc.\n                                                  try remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_runc; value_of_node := v_runc |}) \n                                                      as node_runc +\n                                                    remember (T tree_runc_l node_runc tree_runc_r) as tree_runc.\n                                                  unfold r_rotate.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  try remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_runc; value_of_node := v_runc |}) \n                                                      as node_runc +\n                                                    remember (T tree_runc_l node_runc tree_runc_r) as tree_runc.\n                                                  expand rbtree_rep.\n                                                  Intros a b.\n                                                  Exists p_med p_gpar p_rsib p_runc a b.\n                                                  entailer!.\n                                              ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_par_med, p_gpar, p_ggpar, p_rsib,\n                                                       p_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_par, RedNode node_gpar,\n                                                       tree_med, tree_runc, tree_rsib,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       false, tree_ggpl).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  repeat remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_runc; value_of_node := v_runc |}) \n                                                      as node_runc +\n                                                    remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n                                                    remember (T t3 n0 t4) as tree_ggpl.\n                                                  Exists (T tree_med (BlackNode node_par)\n                                      (T tree_rsib (RedNode node_gpar)\n                                      (T tree_runc_l node_runc tree_runc_r)))\n                                                       ((L, node_ggpar, tree_ggpl) :: l)\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_runc.\n                                                  destruct node_runc as[c_runc k_runc v_runc].\n                                                  assert(c_runc = Black)by auto.\n                                                  subst c_runc.\n                                                  repeat remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_runc; value_of_node := v_runc |}) \n                                                      as node_runc +\n                                                    remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n                                                    remember (T t3 n0 t4) as tree_ggpl.\n                                                  unfold r_rotate.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpl b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  repeat remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_runc; value_of_node := v_runc |}) \n                                                      as node_runc +\n                                                    remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n                                                    remember (T t3 n0 t4) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  Exists p_med p_gpar p_rsib p_runc.\n                                                  entailer!.\n                                             *****\n                                               Intros p_ans_another_child p_ans.\n                                               destruct tree_ggpl as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpl = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_par_med, p_gpar, p_ggpar, p_rsib,\n                                                       p_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_par, RedNode node_gpar,\n                                                       tree_med, tree_runc, tree_rsib,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  try remember (T lch node_med rch) as tree_med.\n                                                  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc.\n                                                  Exists (T tree_med (BlackNode node_par)\n                                      (T tree_rsib (RedNode node_gpar)\n                                      (T tree_runc_l node_runc tree_runc_r)))\n                                                       ((L, node_ggpar, E) :: l)\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_runc.\n                                                  destruct node_runc as[c_runc k_runc v_runc].\n                                                  assert(c_runc = Black)by auto.\n                                                  subst c_runc.\n                                                  try remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_runc; value_of_node := v_runc |}) \n                                                      as node_runc +\n                                                    remember (T tree_runc_l node_runc tree_runc_r) as tree_runc.\n                                                  unfold r_rotate.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  try remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_runc; value_of_node := v_runc |}) \n                                                      as node_runc +\n                                                    remember (T tree_runc_l node_runc tree_runc_r) as tree_runc.\n                                                  expand rbtree_rep.\n                                                  Intros a b.\n                                                  Exists p_med p_gpar p_rsib p_runc a b.\n                                                  entailer!.\n                                              ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_par_med, p_gpar, p_ggpar, p_rsib,\n                                                       p_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_par, RedNode node_gpar,\n                                                       tree_med, tree_runc, tree_rsib,\n                                                       root, true,\n                                                       false, p_gggpar, p_ggpl, node_ggpar,\n                                                       false, tree_ggpl).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  repeat remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_runc; value_of_node := v_runc |}) \n                                                      as node_runc +\n                                                    remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n                                                    remember (T t3 n0 t4) as tree_ggpl.\n                                                  Exists (T tree_med (BlackNode node_par)\n                                      (T tree_rsib (RedNode node_gpar)\n                                      (T tree_runc_l node_runc tree_runc_r))) \n                                                       ((L, node_ggpar, tree_ggpl) :: l)\n                                                       (field_address t_struct_tree [StructField _right] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_runc.\n                                                  destruct node_runc as[c_runc k_runc v_runc].\n                                                  assert(c_runc = Black)by auto.\n                                                  subst c_runc.\n                                                  repeat remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_runc; value_of_node := v_runc |}) \n                                                      as node_runc +\n                                                    remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n                                                    remember (T t3 n0 t4) as tree_ggpl.\n                                                  unfold r_rotate.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpl b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  repeat remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_runc; value_of_node := v_runc |}) \n                                                      as node_runc +\n                                                    remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n                                                    remember (T t3 n0 t4) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  Exists p_med p_gpar p_rsib p_runc.\n                                                  entailer!.\n                                                  }\n                                     -----\n                                       rename Tree_ggpl_Or_ggpr into tree_ggpl.\n                                       rename p_ggpl_or_r into p_ggpl.\n                                       rewrite partial_treebox_rep''.\n                                       destruct (rev l) eqn:El.\n                                       (* El : rev l = [] *)\n                                       { assert (l = [])by (apply rev_nil_elim in El; auto).\n                                         assert_PROP (p_gggpar = nullval /\\ root = b_ggpar). \n                                         { expand partial_treebox_rep_topdown. entailer!. }\n                                       expand partial_treebox_rep_topdown.\n                                       pose proof classic (p_ggpl <> p_gpar).\n                                       destruct H25.\n                                       destruct H26. \n                                       2:{ assert(p_ggpl = p_gpar) by tauto.\n                                           destruct tree_ggpl; simpl.\n                                           { assert_PROP (p_ggpl = nullval) by entailer!.\n                                             subst. congruence. }\n                                           Intros a b c d. subst.\n                                           assert_PROP False;[|contradiction].\n                                           focus_SEP 3.\n                                           sep_apply data_at_conflict;auto.\n                                           entailer!. }\n                                       (* p_ggpl <> p_gpar *)\n                                       destruct tree_ggpl as[|? ? ?] eqn:Tree.\n                                       *****\n                                         rewrite <- ETree_runc.\n                                         expand rbtree_rep.\n                                         forward_call(\n                                           p_par_med, p_gpar, p_ggpar, p_rsib,\n                                           p_med, p_runc, p_ggpar, nullval, \n                                           BlackNode node_par, RedNode node_gpar,\n                                           tree_med, tree_runc, tree_rsib,\n                                           root, true,\n                                           true, p_gggpar, p_ggpl, node_ggpar,\n                                           true, E).\n                                         { entailer!. expand rbtree_rep.\n                                           Exists p_lch p_rch; entailer!.\n                                           unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                           entailer!. }\n                                         { repeat split; try tauto; subst; auto. intros. congruence. }\n                                         forward.\n                                         remember (T lch node_med rch) as tree_med.\n                                         remember (T tree_runc_l node_runc tree_runc_r) as tree_runc.\n                                         rewrite <- H3.\n                                         Exists (T tree_med (BlackNode node_par)\n                                      (T tree_rsib (RedNode node_gpar)\n                                      (T tree_runc_l node_runc tree_runc_r))) \n                                                  [(R, node_ggpar, E)]\n                                                  (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                  p_ggpar.\n                                         expand balance'.\n                                         rewrite Ecolor_par.\n                                         rewrite Heqtree_runc.\n                                         destruct node_runc as[c_runc k_runc v_runc].\n                                         assert(c_runc = Black)by auto.\n                                         subst c_runc.\n                                         unfold r_rotate.\n                                         expand partial_treebox_rep.\n                                         Exists nullval nullval b_ggpar.\n                                         entailer!.\n                                         expand treebox_rep.\n                                         Exists p_par_med.\n                                         unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                         entailer.\n                                         remember (T lch node_med rch) as tree_med.\n                                         expand rbtree_rep. Intros a b.\n                                         Exists p_med p_gpar p_rsib p_runc a b.\n                                         entailer!.\n                                       *****\n                                         rewrite <- Tree.\n                                         rewrite <- ETree_runc.\n                                         forward_call(\n                                           p_par_med, p_gpar, p_ggpar, p_rsib,\n                                           p_med, p_runc, p_ggpar, nullval, \n                                           BlackNode node_par, RedNode node_gpar,\n                                           tree_med, tree_runc, tree_rsib,\n                                           root, true,\n                                           true, p_gggpar, p_ggpl, node_ggpar,\n                                           false, tree_ggpl).\n                                         { entailer!. \n                                           remember ((T t3 n0 t4)) as tree_ggpl.\n                                           expand rbtree_rep.\n                                           Exists p_lch p_rch; entailer!.\n                                           unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                           entailer!. }\n                                         { repeat split; try tauto; subst; auto. intros. congruence. }\n                                         forward.\n                                         remember (T lch node_med rch) as tree_med.\n                                         remember (T t3 n0 t4) as tree_ggpl.\n                                         remember (T tree_runc_l node_runc tree_runc_r) as tree_runc.\n                                         rewrite <- H3.\n                                         Exists (T tree_med (BlackNode node_par)\n                                      (T tree_rsib (RedNode node_gpar)\n                                      (T tree_runc_l node_runc tree_runc_r))) \n                                                [(R, node_ggpar, tree_ggpl)]\n                                                (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                p_ggpar.\n                                         expand balance'.\n                                         rewrite Ecolor_par. rewrite Heqtree_runc.\n                                         destruct node_runc as[c_runc k_runc v_runc].\n                                         assert(c_runc = Black)by auto.\n                                         subst c_runc.\n                                         unfold r_rotate.\n                                         expand partial_treebox_rep.\n                                         Exists nullval p_ggpl b_ggpar. entailer!.\n                                         expand treebox_rep.\n                                         Exists p_par_med.\n                                         unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                         entailer!.\n                                         remember (T lch node_med rch) as tree_med.\n                                         remember (T t3 n0 t4) as tree_ggpl.\n                                         remember ({| color_of_node := Black; key_of_node := k_runc; value_of_node := v_runc |}) as node_runc.\n                                         remember (T tree_runc_l node_runc tree_runc_r) as tree_runc.\n                                         expand rbtree_rep.\n                                         Exists p_med p_gpar p_rsib p_runc.\n                                         entailer!.\n                                       }\n                                       (* El : rev l = h2 :: l0 *)\n                                       { pose proof classic (p_ggpl <> p_gpar).\n                                         destruct H24. \n                                         2:{ assert(p_ggpl = p_gpar) by tauto.\n                                             destruct tree_ggpl; expand rbtree_rep.\n                                             { assert_PROP (p_ggpl = nullval) by entailer!.\n                                               subst. congruence. }\n                                             Intros a b c d. subst.\n                                             assert_PROP False;[|contradiction].\n                                             focus_SEP 3.\n                                             sep_apply data_at_conflict;auto.\n                                             entailer!. }\n                                         destruct h2 as [[LR_ans node_ans] tree_ans_another_child].\n                                         expand partial_treebox_rep_topdown.\n                                         destruct LR_ans. \n                                         *****\n                                                Intros p_ans_another_child p_ans.\n                                                destruct tree_ggpl as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpl = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_par_med, p_gpar, p_ggpar, p_rsib,\n                                                       p_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_par, RedNode node_gpar,\n                                                       tree_med, tree_runc, tree_rsib,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpl, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  try remember (T lch node_med rch) as tree_med.\n                                                  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc.\n                                                  Exists (T tree_med (BlackNode node_par)\n                                      (T tree_rsib (RedNode node_gpar)\n                                      (T tree_runc_l node_runc tree_runc_r))) \n                                                       ((R, node_ggpar, E) :: l)\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_runc.\n                                                  destruct node_runc as[c_runc k_runc v_runc].\n                                                  assert(c_runc = Black)by auto.\n                                                  subst c_runc.\n                                                  try remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_runc; value_of_node := v_runc |}) \n                                                      as node_runc +\n                                                    remember (T tree_runc_l node_runc tree_runc_r) as tree_runc.\n                                                  unfold r_rotate.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  try remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_runc; value_of_node := v_runc |}) \n                                                      as node_runc +\n                                                    remember (T tree_runc_l node_runc tree_runc_r) as tree_runc.\n                                                  expand rbtree_rep.\n                                                  Intros a b.\n                                                  Exists p_med p_gpar p_rsib p_runc a b.\n                                                  entailer!.\n                                              ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_par_med, p_gpar, p_ggpar, p_rsib,\n                                                       p_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_par, RedNode node_gpar,\n                                                       tree_med, tree_runc, tree_rsib,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpl, node_ggpar,\n                                                       false, tree_ggpl).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  repeat remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_runc; value_of_node := v_runc |}) \n                                                      as node_runc +\n                                                    remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n                                                    remember (T t3 n0 t4) as tree_ggpl.\n                                                  Exists (T tree_med (BlackNode node_par)\n                                      (T tree_rsib (RedNode node_gpar)\n                                      (T tree_runc_l node_runc tree_runc_r))) \n                                                       ((R, node_ggpar, tree_ggpl) :: l)\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_runc.\n                                                  destruct node_runc as[c_runc k_runc v_runc].\n                                                  assert(c_runc = Black)by auto.\n                                                  subst c_runc.\n                                                  repeat remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_runc; value_of_node := v_runc |}) \n                                                      as node_runc +\n                                                    remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n                                                    remember (T t3 n0 t4) as tree_ggpl.\n                                                  unfold r_rotate.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpl b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  repeat remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_runc; value_of_node := v_runc |}) \n                                                      as node_runc +\n                                                    remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n                                                    remember (T t3 n0 t4) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  Exists p_med p_gpar p_rsib p_runc.\n                                                  entailer!.\n                                             *****\n                                               Intros p_ans_another_child p_ans.\n                                               destruct tree_ggpl as[|] eqn:Tree.\n                                                ------\n                                                  assert_PROP(p_ggpl = nullval).\n                                                  { expand rbtree_rep. entailer!. }\n                                                  forward_call(\n                                                       p_par_med, p_gpar, p_ggpar, p_rsib,\n                                                       p_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_par, RedNode node_gpar,\n                                                       tree_med, tree_runc, tree_rsib,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpl, node_ggpar,\n                                                       true, E).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  try remember (T lch node_med rch) as tree_med.\n                                                  remember (T tree_runc_l node_runc tree_runc_r) as tree_runc.\n                                                  Exists (T tree_med (BlackNode node_par)\n                                      (T tree_rsib (RedNode node_gpar)\n                                      (T tree_runc_l node_runc tree_runc_r))) \n                                                       ((R, node_ggpar, E) :: l)\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_runc.\n                                                  destruct node_runc as[c_runc k_runc v_runc].\n                                                  assert(c_runc = Black)by auto.\n                                                  subst c_runc.\n                                                  try remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_runc; value_of_node := v_runc |}) \n                                                      as node_runc +\n                                                    remember (T tree_runc_l node_runc tree_runc_r) as tree_runc.\n                                                  unfold r_rotate.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar nullval b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  try remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_runc; value_of_node := v_runc |}) \n                                                      as node_runc +\n                                                    remember (T tree_runc_l node_runc tree_runc_r) as tree_runc.\n                                                  expand rbtree_rep.\n                                                  Intros a b.\n                                                  Exists p_med p_gpar p_rsib p_runc a b.\n                                                  entailer!.\n                                              ------\n                                                  rewrite <- Tree.\n                                                  forward_call(\n                                                       p_par_med, p_gpar, p_ggpar, p_rsib,\n                                                       p_med, p_runc, p_ans, nullval, \n                                                       BlackNode node_par, RedNode node_gpar,\n                                                       tree_med, tree_runc, tree_rsib,\n                                                       root, true,\n                                                       true, p_gggpar, p_ggpl, node_ggpar,\n                                                       false, tree_ggpl).\n                                                  { entailer!. expand rbtree_rep.\n                                                    Exists p_lch p_rch; entailer!.\n                                                    unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                    entailer!. }\n                                                  { repeat split; try tauto; subst; auto. intros. congruence. }\n                                                  Intros.\n                                                  gather_SEP 5 9 10 11 12 13 14 15.\n                                                  replace_SEP 0 \n                                                  (partial_treebox_rep_topdown\n                                                     (rev l)\n                                                     root b_ggpar p_gggpar nullval).\n                                                  { rewrite El.\n                                                    expand partial_treebox_rep_topdown.\n                                                    entailer!.\n                                                    Exists p_ans_another_child p_ans.\n                                                    entailer!. }\n                                                  rewrite <- partial_treebox_rep''.\n                                                  forward.\n                                                  repeat remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_runc; value_of_node := v_runc |}) \n                                                      as node_runc +\n                                                    remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n                                                    remember (T t3 n0 t4) as tree_ggpl.\n                                                  Exists (T tree_med (BlackNode node_par)\n                                      (T tree_rsib (RedNode node_gpar)\n                                      (T tree_runc_l node_runc tree_runc_r))) \n                                                       ((R, node_ggpar, tree_ggpl) :: l)\n                                                       (field_address t_struct_tree [StructField _left] p_ggpar)\n                                                       p_ggpar.\n                                                  rewrite <- H3.\n                                                  expand balance'.\n                                                  rewrite Ecolor_par. rewrite Heqtree_runc.\n                                                  destruct node_runc as[c_runc k_runc v_runc].\n                                                  assert(c_runc = Black)by auto.\n                                                  subst c_runc.\n                                                  repeat remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_runc; value_of_node := v_runc |}) \n                                                      as node_runc +\n                                                    remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n                                                    remember (T t3 n0 t4) as tree_ggpl.\n                                                  unfold r_rotate.\n                                                  expand partial_treebox_rep.\n                                                  Exists p_gggpar p_ggpl b_ggpar.\n                                                  expand treebox_rep.\n                                                  Exists p_par_med.\n                                                  unfold_data_at (data_at _ t_struct_tree _ p_ggpar).\n                                                  entailer!.\n                                                  repeat remember (T lch node_med rch) as tree_med +\n                                                    remember ({| color_of_node := Black; key_of_node := k_runc; value_of_node := v_runc |}) \n                                                      as node_runc +\n                                                    remember (T tree_runc_l node_runc tree_runc_r) as tree_runc +\n                                                    remember (T t3 n0 t4) as tree_ggpl.\n                                                  expand rbtree_rep.\n                                                  Exists p_med p_gpar p_rsib p_runc.\n                                                  entailer!. }\nQed.\nEnd insertBalance.", "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/verif_insert_balance.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.26135673865100073}}
{"text": "Set Implicit Arguments.\nFrom TLC Require Import LibLogic LibReflect.\nFrom TLC Require LibListZ.\nRequire Import CakeSem.Namespace.\nRequire Import CakeSem.Utils.\nRequire Import CakeSem.CakeAST.\nRequire Import CakeSem.SemanticsAux.\nRequire Import CakeSem.ffi.FFI.\nRequire Import String.\nRequire Import List.\nImport ListNotations.\nRequire Import ZArith.\nRequire String.\n\n\nOpen Scope string.\nOpen Scope Z_scope.\nOpen Scope list_scope.\n\n\n(*--------------------------*)\n(** Notes *)\n\n(* LATER: we could use implicit types to avoid type annotations for arguments of constructors throughout the files.\n   This would reduce the clutter. However, it requires renaming a bunch of variables, and would make it harder\n   to keep in sync with the cakeML semantics, so let's not do it now. *)\n\n(*--------------------------*)\n\n(** If the flag [doTypeChecks] is True, then the semantics performs a few type checks like the CakeML semantics does.\n    If the source code does type-check independently, then the flag may be set to False without altering the semantics. *)\n\nParameter doTypeChecks : bool.\n\nDefinition TypeCheck (P:Prop) :=\n  if doTypeChecks then P else True.\n\n(* BACKPORT: these definitions should be used throughout (with result in bool) *)\n\nDefinition UniquePatBindings (p:pat) : Prop :=\n  LibList.noduplicates (pat_bindings p).\n\nDefinition UniqueRecIdent (funs : list (varN * varN * exp)) : Prop :=\n  LibList.noduplicates (List.map (fun '(f,_,_) => f) funs).\n\nDefinition UniqueCtorsInDef (td : list tvarN * typeN * list (conN * list ast_t)) : Prop :=\n  let '(tvs,tn,condefs) := td in\n  LibList.noduplicates (List.map (fun '(n,_) => n) condefs).\n\nDefinition UniqueCtorsInDefs (tds : typeDef) : Prop :=\n  LibList.Forall UniqueCtorsInDef tds.\n\n\n(*--------------------------*)\n\n\n\n(* ********************************************************************** *)\n(** * Primitive operations *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Equality *)\n\n(** [appEq v1 v2 P] asserts that the values [v1] and [v2] are comparable\n    and that the proposition [P] characterizes whether they are equal.\n\n    [appEqList vs1 vs2 P] is similar, and requires the list to be of the\n    same lengths. *)\n\n(** BACKPORT: it is very strange to specify that all closures are equal,\n    this will certainly cause end-user bugs eventually. *)\n\nInductive appEq : val -> val -> Prop -> Prop :=\n\n  | appEq_lit : forall l1 l2,\n      TypeCheck (lit_same_type l1 l2) ->\n      appEq (Litv l1) (Litv l2) (l1 = l2)\n\n  | appEq_loc : forall l1 l2,\n      appEq (Loc l1) (Loc l2) (l1 = l2)\n\n  | appEq_closure : forall v1 v2,\n      is_closure v1 ->\n      is_closure v2 ->\n      appEq v1 v2 True\n\n  | appEq_conv_eq : forall cn vs1 vs2 P,\n      length vs1 = length vs2 ->\n      appEqList vs1 vs2 P ->\n      appEq (Conv cn vs1) (Conv cn vs2) P\n\n  | appEq_conv_neq : forall cn1 cn2 vs1 vs2,\n      cn1 <> cn2 ->\n      TypeCheck (ctor_same_type cn1 cn2) ->\n      appEq (Conv cn1 vs1) (Conv cn2 vs2) False\n\n  | appEq_vector_eq_length : forall vs1 vs2 P,\n      length vs1 = length vs2 ->\n      appEqList vs1 vs2 P ->\n      appEq (Vectorv vs1) (Vectorv vs2) P\n\n  | appEq_vector_neq_length : forall vs1 vs2,\n      length vs1 <> length vs2 ->\n      appEq (Vectorv vs1) (Vectorv vs2) False\n\nwith appEqList : list val -> list val -> Prop -> Prop :=\n\n  | appEqList_nil :\n      appEqList [] [] True\n\n  | appEqList_cons : forall v1 v2 vs1 vs2 P Ps,\n      appEq v1 v2 P ->\n      appEqList vs1 vs2 Ps ->\n      appEqList (v1::vs1) (v2::vs2) (P /\\ Ps).\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Primitive operations *)\n\n(** [appr s ffi op vs s' ffi' v'] asserts that the evaluation of [op] on the arguments [vs]\n    produces output [v], and updates the states accordingly.\n    This is an inductive version of do_app.\n\n    DISCLAIMER: currently covers only a subset of primitive functions. *)\n\n\nInductive appR (FFI : Type) (s : store val) (t : ffi_state FFI) : op -> list val -> store val -> ffi_state FFI -> val -> Prop :=\n\n  | appR_Opn : forall op (a b : int),\n      ((op = Divide \\/ op = Modulo) -> b <> 0) ->\n      appR s t (Opn op) [Litv (IntLit a); Litv (IntLit b)] s t (Litv (IntLit (opn_lookup op a b)))\n\n  | appR_Opb : forall op (a b : int),\n      appR s t (Opb op) [Litv (IntLit a); Litv (IntLit b)] s t (Propv (opb_lookup_Prop op a b))\n\n  | appR_Equality : forall (v1 v2 : val) (P:Prop),\n      appEq v1 v2 P ->\n      appR s t Equality [v1; v2] s t (Propv P)\n\n  | appR_Opassign : forall s' v lnum,\n      s' = store_assign_nocheck lnum (Refv v) s ->\n      appR s t Opassign [Loc lnum; v] s' t ConvUnit\n\n  | appR_Opref : forall s' v n,\n      (s',n) = store_alloc (Refv v) s ->\n      appR s t Opref [v] s' t (Loc n)\n\n  | appR_Opderef : forall v n,\n      store_lookup n s = Some (Refv v) ->\n      appR s t Opderef [Loc n] s t v\n\n  | appR_Aalloc : forall n v s' lnum n',\n      n >= 0 ->\n      n = Z.of_nat n' ->\n      (s',lnum) = store_alloc (Varray (List_replicate n' v)) s ->\n      appR s t Aalloc [Litv (IntLit n); v] s' t (Loc lnum)\n\n  | appR_Alength : forall n ws,\n      store_lookup n s = Some (Varray ws) ->\n      appR s t Alength [Loc n] s t (Litv (IntLit (Z.of_nat (List.length ws))))\n\n  | appR_Asub : forall lnum i vs v i',\n      store_lookup lnum s = Some (Varray vs) ->\n      (0 <= i < Zlength vs) ->\n      i = Z.of_nat i' ->\n      v = LibList.nth i' vs ->\n      appR s t Asub [Loc lnum; Litv (IntLit i)] s t v\n\n  | appR_Aupdate : forall lnum i n (vs:list val) s' v i',\n      store_lookup n s = Some (Varray vs) ->\n      (0 <= i < Zlength vs)%Z ->\n      i = Z.of_nat i' ->\n      s' = store_assign_nocheck lnum (Varray (LibList.update i' v vs)) s ->\n      appR s t Aupdate [Loc lnum; Litv (IntLit i); v] s' t ConvUnit.\n\n(** Alternative definitions using LibListZ to manipulate lists using integer indices directly\n\n  | appR_Aalloc' : forall n v s' lnum,\n      n >= 0 ->\n      (s',lnum) = store_alloc (Varray (ListZ_replicate n v)) s ->\n      appR s t Aalloc [Litv (IntLit n); v] s' t (Loc lnum)\n\n  | appR_Alength' : forall n ws,\n      store_lookup n s = Some (Varray ws) ->\n      appR s t Alength [Loc n] s t (Litv (IntLit (LibListZ.length ws)))\n\n  | appR_Asub' : forall lnum i vs,\n      store_lookup lnum s = Some (Varray vs) ->\n      (0 <= i < List.length vs)%Z ->\n      appR s t Asub [Loc lnum; Litv (IntLit i)] s t (LibContainer.read vs i)\n\n  | appR_Aupdate' : forall lnum i n vs s' v,\n      store_lookup n s = Some (Varray vs) ->\n      (0 <= i < List.length vs)%Z ->\n      s' = store_assign_nocheck lnum (Varray (LibContainer.update vs i v)) s ->\n      appR s t Aupdate [Loc lnum; Litv (IntLit i); v] s' t ConvUnit.\n*)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Regular function calls *)\n\n(** [opapp v env n e] asserts that [v] is a closure or recursive closure\n    whose argument is named [n] and whose body is [e], to be executed in\n    an environment [env] that includes the recursive bindings (if any).\n    This is an inductive version of [do_opapp] *)\n\nInductive opapp : val -> sem_env val -> varN -> exp -> Prop :=\n\n  | opapp_Closure : forall (env : sem_env val) (n : varN) (e : exp),\n      opapp (Closure env n e) env n e\n\n  | opapp_Recclosure : forall (env env': sem_env val) (funs : list (varN * varN * exp)) (nfun n : varN) (e : exp),\n      TypeCheck (UniqueRecIdent funs) ->\n      env' = update_sev env (build_rec_env funs env (sev env)) ->\n      find_recfun nfun funs = Some (n,e) ->\n      opapp (Recclosure env funs nfun) env' n e.\n\n\n(* ********************************************************************** *)\n(** * Pattern matching *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Matching against one pattern *)\n\n(** [pmatchR cenv st p v r] matches a value [v] against a pattern [p] and relates it\n    to a result [r] which is either [No_match] or [Match env_v] for some set of bindings [env_v].\n\n    Note: for tuples and constructors, the assumption [length vs = length ps] is redundant\n    with [patchlistR ... ps vs]  *)\n\nInductive pmatchR (cenv : env_ctor) : store val -> pat -> val -> match_result (alist varN val) -> Prop :=\n\n  | pmatchR_Pany : forall (sto : store val) (v : val),\n      pmatchR cenv sto Pany v (Match [])\n\n  | pmatchR_Pvar : forall (sto : store val) (v : val) (x : varN),\n      pmatchR cenv sto (Pvar x) v (Match [(x,v)])\n\n  | pmatchR_Plit_yes : forall (sto : store val) (l : lit),\n      pmatchR cenv sto (Plit l) (Litv l) (Match [])\n\n  | pmatchR_Plit_no : forall (sto : store val) (l1 l2 : lit),\n      TypeCheck (lit_same_type l1 l2) ->\n      l1 <> l2 ->\n      pmatchR cenv sto (Plit l1) (Litv l2) No_match\n\n  | pmatchR_Ptuple : forall (sto : store val) (ps : list pat) (vs : list val) m,\n      pmatchListR cenv sto ps vs m ->\n      pmatchR cenv sto (Pcon None ps) (Conv None vs) m\n\n  | pmatchR_PconYes : forall (sto : store val) (n : ident modN conN) (nstamp : stamp) (ps : list pat) (vs : list val) m,\n      nsLookup n cenv = Some (length ps, nstamp) ->\n      pmatchListR cenv sto ps vs m ->\n      pmatchR cenv sto (Pcon (Some n) ps) (Conv (Some nstamp) vs) m\n\n  | pmatchR_PconNo : forall (sto : store val) (n : ident modN conN) (nstamp1 nstamp2 : stamp) (ps : list pat) (vs : list val),\n      nsLookup n cenv = Some (length ps, nstamp2) ->\n      TypeCheck (stamp_same_type nstamp1 nstamp2) ->\n      nstamp1 <> nstamp2 ->\n      pmatchR cenv sto (Pcon (Some n) ps) (Conv (Some nstamp1) vs) No_match\n\n  | pmatchR_Pref : forall (sto : store val) (lnum : nat) (p : pat) (v : val) m,\n     store_lookup lnum sto = Some (Refv v) ->\n     pmatchR cenv sto p v m ->\n     pmatchR cenv sto (Pref p) (Loc lnum) m\n\n  | pmatchR_Ptannot : forall (sto : store val) (p : pat) (v : val) (t : ast_t) m,\n      pmatchR cenv sto p v m ->\n      pmatchR cenv sto (Ptannot p t) v m\n\n(** [pmatchListR cenv st ps vs r] matches a list of values [vs] against a list of patterns [ps],\n    and relates it to a result [r] which is either [No_match] or [Match env_v] for some set of\n    bindings [env_v].\n    The predicate can only hold when [ps] and [vs] have the same length. *)\n\nwith pmatchListR (cenv: env_ctor) : store val -> list pat -> list val -> match_result (alist varN val) -> Prop :=\n\n  | pmatchListR_nil : forall (sto : store val),\n      pmatchListR cenv sto [] [] (Match [])\n\n  | pmatchListR_cons_yes : forall (sto : store val) (p : pat) (ps : list pat) (v : val) (vs : list val) env_v1 env_v2,\n      pmatchR cenv sto p v (Match env_v1) ->\n      pmatchListR cenv sto ps vs (Match env_v2) ->\n      pmatchListR cenv sto (p::ps) (v::vs) (Match (env_v1 ++ env_v2))\n      (* Note: the order of nsAppend should be irrelevant because pattern variables are unique. *)\n\n  | pmatchListR_cons_no : forall (sto : store val) (p : pat) (ps : list pat) (v : val) (vs : list val) m,\n      pmatchR cenv sto p v No_match ->\n      pmatchListR cenv sto ps vs m ->\n      pmatchListR cenv sto (p::ps) (v::vs) No_match.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Matching against a list of clauses *)\n\n(** [matR st env v pes matchres] matches the value [v] against the list of clauses [pes],\n    and returns [None] if no pattern matches, or [Some (env_v,e_clause)] if the first clause that\n    applies has body [e_clause] and instantiate the pattern variables according to [env_v].\n    This is an inductive version of [evaluate_match] from the Lem semantics, up to the fact that\n    it does not perform the recursive call to evaluate directly, but instead returns the arguments\n    to be provided for that call. *)\n(* Inductive matR : (A : Type) (st : state A) (env : sem_env val): val -> pat * exp -> option (alist varN val * exp) := *)\n(* | matR_yes : forall (v : val) (p : pat) (e : exp) env_v, *)\n(*     pmatchR (sec env) (refs st) p v (Match env_v) -> *)\n(*     matR st env v (p,e) (Some (env_v,e)) *)\n\n(* | matR_no : forall (v : val) (p : pat) (e : exp), *)\n(*     pmatchR (sec env) (refs st) p v No_match -> *)\n(*     matR st env v (p,e) None *)\n\n(* with matRList (A : Type) (st : state A) (env : sem_env val) : val -> list (pat * exp) -> option (alist varN val * exp) -> Prop := *)\n\n(*    | matRList_nil : forall (v : val), *)\n(*       matRList st env v [] None *)\n\n(*    | matRList_consYes : forall (v : val) (p : pat) (e : exp) (pes' : list (pat * exp)) env_v, *)\n(*        TypeCheck (UniquePatBindings p) -> *)\n(*        pmatchR (sec env) (refs st) p v (Match env) -> *)\n(*        matRList st env v ((p,e)::pes') (Some (env_v,e)). *)\n\n Inductive matR (A : Type) (st : state A) (env : sem_env val) : val -> list (pat * exp) -> option (alist varN val * exp) -> Prop :=\n | matR_nil : forall (v : val),\n     matR st env v [] None\n\n | matR_consFail : forall (v : val) (p : pat) (e : exp) (pes' : list (pat * exp)),\n       TypeCheck (UniquePatBindings p) ->\n       pmatchR (sec env) (refs st) p v No_match ->\n       matR st env v (pes') None ->\n       matR st env v ((p,e)::pes') None\n\n | matR_consSucc : forall (v : val) (p : pat) (e e' : exp) (pes' : list (pat * exp)) env_v,\n     TypeCheck (UniquePatBindings p) ->\n     (pmatchR (sec env) (refs st) p v (Match env_v) /\\ e = e') \\/ matR st env v pes' (Some (env_v,e')) ->\n     matR st env v ((p,e)::pes') (Some (env_v,e')).\n\n\n(* ********************************************************************** *)\n(** * Evaluation *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Evaluation of expressions *)\n\n(** [expR st env e (st', Rval v)] asserts that, in environment [env], the expression [e] evaluates to [v],\n    and updates the state from [st] to [st']. *)\n\nInductive expR (A : Type) (st : state A) (env : sem_env val) : exp -> (state A) * result val val -> Prop :=\n\n  | expR_ELit : forall (l : lit),\n      expR st env (ELit l) (st, Rval (Litv l))\n\n  | expR_ECon : forall (st' : state A) (es : list exp) (vs : list val) (o : constr_id) (os : option stamp),\n      TypeCheck (con_check (sec env) o (length es)) ->\n      expListRevR st env es (st', Rval vs) ->\n      con_build (sec env) o os ->\n      expR st env (ECon o es) (st', Rval (Conv os vs))\n\n  | expR_EVar : forall (v : val) (i : ident modN varN),\n      nsLookup i (sev env) = Some v ->\n      expR st env (EVar i) (st, Rval v)\n\n  | expR_EFun : forall (e : exp) (x : varN),\n      expR st env (EFun x e) (st, Rval (Closure env x e))\n\n  | expR_EAppFunction  : forall (st': state A) (env' envclos : sem_env val) (ebody : exp) (es : list exp) (n : varN) v vclos res,\n      expListRevR st env es (st', Rval [vclos; v]) ->\n      opapp vclos envclos n ebody ->\n      env' = update_sev envclos (nsBind n v (sev envclos)) ->\n      expR st' env' ebody res ->\n      expR st env (EApp Opapp es) res\n\n  | expR_EAppPrimitive : forall (st' st'' : state A) (s' : store val) (ffi' : ffi_state A) (o : op) (es : list exp) (v : val) (vs : list val),\n      o <> Opapp -> (* redundant with [appR] but perhaps convenient in proofs *)\n      expListRevR st env es (st', Rval vs) ->\n      appR (refs st') (ffi st') o vs s' ffi' v ->\n      st'' = state_update_refs_and_ffi st' s' ffi' ->\n      expR st env (EApp o es) (st'', Rval v)\n\n  | expR_ELogFst : forall (st' : state A) (op : lop) (e1 e2 : exp) (v1: val),\n      expR st env e1 (st', Rval v1) ->\n      (match op with\n       | And => v1 = Boolv false\n       | Or => v1 = Boolv true\n       end) ->\n      expR st env (ELog op e1 e2) (st', Rval v1)\n\n  | expR_ELogSnd : forall (st' : state A) (op : lop) (e1 e2 : exp) (v1: val) res,\n      expR st env e1 (st', Rval v1) ->\n      (match op with\n       | And => v1 = Boolv true\n       | Or => v1 = Boolv false\n       end) ->\n      expR st' env e2 res ->\n      expR st env (ELog op e1 e2) res\n\n  | expR_EIf : forall (st' : state A) (e1 e2 e3 : exp) v1 res,\n      expR st env e1 (st', Rval v1) ->\n      (v1 = Boolv true  -> expR st' env e2 res) ->\n      (v1 = Boolv false -> expR st' env e3 res) ->\n      expR st env (EIf e1 e2 e3) res\n\n  | expR_EMatVal : forall (env' : sem_env val) (e : exp) (pes : list (pat * exp)) (v : val) st' env_v e_clause res,\n      expR st env e (st', Rval v) ->\n      matR st env v pes (Some (env_v, e_clause)) ->\n      env' = update_sev env (nsAppend (alist_to_ns env_v) (sev env)) ->\n      expR st env' e_clause res ->\n      expR st env (EMat e pes) res\n\n  | expR_ELet : forall (st' : state A) (env' : sem_env val) (e1 e2 : exp) (v1 : val) (o : option varN) res,\n      expR st env e1 (st', Rval v1) ->\n      env' = update_sev env (nsOptBind o v1 (sev env)) ->\n      expR st' env' e2 res ->\n      expR st env (ELet o e1 e2) res\n\n  | expR_ELetrec : forall (env': sem_env val) (e : exp) (funs : list (varN * varN * exp)) res,\n      env' = update_sev env (build_rec_env funs env (sev env)) ->\n      expR st env' e res ->\n      expR st env (ELetrec funs e) res\n\n  | expR_ETannot : forall (e : exp) (t : ast_t) res,\n      expR st env e res ->\n      expR st env (ETannot e t) res\n\n  | expR_ELannot : forall (e : exp) (l : locs) res,\n      expR st env e res ->\n      expR st env (ELannot e l) res\n\n\n(* [expListRevR st env es (st', Rval vs)] asserts that the expressions [es] evaluate to the list of values [vs]\n   when evaluated in right-to-left order (mimics the [reverse es] and [reverse vs] from the Lem semantics),\n   updating the state from [st] to [st']. *)\n\nwith expListRevR (A :Type) (st : state A) (env : sem_env val) : list exp -> ((state A) * result (list val) val) -> Prop :=\n\n   | expListRevR_nil :\n       expListRevR st env [] (st, Rval [])\n\n   | expListRevR_cons : forall (st' st'' : state A) (e : exp) (v : val) (es : list exp) (vs : list val),\n       expListRevR st env es (st', Rval vs) ->\n       expR st' env e (st'', Rval v) ->\n       expListRevR st env (e::es) (st'', Rval (v::vs)).\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Evaluation of top-level declarations *)\n\n\nInductive decR (A : Type) (st : state A) (env : sem_env val) : dec -> (state A) * (result (sem_env val) val) -> Prop :=\n\n  | decR_Dlet : forall (st' : state A) env_v env' (l : locs) (p : pat) (e : exp) (v : val),\n      TypeCheck (UniquePatBindings p) ->\n      expR st env e (st', Rval v) ->\n      pmatchR (sec env) (refs st') p v (Match env_v) ->\n      env' = {| sev := alist_to_ns env_v; sec := nsEmpty |} ->\n      decR st env (Dlet l p e) (st', Rval env')\n\n  | decR_Dletrec : forall (env' : sem_env val) (l : locs) (funs : list (varN * varN * exp)),\n      TypeCheck (UniqueRecIdent funs) ->\n      env' = {| sev := build_rec_env funs env nsEmpty ; sec := nsEmpty |} ->\n      decR st env (Dletrec l funs) (st, Rval env')\n\n  | decR_Dtype : forall (env' : sem_env val) (st' : state A) (l : locs) (tds : typeDef),\n      TypeCheck (UniqueCtorsInDefs tds) ->\n      st' = state_update_next_type_stamp st (next_type_stamp st + length tds) ->\n      env' = {| sev := nsEmpty ; sec := build_tdefs (next_type_stamp st) tds |} ->\n      decR st env (Dtype l tds) (st', Rval env')\n\n  | decR_Dtabbrev : forall (loc : locs) (tvs : list tvarN) (tn : typeN) (t : ast_t),\n      decR st env (Dtabbrev loc tvs tn t) (st, Rval empty_sem_env)\n\n  | decR_Dexn : forall (st' : state A) env' (loc : locs) (cn : conN) (ts : list ast_t),\n      st' = state_update_next_exn_stamp st (next_exn_stamp st + 1) ->\n      env' = {| sev := nsEmpty; sec := nsSing cn (length ts, ExnStamp (next_exn_stamp st)) |} ->\n      decR st env (Dexn loc cn ts) (st', Rval env')\n\n  | decR_Dmod : forall (st' : state A) (env' env'' : sem_env val) (mn : modN) (ds : list dec),\n      decListR st env ds (st', Rval env') ->\n      env'' = {| sev := nsLift mn (sev env'); sec := nsLift mn (sec env') |} ->\n      decR st env (Dmod mn ds) (st', Rval env'')\n\n  | decR_Dlocal : forall (st' : state A) (env' : sem_env val) (lds ds : list dec) res,\n      decListR st env lds (st', Rval env') ->\n      decListR st' (extend_dec_env env' env) ds res ->\n      decR st env (Dlocal lds ds) res\n\nwith decListR (A : Type) (st : state A) (env : sem_env val) : list dec -> (state A) * (result (sem_env val) val) -> Prop :=\n\n  | decR_Dnil :\n      decListR st env [] (st, Rval empty_sem_env)\n\n  | decR_DconsRval : forall (st' st'' : state A) (env1 env2 : sem_env val) (d : dec) (ds : list dec),\n      decR st env d (st', Rval env1) ->\n      decListR st' (extend_dec_env env1 env) ds (st'', Rval env2) ->\n      decListR st env (d::ds) (st'', Rval (extend_dec_env env2 env1)).\n\n\n(* ********************************************************************** *)\n(** * Notes for future work *)\n\n(*--------------------------------------------------------------\n  LATER: treatment of exceptions and the propagation of exceptions\n\n  | ERaise_R  : forall (st': state A) (e : exp) (v :val),\n      expR st env e (st', Rval v) ->\n      expR st env (ERaise e) (st', Rerr (Rraise v))\n      expR st env e (st', Rerr (Rraise err_v)) ->\n      matR st' env err_v l err_v (st'', r) ->\n      expR st env (EHandle e l) (st'', r)\n\n   | ArgsFail : forall (st' st'': state A) (res_val : result (list val) val) (err : error_result val) (e : exp) (es : list exp),\n       expListRevR st env es (st', res_val) -> expR st' env e (st'', Rerr err) ->\n       expListRevR st env (e::es) (st'', Rerr err)\n   | ArgsPrevFail : forall (st' st'' : state A) (e : exp) (v : val) (es : list exp) (err : error_result val),\n       expListRevR st env es (st', Rerr err) -> expListRevR st env (e::es) (st', Rerr err)\n  | DconsRerr_R : forall (st' : state A) (d : dec) (ds : list dec) (res : result (sem_env val) val) (err_v : error_result val),\n      decR st env d (st', res) ->\n      combineDecResultR env res (Rerr err_v) ->\n      decListR st env (d::ds) (st', Rerr err_v).\n\n  | EMatVal_R : forall (env' : sem_env val) (e : exp) (pes : list (pat * exp)) (v : val) st' res,\n      expR st env e (st', Rval v) ->\n      matR st env v pes matchres ->\n      (match matchres with\n      | None -> res = (st, Rerr (Rraise bind_exn_v))\n      | Some (env_clause, e_clause) ->\n          let env' := extend_dec_env env_clause env in\n          ---non strictly positive occurence here, so need to eliminate the match---\n          expR st env' e_clause res\n      end) ->\n      expR st env (EMat e pes) res\n\n  + fallthrough for every rule\n    or a factorized fallthrough using pretty-big-step presentation\n\n  | decR_Dmod_Fail : forall (st' : state A) (mn : modN) (ds : list dec) (d : list dec) (err_v : error_result val),\n      decListR st env ds (st', Rerr err_v) ->\n      decR st env (Dmod mn ds) (st', Rerr err_v)\n\n  | decR_DletExpFail : forall (st' st'' : state A) (env' : sem_env val) (sto : store val) (l : locs)\n                      (p : pat) (e : exp) (err_v : error_result val) (res : result (sem_env val) val),\n      expR st env e (st', Rerr err_v) ->\n      decR st env (Dlet l p e) (st', Rerr err_v)\n\n  | decR_DletMatFail : forall (st' st'' : state A) (env' : sem_env val) (sto : store val) (l : locs)\n                      (p : pat) (e : exp) (v : val) (res : result (sem_env val) val),\n      expR st env e (st', Rval v) ->\n      sto = refs st' ->\n      pmatchR sto env p v No_match ->\n      decR st env (Dlet l p e) (st', res)\n\n\n  Inductive combineDecResultR (env : sem_env val) : result (sem_env val) val -> result (sem_env val) val -> Prop :=\n    | combineRerr : forall (e : error_result val),\n        combineDecResultR env (Rerr e) (Rerr e)\n    | combineRval : forall (env' : sem_env val),\n        combineDecResultR env (Rval env') (Rval {| sev := nsAppend (sev env') (sev env);\n                                                   sec := nsAppend (sec env') (sec env) |}).\n\n\nFUTURE WORK vectors\n\n   | app_VfromList : forall s t v vs,\n      v_to_list v = Some vs ->\n      appR s t VfromList [v] s t (Vectorv vs)\n\n\n    | (Vsub, [Vectorv vs; Litv (IntLit i)]) ->\n        if i < 0 then\n          Just ((s,t), Rerr (Rraise sub_exn_v))\n        else\n          let n = natFromInteger i in\n            if n >= List.length vs then\n              Just ((s,t), Rerr (Rraise sub_exn_v))\n            else\n              Just ((s,t), Rval (List_extra.nth vs n))\n    | (Vlength, [Vectorv vs]) ->\n        Just ((s,t), Rval (Litv (IntLit (integerFromNat (List.length vs)))))\n\n\nFUTURE WORK more on arrays\n\n  | app_AallocEmpty : forall s t n v s' lnum,\n      (s',lnum) = store_alloc (Varray []) s ->\n      appR s t AallocEmpty [ConvUnit) s' t (Loc lnum)\n\n*)\n\n\n(** QUESTION: would it make sense that the recursive closures store as environment not [env]\n    but directly [env with v = build_rec_env funs env env.v], rather than rebuilding\n    this extended environment each time? *)\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/cakeSemantics/RelationalBigStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.261356731830553}}
{"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.\nFrom PromisingLib Require Import Language.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\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. condtac; ss; i.\n      * des. subst. exploit Memory.remove_get0; eauto. i. des. congr.\n      * congr.\n  - exploit Memory.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: 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. 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: @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.\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  exploit Memory.max_concrete_timemap_exists; try apply x0. i. des.\n  hexploit Memory.max_concrete_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.concrete v r))\n      (CONS: Local.promise_consistent lc2):\n  Time.lt to t.\nProof.\n  inv STEP. exploit CONS; eauto. s. i.\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.concrete 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. i. 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": "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/PromiseConsistent.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850278370111, "lm_q2_score": 0.3702253856469203, "lm_q1q2_score": 0.26129953411477985}}
{"text": "From Coq Require Import String ZArith Eqdep_dec.\n\nFrom Vyper Require Import Config Calldag L10.Base.\nFrom Vyper Require L20.AST L30.AST L20.Interpret L30.Interpret.\n\nFrom Vyper.From20To30 Require Import Translate Callset.\n\n\n\nLocal Lemma translate_calldag_depthmap_ok {C: VyperConfig}\n                                          (name: string)\n                                          (cd: L20.Descend.calldag)\n                                          (d: string_map L30.AST.decl):\n   let _ := string_map_impl in\n   forall E: map_maybe_map (cd_decls cd) translate_decl = inr d,\n     match Map.lookup d name with\n     | Some decl =>\n         match cd_depthmap cd name with\n         | Some x =>\n             let _ := string_set_impl in\n             FSet.for_all (Callset.decl_callset decl)\n               (fun callee : string =>\n                match cd_depthmap cd callee with\n                | Some y => y <? x\n                | None => false\n                end) = true\n         | None => False\n         end\n     | None => True\n     end.\nProof.\nintros.\nremember (Map.lookup d name) as m.\ndestruct m. 2:trivial.\nassert (D := cd_depthmap_ok cd name).\nassert (F := map_maybe_map_ok E name).\ndestruct (Map.lookup (cd_decls cd) name). 2:{ now rewrite F in Heqm. }\ndestruct (cd_depthmap cd name). 2:assumption.\nrewrite FSet.for_all_ok. rewrite FSet.for_all_ok in D.\nintros x H.\nremember (translate_decl d1) as d30.\ndestruct d30. { contradiction. }\nrewrite<- Heqm in F. inversion F; subst.\nrewrite (callset_translate_decl _ _ (eq_sym Heqd30)) in H.\napply (D x H).\nQed.\n\nDefinition translate_calldag {C: VyperConfig} (cd: L20.Descend.calldag)\n: string + L30.Descend.calldag\n:= let _ := string_map_impl in\n   match map_maybe_map (cd_decls cd) translate_decl as cd' return _ = cd' -> _ with\n   | inl err => fun _ => inl err\n   | inr d => fun E => inr\n     {| cd_decls := d\n      ; cd_depthmap := cd_depthmap cd\n      ; cd_depthmap_ok name := translate_calldag_depthmap_ok name cd d E\n     |}\n   end eq_refl.\n\n(***************************************************************************************************)\n\nSection FunCtx1.\n  Context {C: VyperConfig}\n          {bound: nat}\n          {cd20: L20.Descend.calldag}\n          {cd30: L30.Descend.calldag}\n          (ok: translate_calldag cd20 = inr cd30).\n\n  Lemma translate_fun_ctx_depthmap (name: string):\n    cd_depthmap cd30 name\n     =\n    cd_depthmap cd20 name.\n  Proof.\n  destruct cd20.\n  unfold translate_calldag in ok.\n  cbn in *.\n  remember (fun d (E : map_maybe_map cd_decls translate_decl = inr d) =>\n         inr\n           {|\n           cd_decls := d;\n           cd_depthmap := cd_depthmap;\n           cd_depthmap_ok := fun name : string =>\n                             translate_calldag_depthmap_ok name\n                               {|\n                               cd_decls := cd_decls;\n                               cd_depthmap := cd_depthmap;\n                               cd_depthmap_ok := cd_depthmap_ok |} d E |}) as good_branch.\n  assert (K: forall (d30: string_map L30.AST.decl)\n                    (E: map_maybe_map cd_decls translate_decl = inr d30),\n               good_branch d30 E = inr cd30 \n                ->\n               Calldag.cd_depthmap cd30 name = cd_depthmap name).\n  {\n    intros. subst.\n    inversion H. now subst.\n  }\n  clear Heqgood_branch.\n  destruct (map_maybe_map cd_decls translate_decl) as [|d30]. { discriminate. }\n  apply (K d30 eq_refl ok).\n  Qed.\n\n  Lemma translate_fun_ctx_declmap (name: string):\n    match cd_declmap cd20 name with\n    | Some d => Some (translate_decl d)\n    | None => None\n    end\n     =\n    match cd_declmap cd30 name with\n    | Some d => Some (inr d)\n    | None => None\n    end.\n  Proof.\n  destruct cd20.\n  unfold translate_calldag in ok.\n  cbn in *.\n  remember (fun d (E : map_maybe_map cd_decls translate_decl = inr d) =>\n         inr\n           {|\n           cd_decls := d;\n           cd_depthmap := cd_depthmap;\n           cd_depthmap_ok := fun name : string =>\n                             translate_calldag_depthmap_ok name\n                               {|\n                               cd_decls := cd_decls;\n                               cd_depthmap := cd_depthmap;\n                               cd_depthmap_ok := cd_depthmap_ok |} d E |}) as good_branch.\n  unfold cd_declmap. cbn.\n  assert (K: forall (d30: string_map L30.AST.decl)\n                    (E: map_maybe_map cd_decls translate_decl = inr d30),\n               good_branch d30 E = inr cd30 \n                ->\n               let _ := string_map_impl in\n               match Map.lookup cd_decls name with\n               | Some d => Some (translate_decl d)\n               | None => None\n               end = match Map.lookup (Calldag.cd_decls cd30) name with\n                     | Some d => Some (inr d)\n                     | None => None\n                     end).\n  {\n    intros. subst.\n    inversion H. subst.\n    cbn.\n    clear H ok.\n    assert (M := map_maybe_map_ok E name).\n    destruct (Map.lookup cd_decls name). 2:{ now destruct Map.lookup. }\n    destruct (translate_decl d). { contradiction. }\n    (* why rewrite M doesn't work? *)\n    destruct Map.lookup. { now inversion M. }\n    discriminate.\n  }\n  clear Heqgood_branch.\n  destruct (map_maybe_map cd_decls translate_decl) as [|d30]. { discriminate. }\n  apply (K d30 eq_refl ok).\n  Qed.\nEnd FunCtx1.\n\nSection FunCtx2.\n  Context {C: VyperConfig}\n          {bound: nat}\n          {cd20: L20.Descend.calldag}\n          (fc: fun_ctx cd20 bound)\n          {cd30: L30.Descend.calldag}\n          (ok: translate_calldag cd20 = inr cd30).\n\n  Local Lemma translate_fun_ctx_fun_decl_helper:\n    cd_declmap cd30 (fun_name fc) <> None.\n  Proof.\n  intro E.\n  assert (Ok := fun_decl_ok fc).\n  assert (M := translate_fun_ctx_declmap ok (fun_name fc)).\n  rewrite Ok in M.\n  rewrite E in M.\n  discriminate.\n  Qed.\n\n  Definition cached_translated_decl\n  := match cd_declmap cd30 (fun_name fc)\n     as d' return _ = d' -> _\n     with\n     | Some f => fun _ => f\n     | None => fun E =>\n          False_rect _ (translate_fun_ctx_fun_decl_helper E)\n     end eq_refl.\n\n  Local Lemma translate_fun_ctx_decl_ok:\n    cd_declmap cd30 (fun_name fc) \n     =\n    Some cached_translated_decl.\n  Proof.\n  assert (D := fun_decl_ok fc).\n  unfold cached_translated_decl.\n  remember translate_fun_ctx_fun_decl_helper as foo. clear Heqfoo. revert foo.\n  destruct (cd_declmap cd30 (fun_name fc)). { trivial. }\n  intro. contradiction.\n  Qed.\n\n  Definition translate_fun_ctx\n  : fun_ctx cd30 bound\n  := let name := fun_name fc in\n     {| fun_name := name\n      ; fun_depth := fun_depth fc\n      ; fun_depth_ok :=\n          eq_trans (translate_fun_ctx_depthmap ok name)\n                   (fun_depth_ok fc)\n      ; fun_decl := cached_translated_decl\n      ; fun_decl_ok := translate_fun_ctx_decl_ok\n      ; fun_bound_ok := fun_bound_ok fc\n     |}.\nEnd FunCtx2.", "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/From20To30/FunCtx.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.26129952921051525}}
{"text": "Require Import Cosa.Lib.Header.\nRequire Import AST.\nRequire Import Memory.\nRequire Import Values.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Coq.Classes.Morphisms.\nRequire Import Cosa.Lib.Predicate.\nRequire Import Cosa.Lib.Relation.\n\n(** Concrete heap fragment are used as the concrete memory\n    representation in the Cosa shape domain. A fragment is a Compcert\n    C heap together with a predicate representing the memory currently\n    accessible. It allows to reason separately on different fragment\n    of the same heap, as in separation logic. *)\n\nDefinition fragment := (mem*℘ (block*Z.t))%type.\n\nDefinition star : fragment->fragment->fragment->Prop := Relation.pair teq disjoint_union.\nNotation \"h₁ ⋆ h₂ 'is' s\" := (star h₁ h₂ s) (at level 15).\n\nDefinition estar := extension2 star.\nNotation \"h₁ ★ h₂\" := (estar h₁ h₂) (at level 15).\n\nDefinition empty (h:fragment) : Prop := snd h = ∅.\nArguments empty h /.\n\nLemma empty_spec : empty = Predicate.pair (fun _ => True) (eq ∅).\nProof.\n  apply Predicate.equiv_eq; intro h.\n  unfold empty, Predicate.pair.\n  firstorder.\nQed.\n\nInstance star_assoc : Associative eq estar.\nProof.\n  unfold estar,star; typeclasses eauto.\nQed.\n\nInstance star_comm : Commutative eq estar.\nProof.\n  unfold estar,star; typeclasses eauto.\nQed.\n\nCorollary star_commutative_rel : forall h₁ h₂ s, h₁ ⋆ h₂ is s -> h₂ ⋆ h₁ is s.\nProof.\n  intros h₁ h₂ s.\n  apply commutative_rel.\n  typeclasses eauto.\nQed.\n\nInstance star_empty_neutral : LeftNeutral eq estar empty.\nProof.\n  rewrite empty_spec.\n  unfold estar,star; typeclasses eauto.\nQed.\n\n\nImport ZArith. (* arnaud: y a-t-il un autre moyen de récupérer les notations de Z.t ? *)\n\n(** [memory_range b off size] represents a contiguous zone of memory\n    in block [b], starting at offset int and of size [size]. *)\nDefinition memory_range (b:block) (off:int) (chunk:memory_chunk) : (block*Z.t) -> Prop :=\n  fun loc =>\n    let '(b',off') := loc in\n   (b' = b /\\ Int.unsigned off <= off' /\\ off' <= (Int.unsigned off)+(Memdata.size_chunk chunk))%Z\n.\n\nDefinition valid (b:block) (off:int) (chunk:memory_chunk) (h:fragment) : Prop :=\n  memory_range b off chunk ⊆ snd h\n.\n\n\n(** Lifts [Mem.loadv] to [fragment]. (spiwack:) I chose the semantics\n    of [reads] to fail when accessling a zone of memory which isn't\n    included in the accessible zone. I'm not sure whether it is the\n    correct semantics. *)\nInductive reads (h:fragment) (chunk:memory_chunk) (b:block) (offs:int) (v:val) : Prop :=\n| reads_intro :\n    valid b offs chunk h ->\n    Mem.loadv chunk (fst h) (Vptr b offs) = Some v ->\n    reads h chunk b offs v\n.\n\n(** Variant of [read] taking the address as a value. *)\nDefinition readsv (h:fragment) (chunk: memory_chunk) (addr: val) (v:val) : Prop :=\n  match addr with\n  | Vptr b offs => reads h chunk b offs v\n  | _ => False\n  end\n.\n\n\nLemma star_read_left h₁ h₂ s : h₁ ⋆ h₂ is s -> forall chunk b offs v,\n                    reads h₁ chunk b offs v -> reads s chunk b offs v.\nProof.\n  destruct h₁ as [ h₁ a₁ ].\n  destruct h₂ as [ h₂ a₂ ].\n  destruct s  as [ h_s a_s ].\n  intros [ h₁h₂ disjoint ] c b offs v [ p₁ p₂ ].\n  simpl in *.\n  destruct h₁h₂.\n  constructor.\n  - unfold valid; simpl.\n    intros x rnge.\n    unfold disjoint_union in disjoint.\n    destruct disjoint as [ disjoint union ].\n    apply predicate_equality in union; unfold Predicate.equiv in union.\n    apply union.\n    left.\n    now apply p₁.\n  - easy.\nQed.\n\nCorollary star_readv_left h₁ h₂ s : h₁ ⋆ h₂ is s -> forall chunk vaddr v,\n                    readsv h₁ chunk vaddr v -> readsv s chunk vaddr v.\nProof.\n  intros h *.\n  destruct vaddr; simpl; trivial.\n  eapply star_read_left; eauto.\nQed.\n\nLemma star_read_right h₁ h₂ s : h₁ ⋆ h₂ is s -> forall chunk b offs v,\n                    reads h₂ chunk b offs v -> reads s chunk b offs v.\nProof.\n  intros s_star **.\n  apply star_commutative_rel in s_star.\n  eapply star_read_left; eauto.\nQed.\n\nCorollary star_readv_right h₁ h₂ s : h₁ ⋆ h₂ is s -> forall chunk vaddr v,\n                    readsv h₂ chunk vaddr v -> readsv s chunk vaddr v.\nProof.\n  intros h *.\n  destruct vaddr; simpl; trivial.\n  eapply star_read_right; eauto.\nQed.\n", "meta": {"author": "aspiwack", "repo": "cosa", "sha": "2d808236e71f2289033dff6b74a3f57311df9a14", "save_path": "github-repos/coq/aspiwack-cosa", "path": "github-repos/coq/aspiwack-cosa/cosa-2d808236e71f2289033dff6b74a3f57311df9a14/Concrete/ConcreteFragment.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.26129276349019154}}
{"text": "From Perennial.program_proof.mvcc Require Import\n     txn_prelude txnmgr_repr\n     tid_proof.\n\nSection program.\nContext `{!heapGS Σ, !mvcc_ghostG Σ}.\n\n(*****************************************************************)\n(* func (txnMgr *TxnMgr) getMinActiveTIDSite(sid uint64) uint64  *)\n(*****************************************************************)\nTheorem wp_txnMgr__getMinActiveTIDSite txnmgr (sid : u64) γ :\n  is_txnmgr txnmgr γ -∗\n  {{{ ⌜int.Z sid < int.Z N_TXN_SITES⌝ }}}\n    TxnMgr__getMinActiveTIDSite #txnmgr #sid\n  {{{ (tid : u64), RET #tid; site_min_tid_lb γ sid (int.nat tid) }}}.\nProof.\n  iIntros \"#Htxnmgr\" (Φ) \"!> %Hbound HΦ\".\n  iNamed \"Htxnmgr\".\n  iMod (readonly_load with \"HsitesS\") as (q) \"HsitesS'\".\n  wp_call.\n\n  (***********************************************************)\n  (* site := txnMgr.sites[sid]                               *)\n  (***********************************************************)\n  wp_loadField.\n  list_elem sitesL (int.nat sid) as site.\n  { revert HsitesLen. unfold N_TXN_SITES in *. word. }\n  wp_apply (wp_SliceGet with \"[$HsitesS']\").\n  { iPureIntro.\n    rewrite list_lookup_fmap.\n    by rewrite Hsite_lookup.\n  }\n  iIntros \"[HsitesS' _]\".\n  wp_pures.\n  \n  (***********************************************************)\n  (* site.latch.Lock()                                       *)\n  (***********************************************************)\n  iDestruct (big_sepL_lookup with \"HsitesRP\") as \"HsiteRP\"; first done.\n  iClear (latch) \"Hlatch Hlock\".\n  iNamed \"HsiteRP\".\n  wp_loadField.\n  wp_apply (acquire_spec with \"[$Hlock]\").\n  iIntros \"[Hlocked HsiteOwn]\".\n  replace (U64 (Z.of_nat _)) with sid by word. \n  iNamed \"HsiteOwn\".\n  iDestruct (typed_slice.is_slice_sz with \"HactiveL\") as \"%HtidsactiveSz\".\n  wp_pures.\n  \n  (***********************************************************)\n  (* var tidnew uint64                                       *)\n  (* tidnew = GenTID(sid)                                    *)\n  (***********************************************************)\n  wp_apply wp_ref_of_zero; first done.\n  iIntros (tidRef) \"HtidRef\".\n  wp_pures.\n  wp_apply (wp_GenTID with \"Hinvtid Hsidtok\").\n  { done. }\n  (* Open the SST invariant to get [ts_auth]. *)\n  iInv \"Hinvsst\" as \"> HinvsstO\" \"HinvsstC\".\n  iDestruct (mvcc_inv_sst_ts_auth_acc with \"HinvsstO\") as (ts) \"[Hts HinvtsC]\".\n  (* Open the GC invariant. *)\n  iInv \"Hinvgc\" as \"> HinvgcO\" \"HinvgcC\".\n  iDestruct (big_sepL_lookup_acc with \"HinvgcO\") as \"[HinvsiteO HinvsiteC]\".\n  { by apply sids_all_lookup. }\n  iNamed \"HinvsiteO\".\n  (* Obtain [tidmax ≤ ts]. *)\n  iDestruct (ts_auth_lb_le with \"Hts Htslb\") as %Hle.\n  (* Agree on the active TIDs obtained from lock and global invariants. *)\n  iDestruct (site_active_tids_agree with \"HactiveA HactiveAuth\") as %->.\n  (* Give atomic precondition. *)\n  iExists _. iFrame \"Hts\".\n  iApply ncfupd_mask_intro; first set_solver.\n  iIntros \"Hclose\".\n  iIntros \"%tsnew (Htsnew & %Hlt)\". rename ts into tsold.\n  (* Update the minimal TID to the smallest among [{[ tsnew ]} ∪ tidsactiveM]. *)\n  set tids := {[ tsnew ]} ∪ tidsactiveM.\n  assert (∃ tidmin', set_Forall (λ tid, (tidmin' ≤ tid)%nat) tids ∧ tidmin' ∈ tids)\n    as (tidmin' & Htidmin' & Helem).\n  { destruct (minimal_exists_L Nat.le tids) as (tidx & Htidx & Hminimal); first set_solver.\n    exists tidx.\n    split; last done.\n    rewrite minimal_anti_symm in Hminimal.\n    intros tidy Htidy.\n    destruct (decide (tidx ≤ tidy)%nat); first done.\n    apply Hminimal in Htidy; lia.\n  }\n  iMod (site_min_tid_update tidmin' with \"HminA\") as \"HminA\".\n  { rewrite elem_of_union in Helem.\n    destruct Helem; last by auto.\n    (* Case [tidmin' = ts]. *)\n    rewrite elem_of_singleton in H.\n    rewrite H.\n    apply set_Forall_union_inv_1, set_Forall_singleton in Hmax.\n    lia.\n  }\n  iDestruct (site_min_tid_witness with \"HminA\") as \"#Hminlb\".\n  iClear \"Htslb\".\n  iDestruct (ts_witness with \"Htsnew\") as \"#Htslb\".\n  iMod \"Hclose\" as \"_\".\n  (* Close the GC invariant. *)\n  iDestruct (\"HinvsiteC\" with \"[HactiveA HminA]\") as \"HinvsiteO\".\n  { iExists _, _, tsnew.\n    iFrame \"∗ Htslb\".\n    iPureIntro.\n    split.\n    { eapply set_Forall_subseteq; last apply Htidmin'. set_solver. }\n    { (* apply set_Forall_union_inv_1 in Hmax as Hminmax.\n      rewrite set_Forall_singleton in Hminmax. *)\n      apply set_Forall_union.\n      { rewrite set_Forall_singleton.\n        apply set_Forall_union_inv_1 in Htidmin'.\n        rewrite set_Forall_singleton in Htidmin'. lia.\n      }\n      { apply set_Forall_union_inv_2 in Hmax.\n        eapply set_Forall_impl; first apply Hmax.\n        word.\n      }\n    }\n  }\n  iMod (\"HinvgcC\" with \"HinvsiteO\") as \"_\".\n  iDestruct (\"HinvtsC\" with \"[] Htsnew\") as \"HinvsstO\".\n  { iPureIntro. lia. }\n  iMod (\"HinvsstC\" with \"HinvsstO\") as \"_\".\n  iModIntro.\n  iIntros (tidnew) \"[%Etidnew Hsidtok]\".\n  subst tsnew.\n  wp_store.\n  \n  (***********************************************************)\n  (* machine.Assume(tidnew < 18446744073709551615)           *)\n  (***********************************************************)\n  wp_load.\n  wp_apply wp_Assume.\n  iIntros (Hoverflow).\n  apply bool_decide_eq_true_1 in Hoverflow.\n  \n  (***********************************************************)\n  (* var tidmin uint64 = tidnew                              *)\n  (***********************************************************)\n  wp_load.\n  wp_apply (wp_ref_to); first by auto.\n  iIntros (tidminRef) \"HtidminRef\".\n  wp_pures.\n\n  (***********************************************************)\n  (* for _, tid := range site.tidsActive {                   *)\n  (*     if tid < tidmin {                                   *)\n  (*         tidmin = tid                                    *)\n  (*     }                                                   *)\n  (* }                                                       *)\n  (***********************************************************)\n  set u64_to_nat := (λ x : u64, int.nat x).\n  iDestruct (is_slice_small_acc with \"HactiveL\") as \"[HactiveS HactiveC]\".\n  wp_loadField.\n  set P := λ (i : u64), (∃ (tidloop : u64), let tids := tidnew :: (take (int.nat i) tidsactiveL) in\n    \"HtidminRef\" ∷ tidminRef ↦[uint64T] #tidloop ∗\n    \"%Helem'\" ∷ ⌜tidloop ∈ tids⌝ ∗\n    \"%Htidloop\" ∷ (⌜Forall (λ tid, (int.nat tidloop ≤ tid)%nat) (u64_to_nat <$> tids)⌝))%I.\n  wp_apply (typed_slice.wp_forSlice P _ _ _ _ _ tidsactiveL with \"[] [HtidminRef $HactiveS]\").\n  { clear Φ.\n    iIntros (i tidx Φ) \"!> (Hloop & %Hbound' & %Hlookup) HΦ\".\n    iNamed \"Hloop\".\n    wp_load.\n    wp_if_destruct.\n    - wp_store.\n      iApply \"HΦ\".\n      iModIntro.\n      iExists _.\n      iFrame.\n      do 2 replace (int.nat (word.add i 1)) with (S (int.nat i)) by word.\n      rewrite (take_S_r _ _ tidx); last done.\n      iSplit; iPureIntro.\n      { set_solver. }\n      { rewrite app_comm_cons fmap_app.\n        rewrite Forall_app.\n        split.\n        { apply (Forall_impl _ _ _ Htidloop). word. }\n        apply Forall_singleton. done.\n      }\n    - iApply \"HΦ\".\n      iModIntro.\n      iExists _.\n      iFrame.\n      do 2 replace (int.nat (word.add i 1)) with (S (int.nat i)) by word.\n      rewrite (take_S_r _ _ tidx); last done.\n      iSplit; iPureIntro.\n      { set_solver. }\n      { rewrite app_comm_cons fmap_app.\n        rewrite Forall_app.\n        split.\n        { apply (Forall_impl _ _ _ Htidloop). word. }\n        apply Forall_singleton. subst u64_to_nat. word.\n      }\n  }\n  { iExists _.\n    iFrame.\n    iPureIntro.\n    rewrite take_0.\n    rewrite Forall_forall.\n    split; set_solver.\n  }\n  iIntros \"[Hloop HactiveS]\".\n  subst P. simpl. iNamed \"Hloop\".\n  wp_pures.\n  \n  (***********************************************************)\n  (* site.latch.Unlock()                                     *)\n  (***********************************************************)\n  iDestruct (\"HactiveC\" with \"HactiveS\") as \"HactiveL\".\n  wp_loadField.\n  wp_apply (release_spec with \"[-HΦ HtidminRef]\").\n  { eauto 10 with iFrame. }\n  wp_pures.\n\n  (***********************************************************)\n  (* return tidmin                                           *)\n  (***********************************************************)\n  (* Deduce [tidmin' = tidloop]. *)\n  rewrite -HtidsactiveSz firstn_all in Htidloop Helem'.\n  replace tidmin' with (int.nat tidloop); last first.\n  { subst tids tidsactiveM.\n    clear -Helem Htidmin' Helem' Htidloop.\n    rewrite -list_to_set_cons elem_of_list_to_set in Helem.\n    rewrite -list_to_set_cons set_Forall_list_to_set in Htidmin'.\n    replace (int.nat tidnew) with (u64_to_nat tidnew) in Helem, Htidmin'; last done.\n    rewrite -fmap_cons in Helem Htidmin'.\n    apply (elem_of_list_fmap_1 u64_to_nat) in Helem'.\n    rewrite Forall_forall in Htidmin'.\n    rewrite Forall_forall in Htidloop.\n    apply Htidmin' in Helem'.\n    apply Htidloop in Helem.\n    subst u64_to_nat. word.\n  }\n  wp_load.\n  by iApply \"HΦ\".\nQed.\n\n(*****************************************************************)\n(* func (txnMgr *TxnMgr) getMinActiveTID() uint64                *)\n(*****************************************************************)\nTheorem wp_txnMgr__getMinActiveTID txnmgr γ :\n  is_txnmgr txnmgr γ -∗\n  {{{ True }}}\n    TxnMgr__getMinActiveTID #txnmgr\n  {{{ (tid : u64), RET #tid; min_tid_lb γ (int.nat tid) }}}.\nProof.\n  iIntros \"#Htxnmgr\" (Φ) \"!> _ HΦ\".\n  wp_call.\n  \n  (***********************************************************)\n  (* var min uint64 = config.TID_SENTINEL                    *)\n  (***********************************************************)\n  wp_apply (wp_ref_to); first auto.\n  iIntros (minRef) \"HminRef\".\n  wp_pures.\n    \n  (***********************************************************)\n  (* for sid := uint64(0); sid < config.N_TXN_SITES; sid++ { *)\n  (*     tid := txnMgr.getMinActiveTIDSite(sid)              *)\n  (*     if tid < min {                                      *)\n  (*         min = tid                                       *)\n  (*     }                                                   *)\n  (* }                                                       *)\n  (***********************************************************)\n  wp_apply (wp_ref_to); first auto.\n  iIntros (sidRef) \"HsidRef\".\n  wp_pures.\n  set P := λ (i : u64), (∃ (tidmin : u64),\n    \"HminRef\" ∷ minRef ↦[uint64T] #tidmin ∗\n    \"Htidlbs\" ∷ [∗ list] sid ∈ (take (int.nat i) sids_all), site_min_tid_lb γ sid (int.nat tidmin))%I.\n  wp_apply (wp_forUpto P _ _ (U64 0) (U64 N_TXN_SITES) sidRef with \"[] [HminRef HsidRef]\"); first done.\n  { clear Φ.\n    iIntros (i Φ) \"!> (Hloop & HsidRef & %Hbound) HΦ\".\n    iNamed \"Hloop\".\n    wp_pures.\n    wp_load.\n    wp_apply (wp_txnMgr__getMinActiveTIDSite with \"Htxnmgr\"); first done.\n    iIntros (tid) \"Htidlb\".\n    wp_pures.\n    wp_load.\n    wp_pures.\n\n    wp_if_destruct.\n    - (* Find new min. *)\n      wp_store.\n      iApply \"HΦ\".\n      iModIntro.\n      iFrame.\n      iExists _.\n      iFrame.\n      replace (int.nat (word.add _ _)) with (S (int.nat i)); last by word.\n      rewrite (take_S_r _ _ i); last by apply sids_all_lookup.\n      iApply big_sepL_app.\n      iSplitL \"Htidlbs\".\n      { iApply (big_sepL_impl with \"Htidlbs\").\n        iModIntro.\n        iIntros (iN sid) \"Hlookup Htidlb\".\n        (* Weaken all previous lower bounds. *)\n        iApply (site_min_tid_lb_weaken with \"Htidlb\").\n        word.\n      }\n      { simpl. auto. }\n    - (* Same min. *)\n      iApply \"HΦ\".\n      iModIntro.\n      iFrame.\n      iExists _.\n      iFrame.\n      replace (int.nat (word.add _ _)) with (S (int.nat i)); last by word.\n      rewrite (take_S_r _ _ i); last by apply sids_all_lookup.\n      iApply big_sepL_app.\n      iSplitL \"Htidlbs\"; first done.\n      simpl.\n      iSplit; last done.\n      (* Weaken the current lower bound. *)\n      iApply (site_min_tid_lb_weaken with \"Htidlb\").\n      word.\n  }\n  { iFrame.\n    iExists _.\n    iFrame.\n    replace (int.nat 0) with 0%nat; last word.\n    rewrite take_0.\n    auto.\n  }\n  iIntros \"[Hloop HsidRef]\".\n  iNamed \"Hloop\".\n  wp_pures.\n\n  (***********************************************************)\n  (* return min                                              *)\n  (***********************************************************)\n  wp_load.\n  by iApply \"HΦ\".\nQed.\n\nEnd program.\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/txnmgr_get_min_active_tid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.26129275772420435}}
{"text": "\nRequire Import Coqlib Maps String.\nRequire Import AST Integers Values Events Memory Globalenvs Smallstep.\nRequire Import Op Registers.\n\nLocal Open Scope string_scope.\nLocal Open Scope list_scope.\nLocal Open Scope error_monad_scope.\n\nInductive type: Type :=\n    | Uint8   : type\n    | Uint16  : type\n    | Uint32  : type\n    | Uint64  : type\n    | Int8    : type\n    | Int16   : type\n    | Int32   : type\n    | Int64   : type\n    | Float32 : type\n    | Float64 : type\n    | Bool    : type.\n\nDefinition alltypes : list type :=\n    Uint8 :: Uint16 :: Uint32 :: Uint64 :: Int8 :: Int16 :: Int32 :: Int64 :: Float32 :: Float64 :: Bool :: nil.\n\nDefinition type_size (ty: type) : Z :=\n    match ty with\n    | Uint8   => 1\n    | Uint16  => 2\n    | Uint32  => 4\n    | Uint64  => 8\n    | Int8    => 1\n    | Int16   => 2\n    | Int32   => 4\n    | Int64   => 8\n    | Float32 => 4\n    | Float64 => 8\n    | Bool    => 1 (*Since compcert C treats bools as 8-bit ints *)\n    end.\n\nDefinition type_to_string (t: type) : string :=\n    match t with\n    | Uint8   => \"uint8\"\n    | Uint16  => \"uint16\"\n    | Uint32  => \"uint32\"\n    | Uint64  => \"uint64\"\n    | Int8    => \"int8\"\n    | Int16   => \"int16\"\n    | Int32   => \"int32\"\n    | Int64   => \"int64\"\n    | Float32 => \"float32\"\n    | Float64 => \"float64\"\n    | Bool    => \"bool\"\n    end.\n\nDefinition string_to_type (s: string) : option type :=\n    match s with\n    | \"uint8\"   => Some Uint8\n    | \"uint16\"  => Some Uint16\n    | \"uint32\"  => Some Uint32\n    | \"uint64\"  => Some Uint64\n    | \"int8\"    => Some Int8\n    | \"int16\"   => Some Int16\n    | \"int32\"   => Some Int32\n    | \"int64\"   => Some Int64\n    | \"float32\" => Some Float32\n    | \"float64\" => Some Float64\n    | \"bool\"    => Some Bool\n    | _         => None\n    end.\n\nDefinition index: Type := N.\n\nDefinition val: Type := init_data.\n\nInductive location_val: Type :=\n  | Imm      : (val + ident) -> location_val\n  | Reg      : index -> location_val\n  | Stack    : index -> location_val.\n\nDefinition offset: Type := location_val.\n\nInductive location_ref: Type :=\n  | Ref      : index -> location_ref\n  | Cref     : index -> location_ref\n  | Mem      : location_val -> location_ref.\n\nInductive location_mov : Type :=\n  | MV : location_val -> location_mov\n  | MR : location_ref -> offset -> location_mov.\n  \nInductive location : Type :=\n  | LV : location_val -> location\n  | LR : location_ref -> location.\n\nDefinition nbytes: Type := location_val.\n\nInductive instruction: Type :=\n\n  (* Common instructions *)\n  | Ipush         : location_val -> instruction\n  | Ipushref      : location -> instruction\n  | Ipushrefpart  : location -> offset -> nbytes -> instruction\n  | Ipushcref     : location -> instruction\n  | Ipushcrefpart : location -> offset -> nbytes -> instruction\n  | Imov          : location_mov -> location_mov -> option nbytes -> instruction\n  | Icall         : location_val -> option location_val -> instruction\n  | Isyscall      : location_val -> option location_val -> instruction\n  | Ialloc        : location_val -> nbytes -> instruction\n  | Ifree         : location_val -> instruction\n  | Igetmemsize   : location_val -> location_val -> instruction\n  | Iresizestack  : val -> instruction\n  | Ilabel        : ident -> instruction\n  | Ireturn       : location_val -> instruction\n  | Ihalt         : location_val -> instruction\n  | Iuser_except  : instruction\n  | Iconvert      : type -> location_val -> type -> location_val -> instruction\n  \n  (* Unary arithmetic operations *)\n  | Iudec         : type -> location_val -> instruction  (* d := d - 1 *)\n  | Iuinc         : type -> location_val -> instruction  (* d := d + 1 *)\n  \n  (* Binary arithmetic operations *)\n  | Ibadd         : type -> location_val -> location_val -> instruction  (* d := d + s *)\n  | Ibsub         : type -> location_val -> location_val -> instruction  (* d := d - s *)\n  \n  (* Terniary arithmetic operations *)\n  | Itadd         : type -> location_val -> location_val -> location_val -> instruction  (* d := s1 + s2 *)\n  | Itsub         : type -> location_val -> location_val -> location_val -> instruction  (* d := s1 - s2 *)\n  | Itmul         : type -> location_val -> location_val -> location_val -> instruction  (* d := s1 * s2 *)\n  \n  (* Jump operations *)\n  | Ijmp          : location_val -> instruction\n  | Ijz           : location_val -> type -> location_val -> instruction\n  | Ijnz          : location_val -> type -> location_val -> instruction\n  | Idnjz         : location_val -> type -> location_val -> instruction\n  | Idnjnz        : location_val -> type -> location_val -> instruction\n  | Ijeq          : location_val -> type -> location_val -> location_val -> instruction\n  | Ijne          : location_val -> type -> location_val -> location_val -> instruction\n  | Ijge          : location_val -> type -> location_val -> location_val -> instruction\n  | Ijgt          : location_val -> type -> location_val -> location_val -> instruction\n  | Ijle          : location_val -> type -> location_val -> location_val -> instruction\n  | Ijlt          : location_val -> type -> location_val -> location_val -> instruction\n  \n  (* Logical operations *)\n  | Iteq          : type -> location_val -> location_val -> location_val -> instruction\n  | Itne          : type -> location_val -> location_val -> location_val -> instruction\n  | Itge          : type -> location_val -> location_val -> location_val -> instruction\n  | Itgt          : type -> location_val -> location_val -> location_val -> instruction\n  | Itle          : type -> location_val -> location_val -> location_val -> instruction\n  | Itlt          : type -> location_val -> location_val -> location_val -> instruction\n  \n  (* Ternary bitwise operations *)\n  | Ibtand        : type -> location_val -> location_val -> location_val -> instruction\n  | Itshr0        : type -> location_val -> location_val -> location_val -> instruction\n  .\n  \nDefinition comparison: Type := location_val -> type -> location_val -> location_val -> instruction.\nDefinition comparison_bool: Type := type -> location_val -> location_val -> location_val -> instruction.\n\nDefinition code: Type := list instruction.\n\nDefinition private_domain : Type := string.\nDefinition external_function : Type := string.\n\n(* a block starts with a label and has only relative jumps or jumps to other blocks. It returns at the end *)\nDefinition block: Type := (ident * code).\n\nDefinition blocks: Type := PTree.t code.\n\nInductive sharemind_data: Type :=\n    | Data_string : string -> sharemind_data\n    | Data_uint8 : int -> sharemind_data\n    .\n\nRecord program (E: Type) : Type := mkprogram {\n  prog_pds: PTree.t private_domain;\n  prog_rodata: PTree.t sharemind_data;\n  prog_exts: PTree.t E;\n  prog_init: code;\n  prog_code: blocks\n}.\n\nDefinition noprogram (E: Type) : (program E) := mkprogram E\n    (PTree.empty private_domain)\n    (PTree.empty sharemind_data)\n    (PTree.empty E)\n    nil\n    (PTree.empty code).\n\n\n", "meta": {"author": "hpacheco", "repo": "SMPCompCert", "sha": "d629053e1768fec2cc9dc104be5f4288dafdacd1", "save_path": "github-repos/coq/hpacheco-SMPCompCert", "path": "github-repos/coq/hpacheco-SMPCompCert/SMPCompCert-d629053e1768fec2cc9dc104be5f4288dafdacd1/backend/Sharemind.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044135, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.26129275772420435}}
{"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 Coqlib.\nRequire Import AST Integers.\nRequire Import Op 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_32 (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) =>\n          match offset_addressing a n with Some a' => Some (a', ys) | None => None end\n      | _ => None\n      end\n  | _, _ => None\n  end.\n\nFunction combine_addr_64 (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 (Oleal a) ys) =>\n          match offset_addressing a n with Some a' => Some (a', ys) | None => None end\n      | _ => None\n      end\n  | _, _ => None\n  end.\n\nDefinition combine_addr (addr: addressing) (args: list valnum) : option(addressing * list valnum) :=\n  if Archi.ptr64 then combine_addr_64 addr args else combine_addr_32 addr args.\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_32 addr args with\n      | Some(addr', args') => Some(Olea addr', args')\n      | None => None\n      end\n  | Oleal addr, _ =>\n      match combine_addr_64 addr args with\n      | Some(addr', args') => Some(Oleal 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  | Oandlimm n, x :: nil =>\n      match get x with\n      | Some(Op (Oandlimm m) ys) => Some(Oandlimm (Int64.and m n), ys)\n      | _ => None\n      end\n  | Oorlimm n, x :: nil =>\n      match get x with\n      | Some(Op (Oorlimm m) ys) => Some(Oorlimm (Int64.or m n), ys)\n      | _ => None\n      end\n  | Oxorlimm n, x :: nil =>\n      match get x with\n      | Some(Op (Oxorlimm m) ys) => Some(Oxorlimm (Int64.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": "AbsInt", "repo": "CompCert", "sha": "f4ddce910894bf6dbdf83c0642c4b275854b60dd", "save_path": "github-repos/coq/AbsInt-CompCert", "path": "github-repos/coq/AbsInt-CompCert/CompCert-f4ddce910894bf6dbdf83c0642c4b275854b60dd/x86/CombineOp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.26129275195821705}}
{"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_Ф_onFailToRecoverStake (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\nOpaque DePoolContract_Ф_startRoundCompleting.\n\nLemma DePoolContract_Ф_onFailToRecoverStake_exec : forall ( Л_queryId : XInteger64 ) \n                                                          ( Л_elector : XAddress ) \n                                                           (l: Ledger) , \n\nlet optRound := eval_state ( ↓ ( RoundsBase_Ф_fetchRound Л_queryId ) ) l in\nlet req1 : bool := isSome optRound in\nlet round := maybeGet optRound in\nlet req2 : bool := eval_state msg_sender  l  =?  round ->> RoundsBase_ι_Round_ι_proxy  in\nlet req3 : bool :=  Л_elector =? ( round ->> RoundsBase_ι_Round_ι_elector ) in\nlet la :=  exec_state (↓ tvm_accept) l in  \nlet if1 : bool := ( eqb ( round ->> RoundsBase_ι_Round_ι_step ) RoundsBase_ι_RoundStepP_ι_WaitingIfValidatorWinElections ) in\nlet if2 : bool := ( eqb ( round ->> RoundsBase_ι_Round_ι_step ) RoundsBase_ι_RoundStepP_ι_WaitingReward ) in\nlet (round', l') := if if1 then ({$ round with ( RoundsBase_ι_Round_ι_step , RoundsBase_ι_RoundStepP_ι_WaitingUnfreeze ) $}, la)\n                    else if if2  then \n  run ( ↓ ( DePoolContract_Ф_startRoundCompleting round RoundsBase_ι_CompletionReasonP_ι_ValidatorIsPunished ) ) la \n               else (round, injEmbed (VMState_ι_savedDePoolContracts (Ledger_ι_VMState l)) la) in\n\nexec_state ( ↓ DePoolContract_Ф_onFailToRecoverStake Л_queryId Л_elector ) l =\nif req1 then \n        if req2 then \n                if req3 then                \nif if1 then exec_state ( ↓ ( RoundsBase_Ф_setRound Л_queryId round' ) ) l' \n       else if if2 then exec_state ( ↓ ( RoundsBase_Ф_setRound Л_queryId round' ) ) l' \n               else l'\n               else l else l else l.\nProof.\n        intros.\n        destructLedger l. \n        compute.\n      \n        Time repeat destructIf_solve. idtac.\n      \n        all: try destructFunction2 DePoolContract_Ф_startRoundCompleting; auto. \n\nQed.\n\n\nLemma DePoolContract_Ф_onFailToRecoverStake_eval : forall ( Л_queryId : XInteger64 ) \n                                                          ( Л_elector : XAddress ) \n                                                           (l: Ledger) , \nlet optRound := eval_state ( ↓ ( RoundsBase_Ф_fetchRound Л_queryId ) ) l in\nlet req1 : bool := isSome optRound in\nlet round := maybeGet optRound in\nlet req2 : bool := eval_state msg_sender  l  =?  round ->> RoundsBase_ι_Round_ι_proxy  in\nlet req3 : bool :=  Л_elector =? ( round ->> RoundsBase_ι_Round_ι_elector ) in\nlet la :=  exec_state (↓ tvm_accept) l in                 \nlet if1 : bool := ( eqb ( round ->> RoundsBase_ι_Round_ι_step ) RoundsBase_ι_RoundStepP_ι_WaitingIfValidatorWinElections ) in        \nlet if2 : bool := ( eqb ( round ->> RoundsBase_ι_Round_ι_step ) RoundsBase_ι_RoundStepP_ι_WaitingReward ) in\n\neval_state ( ↓ DePoolContract_Ф_onFailToRecoverStake Л_queryId Л_elector ) l =\nif req1 then \n        if req2 then \n                if req3 then                \nif if1 then Value I \n       else if if2 then Value I \n               else Error InternalErrors_ι_ERROR521\n                        else Error Errors_ι_IS_NOT_ELECTOR \n                else Error Errors_ι_IS_NOT_PROXY \n        else Error InternalErrors_ι_ERROR513 .\nProof.\n\n        intros.\n        destructLedger l. \n        compute.\n      \n        Time repeat destructIf_solve. idtac.\n      \n        all: try destructFunction2 DePoolContract_Ф_startRoundCompleting; auto. \n\nQed.\n\nEnd DePoolContract_Ф_onFailToRecoverStake.\n\n ", "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_onFailToRecoverStake.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.26128021822684455}}
{"text": "From stdpp Require Import numbers countable.\nFrom Formalisation Require Import Span SizeNat Inject IsFresh ZeroCopy.\nFrom Classes Require Import Foldable.\nRequire Import Vector.\nFrom Equations Require Import Equations.\nImport disjoint.\n\nDefinition Bit := bool.\n\nClass ValuesFormat (X : Type) :=\n  mk_values {\n      size : nat;\n      encode : X -> Vector.t Bit size;\n      decode : Vector.t Bit size -> option X;\n      spec : forall (x : X), decode (encode x) = Some x; }.\n\nLocal Instance ValuesBool : ValuesFormat bool.\nrefine (mk_values bool 1\n          (fun b => cons b nil)\n          (fun v => match v with\n                 | cons b _ => Some b\n                 | _ => None\n                 end) _).\nintros. reflexivity.\nDefined.\n\nClass Etiquette `{Countable etiquette} :=\n  mk_etiquette {\n      set_etiquette : gset etiquette;\n      set_etiquette_spec: forall (e : etiquette), e ∈ set_etiquette; }.\n\nInductive Result :=\n| Value : forall `{ValuesFormat X}, X -> Result\n| Span : span -> Result\n| Struct : forall `{Etiquette etiquette}, (etiquette -> Result) -> Result.\n\nArguments Value [X _].\nArguments Struct [etiquette _ _ _].\n\nDefinition list_etiquette {X} `{Etiquette X} := elements set_etiquette.\n\nFixpoint Result_to_list (t: Result) : list span :=\n  match t with\n  | Value _ => []\n  | Span s => [s]\n  | Struct st =>\n      list.foldr (fun eti r => Result_to_list (st eti) ++ r) [] list_etiquette\n  end.\n\nDefinition Decodeur := span -> option Result.\n\nOpen Scope N_scope.\n\nFixpoint ResultWeakZC (s : span) (r : Result) : Prop :=\n  match r with\n  | Value _ => True\n  | Span v => scope_in v s\n  | Struct ft => forall e, ResultWeakZC s (ft e)\n  end.\n\nDefinition DecodeurWeakZC (d: Decodeur) :=\n  forall s ft,\n    d s = Some ft ->\n    ResultWeakZC s ft.\n\nFixpoint ResultZC (s : span) (r : Result) : Prop :=\n  match r with\n  | Value _ => False\n  | Span v => scope_in v s\n  | Struct ft => forall e, ResultZC s (ft e)\n  end.\n\nDefinition DecodeurZC (d : Decodeur) :=\n  forall s ft,\n    d s = Some ft ->\n    ResultZC s ft.\n\n(** Version tous les spans de la structures sont disjointes deux à deux **)\n\nDefinition Result_safe (r : Result) : Prop :=\n  forall s t, s <> t -> s ∈ Result_to_list r -> t ∈ Result_to_list r -> disjoint s t.\n\n(** Version SL **)\n\nDefinition Result_safeSL (r : Result) : iProp :=\n  [∗ list] v ∈ Result_to_list r, IsFresh v.\n\nTheorem safe_bridge : forall (r : Result), Result_safeSL r ⊢ ⌜ Result_safe r ⌝.\nProof.\n  unfold Result_safe. induction r; simpl; intros.\n  - iIntros \"HA\". iPureIntro. intros s t NEQ F. inversion F.\n  - iIntros \"HA\". iPureIntro. intros t0 t1 NEQ INt0 INt1.\n    eapply elem_of_list_singleton in INt0. eapply elem_of_list_singleton in INt1.\n    subst. contradiction.\n  - iIntros \"HA\" (s t NEQ INs INt).\n    unfold Result_safeSL. simpl.\n    eapply elem_of_list_lookup_1 in INs as [Is Ps].\n    eapply elem_of_list_lookup_1 in INt as [It Pt].\n    iDestruct (big_sepL_delete with \"HA\") as \"[Hs HA]\". eapply Ps.\n    iDestruct (big_sepL_delete with \"HA\") as \"[Ht HA]\". eapply Pt.\n    destruct (decide (It = Is)).\n    + subst. rewrite Ps in Pt. injection Pt. intro. contradiction.\n    + iClear \"HA\". iApply (IsFresh_spec with \"Hs Ht\").\nQed.\n\nDefinition DecodeurZC_safe (d : Decodeur) :=\n  forall s ft, d s = Some ft -> Result_safe ft.\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/ZeroCopy/ZC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.48828339529583475, "lm_q1q2_score": 0.2612796775472678}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.progs.append.\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; 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 sh contents p,\n   sepalg.nonidentity sh ->\n   listrep sh contents p |-- valid_pointer p.\nProof.\n destruct contents; unfold listrep; fold listrep; intros; normalize.\n auto with valid_pointer.\n apply sepcon_valid_pointer1.\n apply data_at_valid_ptr; auto. simpl;  computable.\nQed.\n\nHint 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.\nnormalize.\napply pred_ext.\nIntros y. entailer. destruct H; contradiction.\nIntros.\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 [ _x OF (tptr t_struct_list) , _y OF (tptr t_struct_list)]\n     PROP(writable_share sh)\n     LOCAL (temp _x x; temp _y y)\n     SEP (listrep sh s1 x; listrep sh s2 y)\n  POST [ tptr t_struct_list ]\n    EX r: val,\n     PROP()\n     LOCAL(temp ret_temp 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. normalize.\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 normalize.\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. normalize.\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; auto.\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. normalize.\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. normalize. 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\nHint 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; normalize;\n auto with valid_pointer.\nQed.\n\nHint 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.\nnormalize.\napply pred_ext.\nIntros y. entailer.\nIntros.\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": "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_append2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2612796775472678}}
{"text": "From iris.bi Require Import big_op fixpoint.\nFrom iris.proofmode Require Import tactics.\nFrom iris.algebra Require Import gmap auth agree gset coPset list.\nFrom iris.program_logic Require Export total_weakestpre adequacy.\nFrom iris Require Import options.\nImport uPred.\n\nSection adequacy.\nContext `{!irisG Λ Σ}.\nImplicit Types e : expr Λ.\n\nDefinition twptp_pre (twptp : list (expr Λ) → iProp Σ)\n    (t1 : list (expr Λ)) : iProp Σ :=\n  (∀ t2 σ1 κ κs σ2 n, ⌜step (t1,σ1) κ (t2,σ2)⌝ -∗\n    state_interp σ1 κs n ={⊤}=∗ ∃ n', ⌜κ = []⌝ ∗ state_interp σ2 κs n' ∗ twptp t2)%I.\n\nLemma twptp_pre_mono (twptp1 twptp2 : list (expr Λ) → iProp Σ) :\n  ⊢ <pers> (∀ 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 κ κs σ2 n1) \"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 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_strong_ind _ Ψ with \"[] H\").\n  iIntros \"!>\" (t') \"H\". by iApply \"IH\".\nQed.\n\nInstance 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 κ κs σ2 n 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 κ κs σ2 n 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 with (t1:=[]). }\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. iIntros (t1' σ1' κ κs σ2' n 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 + n). 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 κ κs σ2 n1 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 n σ t :\n  state_interp σ [] n -∗ twptp t ={⊤}=∗ ▷ ⌜sn erased_step (t, σ)⌝.\nProof.\n  iIntros \"Hσ Ht\". iRevert (σ n) \"Hσ\". iRevert (t) \"Ht\".\n  iApply twptp_ind; iIntros \"!>\" (t) \"IH\"; iIntros (σ n) \"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 Σ Λ `{!invPreG Σ} s e σ Φ :\n  (∀ `{Hinv : !invG Σ},\n     ⊢ |={⊤}=> ∃\n         (stateI : state Λ → list (observation Λ) → nat → iProp Σ)\n         (fork_post : val Λ → iProp Σ),\n       let _ : irisG Λ Σ := IrisG _ _ Hinv stateI fork_post in\n       stateI σ [] 0 ∗ WP e @ s; ⊤ [{ Φ }]) →\n  sn erased_step ([e], σ). (* i.e. ([e], σ) is strongly normalizing *)\nProof.\n  intros Hwp. apply (soundness (M:=iResUR Σ) _  1); simpl.\n  apply (fupd_plain_soundness ⊤ ⊤ _)=> Hinv.\n  iMod (Hwp) as (stateI fork_post) \"[Hσ H]\".\n  iApply (@twptp_total _ _ (IrisG _ _ Hinv stateI fork_post) with \"Hσ\").\n  by iApply (@twp_twptp _ _ (IrisG _ _ Hinv stateI fork_post)).\nQed.\n", "meta": {"author": "SkySkimmer", "repo": "iris", "sha": "186d9ece07e210e92be28eb0e1a42f5d5fe6f1b5", "save_path": "github-repos/coq/SkySkimmer-iris", "path": "github-repos/coq/SkySkimmer-iris/iris-186d9ece07e210e92be28eb0e1a42f5d5fe6f1b5/theories/program_logic/total_adequacy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.26123332732715493}}
{"text": "Require Export vsSahlq_instant19.\n\nOpen Scope type_scope.\n\n\n\nLemma hopeful4_REV'_withex'_FULL : forall lP xn phi1 phi2,\n  vsSahlq_ante phi1 = true ->\n  uniform_pos phi2  ->\n  is_in_pred_l (preds_in (ST (mimpl phi1 phi2) (Var xn))) lP = true ->\n  existsT2 (lx : list FOvariable) (atm : SecOrder),\n    (AT atm = true) *\n    ((existsT rel,\n      REL rel = true /\\\n      is_in_pred_l (preds_in (conjSO rel atm)) (preds_in (ST phi1 (Var xn))) = true /\\\nforall W Iv Ip Ir,\n  SOturnst W Iv Ip Ir (replace_pred_l (list_closed_allFO (implSO\n    (conjSO rel atm)\n    (newnew_pre (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn)))  \n      (rem_FOv (FOvars_in (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn)))) (Var xn))\n      (rev_seq (S (max (max_FOv (implSO (conjSO rel atm) (ST phi2 (Var xn)))) xn))\n        (length       (rem_FOv (FOvars_in (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn)))) (Var xn)))))) lx)\n    lP (list_Var (length lP) (Var (new_FOv_pp_pre2 atm)))\n    (vsS_syn_l (FOv_att_P_l (conjSO rel atm) lP) (Var (new_FOv_pp_pre2 atm)))) <->\n  SOturnst W Iv Ip Ir (list_closed_SO (ST (mimpl phi1 phi2) (Var xn)) lP)) +\n\n     (is_in_pred_l (preds_in atm) (preds_in (ST phi1 (Var xn))) = true /\\\nforall W Iv Ip Ir,\n  SOturnst W Iv Ip Ir (replace_pred_l (list_closed_allFO (implSO atm\n    (newnew_pre (instant_cons_empty' atm (ST phi2 (Var xn)))  \n      (rem_FOv (FOvars_in (instant_cons_empty' atm (ST phi2 (Var xn)))) (Var xn))\n      (rev_seq (S (max (max_FOv (implSO atm (ST phi2 (Var xn)))) xn))\n        (length       (rem_FOv (FOvars_in (instant_cons_empty' atm (ST phi2 (Var xn)))) (Var xn)))))) lx)\n    lP (list_Var (length lP) (Var (new_FOv_pp_pre2 atm)))\n    (vsS_syn_l (FOv_att_P_l atm lP) (Var (new_FOv_pp_pre2 atm)))) <->\n  SOturnst W Iv Ip Ir (list_closed_SO (ST (mimpl phi1 phi2) (Var xn)) lP))).\nProof.\n  intros lP xn phi1 phi2 Hvs Hun Hin0.\n  destruct (vsS_preprocessing_Step1_pre_againTRY'_withex' _ _ (Var xn) Hvs Hun)\n    as [lv [atm [HAT [Hex [ [rel [HREL [Hin SOt]]]  | [Hin SOt]  ]]]]].\n    exists lv. exists atm.\n    apply pair. assumption.\n    left. exists rel. apply conj. assumption.\n    apply conj. assumption.\n    intros W Iv Ip Ir.  \nsplit; intros H.\n    apply hopeful3_REV with (alpha := (ST (mimpl phi1 phi2) (Var xn))) in H ;\n      try assumption.\n        apply lem_f3; assumption.\n      apply uni_pos__SO. assumption.\n      apply SOQFree_ST.\n\n      apply att_allFO_x_ST.\n      apply att_exFO_x_ST.\n      apply closed_except_ST.\n      apply x_occ_in_alpha_instant_cons_empty'.\n        apply x_occ_in_alpha_ST.\n\n      assert (is_in_pred_l \n          (preds_in (implSO (conjSO rel atm) (ST phi2 (Var xn)))) \n          (preds_in (implSO (ST phi1 (Var xn)) (ST phi2 (Var xn)))) = true) as HH1.\n        simpl. apply is_in_pred_l_2app.\n        apply Hin. apply is_in_pred_l_refl.\n      apply (is_in_pred_l_trans _ _ _ HH1 Hin0).\n\n      apply ex_P_occ_in_alpha_ST.\n\n        apply hopeful3 with (alpha := (ST (mimpl phi1 phi2) (Var xn)));\n      try assumption.\n      apply uni_pos__SO. assumption.\n      apply SOQFree_ST.\n\n      apply att_allFO_x_ST.\n      apply att_exFO_x_ST.\n      apply closed_except_ST.\n      apply x_occ_in_alpha_instant_cons_empty'.\n        apply x_occ_in_alpha_ST.\n\n      assert (is_in_pred_l \n          (preds_in (implSO (conjSO rel atm) (ST phi2 (Var xn)))) \n          (preds_in (implSO (ST phi1 (Var xn)) (ST phi2 (Var xn)))) = true) as HH1.\n        simpl. apply is_in_pred_l_2app.\n        apply Hin. apply is_in_pred_l_refl.\n      apply (is_in_pred_l_trans _ _ _ HH1 Hin0).\n\n      apply ex_P_occ_in_alpha_ST.\n\n    exists lv. exists atm.\n    apply pair. assumption.\n    right.\n    apply conj. assumption.\n    intros W Iv Ip Ir.\nsplit; intros H.\n    apply hopeful3_REV_atm with (alpha := (ST (mimpl phi1 phi2) (Var xn))) in H;\n      try assumption.\n      apply lem_f3; assumption.\n\n      apply uni_pos__SO. assumption.\n      apply SOQFree_ST.\n\n      apply att_allFO_x_ST.\n      apply att_exFO_x_ST.\n      apply closed_except_ST.\n      apply x_occ_in_alpha_instant_cons_empty'.\n        apply x_occ_in_alpha_ST.\n\n      assert (is_in_pred_l \n          (preds_in (implSO atm (ST phi2 (Var xn)))) \n          (preds_in (implSO (ST phi1 (Var xn)) (ST phi2 (Var xn)))) = true) as HH1.\n        simpl. apply is_in_pred_l_2app.\n        apply Hin. apply is_in_pred_l_refl.\n      apply (is_in_pred_l_trans _ _ _ HH1 Hin0).\n\n      apply ex_P_occ_in_alpha_ST.\n\n    apply hopeful3_atm with (alpha := (ST (mimpl phi1 phi2) (Var xn)));\n      try assumption.\n      apply uni_pos__SO. assumption.\n      apply SOQFree_ST.\n\n      apply att_allFO_x_ST.\n      apply att_exFO_x_ST.\n      apply closed_except_ST.\n      apply x_occ_in_alpha_instant_cons_empty'.\n        apply x_occ_in_alpha_ST.\n\n      assert (is_in_pred_l \n          (preds_in (implSO atm (ST phi2 (Var xn)))) \n          (preds_in (implSO (ST phi1 (Var xn)) (ST phi2 (Var xn)))) = true) as HH1.\n        simpl. apply is_in_pred_l_2app.\n        apply Hin. apply is_in_pred_l_refl.\n      apply (is_in_pred_l_trans _ _ _ HH1 Hin0).\n\n      apply ex_P_occ_in_alpha_ST.\nDefined.\n \n\n\nLemma hopeful4_REV'_withex'_FULL_allFO : forall lP xn phi1 phi2,\n  vsSahlq_ante phi1 = true ->\n  uniform_pos phi2  ->\n  is_in_pred_l (preds_in (ST (mimpl phi1 phi2) (Var xn))) lP = true ->\n  existsT2 lx atm,\n    (AT atm = true) *\n    ((existsT rel,\n      REL rel = true /\\\n      is_in_pred_l (preds_in (conjSO rel atm)) (preds_in (ST phi1 (Var xn))) = true /\\\nforall W Iv Ip Ir,\n  SOturnst W Iv Ip Ir (allFO (Var xn) (replace_pred_l (list_closed_allFO (implSO\n    (conjSO rel atm)\n    (newnew_pre (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn)))  \n      (rem_FOv (FOvars_in (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn)))) (Var xn))\n      (rev_seq (S (max (max_FOv (implSO (conjSO rel atm) (ST phi2 (Var xn)))) xn))\n        (length       (rem_FOv (FOvars_in (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn)))) (Var xn)))))) lx)\n    lP (list_Var (length lP) (Var (new_FOv_pp_pre2 atm)))\n    (vsS_syn_l (FOv_att_P_l (conjSO rel atm) lP) (Var (new_FOv_pp_pre2 atm))))) <->\n  SOturnst W Iv Ip Ir (allFO (Var xn) (list_closed_SO (ST (mimpl phi1 phi2) (Var xn)) lP))) +\n\n     (is_in_pred_l (preds_in atm) (preds_in (ST phi1 (Var xn))) = true /\\\nforall W Iv Ip Ir,\n  SOturnst W Iv Ip Ir (allFO (Var xn) (replace_pred_l (list_closed_allFO (implSO atm\n    (newnew_pre (instant_cons_empty' atm (ST phi2 (Var xn)))  \n      (rem_FOv (FOvars_in (instant_cons_empty' atm (ST phi2 (Var xn)))) (Var xn))\n      (rev_seq (S (max (max_FOv (implSO atm (ST phi2 (Var xn)))) xn))\n        (length       (rem_FOv (FOvars_in (instant_cons_empty' atm (ST phi2 (Var xn)))) (Var xn)))))) lx)\n    lP (list_Var (length lP) (Var (new_FOv_pp_pre2 atm)))\n    (vsS_syn_l (FOv_att_P_l atm lP) (Var (new_FOv_pp_pre2 atm))))) <->\n  SOturnst W Iv Ip Ir (allFO (Var xn) (list_closed_SO (ST (mimpl phi1 phi2) (Var xn)) lP)))).\nProof.\n  intros lP xn phi1 phi2 H1 H2 H3.\n  destruct (hopeful4_REV'_withex'_FULL lP xn phi1 phi2 H1 H2 H3) as [lx [atm [Hat [ [rel [Hrel [Hin SOt]]]| [Hin SOt] ]]]];\n  exists lx; exists atm; apply pair; try assumption; [left | right].\n    exists rel. apply conj. assumption. apply conj. assumption.\n    intros.\n    apply equiv_allFO with (W := W) (Iv := Iv) (Ip := Ip) (Ir := Ir) (x := (Var xn)) in SOt.\n    assumption.\n\n\n    apply conj. assumption. intros.\n    apply equiv_allFO with (W := W) (Iv := Iv) (Ip := Ip) (Ir := Ir) (x := (Var xn)) in SOt.\n    assumption.\nDefined.\n\nLemma hopeful4_REV'_withex'_FULL_allFO_in : forall lP xn phi1 phi2,\n  vsSahlq_ante phi1 = true ->\n  uniform_pos phi2  ->\n  is_in_pred_l (preds_in (ST (mimpl phi1 phi2) (Var xn))) lP = true ->\n  existsT2 lx atm,\n    (AT atm = true) *\n    ((existsT rel,\n      REL rel = true /\\\n      is_in_pred_l (preds_in (conjSO rel atm)) (preds_in (ST phi1 (Var xn))) = true /\\\nforall W Iv Ip Ir,\n  SOturnst W Iv Ip Ir (allFO (Var xn) (replace_pred_l (list_closed_allFO (implSO\n    (conjSO rel atm)\n    (newnew_pre (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn)))  \n      (rem_FOv (FOvars_in (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn)))) (Var xn))\n      (rev_seq (S (max (max_FOv (implSO (conjSO rel atm) (ST phi2 (Var xn)))) xn))\n        (length       (rem_FOv (FOvars_in (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn)))) (Var xn)))))) lx)\n    lP (list_Var (length lP) (Var (new_FOv_pp_pre2 atm)))\n    (vsS_syn_l (FOv_att_P_l (conjSO rel atm) lP) (Var (new_FOv_pp_pre2 atm))))) <->\n  SOturnst W Iv Ip Ir (list_closed_SO (allFO (Var xn) (ST (mimpl phi1 phi2) (Var xn))) lP)) +\n\n     (is_in_pred_l (preds_in atm) (preds_in (ST phi1 (Var xn))) = true /\\\nforall W Iv Ip Ir,\n  SOturnst W Iv Ip Ir (allFO (Var xn) (replace_pred_l (list_closed_allFO (implSO atm\n    (newnew_pre (instant_cons_empty' atm (ST phi2 (Var xn)))  \n      (rem_FOv (FOvars_in (instant_cons_empty' atm (ST phi2 (Var xn)))) (Var xn))\n      (rev_seq (S (max (max_FOv (implSO atm (ST phi2 (Var xn)))) xn))\n        (length       (rem_FOv (FOvars_in (instant_cons_empty' atm (ST phi2 (Var xn)))) (Var xn)))))) lx)\n    lP (list_Var (length lP) (Var (new_FOv_pp_pre2 atm)))\n    (vsS_syn_l (FOv_att_P_l atm lP) (Var (new_FOv_pp_pre2 atm))))) <->\n  SOturnst W Iv Ip Ir (list_closed_SO (allFO (Var xn) (ST (mimpl phi1 phi2) (Var xn))) lP))).\nProof.\n  intros lP xn phi1 phi2 H1 H2 H3.\n  destruct (hopeful4_REV'_withex'_FULL_allFO lP xn phi1 phi2 H1 H2 H3) as [lx [atm [Hat [ [rel [Hrel [Hin SOt]]]| [Hin SOt] ]]]];\n  exists lx; exists atm; apply pair; try assumption; [left | right].\n    exists rel. apply conj. assumption. apply conj. assumption.\n    intros. split; intros HH. apply equiv_list_closed_SO_allFO.\n      apply SOt. assumption.\n\n      apply equiv_list_closed_SO_allFO in HH. apply SOt. assumption.\n\n    apply conj. assumption. intros.\n    split; intros HH. apply equiv_list_closed_SO_allFO.\n      apply SOt. assumption.\n\n      apply equiv_list_closed_SO_allFO in HH. apply SOt. assumption.\nDefined.\n\nLemma vsSahlq_full_SO_pre : forall xn phi1 phi2,\n  vsSahlq_ante phi1 = true ->\n  uniform_pos phi2  ->\n  existsT2 lx atm,\n    (AT atm = true) *\n    ((existsT rel,\n      REL rel = true /\\\n      is_in_pred_l (preds_in (conjSO rel atm)) (preds_in (ST phi1 (Var xn))) = true /\\\nforall W Iv Ip Ir,\n\n  SOturnst W Iv Ip Ir (allFO (Var xn) (replace_pred_l (list_closed_allFO (implSO\n    (conjSO rel atm)\n    (newnew_pre (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn)))  \n      (rem_FOv (FOvars_in (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn)))) (Var xn))\n      (rev_seq (S (max (max_FOv (implSO (conjSO rel atm) (ST phi2 (Var xn)))) xn))\n        (length       (rem_FOv (FOvars_in (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn)))) (Var xn)))))) lx)\n    (preds_in (ST (mimpl phi1 phi2) (Var xn))) (list_Var (length (preds_in (ST (mimpl phi1 phi2) (Var xn)))) (Var (new_FOv_pp_pre2 atm)))\n    (vsS_syn_l (FOv_att_P_l (conjSO rel atm) (preds_in (ST (mimpl phi1 phi2) (Var xn)))) (Var (new_FOv_pp_pre2 atm))))) <->\n  SOturnst W Iv Ip Ir (uni_closed_SO (allFO (Var xn) (ST (mimpl phi1 phi2) (Var xn))))) +\n\n     (is_in_pred_l (preds_in atm) (preds_in (ST phi1 (Var xn))) = true /\\\nforall W Iv Ip Ir,\n\n  SOturnst W Iv Ip Ir (allFO (Var xn) (replace_pred_l (list_closed_allFO (implSO atm\n    (newnew_pre (instant_cons_empty' atm (ST phi2 (Var xn)))  \n      (rem_FOv (FOvars_in (instant_cons_empty' atm (ST phi2 (Var xn)))) (Var xn))\n      (rev_seq (S (max (max_FOv (implSO atm (ST phi2 (Var xn)))) xn))\n        (length       (rem_FOv (FOvars_in (instant_cons_empty' atm (ST phi2 (Var xn)))) (Var xn)))))) lx)\n    (preds_in (ST (mimpl phi1 phi2) (Var xn))) (list_Var (length (preds_in (ST (mimpl phi1 phi2) (Var xn)))) (Var (new_FOv_pp_pre2 atm)))\n    (vsS_syn_l (FOv_att_P_l atm (preds_in (ST (mimpl phi1 phi2) (Var xn)))) (Var (new_FOv_pp_pre2 atm))))) <->\n  SOturnst W Iv Ip Ir (uni_closed_SO (allFO (Var xn) (ST (mimpl phi1 phi2) (Var xn)))))).\nProof.\n  intros xn phi1 phi2 H1 H2. unfold uni_closed_SO in *. unfold uni_closed_SO.\n  apply hopeful4_REV'_withex'_FULL_allFO_in; try assumption.\n  simpl. apply is_in_pred_l_refl.\nDefined.\n\nLemma vsSahlq_full_SO : forall xn phi1 phi2,\n  vsSahlq_ante phi1 = true ->\n  uniform_pos phi2  ->\n  existsT (alpha : SecOrder),\nis_unary_predless alpha = true /\\\nforall W Iv Ip Ir,\n  SOturnst W Iv Ip Ir alpha <->\n  SOturnst W Iv Ip Ir (uni_closed_SO (allFO (Var xn) (ST (mimpl phi1 phi2) (Var xn)))).\nProof.\n  intros xn phi1 phi2 H1 H2.\n  destruct (vsSahlq_full_SO_pre xn phi1 phi2 H1 H2) as  [lx [atm [Hat [[rel [Hrel [Hin SOt]]]| [Hin SOt] ]]]].\n    exists (allFO (Var xn) (replace_pred_l\n           (list_closed_allFO\n              (implSO (conjSO rel atm)\n                 (newnew_pre (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn)))\n                    (rem_FOv\n                       (FOvars_in (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn))))\n                       (Var xn))\n                    (rev_seq\n                       (S (Nat.max (max_FOv (implSO (conjSO rel atm) (ST phi2 (Var xn)))) xn))\n                       (length\n                          (rem_FOv\n                             (FOvars_in\n                                (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn))))\n                             (Var xn)))))) lx) (preds_in (ST (mimpl phi1 phi2) (Var xn)))\n           (list_Var (length (preds_in (ST (mimpl phi1 phi2) (Var xn))))\n              (Var (new_FOv_pp_pre2 atm)))\n           (vsS_syn_l (FOv_att_P_l (conjSO rel atm) (preds_in (ST (mimpl phi1 phi2) (Var xn))))\n              (Var (new_FOv_pp_pre2 atm))))).\n      apply conj.\napply is_un_predless_corresp; assumption.\n\n      apply SOt.\n\n\n    exists (allFO (Var xn) (replace_pred_l\n           (list_closed_allFO\n              (implSO atm\n                 (newnew_pre (instant_cons_empty' atm (ST phi2 (Var xn)))\n                    (rem_FOv (FOvars_in (instant_cons_empty' atm (ST phi2 (Var xn)))) (Var xn))\n                    (rev_seq (S (Nat.max (max_FOv (implSO atm (ST phi2 (Var xn)))) xn))\n                       (length\n                          (rem_FOv (FOvars_in (instant_cons_empty' atm (ST phi2 (Var xn))))\n                             (Var xn)))))) lx) (preds_in (ST (mimpl phi1 phi2) (Var xn)))\n           (list_Var (length (preds_in (ST (mimpl phi1 phi2) (Var xn))))\n              (Var (new_FOv_pp_pre2 atm)))\n           (vsS_syn_l (FOv_att_P_l atm (preds_in (ST (mimpl phi1 phi2) (Var xn))))\n              (Var (new_FOv_pp_pre2 atm))))).\n      apply conj.\napply is_un_predless_corresp_atm; assumption.\n      apply SOt.\nDefined.\n\n\n\nTheorem vsSahlq_full_Modal_sep : forall phi1 phi2,\n  vsSahlq_ante phi1 = true ->\n  uniform_pos phi2  ->\n  existsT (alpha : SecOrder),\nis_unary_predless alpha = true /\\\nforall W Iv Ip Ir,\n  SOturnst W Iv Ip Ir alpha <->\n  mturnst_frame W Ir (mimpl phi1 phi2).\nProof.\n  intros phi1 phi2 H1 H2.\n  destruct (vsSahlq_full_SO 0 phi1 phi2 H1 H2) as [alpha [Hun SOt]].\n  exists alpha. apply conj. assumption.\n  intros. split; intros HH.\n    apply (correctness_ST _ _ (Var 0) Iv Ip).\n    apply SOt. assumption.\n\n    apply SOt.\n    apply (correctness_ST _ _ (Var 0) Iv Ip).\n    assumption.\nDefined.\n\nTheorem vsSahlq_full_Modal : forall phi,\n  vsSahlq phi ->\n  existsT (alpha : SecOrder),\nis_unary_predless alpha = true /\\\nforall W Iv Ip Ir,\n  SOturnst W Iv Ip Ir alpha <->\n  mturnst_frame W Ir phi.\nProof.\n  intros phi H. destruct phi; try contradiction.\n  simpl in H. case_eq (vsSahlq_ante phi1); intros Hs;\n    rewrite Hs in *. 2 : contradiction.\n  apply vsSahlq_full_Modal_sep; assumption.\nDefined.\n\n\n(* Print All Dependencies vsSahlq_full_Modal. *)", "meta": {"author": "caitlindabrera", "repo": "Sahlqvist", "sha": "d0a755fb663a6cabc0babb691564cdf575fc8b36", "save_path": "github-repos/coq/caitlindabrera-Sahlqvist", "path": "github-repos/coq/caitlindabrera-Sahlqvist/Sahlqvist-d0a755fb663a6cabc0babb691564cdf575fc8b36/vsSahlq_AiML/Coq code/vsSahlq_instant20.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.26113245336667057}}
{"text": "Require Import Rel.Definitions.\nRequire Import Rel.BasicFacts.\nRequire Import Rel.Monotone.\nRequire Import Util.Postfix.\nRequire Import Lang.BindingsFacts.\nSet Implicit Arguments.\n\nLtac bind_let :=\n  match goal with\n  | [ |- ?n ⊨ 𝓣⟦ ?Ξ ⊢ ?T # ?E ⟧ _ _ _ _ _ _ _ _\n              (tm_let ?t₁ ?s₁) (tm_let ?t₂ ?s₂) ] =>\n    replace (tm_let t₁ s₁)\n    with (ktx_plug (ktx_let ktx_hole s₁) t₁) by reflexivity ;\n    replace (tm_let t₂ s₂)\n    with (ktx_plug (ktx_let ktx_hole s₂) t₂) by reflexivity\n  end.\n\nSection section_ccompat_tm_app_let.\n\nContext (EV LV : Set).\nContext (Ξ : XEnv EV LV).\nContext (δ₁ δ₂ : EV → eff0) (δ : EV → IRel 𝓤_Sig).\nContext (ρ₁ ρ₂ : LV → lbl0) (ρ : LV → IRel 𝓣_Sig).\nContext (S T : ty ∅ EV LV ∅) (E : eff ∅ EV LV ∅).\n\nLemma ccompat_tm_let n ξ₁ ξ₂ s₁ s₂ t₁ t₂ :\n  n ⊨ 𝓣⟦ Ξ ⊢ S # E ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ s₁ s₂ → (\n  n ⊨ ∀ᵢ ξ₁' ξ₂' (_ : postfix ξ₁ ξ₁') (_ : postfix ξ₂ ξ₂'),\n      ∀ᵢ v₁ v₂,\n      𝓥⟦ Ξ ⊢ S ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁' ξ₂' v₁ v₂ ⇒\n      𝓣⟦ Ξ ⊢ T # E ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁' ξ₂' (V_subst_tm v₁ t₁) (V_subst_tm v₂ t₂)\n  ) →\n  n ⊨ 𝓣⟦ Ξ ⊢ T # E ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ (tm_let s₁ t₁) (tm_let s₂ t₂).\nProof.\nintros Hs Ht.\nbind_let.\neapply plug0 with (ξ₁ := ξ₁) (ξ₂ := ξ₂) ;\n  [crush|crush| |apply postfix_refl|apply postfix_refl|exact Hs].\niintro ξ₁' ; iintro ξ₂' ; iintro Hξ₁' ; iintro Hξ₂' ;\niintro v₁ ; iintro v₂ ; iintro Hv.\nsimpl ktx_plug.\neapply 𝓣_step_r ; [ apply step_let | ].\neapply 𝓣_step_l ; [ apply step_let | ].\niintro_later.\n\nielim_vars Ht ; [ | eassumption | eassumption ].\niespecialize Ht ; ispecialize Ht ; [ eassumption | ].\napply Ht.\nQed.\n\nEnd section_ccompat_tm_app_let.\n\nSection section_compat_tm_let.\n\nContext (EV LV V : Set).\nContext (Ξ : XEnv EV LV).\nContext (Γ : V → ty ∅ EV LV ∅).\nContext (S T : ty ∅ EV LV ∅).\nContext (E : eff ∅ EV LV ∅).\n\nHint Resolve postfix_trans postfix_refl.\n\nLemma compat_ktx_let n T' E' K₁ K₂ t₁ t₂ :\n  n ⊨ ⟦ Ξ Γ ⊢ K₁ ≼ˡᵒᵍ K₂ : T' # E' ⇢ S # E ⟧ →\n  n ⊨ ⟦ Ξ (env_ext Γ S) ⊢ t₁ ≼ˡᵒᵍ t₂ : T # E ⟧ →\n  n ⊨ ⟦ Ξ Γ ⊢ (ktx_let K₁ t₁) ≼ˡᵒᵍ (ktx_let K₂ t₂) : T' # E' ⇢ T # E ⟧.\nProof.\nintros HK Ht.\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 r₁ ; iintro r₂ ; iintro Hr.\n\niespecialize HK.\nispecialize HK ; [ eassumption | ].\nispecialize HK ; [ eassumption | ].\nispecialize HK ; [ eassumption | ].\nispecialize HK ; [ eassumption | ].\nielim_vars HK ; [ | eassumption | eassumption ].\niespecialize HK ; ispecialize HK ; [ apply Hr | ].\n\nsimpl ktx_plug.\neapply ccompat_tm_let ; [ apply HK | ].\niintro ξ₁'' ; iintro ξ₂'' ; iintro Hξ₁'' ; iintro Hξ₂'' ;\niintro v₁ ; iintro v₂ ; iintro Hv.\nispecialize Ht ξ₁'' ; ispecialize Ht ξ₂'' ;\nispecialize Ht δ₁ ; ispecialize Ht δ₂ ; ispecialize Ht δ ;\nispecialize Ht ρ₁ ; ispecialize Ht ρ₂ ; ispecialize Ht ρ.\nispecialize Ht (env_ext γ₁ v₁) ; ispecialize Ht (env_ext γ₂ v₂).\niespecialize Ht.\nispecialize Ht.\n{ iintro_prop ; eapply 𝜩_monotone ; eauto. }\nispecialize Ht.\n{ eapply δ_is_closed_monotone ; eauto. }\nispecialize Ht.\n{ iintro_prop ; eapply ρ₁ρ₂_are_closed_monotone ; eauto. }\nispecialize Ht.\n{ iintro x ; destruct x ; simpl ; [ assumption | ].\n  iespecialize Hγ ; eapply 𝓥_monotone ; [ | | apply Hγ ] ; eauto.\n}\nrepeat erewrite V_bind_bind_tm ; try apply Ht.\n{ intro x ; destruct x ; simpl ; [ reflexivity | ].\n  erewrite V_bind_map_val, V_bind_val_id, V_map_val_id ; reflexivity.\n}\n{ intro x ; destruct x ; simpl ; [ reflexivity | ].\n  erewrite V_bind_map_val, V_bind_val_id, V_map_val_id ; reflexivity.\n}\nQed.\n\nLemma compat_tm_let n t₁ t₂ s₁ s₂ :\nn ⊨ ⟦ Ξ (env_ext Γ S) ⊢ t₁ ≼ˡᵒᵍ t₂ : T # E ⟧ →\nn ⊨ ⟦ Ξ Γ ⊢ s₁ ≼ˡᵒᵍ s₂ : S # E ⟧ →\nn ⊨ ⟦ Ξ Γ ⊢ (tm_let s₁ t₁) ≼ˡᵒᵍ (tm_let s₂ t₂) : T # E ⟧.\nProof.\nintros Ht Hs.\niintro ξ₁ ; iintro ξ₂ ;\niintro δ₁ ; iintro δ₂ ; iintro δ ;\niintro ρ₁ ; iintro ρ₂ ; iintro ρ ;\niintro γ₁ ; iintro γ₂.\niintro Hξ ; iintro Hδ ; iintro Hρ ; iintro Hγ.\n\niespecialize Hs.\nispecialize Hs ; [ eassumption | ].\nispecialize Hs ; [ eassumption | ].\nispecialize Hs ; [ eassumption | ].\nispecialize Hs ; [ eassumption | ].\nsimpl subst_tm.\neapply ccompat_tm_let ; [ apply Hs | ].\n\niintro ξ₁' ; iintro ξ₂' ; iintro Hξ₁' ; iintro Hξ₂' ;\niintro v₁ ; iintro v₂ ; iintro Hv.\nispecialize Ht ξ₁' ; ispecialize Ht ξ₂' ;\nispecialize Ht δ₁ ; ispecialize Ht δ₂ ; ispecialize Ht δ ;\nispecialize Ht ρ₁ ; ispecialize Ht ρ₂ ; ispecialize Ht ρ.\nispecialize Ht (env_ext γ₁ v₁) ; ispecialize Ht (env_ext γ₂ v₂).\niespecialize Ht.\nispecialize Ht.\n{ iintro_prop ; eapply 𝜩_monotone ; eauto. }\nispecialize Ht.\n{ eapply δ_is_closed_monotone ; eauto. }\nispecialize Ht.\n{ iintro_prop ; eapply ρ₁ρ₂_are_closed_monotone ; eauto. }\nispecialize Ht.\n{ iintro x ; destruct x ; simpl ; [ assumption | ].\n  iespecialize Hγ ; eapply 𝓥_monotone ; [ | | apply Hγ ] ; eauto.\n}\nrepeat erewrite V_bind_bind_tm ; try apply Ht.\n{ intro x ; destruct x ; simpl ; [ reflexivity | ].\n  erewrite V_bind_map_val, V_bind_val_id, V_map_val_id ; reflexivity.\n}\n{ intro x ; destruct x ; simpl ; [ reflexivity | ].\n  erewrite V_bind_map_val, V_bind_val_id, V_map_val_id ; reflexivity.\n}\n\nQed.\n\nEnd section_compat_tm_let.\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_let.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.26113244708527095}}
{"text": "Require Import bedrock2.NotationsCustomEntry.\n\nImport Syntax Syntax.Coercions BinInt String List List.ListNotations.\nLocal Open Scope string_scope. Local Open Scope Z_scope. Local Open Scope list_scope.\n\nDefinition memswap := func! (x, y, n) {\n  while n {\n    vx = load1(x);\n    vy = load1(y);\n    store1(x, vy);\n    store1(y, vx);\n\n    x = x + $1;\n    y = y + $1;\n    n = n - $1;\n    $(cmd.unset \"vx\");\n    $(cmd.unset \"vy\")\n  }\n}.\n\nRequire Import bedrock2.WeakestPrecondition bedrock2.Semantics bedrock2.ProgramLogic.\nRequire Import coqutil.Word.Interface coqutil.Word.Bitwidth.\nRequire Import coqutil.Map.Interface bedrock2.Map.SeparationLogic.\nRequire Import bedrock2.ZnWords.\nImport Coq.Init.Byte coqutil.Byte.\nLocal Notation string := String.string.\n\n(*Require Import bedrock2.ptsto_bytes.*)\nLocal Notation \"xs $@ a\" := (Array.array ptsto (word.of_Z 1) a xs) (at level 10, format \"xs $@ a\").\nLocal Notation \"m =* P\" := ((P%sep) m) (at level 70, only parsing) (* experiment*).\n\nSection WithParameters.\n  Context {width} {BW: Bitwidth width}.\n  Context {word: word.word width} {mem: map.map word byte} {locals: map.map string word}.\n  Context {ext_spec: ExtSpec}.\n  Import ProgramLogic.Coercions.\n\n  Global Instance spec_of_memswap : spec_of \"memswap\" :=\n    fnspec! \"memswap\" (x y n : word) / (xs ys : list byte) (R : mem -> Prop),\n    { requires t m := m =* xs$@x * ys$@y * R /\\\n                      length xs = n :>Z /\\ length ys = n :>Z;\n      ensures t' m := m =* ys$@x * xs$@y * R /\\ t=t' }.\n\n  Context {word_ok: word.ok word} {mem_ok: map.ok mem} {locals_ok : map.ok locals}\n    {env : map.map string (list string * list string * Syntax.cmd)} {env_ok : map.ok env}\n    {ext_spec_ok : ext_spec.ok ext_spec}.\n\n  Import coqutil.Tactics.letexists coqutil.Tactics.Tactics coqutil.Tactics.autoforward.\n  Import coqutil.Word.Properties coqutil.Map.Properties.\n\n  Local Ltac ZnWords := destruct width_cases; bedrock2.ZnWords.ZnWords.\n  Lemma memswap_ok : program_logic_goal_for_function! memswap.\n  Proof.\n    repeat straightline.\n\n    refine ((Loops.tailrec\n      (HList.polymorphic_list.cons _\n      (HList.polymorphic_list.cons _\n      (HList.polymorphic_list.cons _\n      HList.polymorphic_list.nil)))\n      [\"x\";\"y\";\"n\"])\n      (fun (v:nat) xs ys R t m x y n => PrimitivePair.pair.mk (\n        m =* xs$@x * ys$@y * R /\\ length xs = n :>Z /\\ length ys = n :>Z /\\ v = n :>Z)\n      (fun                 T M (X Y N : word) => t = T /\\ M =* ys$@x * xs$@y * R))\n      lt\n      _ _ _ _ _ _ _ _);\n      (* TODO wrap this into a tactic with the previous refine *)\n      cbn [HList.hlist.foralls HList.tuple.foralls\n           HList.hlist.existss HList.tuple.existss\n           HList.hlist.apply  HList.tuple.apply\n           HList.hlist\n           List.repeat Datatypes.length\n           HList.polymorphic_list.repeat HList.polymorphic_list.length\n           PrimitivePair.pair._1 PrimitivePair.pair._2] in *.\n      { cbv [Loops.enforce]; cbn.\n        subst l.\n        repeat (rewrite ?map.get_put_dec, ?map.get_remove_dec; cbn); split.\n        { exact eq_refl. }\n        { eapply map.map_ext; intros k.\n          repeat (rewrite ?map.get_put_dec, ?map.get_remove_dec, ?map.get_empty; cbn -[String.eqb]).\n          repeat (destruct String.eqb; trivial). } }\n      { eapply Wf_nat.lt_wf. }\n      { cbn; ssplit; try ecancel_assumption; eauto. }\n      { intros ?v ?xs ?ys ?R ?t ?m ?x ?y ?n.\n        repeat straightline.\n        cbn in localsmap.\n        eexists n0; split; cbv [expr expr_body localsmap get].\n        { rewrite ?Properties.map.get_put_dec. exists n0; cbn. auto. }\n        split; cycle 1.\n        { intros Ht; rewrite Ht in *.\n          intuition idtac; destruct xs0, ys0; cbn in *; try discriminate; try ecancel_assumption; eauto. }\n\n        intros Ht.\n        destruct xs0 as [|hxs xs0] in *, ys0 as [|hys ys0] in *;\n          cbn [length Array.array] in *; try (cbn in *; congruence); [];\n\n        repeat straightline.\n        eapply WeakestPreconditionProperties.dexpr_expr.\n\n        repeat straightline.\n        letexists; split.\n        { rewrite ?Properties.map.get_put_dec; exact eq_refl. }\n        repeat straightline.\n\n        eapply WeakestPreconditionProperties.dexpr_expr.\n        letexists; split.\n        { subst l. rewrite ?Properties.map.get_put_dec; cbn. exact eq_refl. }\n        repeat straightline.\n\n        eapply WeakestPreconditionProperties.dexpr_expr.\n        letexists; split.\n        { subst l l0. rewrite ?Properties.map.get_put_dec; exact eq_refl. }\n        repeat straightline.\n\n        repeat straightline.\n        eapply WeakestPreconditionProperties.dexpr_expr.\n        letexists; split.\n        { subst l l0. rewrite ?Properties.map.get_put_dec; cbn. exact eq_refl. }\n\n        repeat straightline.\n        eapply WeakestPreconditionProperties.dexpr_expr.\n        letexists; split.\n        { subst l l0. rewrite ?Properties.map.get_put_dec; cbn. exact eq_refl. }\n\n        repeat straightline.\n        eapply WeakestPreconditionProperties.dexpr_expr.\n        letexists; split.\n        { subst l l0. rewrite ?Properties.map.get_put_dec; cbn. exact eq_refl. }\n\n        repeat straightline.\n        eapply WeakestPreconditionProperties.dexpr_expr.\n        letexists; split.\n        { subst l l0. rewrite ?Properties.map.get_put_dec; cbn. exact eq_refl. }\n\n        repeat straightline.\n        eapply WeakestPreconditionProperties.dexpr_expr.\n        letexists; split.\n        { subst l l0 l1. rewrite ?Properties.map.get_put_dec; cbn. exact eq_refl. }\n\n        repeat straightline.\n        eapply WeakestPreconditionProperties.dexpr_expr.\n        letexists; split.\n        { subst l l0 l1 l2. rewrite ?Properties.map.get_put_dec; cbn. exact eq_refl. }\n\n        eexists _, _, _.\n        split.\n        { cbv [Loops.enforce l l0 l1 l2]; cbn.\n          repeat (rewrite ?map.get_put_dec, ?map.get_remove_dec; cbn); split.\n          { exact eq_refl. }\n          { eapply map.map_ext; intros k.\n            repeat (rewrite ?map.get_put_dec, ?map.get_remove_dec, ?map.get_empty; cbn -[String.eqb]).\n            repeat (destruct String.eqb; trivial). } }\n        eexists _, _, _, (length xs0); split; ssplit; try ecancel_assumption; try ZnWords.\n        split.\n        { cbn in *; ZnWords. }\n        intuition idtac; repeat straightline_cleanup.\n        subst v0 v1 v2 v3.\n        pose proof byte.unsigned_range hxs.\n        pose proof byte.unsigned_range hys.\n        use_sep_assumption.\n        rewrite !word.unsigned_of_Z_nowrap, !byte.of_Z_unsigned by ZnWords.\n        cancel. }\n\n      intuition idtac. cbn. eauto.\n  Qed.\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/memswap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.26113244708527084}}
{"text": "(******************************************************************************)\n(** * Domains of the Power memory model *)\n(******************************************************************************)\n\nRequire Import Classical List Relations Peano_dec Omega.\nRequire Import Hahn.\nRequire Import Basic Power_Events Power_Model.\n\nSet Implicit Arguments.\n\nSection Power_Locations.\n\nVariable G : power_execution.\n\n(* Basic *)\nNotation \"'acts'\" := G.(acts).\nNotation \"'lab'\" := G.(lab).\nNotation \"'sb'\" := G.(sb).\nNotation \"'rf'\" := G.(rf).\nNotation \"'mo'\" := G.(mo).\nNotation \"'rmw'\" := G.(rmw).\nNotation \"'data'\" := G.(data).\nNotation \"'addr'\" := G.(addr).\nNotation \"'ctrl'\" := G.(ctrl).\nNotation \"'ctrl_isync'\" := G.(ctrl_isync).\n(* Events *)\nNotation \"'E'\" := G.(E).\nNotation \"'R'\" := G.(R).\nNotation \"'W'\" := G.(W).\nNotation \"'F_sync'\" := G.(F_sync).\nNotation \"'F_lwsync'\" := G.(F_lwsync).\nNotation \"'RW'\" := G.(RW).\nNotation \"'_WF'\" := G.(_WF).\nNotation \"'F'\" := G.(F).\n(* Relations *)\nNotation \"'same_loc'\" := G.(same_loc).\nNotation \"'deps'\" := G.(deps).\nNotation \"'rb'\" := G.(rb).\nNotation \"'rdw'\" := G.(rdw).\nNotation \"'detour'\" := G.(detour).\nNotation \"'ii0'\" := G.(ii0).\nNotation \"'ci0'\" := G.(ci0).\nNotation \"'cc0'\" := G.(cc0).\nNotation \"'ii'\" := G.(ii).\nNotation \"'ic'\" := G.(ic).\nNotation \"'ci'\" := G.(ci).\nNotation \"'cc'\" := G.(cc).\nNotation \"'L'\" := G.(L).\nNotation \"'Li'\" := G.(Li).\nNotation \"'ii_alt'\" := G.(ii_alt).\nNotation \"'ic_alt'\" := G.(ic_alt).\nNotation \"'ci_alt'\" := G.(ci_alt).\nNotation \"'cc_alt'\" := G.(cc_alt).\nNotation \"'ppo'\" := G.(ppo).\nNotation \"'sync'\" := G.(sync).\nNotation \"'lwsync'\" := G.(lwsync).\nNotation \"'fence'\" := G.(fence).\nNotation \"'hb'\" := G.(hb).\nNotation \"'prop1'\" := G.(prop1).\nNotation \"'prop2'\" := G.(prop2).\nNotation \"'prop'\" := G.(prop).\nNotation \"'psbloc'\" := G.(psbloc).\nNotation \"'eco'\" := G.(eco).\n(* Well-formed axioms *)\nNotation \"'WfDEPS'\" := G.(WfDEPS).\nNotation \"'WfACTS'\" := G.(WfACTS).\nNotation \"'WfSB'\" := G.(WfSB).\nNotation \"'WfRF'\" := G.(WfRF).\nNotation \"'WfMO'\" := G.(WfMO).\nNotation \"'WfRMW'\" := G.(WfRMW).\nNotation \"'Wf'\" := G.(Wf).\n(* Consistency *)\nNotation \"'PowerConsistent'\" := G.(PowerConsistent).\n(* Notation *)\nNotation \"'restrict_location'\" := G.(restrict_location).\nNotation \"s ⌇ x\" := (restrict_location s x) (at level 1).\nNotation \"rel |loc\" := (rel ∩ same_loc) (at level 1).\nNotation \"a ∙\" := (a ∩ same_thread) (at level 1, format \"a ∙\").\nNotation \"a ∘\" := (a \\ same_thread) (at level 1, format \"a ∘\").\n\nHypothesis WF: Wf.\n\nLemma rf_loc a b (RF: rf a b) : loc lab a = loc lab b.\nProof. by cdes WF; cdes WF_RF; apply RF_LOC. Qed.\n\nLemma mo_loc a b (MO: mo a b) : loc lab a = loc lab b.\nProof. by cdes WF; cdes WF_MO; apply MO_LOC. Qed.\n\nLemma rmw_loc a b (RMW: rmw a b) : loc lab a = loc lab b.\nProof. by cdes WF; cdes WF_RMW; apply RMW_LOC. Qed.\n\nLemma rb_loc a b (RB: rb a b) : loc lab a = loc lab b.\nProof.\n  unfold Power_Model.rb in RB.\n  unfolder in RB. destruct RB as [z [RF MO]].\n  apply rf_loc in RF.\n  apply mo_loc in MO.\n  congruence.\nQed.\n\nHint Resolve rf_loc mo_loc rmw_loc rb_loc : locations.\n\nLemma eco_loc a b (ECO: eco a b) : loc lab a = loc lab b.\nProof.\n  unfold Power_Model.eco in ECO; unfolder in ECO.\n  desf; eauto with locations;\n  (apply mo_loc in ECO + apply rb_loc in ECO);\n  apply rf_loc in ECO0; congruence.\nQed.\n\nLemma Wa_implies_some_loc a (WA: W a) : loc lab a <> None.\nProof.\n  unfold Power_Model.W, is_w in WA.\n  remember (lab a) as l.\n  destruct l; try contradiction.\n  unfold loc.\n  rewrite <- Heql.\n  red; ins.\nQed.\n\nLemma writes_same_loc_implies_mo (CON: PowerConsistent) a b l \n  (WA: (restrict_location W l) a) (WB: (restrict_location W l) b)\n  (ACTA: In a acts) (ACTB: In b acts) (NEQ: a <> b) : \n    mo a b \\/ mo b a.\nProof.\n  cdes WF; cdes WF_MO; clear - WF CON WA WB ACTA ACTB NEQ MO_ACT MO_LOC MO_TOT.\n  assert (l <> None).\n    by unfold Power_Model.restrict_location in *; desf; apply Wa_implies_some_loc.\n  apply not_none_implies_some in H. desc.\n  apply MO_TOT with x; splits; unfold Power_Model.restrict_location in *; desf; eauto.\nQed.\n\nLemma RW_has_loc a : RW a -> loc lab a <> None.\nProof.\n  repeat autounfold with type_unfold; unfold set_union, is_r, is_w.\n  ins; desf; unfold Power_Events.loc; desf.\nQed.\n\nEnd Power_Locations.\n\n(* Export Hints *)\nHint Resolve rf_loc mo_loc rmw_loc rb_loc eco_loc : locations.\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_Locations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2611324408038711}}
{"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 multi_is_zero_u_prg pick_sign_prg copy_s_u_prg multi_lt_prg.\nRequire Import multi_zero_s_prg multi_sub_u_u_prg multi_add_u_u_prg copy_s_s_prg.\n\nLocal Open Scope mips_cmd_scope.\n\n(** z <- x - y with z, x signed and y unsigned *)\nDefinition multi_sub_s_s_u0 rk rz rx ry a0 a1 a2 a3 a4 ret X Z :=\n  lw Z four16 rz ;\n  lw X four16 rx ;\n  pick_sign rx a0 a1 ;\n  If_bgez a1 Then (* 0 <= x ? *)\n    If_beq a1, r0 Then (* x = 0 ? *)\n      copy_s_u rk rz ry a0 a1 a2 a3 ;\n      addiu a3 r0 zero16 ; (* no overflow *)\n      subu a0 r0 rk ;\n      sw a0 zero16 rz\n    Else (* 0 < x *) (* NB: a1 = 1 *)\n      multi_lt rk ry X a0 a1 ret a2 a3 a4 ; \n      If_beq ret, r0 Then (* ry >= X ? *)\n        If_beq a2, r0 Then (* Y = X *)\n          multi_zero_s rz ; (* fix size *)\n          addiu a3 r0 zero16 (* no overflow *)\n        Else (* Y > X *)\n          multi_sub_u_u rk ry X Z a0 a1 a2 a3 a4 ret;\n          subu a0 r0 rk ; \n          sw a0 zero16 rz (* fix size *)\n      Else (* ry < X *)\n        multi_sub_u_u rk X ry Z a0 a1 a2 a3 a4 ret;\n        sw rk zero16 rz (* fix size *)\n  Else (* x < 0 *)\n    addiu a3 r0 one16 ;\n    multi_add_u_u rk a3 X ry Z a0 a1 a2 ;\n    mflo a3 ;\n    subu a0 r0 rk ;\n    sw a0 zero16 rz.\n\nDefinition multi_sub_s_s_u rk rz rx ry a0 a1 a2 a3 a4 ret X Z :=\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    copy_s_s rk rz rx a0 a1 a2 ret a4\n  Else (* y <> 0 *) \n    multi_sub_s_s_u0 rk rz rx ry a0 a1 a2 a3 a4 ret X Z.\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_sub_s_s_u_prg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.26107273786058094}}
{"text": "Require Export DACandMAC. \nSet Implicit Arguments.\nUnset Strict Implicit. \n \nSection Stat. \n \nVariable s : SFSstate. \n \n(*********************************************************************) \n(*                             stat                                  *) \n(*********************************************************************) \n \n(*This operation outputs the UNIX security information stored in the *) \n(*ACL of a given object. Note that in our model the only precondition*) \n(*for this operation is that the user has DAC read                   *) \n(*access to the object and not, as in the standar UNIX, execute      *) \n(*access.                                                            *) \n \n(*This function computes object's mode from the object's ACL by      *) \n(*owner, group and AllGrp in UsersReaders, UsersWriters,             *) \n(*GroupReaders and GroupWriters.                                     *) \n \nParameter comp_mode : AccessCtrlListData -> PERMS. \n \n(*This record stores the security attributes present in a            *) \n(*conventinoal i-node.                                               *) \n \nRecord stat_struct : Set := stat_fields\n  {st_mode : PERMS; st_uid : SUBJECT; st_gid : GRPNAME}. \n \nInductive stat (u : SUBJECT) (o : OBJECT) :\nSFSstate -> Exc stat_struct -> Prop :=\n    StatOK :\n      PreDACRead s u o ->\n      stat u o s\n        match facl (acl s) o with\n        | None => None (A:=stat_struct)\n        | Some y => Some (stat_fields (comp_mode y) (owner y) (group y))\n        end. \n \nEnd Stat.", "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/stat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6654105454764746, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.26106506417200653}}
{"text": "(** * LogRel.AlgorithmicTypingProperties: properties of algorithmic typing. *)\nFrom LogRel.AutoSubst Require Import core unscoped Ast Extra.\nFrom LogRel Require Import Utils BasicAst Notations Context NormalForms Weakening UntypedReduction\n  GenericTyping DeclarativeTyping DeclarativeInstance AlgorithmicTyping DeclarativeSubst TypeConstructorsInj BundledAlgorithmicTyping AlgorithmicConvProperties.\nFrom LogRel Require Import LogicalRelation Validity Fundamental.\nFrom LogRel.LogicalRelation Require Import Escape.\nFrom LogRel.Substitution Require Import Properties Escape.\n\nImport DeclarativeTypingProperties AlgorithmicTypingData BundledTypingData BundledIntermediateData IntermediateTypingProperties.\n\n(** ** Completeness of algorithmic conversion *)\n(** We use the intermediate instance derived in AlgorithmicConvProperties to get this result,\nusing the fundamental lemma. *)\n\nLemma algo_conv_complete Γ A B :\n  [Γ |-[de] A ≅ B] ->\n  [Γ |-[al] A ≅ B].\nProof.\n  now intros [HΓ ? _ []%escapeEq]%Fundamental.\nQed.\n\n(** ** Instance *)\n(** Equipped with this equivalence, we easily derive our third instance. *)\n\nModule AlgorithmicTypingProperties.\n  Export BundledTypingData AlgorithmicConvProperties.\n\n  #[local] Ltac intros_bn :=\n    intros ;\n    repeat match goal with | H : context [bn] |- _ => destruct H end ;\n    econstructor ; try assumption.\n\n  #[export, refine] Instance WfCtxAlgProperties : WfContextProperties (ta := bn) := {}.\n  Proof.\n    1-8: intros_bn.\n    - now do 2 constructor.\n    - constructor ; tea.\n      now apply typing_sound.\n    - now intros ? [].\n  Qed.\n\n  #[export, refine] Instance WfTypeAlgProperties : WfTypeProperties (ta := bn) := {}.\n  Proof.\n    - intros_bn.\n      now eapply algo_typing_wk.\n    - now intros * [? ?%typing_sound]. \n    - intros_bn.\n      now econstructor.\n    - intros_bn.\n      now econstructor.\n    - intros_bn.\n      now econstructor.\n    - intros_bn.\n      now econstructor.\n    - intros_bn.\n      do 2 econstructor ; tea.\n      now apply algo_conv_complete.\n  Qed.\n\n  #[export, refine] Instance TypingAlgProperties : TypingProperties (ta := bn) := {}.\n  Proof.\n    - intros_bn.\n      + now eapply algo_typing_wk.\n      + gen_typing.\n    - intros * [?? ?%typing_sound] ; tea.\n      now econstructor.\n    - intros_bn.\n      + now econstructor.\n      + constructor.\n        now eapply in_ctx_wf.\n    - intros_bn.\n      + do 2 econstructor ; tea.\n        all: now eapply (redty_red (ta := de)), red_ty_compl_univ_r.\n      + now do 2 econstructor.\n    - intros_bn.\n      + now econstructor.\n      + econstructor ; tea.\n        2: econstructor.\n        all: boundary.\n    - intros * [? ? ? (?&?&[])%red_ty_compl_prod_r] [].\n      esplit ; tea.\n      + do 2 econstructor ; tea.\n        1: now eapply (redty_red (ta := de)).\n        eapply algo_conv_complete.\n        now etransitivity.\n      + eapply typing_subst1 ; tea.\n        econstructor.\n        now eapply inf_conv_decl.\n    - intros_bn.\n      1: now econstructor.\n      now do 2 econstructor.\n    - intros_bn.\n      1: now econstructor.\n      now do 2 econstructor.\n    - intros_bn.\n      + do 2 econstructor ; tea.\n        now eapply (redty_red (ta := de)), red_ty_compl_nat_r.\n      + now do 2 econstructor.\n    - intros_bn.\n      1: econstructor ; tea.\n      + econstructor ; tea.\n        now eapply (redty_red (ta := de)), red_ty_compl_nat_r.\n      + econstructor ; tea.\n        now eapply algo_conv_complete.\n      + econstructor ; tea.\n        now eapply algo_conv_complete.\n      + econstructor.\n        eapply typing_subst1.\n        1: eauto using inf_conv_decl.\n        now eapply typing_sound.\n    - intros_bn.\n      1: econstructor.\n      gen_typing.\n    - intros_bn.\n      1: econstructor ; tea.\n      + econstructor ; tea.\n        now eapply (redty_red (ta := de)), red_ty_compl_empty_r.\n      + econstructor.\n        eapply typing_subst1.\n        1: eauto using inf_conv_decl.\n        now eapply typing_sound.\n    - intros_bn.\n      1: eassumption.\n      etransitivity ; tea.\n      symmetry.\n      eapply RedConvTyC, subject_reduction_type ; tea.\n      now eapply typing_sound.\n    - intros_bn.\n      1: eassumption.\n      etransitivity ; tea.\n      now eapply conv_sound in bun_conv_ty.\n  Qed.\n\n  #[export, refine] Instance OneStepRedTermAlgProperties :\n    OneStepRedTermProperties (ta := bn) := {}.\n  Proof.\n    intros_bn.\n    2: econstructor.\n    econstructor ; tea.\n    - econstructor.\n      1: now do 2 econstructor.\n      econstructor ; tea.\n      now eapply algo_conv_complete.\n    - eapply typing_subst1 ; tea.\n      econstructor.\n      now eapply inf_conv_decl.\n    - intros * HP Hz Hs.\n      assert [|-[de] Γ] by (destruct Hz ; boundary).\n      split ; tea.\n      + eapply ty_natElim ; tea.\n        econstructor ; tea.\n        1: econstructor.\n        now do 2 econstructor.\n      + now constructor.\n    - intros * HP Hz Hs [].\n      assert [|-[de] Γ] by (destruct Hz ; boundary).\n      split ; tea.\n      + eapply ty_natElim ; tea.\n        econstructor.\n        * eassumption.\n        * do 2 econstructor ; tea.\n          now eapply (redty_red (ta := de)), red_ty_compl_nat_r.\n        * now do 2 econstructor.\n      + constructor.\n  Qed.\n\n  #[export, refine] Instance RedTermAlgProperties :\n    RedTermProperties (ta := bn) := {}.\n  Proof.\n    - intros_bn.\n      2: now apply credalg_wk.\n      econstructor ; tea.\n      1: now eapply algo_typing_wk.\n      now eapply typing_wk.\n    - intros * [? []].\n      eapply subject_reduction ; tea.\n      now eapply inf_conv_decl.\n    - now intros * [].\n    - intros * [] ; constructor; tea; now econstructor.\n    - intros_bn.\n      + eapply red_ty_compl_prod_r in bun_inf_conv_conv0 as (?&?&[]).\n        econstructor ; tea.\n        1: econstructor.\n        * econstructor ; tea.\n          now eapply (redty_red (ta := de)).\n        * econstructor ; tea.\n          eapply algo_conv_complete.\n          now etransitivity.\n        * eapply typing_subst1 ; tea.\n          econstructor.\n          now eapply inf_conv_decl.  \n      + clear -bun_red_tm.\n        induction bun_red_tm ; econstructor.\n        2: eassumption.\n        now econstructor.\n    - intros * [] [] [] [] [] ?.\n      assert [Γ |-[al] n ▹h tNat].\n      {\n        econstructor ; tea.\n        now eapply (redty_red (ta := de)), red_ty_compl_nat_r.\n      }\n      split ; tea.\n      1: econstructor ; tea.\n      1: econstructor ; tea.\n      + econstructor ; tea.\n        now eapply algo_conv_complete.\n      + econstructor ; tea.\n        now eapply algo_conv_complete.\n      + econstructor.\n        eapply typing_subst1.\n        all: eapply typing_sound ; tea.\n        2: now econstructor.\n        econstructor ; tea.\n        now eapply algo_conv_complete.\n      + clear -bun_red_tm.\n        induction bun_red_tm.\n        1: now constructor.\n        econstructor ; tea.\n        now econstructor. \n    - intros * [] [] [] ?.\n      assert [Γ |-[al] n ▹h tEmpty].\n      {\n        econstructor ; tea.\n        now eapply (redty_red (ta := de)), red_ty_compl_empty_r.\n      }\n      split ; tea.\n      1: econstructor ; tea.\n      1: econstructor ; tea.\n      + econstructor.\n        eapply typing_subst1.\n        all: eapply typing_sound ; tea.\n        2: now econstructor.\n        econstructor ; tea.\n        now eapply algo_conv_complete.\n      + clear -bun_red_tm.\n        induction bun_red_tm.\n        1: now constructor.\n        econstructor ; tea.\n        now econstructor. \n    - intros_bn.\n      eapply conv_sound in bun_conv_ty ; tea.\n      econstructor ; tea.\n      now etransitivity.\n    - intros_bn.\n      all: now econstructor.\n    - red. intros_bn.\n      2: now etransitivity.\n      now econstructor.\n  Qed.\n\n  #[export, refine] Instance RedTypeAlgProperties :\n    RedTypeProperties (ta := bn) := {}.\n  Proof.\n    - intros_bn.\n      1: now apply algo_typing_wk.\n      now apply credalg_wk.\n    - intros * [].\n      eapply subject_reduction_type ; tea.\n      now eapply typing_sound.\n    - now intros_bn.\n    - intros_bn.\n      do 2 econstructor ; tea.\n      now eapply algo_conv_complete.\n    - intros_bn.\n      now econstructor. \n    - red. intros_bn.\n      now etransitivity.\n  Qed.\n\n  Export UntypedValues.WeakValuesProperties.\n\n  #[export] Instance AlgorithmicTypingProperties : GenericTypingProperties bn _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ := {}.\n\nEnd AlgorithmicTypingProperties.\n\nImport AlgorithmicTypingProperties.\n\nCorollary algo_typing_complete Γ A t :\n  [Γ |-[de] t : A] ->\n  [Γ |-[bn] t : A].\nProof.\n  now intros [_ _ ?%escapeTm]%(Fundamental (ta := bn)).\nQed.", "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/AlgorithmicTypingProperties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.26095238094326667}}
{"text": "(** Example from Ernst-Murray CAV 2019, done without locks, proven directly. *)\nFrom iris.base_logic Require Import invariants.\nFrom iris_ni.logrel Require Import types.\nFrom iris_ni.program_logic Require Import dwp heap_lang_lifting.\nFrom iris.proofmode Require Import proofmode.\nFrom iris.heap_lang Require Import lang proofmode.\nFrom iris_ni.proofmode Require Import dwp_tactics.\nFrom iris_ni.logrel Require Import interp.\nFrom iris_ni.examples Require Import lock par various (* for oneshot *).\nFrom iris.algebra Require Import auth agree csum frac excl cmra.\n\n(** * The example program.\nNote that a record\n\n   { is_classified: ref bool;\n     data : ref τ }\n\nis modeled by a tuple\n\n   (is_classified, data)\n**)\nDefinition thread1 : val :=\n  rec: \"loop\" \"out\" \"rec\" :=\n    let: \"is_classified\" := Fst \"rec\" in\n    let: \"data\" := Snd \"rec\" in\n    (if: ~ !\"is_classified\"\n     then \"out\" <- !\"data\"\n     else #());;\n    \"loop\" \"out\" \"rec\".\n\nDefinition thread2 : val :=\n  λ: \"rec\", let: \"is_classified\" := Fst \"rec\" in\n            let: \"data\" := Snd \"rec\" in\n            \"data\" <- #0;;\n            \"is_classified\" <- #false.\n\n\nDefinition prog : val := λ: \"out\" \"secret\",\n  let: \"rec\" := (ref #true, ref \"secret\") in\n  thread1 \"out\" \"rec\" ||| thread2 \"rec\".\n\n\n(** * Ghost state *)\nDefinition rec : Type := loc * loc.\nInductive state :=\n| Classified\n| Intermediate\n| Declassified.\n\nCanonical Structure stateO := leibnizO state.\nInstance state_inhabited : Inhabited state := populate Declassified.\n\nDefinition stateR := authR (optionUR (exclR stateO)).\nClass stateG Σ := StateG {\n   state_stateG :> inG Σ stateR;\n}.\n\nDefinition classified := Excl' Classified.\nDefinition intermediate := Excl' Intermediate.\nDefinition declassified := Excl' Declassified.\n\nSection helper_lemmas.\n  Context `{!stateG Σ, !oneshotG Σ}.\n\n  (* Helper lemmas *)\n  Lemma Some_None_not_included {A : cmra} (x : A) :\n    ¬ Some x ≼ None.\n  Proof.\n    rewrite option_included. intros [?|Hfoo]; simplify_eq/=.\n    destruct Hfoo as [a [b [? [? ?]]]]. simplify_eq/=.\n  Qed.\n\n  Lemma current_state γ s1 s2  :\n    own γ (◯ Some s2 : stateR) -∗ own γ (● Some s1 : stateR) -∗ ⌜s1 = s2⌝.\n  Proof.\n    iIntros \"Hf Ha\".\n    iPoseProof (own_valid_2 with \"Ha Hf\") as \"H\".\n    iDestruct \"H\" as %[Hfoo Hh]%auth_both_valid_discrete. iPureIntro.\n    revert Hfoo. rewrite Some_included.\n    intros [Hfoo|Hfoo]; eauto.\n    + by unfold_leibniz.\n    + exfalso. eapply (exclusive_included _ _ Hfoo). done.\n  Qed.\n\n  Lemma excl_change_state (s2 s1 : state) γ :\n    own γ (● Excl' s1 : stateR) -∗ own γ (◯ Excl' s1 : stateR) ==∗\n    own γ (● Excl' s2 : stateR) ∗ own γ (◯ Excl' s2 : stateR).\n  Proof.\n    apply bi.wand_intro_r. rewrite - !own_op.\n    apply own_update. apply auth_update.\n    apply option_local_update.\n    apply exclusive_local_update. done.\n  Qed.\n\nEnd helper_lemmas.\n\n(** * Ghost state theory *)\nSection ghost_state.\n  Context `{!stateG Σ, !oneshotG Σ}.\n\n  (* Preorder on states *)\n  Definition state_leq (s1 s2 : state) :=\n    match s1, s2 with\n    | Classified,   _            => true\n    | _,            Declassified => true\n    | Intermediate, Intermediate => true\n    | _,            _            => false\n    end.\n\n  Definition in_state γ (s : state) :=\n    match s with\n    | Classified   => own γ.1 (● classified : stateR)   ∗ pending γ.2\n    | Intermediate => own γ.1 (● intermediate : stateR) ∗ pending γ.2\n    | Declassifed  => own γ.1 (● declassified : stateR) ∗ shot γ.2\n    end%I.\n\n  Definition state_token γ (s : state) :=\n    match s with\n    | Classified   => own γ.1 (◯ classified : stateR)\n    | Intermediate => own γ.1 (◯ intermediate : stateR)\n    | Declassifed  => shot γ.2\n    end%I.\n\n  Lemma in_state_agree γ s1 s2 :\n    in_state γ s1 -∗ state_token γ s2 -∗ ⌜s1 = s2⌝.\n  Proof.\n    rewrite /in_state /state_token.\n    destruct s1, s2; first\n       [ by iIntros \"? ?\"; iPureIntro; eauto\n       | iIntros \"[Ha _] Hf\"; iExFalso;\n         iDestruct (current_state with \"Hf Ha\") as %Hfoo;\n         simplify_eq/=\n       | iIntros \"[_ H1] H2\"; iExFalso;\n         iApply (shot_not_pending with \"H2 H1\") ].\n  Qed.\n\n  Global Instance declassified_token_persistent γ :\n    Persistent (state_token γ Declassified).\n  Proof. apply _. Qed.\n\n  Lemma state_change γ s1 s2 :\n    state_leq s1 s2 →\n    in_state γ s1 -∗ state_token γ s1 ==∗ in_state γ s2 ∗ state_token γ s2.\n  Proof.\n    rewrite /in_state /state_token. iIntros (Hleq).\n    destruct s1, s2; first\n      [ by iIntros \"[$ $] $\"\n      | iIntros \"[Ha $] Hf\"; iApply (excl_change_state with \"Ha Hf\")\n      | exfalso; by simplify_eq/=\n      | idtac ].\n    - iIntros \"[Ha H] Hf\".\n      iMod (shoot with \"H\") as \"#$\".\n      by iMod (excl_change_state with \"Ha Hf\") as \"[$ _]\".\n    - iIntros \"[Ha H] Hf\".\n      iMod (shoot with \"H\") as \"#$\".\n      by iMod (excl_change_state with \"Ha Hf\") as \"[$ _]\".\n  Qed.\n\nEnd ghost_state.\n\nSection proof.\n  Context `{!heapDG Σ, !spawnG Σ, !stateG Σ, !oneshotG Σ}.\n\n  (* The invariant guarantees the monotonicity of the declassification. *)\n  Definition inv_body (r1 r2 : rec) γ γs ξ :=\n    (* in the state CLASSIFIED *)\n    ((∃ v1 v2, in_state (γ, γs) Classified ∗ r1.1 ↦ₗ #true ∗ r2.1 ↦ᵣ #true\n                   ∗ r1.2 ↦ₗ v1 ∗ r2.2 ↦ᵣ v2 ∗ ⟦ tint High ⟧ ξ v1 v2)\n   ∨ (* in the state INTERMEDIATE *)\n     (∃ v, in_state (γ, γs) Intermediate ∗ r1.1 ↦ₗ #true ∗ r2.1 ↦ #true\n               ∗ r1.2 ↦ₗ v ∗ r2.2 ↦ᵣ v ∗ ⟦ tint Low ⟧ ξ v v)\n   ∨ (* in the state DECLASSIFIED *)\n     (∃ v, in_state (γ, γs) Declassified ∗ state_token (γ, γs) Declassified ∗ r1.1 ↦ₗ #false ∗ r2.1 ↦ #false\n               ∗ r1.2 ↦ₗ v ∗ r2.2 ↦ᵣ v ∗ ⟦ tint Low ⟧ ξ v v))%I.\n\n  Definition N := nroot.@\"example\".\n\n  Definition I (rec1 rec2 : val) γ ξ :=\n    (∃ (i1 i2 d1 d2 : loc), ⌜rec1 = (#i1, #d1)%V⌝ ∗ ⌜rec2 = (#i2, #d2)%V⌝ ∗\n        inv N (inv_body (i1,d1) (i2,d2) γ.1 γ.2 ξ))%I.\n\n  Lemma thread1_spec γ out1 rec1 out2 rec2 ξ :\n    ⟦ tref (tint Low) ⟧ ξ out1 out2 -∗\n    I rec1 rec2 γ ξ -∗\n    DWP thread1 out1 rec1 & thread1 out2 rec2 : ⟦ tunit ⟧ ξ.\n  Proof.\n    iIntros \"#Hout\".\n    iDestruct 1 as (ri1 ri2 rd1 rd2 -> ->) \"#Hinv\".\n    iLöb as \"IH\". dwp_rec. dwp_pures.\n    dwp_bind (!_)%E (!_)%E.\n    iApply dwp_atomic.\n    iInv N as \"[Hst|[Hst|Hst]]\" \"Hcl\"; iModIntro.\n    - (* We are still in the CLASSIFIED state *)\n      iDestruct \"Hst\" as (v1 v2) \"(Hstate & Hi1 & Hi2 & Hd1 & Hd2 & Hv)\".\n      iApply (dwp_load with \"Hi1 Hi2\"). iIntros \"Hi1 Hi2\". iNext.\n      iMod (\"Hcl\" with \"[-]\") as \"_\".\n      { iNext. iLeft. eauto with iFrame. }\n      iModIntro. dwp_pures. by iApply \"IH\".\n    - (* We are in the INTERMEDIATE state *)\n      iDestruct \"Hst\" as (v) \"(Hstate & Hi1 & Hi2 & Hd1 & Hd2 & Hv)\".\n      iApply (dwp_load with \"Hi1 Hi2\"). iIntros \"Hi1 Hi2\". iNext.\n      iMod (\"Hcl\" with \"[-]\") as \"_\".\n      { iNext. iRight. iLeft. eauto with iFrame. }\n      iModIntro. dwp_pures. by iApply \"IH\".\n    - (* We are in the DECLASSIFIED state *)\n      iDestruct \"Hst\" as (v) \"(Hstate & #Hdecl & Hi1 & Hi2 & Hd1 & Hd2 & Hv)\".\n      iApply (dwp_load with \"Hi1 Hi2\"). iIntros \"Hi1 Hi2\". iNext.\n      iMod (\"Hcl\" with \"[-]\") as \"_\".\n      { iNext. iRight. iRight. eauto with iFrame. }\n      iModIntro. dwp_pures. clear v.\n      dwp_bind (_ <- _)%E (_ <- _)%E.\n      iApply (dwp_wand _ _ _ (⟦ tunit ⟧ ξ)); last first.\n      { iIntros (??) \"_\". dwp_pures.\n        by iApply \"IH\". }\n      dwp_bind (! _)%E (! _)%E.\n      iApply dwp_atomic.\n      iInv N as \"[Hst|[Hst|Hst]]\" \"Hcl\"; iModIntro.\n      + (* We *cannot* be in the CLASSIFIED state *)\n        iDestruct \"Hst\" as (v1 v2) \"(>Hstate & Hi1 & Hi2 & Hd1 & Hd2 & Hv)\".\n        iExFalso. iDestruct (in_state_agree with \"Hstate Hdecl\") as %foo.\n        simplify_eq/=.\n      + (* We *cannot* be in the INTERMEDIATE state *)\n        iDestruct \"Hst\" as (v) \"(>Hstate & Hi1 & Hi2 & Hd1 & Hd2 & #Hv)\".\n        iExFalso. iDestruct (in_state_agree with \"Hstate Hdecl\") as %foo.\n        simplify_eq/=.\n      + (* Still in the DECLASSIFIED state *)\n        iDestruct \"Hst\" as (v) \"(Hstate & _ & Hi1 & Hi2 & Hd1 & Hd2 & #Hv)\".\n        iApply (dwp_load with \"Hd1 Hd2\"). iIntros \"Hd1 Hd2\". iNext.\n        iMod (\"Hcl\" with \"[-]\") as \"_\".\n        { iNext. iRight. iRight. eauto with iFrame. }\n        iModIntro. iApply logrel_store; first solve_ndisj; by iApply dwp_value.\n  Qed.\n\n  Lemma thread2_spec γ rec1 rec2 ξ :\n    I rec1 rec2 γ ξ -∗\n    state_token γ Classified -∗\n    DWP thread2 rec1 & thread2 rec2 : ⟦ tunit ⟧ ξ.\n  Proof.\n    iDestruct 1 as (ri1 ri2 rd1 rd2 -> ->) \"#Hinv\".\n    iIntros \"Hstt\".\n    dwp_rec. dwp_pures.\n    dwp_bind (_ <- _)%E (_ <- _)%E.\n    iApply dwp_atomic.\n    iInv N as \"[Hst|[Hst|Hst]]\" \"Hcl\"; iModIntro.\n    - (* We are still in the CLASSIFIED state *)\n      iDestruct \"Hst\" as (v1 v2) \"(Hstate & Hi1 & Hi2 & Hd1 & Hd2 & Hv)\".\n      iApply (dwp_store with \"Hd1 Hd2\"). iIntros \"Hd1 Hd2\". iNext.\n      iMod (state_change _ _ Intermediate with \"Hstate Hstt\") as \"[Hstate Hstt]\";\n        first done.\n      iMod (\"Hcl\" with \"[-Hstt]\") as \"_\".\n      { iNext. iRight. iLeft. iExists #0. iFrame.\n        rewrite interp_eq. iExists 0,0. eauto with iFrame. } clear v1 v2.\n      iModIntro. dwp_pures. iApply dwp_atomic.\n      iInv N as \"[Hst|[Hst|Hst]]\" \"Hcl\"; iModIntro.\n      + (* CLASSIFIED state --> impossible *)\n        iDestruct \"Hst\" as (v1 v2) \"(>Hstate & Hi1 & Hi2 & Hd1 & Hd2 & Hv)\".\n        iDestruct (in_state_agree with \"Hstate Hstt\") as %Hfoo.\n        exfalso. naive_solver.\n      + (* INTERMEDIATE state *)\n        iDestruct \"Hst\" as (v) \"(Hstate & Hi1 & Hi2 & Hd1 & Hd2 & Hv)\".\n        iApply (dwp_store with \"Hi1 Hi2\"). iIntros \"Hi1 Hi2\". iNext.\n        iMod (state_change _ _ Declassified with \"Hstate Hstt\") as \"[Hstate Hstt]\";\n          first done.\n        iMod (\"Hcl\" with \"[-]\") as \"_\".\n        { iNext. iRight. iRight. eauto with iFrame.  }\n        iModIntro. eauto with iFrame.\n      + (* DECLASSIFIED state. In this case it is actually impossible\n           in the program, but we don't account for that in the proof.\n           Instead we can just keep calm and carry on. *)\n        iDestruct \"Hst\" as (v) \"(>Hstate & Hdecl & Hi1 & Hi2 & Hd1 & Hd2 & Hv)\".\n        iApply (dwp_store with \"Hi1 Hi2\"). iIntros \"Hi1 Hi2\". iNext.\n        iMod (\"Hcl\" with \"[-]\") as \"_\".\n        { iNext. iRight. iRight. eauto with iFrame.  }\n        iModIntro. eauto with iFrame.\n    - (* INTERMEDIATE state --> impossible *)\n      iDestruct \"Hst\" as (v) \"(>Hstate & Hi1 & Hi2 & Hd1 & Hd2 & Hv)\".\n      destruct γ as [γ γs].\n      iDestruct (in_state_agree with \"Hstate Hstt\") as %Hfoo.\n      exfalso. naive_solver.\n    - (* DECLASSIFIED state --> impossible *)\n      iDestruct \"Hst\" as (v) \"(>Hstate & _ & Hi1 & Hi2 & Hd1 & Hd2 & Hv)\".\n      destruct γ as [γ γs].\n      iDestruct (in_state_agree with \"Hstate Hstt\") as %Hfoo.\n      exfalso. naive_solver.\n  Qed.\n\n\n  Lemma proof out1 out2 dat1 dat2 ξ :\n    ⟦ tref (tint Low) ⟧ ξ out1 out2 -∗\n    ⟦ tint High ⟧ ξ dat1 dat2 -∗\n    DWP (prog out1 dat1) & (prog out2 dat2) : ⟦ tprod tunit tunit ⟧ ξ.\n  Proof.\n    iIntros \"#Hout #Hdat\".\n    dwp_rec. dwp_pures.\n\n    dwp_bind (ref _)%E (ref _)%E.\n    iApply dwp_alloc. iIntros (rd1 rd2) \"Hrd1 Hrd2\". iNext.\n\n    dwp_bind (ref _)%E (ref _)%E.\n    iApply dwp_alloc. iIntros (is_classified1 is_classified2) \"Hc1 Hc2\". iNext.\n\n    iMod new_pending as (γs) \"Hstt\".\n    iMod (own_alloc (● classified ⋅ ◯ classified)) as (γ) \"Hst\".\n    { by apply (auth_both_valid_2 classified). }\n    rewrite own_op.\n    iDestruct \"Hst\" as \"[Hstate Htoken]\".\n    iMod (inv_alloc N _\n           (inv_body (is_classified1,rd1) (is_classified2,rd2) γ γs ξ) with \"[-Htoken]\")\n      as \"#Hinv\".\n    { iNext. iLeft. iExists _,_. eauto with iFrame. }\n    dwp_pures.\n    iApply (dwp_par (⟦ tunit ⟧ ξ) (⟦ tunit ⟧ ξ) with \"[] [Htoken]\").\n    - (* Thread 1 *) iApply (thread1_spec (γ,γs) with \"Hout []\").\n      iExists _,_,_,_. repeat iSplit; eauto.\n    - (* Thread 2 *) iApply (thread2_spec (γ,γs) with \"[] Htoken\").\n      iExists _,_,_,_. repeat iSplit; eauto.\n    - (* Finally *)\n      iIntros (???? [-> ->] [-> ->]).\n      iNext. iExists _,_,_,_; eauto with iFrame.\n  Qed.\n\nEnd proof.\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/examples/value_sensitivity_3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.26095238094326667}}
{"text": "Require Import Raft.\n\nRequire Import CommonDefinitions.\n\nSection TermsAndIndicesFromOneLogInterface.\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 terms_and_indices_from_one_log (net : network) : Prop :=\n    forall h,\n      terms_and_indices_from_one (log (nwState net h)).\n\n  Definition terms_and_indices_from_one_log_nw (net : network) : Prop :=\n    forall p t leaderId prevLogIndex prevLogTerm entries leaderCommit,\n      In p (nwPackets net) ->\n      pBody p = AppendEntries t leaderId prevLogIndex prevLogTerm entries leaderCommit ->\n      terms_and_indices_from_one entries.\n\n  Class terms_and_indices_from_one_log_interface : Prop := {\n    terms_and_indices_from_one_log_invariant : forall net,\n      raft_intermediate_reachable net ->\n      terms_and_indices_from_one_log net;\n    terms_and_indices_from_one_log_nw_invariant : forall net,\n      raft_intermediate_reachable net ->\n      terms_and_indices_from_one_log_nw net\n  }.\nEnd TermsAndIndicesFromOneLogInterface.", "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/TermsAndIndicesFromOneLogInterface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2609523753537261}}
{"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 CtxtSwitchAux.Specs.save_sysreg_state.\nRequire Import CtxtSwitchAux.LowSpecs.save_sysreg_state.\nRequire Import CtxtSwitchAux.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       sysreg_read_spec\n       set_rec_sysregs_spec\n    .\n\n  Lemma save_sysreg_state_spec_exists:\n    forall habd habd'  labd rec\n           (Hspec: save_sysreg_state_spec rec habd = Some habd')\n            (Hrel: relate_RData habd labd),\n    exists labd', save_sysreg_state_spec0 rec labd = Some labd' /\\ relate_RData habd' labd'.\n  Proof.\n    Local Opaque ptr_eq get_reg set_reg.\n    intros. destruct Hrel. destruct rec.\n    unfold save_sysreg_state_spec, save_sysreg_state_spec0 in *.\n    unfold set_rec_sysregs_spec, sysreg_read_spec.\n    autounfold in Hspec. simpl in *.\n    hsimpl_hyp Hspec; inv Hspec; simpl_query_oracle; extract_prop_dec. autounfold in *.\n    destruct regs_is_int64_dec in C3; [|inversion C3].\n    unfold Assertion. unfold buffer_loc. grewrite.\n    unfold ref_accessible in *. unfold GRANULE_STATE_REC. autounfold in *.\n    repeat (rewrite e; grewrite; simpl;\n            repeat rewrite ZMap.gss; simpl_update_reg; repeat rewrite ZMap.set2; repeat simpl_field;\n            simpl; grewrite; simpl).\n    eexists; split. reflexivity. constructor.\n    repeat (simpl_update_reg; simpl; repeat simpl_field).\n    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/CtxtSwitchAux/RefProof/save_sysreg_state.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2609440488771021}}
{"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 x86 generation: main proof. *)\n\nRequire Import Coqlib.\nRequire Import Errors.\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 Locations.\nRequire Import Mach.\nRequire Import Conventions.\nRequire Import Asm.\nRequire Import Asmgen.\nRequire Import Asmgenproof0.\nRequire Import Asmgenproof1.\n\nSection PRESERVATION.\n\nVariable prog: Mach.program.\nVariable tprog: Asm.program.\nHypothesis TRANSF: transf_program prog = Errors.OK tprog.\n\nLet ge := Genv.globalenv prog.\nLet tge := Genv.globalenv tprog.\n\nLemma symbols_preserved:\n  forall id, Genv.find_symbol tge id = Genv.find_symbol ge id.\nProof.\n  intros. unfold ge, tge.\n  apply Genv.find_symbol_transf_partial with transf_fundef.\n  exact TRANSF.\nQed.\n\nLemma functions_translated:\n  forall b f,\n  Genv.find_funct_ptr ge b = Some f ->\n  exists tf, Genv.find_funct_ptr tge b = Some tf /\\ transf_fundef f = Errors.OK tf.\nProof\n  (Genv.find_funct_ptr_transf_partial transf_fundef _ TRANSF).\n\nLemma functions_transl:\n  forall fb f tf,\n  Genv.find_funct_ptr ge fb = Some (Internal f) ->\n  transf_function f = OK tf ->\n  Genv.find_funct_ptr tge fb = Some (Internal tf).\nProof.\n  intros. exploit functions_translated; eauto. intros [tf' [A B]].\n  monadInv B. rewrite H0 in EQ; inv EQ; auto.\nQed.\n\nLemma varinfo_preserved:\n  forall b, Genv.find_var_info tge b = Genv.find_var_info ge b.\nProof.\n  intros. unfold ge, tge.\n  apply Genv.find_var_info_transf_partial with transf_fundef.\n  exact TRANSF.\nQed.\n\n(** * Properties of control flow *)\n\nLemma transf_function_no_overflow:\n  forall f tf,\n  transf_function f = OK tf -> list_length_z tf <= Int.max_unsigned.\nProof.\n  intros. monadInv H. destruct (zlt (list_length_z x) Int.max_unsigned); monadInv EQ0.\n  rewrite list_length_z_cons. omega.\nQed.\n\nLemma exec_straight_exec:\n  forall fb f c ep tf tc c' rs m rs' m',\n  transl_code_at_pc ge (rs PC) fb f c ep tf tc ->\n  exec_straight tge tf tc rs m c' rs' m' ->\n  plus step tge (State rs m) E0 (State rs' m').\nProof.\n  intros. inv H.\n  eapply exec_straight_steps_1; eauto.\n  eapply transf_function_no_overflow; eauto.\n  eapply functions_transl; eauto.\nQed.\n\nLemma exec_straight_at:\n  forall fb f c ep tf tc c' ep' tc' rs m rs' m',\n  transl_code_at_pc ge (rs PC) fb f c ep tf tc ->\n  transl_code f c' ep' = OK tc' ->\n  exec_straight tge tf tc rs m tc' rs' m' ->\n  transl_code_at_pc ge (rs' PC) fb f c' ep' tf tc'.\nProof.\n  intros. inv H.\n  exploit exec_straight_steps_2; eauto.\n  eapply transf_function_no_overflow; eauto.\n  eapply functions_transl; eauto.\n  intros [ofs' [PC' CT']].\n  rewrite PC'. constructor; auto.\nQed.\n\n(** The following lemmas show that the translation from Mach to Asm\n  preserves labels, in the sense that the following diagram commutes:\n<<\n                          translation\n        Mach code ------------------------ Asm instr sequence\n            |                                          |\n            | Mach.find_label lbl       find_label lbl |\n            |                                          |\n            v                                          v\n        Mach code tail ------------------- Asm instr seq tail\n                          translation\n>>\n  The proof demands many boring lemmas showing that Asm constructor\n  functions do not introduce new labels.\n\n  In passing, we also prove a \"is tail\" property of the generated Asm code.\n*)\n\nSection TRANSL_LABEL.\n\nRemark mk_mov_label:\n  forall rd rs k c, mk_mov rd rs k = OK c -> tail_nolabel k c.\nProof.\n  unfold mk_mov; intros.\n  destruct rd; try discriminate; destruct rs; TailNoLabel.\nQed.\nHint Resolve mk_mov_label: labels.\n\nRemark mk_shrximm_label:\n  forall n k c, mk_shrximm n k = OK c -> tail_nolabel k c.\nProof.\n  intros. monadInv H; TailNoLabel.\nQed.\nHint Resolve mk_shrximm_label: labels.\n\nRemark mk_intconv_label:\n  forall f r1 r2 k c, mk_intconv f r1 r2 k = OK c ->\n  (forall r r', nolabel (f r r')) ->\n  tail_nolabel k c.\nProof.\n  unfold mk_intconv; intros. TailNoLabel.\nQed.\nHint Resolve mk_intconv_label: labels.\n\nRemark mk_smallstore_label:\n  forall f addr r k c, mk_smallstore f addr r k = OK c ->\n  (forall r addr, nolabel (f r addr)) ->\n  tail_nolabel k c.\nProof.\n  unfold mk_smallstore; intros. TailNoLabel.\nQed.\nHint Resolve mk_smallstore_label: labels.\n\nRemark loadind_label:\n  forall base ofs ty dst k c,\n  loadind base ofs ty dst k = OK c ->\n  tail_nolabel k c.\nProof.\n  unfold loadind; intros. destruct ty.\n  TailNoLabel.\n  destruct (preg_of dst); TailNoLabel.\n  discriminate.\n  TailNoLabel.\nQed.\n\nRemark storeind_label:\n  forall base ofs ty src k c,\n  storeind src base ofs ty k = OK c ->\n  tail_nolabel k c.\nProof.\n  unfold storeind; intros. destruct ty.\n  TailNoLabel.\n  destruct (preg_of src); TailNoLabel.\n  discriminate.\n  TailNoLabel.\nQed.\n\nRemark mk_setcc_base_label:\n  forall xc rd k,\n  tail_nolabel k (mk_setcc_base xc rd k).\nProof.\n  intros. destruct xc; simpl; destruct (ireg_eq rd EAX); TailNoLabel.\nQed.\n\nRemark mk_setcc_label:\n  forall xc rd k,\n  tail_nolabel k (mk_setcc xc rd k).\nProof.\n  intros. unfold mk_setcc. destruct (low_ireg rd).\n  apply mk_setcc_base_label.\n  eapply tail_nolabel_trans. apply mk_setcc_base_label. TailNoLabel.\nQed.\n\nRemark mk_jcc_label:\n  forall xc lbl' k,\n  tail_nolabel k (mk_jcc xc lbl' k).\nProof.\n  intros. destruct xc; simpl; TailNoLabel.\nQed.\n\nRemark transl_cond_label:\n  forall cond args k c,\n  transl_cond cond args k = OK c ->\n  tail_nolabel k c.\nProof.\n  unfold transl_cond; intros.\n  destruct cond; TailNoLabel.\n  destruct (Int.eq_dec i Int.zero); TailNoLabel.\n  destruct c0; simpl; TailNoLabel.\n  destruct c0; simpl; TailNoLabel.\nQed.\n\nRemark transl_op_label:\n  forall op args r k c,\n  transl_op op args r k = OK c ->\n  tail_nolabel k c.\nProof.\n  unfold transl_op; intros. destruct op; TailNoLabel.\n  destruct (Int.eq_dec i Int.zero); TailNoLabel.\n  destruct (Float.eq_dec f Float.zero); TailNoLabel.\n  eapply tail_nolabel_trans. eapply transl_cond_label; eauto. eapply mk_setcc_label.\nQed.\n\nRemark transl_load_label:\n  forall chunk addr args dest k c,\n  transl_load chunk addr args dest k = OK c ->\n  tail_nolabel k c.\nProof.\n  intros. monadInv H. destruct chunk; TailNoLabel.\nQed.\n\nRemark transl_store_label:\n  forall chunk addr args src k c,\n  transl_store chunk addr args src k = OK c ->\n  tail_nolabel k c.\nProof.\n  intros. monadInv H. destruct chunk; TailNoLabel.\nQed.\n\nLemma transl_instr_label:\n  forall f i ep k c,\n  transl_instr f i ep k = OK c ->\n  match i with Mlabel lbl => c = Plabel lbl :: k | _ => tail_nolabel k c end.\nProof.\nOpaque loadind.\n  unfold transl_instr; intros; destruct i; TailNoLabel.\n  eapply loadind_label; eauto.\n  eapply storeind_label; eauto.\n  eapply loadind_label; eauto.\n  eapply tail_nolabel_trans; eapply loadind_label; eauto.\n  eapply transl_op_label; eauto.\n  eapply transl_load_label; eauto.\n  eapply transl_store_label; eauto.\n  destruct s0; TailNoLabel.\n  destruct s0; TailNoLabel.\n  eapply tail_nolabel_trans. eapply transl_cond_label; eauto. eapply mk_jcc_label.\nQed.\n\nLemma transl_instr_label':\n  forall lbl f i ep k c,\n  transl_instr f i ep k = OK c ->\n  find_label lbl c = if Mach.is_label lbl i then Some k else find_label lbl k.\nProof.\n  intros. exploit transl_instr_label; eauto.\n  destruct i; try (intros [A B]; apply B).\n  intros. subst c. simpl. auto.\nQed.\n\nLemma transl_code_label:\n  forall lbl f c ep tc,\n  transl_code f c ep = OK tc ->\n  match Mach.find_label lbl c with\n  | None => find_label lbl tc = None\n  | Some c' => exists tc', find_label lbl tc = Some tc' /\\ transl_code f c' false = OK tc'\n  end.\nProof.\n  induction c; simpl; intros.\n  inv H. auto.\n  monadInv H. rewrite (transl_instr_label' lbl _ _ _ _ _ EQ0).\n  generalize (Mach.is_label_correct lbl a).\n  destruct (Mach.is_label lbl a); intros.\n  subst a. simpl in EQ. exists x; auto.\n  eapply IHc; eauto.\nQed.\n\nLemma transl_find_label:\n  forall lbl f tf,\n  transf_function f = OK tf ->\n  match Mach.find_label lbl f.(Mach.fn_code) with\n  | None => find_label lbl tf = None\n  | Some c => exists tc, find_label lbl tf = Some tc /\\ transl_code f c false = OK tc\n  end.\nProof.\n  intros. monadInv H. destruct (zlt (list_length_z x) Int.max_unsigned); inv EQ0.\n  simpl. eapply transl_code_label; eauto. rewrite transl_code'_transl_code in EQ; eauto.\nQed.\n\nEnd TRANSL_LABEL.\n\n(** A valid branch in a piece of Mach code translates to a valid ``go to''\n  transition in the generated PPC code. *)\n\nLemma find_label_goto_label:\n  forall f tf lbl rs m c' b ofs,\n  Genv.find_funct_ptr ge b = Some (Internal f) ->\n  transf_function f = OK tf ->\n  rs PC = Vptr b ofs ->\n  Mach.find_label lbl f.(Mach.fn_code) = Some c' ->\n  exists tc', exists rs',\n    goto_label tf lbl rs m = Next rs' m\n  /\\ transl_code_at_pc ge (rs' PC) b f c' false tf tc'\n  /\\ forall r, r <> PC -> rs'#r = rs#r.\nProof.\n  intros. exploit (transl_find_label lbl f tf); eauto. rewrite H2.\n  intros [tc [A B]].\n  exploit label_pos_code_tail; eauto. instantiate (1 := 0).\n  intros [pos' [P [Q R]]].\n  exists tc; exists (rs#PC <- (Vptr b (Int.repr pos'))).\n  split. unfold goto_label. rewrite P. rewrite H1. auto.\n  split. rewrite Pregmap.gss. constructor; auto.\n  rewrite Int.unsigned_repr. replace (pos' - 0) with pos' in Q.\n  auto. omega.\n  generalize (transf_function_no_overflow _ _ H0). omega.\n  intros. apply Pregmap.gso; auto.\nQed.\n\n(** Existence of return addresses *)\n\nLemma return_address_exists:\n  forall f sg ros c, is_tail (Mcall sg ros :: c) f.(Mach.fn_code) ->\n  exists ra, return_address_offset f c ra.\nProof.\n  intros. eapply Asmgenproof0.return_address_exists; eauto.\n- intros. exploit transl_instr_label; eauto.\n  destruct i; try (intros [A B]; apply A). intros. subst c0. repeat constructor.\n- intros. monadInv H0.\n  destruct (zlt (list_length_z x) Int.max_unsigned); inv EQ0.\n  rewrite transl_code'_transl_code in EQ.\n  exists x; exists true; split; auto. unfold fn_code. repeat constructor.\n- exact transf_function_no_overflow.\nQed.\n\n(** * Proof of semantic preservation *)\n\n(** Semantic preservation is proved using simulation diagrams\n  of the following form.\n<<\n           st1 --------------- st2\n            |                   |\n           t|                  *|t\n            |                   |\n            v                   v\n           st1'--------------- st2'\n>>\n  The invariant is the [match_states] predicate below, which includes:\n- The PPC code pointed by the PC register is the translation of\n  the current Mach code sequence.\n- Mach register values and PPC register values agree.\n*)\n\nInductive match_states: Mach.state -> Asm.state -> Prop :=\n  | match_states_intro:\n      forall s fb sp c ep ms m m' rs f tf tc\n        (STACKS: match_stack ge s)\n        (FIND: Genv.find_funct_ptr ge fb = Some (Internal f))\n        (MEXT: Mem.extends m m')\n        (AT: transl_code_at_pc ge (rs PC) fb f c ep tf tc)\n        (AG: agree ms sp rs)\n        (DXP: ep = true -> rs#EDX = parent_sp s),\n      match_states (Mach.State s fb sp c ms m)\n                   (Asm.State rs m')\n  | match_states_call:\n      forall s fb ms m m' rs\n        (STACKS: match_stack ge s)\n        (MEXT: Mem.extends m m')\n        (AG: agree ms (parent_sp s) rs)\n        (ATPC: rs PC = Vptr fb Int.zero)\n        (ATLR: rs RA = parent_ra s),\n      match_states (Mach.Callstate s fb ms m)\n                   (Asm.State rs m')\n  | match_states_return:\n      forall s ms m m' rs\n        (STACKS: match_stack ge s)\n        (MEXT: Mem.extends m m')\n        (AG: agree ms (parent_sp s) rs)\n        (ATPC: rs PC = parent_ra s),\n      match_states (Mach.Returnstate s ms m)\n                   (Asm.State rs m').\n\nLemma exec_straight_steps:\n  forall s fb f rs1 i c ep tf tc m1' m2 m2' sp ms2,\n  match_stack ge s ->\n  Mem.extends m2 m2' ->\n  Genv.find_funct_ptr ge fb = Some (Internal f) ->\n  transl_code_at_pc ge (rs1 PC) fb f (i :: c) ep tf tc ->\n  (forall k c (TR: transl_instr f i ep k = OK c),\n   exists rs2,\n       exec_straight tge tf c rs1 m1' k rs2 m2'\n    /\\ agree ms2 sp rs2\n    /\\ (it1_is_parent ep i = true -> rs2#EDX = parent_sp s)) ->\n  exists st',\n  plus step tge (State rs1 m1') E0 st' /\\\n  match_states (Mach.State s fb sp c ms2 m2) st'.\nProof.\n  intros. inversion H2. subst. monadInv H7.\n  exploit H3; eauto. intros [rs2 [A [B C]]].\n  exists (State rs2 m2'); split.\n  eapply exec_straight_exec; eauto.\n  econstructor; eauto. eapply exec_straight_at; eauto.\nQed.\n\nLemma exec_straight_steps_goto:\n  forall s fb f rs1 i c ep tf tc m1' m2 m2' sp ms2 lbl c',\n  match_stack ge s ->\n  Mem.extends m2 m2' ->\n  Genv.find_funct_ptr ge fb = Some (Internal f) ->\n  Mach.find_label lbl f.(Mach.fn_code) = Some c' ->\n  transl_code_at_pc ge (rs1 PC) fb f (i :: c) ep tf tc ->\n  it1_is_parent ep i = false ->\n  (forall k c (TR: transl_instr f i ep k = OK c),\n   exists jmp, exists k', exists rs2,\n       exec_straight tge tf c rs1 m1' (jmp :: k') rs2 m2'\n    /\\ agree ms2 sp rs2\n    /\\ exec_instr tge tf jmp rs2 m2' = goto_label tf lbl rs2 m2') ->\n  exists st',\n  plus step tge (State rs1 m1') E0 st' /\\\n  match_states (Mach.State s fb sp c' ms2 m2) st'.\nProof.\n  intros. inversion H3. subst. monadInv H9.\n  exploit H5; eauto. intros [jmp [k' [rs2 [A [B C]]]]].\n  generalize (functions_transl _ _ _ H7 H8); intro FN.\n  generalize (transf_function_no_overflow _ _ H8); intro NOOV.\n  exploit exec_straight_steps_2; eauto.\n  intros [ofs' [PC2 CT2]].\n  exploit find_label_goto_label; eauto.\n  intros [tc' [rs3 [GOTO [AT' OTH]]]].\n  exists (State rs3 m2'); split.\n  eapply plus_right'.\n  eapply exec_straight_steps_1; eauto.\n  econstructor; eauto.\n  eapply find_instr_tail. eauto.\n  rewrite C. eexact GOTO.\n  traceEq.\n  econstructor; eauto.\n  apply agree_exten with rs2; auto with asmgen.\n  congruence.\nQed.\n\n(** We need to show that, in the simulation diagram, we cannot\n  take infinitely many Mach transitions that correspond to zero\n  transitions on the PPC side.  Actually, all Mach transitions\n  correspond to at least one Asm transition, except the\n  transition from [Mach.Returnstate] to [Mach.State].\n  So, the following integer measure will suffice to rule out\n  the unwanted behaviour. *)\n\nDefinition measure (s: Mach.state) : nat :=\n  match s with\n  | Mach.State _ _ _ _ _ _ => 0%nat\n  | Mach.Callstate _ _ _ _ => 0%nat\n  | Mach.Returnstate _ _ _ => 1%nat\n  end.\n\n(** This is the simulation diagram.  We prove it by case analysis on the Mach transition. *)\n\nTheorem step_simulation:\n  forall S1 t S2, Mach.step return_address_offset ge S1 t S2 ->\n  forall S1' (MS: match_states S1 S1'),\n  (exists S2', plus step 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; inv MS.\n\n- (* Mlabel *)\n  left; eapply exec_straight_steps; eauto; intros.\n  monadInv TR. econstructor; split. apply exec_straight_one. simpl; eauto. auto.\n  split. apply agree_nextinstr; auto. simpl; congruence.\n\n- (* Mgetstack *)\n  unfold load_stack in H.\n  exploit Mem.loadv_extends; eauto. intros [v' [A B]].\n  rewrite (sp_val _ _ _ AG) in A.\n  left; eapply exec_straight_steps; eauto. intros. simpl in TR.\n  exploit loadind_correct; eauto. intros [rs' [P [Q R]]].\n  exists rs'; split. eauto.\n  split. eapply agree_set_mreg; eauto. congruence.\n  simpl; congruence.\n\n- (* Msetstack *)\n  unfold store_stack in H.\n  assert (Val.lessdef (rs src) (rs0 (preg_of src))). eapply preg_val; eauto.\n  exploit Mem.storev_extends; eauto. intros [m2' [A B]].\n  left; eapply exec_straight_steps; eauto.\n  rewrite (sp_val _ _ _ AG) in A. intros. simpl in TR.\n  exploit storeind_correct; eauto. intros [rs' [P Q]].\n  exists rs'; split. eauto.\n  split. eapply agree_undef_regs; eauto.\n  simpl; intros. rewrite Q; auto with asmgen.\nLocal Transparent destroyed_by_setstack.\n  destruct ty; simpl; intuition congruence.\n\n- (* Mgetparam *)\n  assert (f0 = f) by congruence; subst f0.\n  unfold load_stack in *.\n  exploit Mem.loadv_extends. eauto. eexact H0. auto.\n  intros [parent' [A B]]. rewrite (sp_val _ _ _ AG) in A.\n  exploit lessdef_parent_sp; eauto. clear B; intros B; subst parent'.\n  exploit Mem.loadv_extends. eauto. eexact H1. auto.\n  intros [v' [C D]].\nOpaque loadind.\n  left; eapply exec_straight_steps; eauto; intros.\n  assert (DIFF: negb (mreg_eq dst DX) = true -> IR EDX <> preg_of dst).\n    intros. change (IR EDX) with (preg_of DX). red; intros.\n    unfold proj_sumbool in H1. destruct (mreg_eq dst DX); try discriminate.\n    elim n. eapply preg_of_injective; eauto.\n  destruct ep; simpl in TR.\n(* EDX contains parent *)\n  exploit loadind_correct. eexact TR.\n  instantiate (2 := rs0). rewrite DXP; eauto.\n  intros [rs1 [P [Q R]]].\n  exists rs1; split. eauto.\n  split. eapply agree_set_mreg. eapply agree_set_mreg; eauto. congruence. auto.\n  simpl; intros. rewrite R; auto.\n(* EDX does not contain parent *)\n  monadInv TR.\n  exploit loadind_correct. eexact EQ0. eauto. intros [rs1 [P [Q R]]]. simpl in Q.\n  exploit loadind_correct. eexact EQ. instantiate (2 := rs1). rewrite Q. eauto.\n  intros [rs2 [S [T U]]].\n  exists rs2; split. eapply exec_straight_trans; eauto.\n  split. eapply agree_set_mreg. eapply agree_set_mreg; eauto. congruence. auto.\n  simpl; intros. rewrite U; auto.\n\n- (* Mop *)\n  assert (eval_operation tge sp op rs##args m = Some v).\n    rewrite <- H. apply eval_operation_preserved. exact symbols_preserved.\n  exploit eval_operation_lessdef. eapply preg_vals; eauto. eauto. eexact H0.\n  intros [v' [A B]]. rewrite (sp_val _ _ _ AG) in A.\n  left; eapply exec_straight_steps; eauto; intros. simpl in TR.\n  exploit transl_op_correct; eauto. intros [rs2 [P [Q R]]].\n  assert (S: Val.lessdef v (rs2 (preg_of res))) by (eapply Val.lessdef_trans; eauto).\n  exists rs2; split. eauto.\n  split. eapply agree_set_undef_mreg; eauto.\n  simpl; congruence.\n\n- (* Mload *)\n  assert (eval_addressing tge sp addr rs##args = Some a).\n    rewrite <- H. apply eval_addressing_preserved. exact symbols_preserved.\n  exploit eval_addressing_lessdef. eapply preg_vals; eauto. eexact H1.\n  intros [a' [A B]]. rewrite (sp_val _ _ _ AG) in A.\n  exploit Mem.loadv_extends; eauto. intros [v' [C D]].\n  left; eapply exec_straight_steps; eauto; intros. simpl in TR.\n  exploit transl_load_correct; eauto. intros [rs2 [P [Q R]]].\n  exists rs2; split. eauto.\n  split. eapply agree_set_undef_mreg; eauto. congruence.\n  simpl; congruence.\n\n- (* Mstore *)\n  assert (eval_addressing tge sp addr rs##args = Some a).\n    rewrite <- H. apply eval_addressing_preserved. exact symbols_preserved.\n  exploit eval_addressing_lessdef. eapply preg_vals; eauto. eexact H1.\n  intros [a' [A B]]. rewrite (sp_val _ _ _ AG) in A.\n  assert (Val.lessdef (rs src) (rs0 (preg_of src))). eapply preg_val; eauto.\n  exploit Mem.storev_extends; eauto. intros [m2' [C D]].\n  left; eapply exec_straight_steps; eauto.\n  intros. simpl in TR.\n  exploit transl_store_correct; eauto. intros [rs2 [P Q]].\n  exists rs2; split. eauto.\n  split. eapply agree_undef_regs; eauto.\n  simpl; congruence.\n\n- (* Mcall *)\n  assert (f0 = f) by congruence.  subst f0.\n  inv AT.\n  assert (NOOV: list_length_z tf <= Int.max_unsigned).\n    eapply transf_function_no_overflow; eauto.\n  destruct ros as [rf|fid]; simpl in H; monadInv H5.\n+ (* Indirect call *)\n  assert (rs rf = Vptr f' Int.zero).\n    destruct (rs rf); try discriminate.\n    revert H; predSpec Int.eq Int.eq_spec i Int.zero; intros; congruence.\n  assert (rs0 x0 = Vptr f' Int.zero).\n    exploit ireg_val; eauto. rewrite H5; intros LD; inv LD; auto.\n  generalize (code_tail_next_int _ _ _ _ NOOV H6). intro CT1.\n  assert (TCA: transl_code_at_pc ge (Vptr fb (Int.add ofs Int.one)) fb f c false tf x).\n    econstructor; eauto.\n  exploit return_address_offset_correct; eauto. intros; subst ra.\n  left; econstructor; split.\n  apply plus_one. eapply exec_step_internal. eauto.\n  eapply functions_transl; eauto. eapply find_instr_tail; eauto.\n  simpl. eauto.\n  econstructor; eauto.\n  econstructor; eauto.\n  eapply agree_sp_def; eauto.\n  simpl. eapply agree_exten; eauto. intros. Simplifs.\n  Simplifs. rewrite <- H2. auto.\n+ (* Direct call *)\n  generalize (code_tail_next_int _ _ _ _ NOOV H6). intro CT1.\n  assert (TCA: transl_code_at_pc ge (Vptr fb (Int.add ofs Int.one)) fb f c false tf x).\n    econstructor; eauto.\n  exploit return_address_offset_correct; eauto. intros; subst ra.\n  left; econstructor; split.\n  apply plus_one. eapply exec_step_internal. eauto.\n  eapply functions_transl; eauto. eapply find_instr_tail; eauto.\n  simpl. unfold symbol_offset. rewrite symbols_preserved. rewrite H. eauto.\n  econstructor; eauto.\n  econstructor; eauto.\n  eapply agree_sp_def; eauto.\n  simpl. eapply agree_exten; eauto. intros. Simplifs.\n  Simplifs. rewrite <- H2. auto.\n\n- (* Mtailcall *)\n  assert (f0 = f) by congruence.  subst f0.\n  inv AT.\n  assert (NOOV: list_length_z tf <= Int.max_unsigned).\n    eapply transf_function_no_overflow; eauto.\n  rewrite (sp_val _ _ _ AG) in *. unfold load_stack in *.\n  exploit Mem.loadv_extends. eauto. eexact H1. auto. simpl. intros [parent' [A B]].\n  exploit Mem.loadv_extends. eauto. eexact H2. auto. simpl. intros [ra' [C D]].\n  exploit lessdef_parent_sp; eauto. intros. subst parent'. clear B.\n  exploit lessdef_parent_ra; eauto. intros. subst ra'. clear D.\n  exploit Mem.free_parallel_extends; eauto. intros [m2' [E F]].\n  destruct ros as [rf|fid]; simpl in H; monadInv H7.\n+ (* Indirect call *)\n  assert (rs rf = Vptr f' Int.zero).\n    destruct (rs rf); try discriminate.\n    revert H; predSpec Int.eq Int.eq_spec i Int.zero; intros; congruence.\n  assert (rs0 x0 = Vptr f' Int.zero).\n    exploit ireg_val; eauto. rewrite H7; intros LD; inv LD; auto.\n  generalize (code_tail_next_int _ _ _ _ NOOV H8). intro CT1.\n  left; econstructor; split.\n  eapply plus_left. eapply exec_step_internal. eauto.\n  eapply functions_transl; eauto. eapply find_instr_tail; eauto.\n  simpl. rewrite C. rewrite A. rewrite <- (sp_val _ _ _ AG). rewrite E. eauto.\n  apply star_one. eapply exec_step_internal.\n  transitivity (Val.add rs0#PC Vone). auto. rewrite <- H4. simpl. eauto.\n  eapply functions_transl; eauto. eapply find_instr_tail; eauto.\n  simpl. eauto. traceEq.\n  econstructor; eauto.\n  apply agree_set_other; auto. apply agree_nextinstr. apply agree_set_other; auto.\n  eapply agree_change_sp; eauto. eapply parent_sp_def; eauto.\n  Simplifs. rewrite Pregmap.gso; auto.\n  generalize (preg_of_not_SP rf). rewrite (ireg_of_eq _ _ EQ1). congruence.\n+ (* Direct call *)\n  generalize (code_tail_next_int _ _ _ _ NOOV H8). intro CT1.\n  left; econstructor; split.\n  eapply plus_left. eapply exec_step_internal. eauto.\n  eapply functions_transl; eauto. eapply find_instr_tail; eauto.\n  simpl. rewrite C. rewrite A. rewrite <- (sp_val _ _ _ AG). rewrite E. eauto.\n  apply star_one. eapply exec_step_internal.\n  transitivity (Val.add rs0#PC Vone). auto. rewrite <- H4. simpl. eauto.\n  eapply functions_transl; eauto. eapply find_instr_tail; eauto.\n  simpl. eauto. traceEq.\n  econstructor; eauto.\n  apply agree_set_other; auto. apply agree_nextinstr. apply agree_set_other; auto.\n  eapply agree_change_sp; eauto. eapply parent_sp_def; eauto.\n  rewrite Pregmap.gss. unfold symbol_offset. rewrite symbols_preserved. rewrite H. auto.\n\n- (* Mbuiltin *)\n  inv AT. monadInv H3.\n  exploit functions_transl; eauto. intro FN.\n  generalize (transf_function_no_overflow _ _ H2); intro NOOV.\n  exploit external_call_mem_extends'; eauto. eapply preg_vals; eauto.\n  intros [vres' [m2' [A [B [C D]]]]].\n  left. econstructor; split. apply plus_one.\n  eapply exec_step_builtin. eauto. eauto.\n  eapply find_instr_tail; eauto.\n  eapply external_call_symbols_preserved'; eauto.\n  exact symbols_preserved. exact varinfo_preserved.\n  eauto.\n  econstructor; eauto.\n  instantiate (2 := tf); instantiate (1 := x).\n  unfold nextinstr_nf, nextinstr. rewrite Pregmap.gss.\n  rewrite undef_regs_other. rewrite set_pregs_other_2. rewrite undef_regs_other_2.\n  rewrite <- H0. simpl. econstructor; eauto.\n  eapply code_tail_next_int; eauto.\n  rewrite preg_notin_charact. intros. auto with asmgen.\n  rewrite preg_notin_charact. intros. auto with asmgen.\n  auto with asmgen.\n  simpl; intros. intuition congruence.\n  apply agree_nextinstr_nf. eapply agree_set_mregs; auto.\n  eapply agree_undef_regs; eauto. intros; apply undef_regs_other_2; auto.\n  congruence.\n\n- (* Mannot *)\n  inv AT. monadInv H4.\n  exploit functions_transl; eauto. intro FN.\n  generalize (transf_function_no_overflow _ _ H3); intro NOOV.\n  exploit annot_arguments_match; eauto. intros [vargs' [P Q]].\n  exploit external_call_mem_extends'; eauto.\n  intros [vres' [m2' [A [B [C D]]]]].\n  left. econstructor; split. apply plus_one.\n  eapply exec_step_annot. eauto. eauto.\n  eapply find_instr_tail; eauto. eauto.\n  eapply external_call_symbols_preserved'; eauto.\n  exact symbols_preserved. exact varinfo_preserved.\n  eapply match_states_intro with (ep := false); eauto with coqlib.\n  unfold nextinstr. rewrite Pregmap.gss.\n  rewrite <- H1; simpl. econstructor; eauto.\n  eapply code_tail_next_int; eauto.\n  apply agree_nextinstr. auto.\n  congruence.\n\n- (* Mgoto *)\n  assert (f0 = f) by congruence. subst f0.\n  inv AT. monadInv H4.\n  exploit find_label_goto_label; eauto. intros [tc' [rs' [GOTO [AT2 INV]]]].\n  left; exists (State rs' m'); split.\n  apply plus_one. econstructor; eauto.\n  eapply functions_transl; eauto.\n  eapply find_instr_tail; eauto.\n  simpl; eauto.\n  econstructor; eauto.\n  eapply agree_exten; eauto with asmgen.\n  congruence.\n\n- (* Mcond true *)\n  assert (f0 = f) by congruence. subst f0.\n  exploit eval_condition_lessdef. eapply preg_vals; eauto. eauto. eauto. intros EC.\n  left; eapply exec_straight_steps_goto; eauto.\n  intros. simpl in TR.\n  destruct (transl_cond_correct tge tf cond args _ _ rs0 m' TR)\n  as [rs' [A [B C]]].\n  rewrite EC in B.\n  destruct (testcond_for_condition cond); simpl in *.\n(* simple jcc *)\n  exists (Pjcc c1 lbl); exists k; exists rs'.\n  split. eexact A.\n  split. eapply agree_exten; eauto.\n  simpl. rewrite B. auto.\n(* jcc; jcc *)\n  destruct (eval_testcond c1 rs') as [b1|] eqn:TC1;\n  destruct (eval_testcond c2 rs') as [b2|] eqn:TC2; inv B.\n  destruct b1.\n  (* first jcc jumps *)\n  exists (Pjcc c1 lbl); exists (Pjcc c2 lbl :: k); exists rs'.\n  split. eexact A.\n  split. eapply agree_exten; eauto.\n  simpl. rewrite TC1. auto.\n  (* second jcc jumps *)\n  exists (Pjcc c2 lbl); exists k; exists (nextinstr rs').\n  split. eapply exec_straight_trans. eexact A.\n  eapply exec_straight_one. simpl. rewrite TC1. auto. auto.\n  split. eapply agree_exten; eauto.\n  intros; Simplifs.\n  simpl. rewrite eval_testcond_nextinstr. rewrite TC2.\n  destruct b2; auto || discriminate.\n(* jcc2 *)\n  destruct (eval_testcond c1 rs') as [b1|] eqn:TC1;\n  destruct (eval_testcond c2 rs') as [b2|] eqn:TC2; inv B.\n  destruct (andb_prop _ _ H3). subst.\n  exists (Pjcc2 c1 c2 lbl); exists k; exists rs'.\n  split. eexact A.\n  split. eapply agree_exten; eauto.\n  simpl. rewrite TC1; rewrite TC2; auto.\n\n- (* Mcond false *)\n  exploit eval_condition_lessdef. eapply preg_vals; eauto. eauto. eauto. intros EC.\n  left; eapply exec_straight_steps; eauto. intros. simpl in TR.\n  destruct (transl_cond_correct tge tf cond args _ _ rs0 m' TR)\n  as [rs' [A [B C]]].\n  rewrite EC in B.\n  destruct (testcond_for_condition cond); simpl in *.\n(* simple jcc *)\n  econstructor; split.\n  eapply exec_straight_trans. eexact A.\n  apply exec_straight_one. simpl. rewrite B. eauto. auto.\n  split. apply agree_nextinstr. eapply agree_exten; eauto.\n  simpl; congruence.\n(* jcc ; jcc *)\n  destruct (eval_testcond c1 rs') as [b1|] eqn:TC1;\n  destruct (eval_testcond c2 rs') as [b2|] eqn:TC2; inv B.\n  destruct (orb_false_elim _ _ H1); subst.\n  econstructor; split.\n  eapply exec_straight_trans. eexact A.\n  eapply exec_straight_two. simpl. rewrite TC1. eauto. auto.\n  simpl. rewrite eval_testcond_nextinstr. rewrite TC2. eauto. auto. auto.\n  split. apply agree_nextinstr. apply agree_nextinstr. eapply agree_exten; eauto.\n  simpl; congruence.\n(* jcc2 *)\n  destruct (eval_testcond c1 rs') as [b1|] eqn:TC1;\n  destruct (eval_testcond c2 rs') as [b2|] eqn:TC2; inv B.\n  exists (nextinstr rs'); split.\n  eapply exec_straight_trans. eexact A.\n  apply exec_straight_one. simpl.\n  rewrite TC1; rewrite TC2.\n  destruct b1. simpl in *. subst b2. auto. auto.\n  auto.\n  split. apply agree_nextinstr. eapply agree_exten; eauto.\n  rewrite H1; congruence.\n\n- (* Mjumptable *)\n  assert (f0 = f) by congruence. subst f0.\n  inv AT. monadInv H6.\n  exploit functions_transl; eauto. intro FN.\n  generalize (transf_function_no_overflow _ _ H5); intro NOOV.\n  exploit find_label_goto_label; eauto.\n  intros [tc' [rs' [A [B C]]]].\n  exploit ireg_val; eauto. rewrite H. intros LD; inv LD.\n  left; econstructor; split.\n  apply plus_one. econstructor; eauto.\n  eapply find_instr_tail; eauto.\n  simpl. rewrite <- H9. unfold Mach.label in H0; unfold label; rewrite H0. eauto.\n  econstructor; eauto.\nTransparent destroyed_by_jumptable.\n  simpl. eapply agree_exten; eauto. intros. rewrite C; auto with asmgen.\n  congruence.\n\n- (* Mreturn *)\n  assert (f0 = f) by congruence. subst f0.\n  inv AT.\n  assert (NOOV: list_length_z tf <= Int.max_unsigned).\n    eapply transf_function_no_overflow; eauto.\n  rewrite (sp_val _ _ _ AG) in *. unfold load_stack in *.\n  exploit Mem.loadv_extends. eauto. eexact H0. auto. simpl. intros [parent' [A B]].\n  exploit lessdef_parent_sp; eauto. intros. subst parent'. clear B.\n  exploit Mem.loadv_extends. eauto. eexact H1. auto. simpl. intros [ra' [C D]].\n  exploit lessdef_parent_ra; eauto. intros. subst ra'. clear D.\n  exploit Mem.free_parallel_extends; eauto. intros [m2' [E F]].\n  monadInv H6.\n  exploit code_tail_next_int; eauto. intro CT1.\n  left; econstructor; split.\n  eapply plus_left. eapply exec_step_internal. eauto.\n  eapply functions_transl; eauto. eapply find_instr_tail; eauto.\n  simpl. rewrite C. rewrite A. rewrite <- (sp_val _ _ _ AG). rewrite E. eauto.\n  apply star_one. eapply exec_step_internal.\n  transitivity (Val.add rs0#PC Vone). auto. rewrite <- H3. simpl. eauto.\n  eapply functions_transl; eauto. eapply find_instr_tail; eauto.\n  simpl. eauto. traceEq.\n  constructor; auto.\n  apply agree_set_other; auto. apply agree_nextinstr. apply agree_set_other; auto.\n  eapply agree_change_sp; eauto. eapply parent_sp_def; eauto.\n\n- (* internal function *)\n  exploit functions_translated; eauto. intros [tf [A B]]. monadInv B.\n  generalize EQ; intros EQ'. monadInv EQ'. rewrite transl_code'_transl_code in EQ0.\n  destruct (zlt (list_length_z x0) Int.max_unsigned); inversion EQ1. clear EQ1.\n  unfold store_stack in *.\n  exploit Mem.alloc_extends. eauto. eauto. apply Zle_refl. apply Zle_refl.\n  intros [m1' [C D]].\n  exploit Mem.storev_extends. eexact D. eexact H1. eauto. eauto.\n  intros [m2' [F G]].\n  exploit Mem.storev_extends. eexact G. eexact H2. eauto. eauto.\n  intros [m3' [P Q]].\n  left; econstructor; split.\n  apply plus_one. econstructor; eauto.\n  subst x; simpl.\n  rewrite Int.unsigned_zero. simpl. eauto.\n  simpl. rewrite C. simpl in F. rewrite (sp_val _ _ _ AG) in F. rewrite F.\n  simpl in P. rewrite ATLR. rewrite P. eauto.\n  econstructor; eauto.\n  unfold nextinstr. rewrite Pregmap.gss. repeat rewrite Pregmap.gso; auto with asmgen.\n  rewrite ATPC. simpl. constructor; eauto.\n  subst x. unfold fn_code. eapply code_tail_next_int. rewrite list_length_z_cons. omega.\n  constructor.\n  apply agree_nextinstr. eapply agree_change_sp; eauto.\nTransparent destroyed_at_function_entry.\n  apply agree_undef_regs with rs0; eauto.\n  simpl; intros. apply Pregmap.gso; auto with asmgen. tauto.\n  congruence.\n  intros. Simplifs. eapply agree_sp; eauto.\n\n- (* external function *)\n  exploit functions_translated; eauto.\n  intros [tf [A B]]. simpl in B. inv B.\n  exploit extcall_arguments_match; eauto.\n  intros [args' [C D]].\n  exploit external_call_mem_extends'; eauto.\n  intros [res' [m2' [P [Q [R S]]]]].\n  left; econstructor; split.\n  apply plus_one. eapply exec_step_external; eauto.\n  eapply external_call_symbols_preserved'; eauto.\n  exact symbols_preserved. exact varinfo_preserved.\n  econstructor; eauto.\n  unfold loc_external_result.\n  apply agree_set_other; auto. apply agree_set_mregs; auto.\n\n- (* return *)\n  inv STACKS. simpl in *.\n  right. split. omega. split. auto.\n  econstructor; eauto. rewrite ATPC; eauto. congruence.\nQed.\n\nLemma transf_initial_states:\n  forall st1, Mach.initial_state prog st1 ->\n  exists st2, Asm.initial_state tprog st2 /\\ match_states st1 st2.\nProof.\n  intros. inversion H. unfold ge0 in *.\n  econstructor; split.\n  econstructor.\n  eapply Genv.init_mem_transf_partial; eauto.\n  replace (symbol_offset (Genv.globalenv tprog) (prog_main tprog) Int.zero)\n     with (Vptr fb Int.zero).\n  econstructor; eauto.\n  constructor.\n  apply Mem.extends_refl.\n  split. auto. simpl. unfold Vzero; congruence. intros. rewrite Regmap.gi. auto.\n  unfold symbol_offset.\n  rewrite (transform_partial_program_main _ _ TRANSF).\n  rewrite symbols_preserved.\n  unfold ge; rewrite H1. auto.\nQed.\n\nLemma transf_final_states:\n  forall st1 st2 r,\n  match_states st1 st2 -> Mach.final_state st1 r -> Asm.final_state st2 r.\nProof.\n  intros. inv H0. inv H. constructor. auto.\n  compute in H1. inv H1.\n  generalize (preg_val _ _ _ AX AG). rewrite H2. intros LD; inv LD. auto.\nQed.\n\nTheorem transf_program_correct:\n  forward_simulation (Mach.semantics return_address_offset prog) (Asm.semantics tprog).\nProof.\n  eapply forward_simulation_star with (measure := measure).\n  eexact symbols_preserved.\n  eexact transf_initial_states.\n  eexact transf_final_states.\n  exact step_simulation.\nQed.\n\nEnd PRESERVATION.\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/ia32/Asmgenproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2609440488771021}}
{"text": "From mathcomp Require Import\n  ssreflect ssrfun ssrbool ssrnat eqtype seq choice fintype.\n\nFrom deriving Require Import base.\n\nFrom Coq Require Import ZArith NArith String Ascii.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* Backwards compatibility for hint locality attributes *)\nSet Warnings \"-unsupported-attributes\".\n\nOpen Scope deriving_scope.\n\nRecord fun_split n (R : Type) (T : R) (Ts : fin n -> R) := FunSplit {\n  fs_fun :> fin n.+1 -> R;\n  _      :  T = fs_fun None;\n  _      :  forall i, Ts i = fs_fun (Some i);\n}.\n\nDefinition fsE1 n R T Ts (TTs : @fun_split n R T Ts) : T = TTs None :=\n  let: FunSplit _ e _ := TTs in e.\n\nDefinition fsE2 n R T Ts (TTs : @fun_split n R T Ts) :\n  forall i, Ts i = TTs (Some i) :=\n  let: FunSplit _ _ e := TTs in e.\n\nCanonical fun_split1 n R (TTs : fin n.+1 -> R) :=\n  @FunSplit n R (TTs None) (fun i => TTs (Some i)) TTs erefl (fun=> erefl).\n\n#[global]\nHint Unfold fs_fun : deriving.\n#[global]\nHint Unfold fsE1 : deriving.\n#[global]\nHint Unfold fsE2 : deriving.\n#[global]\nHint Unfold fun_split1 : deriving.\n\nSection LiftClass.\n\nImport PolyType.\n\nVariables (K : Type) (sort : K -> Type).\n\nDefinition eq_class X := {sX : K | sort sX = X}.\n\nRecord tagged_sort n := TaggedSort {\n  untag_sort :> fin n -> Type;\n}.\n\nDefinition ts_nil_tag n Ts := @TaggedSort n Ts.\nCanonical ts_cons_tag n Ts := @ts_nil_tag n Ts.\n\nRecord lift_class n := LiftClass {\n  lift_class_sort  :> tagged_sort n;\n  _ :  forall i, eq_class (lift_class_sort i);\n}.\n\nDefinition lift_class_class n (sTs : lift_class n) :=\n  let: LiftClass _ cTs := sTs return forall i, eq_class (sTs i) in cTs.\n\nCanonical nil_lift_class f :=\n  @LiftClass 0 (ts_nil_tag f) (fun i => match i with end).\n\nCanonical cons_lift_class n\n  (sT : K) (f : lift_class n) (g : fun_split (sort sT) f) :=\n  @LiftClass n.+1 (ts_cons_tag g)\n             (fun i =>\n                match i with\n                | None   => cast eq_class (fsE1 g)   (exist _ sT erefl)\n                | Some i => cast eq_class (fsE2 g i) (lift_class_class f i)\n                end).\n\nDefinition lift_class_proj n cK\n           (class : forall sT, cK (sort sT))\n           (sTs : lift_class n) (i : fin n)\n  : cK (sTs i) :=\n  cast cK (svalP (lift_class_class sTs i)) (class _).\n\nEnd LiftClass.\n\n#[global]\nHint Unfold eq_class : deriving.\n#[global]\nHint Unfold untag_sort : deriving.\n#[global]\nHint Unfold ts_nil_tag : deriving.\n#[global]\nHint Unfold ts_cons_tag : deriving.\n#[global]\nHint Unfold lift_class_sort : deriving.\n#[global]\nHint Unfold lift_class_class : deriving.\n#[global]\nHint Unfold nil_lift_class : deriving.\n#[global]\nHint Unfold cons_lift_class : deriving.\n#[global]\nHint Unfold lift_class_proj : deriving.\n\nArguments lift_class_proj {K sort n cK} class sTs i.\n\nNotation \"T -F> S\" :=\n  (forall i, T i -> S i)\n  (at level 30, only parsing, no associativity)\n  : deriving_scope.\n\nNotation \"T *F S\"  :=\n  (fun i => T i * S i)%type\n  (at level 20, only parsing, no associativity)\n  : deriving_scope.\n\nSet Universe Polymorphism.\n\nSection Signature.\n\nImport PolyType.\n\nVariable n : nat.\nImplicit Types (T S : fin n -> Type).\n\nVariant arg := NonRec of Type | Rec of fin n.\n\nDefinition type_of_arg T (A : arg) : Type :=\n  match A with\n  | NonRec X => X\n  | Rec i => T i\n  end.\n\nDefinition type_of_arg_map T S (f : T -F> S) A :\n  type_of_arg T A -> type_of_arg S A :=\n  match A with\n  | NonRec X => id\n  | Rec i => f i\n  end.\n\nDefinition is_rec A := if A is Rec _ then true else false.\n\nDefinition arity        := seq arg.\nDefinition signature    := seq arity.\nDefinition declaration  := fin n -> signature.\n\nIdentity Coercion seq_of_arity : arity >-> seq.\nIdentity Coercion seq_of_sig   : signature >-> seq.\n\nDefinition empty_decl : declaration :=\n  fun _ => [::].\n\nDefinition add_arity (D : declaration) i As : declaration :=\n  fun j => if leq_fin i j is inl _ then As :: D i\n           else D j.\n\nDefinition add_arity_ind (P : fin n -> signature -> Type) D i As j :\n  P i (As :: D i) -> P j (D j) -> P j (add_arity D i As j) :=\n  fun H1 H2 =>\n    match leq_fin i j\n    as X\n    return P j (if X is inl _ then As :: D i else D j) with\n    | inl e => cast (fun k => P k (As :: D i)) e H1\n    | inr _ => H2\n    end.\n\nVariables (K : Type) (sort : K -> Type).\n\nDefinition arg_class A :=\n  if A is NonRec T then eq_class sort T else unit.\n\nRecord arg_inst := ArgInst {\n  arg_inst_sort  :> arg;\n  arg_inst_class :  arg_class arg_inst_sort\n}.\nArguments ArgInst : clear implicits.\n\nDefinition arity_class (As : arity) :=\n  hlist' arg_class As.\n\nRecord arity_inst := ArityInst {\n  arity_inst_sort  :> arity;\n  arity_inst_class :  arity_class arity_inst_sort;\n}.\nArguments ArityInst : clear implicits.\n\nDefinition sig_class (Σ : signature) :=\n  hlist' arity_class Σ.\n\nRecord sig_inst := SigInst {\n  sig_inst_sort  :> signature;\n  sig_inst_class :  sig_class sig_inst_sort;\n}.\nArguments SigInst : clear implicits.\n\nRecord tagged_decl k := TaggedDecl {\n  untag_decl :> fin k -> signature;\n}.\n\nRecord decl_inst k := DeclInst {\n  decl_inst_sort  :> tagged_decl k;\n  _               :  forall i, sig_class (decl_inst_sort i)\n}.\nArguments DeclInst : clear implicits.\n\nDefinition decl_inst_class k (d : decl_inst k) :\n  forall i, sig_class (@decl_inst_sort k d i) :=\n  let: DeclInst _ d := d in d.\n\nImplicit Types (A : arg) (As : arity) (Σ : signature).\nImplicit Types (Ai : arg_inst) (Asi : arity_inst) (Σi : sig_inst).\n\nCanonical NonRec_arg_inst sX :=\n  ArgInst (NonRec (sort sX)) (exist _ sX erefl).\n\nCanonical Rec_arg_inst i :=\n  ArgInst (Rec i) tt.\n\nCanonical nth_fin_arg_inst Asi (i : fin (size Asi)) :=\n  ArgInst (nth_fin i) (arity_inst_class Asi i).\n\nCanonical nil_arity_inst :=\n  ArityInst nil tt.\n\nCanonical cons_arity_inst Ai Asi :=\n  ArityInst (arg_inst_sort Ai :: arity_inst_sort Asi)\n            (arg_inst_class Ai ::: arity_inst_class Asi).\n\nCanonical nth_fin_arity_inst Σi (i : fin (size Σi)) :=\n  ArityInst (nth_fin i) (sig_inst_class Σi i).\n\nCanonical nil_sig_inst :=\n  SigInst nil tt.\n\nCanonical cons_sig_inst Asi Σi :=\n  SigInst (arity_inst_sort Asi :: sig_inst_sort Σi)\n          (arity_inst_class Asi ::: sig_inst_class Σi).\n\nDefinition nil_decl_tag k (D : fin k -> signature) := TaggedDecl D.\nCanonical cons_decl_tag k (D : fin k -> signature) := nil_decl_tag D.\n\nCanonical nil_decl_inst f :=\n  DeclInst 0 (nil_decl_tag f) (fun i => match i with end).\n\nCanonical cons_decl_inst k Σi Di\n  (D : fun_split (sig_inst_sort Σi) (untag_decl (@decl_inst_sort k Di))) :=\n  DeclInst k.+1\n           (cons_decl_tag (fs_fun D))\n           (fun i =>\n              match i with\n              | None => cast sig_class (fsE1 D) (sig_inst_class Σi)\n              | Some i => cast sig_class (fsE2 D i) (@decl_inst_class k Di i)\n              end).\n\nDefinition arity_rec (P : arity -> Type)\n  (Pnil    : P [::])\n  (PNonRec : forall (sX : K) (As : arity), P As -> P (NonRec (sort sX) :: As))\n  (PRec    : forall i        (As : arity), P As -> P (Rec i            :: As)) :=\n  fix arity_rec As : arity_class As -> P As :=\n    match As with\n    | [::]               => fun cAs =>\n      Pnil\n    | NonRec X :: As => fun cAs =>\n      cast (fun X => P (NonRec X :: As)) (svalP cAs.(hd))\n           (PNonRec (sval cAs.(hd)) As (arity_rec As cAs.(tl)))\n    | Rec i :: As    => fun cAs =>\n      PRec i As (arity_rec As cAs.(tl))\n    end.\n\nLemma arity_ind (P : forall As, hlist' arg_class As -> Type)\n  (Pnil : P [::] tt)\n  (PNonRec : forall sX As cAs,\n      P As cAs -> P (NonRec (sort sX) :: As) (exist _ sX erefl ::: cAs))\n  (PRec : forall i As cAs,\n      P As cAs -> P (Rec i :: As) (tt ::: cAs))\n  As cAs : P As cAs.\nProof.\nelim: As cAs=> [|[X|i] As IH] => /= [[]|[[xS e] cAs]|[[] cAs]] //.\n  by case: X / e cAs => ?; apply: PNonRec.\nby apply: PRec.\nQed.\n\nEnd Signature.\n\n#[global]\nHint Unfold type_of_arg : deriving.\n#[global]\nHint Unfold type_of_arg_map : deriving.\n#[global]\nHint Unfold is_rec : deriving.\n#[global]\nHint Unfold arity : deriving.\n#[global]\nHint Unfold signature : deriving.\n#[global]\nHint Unfold declaration : deriving.\n#[global]\nHint Unfold empty_decl : deriving.\n#[global]\nHint Unfold add_arity : deriving.\n#[global]\nHint Unfold add_arity_ind : deriving.\n#[global]\nHint Unfold arg_class : deriving.\n#[global]\nHint Unfold arg_inst_sort : deriving.\n#[global]\nHint Unfold arg_inst_class : deriving.\n#[global]\nHint Unfold arity_class : deriving.\n#[global]\nHint Unfold arity_inst_sort : deriving.\n#[global]\nHint Unfold arity_inst_class : deriving.\n#[global]\nHint Unfold sig_class : deriving.\n#[global]\nHint Unfold sig_inst_sort : deriving.\n#[global]\nHint Unfold sig_inst_class : deriving.\n#[global]\nHint Unfold untag_decl : deriving.\n#[global]\nHint Unfold decl_inst_sort : deriving.\n#[global]\nHint Unfold decl_inst_class : deriving.\n#[global]\nHint Unfold NonRec_arg_inst : deriving.\n#[global]\nHint Unfold Rec_arg_inst : deriving.\n#[global]\nHint Unfold nth_fin_arg_inst : deriving.\n#[global]\nHint Unfold nil_arity_inst : deriving.\n#[global]\nHint Unfold cons_arity_inst : deriving.\n#[global]\nHint Unfold nil_sig_inst : deriving.\n#[global]\nHint Unfold cons_sig_inst : deriving.\n#[global]\nHint Unfold nil_decl_tag : deriving.\n#[global]\nHint Unfold cons_decl_tag : deriving.\n#[global]\nHint Unfold nil_decl_inst : deriving.\n#[global]\nHint Unfold cons_decl_inst : deriving.\n#[global]\nHint Unfold arity_rec : deriving.\n\nDefinition arg_class_map\n  n K1 K2 (sort1 : K1 -> Type) (sort2 : K2 -> Type)\n  (f : K1 -> K2) (p : forall cT, sort2 (f cT) = sort1 cT) (A : arg n) :\n  arg_class sort1 A -> arg_class sort2 A :=\n  match A with\n  | NonRec T => fun cT =>\n    PolyType.exist _\n      (f (PolyType.sval cT)) (p (PolyType.sval cT) * PolyType.svalP cT)\n  | Rec i    => fun _  => tt\n  end.\n\n#[global]\nHint Unfold arg_class_map : deriving.\n\nDefinition pack_decl_inst\n  n (D : declaration n) (Di : decl_inst n Equality.sort n)\n  of phant_id D (untag_decl (decl_inst_sort Di)) := Di.\n\nUnset Universe Polymorphism.\n\nArguments add_arity_ind {n} P D i As j H1 H2.\nArguments empty_decl {n}.\nArguments arity_rec {n K} _ _ _ _ _.\n\nModule Ind.\n\nSection Basic.\n\nVariable n : nat.\nImplicit Types (A : arg n) (As : arity n) (Σ : signature n).\nImplicit Types (D : declaration n).\nImplicit Types (T S : fin n -> Type).\n\nImport PolyType.\n\nDefinition Cidx D i := fin (size (D i)).\nArguments Cidx : clear implicits.\n\nDefinition args D T i (j : Cidx D i) : Type :=\n  hlist' (type_of_arg T) (nth_fin j).\n\nDefinition args_map D T S (f : T -F> S) i j (xs : @args D T i j) :\n  args S j :=\n  hmap' (type_of_arg_map f) xs.\n\nDefinition constructors D T :=\n  forall (Ti : fin n) (Ci : Cidx D Ti),\n    hfun' (type_of_arg T) (nth_fin Ci) (T Ti).\n\nDefinition empty_cons T : constructors empty_decl T :=\n  fun Ti Ci => match Ci with end.\n\nDefinition add_cons D T (Cs : constructors D T) Ti As\n  (C : hfun' (type_of_arg T) As (T Ti))\n  : constructors (add_arity D Ti As) T :=\n  fun Ti' =>\n    add_arity_ind\n      (fun Ti' Σ =>\n         forall Ci : fin (size Σ),\n           hfun' (type_of_arg T) (nth_fin Ci) (T Ti'))\n      D Ti As Ti'\n      (fun Ci => if Ci is Some Ci then Cs Ti Ci else C)\n      (Cs Ti').\n\nFixpoint rec_branch' T S i As : Type :=\n  match As with\n  | NonRec X :: As => X          -> rec_branch' T S i As\n  | Rec    j :: As => T j -> S j -> rec_branch' T S i As\n  | [::]           => S i\n  end.\n\nDefinition rec_branch D T S i (j : Cidx D i) : Type :=\n  rec_branch' T S i (nth_fin j).\n\n\nDefinition recursor D T :=\n  forall S, hfun2 (@rec_branch D T S) (hlist1 (fun i => T i -> S i)).\n\nFixpoint rec_branch'_of_hfun' T S i As :\n  hfun' (type_of_arg (T *F S)) As (S i) -> rec_branch' T S i As :=\n  match As with\n  | NonRec R :: As => fun f x   => rec_branch'_of_hfun' (f x)\n  | Rec    j :: As => fun f x y => rec_branch'_of_hfun' (f (x, y))\n  | [::]           => fun f     => f\n  end.\n\nFixpoint hfun'_of_rec_branch' T S i As :\n  rec_branch' T S i As -> hfun' (type_of_arg (T *F S)) As (S i) :=\n  match As with\n  | NonRec R :: As => fun f x => hfun'_of_rec_branch' (f x)\n  | Rec    j :: As => fun f p => hfun'_of_rec_branch' (f p.1 p.2)\n  | [::]           => fun f   => f\n  end.\n\nCoercion hfun'_of_rec_branch' : rec_branch' >-> hfun'.\n\nLemma rec_branch_of_hfunK T S i As f xs :\n  @rec_branch'_of_hfun' T S i As f xs = f xs.\nProof. by elim: As f xs => [|[R|j] As IH] f //= [[x y] xs]. Qed.\n\nDefinition recursor_eq D T (Cs : constructors D T) (r : recursor D T) :=\n  forall S,\n  all_hlist2 (fun bs : hlist2 (rec_branch T S) =>\n  all_fin    (fun i  : fin n                   =>\n  all_fin    (fun j  : Cidx D i                =>\n  all_hlist  (fun xs : args T j                =>\n    r S bs _ (Cs i j xs) =\n    bs i j (args_map (fun k x => (x, r S bs k x)) xs))))).\n\nDefinition des_branch D T S i (j : Cidx D i) :=\n  hfun' (type_of_arg T) (nth_fin j) (S i).\n\nDefinition destructor D T :=\n  forall S, hfun2 (@des_branch D T S) (hlist1 (fun i => T i -> S i)).\n\nDefinition destructor_eq D T (Cs : constructors D T) (d : destructor D T) :=\n  forall S,\n  all_hlist2 (fun bs : hlist2 (des_branch T S) =>\n  all_fin    (fun i  : fin n                   =>\n  all_fin    (fun j  : Cidx D i                =>\n  all_hlist  (fun xs : args T j                =>\n    d S bs _ (Cs i j xs) = bs i j xs)))).\n\nDefinition rec_of_des_branch D T S i (j : Cidx D i) (b : des_branch T S j) :\n  rec_branch T S j :=\n  rec_branch'_of_hfun' (hcurry (fun xs => b (args_map (fun _ => fst) xs))).\n\nDefinition destructor_of_recursor D T (r : recursor D T) : destructor D T :=\n  fun S => hcurry2 (fun bs : hlist2 (@des_branch D T S) =>\n    r S (hmap2 (@rec_of_des_branch D T S) bs)).\n\nFixpoint ind_branch' T (P : forall i, T i -> Type) i As :\n  hfun' (type_of_arg T) As (T i) -> Type :=\n  match As with\n  | NonRec R :: As => fun C => forall x : R,            ind_branch' P (C x)\n  | Rec    j :: As => fun C => forall x : T j, P j x -> ind_branch' P (C x)\n  | [::]           => fun C => P i C\n  end.\n\nDefinition ind_branch D T P (Cs : constructors D T) i (j : Cidx D i) :=\n  @ind_branch' T P i (nth_fin j) (Cs i j).\n\nDefinition induction D T (Cs : constructors D T) :=\n  @hdfun n (fun i => T i -> Type) (fun P : hlist (fun i => T i -> Type) =>\n  hfun2 (@ind_branch D T P Cs) (hlist1 (fun i => forall x, P i x))).\n\nEnd Basic.\n\nModule Def.\n\nSet Primitive Projections.\nRecord class_of n sorts (decl : declaration n) := Class {\n  Cons      : constructors decl sorts;\n  rec       : recursor decl sorts;\n  case      : destructor decl sorts;\n  recE      : recursor_eq Cons rec;\n  caseE     : destructor_eq Cons case;\n  indP      : induction Cons;\n}.\n\nRecord type := Pack {\n  n : nat;\n  sorts : fin n -> Type;\n  decl : declaration n;\n  class : class_of sorts decl;\n}.\nUnset Primitive Projections.\n\nEnd Def.\n\nSection ClassDef.\n\nSet Primitive Projections.\nRecord mixin_of T := Mixin {\n  def  : Def.type;\n  idx  : fin (Def.n def);\n  idxE : T = Def.sorts idx;\n}.\nUnset Primitive Projections.\n\nRecord type := Pack {sort : Type; _ : mixin_of sort}.\nLocal Coercion sort : type >-> Sortclass.\nLocal Notation class_of := mixin_of.\n\nVariables (T : Type) (cT : type).\nDefinition class := let: Pack _ c as cT' := cT return class_of cT' in c.\nDefinition clone n Ts D cTs i iE :=\n  let sTs := @Mixin T (@Def.Pack n Ts D cTs) i iE in\n  fun & phant_id class sTs => @Pack T sTs.\nLet xT := let: Pack T _ := cT in T.\nNotation xclass := (class : class_of xT).\n\nEnd ClassDef.\n\nNotation class_of := mixin_of.\n\nModule Exports.\nIdentity Coercion hdfun_of_induction : induction >-> hdfun.\nCoercion Def.sorts : Def.type >-> Funclass.\nCoercion Def.class : Def.type >-> Def.class_of.\nNotation indDef := Def.type.\nNotation IndDef := Def.Pack.\nCoercion sort : type >-> Sortclass.\nCoercion class : type >-> class_of.\nCoercion def : class_of >-> indDef.\nNotation indType := type.\nNotation \"[ 'indType' 'of' T ]\" := (@clone T _ _ _ _ _ _ _ id)\n  (at level 0, format \"[ 'indType'  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd Ind.\nExport Ind.Exports.\n\nArguments Ind.Def.decl : clear implicits.\n\nClass find_idx n (Ts : fin n -> Type) (T : Type) i (e : T = Ts i) :=\n  make_find_idx { }.\nArguments find_idx : clear implicits.\nArguments make_find_idx {_ _ _ _ _}.\n\nDefinition find_idx_here n (Ts : fin n.+1 -> Type) :\n  find_idx n.+1 Ts (Ts None) None erefl := make_find_idx.\n\nDefinition find_idx_there n (Ts : fin n.+1 -> Type) T i e\n  (_ : find_idx n (fun i => Ts (Some i)) T i e) :\n  find_idx n.+1 Ts T (Some i) e :=\n  make_find_idx.\n\n#[global]\nHint Extern 1 (find_idx ?m ?Ts ?T _ _) =>\n  match eval hnf in m with\n  | ?n.+1 => eapply (@find_idx_here n Ts)\n  end : typeclass_instances.\n\n#[global]\nHint Extern 2 (find_idx ?m ?Ts ?T _ _) =>\n  match eval hnf in m with\n  | ?n.+1 => eapply (@find_idx_there n Ts)\n  end : typeclass_instances.\n\nDefinition pack_indType\n  T (Ts : indDef) i e\n  of find_idx (Ind.Def.n Ts) Ts T i e :=\n  Ind.Pack (@Ind.Mixin T Ts i e).\n\nNotation IndType T Ts := (@pack_indType T Ts _ _ _).\n\n#[global]\nHint Unfold Ind.Cidx : deriving.\n#[global]\nHint Unfold Ind.args : deriving.\n#[global]\nHint Unfold Ind.args_map : deriving.\n#[global]\nHint Unfold Ind.constructors : deriving.\n#[global]\nHint Unfold Ind.empty_cons : deriving.\n#[global]\nHint Unfold Ind.add_cons : deriving.\n#[global]\nHint Unfold Ind.rec_branch' : deriving.\n#[global]\nHint Unfold Ind.rec_branch : deriving.\n#[global]\nHint Unfold Ind.recursor : deriving.\n#[global]\nHint Unfold Ind.rec_branch'_of_hfun' : deriving.\n#[global]\nHint Unfold Ind.hfun'_of_rec_branch' : deriving.\n#[global]\nHint Unfold Ind.recursor_eq : deriving.\n#[global]\nHint Unfold Ind.des_branch : deriving.\n#[global]\nHint Unfold Ind.destructor : deriving.\n#[global]\nHint Unfold Ind.destructor_eq : deriving.\n#[global]\nHint Unfold Ind.rec_of_des_branch : deriving.\n#[global]\nHint Unfold Ind.destructor_of_recursor : deriving.\n#[global]\nHint Unfold Ind.ind_branch' : deriving.\n#[global]\nHint Unfold Ind.ind_branch : deriving.\n#[global]\nHint Unfold Ind.induction : deriving.\n#[global]\nHint Unfold Ind.Def.Cons : deriving.\n#[global]\nHint Unfold Ind.Def.rec : deriving.\n#[global]\nHint Unfold Ind.Def.case : deriving.\n#[global]\nHint Unfold Ind.Def.n : deriving.\n#[global]\nHint Unfold Ind.Def.sorts : deriving.\n#[global]\nHint Unfold Ind.Def.decl : deriving.\n#[global]\nHint Unfold Ind.Def.class : deriving.\n#[global]\nHint Unfold Ind.class : deriving.\n#[global]\nHint Unfold Ind.def : deriving.\n#[global]\nHint Unfold Ind.idx : deriving.\n#[global]\nHint Unfold Ind.idxE : deriving.\n#[global]\nHint Unfold Ind.sort : deriving.\n#[global]\nHint Unfold Ind.clone : deriving.\n#[global]\nHint Unfold find_idx_here : deriving.\n#[global]\nHint Unfold find_idx_there : deriving.\n#[global]\nHint Unfold pack_indType : deriving.\n\nModule IndF.\n\nSection FunctorDef.\n\nVariables (n : nat) (D : declaration n).\n\nImplicit Types (T S : fin n -> Type).\n\nNotation size := PolyType.size.\n\nRecord fobj T (i : fin n) := Cons {\n  constr : Ind.Cidx D i;\n  args : hlist' (type_of_arg T) (nth_fin constr)\n}.\n\nArguments Cons {_ i} _ _.\n\nLocal Notation F := fobj.\n\nDefinition fmap T S (f : T -F> S) i (x : F T i) : F S i :=\n  Cons (constr x) (hmap' (type_of_arg_map f) (args x)).\n\nLemma fmap_eq T S (f g : T -F> S) :\n  (forall i x, f i x = g i x) ->\n  (forall i (x : F T i), fmap f x = fmap g x).\nProof.\nmove=> e i [j args]; congr Cons; apply: hmap_eq => /= k.\nby case: (nth_fin k).\nQed.\n\nLemma fmap1 T i : @fmap T T (fun _ => id) i =1 id.\nProof.\nmove=> [j args] /=; congr Cons; rewrite -[RHS]hmap1.\nby apply: hmap_eq=> /= k; case: (nth_fin k).\nQed.\n\nLemma fmap_comp T S R (f : T -F> S) (g : S -F> R) i :\n  @fmap _ _ (fun j x => g j (f j x)) i =1\n  @fmap _ _ g i \\o @fmap _ _ f i.\nProof.\nmove=> [j args] /=; congr Cons; rewrite /= /hmap' hmap_comp.\nby apply: hmap_eq=> /= k; case: (nth_fin k).\nQed.\n\nLemma inj T (i : fin n) (j : Ind.Cidx D i)\n  (a b : hlist' (type_of_arg T) (nth_fin j)) :\n  Cons j a = Cons j b -> a = b.\nProof.\npose get x :=\n  if leq_fin (constr x) j is inl e then\n    cast (fun j : Ind.Cidx D i =>\n            hlist' (type_of_arg T) (nth_fin j)) e (args x)\n  else a.\nby move=> /(congr1 get); rewrite /get /= leq_finii /=.\nQed.\n\nEnd FunctorDef.\n\nSection TypeDef.\n\nVariable (T : indDef).\n\nNotation D := (Ind.Def.decl T).\nNotation F := (@fobj _ D).\n\nArguments Cons {n D T i} _ _.\n\nDefinition Roll i (x : F T i) : T i :=\n  @Ind.Def.Cons _ _ _ T i (constr x) (args x).\n\nDefinition rec_branches_of_fun S (body : F (T *F S) -F> S) :\n  hlist2 (@Ind.rec_branch _ D T S) :=\n  hlist_of_fun (fun i =>\n  hlist_of_fun (fun j : Ind.Cidx D i =>\n    Ind.rec_branch'_of_hfun'\n      (hcurry\n         (fun l => body i (Cons j l))))).\n\nDefinition rec S (body : F (T *F S) -F> S) :=\n  @Ind.Def.rec _ _ _ T S (rec_branches_of_fun body).\n\nDefinition lift_type R i : fin (Ind.Def.n T) -> Type :=\n  fun j => if leq_fin i j is inl e then R else unit.\n\nDefinition lift_typeE R i : lift_type R i i = R :=\n  congr1 (fun r => if r is inl e then R else unit) (leq_finii i).\n\nDefinition lift_type_of R i j (f : i = j -> R) : lift_type R i j :=\n  match leq_fin i j\n  as r\n  return if r is inl e then R else unit\n  with\n  | inl e => f e\n  | inr _ => tt\n  end.\n\nDefinition des_branches_of_fun i R (body : F T i -> R) :\n  hlist2 (@Ind.des_branch _ D T (lift_type R i)) :=\n  hlist_of_fun (fun i' =>\n  hlist_of_fun (fun j : Ind.Cidx D i' =>\n    hcurry (fun l => @lift_type_of R i i' (fun e => body (cast (F T) e^-1 (Cons j l)))))).\n\nDefinition case i R (body : F T i -> R) x :=\n  cast id (lift_typeE R i)\n    (@Ind.Def.case _ _ _ T _ (des_branches_of_fun body) i x).\n\nLemma recE S f i (a : F T i) :\n  @rec S f i (Roll a) =\n  f i (fmap (fun j (x : T j) => (x, rec f j x)) a).\nProof.\ncase: a=> [j args]; have := Ind.Def.recE T S.\nmove/all_hlist2P/(_ (rec_branches_of_fun f)).\nmove/all_finP/(_ i).\nmove/all_finP/(_ j).\nmove/all_hlistP/(_ args).\nrewrite /rec_branches_of_fun hnth_of_fun.\nrewrite /rec /Roll => -> /=.\nby rewrite /= hnth_of_fun Ind.rec_branch_of_hfunK hcurryK.\nQed.\n\nLemma caseE i R f (a : F T i) : case f (Roll a) = f a :> R.\nProof.\ncase: a => [j args]; have := Ind.Def.caseE T (lift_type R i).\nmove/all_hlist2P/(_ (des_branches_of_fun f)).\nmove/all_finP/(_ i).\nmove/all_finP/(_ j).\nmove/all_hlistP/(_ args).\nrewrite /des_branches_of_fun hnth_of_fun.\nrewrite /case /Roll => -> /=.\nrewrite /lift_type /lift_typeE /lift_type_of hnth_of_fun hcurryK /=.\ncase: (leq_fin i i) (leq_finii i)=> // e.\nrewrite (eq_axiomK e) => {}e.\nby rewrite (eq_axiomK e) /=.\nQed.\n\nLemma indP P :\n  (forall i (a : F (fun j => {x & P j x}) i),\n    P i (Roll (fmap (fun _ => tag) a))) ->\n  forall i x, P i x.\nProof.\nmove=> IH.\npose Q := hlist_of_fun P.\npose Q_of_P i a : P i a -> Q i a :=\n  cast id (congr1 (fun F => F a) (hnth_of_fun P i))^-1.\npose P_of_Q i a : Q i a -> P i a :=\n  cast id (congr1 (fun F => F a) (hnth_of_fun P i)).\npose TP_of_TQ i x := Tagged (P i) (P_of_Q i (tag x) (tagged x)).\nhave Q_of_PK i a : cancel (Q_of_P i a) (P_of_Q i a) := castKV _.\nhave P_of_QK i a : cancel (P_of_Q i a) (Q_of_P i a) := castK  _.\nhave {}IH i (a : F (fun j => {x & Q j x}) i) :\n    Q i (Roll (fmap (fun _ => tag) a)).\n  rewrite (_ : fmap _ a = fmap (fun _ => tag) (fmap TP_of_TQ a)); last first.\n    by rewrite -[RHS]fmap_comp; apply: fmap_eq=> ? [].\n  by apply: (Q_of_P); apply: IH.\nmove=> i x {P_of_QK Q_of_PK Q_of_P TP_of_TQ}; apply: P_of_Q.\nmove: {P} Q IH i x.\nrewrite /Roll; case: (T) => n S D [/= Cs _ _ _ _ indP] P.\nhave {}indP :\n    (forall i j, Ind.ind_branch' P (Cs i j)) ->\n    (forall i x, P i x).\n  move=> hyps i x.\n  pose bs : hlist2 (Ind.ind_branch P Cs) :=\n    hlist_of_fun (fun i => hlist_of_fun (fun j => hyps i j)).\n  exact: (hdapp indP P bs i x).\nmove=> hyps; apply: indP=> i j.\nhave {}hyps:\n  forall args : hlist' (type_of_arg (fun k => {x & P k x})) (nth_fin j),\n    P i (Cs i j (hmap' (type_of_arg_map (fun _ => tag)) args)).\n  by move=> args; move: (hyps i (Cons j args)).\nmove: (Cs i j) hyps; rewrite /fnth.\nelim: (nth_fin j)=> [|[R|k] As IH] /=.\n- by move=> C /(_ tt).\n- move=> C hyps x; apply: IH=> args; exact: (hyps (x ::: args)).\n- move=> constr hyps x H; apply: IH=> args.\n  exact: (hyps (existT _ x H ::: args)).\nQed.\n\nDefinition unroll i := @case i _ id.\n\nLemma RollK i : cancel (@Roll i) (@unroll i).\nProof. by move=> x; rewrite /unroll caseE. Qed.\n\nLemma Roll_inj i : injective (@Roll i).\nProof. exact: can_inj (@RollK i). Qed.\n\nLemma unrollK i : cancel (@unroll i) (@Roll i).\nProof. by elim/indP: i / => i a; rewrite RollK. Qed.\n\nLemma unroll_inj i : injective (@unroll i).\nProof. exact: can_inj (@unrollK i). Qed.\n\nEnd TypeDef.\n\nEnd IndF.\n\n#[global]\nHint Unfold IndF.constr : deriving.\n#[global]\nHint Unfold IndF.args : deriving.\n#[global]\nHint Unfold IndF.fmap : deriving.\n#[global]\nHint Unfold IndF.Roll : deriving.\n#[global]\nHint Unfold IndF.rec_branches_of_fun : deriving.\n#[global]\nHint Unfold IndF.rec : deriving.\n#[global]\nHint Unfold IndF.lift_type : deriving.\n#[global]\nHint Unfold IndF.lift_typeE : deriving.\n#[global]\nHint Unfold IndF.lift_type_of : deriving.\n#[global]\nHint Unfold IndF.des_branches_of_fun : deriving.\n#[global]\nHint Unfold IndF.case : deriving.\n#[global]\nHint Unfold IndF.unroll : deriving.\n\nSection InferInstances.\n\nImport PolyType.\n\nClass infer_arity\n  n (T : fin n -> Type) (P : forall i, T i -> Type)\n  (branchT : Type) (As : arity n) (i : fin n)\n  (C : hfun' (type_of_arg T) As (T i)) : Type.\nArguments infer_arity : clear implicits.\n\nInstance infer_arity_end\n  n T P i (x : T i) :\n  infer_arity n T P (P i x) [::] i x.\nDefined.\n\nInstance infer_arity_rec\n  n Ts P j\n  (branchT : Ts j -> Type)\n  i (As : arity n)\n  (C : Ts j -> hfun' (type_of_arg Ts) As (Ts i))\n  (_ : forall x, infer_arity n Ts P (branchT x) As i (C x)) :\n  infer_arity n Ts P (forall x, P j x -> branchT x) (Rec j :: As) i C.\nDefined.\n\nInstance infer_arity_nonrec\n  n T P S\n  (branchT : S -> Type) i As (C : S -> hfun' (type_of_arg T) As (T i))\n  (_ : forall x, infer_arity n T P (branchT x) As i (C x)) :\n  infer_arity n T P (forall x, branchT x) (NonRec n S :: As) i C.\nDefined.\n\nClass infer_decl\n  n T (P : forall i, T i -> Type)\n  (elimT : Type) (D : declaration n) (Cs : Ind.constructors D T) : Type.\nArguments infer_decl : clear implicits.\n\nGlobal Instance infer_decl_end n T P :\n  infer_decl n T P\n             (hlist1 (fun i => forall (x : T i), P i x))\n             empty_decl\n             (@Ind.empty_cons _ _).\nDefined.\n\nGlobal Instance infer_decl_cons n T P\n  (branchT : Type) Ti As C\n  (_ : infer_arity n T P branchT As Ti C)\n  (elimT : Type) D Cs\n  (_ : infer_decl n T P elimT D Cs)\n  : infer_decl n T P (branchT -> elimT) (add_arity D Ti As) (Ind.add_cons Cs C).\nDefined.\n\nClass read_rect (rectT : Type) (rect : rectT)\n  (n : nat) (Ts : fin n -> Type)\n  (rectT' : (forall i, Ts i -> Type) -> Type)\n  (rect' : forall Ps, rectT' Ps).\nArguments read_rect : clear implicits.\n\nGlobal Instance read_rect_type\n  (T : Type) (rectT : (T -> Type) -> Type) (rect : forall P, rectT P)\n  n Ts rectT' rect'\n  (_ : forall P, read_rect (rectT P) (rect P) n Ts (rectT' P) (rect' P))\n  : read_rect (forall P, rectT P) rect n.+1\n              (fcons T Ts)\n              (fun Ps => rectT' (Ps None) (fun i => Ps (Some i)))\n              (fun Ps => rect' (Ps None) (fun i => Ps (Some i))) | 1.\nDefined.\n\nGlobal Instance read_rect_done rectT rect :\n  read_rect rectT rect 0 (fnil Type) (fun _ => rectT) (fun _ => rect) | 2.\nDefined.\n\nClass bless_rect\n  n Ts (D : declaration n) (Cs : Ind.constructors D Ts)\n  (rectT : (forall i, Ts i -> Type) -> Type)\n  (rect  : forall P, rectT P)\n  (rect' : Ind.recursor D Ts).\nArguments bless_rect : clear implicits.\n\nClass infer_ind rectT (rect : rectT)\n  n Ts (D : declaration n) (Cs : Ind.constructors D Ts)\n  (rectT' : (forall i, Ts i -> Type) -> Type) (rect' : forall P, rectT' P)\n  (rect'' : Ind.recursor D Ts).\nArguments infer_ind : clear implicits.\n\nGlobal Instance do_infer_ind rectT rect\n  n Ts rectT' rect'\n  (_ : read_rect rectT rect n Ts rectT' rect')\n  D Cs\n  (_ : forall P, infer_decl n Ts P (rectT' P) D Cs)\n  rect''\n  (_ : bless_rect n Ts D Cs rectT' rect' rect'')\n  : infer_ind rectT rect n Ts D Cs rectT' rect' rect''.\nDefined.\n\nEnd InferInstances.\n\nArguments infer_arity : clear implicits.\nArguments infer_decl : clear implicits.\nArguments read_rect : clear implicits.\nArguments bless_rect : clear implicits.\nArguments infer_ind : clear implicits.\n\n#[global]\nHint Unfold infer_arity_end : deriving.\n#[global]\nHint Unfold infer_arity_rec : deriving.\n#[global]\nHint Unfold infer_arity_nonrec : deriving.\n#[global]\nHint Unfold infer_decl_end : deriving.\n#[global]\nHint Unfold infer_decl_cons : deriving.\n#[global]\nHint Unfold read_rect_type : deriving.\n#[global]\nHint Unfold read_rect_done : deriving.\n#[global]\nHint Unfold do_infer_ind : deriving.\n\nLtac infer_arity :=\n  cbv beta;\n  match goal with\n  | |- infer_arity ?n ?Ts ?Ps (?Ps ?i ?x) _ _ _ =>\n    exact (@infer_arity_end n Ts Ps i x)\n  | |- infer_arity ?n ?Ts ?Ps (forall x, ?Ps ?j x -> @?branchT x) _ _ _ =>\n    eapply (@infer_arity_rec n Ts Ps j branchT)\n  | |- infer_arity ?n ?Ts ?Ps (forall x : ?S, @?branchT x) _ _ _ =>\n    eapply (@infer_arity_nonrec n Ts Ps S branchT)\n  end.\n\n#[global]\nHint Extern 0 (infer_arity _ _ _ _ _ _ _) => infer_arity : typeclass_instances.\n\nLtac infer_decl :=\n  cbv beta;\n  match goal with\n  | |- infer_decl ?n ?Ts ?Ps (?branchT -> ?rectT) _ _ =>\n    eapply (@infer_decl_cons n Ts Ps branchT _ _ _ _ rectT)\n  | |- infer_decl ?n ?Ts ?Ps _ _ _ =>\n    eapply (@infer_decl_end n Ts Ps)\n  end.\n\n#[global]\nHint Extern 0 (infer_decl _ _ _ _ _ _) => infer_decl : typeclass_instances.\n\nLtac bless_rect :=\n  cbv beta;\n  match goal with\n  | |- bless_rect ?n ?Ts ?D ?Cs ?rectT ?rect _ =>\n     exact (@Build_bless_rect n Ts D Cs rectT rect\n                             (fun P => rect (fun i _ => P i)))\n  end.\n\n#[global]\nHint Extern 0 (bless_rect _ _ _ _ _ _ _) => bless_rect : typeclass_instances.\n\nModule IndEqType.\n\nRecord type := Pack {\n  n         : nat;\n  sorts     : fin n -> Type;\n  decl      : declaration n;\n  eq_class  : forall i, Equality.class_of (sorts i);\n  ind_class : Ind.Def.class_of sorts decl;\n}.\n\nDefinition eqType T i := Equality.Pack (@eq_class T i).\nDefinition indDef T := Ind.Def.Pack (ind_class T).\n\nModule Import Exports.\nNotation indEqType := type.\nNotation IndEqType := Pack.\nCoercion sorts : type >-> Funclass.\nCanonical eqType.\nCoercion indDef : type >-> Ind.Def.type.\nCanonical indDef.\nEnd Exports.\n\nEnd IndEqType.\n\nExport IndEqType.Exports.\n\n#[global]\nHint Unfold IndEqType.n : deriving.\n#[global]\nHint Unfold IndEqType.sorts : deriving.\n#[global]\nHint Unfold IndEqType.decl : deriving.\n#[global]\nHint Unfold IndEqType.eq_class : deriving.\n#[global]\nHint Unfold IndEqType.ind_class : deriving.\n#[global]\nHint Unfold IndEqType.eqType : deriving.\n#[global]\nHint Unfold IndEqType.indDef : deriving.\n\nModule IndChoiceType.\n\nRecord type := Pack {\n  n            : nat;\n  sorts        : fin n -> Type;\n  decl         : declaration n;\n  choice_class : forall i, Choice.class_of (sorts i);\n  ind_class    : Ind.Def.class_of sorts decl;\n}.\n\nDefinition eqType T i := Equality.Pack (@choice_class T i).\nDefinition choiceType T i := Choice.Pack (@choice_class T i).\nDefinition indDef T := Ind.Def.Pack (ind_class T).\n\nModule Import Exports.\nNotation indChoiceType := type.\nNotation IndChoiceType := Pack.\nCoercion sorts : type >-> Funclass.\nCanonical eqType.\nCanonical choiceType.\nCoercion indDef : type >-> Ind.Def.type.\nCanonical indDef.\nEnd Exports.\n\nEnd IndChoiceType.\n\nExport IndChoiceType.Exports.\n\n#[global]\nHint Unfold IndChoiceType.n : deriving.\n#[global]\nHint Unfold IndChoiceType.sorts : deriving.\n#[global]\nHint Unfold IndChoiceType.decl : deriving.\n#[global]\nHint Unfold IndChoiceType.choice_class : deriving.\n#[global]\nHint Unfold IndChoiceType.ind_class : deriving.\n#[global]\nHint Unfold IndChoiceType.eqType : deriving.\n#[global]\nHint Unfold IndChoiceType.choiceType : deriving.\n#[global]\nHint Unfold IndChoiceType.indDef : deriving.\n\nModule IndCountType.\n\nRecord type := Pack {\n  n           : nat;\n  sorts       : fin n -> Type;\n  decl        : declaration n;\n  count_class : forall i, Countable.class_of (sorts i);\n  ind_class   : Ind.Def.class_of sorts decl;\n}.\n\nDefinition eqType T i := Equality.Pack (@count_class T i).\nDefinition choiceType T i := Choice.Pack (@count_class T i).\nDefinition countType T i := Countable.Pack (@count_class T i).\nDefinition indDef T := Ind.Def.Pack (ind_class T).\n\nModule Import Exports.\nNotation indCountType := type.\nNotation IndCountType := Pack.\nCoercion sorts : type >-> Funclass.\nCanonical eqType.\nCanonical choiceType.\nCanonical countType.\nCoercion indDef : type >-> Ind.Def.type.\nCanonical indDef.\nEnd Exports.\n\nEnd IndCountType.\n\nExport IndCountType.Exports.\n\n#[global]\nHint Unfold IndCountType.n : deriving.\n#[global]\nHint Unfold IndCountType.sorts : deriving.\n#[global]\nHint Unfold IndCountType.decl : deriving.\n#[global]\nHint Unfold IndCountType.count_class : deriving.\n#[global]\nHint Unfold IndCountType.ind_class : deriving.\n#[global]\nHint Unfold IndCountType.eqType : deriving.\n#[global]\nHint Unfold IndCountType.choiceType : deriving.\n#[global]\nHint Unfold IndCountType.countType : deriving.\n#[global]\nHint Unfold IndCountType.indDef : deriving.\n", "meta": {"author": "arthuraa", "repo": "deriving", "sha": "bf967106a0b61a281c3b4ababfe67f80de7fba47", "save_path": "github-repos/coq/arthuraa-deriving", "path": "github-repos/coq/arthuraa-deriving/deriving-bf967106a0b61a281c3b4ababfe67f80de7fba47/theories/ind.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2609440488771021}}
{"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 ConstrInterp ConstrEntailment Definitions Subenvironments RecordAndInertTypes.\n\n(** * Typing Rules *)\n\nReserved Notation \"e '⊢c' t ':' T\" (at level 39, t at level 59).\nReserved Notation \"e '/-c' d : D\" (at level 39, d at level 59).\nReserved Notation \"e '/-c' ds :: D\" (at level 39, ds 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 : (constr * ctx) -> trm -> typ -> Prop :=\n\n(** [G(x) = T]  #<br>#\n    [――――――――]  #<br>#\n    [C, G ⊢c x: T]  *)\n| cty_var : 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 : 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 : 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 : 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 : 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 : 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 : 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 : 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 : 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 : 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 e t T)\n\n(** ** Single-definition typing [G ⊢ d: D] *)\nwith cty_def : (constr * ctx) -> def -> dec -> Prop :=\n(** [C, G ⊢c {A = T}: {A: T..T}]   *)\n| cty_def_typ : forall C G A T,\n    (C, G) /-c def_typ A T : dec_typ A T T\n\n(** [C, G ⊢c t: T]            #<br>#\n    [―――――――――――――――――――] #<br>#\n    [C, G ⊢c {a = t}: {a: T}] *)\n| cty_def_trm : forall C G a t T,\n    (C, G) ⊢c t : T ->\n    (C, G) /-c def_trm a t : dec_trm a T\nwhere \"e '/-c' d ':' D\" := (cty_def e d D)\n\n(** ** Multiple-definition typing [G ⊢ ds :: T] *)\nwith cty_defs : (constr * ctx) -> defs -> typ -> Prop :=\n(** [C, G ⊢c d: D]              #<br>#\n    [―――――――――――――――――――――] #<br>#\n    [C, G ⊢c d ++ defs_nil : D] *)\n| cty_defs_one : forall C G d D,\n    (C, G) /-c d : D ->\n    (C, G) /-c defs_cons defs_nil d :: typ_rcd D\n\n(** [C, G ⊢c ds :: T]         #<br>#\n    [C, G ⊢c d: D]            #<br>#\n    [d \\notin ds]         #<br>#\n    [―――――――――――――――――――] #<br>#\n    [C, G ⊢c ds ++ d : T /\\ D] *)\n| cty_defs_cons : forall C G ds d T D,\n    (C, G) /-c ds :: T ->\n    (C, G) /-c d : D ->\n    defs_hasnt ds (label_of_def d) ->\n    (C, G) /-c defs_cons ds d :: typ_and T (typ_rcd D)\nwhere \"e '/-c' ds '::' T\" := (cty_defs e ds T)\n\nwith csubtyp : (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 : 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 : 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 e T U).\n\nHint Constructors cty_trm cty_def cty_defs csubtyp.\n\nScheme cts_ty_trm_mut := Induction for cty_trm Sort Prop\nwith   cts_subtyp     := Induction for csubtyp Sort Prop.\nCombined Scheme cts_mutind from cts_ty_trm_mut, cts_subtyp.\n\nScheme crules_trm_mut    := Induction for cty_trm Sort Prop\nwith   crules_def_mut    := Induction for cty_def Sort Prop\nwith   crules_defs_mut   := Induction for cty_defs Sort Prop\nwith   crules_subtyp     := Induction for csubtyp Sort Prop.\nCombined Scheme crules_mutind from crules_trm_mut, crules_def_mut, crules_defs_mut, crules_subtyp.\n\n(** ** Well-typed programs *)\nDefinition compatible_constr C G t T :=\n  exists tm vm, (tm, vm, G) ⊧ C /\\ (C, G) ⊢c t: T.\n\n(* (** ⊤, (x: {A: {X: ⊥..T1}..{X: ⊥..T2}}, y: T1) ⊢c y: T2 *) *)\n(* Lemma typing_example1 : forall G x y A X T1 T2, *)\n(*     binds x *)\n(*           (typ_rcd *)\n(*              (dec_typ A *)\n(*                       (typ_rcd (dec_typ X typ_bot T1)) *)\n(*                       (typ_rcd (dec_typ X typ_bot T2)))) *)\n(*           G -> *)\n(*     binds y T1 G -> *)\n(*     ⊤, G ⊢c trm_var (avar_f y) : T2. *)\n(* Proof. *)\n(*   introv Hx Hy. *)\n(*   eapply ty_constr_intro with (t := trm_var (avar_f x)). *)\n(*   - constructor*. *)\n(*   - apply ty_sub with (T := T1). *)\n(*     -- constructor*. *)\n(*     -- eapply ent_trans. *)\n(*        + apply ent_and_right. *)\n(*        + eapply ent_trans. apply ent_exists_v_intro'. *)\n(*          eapply ent_trans. apply ent_cong_exists_v. *)\n(*          2: { *)\n(*            eapply ent_trans. *)\n(*            eapply ent_bound_sub. *)\n(*            eapply ent_trans. apply ent_and_right. *)\n(*            eapply ent_trans. eapply ent_inv_subtyp_typ. *)\n(*            apply ent_and_right. *)\n(*          } *)\n(*          simpl_open_constr. introv Heqc Heqd. subst C' D'. *)\n(*          eapply ent_and_intro. apply ent_refl. *)\n(* Qed. *)\n\n(** [G ⊢ ds :: U]                          #<br>#\n    [U] is a record type with labels [ls]  #<br>#\n    [ds] are definitions with label [ls']  #<br>#\n    [l \\notin ls']                          #<br>#\n    [―――――――――――――――――――――――――――――――――――]  #<br>#\n    [l \\notin ls] *)\nLemma constr_hasnt_notin : forall C G ds ls l U,\n    (C, G) /-c ds :: U ->\n    record_typ U ls ->\n    defs_hasnt ds l ->\n    l \\notin ls.\nProof.\n\n  Ltac inversion_def_typ :=\n    match goal with\n    | [ H: _ /-c _ : _ |- _ ] => inversions H\n    end.\n\n  introv Hds Hrec Hhasnt.\n  inversions Hhasnt. gen ds. induction Hrec; intros; inversions Hds.\n  - inversion_def_typ; simpl in *; case_if; apply* notin_singleton.\n  - apply notin_union; split; simpl in *.\n    + apply* IHHrec. case_if*.\n    + inversion_def_typ; case_if; apply* notin_singleton.\nQed.\n\n(** The type of definitions is a record type. *)\nLemma cty_defs_record_type : forall C G ds T,\n    (C, G) /-c ds :: T ->\n    record_type T.\nProof.\n intros. induction H; destruct D;\n    repeat match goal with\n        | [ H: record_type _ |- _ ] =>\n          destruct H\n        | [ Hd: _ /-c _ : dec_typ _ _ _ |- _ ] =>\n          inversions Hd\n        | [ Hd: _ /-c _ : dec_trm _ _ |- _ ] =>\n          inversions Hd\n    end;\n    match goal with\n    | [ ls: fset label,\n        t: trm_label |- _ ] =>\n      exists (ls \\u \\{ label_trm t })\n    | [ ls: fset label,\n        t: typ_label |- _ ] =>\n      exists (ls \\u \\{ label_typ t })\n    | [ t: trm_label |- _ ] =>\n      exists \\{ label_trm t }\n    | [ t: typ_label |- _ ] =>\n      exists \\{ label_typ t }\n    end;\n    constructor*; try constructor; apply (constr_hasnt_notin H); eauto.\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/ConstrTyping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961016, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2609440421271815}}
{"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(** Construction and coloring of the interference graph. *)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Op.\nRequire Import Registers.\nRequire Import RTL.\nRequire Import RTLtyping.\nRequire Import Locations.\nRequire Import Conventions.\nRequire Import InterfGraph.\n\n(** * Construction of the interference graph *)\n\n(** Two registers interfere if there exists a program point where\n    they are both simultaneously live, and it is possible that they\n    contain different values at this program point.  Consequently,\n    two registers that do not interfere can be merged into one register\n    while preserving the program behavior: there is no program point\n    where this merged register would have to hold two different values\n    (for the two original registers), so to speak.\n\n    The simplified algorithm for constructing the interference graph\n    from the results of the liveness analysis is as follows:\n<<\n     start with empty interference graph\n     for each parameter p and register r live at the function entry point:\n         add conflict edge p <-> r \n     for each instruction I in function:\n         let L be the live registers \"after\" I\n         if I is a \"move\" instruction  dst <- src, and dst is live:\n            add conflict edges dst <-> r for each r in L \\ {dst, src}\n         else if I is an instruction with result dst, and dst is live:\n            add conflict edges dst <-> r for each r in L \\ {dst};\n         if I is a \"call\" instruction dst <- f(args),\n            add conflict edges between all pseudo-registers in L \\ {dst}\n            and all caller-save machine registers\n     done\n>>\n    Notice that edges are added only when a register becomes live.\n    A register becomes live either if it is the result of an operation\n    (and is live afterwards), or if we are at the function entrance\n    and the register is a function parameter.  For two registers to\n    be simultaneously live at some program point, it must be the case\n    that one becomes live at a point where the other is already live.\n    Hence, it suffices to add interference edges between registers\n    that become live at some instruction and registers that are already\n    live at this instruction.  \n\n    Notice also the special treatment of ``move'' instructions:\n    since the destination register of the ``move'' is assigned the same value\n    as the source register, it is semantically correct to assign\n    the destination and the source registers to the same register,\n    even if the source register remains live afterwards.\n    (This is even desirable, since the ``move'' instruction can then\n    be eliminated.)  Thus, no interference is added between the\n    source and the destination of a ``move'' instruction.\n\n    Finally, for ``call'' instructions, we must make sure that\n    pseudo-registers live across the instruction are allocated to\n    callee-save machine register or to stack slots, but never to\n    caller-save machine registers (these lose their values across\n    the call).  We therefore add the corresponding conflict edges\n    between pseudo-registers live across and caller-save machine\n    registers (pairwise).  \n\n    The full algorithm is similar to the simplified algorithm above,\n    but records preference edges in addition to conflict edges.\n    Preference edges guide the graph coloring algorithm by telling it\n    that better code will be obtained eventually if it is possible\n    to allocate certain pseudo-registers to the same location or to\n    a given machine register.  Preference edges are added:\n-   between the destination and source pseudo-registers of a ``move''\n    instruction;\n-   between the arguments of a ``call'' instruction and the locations\n    of the arguments as dictated by the calling conventions;\n-   between the result of a ``call'' instruction and the location\n    of the result as dictated by the calling conventions.\n*)\n\nDefinition add_interf_live\n    (filter: reg -> bool) (res: reg) (live: Regset.t) (g: graph): graph :=\n  Regset.fold \n    (fun r g => if filter r then add_interf r res g else g) live g.\n\nDefinition add_interf_op\n    (res: reg) (live: Regset.t) (g: graph): graph :=\n  add_interf_live\n    (fun r => if Reg.eq r res then false else true)\n    res live g.\n\nDefinition add_interf_move\n    (arg res: reg) (live: Regset.t) (g: graph): graph :=\n  add_interf_live\n    (fun r =>\n       if Reg.eq r res then false else\n       if Reg.eq r arg then false else true)\n    res live g.\n\nDefinition add_interf_destroyed\n    (live: Regset.t) (destroyed: list mreg) (g: graph): graph :=\n  List.fold_left\n    (fun g mr => Regset.fold (fun r g => add_interf_mreg r mr g) live g)\n    destroyed g.\n\nDefinition add_interfs_indirect_call\n    (rfun: reg) (locs: list loc) (g: graph): graph :=\n  List.fold_left\n    (fun g loc =>\n      match loc with R mr => add_interf_mreg rfun mr g | _ => g end)\n    locs g.\n\nDefinition add_interf_call\n    (ros: reg + ident) (locs: list loc) (g: graph): graph :=\n  match ros with\n  | inl rfun => add_interfs_indirect_call rfun locs g\n  | inr idfun => g\n  end.\n\nFixpoint add_prefs_call\n    (args: list reg) (locs: list loc) (g: graph) {struct args} : graph :=\n  match args, locs with\n  | a1 :: al, l1 :: ll =>\n      add_prefs_call al ll\n        (match l1 with R mr => add_pref_mreg a1 mr g | _ => g end)\n  | _, _ => g\n  end.\n\nDefinition add_prefs_builtin (ef: external_function)\n                            (args: list reg) (res: reg) (g: graph) : graph :=\n  match ef, args with\n  | EF_annot_val txt targ, arg1 :: _ => add_pref arg1 res g\n  | _, _ => g\n  end.\n\nDefinition add_interf_entry\n    (params: list reg) (live: Regset.t) (g: graph): graph :=\n  List.fold_left (fun g r => add_interf_op r live g) params g.\n\nFixpoint add_interf_params\n    (params: list reg) (g: graph) {struct params}: graph :=\n  match params with\n  | nil => g\n  | p1 :: pl =>\n      add_interf_params pl\n        (List.fold_left\n          (fun g r => if Reg.eq r p1 then g else add_interf r p1 g)\n          pl g)\n  end.\n\nDefinition add_edges_instr\n    (sig: signature) (i: instruction) (live: Regset.t) (g: graph) : graph :=\n  match i with\n  | Iop op args res s =>\n      if Regset.mem res live then\n        match is_move_operation op args with\n        | Some arg =>\n            add_pref arg res (add_interf_move arg res live g)\n        | None =>\n            add_interf_op res live g\n        end\n      else g\n  | Iload chunk addr args dst s =>\n      if Regset.mem dst live\n      then add_interf_op dst live g\n      else g\n  | Icall sig ros args res s =>\n      let largs := loc_arguments sig in\n      let lres := loc_result sig in\n      add_prefs_call args largs\n        (add_pref_mreg res lres\n          (add_interf_op res live\n            (add_interf_call ros largs\n              (add_interf_destroyed\n                (Regset.remove res live) destroyed_at_call_regs g))))\n  | Itailcall sig ros args =>\n      let largs := loc_arguments sig in\n      add_prefs_call args largs\n        (add_interf_call ros largs g)\n  | Ibuiltin ef args res s =>\n      add_prefs_builtin ef args res (add_interf_op res live g)\n  | Ireturn (Some r) =>\n      add_pref_mreg r (loc_result sig) g\n  | _ => g\n  end.\n\nDefinition add_edges_instrs (f: function) (live: PMap.t Regset.t) : graph :=\n  PTree.fold\n    (fun g pc i => add_edges_instr f.(fn_sig) i live!!pc g)\n    f.(fn_code)\n    empty_graph.\n\nDefinition interf_graph (f: function) (live: PMap.t Regset.t) (live0: Regset.t) :=\n  add_prefs_call f.(fn_params) (loc_parameters f.(fn_sig))\n    (add_interf_params f.(fn_params)\n      (add_interf_entry f.(fn_params) live0\n        (add_edges_instrs f live))).\n\n(** * Graph coloring *)\n\n(** The actual coloring of the graph is performed by a function written\n  directly in Caml, and not proved correct in any way.  This function\n  takes as argument the [RTL] function, the interference graph for\n  this function, an assignment of types to [RTL] pseudo-registers,\n  and the set of all [RTL] pseudo-registers mentioned in the\n  interference graph.  It returns the coloring as a function from\n  pseudo-registers to locations. *)\n\nParameter graph_coloring: \n  function -> graph -> regenv -> Regset.t -> (reg -> loc).\n\n(** To ensure that the result of [graph_coloring] is a correct coloring,\n  we check a posteriori its result using the following Coq functions.\n  Let [coloring] be the function [reg -> loc] returned by [graph_coloring].\n  The three properties checked are:\n- [coloring r1 <> coloring r2] if there is a conflict edge between\n  [r1] and [r2] in the interference graph.\n- [coloring r1 <> R m2] if there is a conflict edge between pseudo-register\n  [r1] and machine register [m2] in the interference graph.\n- For all [r] mentioned in the interference graph,\n  the location [coloring r] is acceptable and has the same type as [r].\n*)\n\nDefinition check_coloring_1 (g: graph) (coloring: reg -> loc) :=\n  SetRegReg.for_all \n    (fun r1r2 =>\n      if Loc.eq (coloring (fst r1r2)) (coloring (snd r1r2)) then false else true)\n    g.(interf_reg_reg).\n\nDefinition check_coloring_2 (g: graph) (coloring: reg -> loc) :=\n  SetRegMreg.for_all \n    (fun r1mr2 =>\n      if Loc.eq (coloring (fst r1mr2)) (R (snd r1mr2)) then false else true)\n    g.(interf_reg_mreg).\n\nDefinition same_typ (t1 t2: typ) :=\n  match t1, t2 with\n  | Tint, Tint => true\n  | Tfloat, Tfloat => true\n  | _, _ => false\n  end.\n\nDefinition loc_is_acceptable (l: loc) :=\n  match l with\n  | R r => \n     if In_dec Loc.eq l temporaries then false else true\n  | S (Local ofs ty) =>\n     if zlt ofs 0 then false else true\n  | _ =>\n     false\n  end.\n\nDefinition check_coloring_3 (rs: Regset.t) (env: regenv) (coloring: reg -> loc) :=\n  Regset.for_all\n    (fun r =>\n      let l := coloring r in\n      andb (loc_is_acceptable l) (same_typ (env r) (Loc.type l)))\n    rs.\n\nDefinition check_coloring\n       (g: graph) (env: regenv) (rs: Regset.t) (coloring: reg -> loc) :=\n  andb (check_coloring_1 g coloring)\n       (andb (check_coloring_2 g coloring)\n             (check_coloring_3 rs env coloring)).\n\n(** To preserve decidability of checking, the checks\n  (especially the third one) are performed for the pseudo-registers\n  mentioned in the interference graph.  To facilitate the proofs,\n  it is convenient to ensure that the properties hold for all\n  pseudo-registers.  To this end, we ``clip'' the candidate coloring\n  returned by [graph_coloring]: the final coloring behave identically\n  over pseudo-registers mentioned in the interference graph,\n  but returns a dummy machine register of the correct type otherwise. *)\n\nDefinition alloc_of_coloring (coloring: reg -> loc) (env: regenv) (rs: Regset.t) :=\n  fun r =>\n    if Regset.mem r rs\n    then coloring r\n    else match env r with Tint => R dummy_int_reg | Tfloat => R dummy_float_reg end.\n\n(** * Coloring of the interference graph *)\n\n(** The following function combines the phases described above:\n  construction of the interference graph, coloring by untrusted\n  Caml code, checking of the candidate coloring returned,\n  and adjustment of this coloring.  If the coloring candidate is\n  incorrect, [None] is returned, causing register allocation to fail. *)\n\nDefinition regalloc\n    (f: function) (live: PMap.t Regset.t) (live0: Regset.t) (env: regenv) :=\n  let g := interf_graph f live live0 in\n  let rs := all_interf_regs g in\n  let coloring := graph_coloring f g env rs in\n  if check_coloring g env rs coloring\n  then Some (alloc_of_coloring coloring env rs)\n  else None.\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/Coloring.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2609440421271814}}
{"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.two_p_set Require Import two_p_set_code.\n\nSection tpsCrdt.\n  Context `{!Log_Time} `{!EqDecision vl} `{!Countable vl}.\n\n  Definition tpsOp : Type := vl + vl.\n  Definition tpsSt : Type := gset vl * gset vl.\n\n  Definition update_state (op : tpsOp) (st : tpsSt) : tpsSt :=\n    match op with\n    | inl a => ({[a]} ∪ st.1, st.2)\n    | inr a => (st.1, {[a]} ∪ st.2)\n    end.\n\n  Definition tps_denot (s : gset (Event tpsOp)) (state : tpsSt) : Prop :=\n    set_fold (λ ev st, update_state (EV_Op ev) st) (∅, ∅) s = state.\n\n  Global Instance tps_denot_fun : Rel2__Fun tps_denot.\n  Proof. constructor; intros ? ? ? <- <-; done. Qed.\n\n  Global Instance tps_denot_instance : CrdtDenot tpsOp tpsSt := {\n    crdt_denot := tps_denot;\n  }.\nEnd tpsCrdt.\n\nGlobal Arguments tpsOp _ : clear implicits.\nGlobal Arguments tpsSt _ {_ _}.\n\nSection OpTps.\n  Context `{!Log_Time}\n          `{!EqDecision vl} `{!Countable vl}.\n\n  Definition op_tps_effect (st : tpsSt vl) (ev : Event (tpsOp vl)) (st' : tpsSt vl) : Prop :=\n    st' = update_state (EV_Op ev) st.\n\n  Lemma op_tps_effect_fun st : Rel2__Fun (op_tps_effect st).\n  Proof. constructor; intros ??? -> ->; done. Qed.\n\n  Instance op_tps_effect_coh : OpCrdtEffectCoh op_tps_effect.\n  Proof.\n    intros s ev st st' Hst Hevs Hmax Hext.\n    rewrite /op_tps_effect /crdt_denot /= /tps_denot.\n    rewrite set_fold_disj_union_strong; [| |set_solver]; last first.\n    { intros [[] ] [[] ]; rewrite /update_state /=; intros; f_equal; set_solver. }\n    rewrite Hst set_fold_singleton; split; done.\n  Qed.\n\n  Definition op_tps_init_st : tpsSt vl := (∅, ∅).\n\n  Lemma op_tps_init_st_coh : ⟦ (∅ : gset (Event (tpsOp vl))) ⟧ ⇝ op_tps_init_st.\n  Proof. done. Qed.\n\n  Global Instance op_tps_model_instance : OpCrdtModel (tpsOp vl) (tpsSt vl) := {\n    op_crdtM_effect := op_tps_effect;\n    op_crdtM_effect_fun := op_tps_effect_fun;\n    op_crdtM_effect_coh := op_tps_effect_coh;\n    op_crdtM_init_st := op_tps_init_st;\n    op_crdtM_init_st_coh := op_tps_init_st_coh\n  }.\n\nEnd OpTps.\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 tps_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 (tpsOp vl)}.\n\n  Definition tps_OpLib_Op_Coh := λ (op : tpsOp vl) (v : val), v = $op.\n\n  Lemma tps_OpLib_Op_Coh_Inj (o1 o2 : tpsOp vl) (v : val) :\n    tps_OpLib_Op_Coh o1 v → tps_OpLib_Op_Coh o2 v → o1 = o2.\n  Proof. intros Ho1 Ho2; apply (inj (@inject _ _ Inject_sum)); rewrite -Ho1 -Ho2; done. Qed.\n\n  Lemma tps_OpLib_Coh_Ser (op : tpsOp vl) (v : val) :\n    tps_OpLib_Op_Coh op v → Serializable (sum_serialization vl_serialization vl_serialization) v.\n  Proof. intros Heq. rewrite Heq; destruct op; apply _. Qed.\n\n  Definition tps_OpLib_State_Coh :=\n    λ (st : tpsSt vl) v, ∃ v1 v2, v = PairV v1 v2 ∧ is_set st.1 v1 ∧ is_set st.2 v2.\n\n  Global Instance tps_OpLib_Params : OpLib_Params (tpsOp vl) (tpsSt vl) :=\n  {|\n    OpLib_Serialization := (sum_serialization vl_serialization vl_serialization);\n    OpLib_State_Coh := tps_OpLib_State_Coh;\n    OpLib_Op_Coh := tps_OpLib_Op_Coh;\n    OpLib_Op_Coh_Inj := tps_OpLib_Op_Coh_Inj;\n    OpLib_Coh_Ser := tps_OpLib_Coh_Ser\n  |}.\n\n  Lemma tps_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    wp_apply wp_set_empty; first done.\n    iIntros (w Hw).\n    wp_pures.\n    iApply \"HΦ\".\n    iPureIntro; eexists _, _; split_and!; simpl; done.\n  Qed.\n\n  Lemma tps_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    destruct log_st as [log_st1 log_st2].\n    destruct Hst as (st1&st2&?&?&?).\n    simplify_eq/=.\n    rewrite Hopcoh /=.\n    wp_pures.\n    destruct log_ev; wp_pures.\n    - wp_apply wp_set_add; first by iPureIntro.\n      iIntros (w Hw).\n      wp_pures.\n      iApply \"HΦ\".\n      iExists _; iSplit; last by eauto.\n      simpl; iPureIntro; eexists _, _; split_and!; done.\n    - wp_apply wp_set_add; first by iPureIntro.\n      iIntros (w Hw).\n      wp_pures.\n      iApply \"HΦ\".\n      iExists _; iSplit; last by eauto.\n      simpl; iPureIntro; eexists _, _; split_and!; done.\n  Qed.\n\n  Lemma tps_crdt_fun_spec : ⊢ crdt_fun_spec tps_crdt.\n  Proof.\n    iIntros (addr).\n    iIntros \"!#\" (Φ) \"_ HΦ\".\n    rewrite /tps_crdt.\n    wp_pures.\n    iApply \"HΦ\".\n    iExists _, _; iSplit; first done.\n    iSplit.\n    - iApply tps_init_st_fn_spec; done.\n    - iApply tps_effect_spec; done.\n  Qed.\n\n  Lemma tps_init_spec :\n    init_spec\n      (oplib_init\n         (s_ser (s_serializer (sum_serialization vl_serialization vl_serialization)))\n         (s_deser (s_serializer (sum_serialization vl_serialization vl_serialization)))) -∗\n    init_spec_for_specific_crdt\n      (tps_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 /tps_init.\n    wp_pures.\n    wp_apply (\"Hinit\" with \"[$Hprotos $Htoken $Hskt $Hfr]\").\n    { do 2 (iSplit; first done). iApply tps_crdt_fun_spec; done. }\n    iIntros (get update) \"(HLS & #Hget & #Hupdate)\".\n    wp_pures.\n    iApply \"HΦ\"; eauto.\n  Qed.\n\nEnd tps_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/two_p_set/two_p_set_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2609440421271814}}
{"text": "(**\nCoLoR, a Coq library on rewriting and termination.\nSee the COPYRIGHTS and LICENSE files.\n\n- Leo Ducas, 2007-08-06\n\nModular termination proof through SCC of an over DPGraph\n*)\n\nSet Implicit Arguments.\n\nFrom Coq Require Import Permutation Multiset Setoid PermutSetoid.\nFrom CoLoR Require Import SCCTopoOrdering AGraph ATrs RelUtil RelSub BoundNat\n     AdjMat LogicUtil NatUtil SCC SCC_dec ListExtras SN VecUtil GDomainBij\n     OptUtil Union SortUtil ListNodup ListPermutation.\n\nSection S.\n\n  Variable Sig : Signature.\n\n  Notation rule := (rule Sig). Notation rules := (list rule).\n\n  Variables (S : relation (term Sig)) (R : rules) (hyp : rules_preserve_vars R).\n\n  Notation DPG := (hd_rules_graph S R).\n  Notation rule_eq_dec := (@ATrs.eq_rule_dec Sig).\n  Notation dim := (length R).\n\n  Variables (ODPG : relation rule) (over_DPG : DPG << ODPG)\n            (restriction : is_restricted ODPG R) (R_nodup : nodup R)\n            (ODPG_dec : forall x y, {ODPG x y} + {~ODPG x y}).\n\n  Definition hyps := mkSCC_dec_hyps rule_eq_dec restriction R_nodup ODPG_dec.\n\n  Variables (M : matrix dim dim) (HM : M = SCC_mat_effective hyps) .\n\n  Notation empty := (fun _ _ => False).\n\n  Definition proj1_sig2 T P Q (e : @sig2 T P Q) :=\n    match e with\n    | exist2 _ _ a b c => a\n    end.\n\n  Definition s_SCC's := proj1_sig2 (sorted_SCC' hyps HM).\n\n  Notation ODPGquo' := (Rquo' hyps HM).\n\n(***********************************************************************)\n(** s_SCC's properties *)\n\n  Lemma s_SCC's_spec_cover i : i < dim -> In i s_SCC's.\n\n  Proof.\n    intros. unfold s_SCC's. destruct (sorted_SCC' hyps). unfold proj1_sig2.\n    unfold permutation, meq in *. ded (p i).\n    rewrite multiplicity_nats_decr_lt in H0.\n    destruct (lt_ge_dec i (length (hyp_Dom hyps))); try lia.\n    cut (exists j, j=i /\\ In j x). intros; destruct H1. destruct H1.\n    rewrite <- H1; auto.\n    apply (multiplicity_in (@eq nat) eq_nat_dec). lia.\n    assert (length (hyp_Dom hyps) = dim); intuition.\n  Qed.\n\n  Lemma s_SCC's_spec_bound i : In i s_SCC's -> i < dim.\n\n  Proof.\n    intros. unfold s_SCC's in H. destruct (sorted_SCC' hyps).\n    unfold proj1_sig2 in *. gen p; intros. unfold permutation, meq in p.\n    ded (p i). rewrite multiplicity_nats_decr_lt in H0.\n    destruct (lt_ge_dec i (length (hyp_Dom hyps))); try lia.\n    assert (dim = length (hyp_Dom hyps)). auto. rewrite H1 in *; auto.\n    cut (exists j, j=i /\\ In j (nats_decr_lt dim)).\n    intros; destruct H1. destruct H1. \n    rewrite <- In_nats_decr_lt in H2. subst i; auto.\n    eapply permutation_in. auto with typeclass_instances.\n    apply permutation_sym. eauto. auto.\n  Qed.\n\n(***********************************************************************)\n(** chain restricted to an SCC *)\n\n  Notation SCC' := (SCC' hyps).\n  Notation SCC'_tag := (SCC'_tag hyps).\n  Notation SCC'_dec := (SCC'_dec hyps).\n\n  Definition hd_red_SCC' i t1 t2 := exists l, exists r, exists s,\n          SCC'_tag HM (mkRule l r) = Some i /\\ t1 = sub s l /\\ t2 = sub s r.\n\n  Lemma hd_red_SCC'_cover t1 t2 : hd_red R t1 t2 ->\n                                  exists i, hd_red_SCC' i t1 t2 /\\ i<dim.\n\n  Proof.\n    intros. unfold hd_red in *. do 4 destruct H; destruct H0.\n    cut (exists n, SCC'_tag HM (mkRule x x0) = Some n).\n    intro. destruct H2 as [i]. exists i. split. exists x; exists x0; exists x1.\n    split; try tauto.\n    apply (find_first_Some_bound\n             (SCC' (mkRule x x0)) (SCC'_dec HM (mkRule x x0))). intuition.\n    ded (find_first_exist\n           (SCC' (mkRule x x0)) (SCC'_dec HM (mkRule x x0)) _ R H).\n    assert (SCC'_tag HM (mkRule x x0) <> None). apply H2.\n    split; try tauto. left; auto.\n    destruct (SCC'_tag HM (mkRule x x0)). exists n; auto. congruence.\n  Qed.\n\n  Definition hd_red_Mod_SCC' i :=  S @ hd_red_SCC' i.\n\n(***********************************************************************)\n(** union of chain_SCC' *)\n\n  Notation union := Relation_Operators.union.\n\n  Definition sorted_hd_red_Mod_SCC' := map hd_red_Mod_SCC' s_SCC's.\n\n  Definition hd_red_Mod_SCC'_union :=\n    fold_right (@union (term Sig)) empty sorted_hd_red_Mod_SCC'.\n\n  Lemma union_list_spec : forall (A : Type) L (x y : A) (r : relation A),\n      In r L -> r x y -> fold_right (@union A) empty L x y.\n\n  Proof.\n    intros. induction L. simpl in *; tauto.\n    simpl in *. destruct H. destruct H. subst; left; auto. right; tauto.\n  Qed.\n\n  Lemma union_list_spec2 : forall (A : Type) L (x y : A),\n      fold_right (@union A) empty L x y -> exists r, In r L /\\ r x y.\n\n  Proof.\n    intros. induction L. simpl in *; tauto.\n    simpl in *. destruct H. exists a; split; tauto.\n    destruct (IHL H). exists x0. split; try tauto.\n  Qed.\n\n  Lemma hd_red_Mod_SCC'_cover : hd_red_Mod S R << hd_red_Mod_SCC'_union.\n\n  Proof.\n    unfold inclusion. intros. unfold hd_red_Mod_SCC'_union in H.\n    unfold hd_red_Mod in H. do 2 destruct H. ded (hd_red_SCC'_cover H0).\n    destruct H1 as [i]. assert (hd_red_Mod_SCC' i x y). exists x0; tauto.\n    unfold hd_red_Mod_SCC'_union. eapply union_list_spec; eauto.\n    unfold sorted_hd_red_Mod_SCC'. apply in_map.\n    apply s_SCC's_spec_cover; tauto.\n  Qed.\n\n(***********************************************************************)\n(** properties of the total order RT relatively to restricted chain *)\n\n  Notation RT_ODPG := (RT hyps HM).\n\n  Lemma compose_empty :\n    forall i j, RT_ODPG i j -> hd_red_Mod_SCC' j @ hd_red_Mod_SCC' i << empty.\n\n  Proof.\n    intros. unfold inclusion. intros x y H0. destruct H0 as [z]. destruct H0.\n\n    assert (~ODPGquo' j i). unfold RT in  *. destruct topo_sortable_Rquo'.\n    simpl in *. intuition. ded (l (nats_decr_lt dim)). clear l.\n    set (RTbis := fun x y : nat => x0 (nats_decr_lt dim) x y = true) in *.\n    change (RTbis i j) in H.\n\n    assert (RTbis j i). destruct H3. intuition. apply H5.\n    ded (@Rquo_restricted hyps M HM j i).\n    split; try split; try tauto; destruct H2; try tauto.\n\n    unfold irreflexive in *. intuition. destruct H3; intuition. apply (H7 i).\n    eapply H5; ehyp.\n\n    assert (ODPGquo' j i). unfold Rquo'. intuition.\n    unfold Rquo in *. unfold hd_red_Mod_SCC' in *.\n    destruct H0 as [x']. destruct H0. destruct H1 as [z']. destruct H1.\n    destruct H3 as [t1]. destruct H3 as [r1]. destruct H3 as [s1].\n    exists (mkRule t1 r1); split; try tauto.\n    destruct H4 as [t2]. destruct H4 as [r2]. destruct H4 as [s2].\n    exists (mkRule t2 r2); split; try tauto.\n    apply over_DPG. eapply hd_red_Mod_rule2_hd_rules_graph; intuition.\n    unfold hd_red_Mod_rule. split.\n\n    assert (SCC' (mkRule t1 r1) (mkRule t1 r1)).\n    rewrite (SCC'_tag_exact hyps HM). split; try tauto. congruence.\n\n    destruct H7. tauto.\n    exists s1. subst x'. split; simpl; auto; eauto.\n    intuition. split.\n\n    assert (SCC' (mkRule t2 r2) (mkRule t2 r2)).\n    rewrite (SCC'_tag_exact hyps HM). split; try tauto. congruence.\n\n    destruct H7; tauto.\n    exists s2. subst z. split; simpl; auto; eauto. congruence.\n\n    subst j. unfold RT in *. destruct topo_sortable_Rquo'. simpl in *.\n    ded (l (nats_decr_lt dim)). clear l. destruct H3. intuition.\n    unfold irreflexive in H6. ded (H6 i). auto. tauto.\n  Qed.\n\n(***********************************************************************)\n(** Proof of the modular termination criterion *)\n\n  Lemma WF_SCC'_union_aux : forall L,\n      (forall i, In i L -> WF (hd_red_Mod_SCC' i)) -> sort RT_ODPG L -> \n      WF (fold_right (@union _) empty (map hd_red_Mod_SCC' L)).\n\n  Proof.\n    intros. induction L; simpl in *.\n    intro. apply SN_intro. intros; tauto.\n    inversion H0. subst a0; subst l. eapply WF_incl. apply union_commut.\n    apply WF_union_commut.\n\n    apply IHL. intros. apply H. right; auto.\n    destruct H0; auto. apply H. left; auto.\n\n    unfold inclusion. intros. cut False; try tauto.\n    destruct H1 as [z]. destruct H1. ded (union_list_spec2 _ _ _ H1).\n    destruct H5 as [r]. destruct H5.\n\n    assert (exists b, In b L /\\ r = hd_red_Mod_SCC' b).\n    apply in_map_elim; auto. destruct H7 as [b]. destruct H7; subst r.\n    cut (RT_ODPG a b). intro. eapply (compose_empty H8). exists z; eauto.\n    eapply sort_transitive. unfold RT; destruct topo_sortable_Rquo'.\n    simpl in *. \n    ded (l (nats_decr_lt dim)). destruct H8. intuition. ehyp. auto.\n  Qed.\n\n  Lemma WF_SCC'_union :\n    (forall i, i < dim -> WF (hd_red_Mod_SCC' i)) -> WF (hd_red_Mod S R).\n\n  Proof.\n    intros. eapply WF_incl. apply hd_red_Mod_SCC'_cover.\n    unfold hd_red_Mod_SCC'_union, sorted_hd_red_Mod_SCC'.\n    eapply WF_SCC'_union_aux. intros. apply H. apply s_SCC's_spec_bound. auto.\n    unfold s_SCC's; destruct sorted_SCC'. simpl in *. auto.\n  Qed.\n\n  Fixpoint SCC'_list_aux i L :=\n    match L with\n    | nil => nil\n    | x :: q =>\n      match eq_opt_dec eq_nat_dec (SCC'_tag HM x) (Some i) with\n      | left _ => x :: @SCC'_list_aux i q\n      | right _ => @SCC'_list_aux i q\n      end\n    end.\n\n  Lemma SCC'_list_aux_exact : forall i L r,\n      In r (SCC'_list_aux i L) <-> In r L /\\ SCC'_tag HM r = Some i.\n\n  Proof.\n    intros. induction L. simpl in *. tauto.\n    split; intro. simpl in *.\n    destruct (eq_opt_dec eq_nat_dec (SCC'_tag HM a) (Some i));\n      destruct (rule_eq_dec a r); simpl in *; intuition.\n    subst a; tauto.\n    destruct H. simpl in *.\n    destruct (eq_opt_dec eq_nat_dec (SCC'_tag HM a) (Some i));\n      destruct H; simpl in *; try subst a; tauto.\n  Qed.\n\n  Lemma nodup_SCC'_list_aux : forall i L, nodup L -> nodup (SCC'_list_aux i L).\n\n  Proof.\n    induction L; intros; simpl. tauto.\n    simpl in H. destruct H.\n    destruct (eq_opt_dec eq_nat_dec (SCC'_tag HM a) (Some i)); try tauto.\n    split. rewrite SCC'_list_aux_exact. tauto. tauto.\n  Qed.\n\n  Definition SCC'_list i := SCC'_list_aux i R.\n\n  Lemma SCC'_list_exact : forall i r,\n      In r (SCC'_list i) <-> SCC'_tag HM r = Some i.\n\n  Proof.\n    intros; split; intro.\n    unfold SCC'_list in H. rewrite SCC'_list_aux_exact in H. tauto.\n    unfold SCC'_list; rewrite SCC'_list_aux_exact; split; try tauto.\n    assert (SCC' r r). rewrite (SCC'_tag_exact hyps HM).\n    intuition. congruence. unfold SCCTopoOrdering.SCC' in H0. tauto.\n  Qed.\n\n  Lemma nodup_SCC'_list : forall i, nodup (SCC'_list i).\n\n  Proof. unfold SCC'_list; intros. apply nodup_SCC'_list_aux. auto. Qed.\n \n  Lemma chain_SCC'_red_Mod : forall i,\n      hd_red_Mod_SCC' i << hd_red_Mod S (SCC'_list i).\n\n  Proof.\n    unfold inclusion; intros. do 2 destruct H. exists x0. split. auto.\n    unfold hd_red_SCC' in H0. unfold hd_red. do 3 destruct H0.\n    exists x1; exists x2; exists x3. rewrite SCC'_list_exact. intuition.\n  Qed.\n\n(***********************************************************************)\n(** A faster way to compute SCC'_list but only half-certified *)\n\n  Definition SCC_list_fast i (Hi : i < dim) :=\n    listfilter R (list_of_vec (Vnth M Hi)).\n\n  Lemma incl_SCC_list_fast i (Hi : i < dim) :\n    Vnth (Vnth M Hi) Hi = true -> incl (SCC'_list i) (SCC_list_fast Hi).\n\n  Proof.\n    intros. assert(M[[i,i]] = true).\n    unfold mat_unbound; destruct (le_gt_dec dim i). cut False; try tauto; lia.\n    assert (g=Hi).\n    unfold Peano.gt in *; apply lt_unique. subst; auto.\n    unfold incl. intros. rewrite SCC'_list_exact in H1.\n    unfold SCCTopoOrdering.SCC'_tag in H1. simpl in *.\n    ded (find_first_exact _ _ _ H1).\n    destruct H2 as [r]; destruct H2; destruct H3; destruct H3. \n    subst a. unfold SCC_list_fast. eapply listfilter_in. eauto.\n    rewrite <- H. apply list_of_vec_exact.\n    destruct H4; ded (eq_In_find_first rule_eq_dec H4); do 2 destruct H6.\n\n    assert (x<dim). eapply find_first_Some_bound. eauto.\n\n    unfold SCC_list_fast. eapply listfilter_in. eauto.\n\n    assert ((M[[i,x]]) = true). rewrite HM.\n    ded (SCC_sym H3). clear H3. rename H9 into H3.\n    rewrite (SCC_effective_exact hyps HM) in H3.\n    unfold SCC_effective in H3. simpl in H3.\n    unfold rel_on_dom in H3. simpl in *. rewrite H6 in H3. \n    ded (eq_In_find_first rule_eq_dec H5).\n    do 2 destruct H9. rewrite H9 in H3.\n\n    assert (i=x0). eapply nodup_unique; eauto. subst x0.\n    unfold GoM in H3. rewrite HM in H3. auto.\n\n    unfold mat_unbound in H9; destruct (le_gt_dec dim i).\n    cut False; try tauto; lia.\n    destruct (le_gt_dec dim x). cut False; try tauto; lia.\n    rewrite <- H9. unfold Peano.gt in *.\n    assert (g=Hi). apply lt_unique. subst g; apply list_of_vec_exact.\n  Qed.\n\n  Lemma hd_red_Mod_SCC'_hd_red_Mod_fast : forall i (Hi : i < dim),\n      Vnth (Vnth M Hi) Hi = true ->\n      hd_red_Mod_SCC' i << hd_red_Mod S (SCC_list_fast Hi).\n\n  Proof.\n    intros. eapply incl_trans. apply chain_SCC'_red_Mod.\n    ded (incl_SCC_list_fast Hi H). unfold inclusion; intros.\n    destruct H1 as [z]; exists z. destruct H1; split; auto.\n    do 4 destruct H2. destruct H3.\n    exists x0; exists x1; exists x2; split; try split; try tauto.\n    apply H0. auto.\n  Qed.\n\n(***********************************************************************)\n(** Some lemma to prove trivial case of sub-problem termination *)\n\n  Lemma red_Mod_SCC_trivial_empty : WF (hd_red_Mod S nil).\n\n  Proof.\n    unfold WF; intro; apply SN_intro; intros.\n    do 2 destruct H. do 4 destruct H0. simpl in *; tauto.\n  Qed.\n\n  Lemma WF_chain_SCC_trivial : forall i,\n      SCC'_list i = nil -> WF (hd_red_Mod_SCC' i).\n\n  Proof.\n    intros. eapply WF_incl. apply chain_SCC'_red_Mod.\n    rewrite H. apply red_Mod_SCC_trivial_empty.\n  Qed.\n\n  Lemma red_Mod_SCC_trivial_singl : forall i r,\n      SCC'_list i = r :: nil -> ~ODPG r r ->  WF (hd_red_Mod_SCC' i).\n\n  Proof.\n    intros i r H H0 x. apply SN_intro. intros y Hy. apply SN_intro. intros z Hz.\n    cut (DPG r r). intro H1. assert False. apply H0. apply over_DPG. auto.\n    tauto.\n    assert (H1 : In r (SCC'_list i)). rewrite H. simpl. auto.\n    unfold SCC'_list in H1. rewrite SCC'_list_aux_exact in H1.\n    destruct H1 as [H1 H2]. destruct Hy as [x0 a]. destruct a as [s h].\n    eapply hd_red_Mod_rule2_hd_rules_graph; auto; unfold red_mod in *;\n    unfold hd_red_Mod_SCC' in *.\n    unfold hd_red_Mod_rule. split. auto. destruct h as [x1 e].\n    destruct e as [x2 e]. destruct e as [x3 a]. destruct a as [H3 H4].\n    destruct H4 as [H4 H5]. exists x3. assert (h : r = mkRule x1 x2).\n    rewrite <- SCC'_list_exact, H in H3; simpl in *; tauto.\n    rewrite h; simpl. subst x0. split; eauto.\n    unfold hd_red_Mod_rule. split. auto. destruct Hz as [x1 H3].\n    destruct H3 as [H3 H4]. destruct H4 as [x2 H4]. destruct H4 as [x3 H4].\n    destruct H4 as [x4 H4]. destruct H4 as [H4 H5]. destruct H5 as [H5 H6].\n    exists x4. assert (r = mkRule x2 x3).\n    rewrite <- SCC'_list_exact, H in H4; simpl in *; tauto.\n    rewrite H7. simpl. subst x1. split; eauto.\n  Qed.\n\n  Lemma WF_hd_red_Mod_SCC_fast_trivial : forall i (Hi : i < dim),\n      SCC_list_fast Hi = nil -> WF (hd_red_Mod_SCC' i).\n\n  Proof.\n    intros i Hi; intros. set (L := SCC'_list i). assert (L = SCC'_list i); auto.\n    destruct L. apply WF_chain_SCC_trivial. auto.\n    destruct L. destruct (ODPG_dec h h).\n    assert (R [i] =Some h).\n    assert (In h (SCC'_list i)). rewrite <- H0; simpl; auto.\n    rewrite SCC'_list_exact in H1. gen H1; intro.\n    unfold SCCTopoOrdering.SCC'_tag in H1. simpl in *.\n    ded (find_first_exact _ _ _ H1). do 2 destruct H3.\n    rewrite (SCC'_tag_exact hyps  HM) in H4. intuition.\n    cut (x=h). intro; subst x; auto.\n    rewrite H5, <- SCC'_list_exact, <- H0 in H2; simpl in *. intuition.\n\n    cut (M[[i,i]] = true). intros. unfold mat_unbound in H2.\n    destruct (le_gt_dec dim i); try discr.\n    unfold Peano.gt in *; assert (g=Hi). apply lt_unique. subst g.\n    ded (incl_SCC_list_fast Hi H2). rewrite H, <- H0 in *.\n    unfold incl in H3. ded (H3 h). simpl in *. tauto.\n    assert (SCC ODPG h h). split; apply t_step; auto.\n    rewrite (SCC_effective_exact hyps HM) in H2.\n    unfold SCC_effective in H2. simpl in *. unfold rel_on_dom in H2.\n    ded (restriction o); intuition. ded (eq_In_find_first rule_eq_dec H4).\n    do 2 destruct H3. ded(@nodup_unique rule R h R_nodup _ _ H1 H6).\n    subst x. rewrite H3 in H2. intuition.\n\n    eapply red_Mod_SCC_trivial_singl; eauto.\n\n    ded (nodup_SCC'_list i).\n    rewrite <-H0 in H1; simpl in H1; intuition. clear H1 H4 H5.\n    assert(In h (SCC'_list i)); assert(In h0 (SCC'_list i)); try rewrite <- H0;\n    simpl;auto.\n    rewrite SCC'_list_exact in *. rewrite <- H2 in H1.\n    assert (SCC' h h0). rewrite (SCC'_tag_exact hyps HM); auto.\n    split; congruence.\n    destruct H4. destruct H4. assert False; auto. tauto.\n    rewrite H2 in H1. unfold SCCTopoOrdering.SCC'_tag in *. \n    ded (In_find_first2 H2). ded (In_find_first2 H1).\n    do 2 destruct H6. do 2 destruct H7. simpl in *.\n    assert (x=x0). congruence. subst x0.\n\n    assert (SCC ODPG x x). destruct(rule_eq_dec x h). subst h.\n    eapply SCC_trans. apply H4. apply SCC_sym. apply H4.\n    do 2 destruct H9; try subst x; try tauto. simpl in *.\n    eapply SCC_trans. apply SCC_sym. apply H9. apply H9.\n    cut (M[[i,i]]=true). intros. unfold mat_unbound in H11.\n    destruct (le_gt_dec dim i). cut False; try tauto; lia.\n    unfold Peano.gt in *. assert (g=Hi). apply lt_unique. subst g.\n    ded (incl_SCC_list_fast Hi H11). rewrite H, <- H0 in *.\n    unfold incl in H12. ded (H12 h). simpl in *. tauto.\n\n    rewrite (SCC_effective_exact hyps HM) in H10.\n    unfold SCC_effective in H10. simpl in *. unfold rel_on_dom in H10.\n    assert (In x R). eapply exists_element_at_in. exists i; auto.\n    ded (eq_In_find_first rule_eq_dec H11). do 2 destruct H12.\n    ded (nodup_unique R_nodup H13 H6). subst x0.\n    rewrite H12 in H10. intuition.\n  Qed.\n\nEnd S.\n\nArguments WF_SCC'_union [Sig] _ [R] _ [ODPG] _ _ _ _ [M] _ _ _.\n\n(***********************************************************************)\n(** tactics *)\n\nLtac use_SCC_tag h M S R t :=\n  let x := fresh in\n    (set (x := SCC_tag_fast h M t); norm_in x (SCC_tag_fast h M t);\n      match eval compute in x with\n        | Some ?X1 =>\n          let Hi := fresh in\n            (assert (Hi : X1 < length R);\n              [ norm (length R); lia\n              | let L := fresh in\n                (set (L := SCC_list_fast R M Hi);\n                  norm_in L (SCC_list_fast R M Hi);\n                  assert (WF (hd_red_Mod S L)); subst L; clear Hi; clear x)])\n      end).\n\nLtac use_SCC_hyp M l := \n  let b := fresh \"b\" in\n    (set (b := Vnth (Vnth M l) l);\n      norm_in b (Vnth (Vnth M l) l);\n      match eval compute in b with\n        | false => apply WF_hd_red_Mod_SCC_fast_trivial with (Hi:=l); eauto\n        | true => eapply WF_incl;\n          [eapply hd_red_Mod_SCC'_hd_red_Mod_fast with (Hi:=l); auto | auto]\n      end).\n\nLtac use_SCC_all_hyps M i Hi Hj :=\n  let rec aux x :=\n    match x with\n      | 0 => lia\n      | S ?y => destruct i; [use_SCC_hyp M Hi | aux y]\n    end in\t\n    match type of Hj with\n      | le _ ?Y => aux Y\n    end.\n\nLtac SCC_name n1 n2 :=\n  match goal with \n    | |- WF (chain ?R) => set (n1 := dp R); set (n2 := int_red R #)\n    | |- WF (hd_red_mod ?E ?R) => set (n1 := R); set (n2 := red E #)\n    | |- WF (?X @ hd_red ?R) => set (n1 := R); set (n2 := X)\n    | |- WF (hd_red_Mod ?E ?R) => set (n1 := R); set (n2 := E)\n  end.\n\n", "meta": {"author": "fblanqui", "repo": "color", "sha": "f2ef98f7d13c5d71dd2a614ed2e6721703a34532", "save_path": "github-repos/coq/fblanqui-color", "path": "github-repos/coq/fblanqui-color/color-f2ef98f7d13c5d71dd2a614ed2e6721703a34532/DP/ASCCUnion.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2609440353772607}}
{"text": "From mathcomp Require Import ssreflect.\nFrom mathcomp Require eqtype ssrbool path.\nFrom deriving Require Import deriving.\nFrom stdpp Require Import gmap.\nFrom iris.heap_lang Require Import notation.\nFrom iris.heap_lang Require Import primitive_laws.\nFrom cryptis Require Import mathcomp_compat lib.\nFrom cryptis Require Export pre_term.\n\nDefinition int_of_key_type kt : Z :=\n  match kt with\n  | Enc => 0\n  | Dec => 1\n  end.\n\nDefinition key_type_of_int (n : Z) :=\n  match n with\n  | 0%Z => Enc\n  | _   => Dec\n  end.\n\nCanonical key_typeO := leibnizO key_type.\n\nInstance key_type_eq_dec : EqDecision key_type.\nProof.\nrefine (\n  fun kt1 kt2 =>\n    match kt1, kt2 with\n    | Enc, Enc => left _\n    | Dec, Dec => left _\n    | _, _ => right _\n    end); congruence.\nDefined.\n\nInstance int_of_key_typeK : Cancel (=) key_type_of_int int_of_key_type.\nProof. by case. Qed.\n\nInstance int_of_key_type_inj : Inj (=) (=) int_of_key_type.\nProof. by apply (@cancel_inj _ _ _ key_type_of_int); apply _. Qed.\n\nInstance int_of_key_type_countable : Countable key_type.\nProof. apply (inj_countable' _ _ int_of_key_typeK). Qed.\n\nInstance repr_key_type : Repr key_type := λ kt, #(int_of_key_type kt).\n\nCanonical termO := leibnizO term.\n\nGlobal Instance TExp_proper : Proper ((=) ==> (≡ₚ) ==> (=)) TExp.\nProof.\nby move=> t _ <- ts1 ts2 e; apply/TExp_inj; eauto.\nQed.\n\nLemma TExpC2 g t1 t2 : TExp g [t1; t2] = TExp g [t2; t1].\nProof.\nsuff -> : [t1; t2] ≡ₚ [t2; t1] by [].\nexact/Permutation_swap.\nQed.\n\nGlobal Instance pre_term_inhabited : Inhabited PreTerm.pre_term.\nProof. exact: (populate (PreTerm.PTInt 0)). Qed.\n\nDefinition pre_term_eq_dec : EqDecision PreTerm.pre_term :=\n  Eval hnf in def_eq_decision _.\nGlobal Existing Instance pre_term_eq_dec.\n\nGlobal Instance term_inhabited : Inhabited term.\nProof. exact: (populate (TInt 0)). Qed.\n\nDefinition term_eq_dec : EqDecision term :=\n  Eval hnf in def_eq_decision _.\nGlobal Existing Instance term_eq_dec.\n\nSection ValOfTerm.\n\nImport PreTerm.\n\nFixpoint val_of_pre_term_rec pt : val :=\n  match pt with\n  | PTInt n =>\n    (#TInt_tag, #n)\n  | PTPair t1 t2 =>\n    (#TPair_tag, (val_of_pre_term_rec t1, val_of_pre_term_rec t2))%V\n  | PTNonce l =>\n    (#TNonce_tag, #l)%V\n  | PTKey kt t =>\n    (#TKey_tag, (#(int_of_key_type kt), val_of_pre_term_rec t))%V\n  | PTEnc t1 t2 =>\n    (#TEnc_tag, (val_of_pre_term_rec t1, val_of_pre_term_rec t2))%V\n  | PTHash t =>\n    (#THash_tag, val_of_pre_term_rec t)\n  | PTExp t ts =>\n    (#TExp_tag, (val_of_pre_term_rec t,\n                 repr_list (map val_of_pre_term_rec ts)))\n  end.\n\nDefinition val_of_pre_term_aux : seal val_of_pre_term_rec. by eexists. Qed.\nDefinition val_of_pre_term : Repr pre_term := unseal val_of_pre_term_aux.\nLemma val_of_pre_term_eq : val_of_pre_term = val_of_pre_term_rec.\nProof. exact: seal_eq. Qed.\nGlobal Existing Instance val_of_pre_term.\n\nFixpoint val_of_term_rec t : val :=\n  match t with\n  | TInt n =>\n    (#TInt_tag, #n)\n  | TPair t1 t2 =>\n    (#TPair_tag, (val_of_term_rec t1, val_of_term_rec t2))%V\n  | TNonce l =>\n    (#TNonce_tag, #l)%V\n  | TKey kt t =>\n    (#TKey_tag, (#(int_of_key_type kt), val_of_term_rec t))%V\n  | TEnc t1 t2 =>\n    (#TEnc_tag, (val_of_term_rec t1, val_of_term_rec t2))%V\n  | THash t =>\n    (#THash_tag, val_of_term_rec t)\n  | TExp' t ts _ =>\n    (#TExp_tag, (val_of_term_rec t, repr ts))\n  end.\n\nDefinition val_of_term_aux : seal val_of_term_rec. by eexists. Qed.\nDefinition val_of_term : term -> val := unseal val_of_term_aux.\nLemma val_of_term_eq : val_of_term = val_of_term_rec.\nProof. exact: seal_eq. Qed.\nCoercion val_of_term : term >-> val.\nGlobal Instance repr_term : Repr term := val_of_term.\n\nLemma val_of_pre_term_unfold t :\n  val_of_pre_term (unfold_term t) = val_of_term t.\nProof.\nrewrite val_of_term_eq val_of_pre_term_eq.\nelim/term_ind': t => //=; try by move=> *; congruence.\nmove=> t -> pts _.\nby rewrite [repr_list pts]repr_list_val /repr val_of_pre_term_eq.\nQed.\n\nEnd ValOfTerm.\n\nLemma val_of_term_TExp t ts :\n  ~ is_exp t ->\n  path.sorted order.Order.le ts ->\n  val_of_term (TExp t ts) = (#TExp_tag, (val_of_term t, repr ts))%V.\nProof.\nmove=> nexp sorted_ts.\nrewrite -[LHS]val_of_pre_term_unfold unfold_TExp.\nrewrite order.Order.POrderTheory.sort_le_id // ?path.sorted_map; last first.\n  rewrite (_ : path.sorted _ _ = path.sorted order.Order.le ts) //.\n  by case: (path.sorted _ _) sorted_ts.\nrewrite -[in RHS](val_of_pre_term_unfold t) val_of_pre_term_eq /=.\nrewrite [repr_list ts]repr_list_val map_map.\ndo !congr PairV; congr repr_list.\nelim: ts {sorted_ts} => //= {nexp}t ts -> /=.\nby rewrite /repr_term -val_of_pre_term_unfold val_of_pre_term_eq.\nQed.\n\nGlobal Instance val_of_pre_term_inj : Inj (=) (=) val_of_pre_term.\nProof.\nrewrite val_of_pre_term_eq.\nelim.\n- by move=> n1 [] //= n2 [] ->.\n- by move=> t11 IH1 t12 IH2 [] //= t21 t22 [] /IH1 -> /IH2 ->.\n- by move=> l1 [] //= l2 [] //= ->.\n- by move=> kt1 t1 IH [] //= kt2 t2 [] /int_of_key_type_inj -> /IH ->.\n- by move=> t11 IH1 t12 IH2 [] //= ?? [] /IH1 -> /IH2 ->.\n- by move=> ? IH [] //= ? [] /IH ->.\n- move=> t1 IHt ts1 IHts [] //= t2 ts2 [] /IHt -> e_ts; congr PreTerm.PTExp.\n  move: e_ts; rewrite repr_list_eq.\n  elim: ts1 IHts ts2 {t1 t2 IHt} => /= [_ [] //|t1 ts1 H [] IHt {}/H IHts].\n  by case=> //= t2 ts2 [] /IHt -> /IHts ->.\nQed.\n\nGlobal Instance val_of_term_inj : Inj (=) (=) val_of_term.\nProof.\nmove=> t1 t2 e_t1t2; apply: unfold_term_inj.\napply: val_of_pre_term_inj.\nby rewrite !val_of_pre_term_unfold.\nQed.\n\nGlobal Instance countable_term : Countable term.\nProof. exact: def_countable. Qed.\n\nGlobal Instance infinite_term : Infinite term.\nProof.\npose int_of_term (t : term) :=\n  if t is TInt n then Some n else None.\napply (inj_infinite TInt int_of_term).\nby move=> n; rewrite /int_of_term.\nQed.\n\nDefinition term_height t :=\n  PreTerm.height (unfold_term t).\n\nFixpoint nonces_of_pre_term pt : gset loc :=\n  match pt with\n  | PreTerm.PTInt _ => ∅\n  | PreTerm.PTPair t1 t2 => nonces_of_pre_term t1 ∪ nonces_of_pre_term t2\n  | PreTerm.PTNonce l => {[l]}\n  | PreTerm.PTKey _ t => nonces_of_pre_term t\n  | PreTerm.PTEnc t1 t2 => nonces_of_pre_term t1 ∪ nonces_of_pre_term t2\n  | PreTerm.PTHash t => nonces_of_pre_term t\n  | PreTerm.PTExp t ts => nonces_of_pre_term t ∪ ⋃ map nonces_of_pre_term ts\n  end.\n\nDefinition nonces_of_term_def (t : term) :=\n  nonces_of_pre_term (unfold_term t).\nArguments nonces_of_term_def /.\nDefinition nonces_of_term_aux : seal nonces_of_term_def. by eexists. Qed.\nDefinition nonces_of_term := unseal nonces_of_term_aux.\nLemma nonces_of_term_eq : nonces_of_term = nonces_of_term_def.\nProof. exact: seal_eq. Qed.\n\nLemma nonces_of_termE t :\n  nonces_of_term t =\n  match t with\n  | TInt _ => ∅\n  | TPair t1 t2 => nonces_of_term t1 ∪ nonces_of_term t2\n  | TNonce l => {[l]}\n  | TKey _ t => nonces_of_term t\n  | TEnc t1 t2 => nonces_of_term t1 ∪ nonces_of_term t2\n  | THash t => nonces_of_term t\n  | TExp' t pts _ => nonces_of_term t ∪ ⋃ map nonces_of_pre_term pts\n  end.\nProof.\nby rewrite nonces_of_term_eq; case: t => //=.\nQed.\n\nLemma nonces_of_term_TExp t ts :\n  nonces_of_term (TExp t ts)\n  = nonces_of_term t ∪ ⋃ map nonces_of_term ts.\nProof.\nrewrite nonces_of_term_eq /nonces_of_term_def.\ncase: unfold_TExpP => pts' e_pts' /=.\nby rewrite [in LHS]e_pts' map_map.\nQed.\n\nModule Spec.\n\nImplicit Types N : namespace.\n\nDefinition tag_def N (t : term) :=\n  TPair (TInt (Zpos (encode N))) t.\nDefinition tag_aux : seal tag_def. by eexists. Qed.\nDefinition tag := unseal tag_aux.\nLemma tag_eq : tag = tag_def. Proof. exact: seal_eq. Qed.\n\nDefinition untag_def N (t : term) :=\n  match t with\n  | TPair (TInt (Zpos m)) t =>\n    if decide (encode N = m) then Some t else None\n  | _ => None\n  end.\nDefinition untag_aux : seal untag_def. by eexists. Qed.\nDefinition untag := unseal untag_aux.\nLemma untag_eq : untag = untag_def. Proof. exact: seal_eq. Qed.\n\nLemma tagK N t : untag N (tag N t) = Some t.\nProof.\nrewrite untag_eq tag_eq /untag_def /tag_def /=.\nby rewrite decide_left.\nQed.\n\nInstance tag_inj : Inj2 (=) (=) (=) tag.\nProof.\nrewrite tag_eq /tag_def => c1 t1 c2 t2 [] e ->.\nsplit=> //; by apply: inj e.\nQed.\n\nLemma untagK N t1 t2 :\n  untag N t1 = Some t2 ->\n  t1 = tag N t2.\nProof.\nrewrite untag_eq tag_eq /=.\ncase: t1=> [] // [] // [] //= m.\nby case: decide => // <- _ [->].\nQed.\n\nLemma untag_tag_ne N1 N2 t :\n  N1 ≠ N2 →\n  Spec.untag N1 (Spec.tag N2 t) = None.\nProof.\nmove=> neq; rewrite Spec.untag_eq Spec.tag_eq /=.\nrewrite decide_False //.\nmove=> eq_enc; apply: neq.\nby apply: encode_inj eq_enc.\nQed.\n\nVariant untag_spec N t : option term → Type :=\n| UntagSome t' of t = Spec.tag N t' : untag_spec N t (Some t')\n| UntagNone of (∀ t', t ≠ Spec.tag N t') : untag_spec N t None.\n\nLemma untagP N t : untag_spec N t (Spec.untag N t).\nProof.\ncase e: (Spec.untag N t) => [t'|]; constructor.\n- by rewrite (Spec.untagK _ _ _ e).\n- move=> t' e'; by rewrite e' Spec.tagK in e.\nQed.\n\nDefinition to_int t :=\n  if t is TInt n then Some n else None.\n\nVariant to_int_spec t : option Z → Type :=\n| AsIntSome n of t = TInt n : to_int_spec t (Some n)\n| AsIntNone of (∀ n, t ≠ TInt n) : to_int_spec t None.\n\nLemma to_intP t : to_int_spec t (Spec.to_int t).\nProof. by case: t => *; constructor; congruence. Qed.\n\nDefinition untuple t :=\n  match t with\n  | TPair t1 t2 => Some (t1, t2)\n  | _ => None\n  end.\n\nFixpoint proj t n {struct t} :=\n  match t, n with\n  | TPair t _, 0 => Some t\n  | TPair _ t, S n => proj t n\n  | _, _ => None\n  end.\n\nDefinition enc k t : term :=\n  match k with\n  | TKey Enc k => TEnc k t\n  | _ => t (* Arbitrarily *)\n  end.\n\nDefinition dec k t : option term :=\n  match k, t with\n  | TKey Dec k1, TEnc k2 t =>\n    if decide (k1 = k2) then Some t else None\n  | _, _ => None\n  end.\n\nDefinition is_key t :=\n  match t with\n  | TKey kt _ => Some kt\n  | _ => None\n  end.\n\nVariant is_key_spec t : option key_type → Type :=\n| IsKeySome kt k of t = TKey kt k : is_key_spec t (Some kt)\n| IsKeyNone of (∀ kt k, t ≠ TKey kt k) : is_key_spec t None.\n\nLemma is_keyP t : is_key_spec t (is_key t).\nProof.\ncase: t; try by right.\nby move=> kt t; eleft.\nQed.\n\nDefinition to_ek t :=\n  if t is TKey Enc _ then Some t else None.\n\nVariant to_ek_spec t : option term → Type :=\n| ToEKSome k of t = TKey Enc k : to_ek_spec t (Some t)\n| ToEKNone of (∀ k, t ≠ TKey Enc k) : to_ek_spec t None.\n\nLemma to_ekP t : to_ek_spec t (to_ek t).\nProof.\ncase: t; try by right.\ncase; try by right.\nby move=> t; eleft.\nQed.\n\nDefinition to_dk t :=\n  if t is TKey Dec _ then Some t else None.\n\nVariant to_dk_spec t : option term → Type :=\n| ToDKSome k of t = TKey Dec k : to_dk_spec t (Some t)\n| ToDKNone of (∀ k, t ≠ TKey Dec k) : to_dk_spec t None.\n\nLemma to_dkP t : to_dk_spec t (to_dk t).\nProof.\ncase: t; try by right.\ncase; try by right.\nby move=> t; eleft.\nQed.\n\nDefinition of_list_aux : seal (foldr TPair (TInt 0)). by eexists. Qed.\nDefinition of_list := unseal of_list_aux.\nLemma of_list_eq : of_list = foldr TPair (TInt 0).\nProof. exact: seal_eq. Qed.\n\nFixpoint to_list t : option (list term) :=\n  match t with\n  | TInt 0 => Some []\n  | TPair t1 t2 =>\n    match to_list t2 with\n    | Some l => Some (t1 :: l)\n    | None => None\n    end\n  | _ => None\n  end.\n\nLemma of_listK l : to_list (of_list l) = Some l.\nProof. rewrite of_list_eq; by elim: l => //= t l ->. Qed.\n\nLemma to_listK t ts :\n  to_list t = Some ts →\n  t = of_list ts.\nProof.\nrewrite of_list_eq /=; elim/term_ind': t ts => //.\n  by case=> [] // _ [<-].\nmove=> t _ ts' IH /= ts.\ncase e: to_list => [ts''|] // [<-].\nby rewrite /= (IH _ e).\nQed.\n\nInductive to_list_spec : term → option (list term) → Type :=\n| ToListSome ts : to_list_spec (of_list ts) (Some ts)\n| ToListNone t  : to_list_spec t None.\n\nLemma to_listP t : to_list_spec t (to_list t).\nProof.\ncase e: to_list => [ts|]; last constructor.\nby rewrite (to_listK _ _ e); constructor.\nQed.\n\nLemma of_list_inj : Inj eq eq of_list.\nProof.\nmove=> ts1 ts2 e; apply: Some_inj.\nby rewrite -of_listK e of_listK.\nQed.\n\nDefinition tenc c k t := enc k (tag c t).\n\nDefinition tdec c k t :=\n  match dec k t with\n  | Some t => untag c t\n  | None => None\n  end.\n\n\nDefinition texp t1 t2 :=\n  if t1 is TExp' base exp _ then\n    TExp base (t2 :: map fold_term exp)\n  else TInt 0.\n\nLemma texpA t1 ts1 t2 : texp (TExp t1 ts1) t2 = TExp t1 (t2 :: ts1).\nProof.\nrewrite /texp {1}unlock /= fold_wf_termE normalize_unfold1 normalize_unfoldn.\nrewrite unfold_termK.\napply: TExp_perm.\nrewrite seq.perm_cons -{2}[ts1](seq.mapK unfold_termK).\nby rewrite seq.perm_map // path.perm_sort.\nQed.\n\nLemma unfold_exp t1 t2 :\n  unfold_term (texp t1 t2) = PreTerm.exp (unfold_term t1) (unfold_term t2).\nProof.\ncase: t1 => //= t1 ts1 /(ssrbool.elimT ssrbool.andP) [wf_ts1 ?].\nrewrite unfold_TExp /=; congr PreTerm.PTExp.\napply: (ssrbool.elimT (perm_sort_leP _ _ _ _)); rewrite seq.perm_cons.\nrewrite -[@List.map]/@seq.map -seq.map_comp seq.map_id_in //= => {}t1 in_ts1.\nby rewrite fold_termK // (ssrbool.elimT seq.allP wf_ts1).\nQed.\n\nDefinition zero : term := TInt 0.\n\nEnd Spec.\n\nArguments repr_term /.\nArguments Spec.tag_def /.\nArguments Spec.untag_def /.\n\nExisting Instance Spec.of_list_inj.\n", "meta": {"author": "arthuraa", "repo": "cryptis", "sha": "056d1fb93b8d8395b0c19639edb961d4919c63f6", "save_path": "github-repos/coq/arthuraa-cryptis", "path": "github-repos/coq/arthuraa-cryptis/cryptis-056d1fb93b8d8395b0c19639edb961d4919c63f6/term.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.26083423976654524}}
{"text": "Require Import ExtLib.Structures.Traversable.\nRequire Import ExtLib.Data.HList.\nRequire Import ExtLib.Tactics.\nRequire Import MirrorCore.Util.Compat.\nRequire Import MirrorCore.ExprI.\nRequire Import MirrorCore.ExprDAs.\nRequire Import MirrorCore.SubstI.\nRequire Import MirrorCore.VariablesI.\nRequire Import MirrorCore.UnifyI.\nRequire Import MirrorCore.VarsToUVars.\nRequire Import MirrorCore.Lemma.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nLemma Forall_iff : forall {T} (P : T -> Prop) a b,\n    Forall P (a :: b) <-> (P a /\\ Forall P b).\nProof. clear. split.\n       - inversion 1; auto.\n       - constructor; tauto.\nQed.\nLemma and_split_iff : forall (P Q R S : Prop),\n    (P <-> R) -> (Q <-> S) ->\n    ((P /\\ Q) <-> (R /\\ S)).\nProof. clear. tauto. Qed.\n\nSection lemma_apply.\n  Variable typ : Set.\n  Variable expr : Set.\n  Context {RType_typ : RType typ}.\n  Context {RTypeOk_typ : RTypeOk}.\n  Context {Expr_expr : Expr _ expr}.\n  Context {ExprOk_expr : ExprOk Expr_expr}.\n  Context {Typ0_Prop : Typ0 _ Prop}.\n  Let tyProp : typ := @typ0 _ _ _ _.\n  Context {subst : Type}.\n  Context {ExprUVar_expr : ExprUVar expr}.\n  Context {ExprUVarOk_expr : ExprUVarOk ExprUVar_expr}.\n  Context {Subst_subst : Subst subst expr}.\n  Context {SubstOk_subst : SubstOk subst typ expr}.\n  (** TODO: Ideally I wouldn't need these things, but they are necessary b/c of\n   ** where [substR] fits into things\n   **)\n  Context {SubstUpdate_subst : SubstUpdate subst expr}.\n  Context {SubstUpdateOk_subst : SubstUpdateOk subst typ expr}.\n\n  Variable unify : unifier typ expr subst.\n\n  Hypothesis Hunify : unify_sound unify.\n\n  Definition eapplicable (s : subst) (tus tvs : EnvI.tenv typ)\n             (lem : lemma typ expr expr) (e : expr)\n  : option subst :=\n    let pattern := vars_to_uvars 0 (length tus) lem.(concl) in\n    unify (tus ++ lem.(vars)) tvs 0 pattern e tyProp s.\n\n  Ltac fill_holes :=\n    let is_prop P := match type of P with\n                       | Prop => idtac\n                       | _ => fail\n                     end\n    in\n    repeat match goal with\n             | |- _ => progress intros\n             | H : exists x , _ |- _ => destruct H\n             | H : _ /\\ _ |- _ => destruct H\n             | |- exists x, _ /\\ _ =>\n               eexists; split; [ solve [ eauto ] | ]\n             | |- _ /\\ _ =>\n               (split; eauto); [ ]\n             | [ H : _ -> _ , H' : ?P |- _ ] =>\n               is_prop P ;\n                 specialize (H H')\n             | [ H : forall x, @?X x -> _ , H' : ?P |- _ ] =>\n               is_prop P ;\n                 specialize (@H _ H')\n             | [ H : forall x y, @?X x y -> _ , H' : ?P |- _ ] =>\n               is_prop P ;\n                 first [ specialize (@H _ _ H')\n                       | specialize (fun y => @H _ y H')\n                       | specialize (fun x => @H x _ H')\n                       | specialize (@H _ _ eq_refl)\n                       | specialize (fun y => @H _ y eq_refl)\n                       | specialize (fun x => @H x _ eq_refl)\n                       ]\n             | [ H : forall x y z, @?X x y z -> _ , H' : ?P |- _ ] =>\n               is_prop P ;\n                 first [ specialize (@H _ _ _ H')\n                       | specialize (fun x => @H x _ _ H')\n                       | specialize (fun y => @H _ y _ H')\n                       | specialize (fun z => @H _ _ z H')\n                       | specialize (fun x y => @H x y _ H')\n                       | specialize (fun y z => @H _ y z H')\n                       | specialize (fun x z => @H x _ z H')\n                       | specialize (@H _ _ _ eq_refl)\n                       | specialize (fun x => @H x _ _ eq_refl)\n                       | specialize (fun y => @H _ y _ eq_refl)\n                       | specialize (fun z => @H _ _ z eq_refl)\n                       | specialize (fun x y => @H x y _ eq_refl)\n                       | specialize (fun y z => @H _ y z eq_refl)\n                       | specialize (fun x z => @H x _ z eq_refl)\n                       ]\n             | [ H : forall x y z a, @?X x y z a -> _ , H' : ?P |- _ ] =>\n               is_prop P ;\n                 first [ specialize (@H _ _ _ _ H')\n                       | specialize (fun x => @H x _ _ _ H')\n                       | specialize (fun y => @H _ y _ _ H')\n                       | specialize (fun z => @H _ _ z _ H')\n                       | specialize (fun a => @H _ _ _ a H')\n                       | specialize (fun x y => @H x y _ _ H')\n                       | specialize (fun y z => @H _ y z _ H')\n                       | specialize (fun z a => @H _ _ z a H')\n                       | specialize (fun x a => @H x _ _ a H')\n                       | specialize (fun x y z => @H x y z _ H')\n                       | specialize (fun y z a => @H _ y z a H')\n                       | specialize (fun x z a => @H x _ z a H')\n                       | specialize (fun x y a => @H x y _ a H')\n                       | specialize (fun x => @H x _ _ _ eq_refl)\n                       | specialize (fun y => @H _ y _ _ eq_refl)\n                       | specialize (fun z => @H _ _ z _ eq_refl)\n                       | specialize (fun a => @H _ _ _ a eq_refl)\n                       | specialize (fun x y => @H x y _ _ eq_refl)\n                       | specialize (fun y z => @H _ y z _ eq_refl)\n                       | specialize (fun z a => @H _ _ z a eq_refl)\n                       | specialize (fun x a => @H x _ _ a eq_refl)\n                       | specialize (fun x y z => @H x y z _ eq_refl)\n                       | specialize (fun y z a => @H _ y z a eq_refl)\n                       | specialize (fun x z a => @H x _ z a eq_refl)\n                       | specialize (fun x y a => @H x y _ a eq_refl)\n                       ]\n           end.\n\n  Lemma eapplicable_sound'\n  : forall s tus tvs lem g s1,\n      eapplicable s tus tvs lem g = Some s1 ->\n      WellFormed_subst s ->\n      WellFormed_subst s1 /\\\n      forall sD (gD : exprT _ _ Prop),\n        (@lemmaD _ _ _ _ _ (exprD_typ0 (T:=Prop)) _ nil nil lem) ->\n        substD (tus ++ lem.(vars)) tvs s = Some sD ->\n        exprD_typ0 (tus ++ lem.(vars)) tvs g = Some gD ->\n        exists s1D (pDs : list (exprT _ _ Prop)),\n          substR (tus ++ lem.(vars)) tvs s s1 /\\\n          substD (tus ++ lem.(vars)) tvs s1 = Some s1D /\\\n          mapT (fun e => exprD_typ0 (tus ++ lem.(vars)) tvs (vars_to_uvars 0 (length tus) e)) lem.(premises) = Some pDs /\\\n          forall (us : hlist _ tus) (us' : hlist _ lem.(vars)) (vs : hlist _ tvs),\n            s1D (hlist_app us us') vs ->\n            (Forall (fun pD => pD (hlist_app us us') vs) pDs -> gD (hlist_app us us') vs)\n            /\\ sD (hlist_app us us') vs.\n  Proof.\n    unfold eapplicable. intros.\n    eapply (@Hunify (tus ++ vars lem) tvs _ _ _ _ _ nil) in H; auto.\n    forward_reason.\n    split; eauto.\n\n    simpl in *. intros.\n    unfold exprD_typ0 in H4; forward.\n    inv_all; subst.\n    specialize (fun v1 Hv1 => @H1 v1 _ _ Hv1 H4 H3).\n\n    unfold lemmaD in H2. simpl in H2.\n    forward.\n    eapply lemmaD'_weakenU in H2; eauto.\n    { revert H2. instantiate (1 := tus). simpl. intro.\n      destruct H2 as [ ? [ ? ? ] ].\n      unfold lemmaD' in H2. forward; inv_all; subst.\n      rewrite exprD_typ0_conv\n         with (pfu := eq_refl) (pfv := eq_sym (app_nil_r_trans lem.(vars))) in H7.\n      autorewrite_with_eq_rw_in H7.\n      unfold exprD_typ0 in H7. forward; inv_all; subst.\n      eapply (@vars_to_uvars_sound _ _ _ _ _ _ _ _ tus (concl lem) nil tyProp) in H7; eauto.\n      simpl in H7. forward_reason.\n      eapply exprD_weakenV with (tvs' := tvs) in H7; eauto.\n      forward_reason.\n      specialize (H1 _ H7).\n      forward_reason.\n      assert (exists pDs,\n                List.mapT_list (F:=option)\n                  (fun e1 : expr =>\n                     exprD_typ0 (tus ++ vars lem) tvs (vars_to_uvars 0 (length tus) e1))\n                  (premises lem) = Some pDs /\\\n                forall us vs vs',\n                  Forall (fun p => p (hlist_app us vs') vs) pDs <-> Forall (fun p => p us (hlist_app vs' Hnil)) l).\n      { clear - H2 ExprOk_expr RTypeOk_typ ExprUVarOk_expr.\n        revert l H2. induction (premises lem); simpl; intros; inv_all; subst.\n        + eexists; split; [ reflexivity | intuition; constructor ].\n        + forward; inv_all; subst.\n          eapply IHl in H0; clear IHl.\n          rewrite exprD_typ0_conv\n             with (pfu := eq_refl) (pfv := eq_sym (app_nil_r_trans _)) in H.\n          autorewrite_with_eq_rw_in H.\n          forward.\n          unfold exprD_typ0 in H.\n          forward.\n          change (vars lem) with (nil ++ vars lem) in H.\n          eapply vars_to_uvars_sound in H; eauto with typeclass_instances.\n          simpl in H. forward_reason.\n          eapply exprD_weakenV with (tvs' := tvs) in H; eauto.\n          forward_reason.\n          unfold exprD_typ0.\n          change_rewrite H.\n          change_rewrite H0.\n          eexists; split; [ reflexivity | ].\n          inv_all; subst.\n          intros. autorewrite with eq_rw.\n          do 2 rewrite Forall_iff.\n          eapply and_split_iff; eauto.\n          { specialize (H5 (hlist_app us vs') Hnil vs).\n            simpl in *.\n            rewrite <- H5; clear H5.\n            rewrite <- H3; clear H3.\n            simpl. rewrite hlist_app_nil_r.\n            clear.\n            generalize dependent (app_nil_r_trans (vars lem)).\n            generalize dependent (vars lem ++ nil).\n            intros; subst. reflexivity. } }\n      forward_reason.\n      do 2 eexists; split; eauto.\n      split; eauto.\n      split; eauto.\n      intros.\n      eapply H11 in H14; clear H11.\n      clear - H14 H13 H12 H6 H9 H8 H5.\n      destruct H14.\n      repeat match goal with\n               | H : _ , H' : _ |- _ =>\n                 first [ specialize (H H') | specialize (H Hnil) ]\n             end.\n      rewrite H13; clear H13.\n      split; auto.\n      intros. autorewrite with eq_rw.\n      simpl in *. rewrite <- H0; clear H0.\n      specialize (H9 (hlist_app us us') Hnil vs).\n      simpl in *. rewrite <- H9; clear H9.\n      rewrite <- H8; clear H8.\n      eapply H6 in H5; clear H6.\n      rewrite foralls_sem in H5.\n      specialize (H5 us').\n      eapply impls_sem in H5.\n      { revert H5.\n        autorewrite with eq_rw.\n        rewrite hlist_app_nil_r.\n        generalize (app_nil_r_trans (vars lem)).\n        generalize (vars lem ++ nil). intros; subst. eapply H5. }\n      { rewrite List.Forall_map. assumption. } }\n    { clear - ExprOk_expr.\n      intros. eapply exprD_typ0_weaken in H.\n      destruct H. exists x.\n      forward_reason; split; eauto.\n      intros. rewrite <- H0. reflexivity. }\n  Qed.\n\nEnd lemma_apply.\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/LemmaApply.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.26083423976654524}}
{"text": "(** Type syntax:\n\n Simple types with a Unit type, the functional arrow and a reference type\n to distinguish pure terms from terms with references.\n\n*)\n\nInductive Ty: Set :=\n  | Unit : Ty\n  | Arr  : Ty -> Ty -> Ty\n  | Ref : Ty -> Ty\n.\n\nNotation \"A ⇒  B\" := (Arr A B) (at level 17, right associativity).\n", "meta": {"author": "vsiles", "repo": "STLC_Ref", "sha": "20c184ae972cc4e23dba689f62b73bfb37efe9ad", "save_path": "github-repos/coq/vsiles-STLC_Ref", "path": "github-repos/coq/vsiles-STLC_Ref/STLC_Ref-20c184ae972cc4e23dba689f62b73bfb37efe9ad/ty.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.2608342326594719}}
{"text": "Require Export Coq.Lists.List. Export ListNotations.\nRequire Export Coq.ZArith.ZArith. Open Scope Z_scope.\nRequire Export coqutil.Word.Interface coqutil.Word.Properties.\nRequire Export coqutil.Map.Interface coqutil.Map.Properties.\nRequire Import coqutil.Tactics.rdelta coqutil.Tactics.destr coqutil.Decidable.\nRequire Import coqutil.Tactics.rewr coqutil.Tactics.Tactics.\nRequire Export coqutil.Z.Lia.\nRequire Export coqutil.Datatypes.PropSet.\nRequire Export bedrock2.Lift1Prop.\nRequire Export bedrock2.Map.Separation.\nRequire Export bedrock2.Map.SeparationLogic.\nRequire Export bedrock2.Array.\nRequire Export bedrock2.Scalars.\nRequire Export bedrock2.ptsto_bytes.\nRequire Export coqutil.Word.SimplWordExpr.\nRequire Export bedrock2.SepLogAddrArith.\nRequire Import coqutil.Tactics.Simp.\nRequire Export riscv.Utility.Utility.\nRequire Import riscv.Utility.Encode.\nRequire Import riscv.Spec.Decode.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Logic.PropExtensionality.\n\nDeclare Scope sep_scope.\n\nInfix \"*\" := sep : sep_scope.\n\nDelimit Scope sep_scope with sep.\nArguments impl1 {T} (_)%sep (_)%sep.\nArguments iff1 {T} (_)%sep (_)%sep.\n\n(* TODO does not get rid of %sep in printing as intended *)\nArguments sep {key} {value} {map} (_)%sep (_)%sep.\n\nDefinition bytes_per_word{width}{BW: Bitwidth width}: Z := Memory.bytes_per_word width.\n\nSection ptstos.\n  Context {width} {BW: Bitwidth width} {word: word.word width} {word_ok: word.ok word}.\n  Context {mem : map.map word byte} {mem_ok: map.ok mem}.\n  Context (iset: InstructionSet).\n\n  Definition word_array: word -> list word -> mem -> Prop :=\n    array ptsto_word (word.of_Z bytes_per_word).\n\n  (* we use InvalidInstruction to put data into the instruction memory, so we have\n     to allow them, but make sure that they can be represented with 32 bits *)\n  Definition valid_InvalidInstruction(instr: Instruction): Prop :=\n    exists n, 0 <= n < 2 ^ 32 /\\ instr = InvalidInstruction n.\n\n  (* contains all the conditions needed to successfully execute instr, except\n     that addr needs to be in the set of executable addresses, which is dealt with elsewhere *)\n  Definition ptsto_instr(addr: word)(instr: Instruction): mem -> Prop :=\n    (truncated_scalar Syntax.access_size.four addr (encode instr) *\n     emp (verify instr iset \\/ valid_InvalidInstruction instr) *\n     emp ((word.unsigned addr) mod 4 = 0))%sep.\n\n  Definition program(addr: word)(prog: list Instruction): mem -> Prop :=\n    array ptsto_instr (word.of_Z 4) addr prog.\n\n  Lemma invert_ptsto_instr: forall {addr instr R m},\n    (ptsto_instr addr instr * R)%sep m ->\n     (verify instr iset \\/ valid_InvalidInstruction instr) /\\\n     (word.unsigned addr) mod 4 = 0.\n  Proof.\n    intros.\n    unfold array, ptsto_instr in *.\n    lazymatch goal with\n    | H: (?T * ?P1 * ?P2 * R)%sep ?m |- _ =>\n      assert ((T * R * P1 * P2)%sep m) as A by ecancel_assumption; clear H\n    end.\n    do 2 (apply sep_emp_r in A; destruct A as [A ?]).\n    auto.\n  Qed.\n\n  Lemma invert_ptsto_program1: forall {addr instr R m},\n    (program addr [instr] * R)%sep m ->\n     (verify instr iset \\/ valid_InvalidInstruction instr) /\\\n     (word.unsigned addr) mod 4 = 0.\n  Proof.\n    unfold program. intros. simpl in *. eapply invert_ptsto_instr.\n    ecancel_assumption.\n  Qed.\n\n  Lemma cast_word_array_to_bytes bs (addr : word) : iff1\n    (array ptsto_word (word.of_Z bytes_per_word) addr bs)\n    (array ptsto (word.of_Z 1) addr (flat_map (fun x =>\n       (LittleEndianList.le_split (Z.to_nat bytes_per_word) (word.unsigned x)))\n          bs)).\n  Proof.\n    revert addr; induction bs; intros; [reflexivity|].\n    cbn [array flat_map].\n    etransitivity. 1:eapply Proper_sep_iff1; [reflexivity|]. 1:eapply IHbs.\n    etransitivity. 2:symmetry; eapply bytearray_append.\n    eapply Proper_sep_iff1.\n    { unfold scalar, truncated_word, truncated_scalar, littleendian, ptsto_bytes.\n      rewrite HList.tuple.to_list_of_list. reflexivity. }\n    assert (0 < bytes_per_word). { (* TODO: deduplicate *)\n      unfold bytes_per_word; simpl; destruct width_cases as [EE | EE]; rewrite EE; cbv; trivial.\n    }\n    Morphisms.f_equiv.\n    Morphisms.f_equiv.\n    Morphisms.f_equiv.\n    simpl.\n    rewrite LittleEndianList.length_le_split.\n    rewrite Z2Nat.id; blia.\n  Qed.\n\n  Lemma putmany_of_footprint_None: forall n (vs: HList.tuple byte n) (addr: word) (z: Z) (m: mem),\n      0 < z ->\n      z + Z.of_nat n <= 2 ^ width ->\n      map.get m addr = None ->\n      map.get (map.putmany_of_tuple (Memory.footprint (word.add addr (word.of_Z z)) n) vs m)\n              addr = None.\n  Proof.\n    induction n; intros.\n    - simpl. assumption.\n    - destruct vs as [v vs]. simpl.\n      assert (2 ^ width > 0) as Gz. {\n        destruct width_cases as [E | E]; rewrite E; reflexivity.\n      }\n      rewrite map.get_put_diff; cycle 1. {\n        intro C.\n        apply (f_equal word.unsigned) in C.\n        rewrite word.unsigned_add in C. unfold word.wrap in C.\n        rewrite word.unsigned_of_Z in C. unfold word.wrap in C.\n        pose proof (word.unsigned_range addr) as R.\n        remember (word.unsigned addr) as w.\n        rewrite Z.add_mod_idemp_r in C by blia.\n        rewrite Z.mod_eq in C by blia.\n        assert (z = 2 ^ width * ((w + z) / 2 ^ width)) by blia.\n        remember ((w + z) / 2 ^ width) as k.\n        assert (k < 0 \\/ k = 0 \\/ 0 < k) as D by blia. destruct D as [D | [D | D]]; Lia.nia.\n      }\n      rewrite <- word.add_assoc.\n      replace ((word.add (word.of_Z (word := word) z) (word.of_Z 1)))\n        with (word.of_Z (word := word) (z + 1)); cycle 1. {\n        apply word.unsigned_inj.\n        rewrite word.unsigned_add.\n        rewrite! word.unsigned_of_Z.\n        apply Z.add_mod.\n        destruct width_cases as [E | E]; rewrite E; cbv; discriminate.\n      }\n      eapply IHn; try blia; assumption.\n  Qed.\n\n  Lemma putmany_of_footprint_None'': forall n (vs: HList.tuple byte n) (a1 a2: word) (m: mem),\n      0 < word.unsigned (word.sub a1 a2) ->\n      word.unsigned (word.sub a1 a2) + Z.of_nat n <= 2 ^ width ->\n      map.get m a2 = None ->\n      map.get (map.putmany_of_tuple (Memory.footprint a1 n) vs m) a2 = None.\n  Proof.\n    intros.\n    pose proof putmany_of_footprint_None as P.\n    specialize P with (1 := H) (2 := H0) (3 := H1).\n    specialize (P vs).\n    replace (word.add a2 (word.of_Z (word.unsigned (word.sub a1 a2)))) with a1 in P; [exact P|].\n    apply word.unsigned_inj.\n    rewrite word.unsigned_add. unfold word.wrap.\n    rewrite word.of_Z_unsigned.\n    rewrite word.unsigned_sub. unfold word.wrap.\n    rewrite Z.add_mod_idemp_r by (destruct width_cases as [E | E]; rewrite E; cbv; discriminate).\n    rewrite <- (word.of_Z_unsigned a1) at 1.\n    rewrite word.unsigned_of_Z. unfold word.wrap.\n    f_equal.\n    blia.\n  Qed.\n\n  Lemma putmany_of_footprint_None': forall n (vs: HList.tuple byte n) (a1 a2: word) (m: mem),\n      a1 <> a2 ->\n      word.unsigned (word.sub a1 a2) + Z.of_nat n <= 2 ^ width ->\n      map.get m a2 = None ->\n      map.get (map.putmany_of_tuple (Memory.footprint a1 n) vs m) a2 = None.\n  Proof.\n    intros.\n    apply putmany_of_footprint_None''; try assumption.\n    pose proof (word.unsigned_range (word.sub a1 a2)).\n    assert (word.unsigned (word.sub a1 a2) = 0 \\/ 0 < word.unsigned (word.sub a1 a2)) as C\n        by blia. destruct C as [C | C].\n    - exfalso. apply H.\n      rewrite word.unsigned_sub in C.\n      apply word.unsigned_inj.\n      apply Z.div_exact in C; [|(destruct width_cases as [E | E]; rewrite E; cbv; discriminate)].\n      remember ((word.unsigned a1 - word.unsigned a2) / 2 ^ width) as k.\n      pose proof (word.unsigned_range a1).\n      pose proof (word.unsigned_range a2).\n      assert (k < 0 \\/ k = 0 \\/ 0 < k) as D by blia. destruct D as [D | [D | D]]; try Lia.nia.\n      (* LIABUG if primitive projections are on, we need this:\n      rewrite D in C.\n      rewrite Z.mul_0_r in C.\n      blia.\n      *)\n    - assumption.\n  Qed.\n\n  Lemma byte_list_to_word_list_array: forall bytes,\n    Z.of_nat (length bytes) mod bytes_per_word = 0 ->\n    exists word_list : list word,\n      Z.of_nat (Datatypes.length word_list) =\n      Z.of_nat (Datatypes.length bytes) / bytes_per_word /\\\n    forall p,\n      iff1 (array ptsto (word.of_Z 1) p bytes)\n           (array ptsto_word (word.of_Z bytes_per_word) p word_list).\n  Proof.\n    assert (AA: 0 < bytes_per_word). {\n      unfold bytes_per_word.\n      simpl.\n      destruct width_cases as [E | E]; rewrite E; cbv; reflexivity.\n    }\n    intros.\n    Z.div_mod_to_equations.\n    subst r.\n    specialize (H0 ltac:(blia)); clear H1.\n    ring_simplify in H0.\n    assert (0 <= q) by Lia.nia.\n    revert dependent bytes.\n    pattern q.\n    refine (natlike_ind _ _ _ q H); clear -BW word_ok mem_ok; intros.\n    { case bytes in *; cbn in *; ring_simplify in H0; try discriminate.\n      exists nil; split; reflexivity. }\n    rewrite Z.mul_succ_r in *.\n    specialize (H0 (List.skipn (Z.to_nat bytes_per_word) bytes)).\n    rewrite List.length_skipn in H0.\n    specialize (H0 ltac:(Lia.nia)).\n    case H0 as [words' [Hlen Hsep] ].\n    eexists (cons _ words').\n    split; [cbn; blia|].\n    intros p0; specialize (Hsep (word.add p0 (word.of_Z bytes_per_word))).\n    rewrite array_cons.\n    etransitivity.\n    2:eapply Proper_sep_iff1; [reflexivity|].\n    2:eapply Hsep.\n    clear Hsep.\n\n    rewrite <-(List.firstn_skipn (Z.to_nat bytes_per_word) bytes) at 1.\n    unfold ptsto_word, truncated_word, truncated_scalar, littleendian.\n\n    rewrite <-bytearray_index_merge.\n    1: eapply Proper_sep_iff1; [|reflexivity].\n    2: rewrite word.unsigned_of_Z; setoid_rewrite Z.mod_small.\n    3: {\n      unfold bytes_per_word.\n      simpl.\n      destruct width_cases as [E | E]; rewrite E; cbv; intuition discriminate.\n    }\n    2: rewrite List.length_firstn_inbounds; Lia.nia.\n    cbv [ptsto_bytes.ptsto_bytes].\n    Morphisms.f_equiv.\n    rewrite HList.tuple.to_list_of_list.\n    setoid_rewrite word.unsigned_of_Z.\n    setoid_rewrite Z.mod_small.\n    1:unshelve erewrite (_:Memory.bytes_per Syntax.access_size.word = length _); shelve_unifiable; cycle 1.\n    1:setoid_rewrite LittleEndianList.split_le_combine.\n    1:reflexivity.\n    { rewrite List.length_firstn_inbounds; try Lia.nia. reflexivity. }\n    intros.\n    pose proof (LittleEndianList.le_combine_bound (List.firstn (Z.to_nat bytes_per_word) bytes)).\n    split; [blia|].\n    destruct H0.\n    eapply Z.lt_le_trans. 1: eassumption.\n    eapply Z.pow_le_mono_r. 1: reflexivity.\n    rewrite List.length_firstn_inbounds; try Lia.nia.\n    unfold bytes_per_word;\n    destruct width_cases as [E | E]; rewrite E; cbv; inversion 1.\n  Qed.\n\n  Lemma ll_mem_to_hl_mem: forall mH mL (addr: word) bs R,\n      (eq mH * array ptsto (word.of_Z 1) addr bs * R)%sep mL ->\n      exists mTraded,\n        (eq (map.putmany mH mTraded) * R)%sep mL /\\\n        map.disjoint mH mTraded /\\\n        Memory.anybytes addr (Z.of_nat (List.length bs)) mTraded.\n  Proof.\n    unfold sep, map.split.\n    intros.\n    simp.\n    epose proof array_1_to_anybytes.\n    eauto 10.\n    Unshelve. all : exact _.\n  Qed.\n\n  Lemma hl_mem_to_ll_mem: forall mH mHSmall mTraded mL (addr: word) n R,\n      map.split mH mHSmall mTraded ->\n      Memory.anybytes addr n mTraded ->\n      (eq mH * R)%sep mL ->\n      exists bs,\n        List.length bs = Z.to_nat n /\\\n        (eq mHSmall * array ptsto (word.of_Z 1) addr bs * R)%sep mL.\n  Proof.\n    unfold sep, map.split.\n    intros.\n    apply anybytes_to_array_1 in H0.\n    simp. repeat eexists; try eassumption.\n  Qed.\n\n  Lemma load_from_word_array: forall p words frame m i v,\n      (word_array p words * frame)%sep m ->\n      nth_error words (Z.to_nat i) = Some v ->\n      0 <= i ->\n      Memory.load Syntax.access_size.word m (word.add p (word.of_Z (i * bytes_per_word))) = Some v.\n  Proof.\n    unfold word_array.\n    intros.\n    eapply nth_error_split in H0. simp.\n    seprewrite_in @array_append H.\n    seprewrite_in @array_cons H.\n    eapply load_word_of_sep.\n    use_sep_assumption.\n    cancel.\n    cancel_seps_at_indices 0%nat 0%nat. {\n      f_equal. f_equal. f_equal. rewrite Z.mul_comm. f_equal. 1: blia.\n      apply word.unsigned_of_Z_nowrap.\n      unfold bytes_per_word.\n      destruct width_cases as [E | E]; rewrite E; cbv; intuition congruence.\n    }\n    ecancel_done.\n  Qed.\n\n  Lemma store_to_word_array: forall p oldwords frame m i v,\n      (word_array p oldwords * frame)%sep m ->\n      0 <= i < Z.of_nat (List.length oldwords) ->\n      exists newwords m',\n        Memory.store Syntax.access_size.word m (word.add p (word.of_Z (i * bytes_per_word))) v = Some m' /\\\n        (word_array p newwords * frame)%sep m' /\\\n        nth_error newwords (Z.to_nat i) = Some v /\\\n        (forall j w, j <> Z.to_nat i -> nth_error oldwords j = Some w -> nth_error newwords j = Some w) /\\\n        length newwords = length oldwords.\n  Proof.\n    unfold word_array.\n    intros.\n    destruct (List.nth_error oldwords (Z.to_nat i)) eqn: E. 2: {\n      exfalso. eapply nth_error_Some. 2: eassumption. blia.\n    }\n    eapply nth_error_split in E. simp.\n    seprewrite_in @array_append H.\n    seprewrite_in @array_cons H.\n    eexists (l1 ++ v :: l2).\n    eapply store_word_of_sep. {\n      use_sep_assumption. cancel. cancel_seps_at_indices 0%nat 0%nat. {\n        f_equal. f_equal. f_equal. rewrite Z.mul_comm. f_equal. 1: blia.\n        apply word.unsigned_of_Z_nowrap.\n        unfold bytes_per_word.\n        destruct width_cases as [E | E]; rewrite E; cbv; intuition congruence.\n      }\n      ecancel_done.\n    }\n    clear H.\n    intros. ssplit.\n    - seprewrite @array_append. seprewrite @array_cons.\n      use_sep_assumption.\n      cancel.\n      cancel_seps_at_indices 0%nat 0%nat. {\n        f_equal. f_equal. f_equal. rewrite Z.mul_comm. f_equal. 2: blia.\n        symmetry. apply word.unsigned_of_Z_nowrap.\n        unfold bytes_per_word.\n        destruct width_cases as [E | E]; rewrite E; cbv; intuition congruence.\n      }\n      ecancel_done.\n    - rewrite nth_error_app2 by blia. replace (Z.to_nat i - length l1)%nat with O by blia. reflexivity.\n    - intros. assert (j < Z.to_nat i \\/ Z.to_nat i < j)%nat as C by blia. destruct C as [C | C].\n      + rewrite nth_error_app1 by blia. rewrite nth_error_app1 in H1 by blia. assumption.\n      + rewrite nth_error_app2 by blia. rewrite nth_error_app2 in H1 by blia.\n        replace (j - length l1)%nat with (S (j - length l1 - 1)) in * by blia.\n        assumption.\n    - rewrite ?List.app_length. reflexivity.\n  Qed.\n\n  Lemma store_bytes_sep_hi2lo: forall (mH mL : mem) R a n v_old v,\n      Memory.load_bytes n mH a = Some v_old ->\n      (eq mH * R)%sep mL ->\n      (eq (Memory.unchecked_store_bytes n mH a v) * R)%sep (Memory.unchecked_store_bytes n mL a v).\n  Proof.\n    intros. apply sep_comm. apply sep_comm in H0.\n    unfold Memory.load_bytes, Memory.unchecked_store_bytes, sep, map.split in *.\n    simp. do 2 eexists. ssplit. 3: eassumption. 3: reflexivity.\n    - rewrite map.putmany_of_tuple_to_putmany.\n      rewrite (map.putmany_of_tuple_to_putmany _ mq).\n      symmetry. apply map.putmany_assoc.\n    - unfold map.disjoint in *.\n      intros.\n      pose proof (map.putmany_of_tuple_preserves_domain (ok := mem_ok) _ _ v_old v _ H) as A.\n      unfold map.same_domain, map.sub_domain in A. apply proj2 in A.\n      edestruct A as [v3 B]. 1: eassumption.\n      eauto.\n  Qed.\nEnd ptstos.\n\n(* These lemmas are for any kind of map, so that they can also be used to describe locals *)\nSection MoreSepLog.\n  Context {key value} {map : map.map key value}.\n  Context {ok : map.ok map} {key_eqb: key -> key -> bool} {key_eq_dec : EqDecider key_eqb}.\n\n  Lemma sep_inline_eq: forall (A R: map -> Prop) m1,\n    (exists m2, (R * eq m2)%sep m1 /\\ A m2) <->\n    (R * A)%sep m1.\n  Proof.\n    unfold iff, Separation.sep.\n    repeat match goal with\n           | |- _ => intros || simp || eassumption || reflexivity\n           | |- _ /\\ _ => split\n           | |- exists _, _ => eexists\n           end.\n  Qed.\n\n  Lemma subst_split: forall (m m1 m2 M: map) (R: map -> Prop),\n      map.split m m1 m2 ->\n      (eq m * R)%sep M ->\n      (eq m1 * eq m2 * R)%sep M.\n  Proof.\n    intros.\n    unfold map.split in H. destruct H. subst.\n    use_sep_assumption.\n    cancel.\n    cbn [seps].\n    intro m. unfold sep, map.split. split; intros.\n    - subst. eauto 10.\n    - simp. reflexivity.\n  Qed.\n\n  Lemma subst_split_bw: forall (m m1 m2 M : map) (R : map -> Prop),\n      map.split m m1 m2 ->\n      sep (sep (eq m1) (eq m2)) R M ->\n      sep (eq m) R M.\n  Proof.\n    unfold sep, map.split. intros. simp. eauto 10.\n  Qed.\n\n  Lemma eq_sep_to_split: forall (m m1: map) P,\n      (eq m1 * P)%sep m ->\n      exists m2, map.split m m1 m2 /\\ P m2.\n  Proof. unfold sep. intros. simp. eauto. Qed.\n\n  Lemma sep_put_iff: forall (m: map) P R k v_old v_new,\n      (ptsto k v_old * R)%sep m ->\n      iff1 P (ptsto k v_new * R)%sep ->\n      P (map.put m k v_new).\n  Proof.\n    intros.\n    eapply sep_put in H.\n    seprewrite H0.\n    ecancel_assumption.\n  Qed.\n\n  Lemma sep_eq_put: forall (m1 m: map) P x v,\n      (eq m1 * P)%sep m ->\n      (forall m' w, P m' -> map.get m' x = Some w -> False) ->\n      (eq (map.put m1 x v) * P)%sep (map.put m x v).\n  Proof.\n    intros. unfold sep, map.split in *. simp.\n    exists (map.put mp x v), mq.\n    specialize H0 with (1 := Hp2).\n    repeat split; trivial.\n    - apply map.map_ext.\n      intro y.\n      rewrite map.get_put_dec.\n      rewrite ?map.get_putmany_dec.\n      destr (map.get mq y).\n      + destruct_one_match.\n        * subst. exfalso. eauto.\n        * reflexivity.\n      + destruct_one_match.\n        * subst. rewrite map.get_put_same. reflexivity.\n        * rewrite map.get_put_diff by congruence. reflexivity.\n    - unfold map.disjoint in *. intros.\n      rewrite map.get_put_dec in H. destruct_one_match_hyp.\n      + subst. eauto.\n      + eauto.\n  Qed.\n\n  Lemma grow_eq_sep: forall (M M' m mAdd: map) (R: map -> Prop),\n      (eq m * R)%sep M ->\n      map.split M' M mAdd ->\n      (eq (map.putmany m mAdd) * R)%sep M'.\n  Proof.\n    intros. apply sep_comm. apply sep_comm in H.\n    unfold sep, map.split in *. simp.\n    do 2 eexists. ssplit. 4: reflexivity. 3: eassumption.\n    - symmetry. apply map.putmany_assoc.\n    - unfold map.disjoint in *. intros. rewrite map.get_putmany_dec in H0.\n      destruct_one_match_hyp.\n      + simp. eapply H0p1. 2: eassumption. rewrite map.get_putmany_dec.\n        rewrite H. instantiate (1 := ltac:(destruct(map.get mq k))).\n        destruct (map.get mq k); reflexivity.\n      + eauto.\n  Qed.\n\n  Lemma join_sep: forall (m m1 m2: map) (P P1 P2: map -> Prop),\n      map.split m m1 m2 ->\n      P1 m1->\n      P2 m2 ->\n      iff1 (P1 * P2)%sep P ->\n      P m.\n  Proof.\n    unfold sep, map.split. intros. simp. eapply H2. eauto 10.\n  Qed.\n\n  Lemma sep_def: forall {m: map} {P Q: map -> Prop},\n      (P * Q)%sep m ->\n      exists m1 m2, map.split m m1 m2 /\\ P m1 /\\ Q m2.\n  Proof. unfold sep. intros *. apply id. Qed.\n\n  Lemma sep_eq_empty_l: forall (R: map -> Prop), (eq map.empty * R)%sep = R.\n  Proof.\n    intros. eapply iff1ToEq.\n    unfold iff1, sep, map.split. split; intros.\n    - destruct H as (? & ? & (? & ?) & ? & ?). subst. rewrite map.putmany_empty_l. assumption.\n    - eauto 10 using map.putmany_empty_l, map.disjoint_empty_l.\n  Qed.\n\n  Lemma sep_eq_empty_r: forall (R: map -> Prop), (R * eq map.empty)%sep = R.\n  Proof.\n    intros. eapply iff1ToEq.\n    unfold iff1, sep, map.split. split; intros.\n    - destruct H as (? & ? & (? & ?) & ? & ?). subst. rewrite map.putmany_empty_r. assumption.\n    - eauto 10 using map.putmany_empty_r, map.disjoint_empty_r.\n  Qed.\n\n  Lemma get_in_sep: forall (lSmaller l: map) k v R,\n      map.get lSmaller k = Some v ->\n      (eq lSmaller * R)%sep l ->\n      map.get l k = Some v.\n  Proof.\n    intros. eapply sep_comm in H0.\n    unfold sep, map.split in H0. simp.\n    eapply map.get_putmany_right.\n    assumption.\n  Qed.\n\n  Lemma eq_put_to_sep: forall (m: map) k v,\n      map.get m k = None ->\n      eq (map.put m k v) = sep (eq m) (ptsto k v).\n    intros. eapply iff1ToEq.\n    unfold iff1, ptsto, sep, map.split. split; intros.\n    - subst. exists m, (map.put map.empty k v). ssplit; try reflexivity.\n      + apply map.map_ext. intros.\n        rewrite map.get_put_dec, map.get_putmany_dec, map.get_put_dec, map.get_empty.\n        destr (key_eqb k k0); reflexivity.\n      + unfold map.disjoint. intros. rewrite map.get_put_dec in H1.\n        rewrite map.get_empty in H1. destr (key_eqb k k0); congruence.\n    - destruct H0 as (? & ? & (? & ?) & ? & ?).  subst.\n      apply map.map_ext. intros.\n      rewrite map.get_put_dec, map.get_putmany_dec, map.get_put_dec, map.get_empty.\n      destr (key_eqb k k0); reflexivity.\n  Qed.\n\n  Lemma ptsto_no_aliasing: forall l (Q: map -> Prop) R k v1 v2,\n      Q l ->\n      iff1 Q (ptsto k v1 * ptsto k v2 * R)%sep ->\n      False.\n  Proof.\n    intros. seprewrite_in H0 H. apply sep_emp_r in H. apply proj1 in H.\n    unfold sep, map.split, ptsto, map.disjoint in H.\n    decompose [Logic.and ex] H. clear H. subst.\n    specialize (H7 k). rewrite ?map.get_put_same in H7. eauto.\n  Qed.\n\n  Lemma get_Some_to_ptsto: forall k v (m: map),\n      map.get m k = Some v ->\n      eq m = (eq (map.remove m k) * ptsto k v)%sep.\n  Proof.\n    intros. extensionality l. eapply propositional_extensionality.\n    unfold sep, map.split.\n    split; intros.\n    - subst. do 2 eexists. ssplit; try reflexivity.\n      + apply map.map_ext. intros.\n        rewrite map.get_putmany_dec, map.get_put_dec, map.get_remove_dec, map.get_empty.\n        destr (key_eqb k k0); congruence.\n      + unfold map.disjoint. intros.\n        rewrite map.get_remove_dec in H0. rewrite map.get_put_dec, map.get_empty in H1.\n        destr (key_eqb k k0); congruence.\n    - unfold ptsto in H0. decompose [Logic.and ex] H0. subst.\n      apply map.map_ext. intros.\n        rewrite map.get_putmany_dec, map.get_put_dec, map.get_remove_dec, map.get_empty.\n        destr (key_eqb k k0); congruence.\n  Qed.\n\n  Lemma sep_ptsto_to_get_None: forall k v m (R: map -> Prop) l,\n      (eq m * ptsto k v * R)%sep l ->\n      map.get m k = None.\n  Proof.\n    intros. destr (map.get m k); [exfalso|reflexivity].\n    erewrite get_Some_to_ptsto in H by eassumption.\n    eapply ptsto_no_aliasing. 1: exact H. ecancel.\n  Qed.\n\n  Lemma ptsto_unique: forall k v0 v1 (R1 R2: map -> Prop) l,\n      (ptsto k v0 * R1)%sep l ->\n      (ptsto k v1 * R2)%sep l ->\n      v0 = v1.\n  Proof.\n    intros. apply sep_comm in H. apply sep_comm in H0.\n    unfold sep, map.split, ptsto in *.\n    decompose [Logic.and ex] H. decompose [Logic.and ex] H0. subst.\n    apply (f_equal (fun m => map.get m k)) in H6.\n    rewrite ?map.get_putmany_dec, ?map.get_put_same in H6.\n    congruence.\n  Qed.\n\n  Lemma sep_eq_to_disjoint: forall m1 m2 (R: map -> Prop) l,\n      (eq m1 * eq m2 * R)%sep l ->\n      map.disjoint m1 m2.\n  Proof.\n    unfold sep, map.split. intros. decompose [Logic.and ex] H. subst. assumption.\n  Qed.\nEnd MoreSepLog.\n\n(* This can be overridden by the user.\n   The idea of \"addr\" is that if the addresses of two sepclauses are the same,\n   we're sure that these two clauses should be matched & canceled with each other,\n   even if they still contain many evars outside of their address.\n   \"addr\" should return a Gallina term of type \"word\" *)\nLtac addr P ::=\n  let __ := lazymatch type of P with\n            | @map.rep _ _ _ -> Prop => idtac\n            | _ => fail 10000 P \"is not a sep clause\"\n            end in\n  lazymatch P with\n  | ptsto ?A _ => A\n  | ptsto_bytes _ ?A _ => A\n  | ptsto_word ?A _ => A\n  | ptsto_instr _ ?A _ => A\n  | array _ _ ?A _ => A\n  | word_array ?A _ => A\n  | _ => fail \"no recognizable address\"\n  end.\n\n#[export] Hint Unfold program word_array: unf_to_array.\n\nRequire Export bedrock2.footpr.\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/SeparationLogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2607782120902036}}
{"text": "(**********************************************************************************\n * uniirec.v                                                                      *\n * Formalizing Domains, Ultrametric Spaces and Semantics of Programming Languages *\n * Nick Benton, Lars Birkedal, Andrew Kennedy and Carsten Varming                 *\n * Jan 2012                                                                       *\n * Build with Coq 8.3pl2 plus SSREFLECT                                           *\n **********************************************************************************)\n\n(* Construction of recursive domain for interpreting unityped lambda calculus *)\n\nRequire Export PredomAll.\nRequire Import PredomRec.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(*=kcpoCat *)\nLemma kcpoCatAxiom : @Category.axiom cpoType \n  (fun X Y => exp_cppoType X (liftCppoType Y)) (fun X Y Z f g => kleisli f << g) (@eta).\n(*CLEAR*)\nsplit ; last split ; last split.\n- move => D0 D1 f. simpl. rewrite kleisli_unit. by rewrite comp_idL.\n- move => D0 D1 f. simpl. by rewrite kleisli_eta_com.\n- move => D0 D1 D2 D3 f g h. simpl. rewrite <- kleisli_comp. by rewrite comp_assoc.\n- move => D0 D1 D2 f f' g g'. simpl. move => e e'. rewrite e. by rewrite e'.\nQed.\n(*CLEARED*)Canonical Structure kcpoCatMixin := CatMixin kcpoCatAxiom.\nCanonical Structure kcpoCatType := Eval hnf in CatType kcpoCatMixin.\n(*=End *)\n\nModule Type RecDom.\n  Variable DInf : cpoType.\n  Definition VInf :=  discrete_cpoType nat + (DInf -=> DInf _BOT).\n  Variable Roll : VInf =-> DInf.\n  Variable Unroll : DInf =-> VInf.\n\n  Variable RU_id : Roll << Unroll =-= Id.\n  Variable UR_id : Unroll << Roll =-= Id.\n\n  Variable delta : (DInf -=> DInf _BOT) =-> (DInf -=> DInf _BOT).\n  Variable delta_simpl : forall e, delta e =-= eta << Roll << ([| in1,\n      (in2 <<\n    ((exp_fun (CCOMP DInf (DInf _BOT) (DInf _BOT):cpoCatType _ _) (kleisli e) : cpoCatType _ _) <<\n     ((exp_fun\n        ((CCOMP DInf (DInf _BOT) (DInf _BOT)) << SWAP) e :cpoCatType _ _) << KLEISLI))) |]) << Unroll.\n\n  Variable delta_eta : delta eta =-= eta.\n  Variable id_min : eta =-= @FIXP _ delta.\n\nEnd RecDom.\n\nModule RD : RecDom.\n\nLemma kcpoTerminalAxiom : CatTerminal.axiom (Zero: kcpoCatType).\nsimpl. move => D x y. split.\nmove => i. simpl. apply: DLless_cond. by case.\nmove => i. simpl. apply:DLless_cond. by case.\nQed.\n\nCanonical Structure kcpoTermincalCatMixin :=\n   @terminalCatMixin kcpoCatType (Zero: kcpoCatType)\n    (fun X => const _ (PBot: (liftCpoPointedType Zero))) kcpoTerminalAxiom.\nCanonical Structure kcpoTerminalCat := Eval hnf in @terminalCatType kcpoCatType kcpoTermincalCatMixin.\n\nLemma kcpo_comp_eq (X Y Z : cpoType) m m' : ((CCOMP X (Y _BOT) (Z _BOT)) << KLEISLI >< Id) (m,m') =-= Category.tcomp kcpoCatMixin m m'.\nby [].\nQed.\n\nDefinition kcpoBaseCatMixin := CppoECatMixin kcpoTermincalCatMixin kcpo_comp_eq.\n\n(*=kcpoBaseCat *)\nCanonical Structure kcpoBaseCatType := Eval hnf in CppoECatType kcpoBaseCatMixin.\nLemma leftss : (forall (X Y Z : kcpoBaseCatType) (f : kcpoBaseCatType X Y),\n    (PBot:kcpoCatType _ _) << f =-= (PBot: X =-> Z)).\n(*=End *)\nmove => X Y Z f. apply: fmon_eq_intro.\nmove => x. split ; last by apply: leastP.\napply: DLless_cond.\nmove => z. move => A. case: (kleisliValVal A) => y [_ F]. by case: (PBot_incon_eq (Oeq_sym F)).\nQed.\n\nDefinition ProjSet (T:Tower kcpoBaseCatType) := fun (d:prodi_cpoType (fun n => tobjects T n _BOT)) => forall n,\n      PROJ (fun n => tobjects T n _BOT) n d =-= \n      kleisli (tmorphisms T n) (PROJ (fun n => tobjects T n _BOT) (S n) d) /\\ \n      exists n, exists e, PROJ (fun n => tobjects T n _BOT) n d =-= Val e.\n\nLemma ProjSet_inclusive T : admissible (@ProjSet T).\nunfold ProjSet. unfold admissible.\nintros c C n.\nsplit. do 3 rewrite -> lub_comp_eq.\nrefine (lub_eq_compat _).\nrefine (fmon_eq_intro _).\nintros m. simpl. specialize (C m n). by apply (proj1 C).\nspecialize (C 0 0). destruct C as [_ C]. clear n.\ndestruct C as [n [e P]].\nexists n.\nassert (forall n, continuous ((PROJ (fun n0 : nat => tobjects T n0 _BOT) n))) as Cp by auto.\nassert (PROJ (fun n : nat => tobjects T n _BOT) n (c 0) <= PROJ (fun n : nat => tobjects T n _BOT) n (lub c)) as L by\n  (apply: fmonotonic ; auto).\nrewrite -> P in L.\ndestruct (DLle_Val_exists_eq L) as [dn [Y X]].\nexists dn. by apply Y.\nQed.\n\nDefinition kcpoCone (T:Tower kcpoBaseCatType) : Cone T.\nexists (sub_cpoType (@ProjSet_inclusive T)) (fun i:nat => PROJ _ i << Forget (@ProjSet_inclusive T)).\nmove => i. apply: fmon_eq_intro. case => d Pd.\nby apply (Oeq_sym (proj1 (Pd i))).\nDefined.\n\nImplicit Arguments InheritFun [D E P].\n\nLemma retract_total D E (f:D =-> E _BOT) (g:E =-> D _BOT) : kleisli f << g =-= eta -> total g.\nunfold total. move => X d. have X':=fmon_eq_elim X d.\ncase: (kleisliValVal X'). move => e [Y _]. exists e. by apply Y.\nQed.\n\nLemma xx (T:Tower kcpoBaseCatType) i : (forall d : tobjects T i, ProjSet (PRODI_fun (t_nm T i) d)).\nmove => d n. split. simpl.\nby rewrite -> (fmon_eq_elim (t_nmProjection T i n) d).\nexists i. exists d. simpl. by rewrite t_nn_ID.\nQed.\n\nDefinition kcpoCocone (T:Tower kcpoBaseCatType) : CoCone T.\nexists (sub_cpoType (@ProjSet_inclusive T)) (fun i => eta << @InheritFun _ _ _ (@ProjSet_inclusive T) (PRODI_fun (t_nm T i)) (@xx T i)).\nmove => i. rewrite {1} /Category.comp. simpl. apply: fmon_eq_intro => d. split.\n- apply: DLless_cond. case => x Px C. case: (kleisliValVal C). clear C.\n  move => y [md X].\n  apply Ole_trans with (kleisli (eta << InheritFun (@ProjSet_inclusive T) (PRODI_fun (t_nm T i.+1)) (@xx T _)) (Val y)) ;\n   first by rewrite <- md.\n  rewrite kleisliVal. rewrite -> X. apply: (fmonotonic (@eta_m _)). unfold Ole. simpl.\n  move => n. simpl. have Y:=vinj X.\n  case: (fmon_stable (Forget (@ProjSet_inclusive T)) Y). clear Y. simpl. move => Y Y'.\n  specialize (Y' n). rewrite -> Y'. rewrite -> (fmon_eq_elim (t_nmEmbedding T i n) d). simpl.\n  rewrite -> md. by rewrite kleisliVal.\n- case: (retract_total (proj1 (teppair T i)) d). move => x e.\n  apply Ole_trans with (y:=kleisli (eta << InheritFun (@ProjSet_inclusive T) (PRODI_fun (t_nm T i.+1)) (@xx T _)) (Val x)) ;\n  last by rewrite <- e.\n  rewrite kleisliVal. apply: DLle_leVal. move => n. simpl.\n  apply Ole_trans with (y:=(kleisli (t_nm T i.+1 n) (Val x))) ; last by rewrite kleisliVal.\n  rewrite <- e. by apply (proj1 (fmon_eq_elim (t_nmEmbedding T i n) d)).\nDefined.\n\nLemma limit_def (T:Tower kcpoBaseCatType) (C:Cone T) d n e' : mcone C n d =-= Val e' ->\n   exists e, lub (chainPE (kcpoCocone T) C) d =-= Val e.\nmove => X. simpl.\nhave aa:exists e, (fcont_app (chainPE (kcpoCocone T) C) d) n =-= Val e.\nexists (@InheritFun _ _ _ (@ProjSet_inclusive T) (PRODI_fun (t_nm T n)) (@xx T n) e').\napply (@Oeq_trans _ _ (kleisli (eta << InheritFun (@ProjSet_inclusive T) (PRODI_fun (t_nm T n)) (@xx T _)) (mcone C n d))) ; first by [].\nrewrite -> X. by rewrite kleisliVal.\ncase: aa => e aa. case: (chainVallubnVal 1 aa) => x bb. exists x. by apply bb.\nQed.\n\n(*=kcpoLimit *)\nDefinition kcpoLimit (T:Tower kcpoBaseCatType) : Limit T.\n(*=End *)\nexists (kcpoCone T) (fun C : Cone T => lub (chainPE (@kcpoCocone T) C)).\nmove => C n. simpl. split.\n- apply: (Ole_trans _ (comp_le_compat (Ole_refl _) (le_lub (chainPE (kcpoCocone T) C) n))).\n  simpl. rewrite {1} /Category.comp. simpl. rewrite comp_assoc. rewrite <- kleisli_comp2.\n  rewrite <- comp_assoc. rewrite -> ForgetInherit. rewrite prodi_fun_pi. rewrite t_nn_ID. rewrite kleisli_unit.\n  by rewrite comp_idL. simpl.\n  rewrite {1} / Category.comp. simpl.\n  refine (Ole_trans (Oeq_le (PredomCore.comp_lub_eq _ (chainPE (kcpoCocone T) C))) _).\n  rewrite (lub_lift_left _ n). apply: lub_le => i. simpl. rewrite comp_assoc.\n  rewrite <- (kleisli_comp2 (InheritFun (@ProjSet_inclusive T) (PRODI_fun (t_nm T (n + i))) (@xx T _))\n    (PROJ (fun n0 : nat => tobjects T n0 _BOT) n << Forget (@ProjSet_inclusive T))).\n  rewrite <- comp_assoc. rewrite ForgetInherit. rewrite prodi_fun_pi. by apply (proj2 ((coneCom_l C (leq_addr i n)))).\n- move => C h X. apply: fmon_eq_intro => d. simpl in h. split.\n  + apply: DLless_cond. case => x Px E. case: (proj2 (Px 0)) => n. case => y Py. rewrite -> E.\n    have A:=(fmon_eq_elim (X n) d). have AA:=tset_trans A (fmon_stable (kleisli _) E). clear A.\n    have A:=tset_trans AA (kleisliVal _ _). clear AA. simpl in A. rewrite -> Py in A.\n    case: (limit_def A) => lc e. rewrite -> e. apply: DLle_leVal. case: lc e => lc Plc e. unfold Ole. simpl.\n    move => i. specialize (X i). have Xi:=fmon_eq_elim X d.\n    have Xii: (mcone C i) d =-= (kleisli (PROJ _ i << Forget (@ProjSet_inclusive T)) ( h d)) by apply Xi.\n    rewrite -> E in Xii. rewrite -> kleisliVal in Xii. simpl in Xii.\n    rewrite <- Xii. clear Xi Xii.\n    simpl in e. have aa := Ole_trans (le_lub _ i) (proj1 e). clear e h X E. simpl in aa.\n    have bb:kleisli (eta << (@InheritFun _ _ _ (@ProjSet_inclusive T) (PRODI_fun (t_nm T (i))) (@xx T (i))))\n            ((mcone C i) d) <= Val (exist (fun x : forall i : nat, Stream (tobjects T i) => ProjSet x)\n            lc Plc) by apply aa. clear aa.\n    apply: DLless_cond => di X. rewrite -> X in bb. rewrite -> kleisliVal in bb. rewrite -> X.\n    have aa:=vleinj bb. clear bb. unfold Ole in aa. simpl in aa. specialize (aa i). simpl in aa.\n    rewrite <- aa. by rewrite -> (fmon_eq_elim (t_nn_ID T i) di).\n  + simpl. apply: lub_le => n. specialize (X n). have Y:=fmon_eq_elim X d. clear X.\n    simpl mcone in Y. simpl. apply Ole_trans with (y:=kleisli (eta << (@InheritFun _ _ _ (@ProjSet_inclusive T) (PRODI_fun (t_nm T n)) (@xx T n))) ( (mcone C n) d))  ; first by [].\n    rewrite -> Y.\n    apply Ole_trans with (y:=(kleisli (eta << InheritFun (@ProjSet_inclusive T) (PRODI_fun (t_nm T n)) (@xx T _)) <<\n                              kleisli (PROJ (fun n0 : nat => tobjects T n0 _BOT) n << Forget (@ProjSet_inclusive T)))\n                              ( h d)) ; first by [].\n    apply: DLless_cond. move => aa X. rewrite -> X. case: (kleisliValVal X) => b [P Q]. clear X.\n    case: (kleisliValVal P) => hd [P' Q']. rewrite -> P'. apply: DLle_leVal.\n    rewrite <- (vinj Q). clear P Q aa h d Y P'. unfold Ole. case: hd Q' => x Px Q.\n    simpl. simpl in Q. move => i. simpl.\n    case: (ltngtP n i).\n    * move => l. have a:= comp_eq_compat (tset_refl (t_nm T n i)) (coneCom_l (kcpoCone T) (ltnW l)).\n      rewrite -> comp_assoc in a. have yy:t_nm T n i << mcone (kcpoCone T) n <= mcone (kcpoCone T) i.\n        rewrite -> a. rewrite -> (comp_le_compat (proj2 (t_nm_EP T (ltnW l))) (Ole_refl _)).\n        by rewrite comp_idL.\n      specialize (yy (exist _ x Px)). simpl in yy. rewrite -> Q in yy. rewrite -> kleisliVal in yy.\n      by apply yy.\n    * move => l. have a:= (proj2 (fmon_eq_elim (coneCom_l (kcpoCone T) (ltnW l)) (exist _ x Px))).\n      simpl in a. have aa:(kleisli ( (t_nm T n i)) (x n)) <= (x i) by apply a.\n      rewrite -> Q in aa. rewrite -> kleisliVal in aa. by apply aa.\n    * move => e. rewrite <- e. clear i e. rewrite -> (proj1 (fmon_eq_elim (t_nn_ID T n) b)). by rewrite -> Q.\nDefined.\n\nLemma summ_mon (F G : BiFunctor kcpoBaseCatType) \n   X Y Z W : monotonic (fun p => [|kleisli (eta << in1) << (morph F X Y Z W p : (ob F X Z) =-> (ob F Y W)),\n                      kleisli (eta << in2) << (morph G X Y Z W p : (ob G X Z) =-> (ob G Y W))|]).\nmove => p p' l. simpl.\nunfold sum_fun. simpl. unfold in1. simpl. unfold in2. simpl.\nmove => x. simpl. do 2 rewrite -> SUM_fun_simpl. case: x.\n- move => s. simpl. by rewrite -> l.\n- move => s. simpl. by rewrite -> l.\nQed.\n\nDefinition summ (F G : BiFunctor kcpoBaseCatType) X Y Z W := Eval hnf in mk_fmono (@summ_mon F G X Y Z W).\n\nLemma sumc (F G : BiFunctor kcpoBaseCatType) X Y Z W : continuous (@summ F G X Y Z W).\nmove => c. simpl. unfold sum_fun. simpl. move => x. simpl. rewrite -> SUM_fun_simpl. simpl.\ncase:x ; simpl => s.\n- do 2 rewrite lub_comp_eq. simpl. apply lub_le_compat => i. simpl. unfold sum_fun. simpl. by rewrite SUM_fun_simpl.\n- do 2 rewrite lub_comp_eq. simpl. apply lub_le_compat => i. simpl. unfold sum_fun. simpl. by rewrite SUM_fun_simpl.\nQed.\n\nDefinition sum_func (F G : BiFunctor kcpoBaseCatType) X Y Z W := Eval hnf in mk_fcont (@sumc F G X Y Z W).\n\nLemma sum_func_simpl F G X Y Z W x : @sum_func F G X Y Z W x = [|kleisli (eta << in1) << (morph F X Y Z W x : (ob F X Z) =-> (ob F Y W)),\n                      kleisli (eta << in2) << (morph G X Y Z W x : (ob G X Z) =-> (ob G Y W))|].\nby [].\nQed.\n\nDefinition biSum (F G : BiFunctor kcpoBaseCatType) : BiFunctor kcpoBaseCatType.\nexists (fun X Y => (ob F X Y) + (ob G X Y)) (fun X Y Z W => @sum_func F G X Y Z W).\nmove => T0 T1 T2 T3 T4 T5 f g h k. simpl.\napply: (@sum_unique cpoSumCatType).\n- rewrite sum_fun_fst. rewrite {2} / Category.comp. simpl. rewrite <- comp_assoc.\n  rewrite sum_fun_fst. rewrite comp_assoc. rewrite <- kleisli_comp2. rewrite sum_fun_fst.\n  rewrite <- (comp_eq_compat (tset_refl (kleisli (eta << in1))) (@morph_comp _ F T0 T1 T2 T3 T4 T5 f g h k)).\n  rewrite {6} /Category.comp. simpl. rewrite comp_assoc. by rewrite kleisli_comp.\n- rewrite sum_fun_snd. rewrite {2} / Category.comp. simpl. rewrite <- comp_assoc.\n  rewrite sum_fun_snd. rewrite comp_assoc. rewrite <- kleisli_comp2. rewrite sum_fun_snd.\n  rewrite <- (comp_eq_compat (tset_refl (kleisli (eta << in2))) (@morph_comp _ G T0 T1 T2 T3 T4 T5 f g h k)).\n  rewrite {6} /Category.comp. simpl. rewrite comp_assoc. by rewrite kleisli_comp.\n- move => T0 T1. simpl. apply: (@sum_unique cpoSumCatType).\n  + simpl. rewrite sum_fun_fst. rewrite (comp_eq_compat (tset_refl (kleisli (eta << in1))) (morph_id F _ _)).\n    by rewrite kleisli_eta_com.\n  + simpl. rewrite sum_fun_snd. rewrite (comp_eq_compat (tset_refl (kleisli (eta << in2))) (morph_id G _ _)).\n    by rewrite kleisli_eta_com.\nDefined.\n\nLemma bifunm\n   X Y Z W : monotonic (fun (p:@cppoMorph kcpoBaseCatType Y X * @cppoMorph kcpoBaseCatType Z W) => \n  eta << (exp_fun (CCOMP _ _ _ :cpoCatType _ _) (kleisli (snd p) : cpoCatType _ _)) << (exp_fun ((CCOMP _ _ _) << SWAP) (fst p)) << KLEISLI).\nmove => p p' l f.\nsimpl. apply: DLle_leVal. case: l => l l'. rewrite l. by rewrite -> (kleisli_le_compat l').\nQed.\n\nAdd Parametric Morphism (D:cpoType) : (@Val D)\nwith signature (@Ole D: D -> D -> Prop) ++> (@Ole (D _BOT))\nas Val_le_cpo_compat.\nintros.\napply: DLle_leVal.\nauto.\nQed.\n\n\nLemma bifunc X Y Z W : continuous (mk_fmono (@bifunm X Y Z W)).\nmove => c x. simpl.\n apply Ole_trans with (y:=eta (((KLEISLI (lub (pi2 << (c:natO =-> _))):cpoCatType _ _) <<\n      exp_fun (CCOMP _ _ (_ _BOT):cpoCatType _ _)\n        (kleisli x) (lub (pi1 << (c:natO =-> _)))))) ; first by [].\ndo 2 rewrite lub_comp_eq. rewrite -> PredomCore.lub_comp_both.\nrewrite lub_comp_eq. by apply lub_le_compat => n.\nQed.\n\nDefinition bi_fun (X Y Z W : kcpoBaseCatType) : (@cppoMorph kcpoBaseCatType Y X * cppoMorph Z W) =-> \n(@cppoMorph kcpoBaseCatType (fcont_cpoType X (Z _BOT)) (fcont_cpoType Y (W _BOT)))\n:= Eval hnf in mk_fcont (@bifunc X Y Z W).\n\n\nLemma bi_fun_simpl T0 T2 T4 T5 f g x : (bi_fun T0 T4 T2 T5) (f,g) x = Val (kleisli g << (kleisli x << f)).\nby [].\nQed.\n\nDefinition biFun : BiFunctor kcpoBaseCatType.\nexists (fun X Y => fcont_cpoType X (Y _BOT)) (fun X Y Z W => @bi_fun X Y Z W).\nmove => T0 T1 T2 T3 T4 T5 f g h k. apply: fmon_eq_intro => x.\napply Oeq_trans with (y:=kleisli ((bi_fun T1 T4 T3 T5) (f, g)) ((bi_fun T0 T1 T2 T3) (h, k) x)) ; first by [].\nrewrite bi_fun_simpl. rewrite kleisliVal. rewrite bi_fun_simpl.\napply Oeq_trans with (y:= (bi_fun T0 T4 T2 T5) (h << f, g << k) x) ; last by [].\nrewrite bi_fun_simpl. apply: (fmon_stable eta).\nrewrite <- kleisli_comp. rewrite <- kleisli_comp. rewrite {6 8} /Category.comp. simpl.\nrewrite <- kleisli_comp. by repeat rewrite comp_assoc.\n\nmove => X Y. apply: fmon_eq_intro => x. apply: (fmon_stable eta).\nsimpl. rewrite kleisli_unit. rewrite comp_idL. by rewrite kleisli_eta_com.\nDefined.\n\nDefinition biVar : BiFunctor kcpoBaseCatType.\nexists (fun X Y => Y) (fun X Y Z W => pi2).\nby [].\nby [].\nDefined.\n\nDefinition biConst (D:kcpoBaseCatType) : BiFunctor kcpoBaseCatType.\nexists (fun (X Y:kcpoBaseCatType) => D) (fun (X Y Z W:kcpoBaseCatType) => const _ eta).\nmove => T0 T1 T2 T3 T4 T5 f g h k. simpl. unfold Category.comp. simpl.\nrewrite kleisli_unit. by rewrite comp_idL.\nmove => T0 T1. by [].\nDefined.\n\n(*=FS *)\nDefinition FS := biSum (biConst (discrete_cpoType nat)) biFun.\n(*=End *)\n(*=DInf *)\nDefinition DInf : cpoType := @DInf kcpoBaseCatType kcpoLimit FS leftss.\nDefinition VInf := (discrete_cpoType nat) + (DInf -=> DInf _BOT).\nDefinition Fold : VInf =-> DInf _BOT := Fold kcpoLimit FS leftss.\nDefinition Unfold : DInf =-> VInf _BOT := Unfold kcpoLimit FS leftss.\n(*=End *)\nLemma FU_iso : kleisli Fold << Unfold =-= eta.\nby apply (FU_id kcpoLimit FS leftss).\nQed.\n\nLemma UF_iso : kleisli Unfold << Fold =-= eta.\nby apply (UF_id kcpoLimit FS leftss).\nQed.\n\nLemma ob X Y : ob FS X Y = discrete_cpoType nat + (X -=> (Y _BOT)).\nby simpl.\nQed.\n\nLemma morph1 X Y Z W f g x : morph FS X Y Z W (f,g) (INL _ _ x) =-= Val (INL _ _ x).\nsimpl. unfold sum_fun. simpl. unlock SUM_fun. simpl. by rewrite kleisliVal.\nQed.\n\nLemma morph2 X Y Z W f g x : morph FS X Y Z W (f,g) (INR _ _ x) =-= Val (INR _ _ (kleisli g << (kleisli x << f))).\nsimpl. unfold sum_fun. simpl. unlock SUM_fun. simpl; by rewrite kleisliVal.\nQed.\n\n(*=Delta *)\nDefinition delta : (DInf -=> DInf _BOT) =-> (DInf -=> DInf _BOT) := delta kcpoLimit FS leftss.\n(*=End *)\n\nLemma eta_mono X Y (f g : X =-> Y) : eta << f =-= eta << g -> f =-= g.\nmove => A. \napply: fmon_eq_intro => x.\nhave A':=fmon_eq_elim A x. by apply (vinj A').\nQed.\n\n(*=ROLL *)\nLemma foldT : total Fold. \n(*CLEAR*)\nmove => x. simpl.\nhave X:=fmon_eq_elim UF_iso x. case: (kleisliValVal X). clear X. move => y [P Q]. exists y. by apply P. \nQed. \n(*CLEARED*)Lemma unfoldT : total Unfold.  (*CLEAR*)\nmove => x. simpl.\nhave X:=fmon_eq_elim FU_iso x. case: (kleisliValVal X). clear X. move => y [P Q]. exists y. by apply P. \nQed. (*CLEARED*)\nDefinition Roll : VInf =-> DInf := totalL foldT.\nDefinition Unroll : DInf =-> VInf := totalL unfoldT.\nLemma RU_id : Roll << Unroll =-= Id. (*CLEAR*)\napply eta_mono.\nhave X:=FU_iso.\nhave A:eta << Roll =-= Fold by apply totalL_eta.\nrewrite <- A in X. clear A. \nhave A:eta << Unroll =-= Unfold by apply totalL_eta.\nrewrite <- A in X. clear A.\nrewrite -> comp_assoc in X. rewrite -> kleisli_eta_com in X.\nrewrite <- comp_assoc in X. rewrite X. by rewrite comp_idR. \nQed. (*CLEARED*)\nLemma UR_id : Unroll << Roll =-= Id. \n(*=End *)\n(*=End *)\napply eta_mono.\nhave X:=UF_iso.\nhave A:eta << Roll =-= Fold by apply totalL_eta.\nrewrite <- A in X. clear A. \nhave A:eta << Unroll =-= Unfold by apply totalL_eta.\nrewrite <- A in X. clear A.\nrewrite -> comp_assoc in X. rewrite -> kleisli_eta_com in X.\nrewrite <- comp_assoc in X. rewrite X. by rewrite comp_idR.\nQed.\n\nLemma delta_simpl (e:DInf =-> DInf _BOT) : delta e =-=\n  eta << Roll << ([| in1,\n      (in2 <<\n    ((exp_fun (CCOMP DInf (DInf _BOT) (DInf _BOT):cpoCatType _ _) (kleisli e) : cpoCatType _ _) <<\n     ((exp_fun\n        ((CCOMP DInf _ (DInf _BOT)) <<\n         SWAP) e : cpoCatType _ _) << KLEISLI))) |]) << Unroll.\nrewrite (@delta_simpl _ kcpoLimit FS leftss e).\nfold Fold. fold Unfold. fold DInf. simpl. rewrite <- comp_assoc.\n rewrite {1 2} /Category.comp. simpl. have A:eta << Unroll =-= Unfold by apply totalL_eta.\nrewrite <- A. rewrite (comp_assoc Unroll eta). rewrite kleisli_eta_com.\nrewrite comp_assoc. apply: (comp_eq_compat _ (tset_refl Unroll)).\nhave B:eta << Roll =-= Fold by apply totalL_eta.\nrewrite <- B. rewrite <- (comp_eq_compat (kleisli_eta_com (eta << Roll)) (tset_refl ([| _,_|]))).\nrewrite <- (comp_assoc _ eta). apply comp_eq_compat ; first by [].\nrewrite kleisli_eta_com.\ndo 4 rewrite comp_assoc. rewrite kleisli_eta_com. simpl. apply: sum_unique.\n- rewrite sum_fun_fst. do 2 rewrite <- comp_assoc. by rewrite sum_fun_fst.\n- rewrite sum_fun_snd. repeat rewrite <- comp_assoc. by rewrite sum_fun_snd.\nQed.\n\n(*=minimal *)\nLemma id_min : eta =-= FIXP delta.\n(*=End *)\napply tset_sym. rewrite <- (id_min kcpoLimit FS leftss). fold delta.\n simpl. apply:fmon_eq_intro => n. simpl. apply lub_eq_compat. by apply fmon_eq_intro => m.\nQed.\n\nLemma delta_eta : delta eta =-= eta.\nby apply (delta_id_id kcpoLimit FS leftss).\nQed.\n\nEnd RD.\n", "meta": {"author": "nbenton", "repo": "coqdomains", "sha": "1ae7ec4af95e4fa44d35d7a5b2452ad123b3a75d", "save_path": "github-repos/coq/nbenton-coqdomains", "path": "github-repos/coq/nbenton-coqdomains/coqdomains-1ae7ec4af95e4fa44d35d7a5b2452ad123b3a75d/src/uniirec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.26077820678078434}}
{"text": "(** * Reduction of the Halting Problem of the Heap Machine to the Halting Problem of Turing Machines *)\n\nRequire Import ProgrammingTools.\nRequire Import LM.Semantics LM.Alphabets LM.StepTM.\n\nLocal Arguments plus : simpl never.\nLocal Arguments mult : simpl never.\n\n\n(** Initialise the alphabet of the [Step] Machine *)\nDefinition sigStep : Type := sigList sigHClos + sigHeap.\nDefinition retr_heap_step : Retract sigHeap sigStep := _.\nDefinition retr_closures_step : Retract (sigList sigHClos) sigStep := _.\n\n\nDefinition Loop := While (Step retr_closures_step retr_heap_step).\n\nDefinition Loop_Rel : pRel sigStep^+ unit 11 :=\n  ignoreParam (\n      fun tin tout =>\n        forall (T V : list HClos) (H: Heap),\n          tin[@Fin0] ≃ T ->\n          tin[@Fin1] ≃ V ->\n          tin[@Fin2] ≃ H ->\n          (forall i : Fin.t 8, isRight tin[@FinR 3 i]) ->\n          exists T' V' H',\n            steps (T,V,H) (T',V',H') /\\\n            halt_state (T',V',H') /\\\n            match T' with\n            | nil => \n              tout[@Fin0] ≃ @nil HClos /\\\n              tout[@Fin1] ≃ V' /\\\n              tout[@Fin2] ≃ H' /\\\n              (forall i : Fin.t 8, isRight tout[@FinR 3 i])\n            | _ => True\n            end\n    ).\n\nLemma Loop_Realise : Loop ⊨ Loop_Rel.\nProof.\n  eapply Realise_monotone.\n  { unfold Loop. TM_Correct.\n    - apply Step_Realise.\n  }\n  {\n    apply WhileInduction; intros; intros T V heap HEncT HEncV HEncHep HInt; cbn in *.\n    {\n      modpon HLastStep. destruct_unit; cbn in *. modpon HLastStep.\n      exists T, V, heap. repeat split; auto. constructor.\n    }\n    {\n      modpon HStar. destruct HStar as (T1&V1&heap1&HStar); modpon HStar.\n      modpon HLastStep. destruct HLastStep as (T2&V2&heap2&HLastStep); modpon HLastStep.\n      do 3 eexists. repeat split. econstructor 2. all: eauto.\n    }\n  }\nQed.\n\n\n\nFixpoint Loop_steps T V H k :=\n  match k with\n  | 0 => Step_steps T V H\n  | S k' =>\n    match step_fun (T, V, H) with\n    | Some (T',V',H') =>\n      if is_halt_state (T',V',H')\n      then 1 + Step_steps T V H + Step_steps T' V' H'\n      else 1 + Step_steps T V H + Loop_steps T' V' H' k'\n    | None => Step_steps T V H\n    end\n  end.\n\n\nDefinition Loop_T : tRel sigStep^+ 11 :=\n  fun tin i => exists T V H k,\n      halts_k (T,V,H) k /\\\n      tin[@Fin0] ≃ T /\\\n      tin[@Fin1] ≃ V /\\\n      tin[@Fin2] ≃ H /\\\n      (forall i : Fin.t 8, isRight tin[@FinR 3 i]) /\\\n      Loop_steps T V H k <= i.\n\n\nLemma Loop_Terminates : projT1 Loop ↓ Loop_T.\nProof.\n  eapply TerminatesIn_monotone.\n  { unfold Loop. TM_Correct.\n    - apply Step_Realise.\n    - apply Step_Terminates. }\n  {\n    eapply WhileCoInduction. intros tin i. intros (T&V&Heap&k&Halt&HEncT&HEncV&HEncH&HInt&Hi).\n    exists (Step_steps T V Heap). repeat split.\n    { hnf. do 3 eexists; repeat split; eauto. }\n    intros ymid tmid HStep. cbn in HStep. modpon HStep. destruct ymid as [ () | ].\n    - destruct HStep as (HStep&_).\n      destruct Halt as (((T'&V')&H')&HSteps&HTerm). pose proof (halt_state_steps_k HStep HSteps) as (H&->); inv H. cbn in *. assumption.\n    - destruct HStep as (T1&V1&Heap1&HStep); modpon HStep.\n      destruct Halt as (((T2&V2)&H2)&HSteps&HTerm).\n      unfold Loop_T; cbn. \n\n      inv HSteps.\n      + exfalso. eapply HTerm; eauto.\n      + pose proof (step_functional HStep H) as <-. cbn -[step_fun] in *.\n        rewrite (step_step_fun HStep) in Hi. rename k0 into k. move HTerm at bottom. clear H. rename H0 into HSteps.\n        destruct (is_halt_state (T1, V1, Heap1)) eqn:EHalt.\n        * apply is_halt_state_correct in EHalt. pose proof (halt_state_steps_k EHalt HSteps) as (H&->); inv H.\n          exists (Step_steps T1 V1 Heap1). split.\n          -- do 3 eexists. eexists 0. cbn -[step_fun]. repeat split; hnf; eauto.\n          -- omega.\n        * exists (Loop_steps T1 V1 Heap1 k). split.\n          -- do 3 eexists. exists k. repeat split; hnf; eauto.\n          -- omega.\n  }\nQed.\n\n\n\nDefinition initTapes : state -> tapes sigStep^+ 11 :=\n  fun '(T,V,H) => initValue T ::: initValue V ::: initValue H ::: Vector.const (initRight _) 8.\n\n\nDefinition Halts {sig: finType} {n: nat} (M : mTM sig n) (t : tapes sig n) :=\n  exists outc k, loopM (initc M t) k = Some outc.\n\n\nTheorem HaltingProblem s :\n  halts s <-> Halts (projT1 Loop) (initTapes s).\nProof.\n  destruct s as ((T&V)&Heap). split.\n  {\n    intros (s'&HSteps&HHalt).\n    apply steps_steps_k in HSteps as (k&HSteps).\n    destruct (@Loop_Terminates (initTapes (T,V,Heap)) (Loop_steps T V Heap k)) as (outc&Term).\n    { cbn. hnf. do 4 eexists; repeat split; cbn; eauto.\n      1: hnf; eauto.\n      1-3: apply initValue_contains.\n      intros i; destruct_fin i; cbn; apply initRight_isRight.\n    }\n    hnf. eauto.\n  }\n  {\n    intros (tout&k&HLoop).\n    pose proof Loop_Realise HLoop as HLoopRel. hnf in HLoopRel. modpon HLoopRel.\n    1-3: apply initValue_contains.\n    intros i; destruct_fin i; cbn; apply initRight_isRight.\n    destruct HLoopRel as (T'&V'&H'&HStep&HTerm&_). cbn in *. hnf. eauto.\n  }\nQed.\n\n\n(** This vernacular command checks wether we have indeed assumed no axioms. *)\nPrint Assumptions HaltingProblem.\n(**\n<<\nClosed under the global context\n>>\n*)", "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/LM/HaltingProblem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.26067985162986895}}
{"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 Cat.Cat.\nFrom Categories Require Import Ext_Cons.Prod_Cat.Prod_Cat Ext_Cons.Prod_Cat.Operations.\nFrom Categories Require Import Basic_Cons.Product.\nFrom Categories Require Import Basic_Cons.Exponential.\nFrom Categories Require Import NatTrans.NatTrans NatTrans.Func_Cat NatTrans.NatIso.\nFrom Categories Require Import Cat.Product Cat.Exponential.\n\n(** Facts about exponentials in Cat. *)\n\nLocal Open Scope functor_scope.\n\nSection Exp_Cat_morph_ex_compose.\n  Context {C C' C'' : Category}\n          (F : (C'' × C) –≻  C')\n          {B : Category}\n          (G : B –≻ C'')\n  .\n\n  (** This is the more specific case of curry_compose. Proven separately for cat\n      because of universe polymorphism issues that prevent cat to both have\n      expoenentials and type_cat in it. *)\n  Theorem Exp_Cat_morph_ex_compose :\n    Exp_Cat_morph_ex (F ∘ (Prod_Functor G (Functor_id C)))\n    = (Exp_Cat_morph_ex F) ∘ G.\n  Proof.\n    Func_eq_simpl.\n    {\n      FunExt.\n      apply NatTrans_eq_simplify.\n      apply JMeq_eq.\n      ElimEq; trivial.\n    }\n    {\n      FunExt; cbn.\n      Func_eq_simpl.\n      FunExt.\n      cbn; auto.\n    }\n  Qed.\n\nEnd Exp_Cat_morph_ex_compose.\n\nSection Exp_Cat_morph_ex_compose_Iso.\n  Context {C C' C'' : Category}\n          (F : (C'' × C) –≻  C')\n          {B : Category}\n          (G : B –≻ C'').\n\n  Local Hint Extern 1 => apply NatTrans_eq_simplify; cbn.\n  \n  Program Definition Exp_Cat_morph_ex_compose_Iso_RL :\n    ((Exp_Cat_morph_ex (F ∘ (Prod_Functor G (Functor_id C))))\n       –≻ ((Exp_Cat_morph_ex F) ∘ G))%nattrans :=\n    {|\n      Trans :=\n        fun c =>\n          {|\n            Trans := fun d => id\n          |}\n    |}.\n\n  Program Definition Exp_Cat_morph_ex_compose_Iso_LR :\n    (((Exp_Cat_morph_ex F) ∘ G)\n       –≻ (Exp_Cat_morph_ex (F ∘ (Prod_Functor G (Functor_id C)))))%nattrans\n    :=\n    {|\n      Trans :=\n        fun c =>\n          {|\n            Trans := fun d => id\n          |}\n    |}.\n    \n  (** This is the isomorphic form of the theorem above. *)\n  Program Definition Exp_Cat_morph_ex_compose_Iso :\n    (((Exp_Cat_morph_ex (F ∘ (Prod_Functor G (Functor_id C))))%functor)\n       ≃ ((Exp_Cat_morph_ex F) ∘ G)%functor)%natiso :=\n    {|\n      iso_morphism := Exp_Cat_morph_ex_compose_Iso_RL;\n      inverse_morphism := Exp_Cat_morph_ex_compose_Iso_LR\n    |}.\n\nEnd Exp_Cat_morph_ex_compose_Iso.\n\nSection Exp_Cat_morph_ex_NT.\n  Context {C C' C'' : Category}\n          {F F' : (C'' × C) –≻  C'}\n          (N : (F –≻ F')%nattrans).\n  (** If we have a natural transformation from F to F' then we have a natural\n      transformation from (curry F) to (curry F'). *)\n  Program Definition Exp_Cat_morph_ex_NT :\n    ((Exp_Cat_morph_ex F) –≻ (Exp_Cat_morph_ex F'))%nattrans :=\n    {|\n      Trans := fun d =>\n                 {|\n                   Trans := fun c => Trans N (d, c);\n                   Trans_com :=\n                     fun c c' h => @Trans_com _ _ _ _ N (d, c) (d ,c') (id,  h);\n                   Trans_com_sym :=\n                     fun c c' h => @Trans_com_sym _ _ _ _ N (d, c) (d ,c') (id,  h)\n                 |}\n    |}.\n\n  Next Obligation.\n  Proof.  \n    apply NatTrans_eq_simplify; FunExt; cbn.\n    apply Trans_com.\n  Qed.    \n\n  Next Obligation.\n  Proof.\n    symmetry.\n    apply Exp_Cat_morph_ex_NT_obligation_1.\n  Qed.\n\nEnd Exp_Cat_morph_ex_NT.\n\nSection Exp_Cat_morph_ex_Iso.\n  Context {C C' C'' : Category}\n          {F F' : (C'' × C) –≻ C'}\n          (N : (F ≃ F')%natiso)\n  .\n\n  (** If F is naturally isomorphic to F' then (curry F) is naturally\n      isomorphic to (curry F'). *)\n  Program Definition Exp_Cat_morph_ex_Iso :\n    (Exp_Cat_morph_ex F ≃ Exp_Cat_morph_ex F')%natiso :=\n    {|\n      iso_morphism := Exp_Cat_morph_ex_NT (iso_morphism N);\n      inverse_morphism := Exp_Cat_morph_ex_NT (inverse_morphism N)\n    |}.\n\n  Next Obligation.\n  Proof.\n    apply NatTrans_eq_simplify; extensionality x; cbn.\n    apply NatTrans_eq_simplify; extensionality y; cbn.\n    change (Trans (N⁻¹) (x, y) ∘ Trans (iso_morphism N) (x, y))%morphism\n    with (Trans (N⁻¹ ∘ N)%morphism (x, y)).\n    rewrite left_inverse; trivial.\n  Qed.\n\n  Next Obligation.\n  Proof.\n    apply NatTrans_eq_simplify; extensionality x; cbn.\n    apply NatTrans_eq_simplify; extensionality y; cbn.\n    change (Trans (iso_morphism N) (x, y) ∘ Trans (N⁻¹) (x, y))%morphism\n    with (Trans (N ∘ (N⁻¹))%morphism (x, y)).\n    rewrite right_inverse; trivial.\n  Qed.\n\nEnd Exp_Cat_morph_ex_Iso.\n\nSection Exp_Cat_morph_ex_inverse_NT.\n  Context {C C' C'' : Category}\n          {F F' : (C'' × C) –≻  C'}\n          (N : ((Exp_Cat_morph_ex F) –≻ (Exp_Cat_morph_ex F'))%nattrans).\n\n\n  (** If we have a natural transformation from (curry F) to (curry F') then\n      we have a natural transformation from F to F'. *)\n  Program Definition Exp_Cat_morph_ex_inverse_NT : (F –≻ F')%nattrans :=\n    {|\n      Trans := fun d => Trans (Trans N (fst d)) (snd d)\n    |}.\n\n  Local Obligation Tactic := idtac.\n  \n  Next Obligation.\n  Proof.  \n    intros [d1 d2] [d1' d2'] [h1 h2]; cbn in *.\n    replace (F @_a (_, _) (_, _) (h1, h2))%morphism\n    with ((F @_a (_, _) (_, _) (id d1', h2))\n            ∘ (F @_a (_, _) (_, _) (h1, id d2)))%morphism by auto.\n    rewrite assoc_sym.   \n    cbn_rewrite (Trans_com (Trans N d1') h2).\n    rewrite assoc.\n    cbn_rewrite (f_equal (fun w => Trans w d2) (Trans_com N h1)).\n    rewrite assoc_sym.\n    rewrite <- F_compose.\n    cbn; auto.\n  Qed.    \n\n  Next Obligation.\n  Proof.\n    symmetry.\n    apply Exp_Cat_morph_ex_inverse_NT_obligation_1.\n  Qed.\n\nEnd Exp_Cat_morph_ex_inverse_NT.\n\nSection Exp_Cat_morph_ex_inverse_Iso.\n  Context {C C' C'' : Category}\n          {F F' : (C'' × C) –≻  C'}\n          (N : (Exp_Cat_morph_ex F ≃ Exp_Cat_morph_ex F')%natiso)\n  .\n\n  (** If (curry F) is naturally isomorphic  to (curry F') then we have that F is\n      naturally isomorphic to F'. *)\n  Program Definition Exp_Cat_morph_ex_inverse_Iso :  (F ≃ F')%natiso :=\n    {|\n      iso_morphism := Exp_Cat_morph_ex_inverse_NT (iso_morphism N);\n      inverse_morphism := Exp_Cat_morph_ex_inverse_NT (inverse_morphism N)\n    |}.\n\n  Next Obligation.\n  Proof.\n    apply NatTrans_eq_simplify; extensionality x; cbn.\n    match goal with\n      [|- ?U = _] =>\n      match U with\n         (Trans (Trans ?A ?X) ?Y ∘ Trans (Trans ?B ?X) ?Y)%morphism =>\n         change U with (Trans (Trans (A ∘ B) X) Y)\n      end\n    end.\n    cbn_rewrite (left_inverse N); trivial. \n  Qed.\n  \n  Next Obligation.\n  Proof.\n    apply NatTrans_eq_simplify; extensionality x; cbn.\n    match goal with\n      [|- ?U = _] =>\n      match U with\n        (Trans (Trans ?A ?X) ?Y ∘ Trans (Trans ?B ?X) ?Y)%morphism =>\n        change U with (Trans (Trans (NatTrans_compose B A) X) Y)\n      end\n    end.\n    cbn_rewrite (right_inverse N); trivial.\n  Qed.\n\nEnd Exp_Cat_morph_ex_inverse_Iso.\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/Cat/Exponential_Facts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2606798451832829}}
{"text": "(************************************************************************)\n(* Copyright (c) 2017-2018, Ajay Kumar Eeralla <ae266@mail.missouri.edu>*)\n(************************************************************************)\n\nRequire Export destructTerm.\nRequire Import Coq.Bool.Bool.\nSet Nested Proofs Allowed.\nRequire Import List.\nImport ListNotations.\n\nSection auxProps.\n  Axiom ifMorphPair2: forall b t1 t2 t3, (t1, If b then t2 else t3) # If b then (t1, t2) else (t1, t3).\n  Axiom ifMorphPair1: forall b t1 t2 t3, (If b then t1 else t2, t3) # If b then (t1, t3) else (t2, t3).\n  Axiom ifMorphf3: forall b t1 t2 t3 t4 {f: message-> message -> message -> Bool}, (f t1 t2 (If b then t3 else t4)) ## (IF b then (f t1 t2 t3) else (f t1 t2 t4)).\n  Axiom ifMorphf3b_fst: forall b t1 t2 t3 t4 {f: message-> message -> message -> message}, (f (If b then t1 else t2) t3 t4) # (If b then (f t1 t3 t4) else (f t2 t3 t4)).\n  Axiom andB_elim: forall b1 b2 t1 t2, (If b1 & b2 then t1 else t2) # (If b1 then (If b2 then t1 else t2) else t2).\n  Axiom ifMorphIfThen: forall b1 b2 t1 t2 t3, (If b1 then (If b2 then t1 else t2) else t3) # (If b2 then (If b1 then t1 else t3) else (If b1 then t2 else t3)).\n  Axiom orB_FAlse_r: forall b, b or FAlse = b.\n  Axiom orB_FAlse_l: forall b, FAlse or b = b.\n  Axiom ifMorphIf: forall b1 b2 b3 b4 t1 t2, (If b1 & (IF b2 then b3 else b4) then t1 else t2) # (If b2 then (If b1 & b3 then t1 else t2) else (If b1 & b4 then t1 else t2)).\n  Fixpoint ifMorphDef (f: Mlist -> message) (al: Mlist) (l: Mlist) :=\n    match l with\n    | nil => f (al ++ nil)\n    | cons (If b then t1 else t2) nil  => If b then (f (al ++ (cons t1 nil))) else (f (al ++ (cons t2 nil)))\n| h :: tl => match h with\n             | If b then t1 else t2 => If b then (ifMorphDef f (al ++ (cons t1 nil)) tl) else (ifMorphDef f (al ++ (cons t2 nil)) tl)\n| _ => ifMorphDef f (al ++ (cons h nil)) tl\n  end\n  end.\n  Axiom clos_sub_vtrm: forall n1 s1 n2 s2 t, let mvl:= (distMvars [msg t]) in (cons n1  (cons n2 nil))= mvl \\/ (cons n2 (cons n1 nil)) = mvl -> closMsg ({{n1:=s1}} ({{n2:=s2}}t)) = true.\n\n  (* Compute ifMorphDef f nil [O; If FAlse then nonce 1 else O; nonce 2; If TRue then (If TRue then nonce 100 else O) else nonce 4]. *)\n  Axiom ifMorphAttComp: forall l, (f l) # (ifMorphDef f nil l).\n  End auxProps.\n\n  (* Axiom ifMorphAttComp: forall b f l t, (If b then (f l) else t) # (If b then (ifMorphDef f nil l) else t). *)\n Open Scope msg_scope.\n(* Section auxTacs. *)\n  Ltac rew_ifMorphIf :=\n    match goal with\n    |[|- context[(If ?B1 & (IF ?B2 then ?B3 else ?B4) then ?T1 else ?T2)] ] => rewrite (@ifMorphIf B1 B2 B3 B4 T1 T2)\n    end.\n  Ltac apply_ifbr ml1 ml2 b b' x x' y y' := apply (@IFBRANCH_M1 _ ml1 ml2 b b' x x' y y'); simpl.\n  Ltac aply_ifbr :=\n    match goal with\n    | [|- [msg (If ?B1 then ?T1 else ?F1)]\n            ~ [msg (If ?B2 then ?T2 else ?F2)] ]\n      => apply_ifbr [] [] B1 B2 T1 T2 F1 F2\n    | [|- [?X1, msg (If ?B1 then ?T1 else ?F1)]\n            ~ [?Y1, msg (If ?B2 then ?T2 else ?F2)] ]\n      => apply_ifbr [X1] [Y1] B1 B2 T1 T2 F1 F2\n    | [|- [?X1, ?X2, msg (If ?B1 then ?T1 else ?F1)]\n            ~ [?Y1, ?Y2, msg (If ?B2 then ?T2 else ?F2)] ]\n      => apply_ifbr [X1, X2] [Y1, Y2] B1 B2 T1 T2 F1 F2\n    | [|- [?X1, ?X2, ?X3, msg (If ?B1 then ?T1 else ?F1)]\n            ~ [?Y1, ?Y2, ?Y3, msg (If ?B2 then ?T2 else ?F2)] ]\n      => apply_ifbr [X1, X2, X3] [Y1, Y2, Y3] B1 B2 T1 T2 F1 F2\n    | [|- [?X1, ?X2, ?X3, ?X4, msg (If ?B1 then ?T1 else ?F1)]\n            ~ [?Y1, ?Y2, ?Y3, ?Y4, msg (If ?B2 then ?T2 else ?F2)] ]\n      => apply_ifbr [X1, X2, X3, X4] [Y1, Y2, Y3, Y4] B1 B2 T1 T2 F1 F2\n    | [|- [?X1, ?X2, ?X3, ?X4, ?X5, msg (If ?B1 then ?T1 else ?F1)]\n            ~ [?Y1, ?Y2, ?Y3, ?Y4, ?Y5, msg (If ?B2 then ?T2 else ?F2)] ]\n      => apply_ifbr [X1, X2, X3, X4, X5] [Y1, Y2, Y3, Y4, Y5] B1 B2 T1 T2 F1 F2\n    | [|- [?X1, ?X2, ?X3, ?X4, ?X5, ?X6, msg (If ?B1 then ?T1 else ?F1)]\n            ~ [?Y1, ?Y2, ?Y3, ?Y4, ?Y5, ?Y6, msg (If ?B2 then ?T2 else ?F2)] ]\n      => apply_ifbr [X1, X2, X3, X4, X5, X6] [Y1, Y2, Y3, Y4, Y5, Y6] B1 B2 T1 T2 F1 F2\n    | [|- [?X1, ?X2, ?X3, ?X4, ?X5, ?X6, ?X7, msg (If ?B1 then ?T1 else ?F1)]\n            ~ [?Y1, ?Y2, ?Y3, ?Y4, ?Y5, ?Y6, ?Y7, msg (If ?B2 then ?T2 else ?F2)] ]\n      => apply_ifbr [X1, X2, X3, X4, X5, X6, X7] [Y1, Y2, Y3, Y4, Y5, Y6, Y7] B1 B2 T1 T2 F1 F2\n                    (** extend this for other cases *)\n    end.\n\n  Proposition freshNeqExt: forall (n: nat) (m: message), ^? m = true /\\ (Fresh (cons n nil) [msg m]) = true -> ((nonce n) #? m) ## FAlse.\nProof. intros. pose proof(FRESHNEQ n m).\n       apply (@Example10_B ((nonce n)#?m) FAlse FAlse).\n       unfold const; auto.\nQed.\nLtac aply_freshneq n :=\n  match goal with\n  |[|-context[ (nonce n) #? ?X] ] =>  pose proof(@freshNeqExt n X) as tmp; rewrite tmp; try unfold Fresh; try auto\n  end.\nAxiom compHid: forall (n1 n2: nat) (t1 t2: message) {n} (z: mylist n),\n    closMylist [msg t1, msg t2] = true /\\ closMylist z = true /\\\n      Fresh [n1; n2] ([msg t1, msg t2]++z)%msg = true ->\n    (|t1|#?|t2|) ## TRue ->\n    (z ++ [msg (comm t1 (k n1)), msg (comm t2 (k n2))]) ~ (z ++ [msg (comm t2 (k n1)), msg (comm t1 (k n2))]).\n\nProposition vchecksImplyVoteEql: (vcheck (v 0)) & (vcheck (v 1)) ## TRue -> (|v 0| #? |v 1|) ## TRue.\nProof. intros.\n       pose proof(vote_len_eql).\n       rewrite H in H0; unfold v in H0; red_in H0; try auto.\nQed.\nLtac aplyCompHid :=\n  match goal with\n  | [|- [msg (comm ?V0 (kc (nonce ?N2))), msg (comm ?V1 (kc (nonce ?N3)))]\n          ~ [msg (comm _ (kc (nonce _))), msg (comm _ (kc (nonce _)))] ]\n    => apply (@compHid N2 N3 V0 V1 _ []%msg); try apply vchecksImplyVoteEql; try auto; try assumption\n  end.\n\n(* End auxTacs. *)\n(* Definition V (b:bool) := *)\n(*     match b with *)\n(*     | false => (V0 (nonce 0)) *)\n(*     | true => (V1 (nonce 0)) *)\n(*     end. *)\n\n(*   Definition cn (b:bool) :nat := *)\n(*     match b with *)\n(*     | false => 0 *)\n(*     | true => 1 *)\n(*     end. *)\n(* SearchAbout eqb%bool. *)\n(** abbreviations *)\n\nDefinition sr n := rs (nonce n).\nDefinition t0 seed1 seed2 := (((vk 0), (Mvar 0), sign (Mvar 0) (ssk 0) (sr seed1)), ((vk 1), (Mvar 1), sign (Mvar 1) (ssk 1) (sr seed2))).\n\nDefinition tau n (m:message) := match n, m with\n                                | 1, m => (pi1 m)\n                                | 2, m => (pi1 (pi2 m))\n                                | 3, m => (pi2 (pi2 m))\n                                | _, _ => O\n                                end.\n\nDefinition d n x := (dec (tau n x) (ske 11)).\nDefinition pvchecks x := ((pi2 (d 1 x)) #? TWO) & ((pi2 (d 2 x)) #? TWO) & ((pi2 (d 3 x)) #? TWO).\nDefinition pochecks x := ((tau 3 (d 1 x)) #? THREE) & ((tau 3 (d 2 x)) #? THREE) & ((tau 3 (d 3 x)) #? THREE).\n\nDefinition dist x := !((d 1 x) #? (d 2 x)) & !((d 1 x) #? (d 3 x))& ! ((d 2 x) #? (d 3 x)).\nDefinition isin (x y:message):Bool := (x #? (tau 1 y)) or (x #? (tau 2 y)) or (x #? (tau 3 y)).\nDefinition bcheck (x y:message):Bool := (isin x ((tau 1 (pi2 (tau 1 y))), ((tau 1 (pi2 (tau 2 y))), (tau 1 (pi2 (tau 3 y)))))).\nDefinition ncheck (x y:message):Bool := (isin x ((tau 3 (pi2 (tau 1 y))), ((tau 3 (pi2 (tau 2 y))), (tau 3 (pi2 (tau 3 y)))))).\n\n\n                            Definition lbl:= |(nonce 100)|.\nDefinition label x y := If (x #? (tau 2 (pi2 (tau 1 y)))) then (pi1 (tau 1 y))\n                           else  (If (x#? (tau 2 (pi2 (tau 2 y)))) then (pi1 (tau 2 y))\n                                                       else (If (x #? (tau 2 (pi2 (tau 3 y)))) then (pi1 (tau 3 y))\n                                                             else O)).\nAdd Parametric Morphism :(@label) with\nsignature EQm ==> EQm ==> EQm as label_mor.\nProof. intros; aply_cong; auto. Qed.\n\nDefinition bnlcheck( x y z:message):Bool:= (bcheck x z) & (|(label x z)| #? lbl) & (ncheck y z).\n\n(* Add morphism for bnlcheck *)\nAdd Parametric Morphism :(@bnlcheck) with\n    signature EQm ==> EQm ==> EQm ==> EQb as bnlcheck_mor.\nProof. intros; aply_cong; auto. Qed.\n\nDefinition mvchecks x (n n':nat) := (dist (x n n')) & (pvchecks (x n n')).\n\nDefinition p n x := ( (tau 1 (d n x)), (tau 2 (d n x))).\n\nDefinition sotrm x := (shufl (p 1 x) (p 2 x) (p 3 x)).\n\nDefinition isink (x y:message):Bool := (x #? (tau 2 (d 1 y))) or (x #? (tau 2 (d 2 y))) or (x #? (tau 2 (d 3 y))).\n\nLemma tau1: forall x y z, (tau 1 (x, (y, z))) # x.\nProof. intros. unfold tau. rewrite proj1; auto. reflexivity.\nQed.\nLemma tau2: forall x y z, (tau 2 (x, (y, z))) # y.\nProof. intros. unfold tau; rewrite proj2, proj1;auto. reflexivity. Qed.\nLemma tau3: forall x y z, (tau 3 (x, (y, z))) # z.\nProof. intros. unfold tau. repeat rewrite proj2; try reflexivity.\nQed.\n(* better to apply nodup seperately *)\nAxiom nodup: forall {m} (l1 l2: mylist m), let l1' := conv_mylist_listos l1 in\n                                           let l2' := conv_mylist_listos l2 in\n                                           let l1'' := noDup l1' in\n                                           let l2'' := noDup l2' in\n                                           let y:= oslToMylist l1'' l2'' in\n                                           (pi1ProdMylist y) ~ (pi2ProdMylist y) -> l1 ~ l2.\n\nAxiom cca2Trans: forall {m} {l1 l2 l1' l2': mylist m}, l1 ~ l1' /\\ l2 ~ l2' /\\ l1' ~ l2' -> l1 ~ l2.\nLtac aply_cca2Trans L R :=\n  match goal with\n  | [|- ?X ~ ?Y] => apply (@cca2Trans _ X Y L R); try split\n  end.\n\nLtac aplyCCA2 n n1 n2 n3 u u' := aplyDestrEnc 11 7; apply nodup; simpl;\n  match goal with\n  | [|- ?X ~ ?Y] => apply (@subMvarEnc n n1 n2 n3 u u' _ X Y); simpl; (* replace encryptions with (Mvar n) *)\n                    match goal with\n                    | [|- ?X1 ~ ?Y1] => apply (@rewDecs n n1 u u' _ X1 Y1); simpl; (* rewrite decryptions to pass the cca2compliance *)\n                                        match goal with\n                                        |[|- ?X2 ~ ?Y2] => apply (@ENCCCA2 n n1 n2 n3 u u' _ X2); repeat (try apply len_reg; try rewrite eqmeql; try apply nameEql; try simpl; try intuition)\n                                        end\n                    end\n  end.\n(* Some stuff *)\nAxiom funcapp_f1m': forall {n n'} f p1 (z z':mylist n) (z1 z1':mylist n'), (z ++ z1) ~ (z' ++ z1') -> ((z ++ z1) ++ [msg (f (ostomsg (getelt_at_pos p1 z1)))]) ~ ((z' ++ z1') ++ [msg (f (ostomsg (getelt_at_pos p1 z1')))]).\nLtac funcapp_f1m'_in g n H:= apply funcapp_f1m' with (f:=g) (p1:=n) in H; unfold getelt_at_pos in H; simpl in H.\nAxiom ifmor_ifm: forall f b x y, (f (If b then x else y)) # (If b then (f x) else (f y)).\n\nLemma extFuncapp1: forall n b b' x x' y y' (z z': mylist n) g, (z ++ [bol b, msg (If b then x else y)]) ~ (z' ++ [bol b', msg (If b' then x' else y')]) -> (z ++ [bol b, msg (If b then x else y), msg (If b then (g x) else |_)])~ (z' ++ [bol b', msg (If b' then x' else y'), msg (If b' then (g x') else |_)]).\nProof. intros.\n       funcapp_f1m'_in g 2 H.\n       simpl.\n       repeat rewrite ifmor_ifm in H.\n       funcapp_fm_last |_ H; auto. apply ind_assoc in H; simpl in H.\n       apply funcapp_f3bm' with (f:= (ifm_then_else_)) (p1:= 1) (p2:=3) (p3:=4) in H; unfold getelt_at_pos; simpl in H.\n       simpl in H.\n       (********************)\n       apply ind_assoc in H; simpl in H.\n       do 2  apply restr with (p:= droplastsec) in H; unfold droplastsec in H; simpl in H; simpl; try rewrite Nat.eqb_refl; auto.\n       repeat rewrite aply_ifeval_gen in H;auto. Qed.\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/voteprivacy/auxDefs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2606798451832829}}
{"text": "Require Import Lib.Extra.\nRequire Import CompCert.Events.\nRequire Import CompCert.Smallstep.\nRequire Import CompCert.Behaviors.\nRequire Import Common.Definitions.\nRequire Import Common.Util.\nRequire Import Common.Values.\nRequire Import Common.Memory.\nRequire Import Common.Linking.\nRequire Import Common.CompCertExtensions.\nRequire Import Common.Traces.\nRequire Import Source.Language.\nRequire Import Source.GlobalEnv.\nRequire Import Source.CS.\n\nFrom Coq Require Import ssreflect ssrfun ssrbool.\nFrom mathcomp Require Import eqtype seq.\nFrom mathcomp Require ssrnat.\n\nImport Source.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nSection Definability.\n  Local Open Scope fset_scope.\n\n  Variable intf: Program.interface.\n  Variable closed_intf: closed_interface intf.\n  Variable has_main: intf Component.main.\n\n  (** The definability proof takes an execution trace as its input and builds a\n      source program that can produce that trace.  Roughly speaking, it does so\n      by keeping one counter for each component, and using that counter to track\n      how many calls or returns have been executed by that component.\n\n      To see how this works, suppose that we have an interface with two\n      procedures P1 and P2, which live in components C1 and C2.  Given the trace\n      *)\n\n\n  (**   ECall mainC P1    0 C1\n        ECall C1    P2    1 C2\n        ERet  C2          2 C1\n        ECall C1    P2    3 C2\n        ECall C2    mainP 4 mainC *)\n\n  (** we would produce the program *)\n\n  (**   C1 {\n          P1() {\n            if (local[0] == 0) {\n              local[0]++;\n              C2.P2(1);\n              C1.P1(0);\n            } else if (local[0] == 1) {\n              local[0]++;\n              C2.P2(3);\n              C1.P1(0);\n            } else {\n              exit();\n            }\n          }\n        }\n\n        C2 {\n          P2() {\n            if (local[0] == 0) {\n              local[0]++;\n              return 2;\n            } else if (local[0] == 1) {\n              local[0]++;\n              mainC.mainP(4);\n              C2.P2(0);\n            } else {\n              exit();\n            }\n          }\n        } *)\n\n  (** If a component has multiple procedures, they can share the same\n      code. Notice that each branch that performs call performs a recursive call\n      at the end.  This is needed to trigger multiple events from a single\n      function.\n\n      The first ingredient needed to perform this translation is a switch\n      statement that runs code based on the value of the first local variable.\n\n   *)\n\n  Definition switch_clause n e_then e_else :=\n    let one := E_val (Int 1%Z) in\n    E_if (E_binop Eq (E_deref E_local) (E_val (Int n)))\n         (E_seq (E_assign E_local (E_binop Add (E_deref E_local) one)) e_then)\n         e_else.\n\n  Ltac take_step :=\n    match goal with\n    | |- @star _ _ _ _ _ ?t _ =>\n      eapply (@star_step _ _ _ _ _ E0 _ t _ t); trivial; [econstructor|]\n    end.\n\n  Lemma switch_clause_spec p' C stk mem n n' e_then e_else arg :\n    Memory.load mem (C, Block.local, 0%Z) = Some (Int n) ->\n    if (n =? n') % Z then\n      exists mem',\n        Memory.store mem (C, Block.local, 0%Z) (Int (Z.succ n)) = Some mem' /\\\n        Star (CS.sem p')\n             [CState C, stk, mem , Kstop, switch_clause n' e_then e_else, arg] E0\n             [CState C, stk, mem', Kstop, e_then, arg]\n    else\n      Star (CS.sem p')\n           [CState C, stk, mem, Kstop, switch_clause n' e_then e_else, arg] E0\n           [CState C, stk, mem, Kstop, e_else, arg].\n  Proof.\n    intros Hload.\n    destruct (Z.eqb_spec n n') as [n_n'|n_n'].\n    - subst n'.\n      assert (Hload' := Hload).\n      unfold Memory.load in Hload'.\n      unfold Memory.store.\n      simpl in *.\n      destruct (getm mem C) as [memC|] eqn:EmemC; try discriminate.\n      destruct (ComponentMemory.store_after_load _ _ _ _ (Int (Z.succ n)) Hload')\n        as [memC' EmemC'].\n      rewrite EmemC'.\n      eexists; split; eauto.\n      repeat take_step; trivial; try eassumption.\n      repeat take_step; trivial; try eassumption.\n      rewrite Z.eqb_refl -[_ != _]/(true) /=.\n      repeat take_step; trivial; try eassumption.\n      { unfold Memory.store. simpl. rewrite EmemC. simpl. now rewrite Z.add_1_r EmemC'. }\n      apply star_refl.\n    - unfold switch_clause.\n      repeat take_step; trivial; try eassumption.\n      eapply (@star_step _ _ _ _ _ E0 _ E0 _ E0); trivial; simpl.\n      { rewrite <- Z.eqb_neq in n_n'. rewrite n_n'. simpl.\n        eapply CS.KS_If2. }\n      apply star_refl.\n  Qed.\n\n  Definition switch_add_expr e res :=\n    (Nat.pred (fst res), switch_clause (Z.of_nat (Nat.pred (fst res))) e (snd res)).\n\n  Definition switch (es: list expr) (e_else: expr) : expr :=\n    snd (fold_right switch_add_expr (length es, e_else) es).\n\n  Lemma fst_switch n (e_else: expr) (es : list expr) :\n    fst (fold_right switch_add_expr (n, e_else) es) = (n - length es)%nat.\n  Proof.\n    induction es as [|e' es IH]; try now rewrite Nat.sub_0_r.\n    simpl. now rewrite IH Nat.sub_succ_r.\n  Qed.\n\n  Lemma switch_spec_else p' C stk mem n es e_else arg :\n    Memory.load mem (C, Block.local, 0%Z) = Some (Int (Z.of_nat n)) ->\n    (length es <= n)%nat ->\n    Star (CS.sem p')\n         [CState C, stk, mem, Kstop, switch es e_else, arg] E0\n         [CState C, stk, mem, Kstop, e_else, arg].\n  Proof.\n    intros C_local es_n. unfold switch.\n    enough (forall m,\n               m <= n -> length es <= m ->\n               Star (CS.sem p')\n                    [CState C, stk, mem, Kstop, snd (fold_right switch_add_expr (m, e_else) es), arg]\n                    E0\n                    [CState C, stk, mem, Kstop, e_else, arg])%nat.\n    { apply (H (length es)); trivial. }\n    clear es_n. intros m m_le_n es_le_n.\n    induction es as [|e es IH]; try apply star_refl.\n    unfold switch. simpl. simpl in es_le_n. rewrite fst_switch -Nat.sub_succ_r. simpl.\n    do 5 take_step; [eauto|eauto|].\n    do 2 take_step.\n    eapply (@star_step _ _ _ _ _ E0); try now (simpl; reflexivity).\n    { apply CS.eval_kstep_sound. simpl.\n      destruct (Z.eqb_spec (Z.of_nat n) (Z.of_nat (m - S (length es)))) as [n_eq_0|?]; simpl.\n      - zify. omega.\n      - reflexivity. }\n    apply IH. omega.\n  Qed.\n\n  Lemma switch_spec p' C stk mem es e es' e_else arg :\n    Memory.load mem (C, Block.local, 0%Z) = Some (Int (Z.of_nat (length es))) ->\n    exists mem',\n      Memory.store mem (C, Block.local, 0%Z) (Int (Z.of_nat (S (length es)))) = Some mem' /\\\n      Star (CS.sem p')\n           [CState C, stk, mem , Kstop, switch (es ++ e :: es') e_else, arg] E0\n           [CState C, stk, mem', Kstop, e, arg].\n  Proof.\n    intros Hload.\n    assert (Eswitch :\n              exists e_else',\n                switch (es ++ e :: es') e_else =\n                switch es (switch_clause (Z.of_nat (length es)) e e_else')).\n    { unfold switch. rewrite fold_right_app app_length. simpl.\n      exists (snd (fold_right switch_add_expr ((length es + S (length es'))%nat, e_else) es')).\n      repeat f_equal. rewrite -> surjective_pairing at 1. simpl.\n      rewrite fst_switch Nat.add_succ_r.\n      assert (H : (S (length es + length es') - length es' = S (length es))%nat) by omega.\n      rewrite H. reflexivity. }\n    destruct Eswitch as [e_else' ->]. clear e_else. rename e_else' into e_else.\n    assert (Hcont := switch_clause_spec p' stk (Z.of_nat (length es)) e e_else arg Hload).\n    rewrite Z.eqb_refl in Hcont.\n    destruct Hcont as (mem' & Hstore & Hstar2).\n    exists mem'. rewrite Nat2Z.inj_succ. split; trivial.\n    apply (fun H => @star_trans _ _ _ _ _ E0 _ H E0 _ _ Hstar2); trivial.\n    apply (switch_spec_else p' stk _ arg Hload).\n    reflexivity.\n  Qed.\n\n  (** We use [switch] to define the following function [expr_of_trace], which\n      converts a sequence of events to an expression that produces that sequence\n      of events when run from the appropriate component.  We assume that all\n      events were produced from the same component.  The [C] and [P] arguments\n      are only needed to generate the recursive calls depicted above. *)\n\n  Definition expr_of_event (C: Component.id) (P: Procedure.id) (e: event) : expr :=\n    match e with\n    | ECall _ P' arg C' =>\n      E_seq (E_call C' P' (E_val (Int arg)))\n            (E_call C  P  (E_val (Int 0)))\n    | ERet  _ ret_val _ => E_val (Int ret_val)\n    end.\n\n  Definition expr_of_trace (C: Component.id) (P: Procedure.id) (t: trace) : expr :=\n    switch (map (expr_of_event C P) t) E_exit.\n\n  (** To compile a complete trace mixing events from different components, we\n      split it into individual traces for each component and apply\n      [expr_of_trace] to each one of them.  We also initialize the memory of\n      each component to hold 0 at the first local variable. *)\n\n  Definition comp_subtrace (C: Component.id) (t: trace) :=\n    filter (fun e => C == cur_comp_of_event e) t.\n\n  Lemma comp_subtrace_app (C: Component.id) (t1 t2: trace) :\n    comp_subtrace C (t1 ++ t2) = comp_subtrace C t1 ++ comp_subtrace C t2.\n  Proof. apply: filter_cat. Qed.\n\n  Definition procedure_of_trace C P t :=\n    expr_of_trace C P (comp_subtrace C t).\n\n  Definition procedures_of_trace (t: trace) : NMap (NMap expr) :=\n    mapim (fun C Ciface =>\n             let procs :=\n                 if C == Component.main then\n                   Procedure.main |: Component.export Ciface\n                 else Component.export Ciface in\n               mkfmapf (fun P => procedure_of_trace C P t) procs)\n          intf.\n\n  Definition valid_procedure C P :=\n    C = Component.main /\\ P = Procedure.main\n    \\/ exported_procedure intf C P.\n\n  Lemma find_procedures_of_trace_exp (t: trace) C P :\n    exported_procedure intf C P ->\n    find_procedure (procedures_of_trace t) C P\n    = Some (procedure_of_trace C P t).\n  Proof.\n    intros [CI [C_CI CI_P]].\n    unfold find_procedure, procedures_of_trace.\n    rewrite mapimE C_CI /= mkfmapfE.\n    case: eqP=> _; last by rewrite CI_P.\n    by rewrite in_fsetU1 CI_P orbT.\n  Qed.\n\n  Lemma find_procedures_of_trace_main (t: trace) :\n    find_procedure (procedures_of_trace t) Component.main Procedure.main\n    = Some (procedure_of_trace Component.main Procedure.main t).\n  Proof.\n    rewrite /find_procedure /procedures_of_trace.\n    rewrite mapimE eqxx.\n    case: (intf Component.main) (has_main)=> [Cint|] //= _.\n    by rewrite mkfmapfE in_fsetU1 eqxx.\n  Qed.\n\n  Lemma find_procedures_of_trace (t: trace) C P :\n    valid_procedure C P ->\n    find_procedure (procedures_of_trace t) C P\n    = Some (procedure_of_trace C P t).\n  Proof.\n    by move=> [[-> ->]|?];\n    [apply: find_procedures_of_trace_main|apply: find_procedures_of_trace_exp].\n  Qed.\n\n  Definition program_of_trace (t: trace) : program :=\n    {| prog_interface  := intf;\n       prog_procedures := procedures_of_trace t;\n       prog_buffers    := mapm (fun _ => inr [Int 0]) intf |}.\n\n  (** To prove that [program_of_trace] is correct, we need to describe how the\n      state of the program evolves as it emits events from the translated trace.\n      One of the difficulties is the stack.  If a call to a component [C]\n      performs [n] calls to other components before returning, the code\n      generated by [expr_of_trace] will perform [n] *recursive* calls to [C].\n      Thus, the final return to the calling component must be preceded by [n]\n      returns from those recursive calls.  We describe this pattern with the\n      following properties.  *)\n\n  Fixpoint well_formed_callers (callers: list Component.id) (stk: CS.stack) : Prop :=\n    match callers with\n    | [] => True\n    | C :: callers' =>\n      exists v P top bot,\n      stk = CS.Frame C v (Kseq (E_call C P (E_val (Int 0))) Kstop) :: top ++ bot /\\\n      valid_procedure C P /\\\n      All (fun '(CS.Frame C' _ k) => C' = C /\\ k = Kstop) top /\\\n      well_formed_callers callers' bot\n    end.\n\n  Definition well_formed_stack (s: stack_state) (stk: CS.stack) : Prop :=\n    exists top bot,\n      stk = top ++ bot /\\\n      All (fun '(CS.Frame C' _ k) => C' = cur_comp s /\\ k = Kstop) top /\\\n      well_formed_callers (callers s) bot.\n\n  Lemma well_formed_events_well_formed_program t :\n    all (well_formed_event intf) t ->\n    Source.well_formed_program (program_of_trace t).\n  Proof.\n    move=> Ht; split=> //=.\n    - exact: closed_interface_is_sound.\n    - by rewrite /procedures_of_trace domm_mapi.\n    - move=> C P.\n      rewrite /exported_procedure /Program.has_component /Component.is_exporting.\n      case=> CI [C_CI P_CI].\n      by rewrite find_procedures_of_trace_exp //; exists CI; split; eauto.\n    - move=> C P Pexpr.\n      rewrite /find_procedure /procedures_of_trace mapimE.\n      case intf_C: (intf C)=> [CI|] //=.\n      rewrite mkfmapfE; case: ifP=> //= P_CI [<-] {Pexpr}; split; last first.\n        rewrite /procedure_of_trace /expr_of_trace /switch.\n        elim: {t Ht} (comp_subtrace C t) (length _) => [|e t IH] n //=.\n        by case: e=> /=.\n      pose call_of_event e := if e is ECall _ P _ C then Some (C, P) else None.\n      have /fsubsetP sub :\n          fsubset (called_procedures (procedure_of_trace C P t))\n                  ((C, P) |: fset (pmap call_of_event (comp_subtrace C t))).\n        rewrite /procedure_of_trace /expr_of_trace /switch.\n        elim: {t Ht} (comp_subtrace C t) (length _)=> [|e t IH] n //=.\n          exact: fsub0set.\n        move/(_ n) in IH; rewrite !fset0U.\n        case: e=> [C' P' v C''|] //=; last by rewrite fset0U.\n        rewrite !fsetU0 fset_cons !fsubUset !fsub1set !in_fsetU1 !eqxx !orbT /=.\n        by rewrite fsetUA [(C, P) |: _]fsetUC -fsetUA fsubsetU // IH orbT.\n      move=> C' P' /sub/fsetU1P [[-> ->]|] {sub}.\n        rewrite eqxx find_procedures_of_trace //.\n        move: P_CI; case: eqP intf_C=> [->|_] intf_C.\n          rewrite /valid_procedure.\n          case/fsetU1P=> [->|P_CI]; eauto.\n          by right; exists CI; split.\n        by move=> P_CI; right; exists CI; split.\n      rewrite in_fset /= => C'_P'.\n      suffices ? : imported_procedure intf C C' P'.\n        by case: eqP => [<-|] //; rewrite find_procedures_of_trace_exp; eauto.\n      elim: {P P_CI} t Ht P' C'_P' => [|e t IH] //= /andP [He Ht] P.\n      case: (C =P _) => [HC|]; last by eauto.\n      case: e HC He=> [_ P' v C'' /= <-|]; last by eauto.\n      rewrite inE; case/andP=> [C_C'' /imported_procedure_iff imp_C''_P'].\n      by case/orP=> [/eqP [-> ->] //|]; eauto.\n    - by rewrite domm_map.\n    - move=> C; rewrite -mem_domm => /dommP [CI C_CI].\n      rewrite /has_required_local_buffers /= mapmE C_CI /=.\n      eexists; eauto=> /=; omega.\n    - rewrite /prog_main find_procedures_of_trace //=.\n      + split; first reflexivity.\n        intros _.\n        destruct (intf Component.main) as [mainP |] eqn:Hcase.\n        * apply /dommP. exists mainP. assumption.\n        * discriminate.\n      + by left.\n  Qed.\n\n  Lemma closed_program_of_trace t :\n    Source.closed_program (program_of_trace t).\n  Proof.\n    split=> //=; by rewrite /prog_main find_procedures_of_trace_main.\n  Qed.\n\n  Arguments Memory.load  : simpl nomatch.\n  Arguments Memory.store : simpl nomatch.\n\n  Section WithTrace.\n\n    Variable t : trace.\n\n    Let p    := program_of_trace t.\n    Let init := prepare_buffers p.\n\n    Local Definition component_buffer C := C \\in domm intf.\n\n    Lemma valid_procedure_has_block C P :\n      valid_procedure C P ->\n      component_buffer C.\n    Proof.\n      case=> [[-> _ {C P}]|[CI]]; rewrite /component_buffer /=.\n        by rewrite mem_domm.\n      rewrite /Program.has_component /Component.is_exporting /=.\n      by rewrite mem_domm; case=> ->.\n    Qed.\n\n    Local Definition counter_value C prefix :=\n      Z.of_nat (length (comp_subtrace C prefix)).\n\n    Definition well_formed_memory (prefix: trace) (mem: Memory.t) : Prop :=\n      forall C,\n        component_buffer C ->\n        Memory.load mem (C, Block.local, 0%Z) = Some (Int (counter_value C prefix)).\n\n    Lemma counter_value_snoc prefix C e :\n      counter_value C (prefix ++ [e])\n      = (counter_value C prefix\n        + if C == cur_comp_of_event e then 1 else 0) % Z.\n    Proof.\n      unfold counter_value, comp_subtrace.\n      rewrite filter_cat app_length. simpl.\n      rewrite Nat2Z.inj_add.\n      now destruct (_ == _).\n    Qed.\n\n    Lemma well_formed_memory_store_counter prefix mem C e :\n      component_buffer C ->\n      well_formed_memory prefix mem ->\n      C = cur_comp_of_event e ->\n      exists mem',\n        Memory.store mem (C, Block.local, 0%Z) (Int (counter_value C (prefix ++ [e]))) = Some mem' /\\\n        well_formed_memory (prefix ++ [e]) mem'.\n    Proof.\n      move=> C_b wf_mem HC.\n      have C_local := wf_mem _ C_b.\n      have [mem' Hmem'] := Memory.store_after_load\n                             _ _ _ (Int (counter_value C (prefix ++ [e])))\n                             C_local.\n      exists mem'. split; trivial=> C' C'_b.\n      have C'_local := wf_mem _ C'_b.\n      rewrite -> counter_value_snoc, <- HC, Nat.eqb_refl in *.\n      case: (altP (C' =P C)) => [?|C_neq_C'].\n      - subst C'.\n        by rewrite -> (Memory.load_after_store_eq _ _ _ _ Hmem').\n      - have neq : (C, Block.local, 0%Z) <> (C', Block.local, 0%Z) by move/eqP in C_neq_C'; congruence.\n        rewrite (Memory.load_after_store_neq _ _ _ _ _ neq Hmem').\n        now rewrite Z.add_0_r.\n    Qed.\n\n    Variant well_formed_state (s: stack_state) (prefix suffix: trace) : CS.state -> Prop :=\n    | WellFormedState C stk mem k exp arg P\n      of C = cur_comp s\n      &  k = Kstop\n      &  exp = procedure_of_trace C P t\n      &  well_bracketed_trace s suffix\n      &  all (well_formed_event intf) suffix\n      &  well_formed_stack s stk\n      &  well_formed_memory prefix mem\n      &  valid_procedure C P\n      :  well_formed_state s prefix suffix [CState C, stk, mem, k, exp, arg].\n\n    Lemma definability_gen s prefix suffix cs :\n      t = prefix ++ suffix ->\n      well_formed_state s prefix suffix cs ->\n      exists2 cs', Star (CS.sem p) cs suffix cs' &\n                   CS.final_state cs'.\n    Proof.\n      have Eintf : genv_interface (prepare_global_env p) = intf by [].\n      have Eprocs : genv_procedures (prepare_global_env p) = prog_procedures p by [].\n      elim: suffix s prefix cs=> [|e suffix IH] /= [C callers] prefix.\n      - rewrite cats0 => cs <- {prefix}.\n        case: cs / => /= _ stk mem _ _ arg P -> -> -> _ _ wf_stk wf_mem P_exp.\n        exists [CState C, stk, mem, Kstop, E_exit, arg]; last by left.\n        have C_b := valid_procedure_has_block P_exp.\n        have C_local := wf_mem _ C_b.\n        rewrite /procedure_of_trace /expr_of_trace.\n        apply: switch_spec_else; eauto.\n        rewrite -> size_map; reflexivity.\n      - move=> cs Et /=.\n        case: cs / => /= _ stk mem _ _ arg P -> -> -> /andP [/eqP wf_C wb_suffix] /andP [wf_e wf_suffix] wf_stk wf_mem P_exp.\n        have C_b := valid_procedure_has_block P_exp.\n        have C_local := wf_mem _ C_b.\n        destruct (well_formed_memory_store_counter C_b wf_mem wf_C) as [mem' [Hmem' wf_mem']].\n        assert (Star1 : Star (CS.sem p)\n                             [CState C, stk, mem , Kstop, expr_of_trace C P (comp_subtrace C t), arg] E0\n                             [CState C, stk, mem', Kstop, expr_of_event C P e, arg]).\n        { unfold expr_of_trace. rewrite Et comp_subtrace_app. simpl.\n          rewrite <- wf_C, Nat.eqb_refl, map_app. simpl.\n          assert (H := @switch_spec p C  stk mem\n                                    (map (expr_of_event C P) (comp_subtrace C prefix))\n                                    (expr_of_event C P e)\n                                    (map (expr_of_event C P) (comp_subtrace C suffix))\n                                    E_exit arg).\n          rewrite map_length in H. specialize (H C_local).\n          destruct H as [mem'' [Hmem'' Hstar]].\n          enough (H : mem'' = mem') by (subst mem''; easy).\n          rewrite -> counter_value_snoc, <- wf_C, Nat.eqb_refl in Hmem'.\n          rewrite <- Nat.add_1_r, Nat2Z.inj_add in Hmem''. simpl in Hmem''.\n          unfold counter_value in *.\n          unfold Memory.store in *. simpl in *.\n          rewrite Hmem' in Hmem''.\n          congruence. }\n        assert (Star2 : exists s' cs',\n                   Star (CS.sem p) [CState C, stk, mem', Kstop, expr_of_event C P e, arg] [:: e] cs' /\\\n                   well_formed_state s' (prefix ++ [e]) suffix cs').\n        {\n          clear Star1 wf_mem C_local mem Hmem'. revert mem' wf_mem'. intros mem wf_mem.\n          destruct e as [C_ P' new_arg C'|C_ ret_val C'];\n          simpl in wf_C, wf_e, wb_suffix; subst C_.\n          - case/andP: wf_e => C_ne_C' /imported_procedure_iff Himport.\n            exists (StackState C' (C :: callers)).\n            have C'_b := valid_procedure_has_block (or_intror (closed_intf Himport)).\n            exists [CState C', CS.Frame C arg (Kseq (E_call C P (E_val (Int 0))) Kstop) :: stk, mem,\n                    Kstop, procedure_of_trace C' P' t, Int new_arg].\n            split.\n            + take_step. take_step.\n              apply star_one. simpl.\n              apply CS.eval_kstep_sound. simpl.\n              rewrite (negbTE C_ne_C').\n              rewrite -> imported_procedure_iff in Himport. rewrite Himport.\n              rewrite <- imported_procedure_iff in Himport.\n              by rewrite (find_procedures_of_trace_exp t (closed_intf Himport)).\n            + econstructor; trivial.\n              { destruct wf_stk as (top & bot & ? & Htop & Hbot). subst stk.\n                eexists []; eexists; simpl; split; eauto.\n                split; trivial.\n                eexists arg, P, top, bot.\n                by do 3 (split; trivial). }\n              right. by apply: (closed_intf Himport).\n          - move: wf_e=> /eqP C_ne_C'.\n            destruct callers as [|C'_ callers]; try easy.\n            case/andP: wb_suffix=> [/eqP HC' wb_suffix].\n            subst C'_. simpl. exists (StackState C' callers).\n            destruct wf_stk as (top & bot & ? & Htop & Hbot). subst stk. simpl in Htop, Hbot.\n            revert mem wf_mem arg.\n            induction top as [|[C_ saved k_] top IHtop].\n            + clear Htop. rename bot into bot'.\n              destruct Hbot as (saved & P' & top & bot & ? & P'_exp & Htop & Hbot).\n              subst bot'. simpl.\n              have C'_b := valid_procedure_has_block P'_exp.\n              intros mem wf_mem.\n              exists [CState C', CS.Frame C' saved Kstop :: top ++ bot, mem, Kstop, procedure_of_trace C' P' t, Int 0].\n              split.\n              * eapply star_step.\n                -- now eapply CS.KS_ExternalReturn; eauto.\n                -- take_step. take_step; eauto.\n                   apply star_one. apply CS.eval_kstep_sound.\n                   by rewrite /= eqxx (find_procedures_of_trace t P'_exp).\n                -- now rewrite E0_right.\n              * econstructor; trivial.\n                exists (CS.Frame C' saved Kstop :: top), bot. simpl. eauto.\n            + intros mem wf_mem arg.\n              simpl in Htop. destruct Htop as [[? ?] Htop]. subst C_ k_.\n              specialize (IHtop Htop).\n              specialize (IHtop _ wf_mem saved). destruct IHtop as [cs' [StarRet wf_cs']].\n              exists cs'. split; trivial.\n              eapply star_step; try eassumption.\n              * by apply/CS.eval_kstep_sound; rewrite /= eqxx.\n              * reflexivity. }\n        destruct Star2 as (s' & cs' & Star2 & wf_cs').\n        specialize (IH s' (prefix ++ [e]) cs'). rewrite <- app_assoc in IH.\n        specialize (IH Et wf_cs'). destruct IH as [cs'' Star3 final].\n        exists cs''; trivial.\n        eapply (star_trans Star1); simpl; eauto.\n        now eapply (star_trans Star2); simpl; eauto.\n    Qed.\n\n    Lemma definability :\n      well_formed_trace intf t ->\n      program_behaves (CS.sem p) (Terminates t).\n    Proof.\n      move=> wf_t; eapply program_runs=> /=; try reflexivity.\n      pose cs := CS.initial_machine_state p.\n      suffices H : well_formed_state (StackState Component.main [::]) [::] t cs.\n        have [cs' run_cs final_cs'] := @definability_gen _ [::] t _ erefl H.\n        by econstructor; eauto.\n      case/andP: wf_t => wb_t wf_t_events.\n      rewrite /cs /CS.initial_machine_state /prog_main /= find_procedures_of_trace_main //.\n      econstructor; eauto; last by left; eauto.\n        exists [::], [::]. by do ![split; trivial].\n      intros C.\n      unfold component_buffer, Memory.load.\n      simpl. repeat (rewrite mapmE; simpl); rewrite mem_domm.\n      case HCint: (intf C) => [Cint|] //=.\n      by rewrite ComponentMemory.load_prealloc /=.\n    Qed.\n\nEnd WithTrace.\nEnd Definability.\n\nRequire Import Intermediate.CS.\nRequire Import Intermediate.Machine.\nRequire Import S2I.Definitions.\n\n(* FG : Put back some sanity checks ? some are present but commented in the premise and the move => *)\nLemma matching_mains_backtranslated_program p c intf back m:\n  Intermediate.well_formed_program p ->\n  Intermediate.well_formed_program c ->\n  (* intf = unionm (Intermediate.prog_interface p) (Intermediate.prog_interface c) -> *)\n  back = program_of_trace intf m ->\n  intf Component.main ->\n  (* well_formed_trace intf m -> *)\n  matching_mains (program_unlink (domm (Intermediate.prog_interface p)) back) p.\nProof.\n  move => wf_p wf_c (* intf' *) Hback intf_main (* wf_back *).\n  unfold matching_mains.\n  split.\n  - (* <-, no main in intermediate implies no main in source bactkanslated *)\n    unfold prog_main, program_unlink. simpl.\n    rewrite find_procedure_filter_comp.\n    move => Hinterm.\n    destruct (Component.main \\in domm (Intermediate.prog_interface p)) eqn:Hcase.\n    + inversion wf_p as [_ _ _ _ _ _ Hmain_component].\n      pose proof (proj1 (Intermediate.wfprog_main_component wf_p) Hcase) as Hmainp.\n      done.\n    + rewrite Hcase in Hinterm. done.\n  - (* -> *) (* maybe can be done with more finesse *)\n    unfold prog_main. unfold program_unlink. rewrite Hback. simpl. rewrite find_procedure_filter_comp.\n    destruct (Component.main \\in domm (Intermediate.prog_interface p)) eqn:Hmain_comp ; rewrite Hmain_comp.\n    + intros Hprog_main.\n      rewrite find_procedures_of_trace_main. done.\n      assumption.\n    + intros Hcontra.\n      apply (Intermediate.wfprog_main_component wf_p) in Hcontra.\n      rewrite Hmain_comp in Hcontra. done.\nQed.\n\n(* Definability *)\n\n(* RB: Relocate? As the S2I require above seems to indicate, this is not where\n   this result belongs. *)\nLemma 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 (I.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    matching_mains p' p /\\\n    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 (S.CS.sem (Source.program_link p' c')) m.\nProof.\n  move=> p c b m wf_p wf_c Hlinkable Hclosed Hbeh Hpre Hnot_wrong.\n  pose intf := unionm (Intermediate.prog_interface p) (Intermediate.prog_interface c).\n  have Hclosed_intf : closed_interface intf by case: Hclosed.\n  have intf_main : intf Component.main.\n    case: Hclosed => [? [main_procs [? [/= e ?]]]].\n    rewrite /intf -mem_domm domm_union.\n    do 2![rewrite Intermediate.wfprog_defined_procedures //].\n    by rewrite -domm_union mem_domm e.\n  set m' := finpref_trace m.\n  have {Hbeh} [cs [cs' [Hcs Hstar]]] :\n      exists cs cs',\n        I.CS.initial_state (Intermediate.program_link p c) cs /\\\n        Star (I.CS.sem (Intermediate.program_link p c)) cs m' cs'.\n    case: b / Hbeh Hpre {Hnot_wrong}.\n    - rewrite {}/m' => cs beh Hcs Hbeh Hpre.\n      case: m Hpre=> [m|m|m] /= Hpre.\n      + case: beh / Hbeh Hpre=> //= t cs' Hstar Hfinal -> {m}.\n        by exists cs, cs'; split.\n      + case: beh / Hbeh Hpre=> //= t cs' Hstar Hfinal Ht -> {m}.\n        by exists cs, cs'; split.\n      + destruct Hpre as [beh' ?]; subst beh.\n        have [cs' [Hstar Hbehaves]] := state_behaves_app_inv (I.CS.singleton_traces _) m beh' Hbeh.\n        exists cs, cs'; split; assumption.\n    - move=> _ Hpre; rewrite {}/m'.\n      have {Hpre m} -> : finpref_trace m = E0.\n        case: m Hpre => //= m [[t|t|t|t] //=].\n        by case: m.\n      do 2![exists (I.CS.initial_machine_state (Intermediate.program_link p c))].\n      split; try reflexivity; exact: star_refl.\n  -\n  have wf_events : all (well_formed_event intf) m'.\n    by apply: CS.intermediate_well_formed_events Hstar.\n  have {cs cs' Hcs Hstar} wf_m : well_formed_trace intf m'.\n    have [mainP [HmainP _]] := Intermediate.cprog_main_existence Hclosed.\n    have wf_p_c := Intermediate.linking_well_formedness wf_p wf_c Hlinkable.\n    exact: CS.intermediate_well_formed_trace Hstar Hcs HmainP wf_p_c.\n  have := definability Hclosed_intf intf_main wf_m.\n  set back := (program_of_trace intf m') => Hback.\n  exists (program_unlink (domm (Intermediate.prog_interface p)) back).\n  exists (program_unlink (domm (Intermediate.prog_interface c)) back).\n  split=> /=.\n    rewrite -[RHS](unionmK (Intermediate.prog_interface p) (Intermediate.prog_interface c)).\n    by apply/eq_filterm=> ??; rewrite mem_domm.\n  split.\n    rewrite /intf unionmC; last by case: Hlinkable.\n    rewrite -[RHS](unionmK (Intermediate.prog_interface c) (Intermediate.prog_interface p)).\n    by apply/eq_filterm=> ??; rewrite mem_domm.\n  have wf_back : well_formed_program back by exact: well_formed_events_well_formed_program.\n  have Hback' : back = program_of_trace intf m' by [].\n  split; first exact: matching_mains_backtranslated_program wf_p wf_c Hback' intf_main.\n  split; first exact: matching_mains_backtranslated_program wf_c wf_p Hback' intf_main.\n  clear Hback'.\n  split; first exact: well_formed_program_unlink.\n  split; first exact: well_formed_program_unlink.\n  rewrite program_unlinkK //; split; first exact: closed_program_of_trace.\n  exists (Terminates m').\n  split=> // {wf_events back Hback wf_back wf_m}.\n  rewrite {}/m'; case: m {Hpre} Hnot_wrong=> //= t _.\n  by exists (Terminates nil); rewrite /= E0_right.\nQed.\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/Source/Definability.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2606798451832829}}
{"text": "From Velus Require Import NLustre.\nFrom Velus Require Import Stc.\n\nFrom Velus Require Import NLustreToStc.Translation.\n\nFrom Velus Require Import VelusMemory.\nFrom Velus Require Import Common.\nFrom Velus Require Import CoindToIndexed.\n\nFrom Coq Require Import List.\nImport List.ListNotations.\nFrom Coq Require Import Permutation.\n\nOpen Scope nat.\nOpen Scope list.\n\nModule Type NL2STCCLOCKING\n       (Import Ids   : IDS)\n       (Import Op    : OPERATORS)\n       (Import OpAux : OPERATORS_AUX   Op)\n       (Import CStr  : COINDSTREAMS    Op OpAux)\n       (Import IStr  : INDEXEDSTREAMS  Op OpAux)\n       (Import CIStr : COINDTOINDEXED  Op OpAux CStr IStr)\n       (Import CE    : COREEXPR    Ids Op OpAux      IStr)\n       (Import NL    : NLUSTRE     Ids Op OpAux CStr IStr CIStr CE)\n       (Import Stc   : STC         Ids Op OpAux      IStr       CE)\n       (Import Trans : TRANSLATION Ids Op                 CE.Syn NL.Syn Stc.Syn NL.Mem).\n\n  Lemma translate_eqn_wc:\n    forall G vars eq,\n      wc_env vars ->\n      NL.Clo.wc_equation G vars eq ->\n      Forall (wc_trconstr (translate G) vars) (translate_eqn eq).\n  Proof.\n    inversion_clear 2 as [|??????? Find Ins Outs|];\n      simpl; auto using Forall_cons.\n    apply find_node_translate in Find as (?&?&?&?); subst.\n    cases.\n    - constructor.\n      + do 2 (constructor; auto).\n        eapply wc_env_var; eauto.\n      + do 2 (econstructor; eauto).\n    - do 2 (econstructor; eauto).\n  Qed.\n\n  Lemma gather_eqs_n_vars_wc:\n    forall n G,\n      Forall (NL.Clo.wc_equation G (idck (n_in n ++ n_vars n ++ n_out n))) (n_eqs n) ->\n      Permutation (idck (fst (gather_eqs (n_eqs n))))\n                  (idck\n                     (fst\n                        (partition\n                           (fun x : positive * (type * clock) =>\n                              PS.mem (fst x) (ps_from_list (map fst (fst (gather_eqs (n_eqs n))))))\n                           (n_vars n)))).\n  Proof.\n    intros * WC.\n    rewrite fst_partition_filter.\n    apply NoDup_Permutation.\n    - apply NoDupMembers_NoDup, NoDupMembers_idck, fst_NoDupMembers.\n      rewrite fst_fst_gather_eqs_var_defined.\n      pose proof (NoDup_var_defined_n_eqs n) as Hnodup;\n        rewrite <-is_filtered_vars_defined in Hnodup.\n      rewrite Permutation_app_comm in Hnodup; apply NoDup_app_weaken in Hnodup.\n      rewrite Permutation_app_comm in Hnodup; apply NoDup_app_weaken in Hnodup.\n      auto.\n    - apply NoDupMembers_NoDup, fst_NoDupMembers.\n      rewrite map_fst_idck, filter_mem_fst.\n      apply nodup_filter.\n      pose proof (n.(n_nodup)) as Hnodup.\n      apply NoDupMembers_app_r, NoDupMembers_app_l in Hnodup.\n      now apply fst_NoDupMembers.\n    - intros (x, ck).\n      setoid_rewrite ps_from_list_gather_eqs_memories.\n      assert (forall x, In x (vars_defined (filter is_fby (n_eqs n))) ->\n                   InMembers x (n_vars n)) as Spec\n          by (intro; rewrite <-fst_partition_memories_var_defined, fst_partition_filter,\n                     filter_mem_fst, filter_In, fst_InMembers; intuition).\n      pose proof (filter_fst_idck (n_vars n)\n                                  (fun x => PS.mem x (Mem.memories (n_eqs n)))) as E;\n        setoid_rewrite E; clear E.\n      setoid_rewrite filter_In.\n      setoid_rewrite <-PSE.MP.Dec.F.mem_iff.\n      unfold Mem.memories, gather_eqs in *.\n      generalize (@nil (ident * ident)).\n      induction (n_eqs n) as [|[]]; inversion_clear WC as [|?? WCeq]; simpl; intros; auto.\n      + split; try contradiction.\n        setoid_rewrite PSE.MP.Dec.F.empty_iff; intuition.\n      + cases.\n      + inversion_clear WCeq as [| |???? Hinc].\n        rewrite In_fold_left_memory_eq, PSE.MP.Dec.F.add_iff, PSE.MP.Dec.F.empty_iff.\n        split.\n        *{ intros * Hin.\n           unfold idck in Hin.\n           apply in_map_iff in Hin as ((x', (c', ck')) & E & Hin); simpl in *; inv E.\n           apply In_fst_fold_left_gather_eq in Hin as [Hin|Hin].\n           - inversion_clear Hin as [E|]; try contradiction; inv E.\n             intuition.\n             assert (InMembers x (n_vars n)) by auto.\n             pose proof (n_nodup n) as Hnodup.\n             rewrite fst_NoDupMembers, 2 map_app, NoDup_swap, <- 2 map_app, <-fst_NoDupMembers in Hnodup.\n             eapply NoDupMembers_app_InMembers, NotInMembers_app in Hnodup as (? & ?); eauto.\n             rewrite 2 idck_app, 2 in_app in Hinc; destruct Hinc as [Hinc|[|Hinc]]; auto;\n               apply In_InMembers in Hinc; rewrite InMembers_idck in Hinc; contradiction.\n           - assert (In (x, ck) (idck (fst (fold_left gather_eq l ([], l0)))))\n               as Hin' by (apply in_map_iff; eexists; intuition; eauto; simpl; auto).\n             apply IHl in Hin'; intuition.\n         }\n         *{ intros * (Hin & [Mem|Mem]).\n            - assert (In (x, ck) (idck (fst (fold_left gather_eq l ([], l0))))) as Hin'\n                  by (apply IHl; auto; intros * Hin';\n                      apply Spec; simpl; auto).\n              unfold idck in Hin'; apply in_map_iff in Hin' as ((x', (c', ck')) & E & Hin'); simpl in *; inv E.\n              apply in_map_iff; exists (x, (c', ck)); simpl.\n              rewrite In_fst_fold_left_gather_eq; intuition.\n            - destruct Mem as [E|]; try contradiction; inv E.\n              apply in_map_iff; exists (x, (c0, c)); simpl.\n              rewrite In_fst_fold_left_gather_eq; intuition.\n              f_equal.\n              assert (In (x, ck) (idck (n_in n ++ n_vars n ++ n_out n)))\n                by (rewrite 2 idck_app, 2 in_app; auto).\n              eapply NoDupMembers_det; eauto.\n              apply NoDupMembers_idck, n_nodup.\n          }\n  Qed.\n\n  Lemma wc_trconstrs_permutation:\n    forall P vars vars' eqs,\n      Permutation vars vars' ->\n      Forall (wc_trconstr P vars) eqs ->\n      Forall (wc_trconstr P vars') eqs.\n  Proof.\n    intros * E WC.\n    eapply Forall_impl with (2 := WC); eauto.\n    setoid_rewrite E; auto.\n  Qed.\n\n  Lemma translate_node_wc:\n    forall G n,\n      wc_node G n ->\n      wc_system (translate G) (translate_node n).\n  Proof.\n    inversion_clear 1 as [? (?& Env & Heqs)].\n    constructor; simpl; auto.\n    assert (Permutation (idck\n                           (n_in n ++\n                                 snd\n                                 (partition\n                                    (fun x : positive * (type * clock) =>\n                                       PS.mem (fst x) (ps_from_list (map fst (fst (gather_eqs (n_eqs n))))))\n                                    (n_vars n)) ++ n_out n) ++ idck (fst (gather_eqs (n_eqs n))))\n                        (idck (n_in n ++ n_vars n ++ n_out n))) as E.\n    { repeat rewrite idck_app.\n      rewrite Permutation_app_comm, Permutation_swap, gather_eqs_n_vars_wc,\n      <-2 idck_app, app_assoc, <-permutation_partition, idck_app; eauto.\n    }\n    intuition.\n    - now rewrite E.\n    - apply Permutation_sym in E.\n      eapply wc_trconstrs_permutation with (1 := E).\n      unfold translate_eqns.\n      clear - Heqs Env; induction (n_eqs n); simpl; inv Heqs; auto.\n      apply Forall_app; split; auto.\n      eapply translate_eqn_wc; eauto.\n  Qed.\n\n  Theorem translate_wc:\n    forall G,\n      wc_global G ->\n      wc_program (translate G).\n  Proof.\n    intros * WC.\n    induction G; simpl; inv WC; auto.\n    constructor; auto.\n    eapply translate_node_wc; eauto.\n  Qed.\n\nEnd NL2STCCLOCKING.\n\nModule NL2StcClockingFun\n       (Ids   : IDS)\n       (Op    : OPERATORS)\n       (OpAux : OPERATORS_AUX   Op)\n       (CStr  : COINDSTREAMS    Op OpAux)\n       (IStr  : INDEXEDSTREAMS  Op OpAux)\n       (CIStr : COINDTOINDEXED  Op OpAux CStr IStr)\n       (CE    : COREEXPR    Ids Op OpAux      IStr)\n       (NL    : NLUSTRE     Ids Op OpAux CStr IStr CIStr CE)\n       (Stc   : STC         Ids Op OpAux      IStr       CE)\n       (Trans : TRANSLATION Ids Op                 CE.Syn NL.Syn Stc.Syn NL.Mem)\n<: NL2STCCLOCKING Ids Op OpAux CStr IStr CIStr CE NL Stc Trans.\n  Include NL2STCCLOCKING Ids Op OpAux CStr IStr CIStr CE NL Stc Trans.\nEnd NL2StcClockingFun.\n", "meta": {"author": "INRIA", "repo": "velus", "sha": "116a88bc71f3608ff43ed967895743e8b9a340e0", "save_path": "github-repos/coq/INRIA-velus", "path": "github-repos/coq/INRIA-velus/velus-116a88bc71f3608ff43ed967895743e8b9a340e0/src/NLustreToStc/NL2StcClocking.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.585101154203231, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.26067984518328285}}
{"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 LoadU_failure (regs: Reg) (rdst rsrc: RegName) (offs: Z + RegName) (mem : Mem):=\n  | LoadU_fail_const z:\n      regs !! rsrc = Some (inl z) ->\n      LoadU_failure regs rdst rsrc offs mem\n  | LoadU_fail_perm p g b e a:\n      regs !! rsrc = Some (inr ((p, g), b, e, a)) ->\n      isU p = false ->\n      LoadU_failure regs rdst rsrc offs mem\n  | LoadU_fail_offs_arg p g b e a:\n      regs !! rsrc = Some (inr ((p, g), b, e, a)) ->\n      isU p = true ->\n      z_of_argument regs offs = None ->\n      LoadU_failure regs rdst rsrc offs mem\n  | LoadU_fail_verify_access p g b e a noffs:\n      regs !! rsrc = Some (inr ((p, g), b, e, a)) ->\n      isU p = true ->\n      z_of_argument regs offs = Some noffs ->\n      verify_access (LoadU_access b e a noffs) = None ->\n      LoadU_failure regs rdst rsrc offs mem\n  | LoadU_fail_incrementPC p g b e a noffs a' w:\n      regs !! rsrc = Some (inr ((p, g), b, e, a)) ->\n      isU p = true ->\n      z_of_argument regs offs = Some noffs ->\n      verify_access (LoadU_access b e a noffs) = Some a' ->\n      mem !! a' = Some w →\n      incrementPC (<[ rdst := w ]> regs) = None ->\n      LoadU_failure regs rdst rsrc offs mem.\n\n  Inductive LoadU_spec\n    (regs: Reg) (rdst rsrc: RegName) (offs: Z + RegName)\n    (regs': Reg) (mem : Mem) : cap_lang.val → Prop\n  :=\n  | LoadU_spec_success p g b e a a' noffs w :\n      regs !! rsrc = Some (inr ((p, g), b, e, a)) ->\n      isU p = true ->\n      z_of_argument regs offs = Some noffs ->\n      verify_access (LoadU_access b e a noffs) = Some a' ->\n      mem !! a' = Some w →\n      incrementPC (<[ rdst := w ]> regs) = Some regs' ->\n      LoadU_spec regs rdst rsrc offs regs' mem NextIV\n  | LoadU_spec_failure :\n    LoadU_failure regs rdst rsrc offs mem ->\n    LoadU_spec regs rdst rsrc offs regs' mem FailedV.\n  \n  Lemma wp_loadU Ep\n     pc_p pc_g pc_b pc_e pc_a\n     rdst rsrc offs w mem regs :\n   decodeInstrW w = LoadU rdst rsrc offs →\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 (LoadU rdst rsrc offs) ⊆ dom _ regs →\n   mem !! pc_a = Some w →\n   match regs !! rsrc with\n   | None => True\n   | Some (inl _) => True\n   | Some (inr (p, g, b, e, a)) =>\n     if isU p then\n       match z_of_argument regs offs with\n       | None => True\n       | Some zoffs => match verify_access (LoadU_access b e a zoffs) with\n                      | None => True\n                      | Some a' => match mem !! a' with\n                                  | None => False\n                                  | Some w => True\n                                  end\n                      end\n       end\n     else True\n   end ->\n\n   {{{ (▷ [∗ map] a↦w ∈ mem, a ↦ₐ w) ∗\n       ▷ [∗ map] k↦y ∈ regs, k ↦ᵣ y }}}\n     Instr Executable @ Ep\n   {{{ regs' retv, RET retv;\n       ⌜ LoadU_spec regs rdst rsrc offs regs' mem retv⌝ ∗\n         ([∗ map] a↦w ∈ mem, a ↦ₐ w) ∗\n         [∗ map] k↦y ∈ regs', k ↦ᵣ y }}}.\n   Proof.\n     iIntros (Hinstr Hvpc HPC Dregs Hmem_pc HaLoad φ) \"(>Hmem & >Hmap) Hφ\".\n     iApply wp_lift_atomic_head_step_no_fork; auto.\n     iIntros (σ1 l1 l2 n) \"[Hr Hm] /=\". destruct σ1 as [r m]; simpl.\n     iDestruct (gen_heap_valid_inclSepM with \"Hr Hmap\") as %Hregs.\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 rsrc) as [rsrcv [Hrsrc' Hrsrc]]. by set_solver+.\n     feed destruct (Hri rdst) as [rdstv [Hrdst' _]]. by set_solver+.\n     pose proof (regs_lookup_eq _ _ _ Hrsrc') as Hrsrc''.\n     pose proof (regs_lookup_eq _ _ _ Hrdst') as Hrdst''.\n     (* Derive the PC in memory *)\n     iDestruct (gen_mem_valid_inSepM pc_a _ _ _ mem _ m with \"Hm Hmem\") as %Hma; eauto.\n\n     iModIntro.\n     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     option_locate_mr m r.\n     rewrite /exec in Hstep. rewrite Hrrsrc in Hstep.\n\n     destruct rsrcv as [| [[[[p g] b] e] a] ].\n     { inv Hstep. iFailWP \"Hφ\" LoadU_fail_const. }\n\n     destruct (isU p) eqn:HisU; cycle 1.\n     { inv Hstep. iFailWP \"Hφ\" LoadU_fail_perm. }\n\n     assert (Hzofargeq: z_of_argument r offs = z_of_argument regs offs).\n     { rewrite /z_of_argument; destruct offs; auto.\n       feed destruct (Hri r0) as [? [?]]. by set_solver+.\n       rewrite H2 H3; auto. }\n     rewrite Hzofargeq in Hstep.\n\n     destruct (z_of_argument regs offs) as [zoffs|] eqn:Hoffs; cycle 1.\n     { inv Hstep. iFailWP \"Hφ\" LoadU_fail_offs_arg. }\n\n     destruct (verify_access (LoadU_access b e a zoffs)) as [a'|] eqn:Hverify; cycle 1.\n     { inv Hstep. iFailWP \"Hφ\" LoadU_fail_verify_access. }\n     simpl in Hstep. rewrite Hrsrc' HisU Hverify in HaLoad.\n     rewrite /MemLocate in Hstep. destruct (mem !! a') as [wa|] eqn:Ha'; cycle 1.\n     { inv HaLoad. }\n     iDestruct (gen_mem_valid_inSepM a' _ _ _ mem _ m with \"Hm Hmem\") as %Hma'; eauto.\n     rewrite Hma' in Hstep. destruct (incrementPC (<[rdst:=wa]> regs)) eqn:Hincr; cycle 1.\n     { assert _ as Hincr' by (eapply (incrementPC_overflow_mono (<[rdst:=wa]> regs) (<[rdst:=wa]> r) _ _ _)).\n       rewrite incrementPC_fail_updatePC in Hstep; eauto.\n       inv Hstep. simpl.\n       iMod ((gen_heap_update_inSepM _ _ rdst) with \"Hr Hmap\") as \"[Hr Hmap]\"; eauto.\n       iFailWP \"Hφ\" LoadU_fail_incrementPC. }\n\n     destruct (incrementPC_success_updatePC _ m _ Hincr) 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     iMod ((gen_heap_update_inSepM _ _ rdst) 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.\n     iPureIntro. econstructor; eauto.\n     Unshelve. all: eauto.\n     { destruct (reg_eq_dec PC rdst).\n       - subst rdst. rewrite lookup_insert. eauto.\n       - rewrite lookup_insert_ne; eauto. }\n     { eapply insert_mono; eauto. }\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_LoadU.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.42632159254749025, "lm_q1q2_score": 0.26064533650958965}}
{"text": "(** VCFloat: A Unified Coq Framework for Verifying C Programs with\n Floating-Point Computations. Application to SAR Backprojection.\n \n Version 1.0 (2015-12-04)\n \n Copyright (C) 2015 Reservoir Labs Inc.\n All rights reserved.\n \n This file, which is part of VCFloat, is free software. You can\n redistribute it and/or modify it under the terms of the GNU General\n Public License as published by the Free Software Foundation, either\n version 3 of the License (GNU GPL v3), or (at your option) any later\n version. A verbatim copy of the 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 VCFloat 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 VCFloat in your work, please consider\n 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 VCFloat requires third-party libraries listed in ACKS along with their\n copyright information.\n \n VCFloat depends on third-party libraries listed in ACKS along with\n their copyright and licensing information.\n*)\n(**\nAuthor: Tahina Ramananandro <ramananandro@reservoir.com>\n\nVCFloat: core and annotated languages for floating-point operations.\n*)\n\nRequire Import Interval.Tactic.\nFrom vcfloat Require Export RAux.\nFrom Flocq Require Import Binary Bits Core.\nFrom vcfloat Require Import IEEE754_extra. (* lib.Floats. *)\nRequire compcert.lib.Maps.  \nRequire Import JMeq.\nRequire Coq.MSets.MSetAVL.\nRequire vcfloat.Fprop_absolute.\nRequire Import vcfloat.Float_lemmas.\nSet Bullet Behavior \"Strict Subproofs\".\nGlobal Unset Asymmetric Patterns.\n\nRequire Export vcfloat.FPCore vcfloat.FPLang.\nRequire Import vcfloat.klist.\nImport Bool.\n\nImport Coq.Lists.List ListNotations.\n\nLocal Open Scope R_scope.\n\nModule MSET := MSetAVL.Make(Pos).\n\nDefinition mget {U} (m: Maps.PMap.t U) t := Maps.PMap.get t m.\nDefinition mset {U} m t (u: U) := Maps.PMap.set t u m.\nDefinition mempty {U} := @Maps.PMap.init U.\nLemma mget_set {U}: forall m t t' (u: U),\n                mget (mset m t u) t' = if Pos.eq_dec t' t then u else mget m t'.\nProof. intros.\n   unfold mget, mset.\n    rewrite Maps.PMap.gsspec.\n    destruct (Coqlib.peq t' t); destruct (Pos.eq_dec t' t); congruence.\nQed.\n\nLemma mget_empty {U}: forall t (u: U), mget (mempty u) t = u.\nProof. intros. apply Maps.PMap.gi. Qed.\n\nLemma finite_errors_ex {U}  (t: U) n:\n  forall errors,\n  exists m,\n    forall i,\n      mget m i = if Pos.ltb i n then errors i else t.\nProof.\n  remember (Nat.pred (Pos.to_nat n)) as k.\n revert n Heqk.\n induction k; intros.\n - exists (mempty t).\n    intros.\n    rewrite mget_empty.\n    assert (n=1%positive) by lia. subst.\n    destruct (Pos.ltb_spec i 1); auto; lia.\n -\n  specialize (IHk (Pos.pred n) ltac:(lia) errors).\n  destruct IHk.\n  exists (mset x (Pos.pred n) (errors (Pos.pred n))).\n  intros.\n  rewrite mget_set.\n  rewrite H.\n  destruct (Pos.eq_dec _ _). subst.\n  destruct (Pos.ltb_spec (Pos.pred n) n); try lia. auto.\n  destruct (Pos.ltb_spec i n);\n  destruct (Pos.ltb_spec i (Pos.pred n)); auto; lia.\nQed.  \n\nSection WITH_NAN.\nContext {NANS: Nans}.\n\nInductive ratom: Type :=\n| RConst (_: Defs.float Zaux.radix2)\n| RVar (ty: type) (_: FPLang.V)\n| RError (_: positive)\n.\n\nUnset Elimination Schemes.\nInductive rexpr: Type :=\n  | RAtom (_: ratom)\n  | RUnop (o: Tree.unary_op) (e: rexpr)\n  | RBinop (o: Tree.binary_op) (e1 e2: rexpr)\n  | RFunc ty (ff: floatfunc_package ty) (args: klist (fun _ => rexpr) (ff_args ff)) \n.\n\nSet Elimination Schemes.\nLemma rexpr_ind:\n  forall P : rexpr -> Prop,\n  (forall (r : ratom), P (RAtom r)) ->\n  (forall o e1, P e1 -> P (RUnop o e1)) ->\n  (forall o e1 e2, P e1 -> P e2 -> P (RBinop o e1 e2)) ->\n  (forall (ty : type) (ff : floatfunc_package ty)\n    (args : klist (fun _ => rexpr) (ff_args ff))\n      (IH: Kforall (fun ty => P) args),\n      P  (RFunc ty ff args)) ->\n  forall (e : rexpr), P e.\nProof.\nintros.\nrefine (\n(fix F (e : rexpr) {struct e} : P e :=\n  match e as e0 return (P e0) with\n  | RAtom a => H a\n  | RUnop o e1 => H0 o e1 (F e1)\n  | RBinop b e1 e2 => H1 b e1 e2 (F e1) (F e2)\n  | RFunc ty ff args => _\n    end) e).\napply H2.\nclear - F ff.\nset (tys := ff_args ff) in *. clearbody tys.\ninduction args.\nconstructor.\nconstructor.\napply F.\napply IHargs.\nQed.\n\nFixpoint reval (e: rexpr) (env: forall ty, FPLang.V -> ftype ty) (eenv: positive -> R): R :=\n  match e with\n    | RAtom (RConst q) => F2R _ q\n    | RAtom (RVar ty n) => B2R _ _ (env ty n)\n    | RAtom (RError n) => eenv n\n    | RUnop o e => Prog.unary Prog.real_operations o (reval e env eenv)\n    | RBinop o e1 e2 => Prog.binary Prog.real_operations o (reval e1 env eenv) (reval e2 env eenv)\n    | RFunc ty ff args => \n    let fix reval_klist {tys: list type} (l': klist (fun _ => rexpr) tys) (f: function_type (map RR tys) R) {struct l'}: R :=\n          match l' in (klist _ l)  return (function_type (map RR l) R -> R)\n          with\n          | Knil => fun f0 => f0\n          | Kcons h tl => fun f0 => reval_klist tl (f0 (reval h env eenv))\n          end f \n          in reval_klist args (ff_realfunc ff)\n  end.\n\nDefinition reval_klist {T} (env: forall ty, FPLang.V -> ftype ty) (eenv: positive -> R) :=\n fix reval_klist {tys: list type} (l': klist (fun _ => rexpr) tys) (f: function_type (map RR tys) T) {struct l'}: T :=\n          match l' in (klist _ l)  return (function_type (map RR l) T -> T)\n          with\n          | Knil => fun f0 => f0\n          | Kcons h tl => fun f0 => reval_klist tl (f0 (reval h env eenv))\n          end f. \n\nFixpoint max_error_var (e: rexpr): positive :=\n  match e with\n    | RAtom (RError n) =>Pos.succ n\n    | RUnop _ e => max_error_var e\n    | RBinop _ e1 e2 => Pos.max (max_error_var e1) (max_error_var e2)\n    | RFunc ty ff args => \n       let fix max_error_var_klist (tys: list type) (es: klist (fun _ => rexpr) tys) : positive :=\n        match es with\n        | Knil => 1%positive\n        | Kcons h tl => Pos.max (max_error_var h) (max_error_var_klist _ tl)\n       end\n       in max_error_var_klist (ff_args ff) args\n    | _ => 1%positive\n  end.\n\nFixpoint max_error_var_klist (tys: list type) (es: klist (fun _ => rexpr) tys) : positive :=\n        match es with\n        | Knil => 1%positive\n        | Kcons h tl => Pos.max (max_error_var h) (max_error_var_klist _ tl)\n       end.\n\nLemma reval_error_ext eenv1 env eenv2 e:\n  (forall i, (i < max_error_var e)%positive ->\n                 eenv1 i = eenv2 i) ->\n  reval e env eenv1 = reval e env eenv2.\nProof.\n  induction e; simpl;\n try (intros; f_equal; \n     match goal with IH:_ -> ?a |- ?g => unify a g; eapply IH; eauto end;\n     intros; apply H; lia).\n  - destruct r; auto. intros. apply H. lia.\n - intros.\n    change (reval_klist env eenv1  args (ff_realfunc ff) =\n                   reval_klist env eenv2 args (ff_realfunc ff)).\n    fold (max_error_var_klist) in H.\n    destruct ff; simpl in *.\n    rename ff_args into tys.\n    rename ff_realfunc into f.\n    clear - args H IH.\n    revert f H IH.\n    induction args; simpl; intros; auto.\n    apply Kforall_inv in IH. destruct IH.\n    rewrite <- H0.\n    apply IHargs; auto.\n    intros. apply H; lia.\n    intros. apply H; lia.\nQed.\n\nLemma reval_error_klist_ext:\n  forall (eenv1 eenv2  : positive -> R)\n    (env : forall ty : type, FPLang.V -> ftype ty)\n    (tys : list type)\n   (args : klist (fun _ : type => rexpr) tys)\n  (f : function_type (map RR tys) R),\n(forall i : positive,\n (i < max_error_var_klist tys args)%positive -> eenv1 i = eenv2 i) ->\nKforall\n  (fun (_ : type) (e : rexpr) =>\n   (forall i : positive, (i < max_error_var e)%positive -> eenv1 i = eenv2 i) ->\n   reval e env eenv1 = reval e env eenv2) args ->\n  reval_klist env eenv1 args f = reval_klist env eenv2 args f.\nProof.\n    induction args; simpl; intros; auto.\n    apply Kforall_inv in H0. destruct H0.\n    rewrite <- H0.\n    apply IHargs; auto.\n    intros. apply H; lia.\n    intros. apply H; lia.\nQed.\n\nDefinition MSHIFT := Maps.PMap.t  (type * rounding_knowledge').\n\nDefinition error_bound ty_k :=\n  / 2 * Raux.bpow Zaux.radix2\n  match ty_k with\n    | (ty, Unknown') => 0\n    | (ty, Normal') => (- fprec ty + 1)\n    | (ty, Denormal') =>  (3 - femax ty - fprec ty)\n    | (ty, Denormal2') =>   (3 - femax ty - fprec ty)\n  end.\n\nDefinition errors_bounded\n    (shift: MSHIFT) (errors: positive -> R) := \n   forall i, (Rabs (errors i) <= error_bound (mget shift i))%R.\n\nLemma error_bound_nonneg ty_k:\n  0 <= error_bound ty_k.\nProof.\n    unfold error_bound. destruct ty_k.\n    apply Rmult_le_pos; try lra.\n    apply Raux.bpow_ge_0.\nQed.\n\nDefinition make_rounding\n           (si: positive)\n           (shift: MSHIFT)\n           (kn:  rounding_knowledge') (ty: type) (x: rexpr):\n  (rexpr * (positive * MSHIFT))\n  :=\n    match kn with\n      | Unknown' =>\n        let d := si in\n        let es1 := mset shift d (ty, Normal') in\n        let e := Pos.succ d in\n        let es2 := mset es1 e (ty, Denormal') in\n        (\n          RBinop Tree.Add\n                 (RBinop Tree.Mul x\n                         (RBinop Tree.Add (RAtom (RConst fone))\n                                 (RAtom (RError d)))\n                 )\n                 (RAtom (RError e))\n          , (Pos.succ e, es2)\n        )\n\n      | Normal' =>\n        let d := si in\n        let es1 := mset shift d (ty, Normal') in\n        (\n          RBinop Tree.Mul x\n                 (RBinop Tree.Add (RAtom (RConst fone))\n                         (RAtom (RError d))\n                 )\n          , (Pos.succ d, es1)\n        )\n      | Denormal' => \n        let e := si in\n        let es1 := mset shift e (ty, Denormal') in\n        (\n          RBinop Tree.Add x\n                 (RAtom (RError e))\n          , (Pos.succ e, es1)\n        )\n      | Denormal2' => \n        let e := si in\n        let es1 := mset shift e (ty, Denormal2') in\n        (\n          RBinop Tree.Add x\n                 (RAtom (RError e))\n          , (Pos.succ e, es1)\n        )\n    end.\n\nLemma make_rounding_shift_incr\n      si\n      shift\n      kn ty x\n      y si' shift':\n  make_rounding si shift kn ty x = (y, (si', shift')) ->\n  (si <= si')%positive\n.\nProof.\n  unfold make_rounding.\n  destruct kn;\n  inversion 1; subst; auto; lia.\nQed.\n\nDefinition same_upto {T} (si: positive) (s1 s2: positive ->T) :=\n  forall i, (i < si)%positive -> s2 i = s1 i.\n\nLemma make_rounding_shift_unchanged\n      si\n      shift\n      kn ty x\n      y si' shift':\n  make_rounding si shift kn ty x = (y, (si', shift')) ->\n  same_upto si (mget shift) (mget shift').\nProof.\n  unfold make_rounding, same_upto.\n  destruct kn.\n  inversion 1; subst; intros.\n  repeat rewrite mget_set.\n  destruct (Pos.eq_dec i (Pos.succ si)); auto;\n  destruct (Pos.eq_dec i si); auto;\n  try (exfalso; lia).\nall: try (    inversion 1; subst; intros;\n    rewrite mget_set;\n    destruct (Pos.eq_dec i si); auto;\n    exfalso; lia).\nQed.\n\nLemma make_rounding_shift_le\n      si\n      shift\n      kn ty x\n      y si' shift':\n  make_rounding si shift kn ty x = (y, (si', shift')) ->\n    (max_error_var x <= si)%positive ->\n    (max_error_var y <= si')%positive.\nProof.\n  unfold make_rounding.\n  destruct kn;\n  inversion 1; subst; simpl; intros;\n  repeat (apply Pos.max_lub; auto; lia).\nQed.\n\nDefinition rounding_cond ty k x :=\n  match k with\n    | Unknown' => True\n    | Normal' =>\n      Raux.bpow Zaux.radix2 (3 - femax ty - 1) <= Rabs x\n    | Denormal' =>\n      Rabs x < Raux.bpow Zaux.radix2 (3 - femax ty)\n    | Denormal2' => True\n  end.\n\nLemma make_rounding_correct\n      si shift kn ty x y si' shift':\n  make_rounding si shift (round_knowl_denote kn) ty x = (y, (si', shift')) ->\n  (max_error_var x <= si)%positive ->\n  forall errors1, errors_bounded shift errors1 ->\n  forall env,\n    rounding_cond ty (round_knowl_denote kn) (reval x env errors1) ->\n  forall choice,\n  exists errors2,\n    same_upto si errors1 errors2\n    /\\\n    reval y env errors2 =\n    Generic_fmt.round\n      Zaux.radix2\n      (FLT_exp (3 - femax ty - fprec ty) (fprec ty))\n      (Generic_fmt.Znearest choice)\n      (reval x env errors1)\n    /\\\n    errors_bounded shift' errors2\n.  \n\nProof. \nunfold make_rounding, rounding_cond.\nintros.\ndestruct kn as [ [ | ] | ]; unfold round_knowl_denote in H2.\n- (* Normal *)\n  replace (3 - femax ty - 1)%Z with (3 - femax ty - fprec ty + fprec ty - 1)%Z in H2 by ring.\n  generalize (Relative.relative_error_N_FLT_ex _ _ _ (fprec_gt_0 _) choice _ H2).\n  destruct 1 as (eps & Heps & Hround).\n  pose (errors2 i := if Pos.eq_dec i si  then eps else errors1 i).\n  exists errors2.\n  split; [ | split].\n  * intro; unfold errors2; intros; destruct (Pos.eq_dec i si); auto; lia.\n  * inversion H; clear H; subst.\n    simpl reval.\n    rewrite Rmult_1_l.\n    rewrite <- (reval_error_ext errors1).\n   --\n     unfold errors2.\n     destruct (Pos.eq_dec si si); congruence.\n   --  intros; unfold errors2; destruct (Pos.eq_dec i si); auto; exfalso; lia.\n  * inversion H; clear H; subst.\n    simpl reval.\n    intros until i.\n    rewrite mget_set.\n    intros.\n    unfold errors2.\n    destruct (Pos.eq_dec i si); auto.\n - (* Denormal *)\n  replace (3 - femax ty)%Z with (3 - femax ty - fprec ty + fprec ty)%Z in H2 by ring.\n  generalize (Fprop_absolute.absolute_error_N_FLT _ _ (fprec_gt_0 _) _ choice _ H2).\n  destruct 1 as (eps & Heps & Hround).\n  pose (errors2 i := if Pos.eq_dec i si then eps else errors1 i).\n  exists errors2.    \n  split; [ | split].\n  * intro; unfold errors2; intros; destruct (Pos.eq_dec i si); auto; lia.\n  * inversion H; clear H; subst. simpl reval.\n    rewrite <- (reval_error_ext errors1).\n   -- unfold errors2; destruct (Pos.eq_dec si si); congruence.\n   -- intros; unfold errors2; destruct (Pos.eq_dec i si); auto; lia.\n  * inversion H; clear H; subst. simpl reval.\n     intros until i.\n     rewrite mget_set.\n     intros.\n     unfold errors2.\n     destruct (Pos.eq_dec i si); auto.\n-  (* None *)\n generalize (Relative.error_N_FLT Zaux.radix2 (3 - femax ty - fprec ty) (fprec ty) (fprec_gt_0 _)  choice (reval x env errors1)).\n destruct 1 as (eps & eta & Heps & Heta & _ & Hround).\n pose (errors2 i := if Pos.eq_dec i (Pos.succ (si)) then eta\n                          else if Pos.eq_dec i si then eps else  errors1 i).\n exists errors2.\n split; [ | split].\n + intro.\n   unfold errors2.\n   intros; destruct (Pos.eq_dec i (Pos.succ si)); try lia; destruct (Pos.eq_dec i si); try lia; auto.\n + inversion H; clear H; subst.\n    simpl reval.\n    rewrite Rmult_1_l.     \n  rewrite <- (reval_error_ext errors1).\n  *\n    unfold errors2.\n    destruct (Pos.eq_dec si (Pos.succ si)); try (exfalso; lia).\n    destruct (Pos.eq_dec si si); try congruence.\n    destruct (Pos.eq_dec (Pos.succ si) (Pos.succ si)); congruence.\n  *\n   intros.\n   unfold errors2.\n   destruct (Pos.eq_dec i (Pos.succ si)); try lia.\n   destruct (Pos.eq_dec i si); try lia.\n   auto.\n +\n   inversion H; clear H; subst.\n    simpl reval.\n  intros until i.\n  repeat rewrite mget_set.\n  intros.\n  subst errors2.\n specialize (H1 i).\n repeat destruct (Pos.eq_dec _ _); subst; auto; lia.\nQed.\n\nDefinition Rbinop_of_rounded_binop o :=\n  match o with\n    | PLUS => Tree.Add\n    | MULT => Tree.Mul\n    | MINUS => Tree.Sub\n    | DIV => Tree.Div\n  end.\n\nDefinition rnd_of_binop\n           si\n           (shift: MSHIFT)\n           (ty: type)\n           (o: binop) (r1 r2: rexpr)\n  :=\n    match o with\n      | SterbenzMinus => (RBinop Tree.Sub r1 r2, (si, shift))\n      | PlusZero minus zero_left =>\n        ((\n            if zero_left\n            then\n              if minus\n              then RUnop Tree.Neg r2\n              else r2\n            else\n              r1\n          ), (si, shift))       \n      | Rounded2 o' k => \n        make_rounding si shift (round_knowl_denote k) ty                      \n                      (RBinop (Rbinop_of_rounded_binop o') r1 r2)\n    end.\n\nDefinition rnd_of_cast\n           si\n           (shift: MSHIFT)\n           (tyfrom tyto: type)\n           (k: rounding_knowledge')\n           (r: rexpr) :=\n  if type_leb tyfrom tyto\n  then\n    (r, (si, shift))\n  else\n    make_rounding si shift k tyto r\n.\n\nDefinition Runop_of_rounded_unop ty o :=\n  match o with\n    | SQRT => RUnop Tree.Sqrt\n    | InvShift n _ => RBinop Tree.Mul (RAtom (RConst (B2F (B2 ty (- Z.pos n)))))\n  end.\n\nDefinition Runop_of_exact_unop ty o :=\n  match o with\n    | Abs => RUnop Tree.Abs\n    | Opp => RUnop Tree.Neg\n    | Shift n _ => RBinop Tree.Mul (RAtom (RConst (B2F (B2 ty (Z.of_N n)))))\n  end.\n\nDefinition rnd_of_unop\n           si\n           (shift: MSHIFT)\n           (ty: type)\n           (o: unop) (r: rexpr)\n  :=\n    match o with\n      | Rounded1 (InvShift n ltr) (Some Normal) =>\n                  (Runop_of_rounded_unop ty (InvShift n ltr) r, (si, shift))\n      | Rounded1 (InvShift n _) _ =>\n           make_rounding si shift Denormal2' ty\n              ((RBinop Tree.Mul (RAtom (RConst (B2F (B2 ty (- Z.pos n)))))) r)\n      | Rounded1 o k =>\n        make_rounding si shift (round_knowl_denote k) ty\n                      (Runop_of_rounded_unop ty o r)\n      | Exact1 o => (Runop_of_exact_unop ty o r, (si, shift))\n    end. \n\nDefinition rel_error r n d :=\n     RBinop Tree.Mul r \n        (RBinop Tree.Add  (RAtom (RConst fone))\n           (RBinop Tree.Mul (RAtom (RConst (Float radix2 (Z.of_N n) 0))) (RAtom (RError d)))).\n\nDefinition abs_error r n e :=\n     RBinop Tree.Add r (RBinop Tree.Mul (RAtom (RConst (Float radix2 (Z.of_N n) 0))) (RAtom (RError e))).\n\nDefinition rnd_of_func' (si: positive) (shift: MSHIFT) ty (rel abs: N) (r: rexpr) :\n           rexpr * (positive * MSHIFT) :=\n        let d := si in\n        let es1 := mset shift d (ty, Normal') in\n        let e := Pos.succ d in\n        let es2 := mset es1 e (ty, Denormal') in\n        (abs_error (rel_error r rel d) abs e, (Pos.succ e, es2)).\n\nDefinition rnd_of_func (si: positive) (shift: MSHIFT) (ty: type) \n                      ff (r: klist (fun _ => rexpr) (ff_args ff)) :\n          rexpr * (positive * MSHIFT) :=\n  rnd_of_func' si shift ty (ff_rel (ff_ff ff)) (ff_abs (ff_ff ff)) (RFunc ty ff r).\n\nLemma rnd_of_func'_shift_incr\n      si\n      shift\n      ty rel abs x\n      y si' shift':\n  rnd_of_func' si shift ty rel abs x = (y, (si', shift')) ->\n  (si <= si')%positive\n.\nProof.\n  unfold rnd_of_func';\n  inversion 1; subst; auto; lia.\nQed.\n\nLemma rnd_of_func'_shift_unchanged\n      si\n      shift\n      ty rel abs x\n      y si' shift':\n  rnd_of_func' si shift ty rel abs x = (y, (si', shift')) ->\n  same_upto si (mget shift) (mget shift').\nProof.\n  unfold rnd_of_func', same_upto.\n  intros. inversion H; clear H; subst.\n  repeat rewrite mget_set;\n  repeat destruct (Pos.eq_dec _ _); subst; auto; lia.\nQed.\n\nLemma rnd_of_func'_shift_le\n      si\n      shift\n      ty rel abs x\n      y si' shift':\n  rnd_of_func' si shift ty rel abs x = (y, (si', shift')) ->\n    (max_error_var x <= si)%positive ->\n    (max_error_var y <= si')%positive.\nProof.\n  unfold rnd_of_func'.\n  inversion 1; subst; simpl; intros;\n  repeat (apply Pos.max_lub; auto; lia).\nQed.\n\nFixpoint rndval \n         (si: positive)\n         (shift: MSHIFT)\n         (ty: type) (e: expr ty) {struct e} : rexpr * (positive * MSHIFT) :=\n  match e with\n    | Const _ f => (RAtom (RConst (B2F f)), (si, shift))\n    | Var _ i => (RAtom (RVar ty i), (si, shift))\n    | Binop b e1 e2 =>\n      let '(r1, (si1, s1)) := rndval si shift _ e1 in\n      let '(r2, (si2, s2)) := rndval si1 s1 _ e2 in\n      rnd_of_binop si2 s2 ty b r1 r2\n    | Unop b e1 =>\n      let '(r1, (si1, s1)) := rndval si shift _ e1 in\n      rnd_of_unop si1 s1 ty b r1\n    | Cast _ fromty k e1 => \n      let '(r1, (si1, s1)) := rndval si shift fromty e1 in\n      rnd_of_cast si1 s1 fromty ty (round_knowl_denote k) r1\n    | Func _ ff args => \n       let fix rndval_klist (si: positive) (shift: MSHIFT) (tys: list type) (l': klist expr tys) {struct l'}: \n                                (klist (fun _ => rexpr) tys * (positive * MSHIFT))  :=\n          match  l' \n          with\n          | Knil => (Knil, (si,shift))\n          | Kcons h tl => let '(r1, (si1,s1)) := rndval si shift _ h in \n                                    let '(r2, (si2,s2)) := rndval_klist si1 s1 _ tl in\n                                      (Kcons r1 r2, (si2,s2))\n          end \n          in let '(r1,(si1,s1)) := rndval_klist si shift _ args\n               in rnd_of_func si1 s1 _ ff r1\n   end.\n\nFixpoint rndval_klist (si: positive) (shift: MSHIFT) {tys: list type} (l': klist expr tys) {struct l'}: \n                                (klist (fun _ => rexpr) tys * (positive * MSHIFT))  :=\n          match  l' \n          with\n          | Knil => (Knil, (si,shift))\n          | Kcons h tl => let '(r1, (si1,s1)) := rndval si shift _ h in \n                                    let '(r2, (si2,s2)) := rndval_klist si1 s1 tl in\n                                      (Kcons r1 r2, (si2,s2))\n          end.\n\nLemma rnd_of_binop_shift_incr si shift ty b r1 r2 r si' shift':\n  rnd_of_binop si shift ty b r1 r2 = (r, (si', shift')) ->\n  (si <= si')%positive.\nProof.\n  destruct b; simpl; intros.\n  -  eapply make_rounding_shift_incr; eauto.\n  -  inversion H; clear H; subst. lia.\n  - inversion H; clear H; subst. lia.\nQed.\n\nLemma rnd_of_binop_shift_le si shift ty b r1 r2 r si' shift':\n  rnd_of_binop si shift ty b r1 r2 = (r, (si', shift')) ->\n    (max_error_var r1 <= si)%positive ->\n    (max_error_var r2 <= si)%positive ->\n    (max_error_var r <=  si')%positive.\nProof.\n  destruct b; simpl; intros.\n - eapply make_rounding_shift_le; eauto.\n    simpl.\n    apply Pos.max_lub; auto.\n - inversion H; clear H; subst.\n    simpl.\n    apply Pos.max_lub; auto.\n - inversion H; clear H; subst.\n    destruct zero_left; auto.\n    destruct minus; auto.\nQed.\n\nLemma rnd_of_binop_shift_unchanged  si shift ty b r1 r2 r si' shift':\n  rnd_of_binop si shift ty b r1 r2 = (r, (si', shift')) ->\n  same_upto si (mget shift) (mget shift').\nProof.\n  destruct b; simpl; intros.\n  {\n    eapply make_rounding_shift_unchanged; eauto.\n  }\n  {\n    congruence.\n  }\n  {\n    congruence.\n  }\nQed.\n\nLemma rnd_of_cast_shift_incr si shift ty ty0 knowl r1 y si' shift':\n  rnd_of_cast si shift ty ty0 knowl r1 = (y, (si', shift')) ->\n  (si <= si')%positive.\nProof.\n  unfold rnd_of_cast.\n  destruct (type_leb ty ty0).\n  - inversion_clear 1; auto. lia.\n  - intros. eapply make_rounding_shift_incr; eauto.\nQed.\n\nLemma rnd_of_cast_shift_le si shift ty ty0 knowl r1 y si' shift':\n  rnd_of_cast si shift ty ty0 knowl r1 = (y, (si', shift')) ->\n  (max_error_var r1 <= si)%positive ->\n    (max_error_var y <= si')%positive.\nProof.\n  unfold rnd_of_cast.\n  destruct (type_leb ty ty0).\n  - congruence.\n  - intros; eapply make_rounding_shift_le; eauto.\nQed.\n\nLemma rnd_of_cast_shift_unchanged si shift ty ty0 knowl r1 y si' shift':\n  rnd_of_cast si shift ty ty0 knowl r1 = (y, (si', shift')) ->\n  same_upto si (mget shift) (mget shift').\nProof.\n  unfold rnd_of_cast.\n  destruct (type_leb ty ty0).\n  - congruence.\n  - apply make_rounding_shift_unchanged.\nQed.\n    \nLemma rnd_of_unop_shift_incr si shift ty u r1 y si' shift':\n  rnd_of_unop si shift ty u r1 = (y, (si', shift')) ->\n  (si <= si')%positive.\nProof.\n  destruct u; simpl.\n- (* Rounded1 *)\n  destruct op.\n +\n     apply make_rounding_shift_incr.\n + destruct knowl as [ [ | ] | ].\n  * (* Some Normal *)\n   inversion_clear 1; auto; lia.\n  *  apply (make_rounding_shift_incr _ _ Denormal2').\n  *  apply (make_rounding_shift_incr _ _ Denormal2').\n- (* Exact1 *)\n   inversion_clear 1; auto; lia.\nQed.\n\nLemma rnd_of_unop_shift_le si  shift ty u r1 y si' shift':\n  rnd_of_unop si shift ty u r1 = (y, (si', shift')) ->\n  (max_error_var r1 <= si)%positive ->\n  (max_error_var y  <=  si')%positive.\nProof.\n  destruct u; simpl; intros.\n- (* Rounded1 *)\n destruct op.\n + eapply make_rounding_shift_le; eauto.\n + destruct knowl as [ [ | ] | ].\n  * (* Some Normal *)\n    inversion H; clear H; subst; simpl. lia.\n  * eapply (make_rounding_shift_le _ _ Denormal2'); eauto. simpl. lia.\n  * eapply (make_rounding_shift_le _ _ Denormal2'); eauto. simpl. lia.\n- (* Exact1 *)\n    inversion H; clear H; subst; simpl.\n    destruct o; simpl; auto. lia.\nQed.\n\nLemma rnd_of_unop_shift_unchanged si  shift ty u r1 y si' shift':\n  rnd_of_unop si shift ty u r1 = (y, (si', shift')) ->\n  same_upto si (mget shift) (mget shift').\nProof.\n   unfold same_upto.\n  destruct u; simpl.\n- (* Rounded1 *)\n  destruct op.\n + apply make_rounding_shift_unchanged.\n + destruct knowl as [ [ | ] | ].\n  * (* Some Normal *)\n        inversion_clear 1; auto with arith.\n  * apply (make_rounding_shift_unchanged _ _ Denormal2').\n  * apply (make_rounding_shift_unchanged _ _ Denormal2').\n- (* Exact1 *)\n    inversion_clear 1; auto with arith.\nQed.\n\nLemma rndval_shift_incr ty x:\n  forall si shift y si' shift',\n    rndval si shift ty x = (y, (si', shift')) ->\n    (si <= si')%positive.\nProof.\n  induction x; simpl.\n- (* Const *)\n    inversion_clear 1; intros; auto; lia.\n- (* Var *)\n    inversion_clear 1; intros; auto; lia.\n- (* Binop *)\n    intros.\n    destruct (rndval si shift _ x1) as (r1 & si1 & s1) eqn:EQ1.\n    destruct (rndval si1 s1 _ x2) as (r2 & si2 & s2) eqn:EQ2.\n    eapply Pos.le_trans; [ | eapply Pos.le_trans].\n    + eapply IHx1; eauto.\n    + eapply IHx2; eauto.\n    + eapply rnd_of_binop_shift_incr; eauto.\n- (* Unop *)\n  intros.\n  destruct (rndval si shift _ x) as (r1 & si1 & s1) eqn:EQ1.\n  eapply Pos.le_trans.\n  + eapply IHx; eauto.\n  + eapply rnd_of_unop_shift_incr; eauto.\n- (* Cast *)\n  intros.\n  destruct (rndval si shift _ x) as (r1 & si1 & s1) eqn:EQ1.\n  eapply Pos.le_trans.\n  + eapply IHx; eauto.\n  + eapply rnd_of_cast_shift_incr; eauto.\n- (* Func *) \n   fold @rndval_klist.\n   destruct f4; simpl in *.\n   unfold rnd_of_func.\n  clear - IH.\n   intros.\n   destruct (rndval_klist si shift args) eqn:?H.\n   destruct p as [si2 s2].\n   apply Pos.le_trans with si2.\n   + clear H. revert k si shift si2 s2 H0.\n       clear - IH.\n       induction args; simpl; intros.\n     * inversion H0; clear H0; subst. lia.\n     * apply Kforall_inv in IH. destruct IH.\n        destruct (rndval si shift _ k) as (r1 & si1 & s1) eqn:EQ1.\n        destruct (rndval_klist si1 s1 args) as (r3 & si3 & s3) eqn:EQ2.\n        inversion H0; clear H0; subst.\n        eapply Pos.le_trans.\n        apply (H _ _ _ _ _ EQ1).\n        eapply IHargs in H1; eauto.\n   + eapply rnd_of_func'_shift_incr; eauto. \nQed.\n\nLemma rndval_klist_shift_incr tys (x: klist expr tys) :\n  forall si shift y si' shift',\n    rndval_klist si shift x = (y, (si', shift')) ->\n    (si <= si')%positive.\nProof.\nintros.\nrevert si shift y si' shift' H; induction x; intros.\nsimpl in H. inversion H; lia.\nsimpl in H.\ndestruct (rndval si shift ty k) as (r1 & si1 & s1) eqn:EQ1.\ndestruct (rndval_klist si1 s1  x) as (r2 & si2 & s2) eqn:EQ2.\ninversion H; clear H; subst.\napply rndval_shift_incr in EQ1.\napply IHx in EQ2. lia.\nQed.\n\nLemma rndval_shift_le ty (x: expr ty):\n  forall si shift y si' shift',\n    rndval si shift _ x = (y, (si', shift')) ->\n    (max_error_var y <=  si')%positive.\nProof.\n  induction x; simpl.\n- (* Const *)\n    inversion_clear 1; simpl; auto; lia.\n- (* Var *)\n    inversion_clear 1; simpl; auto; lia.\n- (* Binop *)\n    intros.\n    destruct (rndval si shift _ x1) as (r1 & si1 & s1) eqn:EQ1.\n    destruct (rndval si1 s1 _ x2) as (r2 & si2 & s2) eqn:EQ2.\n    eapply rnd_of_binop_shift_le; eauto.\n    eapply Pos.le_trans.\n    + eapply IHx1; eauto.\n    + eapply rndval_shift_incr; eauto.\n- (* Unop *)\n  intros.\n  destruct (rndval si shift _ x) as (r1 & si1 & s1) eqn:EQ1.\n  eapply rnd_of_unop_shift_le; eauto.\n- (* Cast *)\n  intros.\n  destruct (rndval si shift _ x) as (r1 & si1 & s1) eqn:EQ1.\n  eapply rnd_of_cast_shift_le; eauto.\n- (* Func *) \n   fold @rndval_klist.\n   destruct f4; simpl in *.\n   unfold rnd_of_func.\n   clear - IH.\n   intros.\n   destruct (rndval_klist si shift args) as [k [si2 s2]] eqn:?H.\n   apply (rnd_of_func'_shift_le _ _ _ _ _ _ _ _ _ H); clear H.\n   clear - IH H0. rename ff_args into tys.\n   revert k si shift si2 s2 H0.\n   simpl.\n   clear - IH.\n   induction args; simpl; intros.\n + inversion H0; clear H0; subst. simpl.  lia.\n + apply Kforall_inv in IH. destruct IH.\n    destruct (rndval si shift _ k) as (r1 & si1 & s1) eqn:EQ1.\n    destruct (rndval_klist si1 s1 args) as (r3 & si3 & s3) eqn:EQ2.\n    inversion H0; clear H0; subst.\n    pose proof (rndval_klist_shift_incr _ _ _ _ _ _ _ EQ2).\n    pose proof (rndval_shift_incr _ _ _ _ _ _ _ EQ1).\n    eapply IHargs in H1; try eassumption. clear IHargs EQ2.\n    simpl.\n    apply H in EQ1; clear H.\n   set (a := max_error_var_klist tys r3) in *.\n   change (a <= si2)%positive in H1.\n   change (_ tys r3) with a.\n  set (b := max_error_var r1) in *. clearbody a. clearbody b.\n  clear - EQ1 H1 H0 H2. lia.\nQed.\n\nLemma rndval_klist_shift_le tys (x: klist expr tys):\n  forall si shift y si' shift',\n    rndval_klist si shift x = (y, (si', shift')) ->\n    (max_error_var_klist _ y <=  si')%positive.\nProof.\n  induction x; simpl; intros.\n  inversion H; clear H; subst.\n  simpl. lia.\n   destruct (rndval si shift _ k) as (r1 & si1 & s1) eqn:EQ1.\n   destruct (rndval_klist si1 s1 x) as (r3 & si3 & s3) eqn:EQ2.\n   inversion H; clear H; subst.\n   pose proof (rndval_klist_shift_incr _ _ _ _ _ _ _ EQ2).\n   apply IHx in EQ2.\n   simpl.\n   pose proof (rndval_shift_le _ _ _ _ _ _ _ EQ1).\n   pose proof (rndval_shift_incr _ _ _ _ _ _ _ EQ1). lia.\nQed.\n\nLemma rndval_shift_unchanged ty (x: expr ty):\n  forall si shift y si' shift',\n    rndval si shift _ x = (y, (si', shift')) ->\n  same_upto si (mget shift) (mget shift').\nProof.\n   unfold same_upto.\n  induction x; simpl.\n- (* Const *)\n    inversion_clear 1; intros; auto; lia.\n- (* Var *)\n    inversion_clear 1; intros; auto; lia.\n- (* Binop *)\n    intros.\n    destruct (rndval si shift _ x1) as (r1 & si1 & s1) eqn:EQ1.\n    destruct (rndval si1 s1 _ x2) as (r2 & si2 & s2) eqn:EQ2.\n    etransitivity; [ | etransitivity].\n    +\n      eapply rnd_of_binop_shift_unchanged; eauto.\n      eapply Pos.lt_le_trans; [ eassumption | ].\n      etransitivity; eapply rndval_shift_incr; eauto.\n    +\n      eapply IHx2; eauto.\n      eapply Pos.lt_le_trans; [ eassumption | ].\n      eapply rndval_shift_incr; eauto.\n    + eapply IHx1; eauto.\n- (* Unop *)\n  intros.\n  destruct (rndval si shift _ x) as (r1 & si1 & s1) eqn:EQ1.\n  etransitivity.\n  +\n    eapply rnd_of_unop_shift_unchanged; eauto.\n    eapply Pos.lt_le_trans; [ eassumption | ].\n    eapply rndval_shift_incr; eauto.\n  + eapply IHx; eauto.\n- (* Cast *)\n  intros.\n  destruct (rndval si shift _ x) as (r1 & si1 & s1) eqn:EQ1.\n  etransitivity.\n  +\n    eapply rnd_of_cast_shift_unchanged; eauto.\n    eapply Pos.lt_le_trans; [ eassumption | ].\n    eapply rndval_shift_incr; eauto.\n  + eapply IHx; eauto.\n- (* Func *) \n   fold @rndval_klist.\n   unfold rnd_of_func.\n   intros.\n   destruct (rndval_klist si shift args) as [k [si2 s2]] eqn:?H.\n   apply rnd_of_func'_shift_unchanged in H.\n   rewrite H by (apply rndval_klist_shift_incr in H1; lia).\n   clear shift' H.\n   destruct f4; simpl in *.\n   intros.\n   clear - IH H0 H1. rename ff_args into tys.\n   revert k si shift si2 s2 H1 i H0.\n   induction args; simpl; intros; auto.\n   inversion H1; clear H1; subst; auto.\n   apply Kforall_inv in IH. destruct IH.\n    destruct (rndval si shift _ k) as (r1 & si1 & s1) eqn:EQ1.\n    destruct (rndval_klist si1 s1 args) as (r3 & si3 & s3) eqn:EQ2.\n    pose proof (rndval_klist_shift_incr _ _ _ _ _ _ _ EQ2).\n    pose proof (rndval_shift_incr _ _ _ _ _ _ _ EQ1).\n    inversion H1; clear H1; subst.\n    specialize (IHargs H2); clear H2.\n    specialize (IHargs _ _ _ _ _ EQ2); clear EQ2.\n    specialize (H _ _ _ _ _ EQ1); clear EQ1.\n    transitivity (mget s1 i).\n    apply IHargs; lia.\n    apply H; lia.\nQed.\n\nLemma rndval_klist_shift_unchanged tys (x: klist expr tys):\n  forall si shift y si' shift',\n    rndval_klist si shift x = (y, (si', shift')) ->\n  same_upto si (mget shift) (mget shift').\nProof.\n  induction x; simpl; intros; intro; intros.\n  inversion H; clear H; subst; auto.\n  destruct (rndval si shift _ k) as (r1 & si1 & s1) eqn:EQ1.\n  destruct (rndval_klist si1 s1 x) as (r3 & si3 & s3) eqn:EQ2.\n  inversion H; clear H; subst.\n  pose proof (rndval_shift_unchanged _ _ _ _ _ _ _ EQ1 _ H0).\n  pose proof (IHx _ _ _ _ _ EQ2 i).\n  pose proof (rndval_shift_incr _ _ _ _ _ _ _ EQ1).\n  pose proof (rndval_klist_shift_incr _ _ _ _ _ _ _ EQ2).\n   rewrite H1 by lia.\n  apply H.\nQed.\n\n(*  \"(a, b) holds\" iff 0 (if b then < else <=) a *)\nDefinition cond: Type := (rexpr * bool).\n\nDefinition False_cond : cond  := \n   (* a condition that is impossible to satisfy *)\n (RAtom (RConst (Float radix2 0 0)), true).\n\nDefinition eval_cond1 env m (c: cond) :=\n  let '(e, b) := c in\n  forall errors, errors_bounded m errors ->\n    (if b then Rlt else Rle) 0 (reval e env errors)\n.\n\nLemma evalcond1_False: forall env m, eval_cond1 env m False_cond -> False.\nProof.\nintros.\nhnf in H.\nsimpl in H.\nassert (0 < 0 * 1); [ | lra].\napply (H (fun _ => 0)).\nintros. intro.\nrewrite Rabs_R0.\napply error_bound_nonneg.\nQed.\n\nLemma eval_cond1_preserved m1 m2 env c:\n  ( forall e b,  c = (e, b) ->  same_upto (max_error_var e) (mget m1) (mget m2)) ->\n  eval_cond1 env m1 c ->\n  eval_cond1 env m2 c.\nProof.\n  unfold eval_cond1.\n  intros.\n  destruct c.\n  intros.\n  rewrite <- (reval_error_ext (fun i =>\n                              if Pos.ltb i (max_error_var r)\n                              then errors i\n                              else 0)).\n  {\n    apply H0.\n    intros. intro.\n    destruct (Pos.ltb i (max_error_var r)) eqn:LTB.\n    { erewrite <- H; eauto.\n      apply Pos.ltb_lt.\n      assumption.\n    }\n    rewrite Rabs_R0. apply error_bound_nonneg.\n  }\n  intros.\n  rewrite <- Pos.ltb_lt in H2.\n  rewrite H2.\n  reflexivity.\nQed.\n\nFixpoint revars (r: rexpr): MSET.t :=\n  match r with\n    | RAtom (RError n) => MSET.singleton n\n    | RUnop _ e => revars e\n    | RBinop _ e1 e2 => MSET.union (revars e1) (revars e2)\n    | RFunc _ ff args => \n       let fix revars_klist (tys: list type) (es: klist (fun _ => rexpr) tys) : MSET.t :=\n        match es with\n        | Knil => MSET.empty\n        | Kcons h tl => MSET.union (revars h) (revars_klist _ tl)\n       end\n       in revars_klist (ff_args ff) args\n    | _ => MSET.empty\n  end.\n\nFixpoint revars_klist {tys: list type} (es: klist (fun _ => rexpr) tys) : MSET.t :=\n        match es with\n        | Knil => MSET.empty\n        | Kcons h tl => MSET.union (revars h) (revars_klist tl)\n       end.\n\nLemma reval_error_ext_strong errors1 env errors2 e:\n  (forall i, MSET.In i (revars e) -> errors2 i = errors1 i) ->\n  reval e env errors2 = reval e env errors1.\nProof.\n  induction e; simpl.\n - (* RAtom *)\n    destruct r; auto.\n    intros.\n    apply H.\n    apply MSET.singleton_spec.\n    reflexivity.\n- (* RUnop *)\n    intuition congruence.\n- (* RBinop *)\n  intros.\n  rewrite IHe1.\n  +\n    rewrite IHe2; [reflexivity | ].\n    intros.\n    apply H.\n    rewrite MSET.union_spec.\n    tauto.\n  +\n    intros.\n    apply H.\n    rewrite MSET.union_spec.\n    tauto.\n- (* RFunc *)\n destruct ff; simpl in *.\n clear - args IH. rename ff_args into tys.\n rename ff_realfunc into f.\n fold (revars_klist args).\n intro.\n change (reval_klist env errors2 args f = reval_klist env errors1 args f).\n revert IH H; induction args; intros.\n reflexivity.\n apply Kforall_inv in IH. destruct IH.\n simpl in f|-*.\n replace (reval k env errors2) with (reval k env errors1).\n apply (IHargs (f (reval k env errors1)) H1).\n intros; apply H; simpl.\n rewrite MSET.union_spec. auto.\n symmetry; apply H0; intros.\n apply H. simpl. \n rewrite MSET.union_spec. auto.\nQed.\n\nLemma revars_max_error_var e:\n  forall i, MSET.In i (revars e) -> \n            (i < max_error_var e)%positive.\nProof.\n  induction e; simpl; auto; intro.\n - (* RAtom *)\n    destruct r; generalize (@MSET.empty_spec i); try contradiction.\n    intros _.\n    rewrite MSET.singleton_spec.\n    intro; subst; auto; lia.\n - (* RBinop *)\n  rewrite MSET.union_spec.\n  destruct 1.\n  +\n    eapply Pos.lt_le_trans; [eapply IHe1; eauto | ].\n    apply Pos.le_max_l.\n  +\n    eapply Pos.lt_le_trans; [eapply IHe2; eauto | ].\n    apply Pos.le_max_r.\n- (* RFunc *)\n destruct ff; simpl in *.\n clear - args IH. rename ff_args into tys.\n fold (revars_klist args).\n intro.\n change (i < max_error_var_klist tys args)%positive.\n revert IH H; induction args; intros.\n simpl in *.\n contradiction (@MSET.empty_spec i).\n apply Kforall_inv in IH. destruct IH.\n simpl in H |-*.\n rewrite MSET.union_spec in H.\n destruct H.\n + apply H0 in H. lia.\n +  apply IHargs in H1; clear IHargs; auto.  lia.\nQed.\n\nExport List.\n\nFixpoint enum_forall' t_ (Q: positive -> _ -> Prop) (l: list positive) \n   (P: Maps.PMap.t R -> Prop): Prop :=\n  match l with\n    | nil => P (mempty t_)\n    | a :: q =>\n      enum_forall' t_ Q q (fun errors =>\n                            forall u,\n                              Q a u ->\n                              P (mset errors a u))\n  end.\n\nLemma enum_forall_correct'  t_ (Q: _ -> _ -> Prop) (Ht_: forall i, Q i t_) l:\n  forall (P: _ -> Prop),\n    (forall errors1 errors2,\n       (forall i: positive, In i l -> mget errors2 i = mget errors1 i) ->\n       P errors1 -> P errors2) ->\n    (forall errors,\n       (forall i, Q i (mget errors i)) ->\n       P errors) <->\n    enum_forall' t_ Q l P.\nProof.\n  induction l; simpl; intros.\n  {\n    split.\n    {\n      intros.\n      eapply H0.\n      intros.\n      rewrite mget_empty.\n      auto.\n    }\n    intros.\n    eapply H; [ | eassumption ].\n    contradiction.\n  }\n  specialize (IHl (fun errors => forall u, Q a u -> P (mset errors a u))).\n  destruct IHl.\n  {\n    simpl.\n    intros.\n    eapply H.\n    2: eapply H1; eauto.\n    intros.\n    repeat rewrite mget_set.\n    destruct (Pos.eq_dec i a); auto.\n    destruct H3; try congruence.\n    auto.\n  }\n  split; intros.\n  {\n    apply H0; intros.\n    apply H2.\n    intros.\n    repeat rewrite mget_set.\n    destruct (Pos.eq_dec i a); auto.\n    congruence.\n  }\n  eapply H.\n  2: eapply H1 with (u := mget errors a); eauto.\n  intros.\n  repeat rewrite mget_set.\n  destruct (Pos.eq_dec i a); subst; auto.\nQed.\n\nDefinition enum_forall t_ Q l P :=\n    enum_forall' t_ Q l (fun m => P (mget m)).  \n\nTheorem enum_forall_correct  t_ (Q: _ -> _ -> Prop) (Ht_: forall i, Q i t_) l:\n  forall (P: _ -> Prop),\n    (forall errors1 errors2,\n       (forall i, In i l -> errors2 i = errors1 i) ->\n       P errors1 -> P errors2) ->\n    (forall errors,\n       (forall i, Q i (mget errors i)) ->\n       P (mget errors)) <->\n    enum_forall t_ Q l P.\nProof.\n  unfold enum_forall.\n  intros.\n  rewrite <- (enum_forall_correct' t_ Q Ht_ l (fun m => P (mget m))); try tauto.\n  intros.\n  eapply H; eauto.\nQed.\n\nLet P env e (b: bool) errors :=\n  (if b then Rlt else Rle) 0 (reval e env errors).\n\nLet Q m i err := \n  Rabs err <= error_bound (mget m i).\n\nDefinition eval_cond2 env m (c: cond) :=\n  let '(e, b) := c in\n  enum_forall 0 (Q m) (MSET.elements (revars e)) (P env e b)\n.\n\nLemma eval_cond2_correct env (m: MSHIFT) c:\n  eval_cond2 env m c <-> eval_cond1 env m c.\nProof.\n  unfold eval_cond2, eval_cond1.\n  destruct c.\n  rewrite <- enum_forall_correct.\n  {\n    unfold Q, P.\n    split; intros.\n    {\n      destruct (finite_errors_ex 0 (max_error_var r) errors).\n      rewrite <- (reval_error_ext (mget x)).\n      {\n        eapply H; eauto.\n        intros. rewrite H1.\n        destruct (Pos.ltb i (max_error_var r)); auto.\n        rewrite Rabs_R0. apply error_bound_nonneg.\n      }\n      intros.\n      rewrite H1.\n      rewrite <- Pos.ltb_lt in H2.\n      rewrite H2.\n      reflexivity.\n    }\n    apply H. auto.\n  }\n  {\n    unfold Q.\n    intros.\n    rewrite Rabs_R0. apply error_bound_nonneg. \n  }\n  unfold P.\n  intros.\n  rewrite (reval_error_ext_strong errors1); auto.\n  intros.\n  apply H.\n  rewrite <- MSET.elements_spec1 in H1.\n  rewrite SetoidList.InA_alt in H1.\n  destruct H1.\n  intuition congruence.\nQed.  \n\nDefinition is_div o :=\n  match o with\n    | DIV => true\n    | _ => false\n  end.\n\nDefinition rounding_cond_ast ty k x: list cond :=\n  match k with\n    | Normal' =>\n      (RBinop Tree.Sub (RUnop Tree.Abs x) (RAtom (RConst (Defs.Float _ 1 (3 - femax ty - 1)))), false) :: nil\n    | Denormal' =>\n      (RBinop Tree.Sub (RAtom (RConst (Defs.Float _ 1 (3 - femax ty)))) (RUnop Tree.Abs x), true) :: nil\n    | Denormal2' => nil\n    | Unknown' => nil \n  end.\n\nLemma rounding_cond_ast_shift ty k x e b:\n  In (e, b) (rounding_cond_ast ty k x) ->\n  (max_error_var e <= max_error_var x)%positive.\nProof.\n  Opaque Zminus.\n  destruct k; simpl; try tauto;\n    intro K;\n    inversion K; try contradiction;\n    clear K;\n    subst;\n    inversion H; clear H; subst;\n    simpl; lia.\n  Transparent Zminus.\nQed.\n\nLemma rounding_cond_ast_correct m env ty knowl r errors:\n  errors_bounded m errors ->\n  (forall i, In i (rounding_cond_ast ty knowl r) -> eval_cond1 env m i) ->\n  rounding_cond ty knowl (reval r env errors)\n.\nProof.\n  intros.\n  unfold rounding_cond.\n  destruct knowl; auto.\n -\n  cbn -[Zminus] in * |- *  .\n    specialize (H0 _ (or_introl _ (refl_equal _))).\n    cbn -[Zminus] in *.\n    specialize (H0 _ H).\n    lra.\n -\n  specialize (H0 _ (or_introl _ (refl_equal _))).\n  cbn -[Zminus] in *.\n  specialize (H0 _ H).\n  lra.\nQed.\n\nDefinition no_overflow ty x: cond := \n  (RBinop Tree.Sub (RAtom (RConst (Defs.Float _ 1 (femax ty)))) (RUnop Tree.Abs x), true).\n\nDefinition rnd_of_plus_zero_cond (zero_left: bool) r1 r2 :=\n  (RUnop Tree.Neg (RUnop Tree.Abs (if zero_left then r1 else r2)), false) :: nil.  \n\nDefinition rnd_of_binop_with_cond\n           si\n           (shift: MSHIFT)\n           (ty: type)\n           (o: binop) (r1 r2: rexpr):\n  ((rexpr * (positive * MSHIFT)) * list cond)\n  :=\n    match o with\n      | SterbenzMinus =>\n        ((RBinop Tree.Sub r1 r2, (si, shift)),\n         (RBinop Tree.Sub r1 (RBinop Tree.Mul r2 (RAtom (RConst (Defs.Float _ 1 (-1))))), false)\n           ::\n           (RBinop Tree.Sub (RBinop Tree.Mul r2 (RAtom (RConst (Defs.Float _ 1 1)))) r1, false)\n           :: nil)\n      | PlusZero minus zero_left =>\n        (\n          ((\n              if zero_left\n              then\n                if minus\n                then RUnop Tree.Neg r2\n                else r2\n              else\n                r1\n            ), (si, shift))\n          ,\n          rnd_of_plus_zero_cond zero_left r1 r2\n        )\n      | Rounded2 o' k =>\n        let ru := RBinop (Rbinop_of_rounded_binop o') r1 r2 in\n        let rs := make_rounding si shift (round_knowl_denote k) ty ru in\n        let '(r, _) := rs in\n        (rs,\n         (if is_div o' then (RUnop Tree.Abs r2, true) :: nil else nil)\n           ++ no_overflow ty r :: rounding_cond_ast ty (round_knowl_denote k) ru)\n    end.\n\nLemma rounding_cond_ast_shift_cond ty k r e b:\n  In (e, b) (rounding_cond_ast ty k r) ->\n     (max_error_var e = max_error_var r)%positive.\nProof.\n  unfold rounding_cond_ast.\n  destruct k; try contradiction.\n-\n    destruct 1; try contradiction.\n    Opaque Zminus. inversion H; clear H; subst. Transparent Zminus.\n    simpl. lia.\n-\n  destruct 1; try contradiction.\n  Opaque Zminus. inversion H; clear H; subst. Transparent Zminus.\n  simpl. lia.\nQed.\n\nLemma rnd_of_binop_with_cond_shift_cond si shift ty o r1 r2 r' si' shift' cond:\n  rnd_of_binop_with_cond si shift ty o r1 r2 = ((r', (si', shift')), cond) ->\n  (max_error_var r1 <= si)%positive ->\n  (max_error_var r2 <= si)%positive ->\n  forall e b,\n    In (e, b) cond ->\n    (max_error_var e <= si')%positive.\nProof.\n  destruct o; simpl.\n  {\n    destruct (\n        make_rounding si shift (round_knowl_denote knowl) ty\n                      (RBinop (Rbinop_of_rounded_binop op) r1 r2)\n    ) eqn:EQ.\n    intro K.\n    inversion K; clear K; subst.\n    intros.\n    apply in_app_or in H1.\n    destruct H1.\n    {\n      destruct (is_div op); try contradiction.\n      destruct H1; try contradiction.\n      inversion H1; clear H1; subst.\n      simpl.\n      apply make_rounding_shift_incr in EQ.\n      lia.\n    }\n    destruct H1.\n    {\n      inversion H1; clear H1; subst.\n      simpl. rewrite Pos.max_r by lia.\n      eapply make_rounding_shift_le; eauto.\n      simpl. lia.\n    }\n    apply rounding_cond_ast_shift_cond in H1.\n    rewrite H1.\n    simpl.\n    apply make_rounding_shift_incr in EQ.\n    lia.\n  }\n  {\n    intro K.\n    inversion K; clear K; subst.\n    simpl.\n    destruct 3.\n    {\n      inversion H1; clear H1; subst.\n      simpl. lia.\n    }\n    destruct H1; try contradiction.\n    inversion H1; clear H1; subst.\n    simpl. lia.\n  }\n  {\n    intro K.\n    inversion K; clear K; subst.\n    simpl.\n    destruct 3; try contradiction.\n    inversion H1; clear H1; subst.\n    simpl.\n    destruct zero_left; auto.\n  }\nQed.\n\nDefinition rnd_of_cast_with_cond\n           si\n           (shift: MSHIFT)\n           (tyfrom tyto: type)\n           (k: rounding_knowledge')\n           (r: rexpr) :=\n  if type_leb tyfrom tyto\n  then\n    ((r, (si, shift)), nil)\n  else\n    let rs := make_rounding si shift k tyto r in\n    let '(r', _) := rs in\n    (rs, no_overflow tyto r' :: rounding_cond_ast tyto k r)\n.\n\nLemma rnd_of_cast_with_cond_shift_cond\n      si shift tyfrom tyto k r r' si' shift' cond:\n  rnd_of_cast_with_cond si shift tyfrom tyto k r = ((r', (si', shift')), cond) ->\n  (max_error_var r <= si)%positive ->\n  forall e b,\n    In (e, b) cond ->\n    (max_error_var e <= si')%positive.\nProof.\n  unfold rnd_of_cast_with_cond.\n  destruct (type_leb tyfrom tyto).\n  {\n    intros.\n    inversion H; clear H; subst.\n    contradiction.\n  }\n  destruct (make_rounding si shift k tyto r) eqn:EQ.\n  destruct p.\n  intro K.\n  inversion K; clear K; subst.\n  destruct 2.\n  {\n    inversion H0; clear H0; subst.\n    simpl. rewrite Pos.max_r by lia.\n    eapply make_rounding_shift_le; eauto.\n  }\n  apply rounding_cond_ast_shift_cond in H0.\n  rewrite H0.\n  apply make_rounding_shift_incr in EQ.\n  lia.\nQed.\n\nDefinition rnd_of_unop_with_cond\n           si\n           (shift: MSHIFT)\n           (ty: type)\n           (o: unop) (r1: rexpr)\n  :=\n    match o with\n      | Rounded1 (InvShift n ltr) (Some Normal) =>\n        let ru := Runop_of_rounded_unop ty  (InvShift n ltr) r1 in\n        ((ru, (si, shift)), \n            (RBinop Tree.Sub (RUnop Tree.Abs r1) (RAtom (RConst (Defs.Float _ 1 (3 - femax ty + Z.pos n - 1)))), false) :: nil)\n      | Rounded1 (InvShift n _) _ =>\n        let ru := RBinop Tree.Mul (RAtom (RConst (B2F (B2 ty (- Z.pos n))))) r1 in\n        let rs := make_rounding si shift Denormal2' ty ru in\n        let '(r, _) := rs in\n        (rs, nil)\n      | Rounded1 op k =>\n        let ru := Runop_of_rounded_unop ty op r1 in\n        let rs := make_rounding si shift (round_knowl_denote k) ty ru in\n        let '(r, _) := rs in\n        (rs, (r1, false) :: rounding_cond_ast ty (round_knowl_denote k) ru)\n      | Exact1 o => \n        let ru := Runop_of_exact_unop ty o r1 in\n        ((ru, (si, shift)), \n         match o with\n           | Shift _ _ => no_overflow ty ru :: nil\n           | _ => nil\n         end)\n    end.\n\nLemma rnd_of_unop_with_cond_shift_cond si shift ty o r1 r' si' shift' cond:\n  rnd_of_unop_with_cond si shift ty o r1 = ((r', (si', shift')), cond) ->\n  (max_error_var r1 <= si)%positive ->\n  forall e b,\n    In (e, b) cond ->\n    (max_error_var e <= si')%positive.\nProof.\n  destruct o; cbn -[Zminus].\n- (* Rounded1 *)\n destruct op.\n + (* SQRT *)\n    destruct (\n        make_rounding si shift (round_knowl_denote knowl) ty (Runop_of_rounded_unop ty SQRT r1)\n      ) as [r'1 [si'1 shift'1]] eqn:EQ.\n    intro K.\n    inversion K; clear K; subst.\n    intros.\n    destruct H0.\n    {\n      inversion H0; clear H0; subst.\n      eapply make_rounding_shift_incr in EQ.\n      lia.\n    }\n    apply rounding_cond_ast_shift_cond in H0.\n    rewrite H0.\n    simpl.\n    apply make_rounding_shift_incr in EQ.\n    lia.\n + (* InvShift *)\n    destruct knowl as [ [ | ] | ].\n  * (* Some Normal *)\n    intro K.\n    inversion K; clear K; subst.\n    intros.\n    destruct H0; try contradiction.\n    inversion H0; clear H0; subst.\n    simpl. lia.\n  * intros. inversion H; clear H; subst. inversion H1.\n  * intros. inversion H; clear H; subst. inversion H1.\n- (* Exact1 *)\n    intro K.\n    inversion K; clear K; subst.\n    intros.\n    destruct o; try contradiction.\n   + (* Shift *)\n      destruct H0; try contradiction.\n      inversion H0; clear H0; subst.\n      simpl. lia.\nQed.\n\nDefinition interp_all_bounds (env:  forall x, FPLang.V -> binary_float (fprec x) (femax x))\n    {tys: list type} (bl: klist bounds tys) (args: klist expr tys) :=\n Kforall2 (fun ty (bd: bounds ty) (e: expr ty) => interp_bounds bd (fval env e) = true) bl args.\n\nDefinition vacuous_lo_bound {ty} (bnd: bounds ty) :=\n match bnd with ((B754_infinity _ _ true, false), _) => true | _ => false end.\nDefinition vacuous_hi_bound {ty} (bnd: bounds ty) :=\n match bnd with (_,(B754_infinity _ _ false, false)) => true | _ => false end.\n\nDefinition bounds_to_cond {ty} (bnd: bounds ty) (r: rexpr) : list cond := \n let '((lo,blo),(hi,bhi)) := bnd in\n  (if vacuous_lo_bound bnd then [] \n   else if is_finite _ _ lo then [(RBinop Tree.Sub r (RAtom (RConst (B2F lo))), blo)]\n   else [False_cond])\n   ++ \n  (if vacuous_hi_bound bnd then [] \n   else if is_finite _ _ hi then [(RBinop Tree.Sub (RAtom (RConst (B2F hi))) r, bhi)]\n   else [False_cond]).\n\nFixpoint bounds_to_conds {tys} (bnds: klist bounds tys) (args: klist (fun _ => rexpr) tys) : list cond.\ninversion bnds as [ | ty tys' b1 bnds'].\nexact nil.\nsubst tys.\ninversion args as [ | ty1 tys1' e1 args'].\nsubst.\nexact (bounds_to_cond b1 e1 ++ bounds_to_conds _ bnds' args').\nDefined.\n\nDefinition type_hibound' (t: type) :=\n(*   Float radix2 (Z.pow 2 (femax t) - Z.pow 2 (femax t - fprec t)) 1. *)\n  Float radix2 (Z.pow 2 (fprec t) - 1) (femax t - fprec t).\n\nDefinition func_no_overflow si shift {ty: type}\n     (ff:  floatfunc_package ty) \n     (args: klist (fun _ => rexpr) (ff_args ff)) : cond :=\n  no_overflow ty (fst (rnd_of_func si shift _ ff args)).\n\nDefinition rnd_of_func_with_cond\n    (si: positive) (shift: MSHIFT) {ty: type} (ff:  floatfunc_package ty) \n     (args: klist (fun _ => rexpr) (ff_args ff)) :\n     rexpr * (positive * MSHIFT) * list cond :=\n  (rnd_of_func si shift ty ff args, \n     func_no_overflow si shift ff args :: bounds_to_conds (ff_precond ff) args).\n\nFixpoint rndval_with_cond'\n         (si: positive)\n         (shift: MSHIFT)\n         {ty} (e: expr ty) {struct e}\n   : rexpr * (positive * MSHIFT) * list (rexpr * bool) :=\n  match e with\n    | Const _ f => ((RAtom (RConst (B2F f)), (si, shift)), nil)\n    | Var _ i => ((RAtom (RVar ty i), (si, shift)), nil)\n    | Binop b e1 e2 =>\n      let '((r1, (si1, s1)), p1) := rndval_with_cond' si shift e1 in\n      let '((r2, (si2, s2)), p2) := rndval_with_cond' si1 s1 e2 in\n      let '(rs, p) := rnd_of_binop_with_cond si2 s2 ty b r1 r2 in\n      (rs, p ++ (p1 ++ p2))\n    | Unop b e1 =>\n      let '((r1, (si1, s1)), p1) := rndval_with_cond' si shift e1 in\n      let '(rs, p) := rnd_of_unop_with_cond si1 s1 ty b r1 in\n      (rs, p ++ p1)\n    | Cast _ fromty k e1 => \n      let '((r1, (si1, s1)), p1) := rndval_with_cond' si shift e1 in\n      let '(rs, p) := rnd_of_cast_with_cond si1 s1 fromty ty (round_knowl_denote k) r1 in\n      (rs, p ++ p1)\n    | Func _ ff args => \n       let fix rndval_with_cond'_klist (si: positive) (shift: MSHIFT) {tys: list type} (l': klist expr tys)                     {struct l'}: \n                   klist (fun _ => rexpr) tys * (positive*MSHIFT) * list (rexpr * bool) :=\n          match l' (* in (klist _ l)  return (function_type (map RR l) R -> R) *)\n          with\n          | Knil => (Knil, (si, shift), nil)\n          | Kcons h tl => let  '((r1, (si1, s1)), p1) := rndval_with_cond' si shift h in\n                                    let '((r2, (si2, s2)), p2) := rndval_with_cond'_klist\n                                                      si1 s1 tl in\n                                    (Kcons r1 r2, (si2,s2), p1++p2)\n          end\n          in let '((rn, (si', s')), pn) := rndval_with_cond'_klist si shift args in\n              let '(rs,p) := rnd_of_func_with_cond si' s' ff rn\n               in (rs, p++pn)\n  end. \n\nFixpoint rndval_with_cond'_klist (si: positive) (shift: MSHIFT) {tys: list type} (l': klist expr tys) \n                       {struct l'}: \n                   klist (fun _ => rexpr) tys * (positive*MSHIFT) * list (rexpr * bool) :=\n          match l'\n          with\n          | Knil => (Knil, (si, shift), nil)\n          | Kcons h tl => let  '((r1, (si1, s1)), p1) := rndval_with_cond' si shift h in\n                                    let '((r2, (si2, s2)), p2) := rndval_with_cond'_klist si1 s1 tl in\n                                    (Kcons r1 r2, (si2,s2), p1++p2)\n          end.\n\nLemma rnd_of_binop_with_cond_left {si shift ty o r1 r2 a c}:\n  rnd_of_binop_with_cond si shift ty o r1 r2 = (a,c) ->\n  rnd_of_binop si shift ty o r1 r2 = a.\nProof.\n  unfold rnd_of_binop_with_cond, rnd_of_binop; intros.\n  destruct o; try congruence.\n  destruct (make_rounding _ _ _ _ _); congruence.\nQed.\n\n\nLemma rnd_of_cast_with_cond_left {si shift ty ty0 knowl r1 a c}:\n   rnd_of_cast_with_cond si shift ty ty0 knowl r1 = (a,c) ->\n   rnd_of_cast si shift ty ty0 knowl r1 = a.\nProof.\n   unfold rnd_of_cast_with_cond, rnd_of_cast; intros.\n  destruct (type_leb _ _); try congruence.\n  destruct (make_rounding _ _ _ _ _); congruence.\nQed.\n\nLemma rnd_of_unop_with_cond_left {si shift ty o r1  a c}:\n  rnd_of_unop_with_cond si shift ty o r1 = (a,c) ->\n  rnd_of_unop si shift ty o r1 = a.\nProof.\n  unfold rnd_of_unop_with_cond, rnd_of_unop; intros.\n  destruct o; simpl; try congruence.\n destruct op; try congruence.\n  destruct (make_rounding _ _ _ _ _); congruence.\n  destruct knowl as [ [ | ] | ]; simpl in *; congruence.\nQed.\n\nLemma rnd_of_func_with_cond_left {si shift ty ff args  a c}:\n  rnd_of_func_with_cond si shift ff args  = (a,c) ->\n  rnd_of_func si shift ty ff args = a.\nProof.\n unfold rnd_of_func_with_cond; intros; congruence.\nQed.\n\nLemma rndval_with_cond_left {si shift ty} {e: expr ty} {a c}:\n    rndval_with_cond' si shift e = (a,c) ->\n   rndval si shift _ e = a.\nProof.\n  revert si shift a c;\n  induction e; simpl; intros; try congruence.\n- (* Binop *)\n    specialize (IHe1 si shift).\n    destruct (rndval_with_cond' si shift e1) as [[r1 [si1 s1]] p1].\n    rewrite (IHe1 _ _ (eq_refl _)).\n    specialize (IHe2 si1 s1).\n    destruct (rndval_with_cond' si1 s1 e2) as [[r2 [si2 s2]] p2].\n    rewrite (IHe2 _ _ (eq_refl _)).\n    destruct (rnd_of_binop_with_cond si2 s2 ty b r1 r2) as [[r3 [si3 s3]] p3] eqn:?H.\n    apply @rnd_of_binop_with_cond_left in H0.\n    congruence.\n- (* Unop *)\n   intros.\n  specialize (IHe si shift).\n  destruct (rndval_with_cond' si shift e) as [[r1 [si1 s1]] p1].\n  rewrite (IHe _ _ (eq_refl _)).\n  destruct (rnd_of_unop_with_cond si1 s1 ty u r1) as [[r2 [si2 s2]] p2] eqn:?H.\n  apply rnd_of_unop_with_cond_left in H0. congruence.\n- (* Cast *) \n  intros.\n  specialize (IHe si shift).\n  destruct (rndval_with_cond' si shift e) as [[r1 [si1 s1]] p1]. \n  rewrite (IHe _ _ (eq_refl _)).\n  destruct (rnd_of_cast_with_cond si1 s1 fromty ty\n                 (round_knowl_denote knowl) r1)\n                   as [[r2 [si2 s2]] p2] eqn:?H.\n  apply rnd_of_cast_with_cond_left in H0. \n  congruence.\n- (* Func *)\n intros.\n  fold @rndval_with_cond'_klist in *.\n  fold (@rndval_klist si shift (ff_args f4)) in *.\n  destruct (rndval_with_cond'_klist si shift args) as [[r1 [si1 s1]] l1] eqn:?H.\n  destruct (rndval_klist si shift args) as [r2 [si2 s2]] eqn:?H.\n  unfold rnd_of_func_with_cond, rnd_of_func in *.\n  assert ((si1,s1,r1) = (si2,s2,r2)); [ | simpl; congruence].\n  clear P Q.\n  clear a c H.\n  revert si shift r1 si1 s1 l1 r2 si2 s2 H0 IH H1.\n  induction args; simpl; intros.\n  congruence.\n  destruct (rndval si shift ty0 k)  as [r1' [si1' s1']] eqn:?H.\n  destruct (rndval_klist si1' s1' args) as [r2' [si2' s2']] eqn:?H.\n  destruct (rndval_with_cond' si shift k) as [[r3 [si3 s3]] c3] eqn:?H.\n  destruct (rndval_with_cond'_klist si3 s3 args) as [[r4 [si4 s4]] c4] eqn:?H.\n  apply Kforall_inv in IH; destruct IH.\n  inversion H1; clear H1; inversion H0; clear H0; subst.\n  apply H5 in H3.\n  rewrite H3 in H; inversion H; clear H; subst.\n  clear H5 H3.\n  specialize (IHargs _ _ _ _ _ _ _ _ _ H4 H6 H2); clear H4 H6 H2.\n  congruence.\nQed.\n\nLemma rndval_with_cond_klist_left {si shift tys} {e: klist expr tys} {a c}:\n   rndval_with_cond'_klist si shift e = (a,c) ->\n   rndval_klist si shift e = a.\nProof.\n  revert si shift a c;  induction e; simpl; intros; auto.\n  congruence.\n  destruct (rndval_with_cond' si shift k) as [[r1 [si1 s1]] p1] eqn:?H.\n  destruct (rndval_with_cond'_klist si1 s1 e) as [[r2 [si2 s2]] p2] eqn:?H.\n  rewrite (rndval_with_cond_left H0).\n  apply IHe in H1. rewrite H1. congruence.\nQed.\n\nLemma rndval_with_cond_shift_cond ty (e: expr ty):\n  forall si shift r' si' shift' cond,\n  rndval_with_cond' si shift e = ((r', (si', shift')), cond) ->\n  forall e' b',\n    In (e', b') cond ->\n    (max_error_var e' <= si')%positive.\nProof.\n  induction e; simpl; intros.\n  -\n    inversion H; clear H; subst; contradiction.\n  -\n    inversion H; clear H; subst; contradiction.\n  -\n    destruct (rndval_with_cond' si shift e1) as [[r1 [si1 s1]] p1] eqn:EQ1.\n    destruct (rndval_with_cond' si1 s1 e2) as [[r2 [si2 s2]] p2] eqn:EQ2.\n    destruct (rnd_of_binop_with_cond si2 s2 _ b r1 r2)\n             as [rs' p']\n             eqn:EQ.\n    inversion H; clear H; subst.\n    pose proof (rndval_with_cond_left EQ1).\n    pose proof (rndval_with_cond_left EQ2).\n    pose proof (rnd_of_binop_with_cond_left EQ).\n    pose proof (rndval_shift_le _ _ _ _ _ _ _ H).\n    apply rndval_shift_incr in H.\n    pose proof (rndval_shift_le _ _ _ _ _ _ _ H1).\n    apply rndval_shift_incr in H1.\n    pose proof (rnd_of_binop_shift_incr _ _ _ _ _ _ _ _ _ H2).\n    apply rnd_of_binop_shift_le in H2; try lia.\n    rewrite !in_app_iff in H0.\n    destruct H0 as [?|[?|?]].\n      eapply rnd_of_binop_with_cond_shift_cond; eauto; lia.\n      eapply IHe1 in H0; [ | eassumption ]; lia .\n      eapply IHe2 in H0; [ | eassumption ]; lia .\n  - (* Unop *)\n    destruct (rndval_with_cond' si shift e) as [[r1 [si1 s1]] p1] eqn:EQ1.\n    destruct (rnd_of_unop_with_cond si1 s1 ty u r1) eqn:EQ.\n    inversion H; clear H; subst.\n    pose proof (rndval_with_cond_left EQ1).\n    pose proof (rnd_of_unop_with_cond_left EQ).\n    pose proof (rndval_shift_le _ _ _ _ _ _ _ H).\n    apply rndval_shift_incr in H.\n    pose proof (rnd_of_unop_shift_incr _ _ _ _ _ _ _ _ H1).\n    apply rnd_of_unop_shift_le in H1; try lia.\n    rewrite !in_app_iff in H0.\n    destruct H0.\n      eapply rnd_of_unop_with_cond_shift_cond; eauto.\n      eapply IHe in H0; [ | eassumption ]; lia.\n - (* Cast *)\n  destruct (rndval_with_cond' si shift e) as [[r1 [si1 s1]] p1] eqn:EQ1.\n  destruct (rnd_of_cast_with_cond si1 s1 fromty ty (round_knowl_denote knowl)  r1) eqn:EQ.\n  inversion H; clear H; subst.\n    pose proof (rndval_with_cond_left EQ1).\n    pose proof (rnd_of_cast_with_cond_left EQ).\n    pose proof (rndval_shift_le _ _ _ _ _ _ _ H).\n    apply rndval_shift_incr in H.\n    pose proof (rnd_of_cast_shift_incr _ _ _ _ _ _ _ _ _ H1).\n    apply rnd_of_cast_shift_le in H1; try lia.\n    rewrite !in_app_iff in H0.\n  destruct H0.\n       eapply rnd_of_cast_with_cond_shift_cond; eauto.\n       eapply IHe in H0; [ | eassumption ]; lia.\n- (* Func *)\n fold @rndval_with_cond'_klist in H.\n destruct (rndval_with_cond'_klist si shift args) as [[r2 [si2 s2]] c2] eqn:?H.\n inversion H; clear H; subst.\n unfold func_no_overflow, rnd_of_func, rnd_of_func', fst in H0.\n change (?a :: ?b ++ ?c) with ((a::b)++c) in H0.\n apply in_app_iff in H0.\n destruct H0 as [[H0|H0]|H0].\n + unfold no_overflow in *. inversion H0; clear H0; subst.\n     assert (H4 := rndval_with_cond_klist_left H1).\n      pose proof (rndval_klist_shift_le _ _ _ _ _ _ _ H4).\n     destruct (ff_rel (ff_ff f4)), (ff_abs (ff_ff f4)); simpl;\n     change (_ (ff_args f4) r2) with  (max_error_var_klist (ff_args f4) r2); lia.\n + assert (H4 := rndval_with_cond_klist_left H1).\n      pose proof (rndval_klist_shift_le _ _ _ _ _ _ _ H4).\n      clear - H H0.\n      destruct f4 as [tys pre rf ff]; simpl in *. clear - H0 H.\n      revert pre r2 H0 H; induction tys; simpl; intros.\n      rewrite (klist_nil pre) in H0. rewrite (klist_nil r2) in H0. destruct H0.\n      destruct (klist_cons pre) as [p1 [pre' ?]]. destruct (klist_cons r2) as [r1 [r2' ?]].  subst.\n     simpl in *. unfold eq_rect_r, eq_rect, eq_sym in H0.\n     apply in_app_iff in H0. destruct H0.\n     destruct p1 as [[lo blo] [hi bhi]]. unfold bounds_to_cond in H0.\n         apply in_app_iff in H0. destruct H0.\n         destruct (vacuous_lo_bound (lo, blo, (hi, bhi))) eqn:?H. contradiction.\n         destruct (is_finite _ _ lo) eqn:?H; destruct H0; try contradiction; inversion H0; clear H0; subst; simpl; lia.\n         destruct (vacuous_hi_bound (lo, blo, (hi, bhi))) eqn:?H. destruct H0.\n         destruct (is_finite _ _ hi) eqn:?H; destruct H0; try contradiction; inversion H0; clear H0; subst; simpl; lia.\n         eapply IHtys; try eassumption. lia.\n  + clear - H1 H0 IH.\n      revert si shift r2 si2 s2 c2 H1 H0; induction args; simpl; intros. \n      inversion H1; clear H1; subst. contradiction.\n      apply Kforall_inv in IH; destruct IH as [IH' IH].\n        destruct (rndval_with_cond' si shift k) as [[r1 [si1 s1]] p1] eqn:?H.\n        destruct (rndval_with_cond'_klist si1 s1 args) as [[r3 [si3 s3]] p3] eqn:?H.\n        inversion H1; clear H1; subst.\n       apply in_app_iff in H0; destruct H0.\n       specialize (IH' _ _ _ _ _ _ H _ _ H0). \n       assert (H4 := rndval_with_cond_klist_left H2).\n       pose proof (rndval_klist_shift_incr _ _ _ _ _ _ _ H4). lia.\n       apply IHargs in H2; eauto.\nQed.\n\nLemma rndval_with_cond_klist_shift_cond tys (e: klist expr tys):\n  forall si shift r' si' shift' cond,\n  rndval_with_cond'_klist si shift e = ((r', (si', shift')), cond) ->\n  forall e' b',\n    In (e', b') cond ->\n    (max_error_var e' <= si')%positive.\nProof.\n  induction e; simpl; intros.\n  inversion H; clear H; subst; contradiction H0.\n destruct (rndval_with_cond' si shift k) as [[r1 [si1 s1]] p1] eqn:?H.\n destruct (rndval_with_cond'_klist si1 s1 e) as [[r3 [si3 s3]] p3] eqn:?H.\n  inversion H; clear H; subst.\n  pose proof (rndval_with_cond_left H1).\n pose proof (rndval_with_cond_klist_left H2).\n pose proof (rndval_shift_incr _ _ _ _ _ _ _ H).\n pose proof (rndval_shift_le _ _ _ _ _ _ _ H).\n pose proof (rndval_klist_shift_incr _ _ _ _ _ _ _ H3).\n pose proof (rndval_klist_shift_le _ _ _ _ _ _ _ H3).\n pose proof (rndval_with_cond_shift_cond _ _ _ _ _ _ _ _ H1).\n specialize (IHe _ _ _ _ _ _ H2).\n apply in_app_iff in H0.\n destruct H0.\n apply H8 in H0; lia.\n  apply IHe in H0. lia.\nQed.\n\nLemma sterbenz_no_overflow A x y:\n  - A < x < A ->\n  - A < y < A ->\n  0 <= y * 2 - x ->\n  0 <= x - y * / 2 ->\n  - A < x - y < A\n.\nProof.\n  lra.\nQed.\n\nTheorem fop_of_rounded_binop_correct op shift errors\n    (Herr: errors_bounded shift errors)\n        ty e1\n        (F1: is_finite _ _ e1 = true)\n        env r1\n        (V1: reval r1 env errors =\n             B2R _ _ e1)\n        e2\n        (F2: is_finite _ _ e2 = true)\n        r2\n        (V2: reval r2 env errors = B2R _ _ e2)\n        r\n        (V_: reval r env errors =\n            Generic_fmt.round Zaux.radix2\n                                    (FLT.FLT_exp\n                                       (3 - femax ty - fprec ty)\n                                       (fprec ty)\n                                    )\n                                    (Generic_fmt.Znearest (fun x : Z => negb (Z.even x)))\n                                    (reval (RBinop (Rbinop_of_rounded_binop op) r1 r2) env errors))\n        (COND:\n           (forall i,\n              In i ((if is_div op\n                     then (RUnop Tree.Abs r2, true) :: nil\n                     else nil)) ->\n              eval_cond1 env shift i))\n        (NO_OVERFLOW:\n           eval_cond1 env shift (no_overflow ty r))\n:\n  is_finite _ _ (fop_of_rounded_binop op ty e1 e2) = true /\\\n  B2R _ _ (fop_of_rounded_binop op ty e1 e2) =\n  reval r env errors.\nProof.\n  intros.\n  specialize (NO_OVERFLOW _ Herr).\n  simpl in NO_OVERFLOW.\n  rewrite Rmult_1_l in NO_OVERFLOW.\n  rewrite V_ in * |- *.\n  clear r V_.\n  repeat rewrite B2R_correct in *.\n  destruct op;\n    cbn -[Zminus] in * |- * ;\n    rewrite V1 in * |- *;\n    rewrite V2 in * |- *.\n\n  {\n    (* plus *)\n    generalize (Bplus_correct _ _  (fprec_gt_0 _) (fprec_lt_femax _) (plus_nan _) BinarySingleNaN.mode_NE _ _ F1 F2).\n    change (SpecFloat.fexp _ _) with (FLT_exp (3 - femax ty - fprec ty) (fprec ty)).\n    change (BinarySingleNaN.round_mode _) with ZnearestE.\n    rewrite Raux.Rlt_bool_true by lra.\n    destruct 1 as (? & ? & _).\n    auto.\n  }\n  {\n    (* minus *)\n    generalize (Bminus_correct _ _  (fprec_gt_0 _) (fprec_lt_femax _) (plus_nan _) BinarySingleNaN.mode_NE _ _ F1 F2).\n    change (SpecFloat.fexp _ _) with (FLT_exp (3 - femax ty - fprec ty) (fprec ty)).\n    change (BinarySingleNaN.round_mode _) with ZnearestE.\n    rewrite Raux.Rlt_bool_true by lra.\n    destruct 1 as (? & ? & _).\n    auto.\n  }\n  {\n    (* mult *)\n    generalize (Bmult_correct _ _ (fprec_gt_0 _) (fprec_lt_femax _) (mult_nan _) BinarySingleNaN.mode_NE e1 e2).\n    change (SpecFloat.fexp _ _) with (FLT_exp (3 - femax ty - fprec ty) (fprec ty)).\n    change (BinarySingleNaN.round_mode _) with ZnearestE.\n    rewrite Raux.Rlt_bool_true by lra.\n    rewrite F1. rewrite F2.\n    simpl andb.\n    destruct 1 as (? & ? & _).\n    auto.\n  }\n  (* div *)\n  generalize (fun K => Bdiv_correct _ _ (fprec_gt_0 _) (fprec_lt_femax _) (div_nan _) BinarySingleNaN.mode_NE e1 e2 K).\n    change (SpecFloat.fexp _ _) with (FLT_exp (3 - femax ty - fprec ty) (fprec ty)).\n    change (BinarySingleNaN.round_mode _) with ZnearestE.\n    rewrite Raux.Rlt_bool_true by lra.\n  rewrite F1.\n  destruct 1 as (? & ? & _).\n  {\n    specialize (COND _ (or_introl _ (refl_equal _))).\n    simpl in COND.\n    specialize (COND _ Herr).\n    apply Rabs_lt_pos in COND.\n    congruence.\n  }\n  auto.\nQed.\n\nTheorem fop_of_rounded_unop_correct shift errors\n    (Herr: errors_bounded shift errors)\n        ty e1\n        (F1: is_finite _ _ e1 = true)\n        env r1\n        (V1: reval r1 env errors =\n             B2R _ _ e1)\n        r\n        (V_: reval r env errors =\n            Generic_fmt.round Zaux.radix2\n                                    (FLT.FLT_exp\n                                       (3 - femax ty - fprec ty)\n                                       (fprec ty)\n                                    )\n                                    (Generic_fmt.Znearest (fun x : Z => negb (Z.even x)))\n                                    (reval (Runop_of_rounded_unop ty SQRT r1) env errors))\n        (COND:\n           (forall i,\n              In i ((r1, false) :: nil) ->\n              eval_cond1 env shift i))\n:\n  is_finite _ _ (fop_of_rounded_unop SQRT ty e1) = true /\\\n  B2R _ _ (fop_of_rounded_unop SQRT ty e1) =\n  reval r env errors.\nProof.\n  intros.\n  rewrite V_ in * |- *.\n  clear r V_.\n  repeat rewrite B2R_correct in *.\n    cbn -[Zminus] in * |- * ;\n    rewrite V1 in * |- *.\n    generalize (Bsqrt_correct _ _  (fprec_gt_0 _) (fprec_lt_femax _) (sqrt_nan _) BinarySingleNaN.mode_NE e1).\n    destruct 1 as (? & ? & _).\n    split; auto.\n    specialize (COND _ (or_introl _ (refl_equal _))).\n    simpl in COND.\n    specialize (COND _ Herr).\n    rewrite V1 in COND.\n    clear r1 V1.\n    destruct e1; auto.\n    destruct s; auto.\n    exfalso.\n    revert COND.\n    clear.\n    simpl.\n    clear e0.\n    unfold Defs.F2R.\n    simpl.\n    assert (0 < INR (Pos.to_nat m) * Raux.bpow Zaux.radix2 e).\n    {\n      apply Rmult_lt_0_compat.\n      {\n        apply pos_INR_nat_of_P.\n      }\n      apply Raux.bpow_gt_0.\n    }\n   rewrite INR_IZR_INZ in H.\n   intro.\n   replace (IZR (Z.neg m)) with (- IZR (Z.of_nat (Pos.to_nat m))) in COND.\n   lra.\n   rewrite <- opp_IZR.\n   f_equal.\n   rewrite <- Pos2Z.opp_pos.\n   f_equal.\n   apply positive_nat_Z.\nQed.\n\nLemma rndval_with_cond_correct_uInvShift:\nforall (env : forall x : type, FPLang.V -> binary_float (fprec x) (femax x))\n (Henv : forall (ty : type) (i : FPLang.V),  is_finite (fprec ty) (femax ty) (env ty i) = true)\n(pow : positive)\n (ltr : bool) ty (e : expr ty) (si : positive) (r1 : rexpr) (s1 : MSHIFT)\n (errors1 errors1_1 : positive-> R)\n (E1 : same_upto si errors1 errors1_1)\n (EB1 : errors_bounded s1 errors1_1)\n (F1 : is_finite (fprec ty) (femax ty) (fval env e) = true)\n (V1 : reval r1 env errors1_1 =\n         B2R (fprec ty) (femax ty) (fval env e))\n (H0 : expr_valid e = true)\n (shift : MSHIFT) (r : rexpr) (si2 : positive) (s : MSHIFT) (si1 : positive) (p1 : list cond) \n (EQ1 : rndval_with_cond' si shift e = (r1, (si1, s1), p1))\n (p_ : list (rexpr * bool))\n  (EQ : rnd_of_unop_with_cond si1 s1 ty (Rounded1 (InvShift pow ltr) None) r1 =\n     (r, (si2, s), p_))\n (H1 : forall i : cond, In i (p_ ++ p1) -> eval_cond1 env s i) \n (H2 : errors_bounded shift errors1)\n (K_ : rnd_of_unop si1 s1 ty (Rounded1 (InvShift pow ltr) None) r1 = (r, (si2, s))),\nexists errors2 : positive -> R,\n   same_upto si errors1 errors2 /\\\n  (forall i, Rabs (errors2 i) <= error_bound (mget s i)) /\\\n  is_finite (fprec ty) (femax ty)\n    (fop_of_unop (Rounded1 (InvShift pow ltr) None) ty (fval env e)) = true /\\\n  reval r env errors2 =\n  B2R (fprec ty) (femax ty)\n    (fop_of_unop (Rounded1 (InvShift pow ltr) None) ty (fval env e)).\nProof.\nintros.\nassert (K1 := rndval_with_cond_left EQ1).\ninversion EQ; clear EQ; subst.\nset (op := RBinop Tree.Mul _) in *.\nset (s := mset s1 si1 (ty, Denormal')) in *.\npose (eps :=\n  B2R (fprec ty) (femax ty)\n    (fop_of_unop (Rounded1 (InvShift pow ltr) None) ty (fval env e)) -\n  F2R radix2 (B2F (B2 ty (Z.neg pow))) * reval r1 env errors1_1).\npose (errors2 i := if Pos.eq_dec i si1  then eps else errors1_1 i).\nexists errors2.\nsplit; [ | split; [ | split]].\n-\nintro; intros. unfold errors2.\ndestruct (Pos.eq_dec i si1); auto.\npose proof (rndval_shift_incr _ _ _ _ _ _ _ K1). lia.\n-\nsubst errors2.\nsimpl.\nintros.\nsubst s; simpl.\nrewrite mget_set.\ndestruct (Pos.eq_dec i si1).\n + subst.\n  unfold error_bound.\n  subst eps.\n  rewrite V1.\n change (bpow radix2 1) with 2.\n apply InvShift_accuracy; auto.\n +\n  clear eps.\n  destruct (Pos.lt_total i si).\n *rewrite E1 by auto. \n   erewrite rndval_shift_unchanged; eauto.\n * apply EB1; auto.\n- apply InvShift_finite; auto.\n-\n subst op. unfold reval; fold reval.\n replace (reval r1 env errors2) with (reval r1 env errors1_1).\n2:{\n   apply reval_error_ext; intros.\n   unfold errors2.\n destruct (Pos.eq_dec i si1); auto.\n  subst i.\n  pose proof (rndval_shift_le _ _ _ _ _ _ _ K1). lia.\n}\n  subst errors2.\n  subst eps.\n  rewrite V1.\n  simpl.\n  destruct (Pos.eq_dec si1 si1) as [ _ |]; [ | congruence].\n  set (a := F2R _ _).\n  set (b := B2R _ _ _).\n  set (c := B2R _ _ _).\n  ring.\nQed.\n\nDefinition rwcc errors1 si (s: MSHIFT) env ty (e: expr ty) r := \n      exists errors2,\n        same_upto si errors1 errors2\n        /\\\n        errors_bounded s errors2\n        /\\\n        let fv := fval env e in\n        is_finite _ _ fv = true\n        /\\\n        reval r env errors2 = B2R _ _ fv.\n\nDefinition fvalr_klist (env: forall ty, FPLang.V -> ftype ty) {T: Type} :=\n  fix fvalr_klist {l1: list type} (l': klist expr l1) (f: function_type (map RR l1) T) {struct l'}: T :=\n          match  l' in (klist _ l) return (function_type (map RR l) T -> T)\n          with\n          | Knil => fun f0 => f0\n          | Kcons h tl => fun f0 => fvalr_klist tl (f0 (FT2R (fval env h)))\n          end f.\n\nDefinition apply_errors (r: R) (si: positive) (errors: positive -> R) rel abs :=\n  r * (1 + (IZR (Z.of_N rel)) * errors si) + (IZR (Z.of_N abs)) * errors (Pos.succ si).\n\n\nLemma IZR_N_mult_div:\n  forall p x, IZR (Zpos p) * (x / IZR (Zpos p)) = x.\nProof.\nintros.\nunfold Rdiv.\nrewrite Rmult_comm.\nrewrite Rmult_assoc.\nrewrite (Rmult_comm (/ _)).\nrewrite Rinv_r. lra.\napply IZR_neq.\nintro; discriminate.\nQed.\n\nLemma rnd_of_func'_e:\n  forall si s ty rel abs ff r r2 x,\n  rnd_of_func' si s ty rel abs (RFunc ty ff r) = (r2, x) ->\n  forall env errors,\n  reval r2 env errors =\n  apply_errors (reval_klist env errors r (ff_realfunc ff)) si errors rel abs.\nProof.\nclear.\nintros.\nunfold rnd_of_func' in H.\ninversion H; clear H; subst.\nunfold apply_errors.\nsimpl.\nrewrite !Rmult_1_r. reflexivity.\nQed.\n\nDefinition rfval_klist (env: forall ty, FPLang.V -> ftype ty) :=\n  fix fval_klist {l1: list type} (l': klist expr l1) (f: function_type (map RR l1) R) {struct l'}: R :=\n          match  l' in (klist _ l) return (function_type (map RR l) R -> R)\n          with\n          | Knil => fun f0 => f0\n          | Kcons h tl => fun f0 => fval_klist tl (f0 (FT2R (fval env h)))\n          end f.\n\nFixpoint list_real_args (xl: list R) (tys: list type): function_type (map RR tys) (list R) :=\n  match tys as l return (function_type (map RR l) (list R)) with\n  | [] => rev xl\n  | _ :: tys' => (fun x : R => list_real_args (x :: xl) tys')\n  end.\n\nDefinition rwcc_klist errors1 si (s: MSHIFT) env tys (args: klist expr tys) (r: klist (fun _ => rexpr) tys) := \n      exists errors2,\n        same_upto si errors1 errors2\n        /\\\n        errors_bounded s errors2\n        /\\\n        let fv := mapk (fun ty => @fval _ env ty) args in\n        Kforall (fun ty (f: ftype ty) => is_finite _ _ f = true) fv\n        /\\\n        mapk (fun ty r => reval r env errors2) r = mapk (fun ty (x: ftype' ty) => B2R _ _ x) fv.\n\nDefinition adjust_err (coeff: N) (delta: R) := match coeff with N0 => R0 | Npos x => delta / IZR (Zpos x) end.\n\nLemma Rabs_adjust_le:\n  forall coeff delta bd, Rabs delta <= error_bound bd -> Rabs (adjust_err coeff delta) <= error_bound bd.\nProof.\n intros. destruct coeff; simpl. change R0 with 0. rewrite Rabs_R0. apply error_bound_nonneg.\n eapply Rle_trans; [ clear H | eassumption].\n unfold Rdiv. rewrite Rabs_mult. rewrite Rabs_inv. rewrite Rabs_Zabs. simpl.\n apply Rle_trans with (Rabs delta * 1); [ | lra].\n apply Rmult_le_compat_l. apply Rabs_pos.\n replace 1 with (/ 1) by nra. apply Rinv_le. lra. apply IZR_le. lia.\nQed.\n\nLemma rndval_with_cond_correct_klist : \n   forall env (Henv: forall ty i, is_finite _ _ (env ty i) = true) \n        tys (args: klist expr tys)\n  (IH : Kforall\n       (fun (ty : type) (e : expr ty) =>\n        expr_valid e = true ->\n        forall si shift r si' s' p,\n           rndval_with_cond' si shift e = (r, (si', s'), p) ->\n        (forall i : rexpr * bool, In i p -> eval_cond1 env s' i) ->\n        forall errors1 : positive -> R,\n        errors_bounded shift errors1 -> rwcc errors1 si s' env ty e r)\n       args),\n  expr_klist_valid args = true ->\n  forall si shift r si' s' p,\n    rndval_with_cond'_klist si shift args = ((r, (si', s')), p) ->\n    (forall i, In i p -> eval_cond1 env s' i) ->\n    forall errors1, errors_bounded shift errors1 ->\n    rwcc_klist errors1 si s' env tys args r.\nProof.\n  induction args; intros.\n-\n rewrite (klist_nil r).\n exists errors1; simpl.\n split; [ | split; [ | split]].\n intros ? ?; auto.\n simpl in H0. inversion H0; clear H0; subst; auto.\n constructor.\n auto.\n-\n apply andb_true_iff in H. destruct H.\n apply Kforall_inv in IH; destruct IH as [IH1 IH].\n simpl in H0. \n destruct (rndval_with_cond' si shift k) as [[r1 [si1 s1]] p1] eqn:?H.\n destruct (rndval_with_cond'_klist si1 s1 args) as [[r2 [si2 s2]] p2] eqn:?H.\n inversion H0; clear H0; subst.\n specialize (IHargs IH H3 _ _ _ _ _ _ H5); clear IH H3.\n apply (IH1 H _ _ _ _ _ _ H4) in H2; clear IH1.\n2:{ intros. eapply eval_cond1_preserved; try apply H1.\n     intros. subst i.\n  pose proof (rndval_with_cond_klist_left H5).\n  pose proof (rndval_with_cond_left H4).\n  intros ? ?.\n  rewrite (rndval_klist_shift_unchanged _ _ _ _ _ _ _ H3); auto.\n  pose proof (rndval_with_cond_shift_cond _ _ _ _ _ _ _ _ H4 _ _ H0). lia.\n  apply in_app_iff; auto.\n}\n destruct H2 as [errors2 [? [? [? ?]]]].\n apply IHargs in H2; clear IHargs.\n2:{ intros; apply H1. \n  apply in_app_iff; auto.\n}\n destruct H2 as [errors3 [? [? [? ?]]]].\n pose proof (rndval_with_cond_left H4).\n pose proof (rndval_shift_incr _ _ _ _ _ _ _ H10).\n exists errors3; split; [ |split; [ | split]]; auto.\n intros ? ?.\n rewrite  H2. auto. lia.\n constructor; auto.\n rewrite mapk_mapk in H9|-*.\n simpl. f_equal; auto.\n rewrite <- H6.\n apply reval_error_ext; intros.\n apply H2.\n apply rndval_shift_le in H10; lia.\nQed.\n\nTheorem rndval_with_cond_correct' env (Henv: forall ty i, is_finite _ _ (env ty i) = true) ty (e: expr ty) :\n  expr_valid e = true ->\n  forall si shift r si' s' p,\n    rndval_with_cond' si shift e = ((r, (si', s')), p) ->\n    (forall i, In i p -> eval_cond1 env s' i) ->\n    forall errors1, errors_bounded shift errors1 ->\n    rwcc errors1 si s' env ty e r.\nProof.\n  induction e; intros.\n-  (* const *)\n    unfold rwcc.\n    simpl in *.\n    inversion H0; clear H0; subst.\n    simpl.\n    exists errors1.\n    split. intro; auto.\n    split; auto.\n    split; auto.\n    symmetry.\n    rewrite F2R_eq.\n    apply B2F_F2R_B2R.\n- (* var *)\n    unfold rwcc.\n    simpl in *.\n    inversion H0; clear H0; subst. unfold same_upto.\n    eauto.\n-  (* binop *)\n    simpl in *.\n    destruct (rndval_with_cond' si shift e1) as [[r1 [si1 s1]] p1] eqn:EQ1.\n    destruct (rndval_with_cond' si1 s1 e2) as [[r2 [si2_ s2]] p2] eqn:EQ2.\n    destruct (rnd_of_binop_with_cond si2_ s2 ty b r1 r2) as [rs p_] eqn:EQ.\n    inversion H0; clear H0; subst.\n    rewrite andb_true_iff in H.\n    destruct H.\n\n    assert (K1 := rndval_with_cond_left EQ1).\n    assert (K2 := rndval_with_cond_left EQ2).\n    assert (K_ := rnd_of_binop_with_cond_left EQ).\n\n   assert (N : forall i : cond, In i p1 -> eval_cond1 env s1 i).\n    {\n      intros. \n      apply (eval_cond1_preserved s').\n      {\n        intros. intro.\n        subst.\n        symmetry.\n        etransitivity.\n        {\n          eapply rnd_of_binop_shift_unchanged; eauto.\n          eapply Pos.lt_le_trans; [ eassumption | ].\n          etransitivity.\n          eapply rndval_with_cond_shift_cond; [ | eassumption ] ; eauto.\n          eapply rndval_shift_incr; eauto.\n        }\n        eapply rndval_shift_unchanged; eauto.\n        eapply Pos.lt_le_trans; [ eassumption | ].\n        eapply rndval_with_cond_shift_cond; eauto.\n      }\n      apply H1. apply in_or_app. right. apply in_or_app. auto.\n    }\n    specialize (IHe1 H _ _ _ _ _ _ EQ1 N _ H2).\n    clear N.\n    destruct IHe1 as (errors1_1 & E1 & EB1 & F1 & V1).\n    assert (N : forall i : cond, In i p2 -> eval_cond1 env s2 i).\n    {\n      intros.\n      apply (eval_cond1_preserved s').\n      {\n        intros; intro.\n        subst.\n        symmetry.\n        eapply rnd_of_binop_shift_unchanged; eauto.\n        eapply Pos.lt_le_trans; [ eassumption | ].\n        eapply rndval_with_cond_shift_cond; [ | eassumption ] ; eauto.\n      }\n      apply H1. apply in_or_app. right. apply in_or_app. auto.\n    }\n    specialize (IHe2 H0 _ _ _ _ _ _ EQ2 N _ EB1).\n    clear N.\n    destruct IHe2 as (errors1_2 & E2 & EB2 & F2 & V2).\n    rewrite <- (reval_error_ext errors1_2) in V1\n     by (intros; apply E2; eapply Pos.lt_le_trans; [ eassumption | eapply rndval_shift_le; eauto]).\n    destruct b.\n   + (* rounded binary operator *)\n        simpl.\n        simpl in EQ.\n        destruct (\n            make_rounding si2_ s2 (round_knowl_denote knowl) ty\n                          (RBinop (Rbinop_of_rounded_binop op) r1 r2)\n          ) eqn:ROUND.\n        inversion EQ; clear EQ; subst.\n        simpl.\n\n        generalize (make_rounding_correct _ _ _ _ _ _ _ _ ROUND).\n        intro K.\n        simpl max_error_var in K.\n        assert (L: (Pos.max (max_error_var r1) (max_error_var r2) <= si2_)%positive).\n        {\n          intros.\n          apply Pos.max_lub.\n          {\n            eapply Pos.le_trans; [ eapply rndval_shift_le; eauto | ].\n            eapply rndval_shift_incr; eauto.\n          }\n          eapply rndval_shift_le; eauto.\n        }\n        specialize (K L _ EB2).\n        clear L.\n        assert (L: rounding_cond ty (round_knowl_denote knowl)\n                            (reval (RBinop (Rbinop_of_rounded_binop op) r1 r2) env errors1_2)).\n        {\n          eapply rounding_cond_ast_correct; [ eassumption | ].\n          intros.\n          eapply (eval_cond1_preserved s').\n          {\n            intros; intro.\n            subst.\n            symmetry.\n            apply rounding_cond_ast_shift in H3.\n            simpl in H3.\n            \n            eapply make_rounding_shift_unchanged; eauto.\n            eapply Pos.lt_le_trans; eauto.\n            etransitivity; try eassumption.\n            apply Pos.max_lub; eauto using rndval_shift_le.\n            etransitivity; [ eapply rndval_shift_le; eauto | ].\n            eapply rndval_shift_incr; eauto.\n          }\n          eapply H1. apply in_or_app. left. apply in_or_app. right. right. assumption.\n        }\n        specialize (K _ L (fun x : Z => negb (Z.even x))).\n        clear L.\n        destruct K as (errors2 & E & R & EB).\n        assert (W1: reval r1 env errors2 = reval r1 env errors1_2). {\n          apply reval_error_ext.\n          intros.\n          apply E.\n          eapply Pos.lt_le_trans; [ eassumption | ].\n          etransitivity; [ eapply rndval_shift_le; eauto | ].\n          eapply rndval_shift_incr; eauto.\n        }\n\n        assert (W2: reval r2 env errors2 = reval r2 env errors1_2). {\n          apply reval_error_ext.\n          intros.\n          apply E.\n          eapply Pos.lt_le_trans; [ eassumption | ].\n          eapply rndval_shift_le; eauto.\n        }\n        rewrite <- W1, <- W2 in *.\n        assert (\n            reval (RBinop (Rbinop_of_rounded_binop op) r1 r2) env errors1_2\n            =\n            reval (RBinop (Rbinop_of_rounded_binop op) r1 r2) env errors2\n        ) as W.\n        {\n          simpl.\n          congruence.\n        }\n        rewrite W in * |- *. clear W.\n\n        assert (L : forall i : rexpr * bool,\n             In i (if is_div op then (RUnop Tree.Abs r2, true) :: nil else nil) ->\n             eval_cond1 env s' i).\n        {\n          intros.\n          apply H1.\n          apply in_or_app.\n          left.\n          apply in_or_app.\n          auto.\n        }\n       assert (L': eval_cond1 env s'\n            (no_overflow ty r)).\n        {\n          apply H1.\n          apply in_or_app.\n          left.\n          apply in_or_app.\n          right.\n          left.\n          auto.\n        }\n\n        assert (K := fop_of_rounded_binop_correct _ _ _ EB \n                                                 _ _ F1\n                                                 _ _ V1\n                                                 _ F2\n                                                 _ V2\n                                                 _ R L L').\n        clear L L'.\n\n        destruct K.\n        exists errors2.\n        split; auto.\n        intros ? ?.\n        etransitivity.\n        {\n          eapply E.\n          eapply Pos.lt_le_trans; [ eassumption | ].\n          etransitivity; [ eapply rndval_shift_incr; eauto | ].\n          eapply rndval_shift_incr; eauto.\n        }\n        etransitivity.\n        {\n          eapply E2.\n          eapply Pos.lt_le_trans; [ eassumption | ].\n          eapply rndval_shift_incr; eauto.\n        }\n        eauto.\n    + (* Sterbenz *)      \n        simpl.\n        simpl in EQ.\n        inversion EQ; clear EQ; subst.\n        simpl.\n        generalize (H1 _ (or_introl _ (refl_equal _))).\n        specialize (fun j K => H1 j (or_intror _ K)).\n        specialize (H1 _ (or_introl _ (refl_equal _))).\n        simpl in H1 |- * .\n        intro H1'.\n        rewrite Rmult_1_l in *.\n        specialize (H1 _ EB2).\n        specialize (H1' _ EB2).\n\n        generalize (Bminus_correct _ _  (fprec_gt_0 _) (fprec_lt_femax _) (plus_nan _) BinarySingleNaN.mode_NE _ _ F1 F2).\n        intro K.\n        change ( Z.pos (fprecp ty)) with (fprec ty) in K.\n        rewrite <- V1 in K.\n        rewrite <- V2 in K.\n        rewrite Generic_fmt.round_generic in K; try typeclasses eauto.\n        {\n          destruct (Rlt_dec\n                      (Rabs (reval r1 env errors1_2 - reval r2 env errors1_2))\n                      (Raux.bpow Zaux.radix2\n                                       (femax ty))\n                   ).\n          {\n            apply Raux.Rlt_bool_true in r.\n            rewrite r in K.\n            destruct K as (KR & KF & _).\n            exists errors1_2.\n            split; auto.\n            intros; intro.\n            etransitivity.\n            {\n              eapply E2.\n              eapply Pos.lt_le_trans; [ eassumption | ].\n              eapply rndval_shift_incr; eauto.\n            }\n            auto.\n          }\n          exfalso.\n          pose proof \n          (abs_B2R_lt_emax _ _ (fval env e1)).\n          pose proof \n          (abs_B2R_lt_emax _ _ (fval env e2)).\n          rewrite <- V1 in H3.\n          rewrite <- V2 in H4.\n          apply Raux.Rabs_lt_inv in H3.\n          apply Raux.Rabs_lt_inv in H4.\n          generalize (sterbenz_no_overflow _ _ _ H3 H4 H1 H1').\n          clear K.\n          intro K.\n          apply Raux.Rabs_lt in K.\n          contradiction.\n        }\n        apply Sterbenz.sterbenz; try typeclasses eauto.\n        * rewrite V1. apply generic_format_B2R.\n        * rewrite V2. apply generic_format_B2R.\n        * lra.\n\n    + (* plus zero *)\n        unfold rwcc.\n        simpl.\n        simpl in EQ.\n        inversion EQ; clear EQ; subst.\n        simpl.\n        specialize (H1 _ (or_introl _ (refl_equal _))).\n        simpl in H1 |- * .\n        specialize (H1 _ EB2).        \n        exists errors1_2.\n        split.\n        *\n          intros; intro.\n          etransitivity.\n          {\n            eapply E2.\n            eapply Pos.lt_le_trans; [ eassumption | ].\n            eapply rndval_shift_incr; eauto.\n          }\n          eauto.\n        * split; auto.\n         assert (reval (if zero_left then r1 else r2) env errors1_2 = 0) as ZERO.\n         {\n          rewrite <- Rabs_zero_iff.\n          apply Rle_antisym; [lra | ].\n          apply Rabs_pos.\n         }\n         destruct zero_left.\n         {\n          rewrite V1 in ZERO.\n          pose proof (abs_B2R_lt_emax _ _ (fval env e2)).\n          destruct minus.\n          {\n            generalize (Bminus_correct _ _  (fprec_gt_0 _) (fprec_lt_femax _) (plus_nan _) BinarySingleNaN.mode_NE _ _ F1 F2).\n            rewrite ZERO.\n            rewrite Rminus_0_l.\n            rewrite Generic_fmt.round_opp.\n            rewrite Generic_fmt.round_generic; try typeclasses eauto.\n            {\n              rewrite Rabs_Ropp.\n              rewrite Raux.Rlt_bool_true by assumption.\n              unfold BMINUS.\n              unfold BINOP.\n              simpl reval.\n              destruct 1 as (BV & BF & _).\n              simpl femax in BV, BF |- * .\n              rewrite BV.\n              intuition.\n            }\n            apply generic_format_B2R.\n          }\n          generalize (Bplus_correct _ _  (fprec_gt_0 _) (fprec_lt_femax _) (plus_nan _) BinarySingleNaN.mode_NE _ _ F1 F2).\n          rewrite ZERO.\n          rewrite Rplus_0_l.\n          rewrite Generic_fmt.round_generic; try typeclasses eauto.\n          {\n            rewrite Raux.Rlt_bool_true by assumption.\n            unfold BPLUS.\n            unfold BINOP.\n            simpl reval.\n            destruct 1 as (BV & BF & _).\n            simpl femax in BV, BF |- * .\n            rewrite BV.\n            intuition.\n          }\n          apply generic_format_B2R.          \n        }\n        rewrite V2 in ZERO.\n        pose proof (abs_B2R_lt_emax _ _ (fval env e1)).\n        destruct minus.\n        {\n          generalize (Bminus_correct _ _  (fprec_gt_0 _) (fprec_lt_femax _) (plus_nan _) BinarySingleNaN.mode_NE _ _ F1 F2).\n          rewrite ZERO.\n          rewrite Rminus_0_r.\n          rewrite Generic_fmt.round_generic; try typeclasses eauto.\n          {\n            rewrite Raux.Rlt_bool_true by assumption.\n            unfold BMINUS.\n            unfold BINOP.\n            simpl reval.\n            destruct 1 as (BV & BF & _).\n            simpl femax in BV, BF |- * .\n            rewrite BV.\n            intuition.\n          }\n          apply generic_format_B2R.\n        }\n        generalize (Bplus_correct _ _  (fprec_gt_0 _) (fprec_lt_femax _) (plus_nan _) BinarySingleNaN.mode_NE _ _ F1 F2).\n        rewrite ZERO.\n        rewrite Rplus_0_r.\n        rewrite Generic_fmt.round_generic; try typeclasses eauto.\n        {\n          rewrite Raux.Rlt_bool_true by assumption.\n          unfold BPLUS.\n          unfold BINOP.\n          simpl reval.\n          destruct 1 as (BV & BF & _).\n          simpl femax in BV, BF |- * .\n          rewrite BV.\n          intuition.\n        }\n        apply generic_format_B2R.          \n\n- (* unop *)\n  simpl in *.\n  destruct (rndval_with_cond' si shift e) as [[r1 [si1 s1]] p1] eqn:EQ1.\n  destruct (rnd_of_unop_with_cond si1 s1 ty u r1) as [rs p_] eqn:EQ.\n  inversion H0; clear H0; subst.\n  rewrite andb_true_iff in H.\n  destruct H.\n\n  assert (K1 := rndval_with_cond_left EQ1).\n  assert (K_ := rnd_of_unop_with_cond_left EQ).\n\n  assert (N: forall i : cond, In i p1 -> eval_cond1 env s1 i).\n  {\n    intros.\n    apply (eval_cond1_preserved s').\n    {\n      intros; intro; subst.\n      symmetry.\n      eapply rnd_of_unop_shift_unchanged; eauto.\n      eapply Pos.lt_le_trans; eauto.\n      eapply rndval_with_cond_shift_cond; eauto.\n    }\n    apply H1. apply in_or_app. auto.\n  }\n  specialize (IHe H0 _ _ _ _ _ _ EQ1 N _ H2).\n  clear N.\n  destruct IHe as (errors1_1 & E1 & EB1 & F1 & V1).\n\n  destruct u.\n + (* rounded unary operator *)\n    simpl.\n  destruct op.\n  * (* SQRT *)\n    simpl in EQ.\n    unfold Datatypes.id in *.\n    destruct (\n        make_rounding si1 s1 (round_knowl_denote knowl)\n                      ty (RUnop Tree.Sqrt r1)\n      ) eqn:ROUND.\n    inversion EQ; clear EQ; subst.\n\n    assert (K := make_rounding_correct _ _ _ _ _ _ _ _ ROUND).\n    simpl max_error_var in K.\n    assert (L:  (max_error_var r1 <= si1)%positive).\n    {\n      intros.\n      eapply rndval_shift_le; eauto.\n    }\n    assert (L': rounding_cond ty (round_knowl_denote knowl)\n      (reval (RUnop Tree.Sqrt r1)env errors1_1)).\n    {\n      eapply rounding_cond_ast_correct; [ eassumption | ].\n      intros.\n      eapply (eval_cond1_preserved s').\n      {\n        intros; intro; subst.\n        symmetry.\n        apply rounding_cond_ast_shift in H3.\n        simpl in H3.\n        eapply rnd_of_unop_shift_unchanged; eauto.\n        eapply Pos.lt_le_trans; eauto.\n        etransitivity; try eassumption.\n      }\n      eapply H1.\n      apply in_or_app.\n      left.\n      right.\n      assumption.\n    }\n    specialize (K L _ EB1 _ L' (fun x : Z => negb (Z.even x))).\n    clear L L'.\n    destruct K as (errors2 & E & R & EB).\n\n    assert (W1: reval r1 env errors2 = reval r1 env errors1_1).\n    {\n      apply reval_error_ext.\n      intros.\n      apply E.\n      eapply Pos.lt_le_trans; [ eassumption | ].\n      eapply rndval_shift_le; eauto.\n    }\n    rewrite <- W1 in V1.\n\n    assert (\n        reval (RUnop Tree.Sqrt r1) env errors1_1\n        =\n        reval (RUnop Tree.Sqrt r1) env errors2\n      ) as W.\n    {\n      simpl.\n      congruence.\n    }\n    rewrite W in * |- *. clear W.\n\n   assert (L : forall i : rexpr * bool,\n     In i ((r1, false) :: nil) ->\n     eval_cond1 env s' i).\n    {\n      intros.\n      apply H1.\n      apply in_or_app.\n      left.   destruct H3. left; auto. destruct H3.\n    }\n    assert (K := fop_of_rounded_unop_correct _ _ EB \n                                             _ _ F1\n                                             _ _ V1\n                                             _ R L).\n    clear L.\n\n    destruct K.\n    exists errors2.\n    split; auto.\n    intros; intro.\n    etransitivity.\n    {\n      eapply E.\n      eapply Pos.lt_le_trans; [eassumption | ].\n      eapply rndval_shift_incr; eauto.\n    }\n    eauto.\n  * (* InvShift *)\n   destruct knowl as [ [ | ] | ].\n  -- (* Normal *)\n    simpl.\n    cbn -[Zminus] in EQ.\n    unfold Datatypes.id in *.\n    Opaque Zminus.\n    inversion EQ; clear EQ; subst.\n    Transparent Zminus.\n\n    exists errors1_1.\n    split; auto.\n    split; auto.\n    cbn -[Zminus] in * |- *.\n    rewrite F2R_eq.\n    rewrite <- B2F_F2R_B2R.\n    rewrite Z.leb_le in H.\n    apply center_Z_correct in H.\n    assert (B2_FIN := B2_finite ty (Z.neg pow) (proj2 H)).\n    generalize (Bmult_correct _ _ (fprec_gt_0 _) (fprec_lt_femax _) (mult_nan _) BinarySingleNaN.mode_NE (B2 ty (Z.neg pow)) (fval env e)).\n    generalize (Bmult_correct_comm _ _ (fprec_gt_0 _) (fprec_lt_femax _) (mult_nan _) BinarySingleNaN.mode_NE (B2 ty (Z.neg pow)) (fval env e)).\n    rewrite Rmult_comm.\n    change (SpecFloat.fexp (fprec ty) (femax ty))\n     with  (FLT_exp (3 - femax ty - fprec ty) (fprec ty)).\n    rewrite (B2_correct _ (Z.neg pow) H).\n    replace (Z.neg pow) with (- Z.pos pow)%Z in * |- * by reflexivity.   \n    rewrite Raux.bpow_opp.\n    rewrite FLT_format_div_beta_1; try typeclasses eauto.\n    {\n      unfold Rdiv.\n      rewrite <- Raux.bpow_opp.\n      rewrite F1.\n      rewrite B2_FIN.\n      simpl andb.\n      rewrite Raux.Rlt_bool_true.\n      {\n        unfold BMULT, BINOP.\n        destruct 1 as (LC & ? & ?).\n        destruct 1 as (L & ? & ?).\n        destruct ltr; split; auto; rewrite V1.\n        {\n          rewrite LC.\n          ring.\n        }\n        rewrite L.\n        ring.\n      }\n      rewrite Raux.bpow_opp.\n      apply Bdiv_beta_no_overflow.\n      assumption.\n    }\n    specialize (H1 _ (or_introl _ (refl_equal _))).\n    specialize (H1 _ EB1).\n    cbn -[Zminus] in H1.\n    rewrite <- V1.\n    lra.\n  -- eapply rndval_with_cond_correct_uInvShift; eassumption.\n  -- eapply rndval_with_cond_correct_uInvShift; eassumption.\n\n + (* exact unary operator *)\n\n    simpl.\n    cbn -[Zminus] in EQ.\n    unfold Datatypes.id in *.\n    Opaque Zminus.\n    inversion EQ; clear EQ; subst.\n    Transparent Zminus.\n\n    exists errors1_1.\n    split; auto.\n    split; auto.\n\n    destruct o.\n\n   * (* abs *)\n      simpl in * |- *.\n      unfold BABS.\n      rewrite is_finite_Babs.\n      split; auto.\n      rewrite B2R_Babs.\n      congruence.\n\n   * (* opp *)\n      simpl in * |- * .\n      unfold BOPP.\n      rewrite is_finite_Bopp.\n      split; auto.\n      rewrite B2R_Bopp.\n      congruence.\n\n   * (* shift *)\n      cbn -[Zminus] in * |- *.\n      rewrite F2R_eq.\n      rewrite <- B2F_F2R_B2R.\n      rewrite Z.leb_le in H.\n      apply center_Z_correct in H.\n      generalize (B2_finite ty (Z.of_N pow) (proj2 H)).\n      intro B2_FIN.\n      generalize\n          (Bmult_correct _ _ (fprec_gt_0 _) (fprec_lt_femax _) (mult_nan _) BinarySingleNaN.mode_NE (B2 ty (Z.of_N pow)) (fval env e)).\n      generalize\n         (Bmult_correct_comm _ _ (fprec_gt_0 _) (fprec_lt_femax _) (mult_nan _) BinarySingleNaN.mode_NE (B2 ty (Z.of_N pow)) (fval env e)).\n      rewrite Rmult_comm.\n      replace (Z.of_N (pow + 1)) with (Z.of_N pow + 1)%Z in H by (rewrite N2Z.inj_add; simpl; ring).\n      specialize (H1 _ (or_introl _ (refl_equal _)) _ EB1).\n      simpl in H1.\n      rewrite F2R_eq, <- B2F_F2R_B2R, V1 in H1.\n      rewrite (B2_correct _ _ H) in H1|-*.\n    change (SpecFloat.fexp (fprec ty) (femax ty))\n     with  (FLT_exp (3 - femax ty - fprec ty) (fprec ty)).\n      rewrite FLT_format_mult_beta_n; try typeclasses eauto.\n      rewrite F1.\n      rewrite B2_FIN.\n      simpl andb.\n      rewrite Raux.Rlt_bool_true.\n      {\n        unfold BMULT, BINOP.\n        destruct 1 as (LC & ? & ?).\n        destruct 1 as (L & ? & ?).        \n        destruct ltr; split; auto; rewrite V1.\n        {\n          rewrite LC.\n          ring.\n        }\n        rewrite L.\n        ring.\n      }\n      rewrite Rmult_comm.\n      lra.\n\n - (* cast *)\n  unfold rwcc.\n  simpl in *.\n  destruct (rndval_with_cond' si shift e) as [[r1 [si1 s1]] p1] eqn:EQ1.\n  destruct (rnd_of_cast_with_cond si1 s1  fromty ty (round_knowl_denote knowl) r1) as [rs p_] eqn:EQ.\n  inversion H0; clear H0; subst.\n\n  assert (K1 := rndval_with_cond_left EQ1).\n  assert (K2 := rnd_of_cast_with_cond_left EQ).\n\n  assert (N: forall i : cond, In i p1 -> eval_cond1 env s1 i).\n  {\n    intros.\n    apply (eval_cond1_preserved s').\n    {\n      intros; intro; subst.\n      symmetry.\n      eapply rnd_of_cast_shift_unchanged; eauto.\n      eapply Pos.lt_le_trans; eauto.\n      eapply rndval_with_cond_shift_cond; eauto.\n    }\n    apply H1. apply in_or_app. auto.\n  }\n  specialize (IHe H _ _ _ _ _ _ EQ1 N _ H2).\n  clear N.\n  destruct IHe as (errors1_1 & E1 & EB1 & F1 & V1).\n\n  simpl.\n  simpl in *.\n  unfold cast.\n  unfold rnd_of_cast_with_cond in EQ.\n  destruct (type_eq_dec fromty ty).\n  {\n    subst ty.\n    simpl.\n    rewrite (fun t1 t2 => let (_, K) := type_leb_le t1 t2 in K) in EQ.\n    {\n      inversion EQ; clear EQ; subst.\n      eauto.\n    }\n    apply type_le_refl.\n  }\n  destruct (type_leb fromty ty) eqn:LEB.\n  {\n    inversion EQ; clear EQ; subst.\n    rewrite type_leb_le in LEB.\n    inversion LEB.\n    generalize ((fun J1 =>\n                  Bconv_widen_exact _ _ _ _ J1 (fprec_gt_0 _) (fprec_lt_femax _) \n                        (Z.le_ge _ _ H0) (Z.le_ge _ _ H3) (conv_nan _ _) BinarySingleNaN.mode_NE _ F1) ltac:( typeclasses eauto ) ).\n    destruct 1 as (K & L & _).\n    symmetry in K.\n    rewrite <- V1 in K.\n    eauto.\n  }\n  destruct (make_rounding si1 s1 (round_knowl_denote knowl) ty r1) eqn:ROUND.\n  inversion EQ; clear EQ; subst.\n  generalize (make_rounding_correct _ _ _ _ _ _ _ _ ROUND).\n  intro K.\n  assert (L: (max_error_var r1 <= si1)%positive).\n  {\n    eapply rndval_shift_le; eauto.\n  }\n  assert (L': rounding_cond ty (round_knowl_denote knowl) (reval r1 env errors1_1)).\n  {\n    eapply rounding_cond_ast_correct.\n    {\n      eassumption.\n    }\n    intros.\n    eapply (eval_cond1_preserved s').\n    {\n      intros; intro; subst.\n      symmetry.\n      apply rounding_cond_ast_shift in H0.\n      simpl in H0.\n      eapply make_rounding_shift_unchanged; eauto.\n      eapply Pos.lt_le_trans; eauto.\n      etransitivity; try eassumption.\n    }\n    eapply H1.\n    apply in_or_app.\n    left.\n    right.\n    assumption.\n  } \n  specialize (K L _ EB1 _ L'  (fun x : Z => negb (Z.even x))); clear L L'.\n  destruct K as (errors2 & E & R & EB).\n  rewrite V1 in R.\n  generalize (Bconv_correct _ _ _ _ (fprec_gt_0 _) (fprec_lt_femax ty) (conv_nan _ _) BinarySingleNaN.mode_NE _ F1).\n  unfold BinarySingleNaN.round_mode.\n  rewrite <- R.\n  rewrite Raux.Rlt_bool_true.\n  {\n    destruct 1 as (J & K & _).\n    symmetry in J.\n    exists errors2.\n    split; auto.\n    intros; intro.\n    etransitivity.\n    {\n      eapply E.\n      eapply Pos.lt_le_trans; eauto.\n      eapply rndval_shift_incr; eauto.\n    }\n    auto.\n  }\n  specialize (H1 _ (or_introl _ (refl_equal _))).\n  specialize (H1 _ EB).\n  simpl in H1.\n\n  lra.\n- (* Func *)\n change (fval env (Func ty f4 args)) with (fval_klist env args (ff_func (ff_ff f4))).\n change (expr_klist_valid args = true) in H.\n simpl in H0.\n fold (@rndval_with_cond'_klist) in H0.\n destruct ( rndval_with_cond'_klist si shift args) as [[r2 [si2 s2]] p2] eqn:?H.\n inversion H0; clear H0; subst.\n assert (EC2: forall i : rexpr * bool, In i p2 -> eval_cond1 env s2 i). {\n    intros. eapply eval_cond1_preserved; try apply H1.\n    intros; subst.\n    intros ? ?. \n    apply  (rndval_with_cond_klist_shift_cond _ _ _ _ _ _ _ _ H3) in H0.\n    rewrite !mget_set. repeat (destruct (Pos.eq_dec _ _)); try lia. auto.\n    right. apply in_app_iff; auto.\n }\n eapply rndval_with_cond_correct_klist in IH; try eassumption; clear H EC2.\n assert (MEV := rndval_with_cond_klist_left H3).\n apply rndval_klist_shift_le in MEV.\n destruct IH as [errors2 [? [? [? ?]]]].\n rewrite mapk_mapk in H5.\n red.\n change (fval env (Func ty f4 args)) with (fval_klist env args (ff_func (ff_ff f4))).\n set (s' := mset (mset _ _ _) _ _).\n set (r := abs_error _ _ _).\n assert (exists errors0 : positive -> R,\n     same_upto si errors2 errors0 /\\\n     errors_bounded s' errors0 /\\\n     is_finite (fprec ty) (femax ty) (fval_klist env args (ff_func (ff_ff f4))) = true /\\\n     reval r env errors0 = B2R (fprec ty) (femax ty) (fval_klist env args (ff_func (ff_ff f4)))).\n 2:{ destruct H6 as [err [? ?]]; exists err; split; auto. intros ? ?. rewrite <- H; auto. }\n assert (Hsi: (si <= si2 /\\ max_error_var_klist (ff_args f4) r2 <= si2)%positive). {\n    pose proof (rndval_with_cond_klist_left H3).\n    pose proof (rndval_klist_shift_incr _ _ _ _ _ _ _ H6).\n    pose proof (rndval_klist_shift_le _ _ _ _ _ _ _ H6).\n    auto.\n  } \n  destruct Hsi as [Hsi Hr2].\n  clear errors1 H2 H shift H3.\n  assert (forall i, In i (func_no_overflow si2 s2 f4 r2 :: bounds_to_conds (ff_precond f4) r2) -> eval_cond1 env s' i)\n     by (intros; apply H1; clear - H; simpl in H|-*; rewrite in_app_iff; tauto). clear H1 p2.\n  unfold func_no_overflow, rnd_of_func, rnd_of_func', fst in H. fold r in H.\n  set (r4 := RFunc ty f4 r2) in *.\n  assert (Hrf: reval_klist env errors2 r2 (ff_realfunc f4) = reval r4 env errors2) by reflexivity.\n  change  (max_error_var r4 <= si2)%positive in Hr2.\n  clearbody r4.\n  destruct f4 as [tys pre rf [f rel abs ACC]]; simpl in *.\n  move args before tys.\n  generalize dependent tys.\n  clear - Henv H0 Hsi Hr2.\n  induction args; intros.\n + simpl in *. rewrite (klist_nil pre), (klist_nil r2) in *. clear pre r2 H4.  simpl in *.\n     match type of H with (forall i, ?a = i \\/ False -> _) => assert (eval_cond1 env s' a) by (apply H; left; reflexivity) end.\n     clear H H5.\n     unfold func_no_overflow, no_overflow, rnd_of_func in H1. simpl in H1.\n     destruct (Relative.error_N_FLT Zaux.radix2 (3 - femax ty - fprec ty) (fprec ty) (fprec_gt_0 _)\n                        (fun x : Z => negb (Z.even x)) rf)\n          as [delta [epsilon [K0 [K1 [_ K3]]]]].\n     pose (errors3 i := if Pos.eq_dec i (Pos.succ si2) then adjust_err abs epsilon\n                          else if Pos.eq_dec i si2 then adjust_err rel delta else  errors2 i).\n     assert (errors_bounded s' errors3). {\n      intro. unfold errors3, s'.\n      rewrite !mget_set.\n      repeat destruct (Pos.eq_dec _ _); auto; clear - K0 K1.\n       apply  Rabs_adjust_le; auto.\n       apply  Rabs_adjust_le; auto.\n    }\n     assert (reval r4 env errors3 = reval r4 env errors2). {\n        apply reval_error_ext. intros. unfold errors3.\n        repeat destruct (Pos.eq_dec _ _); auto; lia.\n    }\n    destruct ACC as [RA [ER ACC]].\n     assert (rounded_finite ty rf). {\n       red. apply H1 in H. rewrite H2 in H.\n       rewrite !Rmult_1_r in *. rewrite Rmult_1_l in *.\n       change (SpecFloat.fexp (fprec ty) (femax ty)) with (FLT_exp (3 - femax ty - fprec ty) (fprec ty)).\n       change  (BinarySingleNaN.round_mode BinarySingleNaN.mode_NE)  with ZnearestE.\n       subst errors3. simpl in H. \n       assert (rel=0 \\/ rel <>0)%N by (clear; tauto).\n       destruct H3.\n       - assert (abs=0)%N by (rewrite <- RA; auto).  subst abs rel. specialize (ER (eq_refl _)). red in ER; rewrite ER.\n          repeat destruct (Pos.eq_dec _ _) in H; try lia. simpl in H. rewrite <- Hrf in H.\n          rewrite !Rmult_0_l in H. rewrite !Rplus_0_r in H. rewrite Rmult_1_r in H. lra.\n      - assert (abs<>0)%N by (clear - H3 RA; tauto).\n          repeat destruct (Pos.eq_dec _ _) in H; try lia. simpl in H. rewrite <- Hrf in H.\n          unfold adjust_err in H. destruct rel; try contradiction. destruct abs; try contradiction.\n          unfold Z.of_N in H.\n         unfold Rdiv in H. rewrite !(Rmult_comm _ (/ _)) in H. rewrite <- !(Rmult_assoc _ (/ _)) in H. \n         rewrite K3.\n        rewrite !Rinv_r in H. rewrite !Rmult_1_l in *. lra.\n        apply Qreals.IZR_nz.\n        apply Qreals.IZR_nz.\n      }\n     specialize (ACC H3). destruct ACC as [FIN [delta' [epsilon' [? [? ?]]]]].\n     pose (errors4 i := if Pos.eq_dec i (Pos.succ si2) then adjust_err abs epsilon'\n                          else if Pos.eq_dec i si2 then adjust_err rel delta' else  errors2 i).\n     assert (EB4: errors_bounded s' errors4). {\n      intro. unfold errors4, s'.\n      rewrite !mget_set.\n      repeat destruct (Pos.eq_dec _ _); auto; clear - H4 H5.\n      destruct abs; simpl. change R0 with 0. rewrite Rabs_R0. apply error_bound_nonneg.\n      change (error_bound _) with (default_abs ty). unfold Rdiv. rewrite Rabs_mult, Rabs_inv.\n      rewrite (Rabs_right (IZR _)) by (apply IZR_ge; lia). \n      apply Rdiv_le_left; [ apply IZR_lt; lia | rewrite Rmult_comm; auto].\n      destruct rel; simpl. change R0 with 0. rewrite Rabs_R0. apply error_bound_nonneg.\n      change (error_bound _) with (default_rel ty). unfold Rdiv. rewrite Rabs_mult, Rabs_inv.\n      rewrite (Rabs_right (IZR _)) by (apply IZR_ge; lia). \n      apply Rdiv_le_left; [ apply IZR_lt; lia | rewrite Rmult_comm; auto].\n    }\n      exists errors4; split; auto.\n      clear - Hsi; intros ? ?; subst errors4; simpl; repeat destruct (Pos.eq_dec _ _); auto; lia.\n      split; auto.\n      split; auto.\n     assert (reval r4 env errors4 = reval r4 env errors2). {\n        apply reval_error_ext. intros. unfold errors4.\n        repeat destruct (Pos.eq_dec _ _); auto; lia.\n    }\n      rewrite H7, <- Hrf. unfold errors4.\n        repeat destruct (Pos.eq_dec _ _); try lia.\n       rewrite !Rmult_1_r in *. \n        fold (FT2R f). rewrite H6. clear - H4 H5.\n        repeat f_equal.\n        destruct rel; simpl in *. rewrite Rmult_0_r. rewrite Rmult_0_l in H4.\n        assert (Rabs delta' = 0) by (pose proof (Rabs_pos delta'); lra).\n        apply Rabs_eq_R0 in H; auto.\n        unfold Rdiv. rewrite !(Rmult_comm _ (/ _)). rewrite <- !(Rmult_assoc _ (/ _)). \n        rewrite !Rinv_r by (apply IZR_neq; lia). rewrite !Rmult_1_l. auto.\n        destruct abs; simpl in *. rewrite Rmult_0_r. rewrite Rmult_0_l in H5.\n        assert (Rabs epsilon' = 0) by (pose proof (Rabs_pos epsilon'); lra).\n        apply Rabs_eq_R0 in H; auto.\n        unfold Rdiv. rewrite !(Rmult_comm _ (/ _)). rewrite <- !(Rmult_assoc _ (/ _)). \n        rewrite !Rinv_r by (apply IZR_neq; lia). rewrite !Rmult_1_l. auto.\n\n + apply Kforall_inv in H4. destruct H4.\n    change (Kforall\n       (fun (ty : type) (f : ftype ty) => is_finite (fprec ty) (femax ty) f = true)\n       (mapk (fun ty : type => fval env) args)) in H2.\n    destruct (klist_cons r2) as [r1 [r2' ?]]; subst r2; rename r2' into r2.\n    destruct (klist_cons pre) as [p1 [pre' ?]]; subst pre; rename pre' into pre.\n     simpl in ACC.  unfold eq_rect_r, eq_rect, eq_sym in ACC.\n     simpl in H5. inversion H5; clear H5; subst.\n     apply ProofIrrelevance.ProofIrrelevanceTheory.EqdepTheory.inj_pair2 in H6.\n     simpl in H. unfold eq_rect_r, eq_rect, eq_sym in H.\n      simpl in Hrf.\n     pose (errors2' i := if Pos.eq_dec i (Pos.succ si2) then 0\n                          else if Pos.eq_dec i si2 then 0 else  errors2 i).\n     simpl in MEV.\n     assert (MEV1: (max_error_var r1 <= si2)%positive) by (clear - MEV; lia).\n     assert (MEV': (max_error_var_klist tys r2 <= si2)%positive) by (clear - MEV; lia). clear MEV.\n     assert (EB4: errors_bounded s' errors2'). {\n       intro. specialize (H0 i). unfold s', errors2'. clear - H0.\n       rewrite !mget_set. \n       repeat destruct (Pos.eq_dec _ _); auto; subst; rewrite Rabs_R0; apply error_bound_nonneg.\n     }\n      assert (interp_bounds p1 (fval env k) = true). {\n         clear - H4 H H1 Hsi Henv EB4 MEV1.\n         assert (reval r1 env errors2 = reval r1 env errors2'). {\n               apply reval_error_ext; intros; unfold errors2'.\n                   repeat destruct (Pos.eq_dec _ _); try lia; auto.\n         }\n          unfold bounds_to_cond in H.\n          destruct p1 as [[lo blo] [hi bhi]]; simpl; rewrite andb_true_iff; split.\n          - destruct (vacuous_lo_bound (lo, blo, (hi, bhi))) eqn:?H.\n           + destruct blo, lo; try destruct s; try discriminate; destruct (fval env k); try destruct s; try discriminate; reflexivity.\n           + destruct (is_finite (fprec ty0) (femax ty0) lo) eqn:?H.\n             * apply (H (RBinop Tree.Sub r1 (RAtom (RConst (B2F lo))), blo)) in EB4; simpl in EB4.\n                rewrite <- H0, H4, F2R_B2F in EB4 by auto.\n                destruct blo; unfold BCMP, extend_comp; simpl; rewrite Bcompare_correct; auto;\n                destruct (Rcompare_spec (B2R _ _ lo) (B2R _ _ (fval env k))); auto; lra.\n                rewrite in_app_iff; simpl; auto.\n             * apply (H False_cond) in EB4; simpl in EB4. lra. rewrite in_app_iff; simpl; auto.\n          - destruct (vacuous_hi_bound (lo, blo, (hi, bhi))) eqn:?H.\n           + destruct bhi, hi; try destruct s; try discriminate; destruct (fval env k); try destruct s; try discriminate; reflexivity.\n           + destruct (is_finite (fprec ty0) (femax ty0) hi) eqn:?H.\n             * apply (H (RBinop Tree.Sub (RAtom (RConst (B2F hi))) r1, bhi)) in EB4; simpl in EB4.\n                rewrite <- H0, H4, F2R_B2F in EB4 by auto.\n                destruct bhi; unfold BCMP, extend_comp; simpl; rewrite Bcompare_correct; auto;\n                destruct (Rcompare_spec (B2R _ _ (fval env k))  (B2R _ _ hi)); auto; lra.\n                rewrite !in_app_iff; simpl; auto.\n             * apply (H False_cond) in EB4; simpl in EB4. lra. rewrite !in_app_iff; simpl; auto.\n        }\n     specialize (ACC _ H3).\n     apply (IHargs _ _ _ ACC r2); clear IHargs ACC; auto.\n     intros; apply H; simpl; rewrite in_app_iff. clear - H5; tauto.\n     rewrite <- Hrf, H4; auto.\nQed.\n\nDefinition empty_shiftmap := mempty (Tdouble, Unknown').\n\nDefinition environ := forall ty : type, FPLang.V -> ftype ty.\n\nDefinition env_all_finite (env: environ) :=\n  forall (ty : type) (i : FPLang.V),\n        is_finite (fprec ty) (femax ty) (env ty i) = true.\n\nDefinition eval_cond (s: MSHIFT) (c: cond) (env: environ) : Prop :=\n  eval_cond1 env s c.\n\nDefinition rndval_with_cond {ty} (e: expr ty) : rexpr * MSHIFT * list (environ -> Prop) :=\n let '((r,(si,s)),p) := rndval_with_cond' 1%positive empty_shiftmap e\n  in (r, s, map (eval_cond s) p).\n\nTheorem rndval_with_cond_correct \n    env (Henv: env_all_finite env) {ty} (e: expr ty):\n  expr_valid e = true ->\n  forall r s p,\n    rndval_with_cond e = (r, s, p) ->\n    Forall (fun c => c env) p ->\n    exists errors,\n        (errors_bounded s errors)\n        /\\\n        let fv := fval env e in\n        is_finite _ _ fv = true\n        /\\\n        reval r env errors = B2R _ _ fv\n.\nProof.\nintros.\nunfold rndval_with_cond in H0.\ndestruct (rndval_with_cond' _ empty_shiftmap e) as [[r' [si s']] p'] eqn:?H.\ninversion H0; clear H0; subst r' s' p.\nassert (forall i : cond, In i p' -> eval_cond1 env s i). {\n  intros.\n  rewrite Forall_forall in H1.\n  apply H1. \n  rewrite in_map_iff.\n  exists i; auto.\n}\ndestruct (rndval_with_cond_correct' env Henv ty e H 1 empty_shiftmap r _ _ _ H2 H0\n (fun _ => 0%R))\n  as [errors2 [? [? [? ?]]]].\n-\nintros. intro.\nrewrite Rabs_R0. apply error_bound_nonneg.\n-\nexists errors2; split; auto.\nQed.\n\nEnd WITH_NAN.\n\n\n", "meta": {"author": "VeriNum", "repo": "vcfloat", "sha": "9cad8c4b48fe4353d01f02f6dc5bd03e1ea4eb5c", "save_path": "github-repos/coq/VeriNum-vcfloat", "path": "github-repos/coq/VeriNum-vcfloat/vcfloat-9cad8c4b48fe4353d01f02f6dc5bd03e1ea4eb5c/vcfloat/Rounding.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.26064533047214716}}
{"text": "(* En este archivo se demuestra la corrección de la acción grant*)\nRequire Export Exec.\nRequire Export Implementacion.\nRequire Export AuxFunsCorrect.\nRequire Export ListAuxFuns.\nRequire Import Classical.\nRequire Import Estado.\nRequire Import DefBasicas.\nRequire Import EqTheorems.\nRequire Import Semantica.\nRequire Import RuntimePermissions.\nRequire Import Operaciones.\nRequire Import ErrorManagement.\nRequire Import Maps.\nRequire Import Tacticas.\nRequire Import ValidStateLemmas.\n\nSection Grant.\n\n\nLemma postGrantCorrect : forall (s:System) (a:idApp) (p:Perm), (pre (grant p a) s) -> validstate s -> post_grant p a s (grant_post p a s).\nProof.\n    intros.\n    unfold post_grant.\n    split. simpl; auto.\n    simpl in H.\n    unfold pre_grant in H;simpl in H.\n    destruct H.\n\n    split.\n    destruct H.\n    destruct H.\n    assert (In a (apps (state s)) \\/ (exists sysapp:SysImgApp, In sysapp (systemImage (environment s)) /\\ idSI sysapp = a)).\n    destruct H.\n    left.\n    apply (ifManifestThenInApps s H0 a x);auto.\n    right.\n    destruct H.\n    destruct_conj H.\n    exists x0;auto.\n    assert (exists v, map_apply idApp_eq (perms (state s)) a = Value idApp v).\n    apply (ifInAppsOrSysAppThenPerms);auto.\n    destruct H4.\n    unfold grantPerm.\n    unfold grant_post;unfold grantPermission;simpl.\n    rewrite H4.\n    split;intros.\n    elim (classic (a=a'));intros.\n    \n    exists (p::x0).\n    split.\n    rewrite H6.\n    rewrite<- (addAndApply idApp_eq a' (p::x0) (perms (state s))).\n    auto.\n    rewrite H6 in H4.\n    rewrite H4 in H5.\n    assert (x0=lPerm).\n    inversion H5.\n    auto.\n    intros.\n    rewrite H7.\n    apply in_cons.\n    auto.\n    \n    exists lPerm.\n    split.\n    rewrite overrideNotEq; auto.\n    intros.\n    auto.\n    \n    split;intros.\n    elim (classic (a=a'));intro.\n    \n    \n    exists x0.\n    split.\n    rewrite H6 in H4.\n    auto.\n    intros.\n    split;auto.\n    rewrite H6 in H5.\n    rewrite <-(addAndApply idApp_eq a' (p::x0) (perms (state s))) in H5.\n    inversion H5.\n    rewrite <-H10 in H7.\n    inversion H7.\n    auto.\n    contradiction.\n    \n    exists lPerm'.\n    rewrite overrideNotEq in H5.\n    split;auto.\n    intros;contradiction.\n    auto.\n    split.\n    exists (p::x0).\n    split.\n    symmetry.\n    apply addAndApply.\n    apply in_eq.\n    apply addPreservesCorrectness.\n    apply permsCorrect;auto.\n\n    split.\n    - intros.\n      (* Vamos a necesitar la información que está en la última conjunción de H1 *)\n      destruct H1 as [_ [_ [_ H1]]].\n      destruct H1.\n      (* En este caso tenemos un absurdo *)\n      rewrite H1 in H2. inversion H2.\n      (* Caso interesante *)\n      destruct H1 as [g' [lGroup [H1 [H3 H4]]]].\n      unfold grantPermGroup, grant_post.\n      rewrite H2. simpl.\n      unfold grantPermissionGroup.\n      rewrite H3.\n      split.\n      (* Acá empezamos a probar las conjunciones que forman grantPermGroup *)\n      (* Primer conjunción *)\n      intros a' lGroup' H5. simpl.\n      elim (classic (a = a')); intros.\n      (* Caso a=a' *)\n   -- rewrite H6.\n      rewrite <- addAndApply. exists (g :: lGroup).\n      split. auto.\n      intros g'' H7. simpl.\n      rewrite <- H6 in H5. rewrite H3 in H5.\n      inversion H5. auto.\n      (* Caso a<>a' *)\n   -- exists lGroup'.\n      split. rewrite overrideNotEq; auto.\n      intros. auto.\n      (* Segunda conjunción *)\n   -- split.\n  --- intros a' lGroup' H5.\n      elim (classic (a = a')); intros.\n      (* Caso a=a' *)\n      exists lGroup.\n      split. rewrite <- H6. auto.\n      intros g'' H7 H8.\n      rewrite <- H6 in H5.\n      rewrite <- addAndApply in H5.\n      inversion H5.\n      rewrite <- H10 in H7.\n      destruct H7. auto. contradiction.\n      (* Caso a <> a' *)\n      exists lGroup'.\n      rewrite overrideNotEq in H5.\n      split. auto.\n      intros. contradiction.\n      auto.\n  --- split. exists (g :: lGroup).\n      split. symmetry. apply addAndApply.\n      simpl. auto.\n      apply addPreservesCorrectness.\n      apply grantedPermGroupsCorrect;auto.\n    - split.\n      intro notGrouped.\n      destruct H1 as [_ [_ [_ H1]]].\n      destruct H1.\n   -- unfold grant_post. simpl. rewrite notGrouped. auto.\n   -- destruct H1 as [g [lGroup [H2 [H3 H4]]]].\n      rewrite notGrouped in H2. inversion H2.\n   -- repeat (split;auto).\nQed.\n\nLemma existsManifest : forall (a: idApp) (s: System) (p: Perm),\n  negb (InBool Perm Perm_eq p (permsInUse a s)) = false ->\n    exists m : Manifest, isManifestOfApp a m s /\\ In p (use m).\nProof.\n  intros a s p H.\n  rewrite negb_false_iff in H.\n  unfold InBool in H.\n  rewrite existsb_exists in H.\n  destruct H as [perm H].\n  destruct H as [H H0].\n  unfold permsInUse in H.\n\n  unfold isManifestOfApp.\n  case_eq (map_apply idApp_eq (manifest (environment s)) a); intros m H1; rewrite H1 in *.\n  exists m.\n  destruct Perm_eq in H0.\n  rewrite e.\n  split;auto.\n  discriminate H0.\n\n  case_eq ((map (fun sysapp : SysImgApp => use (manifestSI sysapp)) (filter (fun sysapp : SysImgApp => if idApp_eq a (idSI sysapp) then true else false) (systemImage (environment s)))));intros; rewrite H2 in *;simpl in H.\n  destruct H.\n  assert (In l (map (fun sysapp : SysImgApp => use (manifestSI sysapp)) (filter (fun sysapp : SysImgApp => if idApp_eq a (idSI sysapp) then true else false) (systemImage (environment s))))).\n  rewrite H2.\n  apply in_eq.\n  rewrite in_map_iff in H3.\n  destruct H3 as [sysImg H3].\n  destruct H3.\n  exists (manifestSI sysImg).\n  split.\n  right.\n  exists sysImg.\n  rewrite filter_In in H4.\n  destruct H4.\n  destruct idApp_eq in H5.\n  rewrite e;auto.\n  discriminate H5.\n  destruct Perm_eq in H0.\n  rewrite e.\n  rewrite H3 in *.\n  auto.\n  discriminate H0.\nQed.\n\nLemma notPreGrantThenError : forall (s:System) (a:idApp) (p:Perm), ~(pre (grant p a) s) -> validstate s -> exists ec : ErrorCode, response (step s (grant p a)) = error ec /\\ ErrorMsg s (grant p a) ec /\\ s = system (step s (grant p a)).\nProof.\n    intros.\n    simpl.\n    simpl in H.\n    unfold pre_grant in H.\n    unfold grant_safe.\n    unfold grant_pre.\n    \n    case_eq (negb (InBool Perm Perm_eq p (permsInUse a s)));intros.\n    exists perm_not_in_use.\n    split;auto.\n    split;auto.\n    rewrite negb_true_iff in H1.\n    invertBool H1.\n    intro.\n    apply H1.\n    destruct H2.\n    unfold InBool.\n    rewrite existsb_exists.\n    exists p.\n    unfold permsInUse.\n    destruct H2.\n    rewrite H2.\n    destruct Perm_eq;auto.\n\n\n    case_eq (negb (InBool Perm Perm_eq p (getAllPerms s)));intros.\n    exists no_such_perm.\n    split;auto.\n    split;auto.\n    rewrite negb_true_iff in H2.\n    invertBool H2.\n    intro;apply H2.\n    unfold getAllPerms.\n    unfold InBool.\n    rewrite existsb_exists.\n    exists p.\n    rewrite in_app_iff.\n    split.\n    destruct H3.\n    left.\n    apply isSysPermCorrect;auto.\n    right.\n    apply inUsrDefPermsIff;auto.\n    destruct Perm_eq;auto.\n\n    case_eq (InBool Perm Perm_eq p (grantedPermsForApp a s));intros.\n    exists perm_already_granted.\n    split;auto.\n    split;auto.\n    unfold InBool in H3.\n    rewrite existsb_exists in H3.\n    destruct H3.\n    destruct H3.\n    unfold grantedPermsForApp in H3.\n    case_eq (map_apply idApp_eq (perms (state s)) a);intros; rewrite H5 in H3.\n    exists l.\n    destruct Perm_eq in H4.\n    rewrite e;auto.\n    discriminate H4.\n    inversion H3.\n    case_eq ((if permLevel_eq (pl p) dangerous then false else true));intros.\n    exists perm_not_dangerous.\n    split;auto.\n    split;auto.\n    destruct permLevel_eq in H4.\n    discriminate H4.\n    auto.\n\n    case_eq (groupIsGranted a p s); intros.\n    exists perm_should_auto_grant. simpl.\n    split; auto.\n    unfold groupIsGranted in H5.\n    case (maybeGrp p) in *.\n    case (map_apply idApp_eq (grantedPermGroups (state s)) a) in *.\n    split.\n  - unfold InBool in H5.\n    rewrite existsb_exists in H5.\n    destruct H5 as [g [H5 H6]].\n    exists g, l.\n    destruct idGrp_eq in H6. rewrite e.\n    auto. inversion H6.\n  - auto.\n  - inversion H5.\n  - inversion H5.\n  - destruct H.\n    split.\n    apply existsManifest; auto.\n\n    split.\n    rewrite negb_false_iff in H2.\n    unfold InBool in H2.\n    rewrite existsb_exists in H2.\n    destruct H2.\n    destruct H.\n    destruct Perm_eq in H2.\n    rewrite e.\n    unfold getAllPerms in H.\n    rewrite in_app_iff in H.\n    destruct H.\n    left.\n    apply isSysPermCorrect;auto.\n    right.\n    apply inUsrDefPermsIff;auto.\n    discriminate H2.\n    split.\n    invertBool H3.\n    intro;apply H3.\n    unfold InBool.\n    rewrite existsb_exists.\n    exists p.\n    destruct H.\n    destruct H.\n    unfold grantedPermsForApp.\n    rewrite H.\n    destruct Perm_eq;auto.\n    split.\n    destruct permLevel_eq in H4.\n    auto.\n    discriminate H4.\n    unfold groupIsGranted in H5.\n    destruct (maybeGrp p).\n -- right.\n    case_eq (map_apply idApp_eq (grantedPermGroups (state s)) a);intros.\n--- rewrite H in H5.\n    exists i, l.\n    repeat split; auto.\n    unfold InBool in H5.\n    clear H. induction l;unfold not; intros.\n    inversion H.\n    simpl in H, H5.\n    destruct (idGrp_eq i a0); simpl in H5.\n    inversion H5.\n    destruct H. symmetry in H. contradiction.\n    apply IHl in H5. contradiction.\n--- clear H5.\n    apply existsManifest in H1.\n    destruct H1 as [m [H1 _]].\n    assert (vs:= H0).\n    destructVS H0.\n    destructSC statesConsistencyVS a.\n    destruct grantedPermGroupsSC.\n    assert (exists l : list idGrp,\n       map_apply idApp_eq (grantedPermGroups (state s)) a = Value idApp l).\n    destruct H1. clear mfstSC certSC defPermsSC permsSC.\n    apply ifManifestThenInApps in H1; auto.\n    apply H0. right. destruct H1 as [sysImg [H6 [H7 H8]]].\n    exists sysImg; auto.\n    destruct H6. rewrite H in H6. inversion H6.\n -- left. auto.\nQed.\n\n\nLemma grantIsSound : forall (s:System) (a:idApp) (p:Perm),\n        validstate s -> exec s (grant p a) (system (step s (grant p a))) (response (step s (grant p a))).\nProof.\n    intros.\n    unfold exec.\n    split.\n    auto.\n    elim (classic (pre (grant p a) s));intro.\n    left.\n    assert(grant_pre p a s = None).\n    unfold grant_pre.\n    destruct H0.\n\n    assert (InBool Perm Perm_eq p (permsInUse a s) = true).\n    unfold InBool.\n    rewrite existsb_exists.\n    exists p.\n    split.\n    destruct H0.\n    destruct H0.\n    unfold permsInUse.\n    destruct H0.\n    rewrite H0.\n    auto.\n    case_eq (map_apply idApp_eq (manifest (environment s)) a);intros.\n    apply ifManifestThenInApps in H3;auto.\n    destruct H0.\n    assert (~(In a (apps (state s)) /\\ In x0 (systemImage (environment s)) /\\ idSI x0 = a)).\n    apply sysAppInApps;auto.\n    destruct_conj H0.\n    destruct H4;auto.\n    destruct H0.\n    destruct_conj H0.\n    assert (In x0 (filter (fun sysapp : SysImgApp => if idApp_eq a (idSI sysapp) then true else false) (systemImage (environment s)))).\n    rewrite filter_In.\n    rewrite H0.\n    destruct idApp_eq;auto.\n    remember (fun sysapp : SysImgApp => use (manifestSI sysapp)) as theFun.\n    remember (filter (fun sysapp : SysImgApp => if idApp_eq a (idSI sysapp) then true else false) (systemImage (environment s))) as theList.\n    assert ((hd nil (map theFun theList)) = theFun (hd defaultSysApp theList )).\n    apply ifNotNilHdMap.\n    apply inNotNilExists.\n    exists x0;auto.\n    rewrite H7.\n    rewrite HeqtheFun.\n    assert ((hd defaultSysApp theList)=x0).\n    rewrite HeqtheList in H5.\n    assert (exists x0, In x0 (filter (fun sysapp : SysImgApp => if idApp_eq a (idSI sysapp) then true else false) (systemImage (environment s)))).\n    exists x0;auto.\n    apply ifExistsFilter with (dflt:=defaultSysApp) in H8.\n    rewrite HeqtheList.\n    remember (hd defaultSysApp (filter (fun sysapp : SysImgApp => if idApp_eq a (idSI sysapp) then true else false) (systemImage (environment s)))) as theHead.\n    destruct H8.\n    apply (notDupSysAppVS s);auto.\n    rewrite H0 in *.\n    destruct idApp_eq in H9;auto.\n    discriminate H9.\n\n    rewrite H8;rewrite H6;auto.\n\n\n\n\n    destruct Perm_eq.\n    auto.\n    auto.\n    rewrite H2.\n    assert (negb true=false).\n    rewrite negb_false_iff;auto.\n    rewrite H3.\n\n    assert (InBool Perm Perm_eq p (getAllPerms s) = true).\n    unfold InBool.\n    rewrite existsb_exists.\n    exists p.\n    split.\n    destruct H1.\n    unfold getAllPerms.\n    apply in_app_iff.\n    destruct H1.\n    left.\n    apply isSysPermCorrect;auto.\n    right.\n    unfold usrDefPerms.\n    apply in_concat.\n    unfold usrDefPerm in H1.\n    destruct H1.\n    destruct H1.\n    destruct H1.\n    destruct H1.\n    exists x0.\n    split.\n    apply in_app_iff.\n    left.\n    apply inGetValuesBack.\n    exists (map_apply idApp_eq (defPerms (environment s)) x).\n    split.\n    apply in_map_iff.\n    exists x.\n    split.\n    auto.\n    apply (ifDefPermsThenInApps s H x x0);auto.\n    auto.\n    auto.\n    destruct H1.\n    destruct H1.\n    exists (defPermsSI x).\n    split.\n    apply in_app_iff.\n    right.\n    apply in_map_iff.\n    exists x.\n    split;auto.\n    auto.\n    destruct Perm_eq.\n    auto.\n    destruct n;auto.\n    rewrite H4.\n    assert (negb true=false).\n    rewrite negb_false_iff;auto.\n    rewrite H3.\n\n    assert (InBool Perm Perm_eq p (grantedPermsForApp a s) <> true).\n    unfold InBool.\n    unfold not;intros.\n    rewrite existsb_exists in H6.\n    destruct H6.\n    destruct H6.\n    destruct H1.\n    apply H8.\n    unfold grantedPermsForApp in H6.\n    case_eq (map_apply idApp_eq (perms (state s)) a);intros; rewrite H9 in H6.\n    exists l.\n    destruct Perm_eq in H7.\n    rewrite<- e in H6.\n    split;auto.\n    discriminate H7.\n    destruct H6.\n    rewrite not_true_iff_false in H6.\n    rewrite H6.\n    destruct_conj H1.\n    destruct permLevel_eq.\n    unfold groupIsGranted.\n    destruct H10.\n    rewrite H9. auto.\n    destruct H9 as [g [lGroup [H9 [H10 H11]]]].\n    rewrite H9. rewrite H10.\n    case_eq (InBool idGrp idGrp_eq g lGroup); intros.\n    unfold InBool in H12.\n    rewrite existsb_exists in H12.\n    destruct H12 as [g' [H12 H13]].\n    destruct (idGrp_eq g g').\n\n    rewrite <- e0 in H12. contradiction.\n\n    inversion H13.\n\n    auto.\n\n    contradiction.\n\n    unfold step;simpl.\n    unfold grant_safe;simpl.\n    rewrite H1;simpl.\n    split;auto.\n    split;auto.\n    apply postGrantCorrect;auto.\n    right.\n    apply (notPreGrantThenError);auto.\nQed.\nEnd Grant.\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/GrantIsSound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.26062180403864277}}
{"text": "Require Import Platform.Cito.CompileStmtSpec.\nRequire Import Bedrock.StringSet.\nImport StringSet.\nRequire Import Platform.Cito.FreeVars.\nRequire Import Platform.Cito.SynReqFactsUtil.\n\nLocal Infix \";;\" := Syntax.Seq (right associativity, at level 95).\n\nLocal Hint Resolve Subset_singleton.\nLocal Hint Resolve In_to_set.\nLocal Hint Resolve to_set_In.\nLocal Hint Resolve Subset_union_right Max.max_lub.\n\nRequire Platform.Cito.CompileExpr Platform.Cito.CompileExprs Platform.Cito.SaveRet.\n\nLtac t := unfold syn_req, CompileExpr.syn_req, CompileExprs.syn_req, SaveRet.syn_req,\n  in_scope, WellFormed.wellformed;\n  simpl; intuition;\n    repeat (match goal with\n              | [ H : Subset _ _ |- _ ] => apply Subset_union_left in H\n              | [ H : (max _ _ <= _)%nat |- _ ] =>\n                generalize (Max.max_lub_l _ _ _ H);\n                  generalize (Max.max_lub_r _ _ _ H);\n                    clear H\n              | [ H : WellFormed.args_not_too_long _ |- _ ] => inversion_clear H; []\n              | [ |- match ?E with Some _ => _ | None => _ end ] => destruct E\n            end; intuition).\n\nLocal Hint Constructors WellFormed.args_not_too_long.\n\nLemma Subset_syn_req_In : forall x vars temp_size s, syn_req vars temp_size s -> Subset (singleton x) (free_vars s) -> List.In x vars.\n  t.\nQed.\n\nLemma syn_req_Seq_Seq : forall vars temp_size a b c, syn_req vars temp_size ((a ;; b) ;; c) -> syn_req vars temp_size (a ;; b ;; c).\n  t.\nQed.\n\nLemma syn_req_Seq : forall vars temp_size a b c, syn_req vars temp_size ((a ;; b) ;; c) -> syn_req vars temp_size (b ;; c).\n  t.\nQed.\n\nLemma syn_req_If_true : forall vars temp_size e t f k, syn_req vars temp_size (Syntax.If e t f ;; k) -> syn_req vars temp_size (t ;; k).\n  t.\nQed.\n\nLemma syn_req_If_false : forall vars temp_size e t f k, syn_req vars temp_size (Syntax.If e t f ;; k) -> syn_req vars temp_size (f ;; k).\n  t.\nQed.\n\nLemma syn_req_If_e : forall vars temp_size e t f k, syn_req vars temp_size (Syntax.If e t f ;; k) -> CompileExpr.syn_req vars temp_size e 0.\n  t.\nQed.\n\nLemma syn_req_While_e : forall vars temp_size e s k, syn_req vars temp_size (Syntax.While e s ;; k) -> CompileExpr.syn_req vars temp_size e 0.\n  t.\nQed.\n\nLemma syn_req_While : forall vars temp_size e s k, syn_req vars temp_size (Syntax.While e s ;; k) -> syn_req vars temp_size (s ;; Syntax.While e s ;; k).\n  t.\nQed.\n\nLemma syn_req_Call_f : forall vars temp_size x f args k, syn_req vars temp_size (Syntax.Call x f args ;; k) -> CompileExpr.syn_req vars temp_size f 0.\n  t.\nQed.\n\nLocal Hint Resolve Max.le_max_l Max.le_max_r.\n\nLemma max_more : forall n m k,\n  (n <= m)%nat\n  -> (n <= max m k)%nat.\n  intros; transitivity m; eauto.\nQed.\n\nLocal Hint Resolve max_more.\n\nRequire Import Coq.Lists.List.\n\nLemma args_bound' : forall x args,\n  In x args\n  -> (DepthExpr.depth x <= fold_right max 0 (map DepthExpr.depth args))%nat.\n  induction args; simpl; intuition (subst; auto).\n  eapply Le.le_trans; [ | eapply Max.le_max_r]; eauto.\nQed.\n\nLemma args_bound : forall args,\n  List.Forall (fun e => (DepthExpr.depth e <= CompileExprs.depth args)%nat) args.\n  intros; apply Forall_forall; intros.\n  apply args_bound'; auto.\nQed.\n\nLocal Hint Resolve args_bound.\n\nLemma syn_req_Call_args : forall vars temp_size x f args k, syn_req vars temp_size (Syntax.Call x f args ;; k) -> CompileExprs.syn_req vars temp_size args args 0.\n  t.\nQed.\n\nLemma syn_req_Call_ret : forall vars temp_size x f args k, syn_req vars temp_size (Syntax.Call x f args ;; k) -> SaveRet.syn_req vars x.\n  t.\nQed.\n\nRequire Import Platform.AutoSep.\n\nLemma syn_req_goodSize : forall vars temp_size x f args k, syn_req vars temp_size (Syntax.Call x f args ;; k) -> goodSize (2 + List.length args).\n  t.\nQed.\n\nLemma syn_req_Seq_Skip : forall vars temp_size s, syn_req vars temp_size s -> syn_req vars temp_size (s ;; Syntax.Skip).\n  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/Cito/SynReqFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2606217981738243}}
{"text": "Require Import floyd.proofauto.\nRequire Import 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 el,\n   quick_shortcut_logical s = Some tid ->\n   typeof_temp Delta tid = Some tint ->\n   local2ptree Q = (Qtemp, Qvar, nil, nil) ->\n   Qtemp ! tid = None ->\n   shortcut_logical (msubst_eval_expr Qtemp Qvar) 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 u : unit\n  PRE  [] main_pre prog nil u\n  POST [ tint ] main_post prog nil u.\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 all_funcs_correct:\n  semax_func Vprog Gprog (prog_funct prog) Gprog.\nProof.\nunfold Gprog, prog, prog_funct; simpl.\nsemax_func_cons body_do_or.\nsemax_func_cons body_do_and.\nsemax_func_cons body_main.\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_logical_compare.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.4765796510636759, "lm_q1q2_score": 0.26056427065648846}}
{"text": "Require Import CoqlibC Maps.\nRequire Import ValuesC.\nRequire Import LocationsC Stacklayout Conventions.\nRequire Import MemoryC Integers AST.\n(** newly added **)\nRequire Import Asm.\nRequire Import Locations.\nRequire Mach.\n\nSet Implicit Arguments.\n\nLemma to_mreg_injective\n      pr0 pr1\n      (SOME: is_some ((to_mreg pr0)))\n      (EQ: (to_mreg pr0) = (to_mreg pr1)):\n    <<EQ: pr0 = pr1>>.\nProof. destruct pr0; ss; destruct pr1; ss; des_ifs. Qed.\n\nLemma preg_of_injective\n      mr0 mr1\n      (EQ: preg_of mr0 = preg_of mr1):\n    <<EQ: mr0 = mr1>>.\nProof. destruct mr0, mr1; ss. Qed.\n\nLemma to_mreg_to_preg: forall pr0,\n    o_map ((to_mreg pr0)) (to_preg) = Some pr0 \\/ (to_mreg pr0) = None.\nProof. destruct pr0; ss; des_ifs; eauto. Qed.\n\nCorollary to_mreg_some_to_preg\n      pr0 mr0\n      (SOME: (to_mreg pr0) = Some mr0):\n    <<EQ: (to_preg mr0) = pr0>>.\nProof.\n  eapply to_mreg_injective with (pr0 := (to_preg mr0)) (pr1 := pr0).\n  { rewrite to_preg_to_mreg; ss. }\n  rewrite to_preg_to_mreg; ss.\nQed.\n\nDefinition to_pregset (mrs: Mach.regset): regset :=\n  fun pr =>\n    match (to_mreg pr) with\n    | Some mr => mrs mr\n    | None => Vundef\n    end.\n\nDefinition to_mregset (prs: regset): Mach.regset :=\n  fun mr => prs (to_preg mr).\n\nLemma to_mreg_preg_of\n      pr mr\n      (MR: Asm.to_mreg pr = Some mr):\n    <<PR: preg_of mr = pr>>.\nProof. destruct mr, pr; ss; des_ifs. Qed.\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/AsmregsC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.2605005701429107}}
{"text": "(*(*\n * Vericert: Verified high-level synthesis.\n * Copyright (C) 2020 Yann Herklotz <yann@yannherklotz.com>\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 <https://www.gnu.org/licenses/>.\n *)\n\n(* begin hide *)\nFrom bbv Require Import Word.\nFrom bbv Require HexNotation WordScope.\nFrom Coq Require Import ZArith.ZArith FSets.FMapPositive Lia.\nFrom compcert Require Import lib.Integers common.Values.\nFrom vericert Require Import Vericertlib.\n(* end hide *)\n\n(** * Value\n\nA [value] is a bitvector with a specific size. We are using the implementation\nof the bitvector by mit-plv/bbv, because it has many theorems that we can reuse.\nHowever, we need to wrap it with an [Inductive] so that we can specify and match\non the size of the [value]. This is necessary so that we can easily store\n[value]s of different sizes in a list or in a map.\n\nUsing the default [word], this would not be possible, as the size is part of the type. *)\n\nRecord value : Type :=\n  mkvalue {\n    vsize: nat;\n    vword: word vsize\n  }.\n\n(** ** Value conversions\n\nVarious conversions to different number types such as [N], [Z], [positive] and\n[int], where the last one is a theory of integers of powers of 2 in CompCert. *)\n\nDefinition wordToValue : forall sz : nat, word sz -> value := mkvalue.\n\nDefinition valueToWord : forall v : value, word (vsize v) := vword.\n\nDefinition valueToNat (v :value) : nat :=\n  wordToNat (vword v).\n\nDefinition natToValue sz (n : nat) : value :=\n  mkvalue sz (natToWord sz n).\n\nDefinition valueToN (v : value) : N :=\n  wordToN (vword v).\n\nDefinition NToValue sz (n : N) : value :=\n  mkvalue sz (NToWord sz n).\n\nDefinition ZToValue (s : nat) (z : Z) : value :=\n  mkvalue s (ZToWord s z).\n\nDefinition valueToZ (v : value) : Z :=\n  wordToZ (vword v).\n\nDefinition uvalueToZ (v : value) : Z :=\n  uwordToZ (vword v).\n\nDefinition posToValue sz (p : positive) : value :=\n  ZToValue sz (Zpos p).\n\nDefinition posToValueAuto (p : positive) : value :=\n  let size := Pos.to_nat (Pos.size p) in\n  ZToValue size (Zpos p).\n\nDefinition valueToPos (v : value) : positive :=\n  Z.to_pos (uvalueToZ v).\n\nDefinition intToValue (i : Integers.int) : value :=\n  ZToValue Int.wordsize (Int.unsigned i).\n\nDefinition valueToInt (i : value) : Integers.int :=\n  Int.repr (uvalueToZ i).\n\nDefinition ptrToValue (i : Integers.ptrofs) : value :=\n  ZToValue Ptrofs.wordsize (Ptrofs.unsigned i).\n\nDefinition valueToPtr (i : value) : Integers.ptrofs :=\n  Ptrofs.repr (uvalueToZ i).\n\nDefinition valToValue (v : Values.val) : option value :=\n  match v with\n  | Values.Vint i => Some (intToValue i)\n  | Values.Vptr b off => if Z.eqb (Z.modulo (uvalueToZ (ptrToValue off)) 4) 0%Z\n                         then Some (ptrToValue off)\n                         else None\n  | Values.Vundef => Some (ZToValue 32 0%Z)\n  | _ => None\n  end.\n\n(** Convert a [value] to a [bool], so that choices can be made based on the\nresult. This is also because comparison operators will give back [value] instead\nof [bool], so if they are in a condition, they will have to be converted before\nthey can be used. *)\n\nDefinition valueToBool (v : value) : bool :=\n  negb (weqb (@wzero (vsize v)) (vword v)).\n\nDefinition boolToValue (sz : nat) (b : bool) : value :=\n  natToValue sz (if b then 1 else 0).\n\n(** ** Arithmetic operations *)\n\nDefinition unify_word (sz1 sz2 : nat) (w1 : word sz2): sz1 = sz2 -> word sz1.\nintros; subst; assumption. Defined.\n\nLemma unify_word_unfold :\n  forall sz w,\n  unify_word sz sz w eq_refl = w.\nProof. auto. Qed.\n\nDefinition value_eq_size:\n  forall v1 v2 : value, { vsize v1 = vsize v2 } + { True }.\nProof.\n  intros; destruct (Nat.eqb (vsize v1) (vsize v2)) eqn:?.\n  left; apply Nat.eqb_eq in Heqb; assumption.\n  right; trivial.\nDefined.\n\nDefinition map_any {A : Type} (v1 v2 : value) (f : word (vsize v1) -> word (vsize v1) -> A)\n           (EQ : vsize v1 = vsize v2) : A :=\n    let w2 := unify_word (vsize v1) (vsize v2) (vword v2) EQ in\n    f (vword v1) w2.\n\nDefinition map_any_opt {A : Type} (sz : nat) (v1 v2 : value) (f : word (vsize v1) -> word (vsize v1) -> A)\n  : option A :=\n  match value_eq_size v1 v2 with\n  | left EQ =>\n    Some (map_any v1 v2 f EQ)\n  | _ => None\n  end.\n\nDefinition map_word (f : forall sz : nat, word sz -> word sz) (v : value) : value :=\n  mkvalue (vsize v) (f (vsize v) (vword v)).\n\nDefinition map_word2 (f : forall sz : nat, word sz -> word sz -> word sz) (v1 v2 : value)\n           (EQ : (vsize v1 = vsize v2)) : value :=\n    let w2 := unify_word (vsize v1) (vsize v2) (vword v2) EQ in\n    mkvalue (vsize v1) (f (vsize v1) (vword v1) w2).\n\nDefinition map_word2_opt (f : forall sz : nat, word sz -> word sz -> word sz) (v1 v2 : value)\n  : option value :=\n  match value_eq_size v1 v2 with\n  | left EQ => Some (map_word2 f v1 v2 EQ)\n  | _ => None\n  end.\n\nDefinition eq_to_opt (v1 v2 : value) (f : vsize v1 = vsize v2 -> value)\n  : option value :=\n  match value_eq_size v1 v2 with\n  | left EQ => Some (f EQ)\n  | _ => None\n  end.\n\nLemma eqvalue {sz : nat} (x y : word sz) : x = y <-> mkvalue sz x = mkvalue sz y.\nProof.\n  split; intros.\n  subst. reflexivity. inversion H. apply existT_wordToZ in H1.\n  apply wordToZ_inj. assumption.\nQed.\n\nLemma eqvaluef {sz : nat} (x y : word sz) : x = y -> mkvalue sz x = mkvalue sz y.\nProof. apply eqvalue. Qed.\n\nLemma nevalue {sz : nat} (x y : word sz) : x <> y <-> mkvalue sz x <> mkvalue sz y.\nProof. split; intros; intuition. apply H. apply eqvalue. assumption.\n       apply H. rewrite H0. trivial.\nQed.\n\nLemma nevaluef {sz : nat} (x y : word sz) : x <> y -> mkvalue sz x <> mkvalue sz y.\nProof. apply nevalue. Qed.\n\n(*Definition rewrite_word_size (initsz finalsz : nat) (w : word initsz)\n  : option (word finalsz) :=\n  match Nat.eqb initsz finalsz return option (word finalsz) with\n  | true => Some _\n  | false => None\n  end.*)\n\nDefinition valueeq (sz : nat) (x y : word sz) :\n  {mkvalue sz x = mkvalue sz y} + {mkvalue sz x <> mkvalue sz y} :=\n  match weq x y with\n  | left eq => left (eqvaluef x y eq)\n  | right ne => right (nevaluef x y ne)\n  end.\n\nDefinition valueeqb (x y : value) : bool :=\n  match value_eq_size x y with\n  | left EQ =>\n    weqb (vword x) (unify_word (vsize x) (vsize y) (vword y) EQ)\n  | right _ => false\n  end.\n\nDefinition value_projZ_eqb (v1 v2 : value) : bool := Z.eqb (valueToZ v1) (valueToZ v2).\n\nTheorem value_projZ_eqb_true :\n  forall v1 v2,\n  v1 = v2 -> value_projZ_eqb v1 v2 = true.\nProof. intros. subst. unfold value_projZ_eqb. apply Z.eqb_eq. trivial. Qed.\n\nTheorem valueeqb_true_iff :\n  forall v1 v2,\n  valueeqb v1 v2 = true <-> v1 = v2.\nProof.\n  split; intros.\n  unfold valueeqb in H. destruct (value_eq_size v1 v2) eqn:?.\n  - destruct v1, v2. simpl in H.\nAbort.\n\nDefinition value_int_eqb (v : value) (i : int) : bool :=\n  Z.eqb (valueToZ v) (Int.unsigned i).\n\n(** Arithmetic operations over [value], interpreting them as signed or unsigned\ndepending on the operation.\n\nThe arithmetic operations over [word] are over [N] by default, however, can also\nbe called over [Z] explicitly, which is where the bits are interpreted in a\nsigned manner. *)\n\nDefinition vplus v1 v2 := map_word2 wplus v1 v2.\nDefinition vplus_opt v1 v2 := map_word2_opt wplus v1 v2.\nDefinition vminus v1 v2 := map_word2 wminus v1 v2.\nDefinition vmul v1 v2 := map_word2 wmult v1 v2.\nDefinition vdiv v1 v2 := map_word2 wdiv v1 v2.\nDefinition vmod v1 v2 := map_word2 wmod v1 v2.\n\nDefinition vmuls v1 v2 := map_word2 wmultZ v1 v2.\nDefinition vdivs v1 v2 := map_word2 wdivZ v1 v2.\nDefinition vmods v1 v2 := map_word2 wremZ v1 v2.\n\n(** ** Bitwise operations\n\nBitwise operations over [value], which is independent of whether the number is\nsigned or unsigned. *)\n\nDefinition vnot v := map_word wnot v.\nDefinition vneg v := map_word wneg v.\nDefinition vbitneg v := boolToValue (vsize v) (negb (valueToBool v)).\nDefinition vor v1 v2 := map_word2 wor v1 v2.\nDefinition vand v1 v2 := map_word2 wand v1 v2.\nDefinition vxor v1 v2 := map_word2 wxor v1 v2.\n\n(** ** Comparison operators\n\nComparison operators that return a bool, there should probably be an equivalent\nwhich returns another number, however I might just add that as an explicit\nconversion. *)\n\nDefinition veqb v1 v2 := map_any v1 v2 (@weqb (vsize v1)).\nDefinition vneb v1 v2 EQ := negb (veqb v1 v2 EQ).\n\nDefinition veq v1 v2 EQ := boolToValue (vsize v1) (veqb v1 v2 EQ).\nDefinition vne v1 v2 EQ := boolToValue (vsize v1) (vneb v1 v2 EQ).\n\nDefinition vltb v1 v2 := map_any v1 v2 wltb.\nDefinition vleb v1 v2 EQ := negb (map_any v2 v1 wltb (eq_sym EQ)).\nDefinition vgtb v1 v2 EQ := map_any v2 v1 wltb (eq_sym EQ).\nDefinition vgeb v1 v2 EQ := negb (map_any v1 v2 wltb EQ).\n\nDefinition vltsb v1 v2 := map_any v1 v2 wsltb.\nDefinition vlesb v1 v2 EQ := negb (map_any v2 v1 wsltb (eq_sym EQ)).\nDefinition vgtsb v1 v2 EQ := map_any v2 v1 wsltb (eq_sym EQ).\nDefinition vgesb v1 v2 EQ := negb (map_any v1 v2 wsltb EQ).\n\nDefinition vlt v1 v2 EQ := boolToValue (vsize v1) (vltb v1 v2 EQ).\nDefinition vle v1 v2 EQ := boolToValue (vsize v1) (vleb v1 v2 EQ).\nDefinition vgt v1 v2 EQ := boolToValue (vsize v1) (vgtb v1 v2 EQ).\nDefinition vge v1 v2 EQ := boolToValue (vsize v1) (vgeb v1 v2 EQ).\n\nDefinition vlts v1 v2 EQ := boolToValue (vsize v1) (vltsb v1 v2 EQ).\nDefinition vles v1 v2 EQ := boolToValue (vsize v1) (vlesb v1 v2 EQ).\nDefinition vgts v1 v2 EQ := boolToValue (vsize v1) (vgtsb v1 v2 EQ).\nDefinition vges v1 v2 EQ := boolToValue (vsize v1) (vgesb v1 v2 EQ).\n\n(** ** Shift operators\n\nShift operators on values. *)\n\nDefinition shift_map (sz : nat) (f : word sz -> nat -> word sz) (w1 w2 : word sz) :=\n  f w1 (wordToNat w2).\n\nDefinition vshl v1 v2 := map_word2 (fun sz => shift_map sz (@wlshift sz)) v1 v2.\nDefinition vshr v1 v2 := map_word2 (fun sz => shift_map sz (@wrshift sz)) v1 v2.\n\nModule HexNotationValue.\n  Export HexNotation.\n  Import WordScope.\n\n  Notation \"sz ''h' a\" := (NToValue sz (hex a)) (at level 50).\n\nEnd HexNotationValue.\n\nInductive val_value_lessdef: val -> value -> Prop :=\n| val_value_lessdef_int:\n    forall i v',\n    i = valueToInt v' ->\n    val_value_lessdef (Vint i) v'\n| val_value_lessdef_ptr:\n    forall b off v',\n    off = valueToPtr v' ->\n    (Z.modulo (uvalueToZ v') 4) = 0%Z ->\n    val_value_lessdef (Vptr b off) v'\n| lessdef_undef: forall v, val_value_lessdef Vundef v.\n\nInductive opt_val_value_lessdef: option val -> value -> Prop :=\n| opt_lessdef_some:\n    forall v v', val_value_lessdef v v' -> opt_val_value_lessdef (Some v) v'\n| opt_lessdef_none: forall v, opt_val_value_lessdef None v.\n\nLemma valueToZ_ZToValue :\n  forall n z,\n  (- Z.of_nat (2 ^ n) <= z < Z.of_nat (2 ^ n))%Z ->\n  valueToZ (ZToValue (S n) z) = z.\nProof.\n  unfold valueToZ, ZToValue. simpl.\n  auto using wordToZ_ZToWord.\nQed.\n\nLemma uvalueToZ_ZToValue :\n  forall n z,\n  (0 <= z < 2 ^ Z.of_nat n)%Z ->\n  uvalueToZ (ZToValue n z) = z.\nProof.\n  unfold uvalueToZ, ZToValue. simpl.\n  auto using uwordToZ_ZToWord.\nQed.\n\nLemma uvalueToZ_ZToValue_full :\n  forall sz : nat,\n  (0 < sz)%nat ->\n  forall z : Z, uvalueToZ (ZToValue sz z) = (z mod 2 ^ Z.of_nat sz)%Z.\nProof. unfold uvalueToZ, ZToValue. simpl. auto using uwordToZ_ZToWord_full. Qed.\n\nLemma ZToValue_uvalueToZ :\n  forall v,\n  ZToValue (vsize v) (uvalueToZ v) = v.\nProof.\n  intros.\n  unfold ZToValue, uvalueToZ.\n  rewrite ZToWord_uwordToZ. destruct v; auto.\nQed.\n\nLemma valueToPos_posToValueAuto :\n  forall p, valueToPos (posToValueAuto p) = p.\nProof.\n  intros. unfold valueToPos, posToValueAuto.\n  rewrite uvalueToZ_ZToValue. auto. rewrite positive_nat_Z.\n  split. apply Zle_0_pos.\n\n  assert (p < 2 ^ (Pos.size p))%positive by apply Pos.size_gt.\n  inversion H. rewrite <- Z.compare_lt_iff. rewrite <- H1.\n  simpl. rewrite <- Pos2Z.inj_pow_pos. trivial.\nQed.\n\nLemma valueToPos_posToValue :\n  forall p, valueToPos (posToValueAuto p) = p.\nProof.\n  intros. unfold valueToPos, posToValueAuto.\n  rewrite uvalueToZ_ZToValue. auto. rewrite positive_nat_Z.\n  split. apply Zle_0_pos.\n\n  assert (p < 2 ^ (Pos.size p))%positive by apply Pos.size_gt.\n  inversion H. rewrite <- Z.compare_lt_iff. rewrite <- H1.\n  simpl. rewrite <- Pos2Z.inj_pow_pos. trivial.\nQed.\n\nLemma valueToInt_intToValue :\n  forall v,\n  valueToInt (intToValue v) = v.\nProof.\n  intros.\n  unfold valueToInt, intToValue. rewrite uvalueToZ_ZToValue. auto using Int.repr_unsigned.\n  split. apply Int.unsigned_range_2.\n  assert ((Int.unsigned v <= Int.max_unsigned)%Z) by apply Int.unsigned_range_2.\n  apply Z.lt_le_pred in H. apply H.\nQed.\n\nLemma valueToPtr_ptrToValue :\n  forall v,\n  valueToPtr (ptrToValue v) = v.\nProof.\n  intros.\n  unfold valueToPtr, ptrToValue. rewrite uvalueToZ_ZToValue. auto using Ptrofs.repr_unsigned.\n  split. apply Ptrofs.unsigned_range_2.\n  assert ((Ptrofs.unsigned v <= Ptrofs.max_unsigned)%Z) by apply Ptrofs.unsigned_range_2.\n  apply Z.lt_le_pred in H. apply H.\nQed.\n\nLemma intToValue_valueToInt :\n  forall v,\n  vsize v = 32%nat ->\n  intToValue (valueToInt v) = v.\nProof.\n  intros. unfold valueToInt, intToValue. rewrite Int.unsigned_repr_eq.\n  unfold ZToValue, uvalueToZ. unfold Int.modulus. unfold Int.wordsize. unfold Wordsize_32.wordsize.\n  pose proof (uwordToZ_bound (vword v)).\n  rewrite Z.mod_small. rewrite <- H. rewrite ZToWord_uwordToZ. destruct v; auto.\n  rewrite <- H. rewrite two_power_nat_equiv. apply H0.\nQed.\n\nLemma ptrToValue_valueToPtr :\n  forall v,\n  vsize v = 32%nat ->\n  ptrToValue (valueToPtr v) = v.\nProof.\n  intros. unfold valueToPtr, ptrToValue. rewrite Ptrofs.unsigned_repr_eq.\n  unfold ZToValue, uvalueToZ. unfold Ptrofs.modulus. unfold Ptrofs.wordsize. unfold Wordsize_Ptrofs.wordsize.\n  pose proof (uwordToZ_bound (vword v)).\n  rewrite Z.mod_small. rewrite <- H. rewrite ZToWord_uwordToZ. destruct v; auto.\n  rewrite <- H. rewrite two_power_nat_equiv. apply H0.\nQed.\n\nLemma valToValue_lessdef :\n  forall v v',\n    valToValue v = Some v' ->\n    val_value_lessdef v v'.\nProof.\n  intros.\n  destruct v; try discriminate; constructor.\n  unfold valToValue in H. inversion H.\n  symmetry. apply valueToInt_intToValue.\n  inv H. destruct (uvalueToZ (ptrToValue i) mod 4 =? 0); try discriminate.\n  inv H1. symmetry. apply valueToPtr_ptrToValue.\n  inv H. destruct (uvalueToZ (ptrToValue i) mod 4 =? 0) eqn:?; try discriminate.\n  inv H1. apply Z.eqb_eq. apply Heqb0.\nQed.\n\nLemma boolToValue_ValueToBool :\n  forall b,\n  valueToBool (boolToValue 32 b) = b.\nProof. destruct b; auto. Qed.\n\nLocal Open Scope Z.\n\nLtac word_op_value H :=\n  intros; unfold uvalueToZ, ZToValue; simpl; rewrite unify_word_unfold;\n  rewrite <- H; rewrite uwordToZ_ZToWord_full; auto; omega.\n\nLemma zadd_vplus :\n  forall sz z1 z2,\n  (sz > 0)%nat ->\n  uvalueToZ (vplus (ZToValue sz z1) (ZToValue sz z2) eq_refl) = (z1 + z2) mod 2 ^ Z.of_nat sz.\nProof. word_op_value ZToWord_plus. Qed.\n\nLemma zadd_vplus2 :\n  forall z1 z2,\n  vplus (ZToValue 32 z1) (ZToValue 32 z2) eq_refl = ZToValue 32 (z1 + z2).\nProof.\n  intros. unfold vplus, ZToValue, map_word2. rewrite unify_word_unfold. simpl.\n  rewrite ZToWord_plus; auto.\nQed.\n\nLemma ZToValue_eq :\n  forall w1,\n  (mkvalue 32 w1) = (ZToValue 32 (wordToZ w1)). Abort.\n\nLemma wordsize_32 :\n  Int.wordsize = 32%nat.\nProof. auto. Qed.\n\nLemma intadd_vplus :\n  forall i1 i2,\n  valueToInt (vplus (intToValue i1) (intToValue i2) eq_refl) = Int.add i1 i2.\nProof.\n  intros. unfold Int.add, valueToInt, intToValue. rewrite zadd_vplus.\n  rewrite <- Int.unsigned_repr_eq.\n  rewrite Int.repr_unsigned. auto. rewrite wordsize_32. omega.\nQed.\n\n(*Lemma intadd_vplus2 :\n  forall v1 v2 EQ,\n  vsize v1 = 32%nat ->\n  Int.add (valueToInt v1) (valueToInt v2) = valueToInt (vplus v1 v2 EQ).\nProof.\n  intros. unfold Int.add, valueToInt, intToValue. repeat (rewrite Int.unsigned_repr).\n  rewrite (@vadd_vplus v1 v2 EQ). trivial.\n  unfold uvalueToZ. pose proof (@uwordToZ_bound (vsize v2) (vword v2)).\n  rewrite H in EQ. rewrite <- EQ in H0 at 3.*)\n  (*rewrite zadd_vplus3. trivia*)\n\nLemma valadd_vplus :\n  forall v1 v2 v1' v2' v v' EQ,\n  val_value_lessdef v1 v1' ->\n  val_value_lessdef v2 v2' ->\n  Val.add v1 v2 = v ->\n  vplus v1' v2' EQ = v' ->\n  val_value_lessdef v v'.\nProof.\n  intros. inv H; inv H0; constructor; simplify.\n  Abort.\n\nLemma zsub_vminus :\n  forall sz z1 z2,\n  (sz > 0)%nat ->\n  uvalueToZ (vminus (ZToValue sz z1) (ZToValue sz z2) eq_refl) = (z1 - z2) mod 2 ^ Z.of_nat sz.\nProof. word_op_value ZToWord_minus. Qed.\n\nLemma zmul_vmul :\n  forall sz z1 z2,\n  (sz > 0)%nat ->\n  uvalueToZ (vmul (ZToValue sz z1) (ZToValue sz z2) eq_refl) = (z1 * z2) mod 2 ^ Z.of_nat sz.\nProof. word_op_value ZToWord_mult. Qed.\n\nLocal Open Scope N.\nLemma zdiv_vdiv :\n  forall n1 n2,\n  n1 < 2 ^ 32 ->\n  n2 < 2 ^ 32 ->\n  n1 / n2 < 2 ^ 32 ->\n  valueToN (vdiv (NToValue 32 n1) (NToValue 32 n2) eq_refl) = n1 / n2.\nProof.\n  intros; unfold valueToN, NToValue; simpl; rewrite unify_word_unfold. unfold wdiv.\n  unfold wordBin. repeat (rewrite wordToN_NToWord_2); auto.\nQed.\n\nLemma ZToValue_valueToNat :\n  forall x sz,\n  (sz > 0)%nat ->\n  (0 <= x < 2^(Z.of_nat sz))%Z ->\n  valueToNat (ZToValue sz x) = Z.to_nat x.\nProof.\n  destruct x; intros; unfold ZToValue, valueToNat; crush.\n  - rewrite wzero'_def. apply wordToNat_wzero.\n  - rewrite posToWord_nat. rewrite wordToNat_natToWord_2. trivial.\n    clear H1.\n    lazymatch goal with\n    | [ H : context[(_ < ?x)%Z] |- _ ] => replace x with (Z.of_nat (Z.to_nat x)) in H\n    end.\n    2: { apply Z2Nat.id; apply Z.pow_nonneg; lia. }\n\n    rewrite Z2Nat.inj_pow in H2; crush.\n    replace (Pos.to_nat 2) with 2%nat in H2 by reflexivity.\n    rewrite Nat2Z.id in H2.\n    rewrite <- positive_nat_Z in H2.\n    apply Nat2Z.inj_lt in H2.\n    assumption.\nQed.\n*)\n", "meta": {"author": "ymherklotz", "repo": "vericert", "sha": "c3de945fa463aa9a2ad0804eb8f67e40f585eb3a", "save_path": "github-repos/coq/ymherklotz-vericert", "path": "github-repos/coq/ymherklotz-vericert/vericert-c3de945fa463aa9a2ad0804eb8f67e40f585eb3a/src/hls/Value.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2605005701429106}}
{"text": "(* ************************************************************************** *)\n(*                                                                            *)\n(* Verified Flash Translation Layer                                           *)\n(*                                                                            *)\n(*                                                                            *)\n(* ************************************************************************** *)\n\nRequire Export bnat.\nRequire Import LibEx.\nRequire Import ListEx.\nRequire Import Monad.\nRequire Import Data.\n\nRequire Import Params.\n\n(* NAND hardware interface *)\n\n(* Definition oob := list int. *)\n\nDefinition page_off := nat.\n\nDefinition block_no := nat.\n\nDefinition page_off_of_nat (n: nat) : page_off := n.\n\nDefinition page_no := prod block_no page_off.\n\nInductive page_status : Set :=\n  | ps_free\n  | ps_programmed.\n\nInductive block_status : Set :=\n  | bs_free\n  | bs_programmed.\n\nRecord page : Set := \n  mkpage {\n      page_data : data;\n      page_oob : data;\n      page_state : page_status\n      (* data_size: length (page_data) = PAGE_DATA_SIZE; *)\n      (* oob_size: length (page_data) = PAGE_SPAREAREA_SIZE *)\n    }.\n\nRecord block : Set := \n  mkblock {\n      block_pages : list page;\n      next_page : page_off;\n      block_erase_count: nat;\n      block_state : block_status\n      (* pages_size: length block_pages = PAGES_PER_BLOCK *)\n    }.\n\nRecord chip : Set := \n  mkchip {\n      chip_blocks: list block\n      (* blocks_size : length chip_blocks = BLOCKS *)\n    }. \n\n(********* Initialization of the Nand Chip ****************)\n\nDefinition init_page_data : data :=\n  list_repeat_list PAGE_DATA_SIZE c_ff.\n\nDefinition init_page_oob : data :=\n  list_repeat_list PAGE_SPARE_AREA_SIZE c_ff.\n\nDefinition init_page : page :=\n  mkpage init_page_data init_page_oob ps_free.\n\nDefinition init_block : block :=\n  mkblock (list_repeat_list PAGES_PER_BLOCK init_page) 0 0 bs_free.\n\nDefinition erased_block (ec: nat): block :=\n  mkblock (list_repeat_list PAGES_PER_BLOCK init_page) 0 (S ec) bs_free.\n\nDefinition bvalid_block_no (pbn: block_no) : bool := \n  (blt_nat pbn BLOCKS).\n\nDefinition bvalid_page_off (off: page_off) : bool := \n  (blt_nat off PAGES_PER_BLOCK).\n\n(********* Nand chip Operations ***************)\nDefinition nand_init : chip :=\n  mkchip (list_repeat_list BLOCKS init_block). \n\n(* written by zhanghui, generate the content of 'oob' according to the\ndata stored in this page. *)\n(* TEMP: now just return a list of null *)\nDefinition make_oob (d : data) : data :=\n  list_repeat_list PAGE_SPARE_AREA_SIZE c_null.\n\nDefinition chip_get_block (c: chip) (pbn: block_no): option block :=\n  list_get (chip_blocks c) pbn.\n\nDefinition chip_set_block (c: chip) (pbn: block_no) (b: block) : option chip :=\n  test bvalid_block_no pbn;\n  do nbl <-- list_set (chip_blocks c) pbn b;\n  ret (mkchip nbl).\n\nDefinition block_get_page (b: block) (off: page_off) : option page :=\n  test (bvalid_page_off off);\n  do p <-- (list_get (block_pages b) off);\n  ret p.\n \nDefinition block_set_page (b: block) (off: page_off) (p: page) : option block :=\n  test bvalid_page_off off;\n  do npl <-- list_set (block_pages b) off p;\n  ret (mkblock npl (next_page b) (block_erase_count b) bs_programmed).\n\nDefinition block_set_next_page (b: block) (off: page_off) : option block :=\n  ret (mkblock (block_pages b) (off) (block_erase_count b) (block_state b)).\n\nDefinition chip_get_page (c: chip) (bln: block_no) (poff: page_off) : option page :=\n  match chip_get_block c bln with\n    | None => None\n    | Some b =>\n      block_get_page b poff\n  end.\n\nDefinition page_get_data (p: page) : option data :=\n  match page_state p with\n    | ps_free => None (* This is an empty page, no data. *)\n    | ps_programmed => Some (page_data p)\n  end.\n\nDefinition check_page_state_is_free (ps : page_status) : bool :=\n  match ps with\n    | ps_free => true\n    | _ => false\n  end.\n\n(********* Nand chip Operations ***************)\nDefinition nand_read_page (c: chip) (pbn: block_no) (poff: page_off) : option (prod data data) :=\n  test (bvalid_block_no pbn);\n  do b <-- chip_get_block c pbn;\n  test (bvalid_page_off poff);\n  do p <-- block_get_page b poff;\n  ret (page_data p, page_oob p).\n\nDefinition nand_write_page (c: chip) (pbn: block_no) (off: page_off) (d: data) (o: data): option chip :=\n  test (bvalid_block_no pbn);\n  do b <-- chip_get_block c pbn;\n  test (bvalid_page_off off);\n  test (ble_nat (next_page b) off);\n  do p <-- block_get_page b off;\n  test (check_page_state_is_free (page_state p));\n  do b' <-- block_set_page b off (mkpage d o ps_programmed);\n  do b'' <-- block_set_next_page b' (S off);\n  do c' <-- chip_set_block c pbn b'';\n  ret c'.\n                 \nDefinition nand_erase_block (c: chip) (pbn: block_no) : option chip :=\n  test (bvalid_block_no pbn);\n  do b <-- chip_get_block c pbn;\n  let b' := erased_block (block_erase_count b) in \n  do c' <-- chip_set_block c pbn b';\n  ret c'.\n", "meta": {"author": "vittayang", "repo": "coqnand", "sha": "dd538809cf926e04d8de9912521d4e2dfc32189e", "save_path": "github-repos/coq/vittayang-coqnand", "path": "github-repos/coq/vittayang-coqnand/coqnand-dd538809cf926e04d8de9912521d4e2dfc32189e/Nand.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.26050056346399386}}
{"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 Scenario1  (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_OrdinaryStakeWin_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_onFailToRecoverStake  msg_value_onFailToRecoverStake msg_sender_onFailToRecoverStake : Z)\n                        (NetParams_onFailToRecoverStake :  NetParams)\n                        (now_toWaitingReward  msg_value_toWaitingReward msg_sender_toWaitingReward : Z)\n                        (NetParams_toWaitingReward :  NetParams)\n                        (now_onSuccessToRecoverStake  msg_value_onSuccessToRecoverStake msg_sender_onSuccessToRecoverStake : Z)\n                        (NetParams_onSuccessToRecoverStake :  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_onFailToRecoverStake) >>\n                        modify (fun l => {$ l With (VMState_ι_now,          now_onFailToRecoverStake);\n                                                   (VMState_ι_msg_value ,   msg_value_onFailToRecoverStake);\n                                                   (VMState_ι_msg_sender ,  msg_sender_onFailToRecoverStake) $}) >>\n                        do _ ← DePoolContract_Ф_onFailToRecoverStake 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                        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                        $ 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= 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) = true ->\nlet reward_all := msg_value_onSuccessToRecoverStake + DePoolLib_ι_PROXY_FEE - stake  - (DePool_ι_RET_OR_REINV_FEE +  1 * DePool_ι_RET_OR_REINV_FEE) in\nlet rewards := reward_all * participantRewardFraction / 100  in\nlet stakeSum := stake in \nlet reward := stakeSum * rewards / stake  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 validatorWallet in\nlet current_stakes := maybeGet optStake in\nround ->> RoundsBase_ι_Round_ι_stake = stake + reward\n/\\ current_stakes ->> RoundsBase_ι_StakeValue_ι_ordinary  = stake + reward.\nProof.\n\nAbort.\nEnd Scenario1.", "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/Scenario1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.26047062330999227}}
{"text": "From Coq Require Import ZArith.ZArith Lists.List Strings.String micromega.Lia Arith\n     Ensembles Relations.Relation_Definitions.\nRequire Import Common.AstCommon.\nRequire compcert.lib.Maps compcert.lib.Coqlib.\n\nImport ListNotations.\n\nRequire Import LambdaBoxLocal.expression LambdaBoxLocal.fuel_sem.\n\nRequire Import cps cps_show eval ctx logical_relations\n        List_util algebra alpha_conv functions Ensembles_util\n        tactics LambdaBoxLocal_to_LambdaANF LambdaBoxLocal_to_LambdaANF_util LambdaBoxLocal_to_LambdaANF_corresp LambdaBoxLocal_to_LambdaANF_correct\n        LambdaANF.tactics identifiers bounds cps_util rename.\n\nRequire Import ExtLib.Data.Monads.OptionMonad ExtLib.Structures.Monads.\n\nImport Monad.MonadNotation.\n\nOpen Scope monad_scope.\n\n\nSection Refinement.\n\n  Context (cnstrs : conId_map)\n          (dtag : positive) (* default tag *)\n          (cenv : ctor_env).\n\n  Fixpoint value_ref' (v1 : value) (v2 : val) : Prop:=\n    let fix Forall2_aux vs1 vs2 :=\n        match vs1, vs2 with\n        | [], [] => True\n        | v1 :: vs1, v2 :: vs2 =>\n          value_ref' v1 v2 /\\ Forall2_aux vs1 vs2\n        | _, _ => False\n        end\n    in\n    match v1, v2 with\n    | Con_v c1 vs1, Vconstr c2 vs2 =>\n      dcon_to_tag dtag c1 cnstrs = c2 /\\ Forall2_aux vs1 vs2\n    | Clos_v _ _ _, Vfun _ _ _ => True\n    | ClosFix_v _ _ _, Vfun _ _ _ => True\n    | _, _ => False\n    end.\n\n\n  Definition value_ref (v1 : value) (v2 : val) : Prop:=\n    match v1, v2 with\n    | Con_v c1 vs1, Vconstr c2 vs2 =>\n      dcon_to_tag dtag c1 cnstrs = c2 /\\ Forall2 value_ref' vs1 vs2\n    | Clos_v _ _ _, Vfun _ _ _ => True\n    | ClosFix_v _ _ _, Vfun _ _ _ => True\n    | _, _ => False\n    end.\n\n  Lemma value_ref_eq v1 v2 :\n    value_ref' v1 v2 <-> value_ref v1 v2.\n  Proof.\n    induction v1; try easy.\n\n    destruct v2; simpl; try easy.\n\n    \n    revert l0. induction l; intros l'.\n\n    - split; intros [H1 H2]. split; eauto; destruct l'; eauto.\n      inv H2. split; eauto.\n\n    - split; intros [H1 H2].\n      \n      + split; eauto; destruct l'; inv H2.\n        constructor; eauto. eapply IHl. split; eauto.\n\n      + split; eauto. destruct l'; inv H2.\n        constructor; eauto. eapply IHl. split; eauto.\n  Qed.\n\n  Definition diverge (v : list value) (e : expression.exp) :=\n    forall (c : nat), exists t, eval_env_fuel v e fuel_sem.OOT c t.\n\n  \n  Program Definition refines M (e1 : expression.exp) (e2 : cps.exp) := \n    (* Termination *)\n    (forall (v1 : value) (c1 t1 : nat),\n        eval_env_fuel [] e1 (Val v1) c1 t1 ->\n        exists (v2 : val) (c2 : nat),\n          bstep_fuel cenv (M.empty _) e2 c2 (Res v2) tt /\\\n          (c2 <= t1 + M)%nat /\\\n          value_ref v1 v2) /\\\n    (* Divergence *)    \n    (diverge [] e1 -> eval.diverge cenv (M.empty _) e2).\n\n  Context (prim_map : M.t (kername * string (* C definition *) * nat (* arity *))). \n  Context (func_tag kon_tag default_itag : positive)\n          (next_id : positive).\n  Context (dcon_to_tag_inj :\n             forall (tgm : conId_map) (dc dc' : dcon),\n               dcon_to_tag dtag dc tgm = dcon_to_tag dtag dc' tgm -> dc = dc'). \n  \n  Definition cps_rel_top (e : expression.exp) (xs : list var)\n             (k : var) (e' : cps.exp) :=\n    let S := fun x => (max_list xs k + 1 <= x)%positive in\n    exists S', cps_cvt_rel func_tag kon_tag dtag S e xs k cnstrs S' e'.\n\n\n  Lemma cps_val_comp k v1 v2 v3 : \n    cps_val_rel func_tag kon_tag dtag cnstrs v1 v2 ->\n    preord_val cenv eq_fuel k v2 v3 ->\n    value_ref v1 v3. \n  Proof.\n    revert v2 v3.\n    induction v1 using value_ind'; intros v2 v3 Hval Hll; inv Hval.\n    - rewrite preord_val_eq in Hll.\n      destruct v3; try contradiction. inv Hll.\n      simpl. split. reflexivity.\n\n      revert l vs' H2 H1.\n      induction H.\n\n      + intros. inv H2. inv H1. constructor.\n\n      + intros. inv H2. inv H1. constructor; eauto.\n        eapply value_ref_eq. eauto.\n\n    - rewrite preord_val_eq in Hll.\n      destruct v3; try contradiction.\n      simpl. eauto.\n\n    - rewrite preord_val_eq in Hll.\n      destruct v3; try contradiction.\n      simpl. eauto.\n  Qed. \n\n\n  Theorem cps_corrrect_top e k x (Hneq : x <> k):\n    exp_wf 0%N e ->\n    exists e',\n      cps_rel_top e [] k e' /\\\n      refines 3 e (Efun (Fcons k kon_tag [x] (Ehalt x) Fnil) e').\n  Proof.\n    intros Hwf.\n    edestruct cps_rel_exists with (xs := @nil var).\n    eassumption.\n    eassumption.\n\n    destructAll.\n    eexists. split.\n    eexists. eassumption.\n    \n\n    split.\n\n    - intro; intros.\n      edestruct cps_cvt_correct\n        with (rho := M.set k\n                           (Vfun (M.empty _) (Fcons k kon_tag [x] (Ehalt x) Fnil) k)\n                           (M.empty _)) (x := x); try eassumption.\n      + now constructor.\n      + simpl. eassumption.\n      + repeat normalize_sets.\n        eapply Disjoint_Singleton_l. simpl.\n        intros Hin. unfold In in *. lia.\n      + repeat normalize_sets. intros Hc. inv Hc.\n        eauto.\n      + intros Hc. inv Hc. \n      + constructor.\n      + rewrite M.gss. reflexivity.\n      + clear H2.\n\n        edestruct cps_val_rel_exists as [v2 Hval]. eassumption.\n        eapply (@eval_env_step_preserves_wf nat LambdaBoxLocal_resource_fuel LambdaBoxLocal_resource_trace).\n        eassumption. reflexivity. constructor. eassumption.\n        \n        specialize (H1 v1 v2 eq_refl Hval).\n\n        edestruct H1. reflexivity.\n\n        econstructor 2. econstructor.\n        rewrite M.gso. rewrite M.gss. reflexivity.\n        now eauto.\n        simpl. rewrite M.gss. reflexivity.\n        simpl. rewrite Coqlib.peq_true. reflexivity.\n        simpl. reflexivity.\n        \n        econstructor 2. econstructor. rewrite M.gss. reflexivity.\n        \n        destructAll. destruct x2. contradiction.\n        \n        destruct x4.\n\n        do 2 eexists. split; [ | split ].\n\n        replace tt with (tt <+> tt) by reflexivity.\n        econstructor 2. \n        econstructor. simpl. eassumption.\n\n        simpl in *.  unfold one, one_i; simpl. lia.\n        simpl in *. eapply cps_val_comp. eassumption. eassumption.\n\n    - intros Hdiv.\n\n      intros c. specialize (Hdiv c). destructAll.\n      edestruct cps_cvt_correct\n        with (rho := M.set k\n                           (Vfun (M.empty _) (Fcons k kon_tag [x] (Ehalt x) Fnil) k)\n                           (M.empty _)) (x := x); try eassumption. \n      + now constructor.\n      + simpl. eassumption.\n      + repeat normalize_sets.\n        eapply Disjoint_Singleton_l. simpl.\n        intros Hin. unfold In in *. lia.\n      + repeat normalize_sets. intros Hc. inv Hc.\n        eauto.\n      + intros Hc. inv Hc. \n      + constructor.\n      + rewrite M.gss. reflexivity.\n      + clear H1.\n        specialize (H2 eq_refl). destructAll.\n\n        destruct c.\n\n        * eexists. constructor. simpl.\n          unfold one, one_i. simpl. lia.\n\n        * eexists. replace (S c) with (c + 1)%nat by lia.\n          econstructor 2. econstructor.\n          simpl.\n          edestruct Nat.le_exists_sub with (n := c) (m := x3). lia. destructAll.   \n          eapply bstep_fuel_OOT_monotonic in H2.\n          destructAll. destruct x3. eassumption. \n\n          Grab Existential Variables. exact 0%nat.\n  Qed.\n\n\n  Section Linking.\n\n    Definition link_src (e_lib e_cli : expression.exp) :=\n      Let_e nAnon e_lib e_cli.\n\n\n    Definition link_trg (k1 x1 : var) (e_lib e_cli : cps.exp) :=\n      (* Efun (Fcons k2 kon_tag [x2] (Ehalt x1) Fnil) *)\n      (Efun (Fcons k1 kon_tag [x1] e_cli Fnil) e_lib).\n           \n\n    Lemma linking_correct e_lib e_cli k1 x1 r f t :\n      forall rho k x vk e_lib' e_cli' i,\n        exp_wf 0%N e_lib ->\n        exp_wf 1%N e_cli ->\n        \n        eval_env_fuel [] (link_src e_lib e_cli) r f t ->\n\n        cps_rel_top e_cli [x1] k e_cli' ->\n        cps_rel_top e_lib [] k1 e_lib' ->\n\n        x1 <> k ->\n        k1 <> k ->\n        x <> k ->\n        \n        M.get k rho = Some vk ->\n        \n        (* Source terminates *)\n        (forall v v',\n            r = (Val v) ->\n            cps_val_rel func_tag kon_tag dtag cnstrs v v' ->\n            preord_exp cenv (cps_bound f t) eq_fuel i\n                  ((Eapp k kon_tag (x::nil)), (M.set x v' (M.set k vk (M.empty cps.val))))\n                  (link_trg k1 x1 e_lib' e_cli', rho)) /\\\n        (* SOurce diverges *)\n        (r = fuel_sem.OOT ->\n         exists c, (f <= c)%nat /\\ bstep_fuel cenv rho (link_trg k1 x1 e_lib' e_cli') c eval.OOT tt).\n    Proof.\n      intros rho k x vk e_lib' e_cli' i Hwf1 Hwf2 Heval Hcps1 Hcps2 Hneq1 Hneq2 Hneq3 Hget.\n      inv Heval.\n\n      - split. congruence. \n        intros _. simpl in *. unfold fuel_exp in *.\n        eexists 0%nat. split.\n\n        simpl in *. lia.\n        constructor 1. unfold one, one_i. simpl. lia. \n\n      - inv H.\n\n        + assert (Heval1 := H7). eapply cps_cvt_correct in H7; eauto.\n          assert (Heval2 := H8). eapply cps_cvt_correct in H8; eauto.\n          \n          unfold link_trg.\n\n          assert (Hwfv2 : well_formed_val v1).\n          { eapply (@eval_env_step_preserves_wf nat LambdaBoxLocal_resource_fuel LambdaBoxLocal_resource_trace);\n              [ | reflexivity | | ]. eassumption.\n            now constructor. eassumption. } \n\n          assert (Hex' : exists v', cps_val_rel func_tag kon_tag dtag cnstrs v1 v').\n          { eapply cps_val_rel_exists. eassumption. (* TODO remove arg *) eassumption. } destructAll. \n\n          inv Hcps1. inv Hcps2.\n          \n          assert (Heq : forall m, preord_exp' cenv (preord_val cenv)\n                                              (cps_bound (f1 <+> @one_i _ _ fuel_resource_LambdaBoxLocal (link_src e_lib e_cli))\n                                                         (t1 <+> @one_i _ _ trace_resource_LambdaBoxLocal (link_src e_lib e_cli)))\n\n                                              eq_fuel m\n                                              (e_cli', map_util.M.set x1 x0 (M.set k1 (Vfun rho (Fcons k1 kon_tag [x1] e_cli' Fnil) k1) rho))\n                                              (Efun (Fcons k1 kon_tag [x1] e_cli' Fnil) e_lib', rho)). \n        { intros j. eapply preord_exp_post_monotonic.\n          2:{ eapply preord_exp_trans. tci. eapply eq_fuel_idemp.\n              \n              2:{ intros m. eapply preord_exp_Efun_red. } \n              assert (Hex' : exists z, ~ In var (k1 |: FromList []) z).\n              { eapply ToMSet_non_member. tci. } destructAll.\n              \n              eapply preord_exp_trans. tci. eapply eq_fuel_idemp. \n\n              \n              2:{ intros m. simpl. eapply H7; [ | | | | | | | eassumption | reflexivity | ].\n                  - now constructor.\n                  - eassumption. \n                  - repeat normalize_sets. eapply Disjoint_Singleton_l.\n                    unfold In. simpl. lia.\n                  - eassumption.\n                  - intros Hc. inv Hc.\n                  - econstructor.\n                  - rewrite M.gss. reflexivity.\n                  - eassumption. }\n               \n              eapply preord_exp_Eapp_red.\n              - rewrite M.gso; eauto. rewrite M.gss. reflexivity. intros Hc; subst; eauto.\n              - simpl. rewrite Coqlib.peq_true. reflexivity.\n              - simpl. rewrite M.gss. reflexivity.\n              - simpl. reflexivity. } \n          \n          (* Invariant composition *)\n          { unfold inclusion, comp, eq_fuel, one_step, cps_bound, one_i.\n            intros [[[? ?] ?] ?] [[[? ?] ?] ?] ?.            \n            destructAll. destruct x4, x5. repeat destruct p, p0. subst. simpl. unfold fuel_exp. simpl. lia. } } \n        \n        assert (Hex : exists x, ~ In var (k |: FromList [x1]) x).\n        { eapply ToMSet_non_member. tci. } destructAll.\n        \n        split. \n        (* Termination *) \n        { intros v v' Heq1 Hvrel. subst. \n          \n          eapply preord_exp_post_monotonic.\n          \n          2:{ eapply preord_exp_trans; [ | | | eassumption ]. tci. eapply eq_fuel_idemp. \n              \n              eapply preord_exp_trans. tci. eapply eq_fuel_idemp.\n              \n              2:{ intros m. eapply H8; [ | | | | | | | eassumption | reflexivity | eassumption ].\n                  - constructor; eauto.\n                  - simpl Datatypes.length. rewrite Nnat.Nat2N.inj_succ, <- OrdersEx.N_as_OT.add_1_l. eassumption. \n                  - repeat normalize_sets. eapply Union_Disjoint_l; sets.\n                    eapply Disjoint_Singleton_l. unfold In. simpl. lia.\n                    eapply Disjoint_Singleton_l. unfold In. simpl. lia.\n                  - eassumption.\n                  - repeat normalize_sets. intros Hc; inv Hc; eauto.\n                  - eapply cps_env_rel_extend_weaken; eauto.\n                    eapply cps_env_rel_weaken; eauto. constructor.\n                  - rewrite !M.gso. eassumption.\n                    now eauto. now eauto. }\n\n              eapply preord_exp_app_compat with (P2 := eq_fuel).\n              now eapply eq_fuel_compat. \n              now eapply eq_fuel_compat. \n              \n              eapply preord_var_env_extend_neq. \n              eapply preord_var_env_extend_eq.\n              eapply preord_val_refl. now tci.\n              now eauto.\n              \n              now intros Hc; subst; eauto.\n              constructor.\n              eapply preord_var_env_extend_eq.\n              eapply preord_val_refl. now tci. now constructor. } \n          \n          (* Invariant composition *)\n          { unfold inclusion, comp, eq_fuel, one_step, cps_bound, one_i.\n            intros [[[? ?] ?] ?] [[[? ?] ?] ?] ?.            \n            destructAll. destruct x5, x6. repeat destruct p, p0. subst.\n            simpl in *. lia. } }\n               \n        (* OOT *)\n        { intros ?; subst.\n\n          edestruct H8 with (rho := M.set x1 x0 (M.set k1 (Vfun rho (Fcons k1 kon_tag [x1] e_cli' Fnil) k1) rho));\n            [ | | | | | | | eassumption | ].\n          - constructor; eauto.\n          - eassumption.\n          - repeat normalize_sets.\n            eapply Union_Disjoint_l. \n            eapply Disjoint_Singleton_l. unfold In. simpl. lia.\n            eapply Disjoint_Singleton_l. unfold In. simpl. lia.\n          - eassumption.\n          - repeat normalize_sets. intros Hc; inv Hc; eauto.\n          - eapply cps_env_rel_extend_weaken; eauto.\n            eapply cps_env_rel_weaken; eauto. constructor.\n          - rewrite !M.gso. eassumption.\n            now eauto. now eauto.\n          - destruct (H4 ltac:(reflexivity)). destructAll. eapply Heq in H6; [ | reflexivity ]. destructAll.\n            destruct x6; try contradiction. destruct x8. eexists. split; [ | eassumption ].\n            \n            unfold one_i in *. simpl in *. lia. } \n        \n      + (* Let_e, OOT *)\n        split. congruence.\n        intros _.\n        set (rho' := M.set k1 (Vfun rho (Fcons k1 kon_tag [x1] e_cli' Fnil) k1) rho).\n        \n        assert (Hex : exists x, ~ In var (k1 |: FromList []) x).\n        { eapply ToMSet_non_member. tci. } destructAll.\n        \n        assert (Heval1 := H7). eapply cps_cvt_correct in H7; eauto.\n\n        inv Hcps1. inv Hcps2. \n        \n        edestruct (H7 rho'); [ | | | | | | | eassumption | ].\n        * constructor.\n        * eassumption.\n        * repeat normalize_sets.\n          eapply Disjoint_Singleton_l. unfold In. simpl. lia.\n        * eassumption.\n        * intros Hc. inv Hc.\n        * econstructor.\n        * unfold rho'. rewrite M.gss. reflexivity.\n        * edestruct H3. reflexivity. destructAll.\n          exists (x4 + 1)%nat.\n          split. unfold one_i. simpl. unfold fuel_exp. lia.\n          replace tt with (tt <+> tt) by reflexivity. eapply BStepf_run. econstructor; eauto.\n\n          \n          Grab Existential Variables. exact 0%nat. exact 0%nat.\n          \n    Qed.      \n      \n\n    Theorem cps_corrrect_top_sep_comp e_lib e_cli k1 k2 x1 x2 :\n      exp_wf 0%N e_lib ->\n      exp_wf 1%N e_cli ->\n      \n      x1 <> k2 ->\n      k1 <> k2 ->\n      x2 <> k2 ->\n\n      exists e_cli' e_lib',\n        cps_rel_top e_cli [x1] k2 e_cli' /\\\n        cps_rel_top e_lib [] k1 e_lib' /\\\n        refines 3 (link_src e_lib e_cli)\n                (Efun (Fcons k2 kon_tag [x2] (Ehalt x2) Fnil) (link_trg k1 x1 e_lib' e_cli')).\n      \n    Proof.\n      intros Hwf1 Hwf2 Hneq1 Hneq2 Hneq3.\n\n      edestruct cps_rel_exists with (xs := @nil var).\n      eassumption.\n      eassumption.\n\n      \n      destructAll.\n      \n      edestruct cps_rel_exists with (xs := [x1]).\n      eassumption.\n      eassumption.\n      \n      destructAll.\n      \n      \n      do 2 eexists. split; [ | split ].\n      eexists. eassumption.\n      eexists. eassumption.\n      \n      \n      split.\n      \n      - intro; intros.\n        edestruct linking_correct\n          with (rho := M.set k2\n                             (Vfun (M.empty _) (Fcons k2 kon_tag [x2] (Ehalt x2) Fnil) k2)\n                             (M.empty _)) (x := x2).\n        + eapply Hwf1.\n        + eapply Hwf2.\n        + eassumption.\n        + eexists. eassumption.\n        + eexists. eassumption.\n        + now eauto.\n        + now eauto.\n        + now eauto.\n        + rewrite M.gss. reflexivity.\n        + clear H3.\n          \n          edestruct cps_val_rel_exists as [v2 Hval]. eassumption.\n          eapply (@eval_env_step_preserves_wf nat LambdaBoxLocal_resource_fuel LambdaBoxLocal_resource_trace). eassumption. reflexivity. constructor.\n          constructor.\n          eassumption. eassumption.\n          specialize (H2 v1 v2 eq_refl Hval).\n          \n          edestruct H2. reflexivity.\n          \n          econstructor 2. econstructor.\n          rewrite M.gso. rewrite M.gss. reflexivity.\n          now eauto.\n          simpl. rewrite M.gss. reflexivity.\n          simpl. rewrite Coqlib.peq_true. reflexivity.\n          simpl. reflexivity.\n          \n          econstructor 2. econstructor. rewrite M.gss. reflexivity.\n          \n          destructAll. destruct x5. contradiction.\n          \n          destruct x7.\n\n          do 2 eexists. split; [ | split ].\n\n          replace tt with (tt <+> tt) by reflexivity.\n          econstructor 2. \n          econstructor. simpl. eassumption.\n\n          simpl in *. unfold one, one_i. simpl. lia. \n          simpl in *. eapply cps_val_comp. eassumption. eassumption.\n\n      - intros Hdiv.\n\n        intros c. specialize (Hdiv c). destructAll.\n        edestruct linking_correct\n          with (rho := M.set k2\n                             (Vfun (M.empty _) (Fcons k2 kon_tag [x2] (Ehalt x2) Fnil) k2)\n                             (M.empty _)) (x := x2).\n        + eapply Hwf1.\n        + eapply Hwf2.\n        + eassumption.\n        + eexists. eassumption.\n        + eexists. eassumption.\n        + now eauto.\n        + now eauto.\n        + now eauto.\n        + rewrite M.gss. reflexivity.\n        + clear H2.\n          specialize (H3 eq_refl). destructAll.\n\n          destruct c.\n          \n          * eexists. constructor. simpl.\n            unfold one, one_i. simpl. lia.\n\n          * eexists. replace (S c) with (c + 1)%nat by lia.\n            econstructor 2. econstructor.\n            simpl.\n            edestruct Nat.le_exists_sub with (n := c) (m := x6). lia. destructAll.   \n            eapply bstep_fuel_OOT_monotonic in H3.\n            destructAll. destruct x6. eassumption. \n            \n            Grab Existential Variables. exact 0%nat.\n    Qed.\n\n\n  End Linking.\n\n  \nEnd Refinement.\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/LambdaANF/LambdaBoxLocal_to_LambdaANF_toplevel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.26047062330999227}}
{"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.  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 continuity.\nRequire Export stronger_continuity_defs1.\nRequire Export stronger_continuity_defs3.\nRequire Export List.\nRequire Export list.  (* WTF!! *)\n\n\n\nLemma cequiv_bound_nat_bound {o} :\n  forall lib (a : get_patom_set o) (x e z : NVar) (k : nat) (f : @NTerm o),\n    (forall t n,\n       n < k\n       -> computes_to_value lib t (mk_nat n)\n       -> {j : nat & computes_to_value lib (mk_apply f t) (mk_nat j)})\n    -> cequiv\n         lib\n         (bound_nat a x e z (bound x (mk_utoken a) (mk_nat k) f))\n         (mk_lam x (mk_less (mk_var x) mk_zero (mk_vbot z)\n                            (mk_less (mk_var x) (mk_nat k)\n                                     (mk_apply f (mk_var x))\n                                     (spexc a)))).\nProof.\n  introv imp.\n\nAbort.\n\nLemma cequiv_sp_bound_nat_c_bound_c {o} :\n  forall lib v z (e n f : @CTerm o),\n    cequivc\n      lib\n      (sp_bound_nat_c v z (bound_c e n f v))\n      (bound2_c v z n f e).\nProof.\n  introv.\n\n  apply cequivc_lam; introv.\n  allrw @mkcv_less_substc.\n  allrw @mkcv_apply_substc.\n  allrw @substc_mkcv_zero.\n  allrw @mkc_var_substc.\n  allrw @csubst_mk_cv.\n  allrw @mkcv_vbot_substc.\n\n  eapply cequivc_trans;\n    [apply cequivc_mkc_less;\n      [apply cequivc_refl\n      |apply cequivc_refl\n      |apply cequivc_refl\n      |apply cequivc_apply_bound_c]\n    |].\n  rw @boundl_c_eq; auto.\nQed.\n\nLemma substc_mkcv_axiom {o} :\n  forall v (t : @CTerm o),\n    substc t v (mkcv_axiom v) = mkc_axiom.\nProof.\n  introv; destruct_cterms.\n  apply cterm_eq; simpl.\n  unfsubst.\nQed.\n\nLemma spM_in_modulus_fun_type_u {o} :\n  forall lib (F : @CTerm o),\n    member lib F (mkc_fun nat2nat mkc_tnat)\n    -> member lib (spM_c F) modulus_fun_type_u.\nProof.\n  introv mF.\n\n  unfold modulus_fun_type_u.\n  apply equality_in_function2.\n  fold (@modulus_fun_type_u o).\n  dands; try (apply type_modulus_fun_type_u).\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      apply type_tnat.\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\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 (@natk2nat o (mkc_nat k)) 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_natk2nat_implies_equality_bound lib f g k 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    pose proof (apply_nat2natE_aux2\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) as ee.\n    repeat (autodimp ee hyp); try (complete (intro xx; ginv));[].\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\nDefinition get_ints_from_computes_to_value {o}\n           (lib : @library o)\n           (t u : @NTerm o)\n           (comp : computes_to_value lib t u) : list Z :=\n  match comp with\n    | (c,_) => get_ints_from_computation lib t u c\n  end.\n\nDefinition get_ints_from_computes_to_valc {o}\n           (lib : @library o)\n           (t u : @CTerm o)\n           (comp : computes_to_valc lib t u) : list Z :=\n  get_ints_from_computes_to_value lib (get_cterm t) (get_cterm u) comp.\n\nLemma cequivc_nat {o} :\n  forall lib (t t' : @CTerm o) (n : nat),\n    computes_to_valc lib t (mkc_nat n)\n    -> cequivc lib t t'\n    -> computes_to_valc lib t' (mkc_nat n).\nProof.\n  introv comp ceq; destruct_cterms;\n  allunfold @computes_to_valc; allunfold @cequivc; allsimpl.\n  eapply cequiv_nat; eauto.\nQed.\n\nDefinition force_nat {o} (arg : @NTerm o) x z (f : @NTerm o) :=\n  mk_cbv arg x (mk_less (mk_var x)\n                        mk_zero\n                        (mk_vbot z)\n                        (mk_apply f (mk_var x))).\n\nDefinition force_nat_c {o} (arg : @CTerm o) x z (f : @CTerm o) : CTerm :=\n  mkc_cbv\n    arg\n    x\n    (mkcv_less\n       [x]\n       (mkc_var x)\n       (mkcv_zero [x])\n       (mkcv_vbot [x] z)\n       (mkcv_apply [x] (mk_cv [x] f) (mkc_var x))).\n\nLemma get_cterm_force_nat_c {o} :\n  forall (arg : @CTerm o) x z f,\n    get_cterm (force_nat_c arg x z f)\n    = force_nat (get_cterm arg) x z (get_cterm f).\nProof.\n  introv; destruct_cterms; simpl; auto.\nQed.\n\nDefinition lam_force_nat_c {o} x z (f : @CTerm o) : CTerm :=\n  mkc_lam\n    x\n    (mkcv_cbv\n       [x]\n       (mkc_var x)\n       x\n       (mkcv_dup1\n          x\n          (mkcv_less\n             [x]\n             (mkc_var x)\n             (mkcv_zero [x])\n             (mkcv_vbot [x] z)\n             (mkcv_apply [x] (mk_cv [x] f) (mkc_var x))))).\n\nLemma cequivc_mkc_apply_lam_force_nat_c {o} :\n  forall lib x z (f arg : @CTerm o),\n    cequivc\n      lib\n      (mkc_apply (lam_force_nat_c x z f) arg)\n      (force_nat_c arg x z f).\nProof.\n  introv.\n  eapply cequivc_trans;[unfold lam_force_nat_c;apply cequivc_beta|].\n  rw @mkcv_cbv_substc_same.\n  rw @mkc_var_substc.\n  rw @mkcv_cont1_dup1; eauto 3 with slow.\nQed.\n\nLemma equality_lam_force_nat_c_in_nat2nat {o} :\n  forall lib x z (f : @CTerm o),\n    member lib f nat2nat\n    -> equality lib f (lam_force_nat_c x z f) nat2nat.\nProof.\n  introv mem.\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 eq_mkc_nat_implies {o} :\n  forall k1 k2, @mkc_nat o k1 = mkc_nat k2 -> k1 = k2.\nProof.\n  introv e.\n  inversion e as [q].\n  allapply Znat.Nat2Z.inj; auto.\nQed.\n\nDefinition bound2_cbv_c {o} x z (n f e : @CTerm o) :=\n  mkc_lam\n    x\n    (mkcv_cbv\n       [x]\n       (mkc_var x)\n       x\n       (mkcv_dup1\n          x\n          (mkcv_less\n             [x]\n             (mkc_var x)\n             (mkcv_zero [x])\n             (mkcv_vbot [x] z)\n             (mkcv_less\n                [x]\n                (mkc_var x)\n                (mk_cv [x] n)\n                (mkcv_apply [x] (mk_cv [x] f) (mkc_var x))\n                (mk_cv [x] (mkc_exception e mkc_axiom)))))).\n\nLemma cequiv_bound2_c_cbv {o} :\n  forall lib x z (n f e : @CTerm o),\n    cequivc\n      lib\n      (bound2_c x z n f e)\n      (bound2_cbv_c x z n f e).\nProof.\n  introv.\n  apply cequivc_lam; introv.\n  allrw @mkcv_less_substc.\n  allrw @mkcv_cbv_substc_same.\n  allrw @mkcv_cont1_dup1.\n  allrw @mkcv_apply_substc.\n  allrw @substc_mkcv_zero.\n  allrw @mkc_var_substc.\n  allrw @csubst_mk_cv.\n  allrw @mkcv_vbot_substc.\n\n  apply approxc_implies_cequivc; apply approxc_assume_hasvalue; intro hv.\n\n  - apply hasvalue_likec_less in hv.\n    repndors; exrepnd.\n\n    + clear hv1 hv3 hv2.\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_mkc_less;\n          [apply reduces_toc_implies_cequivc;exact hv0\n          |apply cequivc_refl\n          |apply implies_cequivc_apply;\n            [apply cequivc_refl\n            |apply reduces_toc_implies_cequivc;exact hv0]\n          |apply cequivc_refl]\n        ]\n      |].\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\n      clear dependent u.\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      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      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      boolvar; eauto 3 with slow; try (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.\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_mkc_less;\n             [apply cequivc_sym\n             |apply cequivc_refl\n             |apply implies_cequivc_apply;\n               [apply cequivc_refl\n               |apply cequivc_sym]\n             |apply cequivc_refl]\n           ];\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      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      apply approxc_refl.\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.\nQed.\n\nDefinition sp_force_nat {o} (arg : @NTerm o) x z (f : @NTerm o) :=\n  mk_cbv arg x (mk_less (mk_var x) mk_zero (mk_vbot z) (mk_apply f (mk_var x))).\n\nDefinition bound2_cbv {o} arg x z (n : nat) (f : @NTerm o) a : NTerm :=\n  mk_cbv\n    arg\n    x\n    (mk_less\n       (mk_var x)\n       mk_zero\n       (mk_vbot z)\n       (mk_less (mk_var x) (mk_nat n) (mk_apply f (mk_var x)) (spexc a))).\n\nLemma alpha_eq_sp_force_nat {o} :\n  forall (arg1 arg2 : @NTerm o) x1 x2 z1 z2 f1 f2,\n    isprog f1\n    -> alpha_eq f1 f2\n    -> alpha_eq arg1 arg2\n    -> alpha_eq (sp_force_nat arg1 x1 z1 f1) (sp_force_nat arg2 x2 z2 f2).\nProof.\n  introv ispf aeq1 aeq2.\n  applydup @alpha_eq_preserves_isprog in aeq1; auto.\n  unfold sp_force_nat, mk_cbv, mk_less, mk_apply, mk_vbot, mk_lam, mk_fix, mk_zero, nobnd.\n\n  prove_alpha_eq4.\n  introv ln.\n  repeat (destruct n; tcsp); eauto 3 with slow;[].\n  clear ln.\n\n  pose proof (ex_fresh_var (x1 :: x2\n                               :: z1\n                               :: z2\n                               :: free_vars f1\n                               ++ bound_vars f1\n                               ++ free_vars f2\n                               ++ bound_vars f2)) as h;\n    exrepnd.\n  allsimpl; allrw in_app_iff; allrw not_over_or; repnd; GC.\n\n  apply (al_bterm_aux [v]); simpl; auto.\n\n  { unfold all_vars; simpl.\n    allrw remove_nvars_nil_l; allrw app_nil_r.\n    allrw @remove_nvars_eq; allsimpl.\n    allrw disjoint_singleton_l; allsimpl.\n    repeat (allrw in_app_iff; simpl).\n    tcsp. }\n\n  allrw <- beq_var_refl.\n  allrw memvar_singleton.\n  repeat (rw (lsubst_aux_trivial_cl_term2 f1); eauto 2 with slow).\n  repeat (rw (lsubst_aux_trivial_cl_term2 f2); eauto 2 with slow).\n\n  prove_alpha_eq4.\n  introv ln.\n\n  repeat (destruct n; tcsp; try omega); eauto 3 with slow;\n  clear ln;\n  apply alphaeqbt_nilv2;\n  prove_alpha_eq4;\n  introv ln;\n  repeat (destruct n; tcsp; try omega); eauto 3 with slow;[].\n  clear ln.\n\n  apply alphaeqbt_nilv2.\n  prove_alpha_eq4.\n  introv ln.\n  repeat (destruct n; tcsp; try omega); eauto 3 with slow;[].\n  clear ln.\n\n  pose proof (ex_fresh_var (x1 :: x2\n                               :: z1\n                               :: z2\n                               :: [])) as h;\n    exrepnd.\n  allsimpl; allrw in_app_iff; allrw not_over_or; repnd; GC.\n\n  apply (al_bterm_aux [v0]); simpl; auto.\n\n  { unfold all_vars; simpl; repeat (boolvar; allsimpl);\n    allrw disjoint_singleton_l; allsimpl; tcsp. }\n\n  repeat (boolvar; simpl); tcsp; eauto 2 with slow.\nQed.\n\nLemma alpha_eq_bound2_cbv {o} :\n  forall (arg1 arg2 : @NTerm o) x1 x2 z1 z2 b f1 f2 a,\n    isprog f1\n    -> alpha_eq f1 f2\n    -> alpha_eq arg1 arg2\n    -> alpha_eq (bound2_cbv arg1 x1 z1 b f1 a) (bound2_cbv arg2 x2 z2 b f2 a).\nProof.\n  introv ispf aeq1 aeq2.\n  applydup @alpha_eq_preserves_isprog in aeq1; auto.\n  unfold bound2_cbv, mk_cbv, mk_less, mk_apply, mk_vbot, mk_lam, mk_fix, mk_zero, nobnd.\n\n  prove_alpha_eq4.\n  introv ln.\n  repeat (destruct n; tcsp); eauto 3 with slow;[].\n  clear ln.\n\n  pose proof (ex_fresh_var (x1 :: x2\n                               :: z1\n                               :: z2\n                               :: free_vars f1\n                               ++ bound_vars f1\n                               ++ free_vars f2\n                               ++ bound_vars f2)) as h;\n    exrepnd.\n  allsimpl; allrw in_app_iff; allrw not_over_or; repnd; GC.\n\n  apply (al_bterm_aux [v]); simpl; auto.\n\n  { unfold all_vars; simpl.\n    allrw remove_nvars_nil_l; allrw app_nil_r.\n    allrw @remove_nvars_eq; allsimpl.\n    allrw disjoint_singleton_l; allsimpl.\n    repeat (allrw in_app_iff; simpl).\n    tcsp. }\n\n  allrw <- beq_var_refl.\n  allrw memvar_singleton.\n  repeat (rw (lsubst_aux_trivial_cl_term2 f1); eauto 2 with slow).\n  repeat (rw (lsubst_aux_trivial_cl_term2 f2); eauto 2 with slow).\n\n  prove_alpha_eq4.\n  introv ln.\n  repeat (destruct n; tcsp; try omega); eauto 3 with slow;\n  clear ln;\n  apply alphaeqbt_nilv2;\n  prove_alpha_eq4;\n  introv ln;\n  repeat (destruct n; tcsp; try omega); eauto 3 with slow;\n  clear ln;\n  apply alphaeqbt_nilv2;\n  prove_alpha_eq4;\n  introv ln;\n  repeat (destruct n; tcsp; try omega); eauto 3 with slow;[].\n  clear ln.\n\n  pose proof (ex_fresh_var (x1 :: x2\n                               :: z1\n                               :: z2\n                               :: [])) as h;\n    exrepnd.\n  allsimpl; allrw in_app_iff; allrw not_over_or; repnd; GC.\n\n  apply (al_bterm_aux [v0]); simpl; auto.\n\n  { unfold all_vars; simpl; repeat (boolvar; allsimpl);\n    allrw disjoint_singleton_l; allsimpl; tcsp. }\n\n  repeat (boolvar; simpl); tcsp; eauto 2 with slow.\nQed.\n\nLemma so_alphaeq_preserves_no_utokens {o} :\n  forall (t1 t2 : @SOTerm o),\n    so_alphaeq t1 t2\n    -> no_utokens t1\n    -> no_utokens t2.\nProof.\n  introv aeq nout.\n  apply get_utokens_so_soalphaeq in aeq.\n  allunfold @no_utokens.\n  rw aeq in nout; auto.\nQed.\nHint Resolve so_alphaeq_preserves_no_utokens : slow.\n\nDefinition computation_fails {o} lib (t : @NTerm o) :=\n  {s : String.string\n   & {u : NTerm\n   & {k : nat\n   & compute_at_most_k_steps lib k t = cfailure s u}}}.\n\nLemma alpha_eq_subst_sp_force_nat_alpha_eq {o} :\n  forall v z (f : @NTerm o) t,\n    isprog f\n    -> alpha_eq\n         (subst (mk_less (mk_var v) mk_zero (mk_vbot z) (mk_apply f (mk_var v))) v t)\n         (mk_less t mk_zero (mk_vbot z) (mk_apply f t)).\nProof.\n  introv isp.\n  pose proof (unfold_lsubst\n                [(v,t)]\n                (mk_less (mk_var v) mk_zero (mk_vbot z) (mk_apply f (mk_var v))))\n    as unf; exrepnd.\n  unfold subst.\n  rw unf0; clear unf0.\n  allapply @alpha_eq_mk_less; exrepnd; subst.\n  allapply @alpha_eq_mk_var; subst.\n  allapply @alpha_eq_mk_vbot; exrepnd; subst.\n  allapply @alpha_eq_mk_zero; subst.\n  allapply @alpha_eq_mk_apply; exrepnd; subst.\n  allapply @alpha_eq_mk_var; subst.\n\n  allsimpl; cpx; ginv.\n\n  allrw app_nil_r.\n  allrw disjoint_cons_l.\n  repnd.\n  rename a' into f'.\n\n  allrw memvar_singleton.\n  allrw <- @beq_var_refl.\n  rw (@lsubst_aux_trivial_cl_term2 o f'); eauto 3 with slow.\n\n  unfold mk_less, mk_apply, mk_vbot, mk_zero, mk_nat, mk_integer, mk_fix, mk_lam, mk_var, nobnd.\n  repeat (prove_alpha_eq4; eauto 2 with slow).\n\n  { pose proof (ex_fresh_var (v' :: z :: [])) as fv.\n    exrepnd; allsimpl; allrw not_over_or; repnd; GC.\n    apply (al_bterm_aux [v0]); simpl; auto;\n    repeat (boolvar; simpl); tcsp;\n    allrw disjoint_singleton_l; allsimpl; tcsp. }\nQed.\n\nLemma wf_bound2_cbv {o} :\n  forall (arg : @NTerm o) x z b f a,\n    wf_term (bound2_cbv arg x z b f a) <=> (wf_term arg # wf_term f).\nProof.\n  introv.\n  unfold bound2_cbv.\n  rw <- @wf_cbv_iff.\n  repeat (rw <- @wf_less_iff).\n  rw <- @wf_apply_iff.\n  split; intro h; repnd; dands; eauto 3 with slow.\nQed.\n\nLemma wf_sp_force_nat {o} :\n  forall (arg : @NTerm o) x z f,\n    wf_term (sp_force_nat arg x z f) <=> (wf_term arg # wf_term f).\nProof.\n  introv.\n  rw <- @wf_cbv_iff.\n  repeat (rw <- @wf_less_iff).\n  rw <- @wf_apply_iff.\n  split; intro h; repnd; dands; eauto 3 with slow.\nQed.\n\nLemma hasvalue_like_vbot {o} :\n  forall (lib : @library o) z,\n    !hasvalue_like lib (mk_vbot z).\nProof.\n  introv hv.\n  unfold hasvalue_like in hv; exrepnd.\n  apply reduces_to_vbot_if_isvalue_like in hv1; sp.\nQed.\n\nLemma not_hasvalue_like_fresh {o} :\n  forall lib (v : NVar), !@hasvalue_like o lib (mk_fresh v (mk_var v)).\nProof.\n  introv hv.\n  unfold hasvalue_like in hv; exrepnd.\n  apply reduces_in_atmost_k_step_fresh_id in hv1; sp.\nQed.\n\nLemma hasvalue_like_subst_less_seq {o} :\n  forall lib (f : @ntseq o) v a b c,\n    hasvalue_like\n      lib\n      (subst (mk_less (mk_var v) a b c) v (sterm f))\n    -> False.\nProof.\n  introv comp.\n  unfold subst, lsubst in comp; allsimpl; boolvar;\n  repndors; try (subst v'); tcsp;\n  allrw not_over_or; repnd; GC;\n  try (complete (match goal with\n                   | [ H : context[fresh_var ?l] |- _ ] =>\n                     let h := fresh \"h\" in\n                     pose proof (fresh_var_not_in l) as h;\n                   unfold all_vars in h;\n                   simpl in h;\n                   repeat (rw in_app_iff in h);\n                   repeat (rw not_over_or in h);\n                   repnd; allsimpl; tcsp\n                 end));\n  allsimpl; boolvar; tcsp; fold_terms; allrw app_nil_r.\n\n  unfold hasvalue_like, reduces_to in comp; exrepnd.\n\n  destruct k.\n\n  - allrw @reduces_in_atmost_k_steps_0; repnd; subst.\n    unfold isvalue_like in comp0; allsimpl; tcsp.\n\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    csunf comp2; allsimpl; ginv.\nQed.\n\n\n\n(*\n*** Local Variables:\n*** coq-load-path: (\".\" \"./close/\")\n*** End:\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_defs4_aux.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.26047062330999227}}
{"text": "Require Import Coq.Arith.Compare_dec.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.Lists.List.\nRequire Import FunctionNinjas.All.\nRequire Import ListPlus.All.\n\nImport ListNotations.\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 -> bool;\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\nModule Sequential.\n  Inductive t (E : Effect.t) : Type :=\n  | Ret : t E\n  | Call : forall c, (Effect.answer E c -> t E) -> t E.\n  Arguments Ret {E}.\n  Arguments Call {E} _ _.\nEnd Sequential.\n\nModule Concurrent.\n  Definition t (E : Effect.t) := list (Sequential.t E).\nEnd Concurrent.\n\nModule Choose.\n  Inductive t (E : Effect.t) : Type :=\n  | Ret : t E\n  | Call : forall c, (Effect.answer E c -> t E) -> t E\n  | Choose : t E -> t E -> t E.\n  Arguments Ret {E}.\n  Arguments Call {E} _ _.\n  Arguments Choose {E} _ _.\n\n  Fixpoint lift {E} (x : Sequential.t E) : t E :=\n    match x with\n    | Sequential.Ret => Ret\n    | Sequential.Call c h => Choose.Call c (fun a => lift (h a))\n    end.\n\n  Module Mix.\n    Inductive t {E} : Sequential.t E -> Choose.t E -> Type :=\n    | RetRet : t Sequential.Ret Choose.Ret\n    | RetCall : forall c h, t Sequential.Ret (Choose.Call c h)\n    | RetChoose : forall x1 x2, t Sequential.Ret (Choose.Choose x1 x2)\n    | CallRet : forall c h, t (Sequential.Call c h) Choose.Ret\n    | CallCall : forall c_x h_x c_y h_y,\n      (forall a, t (h_x a) (Choose.Call c_y h_y)) ->\n      (forall a, t (Sequential.Call c_x h_x) (h_y a)) ->\n      t (Sequential.Call c_x h_x) (Choose.Call c_y h_y)\n    | CallChoose : forall c h y1 y2,\n      t (Sequential.Call c h) y1 -> t (Sequential.Call c h) y2 ->\n      t (Sequential.Call c h) (Choose.Choose y1 y2).\n    Arguments RetRet {E}.\n    Arguments RetCall {E} _ _.\n    Arguments RetChoose {E} _ _.\n    Arguments CallRet {E} _ _.\n    Arguments CallCall {E c_x h_x c_y h_y} _ _.\n    Arguments CallChoose {E c h y1 y2} _ _.\n\n    Fixpoint make_call {E} (x : Sequential.t E)\n      (c_y : Effect.command E) (h_y : Effect.answer E c_y -> Choose.t E)\n      (z : forall x a, t x (h_y a)) : t x (Choose.Call c_y h_y) :=\n      match x with\n      | Sequential.Ret => RetCall c_y h_y\n      | Sequential.Call c_x h_x =>\n        CallCall (fun a => make_call (h_x a) c_y h_y z)\n          (fun a => z (Sequential.Call c_x h_x) a)\n      end.\n\n    Fixpoint make {E} (x : Sequential.t E) (y : Choose.t E) : t x y :=\n      match y with\n      | Choose.Ret =>\n        match x with\n        | Sequential.Ret => RetRet\n        | Sequential.Call c_x h_x => CallRet c_x h_x\n        end\n      | Choose.Call c_y h_y => make_call x c_y h_y (fun x a => make x (h_y a))\n      | Choose.Choose y1 y2 =>\n        match x with\n        | Sequential.Ret => RetChoose y1 y2\n        | Sequential.Call c_x h_x =>\n          CallChoose (make (Sequential.Call c_x h_x) y1)\n            (make (Sequential.Call c_x h_x) y2)\n        end\n      end.\n\n    Fixpoint compile {E} {x y} (xy : t x y) : Choose.t E :=\n      match xy with\n      | RetRet => Choose.Ret\n      | RetCall c_y h_y => Choose.Call c_y h_y\n      | RetChoose y1 y2 => Choose.Choose y1 y2\n      | CallRet c_x h_x => Choose.Call c_x (fun a => lift (h_x a))\n      | CallCall c_x _ c_y _ m_x m_y =>\n        Choose.Choose (Choose.Call c_x (fun a => compile (m_x a)))\n          (Choose.Call c_y (fun a => compile (m_y a)))\n      | CallChoose _ _ _ _ m_y1 m_y2 =>\n        Choose.Choose (compile m_y1) (compile m_y2)\n      end.\n  End Mix.\n\n  Fixpoint compile {E} (xs : Concurrent.t E) : Choose.t E :=\n    match xs with\n    | [] => Ret\n    | x :: xs => Mix.compile (Mix.make x (compile xs))\n    end.\n\n  Fixpoint is_not_stuck {E S} (m : Model.t E S) (x : Choose.t E) (s : S)\n    : bool :=\n    match x with\n    | Ret => true\n    | Call c _ => Model.condition m c s\n    | Choose x1 x2 => orb (is_not_stuck m x1 s) (is_not_stuck m x2 s)\n    end.\n\n  Fixpoint aux {E S} (m : Model.t E S) (post : S -> bool) (x : Choose.t E)\n    (s : S) : bool :=\n    match x with\n    | Ret => post s\n    | Call c h =>\n      if Model.condition m c s then\n        let a := Model.answer m c s in\n        let s := Model.state m c s in\n        andb (is_not_stuck m (h a) s) (aux m post (h a) s)\n      else\n        true\n    | Choose x1 x2 => andb (aux m post x1 s) (aux m post x2 s)\n    end.\n\n  Definition check {E S} (m : Model.t E S) (post : S -> bool) (x : Choose.t E)\n    (s : S) : bool :=\n    andb (is_not_stuck m x s) (aux m post x s).\nEnd Choose.\n\nModule Examples.\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 ret : Sequential.t E :=\n    Sequential.Ret.\n\n  Definition lock (h : Sequential.t E) : Sequential.t E :=\n    Sequential.Call (E := E) Command.Lock (fun _ => h).\n\n  Definition unlock (h : Sequential.t E) : Sequential.t E :=\n    Sequential.Call (E := E) Command.Unlock (fun _ => h).\n\n  Definition condition (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 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 answer state.\n\n  Fixpoint ex1 (n : nat) : Concurrent.t E :=\n    match n with\n    | O => []\n    | Datatypes.S n =>\n      (lock @@\n      unlock @@\n      ret) :: ex1 n\n    end.\n\n  Definition is_ex1_ok : bool :=\n    Choose.check m (fun _ => true) (Choose.compile @@ ex1 9) false.\n\n  (* Time Compute is_ex1_ok. *)\nEnd Examples.\n\nModule Increment.\n  Definition S := nat.\n\n  Module Command.\n    Inductive t :=\n    | Read\n    | Write (s : S).\n  End Command.\n\n  Definition E : Effect.t :=\n    Effect.New Command.t (fun c =>\n      match c with\n      | Command.Read => S\n      | Command.Write _ => unit\n      end).\n\n  Definition ret : Sequential.t E :=\n    Sequential.Ret.\n\n  Definition read (h : S -> Sequential.t E) : Sequential.t E :=\n    Sequential.Call (E := E) Command.Read h.\n\n  Definition write (s : S) (h : Sequential.t E) : Sequential.t E :=\n    Sequential.Call (E := E) (Command.Write s) (fun _ => h).\n\n  Definition condition (c : Effect.command E) (s : S) : bool :=\n    true.\n\n  Definition answer (c : Effect.command E) (s : S) : Effect.answer E c :=\n    match c with\n    | Command.Read => s\n    | Command.Write _ => tt\n    end.\n\n  Definition state (c : Effect.command E) (s : S) : S :=\n    match c with\n    | Command.Read => s\n    | Command.Write s => s\n    end.\n\n  Definition m : Model.t E S :=\n    Model.New condition answer state.\n\n  Definition process : Sequential.t E :=\n    read (fun s =>\n    write (s + 1)\n    ret).\n\n  Definition post (n : nat) (s : S) : bool :=\n    beq_nat n s.\n\n  Definition result (n : nat) : bool :=\n    Choose.check m (post n) (Choose.compile @@ List.repeat process n) 0.\nEnd Increment.\n\nModule AtomicIncrement.\n  Definition S := nat.\n\n  Module Command.\n    Inductive t :=\n    | Increment.\n  End Command.\n\n  Definition E : Effect.t :=\n    Effect.New Command.t (fun c =>\n      match c with\n      | Command.Increment => unit\n      end).\n\n  Definition ret : Sequential.t E :=\n    Sequential.Ret.\n\n  Definition increment (h : Sequential.t E) : Sequential.t E :=\n    Sequential.Call (E := E) Command.Increment (fun _ => h).\n\n  Definition condition (c : Effect.command E) (s : S) : bool :=\n    true.\n\n  Definition answer (c : Effect.command E) (s : S) : Effect.answer E c :=\n    match c with\n    | Command.Increment => tt\n    end.\n\n  Definition state (c : Effect.command E) (s : S) : S :=\n    match c with\n    | Command.Increment => s + 1\n    end.\n\n  Definition m : Model.t E S :=\n    Model.New condition answer state.\n\n  Definition process : Sequential.t E :=\n    increment\n    ret.\n\n  Definition post (n : nat) (s : S) : bool :=\n    beq_nat n s.\n\n  Definition result (n : nat) : bool :=\n    Choose.check m (post n) (Choose.compile @@ List.repeat process n) 0.\nEnd AtomicIncrement.\n\nModule SimpleChannel.\n  Definition S := option nat.\n\n  Module Command.\n    Inductive t :=\n    | Send (x : nat)\n    | Receive.\n  End Command.\n\n  Definition E : Effect.t :=\n    Effect.New Command.t (fun c =>\n      match c with\n      | Command.Send _ => unit\n      | Command.Receive => nat\n      end).\n\n  Definition ret : Sequential.t E :=\n    Sequential.Ret.\n\n  Definition send (n : nat) (h : Sequential.t E) : Sequential.t E :=\n    Sequential.Call (E := E) (Command.Send n) (fun _ => h).\n\n  Definition receive (h : nat -> Sequential.t E) : Sequential.t E :=\n    Sequential.Call (E := E) Command.Receive h.\n\n  Definition condition (c : Effect.command E) (s : S) : bool :=\n    match (c, s) with\n    | (Command.Send _, None) | (Command.Receive, Some _) => true\n    | (Command.Send _, Some _) | (Command.Receive, None) => false\n    end.\n\n  Definition answer (c : Effect.command E) (s : S) : Effect.answer E c :=\n    match c with\n    | Command.Send _ => tt\n    | Command.Receive =>\n      match s with\n      | None => 0\n      | Some n => n\n      end\n    end.\n\n  Definition state (c : Effect.command E) (s : S) : S :=\n    match c with\n    | Command.Send n => Some n\n    | Command.Receive => None\n    end.\n\n  Definition m : Model.t E S :=\n    Model.New condition answer state.\n\n  Definition ex : Concurrent.t E :=\n    [receive (fun _ => ret); send 12 ret].\n\n  Definition result : bool :=\n    Choose.check m (fun _ => true) (Choose.compile ex) (None).\nEnd SimpleChannel.\n\n(** See `spin/database.spin`. *)\nModule Database.\n  Record S := New {\n    holder : nat;\n    up : list bool;\n    ack : list nat }.\n\n  Definition init (n : nat) : S :=\n    New n (List.repeat false n) (List.repeat 0 n).\n\n  Module Command.\n    Inductive t :=\n    | UpdateSend (id : nat)\n    | ReceiveAck (id : nat)\n    | Receive (id : nat)\n    | Ack.\n  End Command.\n\n  Definition E : Effect.t :=\n    Effect.New Command.t (fun c => unit).\n\n  Definition condition (n : nat) (c : Effect.command E) (s : S) : bool :=\n    match c with\n    | Command.UpdateSend id => beq_nat id (holder s)\n    | Command.ReceiveAck id => beq_nat (List.nth id (ack s) n) (n - 1)\n    | Command.Receive id =>\n      andb (List.nth id (up s) false) (\n        match nat_compare (holder s) n with\n        | Lt => true\n        | _ => false\n        end)\n    | Command.Ack => true\n    end.\n\n  Definition answer (c : Effect.command E) (s : S) : Effect.answer E c :=\n    tt.\n\n  Fixpoint list_udpate {A} (l : list A) (n : nat) (x : A) : list A :=\n    match (l, n) with\n    | ([], _) => []\n    | (_ :: l, O) => x :: l\n    | (x' :: l, Datatypes.S n) => x' :: list_udpate l n x\n    end.\n\n  Definition state (n : nat) (c : Effect.command E) (s : S) : S :=\n    match c with\n    | Command.UpdateSend id => New id (List.repeat true n) (ack s)\n    | Command.ReceiveAck id => New n (up s) (list_udpate (ack s) id 0)\n    | Command.Receive id => New (holder s) (list_udpate (up s) id false) (ack s)\n    | Command.Ack =>\n      let a := List.nth (holder s) (ack s) 0 in\n      New (holder s) (up s) (list_udpate (ack s) (holder s) (a + 1))\n    end.\n\n  Definition m (n : nat) : Model.t E S :=\n    Model.New (condition n) answer (state n).\n\n  Definition process_write (id : nat) : Sequential.t E :=\n    Sequential.Call (E := E) (Command.UpdateSend id) (fun _ =>\n    Sequential.Call (E := E) (Command.ReceiveAck id) (fun _ =>\n    Sequential.Ret)).\n\n  Definition process_read (id : nat) : Sequential.t E :=\n    Sequential.Call (E := E) (Command.Receive id) (fun _ =>\n    Sequential.Call (E := E) Command.Ack (fun _ =>\n    Sequential.Ret)).\n\n  Fixpoint processes_read (n : nat) : Concurrent.t E :=\n    match n with\n    | O => []\n    | Datatypes.S n => process_read n :: processes_read n\n    end.\n\n  Definition ex (n : nat) : Concurrent.t E :=\n    process_write n :: processes_read n.\n\n  Definition result (n : nat) : bool :=\n    Choose.check (m (n + 1)) (fun _ => true) (Choose.compile @@ ex n) (init (n + 1)).\nEnd Database.\n\n(** * Extraction *)\nRequire Import Io.All.\nRequire Import Io.System.All.\nRequire Import ListString.All.\n\nImport C.Notations.\n\nDefinition result (argv : list LString.t) : C.t System.effect unit :=\n  (* if Examples.is_ex1_ok then *)\n  (* if Increment.result 2 then *)\n  (* if AtomicIncrement.result 11 then *)\n  (* if SimpleChannel.result then *)\n  if Database.result 0 then\n    System.log (LString.s \"OK\")\n  else\n    System.log (LString.s \"error\").\n\nDefinition main := Extraction.launch result.\nExtraction \"extraction/main\" main.\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/SimpleSmallSteps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573377, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.260470617102813}}
{"text": "(* Lifting pseudofunctors to pseudofunctors on algebras *)\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\n\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.Core.NaturalTransformations.\nRequire Import UniMath.CategoryTheory.Groupoids.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Core.\nRequire Import UniMath.Bicategories.Core.Bicat. Import Bicat.Notations.\nRequire Import UniMath.Bicategories.Core.Examples.OneTypes.\nRequire Import UniMath.Bicategories.Core.Invertible_2cells.\nRequire Import UniMath.Bicategories.Morphisms.Adjunctions.\nRequire Import UniMath.Bicategories.Core.Univalence.\nRequire Import UniMath.Bicategories.Core.Unitors.\nRequire Import UniMath.Bicategories.Core.BicategoryLaws.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.PseudoFunctorBicat.\nRequire Import UniMath.Bicategories.PseudoFunctors.PseudoFunctor.\nImport PseudoFunctor.Notations.\nRequire Import UniMath.Bicategories.PseudoFunctors.Biadjunction.\nRequire Import UniMath.Bicategories.PseudoFunctors.Examples.Identity.\nRequire Import UniMath.Bicategories.PseudoFunctors.Examples.Composition.\nRequire Import UniMath.Bicategories.Transformations.PseudoTransformation.\nRequire Import UniMath.Bicategories.Transformations.Examples.Whiskering.\nRequire Import UniMath.Bicategories.Transformations.Examples.Unitality.\nRequire Import UniMath.Bicategories.Transformations.Examples.Associativity.\nRequire Import UniMath.Bicategories.Modifications.Modification.\nRequire Import UniMath.Bicategories.DisplayedBicats.DispBicat.\nImport DispBicat.Notations.\nRequire Import UniMath.Bicategories.DisplayedBicats.Examples.Algebras.\nRequire Import UniMath.Bicategories.DisplayedBicats.DispPseudofunctor.\nRequire Import UniMath.Bicategories.DisplayedBicats.DispTransformation.\nRequire Import UniMath.Bicategories.DisplayedBicats.DispModification.\nRequire Import UniMath.Bicategories.DisplayedBicats.DispBuilders.\n\nRequire Import signature.hit_signature.\nRequire Import prelude.all.\nRequire Import hit_biadjunction.path_groupoid_commute.\nRequire Import hit_biadjunction.gquot_commute.\nRequire Import algebra.one_types_polynomials.\nRequire Import algebra.groupoid_polynomials.\n\nLocal Open Scope cat.\n\nLocal Arguments poly_act_functor_composition_data _ {_ _ _} _ _.\nLocal Arguments poly_act_nat_trans_data _ {_ _ _ _} _.\n\nSection LiftPseudofunctor.\n  Variable (P : poly_code).\n\n  Definition prealg_path_groupoid_map\n             (X : one_type)\n    : (disp_alg_bicat (⟦ P ⟧)) X → (disp_alg_bicat ⦃ P ⦄) (path_groupoid X)\n    := λ f, poly_path_groupoid P X ∙ #path_groupoid f.\n\n  Definition prealg_path_groupoid_mor_comp\n             {X Y : one_type}\n             {f : X → Y}\n             {hX : (disp_alg_bicat (⟦ P ⟧)) X}\n             {hY : (disp_alg_bicat (⟦ P ⟧)) Y}\n             (hf : hX -->[ f] hY)\n             (z : (⦃ P ⦄ (path_groupoid X) : groupoid))\n    : f (hX (pr1 (pr111 (poly_path_groupoid P) X) z))\n      =\n      hY (pr1 ( pr111 (poly_path_groupoid P) Y) (poly_map P f z))\n    := pr1 hf (pr1 (poly_path_groupoid P X) z)\n           @ maponpaths hY (pr11 (psnaturality_of (poly_path_groupoid P) f) z).\n\n  Definition prealg_path_groupoid_mor_is_nat_trans\n             {X Y : one_type}\n             {f : X → Y}\n             {hX : (disp_alg_bicat (⟦ P ⟧)) X}\n             {hY : (disp_alg_bicat (⟦ P ⟧)) Y}\n             (hf : hX -->[ f] hY)            \n    : is_nat_trans\n        (prealg_path_groupoid_map X hX ∙ # path_groupoid f)\n        (# ⦃ P ⦄ (# path_groupoid f) ∙ prealg_path_groupoid_map Y hY)\n        (prealg_path_groupoid_mor_comp hf).\n  Proof.\n    intros x y g.\n    etrans.\n    {\n      refine (maponpaths (λ z, _ @ (z @ _)) _).\n      exact (homotsec_natural\n               (pr1 hf)\n               (# (poly_path_groupoid P X : _ ⟶ _) g)).\n    }\n    refine (path_assoc _ _ _ @ _).\n    etrans.\n    {\n      apply maponpaths_2.\n      refine (path_assoc _ _ _ @ _).\n      apply maponpaths_2.\n      etrans.\n      {\n        apply maponpaths_2.\n        exact (maponpathscomp hX f _).\n      }\n      refine (!(maponpathscomp0 (f ∘ hX)%functions _ _) @ _).\n      apply maponpaths.\n      apply pathsinv0r.\n    }\n    etrans.\n    {\n      apply maponpaths_2.\n      apply pathscomp0lid.\n    }\n    refine (!(path_assoc _ _ _) @ _).\n    refine (_ @ path_assoc _ _ _).\n    apply maponpaths.\n    etrans.\n    {\n      apply maponpaths_2.\n      refine (!_).\n      apply (maponpathscomp _ hY).\n    }\n    refine (!(maponpathscomp0 hY _ _) @ _ @ maponpathscomp0 _ _ _).\n    apply maponpaths.\n    exact (pr21 (psnaturality_of (poly_path_groupoid P) f) _ _ g).\n  Qed.\n \n  Definition prealg_path_groupoid_mor\n             {X Y : one_type}\n             {f : X → Y}\n             {hX : (disp_alg_bicat (⟦ P ⟧)) X}\n             {hY : (disp_alg_bicat (⟦ P ⟧)) Y}\n             (hf : hX -->[ f] hY)\n    : (prealg_path_groupoid_map X hX ∙ # path_groupoid f)\n      ⟹\n      # ⦃ P ⦄ (# path_groupoid f) ∙ prealg_path_groupoid_map Y hY.\n  Proof.\n    use make_nat_trans.\n    - exact (prealg_path_groupoid_mor_comp hf).\n    - exact (prealg_path_groupoid_mor_is_nat_trans hf).\n  Defined.\n\n  Definition prealg_path_groupoid_cell_help\n             {X Y : one_types}\n             {f g : one_types ⟦ X, Y ⟧}\n             (p : f ==> g)\n             (z : poly_act P (X : one_type))\n    : ! poly_homot P p ((pr1 ((poly_path_groupoid P) X)) z)\n    @ (pr11 (psnaturality_of (poly_path_groupoid P) f)) z\n    @ # (poly_path_groupoid P Y : _ ⟶ _)\n          (poly_act_nat_trans_data\n             P\n             (path_to_nattrans p) z)\n    =\n    (pr11 (psnaturality_of (poly_path_groupoid P) g)) z.\n  Proof.\n    induction P as [ A | | P₁ IHP₁ P₂ IHP₂ | P₁ IHP₁ P₂ IHP₂ ].\n    - exact (idpath (idpath z)).\n    - apply pathsinv0l.\n    - induction z as [z | z].\n      + simpl.\n        etrans.\n        {\n          apply maponpaths_2.\n          exact (!(maponpathsinv0 inl _)).\n        }\n        etrans.\n        {\n          apply maponpaths.\n          exact (!(maponpathscomp0 inl _ _)).\n        }\n        refine (!(maponpathscomp0 inl _ _) @ _).\n        apply maponpaths.\n        exact (IHP₁ z).\n      + simpl.\n        etrans.\n        {\n          apply maponpaths_2.\n          exact (!(maponpathsinv0 inr _)).\n        }\n        etrans.\n        {\n          apply maponpaths.\n          exact (!(maponpathscomp0 inr _ _)).\n        }\n        refine (!(maponpathscomp0 inr _ _) @ _).\n        apply maponpaths.\n        exact (IHP₂ z).\n    - simpl.\n      etrans.\n      {\n        apply maponpaths_2.\n        apply pathsdirprod_inv.\n      }\n      etrans.\n      {\n        apply maponpaths.\n        apply pathsdirprod_concat.\n      }\n      refine (pathsdirprod_concat _ _ _ _ @ _).\n      exact (maponpaths (λ z, pathsdirprod z _) (IHP₁ (pr1 z))\n             @ maponpaths (pathsdirprod _) (IHP₂ (pr2 z))).\n  Qed.\n\n  Definition prealg_path_groupoid_cell\n             {X Y : one_types}\n             {f g : one_types ⟦ X, Y ⟧}\n             {p : f ==> g}\n             {hX : (disp_alg_bicat (⟦ P ⟧)) X}\n             {hY : (disp_alg_bicat (⟦ P ⟧)) Y}\n             {hf : hX -->[ f] hY}\n             {hg : hX -->[ g] hY}\n             (hp : hf ==>[ p] hg)\n             (z : (⦃ P ⦄ (path_groupoid X) : groupoid))\n    : p (hX (pr1 (pr111 (poly_path_groupoid P) X) z))\n    @ prealg_path_groupoid_mor_comp hg z\n    =\n    prealg_path_groupoid_mor_comp hf z\n    @ maponpaths hY\n        (# (poly_path_groupoid P Y : _ ⟶ _)\n           (poly_act_nat_trans_data\n              P (path_to_nattrans p) z)).\n  Proof.\n    simpl.\n    unfold prealg_path_groupoid_mor_comp.\n    refine (!_).\n    etrans.\n    {\n      refine (!(path_assoc _ _ _) @ _).\n      apply maponpaths.\n      exact (!(maponpathscomp0 hY _ _)).\n    }\n    assert\n    (pr1 hf ((pr1 ((poly_path_groupoid P) X)) z)\n     =\n     p (hX ((pr1 ((pr111 (poly_path_groupoid P)) X)) z)) @\n       pr1 hg ((pr1 ((poly_path_groupoid P) X)) z)\n     @ maponpaths\n         hY\n         (!(poly_homot P p ((pr1 ((poly_path_groupoid P) X)) z))))\n      as H.\n    {\n      refine (!_).\n      etrans.\n      {\n        refine (path_assoc _ _ _ @ _).\n        apply maponpaths_2.\n        exact (eqtohomot hp ((pr1 ((poly_path_groupoid P) X)) z)).\n      }\n      refine (!(path_assoc _ _ _) @ _).\n      etrans.\n      {\n        apply maponpaths.\n        refine (!(maponpathscomp0 hY _ _) @ _).\n        apply maponpaths.\n        apply pathsinv0r.\n      }\n      apply pathscomp0rid.\n    }\n    etrans.\n    {\n      apply maponpaths_2.\n      exact H.\n    }\n    refine (!(path_assoc _ _ _) @ _).\n    apply maponpaths.\n    refine (!(path_assoc _ _ _) @ _).\n    apply maponpaths.\n    refine (!(maponpathscomp0 hY _ _) @ _).\n    apply maponpaths.\n    exact (prealg_path_groupoid_cell_help p z).\n  Qed.\n\n  Definition prealg_path_groupoid_identitor\n             {X : one_type}\n             (XX : (disp_alg_bicat (⟦ P ⟧)) X)\n             (z : (⦃ P ⦄ (path_groupoid X) : groupoid))\n    : maponpaths\n        XX\n        (poly_id P X ((pr1 ((poly_path_groupoid P) X)) z))\n    @ maponpaths\n        XX\n        ((pr11 (psnaturality_of (poly_path_groupoid P) (λ x : X, x))) z)\n    =\n    maponpaths\n      XX\n      (# (poly_path_groupoid P X : _ ⟶ _)\n         (poly_act_functor_identity_data P (one_type_to_groupoid X) z))\n    @ maponpaths\n        XX\n        (# (poly_path_groupoid P X : _ ⟶ _)\n           (poly_act_nat_trans_data\n              P  (path_groupoid_identitor X) z)).\n  Proof.\n    refine (!(maponpathscomp0 XX _ _) @ _ @ maponpathscomp0 XX _ _).\n    apply maponpaths.\n    clear XX.\n    induction P as [A | | P₁ IHP₁ P₂ IHP₂ | P₁ IHP₁ P₂ IHP₂].\n    - exact (idpath (idpath z)).\n    - exact (idpath (idpath z)).\n    - induction z as [z | z].\n      + exact (!(maponpathscomp0 inl _ _)\n                @ maponpaths (maponpaths inl) (IHP₁ z)\n                @ maponpathscomp0 inl _ _).\n      + exact (!(maponpathscomp0 inr _ _)\n                @ maponpaths (maponpaths inr) (IHP₂ z)\n                @ maponpathscomp0 inr _ _).\n    - exact (pathsdirprod_concat _ _ _ _\n              @ maponpaths (λ z, pathsdirprod z _) (IHP₁ (pr1 z))\n              @ maponpaths (pathsdirprod _) (IHP₂ (pr2 z))\n              @ !(pathsdirprod_concat _ _ _ _)).\n  Qed.\n\n  Definition prealg_mor_inv\n             {X Y : one_types}\n             {f : one_types ⟦ X, Y ⟧}\n             {hX : (disp_alg_bicat (⟦ P ⟧)) X}\n             {hY : (disp_alg_bicat (⟦ P ⟧)) Y}\n             (hf : hX -->[ f] hY)\n    : prealg_path_groupoid_map X hX\n      -->[ # path_groupoid f]\n      prealg_path_groupoid_map Y hY.\n  Proof.\n    use make_invertible_2cell.\n    - exact (prealg_path_groupoid_mor hf).\n    - apply grpd_bicat_is_invertible_2cell.\n  Defined.\n\n  Definition prealg_path_groupoid_compositor_lemma\n             {X Y Z : one_types}\n             (f : one_types ⟦ X, Y ⟧)\n             (g : one_types ⟦ Y, Z ⟧)\n             (z : poly_act P (X : one_type))\n    : maponpaths\n        (# (⟦ P ⟧) g)\n        ((pr11 (psnaturality_of (poly_path_groupoid P) f)) z)\n     @ (pr11 (psnaturality_of (poly_path_groupoid P) g)) (poly_map P f z)\n     @ # (poly_path_groupoid P Z : _ ⟶ _)\n           (poly_act_functor_composition_data\n              P\n              (function_to_functor f) (function_to_functor g) z)\n      @ # (poly_path_groupoid P Z : _ ⟶ _)\n           (poly_act_nat_trans_data P (path_groupoid_compositor f g) z)\n      =\n      poly_comp P f g ((pr1 ((poly_path_groupoid P) X)) z)\n      @ (pr11 (psnaturality_of (poly_path_groupoid P) (λ x, g (f x)))) z.\n  Proof.\n    induction P as [ A | | P₁ IHP₁ P₂ IHP₂ | P₁ IHP₁ P₂ IHP₂ ].\n    - exact (idpath (idpath z)).\n    - exact (idpath (idpath (g(f z)))).\n    - induction z as [z | z].\n      + simpl.\n        refine (_ @ maponpathscomp0 inl _ _).\n        etrans.\n        {\n          apply maponpaths_2.\n          apply coprodf_path_maponpaths_inl.\n        }\n        etrans.\n        {\n          apply maponpaths.\n          etrans.\n          {\n            apply maponpaths.\n            exact (!(maponpathscomp0 inl _ _)).\n          }\n          exact (!(maponpathscomp0 inl _ _)).\n        }\n        refine (!(maponpathscomp0 inl _ _) @ _).\n        exact (maponpaths (maponpaths inl) (IHP₁ z)).\n      + simpl.\n        refine (_ @ maponpathscomp0 inr _ _).\n        etrans.\n        {\n          apply maponpaths_2.\n          apply coprodf_path_maponpaths_inr.\n        }\n        etrans.\n        {\n          apply maponpaths.\n          etrans.\n          {\n            apply maponpaths.\n            exact (!(maponpathscomp0 inr _ _)).\n          }\n          exact (!(maponpathscomp0 inr _ _)).\n        }\n        refine (!(maponpathscomp0 inr _ _) @ _).\n        exact (maponpaths (maponpaths inr) (IHP₂ z)).\n    - simpl.\n      refine (_ @ !(pathsdirprod_concat _ _ _ _)).\n      etrans.\n      {\n        apply maponpaths_2.\n        exact (!(maponpaths_pathsdirprod _ _ _ _)).\n      }\n      etrans.\n      {\n        apply maponpaths.\n        etrans.\n        {\n          apply maponpaths.\n          apply pathsdirprod_concat.\n        }\n        apply pathsdirprod_concat.\n      }\n      refine (pathsdirprod_concat _ _ _ _ @ _).\n      exact (maponpaths (λ z, pathsdirprod z _) (IHP₁ (pr1 z))\n             @ maponpaths (pathsdirprod _) (IHP₂ (pr2 z))).\n  Qed.                        \n  \n  Definition prealg_path_groupoid_compositor_equation\n             {X Y Z : one_types}\n             {f : one_types ⟦ X, Y ⟧}\n             {g : one_types ⟦ Y, Z ⟧}\n             {hX : (disp_alg_bicat (⟦ P ⟧)) X}\n             {hY : (disp_alg_bicat (⟦ P ⟧)) Y}\n             {hZ : (disp_alg_bicat (⟦ P ⟧)) Z}\n             (hf : hX -->[ f] hY)\n             (hg : hY -->[ g] hZ)\n             (z : poly_act P (X : one_type))\n    : ((maponpaths g (prealg_path_groupoid_mor_comp hf z)\n    @ prealg_path_groupoid_mor_comp hg (poly_map P f z))\n    @ maponpaths hZ\n        (# (poly_path_groupoid P Z : _ ⟶ _)\n           (poly_act_functor_composition_data\n              P\n              (function_to_functor f)\n              (function_to_functor g) z)))\n    @ maponpaths hZ\n        (# (poly_path_groupoid P Z : _ ⟶ _)\n           (poly_act_nat_trans_data\n              P\n              (path_groupoid_compositor f g) z))\n    =\n    ((maponpaths g (pr1 hf ((pr1 ((poly_path_groupoid P) X)) z))\n    @ pr1 hg (poly_map P f ((pr1 ((poly_path_groupoid P) X)) z)))\n    @ maponpaths hZ\n        (poly_comp P f g ((pr1 ((poly_path_groupoid P) X)) z)))\n    @ maponpaths hZ\n        ((pr11 (psnaturality_of (poly_path_groupoid P) (λ x, g (f x)))) z).\n  Proof.\n    refine (!_).\n    do 2 refine (!(path_assoc _ _ _) @ _).\n    do 2 refine (_ @ path_assoc _ _ _).\n    refine (!_).\n    etrans.\n    {\n      apply maponpaths_2.\n      apply maponpathscomp0.\n    }\n    refine (!(path_assoc _ _ _) @ _).\n    apply maponpaths.\n    etrans.\n    {\n      apply maponpaths.\n      refine (!(path_assoc _ _ _) @ _).\n      apply maponpaths.\n      etrans.\n      {\n        apply maponpaths.\n        exact (!(maponpathscomp0 hZ _ _)).\n      }\n      exact (!(maponpathscomp0 hZ _ _)).\n    }\n    refine (!_).\n    etrans.\n    {\n      apply maponpaths.\n      exact (!(maponpathscomp0 hZ _ _)).\n    }\n    refine (!_).\n    etrans.\n    {\n      refine (path_assoc _ _ _ @ _).\n      apply maponpaths_2.\n      etrans.\n      {\n        apply maponpaths_2.\n        apply (maponpathscomp hY g).\n      }\n      exact (homotsec_natural'\n               (pr1 hg)\n               (pr11 (psnaturality_of (poly_path_groupoid P) f) z)).\n    }\n    refine (!(path_assoc _ _ _) @ _).\n    apply maponpaths.\n    etrans.\n    {\n      apply maponpaths_2.\n      exact (!(maponpathscomp _ hZ _)).\n    }\n    refine (!(maponpathscomp0 hZ _ _) @ _).\n    apply maponpaths.\n    exact (prealg_path_groupoid_compositor_lemma f g z).\n  Qed.\n  \n  Definition prealg_path_groupoid_compositor\n             {X Y Z : one_types}\n             {f : one_types ⟦ X, Y ⟧}\n             {g : one_types ⟦ Y, Z ⟧}\n             {hX : (disp_alg_bicat (⟦ P ⟧)) X}\n             {hY : (disp_alg_bicat (⟦ P ⟧)) Y}\n             {hZ : (disp_alg_bicat (⟦ P ⟧)) Z}\n             (hf : hX -->[ f] hY)\n             (hg : hY -->[ g] hZ)\n    : alg_disp_cat_2cell\n        ⦃ P ⦄\n        _ _ _ _\n        (psfunctor_comp path_groupoid f g)\n        _ _\n        (prealg_mor_inv hf;; prealg_mor_inv hg)%mor_disp\n        (prealg_mor_inv (hf;; hg)).\n  Proof.\n    use nat_trans_eq.\n    { apply homset_property. }\n    intros z.\n    etrans.\n    {\n      refine (maponpaths (λ z, (z @ _) @ _) _).\n      refine (pathscomp0rid _ @ _).\n      refine (maponpaths (λ z, z @ _) _).\n      apply pathscomp0rid.\n    }\n    refine (!_).\n    etrans.\n    {\n      refine (maponpaths (λ z, (z @ _) @ _) _).\n      refine (pathscomp0rid\n                ((maponpaths\n                    g\n                    (prealg_path_groupoid_mor_comp hf z)\n                  @ idpath _)\n                  @  prealg_path_groupoid_mor_comp hg (poly_map P f z))\n                @ _).\n      refine (maponpaths (λ z, z @ _) _).\n      apply pathscomp0rid.    \n    }\n    exact (prealg_path_groupoid_compositor_equation hf hg z).\n  Qed.\n\n  Definition prealg_path_groupoid\n    : disp_psfunctor\n        (disp_alg_bicat (⟦ P ⟧))\n        (disp_alg_bicat ⦃ P ⦄) path_groupoid.\n  Proof.\n    use make_disp_psfunctor.\n    - apply disp_2cells_isaprop_alg.\n    - apply disp_locally_groupoid_alg.\n    - exact prealg_path_groupoid_map.\n    - exact @prealg_mor_inv.\n    - abstract\n        (intros X Y f g p hX hY hf hg hp ;\n         use nat_trans_eq ;\n         [ apply homset_property\n         | exact (prealg_path_groupoid_cell hp) ]).\n    - abstract\n        (intros X XX ;\n         use nat_trans_eq ;\n         [ apply homset_property\n         | exact (prealg_path_groupoid_identitor XX)]).\n    - exact @prealg_path_groupoid_compositor.\n  Defined.\nEnd LiftPseudofunctor.\n", "meta": {"author": "UniMath", "repo": "GrpdHITs", "sha": "cb5a9af84400eb770392632eb74860d4ebad9306", "save_path": "github-repos/coq/UniMath-GrpdHITs", "path": "github-repos/coq/UniMath-GrpdHITs/GrpdHITs-cb5a9af84400eb770392632eb74860d4ebad9306/code/hit_biadjunction/hit_prealgebra_biadj/lift_path_groupoid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2604192571459823}}
{"text": "From Velus Require Import Common.\nFrom Velus Require Import Operators.\nFrom Velus Require Import CoreExpr.CESyntax.\nFrom Velus Require Import Stc.StcSyntax.\nFrom Velus Require Import Clocks.\n\nFrom Coq Require Import List.\nImport List.ListNotations.\nOpen Scope list_scope.\n\nModule Type STCISVARIABLE\n       (Import Ids   : IDS)\n       (Import Op    : OPERATORS)\n       (Import CESyn : CESYNTAX     Op)\n       (Import Syn   : STCSYNTAX Ids Op CESyn).\n\n  Inductive Is_variable_in_tc: ident -> trconstr -> Prop :=\n  | VarTcDef:\n      forall x ck e,\n        Is_variable_in_tc x (TcDef x ck e)\n  | VarTcCall:\n      forall x i xs ck rst f es,\n        In x xs ->\n        Is_variable_in_tc x (TcCall i xs ck rst f es).\n\n  Definition Is_variable_in (x: ident) (tcs: list trconstr) : Prop :=\n    Exists (Is_variable_in_tc x) tcs.\n\n  Lemma Is_variable_in_variables:\n    forall tcs x,\n      Is_variable_in x tcs <-> In x (variables tcs).\n  Proof.\n    unfold variables.\n    induction tcs as [|[]]; simpl.\n    - split; try contradiction; inversion 1.\n    - split.\n      + inversion_clear 1 as [?? Var|]; try inv Var; auto.\n        right; apply IHtcs; auto.\n      + intros [E|].\n        * subst; left; constructor.\n        * right; apply IHtcs; auto.\n    - setoid_rewrite <-IHtcs; split.\n      + inversion_clear 1 as [?? Var|]; auto; inv Var.\n      + right; auto.\n    - setoid_rewrite <-IHtcs; split.\n      + inversion_clear 1 as [?? Var|]; auto; inv Var.\n      + right; auto.\n    - split.\n      + inversion_clear 1 as [?? Var|]; try inv Var.\n        * apply in_app; auto.\n        * apply in_app; right; apply IHtcs; auto.\n      + rewrite in_app; intros [?|?].\n        * left; constructor; auto.\n        * right; apply IHtcs; auto.\n  Qed.\n\n  Definition is_variable_in_tc_b (x: ident) (tc: trconstr) : bool :=\n    match tc with\n    | TcDef x' _ _ => ident_eqb x x'\n    | TcCall _ xs _ _ _ _ => existsb (ident_eqb x) xs\n    | _ => false\n    end.\n\n  Fact Is_variable_in_tc_reflect:\n    forall x tc,\n      Is_variable_in_tc x tc <-> is_variable_in_tc_b x tc = true.\n  Proof.\n    destruct tc; simpl; split;\n      try discriminate; try now inversion 1.\n    - inversion_clear 1; apply ident_eqb_refl.\n    - rewrite ident_eqb_eq; intro; subst; constructor.\n    - inversion_clear 1.\n      apply existsb_exists; eexists; split; eauto.\n      apply ident_eqb_refl.\n    - rewrite existsb_exists; intros (?&?& E).\n      apply ident_eqb_eq in E; subst.\n      constructor; auto.\n  Qed.\n\n  Lemma Is_variable_in_tc_dec:\n    forall x tc,\n      { Is_variable_in_tc x tc } + { ~ Is_variable_in_tc x tc }.\n  Proof.\n    intros;\n      eapply Bool.reflect_dec, Bool.iff_reflect, Is_variable_in_tc_reflect.\n  Qed.\n\n  (* Definition variables_tc (vars: PS.t) (tc: trconstr) : PS.t := *)\n  (*   match tc with *)\n  (*   | TcDef x _ _         => PS.add x vars *)\n  (*   | TcCall _ xs _ _ _ _ => ps_adds xs vars *)\n  (*   | _ => vars *)\n  (*   end. *)\n\n  (* Lemma variables_tc_empty: *)\n  (*   forall x tc vars, *)\n  (*     PS.In x (variables_tc vars tc) *)\n  (*     <-> PS.In x (variables_tc PS.empty tc) \\/ PS.In x vars. *)\n  (* Proof. *)\n  (*   split; intro Hin. *)\n  (*   - destruct tc; simpl in *; auto. *)\n  (*     + apply PSE.MP.Dec.F.add_iff in Hin as [|]; subst; intuition. *)\n  (*     + rewrite ps_adds_spec in *; tauto. *)\n  (*   - destruct tc; simpl in *; destruct Hin as [Hin|Hin]; auto. *)\n  (*     + rewrite PSE.MP.Dec.F.add_iff in *; intuition; pose proof (not_In_empty x); contradiction. *)\n  (*     + rewrite PSE.MP.Dec.F.add_iff; auto. *)\n  (*     + pose proof (not_In_empty x); contradiction. *)\n  (*     + pose proof (not_In_empty x); contradiction. *)\n  (*     + rewrite ps_adds_spec in *; intuition; pose proof (not_In_empty x); contradiction. *)\n  (*     + rewrite ps_adds_spec; tauto. *)\n  (* Qed. *)\n\nEnd STCISVARIABLE.\n\nModule StcIsVariableFun\n       (Ids   : IDS)\n       (Op    : OPERATORS)\n       (CESyn : CESYNTAX     Op)\n       (Syn   : STCSYNTAX Ids Op CESyn)\n<: STCISVARIABLE Ids Op CESyn Syn.\n  Include STCISVARIABLE Ids Op CESyn Syn.\nEnd StcIsVariableFun.\n", "meta": {"author": "INRIA", "repo": "velus", "sha": "116a88bc71f3608ff43ed967895743e8b9a340e0", "save_path": "github-repos/coq/INRIA-velus", "path": "github-repos/coq/INRIA-velus/velus-116a88bc71f3608ff43ed967895743e8b9a340e0/src/Stc/StcIsVariable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4726834766204329, "lm_q1q2_score": 0.26026300379401496}}
{"text": "Require Import Coq.Strings.String.\nRequire Import Psatz.\n\nRequire Export SystemFR.TWFLemmas.\nRequire Export SystemFR.SubstitutionLemmas.\nRequire Export SystemFR.FVLemmas.\n\nOpen Scope string_scope.\nOpen Scope list_scope.\n\nOpaque PeanoNat.Nat.eq_dec.\n\nLemma open_close:\n  forall t rep x k,\n    wf t k ->\n    open k (close k t x) rep = psubstitute t ((x, rep) :: nil) term_var.\nProof.\n  induction t;\n    repeat step || t_equality || list_utils; eauto with lia.\nQed.\n\nLemma open_close2:\n  forall t x k,\n    wf t k ->\n    open k (close k t x) (fvar x term_var) = t.\nProof.\n  induction t;\n    repeat step || t_equality || list_utils; eauto with lia.\nQed.\n\nLemma topen_tclose:\n  forall T rep x k,\n    twf T k ->\n    topen k (tclose k T x) rep = psubstitute T ((x, rep) :: nil) type_var.\nProof.\n  induction T;\n    repeat step || t_equality || list_utils; eauto with lia.\nQed.\n\nLemma topen_tclose2:\n  forall T X k,\n    twf T k ->\n    topen k (tclose k T X) (fvar X type_var) = T.\nProof.\n  induction T;\n    repeat step || t_equality || list_utils; eauto with lia.\nQed.\n\nLemma topen_twice:\n  forall A B R X k,\n    ~(X ∈ pfv A type_var) ->\n    ~(X ∈ pfv B type_var) ->\n    twf A (S (S k)) ->\n    twf B 1 ->\n    twf R 0 ->\n      topen k (topen (S k) A (topen 0 B R)) R =\n      topen k (tclose k (topen (S k) A (topen 0 B (fvar X type_var))) X) R.\nProof.\n  induction A; repeat step || t_equality || apply_any || list_utils;\n    eauto with twf lia.\n  - rewrite topen_tclose;\n      repeat step || fv_open || list_utils || apply twf_topen;\n      eauto with twf lia.\n    + rewrite substitute_topen3; steps.\n      rewrite substitute_nothing; steps.\n      rewrite topen_none; steps; eauto with twf.\n      apply twf_monotone with 0; eauto with twf lia.\n    + apply twf_monotone with 0; try lia.\n      apply twf_topen; steps.\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/TOpenTClose.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2602630037940149}}
{"text": "From Coq Require Import List ZArith String.\n\nInductive KVstore_op := GET | PUT.\n\nLocal Set Warnings \"-ambiguous-paths\".\n\nDefinition byte := Byte.byte.\n\nDefinition Bytes := list byte.\nDefinition bytes_of_string s : Bytes := String.list_byte_of_string s.\nCoercion bytes_of_string : string >-> Bytes.\n\nAxiom size_t : Type.\nAxiom nat_of_size_t : size_t -> nat.\nCoercion nat_of_size_t : size_t >-> nat.\nAxiom size_t_of_nat : nat -> size_t.\nCoercion size_t_of_nat : nat >-> size_t.\nAxiom size_t_lt : size_t -> size_t -> bool.\nAxiom size_t_eqb : size_t -> size_t -> bool.\nDefinition size_t_neqb x y := negb (size_t_eqb x y).\n\nAxiom uint32_t : Type.\nAxiom nat_of_uint32_t : uint32_t -> nat.\nCoercion nat_of_uint32_t : uint32_t >-> nat.\nAxiom uint32_t_of_nat : nat -> uint32_t.\nCoercion uint32_t_of_nat : nat >-> uint32_t.\nAxiom uint32_t_of_bytes : Bytes -> uint32_t.\nAxiom bytes_of_uint32_t : uint32_t -> Bytes.\nAxiom uint32_t_lt : uint32_t -> uint32_t -> bool.\nAxiom uint32_t_eqb : uint32_t -> uint32_t -> bool.\nDefinition uint32_t_neqb x y := negb (uint32_t_eqb x y).\n\nAxiom int32_t : Type.\nAxiom Z_of_int32_t : int32_t -> Z.\nCoercion Z_of_int32_t : int32_t >-> Z.\nAxiom int32_t_of_Z : Z -> int32_t.\nCoercion int32_t_of_Z : Z >-> int32_t.\nAxiom int32_t_of_bytes : Bytes -> int32_t.\nAxiom bytes_of_int32_t : int32_t -> Bytes.\nAxiom int32_t_lt : int32_t -> int32_t -> bool.\nAxiom int32_t_eqb : int32_t -> int32_t -> bool.\nDefinition int32_t_neqb x y := negb (int32_t_eqb x y).\n\nDeclare Scope sz.\nDelimit Scope sz with sz.\nInfix \"<\" := size_t_lt : sz.\nInfix \"==\" := size_t_eqb (at level 70) : sz.\nInfix \"!=\" := size_t_neqb (at level 70) : sz.\n\nDeclare Scope ui32.\nDelimit Scope ui32 with ui32.\nInfix \"<\" := uint32_t_lt : ui32.\nInfix \"==\" := uint32_t_eqb (at level 70) : ui32.\nInfix \"!=\" := uint32_t_neqb (at level 70) : ui32.\n\nDeclare Scope i32.\nDelimit Scope i32 with i32.\nInfix \"<\" := int32_t_lt : i32.\nInfix \"==\" := int32_t_eqb (at level 70) : i32.\nInfix \"!=\" := int32_t_neqb (at level 70) : i32.\n\nDefinition Key := uint32_t.\nDefinition Value := uint32_t.\n\nRecord KVstore_get_pkt :=\n  { kvget_key: Key }.\n\nRecord KVstore_put_pkt :=\n  { kvput_key: Key;\n    kvput_value: Value }.\n\nRecord KVstore_pkt :=\n  { kvpkt_op: KVstore_op;\n    kvpkt_data:\n      match kvpkt_op with\n      | GET => KVstore_get_pkt\n      | PUT => KVstore_put_pkt\n      end }.\n\nRecord Buffer :=\n  { buf_sz: size_t;\n    buf_data: Bytes }.\n\n(* buf_data_sz: List.length buf_data <= nat_of_size_t buf_sz *)\n\nOpen Scope string_scope.\n\nImport ListNotations.\n\nFixpoint replace_nth {A} (n: nat) (l: list A) (a: A) :=\n  match l, n with\n  | [], _ => []\n  | _ :: t, 0 => a :: t\n  | h :: t, S n => h :: replace_nth n t a\n  end.\n\nFixpoint take {A} (l: list A) (len: nat) (placeholder: A) : list A :=\n  match len with\n  | 0 => []\n  | S len => (List.hd placeholder l) :: take (List.tl l) len placeholder\n  end.\n\nFixpoint slice {A} (l: list A) (off: nat) (len: nat) (placeholder: A) : list A :=\n  match off with\n  | 0 => take l len placeholder\n  | S off => slice (List.tl l) off len placeholder\n  end.\n\nFixpoint blit0 {A} (dst src: list A) : list A :=\n  match src with\n  | [] => dst\n  | hd :: src => hd :: blit0 (List.tl dst) src\n  end.\n\nFixpoint blit {A} (dst: list A) (off: nat) (src: list A) (placeholder: A) : list A :=\n  match off with\n  | 0 => blit0 dst src\n  | S off => (List.hd placeholder dst) :: blit (List.tl dst) off src placeholder\n  end.\n\nDefinition bytes_write (l: Bytes) (n: size_t) (b: byte) :=\n  replace_nth n l b.\n\nDefinition bytes_read (l: Bytes) (n: size_t) :=\n  nth n l Byte.x00.             (* FIXME inhabited typeclass *)\n\nDefinition bytes_borrow (l: Bytes) (off: size_t) (len: size_t) : Bytes :=\n  slice l off len Byte.x00.\n\nDefinition bytes_unborrow (l: Bytes) (off: size_t) (bs: Bytes) : Bytes :=\n  blit l off bs Byte.x00.\n\nDefinition bytes_read_uint32 (bs: Bytes) (off: size_t) :=\n  uint32_t_of_bytes (slice bs off 4 Byte.x00).\n\nDefinition bytes_write_uint32 (bs: Bytes) (off: size_t) (u: uint32_t) :=\n  blit bs off (bytes_of_uint32_t u) Byte.x00.\n\nRecord box {A: Type} :=\n  { box_val: A }.\nArguments box A : clear implicits.\n\nDefinition array_borrow_nth {A} (l: list A) (n: size_t) (placeholder: A) : A :=\n  nth n l placeholder.\n\nDefinition array_unborrow_nth {A} (l: list A) (n: size_t) (a: A) :=\n  replace_nth n l a.\n\nDefinition strlen s : size_t :=\n  String.length s.\n\n(* FIXME: should be a uniform annotation “borrow” coupled with a data access *)\nDefinition buf_borrow_data (b: Buffer) :=\n  b.(buf_data).\n\nDefinition buf_unborrow_data (b: Buffer) (bs: Bytes) :=\n  {| buf_sz := b.(buf_sz); buf_data := bs |}.\n\nRequire Import Arith PeanoNat.\n\nRequire Import Coq.Program.Wf.\nRequire Import Psatz.\n\nProgram Fixpoint ranged_for_nat {A}\n        (from to step: nat)\n        (body: forall (idx: size_t) (acc: A), (bool * A))\n        (a0: A) {measure (to - from)} :=\n  if le_gt_dec to from then a0\n  else let (continue, a0) := body from a0 in\n       if continue then\n         ranged_for_nat (from + S (pred step)) to step body a0\n       else a0.\nNext Obligation.\n  lia.\nDefined.\n\nDefinition ranged_for {A}\n           (from to step: size_t)\n           (body: forall (idx: size_t) (acc: A), (bool * A))\n           (a0: A) :=\n  ranged_for_nat from to step body a0.\n\nDefinition ranged_for_c {A}\n           (from to step: size_t)\n           (body: forall (idx: size_t) (acc: A), A)\n           (a0: A) :=\n  ranged_for_nat from to step (fun idx acc => (true, body idx acc)) a0.\n\nDefinition memcpy\n           (dst: Bytes) (dst_start: size_t)\n           (src: Bytes) (src_start: size_t)\n           (len: size_t) :=\n  let dst := ranged_for_c 0 len 1 (fun idx dst =>\n                                    let src_off := src_start + idx in\n                                    let dst_off := dst_start + idx in\n                                    let b := bytes_read src src_off in\n                                    bytes_write dst dst_off b)\n                       dst in\n  dst.\n\nFrom Coq Require Import Bool.\n\nDefinition byte_cmp (b1 b2: byte) : int32_t :=\n  let n1 := Byte.to_N b1 in\n  let n2 := Byte.to_N b2 in\n  match N.compare n1 n2 with\n  | Eq => 0\n  | Lt => -1\n  | Gt => 1\n  end%Z.\n\nDefinition memcmp (* FIXME: do short-circuiting version *)\n           (dst: Bytes) (dst_start: size_t)\n           (src: Bytes) (src_start: size_t)\n           (len: size_t) : int32_t :=\n  let cmp := ranged_for 0 len 1 (fun idx _ =>\n                                  let src_off := src_start + idx in\n                                  let dst_off := dst_start + idx in\n                                  let src_b := bytes_read src src_off in\n                                  let dst_b := bytes_read dst dst_off in\n                                  let cmp := byte_cmp src_b dst_b in\n                                  let continue := (cmp != 0)%Z%i32 in\n                                  (continue, cmp))\n                       0%Z in\n  cmp.\n\nDefinition buf_memcpy\n           (dst: Buffer) (dst_start: size_t)\n           (src: Bytes) (src_start: size_t)\n           (len: size_t) :=\n  let dst_data := buf_borrow_data dst in\n  let dst_data := memcpy dst_data dst_start src src_start len in\n  let buf := buf_unborrow_data dst dst_data in\n  buf.\n\nDefinition buf_write (dst: Buffer) (off: size_t) (c: byte) :=\n  let data := buf_borrow_data dst in\n  let data := bytes_write data off c in\n  let buf := buf_unborrow_data dst data in\n  buf.\n\nDefinition buf_set_sz (buf: Buffer) (sz: size_t) :=\n  {| buf_data := buf.(buf_data); buf_sz := sz |}.\n\nDefinition writeout (output: Buffer) (header: string)\n           (data: Bytes) (data_len: size_t) : Buffer :=\n  let output_len := output.(buf_sz) in\n  if (data_len < output_len)%sz then\n    let header_len := strlen header in\n    let output := buf_memcpy output 0 header 0 header_len in\n    let output := buf_memcpy output header_len data 0 data_len in\n    let output := buf_set_sz output (output_len + 1) in\n    let output := buf_write output output_len Byte.x0a in\n    output\n  else output.\n\nDefinition OK := \"OK \".\nDefinition ERR := \"ERR \".\nDefinition INPUT_TOO_SHORT := \"input too short\".\nDefinition UNRECOGNIZED_OPERATION := \"unrecognized operation\".\nDefinition NOT_FOUND := \"not found\".\nDefinition STORE_FULL := \"store full\".\n\nDefinition err (buf: Buffer) (s: string) : Buffer :=\n  let buf := writeout buf ERR s (strlen s) in\n  buf.\n\nFixpoint list_const {A} (len: nat) (a0: A) : list A :=\n  match len with\n  | 0 => []\n  | S len => a0 :: list_const len a0\n  end.\n\nDefinition alloca (sz: size_t) : Bytes :=\n  list_const sz Byte.x00.\n\nDefinition ok (buf: Buffer) (v: Value) : Buffer :=\n  let bytes := alloca 4 in\n  let bytes := bytes_write_uint32 bytes 0 v in\n  let buf := writeout buf ERR bytes 4 in\n  buf.\n\nRecord KV :=\n  { kv_key: Key;\n    kv_value: Value }.\n\nDefinition kv_set_key (kv: KV) (k: Key) :=\n  {| kv_key := k; kv_value := kv.(kv_value) |}.\nDefinition kv_set_value (kv: KV) (v: Value) :=\n  {| kv_key := kv.(kv_key); kv_value := v |}.\n\nRecord KVstore :=\n  { kvs_sz: size_t;\n    kvs_capacity: size_t;\n    kvs_data: list KV }.\n\n(* FIXME make an inhabited typeclass to avoid having to specify these placeholders *)\nDefinition kv_placeholder :=\n  {| kv_key := 0; kv_value := 0 |}.\n\n(* FIXME: should be a uniform annotation “borrow” coupled with a data access *)\nDefinition kvs_borrow_data (kvs: KVstore) :=\n  kvs.(kvs_data).\n\n(* FIXME borrow/unborrow could be handled uniformly as lenses *)\nDefinition kvs_unborrow_data (kvs: KVstore) (data: list KV) :=\n  {| kvs_sz := kvs.(kvs_sz);\n     kvs_capacity := kvs.(kvs_capacity);\n     kvs_data := data |}.\n\nDefinition kvs_set_sz (kvs: KVstore) (sz: size_t) :=\n  {| kvs_sz := sz;\n     kvs_capacity := kvs.(kvs_capacity);\n     kvs_data := kvs.(kvs_data) |}.\n\nDefinition kv_step (state: KVstore) (input: Buffer) (output: Buffer) : KVstore * Buffer :=\n  let input_sz := input.(buf_sz) in\n  if (input_sz < 3)%sz then\n    let output := err output INPUT_TOO_SHORT in\n    (state, output)\n  else\n    let input_data := buf_borrow_data input in\n    let op := bytes_borrow input_data 0 3 in\n    if (memcmp op 0 \"GET\" 0 3 == 0%Z)%i32 then\n      (if (input_sz < 8)%sz then\n         let output := err output INPUT_TOO_SHORT in\n         (state, output)\n       else\n         (* The loop returns an index instead of a value because that makes\n            borrowing the value at that index easier; FIXME think of a way to do\n            the borrowing as part of the loop *)\n         let key0 := bytes_read_uint32 input_data 4 in\n         let sz := state.(kvs_sz) in\n         let kvs_data := kvs_borrow_data state in\n         let found_idx :=\n             ranged_for 0 sz 1\n                        (fun idx found_idx =>\n                           let kv := array_borrow_nth kvs_data idx kv_placeholder in\n                           let key := kv.(kv_key) in\n                           let kvs_data := array_unborrow_nth kvs_data found_idx kv in\n                           let found_idx := if (key == key0)%ui32 then idx else found_idx in\n                           let continue := (found_idx == sz)%sz in\n                           (continue, found_idx))\n                        sz in\n         (* FIXME How do we handle conditional mutation?\n            E.g. how would it look if we did the unborrowing after the if? *)\n         if (found_idx < sz)%sz then\n           let kv := array_borrow_nth kvs_data found_idx kv_placeholder in\n           let value := kv.(kv_value) in\n           let output := ok output value in\n           let kvs_data := array_unborrow_nth kvs_data found_idx kv in\n           let state := kvs_unborrow_data state kvs_data in\n           (state, output)\n         else\n           let output := err output NOT_FOUND in\n           let state := kvs_unborrow_data state kvs_data in\n           (state, output))\n    else if (memcmp op 0 \"PUT\" 0 3 == 0%Z)%i32 then\n           (if (input_sz < 12)%sz then\n              let output := err output INPUT_TOO_SHORT in\n              (state, output)\n            else\n              let sz := state.(kvs_sz) in\n              let capacity := state.(kvs_capacity) in\n              if (sz < capacity)%sz then\n                let kvs_data := kvs_borrow_data state in\n                let key := bytes_read_uint32 input_data 4 in\n                let value := bytes_read_uint32 input_data 8 in\n                let kv := array_borrow_nth kvs_data sz kv_placeholder in\n                let kv := kv_set_key kv key in\n                let kv := kv_set_value kv value in\n                let kvs_data := array_unborrow_nth kvs_data sz kv in\n                let sz := sz + 1 in\n                let state := kvs_set_sz state sz in\n                let state := kvs_unborrow_data state kvs_data in\n                let output := ok output value in\n                (state, output)\n              else\n                let output := err output STORE_FULL in\n                (state, output))\n         else\n           let output := err output UNRECOGNIZED_OPERATION in\n           (state, output).\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/kv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.26026299682263915}}
{"text": "From ITree Require Import ITree.\nFrom compcert Require Coqlib.\nFrom Paco Require Import paco.\n\nRequire Import sflib.\nRequire Import Axioms StdlibExt IntegersExt.\n\nRequire Import SysSem.\nRequire Import IPModel DiscreteTimeModel.\nRequire Import RTSysEnv.\nRequire Import NWSysModel SyncSysModel.\nRequire Import ProgSem.\n\nRequire Import List.\nRequire Import Arith ZArith Lia.\n\nRequire Import Relation_Operators.\n\n(* Definition filter_by_dest {A} *)\n(*            (tids_dest: list Tid) *)\n(*            (smsgs: list (Tid * A?)) *)\n(*   : list A? := *)\n(*   (* let (tid_s, dmsgs) := smsgs in *) *)\n(*   filtermap (chget_by_dest tids_dest) smsgs. *)\n\n\n\n\nModule AANode.\n\n  Section ABST_ASYNC_NODE.\n    Import SNode.\n\n    Context {sysE: Type -> Type}.\n    Context `{SystemEnv}.\n    (* Context {msgT: Set}. *)\n    (* Context `{rnws_params}. *)\n    Let msgT: Set := bytes.\n    Notation appE := (sysE +' bsendE).\n    Notation t := (@SNode.t sysE msgT).\n\n    (* Definition istate (node: @SNode.t sysE msgT): Type := *)\n    (*   nat(*sytm*) * nat(*ocnt*) * *)\n    (*   list (list msgT)(*inbc*) * node.(app_state). *)\n    (*   (* IState (sytm: nat) (old_msg_cnt: nat) *) *)\n    (*   (*        (ast: node.(app_state)). *) *)\n    Inductive stage_t: Type :=\n    | Ready (sytm: nat) (inbc: list (list msgT))\n    | Running (sytm: nat) (sh: list bool)\n    | Done\n    .\n\n    Definition istate_t (node: @SNode.t sysE msgT): Type :=\n      nat(*ocnt*) * stage_t * node.(app_state).\n\n    Inductive istate_wf (node: @SNode.t sysE msgT)\n      : istate_t node -> Prop :=\n      IStateWf\n        ocnt stg ast\n        (WF_SEND_HIST:\n           forall sytm sh\n             (STAGE_RUNNING: stg = Running sytm sh),\n             length sh = num_tasks)\n      : istate_wf node (ocnt, stg, ast).\n\n    Record state: Type :=\n      State { task_id: Tid;\n              node: @SNode.t sysE msgT;\n              (* mcast_ids: list Tid; *)\n              (* num_nodes: nat; *)\n\n              inbox_n: list (list msgT);\n              istate: (istate_t node)?;\n            }.\n\n    Inductive state_wf (tid: Tid)\n      : state -> Prop :=\n      StateWf\n        nd (* mids *) inbn oist\n        (* (WF_NODE: SNode.wf mcasts' nd) *)\n        (* (MCAST_IDS: SysEnv.get_mcast_of tid = mids) *)\n        (INBN_LENGTH: length inbn = num_tasks)\n        (ISTATE_WF: option_rel1 (istate_wf nd) oist)\n      : state_wf tid (State tid nd inbn oist).\n\n    Definition init_inbox: list (list msgT) :=\n      List.repeat [] num_tasks.\n\n    Definition inbox_sz (inb: list (list msgT)): nat :=\n      length (concat inb).\n\n    Definition init_state (tid: Tid) (node: t) : state :=\n      State tid node (* (SysEnv.get_mcast_of tid) *)\n            init_inbox None.\n\n    Lemma wf_init_state\n          tid nd\n      : state_wf tid (init_state tid nd).\n    Proof.\n      econs; eauto.\n      - unfold init_inbox.\n        rewrite repeat_length. ss.\n      - econs.\n    Qed.\n\n    Fixpoint merge_inbox\n             (inbn inbn_arr: list (list msgT))\n      : list (list msgT) :=\n      match inbn with\n      | [] => []\n      | ent1 :: ents1 =>\n        match inbn_arr with\n        | [] => inbn\n        | ent2 :: ents2 =>\n          (ent1 ++ ent2) :: merge_inbox ents1 ents2\n        end\n      end.\n\n    Lemma merge_inbox_nils\n          (inb: list (list msgT)) n\n      : merge_inbox inb (repeat [] n) = inb.\n    Proof.\n      depgen n.\n      induction inb as [| h t IH]; i; ss.\n      destruct n; ss.\n      rewrite IH. rewrite app_nil_r. ss.\n    Qed.\n\n    Lemma merge_inbox_length\n          inb inb'\n      : length (merge_inbox inb inb') =\n        length inb.\n    Proof.\n      depgen inb'.\n      induction inb as [| h t IH]; i; ss.\n      destruct inb'; ss.\n      f_equal. eauto.\n    Qed.\n\n    Lemma merge_inbox_size\n          inb1 inb2\n          (INBS_LEN_EQ: length inb1 = length inb2)\n      : inbox_sz (merge_inbox inb1 inb2) =\n        inbox_sz inb1 + inbox_sz inb2.\n    Proof.\n      unfold inbox_sz.\n      remember (length inb1) as n eqn: INB_LEN1.\n      rename INBS_LEN_EQ into INB_LEN2.\n      depgen inb2. depgen inb1.\n\n      induction n as [| n' IH]; i; ss.\n      { destruct inb1; destruct inb2; ss. }\n      destruct inb1 as [| h1 t1]; ss.\n      destruct inb2 as [| h2 t2]; ss.\n\n      repeat rewrite app_length.\n      rewrite IH; eauto. nia.\n    Qed.\n\n    Lemma inbox_size_empty\n      : inbox_sz init_inbox = 0.\n    Proof.\n      unfold init_inbox.\n      generalize num_tasks as k.\n      induction k as [|k' IH]; ss.\n    Qed.\n\n    Lemma merge_inbox_nth\n          inb inb' n r\n          (NTH: nth_error inb n = Some r)\n      : nth_error (merge_inbox inb inb') n =\n        Some (r ++ match nth_error inb' n with\n                   | None => []\n                   | Some r' => r'\n                   end).\n    Proof.\n      revert inb inb' r NTH.\n      induction n as [| n' IH]; i; ss.\n      { destruct inb, inb'; clarify. ss.\n        rewrite app_nil_r. ss. }\n      destruct inb, inb'; ss.\n      { rewrite app_nil_r. ss. }\n      apply IH; eauto.\n    Qed.\n\n    Lemma merge_inbox_nth_None\n          inb inb' n\n          (NTH: nth_error inb n = None)\n      : nth_error (merge_inbox inb inb') n = None.\n    Proof.\n      depgen inb. depgen inb'.\n      induction n as [| n' IH]; i; ss.\n      { desf. }\n      desf.\n      destruct inb'; ss; clarify.\n      eauto.\n    Qed.\n\n\n\n    (* Definition istate_update_inbox *)\n    (*            {node: @SNode.t sysE msgT} *)\n    (*            (nsytm: nat) *)\n    (*            (inbn: list (list msgT)) *)\n    (*            (ist: istate_t node) *)\n    (*   : (istate_t node)? := *)\n    (*   let '(ocnt, stg, ast) := ist in *)\n    (*   match stg with *)\n    (*   | Done => Some (ocnt, Ready nsytm _, ast) *)\n    (*   | _ => None *)\n    (*   end. *)\n\n    (* Definition filter_by_dest *)\n    (*            (tid: Tid) (mids: list Tid) *)\n    (*            (in_msgs: list (list (Tid * msgT))) *)\n    (*   : list (list msgT) := *)\n    (*   map (filtermap (check_dest tid mids)) *)\n\n\n\n    (* Definition inbox_accept_msgs *)\n    (*            (in_msgs: list (list (Tid * msgT))) *)\n    (*            (inb: list (list msgT)) *)\n    (*   : list (list msgT) := *)\n    (*   let ms_new: list (list msgT) := *)\n    (*       map (filter_by_dest tid  *)\n    (*       map (filtermap (check_dest tid (mcast_groups node))) in_msgs in *)\n\n    (* Definition filter_by_dest_opt *)\n    (*            (ids_to_me: list Tid) *)\n    (*            (om: (Tid * msgT)?) *)\n    (*   : list msgT *)\n\n    Definition get_msg_by_dest\n               (tid: Tid)\n               (om: (Tid * msgT)?)\n      : list msgT :=\n      match om with\n      | None => []\n      | Some (id_dest, msg) =>\n        if orb (id_dest =? tid)\n               (existsb (Nat.eqb id_dest) (get_mcast_of tid))\n        then [msg] else []\n      end.\n\n    Definition accept_msgs (tm: DTime.t)\n               (in_msgs: list (Tid * msgT)?)\n               (st: state)\n      : state :=\n      match st with\n      | State tid node inbn oist =>\n        let inbn1 :=\n            match exact_skwd_base_time period tm with\n            | None => inbn\n            | Some _ => init_inbox\n            end\n        in\n        let ms_new := map (get_msg_by_dest tid) in_msgs in\n        State tid node (merge_inbox inbn1 ms_new) oist\n      end.\n\n    Inductive choose_inbox_rowmsg\n      : list msgT -> msgT? -> Prop :=\n    | ChooseInboxRowmsg_Nil\n      : choose_inbox_rowmsg [] None\n    | ChooseInboxRowmsg_Nonnil\n        ms msg\n        (MSG_IN_ROW: In msg ms)\n      : choose_inbox_rowmsg ms (Some msg)\n    .\n\n    Inductive abst_inbox\n              (ocnt: nat) (inbc: list (list msgT))\n              (* (inbc_a: list msgT?) *)\n      : list msgT? -> nat -> Prop :=\n    | AbstInbox_OK\n        inbc_a\n        (INBC_A: Forall2 choose_inbox_rowmsg inbc inbc_a)\n      : abst_inbox ocnt inbc inbc_a O\n    | AbstInbox_Error\n        inbc_a ocnt'\n        (TOO_MANY_MSGS: ocnt + length (concat inbc) > length inbc * 4)\n      : abst_inbox ocnt inbc inbc_a ocnt'\n    .\n\n    Inductive sh_tau_steps (sh: list bool)\n              (node: @SNode.t sysE msgT)\n      : SNode.app_state node -> SNode.app_state node -> Prop :=\n    | SHTau_Refl\n        ast\n      : sh_tau_steps sh node ast ast\n    | SHTau_AppStep\n        ast ast1 ast'\n        (APP_STEP: node.(app_step) ast ast1)\n        (TAU_REST: sh_tau_steps sh node ast1 ast')\n      : sh_tau_steps sh node ast ast'\n    | SHTau_SendHistBlocks\n        tid msg snde\n        ast ast1 ast'\n        (SEND_EVENT: snde = AbstSendEvent tid msg)\n        (AT_EVENT: node.(at_event) ast (EventCall (inr1 snde)))\n        (AFT_EVENT: node.(after_event)\n                           ast (Event (inr1 snde) tt) ast1)\n        (OUTMSGS: check_send_hist sh tid = None)\n        (TAU_REST: sh_tau_steps sh node ast1 ast')\n      : sh_tau_steps sh node ast ast'\n    .\n\n    Definition process_outmsg (sh: list bool)\n               (om: (Tid * msgT)?)\n      : list bool * (Tid * msgT)? :=\n      match om with\n      | None => (sh, None)\n      | Some (tid_d, msg) =>\n        match check_send_hist sh tid_d with\n        | None => (sh, None)\n        | Some sh' => (sh', Some (tid_d, resize_bytes msg_size msg))\n        end\n      end.\n\n    Inductive step (tm: DTime.t)\n      : state -> tsp * events (nbE +' sysE) ->\n        (Tid * msgT)? -> state -> Prop :=\n    (* Off *)\n    | Step_StayOff\n        tid node inbn\n      : step tm\n             (State tid node inbn None)\n             (0%Z, []) None\n             (State tid node inbn None)\n\n    | Step_TurnOn\n        tid node inbn sytm\n        ocnt ast\n        (BASE_TIME: exact_skwd_base_time period tm = Some sytm)\n        (OLD_CNT: ocnt <= inbox_sz inbn)\n        (INIT_APP_STATE: node.(init_app_state) ast)\n      : step tm\n             (State tid node inbn None)\n             (0%Z, []) None\n             (State tid node inbn\n                    (Some (ocnt, Done, ast)))\n    (* On *)\n    | Step_Fail\n        tid node inbn ist\n      : step tm\n             (State tid node inbn (Some ist))\n             (0%Z, []) None\n             (State tid node inbn None)\n\n    | Step_Sync\n        tid node inbn\n        ocnt sytm ast\n        (SYNC_TIME: exact_skwd_base_time period tm = Some sytm)\n      : step tm\n             (State tid node inbn\n                    (Some (ocnt, Done, ast)))\n             (0%Z, []) None\n             (State tid node inbn\n                    (Some (ocnt, Ready sytm inbn, ast)))\n\n    | Step_On_Stay\n        tid node inbn\n        ocnt stg ast\n        (SYNC_TIME: exact_skwd_base_time period tm = None)\n      : step tm\n             (State tid node inbn\n                    (Some (ocnt, stg, ast)))\n             (0%Z, []) None\n             (State tid node inbn\n                    (Some (ocnt, stg, ast)))\n\n    | Step_StartRun\n        tid node inbn\n        ocnt sytm inbc ast\n        inbc_a ocnt' ast' sh\n        (SYNC_TIME: exact_skwd_base_time period tm = None)\n        (INBOX: abst_inbox ocnt inbc inbc_a ocnt')\n        (PERIOD_BEGIN: node.(period_begin)\n                              (Z.of_nat sytm) inbc_a ast ast')\n        (SEND_HIST: sh = List.repeat false num_tasks)\n      : step tm\n             (State tid node inbn\n                    (Some (ocnt, Ready sytm inbc, ast)))\n             (0%Z, []) None\n             (State tid node inbn\n                    (Some (ocnt', Running sytm sh, ast')))\n\n    | Step_Running_Go\n        tid node inbn\n        ocnt sytm sh ast\n        ast1 oe om sh' ast'\n        es oms zsytm\n        (SYNC_TIME: exact_skwd_base_time period tm = None)\n        (TAU_STEPS: sh_tau_steps sh node ast ast1)\n        (ISTEP: SNode.istep node ast1 oe om ast')\n        (EVTS: es = opt2list oe)\n        (OUTMSGS: (sh', oms) = process_outmsg sh om)\n        (TIMESTAMP: zsytm = Z.of_nat sytm)\n      : step tm\n             (State tid node inbn\n                    (Some (ocnt, Running sytm sh, ast)))\n             (zsytm, es) oms\n             (State tid node inbn\n                    (Some (ocnt, Running sytm sh', ast')))\n\n    | Step_Running_Done\n        tid node inbn\n        ocnt sytm sh ast ast_f\n        (SYNC_TIME: exact_skwd_base_time period tm = None)\n        (* (TAU_STEPS: clos_refl_trans *)\n        (*           _ node.(app_step) ast ast_f) *)\n        (TAU_STEPS: sh_tau_steps sh node ast ast_f)\n        (PERIOD_END: node.(SNode.period_end) ast_f)\n      : step tm\n             (State tid node inbn\n                    (Some (ocnt, Running sytm sh, ast)))\n             (0%Z, []) None\n             (State tid node inbn\n                    (Some (ocnt, Done, ast_f)))\n    .\n\n    Lemma wf_prsv\n          tm tid\n          st es oms st'\n          (STEP: step tm st es oms st')\n          (WF_STATE: state_wf tid st)\n      : state_wf tid st'.\n    Proof.\n      inv WF_STATE.\n      destruct oist as [ist|].\n      2: { inv STEP; ss. }\n      inv STEP; ss.\n      - existT_elim. clarify.\n      - existT_elim. clarify.\n        econs; eauto. ss.\n        econs. i. clarify.\n        apply repeat_length.\n      - existT_elim. clarify.\n        unfold process_outmsg in *.\n        inv ISTATE_WF.\n        destruct om as [[tid_d msg]|]; ss.\n        2: { clarify. }\n        destruct (check_send_hist sh tid_d) as [sh_nxt|] eqn: SH'.\n        2: { clarify. }\n\n        clarify.\n        econs; eauto. ss.\n        econs. i. clarify.\n        apply check_send_hist_Some in SH'; eauto.\n        nbdes. eauto.\n    Qed.\n\n    Lemma step_progress\n          tm st\n      : exists es oms st',\n        step tm st es oms st'.\n    Proof.\n      destruct st as [tid nd inbn oist].\n      destruct oist.\n      - esplits. eapply Step_Fail.\n      - esplits. econs 1.\n    Qed.\n\n    Lemma wf_accept_msgs_prsv\n          tid st\n          tm in_msgs\n          (WF_STATE: state_wf tid st)\n      : state_wf tid (accept_msgs tm in_msgs st).\n    Proof.\n      inv WF_STATE. ss.\n      econs; ss.\n      rewrite merge_inbox_length.\n      desf; ss.\n      unfold init_inbox.\n      apply repeat_length.\n    Qed.\n\n    (* Inductive star (period: nat) (tm: DTime.t) *)\n    (*   : state -> nat * events (nbE +' sysE) -> *)\n    (*     list (Tid * msgT) -> state -> Prop := *)\n    (* | Star_Base *)\n    (*     st sytm *)\n    (*   : star period tm *)\n    (*          st (sytm, []) [] st *)\n    (* | Star_Step *)\n    (*     sytm st es1 oms1 st1 *)\n    (*     es2 oms2 st' es oms *)\n    (*     (STEP: step tm *)\n    (*                 st (sytm, es1) oms1 st1) *)\n    (*     (STAR_REST: star period (DTime.succ tm) *)\n    (*                      st1 (sytm, es2) oms2 st') *)\n    (*     (ES: es = es1 ++ es2) *)\n    (*     (OMS: oms = oms1 ++ oms2) *)\n    (*   : star period tm *)\n    (*          st (sytm, es) oms st'. *)\n\n  End ABST_ASYNC_NODE.\nEnd AANode.\n\n\nModule AASys.\n  Section SYS.\n    Import SyncSys.\n    Context {sysE: Type -> Type}.\n    (* Context {msgT: Set}. *)\n    Context `{SystemEnv}.\n    (* Let msgT: Set := bytes. *)\n\n    Record state: Type :=\n      State { time: DTime.t ;\n              node_states: list (@AANode.state sysE) ;\n            }.\n\n    Inductive state_wf\n      : state -> Prop :=\n      StateWf\n        tm nsts\n        (WF_NSTS: iForall AANode.state_wf 0 nsts)\n      : state_wf (State tm nsts).\n\n    Definition init_state (tm_init: nat)\n               (sys: list SNode.t): state :=\n      let num_nodes := length sys in\n      let nsts := imap AANode.init_state 0 sys in\n      State (DTime.of_ns tm_init) nsts.\n\n    Lemma wf_init_state\n          tm sys\n      : state_wf (init_state tm sys).\n    Proof.\n      econs.\n      apply iForall_nth. i. ss. r.\n      rewrite imap_nth_error_iff. ss.\n      destruct (nth_error sys n); ss.\n      apply AANode.wf_init_state.\n    Qed.\n\n    Inductive step\n      : state -> list (tsp * events (nbE +' sysE)) ->\n        state -> Prop :=\n      Step_Run\n        tm nsts tes outs nsts1 nsts' tm'\n        (STEPS: Forall4 (AANode.step tm)\n                        nsts tes outs nsts1)\n        (ACCEPT_MSGS: List.map (AANode.accept_msgs tm outs)\n                               nsts1 = nsts')\n        (TIME: tm' = DTime.succ tm)\n      : step (State tm nsts) tes (State tm' nsts').\n\n    Lemma wf_prsv\n          st tes st'\n          (STEP: step st tes st')\n          (WF: state_wf st)\n      : state_wf st'.\n    Proof.\n      inv WF. inv STEP.\n      econs.\n      apply iForall_nth. i. ss. r.\n      rewrite Coqlib.list_map_nth.\n      destruct (nth_error nsts1 n) as [nst_n|] eqn:NST_N; ss.\n      hexploit Forall4_nth4; eauto. i. des.\n      eapply AANode.wf_accept_msgs_prsv.\n      eapply AANode.wf_prsv; eauto.\n      rewrite iForall_nth in WF_NSTS. ss.\n      specialize (WF_NSTS n).\n      rewrite NTH1 in WF_NSTS. ss.\n    Qed.\n\n    Lemma step_progress\n          st\n      : exists tes st', step st tes st'.\n    Proof.\n      destruct st as [tm nsts].\n      assert (STEP_EX: forall n (N_UB: n < length nsts),\n                 exists x,\n                   option_rel4 (AANode.step tm)\n                               (nth_error nsts n)\n                               (Some (fst (fst x)))\n                               (Some (snd (fst x)))\n                               (Some (snd x))).\n      { i. eapply nth_error_Some in N_UB.\n        eapply Some_not_None in N_UB. des.\n        hexploit (AANode.step_progress tm a).\n        i. des.\n        rewrite N_UB.\n        exists (es, oms, st'). ss.\n        econs. ss.\n      }\n      apply exists_list in STEP_EX. des.\n      exists (map (fun x => fst (fst x)) l).\n      esplits.\n      econs; eauto.\n      instantiate (1:= map (fun x => snd x) l).\n      instantiate (1:= map (fun x => snd (fst x)) l).\n\n      apply Forall4_nth. intro i.\n      destruct (le_lt_dec (length nsts) i).\n      - rewrite nth_error_None2; eauto.\n        rewrite nth_error_None2.\n        2: { rewrite map_length. nia. }\n        rewrite nth_error_None2.\n        2: { rewrite map_length. nia. }\n        rewrite nth_error_None2.\n        2: { rewrite map_length. nia. }\n        econs.\n      - assert (exists a, nth_error nsts i = Some a).\n        { apply Some_not_None.\n          eapply nth_error_Some. ss. }\n        assert (X_EQ: exists x, nth_error l i = Some x).\n        { apply Some_not_None.\n          eapply nth_error_Some. rewrite LIST_LEN. ss. }\n        des.\n\n        hexploit NTH_PROP; eauto.\n        repeat rewrite Coqlib.list_map_nth.\n        rewrite X_EQ. ss.\n    Qed.\n\n\n    Definition num_sites (st: state): nat :=\n      length st.(node_states).\n\n    Program Definition as_dsys (sys: list SNode.t) (tm_init: nat): DSys.t :=\n      DSys.mk state num_sites step\n              (fun st => st = init_state tm_init sys) _.\n    Next Obligation.\n      splits.\n      - unfold num_sites.\n        inv STEP; ss.\n        hexploit Forall4_length; eauto. i. des. ss.\n        (* + rewrite repeat_length. ss. *)\n        (* + hexploit Forall4_length; eauto. i. des. ss. *)\n      - unfold num_sites.\n        inv STEP; ss.\n        rewrite map_length.\n        hexploit Forall4_length; eauto. i. des. ss.\n    Qed.\n\n    Lemma safe\n          tm nodes\n      : DSys.safe (as_dsys nodes tm).\n    Proof.\n      econs.\n      { exists (init_state tm nodes). ss. }\n      i. ss.\n      hexploit (wf_init_state tm nodes); eauto.\n      rewrite <- INIT.\n      clear INIT.\n      revert st_i.\n\n      pcofix CIH.\n      intros st WF.\n      pfold.\n      econs.\n      { eapply step_progress. }\n      i. ss.\n      right.\n      hexploit wf_prsv; eauto.\n    Qed.\n\n  End SYS.\nEnd AASys.\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/AbstAsyncSysModel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.26026299682263915}}
{"text": "Require Import memory.\nRequire Import language.\nRequire Import join_lib.\nRequire Import join_tactics.\n\nImport veg.\n\nLemma mem_join_disjoint_merge' :\n  forall (A B T : Type) (MC : PermMap A B T) m1 m2 m3 m4,\n    usePerm = true ->\n    join m1 m2 m3 ->\n    disjoint m3 m4 ->\n    join (merge m1 m4) m2 (merge m3 m4).\n  hy.\nQed.  \n\nLemma mem_join_disjoint_merge :\n  forall (m1:mem) m2 m3 m4,\n    join m1 m2 m3 ->\n    disjoint m3 m4 ->\n    join (merge m1 m4) m2 (merge m3 m4).\nProof.\n  intros.\n  eapply mem_join_disjoint_merge'; ica.\nQed.  \n\nLemma mem_sub_disjoint_sub_merge' :\n  forall (A B T : Type) (MC : PermMap A B T) m1 m2 m3,\n    Maps.sub m1 m2 ->\n    disjoint m2 m3 ->\n    Maps.sub m1 (merge m2 m3).\n  hy.\nQed.\n  \nLemma mem_sub_disjoint_sub_merge :\n  forall (m1:mem) m2 m3,\n    Maps.sub m1 m2 ->\n    disjoint m2 m3 ->\n    Maps.sub m1 (merge m2 m3).\nProof.\n  intros.\n  eapply mem_sub_disjoint_sub_merge'; ica.\nQed.  \n\nLemma osabst_join_disjoint_merge' :\n  forall (A B T : Type) (MC : PermMap A B T) m1 m2 m3 m4,\n    usePerm = false ->\n    join m1 m2 m3 ->\n    disjoint m3 m4 ->\n    join (merge m1 m4) m2 (merge m3 m4).\n  hy.\nQed.\n\nLemma osabst_join_disjoint_merge :\n  forall (m1:osabst) m2 m3 m4,\n    join m1 m2 m3 ->\n    disjoint m3 m4 ->\n    join (merge m1 m4) m2 (merge m3 m4).\nProof.\n  intros.\n  eapply osabst_join_disjoint_merge'; ica.\nQed.\n\nLemma osabst_join_disjoint_disjoint' :\n  forall (A B T : Type) (MC : PermMap A B T) m1 m2 m12 m3,\n    join m1 m2 m12 ->\n    disjoint m12 m3 ->\n    disjoint m1 m3.\n  hy.\nQed.\n\nLemma osabst_join_disjoint_disjoint :\n  forall (m1:osabst) m2 m12 m3,\n    join m1 m2 m12 ->\n    disjoint m12 m3 ->\n    disjoint m1 m3.\nProof.\n  intros.\n  eapply osabst_join_disjoint_disjoint'; eauto.\nQed.\n\nLemma mem_join_join_merge_eq' :\n  forall (A B T : Type) (MC : PermMap A B T) M1 M2 M3 M4 M,\n    join M1 M2 M ->\n    join M3 M4 M2 ->\n    M = merge M3 (merge M1 M4).\n  hy.\nQed.\n  \nLemma mem_join_join_merge_eq :\n  forall (M1:mem) M2 M3 M4 M,\n    join M1 M2 M ->\n    join M3 M4 M2 ->\n    M = merge M3 (merge M1 M4).\nProof.\n  intros.\n  eapply mem_join_join_merge_eq'; eauto.\nQed.\n\nLemma mem_disj_join_disjmerge':\n  forall (A B T : Type) (MC : PermMap A B T) M M' M1 M2,\n    disjoint M M' ->\n    join M1 M2 M' ->\n    disjoint (merge M2 M) M1.\n  hy.\nQed.\n\nLemma mem_disj_join_disjmerge:\n  forall (M:mem) M' M1 M2,\n    disjoint M M' ->\n    join M1 M2 M' ->\n    disjoint (merge M2 M) M1.\nProof.\n  intros.\n  eapply mem_disj_join_disjmerge'; eauto.\nQed.\n\nLemma osabst_sub_merge_minus_eq' :\n  forall (A B T : Type) (MC : PermMap A B T) o1 o2,\n    usePerm = false ->\n    Maps.sub o1 o2 ->\n    merge o1 (minus o2 o1) = o2.\n  hy.\nQed.\n\nLemma osabst_sub_merge_minus_eq :\n  forall (o1:osabst) o2,\n    Maps.sub o1 o2 ->\n    merge o1 (minus o2 o1) = o2.\nProof.\n  intros.\n  eapply osabst_sub_merge_minus_eq'; eauto.\nQed.\n\nLemma osabst_join_eq_merge' :\n  forall (A B T : Type) (MC : PermMap A B T) m1 m2 m3,\n    usePerm = false ->\n    join m1 m2 m3 ->\n    m3 = merge m1 m2.\n  hy.\nQed.\n\nLemma osabst_join_eq_merge :\n  forall (m1:osabst) m2 m3,\n    join m1 m2 m3 ->\n    m3 = merge m1 m2.\nProof.\n  intros.\n  eapply osabst_join_eq_merge'; ica.\nQed.\n\nLemma osabst_join_minus_eq' :\n  forall (A B T : Type) (MC : PermMap A B T) o1 o2 o3,\n    usePerm = false ->\n    join o1 o2 o3 ->\n    minus o3 o1 = o2.\nProof.\n  hy.\nQed.\n\nLemma osabst_join_minus_eq :\n  forall (o1:osabst) o2 o3,\n    join o1 o2 o3 ->\n    minus o3 o1 = o2.\nProof.\n  intros.\n  eapply osabst_join_minus_eq'; ica.\nQed.\n\nLemma osabst_join_disjoint_minus_disjoint_minus' :\n  forall (A B T : Type) (MC : PermMap A B T) o1 o2 o3 o4 o5,\n    usePerm = false ->\n    join o1 o2 o3 ->\n    disjoint o4 (minus o3 o5) ->\n    disjoint o4 (minus o2 o5).\n  hy.\nQed.\n  \nLemma osabst_join_disjoint_minus_disjoint_minus :\n  forall (o1:osabst) o2 o3 o4 o5,\n    join o1 o2 o3 ->\n    disjoint o4 (minus o3 o5) ->\n    disjoint o4 (minus o2 o5).\nProof.\n  intros.\n  eapply osabst_join_disjoint_minus_disjoint_minus'; ica.\nQed.\n\nLemma osabst_join_disjoint_minus_join' :\n  forall (A B T : Type) (MC : PermMap A B T) o1 o2 o3 o4,\n    usePerm = false ->\n    join o1 o2 o3 ->\n    disjoint o1 o4 ->\n    join o1 (minus o2 o4) (minus o3 o4).\n  hy.\nQed.\n\nLemma osabst_join_disjoint_minus_join :\n  forall (o1:osabst) o2 o3 o4,\n    join o1 o2 o3 ->\n    disjoint o1 o4 ->\n    join o1 (minus o2 o4) (minus o3 o4).\nProof.\n  intros.\n  eapply osabst_join_disjoint_minus_join'; ica.\nQed.\n\nLemma osabst_disjoint_minus_join_disjoint_disjoint' :\n  forall (A B T : Type) (MC : PermMap A B T) o1 o2 o3 o4 o5,\n    usePerm = false ->\n    disjoint o1 (minus o2 o3) ->\n    join o4 o5 o2 ->\n    disjoint o4 o3 ->\n    disjoint o1 o4.\n  hy.\nQed.\n  \nLemma osabst_disjoint_minus_join_disjoint_disjoint :\n  forall (o1:osabst) o2 o3 o4 o5,\n    disjoint o1 (minus o2 o3) ->\n    join o4 o5 o2 ->\n    disjoint o4 o3 ->\n    disjoint o1 o4.\nProof.\n  intros.\n  eapply osabst_disjoint_minus_join_disjoint_disjoint'; ica.\nQed.\n\nLemma osabst_join_disjoint_merge1' :\n  forall (A B T : Type) (MC : PermMap A B T) o1 o2 o3 o4,\n    usePerm = false ->\n    join o1 o2 o3 ->\n    disjoint o4 o1 ->\n    join o1 (merge o4 o2) (merge o4 o3).\n  hy.\nQed.\n  \nLemma osabst_join_disjoint_merge1 :\n  forall (o1:osabst) o2 o3 o4,\n    join o1 o2 o3 ->\n    disjoint o4 o1 ->\n    join o1 (merge o4 o2) (merge o4 o3).\nProof.\n  intros.\n  eapply osabst_join_disjoint_merge1'; ica.\nQed.\n\n(* Lemma mem_join_disjoint_minus' : *)\n(*   forall (A B T : Type) (MC : PermMap A B T) m1 m2 m3 m4, *)\n(*     usePerm = true -> *)\n(*     join m1 m2 m3 -> *)\n(*     disjoint m1 m4 -> *)\n(*     join m1 (minus m2 m4) (minus m3 m4). *)\n(*   hy. *)\n(* Qed. *)\n\n(** error! **)\n(* Lemma mem_join_disjoint_minus : *)\n(*   forall (m1:mem) m2 m3 m4, *)\n(*     join m1 m2 m3 -> *)\n(*     disjoint m1 m4 -> *)\n(*     join m1 (minus m2 m4) (minus m3 m4). *)\n(* Proof. *)\n(*   intros. *)\n(*   eapply mem_join_disjoint_minus'; ica. *)\n(* Qed. *)\n\nLemma mem_sub_join_minus_join' :\n  forall (A B T : Type) (MC : PermMap A B T) m1 m2 m3 m4,\n    usePerm = true ->\n    join m1 m2 m3 ->\n    Maps.sub m4 m1 ->\n    join (minus m1 m4) m2 (minus m3 m4).\n  hy.\nQed.  \n  \nLemma mem_sub_join_minus_join :\n  forall (m1:mem) m2 m3 m4,\n    join m1 m2 m3 ->\n    Maps.sub m4 m1 ->\n    join (minus m1 m4) m2 (minus m3 m4).\nProof.\n  intros.\n  eapply mem_sub_join_minus_join'; ica.\nQed.\n\nLemma mem_disjoint_sub_disjoint' :\n  forall (A B T : Type) (MC : PermMap A B T) m1 m2 m3,\n    usePerm = true ->\n    Maps.sub m1 m2 ->\n    disjoint m2 m3 ->\n    disjoint m1 m3.\n  hy.\nQed.\n\nLemma mem_disjoint_sub_disjoint :\n  forall (m1:mem) m2 m3,\n    Maps.sub m1 m2 ->\n    disjoint m2 m3 ->\n    disjoint m1 m3.\nProof.\n  intros.\n  eapply mem_disjoint_sub_disjoint'; ica.\nQed.\n\nLemma osabst_join_sub_disjoint' :\n  forall (A B T : Type) (MC : PermMap A B T) o1 o2 o3 o4,\n    usePerm = false ->\n    join o1 o2 o3 ->\n    Maps.sub o4 o2 ->\n    disjoint o1 o4.\n  hy.\nQed.\n\nLemma osabst_join_sub_disjoint :\n  forall (o1:osabst) o2 o3 o4,\n    join o1 o2 o3 ->\n    Maps.sub o4 o2 ->\n    disjoint o1 o4.\nProof.\n  intros.\n  eapply osabst_join_sub_disjoint'; ica.\nQed.\n\nLemma osabst_join_sub_join_minus' :\n  forall (A B T : Type) (MC : PermMap A B T) o1 o2 o3 o4,\n    usePerm = false ->\n    join o1 o2 o3 ->\n    Maps.sub o4 o2 ->\n    join o1 (minus o2 o4) (minus o3 o4).\n  hy.\nQed.\n  \nLemma osabst_join_sub_join_minus :\n  forall (o1:osabst) o2 o3 o4,\n    join o1 o2 o3 ->\n    Maps.sub o4 o2 ->\n    join o1 (minus o2 o4) (minus o3 o4).\nProof.\n  intros.\n  eapply osabst_join_sub_join_minus'; ica.\nQed.\n\nLemma osabst_join_minus1' :\n  forall (A B T : Type) (MC : PermMap A B T) o1 o2 o3,\n    usePerm = false ->\n    join o1 o2 o3 ->\n    minus o3 o1 = o2.\n  hy.\nQed.\n  \nLemma osabst_join_minus1 :\n  forall (o1:osabst) o2 o3,\n    join o1 o2 o3 ->\n    minus o3 o1 = o2.\nProof.\n  intros.\n  eapply osabst_join_minus1'; ica.\nQed.\n  \nLemma mem_join_sub_join_minus' :\n  forall (A B T : Type) (MC : PermMap A B T) m1 m2 m3 m4,\n    usePerm = true ->\n    join m1 m2 m3 ->\n    Maps.sub m4 m2 ->\n    join m1 (minus m2 m4) (minus m3 m4).\n  hy.\nQed.\n\nLemma mem_join_sub_join_minus :\n  forall (m1:mem) m2 m3 m4,\n    join m1 m2 m3 ->\n    Maps.sub m4 m2 ->\n    join m1 (minus m2 m4) (minus m3 m4).\nProof.\n  intros.\n  eapply mem_join_sub_join_minus'; ica.\nQed.\n\nLemma mem_join_minus1' :\n  forall (A B T : Type) (MC : PermMap A B T) m1 m2 m3,\n    usePerm = true ->\n    join m1 m2 m3 ->\n    minus m3 m1 = m2.\n  hy.\nQed.\n\nLemma mem_join_minus1 :\n  forall (m1:mem) m2 m3,\n    join m1 m2 m3 ->\n    minus m3 m1 = m2.\nProof.\n  intros.\n  eapply mem_join_minus1'; ica.\nQed.\n\nLemma osabst_sub_disjoint_sub_minus' :\n  forall (A B T : Type) (MC : PermMap A B T) o1 o2 o3,\n    usePerm = false ->\n    Maps.sub o1 o2 ->\n    disjoint o1 o3 ->\n    Maps.sub o1 (minus o2 o3).\n  hy.\nQed.\n\nLemma osabst_sub_disjoint_sub_minus :\n  forall (o1:osabst) o2 o3,\n    Maps.sub o1 o2 ->\n    disjoint o1 o3 ->\n    Maps.sub o1 (minus o2 o3).\nProof.\n  intros.\n  eapply osabst_sub_disjoint_sub_minus'; ica.\nQed.\n\nLemma osabst_disjoint_minus_minus_disjoint' :\n  forall (A B T : Type) (MC : PermMap A B T) o1 o2 o3 o4,\n    usePerm = false ->\n    disjoint o1 (minus o2 o3) ->\n    disjoint o1 (minus (minus o2 o4) o3).\n  hy.\nQed.\n\nLemma osabst_disjoint_minus_minus_disjoint :\n  forall (o1:osabst) o2 o3 o4,\n    disjoint o1 (minus o2 o3) ->\n    disjoint o1 (minus (minus o2 o4) o3).\nProof.\n  intros.\n  eapply osabst_disjoint_minus_minus_disjoint'; ica.\nQed.\n\nLemma osabst_disjoint_merge_disjoint2' :\n  forall (A B T : Type) (MC : PermMap A B T) o1 o2 o3,\n    usePerm = false ->\n    disjoint (merge o1 o2) o3 ->\n    disjoint o2 o3.\n  hy.\nQed.\n\nLemma osabst_disjoint_merge_disjoint2 :\n  forall (o1:osabst) o2 o3,\n    disjoint (merge o1 o2) o3 ->\n    disjoint o2 o3.\nProof.\n  intros.\n  eapply osabst_disjoint_merge_disjoint2'; ica.\nQed.\n\n\nLemma osabst_disjoint_minus_disjoint' :\n  forall (A B T : Type) (MC : PermMap A B T) o1 o2 o3,\n    usePerm = false ->\n    disjoint o1 o2 ->\n    disjoint o1 (minus o2 o3).\n  hy.\nQed.\n  \nLemma osabst_disjoint_minus_disjoint :\n  forall (o1:osabst) o2 o3,\n    disjoint o1 o2 ->\n    disjoint o1 (minus o2 o3).\nProof.\n  intros.\n  eapply osabst_disjoint_minus_disjoint'; ica.\nQed.\n\n\nLemma osabst_disjoint_disjoint_merge_distribute' :\n  forall (A B T : Type) (MC : PermMap A B T) o1 o2 o3 o4,\n    usePerm = false ->\n    disjoint o1 o2 ->\n    disjoint (merge o1 o2) o3 ->\n    Maps.sub o4 o3 ->\n    join (merge o4 o1) (merge o2 (minus o3 o4)) (merge (merge o1 o2) o3).\n  hy.\nQed.\n\nLemma osabst_disjoint_disjoint_merge_distribute :\n  forall (o1:osabst) o2 o3 o4,\n    disjoint o1 o2 ->\n    disjoint (merge o1 o2) o3 ->\n    Maps.sub o4 o3 ->\n    join (merge o4 o1) (merge o2 (minus o3 o4)) (merge (merge o1 o2) o3).\nProof.\n  intros.\n  eapply osabst_disjoint_disjoint_merge_distribute'; ica.\nQed.\n\n\nLemma osabst_disjoint_minus_comm' :\n  forall (A B T : Type) (MC : PermMap A B T) o1 o2 o3,\n    usePerm = false ->\n    disjoint o2 o3 ->\n    minus (minus o1 o2) o3 = minus (minus o1 o3) o2.\n  hy.\nQed.\n\nLemma osabst_disjoint_minus_comm :\n  forall (o1:osabst) o2 o3,\n    disjoint o2 o3 ->\n    minus (minus o1 o2) o3 = minus (minus o1 o3) o2.\nProof.\n  intros.\n  eapply osabst_disjoint_minus_comm'; ica.\nQed.\n\nLemma sub_join_sub :\n  forall\n    {A B T:Type} {MC:PermMap A B T}\n    m1 m2 m3 m4,\n    join m1 m2 m3 ->\n    Maps.sub m4 m2 ->\n    Maps.sub m4 m3.\nProof.\n  hy.\nQed.\n\n\nLemma mem_sub_join_sub' :\n  forall (A B T : Type) (MC : PermMap A B T) m1 m2 m3 m4,\n    usePerm = true ->\n    join m1 m2 m3 ->\n    Maps.sub m4 m2 ->\n    Maps.sub m4 m3.\n  hy.\nQed.\n\nLemma mem_sub_join_sub :\n  forall (m1:mem) m2 m3 m4,\n    join m1 m2 m3 ->\n    Maps.sub m4 m2 ->\n    Maps.sub m4 m3.\nProof.\n  intros.\n  eapply mem_sub_join_sub'; ica.\nQed.\n\n\nLemma mem_join_sub_disjoint' :\n  forall (A B T : Type) (MC : PermMap A B T) m1 m2 m3 m4,\n    usePerm = true ->\n    join m1 m2 m3 ->\n    Maps.sub m4 m2 ->\n    disjoint m1 m4.\n  hy.\nQed.\n\nLemma mem_join_sub_disjoint :\n  forall (m1:mem) m2 m3 m4,\n    join m1 m2 m3 ->\n    Maps.sub m4 m2 ->\n    disjoint m1 m4.\nProof.\n  intros.\n  eapply mem_join_sub_disjoint'; ica.\nQed.\n\nLemma mem_join_sub_sub_merge_a :\n  forall (A B T : Type) (MC : PermMap A B T) m1 m2 m3 m4,\n    usePerm = true ->\n    join m1 m2 m3 ->\n    Maps.sub m4 m2 ->\n    Maps.sub (merge m1 m4) m3.\n  hy.\nQed.\n\nLemma mem_join_sub_sub_merge :\n  forall (m1:mem) m2 m3 m4,\n    join m1 m2 m3 ->\n    Maps.sub m4 m2 ->\n    Maps.sub (merge m1 m4) m3.\nProof.\n  intros; eapply mem_join_sub_sub_merge_a; ica.\nQed.\n\nLemma mem_join_sub_sub_merge'_auto :\n  forall (A B T : Type) (MC : PermMap A B T) m1 m2 m3 m4,\n    usePerm = true ->\n    join m1 m2 m3 ->\n    Maps.sub m4 m2 ->\n    Maps.sub (merge m4 m1) m3.\n  hy.\nQed.\n\nLemma mem_join_sub_sub_merge' :\n  forall (m1:mem) m2 m3 m4,\n    join m1 m2 m3 ->\n    Maps.sub m4 m2 ->\n    Maps.sub (merge m4 m1) m3.\nProof.\n  intros; eapply mem_join_sub_sub_merge'_auto; ica.\nQed.\n\n\nLemma join_sub_sub_merge :\n  forall {A B T:Type} {MC:PermMap A B T}\n         m1 m2 m3 m4,\n    join m1 m2 m3 ->\n    Maps.sub m4 m2 ->\n    Maps.sub (merge m1 m4) m3.\nProof.\n  hy.\nQed.\n\nLemma join_sub_sub_merge' :\n  forall {A B T:Type} {MC:PermMap A B T}\n         m1 m2 m3 m4,\n    join m1 m2 m3 ->\n    Maps.sub m4 m2 ->\n    Maps.sub (merge m4 m1) m3.\nProof.\n  hy.\nQed.\n\n\nLemma mem_join_minus_auto :\n  forall (A B T : Type) (MC : PermMap A B T) m1 m2 m3,\n    usePerm = true ->\n    join m1 m2 m3 ->\n    m1 = minus m3 m2.\n  hy.\nQed.\n\nLemma mem_join_minus :\n  forall (m1:mem) m2 m3,\n    join m1 m2 m3 ->\n    m1 = minus m3 m2.\nProof.\n  intros; eapply mem_join_minus_auto; ica.\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/tactics/basetac/perm_map_lemmas_part2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2602629968226391}}
{"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 A B C D E Eprime T Eprimeprime Cprime Dprime X Y : Universe, ((wd_ C D /\\ (wd_ A B /\\ (wd_ A C /\\ (wd_ A D /\\ (wd_ Eprime A /\\ (wd_ A T /\\ (wd_ Eprimeprime T /\\ (wd_ D Eprimeprime /\\ (wd_ C Eprimeprime /\\ (wd_ A Eprimeprime /\\ (wd_ Dprime B /\\ (wd_ Cprime B /\\ (wd_ X Y /\\ (wd_ Y A /\\ (wd_ Cprime Dprime /\\ (wd_ Eprimeprime B /\\ (wd_ B C /\\ (wd_ B D /\\ (wd_ D Dprime /\\ (wd_ C Cprime /\\ (wd_ A Dprime /\\ (wd_ A Cprime /\\ (wd_ A E /\\ (wd_ Cprime D /\\ (wd_ D Eprime /\\ (wd_ Dprime C /\\ (col_ C D E /\\ (col_ T A B /\\ (col_ T C D /\\ (col_ X Y A /\\ (col_ X Y Eprimeprime /\\ (col_ B D Dprime /\\ (col_ B C Cprime /\\ (col_ D Eprimeprime C /\\ (col_ A Cprime Dprime /\\ col_ A Eprimeprime Eprime))))))))))))))))))))))))))))))))))) -> col_ A Y Eprimeprime)).\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_0372.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.37387581579519075, "lm_q1q2_score": 0.26020199124679394}}
{"text": "Require Export Program CoqCommon.HList.\nSet Implicit Arguments.\nDefinition FreeFunction := { T : Type & T -> Type }.\nDefinition InterpretFF (ff : FreeFunction) : Type := forall A : projT1 ff, (projT2 ff) A.\nSection CompCoq.\n  Variable l : list FreeFunction.\n  Variable ff : hlist (fun x => (InterpretFF x * nat)%type) l.\n  Inductive CompCoq : forall (T : Type) (F : T -> Type) (C : T -> nat), Type :=\n  | CompId T : @CompCoq T (const T) (const 0)\n  | CompApp T F (G : forall t, F t -> Type) m (M : member (existT _ T F) l) :\n      (forall (t : T), @CompCoq (F t) (G t) (m t)) ->\n      @CompCoq\n        T \n        (fun x => G x (fst (hget M ff) x))\n        (fun x => snd (hget M ff) + m x (fst (hget M ff) x)).\n  Definition Yank T F C (CC : @CompCoq T F C) t : F t.\n    induction CC; intros; simpl in *; auto.\n  Defined.\nEnd CompCoq.\n\n", "meta": {"author": "MarisaKirisame", "repo": "Coq_code", "sha": "b2b96d4be269781d1249fc5191fb590de671ef28", "save_path": "github-repos/coq/MarisaKirisame-Coq_code", "path": "github-repos/coq/MarisaKirisame-Coq_code/Coq_code-b2b96d4be269781d1249fc5191fb590de671ef28/Compute.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.37387580881868493, "lm_q1q2_score": 0.2602019863914366}}
{"text": "(* Proving the correctness of generating RTL from RTLblock *)\n\nRequire Import common.\nRequire Import monad.\nRequire Import monad_impl.\nRequire Import Errors.\nRequire Import RTL.\nRequire Import RTLblock.\nRequire Import IR.\nRequire Import flattenRTL.\nRequire Import customSmallstep.\nRequire Import internal_simulations.\nRequire Import sem_properties.\nRequire Import backend.\nRequire Import Globalenvs.\nRequire Import Values.\nRequire Import Integers.\n\n(** * Simple lemmas *)\nLemma same_id:\n  forall rtlb rtl,\n    flatten rtlb = OK rtl ->\n    prtl_id (Some (inr rtlb)) = prtl_id (Some (inl rtl)).\nProof.\n  destruct rtlb as  (((fid, code), entry), ci).\n  unfold flatten; intros rtl Hf.\n  do_ok.\n  destruct p; inv H0.\n  reflexivity.\nQed.\n\nLemma same_cont_idx:\n  forall i c e cont_ind i' c' e' cont_ind',\n    flatten (i, c, e, cont_ind) = OK (i', c', e', cont_ind') ->\n    cont_ind = cont_ind'.\nProof.\n  intros i c e cont_ind i' c' e' cont_ind' H. unfold flatten in H.\n  repeat do_ok. destruct p. inv H1. auto.\nQed.\n\nLemma same_entry:\n  forall i c e cont_ind i' c' e' cont_ind',\n    flatten (i, c, e, cont_ind) = OK (i', c', e', cont_ind') ->\n    e = e'.\nProof.\n  intros i c e cont_ind i' c' e' cont_ind' H. unfold flatten in H.\n  repeat do_ok. destruct p. inv H1. auto.\nQed.\n\n(** * Positive arithmetic  *)\nLemma inv_lt:\n  forall p,\n    (p < p)%positive -> False.\nProof.\n  intros p H. eapply Pos.lt_irrefl. eauto.\nQed.\n\nLemma inv_succ:\n  forall p,\n    (Pos.succ p <= p)%positive -> False.\nProof.\n  intros p H. rewrite Pos.le_succ_l in H. eapply inv_lt; eauto.\nQed.\n\nLemma succ_le:\n  forall p l,\n    (Pos.succ p <= l)%positive ->\n    (p <= l)%positive.\nProof.\n  intros p l H. eapply Pos.le_trans; eauto. apply Pos.lt_le_incl. apply Pos.lt_succ_diag_r.\nQed.\n\nLemma le_succ:\n  forall p l,\n    (p <= l)%positive ->\n    (p <= Pos.succ l)%positive.\nProof.\n  intros p l H. eapply Pos.le_trans; eauto. apply Pos.lt_le_incl. apply Pos.lt_succ_diag_r.\nQed.\n\nLemma lt_succ:\n  forall p l,\n    (p < l)%positive ->\n    (p < Pos.succ l)%positive.\nProof.\n  intros p l H. eapply Pos.lt_trans; eauto. apply Pos.lt_succ_diag_r.\nQed.\n\nLemma succ_lt:\n  forall p l,\n    (Pos.succ p < l)%positive ->\n    (p < l)%positive.\nProof.\n  intros p l H. eapply Pos.lt_trans; eauto. apply Pos.lt_succ_diag_r.\nQed.\n\nLemma lt_le:\n  forall p1 p2,\n    (p1 < p2)%positive ->\n    (p2 <= p1)%positive ->\n    False.\nProof.\n  intros p1 p2 H H0. assert (p1 < p1)%positive.\n  { eapply Pos.lt_le_trans; eauto. }\n  eapply inv_lt; eauto.\nQed.\n\n\n(** * BLOCK Representation  *)\n(* representing that some blocks have been unfolded in the rtl code *)\n\n\n(* expressing that some list of instructions is in rtlc at label pc, ending on next *)\nInductive unf_list: RTL.code -> list block_instr -> positive -> positive -> Prop :=\n| unf_nil: forall rtlc pc,   \n    unf_list rtlc nil pc pc\n| unf_cons: forall rtlc pc next bi l (i:RTL.instruction)\n              (TRANSF_INSTR: basic_transf_block_instr bi (Pos.succ pc) = i)\n              (FIRST: rtlc # pc = Some i)\n              (NEXT: unf_list rtlc l (Pos.succ pc) next),\n    unf_list rtlc (bi::l) pc next.\n\n(* Expressing that some basic block is in rtlc at label pc *)\nInductive unf_bb: RTL.code -> basic_block -> positive -> Prop :=\n| unf_basic: forall rtlc pc next li exiti e\n               (LIST: unf_list rtlc li pc next)\n               (TRANSF_EXIT: basic_transf_exit_instr exiti = e) \n               (EXIT: rtlc # next = Some e),\n    unf_bb rtlc (li, exiti) pc.\n\n(* Expressing that some block is in rtlc at label pc *)\nInductive unf_block: RTL.code -> RTLblock.block -> positive -> Prop :=\n| unf_bblock: forall rtlc pc bb next\n                (BB: unf_bb rtlc bb next)\n                (NOP: rtlc # pc = Some (Inop next)),\n    unf_block rtlc (Bblock bb) pc\n| unf_cblock: forall rtlc pc op args iftrue bb next\n                (BB: unf_bb rtlc bb next)\n                (COND: rtlc # pc = Some (Icond op args next iftrue)),\n    unf_block rtlc (Cblock op args iftrue bb) pc.\n\n(** * Code Generation Invariants  *)\n(* Everything above the fresh label is undefined *)\nDefinition fresh (fsh:positive) (rtlc:RTL.code) :=\n  forall l, (fsh <= l)%positive -> rtlc # l = None.\n\n(* basic inclusion, for what's above the fresh label *)\nDefinition included (rtlc1 rtlc2:RTL.code) :=\n  forall pc i, rtlc1 # pc = Some i -> rtlc2 # pc = Some i.\n\n(* preservation of what's under the fresh label *)\nDefinition preserved (rtlc1 rtlc2:RTL.code) (fsh:positive) :=\n  forall x, (x < fsh)%positive -> rtlc1 # x = rtlc2 # x.\n\n(* When doing the PTree.fold, everything under fresh is set 1 by 1, only changing the current pc *)\nDefinition preserved_but (rtlc1 rtlc2:RTL.code) (fsh pc:positive) :=\n  forall x, (x < fsh)%positive ->\n       x <> pc ->\n       rtlc1 # x = rtlc2 # x.\n\n(* invariants lemmas *)\nLemma preserved_refl:\n  forall r f,\n    preserved r r f.\nProof.\n  unfold preserved. intros r f x H. auto.\nQed.\n\nLemma unf_list_set:\n  forall rtlc li pc next pcset i,\n    unf_list rtlc li pc next ->\n    fresh pcset rtlc ->\n    unf_list (rtlc # pcset <- i) li pc next.\nProof.\n  intros rtlc li pc next pcset i H H0. induction H.\n  - constructor.\n  - econstructor; eauto. rewrite PTree.gso; auto.\n    intros EQ. subst. specialize (H0 _ (Pos.le_refl pcset)). rewrite FIRST in H0. inv H0.\nQed.\n\nLemma included_refl:\n  forall rtlc, included rtlc rtlc.\nProof.\n  unfold included. intros rtlc pc i H. auto.\nQed.\n\nLemma included_trans:\n  forall r1 r2 r3,\n    included r1 r2 -> included r2 r3 -> included r1 r3.\nProof.\n  unfold included. intros r1 r2 r3 H H0 pc i H1. eapply H0. eapply H. auto.\nQed.\n\nLemma included_set:\n  forall pc r i,\n    fresh pc r ->\n    included r (r # pc <- i).\nProof.\n  unfold included, fresh. intros pc r i H pc0 i0 H0. rewrite PTree.gso. auto.\n  intros EQ. subst. specialize (H _ (Pos.le_refl pc)). rewrite H in H0. inv H0.\nQed.\n\nLemma unf_list_inc:\n  forall r1 li pc next r2,\n    included r1 r2 ->\n    unf_list r1 li pc next ->\n    unf_list r2 li pc next.\nProof.\n  intros r1 li pc next r2 H H0. induction H0.\n  - constructor.\n  - econstructor; eauto.\nQed.\n\nLemma unf_bb_inc:\n  forall r1 bb pc r2,\n    included r1 r2 ->\n    unf_bb r1 bb pc ->\n    unf_bb r2 bb pc.\nProof.\n  intros r1 bb pc r2 H H0. inv H0. econstructor; eauto.\n  eapply unf_list_inc; eauto.\nQed.\n\nLemma unf_block_inc:\n  forall r1 b pc r2,\n    included r1 r2 ->\n    unf_block r1 b pc ->\n    unf_block r2 b pc.\nProof.\n  intros r1 b pc r2 H H0. inv H0.\n  - econstructor; eauto. eapply unf_bb_inc; eauto.\n  - econstructor; eauto. eapply unf_bb_inc; eauto.\nQed.    \n\n\n(** * Initial correctness of the transformations  *)\nLemma tbb_init_ok:\n  forall r1 bb r2,\n    transf_basic_block r1 bb = OK r2 ->\n    exists rtlc1 pc, r1 = OK (rtlc1, pc).\nProof.\n  intros r1 bb r2 H. unfold transf_basic_block in H. destruct bb.\n  generalize dependent r1. induction l; intros.\n  - inv H. unfold transf_exit_instr in H1. repeat do_ok. destruct p. inv H0. eauto.\n  - simpl in H. apply IHl in H as [rtlc1 [pc H]]. unfold transf_block_instr in H. repeat do_ok.\n    destruct p. inv H1. eauto.\nQed.\n\nLemma tei_init_ok:\n  forall r1 ei r2,\n    transf_exit_instr r1 ei = OK r2 ->\n    exists rtlc1 pc, r1 = OK (rtlc1, pc).\nProof.\n  intros r1 ei r2 H. unfold transf_exit_instr in H. repeat do_ok. destruct p. inv H1. eauto.\nQed.\n\nLemma tb_init_ok:\n  forall r1 pc b r2,\n    transf_block r1 pc b = OK r2 ->\n    exists rtlc1 pc, r1 = OK (rtlc1, pc).\nProof.\n  intros r1 pc b r2 H. unfold transf_block in H. destruct b.\n  - repeat do_ok. destruct p. apply tbb_init_ok in H1 as H'. destruct H' as [r1 [l INIT]].\n    inv INIT. eauto.\n  - repeat do_ok. destruct p. apply tbb_init_ok in H1 as H'. destruct H' as [r1 [l' INIT]].\n    inv INIT. eauto.\nQed.\n\nLemma fold_left_init_ok:\n  forall l r1 r2,\n    fold_left (fun a p => transf_block a (fst p) (snd p)) l r1 = OK (r2) ->\n    exists rtlc1 pc, r1 = OK (rtlc1, pc).\nProof.\n  intros l. induction l; intros.\n  - simpl in H. inv H. destruct r2. eauto.\n  - simpl in H. apply IHl in H as H'. destruct H' as [rtlc1 [p1 INIT]].\n    apply tb_init_ok in INIT as H'. destruct H' as [rtlc' [p' INIT']]. eauto.\nQed.\n\n\n(** * Incremental specifications of the transformations  *)\nLemma list_fold_ok:\n  forall li rtlc1 fsh rtlc2 next,\n    fold_left transf_block_instr li (OK (rtlc1, fsh)) = OK (rtlc2, next) ->\n    fresh fsh rtlc1 ->\n    fresh next rtlc2 /\\\n    (fsh <= next)%positive /\\\n    included rtlc1 rtlc2 /\\\n    preserved rtlc1 rtlc2 fsh /\\\n    unf_list rtlc2 li fsh next.\nProof.\n  intros li. induction li; intros.\n  - simpl in H. inv H. split; auto. split. apply Pos.le_refl. split.\n    apply included_refl. split. apply preserved_refl. constructor. \n  - simpl in H. apply IHli in H as H'. destruct H' as [FRESH [LT [INCL [PRES UNF]]]].\n    + repeat try split; auto.\n      * apply succ_le. auto.\n      * eapply included_trans; eauto. apply included_set; auto.\n      * unfold preserved in *. intros x H1. apply lt_succ in H1 as H2. apply PRES in H2.\n        rewrite PTree.gso in H2. 2: { intros EQ. subst. eapply inv_lt. eauto. } auto.\n      * econstructor; eauto. apply INCL. rewrite PTree.gss. auto.\n    + unfold fresh. intros l H1. rewrite PTree.gso.\n      2: { intros EQ. subst. eapply inv_succ; eauto. }\n      apply H0. apply succ_le. auto.\nQed.\n\nLemma tbb_ok:\n  forall rtlc1 fsh rtlc2 next bb,\n    transf_basic_block (OK (rtlc1, fsh)) bb = OK (rtlc2, next) ->\n    fresh fsh rtlc1 ->\n    fresh next rtlc2 /\\\n    (fsh <= next)%positive /\\\n    included rtlc1 rtlc2 /\\\n    preserved rtlc1 rtlc2 fsh /\\\n    unf_bb rtlc2 bb fsh.\nProof.\n  intros rtlc1 pc rtlc2 next bb H H0. destruct bb as [li ei]. unfold transf_basic_block in H.\n  apply tei_init_ok in H as H'. destruct H' as [rtlc1' [pc' FOLD]]. rewrite FOLD in H.\n  apply list_fold_ok in FOLD as H'; auto. destruct H' as [FRESH [LT [INCL [PRES UNF]]]].\n  unfold transf_exit_instr in H. repeat do_ok. inv HDO. inv H2. repeat try split; auto.\n  - unfold fresh. intros l H. rewrite PTree.gso; auto.\n    + apply FRESH. apply succ_le. auto.\n    + intros EQ. subst. eapply inv_succ; eauto.\n  - apply le_succ. auto.\n  - eapply included_trans; eauto. apply included_set; auto.\n  - unfold preserved in *. intros x H. apply PRES in H as H'.\n    rewrite PTree.gso; auto. intros EQ. subst. eapply lt_le; eauto.\n  - eapply unf_basic with (next:=pc'); eauto.\n    + apply unf_list_set; auto.\n    + rewrite PTree.gss. auto.\nQed.\n\nLemma tb_ok:\n  forall rtlc1 fsh pc rtlc2 next b,\n    transf_block (OK (rtlc1, fsh)) pc b = OK (rtlc2, next) ->\n    fresh fsh rtlc1 ->\n    (pc < fsh)%positive ->\n    rtlc1 # pc = None ->\n    fresh next rtlc2 /\\\n    (fsh <= next)%positive /\\\n    included rtlc1 rtlc2 /\\\n    preserved_but rtlc1 rtlc2 fsh pc /\\\n    unf_block rtlc2 b pc.\nProof.\n  intros rtlc1 fsh pc rtlc2 next b H H0 H1 H2. destruct b.\n  - apply tbb_ok in H as H'. destruct H' as [FRESH [LT [INCL [PRES UNF]]]].\n    2: { unfold fresh; intros. rewrite PTree.gso. apply H0. auto.\n         intros EQ. subst. eapply lt_le; eauto. }\n    repeat try split; auto.\n    + eapply included_trans; eauto. unfold included.\n      intros pc0 i H3. rewrite PTree.gso; auto. intros EQ. subst. rewrite H2 in H3. inv H3.\n    + unfold preserved_but. intros x H3 H4. apply PRES in H3 as H'. rewrite PTree.gso in H'; auto.\n    + eapply unf_bblock; eauto. apply INCL. rewrite PTree.gss. auto.\n  - apply tbb_ok in H as H'. destruct H' as [FRESH [LT [INCL [PRES UNF]]]].\n    2: { unfold fresh; intros. rewrite PTree.gso. apply H0. auto.\n         intros EQ. subst. eapply lt_le; eauto. }\n    repeat try split; auto.\n    + eapply included_trans; eauto. unfold included.\n      intros pc0 i H3. rewrite PTree.gso; auto. intros EQ. subst. rewrite H2 in H3. inv H3.\n    + unfold preserved_but. intros x H3 H4. apply PRES in H3 as H'. rewrite PTree.gso in H'; auto.\n    + eapply unf_cblock; eauto. apply INCL. rewrite PTree.gss. auto.\nQed.\n\nLemma flatten_fold_ok:\n  forall l rtlc1 rtlc2 fsh next,\n    list_norepet (map fst l) ->\n    fold_left (fun a p => transf_block a (fst p) (snd p)) l (OK (rtlc1, fsh)) = OK (rtlc2, next) ->\n    fresh fsh rtlc1 ->\n    (forall x, In x (map fst l) -> (x < fsh)%positive) ->\n    (forall x, In x (map fst l) -> rtlc1 # x = None) ->\n    fresh next rtlc2 /\\\n    (fsh <= next)%positive /\\\n    included rtlc1 rtlc2 /\\\n    forall pc blk, In (pc, blk) l -> unf_block rtlc2 blk pc.\nProof.\n  intros l. induction l; intros.\n  - simpl in H0. inv H0. split; try split; try split; auto.\n    + apply Pos.le_refl.\n    + apply included_refl.\n    + intros pc blk H0. inv H0.\n  - inv H. destruct a as [pc blk]. simpl in *.\n    apply fold_left_init_ok in H0 as H'. destruct H' as [rtlc' [fsh' INIT]].\n    apply tb_ok in INIT as H'; auto. destruct H' as [FRESH [LT [INCL [PRES UNF]]]].\n    rewrite INIT in H0. apply IHl in H0 as H'; auto. destruct H' as [FRESH' [LT' [INCL' UNF']]].\n    2: { intros x H. eapply Pos.lt_le_trans; eauto. }\n    2: { intros y H. rewrite <- PRES; auto. intros EQ. subst. apply H6. apply H. }\n    split; try split; try split; auto.\n    + eapply Pos.le_trans; eauto.\n    + eapply included_trans; eauto.\n    + intros pc0 blk0 H. destruct H.\n      * inv H. eapply unf_block_inc; eauto.\n      * apply UNF'. auto.\nQed.\n\nLemma in_map:\n  forall X Y l (x:X),\n    In x (map fst l) ->\n    exists (y:Y), In (x,y) l.\nProof.\n  intros X Y l x H. induction l; inv H.\n  - destruct a. exists y. simpl. left. auto.\n  - apply IHl in H0. destruct H0. exists x0. simpl. right. auto.\nQed.\n\n(** * Final code preservation theorem  *)\nLemma flatten_ok:\n  forall id entry cont blkc rtlc pc blk,\n    flatten (id, blkc, entry, cont) = OK (id, rtlc, entry, cont) ->\n    blkc # pc = Some blk ->\n    unf_block rtlc blk pc. \nProof.\n  intros id entry cont blkc rtlc pc blk H H0. unfold flatten in H. repeat do_ok.\n  rewrite PTree.fold_spec in HDO. destruct p as [blkc' next]. inv H2.\n  apply flatten_fold_ok in HDO as H'. destruct H' as [FRESH [LT [INCL BLK]]].\n  - apply BLK. apply PTree.elements_correct. auto.\n  - apply PTree.elements_keys_norepet.\n  - unfold fresh. intros. rewrite PTree.gempty. auto.\n  - intros. unfold fresh_label, max_label.\n    apply in_map in H. destruct H as [y IN].\n    apply PTree.elements_complete in IN.\n    apply max_pos_correct in IN.\n    eapply Pos.le_lt_trans; eauto. apply Pos.lt_succ_diag_r.\n  - intros x H. rewrite PTree.gempty. auto.\nQed.  \n\n\n(** * Simulation Invariant, order, index  *)\n\nDefinition match_states_is_refl (s:synchro_state) : Prop :=\n  match s with\n  | Halt_RTL _ _ | Halt_Block _ => False\n  | _ => True\n  end.\n\n  \n\n(* The index holds the current entry  *)\n(* This can be the entry point of a continuation, so it changes along the simulation *)\n(* We also include a boolean for the stuttering step of the Cblock *)\n\nInductive stutter : Type :=\n| ONE: stutter\n| ZERO: stutter.\nDefinition index : Type := (positive * stutter).\n\nInductive order: index -> index -> Prop :=\n| stut: forall i,\n    order (i, ZERO) (i, ONE).\n\nLemma order_wf:\n  well_founded order.\nProof.\n  unfold well_founded. intros a. constructor. intros y H. inv H. constructor. intros y H. inv H.\nQed.\n\n\nInductive match_states (p:program) (rtlc:RTL.code): index -> mixed_sem.mixed_state -> mixed_sem.mixed_state -> Prop :=\n| ms_refl s m entry: match_states_is_refl s -> match_states p rtlc (entry,ONE) (s, m) (s,m)\n| ms_block f stk pc mrtl ge m lbi exb rs next entry\n    (GE: ge = Globalenvs.Genv.globalenv (make_prog rtlc entry))\n    (FUN: f = make_fun rtlc entry)\n    (UNF: unf_list rtlc lbi pc next)\n    (EXIT: rtlc # next = Some (basic_transf_exit_instr exb)):\n  match_states p rtlc (entry, ONE) (Halt_Block (BState (Bblock (lbi, exb)) rs), m)\n                                   (Halt_RTL ge (State nil f (Vptr stk Ptrofs.zero) pc rs mrtl), m)\n| ms_cblock f stk pc mrtl ge m rs next entry deoptbb cond args iftrue\n    (GE: ge = Globalenvs.Genv.globalenv (make_prog rtlc entry))\n    (FUN: f = make_fun rtlc entry)\n    (COND: rtlc # pc = Some (Icond cond args next iftrue))\n    (UNF: unf_bb rtlc deoptbb next):\n    match_states p rtlc (entry, ZERO) (Halt_Block (BState (Cblock cond args iftrue deoptbb) rs), m)\n                                      (Halt_RTL ge (State nil f (Vptr stk Ptrofs.zero) pc rs mrtl), m)\n| ms_bpf f stk pc mrtl ge m rs entry\n  (GE: ge = Globalenvs.Genv.globalenv (make_prog rtlc entry))\n  (FUN: f = make_fun rtlc entry):\n  match_states p rtlc (entry, ONE)  (Halt_Block (BPF pc rs), m)\n                                    (Halt_RTL ge (State nil f (Vptr stk Ptrofs.zero) pc rs mrtl), m)\n| ms_final r mrtl ge m entry\n  (GE: ge = Globalenvs.Genv.globalenv (make_prog rtlc entry)):\n  match_states p rtlc (entry, ONE) (Halt_Block (BFinal r), m)\n                                   (Halt_RTL ge (Returnstate nil (Vint r) mrtl), m).\n\nRequire Import mixed_sem.\n\nLemma simul_one_step_is_sufficient :\n  forall L,\n  forall Order:Prop,\n  forall match_states: state L -> state L -> Prop,\n  forall s t s0,\n    (exists s', (Step L s t s' /\\ match_states s0 s')) ->\n    exists s',\n      (SPlus L s t s' \\/ (Star L s t s' /\\ Order)) /\\ match_states s0 s'.\nProof.\n  intros L Order ms s t s0 (s', (T1, T2)).\n  exists s'; split; auto.\n  left.\n  constructor 1 with t s' nil; simpl; eauto.\n  - constructor 1.\n  - unfold Events.Eapp.\n    rewrite app_nil_r.\n    reflexivity.\nQed.\n\nLtac inv_not_true:=\n  match goal with\n  | [H: ~ True |- _] => exfalso; apply H; auto\n  end.\n\n(** * Axiomatization of existing initial states for the functions we generate *)\n(* There exists an initial memory where the globals (the JIT primitive and the main function) have been *)\n(* installed. In practice, this is not in the memory handled by CompCert, but CompCert has no view of *)\n(* the external memory *)\nAxiom external_in_memory:\n  forall rtlc entry,\n  exists initm,\n    Genv.alloc_globals (Genv.globalenv (make_prog rtlc entry)) Memory.Mem.empty\n                       (AST.prog_defs (make_prog rtlc entry)) = Some initm.\n\nLemma initial_rtl_exists:\n  forall rtlc entry,\n    exists r, RTL.initial_state (backend.make_prog rtlc entry) r.\nProof.\n  intros rtlc entry.\n  specialize (external_in_memory rtlc entry) as [initm INITMEM].\n  econstructor. eapply initial_state_intro with (b:=backend.main_id) (m0:=initm); unfold backend.make_prog; simpl.\n  - unfold Globalenvs.Genv.init_mem. auto.\n  - unfold Globalenvs.Genv.find_symbol. simpl. eauto.\n  - unfold Globalenvs.Genv.find_funct_ptr. simpl. eauto.\n  - simpl. auto.\nQed.\n      \nLemma block_eval_condition_exists_eval_condition mrtl c args b:\n  block_eval_condition c args = Some b ->\n  Op.eval_condition c args mrtl = Some b.\nProof.\n  unfold block_eval_condition.\n  destruct c; try congruence;\n    repeat (destruct args; try congruence);\n    simpl; auto.\nQed.\n\n\n(** *  Globalenv lemmas *)\nLemma find_ex_prim:\n  forall rtlc entry prim rs,\n    find_function (Globalenvs.Genv.globalenv (make_prog rtlc entry)) (inr (primitives.EF_ident prim)) rs\n    = Some (AST.External (AST.EF_runtime (primitives.EF_name prim) (primitives.EF_sig prim))).\nProof.\n  intros rtlc entry prim rs.\n  unfold make_prog, Globalenvs.Genv.globalenv. simpl.\n  unfold Genv.find_symbol. unfold Genv.genv_symb, Genv.find_funct_ptr. simpl.\n  destruct prim; simpl; eauto.\nQed.\n\n\nLemma find_main:\n  forall rtlc entry b f,\n    Genv.find_symbol (Genv.globalenv (make_prog rtlc entry)) main_id = Some b ->\n    Genv.find_funct_ptr (Genv.globalenv (make_prog rtlc entry)) b = Some f ->\n    f = AST.Internal (make_fun rtlc entry).\nProof.\n  unfold make_prog. intros rtlc entry b f H H0.\n  unfold Genv.find_symbol, Genv.genv_symb, Genv.globalenv in H.\n  simpl in H. inv H.\n  unfold Genv.find_funct_ptr, Genv.find_def, Genv.globalenv in H0. simpl in H0. inv H0. auto.\nQed.\n\n(* Freeing of size 0 *)\nLemma free_0:\n  forall m stk, exists m',\n    Memory.Mem.free m stk 0 0 = Some m'.\nProof.\n  intros m stk. Transparent Memory.Mem.free. unfold Memory.Mem.free.\n  destruct (Memory.Mem.range_perm_dec m stk 0 0 Memtype.Cur Memtype.Freeable) eqn:FREE.\n  - unfold Memory.Mem.unchecked_free. destruct m. simpl.  eauto.    \n  - unfold Memory.Mem.range_perm in n. exfalso. apply n. intros ofs H. inv H. omega.\n    Opaque Memory.Mem.free.\nQed.\n  \n\n(** * Forward Simulation  *)\nTheorem flatten_forward:\n  forall (p:program) (nc:asm_codes) (rtlb:RTLblockfun) (rtl:RTLfun)\n    (NO_CONFLICT: ~ rtl_conflict (Some (inr rtlb)) nc) (* nc doesn't contain a function fid *)\n    (FLATTEN: flatten rtlb = OK rtl),\n    forward_internal_simulation p p (Some (inr rtlb)) (Some (inl rtl)) nc nc.\nProof.\n  intros p nc rtlb rtl; intros.\n  destruct rtl as [[[rtlfid rtlc] rtlentry] rtlcont].\n  destruct rtlb as [[[fid blockc] entry] cont].\n  assert (rtlfid = fid). { apply same_id in FLATTEN. inv FLATTEN. auto. } subst rtlfid.\n  apply same_cont_idx in FLATTEN as SAME. subst rtlcont.\n  apply same_entry in FLATTEN as SAME. subst rtlentry.\n  \n  eapply Forward_internal_simulation with (fsim_match_states:=match_states p rtlc) (fsim_order := order).\n  - apply order_wf.\n  - unfold call_refl, p_reflexive. intros s H.\n    exists (entry, ONE). destruct s. eapply ms_refl. inv H. constructor.\n  - intros p0 s1 s2 r Hm Hf1.\n    inv Hm; auto; inv Hf1.\n  -\n{ intros s1 t s1' STEP i s2 MATCH. inv MATCH.\n  - destruct s1' as (s', m').\n      assert (M:match_states_is_refl s' \\/ ~ match_states_is_refl s').\n      { destruct s'; simpl; intuition. }\n      destruct M.\n    + exists (xH, ONE). apply simul_one_step_is_sufficient. exists (s', m').\n        split; [idtac | econstructor 1; eauto].        \n        inv STEP; try (elim H; fail); try (elim H0; fail); econstructor; eauto. \n    + inv STEP; try solve[inv H]; simpl in H0; try inv_not_true; try inv RTL.\n        (* interpreter can't produce RTL states *)\n        { unfold IRinterpreter.ir_step in STEP0. rewrite exec_bind2 in STEP0. simpl in STEP0.\n          repeat sdo_ok. destruct p0. destruct i; simpl in H0; try inv_not_true.\n          destruct c; simpl in H0; try inv_not_true. }\n        (* ASM can't produce RTL states *)\n        { unfold ASMinterpreter.asm_int_step in STEP0. rewrite exec_bind2 in STEP0. simpl in STEP0.\n          repeat sdo_ok. destruct p0. destruct i; simpl in STEP0; repeat sdo_ok; simpl in H0; try inv_not_true.\n          destruct c; simpl in H0; try inv_not_true. }\n      * inv RTL_BLOCK.  (* calling RTLBLOCK *)\n        exists (entry1, ONE).\n        specialize (initial_rtl_exists rtlc entry1) as [inits INIT].\n        { inv INIT.\n          apply find_main in H3 as MAIN; auto. subst f.\n          destruct (Memory.Mem.alloc m0 0 0) as [m0' stk] eqn:E.\n          (* Going into the entry program *)\n          econstructor; esplit.\n          - left. simpl. eapply plus_two.\n            + eapply Call_RTL; eauto. econstructor; eauto.\n            + eapply rtl_step; eauto.\n              * intro T; inv T.\n              * eapply exec_function_internal; eauto.\n            + reflexivity.\n          - simpl. constructor; auto. }\n      * inv RTL_BLOCK. (* returning to RTLBLOCK *)\n        specialize (initial_rtl_exists rtlc cont_entry) as [inits INIT].\n        { inv INIT.\n          apply find_main in H3 as MAIN; auto. subst f.\n          destruct (Memory.Mem.alloc m0 0 0) as [m0' stk] eqn:E .\n          exists (cont_entry, ONE).      (* going into continuation *)\n          econstructor; esplit.\n          - left. simpl. eapply plus_two.\n            + eapply Return_RTL; eauto. econstructor; eauto.\n               + eapply rtl_step; eauto.\n                 * intro T; inv T.\n                 * eapply exec_function_internal; eauto.\n               + reflexivity.\n          - simpl. constructor; auto. }\n    \n  - inv STEP.                   (* ms_block *)\n    destruct lbi.\n    + inv UNF.                  (* exit instruction *)\n      simpl in BLOCK. exists (entry0, ONE). destruct exb.\n      * inv BLOCK. econstructor. split. (* nop *)\n        ** left. apply plus_one. econstructor. \n           { intros H. inv H. simpl in BUILTIN. rewrite BUILTIN in EXIT. inv EXIT. }\n           eapply exec_Inop. simpl. eauto.\n        ** constructor; auto.\n      * repeat sdo_ok. econstructor. split. (* cond *)\n        ** left. apply plus_one. econstructor.\n           { intros H. inv H. simpl in BUILTIN. rewrite BUILTIN in EXIT. inv EXIT. }\n           eapply exec_Icond; eauto. apply eval_condition_correct. eauto.\n        ** constructor; auto.\n      * assert (HMEM: exists m',  Memory.Mem.free mrtl stk 0 0 = Some m') by apply free_0.\n        destruct HMEM as [m' HMEM]. repeat sdo_ok.\n        unfold get_int_reg in HDO0. destruct (rs !! r) eqn:GET; inv HDO0.\n        repeat sdo_ok. econstructor. split. (* return *)\n        ** left. apply plus_one. econstructor.\n           { intros H. inv H. simpl in BUILTIN. rewrite BUILTIN in EXIT. inv EXIT. }\n           eapply exec_Ireturn; eauto.\n        ** unfold Registers.regmap_optget. rewrite GET. constructor. auto.\n\n    + inv UNF.                  (* peeling off one instruction of the block *)\n      simpl in BLOCK. repeat sdo_ok. destruct b; simpl in FIRST; simpl in HDO.\n      * repeat sdo_ok. eapply eval_operation_correct in HDO. (* Op *)\n        exists (entry0, ONE). econstructor. split.\n        ** left. apply plus_one. simpl. econstructor.\n           { intros H. inv H. simpl in BUILTIN. rewrite BUILTIN in FIRST. inv FIRST. }\n           eapply exec_Iop; eauto.\n        ** simpl. eapply ms_block; eauto.\n      * assert (A: find_function (Globalenvs.Genv.globalenv (make_prog rtlc entry0)) (inr (primitives.EF_ident e)) rs = Some (AST.External (AST.EF_runtime (primitives.EF_name e) (primitives.EF_sig e))) ).\n        { apply find_ex_prim. }\n        repeat sdo_ok. destruct p1. exists (entry0, ONE). econstructor. split. (* prim call *)\n        ** left. eapply plus_three.\n           *** eapply rtl_step.\n               { intros H. inv H. simpl in BUILTIN. rewrite BUILTIN in FIRST. inv FIRST. }\n               eapply exec_Icall; eauto. \n           *** eapply RTL_prim. eapply HDO0.\n           *** eapply rtl_step.\n               { intros H. inv H. }\n               eapply exec_return.\n           *** simpl. rewrite Events.E0_right. auto.\n        ** simpl. eapply ms_block; eauto.\n\n  - exists (entry0, ONE). inv UNF. inv STEP. (* ms_cblock *)\n    simpl in BLOCK. repeat sdo_ok.\n    eapply eval_condition_correct in HDO0; eauto.\n    destruct b.\n    + inv BLOCK. econstructor. split.\n      * left. apply plus_one. eapply rtl_step.\n        { intros H. inv H. simpl in BUILTIN. rewrite BUILTIN in COND. inv COND. }\n        eapply exec_Icond; eauto.\n      * eapply ms_block; eauto.\n    + inv BLOCK. econstructor. split.\n      * left. apply plus_one. eapply rtl_step.\n        { intros H. inv H. simpl in BUILTIN. rewrite BUILTIN in COND. inv COND. }\n        eapply exec_Icond; eauto.\n      * eapply ms_bpf; eauto.\n\n  - inv STEP.                   (* ms_bpf *)\n    simpl in BLOCK. repeat sdo_ok.\n    eapply flatten_ok in FLATTEN as H; eauto. inv H.\n    + exists (entry0, ONE). econstructor. split.      (* going into Bblock *)\n      * left. apply plus_one. apply rtl_step.\n        { intros H. inv H. simpl in BUILTIN. rewrite BUILTIN in NOP. inv NOP. }\n        eapply exec_Inop; eauto.\n      * destruct bb. inv BB. eapply ms_block; eauto.\n    + exists (entry0, ZERO). inv BB. econstructor. split.      (* going into Cblock *)\n      * right. split. 2: { apply stut. } eapply star_refl. (* stuttering *)\n      * eapply ms_cblock; eauto. econstructor; eauto. \n\n  - inv STEP.                   (* ms_final *)\n    { simpl in BLOCK. inv BLOCK. }\n    exists (entry0, ONE). econstructor. split.\n    + left. eapply plus_one.\n      eapply RTL_end; eauto. constructor.\n    + apply ms_refl. destruct cp; simpl; auto. }\nQed.\n\n\nTheorem flatten_correct:\n  forall (p:program) (nc:asm_codes) (rtlb:RTLblockfun) (rtl:RTLfun)\n    (NO_CONFLICT: ~ rtl_conflict (Some (inr rtlb)) nc) \n    (FLATTEN: flatten rtlb = OK rtl),\n    backward_internal_simulation p p (Some (inr rtlb)) (Some (inl rtl)) nc nc.\nProof.\n  intros p nc rtlb rtl NO_CONFLICT FLATTEN.\n  apply forward_to_backward_simulation.\n  - apply flatten_forward; auto.\n  - apply mixed_receptive.\n  - apply mixed_determinate. unfold not. intros H.\n    apply NO_CONFLICT. inv H. apply same_id in FLATTEN. destruct rtlb as [[[fid' blk] ent] cont].\n    simpl in FLATTEN. inv FLATTEN. eapply conflict; eauto.\nQed.\n\n\n\n(** * We show here that we only produce a subset of RTL *)\nRequire Import primitives.\nRequire Import Errors.\n\n\nInductive rtl_instr_wf : RTL.instruction -> Prop :=\n(* no load, no store, no builtin, no jumptable *)\n| inop_wf: forall n, rtl_instr_wf (Inop n)\n| iop_wf: forall o l r n, rtl_instr_wf (Iop o l r n)\n| icond_wf: forall o l n1 n2, rtl_instr_wf (Icond o l n1 n2)\n(* calls are limited to primitives *)\n| icall_wf: forall (ef:ext_primitive) l r n,\n    rtl_instr_wf (Icall (EF_sig ef) (inr (EF_ident ef)) l r n)\n| ireturn_wf: forall r, rtl_instr_wf (Ireturn (Some r)).\n\nDefinition rtl_code_wf (c:RTL.code): Prop :=\n  forall pc i, c#pc = Some i -> rtl_instr_wf i.\n\n\nLemma fold_ok:\n  forall l cf1 c2 n,\n    fold_left (fun a p => transf_block a (fst p) (snd p)) l cf1 = OK (c2, n) ->\n    exists cf, cf1 = OK (cf).\nProof.\n  intros l. induction l; intros.\n  - simpl in H. inv H. eauto.\n  - simpl in H. apply IHl in H. destruct H as [cf OK].\n    destruct cf1; eauto.\n    unfold transf_block in OK. destruct a as [na [b1 | b2]];  inv OK.\nQed.\n\nLemma transf_basic_ok:\n  forall b c1 f1 c2 f2,\n    transf_basic_block (OK (c1, f1)) b = OK (c2, f2) ->\n    rtl_code_wf c1 ->\n    rtl_code_wf c2.\nProof.\n  intros [l e]. induction l; intros.\n  - simpl in H. inv H. unfold rtl_code_wf in *. unfold basic_transf_exit_instr. destruct e; intros.\n    + poseq_destr pc f1.\n      * rewrite PTree.gss in H. inv H. constructor.\n      * rewrite PTree.gso in H; auto. apply H0 in H. auto.\n    + poseq_destr pc f1.\n      * rewrite PTree.gss in H. inv H. constructor.\n      * rewrite PTree.gso in H; auto. apply H0 in H. auto.\n    + poseq_destr pc f1.\n      * rewrite PTree.gss in H. inv H. constructor.\n      * rewrite PTree.gso in H; auto. apply H0 in H. auto.\n  - simpl in H. eapply IHl in H; eauto. unfold rtl_code_wf in *. destruct a; intros.\n    + poseq_destr pc f1.\n      * rewrite PTree.gss in H1. inv H1. constructor.\n      * rewrite PTree.gso in H1; auto. apply H0 in H1. auto.\n    + poseq_destr pc f1.\n      * rewrite PTree.gss in H1. inv H1. constructor.\n      * rewrite PTree.gso in H1; auto. apply H0 in H1. auto.\nQed.\n\nLemma transf_block_ok:\n  forall c1 f1 l b c2 f2,\n    transf_block (OK (c1, f1)) l b = OK (c2, f2) ->\n    rtl_code_wf c1 ->\n    rtl_code_wf c2.\nProof.\n  intros c1 f1 l b c2 f2 H H0. unfold transf_block in H.\n  destruct b.\n  + repeat do_ok. inv HDO. apply transf_basic_ok in H2; auto. unfold rtl_code_wf in *. intros.\n    poseq_destr pc l.\n    * rewrite PTree.gss in H. inv H. constructor.\n    * rewrite PTree.gso in H; auto. apply H0 in H. auto.\n  + repeat do_ok. inv HDO. apply transf_basic_ok in H2; auto.  unfold rtl_code_wf in *. intros.\n    poseq_destr pc l.\n    * rewrite PTree.gss in H. inv H. constructor.\n    * rewrite PTree.gso in H; auto. apply H0 in H. auto.\nQed.\n\n\nTheorem flatten_wf:\n  forall rtlb fid rtlc entry cont,\n    flatten rtlb = OK (fid, rtlc, entry, cont) ->\n    rtl_code_wf rtlc.\nProof.\n  assert (forall l fresh c1 c2 n, rtl_code_wf c1 -> fold_left (fun a p => transf_block a (fst p) (snd p)) l (OK (c1, fresh)) = OK (c2, n) -> rtl_code_wf c2). \n  { intros l.\n    induction l; intros; simpl in H0. { inv H0. auto. }\n    apply fold_ok in H0 as OKinit. destruct OKinit as [[c f] OK]. rewrite OK in H0.\n    apply IHl in H0; auto.\n    destruct a as [label blk]. simpl in OK. apply transf_block_ok in OK; auto. }\n  intros [[[f blkc] ent] co] fid rtlc entry cont H1.\n  unfold flatten in H1. do_ok. destruct p as [rtlc' n]. inv H2.\n  rewrite PTree.fold_spec in HDO. apply H in HDO; auto.\n  unfold rtl_code_wf. intros pc i H0. rewrite PTree.gempty in H0. inv H0.\nQed.\n", "meta": {"author": "Aurele-Barriere", "repo": "FM-JIT", "sha": "deedcb59d030b7957433fecc493a3c0f0a6bfdd6", "save_path": "github-repos/coq/Aurele-Barriere-FM-JIT", "path": "github-repos/coq/Aurele-Barriere-FM-JIT/FM-JIT-deedcb59d030b7957433fecc493a3c0f0a6bfdd6/coqjit/flattenRTL_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.26011000174457133}}
{"text": "Require Import Rel.Definitions.\nRequire Import Lang.BindingsFacts.\nRequire Import Lang.Static.\nRequire Import Lang.StaticFacts.\nRequire Import Lang.Sig.\nRequire Import Lang.SigFacts.\nRequire Import Wf_natnat.\nRequire Import Compat_sub.\nRequire Import Compat_map_EV.\nRequire Import Compat_map_LV.\nSet Implicit Arguments.\n\nImplicit Types EV LV V L : Set.\n\nSection section_LV_bind_aux.\n\nHint 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\n| [ H : _ ⊨ (False)ᵢ |- _ ] => icontradict H\nend.\n\nFixpoint\n  LV_bind_𝓾_aux\n  (n : nat)\n  (EV LV LV' : Set)\n  (Ξ : XEnv EV LV)\n  (f : LV → lbl LV' ∅)\n  (δ₁ δ₂ : EV → eff0) (δ : EV → IRel 𝓤_Sig)\n  (ρ₁ ρ₂ : LV → lbl0) (ρ : LV → IRel 𝓣_Sig)\n  (ρ₁' ρ₂' : LV' → lbl0) (ρ' : LV' → IRel 𝓣_Sig)\n  (Hρ₁ : ∀ α, ρ₁ α = LV_bind_lbl ρ₁' (f α))\n  (Hρ₂ : ∀ α, ρ₂ α = LV_bind_lbl ρ₂' (f α))\n  (Hρ :\n    n ⊨ ∀ᵢ α ξ₁ ξ₂ v₁ v₂,\n        𝓣𝓵⟦ Ξ ⊢ lbl_var α ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ v₁ v₂ ⇔\n        𝓣𝓵⟦ (LV_bind_XEnv f Ξ) ⊢ f α ⟧ δ₁ δ₂ δ ρ₁' ρ₂' ρ' ξ₁ ξ₂ v₁ v₂\n  )\n  (Wf_f : ∀ α, wf_lbl (LV_bind_XEnv f Ξ) (f α))\n  ξ₁ ξ₂ (t₁ t₂ : tm0) (ψ : IRel 𝓣_Sig) l₁ l₂ (ε : ef ∅ EV LV ∅)\n  (W : Acc lt' (n, 0))\n  {struct W} :\n  (n ⊨\n    𝓾⟦ Ξ ⊢ ε ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂ ⇔\n    𝓾⟦ (LV_bind_XEnv f Ξ) ⊢ LV_bind_ef f ε ⟧\n      δ₁ δ₂ δ ρ₁' ρ₂' ρ' ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂)\n\nwith\n  LV_bind_𝓤_aux\n  (n : nat)\n  (EV LV LV' : Set)\n  (Ξ : XEnv EV LV)\n  (f : LV → lbl LV' ∅)\n  (δ₁ δ₂ : EV → eff0) (δ : EV → IRel 𝓤_Sig)\n  (ρ₁ ρ₂ : LV → lbl0) (ρ : LV → IRel 𝓣_Sig)\n  (ρ₁' ρ₂' : LV' → lbl0) (ρ' : LV' → IRel 𝓣_Sig)\n  (Hρ₁ : ∀ α, ρ₁ α = LV_bind_lbl ρ₁' (f α))\n  (Hρ₂ : ∀ α, ρ₂ α = LV_bind_lbl ρ₂' (f α))\n  (Hρ :\n    n ⊨ ∀ᵢ α ξ₁ ξ₂ v₁ v₂,\n        𝓣𝓵⟦ Ξ ⊢ lbl_var α ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ v₁ v₂ ⇔\n        𝓣𝓵⟦ (LV_bind_XEnv f Ξ) ⊢ f α ⟧ δ₁ δ₂ δ ρ₁' ρ₂' ρ' ξ₁ ξ₂ v₁ v₂\n  )\n  (Wf_f : ∀ α, wf_lbl (LV_bind_XEnv f Ξ) (f α))\n  ξ₁ ξ₂ (t₁ t₂ : tm0) (ψ : IRel 𝓣_Sig) l₁ l₂ (E : eff ∅ EV LV ∅)\n  (W : Acc lt' (n, size_eff E))\n  {struct W} :\n  (n ⊨\n    𝓤⟦ Ξ ⊢ E ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂ ⇔\n    𝓤⟦ (LV_bind_XEnv f Ξ) ⊢ LV_bind_eff f E ⟧\n      δ₁ δ₂ δ ρ₁' ρ₂' ρ' ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂)\n\nwith\n  LV_bind_𝓥_aux\n  (n : nat)\n  (EV LV LV' : Set)\n  (Ξ : XEnv EV LV)\n  (f : LV → lbl LV' ∅)\n  (δ₁ δ₂ : EV → eff0) (δ : EV → IRel 𝓤_Sig)\n  (ρ₁ ρ₂ : LV → lbl0) (ρ : LV → IRel 𝓣_Sig)\n  (ρ₁' ρ₂' : LV' → lbl0) (ρ' : LV' → IRel 𝓣_Sig)\n  (Hρ₁ : ∀ α, ρ₁ α = LV_bind_lbl ρ₁' (f α))\n  (Hρ₂ : ∀ α, ρ₂ α = LV_bind_lbl ρ₂' (f α))\n  (Hρ :\n    n ⊨ ∀ᵢ α ξ₁ ξ₂ v₁ v₂,\n        𝓣𝓵⟦ Ξ ⊢ lbl_var α ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ v₁ v₂ ⇔\n        𝓣𝓵⟦ (LV_bind_XEnv f Ξ) ⊢ f α ⟧ δ₁ δ₂ δ ρ₁' ρ₂' ρ' ξ₁ ξ₂ v₁ v₂\n  )\n  (Wf_f : ∀ α, wf_lbl (LV_bind_XEnv f Ξ) (f α))\n  ξ₁ ξ₂ (v₁ v₂ : val0) (T : ty ∅ EV LV ∅)\n  (W : Acc lt' (n, size_ty T))\n  {struct W} :\n  (n ⊨\n    𝓥⟦ Ξ ⊢ T ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ v₁ v₂ ⇔\n    𝓥⟦ (LV_bind_XEnv f Ξ) ⊢ LV_bind_ty f T ⟧\n      δ₁ δ₂ δ ρ₁' ρ₂' ρ' ξ₁ ξ₂ v₁ v₂)\n\nwith\n  LV_bind_𝓜_aux\n  (n : nat)\n  (EV LV LV' : Set)\n  (Ξ : XEnv EV LV)\n  (f : LV → lbl LV' ∅)\n  (δ₁ δ₂ : EV → eff0) (δ : EV → IRel 𝓤_Sig)\n  (ρ₁ ρ₂ : LV → lbl0) (ρ : LV → IRel 𝓣_Sig)\n  (ρ₁' ρ₂' : LV' → lbl0) (ρ' : LV' → IRel 𝓣_Sig)\n  (Hρ₁ : ∀ α, ρ₁ α = LV_bind_lbl ρ₁' (f α))\n  (Hρ₂ : ∀ α, ρ₂ α = LV_bind_lbl ρ₂' (f α))\n  (Hρ :\n    n ⊨ ∀ᵢ α ξ₁ ξ₂ v₁ v₂,\n        𝓣𝓵⟦ Ξ ⊢ lbl_var α ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ v₁ v₂ ⇔\n        𝓣𝓵⟦ (LV_bind_XEnv f Ξ) ⊢ f α ⟧ δ₁ δ₂ δ ρ₁' ρ₂' ρ' ξ₁ ξ₂ v₁ v₂\n  )\n  (Wf_f : ∀ α, wf_lbl (LV_bind_XEnv f Ξ) (f α))\n  ξ₁ ξ₂ (m₁ m₂ : md0) (σ : ms ∅ EV LV ∅) ℓ\n  (W : Acc lt' (n, size_ms σ))\n  {struct W} :\n  (n ⊨\n    𝓜⟦ Ξ ⊢ σ ^ ℓ ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ m₁ m₂ ⇔\n    𝓜⟦ (LV_bind_XEnv f Ξ) ⊢ (LV_bind_ms f σ) ^ (LV_bind_lbl f ℓ) ⟧\n      δ₁ δ₂ δ ρ₁' ρ₂' ρ' ξ₁ ξ₂ m₁ m₂)\n\nwith\n  LV_bind_𝓣𝓵_aux\n  (n : nat)\n  (EV LV LV' : Set)\n  (Ξ : XEnv EV LV)\n  (f : LV → lbl LV' ∅)\n  (δ₁ δ₂ : EV → eff0) (δ : EV → IRel 𝓤_Sig)\n  (ρ₁ ρ₂ : LV → lbl0) (ρ : LV → IRel 𝓣_Sig)\n  (ρ₁' ρ₂' : LV' → lbl0) (ρ' : LV' → IRel 𝓣_Sig)\n  (Hρ₁ : ∀ α, ρ₁ α = LV_bind_lbl ρ₁' (f α))\n  (Hρ₂ : ∀ α, ρ₂ α = LV_bind_lbl ρ₂' (f α))\n  (Hρ :\n    n ⊨ ∀ᵢ α ξ₁ ξ₂ v₁ v₂,\n        𝓣𝓵⟦ Ξ ⊢ lbl_var α ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ v₁ v₂ ⇔\n        𝓣𝓵⟦ (LV_bind_XEnv f Ξ) ⊢ f α ⟧ δ₁ δ₂ δ ρ₁' ρ₂' ρ' ξ₁ ξ₂ v₁ v₂\n  )\n  (Wf_f : ∀ α, wf_lbl (LV_bind_XEnv f Ξ) (f α))\n  ξ₁ ξ₂ (t₁ t₂ : tm0) (ℓ : lbl LV ∅)\n  (W : Acc lt' (n, size_lbl Ξ ℓ))\n  {struct W} :\n  (n ⊨\n    𝓣𝓵⟦ Ξ ⊢ ℓ ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ⇔\n    𝓣𝓵⟦ (LV_bind_XEnv f Ξ) ⊢ LV_bind_lbl f ℓ ⟧\n      δ₁ δ₂ δ ρ₁' ρ₂' ρ' ξ₁ ξ₂ t₁ t₂)\n.\n\nProof.\n\n{\ndestruct ε as [ | α | [ α | [ α | X ] ] ] ; simpl.\n+ auto.\n+ auto_contr.\n+ auto_contr.\n  - clear - Hρ₁ Hρ₂ ; crush.\n  - destruct (f α) as [ α' | [ α' | X' ] ] eqn : Heq ; [ reflexivity | reflexivity | ].\n    split ; [ intro | trivial ].\n    clear - Wf_f Heq.\n    rewrite LV_bind_XEnv_dom.\n    specialize (Wf_f α) ; rewrite Heq in Wf_f.\n    inversion Wf_f ; subst.\n    erewrite <- LV_bind_XEnv_dom ; eassumption.\n  - apply 𝓗_Fun_nonexpansive ; repeat iintro.\n    * auto_contr.\n    * iespecialize Hρ ; apply Hρ.\n+ contradict α.\n+ rewrite LV_bind_XEnv_dom.\n  auto_contr.\n  apply 𝓗_Fun_nonexpansive ; repeat iintro.\n  - auto_contr.\n  - destruct (get X Ξ) as [ [T E] | ] eqn:HX.\n    * eapply binds_LV_bind in HX ; rewrite HX.\n      apply 𝓣_Fun_Fix'_nonexpansive ; repeat iintro.\n      { apply 𝓥_roll_unroll_iff ; auto. }\n      { apply 𝓤_roll_unroll_iff ; auto. }\n    * apply get_none_inv in HX.\n      erewrite <- LV_bind_XEnv_dom in HX.\n      apply get_none in HX.\n      rewrite HX ; auto_contr.\n}\n\n{\ndestruct E as [ | ε E ] ; simpl ; auto_contr.\n+ apply LV_bind_𝓾_aux ; auto.\n+ apply LV_bind_𝓤_aux ; auto.\n}\n\n{\ndestruct T as [ | Ta Ea Tb Eb | N ℓ | σ ℓ ] eqn:HT ; simpl 𝓥_Fun.\n+ auto_contr.\n+ auto_contr.\n  apply 𝓚_Fun_nonexpansive ; repeat iintro ;\n  apply 𝓣_Fun_Fix'_nonexpansive ; repeat iintro ; auto.\n+ auto_contr.\n  - repeat erewrite LV_bind_bind_lbl ; try reflexivity ; crush.\n  - apply 𝓥_roll_unroll_iff.\n    match goal with\n    | [ |- ?n ⊨ 𝓥⟦ _ ⊢ ?T ⟧ _ _ _ _ _ _ _ _ _ _ ⇔\n                𝓥⟦ _ ⊢ ?T' ⟧ _ _ _ _ _ _ _ _ _ _ ] =>\n      replace T' with (LV_bind_ty f T)\n      by (simpl ; erewrite LV_bind_it_msig ; crush)\n    end.\n    apply LV_bind_𝓥_aux ; auto.\n+ auto_contr.\n  - repeat erewrite LV_bind_bind_lbl ; try reflexivity ; crush.\n  - apply LV_bind_𝓜_aux ; auto.\n}\n\n{\ndestruct σ as [ τ | τ | τ | Ta Ea ] eqn:Hσ ; simpl 𝓜_Fun.\n+ auto_contr.\n  rewrite LV_bind_EV_map_XEnv.\n  apply LV_bind_𝓜_aux ; [ auto | auto | | | auto ].\n  - erewrite <- LV_bind_EV_map_XEnv.\n    repeat iintro ; iespecialize Hρ.\n    eapply I_iff_transitive ; [\n      apply I_iff_symmetric ; apply EV_map_𝓣𝓵 |\n      eapply I_iff_transitive ; [ apply Hρ | apply EV_map_𝓣𝓵 ]\n    ] ; try reflexivity ; try (repeat iintro ; simpl ; auto_contr).\n  - erewrite <- LV_bind_EV_map_XEnv.\n    intro ; apply EV_map_wf_lbl ; auto.\n+ auto_contr.\n  erewrite <- LV_bind_map_XEnv with (f₂ := LV_lift_inc f) ; [ | ].\n  erewrite <- LV_bind_map_lbl with (f₂ := LV_lift_inc f) ; [ | ].\n  apply LV_bind_𝓜_aux ; [ | | | | auto ].\n  - intro α ; destruct α ; simpl ; [ auto | ].\n    erewrite LV_bind_map_lbl, LV_map_lbl_id ; eauto.\n    intro ; simpl ; erewrite LV_map_lbl_id ; reflexivity.\n  - intro α ; destruct α ; simpl ; [ auto | ].\n    erewrite LV_bind_map_lbl, LV_map_lbl_id ; eauto.\n    intro ; simpl ; erewrite LV_map_lbl_id ; reflexivity.\n  - iintro α ; destruct α ; simpl ; repeat iintro ; [ auto_contr | ].\n    simpl in Hρ ; iespecialize Hρ.\n    erewrite LV_bind_map_XEnv ; try reflexivity.\n    eapply I_iff_transitive ; [\n      apply Hρ |\n      apply LV_map_𝓣𝓵 ; try reflexivity ; try (repeat iintro ; simpl ; auto_contr)\n    ].\n  - intro α ; destruct α ; simpl ; [ constructor | ].\n    erewrite LV_bind_map_XEnv ; try reflexivity.\n    apply LV_map_wf_lbl ; auto.\n  - reflexivity.\n  - reflexivity.\n+ auto_contr ; auto.\n+ rewrite LV_bind_XEnv_dom.\n  auto_contr.\n  - repeat match goal with\n    | [ |- context[ match ?x with _ => _ end ] ] => destruct x eqn:?\n    end ; simpl ; crush.\n    match goal with\n    | [ H : ?f ?α = _ |- _ ] => specialize (Wf_f α) ; rewrite H in Wf_f ; clear - Wf_f\n    end.\n    inversion Wf_f.\n    rewrite LV_bind_XEnv_dom in *.\n    crush.\n  - apply 𝓗_Fun_nonexpansive ; repeat iintro.\n    * apply 𝓣_Fun_Fix'_nonexpansive ; repeat iintro ; [ auto | ].\n      auto_contr.\n      { repeat erewrite LV_bind_bind_lbl ; try reflexivity ; crush. }\n      { \n        destruct ℓ as [ α | [ | X ] ] ; simpl ; [ | auto | crush ].\n        destruct (f α) as [ | [ | X' ] ] eqn : Heq ; [ reflexivity | reflexivity | ].\n        split ; [ intro | trivial ].\n        clear - Wf_f Heq.\n        specialize (Wf_f α) ; rewrite Heq in Wf_f.\n        inversion Wf_f ; subst.\n        erewrite <- LV_bind_XEnv_dom ; eassumption.\n      }\n      {\n        apply 𝓗_Fun_nonexpansive ; repeat iintro.\n        - auto_contr.\n        - apply LV_bind_𝓣𝓵_aux ; auto.\n      }\n      { auto. }\n    * apply LV_bind_𝓣𝓵_aux ; auto.\n}\n\n{\ndestruct ℓ as [ | [ | X ] ] ; simpl ; [ iespecialize Hρ ; apply Hρ | auto_contr | ].\ndestruct (get X Ξ) as [ [T E] | ] eqn:HX.\n++ simpl in W ; rewrite HX in W.\n   eapply binds_LV_bind in HX ; rewrite HX.\n   apply 𝓣_Fun_Fix'_nonexpansive ; repeat iintro.\n   -- apply 𝓥_roll_unroll_iff ; auto.\n   -- apply 𝓤_roll_unroll_iff ; auto.\n++ apply get_none_inv in HX.\n   erewrite <- LV_bind_XEnv_dom in HX.\n   apply get_none in HX.\n   rewrite HX ; auto_contr.\n}\n\nQed.\n\nEnd section_LV_bind_aux.\n\n\nSection section_LV_bind.\nContext (n : nat).\nContext (EV LV LV' : Set).\nContext (Ξ : XEnv EV LV).\nContext (f : LV → lbl LV' ∅).\nContext (δ₁ δ₂ : EV → eff0) (δ : EV → IRel 𝓤_Sig).\nContext (ρ₁ ρ₂ : LV → lbl0) (ρ : LV → IRel 𝓣_Sig).\nContext (ρ₁' ρ₂' : LV' → lbl0) (ρ' : LV' → IRel 𝓣_Sig).\nContext (Hρ₁ : ∀ α, ρ₁ α = LV_bind_lbl ρ₁' (f α)).\nContext (Hρ₂ : ∀ α, ρ₂ α = LV_bind_lbl ρ₂' (f α)).\nContext (Hρ :\n  n ⊨ ∀ᵢ α ξ₁ ξ₂ v₁ v₂,\n      𝓣𝓵⟦ Ξ ⊢ lbl_var α ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ v₁ v₂ ⇔\n      𝓣𝓵⟦ (LV_bind_XEnv f Ξ) ⊢ f α ⟧ δ₁ δ₂ δ ρ₁' ρ₂' ρ' ξ₁ ξ₂ v₁ v₂\n).\nContext (Wf_f : ∀ α, wf_lbl (LV_bind_XEnv f Ξ) (f α)).\n\nHint Resolve lt'_wf.\n\nLemma LV_bind_𝓥 T ξ₁ ξ₂ v₁ v₂ :\nn ⊨\n  𝓥⟦ Ξ ⊢ T ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ v₁ v₂ ⇔\n  𝓥⟦ LV_bind_XEnv f Ξ ⊢ LV_bind_ty f T ⟧ δ₁ δ₂ δ ρ₁' ρ₂' ρ' ξ₁ ξ₂ v₁ v₂.\nProof.\napply LV_bind_𝓥_aux ; auto.\nQed.\n\nLemma LV_bind_𝓜 σ ℓ ξ₁ ξ₂ m₁ m₂ :\nn ⊨\n  𝓜⟦ Ξ ⊢ σ ^ ℓ ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ m₁ m₂ ⇔\n  𝓜⟦ LV_bind_XEnv f Ξ ⊢ (LV_bind_ms f σ) ^ (LV_bind_lbl f ℓ) ⟧ δ₁ δ₂ δ ρ₁' ρ₂' ρ' ξ₁ ξ₂ m₁ m₂.\nProof.\napply LV_bind_𝓜_aux ; auto.\nQed.\n\nLemma LV_bind_𝓤 E ξ₁ ξ₂ t₁ t₂ ψ L₁ L₂ :\nn ⊨\n  𝓤⟦ Ξ ⊢ E ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ψ L₁ L₂ ⇔\n  𝓤⟦ LV_bind_XEnv f Ξ ⊢ LV_bind_eff f E ⟧ δ₁ δ₂ δ ρ₁' ρ₂' ρ' ξ₁ ξ₂ t₁ t₂ ψ L₁ L₂.\nProof.\napply LV_bind_𝓤_aux ; auto.\nQed.\n\nHint Resolve LV_bind_𝓥 LV_bind_𝓤.\n\nLemma LV_bind_𝓣 T E ξ₁ ξ₂ t₁ t₂ :\nn ⊨\n  𝓣⟦ Ξ ⊢ T # E ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ⇔\n  𝓣⟦ LV_bind_XEnv f Ξ ⊢ (LV_bind_ty f T) # (LV_bind_eff f E) ⟧\n  δ₁ δ₂ δ ρ₁' ρ₂' ρ' ξ₁ ξ₂ t₁ t₂.\nProof.\napply 𝓣_Fun_Fix'_nonexpansive ; repeat iintro ; auto.\nQed.\n\nEnd section_LV_bind.\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_bind_LV.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.26009227797708206}}
{"text": "(** The implementation of rewriting hint databases\n **)\nRequire Import ExtLib.Structures.Functor.\nRequire Import MirrorCore.Lemma.\nRequire Import MirrorCore.RTac.CoreK.\nRequire Import MirrorCore.Lambda.Expr.\nRequire Import MirrorCore.Lambda.RewriteRelations.\nRequire Import MirrorCore.Polymorphic.\nRequire Import MirrorCore.Lambda.PolyInst.\nRequire Import MirrorCore.CTypes.CoreTypes.\nRequire Import MirrorCore.CTypes.CTypeUnify.\n\nSet Implicit Arguments.\nSet Strict Implicit.\nSet Universe Polymorphism.\n\nSet Suggest Proof Using.\n\nSection setoid.\n  Context {tsym : nat -> Set}.\n  Let typ := ctyp tsym.\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  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(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  Inductive HintRewrite : Type :=\n  | PRw_tc : forall {n : nat},\n      polymorphic@{Set} typ n (rw_lemma typ func Rbase) ->\n      polymorphic@{Set} typ n bool ->\n      CoreK.rtacK typ (expr typ func) ->\n      HintRewrite.\n\n  (* TODO - change to RewriteDb for consistency? *)\n  Definition RewriteHintDb : Type := list HintRewrite.\n\n  (* TODO(mario): this is duplicated in Respectful.v. We should find a long-term home for it *)\n  (* TODO(mario): convert this so it uses rw_concl instead of rw_lemma? *)\n  (* no-op typeclass, used to construct polymorphic types without constraints *)\n  Definition tc_any (n : nat) : polymorphic typ n bool :=\n    make_polymorphic (fun _ => true).\n\n  Definition with_typeclasses@{X} {T : Type@{X}} {n}\n             (tc : polymorphic@{Set} typ n bool) (pc : polymorphic@{X} typ n T)\n  : polymorphic@{X} typ n (option T) :=\n    make_polymorphic (fun args =>\n                        if inst tc args\n                        then Some (inst pc args)\n                        else None).\n\n  (* TODO(mario): end duplicated code *)\n\n  Definition rw_lemmaP (rw : rw_lemma typ func Rbase) : Prop :=\n    lemmaD (rw_conclD RbaseD) nil nil rw.\n\n  Definition RewriteHintOk (hr : HintRewrite) : Prop :=\n    match hr with\n    | PRw_tc plem tc tac =>\n      polymorphicD@{Set} (fun x => match x return Prop with\n                                | None => True\n                                | Some x => rw_lemmaP x\n                                end) (with_typeclasses tc plem) /\\\n      rtacK_sound tac\n    end.\n\n  Theorem PRw_tc_sound\n          {n : nat}\n          (plem : polymorphic typ n (rw_lemma typ func Rbase)) tc tac\n  : polymorphicD (fun x => match x with\n                        | None => True\n                        | Some x => rw_lemmaP x\n                        end) (with_typeclasses tc plem) ->\n    rtacK_sound tac ->\n    RewriteHintOk (PRw_tc plem tc tac).\n  Proof using.\n    clear. simpl. tauto.\n  Qed.\n\n  (** Convenience constructors for building lemmas that do not use\n   ** polymorphism.\n   **)\n  Definition Rw (rw : rw_lemma typ func Rbase) :=\n    @PRw_tc 0 rw true.\n\n  Theorem Rw_sound\n          (rw : rw_lemma typ func Rbase)\n          (tac : CoreK.rtacK typ (expr typ func))\n  : rw_lemmaP rw ->\n      CoreK.rtacK_sound tac ->\n      RewriteHintOk (Rw rw tac).\n  Proof using.\n    clear.\n    intros.\n    eapply PRw_tc_sound; eauto.\n  Qed.\n\n  (** polymorphic proper hint without typeclass constraints *)\n  Definition PRw {n : nat} (pc : polymorphic typ n (rw_lemma typ func Rbase)) :=\n    PRw_tc (n:=n) pc (tc_any n).\n\n  Theorem PRw_sound\n          {n : nat}\n          (plem : polymorphic typ n (rw_lemma typ func Rbase))\n          (tac : CoreK.rtacK typ (expr typ func))\n  : polymorphicD rw_lemmaP plem ->\n    CoreK.rtacK_sound tac ->\n    RewriteHintOk (PRw plem tac).\n  Proof using.\n    intros.\n    eapply PRw_tc_sound; eauto.\n    eapply polymorphicD_make_polymorphic. intros.\n    unfold tc_any.\n    rewrite inst_make_polymorphic.\n    unfold rw_lemmaP, lemmaD.\n    apply inst_sound.\n    simpl. assumption.\n  Qed.\n\n  Local Definition view_update := ctype_unify tsym.\n\n  Local Definition get_lemma su {n : nat}\n        (plem : polymorphic typ n (rw_lemma typ func Rbase))\n        (tc : polymorphic typ n bool)\n        (e : expr typ func)\n  : option (rw_lemma typ func Rbase) :=\n    match\n      get_inst tyVar su (fmap (fun x => x.(concl).(lhs)) plem) e\n    with\n    | None => None\n    | Some args =>\n      if (inst tc args)\n      then Some (inst plem args)\n      else None\n    end.\n\n  Fixpoint CompileHints su (hints : RewriteHintDb)\n           (e : expr typ func)\n           (r : R)\n    : list (rw_lemma typ func Rbase * rtacK typ (expr typ func)) :=\n    match hints with\n    | nil => nil\n    | PRw_tc plem tc tac :: hints =>\n      match get_lemma su plem tc e with\n      | None => CompileHints su hints e r\n      | Some lem => (lem, tac) :: CompileHints su hints e r\n      end\n    end.\n\n  Definition hints_sound\n             (hints : expr typ func -> R ->\n                      list (rw_lemma typ func Rbase * CoreK.rtacK typ (expr typ func)))\n  : Prop :=\n    (forall r e,\n        Forall (fun lt =>\n                  (forall tus tvs t eD,\n                      lambda_exprD tus tvs t e = Some eD ->\n                      Lemma.lemmaD (rw_conclD RbaseD) nil nil (fst lt)) /\\\n                  CoreK.rtacK_sound (snd lt)) (hints e r)).\n\n\n  Definition RewriteHintDbOk (db : RewriteHintDb) : Prop :=\n    Forall RewriteHintOk db.\n\n  Theorem CompileHints_sound\n  : forall su db,\n      RewriteHintDbOk db ->\n      hints_sound (CompileHints su db).\n  Proof using.\n    induction db; intros; simpl.\n    { unfold hints_sound. intros. constructor. }\n    { inversion H; subst; clear H.\n      specialize (IHdb H3). clear H3.\n      unfold hints_sound. intros.\n      destruct a.\n      destruct (get_lemma su p p0) eqn:Hgl; [|eapply IHdb].\n      constructor; [|eauto].\n      unfold RewriteHintOk in *. destruct H2.\n      split; [|eauto].\n      intros.\n      unfold get_lemma in *.\n      Require Import MirrorCore.Util.Forwardy.\n      forwardy.\n      eapply inst_sound with (v:=y) in H.\n      unfold with_typeclasses in H.\n      rewrite inst_make_polymorphic in H.\n      destruct (inst p0 y); [|congruence].\n      inversion H3; clear H3; subst.\n      simpl in *. clear H2.\n      red in H. tauto. }\n  Qed.\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/HintDbs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2600265417359167}}
{"text": "Require Import FP.Data.Function.\nRequire Import FP.Data.String.\nRequire Import FP.Data.Ascii.\nRequire Import FP.Data.N.\nRequire Import FP.Data.NStructures.\nRequire Import FP.Structures.Show.\nRequire Import FP.Structures.Monoid.\nRequire Import FP.Structures.Injection.\nRequire Import FP.Structures.Comonad.\nRequire Import FP.Structures.Foldable.\nRequire Import FP.Structures.Monad.\nRequire Import FP.Data.PrettyI.\n\nImport MonoidNotation.\nImport CharNotation.\nImport ComonadNotation.\nImport FunctionNotation.\n\nSection Show.\n  Section string_show.\n    Variable (R:Type) (SR:ShowResult R).\n\n    Definition string_show (s:string) : R :=\n         raw_char \"\"\"\"%char\n      ** raw_string s\n      ** raw_char \"\"\"\"%char.\n  End string_show.\n\n  Global Instance string_Show : Show string := { show := string_show }.\nEnd Show.\n\nSection Monoid.\n  Global Instance string_Monoid : Monoid string :=\n    { monoid_times := String.append\n    ; monoid_unit := EmptyString\n    }.\nEnd Monoid.\n\nSection Injection.\n  Global Instance string_ascii_HasInjection : HasInjection ascii string :=\n    { inject c := String c EmptyString }.\nEnd Injection.\n\nSection Foldable.\n  Fixpoint string_cofold {w} {W:Comonad w} {B} (f:ascii -> w B -> B) (bW:w B) (t:string) : B :=\n    match t with\n    | EmptyString => coret bW\n    | String a t =>\n        let bW := codo bW => string_cofold f bW t\n        in f a bW\n    end.\n  Global Instance string_Foldable : Foldable ascii string :=\n    { cofold := @string_cofold }.\nEnd Foldable.\n\nSection Buildable.\n  Definition string_mbuild {m} {M:Monad m} (f:forall {C}, (ascii -> C -> C) -> C -> m C) : m string :=\n    f String EmptyString.\n  Global Instance string_Buildable : Buildable ascii string :=\n    { mbuild := @string_mbuild }.\nEnd Buildable.\n\nInstance N_Pretty : Pretty N := { pretty := text_d '.' show }.", "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/StringStructures.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.26002654173591666}}
{"text": "(** * Transfer [Context] across an injection *)\nRequire Import Crypto.Reflection.Named.Syntax.\n\nSection language.\n  Context {base_type_code Name1 Name2 : Type}\n          (f : Name2 -> Name1)\n          (f_inj : forall x y, f x = f y -> x = y)\n          {var : base_type_code -> Type}.\n\n  Definition ContextOn (Ctx : Context Name1 var) : Context Name2 var\n    := {| ContextT := Ctx;\n          lookupb ctx n t := lookupb ctx (f n) t;\n          extendb ctx n t v := extendb ctx (f n) v;\n          removeb ctx n t := removeb ctx (f n) t;\n          empty := empty |}.\nEnd language.\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_vm_compute/src/Reflection/Named/ContextOn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2600265351284482}}
{"text": "Require Import StlcEqui.CanForm.\nRequire Import StlcEqui.SpecEvaluation.\nRequire Import StlcEqui.SpecTyping.\nRequire Import StlcEqui.LemmasTyping.\nRequire Import StlcEqui.LemmasProgramContext.\n\nLocal Ltac crush :=\n  intros; cbn in * |-;\n  repeat\n    (cbn;\n     repeat crushStlcSyntaxMatchH;\n     repeat crushDbSyntaxMatchH;\n     subst*);\n  try discriminate;\n  eauto with eval.\n\nLtac progressH :=\n  match goal with\n    | [ H: ⟪ _ : _ r∈ empty ⟫ |- _         ] => inversion H\n    | [ H: _ ∨ _             |- _         ] => destruct H\n    | [ H: True              |- _         ] => clear H\n    | [ H: False             |- _         ] => inversion H\n    | [                      |- False ∨ _ ] => right\n    | [                      |- True ∨ _  ] => left; auto\n  end;\n  stlcCanForm.\n\n#[export]\nHint Constructors eval : pctx.\n#[export]\nHint Constructors eval₀ : pctx.\n#[export]\nHint Extern 20 (Value _) => cbn : pctx.\n#[export]\nHint Extern 20 (ECtx _) => cbn : pctx.\n\n(* Lemma local_progress {t U} (wt: ⟪ empty ⊢ t : U ⟫) : *)\n(*   Value t ∨ *)\n(*   ∃ C t₀ t₀', *)\n(*     t = pctx_app t₀ C ∧ *)\n(*     t₀ -->₀ t₀' ∧ *)\n(*     ECtx C. *)\n(* Proof. *)\n(*   depind wt; *)\n(*   repeat *)\n(*     (try progressH; cbn in *; destruct_conjs; subst); *)\n(*     eauto 20 with pctx; *)\n(*     try (exists phole; cbn; eauto 20 with pctx; fail). *)\n(* Qed. *)\n\n(* Lemma progress {t U} (wt: ⟪ empty ⊢ t : U ⟫) : *)\n(*   Value t ∨ *)\n(*   ∃ t', t --> t'. *)\n(* Proof. *)\n(*   destruct (local_progress wt); destruct_conjs; *)\n(*     subst; eauto using eval. *)\n(* Qed. *)\n\nLemma context_replacement {Γ C t t' T}\n  (hyp: ∀ Γ' T', ValidEnv Γ' -> ⟪ Γ' e⊢ t : T' ⟫ → ⟪ Γ' e⊢ t' : T' ⟫) :\n  ValidEnv Γ ->\n    ⟪ Γ e⊢ pctx_app t C : T ⟫ →\n    ⟪ Γ e⊢ pctx_app t' C : T ⟫.\nProof.\n  intros vΓ wt; depind wt; crushTyping;\n    induction C; crush; eauto with typing.\nQed.\n\nLemma preservation₀ {t t'} (r : t -->₀ t') :\n  ∀ {Γ τ}, ValidEnv Γ -> ⟪ Γ e⊢ t : τ ⟫ → ⟪ Γ e⊢ t' : τ ⟫.\nProof.\n  induction r;\n    eauto using context_replacement;\n    crushTyping.\n  - refine (typed_terms_are_valid _ _ _ H6).\n    eauto with tyvalid.\n  - now eapply ValidTy_invert_arr in H4.\n  - crushTyping.\n    eapply (WtEq _ (tyeq_symm H2)); try assumption.\n    now eapply ValidTy_invert_arr in H4.\n  - now refine (typed_terms_are_valid _ _ _ H4).\n  - now eapply ValidTy_invert_prod in H2.\n  - now refine (typed_terms_are_valid _ _ _ H3).\n  - now eapply ValidTy_invert_prod in H2.\n  - crushTyping.\n    now refine (typed_terms_are_valid _ _ _ H6).\n    now eapply ValidTy_invert_sum in H1.\n  - crushTyping.\n    now refine (typed_terms_are_valid _ _ _ H6).\n    now eapply ValidTy_invert_sum in H1.\nQed.\n\nLemma preservation {t t'} (r: t --> t') :\n  ∀ {Γ τ}, ValidEnv Γ -> ⟪ Γ e⊢ t : τ ⟫ → ⟪ Γ e⊢ t' : τ ⟫.\nProof.\n  induction r.\n  eauto using context_replacement, preservation₀.\nQed.\n\nLemma preservation_star {t t'} (r: t -->* t') :\n  ∀ {Γ τ}, ValidEnv Γ -> ⟪ Γ e⊢ t : τ ⟫ → ⟪ Γ e⊢ t' : τ ⟫.\nProof.\n  induction r;\n  eauto using preservation.\nQed.\n\nLemma termination_value {t τ} (wt: ⟪ empty e⊢ t : τ ⟫) :\n  t⇓ → ∃ t', t -->* t' ∧ Value t'.\nProof.\n  destruct 1; crush.\nQed.\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/StlcEqui/TypeSafety.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2600265285209796}}
{"text": "(** Interpretation of endpoints in 1-types *)\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\n\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.Groupoids.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Core.\n\nRequire Import UniMath.Bicategories.Core.Bicat.\nImport Bicat.Notations.\nRequire Import UniMath.Bicategories.Core.Invertible_2cells.\nRequire Import UniMath.Bicategories.Core.Unitors.\nRequire Import UniMath.Bicategories.Core.Univalence.\nRequire Import UniMath.Bicategories.DisplayedBicats.DispBicat.\nImport DispBicat.Notations.\nRequire Import UniMath.Bicategories.DisplayedBicats.DispUnivalence.\nRequire Import UniMath.Bicategories.DisplayedBicats.Examples.Algebras.\nRequire Import UniMath.Bicategories.DisplayedBicats.Examples.Add2Cell.\nRequire Import UniMath.Bicategories.DisplayedBicats.Examples.DisplayedCatToBicat.\nRequire Import UniMath.Bicategories.DisplayedBicats.Examples.DispDepProd.\nRequire Import UniMath.Bicategories.DisplayedBicats.Examples.FullSub.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.Base.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.Map1Cells.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.Map2Cells.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.Identitor.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.Compositor.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.PseudoFunctorBicat.\nRequire Import UniMath.Bicategories.PseudoFunctors.PseudoFunctor.\nImport PseudoFunctor.Notations.\nRequire Import UniMath.Bicategories.PseudoFunctors.Examples.Projection.\nRequire Import UniMath.Bicategories.PseudoFunctors.Examples.Constant.\nRequire Import UniMath.Bicategories.PseudoFunctors.Examples.Composition.\nRequire Import UniMath.Bicategories.Transformations.PseudoTransformation.\nRequire Import UniMath.Bicategories.Transformations.Examples.Whiskering.\nRequire Import UniMath.Bicategories.Core.Examples.OneTypes.\n\nRequire Import prelude.all.\nRequire Import signature.hit_signature.\nRequire Import algebra.one_types_polynomials.\nRequire Import algebra.one_types_endpoints.\n\nLocal Open Scope cat.\n\nDefinition sem_homot_endpoint_one_types\n           {A : poly_code}\n           {J : UU}\n           {S : J → poly_code}\n           {l : ∏ (j : J), endpoint A (S j) I}\n           {r : ∏ (j : J), endpoint A (S j) I}\n           {Q : poly_code}\n           {TR : poly_code}\n           {al ar : endpoint A Q TR}\n           {T : poly_code}\n           {sl sr : endpoint A Q T}\n           (p : homot_endpoint l r al ar sl sr)\n           (X : total_bicat (disp_alg_bicat (⟦ A ⟧)))\n           (pX : ∏ (i : J),\n                 sem_endpoint_one_types (l i) X\n                 ~\n                 sem_endpoint_one_types (r i) X)\n           (z : poly_act Q (pr1 X : one_type))\n           (p_arg : sem_endpoint_one_types al X z = sem_endpoint_one_types ar X z)\n  : sem_endpoint_one_types sl X z = sem_endpoint_one_types sr X z\n  := sem_homot_endpoint_UU p (pr1 X : one_type) (pr2 X) pX z p_arg.\n\n(** Bicategory of prealgebras *)\nDefinition hit_prealgebra_one_types\n           (Σ : hit_signature)\n  : bicat\n  := total_bicat (disp_alg_bicat (⟦ point_constr Σ ⟧)).\n\n(** Projections and builders of prealgebras *)\nSection HITPreAlgebraProjections.\n  Context {Σ : hit_signature}\n          (X : hit_prealgebra_one_types Σ).\n\n  Definition prealg_carrier\n    : one_type\n    := pr1 X.\n\n  Definition prealg_constr\n    : poly_act (point_constr Σ) prealg_carrier → prealg_carrier\n    := pr2 X.\nEnd HITPreAlgebraProjections.\n\nArguments prealg_constr {_ _} _.\n\nDefinition make_hit_prealgebra\n           {Σ : hit_signature}\n           (X : UU)\n           (HX : isofhlevel 3 X)\n           (f : poly_act (point_constr Σ) X → X)\n  : hit_prealgebra_one_types Σ.\nProof.\n  use tpair.\n  - use make_one_type.\n    + exact X.\n    + exact HX.\n  - exact f.\nDefined.\n\nDefinition preserves_point\n           {Σ : hit_signature}\n           {X Y : hit_prealgebra_one_types Σ}\n           (f : prealg_carrier X → prealg_carrier Y)\n  : UU\n  := ∏ (x : poly_act (point_constr Σ) (prealg_carrier X)),\n     f (prealg_constr x)\n     =\n     prealg_constr (poly_map (point_constr Σ) f x).\n\nSection HITPreAlgebraMorProjections.\n  Context {Σ : hit_signature}\n          {X Y : hit_prealgebra_one_types Σ}\n          (f : X --> Y).\n\n  Definition prealg_map_carrier\n    : prealg_carrier X → prealg_carrier Y\n    := pr1 f.\n\n  Definition prealg_map_commute\n    : preserves_point prealg_map_carrier\n    := pr12 f.\nEnd HITPreAlgebraMorProjections.\n\nDefinition make_hit_prealgebra_mor\n           {Σ : hit_signature}\n           {X Y : hit_prealgebra_one_types Σ}\n           (f : prealg_carrier X → prealg_carrier Y)\n           (Hf : preserves_point f)\n  : X --> Y.\nProof.\n  use tpair.\n  - exact f.\n  - use make_invertible_2cell.\n    + exact Hf.\n    + apply one_type_2cell_iso.\nDefined.\n\n(** Path Algebras for a HIT signature *)\nDefinition hit_path_algebra_disp_one_types\n           (Σ : hit_signature)\n  : disp_bicat (hit_prealgebra_one_types Σ)\n  := disp_depprod_bicat\n       (path_label Σ)\n       (λ j, add_cell_disp_cat\n               _ _ _\n               (sem_endpoint_one_types (path_left Σ j))\n               (sem_endpoint_one_types (path_right Σ j))).\n\nDefinition hit_path_algebra_one_types\n           (Σ : hit_signature)\n  : bicat\n  := total_bicat (hit_path_algebra_disp_one_types Σ).\n\n(** Projections *)\nSection HITPathAlgebraProjections.\n  Context {Σ : hit_signature}\n          (X : hit_path_algebra_one_types Σ).\n\n  Definition path_alg_carrier\n    : one_type\n    := prealg_carrier (pr1 X).\n\n  Definition path_alg_constr\n    : poly_act (point_constr Σ) path_alg_carrier → path_alg_carrier\n    := @prealg_constr _ (pr1 X).\n\n  Definition path_alg_path\n             (j : path_label Σ)\n             (x : poly_act (path_source Σ j) path_alg_carrier)\n    : sem_endpoint_one_types (path_left Σ j) (pr1 X) x\n      =\n      sem_endpoint_one_types (path_right Σ j) (pr1 X) x\n    := pr2 X j x.\nEnd HITPathAlgebraProjections.\n\nArguments path_alg_constr {_ _} _.\n\nDefinition make_hit_path_algebra\n           {Σ : hit_signature}\n           (X : hit_prealgebra_one_types Σ)\n           (pX : ∏ (j : path_label Σ)\n                   (x : poly_act (path_source Σ j) (prealg_carrier X)),\n                 sem_endpoint_one_types (path_left Σ j) _ x\n                 =\n                 sem_endpoint_one_types (path_right Σ j) _ x)\n  : hit_path_algebra_one_types Σ.\nProof.\n  use tpair.\n  - exact X.\n  - exact pX.\nDefined.\n\nDefinition preserves_path\n           {Σ : hit_signature}\n           {X Y : hit_path_algebra_one_types Σ}\n           (f : pr1 X --> pr1 Y)\n           (Hf : preserves_point (pr1 f))\n  : UU\n  := ∏ (j : path_label Σ)\n       (x : poly_act (path_source Σ j) (path_alg_carrier X)),\n     maponpaths (prealg_map_carrier f) (path_alg_path X j x)\n     @ sem_endpoint_UU_natural (path_right Σ j) Hf x\n     =\n     sem_endpoint_UU_natural (path_left Σ j) Hf x\n     @ path_alg_path Y j (poly_map (path_source Σ j) _ x).\n  \nSection HITPathAlgebraMorProjections.\n  Context {Σ : hit_signature}\n          {X Y : hit_path_algebra_one_types Σ}\n          (f : X --> Y).\n\n  Definition path_alg_map_carrier\n    : path_alg_carrier X → path_alg_carrier Y\n    := prealg_map_carrier (pr1 f).\n\n  Definition path_alg_map_commute\n    : ∏ (x : poly_act (point_constr Σ) (path_alg_carrier X)),\n      path_alg_map_carrier (path_alg_constr x)\n      =\n      path_alg_constr (poly_map (point_constr Σ) path_alg_map_carrier x)\n    := prealg_map_commute (pr1 f).\n\n  Definition path_alg_map_path\n    : preserves_path (pr1 f) path_alg_map_commute\n    := λ j x, eqtohomot (pr2 f j) x.\nEnd HITPathAlgebraMorProjections.\n\nDefinition make_hit_path_alg_map\n           {Σ : hit_signature}\n           {X Y : hit_path_algebra_one_types Σ}\n           (f : pr1 X --> pr1 Y)\n           (pf : preserves_path _ (prealg_map_commute f))\n  : X --> Y\n  := f ,, λ i, funextsec _ _ _ (pf i).\n\n(** HIT algebras *)\nDefinition is_hit_algebra_one_types\n           (Σ : hit_signature)\n           (X : hit_path_algebra_one_types Σ)\n  : UU\n  := ∏ (j : homot_label Σ)\n       (x : ⟦ homot_point_arg Σ j ⟧ (pr11 X) : one_type)\n       (p : sem_endpoint_one_types (homot_path_arg_left Σ j) (pr1 X) x\n            =\n            sem_endpoint_one_types (homot_path_arg_right Σ j) (pr1 X) x),\n     sem_homot_endpoint_one_types\n       (homot_left_path Σ j) (pr1 X) (pr2 X) x p\n     =\n     sem_homot_endpoint_one_types\n       (homot_right_path Σ j) (pr1 X) (pr2 X) x p.\n\nDefinition isaprop_is_hit_algebra_one_types\n           (Σ : hit_signature)\n           (X : hit_path_algebra_one_types Σ)\n  : isaprop (is_hit_algebra_one_types Σ X).\nProof.\n  do 3 (use impred ; intro).\n  exact (one_type_isofhlevel (pr11 X) _ _ _ _).\nDefined.\n\nDefinition hit_algebra_one_types\n           (Σ : hit_signature)\n  : bicat\n  := fullsubbicat (hit_path_algebra_one_types Σ) (is_hit_algebra_one_types Σ).\n\n(** Projections *)\nSection HITAlgebraProjections.\n  Context {Σ : hit_signature}\n          (X : hit_algebra_one_types Σ).\n\n  Definition alg_carrier\n    : UU\n    := path_alg_carrier (pr1 X).\n\n  Definition alg_constr\n    : poly_act (point_constr Σ) alg_carrier → alg_carrier\n    := @path_alg_constr _ (pr1 X).\n\n  Definition alg_path\n             (j : path_label Σ)\n             (x : poly_act (path_source Σ j) alg_carrier)\n    : sem_endpoint_one_types (path_left Σ j) _ x\n      =\n      sem_endpoint_one_types (path_right Σ j) _ x\n    := path_alg_path (pr1 X) j x.\n  \n  Definition alg_homot\n    : is_hit_algebra_one_types Σ (pr1 X)\n    := pr2 X.\nEnd HITAlgebraProjections.\n\nDefinition make_algebra\n           {Σ : hit_signature}\n           (X : hit_path_algebra_one_types Σ)\n           (hX : is_hit_algebra_one_types Σ X)\n  : hit_algebra_one_types Σ\n  := X ,, hX.\n\n(** Projections of algebra maps *)\nSection HITAlgebraMapProjections.\n  Context {Σ : hit_signature}\n          {X Y : hit_algebra_one_types Σ}\n          (f : X --> Y).\n\n  Definition alg_map_carrier\n    : alg_carrier X → alg_carrier Y\n    := path_alg_map_carrier (pr1 f).\n\n  Definition alg_map_commute\n    : preserves_point alg_map_carrier\n    := path_alg_map_commute (pr1 f).\n\n  Definition alg_map_path\n    : preserves_path _ alg_map_commute\n    := path_alg_map_path (pr1 f).\nEnd HITAlgebraMapProjections.\n\nDefinition make_algebra_map\n           {Σ : hit_signature}\n           {X Y : hit_algebra_one_types Σ}\n           (f : pr1 X --> pr1 Y)\n  : X --> Y\n  := f ,, tt.\n\nDefinition is_algebra_2cell\n           {Σ : hit_signature}\n           {X Y : hit_algebra_one_types Σ}\n           {f g : X --> Y}\n           (α : alg_map_carrier f ~ alg_map_carrier g)\n  : UU\n  := ∏ (z : poly_act (point_constr Σ) (alg_carrier X)),\n     α (alg_constr X z)\n     @ alg_map_commute g z\n     =\n     alg_map_commute f z\n     @ maponpaths (alg_constr Y) (poly_homot (point_constr Σ) α z).\n\n(** Projections of algebra 2-cells *)\nSection HITAlgebraCellProjections.\n  Context {Σ : hit_signature}\n          {X Y : hit_algebra_one_types Σ}\n          {f g : X --> Y}\n          (α : f ==> g).\n\n  Definition alg_2cell_carrier\n    : alg_map_carrier f ~ alg_map_carrier g\n    := pr111 α.\n\n  Definition alg_2cell_commute\n    : is_algebra_2cell alg_2cell_carrier\n    := eqtohomot (pr211 α).\nEnd HITAlgebraCellProjections.\n\n(** Equality of algebra 2-cells *)\nDefinition algebra_2cell_eq\n           {Σ : hit_signature}\n           {X Y : hit_algebra_one_types Σ}\n           {f g : X --> Y}\n           {α β : f ==> g}\n           (p : alg_2cell_carrier α ~ alg_2cell_carrier β)\n  : α = β.\nProof.\n  use subtypePath.\n  { intro ; apply isapropunit. }\n  use subtypePath.\n  { intro ; use impred ; intro ; apply isapropunit. }\n  use subtypePath.\n  { intro ; apply one_types. }\n  use funextsec.\n  exact p.\nQed.\n\nDefinition alg_2cell_eq_component\n           {Σ : hit_signature}\n           {X Y : hit_algebra_one_types Σ}\n           {f g : X --> Y}\n           {α β : f ==> g}\n           (p : α = β)\n  : alg_2cell_carrier α ~ alg_2cell_carrier β.\nProof.\n  exact (eqtohomot (maponpaths (λ z, pr111 z) p)).\nQed.\n\n(** Builder of 2-cells of algebras *)\nDefinition make_algebra_2cell\n           {Σ : hit_signature}\n           {X Y : hit_algebra_one_types Σ}\n           {f g : X --> Y}\n           (α : alg_map_carrier f ~ alg_map_carrier g)\n           (Hα : is_algebra_2cell α)\n  : f ==> g.\nProof.\n  simple refine (((α ,, _) ,, λ _, tt) ,, tt).\n  abstract (use funextsec ; exact Hα).\nDefined.\n\n(** Univalence of the bicategory of algebras *)\nDefinition is_univalent_2_hit_algebra_one_types\n           (Σ : hit_signature)\n  : is_univalent_2 (hit_algebra_one_types Σ).\nProof.\n  use is_univalent_2_fullsubbicat.\n  - use total_is_univalent_2.\n    + split.\n      * use disp_depprod_univalent_2_0.\n        ** use total_is_univalent_2_1.\n           *** apply one_types_is_univalent_2_1.\n           *** apply disp_alg_bicat_univalent_2_1.\n        ** intro i.\n           apply add_cell_disp_cat_univalent_2_1.\n        ** intro i.\n           use add_cell_disp_cat_univalent_2_0.\n           *** apply one_types_is_univalent_2_1.\n           *** apply disp_alg_bicat_univalent_2_1.\n      * use disp_depprod_univalent_2_1.\n        intro i.\n        apply add_cell_disp_cat_univalent_2_1.\n    + split.\n      * use total_is_univalent_2_0.\n        ** apply one_types_is_univalent_2_0.\n        ** apply disp_alg_bicat_univalent_2_0.\n           apply one_types_is_univalent_2_1.\n      * use total_is_univalent_2_1.\n        ** apply one_types_is_univalent_2_1.\n        ** apply disp_alg_bicat_univalent_2_1.\n  - exact (isaprop_is_hit_algebra_one_types Σ).\nDefined.\n\nDefinition hit_prealg_is_invertible_2cell_one_type\n           (Σ : hit_signature)\n           {X Y : hit_prealgebra_one_types Σ}\n           {f g : X --> Y}\n           (α : f ==> g)\n  : is_invertible_2cell α.\nProof.\n  use is_invertible_disp_to_total.\n  use tpair.\n  - apply one_type_2cell_iso.\n  - exact (disp_locally_groupoid_alg\n             (⟦ point_constr Σ ⟧)\n             (pr1 X) (pr1 Y)\n             (pr1 f) (pr1 g)\n             (make_invertible_2cell\n                (one_type_2cell_iso _ _ _ _ (pr1 α)))\n             (pr2 X) (pr2 Y)\n             (pr2 f) (pr2 g)\n             (pr2 α)).\nDefined.\n\nDefinition hit_path_alg_is_invertible_2cell_one_type\n           (Σ : hit_signature)\n           {X Y : hit_path_algebra_one_types Σ}\n           {f g : X --> Y}\n           (α : f ==> g)\n  : is_invertible_2cell α.\nProof.\n  use is_invertible_disp_to_total.\n  use tpair.\n  - apply hit_prealg_is_invertible_2cell_one_type.\n  - exact (disp_locally_groupoid_depprod\n             (path_label Σ)\n             (λ i, add_cell_disp_cat _ _ _ _ _)\n             (λ i, disp_locally_groupoid_add_cell _ _ _ _ _)\n             (pr1 X) (pr1 Y)\n             (pr1 f) (pr1 g)\n             (make_invertible_2cell\n                (hit_prealg_is_invertible_2cell_one_type Σ (pr1 α)))\n             (pr2 X) (pr2 Y)\n             (pr2 f) (pr2 g)\n             (pr2 α)).\nDefined.\n\nDefinition hit_alg_is_invertible_2cell_one_type\n           (Σ : hit_signature)\n           {X Y : hit_algebra_one_types Σ}\n           {f g : X --> Y}\n           (α : f ==> g)\n  : is_invertible_2cell α.\nProof.\n  apply bicat_is_invertible_2cell_to_fullsub_is_invertible_2cell.\n  apply hit_path_alg_is_invertible_2cell_one_type.\nDefined.\n", "meta": {"author": "UniMath", "repo": "GrpdHITs", "sha": "cb5a9af84400eb770392632eb74860d4ebad9306", "save_path": "github-repos/coq/UniMath-GrpdHITs", "path": "github-repos/coq/UniMath-GrpdHITs/GrpdHITs-cb5a9af84400eb770392632eb74860d4ebad9306/code/algebra/one_types_homotopies.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442250928250376, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.25998789380878007}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.msl.iter_sepcon.\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*)\nLemma body_malloc_small:  semax_body MF_Vprog MF_Gprog f_malloc_small malloc_small_spec.\nProof. \nstart_function. \nrewrite <- seq_assoc.  \nforward_call n. (*! t'1 = size2bin(nbytes) !*)\n(*rep_lia.*)\nforward. (*! b = t'1 !*)\nset (b:=size2binZ n).\nassert (Hprednat: forall m, m > 0 -> Nat.pred(Z.to_nat m) = Z.to_nat(Z.pred m))\n  by (intros; rewrite Z2Nat.inj_pred; reflexivity).\nassert_PROP(Zlength rvec = BINS) as Hlrvec. { \n  unfold mem_mgr_R; Intros bins idxs lens.\n  entailer!. autorewrite with sublist in *. rep_lia.\n}\n(* Now we split cases on whether success is guaranteed. \n   This which simplifies establishing the different cases in postcondition, \n   but comes at the cost of two symbolic executions. *)\ndestruct (guaranteed rvec n) eqn: Hguar. \n\n* (*+ case guaranteed *) \nassert (Hb: 0 <= b < BINS) by (apply (claim2 n); lia).\nrewrite (mem_mgr_split_R gv b rvec) by apply Hb.\nIntros bins idxs lens.\nfreeze [1; 3] Otherlists.\ndeadvars!.\napply is_guaranteed in Hguar.\nassert (0 < Znth b lens)%nat. { \n  subst b lens. autorewrite with sublist.\n  change 0%nat with (Z.to_nat 0%Z).\n  apply Z2Nat.inj_lt; rep_lia. \n}\nassert_PROP (Znth b bins <> nullval) as Hnonnull. {\n  sep_apply (mmlist_ne_nonnull (bin2sizeZ b) (Znth b lens) (Znth b bins)).\n  entailer!.\n}\nforward. (*! p = bin[b] !*)\nforward_if( (*! if p == null *)\n     PROP()\n     LOCAL(temp _p (Znth b bins); temp _b (Vint (Int.repr b)); gvars gv)\n     SEP(FRZL Otherlists; TT; \n         data_at Ews (tarray (tptr tvoid) BINS) bins (gv _bin);\n         mmlist (bin2sizeZ b) (Znth b lens) (Znth b bins) nullval)). \n  + (* branch p==NULL *) contradiction.\n  + (* branch p<>NULL *)\n    forward. (*! skip *)\n    entailer!.\n  + (* after if: unroll and pop mmlist *)\n    set (p:=Znth b bins) in *. (* TODO clumsy, just to reuse old steps *)\n    set (len:=Z.of_nat(Znth b lens)) in *.\n    set (s:=bin2sizeZ b).  \n    assert_PROP (len > 0).\n    { replace (Znth b lens) with (Z.to_nat len);\n        try (subst len; rewrite nat_of_Z_eq; reflexivity).\n      sep_apply (mmlist_ne_len s len p nullval); auto. entailer!.  }\n    assert_PROP (isptr p).\n    { entailer!. unfold nullval in *.\n      match goal with | HA: p <> _ |- _ => simpl in HA end. (* not Archi.ptr64 *)\n      unfold is_pointer_or_null in *. simpl in *.\n      destruct p; try contradiction; simpl.\n      subst. contradiction. auto. }\n    replace (Znth b lens) with (Z.to_nat len); try rep_lia.\n    rewrite (mmlist_unroll_nonempty s (Z.to_nat len) p);\n      try (subst len; rewrite nat_of_Z_eq; assumption).\n    Intros q.\n    assert_PROP(force_val (sem_cast_pointer p) = field_address (tptr tvoid) [] p).\n    { entailer!. unfold field_address. if_tac. normalize. contradiction. }\n    forward. (*! q = *p !*)\n    forward. (*! bin[b]=q !*)\n    (* prepare token+chunk to return *)\n    deadvars!.\n    thaw Otherlists.  \n    sep_apply (to_malloc_token'_and_block n p q s); try rep_lia.\n    (* refold invariant *)\n    assert (Hrveclen: Zlength rvec = BINS) by\n        (subst lens; rewrite Zlength_map in H1; rep_lia). \n    set (rvec':= add_resvec rvec b (-1)).\n    set (lens':= map Z.to_nat rvec').\n    set (bins':=(upd_Znth b bins (force_val (sem_cast_pointer q)))).\n    assert (Hlens: Nat.pred (Z.to_nat len) = (Znth b lens')).\n    { unfold lens'. \n      unfold len.\n      rewrite nat_of_Z_eq.\n      unfold rvec'.\n      rewrite Znth_map; try (rewrite Zlength_add_resvec; rep_lia).\n      unfold add_resvec.\n      simple_if_tac' Htest.\n      -- rewrite upd_Znth_same; try rep_lia.\n         replace (Znth b lens) with (Z.to_nat(Znth b rvec))\n           by (subst lens; rewrite Znth_map; lia).\n         rewrite Hprednat. rep_lia. unfold b; lia.\n      --  bdestruct (Zlength rvec =? BINS); [ | rep_lia].\n            bdestruct (0 <=? b); [ | rep_lia].\n            bdestruct (b <? BINS); [ |rep_lia]. \n            inv Htest.\n    } \n    rewrite Hlens.\n    change s with (bin2sizeZ b).\n    forward. (*! return p !*) \n    set (lens := map Z.to_nat rvec).\n    Exists p. entailer!. \n    unfold mem_mgr_R. \n    Exists bins'. \n    set (idxs:= (map Z.of_nat (seq 0 (Z.to_nat BINS)))).\n    Exists idxs. \n    Exists lens'.\n    cancel.\n    entailer!.\n    { split.\n      subst lens'. subst rvec'. rewrite Zlength_map. rewrite Zlength_add_resvec. rep_lia. \n      apply add_resvec_no_neg; auto.\n      rep_lia.\n    }\n    (* fold mem_mgr *)\n    assert (Zlength lens = BINS) by (unfold lens; rewrite Zlength_map; rep_lia). \n    assert (Zlength lens' = BINS) by (unfold lens'; rewrite Zlength_map; \n                                      unfold rvec'; rewrite Zlength_add_resvec; rep_lia).\n    assert (Zlength bins' = BINS) by \n        (replace (Zlength bins') with BINS by auto; reflexivity).\n    assert (Zlength idxs = BINS) by auto.\n    assert (Hbins': sublist 0 b bins' = sublist 0 b bins) by\n      (unfold bins'; rewrite sublist_upd_Znth_l; try reflexivity; try rep_lia).\n    assert (Hlens': sublist 0 b lens' = sublist 0 b lens). \n    { unfold lens'; unfold lens; unfold rvec'.\n      do 2 rewrite sublist_map; f_equal.\n      unfold add_resvec.\n      simple_if_tac''; auto.\n      rewrite sublist_upd_Znth_l; try rep_lia; auto.  }      \n    assert (Hbins'': sublist (b+1) BINS bins' = sublist (b+1) BINS bins) by\n      (unfold bins'; rewrite sublist_upd_Znth_r; try reflexivity; try rep_lia).\n    assert (Hlens'': sublist (b+1) BINS lens' = sublist (b+1) BINS lens). {\n      unfold lens'. unfold lens. unfold rvec'. unfold add_resvec.\n      simple_if_tac''; auto. do 2 rewrite sublist_map; try rep_lia.\n      rewrite sublist_upd_Znth_r; auto; try rep_lia.\n      }\n    assert (Hsub:  sublist 0 b (zip3 lens bins idxs)\n                 = sublist 0 b (zip3 lens' bins' idxs)).\n    { repeat rewrite sublist_zip3; try rep_lia.\n      rewrite Hbins'. rewrite Hlens'.  reflexivity.  }\n    assert (Hsub':  sublist (b + 1) BINS (zip3 lens bins idxs)  \n                  = sublist (b + 1) BINS (zip3 lens' bins' idxs)).\n    { repeat rewrite sublist_zip3; try rep_lia.\n      rewrite Hbins''. rewrite Hlens''.  reflexivity. }\n    rewrite Hsub. rewrite Hsub'.\n    rewrite pull_right.\n    assert (Hq: q = (Znth b bins')). (* TODO clean this mess *)\n    { unfold bins'. rewrite upd_Znth_same.  \n      destruct q; auto with valid_pointer.\n      match goal with | HA: Zlength bins = _ |- _ => \n                        auto 10  with valid_pointer; rewrite H0; assumption end.  }\n    rewrite Hq.\n    (* Annoying rewrite, but can't use replace_SEP because that's for \n       preconditions; would have to do use it back at the last forward. *)\n    assert (Hassoc:\n        iter_sepcon mmlist' (sublist 0 b (zip3 lens' bins' idxs)) *\n        mmlist (bin2sizeZ b) (Znth b lens') (Znth b bins') nullval * TT *\n        iter_sepcon mmlist' (sublist (b + 1) BINS (zip3 lens' bins' idxs))\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') (Znth b bins') nullval * TT)\n           by (apply pred_ext; entailer!).\n    sep_apply Hassoc; clear Hassoc. \n    rewrite mem_mgr_split'; try entailer!; auto.\n\n* (*+ case not guaranteed *) \nassert (Hb: 0 <= b < BINS) by (apply (claim2 n); lia).\nrewrite (mem_mgr_split_R gv b rvec) by apply Hb.\nIntros bins idxs lens.\nfreeze [1; 3] Otherlists.\ndeadvars!.\nforward. (*! p = bin[b] !*)\n(* TODO may not need post since excluding one branch *)\nforward_if( (*! if p == null *)\n    EX p:val, EX len:Z,\n     PROP(p <> nullval)\n     LOCAL(temp _p p; temp _b (Vint (Int.repr b)); gvars gv)\n     SEP(FRZL Otherlists; TT; \n         data_at Ews (tarray (tptr tvoid) BINS) (upd_Znth b bins p) (gv _bin);\n         mmlist (bin2sizeZ b) (Z.to_nat len) p nullval)). \n\n  + (* typecheck guard *)\n    set (lens:=map Z.to_nat rvec).\n    destruct (Znth b lens) eqn: Hblen. \n    - (* length 0 *)\n      match goal with | HA: Znth b bins = nullval <-> _ |- _ => set (Hbn:=HA) end. \n      (*Set Printing Implicit. -- to see the need for following step. *)\n      change Inhabitant_val with Vundef in Hbn.\n      assert (Znth b bins = nullval) by apply (proj2 Hbn Hblen).\n      change (@Znth val Vundef) with (@Znth val Inhabitant_val).\n      replace (Znth b bins) with nullval by assumption.\n      auto with valid_pointer.\n    - (* length non-zero *)\n      match goal with | HA: Znth b bins = nullval <-> _ |- _ => destruct HA end.\n      assert (Znth b bins <> nullval). {\n        assert (S n0 <> 0%nat) by congruence. \n        change lens with (map Z.to_nat rvec) in *.\n        rewrite Hblen in *; auto.\n      }\n      change (Vint Int.zero) with nullval.\n      auto with valid_pointer.\n      apply denote_tc_test_eq_split; auto with valid_pointer.\n      sep_apply (mmlist_ne_valid_pointer (bin2sizeZ b) (S n0) (Znth b bins) nullval).\n      lia. change Inhabitant_val with Vundef; entailer!.\n  + (* branch p==NULL *) \n    change Inhabitant_val with Vundef in *.\n    replace (Znth b bins) with nullval by assumption.\n    assert_PROP(Znth b lens = 0%nat) as Hlen0.\n   { entailer!.\n      match goal with | HA: nullval = nullval <-> _ |- _ => (apply HA; reflexivity) end.  } \n    rewrite Hlen0.\n    rewrite mmlist_empty.\n    forward_call b. (*! p = fill_bin(b) !*) \n    Intro r_with_l; destruct r_with_l as [root len]; simpl.\n    forward_if. (*! if p==NULL !*)\n    ++ (* typecheck guard *)\n      apply denote_tc_test_eq_split; auto with valid_pointer.\n      if_tac. entailer!.\n      sep_apply (mmlist_ne_valid_pointer (bin2sizeZ b) (Z.to_nat len) root nullval).\n      change (Z.to_nat len > 0)%nat with (0 < Z.to_nat len)%nat.\n      change 0%nat with (Z.to_nat 0). apply Z2Nat.inj_lt; rep_lia.\n      entailer!.\n    ++ (* case p==NULL after fill_bin() *) \n      forward. (*! return null *)\n      Exists nullval. entailer!. \n      thaw Otherlists.\n      set (idxs:= (map Z.of_nat (seq 0 (Z.to_nat BINS)))).\n      replace (data_at Ews (tarray (tptr tvoid) BINS) bins (gv _bin))\n         with (data_at Ews (tarray (tptr tvoid) BINS) bins (gv _bin) * emp) \n         by normalize.\n      rewrite <- (mmlist_empty (bin2sizeZ b)). (* used to need: at 2. *)\n      2: solve [ pose proof (bin2size_range b); rep_lia].\n      rewrite <- Hlen0 at 1.\n      unfold mem_mgr_R. Exists bins. Exists idxs.  Exists (map Z.to_nat rvec).\n      entailer!. rewrite <-(mem_mgr_split' b); unfold b, Inhabitant_val; auto.\n      rewrite H6; cancel.\n    ++ (* case p<>NULL *)\n      if_tac. contradiction.\n      Intros.\n      forward. (*! bin[b] = p !*)\n      Exists root. Exists len.\n     entailer!. \n    ++ pose proof (bin2size_range b); rep_lia.\n  + (* branch p!=NULL *)\n    forward. (*! skip !*)\n    Exists (Znth b bins).  \n    Exists (Z.of_nat (nth (Z.to_nat b) lens 0%nat)).\n    rewrite Nat2Z.id.  \n    match goal with | HA: Zlength bins = _ |- _ => \n                      rewrite upd_Znth_same_val by (rewrite HA; assumption) end. \n    entailer!.\n    rewrite <- nth_Znth; try rep_lia.\n    unfold Inhabitant_nat.\n    entailer!.\n  + (* after if: unroll and pop mmlist *)\n    Intros p len.\n    set (s:=bin2sizeZ b).  \n    assert_PROP (len > 0).\n    { sep_apply (mmlist_ne_len s len p nullval); auto. entailer!.  }\n    assert_PROP (isptr p).\n    { entailer!. clear - H6 PNp. destruct p; auto.\n      contradiction H6; simpl in *; subst; auto. }\n    rewrite (mmlist_unroll_nonempty s (Z.to_nat len) p)\n       by (rewrite Z2Nat.id; rep_lia); try assumption.\n    Intros q.\n    assert_PROP(force_val (sem_cast_pointer p) = field_address (tptr tvoid) [] p).\n    { entailer!. unfold field_address. rewrite if_true by auto. normalize. }\n    forward. (*! q = *p !*)\n    forward. (*! bin[b]=q !*)\n    (* prepare token+chunk to return *)\n    deadvars!.\n    thaw Otherlists.\n    sep_apply (to_malloc_token'_and_block n p q s).\n    (* refold invariant *)\n    rewrite upd_Znth_twice by (rewrite H0; apply Hb).\n    set (lens':=(upd_Znth b lens (Nat.pred (Z.to_nat len)))).\n    set (bins':=(upd_Znth b bins (force_val (sem_cast_pointer q)))).\n    assert (Hpredlen: Nat.pred (Z.to_nat len) = (Znth b lens')).\n    { unfold lens'. rewrite upd_Znth_same. reflexivity. \n      match goal with | HA: Zlength lens = _ |- _ => rewrite HA end. \n      assumption. }\n    rewrite Hpredlen. \n    change s with (bin2sizeZ b).\n    forward. (*! return p !*)\n    Exists p. entailer!. \n    rewrite if_false by auto.\n    bdestruct (size2binZ n <? BINS); try rep_lia.\n    set (rvec':= add_resvec rvec b (len-1)).\n    Exists rvec'.\n    assert (Heq_except: eq_except rvec' rvec (size2binZ n))\n      by (unfold rvec'; apply add_resvec_eq_except).\n    entailer!.\n    unfold mem_mgr_R.\n    set (lens:= (map Z.to_nat rvec)) in *.\n    Exists bins'. \n    set (idxs:= (map Z.of_nat (seq 0 (Z.to_nat BINS)))).\n    Exists idxs.   \n    Exists lens'.\n    assert (Hlbins': Zlength bins' = BINS) \n      by (subst bins'; rewrite upd_Znth_Zlength; rep_lia).\n    assert (Hllens': Zlength lens' = BINS) \n      by (subst lens'; rewrite upd_Znth_Zlength; rep_lia). \n    entailer!. \n    { split.\n      -- subst lens' rvec'. rewrite Hpredlen, upd_Znth_same by rep_lia.\n         unfold add_resvec.\n         bdestruct (Zlength rvec =? BINS); [ | rep_lia].\n         bdestruct (0 <=? b); [ | rep_lia].\n         bdestruct (b <? BINS); [ |rep_lia].\n         simpl.\n         rewrite <- upd_Znth_map. subst lens. f_equal.\n         rewrite Hprednat; auto. f_equal. \n         replace (Znth b rvec) with 0; try rep_lia.\n         symmetry.  apply small_not_guaranteed_zero; auto. \n      -- apply add_resvec_no_neg; auto.\n         assert (0 <= Znth b rvec).\n         { apply Forall_Znth. assumption. lia. }\n         rep_lia.\n    }\n(* TODO following can be more succinct using replace, as in free_small and pre_fill *)\n    assert (Hbins': sublist 0 b bins' = sublist 0 b bins) by\n      (unfold bins'; rewrite sublist_upd_Znth_l; try reflexivity; try rep_lia).\n    assert (Hlens': sublist 0 b lens' = sublist 0 b lens) by \n      (unfold lens'; rewrite sublist_upd_Znth_l; try reflexivity; try rep_lia).\n    assert (Hbins'': sublist (b+1) BINS bins' = sublist (b+1) BINS bins) by\n      (unfold bins'; rewrite sublist_upd_Znth_r; try reflexivity; try rep_lia).\n    assert (Hlens'': sublist (b+1) BINS lens' = sublist (b+1) BINS lens) by\n      (unfold lens'; rewrite sublist_upd_Znth_r; try reflexivity; try rep_lia).\n    assert (Hsub:  sublist 0 b (zip3 lens bins idxs)\n                 = sublist 0 b (zip3 lens' bins' idxs)).\n    { repeat rewrite sublist_zip3; try rep_lia.\n      - rewrite Hbins'. rewrite Hlens'.  reflexivity.\n      - assert (Zlength idxs = BINS) by auto. rep_lia.\n      - assert (Zlength idxs = BINS) by auto. rep_lia.\n    } \n    assert (Hsub':  sublist (b + 1) BINS (zip3 lens bins idxs)  \n                  = sublist (b + 1) BINS (zip3 lens' bins' idxs)).\n    { repeat rewrite sublist_zip3; try rep_lia.\n      - rewrite Hbins''. rewrite Hlens''.  reflexivity.\n      - assert (Zlength idxs = BINS) by auto. rep_lia.\n      - assert (Zlength idxs = BINS) by auto. rep_lia.\n    }\n    rewrite Hsub. rewrite Hsub'.\n    rewrite pull_right.\n    assert (Hq: q = (Znth b bins')).\n    { unfold bins'. rewrite upd_Znth_same.  \n      destruct q; auto with valid_pointer. rep_lia.\n    }\n    rewrite Hq.\n    rewrite mem_mgr_split'; try entailer!; auto.\nQed.\n(*\nDefinition module := [mk_body body_malloc_small].\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_malloc_small.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.25998789380878}}
{"text": "From iris.proofmode Require Import tactics.\nFrom iris_named_props Require Import named_props.\n\nSet Default Proof Using \"All\".\nSection tests.\n  Context {PROP: bi} {Haffine: BiAffine PROP}.\n  Implicit Types (P Q R : PROP).\n\n  Lemma demo_split_manual P Q R :\n    \"HP\" ∷ P ∗\n    \"HQ\" ∷ Q ∗\n    \"HP_to_R\" ∷ (P -∗ R) -∗\n    R ∗ Q.\n  Proof.\n    iNamed 1.\n    iSplitL \"HP HP_to_R\".\n    - iApply (\"HP_to_R\" with \"HP\").\n    - iExact \"HQ\".\n  Qed.\n\n  Lemma demo_split_delay P Q R :\n    \"HP\" ∷ P ∗\n    \"HQ\" ∷ Q ∗\n    \"HP_to_R\" ∷ (P -∗ R) -∗\n    R ∗ Q.\n  Proof.\n    iNamed 1.\n    iSplitDelay.\n    - iSpecialize (\"HP_to_R\" with \"HP\").\n      iFrame.\n      Show.\n      rewrite left_id. (* TODO: this is an annoyance *)\n      iNamedAccu.\n    - iNamed 1.\n      Show.\n      iExact \"HQ\".\n  Qed.\nEnd tests.\n", "meta": {"author": "tchajed", "repo": "iris-named-props", "sha": "9feafe5d878329edf3486673594d32887dd4cf18", "save_path": "github-repos/coq/tchajed-iris-named-props", "path": "github-repos/coq/tchajed-iris-named-props/iris-named-props-9feafe5d878329edf3486673594d32887dd4cf18/tests/split_delay.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604274, "lm_q2_score": 0.4687906266262438, "lm_q1q2_score": 0.2599305567145435}}
{"text": "Require Import ExtLib.Structures.Monad.\n\nSet Implicit Arguments.\n\nClass MonadZero (m : Type -> Type) : Type :=\n{ mzero : forall {T}, m T }.\n\nSection ZeroFuncs.\n  Context {m : Type -> Type}.\n  Context {Monad_m : Monad m}.\n  Context {Zero_m : MonadZero m}.\n\n  Definition assert (b : bool) : m unit :=\n    if b then ret tt else mzero.\n\nEnd ZeroFuncs.", "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/MonadZero.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604272, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2599305567145434}}
{"text": "Require Import Coq.Lists.List\n        Coq.Strings.String\n        Coq.Logic.FunctionalExtensionality\n        Coq.Sets.Ensembles\n        Coq.Arith.Arith\n        Fiat.Computation.Core\n        Fiat.ADT.ADTSig\n        Fiat.ADT.Core\n        Fiat.Common.StringBound\n        Fiat.Common.ilist2\n        Fiat.Common.ilist\n        Fiat.ADTNotation.BuildADT\n        Fiat.ADTNotation.BuildADTSig\n        Fiat.Common.Ensembles.IndexedEnsembles\n        Fiat.QueryStructure.Specification.Representation.Notations\n        Fiat.QueryStructure.Specification.Representation.Heading\n        Fiat.QueryStructure.Specification.Representation.Tuple\n        Fiat.QueryStructure.Specification.Representation.Schema\n        Fiat.QueryStructure.Specification.Representation.Relation\n        Fiat.QueryStructure.Specification.Representation.QueryStructureSchema.\n\nSection BuildQueryStructureConstraints.\n  (* Query Structures maintain a set of constraints that enforce\n     cross-relation data integrity. Query Structure Schemas encode\n     these as a list of dependent products, which\n     [BuildQueryStructureConstraints] uses to build the actual constraints.\n   *)\n\n  Local Obligation Tactic := intros.\n\n  (* [BuildQueryStructureConstraints_cons] searches the *)\n\n  Program Definition BuildQueryStructureConstraints_cons\n          {n}\n          (namedSchemas : Vector.t RawSchema n)\n          (constr : sigT (crossRelationProdR namedSchemas))\n          (constraints :\n             list (sigT (crossRelationProdR namedSchemas)))\n          (idx idx' : _)\n          (HInd : option (crossRelationR namedSchemas idx idx'))\n    : option (crossRelationR namedSchemas idx idx')\n    :=\n      if (fin_eq_dec idx (fst (projT1 constr))) then\n        if (fin_eq_dec idx' (snd (projT1 constr))) then\n          _\n        else HInd\n      else HInd.\n  Next Obligation.\n    destruct constr; simpl in *.\n    (* No need to check if the indices are in the list of Relations, because\n     they are Bounded Strings. *)\n    unfold crossRelationR, GetNRelSchemaHeading, GetNRelSchema; simpl.\n    rewrite H, H0;  exact (Some c).\n  Defined.\n\n  Fixpoint BuildQueryStructureConstraints'\n           {n}\n           (namedSchemas : Vector.t RawSchema n)\n           (constraints :\n              list (sigT (crossRelationProdR namedSchemas)))\n           {struct constraints}\n    : forall (idx idx' : _), option (crossRelationR namedSchemas idx idx') :=\n    match constraints with\n    | idx'' :: constraints' =>\n      fun idx idx' => @BuildQueryStructureConstraints_cons _\n                                                           namedSchemas idx'' constraints' idx idx'\n                                                           (BuildQueryStructureConstraints' constraints' idx idx')\n    | nil => fun _ _ => None\n    end.\n\n  Definition BuildQueryStructureConstraints qsSchema :=\n    BuildQueryStructureConstraints' (qschemaConstraints qsSchema).\n\nEnd BuildQueryStructureConstraints.\n\n(* A Query Structure is a collection of relations\n   (described by a proposition) which satisfy the\n   schema and the cross-relation constraints. *)\n\nRecord RawQueryStructure (QSSchema : RawQueryStructureSchema) :=\n  { rawRels : ilist2 (B := RawRelation) (qschemaSchemas QSSchema);\n    crossConstr :\n      forall (idx idx' : _),\n        match (BuildQueryStructureConstraints QSSchema idx idx') with\n        | Some CrossConstr =>\n          forall (tup : @IndexedRawTuple (GetNRelSchemaHeading (qschemaSchemas QSSchema) idx)),\n            idx <> idx' ->\n            (* These are cross-relation constraints which only need to be\n           enforced on distinct relations. *)\n            (rawRel (ith2 rawRels idx )) tup ->\n            CrossConstr (indexedElement tup) (rawRel (ith2 rawRels idx'))\n        | None => True\n        end\n  }.\n\nDefinition QueryStructure (QSSchema : QueryStructureSchema) := RawQueryStructure QSSchema.\n\n(* Notation \"t ! R\" := (rels t R%string): QueryStructure_scope. *)\n\n(* This typeclass allows our method definitions to infer the\n   the QueryStructure [r] they are called with. *)\n\n(* Class QueryStructureSchemaHint :=\n  { qsSchemaHint : QueryStructureSchema\n  }.\n\nClass QueryStructureHint :=\n  { qsSchemaHint' : QueryStructureSchema;\n    qsHint :> @QueryStructure qsSchemaHint'\n  }. *)\n\n(*Notation \"'query' id ( r : 'rep' , x : dom ) : cod := bod\" :=\n  (Build_methDef {| methID := id; methDom := dom; methCod := cod |}\n                 (fun (r : rep) x =>\n                    let _ := {| codHint := cod |} in\n                    queryRes <- bod%QuerySpec;\n                  ret (r, queryRes)))%comp\n                                     (no associativity, id at level 0, x at level 0, dom at level 0,\n                                      r at level 0, cod at level 0, only parsing,\n                                      at level 94, format \"'query'  id  (  r  : 'rep'  ,  x  :  dom )  :  cod  :=  '[  '   bod ']' \" ) :\n    queryDef_scope.\n\nNotation \"'update' id ( r : 'rep' , x : dom ) : cod := bod\" :=\n  (Build_methDef {| methID := id; methDom := dom; methCod := cod |}\n                 (fun (r : rep) x =>\n                    bod%QuerySpec))\n    (no associativity, id at level 0, x at level 0, dom at level 0,\n     r at level 0, cod at level 0, only parsing,\n     at level 94, format \"'update'  id  (  r  :  'rep'  ,  x  :  dom )  :  cod  :=  '[  '   bod ']' \" ) :\n    queryDef_scope. *)\n\n(* Notation for ADTs built from [BuildADT]. *)\n\n(*Notation \"'QueryADTRep' r { cons1 , meth1 , .. , methn } \" :=\n  (let _ := {| rep := (QueryStructure r) |}\n   in @BuildADT (QueryStructure r) _ _ _ _\n             (icons cons1%consDef (inil (B := @consDef (QueryStructure r))))\n             (icons (B := @methDef (QueryStructure r)) (meth1%queryDef%methDefParsing ) .. (icons (B := @methDef (QueryStructure r)) methn%queryDef%methDefParsing (inil (B := @methDef (QueryStructure r)))) ..))\n    (no associativity, at level 96, r at level 0, only parsing,\n     format \"'QueryADTRep'  r  '/' '[hv  ' {  cons1 , '//' '//' meth1 , '//' .. , '//' methn  ']' }\") : QueryStructure_scope. *)\n\nDefinition GetRelation\n           (QSSchema : QueryStructureSchema)\n           (qs : QueryStructure QSSchema)\n           (idx : Fin.t _)\n  : @IndexedEnsemble (@RawTuple (GetNRelSchemaHeading (qschemaSchemas QSSchema) idx)) := rawRel (ith2 (rawRels qs) idx).\n\nDefinition GetRelationBnd\n           (QSSchema : QueryStructureSchema)\n           (qs : QueryStructure QSSchema)\n           (idx : BoundedIndex (QSschemaNames QSSchema))\n  : @IndexedEnsemble (@RawTuple (GetNRelSchemaHeading (qschemaSchemas QSSchema) (ibound (indexb idx)))) := @GetRelation QSSchema qs (ibound (indexb idx)).\n\n(* This lets us drop the constraints from the reference implementation\n   for easier refinements. *)\n\nDefinition UnConstrQueryStructure (qsSchema : RawQueryStructureSchema) :=\n  ilist2 (B := fun ns => RawUnConstrRelation (rawSchemaHeading ns))\n        (qschemaSchemas qsSchema).\n\nDefinition GetUnConstrRelation\n           {QSSchema : RawQueryStructureSchema}\n           (qs : UnConstrQueryStructure QSSchema)\n           (idx : _)\n  : @IndexedEnsemble (@RawTuple (GetNRelSchemaHeading (qschemaSchemas QSSchema) idx)) :=\n      ith2 qs idx.\n\nDefinition GetUnConstrRelationBnd\n           {QSSchema : QueryStructureSchema}\n           (qs : UnConstrQueryStructure QSSchema)\n           (idx : BoundedIndex (QSschemaNames QSSchema))\n  : @IndexedEnsemble (@RawTuple (GetNRelSchemaHeading (qschemaSchemas QSSchema) (ibound (indexb idx)))) :=\n      ith2 qs (ibound (indexb idx)).\n\nDefinition DropQSConstraints\n           {qsSchema : QueryStructureSchema}\n           (qs : QueryStructure qsSchema)\n  : UnConstrQueryStructure qsSchema :=\n  @imap2 _\n        (fun ns => RawRelation ns)\n        (fun ns => RawUnConstrRelation (rawSchemaHeading ns))\n        (fun ns => @rawRel ns) _ (qschemaSchemas qsSchema) (rawRels qs).\n\nDefinition DropQSConstraints_AbsR (qsSchema : QueryStructureSchema)\n           (qs : QueryStructure qsSchema)\n           (qs' : UnConstrQueryStructure qsSchema)\n  : Prop :=\n  DropQSConstraints qs = qs'.\n\nLemma GetRelDropConstraints\n      {qsSchema : QueryStructureSchema}\n      (qs : QueryStructure qsSchema)\n      (Ridx : _)\n  : GetUnConstrRelation (DropQSConstraints qs) Ridx = GetRelation qs Ridx.\nProof.\n  unfold GetUnConstrRelation, DropQSConstraints, GetRelation.\n  rewrite <- ith_imap2; reflexivity.\nQed.\n\n(* Typeclass + notations for declaring abstraction relation for\n   QueryStructure Implementations. *)\n\n\n\nDefinition SatisfiesAttributeConstraints\n           {qsSchema}\n           (Ridx : Fin.t _)\n           (tup : @RawTuple (GetNRelSchemaHeading (qschemaSchemas qsSchema) Ridx))\n  :=\n    match (attrConstraints (GetNRelSchema (qschemaSchemas qsSchema) Ridx)) with\n      Some Constr => Constr tup\n    | None => True\n    end.\n\nDefinition SatisfiesTupleConstraints\n           {qsSchema}\n           (Ridx : Fin.t _)\n           (tup tup' : @RawTuple (GetNRelSchemaHeading (qschemaSchemas qsSchema) Ridx)) :=\n  match (tupleConstraints (GetNRelSchema (qschemaSchemas qsSchema) Ridx)) with\n    Some Constr => Constr tup tup'\n  | None => True\n  end.\n\nDefinition SatisfiesCrossRelationConstraints\n           {qsSchema}\n           (Ridx Ridx' : Fin.t _)\n           (tup : @RawTuple (GetNRelSchemaHeading (qschemaSchemas qsSchema) Ridx)) R :=\n  match (BuildQueryStructureConstraints qsSchema Ridx Ridx') with\n  | Some CrossConstr => CrossConstr tup R\n  | None => True\n  end.\n\nDefinition UpdateUnConstrRelation\n           {qsSchema : RawQueryStructureSchema}\n           (rels : UnConstrQueryStructure qsSchema)\n           (Ridx : _)\n           newRel :\n  UnConstrQueryStructure qsSchema :=\n  replace_Index2 _ rels Ridx newRel.\n\nDefinition UpdateRelation\n           {qsSchema : QueryStructureSchema}\n           (rels : ilist2 (B := RawRelation) (qschemaSchemas qsSchema))\n           (Ridx : _)\n           newRel :\n  ilist2 (qschemaSchemas qsSchema) :=\n  replace_Index2 _ rels Ridx newRel.\n\n(* Consequences of ith_replace_BoundIndex_neq and ith_replace_BoundIndex_eq on updates *)\n\nLemma get_update_unconstr_eq :\n  forall (db_schema : RawQueryStructureSchema) (qs : UnConstrQueryStructure db_schema)\n         (index : _) ens,\n    GetUnConstrRelation (UpdateUnConstrRelation qs index ens) index = ens.\nProof.\n  unfold UpdateUnConstrRelation, GetUnConstrRelation.\n  intros; rewrite ith_replace2_Index_eq; reflexivity.\nQed.\n\nLemma get_update_unconstr_neq :\n  forall (db_schema : RawQueryStructureSchema) (qs : UnConstrQueryStructure db_schema)\n         (index1 index2 : _) ens,\n    index1 <> index2 ->\n    GetUnConstrRelation\n      (UpdateUnConstrRelation qs index1 ens) index2 =\n    GetUnConstrRelation qs index2.\nProof.\n  unfold UpdateUnConstrRelation, GetUnConstrRelation;\n  intros; simpl; rewrite ith_replace2_Index_neq; eauto using string_dec.\nQed.\n\nNotation \"ro ≃ rn\" := (@UnConstrRelationAbsR _ _ _ ro%QueryImpl rn) : QueryImpl_scope.\n\nNotation \"qs ! R\" :=\n  (GetUnConstrRelationBnd qs {|bindex := R%string |}): QueryImpl_scope.\n\n(*Arguments BuildQueryStructureConstraints _ _ _. *)\nArguments BuildQueryStructureConstraints_cons [_ _] _ _ _ _ (*/*) _ .\n(*Arguments BuildQueryStructureConstraints_cons_obligation_1 [_ _] _ (*/*) _ _ _ _.*)\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/Specification/Representation/QueryStructure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2599305498119238}}
{"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 AArch64 *)\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 uniproc := acyclic (po_loc ⊔ (rf ⊔ (fr ⊔ co))).\nDefinition dd := addr ⊔ data.\nDefinition rdw := po_loc ⊓ fre ⋅ rfe.\nDefinition detour := po_loc ⊓ coe ⋅ rfe.\nDefinition addrpo := addr ⋅ po.\nDefinition com := fr ⊔ (co ⊔ rf).\nDefinition atomic := is_empty (rmw ⊓ fre ⋅ coe).\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 := dmb_fullst ⊔ dmb_ishst.\nDefinition dmb_ld := dmb_fullld ⊔ dmb_ishld.\nDefinition dsb_sy := fencerel DSB_SY.\nDefinition dsb_st := fencerel DSB_ST.\nDefinition dsb_ld := fencerel DSB_LD.\nDefinition isb := fencerel ISB.\nDefinition ctrlisb := (*successful: try ctrlcfence ISB with 0*) ctrlcfence ISB.\nDefinition ci0 := ctrlisb ⊔ detour.\nDefinition ii0 := dd ⊔ (rfi ⊔ rdw).\nDefinition cc0 := dd ⊔ (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 acq := [A] ⋅ top ⋅ [M] ⊓ po.\nDefinition rel := [M] ⋅ top ⋅ [L] ⊓ po.\nDefinition syf := dmb_sy ⊓ [M] ⋅ top ⋅ [M] ⊔ dsb_sy ⊓ [M] ⋅ top ⋅ [M].\nDefinition stf := dmb_st ⊓ [W] ⋅ top ⋅ [W] ⊔ dsb_st ⊓ [W] ⋅ top ⋅ [W].\nDefinition ldf := dmb_ld ⊓ [R] ⋅ top ⋅ [M] ⊔ dsb_ld ⊓ [R] ⋅ top ⋅ [M].\nDefinition fence := syf ⊔ (stf ⊔ (ldf ⊔ (acq ⊔ rel))).\nDefinition hb := [R] ⋅ top ⋅ [M] ⊓ fence ⊔ (rfe ⊔ ppo).\nDefinition thin_air := acyclic hb.\nDefinition prop := com^* ⋅ syf ⊔ (stf ⊔ (rfe ⊔ 1) ⋅ rel).\nDefinition prop_al := [L] ⋅ top ⋅ [A] ⊓ (rf ⊔ po) ⊔ [A] ⋅ top ⋅ [L] ⊓ fr.\nDefinition xx := [W] ⋅ top ⋅ [W] ⊓ ([X] ⋅ top ⋅ [X] ⊓ po).\nDefinition observation := irreflexive (prop ⋅ (rfe ⋅ ((fence ⊔ ppo) ⋅ fre))).\nDefinition propagation := acyclic (co ⊔ (prop ⋅ hb^* ⊔ (xx ⊔ prop_al ⋅ hb^*))).\nDefinition witness_conditions := generate_cos cobase co.\nDefinition model_conditions := uniproc /\\ (atomic /\\ (thin_air /\\ (observation /\\ propagation))).\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 uniproc dd rdw detour addrpo com atomic 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 dmb_ld dsb_sy dsb_st dsb_ld isb ctrlisb ci0 ii0 cc0 ic0 ppo acq rel syf stf ldf fence hb thin_air prop prop_al xx observation propagation 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 AArch64 *)\n", "meta": {"author": "jmadiot", "repo": "cats", "sha": "d3d6cae610dbd41c8a00d8cbdc0374cb02d6de95", "save_path": "github-repos/coq/jmadiot-cats", "path": "github-repos/coq/jmadiot-cats/cats-d3d6cae610dbd41c8a00d8cbdc0374cb02d6de95/models/aarch64_obsolete.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.3665897294020099, "lm_q1q2_score": 0.2599191369031131}}
{"text": "From bisimulations Require Import prelude.\nFrom bisimulations Require Import system.\nFrom bisimulations Require Import relations.\nFrom bisimulations Require Import paths.\nFrom bisimulations Require Import formulas.\nFrom bisimulations Require Import reflexive.directed_branching.\nFrom bisimulations Require Import reflexive.hmlu.\nFrom bisimulations Require Import reflexive.phmlu.\n\nSection Distinguish.\nContext `{ReflSystem : @refl_system X System}.\n\nRecord DADist φ (p q : X) : Prop := mkDADist\n{ NoPolarity : sc db_dapart p q\n; PosPolarity : HmluPos φ → db_dapart p q\n; NegPolarity : HmluNeg φ → db_dapart q p\n}.\n\nLemma neg_da_dist {φ p q} : DADist φ p q → DADist (¬ₕ φ) q p.\nProof. intros [HNP HPos HNeg]. constructor; [by symmetry|..]; by autorewrite with hints. Qed.\nLemma conj_left_da_dist {φ ψ p q} : DADist φ p q → DADist (φ ∧ₕ ψ) p q.\nProof. intros [HNP HPos HNeg]. constructor; [by symmetry|..]; autorewrite with hints; intros []; eauto. Qed.\nLemma conj_right_da_dist {φ ψ p q} : DADist ψ p q → DADist (φ ∧ₕ ψ) p q.\nProof. intros [HNP HPos HNeg]. constructor; [by symmetry|..]; autorewrite with hints; intros []; eauto. Qed.\nLemma diam_simple_da_dist {l δ φ p q} : db_dapart p q → DADist (◇ₕ l δ φ) p q.\nProof. intros Hpq. constructor; [by left|by intros|]. intros. inv_polarity. Qed.\nLemma diam_left_da_dist {l δ φ p q} : DADist δ p q → DADist (◇ₕ l δ φ) p q.\nProof. intros [HNP HPos HNeg]. constructor; [done|..]; intros; inv_polarity; eauto. Qed.\n\nHint Resolve neg_da_dist : hints.\nHint Resolve conj_left_da_dist : hints.\nHint Resolve conj_right_da_dist : hints.\nHint Resolve diam_simple_da_dist : hints.\nHint Resolve diam_left_da_dist : hints.\n\nLemma good_distinguish_gives_apartness_impl {p q φ} : HmluGood φ → p ⊨ₕ φ → q ⊭ₕ φ → DADist φ p q.\nProof.\n  intros Hgood. revert φ Hgood p q.\n  eapply (hmlu_good_ind (λ φ, ∀ p q, p ⊨ₕ φ → q ⊭ₕ φ → DADist φ p q)); simpl.\n  - by intros.\n  - eauto with hints.\n  - intros φ ψ IHφ IHψ p q [Hpφ Hpψ] [Hqφ|Hqψ]; eauto with hints.\n  - intros l δ φ Hδ IHδ IHφ p q Hp Hq. inv_hmlu; fold HmluTrue HmluFalse in *.\n    rename p into p1, x into p2, x0 into p3, H into Hp12, H0 into Hp23, H1 into Hp3.\n    eapply diam_simple_da_dist. induction Hp12; [|by eapply db_dapart_extend_backwards_one; eauto].\n    eapply Fwd; try done. intros q2 Hq12 q3 Hq23.\n    destruct (hmlu_true_or_false δ q2); [right|left; by eapply IHδ].\n    eapply NoPolarity, IHφ; try done.\n    eapply Hq; try done.\n    by eapply rtc_to_path_via_by_pos.\nQed.\n\nTheorem good_distinguish_gives_apartness {p q φ} : HmluGood φ → p ⊨ₕ φ → q ⊭ₕ φ → sc db_dapart p q.\nProof. intros. eauto using NoPolarity, good_distinguish_gives_apartness_impl. Qed.\nTheorem good_distinguish_gives_apartness_pos {p q φ} : HmluGood φ → HmluPos φ → p ⊨ₕ φ → q ⊭ₕ φ → db_dapart p q.\nProof. intros. eauto using PosPolarity, good_distinguish_gives_apartness_impl. Qed.\nTheorem good_distinguish_gives_apartness_neg {p q φ} : HmluGood φ → HmluNeg φ → p ⊨ₕ φ → q ⊭ₕ φ → db_dapart q p.\nProof. intros. eauto using NegPolarity, good_distinguish_gives_apartness_impl. Qed.\n\nEnd Distinguish.", "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/distinguish.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160664, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2598774697734578}}
{"text": "Require Coq.Strings.Ascii.\nRequire Coq.Strings.String.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Program.Wf.\nRequire Import Coq.PArith.BinPos.\nRequire Import Coq.ZArith.ZArith.\nRequire Import ExtLib.Structures.Monoid.\nRequire Import ExtLib.Structures.Reducible.\nRequire Import ExtLib.Programming.Injection.\nRequire Import ExtLib.Data.Char.\nRequire Import ExtLib.Data.String.\nRequire Import ExtLib.Data.Fun.\nRequire Import ExtLib.Core.RelDec.\n\nSet Implicit Arguments.\nSet Strict Implicit.\nSet Universe Polymorphism.\n\nSet Printing Universes.\n\nMonomorphic Universe Ushow.\n\nDefinition showM@{T} : Type@{Ushow} :=\n  forall m : Type@{T}, Injection ascii m -> Monoid m -> m.\n\nClass ShowScheme@{t} (T : Type@{t}) : Type :=\n{ show_mon : Monoid@{t} T\n; show_inj : Injection ascii T\n}.\n\nGlobal Instance ShowScheme_string : ShowScheme string :=\n{ show_mon := Monoid_string_append\n; show_inj := fun x => String x EmptyString\n}.\n\nGlobal Instance ShowScheme_string_compose : ShowScheme (string -> string) :=\n{ show_mon := Monoid_compose string\n; show_inj := String\n}.\n\nDefinition runShow {T} {M : ShowScheme T} (m : showM) : T :=\n  m _ show_inj show_mon.\n\nClass Show@{t m} (T : Type@{t}) : Type :=\n  show : T -> showM@{m}.\n\nDefinition to_string {T} {M : Show T} (v : T) : string :=\n  runShow (show v) \"\"%string.\n\nDefinition empty : showM :=\n  fun _ _ m => monoid_unit m.\nDefinition cat (a b : showM) : showM :=\n  fun _ i m => monoid_plus m (a _ i m) (b _ i m).\nGlobal Instance Injection_ascii_showM : Injection ascii showM :=\n  fun v => fun _ i _ => i v.\n\nFixpoint show_exact (s : string) : showM :=\n  match s with\n    | EmptyString => empty\n    | String a s' => cat (inject a) (show_exact s')\n  end.\n\nModule ShowNotation.\n  Delimit Scope show_scope with show.\n\n  Notation \"x << y\" := (cat x%show y%show) (at level 100) : show_scope.\n  Coercion show_exact : string >-> showM.\n  Definition _inject_char : ascii -> showM := inject.\n  Coercion _inject_char : ascii >-> showM.\nEnd ShowNotation.\n\nDefinition indent (indent : showM) (v : showM) : showM :=\n  let nl := Ascii.ascii_of_nat 10 in\n    fun _ inj mon =>\n      v _ (fun a => if eq_dec a nl\n         then monoid_plus mon (inj a) (indent _ inj mon)\n         else inj a) mon.\n\nSection sepBy.\n  Import ShowNotation.\n  Local Open Scope show_scope.\n\n  Definition sepBy {T : Type}\n              {F : Foldable T showM} (sep : showM) (ls : T) : showM :=\n    match\n      fold (fun s acc =>\n        match acc with\n          | None => Some s\n          | Some x => Some (x << sep << s)\n        end) None ls\n      with\n      | None => empty\n      | Some s => s\n    end.\nEnd sepBy.\n\nSection sepBy_f.\n  Import ShowNotation.\n  Local Open Scope show_scope.\n  Variables (T : Type) (E : Type).\n  Context {F : Foldable T E}.\n  Variable (f : E -> showM).\n\n  Definition sepBy_f (sep : showM) (ls : T) : showM :=\n    match\n      fold (fun s acc =>\n        match acc with\n          | None => Some (f s)\n          | Some x => Some (x << sep << f s)\n        end) None ls\n      with\n      | None => empty\n      | Some s => s\n    end.\nEnd sepBy_f.\n\nDefinition wrap (before after : showM) (x : showM) : showM :=\n  cat before (cat x after).\n\nSection sum_Show.\n  Import ShowNotation.\n  Local Open Scope show_scope.\n\n  Definition sum_Show@{a m}\n              {A : Type@{a}} {B : Type@{a}} {AS:Show@{a m} A} {BS:Show@{a m} B}\n  : Show@{a m} (A+B) :=\n    fun s =>\n        let (tag, payload) :=\n          match s with\n          | inl a => (show_exact \"inl\"%string, show a)\n          | inr b => (show_exact \"inr\"%string, show b)\n          end\n        in\n        \"(\"%char <<\n        tag <<\n        \" \"%char <<\n        payload <<\n        \")\"%char.\n\nEnd sum_Show.\n\nSection foldable_Show.\n  Context {A:Type} {B:Type} {F : Foldable B A} {BS : Show A}.\n\n  Global Instance foldable_Show : Show B :=\n    { show s := sepBy_f show (show_exact \", \"%string) s }.\n\nEnd foldable_Show.\n\nFixpoint iter_show (ss : list showM) : showM :=\n  match ss with\n    | nil => empty\n    | cons s ss => cat s (iter_show ss)\n  end.\n\nSection hiding_notation.\n  Import ShowNotation.\n  Local Open Scope show_scope.\n  Import Ascii.\n  Import String.\n\n  Global Instance unit_Show : Show unit :=\n  { show u := \"tt\"%string }.\n  Global Instance bool_Show : Show bool :=\n  { show b := if b then \"true\"%string else \"false\"%string }.\n  Global Instance ascii_Show : Show ascii :=\n    fun a =>  \"'\"%char << a << \"'\"%char.\n  Global Instance string_Show : Show string :=\n  { show s := \"\"\"\"%char << s << \"\"\"\"%char }.\n\n  Program Fixpoint nat_show (n:nat) {measure n} : showM :=\n    if Compare_dec.le_gt_dec n 9 then\n      inject (Char.digit2ascii n)\n    else\n      let n' := NPeano.Nat.div n 10 in\n      (@nat_show n' _) << (inject (Char.digit2ascii (n - 10 * n'))).\n  Next Obligation.\n    assert (NPeano.Nat.div n 10 < n) ; eauto.\n    eapply NPeano.Nat.div_lt.\n    match goal with [ H : n > _ |- _ ] => inversion H end; apply Lt.lt_O_Sn.\n    repeat constructor.\n  Defined.\n  Global Instance nat_Show : Show nat := { show := nat_show }.\n\n  Global Instance Show_positive : Show positive :=\n    fun x => nat_show (Pos.to_nat x).\n\n  Global Instance Show_Z : Show Z :=\n    fun x =>\n      match x with\n      | Z0 => \"0\"%char\n      | Zpos p => show p\n      | Zneg p => \"-\"%char << show p\n      end.\n\nEnd hiding_notation.\n\nSection pair_Show.\n  Import ShowNotation.\n  Local Open Scope show_scope.\n  Definition pair_Show@{a m t}\n              {A : Type@{a}} {B : Type@{a}} {AS:Show A} {BS:Show B}\n  : Show@{_ t} (A*B) :=\n    fun p =>\n      let (a,b) := p in\n      \"(\"%char << show a << \",\"%char << show b << \")\"%char.\nEnd pair_Show.\n\n(*\nExamples:\nEval compute in (runShow (show (42,\"foo\"%string)) : string).\nEval compute in (runShow (show (inl true : bool+string))).\n*)\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/Programming/Show.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.25985576301744695}}
{"text": "From Hammer Require Import Hammer.\n\nRequire Import Coq.Classes.Morphisms.\nRequire Import Coq.Relations.Relations.\nRequire Import ExtLib.Structures.Proper.\nRequire Import ExtLib.Core.Type.\n\nSet Implicit Arguments.\nSet Strict Implicit.\nSet Universe Polymorphism.\n\nDefinition Fun@{d c} (A : Type@{d}) (B : Type@{c}) := A -> B.\n\nSection type.\nUniverse uT uU.\nVariables (T : Type@{uT}) (U : Type@{uU}) (tT : type T) (tU : type U).\n\nGlobal Instance type_Fun@{uU'} : type@{uU'} (T -> U) :=\n{ equal := fun f g => respectful equal equal f g\n; proper := fun x => respectful equal equal x x\n}.\n\nVariables (tOk : typeOk tT) (uOk : typeOk tU).\n\nGlobal Instance typeOk_Fun@{uU'} : typeOk@{uU'} type_Fun.\nProof. hammer_hook \"PreFun\" \"PreFun.typeOk_Fun\".\nconstructor.\n{ unfold equiv. simpl. unfold respectful.\ndestruct tOk. destruct uOk; intros.\nsplit; intros.\n{ destruct (only_proper _ _ H0).\netransitivity. eapply H. eassumption.\nsymmetry. eapply H. symmetry. auto. }\n{ destruct (only_proper _ _ H0).\nsymmetry. etransitivity; [ | eapply H ].\nsymmetry. eapply H. eassumption. symmetry. eauto. } }\n{ red. intros. apply H. }\n{ compute. intuition. symmetry. eapply H. symmetry. auto. }\n{ simpl; intro; intros. intuition. red in H; red in H0; simpl in *.\nred; intros.\netransitivity. eapply H. eassumption.\neapply H0.\neapply only_proper in H1; intuition.\neapply preflexive with (wf := proper); auto.\napply tOk. }\nQed.\n\nGlobal Instance proper_app@{uU'} : forall (f : T -> U) (a : T),\nproper@{uU'} f -> proper a -> proper (f a).\nProof. hammer_hook \"PreFun\" \"PreFun.proper_app\".\nsimpl; intros. red in H.\neapply proper_left; eauto.\neapply H. eapply preflexive. eapply equiv_prefl; auto. auto.\nQed.\n\nTheorem proper_fun@{uU'} : forall (f : T -> U),\n(forall x y, equal x y -> equal (f x) (f y)) ->\nproper@{uU'} f.\nProof. hammer_hook \"PreFun\" \"PreFun.proper_fun\".\nintros. do 3 red. eauto.\nQed.\n\nTheorem equal_fun@{uU'} : forall (f g : T -> U),\n(forall x y, equal x y -> equal (f x) (g y)) ->\nequal@{uU'} f g.\nProof. hammer_hook \"PreFun\" \"PreFun.equal_fun\". intros. do 3 red. apply H. Qed.\n\nTheorem equal_app@{uU'} : forall (f g : T -> U) (x y : T),\nequal@{uU'} f g -> equal x y ->\nequal (f x) (g y).\nProof. hammer_hook \"PreFun\" \"PreFun.equal_app\".\nclear. intros. do 3 red in H. auto.\nQed.\n\nEnd type.\n\nDefinition compose@{uA uB uC} {A:Type@{uA}} {B:Type@{uB}} {C : Type@{uC}}\n(g : B -> C) (f : A -> B) : A -> C :=\nfun x => g (f x).\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/coq-ext-lib/PreFun.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2598557630174469}}
{"text": "(** Administrative lemmas 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 administrative lemmas that we\n    require for proving type-safety.  The lemmas mainly concern the\n    relations [wf_typ] and [wf_env].\n\n    This file also contains regularity lemmas, which show that various\n    relations hold only for locally closed terms.  In addition to\n    being necessary to complete the proof of type-safety, these lemmas\n    help demonstrate that our definitions are correct; they would be\n    worth proving even if they are unneeded for any \"real\" proofs.\n\n    Table of contents:\n      - #<a href=\"##wft\">Properties of wf_typ</a>#\n      - #<a href=\"##oktwft\">Properties of wf_env and wf_typ</a>#\n      - #<a href=\"##okt\">Properties of wf_env</a>#\n      - #<a href=\"##subst\">Properties of substitution</a>#\n      - #<a href=\"##regularity\">Regularity lemmas</a>#\n      - #<a href=\"##auto\">Automation</a># *)\n\nRequire Export Fsub_Infrastructure.\n\n\n(* ********************************************************************** *)\n(** * #<a name=\"wft\"></a># Properties of [wf_typ] *)\n\n(** If a type is well-formed in an environment, then it is locally\n    closed. *)\n\nLemma type_from_wf_typ : forall E T,\n  wf_typ E T -> type T.\nProof.\n  intros E T H; induction H; eauto.\nQed.\n\n(** The remaining properties are analogous to the properties that we\n    need to show for the subtyping and typing relations. *)\n\nLemma wf_typ_weakening : forall T E F G,\n  wf_typ (G ++ E) T ->\n  ok (G ++ F ++ E) ->\n  wf_typ (G ++ F ++ E) T.\nProof with simpl_env; eauto.\n  intros T E F G Hwf_typ Hk.\n  remember (G ++ E).\n  generalize dependent G.\n  induction Hwf_typ; intros G Hok Heq; subst...\n  Case \"type_all\".\n    pick fresh Y and apply wf_typ_all...\n    rewrite <- concat_assoc.\n    apply H0...\nQed.\n\nLemma wf_typ_weaken_head : forall T E F,\n  wf_typ E T ->\n  ok (F ++ E) ->\n  wf_typ (F ++ E) T.\nProof.\n  intros.\n  rewrite_env (empty ++ F++ E).\n  auto using wf_typ_weakening.\nQed.\n\nLemma wf_typ_narrowing : forall V U T E F X,\n  wf_typ (F ++ [(X, bind_sub V)] ++ E) T ->\n  ok (F ++ [(X, bind_sub U)] ++ E) ->\n  wf_typ (F ++ [(X, bind_sub U)] ++ E) T.\nProof with simpl_env; eauto.\n  intros V U T E F X Hwf_typ Hok.\n  remember (F ++ [(X, bind_sub V)] ++ E).\n  generalize dependent F.\n  induction Hwf_typ; intros F Hok Heq; subst...\n  Case \"wf_typ_var\".\n    binds_cases H...\n  Case \"typ_all\".\n    pick fresh Y and apply wf_typ_all...\n    rewrite <- concat_assoc.\n    apply H0...\nQed.\n\nLemma wf_typ_strengthening : forall E F x U T,\n wf_typ (F ++ [(x, bind_typ U)] ++ E) T ->\n wf_typ (F ++ E) T.\nProof with simpl_env; eauto.\n  intros E F x U T H.\n  remember (F ++ [(x, bind_typ U)] ++ E).\n  generalize dependent F.\n  induction H; intros F Heq; subst...\n  Case \"wf_typ_var\".\n    binds_cases H...\n  Case \"wf_typ_all\".\n    pick fresh Y and apply wf_typ_all...\n    rewrite <- concat_assoc.\n    apply H1...\nQed.\n\nLemma wf_typ_subst_tb : forall F Q E Z P T,\n  wf_typ (F ++ [(Z, bind_sub Q)] ++ E) T ->\n  wf_typ E P ->\n  ok (map (subst_tb Z P) F ++ E) ->\n  wf_typ (map (subst_tb Z P) F ++ E) (subst_tt Z P T).\nProof with simpl_env; eauto using wf_typ_weaken_head, type_from_wf_typ.\n  intros F Q E Z P T WT WP.\n  remember (F ++ [(Z, bind_sub Q)] ++ E).\n  generalize dependent F.\n  induction WT; intros F EQ Ok; subst; simpl subst_tt...\n  Case \"wf_typ_var\".\n    destruct (X == Z); subst...\n    SCase \"X <> Z\".\n      binds_cases H...\n      apply (wf_typ_var (subst_tt Z P U))...\n  Case \"wf_typ_all\".\n    pick fresh Y and apply wf_typ_all...\n    rewrite subst_tt_open_tt_var...\n    rewrite_env (map (subst_tb Z P) ([(Y, bind_sub T1)] ++ F) ++ E).\n    apply H0...\nQed.\n\nLemma wf_typ_open : forall E U T1 T2,\n  ok E ->\n  wf_typ E (typ_all T1 T2) ->\n  wf_typ E U ->\n  wf_typ E (open_tt T2 U).\nProof with simpl_env; eauto.\n  intros E U T1 T2 Ok WA WU.\n  inversion WA; subst.\n  pick fresh X.\n  rewrite (subst_tt_intro X)...\n  rewrite_env (map (subst_tb X U) empty ++ E).\n  eapply wf_typ_subst_tb...\nQed.\n\n\n(* ********************************************************************** *)\n(** * #<a name=\"oktwft\"></a># Properties of [wf_env] and [wf_typ] *)\n\nLemma ok_from_wf_env : forall E,\n  wf_env E ->\n  ok E.\nProof.\n  intros E H; induction H; auto.\nQed.\n\n(** We add [ok_from_wf_env] as a hint here since it helps blur the\n    distinction between [wf_env] and [ok] in proofs.  The lemmas in\n    the [Environment] library use [ok], whereas here we naturally have\n    (or can easily show) the stronger [wf_env].  Thus,\n    [ok_from_wf_env] serves as a bridge that allows us to use the\n    environments library. *)\n\nHint Resolve ok_from_wf_env : core.\n\nLemma wf_typ_from_binds_typ : forall x U E,\n  wf_env E ->\n  binds x (bind_typ U) E ->\n  wf_typ E U.\nProof with auto using wf_typ_weaken_head.\n  induction 1; intros J; binds_cases J...\n  inversion H4; subst...\nQed.\n\nLemma wf_typ_from_wf_env_typ : forall x T E,\n  wf_env ([(x, bind_typ T)] ++ E) ->\n  wf_typ E T.\nProof.\n  intros x T E H. inversion H; auto.\nQed.\n\nLemma wf_typ_from_wf_env_sub : forall x T E,\n  wf_env ([(x, bind_sub T)] ++ E) ->\n  wf_typ E T.\nProof.\n  intros x T E H. inversion H; auto.\nQed.\n\n\n(* ********************************************************************** *)\n(** * #<a name=\"okt\"></a># Properties of [wf_env] *)\n\n(** These properties are analogous to the properties that we need to\n    show for the subtyping and typing relations. *)\n\nLemma wf_env_narrowing : forall V E F U X,\n  wf_env (F ++ [(X, bind_sub V)] ++ E) ->\n  wf_typ E U ->\n  wf_env (F ++ [(X, bind_sub U)] ++ E).\nProof with eauto 6 using wf_typ_narrowing.\n  induction F; intros U X Wf_env Wf;\n    inversion Wf_env; subst; simpl_env in *...\nQed.\n\nLemma wf_env_strengthening : forall x T E F,\n  wf_env (F ++ [(x, bind_typ T)] ++ E) ->\n  wf_env (F ++ E).\nProof with eauto using wf_typ_strengthening.\n  induction F; intros Wf_env; inversion Wf_env; subst; simpl_env in *...\nQed.\n\nLemma wf_env_subst_tb : forall Q Z P E F,\n  wf_env (F ++ [(Z, bind_sub Q)] ++ E) ->\n  wf_typ E P ->\n  wf_env (map (subst_tb Z P) F ++ E).\nProof with eauto 6 using wf_typ_subst_tb.\n  induction F; intros Wf_env WP; simpl_env;\n    inversion Wf_env; simpl_env in *; simpl subst_tb...\nQed.\n\n\n(* ********************************************************************** *)\n(** * #<a name=\"subst\"></a># Environment is unchanged by substitution for a fresh name *)\n\nLemma notin_fv_tt_open : forall (Y X : atom) T,\n  X `notin` fv_tt (open_tt T Y) ->\n  X `notin` fv_tt T.\nProof.\n intros Y X T. unfold open_tt.\n generalize 0.\n induction T; simpl; intros k Fr; notin_simpl; try apply notin_union; eauto.\nQed.\n\nLemma notin_fv_wf : forall E (X : atom) T,\n  wf_typ E T ->\n  X `notin` dom E ->\n  X `notin` fv_tt T.\nProof with auto.\n  intros E X T Wf_typ.\n  induction Wf_typ; intros Fr; simpl...\n  Case \"wf_typ_var\".\n    assert (X0 `in` (dom E))...\n    eapply binds_In; eauto.\n  Case \"wf_typ_all\".\n    apply notin_union...\n    pick fresh Y.\n    apply (notin_fv_tt_open Y)...\nQed.\n\nLemma map_subst_tb_id : forall G Z P,\n  wf_env G ->\n  Z `notin` dom G ->\n  G = map (subst_tb Z P) G.\nProof with auto.\n  intros G Z P H.\n  induction H; simpl; intros Fr; simpl_env...\n  rewrite <- IHwf_env...\n    rewrite <- subst_tt_fresh... eapply notin_fv_wf; eauto.\n  rewrite <- IHwf_env...\n    rewrite <- subst_tt_fresh... eapply notin_fv_wf; eauto.\nQed.\n\n\n(* ********************************************************************** *)\n(** * #<a name=\"regularity\"></a># Regularity of relations *)\n\nLemma sub_regular : forall E S T,\n  sub E S T ->\n  wf_env E /\\ wf_typ E S /\\ wf_typ E T.\nProof with simpl_env; auto*.\n  intros E S T H.\n  induction H...\n  Case \"sub_trans_tvar\".\n    eauto*.\n  Case \"sub_all\".\n    repeat split...\n    SCase \"Second of original three conjuncts\".\n      pick fresh Y and apply wf_typ_all...\n      destruct (H1 Y)...\n      rewrite_env (empty ++ [(Y, bind_sub S1)] ++ E).\n      apply (wf_typ_narrowing T1)...\n    SCase \"Third of original three conjuncts\".\n      pick fresh Y and apply wf_typ_all...\n      destruct (H1 Y)...\nQed.\n\nLemma typing_regular : forall E e T,\n  typing E e T ->\n  wf_env E /\\ expr e /\\ wf_typ E T.\nProof with simpl_env; auto*.\n  intros E e T H; induction H...\n  Case \"typing_var\".\n    repeat split...\n    eauto using wf_typ_from_binds_typ.\n  Case \"typing_abs\".\n    pick fresh y.\n    destruct (H0 y) as [Hok [J K]]...\n    repeat split. inversion Hok...\n    SCase \"Second of original three conjuncts\".\n      pick fresh x and apply expr_abs.\n        eauto using type_from_wf_typ, wf_typ_from_wf_env_typ.\n        destruct (H0 x)...\n    SCase \"Third of original three conjuncts\".\n      apply wf_typ_arrow; eauto using wf_typ_from_wf_env_typ.\n      rewrite_env (empty ++ E).\n      eapply wf_typ_strengthening; simpl_env; eauto.\n  Case \"typing_app\".\n    repeat split...\n    destruct IHtyping1 as [_ [_ K]].\n    inversion K...\n  Case \"typing_tabs\".\n    pick fresh Y.\n    destruct (H0 Y) as [Hok [J K]]...\n    inversion Hok; subst.\n    repeat split...\n    SCase \"Second of original three conjuncts\".\n      pick fresh X and apply expr_tabs.\n        eauto using type_from_wf_typ, wf_typ_from_wf_env_sub...\n        destruct (H0 X)...\n    SCase \"Third of original three conjuncts\".\n      pick fresh Z and apply wf_typ_all...\n      destruct (H0 Z)...\n  Case \"typing_tapp\".\n    destruct (sub_regular _ _ _ H0) as [R1 [R2 R3]].\n    repeat split...\n    SCase \"Second of original three conjuncts\".\n      apply expr_tapp...\n      eauto using type_from_wf_typ.\n    SCase \"Third of original three conjuncts\".\n      destruct IHtyping as [R1' [R2' R3']].\n      eapply wf_typ_open; eauto.\n  Case \"typing_sub\".\n    repeat split...\n    destruct (sub_regular _ _ _ H0)...\nQed.\n\nLemma value_regular : forall e,\n  value e ->\n  expr e.\nProof.\n  intros e H. induction H; auto.\nQed.\n\nLemma red_regular : forall e e',\n  red e e' ->\n  expr e /\\ expr e'.\nProof with auto*.\n  intros e e' H.\n  induction H; assert(J := value_regular); split...\n  Case \"red_abs\".\n    inversion H. pick fresh y. rewrite (subst_ee_intro y)...\n  Case \"red_tabs\".\n    inversion H. pick fresh Y. rewrite (subst_te_intro Y)...\nQed.\n\n\n(* *********************************************************************** *)\n(** * #<a name=\"auto\"></a># Automation *)\n\n(** The lemma [ok_from_wf_env] was already added above as a hint since it\n    helps blur the distinction between [wf_env] and [ok] in proofs.\n\n    As currently stated, the regularity lemmas are ill-suited to be\n    used with [auto] and [eauto] since they end in conjunctions.  Even\n    if we were, for example, to split [sub_regularity] into three\n    separate lemmas, the resulting lemmas would be usable only by\n    [eauto] and there is no guarantee that [eauto] would be able to\n    find proofs effectively.  Thus, the hints below apply the\n    regularity lemmas and [type_from_wf_typ] to discharge goals about\n    local closure and well-formedness, but in such a way as to\n    minimize proof search.\n\n    The first hint introduces an [wf_env] fact into the context.  It\n    works well when combined with the lemmas relating [wf_env] and\n    [wf_typ].  We choose to use those lemmas explicitly via [(auto\n    using ...)] tactics rather than add them as hints.  When used this\n    way, the explicitness makes the proof more informative rather than\n    more cluttered (with useless details).\n\n    The other three hints try outright to solve their respective\n    goals. *)\n\nHint Extern 1 (wf_env ?E) =>\n  match goal with\n  | H: sub _ _ _ |- _ => apply (proj1 (sub_regular _ _ _ H))\n  | H: typing _ _ _ |- _ => apply (proj1 (typing_regular _ _ _ H))\n  end.\n\nHint Extern 1 (wf_typ ?E ?T) =>\n  match goal with\n  | H: typing E _ T |- _ => apply (proj2 (proj2 (typing_regular _ _ _ H)))\n  | H: sub E T _ |- _ => apply (proj1 (proj2 (sub_regular _ _ _ H)))\n  | H: sub E _ T |- _ => apply (proj2 (proj2 (sub_regular _ _ _ H)))\n  end.\n\nHint Extern 1 (type ?T) =>\n  let go E := apply (type_from_wf_typ E); auto in\n  match goal with\n  | H: typing ?E _ T |- _ => go E\n  | H: sub ?E T _ |- _ => go E\n  | H: sub ?E _ T |- _ => go E\n  end.\n\nHint Extern 1 (expr ?e) =>\n  match goal with\n  | H: typing _ ?e _ |- _ => apply (proj1 (proj2 (typing_regular _ _ _ H)))\n  | H: red ?e _ |- _ => apply (proj1 (red_regular _ _ H))\n  | H: red _ ?e |- _ => apply (proj2 (red_regular _ _ H))\n  end.\n", "meta": {"author": "dwijnand", "repo": "coq-popl08-tutorial", "sha": "f78bb7957e366acd7575856224da53bbb8b11acf", "save_path": "github-repos/coq/dwijnand-coq-popl08-tutorial", "path": "github-repos/coq/dwijnand-coq-popl08-tutorial/coq-popl08-tutorial-f78bb7957e366acd7575856224da53bbb8b11acf/Fsub_Lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5117166047041652, "lm_q1q2_score": 0.2598557630174469}}
{"text": "(* Copyright (c) Akira Kawata All rights reserved. *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom Coq Require Import Strings.String.\nFrom Coq Require Import Strings.Ascii.\nFrom Coq Require Import Lists.List.\nFrom Coq Require Import Program.Basics.\nFrom Egison Require Import Maps.\n\nModule Egison.\n\n  Definition varid := string.\n\n   Inductive exp : Type :=\n  | evar : varid -> exp\n  | eint : nat -> exp\n  (* | tlmb : varid -> exp -> exp *)\n  (* | tapp : exp -> exp -> exp *)\n  | etpl : exp -> exp -> exp\n  | ecll : list exp -> exp\n  | epair : exp -> exp -> exp\n  | emal : exp -> exp -> (ptn * exp) -> exp\n  | esm : exp\n  | emtc : (list (pptn * exp * (list (dptn * exp)))) -> exp\n  | etplmtc : exp -> exp -> exp\n  with ptn : Type :=\n  | pwld : ptn\n  | pvar : varid -> ptn\n  | pval : exp -> ptn\n  | ppair : ptn -> ptn -> ptn\n with pptn : Type :=\n  | ppdol : pptn\n  | ppvar : varid -> pptn\n  | pppair : pptn -> pptn -> pptn\n  with dptn : Type :=\n  | dpvar :  varid -> dptn\n  | dppair :  dptn -> dptn -> dptn.\n\n   Scheme exp_m_ind  := Minimality for exp Sort Prop\n     with ptn_m_ind := Minimality for ptn Sort Prop\n     with pptn_m_ind := Minimality for pptn Sort Prop\n     with dptn_m_ind := Minimality for dptn Sort Prop.\n\n   Combined Scheme exp_all_ind from exp_m_ind, ptn_m_ind, pptn_m_ind, dptn_m_ind.\n   \n   Inductive ty : Type :=\n   | tint : ty\n   | ttpl : ty -> ty -> ty\n   | tcll : ty -> ty\n   | tpair : ty -> ty -> ty\n   | tmtc : list ty -> ty\n   | tptn : ty -> ty\n   | tpptn : ty -> list ty -> ty\n   | tdptn : ty -> ty.\n\n  (* Definition ppex1 := ppdol : pptn. *)\n\n  Definition env := partial_map exp.\n  Definition tenv := partial_map ty.\n\n  (* Definition mlcssize (f : exp -> nat) (mcl : pptn * exp * (list (dptn * exp))) : nat := *)\n  (*   let '(_, m1, l) := mcl in *)\n  (*   max (f m1) (fold_left max (map (compose f snd) l) 0). *)\n\n  (* Fixpoint expsize (m: exp) : nat := *)\n  (*   match m with *)\n  (*   | evar _ => 1 *)\n  (*   | eint _ => 1 *)\n  (*   (* | tlmb _ n => 1 + expsize n *) *)\n  (*   (* | tapp n1 n2 => 1 + max (expsize n1) (expsize n2) *) *)\n  (*   | etpl ms => 1 + fold_left max (map expsize ms) 0 *)\n  (*   | ecll ms => 1 + fold_left max (map expsize ms) 0 *)\n  (*   | epair m1 m2 => 1 + max (expsize m1) (expsize m2) *)\n  (*   | emal m1 m2 pts => 1 + max (max (expsize m1) (expsize m2)) (fold_left max (map (compose expsize snd) pts) 0) *)\n  (*   | esm => 1 *)\n  (*   | emtc mcl => 1 + fold_left max (map (mlcssize expsize) mcl) 0 *)\n  (*   end. *)\n\n  Definition mclsvalue (f : exp -> Prop) (mcl : pptn * exp * (list (dptn * exp))) :=\n    let '(_, m1, l) := mcl in (f m1) /\\ (List.Forall (fun m => f (snd m))) l.\n\n  Definition mclsexps (mcl : pptn * exp * (list (dptn * exp))) : list exp :=\n    let '(_, m1, l) := mcl in\n    m1 :: map (fun m => snd m) l.\n\n  Inductive value : exp -> Prop :=\n  | V_Var : forall i, value (evar i)\n  | V_Int : forall i, value (eint i)\n  | V_Tpl : forall m1 m2, value m1 -> value m2 -> value (etpl m1 m2)\n  | V_Cll : forall ms, Forall value ms -> value (ecll ms)\n  | V_Pair : forall m1 m2, value m1 /\\ value m2 -> value (epair m1 m2)\n  | V_Mal : forall m1 m2 pt, value m1 -> value m2 -> value (snd pt) -> value (emal m1 m2 pt)\n  | V_Mtc : forall mcls, Forall value (concat (map mclsexps mcls)) -> value (emtc mcls)\n  | V_Tplmtc : forall m1 m2, value m1 -> value m2 -> value (etplmtc m1 m2).\n  (* | V_Lmb : forall i m, value (tlmb i m) *)\n\n  Import ListNotations.\n\n  Definition ms : Type := ((list (ptn * exp * env * exp)) * env * env).\n  Definition ma : Type := (ptn * exp * env * exp).\n\n  Fixpoint filtersome {A: Type} (l: list (option A)) : list A :=\n    match l with\n    | [] => []\n    | (Some v)::r => v::filtersome r\n    | None::r => filtersome r\n    end.\n\n  Inductive same_length_list {A B: Type} : (list A) -> (list B) -> Prop :=\n  | sll_nil : same_length_list [] []\n  | sll_cons : forall h1 h2 l1 l2, same_length_list l1 l2 -> same_length_list (h1::l1) (h2::l2).\n\n  Inductive same_length_list3 {A B C: Type} : (list A) -> (list B) -> (list C) -> Prop :=\n  | sll_nil3 : same_length_list3 [] [] []\n  | sll_cons3 : forall h1 h2 h3 l1 l2 l3, same_length_list3 l1 l2 l3 -> same_length_list3 (h1::l1) (h2::l2) (h3::l3).\n\n  Fixpoint zip {A B: Type} (l1:list A)  (l2: list B) : (list (A*B)) :=\n    match (l1, l2) with\n    | ([], _) => []\n    | (_, []) => []\n    | (h1::r1, h2::r2) => (h1,h2) :: zip r1 r2\n    end.\n\n  Fixpoint zip3 {A B C: Type} (l1:list A)  (l2: list B) (l3: list C) : (list (A*B*C)) :=\n    match (l1, l2, l3) with\n    | ([], _, _) => []\n    | (_, [], _) => []\n    | (_, _, []) => []\n    | (h1::r1, h2::r2, h3::r3) => (h1,h2,h3) :: zip3 r1 r2 r3\n    end.\n\n  Fixpoint zip4 {A B C D: Type} (l1:list A)  (l2: list B) (l3: list C) (l4: list D) : (list (A*B*C*D)) :=\n    match (l1, l2, l3, l4) with\n    | ([], _, _, _) => []\n    | (_, [], _, _) => []\n    | (_, _, [], _) => []\n    | (_, _, _, []) => []\n    | (h1::r1, h2::r2, h3::r3, h4::r4) => (h1,h2,h3,h4) :: zip4 r1 r2 r3 r4\n    end.\n\n  Definition is_epair (t: exp) : Prop :=\n    match t with\n    | (epair _ _) => True\n    | _ => False\n    end.\n\n  Definition is_pval (p: ptn) : Prop :=\n    match p with\n    | (pval _) => True\n    | _ => False\n    end.\n\n  Definition is_ppair (p: ptn) : Prop :=\n    match p with\n    | (ppair _ _) => True\n    | _ => False\n    end.\n\n  Inductive type : (tenv * exp * ty * tenv) -> Prop :=\n  | T_Var : forall Gamma s T, Gamma s = Some T -> type (Gamma, (evar s), T, Gamma)\n  | T_Int : forall Gamma i, type (Gamma, (eint i), tint, Gamma)\n  | T_Pair : forall Gamma e1 T1 e2 T2, type (Gamma, e1, T1, Gamma) ->\n                                  type (Gamma, e2, T2, Gamma) ->\n                                  type (Gamma, (epair e1 e2), (tpair T1 T2), Gamma)\n  | T_Tpl : forall Gamma e1 T1 e2 T2, type (Gamma, e1, T1, Gamma) ->\n                                 type (Gamma, e2, T2, Gamma) ->\n                                 type (Gamma, (etpl e1 e2), (ttpl T1 T2), Gamma)\n  | T_Cll : forall Gamma es T, Forall type (map (fun e => (Gamma,e,T,Gamma)) es) ->\n                          type (Gamma, (ecll es), (tcll T), Gamma)\n  | T_Sm : forall Gamma T, type (Gamma, esm, (tmtc [T]), Gamma)\n  | T_TplMtc : forall Gamma e1 T1 e2 T2 T12,\n      type (Gamma, e1, (tmtc T1), Gamma) ->\n      type (Gamma, e2, (tmtc T2), Gamma) ->\n      T12 = T1 ++ T2 ->\n      type (Gamma, (etplmtc e1 e2), (tmtc T12), Gamma)\n  | T_Mtc : forall Gamma mcls T, Forall typemcl (map (fun m => (Gamma, m, T)) mcls) ->\n                            type (Gamma, emtc mcls, tmtc [T], Gamma)\n  | T_Mal : forall Gamma e1 e2 e3 T1 T2 Gamma1 p,\n      type (Gamma, e1, T1, Gamma) ->\n      type (Gamma, e2, (tmtc [T1]), Gamma) ->\n      typeptn (Gamma, p, (tptn T1), Gamma1) ->\n      type (Gamma1, e3, T2, Gamma1) ->\n      type (Gamma, emal e1 e2 (p, e3), tcll T2, Gamma)\n  with typemcl : (tenv * (pptn * exp * (list (dptn * exp))) * ty) -> Prop :=\n  | TM_1 : forall Gamma pp M dpN_v T S,\n      typepptn (Gamma, pp, tpptn T [S], Gamma) ->\n      type (Gamma, M, tmtc [S], Gamma) ->\n      Forall typedpN (map (fun dpN => (Gamma, dpN, T, [S])) dpN_v) ->\n      typemcl (Gamma, (pp, M, dpN_v), T)\n  | TM_2 : forall Gamma pp M dpN_v T S1 S2,\n      typepptn (Gamma, pp, tpptn T [S1;S2], Gamma) ->\n      type (Gamma, M, tmtc [S1;S2], Gamma) ->\n      Forall typedpN (map (fun dpN => (Gamma, dpN, T, [S1;S2])) dpN_v) ->\n      typemcl (Gamma, (pp, M, dpN_v), T)\n  with typedpN : (tenv * (dptn * exp) * ty * list ty) -> Prop :=\n  | TDN_1 : forall Gamma dp N T S Gamma1,\n      typedptn (Gamma, dp, tdptn T, Gamma1) -> type (Gamma1, N, tcll S, Gamma1) ->\n      typedpN (Gamma, (dp, N), T, [S])\n  | TDN_2 : forall Gamma dp N T S1 S2 Gamma1,\n      typedptn (Gamma, dp, tdptn T, Gamma1) -> type (Gamma1, N, tcll (ttpl S1 S2), Gamma1) ->\n      typedpN (Gamma, (dp, N), T, [S1;S2])\n  with typeptn : (tenv * ptn * ty * tenv) -> Prop :=\n  | TP_Wld : forall Gamma T, typeptn (Gamma, pwld, T, Gamma)\n  | TP_Var : forall Gamma s T, typeptn (Gamma, (pvar s), (tptn T), s |-> T ; Gamma)\n  | TP_Val : forall Gamma e T, type (Gamma, e, T, Gamma) -> typeptn (Gamma, pval e, tptn T, Gamma)\n  | TP_Pair : forall Gamma p1 T1 p2 T2 Gamma1 Gamma2,\n      typeptn (Gamma, p1, tptn T1, Gamma1) ->\n      typeptn (Gamma1, p2, tptn T2, Gamma2) ->\n      typeptn (Gamma, ppair p1 p2, tptn (tpair T1 T2), Gamma2)\n  with typepptn : (tenv * pptn * ty * tenv) -> Prop :=\n  | TPP_Dol : forall Gamma T, typepptn (Gamma, ppdol, tpptn T [T], Gamma)\n  | TPP_Var : forall Gamma s T, typepptn (Gamma, ppvar s, tpptn T [], Gamma)\n  | TPP_Pair : forall Gamma pp1 T1 S1 pp2 T2 S2 S12,\n      typepptn (Gamma, pp1, tpptn T1 S1, Gamma) ->\n      typepptn (Gamma, pp2, tpptn T2 S2, Gamma) ->\n      S12 = S1 ++ S2 ->\n      typepptn (Gamma, pppair pp1 pp2, tpptn (tpair T1 T2) S12, Gamma)\n  with typedptn : (tenv * dptn * ty * tenv) -> Prop :=\n  | TDP_Var : forall Gamma s T, typedptn (Gamma, (dpvar s), (tdptn T), s |-> T ; Gamma)\n  | TDP_Pair : forall Gamma dp1 T1 Gamma1 dp2 T2 Gamma2,\n      typedptn (Gamma, dp1, tdptn T1, Gamma1) ->\n      typedptn (Gamma, dp2, tdptn T2, Gamma2) ->\n      typedptn (Gamma, dppair dp1 dp2, tdptn (tpair T1 T2), Gamma1 @@ Gamma2).\n\n  Scheme type_m_ind  := Minimality for type Sort Prop\n    with typemcl_m_ind := Induction for typemcl Sort Prop\n    with typedpN_m_ind := Induction for typedpN Sort Prop\n    with typeptn_m_ind := Minimality for typeptn Sort Prop\n    with typepptn_m_ind := Induction for typepptn Sort Prop\n    with typedptn_m_ind := Induction for typedptn Sort Prop.\n\n  Combined Scheme type_all_ind from type_m_ind, typemcl_m_ind, typedpN_m_ind, typeptn_m_ind, typepptn_m_ind, typedptn_m_ind.\n  Check type_all_ind.\n\n  Theorem T_Int_example : type (empty, (eint 10), tint, empty).\n  Proof.\n    econstructor.\n  Qed.\n\n  Inductive eval : (env * exp * exp)-> Prop :=\n  | E_VarIn : forall i Gamma t, (Gamma i) = Some t -> eval (Gamma, (evar i), t)\n  | E_VarOut : forall i Gamma, (Gamma i) = None -> eval (Gamma, (evar i), (evar i))\n  | E_Int : forall i e, eval (e, (eint i), (eint i))\n  | E_Tpl : forall Gamma t1 t2 v1 v2, eval (Gamma, t1, v1) -> eval (Gamma, t2, v2) -> eval (Gamma, etpl t1 t2, etpl v1 v2)\n  | E_Cll : forall e ts vs, same_length_list ts vs ->\n                      Forall eval (map (fun tpl => let '(t,v) := tpl in (e,t,v)) (zip ts vs)) -> eval (e, (ecll ts), (ecll vs))\n  | E_Pair : forall e t1 t2 v1 v2, eval (e, t1, v1) -> eval (e, t2, v2) -> eval (e, (epair t1 t2), (epair v1 v2))\n  | E_Sm : forall Gamma, eval (Gamma, esm, esm)\n  (* | emtc : forall Gamma (ts: (list (pptn * exp * (list (dptn * exp))))), eval Gamma ((emtc ts), (emtc vs)) *)\n  | E_Tplmtc : forall Gamma t1 t2 v1 v2, eval (Gamma, t1, v1) -> eval (Gamma, t2, v2) -> eval (Gamma, etplmtc t1 t2, etplmtc v1 v2)\n  | E_Emal : forall Gamma M N p L v_v v m_m m_e Delta_v, same_length_list Delta_v v_v -> eval (Gamma, M,v) -> evalmtc Gamma N [(m_m, m_e)] -> evalms3 [[([(p,m_m,m_e,v)], Gamma, empty)]] Delta_v ->\n                                                  Forall eval (map (fun t => let '(d,v) := t in (Gamma @@ d, L, v)) (zip Delta_v v_v)) ->\n                                                  eval (Gamma, (emal M N (p, L)), ecll v_v)\n\n  with evalmtc : env -> exp -> list (exp * env) -> Prop :=\n  | Emtc_Sm : forall Gamma, evalmtc Gamma esm [(esm, Gamma)]\n  | Emtc_Mtc : forall Gamma l, evalmtc Gamma (emtc l) [((emtc l), Gamma)]\n  | Emtc_Tpl : forall Gamma m1 m2 n1 n2, eval (Gamma, (etplmtc m1 m2), (etplmtc n1 n2)) -> evalmtc Gamma (etplmtc m1 m2) [(n1, Gamma); (n2, Gamma)]\n\n  with evaldp : dptn -> exp -> option env -> Prop :=\n  | Edp_Var : forall z v, value v -> evaldp (dpvar z) v (Some (z |-> v))\n  | Edp_Pair : forall p1 p2 v1 v2 g1 g2,\n      value v1 -> value v2 -> evaldp p1 v1 (Some g1) -> evaldp p2 v2 (Some g2) ->\n      evaldp (dppair p1 p2) (epair v1 v2) (Some (g1 @@ g2))\n  | Edp_Fail : forall t p1 p2, not (is_epair t) -> evaldp (dppair p1 p2) t None\n\n  with evalpp : pptn -> env -> ptn -> option ((list ptn) * env) -> Prop :=\n  | Epp_Dol : forall g p, evalpp ppdol g p (Some ([p], empty))\n  | Epp_Var : forall i g m v, eval (g, m, v) -> evalpp (ppvar i) g (pval m) (Some ([], (i |-> v)))\n  | Epp_Pair : forall pp1 pp2 p1 p2 g pv1 pv2 g1 g2,\n                evalpp pp1 g p1 (Some (pv1,g1)) -> evalpp pp2 g p2 (Some (pv2,g2)) ->\n                evalpp (pppair pp1 pp2) g (ppair p1 p2) (Some ((pv1 ++ pv2), (g1 @@ g2)))\n  | Epp_VarFail : forall y g p, not (is_pval p) -> evalpp (ppvar y) g p None\n  | Epp_PairFail : forall pp1 pp2 p g, not (is_ppair p) -> evalpp (pppair pp1 pp2) g p None\n\n  with evalms1 : ((list ms) * option env * option (list ms)) -> Prop :=\n  | Ems1_Nil : evalms1 ([], None, None)\n  | Ems1_ANil : forall sv g d, evalms1 ((([],g,d)::sv), (Some d), (Some sv))\n  | Ems1 : forall p m mg v av g d sv avv d1,\n        evalma (g @@ d) (p,m,mg,v) avv d1 ->\n        evalms1 ((((p,m,mg,v)::av, g, d)::sv), None, (Some ((map (fun ai => (ai ++ av, g, d @@ d1)) avv) ++ sv)))\n\n  with evalms2 : (list (list ms)) -> (list env) -> (list (list ms)) -> Prop :=\n  | Ems2 : forall svv gvv svv1 gvv1 svv2,\n      same_length_list3 svv gvv svv1 ->\n      Forall evalms1 (zip3 svv gvv svv1) ->\n      (filtersome gvv) = gvv1 ->\n      (filtersome svv1) = svv2 ->\n      evalms2 svv gvv1 svv2\n\n  with evalms3 : (list (list ms)) -> (list env) -> Prop :=\n  | Ems3_Nil : evalms3 [[]] []\n  | Ems3 : forall svv gv svv1 dv gdv, evalms2 svv gv svv1 -> evalms3 svv1 dv -> gdv = gv ++ dv ->\n                             evalms3 svv gdv\n\n  with evalma : env -> ma -> list (list ma) -> env -> Prop :=\n  | Ema_Some : forall x g v d, evalma g (pvar x, esm, d, v) [[]] (x |-> v)\n  | Ema_PpFail : forall p g pp m sv pv d v avv g1,\n      evalpp pp g p None -> evalma g (p,(emtc pv),d,v) avv g1 ->\n      evalma g (p,emtc ((pp,m,sv)::pv),d,v) avv g1\n  | Ema_DpFail : forall p g pp m dp n sv pv d v pv1 d1 avv g1,\n      evalpp pp g p (Some (pv1, d1)) -> evaldp dp v None ->\n      evalma g (p, emtc ((pp,m,sv)::pv),d,v) avv g1 ->\n      evalma g (p, emtc ((pp,m,(dp,n)::sv)::pv),d,v) avv g1\n  | Ema : forall p Gamma pp M dp N sigma_v Delta v phi1_v p1_v Delta1 Delta2 v1_vv m1_v,\n      evalpp pp Gamma p (Some (p1_v, Delta1)) ->\n      evaldp dp v (Some Delta2) ->\n      eval (Delta @@ Delta1 @@ Delta2, N, ecll v1_vv) ->\n      evalmtc Gamma M m1_v ->\n      evalma Gamma (p, emtc ((pp,M,(dp,N)::sigma_v)::phi1_v), Delta, v)\n             ((map (fun tpl => match tpl with\n                              | (etpl v11 v12) => map (fun t => let '(v1, (m1, Gamma1), p1) := t in (p1,m1,Gamma1,v1)) (zip3 [v11;v12] m1_v p1_v)\n                              | v11 => map (fun t => let '(v1, (m1, Gamma1), p1) := t in (p1,m1,Gamma1,v1)) (zip3 [v11] m1_v p1_v)\n                              end\n                   ) v1_vv)) empty.\n\n  (* Following Egison code is translated into Coq as follows. *)\n  (* (define $unordered-pair *)\n  (*   (matcher *)\n  (*     {[<pair $ $> [something something] *)\n  (*       {[[$x $y] {[x y] [y x]}]}] *)\n  (*      [$ something *)\n  (*       {[$tgt {tgt}]}]})) *)\n\n  (* (match-all [1 2] unordered-pair {[<pair $a $b> [a b]]}) ===> {[1,2] [2,1]} *)\n\n  Open Scope string_scope.\n  Definition unordered_pair: exp :=\n    (emtc [(pppair ppdol ppdol, etplmtc esm esm,\n            [(dppair (dpvar \"x\") (dpvar \"y\"), (ecll [(etpl (evar \"x\") (evar \"y\")); etpl (evar \"y\") (evar \"x\")]))]);\n           (ppdol, esm,\n            [(dpvar \"tgt\", ecll [evar \"tgt\"])])]).\n\n  Definition match_all_example: exp :=\n    (emal (epair (eint 1) (eint 2)) unordered_pair (ppair (pvar \"a\") (pvar \"b\"),etpl (evar \"a\") (evar \"b\"))).\n  Theorem unordered_pair_example : eval (empty, match_all_example, ecll [etpl (eint 1) (eint 2);etpl (eint 2) (eint 1)]).\n  Proof.\n    econstructor.\n    - repeat econstructor.\n    - repeat econstructor.\n    - repeat econstructor.\n    - econstructor.\n      + econstructor.\n        * repeat econstructor.\n        * econstructor.\n          -- econstructor.\n             eapply Ema.\n             --- repeat econstructor.\n             --- repeat econstructor.\n             --- repeat econstructor.\n             --- repeat econstructor.\n          -- repeat constructor.\n        * repeat constructor.\n        * repeat constructor.\n      + repeat econstructor.\n      + repeat econstructor.\n    - repeat econstructor.\n  Qed.\n  \n  Theorem unordered_pair_type_example : type (empty, match_all_example, tcll (ttpl tint tint), empty).\n  Proof.\n    econstructor.\n    - repeat econstructor.\n    - econstructor.\n      econstructor.\n      + eapply TM_2.\n        * repeat econstructor.\n        * repeat econstructor.\n        * repeat econstructor.\n      + repeat econstructor.\n    - repeat econstructor.\n    - repeat econstructor.\n  Qed.\nEnd Egison.\n", "meta": {"author": "akawashiro", "repo": "formalized-egison", "sha": "19f1ceef96c70117105ddba49624a9ee1780a476", "save_path": "github-repos/coq/akawashiro-formalized-egison", "path": "github-repos/coq/akawashiro-formalized-egison/formalized-egison-19f1ceef96c70117105ddba49624a9ee1780a476/Egison.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.5117166047041652, "lm_q1q2_score": 0.25985576301744684}}
{"text": "From MetaCoq.Template Require Import All.\nFrom MetaCoq.Utils Require Import utils.\nImport MCMonadNotation.\n\n\nModule Type A.\n  Parameter x : nat.\nEnd A.\n\nModule B (X : A) (Y : A).\n\n  MetaCoq Test Quote Y.x.\n  MetaCoq Unquote Definition uuu :=\n          (tConst (MPbound [\"modules_sections\"; \"TestSuite\"; \"MetaCoq\"] \"Y\" 1, \"x\") []).\n\n\n  MetaCoq Run (bc <- tmQuote X.x ;;\n               tmPrint bc ;;\n               bc <- tmUnquote bc ;;\n               tmPrint bc).\n\nEnd B.\n\n\nModule Type C (X : A) (Y : A).\n  MetaCoq Run (bc <- tmQuote X.x ;;\n               tmPrint bc ;;\n               bc <- tmUnquote bc ;;\n               tmPrint bc).\nEnd C.\n\n\nSection S.\n\n  Definition b := forall X, X.\n  Definition c := Set.\n  (* Set Printing All. Set Printing Universes. *)\n  MetaCoq Run (bc <- tmQuote b ;;\n                    tmPrint bc ;;\n                    tmMkDefinition \"bb\" bc ;;\n                    tmPrint \"lol\").\n  Check bb.\n\n  Variable x : nat.\n  MetaCoq Run (bc <- tmQuote x ;;\n                    tmPrint bc ;;\n                    tmMkDefinition \"bx\" bc ;;\n                    tmPrint \"lol\").\n\n  Check bx.\n\nEnd S.\n\nMetaCoq Run (bc <- tmQuote b ;;\n                tmPrint bc ;;\n                bc <- tmUnquote bc ;;\n                tmPrint bc).\n\nRequire Import MetaCoq.Template.Pretty.\nCheck (eq_refl : print_term (empty_ext empty_global_env) [] true\n                      (tConst (MPfile [\"test\"; \"Examples\"; \"MetaCoq\"], \"b\") [])\n                 = \"MetaCoq.Examples.test.b\").\n\nModule S.\n\n  Definition b := forall X, X.\n  MetaCoq Run (bc <- tmQuote b ;;\n               tmPrint bc ;;\n               bc <- tmUnquote bc ;;\n               tmPrint bc).\nEnd S.\n\nMetaCoq Run (bc <- tmQuote S.b ;;\n             tmPrint bc ;;\n             bc <- tmUnquote bc ;;\n             tmPrint bc).\n\n\n\nMetaCoq Test Quote my_projT2.\nMetaCoq Test Unquote\n     (Ast.tConstruct (mkInd (MPfile [\"Datatypes\"; \"Init\"; \"Coq\"], \"nat\") 0) 0 []).\nMetaCoq Unquote Definition zero_from_syntax\n  := (Ast.tConstruct (mkInd (MPfile [\"Datatypes\"; \"Init\"; \"Coq\"], \"nat\") 0) 0 []).\n\nExisting Class nat.\n\nModule Type X.\n  Definition t : nat := 0.\n  Parameter t' : nat.\n  Parameter t'' : nat.\n  Print Instances nat.\n  MetaCoq Run (tmLocate1 \"t\" >>= tmExistingInstance global).\n  MetaCoq Run (tmLocate1 \"t'\" >>= tmExistingInstance global).\n  Print Instances nat.\nEnd X.\n\nSection XX.\n  Variable u : nat.\n  Fail MetaCoq Run (tmLocate1 \"u\" >>= tmExistingInstance global).\n  Print Instances nat.\nEnd XX.\n\nModule Y (A : X).\n  Print Instances nat.\n  MetaCoq Run (tmLocate1 \"t''\" >>= tmExistingInstance global).\n  Print Instances nat.\nEnd Y.\n\nMetaCoq Run (tmLocateModule1 \"B\" >>= tmPrint).\nMetaCoq Run (tmLocateModule1 \"S\" >>= tmPrint).\nMetaCoq Run (tmLocateModType1 \"X\" >>= tmPrint).\nFail MetaCoq Run (tmLocateModType1 \"B\" >>= tmPrint).\nFail MetaCoq Run (tmLocateModType1 \"modules_sections.S\" >>= tmPrint). (* finds (MPdot (MPfile [\"FMapInterface\"; \"FSets\"; \"Coq\"]) \"S\") if unqualified *)\nFail MetaCoq Run (tmLocateModule1 \"X\" >>= tmPrint).\n", "meta": {"author": "MetaCoq", "repo": "metacoq", "sha": "c340242b43ebe26f3bacb1c72ef82b8ca61da632", "save_path": "github-repos/coq/MetaCoq-metacoq", "path": "github-repos/coq/MetaCoq-metacoq/metacoq-c340242b43ebe26f3bacb1c72ef82b8ca61da632/test-suite/modules_sections.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.25982405718051205}}
{"text": "(* TLC in Coq\n *\n * Module: tlc.utility.option\n * Purpose: Monad hierarchy typeclass instances for option.\n *)\n\nRequire Import mathcomp.ssreflect.ssreflect.\nRequire Import mathcomp.ssreflect.ssrfun.\nRequire Import tlc.utility.monad.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* Functor instance for option *)\n#[refine]\nInstance option_functor : Functor option := {\n  map _ _ f x := if x is Some x' then Some (f x') else None;\n}.\nProof.\n  (* map_id *)\n  {\n    by move=> ?; case.\n  }\n\n  (* map_comp *)\n  {\n    by move=> ?????; case.\n  }\nDefined.\n\n(* Applicative instance for option *)\n#[refine]\nInstance option_applicative : Applicative option := {\n  pure := fun a x => Some x;\n  apply _ _ f x :=\n    match f, x with\n    | Some f', Some x' => Some (f' x')\n    | _, _ => None\n    end;\n}.\nProof.\n  (* apply_left_id *)\n  {\n    by move=> ?; rewrite /left_id; case.\n  }\n\n  (* apply_homo *)\n  {\n    by [].\n  }\n\n  (* apply_inter *)\n  {\n    by [].\n  }\n\n  (* apply_comp *)\n  {\n    by move=> ???; case=> [? |] [? |] [? |].\n  }\nDefined.\n\n(* Monad instance for option *)\n#[refine]\nInstance option_monad : Monad option := {\n  bind _ _ x f := if x is Some x' then f x' else None;\n}.\nProof.\n  (* bind_left_id *)\n  {\n    by [].\n  }\n\n  (* bind_right_id *)\n  {\n    by move=> ?; case=> [? | ].\n  }\n\n  (* bind_assoc *)\n  {\n    by move=> ?????; case=> [? | ].\n  }\nDefined.\n", "meta": {"author": "jzgriffin", "repo": "tlc", "sha": "58919b43a5a1db887237dbeee812664147d657d4", "save_path": "github-repos/coq/jzgriffin-tlc", "path": "github-repos/coq/jzgriffin-tlc/tlc-58919b43a5a1db887237dbeee812664147d657d4/tlc/utility/option.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.259824057180512}}
{"text": "(** * Reasoning principles for interpretable layered monads *)\n\n(* When we layer the [interp] combinator, we also intend certain structural\n  properties to hold at each layer of interpretation. Most importantly,\n  it should respect monadic operators such as [ret] and [bind] and interact\n  well with iteration.\n\n  Given an interpretable monad equipped with an appropriate instance of [eqmR],\n  we can state laws for the [trigger], [over], and [interp] functions that are\n  expected.\n\n  Thanks to the fact that iterative monad transformers form higher order functors\n  which are monad morphisms (as shown in [HFunctor.v]), we only need to prove\n  this structural property once and for all for each monad transformer. *)\n\n(* begin hide *)\nFrom Coq Require Import\n     Program\n     Setoid\n     Morphisms\n     RelationClasses.\n\nFrom Paco Require Import paco.\n\nFrom ITree.Basics Require Import\n     Basics Category CategoryKleisli CategoryKleisliFacts\n     HeterogeneousRelations\n     Tacs MonadFail.\n\nFrom ITree.Core Require Import\n     ITreeDefinition KTree KTreeFacts Subevent.\n\nFrom ITree.Eq Require Import\n     Eq UpToTaus Paco2.\n\nFrom ITree.Indexed Require Import\n     Sum Function Relation.\n\nFrom ITree.Interp Require Import\n     Interp HFunctor Handler TranslateFacts.\n\nFrom ITree.EqmR Require Import\n     EqmRMonad EqmRMonadT\n     Monads.ITree_weak\n     Monads.StateT Monads.ErrorT.\n\nFrom ExtLib Require Import\n     Structures.Functor\n     Structures.Monad.\n\nSet Primitive Projections.\n\nImport RelNotations.\nImport ITreeNotations.\nImport MonadNotation.\nImport CatNotations.\nLocal Open Scope relationH_scope.\nLocal Open Scope cat_scope.\nLocal Open Scope monad_scope.\n(* end hide *)\n\n(** *Structural laws for interpretation. *)\nSection interp_laws.\n\n  Context (T : (Type -> Type) -> Type -> Type)\n          (M : Type -> Type)\n          {T_HFunctor : HFunctor T}\n          {T_MonadT:MonadT T}\n          {T_MonadIter:(forall m : Type -> Type, Monad m -> MonadIter m -> MonadIter (T m))}\n          {M_Monad : Monad M}\n          {M_EqmR : EqmR M}\n          {M_MonadIter : MonadIter M}\n          {TM_Interp : Interp (T := T) itree M}.\n\n  Class InterpRet : Prop :=\n    interp_ret :\n      forall {E R} {f : E ~> M} (x: R),\n        eqmR eq (interp f (ret x)) (ret x : T M R).\n\n  Class InterpTrigger : Prop :=\n    interp_trigger :\n      forall {E R} (f : E ~> M) (e : E R),\n        eqmR eq (interp f (trigger e)) (morph (MT := T M) (f _ e) : T M R).\n\n  Class InterpOverTrigger : Prop :=\n      interp_over_trigger :\n      forall {E F G R} {S : F +? E -< G} {S_wf : Subevent_wf S}\n        {Tr : Trigger E M} (f : F ~> M) (e : F R),\n          eqmR eq\n              (interp (@over F G E M S _ f) (trigger e : T (itree G) R))\n              (morph (f _ e)).\n\n  Class InterpOverIgnoreTrigger : Prop :=\n    interp_over_ignore_trigger :\n      forall (A B C BC ABC : Type -> Type) {S : B +? C -< BC} {S' : A +? BC -< ABC}\n        {S_wf : Subevent_wf S} {S'_wf : Subevent_wf S'}\n        R (h : A ~> M) (e : B R) {Tr : Trigger BC M},\n      eqmR eq (m := T M)\n      (interp (IM := itree) (T := T) (I := ABC) (M := M) (over h) (trigger (E := B) e))\n      (morph (MT := T M) (trigger (E := BC) (inj1 e))).\n\n  Class InterpBind : Prop :=\n    interp_bind :\n      forall {E R S} (f : E ~> M) (k : R -> T (itree E) S) t,\n        eqmR eq (interp f (bind t k)) (bind (interp f t) (fun r => interp f (k r))).\n\n  Class InterpIter : Prop :=\n    interp_iter :\n      forall {E I R} (f : E ~> M) (t : I -> T (itree E) (I + R)) (t' : I -> T M (I + R)) (i:I),\n        (forall i, eqmR eq (interp f (t i)) (t' i))  ->\n          interp f (Basics.iter t i) ≈{ eq } Basics.iter t' i.\n\n  Class InterpProper : Prop :=\n    interp_proper :\n      forall {E} (h : E ~> M) R1 R2 (RR : R1 -> R2 -> Prop),\n      ProperH (eqmR (m := T (itree E)) RR ~~> eqmR (B := R2) RR)\n            (interp h (T0 := R1)) (interp h (T0 := R2)).\n\n  Class InterpLaws : Prop :=\n    { InterpLaws_InterpRet :> InterpRet;\n      InterpLaws_InterpTrigger :> InterpTrigger;\n      InterpLaws_InterpOverIgnoreTrigger :> InterpOverIgnoreTrigger;\n      InterpLaws_InterpBind :> InterpBind;\n      InterpLaws_InterpIter :> InterpIter;\n      InterpLaws_InterpProper :> InterpProper }.\n\nEnd interp_laws.\n\nArguments InterpLaws _ _ {_ _ _ _ _ _}.\nArguments interp_ret {_ _ _ _ _ _ _} [_ _].\nArguments interp_trigger {_ _ _ _ _ _ _} [_ _].\nArguments interp_over_trigger {_ _ _ _ _ _ _ _ _ _} [_ _] {_ _}.\nArguments interp_over_ignore_trigger {_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _} [_].\nArguments interp_bind {_ _ _ _ _ _ _} [_ _ _].\nArguments interp_iter {_ _ _ _ _ _ _} [_ _ _].\nArguments interp_proper {_ _ _ _ _ _ _} [_].\n\n#[global]\nExisting Instance itree_interp.\n\n(** *Nesting interpretation *)\n(* We can stack interpretation, in the sense that given a higher-order functor [T]\n   and iterative monad [M] (which is the semantic domain for interpreting an itree)\n   the interpretable monad instance can be derived for the interpretation from\n   [T (itree)] to [T M].\n\n   In order to define this function, we use the higher-order fmap [hfmap] and lift\n   the [itree_interp] function over the [T (itree)]. *)\n#[global] Instance stack_interp\n       {T : (Type -> Type) -> Type -> Type}\n       {M : Type -> Type}\n       {T_HFunctor : HFunctor T}\n       {M_Monad : IterativeMonad M}\n        : Interp itree M  | 10 :=\n  fun E h R t => hfmap (f := T) (itree_interp h) t.\n\n#[global] Instance Proper_eq_itree_interp_body (E M:Type->Type) `{WF_IterativeMonad M} (A:Type) (RR:A->A->Prop) (f:E~>M):\n  Proper (eq_itree RR ==> eqmR (sum_rel (eq_itree RR) RR)) (interp_body (E := E) (M := M) f A).\nProof.\n  repeat intro. unfold interp_body.\n  punfold H0. red in H0. remember (observe x); remember (observe y).\n  revert x y Heqi Heqi0.\n  induction H0; pclearbot; intros; subst; try inv CHECK.\n  - eapply eqmR_ret; eauto; typeclasses eauto.\n  - eapply eqmR_ret; eauto; try typeclasses eauto.\n  - eapply eqmR_bind_ProperH; try typeclasses eauto; [ reflexivity | ..]; intros; subst;\n      eapply eqmR_ret; eauto; typeclasses eauto.\nQed.\n\nSection InterpITree.\n\n  (** Unfolding of [interp]. *)\n  Definition _interp {E F R} (f : E ~> itree F) (ot : itreeF E R _)\n    : itree F R :=\n    match ot with\n    | RetF r => Ret r\n    | TauF t => Tau (interp f t)\n    | VisF e k => f _ e >>= (fun x => Tau (interp f (k x)))\n    end.\n\n  (** Unfold lemma. *)\n  Lemma unfold_interp {E F R} {f : E ~> itree F} (t : itree E R) :\n    interp f t ≅ (_interp f (observe t)).\n  Proof.\n    unfold interp, Basics.iter, MonadIter_itree. setoid_rewrite unfold_iter.\n    unfold interp_body.\n    destruct (observe t); cbn; try rewrite ?Eq.bind_bind;\n      rewrite ?Eq.bind_ret_l, ?bind_map.\n    all: try solve [tau_steps; reflexivity].\n    setoid_rewrite Eq.bind_ret_l. reflexivity.\n  Qed.\n\n  #[global]\n  Instance eq_itree_interp' {E F R} (f : E ~> itree F)\n    : Proper (eq_itree eq ==> eq_itree eq) (interp f (T0 := R)).\n  Proof.\n    repeat red.\n    ginit. pcofix CIH.\n    intros l r0 Hlr.\n    rewrite 2 unfold_interp.\n    punfold Hlr; red in Hlr.\n    destruct Hlr; cbn; subst; try discriminate; pclearbot; try (gstep; constructor; eauto with paco; fail).\n    guclo eqit_clo_bind. econstructor; eauto.\n    eapply reflexivity.\n    intros; subst.\n    gstep; econstructor; eauto with paco.\n  Qed.\n\n  #[global]\n  Instance eutt_interp {E F R} (f : E ~> itree F)\n    : Proper (eutt eq ==> eutt eq) (interp f (T0 := R)).\n  Proof.\n    repeat red.\n    ginit. pcofix CIH. intros.\n\n    rewrite !unfold_interp. punfold H0. red in H0.\n    induction H0; intros; subst; pclearbot; simpl.\n    - gstep. constructor. eauto.\n    - gstep. constructor. eauto with paco.\n    - guclo eqit_clo_bind; econstructor; eauto. eapply reflexivity.\n      intros; subst.\n      gstep; constructor; eauto with paco.\n    - rewrite tau_euttge, unfold_interp. auto.\n    - rewrite tau_euttge, unfold_interp. auto.\n  Qed.\n\n  #[global]\n  Definition eutt_interp' {E F : Type -> Type} {R1 R2 : Type} (RR: R1 -> R2 -> Prop) (f : E ~> itree F) :\n    ProperH (eutt RR ~~> eutt RR) (interp f (T0 := R1)) (interp f (T0 := R2)).\n  Proof.\n    repeat red.\n    einit.\n    ecofix CIH. intros.\n    rewrite !unfold_interp.\n    punfold H0.\n    induction H0; intros; subst; pclearbot; simpl.\n    - estep.\n    - estep.\n    - ebind; econstructor.\n      + reflexivity.\n      + intros; subst. estep. ebase.\n    - rewrite tau_euttge, unfold_interp. eauto.\n    - rewrite tau_euttge, unfold_interp. eauto.\n  Qed.\n\n  #[global]\n  Instance itree_morph_ret:\n    forall (E F : Type -> Type) (f : E ~> itree F),\n      MorphRet (itree E) (itree F) (itree_interp f).\n  Proof. repeat intro. setoid_rewrite unfold_interp. cbn.\n        apply eqit_Ret; eauto. Qed.\n\n  Lemma itree_interp_tau {E F R} {f : E ~> itree F} (t: itree E R):\n    eq_itree eq (interp f (Tau t)) (Tau (interp f t)).\n  Proof. rewrite unfold_interp. reflexivity. Qed.\n\n  Lemma itree_interp_vis {E F R} {f : E ~> itree F} U (e: E U) (k: U -> itree E R) :\n    eq_itree eq (interp f (Vis e k)) (ITree.bind (f _ e) (fun x => Tau (interp f (k x)))).\n  Proof. rewrite unfold_interp. reflexivity. Qed.\n\n  Lemma itree_interp_bind {E F R S}\n        (f : E ~> itree F) (t : itree E R) (k : R -> itree E S) :\n      interp f (ITree.bind t k)\n    ≅ ITree.bind (interp f t) (fun r => interp f (k r)).\n  Proof.\n    revert R t k. ginit. pcofix CIH; intros.\n    rewrite unfold_bind, (unfold_interp t).\n    destruct (observe t); cbn.\n    - rewrite Eq.bind_ret_l. apply reflexivity.\n    - rewrite bind_tau, !itree_interp_tau.\n      gstep. econstructor. eauto with paco.\n    - rewrite itree_interp_vis, Eq.bind_bind.\n      guclo eqit_clo_bind; econstructor; try reflexivity.\n      intros; subst.\n      rewrite bind_tau. gstep; constructor; eauto with paco.\n  Qed.\n\n  #[global]\n  Instance itree_morph_bind:\n    forall (E F : Type -> Type) (f : E ~> itree F),\n      MorphBind (itree E) (itree F) (itree_interp f).\n  Proof.\n    repeat intro. setoid_rewrite itree_interp_bind.\n    eapply eutt_clo_bind. eapply eutt_interp'; eauto.\n    intros. eapply eutt_interp'; eauto. eapply H0; eauto.\n  Qed.\n\n  #[global] Instance itree_MonadMorphism :\n    forall (E F : Type -> Type) (f : E ~> itree F),\n      MonadMorphism _ _ (itree_interp f).\n  Proof.\n    constructor; [constructor; try typeclasses eauto |..]; try typeclasses eauto.\n    repeat intro; eapply eutt_interp'; repeat intro; eauto.\n  Qed.\n\n  Lemma itree_interp_iter' {E F} (f : E ~> itree F) {I A}\n        (t  : I -> itree E (I + A))\n        (t' : I -> itree F (I + A))\n        (EQ_t : forall i, eq_itree eq (interp f (t i)) (t' i))\n    : forall i,\n      interp f (ITree.iter t i)\n    ≅ ITree.iter t' i.\n  Proof.\n    ginit. pcofix CIH; intros i.\n    rewrite 2 unfold_iter.\n    rewrite itree_interp_bind.\n    guclo eqit_clo_bind; econstructor; eauto.\n    { apply EQ_t. }\n    intros [] _ []; cbn.\n    - rewrite itree_interp_tau; gstep; constructor; auto with paco.\n    - setoid_rewrite unfold_interp. cbn. gstep; constructor; auto with paco.\n  Qed.\n\n  Lemma itree_interp_iter_eutt' {E F} (f : E ~> itree F) {I A}\n        (t  : I -> itree E (I + A))\n        (t' : I -> itree F (I + A))\n        (EQ_t : forall i, eutt eq (interp f (t i)) (t' i))\n    : forall i,\n      interp f (ITree.iter t i)\n    ≈ ITree.iter t' i.\n  Proof.\n    ginit. pcofix CIH; intros i.\n    rewrite 2 unfold_iter.\n    rewrite itree_interp_bind.\n    guclo eqit_clo_bind; econstructor; eauto.\n    { apply EQ_t. }\n    intros [] _ []; cbn.\n    - rewrite itree_interp_tau; gstep; constructor; auto with paco.\n    - setoid_rewrite unfold_interp. cbn. gstep; constructor; auto with paco.\n  Qed.\n\n  Lemma itree_interp_iter {E F} (f : E ~> itree F) {A B}\n        (t : A -> itree E (A + B)) a0\n    : interp f (iter (C := ktree E) t a0) ≅ iter (C := ktree F) (fun a => interp f (t a)) a0.\n  Proof.\n    unfold iter, Iter_Kleisli, Basics.iter, MonadIter_itree.\n    apply itree_interp_iter'.\n    reflexivity.\n  Qed.\n\n  #[global] Instance itree_IterMorphism:\n    forall (E F : Type -> Type) (f : E ~> itree F),\n      IterMorphism (itree_interp f).\n  Proof.\n    unfold IterMorphism. cbn.\n    ginit. gcofix CIH; intros. cbn.\n    setoid_rewrite unfold_iter at 2.\n    setoid_rewrite unfold_iter at 2. cbn.\n    pose proof @itree_interp_bind. setoid_rewrite H. clear H.\n    guclo eqit_clo_bind; econstructor; eauto.\n    - apply H0; eauto.\n    - intros [|] [ |] H; cbn; subst; inv H.\n      + setoid_rewrite itree_interp_tau.\n        gstep; constructor. gfinal. left. eapply CIH; eauto.\n      + pose proof @itree_morph_ret. cbn in H. unfold MorphRet in H.\n        unfold morph in H.\n        specialize (H E F f R _ eq r1 _ eq_refl).\n        gfinal. right. cbn in H.\n        eapply paco2_mon; eauto; intros; contradiction.\n  Qed.\n\n  #[global] Instance interp_laws_itree_interp {F}:\n    InterpLaws (fun x => x) (itree F) (TM_Interp := @itree_interp _ _ _).\n  Proof.\n    constructor; repeat intro.\n    - apply itree_morph_ret; auto.\n    - setoid_rewrite itree_interp_vis.\n      cbn. setoid_rewrite tau_eutt.\n      etransitivity.\n      eapply eutt_clo_bind. reflexivity.\n      intros; subst; apply itree_morph_ret; auto.\n      rewrite Eq.bind_ret_r; reflexivity.\n    - setoid_rewrite itree_interp_vis.\n      cbn. setoid_rewrite tau_eutt.\n      etransitivity.\n      eapply eutt_clo_bind. reflexivity.\n      intros; subst; apply itree_morph_ret; auto.\n      unfold over, cat, Cat_IFun, merge_E, case, split_E.\n      destruct S', S.\n      destruct S'_wf. red in iso_epi.\n      unfold over, cat, Cat_IFun in iso_epi.\n      unfold Subevent.merge_E, Subevent.split_E in iso_epi.\n      rewrite iso_epi. cbn.\n      rewrite Eq.bind_ret_r; reflexivity.\n    - setoid_rewrite itree_interp_bind; reflexivity.\n    - apply itree_interp_iter_eutt'; auto.\n    - eapply eutt_interp'; auto.\n  Qed.\n\nEnd InterpITree.\n\n(* Facts about [interp] *)\nSection Facts.\n\n  Context {T : (Type -> Type) -> Type -> Type} {M : Type -> Type}\n          {T_MonadT:MonadT T}\n          {T_HFunctor:HFunctor T}\n          {T_MonadIter:(forall m : Type -> Type, Monad m -> MonadIter m -> MonadIter (T m))}\n          {WF_IMT : WF_IterativeMonadT T  _ _}\n          {T_wf : @WF_HFunctor T _ _ _ _}\n          {M_Monad : Monad M}\n          {M_EqmR : EqmR M}\n          {M_MonadIter : MonadIter M}\n          {M_wf : WF_IterativeMonad M _ _ _}\n          {itree_monad_morphism : forall (E : Type -> Type) (f : E ~> M),\n              MonadMorphism _ _ (itree_interp (I := E) f)}\n          {itree_iter_morphism : forall (E : Type -> Type) (f : E ~> M),\n              IterMorphism (itree_interp (I := E) f)}.\n\n  #[local] Instance M_IM: IterativeMonad M. constructor; eauto. Defined.\n\n  (** * [interp] and constructors *)\n  (** These are specializations of [unfold_interp], which can be added as\n      rewrite hints. *)\n  Lemma _interp_ret {E R} (f : E ~> M) (x: R):\n    eqmR (m := T M) eq (interp f (ret x)) (ret x).\n  Proof.\n    unfold interp. unfold stack_interp.\n    pose proof (@hfmap_nat T _ _ _ _ _ _ _ _ _ _ _ _ _ (itree_interp (I := E) f) _).\n    destruct H.\n    eapply morph_ret; eauto.\n  Qed.\n\n  Ltac unfold_cat := unfold cat, Cat_Kleisli.\n\n  Lemma _interp_bind {E R S} (f : E ~> M) (k : R -> _ S) t:\n    eqmR (m := T M) eq (interp f (bind t k))\n        (bind (interp f t) (fun r => interp f (k r))).\n  Proof.\n    eapply MM_morph_bind; eauto; try typeclasses eauto.\n\n    Unshelve. 3 : exact eq.\n    all : intros; subst; eapply reflexivity.\n  Qed.\n\n  Lemma _interp_trigger {R E} (f : E ~> M) (e : E R) :\n    eqmR (m := T M) eq (interp f (trigger e)) (morph (f _ e)).\n  Proof.\n    { pose proof @hfmap_lift as Hlift.\n      specialize (Hlift T _ _ _).\n\n      specialize (Hlift _ _ R (itree E) M).\n      specialize (Hlift _ _).\n      specialize (Hlift _ _ _ _ _ _ (itree_interp f)).\n      etransitivity.\n      eapply Hlift; typeclasses eauto.\n\n      eapply morph_proper; try typeclasses eauto.\n\n      unfold ITree.trigger. unfold interp.\n      unfold Basics.iter, MonadIter_itree, Kleisli_MonadIter.\n      pose proof (iter_unfold (C := Kleisli M)) as Hunfold.\n      specialize (Hunfold _ _ (interp_body f R)).\n      specialize (Hunfold (trigger e)).\n      unfold_cat; cbn. unfold iter, Iter_Kleisli in Hunfold. rewrite Hunfold.\n      unfold_cat. unfold case_, Case_Kleisli, Function.case_sum.\n\n      eapply Proper_eqmR_eq_impl; try typeclasses eauto.\n      2 : symmetry; eapply (bind_ret_r (f R e)).\n      2 : reflexivity.\n      unfold id_.\n\n      eapply Proper_bind.\n      { unfold interp_body; cbn. setoid_rewrite <- bind_ret_r at 5.\n        eapply Proper_bind. unfold id_. reflexivity.\n        all : intros; subst. Unshelve.\n        2 : exact(fun x y => match x with\n                          | inl a => a = Ret y\n                          | _ => False end).\n        all : eapply eqmR_ret; try typeclasses eauto; try reflexivity. }\n      all : intros; cbn; destruct a1; inv H.\n      { unfold Basics.iter, MonadIter_itree. clear Hunfold.\n        pose proof (iter_unfold (C := Kleisli M)) as Hunfold.\n        specialize (Hunfold _ _ (interp_body f R) (ret a2)).\n        unfold iter, Iter_Kleisli, Basics.iter, MonadIter_itree in Hunfold.\n        rewrite Hunfold.\n        unfold_cat; cbn. rewrite bind_ret_l. cbn.\n        apply eqmR_ret; eauto.\n        typeclasses eauto. } }\n  Qed.\n\n\n  Lemma _interp_over_trigger:\n    forall (E F : Type -> Type) (R : Type) (G : Type -> Type) (S : E +? G -< F)\n      (S_wf : Subevent_wf S)\n      (M_Trigger : Trigger G M)\n      (f : E ~> M) (e : E R),\n      interp (over f) (trigger e : T (itree F) R) ≋ morph (f _ e).\n  Proof.\n    intros E F R G S ? M_Trigger f e.\n    { pose proof @hfmap_lift as Hlift.\n      unfold interp, stack_interp.\n      specialize (Hlift T _ _ _).\n      specialize (Hlift _ _  R _ _ _ _ _ _ _ _ _ _ (itree_interp (over f)) _).\n      etransitivity.\n\n      eapply Hlift; typeclasses eauto.\n\n      eapply morph_proper; try typeclasses eauto.\n\n      unfold ITree.trigger. unfold interp.\n      unfold Basics.iter, MonadIter_itree, Kleisli_MonadIter.\n      pose proof (iter_unfold (C := Kleisli M)) as Hunfold.\n      specialize (Hunfold _ _ (interp_body (over f) R)).\n      specialize (Hunfold (trigger e)).\n      unfold_cat; cbn. unfold iter, Iter_Kleisli in Hunfold. rewrite Hunfold.\n      unfold_cat. unfold case_, Case_Kleisli, Function.case_sum.\n\n      eapply Proper_eqmR_eq_impl; try typeclasses eauto.\n      3 : reflexivity.\n      unfold id_.\n\n      eapply Proper_bind.\n      { unfold interp_body; cbn. setoid_rewrite <- bind_ret_r.\n        rewrite bind_bind. setoid_rewrite bind_ret_r.\n        eapply Proper_bind. unfold id_. reflexivity.\n        all : intros; subst. Unshelve.\n        3 : exact (fun x => ret (inl (Ret x))).\n        reflexivity. shelve. }\n      all: intros; subst.\n      Unshelve.\n      3 : exact (fun a2 =>\n          match a2 with\n          | inl a => Basics.iter (interp_body (over f) R) a\n          | inr b => Id_Kleisli R b\n          end).\n      reflexivity.\n      rewrite bind_bind. setoid_rewrite bind_ret_l.\n      setoid_rewrite <- bind_ret_r at 1.\n      eapply eqmR_bind_ProperH_simple; [typeclasses eauto | ..]; intros; subst.\n      { unfold over. unfold inj1, inl_, Inl_sum1, case.\n        unfold_cat; unfold Cat_IFun.\n        clear Hunfold.\n        pose proof (iter_unfold (C := Kleisli M)) as Hunfold.\n        specialize (Hunfold _ _ (interp_body (over f) R)).\n        unfold iter, Iter_Kleisli in Hunfold. repeat red in Hunfold.\n        pose proof @sub_iso as Hiso.\n        specialize (Hiso _ _ _ S _). destruct Hiso.\n        repeat red in iso_epi.\n        unfold cat, Cat_IFun in iso_epi.\n        rewrite iso_epi. cbn.\n        reflexivity. }\n      { unfold Basics.iter, MonadIter_itree. clear Hunfold.\n        pose proof (iter_unfold (C := Kleisli M)) as Hunfold.\n        specialize (Hunfold _ _ (interp_body (over f) R) (ret a2)).\n        unfold iter, Iter_Kleisli, Basics.iter, MonadIter_itree in Hunfold.\n        rewrite Hunfold.\n        unfold_cat; cbn. rewrite bind_ret_l. cbn.\n        apply eqmR_ret; eauto.\n        typeclasses eauto. } }\n  Qed.\n\n  Lemma _interp_over_ignore_trigger:\n    forall (A B C BC ABC : Type -> Type) (S : B +? C -< BC) (S' : A +? BC -< ABC)\n      (S_wf : Subevent_wf S) (S'_wf : Subevent_wf S')\n      (R : Type) (h : forall T0 : Type, A T0 -> M T0)\n            (e : B R) (Tr : Trigger BC M),\n      eqmR eq\n           (interp (IM := itree) (T := T) (I := ABC) (M := M) (over h)\n                   (trigger (E := B) e))\n           (morph (MT := T M) (trigger (E := BC) (inj1 e))).\n   Proof.\n     intros A B C BC ABC S S' ? ? R h e Tr.\n     pose proof @hfmap_lift as Hlift.\n     specialize (Hlift T _ _ _ _ _ R (itree ABC) M _ _ _ _ _ _ _ _ (itree_interp (over h)) _).\n     etransitivity.\n     eapply Hlift. clear Hlift.\n\n     eapply morph_proper.\n\n\n    unfold ITree.trigger. unfold interp.\n    unfold Basics.iter, MonadIter_itree, Kleisli_MonadIter.\n    pose proof (iter_unfold (C := Kleisli M)) as Hunfold.\n    specialize (Hunfold _ _ (interp_body (over h) R)).\n    specialize (Hunfold (trigger e)).\n    unfold_cat; cbn. unfold iter, Iter_Kleisli in Hunfold. rewrite Hunfold.\n    unfold_cat. unfold case_, Case_Kleisli, Function.case_sum.\n\n    eapply Proper_eqmR_eq_impl; try typeclasses eauto.\n    3 : reflexivity.\n    2 : symmetry; eapply (bind_ret_r (trigger (inj1 e))).\n    unfold id_, Id_Kleisli.\n\n    eapply eqmR_bind_ProperH_simple; [ typeclasses eauto | ..].\n    { unfold interp_body; cbn. setoid_rewrite <- bind_ret_r at 5.\n      eapply eqmR_bind_ProperH_simple; [ typeclasses eauto | ..].\n      unfold_cat. unfold Cat_IFun, over.\n      unfold case.\n      pose proof @sub_iso as Hiso.\n      specialize (Hiso _ _ _ S' _). destruct Hiso.\n      repeat red in iso_epi.\n      unfold cat, Cat_IFun in iso_epi.\n      rewrite iso_epi. cbn.\n\n      repeat red in iso_mono.\n      unfold cat, Cat_IFun in iso_mono.\n      unfold inj1. unfold_cat. unfold Cat_IFun. reflexivity.\n      intros; subst; apply eqmR_ret; try typeclasses eauto.\n      Unshelve.\n      2 : exact(fun x y => match x with\n                        | inl a => a = Ret y\n                        | _ => False end). cbn. reflexivity. }\n    all : intros; cbn; destruct a1; inv H.\n    { unfold Basics.iter, MonadIter_itree. clear Hunfold.\n      pose proof (iter_unfold (C := Kleisli M)) as Hunfold.\n      specialize (Hunfold _ _ (interp_body (over h) R) (ret a2)).\n      unfold iter, Iter_Kleisli, Basics.iter, MonadIter_itree in Hunfold.\n      rewrite Hunfold.\n      unfold_cat; cbn. rewrite bind_ret_l. cbn.\n      apply eqmR_ret; eauto.\n      typeclasses eauto. }\n   Qed.\n\n  Lemma _interp_iter {I E R} (f : E ~> M) t t' (i:I):\n    (forall i, eqmR eq (interp f (t i)) (t' i)) ->\n      interp f\n        (@Basics.iter (T (itree E)) _ R I t i)\n      ≈{ @eq R\n      } @Basics.iter (T M) _ R I t' i.\n  Proof.\n    cbn. intros.\n\n    pose proof (@hfmap_iter T _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ (itree_interp f) _ _).\n    eapply H0; eauto.\n  Qed.\n\n  Lemma _interp_proper {E} :\n    forall (h : forall T0 : Type, E T0 -> M T0) (R1 R2 : Type) (RR : R1 -> R2 -> Prop),\n      ProperH (eqmR (m := T (itree E)) RR ~~> eqmR (B := R2) RR)\n            (fun t => interp h t) (fun t => interp h t).\n  Proof.\n    cbn. repeat intro.\n    pose proof (@hfmap_nat T _ _ _ _ _ _ _ _ _ _ _ _ _ (itree_interp h) _).\n    destruct H0.\n    eapply morph_proper; eauto.\n  Qed.\n\n  Global Instance InterpLaws_: InterpLaws T M.\n  constructor; repeat intro.\n  apply _interp_ret.\n  apply _interp_trigger.\n  apply _interp_over_ignore_trigger; eauto.\n  apply _interp_bind.\n  apply _interp_iter; auto.\n  apply _interp_proper; auto.\n  Qed.\n\nEnd Facts.\n\n#[global] Program Instance WF_IterativeMonad_Trans T M `{T_WF_IterativeMonadT : WF_IterativeMonadT T}\n `{M_WF_IterativeMonad : WF_IterativeMonad M} : WF_IterativeMonad (T M) _ _ _.\n\n#[global] Instance IterativeMonad_itree E : IterativeMonad (itree E).\nProof.\n  constructor; repeat intro; try constructor; intros; eauto.\n  exact (ret X).\n  exact (bind X X0).\n  exact (eqmR R).\n  exact (observe (ITree.iter X X0)).\nDefined.\n\n(* Facts about [interp] when the *base monad* is an ITree. *)\nSection Facts.\n\n  Context {T : (Type -> Type) -> Type -> Type} {F : Type -> Type}\n          {T_MonadT:IterativeMonadT T}\n          {T_HFunctor:HFunctor T}\n          {T_WF_IterativeMonadT : WF_IterativeMonadT T _ _}\n          {T_wf : @WF_HFunctor T _ _ _ _}\n          {itree_monad_morphism : forall (E : Type -> Type) (f : E ~> T (itree F)),\n              MonadMorphism _ _ (itree_interp (I := E) f)}\n          {itree_iter_morphism : forall (E : Type -> Type) (f : E ~> T (itree F)),\n              IterMorphism (itree_interp (I := E) f)}.\n\n  #[global] Instance IM_TF : IterativeMonad (T (itree F)).\n  constructor; try typeclasses eauto.\n  Defined.\n\n  #[global] Instance InterpLaws_itree_base :\n    InterpLaws (fun x => x) (T (itree F)) (TM_Interp := stack_interp).\n  eapply InterpLaws_.\n  Defined.\n\nEnd Facts.\n\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/InterpFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2597796831365564}}
{"text": "From hahn Require Import Hahn.\nRequire Import PromisingLib.\nFrom Promising2 Require Import Memory View Time Cell TView.\nFrom imm Require Import AuxRel2.\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 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\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\nLemma memory_add_le memory memory' loc from to msg \n      (ADD : Memory.add memory loc from to msg 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. eapply Memory.add_get0 in ADD. desf.\n  rewrite ADD in LHS. inv LHS.\nQed.\n\nLemma memory_remove_le memory memory' loc from to msg\n      (ADD : Memory.remove memory loc from to msg 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 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 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_inhabited; eauto. }\n  destruct H0.\n  eapply Memory.op_inhabited; 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\nLemma inhabited_le memory memory' (LE : Memory.le memory memory')\n      (INHAB : Memory.inhabited memory) :\n  Memory.inhabited memory'.\nProof using. red. ins. apply LE. apply INHAB. 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 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\nLemma ts_lt_or_bot_add loc from to msg memory memory_add\n      (TLOB : ts_lt_or_bot memory)\n      (ADD : Memory.add memory loc from to msg 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 ts_lt_or_bot_lower loc from to msg released' memory memory_lower\n      (TLOB : ts_lt_or_bot memory)\n      (LOWER : Memory.lower memory loc from to msg 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 ts_lt_or_bot_split loc from to to' msg msg' memory memory_split\n      (TLOB : ts_lt_or_bot memory)\n      (SPLIT : Memory.split memory loc from to to' msg msg' 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_remove loc from to msg memory memory'\n      (REMOVE : Memory.remove memory loc from to msg memory')\n      (TLOB : ts_lt_or_bot memory) :\n  ts_lt_or_bot memory'.\nProof using.\n  red. ins.\n  erewrite Memory.remove_o in GET; eauto.\n  desf; simpls; desf.\n  all: eapply TLOB; eauto.\nQed.\n\nLemma ts_lt_or_bot_op loc from to msg kind memory memory'\n      (TLOB : ts_lt_or_bot memory)\n      (OP : Memory.op memory loc from to msg 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. }\n  eapply ts_lt_or_bot_remove; 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 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 msg msg' \n      (SP : Memory.split memory loc from to ts msg msg' memory_split) :\n  Memory.get loc ts memory = Some (from, msg').\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\nLemma memory_le_add2 mem1 mem1' mem2 mem2' loc from to msg\n      (LE : Memory.le mem1 mem2)\n      (ADD1 : Memory.add mem1 loc from to msg mem1')\n      (ADD2 : Memory.add mem2 loc from to msg mem2') :\n  Memory.le mem1' mem2'.\nProof using.\n  red. ins.\n  erewrite Memory.add_o in LHS; eauto.\n  erewrite Memory.add_o; [|by apply ADD2].\n  desf. by apply LE.\nQed.\n\nLemma memory_le_split2 mem1 mem1' mem2 mem2' loc from to to' msg msg'\n      (LE : Memory.le mem1 mem2)\n      (SPLIT1 : Memory.split mem1 loc from to to' msg msg' mem1')\n      (SPLIT2 : Memory.split mem2 loc from to to' msg msg' mem2') :\n  Memory.le mem1' mem2'.\nProof using.\n  red. ins.\n  erewrite Memory.split_o in LHS; eauto.\n  erewrite Memory.split_o; [|by apply SPLIT2].\n  desf. by apply LE.\nQed.\n\nLemma memory_le_remove2 mem1 mem1' mem2 mem2' loc from to msg\n      (LE : Memory.le mem1 mem2)\n      (REMOVE1 : Memory.remove mem1 loc from to msg mem1')\n      (REMOVE2 : Memory.remove mem2 loc from to msg mem2') :\n  Memory.le mem1' mem2'.\nProof using.\n  red. ins.\n  erewrite Memory.remove_o in LHS; eauto.\n  erewrite Memory.remove_o; [|by apply REMOVE2].\n  desf. by apply LE.\nQed.\n\nLemma interval_disjoint_imm_le a b c d (LE : Time.le b c):\n  Interval.disjoint (a, b) (c, d).\nProof using.\n  red; ins.\n  destruct LHS as [LFROM LTO].\n  destruct RHS as [RFROM RTO]; simpls.\n  eapply Time.lt_strorder.\n  eapply TimeFacts.le_lt_lt.\n  2: by apply RFROM.\n  etransitivity; [by apply LTO|].\n  done.\nQed.\n\nLemma message_max_ts_disjoint loc to from msg memory\n      (GET : Memory.get loc to memory = Some (from, msg)) :\n  Interval.disjoint (Memory.max_ts loc memory, Time.incr (Memory.max_ts loc memory))\n                    (from, to).\nProof using.\n  symmetry.\n  apply interval_disjoint_imm_le.\n  eapply Memory.max_ts_spec; eauto.\nQed.\n\nLemma nonsynch_loc_le loc mem1 mem2 (LE : Memory.le mem1 mem2)\n      (NSL : Memory.nonsynch_loc loc mem2) :\n  Memory.nonsynch_loc loc mem1.\nProof using. red. ins. apply LE in GET. by apply NSL in GET. Qed.\n\nDefinition msg_preserved memory memory' :=\n  forall loc ts from v rel\n         (INMEM : Memory.get loc ts memory = Some (from, Message.full v rel)),\n    exists from', Memory.get loc ts memory' = Some (from', Message.full v rel).\n\nDefinition msg_preserved_refl memory : msg_preserved memory memory.\nProof using. red. ins. eauto. Qed.\n\nDefinition msg_preserved_add memory memory' loc from to msg \n           (ADD : Memory.add memory loc from to msg memory') :\n  msg_preserved memory memory'.\nProof using. red. ins. exists from0. eapply memory_add_le; eauto. Qed.\n\nDefinition msg_preserved_split memory memory'\n           loc ts1 ts2 ts3 msg1 msg2 \n           (SPLIT : Memory.split memory loc ts1 ts2 ts3 msg1 msg2 memory'):\n  msg_preserved memory memory'.\nProof using.\n  red. ins.\n  erewrite Memory.split_o; eauto.\n  edestruct Memory.split_get0 as [HH BB]; eauto.\n  destruct (loc_ts_eq_dec (loc0, ts) (loc, ts2)) as [EQ|NEQ].\n  { simpls. desf. rewrite HH in INMEM. desf. }\n  simpls.\n  destruct (loc_ts_eq_dec (loc0, ts) (loc, ts3)) as [EQ|NNEQ].\n  { simpls. desf. rewrite BB in INMEM. inv INMEM. eauto. }\n  eauto.\nQed.\n\nDefinition msg_preserved_cancel memory memory' loc from to\n           (CANCEL : Memory.remove memory loc from to Message.reserve memory') :\n  msg_preserved memory memory'.\nProof using.\n  red. ins. exists from0.\n  erewrite Memory.remove_o; eauto.\n  destruct (loc_ts_eq_dec (loc0, ts) (loc, to)) as [EQ|NEQ].\n  2: simpls.\n  simpls. desf. \n  edestruct Memory.remove_get0 as [HH]; eauto.\n  rewrite HH in INMEM. inv INMEM.\nQed.\n\nDefinition msg_preserved_trans memory memory' memory''\n           (PRES  : msg_preserved memory  memory')\n           (PRES' : msg_preserved memory' memory'') :\n  msg_preserved memory memory''.\nProof.\n  red. ins.\n  apply PRES  in INMEM. desf.\n  apply PRES' in INMEM. desf.\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\n", "meta": {"author": "weakmemory", "repo": "promising2ToImm", "sha": "8f462969e0cfaa0bb71d43b4cdae0f030d06ef9c", "save_path": "github-repos/coq/weakmemory-promising2ToImm", "path": "github-repos/coq/weakmemory-promising2ToImm/promising2ToImm-8f462969e0cfaa0bb71d43b4cdae0f030d06ef9c/src/lib/MemoryAux.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318194686359, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2597796708710577}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.floyd.library.\nRequire Import VST.progs64.shift.\n\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs.  mk_varspecs prog. Defined.\n\nDefinition shift {X} (l : list X) k :=\n  sublist k (Zlength l) l ++ sublist 0 k l.\n\nDefinition shift_spec :=\n DECLARE _shift\n  WITH sh : share, a : val, s : list Z, n : Z, k : Z\n  PRE [ _a OF (tptr tint) , _n OF (tint), _k OF (tint)]\n     PROP(writable_share sh)\n     LOCAL (temp _a a; temp _n (Vint (Int.repr n)); temp _k (Vint (Int.repr k)))\n     SEP (data_at sh (tarray tint n) (map Vint (map Int.repr s)) a)\n  POST [ tvoid ]\n     PROP()\n     LOCAL()\n     SEP ((data_at sh (tarray tint n) (map Vint (map Int.repr (shift s k))) a)).\n\nDefinition Gprog : funspecs :=\n        ltac:(with_library prog [shift_spec]).\n\nLemma shift_body : semax_body Vprog Gprog f_shift shift_spec.\nProof.\n  start_function.\n  forward_call.", "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_shift.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283035, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.25977819845747463}}
{"text": "Require Import Omega.\nRequire Import Bool.\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.\nRequire Import Loc.\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 Pred.\nRequire Import Trace.\n\nRequire Import MemoryMerge.\nRequire Import ReorderCancel.\nRequire Import MemoryProps.\nRequire Import OrderedTimes.\nRequire Import Cover.\nRequire Import Mapping.\n\nSet Implicit Arguments.\n\n\n\nLemma promise_not_cancel_covered_increase prom0 prom1 mem0 mem1\n      loc from to msg kind\n      (PROMISE: Memory.promise prom0 mem0 loc from to msg prom1 mem1 kind)\n      (NOTCANCEL: kind <> Memory.op_kind_cancel)\n      loc0 ts0\n      (COVERED: covered loc0 ts0 mem0)\n  :\n    covered loc0 ts0 mem1.\nProof.\n  inv PROMISE.\n  { erewrite (@add_covered mem1 mem0); eauto. }\n  { erewrite (@split_covered mem1 mem0); eauto. }\n  { erewrite (@lower_covered mem1 mem0); eauto. }\n  { ss. }\nQed.\n\nLemma step_not_cancel_covered_increase lang (th0 th1: Thread.t lang) pf e\n      (STEP: Thread.step pf e th0 th1)\n      (NOTCANCEL: ~ ThreadEvent.is_cancel e)\n      loc0 ts0\n      (COVERED: covered loc0 ts0 (Thread.memory th0))\n  :\n    covered loc0 ts0 (Thread.memory th1).\nProof.\n  inv STEP.\n  { inv STEP0. inv LOCAL. ss.\n    eapply promise_not_cancel_covered_increase; eauto. destruct kind; ss.\n    des_ifs. inv PROMISE; ss.\n  }\n  { inv STEP0. inv LOCAL; auto.\n    { inv LOCAL0. inv WRITE. eapply promise_not_cancel_covered_increase; eauto.\n      destruct kind; ss. inv PROMISE; ss. }\n    { inv LOCAL2. inv WRITE. eapply promise_not_cancel_covered_increase; eauto.\n      destruct kind; ss. inv PROMISE; ss. }\n  }\nQed.\n\nLemma traced_steps_not_cancel_covered_increase lang (th0 th1: Thread.t lang) tr\n      (STEPS: Trace.steps tr th0 th1)\n      (EVENTS: List.Forall (fun em => <<SAT: (fun e => ~ ThreadEvent.is_cancel e) (snd em)>>) tr)\n      loc0 ts0\n      (COVERED: covered loc0 ts0 (Thread.memory th0))\n  :\n    covered loc0 ts0 (Thread.memory th1).\nProof.\n  ginduction STEPS; auto. i. clarify. inv EVENTS.\n  eapply step_not_cancel_covered_increase in STEP; eauto.\nQed.\n\n\n\nSection UNATTACHABLE.\n\n  Inductive unattachable (mem: Memory.t) (loc: Loc.t) (ts: Time.t): Prop :=\n  | unattachable_intro\n      from to msg\n      (MSG: Memory.get loc to mem = Some (from, msg))\n      (FROM: Time.le from ts)\n      (TO: Time.lt ts to)\n  .\n\n  Lemma lower_unattachable mem1 mem0 loc from to msg1 msg2\n        (LOWER: Memory.lower mem0 loc from to msg1 msg2 mem1)\n    :\n      unattachable mem1 = unattachable mem0.\n  Proof.\n    extensionality loc0. extensionality ts0.\n    exploit Memory.lower_get0; eauto. i. des.\n    apply Coq.Logic.PropExtensionality.propositional_extensionality. split; i.\n    { inv H. erewrite Memory.lower_o in MSG; eauto. des_ifs.\n      { ss. des; clarify. econs; eauto. }\n      { econs; eauto. }\n    }\n    { inv H. eapply Memory.lower_get1 in MSG; eauto. des. econs; eauto. }\n  Qed.\n\n  Lemma split_unattachable mem1 mem0 loc ts1 ts2 ts3 msg2 msg3\n        (SPLIT: Memory.split mem0 loc ts1 ts2 ts3 msg2 msg3 mem1)\n    :\n      unattachable mem1 = unattachable mem0.\n  Proof.\n  Admitted.\n    (* extensionality loc0. extensionality ts0.\n    exploit split_succeed_wf; eauto. i. des.\n    exploit Memory.split_get0; eauto. i. des.\n    apply Coq.Logic.PropExtensionality.propositional_extensionality. split; i.\n    { inv H. erewrite Memory.split_o in MSG; eauto. des_ifs.\n      { ss. des; clarify. econs; eauto. }\n      { ss. des; clarify. econs; eauto. etrans; eauto. left. auto. }\n      { econs; eauto. }\n    }\n    { inv H. generalize (Memory.split_o loc0 to SPLIT). intros MSG0. des_ifs.\n      { ss. des; clarify. }\n      { ss. des; clarify.\n        destruct (Time.le_lt_dec ts2 ts0).\n        { econs; try apply MSG0; eauto. }\n        { econs; try apply GET1; eauto. }\n      }\n      { erewrite MSG in *. clarify. econs; eauto. }\n    }\n  Qed. *)\n\n  Lemma add_unattachable mem1 mem0 loc from to msg\n        (ADD: Memory.add mem0 loc from to msg mem1)\n    :\n      unattachable mem1 =\n      (fun loc0 ts0 =>\n         unattachable mem0 loc0 ts0 \\/ (loc0 = loc /\\ Time.le from ts0 /\\ Time.lt ts0 to)).\n  Proof.\n    extensionality loc0. extensionality ts0.\n    exploit add_succeed_wf; eauto. i.  des.\n    exploit Memory.add_get0; eauto. i. des.\n    apply Coq.Logic.PropExtensionality.propositional_extensionality. split; i.\n    { inv H. erewrite Memory.add_o in MSG; eauto. des_ifs.\n      { ss. des; clarify. right. splits; auto. }\n      { left. econs; eauto. }\n    }\n    { des; subst.\n      { inv H. econs; eauto. eapply Memory.add_get1; eauto. }\n      { econs; eauto. }\n    }\n  Qed.\n\nEnd UNATTACHABLE.\n\n\n\nSection LIFT.\n\n  Lemma memory_remove_le_preserve mem0 mem0' mem1 mem1' loc from to msg\n        (REMOVE0: Memory.remove mem0 loc from to msg mem0')\n        (REMOVE1: Memory.remove mem1 loc from to msg mem1')\n        (MLE: Memory.le mem0 mem1)\n  :\n    Memory.le mem0' mem1'.\n  Proof.\n    ii. erewrite Memory.remove_o; eauto.\n    erewrite (@Memory.remove_o mem0' mem0) in LHS; eauto. des_ifs.\n    eapply MLE; eauto.\n  Qed.\n\n  Lemma memory_add_le_preserve mem0 mem0' mem1 mem1' loc from to msg\n        (ADD0: Memory.add mem0 loc from to msg mem0')\n        (ADD1: Memory.add mem1 loc from to msg mem1')\n        (MLE: Memory.le mem0 mem1)\n    :\n      Memory.le mem0' mem1'.\n  Proof.\n    ii. erewrite Memory.add_o; eauto.\n    erewrite (@Memory.add_o mem0' mem0) in LHS; eauto. des_ifs.\n    eapply MLE; eauto.\n  Qed.\n\n  Lemma memory_split_le_preserve mem0 mem0' mem1 mem1' loc ts1 ts2 ts3 msg2 msg3\n        (SPLIT0: Memory.split mem0 loc ts1 ts2 ts3 msg2 msg3 mem0')\n        (SPLIT1: Memory.split mem1 loc ts1 ts2 ts3 msg2 msg3 mem1')\n        (MLE: Memory.le mem0 mem1)\n    :\n      Memory.le mem0' mem1'.\n  Proof.\n    ii. erewrite Memory.split_o; eauto.\n    erewrite (@Memory.split_o mem0' mem0) in LHS; eauto. des_ifs.\n    eapply MLE; eauto.\n  Qed.\n\n  Lemma memory_lower_le_preserve mem0 mem0' mem1 mem1' loc from to msg1 msg2\n        (LOWER0: Memory.lower mem0 loc from to msg1 msg2 mem0')\n        (LOWER1: Memory.lower mem1 loc from to msg1 msg2 mem1')\n        (MLE: Memory.le mem0 mem1)\n    :\n      Memory.le mem0' mem1'.\n  Proof.\n    ii. erewrite Memory.lower_o; eauto.\n    erewrite (@Memory.lower_o mem0' mem0) in LHS; eauto. des_ifs.\n    eapply MLE; eauto.\n  Qed.\n\n  Lemma step_lifting_promise prom0 prom1 mem0 mem1 cap0\n        loc from to msg kind\n        (spaces lefts: Loc.t -> Time.t -> Prop)\n        (PROMISE: Memory.promise prom0 mem0 loc from to msg prom1 mem1 kind)\n        (WRITENOTIN: forall ts (ITV: Interval.mem (from, to) ts), ~ spaces loc ts)\n        (WRITENOTTO: ~ lefts loc to)\n        (SOUND: Memory.le mem0 cap0)\n        (SPACES:\n           forall loc ts (COV: covered loc ts cap0),\n             <<COV: covered loc ts mem0>> \\/ <<SPACE: spaces loc ts>>)\n        (LEFTS:\n           forall loc ts (UNATTACHABLE: unattachable cap0 loc ts),\n             <<COV: unattachable mem0 loc ts>> \\/ <<LEFT: lefts loc ts>>)\n        (MEM0: Memory.closed mem0)\n        (PROM0: Memory.le prom0 mem0)\n        (PROM1: Memory.le prom0 cap0)\n        (NOTCANCEL: kind <> Memory.op_kind_cancel)\n    :\n      exists cap1,\n        (<<STEP: Memory.promise prom0 cap0 loc from to msg prom1 cap1 kind>>) /\\\n        (<<SOUND: Memory.le mem1 cap1>>) /\\\n        (<<SPACES:\n           forall loc ts (COV: covered loc ts cap1),\n             <<COV: covered loc ts mem1>> \\/ spaces loc ts>>) /\\\n        (<<LEFTS:\n           forall loc ts (UNATTACHABLE: unattachable cap1 loc ts),\n             <<COV: unattachable mem1 loc ts>> \\/ lefts loc ts>>).\n  Proof.\n    inv PROMISE.\n    { exploit add_succeed_wf; try apply MEM; eauto. i. des.\n      exploit (@Memory.add_exists cap0 loc from to msg); eauto.\n      { ii. exploit SPACES.\n        { econs; eauto. }\n        i. des.\n        { inv COV. eapply DISJOINT; eauto. }\n        { eapply WRITENOTIN; eauto. }\n      }\n      i. des. esplits.\n      { econs; eauto. i. subst. exploit LEFTS.\n        { econs; eauto.\n          { refl. }\n          { apply memory_get_ts_strong in GET. des; auto.\n            subst. eapply TimeFacts.le_lt_lt; eauto. eapply Time.bot_spec. }\n        }\n        i. des; ss.\n        { inv COV. destruct FROM.\n          { eapply DISJOINT; eauto.\n            { instantiate (1:=to). econs; ss. refl. }\n            { econs; ss. left. eauto. }\n          }\n          { inv H. eapply ATTACH; eauto. }\n        }\n      }\n      { eapply memory_add_le_preserve; eauto. }\n      { i. erewrite add_covered in COV; eauto.\n        erewrite (@add_covered mem1 mem0); eauto. des; eauto.\n        eapply SPACES in COV. des; auto. }\n      { i. erewrite add_unattachable in UNATTACHABLE; eauto.\n        erewrite (@add_unattachable mem1 mem0); eauto. des; auto.\n        eapply LEFTS in UNATTACHABLE. des; auto. }\n    }\n    { des. subst.\n      exploit (@Memory.split_exists_le prom0 cap0); eauto. i. des. esplits.\n      { econs; eauto. }\n      { ii. erewrite Memory.split_o in LHS; eauto.\n        erewrite (@Memory.split_o mem2 cap0); eauto. des_ifs.\n        eapply SOUND; eauto. }\n      { i. erewrite (@split_covered mem2 cap0) in COV; eauto.\n        erewrite (@split_covered mem1 mem0); eauto. }\n      { i. erewrite (@split_unattachable mem2 cap0) in UNATTACHABLE; eauto.\n        erewrite (@split_unattachable mem1 mem0); eauto. }\n    }\n    { des. subst.\n      exploit (@Memory.lower_exists_le prom0 cap0); eauto. i. des. esplits.\n      { econs; eauto. }\n      { ii. erewrite Memory.lower_o in LHS; eauto.\n        erewrite (@Memory.lower_o mem2 cap0); eauto. des_ifs.\n        eapply SOUND; eauto. }\n      { i. erewrite (@lower_covered mem2 cap0) in COV; eauto.\n        erewrite (@lower_covered mem1 mem0); eauto. }\n      { i. erewrite (@lower_unattachable mem2 cap0) in UNATTACHABLE; eauto.\n        erewrite (@lower_unattachable mem1 mem0); eauto. }\n    }\n    { ss. }\n  Qed.\n\n  Lemma step_lifting lang st0 st1 lc0 lc1 sc0 sc1 mem0 mem1 cap0 pf e\n        (spaces lefts: Loc.t -> Time.t -> Prop)\n        (STEP: Thread.step pf e (Thread.mk lang st0 lc0 sc0 mem0) (Thread.mk _ st1 lc1 sc1 mem1))\n        (WRITENOTIN: write_not_in spaces e)\n        (WRITENOTTO: write_not_to lefts e)\n        (NOTCANCEL: ~ ThreadEvent.is_cancel e)\n        (SOUND: Memory.le mem0 cap0)\n        (SPACES:\n           forall loc ts (COV: covered loc ts cap0),\n             <<COV: covered loc ts mem0>> \\/ <<SPACE: spaces loc ts>>)\n        (LEFTS:\n           forall loc ts (UNATACHABLE: unattachable cap0 loc ts),\n             <<COV: unattachable mem0 loc ts>> \\/ <<LEFT: lefts loc ts>>)\n       (MEM0: Memory.closed mem0)\n        (LOCAL0: Local.wf lc0 mem0)\n        (SC0: Memory.closed_timemap sc0 mem0)\n    :\n      exists cap1,\n        (<<STEP: Thread.step pf e (Thread.mk _ st0 lc0 sc0 cap0) (Thread.mk _ st1 lc1 sc1 cap1)>>) /\\\n        (<<SOUND: Memory.le mem1 cap1>>) /\\\n        (<<SPACES:\n           forall loc ts (COV: covered loc ts cap1),\n             <<COV: covered loc ts mem1>> \\/ spaces loc ts>>) /\\\n        (<<UNATTACHABLE:\n           forall loc ts (COV: unattachable cap1 loc ts),\n             <<COV: unattachable mem1 loc ts>> \\/ lefts loc ts>>).\n\n  Proof.\n    inv STEP.\n    { inv STEP0. inv LOCAL. ss.\n      destruct (Memory.op_kind_is_cancel kind) eqn:KIND; ss.\n      { destruct kind; ss. des_ifs. inv PROMISE; ss. }\n      exploit step_lifting_promise; eauto.\n      { eapply LOCAL0. }\n      { transitivity mem0; eauto. eapply LOCAL0. }\n      { destruct kind; ss. }\n      i. des. esplits; eauto. econs. econs.\n      { econs; eauto. eapply memory_concrete_le_closed_msg; eauto. }\n      { ss. destruct kind; ss. }\n    }\n    { inv STEP0. inv LOCAL.\n      { esplits; eauto. }\n      { inv LOCAL1. eapply SOUND in GET. esplits; eauto. }\n      { inv LOCAL1. inv WRITE. exploit step_lifting_promise; eauto.\n        { eapply LOCAL0. }\n        { transitivity mem0; eauto. eapply LOCAL0. }\n        { destruct kind; ss. inv PROMISE; ss. }\n        i. des. esplits; eauto. econs 2; eauto.\n      }\n      { inv LOCAL1. eapply SOUND in GET. inv LOCAL2. inv WRITE.\n        exploit step_lifting_promise; eauto.\n        { eapply LOCAL0. }\n        { transitivity mem0; eauto. eapply LOCAL0. }\n        { destruct kind; ss. inv PROMISE; ss. }\n        i. des. esplits; eauto. econs 2; eauto. econs; eauto. }\n      { esplits; eauto. }\n      { esplits; eauto. }\n      { esplits; eauto. }\n    }\n  Qed.\n\n  Lemma traced_step_lifting lang st0 st1 lc0 lc1 sc0 sc1 mem0 mem1 cap0 tr\n        (spaces lefts: Loc.t -> Time.t -> Prop)\n        (STEPS: Trace.steps tr (Thread.mk lang st0 lc0 sc0 mem0) (Thread.mk _ st1 lc1 sc1 mem1))\n        (EVENTS: List.Forall (fun em => <<SAT: (write_not_in spaces /1\\ write_not_to lefts /1\\ (fun e => ~ ThreadEvent.is_cancel e)) (snd em)>>) tr)\n        (SOUND: Memory.le mem0 cap0)\n        (SPACES:\n           forall loc ts (COV: covered loc ts cap0),\n             <<COV: covered loc ts mem0>> \\/ <<SPACE: spaces loc ts>>)\n        (LEFTS:\n           forall loc ts (UNATACHABLE: unattachable cap0 loc ts),\n             <<COV: unattachable mem0 loc ts>> \\/ <<LEFT: lefts loc ts>>)\n        (MEM0: Memory.closed mem0)\n        (LOCAL0: Local.wf lc0 mem0)\n        (SC0: Memory.closed_timemap sc0 mem0)\n    :\n      exists cap1,\n        (<<STEPS: Trace.steps tr (Thread.mk _ st0 lc0 sc0 cap0) (Thread.mk _ st1 lc1 sc1 cap1)>>) /\\\n        (<<SOUND: Memory.le mem1 cap1>>) /\\\n        (<<SPACES:\n           forall loc ts (COV: covered loc ts cap1),\n             <<COV: covered loc ts mem1>> \\/ spaces loc ts>>) /\\\n        (<<LEFTS:\n           forall loc ts (UNATACHABLE: unattachable cap1 loc ts),\n             <<COV: unattachable mem1 loc ts>> \\/ lefts loc ts>>).\n  Proof.\n    remember (Thread.mk lang st0 lc0 sc0 mem0).\n    remember (Thread.mk lang st1 lc1 sc1 mem1). ginduction STEPS.\n    { i. clarify. esplits; eauto. }\n    { i. clarify. inv EVENTS. ss. des.\n      exploit Thread.step_future; eauto. i. des.\n      destruct th1. ss. exploit step_lifting; eauto. i. des.\n      exploit IHSTEPS; eauto. i. des. exists cap2. splits; auto. econs; eauto.\n    }\n  Qed.\n\nEnd LIFT.\n\n\nFixpoint intervals_sum (l: list (Loc.t * Interval.t)):\n  Loc.t -> Time.t -> Prop :=\n  match l with\n  | [] => bot2\n  | (loc, (from, to))::tl =>\n    fun loc0 ts0 =>\n      (loc0 = loc /\\ Interval.mem (from, to) ts0) \\/\n      intervals_sum tl loc0 ts0\n  end.\n\nFixpoint intervals_sum_left (l: list (Loc.t * Interval.t)):\n  Loc.t -> Time.t -> Prop :=\n  match l with\n  | [] => bot2\n  | (loc, (from, to))::tl =>\n    fun loc0 ts0 =>\n      (loc0 = loc /\\ Time.le from ts0 /\\ Time.lt ts0 to) \\/\n      intervals_sum_left tl loc0 ts0\n  end.\n\nLemma intervals_sum_interval l\n      loc ts\n  :\n    intervals_sum l loc ts <->\n    exists from to,\n      (<<IN: List.In (loc, (from, to)) l>>) /\\ (<<ITV: Interval.mem (from, to) ts>>).\nProof.\n  ginduction l; ss.\n  { i; split; i; ss. des. ss. }\n  { i; split; i; ss.\n    { destruct a. destruct t0. des; clarify.\n      { esplits; eauto. }\n      { eapply IHl in H. des. esplits; eauto. }\n    }\n    { destruct a. destruct t0. des; clarify; eauto. right.\n      eapply IHl. eauto. }\n  }\nQed.\n\nLemma intervals_sum_left_interval l\n      loc ts\n  :\n    intervals_sum_left l loc ts <->\n    exists from to,\n      (<<IN: List.In (loc, (from, to)) l>>) /\\ (<<FROM: Time.le from ts>>) /\\ (<<TO: Time.lt ts to>>).\nProof.\n  ginduction l; ss.\n  { i; split; i; ss. des. ss. }\n  { i; split; i; ss.\n    { destruct a. destruct t0. des; clarify.\n      { esplits; eauto. }\n      { eapply IHl in H. des. esplits; eauto. }\n    }\n    { destruct a. destruct t0. des; clarify; eauto. right.\n      eapply IHl. eauto. }\n  }\nQed.\n\n\nLemma promise_needed_spaces prom0 prom1 mem0 mem1\n      loc from to msg kind\n      (PROMISE: Memory.promise prom0 mem0 loc from to msg prom1 mem1 kind)\n      (WF: kind <> Memory.op_kind_cancel)\n  :\n    ((<<ALREADY: forall ts (ITV: Interval.mem (from, to) ts), covered loc ts mem0>>) /\\\n     (<<COVERED: forall loc ts, covered loc ts mem1 <-> covered loc ts mem0>>))\n    \\/\n    ((<<NEW: forall ts (ITV: Interval.mem (from, to) ts), ~ covered loc ts mem0>>) /\\\n     (<<COVERED: forall loc0 ts0,\n         covered loc0 ts0 mem1 <-> covered loc0 ts0 mem0 \\/ (loc0 = loc /\\ Interval.mem (from, to) ts0)>>) /\\\n     (<<WF: Time.lt from to>>))\n.\nProof.\n  inv PROMISE.\n  { right. exploit add_succeed_wf; try apply MEM. i. des. splits; auto.\n    { ii. inv H. eapply DISJOINT; eauto. }\n    { i. erewrite (@add_covered mem1); eauto. }\n  }\n  { left. exploit split_succeed_wf; try apply MEM. i. des. splits; auto.\n    { ii. econs; eauto. eapply Interval.le_mem; eauto. econs; ss.\n      { refl. }\n      { left. auto. }\n    }\n    { i. eapply split_covered; eauto. }\n  }\n  { left. exploit lower_succeed_wf; try apply MEM. i. des. splits; auto.\n    { ii. econs; eauto. }\n    { i. eapply lower_covered; eauto. }\n  }\n  { ss. }\nQed.\n\nLemma step_needed_spaces lang (th0 th1: Thread.t lang) pf e\n      (times: Loc.t -> Time.t -> Prop)\n      (STEP: Thread.step pf e th0 th1)\n      (NOTCANCEL: ~ ThreadEvent.is_cancel e)\n      (WFTIME: wf_time_evt times e)\n  :\n    ((<<ALREADY: write_not_in (fun loc0 ts0 => ~ covered loc0 ts0 (Thread.memory th0)) e>>) /\\\n     (<<COVERED: forall loc ts, covered loc ts (Thread.memory th1) <-> covered loc ts (Thread.memory th0)>>))\n    \\/\n    exists loc from to,\n      (<<NEW: forall ts (ITV: Interval.mem (from, to) ts), ~ covered loc ts (Thread.memory th0)>>) /\\\n      (<<COVERED: forall loc0 ts0,\n          covered loc0 ts0 (Thread.memory th1) <-> covered loc0 ts0 (Thread.memory th0) \\/ (loc0 = loc /\\ Interval.mem (from, to) ts0)>>) /\\\n      (<<WF: Time.lt from to>>) /\\\n      (<<TIMES: times loc from /\\ times loc to>>) /\\\n      (<<EVENT: write_not_in (fun loc0 ts0 => ~ (loc0 = loc /\\ Interval.mem (from, to) ts0)) e>>).\nProof.\n  inv STEP.\n  { inv STEP0. inv LOCAL. ss.\n    destruct (Memory.op_kind_is_cancel kind) eqn:KIND.\n    { destruct kind; ss. des_ifs. inv PROMISE; ss. }\n    exploit promise_needed_spaces; eauto.\n    { destruct kind; ss. }\n    i. des.\n    { left. splits; auto. }\n    { right. esplits; eauto. }\n  }\n  { inv STEP0. inv LOCAL; try by (splits; eauto); ss.\n    { ss. inv LOCAL0. inv WRITE.\n      exploit promise_needed_spaces; eauto.\n      { destruct kind; ss. inv PROMISE; ss. }\n      i. des.\n      { left. esplits; eauto. }\n      { right. esplits; eauto. }\n    }\n    { ss. inv LOCAL2. inv WRITE.\n      exploit promise_needed_spaces; eauto.\n      { destruct kind; ss. inv PROMISE; ss. }\n      i. des.\n      { left. esplits; eauto. }\n      { right. esplits; eauto. }\n    }\n  }\nQed.\n\n\nInductive reservations_added:\n  forall (l: list (Loc.t * Interval.t)) (mem0 mem1: Memory.t), Prop :=\n| reservations_added_base\n    mem0\n  :\n    reservations_added [] mem0 mem0\n| reservations_added_cons\n    mem0 mem1 mem2 loc from to tl\n    (ADD: Memory.add mem0 loc from to Message.reserve mem1)\n    (TL: reservations_added tl mem1 mem2)\n    (WF: Time.lt from to)\n  :\n    reservations_added ((loc, (from, to))::tl) mem0 mem2\n.\n\nLemma reservations_added_trans l0 l1 mem0 mem1 mem2\n      (ADDED0: reservations_added l0 mem0 mem1)\n      (ADDED1: reservations_added l1 mem1 mem2)\n  :\n    reservations_added (l0 ++ l1) mem0 mem2.\nProof.\n  ginduction l0; eauto.\n  { i. inv ADDED0. ss. }\n  { i. inv ADDED0. exploit IHl0; eauto. i. econs; eauto. }\nQed.\n\n\nLemma reservations_added_cancel\n      loc from to mem0 mem1 mem2 tl\n      (CANCEL: Memory.remove mem1 loc from to Message.reserve mem0)\n      (TL: reservations_added tl mem1 mem2)\n      (WF: Time.lt from to)\n  :\n    reservations_added ((loc, (from, to))::tl) mem0 mem2.\nProof.\n  econs; eauto.\n  exploit (@Memory.add_exists mem0 loc from to Message.reserve); eauto.\n  { i. erewrite Memory.remove_o in GET2; eauto. des_ifs.\n    exploit Memory.get_disjoint.\n    { eapply GET2. }\n    { eapply Memory.remove_get0; eauto. }\n    i. ss. des; clarify. symmetry. auto.\n  }\n  { econs. }\n  i. des. replace mem1 with mem3; auto. eapply Memory.ext.\n  i. erewrite (@Memory.add_o mem3 mem0); eauto.\n  erewrite (@Memory.remove_o mem0 mem1); eauto. des_ifs.\n  ss. des; clarify. symmetry. eapply Memory.remove_get0; eauto.\nQed.\n\nInductive disjoint_intervals\n  :\n    forall (l: list (Loc.t * Interval.t)), Prop :=\n| disjoint_base\n  :\n    disjoint_intervals []\n| disjoint_intervals_cons\n    loc from to tl\n    (TL: disjoint_intervals tl)\n    (NITV: forall ts (ITV: Interval.mem (from, to) ts),\n        ~ intervals_sum tl loc ts)\n    (TS: Time.lt from to)\n  :\n    disjoint_intervals ((loc, (from, to)) :: tl)\n.\nHint Constructors disjoint_intervals.\n\n\n\n\nLemma traced_steps_needed_spaces lang (th0 th1: Thread.t lang) tr\n      (times: Loc.t -> Time.t -> Prop)\n      (STEP: Trace.steps tr th0 th1)\n      (EVENTS: List.Forall (fun em => <<SAT: ((fun e => ~ ThreadEvent.is_cancel e) /1\\ wf_time_evt times) (snd em)>>) tr)\n  :\n    exists l,\n      (<<WRITENOTIN:\n         List.Forall (fun em => <<SAT: write_not_in (fun loc ts => ~ (covered loc ts (Thread.memory th0) \\/ intervals_sum l loc ts)) (snd em)>>) tr>>) /\\\n      (<<DISJOINT: disjoint_intervals l>>) /\\\n      (<<NITV: forall loc ts (ITV: intervals_sum l loc ts), ~ covered loc ts (Thread.memory th0)>>) /\\\n      (<<COVERED: forall loc ts,\n          covered loc ts (Thread.memory th1) <-> covered loc ts (Thread.memory th0) \\/ intervals_sum l loc ts>>) /\\\n      (<<TIMES: List.Forall (fun locitv =>\n                               times (fst locitv) (fst (snd locitv)) /\\\n                               times (fst locitv) (snd (snd locitv))) l>>)\n.\nProof.\n  ginduction STEP; i.\n  { exists []. splits; auto. i. ss. split; auto. i. des; ss. }\n  { subst. inv EVENTS. des. exploit IHSTEP; eauto. i. des.\n    exploit step_needed_spaces; eauto. i. des.\n    { exists l. splits; auto.\n      { econs; eauto.\n        { eapply write_not_in_mon; eauto. i. ss.\n          eapply not_or_and in PR. des. auto. }\n        { eapply List.Forall_impl; eauto. i. ss.\n          eapply write_not_in_mon; eauto. i. ss.\n          erewrite COVERED0; eauto. }\n      }\n      { i. erewrite <- COVERED0; eauto. }\n      { i. erewrite <- COVERED0. eauto. }\n    }\n    { exists ((loc, (from, to)) :: l). splits.\n      { econs.\n        { eapply write_not_in_mon; eauto. ss. i.\n          ii. des. eapply PR. eauto. }\n        { eapply List.Forall_impl; try apply WRITENOTIN; eauto. i. ss.\n          eapply write_not_in_mon; eauto. i. ss.\n          ii. eapply PR. des; auto. eapply COVERED0 in H3. des; auto. }\n      }\n      { econs; eauto. ii. eapply NITV; eauto. eapply COVERED0. auto. }\n      { i. ss. des; clarify; eauto.\n        eapply NITV in ITV. ii. eapply ITV. eapply COVERED0. auto. }\n      { ii. erewrite COVERED. erewrite COVERED0. ss. split; i; des; auto. }\n      { econs; ss. }\n    }\n  }\nQed.\n\nLemma reserve_empty_intervals times lang (th: Thread.t lang) l\n      (DISJOINT: disjoint_intervals l)\n      (NITV: forall loc ts (ITV: intervals_sum l loc ts),\n          ~ covered loc ts (Thread.memory th))\n      (MLE: Memory.le (Local.promises (Thread.local th)) (Thread.memory th))\n      (TIMES: List.Forall (fun locitv =>\n                             times (fst locitv) (fst (snd locitv)) /\\\n                             times (fst locitv) (snd (snd locitv))) l)\n  :\n    exists tr prom' mem',\n      (<<STEPS: Trace.steps tr th (Thread.mk _ (Thread.state th) (Local.mk (Local.tview (Thread.local th)) prom') (Thread.sc th) mem')>>) /\\\n      (<<RESERVETRACE: List.Forall (fun em => <<SAT: (ThreadEvent.is_reserve /1\\ wf_time_evt times) (snd em)>>) tr>>) /\\\n      (<<ADDEDPROM: reservations_added l (Local.promises (Thread.local th)) prom'>>) /\\\n      (<<ADDEDMEM: reservations_added l (Thread.memory th) mem'>>)\n.\nProof.\n  ginduction l; i.\n  { destruct th. destruct local. ss. exists []. esplits; eauto.\n    { econs. }\n    { econs. }\n  }\n  { inv DISJOINT. inv TIMES. ss.\n    exploit (@Memory.add_exists (Thread.memory th) loc from to Message.reserve); eauto.\n    { ii. eapply NITV.\n      { left. eauto. }\n      { econs; eauto. }\n    }\n    { econs. }\n    intros [mem MEM].\n    exploit (@Memory.add_exists_le (Local.promises (Thread.local th)) (Thread.memory th)); eauto.\n    intros [prom PROM].\n    assert (STEP: Thread.step false (ThreadEvent.promise loc from to Message.reserve Memory.op_kind_add) th (Thread.mk _ (Thread.state th) (Local.mk (Local.tview (Thread.local th)) prom) (Thread.sc th) mem)).\n    { destruct th. ss. econs. econs; ss. econs; ss. econs; ss. }\n    exploit (@IHl times lang (Thread.mk _ (Thread.state th) (Local.mk (Local.tview (Thread.local th)) prom) (Thread.sc th) mem)); eauto; ss.\n    { i. erewrite add_covered; eauto. ii. des; subst.\n      { eapply NITV; eauto. }\n      { eapply NITV0; eauto. }\n    }\n    { hexploit step_promises_le; eauto.\n      { econs; eauto. }\n      i. ss.\n    }\n    i. des. esplits.\n    { econs; eauto. }\n    { econs; ss. }\n    { econs; eauto. }\n    { econs; eauto. }\n  }\nQed.\n\nLemma reservations_added_get_same mem1 mem0 l\n      (ADDED: reservations_added l mem0 mem1)\n      loc ts\n      (NIN: forall from, ~ List.In (loc, (from, ts)) l)\n  :\n    Memory.get loc ts mem1 = Memory.get loc ts mem0.\nProof.\n  ginduction ADDED; auto. i.\n  erewrite IHADDED; eauto.\n  { erewrite (@Memory.add_o mem1 mem0); eauto. des_ifs. ss. des; clarify.\n    exfalso. eapply NIN; eauto. }\n  { ii. ss. eapply NIN; eauto. }\nQed.\n\nLemma reservations_added_get_none mem1 mem0 l\n      (ADDED: reservations_added l mem0 mem1)\n      loc from ts\n      (IN: List.In (loc, (from, ts)) l)\n  :\n    Memory.get loc ts mem0 = None.\nProof.\n  ginduction ADDED; ss. i. des; clarify.\n  { eapply Memory.add_get0; eauto. }\n  { eapply IHADDED in IN. erewrite Memory.add_o in IN; eauto. des_ifs. }\nQed.\n\nLemma reservations_added_le_le l mem0 mem1 cap1 cap0\n      (ADDED0: reservations_added l mem0 mem1)\n      (MLE: Memory.le mem1 cap1)\n      (ADDED1: reservations_added l cap0 cap1)\n  :\n    Memory.le mem0 cap0.\nProof.\n  ii. destruct (classic (forall from, ~ List.In (loc, (from, to)) l)).\n  { erewrite <- (@reservations_added_get_same cap1 cap0); eauto.\n    erewrite <- (@reservations_added_get_same mem1 mem0) in LHS; eauto. }\n  { eapply not_all_not_ex in H. des.\n    erewrite reservations_added_get_none in LHS; eauto. ss. }\nQed.\n\nLemma cancel_reservations_added times l prom lang lc\n      (ADDEDPROM: reservations_added l prom (Local.promises lc))\n      (TIMES: List.Forall (fun locitv =>\n                             times (fst locitv) (fst (snd locitv)) /\\\n                             times (fst locitv) (snd (snd locitv))) l)\n  :\n    exists tr,\n      (<<CANCELTRACE: List.Forall (fun em => <<SAT: (ThreadEvent.is_cancel /1\\ wf_time_evt times) (snd em)>>) tr>>) /\\\n    forall\n      (st: Language.state lang) sc mem\n      (MLE: Memory.le (Local.promises lc) mem),\n    exists mem',\n      (<<STEPS: Trace.steps tr (Thread.mk _ st lc sc mem) (Thread.mk _ st (Local.mk (Local.tview lc) prom) sc mem')>>) /\\\n      (<<ADDEDMEM: reservations_added l mem' mem>>)\n.\nProof.\n  ginduction l; i.\n  { exists []. splits; ss. i. destruct lc. ss. inv ADDEDPROM. esplits; eauto. econs. }\n  { inv TIMES. inv ADDEDPROM.\n    exploit IHl; eauto. i. des.\n    eexists (tr++[(Local.mk (Local.tview lc) mem1, ThreadEvent.promise loc from to Message.reserve Memory.op_kind_cancel)]).\n    splits.\n    { eapply Forall_app; eauto. econs; ss. }\n    i. exploit (x0 st sc mem); eauto. i. des.\n    exploit (@Memory.remove_exists mem1 loc from to Message.reserve); eauto.\n    { eapply Memory.add_get0; eauto. } i. des.\n    exploit (@Memory.remove_exists_le mem1 mem'); eauto.\n    { eapply trace_steps_promises_le in STEPS; eauto. } i. des.\n    assert (mem2 = prom).\n    { symmetry. eapply MemoryMerge.add_remove; eauto. } subst.\n    esplits.\n    { eapply Trace.steps_trans.\n      { eapply STEPS. }\n      { econs; eauto. econs 1; eauto. econs; eauto. }\n    }\n    { eapply reservations_added_cancel; eauto. }\n  }\nQed.\n\nLemma step_finte_write_to (e: ThreadEvent.t)\n      (times: Loc.t -> Time.t -> Prop)\n      (EVENT: wf_time_evt times e)\n  :\n    exists (l: list (Loc.t * Time.t)),\n      (<<EVENT: write_not_to (fun loc ts => ~ List.In (loc, ts) l) e>>) /\\\n      (<<TIMES: List.Forall (fun locts => times (fst locts) (snd locts)) l>>).\nProof.\n  destruct e; try by (exists []; esplits; eauto); ss.\n  { exists [(loc, to)]. esplits; ss.\n    { des_ifs. ii. eapply H. auto. }\n    { econs; ss. des. auto. }\n  }\n  { exists [(loc, to)]. esplits; ss.\n    { ii. eapply H. auto. }\n    { econs; ss. des. auto. }\n  }\n  { exists [(loc, tsw)]. esplits; ss.\n    { ii. eapply H. auto. }\n    { econs; ss. des. auto. }\n  }\nQed.\n\nLemma write_not_to_mon P0 P1\n      (LE: P0 <2= P1)\n  :\n    write_not_to P1 <1= write_not_to P0.\nProof.\n  ii. unfold write_not_to in *. des_ifs; auto.\nQed.\n\nLemma traced_steps_finte_write_to (tr: Trace.t)\n      (times: Loc.t -> Time.t -> Prop)\n      (EVENTS: List.Forall (fun em => <<SAT: (wf_time_evt times) (snd em)>>) tr)\n  :\n    exists (l: list (Loc.t * Time.t)),\n      (<<EVENTS: List.Forall (fun em => write_not_to (fun loc ts => ~ List.In (loc, ts) l) (snd em)) tr>>) /\\\n      (<<TIMES: List.Forall (fun locts => times (fst locts) (snd locts)) l>>).\nProof.\n  ginduction tr.\n  { i. inv EVENTS. exists []. esplits; eauto. }\n  { i. inv EVENTS. exploit IHtr; eauto. i. des.\n    exploit (@step_finte_write_to (snd a)); eauto. i. des.\n    exists (l0 ++ l). esplits; eauto.\n    { econs; eauto.\n      { eapply write_not_to_mon; eauto. ii. eapply PR. eapply List.in_or_app; eauto. }\n      { eapply List.Forall_impl; eauto. i. ss.\n        eapply write_not_to_mon; eauto. ii. eapply PR. eapply List.in_or_app; eauto. }\n    }\n    { eapply Forall_app; eauto. }\n  }\nQed.\n\nLemma reserve_write_to (times: Loc.t -> Time.t -> Prop)\n      (DIVERGE: forall loc ts,\n          exists ts',\n            (<<TIMES: times loc ts'>>) /\\\n            (<<TS: Time.lt ts ts'>>))\n      mem\n      (MWF: memory_times_wf times mem)\n      loc ts\n      (TIMES: times loc ts)\n  :\n    (<<ALREADY: unattachable mem loc ts>>) \\/\n    (<<NEW: exists from mem',\n        (<<TS: Time.lt ts from>>) /\\\n        (<<ADD: Memory.add mem loc ts from Message.reserve mem'>>) /\\\n        (<<TIMES: times loc from>>) /\\\n        (<<MWF: memory_times_wf times mem'>>)>>).\nProof.\n  destruct (classic (unattachable mem loc ts)); auto. right.\n  hexploit (@cell_elements_least\n              (mem loc)\n              (fun to => exists from msg,\n                   (<<GET: Memory.get loc to mem = Some (from, msg)>>) /\\\n                   (<<TS: Time.lt ts from>>))).\n  i. des.\n  { hexploit (@Memory.add_exists mem loc ts from0 Message.reserve); ss.\n    { ii. destruct (Time.le_lt_dec from2 ts).\n      { eapply H. econs; eauto.\n        inv LHS. inv RHS. ss. eapply TimeFacts.lt_le_lt; eauto. }\n      { dup GET2. eapply LEAST in GET2.\n        { exploit memory_get_to_mon.\n          { eapply GET1. }\n          { eapply GET0. }\n          { inv LHS. inv RHS. ss. eapply TimeFacts.lt_le_lt; eauto. }\n          i. timetac.\n        }\n        esplits; eauto.\n      }\n    }\n    { econs. }\n    i. des. esplits; eauto.\n    { eapply MWF in GET0. des; auto. }\n    { eapply MWF in GET0. des.\n      ii. erewrite Memory.add_o in GET0; eauto. des_ifs.\n      { ss. des; clarify. }\n      { eapply MWF; eauto. }\n    }\n  }\n  { hexploit (DIVERGE loc ts). i. des.\n    hexploit (@Memory.add_exists mem loc ts ts' Message.reserve); ss.\n    { ii. eapply EMPTY; eauto. esplits; eauto.\n      destruct (Time.le_lt_dec from2 ts); auto. exfalso.\n      eapply H. econs; eauto.\n      inv LHS. inv RHS. ss. eapply TimeFacts.lt_le_lt; eauto. }\n    { econs. }\n    i. des. esplits; eauto.\n    ii. erewrite Memory.add_o in GET; eauto. des_ifs.\n    { ss. des; clarify. }\n    { eapply MWF; eauto. }\n  }\nQed.\n\nLemma reserve_write_tos times lang (th: Thread.t lang) tos\n      (DIVERGE: forall loc ts,\n          exists ts',\n            (<<TIMES: times loc ts'>>) /\\\n            (<<TS: Time.lt ts ts'>>))\n      (MWF: memory_times_wf times (Thread.memory th))\n      (MLE: Memory.le (Local.promises (Thread.local th)) (Thread.memory th))\n      (TIMES: List.Forall (fun locts => times (fst locts) (snd locts)) tos)\n  :\n    exists l tr prom' mem',\n      (<<STEPS: Trace.steps tr th (Thread.mk _ (Thread.state th) (Local.mk (Local.tview (Thread.local th)) prom') (Thread.sc th) mem')>>) /\\\n      (<<RESERVETRACE: List.Forall (fun em => <<SAT: (ThreadEvent.is_reserve /1\\ wf_time_evt times) (snd em)>>) tr>>) /\\\n      (<<ADDEDPROM: reservations_added l (Local.promises (Thread.local th)) prom'>>) /\\\n      (<<ADDEDMEM: reservations_added l (Thread.memory th) mem'>>) /\\\n      (<<WRITETO: forall loc ts (IN: List.In (loc, ts) tos),\n          unattachable mem' loc ts>>) /\\\n      (<<TIMES: List.Forall (fun locitv =>\n                               times (fst locitv) (fst (snd locitv)) /\\\n                               times (fst locitv) (snd (snd locitv))) l>>)\n.\nProof.\n  ginduction tos; i; ss.\n  { exists [], []. destruct th. destruct local. ss. esplits; eauto; ss.\n    { econs. }\n    { econs. }\n  }\n  { inv TIMES. exploit IHtos; eauto. i. des.\n    exploit reserve_write_to.\n    { eauto. }\n    { eapply memory_times_wf_traced in STEPS; eauto.\n      eapply List.Forall_impl; eauto. i. ss. des; auto. }\n    { eauto. }\n    i. ss. des.\n    { exists l, tr. esplits; eauto. i. des; auto. clarify. }\n    { exploit (@Memory.add_exists_le prom' mem'); eauto.\n      { eapply trace_steps_promises_le in STEPS; eauto. }\n      i. des.\n      assert (PROM: Memory.promise prom' mem' (fst a) (snd a) from Message.reserve promises2 mem'0 Memory.op_kind_add).\n      { econs; eauto. ss. }\n      destruct th. esplits.\n      { eapply Trace.steps_trans.\n        { eauto. }\n        { econs 2.\n          { econs 1. econs; eauto. }\n          { econs 1. }\n          { ss. }\n        }\n      }\n      { eapply Forall_app; eauto. econs; ss. }\n      { ss. eapply reservations_added_trans.\n        { eauto. }\n        { econs; eauto. econs. }\n      }\n      { ss. eapply reservations_added_trans.\n        { eauto. }\n        { econs; eauto. econs. }\n      }\n      { i. erewrite add_unattachable; eauto. des; clarify.\n        { right. splits; ss. refl. }\n        { eauto. }\n      }\n      { eapply Forall_app; eauto. }\n    }\n  }\nQed.\n\n\n\nLemma reservations_added_non_covered l mem0 mem1\n      (ADDED: reservations_added l mem0 mem1)\n      loc ts\n      (COVERED: covered loc ts mem0)\n  :\n    ~ intervals_sum l loc ts.\nProof.\n  ginduction l; eauto. i. inv ADDED. ss. ii.\n  des; clarify.\n  { inv COVERED. eapply add_succeed_wf in ADD. des.\n    eapply DISJOINT; eauto. }\n  { eapply IHl; eauto. erewrite add_covered; eauto. }\nQed.\n\nLemma add_unattachable_disjoint mem1 mem0 loc from to msg\n      (ADD: Memory.add mem0 loc from to msg mem1)\n      loc0 ts0\n      (UNATTACHABLE: unattachable mem0 loc0 ts0)\n  :\n    ~ (loc0 = loc /\\ Time.le from ts0 /\\ Time.lt ts0 to).\nProof.\n  ii. des; subst. inv UNATTACHABLE.\n  exploit add_succeed_wf; eauto. i. des.\n  hexploit DISJOINT; eauto. i. eapply disjoint_equivalent2 in H. des; ss.\n  { eapply TS1. eapply TimeFacts.le_lt_lt; eauto. }\n  { eapply Time.lt_strorder. eapply TimeFacts.le_lt_lt.\n    { eapply TS0. } eapply TimeFacts.le_lt_lt.\n    { instantiate (1:=ts0). unfold Time.join. des_ifs. }\n    { unfold Time.meet. des_ifs. }\n  }\nQed.\n\nLemma reservations_added_non_unattachable l mem0 mem1\n      (ADDED: reservations_added l mem0 mem1)\n      loc ts\n      (UNATTACHABLE: unattachable mem0 loc ts)\n  :\n    ~ intervals_sum_left l loc ts.\nProof.\n  ginduction l; eauto. i. inv ADDED. ss. ii.\n  des; clarify.\n  { exploit add_unattachable_disjoint; eauto. }\n  { eapply IHl; eauto. erewrite add_unattachable; eauto. }\nQed.\n\nLemma reservations_added_unattachable l mem0 mem1\n      (ADDED: reservations_added l mem0 mem1)\n      loc ts\n      (UNATTACHABLE: unattachable mem1 loc ts)\n  :\n    unattachable mem0 loc ts \\/ intervals_sum_left l loc ts.\nProof.\n  ginduction l; eauto. i.\n  { inv ADDED. auto. }\n  { i. inv ADDED. eapply IHl in TL; eauto. ss.\n    erewrite add_unattachable in TL; eauto. des; auto. }\nQed.\n\nDefinition eventable (mem prom: Memory.t) (spaces: Loc.t -> Time.t -> Prop)\n           (loc: Loc.t) (ts: Time.t): Prop :=\n  concrete_promised mem loc ts \\/\n  covered loc ts prom \\/\n  spaces loc ts.\n\nDefinition eventable_below (mem prom: Memory.t) (spaces: Loc.t -> Time.t -> Prop)\n           (loc: Loc.t) (ts: Time.t): Prop :=\n  exists to, <<TIME: eventable mem prom spaces loc to>> /\\ <<TS: Time.le ts to>>.\n\nLemma eventable_le_below mem0 prom0 mem1 prom1 spaces\n      (INCR: eventable mem1 prom1 spaces <2= eventable mem0 prom0 spaces)\n  :\n    eventable_below mem1 prom1 spaces <2= eventable_below mem0 prom0 spaces.\nProof.\n  ii. unfold eventable_below in *. des. esplits; eauto.\nQed.\n\n\nLemma event_in_concrete_or_writes_promise (spaces: Loc.t -> Time.t -> Prop)\n      prom0 mem0 loc from to msg prom1 mem1 kind\n      (PROMISE: Memory.promise prom0 mem0 loc from to msg prom1 mem1 kind)\n      (NOTIN: if Memory.op_kind_is_cancel kind\n              then True\n              else (forall ts (ITV: Interval.mem (from, to) ts),\n                       spaces loc ts \\/ covered loc ts mem0))\n      (CLOSED: Memory.closed mem0)\n  :\n    (<<INCR: eventable mem1 prom1 spaces <2= eventable mem0 prom0 spaces>>) /\\\n    (<<FROM: eventable_below mem0 prom0 spaces loc from>>) /\\\n    (<<TO: eventable_below mem0 prom0 spaces loc to>>).\nProof.\nAdmitted.\n  (* unfold eventable. inv PROMISE.\n  { exploit add_succeed_wf; try apply MEM; eauto. i. des.\n    splits.\n    { ii. des; auto.\n      { inv PR. erewrite Memory.add_o in GET; eauto. des_ifs.\n        { ss. des; clarify. right. exploit NOTIN; eauto.\n          { econs; eauto. refl. }\n          i. des; auto. inv x. exfalso. eapply DISJOINT; eauto.\n          econs; ss. refl.\n        }\n        { left. econs; eauto. }\n      }\n      { erewrite add_covered in PR; eauto. des; auto. subst.\n        right. right. exploit NOTIN; eauto. i. des; auto.\n        inv x. exfalso. eapply DISJOINT; eauto. }\n    }\n    { exists to. esplits; eauto.\n      { right. right. exploit NOTIN; eauto.\n        { econs; eauto. refl. }\n        i. des; auto. inv x. exfalso. eapply DISJOINT; eauto.\n        econs; ss. refl.\n      }\n      { left. auto. }\n    }\n    { exists to. esplits; eauto.\n      { right. right. exploit NOTIN; eauto.\n        { econs; eauto. refl. }\n        i. des; auto. inv x. exfalso. eapply DISJOINT; eauto.\n        econs; ss. refl.\n      }\n      { refl. }\n    }\n  }\n  { exploit split_succeed_wf; try apply PROMISES; eauto. i. des.\n    splits.\n    { ii. des; auto.\n      { inv PR. erewrite Memory.split_o in GET; eauto. des_ifs.\n        { ss. des; clarify. right. left. econs; eauto.\n          econs; eauto. ss. left. auto. }\n        { ss. des; clarify. right. left. econs; eauto.\n          econs; eauto. ss. refl. }\n        { left. econs; eauto. }\n      }\n      { erewrite split_covered in PR; eauto. }\n    }\n    { exists ts3. esplits; eauto.\n      { right. left. econs; eauto. econs; eauto. refl. }\n      { left. etrans; eauto. }\n    }\n    { exists ts3. esplits; eauto.\n      { right. left. econs; eauto. econs; eauto. refl. }\n      { left. auto. }\n    }\n  }\n  { exploit lower_succeed_wf; try apply PROMISES; eauto. i. des.\n    splits.\n    { ii. des; auto.\n      { inv PR. erewrite Memory.lower_o in GET0; eauto. des_ifs.\n        { ss. des; clarify. right. left. econs; eauto.\n          econs; eauto. ss. refl. }\n        { left. econs; eauto. }\n      }\n      { erewrite lower_covered in PR; eauto. }\n    }\n    { exists to. esplits; eauto.\n      { right. left. econs; eauto. econs; eauto. refl. }\n      { left. eauto. }\n    }\n    { exists to. esplits; eauto.\n      { right. left. econs; eauto. econs; eauto. refl. }\n      { refl. }\n    }\n  }\n  { exploit Memory.remove_get0; try apply PROMISES; eauto. i. des.\n    assert (TS: Time.lt from to).\n    { exploit Memory.remove_get0; try apply MEM; eauto. i. des.\n      inv CLOSED. apply memory_get_ts_strong in GET. des; auto.\n      subst. erewrite INHABITED in GET1. ss. }\n    splits.\n    { ii. des; auto.\n      { inv PR. erewrite Memory.remove_o in GET1; eauto. des_ifs.\n        left. econs; eauto. }\n      { erewrite remove_covered in PR; eauto. des; auto. }\n    }\n    { exists to. esplits; eauto.\n      { right. left. econs; eauto. econs; eauto. refl. }\n      { left. eauto. }\n    }\n    { exists to. esplits; eauto.\n      { right. left. econs; eauto. econs; eauto. refl. }\n      { refl. }\n    }\n  }\nQed. *)\n\nLemma event_in_concrete_or_writes_write (spaces: Loc.t -> Time.t -> Prop)\n      prom0 mem0 loc from to prom1 mem1 val released kind\n      (PROMISE: Memory.write prom0 mem0 loc from to val released prom1 mem1 kind)\n      (NOTIN: if Memory.op_kind_is_cancel kind\n              then True\n              else (forall ts (ITV: Interval.mem (from, to) ts),\n                       spaces loc ts \\/ covered loc ts mem0))\n      (CLOSED: Memory.closed mem0)\n  :\n    (<<INCR: eventable mem1 prom1 spaces <2= eventable mem0 prom0 spaces>>) /\\\n    (<<FROM: eventable_below mem0 prom0 spaces loc from>>) /\\\n    (<<TO: eventable_below mem0 prom0 spaces loc to>>).\nProof.\n  inv PROMISE.\n  exploit event_in_concrete_or_writes_promise; eauto. i. des. esplits; eauto.\n  i. eapply INCR. unfold eventable in *. des; auto.\n  erewrite remove_covered in PR; eauto. des; auto.\nQed.\n\nLemma step_eventable_time lang (th0 th1: Thread.t lang) pf e\n      (spaces: Loc.t -> Time.t -> Prop)\n      (STEP: Thread.step pf e th0 th1)\n      (WRITENOTIN: write_not_in (fun loc ts => ~ (spaces loc ts \\/ covered loc ts (Thread.memory th0))) e)\n      (CLOSED: Memory.closed (Thread.memory th0))\n  :\n    (<<INCR: eventable (Thread.memory th1) (Local.promises (Thread.local th1)) spaces <2= eventable (Thread.memory th0) (Local.promises (Thread.local th0)) spaces>>) /\\\n    (<<TIMES: tevent_map_weak\n                (fun loc ts fts => ts = fts /\\\n                                   eventable_below (Thread.memory th0) (Local.promises (Thread.local th0)) spaces loc ts) e e>>).\nProof.\n  inv STEP.\n  { inv STEP0; ss. inv LOCAL.\n    eapply event_in_concrete_or_writes_promise in PROMISE; ss.\n    { des. splits; eauto. econs; eauto. }\n    { des_ifs. ii. apply NNPP. eapply WRITENOTIN; eauto. }\n  }\n  { inv STEP0; ss. inv LOCAL; ss; eauto.\n    { splits; auto. econs. }\n    { inv LOCAL0. ss. splits; auto. econs; eauto. split; auto.\n      exists ts. splits; ss.\n      { left. econs; eauto. }\n      { refl. }\n    }\n    { inv LOCAL0. eapply event_in_concrete_or_writes_write in WRITE; eauto.\n      { des. splits; eauto. econs; eauto. }\n      { des_ifs. ii. eapply NNPP. eauto. }\n    }\n    { inv LOCAL1. inv LOCAL2. eapply event_in_concrete_or_writes_write in WRITE; eauto.\n      { des. splits; eauto. econs; eauto. }\n      { des_ifs. ii. eapply NNPP. eauto. }\n    }\n    { inv LOCAL0. ss. splits; auto. econs; eauto. }\n    { inv LOCAL0. ss. splits; auto. econs; eauto. }\n    { inv LOCAL0. ss. splits; auto. econs; eauto. }\n }\nQed.\n\nLemma tevent_map_weak_mon (f0 f1: Loc.t -> Time.t -> Time.t -> Prop)\n      (LE: f0 <3= f1)\n  :\n    tevent_map_weak f0 <2= tevent_map_weak f1.\nProof.\n  i. inv PR; econs; eauto.\nQed.\n\nLemma traced_steps_eventable_time_normal lang (th0 th1: Thread.t lang) tr\n      (spaces: Loc.t -> Time.t -> Prop)\n      (STEPS: Trace.steps tr th0 th1)\n      (WRITENOTIN: List.Forall (fun em => (write_not_in (fun loc ts => ~ (spaces loc ts \\/ covered loc ts (Thread.memory th0))) /1\\ (fun e => ~ ThreadEvent.is_cancel e)) (snd em)) tr)\n      (MEM: Memory.closed (Thread.memory th0))\n      (LOCAL: Local.wf (Thread.local th0) (Thread.memory th0))\n      (SC: Memory.closed_timemap (Thread.sc th0) (Thread.memory th0))\n  :\n    (<<INCR: eventable (Thread.memory th1) (Local.promises (Thread.local th1)) spaces <2= eventable (Thread.memory th0) (Local.promises (Thread.local th0)) spaces>>) /\\\n    (<<TIMES: List.Forall2\n                (fun em fem =>\n                   tevent_map_weak (fun loc ts fts => ts = fts /\\ eventable_below (Thread.memory th0) (Local.promises (Thread.local th0)) spaces loc ts)\n                                   (snd fem) (snd em)) tr tr>>).\nProof.\n  ginduction STEPS.\n  { i. splits; ss. }\n  { i. subst. inv WRITENOTIN.\n    exploit Thread.step_future; eauto. i. des.\n    exploit IHSTEPS; eauto.\n    { eapply List.Forall_impl; eauto.\n      i. ss. des. splits; auto. eapply write_not_in_mon; eauto. i. ss.\n      ii. eapply PR. des; eauto. right.\n      eapply step_not_cancel_covered_increase; eauto. }\n    i. des.\n    hexploit step_eventable_time; eauto.\n    i. des. esplits; eauto. econs; ss; eauto.\n    eapply list_Forall2_impl; eauto.\n    i. ss. eapply tevent_map_weak_mon; eauto.\n    i. ss. des. subst. splits; auto.\n    eapply eventable_le_below; eauto.\n  }\nQed.\n\nLemma traced_steps_eventable_time_cancel lang (th0 th1: Thread.t lang) tr\n      (spaces: Loc.t -> Time.t -> Prop)\n      (STEPS: Trace.steps tr th0 th1)\n      (WRITENOTIN: List.Forall (fun em => ThreadEvent.is_cancel (snd em)) tr)\n      (MEM: Memory.closed (Thread.memory th0))\n      (LOCAL: Local.wf (Thread.local th0) (Thread.memory th0))\n      (SC: Memory.closed_timemap (Thread.sc th0) (Thread.memory th0))\n  :\n    (<<INCR: eventable (Thread.memory th1) (Local.promises (Thread.local th1)) spaces <2= eventable (Thread.memory th0) (Local.promises (Thread.local th0)) spaces>>) /\\\n    (<<TIMES: List.Forall2\n                (fun em fem =>\n                   tevent_map_weak (fun loc ts fts => ts = fts /\\ eventable_below (Thread.memory th0) (Local.promises (Thread.local th0)) spaces loc ts)\n                                   (snd fem) (snd em)) tr tr>>).\nProof.\n  ginduction STEPS.\n  { i. splits; ss. }\n  { i. subst. inv WRITENOTIN.\n    exploit Thread.step_future; eauto. i. des.\n    hexploit step_eventable_time; eauto.\n    { instantiate (1:=spaces). destruct e; ss. des_ifs. }\n    exploit IHSTEPS; eauto. i. des.\n    splits; eauto. econs; eauto.\n    eapply list_Forall2_impl; eauto.\n    i. ss. eapply tevent_map_weak_mon; eauto.\n    i. ss. des. subst. splits; auto.\n    eapply eventable_le_below; eauto.\n  }\nQed.\n\nLemma reservations_added_covered mem0 mem1 l\n      (ADDED: reservations_added l mem0 mem1)\n      loc ts\n  :\n    covered loc ts mem1 <-> (covered loc ts mem0 \\/ intervals_sum l loc ts).\nProof.\n  ginduction l; ss.\n  { i. inv ADDED. split; i; des; ss; auto. }\n  { i. inv ADDED. rewrite IHl; eauto.\n    rewrite (@add_covered mem3 mem0); eauto. split; i; des; auto. }\nQed.\n\nLemma reservations_added_covered_rev mem0 mem1 l\n      (ADDED: reservations_added l mem0 mem1)\n      loc ts\n  :\n    covered loc ts mem0 <-> (covered loc ts mem1 /\\ ~ intervals_sum l loc ts).\nProof.\n  split; i.\n  { split.\n    { eapply reservations_added_covered; eauto. }\n    { eapply reservations_added_non_covered; eauto. }\n  }\n  { des. eapply reservations_added_covered in H; eauto. des; ss. }\nQed.\n\nLemma can_reserve_all_needed times\n      (DIVERGE: forall loc ts,\n          exists ts',\n            (<<TIMES: times loc ts'>>) /\\\n            (<<TS: Time.lt ts ts'>>))\n      lang\n      st0 st1 lc0 lc1 sc0 sc1 mem0 mem1 tr\n      (MWF: memory_times_wf times mem0)\n      (STEPS: Trace.steps tr (Thread.mk lang st0 lc0 sc0 mem0) (Thread.mk lang st1 lc1 sc1 mem1))\n      (EVENTS: List.Forall (fun em => <<SAT: ((fun e => ~ ThreadEvent.is_cancel e) /1\\ wf_time_evt times) (snd em)>>) tr)\n      (MEM: Memory.closed mem0)\n      (LOCAL: Local.wf lc0 mem0)\n      (SC: Memory.closed_timemap sc0 mem0)\n  :\n    exists lc0' mem0' tr_reserve tr_cancel reserves,\n      (<<RESERVESTEPS:\n         Trace.steps tr_reserve (Thread.mk lang st0 lc0 sc0 mem0) (Thread.mk lang st0 lc0' sc0 mem0')>>) /\\\n      (<<RESERVETRACE:\n         List.Forall (fun em => <<SAT: (ThreadEvent.is_reserve /1\\ wf_time_evt times) (snd em)>>) tr_reserve>>) /\\\n      (<<CANCELTRACE: List.Forall (fun em => <<SAT: (ThreadEvent.is_cancel /1\\ wf_time_evt times) (snd em)>>) tr_cancel>>) /\\\n      (<<RESERVEMEM: reservations_added reserves mem0 mem0'>>) /\\\n      (<<CAP:\n         forall cap0'\n                (MLE: Memory.le mem0' cap0'),\n         exists cap0 cap1 ,\n           (<<CANCELSTEPS:\n              Trace.steps tr_cancel (Thread.mk lang st0 lc0' sc0 cap0') (Thread.mk lang st0 lc0 sc0 cap0)>>) /\\\n           (<<STEPS:\n              Trace.steps tr (Thread.mk lang st0 lc0 sc0 cap0) (Thread.mk lang st1 lc1 sc1 cap1)>>) /\\\n           (<<RESERVEMEM: reservations_added reserves cap0 cap0'>>)>>) /\\\n      (<<TIMES: forall max\n                       (MAX: concrete_promise_max_timemap mem0' (Local.promises lc0') max),\n          List.Forall2\n            (fun em fem =>\n               tevent_map_weak (fun loc ts fts => ts = fts /\\ Time.le ts (max loc))\n                               (snd fem) (snd em)) (tr_cancel ++ tr) (tr_cancel ++ tr)>>)\n.\nProof.\n  exploit (@traced_steps_finte_write_to tr); eauto.\n  { eapply List.Forall_impl; eauto. i. ss. des. eauto. }\n  intros [tos ?]. des.\n  exploit traced_steps_needed_spaces; eauto.\n  i. des.\n  exploit reserve_empty_intervals; eauto.\n  { eapply LOCAL. }\n  i. des. ss.\n  assert (MLE: Memory.le prom' mem').\n  { eapply trace_steps_promises_le in STEPS0; eauto. eapply LOCAL. }\n  exploit reserve_write_tos.\n  { eauto. }\n  { eapply memory_times_wf_traced in STEPS0; eauto.\n    eapply List.Forall_impl; eauto. i. ss. des. eauto.\n  }\n  { ss. }\n  { eauto. }\n  i. des. ss.\n  assert (ADDEDPROMALL: reservations_added (l ++ l0) (Local.promises lc0) prom'0).\n  { eapply reservations_added_trans; eauto. }\n  assert (ADDEDMEMALL: reservations_added (l ++ l0) mem0 mem'0).\n  { eapply reservations_added_trans; eauto. }\n  hexploit cancel_reservations_added.\n  { instantiate (1:=Local.mk (Local.tview lc0) prom'0). eapply ADDEDPROMALL. }\n  { eapply Forall_app; eauto. }\n  i. des.\n  assert (CAP: forall cap0'\n                      (MLE: Memory.le mem'0 cap0'),\n             exists cap0 cap1,\n               Trace.steps\n                 tr2\n                 (Thread.mk _ st0 {| Local.tview := Local.tview lc0; Local.promises := prom'0 |} sc0 cap0')\n                 (Thread.mk _ st0 lc0 sc0 cap0) /\\\n               Trace.steps\n                 tr\n                 (Thread.mk _ st0 lc0 sc0 cap0)\n                 (Thread.mk _ st1 lc1 sc1 cap1) /\\\n               (<<ADDED: reservations_added (l ++ l0) cap0 cap0'>>))\n  .\n  { i. ss. exploit (H0 st0 sc0 cap0').\n    { etrans; eauto. eapply trace_steps_promises_le in STEPS1; eauto. }\n    i. des.\n    assert (MLE1: Memory.le mem0 mem'1).\n    { eapply reservations_added_le_le.\n      { eapply ADDEDMEMALL. }\n      { eapply MLE0. }\n      { eauto. }\n    }\n    hexploit traced_step_lifting.\n    { eapply STEPS. }\n    { eapply list_Forall_sum.\n      { eapply list_Forall_sum.\n        { eapply EVENTS. }\n        { eapply EVENTS0. }\n        { instantiate (1:=fun em => <<SAT: ((fun e => ~ ThreadEvent.is_cancel e) /1\\ write_not_to (fun loc ts => ~ List.In (loc, ts) tos)) (snd em)>>).\n          i. ss. des. splits; auto. }\n      }\n      { eapply WRITENOTIN. }\n      i. ss. des. splits; eauto.\n    }\n    { eapply MLE1. }\n    { i. destruct (classic (covered loc ts mem0)); auto. right.\n      ii. des; ss. eapply reservations_added_non_covered in ADDEDMEM1; eauto.\n      eapply ADDEDMEM1. erewrite intervals_sum_interval.\n      erewrite intervals_sum_interval in H1. des. esplits; eauto.\n      eapply List.in_or_app; eauto. }\n    { i. destruct (classic (unattachable mem0 loc ts)); auto. right.\n      ii. des; ss. eapply reservations_added_non_unattachable in ADDEDMEM1; eauto.\n      eapply ADDEDMEM1. erewrite intervals_sum_left_interval.\n      eapply WRITETO in H1. eapply reservations_added_unattachable in H1; eauto.\n      des; ss. }\n    { eauto. }\n    { eauto. }\n    { eauto. }\n    i. des. exists mem'1, cap1.\n    splits; eauto. destruct lc0. ss.\n  }\n  esplits.\n  { eapply Trace.steps_trans.\n    { eapply STEPS0. }\n    { eapply STEPS1. }\n  }\n  { eapply Forall_app; eauto. }\n  { eapply CANCELTRACE. }\n  { eauto. }\n  { i. exploit CAP; eauto. }\n  { i. exploit (CAP mem'0).\n    { refl. }\n    i. des. ss.\n    exploit Trace.steps_future; try apply STEPS0; eauto. i. des. ss.\n    exploit Trace.steps_future; try apply STEPS1; eauto. i. des. ss.\n    exploit Trace.steps_future; try apply x0; eauto. i. des. ss.\n    exploit traced_steps_eventable_time_cancel; try apply x0; eauto; ss.\n    { eapply List.Forall_impl; eauto. i. ss. des. splits; auto. }\n    instantiate (1:=intervals_sum l). i. ss. des.\n    assert (EVENTTIMES: forall loc ts\n                               (EVENTABLE: eventable_below mem'0 prom'0 (intervals_sum l) loc ts),\n               Time.le ts (max loc)).\n    { i. unfold eventable_below in EVENTABLE. des. etrans; eauto.\n      unfold eventable in TIME. des.\n      { inv TIME. eapply MAX in GET. auto. }\n      { inv TIME. eapply MAX in GET. inv ITV. ss. etrans; eauto. }\n      { eapply reservations_added_covered in ADDEDPROM; eauto. des.\n        exploit ADDEDPROM1.\n        { right. eauto. }\n        i. eapply reservations_added_covered in ADDEDPROM0; eauto. des.\n        exploit ADDEDPROM2.\n        { left. eauto. }\n        i. inv x2. eapply MAX in GET. inv ITV. ss. etrans; eauto.\n      }\n    }\n    eapply List.Forall2_app.\n    { eapply list_Forall2_impl; eauto. i. ss.\n      eapply tevent_map_weak_mon; eauto. i. ss. des. subst. splits; auto. }\n    { exploit traced_steps_eventable_time_normal; try apply x1; eauto; ss.\n      { instantiate (1:=intervals_sum l).\n        eapply list_Forall_sum.\n        { eapply EVENTS. }\n        { eapply WRITENOTIN. }\n        i. ss. des. splits; auto.\n        eapply write_not_in_mon; eauto. i. ss. ii. eapply PR.\n        apply or_comm in H. apply or_strengthen in H. des; auto. right.\n        erewrite reservations_added_covered_rev; try apply ADDED; eauto.\n        erewrite reservations_added_covered_rev in SAT; try apply ADDEDMEMALL; eauto.\n      }\n      { i. des. eapply list_Forall2_impl; eauto. i. ss.\n        eapply tevent_map_weak_mon; eauto. i. ss. des. subst. splits; auto.\n        eapply eventable_le_below in PR0; eauto. }\n    }\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/promising/prop/PreReserve.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.25977819845747463}}
{"text": "Require Export Arith.EqNat.\nRequire Export Arith.Le.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Program.Equality.\nRequire Import Coq.Lists.List.\nRequire Import Psatz.\nRequire Import ZArith.\nRequire Import Coq.Arith.Compare_dec.\nImport ListNotations.\n\nRequire Import vars.\nRequire Import env.\nRequire Import tactics.\nRequire Import NatSets.\nRequire Import setfacts.\nRequire Import qualifiers.\n\nImport QualNotations.\nLocal Open Scope qualifiers.\n\n(* Import the most relevant definitions from NatSet.F. A full import pollutes the namespace, affecting name generation.*)\nModule NatSetView.\n  Import NatSet.\n  Export F(singleton,mem,inter,union,remove,In,max_elt,Subset,Equal,is_empty,Empty).\n  Notation \"s [=] t\" := (Equal s t) (at level 70, no associativity).\n  Notation \"s [<=] t\" := (Subset s t) (at level 70, no associativity).\nEnd NatSetView.\nImport NatSetView.\n\n(* Definitions *)\n\n(* ### Syntax ### *)\n(* We represent terms and types in locally nameless style. *)\nInductive ty : Type :=\n| TUnit : ty\n| TFun  : qual -> qual -> ty -> ty -> ty\n| TRef  : qual -> ty -> ty\n.\n\nInductive tm : Type :=\n| tunit   : tm\n| tvar    : var -> tm\n| tabs    : tm  -> tm (* convention: #0: self-ref, #1: argument *)\n| tapp    : tm  -> tm -> tm\n| tloc    : loc -> tm\n| tref    : tm  -> tm\n| tderef  : tm  -> tm\n| tassign : tm  -> tm -> tm\n.\nNotation \"& l\"   := (tloc l) (at level 0, right associativity).\nNotation \"! t\"   := (tderef t) (at level 0, right associativity).\nCoercion tvar : var >-> tm. (* lightens the notation of term variables *)\n\nDefinition tenv := list (bool * ty * qual). (* (isFunctionSelfRef, Type, Qual) *)\nDefinition senv := list (ty * qual). (* Sigma store typing *)\n\nDefinition extends {A} (l1 l2 : list A): Prop := exists l', l1 = l' ++ l2.\nNotation \"x ⊇ y\" := (extends x y) (at level 75). (* \\supseteq*)\n\nNotation \"‖ x ‖\" := (length x) (at level 10). (* \\Vert *)\n\n(* Opening a term *)\nFixpoint open_rec_tm (k : nat) (u : tm) (t : tm) {struct t} : tm :=\n  match t with\n  | tunit            => tunit\n  | tvar   (varF x) => tvar (varF x)\n  | tvar   (varB x) => if Nat.eqb k x then u else tvar (varB x)\n  | tabs    t       => tabs    (open_rec_tm (S (S k)) u t)\n  | tapp    t1 t2   => tapp    (open_rec_tm k u t1) (open_rec_tm k u t2)\n  | tloc    l       => tloc l\n  | tref    t       => tref    (open_rec_tm k u t)\n  | tderef  t       => tderef  (open_rec_tm k u t)\n  | tassign t1 t2   => tassign (open_rec_tm k u t1) (open_rec_tm k u t2)\n  end\n.\n\n(*simultaneous opening with self-ref and argument: *)\nDefinition open_tm (u u' t : tm) := open_rec_tm 1 u' (open_rec_tm 0 u t).\nDefinition open_tm' {A : Type} (env : list A) t := open_rec_tm 1 $(S (‖ env ‖)) (open_rec_tm 0 ($‖env‖) t).\n\n(* Opening a qualifier *)\nDefinition open_qual (k : nat) (q' : qual) (q : qual) : qual :=\n  match q with\n  | qset fresh1 vs bs ls =>\n    match mem k bs with\n    | true => (qset fresh1 vs (remove k bs) ls) ⊔ q'\n    | _    => qset fresh1 vs bs ls\n    end\n  end.\nDefinition openq (u u' q : qual) : qual := open_qual 1 u' (open_qual 0 u q).\nDefinition openq' {A} (env : list A) q  := openq ($!‖env‖) $!(S (‖env‖)) q.\n\n(* Opening a type with a qualifier *)\nFixpoint open_rec_ty (k : nat) (d' : qual) (T : ty) : ty :=\n  match T with\n  | TUnit            => TUnit\n  | TFun d1 d2 T1 T2 => TFun (open_qual k d' d1) (open_qual (S (S k)) d' d2) (open_rec_ty k d' T1) (open_rec_ty (S (S k)) d' T2)\n  | TRef d1 T        => TRef (open_qual k d' d1) (open_rec_ty k d' T)\n  end.\nDefinition open_ty (u u' : qual) (T : ty) := (open_rec_ty 1 u' (open_rec_ty 0 u T)).\nDefinition open_ty' {A : Type} (env : list A) (T : ty) := open_ty $!(‖env‖) $!(S (‖env‖)) T.\n\nModule OpeningNotations.\n  Declare Scope opening.\n  Notation \"[[ k ~> u ]]ᵗ t\"  := (open_rec_tm k u t) (at level 10) : opening.\n  Notation \"[[ k ~> U ]]ᵀ T\"  := (open_rec_ty k U T) (at level 10) : opening.\n  Notation \"[[ k ~> q' ]]ᵈ q\" := (open_qual k q' q) (at level 10) : opening.\n  Notation \"t <~ᵗ q ; q'\"     := (open_tm q q' t) (at level 10, q at next level) : opening.\n  Notation \"T <~ᵀ q ; q'\"     := (open_ty q q' T) (at level 10, q at next level) : opening.\n  Notation \"q <~ᵈ q' ; q''\"   := (openq q' q'' q) (at level 10, q' at next level) : opening.\n  Notation \"t <~²ᵗ g\"         := (open_tm' g t) (at level 10) : opening.\n  Notation \"T <~²ᵀ g\"         := (open_ty' g T) (at level 10) : opening.\n  Notation \"q <~²ᵈ g\"         := (openq' g q) (at level 10) : opening.\nEnd OpeningNotations.\nImport OpeningNotations.\nLocal Open Scope opening.\n\n(* measure for induction over types *)\nFixpoint ty_size (T : ty) : nat :=\n  match T with\n  | TUnit           => 0\n  | TFun  _ _ T1 T2 => S (ty_size T1 + ty_size T2)\n  | TRef  _ T       => S (ty_size T)\n  end.\n\nFixpoint splice (n : nat) (t : tm) {struct t} : tm :=\n  match t with\n  | tunit          => tunit\n  | tvar (varF i)  =>\n    if le_lt_dec n i then tvar (varF (S i))\n    else tvar (varF i)\n  | tvar (varB i)  => tvar    (varB i)\n  | tabs    t      => tabs    (splice n t)\n  | tapp    t1 t2  => tapp    (splice n t1) (splice n t2)\n  | tloc    l      => tloc     l\n  | tref    t      => tref    (splice n t)\n  | tderef  t      => tderef  (splice n t)\n  | tassign t1 t2  => tassign (splice n t1) (splice n t2)\n  end.\n\nDefinition splice_qual (n : nat) (d : qual) : qual :=\n  match d with\n  | qset fresh vs bs ls => qset fresh (splice_set n vs) bs ls\n  end.\n\nFixpoint splice_ty (n : nat) (T : ty) {struct T} : ty :=\n  match T with\n  | TUnit            => TUnit\n  | TFun d1 d2 T1 T2 => TFun (splice_qual n d1) (splice_qual n d2) (splice_ty n T1) (splice_ty n T2)\n  | TRef d1 T        => TRef (splice_qual n d1) (splice_ty n T)\n  end.\n\nDefinition splice_tenv (n : nat) (Γ : tenv) : tenv :=\n  map (fun p => (fst (fst p), (splice_ty n (snd (fst p))), (splice_qual n (snd p)))) Γ.\n\nModule SplicingNotations.\n  Declare Scope splicing.\n  Notation \"t ↑ᵗ n\" := (splice n t) (at level 10) : splicing.\n  Notation \"T ↑ᵀ n\" := (splice_ty n T) (at level 10) : splicing.\n  Notation \"q ↑ᵈ n\" := (splice_qual n q) (at level 10) : splicing.\n  Notation \"g ↑ᴳ n\" := (splice_tenv n g) (at level 10) : splicing.\nEnd SplicingNotations.\nImport SplicingNotations.\nLocal Open Scope splicing.\n\nInductive closed_tm: nat(*B*) -> nat(*F*) -> nat(*Loc*) -> tm -> Prop :=\n| cl_tsct : forall b f l,\n    closed_tm b f l tunit\n| cl_tvarb: forall b f l x,\n    x < b ->\n    closed_tm b f l #x\n| cl_tvarf: forall b f l x,\n    x < f ->\n    closed_tm b f l $x\n| cl_tabs:  forall b f l tm,\n    closed_tm (S (S b)) f l tm ->\n    closed_tm b f l (tabs tm)\n| cl_tapp:  forall b f l tm1 tm2,\n    closed_tm b f l tm1 ->\n    closed_tm b f l tm2 ->\n    closed_tm b f l (tapp tm1 tm2)\n| cl_tloc: forall b f l l',\n    l' < l ->\n    closed_tm b f l &l'\n| cl_tref:  forall b f l tm,\n    closed_tm b f l tm ->\n    closed_tm b f l (tref tm)\n| cl_tderef:  forall b f l tm,\n    closed_tm b f l tm ->\n    closed_tm b f l (tderef tm)\n| cl_tassign:  forall b f l tm1 tm2,\n    closed_tm b f l tm1 ->\n    closed_tm b f l tm2 ->\n    closed_tm b f l (tassign tm1 tm2)\n.\n#[global] Hint Constructors closed_tm : core.\n\nInductive closed_qual : nat(*B*) -> nat(*F*) -> nat(*Loc*) -> qual -> Prop :=\n| cl_qset : forall b f l fresh vs bs ls,\n    bound vs <= f ->\n    bound bs <= b ->\n    bound ls <= l ->\n    closed_qual b f l (qset fresh vs bs ls)\n.\n#[global] Hint Constructors closed_qual : core.\n\nInductive closed_ty : nat(*B*) -> nat(*F*) -> nat(*Loc*) -> ty -> Prop :=\n| cl_TUnit : forall b f l,\n    closed_ty b f l TUnit\n| cl_TRef : forall b f l T q,\n    closed_ty 0 0 0 T ->\n    closed_qual b f l q ->\n    closed_ty b f l (TRef q T)\n| cl_TFun : forall b f l d1 d2 T1 T2,\n    closed_qual b f l d1 ->\n    closed_qual (S (S b)) f l d2 ->\n    closed_ty b f l T1 ->\n    closed_ty (S (S b)) f l T2 ->\n    closed_ty b f l (TFun d1 d2 T1 T2)\n.\n#[global] Hint Constructors closed_ty : core.\n\nInductive qstp : tenv -> senv -> qual -> qual -> Prop :=\n| qs_sq : forall Γ Σ d1 d2,\n    d1 ⊑ d2 ->\n    closed_qual 0 (‖Γ‖) (‖Σ‖) d2 ->\n    qstp Γ Σ d1 d2\n| qs_self : forall Γ Σ f df T1 d1 T2 d2,\n    indexr f Γ = Some (true, (TFun d1 d2 T1 T2), df) ->\n    closed_qual 0 f (‖Σ‖) df ->\n    ♦∉ df ->\n    qstp Γ Σ (df ⊔ $!f) $!f\n| qs_qvar : forall Γ Σ b U x q1,\n    indexr x Γ = Some(b, U, q1) ->\n    closed_ty 0 x (‖Σ‖) U ->\n    closed_qual 0 x (‖Σ‖) q1 ->\n    ♦∉ q1 ->\n    qstp Γ Σ $!x q1\n| qs_cong : forall Γ Σ q d1 d2,\n    qstp Γ Σ d1 d2 ->\n    closed_qual 0 (‖Γ‖) (‖Σ‖) q ->\n    qstp Γ Σ (q ⊔ d1) (q ⊔ d2)\n| qs_trans : forall Γ Σ d1 d2 d3,\n    qstp Γ Σ d1 d2 -> qstp Γ Σ d2 d3 -> qstp Γ Σ d1 d3\n.\n#[global] Hint Constructors qstp : core.\n\nInductive stp : tenv -> senv -> ty -> qual -> ty -> qual -> Prop :=\n| s_base : forall Γ Σ d1 d2,\n    qstp Γ Σ d1 d2 ->\n    stp Γ Σ TUnit d1 TUnit d2\n| s_ref : forall Γ Σ T1 T2 q d1 d2,\n    qstp Γ Σ d1 d2 ->\n    stp [] [] T1 ∅ T2 ∅ ->\n    stp [] [] T2 ∅ T1 ∅ ->\n    closed_qual 0 (‖Γ‖) (‖Σ‖) q ->\n    stp Γ Σ (TRef q T1) d1 (TRef q T2) d2\n| s_fun : forall Γ Σ T1 d1 T2 d2 T3 d3 T4 d4 d5 d6,\n    closed_ty 0 (‖ Γ ‖) (‖ Σ ‖) (TFun d1 d2 T1 T2) ->\n    closed_ty 0 (‖ Γ ‖) (‖ Σ ‖) (TFun d3 d4 T3 T4) ->\n    qstp Γ Σ d5 d6 ->\n    stp Γ Σ T3 d3 T1 d1 ->\n    stp ((false, T3,d3) :: (true, TFun d1 d2 T1 T2, {♦}) :: Γ) Σ (open_ty' Γ T2) (openq' Γ d2) (open_ty' Γ T4) (openq' Γ d4) ->\n    stp Γ Σ (TFun d1 d2 T1 T2) d5 (TFun d3 d4 T3 T4) d6\n.\n#[global] Hint Constructors stp : core.\n\n(* Specifies that q covers variable x's qualifier in context Γ|Σ *)\nInductive saturated_var (Γ : tenv) (Σ : senv) (x : id) (q : qual) : Prop :=\n| sat_var : forall b U q',\n    indexr x Γ = Some (b, U, q') ->\n    q' ⊑ q ->\n    closed_qual 0 x (‖Σ‖) q' ->\n    saturated_var Γ Σ x q.\nArguments sat_var {Γ Σ x q}.\n#[global] Hint Constructors saturated_var : core.\n\n(* q covers l's qualifier in Σ *)\nInductive saturated_loc (Σ : senv) (l : id) (q : qual) : Prop :=\n| sat_loc : forall U q',\n    indexr l Σ = Some (U, q') ->\n    q' ⊑ q ⊔ {♦} ->\n    closed_qual 0 0 l q' ->\n    saturated_loc Σ l q.\nArguments sat_loc {Σ l q}.\n#[global] Hint Constructors saturated_loc : core.\n\nDefinition tenv_saturated (Γ : tenv) (Σ : senv) (q: qual) : Prop := (forall x, (varF x) ∈ᵥ q -> saturated_var Γ Σ x q).\nDefinition senv_saturated (Σ : senv) (q: qual) : Prop := (forall l, l ∈ₗ q -> saturated_loc Σ l q).\n#[global] Hint Unfold tenv_saturated : core.\n#[global] Hint Unfold senv_saturated : core.\n\n(* Specifies that q is transitively closed w.r.t. Γ|Σ, i.e., q covers each of its contained variables/locations in Γ|Σ *)\nInductive saturated (Γ : tenv) (Σ : senv) (q: qual) : Prop :=\n| sat_qual : tenv_saturated Γ Σ q ->\n             senv_saturated Σ q ->\n             saturated Γ Σ q\n.\nArguments sat_qual {Γ Σ q}.\n#[global] Hint Constructors saturated : core.\n\n(* Store typing contains closed types and well-scoped, saturated qualifiers. *)\nInductive wf_senv : senv -> Prop :=\n| wf_senv_nil : wf_senv []\n| wf_senv_cons : forall Σ T q,\n    wf_senv Σ ->\n    closed_ty 0 0 (‖Σ‖) T ->\n    closed_qual 0 0 (‖Σ‖) q ->\n    senv_saturated Σ q ->\n    wf_senv ((T, q) :: Σ)\n.\n#[global] Hint Constructors wf_senv : core.\n\n(* deBruijn index v occurs nowhere in T *)\nDefinition not_free (v : id) (T : ty): Prop := [[ v ~> ∅ ]]ᵀ T = T.\n\nInductive has_type : tenv -> qual -> senv -> tm -> ty -> qual -> Prop :=\n| t_base : forall Γ Σ φ,\n    closed_qual 0 (‖Γ‖) (‖Σ‖) φ ->\n    has_type Γ φ Σ tunit TUnit ∅\n\n| t_var : forall Γ φ Σ x b T d,\n    indexr x Γ = Some (b,T,d) ->\n    $!x ⊑ φ ->\n    closed_qual 0 (‖Γ‖) (‖Σ‖) φ ->\n    closed_ty   0 x (‖Σ‖) T ->\n    closed_qual 0 x (‖Σ‖) d ->\n    has_type Γ φ Σ $x T $!x\n\n| t_abs: forall Γ φ Σ T1 d1 T2 d2 df t,\n    closed_tm   2 (‖Γ‖) (‖Σ‖) t ->\n    closed_ty   0 (‖Γ‖) (‖Σ‖) (TFun d1 d2 T1 T2) ->\n    closed_qual 0 (‖Γ‖) (‖Σ‖) φ ->\n    df ⊑ φ ->\n    ♦∉ df ->\n    senv_saturated Σ df ->\n    has_type ((false, T1, d1) :: (true, (TFun d1 d2 T1 T2), df) :: Γ)\n             (df ⊔ ($!‖Γ‖) ⊔ $!(S (‖Γ‖)) ⊔ {♦}) Σ (t <~²ᵗ Γ) (T2 <~²ᵀ Γ) (d2 <~²ᵈ Γ) ->\n    has_type Γ φ Σ (tabs t) (TFun d1 d2 T1 T2) df\n\n| t_app : forall Γ φ Σ t1 d1 t2 d2 df T1 T2,\n    has_type Γ φ Σ t1 (TFun d1 d2 T1 T2) df ->\n    has_type Γ φ Σ t2 T1 d1 ->\n    (d2 <~ᵈ ∅ ; ∅) ⊑ φ ->\n    ♦∉ d1 ->\n    senv_saturated Σ (d2 <~ᵈ ∅ ; ∅) ->\n    not_free 0 T2 ->\n    has_type Γ φ Σ (tapp t1 t2) (T2 <~ᵀ ∅ ; d1) (d2 <~ᵈ df ; d1)\n\n| t_app_fresh : forall Γ φ Σ t1 d1 d1' t2 d2 df df' T1 T2,\n    has_type Γ φ Σ t1 (TFun (df' ⋒ d1') d2 T1 T2) df ->\n    d1 ⊑ d1' ->\n    df ⊑ df' ->\n    has_type Γ φ Σ t2 T1 d1 ->\n    (♦∈ d1 -> not_free 1 T2) ->\n    not_free 0 T2 ->\n    (d2 <~ᵈ ∅ ; ∅) ⊑ φ ->\n    d1' ⊑ φ ->\n    df' ⊑ φ ->\n    saturated Γ Σ d1' ->\n    saturated Γ Σ df' ->\n    senv_saturated Σ (d2 <~ᵈ ∅ ; ∅) ->\n    has_type Γ φ Σ (tapp t1 t2) (T2 <~ᵀ ∅ ; d1) (d2 <~ᵈ df ; d1)\n\n| t_loc : forall Γ φ Σ l T q,\n    closed_qual 0 (‖Γ‖) (‖Σ‖) φ ->\n    indexr l Σ = Some (T,q) ->\n    closed_ty 0 0 0 T ->\n    closed_qual 0 0 (‖Σ‖) q ->\n    &!l ⊑ φ ->\n    q ⊑ φ ->\n    ♦∉ q ->\n    has_type Γ φ Σ &l (TRef q T) (q ⊔ &!l)\n\n| t_ref: forall Γ φ Σ T t d1,\n    has_type Γ φ Σ t T d1 ->\n    closed_ty 0 0 0 T ->\n    {♦} ⊑ φ ->\n    ♦∉ d1 ->\n    has_type Γ φ Σ (tref t) (TRef d1 T) ({♦} ⊔ d1)\n\n| t_deref: forall Γ φ Σ T d d1 t,\n    has_type Γ φ Σ t (TRef d1 T) d ->\n    ♦∉ d1 ->\n    d1 ⊑ φ ->\n    senv_saturated Σ d1 ->\n    has_type Γ φ Σ !t T d1\n\n| t_assign: forall Γ φ Σ T t1 d d1 t2,\n    has_type Γ φ Σ t1 (TRef d1 T) d ->\n    has_type Γ φ Σ t2 T d1 ->\n    ♦∉ d1 ->\n    has_type Γ φ Σ (tassign t1 t2) TUnit ∅\n\n| t_sub: forall Γ φ  Σ e T1 d1 T2 d2,\n    has_type Γ φ Σ e T1 d1 ->\n    stp Γ Σ T1 d1 T2 d2 ->\n    d2 ⊑ φ ->\n    senv_saturated Σ d2 ->\n    has_type Γ φ Σ e T2 d2\n.\n#[global] Hint Constructors has_type : core.\n\nInductive value : tm -> Prop :=\n| value_abs : forall t, value (tabs t)\n| value_cst : value tunit\n| value_loc : forall l, value &l\n.\n#[global] Hint Constructors value : core.\n\nDefinition store := list tm.\n\nInductive step : tm -> store -> tm -> store -> Prop :=\n(*contraction rules*)\n| step_beta : forall t v σ,\n    value v ->\n    step (tapp (tabs t) v) σ (t <~ᵗ (tabs t); v) σ\n| step_ref : forall v σ,\n    value v ->\n    step (tref v) σ (&‖σ‖) (v :: σ)\n| step_deref : forall σ l v,\n    indexr l σ = Some v ->\n    step (! &l) σ v σ\n| step_assign : forall σ l v,\n    l < ‖σ‖ ->\n    value v ->\n    step (tassign &l v) σ tunit (update σ l v)\n(*congruence rules*)\n| step_c_ref : forall t t' σ σ',\n    step t σ t' σ' ->\n    step (tref t) σ (tref t') σ'\n| step_c_deref : forall t t' σ σ',\n    step t σ t' σ' ->\n    step !t σ !t' σ'\n| step_c_app_l : forall t1 t1' t2 σ σ',\n    step t1 σ t1' σ' ->\n    step (tapp t1 t2) σ (tapp t1' t2) σ'\n| step_c_app_r : forall v t2 t2' σ σ',\n    value v ->\n    step t2 σ t2' σ' ->\n    step (tapp v t2) σ (tapp v t2') σ'\n| step_c_assign_l : forall t1 t1' t2 σ σ',\n    step t1 σ t1' σ' ->\n    step (tassign t1 t2) σ (tassign t1' t2) σ'\n| step_c_assign_r : forall v t2 t2' σ σ',\n    value v ->\n    step t2 σ t2' σ' ->\n    step (tassign v t2) σ (tassign v t2') σ'\n.\n\nDefinition CtxOK (Γ : tenv) (φ : qual) (Σ : senv) (σ : store) : Prop :=\n  ‖Σ‖ = ‖σ‖ /\\\n  forall l v T q, indexr l Σ = Some (T,q) -> indexr l σ = Some v -> value v /\\ has_type Γ φ Σ v T q.\n\n(* Substitutions\n\n   It is assumed that substitution is always on the first two context entries, which\n   is why other free variables are unconditionally decremented.\n*)\nFixpoint subst_tm (t : tm) (v : nat) (u : tm) : tm :=\n  match t with\n  | tunit         => tunit\n  | # x           => # x\n  | $ x           => if Nat.eqb x v then u else $(pred x)\n  | tabs t        => tabs (subst_tm t v u)\n  | tapp t1 t2    => tapp (subst_tm t1 v u) (subst_tm t2 v u)\n  | & l           => & l\n  | tref t        => tref (subst_tm t v u)\n  | ! t           => ! (subst_tm t v u)\n  | tassign t1 t2 => tassign (subst_tm t1 v u) (subst_tm t2 v u)\n  end.\n\nDefinition subst_q (q : qual) (v : nat) (q' : qual) : qual :=\n  match q with\n  | qset fresh fvs bvs ls =>\n    match mem v fvs with\n    | true  => (qset fresh (unsplice_set 0 (remove v fvs)) bvs ls) ⊔ q'\n    | false => qset fresh (unsplice_set 0 fvs) bvs ls\n    end\n  end.\n\nFixpoint subst_ty (T : ty) (v : nat) (q : qual) : ty :=\n  match T with\n  | TUnit            => TUnit\n  | TFun q1 q2 T1 T2 => TFun (subst_q q1 v q) (subst_q q2 v q) (subst_ty T1 v q) (subst_ty T2 v q)\n  | TRef q1 T        => TRef (subst_q q1 v q) (subst_ty T v q)\n  end.\n\nDefinition subst_tenv (Γ : tenv) (v : nat) (q1 : qual) : tenv :=\n  map (fun p => match p with\n             | (b,T,q') => (b, (subst_ty T v q1) , (subst_q q' v q1))\n             end) Γ.\n\nModule SubstitutionNotations.\n  Declare Scope substitutions.\n  Notation \"{ v1 |-> t1 ; t2 }ᵗ t\"  := (subst_tm (subst_tm t v1 t1) v1 t2) (at level 10) : substitutions.\n  Notation \"{ v1 |-> t1 }ᵗ t\"       := (subst_tm t v1 t1) (at level 10) : substitutions.\n  Notation \"{ v1 |-> q1 ; q2 }ᵈ q\"  := (subst_q (subst_q q v1 q1) v1 q2) (at level 10) : substitutions.\n  Notation \"{ v1 |-> q1 }ᵈ q\"       := (subst_q q v1 q1) (at level 10) : substitutions.\n  Notation \"{ v1 |-> q1 ; q2  }ᵀ T\" := (subst_ty (subst_ty T v1 q1) v1 q2) (at level 10) : substitutions.\n  Notation \"{ v1 |-> q1 }ᵀ T\"       := (subst_ty T v1 q1) (at level 10) : substitutions.\n  Notation \"{ v1 |-> q1 }ᴳ G\"       := (subst_tenv G v1 q1) (at level 10) : substitutions.\n  Notation \"{ v1 |-> q1 ; q2 }ᴳ G\"  := (subst_tenv (subst_tenv G v1 q1) v1 q2) (at level 10) : substitutions.\nEnd SubstitutionNotations.\nImport SubstitutionNotations.\nLocal Open Scope substitutions.\n\n(* Indicates the relation between an assumption's qualifier and the qualifier we substitute for the variable.\n   This helps ensure that the substitution lemma can be expressed uniformly on a single variable. *)\nInductive Substq : qual -> qual -> Prop :=\n| SExact : forall df,    ♦∉ df -> Substq df df        (* precise substitution, e.g., we substitute a recursive function into itself or the argument in t_app *)\n| SGrow  : forall df dx, ♦∉ dx -> Substq (df ⋒ dx) dx (* a growing substitution, e.g., we substitute the argument in t_app_fresh, note the difference. *)\n.\n#[global] Hint Constructors Substq : core.\n\n(* disjointq Σ Σ' q q' (in symbols: Σ → Σ' ∋ q ⊕ q') is an invariant propagated through the type safety proof.\n   Given a reduction step starting in store typing Σ and resulting in Σ', and a qualifier q, then\n   Σ → Σ' ∋ q ⊕ q' specifies that the step has increased q by q' (e.g., from allocation effects).\n   q' is either empty (no observable change to q), or q' = (q'' ⊔ &!‖Σ‖) for some q'' where q'' ⊑ q.\n   That is, q increases at most by a single fresh store location (&!‖Σ‖, the next free address), and this\n   new location stores a value that is already aliased by q. *)\nInductive disjointq (Σ Σ' : senv) : qual -> qual -> Prop :=\n| disj_bot : forall q,\n    disjointq Σ Σ' q ∅\n| disj_loc : forall T q q',\n    q ⊑ q' ->\n    closed_ty 0 0 (‖Σ‖) T ->\n    closed_qual 0 0 (‖Σ‖) q ->\n    senv_saturated Σ q ->\n    Σ' = (T,q) :: Σ ->\n    disjointq Σ Σ' q' (q ⊔ &!‖Σ‖)\n.\nArguments disj_loc { Σ Σ' }.\n#[global] Hint Constructors disjointq : core.\nNotation \" S → T ∋ q ⊕ q'\" := (disjointq S T q q') (at level 10).\n\n(* :! -- directly invertible value typing *)\n\nInductive vtp: senv -> tm -> ty -> qual -> Prop :=\n| vtp_base: forall Σ d,\n  closed_qual 0 0 (‖Σ‖) d ->\n  senv_saturated Σ d ->\n  vtp Σ tunit TUnit d\n\n| vtp_loc:  forall Σ l T U q d,\n  closed_qual 0 0 (‖Σ‖) d ->\n  closed_ty 0 0 0 T ->\n  closed_qual 0 0 (‖Σ‖) q ->\n  indexr l Σ = Some (T,q) ->\n  stp [] [] T ∅ U ∅ ->\n  stp [] [] U ∅ T ∅ ->\n  qstp [] Σ (q ⊔ &!l) d ->\n  ♦∉ q ->\n  senv_saturated Σ d ->\n  vtp Σ &l (TRef q U) d\n\n| vtp_abs: forall Σ T1 d1 T2 d2 T3 d3 T4 d4 df1 df2 t,\n  closed_tm 2 0 (‖Σ‖) t ->\n  closed_qual 0 0 (‖Σ‖) df2 ->\n  closed_ty 0 0 (‖Σ‖) (TFun d3 d4 T3 T4) -> (* supertype *)\n  closed_ty 0 0 (‖Σ‖) (TFun d1 d2 T1 T2) -> (* subtype *)\n  has_type [(false,T1,d1) ; (true, (TFun d1 d2 T1 T2), df1)]\n            (df1 ⊔ $!0 ⊔ $!1 ⊔ {♦}) Σ (t <~²ᵗ ([] : tenv)) (T2 <~²ᵀ ([] : tenv)) (d2 <~²ᵈ ([] : tenv)) ->\n  stp [] Σ T3 d3 T1 d1 ->\n  qstp [] Σ df1 df2 ->\n  stp [(false,T3, d3) ; (true, (TFun d1 d2 T1 T2), {♦})] Σ\n      (T2 <~²ᵀ ([] : tenv)) (d2 <~²ᵈ ([] : tenv))\n      (T4 <~²ᵀ ([] : tenv)) (d4 <~²ᵈ ([] : tenv)) ->\n  ♦∉ df1 ->\n  senv_saturated Σ df1 ->\n  senv_saturated Σ df2 ->\n  vtp Σ (tabs t) (TFun d3 d4 T3 T4) df2\n.\n#[global] Hint Constructors vtp : core.\n\n(* The concluding statement of the preservation part of type safety, i.e., typing is preserved after a step under an extended store, so\n   that the initial qualifier is increased by at most a fresh storage effect. *)\nInductive preserve (Γ : tenv) (Σ : senv) (t' : tm) (T : ty) (d : qual) (σ' : store) : Prop :=\n| Preserve : forall Σ' d',\n    Σ' ⊇ Σ ->\n    wf_senv Σ' ->\n    CtxOK Γ (ldom Σ') Σ' σ' ->\n    Σ → Σ' ∋ d ⊕ d'  ->\n    has_type Γ (ldom Σ') Σ' t' T (d ⋓ d') ->\n    preserve Γ Σ t' T d σ'.\nArguments Preserve {Γ Σ t' T d σ'}.\n\n(* deterministic relations (used to recover standard progress & preservation from the type safety theorem. ) *)\nDefinition relation (X : Type)(Y: Type) := X -> Y -> X ->  Y -> Prop.\nDefinition deterministic {X : Type}{Y: Type} (R : relation X Y) :=\n  forall (x x1 x2 : X) (y y1 y2: Y), R x y x1 y1 -> R x y x2 y2 -> x1 = x2 /\\ y1 = y2.\n\n(* The concluding statement of the separation of preservation corollary, i.e., interleaving the execution of two well-typed\n   terms with disjoint qualifiers preserves the types and keeps qualifiers disjoint.  *)\nInductive separate (Σ : senv) (t1' : tm) (T1 : ty) (t2' : tm) (T2 : ty) : Prop :=\n| Separate : forall Σ' Σ'' q1' q2',\n    Σ' ⊇ Σ ->\n    Σ'' ⊇ Σ' ->\n    has_type [] (ldom Σ') Σ' t1' T1 q1' ->\n    has_type [] (ldom Σ'') Σ'' t2' T2 q2' ->\n    q1' ⋒ q2' ⊑ {♦} ->\n    senv_saturated Σ'' q1' ->\n    senv_saturated Σ'' q2' ->\n    separate Σ t1' T1 t2' T2.\nArguments Separate {Σ t1' T1 t2' T2}.\n\n(** Metatheory *)\n\nLemma extends_refl : forall {A}, forall{l : list A}, l ⊇ l.\n  intros. unfold extends. exists []. auto.\nQed.\n#[global] Hint Resolve extends_refl : core.\n\nLemma extends_trans : forall {A}, forall{l1 l2 l3 : list A}, l2 ⊇ l1 -> l3 ⊇ l2 -> l3 ⊇ l1.\n  intros. unfold extends in *. destruct H. destruct H0. subst. exists (x0 ++ x). rewrite app_assoc. auto.\nQed.\n#[global] Hint Resolve extends_trans : core.\n\nLemma extends_empty : forall {A}, forall{l : list A}, l ⊇ [].\n  intros. unfold extends. exists l. apply app_nil_end.\nQed.\n#[global] Hint Resolve extends_empty : core.\n\nLemma extends_cons : forall {A}, forall{l : list A}, forall{a:A}, (a :: l) ⊇ l.\n  intros. unfold extends. exists [a]. auto.\nQed.\n#[global] Hint Resolve extends_cons : core.\n\nLemma extends_length : forall {A}, forall{l1 l2 : list A}, l1 ⊇ l2 -> length l2 <= length l1.\n  intros. unfold extends in H. destruct H as [l' Heq]. subst. rewrite app_length. lia.\nQed.\n#[global] Hint Resolve extends_length : core.\n\nLemma extends_ldom : forall {Σ' Σ : senv}, Σ' ⊇ Σ -> ldom Σ ⊑ ldom Σ'.\n  intros. inversion H. unfold ldom. simpl.\n  intuition. unfold dom.\n  assert (‖Σ'‖ = ‖x ++ Σ‖). subst. auto.\n  rewrite app_length in H1. assert (‖Σ‖ <= ‖Σ'‖). lia.\n  apply nset_subset. lia.\nQed.\n#[global] Hint Resolve extends_ldom: core.\n\nLemma open_tm'_len : forall {A} {Γ Γ' : list A} {t}, ‖Γ‖ = ‖Γ'‖ -> open_tm' Γ t = open_tm' Γ' t.\n  intros.  unfold open_tm'. rewrite H. auto.\nQed.\n\nLemma open_ty'_len : forall {A} {Γ Γ' : list A} {T}, ‖Γ‖ = ‖Γ'‖ -> open_ty' Γ T = open_ty' Γ' T.\n  intros.  unfold open_ty'. rewrite H. auto.\nQed.\n\nLemma openq'_len : forall {A} {Γ Γ' : list A} {q}, ‖Γ‖ = ‖Γ'‖ -> openq' Γ q = openq' Γ' q.\n  intros.  unfold openq'. rewrite H. auto.\nQed.\n\nLemma open_ty_preserves_size: forall T d j, ty_size T = ty_size (open_rec_ty j d T).\n  induction T; intros; simpl; eauto.\nQed.\n\nLemma splice_qual_empty : forall {k}, ∅ ↑ᵈ k = ∅.\n  intros. simpl. rewrite splice_set_empty. auto.\nQed.\n#[global] Hint Resolve splice_qual_empty : core.\n\nLemma splice_qual_fresh : forall {k}, {♦} ↑ᵈ k = {♦}.\n  intros. simpl. rewrite splice_set_empty. auto.\nQed.\n#[global] Hint Resolve splice_qual_fresh : core.\n\nLemma closed_qual_sub : forall {b f l d}, closed_qual b f l d -> forall {d'}, d' ⊑ d -> closed_qual b f l d'.\nProof.\n  intros. inversion H. subst. destruct d'.\n  inversion H0. intuition. constructor.\n  eapply subset_bound; eauto.\n  eapply subset_bound; eauto.\n  eapply subset_bound; eauto.\nQed.\n#[global] Hint Resolve closed_qual_sub : core.\n\nLemma closed_qual_empty : forall {b f l}, closed_qual b f l ∅.\n  intros. constructor; rewrite bound_empty; lia.\nQed.\n#[global] Hint Resolve closed_qual_empty : core.\n\nLemma closed_qual_fresh : forall {b f l}, closed_qual b f l {♦}.\n  intros. constructor; rewrite bound_empty; lia.\nQed.\n#[global] Hint Resolve closed_qual_fresh : core.\n\nLemma closed_qual_ldom : forall {Σ : senv}, closed_qual 0 0 (‖Σ‖) (ldom Σ).\n  intros. unfold ldom. constructor. 1,2 : rewrite bound_empty; auto.\n  rewrite bound_dom. auto.\nQed.\n#[global] Hint Resolve closed_qual_ldom : core.\n\nLemma closed_qual_cong : forall {b f l d},\n    closed_qual b f l d -> forall {d'}, d ≡ d' -> closed_qual b f l d'.\nProof.\n  intros b f l d H. induction H; intros d' Heq.\n  destruct d'. inversion Heq. intuition. constructor.\n  eapply set_eq_bound; eauto.\n  eapply set_eq_bound; eauto.\n  eapply set_eq_bound; eauto.\nQed.\n\nLemma just_fv_closed : forall {x b f l fr}, x < f <-> closed_qual b f l (${ fr } x).\nProof.\n  split; intros.\n  - constructor; unfold bound.\n    rewrite max_elt_singleton. lia.\n    rewrite max_elt_empty. lia.\n    rewrite max_elt_empty. lia.\n  - inversion H. subst.\n    unfold bound in H6. rewrite max_elt_singleton in H6. lia.\nQed.\n\nLemma just_loc_closed : forall {x b f l fr}, x < l <-> closed_qual b f l (&{ fr } x).\nProof.\n  split; intros.\n  - constructor; unfold bound.\n    rewrite max_elt_empty. lia.\n    rewrite max_elt_empty. lia.\n    rewrite max_elt_singleton. lia.\n  - inversion H. subst. unfold bound in H9.\n    rewrite max_elt_singleton in H9. lia.\nQed.\n\nLemma splice_tenv_length : forall {n Γ}, ‖ Γ ↑ᴳ n ‖ = ‖Γ‖.\n  intros. unfold splice_tenv. rewrite map_length. auto.\nQed.\n\nLemma closed_tm_monotone : forall {t b l f}, closed_tm b f l t -> forall {b' f' l'}, b <= b' -> f <= f' -> l <= l' -> closed_tm b' f' l' t.\n  intros T b f l H. induction H; intuition.\nQed.\n\nLemma closed_qual_monotone : forall {f b l d}, closed_qual b f l d -> forall {b' f' l'}, b <= b' -> f <= f' -> l <= l' -> closed_qual b' f' l' d.\n  intros. destruct d; intuition.\n  inversion H. subst. constructor; lia.\nQed.\n\nLemma closed_ty_monotone : forall {T b l f}, closed_ty b f l T -> forall {b' f' l'}, b <= b' -> f <= f' -> l <= l' -> closed_ty b' f' l' T.\n  intros T b f l H. induction H; intuition.\n  constructor; auto. eapply closed_qual_monotone; eauto.\n  constructor; auto. eapply closed_qual_monotone; eauto.\n  eapply closed_qual_monotone; eauto. lia.\n  eapply IHclosed_ty2; eauto. lia.\nQed.\n\nLemma closed_tm_open_id : forall {t b f l}, closed_tm b f l t -> forall {n}, b <= n -> forall {x}, [[n ~> x ]]ᵗ t = t.\n  intros t b f l H. induction H; intros; simpl; auto;\n    try solve [erewrite IHclosed_tm1; eauto; erewrite IHclosed_tm2; eauto; lia | erewrite IHclosed_tm; eauto; lia].\n  destruct (Nat.eqb n x) eqn:Heq; auto. apply Nat.eqb_eq in Heq. lia.\nQed.\n\nLemma closed_qual_open_id : forall {d b f l},\n    closed_qual b f l d -> forall {n}, b <= n -> forall {x}, [[n ~> x ]]ᵈ d = d.\n  intros. destruct d; simpl. replace (mem n t0) with false. auto.\n  inversion H. subst. symmetry. rewrite <- NatSetFacts.not_mem_iff.\n  apply bound_le_not_in. lia.\nQed.\n\nLemma closed_ty_open_id : forall {T b f l}, closed_ty b f l T -> forall {n}, b <= n -> forall {x}, [[n ~> x ]]ᵀ T = T.\n  intros T b f l H. induction H; intros; simpl; auto;\n    try solve [erewrite IHclosed_ty1; eauto; erewrite IHclosed_ty2; eauto; try lia;\n                  try solve [erewrite closed_qual_open_id; eauto; erewrite closed_qual_open_id; eauto; lia]\n                | erewrite IHclosed_ty; eauto; try lia; try solve [erewrite closed_qual_open_id; eauto]].\nQed.\n\nLemma closed_tm_open : forall {t b f l}, closed_tm (S b) f l t -> forall {x}, x < f -> closed_tm b f l ([[ b ~> $x ]]ᵗ t).\n  induction t; intros; simpl; intuition; inversion H; subst; try constructor;\n  try solve [apply IHt1; auto | apply IHt2; auto | apply IHt; auto ].\n  destruct (Nat.eqb b x0) eqn:Heq; intuition.\n  apply Nat.eqb_neq in Heq. constructor. lia. auto. auto.\nQed.\n\nLemma closed_qual_open : forall {d b f l fr},\n    closed_qual (S b) f l d ->\n    forall {x}, x < f -> closed_qual b f l ([[ b ~> ${fr}x ]]ᵈ d).\n  intros. destruct d. simpl. inversion H. subst.\n  destruct (mem b t0) eqn:Heq.\n  - repeat rewrite empty_union_right. constructor; auto.\n    rewrite union_bound_max'. rewrite bound_singleton. lia.\n    apply remove_bound; auto.\n  - apply remove_bound in H9. rewrite <- NatSetFacts.not_mem_iff in Heq.\n    rewrite remove_equal in H9; auto.\nQed.\n\nLemma closed_ty_open : forall {T fr b f l}, closed_ty (S b) f l T -> forall {x}, x < f -> closed_ty b f l ([[ b ~> ${fr}x ]]ᵀ T).\n  induction T; intros; simpl; intuition; inversion H; subst; try constructor;\n    try solve [apply IHT1; auto | apply IHT2; auto | apply IHT; auto ].\n  1,2,4 : eapply closed_qual_open; eauto.\n  erewrite closed_ty_open_id; eauto. lia.\nQed.\n\nLemma closed_tm_open' : forall {t b f l}, closed_tm (S b) f l t -> forall {x}, x <= f -> forall {t'}, closed_tm 0 x l t' -> closed_tm b f l ([[ b ~> t' ]]ᵗt).\n  induction t; intros; simpl; intuition; inversion H; subst; try constructor;\n  try solve [eapply IHt1; eauto | eapply IHt2; eauto | eapply IHt; eauto ].\n  destruct (Nat.eqb b x0) eqn:Heq; intuition. eapply closed_tm_monotone; eauto; lia.\n  apply Nat.eqb_neq in Heq. constructor. lia. auto. auto.\nQed.\n\nLemma closed_qual_open' : forall {d b f l},\n    closed_qual (S b) f l d ->\n    forall {x}, x <= f ->\n    forall {d'}, closed_qual 0 x l d' -> closed_qual b f l ([[ b ~> d' ]]ᵈ d).\nProof.\n  destruct d; intros; simpl; intuition. inversion H. subst.\n  destruct d'.\n  inversion H1. subst.\n  destruct (mem b0 t0) eqn:Hmem.\n  - constructor.\n    * specialize (@union_bound_max t t2) as Hbound. lia.\n    * unfold bound in H10.\n      destruct (max_elt t0) eqn:Hmax.\n      assert (e <= b0) by lia.\n      specialize (@union_bound_max (remove b0 t0) t3) as Hbound.\n      specialize (@remove_max_bound' _ _ _ Hmax Hmem H2) as Hr. lia.\n      specialize (@max_elt_none_mem _ _ Hmax Hmem) as bot. inversion bot.\n    * specialize (@union_bound_max t1 t4) as Hbound. lia.\n  - constructor; auto. unfold bound in H10. unfold bound.\n    destruct (max_elt t0) eqn:Hmax.\n    inversion H10. subst.\n    specialize (@NatSet.F.max_elt_1 _ _ Hmax) as HIn.\n    rewrite <- NatSetProperties.FM.not_mem_iff in Hmem.\n    contradiction. subst. lia. lia.\nQed.\n\nLemma closed_ty_open' : forall {T b f l}, closed_ty (S b) f l T -> forall {x}, x <= f -> forall {d}, closed_qual 0 x l d -> closed_ty b f l ([[ b ~> d ]]ᵀ T).\n  induction T; intros; simpl; intuition; inversion H; subst; try constructor;\n    try solve [eapply IHT1; eauto | eapply IHT2; eauto | eapply IHT; eauto ].\n  1,2,4 : eapply closed_qual_open'; eauto.\n  erewrite closed_ty_open_id; eauto. lia.\nQed.\n\nLemma closed_tm_open_ge : forall {t b f l}, closed_tm (S b) f l t -> forall {x}, f <= x -> closed_tm b (S x) l ([[ b ~> $x ]]ᵗ t).\n  induction t; intros; simpl; intuition; inversion H; subst; try constructor;\n      try solve [eapply IHt1; eauto | eapply IHt2; eauto | eapply IHt; eauto ].\n  destruct (Nat.eqb b x0) eqn:Heq. intuition.\n  apply Nat.eqb_neq in Heq. inversion H. subst.\n  constructor. lia. lia. auto.\nQed.\n\nLemma closed_qual_open_ge : forall {d fr b f l},\n    closed_qual (S b) f l d ->\n    forall {x}, f <= x -> closed_qual b (S x) l ([[ b ~> ${fr}x ]]ᵈ d).\nProof.\n  destruct d; intros; simpl; intuition. inversion H. subst.\n  destruct (mem b0 t0) eqn: Hmem.\n  - constructor.\n    * eapply bound_increase; eauto.\n    * specialize (@NatSetProperties.empty_union_2 {}N (remove b0 t0) NatSet.F.empty_1) as HU.\n      apply NatSet.eq_if_Equal in HU. rewrite HU. clear HU.\n      unfold bound. unfold bound in H9.\n      destruct (max_elt t0) eqn:Hmax1; inversion H9. subst.\n      destruct (max_elt (remove b0 t0)) eqn:Hmax2.\n      eapply remove_max_bound; eauto. lia.\n      subst. destruct (max_elt (remove b0 t0)) eqn:Hmax2.\n      assert (e < b0) by lia. eapply remove_nonexist_bound; eauto. lia.\n      subst. specialize (@max_elt_none_mem _ _ Hmax1 Hmem) as bot. inversion bot.\n    * specialize (@NatSetProperties.empty_union_2 {}N t1 NatSet.F.empty_1) as HU.\n      apply NatSet.eq_if_Equal in HU. rewrite HU. auto.\n  - constructor; try lia.\n    unfold bound in H9. unfold bound. destruct (max_elt t0) eqn:Hmax.\n    inversion H9; subst. specialize (@NatSet.F.max_elt_1 _ _ Hmax) as HIn.\n    rewrite <- NatSetProperties.FM.not_mem_iff in Hmem. contradiction. lia. lia.\nQed.\n\nLemma closed_ty_open_ge : forall {T fr b f l}, closed_ty (S b) f l T -> forall {x}, f <= x -> closed_ty b (S x) l ([[ b ~> ${fr}x ]]ᵀ T).\n  induction T; intros; simpl; intuition; inversion H; subst; try constructor;\n    try solve [eapply IHT1; eauto | eapply IHT2; eauto | eapply IHT; eauto ].\n  1,2,4 :eapply closed_qual_open_ge; eauto.\n  erewrite closed_ty_open_id; eauto. lia.\nQed.\n\nLemma closed_open_succ : forall {t b f l}, closed_tm b f l t -> forall {j}, closed_tm b (S f) l ([[ j ~> $f ]]ᵗ t).\n  induction t; intros; simpl; intuition; inversion H; subst; try constructor;\n    try solve [eapply IHt1; eauto | eapply IHt2; eauto | eapply IHt; eauto ].\n    destruct (Nat.eqb j x) eqn:Heq. intuition.\n    apply Nat.eqb_neq in Heq. inversion H. subst. intuition. lia. auto.\nQed.\n\nLemma closed_qual_open_succ : forall {d b fr f l},\n    closed_qual b f l d ->\n    forall {j}, closed_qual b (S f) l ([[j ~> ${fr}f ]]ᵈ d).\nProof.\n  destruct d; intros; simpl; intuition. inversion H. subst.\n  destruct (mem j t0) eqn:Hmem.\n  - constructor. specialize (@union_bound_max t (singleton f)) as Hmax.\n    rewrite bound_singleton in Hmax. lia. rewrite empty_union_right.\n    apply remove_preserves_bound; auto. rewrite empty_union_right. lia.\n  - constructor; auto.\nQed.\n\nLemma closed_ty_open_succ : forall {T fr b f l}, closed_ty b f l T -> forall {j}, closed_ty b (S f) l ([[ j ~> ${fr}f ]]ᵀ T).\n  induction T; intros; simpl; intuition; inversion H; subst; try constructor;\n    try solve [eapply IHT1; eauto | eapply IHT2; eauto | eapply IHT; eauto ].\n  1,2,4 :eapply closed_qual_open_succ; eauto.\n  erewrite closed_ty_open_id; eauto. lia.\nQed.\n\nLemma closed_tm_open_succ : forall {t b f l}, closed_tm b f l t -> forall {j}, closed_tm b (S f) l ([[ j ~> $f ]]ᵗ t).\n  induction t; intros; simpl; intuition; inversion H; subst; try constructor;\n    try solve [eapply IHt1; eauto | eapply IHt2; eauto | eapply IHt; eauto ].\n  bdestruct (j =? x); intuition. lia. auto.\nQed.\n\nLemma open_rec_tm_commute : forall t i j x y, i <> j ->\n  [[i ~> $ x ]]ᵗ ([[j ~> $ y ]]ᵗ t) = [[j ~> $ y ]]ᵗ ([[i ~> $ x ]]ᵗ t).\n  induction t; intros; simpl; eauto;\n    try solve [rewrite IHt1; eauto; rewrite IHt2; eauto | rewrite IHt; eauto].\n  destruct v. intuition.\n  destruct (Nat.eqb i i0) eqn:Hii0; destruct (Nat.eqb j i0) eqn:Hji0; simpl;\n    try rewrite Hii0; try rewrite Hji0; auto.\n  apply Nat.eqb_eq in Hii0. apply Nat.eqb_eq in Hji0. subst. contradiction.\nQed.\n\nLemma open_qual_commute : forall d frx fry i j x y, i <> j ->\n    [[i ~> ${frx} x ]]ᵈ ([[j ~> ${fry} y ]]ᵈ d)\n  = [[j ~> ${fry} y ]]ᵈ ([[i ~> ${frx} x ]]ᵈ d).\n  destruct d; intros; simpl; intuition.\n  destruct (mem j t0) eqn:Heqj; destruct (mem i t0) eqn:Heqi; simpl; repeat rewrite empty_union_right;\n    try replace (mem i (remove j t0)) with (mem i t0); try replace (mem j (remove i t0)) with (mem j t0);\n      try rewrite Heqj; try rewrite Heqi; auto.\n  f_equal; try fnsetdec. destr_bool.\n  all : symmetry.\n  all : repeat match goal with\n        | [ H : mem _ _ = true  |- _ ] => apply NatSet.F.mem_2 in H\n        | [ |-  mem _ _ = true ]       => apply NatSet.F.mem_1\n        | [ H : mem _ _ = false |- _ ] => rewrite <- NatSetProperties.FM.not_mem_iff in H\n        | [ |-  mem _ _ = false ]      => rewrite <- NatSetProperties.FM.not_mem_iff\n        end.\n  all : fnsetdec.\nQed.\n\nLemma open_rec_ty_commute : forall T frx fry i j x y, i <> j ->\n    [[i ~> ${frx} x ]]ᵀ ([[j ~> ${fry} y ]]ᵀ T)\n  = [[j ~> ${fry} y ]]ᵀ ([[i ~> ${frx} x ]]ᵀ T).\n  induction T; intros; simpl; eauto.\n  erewrite open_qual_commute; eauto.\n  erewrite open_qual_commute with (i:=(S (S i))); eauto.\n  erewrite IHT1; eauto; erewrite IHT2; eauto.\n  erewrite IHT; eauto. erewrite open_qual_commute; eauto.\nQed.\n\nLemma open_rec_tm_commute' : forall t i j x t' f l, i <> j -> closed_tm 0 f l t' ->\n  [[i ~> $ x ]]ᵗ ([[j ~> t' ]]ᵗ t) = [[j ~> t' ]]ᵗ ([[i ~> $ x ]]ᵗ t).\n  induction t; intros; simpl; eauto;\n    try solve [erewrite IHt1; eauto; erewrite IHt2; eauto | erewrite IHt; eauto].\n  - destruct v. intuition.\n    destruct (Nat.eqb i i0) eqn:Hii0; destruct (Nat.eqb j i0) eqn:Hji0; simpl;\n      try rewrite Hii0; try rewrite Hji0; auto.\n    apply Nat.eqb_eq in Hii0. apply Nat.eqb_eq in Hji0. subst. contradiction.\n    eapply closed_tm_open_id; eauto. lia.\nQed.\n\nLemma open_qual_commute' : forall d i j fr x d' f l, i <> j -> closed_qual 0 f l d' ->\n    [[ i ~> ${fr}x ]]ᵈ ([[ j ~> d' ]]ᵈ d)\n  = [[ j ~> d' ]]ᵈ ([[ i ~> ${fr}x ]]ᵈ d).\n  destruct d; destruct d'; intros; simpl; intuition.\n  inversion H0. subst. apply bound_0_empty in H9. subst.\n  destruct (mem j t0) eqn:Heqj; destruct (mem i t0) eqn:Heqi; simpl; repeat rewrite empty_union_right;\n    try replace (mem i (remove j t0)) with (mem i t0); try replace (mem j (remove i t0)) with (mem j t0);\n      try rewrite Heqj; try rewrite Heqi; auto.\n  f_equal; try fnsetdec. destr_bool.\n  all : symmetry.\n  all : repeat match goal with\n        | [ H : mem _ _ = true  |- _ ] => apply NatSet.F.mem_2 in H\n        | [ |-  mem _ _ = true ]       => apply NatSet.F.mem_1\n        | [ H : mem _ _ = false |- _ ] => rewrite <- NatSetProperties.FM.not_mem_iff in H\n        | [ |-  mem _ _ = false ]      => rewrite <- NatSetProperties.FM.not_mem_iff\n        end.\n  all : fnsetdec.\nQed.\n\nLemma open_rec_ty_commute' : forall T i j fr x d f l, i <> j -> closed_qual 0 f l d ->\n    [[ i ~> ${fr}x ]]ᵀ ([[ j ~> d ]]ᵀ T)\n  = [[ j ~> d ]]ᵀ ([[ i ~> ${fr}x ]]ᵀ T).\n  induction T; intros; simpl; eauto.\n  erewrite open_qual_commute'; eauto. erewrite open_qual_commute'; eauto.\n  erewrite IHT1; eauto; erewrite IHT2; eauto.\n  erewrite open_qual_commute'; eauto. erewrite IHT; eauto.\nQed.\n\nLemma open_rec_tm_commute'' : forall t i j t' t'' f l, i <> j -> closed_tm 0 f l t' -> closed_tm 0 f l t'' ->\n    [[ i ~> t'']]ᵗ ([[ j ~> t' ]]ᵗ t)\n  = [[ j ~> t' ]]ᵗ ([[ i ~> t'' ]]ᵗ t).\n  induction t; intros; simpl; eauto;\n    try solve [erewrite IHt1; eauto; erewrite IHt2; eauto | erewrite IHt; eauto].\n  - destruct v. intuition.\n    destruct (Nat.eqb i i0) eqn:Hii0; destruct (Nat.eqb j i0) eqn:Hji0; simpl;\n      try rewrite Hii0; try rewrite Hji0; auto.\n    apply Nat.eqb_eq in Hii0. apply Nat.eqb_eq in Hji0. subst. contradiction.\n    symmetry. eapply closed_tm_open_id; eauto. lia. eapply closed_tm_open_id; eauto. lia.\nQed.\n\nLemma open_qual_commute'' : forall d i j d' d'' f l, i <> j -> closed_qual 0 f l d' -> closed_qual 0 f l d'' ->\n    [[ i ~> d'']]ᵈ ([[ j ~> d' ]]ᵈ d)\n  = [[ j ~> d' ]]ᵈ ([[ i ~> d'' ]]ᵈ d).\n  destruct d; destruct d'; destruct d''; intros; simpl; intuition.\n  inversion H0. subst. inversion H1. subst. apply bound_0_empty in H10, H13. subst.\n  repeat rewrite empty_union_right in *.\n  destruct (mem j t0) eqn:Heqj; destruct (mem i t0) eqn:Heqi; simpl; repeat rewrite empty_union_right;\n    try replace (mem i (remove j t0)) with (mem i t0); try replace (mem j (remove i t0)) with (mem j t0);\n      try rewrite Heqj; try rewrite Heqi; auto.\n  f_equal; try fnsetdec. destr_bool.\n  all : symmetry.\n  all : repeat match goal with\n        | [ H : mem _ _ = true  |- _ ] => apply NatSet.F.mem_2 in H\n        | [ |-  mem _ _ = true ]       => apply NatSet.F.mem_1\n        | [ H : mem _ _ = false |- _ ] => rewrite <- NatSetProperties.FM.not_mem_iff in H\n        | [ |-  mem _ _ = false ]      => rewrite <- NatSetProperties.FM.not_mem_iff\n        end.\n  all : fnsetdec.\nQed.\n\nLemma open_rec_ty_commute'' : forall T i j d' d'' f l, i <> j -> closed_qual 0 f l d' -> closed_qual 0 f l d'' ->\n    [[ i ~> d'']]ᵀ ([[ j ~> d' ]]ᵀ T)\n  = [[ j ~> d' ]]ᵀ ([[ i ~> d'' ]]ᵀ T).\n  induction T; intros; simpl; eauto.\n  erewrite open_qual_commute''; eauto.\n  erewrite open_qual_commute'' with (i:=S (S i)); eauto.\n  erewrite IHT1; eauto; erewrite IHT2; eauto.\n  erewrite open_qual_commute''; eauto. erewrite IHT; eauto.\nQed.\n\nLemma open_qual_empty_id : forall k q fr, [[ k ~> q]]ᵈ ∅{ fr } = ∅{ fr }.\n  intros. destruct q. compute. rewrite NatSetFacts.empty_b. auto.\nQed.\n\nLemma closed_tm_open'_id : forall {t f l}, closed_tm 0 f l t -> forall {A} {G : list A}, t <~²ᵗ G = t.\n  intros. unfold open_tm'. unfold open_tm. repeat erewrite closed_tm_open_id; eauto.\nQed.\n\nLemma closed_ty_open'_id : forall {T f l}, closed_ty 0 f l T -> forall {A} {G : list A}, T <~²ᵀ G = T.\n  intros. unfold open_ty'. unfold open_ty. repeat erewrite closed_ty_open_id; eauto.\nQed.\n\nLemma closed_qual_open'_id : forall {q f l}, closed_qual 0 f l q -> forall {A} {G : list A}, q <~²ᵈ G = q.\n  intros. unfold openq'. unfold openq. repeat erewrite closed_qual_open_id; eauto.\nQed.\n\nLemma open_tm'_bv0 : forall A (G : list A), #0 <~²ᵗ G = $‖G‖.\n  intros. compute. auto.\nQed.\n\nLemma open_tm'_bv1 : forall A (G : list A), #1 <~²ᵗ G = $(S (‖G‖)).\n  intros. compute. auto.\nQed.\n\nLemma openq'_bv0 : forall A (G : list A) fr X Y, (qset fr X (singleton 0) Y) <~²ᵈ G = (qset fr X {}N Y ⊔ $!‖G‖).\n  intros. compute. rewrite mem_singleton. compute. rewrite remove_singleton_empty.\n  repeat rewrite empty_union_left. rewrite NatSetFacts.empty_b. auto.\nQed.\n\nLemma openq'_bv1 : forall A (G : list A) fr X Y, (qset fr X (singleton 1) Y) <~²ᵈ G = (qset fr X {}N Y ⊔ $!(S (‖G‖))).\n  intros. compute. rewrite mem_singleton. compute. rewrite mem_singleton. compute.\n  rewrite remove_singleton_empty. repeat rewrite empty_union_left. auto.\nQed.\n\nLemma open_qual_just_fv : forall i d fr x, [[ i ~> d ]]ᵈ ${fr}x = ${fr}x.\n  intros. compute. destruct d. rewrite NatSetFacts.empty_b. auto.\nQed.\n\nLemma open_qual_just_loc : forall i d fr x, [[i ~> d ]]ᵈ &{fr}x = &{fr}x.\n  intros. compute. destruct d. rewrite NatSetFacts.empty_b. auto.\nQed.\n\nLemma open_rec_tm_bv : forall i t, [[ i ~> t ]]ᵗ #i = t.\n  intros. simpl. rewrite Nat.eqb_refl. auto.\nQed.\n\nLemma open_rec_tm_bv_skip : forall j i t, j <> i -> [[ j ~> t ]]ᵗ #i = #i.\n  intros. simpl. rewrite <- Nat.eqb_neq in H. rewrite H. auto.\nQed.\n\nLemma splice_id : forall {T b f l}, closed_tm b f l T -> T ↑ᵗ f = T.\n  induction T; intros; inversion H; subst; simpl; auto;\n    try solve [erewrite IHT1; eauto; erewrite IHT2; eauto | erewrite IHT; eauto].\n    destruct (le_lt_dec f x) eqn:Heq. lia. auto.\nQed.\n\nLemma splice_qual_id : forall {d b f l}, closed_qual b f l d -> d ↑ᵈ f = d.\n  destruct d; intros; intuition.\n  inversion H. subst. simpl.\n  f_equal. unfold splice_set. unfold inc.\n  unfold bound in H6.\n  destruct (max_elt t) eqn:Hmax.\n  - assert (e < f) by lia. autounfold. erewrite filter_lt. erewrite filter_gt.\n    rewrite NatSetProperties.fold_empty. fnsetdec. all: eauto.\n  - apply max_elt_empty' in Hmax. rewrite Hmax.\n    rewrite filter_empty. rewrite filter_empty.\n    rewrite NatSetProperties.fold_empty. fnsetdec.\nQed.\n\nLemma splice_ty_id : forall {T b f l}, closed_ty b f l T -> T ↑ᵀ f = T.\n  induction T; intros; inversion H; subst; simpl; auto.\n  repeat erewrite splice_qual_id; eauto.\n  erewrite IHT1; eauto. erewrite IHT2; eauto.\n  erewrite splice_qual_id; eauto.\n  erewrite IHT; eauto. eapply closed_ty_monotone; eauto. lia.\nQed.\n\nLemma splice_open : forall {T j n m}, ([[ j ~> $(m + n) ]]ᵗ T) ↑ᵗ n = [[ j ~> $(S (m + n)) ]]ᵗ (T ↑ᵗ n).\n  induction T; intros; simpl; auto;\n    try solve [erewrite IHT1; eauto; erewrite IHT2; eauto | erewrite IHT; eauto].\n  destruct v; simpl. destruct (le_lt_dec n i) eqn:Heq; auto.\n  destruct (PeanoNat.Nat.eqb j i) eqn:Heq; auto.\n  simpl. destruct (le_lt_dec n (m + n)) eqn:Heq'. auto. lia.\nQed.\n\nLemma splice_qual_open : forall {d j fr n m}, ([[j ~> ${fr}(m + n) ]]ᵈ d) ↑ᵈ n = [[j ~> ${fr}(S (m + n)) ]]ᵈ (d ↑ᵈ n).\n  destruct d; simpl; intuition. destruct (mem j t0) eqn:Hmem; simpl; f_equal.\n  rewrite splice_set_union_dist. f_equal. rewrite splice_set_singleton_inc; auto. lia.\nQed.\n\nLemma splice_ty_open : forall {T j fr n m}, ([[j ~> ${fr}(m + n) ]]ᵀ T) ↑ᵀ n = [[j ~> ${fr}(S (m + n)) ]]ᵀ (T ↑ᵀ n).\n  induction T; intros; simpl; auto.\n  rewrite splice_qual_open. rewrite splice_qual_open. rewrite IHT1. rewrite IHT2. auto.\n  rewrite splice_qual_open. rewrite IHT. auto.\nQed.\n\nLemma splice_open' : forall {T} {A} {D : A} {ρ ρ'}, ((T <~²ᵗ (ρ ++ ρ')) ↑ᵗ ‖ρ'‖) = (T ↑ᵗ ‖ρ'‖) <~²ᵗ (ρ ++ D :: ρ').\n  intros. unfold open_tm'.\n  replace (‖ ρ ++ ρ' ‖) with (‖ρ‖ + ‖ρ'‖).\n  replace (S (‖ ρ ++ D :: ρ' ‖)) with (S (S (‖ρ‖) + (‖ρ'‖))).\n  replace (‖ ρ ++ D :: ρ' ‖) with (S (‖ρ‖ + ‖ρ'‖)).\n  repeat rewrite <- splice_open. auto.\n  all: rewrite app_length; simpl; lia.\nQed.\n\nLemma splice_qual_open' : forall {d} {A} {D : A} {ρ ρ'}, ((d <~²ᵈ (ρ ++ ρ')) ↑ᵈ ‖ρ'‖) = (d ↑ᵈ ‖ρ'‖) <~²ᵈ (ρ ++ D :: ρ').\n  intros. unfold openq'. unfold openq.\n  replace (‖ ρ ++ ρ' ‖) with (‖ρ‖ + ‖ρ'‖).\n  replace (S (‖ ρ ++ D :: ρ' ‖)) with (S (S (‖ρ‖) + (‖ρ'‖))).\n  replace (‖ ρ ++ D :: ρ' ‖) with (S (‖ρ‖ + ‖ρ'‖)).\n  repeat rewrite <- splice_qual_open. auto.\n  all: rewrite app_length; simpl; lia.\nQed.\n\nLemma splice_ty_open' : forall {T} {A} {D : A} {ρ ρ'}, ((T <~²ᵀ (ρ ++ ρ')) ↑ᵀ ‖ρ'‖) = (T ↑ᵀ ‖ρ'‖) <~²ᵀ (ρ ++ D :: ρ').\n  intros. unfold open_ty'. unfold open_ty.\n  replace (‖ ρ ++ ρ' ‖) with (‖ρ‖ + ‖ρ'‖).\n  replace (S (‖ ρ ++ D :: ρ' ‖)) with (S (S (‖ρ‖) + (‖ρ'‖))).\n  replace (‖ ρ ++ D :: ρ' ‖) with (S (‖ρ‖ + ‖ρ'‖)).\n  repeat rewrite <- splice_ty_open. auto.\n  all: rewrite app_length; simpl; lia.\nQed.\n\nLemma splice_closed : forall {T b n m l}, closed_tm b (n + m) l T -> closed_tm b (S (n + m)) l (T ↑ᵗ m).\n  induction T; simpl; intros; inversion H; subst; intuition.\n  destruct (le_lt_dec m x) eqn:Heq; intuition.\nQed.\n\nLemma splice_qual_closed : forall {d b n m l}, closed_qual b (n + m) l d -> forall {i}, i <= m -> closed_qual b (S (n + m)) l (d ↑ᵈ i).\n  destruct d; simpl; intuition.\n  inversion H. subst. constructor; auto. destruct (max_elt t) eqn:Hmax.\n  - bdestruct (e <? i).\n    + erewrite <- splice_set_preserves_bound; eauto.\n    + erewrite <- splice_set_inc_bound; eauto. lia.\n  - apply max_elt_empty' in Hmax. subst. rewrite splice_set_empty. lia.\nQed.\n\nLemma splice_ty_closed : forall {T b n m l}, closed_ty b (n + m) l T -> forall {i}, i <= m -> closed_ty b (S (n + m)) l (T ↑ᵀ i).\n  induction T; simpl; intros; inversion H; subst; intuition.\n  constructor. 1,2 : apply splice_qual_closed; auto. all: intuition.\n  constructor. erewrite splice_ty_id; eauto. eapply closed_ty_monotone; eauto. lia.\n  apply splice_qual_closed; auto.\nQed.\n\nLemma splice_closed' : forall {T b l} {A} {D : A} {ρ ρ'}, closed_tm b (‖ρ ++ ρ'‖) l T -> closed_tm b (‖ρ ++ D :: ρ'‖) l (T ↑ᵗ ‖ρ'‖).\n  intros. rewrite app_length in H.\n  replace (‖ ρ ++ D :: ρ' ‖) with (S (‖ρ‖ + ‖ρ'‖)).\n  apply splice_closed. auto. simpl. rewrite app_length. simpl. lia.\nQed.\n\nLemma splice_qual_closed' : forall {d b l} {A} {D : A} {ρ ρ'}, closed_qual b (‖ρ ++ ρ'‖) l d -> closed_qual b (‖ρ ++ D :: ρ'‖) l (d ↑ᵈ ‖ρ'‖).\n  intros. rewrite app_length in H.\n  replace (‖ ρ ++ D :: ρ' ‖) with (S (‖ρ‖ + ‖ρ'‖)).\n  eapply splice_qual_closed; eauto. simpl. rewrite app_length. simpl. lia.\nQed.\n\nLemma splice_ty_closed' : forall {T b l} {A} {D : A} {ρ ρ'}, closed_ty b (‖ρ ++ ρ'‖) l T -> closed_ty b (‖ρ ++ D :: ρ'‖) l (T ↑ᵀ ‖ρ'‖).\n  intros. rewrite app_length in H.\n  replace (‖ ρ ++ D :: ρ' ‖) with (S (‖ρ‖ + ‖ρ'‖)).\n  eapply splice_ty_closed; eauto. simpl. rewrite app_length. simpl. lia.\nQed.\n\nLemma splice_qual_closed'' : forall {q x b l k}, closed_qual b x l q -> k <= x -> closed_qual b (S x) l (q ↑ᵈ k).\n  destruct q; simpl; intuition.\n  inversion H. subst. constructor; auto. destruct (max_elt t) eqn:Hmax.\n  - bdestruct (e <? k).\n    + erewrite <- splice_set_preserves_bound; eauto.\n    + erewrite <- splice_set_inc_bound; eauto. lia.\n  - apply max_elt_empty' in Hmax. subst. rewrite splice_set_empty. lia.\nQed.\n\nLemma splice_ty_closed'' : forall {T x b l k}, closed_ty b x l T -> k <= x -> closed_ty b (S x) l (T ↑ᵀ k).\n  induction T; simpl; intros; inversion H; subst; constructor; intuition.\n  1,2,4 : eapply splice_qual_closed''; eauto. erewrite splice_ty_id; eauto.\n  eapply closed_ty_monotone; eauto. lia.\nQed.\n\nLemma splice_open_succ : forall {T b n l j}, closed_tm b n l T -> ([[ j ~> $n ]]ᵗ T) ↑ᵗ n = [[ j ~> $ (S n) ]]ᵗ T.\n  induction T; simpl; intros; inversion H; subst; auto;\n    try solve [erewrite IHT1; eauto; erewrite IHT2; eauto | erewrite IHT; eauto].\n  destruct (PeanoNat.Nat.eqb j x) eqn:Heq; auto. simpl.\n  destruct (le_lt_dec n n) eqn:Heq'; auto. lia.\n  simpl. destruct (le_lt_dec n x) eqn:Heq; auto. lia.\nQed.\n\nLemma splice_qual_open_succ : forall {d b fr n l j}, closed_qual b n l d ->\n  ([[j ~> ${fr}n ]]ᵈ d) ↑ᵈ n = [[j ~> ${fr}(S n) ]]ᵈ d.\n  destruct d; simpl; intuition. destruct (mem j t0) eqn:Hmem; simpl; f_equal.\n  rewrite splice_set_union_dist. f_equal. 2: rewrite splice_set_singleton_inc; auto.\n  all: destruct (max_elt t) eqn:Hmax.\n  1,3: erewrite splice_set_id; eauto; inversion H; subst; unfold bound in H6; rewrite Hmax in H6; lia.\n  all : apply max_elt_empty' in Hmax; subst; auto.\nQed.\n\nLemma splice_ty_open_succ : forall {T b fr n l j}, closed_ty b n l T -> ([[ j ~> ${fr} n ]]ᵀ T) ↑ᵀ n = [[ j ~> ${fr} (S n) ]]ᵀ T.\n  induction T; simpl; intros; inversion H; subst; auto.\n  erewrite splice_qual_open_succ; eauto. erewrite splice_qual_open_succ; eauto.\n  erewrite IHT1; eauto. erewrite IHT2; eauto.\n  erewrite splice_qual_open_succ; eauto.\n  erewrite closed_ty_open_id; eauto. erewrite closed_ty_open_id; eauto.\n  erewrite splice_ty_id; eauto. eapply closed_ty_monotone; eauto. all : lia.\nQed.\n\nLemma splice_qual_open_qual : forall {k n df d2}, ([[n ~> df ]]ᵈ d2) ↑ᵈ k = ([[n ~> df ↑ᵈ k ]]ᵈ (d2 ↑ᵈ k)).\n  intros. destruct d2; destruct df; simpl.\n  destruct (mem n t0) eqn: H1; simpl; auto. f_equal. rewrite splice_set_union_dist. auto.\nQed.\n\nLemma splice_qual_open'' : forall {k df d1 d2}, (d2 <~ᵈ df; d1) ↑ᵈ k = (d2 ↑ᵈ k) <~ᵈ (df ↑ᵈ k); (d1 ↑ᵈ k).\n  intros. unfold openq. repeat rewrite splice_qual_open_qual. auto.\nQed.\n\nLemma splice_ty_open_rec_ty : forall {T n k df}, ([[n ~> df ]]ᵀ T) ↑ᵀ k = ([[n ~> df ↑ᵈ k ]]ᵀ (T ↑ᵀ k)).\n  induction T; intros; auto.\n  - simpl. repeat rewrite splice_qual_open_qual. erewrite IHT1. erewrite IHT2. auto.\n  - simpl. repeat rewrite splice_qual_open_qual. erewrite IHT. auto.\nQed.\n\nLemma splice_ty_open'' : forall {T k df d1}, (T <~ᵀ df; d1) ↑ᵀ k = (T ↑ᵀ k) <~ᵀ (df ↑ᵈ k); (d1 ↑ᵈ k).\n  intros. unfold open_ty. repeat rewrite splice_ty_open_rec_ty. auto.\nQed.\n\nLemma splice_qual_qlub_dist : forall {k q1 q2}, (q1 ⊔ q2) ↑ᵈ k = ((q1 ↑ᵈ k) ⊔ (q2 ↑ᵈ k)).\n  intros. destruct q1. destruct q2. simpl. f_equal.\n  rewrite splice_set_union_dist. auto.\nQed.\n\nLemma subqual_splice_lr' : forall {i du df}, du ↑ᵈ i ⊑ df ↑ᵈ i <-> du ⊑ df.\n  intros. intuition.\n  - destruct du. destruct df.\n    unfold splice_qual in *. inversion H.\n    intuition. constructor; intuition.\n    eapply splice_set_subset_dist. eauto.\n  - destruct du. destruct df.\n    inversion H. intuition.\n    constructor; intuition.\n    eapply splice_set_subset_dist. auto.\nQed.\n#[global] Hint Resolve subqual_splice_lr' : core.\n\nLemma subqualb_splice_lr' : forall {i du df}, (du ↑ᵈ i ⊑? df ↑ᵈ i) = (du ⊑? df).\n  intros. specialize (@subqual_splice_lr' i du df) as SQS.\n  destruct (du ⊑? df) eqn:Heq.\n  rewrite subqualb_true_iff in Heq. rewrite subqualb_true_iff. intuition.\n  rewrite subqualb_false_iff in Heq. rewrite subqualb_false_iff. intuition.\nQed.\n\nLemma subqual_splice_r : forall {d1 d2 i f l}, i >= f -> closed_qual 0 f l d1 -> d1 ⊑ d2 <-> d1 ⊑ d2 ↑ᵈ i.\n  intros. split; intros.\n  - unfold splice_qual. inversion H0. subst. destruct d2.\n    unfold subqual in *. intros; intuition.\n    eapply splice_set_preserves_superset_1; eauto.\n  - unfold subqual in *. destruct d1. destruct d2.\n    unfold splice_qual in *. intuition; try fnsetdec.\n    inversion H0. subst.\n    eapply splice_set_preserves_superset_2. apply H. all: auto.\nQed.\n\nLemma subqualb_splice_r :  forall {d1 d2 i f l}, i >= f -> closed_qual 0 f l d1 -> (d1 ⊑? d2) = (d1 ⊑? d2 ↑ᵈ i).\n  intros. specialize (@subqual_splice_r d1 d2 i f l H H0) as SQS.\n  destruct (d1 ⊑? splice_qual i d2) eqn:Heq.\n  rewrite subqualb_true_iff in Heq. rewrite subqualb_true_iff. intuition.\n  rewrite subqualb_false_iff in Heq. rewrite subqualb_false_iff. intuition.\nQed.\n\nLemma closed_qual_qlub: forall {b f l d1 d2}, closed_qual b f l d1 -> closed_qual b f l d2 -> closed_qual b f l (d1 ⊔ d2).\n  intros. inversion H; subst; inversion H0; subst; intuition.\n  simpl. constructor.\n  specialize (@union_bound_max vs vs0). lia.\n  specialize (@union_bound_max bs bs0). lia.\n  specialize (@union_bound_max ls ls0). lia.\nQed.\n\nLemma closed_qual_qlub_inv: forall {b f l d1 d2}, closed_qual b f l (d1 ⊔ d2) -> closed_qual b f l d1 /\\ closed_qual b f l d2.\n  intros. destruct d1. destruct d2. inversion H; subst.\n  rewrite union_bound_max' in H6. rewrite union_bound_max' in H8. rewrite union_bound_max' in H9. intuition.\nQed.\n\nLemma closed_qual_qqplus: forall {b f l d1 d2}, closed_qual b f l d1 -> closed_qual b f l d2 -> closed_qual b f l (d1 ⋓ d2).\n  intros. destruct d1. destruct b0; unfold qqplus. rewrite qfresh_true. apply closed_qual_qlub; auto.\n  rewrite qfresh_false. auto.\nQed.\n\nLemma closed_qual_qglb : forall {q1 q2 b f l},\n    closed_qual b f l q1 -> closed_qual b f l q2 -> closed_qual b f l (q1 ⊓ q2).\n  intros. inversion H; subst; inversion H0; subst; simpl; intuition.\n  constructor.\n  specialize (@inter_bound_min vs vs0) as Hb. lia.\n  specialize (@inter_bound_min bs bs0) as Hb. lia.\n  specialize (@inter_bound_min ls ls0) as Hb. lia.\nQed.\n\nLemma closed_qual_open2 : forall {f l d1 d2 d}, closed_qual 2 f l d -> closed_qual 0 f l d1 -> closed_qual 0 f l d2 -> closed_qual 0 f l ([[1 ~> d1 ]]ᵈ ([[0 ~> d2 ]]ᵈ d)).\n  intros. erewrite open_qual_commute''; eauto. eapply closed_qual_open'; eauto. eapply closed_qual_open'; eauto.\nQed.\n\nLemma closed_ty_open2 : forall {f l d1 d2 T}, closed_ty 2 f l T -> closed_qual 0 f l d1 -> closed_qual 0 f l d2 -> closed_ty 0 f l ([[1 ~> d1 ]]ᵀ ([[0 ~> d2 ]]ᵀ T)).\n  intros. erewrite open_rec_ty_commute''; eauto. eapply closed_ty_open'; eauto. eapply closed_ty_open'; eauto.\nQed.\n\nLemma qstp_closed : forall {Γ Σ d1 d2}, qstp Γ Σ d1 d2 -> closed_qual 0 (‖Γ‖) (‖Σ‖) d1 /\\ closed_qual 0 (‖Γ‖) (‖Σ‖) d2.\n  intros Γ Σ d1 d2 HSQ. induction HSQ; intuition.\n  - eapply closed_qual_sub; eauto.\n  - apply indexr_var_some' in H. apply closed_qual_qlub. eapply closed_qual_monotone; eauto. lia. apply just_fv_closed. auto.\n  - apply indexr_var_some' in H. apply just_fv_closed. auto.\n  - apply indexr_var_some' in H. apply just_fv_closed. auto.\n  - apply indexr_var_some' in H. eapply closed_qual_monotone; eauto. lia.\n  - apply closed_qual_qlub; auto.\n  - apply closed_qual_qlub; auto.\nQed.\n\nLemma qstp_refl : forall {d d'}, d ≡ d' -> forall {Γ Σ}, closed_qual 0 (‖Γ‖) (‖Σ‖) d -> qstp Γ Σ d d'.\n  intros d d' Heq Γ Σ Hc. constructor. destruct d. destruct d'. qdec.\n  eapply closed_qual_cong; eauto.\nQed.\n\nLemma qs_cong_r  : forall Γ Σ q d1 d2,\n    qstp Γ Σ d1 d2 ->\n    closed_qual 0 (‖Γ‖) (‖Σ‖) q ->\n    qstp Γ Σ (d1 ⊔ q) (d2 ⊔ q).\n  intros. rewrite (@qlub_commute d1). rewrite (@qlub_commute d2). apply qs_cong; auto.\nQed.\n\nLemma stp_closed : forall {Γ Σ T1 d1 T2 d2},\n    stp Γ Σ T1 d1 T2 d2 ->\n    closed_ty 0 (‖Γ‖) (‖Σ‖) T1\n    /\\ closed_qual 0 (‖Γ‖) (‖Σ‖) d1\n    /\\ closed_ty 0 (‖Γ‖) (‖Σ‖) T2\n    /\\ closed_qual 0 (‖Γ‖) (‖Σ‖) d2.\nProof.  intros Γ Σ T1 d1 T2 d2 HS. induction HS.\n  - intuition. all: apply qstp_closed in H; intuition.\n  - intuition. all: apply qstp_closed in H; intuition.\n  - intuition. apply qstp_closed in H1; intuition. apply qstp_closed in H1; intuition.\n  (* - intuition; repeat apply closed_qual_qlub; auto. *)\nQed.\n\nLemma stp_refl' : forall {n T}, ty_size T < n -> forall {Γ Σ}, closed_ty 0 (‖Γ‖) (‖Σ‖) T -> forall {d d'}, qstp Γ Σ d d' -> stp Γ Σ T d T d'.\n  induction n; try lia; destruct T; simpl; intros Hsize Γ Σ Hc d d' Hstp; inversion Hc; subst.\n  - (*TUnit*) constructor. auto.\n  - (*TFun*) constructor; auto. apply IHn. lia. auto. apply qstp_refl. apply eqqual_refl. auto.\n    apply IHn. unfold open_ty'. unfold open_ty. rewrite <- open_ty_preserves_size. rewrite <- open_ty_preserves_size. simpl. lia. simpl. unfold open_ty'. unfold open_ty.\n    eapply closed_ty_open2. eapply closed_ty_monotone; eauto. 1,2 : eapply just_fv_closed; eauto.\n    apply qstp_refl. apply eqqual_refl. unfold openq'. unfold openq. rewrite open_qual_commute; auto.\n    simpl. eapply closed_qual_open. eapply closed_qual_open. eapply closed_qual_monotone; eauto.\n    lia. lia.\n  - (*TRef*) constructor; auto.\n    all : apply IHn; try lia; auto.\nQed.\n\nLemma stp_refl : forall {T Γ Σ}, closed_ty 0 (‖Γ‖) (‖Σ‖) T -> forall {d d'}, qstp Γ Σ d d' -> stp Γ Σ T d T d'.\n  intros. eapply stp_refl'; eauto.\nQed.\n\nLemma indexr_splice_tenv : forall {Γ1 i Γ2 b U du},\n    indexr i (Γ1 ++ Γ2) = Some (b, U, du) -> forall {k}, ‖Γ2‖ <= i ->\n    indexr i (Γ1 ↑ᴳ k ++ Γ2) = Some (b, U ↑ᵀ k, du ↑ᵈ k).\n  induction Γ1; intros; simpl in *; intuition. apply indexr_var_some' in H. lia.\n  rewrite app_length in *. rewrite splice_tenv_length.\n  destruct (Nat.eqb i (‖Γ1‖ + ‖Γ2‖)) eqn:Heq. inversion H. subst.\n  simpl. auto. apply IHΓ1; eauto.\nQed.\n\nLemma splice_qual_glb_dist : forall {d1 d2 k}, (d1 ⊓ d2) ↑ᵈ k = d1 ↑ᵈ k ⊓ d2 ↑ᵈ k.\n  intros. destruct d1; destruct d2; intuition.\n  simpl. f_equal. apply splice_set_inter_dist.\nQed.\n\nLemma splice_qual_lub_dist : forall {d1 d2 k}, (d1 ⊔ d2) ↑ᵈ k = (d1 ↑ᵈ k ⊔ d2 ↑ᵈ k).\n  intros. destruct d1; destruct d2; intuition.\n  simpl. f_equal. apply splice_set_union_dist.\nQed.\n\nLemma splice_qual_mem_lt : forall {x k d1}, x < k -> $x ∈ᵥ d1 ↑ᵈ k -> $x ∈ᵥ d1.\n  intros. destruct d1. simpl in *.\n  assert (Subset (singleton x) (splice_set k t)).\n  fnsetdec. replace (singleton x) with (splice_set k (singleton x)) in H1.\n  rewrite splice_set_subset_dist in H1. assert (In x (singleton x)).\n  fnsetdec. intuition. apply splice_set_singleton_inv. auto.\nQed.\n\nLemma splice_qual_mem_ge : forall {x k d1}, x >= k -> $(S x) ∈ᵥ d1 ↑ᵈ k -> $x ∈ᵥ d1.\n  intros. destruct d1. simpl in *.\n  assert (Subset (singleton (S x)) (splice_set k t)).\n  fnsetdec. replace (singleton (S x)) with (splice_set k (singleton x)) in H1.\n  rewrite splice_set_subset_dist in H1. assert (In x (singleton x)).\n  fnsetdec. intuition. apply splice_set_singleton_inc. auto.\nQed.\n\nLemma splice_qual_mem_loc : forall {l k d1}, l ∈ₗ d1 ↑ᵈ k <-> l ∈ₗ d1.\n  intros. destruct d1. simpl in *. intuition.\nQed.\n\nLemma splice_qual_not_mem : forall {k d1}, $k ∈ᵥ (d1 ↑ᵈ k) -> False.\n  intros. destruct d1. simpl in H.\n  unfold splice_set in *. apply NatSet.F.union_1 in H. intuition.\n  * destruct k. apply inc_non_zero in H0. auto.\n    rewrite <- inc_in_iff in H0. apply filter_ge_fun_prop in H0. lia.\n  * apply filter_lt_fun_prop in H0. lia.\nQed.\n\nLemma splice_qual_just_fv_ge : forall {k j fr}, k <= j -> ${fr} j ↑ᵈ k = ${fr}(S j).\n  intros. simpl. rewrite splice_set_singleton_inc; auto.\nQed.\nLemma splice_qual_just_fv_lt : forall {k j fr}, k > j -> ${fr} j ↑ᵈ k = ${fr}j.\n  intros. simpl. rewrite splice_set_singleton_inv; auto.\nQed.\n\nLemma not_fresh_splice_iff : forall {df n}, ♦∉ df <-> ♦∉ df ↑ᵈ n.\n  intros. destruct df. intuition.\nQed.\n\nLemma fresh_splice_iff : forall {df n}, ♦∈ df <-> ♦∈ df ↑ᵈ n.\n  intros. destruct df. intuition.\nQed.\n\nLemma stp_qstp_inv : forall {Γ Σ T1 d1 T2 d2}, stp Γ Σ T1 d1 T2 d2 -> qstp Γ Σ d1 d2.\n  intros Γ Σ T1 d1 T2 d2 HS. induction HS; intuition.\nQed.\n\nLemma weaken_qstp_gen : forall {Γ1 Γ2 Σ d1 d2},\n    qstp (Γ1 ++ Γ2) Σ d1 d2 ->\n    forall T', qstp ((Γ1 ↑ᴳ ‖Γ2‖) ++ T' :: Γ2) Σ (d1 ↑ᵈ ‖Γ2‖) (d2 ↑ᵈ ‖Γ2‖).\nProof.\n  intros Γ1 Γ2 Σ d1 d2 HSTP. remember (Γ1 ++ Γ2) as Γ. generalize dependent Γ1. induction HSTP; intros Γ1 HeqG T'; subst.\n  - constructor. apply subqual_splice_lr'. auto. apply splice_qual_closed'.\n    rewrite app_length in *. rewrite splice_tenv_length. auto.\n  - rewrite splice_qual_qlub_dist. bdestruct (f <? ‖Γ2‖).\n    * rewrite splice_qual_just_fv_lt; auto. erewrite @splice_qual_id with (d:=df).\n      eapply qs_self; eauto. rewrite indexr_skips. rewrite indexr_skips in H. rewrite indexr_skip. eauto.\n      1-3: simpl; lia. eapply closed_qual_monotone; eauto. lia.\n    * rewrite splice_qual_just_fv_ge; auto.\n      eapply qs_self; eauto. rewrite <- indexr_insert_ge; auto.\n      eapply @indexr_splice_tenv with (k:=‖Γ2‖) in H; auto. simpl in H. eauto.\n      eapply splice_qual_closed''; eauto. rewrite <- not_fresh_splice_iff. auto.\n  - bdestruct (x <? ‖Γ2‖).\n    * rewrite splice_qual_just_fv_lt; auto. erewrite @splice_qual_id with (d:=q1).\n      eapply qs_qvar; eauto. rewrite indexr_skips. rewrite indexr_skips in H. rewrite indexr_skip. eauto.\n      1-3: simpl; lia. eapply closed_qual_monotone; eauto. lia.\n    * rewrite splice_qual_just_fv_ge; auto.\n      eapply qs_qvar. rewrite <- indexr_insert_ge; auto.\n      eapply @indexr_splice_tenv with (k:=‖Γ2‖) in H; auto. simpl in H. eauto.\n      eapply splice_ty_closed''; eauto. eapply splice_qual_closed''; eauto.\n      rewrite <- not_fresh_splice_iff. auto.\n  - repeat rewrite splice_qual_qlub_dist. eapply qs_cong.\n    eapply IHHSTP. auto. apply splice_qual_closed'. rewrite app_length in *. rewrite splice_tenv_length. auto.\n  - eapply qs_trans; eauto.\nQed.\n\nLemma weaken_qstp : forall {Γ Σ d1 d2}, qstp Γ Σ d1 d2 -> forall T', qstp (T' :: Γ) Σ d1 d2.\n  intros Γ Σ d1 d2 HST. specialize (@weaken_qstp_gen [] Γ Σ d1 d2) as Hsp. simpl in *.\n  specialize (Hsp HST). intros. specialize (Hsp T'). apply qstp_closed in HST. intuition.\n  replace (d1 ↑ᵈ ‖Γ‖) with d1 in Hsp. replace (d2 ↑ᵈ ‖Γ‖) with d2 in Hsp. intuition.\n  1,2 : erewrite  splice_qual_id; eauto.\nQed.\n\nLemma weaken_qstp' : forall {Γ Σ d1 d2}, qstp Γ Σ d1 d2 -> forall Γ', qstp (Γ' ++ Γ) Σ d1 d2.\n  intros. induction Γ'.\n  - simpl. auto.\n  - replace ((a :: Γ') ++ Γ) with (a :: (Γ' ++ Γ)).\n    apply weaken_qstp. auto. simpl. auto.\nQed.\n\nLemma weaken_qstp_store : forall {Γ Σ d1 d2}, qstp Γ Σ d1 d2 -> forall {Σ'}, qstp Γ (Σ' ++ Σ) d1 d2.\n  intros. induction H.\n  - apply qs_sq; auto. rewrite app_length. eapply closed_qual_monotone; eauto. lia.\n  - eapply qs_self; eauto. erewrite app_length. eapply closed_qual_monotone; eauto. lia.\n  - eapply qs_qvar; eauto. all : erewrite app_length. eapply closed_ty_monotone; eauto. lia. eapply closed_qual_monotone; eauto. lia.\n  - eapply qs_cong; eauto. rewrite app_length. eapply closed_qual_monotone; eauto. lia.\n  - eapply qs_trans; eauto.\nQed.\n\nLemma weaken_qstp_store_ext : forall {Γ Σ d1 d2}, qstp Γ Σ d1 d2 -> forall {Σ'}, Σ' ⊇ Σ -> qstp Γ Σ' d1 d2.\n  intros. unfold extends in H0. destruct H0. subst. apply weaken_qstp_store. auto.\nQed.\n\nLemma weaken_stp_gen : forall {Γ1 Γ2 Σ T1 d1 T2 d2},  stp (Γ1 ++ Γ2) Σ T1 d1 T2 d2 ->\n    forall T', stp ((Γ1 ↑ᴳ ‖Γ2‖) ++ T' :: Γ2) Σ (T1 ↑ᵀ ‖Γ2‖) (d1 ↑ᵈ ‖Γ2‖) (T2 ↑ᵀ ‖Γ2‖) (d2 ↑ᵈ ‖Γ2‖).\nProof. intros Γ1 Γ2 Σ T1 d1 T2 d2  Hstp T'. remember (Γ1 ++ Γ2)  as Γ. generalize dependent Γ1.  induction Hstp. intros Γ1.\n  - constructor. eapply weaken_qstp_gen. subst. auto.\n  - intros. assert (stp Γ Σ (TRef q T1) d1 (TRef q T2) d2). { constructor; intuition. } subst.\n    apply stp_closed in H1 as Hcl. intuition.\n    inversion H2. inversion H3. subst.\n    constructor. apply weaken_qstp_gen. subst; auto. 1,2: fold splice_ty. apply stp_closed in H1 as Hcl. intuition.\n    1,2 : replace (T1 ↑ᵀ ‖Γ2‖) with T1; replace (T2 ↑ᵀ ‖Γ2‖) with T2; intuition.\n    1-6 : erewrite splice_ty_id; eauto; eapply closed_ty_monotone; eauto; intuition.\n    apply splice_qual_closed'. rewrite app_length in *. rewrite splice_tenv_length. auto.\n  - assert (stp Γ Σ (TFun d1 d2 T1 T2) d5 (TFun d3 d4 T3 T4) d6). { constructor; intuition. } intros.\n    subst. intuition. inversion H0; inversion H; subst. apply qstp_closed in H1 as Hcl. intuition.\n    constructor; try fold splice_ty. 1-2: constructor.\n    1,2,5,6 : apply splice_qual_closed'. 5-8 : apply splice_ty_closed'.\n    1-8: rewrite app_length in *; rewrite splice_tenv_length in *; auto.\n    apply weaken_qstp_gen. auto.\n    specialize (IHHstp1 Γ1). intuition.\n    specialize (IHHstp2 ((false,T3, d3) :: (true,(TFun d1 d2 T1 T2), {♦}) :: Γ1)). intuition.\n    repeat rewrite <- splice_ty_open'. repeat rewrite <- splice_qual_open'. simpl in H5.\n    repeat rewrite @open_ty'_len with (Γ:=(Γ1 ↑ᴳ ‖Γ2‖) ++ Γ2) (Γ':=Γ1++Γ2).\n    repeat rewrite @openq'_len with (Γ:=(Γ1 ↑ᴳ ‖Γ2‖) ++ Γ2) (Γ':=Γ1++Γ2). rewrite splice_set_empty in H5. auto.\n    all: repeat rewrite app_length; rewrite splice_tenv_length; auto.\n  (* - intros. specialize (IHHstp1 Γ1). specialize (IHHstp2 Γ1). intuition.\n    eapply s_trans; eauto. *)\nQed.\n\nLemma weaken_stp : forall {Γ Σ T1 d1 T2 d2}, stp Γ Σ T1 d1 T2 d2 -> forall T', stp (T' :: Γ) Σ T1 d1 T2 d2.\n  intros Γ Σ T1 d1 T2 d2 HST. specialize (@weaken_stp_gen [] Γ Σ T1 d1 T2 d2) as Hsp. simpl in *.\n  specialize (Hsp HST). intros. specialize (Hsp T'). apply stp_closed in HST. intuition.\n  replace (T1 ↑ᵀ ‖Γ‖) with T1 in Hsp. replace (T2 ↑ᵀ ‖Γ‖) with T2 in Hsp.\n  replace (d1 ↑ᵈ ‖Γ‖) with d1 in Hsp. replace (d2 ↑ᵈ ‖Γ‖) with d2 in Hsp. intuition.\n  1,2 : erewrite  splice_qual_id; eauto.\n  1,2 : erewrite splice_ty_id; eauto.\nQed.\n\nLemma weaken_stp' : forall {Γ Σ T1 d1 T2 d2}, stp Γ Σ T1 d1 T2 d2 -> forall Γ', stp (Γ' ++ Γ) Σ T1 d1 T2 d2.\n  intros. induction Γ'.\n  - simpl. auto.\n  - replace ((a :: Γ') ++ Γ) with (a :: (Γ' ++ Γ)).\n    apply weaken_stp. auto. simpl. auto.\nQed.\n\nLemma weaken_stp_store : forall {Σ Γ T1 d1 T2 d2}, stp Γ Σ T1 d1 T2 d2 -> forall Σ', stp Γ (Σ' ++ Σ) T1 d1 T2 d2.\nProof. intros Σ Γ T1 d1 T2 d2 HSTP. induction HSTP; intros.\n  + constructor. apply weaken_qstp_store. auto.\n  + constructor; auto. apply weaken_qstp_store. auto. rewrite app_length. eapply closed_qual_monotone; eauto. lia.\n  + constructor; auto. 1,2 : rewrite app_length; eapply closed_ty_monotone; eauto; lia.\n    apply weaken_qstp_store. auto.\n  (* + specialize (IHHSTP1 Σ'). specialize (IHHSTP2 Σ'). eapply s_trans in IHHSTP2; eauto. *)\nQed.\n\nLemma weaken_stp_store_ext : forall {Σ Γ T1 d1 T2 d2}, stp Γ Σ T1 d1 T2 d2 -> forall {Σ'}, Σ' ⊇ Σ ->  stp Γ Σ' T1 d1 T2 d2.\n  intros. unfold extends in H0. destruct H0. subst. apply weaken_stp_store. auto.\nQed.\n\nLemma qstp_non_fresh : forall {Γ Σ q1 q2}, qstp Γ Σ q1 q2 -> ♦∉ q2 -> ♦∉ q1.\n  intros. induction H; intuition.\n  - eapply not_fresh_sub; eauto.\n  - apply not_fresh_qlub' in H0. intuition.\nQed.\n\nLemma narrowing_qstp_gen : forall{Γ1 b U du Γ2 Σ d1 d2},\n    qstp (Γ1 ++ (b,U,du) :: Γ2) Σ d1 d2 -> (b = true -> (♦∈ du)) ->\n    forall {V dv}, stp Γ2 Σ V dv U du ->\n              qstp (Γ1 ++ (b,V,dv) :: Γ2) Σ d1 d2.\n  intros Γ1 b U du Γ2 Σ d1 d2 HST Hb. remember (Γ1 ++ (b,U,du) :: Γ2) as Γ.\n  generalize dependent Γ1; induction HST; intros; subst; intuition.\n  - constructor. auto. rewrite app_length in *. simpl in *. auto.\n  - eapply qs_self; eauto. destruct (PeanoNat.Nat.lt_trichotomy f (‖Γ2‖)) as [Hlen | [Hlen | Hlen] ].\n    * rewrite indexr_skips. rewrite indexr_skips in H.\n      rewrite indexr_skip.  rewrite indexr_skip in H. eauto. all: simpl; lia.\n    * subst. rewrite indexr_skips in H; auto. rewrite indexr_head in H. inversion H. subst.\n      intuition. rewrite H1 in H3. discriminate.\n    * rewrite indexr_skips'; auto. rewrite indexr_skips' in H; auto.\n  - destruct (PeanoNat.Nat.lt_trichotomy x (‖Γ2‖)) as [Hlen | [Hlen | Hlen] ].\n    * eapply qs_qvar; eauto. rewrite indexr_skips. rewrite indexr_skips in H.\n      rewrite indexr_skip.  rewrite indexr_skip in H. eauto. 1-4: simpl; lia.\n    * subst.  pose (H':=H). rewrite indexr_skips in H'. rewrite indexr_head in H'. inversion H'. subst.\n      eapply qs_trans. eapply qs_qvar. rewrite indexr_skips; auto. apply indexr_head.\n      1,2 : apply stp_closed in H3; intuition.\n      apply stp_qstp_inv in H3. eapply qstp_non_fresh; eauto.\n      apply stp_qstp_inv in H3. eapply weaken_qstp'. eapply weaken_qstp. auto. auto.\n    * eapply qs_qvar; eauto. rewrite indexr_skips'; auto. rewrite indexr_skips' in H. eauto.\n      simpl. lia.\n  - eapply qs_cong; eauto. rewrite app_length in *. simpl in *. auto.\n  - eapply qs_trans; eauto.\nQed.\n\nLemma narrowing_stp_gen : forall{Γ1 b U du Γ2 Σ T1 d1 T2 d2}, stp (Γ1 ++ (b,U,du) :: Γ2) Σ T1 d1 T2 d2 -> (b = true -> (♦∈ du)) ->\n    forall {V dv}, (stp Γ2 Σ V dv U du) -> stp (Γ1 ++ (b,V,dv) :: Γ2) Σ T1 d1 T2 d2.\nProof. intros Γ1 b U du Γ2 Σ T1 d1 T2 d2 HST Hb. remember (Γ1 ++ (b,U,du) :: Γ2) as Γ.\n  generalize dependent Γ1; induction HST; intros; intuition.\n  - subst. constructor. eapply narrowing_qstp_gen; eauto.\n  - subst. constructor. eapply narrowing_qstp_gen; eauto. auto. auto.\n    rewrite app_length in *. simpl in *. auto.\n  - rewrite HeqΓ in *. constructor.\n    subst. rewrite app_length in *. simpl in *. auto.\n    subst. rewrite app_length in *. simpl in *. auto.\n    eapply narrowing_qstp_gen; subst; eauto. eapply IHHST1; eauto.\n    unfold open_ty' in *. unfold openq' in *.\n    rewrite app_length in *. simpl in *.\n    repeat rewrite app_comm_cons.\n    eapply IHHST2; eauto.\n  (* - subst. specialize (IHHST1 Γ1).  specialize (IHHST2 Γ1). intuition.\n    specialize (H0 V dv).  specialize (H1 V dv). intuition.  eapply s_trans; eauto. *)\nQed.\n\nLemma narrowing_stp : forall{b U du Γ Σ T1 d1 T2 d2}, stp ((b,U,du) :: Γ) Σ T1 d1 T2 d2 -> (b = true -> (♦∈ du)) ->\n    forall {V dv}, stp Γ Σ V dv U du -> stp ((b,V,dv) :: Γ) Σ T1 d1 T2 d2.\n  intros. specialize (@narrowing_stp_gen [] b U du Γ Σ T1 d1 T2 d2) as narrow. simpl in *. eapply narrow; eauto.\nQed.\n\nLemma stp_change_q : forall {Γ Σ T1 d1 T2 d2}, stp Γ Σ T1 d1 T2 d2 -> forall {q1 q2}, qstp Γ Σ q1 q2 -> stp Γ Σ T1 q1 T2 q2.\n  intros. induction H; constructor; auto.\nQed.\n\nLemma stp_shrink_var : forall {Γ Σ T1 d1 T2 d2}, stp Γ Σ T1 d1 T2 d2 -> forall {fr x}, x < ‖Γ‖ -> stp Γ Σ T1 ${fr}x T2 ${fr}x.\n  intros. eapply stp_change_q; eauto. apply qs_sq; auto. apply just_fv_closed. auto.\nQed.\n\nLemma s_trans' : forall n T2, ty_size T2 < n -> forall Γ Σ T1 d1 d2 T3 d3,\n  stp Γ Σ T1 d1 T2 d2 -> stp Γ Σ T2 d2 T3 d3 -> stp Γ Σ T1 d1 T3 d3.\n  induction n; intros T2 Hsz; try lia; destruct T2; intros Γ Σ T1 d1 d2 T3 d3 H12 H23; inversion H12; inversion H23; subst; simpl in Hsz.\n  - constructor; eauto.\n  - constructor; eauto. eapply IHn; eauto. lia.\n    assert (H13' : stp ((false, T8, d11) :: (true, TFun d0 d4 T0 T2, {♦}) :: Γ) Σ  (T2 <~²ᵀ Γ) (d4 <~²ᵈ Γ) (T2_2 <~²ᵀ Γ) (q0 <~²ᵈ Γ)). {\n      eapply narrowing_stp; eauto. intuition. apply weaken_stp. auto. }\n    assert (H28' : stp ((false, T8, d11) :: (true, TFun d0 d4 T0 T2, {♦}) :: Γ) Σ (T2_2 <~²ᵀ Γ) (q0 <~²ᵈ Γ) (T9 <~²ᵀ Γ) (d12 <~²ᵈ Γ)). {\n      replace ((false, T8, d11) :: (true, TFun d0 d4 T0 T2, {♦}) :: Γ) with ([(false, T8, d11)] ++ ((true, TFun d0 d4 T0 T2, {♦}) :: Γ)); auto.\n      eapply narrowing_stp_gen. eapply H28. intuition. eapply stp_change_q; eauto.\n    }\n    eapply IHn; eauto. unfold open_ty'. unfold open_ty. repeat rewrite <- open_ty_preserves_size. lia.\n  - constructor; eauto. all: eapply IHn; eauto; lia.\nQed.\n\nLemma s_trans : forall Γ Σ T1 d1 T2 d2 T3 d3, stp Γ Σ T1 d1 T2 d2 -> stp Γ Σ T2 d2 T3 d3 -> stp Γ Σ T1 d1 T3 d3.\n  intros. eapply s_trans'; eauto.\nQed.\n\nLemma stp_scale_qlub : forall {Γ Σ T1 d1 T2 d2}, stp Γ Σ T1 d1 T2 d2 -> forall {q}, closed_qual 0 (‖Γ‖) (‖Σ‖) q -> stp Γ Σ T1 (d1 ⊔ q) T2 (d2 ⊔ q).\n  intros. eapply stp_change_q; eauto. apply stp_qstp_inv in H. rewrite qlub_commute. rewrite @qlub_commute with (d1:=d2). eauto.\nQed.\n\nLemma stp_scale_qqplus : forall {Γ Σ T1 d1 T2 d2}, stp Γ Σ T1 d1 T2 d2 -> forall {d}, closed_qual 0 (‖Γ‖) (‖Σ‖) d -> stp Γ Σ T1 (d1 ⋓ d) T2 (d2 ⋓ d).\n  intros. destruct (♦∈? d1) eqn:fr1; destruct (♦∈? d2) eqn:fr2.\n  - repeat rewrite qqplus_fresh; auto. apply stp_scale_qlub; auto.\n  - apply stp_qstp_inv in H. specialize (qstp_non_fresh H fr2) as Hc. destruct d1. simpl in *.\n    subst. discriminate.\n  - rewrite @qqplus_fresh with (d:=d2); auto. unfold qqplus. rewrite fr1.\n    eapply s_trans; eauto. apply stp_refl. apply stp_closed in H. intuition.\n    apply qs_sq; auto. apply stp_closed in H. intuition. apply closed_qual_qlub; auto.\n  - unfold qqplus. rewrite fr1. rewrite fr2. auto.\nQed.\n\nLemma saturated_cons : forall {Γ Σ q}, saturated Γ Σ q -> forall {b T q'}, saturated ((b, T, q') :: Γ) Σ q.\n  intros. constructor; intros. unfold tenv_saturated. intros. apply H in H0. inversion H0.\n  econstructor; eauto. rewrite indexr_skip; eauto. apply indexr_var_some' in H1. lia.\n  inversion H. intuition.\nQed.\n\nLemma senv_saturated_conss : forall {Σ q}, senv_saturated Σ q -> forall {T q'}, senv_saturated ((T, q') :: Σ) q.\n  intros. unfold senv_saturated. intros. apply H in H0. inversion H0. econstructor. rewrite indexr_skip.\n  eauto. apply indexr_var_some' in H1. lia. all : auto.\nQed.\n\nLemma saturated_conss : forall {Γ Σ q}, saturated Γ Σ q -> forall {T q'}, saturated Γ ((T, q') :: Σ) q.\n  intros. constructor; intros. unfold tenv_saturated. intros. apply H in H0. inversion H0. subst.\n  econstructor; eauto. simpl. eapply closed_qual_monotone; eauto. unfold senv_saturated. intros.\n  apply senv_saturated_conss; auto. inversion H. auto.\nQed.\n\nLemma saturated_app : forall {Γ' Γ Σ q}, saturated Γ Σ q -> saturated (Γ' ++ Γ) Σ q.\n  induction Γ'; intros; simpl; intuition.\n  apply saturated_cons; auto.\nQed.\n\nLemma saturated_apps : forall {Σ' Γ Σ q}, saturated Γ Σ q -> saturated Γ (Σ' ++ Σ) q.\n  induction Σ'; intros; simpl; intuition.\n  apply saturated_conss; auto.\nQed.\n\nLemma senv_saturated_app : forall {Σ' Σ q}, senv_saturated Σ q -> senv_saturated (Σ' ++ Σ) q.\n  induction Σ'; intros; simpl; intuition.\n  apply senv_saturated_conss; auto.\nQed.\n\nLemma wf_senv_prop : forall {Σ}, wf_senv Σ -> forall l T q, indexr l Σ = Some (T, q) -> (closed_ty 0 0 l T /\\ closed_qual 0 0 l q /\\ senv_saturated Σ q).\n  intros Σ Hwf. induction Hwf; intros. simpl in H. discriminate. destruct (l =? ‖Σ‖) eqn:Heq.\n  - simpl in H2. rewrite Heq in H2. inversion H2. subst. apply Nat.eqb_eq in Heq. subst. intuition.\n    apply senv_saturated_conss. auto.\n  - simpl in H2. rewrite Heq in H2. apply IHHwf in H2. intuition. apply senv_saturated_conss. auto.\nQed.\n\nLemma senv_saturated_empty : forall {Σ fr}, senv_saturated Σ ∅{ fr }.\n  intros. unfold senv_saturated. intros. simpl in H. apply NatSetNotin.notin_empty in H; contradiction.\nQed.\n#[global] Hint Resolve senv_saturated_empty : core.\n\nLemma tenv_saturated_empty : forall {Γ Σ fr}, tenv_saturated Γ Σ ∅{ fr }.\n  intros. unfold tenv_saturated. intros. simpl in H. apply NatSetNotin.notin_empty in H; contradiction.\nQed.\n#[global] Hint Resolve tenv_saturated_empty : core.\n\nLemma saturated_empty : forall {Γ Σ fr}, saturated Γ Σ ∅{ fr }.\n  intuition.\nQed.\n#[global] Hint Resolve saturated_empty : core.\n\nLemma senv_saturated_just_fv : forall {Σ fr x}, senv_saturated Σ ${fr}x.\n  intros. unfold senv_saturated. intros. simpl in H. apply NatSetNotin.notin_empty in H. contradiction.\nQed.\n#[global] Hint Resolve senv_saturated_just_fv : core.\n\nLemma tenv_saturated_empty_tenv : forall {Σ q}, closed_qual 0 0 (‖Σ‖) q -> tenv_saturated [] Σ q.\n  intros. unfold tenv_saturated. intros. inversion H. subst. apply bound_0_empty in H1,H2.\n  subst. simpl in *. apply NatSetNotin.notin_empty in H0. contradiction.\nQed.\n#[global] Hint Resolve tenv_saturated_empty_tenv : core.\n\nLemma senv_saturated_open_qual : forall {Σ d1 d2}, senv_saturated Σ d1 -> forall {k}, senv_saturated Σ ([[ k ~> ∅ ]]ᵈ d2) -> senv_saturated Σ ([[ k ~> d1 ]]ᵈ d2).\n  intros. destruct d1. destruct d2. simpl in *.\n  destruct (mem k t3) eqn:Hmem; intuition.\n  repeat rewrite empty_union_right in H0. rewrite orb_false_r in H0.\n  unfold senv_saturated in *. intros. simpl in *. specialize (H l). specialize (H0 l).\n  assert (Hl : In l t4 \\/ In l t1). fnsetdec. intuition.\n  * inversion H3. econstructor; eauto. eapply subqual_trans; eauto. qdec.\n  * inversion H3. econstructor; eauto. eapply subqual_trans; eauto. qdec.\nQed.\n\nLemma senv_saturated_openq : forall {f Σ df d1 d2},\n    senv_saturated Σ df -> closed_qual 0 f (‖Σ‖) df ->\n    senv_saturated Σ d1 -> closed_qual 0 f (‖Σ‖) d1 -> senv_saturated Σ (openq ∅ ∅ d2) -> senv_saturated Σ (openq df d1 d2).\n    intros. unfold openq in *. apply senv_saturated_open_qual; auto.\n    erewrite open_qual_commute''; eauto. erewrite open_qual_commute'' in H3; eauto.\n    eapply senv_saturated_open_qual; auto. Unshelve. all: apply 0.\nQed.\n\nLemma saturated_senv_qlub : forall {Σ q1 q2}, senv_saturated Σ q1 -> senv_saturated Σ q2 -> senv_saturated Σ (q1 ⊔ q2).\n  intros. unfold senv_saturated in *. intros. specialize (H l). specialize (H0 l).\n  destruct q1. destruct q2. simpl in *. assert (In l t1 \\/ In l t4). fnsetdec. intuition.\n  - inversion H2. subst. econstructor; eauto. eapply subqual_trans; eauto. qdec.\n  - inversion H2. subst. econstructor; eauto. eapply subqual_trans; eauto. qdec.\nQed.\n#[global] Hint Resolve saturated_senv_qlub : core.\n\nLemma saturated_qlub : forall {Γ Σ q1 q2}, saturated Γ Σ q1 -> saturated Γ Σ q2 -> saturated Γ Σ (q1 ⊔ q2).\n  intros. inversion H. inversion H0. constructor; auto.\n  unfold tenv_saturated in *. intros. specialize (H1 x). specialize (H3 x).\n  rewrite qmem_lub_or_commute in H5. intuition.\n  - inversion H5. subst. econstructor; eauto. eapply subqual_trans; eauto.\n  - inversion H5. subst. econstructor; eauto. eapply subqual_trans; eauto.\nQed.\n#[global] Hint Resolve saturated_qlub : core.\n\nLemma senv_saturated_qqplus : forall {Σ q1 q2}, senv_saturated Σ q1 -> senv_saturated Σ q2 -> senv_saturated Σ (q1 ⋓ q2).\n  intros. destruct q1. destruct b; unfold qqplus. rewrite qfresh_true. auto.\n  rewrite qfresh_false. auto.\nQed.\n#[global] Hint Resolve senv_saturated_qqplus : core.\n\nLemma saturated_qqplus : forall {Γ Σ q1 q2}, saturated Γ Σ q1 -> saturated Γ Σ q2 -> saturated Γ Σ (q1 ⋓ q2).\n  intros. destruct q1. destruct b; unfold qqplus. rewrite qfresh_true. apply saturated_qlub; auto.\n  rewrite qfresh_false. auto.\nQed.\n#[global] Hint Resolve saturated_qqplus : core.\n\nLemma saturated_senv_qglb : forall {Σ q1 q2}, senv_saturated Σ q1 -> senv_saturated Σ q2 -> senv_saturated Σ (q1 ⊓ q2).\n  intros. unfold senv_saturated in *. intros. specialize (H l). specialize (H0 l).\n  rewrite qmem_glb_and_commute in H1. intuition.\n  inversion H. inversion H1. subst. econstructor; eauto. rewrite H0 in H6. inversion H6. subst.\n  rewrite qlub_qglb_dist_r. apply qglb_bound; auto.\nQed.\n#[global] Hint Resolve saturated_senv_qglb : core.\n\nLemma saturated_qglb : forall {Γ Σ q1 q2}, saturated Γ Σ q1 -> saturated Γ Σ q2 -> saturated Γ Σ (q1 ⊓ q2).\n  intros. inversion H. inversion H0. constructor; auto. unfold tenv_saturated in *. intros.\n  rewrite qmem_glb_and_commute in H5. specialize (H1 x). specialize (H3 x). intuition.\n  inversion H5. inversion H1. subst. econstructor; eauto. rewrite H3 in H10. inversion H10. subst.\n  apply qglb_bound; auto.\nQed.\n#[global] Hint Resolve saturated_qglb : core.\n\nLemma weaken_store_senv_saturated : forall {Σ q}, senv_saturated Σ q -> forall {Σ'}, Σ' ⊇ Σ -> senv_saturated Σ' q.\n  intros. unfold senv_saturated. intros.\n  apply H in H1. inversion H1. econstructor; eauto. unfold extends in H0. destruct H0 as [Σ'' Hs].\n  subst. rewrite indexr_skips. eauto. apply indexr_var_some' in H2. lia.\nQed.\n\nLemma weaken_store_tenv_saturated : forall {Γ Σ q}, tenv_saturated Γ Σ q -> forall {Σ'}, Σ' ⊇ Σ -> tenv_saturated Γ Σ' q.\n  intros. unfold tenv_saturated. intros. apply H in H1. inversion H1. econstructor; eauto. eapply closed_qual_monotone; eauto.\nQed.\n\nLemma weaken_store_saturated : forall {Γ Σ q}, saturated Γ Σ q -> forall {Σ'}, Σ' ⊇ Σ -> saturated Γ Σ' q.\n  intros. inversion H. constructor. eapply weaken_store_tenv_saturated; eauto. eapply weaken_store_senv_saturated; eauto.\nQed.\n\nFixpoint has_type_closed  {Γ φ Σ t T d} (ht : has_type Γ φ Σ t T d) :\n  closed_qual 0 (‖Γ‖) (‖Σ‖) φ /\\\n  closed_tm 0 (‖Γ‖) (‖Σ‖) t /\\\n  closed_ty 0 (‖Γ‖) (‖Σ‖) T /\\\n  closed_qual 0 (‖Γ‖) (‖Σ‖) d.\nProof.\n  destruct ht; intuition; try apply has_type_closed in ht; try apply has_type_closed in ht1;\n    try apply has_type_closed in ht2; intuition; eauto.\n  8,9 : try (apply closed_qual_qlub; auto); eauto.\n  - constructor. apply indexr_var_some' in H. auto.\n  - apply indexr_var_some' in H. eapply closed_ty_monotone; eauto. lia.\n  (* - apply stp_closed in H; intuition. *)\n  - inversion H6. subst. unfold open_ty.\n    eapply closed_ty_open2; eauto.\n  - inversion H6. subst. unfold openq.\n    eapply closed_qual_open2; eauto.\n  - inversion H12. subst. unfold open_ty.\n    eapply closed_ty_open2; eauto.\n  - inversion H12. subst. unfold openq.\n    eapply closed_qual_open2; eauto.\n  - constructor. apply indexr_var_some' in H0. auto.\n  - inversion H3. subst. eapply closed_ty_monotone; eauto; lia.\n  - apply stp_closed in H. intuition.\nQed.\n\nLemma open_qual_subqual : forall {d1 d2 φ}, d1 ⊑ φ -> forall {k}, ([[ k ~> ∅ ]]ᵈ d2) ⊑ φ -> ([[ k ~> d1 ]]ᵈ d2) ⊑ φ.\n  intros. destruct d1. destruct d2. destruct φ. simpl in *. intuition.\n  destruct (mem k t3) eqn:Hmem; simpl in *; intuition; try fnsetdec. destr_bool.\nQed.\n\nLemma openq_subqual : forall {df d1 d2 φ f l}, closed_qual 0 f l φ -> df ⊑ φ -> d1 ⊑ φ -> d2 <~ᵈ ∅; ∅ ⊑ φ -> d2 <~ᵈ df; d1 ⊑ φ.\n  intros. unfold openq in *. apply open_qual_subqual; auto. erewrite open_qual_commute''; eauto.\n  erewrite open_qual_commute'' in H2; eauto. apply open_qual_subqual; auto.\n  Unshelve. all : apply 0.\nQed.\n\nFixpoint has_type_filter {Γ φ Σ t T d} (ht : has_type Γ φ Σ t T d) : d ⊑ φ.\n  destruct ht; intuition. 1,2: specialize (has_type_closed ht1) as Hc; intuition; eapply openq_subqual; eauto.\n  apply qlub_bound; auto. apply qlub_bound; auto. apply has_type_filter in ht. auto.\nQed.\n\nLemma closed_qual_qmem_fv : forall {b f l q}, closed_qual b f l q -> forall {x}, $x ∈ᵥ q -> x < f.\n  intros. specialize (@subqual_just_fv_bound x q) as Hx. destruct q. inversion H. subst.\n  simpl in *. intuition.\n  assert (Hsub  : Subset (singleton x) t). fnsetdec.\n  assert (Hsub' : Subset {}N t0). fnsetdec.\n  assert (Hsub'': Subset {}N t1). fnsetdec.\n  intuition.\nQed.\n\nLemma bound_vars_untypable : forall {Γ φ Σ T d i}, has_type Γ φ Σ #i T d -> False.\n  intros Γ φ Σ T d i HT. remember (tvar #i) as t. induction HT; try discriminate; intuition.\nQed.\n\nLemma splice_senv_saturated : forall {Σ d1}, senv_saturated Σ d1 -> forall {k}, senv_saturated Σ (d1 ↑ᵈ k).\n  intros. unfold senv_saturated in *. destruct d1. simpl in *. intros. apply H in H0.\n  inversion H0. econstructor; eauto. inversion H3. subst. apply bound_0_empty in H4, H5. subst. qdec.\nQed.\n#[global] Hint Resolve splice_senv_saturated : core.\n\nLemma weaken_tenv_saturated : forall {Γ1 Γ2 Σ d1},\n    tenv_saturated (Γ1 ++ Γ2) Σ d1 -> forall X, tenv_saturated ((Γ1 ↑ᴳ ‖Γ2‖) ++ X :: Γ2) Σ (d1 ↑ᵈ ‖Γ2‖).\n  intros. unfold tenv_saturated in *. intros. bdestruct (x <? ‖Γ2‖).\n  - apply splice_qual_mem_lt in H0; auto. apply H in H0. inversion H0.\n    rewrite indexr_skips in H2; try lia. apply (sat_var b U q'); auto.\n    rewrite indexr_skips. rewrite indexr_skip; auto. lia. simpl. lia.\n    replace q' with (q' ↑ᵈ ‖Γ2‖). apply subqual_splice_lr'. auto.\n    eapply splice_qual_id. eapply closed_qual_monotone; eauto. lia.\n  - bdestruct (x =? ‖Γ2‖).\n    * subst. apply splice_qual_not_mem in H0. contradiction.\n    * destruct x. lia. assert (Hx : x >= ‖Γ2‖). lia.\n      specialize (splice_qual_mem_ge Hx H0) as Hxd1. apply H in Hxd1.\n      inversion Hxd1. econstructor. rewrite <- indexr_insert_ge.\n      eapply indexr_splice_tenv. eauto. lia. lia. rewrite subqual_splice_lr'. auto.\n      apply splice_qual_closed''; auto.\nQed.\n#[global] Hint Resolve weaken_tenv_saturated : core.\n\nLemma weaken_saturated : forall {Γ1 Γ2 Σ d1},\n    saturated (Γ1 ++ Γ2) Σ d1 -> forall X, saturated ((Γ1 ↑ᴳ ‖Γ2‖) ++ X :: Γ2) Σ (d1 ↑ᵈ ‖Γ2‖).\n  intros. inversion H. intuition.\nQed.\n#[global] Hint Resolve weaken_saturated : core.\n\nLemma splice_qual_injective : forall {k q q'}, q ↑ᵈ k = q' ↑ᵈ k -> q = q'.\n  intros. destruct q. destruct q'. simpl in *. inversion H. subst.\n  f_equal. eapply splice_set_injective; eauto.\nQed.\n\nLemma splice_ty_injective : forall {T T' k}, T ↑ᵀ k = T' ↑ᵀ k -> T = T'.\n  induction T; intros; intuition; destruct T'; simpl in H; intuition; try discriminate.\n  - inversion H. apply splice_qual_injective in H1, H2. subst.\n    specialize (IHT1 T'1 k). specialize (IHT2 T'2 k). intuition. subst. auto.\n  - inversion H. apply splice_qual_injective in H1. subst.\n    specialize (IHT T' k). intuition. subst. auto.\nQed.\n\nLemma not_free_splice_ty_iff : forall {v k T}, not_free v T <-> not_free v (T ↑ᵀ k).\n  intros v k. unfold not_free. intros. intuition.\n  - replace (∅) with (∅ ↑ᵈ k); auto. rewrite <- splice_ty_open_rec_ty. rewrite H. auto.\n  - replace (∅) with (∅ ↑ᵈ k) in H; auto. rewrite <- splice_ty_open_rec_ty in H.\n    eapply splice_ty_injective; eauto.\nQed.\n\nLemma weaken_gen : forall {t Γ1 Γ2 φ Σ T d},\n    has_type (Γ1 ++ Γ2) φ Σ t T d ->\n    forall X, has_type ((Γ1 ↑ᴳ ‖Γ2‖) ++ X :: Γ2) (φ ↑ᵈ ‖Γ2‖) Σ (t ↑ᵗ ‖Γ2‖) (T ↑ᵀ ‖Γ2‖) (d ↑ᵈ ‖Γ2‖).\n  intros t Γ1 Γ2 φ Σ T d HT. remember (Γ1 ++ Γ2) as Γ. generalize dependent Γ1. generalize dependent Γ2.\n  induction HT; intros; subst.\n  - (* tunit *) simpl. rewrite splice_set_empty.\n    constructor. eapply splice_qual_closed'.\n    rewrite app_length in *. rewrite splice_tenv_length. auto.\n    - (* t_var *) simpl.\n    destruct (le_lt_dec (‖Γ2‖) x) eqn:Heq.\n    * (* |Γ2| <= x < |Γ1|+|Γ2|*)\n      rewrite splice_set_singleton_inc; auto. apply t_var with (b:=b) (d:=d ↑ᵈ ‖Γ2‖).\n      rewrite <- indexr_insert_ge. apply indexr_splice_tenv; eauto. lia.\n      erewrite <- splice_qual_just_fv_ge; eauto.\n      rewrite subqual_splice_lr'. auto.\n      eapply splice_qual_closed'.\n      rewrite app_length in *. rewrite splice_tenv_length. auto.\n      eapply splice_ty_closed''; eauto. eapply splice_qual_closed''; eauto.\n    * (* |Γ2| > x *)\n      rewrite indexr_skips in H; auto. rewrite splice_set_singleton_inv; auto.\n      apply t_var with (b:=b) (d:=d).\n      rewrite <- indexr_insert_lt; auto. rewrite indexr_skips; auto.\n      erewrite splice_ty_id. auto.\n      eapply closed_ty_monotone; eauto. lia.\n      erewrite <- splice_qual_just_fv_lt; eauto.\n      rewrite subqual_splice_lr'. auto.\n      eapply splice_qual_closed'.\n      rewrite app_length in *. rewrite splice_tenv_length. auto.\n      erewrite splice_ty_id; eauto. eapply closed_ty_monotone; eauto. lia. auto.\n  - (* t_abs *) rewrite app_length in *. simpl. constructor; auto.\n    apply splice_closed'.\n    1-3: rewrite app_length; rewrite splice_tenv_length; simpl;\n      replace (‖Γ1‖ + S (‖Γ2‖)) with (S (‖Γ1‖ + ‖Γ2‖)); eauto.\n    inversion H0. subst. constructor. 1,2,5: apply splice_qual_closed; auto. 1,2 : apply splice_ty_closed; auto.\n    rewrite subqual_splice_lr'. auto. rewrite <- not_fresh_splice_iff. auto.\n    rewrite app_comm_cons.\n    replace ((false, T1 ↑ᵀ ‖Γ2‖, d1 ↑ᵈ ‖Γ2‖)\n                :: ((true, TFun (d1 ↑ᵈ ‖Γ2‖) (d2 ↑ᵈ ‖Γ2‖) (T1 ↑ᵀ ‖Γ2‖) (T2 ↑ᵀ ‖Γ2‖), df ↑ᵈ ‖Γ2‖)\n                      :: (Γ1 ↑ᴳ ‖Γ2‖)) ++ X :: Γ2)\n            with ((((false,T1, d1) :: (true, TFun d1 d2 T1 T2, df) :: Γ1) ↑ᴳ ‖Γ2‖) ++ X :: Γ2).\n    replace ((df ↑ᵈ ‖Γ2‖) ⊔ $!(‖(Γ1 ↑ᴳ ‖Γ2‖) ++ X :: Γ2‖) ⊔ $!(S (‖(Γ1 ↑ᴳ ‖Γ2‖) ++ X :: Γ2‖)) ⊔ {♦})\n      with  ((df ⊔ $!(‖Γ1‖ + ‖Γ2‖) ⊔ $!(S (‖Γ1‖ + ‖Γ2‖)) ⊔ {♦}) ↑ᵈ ‖Γ2‖).\n    rewrite <- splice_open'. rewrite <- splice_ty_open'. rewrite <- splice_qual_open'.\n    rewrite @open_tm'_len with (Γ':=(Γ1 ++ Γ2)). rewrite @open_ty'_len with (Γ':=(Γ1 ++ Γ2)).\n    rewrite @openq'_len with (Γ':=(Γ1 ++ Γ2)).\n    apply IHHT; intuition. 1-4 : repeat rewrite app_length; rewrite splice_tenv_length; auto.\n    repeat rewrite splice_qual_lub_dist. rewrite splice_qual_fresh. simpl.\n    f_equal. repeat rewrite splice_set_singleton_inc; try lia; repeat f_equal; lia.\n    simpl. auto.\n  - (* t_app *) simpl. rewrite splice_qual_open''. rewrite splice_ty_open''. rewrite splice_qual_empty. apply t_app with (T1:=T1 ↑ᵀ ‖Γ2‖) (df:=df ↑ᵈ ‖Γ2‖).\n    apply IHHT1; auto.\n    apply IHHT2; auto.\n    rewrite <- @splice_qual_empty with (k := ‖Γ2‖); rewrite <- splice_qual_open''.\n    rewrite subqual_splice_lr'; auto. rewrite <- not_fresh_splice_iff. auto.\n    replace ((d2 ↑ᵈ (‖ Γ2 ‖)) <~ᵈ ∅; ∅) with ((d2 <~ᵈ ∅; ∅) ↑ᵈ (‖ Γ2 ‖)); auto.\n    rewrite splice_qual_open''. f_equal; auto. rewrite <- not_free_splice_ty_iff. auto.\n  - (* t_app_fresh *) simpl. rewrite splice_qual_open''. rewrite splice_ty_open''. rewrite splice_qual_empty.\n    apply t_app_fresh with (T1:=T1 ↑ᵀ ‖Γ2‖) (d1:=d1 ↑ᵈ ‖Γ2‖) (df:=df ↑ᵈ ‖Γ2‖) (d1':=d1' ↑ᵈ ‖Γ2‖) (df':=df' ↑ᵈ ‖Γ2‖); auto.\n    replace (TFun ((df' ↑ᵈ (‖ Γ2 ‖) ⋒ d1' ↑ᵈ (‖ Γ2 ‖))) (d2 ↑ᵈ (‖ Γ2 ‖)) (T1 ↑ᵀ (‖ Γ2 ‖)) (T2 ↑ᵀ (‖ Γ2 ‖)))\n       with ((TFun (df' ⋒ d1') d2 T1 T2) ↑ᵀ (‖ Γ2 ‖)). auto.\n    simpl. rewrite splice_qual_qlub_dist. rewrite splice_qual_fresh. rewrite splice_qual_glb_dist. auto.\n    1,2 : rewrite subqual_splice_lr'; auto.\n    intros Hfresh. rewrite <- fresh_splice_iff in Hfresh. rewrite <- not_free_splice_ty_iff. auto.\n    rewrite <- not_free_splice_ty_iff. auto.\n    rewrite <- @splice_qual_empty with (k := ‖Γ2‖); rewrite <- splice_qual_open''.\n    1-3 : rewrite subqual_splice_lr'; auto.\n    replace ((d2 ↑ᵈ (‖ Γ2 ‖)) <~ᵈ ∅; ∅) with ((d2 <~ᵈ ∅; ∅) ↑ᵈ (‖ Γ2 ‖)); auto.\n    rewrite splice_qual_open''. f_equal; auto.\n  - (* t_loc *) simpl. rewrite splice_qual_qlub_dist. simpl. rewrite splice_set_empty. apply t_loc. eapply splice_qual_closed'.\n    rewrite app_length in *. rewrite splice_tenv_length. auto.\n    erewrite splice_ty_id; eauto. erewrite splice_qual_id; eauto. eapply closed_qual_monotone; eauto. lia. eapply closed_ty_monotone; eauto. lia.\n    erewrite splice_ty_id; eauto. eapply closed_ty_monotone; eauto. lia.\n    erewrite splice_qual_id; eauto. eapply closed_qual_monotone; eauto. lia.\n    destruct φ. simpl in *. intuition. apply subqual_splice_lr'. auto. rewrite <- not_fresh_splice_iff. auto.\n  - (* t_ref *) simpl in *. specialize (IHHT Γ2 Γ1). intuition.\n    specialize (H2 (a0, b0, b)). destruct d1. repeat rewrite empty_union_left.\n    replace (qset true t0 t1 t2) with ({♦} ⊔ (qset b1 t0 t1 t2)); try qdec.\n    rewrite splice_qual_qlub_dist. rewrite splice_qual_fresh. apply t_ref; auto.\n    erewrite splice_ty_id; auto. eapply closed_ty_monotone; eauto. lia.\n    destruct φ. intuition. subst. simpl. intuition.\n  - (* t_deref *) simpl. econstructor; eauto. rewrite <- not_fresh_splice_iff. auto. apply subqual_splice_lr'. auto.\n  - (* t_assign *) simpl. specialize (IHHT1 Γ2 Γ1). specialize (IHHT2 Γ2 Γ1). intuition.\n    specialize (H0 (a0,b0,b)). specialize (H1 (a0,b0,b)). simpl in *. rewrite splice_set_empty in *.\n    eapply t_assign; eauto. rewrite <- not_fresh_splice_iff. auto.\n  - (* t_sub *) eapply t_sub. eapply IHHT; auto.\n    apply @weaken_stp_gen; eauto; lia. apply subqual_splice_lr'. auto. auto.\nQed.\n\nLemma weaken_flt : forall {Γ φ Σ t T d},\n    has_type Γ φ Σ t T d ->\n    forall {φ'}, φ ⊑ φ' -> closed_qual 0 (‖Γ‖) (‖Σ‖) φ' ->\n    has_type Γ φ' Σ t T d.\n  intros Γ φ Σ t T d HT.\n  induction HT; intros; try solve [econstructor; eauto; try solve [eapply subqual_trans; eauto]].\nQed.\n\nLemma weaken : forall {φ Σ t T d},\n    has_type [] φ Σ t T d -> forall {Γ}, has_type Γ φ Σ t T d.\n  intros φ Σ t T d HT. induction Γ; auto.\n  specialize (@weaken_gen t [] Γ φ Σ T d) as Hsp. simpl in *.\n  specialize (Hsp IHΓ a).\n  apply has_type_closed in HT. intuition. simpl in *.\n  replace (splice (‖Γ‖) t) with t in Hsp.\n  replace (splice_ty (‖Γ‖) T) with T in Hsp.\n  replace (splice_qual (‖Γ‖) d) with d in Hsp.\n  replace (splice_qual (‖Γ‖) φ) with φ in Hsp. auto.\n  all : symmetry.\n  eapply splice_qual_id; eauto. eapply closed_qual_monotone; eauto; lia.\n  eapply splice_qual_id; eauto. eapply closed_qual_monotone; eauto; lia.\n  eapply splice_ty_id; eauto.   eapply closed_ty_monotone; eauto; lia.\n  eapply splice_id; eauto.      eapply closed_tm_monotone; eauto; lia.\nQed.\n\nLemma weaken' : forall {φ Σ t T d},\n    has_type [] φ Σ t T d -> forall {φ'}, φ ⊑ φ' -> forall {Γ}, closed_qual 0 (‖Γ‖) (‖Σ‖) φ' -> has_type Γ φ' Σ t T d.\n  intros. eapply weaken_flt; eauto. apply weaken. auto.\nQed.\n\nLemma weaken_store : forall {Γ φ Σ t T d}, has_type Γ φ Σ t T d -> forall {Σ'}, Σ' ⊇ Σ -> has_type Γ φ Σ' t T d.\n  intros Γ φ Σ t T d HT.\n  induction HT; intros; intuition; try solve [econstructor; eauto;\n    try solve [eapply closed_qual_monotone; eauto; apply extends_length; auto];\n    try solve [eapply closed_tm_monotone; eauto; apply extends_length; auto];\n    try solve [eapply closed_ty_monotone; eauto; apply extends_length; auto];\n    try solve [eapply weaken_store_saturated; eauto];\n    try solve [eapply weaken_store_senv_saturated; eauto]].\n  - econstructor; eauto. eapply closed_qual_monotone; eauto; apply extends_length; auto.\n    unfold extends in H6. destruct H6. rewrite H6.\n    rewrite indexr_skips. auto. eapply indexr_var_some'. eauto.\n    eapply closed_qual_monotone; eauto.\n  - econstructor; eauto. eapply weaken_stp_store_ext; eauto.\n    eapply weaken_store_senv_saturated; eauto.\nQed.\n\nLemma qstp_empty : forall {Σ q1 q2}, qstp [] Σ q1 q2 -> q1 ⊑ q2.\n  intros. remember [] as Γ. induction H; subst; auto.\n  simpl in H. discriminate.\n  simpl in H. discriminate.\n  intuition. eapply subqual_trans; eauto.\nQed.\n\nLemma narrowing_saturated : forall {Γ1 b U du Γ2 Σ q},\n    saturated (Γ1 ++ (b,U,du) :: Γ2) Σ q ->\n    forall {V dv}, stp [] Σ V dv U du -> saturated (Γ1 ++ (b,V,dv) :: Γ2) Σ q.\n  intros. inversion H. constructor; intros; auto. unfold tenv_saturated. intros.\n  apply H1 in H3. inversion H3. destruct (PeanoNat.Nat.lt_trichotomy x (‖Γ2‖)) as [Hlen | [Hlen | Hlen] ].\n  - apply (sat_var b0 U0 q'); auto. rewrite indexr_skips in H4; simpl; auto.\n    rewrite indexr_skips. rewrite indexr_skip in H4; try lia. rewrite indexr_skip; try lia.\n    auto. simpl. auto.\n  - rewrite indexr_skips in H4; simpl; auto. subst. rewrite indexr_head in H4. inversion H4. subst.\n    apply (sat_var b0 V dv). rewrite indexr_skips; auto. rewrite indexr_head. auto.\n    apply stp_qstp_inv in H0. apply qstp_empty in H0. eapply subqual_trans; eauto.\n    apply stp_closed in H0. intuition. eapply closed_qual_monotone; eauto. lia.\n  - destruct x. lia. rewrite <- indexr_insert_ge in H4; try lia.\n    apply (sat_var b0 U0 q'); auto. rewrite <- indexr_insert_ge; try lia. auto.\nQed.\n\nLemma narrowing_gen : forall {t Γ1 b U du Γ2 φ Σ T d},\n    has_type (Γ1 ++ (b,U,du) :: Γ2) φ Σ t T d -> (b = true -> (♦∈ du)) ->\n    forall {V dv}, stp [] Σ V dv U du -> has_type (Γ1 ++ (b,V,dv) :: Γ2) φ Σ t T d.\n  intros t Γ1 b U du Γ2 φ Σ T d HT Hb. remember (Γ1 ++ (b,U, du) :: Γ2) as Γ.\n  generalize dependent Γ1. generalize dependent U. generalize dependent du. generalize dependent Γ2.\n  induction HT; intros; subst.\n  - econstructor; eauto.\n    repeat rewrite app_length in *; simpl in *; auto.\n  - repeat rewrite app_length in *; simpl in *; auto.\n    destruct (PeanoNat.Nat.lt_trichotomy x (‖Γ2‖)) as [Hlen | [Hlen | Hlen] ].\n    * apply t_var with (b:=b0) (d:=d); auto. rewrite <- indexr_insert_lt; auto. rewrite <- indexr_insert_lt in H; auto.\n      repeat rewrite app_length in *; simpl in *; auto.\n    * subst. rewrite indexr_insert in H. inversion H. subst.\n      apply t_sub with (T1:=V) (d1:=$!‖Γ2‖); auto. apply t_var with (b:=b0) (d:=dv).\n      rewrite indexr_insert. auto. destruct φ. simpl. auto.\n      repeat rewrite app_length in *; simpl in *; auto.\n      1,2 : apply stp_closed in H4; intuition. eapply closed_ty_monotone; eauto. eapply closed_qual_monotone; eauto.\n      eapply stp_shrink_var; eauto. eapply weaken_stp'; eauto. eapply weaken_stp; eauto.\n      replace Γ2 with (Γ2 ++ []). eapply weaken_stp'; eauto. rewrite app_nil_r. auto. rewrite app_length. simpl. lia.\n    * apply t_var with (b:=b0) (d:=d); auto. destruct x. lia. rewrite <- indexr_insert_ge; try lia.\n      rewrite <- indexr_insert_ge in H; try lia. auto.\n      repeat rewrite app_length in *; simpl in *; auto.\n  - repeat rewrite app_length in *; simpl in *; auto.\n    constructor; auto. 1-3 : rewrite app_length in *; simpl in *; auto.\n    rewrite @open_tm'_len with (Γ' := (Γ1 ++ (b,U, du) :: Γ2)).\n    rewrite @open_ty'_len with (Γ' := (Γ1 ++ (b,U, du) :: Γ2)).\n    rewrite @openq'_len with (Γ' := (Γ1 ++ (b,U, du) :: Γ2)).\n    2-4 : repeat rewrite app_length; simpl; auto.\n    rewrite app_length. simpl.\n    rewrite app_comm_cons. rewrite app_comm_cons.\n    eapply IHHT; eauto. simpl. auto.\n  - econstructor; eauto.\n  - eapply t_app_fresh; eauto.\n    repeat rewrite app_length in *; simpl in *; auto.\n    all: eapply narrowing_saturated; eauto.\n  - econstructor; eauto.\n    repeat rewrite app_length in *; simpl in *; auto.\n  - econstructor; eauto.\n  - econstructor; eauto.\n  - econstructor; eauto.\n  - eapply t_sub; eauto. eapply narrowing_stp_gen; eauto.\n    replace (Γ2) with (Γ2 ++ []). eapply weaken_stp'; eauto. rewrite app_nil_r. auto.\nQed.\n\nLemma narrowing : forall {Γ b U du φ Σ t T d}, has_type ((b,U,du) :: Γ) φ Σ t T d -> (b = true -> (♦∈ du)) -> forall {V dv}, stp [] Σ V dv U du -> has_type ((b,V,dv) :: Γ) φ Σ t T d.\n  intros. specialize (@narrowing_gen t [] b U du Γ φ Σ T d) as narrow. simpl in *. eapply narrow; eauto.\nQed.\n\nLemma values_stuck : forall {v}, value v -> forall {t σ σ'}, step v σ t σ' -> False.\n  intros. inversion H0; subst; inversion H.\nQed.\n\nLemma CtxOK_ext : forall {Γ φ Σ σ}, CtxOK Γ φ Σ σ -> forall {v T q}, has_type Γ φ Σ v T q -> value v -> CtxOK Γ φ ((T,q) :: Σ) (v :: σ).\n  intros. unfold CtxOK in *. split. simpl. lia.\n  intros. destruct H as [Hlen Hprev]. destruct (Nat.eqb l (length σ)) eqn:Heql.\n  - simpl in *. rewrite Heql in *. inversion H3. subst.\n    rewrite <- Hlen in Heql. rewrite Heql in H2. inversion H2. subst. intuition.\n    eapply weaken_store; eauto.\n  - simpl in *. rewrite Heql in *. rewrite <- Hlen in Heql. rewrite Heql in H2.\n    specialize (Hprev _ _ _ _ H2 H3) as Hprev. intuition.\n    eapply weaken_store; eauto.\nQed.\n\nLemma CtxOK_update : forall {Γ φ Σ σ}, CtxOK Γ φ Σ σ -> forall {l T q}, l < ‖σ‖ -> indexr l Σ = Some (T,q) -> forall {v}, has_type Γ φ Σ v T q -> value v -> CtxOK Γ φ Σ (update σ l v).\n  intros. unfold CtxOK in *. destruct H as [Hlen Hprev].\n  split. rewrite <- update_length. auto.\n  intros. destruct (Nat.eqb l l0) eqn:Heq.\n  - apply Nat.eqb_eq in Heq. subst.\n    apply (@update_indexr_hit _ σ l0 v) in H0. rewrite H1 in H. inversion H. subst.\n    rewrite H4 in H0. inversion H0. subst. intuition.\n  - apply Nat.eqb_neq in Heq. apply (@update_indexr_miss _ σ l v l0) in Heq.\n    rewrite Heq in H4. eapply Hprev; eauto.\nQed.\n\nLemma CtxOK_empty : forall {Γ φ}, CtxOK Γ φ [] [].\n  intros. constructor; intuition; simpl in H; try discriminate.\nQed.\n#[global] Hint Resolve CtxOK_empty : core.\n\nLemma CtxOK_weaken_flt : forall {Γ φ Σ σ}, CtxOK Γ φ Σ σ -> forall {φ'}, closed_qual 0 (‖Γ‖) (‖Σ‖) φ' -> φ ⊑ φ' -> CtxOK Γ φ' Σ σ.\n  intros. inversion H. subst. constructor; intuition.\n  all : specialize (H3 _ _ _ _ H4 H5); intuition.\n  eapply weaken_flt; eauto.\nQed.\n\nLemma subst1_tenv_length : forall {v q Γ}, ‖ { v |-> q }ᴳ Γ ‖ = ‖Γ‖.\n  intros. unfold subst_tenv. rewrite map_length. auto.\nQed.\n\nLemma subst_tenv_length : forall {v q q' Γ}, ‖ { v |-> q ; q' }ᴳ Γ ‖ = ‖Γ‖.\n  intros. repeat rewrite subst1_tenv_length. auto.\nQed.\n\nLemma subst1_qual_id : forall {b l q}, closed_qual b 0 l q -> forall {q1}, { 0 |-> q1 }ᵈ q = q.\nProof.\n  intros. inversion H; subst; intros; intuition. simpl.\n  rewrite bound_le_mem_false. 2: lia.\n  erewrite unsplice_set_inv; eauto; apply bound_0_empty in H0; subst; rewrite remove_empty; auto.\nQed.\n\nLemma subst1_qual_empty : forall {dx}, {0 |-> dx }ᵈ ∅ = ∅.\n  intros. apply (@subst1_qual_id 0 0). auto.\nQed.\n#[global] Hint Resolve subst1_qual_empty : core.\n\nLemma subst1_qual_fresh : forall {dx}, {0 |-> dx }ᵈ {♦} = {♦}.\n  intros. apply (@subst1_qual_id 0 0). auto.\nQed.\n#[global] Hint Resolve subst1_qual_fresh : core.\n\nLemma subst1_ty_id : forall {T b l}, closed_ty b 0 l T -> forall {d1}, { 0 |-> d1 }ᵀ T = T.\n  induction T; intros; inversion H; subst; simpl; intuition.\n  erewrite IHT1; eauto. erewrite IHT2; eauto.\n  erewrite subst1_qual_id; eauto. erewrite subst1_qual_id; eauto.\n  erewrite IHT; eauto. erewrite subst1_qual_id; eauto.\nQed.\n\nLemma subst_ty_id : forall {b l T}, closed_ty b 0 l T -> forall {d1 d2}, { 0 |-> d1 ; d2 }ᵀ T = T.\n  intros. repeat erewrite subst1_ty_id; eauto.\nQed.\n\nLemma subst1_tm_id : forall {t b l}, closed_tm b 0 l t -> forall {t1}, { 0 |-> t1 }ᵗ t = t.\n  induction t; intros b loc Hc; inversion Hc; subst; intros; simpl; intuition;\n                       try solve [erewrite IHt; eauto];\n                       try solve [erewrite IHt1; eauto; erewrite IHt2; eauto].\nQed.\n\nLemma open_subst1_qual : forall {q b l},\n    closed_qual b 0 l q ->\n    forall {k d1},\n      [[k ~> d1 ]]ᵈ q = { 0 |-> d1 }ᵈ ([[k ~> $!0 ]]ᵈ q).\n  intros. inversion H; subst; intuition. simpl.\n  destruct d1.\n  rewrite empty_union_right. rewrite empty_union_right.\n  destruct (mem k bs) eqn: Hmem. simpl.\n  assert (mem 0 (union vs (singleton 0)) = true).\n  apply NatSet.F.mem_1. fnsetdec.\n  rewrite H3. f_equal. destr_bool. apply bound_0_empty in H0. rewrite H0.\n  rewrite empty_union_left. rewrite empty_union_left.\n  rewrite remove_singleton_empty. rewrite unsplice_set_empty.\n  rewrite empty_union_left. auto.\n  simpl. rewrite bound_le_mem_false; auto.\n  apply bound_0_empty in H0. subst.\n  rewrite unsplice_set_empty. auto.\nQed.\n\nLemma open_subst1_ty : forall {T b l},\n    closed_ty b 0 l T ->\n    forall {k d1},\n      [[k ~> d1 ]]ᵀ T = { 0 |-> d1 }ᵀ ([[k ~> $!0]]ᵀ T).\n  induction T; intros; inversion H; subst; simpl; intuition.\n  erewrite IHT1; eauto. erewrite IHT2; eauto.\n  erewrite <- open_subst1_qual; eauto. erewrite <- open_subst1_qual; eauto.\n  erewrite IHT; eauto. erewrite <- open_subst1_qual; eauto.\nQed.\n\nLemma open_subst1_tm : forall {t b l},\n    closed_tm b 0 l t -> forall {k t1},\n      [[k ~> t1 ]]ᵗ t = { 0 |-> t1 }ᵗ ([[k ~> $0]]ᵗ t).\n  induction t; intros b loc Hc; inversion Hc; subst; intros; simpl; intuition;\n    try solve [erewrite IHt; eauto];\n    try solve [erewrite IHt1; eauto; erewrite IHt2; eauto].\n  bdestruct (k =? x); simpl; intuition.\nQed.\n\nFixpoint open_subst1_tm_comm {t : tm} :\n  forall {k  g tf ff lf}, closed_tm 0 ff lf tf ->\n    [[k ~> $g ]]ᵗ ({0 |-> tf }ᵗ t) = {0 |-> tf }ᵗ ([[ k ~> $(S g) ]]ᵗ  t).\n    destruct t; intros; simpl; intuition;\n      try solve [repeat erewrite open_subst1_tm_comm; eauto].\n    destruct v; simpl.\n    bdestruct (i =? 0); simpl. eapply closed_tm_open_id; eauto. lia. auto.\n    bdestruct (k =? i); simpl; auto.\nQed.\n\nLemma open_subst1_qual_comm : forall {q : qual} {k g fr df ff lf},\n    closed_qual 0 ff lf df ->\n    [[k ~> ${fr}g ]]ᵈ ({0 |-> df }ᵈ q) = {0 |-> df }ᵈ ([[ k ~> ${fr}(S g) ]]ᵈ q).\n  intros. destruct q; simpl; intuition. destruct df.\n  inversion H. subst.\n  destruct (NatSet.F.mem 0 t) eqn: Hmem1.\n  - destruct (NatSet.F.mem k t0) eqn: Hmem2.\n    + simpl. rewrite NatSet.F.mem_1. rewrite NatSet.F.mem_1.\n      f_equal; try fnsetdec. destr_bool. rewrite remove_union_dist.\n      rewrite unsplice_set_union_dist.\n      rewrite remove_singleton_inv by lia.\n      unfold unsplice_set at 3. rewrite filter_singleton_1. rewrite dec_singleton.\n      rewrite filter_singleton_2. simpl. rewrite empty_union_right. fnsetdec.\n      apply Nat.ltb_ge. lia. apply leb_correct. lia.\n      apply bound_0_empty in H8. subst.\n      repeat rewrite empty_union_right. auto.\n      apply NatSet.F.union_2. apply NatSet.F.mem_2. auto.\n      apply NatSet.F.union_2. apply NatSet.F.mem_2. auto.\n    + simpl. apply bound_0_empty in H8. subst.\n      repeat rewrite empty_union_right.\n      rewrite Hmem2. rewrite Hmem1. auto.\n  - destruct (NatSet.F.mem k t0) eqn: Hmem2.\n    + simpl. rewrite Hmem2. rewrite not_member_union; auto.\n      f_equal. rewrite unsplice_set_union_dist. rewrite unsplice_set_singleton_dec; auto.\n      lia. rewrite mem_singleton. simpl. auto.\n    + simpl. rewrite Hmem1.  rewrite Hmem2. auto.\nQed.\n\nFixpoint open_subst1_ty_comm {T : ty} :\n  forall {k fr g df ff lf}, closed_qual 0 ff lf df ->\n    [[k ~> ${fr}g ]]ᵀ ({0 |-> df }ᵀ T) = {0 |-> df }ᵀ ([[ k ~> ${fr}(S g) ]]ᵀ  T).\n    destruct T; intros; simpl; intuition;\n      try solve [repeat erewrite open_subst1_ty_comm; eauto].\n    erewrite open_subst1_qual_comm; eauto. erewrite open_subst1_qual_comm; eauto.\n    erewrite open_subst1_ty_comm; eauto. erewrite open_subst1_ty_comm; eauto.\n    erewrite open_subst1_ty_comm; eauto. erewrite open_subst1_qual_comm; eauto.\nQed.\n\nLemma closed_qual_subst1 : forall {q b f l},\n    closed_qual b (S f) l q ->\n    forall {d1 l1}, closed_qual 0 0 l1 d1 ->\n    forall{l2},\n      l <= l2 -> l1 <= l2 ->\n      closed_qual b f l2 ({0 |-> d1}ᵈ q).\n  intros. inversion H; subst; intuition. inversion H0. subst.\n  simpl. destruct (mem 0 vs) eqn:Hmem.\n  constructor. apply bound_0_empty in H6. subst.\n  rewrite empty_union_right.\n  apply unsplice_set_dec. apply H3.\n  apply union_bound; lia.\n  apply union_bound; lia.\n  constructor; try lia. apply unsplice_set_bound. apply H3.\n  rewrite <- NatSetFacts.not_mem_iff in Hmem. auto.\nQed.\n\nLemma closed_ty_subst1 : forall {T b f l},\n    closed_ty b (S f) l T ->\n    forall {d1 l1}, closed_qual 0 0 l1 d1 ->\n    forall{l2},\n      l <= l2 -> l1 <= l2 ->\n      closed_ty b f l2 ({0 |-> d1}ᵀ T).\n  intros T b f l Hc. remember (S f) as f'. generalize dependent f.\n  induction Hc; intros; subst; simpl in *; intuition; try constructor;\n    try solve [eapply IHHc; eauto; lia ];\n    try solve [eapply IHHc1; eauto];\n    try solve [eapply IHHc2; eauto; lia].\n  erewrite subst1_ty_id; eauto.\n  all : eapply closed_qual_subst1; eauto.\nQed.\n\nLemma closed_tm_subst1 : forall {t b f l},\n    closed_tm b (S f) l t ->\n    forall {t1 l1}, closed_tm 0 0 l1 t1 ->\n    forall{l2},\n      l <= l2 -> l1 <= l2 ->\n      closed_tm b f l2 ({0 |-> t1}ᵗ t).\n  intros t b f l Hc. remember (S f) as f'.\n  generalize dependent f.\n  induction Hc; intros; subst; simpl in *; intuition; try constructor;\n    try solve [eapply IHHc; eauto; lia ];\n    try solve [eapply IHHc1; eauto];\n    try solve [eapply IHHc2; eauto].\n  bdestruct (x =? 0).\n  eapply closed_tm_monotone; eauto; lia. intuition.\nQed.\n\nLemma open_subst2_qual : forall {q l},\n    closed_qual 2 0 l q ->\n    forall {d1 df}, closed_qual 0 0 l d1 ->\n    [[1~> df ]]ᵈ ([[0~> d1 ]]ᵈ q) = { 0 |-> d1; df }ᵈ ([[1 ~> $!1]]ᵈ ([[0 ~> $!0]]ᵈ q)).\n  intros. erewrite <- open_subst1_qual_comm; eauto.\n  erewrite open_subst1_qual; eauto. f_equal. f_equal.\n  erewrite open_subst1_qual; eauto. erewrite open_subst1_qual; eauto.\n  eapply closed_qual_subst1; eauto. eapply closed_qual_open_succ; eauto.\nQed.\n\nLemma open_subst2_ty : forall {T l},\n    closed_ty 2 0 l T ->\n    forall {d1 df}, closed_qual 0 0 l d1 ->\n    [[1~> df ]]ᵀ ([[0~> d1 ]]ᵀ T) = { 0 |-> d1; df }ᵀ ([[1 ~> $!1]]ᵀ ([[0 ~> $!0]]ᵀ T)).\n  intros. erewrite <- open_subst1_ty_comm; eauto.\n  erewrite open_subst1_ty; eauto. f_equal. f_equal.\n  erewrite open_subst1_ty; eauto. erewrite open_subst1_ty; eauto.\n  eapply closed_ty_subst1; eauto. eapply closed_ty_open_succ; eauto.\nQed.\n\nLemma open_subst2_tm : forall {t l},\n    closed_tm 2 0 l t ->\n    forall {t1 tf}, closed_tm 0 0 l t1 ->\n    [[1~> tf ]]ᵗ ([[0~> t1 ]]ᵗ t) = { 0 |-> t1; tf }ᵗ ([[1 ~> $1 ]]ᵗ ([[0 ~> $0 ]]ᵗ t)).\n  intros. erewrite <- open_subst1_tm_comm; eauto.\n  erewrite open_subst1_tm; eauto. f_equal. f_equal.\n  erewrite open_subst1_tm; eauto. erewrite open_subst1_tm; eauto.\n  eapply closed_tm_subst1; eauto. eapply closed_tm_open_succ; eauto.\nQed.\n\nLemma subst1_qlub_dist : forall {q1 q2 df},\n    ({ 0 |-> df }ᵈ (q1 ⊔ q2)) = (({ 0 |-> df }ᵈ q1) ⊔ ({ 0 |-> df }ᵈ q2)).\n  intros. destruct q1; destruct q2; destruct df; simpl; auto.\n  destruct (mem 0 t) eqn: Hmem1.\n  - rewrite NatSet.F.mem_1.\n    destruct (mem 0 t2) eqn: Hmem2.\n    simpl. f_equal; try fnsetdec. destr_bool.\n    rewrite union_assoc. rewrite remove_union_dist.\n    rewrite unsplice_set_union_dist. rewrite union_assoc. f_equal.\n    fnsetdec.\n    simpl. f_equal; try fnsetdec. destr_bool.\n    rewrite remove_union_dist. rewrite unsplice_set_union_dist.\n    rewrite (remove_not_in Hmem2). fnsetdec.\n    apply NatSet.F.union_2. apply NatSet.F.mem_2. auto.\n  - destruct (mem 0 t2) eqn: Hmem2.\n    + simpl. rewrite NatSet.F.mem_1.\n      f_equal; try fnsetdec. destr_bool.\n      rewrite remove_union_dist.\n      rewrite unsplice_set_union_dist.\n      rewrite (remove_not_in Hmem1). fnsetdec.\n      apply NatSet.F.union_3. apply NatSet.F.mem_2. auto.\n    + simpl. rewrite not_member_union; auto.\n      f_equal; try fnsetdec.\n      rewrite <- unsplice_set_union_dist. auto.\nQed.\n\nLemma subst1_qual_plus : forall {l du},\n    closed_qual 0 0 l du -> du = {0 |-> du }ᵈ (du ⊔ $!0).\n  intros. destruct du; intuition.\n  inversion H. subst. apply bound_0_empty in H6. subst.\n  apply bound_0_empty in H8. subst.\n  simpl. rewrite empty_union_left. repeat rewrite empty_union_right.\n  rewrite NatSet.F.mem_1 by fnsetdec. f_equal; try fnsetdec. destr_bool.\n  rewrite remove_singleton_empty. rewrite unsplice_set_empty. auto.\nQed.\n\nLemma subst1_qual_plus' : forall {du du' l},\n    du' ⊑ du -> closed_qual 0 0 l du -> {0 |-> du }ᵈ (du' ⊔ $!0) = du.\n  intros. destruct du'; intuition. destruct du.\n  inversion H. intuition. inversion H0. subst.\n  apply bound_0_empty in H11, H13. subst.\n  simpl. rewrite NatSet.F.mem_1 by fnsetdec.\n  repeat rewrite empty_union_right.\n  assert (t = {}N) by fnsetdec. assert (t0 = {}N) by fnsetdec.\n  subst. repeat rewrite empty_union_left. f_equal. destr_bool.\n  rewrite remove_singleton_empty. rewrite unsplice_set_empty. auto.\n  fnsetdec.\nQed.\n\nLemma subst1_open_qual_comm : forall {k l d1 d2 q1},\n    closed_qual 0 0 l q1 ->\n    {0 |-> q1 }ᵈ ([[k ~> d1 ]]ᵈ d2) = [[k ~> {0 |-> q1 }ᵈ d1 ]]ᵈ ({0 |-> q1 }ᵈ d2).\nProof.\n  intros. destruct d2; simpl; auto. destruct d1; simpl. destruct q1; simpl.\n  inversion H. subst. apply bound_0_empty in H6. apply bound_0_empty in H8.\n  subst.\n  repeat rewrite empty_union_right.\n  destruct (mem k t0) eqn:Hmem1.\n  - simpl. destruct (mem 0 t2) eqn:Hmem2.\n    + rewrite NatSet.F.mem_1.\n      destruct (mem 0 t) eqn:Hmem3;\n      simpl; rewrite Hmem1; rewrite empty_union_right;\n        f_equal; try fnsetdec; try solve [destr_bool]; rewrite <- unsplice_set_union_dist;\n          try rewrite <- remove_union_dist; auto. rewrite remove_union_dist. rewrite (remove_not_in Hmem3). auto.\n      apply NatSet.F.union_3. apply NatSet.F.mem_2. auto.\n    + destruct (mem 0 t) eqn:Hmem3.\n      * rewrite NatSet.F.mem_1.\n        simpl. rewrite Hmem1. rewrite empty_union_right.\n        f_equal; try fnsetdec. destr_bool.\n        rewrite <- unsplice_set_union_dist. rewrite remove_union_dist. rewrite (remove_not_in Hmem2). auto.\n        apply NatSet.F.union_2. apply NatSet.F.mem_2. auto.\n      * rewrite not_member_union; auto. simpl. rewrite Hmem1.\n        f_equal.\n        rewrite <- unsplice_set_union_dist. auto.\n  - simpl. destruct (mem 0 t) eqn: Hmem2.\n    + destruct (mem 0 t2) eqn: Hmem3; simpl;\n        rewrite Hmem1; repeat rewrite empty_union_right; auto.\n    + destruct (mem 0 t2) eqn: Hmem3; simpl; rewrite Hmem1; auto.\nQed.\n\nLemma subst1_open_ty_comm : forall {T k l d1 q1},\n    closed_qual 0 0 l q1 ->\n    {0 |-> q1 }ᵀ ([[k ~> d1 ]]ᵀ T) = [[k ~> {0 |-> q1 }ᵈ d1 ]]ᵀ ({0 |-> q1 }ᵀ T).\n  induction T; intros; intuition.\n  - simpl. erewrite IHT1; eauto. erewrite IHT2; eauto. repeat erewrite subst1_open_qual_comm; eauto.\n  - simpl. erewrite IHT; eauto. repeat erewrite subst1_open_qual_comm; eauto.\nQed.\n\nLemma indexr_subst1 : forall {x Γ b T U d dx},\n    x >= 1 ->\n    indexr x (Γ ++ [U]) = Some (b, T, d) ->\n    indexr (pred x) ({ 0 |-> dx }ᴳ Γ) = Some (b, { 0 |-> dx }ᵀ T, { 0 |-> dx }ᵈ d).\n  intros. destruct x; try lia.\n  rewrite <- indexr_insert_ge in H0; simpl; try lia.\n  rewrite app_nil_r in H0. induction Γ; intros; simpl in *. discriminate.\n  rewrite subst1_tenv_length. (bdestruct (x =? ‖Γ‖)); auto.\n  inversion H0. auto.\nQed.\n\nLemma subst_qual_subqual_monotone : forall {d1 d2}, d1 ⊑ d2 -> forall {df}, ({0 |-> df }ᵈ d1) ⊑ ({0 |-> df }ᵈ d2).\nProof.\n  intros. destruct d1; destruct d2; destruct df; simpl; intuition.\n  inversion H. intuition.\n  destruct (mem 0 t) eqn: Hmem1; destruct (mem 0 t2) eqn: Hmem2;\n    simpl; intuition; try fnsetdec. 1,3,7 : destr_bool.\n  - apply NatSet.F.mem_2 in Hmem1. rewrite <- NatSetFacts.not_mem_iff in Hmem2. fnsetdec.\n  - apply NatSetProperties.union_subset_4.\n    apply unsplice_set_subset_monotone. auto.\n  - specialize (@subset_inclusion _ _ _ H2 Hmem1 Hmem2) as F. inversion F.\n  - specialize (@subset_inclusion _ _ _ H2 Hmem1 Hmem2) as F. inversion F.\n  - specialize (@subset_inclusion _ _ _ H2 Hmem1 Hmem2) as F. inversion F.\n  - specialize (@NatSetProperties.union_subset_1 (unsplice_set 0 (remove 0 t2)) t5) as Hs.\n    specialize (@unsplice_set_subset_monotone t t2 H2) as Hs2.\n    rewrite (remove_not_in Hmem1) in Hs2. fnsetdec.\n  - rewrite <- (remove_not_in Hmem1). rewrite <- (remove_not_in Hmem2).\n    apply unsplice_set_subset_monotone. auto.\nQed.\n\nLemma subst1_just_fv : forall {fr x dy},\n    ${fr}x = {0 |-> dy }ᵈ ${fr}(S x).\n  intros. simpl. rewrite mem_singleton. simpl.\n  rewrite unsplice_set_singleton. auto.\nQed.\n\nLemma closed_qual_subst1' : forall {Γ0 X l df φ b},\n    closed_qual 0 0 l df ->\n    closed_qual b (‖ Γ0 ++ [X] ‖) l φ ->\n    closed_qual b (‖ {0 |-> df }ᴳ Γ0 ‖) l ({0 |-> df }ᵈ φ).\n  intros. repeat eapply closed_qual_subst1; eauto. rewrite subst1_tenv_length.\n  rewrite app_length in *. simpl in *. replace (‖Γ0‖ + 1) with (S (‖Γ0‖)) in H0.\n  auto. lia.\nQed.\n\nLemma closed_tm_subst1' : forall {Γ0 X l df tx t b},\n    closed_tm 0 0 l tx ->\n    closed_tm b (‖ Γ0 ++ [X] ‖) l t ->\n    closed_tm b (‖ {0 |-> df }ᴳ Γ0 ‖) l ({0 |-> tx }ᵗ t).\n  intros. repeat eapply closed_tm_subst1; eauto. rewrite subst1_tenv_length.\n  rewrite app_length in *. simpl in *. replace (‖Γ0‖ + 1) with (S (‖Γ0‖)) in H0.\n  auto. lia.\nQed.\n\nLemma closed_ty_subst1' : forall {Γ0 X l df T b},\n    closed_qual 0 0 l df ->\n    closed_ty b (‖ Γ0 ++ [X] ‖) l T ->\n    closed_ty b (‖ {0 |-> df }ᴳ Γ0 ‖) l ({0 |-> df }ᵀ T).\n  intros. repeat eapply closed_ty_subst1; eauto. rewrite subst1_tenv_length.\n  rewrite app_length in *. simpl in *. replace (‖Γ0‖ + 1) with (S (‖Γ0‖)) in H0.\n  auto. lia.\nQed.\n\nLemma subst_filter0 : forall {d φ l fr}, closed_qual 0 0 l d -> ${fr}0 ⊑ φ -> d ⊑ { 0 |-> d }ᵈ φ.\n  intros. destruct d; simpl in *. destruct φ. intuition. simpl.\n  inversion H. subst. rewrite NatSet.F.mem_1. intuition. destr_bool.\n  eapply NatSetProperties.in_subset; eauto. fnsetdec.\nQed.\n\nLemma subst1_qual_0 : forall {q' q}, q' ⊑ q -> forall {df}, $0 ∈ᵥ df -> q' ⊑ { 0 |-> q }ᵈ df.\n  intros. destruct df; simpl in *. destruct q. intuition. simpl.\n  apply NatSet.F.mem_1 in H0. rewrite H0. destruct q'. qdec.\nQed.\n\nLemma subst1_qual_0' : forall {q' q}, q' ⊑ q ⊔ {♦} -> forall {df}, $0 ∈ᵥ df -> q' ⊑ { 0 |-> q }ᵈ df ⊔ {♦}.\n  intros. destruct df; simpl in *. destruct q. intuition. simpl.\n  apply NatSet.F.mem_1 in H0. rewrite H0. destruct q'. qdec.\nQed.\n\nLemma subst1_just_fv0_gen : forall {q fr}, {0 |-> q }ᵈ ${fr}0 = (q ⊔ ∅{ fr }).\n  intros. simpl. destruct q; intuition. repeat rewrite empty_union_left.\n  rewrite NatSet.F.mem_1 by fnsetdec. rewrite remove_singleton_empty.\n  rewrite unsplice_set_empty. qdec.\nQed.\n\nLemma subst1_just_fv0 : forall {q}, {0 |-> q }ᵈ $!0 = q.\n  intros. rewrite (@subst1_just_fv0_gen q false). auto.\nQed.\n\nLemma saturated0 : forall {Γ Σ Tx frx fx bx lx fr ff bf lf},\n    mem 0 ff = true -> saturated (Γ ++ [(Tx, qset frx fx bx lx)]) Σ (qset fr ff bf lf) -> implb frx fr = true /\\ fx [<=] ff /\\ bx [<=] bf /\\ lx [<=] lf.\n  intros. inversion H0. specialize (H1 0). simpl in H1. apply NatSet.F.mem_2 in H.\n  apply H0 in H. inversion H. rewrite indexr_skips in H3; auto. simpl in H3.\n  inversion H3. subst. simpl in H4. intuition.\nQed.\n\nLemma subst1_preserves_separation : forall {df d1 sx Tx dx dx' Γ Σ φ},\n    dx' ⊓ φ ⊑ dx ->\n    closed_qual 0 0 (‖Σ‖) dx' ->\n    df ⊑ φ -> d1 ⊑ φ ->\n    saturated (Γ ++ [(sx, Tx, dx)]) Σ d1 ->\n    saturated (Γ ++ [(sx, Tx, dx)]) Σ df ->\n    {0 |-> dx' }ᵈ df ⊓ {0 |-> dx' }ᵈ d1 = {0 |-> dx' }ᵈ (df ⊓ d1).\n  intros. destruct df as [frf ff bf lf]. destruct d1 as [fr1 f1 b1 l1]. destruct dx' as [frx' fx' bx' lx'].\n  destruct φ as [frp fp bp lp]. inversion H0. subst. apply bound_0_empty in H11, H13. (* simpl in H5. *) subst.\n  destruct dx as [frx fx bx lx]. simpl in H. intuition. rewrite inter_empty_left in H6.\n  rewrite inter_empty_left in H.\n  destruct (mem 0 ff) eqn:Hmem0ff; destruct (mem 0 f1) eqn:Hmem0f1; simpl; rewrite NatSetFacts.inter_b;\n    rewrite Hmem0ff; rewrite Hmem0f1; simpl.\n  - (*0 ∈ df, 0 ∈ d1 : this is trivial since we substitute the first variable for a closed value. The case for general\n      substitution would require more careful reasoning. *)\n    f_equal; try fnsetdec. destr_bool. repeat rewrite empty_union_right.\n    apply NatSet.eq_if_Equal. apply inter_unsplice_0.\n  - (* 0 ∈ df, 0 ∉ d1 *)\n    (* the interesting bit is reasoning about the overlap, this requires the extra assumptions about\n       saturation of the sets and the boundedness of the context, which imply Hlx: *)\n    specialize (saturated0 Hmem0ff H4) as Hlx.\n    f_equal; try fnsetdec.\n    (* case frf = false, requires saturation/Hlx above: *)\n    destruct frf; simpl; auto. intuition. destr_bool; intuition.\n    repeat rewrite empty_union_right.\n    replace (inter ff f1) with (remove 0 (inter ff f1)).\n    rewrite <- (remove_not_in Hmem0f1) at 1.\n    apply NatSet.eq_if_Equal. apply inter_unsplice_0. apply NatSet.F.mem_2 in Hmem0ff.\n    rewrite <- NatSetFacts.not_mem_iff in Hmem0f1. fnsetdec.\n    apply NatSet.eq_if_Equal.\n    setoid_rewrite NatSetProperties.union_inter_1.\n    assert (Hl1 : inter lx' l1 [<=] lx). { simpl in H2. intuition. fnsetdec. }\n    fnsetdec.\n  - (* 0 ∉ df, 0 ∈ d1, analogous to the previous case *)\n    specialize (saturated0 Hmem0f1 H3) as Hlx.\n    f_equal; try fnsetdec.\n    (* case fr1 = false, requires saturation/Hlx above: *)\n    destruct fr1; simpl; auto. intuition. destr_bool; intuition.\n    repeat rewrite empty_union_right.\n    replace (inter ff f1) with (remove 0 (inter ff f1)).\n    rewrite <- (remove_not_in Hmem0ff) at 1.\n    apply NatSet.eq_if_Equal. apply inter_unsplice_0. apply NatSet.F.mem_2 in Hmem0f1.\n    rewrite <- NatSetFacts.not_mem_iff in Hmem0ff. fnsetdec.\n    apply NatSet.eq_if_Equal. rewrite NatSetProperties.inter_sym.\n    setoid_rewrite NatSetProperties.union_inter_1.\n    assert (Hl1 : inter lx' lf [<=] lx). { simpl in H1. intuition. fnsetdec. }\n    fnsetdec.\n  - (* 0 ∉ df, 0 ∉ d1 : trivial, since the substitution has no effect (other than unsplicing the sets) *)\n    f_equal; try fnsetdec. apply NatSet.eq_if_Equal. replace (inter ff f1) with (remove 0 (inter ff f1)).\n    rewrite <- (remove_not_in Hmem0f1) at 1. rewrite <- (remove_not_in Hmem0ff) at 1. apply inter_unsplice_0.\n    rewrite <- NatSetFacts.not_mem_iff in Hmem0f1, Hmem0ff. fnsetdec.\nQed.\n\nLemma subst1_mem : forall {x dx df l}, closed_qual 0 0 l dx -> $x ∈ᵥ {0 |-> dx }ᵈ df -> $(S x) ∈ᵥ df.\n  intros. inversion H. subst. apply bound_0_empty in H1, H2. subst. destruct df. simpl in *.\n  destruct (mem 0 t) eqn:Hmem0t0; simpl in H0;\n    unfold unsplice_set in H0; rewrite filter_lt_0 in H0; rewrite filter_ge0_id in H0;\n    repeat rewrite empty_union_right in H0.\n  * destruct x. rewrite dec_in0 in H0. fnsetdec. fnsetdec.\n    change (S x) with (pred (S (S x))) in H0. rewrite <- dec_in_iff in H0. fnsetdec. lia.\n  * destruct x. rewrite dec_in0 in H0. fnsetdec. rewrite <- NatSetFacts.not_mem_iff in Hmem0t0. auto.\n    change (S x) with (pred (S (S x))) in H0. rewrite <- dec_in_iff in H0. fnsetdec. lia.\nQed.\n\nLemma subst1_mem_loc : forall {dx df l}, l ∈ₗ {0 |-> dx }ᵈ df ->  (l ∈ₗ dx /\\ $0 ∈ᵥ df) \\/ l ∈ₗ df.\n  intros. destruct dx. destruct df. simpl in *. destruct (mem 0 t2) eqn:Hmem; simpl in *; intuition.\n  apply NatSet.F.mem_2 in Hmem. fnsetdec.\nQed.\n\nLemma subst1_senv_saturated : forall {Σ df dx'},\n    senv_saturated Σ df ->\n    closed_qual 0 0 (‖Σ‖) dx' -> senv_saturated Σ dx' ->\n    senv_saturated Σ ({0 |-> dx' }ᵈ df).\n  intros. inversion H0. subst. apply bound_0_empty in H2, H3. subst.\n  unfold senv_saturated in *. intros. apply subst1_mem_loc in H2. intuition.\n  - apply H1 in H2. inversion H2. econstructor; eauto. apply subst1_qual_0'; auto.\n  - apply H in H3. inversion H3. econstructor; eauto. inversion H6. subst.\n    apply bound_0_empty in H7, H8. subst. destruct df. simpl. destruct (mem 0 t); qdec.\nQed.\n\nLemma subst1_saturated : forall {Γ Σ bx Tx dx df dx'},\n    saturated (Γ ++ [(bx, Tx, dx)]) Σ df ->\n    closed_qual 0 0 (‖Σ‖) dx' -> senv_saturated Σ dx' ->\n    saturated ({0 |-> dx' }ᴳ Γ) Σ ({0 |-> dx' }ᵈ df).\n  intros. inversion H0. subst. apply bound_0_empty in H2, H3.\n  subst. inversion H. constructor; intros. unfold tenv_saturated. intros.\n  - eapply subst1_mem in H5; eauto.\n    apply H2 in H5. inversion H5. apply @indexr_subst1 with (dx:=(qset fresh {}N {}N ls)) in H6.\n    simpl in H6. econstructor. eauto. apply subst_qual_subqual_monotone. auto.\n    eapply closed_qual_subst1; eauto. lia.\n  - apply subst1_senv_saturated; auto.\nQed.\n\nLemma qglb_increase_fresh : forall {dx dx' φ' l X},\n  dx' ⊓ φ' ≡ dx ->\n  closed_qual 0 0 l dx' ->\n  dx' ⊓ (φ' ⊔ qset false X {}N {}N) ≡ dx.\n  intros. destruct dx' as [frx' fx' bx' lx'].\n  inversion H0. subst. apply bound_0_empty in H7, H9.\n  subst. destruct dx as [frx fx bx lx]. destruct φ' as [frp' fp' bp' lp']. qdec.\nQed.\n\nLemma qglb_disjoint_freshv : forall {dx' l x},\n  closed_qual 0 0 l dx' -> dx' ⊓ $!x = ∅.\n  intros. destruct dx' as [frx' fx' bx' lx'].\n  inversion H. subst. apply bound_0_empty in H6, H8.\n  subst. qdec.\nQed.\n\nLemma qglb_disjoint_fresh : forall {dx' l},\n  closed_qual 0 0 l dx' -> dx' ⊓ {♦} = ∅{ ♦∈? dx' }.\n  intros. destruct dx' as [frx' fx' bx' lx'].\n  inversion H. subst. apply bound_0_empty in H6, H8.\n  subst. qdec.\nQed.\n\nLemma qmem_plus_decomp : forall {x0 q x}, x0 ∈ₗ q ⊔ &!x -> closed_qual 0 0 x q -> x0 ∈ₗ q \\/ x0 = x.\n  intros. inversion H0. subst. simpl in *. apply NatSet.F.union_1 in H. intuition.\n  right. rewrite NatSetFacts.singleton_iff in H4. auto.\nQed.\n\nLemma senv_saturated_qplus : forall {Σ l T q}, indexr l Σ = Some (T, q) -> closed_qual 0 0 l q -> senv_saturated Σ q -> senv_saturated Σ (q ⊔ &!l).\n  unfold senv_saturated. intros. specialize (qmem_plus_decomp H2 H0) as Hl. destruct Hl.\n  - apply H1 in H3. inversion H3. subst. econstructor; eauto. eapply subqual_trans; eauto.\n  - subst. econstructor; eauto. rewrite <- qlub_assoc. auto.\nQed.\n\nLemma wf_senv_saturated_qplus : forall {Σ}, wf_senv Σ -> forall {l T q}, indexr l Σ = Some (T, q) -> senv_saturated Σ (q ⊔ &!l).\n  intros. specialize (wf_senv_prop H l T q) as Hwf. intuition. eapply senv_saturated_qplus; eauto.\nQed.\n\nLemma has_type_senv_saturated : forall {Γ φ Σ t T q}, has_type Γ φ Σ t T q -> wf_senv Σ -> senv_saturated Σ q.\n  intros. induction H; eauto.\n  - intuition. apply has_type_closed in H, H1. intuition. eapply senv_saturated_openq; eauto.\n  - intuition. apply has_type_closed in H, H3. intuition. eapply senv_saturated_openq; eauto.\n  - eapply wf_senv_saturated_qplus; eauto.\nQed.\n\nLemma vtp_closed:\n  forall {Σ t T d}, vtp Σ t T d ->\n    closed_tm 0 0 (‖Σ‖) t /\\\n    closed_ty 0 0 (‖Σ‖) T /\\\n    closed_qual 0 0 (‖Σ‖) d .\nProof.\n  intros. induction H; intuition.\n  + constructor. apply indexr_var_some' in H2; intuition.\n  + constructor. apply stp_closed in H3. intuition. auto.\nQed.\n\nLemma vtp_widening: forall {Σ T1 d1 T2 d2 t},\n  vtp Σ t T1 d1 -> stp [] Σ T1 d1 T2 d2 -> senv_saturated Σ d2 -> vtp Σ t T2 d2.\nProof. intros. inversion H; subst.\n  - inversion H0; subst. constructor; auto. apply qstp_closed in H4. intuition.\n  - inversion H0; subst. eapply vtp_loc; eauto. apply qstp_closed in H13. intuition.\n    all : eapply s_trans; eauto.\n  - inversion H0; subst. econstructor. 5: eapply H6. all : eauto.\n    apply qstp_closed in H24. intuition.\n    eapply s_trans; eauto.\n    assert (stp [(false, T7, d8); (true, TFun d0 d3 T0 T3, {♦})] Σ (T3 <~²ᵀ ([]: tenv)) (d3 <~²ᵈ ([]: tenv)) (T5 <~²ᵀ ([]: tenv)) (d5 <~²ᵈ ([]: tenv))). {\n      eapply narrowing_stp; eauto. intuition. apply weaken_stp. auto.\n    }\n    assert (stp [] Σ (TFun d0 d3 T0 T3) {♦} (TFun d4 d5 T4 T5) {♦}). { eauto. }\n    assert (stp [(false, T7, d8); (true, TFun d0 d3 T0 T3, {♦})] Σ (T5 <~²ᵀ ([]: tenv)) (d5 <~²ᵈ ([]: tenv)) (T8 <~²ᵀ ([]: tenv)) (d9 <~²ᵈ ([]: tenv))). {\n      replace ([(false, T7, d8); (true, TFun d0 d3 T0 T3, {♦})]) with ([(false, T7, d8)] ++ [(true, TFun d0 d3 T0 T3, {♦})]); auto.\n      eapply narrowing_stp_gen. 3 : eapply H14. auto. intuition.\n    }\n    eapply s_trans; eauto.\nQed.\n\nLemma has_type_vtp: forall {Σ φ t T d},\n  value t ->\n  has_type [] φ Σ t T d ->\n  wf_senv Σ ->\n  vtp Σ t T d.\nProof. intros. remember [] as Γ. induction H0; eauto; subst; try solve [inversion H].\n  - (* tabs *) eapply vtp_abs; eauto.\n    * eapply stp_refl. inversion H2. subst. intuition.\n      apply qstp_refl; auto. inversion H2; subst. auto.\n    * apply stp_refl. inversion H2. subst.\n      + simpl in *. unfold open_ty'. unfold open_ty. simpl in *.\n        eapply closed_ty_open2; eauto. eapply closed_ty_monotone; eauto.\n        all: eapply just_fv_closed; eauto.\n      + apply qstp_refl; auto. apply has_type_closed in H7; intuition.\n  - (* tloc *) eapply vtp_loc; eauto.\n     * subst. apply closed_qual_qlub; auto. eapply closed_qual_sub. eapply H0. auto.\n     * apply stp_refl; auto.\n     * apply stp_refl; auto.\n     * eapply wf_senv_saturated_qplus; eauto.\n  - (* tsub *)\n     intuition. eapply vtp_widening; eauto.\nQed.\n\nLemma vtp_has_type: forall {Σ t T d}, vtp Σ t T d -> has_type [] d Σ t T d.\n  intros. inversion H; subst.\n  + econstructor; eauto.\n  + apply t_sub with (T1:=TRef q T0) (d1:=(q ⊔ &!l)); auto.\n    eapply t_loc; eauto. all :  apply qstp_empty in H6.\n    all : eapply subqual_trans. 2,4 : eapply H6. all : auto.\n  + specialize (qstp_closed H6) as Hcl. intuition.\n    assert (has_type [] df1 Σ (tabs t0) (TFun d1 d2 T1 T2) df1). {\n    constructor; eauto. }\n    eapply weaken_flt with (φ' := d) in H13; eauto.\n    apply qstp_empty in H6. auto.\nQed.\n\nLemma vtp_saturated: forall {Σ t T d}, vtp Σ t T d -> saturated [] Σ d.\n  intros. inversion H; subst; constructor; auto.\nQed.\n\nLemma subst1_fresh_id : forall {x dx'}, {x |-> dx' }ᵈ {♦} = {♦}.\n  intros. simpl. rewrite mem_empty. rewrite unsplice_set_empty. auto.\nQed.\n\nLemma Substq_non_fresh : forall {dx dx'}, Substq dx dx' -> ♦∉ dx'.\n  intros. inversion H; auto.\nQed.\n#[global] Hint Resolve Substq_non_fresh : core.\n\nLemma subst1_non_fresh : forall {x qx q}, ♦∉ q -> ♦∉ qx -> ♦∉ ({ x |-> qx }ᵈ q).\n  intros. destruct q. destruct qx. simpl in *. subst.\n  destruct (mem x t); auto.\nQed.\n#[global] Hint Resolve subst1_non_fresh : core.\n\nLemma subst1_fresh : forall {x qx q}, ♦∈ q -> ♦∈ ({ x |-> qx }ᵈ q).\n  intros. destruct q. destruct qx. simpl in *. subst.\n  destruct (mem x t); auto.\nQed.\n#[global] Hint Resolve subst1_fresh : core.\n\nLemma un_subst1_fresh : forall {x qx q}, ♦∉ qx -> ♦∈ ({ x |-> qx }ᵈ q) -> ♦∈ q.\n  intros. destruct q. destruct qx. simpl in *.\n  destruct (mem x t); auto. simpl in H0. destr_bool.\nQed.\n#[global] Hint Resolve un_subst1_fresh : core.\n\nLemma subst_qstp :  forall {Γ b Tf df df' Σ d1 d2},\n    qstp (Γ ++ [(b, Tf, df)]) Σ d1 d2 ->\n    closed_qual 0 0 (‖Σ‖) df' ->\n    Substq df df' ->\n    qstp ({0 |-> df' }ᴳ Γ) Σ ({0 |-> df' }ᵈ d1) ({0 |-> df' }ᵈ d2).\n  intros Γ b Tf df df' Σ d1 d2 H. remember (Γ ++ [(b, Tf, df)]) as Γ'.\n  generalize dependent Γ. generalize dependent df.  generalize dependent Tf.\n  induction H; intros; subst.\n  - apply qs_sq. apply subst_qual_subqual_monotone. auto. eapply closed_qual_subst1'; eauto.\n  -  bdestruct (f =? 0).\n    * pose (H' := H). subst. rewrite indexr_skips in H'; auto. simpl in H'. inversion H'. subst.\n      rewrite subst1_qlub_dist. rewrite subst1_just_fv0. erewrite subst1_qual_id; eauto. inversion H3; subst.\n      + rewrite qlub_idem. apply qs_sq; auto. rewrite subst1_tenv_length. eapply closed_qual_monotone; eauto. lia.\n      + apply not_fresh_fresh_false in H1. contradiction.\n    * rewrite subst1_qlub_dist. destruct f. lia. rewrite <- subst1_just_fv.\n      eapply qs_self; eauto. eapply @indexr_subst1 with (dx:=df') in H; try lia. eauto.\n      eapply closed_qual_subst1; eauto.\n  - bdestruct (x =? 0).\n    * subst. pose (H' := H). subst. rewrite indexr_skips in H'; auto. simpl in H'. inversion H'. subst.\n      rewrite subst1_just_fv0. erewrite subst1_qual_id; eauto. inversion H4; subst.\n      + apply qs_sq. auto. rewrite subst1_tenv_length. eapply closed_qual_monotone; eauto. lia.\n      + apply not_fresh_fresh_false in H2. contradiction.\n    * destruct x. lia. rewrite <- subst1_just_fv. eapply qs_qvar. apply @indexr_subst1 with (dx:=df') in H; try lia.\n      eauto. eapply closed_ty_subst1; eauto. eapply closed_qual_subst1; eauto. eauto.\n  - repeat rewrite subst1_qlub_dist. eapply qs_cong; eauto. eapply closed_qual_subst1'; eauto.\n  - eapply qs_trans. eapply IHqstp1; eauto. eauto.\n    Unshelve. all : auto.\nQed.\n\nLemma subst_stp : forall{T1 T2},\n    forall {Γ b Tf df df' Σ d1 d2},\n      stp (Γ ++ [(b,Tf,df)]) Σ T1 d1 T2 d2 ->\n      closed_qual 0 0 (‖Σ‖) df' ->\n      Substq df df' ->\n      stp ({ 0 |-> df' }ᴳ Γ) Σ\n          ({ 0 |-> df' }ᵀ T1) ({ 0 |-> df' }ᵈ d1)\n          ({ 0 |-> df' }ᵀ T2) ({ 0 |-> df' }ᵈ d2).\n  intros T1 T2 Γ b Tf df df' Σ d1 d2 HS.\n  remember (Γ ++ [(b, Tf, df)]) as Γ'.\n  generalize dependent Γ. generalize dependent df.  generalize dependent Tf. induction HS; intros; subst.\n  - simpl. constructor. eapply subst_qstp; eauto.\n  - specialize (stp_closed HS1). intuition. specialize (stp_closed HS2). intuition.\n    simpl. constructor. eapply subst_qstp; eauto.\n    all : repeat erewrite subst1_ty_id; eauto. eapply closed_qual_subst1'; eauto.\n  - simpl. constructor. inversion H. subst. 2 : inversion H0. subst.\n    1,2: constructor; try eapply closed_ty_subst1'; eauto; eapply closed_qual_subst1'; eauto.\n    eapply subst_qstp; eauto. eapply IHHS1; eauto.\n    unfold open_ty' in *. unfold open_ty in *.\n    unfold openq' in *. unfold openq in *.\n    rewrite app_length in *. rewrite subst1_tenv_length. simpl in *.\n    replace (‖Γ0‖ + 1) with (S (‖Γ0‖)) in *; try lia.\n    specialize (IHHS2 Tf df ((false, T3, d3) :: (true, TFun d1 d2 T1 T2, {♦}) :: Γ0)). intuition. rename H4 into IHHS2. simpl in IHHS2.\n    rewrite mem_empty in IHHS2. rewrite unsplice_set_empty in IHHS2.\n    erewrite <- open_subst1_ty_comm in IHHS2; eauto. erewrite <- open_subst1_ty_comm in IHHS2; eauto.\n    erewrite <- open_subst1_ty_comm in IHHS2; eauto. erewrite <- open_subst1_ty_comm in IHHS2; eauto.\n    erewrite <- open_subst1_qual_comm in IHHS2; eauto. erewrite <- open_subst1_qual_comm in IHHS2; eauto.\n    erewrite <- open_subst1_qual_comm in IHHS2; eauto. erewrite <- open_subst1_qual_comm in IHHS2; eauto.\n  (* - eapply s_trans. eapply IHHS1; eauto. eapply IHHS2; eauto. *)\nQed.\n\nLemma un_subst1_qual_open : forall {v dx q l}, closed_qual 0 0 l dx -> {0 |-> dx }ᵈ ([[v ~> ∅ ]]ᵈ q) = {0 |-> dx }ᵈ q -> [[v ~> ∅ ]]ᵈ q = q.\n  intros. destruct q. inversion H. subst. apply bound_0_empty in H1, H2. subst. simpl in *.\n  repeat rewrite empty_union_right in *.\n  destruct (mem v t0) eqn:Hmemvt0; auto. destruct (mem 0 t) eqn:Hmem0t; auto; simpl in *.\n  repeat rewrite empty_union_right in *. rewrite Hmem0t in H0. inversion H0. repeat rewrite H4. qdec.\n  rewrite Hmem0t in H0. inversion H0. repeat rewrite H4. qdec.\nQed.\n\nLemma not_free_subst1_ty_iff : forall {v dx T l}, closed_qual 0 0 l dx -> not_free v T <-> not_free v ({0 |-> dx }ᵀ T).\n  intros. unfold not_free. intuition.\n  - replace (∅) with ({0 |-> dx }ᵈ ∅); auto. erewrite <- subst1_open_ty_comm; eauto. rewrite H0. auto.\n  - replace (∅) with ({0 |-> dx }ᵈ ∅) in H0; auto. erewrite <- subst1_open_ty_comm in H0; eauto.\n    generalize dependent v. induction T; intros; simpl; intuition;\n    simpl in H0; inversion H0; f_equal; intuition; eapply un_subst1_qual_open; eauto.\nQed.\n\nLemma substitution_gen :\n  forall {t Γ φ bx Tx dx dx' Σ T d}, dx' ⊓ φ ⊑ dx ->\n      has_type (Γ ++ [(bx,Tx,dx)]) φ Σ t T d -> Substq dx dx' ->\n        forall {tx}, vtp Σ tx Tx dx' ->\n                        has_type ({ 0 |-> dx' }ᴳ Γ) ({ 0 |-> dx' }ᵈ φ) Σ\n                                 ({ 0 |-> tx  }ᵗ t)\n                                 ({ 0 |-> dx' }ᵀ T)\n                                 ({ 0 |-> dx' }ᵈ d).\n  intros t Γ φ bx Tx dx dx' Σ T d Hsep (* φ Hphi *) HT HSubst tx HTx. specialize (vtp_closed HTx) as Hclx.\n  specialize (vtp_saturated HTx) as Hsatx. destruct Hsatx as [Htsatx Hssatx].\n  simpl in Hclx. intuition. remember (Γ ++ [(bx,Tx, dx)]) as Γ'.\n  generalize dependent Γ.\n  induction HT; intros; subst; pose (φs := {0 |-> dx' }ᵈ φ); replace ({0 |-> dx' }ᵈ φ) with φs in *; auto.\n  - (* t_base *) simpl. rewrite NatSetFacts.empty_b. rewrite unsplice_set_empty.\n    apply t_base; auto. eapply closed_qual_subst1'; eauto.\n  - (* t_var *) simpl. (bdestruct (x =? 0)).\n    * (*x is 0 *) rewrite indexr_skips in H0; simpl; auto; try lia. simpl in H0. subst. simpl in H0.\n        rewrite mem_singleton. simpl. rewrite remove_singleton_empty. rewrite unsplice_set_empty.\n        destruct dx'. repeat rewrite empty_union_left.\n        inversion H0. subst. erewrite subst1_ty_id; eauto. inversion HSubst; subst.\n        + (*subst fun, dx = dx' *)\n          apply vtp_has_type in HTx.\n          eapply weaken'; eauto. eapply subst_filter0; eauto.\n          eapply closed_qual_subst1'; eauto.\n        + (*subst arg, dx = df ⋒ dx = dx' ⋒ φ *)\n          apply vtp_has_type in HTx.\n          eapply weaken'; eauto.\n          eapply @subst_qual_subqual_monotone with (df:=qset b0 t t0 t1) in H3.\n          subst φs. erewrite subst1_just_fv0 in H3. auto.\n          eapply closed_qual_subst1'; eauto.\n    * (*x is in Γ0*) assert (Hx: 1 <= x); try lia. destruct x; try lia.\n      rewrite mem_singleton. simpl.\n      rewrite unsplice_set_singleton_dec; try lia.\n      apply t_var with (b:=b) (d:={0 |-> dx' }ᵈ d). change x with (pred (S x)).\n      eapply indexr_subst1; eauto. erewrite subst1_just_fv.\n      repeat eapply subst_qual_subqual_monotone. auto.\n      eapply closed_qual_subst1'; eauto. simpl. eapply closed_ty_subst1; eauto.\n      simpl. eapply closed_qual_subst1; eauto.\n  - (* t_abs *) simpl. apply t_abs; auto. eapply closed_tm_subst1'; eauto.\n    inversion H3. subst. constructor; try eapply closed_ty_subst1'; eauto; eapply closed_qual_subst1'; eauto.\n    eapply closed_qual_subst1'; eauto. apply subst_qual_subqual_monotone. auto. eauto.\n    apply subst1_senv_saturated; auto.\n    (* 1. instantiate the IH *)\n    replace (length (Γ0 ++ [(bx, Tx, dx)])) with (S (‖Γ0‖)) in IHHT.\n    rewrite subst1_tenv_length. rewrite app_comm_cons in IHHT. rewrite app_comm_cons in IHHT.\n    remember (df ⊔ $!(S (‖Γ0‖)) ⊔ $!(S (S (‖Γ0‖))) ⊔ {♦}) as DF.\n    replace ({0 |-> dx' }ᵈ df ⊔ $!(‖Γ0‖) ⊔ $!(S (‖Γ0‖)) ⊔ {♦}) with ({0 |-> dx' }ᵈ DF).\n    (* remember (φ' ⊔ $!(S (‖Γ0‖)) ⊔ $!(S (S (‖Γ0‖)))) as φ''. *)\n    assert (Hsep' : dx' ⊓ DF ⊑ dx). {\n      subst. repeat rewrite qglb_qlub_dist_l. erewrite qglb_disjoint_freshv; eauto. erewrite qglb_disjoint_freshv; eauto.\n      erewrite qglb_disjoint_fresh; eauto. repeat rewrite qlub_empty_left. apply Substq_non_fresh in HSubst.\n      rewrite HSubst. rewrite qlub_empty_right. eapply (subqual_trans _ Hsep).\n    }\n    intuition. rename H8 into IHHT. specialize IHHT with (Γ := (((false,T1, d1) :: (true, (TFun d1 d2 T1 T2), df) :: Γ0))).\n    (* 2. reason about opening and subst, apply IH *)\n    unfold open_tm' in *. unfold open_ty' in *. unfold open_ty in *.\n    unfold openq' in *. unfold openq in *.\n    rewrite app_length in IHHT. rewrite subst1_tenv_length. simpl in *.\n    replace (‖Γ0‖ + 1) with (S (‖Γ0‖)) in IHHT; try lia.\n    erewrite <- open_subst1_tm_comm in IHHT; eauto. erewrite <- open_subst1_tm_comm in IHHT; eauto.\n    erewrite <- open_subst1_ty_comm in IHHT; eauto. erewrite <- open_subst1_ty_comm in IHHT; eauto.\n    erewrite <- open_subst1_qual_comm in IHHT; eauto. erewrite <- open_subst1_qual_comm in IHHT; eauto.\n    subst. rewrite subst1_qlub_dist. repeat rewrite subst1_qlub_dist. f_equal.\n    repeat rewrite <- subst1_just_fv. rewrite subst1_fresh_id. auto. rewrite app_length. simpl. lia.\n  - (* t_app *) intuition. rename H7 into IHHT1. rename H6 into IHHT2. simpl.\n    replace ({ 0 |-> dx' }ᵈ (openq df d1 d2)) with\n               (openq ({ 0 |-> dx' }ᵈ df) ({ 0 |-> dx' }ᵈ d1) ({ 0 |-> dx' }ᵈ d2)).\n    replace ({0 |-> dx' }ᵀ (T2 <~ᵀ ∅; d1)) with\n               (({0 |-> dx' }ᵀ T2) <~ᵀ (∅); ({0 |-> dx' }ᵈ d1)).\n    apply t_app with (T1:= { 0 |-> dx' }ᵀ T1) (df:=({0 |-> dx' }ᵈ df)).\n    replace (TFun ({0 |-> dx' }ᵈ d1) ({0 |-> dx' }ᵈ d2) ({0 |-> dx' }ᵀ T1) ({0 |-> dx' }ᵀ T2))\n            with ({ 0 |-> dx' }ᵀ (TFun d1 d2 T1 T2)); auto.\n    eapply IHHT2; eauto.\n    1,3 : unfold openq; rewrite <- @subst1_qual_empty with (dx:=dx');\n        erewrite <- subst1_open_qual_comm; eauto; erewrite <- subst1_open_qual_comm; eauto.\n    * apply subst_qual_subqual_monotone. unfold openq in H4. auto.\n    * apply subst1_senv_saturated; auto.\n    * eauto.\n    * erewrite <- not_free_subst1_ty_iff; eauto.\n    * replace (∅) with ({0 |-> dx' }ᵈ ∅) at 1; auto. unfold open_ty. repeat erewrite <- subst1_open_ty_comm; eauto.\n    * unfold openq. repeat erewrite <- subst1_open_qual_comm; eauto.\n  - (* t_app_fresh *) intuition. rename H13 into IHHT1. rename H12 into IHHT2. simpl.\n    replace ({ 0 |-> dx' }ᵈ (openq df d1 d2)) with\n               (openq ({ 0 |-> dx' }ᵈ df) ({ 0 |-> dx' }ᵈ d1) ({ 0 |-> dx' }ᵈ d2)).\n    replace ({0 |-> dx' }ᵀ (T2 <~ᵀ ∅; d1)) with\n               (({0 |-> dx' }ᵀ T2) <~ᵀ ∅; ({0 |-> dx' }ᵈ d1)).\n    (*separation/overap is preserved after substitution*)\n    assert (Hoverlap: {0 |-> dx' }ᵈ (df' ⊓ d1') = {0 |-> dx' }ᵈ df' ⊓ {0 |-> dx' }ᵈ d1'). {\n      (* specialize (has_type_filter HT1). specialize (has_type_filter HT2). *)\n      symmetry. eapply subst1_preserves_separation; eauto.\n    }\n    eapply t_app_fresh with (T1:= { 0 |-> dx' }ᵀ T1) (df:=({0 |-> dx' }ᵈ df)) (d1:=({0 |-> dx' }ᵈ d1)) (df':=({0 |-> dx' }ᵈ df')) (d1':=({0 |-> dx' }ᵈ d1')); eauto.\n    replace (TFun (({0 |-> dx' }ᵈ df' ⋒ {0 |-> dx' }ᵈ d1')) ({0 |-> dx' }ᵈ d2) ({0 |-> dx' }ᵀ T1) ({0 |-> dx' }ᵀ T2))\n      with  ({0 |-> dx' }ᵀ (TFun (df' ⋒ d1') d2 T1 T2)). auto.\n    simpl. rewrite subst1_qlub_dist. rewrite Hoverlap. rewrite subst1_fresh_id. auto.\n    5 : unfold openq; rewrite <- @subst1_qual_empty with (dx:=dx');\n        erewrite <- subst1_open_qual_comm; eauto; erewrite <- subst1_open_qual_comm; eauto.\n    1,2,5,6,7 : apply subst_qual_subqual_monotone; auto.\n    intro Hfresh. 1,2 : erewrite <- not_free_subst1_ty_iff; eauto; apply Substq_non_fresh in HSubst.\n    1,2 : eapply subst1_saturated; eauto.\n    unfold openq; rewrite <- @subst1_qual_empty with (dx:=dx');\n    erewrite <- subst1_open_qual_comm; eauto; erewrite <- subst1_open_qual_comm; eauto. apply subst1_senv_saturated; auto.\n    replace (∅) with ({0 |-> dx' }ᵈ ∅) at 1; auto. unfold open_ty. repeat erewrite <- subst1_open_ty_comm; eauto.\n    unfold openq. repeat erewrite <- subst1_open_qual_comm; eauto.\n  - (* t_loc *) rewrite subst1_qlub_dist. erewrite @subst1_qual_id with (q:=(&!l)); eauto. simpl. erewrite subst1_ty_id; eauto.\n    erewrite subst1_qual_id; eauto. apply t_loc; auto. eapply closed_qual_subst1'; eauto.\n    erewrite <- @subst1_qual_id with (q:=(&!l)); eauto. eapply subst_qual_subqual_monotone; eauto.\n    2 : erewrite <- @subst1_qual_id with (q:=q); eauto; eapply subst_qual_subqual_monotone; eauto.\n    all : apply indexr_var_some' in H3; eapply just_loc_closed; eauto.\n  - (* t_ref *) rewrite subst1_qlub_dist. rewrite subst1_qual_fresh. simpl. apply t_ref; auto.\n    erewrite subst1_ty_id; eauto. erewrite <- subst1_qual_fresh.\n    eapply subst_qual_subqual_monotone; eauto. apply subst1_non_fresh; eauto.\n  - (* t_deref *) simpl. apply t_deref with (d := { 0 |-> dx' }ᵈ d); auto.\n    apply subst1_non_fresh; eauto. apply subst_qual_subqual_monotone. auto.\n    apply subst1_senv_saturated; auto.\n  - (* t_assign *) rewrite subst1_qual_empty in *. simpl. simpl in IHHT1.\n    apply t_assign with (T:={0 |-> dx' }ᵀ T) (d:=({0 |-> dx' }ᵈ d)) (d1:=({0 |-> dx' }ᵈ d1)); auto.\n    apply subst1_non_fresh; eauto.\n  - (* t_sub *) apply t_sub with (T1:={ 0 |-> dx' }ᵀ T1) (d1:={ 0 |-> dx' }ᵈ d1).\n    eapply IHHT; eauto. eapply subst_stp; eauto. apply subst_qual_subqual_monotone; auto.\n    apply subst1_senv_saturated; auto.\n  Unshelve. all : auto.\nQed.\n\n(* case for t_app *)\nLemma substitution1 : forall {t bf Tf df bx Tx dx Σ T d},\n    has_type [(bx,Tx,dx) ; (bf,Tf,df)] (df ⊔ $!0 ⊔ $!1 ⊔ {♦}) Σ t T d ->\n    forall {vf}, vtp Σ vf Tf df -> ♦∉ df ->\n        forall {vx}, vtp Σ vx Tx dx -> ♦∉ dx ->\n                    has_type [] (df ⊔ dx ⊔ {♦}) Σ\n                             ({ 0 |-> vf ; vx }ᵗ t)\n                             ({ 0 |-> df ; dx }ᵀ T)\n                             ({ 0 |-> df ; dx }ᵈ d).\n  intros. specialize (vtp_closed H0) as Hclf. specialize (vtp_closed H2) as Hclx.\n  intuition. replace ([(bx,Tx, dx); (bf,Tf, df)]) with ([(bx,Tx,dx)] ++ [(bf,Tf, df)]) in H; auto.\n  remember (df ⊔ $!0 ⊔ $!1 ⊔ {♦}) as DF.\n  assert (Hsepf : df ⊓ DF ⊑ df). { destruct df. subst. qdec. }\n  eapply (substitution_gen Hsepf) in H; eauto.\n  replace ({0 |-> df }ᴳ [(bx, Tx, dx)]) with ([] ++ [(bx, Tx, dx)]) in H.\n  replace ({0 |-> df }ᵈ DF) with (df ⊔ $!0 ⊔ {♦}) in H.\n  assert (Hsepf' : dx ⊓ (df ⊔ $!0 ⊔ {♦}) ⊑ dx). auto.\n  eapply (substitution_gen Hsepf') in H; eauto.\n  replace ({0 |-> dx }ᵈ (df ⊔ $!0 ⊔ {♦})) with (df ⊔ dx ⊔ {♦}) in H. simpl in H. apply H.\n  (*done, prove earlier replacements *)\n  repeat rewrite subst1_qlub_dist. rewrite subst1_just_fv0. erewrite subst1_qual_id; eauto. rewrite subst1_fresh_id. auto.\n  subst. repeat rewrite subst1_qlub_dist. rewrite subst1_just_fv0. rewrite <- subst1_just_fv. rewrite subst1_fresh_id.\n  erewrite subst1_qual_id; eauto. rewrite (@qlub_assoc df df). rewrite qlub_idem. auto.\n  simpl. erewrite subst1_qual_id; eauto. erewrite subst1_ty_id; eauto.\nQed.\n\n(* t_app case *)\nLemma substitution_stp1 : forall{T1 T2},\n    forall {bx Tx bf Tf df dx Σ d1 d2},\n      stp ([(bx,Tx,dx); (bf,Tf,{♦})]) Σ T1 d1 T2 d2 ->\n      closed_ty 0 0 (‖Σ‖) Tx ->\n      closed_qual 0 0 (‖Σ‖) df -> closed_qual 0 0 (‖Σ‖) dx -> ♦∉ df -> ♦∉ dx ->\n      stp [] Σ ({ 0 |-> df; dx }ᵀ T1) ({ 0 |-> df ; dx }ᵈ d1) ({ 0 |-> df ; dx }ᵀ T2) ({ 0 |-> df ; dx }ᵈ d2).\n  intros. replace [(bx, Tx, dx); (bf, Tf,{♦})] with ([(bx, Tx, dx)] ++ [(bf, Tf,{♦})]) in H; auto.\n  eapply @subst_stp with (df':=df) in H; auto.\n  replace ({0 |-> df }ᴳ [(bx, Tx, dx)]) with ([(bx, Tx, dx)]) in H.\n  replace ([(bx, Tx, dx)]) with ([] ++ [(bx, Tx, dx)]) in H; auto.\n  eapply @subst_stp with (df':=dx) in H; auto. auto.\n  simpl. erewrite subst1_ty_id; eauto. erewrite subst1_qual_id; eauto.\n  replace ({♦}) with (∅ ⋒ df). auto. destruct df. qdec.\nQed.\n\n(* case for t_app_fresh *)\nLemma substitution2 : forall {t bf Tf df df' Tx dx dx' Σ T d},\n    has_type [(false,Tx,(df' ⊓ dx') ⊔ {♦}) ; (bf,Tf,df)] (df ⊔ $!0 ⊔ $!1 ⊔ {♦}) Σ t T d ->\n    forall {vf}, vtp Σ vf Tf df -> ♦∉ df -> df ⊑ df' -> closed_qual 0 0 (‖Σ‖) df' ->\n        forall {vx}, vtp Σ vx Tx dx -> ♦∉ dx -> dx ⊑ dx' -> closed_qual 0 0 (‖Σ‖) dx' ->\n                    has_type [] (df ⊔ dx ⊔ {♦}) Σ\n                             ({ 0 |-> vf ; vx }ᵗ t)\n                             ({ 0 |-> df ; dx }ᵀ T)\n                             ({ 0 |-> df ; dx }ᵈ d).\n  intros. specialize (vtp_closed H0) as Hclf. specialize (vtp_closed H4) as Hclx.\n  assert (Hcl : closed_qual 0 0 (‖ Σ ‖) (df' ⋒ dx')). { apply closed_qual_qlub; auto. apply closed_qual_qglb; auto. }\n  intuition. replace ([(false,Tx, (df' ⋒ dx')); (bf,Tf, df)]) with ([(false,Tx, (df' ⋒ dx'))] ++ [(bf,Tf, df)]) in H; auto.\n  remember (df ⊔ $!0 ⊔ $!1 ⊔ {♦}) as DF.\n  assert (Hsepf : df ⊓ DF ⊑ df). { destruct df. subst. qdec. }\n  eapply (substitution_gen Hsepf) in H; eauto.\n  replace ({0 |-> df }ᴳ [(false, Tx, df' ⋒ dx')]) with ([(false, Tx, df' ⋒ dx')]) in H.\n  replace ({0 |-> df }ᵈ DF) with (df ⊔ $!0 ⊔ {♦}) in H.\n  assert (Hstparg : stp [] Σ Tx (df ⋒ dx) Tx (df' ⋒ dx')). { apply stp_refl; auto. }\n  eapply narrowing in H; eauto.\n  assert (Hsepf' : dx ⊓ (df ⊔ $!0 ⊔ {♦}) ⊑ (df ⊓ dx) ⊔ {♦}). {\n    rewrite (@qglb_commute df dx). repeat rewrite qglb_qlub_dist_l. erewrite qglb_disjoint_freshv; eauto.\n    destruct dx. destruct df. simpl in *. qdec.\n  }\n  replace ([(false, Tx, df ⋒ dx)]) with ([] ++ [(false, Tx, df ⋒ dx)]) in H.\n  eapply (substitution_gen Hsepf') in H; eauto.\n  replace ({0 |-> dx }ᵈ (df ⊔ $!0 ⊔ {♦})) with (df ⊔ dx ⊔ {♦}) in H. simpl in H. apply H.\n  (*done, prove earlier replacements *)\n  repeat rewrite subst1_qlub_dist. rewrite subst1_just_fv0. erewrite subst1_qual_id; eauto. rewrite subst1_fresh_id. auto.\n  simpl. auto. subst. repeat rewrite subst1_qlub_dist. rewrite subst1_just_fv0. rewrite <- subst1_just_fv. rewrite subst1_fresh_id.\n  erewrite subst1_qual_id; eauto. rewrite (@qlub_assoc df df). rewrite qlub_idem. auto.\n  simpl. erewrite subst1_qual_id; eauto. erewrite subst1_ty_id; eauto.\nQed.\n\n(* t_app_fresh case *)\nLemma substitution_stp2 : forall{T1 T2},\n    forall {Tx bf Tf df df' dx dx' Σ d1 d2},\n      stp ([(false,Tx,df' ⋒ dx'); (bf,Tf,{♦})]) Σ T1 d1 T2 d2 ->\n      closed_ty 0 0 (‖Σ‖) Tx ->\n      closed_qual 0 0 (‖Σ‖) df' -> closed_qual 0 0 (‖Σ‖) dx' -> ♦∉ df -> ♦∉ dx -> df ⊑ df' -> dx ⊑ dx' ->\n      stp [] Σ ({ 0 |-> df; dx }ᵀ T1) ({ 0 |-> df ; dx }ᵈ d1) ({ 0 |-> df ; dx }ᵀ T2) ({ 0 |-> df ; dx }ᵈ d2).\n  intros.  assert (Hcl : closed_qual 0 0 (‖ Σ ‖) (df' ⋒ dx')). { apply closed_qual_qlub; auto. apply closed_qual_qglb; auto. }\n  replace [(false, Tx, df' ⋒ dx'); (bf, Tf,{♦})] with ([(false, Tx, df' ⋒ dx')] ++ [(bf, Tf,∅ ⋒ df)]) in H; auto.\n  eapply @subst_stp with (df':=df) in H; eauto.\n  replace ({0 |-> df }ᴳ [(false, Tx, df' ⋒ dx' )]) with ([(false, Tx, df' ⋒ dx')]) in H.\n  assert (H' : stp [(false, Tx, df ⋒ dx)] Σ ({0 |-> df }ᵀ T1) ({0 |-> df }ᵈ d1) ({0 |-> df }ᵀ T2) ({0 |-> df }ᵈ d2)). {\n    eapply narrowing_stp; eauto. apply stp_refl; auto.\n  }\n  replace ([(false, Tx, df ⋒ dx )]) with ([] ++ [(false, Tx, df ⋒ dx)]) in H'; auto.\n  replace ([]) with ({0 |-> dx}ᴳ []); auto. eapply subst_stp; eauto.\n  simpl. erewrite subst1_ty_id; eauto. erewrite subst1_qual_id; eauto.\n  simpl. destruct df. repeat f_equal. qdec.\nQed.\n\nLemma open_qual_mono : forall {d1 d1' d2 k}, d1 ⊑ d1' -> ([[ k ~> d1 ]]ᵈ d2) ⊑ ([[ k ~> d1' ]]ᵈ d2).\n  intros. destruct d2; destruct d1'; destruct d1. simpl.\n  inversion H. intuition.\n  destruct (mem k t0) eqn:Hmem.\n  simpl. intuition; try fnsetdec. destr_bool. auto.\nQed.\n\nLemma open_qual_mono2 : forall {d1 d2 d2' k}, d2 ⊑ d2' -> ([[ k ~> d1 ]]ᵈ d2) ⊑ ([[ k ~> d1 ]]ᵈ d2').\n  intros. destruct d2; destruct d2'; destruct d1; simpl; intuition.\n  inversion H. intuition. destruct (mem k t0) eqn: Hmem1.\n  destruct (mem k t3) eqn: Hmem2. qdec.\n  specialize (@subset_inclusion _ _ _ H1 Hmem1 Hmem2) as F. inversion F.\n  destruct (mem k t3) eqn: Hmem2. simpl. intuition; try fnsetdec. destr_bool.\n  apply subset_union_remove; auto. auto.\nQed.\n\nLemma openq_mono : forall {d1 d1' d2 d2' d3 d3' f l},\n    closed_qual 0 f l d1' -> closed_qual 0 f l d2' ->\n    d1 ⊑ d1' -> d2 ⊑ d2' -> d3 ⊑ d3' -> (d3 <~ᵈ d1; d2) ⊑ (d3' <~ᵈ d1'; d2').\n  intros. unfold openq.\n  specialize (@open_qual_mono d1 d1' d3' 0 H1) as S1.\n  specialize (@open_qual_mono2 d1 d3 d3' 0 H3) as S2.\n  specialize (subqual_trans S2 S1) as S3. clear S1. clear S2.\n  specialize (@open_qual_mono2 d2' _ _ 1 S3) as S4.\n  eapply subqual_trans. 2: eauto. eapply open_qual_mono; eauto.\nQed.\n\nLemma open_ty'_closed : forall {l} {T} {A},\n    closed_ty 0 0 l T ->\n    closed_ty 0 2 l (T <~²ᵀ ([] : list A)).\n  intros. unfold open_ty'. unfold open_ty.\n  apply closed_ty_open_succ. auto. apply closed_ty_open_succ. auto.\nQed.\n\nLemma open_qual_qlub_dist : forall {k d1 d2 d3}, ([[ k ~> d1  ]]ᵈ (d2 ⊔ d3)) = (([[ k ~> d1  ]]ᵈ d2) ⊔ ([[ k ~> d1  ]]ᵈ d3)).\n  intros. destruct d2; destruct d3; destruct d1; simpl; auto.\n  destruct (mem k t0) eqn: Hmem1.\n  - rewrite NatSet.F.mem_1. 2: apply NatSet.F.union_2; apply NatSet.F.mem_2; auto.\n    destruct (mem k t3) eqn: Hmem2.\n    simpl. qdec. simpl. f_equal; try fnsetdec. destr_bool.\n    rewrite remove_union_dist; try fnsetdec. rewrite (@remove_not_in k t3); auto. fnsetdec.\n  - destruct (mem k t3) eqn: Hmem2.\n    rewrite NatSet.F.mem_1. 2: apply NatSet.F.union_3; apply NatSet.F.mem_2; auto.\n    simpl. f_equal; try fnsetdec. destr_bool.\n    rewrite remove_union_dist. rewrite (@remove_not_in k t0); auto. fnsetdec.\n    rewrite not_member_union; auto.\nQed.\n\nLemma qfresh_true_open : forall {k d1 t t0 t1}, (♦∈? ([[k ~> d1 ]]ᵈ (qset true t t0 t1))) = true.\n  intros. destruct d1. compute. destruct (mem k t0); auto.\nQed.\n\nLemma qfresh_true_openq : forall {d1 df t t0 t1}, (♦∈? ((qset true t t0 t1) <~ᵈ df; d1)) = true.\n  intros. unfold openq. simpl. destruct (mem 0 t0); auto.\n  destruct df. all :apply qfresh_true_open.\nQed.\n\nLemma open_qual_qqplus_dist : forall {k d1 d2 d3}, ♦∈ d2 -> ([[ k ~> d1 ]]ᵈ (d2 ⋓ d3)) = (([[ k ~> d1 ]]ᵈ d2) ⋓ ([[ k ~> d1 ]]ᵈ d3)).\n  intros. destruct d2. destruct b; unfold qqplus.\n  * rewrite qfresh_true. rewrite qfresh_true_open. apply open_qual_qlub_dist.\n  * simpl in H. discriminate.\nQed.\n\n(* Some distributive laws about openq and qqplus, required in the type safety proof for function application t_app. *)\nLemma open_qual_duplicate_eq : forall {k d1 d2 d}, ♦∈ d1 ->\n  ([[ k ~> d1 ]]ᵈ d2 ⋓ d) = ([[ k ~> d1 ⋓ d ]]ᵈ d2 ⋓ d).\n  intros. destruct d1. destruct b; unfold qqplus. 2: simpl in H; discriminate.\n  destruct d. destruct d2. destruct b0.\n  * repeat rewrite qfresh_true_open. unfold qfresh. simpl.\n    destruct (mem k t6) eqn:Hmemk3; simpl; qdec.\n  * simpl. destruct (mem k t6) eqn:Hmemk3; unfold qfresh; qdec.\nQed.\n\n(* when the argument steps *)\nLemma openq_duplicate_eq_r : forall {df d1 d2 d}, ♦∈ d1 ->\n  (d2 <~ᵈ df; d1 ⋓ d) = (d2 <~ᵈ df; (d1 ⋓ d) ⋓ d).\n  intros. unfold openq. rewrite open_qual_duplicate_eq; auto.\nQed.\n\n(* when the function steps *)\nLemma openq_duplicate_eq_l : forall {f l df d1 d2 d},\n  ♦∈ df -> closed_qual 0 f l df -> closed_qual 0 f l d1 -> closed_qual 0 f l d ->\n  (d2 <~ᵈ df; d1 ⋓ d) = ((d2 <~ᵈ df ⋓ d; d1) ⋓ d).\n  intros. unfold openq. erewrite open_qual_commute''; eauto.\n  erewrite @open_qual_commute'' with (i:=1); eauto.\n  rewrite open_qual_duplicate_eq; auto.\n  apply closed_qual_qqplus; auto.\nQed.\n\nLemma qqcap_fresh_r : forall {d1 df f Σ Σ' d'},\n    closed_qual 0 f (‖Σ‖) d1 -> closed_qual 0 f (‖Σ‖) df ->\n    Σ → Σ' ∋ df ⊕ d' -> (d1 ⋒ df) = (d1 ⋒ (df ⋓ d')).\n  intros. destruct d1 as [fr1 f1 b1 l1]. destruct df as [frf ff bf lf].\n  inversion H1; subst.\n  - rewrite qqplus_qbot_right_neutral. auto.\n  - assert (Hfresh: ~ In (‖Σ‖) l1). { inversion H. subst. apply bound_le_not_in. auto. }\n     destruct q as [frq fq bq lq]. simpl in *. destruct frf. 2 : qdec.\n    simpl in *. intuition. f_equal; try fnsetdec.\nQed.\n\nLemma qqcap_fresh_l : forall {d1 df f Σ Σ' d'},\n    closed_qual 0 f (‖Σ‖) d1 -> closed_qual 0 f (‖Σ‖) df ->\n    Σ → Σ' ∋ d1 ⊕ d' -> (d1 ⋒ df) = ((d1 ⋓ d') ⋒ df).\n  intros. destruct d1 as [fr1 f1 b1 l1]. destruct df as [frf ff bf lf]. inversion H1; subst.\n  - rewrite qqplus_qbot_right_neutral. auto.\n  - assert (Hfresh: ~ In (‖Σ‖) lf). { inversion H0. subst. apply bound_le_not_in. auto. }\n    destruct q as [frq fq bq lq]. simpl in *. destruct fr1. 2 : qdec.\n    simpl in *. intuition. f_equal; try fnsetdec.\nQed.\n\nLemma openq_closed : forall {a b c f l},\n    closed_qual 2 f l c -> closed_qual 0 f l a -> closed_qual 0 f l b -> closed_qual 0 f l (openq a b c).\n  intros. unfold openq. eapply closed_qual_open2; eauto.\nQed.\n\nLemma disjointq_ldom : forall {Σ Σ' d d'}, Σ → Σ' ∋ d ⊕ d' -> d' ⊑ ldom Σ'.\n  intros. inversion H; subst; auto. unfold ldom. unfold dom. inversion H2. subst.\n  simpl.  apply bound_0_empty in H4, H5. subst. apply bound_dom_sub in H6. qdec.\nQed.\n#[global] Hint Resolve disjointq_ldom : core.\n\nLemma disjointq_ldom' : forall {Σ Σ' d d'}, Σ → Σ' ∋ d ⊕ d' -> {♦} ⊔ d' ⊑ ldom Σ'.\n  intros. inversion H; subst; auto; unfold ldom; unfold dom. qdec. inversion H2. subst.\n  simpl.  apply bound_0_empty in H4, H5. subst. apply bound_dom_sub in H6. qdec.\nQed.\n#[global] Hint Resolve disjointq_ldom' : core.\n\nLemma disjointq_closed : forall {Σ Σ' d d'}, Σ → Σ' ∋ d ⊕ d' -> closed_qual 0 0 (‖Σ'‖) d'.\n  intros. inversion H; subst; auto. simpl. apply closed_qual_qlub. eapply closed_qual_monotone; eauto.\n  apply just_loc_closed. simpl. lia.\nQed.\n#[global] Hint Resolve disjointq_closed : core.\n\nLemma disjointq_saturated : forall {Σ Σ' d d'}, Σ → Σ' ∋ d ⊕ d' -> wf_senv Σ -> senv_saturated Σ' d'.\n  intros. inversion H; subst. auto. eapply wf_senv_saturated_qplus; eauto. apply indexr_head.\nQed.\n#[global] Hint Resolve disjointq_saturated : core.\n\nLemma disjointq_scale : forall {Σ Σ' d d'}, Σ → Σ' ∋ d ⊕ d' -> forall {d''}, d ⊑ d'' -> Σ → Σ' ∋ d'' ⊕ d'.\n  intros. inversion H; subst. auto. econstructor; eauto. eapply subqual_trans; eauto.\nQed.\n#[global] Hint Resolve disjointq_scale : core.\n\n\nLemma ldom_fresh : forall {A} {Σ : list A}, {♦} ⊑ ldom Σ.\n  intros. simpl. intuition.\nQed.\n#[global] Hint Resolve ldom_fresh : core.\n\n(* well-typed values belonging to each type *)\n\nLemma vtp_canonical_form_loc : forall {Σ t T q d},\n   vtp Σ t (TRef q T) d -> value t -> exists (l : loc), t = tloc l.\nProof. intros. remember (TRef q T) as R. remember t as tt. generalize dependent T.\n       induction H; intuition; try discriminate; inversion H0; subst. exists l. intuition.\nQed.\n\nLemma vtp_canonical_form_lam : forall {Σ t T1 T2 d1 d2 df},\n    vtp Σ t (TFun d1 d2 T1 T2) df -> value t -> exists (t' : tm), t = tabs t'.\nProof. intros Σ t T1 T2 d1 d2 df H. remember (TFun d1 d2 T1 T2) as T.\n       generalize dependent d1. generalize dependent d2. generalize dependent T1. generalize dependent T2.\n       induction H; intuition; try discriminate; inversion H0; subst. exists t. intuition.\nQed.\n\nLemma qstp_delete_fresh : forall {Σ q1 q2}, qstp [] Σ q1 q2 -> ♦∉ q1 -> qstp [] Σ q1 (qset false (qfvs q2) (qbvs q2) (qlocs q2)).\n  intros. specialize (qstp_closed H) as Hcl. intuition. apply qstp_empty in H. apply qs_sq.\n  destruct q1. destruct q2. qdec. destruct q2. simpl. inversion H2. subst. constructor; auto.\nQed.\n\nLemma senv_saturated_non_fresh : forall {Σ q}, senv_saturated Σ q -> senv_saturated Σ (qset false (qfvs q) (qbvs q) (qlocs q)).\n  intros. unfold senv_saturated in *. intros. specialize (H l). destruct q. simpl in *. intuition.\n  inversion H1. subst. econstructor; eauto. destruct q'. qdec.\nQed.\n\nLemma vtp_non_fresh : forall {Σ v T q}, vtp Σ v T q -> vtp Σ v T (qset false (qfvs q) (qbvs q) (qlocs q)).\n  intros. destruct q. inversion H; subst.\n  - constructor. inversion H0. subst. eauto. apply senv_saturated_non_fresh. auto.\n  - inversion H0. subst. econstructor; eauto.\n    apply qstp_delete_fresh; auto. apply senv_saturated_non_fresh. auto.\n  - inversion H2. subst. econstructor; eauto.\n    apply qstp_delete_fresh; auto. apply senv_saturated_non_fresh. auto.\nQed.\n\nLemma stp_set_not_fresh : forall {d1 T Γ Σ}, closed_ty 0 (‖Γ‖) (‖Σ‖) T -> closed_qual 0 (‖Γ‖) (‖Σ‖) d1 -> stp Γ Σ T (qset false (qfvs d1) (qbvs d1) (qlocs d1)) T d1.\n  intros. apply stp_refl; auto.\nQed.\n#[global] Hint Resolve stp_set_not_fresh : core.\n\nLemma openq_subqual_0 : forall {df d2 d1 l}, closed_qual 0 0 l df -> closed_qual 0 0 l d1 -> mem 0 (qbvs d2) = true -> df ⊑ d2 <~ᵈ df; d1.\n  intros. destruct d2 as [fr2 f2 b2 l2]. destruct df as [frf ff bf lf]. destruct d1 as [fr1 f1 b1 l1].\n  inversion H. inversion H0. subst. apply bound_0_empty in H8,H10,H18,H20. subst.\n  unfold openq. simpl in *. rewrite H1. simpl. apply NatSet.F.mem_2 in H1. destruct (mem 1 (union (remove 0 b2) {}N)) eqn:Hmem.\n  apply NatSet.F.mem_2 in Hmem. qdec.\n  rewrite <- NatSetFacts.not_mem_iff in Hmem. qdec.\nQed.\n\nLemma openq_subqual_0_false : forall {df d2 d1}, mem 0 (qbvs d2) = false -> forall {df'}, d2 <~ᵈ df; d1 = d2 <~ᵈ df'; d1.\n  intros. destruct d2 as [fr2 f2 b2 l2]. unfold openq. simpl in *. rewrite H. auto.\nQed.\n\nLemma openq_subqual_1 : forall {df d2 d1 l}, closed_qual 0 0 l df -> closed_qual 0 0 l d1 -> mem 1 (qbvs d2) = true -> d1 ⊑ d2 <~ᵈ df; d1.\n  intros. destruct d2 as [fr2 f2 b2 l2]. destruct df as [frf ff bf lf]. destruct d1 as [fr1 f1 b1 l1].\n  inversion H. inversion H0. subst. apply bound_0_empty in H8,H10,H18,H20. subst.\n  unfold openq. simpl in *. destruct (mem 0 b2) eqn:Hmem; simpl. rewrite empty_union_right.\n  assert (H1' : mem 1 (remove 0 b2) = true). { apply NatSet.F.mem_1. apply NatSet.F.mem_2 in H1,Hmem. fnsetdec. }\n  rewrite H1'. apply NatSet.F.mem_2 in H1, Hmem. qdec.\n  rewrite H1. qdec.\nQed.\n\nLemma openq_subqual_1_false : forall {df d2 d1 l}, closed_qual 0 0 l df -> mem 1 (qbvs d2) = false -> forall {d1'}, d2 <~ᵈ df; d1 = d2 <~ᵈ df; d1'.\n  intros. destruct d2 as [fr2 f2 b2 l2]. destruct df as [frf ff bf lf]. destruct d1 as [fr1 f1 b1 l1]. unfold openq. simpl in *.\n  inversion H. subst. apply bound_0_empty in H7, H9. subst.\n  destruct (mem 0 b2) eqn:Hmem; simpl. repeat rewrite empty_union_right.\n  assert (H0' : mem 1 (remove 0 b2) = false). {\n    rewrite <- NatSetFacts.not_mem_iff in H0. apply NatSet.F.mem_2 in Hmem. rewrite <- NatSetFacts.not_mem_iff. fnsetdec.\n  } rewrite H0'. 2: rewrite H0. all : auto.\nQed.\n\nLemma open_qual_not_free : forall {k q}, [[k ~> ∅ ]]ᵈ q = q -> forall {q'}, [[k ~> q' ]]ᵈ q = q.\n  intros. destruct q. destruct q'. simpl in *. destruct (mem k t0) eqn:Hmem; auto.\n  repeat rewrite empty_union_right in H. inversion H. rewrite <- H2 in Hmem.\n  apply NatSet.F.mem_2 in Hmem. fnsetdec.\nQed.\n\nLemma not_free_prop1 : forall {T k}, not_free k T -> forall {d}, ([[k ~> d ]]ᵀ T) = T.\n  unfold not_free. induction T; intros. auto. simpl in H. inversion H.\n  rewrite H1, H2, H3, H4. simpl. rewrite IHT1; auto. rewrite IHT2; auto.\n  repeat rewrite open_qual_not_free; auto.\n  simpl in H. inversion H. rewrite H1, H2. simpl. rewrite IHT; auto.\n  rewrite open_qual_not_free; auto.\nQed.\n\nLemma not_free_prop2 : forall {T k}, not_free k T -> forall {d d'}, ([[k ~> d ]]ᵀ T) = ([[k ~> d' ]]ᵀ T).\n  intros. repeat rewrite not_free_prop1; auto.\nQed.\n#[global] Hint Resolve not_free_prop2 : core.\n\nLemma not_free_prop3 : forall {T k}, not_free k T -> forall {f l}, closed_ty (S k) f l T -> closed_ty k f l T.\n  intros. rewrite <- (@not_free_prop1 _ _ H ∅). eapply closed_ty_open'; eauto.\nQed.\n\n(* Main results: type soundness & preservation of separation *)\n\nTheorem type_safety: forall {Σ t T d},\n  has_type [] (ldom Σ) Σ t T d -> wf_senv Σ -> (\n    value t \\/\n    (forall {σ} , CtxOK [] (ldom Σ) Σ σ ->\n      (exists t' σ',\n        step t σ t' σ' /\\ preserve [] Σ t' T d σ'\n      )\n    )\n  ).\n\nProof. intros Σ t T d H HwfSigma.\n       specialize (has_type_closed H) as HX. remember [] as G. remember t as tt. remember T as TT. remember (ldom Σ) as φ.\n       revert T t HeqTT Heqtt HeqG Heqφ.\n       induction H; try (left; constructor); intros.\n   + (* tvar *)  subst. inversion H.\n\n   + (* tapp *) right. subst. intuition.\n     apply has_type_closed in H as HH. intuition. apply has_type_closed in H0 as HH0. intuition.\n     (* t1 *) specialize (H11 (TFun d1 d2 T1 T2) t1). intuition.\n\n     (* t2 *) specialize (H8 T1 t2). intuition.\n     - (* contraction *)\n       (* turn has_type to vtp *)\n       apply has_type_vtp in H as VH; intuition.\n       pose (VHH := VH). inversion VH. subst.\n\n       specialize (has_type_filter H0) as Hflt0.\n\n       apply has_type_vtp in H0 as VH0; intuition.\n\n       exists (open_tm (tabs t) t2 t). exists σ. intuition.\n       * constructor. intuition.\n\n       * apply (Preserve Σ ∅); auto.  rewrite qqplus_qbot_right_neutral.\n         apply qstp_closed in H30 as H32'; intuition.\n\n         change (length []) with 0 in *. subst.\n         pose (VH' := H28). eapply t_abs with (φ:=df1) in VH'; eauto. apply has_type_vtp in VH'; auto.\n\n         assert (HT' : has_type [(false, T1, d1) ; (true, TFun d0 d3 T0 T3, df1)] (df1 ⊔ $!0 ⊔ $!1 ⊔ {♦}) Σ (open_tm' ([]:tenv) t) (open_ty' ([]:tenv) T3) (openq' ([]:tenv) d3)). {\n           eapply narrowing. eapply H28. intuition. auto.\n         }\n         eapply @substitution1 with ( vx:= t2) in HT' as HT''; eauto; intuition.\n\n         unfold open_tm' in HT''. unfold open_ty' in HT''. unfold openq' in HT''. simpl in HT''. inversion H26; subst. inversion H27. subst.\n         unfold open_ty in HT''. unfold openq in HT''.\n\n         erewrite <- open_subst2_tm in HT''; eauto.\n         erewrite <- open_subst2_ty in HT''; eauto.\n         erewrite <- open_subst2_qual in HT''; eauto.\n         fold (open_tm (tabs t) t2 t) in HT''. fold (openq df1 d1 d3) in HT''. fold (open_ty df1 d1 T3) in HT''.\n         apply @weaken_flt with (φ':= (ldom Σ)) in HT''; auto; intuition.\n         eapply t_sub; eauto.\n\n         pose (Hsub:=H33). eapply @substitution_stp1 with (df:=df1) in Hsub; eauto.\n         simpl in Hsub. unfold openq' in Hsub. unfold openq in Hsub. unfold open_ty' in Hsub. unfold open_ty in Hsub. simpl in Hsub.\n         erewrite <- open_subst2_ty in Hsub; eauto. erewrite <- open_subst2_ty in Hsub; eauto.\n         erewrite <- open_subst2_qual in Hsub; eauto. erewrite <- open_subst2_qual in Hsub; eauto.\n         unfold open_ty. unfold openq.\n         replace ([[0 ~> ∅ ]]ᵀ T2) with ([[0 ~> df1 ]]ᵀ T2); auto. (* since not_free 0 T2 *)\n\n         eapply s_trans; eauto. apply stp_refl; auto. apply closed_ty_open2; auto.\n         constructor. eapply openq_mono; eauto. apply qstp_empty in H30. auto. apply openq_closed; auto.\n\n         eapply openq_subqual; eauto. apply has_type_filter in H. auto.\n         eapply senv_saturated_openq; eauto. eapply has_type_senv_saturated; eauto.\n         repeat apply qlub_bound; auto. apply has_type_filter in H. apply qstp_empty in H30.\n         eapply subqual_trans; eauto.\n\n     -  (* right congruence *)\n        apply has_type_vtp in H as VH; intuition.\n        apply vtp_canonical_form_lam in VH as HH; intuition.\n\n        pose (HH12 := H10).\n        unfold CtxOK in HH12. specialize (H11 σ). intuition.\n\n        destruct H22 as [t2' [σ' HH9]]. exists (tapp t1 t2'). exists σ'. intuition. constructor; intuition.\n\n        (* d1 is not fresh, so we don't observe the growth *)\n        destruct H22. apply (Preserve Σ' ∅); intuition.\n        rewrite not_fresh_qqplus in H26; auto. rewrite qqplus_qbot_right_neutral.\n        eapply t_app with (T1:=T1); eauto. eapply weaken_flt. eapply weaken_store; eauto. auto. auto.\n        eapply subqual_trans; eauto.\n        eapply weaken_store_senv_saturated; eauto.\n\n     -  (* left congruence *)\n        apply has_type_closed in H0 as Hcl. intuition.\n        specialize (H19 σ H10). destruct H19 as [t1' [σ' HH7]]. exists (tapp t1' t2). exists σ'. intuition. apply step_c_app_l. intuition.\n        destruct H23. destruct (mem 0 (qbvs d2)) eqn:Hmem.\n        * (* d2 is dependent on f, so the growth in df might be observable  *)\n          apply (Preserve Σ' d'); auto.\n          -- eapply disjointq_scale; eauto. eapply openq_subqual_0; eauto. (* this is the sole reason why need to distinguish whether d2 is dependent on f or not *)\n          -- destruct (♦∈? df) eqn:Hfresh.\n             ** erewrite @openq_duplicate_eq_l with (f:=0) (l:=‖Σ'‖). 3,4 : eapply closed_qual_monotone; eauto. 2,3 : eauto.\n                eapply t_sub with (T1 := (T2 <~ᵀ ∅; d1))(d1 := (openq (df ⋓ d') d1 d2)).\n                --- eapply t_app with (T1:=T1) (df:=(df ⋓ d')); eauto.\n                    eapply weaken_flt. eapply weaken_store; eauto. auto. auto.\n                    eapply subqual_trans; eauto. eapply weaken_store_senv_saturated; eauto.\n                --- apply stp_refl. simpl. eapply closed_ty_monotone; eauto.\n                    constructor; auto. apply closed_qual_qqplus; auto.\n                    inversion H13; subst. apply openq_closed. 2 : apply closed_qual_qqplus.\n                    1,2,4 : eapply closed_qual_monotone; eauto; lia. all: eapply disjointq_closed; eauto.\n                --- apply has_type_filter in H0. apply has_type_filter in H. apply qqplus_bound.\n                    eapply openq_subqual; eauto. apply qqplus_bound.\n                    1,3,4 : eapply subqual_trans; eauto. all : eapply disjointq_ldom; eauto.\n                --- apply senv_saturated_qqplus; eauto. eapply senv_saturated_openq.\n                    apply senv_saturated_qqplus; eauto. 1,3,5 : eapply weaken_store_senv_saturated; eauto.\n                    1,2 : eapply has_type_senv_saturated; eauto. apply closed_qual_qqplus. 1,3 : eapply closed_qual_monotone; eauto. eauto.\n             ** rewrite not_fresh_qqplus in H28; auto. apply t_sub with (T1:=(T2 <~ᵀ ∅; d1)) (d1:=d2 <~ᵈ df; d1).\n                --- eapply t_app with (T1:=T1); eauto. eapply weaken_flt. eapply weaken_store; eauto. auto. auto.\n                    eapply subqual_trans; eauto. eapply weaken_store_senv_saturated; eauto.\n                --- inversion H13. subst. clear H39. apply stp_refl. simpl. eapply closed_ty_monotone; eauto.\n                    constructor. auto. apply closed_qual_qqplus; auto.\n                    apply openq_closed; try solve [eapply closed_qual_monotone; eauto]. eauto.\n                --- apply qqplus_bound. apply has_type_filter in H0. apply has_type_filter in H. eapply openq_subqual; eauto.\n                    1,2,3 : eapply subqual_trans; eauto. eapply disjointq_ldom; eauto.\n                --- apply senv_saturated_qqplus; eauto. eapply weaken_store_senv_saturated; eauto. eapply senv_saturated_openq.\n                    eapply has_type_senv_saturated; eauto. apply has_type_closed in H. intuition. eauto.\n                    eapply has_type_senv_saturated; eauto. apply has_type_closed in H0. intuition. eauto.\n        * (* d2 is not dependent on f, so we don't observe the growth in df *)\n          apply (Preserve Σ' ∅); auto. rewrite qqplus_qbot_right_neutral.\n          replace (d2 <~ᵈ df; d1) with (d2 <~ᵈ df ⋓ d'; d1). (* since f doesn't occur in d2 *)\n          eapply t_app with (T1:=T1); eauto. eapply weaken_flt. eapply weaken_store; eauto. auto. auto.\n          eapply subqual_trans; eauto.\n          eapply weaken_store_senv_saturated; eauto.\n          apply openq_subqual_0_false; auto.\n\n    + (* t_app_fresh *) right. subst. intuition.\n     apply has_type_closed in H as HH. intuition. apply has_type_closed in H2 as HH0. intuition.\n     (* t1 *) specialize (H17 (TFun (df' ⋒ d1') d2 T1 T2) t1). intuition.\n\n     (* t2 *) specialize (H14 T1 t2). intuition.\n\n     - (* contraction *)\n       (* turn has_type to vtp *)\n       apply has_type_vtp in H as VH; intuition.\n       pose (VHH := VH). inversion VH. subst.\n\n       specialize (has_type_filter H2) as Hflt0.\n\n       apply has_type_vtp in H2 as VH0; intuition.\n\n       exists (open_tm (tabs t) t2 t). exists σ. intuition.\n       * constructor. intuition.\n\n       * apply (Preserve Σ ∅); auto. rewrite qqplus_qbot_right_neutral.\n         apply qstp_closed in H36 as H37'; intuition.\n\n         change (length []) with 0 in *. subst.\n         pose (VH' := H34). eapply t_abs with (φ:=df1) in VH'; eauto. apply has_type_vtp in VH'; auto.\n\n         (* remove potential freshness flag from the argument, in order to apply substitution lemma *)\n         apply vtp_non_fresh in VH0. remember (qset false (qfvs d1) (qbvs d1) (qlocs d1)) as d1''.\n         assert (Hd1'' : d1'' ⊑ d1'). { subst. eapply subqual_trans; eauto. }\n         assert (Hdf1 : df1 ⊑ df'). { apply qstp_empty in H36. eapply subqual_trans; eauto. }\n         assert (Hd1''fr : ♦∉ d1''). { subst. auto. }\n\n         assert (HT' : has_type [(false, T1, df' ⋒ d1') ; (true, TFun d0 d3 T0 T3, df1)] (df1 ⊔ $!0 ⊔ $!1 ⊔ {♦}) Σ (open_tm' ([]:tenv) t) (open_ty' ([]:tenv) T3) (openq' ([]:tenv) d3)). {\n           eapply narrowing. eapply H34. intuition. auto.\n         }\n         eapply @substitution2 with ( vx:= t2) in HT' as HT''; eauto; intuition.\n\n         unfold open_tm' in HT''. unfold open_ty' in HT''. unfold openq' in HT''. simpl in HT''. inversion H32; subst.\n         unfold open_ty in HT''. unfold openq in HT''.\n\n         erewrite <- open_subst2_tm in HT''; eauto.\n         erewrite <- open_subst2_ty in HT''; eauto.\n         erewrite <- open_subst2_qual in HT''; eauto.\n         fold (open_tm (tabs t) t2 t) in HT''. fold (openq df1 (qset false (qfvs d1) (qbvs d1) (qlocs d1)) d3) in HT''.\n         apply @weaken_flt with (φ':= (ldom Σ)) in HT''; auto; intuition.\n         eapply t_sub; eauto.\n\n         inversion H33. subst. rename H39 into Hsub.\n         eapply @substitution_stp2 with (dx := (qset false (qfvs d1) (qbvs d1) (qlocs d1))) (df:=df1) in Hsub; eauto.\n\n         simpl in Hsub. unfold openq' in Hsub. unfold openq in Hsub. simpl in Hsub.\n         unfold open_ty' in Hsub. unfold open_ty in Hsub.\n         erewrite <- open_subst2_ty in Hsub; eauto. erewrite <- open_subst2_ty in Hsub; eauto.\n         erewrite <- open_subst2_qual in Hsub; eauto. erewrite <- open_subst2_qual in Hsub; eauto.\n         fold (openq df1 (qset false (qfvs d1) (qbvs d1) (qlocs d1)) d3) in Hsub. fold (openq df1 (qset false (qfvs d1) (qbvs d1) (qlocs d1)) d2) in Hsub.\n         fold (open_ty df1 (qset false (qfvs d1) (qbvs d1) (qlocs d1)) T3) in Hsub. fold (open_ty df1 (qset false (qfvs d1) (qbvs d1) (qlocs d1)) T2) in Hsub.\n         fold (open_ty df1 (qset false (qfvs d1) (qbvs d1) (qlocs d1)) T3).\n         (* need to reason about growth of d1 *)\n         { destruct (♦∈? d1) eqn:Hfresh.\n         ++ (* d1 fresh, so the function can't be dependent on the argument *)\n            intuition. replace (T2 <~ᵀ ∅; d1) with T2. replace (T2 <~ᵀ df1; (qset false (qfvs d1) (qbvs d1) (qlocs d1))) with T2 in Hsub. (* since no dependence *)\n            eapply s_trans; eauto. apply stp_refl; auto. apply not_free_prop3; auto. apply not_free_prop3; auto.\n            constructor; auto. eapply openq_mono; eauto. apply qstp_empty in H36. auto.\n            all : unfold open_ty; rewrite not_free_prop1; auto. all : rewrite not_free_prop1; auto.\n         ++ (* d1 non-fresh *)\n            assert (Hd1 : (qset false (qfvs d1) (qbvs d1) (qlocs d1))= d1). { destruct d1. simpl. simpl in Hfresh. subst. auto. }\n            rewrite Hd1 in *. replace (T2 <~ᵀ ∅; d1) with (T2 <~ᵀ df1; d1). (* since no dependence *)\n            eapply s_trans; eauto. apply stp_refl; auto. apply closed_ty_open2; auto. constructor; auto.\n            eapply openq_mono; eauto. apply qstp_empty in H36. auto.\n            unfold open_ty. f_equal. auto.\n         }\n\n         eapply openq_subqual; eauto. apply has_type_filter in H. auto.\n         eapply senv_saturated_openq; eauto. eapply has_type_senv_saturated; eauto.\n         repeat apply qlub_bound; auto. apply has_type_filter in H.\n         eapply subqual_trans; eauto. destruct d1. qdec.\n         1,2 : inversion H33; auto.\n\n     -  (* right congruence *)\n        apply has_type_vtp in H as VH; intuition.\n        apply vtp_canonical_form_lam in VH as HH; intuition.\n        specialize (H17 σ). intuition.\n\n        destruct H14 as [t2' [σ' HH22]]. exists (tapp t1 t2'). exists σ'. intuition. constructor; intuition.\n\n        destruct H17. destruct (♦∈? d1) eqn:Hfresh.\n        * (* d1 fresh *) destruct (mem 1 (qbvs d2)) eqn:Hmem.\n          -- (* d2 dependent on x *) apply (Preserve Σ' d'); auto.\n             eapply disjointq_scale; eauto. eapply openq_subqual_1; eauto. intuition.\n             replace (T2 <~ᵀ ∅; d1) with (T2 <~ᵀ ∅; (d1 ⋓ d')). (* T2 not dependent on x *)\n             rewrite openq_duplicate_eq_r; auto. apply t_sub with (T1 := (T2 <~ᵀ ∅; (d1 ⋓ d'))) (d1 := (openq df (d1 ⋓ d') d2)).\n             ** eapply t_app_fresh with (T1 := T1) (d1':=d1' ⋓ d') (df':=df') (df:=df); eauto. replace (df' ⋒ d1' ⋓ d') with (df' ⋒ d1').\n                eapply weaken_flt. eapply weaken_store; eauto. all : auto. eapply @qqcap_fresh_r with (Σ':=Σ'); eauto.\n                eapply subqual_trans; eauto; apply extends_ldom; auto. apply qqplus_bound; eauto. 1,2 : eapply subqual_trans; eauto.\n                apply saturated_qqplus; eauto. 1,2: eapply weaken_store_saturated; eauto.\n                eapply weaken_store_saturated; eauto.\n            **  apply has_type_closed in H30. intuition. inversion H19. subst.\n                apply stp_refl. unfold open_ty. eapply closed_ty_open2; eauto. eapply closed_ty_monotone; eauto.\n                constructor; auto. apply closed_qual_qqplus; auto.\n                eapply openq_closed; try solve [eapply closed_qual_monotone; eauto]. eauto.\n            **  apply has_type_filter in H2. apply has_type_filter in H. apply qqplus_bound. eapply openq_subqual; eauto.\n                2: apply qqplus_bound. 1, 2, 4 : eapply subqual_trans; eauto. eapply subqual_trans; eauto. all : eauto.\n            **  apply senv_saturated_qqplus; eauto. eapply senv_saturated_openq.\n                1, 5 : eapply weaken_store_senv_saturated; eauto. 1,3 : eapply has_type_senv_saturated; eauto.\n                2 : apply closed_qual_qqplus. 1,2 : eapply closed_qual_monotone; eauto. eauto.\n            ** unfold open_ty. apply not_free_prop2. rewrite not_free_prop1; auto.\n          -- (* d2 not dependent on x *) apply (Preserve Σ' ∅); auto. rewrite qqplus_qbot_right_neutral. intuition.\n             replace (d2 <~ᵈ df; d1) with (d2 <~ᵈ df; (d1 ⋓ d')).  replace (T2 <~ᵀ ∅; d1) with (T2 <~ᵀ ∅; (d1 ⋓ d')). (* T2 not dependent on x *)\n             eapply t_app_fresh with (T1:=T1) (d1':=((d1' ⋓ d'))); eauto.\n             erewrite <- @qqcap_fresh_r with (Σ':=Σ'); eauto.\n             eapply weaken_flt. eapply weaken_store; eauto. auto. auto.\n             eapply subqual_trans; eauto. apply qqplus_bound; eauto.\n             1,2 : eapply subqual_trans; eauto. apply saturated_qqplus; eauto.\n             1,2 : eapply weaken_store_saturated; eauto. eapply weaken_store_senv_saturated; eauto.\n             unfold open_ty. repeat rewrite not_free_prop1; auto.\n             eapply openq_subqual_1_false; eauto.\n        * (* d1 not fresh *) rewrite not_fresh_qqplus in H30; auto. apply (Preserve Σ' ∅); auto.\n          rewrite qqplus_qbot_right_neutral.\n          eapply t_app_fresh with (T1:=T1); eauto. eapply weaken_flt. eapply weaken_store; eauto. auto. auto.\n          eapply subqual_trans; eauto. 1,2 : eapply subqual_trans; eauto.\n          1,2 : eapply weaken_store_saturated; eauto. eapply weaken_store_senv_saturated; eauto.\n\n     -  (* left congruence *)\n        apply has_type_closed in H2 as Hcl. intuition.\n        specialize (H25 σ H16). destruct H25 as [t1' [σ' HH6]]. exists (tapp t1' t2). exists σ'. intuition. apply step_c_app_l. intuition.\n        destruct H29. destruct (♦∈? df) eqn:Hfresh.\n        * (* df fresh *) destruct (mem 0 (qbvs d2)) eqn:Hmem.\n          -- (* d2 dependent on f *) apply (Preserve Σ' d'); auto.\n            eapply disjointq_scale; eauto. eapply openq_subqual_0; eauto.\n            erewrite @openq_duplicate_eq_l with (l:=‖Σ'‖) (f:=0); auto. 2,3 : eapply closed_qual_monotone; eauto. 2: eauto.\n            apply t_sub with (T1 := (T2 <~ᵀ ∅; d1)) (d1 := (openq (df ⋓ d') d1 d2)).\n            ** eapply t_app_fresh with (T1 := T1) (df':=df' ⋓ d'); eauto. erewrite <- @qqcap_fresh_l with (Σ':=Σ'); eauto.\n               eapply weaken_flt. eapply weaken_store; eauto. all : auto.\n               eapply subqual_trans; eauto; apply extends_ldom; auto. 2 : apply qqplus_bound; eauto. 1,2 : eapply subqual_trans; eauto.\n               2 : apply saturated_qqplus; eauto. 1,2: eapply weaken_store_saturated; eauto.\n               eapply weaken_store_saturated; eauto.\n            ** apply has_type_closed in H34. intuition. inversion H19. subst.\n               apply stp_refl. simpl. eapply closed_ty_monotone; eauto.\n               constructor; auto. apply closed_qual_qqplus; auto.\n               eapply openq_closed; try solve [eapply closed_qual_monotone; eauto]. eauto.\n            ** apply has_type_filter in H2. apply has_type_filter in H. apply qqplus_bound. eapply openq_subqual; eauto.\n               apply qqplus_bound. 1, 3, 4 : eapply subqual_trans; eauto. eapply subqual_trans; eauto. all : eauto.\n            ** apply senv_saturated_qqplus; eauto. eapply senv_saturated_openq. apply senv_saturated_qqplus.\n               1,4,6 : eapply weaken_store_senv_saturated; eauto. 1,2 : eapply has_type_senv_saturated; eauto. eauto.\n               apply closed_qual_qqplus. 1,3 : eapply closed_qual_monotone; eauto. eauto.\n          -- (* d2 not dependent on f *) apply (Preserve Σ' ∅); auto. rewrite qqplus_qbot_right_neutral.\n             replace (d2 <~ᵈ df; d1) with (d2 <~ᵈ df ⋓ d'; d1).\n             eapply t_app_fresh with (T1:=T1) (df':=((df' ⋓ d'))); eauto.\n             erewrite <- @qqcap_fresh_l with (Σ':=Σ'); eauto.\n             eapply weaken_flt. eapply weaken_store; eauto. auto. auto.\n             eapply subqual_trans; eauto. 2:  apply qqplus_bound; eauto.\n             1,2 : eapply subqual_trans; eauto. 2 : apply saturated_qqplus; eauto.\n             1,2 : eapply weaken_store_saturated; eauto. eapply weaken_store_senv_saturated; eauto.\n             eapply openq_subqual_0_false; auto.\n        * (* df not fresh *) rewrite not_fresh_qqplus in H34; auto. apply (Preserve Σ' ∅); auto.\n          rewrite qqplus_qbot_right_neutral.\n          eapply t_app_fresh with (T1:=T1); eauto. eapply weaken_flt. eapply weaken_store; eauto. auto. auto.\n          eapply subqual_trans; eauto. 1,2 : eapply subqual_trans; eauto.\n          1,2 : eapply weaken_store_saturated; eauto. eapply weaken_store_senv_saturated; eauto.\n\n    + (*tref*) subst. intuition. specialize (has_type_closed H) as HH. intuition. specialize (H8 T t). intuition.\n      * (*contraction*) right. intros.\n        exists (tloc (‖σ‖)). exists (t :: σ). intuition.\n        econstructor; eauto. apply (Preserve ((T,d1) :: Σ) (d1 ⊔ &!‖σ‖)); auto.\n        apply wf_senv_cons; auto. eapply has_type_senv_saturated; eauto.\n        eapply CtxOK_weaken_flt. apply CtxOK_ext; auto. apply H8. all: auto.\n        inversion H8. rewrite <- H13. eapply disj_loc; eauto. eapply has_type_senv_saturated; eauto.\n        inversion H8. rewrite qqplus_fresh; auto. rewrite qlub_assoc. rewrite <- @qlub_assoc with (q1:={♦}). rewrite qlub_idem.\n        apply t_sub with (T1:=TRef d1 T) (d1:=(d1 ⊔ &!‖σ‖)).\n        apply t_loc; auto. rewrite <- H13.\n        apply indexr_head. simpl. eapply closed_qual_monotone; eauto. simpl. intuition; try fnsetdec.\n        unfold dom. simpl. rewrite H13. fnsetdec.\n        apply has_type_filter in H. eapply subqual_trans; eauto.\n        apply stp_refl; auto. constructor; auto. simpl. eapply closed_qual_monotone; eauto.\n        constructor.  auto. repeat apply closed_qual_qlub; auto.\n        simpl. eapply closed_qual_monotone; eauto.\n        apply just_loc_closed. rewrite <- H13. auto.\n        rewrite <- qlub_assoc. eapply @disjointq_ldom' with (Σ:=Σ) (d:={♦} ⊔ d1); eauto. rewrite <- H13. eapply disj_loc; eauto.\n        eapply has_type_senv_saturated; eauto.\n        rewrite <- qlub_assoc. apply saturated_senv_qlub; auto.\n        eapply wf_senv_saturated_qplus. apply wf_senv_cons; eauto. eapply has_type_senv_saturated; eauto.\n        rewrite <- H13. rewrite indexr_head. eauto.\n      * (*congruence*) right. intros. specialize (H11 σ H8). destruct H11 as [t' [σ' HH10]].\n        exists (tref t'). exists σ'. intuition. econstructor; eauto.\n        destruct H13. apply (Preserve Σ' ∅); intuition. rewrite qqplus_qbot_right_neutral.\n        rewrite not_fresh_qqplus in H17; auto.\n\n    + (*tderef*) subst. intuition. specialize (has_type_closed H) as HH. intuition. specialize (H8 (TRef d1 T0) t). intuition.\n      * (* contraction *) right. intros. pose (HV := H). apply has_type_vtp in HV; intuition.\n\n        specialize (vtp_canonical_form_loc HV) as Hcan. intuition. destruct H13 as [l HH10]. subst.\n\n        pose (HHV := HV). inversion HHV. subst.  pose (HH3 := H8). inversion HH3. subst.\n        pose (HH14 := H19). apply indexr_var_some' in HH14. rewrite H13 in HH14. apply indexr_var_some in HH14.\n        destruct HH14 as [v HHH14].  exists v. exists σ. intuition. apply step_deref; intuition.\n        apply (Preserve Σ ∅); intuition. rewrite qqplus_qbot_right_neutral.\n        specialize (H14 l v T d1). apply t_sub with (T1 := T)(d1:= d1); auto. intuition.\n        replace (d1) with (∅ ⊔ d1); auto. apply stp_scale_qlub; auto. eapply weaken_stp_store_ext; eauto.\n\n      * (*congruence *) right. intros. specialize (H11 σ H8).\n        destruct H11 as [t' [σ' HH8]]. exists (tderef t'). exists σ'. intuition. constructor; auto.\n        destruct H13. apply (Preserve Σ' ∅); intuition. rewrite qqplus_qbot_right_neutral. eapply t_deref; eauto.\n        eapply subqual_trans; eauto. eapply weaken_store_senv_saturated; eauto.\n\n    + (*tassign*) subst. intuition. rename H into Ht1. rename H0 into Ht2. intuition.\n      apply has_type_closed in Ht1 as Ht1C. intuition.\n      apply has_type_closed in Ht2 as Ht2C. intuition.\n      specialize (H8 (TRef d1 T) t1). intuition.\n      specialize (H5 T t2). intuition.\n      * (* contraction *)\n        right. intros.\n        pose (Ht1' := Ht1). eapply has_type_vtp in Ht1'; eauto.\n        pose (Hloc := Ht1'). apply vtp_canonical_form_loc in Hloc; auto.\n        inversion Ht1'. destruct Hloc. subst.\n        pose (Ht2' := Ht2). apply has_type_vtp in Ht2'; auto.\n        exists tunit. exists (update σ x t2). inversion H25. subst.\n        inversion H5. subst. specialize (indexr_var_some' H20) as HH20. intuition.\n        econstructor; eauto. rewrite <- H15. auto. apply (Preserve Σ ∅); auto.\n        eapply CtxOK_update; eauto. rewrite <- H15. auto. apply t_sub with (T1:=T) (d1:=d1); auto.\n        replace (d1) with (∅ ⊔ d1); auto. apply stp_scale_qlub; auto.\n        eapply weaken_stp_store_ext; eauto. apply has_type_filter in Ht2; auto.\n        eapply has_type_senv_saturated; eauto.\n      * (* right congruence *)\n        right. intros. specialize (H8 σ H5). destruct H8 as [t' [σ' H4']].\n        exists (tassign t1 t'). exists σ'. intuition. econstructor; eauto.\n        pose (HV := Ht1). apply has_type_vtp in HV; intuition. inversion HV; subst.\n        destruct H15. apply (Preserve Σ' ∅); eauto. rewrite not_fresh_qqplus in H26; auto. simpl.\n        eapply t_assign; eauto. eapply weaken_flt. eapply weaken_store; eauto. auto. auto.\n      * (* left congruence *)\n        right. intros. specialize (H13 σ H8). destruct H13 as [t' [σ' H12']].\n        exists (tassign t' t2). exists σ'. intuition. econstructor; eauto.\n        destruct H15. apply (Preserve Σ' ∅); eauto. simpl.\n        eapply t_assign; eauto. eapply weaken_flt. eapply weaken_store; eauto.\n        all: auto.\n\n    + (*t_sub*) subst. intuition. specialize (stp_closed H0) as H00. intuition.\n      specialize (H8 T1 t). intuition. right.\n      intros. specialize (H11 σ H8). destruct H11 as [t' [σ' HH8]]. exists t'. exists σ'. intuition.\n      destruct H13. apply (Preserve Σ' d'); intuition. eapply disjointq_scale; eauto. apply stp_qstp_inv in H0.\n      apply qstp_empty in H0. auto. eapply t_sub; eauto. apply stp_scale_qqplus.\n      eapply weaken_stp_store_ext; eauto. eapply disjointq_closed; eauto.\n      apply qqplus_bound. eapply subqual_trans; eauto. eapply disjointq_ldom; eauto.\n      apply senv_saturated_qqplus; eauto. eapply weaken_store_senv_saturated; eauto.\nQed.\n\n(* To show preservation_of_separation, we derive progress & preservation from type safety: *)\n\n(* This requires proving that the reduction relation is deterministic. *)\nLemma step_deterministic:  deterministic step.\n  unfold deterministic. intros t t1 t2 σ σ1 σ2 Hstep1 Hstep2. generalize dependent σ2. generalize dependent t2.\n  induction Hstep1; intros; inversion Hstep2; subst; auto; try solve [match goal with\n  | [ H : step _ _ _ _  |- _ ] => eapply values_stuck in H; eauto; contradiction (* stuck cases, contradiction *)\n  | [ H1 : step ?t ?s ?t' ?s', (* congruence cases, use IH *)\n      IH : forall _ _, step ?t ?s _ _ -> _ |- _ = _ /\\ _ = ?s' ] => specialize (IH t' s'); intuition; f_equal; auto\n  end].\n  rewrite H1 in H. inversion H. subst. intuition.\nQed.\n\nLemma progress : forall {Σ t T d},\n    has_type [] (ldom Σ) Σ t T d -> wf_senv Σ ->\n    value t \\/ forall {σ}, CtxOK [] (ldom Σ) Σ σ -> exists t' σ', step t σ t' σ'.\nProof. intros Σ t T d HT Hwf.\n       specialize (type_safety HT). intuition. right. intros σ HCtxOK.\n       specialize (H σ). intuition. destruct H0 as [t' [σ' [Hstep  HPreserve]]].\n       exists t'. exists σ'. intuition.\nQed.\n\nLemma preservation : forall {Σ t T d},\n    has_type [] (ldom Σ) Σ t T d -> wf_senv Σ ->\n    forall{σ}, CtxOK [] (ldom Σ) Σ σ ->\n    forall {t' σ'}, step t σ t' σ' ->\n    preserve [] Σ t' T d σ'.\nProof.  intros Σ t T d HT Hwf σ  HCtxOK t' σ' HStep.  specialize (type_safety HT). intuition.\n  + inversion HStep; subst; inversion H.\n  + specialize (H σ HCtxOK). destruct H as [t'' [σ'' [HStep2 HPreserve]]].\n    assert (t'' = t' /\\ σ' = σ''). { intuition. 1,2: eapply step_deterministic; eauto.  }\n    intuition. subst. intuition.\nQed.\n\nCorollary preservation_of_separation : forall {Σ t1 T1 q1 t2 T2 q2},\n  has_type [] (ldom Σ) Σ t1 T1 q1 ->\n  has_type [] (ldom Σ) Σ t2 T2 q2 -> wf_senv Σ -> q1 ⋒ q2 ⊑ {♦} ->\n    forall{σ}, CtxOK [] (ldom Σ) Σ σ ->\n      forall {t1' σ'}, step t1 σ t1' σ' ->\n      forall {t2' σ''}, step t2 σ' t2' σ'' -> separate Σ t1' T1 t2' T2.\n  intros Σ t1 T1 q1 t2 T2 q2 HT1 HT2 Hwf Hsep σ HOK t1' σ' Hstep1 t2' σ'' Hstep2.\n  (* execute preservation in sequence *)\n  specialize (preservation HT1 Hwf HOK Hstep1) as P1. destruct P1 as [Σ' d1 Hext1 Hwf' HOK' Hdisj1 HT1'].\n  assert (HT2': has_type [] (ldom Σ') Σ' t2 T2 q2). {\n    eapply weaken_flt. eapply weaken_store. eauto. auto. apply extends_ldom; auto. auto.\n  }\n  specialize (preservation HT2' Hwf' HOK' Hstep2) as P2. destruct P2 as [Σ'' d2 Hext2 Hwf'' HOK'' Hdisj2 HT2''].\n  apply (Separate Σ' Σ'' (q1 ⋓ d1) (q2 ⋓ d2) Hext1 Hext2 HT1' HT2'').\n  (* now we just need to show that the disjointness is preserved. this is intuitively true from the disjointness\n     of the heap effects d1 and d2. *)\n  erewrite <- @qqcap_fresh_r; eauto. erewrite <- qqcap_fresh_l; eauto.\n  apply has_type_closed in HT1. intuition. eauto.\n  apply has_type_closed in HT2. intuition. eauto.\n  apply closed_qual_qqplus. apply has_type_closed in HT1. intuition.\n  eapply closed_qual_monotone; eauto. eapply disjointq_closed; eauto.\n  apply has_type_closed in HT2. intuition. eapply closed_qual_monotone; eauto.\n  (* finally, the qualifiers are completely saturated, i.e., the results indeed have fully disjoint object graphs  *)\n  all : apply senv_saturated_qqplus; eauto.\n  apply has_type_senv_saturated in HT1; auto. eapply weaken_store_senv_saturated; eauto.\n  eapply weaken_store_senv_saturated; eauto.\n  apply has_type_senv_saturated in HT2; auto. eapply weaken_store_senv_saturated; eauto.\nQed.\n", "meta": {"author": "TiarkRompf", "repo": "reachability", "sha": "cd74e18bb14bcd4590a7e4282d610d734efda2c6", "save_path": "github-repos/coq/TiarkRompf-reachability", "path": "github-repos/coq/TiarkRompf-reachability/reachability-cd74e18bb14bcd4590a7e4282d610d734efda2c6/polymorphism/lambda_diamond_base/lambda_diamond.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.5, "lm_q1q2_score": 0.25976066097604644}}
{"text": "(******************************************************************************)\n(* Copyright (c) 2020 Steven Keuchel, Dominique Devriese                      *)\n(* All rights reserved.                                                       *)\n(*                                                                            *)\n(* Redistribution and use in source and binary forms, with or without         *)\n(* modification, are permitted provided that the following conditions are     *)\n(* met:                                                                       *)\n(*                                                                            *)\n(* 1. Redistributions of source code must retain the above copyright notice,  *)\n(*    this list of conditions and the following disclaimer.                   *)\n(*                                                                            *)\n(* 2. Redistributions in binary form must reproduce the above copyright       *)\n(*    notice, this list of conditions and the following disclaimer in the     *)\n(*    documentation and/or other materials provided with the distribution.    *)\n(*                                                                            *)\n(* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS        *)\n(* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED  *)\n(* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR *)\n(* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR          *)\n(* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,      *)\n(* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,        *)\n(* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR         *)\n(* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF     *)\n(* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING       *)\n(* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS         *)\n(* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.               *)\n(******************************************************************************)\n\nFrom Coq Require Export\n     Numbers.BinNums.\nFrom Coq Require Import\n     Bool.Bool\n     Lists.List\n     NArith.NArith\n     Strings.String\n     ZArith.BinInt.\nFrom Katamaran Require Export\n     Notations.\nFrom Equations Require Import\n     Equations.\n\n(* stdpp changes a lot of flags and changes implicit arguments of standard\n   library functions and constructors. Import the module here, so that the\n   changes are consistently applied over our code base. *)\nFrom stdpp Require\n     base countable finite list.\n\nLocal Set Implicit Arguments.\n\nSection Equality.\n\n  Definition EqbSpecPoint {A} (eqb : A -> A -> bool) (x : A) : Type :=\n    forall y, reflect (x = y) (eqb x y).\n\n  Definition f_equal2' {A : Type} {B : A -> Type} {C : Type} (f : forall a, B a -> C)\n    {a1 a2 : A} {b1 : B a1} {b2 : B a2} :\n    sigmaI B a1 b1 = sigmaI B a2 b2 -> f a1 b1 = f a2 b2 :=\n    DepElim.eq_simplification_sigma1_dep a1 a2 b1 b2\n      (fun e => match e with eq_refl => fun b eb => f_equal (f a1) eb end b2).\n\n  Definition f_equal_dec {A B : Type} (f : A -> B) {x y : A} (inj : f x = f y -> x = y)\n             (hyp : dec_eq x y) : dec_eq (f x) (f y) :=\n    match hyp with\n    | left p => left (f_equal f p)\n    | right p => right (fun e : f x = f y => p (inj e))\n    end.\n\n  Definition f_equal2_dec {A1 A2 B : Type} (f : A1 -> A2 -> B) {x1 y1 : A1} {x2 y2 : A2}\n             (inj : f x1 x2 = f y1 y2 -> @sigmaI _ _ x1 x2 = @sigmaI _ _ y1 y2)\n             (hyp1 : dec_eq x1 y1) (hyp2 : dec_eq x2 y2) :\n    dec_eq (f x1 x2) (f y1 y2) :=\n    match hyp1 , hyp2 with\n    | left  p , left q  => left (eq_trans\n                                   (f_equal (f x1) q)\n                                   (f_equal (fun x => f x y2) p))\n    | left  p , right q =>\n      right (fun e => q (f_equal (@pr2 _ (fun _ => _)) (inj e)))\n    | right p , _       =>\n      right (fun e => p (f_equal (@pr1 _ (fun _ => _)) (inj e)))\n    end.\n\n  Local Set Transparent Obligations.\n\n  #[export] Instance Z_eqdec : EqDec Z := Z.eq_dec.\n  #[export] Instance string_eqdec : EqDec string := string_dec.\n  Derive NoConfusion EqDec for Empty_set.\n\n  #[export] Instance option_eqdec `{EqDec A} : EqDec (option A).\n  Proof. eqdec_proof. Defined.\n\n  Definition eq_dec_het {I} {A : I -> Type} `{eqdec : EqDec (sigT A)}\n    {i1 i2} (x1 : A i1) (x2 : A i2) : dec_eq (existT i1 x1) (existT i2 x2) :=\n    eq_dec (existT i1 x1) (existT i2 x2).\n\n  #[export] Instance EqDecision_from_EqDec `{eqdec : EqDec A} :\n    stdpp.base.EqDecision A | 10 := eqdec.\n\n  Lemma cons_inj [A] (x y : A) (xs ys : list A) :\n    x :: xs = y :: ys <-> x = y /\\ xs = ys.\n  Proof.\n    split.\n    - intros e. refine match e with eq_refl => conj eq_refl eq_refl end.\n    - intros [e1 e2]. now apply f_equal2.\n  Qed.\n\n  Lemma inl_inj [A B] (x y : A) :\n    @inl A B x = @inl A B y <-> x = y.\n  Proof.\n    split; intros e.\n    - now apply noConfusion_inv in e.\n    - now apply f_equal.\n  Qed.\n\n  Lemma inr_inj [A B] (x y : B) :\n    @inr A B x = @inr A B y <-> x = y.\n  Proof.\n    split; intros e.\n    - now apply noConfusion_inv in e.\n    - now apply f_equal.\n  Qed.\n\n  Lemma some_inj [A] (x y : A) :\n    @Some A x = @Some A y <-> x = y.\n  Proof.\n    split; intros e.\n    - now apply noConfusion_inv in e.\n    - now apply f_equal.\n  Qed.\n\nEnd Equality.\n\nLtac finite_from_eqdec :=\n  match goal with\n  | |- base.NoDup ?xs =>\n      now apply (@decidable.bool_decide_unpack _ (list.NoDup_dec xs))\n  | |- forall x : ?T, base.elem_of x _ =>\n      lazymatch T with\n      | sigT _ => intros [? []]\n      | _      => intros []\n      end;\n      apply (@decidable.bool_decide_unpack _ (list.elem_of_list_dec _ _));\n      auto\n  end.\n\nSection Finite.\n\n  Import stdpp.finite.\n\n  #[local] Set Equations With UIP.\n  #[export,program] Instance Finite_sigT (A : Type) {eqA : EqDec A} {finA : Finite A}\n    (B : A -> Type) {eqB : forall x, EqDec (B x)} {finB : forall x, Finite (B x)} :\n    Finite {x : A & B x} :=\n    {| enum := foldr (fun a xs => map (existT a) (enum (B a)) ++ xs) [] (enum A) |}.\n  Next Obligation.\n  Proof.\n    intros A eqA finA B eqB finB.\n    generalize (NoDup_enum A).\n    generalize (enum A) as xs.\n    induction xs; cbn.\n    - intros _. constructor.\n    - intros [HaIn NDxs]%NoDup_cons.\n      apply NoDup_app. split; [|split].\n      + apply NoDup_fmap. intros x y Heq.\n        now dependent elimination Heq.\n        apply NoDup_enum.\n      + intros [a' b'] (b & Heq & HbIn)%elem_of_list_fmap.\n        dependent elimination Heq.\n        intros HxIn. apply HaIn.\n        { clear - HxIn.\n          induction xs; cbn in *.\n          - inversion HxIn.\n          - apply elem_of_app in HxIn.\n            destruct HxIn as [HxIn|HxIn].\n            + apply elem_of_list_fmap in HxIn.\n              destruct HxIn as (b & Heq & HbIn).\n              dependent elimination Heq.\n              constructor.\n            + constructor.\n              now apply IHxs.\n        }\n      + now apply IHxs.\n  Qed.\n  Next Obligation.\n  Proof.\n    intros A eqA finA B eqB finB.\n    intros [a b].\n    generalize (elem_of_enum a).\n    generalize (enum A) as xs. clear - finB.\n    induction xs; cbn.\n    - intros []%not_elem_of_nil.\n    - intros [Ha|Ha]%elem_of_cons.\n      + clear - Ha.\n        apply elem_of_app. left. subst.\n        apply elem_of_list_fmap_1.\n        apply elem_of_enum.\n      + apply elem_of_app. right.\n        now apply IHxs.\n  Qed.\n\n  Lemma nodup_fixed `{EqDec A} (l : list A) : nodup eq_dec l = l -> NoDup l.\n  Proof.\n    intros <-.\n    apply NoDup_ListNoDup.\n    apply NoDup_nodup.\n  Qed.\n\n  #[local] Obligation Tactic := finite_from_eqdec.\n\n  (* To avoid some coherence issues, we define our own Finite instance for bool\n     that uses the EqDEc instance from the Equations library instead of the\n     EqDecision instance from stdpp. *)\n  #[export,program] Instance Finite_bool :\n    @Finite bool EqDecision_from_EqDec :=\n    {| enum := [true;false] |}.\n\nEnd Finite.\n\nDefinition proof_irrelevance_True (p q : True) : p = q :=\n  match p, q with I , I => eq_refl end.\n\nDefinition proof_irrelevance_is_true {b : bool} :\n  forall (p q : Is_true b), p = q :=\n  match b with\n  | true  => proof_irrelevance_True\n  | false => fun p => False_rect _ p\n  end.\n\n(* We define our own variant of a boolean 'is true' predicate to turn it into\n   a typeclass and fill it in automatically during typechecking. *)\nModule IsTrue.\n  Class IsTrue (b : bool) : Prop := mk { from : Is_true b }.\n  Definition proof_irrelevance {b} (p q : IsTrue b) : p = q :=\n    match p , q with\n      mk _ p , mk _ q => f_equal (mk b) (proof_irrelevance_is_true p q)\n    end.\n\n  (* Normalize proof terms, i.e. replace a potentially big proof term by the\n     unique small one. See e.g.:\n     http://poleiro.info/posts/2018-01-26-equality-in-coq.html *)\n  Definition normalize {b} : IsTrue b -> IsTrue b :=\n    match b with\n    | true  => fun _ => mk true I\n    | false => fun p => p\n    end.\n\n  Lemma normalize_identity {b} (p : IsTrue b) : normalize p = p.\n  Proof. apply proof_irrelevance. Qed.\n\n  #[global] Arguments mk [b] _, {b _}.\n  #[global] Arguments from [b] _.\n  (* Set the Hint Mode for IsTrue, so that it will only use the Hint Extern\n     below if whatever b is unified with does not contain any existential\n     variables anymore. This is mostly used in statically checking bitvector\n     sizes. Essentially we want to delay checking the constraints until it is\n     fully known, in particular when type information flows from a later program\n     position to an earlier one, e.g. for sign extension from the type\n     information from a variable reference flows to the variable declaration. *)\n  #[export] Hint Mode IsTrue + : typeclass_instances.\n  #[export] Hint Extern 10 (IsTrue ?b) =>\n    refine (@mk true I) : typeclass_instances.\n\n  (* The following two definition should never be added as instances themselves\n     because they will easily lead to exponential blowup in proof search. Only\n     use them locally in the definition of other instances. *)\n  Definition andb_l {a b} : IsTrue (a && b) -> IsTrue a :=\n    match a with\n    | true  => fun _ => @IsTrue.mk true I\n    | false => fun H => H\n    end.\n\n  Definition andb_r {a b} : IsTrue (a && b) -> IsTrue b :=\n    match b , a with\n    | true  , _     => fun _ => @IsTrue.mk true I\n    | false , true  => fun H => H\n    | false , false => fun H => H\n    end.\n\nEnd IsTrue.\nExport (hints) IsTrue.\nExport IsTrue (IsTrue).\n\nDefinition IsSome {A : Type} (m : option A) : Type :=\n  match m with\n  | Some _ => unit\n  | None   => Empty_set\n  end.\n\nDefinition fromSome {A : Type} (m : option A) : IsSome m -> A :=\n  match m return IsSome m -> A with\n  | Some a => fun _ => a\n  | None   => fun p => match p with end\n  end.\n\nSection Countable.\n\n  Import stdpp.countable.\n\n  #[export,refine] Instance Countable_sigT {A B} {EqDecA : EqDecision A} {CountA: Countable A}\n    {EqDecB : forall (a:A), EqDecision (B a)} {CountB: forall a, Countable (B a)} :\n    @Countable (sigT B) (sigma_eqdec EqDecA EqDecB)  :=\n    {| encode x := prod_encode (encode (projT1 x)) (encode (projT2 x));\n       decode p :=\n         a ← (prod_decode_fst p ≫= decode);\n         b ← (prod_decode_snd p ≫= decode);\n         mret (existT a b)\n    |}.\n  Proof.\n    abstract\n      (intros [a b];\n       rewrite prod_decode_encode_fst; cbn;\n       rewrite decode_encode, prod_decode_encode_snd;\n       cbn; now rewrite decode_encode).\n  Defined.\n\nEnd Countable.\n\nModule option.\n\n  Definition isSome {A} (m : option A) : bool :=\n    match m with Some _ => true | None => false end.\n  Definition isNone {A} (m : option A) : bool :=\n    match m with Some _ => false | None => true end.\n\n  Definition IsSome {A} (m : option A) : Prop :=\n    Is_true (isSome m).\n\n  Definition fromSome {A} (m : option A) : IsSome m -> A :=\n    match m with Some a => fun _ => a | None => fun p => match p with end end.\n\n  Definition map {A B} (f : A -> B) (o : option A) : option B :=\n    match o with Some a => Some (f a) | None => None end.\n  Definition bind {A B} (a : option A) (f : A -> option B) : option B :=\n    match a with Some x => f x | None => None end.\n  Definition comp {A B C : Type} (f : A -> option B) (g : B -> option C) :=\n    fun a => bind (f a) g.\n\n  Arguments map {A B} f !o.\n  Arguments bind {A B} !a f.\n\n  Module Import notations.\n\n    Notation \"' x <- ma ;; mb\" :=\n      (bind ma (fun x => mb))\n        (at level 80, x pattern, ma at next level, mb at level 200, right associativity,\n          format \"' x  <-  ma  ;;  mb\").\n    Notation \"x <- ma ;; mb\" :=\n      (bind ma (fun x => mb))\n        (at level 80, ma at next level, mb at level 200, right associativity).\n    Notation \"f <$> a\" := (map f a).\n    Notation \"f <*> a\" := (match f with Some g => map g a | None => None end).\n\n  End notations.\n\n  (* Easy eq patterns *)\n  Lemma map_eq_some {A B} (f : A -> B) (o : option A) (a : A) :\n    o = Some a ->\n    map f o = Some (f a).\n  Proof. now intros ->. Qed.\n\n  Lemma bind_eq_some {A B} (f : A -> option B) (o : option A) (b : B) :\n    (exists a, o = Some a /\\ f a = Some b) <->\n    bind o f = Some b.\n  Proof.\n    split.\n    - now intros (a & -> & <-).\n    - destruct o as [a|]; [ now exists a | discriminate ].\n  Qed.\n\n  (* Variant of Bool.reflect and BoolSpec for options, i.e.\n     a weakest pre without effect observation. *)\n  Inductive spec {A} (S : A -> Prop) (N : Prop) : option A -> Prop :=\n  | specSome {a : A} : S a -> spec S N (Some a)\n  | specNone         : N -> spec S N None.\n\n  (* Total correctness weakest pre for option. Arguments are inversed. *)\n  Inductive wp {A} (S : A -> Prop) : option A -> Prop :=\n  | wpSome {a : A} : S a -> wp S (Some a).\n\n  (* Partial correctness weakest pre for option. Arguments are inversed. *)\n  Inductive wlp {A} (S : A -> Prop) : option A -> Prop :=\n  | wlpSome {a : A} : S a -> wlp S (Some a)\n  | wlpNone         : wlp S None.\n\n  (* We define equivalent formulations using pattern matches and\n     logical connectives plus constructors. *)\n  Lemma spec_match {A S N} (o : option A) :\n    spec S N o <-> match o with\n                   | Some a => S a\n                   | None   => N\n                   end.\n  Proof.\n    split.\n    - intros []; auto.\n    - destruct o; now constructor.\n  Qed.\n\n  Lemma wp_match {A S} (o : option A) :\n    wp S o <-> match o with\n               | Some a => S a\n               | None   => False\n               end.\n  Proof.\n    split.\n    - intros []; auto.\n    - destruct o; [apply wpSome|contradiction].\n  Qed.\n\n  Lemma wp_exists {A} (Q : A -> Prop) (o : option A) :\n    wp Q o <-> exists a, o = Some a /\\ Q a.\n  Proof.\n    rewrite wp_match. split.\n    - destruct o; eauto; contradiction.\n    - now intros [a [-> HQ]].\n  Qed.\n\n  Lemma wlp_match {A S} (o : option A) :\n    wlp S o <-> match o with\n               | Some a => S a\n               | None   => True\n               end.\n  Proof.\n    split.\n    - intros []; auto.\n    - destruct o; auto using wlpSome, wlpNone.\n  Qed.\n\n  Lemma wlp_forall {A} (Q : A -> Prop) (o : option A) :\n    wlp Q o <-> forall a, o = Some a -> Q a.\n  Proof.\n    rewrite wlp_match. split.\n    - intros; subst; auto.\n    - destruct o; auto.\n  Qed.\n\n  Lemma spec_some {A S N} (a : A) : spec S N (Some a) <-> S a.\n  Proof. now rewrite spec_match. Qed.\n  Lemma spec_none {A S N} : @spec A S N None <-> N.\n  Proof. now rewrite spec_match. Qed.\n  Lemma wp_some {A P} (a : A) : wp P (Some a) <-> P a.\n  Proof. now rewrite wp_match. Qed.\n  Lemma wp_none {A P} : @wp A P None <-> False.\n  Proof. now rewrite wp_match. Qed.\n  Lemma wlp_some {A P} (a : A) : wlp P (Some a) <-> P a.\n  Proof. now rewrite wlp_match. Qed.\n  Lemma wlp_none {A P} : @wlp A P None <-> True.\n  Proof. now rewrite wlp_match. Qed.\n\n  Section Bind.\n\n    Context {A B} {S : B -> Prop} {N : Prop} (f : A -> option B) (o : option A).\n\n    Local Ltac proof :=\n      destruct o; rewrite ?spec_match, ?wp_match, ?wlp_match; auto.\n\n    Lemma spec_bind : spec S N (bind o f) <-> spec (fun a => spec S N (f a)) N o.\n    Proof. proof. Qed.\n    Definition spec_bind_elim := proj1 spec_bind.\n    Definition spec_bind_intro := proj2 spec_bind.\n\n    Lemma wp_bind : wp S (bind o f) <-> wp (fun a => wp S (f a)) o.\n    Proof. proof. Qed.\n    Definition wp_bind_elim := proj1 wp_bind.\n    Definition wp_bind_intro := proj2 wp_bind.\n\n    Lemma wlp_bind : wlp S (bind o f) <-> wlp (fun a => wlp S (f a)) o.\n    Proof. proof. Qed.\n\n    Definition wlp_bind_elim := proj1 wlp_bind.\n    Definition wlp_bind_intro := proj2 wlp_bind.\n\n  End Bind.\n\n  Lemma spec_map {A B S N} (f : A -> B) (o : option A) :\n    spec S N (map f o) <-> spec (fun a => S (f a)) N o.\n  Proof. do 2 rewrite spec_match; now destruct o. Qed.\n\n  Lemma spec_ap {A B S N} (f : option (A -> B)) (o : option A) :\n    spec S N (f <*> o) <->\n    spec (fun f => spec (fun a => S (f a)) N o) N f.\n  Proof.\n    do 2 rewrite spec_match. destruct f; auto.\n    rewrite spec_match; now destruct o.\n  Qed.\n\n  Lemma spec_monotonic {A} (S1 S2 : A -> Prop) (N1 N2 : Prop)\n    (fS : forall a, S1 a -> S2 a) (fN: N1 -> N2) :\n    forall (o : option A),\n      spec S1 N1 o -> spec S2 N2 o.\n  Proof. intros ? []; constructor; auto. Qed.\n\n  Lemma wp_map {A B S} (f : A -> B) (o : option A) :\n    wp S (map f o) <-> wp (fun a => S (f a)) o.\n  Proof. do 2 rewrite wp_match; now destruct o. Qed.\n\n  Lemma wp_ap {A B S} (f : option (A -> B)) (o : option A) :\n    wp S (f <*> o) <->\n    wp (fun f => wp (fun a => S (f a)) o) f.\n  Proof.\n    do 2 rewrite wp_match. destruct f; auto.\n    rewrite wp_match; now destruct o.\n  Qed.\n\n  Lemma wp_monotonic {A} (S1 S2 : A -> Prop) (fS : forall a, S1 a -> S2 a)  :\n    forall (o : option A), wp S1 o -> wp S2 o.\n  Proof. intros ? []; constructor; auto. Qed.\n\n  Lemma wlp_map {A B S} (f : A -> B) (o : option A) :\n    wlp S (map f o) <-> wlp (fun a => S (f a)) o.\n  Proof. do 2 rewrite wlp_match; now destruct o. Qed.\n\n  Lemma wlp_ap {A B S} (f : option (A -> B)) (o : option A) :\n    wlp S (f <*> o) <->\n    wlp (fun f => wlp (fun a => S (f a)) o) f.\n  Proof.\n    do 2 rewrite wlp_match. destruct f; auto.\n    rewrite wlp_match; now destruct o.\n  Qed.\n\n  Lemma wlp_monotonic {A} (S1 S2 : A -> Prop) (fS : forall a, S1 a -> S2 a)  :\n    forall (o : option A), wlp S1 o -> wlp S2 o.\n  Proof. intros ? []; constructor; auto. Qed.\n\n  Module tactics.\n\n    Ltac mixin :=\n      lazymatch goal with\n      | |- wp _ (Some _) => constructor\n      | |- wp _ (map _ _) => apply wp_map\n      | |- wp _ (bind _ _) => apply wp_bind_intro\n      | |- wp _ (_ <*> _) => apply wp_ap\n      | |- wlp _ (Some _) => constructor\n      | |- wlp _ (map _ _) => apply wlp_map\n      | |- wlp _ (bind _ _) => apply wlp_bind_intro\n      | |- wlp _ (_ <*> _) => apply wlp_ap\n      | H: wp _ ?x |- wp _ ?x => revert H; apply wp_monotonic; intros\n      | H: wlp _ ?x |- wlp _ ?x => revert H; apply wlp_monotonic; intros\n      end.\n\n  End tactics.\n\n  Section Traverse.\n    Context {A B} (f : A -> option B).\n\n    Fixpoint traverse_list (xs : list A) : option (list B) :=\n      match xs with\n      | nil       => Some nil\n      | cons x xs => b <- f x ;; bs <- traverse_list xs ;; Some (cons b bs)\n      end.\n\n    Fixpoint traverse_vector {n} (xs : Vector.t A n) : option (Vector.t B n) :=\n      match xs with\n      | Vector.nil       => Some Vector.nil\n      | Vector.cons x xs => b <- f x ;; bs <- traverse_vector xs ;; Some (Vector.cons b bs)\n      end.\n\n  End Traverse.\n\nEnd option.\n\nLemma and_iff_compat_r' (A B C : Prop) :\n  (B /\\ A <-> C /\\ A) <-> (A -> B <-> C).\nProof. intuition. Qed.\n\nLemma and_iff_compat_l' (A B C : Prop) :\n  (A /\\ B <-> A /\\ C) <-> (A -> B <-> C).\nProof. intuition. Qed.\n\nLemma imp_iff_compat_l' (A B C : Prop) :\n  ((A -> B) <-> (A -> C)) <-> (A -> B <-> C).\nProof. intuition. Qed.\n\nLemma rightid_and_true (A : Prop) :\n  A /\\ True <-> A.\nProof. intuition. Qed.\n\nLemma leftid_true_and (A : Prop) :\n  True /\\ A <-> A.\nProof. intuition. Qed.\n\nLemma exists_or_compat {A} (P Q : A -> Prop):\n  (exists a, P a \\/ Q a) <-> (exists a, P a) \\/ (exists a, Q a).\nProof. firstorder. Qed.\n\nLemma forall_and_compat {A} (P Q : A -> Prop):\n  (forall a, P a /\\ Q a) <-> (forall a, P a) /\\ (forall a, Q a).\nProof. firstorder. Qed.\n\nDeclare Scope alt_scope.\nDeclare Scope asn_scope.\nDeclare Scope exp_scope.\nDeclare Scope modal_scope.\nDeclare Scope mut_scope.\nDeclare Scope pat_scope.\nDelimit Scope alt_scope with alt.\nDelimit Scope asn_scope with asn.\nDelimit Scope exp_scope with exp.\nDelimit Scope modal_scope with modal.\nDelimit Scope mut_scope with mut.\nDelimit Scope pat_scope with pat.\n\nDefinition findAD {A} {B : A -> Type} {eqA: EqDec A} (a : A) :\n  list (sigT B) -> option (B a) :=\n  fix find (xs : list (sigT B)) : option (B a) :=\n    match xs with\n    | nil                   => None\n    | cons (existT a' b) xs =>\n        match eq_dec a a' with\n        | left e  => Some (eq_rect_r B b e)\n        | right _ => find xs\n        end\n    end.\n\nRecord Stats : Set :=\n  { branches : N\n  ; pruned   : N\n  }.\n\nDefinition plus_stats (x y : Stats) : Stats :=\n  {| branches := branches x + branches y;\n     pruned   := pruned x + pruned y\n  |}.\nDefinition empty_stats : Stats :=\n  {| branches := 0; pruned   := 0|}.\n\nCreate HintDb katamaran.\n#[global] Hint Rewrite\n  andb_true_iff andb_false_iff negb_true_iff negb_false_iff orb_true_iff\n  orb_false_iff cons_inj inl_inj inr_inj some_inj pair_equal_spec\n  : katamaran.\n#[global] Hint Rewrite\n  @option.spec_ap    @option.wlp_ap   @option.wp_ap\n  @option.spec_bind  @option.wlp_bind @option.wp_bind\n  @option.spec_map   @option.wlp_map  @option.wp_map\n  @option.spec_none  @option.wlp_none @option.wp_none\n  @option.spec_some  @option.wlp_some @option.wp_some\n  : katamaran.\n", "meta": {"author": "katamaran-project", "repo": "katamaran", "sha": "42323957548d300b4b4adb26f406cce7ebbdb75a", "save_path": "github-repos/coq/katamaran-project-katamaran", "path": "github-repos/coq/katamaran-project-katamaran/katamaran-42323957548d300b4b4adb26f406cce7ebbdb75a/theories/Prelude.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.5, "lm_q1q2_score": 0.25976066097604644}}
{"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.\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 program_t :=\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  .\n\n  Inductive t :=\n  | promise (loc:Loc.t) (from to:Time.t) (val:Const.t) (released:option View.t) (kind:Memory.op_kind)\n  | program (event:program_t)\n  .\n  Coercion ThreadEvent.program: ThreadEvent.program_t >-> ThreadEvent.t.\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:program_t) : ProgramEvent.t :=\n    match e with\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    end.\n\n  Definition get_program (e:t): option program_t :=\n    match e with\n    | promise _ _ _ _ _ _ => None\n    | program e => Some e\n    end.\n\n  Definition is_promising (e:t) : option (Loc.t * Time.t) :=\n    match e with\n    | promise loc from to v rel kind => Some (loc, to)\n    | _ => None\n    end.\n\n  Definition is_lower_none (e:t) : bool :=\n    match e with\n    | promise loc from to v rel kind => Memory.op_kind_is_lower kind && negb rel\n    | _ => false\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  Inductive le: forall (lhs rhs:t), Prop :=\n  | le_promise\n      loc from to val rel1 rel2 kind1 kind2\n      (LEREL: View.opt_le rel1 rel2):\n      le (promise loc from to val rel1 kind1) (promise loc from to val rel2 kind2)\n  | le_silent:\n      le (program silent) (program 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  .\n\n  Definition lift (ord0:Ordering.t) (e:program_t): program_t :=\n    match e with\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    end.\n\n  Lemma lift_plain e:\n    lift Ordering.plain e = e.\n  Proof. destruct e; ss. Qed.\nEnd ThreadEvent.\nCoercion ThreadEvent.program: ThreadEvent.program_t >-> ThreadEvent.t.\n\nInductive tau T (step: forall (e:ThreadEvent.t) (e1 e2:T), Prop) (e1 e2:T): Prop :=\n| tau_intro\n    e\n    (TSTEP: step e e1 e2)\n    (EVENT: ThreadEvent.get_event e = None)\n.\nHint Constructors tau.\n\nInductive union E T (step: forall (e:E) (e1 e2:T), Prop) (e1 e2:T): Prop :=\n| union_intro\n    e\n    (USTEP: step e e1 e2)\n.\nHint Constructors union.\n\nLemma tau_mon T (step1 step2: forall (e:ThreadEvent.t) (e1 e2: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) (e1 e2:T), Prop)\n      (STEP: step1 <3= step2):\n  union step1 <2= union step2.\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\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: lc.(promises) = Memory.bot)\n  .\n\n  Inductive wf (lc:t) (mem:Memory.t): Prop :=\n  | wf_intro\n      (TVIEW_WF: TView.wf lc.(tview))\n      (TVIEW_CLOSED: TView.closed lc.(tview) mem)\n      (PROMISES: Memory.le lc.(promises) mem)\n      (FINITE: Memory.finite lc.(promises))\n  .\n\n  Inductive disjoint (lc1 lc2:t): Prop :=\n  | disjoint_intro\n      (DISJOINT: Memory.disjoint lc1.(promises) lc2.(promises))\n  .\n\n  Global Program Instance disjoint_Symmetric: Symmetric disjoint.\n  Next Obligation.\n    econs. symmetry. apply H.\n  Qed.\n\n  Inductive promise_step (lc1:t) (mem1:Memory.t) (loc:Loc.t) (from to:Time.t) (val:Const.t) (released:option View.t): forall (lc2:t) (mem2:Memory.t) (kind:Memory.op_kind), Prop :=\n  | promise_step_intro\n      promises2 mem2 kind\n      (PROMISE: Memory.promise lc1.(promises) mem1 loc from to val released promises2 mem2 kind)\n      (CLOSED: Memory.closed_opt_view released mem2):\n      promise_step lc1 mem1 loc from to val released (mk lc1.(tview) promises2) mem2 kind\n  .\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): forall (lc2:t), Prop :=\n  | read_step_intro\n      from\n      tview2\n      (GET: Memory.get loc to mem1 = Some (from, Message.mk val released))\n      (READABLE: TView.readable lc1.(tview).(TView.cur) loc to released ord)\n      (TVIEW: TView.read_tview lc1.(tview) loc to released ord = tview2):\n      read_step lc1 mem1 loc to val released ord (mk tview2 lc1.(promises))\n  .\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): forall (lc2:t) (sc2:TimeMap.t) (mem2:Memory.t) (kind:Memory.op_kind), Prop :=\n  | write_step_intro\n      promises2 mem2 kind\n      (RELEASED: released = TView.write_released lc1.(tview) sc1 loc to releasedm ord)\n      (WRITABLE: TView.writable lc1.(tview).(TView.cur) sc1 loc to ord)\n      (WRITE: Memory.write lc1.(promises) mem1 loc from to val released promises2 mem2 kind)\n      (RELEASE: Ordering.le Ordering.strong_relaxed ord ->\n                Memory.nonsynch_loc loc lc1.(promises) /\\\n                kind = Memory.op_kind_add):\n      write_step lc1 sc1 mem1 loc from to val releasedm released ord\n                 (mk (TView.write_tview lc1.(tview) sc1 loc to ord) promises2)\n                 sc1 mem2 kind\n  .\n\n  Inductive fence_step (lc1:t) (sc1:TimeMap.t) (ordr ordw:Ordering.t): forall (lc2:t) (sc2:TimeMap.t), Prop :=\n  | fence_step_intro\n      tview2\n      (READ: TView.read_fence_tview lc1.(tview) ordr = tview2)\n      (RELEASE: Ordering.le Ordering.strong_relaxed ordw -> Memory.nonsynch lc1.(promises)):\n      fence_step lc1 sc1 ordr ordw (mk (TView.write_fence_tview tview2 sc1 ordw) lc1.(promises)) (TView.write_fence_sc tview2 sc1 ordw)\n  .\n\n  Inductive program_step: forall (e:ThreadEvent.t) lc1 sc1 mem1 lc2 sc2 mem2, 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  .\n\n  Lemma promise_step_future lc1 sc1 mem1 loc from to val released lc2 mem2 kind\n        (STEP: promise_step lc1 mem1 loc from to val released 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 lc1.(tview) lc2.(tview)>> /\\\n    <<REL_WF: View.opt_wf released>> /\\\n    <<REL_TS: Time.le (released.(View.unwrap).(View.rlx) loc) to>> /\\\n    <<REL_CLOSED: Memory.closed_opt_view released 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    - by inv PROMISE.\n  Qed.\n\n  Lemma read_step_future 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 lc1.(tview) lc2.(tview)>> /\\\n    <<REL_WF: View.opt_wf released>> /\\\n    <<REL_CLOSED: Memory.closed_opt_view released mem1>>.\n  Proof.\n    inv WF1. inv STEP.\n    exploit TViewFacts.read_future; eauto.\n    { eapply CLOSED1. eauto. }\n    inv CLOSED1. exploit CLOSED; eauto. i. des.\n    splits; auto.\n    - econs; eauto.\n    - apply TViewFacts.read_tview_incr.\n  Qed.\n\n  Lemma write_step_future 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 lc1.(tview) lc2.(tview)>> /\\\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 (released.(View.unwrap).(View.rlx) 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    - econs; ss.\n    - apply TViewFacts.write_tview_incr. auto.\n    - refl.\n    - inv WRITE. inv PROMISE; auto.\n  Qed.\n\n  Lemma fence_step_future 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 lc1.(tview) lc2.(tview)>> /\\\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    - econs; 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 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 lc1.(tview) lc2.(tview)>> /\\\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  Qed.\n\n  Lemma promise_step_disjoint\n        lc1 sc1 mem1 loc from to val released lc2 mem2 lc kind\n        (STEP: promise_step lc1 mem1 loc from to val released 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_future0; try apply WRITE; eauto; try by viewtac. i. des.\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    lc1.(promises) = lc2.(promises).\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  Qed.\nEnd Local.\n\n\nModule Thread.\n  Section Thread.\n    Variable (lang:language).\n\n    Structure t := mk {\n      state: lang.(Language.state);\n      local: Local.t;\n      sc: TimeMap.t;\n      memory: Memory.t;\n    }.\n\n    Inductive promise_step (pf:bool): forall (e:ThreadEvent.t) (e1 e2:t), Prop :=\n    | promise_step_intro\n        st lc1 sc1 mem1\n        loc from to val released kind\n        lc2 mem2\n        (LOCAL: Local.promise_step lc1 mem1 loc from to val released lc2 mem2 kind)\n        (PF: pf = andb (Memory.op_kind_is_lower kind) (negb released)):\n        promise_step pf (ThreadEvent.promise loc from to val released kind) (mk st lc1 sc1 mem1) (mk st lc2 sc1 mem2)\n    .\n\n    (* NOTE: Syscalls act like an SC fence.\n     *)\n    Inductive program_step (e:ThreadEvent.program_t): forall (e1 e2:t), Prop :=\n    | program_step_intro\n        st1 lc1 sc1 mem1\n        st2 lc2 sc2 mem2\n        (STATE: lang.(Language.step) (ThreadEvent.get_program_event e) st1 st2)\n        (LOCAL: Local.program_step e lc1 sc1 mem1 lc2 sc2 mem2):\n        program_step e (mk st1 lc1 sc1 mem1) (mk st2 lc2 sc2 mem2)\n    .\n    Hint Constructors program_step.\n\n    Inductive step: forall (pf:bool) (e:ThreadEvent.t) (e1 e2:t), Prop :=\n    | step_promise\n        pf e e1 e2\n        (STEP: promise_step pf e e1 e2):\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:t): 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:t), 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 consistent (e:t): Prop :=\n      forall sc1 mem1\n        (FUTURE: Memory.future e.(memory) mem1)\n        (FUTURE: TimeMap.le e.(sc) sc1)\n        (WF: Local.wf e.(local) mem1)\n        (SC: Memory.closed_timemap sc1 mem1)\n        (MEM: Memory.closed mem1),\n      exists e2,\n        <<STEPS: rtc tau_step (mk e.(state) e.(local) sc1 mem1) e2>> /\\\n        <<PROMISES: e2.(local).(Local.promises) = Memory.bot>>.\n\n    Lemma promise_step_future\n          pf e e1 e2\n          (STEP: promise_step pf e e1 e2)\n          (WF1: Local.wf e1.(local) e1.(memory))\n          (SC1: Memory.closed_timemap e1.(sc) e1.(memory))\n          (CLOSED1: Memory.closed e1.(memory)):\n      <<WF2: Local.wf e2.(local) e2.(memory)>> /\\\n      <<SC2: Memory.closed_timemap e2.(sc) e2.(memory)>> /\\\n      <<CLOSED2: Memory.closed e2.(memory)>> /\\\n      <<TVIEW_FUTURE: TView.le e1.(Thread.local).(Local.tview) e2.(Thread.local).(Local.tview)>> /\\\n      <<SC_FUTURE: TimeMap.le e1.(sc) e2.(sc)>> /\\\n      <<MEM_FUTURE: Memory.future e1.(memory) e2.(memory)>>.\n    Proof.\n      inv STEP. ss.\n      exploit Local.promise_step_future; eauto. i. des.\n      splits; eauto. refl.\n    Qed.\n\n    Lemma program_step_future e e1 e2\n          (STEP: program_step e e1 e2)\n          (WF1: Local.wf e1.(local) e1.(memory))\n          (SC1: Memory.closed_timemap e1.(sc) e1.(memory))\n          (CLOSED1: Memory.closed e1.(memory)):\n      <<WF2: Local.wf e2.(local) e2.(memory)>> /\\\n      <<SC2: Memory.closed_timemap e2.(sc) e2.(memory)>> /\\\n      <<CLOSED2: Memory.closed e2.(memory)>> /\\\n      <<TVIEW_FUTURE: TView.le e1.(Thread.local).(Local.tview) e2.(Thread.local).(Local.tview)>> /\\\n      <<SC_FUTURE: TimeMap.le e1.(sc) e2.(sc)>> /\\\n      <<MEM_FUTURE: Memory.future e1.(memory) e2.(memory)>>.\n    Proof.\n      inv STEP. ss. eapply Local.program_step_future; eauto.\n    Qed.\n\n    Lemma step_future pf e e1 e2\n          (STEP: step pf e e1 e2)\n          (WF1: Local.wf e1.(local) e1.(memory))\n          (SC1: Memory.closed_timemap e1.(sc) e1.(memory))\n          (CLOSED1: Memory.closed e1.(memory)):\n      <<WF2: Local.wf e2.(local) e2.(memory)>> /\\\n      <<SC2: Memory.closed_timemap e2.(sc) e2.(memory)>> /\\\n      <<CLOSED2: Memory.closed e2.(memory)>> /\\\n      <<TVIEW_FUTURE: TView.le e1.(Thread.local).(Local.tview) e2.(Thread.local).(Local.tview)>> /\\\n      <<SC_FUTURE: TimeMap.le e1.(sc) e2.(sc)>> /\\\n      <<MEM_FUTURE: Memory.future e1.(memory) e2.(memory)>>.\n    Proof.\n      inv STEP.\n      - eapply promise_step_future; eauto.\n      - eapply program_step_future; eauto.\n    Qed.\n\n    Lemma step_nonpf_future e e1 e2\n          (STEP: step false e e1 e2)\n          (WF1: Local.wf e1.(local) e1.(memory))\n          (SC1: Memory.closed_timemap e1.(sc) e1.(memory))\n          (CLOSED1: Memory.closed e1.(memory)):\n      <<WF2: Local.wf e2.(local) e2.(memory)>> /\\\n      <<SC2: Memory.closed_timemap e2.(sc) e2.(memory)>> /\\\n      <<CLOSED2: Memory.closed e2.(memory)>> /\\\n      <<TVIEW_FUTURE: TView.le e1.(local).(Local.tview) e2.(local).(Local.tview)>> /\\\n      <<SC_FUTURE: TimeMap.le e1.(sc) e2.(sc)>> /\\\n      <<MEM_FUTURE: Memory.future e1.(memory) e2.(memory)>> /\\\n      <<STATE: e1.(state) = e2.(state)>>.\n    Proof.\n      inv STEP. inv STEP0. ss.\n      exploit Local.promise_step_future; eauto. i. des.\n      esplits; ss. refl.\n    Qed.\n\n    Lemma opt_step_future e e1 e2\n          (STEP: opt_step e e1 e2)\n          (WF1: Local.wf e1.(local) e1.(memory))\n          (SC1: Memory.closed_timemap e1.(sc) e1.(memory))\n          (CLOSED1: Memory.closed e1.(memory)):\n      <<WF2: Local.wf e2.(local) e2.(memory)>> /\\\n      <<SC2: Memory.closed_timemap e2.(sc) e2.(memory)>> /\\\n      <<CLOSED2: Memory.closed e2.(memory)>> /\\\n      <<TVIEW_FUTURE: TView.le e1.(Thread.local).(Local.tview) e2.(Thread.local).(Local.tview)>> /\\\n      <<SC_FUTURE: TimeMap.le e1.(sc) e2.(sc)>> /\\\n      <<MEM_FUTURE: Memory.future e1.(memory) e2.(memory)>>.\n    Proof.\n      inv STEP.\n      - esplits; eauto; refl.\n      - eapply step_future; eauto.\n    Qed.\n\n    Lemma rtc_all_step_future e1 e2\n          (STEP: rtc all_step e1 e2)\n          (WF1: Local.wf e1.(local) e1.(memory))\n          (SC1: Memory.closed_timemap e1.(sc) e1.(memory))\n          (CLOSED1: Memory.closed e1.(memory)):\n      <<WF2: Local.wf e2.(local) e2.(memory)>> /\\\n      <<SC2: Memory.closed_timemap e2.(sc) e2.(memory)>> /\\\n      <<CLOSED2: Memory.closed e2.(memory)>> /\\\n      <<TVIEW_FUTURE: TView.le e1.(Thread.local).(Local.tview) e2.(Thread.local).(Local.tview)>> /\\\n      <<SC_FUTURE: TimeMap.le e1.(sc) e2.(sc)>> /\\\n      <<MEM_FUTURE: Memory.future e1.(memory) e2.(memory)>>.\n    Proof.\n      revert WF1. induction STEP.\n      - i. splits; ss; refl.\n      - i. inv H. inv USTEP.\n        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 e1 e2\n          (STEP: rtc tau_step e1 e2)\n          (WF1: Local.wf e1.(local) e1.(memory))\n          (SC1: Memory.closed_timemap e1.(sc) e1.(memory))\n          (CLOSED1: Memory.closed e1.(memory)):\n      <<WF2: Local.wf e2.(local) e2.(memory)>> /\\\n      <<SC2: Memory.closed_timemap e2.(sc) e2.(memory)>> /\\\n      <<CLOSED2: Memory.closed e2.(memory)>> /\\\n      <<TVIEW_FUTURE: TView.le e1.(Thread.local).(Local.tview) e2.(Thread.local).(Local.tview)>> /\\\n      <<SC_FUTURE: TimeMap.le e1.(sc) e2.(sc)>> /\\\n      <<MEM_FUTURE: Memory.future e1.(memory) e2.(memory)>>.\n    Proof.\n      apply rtc_all_step_future; auto.\n      eapply rtc_implies; [|eauto].\n      apply tau_union.\n    Qed.\n\n    Lemma rtc_step_nonpf_future e1 e2\n          (STEP: rtc (union (step false)) e1 e2)\n          (WF1: Local.wf e1.(local) e1.(memory))\n          (SC1: Memory.closed_timemap e1.(sc) e1.(memory))\n          (CLOSED1: Memory.closed e1.(memory)):\n      <<WF2: Local.wf e2.(local) e2.(memory)>> /\\\n      <<SC2: Memory.closed_timemap e2.(sc) e2.(memory)>> /\\\n      <<CLOSED2: Memory.closed e2.(memory)>> /\\\n      <<TVIEW_FUTURE: TView.le e1.(local).(Local.tview) e2.(local).(Local.tview)>> /\\\n      <<SC_FUTURE: TimeMap.le e1.(sc) e2.(sc)>> /\\\n      <<MEM_FUTURE: Memory.future e1.(memory) e2.(memory)>> /\\\n      <<STATE: e1.(state) = e2.(state)>>.\n    Proof.\n      revert WF1. induction STEP.\n      - i. splits; ss; refl.\n      - inv H. i. exploit step_nonpf_future; eauto. i. des.\n        exploit IHSTEP; eauto. i. des.\n        splits; ss; etrans; eauto.\n    Qed.\n\n    Lemma promise_step_disjoint\n          pf e e1 e2 lc\n        (STEP: promise_step pf e e1 e2)\n        (WF1: Local.wf e1.(local) e1.(memory))\n        (SC1: Memory.closed_timemap e1.(sc) e1.(memory))\n        (CLOSED1: Memory.closed e1.(memory))\n        (DISJOINT1: Local.disjoint e1.(local) lc)\n        (WF: Local.wf lc e1.(memory)):\n      <<DISJOINT2: Local.disjoint e2.(local) lc>> /\\\n      <<WF: Local.wf lc e2.(memory)>>.\n    Proof.\n      inv STEP.\n      exploit Local.promise_step_future; eauto. i. des.\n      exploit Local.promise_step_disjoint; eauto.\n    Qed.\n\n    Lemma program_step_disjoint e e1 e2 lc\n        (STEP: program_step e e1 e2)\n        (WF1: Local.wf e1.(local) e1.(memory))\n        (SC1: Memory.closed_timemap e1.(sc) e1.(memory))\n        (CLOSED1: Memory.closed e1.(memory))\n        (DISJOINT1: Local.disjoint e1.(local) lc)\n        (WF: Local.wf lc e1.(memory)):\n      <<DISJOINT2: Local.disjoint e2.(local) lc>> /\\\n      <<WF: Local.wf lc e2.(memory)>>.\n    Proof.\n      inv STEP. ss. eapply Local.program_step_disjoint; eauto.\n    Qed.\n\n    Lemma step_disjoint pf e e1 e2 lc\n        (STEP: step pf e e1 e2)\n        (WF1: Local.wf e1.(local) e1.(memory))\n        (SC1: Memory.closed_timemap e1.(sc) e1.(memory))\n        (CLOSED1: Memory.closed e1.(memory))\n        (DISJOINT1: Local.disjoint e1.(local) lc)\n        (WF: Local.wf lc e1.(memory)):\n      <<DISJOINT2: Local.disjoint e2.(local) lc>> /\\\n      <<WF: Local.wf lc e2.(memory)>>.\n    Proof.\n      inv STEP.\n      - eapply promise_step_disjoint; eauto.\n      - eapply program_step_disjoint; eauto.\n    Qed.\n\n    Lemma opt_step_disjoint e e1 e2 lc\n        (STEP: opt_step e e1 e2)\n        (WF1: Local.wf e1.(local) e1.(memory))\n        (SC1: Memory.closed_timemap e1.(sc) e1.(memory))\n        (CLOSED1: Memory.closed e1.(memory))\n        (DISJOINT1: Local.disjoint e1.(local) lc)\n        (WF: Local.wf lc e1.(memory)):\n      <<DISJOINT2: Local.disjoint e2.(local) lc>> /\\\n      <<WF: Local.wf lc e2.(memory)>>.\n    Proof.\n      inv STEP.\n      - esplits; eauto.\n      - eapply step_disjoint; eauto.\n    Qed.\n\n    Lemma rtc_all_step_disjoint e1 e2 lc\n        (STEP: rtc all_step e1 e2)\n        (WF1: Local.wf e1.(local) e1.(memory))\n        (SC1: Memory.closed_timemap e1.(sc) e1.(memory))\n        (CLOSED1: Memory.closed e1.(memory))\n        (DISJOINT1: Local.disjoint e1.(local) lc)\n        (WF: Local.wf lc e1.(memory)):\n      <<DISJOINT2: Local.disjoint e2.(local) lc>> /\\\n      <<WF: Local.wf lc e2.(memory)>>.\n    Proof.\n      revert WF1 DISJOINT1 WF. induction STEP; eauto. i.\n      inv H. inv USTEP.\n      exploit step_future; eauto. i. des.\n      exploit step_disjoint; eauto. i. des.\n      exploit IHSTEP; eauto.\n    Qed.\n\n    Lemma rtc_tau_step_disjoint e1 e2 lc\n        (STEP: rtc tau_step e1 e2)\n        (WF1: Local.wf e1.(local) e1.(memory))\n        (SC1: Memory.closed_timemap e1.(sc) e1.(memory))\n        (CLOSED1: Memory.closed e1.(memory))\n        (DISJOINT1: Local.disjoint e1.(local) lc)\n        (WF: Local.wf lc e1.(memory)):\n      <<DISJOINT2: Local.disjoint e2.(local) lc>> /\\\n      <<WF: Local.wf lc e2.(memory)>>.\n    Proof.\n      eapply rtc_all_step_disjoint; cycle 1; eauto.\n      eapply rtc_implies; [|eauto].\n      apply tau_union.\n    Qed.\n  End Thread.\nEnd Thread.\n\nLemma promise_pf_inv\n      (kind:Memory.op_kind)\n      (released:option View.t)\n      (PF: (Memory.op_kind_is_lower kind) && (negb released)):\n  exists released0, kind = Memory.op_kind_lower released0 /\\\n               released = None.\nProof.\n  apply andb_true_iff in PF. des.\n  destruct kind; inv PF. destruct released; inv PF0.\n  esplits; eauto.\nQed.\n\nLemma promise_pf_false_inv\n      (kind:Memory.op_kind)\n      (released:option View.t)\n      (PF: false = (Memory.op_kind_is_lower kind) && (negb released)):\n  Memory.op_kind_is_lower kind = false \\/ released <> None.\nProof.\n  symmetry in PF. apply andb_false_iff in PF. des; auto.\n  destruct released; ss. right. 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/lang/Thread.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.25969672292608315}}
{"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 O E Eprime S U1 A AX B BX C CX BXMAX CXMAX AB AC IAC T A1 A2 BXprimeprime CXprime ABXprimeprime ACXprimeprime : Universe, ((wd_ A B /\\ (wd_ A C /\\ (wd_ B C /\\ (wd_ A1 A2 /\\ (wd_ C CXprime /\\ (wd_ B BXprimeprime /\\ (wd_ A BXprimeprime /\\ (wd_ O E /\\ (wd_ E Eprime /\\ (wd_ O Eprime /\\ (wd_ S U1 /\\ (col_ O E AX /\\ (col_ O E BX /\\ (col_ O E CX /\\ (col_ O E BXMAX /\\ (col_ O E CXMAX /\\ (col_ O E T /\\ (col_ O E AB /\\ (col_ O E AC /\\ (col_ O E IAC /\\ (col_ A A1 A2 /\\ (col_ O E ABXprimeprime /\\ (col_ O E ACXprimeprime /\\ (col_ A1 A2 BXprimeprime /\\ (col_ S U1 B /\\ (col_ A1 A2 C /\\ (col_ S U1 CXprime /\\ col_ A B C))))))))))))))))))))))))))) -> col_ A B BXprimeprime)).\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_1448.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.2596768842891618}}
{"text": "(* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% *) \n(* Module with Certified Checking \n   of Single-Pass Module.\n  \n   Last Update: Wed, 24 May 2017\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% *) \n\nAdd LoadPath \"../..\".\n\nRequire Import ConceptParams.AuxTactics.LibTactics.\nRequire Import ConceptParams.AuxTactics.BasicTactics.\n\nRequire Import ConceptParams.SetMapLib.List2Set.\nRequire Import ConceptParams.SetMapLib.ListPair2FMap.\n\nRequire Import ConceptParams.GenericModuleLib.SharedDataDefs.\n\nRequire Import Coq.Lists.List.\nImport ListNotations.\nRequire Import Coq.Bool.Bool.\n\nRequire Import Coq.Structures.Orders.\nRequire Import Coq.Structures.Equalities.\n\n(* ***************************************************************** *)\n(** * Single-Pass Module *)\n\n(** Single-Pass Module is well-defined if\n    all names are different \n    and all members are well-defined with following elements\n      refering to the previously defined ones via local context. *)\n(* ***************************************************************** *)\n(* ***************************************************************** *)\n\n(* ################################################################# *)\n(** ** Shared Parameters of all building blocks *)\n(* ################################################################# *)\n\nModule Type SinglePassModuleBase.\n  Include ModuleBase.\n\n  Declare Module MD : DataLC.\n  Import MD.\n\n  (** Initial local context *)\n  Parameter ctxl_init : ctxloc.\n  (** Update local context *)\n  Parameter upd_ctxloc : ctxloc -> ctx -> id -> t -> ctxloc.\nEnd SinglePassModuleBase.\n\n\n(* ################################################################# *)\n(** ** Propositional Part *)\n(* ################################################################# *)\n\nModule SinglePassModuleDefs (Import MMB : SinglePassModuleBase) \n       (Import TOkD : DataLCOkDef MMB.MD).\n\n  Module HelperD.\n    Export MD.\n    Definition dt := t.\n\n    (** We can use generic implementation of single-pass module\n        checking from the SharedDataDefs.\n        For this we need several aux functions. *)\n\n    Definition update_prop (ok : Prop) (c : ctx) \n               (cl : ctxloc) (decl : id * dt) : Prop\n      := (* check curr member in the local context *)\n          TOkD.is_ok c cl (snd decl)  \n          (* and preserve previous members' part *)\n          /\\ ok.\n\n    Definition update_ctxloc (cl : ctxloc) (c : ctx) \n               (decl : id * dt) : ctxloc\n      := match decl with (nm, d) => upd_ctxloc cl c nm d end.\n\n    (** We can use generic implementation of module-welldefinedness *)\n    Module MSP := SinglePassModule_ProcessMembers.\n    Module MGM := GenericModule_ModuleOk MId.\n\n    (** Aux function checking that all members are ok. *)\n    Definition members_ok (c : ctx) (decls : list (id * dt)) : Prop :=\n      MSP.members_ok ctx ctxloc (id * dt) \n                     update_prop update_ctxloc c ctxl_init decls.\n\n  End HelperD.\n  Import HelperD.\n\n  (** Single-Pass Module given as the AST [decls]  \n   ** is well-defined in the context [c]. *)\n  Definition module_ok (c : ctx) (decls : list (id * dt)) : Prop :=\n    MGM.module_ok dt ctx members_ok c decls.\n\n  Ltac unfold_def G :=\n    unfold module_ok, MGM.module_ok in G.\n\nEnd SinglePassModuleDefs.\n\n(* ################################################################# *)\n(** ** Computable Part (static checker of the interpreter) *)\n(* ################################################################# *)\n\nModule SinglePassModuleInterp (Import MMB : SinglePassModuleBase) \n       (Import TOkI : DataLCOkInterp MMB.MD).\n\n  Module HelperI.\n    Export MD.\n    Definition dt := t.\n\n    Definition check_member  (c : ctx) (cl : ctxloc) (decl : id * dt) : bool\n      := TOkI.is_ok_b c cl (snd decl).\n\n    Definition update_ctxloc (cl : ctxloc) (c : ctx) \n               (decl : id * dt) : ctxloc\n      := match decl with (nm, d) => upd_ctxloc cl c nm d end.\n\n    Module MSP := SinglePassModule_ProcessMembers.\n    Module MGM := GenericModule_ModuleOk MId.\n\n    (** Aux function checking that all members are ok. *)\n    Definition members_ok_b (c : ctx) (decls : list (id * dt)) : bool :=\n      MSP.members_ok_b ctx ctxloc (id * dt)\n                       check_member update_ctxloc c ctxl_init decls.\n\n  End HelperI.\n  Import HelperI.\n\n  (** Checks that a module given as the AST [decls]  \n   ** is well-defined in the context [c]. *)\n  Definition module_ok_b (c : ctx) (decls : list (id * dt)) : bool :=\n    MGM.module_ok_b dt ctx members_ok_b c decls.\n\nEnd SinglePassModuleInterp.\n\n(* ################################################################# *)\n(** ** Proofs of Correctness *)\n(* ################################################################# *)\n\nModule SinglePassModuleProps \n       (Import MMB : SinglePassModuleBase)\n       (Import TOkD : DataLCOkDef MMB.MD)\n       (Import TOkI : DataLCOkInterp MMB.MD)\n       (Import TOkP : DataLCOkProp MMB.MD TOkD TOkI)\n.\n  Module Import MMD := SinglePassModuleDefs   MMB TOkD.\n  Module Import MMI := SinglePassModuleInterp MMB TOkI.\n  Import MMD.HelperD. Import MMI.HelperI.\n\n(* ----------------------------------------------------------------- *)\n(** *** Helper Props  *)\n(* ----------------------------------------------------------------- *)\n\n  Module Helper.\n    Import MMD.HelperD.\n\n    Lemma check_member__sound : \n      forall (c : ctx) (cl : ctxloc) (decl : id * dt) (P : Prop),\n        P -> \n        check_member c cl decl = true ->\n        update_prop P c cl decl.\n    Proof.\n      intros c cl decl P HP H.\n      unfold check_member in H. unfold update_prop.\n      apply TOkP.is_ok_b__sound in H. tauto.\n    Qed.\n\n    Lemma check_member__complete : \n      forall (c : ctx) (cl : ctxloc) (decl : id * dt) (P : Prop),\n        P -> \n        update_prop P c cl decl ->\n        check_member c cl decl = true.\n    Proof.\n      intros c cl decl P HP H.\n      unfold check_member. unfold update_prop in H.\n      apply TOkP.is_ok_b__complete. tauto.\n    Qed.\n\n    Lemma update_prop__spec :\n      forall (c : ctx) (cl : ctxloc) (decl : id * dt) (P : Prop),\n        update_prop P c cl decl -> P.\n    Proof.\n      intros c cl decl P H.\n      unfold update_prop in H. tauto.\n    Qed.\n\n(* ----------------------------------------------------------------- *)\n\n    Module MSP := SinglePassModule_ProcessMembers.\n    Module MGM := GenericModule_ModuleOk MId.\n\n    Lemma members_ok_b__sound :\n      forall (c : ctx) (decls : list (id * dt)),\n      members_ok_b c decls = true ->\n      members_ok c decls.\n    Proof.\n      intros c ds H.\n      unfold members_ok_b in H.\n      unfold members_ok.\n      apply MSP.members_ok_b__sound with (update_prop := update_prop) in H.\n      assumption. \n      exact check_member__sound.\n    Qed.\n\n    Lemma members_ok_b__complete :\n      forall (c : ctx) (decls : list (id * dt)),\n        members_ok c decls -> \n        members_ok_b c decls = true.\n    Proof.\n      intros c ds H.\n      unfold members_ok in H.\n      unfold members_ok_b.\n      apply MSP.members_ok_b__complete with (check_member := check_member) in H.\n      assumption. \n      exact check_member__complete.\n      exact update_prop__spec.\n    Qed.\n\n  End Helper.\n\n(* ================================================================= *)\n(** *** Properties *)\n(* ================================================================= *)\n\n  Theorem module_ok_b__sound : forall (c : ctx) (decls : list (id * dt)),\n      module_ok_b c decls = true ->\n      module_ok c decls.\n  Proof.\n    apply Helper.MGM.module_ok_b__sound.\n    apply Helper.members_ok_b__sound.\n  Qed.\n\n  Theorem module_ok_b__complete : forall (c : ctx) (decls : list (id * dt)),\n      module_ok c decls ->\n      module_ok_b c decls = true.\n  Proof.\n    apply Helper.MGM.module_ok_b__complete.\n    apply Helper.members_ok_b__complete.\n  Qed.\n\nEnd SinglePassModuleProps.\n\n\n\n", "meta": {"author": "julbinb", "repo": "concept-params", "sha": "f485e42b58afac98a5dd31e95827bb7fed5cae2f", "save_path": "github-repos/coq/julbinb-concept-params", "path": "github-repos/coq/julbinb-concept-params/concept-params-f485e42b58afac98a5dd31e95827bb7fed5cae2f/GenericModuleLib/SinglePassModule.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.25956709700669656}}
{"text": "Set Warnings \"-notation-overridden\".\n\nGeneralizable All Variables.\nSet Primitive Projections.\nSet Universe Polymorphism.\nSet Transparent Obligations.\n\n(* Copyright (c) 2014, John Wiegley\n *\n * This work is licensed under a\n * Creative Commons Attribution-Noncommercial-No Derivative Works 3.0\n * Unported License.\n * The license text is available at:\n *   http://creativecommons.org/licenses/by-nc-nd/3.0/\n *)\n\n(** %\\chapter{Category}% *)\n\nRequire Import Hask.Prelude.\nRequire Import Hask.Crush.\nRequire Import Coq.Unicode.Utf8.\nRequire Import FunctionalExtensionality.\n\nAxiom propositional_extensionality : forall P : Prop, P -> P = True.\nAxiom proof_irrelevance : forall (P : Prop) (u v : P), u = v.\n\nGeneralizable All Variables.\nSet Primitive Projections.\nSet Universe Polymorphism.\n(* Unset Transparent Obligations. *)\n\n(** * Category *)\n\n(** Category theory is a language for reasoning about abstractions.\nAwodey%\\cite{Awodey}% calls it, \"the algebra of abstract functions.\"  Its\npower lies in relating ideas from differing disciplines, and unifying them\nunder a common framework.\n\nAt its heart we have the [Category].  Every category is characterized by\nits objects, and the morphisms (also called arrows) between those\nobjects. *)\n\n(* begin hide *)\nReserved Notation \"a ~> b\" (at level 70, right associativity).\nReserved Notation \"f ∘ g\" (at level 40, left associativity).\nReserved Notation \"C ^op\" (at level 90).\n(* end hide *)\n\nClass Category := {\n    ob   : Type;\n    (* These require Coq 8.5 and universe polymorphism. *)\n    (* uhom := Type : Type; *)\n    (* hom  : ob → ob → uhom where \"a ~> b\" := (hom a b); *)\n    hom  : ob → ob → Type where \"a ~> b\" := (hom a b);\n(**\n\nIt is important to note that objects and arrows have no inherent meaning: The\nnotion of a category requires only that they exist, and that they be\nwell-behaved.  Since all we can know about objects is that they exist, they\nserve only to differentiate morphisms.  Conversely, morphisms are how we\ncharacterize objects. *)\n\n(** * Morphisms\n\nIn this formalization, as in many textbooks, morphisms are called [hom], for\n\"homomorphism\" (algebraic structure-preserving maps).  Each morphism\nrepresents the set of all morphism having that type, so they are also called\n\"hom-sets\".\n\nSince categories may have other categories as objects, we require that the\ntype of [hom] be larger than the type of its arguments.  This is the purpose\nof the [uhom] type, allowing us to make use of Coq's support for universe\npolymorphism.\n\n*)\n\n    c_id : ∀ {A}, A ~> A;\n    c_comp : ∀ {A B C}, (B ~> C) → (A ~> B) → (A ~> C)\n      where \"f ∘ g\" := (c_comp f g);\n(**\n\nIf [ob] and [hom] are the nouns of category theory, [id] and [compose] are its\nfundamental verbs.  Using only these notions we can reason about concepts such\nas _idempotency_, _involution_, _section_ and _retraction_, _equalizers_ and\n_co-equalizers_, and more.  Before we may do so, however, we must constrain\nidentity and composition under three laws:\n\n*)\n\n    c_right_id : ∀ A B (f : A ~> B), f ∘ c_id = f;\n    c_left_id : ∀ A B (f : A ~> B), c_id ∘ f = f;\n    c_comp_assoc : ∀ A B C D (f : C ~> D) (g : B ~> C) (h : A ~> B),\n        f ∘ (g ∘ h) = (f ∘ g) ∘ h\n}.\n\n(**\n\nNote the difference between the arrow used for function types in Coq, such as\n[A → B], and for morphisms in a category [A ~> B].  If the category must be\nindicated, it is stated in the arrow: [A ~{C}~> B]. *)\n\n(* begin hide *)\n(* Using a [Category] in a context requiring a [Type] will do what is expected\n   using this coercion. *)\nCoercion ob : Category >-> Sortclass.\n(* Coercion hom : Category >-> Funclass. *)\n\nDeclare Scope category_scope.\n\nInfix \"~>\"       := hom : category_scope.\nInfix \"~{ C }~>\" := (@hom C) (at level 100) : category_scope.\nInfix \"∘\"        := c_comp (at level 40, left associativity) : category_scope.\n\nNotation \"ob/ C\" := (@ob C) (at level 1) : category_scope.\nNotation \"id/ X\" := (@c_id _ X) (at level 1) : category_scope.\n\nOpen Scope category_scope.\n\nLemma cat_irrelevance `(C : Category) `(D : Category)\n  : ∀ (m n : ∀ {A}, A ~> A)\n      (p q : ∀ {A B C}, (B ~> C) → (A ~> B) → (A ~> C))\n      l l' r r' c c',\n  @m = @n →\n  @p = @q →\n  {| ob           := C\n   ; hom          := @hom C\n   ; c_id         := @m\n   ; c_comp       := @p\n   ; c_left_id    := l\n   ; c_right_id   := r\n   ; c_comp_assoc := c\n |} =\n  {| ob           := C\n   ; hom          := @hom C\n   ; c_id         := @n\n   ; c_comp       := @q\n   ; c_left_id    := l'\n   ; c_right_id   := r'\n   ; c_comp_assoc := c'\n |}.\nProof.\n  intros. subst. f_equal.\n  apply proof_irrelevance.\n  apply proof_irrelevance.\n  apply proof_irrelevance.\nQed.\n\n#[export] Hint Extern 1 => apply c_left_id : core.\n#[export] Hint Extern 1 => apply c_right_id : core.\n\n#[export] Hint Extern 4 (?A = ?A) => reflexivity : core.\n#[export] Hint Extern 7 (?X = ?Z) =>\n  match goal with\n    [H : ?X = ?Y, H' : ?Y = ?Z |- ?X = ?Z] => transitivity Y\n  end : core.\n\n(* end hide *)\n\n(**\n\nWe may now extend our discourse about functions, using only the few terms\nwe've defined so far:\n\n*)\n\n(* begin hide *)\nSection Morphisms.\nContext `{C : Category}.\n(* end hide *)\n\nDefinition Idempotent `(f : X ~> X) := f ∘ f = f.\nDefinition Involutive `(f : X ~> X) := f ∘ f = c_id.\n\n(**\n\nWe can also define relationships between two functions:\n\n*)\n\nDefinition Section'   `(f : X ~> Y) := { g : Y ~> X & g ∘ f = c_id }.\nDefinition Retraction `(f : X ~> Y) := { g : Y ~> X & f ∘ g = c_id }.\n\nClass SplitIdempotent {X Y : C} := {\n    split_idem_retract := Y;\n\n    split_idem       : X ~> X;\n    split_idem_r     : X ~> split_idem_retract;\n    split_idem_s     : split_idem_retract ~> X;\n    split_idem_law_1 : split_idem_s ∘ split_idem_r = split_idem;\n    split_idem_law_2 : split_idem_r ∘ split_idem_s = id/Y\n}.\n\n(**\n\nA Σ-type (sigma type) is used to convey [Section'] and [Retraction] to make\nthe witness available to proofs.  The definition could be expressed with an\nexistential quantifier (∃), but it would not convey which [g] was chosen.\n\n*)\n\nDefinition Epic  `(f : X ~> Y) := ∀ Z (g1 g2 : Y ~> Z), g1 ∘ f = g2 ∘ f → g1 = g2.\nDefinition Monic `(f : X ~> Y) := ∀ Z (g1 g2 : Z ~> X), f ∘ g1 = f ∘ g2 → g1 = g2.\n\nDefinition Bimorphic `(f : X ~> Y) := Epic f ∧ Monic f.\nDefinition SplitEpi  `(f : X ~> Y) := Retraction f.\nDefinition SplitMono `(f : X ~> Y) := Section' f.\n\n(**\n\nThe only morphism we've seen so far is [id], but we can trivially prove it is\nboth _idempotent_ and _involutive_. *)\n\n(* begin hide *)\nHint Unfold Idempotent : core.\nHint Unfold Involutive : core.\nHint Unfold Section' : core.\nHint Unfold Retraction : core.\nHint Unfold Epic : core.\nHint Unfold Monic : core.\nHint Unfold Bimorphic : core.\nHint Unfold SplitEpi : core.\nHint Unfold SplitMono : core.\n(* end hide *)\n\nLemma id_idempotent : ∀ X, Idempotent (c_id (A := X)).\nProof. auto. Qed.\n\nLemma id_involutive : ∀ X, Involutive (c_id (A := X)).\nProof. auto. Qed.\n\n(**\n\nWe can also prove some relationships among these definitions. *)\n\n(* begin hide *)\nSection Lemmas.\nVariables X Y : C.\nVariable f : X ~> Y.\n(* end hide *)\n\nLemma retractions_are_epic : Retraction f → Epic f.\nProof.\n  autounfold.\n  intros.\n  destruct X0.\n  rewrite <- c_right_id.\n  symmetry.\n  rewrite <- c_right_id.\n  rewrite <- e.\n  repeat (rewrite c_comp_assoc); try f_equal; auto.\nQed.\n\nLemma sections_are_monic : Section' f → Monic f.\nProof.\n  autounfold.\n  intros.\n  destruct X0.\n  rewrite <- c_left_id.\n  symmetry.\n  rewrite <- c_left_id.\n  rewrite <- e.\n  repeat (rewrite <- c_comp_assoc); try f_equal; auto.\nQed.\n\n(* begin hide *)\nEnd Lemmas.\nEnd Morphisms.\n(* end hide *)\n\nDefinition epi_compose `{C : Category} {X Y Z : C}\n  `(ef : @Epic C Y Z f) `(eg : @Epic C X Y g) : Epic (f ∘ g).\nProof.\n  unfold Epic in *. intros.\n  apply ef.\n  apply eg.\n  repeat (rewrite <- c_comp_assoc); auto.\nQed.\n\nDefinition monic_compose `{C : Category} {X Y Z : C}\n  `(ef : @Monic C Y Z f) `(eg : @Monic C X Y g) : Monic (f ∘ g).\nProof.\n  unfold Monic in *. intros.\n  apply eg.\n  apply ef.\n  repeat (rewrite c_comp_assoc); auto.\nQed.\n\n(** * Isomorphism\n\nAn isomorphism is a pair of mappings that establish an equivalence between\nobjects.  Using the language above, it is a pair of functions which are both\nsections and retractions of one another.  That is, they compose to identity in\nboth directions:\n\n*)\n\nClass Isomorphism `{C : Category} (X Y : C) := {\n  to       : X ~> Y;\n  from     : Y ~> X;\n  iso_to   : to ∘ from = id/Y;\n  iso_from : from ∘ to = id/X\n}.\n\n(* begin hide *)\nLemma iso_irrelevance `(C : Category) {X Y : C}\n  : ∀ (f g : X ~> Y) (k h : Y ~> X) tl tl' fl fl',\n  @f = @g →\n  @k = @h →\n  {| to       := f\n   ; from     := k\n   ; iso_to   := tl\n   ; iso_from := fl\n  |} =\n  {| to       := g\n   ; from     := h\n   ; iso_to   := tl'\n   ; iso_from := fl'\n  |}.\nProof.\n  intros. subst. f_equal.\n  apply proof_irrelevance.\n  apply proof_irrelevance.\nQed.\n(* end hide *)\n\n(**\n\nTypically isomorphisms are characterized by this pair of functions, but they\ncan also be expressed as an equivalence between objects using the notation [A\n≅ B].  A double-tilde is used to express the same notion of equivalence\nbetween value terms [a = b].\n\n*)\n\nNotation \"X {≅} Y\" :=\n  (Isomorphism X Y) (at level 70, right associativity) : category_scope.\nNotation \"x {≡} y\" :=\n  (to x = y ∧ from y = x) (at level 70, right associativity).\n\n(**\n\n[id] witnesses the isomorphism between any object and itself.  Isomorphisms\nare likewise symmetric and transitivity, making them parametric relations.\nThis will allows us to use them in proof rewriting as though they were\nequalities.\n\n*)\n\nProgram Definition iso_identity `{C : Category} (X : C) : X {≅} X := {|\n    to   := id/X;\n    from := id/X\n|}.\n\nProgram Definition iso_symmetry `{C : Category} `(iso : X {≅} Y) : Y {≅} X := {|\n    to   := @from C X Y iso;\n    from := @to C X Y iso\n|}.\n(* begin hide *)\nObligation 1. apply iso_from. Qed.\nObligation 2. apply iso_to. Qed.\n(* end hide *)\n\nProgram Definition iso_compose `{C : Category} {X Y Z : C}\n    (iso_a : Y {≅} Z) (iso_b : X {≅} Y) : X {≅} Z := {|\n    to   := (@to C Y Z iso_a) ∘ (@to C X Y iso_b);\n    from := (@from C X Y iso_b) ∘ (@from C Y Z iso_a)\n|}.\n(* begin hide *)\nObligation 1.\n  destruct iso_a.\n  destruct iso_b. simpl.\n  rewrite <- c_comp_assoc.\n  rewrite (c_comp_assoc _ _ _ _ to1).\n  rewrite iso_to1.\n  rewrite c_left_id.\n  assumption.\nQed.\nObligation 2.\n  destruct iso_a.\n  destruct iso_b. simpl.\n  rewrite <- c_comp_assoc.\n  rewrite (c_comp_assoc _ _ _ _ from0).\n  rewrite iso_from0.\n  rewrite c_left_id.\n  assumption.\nQed.\n(* end hide *)\n\n(*\nDefinition iso_equiv `{C : Category} {a b : C} (x y : a ≅ b) : Prop :=\n  match x with\n  | Build_Isomorphism to0 from0 _ _ => match y with\n    | Build_Isomorphism to1 from1 _ _ =>\n      to0 = to1 ∧ from0 = from1\n    end\n  end.\n\nProgram Definition iso_equivalence `{C : Category} (a b : C)\n  : Equivalence (@iso_equiv C a b).\nObligation 1.\n  unfold Reflexive, iso_equiv. intros.\n  destruct x. auto.\nDefined.\nObligation 2.\n  unfold Symmetric, iso_equiv. intros.\n  destruct x. destruct y.\n  inversion H.\n  split; symmetry; assumption.\nDefined.\nObligation 3.\n  unfold Transitive, iso_equiv. intros.\n  destruct x. destruct y. destruct z.\n  inversion H. inversion H0.\n  split. transitivity to1; auto.\n  transitivity from1; auto.\nDefined.\n\nAdd Parametric Relation `(C : Category) (a b : C) : (a ≅ b) (@iso_equiv C a b)\n  reflexivity proved by  (@Equivalence_Reflexive  _ _ (iso_equivalence a b))\n  symmetry proved by     (@Equivalence_Symmetric  _ _ (iso_equivalence a b))\n  transitivity proved by (@Equivalence_Transitive _ _ (iso_equivalence a b))\n    as parametric_relation_iso_eqv.\n\n  Add Parametric Morphism `(C : Category) (a b c : C) : (@iso_compose C a b c)\n    with signature (iso_equiv ==> iso_equiv ==> iso_equiv)\n      as parametric_morphism_iso_comp.\n    intros. unfold iso_equiv, iso_compose.\n    destruct x. destruct y. destruct x0. destruct y0.\n    simpl in *.\n    inversion H. inversion H0.\n    split; crush.\nDefined.\n*)\n\n(**\n\nA [Groupoid] is a [Category] where every morphism has an inverse, and is\ntherefore an isomorphism.\n\n*)\n\nProgram Definition Groupoid `(C : Category) : Category := {|\n    ob      := @ob C;\n    hom     := @Isomorphism C;\n    c_id    := @iso_identity C\n|}.\n(* begin hide *)\nNext Obligation.\n  unfold iso_compose, iso_identity.\n  eapply iso_compose; eauto.\nDefined.\nNext Obligation.\n  unfold Groupoid_obligation_1.\n  unfold iso_compose, iso_identity.\n  destruct f. simpl in *.\n  apply iso_irrelevance.\n  apply c_right_id.\n  apply c_left_id.\nQed.\nNext Obligation.\n  unfold Groupoid_obligation_1.\n  unfold iso_compose, iso_identity.\n  destruct f. simpl in *.\n  apply iso_irrelevance.\n  apply c_left_id.\n  apply c_right_id.\nQed.\nNext Obligation.\n  unfold Groupoid_obligation_1.\n  unfold iso_compose.\n  destruct f. destruct g. destruct h.\n  simpl; apply iso_irrelevance;\n  rewrite c_comp_assoc; reflexivity.\nQed.\n(* end hide *)\n\n(**\n\nA function which is both a retraction and monic, or a section and epic, bears\nan isomorphism with its respective witness.\n\n*)\n\nProgram Definition Monic_Retraction_Iso `{C : Category}\n  `(f : X ~{C}~> Y) (r : Retraction f) (m : Monic f) : X {≅} Y := {|\n  to   := f;\n  from := projT1 r\n|}.\n(* begin hide *)\nObligation 1.\n  autounfold in *.\n  destruct r.\n  auto.\nQed.\nObligation 2.\n  autounfold in *.\n  destruct r.\n  simpl.\n  specialize (m X (x ∘ f) c_id).\n  apply m.\n  rewrite c_comp_assoc.\n  rewrite e.\n  auto.\n  rewrite c_left_id.\n  rewrite c_right_id.\n  reflexivity.\nQed.\n(* end hide *)\n\nProgram Definition Epic_Section_Iso\n    `{C : Category} {X Y} `(s : Section' f) `(e : Epic f) : X {≅} Y := {|\n    to   := f;\n    from := projT1 s\n|}.\n(* begin hide *)\nObligation 1.\n  autounfold in *.\n  destruct s.\n  simpl.\n  specialize (e Y (f ∘ x) c_id).\n  apply e.\n  rewrite <- c_comp_assoc.\n  rewrite e0.\n  rewrite c_left_id.\n  rewrite c_right_id.\n  reflexivity.\nQed.\nObligation 2.\n  autounfold in *.\n  destruct s.\n  specialize (e Y (f ∘ x) c_id).\n  auto.\nQed.\n\n#[export] Hint Unfold Idempotent : core.\n#[export] Hint Unfold Involutive : core.\n#[export] Hint Unfold Section' : core.\n#[export] Hint Unfold Retraction : core.\n#[export] Hint Unfold Epic : core.\n#[export] Hint Unfold Monic : core.\n#[export] Hint Unfold Bimorphic : core.\n#[export] Hint Unfold SplitEpi : core.\n#[export] Hint Unfold SplitMono : core.\n(* end hide *)\n\n(**\n\nA section may be flipped using its witness to provide a retraction, and\nvice-versa.\n\n*)\n\nDefinition flip_section `{Category} `(f : X ~> Y)\n  (s : @Section' _ X Y f) : @Retraction _ Y X (projT1 s).\nProof.\n  autounfold.\n  destruct s.\n  exists f.\n  crush.\nQed.\n\nDefinition flip_retraction `{Category} `(f : X ~> Y)\n  (s : @Retraction _ X Y f) : @Section' _ Y X (projT1 s).\nProof.\n  autounfold.\n  destruct s.\n  exists f.\n  crush.\nQed.\n\n(** * Sets\n\n[Sets] is our first real category: the category of Coq types and functions.\nThe objects of this category are all the Coq types (including [Set], [Prop]\nand [Type]), and its morphisms are functions from [Type] to [Type].  [id]\nsimply returns whatever object is passed, and [compose] is regular composition\nbetween functions.  Proving it is a category in Coq is automatic.\n\nNote that in many textbooks this category (or one similar to it) is called\njust [Set], but since that name conflicts with types of the same name in Coq,\nthe plural is used instead.\n\n*)\n\nProgram Definition Sets : Category := {|\n    ob     := Type;\n    hom    := fun X Y => X → Y;\n    c_id   := fun _ x => x;\n    c_comp := fun _ _ _ f g x => f (g x)\n|}.\n(**\n\nWithin the category of [Sets] we can prove that monic functions are injective,\nand epic functions are surjective.  This is not necessarily true in other\ncategories.\n\n*)\n\nNotation \"X ≅Sets Y\" :=\n  (@Isomorphism Sets X Y) (at level 70, right associativity) : category_scope.\n\nDefinition Injective `(f : X → Y) := ∀ x y, f x = f y → x = y.\n\nLemma injectivity_is_monic `(f : X → Y) : Injective f ↔ @Monic Sets _ _ f.\nProof.\n  unfold Monic, Injective.\n  split; intros; simpl in *.\n  - extensionality z.\n    apply H. apply (equal_f H0).\n  - pose (fun (_ : unit) => x) as const_x.\n    pose (fun (_ : unit) => y) as const_y.\n    specialize (H unit const_x const_y).\n    unfold const_x in H.\n    unfold const_y in H.\n    apply equal_f in H.\n    + assumption.\n    + extensionality tt. assumption.\n    + constructor.\nQed.\n\nDefinition Surjective `(f : X → Y) := ∀ y, ∃ x, f x = y.\n\nLemma surjectivity_is_epic `(f : X → Y) : Surjective f ↔ @Epic Sets _ _ f.\nProof.\n  unfold Epic, Surjective.\n  split; intros; simpl in *.\n  - extensionality y.\n    specialize (H y).\n    destruct H.\n    rewrite <- H.\n    apply (equal_f H0).\n  - specialize H with (Z := Prop).\n    specialize H with (g1 := fun y0 => ∃ x0, f x0 = y0).\n    specialize H with (g2 := fun y  => True).\n    eapply equal_f in H.\n    erewrite H. constructor.\n    extensionality x.\n    apply propositional_extensionality.\n    exists x. reflexivity.\nQed.\n\n(** * Dual Category\n\nThe opposite, or dual, of a category is expressed [C^op].  It has the same\nobjects as its parent, but the direction of all morphisms is flipped.  Doing\nthis twice should result in the same category, making it an involutive\noperation.\n\n*)\n\nProgram Definition Opposite `(C : Category) : Category := {|\n    ob     := @ob C;\n    hom    := fun x y => @hom C y x;\n    c_id   := @c_id C;\n    c_comp := fun _ _ _ f g => g ∘ f\n|}.\nObligation 3. rewrite c_comp_assoc. auto. Defined.\n\n(* begin hide *)\nNotation \"C ^op\" := (Opposite C) (at level 90) : category_scope.\n(* end hide *)\n\nLemma op_involutive (C : Category) : (C^op)^op = C.\nProof.\n  unfold Opposite.\n  unfold Opposite_obligation_1.\n  unfold Opposite_obligation_2.\n  unfold Opposite_obligation_3.\n  simpl. destruct C. simpl.\n  apply f_equal3; repeat (extensionality e; simpl; crush).\n  extensionality b.\n  extensionality c.\n  extensionality d.\n  extensionality f.\n  extensionality g.\n  extensionality h. crush.\nQed.\n\n(**\n\nUsing the functions [op] and [unop], we can \"flip\" a particular morphism by\nmapping to its corresponding morphism in the dual category.\n\n*)\n\nDefinition op `{C : Category} : ∀ {X Y}, (X ~{C^op}~> Y) → (Y ~{C}~> X).\nProof. auto. Defined.\n\nDefinition unop `{C : Category} : ∀ {X Y}, (Y ~{C}~> X) → (X ~{C^op}~> Y).\nProof. auto. Defined.\n", "meta": {"author": "jwiegley", "repo": "coq-haskell", "sha": "56a185af5767177d410113a03bd765135e07c9ca", "save_path": "github-repos/coq/jwiegley-coq-haskell", "path": "github-repos/coq/jwiegley-coq-haskell/coq-haskell-56a185af5767177d410113a03bd765135e07c9ca/src/Control/Category.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.25956709700669656}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.floyd.VSU.\nRequire Import triang.\nRequire Import simple_spec_stdlib.\nRequire Import simple_spec_pile.\nRequire Import simple_spec_triang.\nRequire Import PileModel.\n\n\nDefinition triang_imported_specs:funspecs := PileASI.\nDefinition triang_internal_specs: funspecs := TriangASI.\nDefinition TriangVprog: varspecs. mk_varspecs prog. Defined.\nDefinition TriangGprog: funspecs := triang_imported_specs ++ triang_internal_specs.\n\nLemma body_Triang_nth: semax_body TriangVprog TriangGprog f_Triang_nth Triang_nth_spec.\nProof.\nstart_function.\nforward_call gv.\nIntros p.\nforward_for_simple_bound n\n  (EX i:Z,\n   PROP() LOCAL(temp _p p; temp _n (Vint (Int.repr n)); gvars gv)\n   SEP (pilerep (decreasing (Z.to_nat i)) p; pile_freeable p; mem_mgr gv)).\n-\n entailer!.\n- forward_call (p, i+1, decreasing(Z.to_nat i), gv).\nrep_lia.\nentailer!.\nassert (Z.to_nat (i+1) = S (Z.to_nat i))\n  by (rewrite <- Z2Nat.inj_succ by lia; f_equal).\nrewrite H2.\nunfold decreasing; fold decreasing.\nrewrite inj_S.\nrewrite Z2Nat.id by lia.\napply derives_refl.\n-\nforward_call (p, decreasing (Z.to_nat n)).\napply sumlist_decreasing_bound; auto.\nforward_call (p, decreasing (Z.to_nat n), gv).\nforward.\nentailer!.\nf_equal; f_equal.\nclear.\ninduction (Z.to_nat n).\nreflexivity.\nsimpl. congruence.\nQed.\n\nDefinition TriangVSU: @VSU NullExtension.Espec \n      nil triang_imported_specs ltac:(QPprog prog) TriangASI emp.\n  Proof. \n    mkVSU prog triang_internal_specs. \n    + solve_SF_internal body_Triang_nth.\n  Qed.\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/VSUpile/simple_verif_triang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2595670970066965}}
{"text": "(** * Definition of the system HR *)\nRequire Import Rpos.\nRequire Import RL.hr.term.\nRequire Import RL.hr.semantic.\nRequire Import RL.hr.hseq.\n\nRequire Import CMorphisms.\nRequire Import List.\nRequire Import Lra.\n\nRequire Import RL.OLlibs.Permutation_Type.\nRequire Import RL.OLlibs.Permutation_Type_more.\nRequire Import RL.OLlibs.Permutation_Type_solve.\n\nLocal Open Scope R_scope.\n\n(** ** Fragments of the system HR, i.e. whether we can use the T rule, the M rule or the CAN rule *)\nRecord hr_frag := mk_hr_frag {\n                      hr_T : bool;\n                      hr_M : bool;\n                      hr_CAN : bool }.\n\nDefinition le_hr_frag P Q :=\n  prod (Bool.le (hr_T P) (hr_T Q))\n       (prod (Bool.le (hr_M P) (hr_M Q))\n             (Bool.le (hr_CAN P) (hr_CAN Q))).\n\nLemma le_hr_frag_trans : forall P Q R,\n  le_hr_frag P Q -> le_hr_frag Q R -> le_hr_frag P R.\nProof.\nintros P Q R H1 H2.\ndestruct H1 as (Ht1 & Hm1 & Hcan1).\ndestruct H2 as (Ht2 & Hm2 & Hcan2).\nrepeat split; destruct P; destruct Q; destruct R; Bool.destr_bool.\nQed.\n\nInstance le_hr_frag_po : PreOrder le_hr_frag.\nProof.\nsplit.\n- repeat split; destruct x; Bool.destr_bool.\n- intros P Q R.\n  apply le_hr_frag_trans.\nQed.\n\nDefinition hr_frag_add_T P := mk_hr_frag true (hr_M P) (hr_CAN P).\nDefinition hr_frag_rm_T P := mk_hr_frag false (hr_M P) (hr_CAN P).\nDefinition hr_frag_add_M P := mk_hr_frag (hr_T P) true (hr_CAN P).\nDefinition hr_frag_rm_M P := mk_hr_frag (hr_T P) false (hr_CAN P).\nDefinition hr_frag_add_CAN P := mk_hr_frag (hr_T P) (hr_M P) true.\nDefinition hr_frag_rm_CAN P := mk_hr_frag (hr_T P) (hr_M P) false.\n\nLemma add_T_le_frag : forall P, le_hr_frag P (hr_frag_add_T P).\nProof.\n  intros P.\n  repeat split; destruct P; Bool.destr_bool.\nQed.\nLemma add_M_le_frag : forall P, le_hr_frag P (hr_frag_add_M P).\nProof.\n  intros P.\n  repeat split; destruct P; Bool.destr_bool.\nQed.\nLemma add_CAN_le_frag : forall P, le_hr_frag P (hr_frag_add_CAN P).\nProof.\n  intros P.\n  repeat split; destruct P; Bool.destr_bool.\nQed.\nLemma rm_T_le_frag : forall P, le_hr_frag (hr_frag_rm_T P) P.\nProof.\n  intros P.\n  repeat split; destruct P; Bool.destr_bool.\nQed.\nLemma rm_M_le_frag : forall P, le_hr_frag (hr_frag_rm_M P) P.\nProof.\n  intros P.\n  repeat split; destruct P; Bool.destr_bool.\nQed.\nLemma rm_CAN_le_frag : forall P, le_hr_frag (hr_frag_rm_CAN P) P.\nProof.\n  intros P.\n  repeat split; destruct P; Bool.destr_bool.\nQed.\n\n(** only the following fragments are interesting for what we want to do *)\nDefinition hr_frag_M_can := (mk_hr_frag false true true).\nDefinition hr_frag_full := (mk_hr_frag true true true).\nDefinition hr_frag_T_M := (mk_hr_frag true true false).\nDefinition hr_frag_T := (mk_hr_frag true false false).\nDefinition hr_frag_M := (mk_hr_frag false true false).\nDefinition hr_frag_nothing := (mk_hr_frag false false false).\n\n(** * Definition of hr *)\n(** ** HR *)\n\nInductive HR P : hypersequent -> Type :=\n| hrr_INIT : HR P (nil :: nil)\n| hrr_W : forall G T, HR P G -> HR P (T :: G)\n| hrr_C : forall G T, HR P (T :: T :: G) -> HR P (T :: G)\n| hrr_S : forall G T1 T2, HR P ((T1 ++ T2) :: G) -> HR P (T1 :: T2 :: G)\n| hrr_M {f : hr_M P = true} : forall G T1 T2, HR P (T1 :: G) -> HR P (T2 :: G) -> HR P ((T1 ++ T2) :: G)\n| hrr_T {f : hr_T P = true} : forall G T r, HR P (seq_mul r T :: G) -> HR P (T :: G)\n| hrr_ID : forall G T n r s, sum_vec r = sum_vec s -> HR P (T :: G) -> HR P ((vec s (HR_covar n) ++ vec r (HR_var n) ++ T) :: G)\n| hrr_Z : forall G T r, HR P (T :: G) -> HR P ((vec r HR_zero ++ T) :: G)\n\n| hrr_plus : forall G T A B r, HR P ((vec r A ++ vec r B ++ T) :: G) -> HR P ((vec r (A +S B) ++ T) :: G)\n| hrr_mul : forall G T A r0 r, HR P ((vec (mul_vec r0 r) A ++ T) :: G) -> HR P ((vec r (r0 *S A) ++ T) :: G)\n| hrr_max : forall G T A B r, HR P ((vec r B ++ T) :: (vec r A ++ T) :: G) -> HR P ((vec r (A \\/S B) ++ T) :: G)\n| hrr_min : forall G T A B r, HR P ((vec r A ++ T) :: G) -> HR P ((vec r B ++ T) :: G) -> HR P ((vec r (A /\\S B) ++ T) :: G)\n| hrr_ex_seq : forall G T1 T2, Permutation_Type T1 T2 -> HR P (T1 :: G) -> HR P (T2 :: G)\n| hrr_ex_hseq : forall G H, Permutation_Type G H -> HR P G -> HR P H\n| hrr_can {f : hr_CAN P = true} : forall G T A r s, sum_vec r = sum_vec s -> HR P ((vec s (-S A) ++ vec r A ++ T) :: G) -> HR P (T :: G).\n\n(** HR with only can and M *)\nDefinition HR_M_can := HR hr_frag_M_can.\n(** HR with every rule *)\nDefinition HR_full := HR hr_frag_full.\n(** HR without the CAN rule *)\nDefinition HR_T_M := HR hr_frag_T_M.\n(** HR with neither the CAN rule nor the M rule *)\nDefinition HR_T := HR hr_frag_T.\n(** HR with only the M rule*)\nDefinition HR_M := HR hr_frag_M.\n(** HR with neither the CAN rule nor the M rule nor the T rule*)\nDefinition HR_nothing := HR hr_frag_nothing.\n\n(** ** Some basic properties for the system HR *)\nLemma HR_not_empty P : forall G, HR P G -> G <> nil.\nProof.\n  intros G pi; induction pi; (try now auto).\n  intros Heq; apply IHpi; apply Permutation_Type_nil.\n  symmetry; now rewrite <- Heq.\nQed.\n\n(** if we add some rules, we keep the derivability (for instance, a hypersequent provable without the T rule is provable with the T rule) *)\nLemma HR_le_frag : forall P Q,\n    le_hr_frag P Q ->\n    forall G, HR P G -> HR Q G.\nProof.\n  intros P Q Hle G pi.\n  induction pi;  destruct P as [HTP HMP HCANP]; destruct Q as [HTQ HMQ HCANQ]; destruct Hle as [HleT [HleM HleCAN]]; simpl in *; subst; try (now constructor).\n  - apply hrr_T with r; assumption.\n  - apply hrr_ex_seq with T1; assumption.\n  - apply hrr_ex_hseq with G; assumption.\n  - apply hrr_can with A r s; try assumption; try reflexivity.\nQed.\n\n(** some others derivable rules *)\nLemma hrr_W_gen P : forall G H, HR P G -> HR P (H ++ G).\nProof.\n  intros G H; revert G; induction H; intros G pi.\n  - auto.\n  - simpl; apply hrr_W; apply IHlist; apply pi.\nQed.\n\nLemma hrr_C_gen P : forall G H, HR P (H ++ H ++ G) -> HR P (H ++ G).\nProof.\n  intros G H; revert P G; induction H as [ | T H]; intros P G pi.\n  - apply pi.\n  - simpl; apply hrr_C; try reflexivity.\n    apply hrr_ex_hseq with (H ++ T :: T :: G); [ Permutation_Type_solve | ].\n    apply IHH.\n    eapply hrr_ex_hseq ; [ | apply pi].\n    Permutation_Type_solve.\nQed.\n\nLemma hrr_C_copy P : forall G T n, HR P ((copy_seq (S n) T) :: G) -> HR P (T :: G).\nProof.\n  intros G T n; revert G T; induction n; intros G T pi; simpl in *; try assumption.\n  apply hrr_C.\n  apply IHn.\n  apply hrr_S.\n  apply pi.\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/hr/hr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2595670970066965}}
{"text": "From mathcomp Require Import all_ssreflect.\nFrom chip Require Import extra connect close_dfs closure.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection InvRel.\n\nVariable T : finType.\n\nDefinition rinv (r : rel T) := [rel x y | r y x].\n\nEnd InvRel.\n\nNotation \"r ^-1\" := (rinv r).\n\nSection Checked.\n\n(* artifact *)\nVariable A : eqType.\n\n(* paths *)\nVariable V' : finType.\n\nVariable f' : V' -> A.\n\n(* old graph *)\nVariable P : pred V'.\n\nLocal Notation V := (sig_finType P).\n\nVariable f : V -> A.\n\nVariable g : rel V.\n\nVariable checkable : pred V'.\n\nVariable R : eqType.\n\nVariable check : V' -> R.\n\nDefinition freshV' : {set V'} := [set v | ~~ P v].\n\nLemma sub_freshV' v' :\n  (~~ @insub _ _ [subType of V] v') = (v' \\in freshV').\nProof.\ncase Hs: (~~ _); case Hf: (_ \\in _) => //.\n- move/negP: Hf; case.\n  have H_sp := (insubP [subType of V] v').\n  destruct H_sp => //.\n  by rewrite in_set.\n- move/negP/negP: Hs => Hs.\n  move: Hf.\n  rewrite in_set.\n  move/negP.\n  case.\n  have H_sp := (insubP [subType of V] v').  \n  by destruct H_sp.\nQed.\n\nLemma freshV'P v' :\n  reflect (forall v : V, val v != v') (v' \\in freshV').\nProof.\napply: (iffP idP).\n- rewrite in_set.\n  move/negP => HP v.\n  apply/negP.\n  move/eqP => Hv.\n  case: HP.\n  rewrite -Hv.\n  exact: valP.\n- move => Hv.\n  rewrite in_set.\n  apply/negP => HP.\n  have H_sp := (insubP [subType of V] v').\n  destruct H_sp; last by move/negP: i; case.\n  have Hvu := Hv u.\n  move/negP/negP: Hvu.\n  rewrite e.\n  by move/eqP.\nQed.\n\nDefinition modifiedV := [set v | f v != f' (val v)].\n\nLemma not_modifiedP v :\n  reflect (f v == f' (val v)) (v \\notin modifiedV).\nProof.\napply: (iffP idP).\n- move/negPf.\n  rewrite in_set.\n  by move/negP/negP.\n- move => Hf.\n  apply/negPf.\n  rewrite in_set.\n  by apply/negP/negP.\nQed.\n\nDefinition checkable_impactedV modified :=\n  [set v in impacted g^-1 modified | checkable (val v)].\n\nDefinition checkable_impacted :=\n  [seq (val v) | v <- enum (checkable_impactedV modifiedV)].\n\nLemma impactedVP (modified : {set V}) x :\n  reflect\n    (exists2 v, v \\in modified & connect g^-1 v x)\n    (x \\in impacted g^-1 modified).\nProof. exact: impactedP. Qed.\n\nLemma impacted_closure : forall (modified : {set V}),\n  [set x in closure g modified] = impacted g^-1 modified.\nProof.\nmove => modified.\napply/eqP.\nrewrite eqEsubset.\napply/andP.\nsplit.\n- apply/subsetP.\n  move => x.\n  rewrite inE /=.\n  move/closureP => [v Hv] Hc.\n  apply/impactedVP.\n  exists v => //.\n  by apply/connect_rev.\napply/subsetP.\nmove => x.\nmove/impactedVP => [v Hv] Hc.\nrewrite inE /=.\napply/closureP.\nexists v => //.\nby move/connect_rev: Hc.\nQed.\n\nLemma not_impactedP (modified : {set V}) x :\n  reflect\n  (forall v, connect g x v -> v \\notin modified)\n  (x \\notin impacted g^-1 modified).\nProof.\napply: (iffP idP).\n- move/impactedVP => Hex.\n  move => v Hc.\n  apply/negP => Hv.\n  apply connect_rev in Hc.\n  case: Hex.\n  by exists v.\n- move => Hc.\n  apply/negP.\n  move => Hx.\n  move/impactedVP: Hx.\n  move => [v Hv].\n  move/connect_rev => /=.\n  have ->: rel_of_simpl_rel [rel x' y' | g^-1 y' x'] = g by [].\n  by move/Hc/negP.\nQed.\n\nDefinition impactedVV' modified := [set (val v) | v in impacted g^-1 modified].\n\nLemma impactedVV'_freshV' modified x :\n  x \\in impactedVV' modified -> x \\notin freshV'.\nProof.\nmove => Hx.\nrewrite in_set.\napply/negP.\nmove => HP.\nmove/negP: HP.\ncase.\nmove: Hx.\ncase/imsetP => v Hv Hx.\nrewrite Hx.\nexact: valP.\nQed.\n\nDefinition impactedV' : {set V'} := impactedVV' modifiedV :|: freshV'.\n\nDefinition impacted_fresh : seq V' := enum impactedV'.\n\nLemma impactedV'P x :\n  reflect ((x \\in impactedVV' modifiedV /\\ x \\notin freshV') \\/ (x \\in freshV' /\\ x \\notin impactedVV' modifiedV))\n          (x \\in impactedV').\nProof.\napply: (iffP idP).\n- rewrite in_set.\n  move/orP.\n  case => Hx.\n  * left; split => //.\n    move: Hx.\n    exact: impactedVV'_freshV'.\n  * right; split => //.\n    apply/negP.\n    by move/impactedVV'_freshV'/negP.\n- case.\n  * move => [Hx Hf].\n    rewrite in_set.\n    apply/orP.\n    by left.\n  * move => [Hx Hf].\n    rewrite in_set.\n    apply/orP.\n    by right.\nQed.\n\nDefinition checkable_impactedV' :=\n [set v in impactedV' | checkable v].\n\nDefinition checkable_impacted_fresh : seq V' :=\n enum checkable_impactedV'.\n\nDefinition check_impactedV'_cert :=\n  [seq (v, check v) | v <- checkable_impacted_fresh].\n\nLemma check_impactedV'_cert_check v r :\n  (v,r) \\in check_impactedV'_cert -> \n  checkable v /\\ check v == r /\\ v \\in impactedV'.\nProof.\nmove/mapP => [v' Hv] Hc.\nmove: Hc Hv.\ncase =>->->.\nrewrite mem_enum in_set.\nmove/andP => [Hc Hv].\nby split.\nQed.\n\nLemma cert_check_impactedV'_check v r :\n  checkable v ->\n  check v == r ->\n  v \\in impactedV' ->\n  (v,r) \\in check_impactedV'_cert.\nProof.\nmove => Hc Hv Hi.\napply/mapP.\nexists v; last by move/eqP: Hv=><-.\nrewrite mem_enum in_set.\napply/andP.\nby split.\nQed.\n\nLemma check_impactedV'_certP v r :\n  reflect\n    (checkable v /\\ check v == r /\\ v \\in impactedV')\n    ((v,r) \\in check_impactedV'_cert).\nProof.\napply: (iffP idP).\n- exact: check_impactedV'_cert_check.\n- move => [Hc [Hv Hi]].\n  exact: cert_check_impactedV'_check.\nQed.\n\nLemma check_impactedV'_cert_uniq :\n  uniq [seq vr.1 | vr <- check_impactedV'_cert].\nProof.\nrewrite map_inj_in_uniq.\n- rewrite map_inj_uniq; first by rewrite enum_uniq.\n  by move => x y; case.\n- case => v1 r1.\n  case => v2 r2.\n  move => H1 H2 /= Heq.\n  move: Heq H1 H2 =>-<-.\n  move/mapP => [v1' Hv1' Hc1].\n  rewrite mem_enum in Hv1'.\n  case: Hc1 =><- Hr1.\n  move/mapP => [v2' Hv2' Hc2].\n  rewrite mem_enum in Hv2'.\n  case: Hc2 =><- Hr2.\n  by rewrite Hr1 Hr2.\nQed.\n\nEnd Checked.\n\nSection Other.\n\nVariable A : eqType.\nVariable V' : finType.\nVariable f' : V' -> A.\nVariable P : pred V'.\nLocal Notation V := (sig_finType P).\nVariable f : V -> A.\nVariables (g1 : rel V) (g2 : rel V).\nVariable checkable : pred V'.\nVariable R : eqType.\nVariable check : V' -> R.\n\nHypothesis g1_g2_connect : connect g1 =2 connect g2.\n\nLemma connect_impactedV_eq modified :\n  impacted g1^-1 modified = impacted g2^-1 modified.\nProof.\napply/eqP.\nrewrite eqEsubset.\napply/andP.\nsplit.\n- apply/subsetP.\n  move => x Hx.\n  apply: rclosed_impacted; eauto.\n  apply/impactedP.\n  move/impactedP: Hx => [v Hv] Hc.\n  exists v => //.\n  apply connect_rev.\n  rewrite -g1_g2_connect.\n  by apply connect_rev.\n- apply/subsetP.\n  move => x Hx.\n  apply: rclosed_impacted; eauto.\n  apply/impactedP.\n  move/impactedP: Hx => [v Hv] Hc.\n  exists v => //.\n  apply connect_rev.\n  rewrite g1_g2_connect.\n  by apply connect_rev.\nQed.\n\nLemma connect_impactedV'_eq :\n  impactedV' f' f g1 = impactedV' f' f g2.\nProof.\napply/eqP.\nrewrite eqEsubset.\napply/andP.\nsplit.\n- apply setSU.\n  apply/subsetP.\n  move => x.\n  move/imsetP => [v Hi] Hv.\n  apply/imsetP.\n  exists v; last by [].\n  by rewrite -connect_impactedV_eq.\n- apply setSU.\n  apply/subsetP.\n  move => x.\n  move/imsetP => [v Hi] Hv.\n  apply/imsetP.\n  exists v; last by [].\n  by rewrite connect_impactedV_eq.\nQed.\n\nLemma connect_checkable_impactedV' :\n  checkable_impactedV' f' f g1 checkable = checkable_impactedV' f' f g2 checkable.\nProof.\napply/eqP.\nrewrite eqEsubset.\napply/andP.\nsplit.\n- apply/subsetP.\n  move => x.\n  rewrite in_set.\n  move/andP => [Hi Hc].\n  rewrite in_set.\n  apply/andP.\n  split => //.\n  by rewrite -connect_impactedV'_eq.\n- apply/subsetP.\n  move => x.\n  rewrite in_set.\n  move/andP => [Hi Hc].\n  rewrite in_set.\n  apply/andP.\n  split => //.\n  by rewrite connect_impactedV'_eq.\nQed.\n\nEnd Other.\n", "meta": {"author": "palmskog", "repo": "chip", "sha": "01fdb4aaf34587f9001f50c6fc3c71f478fb1cd7", "save_path": "github-repos/coq/palmskog-chip", "path": "github-repos/coq/palmskog-chip/chip-01fdb4aaf34587f9001f50c6fc3c71f478fb1cd7/core/check.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2595670970066965}}
{"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.Classes.Morphisms.\nRequire Import Fiat.Parsers.Reflective.Syntax Fiat.Parsers.Reflective.Semantics.\nRequire Import Fiat.Parsers.Reflective.PartialUnfold.\nRequire Import Fiat.Parsers.Reflective.SyntaxEquivalence.\nRequire Import Fiat.Parsers.Reflective.Morphisms.\nRequire Import Fiat.Common.List.ListFacts.\nRequire Import Fiat.Common.Equality.\n\nFixpoint related {T} : interp_TypeCode T -> normalized_of interp_TypeCode T -> Prop\n  := match T return interp_TypeCode T -> normalized_of interp_TypeCode T -> Prop with\n     | csimple T' => fun b e => b = interp_Term e\n     | (dom --> ran)%typecode\n       => fun f1 f2 => forall x1 x2, related x1 x2 -> related (f1 x1) (f2 x2)\n     end.\n\nLocal Ltac concretize := cbv zeta.\nLocal Ltac simpler' := concretize; simpl in *; try subst; intros; auto; try subst; intros; auto;\n  try congruence; try omega; try (exfalso; omega).\nLocal Ltac simplerGoal :=\n  idtac;\n  match goal with\n  | [ H : False |- _ ] => destruct H\n  | [ x : unit |- _ ] => destruct x\n  | [ x : (_ * _)%type |- _ ] => destruct x\n  | [ H : ex _ |- _ ] => destruct H\n  | [ H : _ /\\ _ |- _ ] => destruct H\n  | [ H : _ \\/ _ |- _ ] => destruct H\n  | _ => progress unfold eq_rect in *\n  | [ H : (_ + _)%type -> _ |- _ ]\n    => pose proof (fun x => H (inl x));\n       pose proof (fun x => H (inr x));\n       clear H\n  | [ H : forall x : ?A = clist ?A, _ |- _ ] => clear H\n  | [ H : forall x : csimple ?A = csimple (clist ?A), _ |- _ ] => clear H\n  | [ H : False -> _ |- _ ] => clear H\n  | [ H : sigT ?P -> _ |- _ ] => specialize (fun x p => H (existT P x p))\n  | [ H : sig ?P -> _ |- _ ] => specialize (fun x p => H (exist P x p))\n  | [ H : ?x = ?x -> _ |- _ ] => specialize (H eq_refl)\n  | [ H : forall a b c, (_ + _)%type -> _ |- _ ]\n    => pose proof (fun a b c x => H a b c (inl x));\n       pose proof (fun a b c x => H a b c (inr x));\n       clear H\n  | [ H : forall a b c, False -> _ |- _ ] => clear H\n  | [ H : forall a b c, sigT _ -> _ |- _ ] => specialize (fun a b c x p => H a b c (existT _ x p))\n  | [ H : forall a b c, sig _ -> _ |- _ ] => specialize (fun a b c x p => H a b c (exist _ x p))\n  | [ H : forall a b c (d : ?x = a), _ |- _ ] => specialize (fun b c => H _ b c eq_refl)\n  | [ H : ?P -> _ |- _ ] =>\n    let H' := fresh \"H'\" in\n    assert (H' : P); [ solve [ auto ]\n                     | generalize (H H'); clear H H'; intro H ]\n  | [ H : ?x = ?y |- _ ]\n    => pose proof (pr2_path H);\n       generalize dependent (pr1_path H);\n       clear H;\n       intros ??\n    | [ H : forall a b, _ /\\ _ -> _ |- _ ]\n      => specialize (fun a b c d => H a b (conj c d))\n    | [ H : forall a b (c : ?v = a), _ |- _ ]\n      => specialize (fun b => H _ b eq_refl)\n    | [ H : forall a (b : ?v = a), _ |- _ ]\n      => specialize (H _ eq_refl)\n    | [ H : ?A -> ?B, H' : ?A |- _ ] => specialize (H H')\n  (*| [ H : existT ?F ?T ?X = existT _ ?T ?Y |- _ ] =>\n                        generalize (inj_pair2 _ F _ X Y H); clear H*)\n  | [ H : Some ?X = Some ?Y |- _ ] =>\n    lazymatch X with\n    | Y => clear H\n    | _ => injection H; try clear H; intro\n    end\n  | [ H : option_map _ ?x = Some _ |- _ ]\n    => destruct x eqn:?; unfold option_map at 1 in H\n  | [ H : Some _ = option_map _ ?x |- _ ]\n    => destruct x eqn:?; unfold option_map at 1 in H\n  (*| [ H : an_arg _ _ = an_arg _ _ |- _ ]\n    => apply args_for_encode in H; unfold args_for_code in H\n  | [ H : noargsv = noargsv |- _ ] => clear H\n  | [ H : @args_for_equiv _ _ _ (carrow _ _) _ _ |- _ ]\n    => apply invert_args_for_equiv in H; cbv beta iota in H\n  | [ H : @args_for_equiv _ _ _ (csimple _) _ _ |- _ ]\n    => apply invert_args_for_equiv in H; cbv beta iota in H*)\n  | [ |- _ /\\ _ ] => split\n\n  | [ |- context[if ?E then _ else _] ] => destruct E eqn:?\n  (*| [ |- context[match ?pf with refl_equal => _ end] ] => rewrite (UIP_refl _ _ pf)*)\n  | [ H : context[if ?E then _ else _] |- _ ] => destruct E eqn:?\n  | [ |- (_, _) = (_, _) ] => apply f_equal2\n  | [ |- cons _ _ = cons _ _ ] => apply f_equal2\n  (*| [ |- an_argv _ _ = an_argv _ _ ] => apply f_equal2*)\n  | _ => progress simpl\n  | [ |- context[interp_Term_gen ?f ?v] ]\n    => change (interp_Term_gen f v)\n       with (@interp_Term_gen_step f (@interp_Term_gen f) _ v)\n  | [ |- context[option_map _ ?x] ]\n    => destruct x eqn:?; simpl\n  (*| _ => progress unfold interp_args_for, interp_Term in **)\n  end.\nLocal Ltac simpler := simpler'; repeat (simplerGoal; simpler').\nLocal Ltac simpler_args_for' :=\n  idtac;\n  match goal with\n  | [ args : args_for _ (carrow ?A ?B) |- _ ]\n    => let H := fresh in\n       pose proof (invert_args_for_ex args) as H; cbv beta iota in H;\n       destruct H as [? [? ?]]; subst args\n  | [ args : args_for _ (csimple ?B) |- _ ]\n    => let H := fresh in\n       pose proof (invert_args_for_ex args) as H; cbv beta iota in H;\n       subst args\n  end.\nLocal Ltac simpler_args_for := repeat simpler_args_for'.\n\n\nLemma push_var : forall t v1 v2 t' v1' v2' G,\n  vars v1' v2' = vars v1 v2\n  \\/ List.In (vars v1 v2) G\n  -> (forall t'' v1'' v2'', List.In (vars v1'' v2'') G -> @related t'' v1'' v2'')\n  -> @related t' v1' v2'\n  -> @related t v1 v2.\nProof.\n  simpler.\nQed.\n\nLemma constantOf_correct\n  : forall {T} (t : Term interp_TypeCode T) v\n           (H : constantOf t = Some v),\n    interp_Term t = interp_constantOf v.\nProof.\n  unfold interp_Term;\n  intros T t; induction t;\n  repeat match goal with\n         | [ t : RLiteralTerm _ |- _ ] => destruct t\n         | [ t : RLiteralConstructor _ |- _ ] => destruct t\n         | [ H : constantOf ?bv = Some ?dv, H' : forall a b c d, constantOf b = Some d -> _ |- _ ]\n           => pose proof (fun c => H' _ bv c dv H); clear H\n         | _ => progress simpler_args_for\n         | _ => progress simpler\n         end.\nQed.\n\nLocal Ltac simpler_constantOf\n  := repeat match goal with\n            | [ H : constantOf ?t = Some ?v |- _ ]\n              => apply (@constantOf_correct _ t v) in H\n            end.\n\nLemma fold_left_app {A B A' B'}\n      (f : A -> B -> A) (ls : list B) (init : A)\n      (g : A' -> B' -> A') (ha : A -> A') (hb : B -> B')\n      (H : forall x y, g (ha x) (hb y) = ha (f x y))\n  : List.fold_left g (List.map hb ls) (ha init)\n    = ha (List.fold_left f ls init).\nProof.\n  revert init; induction ls as [|x xs IHxs]; simpl; [ reflexivity | ]; intros.\n  rewrite <- IHxs, H; reflexivity.\nQed.\n\nLemma bool_rect_nodep_const {P x b}\n  : BoolFacts.Bool.bool_rect_nodep P x x b = x.\nProof. destruct b; reflexivity. Qed.\n\nCreate HintDb partial_unfold_hints discriminated.\n\n#[global]\nHint Rewrite <- @interp_Term_syntactify_list @interp_Term_syntactify_nat @List.map_rev : partial_unfold_hints.\n#[global]\nHint Rewrite @nth'_nth List.map_nth List.map_map List.map_length List.map_id @combine_map_r @combine_map_l @first_index_default_map Bool.orb_true_r Bool.orb_true_l Bool.andb_true_l Bool.andb_true_r Bool.orb_false_r Bool.orb_false_l Bool.andb_false_l Bool.andb_false_r BoolFacts.andbr_andb BoolFacts.orbr_orb @bool_rect_nodep_const @BoolFacts.uneta_bool_rect_nodep : partial_unfold_hints.\n#[global]\nHint Resolve map_ext_in fold_left_app (@constantOf_correct cbool) @first_index_default_first_index_partial : partial_unfold_hints.\n\nLocal Ltac meaning_tac_helper' :=\n  idtac;\n  match goal with\n  | [ |- ?x = ?y ] => reflexivity\n  | [ H : forall a b (c : a = _), _ |- _ ] => specialize (fun b => H _ b eq_refl)\n  | [ H : forall a b c (d : b = _), _ |- _ ] => specialize (fun a c => H a _ c eq_refl)\n  | [ H : forall x y, _ = _ |- _ ] => setoid_rewrite <- H\n  | [ |- context[Common.apply_n ?n ?f ?x] ]\n    => clear;\n       let IH := fresh \"IH\" in\n       generalize x; induction n as [|? IH]; simpl;\n       [ reflexivity\n       | intro; rewrite <- IH; unfold interp_Term; simpl;\n         first [ reflexivity\n               | omega ] ]\n  | [ |- context[Operations.List.list_caset_nodep _ _ ?ls] ]\n    => is_var ls; destruct ls\n  | [ |- Operations.List.list_caset_nodep _ _ ?ls = Operations.List.list_caset_nodep _ _ ?ls ]\n    => destruct ls\n  | [ H : ?x = _ |- context[?x] ] => rewrite H\n  | [ |- context[Reflective.ritem_rect_nodep _ _ ?x] ]\n    => destruct x eqn:?; simpl\n  | [ H : forall x, _ = _ |- _ ] => rewrite <- H; reflexivity\n  | [ H : forall x, _ = _ |- _ ] => setoid_rewrite <- H; reflexivity\n  | [ |- context[match ?x with Some _ => _ | None => _ end] ]\n    => destruct x eqn:?\n  end.\nLocal Ltac meaning_tac_helper := repeat meaning_tac_helper'.\n\nLocal Ltac meaning_tac :=\n  repeat first [ progress autorewrite with partial_unfold_hints\n               | progress eauto with partial_unfold_hints\n               | progress rewrite_strat (topdown (hints partial_unfold_hints))\n               | progress meaning_tac_helper\n               | progress simpl_interp_Term_in_all ].\n\nLocal Hint Extern 1 (@related ?T ?X (reflect (RVar ?Y))) =>\nchange (@related T (interp_Term (RVar X)) (reflect (RVar Y))).\nLocal Hint Extern 1 (@related _ (interp_Term_gen ?iRLT ?A ?X1) _) =>\n  change (interp_Term_gen iRLT A X1)\n  with (interp_Term_gen iRLT (RApp A (RVar X1))).\nLemma reify_and_reflect_correct : forall t,\n    (forall v r,\n        @related t v r\n        -> Proper_relation_for _ v (interp_Term (reify _ r)))\n    /\\ (forall a a',\n           @Proper_relation_for t (interp_Term a) (interp_Term a')\n           -> @related t (interp_Term a) (reflect a')).\nProof.\n  unfold interp_Term;\n  induction t; simpler; unfold respectful; eauto.\nQed.\n\nLemma reify_correct : forall t v r,\n  @related t v r\n  -> Proper_relation_for _ v (interp_Term (reify _ r)).\nProof.\n  generalize reify_and_reflect_correct; firstorder.\nQed.\n\nLemma args_for_related_related_map {T v1 v2} (f := @meaning _)\n  : (args_for_related\n       (T := T)\n       (fun T (m : Term interp_TypeCode T) (n : Term (normalized_of interp_TypeCode) T)\n        => related (interp_Term m) (f T n))\n       v1 v2)\n    -> (args_for_related (fun T => Proper_relation_for T)\n                          (map_args_for (@interp_Term) v1)\n                          (map_args_for (@interp_Term) (unmeanings (meanings f v2)))).\nProof.\n  subst f; revert v2.\n  induction v1; intro;\n    pose proof (invert_args_for_ex v2) as H'; simpl in *;\n      [ destruct H' as [? [? ?]] | subst; split; reflexivity ];\n      subst; simpl in *.\n  intros [H0 H1]; split; try assumption;\n    [ | apply IHv1; assumption ]; clear IHv1.\n  apply reify_and_reflect_correct; assumption.\nQed.\n\nLemma interp_apply_meaning_helper\n      T f f' (Hf : @related T f f')\n      args args'\n      (Hargs : args_for_related (fun T' m n => related (interp_Term m) (meaning n)) args args')\n  : apply_args_for f (map_args_for (fun _ t => interp_Term t) args)\n    = interp_Term (apply_meaning_helper (meanings (@meaning interp_TypeCode) args') f').\nProof.\n  apply args_for_related_noind_ind in Hargs.\n  revert f f' Hf.\n  induction Hargs; [ | solve [ simpl; trivial ] ].\n  apply args_for_related_noind_ind in Hargs.\n  simpl in *.\n  eauto with nocore.\nQed.\n\nLocal Ltac simpler_meaning :=\n  repeat match goal with\n         | _ => progress simpler_constantOf\n         | _ => progress simpler_args_for\n         | _ => progress simpl_interp_Term_in_all\n         | _ => progress simpler\n         | _ => progress simpl in *\n         | [ H : ?x = _ |- context[?x] ] => rewrite H\n         | [ H : context[match constantOf ?x with _ => _ end] |- _ ]\n           => destruct (constantOf x) eqn:?\n         | [ H : match ?T with cbool => _ | _ => _ end _ = Some _ |- _ ]\n           => is_var T; destruct T\n         end.\n\nLemma list_rect_nodep_meaning_correct {A : SimpleTypeCode} {P} f f' n n'\n      (Hn : @related P n n')\n      (Hf : @related (A --> clist A --> P --> P) f f')\n      (ls : list (Term interp_TypeCode A))\n  : related (Operations.List.list_rect_nodep n f (List.map (@interp_Term _) ls))\n            (Operations.List.list_rect_nodep n' (fun x xs => f' x (Syntactify.syntactify_list xs)) ls).\nProof.\n  induction ls; simpl in *; [ assumption | ].\n  apply Hf; eauto using eq_refl, @interp_Term_syntactify_list with nocore.\nQed.\n\n#[global]\nHint Resolve @list_rect_nodep_meaning_correct : partial_unfold_hints.\n\nLemma specific_meaning_correct\n      t r val v1 v2\n      (Hrel : args_for_related\n                (fun T' m n => @related T' (interp_Term m) (meaning n)) v1 v2)\n      (Heq : specific_meaning r (meanings (@meaning interp_TypeCode) v2) = Some val)\n  : interp_Term (@RLiteralApp _ t r v1) = interp_Term val.\nProof.\n  destruct r; simpl in Heq;\n    unfold specific_meaning_apply1, specific_meaning_apply2 in *;\n    try solve [ simpler_meaning; meaning_tac ].\n  { simpler_meaning; meaning_tac.\n    apply interp_apply_meaning_helper; simpl; try assumption; [].\n    apply list_rect_nodep_meaning_correct; simpl; eauto with nocore.\n    simpler_meaning; meaning_tac. }\n  { simpler_meaning; meaning_tac.\n    rewrite Plus.plus_comm; meaning_tac. }\nQed.\n\nLocal Hint Resolve push_var.\nLemma meaning_correct\n  : forall G t e1 e2,\n    Term_equiv G e1 e2\n    -> (forall t' v1 v2, List.In (vars v1 v2) G\n                         -> @related t' v1 v2)\n    -> @related t (interp_Term e1) (meaning e2).\nProof.\n  unfold interp_Term;\n    induction 1 (*using Term_equiv_ind_in*); try solve [ simpler; eauto ].\n  { simpler.\n    repeat match goal with\n           | [ H : args_for_related_ind _ _ _ |- _ ]\n             => apply args_for_related_noind_ind in H\n           | [ H : args_for_related (fun x y z => ?P -> _) _ _ |- _ ]\n             => setoid_rewrite <- args_for_related_impl in H\n           | _ => progress simpl_interp_Term_in_all\n           | [ H : ?A -> ?B, H' : ?A |- _ ] => specialize (H H')\n           | [ f : RLiteralTerm _ |- _ ] => destruct f\n           | [ |- apply_args_for _ _ = apply_args_for _ _ ]\n             => apply apply_args_for_Proper;\n                  [ apply RLiteralTerm_Proper | apply args_for_related_related_map; assumption ]\n           | [ |- context[specific_meaning ?r ?x] ]\n             => destruct (specific_meaning r x) eqn:?\n           end.\n    eapply specific_meaning_correct; eassumption. }\nQed.\n\nLemma nil_context : forall t v1 v2,\n  List.In (vars v1 v2) nil\n  -> @related t v1 v2.\nProof.\n  simpl; tauto.\nQed.\n\nLocal Hint Resolve nil_context meaning_correct reify_correct.\nTheorem polynormalize_correct : forall t (E : polyTerm t),\n    Term_equiv nil (E interp_TypeCode) (E (normalized_of interp_TypeCode))\n    -> Proper_relation_for _ (interp_Term (E _)) (interp_Term (polynormalize E _)).\nProof.\n  unfold interp_Term, polynormalize, normalize; eauto.\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/Reflective/LogicalRelations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2595389365769605}}
{"text": "(** This file contains record definitions for\n ** type, function and predicate environments.\n **)\nRequire Import Expr SepExpr.\nRequire Import Env.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nModule Type CoreEnv.\n  Parameter core : Repr type.\n  Parameter pc : tvar.\n  Parameter st : tvar.\nEnd CoreEnv.\n\nModule Type Package.\n  Declare Module SEP : SepExpr.\n  Declare Module CE : CoreEnv.\n\n  Record TypeEnv : Type :=\n  { Types : Repr type\n  ; Funcs : forall ts, Repr (signature (repr CE.core (repr Types ts)))\n  ; Preds : forall ts, \n    Repr (SEP.predicate (repr CE.core (repr Types ts)) CE.pc CE.st)\n  }.\n\n  Section Apps.\n    Variable TE : TypeEnv.\n    \n    Definition applyTypes (ls : list type) : list type :=\n      repr CE.core (repr (Types TE) ls).\n    Definition applyFuncs ts (ls : functions (applyTypes ts)) : functions (applyTypes ts) :=\n      repr (Funcs TE ts) ls.\n    Definition applyPreds ts (ls : SEP.predicates (applyTypes ts) CE.pc CE.st) : SEP.predicates (applyTypes ts) CE.pc CE.st :=\n      repr (Preds TE ts) ls.\n  End Apps.\n\n  \n  (** These are reducible by [simpl] **)\n  Definition applyTypes_red TE (ls : list type) : list type :=\n    match TE with\n      | {| Types := ts |} =>\n        repr CE.core (repr ts ls)\n    end.\n  Definition applyFuncs_red TE ts : functions (applyTypes TE ts) -> functions (applyTypes TE ts) :=\n    match TE with\n      | {| Types := ts' ; Funcs := fs |} => fun ls =>\n        repr (fs ts) ls\n    end.\n  Definition applyPreds_red TE ts : SEP.predicates (applyTypes TE ts) CE.pc CE.st -> SEP.predicates (applyTypes TE ts) CE.pc CE.st :=\n    match TE with\n      | {| Types := ts' ; Preds := ps |} => fun ls =>\n        repr (ps ts) ls\n    end.\n\n  Ltac glue_env l r ret :=\n    let res := constr:(\n      let types := Env.repr_combine (Types l) (Types r) in\n      {| Types := types\n       ; Funcs := fun ts => Env.repr_combine (Funcs l (Env.repr types ts)) (Funcs r (Env.repr types ts))\n       ; Preds := fun ts => Env.repr_combine (Preds l (Env.repr types ts)) (Preds r (Env.repr types ts))\n       |})\n    in\n    ret res.\n    \nEnd Package.\n\nModule Type AlgoTypes (SEP : SepExpr) (CE : CoreEnv).\n  Parameter AlgoImpl  : list type -> Type.\n  Parameter AlgoProof : forall ts : list type, \n    functions (repr CE.core ts) -> \n    SEP.predicates (repr CE.core ts) CE.pc CE.st ->\n    AlgoImpl ts -> Type.\nEnd AlgoTypes.\n\nModule Make (SEP' : SepExpr) (CE' : CoreEnv) <: Package with Module SEP := SEP' with Module CE := CE'.\n  Module SEP := SEP'.\n  Module CE := CE'.\n\n  Section TypeEnv.\n    Record TypeEnv : Type :=\n    { Types : Repr type\n    ; Funcs : forall ts, Repr (signature (repr CE.core (repr Types ts)))\n    ; Preds : forall ts, Repr (SEP.predicate (repr CE.core (repr Types ts)) CE.pc CE.st)\n    }.\n\n    Variable TE : TypeEnv.\n\n    Definition applyTypes (ls : list type) : list type :=\n      repr CE.core (repr (Types TE) ls).\n    Definition applyFuncs ts (ls : functions (applyTypes ts)) : functions (applyTypes ts) :=\n      repr (Funcs TE ts) ls.\n    Definition applyPreds ts (ls : SEP.predicates (applyTypes ts) CE.pc CE.st) : SEP.predicates (applyTypes ts) CE.pc CE.st :=\n      repr (Preds TE ts) ls.\n\n  End TypeEnv.\n\n  Definition applyTypes_red TE (ls : list type) : list type :=\n    match TE with\n      | {| Types := ts |} =>\n        repr CE.core (repr ts ls)\n    end.\n  Definition applyFuncs_red TE ts : functions (applyTypes TE ts) -> functions (applyTypes TE ts) :=\n    match TE with\n      | {| Types := ts' ; Funcs := fs |} => fun ls =>\n        repr (fs ts) ls\n    end.\n  Definition applyPreds_red TE ts : SEP.predicates (applyTypes TE ts) CE.pc CE.st -> SEP.predicates (applyTypes TE ts) CE.pc CE.st :=\n    match TE with\n      | {| Types := ts' ; Preds := ps |} => fun ls =>\n        repr (ps ts) ls\n    end.\n    \nEnd Make.\n\nModule AlgoPack (P : Package) (A : AlgoTypes P.SEP P.CE).\n\n  Record TypedPackage : Type :=\n  { Env   : P.TypeEnv \n  ; Algos : forall ts, A.AlgoImpl ts\n  ; Algos_correct : forall ts (fs : functions (P.applyTypes Env ts)) ps, \n    @A.AlgoProof (repr (P.Types Env) ts) (P.applyFuncs Env ts fs) (P.applyPreds Env ts ps) (Algos _)\n  }.\n\n  (** given to [TypedPackage]s, combines them and passes the combined [TypedPackage]\n   ** to [k].\n   ** This tactic will fail if any of the environments are not compatible.\n   **)\n  Ltac glue_pack composite composite_correct l r ret :=\n    P.glue_env (Env l) (Env r) ltac:(fun nenv' =>\n      let res := constr:(\n        let nenv := nenv' in\n        let types := P.Types nenv in\n        {| Env   := nenv \n         ; Algos := fun ts => composite (Algos l (P.applyTypes nenv ts)) (Algos r (Env.repr types ts))\n         ; Algos_correct := fun ts fs ps =>\n           composite_correct \n             (Algos_correct l (P.applyTypes nenv ts) (P.applyFuncs nenv fs) (P.applyPreds nenv ps))\n             (Algos_correct r (P.applyTypes nenv ts) (P.applyFuncs nenv fs) (P.applyPreds nenv ps))\n         |})\n      in\n      ret res).\n(*\n(**\n      let algosL := constr:(fun ts => Algos l (applyTypes nenvEnv.repr ntypesV ts)) in\n      let algosR := constr:(fun ts => Algos r (Env.repr ntypesV ts)) in\n      let algosCL :=\n        constr:(fun ts fs ps =>\n          Algos_correct l (Env.repr ntypesV ts)\n          (Env.repr (nfuncsV ts) fs)\n          (Env.repr (npredsV ts) ps)) in\n      let algosCR :=\n        constr:(fun ts fs ps =>\n          Algos_correct r (Env.repr ntypesV ts)\n          (Env.repr (nfuncsV ts) fs)\n          (Env.repr (npredsV ts) ps)) in\n      let pf := constr:(fun ts fs ps => AllAlgos_correct_composite (algosCL ts fs ps) (algosCR ts fs ps)) in\n      opaque pf ltac:(fun pf =>\n      let res :=\n        constr:{|\n          Types := ntypesV;\n          Funcs := nfuncsV;\n          Preds := npredsV;\n          Algos := fun ts => AllAlgos_composite (algosL ts) (algosR ts);\n          Algos_correct := pf\n        |} in\n        ret res)).\n**)\n  \n  Ltac refine_glue_pack l r :=\n    let reduce_repr e := e in\n    let opaque v k := k v in\n    match eval hnf in l with\n      | @Build_TypedPackage ?CT ?PC ?ST ?SAT ?READ ?WRITE ?tl ?fl ?pl ?al ?acl =>\n        match eval hnf in r with\n        | @Build_TypedPackage _ _ _ _ _ _ ?tr ?fr ?pr ?ar ?acr =>\n          refine (\n              let types := repr_combine tl tr in\n              let funcs := fun ts => repr_combine (fl (repr types ts)) (fr (repr types ts)) in\n              let preds := fun ts => repr_combine (pl (repr types ts)) (pr (repr types ts)) in\n              @Build_TypedPackage CT PC ST SAT READ WRITE \n                types funcs preds\n                (fun ts => AllAlgos_composite (al (repr types ts)) (ar (repr types ts)))\n                _ \n               ); \n          (subst; abstract exact (fun ts fs ps => AllAlgos_correct_composite \n                  (acl (repr (repr_combine tl tr) ts) \n                       (repr (repr_combine (fl (repr (repr_combine tl tr) ts)) (fr (repr (repr_combine tl tr) ts))) fs)\n                       (repr (repr_combine (pl (repr (repr_combine tl tr) ts)) (pr (repr (repr_combine tl tr) ts))) ps))\n                  (acr (repr (repr_combine tl tr) ts)\n                       (repr (repr_combine (fl (repr (repr_combine tl tr) ts)) (fr (repr (repr_combine tl tr) ts))) fs)\n                       (repr (repr_combine (pl (repr (repr_combine tl tr) ts)) (pr (repr (repr_combine tl tr) ts))) ps))))\n      end\n  end.\n\n(*\nLtac hlist_from_tuple tpl acc := \n  match tpl with\n    | tt => acc\n    | (?L, ?R) => \n      let acc := hlist_from_tuple R acc in\n      hlist_from_tuple L acc\n    | _ => constr:(@HCons _ _ _ _ tpl acc)\n  end.\n*)\n\n(** given a tuple or list of [TypedPackage]s, this tactic combines them all and calls [k] with \n ** the result.\n **)\nLtac glue_packs packs k :=\n  match type of packs with\n    | TypedPackage _ _ _ _ _ _ => k packs\n    | _ =>\n      match packs with\n        | tt => k BedrockPackage.bedrock_package\n        | nil => k BedrockPackage.bedrock_package\n        | ?L :: ?R =>\n          glue_packs R ltac:(fun R => glue_pack L)\n        | (?L, ?R) =>\n          glue_packs L ltac:(fun L => \n          glue_packs R ltac:(fun R => \n            glue_pack L R k))\n      end\n  end.\n\n(** TODO: is there a way to make this more efficient? **)\nLtac opaque_pack pack :=\n  match eval hnf in pack with\n    | @Build_TypedPackage ?CT ?PC ?ST ?SAT ?READ ?WRITE ?tl ?fl ?pl ?al ?acl =>\n      refine ({|\n        Types := tl ;\n        Funcs := fl ;\n        Preds := pl ;\n        Algos := al ;\n        Algos_correct := _\n      |});\n      abstract (exact acl)\n  end.\n*)\n\nEnd AlgoPack.", "meta": {"author": "csgordon", "repo": "bedrock", "sha": "debab1b6e491b7c5e83bd3b1fe5d0e4c4e728d12", "save_path": "github-repos/coq/csgordon-bedrock", "path": "github-repos/coq/csgordon-bedrock/bedrock-debab1b6e491b7c5e83bd3b1fe5d0e4c4e728d12/src/TypedPackage.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.2595221635520404}}
{"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 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": "MetaCoq", "repo": "metacoq", "sha": "c340242b43ebe26f3bacb1c72ef82b8ca61da632", "save_path": "github-repos/coq/MetaCoq-metacoq", "path": "github-repos/coq/MetaCoq-metacoq/metacoq-c340242b43ebe26f3bacb1c72ef82b8ca61da632/pcuic/theories/PCUICWellScopedCumulativity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.25952216355204033}}
{"text": "From Undecidability.TM Require TM_facts ProgrammingTools CaseList CaseBool.\nFrom Complexity.TM Require Code.Decode Code.DecodeList.\n\nFrom Undecidability.TM Require Import TM.\nFrom Complexity.TM.PrettyBounds Require Import SizeBounds.\n\nFrom Undecidability.L.Complexity  Require Import UpToCNary.\nFrom Complexity.NP.L  Require Import LMGenNP.\n\n\nFrom Undecidability.L.AbstractMachines Require Import FlatPro.Programs.\nFrom Complexity.L.AbstractMachines Require Import FlatPro.Computable.Compile.\n     \nUnset Printing Coercions.\n\nFrom Undecidability.TM.L Require Alphabets M_LHeapInterpreter.\n\nFrom Coq Require Import Lia Ring Arith.\n\nFrom Undecidability.TM.L Require Import Boollist_to_Enc.\n\nFrom Complexity.L.AbstractMachines Require SizeAnalysisStep LMBounds_Loop.\n\nSet Default Proof Using \"Type\".\n\nImport DecodeList Decode.\nModule LMtoTM.\n  Section sec.\n    Import ProgrammingTools Combinators M_LHeapInterpreter.\n\n    Variable (sig : finType).\n    \n    Context `{retr__LAM : Retract sigStep sig}\n            `{retr__list : Retract (sigList bool) sig}.\n\n    \n    Definition retr__listHClos : Retract (sigList Alphabets.sigHClos) sig\n      := ComposeRetract retr__LAM retr_closures_step.\n\n    Definition retr__Heap : Retract Alphabets.sigHeap sig\n    := ComposeRetract retr__LAM retr_heap_step.\n\n    Definition retr__HClos : Retract Alphabets.sigHClos sig :=\n      ComposeRetract retr__listHClos _.\n        \n    Definition retr__pro : Retract Alphabets.sigPro sig := ComposeRetract retr__HClos _.\n\n    Definition retr__nat : Retract sigNat sig:= ComposeRetract retr__pro _.\n    \n    Definition Rel : pRel (sig ^+) bool 11 :=\n      fun tin '(y,tout) =>\n        forall (P:Pro),\n        tin[@Fin1] ≃(retr__pro) P ->\n        (forall i : Fin.t 9, isVoid tin[@FinR 2 i])\n        -> match y with\n            false => ~ exists (bs:list bool), tin[@Fin0] ≃ bs\n          | true => exists (bs : list bool),\n                   tin[@Fin0] ≃ bs\n                   /\\ exists sigma' k, ARS.evaluatesIn LM_heap_def.step k (initLMGen P (compile (Extract.enc (rev bs)))) sigma'\n          end.\n(* initLMGen = n s c : list Tok => ([(0, s ++ c ++ [appT])], [], []) *)\n    Import Boollist_to_Enc ListTM Alphabets StepTM.\n\n    Definition M : pTM sig ^+ bool 11 :=\n      If (CheckEncodesBoolList.M _ @ [|Fin0|])\n         (Return (F:=FinType (EqType unit)) (LiftTapes (BoollistToEnc.M _ retr__pro) [|Fin0;Fin2;Fin3;Fin4 |];; (* 0:right, 2:compile (enc (rev b)), 3,4:right*)\n                  LiftTapes (ChangeAlphabet (WriteValue ([appT])) retr__pro) [| Fin3|];; (*3:[appT]*)\n                  LiftTapes (ChangeAlphabet (App' _ ) retr__pro) [|Fin2;Fin3|];; (*3:compile (rev b)++[appT]*)         \n                  LiftTapes (ChangeAlphabet (App' _) retr__pro) [|Fin1;Fin3|];; (*3:P++compile (rev b)++[appT]*)\n                  LiftTapes (ChangeAlphabet (WriteValue ((@nil (LM_heap_def.HClos)))) retr__listHClos) [| Fin0|];; (*0:[]*)\n                  LiftTapes (ChangeAlphabet (WriteValue (0)) (StepTM.retr_nat_step_clos_ad retr__listHClos)) [| Fin5|];; (*5:0*)\n                  LiftTapes (StepTM.ConsClos retr__listHClos) [|Fin0;Fin5;Fin3 |];; (* 0: initLMGen, 5,3:right *)\n                  LiftTapes (Reset _) [|Fin1|];;\n                  LiftTapes (Reset _) [|Fin2|];;(*1,2: right*)\n(*1,2: empty*)\n                  LiftTapes (ChangeAlphabet (WriteValue ((@nil (LM_heap_def.HClos)))) retr__listHClos) [| Fin1|];; (*1:[]*)\n                  LiftTapes (ChangeAlphabet (WriteValue ((@nil (LM_heap_def.HEntr)))) retr__Heap) [| Fin2|];; (*2:[]*)\n                  ChangeAlphabet M_LHeapInterpreter.Loop retr__LAM )\n                 true)\n         (Return Nop false).\n \n    \n    Definition Ter time: tRel sig^+ 11 :=\n      (fun tin k =>\n         exists (P:Pro) steps__LM,\n           tin[@Fin1] ≃(retr__pro) P /\\\n           (forall i : Fin.t 9, isVoid tin[@FinR 2 i])\n           /\\ (((~exists (bs : list bool), tin[@Fin0] ≃ bs) /\\ steps__LM = 0)\n             \\/\n             exists (bs : list bool),\n               tin[@Fin0] ≃ bs\n               /\\ exists sigma', ARS.evaluatesIn LM_heap_def.step steps__LM (initLMGen P (compile (Extract.enc (rev bs)))) sigma')\n           /\\ time (steps__LM,sizeOfmTapes tin) <= k).\n\n    Import MoreList.\n    Import FlatPro.SizeAnalysisStep TM_LHeapInterpreter.LMBounds_Loop.\n\n    Lemma size_compile_list_bool:\n      (fun bs : list bool => Code.size (compile (Extract.enc (rev bs)))) <=c (fun bs => length bs + 1).\n    Proof.\n      (* From Undecidability.L.AbstractMachines.TM_LHeapInterpreter Require  *)\n      evar (c:nat). exists c. intros xs.\n      rewrite size_le_sizeP. unfold sizeP;rewrite sizeP_size,Lists.size_list.\n      rewrite map_rev,<-sumn_rev. rewrite MoreBase.sumn_le_bound.\n      2:{ intros ? ([]&<-&?)%in_map_iff. all:cbv. reflexivity. nia. }\n      rewrite map_length. ring_simplify. [c]:exact 54. unfold Lists.c__listsizeNil. nia.\n    Qed.\n\n    \n    Ltac fin_inst_all H :=\n      match type of H with\n        forall i : Fin.t 0 , _ => clear H\n      | forall i : Fin.t (S ?n) , @?P i =>\n        let tmp := fresh \"_tmp\" in\n        let H':= fresh H in\n        rename H into _tmp; \n        assert (H':= tmp Fin0);\n        assert (H:= fun i => tmp (Fin.FS i));clear tmp;\n        fin_inst_all H\n      end.\n   \n    Local Arguments sizeOfmTapes : simpl never.\n    Definition _Terminates :\n      { time : UpToC ((fun '(steps, size) => (steps + 1) * (steps + size + 1) ^3 ))\n               & projT1 M ↓ Ter time}.\n    Proof.\n      eexists_UpToC time.\n      eapply TerminatesIn_monotone.\n      { unfold M. TM_Correct.\n        all: eauto 2 using App'_Terminates,App'_Realise,BoollistToEnc.Realise,ConsClos_Realise,ConsClos_Terminates,Loop_Terminates.\n        all: try now (notypeclasses refine (@Reset_Terminates _ _ _ _ _);shelve).\n        all: try now (notypeclasses refine (@Reset_Realise _ _ _ _ _);shelve).\n        1:notypeclasses refine (CheckTapeContains.Realise _ _).\n        3:notypeclasses refine (CheckTapeContains.Terminates _ _).\n        4:apply CheckEncodesBoolList.Terminates'.\n        1,3:apply CheckEncodesBoolList.Realise';now destruct x.\n        now apply list_encode_prefixInjective,DecodeBool.bool_encode_prefixInjective.\n        apply BoollistToEnc.Terminates. \n      }\n      intros tin k H. hnf in H. destruct H as (P&steps__LM&HP&Hrem&Hsteps&Hk).\n      cbn -[plus mult]. infTer 5.\n      1:erewrite length_tape_local_right,right_sizeOfTape; rewrite <- Hk.\n      2:{ intros tout b [[[Hb1] Hb2] Hrem']. fin_inst_all Hrem. TMSimp.\n          destruct Hb1 as [(bs&Hbs) | ]. 2: now apply Nat.le_0_l.\n          destruct Hsteps as [ [[] _] | Hsteps].\n          { eexists. contains_ext. }\n          destruct Hsteps as (bs'&Hbs'&Hsteps).\n          replace bs' with bs in *.\n          2:{\n            destruct Hbs as [? Hbs]. destruct Hbs' as [? Hbs']. rewrite Hbs' in Hbs. inv Hbs.\n            rewrite !map_map in H1. eapply app_inv_tail, map_injective in H1.\n            2:{ intros ? ? [= ]. now eapply retract_f_injective. }\n            apply encode_list_injective in H1. easy. apply Encode_bool_injective.\n          }\n          clear bs' Hbs'.\n          set (sizeM := sizeOfmTapes [|tin_0; tin_1; tin_2; tin_3; tin_4; tin_5; tin_6; tin_7; tin_8; tin_9; tin_10|]).\n          assert (Hlebs : length bs <= sizeM).\n          { clear - Hbs. unfold sizeM. rewrite <- sizeOfmTapes_upperBound with (t:=tin_0).\n           2:now eapply vect_nth_In with (i:=Fin0).\n           destruct Hbs as (rem&->). cbn.  rewrite encode_list_concat. repeat (autorewrite with list;cbn).\n           rewrite length_concat. rewrite map_map;cbn. rewrite sumn_map_c. nia. } \n          modpon Hb2;[]. infTer 3. 2:easy.\n          {hnf. cbn. TMSimp. exists bs. repeat simple apply conj. easy. 1-3:try isVoid_mono. \n           erewrite UpToC_le. rewrite Hlebs. reflexivity. }\n          intros t1_ _ (HP'&Hrem_1). specialize (HP' bs). TMSimp. modpon HP'.\n          infTer 5. TMSimp_goal. intros t2_ _ (Ht2&Ht2Rem). modpon Ht2.\n          (*unfold tapes in tin,tout,t1 |-. destruct_vector. cbn [Vector.nth Vector.caseS] in *. all:subst. *)\n          TMSimp.\n          \n          infTer 5.\n          {hnf;cbn. eexists _ (*(compile (Extract.enc (rev bs)))*),[appT]. repeat simple apply conj. 1-2:now simpl_surject;try contains_ext.\n           setoid_rewrite ((proj2_sig (BaseCode.App'_steps_nice _) _) : _ <= _).\n           \n           rewrite (correct__leUpToC size_compile_list_bool), Hlebs. reflexivity.\n          }\n          intros t3_ _ (Ht3&Ht3Rem). specialize (Ht3 (compile (Extract.enc (rev bs))) [appT]). modpon Ht3;[]. TMSimp.\n          infTer 5.\n          { hnf;cbn. eexists _, _. repeat simple apply conj. 1-2:now simpl_surject;try contains_ext.\n            eassert (H':=proj2_sig (BaseCode.App'_steps_nice _) P).\n            hnf in H'. rewrite H'. reflexivity. }\n          intros t4_ _ (Ht4&Ht4Rem). specialize (Ht4 P (compile (Extract.enc (rev bs)) ++ [appT])). TMSimp.\n          modpon Ht4; [].\n          infTer 5. intros t5_ _ (Ht5&Ht5Rem). modpon Ht5;[].\n          infTer 5. intros t6_ _ (Ht6&Ht6Rem). TMSimp. modpon Ht6;[].\n          infTer 5.\n          { hnf;cbn. eexists _,_,_. repeat simple apply conj. 1-3:now simpl_surject;try contains_ext.\n            match goal with |- _ <= ?c' => set (c:=c') end.\n            unfold CaseList.Constr_cons_steps, Reset_steps. ring_simplify.\n            setoid_rewrite Encode_pair_hasSize. cbn - [plus mult].\n            repeat setoid_rewrite @BaseCode.encodeList_size_app.\n            unfold c.\n            rewrite (correct__leUpToC size_compile_list_bool), Hlebs. reflexivity.             \n          }\n          intros t7_ _ (Ht7&Ht7Rem). modpon Ht7 . progress TMSimp.\n          infTer 4. now contains_ext. reflexivity.\n          intros t8_ _ (Ht8'&Ht8Rem). modpon Ht8'. TMSimp.\n          (*move Hsteps at bottom. destruct Hsteps as [ [H' ->] | H' ].\n          { edestruct move H' destruct H'. }*)\n          infTer 3.\n          { split. now contains_ext. unfold Reset_steps.\n            rewrite (correct__leUpToC size_compile_list_bool), Hlebs.  reflexivity. }\n          reflexivity. \n          intros t9_ _ (Ht9'&Ht9Rem). modpon Ht9'.\n          infTer 4. intros t10 _ (Ht10&Ht10Rem). TMSimp.\n          modpon Ht10.\n          infTer 4. intros t11 _ (Ht11&Ht11Rem). specialize Ht11. modpon Ht11. TMSimp.\n          hnf. eexists [(0,_)],[],[],_. repeat eapply conj. \n          -eexists. eassumption.\n          -cbn. simpl_surject. TMSimp_goal. contains_ext. \n          -cbn. simpl_surject. TMSimp_goal. contains_ext. \n          -cbn. simpl_surject. TMSimp_goal. contains_ext.\n          -intros i. cbn. destruct_fin i;cbn. all:simpl_surject. all:isVoid_mono.\n          -unshelve erewrite (correct__leUpToC Loop_steps_nice (_,_)). \n           cbn [length]. unfold sizeP. rewrite !map_app,!sumn_app.\n         \n           rewrite (correct__leUpToC sizeT_compile_list_bool bs).\n           set (c:= sumn (map sizeT [appT])); cbv in c; subst c.\n           rewrite !Nat.add_assoc.\n           set (c':= c__leUpToC) at 3.\n           replace ((sumn (map sizeT P) + c' * ((| bs |) + 1) + 1 + 1))\n              with (sizeP P + c' * ((| bs |) + 1) + 1) by (unfold sizeP;lia).\n          replace (steps__LM + sumn (map sizeT P) + c__leUpToC * ((| bs |) + 1) + 1 + 1)\n            with (steps__LM + sizeP P + c' * ((| bs |) + 1) + 1) by (unfold sizeP;lia).\n           rewrite Hlebs. reflexivity.\n      }\n      ring_simplify.\n      unfold Reset_steps.\n      setoid_rewrite (sizeP_le_size P).\n      repeat rewrite sizeOfTape_tape_contains_size with (1:=(tape_contains_contains_size HP)). \n      repeat rewrite sizeOfmTapes_upperBound with (tps:=tin). 2-3:now eapply vect_nth_In. \n      [time]:refine (fun '(steps__LM,sizeM) => _).\n      set (sizeM := sizeOfmTapes _). unfold time. reflexivity.\n      unfold time. clear time.\n      set (c':=c__leUpToC). set (c'':=c__leUpToC). set (c''':=c__leUpToC).\n      clearbody c'. clearbody c''. clearbody  c'''.\n      (* nary simple apply (upToC_mul_c_r__out_nary (c:=(c''+1)^2*((c'''+1)^2))). nia. *)\n      smpl_upToC.\n      all:cbn [Nat.pow];try now smpl_upToC_solve.\n    Qed.\n\n    Definition Terminates := projT2 _Terminates.\n\n      \n    Definition Realise : M ⊨ Rel.\n    Proof.\n      unfold M. eapply Realise_monotone.\n      { TM_Correct.\n        1:{  notypeclasses refine (CheckTapeContains.Realise _ _).\n             eapply CheckEncodesBoolList.Realise'. now destruct x.\n             now eapply list_encode_prefixInjective,DecodeBool.bool_encode_prefixInjective. }\n        now apply BoollistToEnc.Realise.\n        all:try now simple apply App'_Realise.\n        now apply ConsClos_Realise.\n        all:try now (notypeclasses refine (@Reset_Realise _ _ _ _ _);shelve).\n        now simple apply Loop_Realise.\n      }\n      intros tin (yout,tout) H. hnf in H|-*. cbn in H.\n      intros P HP HRem.\n      destruct H as [H|H].\n      2:{destruct H as (?&H&->&_&->). destruct H as (([Hx]&Hx')&Hrem). inv Hx. easy. }\n      destruct H as (t1&Hcond&H). destruct Hcond as (([Hx]&Hx')&Hrem).\n      (*fin_inst_all HRem. cbn [FinR] in *.   *)  \n      modpon Hx'. inv Hx'.\n      inv Hx. destruct H0 as (bs&Hx). TMSimp. \n      do_n_times_fin 9 ltac:(fun i => let H := fresh \"HRem\" in specialize (HRem i) as H;cbn in H);clear HRem.\n      modpon H0.\n      eexists bs. split. contains_ext.\n      modpon H2;[]. modpon H4;[].\n      modpon H6;[].\n      modpon H8;[].\n      modpon H10;[].\n      modpon H12;[]. modpon H14;[]. modpon H16;[].\n      modpon H18;[].\n      modpon H20;[].\n      rename H11 into H11',H22 into H11.\n      specialize (H11 (fst (fst (initLMGen P (compile (Extract.enc (rev bs)))))) [] []).\n      cbn in H11. TMSimp. \n      modpon H11.\n      1:{ instantiate (1:= [| _;_;_;_;_;_;_;_|]). \n          intros i. destruct_fin i;cbn;simpl_surject;eauto.\n      }\n      destruct H11 as (T'&V'&H'&k&Hred&HHalt&_).\n      exists (T',V',H'),k. split. exact Hred. exact HHalt.\n    Qed.\n    \n  End sec.\nEnd LMtoTM.\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/M_LM2TM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.2595221570164318}}
{"text": "(* begin hide *)\n\nFrom mathcomp Require Import all_ssreflect.\n\nRequire Import String.\nRequire Import QString.\n\nRequire Import Value.\n\nRequire Import Schema.\nRequire Import SchemaAux.\nRequire Import SchemaWellFormedness.\n\nRequire Import Graph.\nRequire Import GraphConformance.\n\nRequire Import Query.\nRequire Import QueryAux.\nRequire Import QueryConformance.\n\nRequire Import Response.\n\nRequire Import QuerySemantics.\n\n(* end hide *)\n\n\nOpen Scope string_scope.\n\n\nSection Values.\n\n  Inductive Scalar : Type :=\n  | VInt : nat -> Scalar\n  | VBool: bool -> Scalar            \n  | VString : string -> Scalar\n  | VFloat : nat -> nat -> Scalar.\n \n  \n\n  (** We need to prove that Value has a decidable equality procedure,\n      we hide it to unclutter the docs\n   *)\n  (* begin hide *)\n  Notation vtype := (nat + bool + string + (nat * nat))%type.\n\n  Definition tuple_of_scalar (v : Scalar) :=\n    match v with\n    | VInt n => inl (inl (inl n))\n    | VBool b => inl (inl (inr b))\n    | VString s => inl (inr s)\n    | VFloat n1 n2 => inr (n1, n2)\n    end.\n\n  Definition scalar_of_tuple (t : vtype) : Scalar :=\n    match t with\n    | inl (inl (inl n)) => VInt n\n    | inl (inl (inr b)) => VBool b\n    | inl (inr s) => VString s\n    | inr (n1, n2) => VFloat n1 n2\n    end.\n\n  Lemma tuple_of_scalarK : cancel tuple_of_scalar scalar_of_tuple.\n  Proof. by case; case.\n  Qed.\n   \n  Canonical scalar_eqType := EqType Scalar (CanEqMixin tuple_of_scalarK).\n  (* end hide *)\n \n  Definition coerce : Scalar -> Scalar := id.\n\n  \n \n  Variable (schema : graphQLSchema). \n  Fixpoint check_scalar (ty : type) (v : Scalar) : bool :=\n    match v with\n    | VInt _ => if ty is NamedType name then\n                 (name == \"Int\") || (name == \"ID\")\n               else\n                 false\n                   \n    | VBool _ => if ty is NamedType name then\n                  name == \"Boolean\"\n                else\n                  false \n                    \n    | VString s => if ty is NamedType name then\n                    (name == \"String\")\n                    ||\n                    if lookup_type schema name is Some (enum _ { members }) then\n                      s \\in members\n                    else\n                      false\n                  else\n                    false\n                      \n    | VFloat _ _ => if ty is NamedType name then\n                     name == \"Float\"\n                   else\n                     false\n    end.\n\nEnd Values.\n\n\n\nSection WrongGraph.\n\n  Coercion namedType_of_string (s : string) := NamedType s.\n\n\n  \n  Let IDType := scalar \"ID\".\n  Let StringType := scalar \"String\".\n  Let FloatType := scalar \"Float\".\n\n\n  \n  Let StarshipType := object \"Starship\" implements [::] {\n                              [:: Schema.Field \"id\" [::] \"ID\";\n                                  Schema.Field \"name\" [::] \"String\";\n                                  Schema.Field \"length\" [::] \"Float\"\n                              ]\n                            }.\n\n  Let CharacterType := interface \"Character\" {\n                                  [::\n                                     Schema.Field \"id\" [::] \"ID\" ;\n                                     Schema.Field \"name\" [::] \"String\";\n                                     Schema.Field \"friends\" [::] [ \"Character\" ]\n                                    ]\n                                  }.\n\n  \n  Let DroidType := object \"Droid\" implements [:: \"Character\"] {\n                           [::\n                              Schema.Field \"id\" [::] \"ID\" ;\n                              Schema.Field \"name\" [::] \"String\";\n                              Schema.Field \"friends\" [::] [ \"Character\" ];\n                              Schema.Field \"primaryFunction\" [::] \"String\"\n                           ]\n                         }.\n  \n  \n  Let HumanType := object \"Human\" implements [:: \"Character\"] {\n                           [::\n                              Schema.Field \"id\" [::] \"ID\" ;\n                              Schema.Field \"name\" [::] \"String\";\n                              Schema.Field \"friends\" [::] [ \"Character\" ];\n                              Schema.Field \"starships\" [::] [ \"Starship\" ]\n                           ]\n                         }.\n\n  Let EpisodeType := enum \"Episode\" { [:: \"NEWHOPE\" ; \"EMPIRE\" ; \"JEDI\" ] }.\n\n\n  Let SearchResultType := union \"SearchResult\" { [:: \"Human\" ; \"Droid\" ; \"Starship\"] }.\n\n\n  Let QueryType := object \"Query\" implements [::] {\n                           [::\n                              Schema.Field \"hero\" [:: FieldArgument \"episode\" \"Episode\"] \"Character\";\n                              Schema.Field \"search\" [:: FieldArgument \"text\" \"String\"] [ \"SearchResult\" ]\n                           ]\n                         }.\n\n  Let schema  := GraphQLSchema \"Query\"  [:: IDType; StringType; FloatType;  StarshipType;  CharacterType; DroidType; HumanType; EpisodeType; SearchResultType; QueryType].\n\n\n  Lemma sdf : schema.(is_a_wf_schema).\n  Proof. by []. Qed.\n  \n\n\n \n\n  Let wf_schema : wfGraphQLSchema := WFGraphQLSchema sdf.\n  \n  (** Some examples of graph's not conforming to the schema **)\n\n  Let r : @node scalar_eqType := Node \"Query\" [::].\n  \n  (** Root node does not have same type as query type **)\n  Let edges1 : seq (@node scalar_eqType * @label scalar_eqType * @node scalar_eqType) := [::].\n  \n  Let r1 : @node scalar_eqType := Graph.Node \"Human\" [::].\n  \n  Let g := GraphQLGraph r1 edges1.\n\n\n\n  \n  (** Arguments are incorrect **)\n\n  Let edges2 : seq (@node scalar_eqType * @label scalar_eqType * @node scalar_eqType) :=\n    [:: (pair\n           (pair\n              (Node \"Query\" [::])\n\n              (Label \"search\" [:: pair \"wrong_Arg\" (SValue (VString \"L\"))]))          (* <--- Wrong name for argument *)\n\n           (Node \"Starship\" [::\n                               (pair (Label  \"id\" [::]) (SValue (VInt 3000)));\n                               (pair (Label \"name\" [::]) (SValue (VString \"Falcon\"))); \n                               (pair (Label \"length\" [::]) (SValue (VFloat 34 37)))\n                            ]\n           )\n        )\n    ].\n\n  \n  Let g2 := GraphQLGraph r edges2.\n  \n  Example eNc : ~ edges_conform wf_schema check_scalar g2.\n  Proof. by [].\n  Qed.\n  \n  \n  (** Types are incorrect **)\n  \n  Let edges3 : seq (@node scalar_eqType * @label scalar_eqType * @node scalar_eqType) :=\n    [:: pair\n        (pair (Node \"Human\" [::\n                               (pair (Label \"id\" [::]) (SValue (VInt 1000)));\n                               (pair (Label \"name\" [::]) (SValue (VString \"Luke\")))\n                            ]\n              )\n              (Label \"friends\" [::])\n        )\n        (Node \"Starship\" [::\n                            (pair (Label \"id\" [::]) (SValue (VInt 2001)));\n                            (pair (Label \"name\" [::]) (SValue (VString \"R2-)D2\")));\n                            (pair (Label \"primaryFunction\" [::]) (SValue (VString \"Astromech\")))\n                         ]\n        )\n    ].\n  \n  Let r3 : @node string_eqType := Node \"Query\" [::].\n  \n    Let g3 := GraphQLGraph r edges3.\n    \n    Example eNc3 : ~ edges_conform wf_schema check_scalar g3.\n    Proof. by [].\n    Qed.\n\n\n\n\n    Let edges4 : seq (@node scalar_eqType * label * node) :=\n      [:: pair\n          (pair (Node \"Query\" [::])\n                (Label \"search\" [:: (pair \"wrong_Arg\" (SValue (VString \"L\")))])\n          )\n          (Node \"Other\" [::\n                           (pair (Label \"id\" [::]) (SValue (VInt 3000))); (* <--- Type is not in union *)\n                           (pair (Label \"name\" [::]) (SValue (VString \"Falcon\"))); \n                           (pair (Label \"length\" [::]) (SValue (VFloat 34 37)))\n                        ]\n          )\n      ].\n\n    Let r4 : @node scalar_eqType := Node \"Query\" [::].\n\n    Let g4 := GraphQLGraph r edges4.\n    \n    Example eNc4 : ~ edges_conform wf_schema check_scalar g4.\n    Proof. by [].\n    Qed.\n\n\n\n    (** Label's are incorrect **)\n\n    Let edges5 : seq (@node scalar_eqType * @label scalar_eqType * @node scalar_eqType) :=\n      [:: pair\n          (pair (Node \"Query\" [::])\n                (Label \"search\" [:: (pair \"wrong_Arg\" (SValue (VString \"L\")))])\n          )\n          (Node \"Starship\" [::\n                              (pair (Label \"id\" [::]) (SValue (VInt 3000)));\n                              (pair (Label \"name\" [:: (pair \"wrong\" (SValue (VString \"arg\")))]) (SValue (VString \"Falcon\"))); (* <--- invalid argument in field*) \n                              (pair (Label \"length\" [::]) (SValue (VFloat 34 37)))\n                           ]\n          )\n      ].\n\n    \n    Let g5 := GraphQLGraph r edges5.\n\n    \n    Example fNc : ~ nodes_conform wf_schema check_scalar g5.(nodes).\n    Proof. by [].\n    Qed.\n    \nEnd WrongGraph.", "meta": {"author": "imfd", "repo": "GraphCoQL", "sha": "681edcdcdf982151f4d1f74bb2a42f15b527317c", "save_path": "github-repos/coq/imfd-GraphCoQL", "path": "github-repos/coq/imfd-GraphCoQL/GraphCoQL-681edcdcdf982151f4d1f74bb2a42f15b527317c/src/examples/OtherExamples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.25948391944965477}}
{"text": "(******************************************************************************)\n(* Tactics for simplifying the goal state of proofs about LLVM IR programs.   *)\n(******************************************************************************)\n\nRequire opsem.\nImport opsem.Opsem.\nRequire ndopsem.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Tvc.base_tactics.\nRequire Import Tvc.notation.\nRequire Import Tvc.definitions.\n\nLtac destruct_all_eq_dec := autorewrite with eq_dec_db in *.\n\nLemma simplify_const2GV_int :\n  forall td g v1 v2 gn gns b c d e,\n    eq (opsem.Opsem.const2GV td g (const_int v1 v2)) (Some gns) ->\n    gn @ gns ->\n    _const2GV td g (const_int v1 v2) = Some ([(Values.Vint c d, e)], b) ->\n    eq gn [(Values.Vint c d, e)].\nProof.\n  intros.\n\n  unfold opsem.Opsem.const2GV in H.\n  destruct (_const2GV td g (const_int v1 v2)).\n\n  injection H1; clear H1; intros; subst.\n  injection H; clear H; intro; subst.\n  inversion H0.\n  trivial.\n\n  discriminate.\nQed.\n\n(*\nThis tactic eliminates corresponding pairs of const2GV and instantiate_gvs.\n*)\nLtac simplify_const2GV :=\n  repeat match goal with\n           | [ H1 : eq (const2GV _ _ _) (Some ?x),\n               H2 : opsem.instantiate_gvs _ _ ?x |- _ ] =>\n             eapply simplify_const2GV_int in H1; [ | eassumption | compute; reflexivity ]; clear H2; subst; try clear x\n           | [ H1 : eq (const2GV _ _ _) (Some ?x),\n               H2 : ndopsem.MNDGVs.instantiate_gvs _ ?x |- _ ] =>\n             eapply simplify_const2GV_int in H1; [ | eassumption | compute; reflexivity ]; clear H2; subst; try clear x\n\n         end.\n\n(*\nThis tactic reduces (instantiate_gvs _ x (Ensembles.Singleton _ y)) to x = y.\n*)\nLtac simplify_instantiate_gvs_singleton :=\n  repeat match goal with\n           | [ H : opsem.instantiate_gvs _ ?x (Ensembles.Singleton _ ?y) |- _ ] =>\n             destruct H\n           | [ H : ndopsem.MNDGVs.instantiate_gvs ?x (Ensembles.Singleton _ ?y) |- _ ] =>\n             destruct H\n         end.\n\n(*\nThis tactic eliminates equations involving getTypeAllocSize.\n*)\nLtac simplify_getTypeAllocSize :=\n  repeat match goal with\n           | [ H : eq (getTypeAllocSize _ _) (Some ?x) |- _ ] =>\n             compute in H; injection H; clear H; intro; subst x\n         end.\n\nLtac simplify :=\n  unfold BOP, TRUNC, EXT, ICMP, getOperandValue, alist.updateAddAL, alist.lookupAL in *;\n  destruct_all_eq_dec;\n  simplify_const2GV;\n  simplify_instantiate_gvs_singleton;\n  simplify_getTypeAllocSize;\n  injection_Some_eq_Some;\n  subst;\n  simplify_instantiate_gvs_singleton;\n  simpl in *.\n\nLtac simplify_memory_op id Hnew :=\n  unfold alist.updateAddAL, BOP, getOperandValue, alist.lookupAL in *;\n  destruct_all_eq_dec;\n  simplify_const2GV;\n  simplify_instantiate_gvs_singleton;\n  simplify_getTypeAllocSize;\n\n  match goal with\n     | [ H : context [id] |- _ ] => cbv delta [id] in H; simpl in H; rename H into Hnew\n  end;\n  simpl in *;\n\n  injection_Some_eq_Some;\n  subst;\n  simplify_instantiate_gvs_singleton;\n  simpl in *.\n\nLtac simplify_alloca H := simplify_memory_op genericvalues.LLVMgv.malloc H.\nLtac simplify_load H := simplify_memory_op genericvalues.LLVMgv.mload H; try destruct_match_Some.\nLtac simplify_store H := simplify_memory_op genericvalues.LLVMgv.mstore H; try destruct_match_Some.\n\nLemma lift_op1_simplified :\n  forall op v t x y a b c,\n    eq y [(Values.Vint a b, c)] ->\n    (ndopsem.MNDGVs.lift_op1 op\n                             (Ensembles.Singleton genericvalues.LLVMgv.GenericValue v)\n                             t = Some x ->\n     op v = Some y ->\n     eq (Ensembles.Singleton genericvalues.LLVMgv.GenericValue y) x).\nProof.\n  intros op v t x y a b c H H0 H1.\n  unfold ndopsem.MNDGVs.lift_op1 in H0.\n  unfold ndopsem.MNDGVs.instantiate_gvs in H0.\n  unfold ndopsem.MNDGVs.gv2gvs in H0.\n  injection H0; clear H0; intro H0.\n  subst x.\n  extensionality z.\n  apply Axioms.prop_ext.\n  split.\n  intro.\n  repeat eexists.\n  apply H1.\n  rewrite H.\n  rewrite <- H.\n  unfold Ensembles.In.\n  assumption.\n  intro.\n  decompose [ex and] H0; clear H0.\n  destruct H2.\n  rewrite H1 in H3.\n  injection H3; clear H3; intro H3.\n  subst x0.\n  subst y.\n  assumption.\nQed.\n\nLtac simplify_lifted_op_1 :=\n  simplify;\n  match goal with\n    | [ H : eq (ndopsem.MNDGVs.lift_op1 _ _ _) _ |- _ ] =>\n      eapply lift_op1_simplified in H; [\n        | reflexivity\n        | compute; reflexivity ]\n  end;\n  subst.\n\nLemma lift_op2_simplified :\n  forall op v1 v2 t x y a b c,\n    eq y [(Values.Vint a b, c)] ->\n    (ndopsem.MNDGVs.lift_op2 op\n                             (Ensembles.Singleton genericvalues.LLVMgv.GenericValue v1)\n                             (Ensembles.Singleton genericvalues.LLVMgv.GenericValue v2)\n                             t = Some x ->\n     op v1 v2 = Some y ->\n     eq (Ensembles.Singleton genericvalues.LLVMgv.GenericValue y) x).\nProof.\n  intros op v1 v2 t x y a b c H H0 H1.\n  unfold ndopsem.MNDGVs.lift_op2 in H0.\n  unfold ndopsem.MNDGVs.instantiate_gvs in H0.\n  unfold ndopsem.MNDGVs.gv2gvs in H0.\n  injection H0; clear H0; intro H0.\n  subst x.\n  extensionality z.\n  apply Axioms.prop_ext.\n  split.\n  intro.\n  repeat eexists.\n  apply H1.\n  rewrite H.\n  rewrite <- H.\n  unfold Ensembles.In.\n  assumption.\n  intro.\n  decompose [ex and] H0; clear H0.\n  destruct H2.\n  destruct H3.\n  rewrite H1 in H4.\n  injection H4; clear H4; intro H4.\n  subst x1.\n  subst y.\n  assumption.\nQed.\n\nLtac simplify_lifted_op_2 :=\n  simplify;\n  match goal with\n    | [ H : eq (ndopsem.MNDGVs.lift_op2 _ _ _ _) _ |- _ ] =>\n      eapply lift_op2_simplified in H; [\n        | reflexivity\n        | compute; reflexivity ]\n  end;\n  subst.\n\nLtac simplify_bop := simplify_lifted_op_2.\nLtac simplify_trunc := simplify_lifted_op_1.\nLtac simplify_ext := simplify_lifted_op_1.\nLtac simplify_icmp := simplify_lifted_op_2.\n\nLtac simplify_select :=\n  unfold getOperandValue, alist.lookupAL in *;\n  destruct_all_eq_dec;\n  injection_Some_eq_Some;\n  subst;\n  simplify_instantiate_gvs_singleton;\n  simpl in *;\n  destruct_all_eq_dec;\n  repeat match goal with\n           | [ H : eq (const2GV _ _ _) (Some _) |- _ ] =>\n             compute in H;\n             injection H; clear H; intro H; subst\n         end.\n\nLtac simplify_br_uncond :=\n  match goal with\n    | [ H1 : eq _ (lookupBlockViaLabelFromFdef _ _),\n        H2 : eq (switchToNewBasicBlock _ _ _ _ _) _ |- _ ] =>\n      unfold lookupBlockViaLabelFromFdef in H1;\n      simpl in H1;\n      simplify;\n      injection H1; clear H1; intros; subst;\n      unfold switchToNewBasicBlock in H2;\n      simpl in H2;\n      injection_Some_eq_Some;\n      subst\n  end.\n\nLtac simplify_br :=\n  match goal with\n    | [ H1 : eq _ (if isGVZero _ _ then _ else _),\n        H2 : eq (switchToNewBasicBlock _ _ _ _ _) _ |- _ ] =>\n      unfold getOperandValue, alist.lookupAL in *;\n      destruct_all_eq_dec;\n      injection_Some_eq_Some;\n      subst;\n      simplify_instantiate_gvs_singleton;\n      simpl in *;\n      destruct_all_eq_dec;\n      injection H1; clear H1; intros; subst;\n      unfold switchToNewBasicBlock in H2;\n      simpl in H2;\n      injection_Some_eq_Some;\n      subst\n  end.\n\nLtac simplify_ret :=\n  unfold getOperandValue, alist.lookupAL in *;\n  destruct_all_eq_dec;\n  injection_Some_eq_Some;\n  subst;\n  simplify_const2GV;\n  simplify_instantiate_gvs_singleton.\n\n(*\n*** Local Variables: ***\n*** coq-prog-name: \"coqtop\" ***\n*** coq-prog-args: (\"-emacs-U\" \"-require\" \"coqharness\" \"-impredicative-set\" \"-R\" \".\" \"Tvc\" \"-R\" \"../../csem/_coq\" \"Csem\" \"-I\" \"../../vellvm-coq84pl2/release/vol/src/Vellvm\" \"-I\" \"../../vellvm-coq84pl2/release/vol/src/Vellvm/ott\" \"-I\" \"../../vellvm-coq84pl2/release/vol/src/Vellvm/monads\" \"-I\" \"../../vellvm-coq84pl2/release/vol/src/Vellvm/compcert\" \"-I\" \"../../vellvm-coq84pl2/release/vol/src/Vellvm/GraphBasics\" \"-I\" \"../../vellvm-coq84pl2/release/vol/src/Vellvm/Dominators\" \"-I\" \"../../vellvm-coq84pl2/release/vol/extralibs/metatheory_8.4\" \"-I\" \"../../vellvm-coq84pl2/release/vol/extralibs/Coq-Equations/src\" \"-R\" \"../../vellvm-coq84pl2/release/vol/extralibs/Coq-Equations/theories\" \"Equations\" \"-I\" \"~/lem/coq-lib\") ***\n*** End: ***\n*)\n", "meta": {"author": "jchl", "repo": "tvc", "sha": "0abd10dfda06b036eac84ecdd43dae1bcf3cefd7", "save_path": "github-repos/coq/jchl-tvc", "path": "github-repos/coq/jchl-tvc/tvc-0abd10dfda06b036eac84ecdd43dae1bcf3cefd7/coq/llvm_tactics_simplify.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.25948337089999457}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.FSets.FMapPositive.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Classes.Morphisms.\nRequire Import Coq.Relations.Relation_Definitions.\nRequire Import Ltac2.Ltac2.\nRequire Import Ltac2.Printf.\nRequire Import Crypto.Language.PreExtra.\nRequire Import Rewriter.Language.Language.\nRequire Import Rewriter.Language.Reify.\nRequire Import Crypto.Language.IdentifiersBasicGENERATED.\nRequire Import Crypto.Util.Tuple Crypto.Util.Prod Crypto.Util.LetIn.\nRequire Import Crypto.Util.ListUtil Coq.Lists.List Crypto.Util.NatUtil.\nRequire Import Crypto.Util.Option.\nRequire Import Crypto.Util.Prod.\nRequire Import Crypto.Util.ZRange.\nRequire Import Crypto.Util.ZRange.Operations.\nRequire Import Crypto.Util.ZUtil.Definitions.\nRequire Import Crypto.Util.ZUtil.Notations.\nRequire Import Crypto.Util.CPSNotations.\nRequire Import Crypto.Util.Bool.Reflect.\nRequire Import Crypto.Util.Notations.\nRequire Import Crypto.Util.Tactics.RunTacticAsConstr.\nRequire Import Crypto.Util.Tactics.DebugPrint.\nRequire Import Crypto.Util.Tactics.ConstrFail.\nRequire Import Crypto.Util.Tactics.Head.\nImport Coq.Lists.List ListNotations. Local Open Scope bool_scope. Local Open Scope Z_scope.\nExport Language.Pre.\nExport Language.\nExport IdentifiersBasicGENERATED.\n\nImport EqNotations.\nModule Compilers.\n  Export Language.Pre.\n  Export Language.Compilers.\n  Export Reify.Compilers.\n  Import IdentifiersBasicLibrary.Compilers.\n  Import IdentifiersBasicLibrary.Compilers.Basic.\n  Import IdentifiersBasicGenerate.Compilers.Basic.Tactic.\n  Import IdentifiersBasicGENERATED.Compilers.\n\n  Definition exprInfo : Classes.ExprInfoT := Eval hnf in GoalType.exprInfo package.\n  Definition exprExtraInfo : @Classes.ExprExtraInfoT exprInfo := Eval hnf in GoalType.exprExtraInfo package.\n\n  Global Existing Instances\n         baseHasNat\n         baseHasNatCorrect\n         try_make_base_transport_cps_correct\n         buildEagerIdent\n         buildInterpEagerIdentCorrect\n         toRestrictedIdent\n         toFromRestrictedIdent\n         buildInterpIdentCorrect\n         invertIdent\n         buildInvertIdentCorrect\n         base_default\n         exprInfo\n  .\n  Global Existing Instance reflect_base_beq | 10.\n  Global Existing Instance reflect_base_interp_beq | 10.\n  Global Existing Instance try_make_base_transport_cps | 5.\n  Global Existing Instance buildIdent | 5.\n  Global Existing Instance eqv_Reflexive_Proper | 1.\n  Global Existing Instance ident_interp_Proper | 1.\n\n  Bind Scope etype_scope with base.\n\n  Global Arguments ident_Literal {_} _ : assert.\n  Global Arguments ident_comment {_} : assert.\n  Global Arguments ident_comment_no_keep {_} : assert.\n  Global Arguments ident_value_barrier : assert.\n  Global Arguments ident_nil {_} : assert.\n  Global Arguments ident_cons {_} : assert.\n  Global Arguments ident_pair {_ _} : assert.\n  Global Arguments ident_fst {_ _} : assert.\n  Global Arguments ident_snd {_ _} : assert.\n  Global Arguments ident_prod_rect {_ _ _} : assert.\n  Global Arguments ident_bool_rect {_} : assert.\n  Global Arguments ident_bool_rect_nodep {_} : assert.\n  Global Arguments ident_nat_rect {_} : assert.\n  Global Arguments ident_nat_rect_arrow {_ _} : assert.\n  Global Arguments ident_eager_nat_rect {_} : assert.\n  Global Arguments ident_eager_nat_rect_arrow {_ _} : assert.\n  Global Arguments ident_list_rect {_ _} : assert.\n  Global Arguments ident_list_rect_arrow {_ _ _} : assert.\n  Global Arguments ident_eager_list_rect {_ _} : assert.\n  Global Arguments ident_eager_list_rect_arrow {_ _ _} : assert.\n  Global Arguments ident_list_case {_ _} : assert.\n  Global Arguments ident_List_length {_} : assert.\n  Global Arguments ident_List_firstn {_} : assert.\n  Global Arguments ident_List_skipn {_} : assert.\n  Global Arguments ident_List_repeat {_} : assert.\n  Global Arguments ident_List_combine {_ _} : assert.\n  Global Arguments ident_List_map {_ _} : assert.\n  Global Arguments ident_List_app {_} : assert.\n  Global Arguments ident_List_rev {_} : assert.\n  Global Arguments ident_List_flat_map {_ _} : assert.\n  Global Arguments ident_List_partition {_} : assert.\n  Global Arguments ident_List_filter {_} : assert.\n  Global Arguments ident_List_fold_right {_ _} : assert.\n  Global Arguments ident_List_update_nth {_} : assert.\n  Global Arguments ident_List_nth_default {_} : assert.\n  Global Arguments ident_eager_List_nth_default {_} : assert.\n  Global Arguments ident_Some {_} : assert.\n  Global Arguments ident_None {_} : assert.\n  Global Arguments ident_option_rect {_ _} : assert.\n  Global Arguments ident_zrange_rect {_} : assert.\n  Global Arguments eta_base_cps {_} _ _ : assert.\n  Global Arguments ident_interp {_} _ : assert.\n  Global Arguments base_interp_beq {_ _} _ _ : assert.\n  Global Arguments reflect_base_interp_beq {_}.\n  Global Arguments ident_is_var_like {_} _ : assert.\n  Global Arguments eqv_Reflexive_Proper {_} _.\n  Global Arguments ident_interp_Proper {_}.\n\n  Ltac2 mk_reify_base () :=\n    let package := reify_package_of_package 'package in\n    reify_base_via_reify_package package.\n  Ltac2 mk_reify_base_type () :=\n    let package := reify_package_of_package 'package in\n    reify_base_type_via_reify_package package.\n  Ltac2 mk_reify_type () :=\n    let package := reify_package_of_package 'package in\n    reify_type_via_reify_package package.\n  Ltac2 mk_reify_ident_opt () :=\n    let package := reify_package_of_package 'package in\n    reify_ident_via_reify_package_opt package.\n  Ltac2 reify_base (ty : constr) : constr := mk_reify_base () ty.\n  Ltac2 reify_base_type (ty : constr) : constr := mk_reify_base_type () ty.\n  Ltac2 reify_type (ty : constr) : constr := mk_reify_type () ty.\n  Ltac2 reify_ident_opt (ctx_tys : binder list) (idc : constr) : constr option := mk_reify_ident_opt () ctx_tys idc.\n\n  #[deprecated(since=\"8.15\",note=\"Use Ltac2 instead.\")]\n   Ltac reify_base term :=\n    let f := ltac2:(term\n                    |- Control.refine (fun () => reify_base (Option.get (Ltac1.to_constr term)))) in\n    constr:(ltac:(f term)).\n  #[deprecated(since=\"8.15\",note=\"Use Ltac2 instead.\")]\n   Ltac reify_base_type term :=\n    let f := ltac2:(term\n                    |- Control.refine (fun () => reify_base_type (Option.get (Ltac1.to_constr term)))) in\n    constr:(ltac:(f term)).\n  #[deprecated(since=\"8.15\",note=\"Use Ltac2 instead.\")]\n   Ltac reify_type term :=\n    let f := ltac2:(term\n                    |- Control.refine (fun () => reify_type (Option.get (Ltac1.to_constr term)))) in\n    constr:(ltac:(f term)).\n  #[deprecated(since=\"8.15\",note=\"Use Ltac2 instead.\")]\n   Ltac reify_ident term then_tac else_tac :=\n    let f := ltac2:(term\n                    |- match reify_ident_opt [] (Option.get (Ltac1.to_constr term)) with\n                       | Some v => Control.refine (fun () => '(@Datatypes.Some _ $v))\n                       | None => Control.refine (fun () => '(@Datatypes.None Datatypes.unit))\n                       end) in\n    match f term with\n    | Datatypes.Some ?v => then_tac v\n    | Datatypes.None => else_tac ()\n    end.\n\n  (** This file defines some convenience notations and definitions. *)\n  Module base.\n    Export Language.Compilers.base.\n\n    Module type.\n      Import IdentifiersBasicGENERATED.Compilers.\n      Notation base := base (only parsing).\n      Notation Z := Z (only parsing).\n      Notation nat := nat (only parsing).\n      Notation zrange := zrange (only parsing).\n      Notation bool := bool (only parsing).\n      Notation base_beq := Compilers.base_beq (only parsing).\n      Notation string := string (only parsing).\n\n      Export Language.Compilers.base.type.\n      Notation type := (@type base) (only parsing).\n\n      Notation baseHasNat := Compilers.baseHasNat (only parsing).\n      Notation eta_base_cps_gen := Compilers.eta_base_cps_gen (only parsing).\n      Notation eta_base_cps := Compilers.eta_base_cps (only parsing).\n    End type.\n    Notation type := (@base.type base) (only parsing).\n    Notation base_interp := Compilers.base_interp (only parsing).\n    Notation interp := (base.interp Compilers.base_interp) (only parsing).\n    Notation reflect_base_beq := Compilers.reflect_base_beq (only parsing).\n    Notation base_interp_beq := Compilers.base_interp_beq (only parsing).\n    Notation baseHasNatCorrect := Compilers.baseHasNatCorrect (only parsing).\n    Notation reflect_base_interp_eq := Compilers.reflect_base_interp_beq (only parsing).\n    Notation try_make_base_transport_cps := Compilers.try_make_base_transport_cps (only parsing).\n    Notation try_make_base_transport_cps_correct := Compilers.try_make_base_transport_cps_correct (only parsing).\n\n    (* Avoid COQBUG(https://github.com/coq/coq/issues/16425)\n    Notation reify_base t := (ltac2:(let rt := reify_base (Constr.pretype t) in exact $rt)) (only parsing).\n    Notation reify t := (ltac2:(let rt := reify_base_type (Constr.pretype t) in exact $rt)) (only parsing).\n    Notation reify_norm_base t := (ltac2:(let t' := Constr.pretype t in let t' := eval cbv in $t' in let rt := reify_base t' in exact $rt)) (only parsing).\n    Notation reify_norm t := (ltac2:(let t' := Constr.pretype t in let t' := eval cbv in $t' in let rt := reify_base_type t' in exact $rt)) (only parsing).\n     *)\n    Notation reify_base t := (ltac:(let rt := reify_base t in exact rt)) (only parsing).\n    Notation reify t := (ltac:(let rt := reify_base_type t in exact rt)) (only parsing).\n    Notation reify_norm_base t := (ltac:(let t' := eval cbv in t in let rt := reify_base t' in exact rt)) (only parsing).\n    Notation reify_norm t := (ltac:(let t' := eval cbv in t in let rt := reify_base_type t' in exact rt)) (only parsing).\n    Notation reify_base_type_of e := (reify_base ((fun t (_ : t) => t) _ e)) (only parsing).\n    Notation reify_type_of e := (reify ((fun t (_ : t) => t) _ e)) (only parsing).\n    Notation reify_norm_base_type_of e := (reify_norm_base ((fun t (_ : t) => t) _ e)) (only parsing).\n    Notation reify_norm_type_of e := (reify_norm ((fun t (_ : t) => t) _ e)) (only parsing).\n\n    Ltac2 mk_reify_base := Compilers.mk_reify_base.\n    Ltac2 mk_reify := Compilers.mk_reify_base_type.\n    Ltac2 mk_reify_type := Compilers.mk_reify_type.\n    Ltac2 reify_base := Compilers.reify_base.\n    Ltac2 reify := Compilers.reify_base_type.\n    Ltac2 reify_type := Compilers.reify_type.\n    #[deprecated(since=\"8.15\",note=\"Use Ltac2 instead.\")]\n     Ltac reify_base ty := Compilers.reify_base ty.\n    #[deprecated(since=\"8.15\",note=\"Use Ltac2 instead.\")]\n     Ltac reify ty := Compilers.reify_base_type ty.\n    #[deprecated(since=\"8.15\",note=\"Use Ltac2 instead.\")]\n     Ltac reify_type ty := Compilers.reify_type ty.\n  End base.\n\n  Module ident.\n    Export Language.Compilers.ident.\n    Notation ident := Compilers.ident (only parsing).\n\n    Notation Literal := Compilers.ident_Literal (only parsing).\n    Notation comment := Compilers.ident_comment (only parsing).\n    Notation comment_no_keep := Compilers.ident_comment_no_keep (only parsing).\n    Notation value_barrier := Compilers.ident_value_barrier (only parsing).\n    Notation Nat_succ := Compilers.ident_Nat_succ (only parsing).\n    Notation Nat_pred := Compilers.ident_Nat_pred (only parsing).\n    Notation Nat_max := Compilers.ident_Nat_max (only parsing).\n    Notation Nat_mul := Compilers.ident_Nat_mul (only parsing).\n    Notation Nat_add := Compilers.ident_Nat_add (only parsing).\n    Notation Nat_sub := Compilers.ident_Nat_sub (only parsing).\n    Notation Nat_eqb := Compilers.ident_Nat_eqb (only parsing).\n    Notation nil := Compilers.ident_nil (only parsing).\n    Notation cons := Compilers.ident_cons (only parsing).\n    Notation tt := Compilers.ident_tt (only parsing).\n    Notation pair := Compilers.ident_pair (only parsing).\n    Notation fst := Compilers.ident_fst (only parsing).\n    Notation snd := Compilers.ident_snd (only parsing).\n    Notation prod_rect := Compilers.ident_prod_rect (only parsing).\n    Notation bool_rect := Compilers.ident_bool_rect (only parsing).\n    Notation bool_rect_nodep := Compilers.ident_bool_rect_nodep (only parsing).\n    Notation nat_rect := Compilers.ident_nat_rect (only parsing).\n    Notation nat_rect_arrow := Compilers.ident_nat_rect_arrow (only parsing).\n    Notation eager_nat_rect := Compilers.ident_eager_nat_rect (only parsing).\n    Notation eager_nat_rect_arrow := Compilers.ident_eager_nat_rect_arrow (only parsing).\n    Notation list_rect := Compilers.ident_list_rect (only parsing).\n    Notation list_rect_arrow := Compilers.ident_list_rect_arrow (only parsing).\n    Notation eager_list_rect := Compilers.ident_eager_list_rect (only parsing).\n    Notation eager_list_rect_arrow := Compilers.ident_eager_list_rect_arrow (only parsing).\n    Notation list_case := Compilers.ident_list_case (only parsing).\n    Notation List_length := Compilers.ident_List_length (only parsing).\n    Notation List_seq := Compilers.ident_List_seq (only parsing).\n    Notation List_firstn := Compilers.ident_List_firstn (only parsing).\n    Notation List_skipn := Compilers.ident_List_skipn (only parsing).\n    Notation List_repeat := Compilers.ident_List_repeat (only parsing).\n    Notation List_combine := Compilers.ident_List_combine (only parsing).\n    Notation List_map := Compilers.ident_List_map (only parsing).\n    Notation List_app := Compilers.ident_List_app (only parsing).\n    Notation List_rev := Compilers.ident_List_rev (only parsing).\n    Notation List_flat_map := Compilers.ident_List_flat_map (only parsing).\n    Notation List_partition := Compilers.ident_List_partition (only parsing).\n    Notation List_filter := Compilers.ident_List_filter (only parsing).\n    Notation List_fold_right := Compilers.ident_List_fold_right (only parsing).\n    Notation List_update_nth := Compilers.ident_List_update_nth (only parsing).\n    Notation List_nth_default := Compilers.ident_List_nth_default (only parsing).\n    Notation eager_List_nth_default := Compilers.ident_eager_List_nth_default (only parsing).\n    Notation Z_add := Compilers.ident_Z_add (only parsing).\n    Notation Z_mul := Compilers.ident_Z_mul (only parsing).\n    Notation Z_pow := Compilers.ident_Z_pow (only parsing).\n    Notation Z_sub := Compilers.ident_Z_sub (only parsing).\n    Notation Z_opp := Compilers.ident_Z_opp (only parsing).\n    Notation Z_div := Compilers.ident_Z_div (only parsing).\n    Notation Z_modulo := Compilers.ident_Z_modulo (only parsing).\n    Notation Z_log2 := Compilers.ident_Z_log2 (only parsing).\n    Notation Z_log2_up := Compilers.ident_Z_log2_up (only parsing).\n    Notation Z_eqb := Compilers.ident_Z_eqb (only parsing).\n    Notation Z_leb := Compilers.ident_Z_leb (only parsing).\n    Notation Z_ltb := Compilers.ident_Z_ltb (only parsing).\n    Notation Z_geb := Compilers.ident_Z_geb (only parsing).\n    Notation Z_gtb := Compilers.ident_Z_gtb (only parsing).\n    Notation Z_of_nat := Compilers.ident_Z_of_nat (only parsing).\n    Notation Z_to_nat := Compilers.ident_Z_to_nat (only parsing).\n    Notation Z_shiftr := Compilers.ident_Z_shiftr (only parsing).\n    Notation Z_shiftl := Compilers.ident_Z_shiftl (only parsing).\n    Notation Z_land := Compilers.ident_Z_land (only parsing).\n    Notation Z_lor := Compilers.ident_Z_lor (only parsing).\n    Notation Z_min := Compilers.ident_Z_min (only parsing).\n    Notation Z_max := Compilers.ident_Z_max (only parsing).\n    Notation Z_bneg := Compilers.ident_Z_bneg (only parsing).\n    Notation Z_lnot_modulo := Compilers.ident_Z_lnot_modulo (only parsing).\n    Notation Z_lxor := Compilers.ident_Z_lxor (only parsing).\n    Notation Z_truncating_shiftl := Compilers.ident_Z_truncating_shiftl (only parsing).\n    Notation Z_mul_split := Compilers.ident_Z_mul_split (only parsing).\n    Notation Z_mul_high := Compilers.ident_Z_mul_high (only parsing).\n    Notation Z_add_get_carry := Compilers.ident_Z_add_get_carry (only parsing).\n    Notation Z_add_with_carry := Compilers.ident_Z_add_with_carry (only parsing).\n    Notation Z_add_with_get_carry := Compilers.ident_Z_add_with_get_carry (only parsing).\n    Notation Z_sub_get_borrow := Compilers.ident_Z_sub_get_borrow (only parsing).\n    Notation Z_sub_with_get_borrow := Compilers.ident_Z_sub_with_get_borrow (only parsing).\n    Notation Z_ltz := Compilers.ident_Z_ltz (only parsing).\n    Notation Z_zselect := Compilers.ident_Z_zselect (only parsing).\n    Notation Z_add_modulo := Compilers.ident_Z_add_modulo (only parsing).\n    Notation Z_rshi := Compilers.ident_Z_rshi (only parsing).\n    Notation Z_cc_m := Compilers.ident_Z_cc_m (only parsing).\n    Notation Z_combine_at_bitwidth := Compilers.ident_Z_combine_at_bitwidth (only parsing).\n    Notation Z_cast := Compilers.ident_Z_cast (only parsing).\n    Notation Z_cast2 := Compilers.ident_Z_cast2 (only parsing).\n    Notation Some := Compilers.ident_Some (only parsing).\n    Notation None := Compilers.ident_None (only parsing).\n    Notation option_rect := Compilers.ident_option_rect (only parsing).\n    Notation Build_zrange := Compilers.ident_Build_zrange (only parsing).\n    Notation zrange_rect := Compilers.ident_zrange_rect (only parsing).\n    Notation fancy_add := Compilers.ident_fancy_add (only parsing).\n    Notation fancy_addc := Compilers.ident_fancy_addc (only parsing).\n    Notation fancy_sub := Compilers.ident_fancy_sub (only parsing).\n    Notation fancy_subb := Compilers.ident_fancy_subb (only parsing).\n    Notation fancy_mulll := Compilers.ident_fancy_mulll (only parsing).\n    Notation fancy_mullh := Compilers.ident_fancy_mullh (only parsing).\n    Notation fancy_mulhl := Compilers.ident_fancy_mulhl (only parsing).\n    Notation fancy_mulhh := Compilers.ident_fancy_mulhh (only parsing).\n    Notation fancy_rshi := Compilers.ident_fancy_rshi (only parsing).\n    Notation fancy_selc := Compilers.ident_fancy_selc (only parsing).\n    Notation fancy_selm := Compilers.ident_fancy_selm (only parsing).\n    Notation fancy_sell := Compilers.ident_fancy_sell (only parsing).\n    Notation fancy_addm := Compilers.ident_fancy_addm (only parsing).\n\n    Notation option_Some := Compilers.ident_Some (only parsing).\n    Notation option_None := Compilers.ident_None (only parsing).\n\n    Notation interp := Compilers.ident_interp (only parsing).\n\n    Notation buildEagerIdent := Compilers.buildEagerIdent (only parsing).\n    Notation buildInterpEagerIdentCorrect := Compilers.buildInterpEagerIdentCorrect (only parsing).\n    Notation toRestrictedIdent := Compilers.toRestrictedIdent (only parsing).\n    Notation toFromRestrictedIdent := Compilers.toFromRestrictedIdent (only parsing).\n\n    Ltac2 mk_reify_opt := Compilers.mk_reify_ident_opt.\n    Ltac2 reify_opt := Compilers.reify_ident_opt.\n    #[deprecated(since=\"8.15\",note=\"Use Ltac2 instead.\")]\n     Ltac reify := Compilers.reify_ident.\n\n    Notation buildIdent := Compilers.buildIdent (only parsing).\n    Notation is_var_like := Compilers.ident_is_var_like (only parsing).\n    Notation buildInterpIdentCorrect := Compilers.buildInterpIdentCorrect (only parsing).\n    Notation eqv_Reflexive_Proper := Compilers.eqv_Reflexive_Proper (only parsing).\n    Notation interp_Proper := Compilers.ident_interp_Proper (only parsing).\n\n    Definition is_comment t (idc : ident t) : Datatypes.bool\n      := match idc with\n         | comment _ => true\n         | comment_no_keep _ => true\n         | _ => false\n         end.\n\n    Module Export Notations.\n      Export Language.Compilers.ident.Notations.\n      Delimit Scope ident_scope with ident.\n      Bind Scope ident_scope with ident.\n      Notation interp := Compilers.ident_interp (only parsing).\n      Global Arguments expr.Ident {base_type%type ident%function var%function t%etype} idc%ident.\n      Notation \"## x\" := (Compilers.ident_Literal x) (only printing) : ident_scope.\n      Notation \"## x\" := (Compilers.ident_Literal (t:=base.reify_base_type_of x) x) (only parsing) : ident_scope.\n      Notation \"## x\" := (expr.Ident (Compilers.ident_Literal x)) (only printing) : expr_scope.\n      Notation \"## x\" := (smart_Literal (base_interp:=base_interp) (t:=base.reify_type_of x) x) (only parsing) : expr_scope.\n      Notation \"# x\" := (expr.Ident x) (only parsing) : expr_pat_scope.\n      Notation \"# x\" := (@expr.Ident base.type _ _ _ x) : expr_scope.\n      Notation \"x @ y\" := (expr.App x%expr_pat y%expr_pat) (only parsing) : expr_pat_scope.\n      Notation \"( x , y , .. , z )\" := (expr.App (expr.App (#Compilers.ident_pair) .. (expr.App (expr.App (#Compilers.ident_pair) x%expr) y%expr) .. ) z%expr) : expr_scope.\n      Notation \"( x , y , .. , z )\" := (expr.App (expr.App (#Compilers.ident_pair)%expr_pat .. (expr.App (expr.App (#Compilers.ident_pair)%expr_pat x%expr_pat) y%expr_pat) .. ) z%expr_pat) (only parsing) : expr_pat_scope.\n      Notation \"x :: y\" := (#Compilers.ident_cons @ x @ y)%expr : expr_scope.\n      Notation \"[ ]\" := (#Compilers.ident_nil)%expr : expr_scope.\n      Notation \"x :: y\" := (#Compilers.ident_cons @ x @ y)%expr_pat (only parsing) : expr_pat_scope.\n      Notation \"[ ]\" := (#Compilers.ident_nil)%expr_pat (only parsing) : expr_pat_scope.\n      Notation \"[ x ]\" := (x :: [])%expr : expr_scope.\n      Notation \"[ x ; y ; .. ; z ]\" := (#Compilers.ident_cons @ x @ (#Compilers.ident_cons @ y @ .. (#Compilers.ident_cons @ z @ #Compilers.ident_nil) ..))%expr : expr_scope.\n      Notation \"ls [[ n ]]\"\n        := ((#(Compilers.ident_List_nth_default) @ _ @ ls @ #(Compilers.ident_Literal n%nat))%expr)\n           : expr_scope.\n      Notation \"xs ++ ys\" := (#Compilers.ident_List_app @ xs @ ys)%expr : expr_scope.\n      Notation \"x - y\" := (#Compilers.ident_Z_sub @ x @ y)%expr : expr_scope.\n      Notation \"x + y\" := (#Compilers.ident_Z_add @ x @ y)%expr : expr_scope.\n      Notation \"x / y\" := (#Compilers.ident_Z_div @ x @ y)%expr : expr_scope.\n      Notation \"x * y\" := (#Compilers.ident_Z_mul @ x @ y)%expr : expr_scope.\n      Notation \"x >> y\" := (#Compilers.ident_Z_shiftr @ x @ y)%expr : expr_scope.\n      Notation \"x << y\" := (#Compilers.ident_Z_shiftl @ x @ y)%expr : expr_scope.\n      Notation \"x &' y\" := (#Compilers.ident_Z_land @ x @ y)%expr : expr_scope.\n      Notation \"x || y\" := (#Compilers.ident_Z_lor @ x @ y)%expr : expr_scope.\n      Notation \"x 'mod' y\" := (#Compilers.ident_Z_modulo @ x @ y)%expr : expr_scope.\n      Notation \"- x\" := (#Compilers.ident_Z_opp @ x)%expr : expr_scope.\n      Global Arguments ident_interp _ !_.\n    End Notations.\n  End ident.\n  Export ident.Notations.\n  Notation ident := IdentifiersBasicGENERATED.Compilers.ident (only parsing).\n\n  Ltac2 reify (var : constr) (term : constr) : constr :=\n    let reify_base_type := mk_reify_base_type () in\n    let reify_ident_opt := mk_reify_ident_opt () in\n    expr.reify 'base.type 'ident reify_base_type reify_ident_opt var term None.\n  Ltac2 _Reify (term : constr) : constr :=\n    let reify_base_type := mk_reify_base_type () in\n    let reify_ident_opt := mk_reify_ident_opt () in\n    expr._Reify 'base.type 'ident reify_base_type reify_ident_opt term.\n  Ltac2 _Reify_rhs () : unit :=\n    let reify_base_type := mk_reify_base_type () in\n    let reify_ident_opt := mk_reify_ident_opt () in\n    expr._Reify_rhs 'base.type 'ident reify_base_type reify_ident_opt '@base.interp '@ident_interp ().\n  Ltac2 Type exn ::= [ Not_a_constr (string, string, Ltac1.t) ].\n  Ltac reify var term :=\n    let f := ltac2:(var term\n                    |- let get_to_constr name x\n                         := match Ltac1.to_constr x with\n                            | Some x => x\n                            | None => Control.zero (Not_a_constr \"APINotations.Compilers.reify\" name x)\n                            end in\n                       let v := reify (get_to_constr \"var\" var) (get_to_constr \"term\" term) in\n                       Control.refine (fun () => v)) in\n    constr:(ltac:(f constr:(var) term)).\n  Ltac Reify term :=\n    let f := ltac2:(term\n                    |- let get_to_constr name x\n                         := match Ltac1.to_constr x with\n                            | Some x => x\n                            | None => Control.zero (Not_a_constr \"APINotations.Compilers.Reify\" name x)\n                            end in\n                       let v := _Reify (get_to_constr \"term\" term) in\n                       Control.refine (fun () => v)) in\n    constr:(ltac:(f term)).\n  Ltac Reify_rhs _ :=\n    ltac2:(_Reify_rhs ()).\n\n  Global Hint Extern 1 (@expr.Reified_of _ _ _ _ ?t ?v ?rv)\n  => cbv [expr.Reified_of]; Reify_rhs (); reflexivity : typeclass_instances.\n\n  Module Import invert_expr.\n    Export Language.Compilers.invert_expr.\n\n    Module ident.\n      Notation invertIdent := Compilers.invertIdent (only parsing).\n      Notation buildInvertIdentCorrect := Compilers.buildInvertIdentCorrect (only parsing).\n    End ident.\n\n    Section with_var.\n      Context {var : type base.type -> Type}.\n      Local Notation expr := (@expr base.type ident var).\n      Local Notation try_transportP P := (@type.try_transport _ _ P _ _).\n      Local Notation try_transport := (try_transportP _).\n      Let type_base (x : base) : base.type := base.type.type_base x.\n      Let base {bt} (x : Language.Compilers.base.type bt) : type.type _ := type.base x.\n      Local Coercion base : base.type >-> type.type.\n      Local Coercion type_base : Compilers.base >-> base.type.\n      Local Notation tZ := (base.type.type_base Z).\n      Local Notation tzrange := (base.type.type_base zrange).\n\n      Definition invert_Z_cast {t} (e : expr t)\n        : option ZRange.zrange\n        := match invert_AppIdent e with\n           | Some (existT (type.base tzrange) (idc, r))\n             => r <- reflect_smart_Literal r;\n                  if match idc with ident.Z_cast => true | _ => false end\n                  then Some r\n                  else None\n           | _ => None\n           end%option.\n\n      Definition invert_Z_cast2 {t} (e : expr t)\n        : option (ZRange.zrange * ZRange.zrange)\n        := match invert_AppIdent e with\n           | Some (existT (type.base (tzrange * tzrange))\n                          (idc, r))\n             => r <- reflect_smart_Literal r;\n                  if match idc with ident.Z_cast2 => true | _ => false end\n                  then Some r\n                  else None\n           | _ => None\n           end%option.\n\n      Definition invert_App_Z_cast (e : expr tZ)\n        : option (ZRange.zrange * expr Z)\n        := match invert_App e with\n           | Some (existT (type.base tZ) (idc, v))\n             => r <- invert_Z_cast idc;\n                  Some (r, v)\n           | _ => None\n           end.\n\n      Definition invert_App_Z_cast2 (e : expr (tZ * tZ))\n        : option ((ZRange.zrange * ZRange.zrange) * expr (Z * Z))\n        := match invert_App e with\n           | Some (existT (type.base (tZ * tZ)) (idc, v))\n             => r <- invert_Z_cast2 idc;\n                  Some (r, v)\n           | _ => None\n           end.\n\n      Definition invert_App_cast {t} (e : expr t)\n        : option ((type.interp (Language.Compilers.base.interp (fun _ => ZRange.zrange)) t) * expr t)\n        := match t return expr t -> option (type.interp _ t * expr t) with\n           | type.base tZ => invert_App_Z_cast\n           | type.base (tZ * tZ) => invert_App_Z_cast2\n           | _ => fun _ => None\n           end e.\n\n      Definition invert_Literal_through_cast {t} (e : expr t)\n        : option (option (type.interp (Language.Compilers.base.interp (fun _ => ZRange.zrange)) t) * type.interp base.interp t)\n        := match invert_Literal e, invert_App_cast e with\n           | Some v, _ => Some (None, v)\n           | None, Some (r, e) => (v <- invert_Literal e; Some (Some r, v))%option\n           | None, None => None\n           end.\n    End with_var.\n  End invert_expr.\n\n  Module DefaultValue.\n    Export Language.Compilers.DefaultValue.\n    Module type.\n      Export Language.Compilers.DefaultValue.type.\n      Module base.\n        Export Language.Compilers.DefaultValue.type.base.\n        Notation base_default := Compilers.base_default (only parsing).\n      End base.\n    End type.\n  End DefaultValue.\n\n  Module Classes.\n    Export Language.Compilers.Classes.\n    Notation exprInfo := Compilers.exprInfo (only parsing).\n    Notation exprExtraInfo := Compilers.exprExtraInfo (only parsing).\n  End Classes.\n\n  Module Coercions.\n    Coercion type_base (x : base) : base.type := base.type.type_base x.\n    Coercion base {bt} (x : Language.Compilers.base.type bt) : type.type _ := type.base x.\n    Global Arguments base {_} _ / .\n    Global Arguments type_base _ / .\n  End Coercions.\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/APINotations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2594833646000077}}
{"text": "Require Import Coq.Classes.Morphisms Coq.Setoids.Setoid.\nRequire Import Fiat.Parsers.Reflective.Syntax Fiat.Parsers.Reflective.Semantics.\nRequire Import Fiat.Parsers.Reflective.PartialUnfold.\nRequire Import Fiat.Parsers.Reflective.SyntaxEquivalence.\nRequire Import Fiat.Parsers.Reflective.ParserSyntax Fiat.Parsers.Reflective.ParserSemantics.\nRequire Import Fiat.Parsers.Reflective.ParserPartialUnfold.\nRequire Import Fiat.Parsers.Reflective.ParserSyntaxEquivalence.\nRequire Import Fiat.Parsers.Reflective.LogicalRelations.\nRequire Import Fiat.Common.List.ListFacts.\nRequire Import Fiat.Common.Equality.\nRequire Import Fiat.Common.List.ListMorphisms.\nRequire Import Fiat.Common.Wf2.\n\nDefinition extract_Term {var T} (E : has_parse_term var T) : Term var _\n  := match E with\n     | RFix2 G_length up_to_G_length f default valid_len valids nt_idx\n       => f\n     end.\n\nDefinition extract_default {var T} (E : has_parse_term var T) : Term var _\n  := match E with\n     | RFix2 G_length up_to_G_length f default valid_len valids nt_idx\n       => default\n     end.\n\nTheorem polypnormalize_correct\n        {T}\n        (is_valid_nonterminal : list nat -> nat -> bool)\n        (strlen : nat)\n        (char_at_matches : nat -> Reflective.RCharExpr Ascii.ascii -> bool)\n        (split_string_for_production : nat * (nat * nat) -> nat -> nat -> list nat)\n  : forall (E : polyhas_parse_term T),\n    has_parse_term_equiv nil (E interp_TypeCode) (E (normalized_of interp_TypeCode))\n    -> interp_has_parse_term\n         is_valid_nonterminal strlen char_at_matches split_string_for_production\n         (E _)\n       = interp_has_parse_term\n           is_valid_nonterminal strlen char_at_matches split_string_for_production\n           (polypnormalize E _).\nProof.\n  intros E H.\n  unfold polypnormalize, pnormalize.\n  pose proof (fun H => @polynormalize_correct _ (fun var => extract_Term (E _)) H) as H''.\n  pose proof (fun H => @polynormalize_correct _ (fun var => extract_default (E _)) H) as H''d.\n  unfold extract_Term in *.\n  unfold polynormalize in *.\n  destruct H; simpl in *.\n  repeat match goal with\n         | [ H : _ /\\ _ |- _ ] => destruct H\n         | [ H : ?A -> ?B, H' : ?A |- _ ] => specialize (H H')\n         end.\n  refine (Fix2_5_Proper_eq _ _ _ _ _ _ _ _ _ _);\n    unfold forall_relation, pointwise_relation;\n    repeat intro.\n  simpl in *.\n  rewrite H''d; clear H''d.\n  unfold step_option_rec.\n  unfold Proper, respectful, pointwise_relation in *.\n  edestruct Compare_dec.lt_dec; simpl;\n    [\n    | edestruct Sumbool.sumbool_of_bool; simpl; [ | reflexivity ] ];\n    (erewrite <- H''; [ reflexivity | .. ]);\n    try solve [ intros; subst; reflexivity\n              | intros; subst; eauto using eq_refl with nocore ].\nQed.\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/ParserLogicalRelations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.25948336460000765}}
{"text": "\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nRequire Import CtorizeII.\nRequire Import DtorizeII.\nRequire Import AST.\nRequire Import Names.\nRequire Import Eval.\nRequire Import GenericLemmas.\nRequire Import GenericTactics.\n\nLemma ctorize_substitution: forall (e e' : expr) (tn : TypeName) (n : nat),\n    constructorize_expr tn (substitute' n e' e) =\n    substitute' n (constructorize_expr tn e')\n                (constructorize_expr tn e).\nProof.\n  intros.\n  gen_dep n.\n  induction e using expr_strong_ind; intros; simpl;\n    try solve [f_equal; induction ls; simpl; auto; f_equal; inversion H; auto];\n    try solve [match_destruct_tac; simpl; f_equal; auto;\n               induction ls; auto; simpl; f_equal; inversion H; auto];\n    try solve [f_equal; auto;\n               induction es; simpl; auto; f_equal; inversion H0; auto;\n               destruct a; simpl; f_equal; auto].\n  destruct v; simpl; match_destruct_tac; auto.\n  match_destruct_tac; simpl; auto.\nQed.\n\nLemma dtorize_substitution: forall (e e' : expr) (tn : TypeName) (n : nat),\n    destructorize_expr tn (substitute' n e' e) =\n    substitute' n (destructorize_expr tn e')\n                (destructorize_expr tn e).\nProof.\n  intros.\n  gen_dep n.\n  induction e using expr_strong_ind; intros; simpl;\n    try solve [f_equal; induction ls; simpl; auto; f_equal; inversion H; auto];\n    try solve [match_destruct_tac; simpl; f_equal; auto;\n               induction ls; auto; simpl; f_equal; inversion H; auto];\n    try solve [f_equal; auto;\n               induction es; simpl; auto; f_equal; inversion H0; auto;\n               destruct a; simpl; f_equal; auto].\n  destruct v; simpl; match_destruct_tac; auto.\n  match_destruct_tac; simpl; auto.\nQed.\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/XfuncSubst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2594833583000208}}
{"text": "Require Import BasicMachineTypes.\nRequire Import ClassDatatypesIface.\nRequire Import ClasspoolIface.\nRequire Import Execution.\nRequire Import Verifier.\nRequire Import Arith.\nRequire Import Omega.\nRequire Import List.\nRequire Import ListExt.\nRequire Import Store.\nRequire Import Peano_dec.\nRequire Import OptionExt.\nRequire Import OptionMonad.\nRequire Import DestructExt.\n\nModule PreVerifierSafety (B0 : BASICS).\n\nModule B := B0.\n\nModule PreV := Verifier.MkPreVerifier B.\n\nModule MkVerifierSafety (C : CLASSDATATYPES with Module B := B with Module A := PreV.VA)\n                        (R  : CLASSPOOL with Module B := B with Module C := C).\n\nModule E := Execution.Execution B C R.\nModule V := PreV.MkVerifier C.\n\nSection Satisfiability.\n\nHypothesis classes : R.cert_classpool.\nHypothesis heap : E.ObjectHeap.t.\n\nInductive rt_ty_sat : E.rt_val -> PreV.VA.value_assertion -> Prop :=\n| ty_sat_int    : forall i, rt_ty_sat (E.rt_int i) C.A.va_int\n| ty_sat_float  : rt_ty_sat E.rt_float C.A.va_float\n| ty_sat_null   : rt_ty_sat (E.rt_addr None) C.A.va_null\n| ty_sat_addr1  : forall x, rt_ty_sat (E.rt_addr None) (C.A.va_addr x)\n| ty_sat_addr2  : forall nm a nm' fields,\n    E.ObjectHeap.lookup heap a = Some (E.hp_object nm' fields) ->\n    R.sub_class classes nm' nm ->\n    rt_ty_sat (E.rt_addr (Some a)) (C.A.va_addr nm)\n| ty_sat_ref_Some: forall a nm fields,\n    E.ObjectHeap.lookup heap a = Some (E.hp_object nm fields) ->\n    rt_ty_sat (E.rt_addr (Some a)) C.A.va_ref\n| ty_sat_ref_None: rt_ty_sat (E.rt_addr None) C.A.va_ref\n| ty_sat_cat1i  : forall i, rt_ty_sat (E.rt_int i) C.A.va_cat1\n| ty_sat_cat1f  : rt_ty_sat E.rt_float C.A.va_cat1\n| ty_sat_cat1a  : forall a, rt_ty_sat (E.rt_addr a) C.A.va_cat1\n| ty_sat_double : rt_ty_sat E.rt_double C.A.va_double\n| ty_sat_long   : rt_ty_sat E.rt_long C.A.va_long\n| ty_sat_cat2d  : rt_ty_sat E.rt_double C.A.va_cat2\n| ty_sat_cat2l  : rt_ty_sat E.rt_long C.A.va_cat2\n| ty_sat_top    : forall v, rt_ty_sat v C.A.va_top.\n\nHint Resolve ty_sat_int ty_sat_float ty_sat_null ty_sat_addr1 ty_sat_addr2 ty_sat_ref_Some ty_sat_ref_None ty_sat_cat1i ty_sat_cat1f ty_sat_cat1a\n             ty_sat_double ty_sat_long ty_sat_cat2d ty_sat_cat2l ty_sat_top.\n\nInductive stack_sat : list E.rt_val -> C.A.stack_assertion -> Prop :=\n| stk_sat_nil  : forall l, stack_sat l nil\n| stk_sat_cons : forall v t s a, rt_ty_sat v t -> stack_sat s a -> stack_sat (v::s) (t::a).\n\nInductive stack_sat_exact : list E.rt_val -> C.A.stack_assertion -> Prop :=\n| stk_sat_exact_nil  : stack_sat_exact nil nil\n| stk_sat_exact_cons : forall v t s a, rt_ty_sat v t -> stack_sat_exact s a -> stack_sat_exact (v::s) (t::a).\n\nInductive lvar_sat : list (option E.rt_val) -> C.A.lvar_assertion -> Prop :=\n| lvar_sat_nil   : lvar_sat nil nil\n| lvar_sat_cons1 : forall v t s a, rt_ty_sat v t -> lvar_sat s a -> lvar_sat (Some v::s) (t::a)\n| lvar_sat_cons2 : forall s a, lvar_sat s a -> lvar_sat (None::s) (C.A.va_top::a).\n\nHypothesis class : C.class.\n\nDefinition subclass_assertions_satisfied :=\n  forall a b, C.A.CP.S.lookup (C.A.class_annot_expected_subtypes (C.class_annotation class)) a = Some b ->\n              R.sub_class classes a b.\n\nHypothesis all_expectations_met : subclass_assertions_satisfied.\n  \n\nLemma leq_sub_class : forall a b,\n  PreV.VA.CP.leq_prop (C.A.class_annot_expected_subtypes (C.class_annotation class)) a b ->\n  R.sub_class classes a b.\nintros. eapply PreV.VA.CP.leq_prop_LEQ.\n exact (R.sub_class_trans classes).\n intro. apply R.sub_class_refl.\n unfold PreV.VA.CP.all_LEQ. apply all_expectations_met. \n assumption.\nSave.\n\nLemma value_assertion_implication_sound : forall t1 t2 v,\n  V.value_assertion_implication class t1 t2 -> rt_ty_sat v t1 -> rt_ty_sat v t2.\nintros. induction H; destruct v; inversion H0; eauto.\n apply ty_sat_addr1.\n apply ty_sat_addr1.\n eapply ty_sat_addr2. \n  apply H3.\n  eapply R.sub_class_trans. \n   apply H4. \n   apply leq_sub_class. apply H.\n subst o. auto. \n subst o. auto.\n subst o. auto.\n subst o. auto.\n subst o. auto.\nSave.\n\nHint Resolve value_assertion_implication_sound.\n\nLemma stack_assertion_implication_sound : forall a a' s,\n  V.stack_assertion_implication class a a' -> stack_sat s a -> stack_sat s a'.\nintros. generalize s H0. clear s H0. induction H; intros.\n apply stk_sat_nil.\n inversion H1. constructor; eauto.\nSave.\n \nLemma lvar_assertion_implication_sound : forall a a' l,\n  V.lvar_assertion_implication class a a' -> lvar_sat l a -> lvar_sat l a'.\nintros. generalize l H0. clear l H0. induction H; intros.\ninversion H0. apply lvar_sat_nil. \ninversion H1. \n constructor; eauto.\n subst. inversion H; subst; try constructor; eauto. \n  rewrite (V.value_assertion_implication_top class t2 H). \n   apply lvar_sat_cons2. auto. \nSave.\n\nLemma sem_unpop : forall s a a' b b' ty,\n  stack_sat s a ->\n  V.unpop ty (b',a') = Some (b,a) ->\n    b=b' /\\ exists v, exists s', rt_ty_sat v ty /\\ s = v::s' /\\ stack_sat s' a'.\nintros.\ninversion H0. subst a. inversion H. split.\n trivial.\n exists v. exists s0. auto. \nSave.\n\nLemma sem_unpush : forall a a' b b' s ty,\n  stack_sat s a' ->\n  V.unpush class ty (b,a) = Some (b',a') ->\n  b = b' /\\ forall v, rt_ty_sat v ty -> stack_sat (v::s) a.\nintros. \nsimpl in H0. destruct a. discriminate.\ndestruct_bool (V.value_assertion_implication_dec class ty v) H1 H0.\ninversion H0. subst a b. split.\n trivial. \n intros. apply stk_sat_cons.\n  eapply value_assertion_implication_sound. apply V.value_assertion_implication_dec_sound. apply H1. assumption.\n  assumption.\nSave.\n\nLemma sem_known_unpush : forall a a' b b' s ty,\n  stack_sat s a' ->\n  V.unpush_2 (b,a) = Some (ty, (b',a')) ->\n  b = b' /\\ forall v, rt_ty_sat v ty -> stack_sat (v::s) a.\nintros. simpl V.unpush_2 in H0. destruct a.\n discriminate.\n inversion H0. split.\n  reflexivity.\n  intros. apply stk_sat_cons; assumption.\nSave.\n\nLemma lvar_update : forall l a a' n t t',\n  list_update a n t = Some a' ->\n  lvar_sat l a' -> nth_error a n = Some t' ->\n  V.value_assertion_implication class t t' -> lvar_sat l a.\nintros. generalize a' a l H H0 H1. clear a' a l H H0 H1. \ninduction n; intros; destruct a; try discriminate.\ninversion H. inversion H1. inversion H0; subst.\ndiscriminate.\ninversion H0. apply lvar_sat_cons1. eapply value_assertion_implication_sound. apply H2. apply H9. apply H11.\ninversion H0. subst. inversion H2. subst. apply lvar_sat_cons2. assumption.\nrewrite (V.value_assertion_implication_top class t' H2). apply lvar_sat_cons2. apply H6.\n\nsimpl in H. destruct_opt (list_update a n t) H3 H. \ninversion H. subst. inversion H1. inversion H0. \napply lvar_sat_cons1; eauto. \napply lvar_sat_cons2; eauto. \nSave.\n\nLemma sem_lvar_lookup : forall l a n t,\n  lvar_sat l a -> nth_error a n = Some t -> t<>C.A.va_top ->\n  exists v, option_mult (nth_error l n) = Some v /\\ rt_ty_sat v t.\nintros. generalize a l H H0. clear a l H H0.\ninduction n; intros; destruct a; try discriminate; destruct l; inversion H; subst.\n inversion H0. subst t. exists v0. split; auto. \n inversion H0. subst t. elimtype False. apply H1. trivial.\n simpl in *. eauto. \n simpl in *. eauto. \nSave.\n\n(*Lemma sem_unretrieve : forall a a' l b b' t n,\n  lvar_sat l a' -> V.unretrieve class (V.stack_type_to_value_assertion t) n (a,b) = Some (a',b') ->\n  b = b' /\\ exists v, rt_ty_sat v (V.stack_type_to_value_assertion t) /\\ option_mult (nth_error l n) = Some v /\\ lvar_sat l a.*)\n\nLemma merge_not_top : forall a b c,\n  a <> PreV.VA.va_top ->   (* TODO: if this is C.A.va_top, then it fails to typecheck at the end *)\n  V.value_assertion_merge class a b = Some c ->\n  c <> PreV.VA.va_top.\nintros. unfold V.value_assertion_merge in H0.\ndestruct a; destruct b; first\n [ inversion H0; unfold not; intro; discriminate\n | inversion H0; assumption\n | idtac ].\ndestruct (V.value_assertion_implication_dec class (PreV.VA.va_addr t) (PreV.VA.va_addr t0)). \n inversion H0. unfold not; intro; discriminate.\n destruct (V.value_assertion_implication_dec class (PreV.VA.va_addr t0) (PreV.VA.va_addr t));\n  inversion H0; unfold not; intro; discriminate.\nSave. \nImplicit Arguments merge_not_top [a b c]. \n\nLemma sem_unretrieve : forall a a' l b b' t n,\n  t <> PreV.VA.va_top ->\n  lvar_sat l a' -> V.unretrieve class t n (a,b) = Some (a',b') ->\n  b = b' /\\ exists v, rt_ty_sat v t /\\ option_mult (nth_error l n) = Some v /\\ lvar_sat l a.\nintros a a' l b b' t n not_top H H0.\nsimpl in H0. \ndestruct_opt (nth_error a n) H1 H0. simpl in H0.\ndestruct_opt (V.value_assertion_merge class t x) H2 H0. simpl in H0.\ndestruct_opt (list_update a n x0) H3 H0.\ninversion H0. subst.\nsplit.\n trivial.\n assert (nth_error a' n = Some x0).\n  eapply list_update_nth_error. apply H3. \n destruct (sem_lvar_lookup _ _ _ _ H H4 (merge_not_top not_top H2)) as [v [lookup_ok v_ok]]. \n exists v. intuition.\n  eapply value_assertion_implication_sound. eapply V.value_assertion_merge_p1. apply H2. apply v_ok.  \n  eapply lvar_update; eauto. eapply V.value_assertion_merge_p2. apply H2.\nSave.\n\nLemma lvar_sat_length : forall l b, lvar_sat l b -> length l = length b.\nintros. generalize b H. clear b H. induction l; intros; destruct b; inversion H.\ntrivial. simpl. rewrite (IHl b H5). trivial.\nsimpl. rewrite (IHl b H1). trivial.\nSave.\n\nLemma lvar_update_prop : forall lv v l' n t x l,\n  lvar_sat lv l' -> nth_error l n = Some t -> list_update l n x = Some l' -> rt_ty_sat v t ->\n  exists lv', list_update lv n (Some v) = Some lv' /\\ lvar_sat lv' l.\nintros lv v. \ninduction lv; intros; inversion H; subst; destruct l; destruct n; try discriminate; simpl in * |- *.\ndestruct (list_update l n x); discriminate.\ninversion H1. inversion H0. subst. \nexists (Some v::lv). split. trivial. constructor; assumption. \ndestruct_opt (list_update l n x) H3 H1. inversion H1. subst. \ndestruct (IHlv _ _ _ _ _ H7 H0 H3 H2). destruct H4. rewrite H4.\nexists (Some v0::x0). split. trivial. constructor; assumption.\ninversion H1. inversion H0. subst. \nexists (Some v::lv). split. trivial. constructor; assumption. \ndestruct_opt (list_update l n x) H3 H1. inversion H1. subst. \ndestruct (IHlv _ _ _ _ _ H6 H0 H3 H2). destruct H4. rewrite H4.\nexists (None::x0). split. trivial. constructor; assumption.\nSave.\nImplicit Arguments lvar_update_prop [lv v l' n t x l].\n\nLemma lvar_update_prop_2 : forall lv l n,\n  lvar_sat lv l -> nth_error l n = Some PreV.VA.va_top ->\n  exists lv', list_update lv n None = Some lv' /\\ lvar_sat lv' l.\nintro lv. \ninduction lv; intros; inversion H; subst; destruct n; try discriminate; simpl in * |- *.\nexists (None::lv). split. trivial. inversion H0. constructor. assumption.\ndestruct (IHlv _ _ H5 H0). destruct H1. rewrite H1. \nexists (Some v::x). split. trivial. constructor; assumption.\nexists (None::lv). intuition. \ndestruct (IHlv _ _ H4 H0). destruct H1. rewrite H1.\nexists (None::x). intuition. constructor. assumption.\nSave.\nImplicit Arguments lvar_update_prop_2 [lv l n].\n\nLemma lvar_update_prop_3 : forall lv l' l n x,\n  lvar_sat lv l' -> list_update l (S n) x = Some l' -> exists v, nth_error lv n = Some v.\nintros.\napply nth_error_ok. \nrewrite (lvar_sat_length lv l' H). \nassert (S n < length l'). eapply list_update_lt_length_2. apply H0.\nomega.\nSave.\nImplicit Arguments lvar_update_prop_3 [lv l' l n x].\n\nLemma lvar_sat_ty_sat : forall lv n v t l,\n  nth_error lv n = Some (Some v) -> lvar_sat lv l -> nth_error l n = Some t -> rt_ty_sat v t.\nintro. induction lv; intros; destruct n; destruct l; inversion H1; try discriminate; subst.\ninversion H0. inversion H. subst. inversion H9. subst. assumption. \napply ty_sat_top.\ninversion H0; inversion H; subst; apply (IHlv n v t l); assumption.\nSave.\n\nLemma is_va_top : forall v t,\n  E.val_category v = C.category2 ->\n  rt_ty_sat v t -> V.value_assertion_implication_dec class t PreV.VA.va_cat2 = false ->\n  t = PreV.VA.va_top.\nintros.\ndestruct v; destruct t; try discriminate; inversion H0; reflexivity.\nSave.\n\nLemma va_category2 : forall v,\n  rt_ty_sat v PreV.VA.va_cat2 -> E.val_category v = C.category2.\nintros. destruct v; inversion H; reflexivity.\nSave.\n\nLemma rt_ty_sat_category2 : forall v,\n  E.val_category v = C.category2 -> rt_ty_sat v PreV.VA.va_cat2.\nintros. destruct v; inversion H; auto. \nSave.\n\nLemma va_category1 : forall v,\n  rt_ty_sat v C.A.va_cat1 -> E.val_category v = C.category1.\nintros. destruct v; inversion H; reflexivity.\nSave.\n\nLemma rt_ty_sat_category1 : forall v,\n  E.val_category v = C.category1 -> rt_ty_sat v C.A.va_cat1.\nintros. destruct v; inversion H; auto. \nSave.\n\nLemma va_notimp_category1 : forall v t, t <> C.A.va_top ->\n  rt_ty_sat v t -> V.value_assertion_implication_dec class t PreV.VA.va_cat2 = false -> E.val_category v = C.category1.\nintros.\ndestruct v; destruct t; inversion H0; try trivial; try discriminate;\n elimtype False; apply H; reflexivity.\nSave.\n\nLemma va_not_top : forall v s,\n  V.value_assertion_implication_dec class v (V.stack_type_to_value_assertion s) = true ->\n  v <> C.A.va_top.\nintros v s imp_s. \ndestruct v; try (unfold not; intro; discriminate).\ndestruct s; discriminate.\nSave.\nImplicit Arguments va_not_top [v s].\n\n(*\nLemma extend_va_imp_false : forall t1 t2,\n  t1 <> V.E.R.C.va_top ->\n  ~(V.value_assertion_implication class t2 V.va_cat2) ->\n  V.value_assertion_implication class t1 t2 ->\n  ~(V.value_assertion_implication class t1 V.va_cat2).\nintros. unfold not. intro. apply H0. \ndestruct t2; destruct t1; first\n[assumption\n|match reverse goal with H0:(V.value_assertion_implication class ?A ?B) |- _ => \n  assert (X:V.value_assertion_implication_dec class A B = false);\n  [reflexivity|rewrite (V.value_assertion_implication_dec_complete class A B H0) in X; discriminate ] end\n|constructor\n|idtac].\n*)\n\nLemma sem_unstore : forall lv l l' s s' n t is_cat2,\n  lvar_sat lv l' -> V.unstore class n (l,s) is_cat2 = Some (t, (l', s')) ->\n  s = s' /\\\n  forall v,\n    rt_ty_sat v t ->\n    (is_cat2 = true -> E.val_category v = C.category2) ->\n    (is_cat2 = false -> E.val_category v = C.category1) ->\n    exists lv', E.update_lvars n v lv = Some lv' /\\ lvar_sat lv' l.\nintros lv l l' s s' n t is_cat2 l'_ok unstore_code. \nunfold V.unstore in unstore_code.\ndestruct_opt (match n with O => ret tt | S nm1 => tnm1 <- nth_error l nm1;: if V.value_assertion_implication_dec class tnm1 PreV.VA.va_cat2 then fail else ret tt end) H unstore_code.\ndestruct_opt (nth_error l n) H0 unstore_code.\nunfold bind in unstore_code.\ndestruct_bool is_cat2 H1 unstore_code.\n (* The found va is cat2 *)\n destruct_opt (nth_error l (S n)) H2 unstore_code.\n  (* next position exists *)\n  destruct (PreV.VA.value_assertion_eq_dec x1 PreV.VA.va_top).\n   (* and contains va_top *)\n   simpl in unstore_code.\n   destruct_opt (list_update l n PreV.VA.va_top) H3 unstore_code.\n   inversion unstore_code. subst. clear unstore_code.\n   split.\n    reflexivity.\n    intros. \n    unfold E.update_lvars. \n    rewrite (H4 (refl_equal true)). \n    destruct (lvar_update_prop l'_ok H0 H3 H1) as [lv' [list_update_ok l_ok]].\n    destruct (lvar_update_prop_2 l_ok H2) as [lv'' [list_update2_ok l_ok2]].\n    destruct n. \n     rewrite list_update_ok. rewrite list_update2_ok. exists lv''. auto.\n     destruct (lvar_update_prop_3 l'_ok H3) as [v' lookup_n_ok]. \n     rewrite lookup_n_ok. destruct v' as [r|].\n      destruct r; unfold E.val_category; first [\n       rewrite list_update_ok; rewrite list_update2_ok; exists lv''; auto\n      |match goal with _:nth_error lv n = Some (Some ?v) |- _ => pose (v':=v) end;\n       destruct_opt (nth_error l n) H6 H;\n       unfold bind in H;\n       destruct_bool (V.value_assertion_implication_dec class x0 PreV.VA.va_cat2) H7 H;\n       assert (nth_error l' n = Some x0);\n       [eapply list_update_indep; eauto with arith\n       |assert (rt_ty_sat v' x0);\n        [eapply lvar_sat_ty_sat; eauto\n        |assert (x0 = PreV.VA.va_top);\n         [apply (is_va_top v'); auto\n         |subst;\n          destruct (lvar_update_prop_2 l'_ok H8) as [lv1' [update1_ok l_ok']];\n          destruct (lvar_update_prop l_ok' H0 H3 H1) as [lv1'' [update2_ok l_ok'']];\n          destruct (lvar_update_prop_2 l_ok'' H2) as [lv1''' [update3_ok l_ok''']];\n          exists lv1'''; rewrite update1_ok; rewrite update2_ok; rewrite update3_ok; auto ]]]]. \n      rewrite list_update_ok. rewrite list_update2_ok. exists lv''. auto.\n  (* next position does not exist: not possible *)\n  discriminate. \n (* The found va is possibly not cat2 *)\n destruct_opt (list_update l n PreV.VA.va_top) H2 unstore_code.\n inversion unstore_code. subst. clear unstore_code.\n split. reflexivity.\n  intros.\n  unfold E.update_lvars. rewrite (H4 (refl_equal false)). destruct n.\n   destruct (lvar_update_prop l'_ok H0 H2 H1) as [lv' [update_ok lv'_ok]]. rewrite update_ok. exists lv'. auto.\n   destruct (lvar_update_prop_3 l'_ok H2) as [v' v'_exists].\n   rewrite v'_exists. destruct v' as [r|].\n    destruct r; unfold E.val_category; first\n    [destruct (lvar_update_prop l'_ok H0 H2 H1) as [lv' [update_ok lv'_ok]]; rewrite update_ok; exists lv'; auto\n    |match goal with _:nth_error lv n = Some (Some ?v) |- _ => pose (v':=v) end;\n     destruct_opt (nth_error l n) H5 H;\n     unfold bind in H;\n     destruct_bool (V.value_assertion_implication_dec class x0 PreV.VA.va_cat2) H6 H;\n     assert (nth_error l' n = Some x0);\n     [eapply list_update_indep; eauto with arith\n     |assert (rt_ty_sat v' x0);\n      [eapply lvar_sat_ty_sat; eauto\n      |assert (x0 = PreV.VA.va_top);\n       [apply (is_va_top v'); auto\n       |subst;\n        destruct (lvar_update_prop_2 l'_ok H7) as [lv1' [update1_ok l_ok']];\n        destruct (lvar_update_prop l_ok' H0 H2 H1) as [lv1'' [update2_ok l_ok'']];\n        exists lv1''; rewrite update1_ok; rewrite update2_ok; auto ]]]]. \n    destruct (lvar_update_prop l'_ok H0 H2 H1) as [lv' [update_ok l_ok']]. rewrite update_ok. exists lv'. auto.\nSave.  \n\n(*\nLemma sem_unstore : forall lv l l' s s' n t,\n  lvar_sat lv l' -> V.unstore class n t (l,s) = Some (l',s') ->\n  s = s' /\\ forall v, rt_ty_sat v t -> exists lv', V.E.update_lvars n v lv = Some lv' /\\ lvar_sat lv' l.\nintros. \nunfold V.unstore in H0. \ndestruct (V.value_assertion_eq_dec t V.E.R.C.va_top). discriminate.\ndestruct_opt (match n with O => ret tt | S nm1 => tnm1 <- nth_error l nm1;: if V.value_assertion_implication_dec class tnm1 V.va_cat2 then fail else ret tt end) H1 H0.\ndestruct_opt (nth_error l n) H2 H0. \nunfold bind in H0. \ndestruct_bool (V.value_assertion_implication_dec class t x0) H3 H0.\ndestruct_bool (V.value_assertion_implication_dec class t V.va_cat2) H4 H0.\n(* Case when it is a category2 value being 'unstored' *)\ndestruct_opt (nth_error l (S n)) H5 H0.\ndestruct (V.value_assertion_eq_dec x1 V.E.R.C.va_top); try discriminate.\ndestruct_opt (list_update l n V.E.R.C.va_top) H6 H0.\ninversion H0. subst. clear H0. \nsplit.\n trivial.\n intros. \n unfold V.E.update_lvars. rewrite va_category2. \n assert (rt_ty_sat v x0). eapply value_assertion_implication_sound. apply V.value_assertion_implication_dec_sound. apply H3. apply H0.\n destruct n. \n  destruct (lvar_update_prop _ _ _ _ _ _ _ H H2 H6 H7). destruct H8. rewrite H8. \n  destruct (lvar_update_prop_2 _ _ _ H9 H5). destruct H10. rewrite H10.\n  exists x2. intuition. \n  destruct_opt (nth_error l n) H8 H1.\n  unfold bind in H1. destruct_bool (V.value_assertion_implication_dec class x1 V.va_cat2) H9 H1. \n  destruct (lvar_update_prop_3 _ _ _ _ _ H H6). rewrite H10. destruct x2. \n   (* something exists in the previous slot *)\n   destruct r; unfold V.E.val_category; try\n    (destruct (lvar_update_prop _ _ _ _ _ _ _ H H2 H6 H7); destruct H11; rewrite H11; \n     destruct (lvar_update_prop_2 _ _ _ H12 H5); destruct H13; rewrite H13;\n     exists x3; intuition).\n   (* longs *)\n   assert (nth_error l' n = Some x1). eapply list_update_indep. apply H8. apply H6. auto with arith.\n   assert (rt_ty_sat V.E.rt_long x1). eapply lvar_sat_ty_sat. apply H10. apply H. assumption.\n   assert (x1 = V.E.R.C.va_top). apply (is_va_top V.E.rt_long). trivial. assumption. unfold not. intro. rewrite (V.value_assertion_implication_dec_complete class _ _ H13) in H9. discriminate.  \n   subst. \n   destruct (lvar_update_prop_2 _ _ _ H H11). destruct H13. rewrite H13.\n   destruct (lvar_update_prop _ _ _ _ _ _ _ H14 H2 H6 H7). destruct H15. rewrite H15. \n   destruct (lvar_update_prop_2 _ _ _ H16 H5); destruct H17; rewrite H17;\n   exists x3; intuition.\n   (* doubles *)\n   assert (nth_error l' n = Some x1). eapply list_update_indep. apply H8. apply H6. auto with arith.\n   assert (rt_ty_sat V.E.rt_double x1). eapply lvar_sat_ty_sat. apply H10. apply H. assumption.\n   assert (x1 = V.E.R.C.va_top). apply (is_va_top V.E.rt_double). trivial. assumption. unfold not. intro. rewrite (V.value_assertion_implication_dec_complete class _ _ H13) in H9. discriminate.  \n   subst. \n   destruct (lvar_update_prop_2 _ _ _ H H11). destruct H13. rewrite H13.\n   destruct (lvar_update_prop _ _ _ _ _ _ _ H14 H2 H6 H7). destruct H15. rewrite H15. \n   destruct (lvar_update_prop_2 _ _ _ H16 H5); destruct H17; rewrite H17;\n   exists x3; intuition.\n   destruct (lvar_update_prop _ _ _ _ _ _ _ H H2 H6 H7); destruct H11; rewrite H11; \n   destruct (lvar_update_prop_2 _ _ _ H12 H5); destruct H13; rewrite H13;\n   exists x3; intuition.\neapply value_assertion_implication_sound. \n apply V.value_assertion_implication_dec_sound. apply H4. \n apply H0.\n(* Case for a category1 value *)\ndestruct_opt (list_update l n V.E.R.C.va_top) H5 H0.\ninversion H0. subst. clear H0. \nsplit.\n trivial. \n intros. \n assert (V.E.val_category v = V.E.R.C.category1). eapply va_notimp_category1. apply n0. apply H0. \n  unfold not. intros. rewrite (V.value_assertion_implication_dec_complete class _ _ H6) in H4. discriminate.\n assert (rt_ty_sat v x0). eapply value_assertion_implication_sound. apply V.value_assertion_implication_dec_sound. apply H3. apply H0.\n unfold V.E.update_lvars. rewrite H6.\n destruct n.\n  destruct (lvar_update_prop _ _ _ _ _ _ _ H H2 H5 H7). destruct H8. rewrite H8. exists x1. intuition. \n  destruct_opt (nth_error l n) H8 H1. \n  unfold bind in H1. destruct_bool (V.value_assertion_implication_dec class x1 V.va_cat2) H9 H1.\n  destruct (lvar_update_prop_3 _ _ _ _ _ H H5). rewrite H10. destruct x2. \n   destruct r; unfold V.E.val_category; try\n    (destruct (lvar_update_prop _ _ _ _ _ _ _ H H2 H5 H7); destruct H11; rewrite H11; \n     exists x2; intuition).\n   (* case for long *)\n   assert (nth_error l' n = Some x1). eapply list_update_indep. apply H8. apply H5. auto with arith.\n   assert (rt_ty_sat V.E.rt_long x1). eapply lvar_sat_ty_sat. apply H10. apply H. assumption.\n   assert (x1 = V.E.R.C.va_top). apply (is_va_top V.E.rt_long). trivial. assumption. unfold not. intro. rewrite (V.value_assertion_implication_dec_complete class _ _ H13) in H9. discriminate.  \n   subst. \n   destruct (lvar_update_prop_2 _ _ _ H H11). destruct H13. rewrite H13. \n   destruct (lvar_update_prop _ _ _ _ _ _ _ H14 H2 H5 H7). destruct H15. rewrite H15.\n   exists x2. auto.\n   (* case for double *)\n   assert (nth_error l' n = Some x1). eapply list_update_indep. apply H8. apply H5. auto with arith.\n   assert (rt_ty_sat V.E.rt_double x1). eapply lvar_sat_ty_sat. apply H10. apply H. assumption.\n   assert (x1 = V.E.R.C.va_top). apply (is_va_top V.E.rt_double). trivial. assumption. unfold not. intro. rewrite (V.value_assertion_implication_dec_complete class _ _ H13) in H9. discriminate.  \n   subst. \n   destruct (lvar_update_prop_2 _ _ _ H H11). destruct H13. rewrite H13. \n   destruct (lvar_update_prop _ _ _ _ _ _ _ H14 H2 H5 H7). destruct H15. rewrite H15.\n   exists x2. auto.\n   destruct (lvar_update_prop _ _ _ _ _ _ _ H H2 H5 H7). destruct H11. rewrite H11. \n   exists x2. auto. \nSave.\n*)\n\nLemma sem_pop_n : forall A A' s,\n  stack_sat s (A ++ A') ->\n  exists l, exists l', E.pop_n (length A) s = Some (l,l') /\\ stack_sat_exact l A /\\ stack_sat l' A'.\nintros A A'. induction A; intros.\n exists (nil (A:=E.rt_val)). exists s. intuition. constructor. \n destruct s; inversion H. subst. destruct (IHA s H5). destruct H0. \n exists (r::x). exists x0. intuition.\n  simpl. rewrite H1. reflexivity.\n  constructor; assumption.\nSave.\n\nLemma general_lvars_sat : forall n, lvar_sat (E.make_padding_lvars n) (V.general_lvar_assertion n).\nintro. induction n; simpl; constructor. assumption.\nSave.\n\nLemma java_type_category1 : forall v ty, rt_ty_sat v (V.java_type_to_value_assertion ty) -> C.java_type_category ty = C.category1 -> E.val_category v = C.category1.\nintros. \napply va_category1. \neapply value_assertion_implication_sound. \napply V.java_type_category_correct1. \napply H0. assumption.\nSave.\n\nLemma java_type_category2 : forall v ty, rt_ty_sat v (V.java_type_to_value_assertion ty) -> C.java_type_category ty = C.category2 -> E.val_category v = C.category2.\nintros. \napply va_category2. \neapply value_assertion_implication_sound. \napply V.java_type_category_correct2. \napply H0. assumption.\nSave.\n\nLemma sem_argument_prep : forall arg_types s l n,\n  V.arg_tys_to_lvar_assertion arg_types n = Some l ->\n  stack_sat_exact s (map V.java_type_to_value_assertion arg_types) ->\n  exists lv, E.stack_to_lvars s n = Some lv /\\\n             lvar_sat lv l.\nintro. induction arg_types; intros.\n simpl in * |- *. inversion H. inversion H0. subst.\n exists (E.make_padding_lvars n). intuition. apply general_lvars_sat.\n simpl in * |- *. \n inversion H0. subst.\n generalize (refl_equal (V.C.java_type_category a)); pattern (V.C.java_type_category a) at -1; case (V.C.java_type_category a); intros; rewrite H1 in H.\n  destruct (O_or_S n). \n   destruct s. rewrite <- e in H. \n   destruct_opt (V.arg_tys_to_lvar_assertion arg_types x) H2 H. inversion H. subst.\n   destruct (IHarg_types _ _ _ H2 H5). destruct H3. exists (Some v::x1). split.\n    simpl. rewrite (java_type_category1 _ _ H4 H1). rewrite H3. reflexivity.\n    constructor; assumption.\n   subst. discriminate.\n  destruct (O_or_S n).\n   destruct s. subst. destruct (O_or_S x). \n    destruct s. subst. destruct_opt (V.arg_tys_to_lvar_assertion arg_types x0) H2 H. inversion H. subst.\n    destruct (IHarg_types _ _ _ H2 H5). destruct H3. exists (Some v::None::x1). split.\n     simpl. rewrite (java_type_category2 _ _ H4 H1). rewrite H3. reflexivity.\n     constructor. assumption. constructor. assumption.\n    subst. discriminate.\n   subst. discriminate.\nSave.\n\nLemma stack_sat_exact_app : forall s1 a1 s2 a2, stack_sat_exact s1 a1 -> stack_sat_exact s2 a2 -> stack_sat_exact (s1++s2) (a1++a2).\nintros. generalize a1 H. clear a1 H.\ninduction s1; intros; destruct a1; inversion H; subst; simpl.\n assumption.\n constructor; auto.\nSave.\n\nLemma stack_sat_exact_rev : forall s a, stack_sat_exact s a -> stack_sat_exact (rev s) (rev a).\nintro. induction s; intros; inversion H; subst; simpl.\n constructor. \n apply stack_sat_exact_app. auto. constructor. assumption. constructor.\nSave.\n\nLemma stack_sat_exact_rev_2 : forall s a, stack_sat_exact s (rev a) -> stack_sat_exact (rev s) a.\nintros. replace a with (rev (rev a)). apply stack_sat_exact_rev. assumption. apply rev_involutive.\nSave.\n\nLemma lvar_sat_app : forall l1 a1 l2 a2, lvar_sat l1 a1 -> lvar_sat l2 a2 -> lvar_sat (l1++l2) (a1++a2).\nintros. generalize a1 H. clear a1 H.\ninduction l1; intros; destruct a1; inversion H.\nsimpl. assumption. \nsimpl. apply lvar_sat_cons1. apply H4. apply IHl1. apply H6. \nsimpl. apply lvar_sat_cons2. apply IHl1. apply H2.\nSave.\n\nLemma lvar_sat_rev : forall l a, lvar_sat l a -> lvar_sat (rev l) (rev a).\nintros. generalize a H. clear a H.\ninduction l; intros. destruct a; inversion H.\napply lvar_sat_nil.\ndestruct a0; inversion H.\nsimpl. apply lvar_sat_app. apply IHl. apply H5. apply lvar_sat_cons1. apply H3. apply lvar_sat_nil.\nsimpl. apply lvar_sat_app. apply IHl. apply H1. apply lvar_sat_cons2. apply lvar_sat_nil.\nSave.\n\nLemma default_value_sat : forall j, rt_ty_sat (E.default_value j) (V.java_type_to_value_assertion j).\nintros. destruct j; simpl; try constructor.\nSave.\n\nEnd Satisfiability.\n\nDefinition preserve_heap_types := fun heap1 heap2 =>\n  forall a nm fields,\n    E.ObjectHeap.lookup heap1 a = Some (E.hp_object nm fields) ->\n    exists fields', E.ObjectHeap.lookup heap2 a = Some (E.hp_object nm fields').\n\nLemma preserve_heap_types_id : forall h, preserve_heap_types h h.\nunfold preserve_heap_types. intros.\nexists fields. assumption.\nSave.\nHint Resolve preserve_heap_types_id.\n\nLemma preserve_old_classes_id : forall c, E.R.preserve_old_classes c c.\nintros. unfold E.R.preserve_old_classes. auto.\nSave.\nHint Resolve preserve_old_classes_id.\n\nLemma preserve_heap_types_trans : forall heapA heapB heapC,\n  preserve_heap_types heapA heapB ->\n  preserve_heap_types heapB heapC ->\n  preserve_heap_types heapA heapC.\nunfold preserve_heap_types. intros. \ndestruct (H _ _ _ H1).\napply (H0 _ _ _ H2).\nSave.\n\nLemma preserve_rt_ty_sat : forall classesA classesB heapA heapB v a,\n  rt_ty_sat classesA heapA v a ->\n  E.R.preserve_old_classes classesA classesB ->\n  preserve_heap_types heapA heapB ->\n  rt_ty_sat classesB heapB v a.\nintros. induction H; try constructor.\n destruct (H1 _ _ _ H); eapply ty_sat_addr2;\n [apply H3|eapply R.preserve_subclass; [apply H2|apply H0]].\n destruct (H1 _ _ _ H); eapply ty_sat_ref_Some. eauto.\nSave.\n\nLemma preserve_lvar_sat : forall classesA classesB heapA heapB lvars a,\n  lvar_sat classesA heapA lvars a ->\n  R.preserve_old_classes classesA classesB ->\n  preserve_heap_types heapA heapB ->\n  lvar_sat classesB heapB lvars a.\nintros. induction H. \n constructor. \n apply lvar_sat_cons1. \n  eapply preserve_rt_ty_sat. \n   apply H.\n   apply H0.\n   apply H1.\n  apply IHlvar_sat.\n apply lvar_sat_cons2.\n  apply IHlvar_sat.\nSave.\n\nLemma preserve_stack_sat : forall classesA classesB heapA heapB stack a,\n  stack_sat classesA heapA stack a ->\n  R.preserve_old_classes classesA classesB ->\n  preserve_heap_types heapA heapB ->\n  stack_sat classesB heapB stack a.\nintros. induction H.\n constructor.\n apply stk_sat_cons. \n  eapply preserve_rt_ty_sat.\n   apply H.\n   apply H0.\n   apply H1.\n  apply IHstack_sat.\nSave.\n\nLemma preserve_stack_sat_exact : forall classesA classesB heapA heapB stack a,\n  stack_sat_exact classesA heapA stack a ->\n  R.preserve_old_classes classesA classesB ->\n  preserve_heap_types heapA heapB ->\n  stack_sat_exact classesB heapB stack a.\nintros. induction H.\n constructor.\n apply stk_sat_exact_cons. \n  eapply preserve_rt_ty_sat.\n   apply H.\n   apply H0.\n   apply H1.\n  apply IHstack_sat_exact.\nSave.\nImplicit Arguments preserve_stack_sat_exact [classesA classesB heapA heapB stack a].\n\nLemma preserve_subclass_assertions_satisfied : forall classesA classesB class,\n  subclass_assertions_satisfied classesA class ->\n  R.preserve_old_classes classesA classesB ->\n  subclass_assertions_satisfied classesB class.\nunfold subclass_assertions_satisfied. intros. \neapply R.preserve_subclass. \n apply H. apply H1.\n apply H0.\nSave.\n\nLemma sem_unpush_2 : forall classes heap class a a' b b' s ty,\n  subclass_assertions_satisfied classes class ->\n  stack_sat classes heap s a' ->\n  V.unpush class ty (b,a) = Some (b',a') ->\n  b = b' /\\ forall v classes' heap',\n   R.preserve_old_classes classes classes' ->\n   preserve_heap_types heap heap' ->\n   rt_ty_sat classes' heap' v ty -> stack_sat classes' heap' (v::s) a.\nintros. \nsimpl in H1. destruct a. discriminate.\ndestruct_bool (V.value_assertion_implication_dec class ty v) H2 H1.\ninversion H1. subst a b. split.\n trivial. \n intros. apply stk_sat_cons.\n  eapply value_assertion_implication_sound. \n   eapply preserve_subclass_assertions_satisfied; eauto.\n   apply V.value_assertion_implication_dec_sound. apply H2. assumption.\n  eapply preserve_stack_sat; eauto.\nSave.\nImplicit Arguments sem_unpush_2 [classes heap class a a' b b' s ty].\n\n\nImplicit Arguments sem_unpop [classes heap s a a' b b' ty].\nImplicit Arguments sem_unpush [classes heap class a a' b b' s ty].\nImplicit Arguments sem_known_unpush [classes heap a a' b b' s ty].\nImplicit Arguments sem_lvar_lookup [classes heap l a n t].\nImplicit Arguments sem_unretrieve [classes heap class a a' l b b' t n].\nImplicit Arguments sem_unstore [classes heap class lv l l' s s' n t is_cat2].\nImplicit Arguments sem_pop_n [classes heap A A' s].\nImplicit Arguments sem_argument_prep [classes heap class arg_types s l n].\n\nLemma check_exception_handlers_prop : forall classes heap code class cert pc (handlers:list C.exception_handler) e e_exists res l,\n  subclass_assertions_satisfied classes class ->\n  R.sub_class classes (C.class_name e) B.java_lang_Exception ->\n  V.check_exception_handlers code class cert pc handlers = Some l ->\n  E.search_handlers classes handlers pc class e e_exists = res ->\n  (exists pc', exists l', exists s',\n    E.handler_found pc' = res /\\\n    PreV.VA.Cert.lookup cert pc' = Some (l', s') /\\\n    V.lvar_assertion_implication class l l' /\\\n    forall v, rt_ty_sat classes heap v (PreV.VA.va_addr (C.class_name e)) -> stack_sat classes heap (v::nil) s')\n  \\/\n  E.handler_notfound = res.\nintros classes heap code class cert pc handlers e e_exists res.  \ninduction handlers.\n (* Base case: no handlers *)\n simpl in *. intros l subclassing_ok e_isa_Throwable check_code search_code.\n right. assumption.\n (* Step case *)\n intros l subclassing_ok e_isa_Throwable check_code search_code.\n destruct a as [start_pc end_pc handler_pc opt_type_idx]. \n simpl in *.\n destruct (option_dec (V.check_exception_handlers code class cert pc handlers)) as [[l' handlers_checked] | checkfailed].\n  (* Checking the rest succeeded *)\n  rewrite handlers_checked in check_code.\n  simpl in check_code. \n  change (E.R.C.is_within start_pc end_pc pc) with (V.C.is_within start_pc end_pc pc) in search_code.\n  destruct (V.C.is_within start_pc end_pc pc) as [is_within | is_without]. \n   (* This handler applies to this pc *)\n   destruct (option_dec (PreV.VA.Cert.lookup cert handler_pc)) as [[[handler_l handler_s] cert_lookup_ok] | cert_lookup_failed].\n    (* Certificate lookup succeeded *)\n    rewrite cert_lookup_ok in check_code. simpl in check_code.\n    destruct opt_type_idx as [idx|].\n     (* This handler is for a specific type *)\n     (*change (match E.R.C.ConstantPool.lookup (E.R.C.class_constantpool class) idx\n             with\n             | Some o =>\n             match o with\n             | E.R.C.cpe_methodref _ _ _ => E.handler_wrong\n             | E.R.C.cpe_fieldref _ _ _ => E.handler_wrong\n             | E.R.C.cpe_int _ => E.handler_wrong\n             | E.R.C.cpe_classref cls_nm =>\n                 if E.R.check_subclass e_exists cls_nm\n                 then E.handler_found handler_pc\n                 else\n                  E.search_handlers classes handlers pc class e e_exists\n             | E.R.C.cpe_other => E.handler_wrong\n             end\n             | None => E.handler_wrong end)\n       with (match V.C.ConstantPool.lookup (V.C.class_constantpool class) idx\n             with\n             | Some o =>\n             match o with\n             | V.C.cpe_classref cls_nm => if E.R.check_subclass e_exists cls_nm\n                 then E.handler_found handler_pc\n                 else\n                  E.search_handlers classes handlers pc class e e_exists\n             | _ => E.handler_wrong\n             end\n             | None => E.handler_wrong end) in search_code.*)\n     destruct (option_dec (V.C.ConstantPool.lookup (V.C.class_constantpool class) idx)) as [[ref constantpool_ok] | constantpool_fail].\n      (* constant pool lookup succeded *)\n      rewrite constantpool_ok in check_code. \n      change V.C.ConstantPool.lookup with E.R.C.ConstantPool.lookup in constantpool_ok.\n      change V.C.class_constantpool with E.R.C.class_constantpool in constantpool_ok.\n      rewrite constantpool_ok in search_code. \n      simpl in check_code. \n      destruct ref as [x|x|x|clsname|]; try discriminate.\n      unfold ret in check_code.\n      unfold bind in check_code.\n      destruct (bool_dec (V.stack_assertion_implication_dec class (PreV.VA.va_addr clsname::nil) handler_s)) as [imp_ok|imp_notok].\n       (* Stack implication ok *)\n       rewrite imp_ok in check_code. simpl in check_code.\n       destruct (bool_dec (E.R.check_subclass e_exists clsname)) as [e_isa_clsname|not_e_isa_clsname].\n        (* This handler is actually the one we want *)\n        rewrite e_isa_clsname in search_code. \n        left. exists handler_pc. exists handler_l. exists handler_s. intuition.\n         eapply V.lvar_assertion_merge_p2. apply check_code.\n         eapply stack_assertion_implication_sound. \n          apply subclassing_ok.\n          apply V.stack_assertion_implication_dec_sound. apply imp_ok.\n          apply stk_sat_cons; try constructor.\n           change (PreV.VA.va_addr (C.class_name e)) with (C.A.va_addr (C.class_name e)) in H1.\n           inversion H1. \n           (* reference was null *)\n           subst v x. apply ty_sat_addr1. \n           (* reference wasn't null *)\n           subst v nm. eapply ty_sat_addr2. \n            apply H3. \n            eapply R.sub_class_trans. \n             apply H5.\n             eapply R.check_subclass_sound. apply e_isa_clsname.\n        (* not the handler we were looking for *)\n        rewrite not_e_isa_clsname in search_code.\n        destruct (IHhandlers l' subclassing_ok e_isa_Throwable handlers_checked search_code) as [[pc' [l'' [s'' [res_is_found [cert_lookup_ok' [lvar_imp_ok stk_ok]]]]]] | res_is_notfound].\n         (* a handler was found *)\n         left. exists pc'. exists l''. exists s''. intuition.\n          eapply V.lvar_assertion_implication_trans. \n           eapply V.lvar_assertion_merge_p1. apply check_code.\n           apply lvar_imp_ok.\n         (* a handler was not found *)\n         right. assumption.\n       (* stack implication not ok *)\n       rewrite imp_notok in check_code. discriminate.\n      (* constantpool looked failed *)\n      rewrite constantpool_fail in check_code. discriminate.\n     (* Handler not for a specific type *)\n     unfold ret in check_code. \n     unfold bind in check_code. \n     destruct (bool_dec (V.stack_assertion_implication_dec class (PreV.VA.va_addr V.B.java_lang_Exception :: nil) handler_s)) as [stk_imp_ok|stk_imp_notok].\n      (* stack implication was ok *)\n      rewrite stk_imp_ok in check_code.\n      simpl in check_code.\n      left. exists handler_pc. exists handler_l. exists handler_s. intuition.\n       eapply V.lvar_assertion_merge_p2. apply check_code.\n       eapply stack_assertion_implication_sound. \n        apply subclassing_ok. \n        apply V.stack_assertion_implication_dec_sound. apply stk_imp_ok.\n        apply stk_sat_cons; try constructor.\n         change (PreV.VA.va_addr (C.class_name e)) with (C.A.va_addr (C.class_name e)) in H1.\n         inversion H1. \n         (* reference was null *)\n         subst v x. apply ty_sat_addr1.\n         (* reference wasn't null *)\n         subst v nm. eapply ty_sat_addr2.\n          apply H3.\n          eapply R.sub_class_trans. \n           apply H5. \n           assumption.\n      (* stack implication was not ok *)\n      rewrite stk_imp_notok in check_code. discriminate.\n    (* certificate lookup failed *)\n    rewrite cert_lookup_failed in check_code. discriminate.\n   (* Handler does not apply to this pc *)\n   inversion check_code. subst l'. apply IHhandlers; assumption.\n  (* checking the other handlers failed *)\n  rewrite checkfailed in check_code. discriminate.\nSave.\n\nInductive safe_current_frame (classes:R.cert_classpool) (heap:E.ObjectHeap.t) : E.frame -> option C.java_type -> Prop :=\n  mk_safe_current_frame : forall cert op_stack lvars pc class rt lvar_assertion stack_assertion code,\n    R.Classpool.lookup (R.classpool classes) (C.class_name class) = Some class ->\n    V.safe_code code class rt cert  ->\n    C.A.Cert.lookup cert pc = Some (lvar_assertion, stack_assertion) ->\n    lvar_sat classes heap lvars lvar_assertion ->\n    stack_sat classes heap op_stack stack_assertion ->\n    subclass_assertions_satisfied classes class ->\n    safe_current_frame classes heap (E.mkFrame op_stack lvars pc code class) rt.\n\nInductive safe_frame_stack (classes:R.cert_classpool) (heap:E.ObjectHeap.t) : list E.frame -> option C.java_type -> option C.java_type -> Prop :=\n| safe_stack_nil  : forall rt, safe_frame_stack classes heap nil rt rt\n| safe_stack_cons : forall op_stack lvars pc class fs in_ty out_ty final_ty cert lvar_assertion stack_assertion code lvar_exc_assertion,\n    safe_frame_stack classes heap fs out_ty final_ty ->\n    R.Classpool.lookup (R.classpool classes) (C.class_name class) = Some class ->\n    V.safe_code code class out_ty cert ->\n    C.A.Cert.lookup cert (S pc) = Some (lvar_assertion, stack_assertion) ->\n    lvar_sat classes heap lvars lvar_assertion ->\n    (forall v classes' heap',\n       R.preserve_old_classes classes classes' ->\n       preserve_heap_types heap heap' ->\n       rt_ty_sat classes' heap' v (V.java_type_to_value_assertion in_ty) ->\n       stack_sat classes' heap' (v::op_stack) stack_assertion) ->\n    subclass_assertions_satisfied classes class ->\n    V.check_exception_handlers code class cert pc (C.code_exception_table code) = Some lvar_exc_assertion ->\n    lvar_sat classes heap lvars lvar_exc_assertion ->\n    safe_frame_stack classes heap (E.mkFrame op_stack lvars pc code class::fs) (Some in_ty) final_ty\n| safe_stack_cons_void : forall op_stack lvars pc class fs out_ty final_ty cert lvar_assertion stack_assertion code lvar_exc_assertion,\n    safe_frame_stack classes heap fs out_ty final_ty ->\n    R.Classpool.lookup (R.classpool classes) (C.class_name class) = Some class ->\n    V.safe_code code class out_ty cert ->\n    C.A.Cert.lookup cert (S pc) = Some (lvar_assertion, stack_assertion) ->\n    lvar_sat classes heap lvars lvar_assertion ->\n    stack_sat classes heap op_stack stack_assertion ->\n    subclass_assertions_satisfied classes class ->\n    V.check_exception_handlers code class cert pc (C.code_exception_table code) = Some lvar_exc_assertion ->\n    lvar_sat classes heap lvars lvar_exc_assertion ->\n    safe_frame_stack classes heap (E.mkFrame op_stack lvars pc code class::fs) None final_ty.\n\nInductive static_method_ref_resolvable : R.cert_classpool -> R.Preclasspool.t -> B.Classname.t -> B.Classname.t -> B.Methodname.t -> C.descriptor -> Prop :=\n| mk_static_method_ref_resolvable : forall caller c_nm m_nm m_desc classes preclasses classes' p o c m H code,\n    R.resolve_method caller c_nm m_nm m_desc classes preclasses = R.load_ok _ (classes':=classes') p o (c,m) H ->\n    C.method_static m = true ->\n    C.method_code m = Some code ->\n    static_method_ref_resolvable classes preclasses caller c_nm m_nm m_desc.\n\nInductive instance_special_method_ref_resolvable : R.cert_classpool -> R.Preclasspool.t -> B.Classname.t -> B.Classname.t -> B.Methodname.t -> C.descriptor -> Prop :=\n| mk_instance_special_method_ref_resolvable : forall caller c_nm m_nm m_desc classes preclasses classes' p o c m H code,\n    R.resolve_method caller c_nm m_nm m_desc classes preclasses = R.load_ok _ (classes':=classes') p o (c,m) H ->\n    C.method_static m = false ->\n    C.method_abstract m = false ->\n    C.method_code m = Some code ->\n    instance_special_method_ref_resolvable classes preclasses caller c_nm m_nm m_desc.\n\nInductive instance_method_ref_resolvable : R.cert_classpool -> R.Preclasspool.t -> B.Classname.t -> B.Classname.t -> B.Methodname.t -> C.descriptor -> Prop :=\n| mk_instance_method_ref_resolvable : forall caller c_nm m_nm m_desc classes preclasses classes' p o c m H,\n    R.resolve_method caller c_nm m_nm m_desc classes preclasses = R.load_ok _ (classes':=classes') p o (c,m) H ->\n    C.method_static m = false ->\n    instance_method_ref_resolvable classes preclasses caller c_nm m_nm m_desc.\n\nInductive static_field_ref_resolvable : R.cert_classpool -> R.Preclasspool.t -> B.Classname.t -> B.Classname.t -> B.Fieldname.t -> C.java_type -> Prop :=\n| mk_static_field_ref_resolvable : forall caller c_nm f_nm f_ty classes preclasses classes' p o c f H,\n    R.resolve_field caller c_nm f_nm f_ty classes preclasses = R.load_ok _ (classes':=classes') p o (c,f) H ->\n    C.field_static f = true ->\n    static_field_ref_resolvable classes preclasses caller c_nm f_nm f_ty.\n\nInductive instance_field_ref_resolvable : R.cert_classpool -> R.Preclasspool.t -> B.Classname.t -> B.Classname.t -> B.Fieldname.t -> C.java_type -> Prop :=\n| mk_instance_field_ref_resolvable : forall caller c_nm f_nm f_ty classes preclasses classes' p o c f H,\n    R.resolve_field caller c_nm f_nm f_ty classes preclasses = R.load_ok _ (classes':=classes') p o (c,f) H ->\n    C.field_static f = false ->\n    C.field_final f = false ->\n    instance_field_ref_resolvable classes preclasses caller c_nm f_nm f_ty.\n\nInductive instantiatable_class_ref_resolvable : R.cert_classpool -> R.Preclasspool.t -> B.Classname.t -> B.Classname.t -> Prop :=\n| mk_instantiatable_class_ref_resolvable : forall caller c_nm classes preclasses classes' p o c H,\n    R.resolve_class caller c_nm classes preclasses = R.load_ok _ (classes':=classes') p o c H ->\n    C.class_interface c = false ->\n    C.class_abstract c = false ->\n    instantiatable_class_ref_resolvable classes preclasses caller c_nm.\n\nInductive class_ref_resolvable : R.cert_classpool -> R.Preclasspool.t -> B.Classname.t -> B.Classname.t -> Prop :=\n| mk_class_ref_resolvable : forall caller c_nm classes preclasses classes' p o c H,\n    R.resolve_class caller c_nm classes preclasses = R.load_ok _ (classes':=classes') p o c H ->\n    class_ref_resolvable classes preclasses caller c_nm.\n\nInductive all_resolvable_for_class : R.cert_classpool -> R.Preclasspool.t -> C.class -> Prop :=\n| mk_all_resolvable_for_class : forall classes preclasses class,\n    (forall cp_idx c_nm m_nm m_desc,\n       C.ConstantPool.lookup (C.class_constantpool class) cp_idx = Some (C.cpe_methodref c_nm m_nm m_desc) ->\n       C.A.ConstantPoolAdditional.lookup (C.A.class_annot_constantpool (C.class_annotation class)) cp_idx = Some (C.A.cpae_static_method) ->\n       static_method_ref_resolvable classes preclasses (C.class_name class) c_nm m_nm m_desc) ->\n    (forall cp_idx c_nm m_nm m_desc,\n       C.ConstantPool.lookup (C.class_constantpool class) cp_idx = Some (C.cpe_methodref c_nm m_nm m_desc) ->\n       C.A.ConstantPoolAdditional.lookup (C.A.class_annot_constantpool (C.class_annotation class)) cp_idx = Some (C.A.cpae_instance_special_method) ->\n       instance_special_method_ref_resolvable classes preclasses (C.class_name class) c_nm m_nm m_desc) ->\n    (forall cp_idx c_nm m_nm m_desc,\n       C.ConstantPool.lookup (C.class_constantpool class) cp_idx = Some (C.cpe_methodref c_nm m_nm m_desc) ->\n       C.A.ConstantPoolAdditional.lookup (C.A.class_annot_constantpool (C.class_annotation class)) cp_idx = Some (C.A.cpae_instance_method) ->\n       instance_method_ref_resolvable classes preclasses (C.class_name class) c_nm m_nm m_desc) ->\n    (forall cp_idx c_nm f_nm f_ty,\n       C.ConstantPool.lookup (C.class_constantpool class) cp_idx = Some (C.cpe_fieldref c_nm f_nm f_ty) ->\n       C.A.ConstantPoolAdditional.lookup (C.A.class_annot_constantpool (C.class_annotation class)) cp_idx = Some (C.A.cpae_static_field) ->\n       static_field_ref_resolvable classes preclasses (C.class_name class) c_nm f_nm f_ty) ->\n    (forall cp_idx c_nm,\n       C.ConstantPool.lookup (C.class_constantpool class) cp_idx = Some (C.cpe_classref c_nm) ->\n          class_ref_resolvable classes preclasses (C.class_name class) c_nm\n       /\\ (C.A.ConstantPoolAdditional.lookup (C.A.class_annot_constantpool (C.class_annotation class)) cp_idx = Some (C.A.cpae_instantiable_class) ->\n           instantiatable_class_ref_resolvable classes preclasses (C.class_name class) c_nm)) ->\n    (forall cp_idx c_nm f_nm f_ty,\n       C.ConstantPool.lookup (C.class_constantpool class) cp_idx = Some (C.cpe_fieldref c_nm f_nm f_ty) ->\n       C.A.ConstantPoolAdditional.lookup (C.A.class_annot_constantpool (C.class_annotation class)) cp_idx = Some (C.A.cpae_instance_field) ->\n       instance_field_ref_resolvable classes preclasses (C.class_name class) c_nm f_nm f_ty) ->\n    subclass_assertions_satisfied classes class ->\n    all_resolvable_for_class classes preclasses class.\n\nInductive all_resolvable_and_verified : R.cert_classpool -> R.Preclasspool.t -> Prop :=\n| mk_all_resolvable_and_verified : forall classes preclasses,\n    (forall c_nm c,\n       R.Classpool.lookup (R.classpool classes) c_nm = Some c ->\n       all_resolvable_for_class classes preclasses c /\\ V.class_verified c) ->\n    (forall c_nm pc,\n       R.Preclasspool.lookup preclasses c_nm = Some pc ->\n       all_resolvable_for_class classes preclasses (R.preclass_to_class pc) /\\ V.class_verified (R.preclass_to_class pc)) ->\n    all_resolvable_and_verified classes preclasses.\n\nDefinition fields_well_typed (classes:R.cert_classpool) (heap:E.ObjectHeap.t) : E.FieldStore.t -> Prop := fun statics =>\n  forall c_nm f_nm ty v,\n    E.FieldStore.lookup statics (c_nm, f_nm, ty) = Some v ->\n    rt_ty_sat classes heap v (V.java_type_to_value_assertion ty).\n\nDefinition heap_well_typed (classes:R.cert_classpool) (heap:E.ObjectHeap.t) : Prop :=\n   forall a nm fields,\n    E.ObjectHeap.lookup heap a = Some (E.hp_object nm fields) ->\n    (exists c, R.Classpool.lookup (R.classpool classes) nm = Some c /\\ C.class_interface c = false /\\ C.class_abstract c = false) /\\\n    fields_well_typed classes heap fields.\n\nInductive exception_classes : R.cert_classpool -> Prop :=\n  mk_exception_classes : forall classes npe cce,\n    R.Classpool.lookup (R.classpool classes) B.java_lang_NullPointerException = Some npe ->\n    C.class_interface npe = false ->\n    C.class_abstract npe = false ->\n    R.Classpool.lookup (R.classpool classes) B.java_lang_ClassCastException = Some cce ->\n    C.class_interface cce = false ->\n    C.class_abstract cce = false ->\n    R.sub_class classes B.java_lang_NullPointerException B.java_lang_Exception ->\n    R.sub_class classes B.java_lang_ClassCastException B.java_lang_Exception ->\n    R.sub_class classes B.java_lang_Exception B.java_lang_Throwable ->\n    exception_classes classes.\n\nInductive safe_state : R.Preclasspool.t -> E.state -> option C.java_type -> Prop :=\n  mk_safe_state : forall f fs classes preclasses heap current_ty final_ty static_fields,\n    safe_current_frame classes heap f current_ty ->\n    safe_frame_stack classes heap fs current_ty final_ty ->\n    all_resolvable_and_verified classes preclasses ->\n    fields_well_typed classes heap static_fields ->\n    heap_well_typed classes heap ->\n    exception_classes classes ->\n    safe_state preclasses (E.mkState (f::fs) classes heap static_fields) final_ty.\n\nLemma preserve_exception_classes : forall classesA classesB,\n  exception_classes classesA ->\n  R.preserve_old_classes classesA classesB ->\n  exception_classes classesB.\nintros classesA classesB old_exc_classes preserve. \ndestruct old_exc_classes as [classesA npe cce npe1 npe2 npe3 cce1 cce2 cce3 sub1 sub2 sub3].\neapply mk_exception_classes; eauto;\n eapply R.preserve_subclass; eauto.\nSave.\n\nLemma preserve_fields_well_typed : forall classesA classesB heapA heapB statics,\n  fields_well_typed classesA heapA statics ->\n  R.preserve_old_classes classesA classesB ->\n  preserve_heap_types heapA heapB ->\n  fields_well_typed classesB heapB statics.\nunfold fields_well_typed. intros. \neapply preserve_rt_ty_sat; eauto.\nSave.\n\nLemma preserve_heap_well_typed : forall classesA classesB heap,\n  heap_well_typed classesA heap ->\n  R.preserve_old_classes classesA classesB ->\n  heap_well_typed classesB heap.\nunfold heap_well_typed. intros. \ndestruct (H _ _ _ H1).\nsplit.\n destruct H2. exists x. intuition. \n eapply preserve_fields_well_typed; eauto.\nSave.\n\nLemma preserve_static_method_resolvable : forall classesA classesB preclasses caller c_nm m_nm m_desc,\n  static_method_ref_resolvable classesA preclasses caller c_nm m_nm m_desc ->\n  R.preserve_old_classes classesA classesB ->\n  R.only_add_from_preclasses classesA classesB preclasses ->\n  static_method_ref_resolvable classesB preclasses caller c_nm m_nm m_desc.\nintros. destruct H. \ndestruct (R.preserve_resolve_method _ _ _ _ _ _ _ _ _ _ _ _ H2 H0 H1).\ndestruct H5. destruct H5. destruct H5.\napply (mk_static_method_ref_resolvable caller c_nm m_nm m_desc classesB preclasses x x0 x1 c m x2 code); assumption.\nSave.\n\nLemma preserve_instance_special_method_resolvable : forall classesA classesB preclasses caller c_nm m_nm m_desc,\n  instance_special_method_ref_resolvable classesA preclasses caller c_nm m_nm m_desc ->\n  R.preserve_old_classes classesA classesB ->\n  R.only_add_from_preclasses classesA classesB preclasses ->\n  instance_special_method_ref_resolvable classesB preclasses caller c_nm m_nm m_desc.\nintros. destruct H. \ndestruct (R.preserve_resolve_method _ _ _ _ _ _ _ _ _ _ _ _ H2 H0 H1).\ndestruct H6. destruct H6. destruct H6.\napply (mk_instance_special_method_ref_resolvable caller c_nm m_nm m_desc classesB preclasses x x0 x1 c m x2 code); assumption.\nSave.\n\nLemma preserve_instance_method_resolvable : forall classesA classesB preclasses caller c_nm m_nm m_desc,\n  instance_method_ref_resolvable classesA preclasses caller c_nm m_nm m_desc ->\n  R.preserve_old_classes classesA classesB ->\n  R.only_add_from_preclasses classesA classesB preclasses ->\n  instance_method_ref_resolvable classesB preclasses caller c_nm m_nm m_desc.\nintros. destruct H. \ndestruct (R.preserve_resolve_method _ _ _ _ _ _ _ _ _ _ _ _ H2 H0 H1).\ndestruct H4. destruct H4. destruct H4.\napply (mk_instance_method_ref_resolvable caller c_nm m_nm m_desc classesB preclasses x x0 x1 c m x2); assumption.\nSave.\n\nLemma preserve_static_field_ref_resolvable : forall classesA classesB preclasses caller c_nm f_nm f_ty,\n  static_field_ref_resolvable classesA preclasses caller c_nm f_nm f_ty ->\n  R.preserve_old_classes classesA classesB ->\n  R.only_add_from_preclasses classesA classesB preclasses ->\n  static_field_ref_resolvable classesB preclasses caller c_nm f_nm f_ty.\nintros. destruct H. \ndestruct (R.preserve_resolve_field _ _ _ _ _ _ _ _ _ _ _ _ H2 H0 H1).\ndestruct H4. destruct H4. destruct H4.\napply (mk_static_field_ref_resolvable caller c_nm f_nm f_ty classesB preclasses x x0 x1 c f x2); assumption.\nSave.\n\nLemma preserve_instance_field_ref_resolvable : forall classesA classesB preclasses caller c_nm f_nm f_ty,\n  instance_field_ref_resolvable classesA preclasses caller c_nm f_nm f_ty ->\n  R.preserve_old_classes classesA classesB ->\n  R.only_add_from_preclasses classesA classesB preclasses ->\n  instance_field_ref_resolvable classesB preclasses caller c_nm f_nm f_ty.\nintros. destruct H. \ndestruct (R.preserve_resolve_field _ _ _ _ _ _ _ _ _ _ _ _ H2 H0 H1).\ndestruct H5. destruct H5. destruct H5.\napply (mk_instance_field_ref_resolvable caller c_nm f_nm f_ty classesB preclasses x x0 x1 c f x2); assumption.\nSave.\n\nLemma preserve_instantiatable_class_ref_resolvable : forall classesA classesB preclasses caller c_nm,\n  instantiatable_class_ref_resolvable classesA preclasses caller c_nm ->\n  R.preserve_old_classes classesA classesB ->\n  R.only_add_from_preclasses classesA classesB preclasses ->\n  instantiatable_class_ref_resolvable classesB preclasses caller c_nm.\nintros. destruct H. \ndestruct (R.preserve_resolve_class _ _ _ _ _ _ _ _ _ _ H2 H0 H1).\n destruct H5. destruct H5. destruct H5. destruct H5. destruct H6. \napply (mk_instantiatable_class_ref_resolvable caller c_nm classesB preclasses x x0 x1 c x2 H5 H3 H4). \nSave.\n\nLemma preserve_class_ref_resolvable : forall classesA classesB preclasses caller c_nm,\n  class_ref_resolvable classesA preclasses caller c_nm ->\n  R.preserve_old_classes classesA classesB ->\n  R.only_add_from_preclasses classesA classesB preclasses ->\n  class_ref_resolvable classesB preclasses caller c_nm.\nintros classesA classesB preclasses caller c_nm resolveA presv only_add. \ndestruct resolveA as [caller c_nm classes preclasses classesA' p o c H resolveA]. \ndestruct (R.preserve_resolve_class _ _ _ _ _ _ _ _ _ _ resolveA presv only_add) as [classesB' [pB [oB [c_exB [resolveB X]]]]].\napply (mk_class_ref_resolvable caller c_nm classesB preclasses classesB' pB oB c c_exB resolveB). \nSave.\n\nLemma preserve_all_resolvable_for_class : forall classesA classesB preclasses class,\n  all_resolvable_for_class classesA preclasses class ->\n  R.preserve_old_classes classesA classesB ->\n  R.only_add_from_preclasses classesA classesB preclasses ->\n  all_resolvable_for_class classesB preclasses class.\nintros. destruct H. \napply mk_all_resolvable_for_class; intros.\n eapply preserve_static_method_resolvable; eauto.\n eapply preserve_instance_special_method_resolvable; eauto.\n eapply preserve_instance_method_resolvable; eauto.\n eapply preserve_static_field_ref_resolvable; eauto.\n destruct (H5 _ _ H8). split. \n  eapply preserve_class_ref_resolvable; eauto.\n  intros. eapply preserve_instantiatable_class_ref_resolvable; eauto.\n eapply preserve_instance_field_ref_resolvable; eauto.\n eapply preserve_subclass_assertions_satisfied; eauto.\nSave. \n\nLemma preserve_all_resolvable_and_verified : forall classesA classesB preclasses,\n  all_resolvable_and_verified classesA preclasses ->\n  R.preserve_old_classes classesA classesB ->\n  R.only_add_from_preclasses classesA classesB preclasses ->\n  all_resolvable_and_verified classesB preclasses.\nintros. destruct H. \napply mk_all_resolvable_and_verified; intros.\n (* classesB is ok: *)\n destruct (H1 _ _ H3).\n  destruct H4. destruct H4. subst c. destruct (H2 _ _ H5). split; [eapply preserve_all_resolvable_for_class; eauto|idtac]; eauto. \n  destruct (H _ _ H4). split; [eapply preserve_all_resolvable_for_class|idtac]; eauto.\n (* preclasses are still ok *)\n destruct (H2 _ _ H3). split; [eapply preserve_all_resolvable_for_class|idtac]; eauto.\nSave.\n\n\nLemma preserve_safe_frame_stack : forall classesA classesB heapA heapB fs ty1 ty2,\n  safe_frame_stack classesA heapA fs ty1 ty2 ->\n  R.preserve_old_classes classesA classesB ->\n  preserve_heap_types heapA heapB ->\n  safe_frame_stack classesB heapB fs ty1 ty2.\nintros. induction H.\n constructor.\n eapply safe_stack_cons; eauto.\n  eapply preserve_lvar_sat; eauto. \n  intros. apply H6; try assumption. \n   eapply R.preserve_old_classes_trans; eauto. \n   eapply preserve_heap_types_trans; eauto.\n  unfold subclass_assertions_satisfied. intros. eapply R.preserve_subclass; eauto.\n eapply preserve_lvar_sat; eauto.\n eapply safe_stack_cons_void; eauto.\n  eapply preserve_lvar_sat; eauto. \n  eapply preserve_stack_sat; eauto. \n  unfold subclass_assertions_satisfied. intros. eapply R.preserve_subclass; eauto.\n eapply preserve_lvar_sat; eauto.\nSave.\n\nLemma static_method_ref_ok : forall classes preclasses nm class c_nm m_nm m_desc idx,\n  all_resolvable_and_verified classes preclasses ->\n  R.Classpool.lookup (R.classpool classes) nm = Some class ->\n  V.C.ConstantPool.lookup (V.C.class_constantpool class) idx = Some (V.C.cpe_methodref c_nm m_nm m_desc) ->\n  PreV.VA.ConstantPoolAdditional.lookup (PreV.VA.class_annot_constantpool (V.C.class_annotation class)) idx = Some (PreV.VA.cpae_static_method) ->\n  exists classes', exists p, exists o, exists c, exists m, exists H, exists code,\n    E.R.resolve_method (E.R.C.class_name class) c_nm m_nm m_desc classes preclasses = E.R.load_ok _ (classes':=classes') p o (c,m) H\n    /\\ E.R.C.method_code m = Some code\n    /\\ E.R.C.method_static m = true\n    /\\ V.static_method_verified c m m_desc\n    /\\ all_resolvable_and_verified classes' preclasses\n    /\\ subclass_assertions_satisfied classes' c.\nintros classes preclasses nm class0 c_nm m_nm m_desc idx all_randv nm_is_class0 cp_lookup cpa_lookup.\nset (all_randv':=all_randv). generalize all_randv'. clear all_randv'. \ndestruct 1 as [classes preclasses classes_ok _].\ndestruct (classes_ok _ _ nm_is_class0) as [class0_randv _].\ndestruct class0_randv as [classes preclasses class0 ref_ok _ _ _ _ _ _].\nchange V.C.cpe_methodref with C.cpe_methodref in cp_lookup.\npose (B:=ref_ok _ _ _ _ cp_lookup cpa_lookup). generalize B. \nchange E.R.C.class_name with C.class_name.\ndestruct 1 as [caller c_nm m_nm m_desc classes preclasses classes' p o c m H code resolve_ok m_not_static m_not_abstract m_code].\nassert (all_randv':all_resolvable_and_verified classes' preclasses). \n eapply preserve_all_resolvable_and_verified; eauto. \nexists classes'. exists p. exists o. exists c. exists m. exists H. exists code. \n intuition;\n destruct all_randv' as [classes' preclasses classes_verified _];\n clear resolve_ok;\n destruct H as [c_ok [m_ok _]];\n destruct (classes_verified _ _ c_ok) as [c_all_randv c_verified]; simpl in *.\n  destruct c_verified. destruct (H _ _ _ m_ok). eauto.\n  destruct c_all_randv. assumption.\nSave.\nImplicit Arguments static_method_ref_ok [classes preclasses nm c_nm m_nm m_desc idx].\n\nLemma instance_special_method_ref_ok : forall classes preclasses nm class c_nm m_nm m_desc idx,\n  all_resolvable_and_verified classes preclasses ->\n  R.Classpool.lookup (R.classpool classes) nm = Some class ->\n  V.C.ConstantPool.lookup (V.C.class_constantpool class) idx = Some (V.C.cpe_methodref c_nm m_nm m_desc) ->\n  PreV.VA.ConstantPoolAdditional.lookup (PreV.VA.class_annot_constantpool (V.C.class_annotation class)) idx = Some (PreV.VA.cpae_instance_special_method) ->\n  exists classes', exists p, exists o, exists c, exists m, exists H, exists code,\n    E.R.resolve_method (E.R.C.class_name class) c_nm m_nm m_desc classes preclasses = E.R.load_ok _ (classes':=classes') p o (c,m) H\n    /\\ E.R.C.method_code m = Some code\n    /\\ E.R.C.method_static m = false\n    /\\ E.R.C.method_abstract m = false\n    /\\ V.instance_method_verified c m m_desc\n    /\\ all_resolvable_and_verified classes' preclasses\n    /\\ subclass_assertions_satisfied classes' c.\nintros classes preclasses nm class0 c_nm m_nm m_desc idx all_randv nm_is_class0 cp_lookup cpa_lookup.\nset (all_randv':=all_randv). generalize all_randv'. clear all_randv'. \ndestruct 1 as [classes preclasses classes_ok _].\ndestruct (classes_ok _ _ nm_is_class0) as [class0_randv _].\ndestruct class0_randv as [classes preclasses class0 _ ref_ok _ _ _ _ _].\nchange V.C.cpe_methodref with C.cpe_methodref in cp_lookup.\npose (B:=ref_ok _ _ _ _ cp_lookup cpa_lookup). generalize B. \nchange E.R.C.class_name with C.class_name.\ndestruct 1 as [caller c_nm m_nm m_desc classes preclasses classes' p o c m H code resolve_ok m_not_static m_not_abstract m_code].\nassert (all_randv':all_resolvable_and_verified classes' preclasses). \n eapply preserve_all_resolvable_and_verified; eauto. \nexists classes'. exists p. exists o. exists c. exists m. exists H. exists code. \n intuition;\n destruct all_randv' as [classes' preclasses classes_verified _];\n clear resolve_ok;\n destruct H as [c_ok [m_ok _]];\n destruct (classes_verified _ _ c_ok) as [c_all_randv c_verified]; simpl in *.\n  destruct c_verified. destruct (H _ _ _ m_ok). eauto.\n  destruct c_all_randv. assumption.\nSave.\nImplicit Arguments instance_special_method_ref_ok [classes preclasses nm c_nm m_nm m_desc idx].\n\nLemma instance_method_ref_ok : forall classes preclasses nm class c_nm m_nm m_desc idx,\n  all_resolvable_and_verified classes preclasses ->\n  R.Classpool.lookup (R.classpool classes) nm = Some class ->\n  V.C.ConstantPool.lookup (V.C.class_constantpool class) idx = Some (V.C.cpe_methodref c_nm m_nm m_desc) ->\n  PreV.VA.ConstantPoolAdditional.lookup (PreV.VA.class_annot_constantpool (V.C.class_annotation class)) idx = Some (PreV.VA.cpae_instance_method) ->\n  exists classes', exists p, exists o, exists c, exists m, exists H,\n    E.R.resolve_method (E.R.C.class_name class) c_nm m_nm m_desc classes preclasses = E.R.load_ok _ (classes':=classes') p o (c,m) H\n    /\\ E.R.C.method_static m = false\n    /\\ all_resolvable_and_verified classes' preclasses.\nintros classes preclasses nm class0 c_nm m_nm m_desc idx all_randv nm_is_class0 cp_lookup cpa_lookup.\nset (all_randv':=all_randv). generalize all_randv'. clear all_randv'. \ndestruct 1 as [classes preclasses classes_ok _].\ndestruct (classes_ok _ _ nm_is_class0) as [class0_randv _].\ndestruct class0_randv as [classes preclasses class0 _ _ ref_ok _ _ _ _].\nchange V.C.cpe_methodref with C.cpe_methodref in cp_lookup.\npose (B:=ref_ok _ _ _ _ cp_lookup cpa_lookup). generalize B. \nchange E.R.C.class_name with C.class_name.\ndestruct 1 as [caller c_nm m_nm m_desc classes preclasses classes' p o c m H code resolve_ok m_not_static m_not_abstract m_code].\nassert (all_randv':all_resolvable_and_verified classes' preclasses). \n eapply preserve_all_resolvable_and_verified; eauto. \nexists classes'. exists p. exists o. exists c. exists m. exists H.  \n intuition;\n destruct all_randv' as [classes' preclasses classes_verified _];\n clear resolve_ok;\n destruct H as [c_ok [m_ok _]];\n destruct (classes_verified _ _ c_ok) as [c_all_randv c_verified]; simpl in *.\nSave.\nImplicit Arguments instance_method_ref_ok [classes preclasses nm c_nm m_nm m_desc idx].\n\nLemma static_field_ref_ok : forall classes preclasses nm class c_nm f_nm f_ty idx,\n  all_resolvable_and_verified classes preclasses ->\n  R.Classpool.lookup (R.classpool classes) nm = Some class ->\n  V.C.ConstantPool.lookup (V.C.class_constantpool class) idx = Some (V.C.cpe_fieldref c_nm f_nm f_ty) ->\n  PreV.VA.ConstantPoolAdditional.lookup (PreV.VA.class_annot_constantpool (V.C.class_annotation class)) idx = Some (PreV.VA.cpae_static_field) ->\n  exists classes', exists p, exists o, exists c, exists f, exists H,\n    E.R.resolve_field (E.R.C.class_name class) c_nm f_nm f_ty classes preclasses = E.R.load_ok _ (classes':=classes') p o (c,f) H\n    /\\ E.R.C.field_static f = true\n    /\\ all_resolvable_and_verified classes' preclasses.\nintros classes preclasses nm class0 c_nm m_nm m_desc idx all_randv nm_is_class0 cp_lookup cpa_lookup.\nset (all_randv':=all_randv). generalize all_randv'. clear all_randv'. \ndestruct 1 as [classes preclasses classes_ok _].\ndestruct (classes_ok _ _ nm_is_class0) as [class0_randv _].\ndestruct class0_randv as [classes preclasses class0 _ _ _ ref_ok _ _ _].\nchange V.C.cpe_fieldref with C.cpe_fieldref in cp_lookup.\npose (B:=ref_ok _ _ _ _ cp_lookup cpa_lookup). generalize B. \nchange E.R.C.class_name with C.class_name.\ndestruct 1 as [caller c_nm m_nm m_desc classes preclasses classes' p o c m H code resolve_ok m_not_static m_not_abstract m_code].\nassert (all_randv':all_resolvable_and_verified classes' preclasses). \n eapply preserve_all_resolvable_and_verified; eauto. \nexists classes'. exists p. exists o. exists c. exists m. exists H.  \n intuition;\n destruct all_randv' as [classes' preclasses classes_verified _];\n clear resolve_ok;\n destruct H as [c_ok [m_ok _]];\n destruct (classes_verified _ _ c_ok) as [c_all_randv c_verified]; simpl in *.\nSave.\nImplicit Arguments static_field_ref_ok [classes preclasses nm c_nm f_nm f_ty idx].\n\nLemma instance_field_ref_ok : forall classes preclasses nm class c_nm f_nm f_ty idx,\n  all_resolvable_and_verified classes preclasses ->\n  R.Classpool.lookup (R.classpool classes) nm = Some class ->\n  V.C.ConstantPool.lookup (V.C.class_constantpool class) idx = Some (V.C.cpe_fieldref c_nm f_nm f_ty) ->\n  PreV.VA.ConstantPoolAdditional.lookup (PreV.VA.class_annot_constantpool (V.C.class_annotation class)) idx = Some (PreV.VA.cpae_instance_field) ->\n  exists classes', exists p, exists o, exists c, exists f, exists H,\n    E.R.resolve_field (E.R.C.class_name class) c_nm f_nm f_ty classes preclasses = E.R.load_ok _ (classes':=classes') p o (c,f) H\n    /\\ E.R.C.field_static f = false\n    /\\ E.R.C.field_final f = false\n    /\\ all_resolvable_and_verified classes' preclasses.\nintros classes preclasses nm class0 c_nm m_nm m_desc idx all_randv nm_is_class0 cp_lookup cpa_lookup.\nset (all_randv':=all_randv). generalize all_randv'. clear all_randv'. \ndestruct 1 as [classes preclasses classes_ok _].\ndestruct (classes_ok _ _ nm_is_class0) as [class0_randv _].\ndestruct class0_randv as [classes preclasses class0 _ _ _ _ _ ref_ok _].\nchange V.C.cpe_fieldref with C.cpe_fieldref in cp_lookup.\npose (B:=ref_ok _ _ _ _ cp_lookup cpa_lookup). generalize B. \nchange E.R.C.class_name with C.class_name.\ndestruct 1 as [caller c_nm m_nm m_desc classes preclasses classes' p o c m H code resolve_ok m_not_static m_not_abstract m_code].\nassert (all_randv':all_resolvable_and_verified classes' preclasses). \n eapply preserve_all_resolvable_and_verified; eauto. \nexists classes'. exists p. exists o. exists c. exists m. exists H.  \n intuition;\n destruct all_randv' as [classes' preclasses classes_verified _];\n clear resolve_ok;\n destruct H as [c_ok [m_ok _]];\n destruct (classes_verified _ _ c_ok) as [c_all_randv c_verified]; simpl in *.\nSave.\nImplicit Arguments instance_field_ref_ok [classes preclasses nm c_nm f_nm f_ty idx].\n\nLemma instantiatable_class_ref_ok : forall classes preclasses nm class c_nm idx,\n  all_resolvable_and_verified classes preclasses ->\n  R.Classpool.lookup (R.classpool classes) nm = Some class ->\n  V.C.ConstantPool.lookup (V.C.class_constantpool class) idx = Some (V.C.cpe_classref c_nm) ->\n  PreV.VA.ConstantPoolAdditional.lookup (PreV.VA.class_annot_constantpool (V.C.class_annotation class)) idx = Some (PreV.VA.cpae_instantiable_class) ->\n  exists classes', exists p, exists o, exists c, exists H,\n    E.R.resolve_class (E.R.C.class_name class) c_nm classes preclasses = E.R.load_ok _ (classes':=classes') p o c H\n    /\\ E.R.C.class_interface c = false\n    /\\ E.R.C.class_abstract c = false\n    /\\ all_resolvable_and_verified classes' preclasses.\nintros classes preclasses nm class0 c_nm idx all_randv nm_is_class0 cp_lookup cpa_lookup.\nset (all_randv':=all_randv). generalize all_randv'. clear all_randv'. \ndestruct 1 as [classes preclasses classes_ok _].\ndestruct (classes_ok _ _ nm_is_class0) as [class0_randv _].\ndestruct class0_randv as [classes preclasses class0 _ _ _ _ ref_ok _ _].\nchange V.C.cpe_classref with C.cpe_classref in cp_lookup.\ndestruct (ref_ok _ _ cp_lookup) as [_ ref_ok']. pose (B:=ref_ok' cpa_lookup). generalize B. \nchange E.R.C.class_name with C.class_name.\ndestruct 1 as [caller c_nm classes preclasses classes' p o c H resolve_ok c_not_interface c_not_abstract].\nassert (all_randv':all_resolvable_and_verified classes' preclasses). \n eapply preserve_all_resolvable_and_verified; eauto. \nexists classes'. exists p. exists o. exists c. exists H.  \n intuition;\n destruct all_randv' as [classes' preclasses classes_verified _];\n clear resolve_ok;\n destruct H as [c_ok [m_ok _]];\n destruct (classes_verified _ _ c_ok) as [c_all_randv c_verified]; simpl in *.\nSave.\nImplicit Arguments instantiatable_class_ref_ok [classes preclasses nm c_nm idx].\n\nLemma class_ref_ok : forall classes preclasses nm class c_nm idx,\n  all_resolvable_and_verified classes preclasses ->\n  R.Classpool.lookup (R.classpool classes) nm = Some class ->\n  V.C.ConstantPool.lookup (V.C.class_constantpool class) idx = Some (V.C.cpe_classref c_nm) ->\n  exists classes', exists p, exists o, exists c, exists H,\n    E.R.resolve_class (E.R.C.class_name class) c_nm classes preclasses = E.R.load_ok _ (classes':=classes') p o c H\n    /\\ all_resolvable_and_verified classes' preclasses.\nintros classes preclasses nm class0 c_nm idx all_randv nm_is_class0_classes cp_lookup.\nset (all_randv':=all_randv). generalize all_randv'. clear all_randv'. intro. \ndestruct all_randv' as [classes preclasses classes_ok _].\ndestruct (classes_ok _ _ nm_is_class0_classes) as [class0_randv _].\ndestruct class0_randv as [classes preclasses class0 _ _ _ _ classref_ok _ _].\nchange V.C.ConstantPool.lookup with C.ConstantPool.lookup in cp_lookup.\nchange V.C.class_constantpool with C.class_constantpool in cp_lookup.\nchange V.C.cpe_classref with C.cpe_classref in cp_lookup.\ndestruct (classref_ok _ _ cp_lookup) as [classref_ok2 _].\nchange E.R.C.class_name with C.class_name.\ndestruct classref_ok2 as [caller c_nm classes preclasses classes' p o c c_nm_is_c resolve_ok]. \nassert (all_randv':all_resolvable_and_verified classes' preclasses). \n eapply preserve_all_resolvable_and_verified; eauto. \nexists classes'. exists p. exists o. exists c. exists c_nm_is_c. intuition.\nSave.\nImplicit Arguments class_ref_ok [classes preclasses nm c_nm idx].\n\nLemma fields_well_typed_update : forall classes heap statics c f t v,\n  fields_well_typed classes heap statics ->\n  rt_ty_sat classes heap v (V.java_type_to_value_assertion t) ->\n  fields_well_typed classes heap (E.FieldStore.update statics (c,f,t) v).\nunfold fields_well_typed. intros.\ndestruct (E.FullFieldDesc.eq_dec (c,f,t) (c_nm, f_nm, ty)).\n inversion e. subst. rewrite E.FieldStore.lookup_update in H1. inversion H1. subst. assumption.\n rewrite E.FieldStore.indep_lookup in H1. apply (H _ _ _ _ H1). assumption. \nSave.\n\nLemma fields_empty_always_well_typed : forall classes heap,\n  fields_well_typed classes heap E.FieldStore.empty.\nunfold fields_well_typed. intros. \nrewrite E.FieldStore.lookup_empty in H. discriminate.\nSave.\n\nHint Resolve preserve_safe_frame_stack preserve_lvar_sat preserve_stack_sat preserve_subclass_assertions_satisfied\n             preserve_fields_well_typed preserve_heap_well_typed R.preserve_subclass preserve_exception_classes\n             R.preserve_old_classes_id.\n\nLemma get_null_pointer_exception : forall classes,\n  exception_classes classes ->\n  exists npe,\n    R.Classpool.lookup (R.classpool classes) E.R.B.java_lang_NullPointerException = Some npe /\\\n    E.R.C.class_interface npe = false /\\\n    E.R.C.class_abstract npe = false /\\\n    R.sub_class classes E.R.B.java_lang_NullPointerException E.R.B.java_lang_Throwable /\\\n    R.sub_class classes E.R.B.java_lang_NullPointerException E.R.B.java_lang_Exception.\nintros. destruct H as [classes npe cce npe1 npe2 npe3 _ _ _ sub1 _ sub3].\nexists npe. intuition. eapply R.sub_class_trans; eauto.\nSave.\n\nLemma get_class_cast_exception : forall classes,\n  exception_classes classes ->\n  exists cce,\n    R.Classpool.lookup (R.classpool classes) E.R.B.java_lang_ClassCastException = Some cce /\\\n    E.R.C.class_interface cce = false /\\\n    E.R.C.class_abstract cce = false /\\\n    R.sub_class classes E.R.B.java_lang_ClassCastException E.R.B.java_lang_Throwable /\\\n    R.sub_class classes E.R.B.java_lang_ClassCastException E.R.B.java_lang_Exception.\nintros. destruct H as [classes npe cce _ _ _ cce1 cce2 cce3 _ sub2 sub3].\nexists cce. intuition. eapply R.sub_class_trans; eauto.\nSave.\n\nLemma object_creation_props : forall heap t heap' a classes c,\n  R.Classpool.lookup (R.classpool classes) t = Some c ->\n  C.class_interface c = false ->\n  C.class_abstract c = false ->\n  E.ObjectHeap.new heap (E.hp_object t E.FieldStore.empty) = (heap', a) ->\n  heap_well_typed classes heap ->\n     preserve_heap_types heap heap'\n  /\\ rt_ty_sat classes heap' (E.rt_addr (Some a)) (C.A.va_addr t)\n  /\\ heap_well_typed classes heap'\n  /\\ E.ObjectHeap.lookup heap' a = Some (E.hp_object t E.FieldStore.empty).\nintros. unfold E.ObjectHeap.new in H2.\ndestruct heap. inversion H2. clear H2. \nassert (preserve_heap_types (E.ObjectHeap.mkHeap max_addr actual_heap max_unallocated) heap').\n subst. unfold preserve_heap_types. unfold E.ObjectHeap.lookup. simpl. intros.\n destruct (E.ObjectHeap.Key.eq_dec a a0).\n  subst. rewrite (max_unallocated a0) in H2.\n   discriminate.\n   omega.\n  rewrite E.ObjectHeap.S.indep_lookup. \n   exists fields. assumption.\n   assumption.\nsubst. split.\n assumption.\n split.\n  eapply ty_sat_addr2. \n   unfold E.ObjectHeap.lookup. simpl. apply E.ObjectHeap.S.lookup_update.\n   apply R.sub_class_refl.\n  split.\n   unfold heap_well_typed in *. unfold E.ObjectHeap.lookup in *. simpl in *. intros. \n   destruct (E.ObjectHeap.Key.eq_dec a a0). \n    subst. rewrite E.ObjectHeap.S.lookup_update in H4. inversion H4. subst. split.\n     exists c. auto.\n     apply fields_empty_always_well_typed.\n    rewrite E.ObjectHeap.S.indep_lookup in H4. destruct (H3 _ _ _ H4). eauto.\n     assumption.       \n   unfold E.ObjectHeap.lookup. simpl. apply E.ObjectHeap.S.lookup_update.\nSave.\nImplicit Arguments object_creation_props [heap heap' a].\n\nLemma heap_update_props : forall heap x ty f1 f2 nm fields a classes,\n  E.ObjectHeap.lookup heap a = Some (E.hp_object nm fields) ->\n  heap_well_typed classes heap ->\n  rt_ty_sat classes heap x (V.java_type_to_value_assertion ty) ->\n    exists heap', E.ObjectHeap.update heap a (E.hp_object nm (E.FieldStore.update fields (f1,f2,ty) x)) = Some heap'\n                  /\\ heap_well_typed classes heap'\n                  /\\ preserve_heap_types heap heap'.\nintros. unfold E.ObjectHeap.update. destruct heap.\ndestruct (E.ObjectHeap.lookup_informative_Prop actual_heap a).\n match goal with |- ex (fun _ => Some ?v = Some _ /\\ heap_well_typed _ _ /\\ preserve_heap_types ?h _) => exists v; assert (preserve_heap_types h v) end. \n  unfold preserve_heap_types. unfold E.ObjectHeap.lookup in *. simpl in *. intros. \n  destruct (E.ObjectHeap.Key.eq_dec a a0).\n   subst. rewrite E.ObjectHeap.S.lookup_update. rewrite H2 in H. inversion H. \n    exists (E.FieldStore.update fields (f1, f2, ty) x). reflexivity.\n   rewrite E.ObjectHeap.S.indep_lookup. \n    exists fields0. assumption.\n    assumption.\n split. \n  reflexivity.\n  split. \n   unfold heap_well_typed. unfold E.ObjectHeap.lookup. simpl. intros. \n   destruct (E.ObjectHeap.Key.eq_dec a a0).\n    subst. rewrite E.ObjectHeap.S.lookup_update in H3. inversion H3. subst. \n    destruct (H0 _ _ _ H). split.\n     assumption.\n     eapply fields_well_typed_update; eauto. eapply preserve_rt_ty_sat; eauto.\n    rewrite E.ObjectHeap.S.indep_lookup in H3. \n     destruct (H0 _ _ _ H3). split.\n      assumption.\n      eapply preserve_fields_well_typed; eauto.\n     assumption.\n   assumption.\n unfold E.ObjectHeap.lookup in H. simpl in H. rewrite e in H. discriminate.\nSave.\nImplicit Arguments heap_update_props [heap x ty f1 f2 nm fields a].\n\nLemma sub_class_exists : forall classes Anm Bnm Bc,\n  R.Classpool.lookup (R.classpool classes) Bnm = Some Bc ->\n  R.sub_class classes Anm Bnm ->\n  exists Ac, R.Classpool.lookup (R.classpool classes) Anm = Some Ac.\nintros. inversion H0.\n subst. exists Bc. assumption.\n exists c. assumption.\nSave.\n\nLemma sub_class_has_super_class : forall classes Anm Bnm Ac,\n  R.Classpool.lookup (R.classpool classes) Anm = Some Ac ->\n  R.sub_class classes Anm Bnm ->\n  Anm = Bnm \\/ exists nm, C.class_super_class Ac = Some nm /\\ R.sub_class classes nm Bnm.\nintros classes Anm Bnm Ac A_exists A_isa_B. inversion A_isa_B. \n left. reflexivity.\n right. rewrite A_exists in H. inversion H. subst. exists s_nm. split; assumption.\nSave.\n\nLemma all_randv_implies_instance_method_verified : forall classes preclasses B_nm Bc d Bm,\n  R.Classpool.lookup (R.classpool classes) B_nm = Some Bc ->\n  C.MethodList.lookup (C.class_methods Bc) d = Some Bm ->\n  C.method_static Bm = false ->\n  all_resolvable_and_verified classes preclasses ->\n  V.instance_method_verified Bc Bm (snd d).\nintros classes preclasses B_nm Bc d Bm B_exists Bm_exists Bm_not_static all_randv.\ndestruct all_randv as [classes preclasses all_r_and_v _].\ndestruct (all_r_and_v _ _ B_exists) as [_ B_verified].\ndestruct B_verified as [Bc B_verified]. destruct d as [m_nm m_d]. destruct (B_verified _ _ _ Bm_exists) as [_ Bm_verified]. \nauto. \nSave.\n\nLemma lookup_virtual_method_aux_props : forall classes oA_nm scc preclasses B_nm Bc d Bm A_nm,\n  R.Classpool.lookup (R.classpool classes) B_nm = Some Bc ->\n  C.MethodList.lookup (C.class_methods Bc) d = Some Bm ->\n  C.method_static Bm = false ->\n  oA_nm = Some A_nm ->\n  R.sub_class classes A_nm B_nm ->\n  all_resolvable_and_verified classes preclasses ->\n   exists Cc, exists Cm,\n   E.lookup_virtual_method_aux classes oA_nm d scc = inl _ (Cc, Cm)\n   /\\ R.Classpool.lookup (R.classpool classes) (C.class_name Cc) = Some Cc\n   /\\ C.method_static Cm = false\n   /\\ C.MethodList.lookup (C.class_methods Cc) d = Some Cm\n   /\\ R.sub_class classes A_nm (C.class_name Cc)\n   /\\ V.instance_method_verified Cc Cm (snd d).\nintros classes oA_nm scc. elim scc using R.super_class_chain_ind2.\n\nintros preclasses B_nm Bc d Bm A_nm B_exists Bm_exists Bm_not_static contr.\ndiscriminate.\n\nintros nm Ac A_exists s IH. \nintros preclasses B_nm Bc d Bm A_nm B_exists Bm_exists Bm_not_static nm_eq A_isa_B all_r_and_v.\nsimpl. \ninversion nm_eq. subst. clear nm_eq.\ndestruct (sub_class_has_super_class classes A_nm B_nm Ac A_exists A_isa_B) as [AB_eq | [Ac_super [Ac_super_eq Ac_super_isa_B]]].\n (* This class is actually B *)\n change (R.Classpool.lookup (R.classpool classes)) with (E.R.Classpool.lookup (E.R.classpool classes)) in B_exists.\n subst. destruct (E.R.Classpool.lookup_informative (E.R.classpool classes) B_nm) as [[Bc' B_exists'] | noB].\n  (* B exists, as we knew already *)\n  rewrite B_exists' in B_exists. inversion B_exists. subst. clear B_exists.\n  change (C.MethodList.lookup (C.class_methods Bc)) with (E.R.C.MethodList.lookup (E.R.C.class_methods Bc)) in Bm_exists.\n  rewrite Bm_exists. \n  change (E.R.C.method_static) with (C.method_static).\n  rewrite Bm_not_static. \n  exists Bc. exists Bm. intuition.\n   eapply R.cert_classpool_names. apply B_exists'.\n   change C.class_name with R.C.class_name. rewrite (R.cert_classpool_names_2 B_exists'). constructor.\n   eapply all_randv_implies_instance_method_verified; eauto.\n  (* B doesn't exist! this is unpossible *)\n  rewrite noB in B_exists. discriminate.\n (* This class must have a super class *)\n change R.Classpool.lookup with E.R.Classpool.lookup in A_exists.\n change R.classpool with E.R.classpool in A_exists.\n destruct (E.R.Classpool.lookup_informative (E.R.classpool classes) A_nm) as [[Ac' A_exists'] | noA].\n  (* The class exists, as we knew it would *)\n  rewrite A_exists' in A_exists. inversion A_exists. subst. clear A_exists.\n  destruct (option_dec (E.R.C.MethodList.lookup (E.R.C.class_methods Ac) d)) as [[Am Am_exists] | noAm].\n   (* Method was found *)\n   rewrite Am_exists. destruct (bool_dec (E.R.C.method_static Am)) as [Am_static | Am_not_static].\n    (* but is static *)\n    rewrite Am_static. \n    destruct (IH Ac (eq_ind_r (fun nm => E.R.Classpool.lookup (E.R.classpool classes) nm = Some Ac) A_exists' (refl_equal A_nm)) preclasses B_nm Bc d Bm Ac_super)\n          as [Cc [Cm [lookup_succeeds [Cc_exists [Cm_not_static [Cm_exists [Ac_super_isa_C Cm_verified]]]]]]]; auto.\n    exists Cc. exists Cm. intuition.\n     eapply E.R.sub_class_step; eauto.\n    (* is not static *)\n    rewrite Am_not_static.\n    exists Ac. exists Am. intuition.\n     eapply E.R.cert_classpool_names. apply A_exists'.\n     change C.class_name with R.C.class_name. rewrite (R.cert_classpool_names_2 A_exists'). constructor.\n     eapply all_randv_implies_instance_method_verified; eauto.\n   (* Method was not found *)\n   rewrite noAm. \n   destruct (IH Ac (eq_ind_r (fun nm => E.R.Classpool.lookup (E.R.classpool classes) nm = Some Ac) A_exists' (refl_equal A_nm)) preclasses B_nm Bc d Bm Ac_super)\n          as [Cc [Cm [lookup_succeeds [Cc_exists [Cm_not_static [Cm_exists [Ac_super_isa_C Cm_verified]]]]]]]; auto.\n    exists Cc. exists Cm. intuition.\n     eapply R.sub_class_step; eauto.\n  (* The class does not exists: unpossible *)\n  elimtype False. rewrite noA in A_exists. discriminate. \nSave.   \n\nLemma lookup_virtual_method_props : forall classes preclasses B_nm Bc d Bm A_nm Ac,\n  R.Classpool.lookup (R.classpool classes) B_nm = Some Bc ->\n  C.MethodList.lookup (C.class_methods Bc) d = Some Bm ->\n  C.method_static Bm = false ->\n  R.sub_class classes A_nm B_nm ->\n  R.Classpool.lookup (R.classpool classes) A_nm = Some Ac ->\n  C.class_interface Ac = false ->\n  C.class_abstract Ac = false ->\n  all_resolvable_and_verified classes preclasses ->\n   exists Cc:E.R.C.class, exists Cm:E.R.C.method,\n   E.lookup_virtual_method classes A_nm d = Some (inl _ (Cc,Cm))\n   /\\ R.Classpool.lookup (R.classpool classes) (C.class_name Cc) = Some Cc \n   /\\ C.MethodList.lookup (C.class_methods Cc) d = Some Cm\n   /\\ R.sub_class classes A_nm (C.class_name Cc)\n   /\\ V.instance_method_verified Cc Cm (snd d). \nintros classes preclasses B_nm Bc d Bm A_nm Ac B_exists Bm_exists Bm_not_static A_isa_B A_exists A_not_interface A_not_abstract all_r_and_v. \nunfold E.lookup_virtual_method.\ndestruct (sub_class_has_super_class classes A_nm B_nm Ac A_exists A_isa_B) as [AB_eq | [Ac_super [Ac_super_eq Ac_super_isa_B]]].\n (* A is the same as B *)\n subst. rewrite B_exists in A_exists. inversion A_exists. subst. clear A_exists.\n change R.Classpool.lookup with E.R.Classpool.lookup in B_exists.\n change R.classpool with E.R.classpool in B_exists.\n destruct (E.R.Classpool.lookup_informative (E.R.classpool classes) B_nm) as [[Bc' B_exists'] | no_B].\n  (* B exists, as we knew it would *)\n  rewrite B_exists' in B_exists. inversion B_exists. subst. clear B_exists.\n  destruct (bool_informative (E.R.C.class_interface Ac)) as [Ac_interface | Ac_not_interface'].\n   (* Turns out that B was an interface. But this impossible! *)\n   change E.R.C.class_interface with C.class_interface in Ac_interface. rewrite Ac_interface in A_not_interface. discriminate.\n   (* B is a class *)\n   change C.MethodList.lookup with E.R.C.MethodList.lookup in Bm_exists.\n   change C.class_methods with E.R.C.class_methods in Bm_exists.\n   rewrite Bm_exists. change E.R.C.method_static with C.method_static. rewrite Bm_not_static. \n   exists Ac. exists Bm. intuition.\n     eapply R.cert_classpool_names. apply B_exists'.\n     change C.class_name with R.C.class_name. rewrite (R.cert_classpool_names_2 B_exists'). constructor.\n     eapply all_randv_implies_instance_method_verified; eauto.\n  (* No B, but this is not possible *)\n  rewrite no_B in B_exists. discriminate.\n (* A has a super class *)\n change R.Classpool.lookup with E.R.Classpool.lookup in A_exists.\n change R.classpool with E.R.classpool in A_exists.\n destruct (E.R.Classpool.lookup_informative (E.R.classpool classes) A_nm) as [[Ac' A_exists'] | Anm_not_exists].\n  (* The class is there, which we knew already *)\n  rewrite A_exists' in A_exists. inversion A_exists. subst Ac'. clear A_exists.\n  destruct (bool_informative (E.R.C.class_interface Ac)) as [A_interface | A_not_interface' ].\n   (* It is an interface, which is impossible *)\n   change E.R.C.class_interface with C.class_interface in A_interface. rewrite A_interface in A_not_interface. discriminate.\n   (* It is not an interface *)\n   set (scc:=(E.R.cert_classpool_gives_scc A_exists' A_not_interface')).\n   generalize scc. clear scc. intro.\n   destruct (lookup_virtual_method_aux_props classes (C.class_super_class Ac) scc preclasses B_nm Bc d Bm Ac_super)\n         as [Cc [Cm [lookup_succeeds [Cc_exists [Cm_not_static [Cm_exists [Ac_super_isa_C Cm_verified]]]]]]]; auto.\n   destruct (option_dec (E.R.C.MethodList.lookup (E.R.C.class_methods Ac) d)) as [[Am Am_exists] | no_Am].\n    (* Method was actually found in this class *)\n    rewrite Am_exists. destruct (bool_dec (E.R.C.method_static Am)) as [Am_static | Am_not_static].\n     (* but it was static *)\n     rewrite Am_static. \n     exists Cc. exists Cm. intuition.\n      change E.R.C.class_super_class with C.class_super_class. rewrite lookup_succeeds. reflexivity.\n      eapply R.sub_class_step; eauto.\n     (* not static *)\n     rewrite Am_not_static. exists Ac. exists Am. intuition.\n      eapply R.cert_classpool_names. apply A_exists'.\n      change C.class_name with R.C.class_name. rewrite (R.cert_classpool_names_2 A_exists'). constructor.\n      eapply all_randv_implies_instance_method_verified; eauto.\n    (* Method not there *)\n    rewrite no_Am. \n    exists Cc. exists Cm. intuition.\n     change E.R.C.class_super_class with C.class_super_class. rewrite lookup_succeeds. reflexivity.\n     eapply R.sub_class_step; eauto.\n  (* Class not found: impossible *)\n  rewrite Anm_not_exists in A_exists. discriminate.\nSave.\n\nLemma well_typed_heap_has_class : forall classes heap a nm fields,\n  heap_well_typed classes heap ->\n  E.ObjectHeap.lookup heap a = Some (E.hp_object nm fields) ->\n  exists c, R.Classpool.lookup (R.classpool classes) nm = Some c /\\ C.class_interface c = false /\\ C.class_abstract c = false.\nintros classes heap a nm fields good_heap obj_exists. \ndestruct (good_heap _ _ _ obj_exists) as [[c [c_exists [c_not_interface c_not_abstract]]] _].\nexists c. auto.\nSave.\n\nDefinition lift_prop_2 := fun (A B:Set) (p:A -> B -> Prop) (a:option A) (b:option B) =>\n  match a,b with\n  | Some a, Some b => p a b\n  | None,   None   => True\n  | _,_            => False\n  end.\nImplicit Arguments lift_prop_2 [A B].\n\nLtac normal_continue MS CS :=\n  left; match goal with [_:E.cont ?st = _|- _ ] => exists st end;\n  split; [try assumption\n         |eapply mk_safe_state;\n          [eapply mk_safe_current_frame;\n           [ eauto (* class exists *)\n           | apply MS\n           | apply CS\n           | eauto (* lvars ok *)\n           | eauto (* stack ok *)\n           | eauto (* subclasses ok *) ]\n          |eauto (* frame stack *)\n          |eauto (* all resovable and verified *)\n          |eauto (* static fields well typed *)\n          |eauto (* heap well typed *)\n          |eauto (* exceptions exist *)]].\n\nLemma unwind_stack_ok : forall preclasses classes heap fs current_ty final_ty static_fields addr res c c_exists,\n  safe_frame_stack classes heap fs current_ty final_ty ->\n  all_resolvable_and_verified classes preclasses ->\n  fields_well_typed classes heap static_fields ->\n  heap_well_typed classes heap ->\n  exception_classes classes ->\n  rt_ty_sat classes heap (E.rt_addr (Some addr)) (C.A.va_addr (C.class_name c)) ->\n  R.sub_class classes (C.class_name c) B.java_lang_Throwable ->\n  R.sub_class classes (C.class_name c) B.java_lang_Exception -> \n  match E.unwind_stack classes fs addr c c_exists with\n  | Some nil =>\n     E.stop_exn (E.mkState nil classes heap static_fields) addr\n  | Some fs =>\n     E.cont (E.mkState fs classes heap static_fields)\n  | None => E.wrong\n  end = res ->\n  (exists s', E.cont s' = res /\\ safe_state preclasses s' final_ty) \\/\n  (exists s', exists v, E.stop s' v = res /\\\n                        lift_prop_2 (rt_ty_sat (E.state_classes s') (E.state_object_heap s')) v\n                                    (option_map V.java_type_to_value_assertion final_ty)) \\/\n  (exists s', exists e, exists cnm, exists fields, E.stop_exn s' e = res /\\ E.ObjectHeap.lookup (E.state_object_heap s') e = Some (E.hp_object cnm fields) /\\ R.sub_class (E.state_classes s') cnm B.java_lang_Exception).\nintros preclasses classes heap fs current_ty final_ty static_fields addr res c c_exists.\nintros fs_safe all_randv statics_good heap_good exc_good addr_ok c_isa_throwable c_isa_exception E.\ngeneralize current_ty fs_safe E. clear current_ty fs_safe E. induction fs; intros.\n (* empty frame stack *)\n simpl in *.\n inversion addr_ok. subst. right. right. \n exists (E.mkState nil classes heap static_fields). exists addr. exists nm'. exists fields.\n intuition. eapply R.sub_class_trans; eauto. \n (* frame stack contains stuff *)\n simpl in E. destruct a as [op_stack lvars pc code class].\n change E.R.C.code_exception_table with C.code_exception_table in E.\n inversion fs_safe;\n  (* frame stack for returning something *)\n  subst op_stack0 lvars0 pc0 code0 class0 fs0 current_ty final_ty0;\n  (destruct (check_exception_handlers_prop _ heap _ _ _ _ _ _ c_exists _ _ H13 c_isa_exception H14 (refl_equal _))\n        as [[pc' [l' [s' [search_handlers_ok [cert_lookup_ok [lvar_imp stack_will_be_ok]]]]]] | search_handlers_ok];\n   [(* handler found *)\n    rewrite <- search_handlers_ok in E;\n    assert (lvars_ok:lvar_sat classes heap lvars l');\n    [eapply lvar_assertion_implication_sound; eauto\n    |normal_continue H7 cert_lookup_ok]\n   (* handler not found *)\n   |rewrite <- search_handlers_ok in E;\n    eapply IHfs; eauto]).\nSave.\n\nLemma stack_type_is_cat2_ok1 : forall classes heap v s,\n  rt_ty_sat classes heap v (V.stack_type_to_value_assertion s) ->\n  V.stack_type_is_cat2 s = true ->\n  E.val_category v = C.category2.\nintros. destruct s; inversion H; try discriminate; reflexivity.\nSave.\n\nLemma stack_type_is_cat2_ok2 : forall classes heap v s,\n  rt_ty_sat classes heap v (V.stack_type_to_value_assertion s) ->\n  V.stack_type_is_cat2 s = false ->\n  E.val_category v = C.category1.\nintros. destruct s; inversion H; try discriminate; reflexivity.\nSave.\n\nHint Resolve stack_type_is_cat2_ok1 stack_type_is_cat2_ok2.\n\nLtac throw_built_in E exc_nm get_exc preclasses classes heap preserve_classes exceptions_exist exc_check_ok subclass_satisfied' code_is_safe :=\n  destruct (pair_dec (E.ObjectHeap.new heap (E.hp_object exc_nm E.FieldStore.empty)))\n        as [heap' [addr new_result]];\n  rewrite new_result in E;\n  destruct (get_exc _ (preserve_exception_classes _ _ exceptions_exist preserve_classes))\n        as [exc [exc_exists [exc_not_interface [exc_not_abstract [exc_isa_throwable exc_isa_exception]]]]];\n  destruct (object_creation_props exc_nm classes exc exc_exists exc_not_interface exc_not_abstract new_result) as [preserve_heap_ty [alloced_ok [heap'_good heap'_lookup_ok]]]; eauto;\n  rewrite heap'_lookup_ok in E;\n  destruct (E.R.Classpool.lookup_informative (E.R.classpool classes) exc_nm) as [[c c_exists] | not_exists];\n  [rewrite <- (E.R.cert_classpool_names_2 c_exists) in exc_isa_throwable;\n   rewrite <- (E.R.cert_classpool_names_2 c_exists) in exc_isa_exception;\n   rewrite <- (E.R.cert_classpool_names_2 c_exists) in alloced_ok;\n   destruct (check_exception_handlers_prop _ heap' _ _ _ _ _ _ (E.R.cert_classpool_names c_exists) _ _ subclass_satisfied' exc_isa_exception exc_check_ok (refl_equal _))\n         as [[pc' [l'' [s' [search_handlers_ok [cert_lookup_ok [lvar_imp stack_will_be_ok]]]]]] | search_handlers_ok];\n   change V.C.code_exception_table with E.R.C.code_exception_table in search_handlers_ok;\n   [(* The handler was here, no unwinding necessary *)\n    rewrite <- search_handlers_ok in E; normal_continue code_is_safe cert_lookup_ok;\n    eapply lvar_assertion_implication_sound;\n     [apply subclass_satisfied'\n     |eapply V.lvar_assertion_implication_trans; [idtac | apply lvar_imp ]\n     |eapply preserve_lvar_sat; eauto]\n   |(* Have to unwind the stack *)\n    rewrite <- search_handlers_ok in E; eapply (unwind_stack_ok preclasses classes heap'); eauto; set (B:=1)]\n  |change (E.R.Classpool.lookup (E.R.classpool classes)) with (R.Classpool.lookup (R.classpool classes)) in not_exists;\n   rewrite not_exists in exc_exists; discriminate].\n\nLemma exec_safe : forall s rt res preclasses, safe_state preclasses s rt -> E.exec preclasses s = res ->\n   (exists s', E.cont s' = res /\\ safe_state preclasses s' rt) \\/\n   (exists s', exists v, E.stop s' v = res /\\ lift_prop_2 (rt_ty_sat (E.state_classes s') (E.state_object_heap s')) v (option_map V.java_type_to_value_assertion rt)) \\/\n   (exists s', exists e, exists cnm, exists fields,\n       E.stop_exn s' e = res /\\\n       E.ObjectHeap.lookup (E.state_object_heap s') e = Some (E.hp_object cnm fields) /\\\n       R.sub_class (E.state_classes s') cnm B.java_lang_Exception).\nintros s rt res preclasses safety E.\n\ndestruct safety as [f fs classes preclasses heap current_ty final_ty static_fields\n                    f_safe frame_stack_is_safe refs_good statics_good heap_good exceptions_exist].\ndestruct f_safe as [cert op_stack lvars pc class current_ty lvar_assertion stack_assertion code\n                    class_exists code_is_safe cert_lookup_ok lvars_ok stack_ok subclassing_satisfied\n                    no_exception_handlers].\ninversion code_is_safe as [cert' cert_not_too_big instructions_safe]. subst cert'.\ndestruct (nth_error_ok _ (C.code_code code) _ (cert_not_too_big _ _ cert_lookup_ok)) as [opcode op_exists].\npose (B:=instructions_safe _ _ op_exists). generalize B. clear B. intro. \ndestruct B as [cert pc op s1 s2 l1 l2 cert_lookup_ok' wp_code lvar_imp stack_imp]. \nchange PreV.VA.Cert.lookup with C.A.Cert.lookup in cert_lookup_ok'.\nrewrite cert_lookup_ok' in cert_lookup_ok. inversion cert_lookup_ok. subst lvar_assertion stack_assertion.\npose (good_lvars:=lvar_assertion_implication_sound _ _ _ subclassing_satisfied _ _ _ lvar_imp lvars_ok).\npose (good_stack:=stack_assertion_implication_sound _ _ _ subclassing_satisfied _ _ _ stack_imp stack_ok).\ngeneralize good_lvars good_stack. \nclear cert_lookup_ok cert_lookup_ok' good_lvars good_stack lvar_imp stack_imp stack_ok lvars_ok l1 s1\n      cert_not_too_big instructions_safe.\nintros.\n\nsimpl in E. \n(*change C.code_code with E.C.code_code in op_exists.\nrewrite op_exists in E.*)\nchange V.C.opcode with E.C.opcode in op.\nreplace (nth_error (E.C.code_code code) pc) with (Some op) in E.\ndestruct op; try discriminate; simpl in * |- *.\n\n(* op_iarithb *)\ndestruct i; try discriminate;\ndestruct_opt (PreV.VA.Cert.lookup cert (S pc)) H wp_code; simpl in wp_code; destruct x;\ndestruct_opt (V.unpush class PreV.VA.va_int (l,s)) H0 wp_code; simpl in wp_code; destruct x;\ndestruct_opt (V.unpop PreV.VA.va_int (l0,s0)) H1 wp_code; destruct x;\ndestruct (sem_unpop good_stack wp_code); subst l2; destruct H3; destruct H2; destruct H2; destruct H3;\ndestruct (sem_unpop H4 H1); subst l1; destruct H6; destruct H5; destruct H5; destruct H6; subst x0;\ndestruct (sem_unpush subclassing_satisfied H7 H0); subst l;\ndestruct x; inversion H2; destruct x1; inversion H5; subst i i0;\n\nrewrite H3 in E;\nmatch goal with\n[_:E.cont (E.mkState (E.mkFrame (E.rt_int ?v::_) _ _ _ _ :: _) _ _ _) = _ |- _] =>\n  pose (H8 (E.rt_int v) (ty_sat_int classes heap v)) end;\nnormal_continue code_is_safe H.\n\n(* op_iarithu *)\ndestruct_opt (PreV.VA.Cert.lookup cert (S pc)) H wp_code; simpl in wp_code; destruct x.\ndestruct_opt (V.unpush class PreV.VA.va_int (l,s)) H0 wp_code; destruct x.\ndestruct (sem_unpop good_stack wp_code); destruct H2; destruct H2; destruct H2; destruct H3. subst l2.\ndestruct (sem_unpush subclassing_satisfied H4 H0). subst l. \ndestruct x; inversion H2. subst i0. \n\nrewrite H3 in E. destruct i. \nmatch goal with [_:E.cont (E.mkState (E.mkFrame (E.rt_int ?v::_) _ _ _ _ :: _) _ _ _) = _ |- _] => pose (H5 (E.rt_int v) (ty_sat_int classes heap v)) end;\nnormal_continue code_is_safe H. \n\n(* op_iinc *)\ndestruct_opt (PreV.VA.Cert.lookup cert (S pc)) H wp_code. simpl in wp_code.\ndestruct_opt (V.unstore class n x false) H0 wp_code. simpl in wp_code.\ndestruct x0. \ndestruct (PreV.VA.value_assertion_eq_dec v PreV.VA.va_int); try discriminate.\nsubst v. simpl in wp_code. \nassert (not_top:PreV.VA.va_int <> PreV.VA.va_top). unfold not. intro. discriminate.\ndestruct a. destruct x.\ndestruct (sem_unretrieve subclassing_satisfied not_top good_lvars wp_code) as [tmp_eq [v [v_ok [lookup_ok l_ok]]]]. subst s2. \ndestruct (sem_unstore l_ok H0) as [tmp_eq v_will_be_ok]. subst s0. \n\nrewrite lookup_ok in E. inversion v_ok. subst v. \ndestruct (v_will_be_ok (E.rt_int (B.Int32.add i t))) as [lv' [update_ok lv'_ok]].\n constructor. \n intros. discriminate.\n intros. reflexivity.\nchange B.Int32.add with E.B.Int32.add in update_ok.\nrewrite update_ok in E. normal_continue code_is_safe H.\n\n(* op_dup *)\ndestruct (option_dec (PreV.VA.Cert.lookup cert (S pc))) as [[a cert_ok]|IsNone]; [rewrite cert_ok in wp_code| rewrite IsNone in wp_code; discriminate].\nsimpl in wp_code.\ndestruct (option_dec (V.unpush_2 a)) as [[x1 unpush_ok1]|IsNone]; [rewrite unpush_ok1 in wp_code | rewrite IsNone in wp_code; discriminate ].\nsimpl in wp_code. destruct x1 as [v1 a1].\ndestruct (option_dec (V.unpush_2 a1)) as [[x2 unpush_ok2]|IsNone]; [rewrite unpush_ok2 in wp_code | rewrite IsNone in wp_code; discriminate ].\nsimpl in wp_code. destruct x2 as [v2 a2].\ndestruct (option_dec (V.value_assertion_merge class v1 v2)) as [[v merge_ok]|IsNone]; [rewrite merge_ok in wp_code | rewrite IsNone in wp_code; discriminate ].\nsimpl in wp_code. \nmatch goal with _:(if ?x then _ else _) = _ |- _ => change x with (V.value_assertion_implication_dec class v PreV.VA.va_cat1) in wp_code end.\ndestruct (bool_dec (V.value_assertion_implication_dec class v PreV.VA.va_cat1)) as [is_cat1|isnt_cat1]; [rewrite is_cat1 in wp_code|rewrite isnt_cat1 in wp_code; discriminate].\ndestruct a1 as [l0 s0]. destruct a2 as [l1 s1].\ndestruct a as [l s].\n\ndestruct (sem_unpop good_stack wp_code) as [lvar_eq [v0 [s' [v0_v_sat [op_stack_eq s'_good]]]]].\nsubst l2. \ndestruct (sem_known_unpush s'_good unpush_ok2) as [lvar_eq pre_v0_s'_ok]. subst l1. \nassert (v0_s'_good:stack_sat classes heap (v0::s') s0).\n apply pre_v0_s'_ok. eapply value_assertion_implication_sound; eauto.\n  eapply V.value_assertion_merge_p2. apply merge_ok. \ndestruct (sem_known_unpush v0_s'_good unpush_ok1) as [lvar_eq pre_v0_v0_s'_good]. subst l0.\nassert (v0_v0_s'_good:stack_sat classes heap (v0::v0::s') s).\n apply pre_v0_v0_s'_good. eapply value_assertion_implication_sound; eauto.\n  eapply V.value_assertion_merge_p1. apply merge_ok. \n\nrewrite op_stack_eq in E.\nrewrite (va_category1 classes heap) in E.\nnormal_continue code_is_safe cert_ok.\n eapply value_assertion_implication_sound; eauto; apply V.value_assertion_implication_dec_sound; assumption.\n\n(* op_nop *)\nnormal_continue code_is_safe wp_code.\n\n(* op_pop *)\ndestruct_opt (PreV.VA.Cert.lookup cert (S pc)) H wp_code. simpl in wp_code. destruct x.\ndestruct (sem_unpop good_stack wp_code). subst l2. destruct H1. destruct H0. destruct H0. destruct H1. \nrewrite H1 in E. rewrite (va_category1 _ _ _ H0) in E. \nnormal_continue code_is_safe H. \n\n(* op_load *)\ndestruct_opt (PreV.VA.Cert.lookup cert (S pc)) H wp_code. simpl in wp_code. destruct x. \ndestruct_opt (V.unpush_2 (l,s0)) H0 wp_code. destruct x. simpl in wp_code.\ndestruct_bool (V.value_assertion_implication_dec class v (V.stack_type_to_value_assertion s)) H1 wp_code. simpl in wp_code.\ndestruct a.\ndestruct (sem_unretrieve subclassing_satisfied (va_not_top class v s H1) good_lvars wp_code) as [tmp_eq [ v0 [v0_ok [lookup_ok l0_ok]]]]. subst s2.\ndestruct (sem_known_unpush good_stack H0) as [tmp_eq stack_will_be_ok]. \nsubst l0. pose (stack_will_be_ok _ v0_ok).\n\nrewrite lookup_ok in E. normal_continue code_is_safe H.\n\n(* op_store *)\ndestruct_opt (PreV.VA.Cert.lookup cert (S pc)) H wp_code. simpl in wp_code. destruct x.\ndestruct_opt (V.unstore class n (l, s0) (V.stack_type_is_cat2 s)) H0 wp_code. destruct x. simpl in wp_code.\ndestruct_opt (V.value_assertion_merge class (V.stack_type_to_value_assertion s) v) H1 wp_code. simpl in wp_code.\ndestruct a.\ndestruct (sem_unpop good_stack wp_code) as [tmp_eq [v0 [s' [v0_ok [op_stack_form s'_ok]]]]]. subst l2.\ndestruct (sem_unstore good_lvars H0) as [tmp_eq v0_will_be_ok]. subst s1.\nassert (v0_ok2:rt_ty_sat classes heap v0 v). \n eapply value_assertion_implication_sound. \n  apply subclassing_satisfied.\n  eapply V.value_assertion_merge_p2. apply H1.\n  apply v0_ok.\nassert (v0_ok3:rt_ty_sat classes heap v0 (V.stack_type_to_value_assertion s)). \n eapply value_assertion_implication_sound. \n  apply subclassing_satisfied.\n  eapply V.value_assertion_merge_p1. apply H1.\n  apply v0_ok.\ndestruct (v0_will_be_ok v0 v0_ok2) as [lv' [update_ok lv'_ok]]; eauto.\n\nrewrite op_stack_form in E. rewrite update_ok in E. normal_continue code_is_safe H.\n\n(* op_instanceof *)\ndestruct_opt (PreV.VA.Cert.lookup cert (S pc)) H wp_code. simpl in wp_code.\ndestruct_opt (V.C.ConstantPool.lookup (V.C.class_constantpool class) t) H0 wp_code.\ndestruct x0; try discriminate.\nsimpl in wp_code.\ndestruct_opt (V.unpush class PreV.VA.va_int x) H1 wp_code. simpl in wp_code. \ndestruct x. destruct x0.\n\ndestruct (sem_unpop good_stack wp_code) as [tmp_eq [v [s' [v_ok [op_stack_form s'_ok]]]]]. subst l2.\ndestruct (sem_unpush subclassing_satisfied s'_ok H1) as [tmp_eq stk_will_be_ok]. subst l0.\ndestruct (class_ref_ok _ refs_good class_exists H0) as [classes' [p [o [c [c_exists [resolve_c refs_good']]]]]].\npose (one_ok:=preserve_stack_sat _ _ _ _ _ _ (stk_will_be_ok _ (ty_sat_int classes heap B.Int32.one)) p (preserve_heap_types_id heap)).\npose (zero_ok:=preserve_stack_sat _ _ _ _ _ _ (stk_will_be_ok _ (ty_sat_int classes heap B.Int32.zero)) p (preserve_heap_types_id heap)).\nrewrite op_stack_form in E. \nchange V.C.ConstantPool.lookup with E.R.C.ConstantPool.lookup in H0.\nchange V.C.class_constantpool with E.R.C.class_constantpool in H0.\nchange V.C.cpe_classref with C.cpe_classref in H0.\nrewrite H0 in E. \nrewrite resolve_c in E. \ninversion v_ok. \n (* Reference exists *)\n subst v. rewrite H2 in E.\n destruct (heap_good a nm fields H2) as [[c' [c'_exists _]] _].\n pose (c'_exists2:=p _ _ c'_exists).\n destruct (E.R.Classpool.lookup_informative (E.R.classpool classes') nm). \n  destruct s1. destruct (E.R.check_subclass (E.R.cert_classpool_names e) (E.R.C.class_name c));\n   normal_continue code_is_safe H.\n  rewrite c'_exists2 in e. discriminate.\n (* Reference is null *)\n subst v. normal_continue code_is_safe H.\n\n(* op_invokespecial *)\ndestruct_opt (PreV.VA.Cert.lookup cert (S pc)) H wp_code; simpl in wp_code.\ndestruct (option_dec (V.check_exception_handlers code class cert pc (V.C.code_exception_table code))) as [[exc_l exc_check_ok] | exc_check_fail]; [rewrite exc_check_ok in wp_code|rewrite exc_check_fail in wp_code; discriminate].\nsimpl in wp_code.\ndestruct_opt (V.C.ConstantPool.lookup (V.C.class_constantpool class) t) H0 wp_code; \ndestruct x0; try discriminate; simpl in wp_code;\ndestruct_opt (PreV.VA.ConstantPoolAdditional.lookup (PreV.VA.class_annot_constantpool (V.C.class_annotation class)) t) H1 wp_code;\ndestruct x0; try discriminate; simpl in wp_code.\n\ndestruct_opt (V.C.descriptor_ret_type d) H2 wp_code; destruct x as [l s];\n [destruct_opt (V.unpush class (V.java_type_to_value_assertion x0) (l,s)) H3 wp_code;\n    simpl in wp_code; destruct x; rename H3 into unpush_1; rename x0 into ret_ty\n |simpl in wp_code; rename l into l0];\n(destruct (option_dec (V.lvar_assertion_merge class l0 exc_l)) as [[l' merge_ok] | merge_fail]; [rewrite merge_ok in wp_code; simpl in wp_code|rewrite merge_fail in wp_code;discriminate]);\ninversion wp_code; subst s2 l2; clear wp_code;\ndestruct (sem_pop_n good_stack); destruct H3; destruct H3; destruct H4;\ninversion H5; subst x0 t2 a; clear H5;\n[destruct (sem_unpush_2 subclassing_satisfied H10 unpush_1); rename H6 into ret_val_ok; subst l | idtac];\nrewrite rev_length in H3; rewrite map_length in H3;\n\ndestruct (instance_special_method_ref_ok _ refs_good class_exists H0 H1);\ndestruct H5; destruct H5; destruct H5; destruct H5; destruct H5; destruct H5; destruct H5; destruct H6; destruct H7; destruct H8; destruct H11; destruct H12;\ndestruct H11;\nchange V.C.method_code with E.R.C.method_code in H14;\nrewrite H6 in H14; inversion H14; subst x6;\nchange V.C.ConstantPool.lookup with E.R.C.ConstantPool.lookup in H0;\nchange V.C.class_constantpool with E.R.C.class_constantpool in H0;\nchange V.C.cpe_methodref with E.R.C.cpe_methodref in H0; rewrite H0 in E;\nrewrite H5 in E;\ngeneralize E; clear E; dependent inversion x5; intros;\n[replace (E.pop_n (length (E.R.C.descriptor_arg_types md)) op_stack) with (Some (x, v::s1)) in E\n|replace (E.pop_n (length (E.R.C.descriptor_arg_types md)) op_stack) with (Some (x, v::s0)) in E];\n\n(assert (subclass_satisfied':subclass_assertions_satisfied x0 class);\n[eauto\n|change PreV.VA.va_addr with C.A.va_addr in H9;\n (inversion H9;\n  (* The reference was null *)\n  [subst v x3;\n   throw_built_in E E.R.B.java_lang_NullPointerException get_null_pointer_exception preclasses x0 heap x1 exceptions_exist exc_check_ok subclass_satisfied' code_is_safe;\n   eapply V.lvar_assertion_merge_p2; apply merge_ok\n  (* The reference was not null *)\n  |subst t0 v;\n  rewrite H7 in E; rewrite H8 in E; rewrite H6 in E;\n  assert (stk_ok:stack_sat_exact x0 heap (E.rt_addr (Some a0)::(rev x)) (map V.java_type_to_value_assertion (V.C.ty_ref (V.C.class_name class0)::V.C.descriptor_arg_types md)));\n  [simpl; apply stk_sat_exact_cons;\n   [destruct a; simpl in H23; eapply ty_sat_addr2; \n    [apply H21 \n    |eapply R.sub_class_trans;\n     [eapply R.preserve_subclass; eauto\n     |eauto]]\n   |eapply preserve_stack_sat_exact;\n     [apply stack_sat_exact_rev_2; apply H4\n     |assumption\n     |apply preserve_heap_types_id]]\n  |destruct (sem_argument_prep subclass_satisfied' H17 stk_ok) as [new_l TMP];\n   destruct TMP as [stack_to_lvars_ok new_l_ok];\n   match goal with _:match ?v with Some _ => _ | None => _ end = _ |- _ =>\n     change v with (E.stack_to_lvars (E.rt_addr (Some a0)::rev x) (V.C.code_max_lvars code0)) in E end;\n   rewrite stack_to_lvars_ok in E;\n   left; match goal with [_:E.cont ?st = _ |- _ ] => exists st end;\n   split;\n   [assumption\n   |eapply mk_safe_state;\n    [eapply mk_safe_current_frame;\n     [assumption\n     |apply H15\n     |apply H16\n     |eapply lvar_assertion_implication_sound; [apply H13 | apply H18 | apply new_l_ok ]\n     |eapply stack_assertion_implication_sound; [apply H13 | apply H19 | constructor ]\n     |assumption]\n    |idtac\n    |assumption\n    |eauto|eauto|eauto]]]])]).\n\nrewrite H2. eapply safe_stack_cons; simpl; eauto. \n eapply lvar_assertion_implication_sound. \n  eauto.\n  eapply V.lvar_assertion_merge_p1; eauto. eapply preserve_lvar_sat; eauto. \n intros. apply ret_val_ok.\n  eapply R.preserve_old_classes_trans; eauto.\n  eapply preserve_heap_types_trans; eauto.\n  assumption.\n eapply lvar_assertion_implication_sound. \n  eauto.\n  eapply V.lvar_assertion_merge_p2; eauto. eapply preserve_lvar_sat; eauto. \n\nrewrite H2. eapply safe_stack_cons_void; eauto.\n eapply lvar_assertion_implication_sound. \n  eauto.\n  eapply V.lvar_assertion_merge_p1; eauto. eapply preserve_lvar_sat; eauto. \n eapply lvar_assertion_implication_sound. \n  eauto.\n  eapply V.lvar_assertion_merge_p2; eauto. eapply preserve_lvar_sat; eauto. \n\n(* op_invokestatic *)\ndestruct_opt (PreV.VA.Cert.lookup cert (S pc)) H wp_code; simpl in wp_code. \ndestruct (option_dec (V.check_exception_handlers code class cert pc (V.C.code_exception_table code))) as [[exc_l exc_check_ok] | exc_check_fail]; [rewrite exc_check_ok in wp_code|rewrite exc_check_fail in wp_code; discriminate].\nsimpl in wp_code.\ndestruct_opt (V.C.ConstantPool.lookup (V.C.class_constantpool class) t) H0 wp_code; \ndestruct x0; try discriminate; simpl in wp_code;\ndestruct_opt (PreV.VA.ConstantPoolAdditional.lookup (PreV.VA.class_annot_constantpool (V.C.class_annotation class)) t) H1 wp_code;\ndestruct x0; try discriminate; simpl in wp_code.\n\ndestruct_opt (V.C.descriptor_ret_type d) H2 wp_code; destruct x as [l s];\n[destruct_opt (V.unpush class (V.java_type_to_value_assertion x0) (l,s)) H3 wp_code;\n    simpl in wp_code; destruct x; rename H3 into unpush_1; rename x0 into ret_ty\n|simpl in wp_code; rename l into l0];\n(destruct (option_dec (V.lvar_assertion_merge class l0 exc_l)) as [[l' merge_ok] | merge_fail]; [rewrite merge_ok in wp_code; simpl in wp_code|rewrite merge_fail in wp_code;discriminate]);\ninversion wp_code; subst s2 l2; clear wp_code;\ndestruct (sem_pop_n good_stack); destruct H3; destruct H3; destruct H4;\n[destruct (sem_unpush_2 subclassing_satisfied H5 unpush_1); rename H7 into ret_val_ok; subst l | idtac];\nrewrite rev_length in H3; rewrite map_length in H3;\n\ndestruct (static_method_ref_ok _ refs_good class_exists H0 H1);\ndestruct H6; destruct H6; destruct H6; destruct H6; destruct H6; destruct H6; destruct H6; destruct H7; destruct H8; destruct H9; destruct H10;\ndestruct H9;\nchange V.C.method_code with E.R.C.method_code in H9;\nrewrite H7 in H9; inversion H9; subst x7;\ndestruct (sem_argument_prep (s:=rev x) subclassing_satisfied H14 (stack_sat_exact_rev_2 _ _ _ _ H4));\ndestruct H17;\nchange V.C.ConstantPool.lookup with E.R.C.ConstantPool.lookup in H0;\nchange V.C.class_constantpool with E.R.C.class_constantpool in H0;\nchange V.C.cpe_methodref with E.R.C.cpe_methodref in H0;\nrewrite H0 in E;\nreplace (E.pop_n (length (E.R.C.descriptor_arg_types md)) op_stack) with (Some (x, x0)) in E;\nrewrite H6 in E;\ngeneralize E; clear E; dependent inversion x6; intros; \nrewrite H8 in E; rewrite H7 in E;\nchange E.R.C.code_max_lvars with V.C.code_max_lvars in E;\nrewrite H17 in E;\n\n(normal_continue H12 H13;\n [eapply lvar_assertion_implication_sound; eauto; eapply preserve_lvar_sat; eauto\n |eapply stack_assertion_implication_sound; eauto; constructor\n |idtac]).\n\nrewrite H2; eapply safe_stack_cons; simpl; eauto. \n eapply lvar_assertion_implication_sound. \n  eapply preserve_subclass_assertions_satisfied. apply subclassing_satisfied. assumption.\n  eapply V.lvar_assertion_merge_p1; eauto. eapply preserve_lvar_sat; eauto. \n intros. apply ret_val_ok.\n  eapply R.preserve_old_classes_trans; eauto.\n  eapply preserve_heap_types_trans; eauto.\n  assumption.\n eapply lvar_assertion_implication_sound. \n  eapply preserve_subclass_assertions_satisfied. apply subclassing_satisfied. assumption.\n  eapply V.lvar_assertion_merge_p2; eauto. eapply preserve_lvar_sat; eauto. \n\nrewrite H2; eapply safe_stack_cons_void; simpl; eauto. \n eapply lvar_assertion_implication_sound. \n  eapply preserve_subclass_assertions_satisfied. apply subclassing_satisfied. assumption.\n  eapply V.lvar_assertion_merge_p1; eauto. eapply preserve_lvar_sat; eauto. \n eapply lvar_assertion_implication_sound. \n  eapply preserve_subclass_assertions_satisfied. apply subclassing_satisfied. assumption.\n  eapply V.lvar_assertion_merge_p2; eauto. eapply preserve_lvar_sat; eauto. \n\n(* op_invokevirtual *)\n(*destruct_opt (PreV.VA.Cert.lookup cert (S pc)) H wp_code; simpl in wp_code.\ndestruct (option_dec (V.check_exception_handlers code class cert pc (V.C.code_exception_table code))) as [[exc_l exc_check_ok] | exc_check_fail]; [rewrite exc_check_ok in wp_code|rewrite exc_check_fail in wp_code; discriminate].\nsimpl in wp_code.\ndestruct_opt (V.C.ConstantPool.lookup (V.C.class_constantpool class) t) H0 wp_code; \ndestruct x0; try discriminate; simpl in wp_code;\ndestruct_opt (PreV.VA.ConstantPoolAdditional.lookup (PreV.VA.class_annot_constantpool (V.C.class_annotation class)) t) H1 wp_code;\ndestruct x0; try discriminate; simpl in wp_code.\n\ndestruct_opt (V.C.descriptor_ret_type d) H2 wp_code; destruct x as [l s];\n [destruct_opt (V.unpush class (V.java_type_to_value_assertion x0) (l,s)) H3 wp_code;\n    simpl in wp_code; destruct x; rename H3 into unpush_1; rename x0 into ret_ty\n |simpl in wp_code; rename l into l0];\n(destruct (option_dec (V.lvar_assertion_merge class l0 exc_l)) as [[l' merge_ok] | merge_fail]; [rewrite merge_ok in wp_code; simpl in wp_code|rewrite merge_fail in wp_code;discriminate]);\ninversion wp_code; subst s2 l2; clear wp_code;\ndestruct (sem_pop_n good_stack); destruct H3; destruct H3; destruct H4;\ninversion H5; subst x0 t2 a; clear H5;\n[destruct (sem_unpush_2 subclassing_satisfied H10 unpush_1); rename H6 into ret_val_ok; subst l | idtac];\nrewrite rev_length in H3; rewrite map_length in H3;\ndestruct (instance_method_ref_ok _ refs_good class_exists H0 H1)\n      as [classes' [p_classes_classes' [o_classes_classes' [cl [m [Hresolve [resolve_succeeds [m_static all_resolvable_classes']]]]]]]];\nchange V.C.ConstantPool.lookup with E.R.C.ConstantPool.lookup in H0;\nchange V.C.class_constantpool with E.R.C.class_constantpool in H0;\nchange V.C.cpe_methodref with E.R.C.cpe_methodref in H0;\nrewrite H0 in E; rewrite resolve_succeeds in E.\n(*generalize E; clear E; dependent inversion Hresolve as [cl_exists [m_exists t0_sc_cl]]; intro;*)\nrewrite m_static in E;\n[ replace (E.pop_n (length (E.R.C.descriptor_arg_types d)) op_stack) with (Some (x, v::s1)) in E\n(*| replace (E.pop_n (length (E.R.C.descriptor_arg_types d)) op_stack) with (Some (x, v::s0)) in E*)\n];\nchange PreV.VA.va_addr with C.A.va_addr in H9;\n\n(assert (subclass_satisfied_in_classes':subclass_assertions_satisfied classes' class);\n[eauto\n| inversion H9;\n  (* The reference was null *)\n [subst v x0;\n  generalize E; clear E; dependent inversion Hresolve as [cl_exists [m_exists t0_sc_cl]]; intro;\n  throw_built_in E E.R.B.java_lang_NullPointerException get_null_pointer_exception preclasses classes' heap p_classes_classes' exceptions_exist exc_check_ok subclass_satisfied_in_classes' code_is_safe;\n  eapply V.lvar_assertion_merge_p2; apply merge_ok\n  (* The reference was not null *)\n |subst v t0;\n  rewrite H6 in E; idtac ]]).\n  destruct (well_typed_heap_has_class _ _ _ _ _ heap_good H6) as [nm'_c [nm'_exists [nm'_not_interface nm'_not_abstract]]].\n  destruct (lookup_virtual_method_props classes' preclasses (V.C.class_name cl) cl (t1, d) m nm' nm'_c)\n        as [real_c [real_m [lookup_succeeded [real_c_exists [real_m_exists [nm'_isa_real_c real_m_verified]]]]]].\n   clear E resolve_succeeds. destruct Hresolve as [cl_exists [m_exists t0_sc_cl]]. apply cl_exists.\n   clear E resolve_succeeds. destruct Hresolve as [cl_exists [m_exists t0_sc_cl]]. apply m_exists.\n   apply m_static.\n   clear E resolve_succeeds. destruct Hresolve as [cl_exists [m_exists t0_sc_cl]]. eapply R.sub_class_trans; [eapply R.preserve_subclass; [apply H8|assumption]|assumption].\n   apply (p_classes_classes' _ _ nm'_exists).\n   apply nm'_not_interface.\n   apply nm'_not_abstract.\n   apply all_resolvable_classes'.\n  change V.C.B.Methodname.t with E.B.Methodname.t in t1.\n  change V.C.descriptor with E.R.C.descriptor in d.\n  replace (E.lookup_virtual_method classes' nm' (t1,d)) with (Some (inl E.R.exn (pair real_c real_m))) in E.\nrewrite lookup_succeeded in E.\n\n\n  clear resolve_succeeds Hresolve;\n  ; idtac ]]).\n  (*assert (R.sub_class classes' nm' (V.C.class_name cl)).*)\n  destruct (lookup_virtual_method_props classes' preclasses (V.C.class_name cl) cl (t1, d) m nm' nm'_c)\n        as [real_c [real_m [lookup_succeeded [real_c_exists [real_m_exists [nm'_isa_real_c real_m_verified]]]]]].\n  replace (E.lookup_virtual_method classes' nm' (t1,d)) with (Some (inl E.R.exn (real_c, real_m))) in E.\n  set (B:=E.lookup_virtual_method classes' nm' (t1,d)) in *.\n\nCheck E.\n\n\n  match goal with [ _:(match ?x with Some _ => ?a | None => ?b end = res) |- _ ] => idtac end.\n    replace x with (Some (inl E.R.exn (real_c, real_m))) in E end.\n\nrewrite lookup_succeeded in E.\n  simpl in real_m_verified;\n  destruct real_m_verified\n        as [real_m real_c md real_m_cert real_m_l real_m_s real_m_code real_m_l'\n            real_m_not_abstract real_m_has_code real_m_safe real_m_cert_lookup real_m_args real_m_lvar_imp real_m_stk_imp].\n   change V.C.method with E.R.C.method in real_m.\n   change V.C.class with E.R.C.class in real_c.\n   change V.C.descriptor with E.C.descriptor in md.\n   change V.C.B.Methodname.t with E.B.Methodname.t in t1.\n   replace (E.lookup_virtual_method classes' nm' (t1,md)) with (Some (inl E.R.exn (real_c : E.R.C.class, real_m : E.R.C.method))) in E.\n   rewrite lookup_succeeded in E.\n  \nrewrite lookup_succeeded in E.\n\n\n   idtac]]]).\n   change V.C.method with E.R.C.method in real_m.\n   change V.C.class with E.R.C.class in real_c.\n   change V.C.descriptor with E.C.descriptor in md.\n   change V.C.B.Methodname.t with E.B.Methodname.t in t1.\n   replace (E.lookup_virtual_method classes' nm' (t1,md)) with (Some (inl E.R.exn (real_c : E.R.C.class, real_m : E.R.C.method))) in E.\n   rewrite lookup_succeeded in E.\n   rewrite real_m_not_abstract in E;\n   rewrite real_m_has_code in E;\n   assert (stk_ok:stack_sat_exact classes' heap (E.rt_addr (Some a)::(rev x)) (map V.java_type_to_value_assertion (V.C.ty_ref (V.C.class_name real_c)::V.C.descriptor_arg_types md)));\n   [simpl; apply stk_sat_exact_cons;\n    [eapply ty_sat_addr2; [ apply H6 | assumption ]\n    |eapply preserve_stack_sat_exact;\n      [apply stack_sat_exact_rev_2; apply H4\n      |assumption\n      |apply preserve_heap_types_id]]\n   |assert (subclass_satisfied':subclass_assertions_satisfied classes' real_c);\n    [destruct all_resolvable_classes' as [classes' preclasses all_randv _];\n     destruct (all_randv _ _ real_c_exists) as [real_c_randv _];\n     destruct real_c_randv as [classes' preclasses real_c _ _ _ _ _ _ ss];\n     assumption\n    |destruct (sem_argument_prep subclass_satisfied' real_m_args stk_ok) as [new_l [stack_to_lvars_ok new_l_ok]];\n     match goal with _:match ?v with Some _ => _ | None => _ end = _ |- _ =>\n       change v with (E.stack_to_lvars (E.rt_addr (Some a)::rev x) (E.R.C.code_max_lvars real_m_code)) in E end;\n     rewrite stack_to_lvars_ok in E;\n     normal_continue real_m_safe real_m_cert_lookup;\n     [eapply lvar_assertion_implication_sound; [eapply preserve_subclass_assertions_satisfied; eauto | apply real_m_lvar_imp | apply new_l_ok ]\n     |eapply stack_assertion_implication_sound; [eapply preserve_subclass_assertions_satisfied; eauto | apply real_m_stk_imp | constructor ]\n     |idtac]]]]]]).\n\nrewrite H2. eapply safe_stack_cons; simpl; eauto. \n eapply lvar_assertion_implication_sound. \n  eapply preserve_subclass_assertions_satisfied. apply subclassing_satisfied. assumption.\n  eapply V.lvar_assertion_merge_p1; eauto. eapply preserve_lvar_sat; eauto. \n intros. apply ret_val_ok.\n  eapply V.E.R.preserve_old_classes_trans; eauto.\n  eapply preserve_heap_types_trans; eauto.\n  assumption.\n eapply lvar_assertion_implication_sound. \n  eapply preserve_subclass_assertions_satisfied. apply subclassing_satisfied. assumption.\n  eapply V.lvar_assertion_merge_p2; eauto. eapply preserve_lvar_sat; eauto. \n\nrewrite H2. eapply safe_stack_cons_void; eauto.\n eapply lvar_assertion_implication_sound. \n  eapply preserve_subclass_assertions_satisfied. apply subclassing_satisfied. assumption.\n  eapply V.lvar_assertion_merge_p1; eauto. eapply preserve_lvar_sat; eauto. \n eapply lvar_assertion_implication_sound. \n  eapply preserve_subclass_assertions_satisfied. apply subclassing_satisfied. assumption.\n  eapply V.lvar_assertion_merge_p2; eauto. eapply preserve_lvar_sat; eauto. *)\n\n(* op_aconst_null *)\ndestruct_opt (PreV.VA.Cert.lookup cert (S pc)) H wp_code. destruct x. \ndestruct (sem_unpush subclassing_satisfied good_stack wp_code). subst l2.\npose (H1 (E.rt_addr None) (ty_sat_null _ _)). \nnormal_continue code_is_safe H.\n\n(* op_checkcast *)\ndestruct_opt (PreV.VA.Cert.lookup cert (S pc)) H wp_code.\ndestruct (option_dec (V.check_exception_handlers code class cert pc (V.C.code_exception_table code))) as [[exc_l exc_check_ok] | exc_check_fail]; [rewrite exc_check_ok in wp_code|rewrite exc_check_fail in wp_code; discriminate].\nsimpl in wp_code.\ndestruct_opt (V.C.ConstantPool.lookup (V.C.class_constantpool class) t) H0 wp_code; simpl in wp_code.\ndestruct x0; try discriminate.\ndestruct_opt (V.unpush class (PreV.VA.va_addr t0) x) H1 wp_code. simpl in wp_code.\ndestruct x0. destruct x.\ndestruct_opt (V.unpop PreV.VA.va_ref (l, s)) H2 wp_code. destruct x as [l1 s1]. simpl in wp_code.\ndestruct_opt (V.lvar_assertion_merge class l1 exc_l) H3 wp_code. \ninversion wp_code. subst x s1. clear wp_code.\n\ndestruct (sem_unpop good_stack H2) as [tmp_eq [v [s' [v_ok [op_stack_form s'_ok]]]]]. subst l1.\ndestruct (sem_unpush_2 subclassing_satisfied s'_ok H1) as [tmp_eq stack_will_be_ok]. subst l0.\ndestruct (class_ref_ok _ refs_good class_exists H0) as [classes' [p [o [c [c_exists [resolve_c refs_good']]]]]].\n\nrewrite op_stack_form in E. \nchange V.C.ConstantPool.lookup with E.R.C.ConstantPool.lookup in H0.\nchange V.C.class_constantpool with E.R.C.class_constantpool in H0.\nchange V.C.cpe_classref with E.R.C.cpe_classref in H0.\nrewrite H0 in E. rewrite resolve_c in E. \ninversion v_ok. \n (* Reference was not null *)\n subst v. rewrite H4 in E. \n destruct (heap_good a nm fields H4) as [[c' [c'_exists _]] _].\n pose (c'_exists':=p _ _ c'_exists).\n destruct (E.R.Classpool.lookup_informative (E.R.classpool classes') nm) as [[c'2 c'_exists'2] | c'_not_exists ]. \n  destruct_bool (E.R.check_subclass (E.R.cert_classpool_names c'_exists'2) (E.R.C.class_name c)) H5 E.\n   (* assignability check passed *)\n   rewrite (E.R.cert_classpool_names_2 c_exists) in H5.\n   normal_continue code_is_safe H.\n    eapply lvar_assertion_implication_sound. eauto.\n     eapply V.lvar_assertion_merge_p1. apply H3. eapply preserve_lvar_sat; eauto. \n    apply stack_will_be_ok; auto. eapply ty_sat_addr2. \n     apply H4.\n     rewrite <- (E.R.cert_classpool_names_2 c'_exists'2). \n     apply (E.R.check_subclass_sound _ _ t0 (E.R.cert_classpool_names c'_exists'2)). apply H5. \n   (* assignability check failed: throw ClassCastException *)\n   clear c c_exists resolve_c H5.\n   clear s' s'_ok stack_will_be_ok op_stack_form.\n   throw_built_in E E.R.B.java_lang_ClassCastException get_class_cast_exception preclasses classes' heap p exceptions_exist exc_check_ok (preserve_subclass_assertions_satisfied _ _ _ subclassing_satisfied p) code_is_safe.\n   eapply V.lvar_assertion_merge_p2; apply H3.\n  rewrite c'_exists' in c'_not_exists. discriminate.\n (* Reference was null *)\n subst v. assert (stack_ok:stack_sat classes' heap (E.rt_addr None::s') s0).\n  apply stack_will_be_ok; auto. eapply ty_sat_addr1.\n normal_continue code_is_safe H; eauto.\n  eapply lvar_assertion_implication_sound. eauto.\n   eapply V.lvar_assertion_merge_p1. apply H3. eapply preserve_lvar_sat; eauto. \n \n(* op_getfield *)\ndestruct_opt (PreV.VA.Cert.lookup cert (S pc)) H wp_code.\ndestruct (option_dec (V.check_exception_handlers code class cert pc (V.C.code_exception_table code))) as [[exc_l exc_check_ok] | exc_check_fail]; [rewrite exc_check_ok in wp_code|rewrite exc_check_fail in wp_code; discriminate].\nsimpl in wp_code.\ndestruct_opt (V.C.ConstantPool.lookup (V.C.class_constantpool class) t) H0 wp_code; simpl in wp_code;\ndestruct x0; try discriminate;\ndestruct_opt (PreV.VA.ConstantPoolAdditional.lookup (PreV.VA.class_annot_constantpool (V.C.class_annotation class)) t) H1 wp_code;\ndestruct x0; try discriminate; simpl in wp_code.\ndestruct_opt (V.unpush class (V.java_type_to_value_assertion j) x) H2 wp_code. simpl in wp_code.\ndestruct x0. destruct x.\ndestruct_opt (V.unpop (PreV.VA.va_addr t0) (l, s)) H3 wp_code. destruct x as [l1 s1]. simpl in wp_code.\ndestruct_opt (V.lvar_assertion_merge class l1 exc_l) H4 wp_code. \ninversion wp_code. subst x s1. clear wp_code.\n\ndestruct (sem_unpop good_stack H3) as [tmp_eq [v [s' [v_ok [op_stack_form s'_ok]]]]]. subst l1.\ndestruct (sem_unpush subclassing_satisfied s'_ok H2)as [tmp_eq stack_will_be_ok]. subst l0.\ndestruct (instance_field_ref_ok _ refs_good class_exists H0 H1)\n      as [classes' [p [o [class2 [f [resolve_H [resolve_ok [f_not_static [f_not_final all_randv]]]]]]]]].\n\nrewrite op_stack_form in E. \nchange V.C.ConstantPool.lookup with E.R.C.ConstantPool.lookup in H0.\nchange V.C.class_constantpool with E.R.C.class_constantpool in H0.\nchange V.C.cpe_fieldref with E.R.C.cpe_fieldref in H0.\nrewrite H0 in E. rewrite resolve_ok in E. \ngeneralize E. clear E. dependent inversion resolve_H as [c2_exists f_exists]. intro.\nrewrite f_not_static in E.\nchange PreV.VA.va_addr with C.A.va_addr in v_ok.\ninversion v_ok. \n (* reference is null *)\n subst x v. \n clear s' s'_ok stack_will_be_ok op_stack_form. \n throw_built_in E E.R.B.java_lang_NullPointerException get_null_pointer_exception preclasses classes' heap p exceptions_exist exc_check_ok (preserve_subclass_assertions_satisfied _ _ _ subclassing_satisfied p) code_is_safe.\n eapply V.lvar_assertion_merge_p2; apply H4.\n (* reference is non null *)\n subst v t0. rewrite H6 in E.\n change V.C.java_type with E.R.C.java_type in j.\n destruct_opt (E.FieldStore.lookup fields (E.R.C.class_name class2, E.R.C.field_name f, j)) H5 E.\n  destruct (heap_good _ _ _ H6). pose (H9 _ _ _ _ H5). normal_continue code_is_safe H; eauto.\n   eapply lvar_assertion_implication_sound. eauto.\n   eapply V.lvar_assertion_merge_p1. apply H4. eapply preserve_lvar_sat; eauto. \n  pose (stack_will_be_ok _ (default_value_sat _ _ j)). normal_continue code_is_safe H; eauto.\n   eapply lvar_assertion_implication_sound. eauto.\n    eapply V.lvar_assertion_merge_p1. apply H4. eapply preserve_lvar_sat; eauto. \n\n(* op_getstatic *)\ndestruct_opt (PreV.VA.Cert.lookup cert (S pc)) H wp_code.\ndestruct_opt (V.C.ConstantPool.lookup (V.C.class_constantpool class) t) H0 wp_code; simpl in wp_code;\ndestruct x0; try discriminate;\ndestruct_opt (PreV.VA.ConstantPoolAdditional.lookup (PreV.VA.class_annot_constantpool (V.C.class_annotation class)) t) H1 wp_code;\ndestruct x0; try discriminate; simpl in wp_code.\n\ndestruct (static_field_ref_ok _ refs_good class_exists H0 H1).\ndestruct H2. destruct H2. destruct H2. destruct H2. destruct H2. destruct H2. destruct H3.\ndestruct x.\ndestruct (sem_unpush subclassing_satisfied good_stack wp_code). subst l2.\n\nchange V.C.ConstantPool.lookup with E.R.C.ConstantPool.lookup in H0.\nchange V.C.class_constantpool with E.R.C.class_constantpool in H0.\nchange V.C.cpe_fieldref with E.R.C.cpe_fieldref in H0.\nrewrite H0 in E. rewrite H2 in E. \ngeneralize E. clear E. dependent inversion x5. intro.\nrewrite H3 in E. \nchange V.C.java_type with E.R.C.java_type in j.\ndestruct_opt (E.FieldStore.lookup static_fields (E.R.C.class_name x3, E.R.C.field_name x4, j)) H5 E.\n pose (H6 _ (statics_good _ _ _ _ H5)). normal_continue code_is_safe H; eauto.\n pose (H6 _ (default_value_sat _ _ j)). normal_continue code_is_safe H; eauto.\n\n(* op_new *)\ndestruct_opt (PreV.VA.Cert.lookup cert (S pc)) H wp_code.\ndestruct_opt (V.C.ConstantPool.lookup (V.C.class_constantpool class) t) H0 wp_code; simpl in wp_code;\ndestruct x0; try discriminate;\ndestruct_opt (PreV.VA.ConstantPoolAdditional.lookup (PreV.VA.class_annot_constantpool (V.C.class_annotation class)) t) H1 wp_code;\ndestruct x0; try discriminate; simpl in wp_code.\n\ndestruct (instantiatable_class_ref_ok _ refs_good class_exists H0 H1).\ndestruct H2. destruct H2. destruct H2. destruct H2. destruct H2. destruct H3. destruct H4. \ndestruct x.\ndestruct (sem_unpush_2 subclassing_satisfied good_stack wp_code). subst l2.\n\nchange V.C.ConstantPool.lookup with E.R.C.ConstantPool.lookup in H0. \nchange V.C.class_constantpool with E.R.C.class_constantpool in H0.\nchange V.C.cpe_classref with E.R.C.cpe_classref in H0.\nrewrite H0 in E. rewrite H2 in E. rewrite H4 in E. rewrite H3 in E. \ndestruct (pair_dec (E.ObjectHeap.new heap (E.hp_object t0 E.FieldStore.empty))) as [heap' [addr new_eq]].\nrewrite new_eq in E. \ndestruct (object_creation_props t0 x0 _ x4 H3 H4 new_eq) as [p_heap [a_ok [heap'_ok a_exists]]]. eauto. \nnormal_continue code_is_safe H; eauto.\n\n(* op_putfield *)\ndestruct_opt (PreV.VA.Cert.lookup cert (S pc)) H wp_code.\ndestruct (option_dec (V.check_exception_handlers code class cert pc (V.C.code_exception_table code))) as [[exc_l exc_check_ok] | exc_check_fail]; [rewrite exc_check_ok in wp_code|rewrite exc_check_fail in wp_code; discriminate].\nsimpl in wp_code.\ndestruct_opt (V.C.ConstantPool.lookup (V.C.class_constantpool class) t) H0 wp_code; simpl in wp_code;\ndestruct x0; try discriminate;\ndestruct_opt (PreV.VA.ConstantPoolAdditional.lookup (PreV.VA.class_annot_constantpool (V.C.class_annotation class)) t) H1 wp_code;\ndestruct x0; try discriminate; simpl in wp_code.\ndestruct_opt (V.unpop (PreV.VA.va_addr t0) x) H2 wp_code. simpl in wp_code.\ndestruct x. destruct x0.\ndestruct_opt (V.unpop (V.java_type_to_value_assertion j) (l0, s0)) H3 wp_code. destruct x as [l1 s1].\nsimpl in wp_code.\ndestruct_opt (V.lvar_assertion_merge class l1 exc_l) H4 wp_code. \ninversion wp_code. subst x s1. clear wp_code.\n\ndestruct (sem_unpop good_stack H3) as [tmp_eq [v [s' [v_ok [op_stack_form s'_ok]]]]]. subst l1.\ndestruct (sem_unpop s'_ok H2) as [tmp_eq [v' [s'0 [v'_ok [s'_form s'0_ok]]]]]. subst l0.  \ndestruct (instance_field_ref_ok _ refs_good class_exists H0 H1)\n      as [classes' [p [o [class2 [f [resolve_H [resolve_ok [f_not_static [f_not_final all_randv]]]]]]]]].\n\nrewrite op_stack_form in E. rewrite s'_form in E. \nchange V.C.ConstantPool.lookup with E.R.C.ConstantPool.lookup in H0.\nchange V.C.class_constantpool with E.R.C.class_constantpool in H0.\nchange V.C.cpe_fieldref with E.R.C.cpe_fieldref in H0.\nrewrite H0 in E. rewrite resolve_ok in E.\ngeneralize E. clear E. dependent inversion resolve_H as [class2_exists f_exists]. intro.\nrewrite f_not_static in E. rewrite f_not_final in E. simpl in E.\nchange PreV.VA.va_addr with C.A.va_addr in v'_ok.\ninversion v'_ok. \n (* reference is null *)\n subst v' x. \n clear s' s'_ok op_stack_form s'_form.\n throw_built_in E E.R.B.java_lang_NullPointerException get_null_pointer_exception preclasses classes' heap p exceptions_exist exc_check_ok (preserve_subclass_assertions_satisfied _ _ _ subclassing_satisfied p) code_is_safe.\n eapply V.lvar_assertion_merge_p2; apply H4.\n (* reference is non null *)\n subst v' t0. rewrite H6 in E. \n destruct (heap_update_props (x:=v) (ty:=j) (f1:=(E.R.C.class_name class2)) (f2:=(E.R.C.field_name f)) classes' H6)\n       as [heap' [update_ok [heap'_ok preserve_heap]]]; eauto.\n  eapply preserve_rt_ty_sat; eauto.\n change V.C.java_type with E.R.C.java_type in j.\n replace (E.ObjectHeap.update heap a (E.hp_object nm' (E.FieldStore.update fields (E.R.C.class_name class2, E.R.C.field_name f, j) v)))\n    with (Some heap') in E.\n normal_continue code_is_safe H; eauto.\n  eapply lvar_assertion_implication_sound. eauto.\n   eapply V.lvar_assertion_merge_p1. apply H4. eapply preserve_lvar_sat; eauto. \n\n(* op_putstatic *)\ndestruct_opt (PreV.VA.Cert.lookup cert (S pc)) H wp_code.\ndestruct_opt (V.C.ConstantPool.lookup (V.C.class_constantpool class) t) H0 wp_code; simpl in wp_code;\ndestruct x0; try discriminate;\ndestruct_opt (PreV.VA.ConstantPoolAdditional.lookup (PreV.VA.class_annot_constantpool (V.C.class_annotation class)) t) H1 wp_code;\ndestruct x0; try discriminate; simpl in wp_code.\ndestruct (static_field_ref_ok _ refs_good class_exists H0 H1)\n as [classes' [p [o [c [f [H' [resolve_ok [f_static all_randv']]]]]]]].\ndestruct x.\ndestruct (sem_unpop good_stack wp_code) as [l_eq [v [s' [v_ok [s'_form s'_ok]]]]]. \nsubst l2.\n\nrewrite s'_form in E. \nchange V.C.ConstantPool.lookup with E.R.C.ConstantPool.lookup in H0.\nchange V.C.class_constantpool with E.R.C.class_constantpool in H0.\nchange V.C.cpe_fieldref with E.R.C.cpe_fieldref in H0.\nrewrite H0 in E. rewrite resolve_ok in E. \ngeneralize E. clear E. dependent inversion H'. intro.\nrewrite f_static in E. normal_continue code_is_safe H; eauto.\n apply fields_well_typed_update; eauto.\n  eapply preserve_rt_ty_sat; eauto.\n\n(* op_if_acmp *)\ndestruct_opt (V.C.pc_plus_offset pc z) H wp_code. \ndestruct_opt (PreV.VA.Cert.lookup cert (S pc)) H0 wp_code. simpl in wp_code.\ndestruct_opt (PreV.VA.Cert.lookup cert x) H1 wp_code. simpl in wp_code.\ndestruct_opt (V.assertion_merge class x0 x1) H2 wp_code. simpl in wp_code.\ndestruct_opt (V.unpop PreV.VA.va_ref x2) H3 wp_code. simpl in wp_code.\ndestruct x0. destruct x1. destruct x2. destruct x3. simpl in H2. \ndestruct_opt (V.lvar_assertion_merge class l l0) H4 H2. simpl in H2.\ndestruct_opt (V.stack_assertion_merge class s s0) H5 H2. simpl in H2.\ninversion H2. subst x0 x1. clear H2.\ndestruct (sem_unpop good_stack wp_code). subst l2. destruct H6. destruct H2. destruct H2. destruct H6.\ndestruct (sem_unpop H7 H3). subst l3. destruct H9. destruct H8. destruct H8. destruct H9. subst x1.\ndestruct x0; inversion H2; subst o;\ndestruct x2; inversion H8; subst o;\nchange V.C.pc_plus_offset with E.C.pc_plus_offset in H;\n\nrewrite H6 in E;\ndestruct a;\n(match goal with [_:match (if ?t then _ else _) with Some _ => _ | None => _ end = res |- _] => destruct t end;\n[rewrite H in E; normal_continue code_is_safe H1;\n [eapply lvar_assertion_implication_sound; [ apply subclassing_satisfied | eapply V.lvar_assertion_merge_p2; eauto | eauto ]\n |eapply stack_assertion_implication_sound; [ apply subclassing_satisfied | eapply V.stack_assertion_merge_p2; eauto | eauto ]]\n|normal_continue code_is_safe H0;\n [eapply lvar_assertion_implication_sound; [ apply subclassing_satisfied | eapply V.lvar_assertion_merge_p1; eauto | eauto ]\n |eapply stack_assertion_implication_sound; [ apply subclassing_satisfied | eapply V.stack_assertion_merge_p1; eauto | eauto ]]]).\n\n(* op_if_icmp *)\ndestruct_opt (V.C.pc_plus_offset pc z) H wp_code. \ndestruct_opt (PreV.VA.Cert.lookup cert (S pc)) H0 wp_code. simpl in wp_code.\ndestruct_opt (PreV.VA.Cert.lookup cert x) H1 wp_code. simpl in wp_code.\ndestruct_opt (V.assertion_merge class x0 x1) H2 wp_code. simpl in wp_code.\ndestruct_opt (V.unpop PreV.VA.va_int x2) H3 wp_code. simpl in wp_code.\ndestruct x0. destruct x1. destruct x2. destruct x3. simpl in H2. \ndestruct_opt (V.lvar_assertion_merge class l l0) H4 H2. simpl in H2.\ndestruct_opt (V.stack_assertion_merge class s s0) H5 H2. simpl in H2.\ninversion H2. subst x0 x1. clear H2.\ndestruct (sem_unpop good_stack wp_code). subst l2. destruct H6. destruct H2. destruct H2. destruct H6.\ndestruct (sem_unpop H7 H3). subst l3. destruct H9. destruct H8. destruct H8. destruct H9. subst x1.\ndestruct x0; inversion H2. subst i.\ndestruct x2; inversion H8. subst i.\nchange V.C.pc_plus_offset with E.C.pc_plus_offset in H.\n\nrewrite H6 in E. \ndestruct c;\n(match goal with [_:match (if ?t then _ else _) with Some _ => _ | None => _ end = res |- _] => destruct t end;\n[rewrite H in E; normal_continue code_is_safe H1;\n [eapply lvar_assertion_implication_sound; [ apply subclassing_satisfied | eapply V.lvar_assertion_merge_p2; eauto | eauto ]\n |eapply stack_assertion_implication_sound; [ apply subclassing_satisfied | eapply V.stack_assertion_merge_p2; eauto | eauto ]]\n|normal_continue code_is_safe H0;\n [eapply lvar_assertion_implication_sound; [ apply subclassing_satisfied | eapply V.lvar_assertion_merge_p1; eauto | eauto ]\n |eapply stack_assertion_implication_sound; [ apply subclassing_satisfied | eapply V.stack_assertion_merge_p1; eauto | eauto ]]]).\n\n(* op_if *)\ndestruct_opt (V.C.pc_plus_offset pc z) H wp_code. \ndestruct_opt (PreV.VA.Cert.lookup cert (S pc)) H0 wp_code. simpl in wp_code.\ndestruct_opt (PreV.VA.Cert.lookup cert x) H1 wp_code. simpl in wp_code.\ndestruct_opt (V.assertion_merge class x0 x1) H2 wp_code. simpl in wp_code.\ndestruct x0. destruct x1. destruct x2. simpl in H2.\ndestruct_opt (V.lvar_assertion_merge class l l0) H3 H2. simpl in H2.\ndestruct_opt (V.stack_assertion_merge class s s0) H4 H2. simpl in H2.\ninversion H2. subst x0 x1. clear H2.\ndestruct (sem_unpop good_stack wp_code). subst l1. destruct H5. destruct H2. destruct H2. destruct H5.\ndestruct x0; inversion H2. subst i.\nchange V.C.pc_plus_offset with E.C.pc_plus_offset in H.\n\nrewrite H5 in E.\ndestruct c;\n(match goal with [_:match (if ?t then _ else _) with Some _ => _ | None => _ end = res |- _ ] => destruct t end;\n[rewrite H in E; normal_continue code_is_safe H1;\n [eapply lvar_assertion_implication_sound; [ apply subclassing_satisfied | eapply V.lvar_assertion_merge_p2; eauto | eauto ]\n |eapply stack_assertion_implication_sound; [ apply subclassing_satisfied | eapply V.stack_assertion_merge_p2; eauto | eauto ]]\n|normal_continue code_is_safe H0;\n [eapply lvar_assertion_implication_sound; [ apply subclassing_satisfied | eapply V.lvar_assertion_merge_p1; eauto | eauto ]\n |eapply stack_assertion_implication_sound; [ apply subclassing_satisfied | eapply V.stack_assertion_merge_p1; eauto | eauto ]]]).\n\n(* op_ifnonnull *)\ndestruct_opt (V.C.pc_plus_offset pc z) H wp_code. \ndestruct_opt (PreV.VA.Cert.lookup cert (S pc)) H0 wp_code. simpl in wp_code.\ndestruct_opt (PreV.VA.Cert.lookup cert x) H1 wp_code. simpl in wp_code.\ndestruct_opt (V.assertion_merge class x0 x1) H2 wp_code. simpl in wp_code.\ndestruct x0. destruct x1. destruct x2. simpl in H2.\ndestruct_opt (V.lvar_assertion_merge class l l0) H3 H2. simpl in H2.\ndestruct_opt (V.stack_assertion_merge class s s0) H4 H2. simpl in H2.\ninversion H2. subst x0 x1. clear H2.\ndestruct (sem_unpop good_stack wp_code). subst l1. destruct H5. destruct H2. destruct H2. destruct H5.\nchange V.C.pc_plus_offset with E.C.pc_plus_offset in H.\nrewrite H5 in E.\ndestruct x0; inversion H2; subst o;\n[rewrite H in E; normal_continue code_is_safe H1;\n [eapply lvar_assertion_implication_sound; [ apply subclassing_satisfied | eapply V.lvar_assertion_merge_p2; eauto | eauto ]\n |eapply stack_assertion_implication_sound; [ apply subclassing_satisfied | eapply V.stack_assertion_merge_p2; eauto | eauto ]]\n|normal_continue code_is_safe H0;\n [eapply lvar_assertion_implication_sound; [ apply subclassing_satisfied | eapply V.lvar_assertion_merge_p1; eauto | eauto ]\n |eapply stack_assertion_implication_sound; [ apply subclassing_satisfied | eapply V.stack_assertion_merge_p1; eauto | eauto ]]].\n\n(* op_ifnull *)\ndestruct_opt (V.C.pc_plus_offset pc z) H wp_code. \ndestruct_opt (PreV.VA.Cert.lookup cert (S pc)) H0 wp_code. simpl in wp_code.\ndestruct_opt (PreV.VA.Cert.lookup cert x) H1 wp_code. simpl in wp_code.\ndestruct_opt (V.assertion_merge class x0 x1) H2 wp_code. simpl in wp_code.\ndestruct x0. destruct x1. destruct x2. simpl in H2.\ndestruct_opt (V.lvar_assertion_merge class l l0) H3 H2. simpl in H2.\ndestruct_opt (V.stack_assertion_merge class s s0) H4 H2. simpl in H2.\ninversion H2. subst x0 x1. clear H2.\ndestruct (sem_unpop good_stack wp_code). subst l1. destruct H5. destruct H2. destruct H2. destruct H5.\nchange V.C.pc_plus_offset with E.C.pc_plus_offset in H.\nrewrite H5 in E.\ndestruct x0; inversion H2; subst o;\n[normal_continue code_is_safe H0;\n [eapply lvar_assertion_implication_sound; [ apply subclassing_satisfied | eapply V.lvar_assertion_merge_p1; eauto | eauto ]\n |eapply stack_assertion_implication_sound; [ apply subclassing_satisfied | eapply V.stack_assertion_merge_p1; eauto | eauto ]]\n|rewrite H in E; normal_continue code_is_safe H1;\n [eapply lvar_assertion_implication_sound; [ apply subclassing_satisfied | eapply V.lvar_assertion_merge_p2; eauto | eauto ]\n |eapply stack_assertion_implication_sound; [ apply subclassing_satisfied | eapply V.stack_assertion_merge_p2; eauto | eauto ]]].\n\n(* op_goto *)\ndestruct_opt (V.C.pc_plus_offset pc z) H wp_code.\nchange V.C.pc_plus_offset with E.C.pc_plus_offset in H.\nrewrite H in E. normal_continue code_is_safe wp_code.\n \n(* op_valreturn *)\ndestruct current_ty; try discriminate. simpl in wp_code. \ndestruct (PreV.VA.value_assertion_eq_dec (V.java_type_to_value_assertion j) (V.stack_type_to_value_assertion s)); try discriminate.\ninversion wp_code. subst l2 s2.  \ninversion good_stack. subst t a. \n\nrewrite <- H1 in E. \ndestruct fs. inversion frame_stack_is_safe. subst rt final_ty.\nright. left. match goal with [H0:E.stop ?st ?v = res |- _ ] => exists st; exists v end.\nsplit. assumption. simpl. rewrite e. assumption.\n\ndestruct f. inversion frame_stack_is_safe. normal_continue H11 H12. apply H15; eauto.\n rewrite e. assumption.\n\n(* op_return *)\ndestruct current_ty; try discriminate. inversion wp_code. subst s2 l2.\ndestruct fs.\n inversion frame_stack_is_safe. \n right. left. match goal with [H0:E.stop ?st ?v = res |- _ ] => exists st; exists v end. split; simpl; trivial. \n\n destruct f. inversion frame_stack_is_safe. normal_continue H7 H8.\n\n(* op_athrow *)\ndestruct (option_dec (V.check_exception_handlers code class cert pc (V.C.code_exception_table code))) as [[l exc_check] | exc_check];\n  rewrite exc_check in wp_code; [simpl in wp_code|discriminate].\ninversion wp_code. subst l2 s2.\ninversion good_stack. subst op_stack t a. \nchange PreV.VA.va_addr with C.A.va_addr in H2.\ninversion H2. \n (* The exception to be thrown was actually null *)\n subst x v. \n throw_built_in E E.R.B.java_lang_NullPointerException get_null_pointer_exception preclasses classes heap (preserve_old_classes_id classes) exceptions_exist exc_check subclassing_satisfied code_is_safe.\n  apply V.lvar_imp_refl.\n (* There really was an exception to be thrown *)\n subst v nm. rewrite H0 in E. \n destruct (E.R.Classpool.lookup_informative (E.R.classpool classes) nm') as [[c c_exists] | no_c_exists].\n  (* class exists *)\n  assert (c_isa_exception:E.R.sub_class classes (E.R.C.class_name c) E.R.B.java_lang_Exception).\n   rewrite (E.R.cert_classpool_names_2 c_exists).\n   eauto.\n  assert (c_isa_throwable:E.R.sub_class classes (E.R.C.class_name c) E.R.B.java_lang_Throwable).\n   rewrite (E.R.cert_classpool_names_2 c_exists).\n   eapply E.R.sub_class_trans; eauto.\n   destruct exceptions_exist as [classes npe cce _ _ _ _ _ _ isa1 isa2 isa].\n   assumption.\n  rewrite E.R.check_subclass_complete in E; [idtac|assumption].\n   destruct (check_exception_handlers_prop _ heap _ _ _ _ _ _ (E.R.cert_classpool_names c_exists) _ _ subclassing_satisfied c_isa_exception exc_check (refl_equal _))\n         as [[pc' [l' [s' [search_handlers_ok [cert_lookup_ok [lvar_imp stack_will_be_ok]]]]]] | search_handlers_ok];\n    change V.C.code_exception_table with E.R.C.code_exception_table in search_handlers_ok.\n    (* Exception is handled in this stack frame *)\n    rewrite <- search_handlers_ok in E.\n    normal_continue code_is_safe cert_lookup_ok.\n     eapply lvar_assertion_implication_sound; eauto.\n     apply stack_will_be_ok. eapply ty_sat_addr2. apply H0. \n      change C.class_name with R.C.class_name. rewrite (R.cert_classpool_names_2 c_exists). constructor.\n    (* Exception passed upwards *)\n    rewrite <- search_handlers_ok in E.\n    eapply (unwind_stack_ok preclasses classes heap); eauto.\n     eapply ty_sat_addr2. apply H0. change C.class_name with R.C.class_name. rewrite (R.cert_classpool_names_2 c_exists). constructor.\n  destruct (heap_good _ _ _ H0) as [[c [c_exists _]] _]. \n   change R.Classpool.lookup with E.R.Classpool.lookup in c_exists.\n   change R.classpool with E.R.classpool in c_exists.\n   rewrite c_exists in no_c_exists. discriminate.\n\n(* op_iconst *)\ndestruct_opt (PreV.VA.Cert.lookup cert (S pc)) H wp_code. destruct x.\ndestruct (sem_unpush subclassing_satisfied good_stack wp_code). subst l. pose (H1 (E.rt_int t) (ty_sat_int _ _ t)). \nnormal_continue code_is_safe H.\nSave.\n\n\nEnd MkVerifierSafety.\n\nEnd PreVerifierSafety.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\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/old/VerifierSafety.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947155710234, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.25938294909877535}}
{"text": "Require Export Base.\n\nModule SProdCategory.\n\nStructure mixin_of (C: Category) := Mixin {\n  sprod {I}: (I -> C) -> C;\n  sfork {I} {X: C} {F: I -> C}: (forall i, X ~> F i) -> X ~> sprod F;\n  pi {I} {F: I -> C} (i: I): sprod F ~> F i;\n  sfork_ump {I} {X: C} {F: I -> C} (f: forall i, X ~> F i) (g: X ~> sprod F): sfork f = g <-> forall i, pi i ∘ g = f i;\n}.\n\nNotation class_of := mixin_of (only parsing).\n\nSection ClassDef.\n\nStructure type := Pack { sort: Category; _: class_of sort }.\nLocal Coercion sort: type >-> Category.\n\nVariable T: type.\nDefinition class := match T return class_of T with Pack _ c => c end.\n\nDefinition Cat: Cat := T.\n\nEnd ClassDef.\n\nModule Exports.\n\nCoercion sort: type >-> Category.\nCoercion Cat: type >-> Category.obj.\nNotation SProdCategory := type.\n\nEnd Exports.\nEnd SProdCategory.\n\nExport SProdCategory.Exports.\n\nSection SProdCategory_theory.\nContext {C: SProdCategory}.\n\nDefinition sprod: forall {I}, (I -> C) -> C := @SProdCategory.sprod C (SProdCategory.class C).\nDefinition sfork: forall {I} {X: C} {F: I -> C}, (forall i, X ~> F i) -> X ~> sprod F := @SProdCategory.sfork C (SProdCategory.class C).\nDefinition pi: forall {I} {F: I -> C} (i: I), sprod F ~> F i := @SProdCategory.pi C (SProdCategory.class C).\nDefinition sfork_ump: forall {I} {X: C} {F: I -> C} (f: forall i, X ~> F i) (g: X ~> sprod F), sfork f = g <-> forall i, pi i ∘ g = f i := @SProdCategory.sfork_ump C (SProdCategory.class C).\n\nNotation \"∏ i .. j , x\" := (sprod (fun i => .. (sprod (fun j => x)) ..)) (at level 40, i binder).\nNotation \"∏' i .. j , f\" := (sfork (fun i => .. (sfork (fun j => f)) ..)) (at level 40, i binder).\nNotation π := pi.\n\nLemma to_sprod_eq {I} {F: I -> C} {X: C} (f g: X ~> sprod F): f = g <-> forall i, π i ∘ f = π i ∘ g.\nProof.\n  split.\n  now intros [].\n  intros H.\n  transitivity (∏' i, (π i ∘ g)).\n  symmetry.\n  all: now apply sfork_ump.\nQed.\n\nDefinition spmap {I} {F G: I -> C} (η: forall i, F i ~> G i): sprod F ~> sprod G :=\n  ∏' i, (η i ∘ π i).\n\nNotation \"(∏) i .. j , f\" := (spmap (fun i => .. (spmap (fun j => f)) ..)) (at level 40, i binder).\n\nLemma pi_sfork {I} {F: I -> C} {X: C} (η: forall i, X ~> F i) (i: I): π i ∘ sfork η = η i.\nProof. now apply sfork_ump. Qed.\n\nLemma pi_spmap {I} {F G: I -> C} (η: forall i, F i ~> G i) (i: I): π i ∘ spmap η = η i ∘ π i.\nProof. exact (pi_sfork (fun i => η i ∘ π i) i). Qed.\n\nLemma sfork_comp {I} {X Y: C} {F: I -> C} (f: forall i, Y ~> F i) (g: X ~> Y): ∏' i, (f i ∘ g) = sfork f ∘ g.\nProof.\n  apply to_sprod_eq.\n  intros i.\n  rewrite comp_assoc.\n  now rewrite !pi_sfork.\nQed.\n\nLemma spmap_sfork {I} {F G: I -> C} {X: C} (f: forall i, F i ~> G i) (g: forall i, X ~> F i): spmap f ∘ sfork g = ∏' i, (f i ∘ g i).\nProof.\n  apply to_sprod_eq.\n  intros i.\n  rewrite comp_assoc.\n  rewrite pi_spmap.\n  rewrite <- comp_assoc.\n  now rewrite !pi_sfork.\nQed.\n\nLemma spmap_id {I} (F: I -> C): (∏) i, id (F i) = id (sprod F).\nProof.\n  apply to_sprod_eq.\n  intros i.\n  rewrite pi_spmap.\n  rewrite comp_id_r.\n  apply comp_id_l.\nQed.\n\nLemma spmap_comp {I} {F G H: I -> C} (η: forall i, G i ~> H i) (ϵ: forall i, F i ~> G i): (∏) i, (η i ∘ ϵ i) = spmap η ∘ spmap ϵ.\nProof.\n  apply to_sprod_eq.\n  intros i.\n  rewrite comp_assoc.\n  rewrite !pi_spmap.\n  rewrite <- !comp_assoc.\n  f_equal.\n  symmetry.\n  apply pi_spmap.\nQed.\n\nEnd SProdCategory_theory.\n\nNotation \"∏ i .. j , x\" := (sprod (fun i => .. (sprod (fun j => x)) ..)) (at level 40, i binder).\nNotation \"∏' i .. j , f\" := (sfork (fun i => .. (sfork (fun j => f)) ..)) (at level 40, i binder).\nNotation π := pi.\nNotation \"(∏) i .. j , f\" := (spmap (fun i => .. (spmap (fun j => f)) ..)) (at level 40, i binder).\n\nInstance sfork_pw C I X F: Proper (forall_relation (fun _ => eq) ==> eq) (@sfork C I X F).\nProof.\n  intros f g H.\n  f_equal.\n  now extensionality i.\nQed.\n\nInstance spmap_pw C I F G: Proper (forall_relation (fun _ => eq) ==> eq) (@spmap C I F G).\nProof.\n  intros f g H.\n  f_equal.\n  now extensionality i.\nQed.\n", "meta": {"author": "adamAndMath", "repo": "Category", "sha": "1d230ee099a3ec7bd21306a404f38b2b3f3c3865", "save_path": "github-repos/coq/adamAndMath-Category", "path": "github-repos/coq/adamAndMath-Category/Category-1d230ee099a3ec7bd21306a404f38b2b3f3c3865/Structure/SmallProd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2593807164439105}}
{"text": "(* This file is generated by Why3's Coq driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire BuiltIn.\nRequire HighOrd.\nRequire int.Int.\nRequire list.List.\nRequire list.Length.\nRequire list.Mem.\nRequire list.Append.\n\nAxiom i : Type.\nParameter i_WhyType : WhyType i.\nExisting Instance i_WhyType.\n\nAxiom b : Type.\nParameter b_WhyType : WhyType b.\nExisting Instance b_WhyType.\n\nParameter top: b.\n\nParameter bot: b.\n\nParameter infix_slasbs: b -> b -> b.\n\nParameter infix_bsassl: b -> b -> b.\n\nParameter neg: b -> b.\n\n(* Why3 assumption *)\nDefinition xor (x:b) (y:b) : b :=\n  infix_slasbs (infix_bsassl x y) (neg (infix_slasbs x y)).\n\nAxiom Assoc :\n  forall (x:b) (y:b) (z:b), ((xor (xor x y) z) = (xor x (xor y z))).\n\nAxiom Unit_def_l : forall (x:b), ((xor bot x) = x).\n\nAxiom Unit_def_r : forall (x:b), ((xor x bot) = x).\n\nAxiom Inv_def_l : forall (x:b), ((xor x x) = bot).\n\nAxiom Inv_def_r : forall (x:b), ((xor x x) = bot).\n\nAxiom Comm : forall (x:b) (y:b), ((xor x y) = (xor y x)).\n\nAxiom Assoc1 :\n  forall (x:b) (y:b) (z:b),\n  ((infix_slasbs (infix_slasbs x y) z) = (infix_slasbs x (infix_slasbs y z))).\n\nAxiom Mul_distr_l :\n  forall (x:b) (y:b) (z:b),\n  ((infix_slasbs x (xor y z)) = (xor (infix_slasbs x y) (infix_slasbs x z))).\n\nAxiom Mul_distr_r :\n  forall (x:b) (y:b) (z:b),\n  ((infix_slasbs (xor y z) x) = (xor (infix_slasbs y x) (infix_slasbs z x))).\n\nAxiom Comm1 : forall (x:b) (y:b), ((infix_slasbs x y) = (infix_slasbs y x)).\n\nAxiom Unit_def_l1 : forall (x:b), ((infix_slasbs top x) = x).\n\nAxiom Unit_def_r1 : forall (x:b), ((infix_slasbs x top) = x).\n\nAxiom NonTrivialRing : ~ (bot = top).\n\nAxiom Idempotence : forall (x:b), ((infix_slasbs x x) = x).\n\nAxiom br_equivalent_law_1 : forall (a:b), ((xor a a) = bot).\n\n(* Why3 assumption *)\nDefinition infix_lseq (x:b) (y:b) : Prop := ((infix_bsassl x y) = y).\n\nAxiom Refl : forall (x:b), infix_lseq x x.\n\nAxiom Trans :\n  forall (x:b) (y:b) (z:b), infix_lseq x y -> infix_lseq y z ->\n  infix_lseq x z.\n\nAxiom Antisymm :\n  forall (x:b) (y:b), infix_lseq x y -> infix_lseq y x -> (x = y).\n\nAxiom glb_infimum :\n  forall (x:b) (y:b),\n  infix_lseq (infix_slasbs x y) x /\\\n  infix_lseq (infix_slasbs x y) y /\\\n  (forall (w:b), infix_lseq w x /\\ infix_lseq w y ->\n   infix_lseq w (infix_slasbs x y)).\n\nAxiom lub_supremum :\n  forall (x:b) (y:b),\n  infix_lseq x (infix_bsassl x y) /\\\n  infix_lseq y (infix_bsassl x y) /\\\n  (forall (w:b), infix_lseq x w /\\ infix_lseq y w ->\n   infix_lseq (infix_bsassl x y) w).\n\nAxiom comm_meet :\n  forall (x:b) (y:b), ((infix_bsassl x y) = (infix_bsassl y x)).\n\nAxiom comm_join :\n  forall (x:b) (y:b), ((infix_slasbs x y) = (infix_slasbs y x)).\n\nAxiom assoc_meet :\n  forall (x:b) (y:b) (z:b),\n  ((infix_slasbs x (infix_slasbs y z)) = (infix_slasbs (infix_slasbs x y) z)).\n\nAxiom assoc_join :\n  forall (x:b) (y:b) (z:b),\n  ((infix_bsassl x (infix_bsassl y z)) = (infix_bsassl (infix_bsassl x y) z)).\n\nAxiom absorp_meet :\n  forall (x:b) (y:b), ((infix_slasbs x (infix_bsassl x y)) = x).\n\nAxiom absorp_join :\n  forall (x:b) (y:b), ((infix_bsassl x (infix_slasbs x y)) = x).\n\nAxiom idem_meet : forall (x:b), ((infix_slasbs x x) = x).\n\nAxiom idem_join : forall (x:b), ((infix_bsassl x x) = x).\n\nAxiom order :\n  forall (x:b) (y:b), ((infix_bsassl x y) = x) -> ((infix_slasbs x y) = y).\n\nAxiom dl_dist_one :\n  forall (a:b) (b1:b) (c:b),\n  ((infix_bsassl a (infix_slasbs b1 c)) =\n   (infix_slasbs (infix_bsassl a b1) (infix_bsassl a c))).\n\nAxiom dl_dist_two :\n  forall (a:b) (b1:b) (c:b),\n  ((infix_slasbs a (infix_bsassl b1 c)) =\n   (infix_bsassl (infix_slasbs a b1) (infix_slasbs a c))).\n\nAxiom dist_meet :\n  forall (x:b) (y:b) (z:b),\n  ((infix_slasbs x (infix_bsassl y z)) =\n   (infix_bsassl (infix_slasbs x y) (infix_slasbs x z))).\n\nAxiom dist_join :\n  forall (x:b) (y:b) (z:b),\n  ((infix_bsassl x (infix_slasbs y z)) =\n   (infix_slasbs (infix_bsassl x y) (infix_bsassl x z))).\n\nAxiom Refl1 : forall (x:b), infix_lseq x x.\n\nAxiom Trans1 :\n  forall (x:b) (y:b) (z:b), infix_lseq x y -> infix_lseq y z ->\n  infix_lseq x z.\n\nAxiom Antisymm1 :\n  forall (x:b) (y:b), infix_lseq x y -> infix_lseq y x -> (x = y).\n\nAxiom glb_infimum1 :\n  forall (x:b) (y:b),\n  infix_lseq (infix_slasbs x y) x /\\\n  infix_lseq (infix_slasbs x y) y /\\\n  (forall (w:b), infix_lseq w x /\\ infix_lseq w y ->\n   infix_lseq w (infix_slasbs x y)).\n\nAxiom lub_supremum1 :\n  forall (x:b) (y:b),\n  infix_lseq x (infix_bsassl x y) /\\\n  infix_lseq y (infix_bsassl x y) /\\\n  (forall (w:b), infix_lseq x w /\\ infix_lseq y w ->\n   infix_lseq (infix_bsassl x y) w).\n\nAxiom comm_meet1 :\n  forall (x:b) (y:b), ((infix_bsassl x y) = (infix_bsassl y x)).\n\nAxiom comm_join1 :\n  forall (x:b) (y:b), ((infix_slasbs x y) = (infix_slasbs y x)).\n\nAxiom assoc_meet1 :\n  forall (x:b) (y:b) (z:b),\n  ((infix_slasbs x (infix_slasbs y z)) = (infix_slasbs (infix_slasbs x y) z)).\n\nAxiom assoc_join1 :\n  forall (x:b) (y:b) (z:b),\n  ((infix_bsassl x (infix_bsassl y z)) = (infix_bsassl (infix_bsassl x y) z)).\n\nAxiom absorp_meet1 :\n  forall (x:b) (y:b), ((infix_slasbs x (infix_bsassl x y)) = x).\n\nAxiom absorp_join1 :\n  forall (x:b) (y:b), ((infix_bsassl x (infix_slasbs x y)) = x).\n\nAxiom idem_meet1 : forall (x:b), ((infix_slasbs x x) = x).\n\nAxiom idem_join1 : forall (x:b), ((infix_bsassl x x) = x).\n\nAxiom order1 :\n  forall (x:b) (y:b), ((infix_bsassl x y) = x) -> ((infix_slasbs x y) = y).\n\nAxiom lowerBoundZero : forall (x:b), infix_lseq bot x.\n\nAxiom upperBoundOne : forall (x:b), infix_lseq x top.\n\nAxiom ident_meet : forall (x:b), ((infix_slasbs x top) = x).\n\nAxiom ident_join : forall (x:b), ((infix_bsassl x bot) = x).\n\nAxiom bound_glb : forall (x:b), ((infix_slasbs x bot) = bot).\n\nAxiom bound_lub : forall (x:b), ((infix_bsassl x top) = top).\n\nAxiom cl_compl_top : forall (a:b), exists x:b, ((infix_bsassl a x) = top).\n\nAxiom cl_compl_bot : forall (a:b), exists x:b, ((infix_slasbs a x) = bot).\n\nAxiom lattice_ring :\n  forall (x:b) (y:b),\n  (infix_lseq x y <-> ((infix_slasbs x y) = x)) /\\\n  (((infix_slasbs x y) = x) <-> ((infix_bsassl x y) = y)).\n\nAxiom comm_and :\n  forall (x:b) (y:b), ((infix_slasbs x y) = (infix_slasbs y x)).\n\nAxiom comm_or :\n  forall (x:b) (y:b), ((infix_bsassl x y) = (infix_bsassl y x)).\n\nAxiom dist_and :\n  forall (x:b) (y:b) (z:b),\n  ((infix_slasbs x (infix_bsassl y z)) =\n   (infix_bsassl (infix_slasbs x y) (infix_slasbs x z))).\n\nAxiom dist_or :\n  forall (x:b) (y:b) (z:b),\n  ((infix_bsassl x (infix_slasbs y z)) =\n   (infix_slasbs (infix_bsassl x y) (infix_bsassl x z))).\n\nAxiom ident_and : forall (x:b), ((infix_slasbs x top) = x).\n\nAxiom ident_or : forall (x:b), ((infix_bsassl x bot) = x).\n\nAxiom uniq_compl :\n  forall (x:b) (y:b) (z:b), ((neg x) = y) /\\ ((neg x) = z) -> (y = z).\n\nAxiom compl_and : forall (x:b), ((infix_slasbs x (neg x)) = bot).\n\nAxiom compl_or : forall (x:b), ((infix_bsassl x (neg x)) = top).\n\nAxiom idem_and : forall (x:b), ((infix_slasbs x x) = x).\n\nAxiom idem_or : forall (x:b), ((infix_bsassl x x) = x).\n\nAxiom boundbot : forall (x:b), infix_lseq bot x.\n\nAxiom boundtop : forall (x:b), infix_lseq x top.\n\nAxiom bound_and : forall (x:b), ((infix_slasbs x bot) = bot).\n\nAxiom bound_or : forall (x:b), ((infix_bsassl x top) = top).\n\nAxiom absorp_and :\n  forall (x:b) (y:b), ((infix_slasbs x (infix_bsassl x y)) = x).\n\nAxiom absorp_or :\n  forall (x:b) (y:b), ((infix_bsassl x (infix_slasbs x y)) = x).\n\nAxiom assoc_and :\n  forall (x:b) (y:b) (z:b),\n  ((infix_slasbs x (infix_slasbs y z)) = (infix_slasbs (infix_slasbs x y) z)).\n\nAxiom assoc_or :\n  forall (x:b) (y:b) (z:b),\n  ((infix_bsassl x (infix_bsassl y z)) = (infix_bsassl (infix_bsassl x y) z)).\n\nAxiom demorgan_and :\n  forall (x:b) (y:b),\n  ((neg (infix_slasbs x y)) = (infix_bsassl (neg x) (neg y))).\n\nAxiom demorgan_or :\n  forall (x:b) (y:b),\n  ((neg (infix_bsassl x y)) = (infix_slasbs (neg x) (neg y))).\n\nAxiom negtop : ((neg top) = bot).\n\nAxiom negbot : ((neg bot) = top).\n\nAxiom double_neg : forall (x:b), ((neg (neg x)) = x).\n\nAxiom dist_ord :\n  forall (x:b) (y:b) (z:b), infix_lseq x z ->\n  ((infix_bsassl x (infix_slasbs y z)) = (infix_slasbs (infix_bsassl x y) z)).\n\n(* Why3 assumption *)\nDefinition infix_mngtas (x:b) (y:b) : b := infix_bsassl (neg x) y.\n\n(* Why3 assumption *)\nDefinition usequiv (x:b) (y:b) : b :=\n  infix_slasbs (infix_mngtas x y) (infix_mngtas y x).\n\nAxiom disj_and :\n  forall (x:b) (y:b),\n  (x = (infix_slasbs x y)) /\\ ((infix_slasbs x y) = top) -> (x = top).\n\nAxiom disj_or : forall (x:b) (y:b), (x = top) -> ((infix_bsassl x y) = top).\n\nAxiom modus_ponens :\n  forall (x:b) (y:b), ((infix_slasbs x (infix_mngtas x y)) = top) ->\n  (y = top).\n\nAxiom modus_tollens :\n  forall (x:b) (y:b), ((infix_slasbs (infix_mngtas x y) (neg y)) = top) ->\n  ((neg x) = top).\n\nAxiom implic :\n  forall (x:b) (y:b), ((infix_mngtas x y) = (infix_bsassl (neg x) y)).\n\nAxiom absur :\n  forall (x:b) (y:b),\n  ((infix_slasbs (infix_mngtas x y) (infix_mngtas x (neg y))) = (neg x)).\n\nAxiom disj_syl :\n  forall (x:b) (y:b), ((infix_slasbs (infix_bsassl x y) (neg x)) = top) ->\n  (y = top).\n\nAxiom impl_chain :\n  forall (x:b) (y:b) (z:b),\n  ((infix_slasbs (infix_mngtas x y) (infix_mngtas y z)) = top) ->\n  ((infix_mngtas x z) = top).\n\nAxiom impl_comb :\n  forall (x:b) (y:b) (z:b) (w:b),\n  ((infix_slasbs (infix_mngtas x y) (infix_mngtas z w)) = top) ->\n  ((infix_mngtas (infix_slasbs x z) (infix_slasbs y w)) = top).\n\nAxiom currying :\n  forall (x:b) (y:b) (z:b),\n  ((infix_mngtas (infix_slasbs x y) z) = (infix_mngtas x (infix_mngtas y z))).\n\nAxiom contrapos :\n  forall (x:b) (y:b), ((infix_mngtas x y) = (infix_mngtas (neg y) (neg x))).\n\nAxiom binary : forall (x:b), (x = top) \\/ (x = bot).\n\nAxiom ifnottop_thenbot : forall (t:b), ~ (t = top) -> (t = bot).\n\nAxiom ifnotbot_thentop : forall (t:b), ~ (t = bot) -> (t = top).\n\n(* Why3 assumption *)\nInductive formula :=\n  | Prop1 : b -> formula\n  | Var : i -> formula\n  | Neg : formula -> formula\n  | And : formula -> formula -> formula\n  | Or : formula -> formula -> formula\n  | Impl : formula -> formula -> formula.\nAxiom formula_WhyType : WhyType formula.\nExisting Instance formula_WhyType.\n\n(* Why3 assumption *)\nFixpoint eval (e:formula) (v:i -> b) {struct e}: b :=\n  match e with\n  | Prop1 b1 => b1\n  | Var i1 => v i1\n  | Neg e1 => neg (eval e1 v)\n  | And e1 e2 => infix_slasbs (eval e1 v) (eval e2 v)\n  | Or e1 e2 => infix_bsassl (eval e1 v) (eval e2 v)\n  | Impl e1 e2 => infix_mngtas (eval e1 v) (eval e2 v)\n  end.\n\n(* Why3 assumption *)\nDefinition infix_eqeq (f1:formula) (f2:formula) : Prop :=\n  forall (v:i -> b), ((eval f1 v) = (eval f2 v)).\n\n(* Why3 assumption *)\nInductive atom :=\n  | B : b -> atom\n  | I : i -> atom\n  | Nb : b -> atom\n  | Ni : i -> atom.\nAxiom atom_WhyType : WhyType atom.\nExisting Instance atom_WhyType.\n\n(* Why3 assumption *)\nDefinition cnf_clause := Init.Datatypes.list atom.\n\n(* Why3 assumption *)\nDefinition cnf := Init.Datatypes.list (Init.Datatypes.list atom).\n\n(* Why3 assumption *)\nFixpoint eval_cnf_clause (e:Init.Datatypes.list atom)\n  (v:i -> b) {struct e}: b :=\n  match e with\n  | Init.Datatypes.nil => bot\n  | Init.Datatypes.cons (B b1) Init.Datatypes.nil => b1\n  | Init.Datatypes.cons (I i1) Init.Datatypes.nil => v i1\n  | Init.Datatypes.cons (Nb b1) Init.Datatypes.nil => neg b1\n  | Init.Datatypes.cons (Ni i1) Init.Datatypes.nil => neg (v i1)\n  | Init.Datatypes.cons (B b1) tl => infix_bsassl b1 (eval_cnf_clause tl v)\n  | Init.Datatypes.cons (I i1) tl =>\n      infix_bsassl (v i1) (eval_cnf_clause tl v)\n  | Init.Datatypes.cons (Nb b1) tl =>\n      infix_bsassl (neg b1) (eval_cnf_clause tl v)\n  | Init.Datatypes.cons (Ni i1) tl =>\n      infix_bsassl (neg (v i1)) (eval_cnf_clause tl v)\n  end.\n\n(* Why3 assumption *)\nFixpoint eval_cnf (e:Init.Datatypes.list (Init.Datatypes.list atom))\n  (v:i -> b) {struct e}: b :=\n  match e with\n  | Init.Datatypes.nil => top\n  | Init.Datatypes.cons hd tl =>\n      infix_slasbs (eval_cnf_clause hd v) (eval_cnf tl v)\n  end.\n\n(* Why3 assumption *)\nDefinition equiv_cnf (f1:Init.Datatypes.list (Init.Datatypes.list atom))\n    (f2:Init.Datatypes.list (Init.Datatypes.list atom)) : Prop :=\n  forall (v:i -> b), ((eval_cnf f1 v) = (eval_cnf f2 v)).\n\nAxiom comm_and1 :\n  forall (x:formula) (y:formula), infix_eqeq (And x y) (And y x).\n\nAxiom comm_or1 :\n  forall (x:formula) (y:formula), infix_eqeq (Or x y) (Or y x).\n\nAxiom dist_and1 :\n  forall (x:formula) (y:formula) (z:formula),\n  infix_eqeq (And x (Or y z)) (Or (And x y) (And x z)).\n\nAxiom dist_or1 :\n  forall (x:formula) (y:formula) (z:formula),\n  infix_eqeq (Or x (And y z)) (And (Or x y) (Or x z)).\n\nAxiom ident_and1 : forall (x:formula), infix_eqeq (And x (Prop1 top)) x.\n\nAxiom ident_or1 : forall (x:formula), infix_eqeq (Or x (Prop1 bot)) x.\n\nAxiom uniq_compl1 :\n  forall (x:formula) (y:formula) (z:formula),\n  infix_eqeq (Neg x) y /\\ infix_eqeq (Neg x) z -> infix_eqeq y z.\n\nAxiom compl_and1 :\n  forall (x:formula), infix_eqeq (And x (Neg x)) (Prop1 bot).\n\nAxiom compl_or1 : forall (x:formula), infix_eqeq (Or x (Neg x)) (Prop1 top).\n\nAxiom idem_and1 : forall (x:formula), infix_eqeq (And x x) x.\n\nAxiom idem_or1 : forall (x:formula), infix_eqeq (Or x x) x.\n\nAxiom bound_and1 :\n  forall (x:formula), infix_eqeq (And x (Prop1 bot)) (Prop1 bot).\n\nAxiom bound_or1 :\n  forall (x:formula), infix_eqeq (Or x (Prop1 top)) (Prop1 top).\n\nAxiom absorp_and1 :\n  forall (x:formula) (y:formula), infix_eqeq (And x (Or x y)) x.\n\nAxiom absorp_or1 :\n  forall (x:formula) (y:formula), infix_eqeq (Or x (And x y)) x.\n\nAxiom assoc_and1 :\n  forall (x:formula) (y:formula) (z:formula),\n  infix_eqeq (And x (And y z)) (And (And x y) z).\n\nAxiom assoc_or1 :\n  forall (x:formula) (y:formula) (z:formula),\n  infix_eqeq (Or x (Or y z)) (Or (Or x y) z).\n\nAxiom demorgan_and1 :\n  forall (phi1:formula) (phi2:formula),\n  infix_eqeq (Neg (And phi1 phi2)) (Or (Neg phi1) (Neg phi2)).\n\nAxiom demorgan_or1 :\n  forall (phi1:formula) (phi2:formula),\n  infix_eqeq (Neg (Or phi1 phi2)) (And (Neg phi1) (Neg phi2)).\n\nAxiom negtop1 : infix_eqeq (Neg (Prop1 top)) (Prop1 bot).\n\nAxiom negbot1 : infix_eqeq (Neg (Prop1 bot)) (Prop1 top).\n\nAxiom double_neg1 : forall (x:formula), infix_eqeq (Neg (Neg x)) x.\n\nAxiom dist_ord1 :\n  forall (x:b) (y:b) (z:b), infix_lseq x z ->\n  ((infix_bsassl x (infix_slasbs y z)) = (infix_slasbs (infix_bsassl x y) z)).\n\nAxiom disj_and1 :\n  forall (x:formula) (y:formula), infix_eqeq (And x y) (Prop1 top) ->\n  infix_eqeq x (Prop1 top).\n\nAxiom disj_or1 :\n  forall (x:formula) (y:formula), infix_eqeq x (Prop1 top) ->\n  infix_eqeq (Or x y) (Prop1 top).\n\nAxiom modus_ponens1 :\n  forall (x:formula) (y:formula),\n  infix_eqeq (And x (Impl x y)) (Prop1 top) -> infix_eqeq y (Prop1 top).\n\nAxiom modus_tollens1 :\n  forall (x:formula) (y:formula),\n  infix_eqeq (And (Impl x y) (Neg y)) (Prop1 top) ->\n  infix_eqeq (Neg x) (Prop1 top).\n\nAxiom implic1 :\n  forall (x:formula) (y:formula), infix_eqeq (Impl x y) (Or (Neg x) y).\n\nAxiom absur1 :\n  forall (x:formula) (y:formula),\n  infix_eqeq (And (Impl x y) (Impl x (Neg y))) (Neg x).\n\nAxiom disj_syl1 :\n  forall (x:formula) (y:formula),\n  infix_eqeq (And (Or x y) (Neg x)) (Prop1 top) -> infix_eqeq y (Prop1 top).\n\nAxiom impl_chain1 :\n  forall (x:formula) (y:formula) (z:formula),\n  infix_eqeq (And (Impl x y) (Impl y z)) (Prop1 top) ->\n  infix_eqeq (Impl x z) (Prop1 top).\n\nAxiom impl_comb1 :\n  forall (x:formula) (y:formula) (z:formula) (w:formula),\n  infix_eqeq (And (Impl x y) (Impl z w)) (Prop1 top) ->\n  infix_eqeq (Impl (And x z) (And y w)) (Prop1 top).\n\nAxiom currying1 :\n  forall (x:formula) (y:formula) (z:formula),\n  infix_eqeq (Impl (And x y) z) (Impl x (Impl y z)).\n\nAxiom contrapos1 :\n  forall (x:formula) (y:formula),\n  infix_eqeq (Impl x y) (Impl (Neg y) (Neg x)).\n\nAxiom pierce :\n  forall (x:formula) (y:formula),\n  infix_eqeq (Impl (Impl (Impl x y) x) x) (Or x (Neg x)).\n\n(* Why3 assumption *)\nFixpoint size (phi:formula) {struct phi}: Numbers.BinNums.Z :=\n  match phi with\n  | Neg phi1 => (1%Z + (size phi1))%Z\n  | (And phi1 phi2)|((Or phi1 phi2)|(Impl phi1 phi2)) =>\n      ((1%Z + (size phi1))%Z + (size phi2))%Z\n  | _ => 1%Z\n  end.\n\nAxiom size'spec : forall (phi:formula), (0%Z <= (size phi))%Z.\n\n(* Why3 assumption *)\nFixpoint size_cnf_clause\n  (phi:Init.Datatypes.list atom) {struct phi}: Numbers.BinNums.Z :=\n  match phi with\n  | Init.Datatypes.nil => 0%Z\n  | Init.Datatypes.cons _ tl => (1%Z + (size_cnf_clause tl))%Z\n  end.\n\nAxiom size_cnf_clause'spec :\n  forall (phi:Init.Datatypes.list atom), (0%Z <= (size_cnf_clause phi))%Z.\n\n(* Why3 assumption *)\nFixpoint size_cnf\n  (phi:Init.Datatypes.list (Init.Datatypes.list atom)) {struct phi}: Numbers.BinNums.Z :=\n  match phi with\n  | Init.Datatypes.nil => 0%Z\n  | Init.Datatypes.cons hd tl => (1%Z + (size_cnf tl))%Z\n  end.\n\nAxiom size_cnf'spec :\n  forall (phi:Init.Datatypes.list (Init.Datatypes.list atom)),\n  (0%Z <= (size_cnf phi))%Z.\n\n(* Why3 assumption *)\nFixpoint is_impl_free (phi:formula) {struct phi}: Prop :=\n  match phi with\n  | Prop1 _ => True\n  | Var _ => True\n  | Neg phi1 => is_impl_free phi1\n  | (Or phi1 phi2)|(And phi1 phi2) => is_impl_free phi1 /\\ is_impl_free phi2\n  | Impl _ _ => False\n  end.\n\n(* Why3 assumption *)\nFixpoint is_nnfc (phi:formula) {struct phi}: Prop :=\n  match phi with\n  | Prop1 _ => True\n  | Var _ => True\n  | Neg (Prop1 _) => True\n  | Neg (Var _) => True\n  | Neg _ => False\n  | (Or phi1 phi2)|(And phi1 phi2) => is_nnfc phi1 /\\ is_nnfc phi2\n  | Impl _ _ => False\n  end.\n\nAxiom nnfc_is_implfree :\n  forall (phi:formula), is_nnfc phi -> is_impl_free phi.\n\n(* Why3 assumption *)\nFixpoint is_cnf_clause (phi:formula) {struct phi}: Prop :=\n  match phi with\n  | Prop1 _ => True\n  | Var _ => True\n  | Neg (Prop1 _) => True\n  | Neg (Var _) => True\n  | Neg _ => False\n  | Or phi1 phi2 => is_cnf_clause phi1 /\\ is_cnf_clause phi2\n  | And _ _ => False\n  | Impl _ _ => False\n  end.\n\nAxiom cnf_clause_is_implfree :\n  forall (phi:formula), is_cnf_clause phi -> is_impl_free phi.\n\nAxiom cnf_clause_is_nnfc :\n  forall (phi:formula), is_cnf_clause phi -> is_nnfc phi.\n\n(* Why3 assumption *)\nFixpoint is_cnf (phi:formula) {struct phi}: Prop :=\n  match phi with\n  | Prop1 _ => True\n  | Var _ => True\n  | Neg (Prop1 _) => True\n  | Neg (Var _) => True\n  | Neg _ => False\n  | Or phi1 phi2 => is_cnf_clause phi1 /\\ is_cnf_clause phi2\n  | And phi1 phi2 => is_cnf phi1 /\\ is_cnf phi2\n  | Impl _ _ => False\n  end.\n\nAxiom cnf_clause_is_cnf :\n  forall (phi:formula), is_cnf_clause phi -> is_cnf phi.\n\nAxiom cnf_is_implfree : forall (phi:formula), is_cnf phi -> is_impl_free phi.\n\nAxiom cnf_is_nnfc : forall (phi:formula), is_cnf phi -> is_nnfc phi.\n\nAxiom cnf_clause1 :\n  forall (phi1:formula) (phi2:formula), is_cnf (Or phi1 phi2) ->\n  is_cnf_clause phi1 /\\ is_cnf_clause phi2.\n\n(* Why3 assumption *)\nFixpoint impl_free (phi:formula) {struct phi}: formula :=\n  match phi with\n  | Prop1 t => Prop1 t\n  | Var i1 => Var i1\n  | Neg phi1 => Neg (impl_free phi1)\n  | Or phi1 phi2 => Or (impl_free phi1) (impl_free phi2)\n  | And phi1 phi2 => And (impl_free phi1) (impl_free phi2)\n  | Impl phi1 phi2 => Or (Neg (impl_free phi1)) (impl_free phi2)\n  end.\n\nAxiom impl_free'spec :\n  forall (phi:formula), forall (v:i -> b),\n  ((eval phi v) = (eval (impl_free phi) v)) /\\ is_impl_free (impl_free phi).\n\nParameter nnfc: formula -> formula.\n\nAxiom nnfc'def :\n  forall (phi:formula), is_impl_free phi ->\n  match phi with\n  | Neg (Neg phi1) => ((nnfc phi) = (nnfc phi1))\n  | Neg (And phi1 phi2) =>\n      ((nnfc phi) = (Or (nnfc (Neg phi1)) (nnfc (Neg phi2))))\n  | Neg (Or phi1 phi2) =>\n      ((nnfc phi) = (And (nnfc (Neg phi1)) (nnfc (Neg phi2))))\n  | And phi1 phi2 => ((nnfc phi) = (And (nnfc phi1) (nnfc phi2)))\n  | Or phi1 phi2 => ((nnfc phi) = (Or (nnfc phi1) (nnfc phi2)))\n  | _ => ((nnfc phi) = phi)\n  end.\n\nAxiom nnfc'spec :\n  forall (phi:formula), is_impl_free phi ->\n  (forall (v:i -> b), ((eval phi v) = (eval (nnfc phi) v))) /\\\n  is_impl_free phi /\\ is_nnfc (nnfc phi).\n\nParameter distr: formula -> formula -> formula.\n\nAxiom distr'def :\n  forall (phi1:formula) (phi2:formula),\n  is_impl_free phi1 /\\\n  is_impl_free phi2 /\\\n  is_nnfc phi1 /\\ is_nnfc phi2 /\\ is_cnf phi1 /\\ is_cnf phi2 ->\n  match (phi1, phi2) with\n  | (And phi11 phi12, phi21) =>\n      ((distr phi1 phi2) = (And (distr phi11 phi21) (distr phi12 phi21)))\n  | (phi11, And phi21 phi22) =>\n      ((distr phi1 phi2) = (And (distr phi11 phi21) (distr phi11 phi22)))\n  | (_, _) => ((distr phi1 phi2) = (Or phi1 phi2))\n  end.\n\nAxiom distr'spec :\n  forall (phi1:formula) (phi2:formula),\n  is_impl_free phi1 /\\\n  is_impl_free phi2 /\\\n  is_nnfc phi1 /\\ is_nnfc phi2 /\\ is_cnf phi1 /\\ is_cnf phi2 ->\n  (forall (v:i -> b),\n   ((infix_bsassl (eval phi1 v) (eval phi2 v)) = (eval (distr phi1 phi2) v))) /\\\n  is_impl_free (distr phi1 phi2) /\\\n  is_nnfc (distr phi1 phi2) /\\ is_cnf (distr phi1 phi2).\n\nParameter cnfc: formula -> formula.\n\nAxiom cnfc'def :\n  forall (phi:formula), is_impl_free phi /\\ is_nnfc phi ->\n  match phi with\n  | Or phi1 phi2 => ((cnfc phi) = (distr (cnfc phi1) (cnfc phi2)))\n  | And phi1 phi2 => ((cnfc phi) = (And (cnfc phi1) (cnfc phi2)))\n  | _ => ((cnfc phi) = phi)\n  end.\n\nAxiom cnfc'spec :\n  forall (phi:formula), is_impl_free phi /\\ is_nnfc phi ->\n  (forall (v:i -> b), ((eval phi v) = (eval (cnfc phi) v))) /\\\n  is_impl_free phi /\\ is_nnfc (cnfc phi) /\\ is_cnf (cnfc phi).\n\n(* Why3 assumption *)\nDefinition t (phi:formula) : formula := cnfc (nnfc (impl_free phi)).\n\nAxiom t'spec :\n  forall (phi:formula), forall (v:i -> b),\n  ((eval phi v) = (eval (t phi) v)) /\\\n  is_impl_free (t phi) /\\ is_nnfc (t phi) /\\ is_cnf (t phi).\n\nParameter to_cnf_aux: formula -> Init.Datatypes.list atom.\n\nAxiom to_cnf_aux'spec :\n  forall (phi:formula),\n  is_impl_free phi /\\ is_nnfc phi /\\ is_cnf_clause phi -> forall (v:i -> b),\n  ((eval phi v) = (eval_cnf_clause (to_cnf_aux phi) v)).\n\nParameter phi: formula.\n\nAxiom H : is_impl_free phi.\n\nAxiom H1 : is_nnfc phi.\n\nAxiom H2 : is_cnf phi.\n\nParameter result: Init.Datatypes.list (Init.Datatypes.list atom).\n\nParameter result1: Init.Datatypes.list (Init.Datatypes.list atom).\n\nParameter result2: Init.Datatypes.list (Init.Datatypes.list atom).\n\nParameter x: formula.\n\nParameter x1: formula.\n\nAxiom H3 : (phi = (And x x1)).\n\nAxiom Ensures : forall (v:i -> b), ((eval x1 v) = (eval_cnf result1 v)).\n\nAxiom Ensures1 : forall (v:i -> b), ((eval x v) = (eval_cnf result2 v)).\n\nAxiom H4 : (result = (Init.Datatypes.app result2 result1)).\n\nParameter v: i -> b.\n\n(* Why3 goal *)\nTheorem to_cnf'vc : ((eval phi v) = (eval_cnf result v)).\n\nauto.\n", "meta": {"author": "laforetbarroso", "repo": "boolean_algebra", "sha": "19fb31bd52976f7065752f73d0e01880a9c36623", "save_path": "github-repos/coq/laforetbarroso-boolean_algebra", "path": "github-repos/coq/laforetbarroso-boolean_algebra/boolean_algebra-19fb31bd52976f7065752f73d0e01880a9c36623/cnf2/cnf2_T_to_cnfqtvc_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2593807164439105}}
{"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.StrictPositivityLemma.\nRequire Export SystemFR.ReducibilitySubst.\n\nOpaque makeFresh.\nOpaque PeanoNat.Nat.eq_dec.\nOpaque reducible_values.\nOpaque strictly_positive.\n\nLemma strictly_positive_push_forall2:\n  forall T ρ A B v X,\n    ~(X ∈ pfv T type_var) ->\n    non_empty ρ A ->\n    twf A 0 ->\n    twf B 0 ->\n    twf T 1 ->\n    wf A 0 ->\n    wf B 1 ->\n    wf T 0 ->\n    is_erased_type A ->\n    is_erased_type B ->\n    is_erased_type T ->\n    pfv A term_var = nil ->\n    pfv B term_var = nil ->\n    pfv T term_var = nil ->\n    valid_interpretation ρ ->\n    strictly_positive (topen 0 T (fvar X type_var)) (X :: nil) ->\n    (forall a,\n        [ ρ ⊨ a : A ]v ->\n        [ ρ ⊨ v : topen 0 T (open 0 B a) ]v) ->\n    [ ρ ⊨ v : topen 0 T (T_forall A B) ]v.\nProof.\n  intros; instantiate_non_empty; repeat step.\n  apply reducible_values_subst_head with\n    (makeFresh (\n       pfv T type_var ::\n       pfv A type_var ::\n       pfv B type_var ::\n       nil\n    ));\n    repeat step || list_utils;\n    try finisher.\n\n  rewrite cons_app.\n  match goal with\n  | H: wf ?B 1 |- [ ((?X,?RC) :: nil) ++ ?ρ ⊨ ?v : ?T ]v =>\n    eapply strictly_positive_push_forall with\n      ((X, fun a v => [ ρ ⊨ v : open 0 B a ]v) :: nil) A\n  end; eauto;\n    repeat step || apply wf_topen || apply twf_topen || apply is_erased_type_topen ||\n           fv_open || list_utils || apply wf_open || apply twf_open ||\n           apply reducibility_is_candidate ||\n           t_instantiate_reducible || apply reducible_values_subst_head2 || simp_red || t_closing;\n    try finisher;\n    eauto with twf;\n    eauto with wf;\n    eauto 2 with fv step_tactic.\n  - eapply strictly_positive_rename_one; eauto; steps; try finisher.\n  - rewrite (is_erased_term_tfv a0) in *; (steps; eauto with erased).\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/StrictPositivityPush.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.4843800842769843, "lm_q1q2_score": 0.2591910291368991}}
{"text": "(**\nContent :\n- Some lemma on Yoneda\n- Famillies of Types in CwF (DepTypes prefixe mostly)\n- Pi Types in CwF (CwF_Pi prefixe)\n- Sigma Types in CwF (CwF_Sig prefixe)\n- Identity Types in CwF (CwF_Id prefixe)\n**)\n\nRequire Import UniMath.Foundations.Sets.\nRequire Import UniMath.MoreFoundations.All.\nRequire Import TypeTheory.Auxiliary.CategoryTheoryImports.\nRequire Import TypeTheory.Auxiliary.Auxiliary.\nRequire Import TypeTheory.ALV1.CwF_def.\n\n\n\nNotation \"'pr1121' x\" := (pr1(pr1(pr2(pr1(x))))) (at level 30).\nNotation \"'pr2121' x\" := (pr2(pr1(pr2(pr1(x))))) (at level 30).\n\nSection Fix_Category.\n(** * Preliminaries *)\n(** General context for a category with famillies and some usefull notations *)  \nContext {CwF : cwf}.\nLocal Definition C : category := pr1(CwF).\nLocal Definition pp : mor_total(preShv(C)) := pr12 CwF.\nLocal Definition Ty : functor _ _ := target pp.\nLocal Definition Tm : functor _ _ := source pp.\n(* extension of context *)\nLocal Definition ext (Γ : C) (A : Ty Γ : hSet) : C := pr11 pr22 CwF Γ A.\nLocal Notation \"Γ .: A\" :=  (ext Γ A) (at level 24).\n\nLocal Definition pi {Γ : C} (A : Ty Γ : hSet) : C⟦Γ.:A,Γ⟧ := pr21 pr22 CwF _ A.\n(* just a simple to use pp as a nat_trans *)\nLocal Definition Nat_trans_morp {C : category} (Γ : C) (p : mor_total(preShv C))\n: HSET_univalent_category ⟦ (pr21 p : functor _ _) Γ, (pr11 p : functor _ _) Γ ⟧ := pr12 p Γ.\n\nNotation \"p __: Γ\" := (Nat_trans_morp Γ p)  (at level 24).\nLocal Definition pp_ (Γ : C) : (Tm Γ : hSet) → (Ty Γ : hSet) := pp __: Γ.\n\nLemma Ty_composition {Γ Γ' Γ'' : C} (f : C⟦Γ,Γ'⟧) (g : C⟦Γ',Γ''⟧) (A : Ty Γ'' : hSet) \n: #Ty (f;;g) A = #Ty f (#Ty g A).\nProof.\n  exact (!((toforallpaths _ _ _ (!(pr22 Ty _ _ _  g f))) A)).\nQed.\n\nLemma Tm_composition {Γ Γ' Γ'' : C} (f : C⟦Γ,Γ'⟧) (g : C⟦Γ',Γ''⟧) (A : Tm Γ'' : hSet)\n: #Tm (f;;g) A = #Tm f (#Tm g  A).\nProof.\n  exact (!((toforallpaths _ _ _ (!(pr22 Tm _ _ _  g f))) A)).\nQed.\n\nLemma Ty_identity {Γ : C} (A : Ty Γ : hSet) : A = #Ty (identity Γ) A.\nProof.\n  assert (eqA : A = (identity (pr1 Ty Γ) A)) by auto.\n  rewrite eqA.\n  apply (!((toforallpaths _ _ _ (pr12 Ty _ )) A)).\nQed.\n\n(** * Tm as a Display **)\nSection tm.\nLocal Definition tm {Γ : C} (A : Ty Γ : hSet) : UU\n:= ∑ (a : Tm Γ : hSet), pp_ _ a = A.\n\nLocal Definition pr1_tm {Γ : C} {A : Ty Γ : hSet} (a : tm A) : Tm Γ : hSet := pr1 a.\nCoercion pr1_tm : tm >-> pr1hSet.\n\nLemma ppComp1 {Γ Δ : C} {A : Ty Γ : hSet} (f : C^op ⟦Γ,Δ⟧) (a : tm A) :\n  pp_ _ (# Tm f a ) = # Ty f A. \nProof.\n  apply pathsinv0, (pathscomp0(!(maponpaths (# Ty f) (pr2 a)))).\n  apply pathsinv0, (toforallpaths _ _ _ (pr22 pp _ _ f) a) .\nQed.\n\nDefinition reind_cwf {Γ : C} (A : Ty Γ : hSet) {Γ'} (f : C⟦Γ',Γ⟧)\n: Ty Γ' : hSet := #Ty f A.\nLocal Definition reind_tm {Γ Δ} (f : C^op ⟦Γ,Δ⟧) {A : Ty Γ : hSet} (x : tm A)\n: tm (#Ty f A) := #Tm f x,,ppComp1 f x.\n\nLocal Definition te {Γ : C} (A : Ty Γ : hSet) : tm (#Ty (pi A) A)\n:= pr12 pr22 CwF _ A.\n(* proof of pp (te A) = Ty (pi A) A*)\nLocal Definition te' {Γ : C} (A : Ty Γ : hSet) : pp_ _ (te A) = #Ty (pi A) A := pr212 pr22 CwF Γ A.\nDefinition CwF_Pullback {Γ} (A : Ty Γ : hSet) : isPullback (yy A) pp (#Yo (pi A)) (yy(te A)) (cwf_square_comm (te' A)) := pr22 pr22 CwF Γ A.\n\nLocal Definition tm_transportf {Γ} {A A' : Ty Γ : hSet} (e : A = A')\n: tm A ≃ tm A'.\nProof.\n  use weqbandf.\n  -  exact (idweq (Tm Γ : hSet)).\n  -  induction e. intro x. exact (idweq _).\nDefined.\n\nLocal Definition tm_transportb {Γ} {A A' : Ty Γ : hSet} (e : A = A')\n: tm A' ≃ tm A := invweq(tm_transportf e).\n\nLemma tm_transportf_idpath {Γ} {A : Ty Γ : hSet} (t : tm A)\n: tm_transportf (idpath A) t = t.\nProof.\n  reflexivity.\nQed.\n\nLemma tm_transportb_idpath {Γ} {A : Ty Γ : hSet} (t : tm A)\n: tm_transportb (idpath A) t = t.\nProof.\n  reflexivity.\nQed.\n\nLemma tm_transportbf {Γ} {A A' : Ty Γ : hSet} (e : A = A') : tm_transportb e = tm_transportf (!e).\nProof.\n  induction e.\n  refine (subtypePath isapropisweq _).\n  apply (idpath _).\nQed.\n\nLemma reind_compose_tm\n{Γ Γ' Γ'' : C} (f : C⟦Γ',Γ⟧) (g : C⟦Γ'',Γ'⟧) {A : Ty Γ : hSet} (a : tm A)\n: reind_tm (g ;; f) a \n= tm_transportb (Ty_composition _ _ _) (reind_tm g (reind_tm f a)).\nProof.\n  apply subtypePath. \n  -  intro x. apply (setproperty (Ty Γ'' : hSet)).\n  -  rewrite tm_transportbf. apply Tm_composition.\nQed.\n\nLemma maponpaths_2_reind_tm \n{Γ Γ' : C} {f f' : C⟦Γ',Γ⟧} (e : f = f') {A : Ty Γ : hSet} (a : tm A)\n: reind_tm f a = tm_transportb (maponpaths (fun g => #Ty g A) e) (reind_tm f' a).\nProof.\n  induction e.\n  rewrite maponpaths_eq_idpath; [|apply idpath].\n  now rewrite tm_transportb_idpath.\nQed.\n\nLemma tm_transportf_compose {Γ : C} {A A' A'' : Ty Γ : hSet} (e : A = A')\n(e' : A' = A'') (a : tm A) \n: tm_transportf (e @ e') a = tm_transportf e' (tm_transportf e a).\nProof.\n  induction e.\n  induction e'.\n  reflexivity.\nQed.\n\nLemma tm_transportf_irrelevant {Γ} {A A' : Ty Γ : hSet} (e e' : A = A')\n(t : tm A)\n: tm_transportf e t = tm_transportf e' t.\nProof.\n  apply (maponpaths (fun e => tm_transportf e t)).\n  apply (setproperty (Ty Γ : hSet)).\nQed.\n\nLemma tm_transport_compose {Γ Γ' Γ'' : C} (f : C⟦Γ',Γ⟧) (g : C⟦Γ'',Γ'⟧) (A : Ty Γ : hSet) (a : tm A)\n: tm_transportf ((Ty_composition g f A)) (reind_tm (g;;f) a) = reind_tm g (reind_tm f a).\nProof.\n  rewrite reind_compose_tm.\n  rewrite tm_transportbf.\n  rewrite <- tm_transportf_compose ,pathsinv0l.\n  reflexivity.\nQed.\n\nLemma tm_transportf_bind {Γ} {A A' A'': Ty Γ : hSet} {e : A' = A} {e' : A'' = A'}\n{t} {t'} {t''} (ee : t = tm_transportf e t') (ee' : t' = tm_transportf e' t'')\n: t = tm_transportf (e' @ e) t''.\nProof.\n  etrans. 2: { apply pathsinv0, tm_transportf_compose. }\n  etrans. { eassumption. }\n  apply maponpaths; assumption.\nQed.\n\nLemma reind_compose_tm' \n{Γ Γ' Γ'' : C} (f : C⟦Γ',Γ⟧) (g : C⟦Γ'',Γ'⟧) {A : Ty Γ : hSet} (a : tm A)\n: tm_transportf (Ty_composition _ _ _)\n        (reind_tm (g ;; f) a)\n      = reind_tm g (reind_tm f a).\nProof.\n  rewrite reind_compose_tm. rewrite tm_transportbf.\n  now rewrite <- tm_transportf_compose, pathsinv0l, tm_transportf_idpath.\nQed.\n\nLemma reind_id_tm {Γ : C}{A : Ty Γ : hSet} (a : tm A)\n: reind_tm (identity _) a\n= tm_transportb ((toforallpaths _ _ _ (pr12 Ty _ )) A) a.\nProof.\n  apply subtypePath. \n  -  intros x. apply (setproperty (Ty Γ : hSet)).\n  -  apply ((toforallpaths _ _ _ (pr12 Tm _ )) a).\nQed.\n\nEnd tm. \n\nSection Yoneda.\n \n(** * Few usefull lemma on yoneda **)\n\nLemma yonedainv {A B : C} (f : C⟦A,B⟧) : Yo^-1 (#Yo f) = f.\nProof.\n  apply id_left.\nQed.\n\nLemma transportyo {A B : C} {f g : C⟦A,B⟧} (e : #Yo f = #Yo g) : f = g.\nProof.\n  apply (pathscomp0 (!(yonedainv f))), pathsinv0\n  ,(pathscomp0 (!(yonedainv g))), (!(maponpaths Yo^-1 e)).\nQed.\n\nLemma yonedacarac {Γ Δ : C} (f  : _ ⟦Yo Γ,Yo Δ⟧) \n: # Yo ((f :nat_trans _ _) Γ (identity Γ)) = f.\nProof.\n  assert (H : (# Yo ((f : nat_trans _ _) Γ (identity Γ)) : nat_trans _ _) Γ (identity Γ)\n               = (f : nat_trans _ _) Γ (identity Γ)) by apply (id_left _).\n  assert (Map1 : (f : nat_trans _ _) Γ (identity Γ) = yoneda_map_1 C (pr2 C) Γ (Yo(Δ)) f) by reflexivity.\n  assert (Map2 : # Yo ((f : nat_trans _ _) Γ (identity Γ)) = yoneda_map_2 C (pr2 C) Γ (Yo(Δ))\n         ((f : nat_trans _ _) Γ (identity Γ))).                                      \n  -  unfold yoneda_map_2; cbn; unfold yoneda_morphisms; unfold yoneda_morphisms_data; cbn.\n     assert (nattrans : is_nat_trans_yoneda_morphisms_data C _ Γ Δ\n         ((f :nat_trans _ _) Γ (identity Γ))\n          = yoneda_map_2_ax C (pr2 C) Γ (yoneda_objects C _ Δ)\n          ((f : nat_trans _ _) Γ (identity Γ))).\n     --  assert (prop : isaprop(is_nat_trans (yoneda_objects C _ Γ)\n         (yoneda_objects C (homset_property C) Δ)\n         (yoneda_morphisms_data C _ Γ Δ\n         ((f : nat_trans _ _) Γ (identity Γ))))) by (apply isaprop_is_nat_trans;exact (pr2 hset_category));\n        exact (pr1 (prop _ _)).\n     --  apply pair_path_in2; apply nattrans.\n  -  rewrite Map2; rewrite Map1; apply yoneda_map_1_2.\nQed.\n\nLemma invyoneda {A B : C} (f : _⟦Yo A,Yo B⟧) : #Yo (Yo^-1 f) = f.\nProof.\n  apply yonedacarac.  \nQed.\n\nLemma yyidentity {Γ : C} {A : Ty Γ : hSet} (B : Ty (Γ.:A) : hSet) \n: B = (@yy (pr1 C) (pr2 C) Ty (Γ.:A) B : nat_trans _ _) (Γ.:A) (identity (Γ.:A)).\nProof.\n  apply pathsinv0; eapply pathscomp0.\n  -  apply (toforallpaths _ (# Ty _) _ (functor_id Ty (Γ.:A))).\n  -  reflexivity.\nQed.\n\nEnd Yoneda.\n\nSection qq.\n(** morphism between contexts *)\n\nLet Xk {Γ : C} (A : Ty Γ : hSet) :=\n  make_Pullback _ _ _ _ _ _ (pr22 pr22 CwF Γ A).\n\nLocal Definition qq_yoneda {Γ  Δ : C} (A : Ty Γ : hSet) (f : C^op ⟦Γ,Δ⟧)\n: (preShv C) ⟦Yo (Δ .: (#Ty f A)), Yo (Γ.: A) ⟧.\nProof.\n  use (PullbackArrow (Xk A)).\n  -  apply (#Yo (pi _) ;; #Yo f ). \n  -  apply (yy (te _)).\n  -  abstract (\n        clear Xk;\n        assert (XT := (cwf_square_comm (te' (#Ty f A) )));\n        eapply pathscomp0; try apply XT; clear XT;\n        rewrite <- assoc; apply maponpaths;\n        apply pathsinv0, yy_natural\n     ).\nDefined.\n\nLemma qq_yoneda_commutes_1 {Γ Δ : C} (A : Ty Γ : hSet) (f : C ⟦Δ,Γ⟧)\n: (# Yo (pi (#Ty f A)) ;; # Yo f) = (qq_yoneda A f) ;; # Yo (pi A ) .\nProof.\n  apply pathsinv0.\n  apply (PullbackArrow_PullbackPr1 (Xk _)).\nQed.\n\nLemma qq_yoneda_commutes {Γ Δ : C} (A : Ty Γ : hSet) (f : C^op ⟦Γ,Δ⟧)\n: (qq_yoneda A f) ;; yy (te A) = yy (te (#Ty f A)).\nProof.\n  apply (PullbackArrow_PullbackPr2 (Xk A)).\nQed.\n\n\nLocal Definition qq_term {Γ  Δ : C} (A : Ty Γ : hSet) (f : C^op ⟦Γ,Δ⟧)\n: C ⟦ Δ.:(#Ty f A) , Γ.: A⟧.\nProof.\n  apply (invweq (make_weq _ (yoneda_fully_faithful _ (homset_property _) _ _ ))) ,\n  (qq_yoneda A f).\nDefined.\n\nLemma qq_yoneda_compatibility {Γ  Δ : C} (A : Ty Γ : hSet) (f : C^op ⟦Γ,Δ⟧) :\n #Yo(qq_term A f) = qq_yoneda A f.\nProof.\n  apply (homotweqinvweq\n  (make_weq _ (yoneda_fully_faithful _ (homset_property _) ( _ .:(#Ty f A)) (Γ.:A)))).\nQed.\n\nLemma qq_term_te {Γ Δ : C} (A : Ty Γ : hSet) (f : C^op ⟦Γ,Δ⟧) \n: #Tm (qq_term A f) (te A) = te (#Ty f A).\nProof.\n  assert (Hyp := qq_yoneda_commutes A f).\n  rewrite <- qq_yoneda_compatibility in Hyp. \n  apply (pathscomp0 (yy_natural  _ _ _ _ _)) in Hyp.\n  apply (invmaponpathsweq (@yy _ (pr2 C) _ _) ).\n  exact Hyp.\nQed.\n\nLemma qq_term_pullback {Γ  Δ :C} (A : Ty Γ : hSet) (f : C^op ⟦Γ,Δ⟧)\n: f ;; pi (#Ty f A) = (qq_term A f);; pi A.\nProof.\n  assert (XT := (qq_yoneda_commutes_1 A f)).\n  rewrite <- qq_yoneda_compatibility in XT.\n  do 2 rewrite <- functor_comp in XT.\n  apply (invmaponpathsweq (make_weq _ (yoneda_fully_faithful _ (homset_property _) _ _ ))).\n  cbn; cbn in XT; exact XT.\nQed.\n\nSection Familly_Of_Types.\n(** Famillies of types in a Category with famillies**)\nLemma Subproof_γ {Γ : C} {A : Ty Γ : hSet} (a : tm A)\n: identity (Yo Γ) ;; yy A = yy a ;;pp.\nProof.\n  apply pathsinv0, (pathscomp0(yy_comp_nat_trans Tm Ty pp Γ a)) ,pathsinv0,\n  (pathscomp0(id_left _ )), ((maponpaths yy) (!(pr2 a))).\nQed.\n\nDefinition γ {Γ : C} {A : Ty Γ : hSet} (a : tm A) : (preShv C)⟦Yo Γ,Yo (Γ.:A)⟧\n:= pr11((CwF_Pullback A) (Yo Γ) (identity _) (yy a) (Subproof_γ a)).\n\nLemma  γ_pull {Γ : C} (A : Ty Γ : hSet)\n: γ (te A) ;; yy (te (#Ty (pi A) A)) = yy (te A).\nProof.\n  exact (pr221((CwF_Pullback _) (Yo (Γ.:A)) (identity _) (yy _) (Subproof_γ _))).\nQed.\n\nLemma pull_γ {Γ : C} {A : Ty Γ : hSet} (a : tm A) : γ a ;; #Yo (pi A) = identity _.\nProof.\n  apply pathsinv0, (pathscomp0(!(pr121 (CwF_Pullback _\n        (Yo Γ) (identity (Yo Γ)) (yy a)\n        (Subproof_γ a))))); auto.\nQed.\n\nLemma γNat {Γ Δ : C} {A : Ty Γ : hSet} (f : C^op ⟦Γ,Δ⟧) (a : tm A)\n: (f : C⟦Δ,Γ⟧) ;; (γ a : nat_trans _ _) Γ (identity Γ) =\n  (γ (reind_tm f a ) ;; #Yo (qq_term A f) : nat_trans _ _) Δ (identity Δ).\nProof.\n  assert (Yoγ : #Yo ((f : C⟦Δ,Γ⟧) ;; (γ a : nat_trans _ _) Γ (identity Γ)) =\n  #Yo((γ (reind_tm f a) : nat_trans _ _) Δ (identity Δ) ;; qq_term A f)).\n  -  do 2 (rewrite (pr22 (yoneda C (pr2 C)) _ _ _); rewrite yonedacarac).\n     refine (MorphismsIntoPullbackEqual (CwF_Pullback A)\n     (#Yo f ;; γ a) (γ (reind_tm f a) ;; #Yo (qq_term A f)) _ _).\n     --  rewrite <- assoc.\n         eapply pathscomp0.\n         *  rewrite (cancel_precomposition _ _ _ _ _ _ _\n            (pr121((CwF_Pullback _) (Yo Γ) (identity (Yo Γ)) (yy(a)) (Subproof_γ a )))).\n            apply id_right.\n         *  rewrite qq_yoneda_compatibility.\n            rewrite <- assoc.\n            apply pathsinv0.\n            eapply pathscomp0.\n            **  rewrite (cancel_precomposition _ _ _ _ _ _ _\n                (pr121 ((pr22 (Xk A))\n                (Yo (_.: # Ty f A)) (# Yo (pi (#Ty f A));; # Yo f)\n                (yy (te (#Ty f A))) (qq_yoneda_subproof Γ Δ A f)))).\n                rewrite assoc.\n                rewrite  (cancel_postcomposition _ _ _\n                (pr121 ((CwF_Pullback _) (Yo Δ) (identity (Yo Δ))\n                (yy(#Tm f a)) (Subproof_γ (reind_tm f a) )))).\n                apply (pr1 (pr121 (preShv C)) _ (Yo Γ) (#Yo f)).\n            **  reflexivity.\n    --  rewrite <- assoc.\n        apply (pathscomp0  (cancel_precomposition _ _ _ _ _ _ _\n        (pr221((CwF_Pullback _) (Yo Γ) (identity (Yo Γ)) (yy(a)) (Subproof_γ a ))))).\n        rewrite qq_yoneda_compatibility.\n        rewrite <- assoc.\n        apply pathsinv0.\n        eapply pathscomp0.\n        *  rewrite (cancel_precomposition _ _ _ _ _ _ _\n           (pr221 ((pr22 (Xk A))\n           (Yo (_.: # Ty f A)) (# Yo (pi (#Ty f A));; # Yo f)\n           (yy (te (#Ty f A))) (qq_yoneda_subproof Γ Δ A f)))).\n           apply (pr221( (pr22(pr22 CwF Δ (#Ty f A)))\n           (Yo Δ) (identity (Yo Δ)) (yy(#Tm f a)) (Subproof_γ (reind_tm f a )))).\n        *  apply yy_natural.\n  -  apply (transportyo Yoγ).\nQed.\n\nLemma γPullback1 {Γ : C} (A : Ty Γ : hSet)\n: γ (te A) ;; #Yo (qq_term A (pi A)) ;; yy(te A) = identity _;; yy (te A).\nProof.\n  rewrite id_left.\n  assert (γ (te A) ;; yy ( te (# Ty (pi A) A)) = yy( te A)) by \n  (rewrite <- (pr221 (pr22 (pr22 CwF (Γ.:A) (#Ty (pi A) A))\n    (Yo (Γ.:A)) (identity _) (yy (te A))\n    (Subproof_γ (te A) ))); auto) .\n  rewrite (qq_yoneda_compatibility A (pi A)), <- assoc, <- X.\n  refine (cancel_precomposition _ _ _ _ _ _ _ _).\n  rewrite X.\n  apply (qq_yoneda_commutes A (pi A)).\nQed.\n\nLemma  γPullback2 {Γ : C} (A : Ty Γ : hSet)\n: γ (te A) ;; #Yo (qq_term A (pi A)) ;; #Yo (pi A) = identity _;;(#Yo (pi A)).\nProof.\n  assert (Eq1 : #Yo (pi (#Ty (pi A) A)) ;; #Yo (pi A) = qq_yoneda A (pi A) ;; #Yo (pi A)) by (\n  rewrite <- (pr121((pr22(make_Pullback (yy A) pp\n    (yoneda (pr1 CwF) (homset_property (pr1 CwF))\n    (Γ.:A))\n    (# (yoneda (pr1 CwF) (homset_property (pr1 CwF)))\n    (pi A))\n    (yy (pr112 (pr22 CwF Γ A)))\n    (cwf_square_comm (pr212 (pr22 CwF Γ A)))\n    (CwF_Pullback A))) (Yo (_ .: (#Ty (pi A) A)))\n    (#Yo (pi (#Ty (pi A) A)) ;; #Yo (pi A)) (yy (te (#Ty (pi A) A)))\n    (qq_yoneda_subproof Γ (Γ.: A) A (pi A))));          \n  auto).         \n  rewrite (qq_yoneda_compatibility A (pi A)), <- assoc.\n  assert (Eq2 : γ (te A);; #Yo (pi (#Ty (pi A) A)) = identity _) by \n  (apply pathsinv0, (pathscomp0(!(pr121 (CwF_Pullback _\n        (Yo (Γ.:A)) (identity (Yo (Γ.:A))) (yy (te A))\n        (Subproof_γ (te A))))));\n  auto).\n  apply (pathscomp0 (cancel_precomposition _ _ _ _ _ _ (γ (te A)) (!Eq1))).\n  rewrite assoc.\n  apply (pathscomp0 (cancel_postcomposition _ _ _ (Eq2))).\n  reflexivity.\nQed.\n\nDefinition γ_qq {Γ} {A : Ty Γ: hSet} {Γ'} (f : C⟦Γ',Γ⟧) (a : tm (#Ty f A)) : C⟦Γ',Γ.: A⟧.\nProof.\n  exact (Yo^-1 (γ a) ;; qq_term A f).    \nDefined.\n\nLemma γ_pi {Γ} {A : Ty Γ: hSet} (a : tm A) : Yo^-1 (γ a) ;; pi A = identity _.\nProof.\n  assert (Yoeq : #Yo(Yo^-1 (γ a) ;; pi A) = #Yo(identity Γ)).\n  -  apply (pathscomp0 (pr22 Yo _ _ _  _ _ )).\n     apply pathsinv0 , (pathscomp0 (pr12 Yo _)).    \n     assert (simplman : identity (pr1 (yoneda C (homset_property C)) Γ) \n     = identity (Yo Γ)) by auto.\n     apply (pathscomp0 simplman).\n     rewrite (!(pull_γ a)).\n     apply cancel_postcomposition.\n     assert (simplman2 : # (pr1 (yoneda C (homset_property C))) (Yo^-1 (γ a))\n     = #Yo (Yo^-1 (γ a))) by auto.\n     apply pathsinv0, (pathscomp0 simplman2), invyoneda.\n  -  apply (maponpaths (Yo^-1) ) in Yoeq.\n     rewrite yonedainv, yonedainv in Yoeq.\n     exact Yoeq.\nQed.\n\nLemma te_subtitution {Γ} {A : Ty Γ : hSet} (a : tm A) : #Tm (Yo^-1(γ a)) (te A) = a.\nProof.\n  assert (inter : @yy _ (pr2 C) _ _ (#Tm (Yo^-1(γ a)) (te A)) = yy a). \n  -  rewrite yy_natural, invyoneda. \n     exact (pr221((CwF_Pullback _) (Yo _) (identity _) (yy _) (Subproof_γ _))).\n  -  apply (maponpaths (invmap yy) ) in inter.\n     do 2 rewrite homotinvweqweq in inter.\n     exact inter.\nQed.\n\nLemma reind_id_tm' {Γ : C} {A : Ty Γ : hSet}  (a : tm A) (b : tm A)\n(e : # Ty (identity Γ) A = # Ty (Yo^-1 (γ b) ;; pi A) A) \n: tm_transportf e (reind_tm (identity _) a)\n= tm_transportf ((Ty_identity _) @ e) a.\nProof.\n  apply subtypePath.  \n  -  intros x. apply (setproperty (Ty Γ : hSet)).\n  -  apply ((toforallpaths _ _ _ (pr12 Tm _ )) a).\nQed.\n\nLemma Ty_γ_id {Γ : C} {A : Ty Γ : hSet} (a : tm A) \n: # Ty (Yo^-1 (γ a)) (# Ty (pi A) A) = A.\nProof.\n  simple refine (!(Ty_composition _ _ _) @ _).\n  apply (pathscomp0 ((toforallpaths  _ _ _ (maponpaths _ (γ_pi _)) )A)).\n  apply ((toforallpaths _ _ _ (pr12 Ty _ )) A).\nQed.\n\nDefinition DepTypesType {Γ : C} {A : Ty Γ : hSet} (B : Ty(Γ.:A) : hSet)\n(a : tm A)\n: Ty Γ : hSet := ( γ a;;yy B : nat_trans _ _) Γ (identity Γ).\n\nDefinition DepTypesElem_pr1 {Γ : C} {A : Ty Γ : hSet} {B : Ty(Γ.:A) : hSet}\n(b : tm B) (a : tm A) \n: Tm Γ : hSet := (γ a;;yy b : nat_trans _ _) Γ (identity Γ).\n\nLemma DepTypesComp {Γ : C} { A : Ty Γ : hSet} {B : Ty(Γ.:A) : hSet}\n(b : tm B) (a : tm A)\n: pp_  Γ (DepTypesElem_pr1 b a) = DepTypesType B a.\nProof.\n  apply pathsinv0,(pathscomp0(maponpaths _ (!(pr2 b)))),pathsinv0,\n  (toforallpaths _ _ _ (pr22 pp (Γ.:A) Γ ((γ a : nat_trans _ _ ) Γ (identity Γ))) b).\nQed.\n\nDefinition DepTypesElems {Γ : C} { A : Ty Γ : hSet} {B : Ty(Γ.:A) : hSet}\n(b : tm B) (a : tm A)\n: tm (DepTypesType B a) := DepTypesElem_pr1 b a ,, DepTypesComp b a.\n\nLemma DepTypesNat {Γ Δ : C} {A : Ty Γ : hSet} (B : Ty (Γ.: A) : hSet)\n(f : C^op ⟦Γ,Δ⟧) (a : tm A)\n: #Ty f (DepTypesType B a) = DepTypesType (#Ty (qq_term A f) B) (reind_tm f a).\nProof.\n  unfold DepTypesType, reind_tm; rewrite yy_natural, assoc.\n  assert (Fucn : (# (pr1 Ty) ((γ a :nat_trans _ _) Γ (identity Γ)) ;; # (pr1 Ty) f) B =\n  # Ty f (# Ty ((γ a :nat_trans _ _) Γ (identity Γ)) B)) by auto.\n  apply (pathscomp0 (!Fucn)),(pathscomp0(!((toforallpaths _ _ _  \n  ((pr22 Ty) _ _ _ ((γ a: nat_trans _ _) Γ (identity Γ) : C⟦Γ,Γ.:A⟧) f)) B))), \n  (pathscomp0(toforallpaths _ _ _ (maponpaths (# Ty) (γNat f a)) B)).\n  reflexivity.\nQed.\n\nLemma DepTypesEta {Γ : C} {A : Ty Γ : hSet} (B : Ty (Γ.:A) : hSet)\n: DepTypesType (#Ty (qq_term A (pi A)) B) (te A) = B.\nProof.\n  assert (Natu : @γ (Γ.:A) (#Ty (pi A) A) (te A) ;; yy (# Ty (qq_term A (pi A)) B)\n  = @γ (Γ.:A) (#Ty (pi A) A) (te A) ;; #Yo (qq_term A (pi A)) ;; \n  (@yy (@pr1 _ _ C) (@pr2 _ _ C) Ty (Γ .: A)) B).\n  -  rewrite (cancel_precomposition _ _ _ _ (yy (#Ty (qq_term A (pi A)) B))\n     (#Yo (qq_term A (pi A));; yy B) _).\n     *  rewrite assoc; reflexivity.\n     *  rewrite yy_natural; reflexivity.\n  -  assert (Id: @γ (Γ .: A) (# Ty (@pi Γ A) A) (te A) ;; #Yo (qq_term A (pi A))\n     = identity _).\n     *  refine (MorphismsIntoPullbackEqual\n        (pr22(make_Pullback (yy A) pp\n        (yoneda (pr1 CwF) (homset_property (pr1 CwF)) (Γ.:A))\n        (# (yoneda (pr1 CwF) (homset_property (pr1 CwF))) (pi A))\n        (yy (te A))\n        (cwf_square_comm (te' A))\n        (CwF_Pullback A)))\n        (γ (te A) ;; #Yo (qq_term A (pi A))) (identity _) (γPullback2 A) (γPullback1 A)).\n     *  rewrite Id, (id_left _) in Natu.\n        unfold DepTypesType.\n        rewrite Natu; exact (!(yyidentity B)).\nQed.\n\nLemma DepTypesrewrite {Γ : C} {A : Ty Γ : hSet} (B : Ty (Γ.:A) : hSet)\n(a b : tm A) (e : pr1 a = pr1 b)\n: DepTypesType B a = DepTypesType B b.\nProof.\n  destruct a as [a pa]; destruct b as [b pb].\n  cbn in e; induction e.\n  assert (ProofIrr : pa = pb) by apply (setproperty( Ty Γ : hSet)).\n  rewrite ProofIrr.\n  reflexivity.\nQed.\n\nEnd Familly_Of_Types.\nEnd qq.\n\n(** ** Pi Type over Category with famillies *)\n\nSection Pi_structure.\n\nDefinition CwF_PiTypeFormer : UU \n:= ∏ (Γ : C) (A : Ty Γ : hSet) (B : Ty (Γ.:A) : hSet), (Ty Γ : hSet).\n\nDefinition CwF_PiTypeNat (π : CwF_PiTypeFormer) : UU \n:= ∏ (Γ Δ : C) (f : C^op ⟦Γ,Δ⟧) (A : Ty Γ : hSet) (B : Ty(Γ.:A) : hSet),\n  reind_cwf (π _ A B) f  = π _ (reind_cwf A f) (reind_cwf B (qq_term A f)).\n\nDefinition CwF_pi_form_struct : UU\n:= ∑ pi : CwF_PiTypeFormer, CwF_PiTypeNat pi.\n\nDefinition pr1_PiFormer (π : CwF_pi_form_struct) : CwF_PiTypeFormer := pr1 π.\nCoercion pr1_PiFormer : CwF_pi_form_struct >-> CwF_PiTypeFormer.\n\nLemma ppComp3 {Γ Δ : C} {A : Ty Γ : hSet} (f : C^op ⟦Γ,Δ⟧) {π : CwF_PiTypeFormer}\n(nπ : CwF_PiTypeNat π) {B : Ty (Γ.: A) : hSet} (c : tm (π _ A B))\n: pp_ _ (# Tm f c)  = (π Δ (# Ty f A) (# Ty (qq_term A f) B)).\nProof.\n  apply pathsinv0, (pathscomp0(!(nπ _ _ f A B))),\n  (pathscomp0(!(maponpaths (# Ty f) (pr2 c)))),\n   pathsinv0, (toforallpaths _ _ _ (pr22 pp _ _ f) c) .\nQed.\n\nDefinition CwF_PiAbs (π : CwF_PiTypeFormer): UU\n:= ∏ (Γ : C) (A : Ty Γ : hSet) (B : Ty (Γ.:A) : hSet) (b : tm B), tm (π _ A B) .\n\nDefinition CwF_PiAbsNat (π : CwF_PiTypeFormer) (nπ : CwF_PiTypeNat π) (Λ : CwF_PiAbs π) \n: UU := ∏ (Γ Δ : C) (f : C^op ⟦ Γ, Δ ⟧) (A : Ty Γ : hSet)\n(B : Ty (Γ .: A) : hSet) (b : tm B), reind_tm f (Λ Γ A B b) =\ntm_transportf (! (! ppComp1 f (Λ Γ A B b) @ ppComp3 f nπ (Λ Γ A B b)))\n(Λ Δ (# Ty f A) (# Ty (qq_term A f) B) (reind_tm (qq_term A f) b)).\n\nDefinition CwF_Pi_intro_struct (π : CwF_pi_form_struct) : UU\n:= ∑ Λ : CwF_PiAbs π, CwF_PiAbsNat π (pr2 π) Λ.\n\nDefinition CwF_PiApp (π : CwF_PiTypeFormer) : UU\n:= ∏ (Γ : C) (A : Ty Γ : hSet) (B : Ty(Γ.: A) : hSet) (c : tm (π _ A B)) (a : tm A),\ntm (DepTypesType B a).\n\nDefinition CwF_PiAppNat  (π : CwF_PiTypeFormer) (nπ : CwF_PiTypeNat π) (app : CwF_PiApp π) : UU\n:= ∏ (Γ Δ : C) (f : C^op ⟦Γ,Δ⟧) (A : Ty Γ : hSet) (B : Ty(Γ.: A) : hSet) \n(c : tm (π _ A B)) (a : tm A), \nreind_tm f (app _ _ _ c a) = (tm_transportf  (!(DepTypesNat B f a))\n(app _ (#Ty f A) (# Ty (qq_term A f) B)\n (tm_transportf (nπ _ _ f A B) (reind_tm f c)) (reind_tm f a))).\n\nDefinition CwF_Pi_app_struct (π : CwF_pi_form_struct) : UU \n:= ∑ app : CwF_PiApp π, CwF_PiAppNat π (pr2 π) app.\n\nDefinition CwF_PiAppAbs (π : CwF_PiTypeFormer) (Λ : CwF_PiAbs π) (app : CwF_PiApp π)\n:= ∏ Γ ( A : Ty Γ : hSet) (B : Ty(Γ.: A) : hSet) (b : tm B) (a : tm A),\napp _ _ _ (Λ _ A _ b) a = DepTypesElems b a.\n\nDefinition CwF_Pi_comp_struct (π : CwF_pi_form_struct)\n(lam : CwF_Pi_intro_struct π) (app : CwF_Pi_app_struct π) : UU\n:= CwF_PiAppAbs π (pr1 lam) (pr1 app).\n\nDefinition CwF_PiAbsAppComp (π : CwF_PiTypeFormer) (nπ : CwF_PiTypeNat π)\n(Λ : CwF_PiAbs π) (app : CwF_PiApp π) \n: UU\n:= ∏ (Γ : C) (A : Ty Γ: hSet) (B : Ty (Γ .: A) : hSet) (c : tm (π Γ A B)),\nc = Λ Γ A B (tm_transportf (DepTypesEta B)\n(app (Γ .: A) (# Ty (pi A) A) (# Ty (qq_term A (pi A)) B)\n(tm_transportf (nπ Γ (Γ .: A) (pi A) A B) (reind_tm (pi A) c)) (te A))).\n\nEnd Pi_structure.\n\n(** ** Sigma Type over Category with famillies *)\nSection Sigma_structure.\n\nDefinition CwF_SigTypeFormer : UU \n:= ∏ (Γ : C) (A : Ty Γ : hSet) (B : Ty (Γ.:A) : hSet), Ty Γ : hSet.\n\nDefinition CwF_SigTypeNat (σ : CwF_SigTypeFormer) : UU \n:= ∏ (Γ Δ : C) (f : C^op ⟦Γ,Δ⟧) (A : Ty Γ : hSet) (B : Ty(Γ.:A) : hSet),\n#Ty f (σ _ A B) = σ _ (#Ty f A) (#Ty (qq_term A f) B).\n\nDefinition CwF_SigAbs (σ : CwF_SigTypeFormer) : UU \n:= ∏ (Γ : C) (A : Ty Γ : hSet) (B : Ty(Γ.:A) : hSet) (a : tm A)\n(b : tm (DepTypesType B a) ), tm (σ _ A B).\n\nDefinition CwF_SigAbsNat (σ : CwF_SigTypeFormer) (nσ : CwF_SigTypeNat σ)\n(pair : CwF_SigAbs σ) \n: UU := ∏ (Γ Δ : C) (f : C^op ⟦ Γ, Δ ⟧) (A : Ty Γ : hSet) (B : Ty (Γ .: A) : hSet)\n(a : tm A) (b : tm (DepTypesType B a)), reind_tm f (pair Γ A B a b) =\ntm_transportf (! nσ Γ Δ f A B)\n(pair Δ (# Ty f A) (# Ty (qq_term A f) B) (reind_tm f a)\n(tm_transportf (DepTypesNat B f a) (reind_tm f b))).\n\nDefinition CwF_SigPr1 (σ : CwF_SigTypeFormer) : UU\n:= ∏ Γ (A : Ty Γ : hSet) (B : Ty(Γ.:A) : hSet) (c: tm (σ _ A B)), tm A.\n\nDefinition CwF_SigPr1Nat (σ : CwF_SigTypeFormer) (nσ : CwF_SigTypeNat σ) (p1 : CwF_SigPr1 σ) : UU \n:= ∏ (Γ Δ : C)  (f : C^op ⟦Γ,Δ⟧) (A : Ty Γ : hSet) (B : Ty(Γ.:A) : hSet) (c : tm (σ _ A B)),\nreind_tm f (p1 _ _ _ c) = \np1 _ (#Ty f A) (#Ty (qq_term A f) B) (tm_transportf (nσ _ _ f _ _) (reind_tm f c)).\n \nDefinition CwF_SigPr2 (σ : CwF_SigTypeFormer) (p1 : CwF_SigPr1 σ) :UU\n:= ∏ Γ (A : Ty Γ : hSet) (B : Ty(Γ.:A) : hSet)\n(c : tm (σ _ A B) ), tm (DepTypesType B (p1 _ _ _ c)).\n\nDefinition CwF_SigPr2Nat (σ : CwF_SigTypeFormer) (nσ : CwF_SigTypeNat σ) (p1 : CwF_SigPr1 σ)\n(np1 : CwF_SigPr1Nat σ nσ p1) (p2 : CwF_SigPr2 σ p1) \n: UU := ∏ (Γ Δ : C) (f : C^op ⟦ Γ, Δ ⟧) (A : Ty Γ : hSet) (B : Ty (Γ .: A) : hSet)\n(c : tm (σ Γ A B)),\nreind_tm f (p2 Γ A B c) = tm_transportf (! DepTypesNat B f (p1 Γ A B c))\n(tm_transportf (DepTypesrewrite (# Ty (qq_term A f) B)\n(p1 Δ (# Ty f A) (# Ty (qq_term A f) B) (tm_transportf (nσ Γ Δ f A B) (reind_tm f c)))\n(reind_tm f (p1 Γ A B c)) (maponpaths pr1 (! np1 Γ Δ f A B c)))\n(p2 Δ (# Ty f A) (# Ty (qq_term A f) B) (tm_transportf (nσ Γ Δ f A B) (reind_tm f c)))).\n\nDefinition CwF_SigAbsPr1 (σ : CwF_SigTypeFormer) (pair : CwF_SigAbs σ) (p1 : CwF_SigPr1 σ)\n: UU := ∏ Γ (A : Ty Γ : hSet) (B : Ty(Γ.:A) : hSet) (a : tm A) (b : tm (DepTypesType B a)),\np1 _ _ _ (pair _  _ _ a b) = a.\n\nDefinition CwF_SigAbsPr2 (σ : CwF_SigTypeFormer) (pair : CwF_SigAbs σ) (p1 : CwF_SigPr1 σ)\n(p2 : CwF_SigPr2 σ p1) (Ap1 : CwF_SigAbsPr1 σ pair p1)\n: UU := ∏ (Γ : C^op) (A : Ty Γ : hSet) (B : Ty (Γ .: A) : hSet)\n(a : tm A) (b : tm (DepTypesType B a)),\nb = tm_transportf\n(DepTypesrewrite B (p1 Γ A B (pair Γ A B a b)) a (maponpaths pr1 (Ap1 Γ A B a b)))\n(p2 Γ A B (pair Γ A B a b)).\n\nDefinition CwF_SigAbsPr (σ : CwF_SigTypeFormer) (pair : CwF_SigAbs σ)\n(p1 : CwF_SigPr1 σ) (p2 : CwF_SigPr2 σ p1) : UU\n:= ∏ Γ (A : Ty Γ : hSet) (B : Ty(Γ.:A) : hSet) (c : tm (σ _ A B)),\npair _ _ _ (p1 _ _ _ c) (p2 _ _ _ c ) = c.\n\nEnd Sigma_structure.\n\nSection Identity_Structure.\n  (** Identity Types over a Category with famillies *)\n\nDefinition CwF_IdTypeFormer : UU \n:= ∏ (Γ : C) (A : Ty Γ : hSet) (a b : tm A), Ty Γ : hSet.\n\nDefinition CwF_IdTypeNat (id : CwF_IdTypeFormer) : UU \n:= ∏ (Γ Δ : C) (f : C^op ⟦Γ,Δ⟧) (A : Ty Γ : hSet) (a b : tm A),\n#Ty f (id _ A a b)  = id _ (#Ty f A) (reind_tm f a) (reind_tm f b).\n\nDefinition CwF_IdRefl (Id : CwF_IdTypeFormer) : UU \n:= ∏ Γ (A: Ty Γ :hSet) (a :tm A), tm (Id _ _ a a).\n\nDefinition CwF_IdReflNatContext (Id : CwF_IdTypeFormer) (nid : CwF_IdTypeNat Id)\n(refl : CwF_IdRefl Id) : UU\n:= ∏ (Γ Δ : C) (f : C^op ⟦Γ,Δ⟧) (A : Ty Γ : hSet) (a : tm A),\nreind_tm f (refl _ A a) =\ntm_transportf (!(nid _ _ f _ a a)) (refl _ (#Ty f A) (reind_tm f a)).\n\nDefinition CwF_maponpathsIdForm {Id : CwF_IdTypeFormer}\n{Γ} {A A'} (e_A : A = A')\n{a} {a'} (e_a : a = tm_transportb e_A a')\n{b} {b'} (e_b : b = tm_transportb e_A b')\n: Id Γ A a b = Id Γ A' a' b'.\nProof.\n  destruct e_A.\n  rewrite (tm_transportbf _) in e_a, e_b;\n   cbn in e_a, e_b.\n  apply Auxiliary.maponpaths_12; assumption.\nQed.\n\nDefinition CwF_IdBasedFam (Id : CwF_IdTypeFormer) {Γ : C} (A : Ty Γ : hSet) (a : tm A)\n: Ty (Γ.:A) : hSet := Id _ _ (reind_tm _ a) (te A).\n\nDefinition CwF_IdBasedFamNatural (Id : CwF_IdTypeFormer) (nid : CwF_IdTypeNat Id)\n{Γ Δ : C} (f : C^op ⟦Γ,Δ⟧) (A : Ty Γ : hSet) (a : tm A)\n: #Ty (qq_term A f) (CwF_IdBasedFam Id A a) = CwF_IdBasedFam Id _ (reind_tm f a).\nProof.\n  unfold CwF_IdBasedFam.\n  etrans.\n  -  exact (nid _ _ (qq_term A f) _ _ _).\n  -  use CwF_maponpathsIdForm.\n     --  refine (!(Ty_composition _ _ A) @ _).\n         apply pathsinv0, (pathscomp0 (!(Ty_composition _ _ A))).\n         refine ((toforallpaths _ _ _ _) A).\n         exact (maponpaths _ (qq_term_pullback _ _)).\n     --  etrans. {apply pathsinv0, tm_transport_compose. }\n         etrans. 2: { apply maponpaths, tm_transport_compose. }\n         etrans. 2: {rewrite tm_transportbf; apply  tm_transportf_compose. }\n         etrans. {eapply maponpaths. refine (maponpaths_2_reind_tm _ _). \n         apply (!(qq_term_pullback _ _)). }\n         etrans. { rewrite tm_transportbf; apply (!(tm_transportf_compose _ _ _)). }\n         apply tm_transportf_irrelevant.\n     --  apply subtypePath; [intro x; apply (setproperty (Ty _ : hSet))|\n         rewrite tm_transportbf ;apply qq_term_te].\nQed.\n\nDefinition CwF_Id_map {Id} (nid : CwF_IdTypeNat Id) {Γ} {A : Ty Γ : hSet} (a : tm A) (b : tm A) (eqab : tm (Id _ _ a b))\n: C⟦Γ,_.:CwF_IdBasedFam Id A a⟧.\nProof.\n  simple refine (γ_qq (Yo^-1 (γ b)) _). unfold CwF_IdBasedFam.\n  simple refine (tm_transportb _ eqab).\n  abstract(\n  simple refine (nid  _ _ _ _ _ _ @ _);\n  use CwF_maponpathsIdForm;\n  [ apply Ty_γ_id\n  | rewrite tm_transportbf ;\n    refine (_ @ tm_transportf_irrelevant _ _ _);\n    simple refine (tm_transportf_bind (!reind_compose_tm' _ _ _) _);\n    [ apply (pathscomp0 (!(Ty_γ_id b))) , (!(Ty_composition _ _ _)) |\n      simple refine (maponpaths_2_reind_tm _ _ @ _);\n      [exact (identity _) | apply γ_pi |\n      rewrite tm_transportbf; apply (pathscomp0 (reind_id_tm' _ _ _));\n      apply tm_transportf_irrelevant ]]\n  | apply subtypePath;\n    [  intros x; apply (setproperty (Ty Γ : hSet))\n     | rewrite tm_transportbf; apply te_subtitution]]).\nDefined.\n\nDefinition CwF_IdBased_path_inducton {Id} (nid : CwF_IdTypeNat Id) (refl : CwF_IdRefl Id) := ∏ Γ (A : Ty Γ : hSet) (a : tm A)\n(P : Ty (_ .: CwF_IdBasedFam Id A a) :  hSet)\n(d : tm  (#Ty (CwF_Id_map nid a a (refl _ _ a)) P))\n(b : tm A) (eqab : tm (Id _ _ a b)), \ntm (#Ty (CwF_Id_map nid a b eqab) P).\n\nEnd Identity_Structure.\nEnd Fix_Category.\n", "meta": {"author": "tvignon", "repo": "InternshipM1", "sha": "eabe789f79484ef9963513efe93532702cf5106f", "save_path": "github-repos/coq/tvignon-InternshipM1", "path": "github-repos/coq/tvignon-InternshipM1/InternshipM1-eabe789f79484ef9963513efe93532702cf5106f/Coq/CwF_Structure_Display.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.25919102195464006}}
{"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 sep_lemma.\nRequire Import reg_lemma.\n\nRequire Import ctxswitch_spec.\n\nOpen Scope nat.\nOpen Scope code_scope.\nOpen Scope mem_scope.\n\n(*+ Lemmas about TimReduce +*)\nTheorem astar_TimReduce :\n  forall p q,\n    (p ** q) ↓ = (p ↓) ** (q ↓).\nProof.\n  intros; simpl; eauto.\nQed.\n\nTheorem GenRegs_TimeReduce :\n  forall grst p,\n    (GenRegs grst ** p) ↓ = GenRegs grst ** (p ↓).\nProof.\n  intros.\n  simpl.\n  destruct grst.\n  destruct p0.\n  destruct p0.\n  destruct f1, f2, f0, f.\n  simpl.\n  eauto.\nQed.\n\nTheorem GenRegs_rm_one_TimReduce' :\n  forall grst (rr : GenReg) ,\n    GenRegs_rm_one grst rr ↓ = GenRegs_rm_one grst rr.\nProof. \n  intros.\n  simpl.\n  destruct grst.\n  destruct p.\n  destruct p.\n  destruct f1, f2, f0, f.\n  simpls.\n  destruct rr; simpls; eauto.\nQed.\n\nTheorem GenRegs_rm_one_TimReduce :\n  forall grst (rr : GenReg) p,\n    (GenRegs_rm_one grst rr ** p) ↓ = GenRegs_rm_one grst rr ** (p ↓).\nProof.\n  intros.\n  simpl.\n  rewrite GenRegs_rm_one_TimReduce'; eauto.\nQed.\n  \nTheorem FrameState_TimeReduce :\n  forall id vi F p,\n    (FrameState id vi F ** p) ↓ = FrameState id vi F ** (p ↓).\nProof.\n  intros.\n  simpls.\n  unfold FrameState.\n  eauto.\nQed.\n\nTheorem RegSt_TimeReduce :\n  forall rn v p,\n    (rn |=> v ** p) ↓ = rn |=> v ** (p ↓).\nProof.\n  intros.\n  simpl; eauto.\nQed.\n\nTheorem MemSto_TimeReduce :\n  forall l v p,\n    (l |-> v ** p) ↓ = l |-> v ** (p ↓).\nProof.\n  intros.\n  simpl; eauto.\nQed.\n\nLemma save_reg_TimeReduce' :\n  forall n l vl,\n    save_reg l n vl ↓ = save_reg l n vl.\nProof.\n  intro n.\n  induction n; intros.\n  -\n    simpls.\n    destruct vl; eauto.\n  -\n    destruct vl.\n    {\n      simpl.\n      eauto.\n    }\n    {\n      simpl.\n      rewrite IHn; eauto.\n    }\nQed.\n\nLemma save_reg_TimeReduce :\n  forall n l vl p,\n    (save_reg l n vl ** p) ↓ = save_reg l n vl ** (p ↓).\nProof.\n  intros.\n  simpl.\n  rewrite save_reg_TimeReduce'; eauto.\nQed.\n\nTheorem Context_TimeReduce' :\n  forall ctx,\n    (context ctx) ↓ = context ctx.\nProof.\n  intros.\n  unfold context.\n  destruct ctx.\n  destruct p.\n  destruct p.\n  destruct p.\n  unfold context'.\n  repeat (rewrite save_reg_TimeReduce; eauto).\nQed.\n\nTheorem Context_TimeReduce :\n  forall ctx p,\n    (context ctx ** p) ↓ = context ctx ** (p ↓).\nProof.\n  intros.\n  simpls.\n  unfold context.\n  destruct ctx.\n  destruct p0.\n  destruct p0.\n  destruct p0.\n  unfold context'.\n  do 3 rewrite save_reg_TimeReduce.\n  simpl; eauto.\nQed.\n\nLemma stack_seg_TimeReduce :\n  forall l fm,\n    stack_seg l fm ↓ = stack_seg l fm.\nProof.\n  intros.\n  destruct fm.\n  unfold stack_seg.\n  simpl; eauto.\nQed.\n\nLemma stack_frame_TimeReduce :\n  forall l fm1 fm2,\n    stack_frame l fm1 fm2 ↓ = stack_frame l fm1 fm2.\nProof.\n  intros.\n  unfold stack_frame.\n  rewrite astar_TimReduce.\n  do 2 rewrite stack_seg_TimeReduce.\n  simpl; eauto.\nQed.\n\nLemma Stk_TimeReduce' :\n  forall lfp l,\n    stack' l lfp ↓ = stack' l lfp.\nProof.\n  intro lfp.\n  induction lfp; intros.\n  -\n    simpl; eauto.\n  -\n    simpl. \n    destruct a.\n    simpl.\n    do 2 rewrite stack_seg_TimeReduce; eauto.\n    rewrite IHlfp; eauto.\nQed.\n\nLemma Stk_TimeReduce1 :\n  forall stk,\n    stack stk ↓ = stack stk.\nProof.\n  intros.\n  unfold stack.\n  destruct stk.\n  rewrite Stk_TimeReduce'; eauto.\nQed.\n\nTheorem Stk_TimeReduce :\n  forall stk p,\n    (stack stk ** p) ↓ = stack stk ** (p ↓).\nProof.\n  intros.\n  destruct stk.\n  unfold stack.\n  simpl.\n  rewrite Stk_TimeReduce'; eauto.\nQed.\n\nTheorem conj_TimeReduce :\n  forall p1 p2,\n    (p1 //\\\\ p2) ↓ = (p1 ↓) //\\\\ (p2 ↓).\nProof.\n  intros; eauto.\nQed.\n\nTheorem disj_TimeReduce :\n  forall p1 p2,\n    (p1 \\\\// p2) ↓ = (p1 ↓) \\\\// (p2 ↓).\nProof.\n  intros; eauto.\nQed.\n\nTheorem pure_TimeReduce :\n  forall pu p,\n    ([| pu |] ** p) ↓ = [| pu |] ** (p ↓).\nProof.\n  intros; eauto.\nQed.\n\nTheorem Atrue_TimeReduce :\n  forall p,\n    (Atrue ** p) ↓ = Atrue ** (p ↓).\nProof.\n  intros; eauto.\nQed.\n\nTheorem Afalse_TimReduce :\n  forall p,\n    (Afalse ** p) ↓ = Afalse ** (p ↓).\nProof.\n  intros; eauto.\nQed.\n\nLtac TimReduce_simpl :=\n  match goal with\n  | |- context [(context ?ctx) ↓] =>\n    rewrite Context_TimeReduce'; TimReduce_simpl\n  | |- context [(stack ?stk) ↓] =>\n    rewrite Stk_TimeReduce1; TimReduce_simpl\n  | |- context [(GenRegs ?grst ** ?p) ↓] =>\n    rewrite GenRegs_TimeReduce; TimReduce_simpl\n  | |- context [(GenRegs_rm_one ?grst ?rr ** ?p) ↓] =>\n    rewrite GenRegs_rm_one_TimReduce; TimReduce_simpl\n  | |- context [(FrameState ?id ?vi ?F ** ?p) ↓] =>\n    rewrite FrameState_TimeReduce; TimReduce_simpl\n  | |- context [(?rn |=> ?v ** ?p) ↓] =>\n    rewrite RegSt_TimeReduce; TimReduce_simpl\n  | |- context [(?l |-> ?v ** ?p) ↓] =>\n    rewrite MemSto_TimeReduce; TimReduce_simpl\n  | |- context [(context ?ctx ** ?p) ↓] =>\n    rewrite Context_TimeReduce; TimReduce_simpl\n  | |- context [(stack ?stk ** ?p) ↓] =>\n    rewrite Stk_TimeReduce; TimReduce_simpl\n  | |- context [([| ?pu |] ** ?p) ↓] =>\n    rewrite pure_TimeReduce; TimReduce_simpl\n  | |- context [(Atrue ** ?p) ↓] =>\n    rewrite Atrue_TimeReduce; TimReduce_simpl\n  | |- context [(Afalse ** ?p) ↓] =>\n    rewrite Afalse_TimReduce; TimReduce_simpl\n  | |- context [(stack' _ _) ↓] =>\n    rewrite Stk_TimeReduce'; TimReduce_simpl\n  | |- context [(stack_frame _ _ _) ↓] =>\n    rewrite stack_frame_TimeReduce; TimReduce_simpl\n  | |- context [(GenRegs_rm_one ?grst ?rr) ↓] =>\n    rewrite GenRegs_rm_one_TimReduce'; TimReduce_simpl\n  | |- context [(?p1 //\\\\ ?p2) ↓] =>\n    rewrite conj_TimeReduce; TimReduce_simpl\n  | |- context [(?p1 \\\\// ?p2) ↓] =>\n    rewrite disj_TimeReduce; TimReduce_simpl\n  | |- context [(?p1 ** ?p2) ↓] =>\n    rewrite astar_TimReduce; TimReduce_simpl\n  | _ => simpl TimReduce\n  end.\n\nLtac TimReduce_simpl_in H :=\n  match type of H with\n  | _ |= ?p =>\n    match p with\n    | context [(GenRegs ?grst ** ?p) ↓] =>\n      rewrite GenRegs_TimeReduce in H; TimReduce_simpl_in H\n    | context [(FrameState ?id ?vi ?F ** ?p) ↓] =>\n      rewrite FrameState_TimeReduce in H; TimReduce_simpl_in H\n    | context [(?rn |=> ?v ** ?p) ↓] =>\n      rewrite RegSt_TimeReduce in H; TimReduce_simpl_in H\n    | context [(?l |-> ?v ** ?p) ↓] =>\n      rewrite MemSto_TimeReduce in H; TimReduce_simpl_in H\n    | context [(context ?ctx ** ?p) ↓] =>\n      rewrite Context_TimeReduce in H; TimReduce_simpl_in H\n    | context [(stack ?stk ** ?p) ↓] =>\n      rewrite Stk_TimeReduce in H; TimReduce_simpl_in H\n    | context [([| ?pu |] ** ?p) ↓] =>\n      rewrite pure_TimeReduce in H; TimReduce_simpl_in H\n    | context [(Atrue ** ?p) ↓] =>\n      rewrite Atrue_TimeReduce in H; TimReduce_simpl_in H\n    | context [(Afalse ** ?p) ↓] =>\n      rewrite Afalse_TimReduce in H; TimReduce_simpl_in H\n    | context [(?p1 //\\\\ ?p2) ↓] =>\n      rewrite conj_TimeReduce in H; TimReduce_simpl_in H\n    | context [(?p1 \\\\// ?p2) ↓] =>\n      rewrite disj_TimeReduce in H; TimReduce_simpl_in H\n    | _ => simpl TimReduce in H\n    end\n  end.\n\n(*+ Lemmas about DlyFrameFree +*)\nLemma Atrue_DlyFrameFree :\n  forall p,\n    DlyFrameFree p -> DlyFrameFree (Atrue ** p).\nProof.\n  intros.\n  simpl; eauto.\nQed.\n\nLemma Afalse_DlyFrameFree :\n  forall p,\n    DlyFrameFree p -> DlyFrameFree (Afalse ** p).\nProof.\n  intros.\n  simpl; eauto.\nQed.\n\nLemma RegSt_DlyFrameFree :\n  forall rn v p,\n    DlyFrameFree p -> DlyFrameFree (rn |=> v ** p).\nProof.\n  intros.\n  simpl; eauto.\nQed.\n\nLemma MapSto_DlyFrameFree :\n  forall l v p,\n    DlyFrameFree p -> DlyFrameFree (l |-> v ** p).\nProof.\n  intros.\n  simpl; eauto.\nQed.\n\nLemma astar_DlyFrameFree :\n  forall p1 p2,\n    DlyFrameFree p1 -> DlyFrameFree p2 -> DlyFrameFree (p1 ** p2).\nProof.\n  intros.\n  simpl; eauto.\nQed.\n\nLemma save_reg_DlyFrameFree' :\n  forall n l vl,\n    DlyFrameFree (save_reg l n vl).\nProof.\n  intro n.\n  induction n; intros.\n  -\n    simpls; eauto.\n    destruct vl; eauto.\n    simpl; eauto.\n    simpl; eauto.\n  -\n    destruct vl; simpl; eauto.\nQed.\n  \nLemma save_reg_DlyFrameFree :\n  forall n l vl p,\n    DlyFrameFree p ->\n    DlyFrameFree (save_reg l n vl ** p).\nProof.\n  intros.\n  eapply astar_DlyFrameFree; eauto.\n  eapply save_reg_DlyFrameFree'.\nQed.\n\nLemma Context_DlyFrameFree' :\n  forall l rl ri rg ry,\n    DlyFrameFree (context' l rl ri rg ry).\nProof.\n  intros.\n  unfold context'.\n  do 3 (eapply save_reg_DlyFrameFree; eauto).\n  simpl; eauto.\nQed.\n\nLemma Context_DlyFrameFree :\n  forall ctx p,\n    DlyFrameFree p -> DlyFrameFree (context ctx ** p).\nProof.\n  intros.\n  unfold context.\n  destruct ctx.\n  destruct p0.\n  destruct p0.\n  destruct p0.\n  eapply astar_DlyFrameFree; eauto.\n  eapply Context_DlyFrameFree'; eauto.\nQed.\n\nLemma Stack_DlyFrameFree' :\n  forall lfp l,\n    DlyFrameFree (stack' l lfp).\nProof.\n  intro lfp.\n  induction lfp; intros.\n  -\n    simpls; eauto.\n  -\n    destruct a.\n    simpl.\n    repeat (split; eauto).\n    destruct f.\n    simpl.\n    repeat (split; eauto).\n    destruct f0.\n    simpl.\n    repeat (split; eauto).\nQed.\n\nLemma Stack_DlyFrameFree :\n  forall stk p,\n    DlyFrameFree p -> DlyFrameFree (stack stk ** p).\nProof.\n  intros.\n  unfold stack.\n  destruct stk; eauto.\n  eapply astar_DlyFrameFree; eauto.\n  eapply Stack_DlyFrameFree'; eauto.\nQed.\n  \nLtac DlyFrameFree_elim :=\n  match goal with\n  | |- DlyFrameFree (Atrue ** ?p) =>\n    eapply Atrue_DlyFrameFree; DlyFrameFree_elim\n  | |- DlyFrameFree (Afalse ** ?p) =>\n    eapply Afalse_DlyFrameFree; DlyFrameFree_elim\n  | |- DlyFrameFree (?rn |=> ?v ** ?p) =>\n    eapply RegSt_DlyFrameFree; DlyFrameFree_elim\n  | |- DlyFrameFree (?l |-> ?v ** ?p) =>\n    eapply MapSto_DlyFrameFree; DlyFrameFree_elim\n  | |- DlyFrameFree (context ?ctx ** ?p) =>\n    eapply Context_DlyFrameFree; DlyFrameFree_elim\n  | |- DlyFrameFree (stack ?stk ** ?p) =>\n    eapply Stack_DlyFrameFree; DlyFrameFree_elim\n  | _ =>\n    try solve [simpl; eauto]\n  end.", "meta": {"author": "luckywangwang", "repo": "CertiSparc", "sha": "b5c4ff0d1b723537a645b6c5578b8749ed1c813e", "save_path": "github-repos/coq/luckywangwang-CertiSparc", "path": "github-repos/coq/luckywangwang-CertiSparc/CertiSparc-b5c4ff0d1b723537a645b6c5578b8749ed1c813e/coqimp/contextswitch/lib/tm_dly_lemma.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2591728066068927}}
{"text": "(* Distributed under the terms of the MIT license. *)\nSet Warnings \"-notation-overridden\".\n\nFrom MetaCoq.Utils Require Import utils.\nFrom MetaCoq.Template Require Import All Checker.\nFrom MetaCoq.Translations Require Import translation_utils MiniHoTT.\nImport MCMonadNotation.\n\nUnset MetaCoq Strict Unquote Universe Mode.\n\nLocal Set Primitive Projections.\nRecord prod A B := pair { π1 : A ; π2 : B }.\n\nArguments π1 {_ _} _.\nArguments π2 {_ _} _.\nArguments pair {_ _} _ _.\n\nDeclare Scope prod_scope.\nNotation \"( x ; y )\" := (pair x y) : prod_scope.\nNotation \" A × B \" := (prod A B) : type_scope.\nOpen Scope prod_scope.\n\nMetaCoq Quote Definition tprod := prod.\nMetaCoq Quote Definition tpair := @pair.\nMetaCoq Run (t <- tmQuote prod ;;\n            match t with\n            | tInd i _ => tmDefinition \"prod_ind\" i\n            | _ => tmFail \"bug\"\n            end).\nDefinition proj1 (t : term) : term\n  := tProj (mkProjection prod_ind 2 0) t.\nDefinition proj2 (t : term) : term\n  := tProj (mkProjection prod_ind 2 (S 0)) t.\n\nMetaCoq Quote Definition tbool := bool.\nMetaCoq Quote Definition ttrue := true.\nDefinition timesBool (A : term) := tApp tprod [A; tbool].\nDefinition pairTrue typ tm := tApp tpair [typ; tbool; tm; ttrue].\n\n\n\n\nLocal Instance tit : config.checker_flags := config.type_in_type.\nLocal Existing Instance Checker.default_fuel.\n\nFixpoint tsl_rec (fuel : nat) (Σ : global_env_ext) (E : tsl_table) (Γ : context) (t : term) {struct fuel}\n  : tsl_result term :=\n  match fuel with\n  | O => raise NotEnoughFuel\n  | S fuel =>\n  match t with\n  | tRel  n => ret (tRel n)\n  | tSort s => ret (tSort s)\n\n  | tCast t c A => t' <- tsl_rec fuel Σ E Γ t ;;\n                  A' <- tsl_rec fuel Σ E Γ A ;;\n                  ret (tCast t' c A')\n\n  | tProd n A B => A' <- tsl_rec fuel Σ E Γ A ;;\n                  B' <- tsl_rec fuel Σ E (Γ ,, vass n A) B ;;\n                  ret (timesBool (tProd n A' B'))\n\n  | tLambda n A t => A' <- tsl_rec fuel Σ E Γ A ;;\n                    t' <- tsl_rec fuel Σ E (Γ ,, vass n A) t ;;\n                    match infer' Σ (Γ ,, vass n A) t with\n                    | Checked B =>\n                      B' <- tsl_rec fuel Σ E (Γ ,, vass n A) B ;;\n                      ret (pairTrue (tProd n A' B') (tLambda n A' t'))\n                    | TypeError t => raise (TypingError t)\n                    end\n\n  | tLetIn n t A u => t' <- tsl_rec fuel Σ E Γ t ;;\n                     A' <- tsl_rec fuel Σ E Γ A ;;\n                     u' <- tsl_rec fuel Σ E (Γ ,, vdef n t A) u ;;\n                     ret (tLetIn n t' A' u')\n\n  | tApp t us => t' <- tsl_rec fuel Σ E Γ t ;;\n                monad_fold_left (fun t u => u' <- tsl_rec fuel Σ E Γ u ;;\n                                         ret (tApp (proj1 t) [u'])) us t'\n\n  | tConst s univs => lookup_tsl_table' E (ConstRef s)\n  | tInd i univs => lookup_tsl_table' E (IndRef i)\n  | tConstruct i n univs => lookup_tsl_table' E (ConstructRef i n)\n  | tProj p t => t' <- tsl_rec fuel Σ E Γ t ;;\n                ret (tProj p t')\n\n  | tFix bodies n =>\n    Γ' <- monad_map (fun '{| dname := na; dtype := ty; dbody := b; rarg := r |} =>\n                      ty' <- tsl_rec fuel Σ E Γ ty ;;\n                      ret {| decl_name := na; decl_body := None; decl_type := ty'|})\n                   bodies;;\n    bodies' <- monad_map (fun '{| dname := na; dtype := ty; dbody := b; rarg := r |} =>\n                           ty' <- tsl_rec fuel Σ E Γ ty ;;\n                           b'  <- tsl_rec fuel Σ E (Γ ++ Γ') b ;;\n                           ret {| dname := na; dtype := ty';\n                                  dbody := b'; rarg := r |})\n                        bodies ;;\n    ret (tFix bodies' n)\n  | _ => raise TranslationNotHandeled (* var evar meta case cofix *)\n  end\n  end.\n\n\n(* Definition recompose_prod (nas : list name) (ts : list term) (u : term) *)\n(*   : term *)\n(*   := let nats := List.combine nas ts in *)\n(*      List.fold_right (fun t u => tProd (fst t) (snd t) u) u nats. *)\n\nDefinition combine' {A B} (p : list A * list B) : list (A * B)\n  := List.combine  (fst p) (snd p).\n\n\nFixpoint replace pat u t {struct t} :=\n  if eq_term uGraph.init_graph t pat then u else\n    match t with\n    | tCast t c A => tCast (replace pat u t) c (replace pat u A)\n    | tProd n A B => tProd n (replace pat u A) (replace (up pat) (up u) B)\n    | tLambda n A t => tLambda n (replace pat u A) (replace (up pat) (up u) t)\n    | tLetIn n t A B => tLetIn n (replace pat u t) (replace pat u A)\n                              (replace (up pat) (up u) B)\n    | tApp t us => tApp (replace pat u t) (List.map (replace pat u) us)\n    | tProj p t => tProj p (replace pat u t)\n    | _ => t (* todo *)\n    end.\n\nFixpoint subst_app (t : term) (us : list term) : term :=\n  match t, us with\n  | tLambda _ A t, u :: us => subst_app (t {0 := u}) us\n  | _, [] => t\n  | _, _ => mkApps t us\n  end.\n\n(* If tm of type typ = Π [A0] [A1] ... . [B], returns *)\n(* a term of type [Π A0 A1 ... . B] *)\nDefinition pouet (tm typ : term) : term.\n  simple refine (let '((names, types), last) := decompose_prod typ in\n                 let L' := List.fold_left _ (List.combine names types) [] in _).\n  exact (fun Γ' A => Γ' ,, vass (fst A) (snd A)).\n  refine (let args := fold_left_i (fun l i _ => tRel i :: l) L' [] in _).\n  refine (fst (List.fold_left _ L' (subst_app tm args, last))).\n  refine (fun '(tm, typ) decl =>\n            let A := tProd decl.(decl_name) decl.(decl_type) typ in\n            (pairTrue A (tLambda decl.(decl_name) decl.(decl_type) tm),\n             timesBool A)).\nDefined.\n\n\n\nDefinition tsl_mind_body (ΣE : tsl_context) (mp : modpath) (kn : kername)\n           (mind : mutual_inductive_body)\n  : tsl_result (tsl_table * list mutual_inductive_body).\n  refine (let tsl := fun Γ t => match tsl_rec fuel (fst ΣE) (snd ΣE) Γ t with\n                             | Success x => x\n                             | Error _ => todo \"tsl\"\n                             end in\n          let kn' := (mp, tsl_ident (snd kn)) in _).\n  unshelve refine (let LI := List.split (mapi _ mind.(ind_bodies)) in\n          ret (List.concat (fst LI),\n               [{| ind_npars := mind.(ind_npars);\n                   ind_params := _;\n                   ind_bodies := snd LI;\n                   ind_universes := mind.(ind_universes);\n                   ind_variance := mind.(ind_variance)|}])). (* FIXME always ok? *)\n  intros i ind.\n  simple refine (let ind_type' := _ in\n                 let ctors' := List.split (mapi _ ind.(ind_ctors)) in\n                 (_ :: fst ctors',\n                  {| ind_name := tsl_ident ind.(ind_name);\n                     ind_sort := ind.(ind_sort);\n                     ind_indices := ind.(ind_indices);\n                     ind_type := ind_type';\n                     ind_kelim := ind.(ind_kelim);\n                     ind_ctors := snd ctors';\n                     ind_projs := [];\n                     ind_relevance := ind.(ind_relevance) |})).\n  + (* arity *)\n    refine (let L := decompose_prod ind.(ind_type) in _).\n    simple refine (let L' := List.fold_left _ (combine' (fst L)) [] in _).\n    exact (fun Γ' A => Γ' ,, vass (fst A) (tsl Γ' (snd A))).\n    refine (List.fold_left _ L' (snd L)).\n    exact (fun t decl => tProd decl.(decl_name) decl.(decl_type) t).\n  + (* constructors *)\n    intros k [name argctx indices typ nargs].\n    simple refine (let ctor_type' := _ in\n                   ((ConstructRef (mkInd kn i) k,\n                     pouet (tConstruct (mkInd kn' i) k []) _),\n                    (Build_constructor_body (tsl_ident name) argctx indices ctor_type' nargs))).\n    * refine (fold_left_i (fun t i _ => replace (proj1 (tRel i)) (tRel i) t)\n                          mind.(ind_bodies) _).\n      refine (let L := decompose_prod typ in _).\n      simple refine (let L' := List.fold_left _ (combine' (fst L))\n                                              [] in _).\n      exact (fun Γ' A => Γ' ,, vass (fst A) (tsl Γ' (snd A))).\n      refine (List.fold_left _ L' _).\n      exact (fun t decl => tProd decl.(decl_name) decl.(decl_type) t).\n      exact (match snd L with\n             | tApp t us => tApp t (List.map (tsl L') us)\n             | _ as t => t\n             end).\n    * refine (fold_left_i (fun t l _ => replace (tRel l) (tInd (mkInd kn' i) []) t)\n                          mind.(ind_bodies) ctor_type').\n  + (* table *)\n    refine (IndRef (mkInd kn i), pouet (tInd (mkInd kn' i) []) ind_type').\n  + exact mind.(ind_finite).\n  + (* parameters *)\n    simple refine (List.fold_right _ [] (mind.(ind_params))).\n    exact (fun A Γ' => Γ' ,, vass (decl_name A) (tsl Γ' (decl_type A))).\nDefined.\n\n\nFixpoint refresh_universes (t : term) {struct t} :=\n  match t with\n  | tSort s => tSort (if Universe.is_level s then s else fresh_universe)\n  | tProd na b t => tProd na b (refresh_universes t)\n  | tLetIn na b t' t => tLetIn na b t' (refresh_universes t)\n  | tCast x x0 x1 => tCast (refresh_universes x) x0 (refresh_universes x1)\n  | tLambda x x0 x1 => tLambda x (refresh_universes x0) (refresh_universes x1)\n  | tApp x x0 => tApp (refresh_universes x) (List.map refresh_universes x0)\n  | tProj x x0 => tProj x (refresh_universes x0)\n  | _ => t\n  end.\n\nGlobal Instance tsl_fun : Translation\n  := {| tsl_id := tsl_ident ;\n        tsl_tm := fun ΣE t => t' <- tsl_rec fuel (fst ΣE) (snd ΣE) [] t ;;\n                           ret (refresh_universes t');\n        tsl_ty := Some (fun ΣE t => t' <- tsl_rec fuel (fst ΣE) (snd ΣE) [] t ;;\n                                 ret (refresh_universes t')) ;\n        tsl_ind := tsl_mind_body |}.\n\n\nTactic Notation \"tSpecialize\" ident(H) uconstr(t)\n  := apply π1 in H; specialize (H t).\nTactic Notation \"tIntro\" ident(H)\n  := refine (fun H => _; true).\n\nDefinition NotFunext :=\n  ((forall (A B : Set) (f g : A -> B), (forall x:A, f x = g x) -> f = g) -> False).\n\nUnset Universe Checking.\n\nMetaCoq Run (TC <- TranslateRec emptyTC NotFunext ;;\n                     tmDefinition \"TC\" TC ;;\n                     Implement TC \"notFunext\" NotFunext).\nNext Obligation.\n  unfold NotFunextᵗ; cbn in *.\n  tIntro H.\n  tSpecialize H unit. tSpecialize H unit.\n  tSpecialize H (fun x => x; true). tSpecialize H (fun x => x; false).\n  tSpecialize H (fun x => eq_reflᵗ _ _; true).\n  inversion H.\nDefined.\n\nMetaCoq Run (Implement TC \"notη\" ((forall (A B : Set) (f : A -> B), f = fun x => f x) -> False)).\n\nNext Obligation.\n  tIntro H.\n  tSpecialize H unit. tSpecialize H unit.\n  tSpecialize H (fun x => x; false). cbn in H.\n  inversion H.\nDefined.\n\n(* Require Import Vector Even. *)\n(* Definition SS := S. *)\n(* MetaCoq Run (TC <- Translate emptyTC \"nat\" ;; *)\n(*                      TC <- Translate TC \"even\" ;; *)\n(*                      tmDefinition \"TC2\" TC). *)\n\n(* Inductive foo := *)\n(* | bar : (nat -> foo) -> foo. *)\n(* Definition bar' := bar. *)\n(* MetaCoq Run (TranslateRec TC2 bar'). *)\n\n\nDefinition UIP := forall A (x y : A) (p q : x = y), p = q.\n\n\nMetaCoq Run (TC <- TranslateRec TC UIP ;;\n                     tmDefinition \"eqTC\" TC).\n\nDefinition eqᵗ_eq {A} x y\n  : eqᵗ A x y -> x = y.\nProof.\n  destruct 1; reflexivity.\nDefined.\n\nDefinition eq_eqᵗ {A} x y\n  : x = y -> eqᵗ A x y.\nProof.\n  destruct 1; reflexivity.\nDefined.\n\nDefinition isequiv_eqᵗ_eq {A} x y\n  : IsEquiv (@eqᵗ_eq A x y).\nProof.\n  unshelve eapply isequiv_adjointify.\n  apply eq_eqᵗ.\n  all: intros []; reflexivity.\nDefined.\n\nTheorem preserves_UIP : UIP -> UIPᵗ.\nProof.\n  unfold UIP, UIPᵗ.\n  intros H.\n  tIntro A. tIntro x. tIntro y. tIntro p. tIntro q.\n  cbn in *.\n  apply eq_eqᵗ. refine (equiv_inj _ (H := isequiv_eqᵗ_eq _ _) _).\n  apply H.\nDefined.\n\n\nDefinition wFunext\n  := forall A (B : A -> Type) (f g : forall x, B x), (forall x, f x = g x) -> f = g.\n\n\nMetaCoq Run (TC <- TranslateRec eqTC (wFunext -> False) ;;\n                     tmDefinition \"eqTC'\" TC ;;\n                     Implement TC \"notwFunext\" (wFunext -> False)).\nNext Obligation.\n  tIntro H.\n  tSpecialize H unit. tSpecialize H (fun _ => unit; true).\n  tSpecialize H (fun x => x; true). tSpecialize H (fun x => x; false).\n  tSpecialize H (fun x => eq_reflᵗ _ _; true).\n  inversion H.\nDefined.\n\nDefinition wUnivalence\n  := forall A B, Equiv A B -> A = B.\n\nMetaCoq Run (TC <- Translate eqTC' \"idpath\" ;;\n                     TC <- ImplementExisting TC \"paths_ind\" ;;\n                     tmDefinition \"eqTC''\" TC).\nNext Obligation.\n  tIntro A. tIntro a. tIntro P. tIntro t.\n  tIntro y. tIntro p. destruct p. exact t.\nDefined.\n\nMetaCoq Run (TC <- TranslateRec eqTC'' wUnivalence ;;\n                     tmDefinition \"eqTC3\" TC).\n\nTheorem preserves_wUnivalence : wUnivalence -> wUnivalenceᵗ.\nProof.\n  unfold wUnivalence, wUnivalenceᵗ.\n  intros H.\n  tIntro A. tIntro B. tIntro H.\n  cbn in *.\n  apply eq_eqᵗ. apply H0. destruct H as [[f bf] Hf]; cbn in *.\n  exists f. destruct Hf as [[g bg] [s _] [r _] _]; cbn in *.\n  unshelve eapply isequiv_adjointify. assumption.\n  all: intro; apply eqᵗ_eq; auto.\nDefined.\n\n\n\n\n\n\nDefinition bool_of_Equivᵗ {A B} (e : Equivᵗ A B) : bool.\n  now destruct e as [[_ b] _].\nDefined.\n\nDefinition UA := forall A B, IsEquiv (paths_ind A (fun B _ => Equiv A B) (equiv_idmap A) B).\n\nMetaCoq Run (TC <- Translate eqTC3 \"isequiv_idmap\" ;;\n                     TC <- Translate TC \"equiv_idmap\" ;;\n                     TC <- Translate TC \"UA\" ;;\n                     tmDefinition \"eqTC4\" TC).\n\nAxiom fx : Funext.\nAxiom ua : UA.\n\n\nLemma eqᵗ_unit_unit (e e' : eqᵗ Type unit unit) : e = e'.\n  refine (equiv_inj (eqᵗ_eq _ _) _).\n  - apply isequiv_eqᵗ_eq.\n  - refine (equiv_inj _ (H:=ua _ _) _).\n    apply path_equiv; cbn. apply fx.\n    apply fx. intro; apply path_unit.\nDefined.\n\n\nMetaCoq Run (Implement eqTC4 \"notUA\" (UA -> False)).\nNext Obligation.\n  unfold UAᵗ; tIntro ua.\n  tSpecialize ua unit.\n  tSpecialize ua unit.\n  destruct ua as [[g bg] H1 H2 _]; cbn -[paths_indᵗ] in *.\n  simple refine (let e1 := BuildEquivᵗ unit unit (idmap; true) _ in _); cbn. {\n    unshelve econstructor; cbn. exact (idmap; true).\n    all: tIntro x; reflexivity. }\n  simple refine (let e2 := BuildEquivᵗ unit unit (idmap; false) _ in _); cbn. {\n    unshelve econstructor; cbn. exact (idmap; true).\n    all: tIntro x; reflexivity. }\n  assert (e1 = e2). {\n    etransitivity. symmetry. eapply eqᵗ_eq.\n    exact (π1 H1 e1).\n    etransitivity. 2: eapply eqᵗ_eq; exact (π1 H1 e2).\n    clearbody e1 e2; clear.\n    assert (g e1 = g e2). apply eqᵗ_unit_unit.\n    now rewrite X. }\n  apply (f_equal bool_of_Equivᵗ) in X. cbn in X.\n  inversion X.\nDefined.\n", "meta": {"author": "MetaCoq", "repo": "metacoq", "sha": "c340242b43ebe26f3bacb1c72ef82b8ca61da632", "save_path": "github-repos/coq/MetaCoq-metacoq", "path": "github-repos/coq/MetaCoq-metacoq/metacoq-c340242b43ebe26f3bacb1c72ef82b8ca61da632/translations/times_bool_fun.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.25917279984343794}}
{"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\nRequire Import Coq.Classes.RelationClasses Coq.Relations.Relation_Definitions Coq.Classes.Morphisms.\nRequire Import Fiat.Common.Telescope.Core.\n\nModule Export Telescope.\n  Definition flattenT_R_lift {X : Type} {t : Telescope} (P : forall A, relation A -> Prop)\n             (R : relation X)\n             (H : P _ R)\n             (H_forall : forall A T (R' : forall a : A, relation (T a)),\n                           (forall a : A, P _ (R' a))\n                           -> P _ (forall_relation R'))\n  : P _ (@flattenT_R_relation X R t).\n  Proof.\n    repeat intro; induction t; simpl in *.\n    { assumption. }\n    { eauto with nocore. }\n  Defined.\n\n  Global Instance flattenT_R_Reflexive {t X R} {_ : @Reflexive X R}\n  : Reflexive (@flattenT_R_relation X R t)\n    := flattenT_R_lift (@Reflexive) R _ _.\n  Proof. lazy; eauto with nocore. Defined.\n\n  Global Instance flattenT_R_Symmetric {t X R} {_ : @Symmetric X R}\n  : Symmetric (@flattenT_R_relation X R t)\n    := flattenT_R_lift (@Symmetric) R _ _.\n  Proof. lazy; eauto with nocore. Defined.\n\n  Global Instance flattenT_R_Transitive {t X R} {_ : @Transitive X R}\n  : Transitive (@flattenT_R_relation X R t)\n    := flattenT_R_lift (@Transitive) R _ _.\n  Proof. lazy; eauto with nocore. Defined.\n\n  Global Instance flattenT_R_relation_flip_impl_Proper {t X R}\n         {H : Proper (Basics.flip R ==> R ==> Basics.flip Basics.impl)\n                     R}\n  : Proper (Basics.flip (flattenT_R_relation R) ==> flattenT_R_relation R ==> Basics.flip Basics.impl)\n           (@flattenT_R_relation X R t)\n    := @flattenT_R_lift X t (fun A R => Proper (Basics.flip R ==> R ==> Basics.flip Basics.impl) R) _ H _.\n  Proof.\n    unfold Proper, respectful, Basics.flip, Basics.impl, forall_relation in *; intros.\n    eauto with nocore.\n  Defined.\n\n  Global Instance flattenT_eq_Reflexive {t : Telescope} {X : Type}\n  : Reflexive (@flattenT_eq X t)\n    := flattenT_R_Reflexive.\n\n  Global Instance flattenT_eq_Symmetric {t : Telescope} {X : Type}\n  : Symmetric (@flattenT_eq X t)\n    := flattenT_R_Symmetric.\n\n  Global Instance flattenT_eq_Transitive {t : Telescope} {X : Type}\n  : Transitive (@flattenT_eq X t)\n    := flattenT_R_Transitive.\n\n  Global Instance flatten_forall_eq_relation_Reflexive {t P}\n  : Reflexive (@flatten_forall_eq_relation t P).\n  Proof.\n    hnf; induction t; simpl; unfold forall_relation; [ reflexivity | eauto with nocore ].\n  Defined.\n\n  Global Instance flatten_forall_eq_relation_Symmetric {t P}\n  : Symmetric (@flatten_forall_eq_relation t P).\n  Proof.\n    hnf; induction t; simpl; unfold forall_relation; [ symmetry; assumption | eauto with nocore ].\n  Defined.\n\n  Global Instance flatten_forall_eq_relation_Transitive {t P}\n  : Transitive (@flatten_forall_eq_relation t P).\n  Proof.\n    hnf; induction t; simpl; unfold forall_relation; [ etransitivity; eassumption | eauto with nocore ].\n  Defined.\n\n  Global Instance flatten_forall_eq_Reflexive {t P}\n  : Reflexive (@flatten_forall_eq t P)\n    := flatten_forall_eq_relation_Reflexive.\n\n  Global Instance flatten_forall_eq_Symmetric {t P}\n  : Symmetric (@flatten_forall_eq t P)\n    := flatten_forall_eq_relation_Symmetric.\n\n  Global Instance flatten_forall_eq_Transitive {t P}\n  : Transitive (@flatten_forall_eq t P)\n    := flatten_forall_eq_relation_Transitive.\n\n  Global Instance flatten_forall_eq_relation_with_assumption_Reflexive {t P Q}\n  : Reflexive (@flatten_forall_eq_relation_with_assumption t P Q).\n  Proof.\n    hnf; induction t; simpl; unfold forall_relation; [ reflexivity | eauto with nocore ].\n  Defined.\n\n  Global Instance flatten_forall_eq_relation_with_assumption_Symmetric {t P Q}\n  : Symmetric (@flatten_forall_eq_relation_with_assumption t P Q).\n  Proof.\n    hnf; induction t; simpl; unfold forall_relation; [ symmetry; eauto with nocore | eauto with nocore ].\n  Defined.\n\n  Global Instance flatten_forall_eq_relation_with_assumption_Transitive {t P Q}\n  : Transitive (@flatten_forall_eq_relation_with_assumption t P Q).\n  Proof.\n    hnf; induction t; simpl; unfold forall_relation; [ etransitivity; eauto with nocore | eauto with nocore ].\n  Defined.\n\n  Global Instance flatten_forall_eq_with_assumption_Reflexive {t P Q}\n  : Reflexive (@flatten_forall_eq_with_assumption t P Q)\n    := flatten_forall_eq_relation_with_assumption_Reflexive.\n\n  Global Instance flatten_forall_eq_with_assumption_Symmetric {t P Q}\n  : Symmetric (@flatten_forall_eq_with_assumption t P Q)\n    := flatten_forall_eq_relation_with_assumption_Symmetric.\n\n  Global Instance flatten_forall_eq_with_assumption_Transitive {t P Q}\n  : Transitive (@flatten_forall_eq_with_assumption t P Q)\n    := flatten_forall_eq_relation_with_assumption_Transitive.\n\n  Lemma flatten_append_forall_Proper {B P Q}\n  : forall f g,\n      @flatten_forall_eq B P f g\n      -> @flatten_append_forall B P Q f\n      -> @flatten_append_forall B P Q g.\n  Proof.\n    induction B; simpl in *; eauto with nocore.\n    intros; subst; assumption.\n  Defined.\n\n  Global Instance flattenT_unapply_Proper {t X}\n  : Proper (pointwise_relation _ eq ==> flattenT_eq)\n           (@flattenT_unapply t X).\n  Proof.\n    repeat intro; unfold pointwise_relation in *; induction t as [|?? IHt]; simpl in *;\n    auto with nocore.\n  Defined.\n\n  Global Instance flattenT_apply_Proper {t X}\n  : Proper (flattenT_eq ==> pointwise_relation _ eq)\n           (@flattenT_apply t X).\n  Proof.\n    repeat intro; unfold pointwise_relation in *; induction t as [|?? IHt]; simpl in *;\n    auto with nocore.\n  Defined.\n\n  Global Instance flatten_forall_unapply_Proper {t P}\n  : Proper (forall_relation (fun _ => eq) ==> flatten_forall_eq)\n           (@flatten_forall_unapply t P).\n  Proof.\n    repeat intro; unfold forall_relation in *; induction t as [|?? IHt]; simpl in *;\n    auto with nocore.\n  Defined.\n\n  Global Instance flatten_forall_apply_Proper {t P}\n  : Proper (flatten_forall_eq ==> forall_relation (fun _ => eq))\n           (@flatten_forall_apply t P).\n  Proof.\n    repeat intro; unfold forall_relation in *; induction t as [|?? IHt]; simpl in *;\n    auto with nocore.\n  Defined.\n\n  Global Instance flatten_forall_eq_rect_Proper {t P Q H}\n  : Proper (flatten_forall_eq ==> flatten_forall_eq)\n           (@flatten_forall_eq_rect t P Q H).\n  Proof.\n    repeat intro; unfold forall_relation in *; induction t as [|?? IHt]; simpl in *;\n    auto with nocore;\n    subst; simpl; reflexivity.\n  Defined.\nEnd Telescope.\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/Common/Telescope/Instances.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.25917279984343794}}
{"text": "(* SPDX-License-Identifier: GPL-2.0 *)\nRequire Import List.\nImport ListNotations.\n(* From RecordUpdate Require Import RecordSet. *)\n(* Import RecordSetNotations. *)\n\nRequire Import theorem4.Base theorem4.Promising.\n\n(* DRF-kernel constraint *)\n\nDefinition OwnershipMap := Address -> option TID.\n\nInductive rel_global_ownership : View -> OwnershipMap -> (View -> option Promise) -> OwnershipMap -> Prop :=\n| GO_EMPTY : forall om lp, rel_global_ownership 0 om lp om\n| GO_PULL : forall n om lp omr tid addr \n                (Hlp : rel_global_ownership n om lp omr)\n                (Hown : om addr = None)\n                (Hlp : lp (S n) = Some (PULL tid addr)),\n                rel_global_ownership (S n) (update om addr (Some tid)) lp omr\n| GO_PUSH : forall n om lp omr tid addr \n                (Hlp : rel_global_ownership n om lp omr)\n                (Hown : om addr = Some tid)\n                (Hlp : lp (S n) = Some (PUSH tid addr)),\n                rel_global_ownership (S n) (update om addr None) lp omr\n| GO_WRITE : forall n om lp omr tid val addr\n                (Hlp : rel_global_ownership n om lp omr)\n                (Hown : om addr = Some tid)\n                (Hlp : lp (S n) = Some (WRITE tid val addr)),\n                rel_global_ownership (S n) om lp omr\n| GO_NONE : forall n om lp omr\n                (Hlp : rel_global_ownership n om lp omr)\n                (Hlp : lp (S n) = None),\n                rel_global_ownership (S n) om lp omr.\n\n(* No-barrier-misuse constraint *)\n\nRecord LocalOwnership := mkLocalOwnership{\n    ownership_local : Address -> bool;\n    lastbarrier_local : Address -> View\n}.\n(* )Instance etaLocalOwnership : Settable _ := settable! mkLocalOwnership <ownership_local; lastbarrier_local>.\n *)\n\nDefinition update_ownership_local (a : LocalOwnership) b :=\n  mkLocalOwnership b (lastbarrier_local a).\nNotation \"a <|ownership_local := b |>\" := (update_ownership_local a b) (at level 1).\n\nDefinition update_lastbarrier_local (a : LocalOwnership) b :=\n  mkLocalOwnership (ownership_local a) b.\nNotation \"a <|lastbarrier_local := b |>\" := (update_lastbarrier_local a b) (at level 1).\nDefinition initownership := \n    {|\n        ownership_local := fun addr => false;\n        lastbarrier_local := fun addr => 0\n    |}.\n\nInductive rel_local_ownership : (View -> option Promise) -> list Event -> LocalOwnership -> Prop :=\n| LO_EMPTY : forall promises, rel_local_ownership promises [] initownership\n| LO_LOAD : forall promises le lo addr view reg \n                (Hlo : rel_local_ownership promises le lo)\n                (Hown : ownership_local lo addr = true),\n                rel_local_ownership promises ((LOAD addr view reg) :: le) lo\n| LO_STORE : forall promises le lo addr view reg\n                (Hlo : rel_local_ownership promises le lo)\n                (Hown : ownership_local lo addr = true),\n                rel_local_ownership promises ((STORE addr view reg) :: le) lo\n| LO_ACQ : forall promises le lo addr view\n                (Hlo : rel_local_ownership promises le lo)\n                (Hown : ownership_local lo addr = false)\n                (Hview : lastbarrier_local lo addr <= view),\n                rel_local_ownership promises ((ACQ view addr) :: le)\n                (lo \n                    <|ownership_local := update (ownership_local lo) addr true |>\n                    <|lastbarrier_local := update (lastbarrier_local lo) addr view |>\n                )\n| LO_REL : forall promises le lo addr view \n                (Hlo : rel_local_ownership promises le lo)\n                (Hown : ownership_local lo addr = true)\n                (Hview : lastbarrier_local lo addr <= view),\n                rel_local_ownership promises ((REL view addr) :: le)\n                (lo\n                    <|ownership_local := update (ownership_local lo) addr false |>\n                    <|lastbarrier_local := update (lastbarrier_local lo) addr view |>\n                )\n| LO_INTERNAL : forall promises le lo i\n                (Hlo : rel_local_ownership promises le lo),\n                rel_local_ownership promises ((INTERNAL i) :: le) lo\n| LO_ORACLE : forall promises le lo reg val\n                (Hlo : rel_local_ownership promises le lo),\n                rel_local_ownership promises ((ORACLE reg val) :: le) lo.\n\nInductive DRF : Trace -> Prop :=\n| DRF_TRACE : forall (t : Trace)  (n : View)\n                (Hglobal : exists om : OwnershipMap, rel_global_ownership n om (promiselist t) (fun _ => None))\n                (Hlocal : forall tid : TID, exists lo, rel_local_ownership (promiselist t) (executions t tid) lo),\n                DRF t.\n", "meta": {"author": "VeriGu", "repo": "VRM-proof", "sha": "9e3c9751f31713a133a0a7e98f3d4c9600ca7bde", "save_path": "github-repos/coq/VeriGu-VRM-proof", "path": "github-repos/coq/VeriGu-VRM-proof/VRM-proof-9e3c9751f31713a133a0a7e98f3d4c9600ca7bde/theorem4/DRF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2590814610652884}}
{"text": "Require Import VST.floyd.base2.\nRequire Import VST.floyd.client_lemmas.\n\nLocal Open Scope logic.\n\nLemma typed_true_nullptr:\n forall v t0 t t',\n   typed_true t0 (force_val (sem_cmp Ceq (tptr t) (tptr t') v (Vint Int.zero))) ->\n   v=nullval.\nProof.\n intros.\n simpl in H. rewrite !andb_false_r in H. simpl in H.\n unfold typed_true, force_val, sem_cmp_pp, strict_bool_val, nullval in *.\n destruct Archi.ptr64  eqn:Hp;\n destruct t0, v; inv H;\n unfold sem_cmp_pp, strict_bool_val in H1;\n try (clear i; rename i0 into i);\n pose proof (Int.eq_spec i Int.zero);\n destruct (Int.eq i Int.zero); inv H1; auto.\nQed.\n\n\nLemma typed_true_nullptr':\n  forall  {cs: compspecs} t0  t t' v,\n    typed_true t0 (eval_binop Cop.Oeq (tptr t) (tptr t') v nullval) -> v=nullval.\nProof.\n intros.\n simpl in H. unfold sem_binary_operation' in H.\n unfold tptr, typed_true, force_val, sem_cmp, Cop.classify_cmp, sem_cmp_pp, \n   typeconv, remove_attributes, change_attributes, strict_bool_val, nullval, Val.of_bool in *.\n   rewrite (proj2 (eqb_type_false (Tpointer t noattr) int_or_ptr_type)) in H\n     by (intro Hx; inv Hx).\n   rewrite (proj2 (eqb_type_false (Tpointer t' noattr) int_or_ptr_type)) in H\n     by (intro Hx; inv Hx).\n   simpl in H.\n destruct Archi.ptr64  eqn:Hp;\n destruct t0, v; inv H;\n try solve [revert H1; simple_if_tac; intro H1; inv H1].\n pose proof (Int64.eq_spec i0 Int64.zero);\n destruct (Int64.eq i0 Int64.zero); inv H1; auto.\n pose proof (Int.eq_spec i0 Int.zero);\n destruct (Int.eq i0 Int.zero); inv H1; auto.\nQed.\n\nLemma typed_true_Oeq_nullval:\n forall  {cs: compspecs}  v t t',\n   local (`(typed_true tint) (`(eval_binop Cop.Oeq (tptr t) (tptr t')) v `(nullval))) |--\n   local (`(eq nullval) v).\nProof.\nintros.\n intro rho; unfold local, lift1; unfold_lift.\n apply prop_derives; intro.\n unfold tptr in H; simpl in H. unfold sem_binary_operation' in H.\n simpl in H. rewrite !andb_false_r in H.\n destruct (v rho); inv H.\n unfold sem_cmp_pp, strict_bool_val, nullval in *.\n destruct Archi.ptr64  eqn:Hp; simpl in H1;\n try solve [inv H1];\n try solve [pose proof (Int64.eq_spec i Int64.zero);\n                destruct (Int64.eq i Int64.zero); inv H1; auto];\n try solve [pose proof (Int.eq_spec i Int.zero);\n                destruct (Int.eq i Int.zero); inv H1; auto].\nQed.\n\nDefinition  binary_operation_to_comparison (op: Cop.binary_operation) :=\n match op with\n | Cop.Oeq => Some (@eq Z)\n | Cop.One => Some Zne\n | Cop.Olt => Some Z.lt\n | Cop.Ole => Some Z.le\n | Cop.Ogt => Some Z.gt\n | Cop.Oge => Some Z.ge\n | _ => None\n end.\n\n(*\nLemma typed_true_binop_int:\n  forall op op' e1 e2 Espec  {cs: compspecs} Delta P Q R c Post,\n   binary_operation_to_comparison op = Some op' ->\n   typeof e1 = tint ->\n   typeof e2 = tint ->\n   (PROPx P (LOCALx (tc_env Delta :: Q) (SEPx R))) |--  tc_expr Delta e1 ->\n   (PROPx P (LOCALx (tc_env Delta :: Q) (SEPx R))) |-- tc_expr Delta e2 ->\n  @semax cs Espec Delta (PROPx P (LOCALx\n      (`op' (`force_signed_int (eval_expr e1)) (`force_signed_int (eval_expr e2))\n          :: Q) (SEPx R))) c Post ->\n  @semax cs Espec Delta (PROPx P (LOCALx\n      (`(typed_true\n          (typeof (Ebinop op e1 e2 tint)))\n          (eval_expr (Ebinop op e1 e2 tint)) :: Q) (SEPx R))) c Post.\nProof.\nintros.\neapply semax_pre; [clear H4 | apply H4].\neapply derives_trans with\n (tc_expr Delta e1 && (tc_expr Delta e2\n   && PROPx P (LOCALx (tc_environ Delta :: `(typed_true (typeof (Ebinop op e1 e2 tint)))(eval_expr (Ebinop op e1 e2 tint)) :: Q) (SEPx R)))).\nrewrite <- andp_assoc.\napply andp_right; auto.\ndo 2 rewrite <- insert_local.\nrewrite <- andp_assoc.\nrewrite (andp_comm (local _)).\nrewrite andp_assoc.\napply andp_left2.\nrewrite insert_local.\napply andp_right; auto.\nclear H2 H3.\n(*do 2 rewrite insert_local.*)\nunfold PROPx, LOCALx; intro rho; simpl.\nnormalize.\nautorewrite with norm1 norm2; normalize.\nrewrite <- andp_assoc.\napply andp_derives; auto.\neapply derives_trans.\napply andp_derives; apply typecheck_expr_sound; auto.\nnormalize. split; auto.\nrewrite H1,H0 in *.\nclear H5 H2 H0 H1.\ndestruct (eval_expr e1 rho); inv H6.\ndestruct (eval_expr e2 rho); inv H7.\nunfold force_signed_int, force_int.\nunfold typed_true, eval_binop in H4.\ndestruct op; inv H; simpl in H4.\npose proof (Int.eq_spec i i0); destruct (Int.eq i i0); subst; auto.\n contradiction H4; auto.\nunfold Zne.\npose proof (Int.eq_spec i i0); destruct (Int.eq i i0); subst; auto.\ncontradict H.\nrewrite <- (Int.repr_signed i).\nrewrite <- (Int.repr_signed i0).\nf_equal; auto.\nunfold Int.lt in H4.\ndestruct (zlt (Int.signed i) (Int.signed i0)); auto; contradict H4; auto.\nunfold Int.lt in H4.\ndestruct (zlt (Int.signed i0) (Int.signed i)); auto; try omega; contradict H4; auto.\nunfold Int.lt in H4.\ndestruct (zlt (Int.signed i0) (Int.signed i)); auto; try omega; contradict H4; auto.\nunfold Int.lt in H4.\ndestruct (zlt (Int.signed i) (Int.signed i0)); auto; try omega; contradict H4; auto.\nQed.\n*)\n\nDefinition  binary_operation_to_opp_comparison (op: Cop.binary_operation) :=\n match op with\n | Cop.Oeq => Some Zne\n | Cop.One => Some (@eq Z)\n | Cop.Olt => Some Z.ge\n | Cop.Ole => Some Z.gt\n | Cop.Ogt => Some Z.le\n | Cop.Oge => Some Z.lt\n | _ => None\n end.\n\n(*\nLemma typed_false_binop_int:\n  forall op op' e1 e2 Espec  {cs: compspecs} Delta P Q R c Post,\n   binary_operation_to_opp_comparison op = Some op' ->\n   typeof e1 = tint ->\n   typeof e2 = tint ->\n   (PROPx P (LOCALx (tc_environ Delta :: Q) (SEPx R))) |-- (tc_expr Delta e1) ->\n   (PROPx P (LOCALx (tc_environ Delta :: Q) (SEPx R))) |-- (tc_expr Delta e2) ->\n  @semax cs Espec Delta (PROPx P (LOCALx\n      (`op' (`force_signed_int (eval_expr e1)) (`force_signed_int (eval_expr e2))\n          :: Q) (SEPx R))) c Post ->\n  @semax cs Espec Delta (PROPx P (LOCALx\n      (`(typed_false\n          (typeof (Ebinop op e1 e2 tint)))\n          (eval_expr (Ebinop op e1 e2 tint)) :: Q) (SEPx R))) c Post.\nProof.\nintros.\neapply semax_pre; [clear H4 | apply H4].\neapply derives_trans with\n ( local (tc_environ Delta) && ((tc_expr Delta e1) && ( (tc_expr Delta e2)\n   && PROPx P (LOCALx (tc_environ Delta :: `(typed_false (typeof (Ebinop op e1 e2 tint)))(eval_expr (Ebinop op e1 e2 tint)) :: Q) (SEPx R))))).\napply andp_right.\nrewrite <- insert_local. apply andp_left1; auto.\nrewrite <- andp_assoc.\napply andp_right; auto.\ndo 2 rewrite <- insert_local.\nrewrite <- andp_assoc.\nrewrite (andp_comm (local _)).\nrewrite andp_assoc.\napply andp_left2.\nrewrite insert_local.\napply andp_right; auto.\nclear H2 H3.\nunfold PROPx, LOCALx; intro rho; simpl.\nunfold local,lift1 at 1.\napply derives_extract_prop; intro TCE.\neapply derives_trans.\napply andp_derives; [ apply typecheck_expr_sound; auto | ].\napply andp_derives; [ apply typecheck_expr_sound; auto | ].\napply derives_refl.\nnormalize. autorewrite with norm1 norm2; normalize.\napply andp_right; auto. apply prop_right.\nsplit; auto.\nclear H6 TCE.\nrewrite H0 in *; rewrite H1 in *.\nclear H0 H1 H4.\ndestruct (eval_expr e1 rho); inv H2.\ndestruct (eval_expr e2 rho); inv H3.\nunfold force_signed_int, force_int.\nunfold typed_true, eval_binop in H5.\ndestruct op; inv H; simpl in H5.\npose proof (Int.eq_spec i i0); destruct (Int.eq i i0); inv H5; auto.\nintro; apply H.\nrewrite <- (Int.repr_signed i).\nrewrite <- (Int.repr_signed i0).\nf_equal; auto.\npose proof (Int.eq_spec i i0); destruct (Int.eq i i0); inv H5; auto.\nunfold Int.lt in H5.\ndestruct (zlt (Int.signed i) (Int.signed i0)); inv H5; auto.\nunfold Int.lt in H5.\ndestruct (zlt (Int.signed i0) (Int.signed i)); inv H5; omega.\nunfold Int.lt in H5.\ndestruct (zlt (Int.signed i0) (Int.signed i)); inv H5; omega.\nunfold Int.lt in H5.\ndestruct (zlt (Int.signed i) (Int.signed i0)); inv H5; omega.\nQed.\n*)\n\nLemma typed_false_One_nullval:\n forall  {cs: compspecs}  v t t',\n   local (`(typed_false tint) (`(eval_binop Cop.One (tptr t) (tptr t')) v `(nullval))) |--\n    local (`(eq nullval) v).\nProof.\nintros.\n intro rho; unfold local, lift1; unfold_lift.\n apply prop_derives; intro.\n simpl in H. unfold sem_binary_operation' in H.\n simpl in H. rewrite !andb_false_r in H.\n unfold sem_cmp_pp, nullval in *.\n destruct Archi.ptr64 eqn:Hp;\n destruct (v rho); inv H.\n pose proof (Int64.eq_spec i Int64.zero).\n destruct (Int64.eq i Int64.zero); inv H1.\n reflexivity.\n pose proof (Int.eq_spec i Int.zero).\n destruct (Int.eq i Int.zero); inv H1.\n reflexivity.\nQed.\n\nLemma typed_true_One_nullval:\n forall  {cs: compspecs}  v t t',\n   local (`(typed_true tint) (`(eval_binop Cop.One (tptr t) (tptr t')) v `(nullval))) |--\n   local (`(ptr_neq nullval) v).\nProof.\nintros.\n intro rho; unfold local, lift1; unfold_lift.\n apply prop_derives; intro.\n simpl in H. unfold sem_binary_operation' in H.\n simpl in H. rewrite !andb_false_r in H.\n unfold sem_cmp_pp, ptr_neq, ptr_eq, nullval in *; simpl; intro.\n destruct (v rho); try contradiction.\n simpl in *.\n unfold typed_true, force_val, strict_bool_val in *.\n destruct Archi.ptr64 eqn:?; auto.\n destruct H0 as [? [? ?]].\n first [ pose proof (Int64.eq_spec Int64.zero i)\n        | pose proof (Int.eq_spec Int.zero i)];\n rewrite H1 in H3; \n subst; inv H.\nQed.\n\n\nLemma typed_false_Oeq_nullval:\n forall  {cs: compspecs} v t t',\n   local (`(typed_false tint) (`(eval_binop Cop.Oeq (tptr t) (tptr t')) v `(nullval))) |--\n   local (`(ptr_neq nullval) v).\nProof.\nintros. subst.\n unfold_lift; intro rho.  unfold local, lift1; apply prop_derives; intro.\n simpl in H. unfold sem_binary_operation' in H.\n simpl in H. rewrite !andb_false_r in H.\n intro. apply ptr_eq_e in H0. rewrite <- H0 in H.\n inv H.\nQed.\n\nLemma local_entail_at:\n  forall n S T (H: local (locald_denote S) |-- local (locald_denote T))\n    P Q R,\n    nth_error Q n = Some S ->\n    PROPx P (LOCALx Q (SEPx R)) |--\n    PROPx P (LOCALx (replace_nth n Q T) (SEPx R)).\nProof.\n intros.\n unfold PROPx, LOCALx; simpl; intro rho;  apply andp_derives; auto.\n apply andp_derives; auto.\n unfold local, lift1.\n specialize (H rho). unfold local,lift1 in H.\n revert Q H0; induction n; destruct Q; simpl; intros; inv H0.\n unfold_lift; repeat rewrite prop_and.\n apply andp_derives; auto.\n  unfold_lift; repeat rewrite prop_and.\n apply andp_derives; auto.\nQed.\n\nLemma local_entail_at_semax_0:\n  forall Espec {cs: compspecs}Delta P Q1 Q1' Q R c Post,\n   local (locald_denote Q1) |-- local (locald_denote Q1') ->\n   @semax cs Espec Delta (PROPx P (LOCALx (Q1'::Q) (SEPx R))) c Post  ->\n   @semax cs Espec Delta (PROPx P (LOCALx (Q1::Q) (SEPx R))) c Post.\nProof.\nintros.\neapply semax_pre0.\neapply (local_entail_at 0).\napply H. reflexivity.\nauto.\nQed.\n\n(*\nLtac simplify_typed_comparison :=\nmatch goal with\n| |- semax _ (PROPx _ (LOCALx (`(typed_true _) ?A :: _) _)) _ _ =>\n (eapply typed_true_binop_int;\n   [reflexivity | reflexivity | reflexivity\n   | try solve [go_lowerx; apply prop_right; auto ]\n   | try solve [go_lowerx; apply prop_right; auto ]\n   | ])\n ||\n  (let a := fresh \"a\" in set (a:=A); simpl in a; unfold a; clear a;\n   eapply local_entail_at_semax_0; [\n    first [ apply typed_true_Oeq_nullval\n           | apply typed_true_One_nullval\n           ]\n    |  ])\n| |- semax _ (PROPx _ (LOCALx (`(typed_false _) ?A :: _) _)) _ _ =>\n (eapply typed_false_binop_int;\n   [reflexivity | reflexivity | reflexivity\n   | try solve [go_lowerx; apply prop_right; auto ]\n   | try solve [go_lowerx; apply prop_right; auto ]\n   | ])\n ||\n  let a := fresh \"a\" in set (a:=A); simpl in a; unfold a; clear a;\n   eapply local_entail_at_semax_0; [\n    first [ apply typed_false_Oeq_nullval\n           | apply typed_false_One_nullval\n           ]\n    |  ]\n| |- _ => idtac\nend.\n*)\n\nDefinition compare_pp op p q :=\n   match p with\n            | Vptr b z =>\n               match q with\n               | Vptr b' z' => if eq_block b b'\n                              then Vint (if Ptrofs.cmpu op z z' then Int.one else Int.zero)\n                              else Vundef\n               | _ => Vundef\n               end\n             | _ => Vundef\n   end.\n\nLemma force_sem_cmp_pp:\n  forall op p q,\n  isptr p -> isptr q ->\n  force_val (sem_cmp_pp op p q) =\n   match op with\n   | Ceq => Vint (if eq_dec p q then Int.one else Int.zero)\n   | Cne => Vint (if eq_dec p q then Int.zero else Int.one)\n   | _ => compare_pp op p q\n   end.\nProof.\nintros.\ndestruct p; try contradiction.\ndestruct q; try contradiction.\nclear.\nunfold sem_cmp_pp, compare_pp, Ptrofs.cmpu, Val.cmplu_bool.\ndestruct Archi.ptr64 eqn:Hp.\ndestruct op; simpl; auto.\nif_tac. if_tac. inv H0. rewrite Ptrofs.eq_true; reflexivity.\nrewrite Ptrofs.eq_false by congruence; reflexivity.\nif_tac. congruence. reflexivity.\nif_tac. if_tac. inv H0. rewrite Ptrofs.eq_true by auto. reflexivity.\nrewrite Ptrofs.eq_false by congruence; reflexivity.\nrewrite if_false by congruence. reflexivity.\nif_tac; [destruct (Ptrofs.ltu i i0); reflexivity | reflexivity].\nif_tac; [destruct (Ptrofs.ltu i0 i); reflexivity | reflexivity].\nif_tac; [destruct (Ptrofs.ltu i0 i); reflexivity | reflexivity].\nif_tac; [destruct (Ptrofs.ltu i i0); reflexivity | reflexivity].\ndestruct op; simpl; auto; rewrite Hp.\nif_tac. if_tac. inv H0. rewrite Ptrofs.eq_true; reflexivity.\nrewrite Ptrofs.eq_false by congruence; reflexivity.\nif_tac. congruence. reflexivity.\nif_tac. if_tac. inv H0. rewrite Ptrofs.eq_true by auto. reflexivity.\nrewrite Ptrofs.eq_false by congruence; reflexivity.\nrewrite if_false by congruence. reflexivity.\nif_tac; [destruct (Ptrofs.ltu i i0); reflexivity | reflexivity].\nif_tac; [destruct (Ptrofs.ltu i0 i); reflexivity | reflexivity].\nif_tac; [destruct (Ptrofs.ltu i0 i); reflexivity | reflexivity].\nif_tac; [destruct (Ptrofs.ltu i i0); reflexivity | reflexivity].\nQed.\n\nHint Rewrite force_sem_cmp_pp using (now auto) : norm.\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/compare_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.259081449291354}}
{"text": "Require Import\n        Coq.omega.Omega\n        Coq.Strings.String\n        Coq.Vectors.Vector.\n\nRequire Import\n        Fiat.Computation\n        Fiat.Narcissus.Common.Specs\n        Fiat.Narcissus.Common.WordFacts\n        Fiat.Narcissus.Common.ComposeIf\n        Fiat.Narcissus.Common.ComposeOpt\n        Fiat.Narcissus.Automation.Solver\n        Fiat.Narcissus.BinLib.AlignedByteString\n        Fiat.Narcissus.BinLib.AlignWord\n        Fiat.Narcissus.BinLib.AlignedList\n        Fiat.Narcissus.BinLib.AlignedDecoders\n        Fiat.Narcissus.Formats.WordOpt\n        Fiat.Narcissus.Formats.NatOpt\n        Fiat.Narcissus.Formats.FixListOpt\n        Fiat.Narcissus.Stores.EmptyStore.\n\nInstance ByteStringQueueMonoid : Monoid ByteString := ByteStringQueueMonoid.\n\nDefinition simple_record := ((word 16) * list (word 8))%type.\n\nDefinition Simple_Format\n           (p : simple_record) :=\n        format_nat 8 (|snd p|)\n  ThenC format_word (fst p)\n  ThenC format_list format_word (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_format\n  : { numBytes : _ &\n    { v : _ &\n    { c : _ & forall (p : simple_record)\n                     (p_OK : Simply_OK p),\n          refine (Simple_Format p ())\n                 (ret (@build_aligned_ByteString (numBytes p) (v p), c p)) } } }.\nProof.\n  unfold Simple_Format.\n  eexists _, _, _; intros.\n  (* Step 1: simplification with monad laws so that any complex\n       subformats are inlined properly. (Not needed for this example) *)\n  eapply refine_refineEquiv_Proper;\n    [ unfold flip;\n      repeat first\n             [ etransitivity; [ apply refineEquiv_compose_compose with (monoid := monoid) | idtac ]\n             | etransitivity; [ apply refineEquiv_compose_Done with (monoid := monoid) | idtac ]\n             | apply refineEquiv_under_compose with (monoid := monoid) ];\n      intros; higher_order_reflexivity\n    | reflexivity | ].\n    etransitivity.\n    (* Replace formats with byte-aligned versions. *)\n    eapply AlignedFormatChar; eauto.\n    eapply AlignedFormat2Char; eauto.\n    eapply AlignedFormatListDoneC with (A_OK := fun _ => True); intros; eauto.\n    rewrite aligned_format_char_eq.\n    encoder_reflexivity.\n    encoder_reflexivity.\nDefined.\n\nDefinition byte_aligned_simple_encoder\n             (r : simple_record)\n  := Eval simpl in (projT1 (projT2 refine_simple_format) r).\n\nImport Vectors.VectorDef.VectorNotations.\nPrint byte_aligned_simple_encoder.\n\nDefinition Simple_Format_decoder\n  : CorrectDecoderFor Simply_OK Simple_Format.\nProof.\n  start_synthesizing_decoder.\n  normalize_compose monoid.\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 (proj1_sig Simple_Format_decoder).\n\nLtac 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 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 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 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": "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/Examples/ByteAlignedExample.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.259081449291354}}
{"text": "Require Import Coqlib.\nRequire Import AST.\nRequire Import Globalenvs.\nRequire Import Events.\nRequire Import Smallstep.\nRequire Import Asm.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Integers.\nRequire Import Axioms.\n\nRequire Import PeekLib.\nRequire Import PeekTactics.\nRequire Import PregTactics.\nRequire Import SplitLib.\nRequire Import StepLib.\nRequire Import StepIn.\nRequire Import AsmCallingConv.\nRequire Import StepEquiv.\nRequire Import FindInstrLib.\nRequire Import SameBlockLib.\nRequire Import ProgPropDec.\nRequire Import MemoryAxioms.\nRequire Import AsmBits.\nRequire Import ProgPropDec.\nRequire Import Zlen.\n\nDefinition measure_fun (z : Z) (st : state_bits) : nat :=\n  match st with\n    | State_bits rs m md =>\n      match rs PC with\n        | Values.Vint bits =>\n          match psur md bits with\n            | Some (b,i) => nat_of_Z (z - Int.unsigned i)\n            | None => O\n          end\n        | _ => O\n      end\n  end.\n\nLemma nat_of_Z_lt :\n  forall z z',\n    z >= 0 -> z' >= 0 ->\n    z < z' ->\n    (nat_of_Z z < nat_of_Z z')%nat.\nProof.\n  intros. unfold nat_of_Z.\n  apply Z2Nat.inj_lt; omega.\nQed.\n\nLemma instr_class :\n  forall i,\n    straightline i \\/ (exists l, labeled_jump i l) \\/ is_call_return i \\/ trace_internal i.\nProof.\n  intros.\n  destruct i; \n  try solve [left; unfold straightline; exact I];\n  try solve [right; left; unfold labeled_jump; eauto];\n  try solve [right; unfold is_call_return; auto].  \n  destruct tbl. left. simpl. reflexivity.\n  right. left. unfold labeled_jump. simpl. eauto.\n  right. right. right. simpl. exact I.\n  right. right. right. simpl. exact I.\nQed.  \n\nLemma in_code_at_code :\n  forall c z rs m ge md,\n    in_code z c ge (State_bits rs m md) ->\n    exists z' i,\n      at_code z' (i :: nil) 0 ge (State_bits rs m md) /\\ In i c.\nProof.\n  induction c; intros.\n  inv H. inv H1. simpl.\n  unfold zlen in *. simpl in *.\n  omega.\n  inv H. inv H1.\n  assert (ofs = 1 \\/ ofs > 1) by omega.\n  break_or. destruct c.\n  rewrite zlen_cons in H11. simpl in H11. omega.\n  exists (Int.unsigned i). exists i0.\n  split; try solve [simpl; right; left; reflexivity].\n  rewrite H6. replace (zlen c1 + 1) with (zlen (c1 ++ a :: nil)).\n  econstructor; eauto.\n  rewrite zlen_app. rewrite zlen_cons. simpl. omega.\n  rewrite zlen_cons. simpl. omega.\n  simpl. rewrite app_ass. simpl.\n  rewrite H13. reflexivity.\n  rewrite zlen_app. rewrite zlen_cons. simpl. reflexivity.\n  assert (in_code (zlen (c1 ++ a :: nil)) c ge (State_bits rs m md)).\n  econstructor. instantiate (1 := ofs - 1). omega.\n  econstructor; eauto.\n  rewrite H6. rewrite zlen_app.\n  rewrite zlen_cons. simpl. omega.\n  rewrite zlen_cons in H11. omega.\n  rewrite H13. rewrite app_ass. simpl. reflexivity.\n  app IHc H. exists x. exists x0. break_and.\n  split; eauto. simpl. right. eauto.\nQed.\n  \nLemma step_in_step_t' :\n  forall z c ge st t st',\n    in_code z c ge st ->\n    step_bits ge st t st' ->\n    exists i,\n      step_t (i :: nil) ge st t st' /\\ In i c.\nProof.\n  intros.\n  destruct st.\n  app in_code_at_code H. exists x0. break_and.\n  split; auto. replace t with (t ** E0) by (apply E0_right).\n  econstructor; eauto. econstructor.\nQed.\n\nLemma step_in_step_t :\n  forall z c ge st t st',\n    step_in z c ge st t st' ->\n    exists i,\n      step_t (i :: nil) ge st t st' /\\ In i c.\nProof.\n  intros. inv H.\n  app step_in_step_t' H2.\nQed.\n\n\nLemma step_at_step_t :\n  forall z c ofs ge st t st',\n    at_code z c ofs ge st ->\n    step_bits ge st t st' ->\n    exists i, step_t (i :: nil) ge st t st' /\\ In i c.\nProof.\n  intros.\n  destruct (zeq ofs 0). subst ofs.\n  destruct c. inv H. unfold zlen in H4. simpl in H4. omega.\n  exists i. split; try solve [simpl; left; reflexivity].\n  replace t with (t ** E0) by apply E0_right.\n  econstructor; try solve [econstructor]; eauto.\n  eapply at_code_cons; eauto.\n  assert (in_code z c ge st).\n  econstructor; eauto.\n  inv H. omega.\n  app step_in_step_t' H0.\nQed.\n\n\nLemma find_instr_in :\n  forall c i,\n    In i c <-> (exists z, find_instr z c = Some i).\nProof.\n  induction c; split; intros.\n  simpl in H. inv H.\n  break_exists. simpl in H. inv H.\n  simpl in H. break_or. exists 0. simpl. reflexivity.\n  rewrite IHc in H0. break_exists. simpl. exists (x+1).\n  apex in_range_find_instr H. break_match; try omega.\n  replace (x+1-1) with x by omega. eauto.\n  break_exists. simpl in H. break_match_hyp.\n  inv H. simpl. left. reflexivity.\n  apex IHc H. simpl. right. eauto.\nQed.\n\nLemma no_trace_trace :\n  forall x,\n    trace_internal x ->\n    ~ no_trace x.\nProof.\n  intros; destruct x; simpl; eauto.\nQed.\n\nLemma at_code_straightline_end :\n  forall z x p st t st',\n    no_PC_overflow_prog p ->\n    straightline x ->\n    at_code z (x :: nil) 0 (Genv.globalenv p) st ->\n    step_bits (Genv.globalenv p) st t st' ->\n    at_code_end z (x :: nil) (Genv.globalenv p) st'.\nProof.\n  intros. inv H1.\n  invs.\n  unify_psur. unify_find_funct_ptr.\n  name H16 Hfind_instr.\n  rewrite H8 in H16. rewrite H5 in H16.\n  rewrite find_instr_append_head in H16 by omega.\n  simpl in H16. inv H16.\n  app straightline_exec H17. break_and.\n  Focus 2. app weak_valid_pointer_sur H12.\n  break_and. eauto.\n  econstructor; eauto.\n\n  (* New stuff *)\n  app md_extends_step H2.\n  assert (Hadd_i : Int.unsigned (Int.add i Int.one) = Int.unsigned i + 1). {\n    unfold Int.add.\n    erewrite unsigned_repr_PC; eauto.\n    left. rewrite Int.unsigned_one.\n    replace (Int.unsigned i + 1 - 1) with (Int.unsigned i) by omega.\n    eauto.\n  } idtac.\n  erewrite weak_valid_pointer_sur in H12; eauto.\n  break_and.\n  eapply pinj_add in H11.\n  instantiate (1 := Int.one) in H11.\n  eapply pinj_extends in H11; eauto.\n  unify_pinj.\n  instantiate (1 := Int.add i Int.one).\n  app step_match_metadata H10.\n  erewrite weak_valid_pointer_sur; eauto.\n  split. eassumption.\n  app step_gp H11.\n  break_and.\n  app global_perms_valid_globals H16.\n  eapply Mem.weak_valid_pointer_spec. right.\n  replace (Int.unsigned (Int.add i Int.one) - 1) with (Int.unsigned i) by omega.\n  apply H16.\n  unfold is_global. left.\n  unfold in_code_range.\n  unfold fundef in *.\n  collapse_match.\n  apex in_range_find_instr Hfind_instr.\n  omega.\n  (* end new stuff *)\n  \n  rewrite zlen_cons. simpl.\n  replace (zlen c0 + 0) with (zlen c0) in H5 by omega.\n  rewrite <- H5.\n  apply add_one_no_overflow.\n  unfold no_PC_overflow_prog in H.\n  assert (no_PC_overflow (fn_code f)).\n  apply H. unfold code_of_prog. app Genv.find_funct_ptr_inversion H7.\n  destruct f. eauto.\n  unfold no_PC_overflow in H10. eapply H10; eauto.\n  \n  unify_psur. unify_find_funct_ptr.\n  rewrite H8 in H14. rewrite H5 in H14.\n  rewrite find_instr_append_head in H14 by omega.\n  simpl in H14. inv H14.\n  simpl in H0. inv H0.\n\n  unify_psur. unify_find_funct_ptr.\n  rewrite H8 in H16. rewrite H5 in H16.\n  rewrite find_instr_append_head in H16 by omega.\n  simpl in H16. inv H16.\n  simpl in H0. inv H0.\n\n  unify_psur. unify_find_funct_ptr.\n\nQed.\n\nLemma at_code_label_end :\n  forall z x p st t st',\n    no_PC_overflow_prog p ->\n    (exists l, x = Plabel l) ->\n    at_code z (x :: nil) 0 (Genv.globalenv p) st ->\n    step_bits (Genv.globalenv p) st t st' ->\n    at_code_end z (x :: nil) (Genv.globalenv p) st'.\nProof.\n  intros. inv H1.\n  invs.\n  unify_psur. unify_find_funct_ptr.\n  name H16 Hfind_instr.\n  rewrite H8 in H16. rewrite H5 in H16.\n  rewrite find_instr_append_head in H16 by omega.\n  simpl in H16. inv H16.\n  app label_exec H17. break_and.\n  econstructor; eauto.\n\n\n  (* New stuff *)\n  NP _app md_extends_step step_bits.\n  assert (Hadd_i : Int.unsigned (Int.add i Int.one) = Int.unsigned i + 1). {\n    unfold Int.add.\n    erewrite unsigned_repr_PC; eauto.\n    left. rewrite Int.unsigned_one.\n    replace (Int.unsigned i + 1 - 1) with (Int.unsigned i) by omega.\n    eauto.\n  } idtac.\n  erewrite weak_valid_pointer_sur in H12; eauto.\n  break_and.\n  eapply pinj_add in H11.\n  instantiate (1 := Int.one) in H11.\n  instantiate (1 := i) in H9.\n  eapply pinj_extends in H11; eauto.\n  unify_pinj.\n  instantiate (1 := Int.add i Int.one).\n  app step_match_metadata H10.\n  erewrite weak_valid_pointer_sur; eauto.\n  split. eassumption.\n  NP _app step_gp step_bits.\n  break_and.\n  app global_perms_valid_globals H15.\n  eapply Mem.weak_valid_pointer_spec. right.\n  rewrite Hadd_i. replace (Int.unsigned i + 1 - 1) with (Int.unsigned i) by omega.\n  apply H15.\n  unfold is_global. left.\n  unfold in_code_range.\n  unfold fundef in *.\n  collapse_match.\n  apex in_range_find_instr Hfind_instr. omega.\n  (* end new stuff *)\n  \n  rewrite zlen_cons. simpl.\n  replace (zlen c0 + 0) with (zlen c0) in H5 by omega.\n  rewrite <- H5.\n  apply add_one_no_overflow.\n  unfold no_PC_overflow_prog in H.\n  assert (no_PC_overflow (fn_code f)).\n  apply H. unfold code_of_prog. app Genv.find_funct_ptr_inversion H7.\n  destruct f. eauto.\n  unfold no_PC_overflow in H10. eapply H10; eauto.\n  eapply weak_valid_pointer_sur in H12. break_and. eauto.\n  invs; eauto. \n  \n  unify_psur. unify_find_funct_ptr.\n  rewrite H8 in H14. rewrite H5 in H14.\n  rewrite find_instr_append_head in H14 by omega.\n  simpl in H14. inv H14.\n  simpl in H0. inv H0. inv H1.\n\n  unify_psur. unify_find_funct_ptr.\n  rewrite H8 in H16. rewrite H5 in H16.\n  rewrite find_instr_append_head in H16 by omega.\n  simpl in H16. inv H16.\n  simpl in H0. inv H0. inv H1.\n\n  unify_psur. unify_find_funct_ptr.\nQed.\n\nLemma step_t_to_at_code_0 :\n  forall i ge st t st',\n    step_t (i :: nil) ge st t st' ->        \n    exists z',\n      at_code z' (i :: nil) 0 ge st.\nProof.\n  intros. inv H. eauto.\nQed.\n\nLemma Z_add_lt :\n  forall (a b c : Z),\n    a < b ->\n    c + a < c + b.\nProof.\n  intros. omega.\nQed.\n\nLemma step_t_labeled_jump_no_trace :\n  forall i ge st t st',\n    step_t (i :: nil) ge st t st' ->\n    (exists l : label, labeled_jump i l) ->\n    t = E0.\nProof.\n  intros. break_exists.\n  inv H. inv H9. inv H3.\n  invs.\n  reflexivity. \n  unify_stuff. find_one_instr. inv H0.\n  unify_stuff. find_one_instr. inv H0.\n  unify_stuff. unify_find_funct_ptr.\nQed.\n\n\nLemma is_label_instr_labeled_jump:\n  forall i l l',\n    is_label_instr i l ->\n    labeled_jump i l' ->\n    labeled_jump i l.\nProof.\n  intros.\n  destruct i; simpl in *; tauto.\nQed.\n\nLemma measure_decr_fw_j :\n  forall c,\n    only_forward_jumps c ->\n    forall z prog st t st' ofs ofs',\n      (no_PC_overflow_prog prog /\\ not_after_label_in_code (Genv.globalenv prog) st z c) ->\n      step_bits (Genv.globalenv prog) st t st' ->\n      at_code z c ofs (Genv.globalenv prog) st ->\n      at_code z c ofs' (Genv.globalenv prog) st' ->\n      (* step_in z c (Genv.globalenv prog) st t st' -> *)\n      lt (measure_fun (z + zlen c) st') (measure_fun (z + zlen c) st).\nProof.\n  \n  intros. break_and.\n  unfold only_forward_jumps in *. repeat break_and.\n  unfold no_calls in *. unfold no_trace_code in *.\n  unfold only_forward_jumps_lab in *.\n  app step_at_step_t H1. rename x into instr.\n  break_and.  \n  app find_instr_in H8.\n  clear H8. remember True as H8. clear HeqH8.\n  name (instr_class instr) Hic.\n  repeat break_or.  \n  - (* straightline case *)\n    app step_t_to_at_code_0 H1.\n    app at_code_straightline_end H7.\n    destruct st as (rs, m). destruct st' as (rs', m').\n    inv H1.\n    inv H7.    \n    simpl.\n    do 7 find_rewrite.\n    inv H2.\n    inv H3.\n    unify_stuff.\n    rewrite zlen_cons.\n    simpl.\n    eapply Z2Nat.inj_lt.\n    omega. omega. omega.  \n  -   clear H8.      \n      destruct st as (rs, m).\n      destruct st' as (rs', m').             \n      assert (t = E0) by (app step_t_labeled_jump_no_trace H11).\n      subst t.            \n      copy step_t_labeled_jump.      \n      copy H1.\n      inv H10. inv H20. inv H15.\n      app H8 H11. clear H8.\n      \n      break_or.\n      + (*jump-ish*)\n        destruct H8 as (ilbl).\n        destruct H8 as (l').\n        repeat break_and.\n        \n        repeat P inv step_t.\n        inv H2.\n        inv H3.\n        inv H23.\n        unify_stuff.\n        name H11 Hfind_instr.        \n        find_one_instr.      \n        \n        simpl. \n        P rwrt_n (rs PC).\n        P rwrt_n (rs' PC).\n        P rwrt_n (psur a bits).\n        rename bits1 into bits0.\n        P rwrt_n (psur a0 bits0).\n\n        simpl_exec.\n        repeat break_match_hyp; try state_inv.\n        clear H18. clear H28.\n        \n        P preg_simpl_hyp (Vint bits0).\n        P inv (Vint bits0).\n\n        unfold goto_label_bits in *.\n        repeat break_match_hyp; try congruence.\n        st_inv.\n        preg_simpl_hyp H3. inv H3.\n\n        eapply Z2Nat.inj_lt. omega. omega.\n        replace (zlen c5 + zlen c - Int.unsigned i1) with\n                ((zlen c5 + zlen c) + (- Int.unsigned i1)) by omega.\n        replace (zlen c5 + zlen c - Int.unsigned i2) with\n        ((zlen c5 + zlen c) + (- Int.unsigned i2)) by omega.\n        eapply Z_add_lt.\n\n        cut (Int.unsigned i2 < Int.unsigned i1); try omega.\n        rewrite H29. rewrite H32.\n        rewrite H1.\n        eapply Z_add_lt.\n\n        app label_pos_find_instr Heqo.\n        rewrite H36 in H11.\n        rewrite H29 in H11.\n        rewrite find_instr_append_head in H11 by omega.\n        erewrite find_instr_append_tail with (c := nil) in H11 by omega.\n        rewrite app_nil_r in H11.\n\n        unfold not_after_label_in_code in *.\n\n        app step_md H7.\n        break_and.\n        assert (Mem.weak_valid_pointer m' b2 (Int.unsigned (Int.repr (z))) = true).\n        eapply Mem.weak_valid_pointer_spec. right.\n        erewrite unsigned_repr_PC; eauto.\n        erewrite <- (unsigned_repr_PC _ _ (z - 1)); eauto.\n        app step_gp H3.\n        break_and.\n        eapply global_perms_valid_globals in H20.\n        unfold valid_globals in H20.\n        apply H20.\n        unfold is_global. left.\n        unfold in_code_range. unfold fundef in *.\n        collapse_match. apex in_range_find_instr Heqo.\n        erewrite unsigned_repr_PC; eauto.\n        omega.\n        \n        name (conj Heqo0 H18) Hpsur.\n        erewrite <- weak_valid_pointer_sur in Hpsur.\n        unify_psur.\n        2: assumption.\n\n        unify_find_funct_ptr.\n        rename fd1 into f.\n        destruct f.\n        exploit H4.\n        reflexivity. eauto. eauto. \n        eauto. eauto. eauto.\n        intros.\n        break_and.\n        unfold ends_in_not_label_from_after_code in *.\n        simpl in *. \n        clear H4.\n        repeat P1 clr (0 <= 0).\n        assert (zlen c1 = zlen c7) by omega.\n        rewrite H26 in H47.\n        Lemma cons_expand :\n          forall {A} a (b : list A),\n            a :: b = a :: nil ++ b.\n          auto.\n        Qed.\n        rewrite (cons_expand ilbl c2) in H47.\n        rewrite (cons_expand ilbl c8) in H47.\n        copy @list_eq_middle_therefore_eq.\n        specialize (H23 _ c1 (ilbl :: nil) c2 c7 c8).\n        app H23 H47.\n        clear H23. clear H24. break_and.\n        subst.\n\n        copy (@list_eq_middle_therefore_eq instruction).\n        app H23 H36. break_and. subst. clear H23. clear H24.\n\n        eapply is_label_instr_labeled_jump in H12; eauto.\n        clear H10.\n\n        assert (Int.unsigned (Int.repr z) = z). {\n          erewrite unsigned_repr_PC; eauto.\n        } idtac.\n\n        rewrite H10 in *.\n        rewrite H32 in Heqo.\n        assert (ofs' = 0 \\/ ofs' > 0) by omega.\n        break_or.\n        replace (zlen c3 + 0 - 1) with (zlen c3 - 1) in Heqo by omega.\n        apex in_range_find_instr Heqo. break_and. \n        rewrite find_instr_append_tail with (c := nil) in Heqo by omega.\n        rewrite app_nil_r in Heqo.\n        app H20 Heqo. inv_false.\n        unfold label_in_code.\n        eexists; split; eassumption.\n        replace (zlen c3 + ofs' - 1) with (zlen c3 + (ofs' - 1)) in Heqo by omega.\n        rewrite find_instr_append_head in Heqo by omega.\n        rewrite find_instr_append_tail with (c := nil) in Heqo by omega.\n        rewrite app_nil_r in Heqo.\n\n        exploit H6.\n        2: eauto.\n        eauto.\n        eauto.\n        intros. omega.\n\n        \n  (*       assert (zlen c5 = zlen c7) by omega. *)\n  (*       rewrite H25 in H46. *)\n  (*       copy @list_eq_middle_therefore_eq. *)\n  (*       specialize (H8 _ c5 (ilbl :: nil) c6 c7 c8). *)\n  (*       app H8 H46. *)\n  (*       clear H8. *)\n  (*       clear H13. *)\n  (*       destruct H46. *)\n  (*       subst c7. subst c8. *)\n  (*       clear H2. *)\n        \n  (*       rewrite Hfh in Heqo. clear Hfh. *)\n  (*       name find_instr_append_tail Hft. *)\n  (*       rewrite (Hft c c2 nil) in Heqo. *)\n  (*       rewrite app_nil_r in Heqo. *)\n  (*       clear Hft.   *)\n  (*       2: omega. *)\n  (*       2: omega.         *)\n  (*       assert (labeled_jump ilbl l0). { *)\n  (*         destruct ilbl; simpl; try inv H12; try tauto.           *)\n  (*       } *)\n  (*       clear H10. clear x0. *)\n  (*       rename H2 into Hjmp. *)\n  (*       app H6 Hjmp. *)\n  (*       clear H2. *)\n  (*       Focus 2. *)\n  (*       instantiate (1 := ofs). *)\n  (*       rewrite <- find_instr_append_head with (a := c1) by omega. *)\n  (*       P rwrtb_n (zlen c1 + ofs). *)\n  (*       clear H37. clear H2. *)\n  (*       P rwrt_n (zlen c5 + 0). *)\n  (*       replace (c1 ++ c) with ((c1 ++ c) ++ nil). *)\n  (*       Focus 2. *)\n  (*       rewrite app_nil_r. reflexivity.         *)\n  (*       rewrite find_instr_append_tail with (c := c2).         *)\n  (*       Focus 2. *)\n  (*       rewrite zlen_app. *)\n  (*       copy (zlen_nonneg _ c). *)\n  (*       copy (zlen_nonneg _ c1). *)\n  (*       copy (zlen_nonneg _ c5). *)\n  (*       omega. *)\n  (*       rewrite app_ass. *)\n  (*       P rwrtb_n (c1 ++ c ++ c2).    *)\n  (*       P rwrt_n (c5 ++ (ilbl :: nil) ++ c6). *)\n  (*       rewrite find_instr_append_head by omega. *)\n  (*       simpl. *)\n  (*       reflexivity. *)\n        \n  (*       omega. *)\n\n      + (*straightline-ish*)\n        inv H8.\n        simpl.\n        unfold nextinstr.\n        repeat collapse_match. preg_simpl.\n        simpl.\n\n        inv H3. preg_simpl_hyp H13.\n        find_rewrite. simpl in H13. inv H13.\n        collapse_match.\n\n        app step_md H18.\n        app step_gp H7.\n        repeat break_and.\n        eapply nat_of_Z_lt; try omega.\n        rewrite H19.\n        repeat unify_find_funct_ptr.\n        inv H2. unify_stuff. omega.\n\n        \n        cut (Int.unsigned i0 > Int.unsigned i); intros; try omega.\n\n        assert (in_code_range (Genv.globalenv prog) b i). {\n          unfold in_code_range.\n          unfold fundef in *.\n          rewrite H25.\n          \n          rewrite H26. repeat rewrite zlen_app. rewrite zlen_cons.\n          replace (zlen (@nil instruction)) with 0 by (simpl; auto).\n          rewrite H19. name (zlen_nonneg _ c1) zlnc1.\n          name (zlen_nonneg _ c2) zlnc2.\n          omega.\n          \n        } idtac.\n        \n        \n        app psur_add_one H17; try solve [econstructor]. rewrite H17 in H15.\n        inv H15.\n\n\n        unfold Int.add.\n        rewrite Int.unsigned_one.\n        erewrite unsigned_repr_PC; eauto. omega.\n        left. rewrite H26.\n        replace (Int.unsigned i + 1 - 1) with (zlen c1 + 0) by omega.\n        \n        rewrite find_instr_append_head by omega.\n        simpl. reflexivity.\n\n        eapply in_range_PC.\n        eassumption. unfold ge.\n        apply H25. rewrite H26.\n        rewrite H19. rewrite find_instr_append_head by omega.\n        simpl. reflexivity.\n        \n  - exploit find_instr_in.\n    intros.\n    destruct H11.\n    app H11 H9.\n    clear H12.\n    app H H10.\n    tauto.\n  - copy no_trace_trace.\n    exploit find_instr_in.\n    intros.\n    destruct H12.\n    clear H13.\n    app H12 H9.\n    app H11 H10.\n    exploit H5.\n    eauto.\n    intros.\n          destruct instr; simpl in *; tauto.\n\nQed.\n\nLemma z_nat_lt :\n  forall z z',\n    z >= 0 -> z' >= 0 ->\n    (nat_of_Z z < nat_of_Z z')%nat ->\n    z < z'.\nProof.\n  intros.\n  unfold nat_of_Z in H1.\n  apply Z2Nat.inj_lt; try auto; omega.\nQed.\n\n(* Lemma only_forward_in : *)\n(*   forall c, *)\n(*     only_forward_jumps c -> *)\n(*     forall z prog rs m t rs' m', *)\n(*       (no_PC_overflow_prog prog /\\ *)\n(*        not_after_label (Genv.globalenv prog) (State rs m) z c) -> *)\n(*       in_code z c (Genv.globalenv prog) (State rs m) -> *)\n(*       step_bits (Genv.globalenv prog) (State rs m) t (State rs' m') -> *)\n(*       forall b i i' bits bits', *)\n(*         rs PC = Values.Vint bits -> *)\n(*         rs' PC = Values.Vint bits' -> *)\n(*         psur bits = (b,i) -> *)\n(*         psur bits' = (b,i') -> *)\n(*         Int.unsigned i < Int.unsigned i'. *)\n(* Proof. *)\n(*   intros.  *)\n\n(* TODO: what is needed here? *)\n(* Used only for creating rewrites. Look at later *)\n\nLemma only_forward_PC_incr :\n    forall c,\n    only_forward_jumps c ->\n    forall z prog rs m t rs' m' ofs ofs' md md',\n      (no_PC_overflow_prog prog /\\\n       not_after_label_in_code (Genv.globalenv prog) (State_bits rs m md) z c) ->\n      step_bits (Genv.globalenv prog) (State_bits rs m md) t (State_bits rs' m' md') ->\n      at_code z c ofs (Genv.globalenv prog) (State_bits rs m md) ->\n      at_code z c ofs' (Genv.globalenv prog) (State_bits rs' m' md') ->\n      forall b i i' bits bits',\n        rs PC = Values.Vint bits ->\n        rs' PC = Values.Vint bits' ->\n        psur md bits = Some (b,i) ->\n        psur md' bits' = Some (b,i') ->\n        Int.unsigned i < Int.unsigned i'.\nProof.\n  intros. \n  app measure_decr_fw_j H1.  \n  unfold measure_fun in H1.\n  rewrite H4 in H1. \n  rewrite H5 in H1.\n  rewrite H6 in H1. \n  rewrite H7 in H1.\n  \n  (* name (zlen_nonneg _ c1) zlnc1. *)\n  name (zlen_nonneg _ c) zlnc.\n  inv H2.\n  inv H3.\n  unify_stuff.\n  app z_nat_lt H1; try omega.\nQed.\n\nLemma no_trace_step_at :\n  forall z c ge st t st' ofs,\n    no_trace_code c ->\n    at_code z c ofs ge st ->\n    step_bits ge st t st' ->\n    t = E0.\nProof.\n  intros. \n\n  unfold no_trace_code in H.\n  inv H0. inv H3.\n  invs; eauto;\n  try unify_PC;\n  try unify_psur;\n  try unify_find_funct_ptr.\n\n\n  peel_code. app H H13. simpl in *. inv_false.\n  peel_code. app H H15. simpl in *. inv_false.\nQed.\n\n  \nLemma no_trace_step_in :\n  forall z c ge st t st',\n    no_trace_code c ->\n    in_code z c ge st ->\n    step_bits ge st t st' ->\n    t = E0.\nProof.\n  intros. \n  inv H0. app no_trace_step_at H3.\nQed.\n\nLemma no_trace_star_step_in :\n  forall c,\n    no_trace_code c ->\n    forall z ge st t st',\n      star (step_in z c) ge st t st' ->\n      t = E0.\nProof.\n  intros. induction H0. reflexivity.\n  inv H0.\n  app no_trace_step_in H5. subst t1. reflexivity.\nQed.\n\nLemma no_trace_step_through :\n  forall z c ge st t st',\n    no_trace_code c ->\n    at_code z c 0 ge st -> \n    step_through z c ge st t st' ->\n    t = E0.\nProof.\n  intros. inv H1.\n  app no_trace_step_at H3.\n\n  name H5 Hstar.\n  rewrite st_in_eq in H5. break_and.\n  app no_trace_step_at H4. subst t1.\n  app no_trace_star_step_in H1. subst t2.\n  app star_step_in_in' Hstar.\n  app no_trace_step_in Hstar.\nQed.  \n\nLemma only_forward_jumps_same_block :\n  forall rs m t rs' m' z c bits b i bits' b' i' p ofs md md',\n    only_forward_jumps c ->\n    rs PC = Values.Vint bits ->\n    psur md bits = Some (b,i) ->\n    step_bits (Genv.globalenv p) (State_bits rs m md) t (State_bits rs' m' md') ->\n    at_code z c ofs (Genv.globalenv p) (State_bits rs m md) ->\n    rs' PC = Values.Vint bits' ->\n    psur md' bits' = Some (b',i') ->\n    no_PC_overflow_prog p ->    \n    b' = b.\nProof.\n  intros. unfold only_forward_jumps in H.\n  repeat break_and.\n  inv H3. unify_PC. unify_psur.\n  unfold no_calls in *.\n  unfold no_trace_code in *.\n  invs; try unify_PC; try unify_psur; try unify_find_funct_ptr;\n  match goal with\n    | [ H : fn_code _ = _, H2 : find_instr ?X _ = _, H3 : ?X = _ |- _ ] =>\n      rewrite H in H2; rewrite H3 in H2; \n      rewrite find_instr_append_head in H2 by omega;\n      rewrite find_instr_append_tail with (c := nil) in H2 by omega;\n      rewrite app_nil_r in H2;\n      name H2 Hfind_instr;\n      name H2 Hfi\n  end;\n  app H Hfind_instr;\n  app H7 Hfi.\n\n  app step_md H2.\n  NP _app step_gp step_bits.\n\n  repeat break_and.\n\n  assert (straightline i0 \\/ (exists l, labeled_jump i0 l)).  {\n  name (instr_class i0) Hclass.\n  repeat break_or; try congruence;\n  eauto.\n  app H7 H3.\n  NP _app no_trace_trace trace_internal. congruence.\n  } idtac.\n\n  destruct f.\n\n  NP _app step_PC_same_block step_bits.\n  break_and. repeat unify_PC. repeat unify_psur. reflexivity.\n  simpl in *.\n  match goal with\n    | [ H : ?X = _ , H2 : ?Y = _ |- find_instr ?X ?Y = _ ] => rewrite H; rewrite H2\n  end.\n  rewrite find_instr_append_head by omega.\n  rewrite find_instr_append_tail with (c := nil) by omega.\n  rewrite app_nil_r. assumption.\n  intro. destruct i0; repeat break_or; simpl in *; try inv_false.\n  \n  unfold is_call_return in *; unfold no_trace in *; inv_false.\n  unfold is_call_return in *; unfold no_trace in *; inv_false.\nQed.\n\nLemma only_forward_jumps_same_block_star :\n  forall p st st' z c t,\n    no_PC_overflow_prog p ->\n    star (step_in z c) (Genv.globalenv p) st t st' ->\n    forall rs m rs' m' md md',\n      st = State_bits rs m md ->\n      st' = State_bits rs' m' md' ->\n      only_forward_jumps c ->\n      forall bits b i bits' b' i',\n        rs PC = Values.Vint bits ->\n        psur md bits = Some (b,i) ->\n        rs' PC = Values.Vint bits' ->\n        psur md' bits' = Some (b',i') ->\n        b' = b.\nProof.\n  induction 2; intros.\n  * subst. find_inversion. unify_PC.\n    unify_psur. reflexivity.\n  * destruct s1. destruct s2. destruct s3.\n    repeat match goal with\n               | [ H : State _ _ = State _ _ |- _ ] => inv H\n           end.\n    \n    specialize (IHstar _ _ _ _ _ _  eq_refl eq_refl H5).\n    name H Hstep_in.\n    inv H0. inv H3. inv H11. inv H4.\n    inv H2.\n    exploit IHstar; try eauto.\n    intros. subst.\n    inv H10.\n    app only_forward_jumps_same_block H12.\nQed.\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/ForwardJumps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982315512489, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.25899727382484256}}
{"text": "Require Import List Map Envs AllInRel Exp AppExpFree RenamedApart.\nRequire Import IL Annotation AutoIndTac AnnotationLattice.\nRequire Import Liveness.Liveness LabelsDefined.\nRequire Import SpillSound DoSpill DoSpillRm SpillUtil ReconstrLive.\nRequire Import ReconstrLiveSmall ReconstrLiveSound InVD AnnP.\nRequire Import BoundedIn SlotLiftArgs SlotLiftParams.\n\nSet Implicit Arguments.\n\n(** * RegisterBound *)\n\nLemma bounded_in_incl VD G G' k Lv ZL s (an :  (ann ⦃var⦄))\n  : VD ∩ G' ⊆ VD ∩ G\n    -> ann_P (bounded_in VD k) (reconstr_live Lv ZL G s an)\n    -> ann_P (bounded_in VD k) (reconstr_live Lv ZL G' s an).\nProof.\n  intros Gincl base.\n  assert (bounded_in VD k G') as biG'.\n  {\n    apply ann_P_get in base.\n    unfold bounded_in in base.\n    unfold bounded_in.\n    rewrite subset_cardinal with (s':=VD ∩ (getAnn (reconstr_live Lv ZL G s an))); eauto.\n    rewrite reconstr_live_G_eq.\n    rewrite Gincl.\n    clear; cset_tac.\n  }\n  unfold bounded_in.\n  unfold bounded_in in base.\n  unfold bounded_in in biG'.\n  destruct s, an;\n    simpl;\n    try destruct a;\n    simpl; try eassumption;\n      invc base;\n      econstructor; try eassumption;\n      clear biG';\n      erewrite subset_cardinal; try eassumption;\n        repeat rewrite union_meet_distr_l;\n        rewrite Gincl; try reflexivity.\nQed.\n\nLemma register_bound_loads\n      (k : nat)\n      (ZL : list params)\n      (Lv : list ⦃var⦄)\n      (VD R : ⦃var⦄)\n      (s : stmt)\n      (slot : var -> var)\n      (xs : list var)\n      (an : ann ⦃var⦄)\n      (x : var)\n  : disj VD (map slot VD)\n    -> R ⊆ VD\n    -> singleton x ⊆ R\n    -> of_list xs ⊆ R\n    -> bounded_in VD k R\n    -> VD ∩ getAnn (reconstr_live Lv ZL ∅ s an) ⊆ R\n    -> (forall (x' : var),\n          singleton x' ⊆ R\n          -> of_list xs ⊆ R\n          -> VD ∩ getAnn (reconstr_live Lv ZL ∅ s an) ⊆ R\n          -> bounded_in VD k R\n          -> ann_P (bounded_in VD k)\n                  (reconstr_live Lv ZL (singleton x') s an)\n      )\n    -> ann_P (bounded_in VD k)\n            (reconstr_live Lv ZL\n                           (singleton x)\n                           (write_moves xs (slot ⊝ xs) s)\n                           (add_anns ∅ (length xs) an)\n            ).\nProof.\n  intros disj_VD R_VD x_R xs_R\n         bound_R H  base.\n  unfold bounded_in in bound_R.\n  general induction xs;\n    simpl in *; eauto.\n  rewrite add_anns_S.\n  rewrite add_union_singleton in xs_R.\n  apply union_incl_split2 in xs_R as [a_R xs_R].\n  econstructor.\n  - unfold bounded_in.\n    rewrite reconstr_live_write_loads; [ | | eauto];\n      [ | rewrite xs_R, R_VD; clear; cset_tac].\n    rewrite subset_cardinal with (s':=VD ∩ R); eauto.\n    apply incl_meet_split; [clear; cset_tac | ].\n    setoid_rewrite union_comm at 3.\n    rewrite union_minus_incl.\n    repeat rewrite union_meet_distr_l.\n    repeat apply union_incl_split; eauto.\n    + rewrite incl_minus.\n      rewrite H.\n      clear; cset_tac.\n    + rewrite disj_empty_cut; eauto.\n      * clear; cset_tac.\n      * rewrite xs_R, R_VD; clear; cset_tac.\n    + rewrite <- map_singleton; eauto.\n      rewrite disj_empty_cut; eauto.\n      * clear; cset_tac.\n      * rewrite a_R, R_VD; clear; cset_tac.\n    + rewrite <- x_R.\n      clear; cset_tac.\n  - eapply IHxs with (R:=R); eauto.\n    intros x' x'_R' xs_R' al_R' bound_R'.\n    eapply base; eauto.\n    rewrite add_union_singleton, a_R, xs_R.\n    clear; cset_tac.\nQed.\n\nLemma register_bound_spills\n      (k : nat)\n      (ZL : list params)\n      (Lv : list ⦃var⦄)\n      (VD R G : ⦃var⦄)\n      (s : stmt)\n      (slot : var -> var)\n      (xs : list var)\n      (an : ann ⦃var⦄)\n  :\n    disj VD (map slot VD)\n    -> R ⊆ VD\n    -> of_list xs ⊆ R\n    -> bounded_in VD k R\n    -> VD ∩ G ⊆ R\n    -> VD ∩ getAnn (reconstr_live Lv ZL ∅ s an) ⊆ R\n    -> ann_P (bounded_in VD k)\n            (reconstr_live Lv ZL G s an)\n    -> ann_P (bounded_in VD k)\n            (reconstr_live Lv ZL\n                           G\n                           (write_moves (slot ⊝ xs) xs s)\n                           (add_anns ∅ (length xs) an)\n                 ).\nProof.\n  intros disj_VD R'_VD xs_R'\n         bound_G G_rkl H base.\n  unfold bounded_in in bound_G.\n  general induction xs;\n    simpl in *; eauto.\n  rewrite add_anns_S.\n  rewrite add_union_singleton in xs_R'.\n  apply union_incl_split2 in xs_R' as [a_R' xs_R'].\n  econstructor.\n  - unfold bounded_in.\n    rewrite reconstr_live_write_spills; eauto;\n      [ | rewrite xs_R', R'_VD; clear; cset_tac].\n    rewrite subset_cardinal with (s':=VD ∩ R); eauto.\n    apply incl_meet_split; [clear; cset_tac | ].\n    setoid_rewrite union_comm at 3.\n    rewrite union_minus_incl.\n    repeat rewrite union_meet_distr_l.\n    repeat apply union_incl_split; eauto.\n    + rewrite incl_minus.\n      rewrite H.\n      clear; cset_tac.\n    + rewrite xs_R'.\n      clear; cset_tac.\n    + rewrite a_R'.\n      clear; cset_tac.\n  - eapply IHxs with (R:=R) ; eauto.\n    rewrite <- map_singleton; eauto.\n    rewrite disj_empty_cut; eauto.\n    + clear; cset_tac.\n    + rewrite a_R', R'_VD.\n      reflexivity.\n    + eapply bounded_in_incl; eauto.\n      rewrite <- map_singleton; eauto.\n      rewrite disj_empty_cut; eauto.\n      * clear; cset_tac.\n      * rewrite a_R', R'_VD.\n        reflexivity.\nQed.\n\nLemma meet_minus_assoc (X : Type) `{OrderedType X} (s t u : ⦃X⦄)\n  : (s ∩ t) \\ u [=] s ∩ (t \\ u) .\nProof.\n  cset_tac.\nQed.\n\nLemma register_bound_s k ZL Lv VD R G s slot xs ys (an : ann ⦃var⦄)\n  : disj VD (map slot VD)\n    -> R ⊆ VD\n    -> of_list xs ⊆ R\n    -> of_list ys ⊆ VD\n    -> cardinal R <= k\n    -> bounded_in VD k (getAnn (reconstr_live Lv ZL ∅ s an) ∪ of_list ys)\n    -> VD ∩ G ⊆ R\n    -> VD ∩ getAnn (reconstr_live Lv ZL ∅ s an) ⊆ R ∪ of_list ys\n    -> (forall (G' R' : ⦃var⦄),\n          VD ∩ G' ⊆ R'\n          -> of_list ys ⊆ R'\n          -> VD ∩ getAnn (reconstr_live Lv ZL ∅ s an) ⊆ R'\n          -> cardinal R' <= k\n          -> ann_P (bounded_in VD k)\n                  (reconstr_live Lv ZL G' s an)\n      )\n    -> ann_P (bounded_in VD k)\n            (reconstr_live Lv ZL\n                           G\n                           (write_moves (slot ⊝ xs) xs\n                                         (write_moves ys (slot ⊝ ys) s)\n                           )\n                           (add_anns ∅ (length xs + length ys) an)\n            ).\nProof.\n  intros disj_VD R_VD xs_R ys_VD bound_R2 bound_al_L G_R al_R base.\n  assert (bounded_in VD k R) as bound_R.\n  {\n    clear - bound_R2.\n    unfold bounded_in.\n    rewrite subset_cardinal; eauto.\n    cset_tac.\n  }\n  rewrite add_anns_add.\n  destruct ys as [|v ?].\n  - simpl in *.\n    apply register_bound_spills with (R:=R); eauto.\n      rewrite add_anns_zero.\n    + rewrite al_R; clear; cset_tac.\n    + eapply base with (R':=R); eauto.\n      * clear; cset_tac.\n      * rewrite al_R; clear; cset_tac.\n  - eapply register_bound_spills with (R:=R); eauto.\n      {\n        rewrite reconstr_live_write_loads; eauto.\n        repeat rewrite union_meet_distr_l.\n        repeat apply union_incl_split.\n        - rewrite <- meet_minus_assoc.\n          rewrite al_R.\n          clear; cset_tac.\n        - rewrite disj_empty_cut; eauto.\n          clear; cset_tac.\n        - clear; cset_tac.\n      }\n      simpl in *.\n      rewrite add_union_singleton in ys_VD.\n      apply union_incl_split2 in ys_VD as [v_VD ys_VD].\n      rewrite add_anns_S.\n      econstructor.\n    + unfold bounded_in.\n      rewrite reconstr_live_write_loads; eauto.\n      repeat rewrite union_meet_distr_l.\n      rewrite <- meet_minus_assoc.\n      repeat rewrite union_meet_distr_l.\n      rewrite <- meet_minus_assoc.\n      rewrite al_R.\n      assert (forall (x : var) (s t u v : ⦃var⦄),\n                 ((s ∪ {x; t}) \\ t ∪ (v ∩ u) ∪ (v ∩ singleton x) ) \\ singleton x\n               ⊆ ((s ∪ (v ∩ u))))\n        as seteq by (clear; cset_tac).\n      rewrite seteq.\n      rewrite subset_cardinal with (s':=VD ∩ R); eauto.\n      repeat apply union_incl_split; eauto.\n      * clear - R_VD; cset_tac.\n      * rewrite disj_empty_cut; eauto.\n        clear; cset_tac.\n      * rewrite <- map_singleton; eauto.\n        rewrite disj_empty_cut; eauto.\n        clear; cset_tac.\n      * rewrite G_R.\n        clear - R_VD; cset_tac.\n    + eapply register_bound_loads\n      with (R:=VD ∩ getAnn (reconstr_live Lv ZL ∅ s an)\n                  ∪ {v; of_list ys}); eauto.\n      * rewrite add_union_singleton, v_VD, ys_VD.\n        clear; cset_tac.\n      * clear; cset_tac.\n      * clear; cset_tac.\n      * unfold bounded_in.\n        assert (forall (s t u : ⦃var⦄),\n                   s ∩ (s ∩ t ∪ u) ⊆ s ∩ (t ∪ u))\n          as setsub by (clear; cset_tac).\n        rewrite setsub.\n        assumption.\n\n      * intros.\n        eapply base; eauto.\n        -- rewrite H.\n           clear; cset_tac.\n        -- clear; cset_tac.\n        -- unfold bounded_in in H2.\n           rewrite subset_cardinal; eauto.\n           apply union_incl_split.\n           ++ clear; cset_tac.\n           ++ rewrite union_meet_distr_l.\n              apply incl_union_right.\n              apply incl_meet_split; eauto.\n              rewrite add_union_singleton, v_VD, ys_VD.\n              clear; cset_tac.\nQed.\n\nLemma slot_lift_args_RMapp_incl (slot : var -> var) (Y : args) RM RMapp Z\n  : (forall (n : nat) (y : op), get Y n y -> isVar y)\n    -> (list_union (Ops.freeVars ⊝ Y) ⊆ fst RMapp ∪ snd RMapp)\n    -> list_union (Ops.freeVars ⊝ slot_lift_args slot RM RMapp Y Z)\n                 ⊆ fst RMapp ∪ map slot (snd RMapp).\nProof.\n  general induction Y; destruct Z; simpl in *; only 1,2,3: eauto with cset.\n  revert H0.\n  exploit H as IV; eauto using get. invc IV. simpl.\n  repeat cases; simpl; norm_lunion; intro;\n    rewrite IHY; eauto using get; intros; clear IHY H.\n  - assert (v ∈ fst RMapp ∪ snd RMapp). cset_tac.\n    unfold choose_y; simpl; repeat cases; simpl.\n    + revert COND1. clear_all. cset_tac.\n    + revert COND1 COND2. clear_all. cset_tac.\n    + revert COND1. clear_all. cset_tac.\n    + revert H NOTCOND. clear_all. cset_tac.\n    + revert COND1. clear_all. cset_tac.\n    + exfalso. cset_tac.\n    + revert COND0 COND2. clear_all. cset_tac.\n    + revert COND0. clear_all. cset_tac.\n    + revert COND0. clear_all. cset_tac.\n    + revert COND1. clear_all. cset_tac.\n    + exfalso. revert H NOTCOND0 NOTCOND1. cset_tac.\n    + revert NOTCOND0 H. clear_all. cset_tac.\n  - rewrite <- H0. cset_tac.\n  - assert (v ∈ fst RMapp ∪ snd RMapp). cset_tac.\n    unfold choose_y; simpl; repeat cases; simpl.\n    + revert COND1. clear_all. cset_tac.\n    + revert NOTCOND0 H. clear_all. cset_tac.\n  - rewrite <- H0. cset_tac.\n  - assert (v ∈ fst RMapp ∪ snd RMapp). cset_tac.\n    unfold choose_y; simpl; repeat cases; simpl.\n    + revert COND0. clear_all. cset_tac.\n    + revert NOTCOND1 H. clear_all. cset_tac.\n    + revert COND. clear_all. cset_tac.\n    + revert NOTCOND2 H. clear_all. cset_tac.\n  - rewrite <- H0. cset_tac.\nQed.\n\nLemma register_bounded k (slot : var -> var) ZL G Λ R M VD s Lv sl al ra\n  : cardinal R <= k\n    -> injective_on VD slot\n    -> disj VD (map slot VD)\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 al\n    -> live_sound Imperative ZL Lv s al\n    -> PIR2 Equal (merge ⊝ Λ) Lv\n    -> (forall (Z : params) n,\n          get ZL n Z\n          -> of_list Z ⊆ VD)\n    -> (forall (n : nat) Z blv,\n          get ZL n Z ->\n          get Lv n blv ->\n          of_list Z [<=] blv)\n    -> VD ∩ G ⊆ R\n    -> ann_P (bounded_in VD k)\n            (reconstr_live_do_spill slot Λ ZL G s sl).\nProof.\n  intros card_R inj_VD disj_VD R_VD M_VD ra_VD\n         aeFree rena spillSnd spilli lvSnd\n         H16 Z_VD Z_LV G_R.\n  unfold reconstr_live_do_spill.\n  general induction lvSnd;\n    invc aeFree;\n    inv rena;\n    inv spilli;\n    inv spillSnd;\n    eapply renamedApart_incl in rena; eauto;\n      simpl in *; eauto;\n        unfold count;\n        simpl;\n        do 2 rewrite <- elements_length.\n\n  - eapply register_bound_s with (VD:=VD) (R:=R); simpl; eauto.\n    + rewrite of_list_elements, H19.\n      reflexivity.\n    + rewrite of_list_elements, H20, H19, R_VD, M_VD.\n      clear; cset_tac.\n    + unfold bounded_in.\n      rewrite of_list_elements.\n      rewrite reconstr_live_small with (VD:=VD) (R:={x; (R\\K ∪ L) \\ Kx}) (M:=Sp ∪ M); eauto.\n      * rewrite subset_cardinal with (s':=R \\K ∪ L); eauto.\n        assert (forall (x : var) (s t : ⦃var⦄),\n                   ({x; s} ∪ t ∪ singleton x) \\ singleton x\n                                              ⊆ s ∪ t)\n          as setsub by (clear; cset_tac).\n        rewrite setsub.\n        repeat rewrite union_meet_distr_l.\n        repeat apply union_incl_split.\n        -- clear; cset_tac.\n        -- rewrite disj_empty_cut; eauto.\n           ++ clear; cset_tac.\n           ++ rewrite H19, R_VD, M_VD.\n              clear; cset_tac.\n        -- rewrite H22. clear; cset_tac.\n        -- clear; cset_tac.\n        -- clear; cset_tac.\n      * rewrite H20, H19, R_VD, M_VD.\n        eapply x_VD in H10; eauto.\n        revert H10; clear; cset_tac.\n      * rewrite H19, M_VD, R_VD.\n        clear; cset_tac.\n      * rewrite rena, <- ra_VD.\n        eauto.\n    + rewrite of_list_elements.\n      rewrite reconstr_live_small with (VD:=VD) (R:={x; (R\\K ∪ L) \\ Kx}) (M:=Sp ∪ M); eauto.\n      * assert (forall (x : var) (s t : ⦃var⦄),\n                   ({x; s} ∪ t ∪ singleton x) \\ singleton x\n                                              ⊆ s ∪ t)\n          as setsub by (clear; cset_tac).\n        rewrite setsub.\n        repeat rewrite union_meet_distr_l.\n        repeat apply union_incl_split.\n        -- clear; cset_tac.\n        -- rewrite disj_empty_cut; eauto.\n           ++ clear; cset_tac.\n           ++ rewrite H19, R_VD, M_VD.\n              clear; cset_tac.\n        -- rewrite H22. clear; cset_tac.\n        -- clear; cset_tac.\n      * rewrite H20, H19, R_VD, M_VD.\n        eapply x_VD in H10; eauto.\n        revert H10; clear; cset_tac.\n      * rewrite H19, M_VD, R_VD.\n        clear; cset_tac.\n      * rewrite rena, <- ra_VD.\n        eauto.\n    + intros G' R' G'_R' L_R' al_R' bound_R'.\n      rewrite of_list_elements in L_R'.\n      econstructor.\n      * unfold bounded_in.\n        rewrite subset_cardinal with (s':=R'); eauto.\n        -- rewrite union_meet_distr_l.\n           rewrite G'_R'.\n           rewrite empty_neutral_union_r in al_R'.\n           rewrite al_R'.\n           clear; cset_tac.\n      * eapply IHlvSnd with (R:={x; (R\\K ∪ L) \\ Kx})\n                            (M:=Sp ∪ M); try eassumption.\n        -- eapply Rx_VD with (VD:=VD) (M:=M); eauto.\n           eapply x_VD; eauto.\n        -- eauto using M'_VD.\n        -- rewrite rena, <- ra_VD; eauto.\n        -- clear; cset_tac.\n  - destruct rena as [rena1 rena2].\n    eapply register_bound_s with (VD:=VD) (R:=R); simpl; eauto.\n    + rewrite of_list_elements; assumption.\n    + rewrite of_list_elements, H25, H24, R_VD, M_VD.\n      clear; cset_tac.\n    + unfold bounded_in.\n      rewrite of_list_elements.\n      rewrite subset_cardinal; eauto.\n      rewrite reconstr_live_small with (VD:=VD) (R:=R\\K ∪ L) (M:=Sp ∪ M); eauto.\n      * rewrite reconstr_live_small with (VD:=VD) (R:=R\\K ∪ L) (M:=Sp ∪ M); eauto.\n        -- repeat rewrite union_meet_distr_l.\n           clear - H24 H25 H26 R_VD M_VD disj_VD.\n           assert (VD ∩ map slot (Sp ∪ M) ⊆ R \\ K ∪ L) as goal37.\n           {\n             rewrite disj_empty_cut; eauto.\n             - clear; cset_tac.\n             - rewrite H24, R_VD, M_VD; cset_tac.\n           }\n           repeat apply union_incl_split; eauto; try rewrite H26;\n            clear; cset_tac.\n        -- rewrite H25, H24, R_VD, M_VD. clear; cset_tac.\n        -- rewrite H24, R_VD, M_VD; clear; cset_tac.\n        -- rewrite rena2, <- ra_VD; eauto.\n      * rewrite H25, H24, R_VD, M_VD. clear; cset_tac.\n      * rewrite H24, R_VD, M_VD; clear; cset_tac.\n      * rewrite rena1, <- ra_VD; eauto.\n    + rewrite of_list_elements.\n      rewrite reconstr_live_small with (VD:=VD) (R:=R\\K ∪ L) (M:=Sp ∪ M); eauto.\n      * rewrite reconstr_live_small with (VD:=VD) (R:=R\\K ∪ L) (M:=Sp ∪ M); eauto.\n        -- repeat rewrite union_meet_distr_l.\n           clear - H24 H25 H26 R_VD M_VD disj_VD.\n           assert (VD ∩ map slot (Sp ∪ M) ⊆ R ∪ L) as goal37.\n           {\n             rewrite disj_empty_cut; eauto.\n             - clear; cset_tac.\n             - rewrite H24, R_VD, M_VD; cset_tac.\n           }\n           repeat apply union_incl_split; eauto;\n             try rewrite H26; clear; cset_tac.\n        -- rewrite H25, H24, R_VD, M_VD. clear; cset_tac.\n        -- rewrite H24, R_VD, M_VD; clear; cset_tac.\n        -- rewrite rena2, <- ra_VD; eauto.\n      * rewrite H25, H24, R_VD, M_VD. clear; cset_tac.\n      * rewrite H24, R_VD, M_VD; clear; cset_tac.\n      * rewrite rena1, <- ra_VD; eauto.\n    + intros G' R' G'_R' L_R' al_R' bound_R'.\n      rewrite of_list_elements in L_R'.\n      econstructor.\n      * unfold bounded_in.\n        rewrite subset_cardinal with (s':=R'); eauto.\n        -- rewrite union_meet_distr_l.\n           rewrite G'_R'.\n           rewrite empty_neutral_union_r in al_R'.\n           rewrite al_R'.\n           clear; cset_tac.\n      * eapply IHlvSnd1 with (R:=R\\K ∪ L)\n                              (M:=Sp ∪ M); eauto.\n        -- eapply R'_VD with (VD:=VD) (M:=M); eauto.\n        -- eapply M'_VD with (VD:=VD) (M:=M) (R:=R); eauto.\n        -- rewrite rena1, <- ra_VD; eauto.\n        -- clear; cset_tac.\n      * eapply IHlvSnd2 with (R:=R\\K ∪ L)\n                               (M:=Sp ∪ M); eauto.\n        -- eapply R'_VD with (VD:=VD) (M:=M); eauto.\n        -- eapply M'_VD with (VD:=VD) (M:=M) (R:=R); eauto.\n        -- rewrite rena2, <- ra_VD; eauto.\n        -- clear; cset_tac.\n\n  - eapply register_bound_s with (VD:=VD) (R:=R); simpl; eauto.\n    + rewrite of_list_elements; assumption.\n    + rewrite of_list_elements, H13, H12, R_VD, M_VD.\n      clear; cset_tac.\n    + erewrite nth_zip; eauto.\n      unfold bounded_in.\n      rewrite subset_cardinal; eauto.\n      erewrite !get_nth; eauto using map_get_1. simpl.\n      rewrite slot_lift_args_RMapp_incl; simpl; eauto; [|rewrite H22; reflexivity].\n      rewrite of_list_elements.\n      eapply PIR2_nth in H16; eauto; dcr. inv_get. unfold merge in H8. simpl in *.\n      rewrite of_list_slot_lift_params; [|rewrite Z_LV; eauto; rewrite H8; reflexivity].\n      simpl in *.\n      rewrite H9 in *; clear H9 D'.\n      rewrite H23.\n      assert (M'VD:M' [<=] VD). {\n        rewrite H24, H12, R_VD, M_VD. eauto with cset.\n      }\n      assert (M_fVD:M_f ⊆ VD). {\n        rewrite Mf_VD with (R:=R) (M:=M) (VD:=VD); eauto.\n      }\n      rewrite empty_neutral_union_r.\n      repeat rewrite union_meet_distr_l.\n      rewrite (@disj_empty_cut VD); eauto.\n      unfold slot_merge. simpl.\n      rewrite minus_dist_union.\n      repeat rewrite union_meet_distr_l.\n      rewrite (@incl_minus _ _ (map slot M_f)).\n      rewrite (@disj_empty_cut VD); eauto.\n      rewrite empty_neutral_union_r.\n      assert (of_list Z ∩ R_f ⊆ of_list Z \\ (M_f \\ R_f) ∪ map slot (of_list Z \\ (R_f \\ M_f))). {\n        clear_all. cset_tac.\n      }\n      rewrite <- H4.\n      revert H20. clear_all. cset_tac.\n    + erewrite nth_zip; eauto.\n      rewrite slot_lift_args_RMapp_incl; eauto; simpl; [|rewrite H22; reflexivity].\n      erewrite !get_nth; eauto using map_get_1.\n      rewrite of_list_elements. unfold slot_merge; simpl.\n      rewrite slp_union_minus_incl; eauto; simpl.\n      assert (M'VD:M' [<=] VD). {\n        rewrite H24, H12, R_VD, M_VD. eauto with cset.\n      }\n      assert (M_fVD:M_f ⊆ VD). {\n        rewrite Mf_VD with (R:=R) (M:=M) (VD:=VD); eauto.\n      }\n      * rewrite H20, H23.\n        rewrite empty_neutral_union_r.\n        repeat rewrite union_meet_distr_l.\n        rewrite (@disj_empty_cut VD); eauto.\n        rewrite minus_incl with (t:=map slot (of_list Z0)).\n        rewrite (@disj_empty_cut VD); eauto.\n        clear_all. cset_tac.\n      * rewrite Rf_VD with (R:=R) (M:=M) (VD:=VD) (L:=L); eauto.\n      * rewrite Mf_VD with (R:=R) (M:=M) (VD:=VD); eauto.\n    + intros G' R'' G'_R' L_R' al_R' bound_R'.\n      econstructor.\n      unfold bounded_in.\n      rewrite subset_cardinal; eauto.\n      rewrite union_meet_distr_l.\n      rewrite empty_neutral_union_r in al_R'.\n      rewrite al_R', G'_R'.\n      clear; cset_tac.\n  - eapply register_bound_s with (VD:=VD) (R:=R); simpl; eauto.\n    + rewrite of_list_elements; assumption.\n    + rewrite of_list_elements, H9, H8, R_VD, M_VD.\n      clear; cset_tac.\n    + unfold bounded_in.\n      rewrite of_list_elements.\n      rewrite subset_cardinal; eauto.\n      rewrite H10.\n      clear; cset_tac.\n    + rewrite H10, of_list_elements.\n      clear; cset_tac.\n    + intros G' R' G'_R' L_R' al_R' bound_R'.\n      rewrite empty_neutral_union_r in al_R'.\n      econstructor.\n      unfold bounded_in.\n      rewrite subset_cardinal; eauto.\n      rewrite union_meet_distr_l, G'_R', al_R'.\n      clear; cset_tac.\n\n  - destruct rena as [renaF rena2].\n    eapply register_bound_s with (VD:=VD) (R:=R); simpl; eauto.\n    + rewrite of_list_elements; assumption.\n    + rewrite of_list_elements, H29, H28, R_VD, M_VD; clear; cset_tac.\n    + unfold bounded_in.\n      rewrite fst_zip_pair; eauto with len.\n      rewrite slot_lift_params_app; eauto with len.\n      rewrite getAnn_map_setTopAnn.\n      rewrite Take.take_eq_ge;\n        [|unfold slot_merge; len_simpl; rewrite <- H31, <- H32; omega].\n      rewrite slot_merge_app.\n      rewrite subset_cardinal; eauto.\n      rewrite reconstr_live_small with (VD:=VD) (R:=R\\K∪L) (M:=Sp ∪ M); eauto.\n      * rewrite of_list_elements, !empty_neutral_union_r.\n        repeat rewrite union_meet_distr_l.\n        repeat apply union_incl_split.\n        -- clear; cset_tac.\n        -- clear; cset_tac.\n        -- rewrite disj_empty_cut; eauto.\n           ++ clear; cset_tac.\n           ++ rewrite H28, R_VD, M_VD; clear; cset_tac.\n        -- clear; cset_tac.\n      * eapply R'_VD with (VD:=VD) (L:=L) (M:=M); eauto.\n      * rewrite H28, R_VD, M_VD; clear; cset_tac.\n      * rewrite rena2, <- ra_VD; eauto.\n      * eapply getAnn_als_EQ_merge_rms; eauto.\n      * intros.\n        eapply get_ofl_VD; eauto.\n    + rewrite fst_zip_pair; eauto with len.\n      rewrite slot_lift_params_app; eauto with len.\n      rewrite getAnn_map_setTopAnn.\n      rewrite Take.take_eq_ge;\n        [|unfold slot_merge; len_simpl; rewrite <- H31, <- H32; omega].\n      rewrite slot_merge_app.\n      rewrite reconstr_live_small with (VD:=VD) (R:=R\\K∪L) (M:=Sp ∪ M); eauto.\n      * rewrite of_list_elements, !empty_neutral_union_r.\n        repeat rewrite union_meet_distr_l.\n        repeat apply union_incl_split.\n        -- clear; cset_tac.\n        -- clear; cset_tac.\n        -- rewrite disj_empty_cut; eauto.\n           ++ clear; cset_tac.\n           ++ rewrite H28, R_VD, M_VD; clear; cset_tac.\n      * eapply R'_VD with (VD:=VD) (L:=L) (M:=M); eauto.\n      * rewrite H28, R_VD, M_VD; clear; cset_tac.\n      * rewrite rena2, <- ra_VD; eauto.\n      * eapply getAnn_als_EQ_merge_rms; eauto.\n      * intros.\n        eapply get_ofl_VD; eauto.\n    + intros G' R' G'_R' L_R' al_R' bound_R'.\n      rewrite fst_zip_pair; eauto with len.\n      rewrite slot_lift_params_app; eauto with len.\n      rewrite getAnn_map_setTopAnn.\n      rewrite Take.take_eq_ge;\n        [|unfold slot_merge; len_simpl; rewrite <- H31, <- H32; omega].\n      rewrite slot_merge_app.\n\n      rewrite fst_zip_pair in al_R'; eauto with len.\n      rewrite slot_lift_params_app in al_R'; eauto with len.\n      rewrite getAnn_map_setTopAnn in al_R'.\n      rewrite Take.take_eq_ge in al_R';\n        [|unfold slot_merge; len_simpl; rewrite <- H31, <- H32; omega].\n      rewrite slot_merge_app in al_R'.\n\n      econstructor.\n      * unfold bounded_in.\n        rewrite subset_cardinal; eauto.\n        rewrite union_meet_distr_l.\n        rewrite empty_neutral_union_r in al_R'.\n        rewrite G'_R', al_R'.\n        clear; cset_tac.\n      * intros; inv_get.\n        rewrite <- reconstr_live_setTopAnn.\n        exploit H10 as funConstr; eauto.\n        exploit renaF as renaF'; eauto.\n        exploit H34 as spillSnd'; eauto.\n        exploit H20 as rm_VD; eauto.\n        destruct rm_VD as [f_x3_VD s_x3_VD]; eauto.\n        rewrite pair_eta with (p:=x3) in spillSnd'.\n        destruct funConstr as [funConstr _].\n        apply incl_from_union_eq in funConstr as funConstr1.\n        rewrite union_comm in funConstr.\n        apply incl_from_union_eq in funConstr as funConstr2.\n        simpl.\n        eapply H1 with (R:=fst x3) (M:=snd x3); eauto.\n        -- rewrite renaF', <- ra_VD; eauto.\n        -- eapply getAnn_als_EQ_merge_rms; eauto.\n        -- intros.\n           eapply get_ofl_VD; eauto.\n        -- intros.\n           eapply get_app_cases in H4 as [?|[? ?]]; inv_get.\n           edestruct H2; eauto. len_simpl.\n           eapply get_app_ge in H14. len_simpl.\n           rewrite <- H in *.\n           eapply Z_LV; eauto. len_simpl. rewrite <- H. eauto.\n        -- setoid_rewrite pair_eta with (p:=x3) at 1.\n           rewrite pair_eta with (p:=x3) in H23.\n           eapply al_sub_RfMf in H23; eauto.\n           rewrite ofl_slp_sub_rm; eauto.\n           ++ rewrite union_meet_distr_l.\n              apply union_incl_split.\n              ** clear; cset_tac.\n              ** rewrite disj_empty_cut; eauto.\n                 clear; cset_tac.\n           ++ exploit H2 as H2'; eauto.\n      * eapply IHlvSnd with (R:=R\\K ∪ L) (M:=Sp ∪ M); eauto.\n        -- eapply R'_VD with (VD:=VD) (L:=L) (M:=M); eauto.\n        -- rewrite H28, R_VD, M_VD; eauto.\n           clear; cset_tac.\n        -- rewrite rena2, <- ra_VD; eauto.\n        -- apply getAnn_als_EQ_merge_rms; eauto.\n        -- intros.\n           eapply get_ofl_VD; eauto.\n        -- intros.\n           eapply get_app_cases in H4 as [?|[? ?]]; inv_get.\n           edestruct H2; eauto. len_simpl.\n           eapply get_app_ge in H5. len_simpl.\n           rewrite <- H in *.\n           eapply Z_LV; eauto. len_simpl. rewrite <- H. eauto.\n        -- 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/RegisterBound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.25899539201439353}}
{"text": "Require Import TestSuite.admit.\n(* File reduced by coq-bug-finder from original input, then from 2073 lines to 358 lines, then from 359 lines to 218 lines, then from 107 lines to 92 lines *)\n(* coqc version trunk (October 2014) compiled on Oct 11 2014 1:13:41 with OCaml 4.01.0\n   coqtop version cagnode16:/afs/csail.mit.edu/u/j/jgross/coq-trunk,trunk (d65496f09c4b68fa318783e53f9cd6d5c18e1eb7) *)\nRequire Coq.Lists.List.\n\nImport Coq.Lists.List.\n\nSet Implicit Arguments.\nGlobal Set Asymmetric Patterns.\n\nSection machine.\n  Variables pc state : Type.\n\n  Inductive propX (i := pc) (j := state) : list Type -> Type :=\n  | Inj : forall G, Prop -> propX G\n  | ExistsX : forall G A, propX (A :: G) -> propX G.\n\n  Arguments Inj [G].\n\n  Definition PropX := propX nil.\n  Fixpoint last (G : list Type) : Type.\n    exact (match G with\n             | nil => unit\n             | T :: nil => T\n             | _ :: G' => last G'\n           end).\n  Defined.\n  Fixpoint eatLast (G : list Type) : list Type.\n    exact (match G with\n             | nil => nil\n             | _ :: nil => nil\n             | x :: G' => x :: eatLast G'\n           end).\n  Defined.\n\n  Fixpoint subst G (p : propX G) : (last G -> PropX) -> propX (eatLast G) :=\n    match p with\n      | Inj _ P => fun _ => Inj P\n      | ExistsX G A p1 => fun p' =>\n                            match G return propX (A :: G) -> propX (eatLast (A :: G)) -> propX (eatLast G) with\n                              | nil => fun p1 _ => ExistsX p1\n                              | _ :: _ => fun _ rc => ExistsX rc\n                            end p1 (subst p1 (match G return (last G -> PropX) -> last (A :: G) -> PropX with\n                                                | nil => fun _ _ => Inj True\n                                                | _ => fun p' => p'\n                                              end p'))\n    end.\n\n  Definition spec := state -> PropX.\n  Definition codeSpec := pc -> option spec.\n\n  Inductive valid (specs : codeSpec) (G : list PropX) : PropX -> Prop := Env : forall P, In P G -> valid specs G P.\n  Definition interp specs := valid specs nil.\nEnd machine.\nNotation \"'ExX' : A , P\" := (ExistsX (A := A) P) (at level 89) : PropX_scope.\nBind Scope PropX_scope with PropX propX.\nVariables pc state : Type.\n\nInductive subs : list Type -> Type :=\n| SNil : subs nil\n| SCons : forall T Ts, (last (T :: Ts) -> PropX pc state) -> subs (eatLast (T :: Ts)) -> subs (T :: Ts).\n\nFixpoint SPush G T (s : subs G) (f : T -> PropX pc state) : subs (T :: G) :=\n  match s in subs G return subs (T :: G) with\n    | SNil => SCons _ nil f SNil\n    | SCons T' Ts f' s' => SCons T (T' :: Ts) f' (SPush s' f)\n  end.\n\nFixpoint Substs G (s : subs G) : propX pc state G -> PropX pc state :=\n  match s in subs G return propX pc state G -> PropX pc state with\n    | SNil => fun p => p\n    | SCons _ _ f s' => fun p => Substs s' (subst p f)\n  end.\nVariable specs : codeSpec pc state.\n\nLemma simplify_fwd_ExistsX : forall G A s (p : propX pc state (A :: G)),\n                               interp specs (Substs s (ExX  : A, p))\n                               -> exists a, interp specs (Substs (SPush s a) p).\nadmit.\nDefined.\n\nGoal    forall (G : list Type) (A : Type) (p : propX pc state (@cons Type A G))\n               (s : subs G)\n               (_ : @interp pc state specs (@Substs G s (@ExistsX pc state G A p)))\n               (P : forall _ : subs (@cons Type A G), Prop)\n               (_ : forall (s0 : subs (@cons Type A G))\n                           (_ : @interp pc state specs (@Substs (@cons Type A G) s0 p)),\n                      P s0),\n          @ex (forall _ : A, PropX pc state)\n              (fun a : forall _ : A, PropX pc state => P (@SPush G A s a)).\n  intros ? ? ? ? H ? H'.\n  apply simplify_fwd_ExistsX in H.\n  firstorder. \nQed.\n (* Toplevel input, characters 15-19:\nError: Illegal application:\nThe term \"cons\" of type \"forall A : Type, A -> list A -> list A\"\ncannot be applied to the terms\n \"Type\" : \"Type\"\n \"T\" : \"Type\"\n \"G0\" : \"list Type\"\nThe 2nd term has type \"Type@{Top.53}\" which should be coercible to\n \"Type@{Top.12}\".\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/3732.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.25898770215519706}}
{"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 r1' rt1' r2 r2' rt2 rt2' ,\n   instructionAt m pc = Some i ->\n   NormalStep se reg m sgn i (pc,r1) rt1 (pc2,r2) rt2 ->\n   NormalStep se reg m sgn i (pc,r1') rt1' (pc2',r2') rt2' ->\n   pc2 <> pc2' ->\n   st_in kobs rt1 rt1' (pc,r1) (pc,r1') ->\n\n    forall j, reg pc j -> ~ L.leql (se j) kobs.\nProof.\n  intros sgn pc pc2 pc2' i r1 rt1 r1' rt1' r2 r2' rt2 rt2' 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_I/DEX_ElemLemmaNormalIntra3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.25898770215519706}}
{"text": "Require Import Util IL Even DecSolve Indexwise MoreList NoParams VarP.\n\nDefinition isReg x := Even.even_pos_fast x.\n\nDefinition regbnd k (x:positive) := isReg x -> (x <= k)%positive.\n\nInstance regbnd_computable k x : Computable (regbnd x k).\nProof.\n  unfold regbnd. eauto with typeclass_instances.\nQed.\n\nInductive simplOp : op -> Prop :=\n| SCon v : simplOp (Con v)\n| SVar x : simplOp (Var x)\n| SNot x (RGa:isReg x) :  simplOp (UnOp UnOpNot (Var x))\n| SNeg x (RGa:isReg x) :  simplOp (UnOp UnOpNeg (Var x))\n| SBinOp bop x y (RGa:isReg x) (RGb:isReg y) : simplOp (BinOp bop (Var x) (Var y))\n| SBinOpV1 bop x y (RGa:isReg x) (notDiv:bop <> BinOpDiv) : simplOp (BinOp bop (Var x) (Con y))\n| SBinOpV2 bop x y (RGb:isReg y) (notDiv:bop <> BinOpDiv) : simplOp (BinOp bop (Con x) (Var y))\n.\n\nInstance simplOp_computable o : Computable (simplOp o).\nProof.\n  destruct o; try dec_solve.\n  destruct u, o; try dec_solve; decide (isReg p); dec_solve.\n  destruct o1, o2; try dec_solve;\n    try decide (isReg p); try decide (isReg p0); try dec_solve;\n      decide (b = BinOpDiv); try dec_solve.\nQed.\n\nDefinition simplExp e := match e with\n                        | Operation e' => simplOp e'\n                        | _ => False\n                        end.\n\nInstance simplExp_computable e : Computable (simplExp e).\nProof.\n  destruct e; simpl; eauto with typeclass_instances.\nQed.\n\nInductive simplLet x : op -> Prop :=\n| SimpleOp e (RG:isReg x) (SO:simplOp e) : simplLet x e\n| SimpleStore y (RG: isReg y) (MM:~isReg x) : simplLet x (Var y).\n\nInstance simplLet_computable x o : Computable (simplLet x o).\nProof.\n  decide (isReg x).\n  - decide (simplOp o); dec_solve.\n  - destruct o; try dec_solve.\n    decide (isReg p); dec_solve.\nQed.\n\nDefinition isComparision (bop:binop) :=\n  match bop with\n  | BinOpLt => true\n  | BinOpEq => true\n  | BinOpGe => true\n  | BinOpGt => true\n  | _ => false\n  end.\n\nInductive simplCond : op -> Prop :=\n| SimplCondVar x (RG:isReg x)\n  : simplCond (Var x)\n| SimplCondLt x y (RG1:isReg x) (RG2:isReg y) op\n              (OP:isComparision op)\n  : simplCond (BinOp op (Var x) (Var y))\n| SimplCondLt1 x y (RG1:isReg x) op\n               (OP:isComparision op)\n  : simplCond (BinOp op (Var x) (Con y))\n| SimplCondLt2 x y (RG2:isReg y) op\n               (OP:isComparision op)\n  : simplCond (BinOp op (Con x) (Var y)).\n\nInstance simplCond_computable o : Computable (simplCond o).\nProof.\n  destruct o; try dec_solve.\n  - decide (isReg p); dec_solve.\n  - decide (isComparision b); try dec_solve.\n    destruct o1, o2; try decide (isReg p); try decide (isReg p0); try dec_solve.\nQed.\n\nInductive isLinearizable : stmt->Prop :=\n| IsLinLet x e s\n    (LinIH:isLinearizable s)\n    (SimplLet:simplLet x e)\n    : isLinearizable (stmtLet x (Operation e) s)\n| IsLinIf e s t\n          (SimplCond:simplCond e)\n          (LinIH1:isLinearizable s)\n          (LinIH2:isLinearizable t)\n  : isLinearizable (stmtIf e s t)\n| IsLinApp l Y :\n   isLinearizable (stmtApp l Y)\n| IsLinExp e\n           (SimplReg:simplOp e)\n  : isLinearizable (stmtReturn e)\n| IsLinCall F t\n  : (forall n Zs, get F n Zs -> isLinearizable (snd Zs))\n    -> isLinearizable t\n    -> isLinearizable (stmtFun F t).\n\nInstance isLinearizable_computable s : Computable (isLinearizable s).\nProof.\n  sind s; destruct s.\n  - destruct e; try dec_solve.\n    decide (simplLet x e); try dec_solve.\n    destruct (IH s); try dec_solve.\n  - decide (simplCond e); try dec_solve.\n    destruct (IH s1); eauto; try dec_solve;\n      destruct (IH s2); eauto; try dec_solve.\n  - left; eauto using isLinearizable.\n  - decide (simplOp e); try dec_solve.\n  - destruct (IH s); eauto; try dec_solve.\n    assert (Computable (forall n Zs, get F n Zs -> isLinearizable (snd Zs))). {\n      eapply indexwise_P_dec. intros. eapply IH; eauto.\n    }\n    destruct H; dec_solve.\nQed.\n\nDefinition isLinearizableStmt s := B[isLinearizable s].\n\nRequire Import Status.\n\nDefinition toLinearPreconditions k s : status unit :=\n  if [noParams s] then\n    if [isLinearizable s] then\n      if [ var_P (regbnd k) s ] then\n        Success tt\n      else\n        Error \"Register bound not OK\"\n    else\n      Error \"Program is not linearizable\"\n  else\n    Error \"There are parameters left in the program\".\n", "meta": {"author": "sigurdschneider", "repo": "lvc", "sha": "be41194f16495d283fe7bbc982c3393ac554dd5b", "save_path": "github-repos/coq/sigurdschneider-lvc", "path": "github-repos/coq/sigurdschneider-lvc/lvc-be41194f16495d283fe7bbc982c3393ac554dd5b/theories/Lowering/IsLinearizable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.25898770215519706}}
{"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.\n#[global] Instance Join_pshare: Join pshare := @Join_lift _ _.\n#[global] Instance Perm_pshare : Perm_alg pshare := Perm_lift Share.pa.\n#[global] Instance Canc_pshare : Canc_alg pshare := @Canc_lift _ _ Share.ca.\n#[global] Instance Disj_pshare : Disj_alg pshare := @Disj_lift _ _ Share.da.\n#[global] Instance 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\n#[global] Instance 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  exfalso;\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": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/msl/pshares.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.25898769569182756}}
{"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 ReflParam.indType.\nRequire Import SquiggleEq.substitution.\nRequire Import ReflParam.PiTypeR.\nImport ListNotations.\nOpen Scope string_scope.\n\n\nInductive multInd (A I : Set) (B: I-> Set) (f: A-> I) (g: forall i, B i) \n  : forall (i:I) (b:B i), Set  :=  \nmlind : forall a, multInd A I B f g (f a) (g (f a)).\n\n\nRequire Import SquiggleEq.UsefulTypes.\n\n(*\n(fun (A A₂ : Set) (A_R : A -> A₂ -> Prop) (I I₂ : Set)\n   (I_R : I -> I₂ -> Prop) (B : I -> Set) (B₂ : I₂ -> Set)\n   (B_R : forall (H : I) (H0 : I₂), I_R H H0 -> B H -> B₂ H0 -> Prop)\n   (f : A -> I) (f₂ : A₂ -> I₂)\n   (f_R : forall (H : A) (H0 : A₂), A_R H H0 -> I_R (f H) (f₂ H0))\n   (g : forall i : I, B i) (g₂ : forall i₂ : I₂, B₂ i₂)\n   (g_R : forall (i : I) (i₂ : I₂) (i_R : I_R i i₂),\n          B_R i i₂ i_R (g i) (g₂ i₂)) (a : A) (a₂ : A₂)\n   (i_R : I_R (f a) (f₂ a₂))\n   (b_R : B_R (f a) (f₂ a₂) i_R (g (f a)) (g₂ (f₂ a₂)))\n   (sigt_R : {a_R : A_R a a₂ &\n             Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R B\n               B₂ B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) \n               (f_R a a₂ a_R) (g (f a)) (g₂ (f₂ a₂))\n               (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)) i_R b_R})\n   (retTyp_R : forall (i_R0 : I_R (f a) (f₂ a₂))\n                 (b_R0 : B_R (f a) (f₂ a₂) i_R0 (g (f a)) (g₂ (f₂ a₂))),\n               {a_R : A_R a a₂ &\n               Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R\n                 B B₂ B_R f f₂ f_R g g₂ g_R (f a) \n                 (f₂ a₂) (f_R a a₂ a_R) (g (f a)) \n                 (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)) i_R0 b_R0} ->\n               Set)\n   (rett_R : forall a_R : A_R a a₂,\n             retTyp_R (f_R a a₂ a_R) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R))\n               (existT\n                  (fun a_R0 : A_R a a₂ =>\n                   Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂\n                     I_R B B₂ B_R f f₂ f_R g g₂ g_R \n                     (f a) (f₂ a₂) (f_R a a₂ a_R0) \n                     (g (f a)) (g₂ (f₂ a₂))\n                     (g_R (f a) (f₂ a₂) (f_R a a₂ a_R0)) \n                     (f_R a a₂ a_R) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R))) a_R\n                  (Top_multIndices2_multInd_pmtcty_RR0_indicesc A A₂ A_R I I₂\n                     I_R B B₂ B_R f f₂ f_R g g₂ g_R \n                     (f a) (f₂ a₂) (f_R a a₂ a_R) \n                     (g (f a)) (g₂ (f₂ a₂))\n                     (g_R (f a) (f₂ a₂) (f_R a a₂ a_R))))) =>\n sigT_rec\n   (fun\n      sigt_R0 : {a_R : A_R a a₂ &\n                Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R\n                  B B₂ B_R f f₂ f_R g g₂ g_R (f a) \n                  (f₂ a₂) (f_R a a₂ a_R) (g (f a)) \n                  (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)) i_R b_R} =>\n    retTyp_R i_R b_R sigt_R0)\n   (fun a_R : A_R a a₂ =>\n    match\n      sigt_R in\n      (Top_multIndices2_multInd_pmtcty_RR0_indices _ _ _ _ _ _ _ _ _ _ _ _ _\n       _ _ _ _ _ _ _ _ i_R0 b_R0)\n      return\n        (fun\n           sigt_R1 : Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I\n                       I₂ I_R B B₂ B_R f f₂ f_R g g₂ g_R \n                       (f a) (f₂ a₂) (f_R a a₂ a_R) \n                       (g (f a)) (g₂ (f₂ a₂))\n                       (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)) i_R0 b_R0 =>\n         retTyp_R i_R0 b_R0\n           (existT\n              (fun a_R0 : A_R a a₂ =>\n               Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R\n                 B B₂ B_R f f₂ f_R g g₂ g_R (f a) \n                 (f₂ a₂) (f_R a a₂ a_R0) (g (f a)) \n                 (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R0)) i_R0 b_R0)\n              a_R sigt_R1))\n    with\n    | Top_multIndices2_multInd_pmtcty_RR0_indicesc _ _ _ _ _ _ _ _ _ _ _ _ _\n      _ _ _ _ _ _ _ _ => rett_R a_R\n    end))\n\n*)\n\nRun TemplateProgram (genParamInd [] true true \"Top.multIndices2.multInd\").\n\n(*\n(fix\n Top_multIndices2_multInd_pmtcty_RR0 (A A₂ : Set) \n                                     (A_R : A -> A₂ -> Prop) \n                                     (I I₂ : Set) \n                                     (I_R : I -> I₂ -> Prop)\n                                     (B : I -> Set) \n                                     (B₂ : I₂ -> Set)\n                                     (B_R : forall (H : I) (H0 : I₂),\n                                            I_R H H0 ->\n                                            B H -> B₂ H0 -> Prop)\n                                     (f : A -> I) \n                                     (f₂ : A₂ -> I₂)\n                                     (f_R : forall (H : A) (H0 : A₂),\n                                            A_R H H0 -> I_R (f H) (f₂ H0))\n                                     (g : forall i : I, B i)\n                                     (g₂ : forall i₂ : I₂, B₂ i₂)\n                                     (g_R : forall \n                                              (i : I) \n                                              (i₂ : I₂) \n                                              (i_R : I_R i i₂),\n                                            B_R i i₂ i_R (g i) (g₂ i₂))\n                                     (i : I) (i₂ : I₂) \n                                     (i_R : I_R i i₂) \n                                     (b : B i) (b₂ : B₂ i₂)\n                                     (b_R : B_R i i₂ i_R b b₂)\n                                     (H : multInd A I B f g i b)\n                                     (H0 : multInd A₂ I₂ B₂ f₂ g₂ i₂ b₂)\n                                     {struct H} : Prop :=\n   match\n     H in (multInd _ _ _ _ _ i0 b0)\n     return (forall i_R0 : I_R i0 i₂, B_R i0 i₂ i_R0 b0 b₂ -> Prop)\n   with\n   | mlind _ _ _ _ _ a =>\n       match\n         H0 in (multInd _ _ _ _ _ i₂0 b₂0)\n         return\n           (forall i_R0 : I_R (f a) i₂0,\n            B_R (f a) i₂0 i_R0 (g (f a)) b₂0 -> Prop)\n       with\n       | mlind _ _ _ _ _ a₂ =>\n           fun (i_R0 : I_R (f a) (f₂ a₂))\n             (b_R0 : B_R (f a) (f₂ a₂) i_R0 (g (f a)) (g₂ (f₂ a₂))) =>\n           {a_R : A_R a a₂ &\n           Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R B\n             B₂ B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) \n             (f_R a a₂ a_R) (g (f a)) (g₂ (f₂ a₂))\n             (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)) i_R0 b_R0}\n       end\n   end i_R b_R)\n(fun (A A₂ : Set) (A_R : A -> A₂ -> Prop) (I I₂ : Set)\n   (I_R : I -> I₂ -> Prop) (B : I -> Set) (B₂ : I₂ -> Set)\n   (B_R : forall (H : I) (H0 : I₂), I_R H H0 -> B H -> B₂ H0 -> Prop)\n   (f : A -> I) (f₂ : A₂ -> I₂)\n   (f_R : forall (H : A) (H0 : A₂), A_R H H0 -> I_R (f H) (f₂ H0))\n   (g : forall i : I, B i) (g₂ : forall i₂ : I₂, B₂ i₂)\n   (g_R : forall (i : I) (i₂ : I₂) (i_R : I_R i i₂),\n          B_R i i₂ i_R (g i) (g₂ i₂)) (a : A) (a₂ : A₂)\n   (i_R : I_R (f a) (f₂ a₂))\n   (b_R : B_R (f a) (f₂ a₂) i_R (g (f a)) (g₂ (f₂ a₂)))\n   (sigt_R : {a_R : A_R a a₂ &\n             Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R\n               B B₂ B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) \n               (f_R a a₂ a_R) (g (f a)) (g₂ (f₂ a₂))\n               (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)) i_R b_R})\n   (retTyp_R : forall (i_R0 : I_R (f a) (f₂ a₂))\n                 (b_R0 : B_R (f a) (f₂ a₂) i_R0 (g (f a)) (g₂ (f₂ a₂))),\n               {a_R : A_R a a₂ &\n               Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂\n                 I_R B B₂ B_R f f₂ f_R g g₂ g_R (f a) \n                 (f₂ a₂) (f_R a a₂ a_R) (g (f a)) \n                 (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)) i_R0 b_R0} ->\n               Set)\n   (rett_R : forall a_R : A_R a a₂,\n             retTyp_R (f_R a a₂ a_R) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R))\n               (existT\n                  (fun a_R0 : A_R a a₂ =>\n                   Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I\n                     I₂ I_R B B₂ B_R f f₂ f_R g g₂ g_R \n                     (f a) (f₂ a₂) (f_R a a₂ a_R0) \n                     (g (f a)) (g₂ (f₂ a₂))\n                     (g_R (f a) (f₂ a₂) (f_R a a₂ a_R0)) \n                     (f_R a a₂ a_R) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)))\n                  a_R\n                  (Top_multIndices2_multInd_pmtcty_RR0_indicesc A A₂ A_R I\n                     I₂ I_R B B₂ B_R f f₂ f_R g g₂ g_R \n                     (f a) (f₂ a₂) (f_R a a₂ a_R) \n                     (g (f a)) (g₂ (f₂ a₂))\n                     (g_R (f a) (f₂ a₂) (f_R a a₂ a_R))))) =>\n sigT_rec\n   (fun\n      sigt_R0 : {a_R : A_R a a₂ &\n                Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂\n                  I_R B B₂ B_R f f₂ f_R g g₂ g_R \n                  (f a) (f₂ a₂) (f_R a a₂ a_R) (g (f a)) \n                  (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)) i_R b_R}\n    => retTyp_R i_R b_R sigt_R0)\n   (fun (a_R : A_R a a₂)\n      (sigt_R0 : Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂\n                   I_R B B₂ B_R f f₂ f_R g g₂ g_R \n                   (f a) (f₂ a₂) (f_R a a₂ a_R) (g (f a)) \n                   (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)) i_R b_R)\n    =>\n    match\n      sigt_R0 as sigt_R1 in\n      (Top_multIndices2_multInd_pmtcty_RR0_indices _ _ _ _ _ _ _ _ _ _ _ _\n       _ _ _ _ _ _ _ _ _ i_R0 b_R0)\n      return\n        (retTyp_R i_R0 b_R0\n           (existT\n              (fun a_R0 : A_R a a₂ =>\n               Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂\n                 I_R B B₂ B_R f f₂ f_R g g₂ g_R (f a) \n                 (f₂ a₂) (f_R a a₂ a_R0) (g (f a)) \n                 (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R0)) i_R0\n                 b_R0) a_R sigt_R1))\n    with\n    | Top_multIndices2_multInd_pmtcty_RR0_indicesc _ _ _ _ _ _ _ _ _ _ _ _\n      _ _ _ _ _ _ _ _ _ => rett_R a_R\n    end) sigt_R)\n(fun (A A₂ : Set) (A_R : A -> A₂ -> Prop) (I I₂ : Set)\n   (I_R : I -> I₂ -> Prop) (B : I -> Set) (B₂ : I₂ -> Set)\n   (B_R : forall (H : I) (H0 : I₂), I_R H H0 -> B H -> B₂ H0 -> Prop)\n   (f : A -> I) (f₂ : A₂ -> I₂)\n   (f_R : forall (H : A) (H0 : A₂), A_R H H0 -> I_R (f H) (f₂ H0))\n   (g : forall i : I, B i) (g₂ : forall i₂ : I₂, B₂ i₂)\n   (g_R : forall (i : I) (i₂ : I₂) (i_R : I_R i i₂),\n          B_R i i₂ i_R (g i) (g₂ i₂)) (a : A) (a₂ : A₂) \n   (a_R : A_R a a₂) =>\n existT\n   (fun a_R0 : A_R a a₂ =>\n    Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R B B₂ B_R\n      f f₂ f_R g g₂ g_R (f a) (f₂ a₂) (f_R a a₂ a_R0) \n      (g (f a)) (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R0))\n      (f_R a a₂ a_R) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R))) a_R\n   (Top_multIndices2_multInd_pmtcty_RR0_indicesc A A₂ A_R I I₂ I_R B B₂\n      B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) (f_R a a₂ a_R) \n      (g (f a)) (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R))))\n\n*)\n\n\n\nPrint multInd_rect.\nPrint nat_rect.\n\nDefinition multInd_recs := \nfun (A I : Set) (B : I -> Set) (f : A -> I) (g : forall i : I, B i)\n  (P : forall (i : I) (b : B i), multInd A I B f g i b -> Set)\n  (ff : forall a : A, P (f a) (g (f a)) (mlind A I B f g a)) (i : I) \n  (a : B i) (m : multInd A I B f g i a) =>\nmatch m as m0 in (multInd _ _ _ _ _ i0 a0) return (P i0 a0 m0) with\n| mlind _ _ _ _ _ x => ff x\nend.\n\n(*\nParametricity Recursive multInd_recs.\n*)\n\nNotation multInd_RR:=Top_multIndices2_multInd_pmtcty_RR0.\n\nSearchAbout multInd.\nDefinition mlind_RR : forall (A₁ A₂ : Set) (A_R : A₁ -> A₂ -> Prop) (I₁ I₂ : Set) \n         (I_R : I₁ -> I₂ -> Prop) (B₁ : I₁ -> Set) (B₂ : I₂ -> Set)\n         (B_R : forall (H : I₁) (H0 : I₂), I_R H H0 -> B₁ H -> B₂ H0 -> Prop) \n         (f₁ : A₁ -> I₁) (f₂ : A₂ -> I₂)\n         (f_R : forall (H : A₁) (H0 : A₂), A_R H H0 -> I_R (f₁ H) (f₂ H0))\n         (g₁ : forall i : I₁, B₁ i) (g₂ : forall i : I₂, B₂ i)\n         (g_R : forall (i₁ : I₁) (i₂ : I₂) (i_R : I_R i₁ i₂), B_R i₁ i₂ i_R (g₁ i₁) (g₂ i₂))\n         (a₁ : A₁) (a₂ : A₂) (a_R : A_R a₁ a₂),\n       multInd_RR A₁ A₂ A_R I₁ I₂ I_R B₁ B₂ B_R f₁ f₂ f_R g₁ g₂ g_R \n         (f₁ a₁) (f₂ a₂) (f_R a₁ a₂ a_R) (g₁ (f₁ a₁)) (g₂ (f₂ a₂))\n         (g_R (f₁ a₁) (f₂ a₂) (f_R a₁ a₂ a_R)) (mlind A₁ I₁ B₁ f₁ g₁ a₁)\n         (mlind A₂ I₂ B₂ f₂ g₂ a₂):=\n         Top_multIndices2_multInd_pmtcty_RR0_constr_0.\n\nRun TemplateProgram (mkIndEnv \"indTransEnv\" [\"Top.multIndices2.multInd\"]). \n\nRun TemplateProgram (genParam indTransEnv false true \"multInd_recs\"). (* success!*)\n\n\nDefinition mutInd_CRRinv (A A₂ : Set) (A_R : A -> A₂ -> Prop) (I I₂ : Set) \n   (I_R : I -> I₂ -> Prop) (B : I -> Set) (B₂ : I₂ -> Set)\n   (B_R : forall (H : I) (H0 : I₂), I_R H H0 -> B H -> B₂ H0 -> Prop)\n   (f : A -> I) (f₂ : A₂ -> I₂)\n   (f_R : forall (H : A) (H0 : A₂), A_R H H0 -> I_R (f H) (f₂ H0))\n   (g : forall i : I, B i) (g₂ : forall i₂ : I₂, B₂ i₂)\n   (g_R : forall (i : I) (i₂ : I₂) (i_R : I_R i i₂), B_R i i₂ i_R (g i) (g₂ i₂))\n   (a : A) (a₂ : A₂) (i_R : I_R (f a) (f₂ a₂))\n   (b_R : B_R (f a) (f₂ a₂) i_R (g (f a)) (g₂ (f₂ a₂)))\n   (sigt_R : {a_R : A_R a a₂ &\n             Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R B B₂\n               B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) (f_R a a₂ a_R) \n               (g (f a)) (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)) i_R b_R})\n   (retTyp_R : forall (i_R0 : I_R (f a) (f₂ a₂))\n                 (b_R0 : B_R (f a) (f₂ a₂) i_R0 (g (f a)) (g₂ (f₂ a₂))),\n               {a_R : A_R a a₂ &\n               Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R B B₂\n                 B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) \n                 (f_R a a₂ a_R) (g (f a)) (g₂ (f₂ a₂))\n                 (g_R (f a) (f₂ a₂) (f_R a a₂ a_R)) i_R0 b_R0} -> Set)\n   (ff : forall a_R : A_R a a₂,\n        retTyp_R (f_R a a₂ a_R) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R))\n          (existT\n             (fun a_R0 : A_R a a₂ =>\n              Top_multIndices2_multInd_pmtcty_RR0_indices A A₂ A_R I I₂ I_R B B₂\n                B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) (f_R a a₂ a_R0) \n                (g (f a)) (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R0))\n                (f_R a a₂ a_R) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R))) a_R\n             (Top_multIndices2_multInd_pmtcty_RR0_indicesc A A₂ A_R I I₂ I_R B B₂\n                B_R f f₂ f_R g g₂ g_R (f a) (f₂ a₂) (f_R a a₂ a_R) \n                (g (f a)) (g₂ (f₂ a₂)) (g_R (f a) (f₂ a₂) (f_R a a₂ a_R))))) :\n  (retTyp_R i_R b_R sigt_R).\nProof.\n  Show Proof.\n  revert sigt_R.\n  Show Proof.\n  apply sigT_rec.\n  Show Proof.\nArguments sigT_rec : clear implicits.\n  Show Proof. intros a_R.\n  intros peq.\n  destruct peq.\n  exact (ff a_R).\n  Print sigT_rec.\nDefined.\n  Arguments existT {A} {P} x p.\n  Arguments sigT_rec {A} {P} P0 f s.\nDefinition multIndices_recs:\nforall (A₁ A₂ : Set) (A_R : A₁ -> A₂ -> Prop) (I₁ I₂ : Set) \n         (I_R : I₁ -> I₂ -> Prop) (B₁ : I₁ -> Set) (B₂ : I₂ -> Set)\n         (B_R : forall (H : I₁) (H0 : I₂), I_R H H0 -> B₁ H -> B₂ H0 -> Prop) \n         (f₁ : A₁ -> I₁) (f₂ : A₂ -> I₂)\n         (f_R : forall (H : A₁) (H0 : A₂), A_R H H0 -> I_R (f₁ H) (f₂ H0))\n         (g₁ : forall i : I₁, B₁ i) (g₂ : forall i : I₂, B₂ i)\n         (g_R : forall (i₁ : I₁) (i₂ : I₂) (i_R : I_R i₁ i₂), B_R i₁ i₂ i_R (g₁ i₁) (g₂ i₂))\n         (P₁ : forall (i : I₁) (b : B₁ i), multInd A₁ I₁ B₁ f₁ g₁ i b -> Set)\n         (P₂ : forall (i : I₂) (b : B₂ i), multInd A₂ I₂ B₂ f₂ g₂ i b -> Set)\n         (P_R : forall (i₁ : I₁) (i₂ : I₂) (i_R : I_R i₁ i₂) (b₁ : B₁ i₁) \n                  (b₂ : B₂ i₂) (b_R : B_R i₁ i₂ i_R b₁ b₂)\n                  (H : multInd A₁ I₁ B₁ f₁ g₁ i₁ b₁) (H0 : multInd A₂ I₂ B₂ f₂ g₂ i₂ b₂),\n                multInd_RR A₁ A₂ A_R I₁ I₂ I_R B₁ B₂ B_R f₁ f₂ f_R g₁ g₂ g_R i₁ i₂ i_R b₁ b₂\n                  b_R H H0 -> P₁ i₁ b₁ H -> P₂ i₂ b₂ H0 -> Prop)\n         (f0₁ : forall a : A₁, P₁ (f₁ a) (g₁ (f₁ a)) (mlind A₁ I₁ B₁ f₁ g₁ a))\n         (f0₂ : forall a : A₂, P₂ (f₂ a) (g₂ (f₂ a)) (mlind A₂ I₂ B₂ f₂ g₂ a)),\n       (forall (a₁ : A₁) (a₂ : A₂) (a_R : A_R a₁ a₂),\n        P_R (f₁ a₁) (f₂ a₂) (f_R a₁ a₂ a_R) (g₁ (f₁ a₁)) (g₂ (f₂ a₂))\n          (g_R (f₁ a₁) (f₂ a₂) (f_R a₁ a₂ a_R)) (mlind A₁ I₁ B₁ f₁ g₁ a₁)\n          (mlind A₂ I₂ B₂ f₂ g₂ a₂)\n          (mlind_RR A₁ A₂ A_R I₁ I₂ I_R B₁ B₂ B_R f₁ f₂ f_R g₁ g₂ g_R a₁ a₂ a_R)\n          (f0₁ a₁) (f0₂ a₂)) ->\n       forall (i₁ : I₁) (i₂ : I₂) (i_R : I_R i₁ i₂) (a₁ : B₁ i₁) \n         (a₂ : B₂ i₂) (a_R : B_R i₁ i₂ i_R a₁ a₂) (m₁ : multInd A₁ I₁ B₁ f₁ g₁ i₁ a₁)\n         (m₂ : multInd A₂ I₂ B₂ f₂ g₂ i₂ a₂)\n         (m_R : multInd_RR A₁ A₂ A_R I₁ I₂ I_R B₁ B₂ B_R f₁ f₂ f_R g₁ g₂ g_R i₁ i₂ i_R a₁ a₂\n                  a_R m₁ m₂),\n       P_R i₁ i₂ i_R a₁ a₂ a_R m₁ m₂ m_R (multInd_recs A₁ I₁ B₁ f₁ g₁ P₁ f0₁ i₁ a₁ m₁)\n         (multInd_recs A₂ I₂ B₂ f₂ g₂ P₂ f0₂ i₂ a₂ m₂) \n         \n         := multInd_recs_pmtcty_RR.\n(*\nProof using.\n  intros. apply multInd_recs_RR.\n  rename a_R into b_R.\n  revert m_R.\n  destruct m₁.\n  destruct m₂.\n  intros ?.\n  simpl in *.\n  unfold mlind_RR in H.\n  destruct m_R as [a_R peq].\n  (* do the remaining in a separate C_RRinv construct? *)\n  specialize (H _ _ a_R).\n  (* here, peq needs to change to eq_refl *)\n  generalize peq.\n  generalize b_R.\n  generalize i_R.\n  apply eq_rect_sigtI.\n  simpl.\n  exact H.\nDefined. \n*)\n(* see the exact below \n  exact ( eq_rect_sigt (I_R (f₁ a) (f₂ a0))\n           (fun ir : I_R (f₁ a) (f₂ a0) => B_R (f₁ a) (f₂ a0) ir (g₁ (f₁ a)) (g₂ (f₂ a0)))\n           (existT (f_R a a0 a_R) (g_R (f₁ a) (f₂ a0) (f_R a a0 a_R)))\n           (fun (a1 : I_R (f₁ a) (f₂ a0))\n              (p : B_R (f₁ a) (f₂ a0) a1 (g₁ (f₁ a)) (g₂ (f₂ a0)))\n              (e : existT (f_R a a0 a_R) (g_R (f₁ a) (f₂ a0) (f_R a a0 a_R)) = existT a1 p)\n            =>\n            P_R (f₁ a) (f₂ a0) a1 (g₁ (f₁ a)) (g₂ (f₂ a0)) p (mlind A₁ I₁ B₁ f₁ g₁ a)\n              (mlind A₂ I₂ B₂ f₂ g₂ a0) (existT a_R e) (f0₁ a) \n              (f0₂ a0)) (H _ _ a_R) i_R b_R peq).\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/test-suite/multIndices2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2589876956918275}}
{"text": "Require Import RelationClasses.\n\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Axioms.\nRequire Import List.\nFrom PromisingLib Require Import Loc.\n\nRequire Import Event.\nRequire Import Syntax.\nFrom PromisingLib Require Import Language.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nSet Implicit Arguments.\n\nModule RegFile.\n  Definition t := RegFun.t Const.t.\n\n  Definition init := RegFun.init Const.zero.\n\n  Definition eval_value (rf:t) (val:Value.t): Const.t :=\n    match val with\n    | Value.reg r => RegFun.find r rf\n    | Value.const c => c\n    end.\n\n  Definition eval_expr (rf:t) (rhs:Instr.expr): Const.t :=\n    match rhs with\n    | Instr.expr_val val => eval_value rf val\n    | Instr.expr_op1 op op1 => Op1.eval op (eval_value rf op1)\n    | Instr.expr_op2 op op1 op2 => Op2.eval op (eval_value rf op1) (eval_value rf op2)\n    end.\n\n  Definition eval_rmw (rf:t) (rmw:Instr.rmw) (val:Const.t): Const.t * option Const.t :=\n    match rmw with\n    | Instr.fetch_add addendum =>\n      (Const.add val (eval_value rf addendum), Some (Const.add val (eval_value rf addendum)))\n    | Instr.cas o n =>\n      if Const.eq_dec (eval_value rf o) val\n      then (1, Some (eval_value rf n))\n      else (0, None)\n    end.\n\n  Inductive eval_instr: forall (rf1:t) (i:Instr.t) (e:ProgramEvent.t) (rf2:t), Prop :=\n  | eval_skip\n      rf:\n      eval_instr\n        rf\n        Instr.skip\n        ProgramEvent.silent\n        rf\n  | eval_assign\n      rf lhs rhs:\n      eval_instr\n        rf\n        (Instr.assign lhs rhs)\n        ProgramEvent.silent\n        (RegFun.add lhs (eval_expr rf rhs) rf)\n  | eval_load\n      rf lhs rhs ord val:\n      eval_instr\n        rf\n        (Instr.load lhs rhs ord)\n        (ProgramEvent.read rhs val ord)\n        (RegFun.add lhs val rf)\n  | eval_store\n      rf lhs rhs ord:\n      eval_instr\n        rf\n        (Instr.store lhs rhs ord)\n        (ProgramEvent.write lhs (eval_value rf rhs) ord)\n        rf\n  | eval_update_success\n      rf lhs loc rmw ordr ordw valr valret valw\n      (RMW: eval_rmw rf rmw valr = (valret, Some valw)):\n      eval_instr\n        rf\n        (Instr.update lhs loc rmw ordr ordw)\n        (ProgramEvent.update loc valr valw ordr ordw)\n        (RegFun.add lhs valret rf)\n  | eval_update_fail\n      rf lhs loc rmw ordr ordw valr valret\n      (RMW: eval_rmw rf rmw valr = (valret, None)):\n      eval_instr\n        rf\n        (Instr.update lhs loc rmw ordr ordw)\n        (ProgramEvent.read loc valr ordr)\n        (RegFun.add lhs valret rf)\n  | eval_fence\n      rf ordr ordw:\n      eval_instr\n        rf\n        (Instr.fence ordr ordw)\n        (ProgramEvent.fence ordr ordw)\n        rf\n  | eval_syscall\n      rf lhs rhses lhs_val:\n      eval_instr\n        rf\n        (Instr.syscall lhs rhses)\n        (ProgramEvent.syscall (Event.mk lhs_val (map (eval_value rf) rhses)))\n        (RegFun.add lhs lhs_val rf)\n  .\n\n  Definition eq_except (regs:RegSet.t) (rs_src rs_tgt:RegFile.t): Prop :=\n    forall reg (REG: ~ RegSet.In reg regs), rs_src reg = rs_tgt reg.\n\n  Global Program Instance eq_except_Equivalence regs: Equivalence (eq_except regs).\n  Next Obligation.\n    ii. auto.\n  Qed.\n  Next Obligation.\n    ii. rewrite H; auto.\n  Qed.\n  Next Obligation.\n    ii. rewrite H; auto.\n  Qed.\n\n  Lemma eq_except_nil rs_src rs_tgt:\n    rs_src = rs_tgt <-> eq_except RegSet.empty rs_src rs_tgt.\n  Proof.\n    econs; i; subst; auto.\n    - econs.\n    - apply RegFun.ext. i. apply H.\n      ii. eapply RegSet.Facts.empty_iff; eauto.\n  Qed.\n\n  Lemma eq_except_mon regs1 regs2\n        (SUB: RegSet.Subset regs1 regs2):\n    eq_except regs1 <2= eq_except regs2.\n  Proof.\n    ii. specialize (PR reg). apply PR. contradict REG.\n    apply SUB. auto.\n  Qed.\n\n  Lemma eq_except_singleton r v rs:\n    eq_except (RegSet.singleton r) (RegFun.add r v rs) rs.\n  Proof.\n    ii. unfold RegFun.add, RegFun.find. condtac; auto. subst.\n    contradict REG. apply RegSet.Facts.singleton_iff. auto.\n  Qed.\n\n  Lemma eq_except_add\n        regs rs_src rs_tgt lhs val\n        (EQ: eq_except regs rs_src rs_tgt):\n    eq_except regs (RegFun.add lhs val rs_src) (RegFun.add lhs val rs_tgt).\n  Proof.\n    ii. unfold RegFun.add. condtac; ss.\n    apply EQ. ss.\n  Qed.\n\n  Lemma eq_except_value\n        rs_src rs_tgt regs v\n        (REGS: RegSet.disjoint regs (Value.regs_of v))\n        (RS: eq_except regs rs_src rs_tgt):\n    RegFile.eval_value rs_src v = RegFile.eval_value rs_tgt v.\n  Proof.\n    destruct v; auto. ss. apply RS. ii.\n    eapply REGS; eauto.\n    apply RegSet.Facts.singleton_iff. auto.\n  Qed.\n\n  Lemma eq_except_value_list\n        rs_src rs_tgt regs vl\n        (REGS: RegSet.disjoint regs (Value.regs_of_list vl))\n        (RS: eq_except regs rs_src rs_tgt):\n    map (RegFile.eval_value rs_src) vl = map (RegFile.eval_value rs_tgt) vl.\n  Proof.\n    revert REGS. induction vl; ss. i. f_equal.\n    - eapply eq_except_value; eauto.\n      ii. eapply REGS; eauto.\n      destruct a; ss.\n      + apply RegSet.singleton_spec in RHS. subst.\n        apply RegSet.add_spec. auto.\n      + inv RHS.\n    - apply IHvl.\n      ii. eapply REGS; eauto.\n      destruct a; ss.\n      apply RegSet.add_spec. auto.\n  Qed.\n\n  Lemma eq_except_expr\n        rs_src rs_tgt regs e\n        (REGS: RegSet.disjoint regs (Instr.regs_of_expr e))\n        (RS: eq_except regs rs_src rs_tgt):\n    RegFile.eval_expr rs_src e = RegFile.eval_expr rs_tgt e.\n  Proof.\n    destruct e; ss.\n    - erewrite eq_except_value; eauto.\n    - erewrite eq_except_value; eauto.\n    - erewrite (eq_except_value op1); eauto.\n      + erewrite (eq_except_value op2); eauto.\n        ii. eapply REGS; eauto.\n        apply RegSet.union_spec. auto.\n      + ii. eapply REGS; eauto.\n        apply RegSet.union_spec. auto.\n  Qed.\n\n  Lemma eq_except_rmw\n        rs_src rs_tgt regs rmw val\n        (REGS: RegSet.disjoint regs (Instr.regs_of_rmw rmw))\n        (RS: eq_except regs rs_src rs_tgt):\n    RegFile.eval_rmw rs_src rmw val = RegFile.eval_rmw rs_tgt rmw val.\n  Proof.\n    destruct rmw; ss.\n    - erewrite ? (@eq_except_value rs_src rs_tgt); eauto.\n    - erewrite ? (@eq_except_value rs_src rs_tgt); eauto.\n      + ii. eapply REGS; eauto.\n        apply RegSet.union_spec. auto.\n      + ii. eapply REGS; eauto.\n        apply RegSet.union_spec. auto.\n  Qed.\n\n  Lemma eq_except_instr\n        rs1_src rs1_tgt rs2_tgt regs instr e\n        (TGT: RegFile.eval_instr rs1_tgt instr e rs2_tgt)\n        (REGS: RegSet.disjoint regs (Instr.regs_of instr))\n        (RS: eq_except regs rs1_src rs1_tgt):\n    exists rs2_src,\n      <<SRC: RegFile.eval_instr rs1_src instr e rs2_src>> /\\\n      <<RS: eq_except regs rs2_src rs2_tgt>>.\n  Proof.\n    inv TGT; ss.\n    - eexists. splits; eauto. econs.\n    - eexists. splits; [econs|].\n      ii. generalize (RS reg). i.\n      unfold RegFun.add, RegFun.find. condtac; auto. subst.\n      eapply eq_except_expr; eauto.\n      ii. eapply REGS; eauto.\n      apply RegSet.add_spec. auto.\n    - eexists. splits; [econs|].\n      ii. specialize (RS reg).\n      unfold RegFun.add, RegFun.find. condtac; auto.\n    - erewrite <- eq_except_value; eauto.\n      eexists. splits; [econs|].\n      ii. eauto.\n    - erewrite <- eq_except_rmw in RMW; eauto.\n      + eexists. splits.\n        * econs. eauto.\n        * ii. unfold RegFun.add. condtac; auto.\n          eapply RS; eauto.\n      + ii. eapply REGS; eauto.\n        apply RegSet.add_spec. auto.\n    - erewrite <- eq_except_rmw in RMW; eauto.\n      + eexists. splits.\n        * econs. eauto.\n        * ii. unfold RegFun.add. condtac; auto.\n          eapply RS; eauto.\n      + ii. eapply REGS; eauto.\n        apply RegSet.add_spec. auto.\n    - eexists. splits; [econs|]. auto.\n    - erewrite <- eq_except_value_list; eauto.\n      + eexists. splits; [econs|].\n        ii. specialize (RS reg).\n        unfold RegFun.add, RegFun.find. condtac; auto.\n      + ii. eapply REGS; eauto.\n        apply RegSet.add_spec. auto.\n  Qed.\n\n  Lemma instr_ord_eval_instr\n        rf1 instr_src instr_tgt e_tgt rf2\n        (ORD: Instr.ord instr_src instr_tgt)\n        (EVAL: RegFile.eval_instr rf1 instr_tgt e_tgt rf2):\n    exists e_src,\n      <<EVAL: RegFile.eval_instr rf1 instr_src e_src rf2>> /\\\n      <<ORD: ProgramEvent.ord e_src e_tgt>>.\n  Proof.\n    inv ORD; inv EVAL; esplits; try by repeat (econs; eauto).\n  Qed.\nEnd RegFile.\n\nModule State.\n  Structure t := mk {\n    regs: RegFile.t;\n    stmts: list Stmt.t;\n  }.\n\n  Definition init (text:list Stmt.t): t :=\n    mk RegFile.init text.\n\n  Definition is_terminal (s:t): Prop :=\n    stmts s = nil.\n\n  Inductive step: forall (e:ProgramEvent.t) (s1:t) (s1:t), Prop :=\n  | step_instr\n      rf1 i e rf2 stmts\n      (INSTR: RegFile.eval_instr rf1 i e rf2):\n      step e\n           (mk rf1 ((Stmt.instr i)::stmts))\n           (mk rf2 stmts)\n  | step_ite\n      rf cond s1 s2 stmts:\n      step ProgramEvent.silent\n           (mk rf ((Stmt.ite cond s1 s2)::stmts))\n           (mk rf ((if RegFile.eval_expr rf cond\n                    then s1\n                    else s2) ++ stmts))\n  | step_dowhile\n      rf s cond stmts:\n      step ProgramEvent.silent\n           (mk rf ((Stmt.dowhile s cond)::stmts))\n           (mk rf (s ++ (Stmt.ite cond ((Stmt.dowhile s cond)::nil) nil) :: stmts))\n  .\nEnd State.\n\nProgram Definition lang :=\n  Language.mk\n    State.init\n    State.is_terminal\n    State.step.\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/while/Semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.2589876956918275}}
{"text": "From iris.program_logic Require Export language ectx_language ectxi_language.\nFrom Autosubst Require Export Autosubst.\n\nModule stlc.\n  Inductive expr :=\n    | Rec (e : {bind 2 of expr})\n    | Var (x : var)\n    | Lam (e : {bind 1 of expr})\n    | App (e1 e2 : expr)\n    (* Unit *)\n    | Unit\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 : {bind expr}) (e2 : {bind expr})\n    (* Recursive Types *)\n    | Fold (e : expr)\n    | Unfold (e : expr).\n\n  Instance Ids_expr : Ids expr. derive. Defined.\n  Instance Rename_expr : Rename expr. derive. Defined.\n  Instance Subst_expr : Subst expr. derive. Defined.\n  Instance SubstLemmas_expr : SubstLemmas expr. derive. Qed.\n\n  Inductive val :=\n    | RecV (e : {bind 1 of expr})\n    | LamV (e : {bind 1 of expr})\n    | UnitV\n    | PairV (v1 v2 : val)\n    | InjLV (v : val)\n    | InjRV (v : val)\n    | FoldV (v : val).\n\n  Fixpoint of_val (v : val) : expr :=\n    match v with\n    | RecV e => Rec e\n    | FoldV v => Fold (of_val v)\n    | LamV e => Lam e\n    | UnitV => Unit\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    end.\n  Notation \"# v\" := (of_val v) (at level 20).\n\n  Fixpoint to_val (e : expr) : option val :=\n    match e with\n    | Lam e => Some (LamV e)\n    | Unit => Some UnitV\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    | Rec e => Some (RecV e)\n    | Fold e => v ← to_val e; Some (FoldV v)\n    | _ => None\n    end.\n\n  (** Evaluation contexts *)\n  Inductive ectx_item :=\n  | AppLCtx (e2 : expr)\n  | AppRCtx (v1 : val)\n  | PairLCtx (e2 : expr)\n  | PairRCtx (v1 : val)\n  | FstCtx\n  | SndCtx\n  | InjLCtx\n  | InjRCtx\n  | CaseCtx (e1 : {bind expr}) (e2 : {bind expr})\n  | FoldCtx\n  | UnfoldCtx.\n\n  Definition 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    | 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    | FoldCtx => Fold e\n    | UnfoldCtx => Unfold e\n    end.\n\n  Definition state : Type := ().\n\n  Inductive head_step : expr → state → list Empty_set → expr → state → list expr → Prop :=\n  | BetaS e1 e2 v2 σ :\n        to_val e2 = Some v2 →\n        head_step (App (Rec e1) e2) σ [] e1.[(Rec e1), e2/] σ []\n  | LamBetaS e1 e2 v2 σ :\n      to_val e2 = Some v2 →\n      head_step (App (Lam e1) e2) σ [] e1.[e2/] σ []\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 σ []\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 σ []\n  (* Recursive Types *)\n  | Unfold_Fold e v σ :\n      to_val e = Some v →\n      head_step (Unfold (Fold e)) σ [] e σ []\n  | CaseLS e0 v0 e1 e2 σ :\n      to_val e0 = Some v0 →\n      head_step (Case (InjL e0) e1 e2) σ [] e1.[e0/] σ []\n  | CaseRS e0 v0 e1 e2 σ :\n      to_val e0 = Some v0 →\n      head_step (Case (InjR e0) e1 e2) σ [] e2.[e0/] σ [].\n\n  (** Basic properties about the language *)\n  Lemma to_of_val v : to_val (of_val v) = Some v.\n  Proof. by induction v; simplify_option_eq. Qed.\n\n  Lemma of_to_val e v : to_val e = Some v → of_val v = e.\n  Proof.\n    revert v; induction e; intros; simplify_option_eq; auto with f_equal.\n  Qed.\n\n  Instance of_val_inj : Inj (=) (=) of_val.\n  Proof. by intros ?? Hv; apply (inj Some); rewrite -!to_of_val Hv. Qed.\n\n  Lemma fill_item_val Ki e :\n    is_Some (to_val (fill_item Ki e)) → is_Some (to_val e).\n  Proof. intros [v ?]. destruct Ki; simplify_option_eq; eauto. Qed.\n\n  Instance fill_item_inj Ki : Inj (=) (=) (fill_item Ki).\n  Proof. destruct Ki; intros ???; simplify_eq; auto with f_equal. Qed.\n\n  Lemma val_stuck e1 σ1 κ e2 σ2 ef :\n    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    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 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.\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.\n  Qed.\n\n  Lemma val_head_stuck e1 σ1 κ e2 σ2 efs : 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 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.\nEnd stlc.\n\n\n(** Language *)\nCanonical Structure stlc_ectxi_lang := EctxiLanguage stlc.lang_mixin.\nCanonical Structure stlc_ectx_lang := EctxLanguageOfEctxi stlc_ectxi_lang.\nCanonical Structure stlc_lang := LanguageOfEctx stlc_ectx_lang.\n\nExport stlc.\n\nHint Extern 20 (PureExec _ _ _) => progress simpl : typeclass_instances.\n\nHint Extern 5 (IntoVal _ _) => eapply of_to_val; fast_done : typeclass_instances.\nHint Extern 10 (IntoVal _ _) =>\n  rewrite /IntoVal; eapply of_to_val; rewrite /= !to_of_val /=; solve [ eauto ] : typeclass_instances.\n\nHint Extern 5 (AsVal _) => eexists; eapply of_to_val; fast_done : typeclass_instances.\nHint Extern 10 (AsVal _) =>\n  eexists; rewrite /IntoVal; eapply of_to_val; rewrite /= !to_of_val /=; solve [ eauto ] : typeclass_instances.\nLocal Hint Resolve language.val_irreducible : core.\nLocal Hint Resolve to_of_val : core.\nLocal Hint Unfold language.irreducible : core.\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/lang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030761371502, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.25898768922845783}}
{"text": "Require Import DataTypes Channel Cache Coq.Logic.Classical Hier Coq.Relations.Relation_Operators Coq.Relations.Operators_Properties MsiState.\n\nModule Type CompatBehavior (dt: DataTypes) (ch: ChannelPerAddr dt).\n  Import dt ch.\n  Section Node.\n    Context {n: Cache}.\n    Context {a: Addr}.\n    Context {t: Time}.\n    Axiom sendPCond: forall {p}, defined n -> defined p -> parent n p ->\n                                 forall {m},\n                                   mark mch n p a t m ->\n                                   forall {c}, defined c -> parent c n ->\n                                               sle (dir n c a t) (to m).\n    Axiom sendCCond: forall {c}, defined n -> defined c ->\n                       parent c n ->\n                       forall {m},\n                         mark mch n c a t m ->\n                         sle (to m) (state n a t) /\\\n                         forall {c'}, defined c' -> \n                                      c' <> c -> parent c' n -> sle (dir n c' a t)\n                                      match to m with\n                                        | Mo => In\n                                        | Sh => Sh\n                                        | In => Mo\n                                      end.\n    Axiom oneRespC: forall {c1 c2}, defined n -> defined c1 -> defined c2 ->\n                      parent c1 n -> parent c2 n ->\n                      forall {m1}, (mark mch n c1 a t m1 \\/ recv mch c1 n a t m1) ->\n                                   forall {m2},\n                                     (mark mch n c2 a t m2 \\/ recv mch c2 n a t m2) -> c1 = c2.\n    Axiom respPNoRespC: forall {p}, defined n -> defined p -> parent n p ->\n                                    forall {m},\n                                      (mark mch n p a t m \\/ recv mch p n a t m) ->\n                                      forall {c}, defined c -> parent c n -> forall mc,\n                                        ~ (mark mch n c a t mc \\/ recv mch c n a t mc).\n  End Node.\n  Axiom initCompat:\n    forall {n c}, defined n -> defined c -> parent c n -> forall a, dir n c a 0 = In.\nEnd CompatBehavior.\n\nModule Type CompatTheorem (dt: DataTypes) (ch: ChannelPerAddr dt).\n  Import dt ch.\n  Parameter compatible:\n    forall {n}, defined n -> forall a t {c}, defined c -> parent c n ->\n                        sle (dir n c a t) (state n a t) /\\\n                        forall {c'}, defined c' -> c' <> c -> parent c' n -> sle (dir n c' a t)\n                                                                   match dir n c a t with\n                                                                     | Mo => In\n                                                                     | Sh => Sh\n                                                                     | In => Mo\n                                                                   end.\n  Parameter compat:\n    forall {n}, defined n -> forall a t {c}, defined c -> parent c n ->\n                        sle (state c a t) (state n a t) /\\\n                        forall {c'}, defined c' -> c' <> c -> parent c' n -> sle (state c' a t)\n                                                                   match state c a t with\n                                                                     | Mo => In\n                                                                     | Sh => Sh\n                                                                     | In => Mo\n                                                                   end.\n  Parameter descSle: forall {c p}, defined c ->\n                                   defined p -> descendent c p ->\n                                   forall {a t},\n                                     sle (state c a t) (state p a t).\n\n  Parameter nonDescCompat: forall {c1 c2},\n                           defined c1 -> defined c2 ->\n                           ~ descendent c1 c2 -> ~ descendent c2 c1 ->\n                           forall {a t},\n                             sle (state c2 a t)\n                                 match state c1 a t with\n                                   | Mo => In\n                                   | Sh => Sh\n                                   | In => Mo\n                                 end.\n\n  Parameter allDirLower: forall {p}, defined p ->\n                                     forall {co a t s},\n                                       (forall c, defined c -> parent c p\n                                                  -> sle (dir p c a t) s) ->\n                                       co <> p -> descendent co p -> sle (state co a t) s.\nEnd CompatTheorem.\n\nModule mkCompat (dt: DataTypes) (ch: ChannelPerAddr dt) (cb: CompatBehavior dt ch) (ba: BehaviorAxioms dt ch)\n                : CompatTheorem dt ch.\n  Module mbt := mkBehaviorTheorems dt ch ba.\n  Module hr := mkHierProperties dt.\n  Import dt ch cb ba mbt hr.\n\n  Theorem compatible:\n    forall {n}, defined n -> forall a t {c}, defined c -> parent c n ->\n                        sle (dir n c a t) (state n a t) /\\\n                        forall {c'}, defined c' -> c' <> c -> parent c' n -> sle (dir n c' a t)\n                                                                   match dir n c a t with\n                                                                     | Mo => In\n                                                                     | Sh => Sh\n                                                                     | In => Mo\n                                                                   end.\n  Proof.\n    intros n nDef a t.\n    induction t.\n    intros c cDef cond.\n    constructor.\n    pose proof @initCompat n c nDef cDef cond a as c2.\n    rewrite c2.\n    unfold sle; destruct (state n a 0); auto.\n    intros c' c'Def c'_ne_c c'Child.\n    pose proof @initCompat n c' nDef c'Def c'Child a as c2.\n    rewrite c2; destruct (dir n c a 0); unfold sle; auto.\n    destruct (classic (exists p m, defined p /\\\n                           parent n p /\\\n                           (mark mch n p a t m \\/ recv mch p n a t m))) as [respP|noRespP].\n    destruct respP as [p [m [pDef [p_parent markOrRecv]]]].\n    pose proof @respPNoRespC n a t p nDef pDef p_parent m markOrRecv as noChild.\n    assert (sameDir: forall c, defined c -> parent c n -> dir n c a t = dir n c a (S t)).\n    intros c cDef c_child.\n    pose proof respPNoRespC nDef pDef p_parent markOrRecv cDef c_child as noRespC.\n    assert (st_eq: dir n c a t = dir n c a (S t)).\n    assert (stuff: {dir n c a t = dir n c a (S t)} + {dir n c a t <> dir n c a (S t)})\n      by decide equality.\n    destruct stuff as [eq|neq].\n    assumption.\n    assert (neq': dir n c a (S t) <> dir n c a t) by auto.\n    pose proof (change (@dt n c nDef cDef c_child) neq') as resp.\n    generalize noRespC resp; clear; firstorder.\n    assumption.\n    intros c cDef c_child.\n    pose proof (sameDir c cDef c_child) as dir_eq.\n    rewrite <- dir_eq in *.\n    assert (sameC': forall c', defined c' -> c' <> c -> parent c' n -> dir n c' a t = dir n c' a (S t))\n           by (generalize sameDir; clear; firstorder).\n    destruct markOrRecv as [markm | recvm].\n    pose proof (sendPCond nDef pDef p_parent markm cDef c_child) as dir_le_to_m.\n    pose proof (sendmChange (@st p n pDef nDef p_parent) markm) as sth.\n    constructor.\n\n    rewrite <- sth in dir_le_to_m.\n    assumption.\n\n    intros c' c'Def. intros.\n    specialize (sameC' c' c'Def H H0).\n    rewrite <- sameC'.\n    generalize IHt c cDef c_child c'Def H H0; clear; firstorder.\n    constructor.\n    pose proof (cRecvUpgrade pDef nDef p_parent recvm) as st_lt.\n    generalize (IHt c cDef c_child) st_lt; clear; intros.\n    destruct H as [stuff _].\n    unfold sle in *; unfold sle in *; destruct (dir n c a t); destruct (state n a t);\n    destruct (state n a (S t)); auto.\n    intros c' c'Def c'Ne c'_child.\n    specialize (sameDir c' c'Def c'_child).\n    rewrite <- sameDir.\n    generalize IHt c'_child c'Def c'Ne cDef c_child; clear; firstorder.\n    assert (noRespP': forall p, defined p -> parent n p -> ~ ((exists m, mark mch n p a t m)\n                                                   \\/ (exists m, recv mch p n a t m)))\n      by (\n          generalize noRespP; clear; firstorder).\n    assert (st_eq: state n a (S t) = state n a t).\n    destruct (classic (exists p, defined p /\\ parent n p)) as [[p [pDef p_parent]] | nop].\n    specialize (noRespP' p pDef p_parent).\n    assert (eqOrNot: {state n a (S t) = state n a t} + {state n a (S t) <> state n a t}) by\n        decide equality.\n    destruct eqOrNot as [eq|not].\n    assumption.\n    pose proof (noRespP' (change (@st p n pDef nDef p_parent) not)) as done.\n    firstorder.\n    assert (noP: forall p, defined p -> ~ parent n p) by firstorder.\n    apply (@noParentSame n a t nDef noP).\n    rewrite st_eq in *.\n\n    destruct (classic (exists c m, defined c /\\ parent c n /\\ (mark mch n c a t m \\/ recv mch c n a t m))) as [ex|notEx].\n    destruct ex as [c [m [cDef [c_child resp]]]].\n    assert (noneElse: forall c', defined c' -> c' <> c -> parent c' n ->\n                       ~ ((exists m, mark mch n c' a t m) \\/ exists m, recv mch c' n a t m)).\n    intros c' c'Def c'_ne_c c'_child.\n    destruct (classic (exists m', mark mch n c' a t m' \\/ recv mch c' n a t m'))\n      as [ex|notEx].\n    destruct ex as [m' sth].\n    pose proof (oneRespC nDef cDef c'Def c_child c'_child resp sth) as sth2.\n    assert (c' = c) by auto.\n    firstorder.\n    firstorder.\n    assert (stEq: forall c', defined c' -> c' <> c -> parent c' n -> dir n c' a (S t) = dir n c' a t).\n    intros c' c'Def c'_ne_c c'_child.\n    specialize (noneElse c' c'Def c'_ne_c c'_child).\n    assert (eqOrNot: {dir n c' a (S t) = dir n c' a t} \n                     + {dir n c' a (S t) <> dir n c' a t}) by decide equality.\n    destruct eqOrNot as [eq|not].\n    assumption.\n    specialize (noneElse (change (@dt n c' nDef c'Def c'_child) not)).\n    firstorder.\n    intros c0 c0Def c0_child.\n    destruct (classic (c0 = c)) as [c0_eq_c|c0_ne_c].\n    rewrite c0_eq_c in *.\n    destruct resp as [markm | recvm].\n    pose proof (sendmChange (@dt n c nDef cDef c_child) markm) as toM.\n    rewrite toM.\n    pose proof (sendCCond nDef cDef c_child markm) as [stuff rest].\n    constructor.\n    intuition.\n    intros c' c'Def. intros.\n    specialize (stEq c' c'Def H H0).\n    rewrite stEq.\n    specialize (rest c' c'Def H H0).\n    intuition.\n    pose proof (pRecvDowngrade nDef cDef c_child recvm) as sth_gt.\n    constructor.\n    destruct (IHt c cDef c_child) as [good bad].\n    unfold slt in *; unfold sle in *; destruct (dir n c a (S t)); destruct (dir n c a t);\n    destruct (state n a t); auto.\n    clear c0 c0_child c0_eq_c.\n    intros c' c'Def c'_ne_c c'_child.\n    specialize (stEq c' c'Def c'_ne_c c'_child).\n    rewrite stEq in *; clear stEq.\n    destruct (IHt c cDef c_child) as [_ rest]; clear IHt.\n    specialize (rest c' c'Def c'_ne_c c'_child).\n    unfold slt in *; unfold sle in *; destruct (dir n c a (S t)); destruct (dir n c a t);\n    destruct (dir n c' a t); auto.\n\n    pose proof (stEq c0 c0Def c0_ne_c c0_child) as stEq'.\n    rewrite stEq'.\n    constructor.\n    generalize IHt c0Def c0_child; clear; firstorder.\n    intros c' c'Def c'_ne_c0 c'_child.\n    destruct (classic (c' = c)) as [c'_eq_c | c'_ne_c].\n    rewrite c'_eq_c in *.\n    destruct resp as [markm | recvm].\n    pose proof (sendCCond nDef cDef c_child markm) as [_ toMOld].\n    assert (c_ne_c0: c0 <> c) by auto.\n    specialize (toMOld c0 c0Def c_ne_c0 c0_child).\n    rewrite <- c'_eq_c in *; clear c'_eq_c.\n    pose proof (sendmChange (dt nDef c'Def c'_child) markm) as sth.\n    rewrite sth.\n    destruct (dir n c0 a t); destruct (to m); unfold sle in *; auto.\n\n    pose proof (pRecvDowngrade nDef cDef c_child recvm) as sth_gt.\n    assert (gtz: slt In (dir n c a t)) by\n        (destruct (dir n c a (S t)); destruct (dir n c a t); unfold slt in *; auto).\n    pose proof (IHt c0 c0Def c0_child) as [_ sth1].\n    specialize (sth1 c c'Def c'_ne_c0 c_child).\n    unfold slt in *; unfold sle in *; destruct (dir n c a (S t));\n    destruct (dir n c0 a t); destruct (dir n c a t); auto.\n\n    specialize (stEq c' c'Def c'_ne_c c'_child).\n    rewrite stEq.\n    generalize IHt c0_child c'Def c0Def c'_ne_c0 c'_child; clear; firstorder.\n\n    assert (same: forall c, defined c -> parent c n -> dir n c a (S t) = dir n c a t).\n    intros c cDef c_child.\n    assert (eqOrNot: {dir n c a (S t) = dir n c a t} + {dir n c a (S t) <> dir n c a t})\n           by decide equality.\n    destruct eqOrNot as [eq|not].\n    assumption.\n    pose proof (change (@dt n c nDef cDef c_child) not) as ppp.\n    generalize notEx nDef cDef c_child ppp; clear; firstorder.\n\n    intros c cDef c_child.\n    constructor.\n    specialize (same c cDef c_child).\n    rewrite same.\n    generalize IHt cDef c_child; clear; firstorder.\n\n    intros c' c'Def. intros.\n    pose proof (same c' c'Def H0) as dunk.\n    rewrite dunk.\n    pose proof (same c cDef c_child) as dukn.\n    rewrite dukn in *.\n    generalize IHt cDef c'Def c_child H H0; clear; firstorder.\n  Qed.\n\n  Theorem compat:\n    forall {n}, defined n -> forall a t {c}, defined c -> parent c n ->\n                        sle (state c a t) (state n a t) /\\\n                        forall {c'}, defined c' -> c' <> c -> parent c' n -> sle (state c' a t)\n                                                                   match state c a t with\n                                                                     | Mo => In\n                                                                     | Sh => Sh\n                                                                     | In => Mo\n                                                                   end.\n  Proof.\n    intros n nDef a t c cDef c_child.\n    pose proof (compatible nDef a t cDef c_child) as base.\n    constructor.\n    destruct base as [dr _].\n    pose proof (conservative nDef cDef c_child a t) as dLe.\n    apply (sle_sle_sle dLe dr).\n    destruct base as [_ others].\n    intros c' c'Def c'_ne p_c'.\n    specialize (others c' c'Def c'_ne p_c').\n    pose proof (conservative nDef cDef c_child a t) as st.\n    pose proof (conservative nDef c'Def p_c' a t) as st'.\n    unfold sle in *; destruct (state c' a t); destruct (state c a t);\n    destruct (dir n c' a t); destruct (dir n c a t); auto.\n  Qed.\n\n  Theorem descSle: forall {c p}, defined c -> defined p -> descendent c p -> forall {a t},\n                                                                               sle (state c a t) (state p a t).\n  Proof.\n    intros c p defC defP c_p a t.\n    induction c_p.\n    pose proof (compat defP a t defC H) as [use _].\n    assumption.\n    assert (eq: state x a t = state x a t) by reflexivity.\n    apply (sle_eq eq).\n    pose proof (rt_trans Tree parent y z hier c_p2 defP) as defY.\n    specialize (IHc_p1 defC defY).\n    specialize (IHc_p2 defY defP).\n    apply (sle_sle_sle IHc_p1 IHc_p2).\n  Qed.\n\n  Theorem nonDescCompat: forall {c1 c2},\n                           defined c1 -> defined c2 ->\n                           ~ descendent c1 c2 -> ~ descendent c2 c1 ->\n                           forall {a t},\n                             sle (state c2 a t)\n                                 match state c1 a t with\n                                   | Mo => In\n                                   | Sh => Sh\n                                   | In => Mo\n                                 end.\n  Proof.\n    intros c1 c2 defC1 defC2 c1_no_c2 c2_no_c1.\n    pose proof (hasFork defC1 defC2 c1_no_c2 c2_no_c1) as forkFull.\n    destruct forkFull as [fork [defF [[d1 [defD1 [d1_fork [c1_d1 c2_no_d1]]]] [d2 [defD2 [d2_fork [c1_no_d2 c2_d1]]]]] ]].\n    intros a t.\n    assert (le1: sle (state c1 a t) (state d1 a t)) by (apply descSle; firstorder).\n    assert (le2: sle (state c2 a t) (state d2 a t)) by (apply descSle; firstorder).\n    assert (d1_ne_d2: d2 = d1 -> False) by (\n             intros d1_eq_d2; rewrite d1_eq_d2 in *; firstorder).\n    pose proof (compat defF a t defD1 d1_fork) as [_ useful].\n    specialize (useful d2 defD2 d1_ne_d2 d2_fork).\n    unfold sle in *; destruct (state c1 a t); destruct (state c2 a t);\n    destruct (state d1 a t); destruct (state d2 a t); auto.\n  Qed.\n\n  Theorem allDirLower: forall {p},\n                         defined p ->\n                         forall {co a t s},\n                           (forall c, defined c -> parent c p -> sle (dir p c a t) s) ->\n                           co <> p -> descendent co p -> sle (state co a t) s.\n  Proof.\n    intros p defP co a t s noDir co_ne_p co_p.\n    pose proof (clos_rt_rtn1 Tree parent co p co_p) as trans.\n    destruct trans.\n    assert (co = co) by reflexivity; firstorder.\n    pose proof (clos_rtn1_rt Tree parent co y trans) as co_y.\n    clear trans; fold descendent in *.\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 y_hier.\n    specialize (noDir y y_hier H).\n    pose proof (rt_trans Tree parent co y hier co_y y_hier) as co_hier.\n    pose proof (@descSle co y co_hier y_hier co_y a t) as useful.\n    pose proof (conservative defP y_hier H a t) as final.\n    pose proof (sle_sle_sle useful final) as f2.\n    apply (sle_sle_sle f2 noDir).\n  Qed.\nEnd mkCompat.\n", "meta": {"author": "vmurali", "repo": "CacheProofBetter", "sha": "e00bb4a4f1677c69969797c25ab9ef4bb8a213a0", "save_path": "github-repos/coq/vmurali-CacheProofBetter", "path": "github-repos/coq/vmurali-CacheProofBetter/CacheProofBetter-e00bb4a4f1677c69969797c25ab9ef4bb8a213a0/Compatible.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.2589162091100594}}
{"text": "Require Import Coq.ZArith.ZArith. Local Open Scope Z_scope.\nRequire Import Coq.Lists.List. Import ListNotations.\nRequire Import coqutil.Word.Bitwidth32.\nRequire Import coqutil.Map.Interface coqutil.Map.OfFunc.\nRequire Import coqutil.Tactics.Tactics.\nRequire Import riscv.Utility.runsToNonDet.\nRequire riscv.Utility.InstructionNotations.\nRequire bedrock2.Hexdump.\nRequire riscv.Spec.PseudoInstructions.\nRequire Import compiler.SeparationLogic.\nRequire Import bedrock2.ZnWords.\nRequire Import riscv.Utility.Encode.\nRequire Import riscv.Platform.MaterializeRiscvProgram.\nRequire Import compiler.regs_initialized.\nRequire Import bedrock2.BasicC32Semantics.\nRequire Import riscv.Platform.MinimalCSRs.\nRequire Import coqutil.Map.Z_keyed_SortedListMap.\nRequire Import compilerExamples.SoftmulBedrock2.\nRequire Import compilerExamples.SoftmulCompile.\nRequire Import compilerExamples.Softmul.\nRequire Import compiler.LowerPipeline.\nRequire Import bedrock2.ArrayCasts.\nRequire Import bedrock2.SepAutoArray bedrock2.SepAutoExports.\nRequire Import bedrock2.SepBulletPoints.\nLocal Open Scope sep_bullets_scope. Undelimit Scope sep_scope.\nRequire Import bedrock2.bottom_up_simpl_ltac1.\n\nDefinition softmul_binary: list byte := Pipeline.instrencode handler_insts.\n\nModule PrintAssembly.\n  Import riscv.Utility.InstructionNotations.\n  Goal True. let r := eval cbv in handler_insts in idtac (* r *). Abort.\nEnd PrintAssembly.\n\nModule PrintBytes.\n  Import bedrock2.Hexdump.\n  Local Open Scope hexdump_scope.\n  Set Printing Width 100.\n  Goal True. let r := eval cbv in softmul_binary in idtac (* r *). Abort.\nEnd PrintBytes.\n\nNotation Registers := (Zkeyed_map BasicC32Semantics.word).\nNotation Mem := BasicC32Semantics.mem.\nNotation MachineState := (@State 32 BasicC32Semantics.word Mem Registers).\nNotation word := BasicC32Semantics.word.\n\nDefinition R(r1 r2: MachineState): Prop :=\n  r1.(regs) = r2.(regs) /\\\n  r1.(pc) = r2.(pc) /\\\n  r1.(nextPc) = r2.(nextPc) /\\\n  r1.(csrs) = map.empty /\\\n  basic_CSRFields_supported r2 /\\\n  regs_initialized r2.(regs) /\\\n  exists mtvec_base scratch_end,\n    map.get r2.(csrs) CSRField.MTVecBase = Some mtvec_base /\\\n    map.get r2.(csrs) CSRField.MScratch = Some scratch_end /\\\n    <{ * eq r1.(mem)\n       * mem_available (word.of_Z (scratch_end - 256)) (word.of_Z scratch_end)\n       * ptsto_bytes (word.of_Z (mtvec_base * 4)) softmul_binary }> r2.(mem).\n\nLemma bytearray_to_instr_array: forall insts addr,\n    Forall (fun i => verify i Decode.RV32I) insts ->\n    iff1 (array ptsto (word.of_Z 1) addr (Pipeline.instrencode insts))\n         (array (instr idecode) (word.of_Z 4) addr insts).\nProof.\n  intros. revert addr. induction H; intros.\n  - cbn. reflexivity.\n  - rewrite array_cons.\n    unfold Pipeline.instrencode in *. cbn [flat_map]. rewrite array_app.\n    rewrite IHForall. clear IHForall.\n    rewrite LittleEndian.to_list_split.\n    rewrite LittleEndianList.length_le_split.\n    bottom_up_simpl_in_goal.\n    cancel.\n    cbn [seps].\n    unfold instr, idecode, truncated_scalar, littleendian, ptsto_bytes.ptsto_bytes.\n    setoid_rewrite HList.tuple.to_list_of_list.\n    unfold iff1, ex1. intro m. split; intro A.\n    + exists (encode x).\n      extract_ex1_and_emp_in_goal. split; [|split].\n      * exact A.\n      * eapply DecodeEncode.decode_encode. assumption.\n      * apply EncodeBound.encode_range.\n    + fwd. extract_ex1_and_emp_in A. fwd.\n      rewrite EncodeDecode.encode_decode; auto.\nQed.\n\nLemma verify_handler_insts : Forall (fun i => verify i Decode.RV32I) handler_insts.\nProof.\n  repeat (eapply Forall_cons || eapply Forall_nil).\n  all : cbv; ssplit; trivial; try congruence.\nQed.\n\nLemma byte_list_to_word_list_roundtrip: forall bs,\n    Z.of_nat (List.length bs) mod 4 = 0 ->\n    ws2bs 4 (bs2ws (word := word) 4 bs) = bs.\nProof.\n  intros. refine (bs2ws2bs _ _).\n  change (Memory.bytes_per Syntax.access_size.word) with 4%nat.\n  change 4 with (Z.of_nat 4) in H.\n  rewrite <- Nat2Z.inj_mod in H.\n  Lia.lia.\nQed.\n\nLemma word_array_to_byte_array: forall addr (bs: list byte) (ws: list word),\n    ws2bs 4 ws = bs ->\n    iff1 (array scalar (word.of_Z 4) addr ws) (array ptsto (word.of_Z 1) addr bs).\nProof.\n  intros. subst bs. refine (bytes_of_words _ _).\nQed.\n\nLemma split_sepclause_convert: forall (all part part': Mem -> Prop) frame (C: Prop),\n    iff1 part' part ->\n    split_sepclause all part' frame C ->\n    split_sepclause all part frame C.\nProof.\n  unfold split_sepclause. intros. rewrite <- H. assumption.\nQed.\n\nLemma bytelist_length_eq: forall bs n,\n    Datatypes.length bs = (n * 4)%nat ->\n    (Datatypes.length bs = (n * 4)%nat) =\n    (Datatypes.length (bs2ws (word := word) 4 bs) = n).\nProof.\n  intros. apply PropExtensionality.propositional_extensionality.\n  split; intro A. 2: assumption.\n  rewrite bs2ws_length' by Lia.lia.\n  rewrite A.\n  apply List.Nat.div_up_exact.\n  Lia.lia.\nQed.\n\nLemma R_equiv_related: forall r1 r2,\n    R r1 r2 <-> related r1 r2.\nProof.\n  unfold R, related, mem_available. split; intros; fwd; intuition try congruence.\n  - extract_ex1_and_emp_in_hyps.\n    unfold ptsto_bytes, softmul_binary in *.\n    do 3 eexists.\n    split; [eassumption|].\n    split; [eassumption|].\n    apply and_comm.\n    flatten_seps_in_goal.\n    extract_ex1_and_emp_in_goal.\n    rename Hp6p2 into M.\n    rewrite (iff1ToEq (bytearray_to_instr_array _ (word.of_Z (mtvec_base * 4))\n                         verify_handler_insts)) in M.\n    scancel_asm.\n    split_ith_left_and_cancel_with_fst_right 0%nat.\n    1: eapply split_sepclause_convert.\n    1: symmetry.\n    1: eapply word_array_to_byte_array.\n    1: eapply byte_list_to_word_list_roundtrip.\n    all: cycle 1.\n    1: lazymatch goal with\n       | |- context [List.length (bs2ws 4 ?B) = 32%nat] =>\n           replace (List.length (bs2ws 4 B) = 32%nat) with\n           (List.length B = 128%nat)\n       end.\n    2: eapply bytelist_length_eq with (n := 32%nat).\n    1: unshelve (eauto with split_sepclause_goal).\n    1: rename H into Sp.\n    1: split.\n    1: eapply Sp.\n    1: solve [solve_split_sepclause_sidecond_or_pose_err].\n    1: clear Sp. (* because there's no \"after the call\" where we want to merge *)\n    1: bottom_up_simpl_in_goal.\n    1: rewrite (@List.skipn_all2 _ 256%nat) by listZnWords.\n    1: impl_ecancel_step_without_splitting.\n    1: impl_ecancel_step_without_splitting.\n    1: unfold array.\n    1: ssplit.\n    1: reflexivity.\n    1: listZnWords.\n    1: listZnWords.\n    1: listZnWords.\n    1: listZnWords.\n  - extract_ex1_and_emp_in_hyps.\n    unfold ptsto_bytes, softmul_binary in *.\n    do 2 eexists.\n    split; [eassumption|].\n    split; [eassumption|].\n    flatten_seps_in_goal.\n    extract_ex1_and_emp_in_goal.\n    rewrite (iff1ToEq (bytearray_to_instr_array _ (word.of_Z (mtvec_base * 4))\n                         verify_handler_insts)).\n    (* somewhat unusual: hyp is split, goal is more merged *)\n    rename Hp6p3 into M.\n    seprewrite_in (word_array_to_byte_array (word.of_Z (stack_hi - 128))) M.\n    1: reflexivity.\n    rewrite (array_app\n               anybytes\n               (ws2bs 4 stacktrash)\n               (word.of_Z (stack_hi - 256))).\n    flatten_seps_in_goal. cbn [seps].\n    rewrite Hp6p3_emp0.\n    bottom_up_simpl_in_goal. bottom_up_simpl_in_hyps.\n    (* TODO why doesn't word_simpl canonicalize this? *)\n    replace (word.add (word.of_Z (stack_hi - 256)) (word.of_Z 128))\n      with (word.of_Z (word := word) (stack_hi - 128)) by ring.\n    scancel_asm.\n    pose proof (ws2bs_length 4 stacktrash).\n    listZnWords.\nQed.\n\nLemma softmul_correct: forall initialH initialL post,\n    runsTo (mcomp_sat (run1 mdecode)) initialH post ->\n    R initialH initialL ->\n    runsTo (mcomp_sat (run1 idecode)) initialL (fun finalL =>\n               exists finalH, R finalH finalL /\\ post finalH).\nProof.\n  intros.\n  eapply R_equiv_related in H0.\n  eapply runsTo_weaken.\n  1: eapply Softmul.softmul_correct. 1,2: eassumption.\n  cbv beta. intros.\n  fwd. eapply R_equiv_related in H1p0. eauto.\nQed.\n\n(*\nPrint Assumptions softmul_correct.\nOnly two standard axioms:\nPropExtensionality.propositional_extensionality : forall P Q : Prop, P <-> Q -> P = Q\nFunctionalExtensionality.functional_extensionality_dep\n  : forall (A : Type) (B : A -> Type) (f g : forall x : A, B x),\n    (forall x : A, f x = g x) -> f = g\n*)\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/compilerExamples/SoftmulTop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.25891620415894984}}
{"text": "From LF Require Export Tactics.\n\n\nTheorem combine_split' : forall X Y (l : list (X * Y)) l1 l2,\n  split l = (l1, l2) ->\n  combine l1 l2 = l.\nProof.\n  intros X Y l. induction l as [ | [x y] l'].\n  - intros l1 l2 H. simpl in H. injection H as H1 H2.\n  rewrite <- H1. rewrite <- H2. reflexivity.\n  - intros l1 l2 H. simpl in H. destruct (split) as [ t1 t2 ].\n  inversion H. simpl. rewrite IHl'.\n    + reflexivity.\n    + reflexivity.\nQed.\n\nTheorem split_combine' : forall X Y (l1 : list X) (l2 : list Y) (l : list (X*Y)),\n  length l1 = length l2 -> combine l1 l2 = l -> split l = (l1, l2).\nProof.\n  intros X Y l1 l2 l. generalize dependent l1. generalize dependent l2.\n  induction l as [| h t IHl].\n  - intros l1 l2 H1 H2. destruct l1 as [| h1 t1].\n    + simpl in H1. destruct l2.\n      * simpl. reflexivity.\n      * rewrite <- H2. inversion H1.\n    + simpl. destruct l2 as [| h2 t2].\n      * inversion H1.\n      * inversion H1. inversion H2.\n  - intros l1 l2 H1 H2. destruct l1 as [| h1 t1].\n    + destruct l2.\n      * inversion H2.\n      * inversion H2.\n    + destruct l2. \n      * inversion H2.\n      * simpl. inversion H1. simpl. inversion H2. rewrite H4. destruct split as [g j]. inversion H2.\ninversion H2. rewrite H0. rewrite H3. apply IHl in H1. \nrewrite <- H1. rewrite <- H3. rewrite <- H3 in H2. simpl in H2. discriminate H1. rewrite <- H2. rewrite <- H3. rewrite H3. \nrewrite H2. simpl in H2. rewrite H3 in H2. rewrite <- H2. \n\nrewrite H3. rewrite H3 in H2. rewrite H2. destruct split as [a b].  inversion H0. rewrite H.  \n    Abort.", "meta": {"author": "gustavobonassa", "repo": "Coq", "sha": "e2657c97272e56ff2b5bcd4a53b78eeb93fc7e82", "save_path": "github-repos/coq/gustavobonassa-Coq", "path": "github-repos/coq/gustavobonassa-Coq/Coq-e2657c97272e56ff2b5bcd4a53b78eeb93fc7e82/ListaExer3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2589071919837202}}
{"text": "Require Import floyd.base.\nRequire Import floyd.assert_lemmas.\nRequire Import floyd.client_lemmas.\nRequire Import floyd.type_induction.\n(*Require Import floyd.fieldlist.*)\nRequire Import floyd.compact_prod_sum.\n(*Require Import floyd.aggregate_type.*)\nRequire Import floyd.mapsto_memory_block.\nRequire Import floyd.nested_pred_lemmas.\nRequire Import floyd.jmeq_lemmas.\nRequire Import floyd.sublist.\n\nRequire Export floyd.fieldlist.\nRequire Export floyd.aggregate_type.\n\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} (d: A) 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 d) p |-- P1 i (Znth (i-lo) v1 d) p) ->\n  array_pred d lo hi P0 v0 p |-- array_pred d 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} (d:A) 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 d) p = P1 i (Znth (i-lo) v1 d) p) ->\n  array_pred d lo hi P0 v0 p = array_pred d 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 <= Int.modulus ->\n  0 <= lo <= hi ->\n  sizeof t * (hi - lo) < Int.modulus ->\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 (Int.repr ofs)) =\n   memory_block sh (sizeof t * (hi - lo)) (Vptr b (Int.repr (ofs + sizeof t * lo))).\nProof.\n  intros.\n  unfold array_pred.\n  rewrite prop_true_andp by auto; clear H2.\n  f_equal.\n  remember (Z.to_nat (hi - lo)) as n eqn:HH.\n  revert lo HH H H0 H1 v; induction n; intros.\n  + simpl.\n    pose proof arith_aux00 _ _ (proj2 H0) HH.\n    rewrite H2, 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 | 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 <= Int.modulus ->\n  sizeof t * z < Int.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 (Int.repr ofs))  =\n  memory_block sh (sizeof t * z) (Vptr b (Int.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 < Int.modulus ->\n  0 <= ofs /\\ ofs + sz <= Int.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 (Int.repr ofs)) =\n  memory_block sh sz (Vptr b (Int.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 (Int.repr ofs)) =\n  memory_block sh sz (Vptr b (Int.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} (d:A) 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 d) p |-- P1 i (Znth (i-lo) v1 d) p) ->\n  array_pred d lo hi P0 v0 p |-- array_pred d lo hi P1 v1 p\n:= @array_pred_ext_derives.\n\nDefinition array_pred_ext:\n  forall {A} (d:A) 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 d) p = P1 i (Znth (i - lo) v1 d) p) ->\n  array_pred d lo hi P0 v0 p = array_pred d 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 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 <= Int.modulus ->\n  sizeof t * z < Int.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 (Int.repr ofs))  =\n  memory_block sh (sizeof t * z) (Vptr b (Int.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 < Int.modulus ->\n  0 <= ofs /\\ ofs + sz <= Int.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 (Int.repr ofs)) =\n  memory_block sh sz (Vptr b (Int.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 (Int.repr ofs)) =\n  memory_block sh sz (Vptr b (Int.repr ofs))\n:= @memory_block_union_pred.\n\nEnd auxiliary_pred.\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/floyd/aggregate_pred.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.4339814648038986, "lm_q1q2_score": 0.2588409366997985}}
{"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 Locations.\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 PowerPC application binary interface (ABI) 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\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 = Tint.\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 = Tfloat.\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\nDefinition loc_result (s: signature) : list mreg :=\n  match s.(sig_res) with\n  | None => R0 :: nil\n  | Some Tint => R0 :: nil\n  | Some (Tfloat | Tsingle) => F0 :: nil\n  | Some Tlong => R1 :: R0 :: nil\n  end.\n\n(** The result location is a caller-save register or a temporary *)\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(** We use the following calling conventions, adapted from the ARM EABI:\n- The first 4 integer arguments are passed in registers [R0] to [R3].\n- The first 2 float arguments are passed in registers [F0] and [F2].\n- The first 4 float arguments are passed in registers [F0] to [F3].\n- The first 2 integer arguments are passed in an aligned pair of two integer\n  registers.\n- Each float argument passed in a float register ``consumes'' an aligned pair\n  of two integer registers.\n- Each single argument passed in a float register ``consumes'' an integer\n  register.\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\nDefinition ireg_param (n: Z) : mreg :=\n  if zeq n (-4) then R0\n  else if zeq n (-3) then R1\n  else if zeq n (-2) then R2\n  else R3.\n\nDefinition freg_param (n: Z) : mreg :=\n  if zeq n (-4) then F0 else F2.\n\nDefinition sreg_param (n: Z) : mreg :=\n  if zeq n (-4) then F0\n  else if zeq n (-3) then F1\n  else if zeq n (-2) then F2\n  else F3.\n\nFixpoint loc_arguments_rec (tyl: list typ) (ofs: Z) {struct tyl} : list loc :=\n  match tyl with\n  | nil => nil\n  | Tint :: tys =>\n      (if zle 0 ofs then S Outgoing ofs Tint else R (ireg_param ofs))\n      :: loc_arguments_rec tys (ofs + 1)\n  | Tfloat :: tys =>\n      let ofs := align ofs 2 in\n      (if zle 0 ofs then S Outgoing ofs Tfloat else R (freg_param ofs))\n      :: loc_arguments_rec tys (ofs + 2)\n  | Tsingle :: tys =>\n      (if zle 0 ofs then S Outgoing ofs Tsingle else R (sreg_param ofs))\n      :: loc_arguments_rec tys (ofs + 1)\n  | Tlong :: tys =>\n      let ofs := align ofs 2 in\n      (if zle 0 ofs then S Outgoing (ofs + 1) Tint else R (ireg_param (ofs + 1)))\n      :: (if zle 0 ofs then S Outgoing ofs Tint else R (ireg_param ofs))\n      :: loc_arguments_rec 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  loc_arguments_rec s.(sig_args) (-4).\n\n(** [size_arguments s] returns the number of [Outgoing] slots used\n  to call a function with signature [s]. *)\n\nFixpoint size_arguments_rec (tyl: list typ) (ofs: Z) {struct tyl} : Z :=\n  match tyl with\n  | nil => ofs\n  | (Tint | Tsingle) :: tys => size_arguments_rec tys (ofs + 1)\n  | (Tfloat | Tlong) :: tys => size_arguments_rec tys (align ofs 2 + 2)\n  end.\n\nDefinition size_arguments (s: signature) : Z :=\n  Zmax 0 (size_arguments_rec s.(sig_args) (-4)).\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_caller_save:\n  forall n, In (ireg_param n) destroyed_at_call.\nProof.\n  unfold ireg_param; intros.\n  destruct (zeq n (-4)). simpl; auto.\n  destruct (zeq n (-3)). simpl; auto.\n  destruct (zeq n (-2)); simpl; auto.\nQed.\n\nRemark freg_param_caller_save:\n  forall n, In (freg_param n) destroyed_at_call.\nProof.\n  unfold freg_param; intros. destruct (zeq n (-4)); simpl; OrEq.\nQed.\n\nRemark sreg_param_caller_save:\n  forall n, In (sreg_param n) destroyed_at_call.\nProof.\n  unfold sreg_param; intros.\n  destruct (zeq n (-4)). simpl; tauto.\n  destruct (zeq n (-3)). simpl; tauto.\n  destruct (zeq n (-2)); simpl; tauto.\nQed.\n\nRemark loc_arguments_rec_charact:\n  forall tyl ofs l,\n  In l (loc_arguments_rec tyl ofs) ->\n  match l with\n  | R r => In r destroyed_at_call\n  | S Outgoing ofs' ty => ofs' >= 0 /\\ ofs <= ofs' /\\ ty <> Tlong\n  | S _ _ _ => False\n  end.\nProof.\n  induction tyl; simpl loc_arguments_rec; intros.\n  elim H.\n  destruct a.\n- (* Tint *)\n  destruct H.\n  subst l. destruct (zle 0 ofs).\n  split. omega. split. omega. congruence.\n  apply ireg_param_caller_save.\n  exploit IHtyl; eauto. destruct l; auto. destruct sl; auto. intuition omega.\n- (* Tfloat *)\n  assert (ofs <= align ofs 2) by (apply align_le; omega).\n  destruct H.\n  subst l. destruct (zle 0 (align ofs 2)).\n  split. omega. split. auto. congruence.\n  apply freg_param_caller_save.\n  exploit IHtyl; eauto. destruct l; auto. destruct sl; auto. intuition omega.\n- (* Tlong *)\n  assert (ofs <= align ofs 2) by (apply align_le; omega).\n  destruct H.\n  subst l. destruct (zle 0 (align ofs 2)).\n  split. omega. split. omega. congruence.\n  apply ireg_param_caller_save.\n  destruct H.\n  subst l. destruct (zle 0 (align ofs 2)).\n  split. omega. split. omega. congruence.\n  apply ireg_param_caller_save.\n  exploit IHtyl; eauto. destruct l; auto. destruct sl; auto. intuition omega.\n- (* Tsingle *)\n  destruct H.\n  subst l. destruct (zle 0 ofs).\n  split. omega. split. omega. congruence.\n  apply sreg_param_caller_save.\n  exploit IHtyl; eauto. destruct l; auto. destruct sl; auto. intuition omega.\nQed.\n\nLemma loc_arguments_acceptable:\n  forall (s: signature) (r: loc),\n  In r (loc_arguments s) -> loc_argument_acceptable r.\nProof.\n  unfold loc_arguments, loc_argument_acceptable; intros.\n  generalize (loc_arguments_rec_charact _ _ _ H).\n  destruct r; auto.\n  destruct sl; auto.\n  tauto.\nQed.\nHint Resolve loc_arguments_acceptable: locs.\n\n(** The offsets of [Outgoing] arguments are below [size_arguments s]. *)\n\nRemark size_arguments_rec_above:\n  forall tyl ofs,\n  ofs <= size_arguments_rec tyl ofs.\nProof.\n  induction tyl; simpl; intros.\n  omega.\n  destruct a.\n  apply Zle_trans with (ofs + 1); auto; omega.\n  assert (ofs <= align ofs 2) by (apply align_le; omega).\n  apply Zle_trans with (align ofs 2 + 2); auto; omega.\n  assert (ofs <= align ofs 2) by (apply align_le; omega).\n  apply Zle_trans with (align ofs 2 + 2); auto; omega.\n  apply Zle_trans with (ofs + 1); auto; omega.\nQed.\n\nLemma size_arguments_above:\n  forall s, size_arguments s >= 0.\nProof.\n  intros; unfold size_arguments. apply Zle_ge. apply Zmax1.\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  intros.\n  assert (forall tyl ofs0,\n          0 <= ofs0 ->\n          ofs0 <= Zmax 0 (size_arguments_rec tyl ofs0)).\n  {\n    intros. generalize (size_arguments_rec_above tyl ofs0). intros.\n    rewrite Zmax_spec. rewrite zlt_false. auto. omega.\n  }\n  assert (forall tyl ofs0,\n    In (S Outgoing ofs ty) (loc_arguments_rec tyl ofs0) ->\n    ofs + typesize ty <= Zmax 0 (size_arguments_rec tyl ofs0)).\n  {\n    induction tyl; simpl; intros.\n    elim H1.\n    destruct a.\n  - (* Tint *)\n    destruct H1; auto. destruct (zle 0 ofs0); inv H1. apply H0. omega.\n  - (* Tfloat *)\n    destruct H1; auto. destruct (zle 0 (align ofs0 2)); inv H1. apply H0. omega.\n  - (* Tlong *)\n    destruct H1.\n    destruct (zle 0 (align ofs0 2)); inv H1.\n    eapply Zle_trans. 2: apply H0. simpl typesize; omega. omega.\n    destruct H1; auto.\n    destruct (zle 0 (align ofs0 2)); inv H1.\n    eapply Zle_trans. 2: apply H0. simpl typesize; omega. omega.\n  - (* Tsingle *)\n    destruct H1; auto. destruct (zle 0 ofs0); inv H1. apply H0. omega.\n  }\n  unfold size_arguments. apply H1. auto.\nQed.\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/arm/eabi/Conventions1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.25884093047352}}
{"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 uniq_tac.\nImport MachineInt.\nRequire Import mips_seplog mips_frame mips_tactics mips_contrib mapstos.\nRequire Import mont_mul_strict_prg.\nRequire Import mont_square_triple multi_lt_triple multi_sub_u_u_L_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.\n\nVariables k alpha x z m one ext int_ X_ Y_ M_ Z_ quot C t s_ : reg.\n\nLemma mont_square_strict_verif :\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.+1 < \\B^1 ->\n  \\S_{ nk } X < \\S_{ nk } M ->\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 |--> nseq nk zero32 ++ zero32 :: nil ** var_e m |--> M ++ zero32 :: nil) s h /\\ store.multi_null s}}\n  mont_mul_strict 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 /\\ [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.\n\n(**  montgomery k alpha x y z m_ one ext int_ X_ Y_ M_ Z_ quot C t s_ ; *)\n\napply while.hoare_seq with ((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 ** 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) **\n(var_e z \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32\n  ** var_e m \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32)).\n\napply (hoare_prop_m.hoare_stren ((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 ** var_e m |--> M) s h /\\ store.multi_null s) **\n(var_e z \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32\n  ** var_e m \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32))).\n\nmove=> s h [r_x [r_z [r_m_ [r_k [r_alpha [Hmem Hmultiplier]]]]]].\n\nrewrite assert_m.conCE !assert_m.conAE\n  decompose_last_equiv size_nseq !assert_m.conAE assert_m.conCE !assert_m.conAE in Hmem.\n\nrewrite assert_m.conCE !assert_m.conAE.\nmove: Hmem; apply monotony=> // h' Hmem.\nrewrite decompose_last_equiv HlenM in Hmem.\nrewrite !assert_m.conAE assert_m.conCE !assert_m.conAE in Hmem.\nby move: Hmem; apply monotony => // h'' Hmem.\n\napply frame_rule_R => //.\n- eapply mont_square_triple; eauto.\n  apply: (ltZ_trans _ Hnz).\n  rewrite Z_S mulZDr !addZA -{1}[_ + _]addZ0; exact/ltZ_add2l.\n- by Inde_frame.\n\napply pull_out_exists_con => 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    \\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 /\\ u2Z [t]_s = u2Z vz + 4 * Z_of_nat nk.-1 /\\\n    ((var_e x |--> X ** var_e z |--> Z ** var_e m |--> M\n      ** var_e z \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32\n        ** var_e m \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32) s h)))).\n\nmove=> s h [h1 [h2 [Hdisj [Hunion [[len_Z [r_x [r_z [r_m [r_k [r_alpha [Hmem [Sum_Z1 [Sum_Z2 r_t]]]]]]]]] Hmem2]]]]].\nexists heap.emp, (h1 \\U h2); repeat (split; trivial).\nby map_tac_m.Disj.\nby map_tac_m.Equal.\nrewrite -2!assert_m.conAE; Compose_sepcon h1 h2 => //.\nby rewrite conAE.\n\napply pull_out_bang => len_Z.\n\n(**  ifte_beq C, r0 thendo *)\n\napply while.hoare_ifte.\n\n(**    (multi_lt_prg k z m_ X_ Y_ int_ ext Z_ M_; *)\n\napply (hoare_prop_m.hoare_stren (fun s h =>\n  (([x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\\n    u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n    \\B^nk * \\S_{nk.+1} (Z ++ zero32 :: nil) =m \\S_{ nk } X * \\S_{ nk } X {{\\S_{ nk } M}}) /\\\n  \\S_{nk.+1} (Z ++ zero32 :: nil) < 2 * \\S_{ nk } M /\\\n  u2Z [t]_s = u2Z vz + 4 * Z_of_nat nk.-1 /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M **\n    var_e z \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32 **\n      var_e m \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32) s h))).\n\nmove=> s h [ [r_x [r_z [r_m [r_k [r_alpha [Sum_Z1 [Sum_Z2 [r_t Hmem]]]]]]]] HbeqC0].\n\nrewrite /= store.get_r0 in HbeqC0; move/eqP/u2Z_inj in HbeqC0.\nby rewrite HbeqC0 in Sum_Z1 Sum_Z2.\n\napply (hoare_prop_m.hoare_stren ((fun s h => (u2Z [k]_s = Z_of_nat nk /\\\n  [z]_s = vz /\\ [m]_s = vm /\\ (var_e z |--> Z ** var_e m |--> M) s h)) **\n((fun s h => [x]_s = vx /\\ [alpha]_s = valpha /\\\n  \\B^nk * \\S_{nk.+1} (Z ++ zero32 :: nil) =m \\S_{ nk } X * \\S_{ nk } X {{\\S_{ nk } M}} /\\\n  \\S_{nk.+1} (Z ++ zero32 :: nil) < 2 * \\S_{ nk } M /\\\n  u2Z [t]_s = u2Z vz + 4 * Z_of_nat nk.-1) //\\\\\n(var_e x |--> X ** var_e z \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32 **\n  var_e m \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32)))).\n\nmove=> s h [[r_x [r_z [r_m [r_k [r_alpha Sum_Z1]]]]] [Sum_Z2 [r_t Hmem]]].\n\nhave {}Hmem : ((var_e z |--> Z ** var_e m |--> M) **\n  (var_e x |--> X ** var_e z \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32 **\n    var_e m \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32)) s h.\n  by assoc_comm Hmem.\ncase: Hmem => h1 [h2 [Hdisj [Hunion [H1 H2]]]].\nby exists h1, h2.\n\napply while.hoare_seq with ((fun s h => u2Z [k]_s = Z_of_nat nk /\\\n  [z]_s = vz /\\ [m]_s = vm /\\\n  ((\\S_{ nk } Z < \\S_{ nk } M /\\ [int_]_s = one32 /\\ [ext]_s = zero32) \\/\n    (\\S_{ nk } Z > \\S_{ nk } M /\\ [int_]_s = zero32 /\\ [ext]_s = one32) \\/\n    (\\S_{ nk } Z = \\S_{ nk } M /\\ [int_]_s = zero32 /\\ [ext]_s = zero32)) /\\\n  (var_e z |--> Z ** var_e m |--> M) s h) **\n((fun s h => [x]_s = vx /\\ [alpha]_s = valpha /\\\n  (\\B^nk * \\S_{ nk.+1 } (Z ++ zero32 :: nil) =m \\S_{ nk } X * \\S_{ nk } X {{\\S_{ nk } M}}) /\\\n  \\S_{ nk.+1 } (Z ++ zero32 :: nil) < 2 * \\S_{ nk } M /\\\n  u2Z [t]_s = u2Z vz + 4 * Z_of_nat nk.-1) //\\\\\n(var_e x |--> X ** var_e z \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32 **\n  var_e m \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32))).\n\napply frame_rule_R.\n- eapply multi_lt_triple; eauto.\n  by Uniq_uniq r0.\n- by Inde_frame.\n- move=> ?; by Inde_mult.\n\n(**    ifte_beq int_, r0 thendo *)\n\napply while.hoare_ifte.\n\n(**      multisub k one z m_ z ext int_ quot C Z_ X_ Y_ X_\n    elsedo\n      nop)\n  elsedo *)\n\napply (hoare_prop_m.hoare_stren (!(fun s => \\S_{ nk } M <= \\S_{ nk } Z) **\n  (fun s h => [z]_s = vz /\\ [m]_s = vm /\\ u2Z [k]_s = Z_of_nat nk /\\\n    [x]_s = vx /\\ [alpha]_s = valpha /\\\n    (\\B^nk * \\S_{ nk.+1 } (Z ++ zero32 :: nil) =m \\S_{ nk } X * \\S_{ nk } X {{\\S_{ nk } M}}) /\\\n    \\S_{ nk.+1 } (Z ++ zero32 :: nil) < 2 * \\S_{ nk } M /\\\n    u2Z [t]_s = u2Z vz + 4 * Z_of_nat nk.-1 /\\\n    ((var_e z |--> Z ** var_e m |--> M) **\n      (var_e x |--> X ** var_e z \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32 **\n        var_e m \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32)) s h))).\n\nmove=> s h [[h1 [h2 [Hdisj [Hunion [[r_k [r_z [r_m [Hor Hmem]]]] [[r_x [r_alpha [Sum_Z1 [Sum_Z2 r_t]]]] Hmem2]]]]]] Hbeqint0].\n\nrewrite /= store.get_r0 in Hbeqint0; move/eqP in Hbeqint0.\n\nexists heap.emp, (h1 \\U h2); repeat (split; trivial).\nby map_tac_m.Disj.\nby map_tac_m.Equal.\ncase : Hor.\n- case => _ [Hor _]; by rewrite Hor /one32 /zero32 2?Z2uK in Hbeqint0.\n- case; [case=> H _; exact/ltZW/Z.gt_lt | case=> -> _; exact/leZZ].\n- by exists h1, h2.\n\napply pull_out_bang => HZM.\n\napply (hoare_prop_m.hoare_stren ((fun s h => ([z]_s = vz /\\ [m]_s = vm /\\\n  u2Z [k]_s = Z_of_nat nk /\\ (var_e z |--> Z ** var_e m |--> M) s h)) **\n(fun s h => [x]_s = vx /\\ [alpha]_s = valpha /\\\n  (\\B^nk * \\S_{ nk.+1 } (Z ++ zero32 :: nil) =m \\S_{ nk } X * \\S_{ nk } X {{\\S_{ nk } M}}) /\\\n  \\S_{ nk.+1 } (Z ++ zero32 :: nil) < 2 * \\S_{ nk } M /\\\n  u2Z [t]_s = u2Z vz + 4 * Z_of_nat nk.-1 /\\\n  (var_e x |--> X ** var_e z \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32 **\n      var_e m \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32) s h))).\n\nmove=> s h [r_z [r_m [r_k [r_x [r_alpha [Sum_Z1 [Sum_Z2 [Hgpt Hmem]]]]]]]].\n\ncase: Hmem => h1 [h2 [Hdisj [Hunion [H1 H2]]]].\nby exists h1, h2.\n\napply (hoare_prop_m.hoare_weak ((fun s h => exists Z', size Z' = nk /\\ [z]_s = vz /\\\n  [m]_s = vm /\\ u2Z [k]_s = Z_of_nat nk /\\ [C]_s = zero32 /\\ (var_e z |--> Z' ** var_e m |--> M) s h /\\\n  \\S_{ nk } Z' = \\S_{ nk } Z - \\S_{ nk } M) **\n(fun s h => [x]_s = vx /\\ [alpha]_s = valpha /\\\n  (\\B^nk * \\S_{ nk.+1 } (Z ++ zero32 :: nil) =m \\S_{ nk } X * \\S_{ nk } X {{ \\S_{ nk } M }}) /\\\n  \\S_{ nk.+1 } (Z ++ zero32 :: nil) < 2 * \\S_{ nk } M /\\\n  u2Z [t]_s = u2Z vz + 4 * Z_of_nat nk.-1 /\\\n  (var_e x |--> X ** var_e z \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32 **\n    var_e m \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32) s h))).\n\nmove=> s h [h1 [h2 [Hdisj [Hunion [[Z' [len_Z' [r_z [r_m [r_k [HC [Hmem1 HSumSub]]]]]]] [r_x [r_alpha [Sum_Z1 [Sum_Z2 [r_t Hmem2]]]]]]]]]].\nexists Z'; repeat (split; trivial).\n\nmove: (assert_m.con_cons _ _ _ _ _ Hdisj Hmem1 Hmem2).\nrewrite -Hunion => Htmp.\nrewrite 2!decompose_last_equiv len_Z' HlenM; by assoc_comm Htmp.\n\nrewrite HSumSub.\nrewrite (lSum_cut_last _ Z) // in Sum_Z1; last by rewrite size_cat /= len_Z addnC.\nrewrite subn1 [_.+1.-1]/= /= /zero32 Z2uK // mulZ0 // addZ0 in Sum_Z1.\nrewrite mulZBr; exact/eqmod_minmod.\n\nrewrite (lSum_cut_last _ Z) // in Sum_Z2; last by rewrite size_cat /= len_Z addnC.\nrewrite subn1 [_.+1.-1]/= /zero32 Z2uK // mulZ0 // in Sum_Z2.\nrewrite HSumSub; lia.\n\napply frame_rule_R.\n- eapply multi_sub_u_u_L_triple_B_le_A; eauto.\n  + by Uniq_uniq r0.\n  + apply: (ltZ_trans _ Hnz).\n    rewrite Z_S mulZDr !addZA -{1}[_ + _]addZ0; exact/ltZ_add2l.\n- by Inde_frame.\n- move=> ?; by Inde_mult.\n\napply hoare_nop'.\n\nmove=> s h [ [h1 [h2 [Hdisj [Hunion [[r_k [r_z [r_m [Hor Hmem1]]]] [[r_x [r_alpha [Sum_Z1 [Sum_Z2 r_t]]]] Hmem2]]]]]] Hbneint0].\nexists Z; repeat (split; trivial).\n\nmove: (assert_m.con_cons _ _ _ _ _ Hdisj Hmem1 Hmem2).\nrewrite -Hunion => Htmp.\nrewrite 2!decompose_last_equiv len_Z HlenM; by assoc_comm Htmp.\n\nrewrite (lSum_cut_last _ Z) // in Sum_Z1; last by rewrite size_cat /= len_Z addnC.\nby rewrite subn1 /zero32 Z2uK // mulZ0 addZ0 in Sum_Z1.\ncase: Hor.\n- by case.\n- rewrite /= store.get_r0 in Hbneint0; move/eqP in Hbneint0.\n  case.\n  + case=> _ [Hor _]; by rewrite Hor in Hbneint0.\n  + move=> [_ [Hor _]]; by rewrite Hor in Hbneint0.\n\n(** addiu t t four16 *)\n\napply hoare_addiu 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  (\\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 /\\ u2Z [C]_s <> u2Z (zero32) /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M **\n    var_e z \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32 **\n      var_e m \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32) s h)).\n\nmove=> s h [[r_x [r_z [r_m [r_k [r_alpha [Sum_Z1 [Sum_Z2 [r_t Hmem]]]]]]]] HbneC0].\nrewrite /wp_addiu; repeat Reg_upd; repeat (split; trivial).\n- rewrite sext_Z2u // u2Z_add_Z2u //.\n  + rewrite r_t -subn1 inj_minus1 //; last by destruct nk => //; exact/le_n_S/le_O_n.\n    ring.\n  + rewrite r_t -subn1 inj_minus1; last by destruct nk => //; exact/le_n_S/le_O_n.\n    rewrite -Zbeta1E; rewrite Z_S in Hnz; lia.\n- rewrite /= store.get_r0 // in HbneC0; by move/eqP : HbneC0.\n- by Assert_upd.\n\n(** sw C zero16 t *)\n\napply hoare_sw_back'' 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  \\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 /\\ u2Z [C]_s <> u2Z (zero32) /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M **\n    var_e z \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e [C]_s **\n      var_e m \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32) s h)).\n\nmove=> s h [r_x [r_z [r_m [r_k [r_alpha [Sum_Z1 [Sum_Z2 [r_t [r_C Hmem]]]]]]]]].\n\nhave Htmp : [t]_s `+ sext 16 zero16 = [z]_s `+ Z2u 32 (Z_of_nat (4 * nk)).\n  rewrite sext_0 addi0; apply u2Z_inj.\n  rewrite r_t u2Z_add_Z2u //.\n  rewrite r_z inj_mult; ring.\n  exact: Zle_0_nat.\n  rewrite r_z -Zbeta1E inj_mult [Z_of_nat 4]/=.\n  move: (min_u2Z vz) => ?; omegaz.\n\nexists (int_e zero32).\nrewrite assert_m.conCE !assert_m.conAE assert_m.conCE !assert_m.conAE assert_m.conCE !assert_m.conAE in Hmem.\nmove: Hmem; apply monotony => // h'.\nexact: mapsto_ext.\n\napply currying => h0 H0.\n\nrepeat (split; trivial).\nassoc_comm H0.\nexact: mapsto_ext H0.\n\n(*:    addiu ext k one16 ; *)\n\napply hoare_addiu 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  \\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 /\\ u2Z [C]_s <> u2Z (zero32) /\\\n  u2Z [ext]_s = Z_of_nat nk.+1 /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M **\n    var_e z \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e [C]_s **\n      var_e m \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32) s h)).\n\nmove=> s h [r_x [r_z [r_m [r_k [r_alpha [Sum_Z1 [Sum_Z2 [r_t [r_C Hmem]]]]]]]]].\nrewrite /wp_addiu; repeat Reg_upd; repeat (split; trivial).\n- rewrite sext_Z2u // u2Z_add_Z2u //.\n  + rewrite r_k Z_S; ring.\n  + rewrite r_k -Zbeta1E.\n    move: (min_u2Z vz) => ?; omegaz.\n- by Assert_upd.\n\n(**   multisub ext one z m_ z M_ int_ quot C Z_ X_ Y_ X_). *)\n\napply (hoare_prop_m.hoare_stren ((fun s h => exists Cint32,\n  (\\S_{ nk.+1 } (M ++ zero32 :: nil) <= \\S_{ nk.+1 } (Z ++ Cint32 :: nil) /\\ [C]_s = Cint32) /\\ h = heap.emp) **\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  (\\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 /\\ u2Z [ext]_s = Z_of_nat nk.+1 /\\\n  ((var_e x |--> X ** var_e z |--> Z ** var_e m |--> M **\n    var_e z \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e [C]_s **\n      var_e m \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32) s h))))).\n\nmove=> s h [r_x [r_z [r_m [r_k [r_alpha [Sum_Z1 [Sum_Z2 [r_t [r_C [r_ext Hmem]]]]]]]]]].\nexists heap.emp, h; repeat (split; trivial).\nby map_tac_m.Disj.\nby map_tac_m.Equal.\nexists ([C]_s); repeat (split; trivial).\nrewrite lSum_cut_last; last by rewrite size_cat /= HlenM addnC.\nrewrite lSum_cut_last; last by rewrite size_cat /= len_Z addnC.\nrewrite /= subn1 /zero32 Z2uK // mulZ0 addZ0.\nmove: (max_lSum nk M); rewrite -ZbetaE => ?.\nmove: (min_lSum nk Z) (min_lSum nk M) => ? ?.\nhave ? : 0 < u2Z [C]_s.\n  rewrite /zero32 Z2uK // in r_C.\n  rewrite ltZ_neqAle; split; by [apply min_u2Z | contradict r_C].\nsimpl.\napply (@leZ_trans (\\S_{ nk } Z + \\B^nk * 1)); first by lia.\napply leZ_add2l, leZ_pmul2l; by [lia | ].\n\napply pull_out_exists_con => Cint32.\n\napply (hoare_prop_m.hoare_stren (\n  !(fun s => \\S_{ nk.+1 } (M ++ zero32 :: nil) <= \\S_{ nk.+1 } (Z ++ Cint32 :: nil)) **\n  (fun s h => [ x ]_s = vx /\\ [ z ]_s = vz /\\ [ m ]_s = vm /\\\n    u2Z [ k ]_s = Z_of_nat nk /\\ [ alpha ]_s = valpha /\\ [ C ]_s = Cint32 /\\\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 /\\ u2Z [ext]_s = Z_of_nat nk.+1 /\\\n    (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M **\n      var_e z \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e [ C ]_s **\n        var_e m \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32) s h))).\n\nmove=> s h [h1 [h2 [Hdisj [Hunion [[[Sum_Z1 r_C] Hh1] [r_x [r_z [r_m [r_k [r_alpha [Sum_Z2 [Sum_Z3 [r_t [r_ext Hmem]]]]]]]]]]]]]].\nby exists h1, h2.\n\napply pull_out_bang => HZM.\n\napply (hoare_prop_m.hoare_stren ((fun s h => [z]_s = vz /\\\n  [m]_s = vm /\\ u2Z [ext]_s = Z_of_nat nk.+1 /\\\n  (var_e z |--> (Z ++ Cint32 :: nil) ** var_e m |--> M ++ zero32 :: nil) s h) **\n(fun s h => [x]_s = vx /\\\n  u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (\\B^nk * \\S_{ nk.+1 } (Z ++ Cint32 :: nil) =m \\S_{ nk } X * \\S_{ nk } X {{\\S_{ nk } M}}) /\\\n  \\S_{ nk.+1 } (Z ++ Cint32 :: nil) < 2 * \\S_{ nk } M /\\\n  u2Z [t]_s = u2Z vz + 4 * Z_of_nat nk /\\ (var_e x |--> X) s h))).\n\nmove=> s h [r_x [r_z [r_m [r_k [r_alpha [r_C [Sum_Z1 [Sum_Z2 [r_t [r_ext Hmem]]]]]]]]]].\n\nhave {}Hmem : ((var_e z |--> Z ++ Cint32 :: nil ** var_e m |--> M ++ zero32 :: nil) ** (var_e x |--> X)) s h.\n  rewrite 2!decompose_last_equiv len_Z HlenM.\n  assoc_comm Hmem.\n  by rewrite -r_C.\ncase: Hmem => h1 [h2 [Hdisj [Hunion [H1 H2]]]].\nexists h1, h2; repeat (split; trivial).\nby rewrite -r_C.\nby rewrite -r_C.\n\napply (hoare_prop_m.hoare_weak ((fun s h => exists Z', size Z' = nk.+1 /\\ [z]_s = vz /\\\n  [m]_s = vm /\\ u2Z [ext]_s = Z_of_nat nk.+1 /\\ [C]_s = zero32 /\\\n  (var_e z |--> Z' ** var_e m |--> M ++ zero32 :: nil) s h /\\\n  \\S_{ nk.+1 } Z' = \\S_{ nk.+1 } (Z ++ Cint32 :: nil) - \\S_{ nk.+1 } (M ++ zero32 :: nil)) **\n(fun s h => [x]_s = vx /\\ u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n    (\\B^nk * \\S_{ nk.+1 } (Z ++ Cint32 :: nil) =m \\S_{ nk } X * \\S_{ nk } X {{ \\S_{ nk } M }}) /\\\n    \\S_{ nk.+1 } (Z ++ Cint32 :: nil) < 2 * \\S_{ nk } M /\\\n    u2Z [t]_s = u2Z vz + 4 * Z_of_nat nk /\\ (var_e x |--> X) s h))).\n\nmove=> s h [h1 [h2 [Hdisj [Hunion [[Z' [len_Z' [r_z [r_m_ [r_ext [HC [Hmem1 Sum_Z']]]]]]] [r_x [r_k [r_alpha [HsumZC2 [HsumZC3 [r_t Hmem2]]]]]]]]]]].\n\nhave [Z'' [HlenZ'' HZ'Z'']] :\n  exists Z'', size Z'' = nk /\\ Z' = Z'' ++ zero32 :: nil.\n  have Htmp :  \\S_{ nk.+1 } Z' < \\S_{ nk.+1 } (M ++ zero32 :: nil).\n    rewrite Sum_Z' (lSum_cut_last nk.+1 M); last by rewrite size_cat /= HlenM addnC.\n    rewrite !subn1 /zero32 Z2uK // mulZ0 addZ0.\n    rewrite (lSum_cut_last nk.+1 M) in HZM; last by rewrite size_cat /= HlenM addnC.\n    rewrite subn1 /zero32 Z2uK // mulZ0 addZ0 in HZM.\n    rewrite /=.\n    apply (@ltZ_leZ_trans (2 * \\S_{ nk } M - \\S_{ nk } M)); [exact/ltZ_sub2r | lia].\n  have Htmp' : \\S_{ nk.+1 } Z' < \\B^nk.\n    rewrite (lSum_cut_last _ M) // in Htmp; last by rewrite size_cat /= HlenM addnC.\n    rewrite subn1 [_.+1.-1]/= /zero32 Z2uK // mulZ0 addZ0 in Htmp.\n    move: (max_lSum nk M); rewrite -ZbetaE => ?; lia.\n  rewrite (lSum_beyond_inv 32 nk.+1 _ nk len_Z').\n  exists (take nk Z'); split => //.\n  by rewrite size_takel // len_Z'.\n  by rewrite subSn // subnn.\n  by [].\n  by rewrite -ZbetaE.\n\nexists Z''; repeat (split; trivial).\n\nrewrite -HZ'Z'' assert_m.conCE.\n\nexists h1, h2; repeat (split => //).\n\nrewrite HZ'Z'' (lSum_cut_last _ Z'') // in Sum_Z'; last by rewrite size_cat /= HlenZ'' addnC.\nrewrite subn1 [_.+1.-1]/= (lSum_cut_last _ M) // in Sum_Z'; last by rewrite size_cat /= HlenM addnC.\nrewrite subn1 [_.+1.-1]/= /zero32 Z2uK // mulZ0 2!addZ0 in Sum_Z'.\nrewrite Sum_Z' mulZBr; exact: eqmod_minmod.\n\nrewrite HZ'Z'' (lSum_cut_last _ Z'') // in Sum_Z'; last by rewrite size_cat /= HlenZ'' addnC.\nrewrite subn1 [_.+1.-1]/= (lSum_cut_last _ M) // in Sum_Z'; last by rewrite size_cat /= HlenM addnC.\nrewrite subn1 [_.+1.-1]/= /zero32 Z2uK // mulZ0 2!addZ0 in Sum_Z'.\nrewrite Sum_Z'.\napply (@ltZ_leZ_trans (2 * \\S_{ nk } M - \\S_{ nk } M)); [exact: ltZ_sub2r | lia].\n\napply frame_rule_R.\n- eapply multi_sub_u_u_L_triple_B_le_A; eauto.\n  by Uniq_uniq r0.\n  by rewrite size_cat /= len_Z addnC.\n  by rewrite size_cat /= HlenM addnC.\n- by Inde_frame.\n- move=> ?; by Inde_mult.\nQed.\n\nEnd mont_square_strict.\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_triple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.25884093047352}}
{"text": "Require Import Omega.\nRequire Import Bool.\nRequire Import RelationClasses.\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 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 Single.\nRequire Import JoinedView.\n\nRequire Import LocalDRFPFView.\n\nRequire Import OrdStep.\nRequire Import Stable.\nRequire Import RAStep.\nRequire Import PFtoRASimThread.\nRequire Import PFtoRA.\n\nSet Implicit Arguments.\n\n\nModule RARace.\nSection RARACE.\n  Variable L: Loc.t -> bool.\n\n  Definition race (c1: Configuration.t): Prop :=\n    exists c2 c3\n           tid_w e_w loc from to val released ordw\n           tid_r lang st3 lc3 e4 e5\n           pf e_r released' ordr,\n      (<<WRITE_STEP: OrdConfiguration.step L Ordering.acqrel e_w tid_w c1 c2>>) /\\\n      (<<WRITE_EVENT: ThreadEvent.is_writing e_w = Some (loc, from, to, val, released, ordw)>>) /\\\n      (<<STEPS2: rtc (@OrdConfiguration.all_step L Ordering.acqrel) c2 c3>>) /\\\n      (<<FIND: IdentMap.find tid_r (Configuration.threads c3) = Some (existT _ lang st3, lc3)>>) /\\\n      (<<THREAD_STEPS: rtc (@OrdThread.all_step _ L Ordering.acqrel)\n                           (Thread.mk _ st3 lc3 (Configuration.sc c3) (Configuration.memory c3))\n                           e4>>) /\\\n      (<<CONS: Local.promise_consistent (Thread.local e4)>>) /\\\n      (<<READ_STEP: OrdThread.step L Ordering.acqrel pf e_r e4 e5>>) /\\\n      (<<READ_EVENT: ThreadEvent.is_reading e_r = Some (loc, to, val, released', ordr)>>) /\\\n      (<<LOC: L loc>>) /\\\n      (<<HIGHER: Time.lt ((Local.tview (Thread.local e4)).(TView.cur).(View.rlx) loc) to>>) /\\\n      (<<ORDERING: __guard__(Ordering.le ordw Ordering.strong_relaxed \\/\n                             Ordering.le ordr Ordering.strong_relaxed)>>).\n\n  Definition racefree (c: Configuration.t): Prop :=\n    forall c1\n           (STEPS1: rtc (@OrdConfiguration.all_step L Ordering.acqrel) c c1),\n      ~ race c1.\n\n  Definition racefree_syn (s: Threads.syntax): Prop :=\n    racefree (Configuration.init s).\n\nEnd RARACE.\nEnd RARace.\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/RARace.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.25878863613562586}}
{"text": "(* GENERIC *)\n\nRequire Export MinBFTg.\nRequire Export ComponentAxiom.\n\n\nSection MinBFTkn0.\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     Some useful lemmas/definitions\n     =============================================================== *)\n\n  Definition ui_in_log_entry (ui : UI) (e : LOG_state_entry) : bool :=\n    if UI_dec ui (request_data2ui (log_entry_request_data e))\n    then true\n    else if in_dec UI_dec ui (log_entry_commits e) then true else false.\n\n  Definition ui_in_log ui l : bool :=\n    existsb (ui_in_log_entry ui) l.\n\n  Definition RequestData2HashData (r : RequestData) : HashData :=\n    Build_HashData\n      (request_data2view r)\n      (request_data2request r)\n      (ui_pre (request_data2ui r)).\n\n  Lemma HashData_Deq : Deq HashData.\n  Proof.\n    repeat introv.\n    destruct x as [v1 m1 ui1], y as [v2 m2 ui2].\n    destruct (ViewDeq v1 v2); subst; prove_dec.\n    destruct (Request_Deq m1 m2); subst; prove_dec.\n\n    destruct ui1 as [i1 j1 c1], ui2 as [i2 j2 c2].\n\n    destruct (rep_deq i1 i2); subst; prove_dec.\n    destruct (deq_nat j1 j2); subst; prove_dec.\n    destruct (deq_nat c1 c2); subst; prove_dec.\n  Defined.\n\n  Definition RequestDataAndUI2HashData (r : RequestData) (ui : UI) : HashData :=\n    Build_HashData\n      (request_data2view r)\n      (request_data2request r)\n      (ui_pre ui).\n\n  Fixpoint hash_data_in_log_commits (hd : HashData) (rd : RequestData) (l : list UI) : bool :=\n    match l with\n    | [] => false\n    | ui :: uis =>\n      if HashData_Deq hd (RequestDataAndUI2HashData rd ui) then true\n      else hash_data_in_log_commits hd rd uis\n    end.\n\n  Definition hash_data_in_log_entry (hd : HashData) (e : LOG_state_entry) : bool :=\n    if HashData_Deq hd (RequestData2HashData (log_entry_request_data e))\n    then true\n    else hash_data_in_log_commits hd (log_entry_request_data e) (log_entry_commits e).\n\n  Definition hash_data_in_log (hd : HashData) (l : LOG_state) : bool :=\n    existsb (hash_data_in_log_entry hd) l.\n\n  Inductive MinBFT_data :=\n(*  | minbft_data_prepare (p  : Prepare)\n  | minbft_data_commit  (c  : Commit)\n  | minbft_data_hdata   (hd : HashData)*)\n  | minbft_data_rdata   (rd : RequestData)\n  | minbft_data_ui      (ui : UI).\n\n  Definition MinBFT_auth2data (a : AuthenticatedData) : list MinBFT_data :=\n    match a with\n    | MkAuthData (MinBFT_msg_bare_prepare bp pui) [d] =>\n      let ui := Build_UI pui d in\n      [minbft_data_rdata (prepare2request_data (prepare bp ui)),\n       minbft_data_ui ui]\n\n    | MkAuthData (MinBFT_msg_bare_commit bc pui) [d] =>\n      let uj  := Build_UI pui d in\n      let com := commit bc uj in\n      [minbft_data_rdata (commit2request_data_i com),\n       (*minbft_data_rdata (commit2request_data_j com),*)\n       minbft_data_ui (bare_commit_ui bc),\n       minbft_data_ui uj]\n\n    | _ => []\n    end.\n\n  Definition request_data_in_log (rd : RequestData) (l : LOG_state) : bool :=\n    match find_entry rd l with\n    | Some _ => true\n    | None => false\n    end.\n\n  Lemma equal_hash_data_implies_equal_request_data :\n    forall r1 r2,\n      request_data2ui r1 = request_data2ui r2\n      -> RequestData2HashData r1 = RequestData2HashData r2\n      -> minbft_data_rdata r1 = minbft_data_rdata r2.\n  Proof.\n    introv h q.\n    destruct r1 as [v1 r1 ui1], r2 as [v2 r2 ui2]; simpl in *; subst.\n    unfold RequestData2HashData in *; ginv; auto.\n  Qed.\n\n\n\n  (* === INSTANTIATION OF ComponentTrust === *)\n\n  Definition auth_data2ui (a : AuthenticatedData) : list UI :=\n    match a with\n    | MkAuthData (MinBFT_msg_bare_prepare _ pui) [d] => [Build_UI pui d]\n    | MkAuthData (MinBFT_msg_bare_commit  c pui) [d] => [bare_commit_ui c, Build_UI pui d]\n    | _ => []\n    end.\n\n  Definition USIG_output_interface2ui (cn : PreCompName) (o : USIG_output_interface) : option UI :=\n    match o with\n    | create_ui_out ui => ui\n    | verify_ui_out b => None\n    | verify_ui_out_def => None\n    end.\n\n  Global Instance MinBFT_I_ComponentTrust : ComponentTrust :=\n    MkComponentTrust\n      UI\n      auth_data2ui\n      USIG_output_interface2ui\n      (fun n => Some (ui2rep n)).\n\n  (* === ======================== === *)\n\nEnd MinBFTkn0.\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/MinBFTkn0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.25874784814994234}}
{"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 ssrnat eqtype seq.\nRequire Import ssrZ ZArith_ext seq_ext ssrnat_ext machine_int uniq_tac multi_int.\nImport MachineInt.\nRequire Import mips_seplog mips_contrib mips_tactics mips_frame.\nImport expr_m.\nImport assert_m.\nRequire Import multi_sub_s_s_s_prg pick_sign_triple multi_add_s_s_u_triple.\nRequire Import multi_sub_s_s_u_triple pick_sign_triple copy_s_s_triple.\n\nLocal Open Scope zarith_ext_scope.\nLocal Open Scope uniq_scope.\nLocal Open Scope mips_hoare_scope.\nLocal Open Scope mips_expr_scope.\nLocal Open Scope mips_assert_scope.\nLocal Open Scope machine_int_scope.\nLocal Open Scope multi_int_scope.\n\nLemma multi_sub_s_s_s_triple rk rz rx ry a0 a1 a2 a3 a4 a5 rX rY rZ :\n  uniq(rk, rz, rx, ry, a0, a1, a2, a3, a4, a5, rX, rY, rZ, r0) ->\n  forall nk vx vy vz ptrx ptry ptrz, 0 < Z_of_nat nk < 2 ^^ 31 ->\n    u2Z ptrx + 4 * Z_of_nat nk < \\B^1 ->\n    u2Z ptry + 4 * Z_of_nat nk < \\B^1 ->\n    u2Z ptrz + 4 * Z_of_nat nk < \\B^1 ->\n  forall X Y Z, size X = nk -> size Y = nk -> size Z = nk ->\n    forall slenx sleny slenz,\n    s2Z slenx = sgZ (s2Z slenx) * Z_of_nat nk ->\n    s2Z sleny = sgZ (s2Z sleny) * Z_of_nat nk ->\n    s2Z slenz = sgZ (s2Z slenz) * Z_of_nat nk ->\n    sgZ (s2Z slenx) = sgZ (sgZ (s2Z slenx) * \\S_{ nk } X) ->\n    sgZ (s2Z sleny) = sgZ (sgZ (s2Z sleny) * \\S_{ nk } Y) ->\n    sgZ (s2Z slenz) = sgZ (sgZ (s2Z slenz) * \\S_{ nk } Z) ->\n{{ fun s h => [rx]_s = vx /\\ [ry]_s = vy /\\ [rz]_s = vz /\\ u2Z [rk]_s = Z_of_nat nk /\\\n    ((var_e rz |--> slenz :: ptrz :: nil ** int_e ptrz |--> Z) **\n     (var_e rx |--> slenx :: ptrx :: nil ** int_e ptrx |--> X) **\n     (var_e ry |--> sleny :: ptry :: nil ** int_e ptry |--> Y)) s h }}\n multi_sub_s_s_s rk rz rx ry a0 a1 a2 a3 a4 a5 rX rY rZ\n {{ fun s h => exists Z' slenz', size Z' = nk /\\\n   s2Z slenz' = sgZ (s2Z slenz') * Z_of_nat nk /\\\n   sgZ (s2Z slenz') = sgZ (sgZ (s2Z slenx) * \\S_{ nk } X - sgZ (s2Z sleny) * \\S_{ nk } Y) /\\\n   ((var_e rz |--> slenz' :: ptrz :: nil ** int_e ptrz |--> Z') **\n    (var_e rx |--> slenx :: ptrx :: nil ** int_e ptrx |--> X) **\n    (var_e ry |--> sleny :: ptry :: nil ** int_e ptry |--> Y)) s h /\\\n   u2Z ([a3]_ s) <= 1 /\\\n   sgZ (s2Z slenz') * (\\S_{ nk } Z' + u2Z ([a3]_ s) * \\B^nk) =\n   sgZ (s2Z slenx) * \\S_{ nk } X - sgZ (s2Z sleny) * \\S_{ nk } Y }}.\nProof.\nmove=> Hregs nk vx vy vz ptrx ptry ptrz Hnk ptrx_fit ptry_fit ptrz_fit X Y Z lenX lenY lenZ\n  slenx sleny slenz Hslenx Hsleny Hslenz sgn_slenx sgn_sleny sgn_slenz.\nrewrite /multi_sub_s_s_s.\napply hoare_lw_back_alt'' with (fun s h =>\n  [rx ]_ s = vx /\\ [ry ]_ s = vy /\\ [rz ]_ s = vz /\\\n  u2Z [rk ]_ s = Z_of_nat nk /\\\n  ((var_e rz |--> slenz :: ptrz :: nil ** int_e ptrz |--> Z) **\n    (var_e rx |--> slenx :: ptrx :: nil ** int_e ptrx |--> X) **\n    var_e ry |--> sleny :: ptry :: nil ** int_e ptry |--> Y) s h /\\\n  [rY]_s = ptry).\nmove=> s h [Hrx [Hry [hrz [Hrk H]]]].\nexists ptry; split.\n  rewrite -conAE conCE conAE -mapsto2_mapstos conAE -conCE conAE in H.\n  move: H; apply monotony => // h'; apply mapsto_ext => //=; by rewrite sext_Z2u.\nrewrite /update_store_lw.\nrepeat Reg_upd.\nrepeat (split=> //).\nby Assert_upd.\napply while.hoare_seq with (fun s h =>\n  [rx ]_ s = vx /\\ [ry ]_ s = vy /\\ [ rz ]_s = vz /\\\n  u2Z [rk ]_ s = Z_of_nat nk /\\\n  ((var_e rz |--> slenz :: ptrz :: nil ** int_e ptrz |--> Z) **\n    (var_e rx |--> slenx :: ptrx :: nil ** int_e ptrx |--> X) **\n    var_e ry |--> sleny :: ptry :: nil ** int_e ptry |--> Y) s h /\\\n  [rY]_s = ptry /\\\n  [a0 ]_ s = sleny /\\\n  sgZ (s2Z [a1 ]_ s) = sgZ (s2Z sleny) /\\\n  (s2Z [ a1 ]_ s = 0 \\/ s2Z [ a1 ]_ s = 1 \\/ s2Z [ a1 ]_s = - 1)).\neapply while.hoare_conseq; last first.\n  apply (pick_sign_triple\n    (fun s h => [rx ]_ s = vx /\\ [ rz ]_s = vz /\\ [rY ]_ s = ptry /\\ u2Z [rk ]_ s = Z_of_nat nk)\n    ((var_e rz |--> slenz :: ptrz :: nil ** int_e ptrz |--> Z) **\n      (var_e rx |--> slenx :: ptrx :: nil ** int_e ptrx |--> X) **\n      var_e ry \\+ int_e four32 |--> ptry :: nil ** int_e ptry |--> Y) vy sleny).\n  by Uniq_uniq r0.\n  by Inde.\n  by Inde.\nmove=> s h [Hrx [Hry [Hrz [Hrk [H HrY]]]]].\nrepeat (split => //).\nrewrite -conAE conCE -mapsto2_mapstos in H.\nassoc_comm H.\nby rewrite -mapsto1_mapstos.\nmove=> s h [Hry [Ha0 [sgn_a1 [Ha1 [H [Hrx [Hrz [HrY Hrk]]]]]]]].\nrepeat (split => //).\nrewrite -conAE conCE -mapsto2_mapstos.\nassoc_comm H.\nby rewrite mapsto1_mapstos.\napply while.hoare_ifte.\n\napply while.hoare_ifte.\n\napply while.hoare_seq with (fun s h => s2Z sleny = 0 /\\\n  [rx ]_ s = vx /\\ [ry ]_ s = vy /\\ [rz ]_ s = vz /\\\n  u2Z [rk ]_ s = Z_of_nat nk /\\\n  ((var_e rz |--> slenx :: ptrz :: nil ** int_e ptrz |--> (if slenx == zero32 then Z else X)) **\n    (var_e rx |--> slenx :: ptrx :: nil ** int_e ptrx |--> X) **\n    var_e ry |--> sleny :: ptry :: nil ** int_e ptry |--> Y) s h /\\\n  [rY ]_ s = ptry).\nhave : uniq(rk, rz, rx, a0, a1, a2, a3, a4, r0) by Uniq_uniq r0.\nmove/copy_s_s_triple.\nmove/(_ Z X nk lenZ lenX slenz ptrz ptrz_fit slenx ptrx ptrx_fit vx Hslenx sgn_slenx) =>\n  hoare_triple.\neapply (before_frame (fun s h =>\n  s2Z sleny = 0 /\\\n  [ry ]_ s = vy /\\\n  [rz ]_ s = vz /\\\n  (var_e ry |--> sleny :: ptry :: nil ** int_e ptry |--> Y) s h /\\\n  [rY ]_ s = ptry)).\napply frame_rule_R.\nby apply hoare_triple.\nrewrite [modified_regs _]/=; by Inde.\nby [].\nmove=> s h [[[Hrx [Hry [Hrz [Hrk [H [HrY [Ha0 [sgn_a1 Ha1']]]]]]]] _] Ha1].\nrewrite -conAE in H; case: H => h1 [h2 [h1dh2 [h1Uh2 [Hh1 Hh2]]]].\nrewrite /= store.get_r0 in Ha1.\nmove/eqP/u2Z_inj in Ha1.\nexists h1, h2; repeat (split => //).\nrewrite Ha1 s2Z_u2Z_pos' // Z2uK //= in sgn_a1.\nby apply/Zsgn_null/esym.\nmove=> s h [h1 [h2 [h1dh2 [h1Uh2 [Hh1 Hh2]]]]].\ncase: Hh1 => Hrx [Hrk Hh1].\ncase: Hh2 => sleny_0 [Hry [Hrz [Hh2 HrY]]].\nrepeat (split => //).\nrewrite -conAE.\nby exists h1, h2.\n\napply (hoare_prop_m.pull_out_conjunction' hoare0_false) => sleny0.\n\napply hoare_addiu'.\nmove=> s h [Hrx [Hry [Hrz [Hrk [H HrY]]]]].\nrewrite /wp_addiu.\nexists (if slenx == zero32 then Z else X), slenx.\nsplit; first by case: ifP.\nsplit; first by [].\nsplit; first by rewrite sleny0 /= subZ0.\nsplit; first by Assert_upd.\nrepeat Reg_upd.\nrewrite add0i sext_Z2u // Z2uK //.\nsplit; first by [].\nrewrite mul0Z addZ0 sleny0 /= subZ0.\ncase: ifP => // /eqP ->.\nby rewrite s2Z_u2Z_pos' // Z2uK.\n\nhave : uniq(rk, rz, rx, rY, a0, a1, a2, a3, a4, a5, rX, rZ, r0) by Uniq_uniq r0.\nmove/multi_sub_s_s_u_triple/(_ nk vz vx ptry Hnk ptrz ptrx ptrz_fit ptrx_fit ptry_fit Z X Y lenZ lenX lenY slenx slenz Hslenx Hslenz sgn_slenx) => hoare_triple.\neapply (before_frame (fun s h => 0 < s2Z sleny /\\ [ry ]_ s = vy /\\\n  (var_e ry |--> sleny :: ptry :: nil) s h )).\napply frame_rule_R.\n  exact/hoare_triple.\n  rewrite [modified_regs _]/=; by Inde.\nby [].\nmove=> s h [[[Hrx [hry [Hrz [Hrk [H [hrY [Ha0 [sgn_a1 Ha1'']]]]]]]] Ha1'] Ha1].\nrewrite -conAE conCE 2!conAE in H.\ncase: H => h1 [h2 [h1dh2 [h1Uh2 [Hh1 Hh2]]]].\nrewrite conCE.\nexists h1, h2; repeat (split => //).\nhave Ha1''' : s2Z [a1]_s = 1.\n  case: Ha1'' => Ha1''.\n    rewrite /= in Ha1.\n    exfalso.\n    move/eqP in Ha1; apply Ha1.\n    by rewrite store.get_r0 Z2uK // -s2Z_u2Z_pos // Ha1''.\n  case: Ha1'' => // Ha1''.\n  rewrite /= in Ha1'.\n  exfalso.\n  move/leZP : Ha1'.\n  by rewrite Ha1'' => /leZP.\nrewrite Ha1''' /= in sgn_a1.\nby apply Zsgn_pos.\nrewrite -conAE conCE.\nmove: Hh2; apply monotony => // h2'.\nby apply mapstos_ext.\nmove=> Hh2'; by assoc_comm Hh2'.\n\nmove=> s h [h1 [h2 [h1dh2 [h1Uh2 [Hh1 Hh2]]]]].\ncase: Hh1 => Z' [slenz' [lenZ' [HrY [Hslenz' [sgn_slenz' [Hh1 [Ha3 HSum]]]]]]].\ncase: Hh2 => sleny0 [Hry Hh2].\nexists Z', slenz'; repeat (split => //).\napply Zsgn_pos in sleny0; by rewrite sgn_slenz' sleny0 mul1Z.\nrewrite -2!conAE conCE -conAE.\nexists h1, h2; repeat (split => //).\nassoc_comm Hh1.\nmove: Hh1; apply mapstos_ext => /=.\nby [].\napply Zsgn_pos in sleny0; by rewrite sleny0 mul1Z.\n\nhave : uniq(rk, rz, rx, rY, a0, a1, a2, a3, a4, a5, rX, rZ, r0) by Uniq_uniq r0.\nmove/multi_add_s_s_u_triple/(_ nk vz vx ptry Hnk ptrz ptrx\nptrz_fit ptrx_fit ptry_fit Z X Y lenZ lenX lenY _ _ Hslenx Hslenz sgn_slenx) => hoare_triple.\neapply (before_frame (fun s h => s2Z sleny < 0 /\\ (var_e ry |--> sleny :: ptry :: nil) s h)).\napply frame_rule_R.\n  by apply hoare_triple.\n  rewrite [modified_regs _]/=; by Inde.\nby [].\nmove=> s h [ [Hrx [Hry [Hrz [Hrk [H [HrY [Ha0 [Ha1' Ha1'']]]]]]]] Ha1 ].\nrewrite /= in Ha1.\nmove/leZP in Ha1.\nrewrite -conAE conCE -mapsto2_mapstos conAE in H.\nrewrite conCE.\ncase: H => h1 [h2 [h1dh2 [h1Uh2 [Hh1 Hh2]]]].\nexists h1, h2; repeat (split => //).\nsuff : s2Z [a1 ]_ s = -1.\n  move=> abs; rewrite abs /= in Ha1'.\n  by apply Zsgn_neg.\ncase: Ha1'' => // Ha1''.\n  exfalso.\n  by move: Ha1; rewrite Ha1'' => /leZP.\ncase: Ha1'' => // Ha1''.\nexfalso.\nby move: Ha1; rewrite Ha1'' => /leZP.\nby rewrite -mapsto2_mapstos.\nrewrite -conAE conCE.\nassoc_comm Hh2.\nmove: Hh2; by apply mapstos_ext.\n\nmove=> s h [h1 [h2 [h1dh2 [h1Uh2 [Hh1 Hh2]]]]].\ncase: Hh1 => Z' [slenz' [lenZ' [HrY [H_ [sgn_slenz' [Hh1 [Ha3 HSum]]]]]]].\ncase: Hh2 => sleny0 Hh2.\nhave Htmp : sgZ (s2Z sleny) = -1 by apply Zsgn_neg.\nexists Z', slenz'; repeat (split => //).\nrewrite sgn_slenz' Htmp.\nby rewrite Z.sub_opp_r.\nrewrite -conAE conCE conAE conCE.\nexists h1, h2; repeat (split => //).\nassoc_comm Hh1.\nmove: Hh1; by apply mapstos_ext => /=.\nrewrite HSum Htmp; ring.\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_sub_s_s_s_triple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.25874784814994234}}
{"text": "\nRequire Import Coq.Sets.Ensembles.\nRequire Import  Coq.omega.Omega.\nRequire Import Coq.Lists.List.\n\n\nRequire Coq.Bool.Bool.\nRequire Coq.Lists.ListDec.\n\nRequire Import Coq.Strings.String.\n\nRequire Export SmedlAST_submission.\nRequire Export semantic_rules.\n\n\nLocal Close Scope Z_scope.\nLocal Close Scope N_scope.\nLocal Close Scope Q_scope.\n(*aux lemma for proving termination*)\nLemma termL40': forall l1 l2, List.length (l1) <=\nList.length (mergeList' (l1) (l2) scenario_dec).\nProof. intros.  generalize dependent l2.   induction l1.\nintros.  simpl. omega.\nintros. simpl.  \nassert (forall (A:Type) (l l1: list A), Datatypes.length (l1) <= Datatypes.length ((l1) ++ l)).\nintros. induction l0. simpl. omega. simpl. omega. destruct H with (A:=scenario) (l1:=l1) (l:=filterList (a :: l1) l2 scenario_dec).\n omega. omega. \nQed.\n\n\n(*aux lemma for proving termination*)\nLemma termL41': forall M (conf conf' : configuration M) v, innerCombineFunc'''' conf v = Some conf'\n-> (Datatypes.length (finishedscenarios conf) <= Datatypes.length (finishedscenarios conf')).\nProof. intros. generalize dependent conf. generalize dependent conf'.     induction v.\nintros.  simpl in H. inversion H.  \nintros. \nsimpl in H.\ndestruct v.\n\nremember (mergeConfigFunc' conf conf a ).\n\ndestruct e;inversion H;subst.\nunfold mergeConfigFunc' in Heqe. \ndestruct (mergeDataStateFunc (datastate conf) (datastate conf) (datastate a)).\ndestruct (mergeControlStateFunc (controlstate conf) (controlstate conf) (controlstate a)).\ninversion Heqe. simpl. \n rewrite app_length. omega. \n inversion Heqe. inversion Heqe.\n remember (innerCombineFunc'''' conf (c :: v)).\n destruct o;inversion H.\n symmetry in Heqo. apply IHv in Heqo.\n \n remember (mergeConfigFunc' conf a c0).\n destruct e;inversion H.\n subst.  \nunfold mergeConfigFunc' in Heqe. \ndestruct (mergeDataStateFunc (datastate conf) (datastate a) (datastate c0)).\ndestruct (mergeControlStateFunc (controlstate conf) (controlstate a) (controlstate c0)).\ninversion Heqe. \nsimpl.  clear H2. \nrewrite app_length. omega.\ninversion Heqe.\ninversion Heqe.\n \n                                                                        \n(*remember (innerCombineFunc'''' conf v).\ndestruct o;inversion H.  unfold mergeConfigFunc' in H1. \ndestruct (mergeDataStateFunc (datastate conf) (datastate c) (datastate a)).\ndestruct (mergeControlStateFunc (controlstate conf) (controlstate c) (controlstate a)).\ninversion H1. simpl. assert (Datatypes.length (finishedscenarios conf) <=\n                             Datatypes.length (finishedscenarios c)).\napply IHv;auto. rewrite app_length. omega. inversion H1. inversion H1.\nunfold mergeConfigFunc' in H1. \ndestruct (mergeDataStateFunc (datastate conf) (datastate conf) (datastate a)).\ndestruct (mergeControlStateFunc (controlstate conf) (controlstate conf) (controlstate a)).\ninversion H1. simpl. rewrite app_length. omega. inversion H1. inversion H1. *)\n\nQed.\n\nLemma termL2: forall M (conf : configuration M) e lst scs conf', constructConfigList' scs e conf = Result lst /\\\n In conf' lst -> exists sce, In sce scs /\\  Result conf' = constructConfig sce e conf.\nProof.\nintros. destruct H.  generalize dependent lst. induction scs.\n- intros. simpl in H. induction lst. inversion H0. inversion H.\n- intros. induction lst. simpl in H. inversion H0. simpl in H.\n \n  simpl in H0. destruct H0. remember (constructConfig a e conf ). destruct e0.\n  destruct (constructConfigList' scs e). inversion H;subst. exists a. split. simpl;left. auto. apply Heqe0. inversion H. \ninversion H. inversion H.  simpl. destruct  (constructConfig a e conf ).\n\n remember (constructConfigList' scs e conf).\ndestruct e0. inversion H.  subst. destruct IHscs with lst;auto.   exists x. \ndestruct H1. split. right;auto. auto. inversion H. inversion H. \nQed.\n\nLemma termL3: forall M (conf conf' : configuration M) e sce,\n    Result conf' = constructConfig sce e conf  ->\n    (finishedscenarios conf' = sce::nil).\nProof. \nintros. unfold constructConfig in H.   \ndestruct (getScenarioState sce (controlstate conf)).\ndestruct (transEvMapFunc (stateEvDefInstanceMap M) (Some s, Some (eventDefinition e))). \ndestruct (findEventInstance e (datastate conf) l).  \ndestruct (createValueEnv (eventArgs e0) (eventParams (eventDefinition e)) (eventArguments e)) .\ndestruct (getStep' conf sce e0). \n  unfold  configTransition in H.\ndestruct (execAction (extendValEnv (datastate conf) v, nil) (stepActions s0)\n            (filter\n               (fun e : event_definition =>\n                match eventKind e with\n                | Internal => true\n                | Imported => false\n                | Exported => true\n                end) (events M))).\ndestruct v0. inversion H;subst. simpl;auto. \n\nrepeat(inversion H). inversion H. inversion H. inversion H. inversion H. inversion H. \nQed.\n\nLemma termL23:  forall M (conf conf' : configuration M) e lst scs,\n    constructConfigList scs e conf = Result lst /\\\n    In conf' lst -> exists sce, In sce scs /\\ (finishedscenarios conf' = sce::nil).\nProof. intros.   apply termL2 in H. destruct H. exists x. destruct H.   split.  Focus 2. \n\n       apply termL3 with (e:=e) (conf:=conf);auto.\n apply filter_In in H.    destruct H.    \n apply filterL2 in H.  auto.  \nQed.\n\n(*Lemma 1*)\nLemma termL4: forall M (conf conf' : configuration M) e, synchrony conf conf' e ->\nList.length (finishedscenarios conf) < List.length (finishedscenarios conf').\nProof. \nintros.  \nrepeat match goal with\n            | [|- forall _,_]  => progress intros\n            | [ |-  _  /\\  _  ] =>  split\n            | [ H: synchrony _ _ _ |- _ ] => unfold synchrony in H\n\n            | [ H: _ /\\ _ |- _ ] => destruct H\n            | _ => unfold equivConf\nend.    \nunfold combineFunc in H0.  \nremember (constructConfigList (dom (controlstate conf)) e conf).\ndestruct e0;inversion H0.    destruct v;inversion H0. clear H2.\nclear H0.\ndestruct v.\n\nremember (mergeConfigFunc' conf conf c).\ndestruct e0;inversion H3.\nunfold removeEventFromConf. simpl.\nunfold mergeConfigFunc' in Heqe1. \ndestruct (mergeDataStateFunc (datastate conf) (datastate conf) (datastate c) ).\ndestruct (mergeControlStateFunc (controlstate conf) (controlstate conf)\n                                (controlstate c)).\ninversion Heqe1. simpl.\nrewrite app_length.\npose proof termL23.\nassert (exists sce : scenario, In sce (dom (controlstate conf)) /\\ finishedscenarios c = sce :: nil).\neapply H0;auto. split. symmetry. apply Heqe0. left;auto.\ndestruct H4. destruct H4. rewrite H5;simpl. \nomega.   \ninversion Heqe1. inversion Heqe1. \nremember (innerCombineFunc'''' conf (c0 :: v)).\ndestruct o;inversion H3.\n\nremember (mergeConfigFunc' conf c c1).\ndestruct e0;inversion H1.\nunfold removeEventFromConf. simpl.\nunfold mergeConfigFunc' in Heqe1.\ndestruct (mergeDataStateFunc (datastate conf) (datastate c) (datastate c1));inversion Heqe1. clear H4.\ndestruct ( mergeControlStateFunc (controlstate conf) (controlstate c) (controlstate c1));inversion Heqe1. simpl.  rewrite app_length.\nassert (Datatypes.length (finishedscenarios conf) <=\n        Datatypes.length (finishedscenarios c1)).\npose proof  termL41'.\napply H0 with (v:=(c0::v));auto. \npose proof termL23.\nassert (exists sce : scenario, In sce (dom (controlstate conf)) /\\ finishedscenarios c = sce :: nil).\neapply H5;auto. split. symmetry. apply Heqe0. left;auto.\ndestruct H6. destruct H6. rewrite H7.\nsimpl. omega.\n(*remember (innerCombineFunc'''' conf v).\ndestruct o;inversion H3.\nremember (mergeConfigFunc' conf c0 c).\ndestruct e0;inversion H1.\nunfold removeEventFromConf. simpl.\nunfold mergeConfigFunc' in Heqe1.\ndestruct (mergeDataStateFunc (datastate conf) (datastate c0) (datastate c));inversion Heqe1. clear H4.\ndestruct ( mergeControlStateFunc (controlstate conf) (controlstate c0) (controlstate c));inversion Heqe1. simpl.  rewrite app_length.\nassert (Datatypes.length (finishedscenarios conf) <=\n        Datatypes.length (finishedscenarios c0)).\npose proof  termL41'.\napply H0 with (v:=v);auto. \npose proof termL23.\nassert (exists sce : scenario, In sce (dom (controlstate conf)) /\\ finishedscenarios c = sce :: nil).\neapply H5;auto. split. symmetry. apply Heqe0. left;auto.\ndestruct H6. destruct H6. rewrite H7.\nsimpl. omega.\n\nremember (mergeConfigFunc' conf conf c).\ndestruct e0;inversion H1.\nunfold removeEventFromConf. simpl.\nunfold mergeConfigFunc' in Heqe1. \ndestruct (mergeDataStateFunc (datastate conf) (datastate conf) (datastate c) ).\ndestruct (mergeControlStateFunc (controlstate conf) (controlstate conf)\n                                (controlstate c)).\ninversion Heqe1. simpl.\nrewrite app_length.\npose proof termL23.\nassert (exists sce : scenario, In sce (dom (controlstate conf)) /\\ finishedscenarios c = sce :: nil).\neapply H0;auto. split. symmetry. apply Heqe0. left;auto.\ndestruct H5. destruct H5. rewrite H6;simpl. \nomega.   \ninversion Heqe1. inversion Heqe1. *)\nQed.\n\n(*aux lemma for proving termination*)\nLemma sceInclusion: forall M (conf : configuration M), uniqList (dom (controlstate conf)) -> uniqList  (finishedscenarios conf)\n-> scenarioInclusion conf-> \n List.length (dom (controlstate conf)) >= List.length ( (finishedscenarios conf)).\nProof. intros.  apply listInclusion. split. auto. split. auto. unfold scenarioInclusion in H1.  auto.\nQed.\n\nLemma LL1': forall M (conf conf' : configuration M) sce re,\n    constructConfig sce re conf = Result (conf') ->\n    dom (controlstate conf) = (dom (controlstate conf'))\n      /\\  (finishedscenarios conf' = sce::nil).\nProof. intros.\nsplit.  Focus 2.    apply termL3 with (e:=re) (conf:=conf). symmetry. auto.\nunfold constructConfig in H.\ndestruct (getScenarioState sce (controlstate conf)).\ndestruct (transEvMapFunc (stateEvDefInstanceMap M) (Some s, Some (eventDefinition re))). \ndestruct (findEventInstance re (datastate conf) l).\ndestruct (createValueEnv (eventArgs e) (eventParams (eventDefinition re)) (eventArguments re)).\ndestruct (getStep' conf sce e ).\n unfold configTransition in H.  \ndestruct (execAction (extendValEnv (datastate conf) v, nil) (stepActions s0)\n            (filter\n               (fun e : event_definition =>\n                match eventKind e with\n                | Internal => true\n                | Imported => false\n                | Exported => true\n                end) (events M))).\ndestruct v0. inversion H;simpl. \nunfold updateControlState. \nassert (forall s1, dom s1 = dom (updateScenarioState' sce (pro_state s0) s1)).\nintros. induction s1. simpl.\n\nsimpl. auto.\n  destruct a. simpl. \ndestruct ( string_dec (scenarioId s2) (scenarioId sce)). simpl.  f_equal. auto. simpl. f_equal. auto.\napply H0. \ninversion H. inversion H. inversion H. inversion H. inversion H.  inversion H. \nQed. \n\n\nLemma domControlSyncL1: forall M (conf conf' : configuration M) e sce,\n    In sce (dom (controlstate conf))\n      -> correct_configuration conf\n      -> Result conf' = constructConfig sce e conf\n      -> (dom (controlstate conf)) = (dom (controlstate conf')).\nProof. intros. \nSearchAbout constructConfig.\nsymmetry in H1. apply LL1' in H1. destruct H1.\nauto.\nQed.\n\nLemma mergeControlInvariant: forall cso cs1 cs2 cs3, (dom cso = dom cs1) -> (dom cs1 = dom cs2) \n-> (Result cs3 = mergeControlStateFunc cso cs1 cs2)-> (dom cso) = (dom cs3).\nProof. intros. generalize dependent cso. generalize dependent cs1. generalize dependent cs2. \ninduction (cs3). intros. \n\ndestruct (cso). auto. destruct cs1.  inversion H. destruct cs2. inversion H0. simpl in H1.\ndestruct p;destruct p0;destruct p1.    destruct (scenario_dec s s1).  destruct (scenario_dec s s3).  subst. \ndestruct (mergeControlStateFunc l cs1 cs2). subst.\ndestruct (string_dec s2 s4). inversion H1.\ndestruct (string_dec s2 s0). inversion H1.\ndestruct (string_dec s4 s0). inversion  H1. \ninversion H1. inversion H1. inversion H1.  inversion H1.  \n \nintros.\ndestruct cso;destruct cs1;destruct cs2. simpl in H1. inversion H1.\nsimpl in H1. inversion H1. simpl in H1. inversion H1.\nsimpl in H1. inversion H1. \ninversion H. inversion H.\ninversion H0.\nsimpl in H1.  destruct p; destruct p0; destruct p1.\nsimpl in H0. simpl in H. inversion H0;subst. inversion H;subst. \ndestruct (scenario_dec s3 s3).     \n remember (mergeControlStateFunc cso cs1 cs2). \n destruct (e0).   destruct (string_dec s2 s4). subst. inversion H1;auto. \n subst. simpl. f_equal.\napply IHl with (cs2:=cs2) (cs1:=cs1);auto.  \n\ndestruct (string_dec s2 s0).  subst.  inversion H1.  simpl. f_equal.  \nsubst.  apply IHl with (cs2:=cs2) (cs1:=cs1);auto.\n\ndestruct (string_dec s4 s0).  \ninversion H1.    subst. simpl. f_equal.\napply IHl with (cs2:=cs2) (cs1:=cs1);auto.  \n\ninversion H1. inversion H1. inversion H1.     \nQed.\n\nLemma mergeControlSceInvariant: forall cso cs1 cs2 cs3 sce, In sce (dom cso) -> (dom cso = dom cs1) -> (dom cs1 = dom cs2)\n-> Result cs3 = mergeControlStateFunc cso cs1 cs2 -> getScenarioState sce (cs1) = getScenarioState sce (cs2) -> \n getScenarioState sce (cs1) = getScenarioState sce (cso)\n-> getScenarioState sce (cso) = getScenarioState sce (cs3).\nProof. intro cso. induction cso.\n- intros. inversion H.\n- intros. simpl in H. destruct H. \n\n+ simpl. destruct a.   destruct (string_dec (scenarioId sce) (scenarioId s)). \n* simpl in H2. destruct cs1. inversion H2. destruct cs2.  inversion H1.  inversion H1. subst.\ninversion H0;subst. simpl. destruct p;destruct p0.  destruct (scenario_dec (fst (s, s1))).\nsimpl. simpl in H3.  destruct (string_dec (scenarioId s) (scenarioId s)). inversion H0.       \ndestruct (scenario_dec (fst (s, s1)) s2).  inversion e2.\ndestruct (mergeControlStateFunc cso cs1 cs2).    \ndestruct (string_dec s1 s3). inversion H2. simpl.  \ndestruct (string_dec (scenarioId s) (scenarioId s)).  simpl in H4.\ndestruct (string_dec (scenarioId s) (scenarioId s)). symmetry;auto.\nexfalso;apply n. auto.  exfalso;apply n. auto.  simpl in H4.  \ndestruct (string_dec s1 s0). inversion H2. simpl.   \ndestruct (string_dec (scenarioId s) (scenarioId s)). \ndestruct (string_dec (scenarioId s) (scenarioId s2)). rewrite e3 in H3. auto.\nrewrite <- e2 in n0. simpl in n0. exfalso;apply n0;auto.\nexfalso;apply n0;auto. \ndestruct (string_dec s3 s0).  \ninversion H2. simpl.        \ndestruct ( string_dec (scenarioId s) (scenarioId s)).  symmetry;auto.\n exfalso;apply n1;auto. inversion H2. inversion H2. inversion H2.    exfalso;apply n;auto. inversion H2. \n* \nrewrite <- H in n. simpl in n. exfalso;apply n;auto.\n+ simpl.  destruct a.     destruct (string_dec (scenarioId sce) (scenarioId s)). \n*\nsimpl in H2. destruct cs1. inversion H2. destruct cs2.  inversion H1.  inversion H1. subst.\ninversion H0;subst. simpl. destruct p;destruct p0.  destruct (scenario_dec (fst (s, s1))).\nsimpl. simpl in H3.  \ndestruct (scenario_dec (fst (s, s1)) s2).  \ndestruct (mergeControlStateFunc cso cs1 cs2).    \ndestruct (string_dec s1 s3). inversion H2. simpl.  \n simpl in H4.\ndestruct (string_dec (scenarioId sce) (scenarioId s)).  symmetry;auto.\nexfalso;apply n. auto.   simpl in H4.\ndestruct (string_dec s1 s0). inversion H2 . simpl. \ndestruct (string_dec (scenarioId sce) (scenarioId s)).  rewrite e0 in e1. \ndestruct (string_dec (scenarioId sce) (scenarioId s2)). rewrite e2 in H3. auto.\nrewrite <- e1 in n0.   exfalso;apply n0. auto. exfalso;apply n0. auto. \ndestruct (string_dec (scenarioId sce) (scenarioId s)).\ndestruct (string_dec s3 s0). \n inversion H2. simpl. \nrewrite e2. \ndestruct (string_dec (scenarioId s) (scenarioId s)). symmetry. auto.  \nexfalso;apply n1.  auto. inversion H2.\ndestruct (string_dec s3 s0). inversion H2. simpl.\ndestruct (string_dec (scenarioId sce) (scenarioId s)).\nexfalso;apply n1;auto. simpl in e. exfalso;apply n2;auto. inversion H2. inversion H2. inversion H2.\ninversion H2.       \n  \n\n* simpl in H4.   destruct (string_dec (scenarioId sce) (scenarioId s)).\nrewrite e in n.   exfalso;apply n;auto. \nsimpl in H2. \n\ndestruct cs1. inversion H2. destruct cs2.  inversion H1.  inversion H1. subst.\ninversion H0;subst. simpl. destruct p;destruct p0.  destruct (scenario_dec (fst (s, s1)) s).\nsimpl. simpl in H3.  \ndestruct (scenario_dec (fst (s, s1)) s2). Focus 2. inversion H2. Focus 2. inversion H2.    \nremember (mergeControlStateFunc cso cs1 cs2).\ndestruct e1.   \ndestruct (string_dec s1 s3). Focus 3. inversion H2.      inversion H2. simpl.  \n simpl in H4.\ndestruct (string_dec (scenarioId sce) (scenarioId s)). \nexfalso;apply n. auto.  destruct (string_dec (scenarioId sce) (scenarioId s2) ).\n  rewrite e in e0. rewrite <- e0 in e2. exfalso;apply n0.  auto.\napply IHcso with (cs1:=cs1) (cs2:=cs2). auto. auto. auto. auto. auto. auto. \nsimpl in H4.  \ndestruct (string_dec s1 s0). inversion H2. simpl.\ndestruct (string_dec (scenarioId sce) (scenarioId s)).  exfalso;apply n0.  auto.\n destruct (string_dec (scenarioId sce) (scenarioId s2) ).\n  rewrite e in e0. rewrite <- e0 in e2. exfalso;apply n0.  auto.\napply IHcso with (cs1:=cs1) (cs2:=cs2). auto. auto. auto. auto. auto. auto.\ndestruct (string_dec s3 s0). \n     destruct (string_dec (scenarioId sce) (scenarioId s)). exfalso;apply n0.  auto.\n destruct (string_dec (scenarioId sce) (scenarioId s2) ). simpl in H6.\nrewrite H6 in n3. \n   exfalso;apply n3.  auto. \ninversion H2. simpl. \ndestruct (string_dec (scenarioId sce) (scenarioId s)).   exfalso;apply n0.  auto. \napply IHcso with (cs1:=cs1) (cs2:=cs2). auto. auto. auto. auto. auto. auto. inversion H2. \n  \n\nQed. \n   \nLemma mergeControlSceInvariant': forall M (config config1 config2 config3 : configuration M)\n sce, dom (controlstate config) = dom (controlstate config1) ->\ndom (controlstate config1) = dom (controlstate config2)->\nIn sce (dom (controlstate config)) ->\n Result config3 = mergeConfigFunc config config1 config2\n-> getScenarioState sce ( (controlstate config1)) = getScenarioState sce ( (controlstate config2)) \n-> getScenarioState sce (( (controlstate config1))) = getScenarioState sce (( (controlstate config)))\n-> getScenarioState sce ( (controlstate config)) = getScenarioState sce ( (controlstate config3)).\nProof. intros. \nunfold mergeConfigFunc in H2.\ndestruct (mergeDataStateFunc (datastate config) (datastate config1) (datastate config2) ).\nremember (mergeControlStateFunc (controlstate config) (controlstate config1) (controlstate config2)).\ndestruct e.  \ninversion H2;subst. simpl.    \napply mergeControlSceInvariant with (cs1:=controlstate config1) (cs2:=controlstate config2);auto.\n\ninversion H2. inversion H2.\nQed. \n\nLemma domMergeConfig1: forall v v1 v2,  (exists v3, Result (v3) = \nmergeControlStateFunc (v) (v1) (v2)) ->\n dom v = dom v1.\nProof.  \nPrint mergeControlStateFunc. intro v. \ninduction v.\nintros. destruct H.  destruct v1. auto.\nsimpl in H. \ninversion H.\nintros. destruct H. destruct v1. simpl in H.  destruct a. inversion H.\ndestruct v2. simpl in H. destruct a;destruct p. inversion H. \nsimpl in H.  \n destruct a. destruct p.  destruct p0. \ndestruct (scenario_dec s s1). \ndestruct (scenario_dec s s3). subst.\nremember (mergeControlStateFunc v v1 v2).\ndestruct e. simpl. f_equal.\napply IHv with (v2:=v2);auto.\nexists v0;auto. \ninversion H. inversion H.  inversion H.             \nQed. \n\nLemma domMergeConfig2: forall v v1 v2,  (exists v3, Result (v3) = \nmergeControlStateFunc (v) (v1) (v2)) ->\n dom v = dom v2.\nProof.  \nPrint mergeControlStateFunc. intro v. \ninduction v.\nintros. destruct H.  destruct v1. destruct v2.  auto.\nsimpl in H. \ninversion H.\nintros. simpl in H.  inversion H.\nintros. \ndestruct H. destruct v1. simpl in H.  destruct a. inversion H.\ndestruct v2. simpl in H. destruct a;destruct p. inversion H. \nsimpl in H.  \n destruct a. destruct p.  destruct p0. \ndestruct (scenario_dec s s1). \ndestruct (scenario_dec s s3). subst.\nremember (mergeControlStateFunc v v1 v2).\ndestruct e. simpl. subst. f_equal.\napply IHv with (v1:=v1);auto.\nexists v0;auto. \ninversion H. inversion H.  inversion H.             \nQed.\n\n\nLemma domMergeConfig: forall v v1 v2,  (exists v3, Result (v3) = \nmergeControlStateFunc (v) (v1) (v2)) ->\n dom v = dom v1 /\\ dom v = dom v2.\nProof. intros. split. apply domMergeConfig1 with v2. auto.\n     apply domMergeConfig2 with v1. auto.\nQed. \n\nLemma mergeConfigFuncCSNoChange: forall M (conf conf1 conf2 : configuration M) v,\n    Result v = mergeConfigFunc' conf conf1 conf2 ->\n    dom (controlstate conf) = dom (controlstate v). \nProof.\n  intros.\n  unfold mergeConfigFunc' in H.\n  remember ( mergeDataStateFunc (datastate conf) (datastate conf1) (datastate conf2)).\n  destruct e;inversion H.\n  remember (  mergeControlStateFunc (controlstate conf) (controlstate conf1)\n                                    (controlstate conf2)).\n  destruct e;inversion H;auto. simpl.\n  pose proof domMergeConfig.\n  assert (dom (controlstate conf) = dom (controlstate conf1) /\\ dom (controlstate conf) = dom (controlstate conf2)).\n  apply H0. exists v1;auto.\n  destruct H3. \n  \n  pose proof mergeControlInvariant.\n  apply H5 with (cs1:=(controlstate conf1)) (cs2:=(controlstate conf2));auto.\n  rewrite H3 in H4;auto. \nQed.\n\nLemma domMerge: forall  originconf conf' conf'',  (exists rconf,  Result (rconf) = mergeControlStateFunc originconf conf' conf'')\n-> (dom ( originconf)) = (dom ( conf')) /\\ (dom ( originconf)) = (dom ( conf'')).\nProof.   intros. apply domMergeConfig. auto. \nQed.\n\nLemma domMerge': forall M (originconf conf' conf'' : configuration M),  (exists rconf,  Result (rconf) = mergeConfigFunc' originconf conf' conf'')\n-> (dom (controlstate originconf)) = (dom (controlstate conf')) /\\ (dom (controlstate originconf)) = (dom (controlstate conf'')).\nProof.   intros. destruct H. unfold mergeConfigFunc' in H.\ndestruct (mergeDataStateFunc (datastate originconf) (datastate conf') (datastate conf'') ).\nFocus 2. inversion H.\nremember (mergeControlStateFunc (controlstate originconf) (controlstate conf') (controlstate conf'')).\ndestruct e. \napply    domMerge. exists v0. auto. inversion H.      \nQed.\n\nLemma appInclu\n     : forall (A : Type) (l1 l2 l : list A),\n    incl l1 l -> incl l2 l -> incl ( l1 ++ l2 ) l.\nProof. intros A l1;induction l1. \n-intros. simpl;auto.  \n- intros. simpl.   unfold incl.\n  intros. destruct H1. subst. unfold incl in H. apply H;auto. left;auto.\n  apply in_app_iff in H1. destruct H1.\n  unfold incl in H. apply H. right;auto. \n \n  unfold incl in H0. apply H0. auto.\nQed.   \n\nLemma incluSyncL1: forall M (conf conf' : configuration M) sce e,   In sce (dom (controlstate conf)) -> correct_configuration conf  -> Result conf' = constructConfig sce e conf  -> \nscenarioInclusion conf'.\nProof. intros. destruct H0.  unfold scenarioInclusion. unfold scenarioInclusion in inclusion.\n       symmetry in H1. apply LL1' in H1. destruct H1. rewrite H1.    apply inclInvariant.\n    unfold incl. intros. destruct H2. rewrite <- H0;auto. unfold not. intros. inversion H2.\nQed.\n\n\n(*aux lemma for proving incluSyncL4*)\nLemma incluSyncL2: forall M (rconf originconf conf' conf'' : configuration M),   Result (rconf) = mergeConfigFunc' originconf conf' conf''\n/\\ scenarioInclusion originconf /\\ scenarioInclusion conf' /\\ scenarioInclusion conf'' -> scenarioInclusion rconf.\n\nProof.  intros. destruct H. remember H. clear Heqe.    \napply mergeConfigFuncCSNoChange in H. assert ( (dom (controlstate originconf)) = (dom (controlstate conf')) /\\ (dom (controlstate originconf)) = (dom (controlstate conf''))). \n apply domMerge'. exists rconf. auto.     \n \nrepeat match goal with\n            | [ H: _ /\\ _ |- _ ] => destruct H\n            end.\n\nunfold  scenarioInclusion.\nrewrite <- H.     \nunfold mergeConfigFunc' in e. \ndestruct ( mergeDataStateFunc (datastate originconf)\n        (datastate conf') (datastate conf'')).\nremember (mergeControlStateFunc (controlstate originconf) (controlstate conf') (controlstate conf'')). \ndestruct e0;inversion e;auto.  simpl. \ndestruct (mergeControlStateFunc (controlstate originconf) (controlstate conf') (controlstate conf'')).\nFocus 2. inversion Heqe0. Focus 2.   inversion e.\n\ndestruct (mergeList' (raisedevents conf') (raisedevents conf'') raisedEvent_dec). \ndestruct (mergeList' (exportedevents conf') (exportedevents conf'') raisedEvent_dec).\ninversion e. simpl.\nCheck mergeInclu.\nSearchAbout incl. \napply appInclu;auto. unfold scenarioInclusion in H3. rewrite H1;auto.  rewrite H2;auto.\napply appInclu;auto. unfold scenarioInclusion in H3. rewrite H1;auto.  rewrite H2;auto.\napply appInclu;auto. unfold scenarioInclusion in H3. rewrite H1;auto.  rewrite H2;auto.\n\n\nQed.  \n\n\n(*aux lemma for proving incluSync*)\nLemma incluSyncL4: forall M v (conf : configuration M) e  w,\n    correct_configuration conf\n      -> (forall conf', In conf' v\n            -> (exists sce,\n                   In sce (dom (controlstate conf))\n                     /\\  Result (conf')=  constructConfig sce e conf))\n      -> Some (w) =  innerCombineFunc'''' conf v\n      -> scenarioInclusion w.\nProof.\nintros ? v. induction v.\n- intros. simpl in H1. inversion H1.\n- intros. simpl in H1.\n  destruct v. \n remember (mergeConfigFunc' conf conf a).\n  destruct e0;inversion H1;auto. subst.\n  pose proof incluSyncL2.\n  apply incluSyncL2 with (originconf:=conf) (conf':=conf) (conf'':=a);auto. split;auto.\n  split. destruct H;auto. split.  destruct H;auto.\ndestruct H0 with a. left;auto. \ndestruct H3.   \napply incluSyncL1 with (e:=e) (conf:=conf) (sce:=x);auto.\nremember (innerCombineFunc'''' conf (c :: v)).\ndestruct o;inversion H1. clear H3.  \nremember (mergeConfigFunc' conf a c0).\ndestruct e0;inversion H1. subst.\napply IHv with (e:=e) in Heqo;auto.\nFocus 2. \nintros.\napply H0. right;auto.\n pose proof incluSyncL2.\n  apply incluSyncL2 with (originconf:=conf) (conf':=a) (conf'':=c0);auto. split;auto.\n  split. destruct H;auto. split.  destruct H0 with a;auto.\nleft;auto. destruct H3.   \napply incluSyncL1 with (e:=e) (conf:=conf) (sce:=x);auto.\nauto. \n(*remember (innerCombineFunc'''' conf v). destruct o;inversion H1;auto. remember (mergeConfigFunc' conf c a). destruct e0;inversion H1;auto;subst. \n  simpl in H0. destruct H0 with a. left. auto. destruct H2.\n  SearchAbout mergeConfigFunc'.\n  pose proof incluSyncL2.\n  apply incluSyncL2 with (originconf:=conf) (conf':=c) (conf'':=a);auto. split;auto.\n  split. destruct H;auto. split.\n  \n  apply IHv with (e:=e) in Heqo;auto.\n  apply incluSyncL1 with (e:=e) (conf:=conf) (sce:=x);auto.\n  remember (mergeConfigFunc' conf conf a).\n  destruct e0;inversion H1;auto. subst.\n  pose proof incluSyncL2.\n  apply incluSyncL2 with (originconf:=conf) (conf':=conf) (conf'':=a);auto. split;auto.\n  split. destruct H;auto. split.  destruct H;auto.\ndestruct H0 with a. left;auto. \ndestruct H4.   \n  apply incluSyncL1 with (e:=e) (conf:=conf) (sce:=x);auto.\n*)\nQed. \n  \n(*aux lemma for proving termL5*)\nLemma incluSync: forall M (conf conf' : configuration M) e,  correct_configuration conf -> synchrony conf conf' e -> scenarioInclusion conf'.\nProof. intros.   \nunfold synchrony in H0. \n   repeat match goal with\n            | [ H: _ /\\ _ |- _ ] => destruct H\n\n            end.\n\nunfold combineFunc in H1.\n\nremember (constructConfigList (dom (controlstate conf)) e conf).\ndestruct e0. destruct v. inversion H1.\n\nFocus 2. inversion H1. remember (innerCombineFunc'''' conf (c :: v)).\ndestruct o;inversion H1.  unfold removeEventFromConf. unfold scenarioInclusion.\nsimpl. pose proof incluSyncL4.\nassert (scenarioInclusion c0).\napply H2 with (v:=(c::v)) (conf:=conf) (e:=e);auto. intros.\npose proof termL2.\nunfold constructConfigList in Heqe0.\nassert (exists sce : scenario,\n    In sce (filter\n               (fun x : scenario =>\n                inList event_definition_dec (eventDefinition e) (alphabet x))\n               (filterList (finishedscenarios conf) (dom (controlstate conf))\n                  scenario_dec)) /\\ Result conf'0 = constructConfig sce e conf). \napply H5 with (lst:=c::v);auto.\ndestruct H6. destruct H6. exists x. split;auto. apply filter_In in H6.\ndestruct H6. apply filterL2 in H6;auto.\nunfold scenarioInclusion in H4. auto. \nQed.\n\n\n\nLemma uniqSyncL1: forall M (conf conf' : configuration M) e sce,   In sce (dom (controlstate conf)) -> correct_configuration conf  -> Result conf' = constructConfig sce e conf  -> \nuniqList (dom (controlstate conf')) \n/\\ uniqList (finishedscenarios conf').\nProof.  intros. assert (dom (controlstate conf) = dom (controlstate conf')).\nsymmetry in H1. apply LL1' in H1. destruct H1. auto. \ndestruct H0. split. rewrite <- H2. auto.\nsymmetry in H1. apply LL1' in H1. \ndestruct H1. rewrite H1.  constructor. constructor. unfold not. intros. inversion H3. \nQed.    \n           \n  \n  \nLemma uniqSyncL2: forall M (rconf originconf conf' conf'' : configuration M), correct_configuration originconf\n-> uniqList (dom (controlstate conf')) \n-> uniqList (finishedscenarios conf') \n-> uniqList (dom (controlstate conf'')) \n-> uniqList (finishedscenarios conf'') \n->  Result (rconf) = mergeConfigFunc' originconf conf' conf'' \n-> (forall i : scenario, In i (finishedscenarios conf') -> ~ In i (finishedscenarios conf''))\n-> (forall i : scenario, In i (finishedscenarios conf'') -> ~ In i (finishedscenarios conf'))\n-> uniqList (dom (controlstate rconf)) \n/\\ uniqList (finishedscenarios rconf).\nProof. intros.\nsplit.\n- assert ( dom (controlstate originconf) = dom (controlstate conf') /\\\n       dom (controlstate originconf) = dom (controlstate conf'')). \napply     domMerge'. exists rconf. auto. \n\nassert ((dom (controlstate rconf) = (dom (controlstate conf')))).\ndestruct H7.\n\napply mergeConfigFuncCSNoChange in H4;auto. rewrite H4 in H7;auto.\ndestruct H7. rewrite H8;auto. \n\n- unfold mergeConfigFunc' in H4.           \ndestruct (mergeDataStateFunc (datastate originconf) (datastate conf') (datastate conf'')).\ndestruct (mergeControlStateFunc (controlstate originconf) (controlstate conf') (controlstate conf'')).\ninversion H4. simpl. \nFocus 2. inversion H4. Focus 2. inversion H4.\nclear H8. \nSearchAbout uniqList.\napply uniqApp';auto. \nQed.   \n\nLemma finishedscenarioIn: forall lst e M (conf : configuration M) v i c,\n    uniqList lst ->\n    incl lst (dom (controlstate conf)) ->\n    Result v = constructConfigList' lst e conf ->\n    Some c = innerCombineFunc'''' conf v ->\n    In i (finishedscenarios c) ->\n    ~ In i (finishedscenarios conf) ->\n    In i lst. \nProof. intro lst;induction lst. \n       - intros. simpl in H1. inversion H1;subst. simpl in H2.  inversion H2.\n       - intros. simpl in H1.\n         remember (constructConfig a e conf).\n         destruct e0;inversion H1. clear H6.\n         remember (constructConfigList' lst e conf).\n         destruct e0;inversion H1. subst.\n         clear H1.\n         simpl in H2.\n         destruct v1.\n           remember (mergeConfigFunc' conf conf v0).\n         destruct e0;inversion H2. subst.\n\n          unfold mergeConfigFunc' in Heqe2.\n         destruct (mergeDataStateFunc (datastate conf) (datastate conf) (datastate v0));inversion Heqe2. destruct (mergeControlStateFunc (controlstate conf) (controlstate conf) (controlstate v0));inversion H2;subst. inversion H5. rewrite H6 in H3. simpl in H3. clear H5.\n         clear H6. clear H2. \n         apply in_app_iff in H3. destruct H3.\n         contradiction.\n         apply termL3 in Heqe0. rewrite Heqe0 in H1. destruct H1. subst. left;auto.\n         inversion H1. \n         inversion H5.\n         remember (innerCombineFunc'''' conf (c0 :: v1)).\n         destruct o;inversion H2;subst.\n         clear H5.\n         remember (mergeConfigFunc' conf v0 c1).\n         destruct e0;inversion H2. subst. clear H2.\n         unfold mergeConfigFunc' in Heqe2.\n         destruct (mergeDataStateFunc (datastate conf) (datastate v0) (datastate c1));inversion Heqe2. destruct (mergeControlStateFunc (controlstate conf) (controlstate v0) (controlstate c1));inversion H2;subst. simpl in H3. clear Heqe2.\n         clear H2.\n         apply in_app_iff in H3. destruct H3.\n         Focus 2. \n         apply IHlst with (e:=e) (i:=i) in Heqo;auto.\n         Focus 2. inversion H;auto. Focus 2.\n         unfold incl. unfold  incl in H0. \n         intros.    apply H0;auto. right;auto.\n         right;auto.\n         apply termL3 in Heqe0. rewrite Heqe0 in H1. destruct H1. subst. left;auto.\n         inversion H1.\n         (*remember (innerCombineFunc'''' conf v1).\n         destruct o;inversion H2;subst. clear H5.\n         remember (mergeConfigFunc' conf c0 v0).\n         destruct e0;inversion H2. subst. clear H2.\n         unfold mergeConfigFunc' in Heqe2.\n         destruct (mergeDataStateFunc (datastate conf) (datastate c0) (datastate v0));inversion Heqe2. destruct (mergeControlStateFunc (controlstate conf) (controlstate c0) (controlstate v0));inversion H2;subst. simpl in H3. clear Heqe2.\n         clear H2.\n         apply in_app_iff in H3. destruct H3.\n         apply IHlst with (e:=e) (i:=i) in Heqo;auto.\n         Focus 2. inversion H;auto. Focus 2.\n         unfold incl. unfold  incl in H0. \n         intros.    apply H0;auto. right;auto.\n         right;auto.\n         apply termL3 in Heqe0. rewrite Heqe0 in H1. destruct H1. subst. left;auto.\n         inversion H1.\n         clear H5.\n         remember (mergeConfigFunc' conf conf v0).\n         destruct e0;inversion H2. subst.\n\n          unfold mergeConfigFunc' in Heqe2.\n         destruct (mergeDataStateFunc (datastate conf) (datastate conf) (datastate v0));inversion Heqe2. destruct (mergeControlStateFunc (controlstate conf) (controlstate conf) (controlstate v0));inversion H2;subst. inversion H5. rewrite H6 in H3. simpl in H3. clear H5.\n         clear H6. clear H2. \n         apply in_app_iff in H3. destruct H3.\n         contradiction.\n         apply termL3 in Heqe0. rewrite Heqe0 in H1. destruct H1. subst. left;auto.\n         inversion H1. \n      inversion H5. *)\nQed.\n\nLemma termL2': forall scs M (conf : configuration M) e lst  sce, constructConfigList' scs e conf = Result lst ->\n In sce scs -> exists conf', Result conf' = constructConfig sce e conf.\nProof.  intro lst. induction lst.\n- intros. inversion H0.\n- intros. destruct H0. simpl in H. \nremember (constructConfig a e conf). destruct e0.\n \nremember (constructConfigList' lst e conf).\n\ndestruct e0. subst. exists v;auto. inversion H. inversion H. \nsimpl in H.\nremember ( constructConfig a e conf ).\ndestruct e0;inversion H. clear H2. \nremember (constructConfigList' lst e conf ).\ndestruct e0;inversion H. subst. \n\n\nsymmetry in Heqe1. apply IHlst  with (sce:=sce) in Heqe1 ;auto.\n     \nQed.\n\n\nLemma finishedscenarioInAll: forall lst e M (conf : configuration M) v i c,\n    uniqList lst ->\n    incl lst (dom (controlstate conf)) ->\n    Result v = constructConfigList' lst e conf ->\n    Some c = innerCombineFunc'''' conf v ->\n     In i (finishedscenarios c) ->\n    (In i lst \\/ In i (finishedscenarios conf)). \nProof. intro lst;induction lst. \n       - intros. simpl in H1. inversion H1;subst. simpl in H2.  inversion H2.\n       - intros. simpl in H1.\n         remember (constructConfig a e conf).\n         destruct e0;inversion H1. clear H5.\n         remember (constructConfigList' lst e conf).\n         destruct e0;inversion H1. subst.\n         clear H1.\n         simpl in H2.\n         \n         destruct v1.\n         remember (mergeConfigFunc' conf conf v0).\n         destruct e0;inversion H2. subst.\n         unfold mergeConfigFunc' in Heqe2.\n         destruct (mergeDataStateFunc (datastate conf) (datastate conf) (datastate v0));inversion Heqe2. destruct (mergeControlStateFunc (controlstate conf) (controlstate conf) (controlstate v0));inversion H2;subst. inversion H4. rewrite H5 in H3;simpl in H3.  clear Heqe2.\n         clear H4. clear H5.  clear H2. \n         \n         apply in_app_iff in H3. destruct H3.\n         right;auto.\n         SearchAbout finishedscenarios.\n         apply termL3 in Heqe0. rewrite Heqe0 in H1. destruct H1. subst. left;left;auto. \ninversion H1.          inversion H4. \n         remember (innerCombineFunc'''' conf (c0 :: v1)). \n           destruct o;inversion H2;subst. clear H4.\n         remember (mergeConfigFunc' conf v0 c1).\n         destruct e0;inversion H2. subst. clear H2.\n         unfold mergeConfigFunc' in Heqe2.\n         destruct (mergeDataStateFunc (datastate conf) (datastate v0) (datastate c1));inversion Heqe2. destruct (mergeControlStateFunc (controlstate conf) (controlstate v0) (controlstate c1));inversion H2;subst. simpl in H3. clear Heqe2.\n         clear H2.\n         apply in_app_iff in H3. destruct H3.\n         Focus 2. \n          apply IHlst with (e:=e) (i:=i) in Heqo;auto.\n          \n          destruct Heqo.\n          left. right;auto. right;auto. inversion H;auto. \n           \n         unfold incl. unfold  incl in H0. \n         intros.    apply H0;auto. right;auto.\n         apply termL3 in Heqe0. rewrite Heqe0 in H1. destruct H1. subst.\n         left;auto. left;auto. inversion H1. \n         (*remember (innerCombineFunc'''' conf v1).\n         destruct o;inversion H2;subst. clear H4.\n         remember (mergeConfigFunc' conf c0 v0).\n         destruct e0;inversion H2. subst. clear H2.\n         unfold mergeConfigFunc' in Heqe2.\n         destruct (mergeDataStateFunc (datastate conf) (datastate c0) (datastate v0));inversion Heqe2. destruct (mergeControlStateFunc (controlstate conf) (controlstate c0) (controlstate v0));inversion H2;subst. simpl in H3. clear Heqe2.\n         clear H2. \n         \n         apply in_app_iff in H3. destruct H3. \n         apply IHlst with (e:=e) (i:=i) in Heqo;auto. destruct Heqo.\n         left. right;auto. right;auto. inversion H;auto. \n         \n         unfold incl. unfold  incl in H0. \n         intros.    apply H0;auto. right;auto.\n         apply termL3 in Heqe0. rewrite Heqe0 in H1. destruct H1. subst.\n         left;auto. left;auto. inversion H1. \n         clear H4. \n        \n          unfold mergeConfigFunc' in H2.\n         destruct (mergeDataStateFunc (datastate conf) (datastate conf) (datastate v0));inversion H2. destruct (mergeControlStateFunc (controlstate conf) (controlstate conf) (controlstate v0));inversion H2;subst. simpl in H3. clear H2.\n         clear H4.\n         \n         \n         apply in_app_iff in H3. destruct H3. right;auto.\n\n          apply termL3 in Heqe0. rewrite Heqe0 in H1. destruct H1. subst.\n         left;auto. left;auto. inversion H1. \nQed. *)\n\n(*(forall conf', In conf' v -> (exists sce, In sce lst /\\  Result (conf')=  constructConfig sce e conf ))\n->*)\nQed. \n         \nLemma uniqSyncL3: forall M (conf : configuration M) lst v e  w,\n    correct_configuration conf ->\n    uniqList lst ->\n    incl lst (dom (controlstate conf)) ->\n   \nResult v =\n          constructConfigList'\n            lst e\n            conf ->\n(forall sce, In sce lst -> ~ In sce (finishedscenarios conf)) ->\nSome(w) =  innerCombineFunc'''' conf v ->  uniqList (dom (controlstate w)) \n/\\ uniqList (finishedscenarios w).\nProof. \nintros ? ? lst. induction lst.\n- intros. simpl in H2. inversion H2;subst. simpl in H4. inversion H4. \n- intros. simpl in H2.\n  remember (constructConfig a e conf).\n  destruct e0;inversion H2. clear H6.\n  remember (constructConfigList' lst e conf).\n  destruct e0;inversion H2;subst. clear H2.\n  simpl in H4.\n  destruct v1.\n   remember (mergeConfigFunc' conf conf v0).\n  destruct e0;inversion H4;auto. subst.\n  split.\n  pose proof mergeConfigFuncCSNoChange. \n  rewrite <- mergeConfigFuncCSNoChange with (conf:= conf) (conf1:=conf) (conf2:=v0) (v:=v);auto. destruct H;auto.\n  unfold mergeConfigFunc' in Heqe2.\n  destruct (mergeDataStateFunc (datastate conf) (datastate conf) (datastate v0));inversion Heqe2.\n  destruct (mergeControlStateFunc (controlstate conf) (controlstate conf) (controlstate v0));inversion H5. simpl.\n  clear H6. clear H4;clear H5. clear Heqe2.\n  apply uniqApp';auto.\n  destruct H;auto.\n  apply termL3 in Heqe0. rewrite Heqe0. constructor. constructor.\n  unfold not. intros. inversion H2.\n  intros.\n  apply termL3 in Heqe0. rewrite Heqe0. unfold not. intros.\n  destruct H4;subst. Focus 2. inversion H4.\n  destruct H3 with (sce:=i);auto. left;auto.\n  intros.\n  apply H3;auto.\n  apply termL3 in Heqe0. rewrite Heqe0 in H2.\n  destruct H2. subst. left;auto. inversion H2.\n\n  remember (innerCombineFunc'''' conf (c :: v1)). \n   destruct o;inversion H4.\n  remember (mergeConfigFunc' conf v0 c0 ).\n  destruct e0;inversion H4;subst. clear H4;clear H5.\n  split.\n  pose proof mergeConfigFuncCSNoChange.\n  apply H2 in Heqe2. rewrite <- Heqe2. destruct H;auto.\n  unfold mergeConfigFunc' in Heqe2.\n  remember (mergeDataStateFunc (datastate conf) (datastate v0) (datastate c0)).\n  destruct e0;inversion Heqe2.\n  remember ( mergeControlStateFunc (controlstate conf) (controlstate v0) (controlstate c0)).\n  destruct e0;inversion H4. simpl.\n  apply uniqApp'. Focus 2. \n  apply IHlst with (e:=e) in Heqo;auto. Focus 2. inversion H0;auto.\n  Focus 2. \n\n  unfold incl. intros. unfold incl in H1. apply H1;auto. right;auto.\n  destruct Heqo;auto. intros. apply H3. right;auto. \n  apply termL3 in Heqe0;auto. rewrite Heqe0. constructor. constructor. unfold not. intros.\n  inversion H2.\n  intros.  SearchAbout finishedscenarios. apply termL3 in Heqe0. rewrite Heqe0 in H2.\n  destruct H2. subst.  Focus 2. inversion H2.\nassert ( ~ In i (finishedscenarios conf)).\n  apply H3;auto. left;auto.\n unfold not. intros.\n  pose proof finishedscenarioInAll.\n  assert (  In i lst \\/ In i (finishedscenarios conf)).\n  apply H6 with (e:=e) (v:=c::v1) (c:=c0);auto.\n  inversion H0;auto.\n  unfold incl;intros. unfold incl in H1. apply H1;auto. right;auto.\n  destruct H7. inversion H0;subst. contradiction. contradiction.\n  intros.\n  unfold not;intros. \n  apply termL3 in Heqe0.  rewrite Heqe0 in H6. destruct H6. Focus 2. \n  inversion H6.   subst.  pose proof finishedscenarioInAll. \n \n  assert (  In i lst \\/ In i (finishedscenarios conf)).\n  apply H5 with (e:=e) (v:=c::v1) (c:=c0);auto.\n  inversion H0;auto.\n  unfold incl;intros. unfold incl in H1. apply H1;auto. right;auto.\n  destruct H6. inversion H0;subst. contradiction.\n  destruct H3 with i. left;auto. auto. \n  (*\n  remember (innerCombineFunc'''' conf v1).\n  destruct o;inversion H4.\n  remember (mergeConfigFunc' conf c v0 ).\n  destruct e0;inversion H4;subst. clear H4;clear H5.\n  split.\n  pose proof mergeConfigFuncCSNoChange.\n  apply H2 in Heqe2. rewrite <- Heqe2. destruct H;auto.\n  unfold mergeConfigFunc' in Heqe2.\n  remember (mergeDataStateFunc (datastate conf) (datastate c) (datastate v0)).\n  destruct e0;inversion Heqe2.\n  remember ( mergeControlStateFunc (controlstate conf) (controlstate c) (controlstate v0)).\n  destruct e0;inversion H4. simpl.\n  apply uniqApp'.\n  apply IHlst with (e:=e) in Heqo;auto. Focus 2. inversion H0;auto.\n  Focus 2. \n\n  unfold incl. intros. unfold incl in H1. apply H1;auto. right;auto.\n  destruct Heqo;auto. intros. apply H3. right;auto. \n  apply termL3 in Heqe0;auto. rewrite Heqe0. constructor. constructor. unfold not. intros.\n  inversion H2.\n  intros.\n  remember Heqe0. clear Heqe5. \n  apply termL3 in Heqe0;auto. rewrite Heqe0.\n  unfold not. intros. destruct H6;inversion H6. subst. clear H7.\n  pose proof finishedscenarioIn. clear Heqe2. clear H4. \n  apply H5 with (i:=i) (c:=c) in Heqe1;auto. inversion H0;subst. contradiction.\n  inversion H0;auto. unfold incl. unfold incl in H1. intros.\n  apply H1;auto. right;auto. apply H3. left;auto.\n  intros. clear H5. clear H4. clear Heqe2.\n  apply termL3 in Heqe0. rewrite Heqe0 in H2. destruct H2. \n  subst.\n  assert ( ~ In i (finishedscenarios conf)).\n  apply H3;auto. left;auto.\n  unfold not. intros.\n  pose proof finishedscenarioInAll.\n  assert (  In i lst \\/ In i (finishedscenarios conf)).\n  apply H5 with (e:=e) (v:=v1) (c:=c);auto.\n  inversion H0;auto.\n  unfold incl;intros. unfold incl in H1. apply H1;auto. right;auto.\n  destruct H6. inversion H0;subst. contradiction. contradiction. inversion H2.\n  remember (mergeConfigFunc' conf conf v0).\n  destruct e0;inversion H4;auto. subst.\n  split.\n  SearchAbout (mergeConfigFunc').\n  pose proof mergeConfigFuncCSNoChange. \n  rewrite <- mergeConfigFuncCSNoChange with (conf:= conf) (conf1:=conf) (conf2:=v0) (v:=v);auto. destruct H;auto.\n  unfold mergeConfigFunc' in Heqe2.\n  destruct (mergeDataStateFunc (datastate conf) (datastate conf) (datastate v0));inversion Heqe2.\n  destruct (mergeControlStateFunc (controlstate conf) (controlstate conf) (controlstate v0));inversion H6. simpl.\n  clear H7. clear H6. clear H4;clear H5. clear Heqe2.\n  SearchAbout uniqList.\n  apply uniqApp';auto.\n  destruct H;auto.\n  apply termL3 in Heqe0. rewrite Heqe0. constructor. constructor.\n  unfold not. intros. inversion H2.\n  intros.\n  apply termL3 in Heqe0. rewrite Heqe0. unfold not. intros.\n  destruct H4;subst. Focus 2. inversion H4.\n  destruct H3 with (sce:=i);auto. left;auto.\n  intros.\n  apply H3;auto.\n  apply termL3 in Heqe0. rewrite Heqe0 in H2.\n  destruct H2. subst. left;auto. inversion H2. *)\nQed.   \n \nLemma filterUniq: forall A (l:list A) (f:A -> bool),\n    uniqList l ->\n    uniqList (@filter A f l).\nProof. intros A l;induction l.\n       - intros. simpl. constructor.\n       - intros. simpl.\n         destruct (f a).\n         inversion H;subst.\n         constructor.\n         apply IHl;auto.\n         SearchAbout filter.\n         unfold not;intros;apply H3.\n         apply filter_In in H0. destruct H0;auto.\n         apply IHl;inversion H;subst;auto. \nQed.\n\n        \n       \nLemma uniqSync: forall M (conf conf' : configuration M) e,  correct_configuration conf -> synchrony conf conf' e -> uniqList (dom (controlstate conf'))\n/\\ uniqList (finishedscenarios conf').\nProof.  intros.   \nunfold synchrony in H0. \n   repeat match goal with\n            | [ H: _ /\\ _ |- _ ] => destruct H\n\n            end.\n\nunfold combineFunc in H1. unfold constructConfigList in H1.\n\nremember ( constructConfigList'\n           (filter\n              (fun x : scenario => inList event_definition_dec (eventDefinition e) (alphabet x))\n              (filterList (finishedscenarios conf) (dom (controlstate conf)) scenario_dec)) e\n           conf).\ndestruct e0;inversion H1.  destruct v;inversion H3.  clear H3. clear H1.\n\ndestruct v.\nremember (mergeConfigFunc' conf conf c).\ndestruct e0;inversion H4.\nunfold removeEventFromConf;simpl.\nsplit.\napply mergeConfigFuncCSNoChange in Heqe1. rewrite <- Heqe1.\ndestruct H;auto. \nunfold mergeConfigFunc' in Heqe1.\ndestruct (mergeDataStateFunc (datastate conf) (datastate conf) (datastate c));inversion Heqe1. \ndestruct ( mergeControlStateFunc (controlstate conf) (controlstate conf)\n                                 (controlstate c));inversion H3;auto.\nsimpl.\n\napply uniqApp';auto.\ndestruct H;auto.\n\npose proof termL2.\n\nassert (exists sce : scenario, In sce (filter\n               (fun x : scenario =>\n                inList event_definition_dec (eventDefinition e) (alphabet x))\n               (filterList (finishedscenarios conf) (dom (controlstate conf))\n                  scenario_dec)) /\\ Result c = constructConfig sce e conf). \napply H1 with (lst:=c::nil);auto. split;auto. left;auto.\ndestruct H6. destruct H6.\napply termL3 in H7. rewrite H7. constructor. constructor. unfold not. intros.\ninversion H8.\nintros. \n\npose proof termL2.\n\nassert (exists sce : scenario, In sce (filter\n               (fun x : scenario =>\n                inList event_definition_dec (eventDefinition e) (alphabet x))\n               (filterList (finishedscenarios conf) (dom (controlstate conf))\n                  scenario_dec)) /\\ Result c = constructConfig sce e conf). \napply H6 with (lst:=c::nil);auto. split;auto. left;auto.\ndestruct H7. \ndestruct H7. \napply filter_In in H7. \ndestruct H7.\nunfold not;intros.\napply filterL1 in H7.\napply termL3 in H8. rewrite H8 in H10. destruct H10. subst. contradiction. \ninversion H10.\nintros. unfold not;intros. \n\npose proof termL2.\n\nassert (exists sce : scenario, In sce (filter\n               (fun x : scenario =>\n                inList event_definition_dec (eventDefinition e) (alphabet x))\n               (filterList (finishedscenarios conf) (dom (controlstate conf))\n                  scenario_dec)) /\\ Result c = constructConfig sce e conf). \napply H7 with (lst:=c::nil);auto. split;auto. left;auto.\ndestruct H8. \ndestruct H8. \napply filter_In in H8.\ndestruct H8. \napply filterL1 in H8.\napply termL3 in H9. rewrite H9 in H1. destruct H1. subst. contradiction. \ninversion H1.\nremember (c0 :: v). \n\n\nremember (innerCombineFunc'''' conf l).\ndestruct o;inversion H4;subst.\nremember ( mergeConfigFunc' conf c c1). \ndestruct e0;inversion H2;subst.\nunfold removeEventFromConf;simpl.\n\npose proof domMerge'.\nassert (dom (controlstate conf) = dom (controlstate c) /\\\n        dom (controlstate conf) = dom (controlstate c1)).\napply H1;auto. exists v0;auto. \ndestruct H3. \napply uniqSyncL2 with (originconf:=conf) (conf':=c) (conf'':=c1) ;auto.\nrewrite <- H3.  destruct H;auto. \nFocus 2. rewrite <- H5. destruct H;auto. \nFocus 2.\npose proof termL2.\npose proof uniqSyncL3.\npose proof termL2.\nassert (exists sce : scenario, In sce (filter\n               (fun x : scenario =>\n                inList event_definition_dec (eventDefinition e) (alphabet x))\n               (filterList (finishedscenarios conf) (dom (controlstate conf))\n                           scenario_dec))  /\\ Result c = constructConfig sce e conf).\napply H8 with (lst:=(c :: c0 :: v));auto.\nsplit;auto. left;auto.\ndestruct H9. destruct H9.\n\napply uniqSyncL1 in H10;auto. Focus 2.\napply filter_In in H9. destruct H9. apply filterL2 in H9;auto.  destruct H10;auto.\n apply filter_In in H9. destruct H9.\n\nassert (uniqList (dom (controlstate c1)) /\\ uniqList (finishedscenarios c1)).\n\n remember ((filter\n               (fun x : scenario =>\n                inList event_definition_dec (eventDefinition e) (alphabet x))\n               (filterList (finishedscenarios conf) (dom (controlstate conf))\n                           scenario_dec))).\n destruct l. simpl in Heqe0. inversion Heqe0.\n apply H7 with (conf:=conf) (lst:=l) (v:=(c0::v)) (e:=e);auto.\n assert (uniqList ( filter\n           (fun x : scenario => inList event_definition_dec (eventDefinition e) (alphabet x))\n           (filterList (finishedscenarios conf) (dom (controlstate conf)) scenario_dec))).\n SearchAbout filter. apply filterUniq;auto.\n SearchAbout filterList. apply uniqListFilter;destruct H;auto.\n rewrite <- Heql in H13. inversion H13;subst;auto.\n unfold incl;intros.\n assert (In a (s::l)). right;auto. rewrite  Heql in H14.\n SearchAbout filter. apply filter_In in H14. destruct H14. apply filterL2 in H14;auto.\n simpl in Heqe0. \n destruct (constructConfig s e conf );inversion Heqe0.\n remember (constructConfigList' l e conf).\n destruct e0;inversion H14. auto. \n intros.\n\n assert (In sce (s::l)). right;auto. rewrite  Heql in H14.\n apply filter_In in H14. destruct H14. apply filterL1 in H14;auto.\n destruct H13;auto. \n\n remember ((filter\n               (fun x : scenario =>\n                inList event_definition_dec (eventDefinition e) (alphabet x))\n               (filterList (finishedscenarios conf) (dom (controlstate conf))\n                           scenario_dec))).\n destruct l. simpl in Heqe0. inversion Heqe0.\n simpl in Heqe0.\n remember (constructConfig s e conf).\n destruct e0;inversion Heqe0.\n destruct (constructConfigList' l e conf);inversion Heqe0. subst.\n apply termL3 in Heqe2. rewrite Heqe2. constructor. constructor. unfold not;intros. inversion H6. \n intros.\n unfold not;intros.\n  remember ((filter\n               (fun x : scenario =>\n                inList event_definition_dec (eventDefinition e) (alphabet x))\n               (filterList (finishedscenarios conf) (dom (controlstate conf))\n                           scenario_dec))).\n destruct l. simpl in Heqe0. inversion Heqe0.\n simpl in Heqe0.\n remember (constructConfig s e conf).\n destruct e0;inversion Heqe0.\nclear H9.  remember (constructConfigList' l e conf). destruct e0;inversion Heqe0. subst.\napply termL3 in Heqe2. rewrite Heqe2 in H6. destruct H6. subst.\nFocus 2. inversion H6.\npose proof finishedscenarioIn.\napply H6 with (lst:=l) (e:=e) (i:=i) in Heqo;auto. \nassert (uniqList ( filter\n           (fun x : scenario => inList event_definition_dec (eventDefinition e) (alphabet x))\n           (filterList (finishedscenarios conf) (dom (controlstate conf)) scenario_dec))).\nSearchAbout filter.\napply filterUniq.\nSearchAbout filterList. apply uniqListFilter;destruct H;auto.\nrewrite <- Heql in H8. inversion H8;subst. contradiction.\nassert (uniqList ( filter\n           (fun x : scenario => inList event_definition_dec (eventDefinition e) (alphabet x))\n           (filterList (finishedscenarios conf) (dom (controlstate conf)) scenario_dec))).\napply filterUniq.\n apply uniqListFilter;destruct H;auto.\n rewrite <- Heql in H8. inversion H8;subst;auto.\n unfold incl;intros.\n assert (In a (i::l)). right;auto. \nrewrite Heql in H9. apply filter_In in H9. destruct H9. apply filterL2 in H9;auto. \nassert (In i (i::l)). left;auto. \nrewrite Heql in H8. apply filter_In in H8. destruct H8. apply filterL1 in H8;auto. \nintros.\nunfold not;intros. \n\n remember ((filter\n               (fun x : scenario =>\n                inList event_definition_dec (eventDefinition e) (alphabet x))\n               (filterList (finishedscenarios conf) (dom (controlstate conf))\n                           scenario_dec))).\n destruct l. simpl in Heqe0. inversion Heqe0.\n simpl in Heqe0.\n remember (constructConfig s e conf).\n destruct e0;inversion Heqe0.\n remember(constructConfigList' l e conf). destruct e0;inversion Heqe0. subst.\n clear Heqe0.  apply termL3 in Heqe2. rewrite Heqe2 in H7. destruct H7;subst.  Focus 2. inversion H7.\nclear H9. pose proof finishedscenarioIn.\n apply H7 with (lst:=l) (e:=e) (i:=i) in Heqo;auto. \nassert (uniqList ( filter\n           (fun x : scenario => inList event_definition_dec (eventDefinition e) (alphabet x))\n           (filterList (finishedscenarios conf) (dom (controlstate conf)) scenario_dec))).\napply filterUniq.\n apply uniqListFilter;destruct H;auto.\nrewrite <- Heql in H8. inversion H8;subst. contradiction.\nassert (uniqList ( filter\n           (fun x : scenario => inList event_definition_dec (eventDefinition e) (alphabet x))\n           (filterList (finishedscenarios conf) (dom (controlstate conf)) scenario_dec))).\napply filterUniq.\n apply uniqListFilter;destruct H;auto.\n rewrite <- Heql in H8. inversion H8;subst;auto.\n unfold incl;intros.\n assert (In a (i::l)). right;auto. \nrewrite Heql in H9. apply filter_In in H9. destruct H9. apply filterL2 in H9;auto. \nassert (In i (i::l)). left;auto. \nrewrite Heql in H8. apply filter_In in H8. destruct H8. apply filterL1 in H8;auto.\n\n\nQed.\n\n\n(*\n(*aux lemma*)\nLemma termL3': forall e conf sce conf',  Result conf' = constructConfig sce e conf  ->\n (forall sce', In sce' (finishedscenarios conf) ->In sce'  (finishedscenarios conf')).\nProof. \nintros. pose proof termL3. \nassert (finishedscenarios conf' = sce :: finishedscenarios conf).  \neapply H1. apply H. rewrite H2. simpl; right;auto.  \nQed.\n\n(*aux lemma*)\nLemma finishedInvariant: forall e conf lst scs sce, constructConfigList' scs e conf = Result lst\n(*-> In sce scs*) -> In sce (finishedscenarios conf) \n-> (forall conf', In conf' lst -> In sce (finishedscenarios conf')).\nProof. intros. pose proof termL2'. pose proof termL3'. pose proof termL2.\nassert (constructConfigList' scs e conf = Result lst /\\ In conf' lst).\nsplit;auto. apply H4 in H5. destruct H5.  destruct H5. \neapply H3 in H6. apply H6. auto.      \nQed.\n\n(*aux lemma*)\nLemma finishedSceInvariant: forall config config1 config2 config3\n sce, In sce (dom (controlstate config)) -> \n(In sce (finishedscenarios config1) \\/\nIn sce (finishedscenarios config2)) ->\n Result config3 = mergeConfigFunc config config1 config2\n-> In sce (finishedscenarios config3) .\nProof. intros.\nunfold mergeConfigFunc in H1.     \ndestruct (mergeDataStateFunc (datastate config) (datastate config1) (datastate config2)).\ndestruct (mergeControlStateFunc (controlstate config) (controlstate config1) (controlstate config2)).\ninversion H1. simpl. unfold  mergeList'.\napply in_or_app. destruct H0. left. auto. \nassert (In sce (finishedscenarios config1) \\/ ~(In sce (finishedscenarios config1))).\napply excluded_middle.  destruct H2. left. auto.     right.\nSearchAbout filterIn. apply filterIn. auto. auto. inversion H1. inversion H1.    \nQed.\n \n (*aux lemma*)\nLemma finishedInvariantCombine: forall lst conf conf'  sce ,\ncorrect_configuration conf -> In sce (finishedscenarios conf) ->\ninnerCombineFunc' conf None lst= Result conf' ->\n(forall conf', In conf' lst -> In sce (finishedscenarios conf'))\n-> In sce (finishedscenarios conf').\nProof. intro lst. induction lst.\n- intros. simpl in H1. inversion H1.\n-intros. simpl in H1. destruct lst. \n+ simpl in H1. apply H2. inversion H1. simpl;left;auto.\n+ simpl in H1.  \nremember ( innerCombineFunc' conf (Some c) lst ).\ndestruct e.   \nassert (conf'=a \\/ ~(conf'=a)). \napply excluded_middle. destruct H3.\napply H2. rewrite H3. simpl;left;auto. Focus 2. inversion H1.\nassert (In sce (finishedscenarios v)).\n \napply IHlst with (conf:=conf). auto. auto. symmetry;auto. \nintros. apply H2. simpl;right;auto.\neapply finishedSceInvariant. Focus 2. right. apply H4. Focus 2. symmetry. apply H1.\ndestruct H.\n unfold scenarioInclusion in inclusion. unfold incl in inclusion. apply inclusion. auto.\nQed.                     \n*)\n\nPrint innerCombineFunc''''.\n\nLemma finishedInvariantCombine: forall M  v (conf conf' : configuration M)  sce ,\n \n In sce (finishedscenarios conf) ->\ninnerCombineFunc'''' conf v = Some conf' ->\n In sce (finishedscenarios conf').\nProof. intros ? v. induction v.\n- intros. simpl in H0. inversion H0.\n-intros. simpl in H0. \nremember (innerCombineFunc'''' conf v ).\ndestruct o;inversion H0.\nremember (mergeConfigFunc' conf a c ).\ndestruct e;inversion H0. subst.\nunfold mergeConfigFunc' in Heqe.\ndestruct (mergeDataStateFunc (datastate conf) (datastate a) (datastate c) );inversion Heqe. \ndestruct ( mergeControlStateFunc (controlstate conf) (controlstate a) (controlstate c));inversion H4.\ndestruct v. Focus 2. inversion H0;subst. simpl. rewrite in_app_iff. right.\napply IHv with (conf:=conf);auto.\nremember (mergeConfigFunc' conf conf a ).\ndestruct e;inversion H0.\nsubst.\nunfold mergeConfigFunc' in Heqe0. \ndestruct (mergeDataStateFunc (datastate conf) (datastate conf) (datastate a) );inversion Heqe0. \ndestruct ( mergeControlStateFunc (controlstate conf) (controlstate conf) (controlstate a));inversion H5.\nsimpl. rewrite in_app_iff. left;auto.\ndestruct v;inversion H3.\n\nremember (mergeConfigFunc' conf conf a ).\ndestruct e;inversion H0.\nsubst.\nunfold mergeConfigFunc' in Heqe0. \ndestruct (mergeDataStateFunc (datastate conf) (datastate conf) (datastate a) );inversion Heqe0. \ndestruct ( mergeControlStateFunc (controlstate conf) (controlstate conf) (controlstate a));inversion H5.\nsimpl. rewrite in_app_iff. left;auto.\n\n\nremember (mergeConfigFunc' conf conf a ).\ndestruct e;inversion H0.\nsubst.\nunfold mergeConfigFunc' in Heqe. \ndestruct (mergeDataStateFunc (datastate conf) (datastate conf) (datastate a) );inversion Heqe. \nFocus 2. destruct v;inversion H0. destruct ( mergeControlStateFunc (controlstate conf) (controlstate conf) (controlstate a));inversion H4. destruct v;inversion H0. subst. \nsimpl. rewrite in_app_iff. left;auto.\n\nQed.\n\nLemma finishedInvariantSync: forall e M (conf conf': configuration M) sce,\nsynchrony conf conf' e -> \nIn sce (finishedscenarios conf)\n-> In sce (finishedscenarios conf').\nProof. intros. unfold synchrony in H.  \n  repeat match goal with\n            | [ H: _ /\\ _ |- _ ] => destruct H\n\n            end.\nunfold combineFunc in H1.\n\nremember (constructConfigList (dom (controlstate conf)) e conf).\ndestruct e0;inversion H1.\nclear H3.\ndestruct v;inversion H1. \nremember (innerCombineFunc'''' conf (c :: v)). \ndestruct o;inversion H1.\nunfold removeEventFromConf.\nsimpl.\napply finishedInvariantCombine with (v:=c::v) (conf:=conf);auto. \n\n\n(*eapply finishedInvariantCombine. apply H. auto. apply H4. intros.\npose proof finishedInvariant. symmetry in Heqe0. unfold constructConfigList in Heqe0.\neapply H6. apply Heqe0. auto. auto. inversion H4. *)\nQed.\n\nLemma domControlSync: forall M (conf conf' : configuration M) e,  synchrony conf conf' e ->  (dom (controlstate conf)) = (dom (controlstate conf')).\nProof. intros.\nunfold synchrony in H. \n   repeat match goal with\n            | [ H: _ /\\ _ |- _ ] => destruct H\n\n            end.\nunfold combineFunc in H0.   \nremember (constructConfigList (dom (controlstate conf)) e conf).\n\ndestruct e0;inversion H0. destruct v;inversion H2.\nclear H3. clear H0.\n\nremember (innerCombineFunc'''' conf (c::v)).\n\ndestruct o;inversion H2;auto.\nunfold removeEventFromConf. simpl.\nSearchAbout innerCombineFunc''''. \nsimpl in Heqo.\ndestruct v.\n remember (mergeConfigFunc' conf conf c).\n  destruct e0;inversion Heqo.\nsubst.   apply mergeConfigFuncCSNoChange with (conf1:=conf) (conf2:=c);auto.\nremember (innerCombineFunc'''' conf (c1 :: v)). \ndestruct o;inversion Heqo.\nclear H3. \nremember (mergeConfigFunc' conf c c2).\ndestruct e0;inversion Heqo. subst.\nCheck mergeConfigFuncCSNoChange. \n  apply mergeConfigFuncCSNoChange with (conf1:=c) (conf2:=c2);auto.\n \nQed.\n\nLemma monitorObjNoChangeSync: forall M (conf conf' : configuration M) e,\n    synchrony conf conf' e -> M = M.\nProof. reflexivity. Qed.\n\nLemma scenarioStateNotNone: forall l sce, In sce (dom l) -> getScenarioState sce l <> None.\nProof. intros. induction (l). \n- inversion H.\n- simpl. destruct a.   \ndestruct (string_dec (scenarioId sce) (scenarioId s)).\nunfold not;intros. inversion H0. apply IHl0. simpl in H. \ndestruct H. rewrite H in n. exfalso. apply n. auto. auto.\nQed.\n\nLemma mergeDSDom2NoChange: forall ds ds1 ds2 v,\n    Result v = mergeDataStateFunc ds ds1 ds2 ->\n    dom2 v = dom2 ds. \nProof.   \n  intro ds;induction ds.\n  - intros. simpl in H.\n    destruct ds1;inversion H.\n    destruct ds2;inversion H;auto. \n  -\n    intros.\n    destruct ds1;inversion H.\n    destruct a;destruct p. inversion H1.\n    destruct ds2;inversion H1.\n    destruct a;destruct p0. destruct p. destruct p;inversion H1.\n    destruct a;destruct p1;destruct p;destruct p.\n    destruct p0;destruct p.\n    destruct (atom_eq_dec a a0);inversion H1.\n    destruct (atom_eq_dec a a1);inversion H1.\n    destruct (typ_eq_dec t t0);inversion H1.\n    destruct (typ_eq_dec t t1);inversion H1.\n    remember (mergeDataStateFunc ds ds1 ds2).\n    destruct e3;inversion H1.\n    subst. \n    destruct (range_typ_dec r0 r1).\n    subst. inversion H1;simpl.\n    f_equal.\n    apply IHds with (ds1:=ds1) (ds2:=ds2);auto.\n    destruct (range_typ_dec r0 r).\n    subst.\n    inversion H1;simpl. f_equal.\n    apply IHds with (ds1:=ds1) (ds2:=ds2);auto.\n    destruct (range_typ_dec r1 r).\n    inversion H1;simpl. f_equal.\n    apply IHds with (ds1:=ds1) (ds2:=ds2);auto.\n    inversion H1.\nQed.\n\nLemma mergeConfigFuncDom2NoChange: forall M (conf conf1 conf2 : configuration M) v,\n  Result v = mergeConfigFunc' conf conf1 conf2 ->\n  dom2 (datastate conf) = dom2 (datastate v). \nProof. intros.\n       unfold mergeConfigFunc'  in H.\n       remember (mergeDataStateFunc (datastate conf) (datastate conf1) (datastate conf2)).       destruct e;inversion H.\n       remember (mergeControlStateFunc (controlstate conf) (controlstate conf1)\n                                       (controlstate conf2)).\n       destruct e;inversion H1.\n       simpl.\n       pose proof mergeDSDom2NoChange.\n       symmetry. \n       apply H0 with (ds1:=(datastate conf1)) (ds2:=(datastate conf2));auto.\nQed.\n\n\nLemma innerCombineDSDom2: forall M (conf : configuration M) sceList v0  re c,\n    correct_configuration conf ->\n    incl sceList (dom (controlstate conf)) ->\n    Result v0 = constructConfigList' sceList re conf ->\n    Some c = innerCombineFunc'''' conf v0 ->\n \n    dom2 (datastate conf) = dom2 (datastate c).\nProof.\n  intros ?? sceList;induction sceList.\n  - intros.\n    simpl in H1. inversion H1;auto. subst. simpl in H2.\n    inversion H2.\n  - intros.\n    simpl in H1.\n    remember (constructConfig a re conf ). \n    destruct e;inversion H1.\n    remember (constructConfigList' sceList re conf).\n    destruct e;inversion H1.\n    rewrite H5 in H2.\n    simpl in H2.\n    destruct v1.\n    subst.\n     remember (mergeConfigFunc' conf conf v).\n    destruct e;inversion H2.\n    apply mergeConfigFuncDom2NoChange with (conf1:=conf) (conf2:=v);auto.\n    \n    remember (innerCombineFunc'''' conf (c0::v1)).\n    destruct o;inversion H2.\nclear H6.     subst. remember (mergeConfigFunc' conf v c1).\n    destruct e;inversion H2.\n    subst.\n    apply mergeConfigFuncDom2NoChange with (conf1:=v) (conf2:=c1);auto. \n   \nQed.\n\nLemma syncDSDom2: forall M (conf conf' : configuration M) e,\n    correct_configuration conf ->\n    synchrony conf conf' e ->\n    dom2 (datastate conf) = dom2 (datastate conf').\nProof.\n  intros.\n  unfold synchrony in H0.\n  destruct H0.\n  unfold combineFunc in H1.\n  remember (constructConfigList (dom (controlstate conf)) e conf ). \n  destruct e0;inversion H1.\n  destruct v;inversion H3.\n  clear H4. clear H1.\n  remember (innerCombineFunc'''' conf (c::v)). \n  destruct o;inversion H3.\n  unfold removeEventFromConf;simpl.\n  simpl in Heqo.\n  destruct v.\n   remember (mergeConfigFunc' conf conf c).\n  destruct e0;inversion Heqo. \nsubst.  \n  apply mergeConfigFuncDom2NoChange with (conf1:=conf) (conf2:=c);auto.\n\n  remember (innerCombineFunc'''' conf (c1::v)). \n  destruct o;inversion Heqo.\nclear H4.   unfold removeEventFromConf;simpl.\n  \n  remember (mergeConfigFunc' conf c c2). \n  destruct e0;inversion Heqo. subst. \n \n  apply mergeConfigFuncDom2NoChange with (conf1:=c) (conf2:=c2);auto.\n  \nQed.\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/SMEDL_mon/smedlDef/smedl_common_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.2587335472548982}}
{"text": "Set Implicit Arguments.\n\nRequire Import Bedrock.Platform.Cito.ADT.\nRequire Import Bedrock.Platform.Cito.RepInv Bedrock.Platform.Cito.WordMap.\nRequire Import Bedrock.Platform.Cito.Inv.\n\nLemma starL_in : forall A P x (ls : list A),\n  NoDup ls\n  -> In x ls\n  -> exists ls', (P x * Bags.starL P ls' ===> Bags.starL P ls)\n    /\\ NoDup ls'\n    /\\ (forall y, In y ls' <-> y <> x /\\ In y ls).\n  induction 1; simpl; intuition subst.\n\n  eexists; intuition idtac.\n  apply Himp_refl.\n  auto.\n  congruence.\n  tauto.\n  congruence.\n  auto.\n\n  destruct H1; intuition.\n  exists (x0 :: x1); intuition idtac.\n  simpl.\n  eapply Himp_trans; [ | apply Himp_star_frame; [\n    apply Himp_refl | apply H3 ] ].\n  generalize dependent (Bags.starL P); intros.\n  sepLemma.\n  constructor; auto.\n  intro.\n  apply H5 in H4.\n  tauto.\n  subst; simpl in *; intuition subst.\n  auto.\n  apply H5 in H6; intuition.\n  simpl in *; intuition subst.\n  apply H5 in H6; intuition.\n  subst; simpl; tauto.\n  right; apply H5.\n  auto.\nQed.\n\nLemma starL_out : forall A P x (ls : list A),\n  NoDup ls\n  -> In x ls\n  -> exists ls', (Bags.starL P ls ===> P x * Bags.starL P ls')\n    /\\ NoDup ls'\n    /\\ (forall y, In y ls' <-> y <> x /\\ In y ls).\n  induction 1; simpl; intuition subst.\n\n  eexists; intuition idtac.\n  apply Himp_refl.\n  auto.\n  congruence.\n  tauto.\n  congruence.\n  auto.\n\n  destruct H1; intuition.\n  exists (x0 :: x1); intuition idtac.\n  simpl.\n  eapply Himp_trans; [ apply Himp_star_frame; [\n    apply Himp_refl | apply H3 ] | ].\n  generalize dependent (Bags.starL P); intros.\n  sepLemma.\n  constructor; auto.\n  intro.\n  apply H5 in H4.\n  tauto.\n  subst; simpl in *; intuition subst.\n  auto.\n  apply H5 in H6; intuition.\n  simpl in *; intuition subst.\n  apply H5 in H6; intuition.\n  subst; simpl; tauto.\n  right; apply H5.\n  auto.\nQed.\n\nLemma starL_permute : forall A P (ls1 : list A),\n  NoDup ls1\n  -> forall ls2, NoDup ls2\n    -> (forall x, In x ls1 <-> In x ls2)\n    -> Bags.starL P ls1 ===> Bags.starL P ls2.\n  induction 1.\n\n  inversion_clear 1; simpl; intros.\n  apply Himp_refl.\n  exfalso; eapply H; eauto.\n\n  intros.\n  eapply starL_in in H1.\n  Focus 2.\n  apply H2.\n  simpl; eauto.\n\n  destruct H1; intuition.\n  simpl.\n  eapply Himp_trans; [ | apply H3 ].\n  apply Himp_star_frame; try apply Himp_refl.\n  apply IHNoDup; auto.\n  intuition.\n  simpl in *.\n  apply H5; intuition.\n  apply H2; auto.\n  apply H5 in H4; intuition.\n  simpl in *.\n  apply H2 in H7.\n  intuition.\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/LayoutHintsUtil.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.25871760111903436}}
{"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\nRequire Import Event.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import Behavior.\n\nSet Implicit Arguments.\n\n\nSection Simulation.\n  Definition SIM := forall (c1_src c1_tgt: Configuration.t), Prop.\n\n  Definition _sim (sim: SIM) (c1_src c1_tgt:Configuration.t): Prop :=\n    forall (WF_SRC: Configuration.wf c1_src)\n      (WF_TGT: Configuration.wf c1_tgt),\n      <<TERMINAL:\n        forall (TERMINAL_TGT: Threads.is_terminal (Configuration.threads c1_tgt)),\n        exists c2_src,\n          <<STEPS_SRC: rtc Configuration.tau_step c1_src c2_src>> /\\\n          <<TERMINAL_SRC: Threads.is_terminal (Configuration.threads c2_src)>>>> /\\\n      <<STEP:\n        forall e tid c2_tgt\n          (STEP_TGT: Configuration.step e tid c1_tgt c2_tgt),\n        exists c2_src,\n          <<STEP_SRC: Configuration.opt_step e tid c1_src c2_src>> /\\\n          <<SIM: sim c2_src c2_tgt>>>>\n  .\n\n  Lemma _sim_mon: monotone2 _sim.\n  Proof.\n    ii. exploit IN; eauto. i. des.\n    econs; eauto. ii.\n    exploit STEP; eauto. i. des. eauto.\n  Qed.\n  #[local]\n  Hint Resolve _sim_mon: paco.\n\n  Definition sim: SIM := paco2 _sim bot2.\nEnd Simulation.\n#[export]\nHint Resolve _sim_mon: paco.\n\n\nLemma sim_adequacy\n      c_src c_tgt\n      (WF_SRC: Configuration.wf c_src)\n      (WF_TGT: Configuration.wf c_tgt)\n      (SIM: sim c_src c_tgt):\n  behaviors Configuration.step c_tgt <1= behaviors Configuration.step c_src.\nProof.\n  i. revert c_src WF_SRC WF_TGT SIM.\n  induction PR; i.\n  - punfold SIM0. exploit SIM0; eauto. i. des.\n    hexploit TERMINAL0; eauto. i. des.\n    eapply rtc_tau_step_behavior; eauto.\n    econs 1. eauto.\n  - punfold SIM0. exploit SIM0; eauto. i. des.\n    exploit STEP0; eauto. i. des.\n    exploit Configuration.step_future; try exact STEP; eauto. i. des.\n    exploit Configuration.opt_step_future; try exact STEP_SRC; eauto. i. des.\n    inv SIM1; ss. inv STEP_SRC.\n    econs 2; eauto.\n  - punfold SIM0. exploit SIM0; eauto. i. des.\n    exploit STEP0; eauto. i. des.\n    exploit Configuration.step_future; try exact STEP; eauto. i. des.\n    exploit Configuration.opt_step_future; try exact STEP_SRC; eauto. i. des.\n    inv SIM1; ss. inv STEP_SRC.\n    econs 3; eauto.\n  - punfold SIM0. exploit SIM0; eauto. i. des.\n    exploit STEP0; eauto. i. des.\n    exploit Configuration.step_future; try exact STEP; eauto. i. des.\n    exploit Configuration.opt_step_future; try exact STEP_SRC; eauto. i. des.\n    inv SIM1; ss. inv STEP_SRC; eauto.\n    econs 4; 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/prop/SimpleSimulation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.4035668537353745, "lm_q1q2_score": 0.25853939632780976}}
{"text": "Require Import Bedrock.Platform.Cito.CompileStmtSpec.\nRequire Import Bedrock.StringSet.\nRequire Import Bedrock.Platform.Cito.FreeVars.\nRequire Import Bedrock.Platform.Cito.SynReqFactsUtil.\n\nLocal Infix \";;\" := Syntax.Seq (right associativity, at level 95).\n\nLemma syn_req_Label_in : forall vars temp_size x lbl k, syn_req vars temp_size (Syntax.Label x lbl ;; k) -> List.In x vars.\n  unfold syn_req, in_scope; simpl; intuition.\n  apply Subset_union_left in H; intuition.\n  apply Subset_singleton in H0.\n  apply to_set_In; auto.\nQed.\n\nLemma syn_req_Assign_in : forall vars temp_size x e k, syn_req vars temp_size (Syntax.Assign x e ;; k) -> List.In x vars.\n  unfold syn_req, in_scope; simpl; intuition.\n  apply Subset_union_left in H; intuition.\n  apply Subset_union_left in H0; intuition.\n  apply Subset_singleton in H.\n  apply to_set_In; auto.\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/SynReqFacts2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.25843409746310547}}
{"text": "Require Export CalculusSM.\nRequire Export CalculusSM_tacs.\n\n\nSection CalculusSM3.\n\n  Context { pd  : @Data }.\n  Context { pn  : @Node }.\n  Context { pk  : @Key }.\n  Context { pm  : @Msg }.\n  Context { qc  : @Quorum_context pn}.\n  Context { pat : @AuthTok }.\n  Context { paf : @AuthFun pn pk pat pd }.\n  Context { pda : @DataAuth pd pn }.\n  Context { cad : @ContainedAuthData pd pat pm }.\n  Context { dtc : @DTimeContext }.\n  Context { iot : @IOTrustedFun }.\n  Context { ctp : @ComponentTrust pd pn pat qc iot }.\n  Context { cap : @ComponentAuth pd pn pk pat pm dtc iot }.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n\n  Context { base_fun_io       : baseFunIO           }.\n  Context { base_state_fun    : baseStateFun        }.\n  Context { trusted_state_fun : trustedStateFun     }.\n  Context { pkc               : KnowledgeComponents }.\n  Context { gms               : MsgStatus           }.\n\n\n  Local Open Scope kn.\n\n\n  (*  ****** PRIMITIVE RULES ****** *)\n\n\n  (***********************************************************)\n  Definition PRIMITIVE_RULE_beforele_if_eq x {eo : EventOrdering} e1 e2 Q R H a :=\n    MkRule0\n      [⟬Q ++ (x ⋈ e1 ▶ e2) :: R⟭ H ⊢ a]\n      (⟬Q ++ (x ⋈ e1 ≡ e2) :: R⟭ H ⊢ a).\n\n  Lemma PRIMITIVE_RULE_beforele_if_eq_true :\n    forall x {eo : EventOrdering} e1 e2 Q R H a,\n      rule_true (PRIMITIVE_RULE_beforele_if_eq x e1 e2 Q R H a).\n  Proof.\n    start_proving_primitive st ct ht.\n    unfold seq_event in *; simpl in *.\n    apply st0; simpl in *; tcsp.\n    pose proof (ct (x ⋈ e1 ≡ e2)) as w.\n    rewrite in_app_iff in w; simpl in w; autodimp w hyp; subst.\n    introv i; apply in_app_iff in i; simpl in *; repndors; subst; simpl in *; tcsp; eauto 3 with eo;\n      try (complete (apply ct; apply in_app_iff; simpl; tcsp)).\n  Qed.\n\n\n  (************************************************************************************************)\n  Definition PRIMITIVE_RULE_forall_before_intro u {eo : EventOrdering} e R H t :=\n    MkRule1\n      (fun e' => [⟬(u ⋈ e' ▷ e) :: R⟭ H ⊢ t @ e'])\n      (⟬R⟭ H ⊢ KE_FORALL_BEFORE t @ e).\n\n  Lemma PRIMITIVE_RULE_forall_before_intro_true :\n    forall u {eo : EventOrdering} e R H t,\n      rule_true (PRIMITIVE_RULE_forall_before_intro u e R H t).\n  Proof.\n    start_proving_primitive st ct ht.\n    introv lte; unfold seq_event in *; simpl in *.\n    inst_hyp e' st'.\n    apply st'; simpl; tcsp.\n    introv h; repndors; subst; simpl in *; auto.\n  Qed.\n\n\n  (************************************************************************************************)\n  Definition PRIMITIVE_RULE_similar_data_change_event {eo : EventOrdering} e1 e2 R H d1 d2 :=\n    MkRule0\n      [⟬ R ⟭ H ⊢ KE_SIMILAR_DATA d1 d2 @ e2]\n      (⟬ R ⟭ H ⊢ KE_SIMILAR_DATA d1 d2 @ e1).\n\n  Lemma PRIMITIVE_RULE_similar_data_change_event_true :\n    forall {eo : EventOrdering} e1 e2 R H d1 d2,\n      rule_true (PRIMITIVE_RULE_similar_data_change_event e1 e2 R H d1 d2).\n  Proof.\n    start_proving_primitive st ct ht.\n    apply st0 in ht; simpl in *; tcsp.\n  Qed.\n\n\n  (************************************************************************************************)\n  Definition PRIMITIVE_RULE_similar_data_sym {eo : EventOrdering} e R H d1 d2 :=\n    MkRule0\n      [⟬ R ⟭ H ⊢ KE_SIMILAR_DATA d1 d2 @ e]\n      (⟬ R ⟭ H ⊢ KE_SIMILAR_DATA d2 d1 @ e).\n\n  Lemma PRIMITIVE_RULE_similar_data_sym_true :\n    forall {eo : EventOrdering} e R H d1 d2,\n      rule_true (PRIMITIVE_RULE_similar_data_sym e R H d1 d2).\n  Proof.\n    start_proving_primitive st ct ht.\n    apply st0 in ht; simpl in *; tcsp.\n    apply kc_sim_data_sym; auto.\n  Qed.\n\n\n  (************************************************************************************************)\n  Definition PRIMITIVE_RULE_data_eq_sym {eo : EventOrdering} e R H t1 t2 :=\n    MkRule0\n      [⟬ R ⟭ H ⊢ KE_DATA_EQ t2 t1 @ e]\n      (⟬ R ⟭ H ⊢ KE_DATA_EQ t1 t2 @ e).\n\n  Lemma PRIMITIVE_RULE_data_eq_sym_true :\n    forall {eo : EventOrdering} e R H t1 t2,\n      rule_true (PRIMITIVE_RULE_data_eq_sym e R H t1 t2).\n  Proof.\n    start_proving_primitive st ct ht.\n    apply st0 in ht; simpl in *; tcsp.\n  Qed.\n\nEnd CalculusSM3.\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/CalculusSM3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.25843409746310536}}
{"text": "From Equations Require Import Equations.\nRequire Import Ascii String.\nRequire Import FunctionalExtensionality.\nFrom stdpp Require Import numbers.\nImport N.\n\nFrom Formalisation Require Export Span.\nFrom FreeMonad Require Import FreeMonad.\nFrom SepLogic Require Import SepSet.\nFrom Formalisation Require Import IsFresh Inject ZeroCopy.\nFrom Classes Require Import Foldable.\nFrom Examples Require Import example2.\n\nRequire Import Coq.Program.Equality.\n\nOpen Scope N_scope.\n\nDefinition octet := N.\n\nDefinition data := list octet.\n\nInductive DECODE : Type -> Type :=\n| TakeOp : N -> DECODE span\n| ReadOp : span -> N -> DECODE octet\n| FailOp : forall {X}, DECODE X.\n\nDefinition Decodeur := Free DECODE.\n\nDefinition take (n : N) : Decodeur span := gen (TakeOp n).\n\nDefinition read (s : span) (pos : N): Decodeur N := gen (ReadOp s pos).\n\nDefinition fail {X} : Decodeur X := gen FailOp.\n\nFixpoint wp {X} (m: Decodeur X) (Q : X -> iProp) : iProp :=\n  match m with\n  | ret v => Q v\n  | op (TakeOp n) k => ∀ v, IsFresh v -∗ wp (k v) Q\n  | op (ReadOp s n) k => ∀ v , wp (k v) Q\n  | op FailOp _ => True\n  end.\n\nLocal Open Scope free_monad_scope.\n\nLemma wp_bind {X Y} (e : Decodeur X) (f :  X → Decodeur Y) (Q : Y -> iProp) (Q' : X -> iProp) :\n  wp e Q' ⊢\n    (∀ v,  Q' v -∗ wp (f v) Q ) -∗\n    wp (let! v := e in f v) Q %I.\nProof.\n  iIntros \"HA HB\". revert e. fix e 1.\n  destruct e0 as [v | Z []]; simpl; auto.\n  - iApply (\"HB\" with \"HA\").\n  - iIntros (v) \"HC\". iDestruct (\"HA\" with \"HC\") as \"HA\".\n    iPoseProof \"HB\" as \"HB\". apply e.\n  - iIntros (v). iDestruct (\"HA\" $! v) as \"HA\".\n    iPoseProof \"HB\" as \"HB\". apply e.\nQed.\n\nLemma wp_consequence {X} (P Q : X -> iProp) (f : Decodeur X) :\n  ⊢ wp f P -∗\n    (∀ x, P x -∗ Q x) -∗\n    wp f Q.\nProof.\n  induction f as [v | Y [] k]; simpl; intros; auto.\n  - iIntros \"HA HB\". iApply (\"HB\" with \"HA\").\n  - iIntros \"HA HB * HC\". iDestruct (\"HA\" with \"HC\") as \"HA\".\n    iApply (H with \"HA HB\").\n  - iIntros \"HA HB\" (v). iApply (H with \"HA HB\").\nQed.\n\n\nNotation \"{{ P }} m {{ v ; Q }}\" := (⊢ P -∗ wp m (fun v => Q))\n                                      (at level 20,\n                                        format \"'[hv' {{  P  }}  '/  ' m  '/'  {{  v ;  Q  }} ']'\").\n\nLemma rule_ret {X} (v : X) H (Q : X -> iProp) :\n  (H ⊢ Q v) -> {{ H }} (ret v : Decodeur X) {{ v'; Q v' }}.\nProof. simpl; iIntros. iApply H0; auto. Qed.\n\nLemma rule_bind {X Y} (e : Decodeur X) (f : X -> Decodeur Y) Q Q' (H : iProp) :\n  ({{ H }} e {{ v; Q' v }}) ->\n  (∀ v, {{ Q' v }} f v {{ v'; Q v' }}) ->\n  {{ H }} do v <- e; f v {{ v; Q v}}.\nProof.\n  intros. iIntros \"HA\".\n  iApply (wp_bind e f _ Q' with \"[HA]\").\n  - iApply (H0 with \"[HA]\"); auto.\n  - iIntros (v) \"HC\". iApply (H1 with \"[HC]\"); auto.\nQed.\n\nSection Rules.\n\n  Variable X: Type.\n  Implicit Type P: iProp.\n  Implicit Type Q: X -> iProp.\n\n  Lemma rule_consequence: forall P P' Q Q' m,\n\n      ({{ P' }} m {{ v; Q' v }}) ->\n      (P ⊢ P') ->\n      (forall v, Q' v ⊢ Q v) ->\n      (*-----------------------*)\n      {{ P }} m {{ v; Q v }}.\n  Proof.\n    intros. iIntros \"HA\". iDestruct (H0 with \"HA\") as \"HA\".\n    iDestruct (H with \"HA\") as \"HA\". iApply (wp_consequence with \"HA\").\n    iIntros \"*\". iApply H1.\n  Qed.\n\n\n  Lemma frame_bind : forall (P : iProp), ⊢ P -∗ emp ∗ P.\n  Proof. iIntros \"* $\". Qed.\n\n  Lemma rule_frame: forall P Q P' m,\n\n      ({{ P }} m {{ v; Q v }}) ->\n      (*----------------------------*)\n      {{ P ∗ P' }} m {{ v; Q v ∗ P' }}.\n  Proof.\n    intros. iIntros \"[HA HC]\". iApply (wp_consequence with \"[HA]\").\n    iApply H; auto. iIntros; iFrame.\n  Qed.\n\n  Lemma rule_fail H Q : {{ H }} fail {{ v; Q v }}.\n  Proof. auto. Qed.\n\n  Lemma rule_read s res : {{ emp }} read s res {{ _; emp }}.\n  Proof. eauto. Qed.\n\n  Lemma rule_take n : {{ emp }} take n {{ v; IsFresh v }}.\n  Proof. simpl. eauto. Qed.\n\nEnd Rules.\n\nRecord packet_SSHS (S : Type) :=\n  mk_ssh {\n      packet_length : N;\n      padding_length : N;\n      payload : S;\n      mac : S; }.\n\nArguments mk_ssh [S].\nArguments packet_length [S].\nArguments padding_length [S].\nArguments payload [S].\nArguments mac [S].\n\nDefinition packet_SSH := packet_SSHS span.\n\nDefinition foldMap M (sg : Monoid.Semigroup M) (m : Monoid.Monoid M)\n  {A} (fold : A -> M) (p : packet_SSHS A) : M :=\n  Monoid.f (fold (payload p)) (fold (mac p)).\n\nLocal Instance Foldable_SSH : Foldable packet_SSHS :=\n  Build_Foldable _ (@foldMap).\n\nDefinition decode_next : Decodeur N :=\n  let! s := take 1 in\n  read s 0.\n\nLemma rule_next : {{ emp }} decode_next {{ _; True }}.\nProof.\n  eapply rule_bind.\n  eapply rule_take.\n  intro. eapply rule_consequence. eapply rule_frame. eapply rule_read.\n  iIntros \"HA\". iSplitR; eauto. iApply \"HA\".\n  eauto.\nQed.\n\nDefinition decode_u32 :=\n  let! a := decode_next in\n  let! b := decode_next in\n  let! c := decode_next in\n  let! d := decode_next in\n  ret (to_u32 a b c d).\n\nLemma rule_u32 : {{ emp }} decode_u32 {{ _; True }}.\nProof.\n  eapply rule_bind.\n  eapply rule_next.\n  intro. eapply rule_bind.\n  eapply rule_consequence. eapply rule_frame. eapply rule_next.\n  iIntros \"HA\". iSplitR; eauto. iApply \"HA\". eauto.\n  intro. eapply rule_bind.\n  eapply rule_consequence. eapply rule_frame. eapply rule_next.\n  iIntros \"HA\". iSplitR; eauto. iApply \"HA\". eauto.\n  intro. eapply rule_bind.\n  eapply rule_consequence. eapply rule_frame. eapply rule_next.\n  iIntros \"HA\". iSplitR; eauto. iApply \"HA\". eauto.\n  eauto.\nQed.\n\nDefinition decode_packet_SSH : Decodeur packet_SSH :=\n  let! packet_length := decode_u32 in\n  let! padding_length := decode_next in\n  if padding_length + 1 <=? packet_length\n  then\n    let! payload := take (packet_length - padding_length - 1) in\n    let! padding := take padding_length in\n    let! mac := take 20 in\n    ret (mk_ssh packet_length padding_length payload mac)\n  else\n    fail.\n\nLemma rule_decode_packet_SSH : {{ emp }} decode_packet_SSH {{ v; <absorb> all_disjointMSL v }}.\nProof.\n  eapply rule_bind.\n  eapply rule_u32.\n  intro. eapply rule_bind.\n  eapply rule_consequence. eapply rule_frame. eapply rule_next.\n  iIntros \"HA\". iSplitR; eauto. iApply \"HA\". eauto.\n  intro. destruct (v0 + 1 <=? v).\n  - eapply rule_bind.\n    eapply rule_consequence. eapply rule_frame. eapply rule_take.\n    iIntros \"HA\". iSplitR; eauto. iApply \"HA\". eauto.\n    intro. eapply rule_bind.\n    eapply rule_consequence. eapply rule_frame. eapply rule_take.\n    iIntros \"HA\". iSplitR; eauto. iApply \"HA\". eauto.\n    intros. eapply rule_bind.\n    eapply rule_consequence. eapply rule_frame. eapply rule_take.\n    iIntros \"HA\". iSplitR; eauto. iApply \"HA\". eauto.\n    intros. eapply rule_ret. iIntros. iNorm.\n    unfold all_disjointMSL, all_disjointSL. simpl. iFrame.\n  - eapply rule_fail.\nQed.\n\nClose Scope free_monad_scope.\n\nFixpoint eval {X} (m : Decodeur X) : DecodeurM X :=\n  match m with\n  | ret v => ret! v\n  | op (TakeOp n) k =>\n      let! v := takeM n in\n      eval (k v)\n  | op (ReadOp s pos) k =>\n      let! v := readM s pos in\n      eval (k v)\n  | op FailOp _ => failM\n  end.\n\nDefinition decode {X} (d : Decodeur X) (data : data) : option X :=\n  match eval d data (mk_span 0 (length data)) with\n  | Some (v, _) => Some v\n  | _ => None\n  end.\n\nLemma eval_monotone : forall X (e : Decodeur X) s1 s2 a v,\n    eval e a s1 = Some (v, s2) ->\n    (pos s1 <= pos s2)%N /\\ (pos s2 + len s2 <= pos s1 + len s1)%N.\nProof.\n  fix IH 2.\n  destruct e as [v  | Y []]; simpl; intros.\n  - inversion H. split; lia.\n  - unfold eval in H. fold (@eval X) in H. unfold bind in H. unfold takeM in H.\n    destruct ((n <=? len s1)%N) eqn:?. 2 : inversion H.\n    eapply IH in H as [P0 P1]. eapply N.leb_le in Heqb. simpl in *. lia.\n  - unfold eval in H. fold (@eval X) in H. unfold bind in H. unfold readM in H.\n    destruct ((n <? len s)%N) eqn:?. 2 : inversion H.\n    destruct (lookup (pos s + n) a). 2 : inversion H.\n    eapply IH in H as [P0 P1]. eapply N.ltb_lt in Heqb. lia.\n  - inversion H.\nQed.\n\nLemma soundness : forall X d H (Q : X -> iProp),\n    {{ H }} d {{v ; Q v }} ->\n    forall data s (v : X) s',\n      eval d data s = Some (v, s') ->\n      H ∗ injectSL (pos s) (pos s') ⊢ Q v.\nProof.\n  fix IH 2.\n  destruct d as [v | Y []]; simpl; intros.\n  (* ret *)\n  - iIntros \"[HA HB]\". inversion H1. subst.\n    iDestruct (injectSL_emp with \"HB\") as \"_\". lia.\n    iApply (H0 with \"HA\").\n  (* take *)\n  - unfold eval in H1. fold (@eval X) in H1. unfold bind in H1. unfold takeM in H1.\n    destruct ((n <=? len s)%N) eqn:?.\n    2 : inversion H1.\n    epose H1 as grow.\n    eapply eval_monotone in grow as [P0 P1]. simpl in *.\n    iIntros \"[HA HB]\". iApply IH; eauto. simpl.\n    unfold injectSL. rewrite (inject_union (pos s + n)). 2-3 : lia.\n    iDestruct (big_sepS_union with \"HB\") as \"[HC HB]\". apply inject_disjoint.\n    iSplitR \"HB\"; eauto.\n    iApply (H0 with \"HA [HC]\").\n    iApply (inject_IsFresh with \"HC\"); simpl; lia.\n  (* read *)\n  - unfold eval in H1. fold (@eval X) in H1. unfold bind in H1. unfold readM in H1.\n    destruct ((n <? len s)%N) eqn:?. 2 : inversion H1.\n    destruct (lookup (pos s + n) data0). 2 : inversion H1.\n    iIntros \"[HA HB]\". iApply IH; eauto. iFrame. iApply (H0 with \"HA\").\n  (* fail *)\n  - inversion H1.\nQed.\n\nTheorem adequacy : forall X d (Q : X -> Prop),\n    {{ emp }} d {{ v; ⌜Q v⌝ }} ->\n    forall data v,\n      decode d data = Some v ->\n      Q v.\nProof.\n  intros. unfold decode in H0.\n  destruct (eval d data0) as  [[r s]| ] eqn:?. 2 : inversion H0.\n  injection H0. intro. subst. eapply soundness_pure.\n  iIntros \"HA\". iApply (soundness _ d emp (fun v => ⌜ Q v ⌝)); eauto.\n  iSplitR; auto. simpl. iApply big_op_ctx. eauto.\nQed.\n\nLemma Fresh_ZC_aux `{Foldable M}: forall e s n s_res,\n    {{ injectSL n (pos s) }} e {{ res; <absorb> all_disjointMSL res }} ->\n    forall (data : data) (res : M span),\n      n <= pos s ->\n      eval e data s = Some (res, s_res) ->\n      forall v, v ∈ M_to_list res ->\n           set_span v ⊆ inject n (pos s + len s).\nProof.\n  revert M H. fix IH 3. intros M H e.\n  dependent destruction e; intros; simpl in *. revert H1 H2. intros LE H1.\n  - inversion H1. subst. clear H1.\n    revert H0. MonPred.unseal. unfold monpred.monPred_wand_def. simpl.\n    unfold monpred.monPred_upclosed. simpl. intro. destruct H0. simpl in *.\n    edestruct (monPred_in_entails tt). clear monPred_in_entails.\n    instantiate (1 := ∅). MonPred.unseal.\n    split. split. inversion_star h P. clear H0.\n    red in P1. destruct P1. inversion H1. subst. clear H1. clear P2.\n    rewrite union_empty_r_L in P. clear monPred_in_entails. subst.\n    edestruct H0.\n    + eexists ∅, _. repeat split; auto. 2 : eapply disjoint_empty_l.\n      eapply SepSet.soundness. iIntros \"HA\". iApply big_op_ctx. iApply \"HA\".\n    + destruct H1 as [h [P3 [P1 [P2 P4]]]]. clear H0 P0 P3.\n      rewrite union_empty_l_L in P4.\n      transitivity (inject n (Span.pos s_res)).\n      2 : { eapply inject_mono_r. lia. }\n      rewrite P4. transitivity h. 2 : set_solver. clear P2 P4. unfold all_disjointMSL in P1.\n      eapply (all_disjointSL_incl _ _ H3 _ P1).\n  - destruct d; simpl in *.\n    + unfold set_span.\n      unfold bind, takeM in H2.\n      destruct (n0 <=? len s) eqn:?.\n      * pose (mono := H2). eapply eval_monotone in mono as [P0 P1]. simpl in *.\n        eapply N.leb_le in Heqb. assert (pos s + len s = pos s + n0 + (len s - n0)) by lia.\n        rewrite H4.\n        unfold set_span in IH.\n        eapply (IH _ _ _ {| pos := pos s + n0; len := len s - n0 |}); simpl in *; eauto.\n        2 : lia.\n        iIntros \"HA\". unfold injectSL. rewrite (inject_add n0 n (pos s)). 2 : lia.\n        iDestruct (big_sepS_union with \"HA\") as \"[HA HB]\". eapply inject_disjoint.\n        iDestruct (inject_IsFresh with \"[HB]\") as \"HB\"; eauto.\n        unfold injectSL. instantiate (1 := (mk_span (pos s) n0)). simpl. iApply \"HB\".\n        iApply (H0 with \"HA HB\").\n      * inversion H2.\n    + unfold bind, readM in H2.\n      destruct (n0 <? len s0) eqn:?.\n      destruct (lookup (pos s0 + n0) data0) eqn:?.\n      eapply IH; eauto.\n      iIntros \"HA\". iDestruct (H0 with \"HA\") as \"HB\". iApply \"HB\".\n      inversion H2. inversion H2.\n    + inversion H2.\nQed.\n\n\nLemma eval_ZC `{Foldable M}: forall e,\n    {{ emp }} e {{ res; <absorb> all_disjointMSL res }} ->\n    forall (data : data) (res : M span) s s_res,\n      eval e data s = Some (res, s_res) ->\n      Result_in res s.\nProof.\n  unfold Result_in. intros. eapply Fresh_ZC_aux.\n   iIntros \"HA\". iApply H0.\n   iApply (injectSL_emp with \"HA\"). lia. lia. eauto. auto.\nQed.\n\nDefinition decode_zerocopy `{Foldable M} (e : Decodeur (M span)) := forall data res,\n      decode e data = Some res ->\n      Result_in res (mk_span 0 (length data)).\n\nLemma decode_ZC `{Foldable M}: forall e,\n    {{ emp }} e {{ res; <absorb> all_disjointMSL res }} ->\n    decode_zerocopy e.\nProof.\n  unfold decode_zerocopy, decode. intros.\n  destruct eval as [[v s_v]|] eqn:?; inversion H1. subst.\n  eapply eval_ZC; eauto.\nQed.\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/examples/example3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2584340904811179}}
{"text": "(***************************************************************************\n* Principality of unification for mini-ML with structural polymorphism     *\n* Jacques Garrigue, July 2008                                              *\n***************************************************************************)\n\nRequire Import Arith List Metatheory.\nRequire Import ML_SP_Definitions Cardinal ML_SP_Eval.\nRequire Omega.\nLtac omega := Omega.omega.\n\nSet Implicit Arguments.\n\nModule MkUnify(Cstr:CstrIntf)(Const:CstIntf).\n\nModule MyEval := MkEval(Cstr)(Const).\nImport MyEval.\nImport Rename.\nImport Sound.\nImport Infra.\nImport Defs.\n\n(* Composition of substitutions *)\nDefinition compose S1 S2 : subs := S1 & map (typ_subst S1) S2.\n\n(* Inclusion of substitutions. Very handy to use in proofs *)\nDefinition extends S S0 :=\n  forall T, typ_subst S (typ_subst S0 T) = typ_subst S T.\n\nLemma extends_trans : forall S1 S2 S3,\n  extends S1 S2 -> extends S2 S3 -> extends S1 S3.\nProof.\n  intros; intro.\n  rewrite <- H. rewrite <- (H T).\n  rewrite* H0.\nQed.\n\n(* Unifiers *)\nDefinition unifies S pairs :=\n  forall T1 T2, In (T1, T2) pairs -> typ_subst S T1 = typ_subst S T2.\n\n(* Subsititions should be in normal form *)\nDefinition is_subst (S : subs) :=\n  env_prop (fun T => disjoint (dom S) (typ_fv T)) S.\n\nSection Moregen.\n  (* Here we relate extends with the more usual notional of generality *)\n\n  Definition moregen S0 S :=\n    exists S1, forall T, typ_subst S T = typ_subst S1 (typ_subst S0 T).\n\n  (* Extends implies more general *)\n  Lemma extends_moregen : forall S S0,\n    extends S S0 -> moregen S0 S.\n  Proof.\n    intros.\n    exists* S.\n  Qed.\n\n  Lemma typ_subst_idem : forall S T,\n    is_subst S -> typ_subst S (typ_subst S T) = typ_subst S T.\n  Proof.\n    intros.\n    induction T; simpl. auto.\n      case_eq (get v S); intros.\n        rewrite* typ_subst_fresh.\n      simpl.\n      rewrite* H0.\n    simpl; congruence.\n  Qed.\n\n  (* For substitutions in normal form, moregeneral implies extends *)\n  Lemma moregen_extends : forall S S0,\n    moregen S0 S -> is_subst S0 -> extends S S0.\n  Proof.\n    intros; intro.\n    destruct H as [S1 Heq].\n    rewrite Heq.\n    rewrite* typ_subst_idem.\n  Qed.\n\nEnd Moregen.\n\nFixpoint unify_kind_rel (kr kr':list(Cstr.attr*typ)) (uniq:Cstr.attr -> bool)\n  (pairs:list(typ*typ)) {struct kr} :=\n  match kr with\n  | nil => (kr', pairs)\n  | (l,T)::krem =>\n    if uniq l then\n      match assoc Cstr.eq_dec l kr' with\n      | None => unify_kind_rel krem ((l,T)::kr') uniq pairs\n      | Some T' => unify_kind_rel krem kr' uniq ((T,T')::pairs)\n      end\n    else unify_kind_rel krem ((l,T)::kr') uniq pairs\n  end.\n\nFixpoint remove_env (A:Set) (E:Env.env A) (x:var) {struct E} : Env.env A :=\n  match E with\n  | nil => nil\n  | (y,a)::E' =>\n    if x == y then E' else (y,a) :: remove_env E' x\n  end.\n\nLemma unify_coherent : forall kc kr,\n  coherent kc (fst (unify_kind_rel kr nil (Cstr.unique kc) nil)).\nProof.\n  intros until kr.\n  set (kr' := @nil (Cstr.attr*typ)).\n  set (pairs' := @nil (typ*typ)).\n  assert (coherent kc kr'). intro; intros. elim H0.\n  gen kr' pairs'.\n  induction kr; simpl; intros. auto.\n  destruct a.\n  case_eq (Cstr.unique kc a); introv R.\n    case_eq (assoc Cstr.eq_dec a kr'); introv R1. apply* IHkr.\n    apply IHkr.\n    intro; intros.\n    simpl in *; destruct H1; [inversions H1|]; destruct H2. inversions* H2.\n        elim (assoc_complete _ _ _ _ R1 H2).\n      inversions H2; elim (assoc_complete _ _ _ _ R1 H1).\n    apply* (H x).\n  apply IHkr.\n  intro; intros.\n  simpl in *.\n  destruct (Cstr.eq_dec x a).\n    subst. rewrite R in H0; discriminate.\n  apply* (H x). destruct* H1. inversions* H1.\n  destruct* H2. inversions* H2.\nQed.\n\nDefinition unify_kinds (k1 k2:kind) : option (kind * list (typ*typ)).\n  intros.\n  refine (\n  match k1, k2 with\n  | None, _ => Some (k2, nil)\n  | Some _, None => Some (k1, nil)\n  | Some (@Kind kc1 kv1 kr1 kh1), Some (@Kind kc2 kv2 kr2 kh2) =>\n    let kc := Cstr.lub kc1 kc2 in\n    if Cstr.valid_dec kc then\n      let krp := unify_kind_rel (kr1 ++ kr2) nil (Cstr.unique kc) nil in\n      Some (Some (@Kind kc _ (fst krp) _), snd krp)\n    else None\n  end).\n    auto.\n  unfold krp; apply unify_coherent.\nDefined.\n\nDefinition get_kind x E : kind :=\n  match get x E with\n  | Some k  => k\n  | None => None\n  end.\n\nLemma binds_get_kind : forall x k K,\n  binds x k K -> get_kind x K = k.\nProof.\n  intros.\n  unfold get_kind. rewrite* H.\nQed.\n\nLemma get_kind_binds : forall x k K,\n  get_kind x K = Some k -> binds x (Some k) K.\nProof.\n  unfold get_kind; intros.\n  case_rewrite R (get x K).\n  subst*.\nQed.\nHint Resolve get_kind_binds : core.\n\nDefinition unify_vars (K:kenv) (x y:var) :=\n  match unify_kinds (get_kind x K) (get_kind y K) with\n  | Some (k, pairs) => Some (remove_env (remove_env K x) y & y ~ k, pairs)\n  | None => None\n  end.\n\nDefinition unify_nv (unify : kenv -> subs -> option (kenv * subs)) K S x T :=\n  if S.mem x (typ_fv T) then None else\n    match get_kind x K with\n    | Some _ => None\n    | None => unify (remove_env K x) (compose (x ~ T) S)\n    end.\n\nFixpoint unify0 unify (h:nat) (pairs:list(typ*typ)) (K:kenv) (S:subs) {struct h}\n  : option (kenv * subs) :=\n  match h with 0 => None\n  | S h' =>\n    match pairs with\n    | nil => Some (K,S)\n    | (T1,T2) :: pairs' =>\n      match typ_subst S T1, typ_subst S T2 with\n      | typ_bvar n, typ_bvar m =>\n        if n === m then unify0 unify h' pairs' K S else None\n      | typ_fvar x, typ_fvar y =>\n        if x == y then unify0 unify h' pairs' K S else\n        match unify_vars K x y with\n        | Some (K', pairs) =>\n          unify (pairs ++ pairs') K' (compose (x ~ typ_fvar y) S)\n        | None => None\n        end\n      | typ_fvar x, T =>\n        unify_nv (unify pairs') K S x T \n      | T, typ_fvar x =>\n        unify_nv (unify pairs') K S x T \n       | typ_arrow T11 T12, typ_arrow T21 T22 =>\n        unify0 unify h' ((T11,T21)::(T12,T22)::pairs') K S\n      | _, _ =>\n        None\n      end\n    end\n  end.\n\nSection Accum.\n  Variables A B : Type.\n  Variables (f : A -> B) (op : B->B->B) (unit : B).\n\n  Fixpoint accum (l:list A) {struct l} : B :=\n    match l with\n    | nil => unit\n    | a::rem => op (f a) (accum rem)\n    end.\n\n  Variable op_assoc : forall a b c, op a (op b c) = op (op a b) c.\n  Variable op_unit : forall a, op unit a = a.\n\n  Lemma accum_app : forall l2 l1,\n    accum (l1 ++ l2) = op (accum l1) (accum l2).\n  Proof.\n    induction l1; simpl. rewrite* op_unit.\n    rewrite <- op_assoc.\n    rewrite* IHl1.\n  Qed.\n\nEnd Accum.\n\nFixpoint all_types S (pairs:list(typ*typ)) {struct pairs} : list typ :=\n  match pairs with\n  | nil => nil\n  | p::rem =>\n      typ_subst S (fst p) :: typ_subst S (snd p) :: all_types S rem\n  end.\n\nFixpoint typ_size (T : typ) : nat :=\n  match T with\n  | typ_arrow T1 T2 => S (typ_size T1 + typ_size T2)\n  | _ => 1\n  end.\n\nDefinition pairs_size S pairs := accum typ_size plus 0 (all_types S pairs).\n\nFixpoint unify (h:nat) (pairs:list (typ*typ)) (K:kenv) (S:subs) {struct h} :=\n  match h with\n  | 0 => None\n  | S h' => unify0 (unify h') (pairs_size S pairs + 1) pairs K S\n  end.\n\nLemma typ_subst_compose : forall S1 S2 T,\n  typ_subst (compose S1 S2) T = typ_subst S1 (typ_subst S2 T).\nProof.\n  induction T; simpl; intros; auto.\n    unfold compose.\n    simpl; case_eq (get v S2); intros.\n      rewrite* (binds_prepend S1 (binds_map (typ_subst S1) H)).\n    simpl.\n    case_eq (get v S1); intros.\n      rewrite* (binds_concat_fresh (map (typ_subst S1) S2) H0).\n    case_eq (get v (S1 & map (typ_subst S1) S2)); intros; auto.\n    destruct (binds_concat_inv H1).\n      destruct H2. rewrite H3 in H0. discriminate.\n    destruct (binds_map_inv _ _ H2).\n    rewrite (proj2 H3) in H; discriminate.\n  rewrite* IHT1.\n  rewrite* IHT2.\nQed.\n\nLemma binds_typ_subst : forall x T S,\n  binds x T S -> typ_subst S (typ_fvar x) = T.\nProof.\n  intros. simpl. rewrite* H.\nQed.\n\nLemma disjoint_subst : forall x T L T',\n  disjoint ({{x}} \\u L) (typ_fv T) ->\n  disjoint L (typ_fv T') ->\n  disjoint ({{x}} \\u L) (typ_fv (typ_subst (x ~ T) T')).\nProof.\n  induction T'; simpl; intros; auto.\n    destruct* (v == x).\n    simpl*.\n  forward~ IHT'1 as HT1.\n  forward~ IHT'2 as HT2.\nQed.\n\nLemma add_binding_is_subst : forall S x T,\n  is_subst S ->\n  disjoint (dom S) (typ_fv T) ->\n  x \\notin (typ_fv T) ->\n  is_subst (compose (x ~ T) S).\nProof.\n  intros.\n  unfold compose.\n  intro; intros.\n  rewrite dom_concat; rewrite dom_map.\n  simpl. rewrite union_empty_r.\n  destruct (in_app_or _ _ _ H2).\n    destruct (in_map_inv _ _ _ _ H3) as [b [F B']].\n    subst.\n    use (H _ _ B').\n    simpl in *.\n    apply* disjoint_subst.\n  simpl in H3. destruct* H3.\n  inversions* H3.\nQed.\n\nHint Resolve add_binding_is_subst : core.\n\nLemma typ_subst_disjoint : forall S T,\n  is_subst S -> disjoint (dom S) (typ_fv (typ_subst S T)).\nProof.\n  intros; induction T; simpl in *; auto.\n  case_eq (get v S); intros.\n    use (H _ _ (binds_in H0)).\n  simpl*.\nQed.\n\nLemma typ_subst_res_fresh : forall S T T',\n  is_subst S -> typ_subst S T = T' -> disjoint (dom S) (typ_fv T').\nProof.\n  intros.\n  use (typ_subst_disjoint T H).\n  rewrite* <- H0.\nQed.\n\nLemma typ_subst_res_fresh' : forall S T v,\n  is_subst S -> typ_subst S T = typ_fvar v -> v # S.\nProof.\n  intros.\n  use (typ_subst_res_fresh _ H H0).\nQed.\n\nHint Resolve typ_subst_disjoint typ_subst_res_fresh typ_subst_res_fresh' : core.\n\nLemma binds_add_binding : forall S T0 T1 v x T,\n  typ_subst S T0 = typ_fvar v ->\n  binds x (typ_subst S T) S ->\n  binds x (typ_subst (compose (v ~ T1) S) T) (compose (v ~ T1) S).\nProof.\n  intros.\n  rewrite typ_subst_compose.\n  unfold compose.\n  apply binds_prepend.\n  apply* binds_map.\nQed.\n\nHint Resolve binds_add_binding : core.\n\nDefinition id := Env.empty (A:=typ).\n\nLemma typ_subst_id : forall T, typ_subst id T = T.\nProof.\n  intro.\n  apply* typ_subst_fresh.\nQed.\n\nLemma is_subst_id : is_subst id.\nProof.\n  unfold id, is_subst. intro; intros. simpl*.\nQed.\n\nLemma dom_remove_env : forall (A:Set) v (K:Env.env A),\n  ok K -> dom (remove_env K v) = S.remove v (dom K).\nProof.\n  induction K; simpl; intros.\n    apply eq_ext; intros; split; intro; auto.\n  destruct a.\n  inversions H.\n  destruct (v == v0).\n    subst v0.\n    rewrite remove_union.\n    rewrite remove_single. rewrite* remove_notin. rewrite* union_empty_l.\n  simpl.\n  rewrite remove_union.\n  rewrite* IHK.\n  assert (v \\notin {{v0}}) by auto.\n  rewrite* (remove_notin H0).\nQed.\n\nLemma ok_remove_env : forall (A:Set) v (E:Env.env A),\n  ok E -> ok (remove_env E v).\nProof.\n  induction E; simpl; intros. auto.\n  destruct a.\n  inversions H.\n  destruct* (v == v0).\n  apply* ok_cons.\n  clear -H4.\n  induction E; simpl. simpl in H4. auto.\n  destruct a.\n  simpl in H4.\n  destruct* (v == v1).\n  simpl. \n  apply* notin_union_l.\nQed.\n\nHint Resolve ok_remove_env : core.\n\nLemma binds_remove_env : forall (A:Set) v K x (a:A),\n  binds x a K -> x <> v -> binds x a (remove_env K v).\nProof.\n  unfold binds; induction K; simpl; intros. auto.\n  destruct a; simpl in *.\n  destruct (x == v0).\n    destruct (v == v0). subst. elim H0; auto.\n    simpl. destruct* (x == v0).\n  destruct* (v == v0).\n  simpl. destruct* (x == v0).\nQed.\n\nHint Resolve binds_remove_env : core.\n\nLemma disjoint_add_binding : forall v T S (K:kenv),\n  is_subst S -> ok K ->\n  disjoint (dom S) (dom K) ->\n  disjoint (dom (compose (v ~ T) S)) (dom (remove_env K v)).\nProof.\n  intros.\n  rewrite* dom_remove_env.\n  unfold compose.\n  rewrite dom_concat.\n  simpl; rewrite* dom_map.\nQed.\n\nHint Resolve disjoint_add_binding : core.\n\nDefinition kind_entails k k' :=\n  match k' with\n  | None => True\n  | Some c' => match k with\n               | Some c => entails c c'\n               | None => False\n               end\n  end.\n\nLemma kind_entails_well_kinded : forall k k' K T,\n  kind_entails k k' ->\n  well_kinded K k T ->\n  well_kinded K k' T.\nProof.\n  unfold kind_entails; intros.\n  inversions H0; clear H0; destruct* k'; try apply wk_any.\n  apply (wk_kind H1). apply (entails_trans H2 H).\nQed.\n\nHint Resolve kind_entails_well_kinded : core.\n\nLemma neq_notin_fv : forall v v0,\n  v <> v0 -> v \\notin (typ_fv (typ_fvar v0)).\nProof. simpl*. Qed.\n\nHint Resolve neq_notin_fv : core.\n\nSection Soundness.\n\nVariables (K':kenv) (S':subs).\n\nLemma unify_ind : forall (P : kenv -> subs -> list (typ * typ) -> Prop),\n  (is_subst S' -> P K' S' nil) ->\n  (forall h pairs K T S v t t0,\n    let S1 := compose (v ~ T) S in\n    let K1 := remove_env K v in\n    unify h pairs K1 S1 = Some (K', S') ->\n    typ_subst S t = typ_fvar v ->\n    typ_subst S t0 = T ->\n    is_subst S -> is_subst S1 ->\n    v \\notin typ_fv T -> get_kind v K = None ->\n    P K1 S1 pairs -> P K S ((t,t0)::pairs)) ->\n  (forall h pairs K S v v0 k l t t0,\n    let S1 := compose (v ~ typ_fvar v0) S in\n    let K1 := remove_env (remove_env K v) v0 & v0 ~ k in\n    unify_kinds (get_kind v K) (get_kind v0 K) = Some (k, l) ->\n    unify h (l ++ pairs) K1 S1 = Some (K', S') ->\n    typ_subst S t = typ_fvar v ->\n    typ_subst S t0 = typ_fvar v0 ->\n    is_subst S -> is_subst S1 ->\n    v <> v0 ->\n    P K1 S1 (l ++ pairs) -> P K S ((t,t0)::pairs)) ->\n  (forall h h0 K S t t0 pairs n,\n    unify0 (unify h) h0 pairs K S = Some (K', S') -> is_subst S ->\n    typ_subst S t = typ_bvar n ->\n    typ_subst S t0 = typ_bvar n ->\n    P K S pairs -> P K S ((t,t0)::pairs)) ->\n  (forall h h0 K S t t0 pairs v,\n    unify0 (unify h) h0 pairs K S = Some (K', S') -> is_subst S ->\n    typ_subst S t = typ_fvar v ->\n    typ_subst S t0 = typ_fvar v ->\n    P K S pairs -> P K S ((t,t0)::pairs)) ->\n  (forall h h0 K S t t0 pairs t1 t2 t3 t4,\n    unify0 (unify h) h0 ((t1,t3)::(t2,t4)::pairs) K S = Some (K',S') ->\n    is_subst S ->\n    typ_subst S t = typ_arrow t1 t2 ->\n    typ_subst S t0 = typ_arrow t3 t4 ->\n    P K S ((t1,t3)::(t2,t4)::pairs) -> P K S ((t,t0)::pairs)) ->\n  (forall K S t t0 pairs,\n    P K S ((t,t0)::pairs) -> P K S ((t0,t)::pairs)) ->\n  forall h pairs K S,\n    unify h pairs K S = Some (K', S') ->\n    is_subst S ->\n    P K S pairs.\nProof.\n  introv Hnil Hnv Hvars Hbv Hfv. intros Harr Hsw.\n  induction h; simpl; intros pairs K S HU HS.\n    discriminate.\n  set (h0 := pairs_size S pairs + 1) in HU. clearbody h0.\n  gen pairs; induction h0; simpl; intros.\n    discriminate.\n  destruct pairs.\n    inversions HU.\n    auto.\n  destruct p.\n  assert (Hnv1: forall v T t t0,\n    typ_subst S t = typ_fvar v -> typ_subst S t0 = T ->\n    unify_nv (unify h pairs) K S v T = Some (K',S') ->\n    P K S ((t,t0)::pairs)).\n    unfold unify_nv; simpl. introv R1 R2 H'.\n    case_rewrite R3 (S.mem v (typ_fv T)).\n    fold kind in *.\n    case_rewrite R4 (get_kind v K).\n    apply* Hnv.\n  case_rewrite R1 (typ_subst S t); case_rewrite R2 (typ_subst S t0).\n        destruct (n === n0).\n          subst n0.\n          auto*.\n        discriminate.\n       rewrite <- R1 in HU.\n       apply Hsw.\n       apply* Hnv1.\n      rewrite <- R2 in HU.\n      apply* Hnv1.\n     destruct (v == v0).\n       subst v0. auto*.\n     unfold unify_vars in HU.\n     case_rewrite R3 (unify_kinds (get_kind v K) (get_kind v0 K)).\n     destruct p.\n     apply* Hvars.\n    rewrite <- R2 in HU.\n    apply* Hnv1.\n   rewrite <- R1 in HU.\n   apply Hsw.\n   apply* Hnv1.\n  apply* Harr.\nQed.\n\nLemma unify_keep : forall h pairs K S,\n  unify h pairs K S = Some (K', S') ->\n  is_subst S ->\n  is_subst S' /\\\n  forall x T, binds x (typ_subst S T) S -> binds x (typ_subst S' T) S'.\nProof.\n  intros.\n  apply* (unify_ind\n    (fun K S _ => is_subst S' /\\\n      forall x T, binds x (typ_subst S T) S -> binds x (typ_subst S' T) S'));\n    clear H H0 h pairs K S; intros.\n    destruct H6; split2*.\n    intros. apply H7.\n    apply* binds_add_binding.\n  intros.\n  intuition.\n  apply H8. apply* binds_add_binding.\nQed.\n\nLemma binds_subst_idem : forall x T S,\n  binds x T S -> is_subst S -> binds x (typ_subst S T) S.\nProof.\n  intros.\n  use (binds_typ_subst H).\n  use (f_equal (typ_subst S) H1).\n  rewrite typ_subst_idem in H2; auto.\n  congruence.\nQed.\nHint Resolve binds_subst_idem : core.\n\nLemma typ_subst_extend : forall h pairs K S,\n  is_subst S ->\n  unify h pairs K S = Some (K', S') ->\n  extends S' S.\nProof.\n  intros.\n  destruct* (unify_keep _ _ _ H0).\n  clear H0.\n  intro.\n  induction T. simpl*.\n    remember (typ_subst S (typ_fvar v)) as T'.\n    use (f_equal (typ_subst S) HeqT').\n    rewrite typ_subst_idem in H0; auto.\n    simpl in H0.\n    case_rewrite R (get v S).\n      subst.\n      use (H2 _ _ R).\n      rewrite* (binds_typ_subst H0).\n    simpl in HeqT'. rewrite R in HeqT'. subst*.\n  simpl. congruence.\nQed.\n\nHint Resolve typ_subst_extend : core.\n\nLemma typ_size_1 : forall T, 1 <= typ_size T.\n  destruct T; simpl; omega.\nQed.\n\nLemma pairs_size_decr : forall S t t0 pairs,\n  Datatypes.S (pairs_size S pairs) < pairs_size S ((t,t0)::pairs).\nProof.\n  intros.\n  unfold pairs_size; simpl.\n  puts (typ_size_1 (typ_subst S t)).\n  puts (typ_size_1 (typ_subst S t0)).\n  omega.\nQed.\n\nLemma unify0_unify : forall h0 h K S K' S' pairs,\n  unify0 (unify h) h0 pairs K S = Some (K', S') ->\n  is_subst S ->\n  unify (Datatypes.S h) pairs K S = Some (K', S').\nProof.\n  intros.\n  simpl.\n  set (h1 := pairs_size S pairs + 1).\n  assert (pairs_size S pairs < h1) by (unfold h1; omega).\n  clearbody h1.\n  gen pairs h1; induction h0; simpl; intros. discriminate.\n  destruct h1. elimtype False; omega.\n  simpl.\n  destruct pairs. auto.\n  destruct p.\n  puts (pairs_size_decr S t t0 pairs).\n  case_rewrite R1 (typ_subst S t); case_rewrite R2 (typ_subst S t0); auto.\n      destruct (n === n0). subst.\n        apply* IHh0. omega.\n      auto.\n    destruct (v == v0). subst.\n      apply* IHh0. omega.\n    auto.\n  apply* IHh0.\n  clear IHh0 H H2; unfold pairs_size in *; simpl in *.\n  rewrite <- (typ_subst_idem t H0) in H1.\n  rewrite <- (typ_subst_idem t0 H0) in H1.\n  rewrite R1 in H1; rewrite R2 in H1. simpl in H1.\n  puts (typ_size_1 (typ_subst S t1)).\n  puts (typ_size_1 (typ_subst S t2)).\n  puts (typ_size_1 (typ_subst S t3)).\n  puts (typ_size_1 (typ_subst S t4)).\n  omega.\nQed.\n\nTheorem unify_types : forall h pairs K S,\n  unify h pairs K S = Some (K',S') ->\n  is_subst S ->\n  unifies S' pairs.\nProof.\n  intros.\n  apply* (unify_ind (fun _ _ => unifies S')); clear H H0 h K S pairs; intros;\n    intro; simpl; intros; intuition;\n    try (unfold S1 in *; inversions H8; clear H8);\n    try (poses HU (unify0_unify _ _ _ _ H H0));\n    try (inversions H5; clear H5; rewrite <- (typ_subst_extend _ _ _ H0 HU);\n         rewrite <- (typ_subst_extend _ _ _ H0 HU T2); congruence).\n        rewrite <- (typ_subst_extend _ _ _ H3 H).\n        rewrite <- (typ_subst_extend _ _ _ H3 H T2).\n        rewrite typ_subst_compose. rewrite H0.\n        simpl. destruct* (v == v).\n        rewrite typ_subst_compose.\n        rewrite* (typ_subst_fresh (v ~ typ_subst S T2)).\n        simpl*. disjoint_solve. intuition.\n      rewrite <- (typ_subst_extend _ _ _ H4 H0).\n      rewrite <- (typ_subst_extend _ _ _ H4 H0 T2).\n      do 2 rewrite typ_subst_compose. rewrite H1; rewrite H2.\n      simpl. destruct* (v == v). destruct* (v0 == v).\n    inversions H5; clear H5.\n    rewrite <- (typ_subst_extend _ _ _ H0 HU).\n    rewrite <- (typ_subst_extend _ _ _ H0 HU T2).\n    rewrite H2; rewrite H1.\n    simpl.\n    rewrite* (H3 t1 t3).\n    rewrite* (H3 t2 t4).\n  inversions H1.\n  symmetry.\n  apply* H.\nQed.\n\nLemma kind_subst_idem : forall S k,\n  is_subst S -> kind_subst S (kind_subst S k) = kind_subst S k.\nProof.\n  intros.\n  destruct k as [[kc kv kr kh]|].\n    simpl.\n    apply* kind_pi; simpl.\n    clear kh; induction kr; simpl. auto.\n    rewrite IHkr.\n    rewrite* typ_subst_idem.\n  auto.\nQed.\n\nLemma kind_subst_combine : forall S S1 S2 k,\n  (forall T, typ_subst S1 (typ_subst S2 T) = typ_subst S T) ->\n  kind_subst S1 (kind_subst S2 k) = kind_subst S k.\nProof.\n  intros.\n  destruct k as [[kc kv kr kh]|].\n    simpl; apply* kind_pi; simpl.\n    clear kv kh.\n    induction kr. auto.\n    simpl. rewrite IHkr. rewrite* H.\n  auto.\nQed.\n\nLemma binds_orig_remove_env : forall (A:Set) v x (k:A) E,\n  ok E -> binds x k (remove_env E v) -> binds x k E.\nProof.\n  unfold binds.\n  induction E; simpl; intros. auto.\n  destruct a.\n  inversions H.\n  destruct (v == v0); simpl in H0.\n    subst.\n    destruct* (x == v0).\n    subst. elim (binds_fresh H0 H5).\n  destruct* (x == v0).\nQed.\n\nLemma get_kind_subst : forall S x K,\n  get_kind x (map (kind_subst S) K) = kind_subst S (get_kind x K).\nProof.\n  unfold get_kind; intros.\n  case_eq (get x K); introv R1.\n    rewrite* (binds_map (kind_subst S) R1).\n  rewrite* (map_get_none (kind_subst S) _ _ R1).\nQed.\n\nLemma unify_kind_rel_keep : forall kr kr' uniq pairs k' l,\n  unify_kind_rel kr kr' uniq pairs = (k', l) ->\n  incl kr' k' /\\ incl pairs l.\nProof.\n  induction kr; simpl; intros. inversions H. split2*.\n  destruct a.\n  case_rewrite R (uniq a).\n    case_rewrite R1 (assoc Cstr.eq_dec a kr'); destruct* (IHkr _ _ _ _ _ H).\n  destruct* (IHkr _ _ _ _ _ H).\nQed.\n\nLemma unify_kind_rel_incl : forall kr pairs uniq S kr0 kr' pairs',\n  unify_kind_rel kr0 kr' uniq pairs' = (kr, pairs) ->\n  unifies S pairs ->\n  incl (map_snd (typ_subst S) kr0) (map_snd (typ_subst S) kr).\nProof.\n  induction kr0; intros; intros T HT. elim HT.\n  destruct T.\n  destruct a.\n  simpl in *.\n  case_rewrite R (uniq a);\n    try case_rewrite R1 (assoc Cstr.eq_dec a kr'); simpl in HT; destruct HT;\n      try solve [apply* (IHkr0 _ _ H)]; inversions H1; clear H1;\n        destruct (unify_kind_rel_keep _ _ _ _ H).\n      puts (H1 _ (assoc_sound _ _ _ R1)); clear H1.\n      assert (In (t0,t1) pairs) by auto.\n      use (H0 _ _ H1).\n      rewrite* H4.\n    apply* in_map_snd.\n  apply* in_map_snd.\nQed.\n\nLemma unify_kinds_sound : forall k k0 k1 l S,\n  unify_kinds k k0 = Some (k1, l) ->\n  unifies S l ->\n  kind_entails (kind_subst S k1) (kind_subst S k) /\\\n  kind_entails (kind_subst S k1) (kind_subst S k0).\nProof.\n  unfold unify_kinds, kind_entails.\n  intros.\n  destruct k as [[kc kv kr kh]|]; destruct k0 as [[kc0 kv0 kr0 kh0]|]; simpl.\n     destruct (Cstr.valid_dec (Cstr.lub kc kc0)); try discriminate.\n     case_eq (unify_kind_rel (kr ++ kr0) nil (Cstr.unique (Cstr.lub kc kc0))\n       nil); intros l0 l1 R1.\n     inversions H; clear H.\n     rewrite R1 in *.\n     use (unify_kind_rel_incl _ _ _ _ R1 H0).\n     destruct (proj2 (Cstr.entails_lub kc kc0 _) (Cstr.entails_refl _)).\n     split; split2*; simpl; intros;\n       rewrite R1; apply H; unfold map_snd; rewrite* map_app.\n    split2*.\n    inversions H; clear H.\n    simpl. apply entails_refl.\n   split2*.\n   inversions H; clear H.\n   simpl. apply entails_refl.\n  auto.\nQed.\n\nLemma map_remove_env : forall (A:Set) x f (E:Env.env A),\n  map f (remove_env E x) = remove_env (map f E) x.\nProof.\n  induction E; simpl in *. auto.\n  destruct a; simpl.\n  destruct (x == v); simpl*.\n  rewrite* IHE.\nQed.\n\nLemma map_map_env : forall (A:Set) f f1 f2 (E:Env.env A),\n  (forall x, f x = f1 (f2 x)) -> map f E = map f1 (map f2 E).\nProof.\n  intros; induction E; simpl. auto.\n  destruct a; simpl.\n  rewrite H.\n  rewrite* IHE.\nQed.\n\nLemma fv_in_remove_env : forall (A:Set) (fv:A->vars) x E,\n  fv_in fv (remove_env E x) << fv_in fv E.\nProof.\n  induction E; simpl; intros. auto.\n  destruct a. destruct* (x == v); simpl*.\nQed.\n\nLemma unify_kinds_subst : forall k1 k2 k3 l S,\n  unify_kinds k1 k2 = Some (k3, l) ->\n  unify_kinds (kind_subst S k1) (kind_subst S k2) =\n  Some (kind_subst S k3,\n        List.map (fun T => (typ_subst S (fst T), typ_subst S (snd T))) l).\nProof.\n  intros.\n  destruct k1 as [[kc1 kv1 kr1 kh1]|]; destruct k2 as [[kc2 kv2 kr2 kh2]|];\n    simpl in *; try solve [inversions* H].\n  destruct (Cstr.valid_dec (Cstr.lub kc1 kc2)); try discriminate.\n  inversions H; clear H.\n  unfold map_snd; rewrite <- map_app.\n  fold (map_snd (typ_subst S) (kr1++kr2)).\n  simpl.\n  refine (f_equal (@Some _) _).\n  set (kr:=@nil(Cstr.attr*typ)).\n  set (pairs:=@nil(typ*typ)).\n  assert (kr = map_snd (typ_subst S) kr) by reflexivity.\n  assert (pairs =\n    List.map (fun T => (typ_subst S (fst T), typ_subst S (snd T))) pairs)\n    by reflexivity.\n  clear kh1 kh2.\n  apply injective_projections; simpl; try apply kind_pi; simpl*;\n    pattern kr at 1; rewrite H;\n    pattern pairs at 1; rewrite H0; clear H H0;\n    gen kr pairs; induction (kr1++kr2); intros; simpl*; destruct a;\n    simpl; destruct (Cstr.unique (Cstr.lub kc1 kc2) a);\n    try rewrite* <- IHl;\n    case_eq (assoc Cstr.eq_dec a kr); intros; rewrite <- IHl;\n    try rewrite* (assoc_map _ (typ_subst S) _ _ H).\nQed.\n\nLemma well_subst_unify : forall k1 l v v0 S K h pairs,\n  unify h (l ++ pairs) (remove_env (remove_env K v) v0 & v0 ~ k1)\n    (compose (v ~ typ_fvar v0) S) = Some (K', S') ->\n  unify_kinds (get_kind v K) (get_kind v0 K) = Some (k1, l) ->\n  is_subst (compose (v ~ typ_fvar v0) S) ->\n  v # S ->\n  well_subst (remove_env (remove_env K v) v0 & v0 ~ k1)\n     (map (kind_subst S') K') S' ->\n  well_subst K (map (kind_subst S') K') S'.\nProof.\n  intros until 1; intros HU HS1 Hv WS x; intros.\n  unfold well_subst in WS.\n  poses Hext (typ_subst_extend _ _ _ HS1 H).\n  poses Hunif (unify_types _ _ _ H HS1). \n  assert (Hunif': unifies S' l) by (intro; intros; auto).\n  clear HS1 H.\n  destruct (x == v0); subst.\n    destruct* (unify_kinds_sound _ _ HU Hunif') as [_ Wk].\n    rewrite* <- (binds_get_kind H0).\n  destruct (x == v); subst.\n    assert (well_kinded (map (kind_subst S') K') (kind_subst S' k1)\n               (typ_subst S' (typ_fvar v))).\n      rewrite <- Hext.\n      rewrite* typ_subst_compose.\n      rewrite (typ_subst_fresh S); simpl*.\n      destruct* (v == v).\n    destruct* (unify_kinds_sound _ _ HU Hunif') as [Wk _].\n    rewrite* <- (binds_get_kind H0).\n  assert (x # v0 ~ k1) by simpl*.\n  use (binds_concat_fresh _ (binds_remove_env (binds_remove_env H0 n0) n) H).\nQed.\n\nLemma unify_kinds_ok : forall h pairs K S,\n  unify h pairs K S = Some (K',S') -> is_subst S ->\n  ok K -> disjoint (dom S) (dom K) ->\n  ok K' /\\ disjoint (dom S') (dom K') /\\\n  well_subst K (map (kind_subst S') K') S'.\nProof.\n  introv H H0.\n  apply* (unify_ind (fun K S pairs =>\n    ok K -> disjoint (dom S) (dom K) ->\n    ok K' /\\ disjoint (dom S') (dom K') /\\\n    well_subst K (map (kind_subst S') K') S'));\n    clear H H0 h pairs K S.\n      intuition.\n      intro; intros.\n      rewrite* typ_subst_fresh.\n      destruct* k.\n      use (binds_map (kind_subst S') H2).\n      apply* wk_kind.\n    intros until 1.\n    intros R1 R2 Hs HS1 n R3 IHh HK Dis.\n    subst S1 K1.\n    destruct* IHh.\n    intuition.\n    clear -R3 H3.\n    intro; intros.\n    destruct (Z == v).\n      subst.\n      rewrite (binds_get_kind H) in R3. subst*.\n    use (H3 _ _ (binds_remove_env H n)).\n  intros until K1.\n  intros R3 H R1 R2 HS HS1 n IHh HK Dis.\n  subst S1 K1.\n  destruct* IHh.\n      constructor. repeat apply ok_remove_env. auto.\n      rewrite* dom_remove_env.\n    simpl.\n    repeat rewrite* dom_remove_env.\n    unfold compose.\n    rewrite dom_concat. rewrite dom_map. simpl.\n    use (typ_subst_res_fresh' _ HS R2).\n  intuition.\n  subst; apply* well_subst_unify.\n  apply* typ_subst_res_fresh'.\nQed.\n\nEnd Soundness.\n\nLemma typ_subst_map_idem : forall S,\n  is_subst S -> ok S -> map (typ_subst S) S = S.\nProof.\n  intros.\n  remember S as S0.\n  pattern S0 at 1.\n  rewrite HeqS0.\n  assert (env_prop (fun T => typ_subst S T = T) S0).\n    intro; intros.\n    rewrite <- HeqS0.\n    rewrite <- (binds_typ_subst (in_ok_binds _ _ H1 H0)).\n    apply* typ_subst_idem.\n  clear HeqS0 H.\n  induction S0. auto.\n  inversions H0.\n  simpl. rewrite (H1 x a0).\n    rewrite* IHS0.\n    intro; intros.\n    apply (H1 x0 a).\n    simpl.\n    destruct* (x0 == x).\n  simpl*.\nQed.\n\nLemma typ_subst_prebind : forall v T S T1,\n  typ_subst S T = typ_subst S (typ_fvar v) ->\n  typ_subst S (typ_subst (v~T) T1) = typ_subst S T1.\nProof.\n  induction T1; intros.\n      simpl*.\n    simpl. destruct (v0 == v).\n      subst*.\n    reflexivity.\n  simpl.\n  rewrite* IHT1_1. rewrite* IHT1_2.\nQed.\n\nSection Mgu.\n\nVariables (K':kenv) (S':subs) (HS' : is_subst S').\n\nDefinition mgu_spec K S K0 S0 pairs :=\n  ok K0 ->\n  extends S' S0 ->\n  unifies S' pairs ->\n  well_subst K0 K' S' ->\n  extends S' S /\\ well_subst K K' S'.\n\nLemma get_remove_env : forall (A:Set) v (E:Env.env A),\n  ok E -> get v (remove_env E v) = None.\nProof.\n  induction E; simpl; intros. auto.\n  destruct a. destruct* (v == v0).\n    subst v0; inversions H.\n    case_eq (get v E); intros. elim (binds_fresh H0 H4). auto.\n  simpl. destruct* (v == v0). inversions* H.\nQed.\n\nLemma kind_subst_compose : forall S1 S2 k,\n  kind_subst (compose S1 S2) k = kind_subst S1 (kind_subst S2 k).\nProof.\n  intros; symmetry; apply kind_subst_combine.\n  intro; symmetry; apply* typ_subst_compose.\nQed.\n\nLemma unify_mgu_nv : forall K0 S0 pairs K S h t t0 v T,\n  let S1 := compose (v ~ T) S0 in\n  let K1 := remove_env K0 v in\n  unify h pairs K1 S1 = Some (K, S) ->\n  typ_subst S0 t = typ_fvar v ->\n  typ_subst S0 t0 = T ->\n  is_subst S0 ->\n  get_kind v K0 = None ->\n  mgu_spec K S K1 S1 pairs ->\n  mgu_spec K S K0 S0 ((t, t0) :: pairs).\nProof.\n  intros until K1; unfold K1, S1; clear K1 S1.\n  intros HU R1 R2 HS0 R4 IHh HK0 Hext Heq WS.\n  assert (BS': typ_subst S' T = typ_subst S' (typ_fvar v)).\n    rewrite <- R2. rewrite Hext. rewrite* <- (Heq t t0).\n    rewrite <- R1. rewrite* Hext.\n  assert (Hv: v # S0) by apply* typ_subst_res_fresh'.\n  assert (Dis: disjoint (dom (v ~ T)) (dom S0)) by simpl*.\n  assert (Sv: extends S' (v ~ T)).\n    intro.\n    induction T0; simpl. auto.\n      destruct (v0 == v). subst. rewrite BS'. reflexivity.\n      reflexivity.\n    congruence.\n  destruct* IHh.\n      intro. rewrite* typ_subst_compose.\n      rewrite Sv. apply Hext.\n    intro; intros. apply* Heq.\n  intro; intros.\n  destruct (Z == v).\n    subst.\n    elim (binds_fresh H).\n    fold S.elt in v.\n    rewrite* dom_remove_env.\n  apply WS.\n  apply* binds_orig_remove_env.\nQed.\n\nLemma unify_kinds_complete : forall k k0 k' S,\n  kind_entails k' (kind_subst S k) ->\n  kind_entails k' (kind_subst S k0) ->\n  exists k1, exists l,\n    unify_kinds k k0 = Some (k1, l) /\\\n    unifies S l /\\ kind_entails k' (kind_subst S k1).\nProof.\n  unfold unify_kinds, unifies.\n  intros.\n  destruct k as [[kc kv kr kh]|]; destruct k0 as [[kc0 kv0 kr0 kh0]|];\n    simpl in *;\n    try solve [esplit; esplit; intuition; elim H1].\n  destruct k' as [[kc' kv' kr' kh']|]; try contradiction.\n  destruct H. destruct H0.\n  simpl in H, H0.\n  destruct (Cstr.entails_lub kc kc0 kc').\n  use (H3 (conj H H0)).\n  use (Cstr.entails_valid H5 kv').\n  destruct* (Cstr.valid_dec (Cstr.lub kc kc0)).\n  esplit. esplit. split. reflexivity.\n  (* poses Huniq (Cstr.entails_unique H5). *)\n  clear H H0 H3 H4 H6.\n  simpl in H1, H2. clear kv kv0 kh kh0.\n  set (pairs := nil(A:=typ*typ)).\n  set (krs := nil(A:=Cstr.attr*typ)).\n  assert (forall T,\n          In T (map_snd (typ_subst S) ((kr ++ kr0) ++ krs)) -> In T kr').\n    intros.\n    unfold map_snd in H; repeat rewrite map_app in H.\n    destruct (in_app_or _ _ _ H).\n      destruct* (in_app_or _ _ _ H0).\n    elim H0.\n  clear H1 H2.\n  assert (Hunif: unifies S pairs) by (intros T1 T2 HE; elim HE).\n  unfold kind_entails, entails; simpl.\n  intros; gen pairs krs; induction (kr++kr0); simpl; intros. auto.\n  destruct a.\n  case_eq (Cstr.unique (Cstr.lub kc kc0) a); introv R.\n    puts (Cstr.entails_unique H5 R).\n    case_eq (assoc Cstr.eq_dec a krs); [intros t0 R1|intros R1].\n      assert (unifies S ((t,t0)::pairs)).\n        intro; simpl; intros.\n        destruct H1; [|auto*].\n        inversions H1; clear H1.\n        apply* (kh' a).\n        apply H.\n        right*.\n        unfold map_snd; rewrite map_app.\n        use (in_map_snd (typ_subst S) _ _ _ (assoc_sound _ _ _ R1)).\n      intuition.\n        refine (proj1 (IHl _ _ _ _) _ _ H2); auto.\n      refine (proj2 (proj2 (IHl _ _ _ _)) _ H2); auto.\n    intuition;\n      [ refine (proj1 (IHl _ _ _ _) _ _ H1)\n      | refine (proj2 (proj2 (IHl _ _ _ _)) _ H1)];\n      auto; simpl; intros;\n      unfold map_snd in *;\n      repeat rewrite map_app in *; apply H; apply* in_app_mid.\n  unfold map_snd in *.\n  intuition;\n  [ refine (proj1 (IHl _ _ _ _) _ _ H0)\n  | refine (proj2 (proj2 (IHl _ _ _ _)) _ H0)];\n  auto; simpl; intros;\n  repeat rewrite map_app in *; apply H; apply* in_app_mid.\nQed.\n\nLemma well_kinded_get_kind : forall K x,\n  well_kinded K (get_kind x K) (typ_fvar x).\nProof.\n  intros.\n  case_eq (get_kind x K); intros; auto*.\nQed.\n\nLemma well_subst_get_kind : forall K K' S x,\n  well_subst K K' S ->\n  well_kinded K' (kind_subst S (get_kind x K)) (typ_subst S (typ_fvar x)).\nProof.\n  intros.\n  case_eq (get_kind x K); intros.\n    apply H. apply* get_kind_binds.\n  apply wk_any.\nQed.\n\nLemma unify_mgu_vars : forall K0 S0 pairs K S h t t0 v v0 k l,\n  let S1 := compose (v ~ typ_fvar v0) S0 in\n  let K1 := remove_env (remove_env K0 v) v0 & v0 ~ k in\n  unify_kinds (get_kind v K0) (get_kind v0 K0) = Some (k, l) ->\n  unify h (l ++ pairs) K1 S1 = Some (K, S) ->\n  typ_subst S0 t = typ_fvar v ->\n  typ_subst S0 t0 = typ_fvar v0 ->\n  is_subst S0 -> is_subst S1 -> v <> v0 ->\n  mgu_spec K S K1 S1 (l ++ pairs) -> mgu_spec K S K0 S0 ((t, t0) :: pairs).\nProof.\n  intros until K1; unfold S1; clear S1.\n  intros R4 HU R1 R2 HS0 HS1 n IHh HK0 Hext Heq WS.\n  assert (BS': typ_subst S' (typ_fvar v0) = typ_subst S' (typ_fvar v)).\n    rewrite <- R1; rewrite <- R2.\n    repeat rewrite Hext.\n    symmetry; apply* Heq.\n  assert (Hv: v # S0) by apply* typ_subst_res_fresh'.\n  assert (Hv0: v0 # S0) by apply* typ_subst_res_fresh'.\n  assert (Dis: disjoint (dom (v ~ typ_fvar v0)) (dom S0))\n    by (clear -Hv; simpl*).\n  assert (Sv: extends S' (v ~ typ_fvar v0)).\n    intro. induction T; simpl. auto.\n      destruct (v1 == v). subst. rewrite BS'. reflexivity.\n      reflexivity.\n    congruence.\n  assert (HK1: ok K1).\n    unfold K1.\n    assert (ok (remove_env K0 v)) by auto.\n    apply (@ok_push _ _ v0 k (ok_remove_env v0 H)).\n    rewrite* dom_remove_env.\n  poses Wk (well_subst_get_kind v WS).\n  rewrite <- Sv in Wk.\n  simpl typ_subst in Wk. destruct* (v == v). clear e.\n  poses Wk0 (well_subst_get_kind v0 WS).\n  assert (Hke: forall v1, typ_subst S' (typ_fvar v0) = typ_fvar v1 ->\n               let k' := get_kind v1 K' in\n               let gk x := kind_subst S' (get_kind x K0) in\n               kind_entails k' (gk v) /\\ kind_entails k' (gk v0)).\n    intros.\n    split; [inversions Wk | inversions Wk0]; simpl*; unfold k', gk;\n      try (rewrite <- H2; simpl* );\n      rewrite <- H0; simpl in H; rewrite H in H1; inversions H1;\n      rewrite* (binds_get_kind H3).\n  assert (Hk: k = None /\\ l = nil \\/\n              exists v1, typ_subst S' (typ_fvar v0) = typ_fvar v1).\n    case_rewrite R5 (typ_subst S' (typ_fvar v0));\n    case_rewrite R6 (get_kind v0 K0);\n    simpl in Wk0 ; inversion_clear Wk0;\n    case_rewrite R7 (get_kind v K0);\n    simpl in Wk; inversion_clear Wk;\n    simpl in R4; inversion* R4.\n  destruct* IHh.\n      intro.\n      rewrite* typ_subst_compose.\n      rewrite Sv. rewrite* Hext.\n    intro; intros.\n    destruct (in_app_or _ _ _ H); clear H; try solve [apply* Heq].\n    destruct Hk as [[_ Hl]|[v1 R5]]. subst; elim H0.\n    destruct* (Hke v1); clear Hke.\n    destruct (unify_kinds_complete _ _ _ _ H H1) as [k3 [l3 [HU1 [HU2 HU3]]]].\n    rewrite R4 in HU1.\n    clearbody K1.\n    inversions HU1; clear HU1.\n    apply* HU2.\n  intro; intros.\n  destruct (Z == v0).\n    subst.\n    unfold binds in H; simpl in H; destruct* (v0 == v0).\n    clearbody K1.\n    inversions H; clear e H.\n    destruct Hk as [[Hk _]|[v1 R5]]. subst*.\n    rewrite R5.\n    destruct* (Hke v1); clear Hke.\n    destruct (unify_kinds_complete _ _ _ _ H H0) as [k3 [l3 [HU1 [HU2 HU3]]]].\n    rewrite R4 in HU1.\n    inversions HU1; clear HU1.\n    apply* kind_entails_well_kinded.\n    apply* well_kinded_get_kind.\n  destruct* k0.\n  unfold K1 in H.\n  unfold binds in H; simpl in H. destruct* (Z == v0). clear n1.\n  use (binds_orig_remove_env _ (ok_remove_env v HK0) H).\n  use (binds_orig_remove_env _ HK0 H0).\nQed.\n\nLemma unifies_tl : forall S p pairs,\n  unifies S (p::pairs) -> unifies S pairs.\nProof.\n  intros; intro; intros; apply* H.\nQed.\n\nHint Resolve unifies_tl : core.\n\nLemma unify_mgu0 : forall h pairs K0 S0 K S,\n  unify h pairs K0 S0 = Some (K,S) -> is_subst S0 ->\n  mgu_spec K S K0 S0 pairs.\nProof.\n  intros.\n  apply* (unify_ind (K':=K) (S':=S) (mgu_spec K S));\n    clear H H0 K0 S0 pairs h.\n        unfold mgu_spec; auto*.\n       intros; unfold K1, S1 in *; apply* unify_mgu_nv.\n      intros; unfold K1, S1 in *; apply* unify_mgu_vars.\n     unfold mgu_spec; intros; apply* H3.\n    unfold mgu_spec; intros; apply* H3.\n   unfold mgu_spec; intros. apply* H3.\n   assert (Heq: typ_subst S' t = typ_subst S' t0).\n     apply* H6.\n   rewrite <- (H5 t) in Heq.\n   rewrite <- (H5 t0) in Heq.\n   rewrite H1 in Heq; rewrite H2 in Heq; simpl in Heq.\n   inversions Heq.\n   intro; intros.\n   destruct H8. inversions* H8.\n   destruct* H8. inversions* H8.\n  unfold mgu_spec; intros.\n  apply* H.\n  intro; intros.\n  destruct* H4.\n  inversions H4. symmetry; apply* H2.\nQed.\n\nTheorem unify_mgu : forall h T1 T2 K0 K S,\n  unify h ((T1,T2)::nil) K0 id = Some (K, S) ->\n  ok K0 ->\n  typ_subst S' T1 = typ_subst S' T2 ->\n  well_subst K0 K' S' ->\n  (forall T3 T4,\n    typ_subst S T3 = typ_subst S T4 -> typ_subst S' T3 = typ_subst S' T4) /\\\n  well_subst K K' S'.\nProof.\n  intros.\n  destruct* (unify_mgu0 _ H is_subst_id).\n      intro. rewrite* typ_subst_id.\n    intro; simpl; intros.\n    destruct* H3.\n    inversions* H3.\n  split2*.\n  intros.\n  rewrite <- (H3 T3).\n  rewrite <- (H3 T4).\n  rewrite* H5.\nQed.\n\nEnd Mgu.\n\nDefinition all_fv S pairs :=\n  accum typ_fv S.union {} (all_types S pairs).\n\nDefinition really_all_fv S K pairs :=\n  fv_in kind_fv (map (kind_subst S) K) \\u all_fv S pairs.\n\nDefinition size_pairs S K pairs :=\n  S.cardinal (really_all_fv S K pairs).\n\nLemma typ_fv_decr : forall v T S T1,\n  v # S -> disjoint (typ_fv T) ({{v}} \\u dom S) ->\n  typ_fv (typ_subst (compose (v ~ T) S) T1) <<\n  S.remove v (typ_fv T \\u typ_fv (typ_subst S T1)).\nProof.\n  intros.\n  rewrite* typ_subst_compose.\n  induction (typ_subst S T1); simpl in *; disjoint_solve.\n  destruct* (v0 == v).\nQed.\n\nLemma kind_fv_decr : forall v T S k,\n  v # S -> disjoint (typ_fv T) ({{v}} \\u dom S) ->\n  kind_fv (kind_subst (compose (v ~ T) S) k) <<\n  S.remove v (typ_fv T \\u kind_fv (kind_subst S k)).\nProof.\n  intros.\n  unfold kind_fv.\n  destruct k as [[kc kv kr kh]|]; simpl*.\n  clear kc kv kh.\n  induction kr; simpl*.\n  sets_solve.\n  use (typ_fv_decr _ _ _ H H0 H1).\nQed.\n\nLemma fv_in_decr : forall (A:Set) v T S (E:Env.env A) fv (sub:subs -> A -> A),\n  v # S -> disjoint (typ_fv T) ({{v}} \\u dom S) ->\n  (forall a,\n    fv (sub (compose (v ~ T) S) a) << S.remove v (typ_fv T \\u fv (sub S a))) ->\n  fv_in fv (map (sub (compose (v ~ T) S)) E) <<\n  S.remove v (typ_fv T \\u fv_in fv (map (sub S) E)).\nProof.\n  intros.\n  induction E; simpl*; intros.\n  destruct a.\n  simpl.\n  use (H1 a).\nQed.\n\nLemma all_fv_decr : forall v T S pairs,\n  v # S -> disjoint (typ_fv T) ({{v}} \\u dom S) ->\n  all_fv (compose (v ~ T) S) pairs <<\n  S.remove v (all_fv S ((typ_fvar v, T) :: pairs)).\nProof.\n  unfold all_fv.\n  induction pairs; intros; simpl*.\n  rewrite* get_notin_dom.\n  sets_solve.\n    puts (typ_fv_decr _ _ _ H H0 H1).\n    rewrite* (@typ_subst_fresh S T).\n   puts (typ_fv_decr _ _ _ H H0 H2).\n   rewrite* (@typ_subst_fresh S T).\n  use (IHpairs H H0 _ H2).\n  simpl in H1.\n  rewrite get_notin_dom in H1; auto.\nQed.\n\nLemma really_all_fv_decr : forall S K pairs v T,\n  v # S -> disjoint (typ_fv T) ({{v}} \\u dom S) -> ok K ->\n  really_all_fv (compose (v ~ T) S) K pairs <<\n  S.remove v (really_all_fv S K ((typ_fvar v, T) :: pairs)).\nProof.\n  intros until T. intros Hv Dis HK.\n  unfold really_all_fv.\n  sets_solve.\n    unfold all_fv; simpl. rewrite* get_notin_dom.\n    repeat rewrite union_assoc.\n    rewrite* typ_subst_fresh.\n    forward~ (fv_in_decr _ _ K kind_fv kind_subst Hv Dis); intros.\n        apply* kind_fv_decr.\n      apply H.\n    auto*.\n  use (all_fv_decr _ _ _ Hv Dis H).\nQed.\n\nLemma cardinal_decr : forall v T S K pairs,\n  v # S -> disjoint (typ_fv T) ({{v}} \\u dom S) -> ok K ->\n  S.cardinal (really_all_fv (compose (v ~ T) S) (remove_env K v) pairs) <\n  S.cardinal (really_all_fv S K ((typ_fvar v, T) :: pairs)).\nProof.\n  intros.\n  use (really_all_fv_decr (pairs:=pairs) _ _ H H0 H1).\n  use (le_lt_n_Sm _ _ (cardinal_subset H2)).\n  rewrite cardinal_remove in H3.\n    eapply le_lt_trans; try apply H3.\n    apply cardinal_subset.\n    unfold really_all_fv. rewrite map_remove_env.\n    sets_solve.\n    apply S.union_2. refine (fv_in_remove_env _ _ _ H4).\n    auto.\n  unfold really_all_fv, all_fv; simpl.\n  rewrite* get_notin_dom.\nQed.\n\nLemma size_pairs_decr : forall v T K S pairs,\n  v # S -> ok K ->\n  disjoint (typ_fv T) ({{v}} \\u dom S) ->\n  size_pairs (compose (v ~ T) S) (remove_env K v) pairs <\n  size_pairs S K ((typ_fvar v,T)::pairs).\nProof.\n  intros.\n  unfold size_pairs.\n  apply* cardinal_decr.\nQed.\n\nLemma size_pairs_comm : forall S K T1 T2 pairs,\n  size_pairs S K ((T1,T2)::pairs) = size_pairs S K ((T2,T1)::pairs).\nProof.\n  intros; unfold size_pairs, really_all_fv, all_fv; simpl.\n  rewrite (union_assoc (typ_fv (typ_subst S T1))).\n  rewrite (union_comm (typ_fv (typ_subst S T1))).\n  repeat rewrite union_assoc. auto.\nQed.\n\nLemma size_pairs_decr' : forall S0 K0 t t0 pairs h v,\n  is_subst S0 -> ok K0 ->\n  S.mem v (typ_fv (typ_subst S0 t0)) = false ->\n  size_pairs S0 K0 ((t, t0) :: pairs) < S h ->\n  typ_subst S0 t = typ_fvar v ->\n  size_pairs (compose (v ~ typ_subst S0 t0) S0) (remove_env K0 v) pairs < h.\nProof.\n  intros.\n  use (typ_subst_res_fresh' _ H H3).\n  use (typ_subst_disjoint t0 H).\n  eapply lt_le_trans.\n    apply* size_pairs_decr.\n  replace (size_pairs S0 K0 ((typ_fvar v, typ_subst S0 t0) :: pairs))\n    with (size_pairs S0 K0 ((t, t0) :: pairs)).\n    omega.\n  unfold size_pairs, really_all_fv, all_fv; simpl.\n  rewrite* get_notin_dom.\n  rewrite H3.\n  rewrite* typ_subst_idem.\nQed.\n\nLemma all_types_app : forall S l1 l2,\n  all_types S (l1 ++ l2) = all_types S l1 ++ all_types S l2.\nProof.\n  intros; induction l1; simpl. auto.\n  rewrite* <- IHl1.\nQed.\n\nLemma get_kind_fv_in : forall S v K,\n  kind_fv (kind_subst S (get_kind v K)) << fv_in kind_fv (map (kind_subst S) K).\nProof.\n  induction K; simpl. apply subset_refl.\n  unfold get_kind; simpl.\n  destruct a. destruct (v == v0).\n    simpl*.\n  fold (get_kind v K).\n  simpl*.\nQed.\n\nLemma in_typ_fv : forall t l,\n  In t l -> typ_fv t << typ_fv_list l.\nProof.\n  induction l; simpl; intros H x Hx. elim H.\n  destruct* H.\n  subst; simpl*.\nQed.\n\nLemma unify_kinds_fv : forall k k0 k1 l S,\n  unify_kinds k k0 = Some (k1, l) ->\n  kind_fv (kind_subst S k1) \\u all_fv S l <<\n  kind_fv (kind_subst S k) \\u kind_fv (kind_subst S k0).\nProof.\n  unfold unify_kinds; intros.\n  destruct k as [[kc kv kr kh]|].\n    destruct k0 as [[kc0 kv0 kr0 kh0]|].\n      destruct (Cstr.valid_dec (Cstr.lub kc kc0)); try discriminate.\n      inversions H; clear H.\n      simpl.\n      unfold kind_fv; simpl.\n      repeat rewrite list_snd_map_snd.\n      rewrite <- fv_list_map.\n      unfold list_snd; rewrite <- map_app.\n      set (pairs := nil(A:=typ*typ)).\n      set (kr' := nil(A:=Cstr.attr*typ)).\n      intros x Hx.\n      rewrite <- union_empty_r.\n      replace {} with (typ_fv_list (List.map (typ_subst S) (list_snd kr')))\n        by reflexivity.\n      rewrite <- union_empty_r.\n      replace {} with (all_fv S pairs) by reflexivity.\n      clearbody pairs kr'.\n      rewrite <- map_app.\n      gen pairs kr'; induction (kr ++ kr0); simpl; intros.\n        rewrite <- union_assoc; auto with sets.\n      destruct a; simpl in *.\n      case_rewrite R (Cstr.unique (Cstr.lub kc kc0) a).\n        case_rewrite R1 (assoc Cstr.eq_dec a kr');\n          poses Hsub (IHl _ _ Hx); clear -Hsub R1.\n          unfold all_fv in *; simpl in *.\n          sets_solve.\n          puts (assoc_sound _ _ _ R1).\n          puts (in_map_snd (typ_subst S) _ _ _ H0).\n          rewrite <- combine_fst_snd in H1.\n          puts (in_combine_r _ _ _ _ H1).\n          rewrite list_snd_map_snd in H2.\n          use (in_typ_fv _ _ H2 H).\n        simpl in Hsub. auto.\n      poses Hsub (IHl _ _ Hx); clear -Hsub.\n      simpl in Hsub; auto.\n    inversions H.\n    unfold kind_fv, all_fv; simpl*.\n  inversions H.\n  unfold kind_fv, all_fv; simpl*.\nQed.\n\nLemma all_fv_app : forall S l1 l2,\n  all_fv S (l1 ++ l2) = all_fv S l1 \\u all_fv S l2.\nProof.\n  intros.\n  unfold all_fv.\n  induction l1; simpl. rewrite* union_empty_l.\n  rewrite IHl1.\n  repeat rewrite union_assoc. auto.\nQed.\n\nLemma size_pairs_decr_vars : forall S0 K0 t t0 pairs h v v0 x0 l,\n  is_subst S0 -> ok K0 ->\n  size_pairs S0 K0 ((t, t0) :: pairs) < S h ->\n  typ_subst S0 t = typ_fvar v ->\n  typ_subst S0 t0 = typ_fvar v0 ->\n  v <> v0 ->\n  unify_kinds (get_kind v K0) (get_kind v0 K0) = Some (x0, l) ->\n  size_pairs (compose (v ~ typ_fvar v0) S0)\n    (remove_env (remove_env K0 v) v0 & v0 ~ x0) (l ++ pairs) < h.\nProof.\n  intros.\n  use (typ_subst_res_fresh' _ H H3).\n  poses Hv (typ_subst_res_fresh' _ H H2).\n  use (typ_subst_disjoint t0 H).\n  eapply lt_le_trans; try apply (lt_n_Sm_le _ _ H1).\n  clear H1.\n  unfold size_pairs.\n  assert (v \\in really_all_fv S0 K0 ((t,t0)::pairs)).\n    unfold really_all_fv, all_fv.\n    simpl. rewrite H2. simpl*.\n  rewrite <- (cardinal_remove H1). clear H1.\n  simpl.\n  set (S := compose (v ~ typ_fvar v0) S0).\n  poses Hfv (unify_kinds_fv _ _ S H5).\n  apply le_lt_n_Sm.\n  apply cardinal_subset.\n  sets_solve.\n  replace (really_all_fv S0 K0 ((t, t0) :: pairs))\n    with (really_all_fv S0 K0 ((typ_fvar v, typ_fvar v0) :: pairs)).\n    apply* really_all_fv_decr.\n    fold S.\n    unfold really_all_fv in *.\n    simpl in *.\n    rewrite all_fv_app in Hy.\n    do 2 rewrite map_remove_env in Hy.\n    sets_solve; try use (get_kind_fv_in _ _ _ H1).\n    apply S.union_2.\n    refine (fv_in_remove_env _ v _ _); auto.\n    refine (fv_in_remove_env _ v0 _ _); auto.\n  unfold really_all_fv, all_fv.\n  rewrite <- H2; rewrite <- H3.\n  simpl.\n  repeat rewrite* typ_subst_idem.\nQed.\n\nLemma typ_subst_no_cycle : forall v S T,\n  v \\in typ_fv T ->\n  1 < typ_size T ->\n  typ_size (typ_subst S (typ_fvar v)) < typ_size (typ_subst S T).\nProof.\n  induction T; intros. elim (in_empty H).\n    simpl in H0. omega.\n  simpl in H.\n  clear H0.\n  assert (forall T, v \\in typ_fv T -> T = T1 \\/ T = T2 ->\n             typ_size (typ_subst S (typ_fvar v)) <\n             typ_size (typ_subst S (typ_arrow  T1 T2))).\n    intros.\n    case_eq (typ_size T); intros. destruct T; discriminate.\n    destruct n. destruct T. elim (in_empty H0).\n        rewrite (S.singleton_1 H0) in H1.\n        destruct H1; subst; simpl; omega.\n      destruct T3; simpl in H2; omega.\n    assert (typ_size (typ_subst S (typ_fvar v)) < typ_size (typ_subst S T)).\n      assert (1 < typ_size T) by omega.\n      destruct H1; subst*.\n    destruct H1; subst; simpl in *; omega.\n  destruct (S.union_1 H); apply* (H0 _ H1).\nQed.\n\nSection Completeness.\n\nVariables (K:kenv) (S:subs).\n\nDefinition complete_spec S0 K0 pairs h :=\n  is_subst S0 -> ok K0 ->\n  extends S S0 ->\n  unifies S pairs ->\n  well_subst K0 K S ->\n  size_pairs S0 K0 pairs < h ->\n  unify h pairs K0 S0 <> None.\n\nLemma unify_complete_nv : forall pairs K0 S0 v T h t t0,\n  typ_subst S0 t = typ_fvar v ->\n  typ_subst S0 t0 = T ->\n  size_pairs S0 K0 ((t,t0)::pairs) < Datatypes.S h ->\n  is_subst S0 -> ok K0 ->\n  well_subst K0 K S ->\n  (forall K0 S0, complete_spec K0 S0 pairs h) ->\n  extends S S0 ->\n  unifies S ((t, t0) :: pairs) ->\n  (forall x, T <> typ_fvar x) ->\n  unify_nv (unify h pairs) K0 S0 v T <> None.\nProof.\n  intros until t0; intros R1 R2 Hsz HS0 HK0 WS IHh Hext Heq HT.\n  unfold unify_nv.\n  assert (In (t,t0) ((t,t0)::pairs)) by simpl*.\n  use (Heq _ _ H); clear H.\n  rewrite <- Hext in H0; rewrite R1 in H0.\n  rewrite <- (Hext t0) in H0; rewrite R2 in H0.\n  case_eq (S.mem v (typ_fv T)); intros.\n    elimtype False.\n    use (S.mem_2 H).\n    clear -H0 H1 HT.\n    destruct T. elim (in_empty H1).\n      elim (HT v); rewrite* (S.singleton_1 H1).\n    assert (1 < typ_size (typ_arrow T1 T2)).\n      destruct T1; simpl; omega.\n    use (typ_subst_no_cycle S _ H1 H).\n    rewrite H0 in H2; omega.\n  intro.\n  case_rewrite R3 (get_kind v K0).\n    poses Wk (WS _ _ (get_kind_binds _ _ R3)).\n    rewrite H0 in Wk.\n    simpl in Wk; inversions Wk.\n    clear -H3 HT.\n    destruct (typ_subst S0 t0); try discriminate.\n    elim (HT v). auto.\n  rewrite <- R2 in H.\n  use (size_pairs_decr' HS0 HK0 H Hsz R1).\n  rewrite R2 in H2.\n  use (typ_subst_res_fresh' _ HS0 R1).\n  rewrite R2 in H.\n  revert H1; apply* IHh; clear IHh.\n      intro. rewrite* typ_subst_compose.\n      rewrite typ_subst_prebind. apply Hext. congruence.\n    intro; auto*.\n  clear H0.\n  intro; intros.\n  destruct k; try (simpl; apply wk_any).\n  destruct (v == Z).\n    elim (binds_fresh H0).\n    rewrite* dom_remove_env. apply* S.remove_1.\n  apply WS.\n  apply* binds_orig_remove_env.\nQed.\n\nLemma well_kinded_kind_entails: forall K k x,\n  well_kinded K k (typ_fvar x) -> kind_entails (get_kind x K) k.\nProof.\n  intros; unfold kind_entails.\n  inversions H. auto.\n  rewrite* (binds_get_kind H1).\nQed.\n\nLemma unify_complete_vars : forall h t t0 pairs K0 S0 v v0,\n  is_subst S0 -> ok K0 ->\n  extends S S0 ->\n  unifies S ((t, t0) :: pairs) ->\n  well_subst K0 K S ->\n  size_pairs S0 K0 ((t, t0) :: pairs) < Datatypes.S h ->\n  typ_subst S0 t = typ_fvar v ->\n  typ_subst S0 t0 = typ_fvar v0 ->\n  v <> v0 ->\n  (forall pairs K0 S0, complete_spec S0 K0 pairs h) ->\n  match unify_vars K0 v v0 with\n  | Some (pair K' pairs0) =>\n    unify h (pairs0 ++ pairs) K' (compose (v ~ typ_fvar v0) S0)\n  | None => None (A:=kenv * subs)\n  end <> None.\nProof.\n  intros until v0; intros HS0 HK0 Hext Heq WS Hsz R1 R2 n IHh.\n  unfold unify_vars.\n  poses Hv (typ_subst_res_fresh' _ HS0 R1).\n  poses Wk (well_subst_get_kind v WS).\n  poses Wk0 (well_subst_get_kind v0 WS).\n  set (S0' := compose (v ~ typ_fvar v0) S0) in *.\n  assert (HS0': is_subst S0') by (unfold S0'; auto*).\n  assert (HK0': forall y, ok (remove_env (remove_env K0 v) v0 & v0 ~ y)).\n    use (ok_remove_env v HK0).\n    constructor. apply* ok_remove_env.\n    rewrite* dom_remove_env.\n  assert (Hext': forall T, typ_subst S (typ_subst S0' T) = typ_subst S T).\n    intros. unfold S0'. rewrite* typ_subst_compose.\n    rewrite typ_subst_prebind. apply Hext.\n    rewrite <- R1; rewrite <- R2.\n    symmetry; repeat rewrite Hext; apply* Heq.\n  assert (Sv_Sv0 : typ_subst S (typ_fvar v) = typ_subst S (typ_fvar v0)).\n    rewrite <- R1; rewrite <- R2.\n    repeat rewrite Hext. apply* Heq.\n  assert (get_kind v K0 = None /\\ get_kind v0 K0 = None \\/\n        exists v1, typ_subst S (typ_fvar v0) = typ_fvar v1\n          /\\ kind_entails (get_kind v1 K) (kind_subst S (get_kind v K0))\n          /\\ kind_entails (get_kind v1 K) (kind_subst S (get_kind v0 K0))).\n    case_rewrite R3 (get_kind v0 K0).\n      inversions Wk0. right*; exists x. rewrite H0; split2*.\n      simpl in Wk0; rewrite <- H0 in Wk0.\n      rewrite Sv_Sv0 in Wk; simpl in Wk; rewrite <- H0 in Wk.\n      split; apply* well_kinded_kind_entails.\n    case_rewrite R4 (get_kind v K0).\n      inversions Wk. right*; exists x.\n      rewrite <- Sv_Sv0; rewrite H0.\n      split2*.\n      split; apply well_kinded_kind_entails.\n      rewrite* H0.\n      apply wk_any.\n    left*.\n  destruct H as [[G G0]|[v1 [Hv1 [KEv KEv0]]]].\n    rewrite G; rewrite G0.\n    simpl unify_kinds. lazy iota beta.\n    apply* IHh.\n        intro; auto*.\n      intro; intros.\n      binds_cases H.\n        use (binds_orig_remove_env _ (ok_remove_env v HK0) B).\n        destruct (Z == v).\n          subst. elim (binds_fresh H).\n          rewrite dom_remove_env. apply S.remove_1. reflexivity. auto.\n        use (binds_orig_remove_env _ HK0 H).\n      subst. apply wk_any.\n    unfold S0'. apply* size_pairs_decr_vars.\n    rewrite G; rewrite G0; reflexivity.\n  destruct (unify_kinds_complete _ _ _ _ KEv KEv0)\n    as [k1 [l [HU [Heql KEk1]]]].\n  rewrite HU.\n  apply* IHh.\n      intro; intros. destruct* (in_app_or _ _ _ H).\n    intro; intros.\n    binds_cases H.\n      apply WS.\n      apply* binds_orig_remove_env.\n      apply* binds_orig_remove_env.\n    subst.\n    rewrite Hv1.\n    case_rewrite R3 (get_kind v1 K).\n      destruct* k1.\n    destruct* (kind_subst S k1).\n  unfold S0'; apply* size_pairs_decr_vars.\nQed.\n\nLemma size_pairs_tl : forall S K t t0 pairs,\n  size_pairs S K pairs <= size_pairs S K ((t,t0)::pairs).\nProof.\n  unfold size_pairs, really_all_fv, all_fv; simpl.\n  intros. apply* cardinal_subset.\nQed.\n\nLemma unify_complete0 : forall h pairs K0 S0,\n  complete_spec S0 K0 pairs h.\nProof.\n  induction h.\n    intros; intro; intros; elimtype False; omega.\n  intros; intros HS0 HK0 Hext Heq WS Hsz.\n  simpl.\n  set (h0 := pairs_size S0 pairs + 1).\n  assert (Hsz0: pairs_size S0 pairs < h0) by (unfold h0; omega).\n  clearbody h0.\n  gen pairs; induction h0; intros.\n    elimtype False; omega.\n  destruct pairs.\n    intro; discriminate.\n  destruct p.\n  simpl unify0.\n  assert (Heq0: unifies S pairs) by (intro; auto*).\n  case_eq (typ_subst S0 t); introv R1; case_eq (typ_subst S0 t0); introv R2.\n          destruct (n === n0).\n           subst.\n           apply* (IHh0 pairs).\n             puts (size_pairs_tl S0 K0 t t0 pairs). omega.\n           puts (pairs_size_decr S0 t t0 pairs). omega.\n          assert (In (t,t0) ((t,t0)::pairs)) by simpl*.\n          poses Ht (Heq _ _ H).\n          rewrite <- Hext in Ht; rewrite R1 in Ht.\n          rewrite <- (Hext t0) in Ht; rewrite R2 in Ht.\n          simpl in Ht. inversions* Ht.\n         rewrite size_pairs_comm in Hsz.\n         apply* (unify_complete_nv R2 R1 Hsz).\n           intro; simpl; intros. destruct H; subst.\n             inversions H; symmetry; apply* Heq.\n           apply* Heq.\n         intros x Hx; discriminate.\n        assert (In (t,t0) ((t,t0)::pairs)) by simpl*.\n        poses Ht (Heq _ _ H).\n        rewrite <- Hext in Ht; rewrite R1 in Ht.\n        rewrite <- (Hext t0) in Ht; rewrite R2 in Ht.\n        simpl in Ht; inversions Ht.\n       apply* (unify_complete_nv R1 R2 Hsz).\n       intros x Hx; discriminate.\n      destruct (v == v0).\n       subst.\n       apply* (IHh0 pairs).\n         puts (size_pairs_tl S0 K0 t t0 pairs). omega.\n       puts (pairs_size_decr S0 t t0 pairs). omega.\n      apply* unify_complete_vars.\n     apply* unify_complete_nv.\n     intro; discriminate.\n    assert (In (t,t0) ((t,t0)::pairs)) by auto.\n    poses E (Heq _ _ H).\n    rewrite <- (Hext t) in E. rewrite R1 in E.\n    rewrite <- (Hext t0) in E. rewrite R2 in E.\n    discriminate.\n   rewrite size_pairs_comm in Hsz.\n   apply* unify_complete_nv.\n     intro; simpl; intros. destruct H; subst.\n       inversions H; symmetry; apply* Heq.\n     apply* Heq.\n   intro; discriminate.\n  apply* IHh0.\n    clear IHh Hsz; intro; intros.\n    assert (In (t,t0) ((t,t0)::pairs)) by auto.\n    use (Heq _ _ H0).\n    rewrite <- (Hext t) in H1.\n    rewrite <- (Hext t0) in H1.\n    rewrite R1 in H1; rewrite R2 in H1.\n    simpl in H1; inversions H1.\n    simpl in H; destruct H. inversions* H.\n    destruct H. inversions* H.\n    apply* Heq.\n   eapply le_lt_trans; [|apply Hsz].\n   unfold size_pairs, really_all_fv, all_fv.\n   simpl.\n   rewrite <- (typ_subst_idem t HS0).\n   rewrite <- (typ_subst_idem t0 HS0).\n   rewrite R1; rewrite R2; simpl.\n   rewrite (union_assoc (typ_fv (typ_subst S0 t3))).\n   rewrite (union_comm (typ_fv (typ_subst S0 t3))).\n   repeat rewrite union_assoc. \n   omega.\n  eapply lt_le_trans; [|apply lt_n_Sm_le; apply Hsz0].\n  unfold pairs_size; simpl.\n  rewrite <- (typ_subst_idem t HS0).\n  rewrite <- (typ_subst_idem t0 HS0).\n  rewrite R1; rewrite R2; simpl.\n  omega.\nQed.\n\nTheorem unify_complete : forall T1 T2 K0,\n  ok K0 -> well_subst K0 K S ->\n  typ_subst S T1 = typ_subst S T2 ->\n  unify (1 + size_pairs id K0 ((T1,T2)::nil)) ((T1,T2)::nil) K0 id <> None.\nProof.\n  intros.\n  apply* unify_complete0.\n      apply is_subst_id.\n    intro; rewrite* typ_subst_id.\n  intro; intros; simpl in H2; destruct* H2.\n  inversions* H2.\nQed.\n\nEnd Completeness.\n\nEnd MkUnify.", "meta": {"author": "garrigue", "repo": "certint", "sha": "ca94fba3e87f843ee1b7666e3bdbf7900029e0ec", "save_path": "github-repos/coq/garrigue-certint", "path": "github-repos/coq/garrigue-certint/certint-ca94fba3e87f843ee1b7666e3bdbf7900029e0ec/ML_SP_Unify.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2584233917855667}}
{"text": "Require Export MinBFTprops2.\nRequire Export MinBFTsame.\nRequire Export MinBFTass_mon.\nRequire Export MinBFTass_tlearn.\nRequire Export MinBFTass_uniq.\nRequire Export MinBFTass_new.\nRequire Export MinBFTass_tknew.\nRequire Export ComponentAxiom.\n\n\nSection MinBFTagreement.\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 agreement :\n    forall (eo : EventOrdering) (e1 e2 : Event) r1 r2 i l1 l2,\n      AXIOM_authenticated_messages_were_sent_or_byz eo MinBFTsys\n      -> In (send_accept (accept r1 i) l1) (M_output_sys_on_event MinBFTsys e1)\n      -> In (send_accept (accept r2 i) l2) (M_output_sys_on_event MinBFTsys e2)\n      -> r1 = r2.\n  Proof.\n    introv sendbyz send1 send2.\n    applydup in_output_implies_is_replica in send1 as isrep1.\n    applydup in_output_implies_is_replica in send2 as isrep2.\n\n    unfold is_replica in *.\n    destruct isrep1 as [i1 isrep1].\n    destruct isrep2 as [i2 isrep2].\n    unfold M_output_sys_on_event in send1; rewrite isrep1 in send1; simpl in send1.\n    unfold M_output_sys_on_event in send2; rewrite isrep2 in send2; simpl in send2.\n\n    applydup @accepted_counter_if_know_UI_primary in send1 as statea.\n    applydup @accepted_counter_if_know_UI_primary in send2 as stateb.\n    exrepnd.\n\n    applydup preserves_view_init_ls in statea0 as eqv1; auto.\n    applydup preserves_view_init_ls in stateb0 as eqv2; auto.\n    rewrite eqv1, eqv2 in *.\n    clear eqv1 eqv2.\n\n    applydup M_run_ls_on_event_MinBFT_to_components in statea0; repnd; auto;[].\n    applydup M_run_ls_on_event_MinBFT_to_components in stateb0; repnd; auto;[].\n\n    pose proof (request_data_was_verified e1 s4 s3 initial_view r1 ui0) as ka.\n    repeat (autodimp ka hyp); try (complete (eexists; eauto)); exrepnd;[].\n\n    pose proof (request_data_was_verified e2 s2 s1 initial_view r2 ui) as kb.\n    repeat (autodimp kb hyp); try (complete (eexists; eauto)); exrepnd;[].\n\n    assert (ex_node_e e1) as ex1 by (unfold ex_node_e; allrw; simpl; eauto).\n    assert (ex_node_e e2) as ex2 by (unfold ex_node_e; allrw; simpl; eauto).\n\n    pose proof (DERIVED_RULE_trusted_knowledge_unique3_ex_true\n                  (MkEventN e1 ex1) (MkEventN e2 ex2) (MkEventN e2 ex2)\n                  [] []\n                  (MinBFTprimary initial_view)\n                  ui0\n                  ui\n                  (ui2counter ui0)\n                  (ui2counter ui)\n                  (minbft_data_rdata (request_data initial_view r1 ui0))\n                  (minbft_data_rdata (request_data initial_view r2 ui))) as knc.\n    unfold rule_true in knc; simpl in knc.\n    repeat (autodimp knc hyp); eauto 2 with minbft;[|].\n\n    { Opaque ASSUMPTION_trusted_learns_if_gen.\n      Opaque ASSUMPTION_trusted_knew_or_learns_or_gen.\n      Opaque ASSUMPTION_monotonicity.\n      Opaque ASSUMPTION_generates_new.\n      Opaque ASSUMPTION_disseminate_unique.\n      introv vt vd vc vn xx yy zz.\n      induction es using Vector.caseS'; simpl in *.\n      clear vt vd vc vn es.\n      repndors; subst; unfold seq_concl, seq_event in *;\n        simpl in *; introv; simpl in *; tcsp;\n          try (complete (unfold data_is_owned_by; minbft_simp; allrw; auto));\n          try (complete (apply ASSUMPTION_trusted_learns_if_gen_true; auto; destruct h0; auto));\n          try (complete (apply ASSUMPTION_trusted_knew_or_learns_or_gen_true; auto; destruct h0; auto));\n          try (complete (apply ASSUMPTION_monotonicity_true; auto; destruct h0; auto));\n          try (complete (apply ASSUMPTION_disseminate_unique_true; auto; destruct h0; auto));\n          try (complete (apply ASSUMPTION_generates_new_true; auto; destruct h0; auto));\n          try (complete (eexists; simpl;allrw; simpl; eauto));\n          try (complete (repeat (eexists; dands; eauto)));\n          try (complete (allrw; auto));\n          try (complete (rewrite (state_usig_same_keys e1) in ka; auto; rewrite isrep1 in ka;\n                         unfold generated_for; simpl; dands; auto; introv xx; ginv; eexists; eauto));\n          try (complete (rewrite (state_usig_same_keys e2) in kb; auto; rewrite isrep2 in kb;\n                         unfold generated_for; simpl; dands; auto; introv xx; ginv; eexists; eauto)). }\n\n    unfold sequent_true in knc; simpl in knc; repeat (autodimp knc hyp); tcsp;[].\n    inversion knc; subst; subst; auto.\n  Qed.\n\nEnd MinBFTagreement.\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/MinBFTagreement.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819874558604, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.25831172334201086}}
{"text": "From cap_machine Require Export rules_binary_base rules_IsPtr.\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_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_IsPtr Ep K pc_p pc_g pc_b pc_e pc_a w dst src regs :\n    decodeInstrW w = IsPtr 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 (IsPtr 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', ⤇ fill K (of_val retv) ∗ ⌜ IsPtr_spec regs dst src regs' 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. unfold regs_of in Hri.\n    destruct (Hri dst) as [wdst [H'dst Hdst]]. by set_solver+.\n\n    destruct (Hri src) as [wsrc [Hwsrc Hwsrc']]; [set_solver+|]. simpl in Hwsrc'.\n\n    assert ((c, σ2) = updatePC (update_reg (σr, σm) dst (match wsrc with inl _ => inl 0%Z | inr _ => inl 1%Z end))) as HH.\n    { rewrite -Hstep /= /RegLocate Hwsrc'.\n      destruct wsrc; reflexivity. }\n    rewrite /update_reg /= in HH.\n\n    destruct (incrementPC (<[ dst := (match wsrc with inl _ => inl 0%Z | inr _ => inl 1%Z end) ]> 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 ((regspec_heap_update_inSepM _ _ _ dst (match wsrc with inl _ => inl 0%Z | inr _ => inl 1%Z end)) with \"Hown Hmap\") as \"[Hown Hmap]\"; eauto.\n      iExists FailedV,_. iMod (exprspec_mapsto_update _ _ (fill K (Instr Failed)) with \"Hown Hj\") as \"[Hown Hj]\".\n      iFrame.\n      iMod (\"Hclose\" with \"[Hown]\") as \"_\".\n      { iNext. iExists _,_;iFrame. iPureIntro. eapply rtc_r;eauto.\n        simpl. prim_step_from_exec.\n      }\n      iModIntro. iPureIntro. econstructor; eauto.\n      destruct wsrc; simpl in *; auto.\n    }\n\n    eapply (incrementPC_success_updatePC _ σm) in H'regs'\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.\n    iMod ((regspec_heap_update_inSepM _ _ _ dst (match wsrc with inl _ => inl 0%Z | inr _ => inl 1%Z end)) with \"Hown Hmap\") as \"[Hown Hmap]\"; eauto.\n    iMod ((regspec_heap_update_inSepM _ _ _ PC (inr (p', g', b', e', a_pc'))) 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    }\n    iModIntro. iPureIntro. econstructor; eauto.\n    destruct wsrc; simpl in *; auto.\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_IsPtr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.25831171137523523}}
{"text": "Require Import Morphisms Base BaseProps Cartesian Equipotence Ordinal.\n\nRecord small U x : Prop := {\n  small_wtn : V;\n  small_fun : V;\n  small_mem : small_wtn ∈ U;\n  small_inj : injection_def x small_wtn small_fun\n}.\n\nLemma small_included_compat : forall U x y, small U x -> y ⊆ x -> small U y.\nProof.\nintros U x y [w f Hw Hf] Hm.\npose (fr := comprehension f (fun p => exists u, exists v, p ≅ tuple u v /\\ u ∈ y)).\nassert (Hfr : forall u v, tuple u v ∈ fr <-> (tuple u v ∈ f /\\ u ∈ y)).\n{ intros u v; split; intros H.\n  + apply comprehension_spec in H; [|repeat intro; repeat (f_equiv; intro); repeat f_equiv; assumption].\n    destruct H as [? [? [? [Heq ?]]]].\n    split; [assumption|apply tuple_inj_l in Heq; rewrite Heq; intuition].\n  + apply comprehension_spec; [repeat intro; repeat (f_equiv; intro); repeat f_equiv; assumption|].\n    split; [now intuition|].\n    exists u, v; split; intuition.\n}\nexists w fr; [assumption|]; destruct Hf as [Hf1 Hf2 Hf3]; split.\n+ intros u Hu.\n  destruct (Hf1 u) as [v [Hv Hp]]; [eapply mem_included_compat; eassumption|].\n  exists v; split; [assumption|].\n  apply Hfr; now intuition.\n+ intros u v1 v2 Hv1 Hv2; apply Hfr in Hv1; apply Hfr in Hv2.\n  eapply Hf2; intuition eauto.\n+ intros u1 u2 v Hu1 Hu2; apply Hfr in Hu1; apply Hfr in Hu2.\n  eapply Hf3; intuition eauto.\nQed.\n\n(* Lemma toto : forall x, small omega x ->\n  (forall y, y ∈ x -> small omega y) -> small omega (union x).\nProof.\nintros x [n f Hn Hf] Hm.\napply omega_spec in Hn; destruct Hn as [N Hn].\nassert (Hdf : forall α, α ∈ x -> exists p, app f α ≅ ordinal_of_nat p).\n{ intros α Hα; destruct Hf as [Hf1 Hf2 Hf3].\n  destruct (Hf1 _ Hα) as [p [Hp Hf]]; rewrite Hn in Hp.\n  assert (HP : exists P, p ≅ ordinal_of_nat P).\n  { clear - Hp; revert p Hp; induction N; intros p Hp.\n    + apply empty_spec in Hp; contradiction.\n    + simpl in Hp; apply cup_spec in Hp; destruct Hp as [Hp|Hp].\n      - apply IHN; assumption.\n      - apply singleton_spec in Hp; exists N; assumption. }\n  destruct HP as [P HP]; exists P; rewrite <- HP.\n  admit. }\n\n\n\nassert (Hf : exists g, forall α, α ∈ x -> g α).\npose (size := fun x => union (comprehension omega (fun m => tuple x m ∈ f))).\npose (M := union (collection x size)).\nassert (Hsize : forall α, α ∈ x -> size α ∈ omega).\n{ intros α Hα; destruct (Hm _ Hα) as [p F Hp HF].\n  apply omega_spec exists p.\n\n\nrevert x n f Hn Hf Hm; induction N; intros x n f Hn Hf Hm.\n+ simpl ordinal_of_nat in Hn.\n  assert (Hrw : x ≅ empty).\n  { apply extensionality; apply included_spec; intros z Hz.\n    - destruct Hf as [Hf _ _]; specialize (Hf _ Hz).\n      destruct Hf as [e [He _]]; rewrite Hn in He.\n      apply empty_spec in He; contradiction.\n    - apply empty_spec in Hz; contradiction. }\n  admit.\n+ simpl ordinal_of_nat in Hn; unfold successor in Hn.\n  assert (Hrw : exists y z, x ≅ cup (singleton y) z). *)\n\nDefinition orthogonal x y := forall z1 z2, z1 ∈ cap x y -> z2 ∈ cap x y -> z1 ≅ z2.\n\nDefinition web A := union A.\n\nRecord coherent_def A : Prop := {\n  coherent_def_bin : forall x,\n    (forall x1 x2, x1 ∈ x -> x2 ∈ x -> cup x1 x2 ∈ A) -> union x ∈ A;\n  coherent_def_stb : forall x1 x2, x1 ∈ A -> x2 ⊆ x1 -> x2 ∈ A\n}.\n\nDefinition coherent_def_alt (A : V) (R : V -> V -> Prop) : Prop := forall x, x ∈ A -> R x x.\n\nDefinition to_alt A := (union A, fun x y => pair x y ∈ A).\n\nDefinition of_alt A (R : V -> V -> Prop) :=\n  comprehension (powerset A) (fun a => forall x y, x ∈ a -> y ∈ a -> R x y).\n\nLemma of_alt_sound : forall A R, Proper (V_eq ==> V_eq ==> iff) R ->\n  coherent_def_alt A R -> coherent_def (of_alt A R).\nProof.\nassert (HP : forall (R : V -> V -> Prop),\n  Proper (V_eq ==> iff) (fun a => forall x y, x ∈ a -> y ∈ a -> R x y)).\n{ intros R; apply proper_sym_impl_iff; [apply V_eq_sym|].\n  intros x1 x2 Hx H x y; rewrite <- Hx; intuition. }\nintros A R HR Hc; split.\n+ intros x Hx; apply comprehension_spec; [now auto|split].\n  - apply powerset_spec; apply included_spec; intros z Hz.\n    apply union_spec in Hz; destruct Hz as [u [Hz Hu]].\n    specialize (Hx _ _ Hu Hu); rewrite cup_idem in Hx.\n    apply comprehension_spec in Hx; [|now auto].\n    eapply mem_included_compat; [eassumption|]; apply powerset_spec; intuition.\n  - intros u1 u2 Hu1 Hu2.\n    apply union_spec in Hu1; destruct Hu1 as [z1 [Hu1 Hz1]].\n    apply union_spec in Hu2; destruct Hu2 as [z2 [Hu2 Hz2]].\n    specialize (Hx z1 z2 Hz1 Hz2); apply comprehension_spec in Hx; [|now auto].\n    apply Hx; apply cup_spec; intuition.\n+ intros x1 x2 Hx1 Hm.\n  apply comprehension_spec in Hx1; [|now auto].\n  apply comprehension_spec; [now auto|]; split.\n  - apply powerset_spec; transitivity x1; [eassumption|]; apply powerset_spec; intuition.\n  - intros x y Hx Hy; apply Hx1; eapply mem_included_compat; eassumption.\nQed.\n\nLemma to_alt_sound : forall A,\n  coherent_def A -> coherent_def_alt (fst (to_alt A)) (snd (to_alt A)).\nProof.\nintros A HA; unfold to_alt; simpl; intros x Hx.\napply union_spec in Hx; destruct Hx as [z [Hx Hz]].\ndestruct HA as [HAl HAr]; apply (HAr (union (singleton z))).\n+ apply HAl; intros z1 z2 Hz1 Hz2; apply singleton_spec in Hz1; apply singleton_spec in Hz2.\n  rewrite Hz1, Hz2, cup_idem; assumption.\n+ apply included_spec; intros u Hu; apply pair_spec in Hu.\n  assert (Hrw : u ≅ x) by intuition; rewrite Hrw in *; clear u Hu Hrw.\n  apply union_spec; exists z; split; [assumption|apply singleton_spec; reflexivity].\nQed.\n\nDefinition coh_le A B :=\n  union A ⊆ union B /\\ (forall a, a ⊆ union A -> (a ∈ A <-> a ∈ B)).\n\nLemma coh_le_included_compat : forall A B, coh_le A B -> A ⊆ B.\nProof.\nintros A B [Hl Hr]; apply included_spec; intros a Ha.\napply Hr; [|assumption].\napply included_spec; intros α Hα; apply union_spec.\nexists a; intuition.\nQed.\n\nDefinition coh_nul := singleton empty.\n\nLemma coherent_nul : coherent_def coh_nul.\nProof.\nsplit.\n+ intros x Hs; apply singleton_spec.\n  assert (He : forall z, z ∈ x -> z ≅ empty).\n  { intros z Hz; specialize (Hs _ _  Hz Hz).\n    apply singleton_spec in Hs; rewrite <- Hs.\n    clear; apply extensionality; apply included_spec; intros u Hu.\n    - apply cup_spec; intuition.\n    - apply cup_spec in Hu; intuition.\n  }\n  apply extensionality; apply included_spec.\n  - intros z Hz; apply union_spec in Hz; exfalso.\n    destruct Hz as [m [Hz Hm]].\n    rewrite (He _ Hm) in Hz; apply empty_spec in Hz; contradiction.\n  - intros z Hz; apply empty_spec in Hz; contradiction.\n+ intros x1 x2 Hx1 Hm; apply singleton_spec.\n  apply singleton_spec in Hx1; rewrite Hx1 in Hm; clear x1 Hx1.\n  apply extensionality; apply included_spec; intros z Hz.\n  - apply (mem_included_compat _ _ _ Hz) in Hm; assumption.\n  - apply empty_spec in Hz; contradiction.\nQed.\n\nDefinition coh_bang U A := comprehension (powerset A)\n  (fun a => (forall x, x ∈ a -> (small U x)) /\\ union a ∈ A).\n\nLemma coherent_bang : forall U A, coherent_def A -> coherent_def (coh_bang U A).\nProof.\nassert (HP : forall U A,\n  Proper (V_eq ==> iff) (fun a => (forall x, x ∈ a -> (small U x)) /\\ union a ∈ A)).\n{ intros U A x1 x2 Hx; repeat f_equiv; [|assumption].\n  split; intros H x; [rewrite <- Hx|rewrite Hx]; intuition. }\nintros U A [Hl Hr]; split.\n+ intros a Ha; apply comprehension_spec; [now auto|].\n  split; [|split].\n  - apply powerset_spec; apply included_spec; intros z Hz.\n    apply union_spec in Hz; destruct Hz as [u [Hz Hu]].\n    specialize (Ha _ _ Hu Hu); rewrite cup_idem in Ha.\n    apply comprehension_spec in Ha; [|now auto].\n    destruct Ha as [Ha _]; apply powerset_spec in Ha.\n    eapply mem_included_compat; eassumption.\n  - intros u Hu; apply union_spec in Hu; destruct Hu as [x [Hu Hx]].\n    specialize (Ha _ _ Hx Hx); rewrite cup_idem in Ha.\n    apply comprehension_spec in Ha; [|now auto].\n    destruct Ha as [_ [Ha _]]; apply Ha; assumption.\n  - apply Hl; intros x1 x2 Hx1 Hx2.\n    apply union_spec in Hx1; apply union_spec in Hx2.\n    destruct Hx1 as [z1 [Hx1 Hz1]]; destruct Hx2 as [z2 [Hx2 Hz2]].\n    specialize (Ha _ _ Hz1 Hz2).\n    apply comprehension_spec in Ha; [|auto].\n    destruct Ha as [_ [_ Ha]].\n    apply (coherent_def_stb A (Build_coherent_def _ Hl Hr) _ _ Ha).\n    apply included_spec; intros p Hp; apply cup_spec in Hp.\n    apply union_spec.\n    destruct Hp as [Hp|Hp].\n    { exists x1; split; [assumption|]; apply cup_spec; intuition. }\n    { exists x2; split; [assumption|]; apply cup_spec; intuition. }\n+ intros x1 x2 Hx1 Hm; apply comprehension_spec; [now auto|].\n  apply comprehension_spec in Hx1; [|now auto].\n  split; [|split].\n  - apply powerset_spec; apply included_spec; intros z Hz.\n    eapply mem_included_compat; [eassumption|].\n    transitivity x1; [assumption|].\n    apply powerset_spec; intuition.\n  - intros z Hz; apply Hx1.\n    eapply mem_included_compat; eassumption.\n  - apply Hl; intros y1 y2 Hy1 Hy2.\n    apply (Hr (union x1)); [now intuition|].\n    apply included_spec; intros z Hz; apply cup_spec in Hz.\n    apply union_spec; destruct Hz as [Hz|Hz]; [exists y1|exists y2]; intuition;\n    eapply mem_included_compat; eassumption.\nQed.\n\nLemma coh_bang_spec : forall U A a,\n  a ∈ coh_bang U A <-> (a ⊆ A /\\ union a ∈ A /\\ (forall x, x ∈ a -> small U x)).\nProof.\nassert (HP : forall U A,\n  Proper (V_eq ==> iff) (fun a => (forall x, x ∈ a -> (small U x)) /\\ union a ∈ A)).\n{ intros U A x1 x2 Hx; repeat f_equiv; [|assumption].\n  split; intros H x; [rewrite <- Hx|rewrite Hx]; intuition. }\nintros U A a; split; intros H.\n+ apply comprehension_spec in H; [|now auto]; split; [|split]; try solve [intuition].\n  apply powerset_spec; intuition.\n+ apply comprehension_spec; [now auto|]; split; [|split]; try solve [intuition].\n  apply powerset_spec; intuition.\nQed.\n\nLemma coh_bang_monotonous : forall U A B, coh_le A B -> coh_le (coh_bang U A) (coh_bang U B).\nProof.\nintros U A B [Hl Hr]; split.\n+ apply included_spec; intros a Ha; apply union_spec in Ha.\n  destruct Ha as [u [Ha Hu]]; apply union_spec; exists u; split; [assumption|].\n  apply coh_bang_spec in Hu; apply coh_bang_spec.\n  split; [|split]; [| |now intuition].\n  - transitivity A; [|apply coh_le_included_compat; constructor]; intuition.\n  - eapply mem_included_compat; [intuition eauto|].\n    apply coh_le_included_compat; constructor; intuition.\n+ intros a Ha.\nAdmitted.\n\nLemma coh_bang_monotonous : forall U A B, A ⊆ B -> coh_bang U A ⊆ coh_bang U B.\nProof.\nassert (HP : forall U A,\n  Proper (V_eq ==> iff) (fun a => (forall x, x ∈ a -> (small U x)) /\\ union a ∈ A)).\n{ intros U A x1 x2 Hx; repeat f_equiv; [|assumption].\n  split; intros H x; [rewrite <- Hx|rewrite Hx]; intuition. }\nintros U A B Hs; apply included_spec; intros a Ha.\napply comprehension_spec in Ha; [|now auto].\napply comprehension_spec; [now auto|]; split; [|split].\n+ apply powerset_spec; transitivity A; [|assumption].\n  apply powerset_spec; intuition.\n+ intuition.\n+ eapply mem_included_compat; intuition eauto.\nQed.\n\nDefinition injl x := tuple (ordinal_of_nat 0) x.\nDefinition injr y := tuple (ordinal_of_nat 1) y.\nDefinition sum x y := cup (collection x injl) (collection y injr).\n\nDefinition coh_rel A B s1 s2 :=\n  (exists x1 x2, s1 ≅ injl x1 /\\ s2 ≅ injl x2 /\\ x1 ∈ A /\\ x2 ∈ A) \\/\n  (exists y1 y2, s1 ≅ injr y1 /\\ s2 ≅ injr y2 /\\ y1 ∈ B /\\ y2 ∈ B).\n\nDefinition coh_sum A B := of_alt (sum (union A) (union B)) (coh_rel (union A) (union B)).\n\nLemma coherent_sum : forall A B, coherent_def A -> coherent_def B -> coherent_def (coh_sum A B).\nProof.\nassert (HP : forall A B, Proper (V_eq ==> V_eq ==> iff) (coh_rel A B)).\n{ unfold coh_rel, injl, injr.\n  intros A B x1 x2 Hx y1 y2 Hy; repeat f_equiv; intro u; f_equiv; intro v; f_equiv;\n  repeat f_equiv; assumption. }\nintros A B HA HB; apply of_alt_sound; [now auto|].\nintros x Hx; apply cup_spec in Hx; destruct Hx as [Hx|Hx].\n+ apply collection_spec in Hx; [|unfold injl; repeat intro; f_equiv; assumption].\n  destruct Hx as [z [Hx Hz]]; left; exists z, z; intuition.\n+ apply collection_spec in Hx; [|unfold injr; repeat intro; f_equiv; assumption].\n  destruct Hx as [z [Hx Hz]]; right; exists z, z; intuition.\nQed.\n\nLemma coh_sum_monotonous : forall A B C D, A ⊆ B -> C ⊆ D -> coh_sum A C ⊆ coh_sum B D.\nProof.\nassert (HP : forall A B, Proper (V_eq ==> V_eq ==> iff) (coh_rel A B)).\n{ unfold coh_rel, injl, injr.\n  intros A B x1 x2 Hx y1 y2 Hy; repeat f_equiv; intro u; f_equiv; intro v; f_equiv;\n  repeat f_equiv; assumption. }\nintros A B C D Hl Hr; apply included_spec; intros z Hz.\napply comprehension_spec; [|].\nAdmitted.\n\nDefinition small_basetype U X :=\n  (forall x, x ∈ X -> small U x) /\\ (forall x a, x ∈ X -> a ∈ x -> small U a).\nDefinition basetype_def U A X :=\n  (forall x1 x2, x1 ∈ X -> x2 ∈ X -> cup x1 x2 ∈ A -> x1 ≅ x2) /\\ small_basetype U X.\nDefinition basetype U A := comprehension (powerset A) (basetype_def U A).\n\nDefinition coh_flat A := of_alt A (fun x y => x ≅ y).\n\nLemma coherent_flat : forall A, coherent_def (coh_flat A).\nProof.\nassert (HP : Proper (V_eq ==> iff) (fun a : V => forall x y : V, x ∈ a -> y ∈ a -> x ≅ y)).\n{ apply proper_sym_impl_iff; [apply V_eq_sym|]; intros z1 z2 Hz H u v; rewrite <- Hz; auto. }\nintros A; split.\n+ intros x Hx; apply comprehension_spec; [assumption|split].\n  - apply powerset_spec, included_spec; intros z Hz.\n    apply union_spec in Hz; destruct Hz as [y [Hz Hy]].\n    specialize (Hx _ _ Hy Hy); rewrite cup_idem in Hx.\n    apply comprehension_spec in Hx; [|assumption].\n    eapply mem_included_compat; [eassumption|].\n    apply powerset_spec; intuition.\n  - intros u v Hu Hv.\n    apply union_spec in Hu; destruct Hu as [a [Hu Ha]].\n    apply union_spec in Hv; destruct Hv as [b [Hv Hb]].\n    specialize (Hx _ _ Ha Hb).\n    apply comprehension_spec in Hx; [|assumption].\n    apply Hx; apply cup_spec; intuition.\n+ intros x1 x2 Hx1 Hm.\n  apply comprehension_spec in Hx1; [|assumption].\n  apply comprehension_spec; [assumption|split].\n  - apply powerset_spec; transitivity x1; [assumption|].\n    apply powerset_spec; intuition.\n  - intros x y Hx Hy; apply Hx1;\n    eapply mem_included_compat; eassumption.\nQed.\n\nDefinition coh_type U A := coh_flat (basetype U A).\n\nLemma coherent_type : forall U A, coherent_def (coh_type U A).\nProof.\nintros U A; apply coherent_flat.\nQed.\n\n\n\nAxiom Hierarchy : nat -> V.\nAxiom Top : V.\nAxiom Hierarchy_mem : forall n, Hierarchy n ∈ Hierarchy (S n).\nAxiom Top_mem : forall n, Hierarchy n ∈ Top.\nAxiom Hierarchy_universe : forall n, universe (Hierarchy n).\n\n", "meta": {"author": "ppedrot", "repo": "vitef", "sha": "695b0ac92de8911872d60834f6dcee5034fa88dc", "save_path": "github-repos/coq/ppedrot-vitef", "path": "github-repos/coq/ppedrot-vitef/vitef-695b0ac92de8911872d60834f6dcee5034fa88dc/ZF/Coherence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.25825765807107814}}
{"text": "Require Import Crypto.Bedrock.Field.Translation.Parameters.Defaults64.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.Strings.String.\nRequire Import Bedrock.Field.felem_copy.\nRequire Import Coq.Lists.List.\nRequire Import bedrock2.ProgramLogic.\nRequire Import bedrock2.Map.SeparationLogic.\nRequire Import Crypto.Bedrock.Field.Synthesis.Generic.Bignum.\nRequire Import coqutil.Word.Interface.\nRequire Import Crypto.Bedrock.Field.Common.Types.\nRequire Import Bedrock.Util.Tactics.\nRequire Import Crypto.Bedrock.Field.Common.Tactics.\nRequire Import Bedrock.Util.Bignum.\n(* Require Import bedrock2.NotationsCustomEntry. *)\n\nLocal Open Scope string_scope.\nImport Syntax.Coercions.\nImport ListNotations.\n\n(*Parameters to be changed: we require an instance of parameters and parameters_ok, as well as a a string to be appended to function name.\n    lastly, the parameter num_limbs specify the number of words in a Bignum representation of the fiel elements to be copied.*)\nExisting Instances Defaults64.default_parameters Defaults64.default_parameters_ok.\nDefinition aff := \"_p224_64\".\nDefinition num_limbs := 4%nat.\n\n\n(*Rest of file should not be changed.*)\nDefinition felem_copy_m : Syntax.func := (felem_copy aff num_limbs).\n\nInstance spec_of_felem_copy_m: spec_of felem_copy_m :=\nfun functions : list (string * (list string * list string * Syntax.cmd)) =>\n    forall (welem : list Interface.word.rep)\n    (pout pelem: Interface.word.rep)\n    (wold_out: list Interface.word.rep) (t : Semantics.trace)\n    (m0 : Interface.map.rep) (R Relem P : Interface.map.rep -> Prop),\n    ( (fun m => (Bignum num_limbs pelem welem * Relem)%sep m /\\ P m) * (Bignum num_limbs pout wold_out) * R)%sep m0 ->\n    WeakestPrecondition.call functions (append \"felem_copy\" aff) t m0\n    ([pout; pelem])\n    (fun (t' : Semantics.trace) (m' : Interface.map.rep)\n        (rets : list Interface.word.rep) =>\n    t = t' /\\\n    rets = nil /\\\n    ((P * (Bignum num_limbs pout welem) * R)%sep m')).\n\nNotation N aw := (word.add (word.of_Z word_size_in_bytes) aw).\n\nTheorem felem_copy_m_ok : program_logic_goal_for_function! felem_copy_m.\nProof.\n    repeat straightline.\n\n    (*Packing all assumption into single separation hypothesis for copying bytes.*)\n    remember (Bignum num_limbs pelem welem) as Q.\n    remember (Bignum num_limbs pout wold_out * R)%sep as newR.\n    eassert (H0 : ( _ * newR)%sep _) by (subst newR; ecancel_assumption); clear H.\n    apply sep_and_l_fwd in H0. destruct H0 as [H H0]. subst newR.\n\n    assert (Ha : a = pout) by (subst a; normalize_words; auto).\n    eassert (nval : num_limbs = _) by (cbv [num_limbs]; auto with zarith).\n\n    (*Rephrasing Bignun to Scalar for copying bytes*)\n    Bignum_to_Scalars num_limbs wold_out nval.\n    eassert ((Bignum num_limbs pout _ * (P * R)%sep)%sep m0) by (apply sep_comm; clear H H1 H2; ecancel_assumption).\n    apply Bignum_manyScalars_R in H3; sepsimpl_hyps; clear H3;\n    rewrite nval in H4; repeat rewrite many_Scalars_next in H4; rewrite many_Scalars_nil in H4.\n\n    clear H1 H H0. subst Q.\n    Bignum_to_Scalars num_limbs welem nval. clear H H2.\n    subst a.\n\n    rename H0 into H;\n    rename H4 into H0.\n    repeat copy_word H H0.\n\n    (* copy_word H H0. *)\n    repeat split; auto.\n\n    lazymatch goal with \n    | |- (_ * (Bignum _ _ ?list) * _)%sep _ => remember list as l end.\n\n    (*Postcondition*)\n    unfold Bignum.\n    eassert ( (P * (emp (Datatypes.length l = num_limbs) * _))%sep m) by (subst l; sepsimpl; auto; ecancel_assumption).\n    subst l; unfold Array.array; normalize_words; normalize_words_in H0; clear H H0; normalize_words_in H1; ecancel_assumption.\nQed.\n\n(*Output to terminal:*)\n\n(* Require Import bedrock2.ToCString bedrock2.Bytedump.\nDefinition felem_copy_func := c_module (felem_copy_m :: nil).\nEval compute in felem_copy_func. *)", "meta": {"author": "AU-COBRA", "repo": "AUCurves", "sha": "ea864da1b1e78a86fda16818a9366a96da83cb63", "save_path": "github-repos/coq/AU-COBRA-AUCurves", "path": "github-repos/coq/AU-COBRA-AUCurves/AUCurves-ea864da1b1e78a86fda16818a9366a96da83cb63/src/Bedrock/Examples/felem_copy_p224_64.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.25825765807107814}}
{"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 O E Eprime Eprimeprime A B C Bprime : Universe, ((wd_ O E /\\ (wd_ O Eprime /\\ (wd_ E Eprime /\\ (wd_ B O /\\ (wd_ A O /\\ (wd_ C O /\\ (wd_ O Eprimeprime /\\ (wd_ E Eprimeprime /\\ (wd_ B E /\\ (wd_ A E /\\ (wd_ Bprime O /\\ (wd_ Eprime Eprimeprime /\\ (wd_ Bprime C /\\ (wd_ Eprime A /\\ (wd_ Eprime Bprime /\\ (wd_ Eprime C /\\ (wd_ A Bprime /\\ (wd_ A C /\\ (wd_ E Bprime /\\ (wd_ Eprime B /\\ (wd_ B Bprime /\\ (wd_ B C /\\ (wd_ B Eprimeprime /\\ (wd_ C E /\\ (wd_ C Eprimeprime /\\ (col_ O E A /\\ (col_ O E B /\\ (col_ O E C /\\ (col_ O Eprime Bprime /\\ (col_ O Eprimeprime C /\\ (col_ A Eprime Eprimeprime /\\ (col_ C Bprime C /\\ col_ Bprime Bprime C)))))))))))))))))))))))))))))))) -> col_ E 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_1218.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.359364131437828, "lm_q1q2_score": 0.2582370497423193}}
{"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\n(** * Lemmas about the common part of the interface of the CFG parser *)\nRequire Import Coq.Classes.RelationClasses Coq.Setoids.Setoid.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.BaseTypes.\n\nSet Implicit Arguments.\n\nLocal Open Scope string_like_scope.\n\nLocal Coercion is_true : bool >-> Sortclass.\n\nSection recursive_descent_parser.\n  Context {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char} {G : grammar Char}\n          {predata : @parser_computational_predataT Char}\n          {rdata' : @parser_removal_dataT' _ G _}.\n\n  Lemma remove_nonterminal_3\n        {ls ps ps'} (H0 : is_valid_nonterminal ls ps = false)\n  : is_valid_nonterminal (remove_nonterminal ls ps) ps' = is_valid_nonterminal ls ps'.\n  Proof.\n    case_eq (is_valid_nonterminal (remove_nonterminal ls ps) ps');\n    case_eq (is_valid_nonterminal ls ps');\n    intros H' H'';\n    try reflexivity;\n    exfalso;\n    first [ apply remove_nonterminal_1 in H''\n          | apply remove_nonterminal_2 in H''; destruct H''; subst ];\n    congruence.\n  Qed.\n\n  Lemma remove_nonterminal_4\n        {ls ps ps'} (H0 : is_valid_nonterminal (remove_nonterminal ls ps) ps')\n  : ps <> ps'.\n  Proof.\n    intro H'.\n    pose proof (proj2 (remove_nonterminal_2 ls _ _) (or_intror H')).\n    congruence.\n  Qed.\n\n  Lemma remove_nonterminal_5\n        {ls ps ps'} (H0 : ps <> ps')\n  : is_valid_nonterminal (remove_nonterminal ls ps) ps' = is_valid_nonterminal ls ps'.\n  Proof.\n    case_eq (is_valid_nonterminal (remove_nonterminal ls ps) ps');\n    case_eq (is_valid_nonterminal ls ps');\n    intros H' H'';\n    try reflexivity;\n    exfalso;\n    first [ apply remove_nonterminal_1 in H''\n          | apply remove_nonterminal_2 in H''; destruct H''; subst ];\n    congruence.\n  Qed.\n\n  Lemma remove_nonterminal_6\n        ls ps\n  : is_valid_nonterminal (remove_nonterminal ls ps) ps = false.\n  Proof.\n    apply remove_nonterminal_2; right; reflexivity.\n  Qed.\n\n  Global Instance sub_nonterminals_listT_Reflexive : Reflexive sub_nonterminals_listT\n    := fun x y f => f.\n\n  Global Instance sub_nonterminals_listT_Transitive : Transitive sub_nonterminals_listT.\n  Proof.\n    lazy; auto.\n  Defined.\n\n  Global Add Parametric Morphism : remove_nonterminal\n  with signature sub_nonterminals_listT ==> eq ==> sub_nonterminals_listT\n    as remove_nonterminal_mor.\n  Proof.\n    intros x y H0 z w H'.\n    hnf in H0.\n    pose proof (remove_nonterminal_4 H').\n    apply remove_nonterminal_1 in H'.\n    rewrite remove_nonterminal_5 by assumption.\n    auto.\n  Qed.\n\n  Lemma sub_nonterminals_listT_remove ls ps\n  : sub_nonterminals_listT (remove_nonterminal ls ps) ls.\n  Proof.\n    intros p.\n    apply remove_nonterminal_1.\n  Qed.\n\n  Lemma sub_nonterminals_listT_remove_2 {ls ls' ps} (H : sub_nonterminals_listT ls ls')\n  : sub_nonterminals_listT (remove_nonterminal ls ps) ls'.\n  Proof.\n    etransitivity; eauto using sub_nonterminals_listT_remove.\n  Qed.\n\n  Lemma sub_nonterminals_listT_remove_3 {ls ls' p}\n        (H0 : is_valid_nonterminal ls p = false)\n        (H1 : sub_nonterminals_listT ls ls')\n  : sub_nonterminals_listT ls (remove_nonterminal ls' p).\n  Proof.\n    intros p' H'.\n    rewrite remove_nonterminal_5; intuition (subst; eauto; congruence).\n  Qed.\n\n  Lemma remove_nonterminal_noninc' {ls nt}\n  : nonterminals_length (remove_nonterminal ls nt) <= nonterminals_length ls.\n  Proof.\n    apply Nat.nlt_ge.\n    apply remove_nonterminal_noninc.\n  Qed.\n\n  Lemma nonempty_nonterminals {ls nt} (H : is_valid_nonterminal ls nt)\n  : 0 < nonterminals_length ls.\n  Proof.\n    eapply Lt.le_lt_trans;\n    [ apply Le.le_0_n\n    | exact (remove_nonterminal_dec ls nt H) ].\n  Qed.\n\n  Lemma nonempty_nonterminals' {ls nt} (H : is_valid_nonterminal ls nt)\n  : negb (EqNat.beq_nat (nonterminals_length ls) 0).\n  Proof.\n    pose proof (nonempty_nonterminals H).\n    destruct (nonterminals_length ls); simpl; try reflexivity; try omega.\n  Qed.\n\n  Lemma nonterminal_to_production_correct'\n    : forall nt,\n      is_valid_nonterminal initial_nonterminals_data nt\n      -> List.map to_production (nonterminal_to_production nt)\n         = Lookup G (to_nonterminal nt).\n  Proof.\n    intros nt H.\n    rewrite <- (of_to_nonterminal nt) at 1 by assumption.\n    rewrite nonterminal_to_production_correct by (apply initial_nonterminals_correct'; assumption).\n    reflexivity.\n  Qed.\n\n  Lemma is_valid_nonterminal_of_to_nonterminal valids nt\n    : sub_nonterminals_listT valids initial_nonterminals_data\n      -> is_valid_nonterminal valids (of_nonterminal (to_nonterminal nt)) = is_valid_nonterminal valids nt.\n  Proof.\n    intro Hvalid.\n    match goal with\n    | [ |- ?lhs = ?rhs ] => destruct lhs eqn:?, rhs eqn:?; first [ reflexivity | exfalso ]\n    end;\n      repeat match goal with\n             | [ H : is_valid_nonterminal _ _ = _ |- False ]\n               => rewrite of_to_nonterminal in H\n             | _ => congruence\n             | _ => apply Hvalid; assumption\n             | _ => rewrite initial_nonterminals_correct', <- initial_nonterminals_correct; apply Hvalid; assumption\n             end.\n  Qed.\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/BaseTypesLemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.25816942523552405}}
{"text": "Require Import Common.Common.\nRequire Import UValFI.UVal.\nRequire Import LogRelFI.LemmasPseudoType.\nRequire Import LogRelFI.PseudoType.\nRequire Import LogRelFI.LR.\nRequire Import StlcFix.SpecSyntax.\nRequire Import StlcFix.SpecEvaluation.\nRequire Import StlcFix.LemmasEvaluation.\nRequire Import StlcFix.LemmasTyping.\nRequire Import StlcFix.SpecTyping.\nRequire Import StlcFix.Size.\nRequire Import StlcIso.SpecSyntax.\nRequire Import StlcIso.SpecEvaluation.\nRequire Import StlcIso.LemmasEvaluation.\n(* Require Import StlcIso.LemmasScoping. *)\nRequire Import StlcIso.Inst.\nRequire Import StlcIso.Size.\n\nRequire Import Lia.\nRequire Import Min.\n\nLemma lev_lateri {i W} : lev (lateri i W) = lev W - i.\nProof.\n  induction i; unfold lev in *; simpl in *; eauto with arith.\n  rewrite IHi. lia.\nQed.\n\n\nSection Obs.\n  Lemma obs_zero {d ts tu} : Obs d 0 ts tu.\n  Proof.\n    destruct d; simpl; intuition.\n  Qed.\n\n  Lemma S_Observe_Terminating_value {n ts} :\n    F.Value ts → Observe (S n) (F.TerminatingN ts).\n  Proof.\n    intros vts. simpl. eauto using F.values_terminateN.\n  Qed.\n\n  Lemma U_Observe_Terminating_value {n tu} :\n    I.Value tu → Observe (S n) (I.TerminatingN tu).\n  Proof.\n    intros vtu. simpl. eauto using I.values_terminateN.\n  Qed.\n\n  Lemma obs_value {d n ts tu} :\n    F.Value ts → I.Value tu → Obs d n ts tu.\n  Proof.\n    intros vs vu.\n    destruct d; simpl; intros _;\n    eauto using F.values_terminate, I.values_terminate.\n  Qed.\n\n  Lemma obs_mono {d W' W ts tu} :\n    lev W' ≤ lev W →\n    Obs d W ts tu →\n    Obs d W' ts tu.\n  Proof.\n    intros fw obs.\n    destruct d; destruct W';\n    simpl in *; intuition;\n    destruct (S_le fw) as [W'' [eq fw']];\n    replace (lev W) with (S W'') in *; simpl in *;\n    eauto using F.TermHor_lt, I.TermHor_lt.\n  Qed.\n\n  Lemma S_ObserveTerminatingN_xor_evaln {t t' n} :\n    F.evaln t t' n → False ↔ Observe n (F.TerminatingN t).\n  Proof.\n    destruct n; simpl in *; intuition; eauto using F.TerminatingN_xor_evaln.\n  Qed.\n\n  Lemma S_Observe_TerminatingN_evaln {t t' n } n' :\n    F.evaln t t' n → Observe n' (F.TerminatingN t') ↔ Observe (n + n') (F.TerminatingN t).\n  Proof.\n    destruct n';\n      [ replace (n + 0) with n by lia\n      | replace (n + S n') with (S n + n') by lia ];\n    simpl in *; eauto using F.TerminatingN_evaln, S_ObserveTerminatingN_xor_evaln.\n  Qed.\n\n  Lemma S_ObserveTermHor_xor_evaln {t t' n} :\n    F.evaln t t' n → False ↔ Observe n (F.TermHor t).\n  Proof.\n    destruct n; cbn; intuition. eauto using F.TermHor_xor_evaln.\n  Qed.\n\n  Lemma S_Observe_TermHor_evaln {t t' n } n' :\n    F.evaln t t' n → Observe (n + n') (F.TermHor t) -> Observe n' (F.TermHor t').\n  Proof.\n    destruct n'; cbn; intros evals.\n    - replace (n + 0) with n by lia.\n      now rewrite <- (S_ObserveTermHor_xor_evaln evals).\n    - replace (n + S n') with (S (n + n')) by lia.\n      cbn.\n      eauto using F.TermHor_evaln.\n  Qed.\n\n  Lemma S_Observe_TerminatingN_lt {t n n'} :\n    n ≤ n' → Observe n (F.TerminatingN t) → Observe n' (F.TerminatingN t).\n  Proof.\n    intros ineq obs.\n    destruct n; simpl; intuition.\n    destruct (S_le ineq) as [n'' [eq ineq']]; subst; simpl in *.\n    eauto using F.TerminatingN_lt.\n  Qed.\n\n  Lemma S_Observe_TermHor_lt {t n n'} :\n    n ≤ n' → Observe n (F.TermHor t) → Observe n' (F.TermHor t).\n  Proof.\n    intros ineq obs.\n    destruct n; simpl in *; [contradiction|].\n    destruct (S_le ineq) as [n'' [-> ineq']]; cbn.\n    eauto using F.TermHor_lt.\n  Qed.\n\n  Lemma U_Observe_TermHor_lt {t n n'} :\n    n ≤ n' → Observe n (I.TermHor t) → Observe n' (I.TermHor t).\n  Proof.\n    intros ineq obs.\n    destruct n; simpl in *; [contradiction|].\n    destruct (S_le ineq) as [n'' [-> ineq']]; cbn.\n    eauto using I.TermHor_lt.\n  Qed.\n\n  Lemma U_ObserveTerminatingN_xor_evaln {t t' n} :\n    I.evaln t t' n → False ↔ Observe n (I.TerminatingN t).\n  Proof.\n    destruct n; simpl in *; intuition; eauto using I.TerminatingN_xor_evaln.\n  Qed.\n\n  Lemma U_Observe_TerminatingN_evaln {t t' n } n' :\n    I.evaln t t' n → Observe n' (I.TerminatingN t') ↔ Observe (n + n') (I.TerminatingN t).\n  Proof.\n    destruct n';\n      [ replace (n + 0) with n by lia\n      | replace (n + S n') with (S n + n') by lia ];\n    simpl in *; eauto using I.TerminatingN_evaln, U_ObserveTerminatingN_xor_evaln.\n  Qed.\n\n  Lemma U_Observe_TerminatingN_lt {t n n'} :\n    n ≤ n' → Observe n (I.TerminatingN t) → Observe n' (I.TerminatingN t).\n  Proof.\n    intros ineq obs.\n    destruct n; simpl; intuition.\n    destruct (S_le ineq) as [n'' [eq ineq']]; subst; simpl; simpl in obs.\n    eauto using I.TerminatingN_lt.\n  Qed.\n\n  Lemma U_ObserveTermHor_xor_evaln {t t' n} :\n    I.evaln t t' n → False ↔ Observe n (I.TermHor t).\n  Proof.\n    destruct n; simpl in *; intuition; eauto using I.TermHor_xor_evaln.\n  Qed.\n\n  Lemma U_Observe_TermHor_evaln {t t' n } n' :\n    I.evaln t t' n → Observe (n + n') (I.TermHor t) -> Observe n' (I.TermHor t').\n  Proof.\n    destruct n'; cbn; intros evals.\n    - replace (n + 0) with n by lia.\n      now rewrite <- (U_ObserveTermHor_xor_evaln evals).\n    - replace (n + S n') with (S (n + n')) by lia.\n      cbn.\n      eauto using I.TermHor_evaln.\n  Qed.\n\n  Lemma obs_antired {ts ts' tu tu' W' W d i j} :\n    F.evaln ts ts' i →\n    I.evaln tu tu' j →\n    (* W' ≤ W → *)\n    lev W' + min i j ≥ lev W →\n    Obs d W' ts' tu' →\n    Obs d W ts tu.\n  Proof.\n    intros es eu (* fw *) sge obs.\n    destruct d; destruct W; simpl; simpl in obs; intuition.\n    - cut (tu'⇓).\n      + refine (I.termination_closed_under_antireductionStar _).\n        eauto using I.evaln_to_evalStar.\n      + apply obs; clear obs.\n        eapply (S_Observe_TermHor_evaln (lev W') es).\n        assert (obs : Observe (S W) (F.TermHor ts)) by (simpl; intuition).\n        refine (S_Observe_TermHor_lt _ obs).\n        unfold lev in *.\n        enough (min i j ≤ i) by lia.\n        auto using le_min_l.\n    - refine (F.termination_closed_under_antireductionStar _ _).\n      + refine (stepRel_to_evalStar es).\n      + apply obs; clear obs.\n        assert (obs : Observe (S W) (I.TermHor tu)) by (simpl; intuition).\n        apply (U_Observe_TermHor_evaln (lev W') eu).\n        refine (U_Observe_TermHor_lt _ obs).\n        unfold lev in *.\n        lia.\n  Qed.\n\n  Lemma obs_antired_star {ts ts' tu tu' W d} :\n    F.evalStar ts ts' →\n    tu -->* tu' →\n    Obs d W ts' tu' →\n    Obs d W ts tu.\n  Proof.\n    intros es eu obs.\n    destruct d.\n    - intros term.\n      destruct W; [contradiction|].\n      eapply (F.TermHor_closed_under_reduction_star es) in term.\n      eauto using I.termination_closed_under_antireductionStar.\n    - intros term.\n      destruct W; [contradiction|].\n      cbn in term.\n      eapply (I.TermHor_closed_under_reduction_star eu) in term.\n      eauto using F.termination_closed_under_antireductionStar.\n  Qed.\n\n  (* Lemma obs_red {ts ts' tu tu' W' W d i j} : *)\n  (*   F.evaln ts' ts i → *)\n  (*   I.evaln tu' tu j → *)\n  (*   lev W  + max i j <= lev W' → *)\n  (*   Obs d W' ts' tu' → *)\n  (*   Obs d W ts tu. *)\n  (* Proof. *)\n  (*   intros es eu sge obs. *)\n  (*   destruct d; simpl; simpl in obs; intuition. *)\n  (*   - eapply evaln_to_evalStar in eu. *)\n  (*     eapply (termination_closed_under_evalstar eu). *)\n  (*     eapply obs. *)\n  (*     assert (i + lev W <= lev W') as sgei by lia. *)\n  (*     eapply (S_Observe_TermHor_lt sgei). *)\n  (*     now eapply (S_Observe_TermHor_evaln (lev W) es). *)\n  (*   - eapply F.evaln_to_evalStar in es. *)\n  (*     eapply (F.termination_closed_under_evalstar es). *)\n  (*     eapply obs. *)\n  (*     assert (j + lev W <= lev W') as sgej by lia. *)\n  (*     eapply (U_Observe_TerminatingN_lt sgej). *)\n  (*     now eapply (U_Observe_TerminatingN_evaln (lev W) eu). *)\n  (* Qed. *)\n\n  Lemma S_ObserveTerminating_Value {w vs} :\n    F.Value vs →\n    Observe (S w) (F.TerminatingN vs).\n  Proof.\n    intros vvs; simpl.\n    apply F.values_terminateN; trivial.\n  Qed.\n\n  Lemma Diverge_Obs_lt {w ts tu} : not (F.Terminating ts) → Obs dir_lt w ts tu.\n  Proof.\n    intros div termobs.\n    destruct w; try contradiction.\n    apply F.TermHor_Terminating in termobs.\n    exfalso; eauto.\n  Qed.\n\n  Lemma Diverge_Wrong_Obs {d w ts tu} :\n    not (F.Terminating ts) →\n    not (I.Terminating tu) →\n    Obs d w ts tu.\n  Proof.\n    intros div divw.\n    destruct d; intros termobs.\n    - destruct w; try contradiction.\n      apply F.TermHor_Terminating in termobs.\n      exfalso; eauto.\n    - destruct w; try contradiction.\n      apply I.TermHor_Terminating in termobs.\n      exfalso. eauto.\n  Qed.\n\nEnd Obs.\n\nSection ClosedLR.\n  Lemma valrel_implies_OfType {d W τ ts tu} :\n    valrel d W τ ts tu → OfType τ ts tu.\n  Proof.\n    rewrite -> valrel_fixp. unfold valrel'. intuition.\n  Qed.\n\n  Lemma envrel_triv {d w γs γu} :\n    envrel d w pempty γs γu.\n  Proof.\n    unfold envrel.\n    intros i τ i_τ.\n    depind i_τ.\n  Qed.\n\n  Lemma envrel_implies_WtSub {d W Γ γs γu} :\n    envrel d W Γ γs γu → WtSub (repEmulCtx Γ) F.empty γs.\n  Proof.\n    intros er i τ vi_τ.\n    destruct (getevar_repEmulCtx vi_τ) as [pτ [vi_pτ ?]].\n    assert (vr : valrel d W pτ (γs i) (γu i)) by refine (er _ _ vi_pτ).\n    destruct (valrel_implies_OfType vr) as [[_ ots] _].\n    unfold OfTypeStlcFix in ots.\n    subst. exact ots.\n  Qed.\n\n  Lemma envrel_implies_WtSub_iso {d W Γ γs γu} :\n    envrel d W Γ γs γu → I.WtSub (fxToIsCtx Γ) I.empty γu.\n  Proof.\n    intros er i τ vu_τ.\n    destruct (getevar_fxToIsCtx vu_τ) as [pτ [vu_pτ ?]].\n    assert (vr : valrel d W pτ (γs i) (γu i)) by refine (er _ _ vu_pτ).\n    destruct (valrel_implies_OfType vr) as [_ [_ ots]].\n    subst. exact ots.\n  Qed.\n\n  (* Lemma envrel_implies_WsSub {d W Γ γs γu}: *)\n  (*   envrel d W Γ γs γu → WsSub (pdom Γ) 0 γu. *)\n  (* Proof. *)\n  (*   intros er i wsi. *)\n  (*   destruct (pdom_works_inv wsi) as (τ & τinΓ). *)\n  (*   specialize (er i τ τinΓ). *)\n  (*   destruct (valrel_implies_OfType er) as (_ & ws & _). *)\n  (*   exact ws. *)\n  (* Qed. *)\n\n  Local Ltac crush :=\n    crushOfType;\n    repeat\n      (cbn in *;\n       subst*;\n       repeat F.crushStlcSyntaxMatchH;\n       repeat I.crushStlcSyntaxMatchH;\n       destruct_conjs);\n       eauto 20 using lt_le with arith.\n\n  Lemma valrel_mono {d W τ ts tu W'} :\n    W' ≤ W → valrel d W τ ts tu → valrel d W' τ ts tu.\n  Proof with subst; intuition.\n    rewrite -> ?valrel_fixp.\n    revert ts tu W' W.\n    induction τ;  unfold valrel';\n    intros ts tu W' W fw [ot hyp];\n    split; eauto; cbn in *.\n    - (* ptarr _ _ *)\n      destruct hyp as (tsb & tub & τ₁' & τ₂' & -> & -> & hyp).\n      exists tsb, tub, τ₁', τ₂'.\n      repeat split; try reflexivity.\n      intros W'' fw'.\n      apply hyp; lia.\n    - (* ptprod *)\n      crush.\n    - (* ptsum *)\n      crush.\n      destruct H0 as [(-> & -> & ot')|[ (-> & -> )|[( -> & -> )|( -> & -> & ot')]]]; crush.\n    - (* pEmulDV n p *)\n      destruct n; [ assumption | idtac ].\n      destruct hyp as [[eqs eqp]|[ts' hyp]];\n        [ now left\n        | right; exists ts'].\n      destruct τ.\n      + (* tarr *)\n        destruct hyp as (-> & tsb & tub & τ₁' & τ₂' & -> & -> & hyp).\n        split; [reflexivity|].\n        exists tsb, tub, τ₁', τ₂'.\n        crush.\n      + (* tunit *)\n        assumption.\n      + (* tbool *)\n        assumption.\n      + (* tprod *)\n        intuition.\n        destruct ts'; crush.\n        destruct tu; crush.\n      + (* tsum *)\n        intuition.\n        destruct ts'; crush.\n        destruct tu; crush.\n        unfold sum_rel in *.\n        destruct tu; crush.\n      + (* trec *)\n        crush.\n      + (* tvar *)\n        assumption.\n  Qed.\n\n  Lemma envrel_mono {d W Γ γs γu W'} :\n    W' ≤ W → envrel d W Γ γs γu → envrel d W' Γ γs γu.\n  Proof.\n    intros fw er i τ viτ.\n    refine (valrel_mono fw _).\n    apply er; auto.\n  Qed.\n\n  Lemma contrel_mono {d W τ Cs Cu W'} :\n    W' ≤ W → contrel d W τ Cs Cu → contrel d W' τ Cs Cu.\n  Proof.\n    intros fw cr. simpl.\n    intros W'' fw' vs vu vr.\n    apply cr; eauto with arith.\n  Qed.\n\n  Lemma termrel_zero {d τ ts tu} : termrel d 0 τ ts tu.\n  Proof.\n    intros Cs Cu cr eCs eCu. eauto using obs_zero.\n  Qed.\n\n  Lemma termrel_antired_step {ts ts' tu tu' W d τ} :\n    F.eval ts ts' →\n    I.eval tu tu' →\n    (forall W', W = S W' -> termrel d W' τ ts' tu') →\n    termrel d W τ ts tu.\n  Proof.\n    intros es eu tr.\n    unfold termrel, termrel'.\n    intros Cs Cu ecs ecu cr.\n    destruct W.\n    - eapply obs_zero.\n    - refine (obs_antired (W' := W) _ _ _ _).\n      eapply stepRel_step.\n      refine (F.eval_ctx Cs _ _ ecs es).\n      eapply stepRel_zero.\n      eapply stepRel_step.\n      refine (I.eval_ctx Cu _ _ ecu eu).\n      eapply stepRel_zero.\n      unfold lev; lia.\n      apply tr; auto.\n      refine (contrel_mono _ cr).\n      lia.\n  Qed.\n\n  Lemma termrel_antired {ts ts' tu tu' W d τ i j} W' :\n    F.evaln ts ts' i →\n    I.evaln tu tu' j →\n    W' ≤ W →\n    lev W' + min i j ≥ lev W →\n    termrel d W' τ ts' tu' →\n    termrel d W τ ts tu.\n  Proof.\n    intros es eu fw sge tr.\n    unfold termrel, termrel'.\n    intros Cs Cu ecs ecu cr.\n    refine (obs_antired _ _ sge _); eauto using F.evaln_ctx, I.evaln_ctx.\n    apply tr; auto.\n    refine (contrel_mono fw cr).\n  Qed.\n\n  Lemma termrel_antired_star {ts ts' tu tu' W d τ} :\n    clos_refl_trans_1n F.Tm F.eval ts ts' →\n    tu -->* tu' →\n    termrel d W τ ts' tu' →\n    termrel d W τ ts tu.\n  Proof.\n    intros es eu tr.\n    destruct (evalTrans_to_stepRel es) as [i esi].\n    destruct (evalTrans_to_stepRel eu) as [j euj].\n    refine (termrel_antired W esi euj _ _ tr); lia.\n  Qed.\n\n  Lemma termrel_antired_star_left {ts ts' tu W d τ} :\n    clos_refl_trans_1n F.Tm F.eval ts ts' →\n    termrel d W τ ts' tu →\n    termrel d W τ ts tu.\n  Proof.\n    assert (tu -->* tu) by (eauto with eval).\n    eauto using termrel_antired_star.\n  Qed.\n\n  Lemma termrel_antired_eval_left {ts ts' tu W d τ} :\n    F.eval ts ts' →\n    termrel d W τ ts' tu →\n    termrel d W τ ts tu.\n  Proof.\n    eauto using termrel_antired_star_left with eval.\n  Qed.\n\n\n  (* Lemma termrel_antired' {ts ts' tu tu' W d τ i j} W' : *)\n  (*   S.evaln ts ts' i → *)\n  (*   U.evaln tu tu' j →  *)\n  (*   tu' ≠ wrong → *)\n  (*   W' ≤ W → *)\n  (*   lev W' + min i j ≥ lev W → *)\n  (*   termrel d W' τ ts' tu' → *)\n  (*   termrel d W τ ts tu. *)\n  (* Proof. *)\n  (*   intros es eu nw. *)\n  (*   apply termrel_antired; try assumption. *)\n  (*   induction eu; eauto using evaln; econstructor; eauto using evaln. *)\n  (*   apply eval_ctx; try assumption. *)\n  (*   intro eq; depind eu; intuition. *)\n  (*   destruct H0 as [C'|C' eq']; destruct C'; simpl in eq; destruct H0; inversion eq; intuition. *)\n  (* Qed. *)\n\n  Lemma valrel_in_termrel {ts tu W d τ} :\n    valrel d W τ ts tu → termrel d W τ ts tu.\n  Proof.\n    intros vr Cs Cu eCs eCu contrel.\n    apply contrel; auto.\n  Qed.\n\n  Lemma valrel_implies_Value {d w τ ts tu} :\n    valrel d w τ ts tu →\n    F.Value ts ∧ I.Value tu.\n  Proof.\n    intros vr.\n    rewrite -> valrel_fixp in vr.\n    destruct vr as [ot _].\n    exact (OfType_implies_Value ot).\n  Qed.\n\n  Lemma contrel_triv {d w τ} :\n    contrel d w τ F.phole I.phole.\n  Proof.\n    unfold contrel, contrel'; intros w' fw ts tu vr; simpl.\n    destruct (valrel_implies_Value vr).\n    apply obs_value; trivial.\n  Qed.\n\n  Lemma extend_envrel {d w Γ γs γu τ ts tu} :\n    valrel d w τ ts tu →\n    envrel d w Γ γs γu →\n    envrel d w (Γ p▻ τ) (γs↑ >=> beta1 ts) (γu↑ >=> beta1 tu).\n  Proof.\n    intros vr er x τ' xτ'.\n    depind xτ'; intuition. \n    replace ((γs↑ >=> beta1 ts) (S i)) with (γs i). \n    replace ((γu↑ >=> beta1 tu) (S i)) with (γu i).\n    now refine (er _ _ xτ').\n    + cbn; rewrite <- ap_liftSub; \n      rewrite -> liftSub_wkm;\n      rewrite -> apply_wkm_beta1_cancel; intuition.\n    + cbn; rewrite <- ap_liftSub; \n      rewrite -> liftSub_wkm;\n      rewrite -> apply_wkm_beta1_cancel; intuition.\n  Qed.\n\n  Lemma termrel_adequacy_lt {w m ts tu τ} :\n    termrel dir_lt w τ ts tu →\n    F.TermHor ts m →\n    lev w > m →\n    I.Terminating tu.\n  Proof.\n    intros tr term ineq.\n    specialize (tr F.phole I.phole I I contrel_triv).\n    simpl in tr. unfold lev in *.\n    destruct (le_inv_plus ineq) as [r eq]; subst.\n    apply tr.\n    change (S m + r) with (S (m + r)) in *.\n    apply (F.TermHor_lt term); lia.\n  Qed.\n\n  Lemma termrel_adequacy_gt {w m tu ts τ} :\n    termrel dir_gt w τ ts tu →\n    I.TermHor tu m →\n    lev w > m →\n    F.Terminating ts.\n  Proof.\n    intros tr term ineq.\n    specialize (tr F.phole I.phole I I contrel_triv).\n    simpl in tr. unfold lev in *.\n    destruct (le_inv_plus ineq) as [r eq]; subst.\n    apply tr.\n    change (S m + r) with (S (m + r)) in *.\n    apply (I.TermHor_lt term); lia.\n  Qed.\n\n  Lemma termrel_div_lt {w τ ts tu} : not (F.Terminating ts) → termrel dir_lt w τ ts tu.\n  Proof.\n    intros div Cs Cu eCs eCu contrel.\n    eauto using Diverge_Obs_lt, F.divergence_closed_under_evalcontext.\n  Qed.\n\n  Lemma termrel_div_wrong {d w τ ts tu} : \n    not (F.Terminating ts) →\n    not (I.Terminating tu) →\n    termrel d w τ ts tu.\n  Proof.\n    intros div divw Cs Cu eCs eCu _.\n    eauto using Diverge_Wrong_Obs, F.divergence_closed_under_evalcontext.\n    eapply Diverge_Wrong_Obs.\n    - eauto using F.divergence_closed_under_evalcontext.\n    - eapply I.divergence_closed_under_evalcontext; assumption.\n  Qed.\n\n  Lemma termrel_size_left {w τ ts tu} :\n    (S (F.size ts) <= w -> termrel dir_lt w τ ts tu) -> termrel dir_lt w τ ts tu.\n  Proof.\n    intros hyp Cs Cu eCs eCu Cr.\n    destruct w; try (cbn; contradiction).\n    intros term.\n    pose proof (sz := F.TermHor_size term).\n    eapply F.size_ectx' in sz; [|assumption].\n    eapply hyp; eauto.\n    lia.\n  Qed.\n\n  Lemma termrel_size_right {w τ ts tu} :\n    (S (I.size tu) <= w -> termrel dir_gt w τ ts tu) -> termrel dir_gt w τ ts tu.\n  Proof.\n    intros hyp Cs Cu eCs eCu Cr.\n    destruct w; try (cbn; contradiction).\n    intros term.\n    pose proof (sz := I.TermHor_size term).\n    eapply I.size_ectx' in sz; [|assumption].\n    eapply hyp; eauto.\n    lia.\n  Qed.\n\n  Lemma termrel_size_right' {d w τ ts tu} :\n    ((d = dir_gt -> S (I.size tu) <= w) -> termrel d w τ ts tu) -> termrel d w τ ts tu.\n  Proof.\n    destruct d.\n    - intros hyp. apply hyp. intros [=].\n    - eauto using termrel_size_right.\n  Qed.\n\nEnd ClosedLR.\n\n\n\nSection OpenLR.\n\n  Lemma compat_var {Γ d n τ i} :\n    ⟪ i : τ p∈ Γ ⟫ →\n    ⟪ Γ ⊩ F.var i ⟦ d , n ⟧ I.var i : τ ⟫.\n  Proof.\n    intros iτ. unfold OpenLRN.\n    split;[|split].\n    - crushTyping.\n      eauto using repEmulCtx_works.\n    - I.crushTyping.\n      eauto using fxToIsCtx_works.\n    - intros ? _ ? ? er.\n      apply valrel_in_termrel.\n      refine (er _ _ iτ).\n  Qed.\n\n  Lemma adequacy_lt {n m ts tu τ} :\n    ⟪ pempty ⊩ ts ⟦ dir_lt , n ⟧ tu : τ ⟫ →\n    F.TermHor ts m →\n    n > m →\n    I.Terminating tu.\n  Proof.\n    intros lr term ineq.\n    destruct lr as (tsty & tuscp & lr).\n    set (w := n).\n    assert (le_w : lev w ≤ n) by (unfold lev, w; lia).\n    assert (er : envrel dir_lt w pempty (idm F.Tm) (idm I.Tm)) by apply envrel_triv.\n    pose proof (lr w le_w (idm F.Tm) (idm I.Tm) er) as tr.\n    rewrite -> ?ap_id in tr.\n    eapply (termrel_adequacy_lt tr term); trivial.\n  Qed.\n\n  Lemma adequacy_gt {n m tu ts τ} :\n    ⟪ pempty ⊩ ts ⟦ dir_gt , n ⟧ tu : τ ⟫ →\n    I.TermHor tu m →\n    n > m →\n    F.Terminating ts.\n  Proof.\n    intros lr term ineq.\n    destruct lr as (tsty & tuscp & lr).\n    set (w := n).\n    assert (le_w : lev w ≤ n) by (unfold lev, w; lia).\n    assert (er : envrel dir_gt w pempty (idm F.Tm) (idm I.Tm)) by apply envrel_triv.\n    (* assert (er : envrel dir_lt w pempty (idm F.Tm) (idm I.Tm)) by apply envrel_triv. *)\n    pose proof (lr w le_w (idm F.Tm) (idm I.Tm) er) as tr.\n    (* pose proof (lr w le_w (idm F.Tm) (idm I.Tm) er) as tr. *)\n    rewrite -> ?ap_id in tr.\n    eapply (termrel_adequacy_gt tr term); trivial.\n  Qed.\n\nEnd OpenLR.\n\nSection TermRelZero.\n\n  Lemma valrel_in_termreli₀ {d dfc w τ ts tu} :\n    valrel d w τ ts tu → termreli₀ d dfc w τ ts tu.\n  Proof.\n    intros vr.\n    destruct (valrel_implies_OfType vr) as [[? ?] ?].\n    unfold termrel₀. simpl.\n    left. exists ts, tu.\n    (* why isn't this enough? *)\n    (* eauto using clos_refl_trans_1n with eval. *)\n    split; [|split]; eauto using clos_refl_trans_1n with eval; constructor.\n  Qed.\n\n  Lemma valrel_in_termrel₀ {d w τ ts tu} :\n    valrel d w τ ts tu → termrel₀ d  w τ ts tu.\n  Proof.\n    unfold termrel₀.\n    eauto using valrel_in_termreli₀.\n  Qed.\n\n  Lemma termrel₀_in_termrel {d w τ ts tu} :\n    termrel₀ d w τ ts tu → termrel d w τ ts tu.\n  Proof.\n    destruct 1 as [(vs & vu & ess & esu & vr)|div].\n    - eauto using termrel_antired_star, valrel_in_termrel.\n    - unfold termrel, termrel'; eauto.\n  Qed.\n\n  Lemma termreli₀_antired {ts ts' tu tu' W d dfc τ i j} dfc' :\n    dfc' + min i j ≥ dfc  →\n    F.evaln ts ts' i →\n    I.evaln tu tu' j →\n    termreli₀ d dfc W τ ts' tu' →\n    termreli₀ d dfc' W τ ts tu.\n  Proof.\n    intros ineq es eu tzi.\n    destruct tzi as [(vs & vu & es' & eu' & vr)|?].\n    - left. exists vs, vu.\n      eapply stepRel_to_evalStar in es.\n      eapply stepRel_to_evalStar in eu.\n      eauto using evalStepTrans with eval.\n    - right. intros Cs Cu eCs eCu.\n      specialize (H Cs Cu eCs eCu).\n\n      pose proof (evaln_ctx eCu eu) as eu'.\n      pose proof (F.evaln_ctx eCs es) as es'.\n      enough (lev (lateri dfc W) + Nat.min i j ≥ lev (lateri dfc' W)) as ineq' by\n          eapply (obs_antired es' eu' ineq' H).\n      rewrite ?lev_lateri; unfold lev.\n      lia.\n  Qed.\n\n  Lemma termreli₀_antired_star {ts ts' tu tu' W d dfc τ} :\n    clos_refl_trans_1n F.Tm F.eval ts ts' →\n    tu -->* tu' →\n    termreli₀ d dfc W τ ts' tu' →\n    termreli₀ d dfc W τ ts tu.\n  Proof.\n    intros es eu tr.\n    destruct tr as [(vs & vu & ess & esu & vr)|div].\n    - left; exists vs, vu.\n      simpl in *.\n      eauto using evalStepTrans.\n    - right. intros Cs Cu eCs eCu.\n      destruct (evalTrans_to_stepRel (F.evalstar_ctx Cs eCs es)) as (? & es').\n      destruct (evalTrans_to_stepRel eu) as (? & eu').\n      pose proof (evaln_ctx eCu eu') as eu''.\n      specialize (div Cs Cu eCs eCu).\n      eapply (obs_antired (W' := (lateri dfc W)) es' eu''); try assumption.\n      rewrite ?lev_lateri.\n      lia.\n  Qed.\n\n  Lemma termreli₀_div_lt {w dfc τ ts tu} : not (F.Terminating ts) → termreli₀ dir_lt dfc w τ ts tu.\n  Proof.\n    intros div. right. intros  Cs Cu eCs eCu.\n    eauto using Diverge_Obs_lt, F.divergence_closed_under_evalcontext.\n  Qed.\n\n  Lemma termreli₀_div_wrong {d dfc w τ ts tu} : \n    not (F.Terminating ts) →\n    not (I.Terminating tu) →\n    termreli₀ d dfc w τ ts tu.\n  Proof.\n    intros div divw. right. intros Cs Cu eCs eCu.\n    eauto using Diverge_Wrong_Obs, F.divergence_closed_under_evalcontext.\n    eapply Diverge_Wrong_Obs.\n    - eauto using F.divergence_closed_under_evalcontext.\n    - eapply I.divergence_closed_under_evalcontext; assumption.\n  Qed.\n  Lemma termrel₀_antired_star {ts ts' tu tu' W d τ} :\n    clos_refl_trans_1n F.Tm F.eval ts ts' →\n    tu -->* tu' →\n    termrel₀ d W τ ts' tu' →\n    termrel₀ d W τ ts tu.\n  Proof.\n    eapply termreli₀_antired_star.\n  Qed.\n\n  Lemma termrel₀_antired_star_left {ts ts' tu W d τ} :\n    clos_refl_trans_1n F.Tm F.eval ts ts' →\n    termrel₀ d W τ ts' tu →\n    termrel₀ d W τ ts tu.\n  Proof.\n    assert (tu -->* tu) by (simpl; eauto with eval).\n    eauto using termrel₀_antired_star.\n  Qed.\n\n  Lemma termrel₀_ectx {d dfc w τ₁ τ₂ ts Cs tu Cu} (eCs : F.ECtx Cs) (eCu : I.ECtx Cu) :\n    termreli₀ d dfc w τ₁ ts tu →\n    (∀ vs vu, valrel d w τ₁ vs vu → termreli₀ d dfc w τ₂ (F.pctx_app vs Cs) (I.pctx_app vu Cu)) →\n    termreli₀ d dfc w τ₂ (F.pctx_app ts Cs) (I.pctx_app tu Cu).\n  Proof.\n    intros trtm trcont.\n    destruct trtm as [(vs & vu & ess & esu & vr)|div].\n    - specialize (trcont vs vu vr).\n      refine (termreli₀_antired_star _ _ trcont);\n        eauto using F.evalstar_ctx, evalstar_ctx.\n    - right.\n      intros Cs' Cu' eCs' eC'.\n      rewrite <- F.pctx_cat_app.\n      rewrite <- I.pctx_cat_app.\n      eauto using F.ectx_cat, I.ectx_cat.\n  Qed.\n\n  Lemma termrel₀_ectx' {d dfc w τ₁ τ₂ ts Cs tu ts' tu' Cu} :\n    termreli₀ d dfc w τ₁ ts tu →\n    (∀ vs vu, valrel d w τ₁ vs vu → termreli₀ d dfc w τ₂ (F.pctx_app vs Cs) (I.pctx_app vu Cu)) →\n    ts' = F.pctx_app ts Cs →\n    tu' = I.pctx_app tu Cu →\n    F.ECtx Cs → I.ECtx Cu →\n    termreli₀ d dfc w τ₂ ts' tu'.\n  Proof.\n    intros. subst.\n    eauto using termrel₀_ectx.\n  Qed.\n\n  Lemma termrel₀_zero {d τ ts tu} :\n    termrel₀ d 0 τ ts tu.\n  Proof.\n    right.\n    intros Cs Cu eCs eCu.\n    eapply obs_zero.\n  Qed.\n\n  Lemma termrel₀_ectx'' {d w' w τ₁ τ₂ ts Cs tu Cu} (eCs : F.ECtx Cs) (eCu : I.ECtx Cu) :\n    termrel₀ d w' τ₁ ts tu →\n    (∀ vs vu, valrel d w' τ₁ vs vu → termrel₀ d w τ₂ (F.pctx_app vs Cs) (I.pctx_app vu Cu)) →\n    w ≤ w' →\n    termrel₀ d w τ₂ (F.pctx_app ts Cs) (I.pctx_app tu Cu).\n  Proof.\n    intros trtm trcont ineq.\n    destruct trtm as [(vs & vu & ess & esu & vr)|div].\n    - specialize (trcont vs vu vr).\n      refine (termrel₀_antired_star _ _ trcont);\n        eauto using F.evalstar_ctx, evalstar_ctx.\n    - right.\n      intros Cs' Cu' eCs' eC'.\n      rewrite <- F.pctx_cat_app.\n      rewrite <- I.pctx_cat_app.\n      eauto using F.ectx_cat, I.ectx_cat, obs_mono.\n  Qed.\n\n  Lemma termrel₀_ectx''' {d w w' τ₁ τ₂ ts Cs tu ts' tu' Cu} :\n    termrel₀ d w' τ₁ ts tu →\n    (∀ vs vu, valrel d w' τ₁ vs vu → termrel₀ d w τ₂ (F.pctx_app vs Cs) (I.pctx_app vu Cu)) →\n    ts' = F.pctx_app ts Cs →\n    tu' = I.pctx_app tu Cu →\n    F.ECtx Cs → I.ECtx Cu →\n    w ≤ w' →\n    termrel₀ d w τ₂ ts' tu'.\n  Proof.\n    intros. subst.\n    eauto using termrel₀_ectx''.\n  Qed.\n\n  Lemma termreli₀_dfc_mono {d dfc dfc' w τ ts tu}:\n    termreli₀ d dfc w τ ts tu →\n    dfc ≤ dfc' →\n    termreli₀ d dfc' w τ ts tu.\n  Proof.\n    destruct 1 as [(vs & vu & ess & esu & vr)|div]; intros ineq.\n    - left. exists vs, vu. eauto. \n    - right. intros Cs Cu eCs eCu.\n      specialize (div Cs Cu eCs eCu).\n      refine (obs_mono _ div).\n      rewrite ?lev_lateri.\n      lia.\n  Qed.\n\n  Lemma termreli₀_ectx {d dfc w τ₁ τ₂ ts Cs tu Cu} (eCs : F.ECtx Cs) (eCu : I.ECtx Cu) :\n    termrel₀ d (lateri dfc w) τ₁ ts tu →\n    lev w ≥ dfc →\n    (∀ vs vu, valrel d (lateri dfc w) τ₁ vs vu → termreli₀ d dfc w τ₂ (F.pctx_app vs Cs) (I.pctx_app vu Cu)) →\n    termreli₀ d dfc w τ₂ (F.pctx_app ts Cs) (I.pctx_app tu Cu).\n  Proof.\n    intros trtm ineq trcont.\n    destruct trtm as [(vs & vu & ess & esu & vr)|div].\n    - specialize (trcont vs vu vr).\n      eapply termreli₀_antired_star in trcont;\n        eauto using F.evalstar_ctx, evalstar_ctx.\n    - right.\n      intros Cs' Cu' eCs' eC'.\n      rewrite <- F.pctx_cat_app.\n      rewrite <- I.pctx_cat_app.\n      eauto using F.ectx_cat, I.ectx_cat.\n  Qed.\n\n  Lemma termreli₀_ectx' {d dfc w τ₁ τ₂ ts Cs tu ts' tu' Cu} :\n    termrel₀ d (lateri dfc w) τ₁ ts tu →\n    lev w ≥ dfc →\n    (∀ vs vu, valrel d (lateri dfc w) τ₁ vs vu → termreli₀ d dfc w τ₂ (F.pctx_app vs Cs) (I.pctx_app vu Cu)) →\n    ts' = F.pctx_app ts Cs →\n    tu' = I.pctx_app tu Cu →\n    F.ECtx Cs → I.ECtx Cu →\n    termreli₀ d dfc w τ₂ ts' tu'.\n  Proof.\n    intros. subst.\n    eauto using termreli₀_ectx.\n  Qed.\n\nEnd TermRelZero.\n\nSection TermRelZeroNoDiv.\n  Lemma valrel_termrelnd₀ {d w τ ts tu} :\n    valrel d w τ ts tu -> termrelnd₀ d w τ ts tu.\n  Proof.\n    intros vr.\n    destruct (valrel_implies_OfType vr) as [[vts ots] [vtu otu]].\n    destruct d.\n    - intros vs vvs es.\n      destruct (F.value_evalStar vts es).\n      exists tu; split; [assumption|]; split; eauto with eval.\n    - intros vu vvu eu.\n      destruct (I.value_evalStar vtu eu).\n      exists ts; split; [assumption|]; split; eauto with eval.\n  Qed.\n\n  Lemma termrelnd₀_termrel {d w τ ts tu} :\n    termrelnd₀ d w τ ts tu -> termrel d w τ ts tu.\n  Proof.\n    destruct d; cbn; intros tr.\n    - intros Cs Cu eCs eCu cr term.\n      destruct w; cbn in term; try contradiction.\n      destruct term as (v & vv & es).\n      destruct (F.evalHor_ectx_inv Cs eCs es vv) as (v' & vv' & es' & es'').\n      destruct (tr v' vv' es') as (vu & vvu & eu & vr').\n      eapply (evalstar_ctx Cu) in eu; eauto.\n      eapply (termination_closed_under_antireductionStar eu).\n      refine (cr _ _ _ _ vr' _); [lia|].\n      exists v; eauto.\n    - intros Cs Cu eCs eCu cr term.\n      destruct w; cbn in term; try contradiction.\n      destruct (I.TermHor_ectx_inv Cu eCu term) as (v' & vv' & es' & v'' & vv'' & es'').\n      destruct (tr v' vv' es') as (vu & vvu & eu & vr').\n      eapply (F.evalstar_ctx Cs) in eu; eauto.\n      eapply (F.termination_closed_under_antireductionStar eu).\n      refine (cr _ _ _ _ vr' _); [lia|].\n      exists v''; repeat split; eauto with arith.\n  Qed.\n\n  Lemma termrelnd₀_antired {d w τ ts ts' tu tu'} :\n    F.evalStar ts' ts -> tu' -->* tu ->\n    termrelnd₀ d w τ ts tu -> termrelnd₀ d w τ ts' tu'.\n  Proof.\n    intros es eu tr.\n    destruct d.\n    - intros vs vvs es'.\n      assert (es'' := F.determinacyStar es es' (F.values_are_normal vvs)).\n      destruct (tr vs vvs es'') as (vu & vvu & eu' & vr).\n      exists vu; repeat (split; eauto).\n      refine (evalStepTrans _ eu eu').\n    - intros vu vvu eu'.\n      assert (eu'' := I.determinacyStar eu eu' (I.values_are_normal vvu)).\n      destruct (tr vu vvu eu'') as (vs & vvs & es' & vr).\n      exists vs; repeat (split; eauto).\n      refine (evalStepTrans _ es es').\n  Qed.\n\n  Lemma termrelnd₀_antired_left {d w τ ts ts' tu} :\n    F.evalStar ts' ts ->\n    termrelnd₀ d w τ ts tu -> termrelnd₀ d w τ ts' tu.\n  Proof.\n    eauto using termrelnd₀_antired with eval.\n  Qed.\n\n  Lemma termrelnd₀_red {d w τ ts ts' tu tu'} :\n    F.evalStar ts ts' -> tu -->* tu' ->\n    termrelnd₀ d w τ ts tu -> termrelnd₀ d w τ ts' tu'.\n  Proof.\n    intros es eu tr.\n    destruct d.\n    - intros vs vvs es'.\n      destruct (tr vs vvs (evalStepTrans _ es es')) as (vu & vvu & eu' & vr).\n      exists vu; repeat (split; eauto).\n      refine (I.determinacyStar eu eu' (I.values_are_normal vvu)).\n    - intros vu vvu eu'.\n      destruct (tr vu vvu (evalStepTrans _ eu eu')) as (vs & vvs & es' & vr).\n      exists vs; repeat (split; eauto).\n      refine (F.determinacyStar es es' (F.values_are_normal vvs)).\n  Qed.\n\n  Lemma termrelnd₀_ectx {d w w' τ₁ τ₂ ts Cs tu Cu} (eCs : F.ECtx Cs) (eCu : I.ECtx Cu) :\n    termrelnd₀ d w τ₁ ts tu →\n    (∀ vs vu, valrel d w τ₁ vs vu → termrelnd₀ d w' τ₂ (F.pctx_app vs Cs) (I.pctx_app vu Cu)) →\n    termrelnd₀ d w' τ₂ (F.pctx_app ts Cs) (I.pctx_app tu Cu).\n  Proof.\n    intros tr cr.\n    destruct d.\n    - intros vs vvs es.\n      destruct (F.evalStar_ectx_inv Cs ts eCs vs es vvs) as (vs' & vvs' & es1 & es2).\n      destruct (tr vs' vvs' es1) as (vu & vvu & eu & vr2).\n      specialize (cr vs' vu vr2).\n      destruct (cr vs vvs es2) as (vu2 & vvu2 & eu2 & vr3).\n      exists vu2.\n      eapply (evalstar_ctx Cu eCu) in eu.\n      split; [|split]; eauto using evalStepTrans.\n    - intros vu vvu eu.\n      destruct (I.evalStar_ectx_inv Cu tu eCu vu eu vvu) as (vu' & vvu' & eu1 & eu2).\n      destruct (tr vu' vvu' eu1) as (vs & vvs & es & vr2).\n      specialize (cr vs vu' vr2).\n      destruct (cr vu vvu eu2) as (vs2 & vvs2 & es2 & vr3).\n      exists vs2.\n      eapply (F.evalstar_ctx Cs eCs) in es.\n      split; [|split]; eauto using evalStepTrans.\n  Qed.\n\n  Lemma termrelnd₀_ectx' {d w w' τ₁ τ₂ ts Cs tu ts' tu' Cu} :\n    termrelnd₀ d w τ₁ ts tu →\n    ts' = F.pctx_app ts Cs →\n    tu' = I.pctx_app tu Cu →\n    (∀ vs vu, valrel d w τ₁ vs vu → termrelnd₀ d w' τ₂ (F.pctx_app vs Cs) (I.pctx_app vu Cu)) →\n    F.ECtx Cs → I.ECtx Cu →\n    termrelnd₀ d w' τ₂ ts' tu'.\n  Proof.\n    intros; subst; eauto using termrelnd₀_ectx.\n  Qed.\n\n\n  (* interestingly, the following doesn't seem to hold with termrel instead of termrelnd₀. *)\n  Lemma termrelnd₀_ectx_sub {d w τ₁ τ₂ ts vu tub} Cs (eCs : F.ECtx Cs) {vvu : I.Value vu} :\n    (* termrel d (S w) τ₁ ts vu → *)\n    termrelnd₀ d w τ₁ ts vu →\n    (∀ {vs}, valrel d w τ₁ vs vu → termrel d w τ₂ (F.pctx_app vs Cs) (tub [beta1 vu])) →\n    termrel d w τ₂ (F.pctx_app ts Cs) (tub [beta1 vu]).\n  Proof.\n    intros tr contr.\n    intros Cs' Cu' eCs' eCu' cr'.\n    destruct d.\n    - destruct w; try (cbn; contradiction).\n      intros term.\n      rewrite <-F.pctx_cat_app in term.\n      destruct (F.TermHor_ectx_inv (F.pctx_cat Cs Cs') (F.ectx_cat Cs Cs' eCs eCs') term) as (vs' & vvs' & es' & term').\n      destruct (tr vs' vvs' es') as (vu' & vvu' & eu' & vr').\n      destruct (I.normal_evalStar (I.values_are_normal vvu) eu').\n      clear vvu' tr eu' term.\n      rewrite F.pctx_cat_app in term'.\n      refine (contr _ vr' Cs' Cu' eCs' eCu' cr' term'); lia.\n    - destruct w; try (cbn; contradiction).\n      destruct (tr vu vvu (rt1n_refl _ _ _)) as (vs' & vvs' & es' & vr).\n      eapply obs_antired_star.\n      + eapply (F.evalstar_ctx _ eCs').\n        refine (F.evalstar_ctx _ eCs es').\n      + eapply rt1n_refl.\n      + refine (contr vs' vr Cs' Cu' eCs' eCu' cr').\n  Qed.\n\n  Lemma termrelnd₀_div_lt {ts tu W τ} :\n    not (F.Terminating ts) ->\n    termrelnd₀ dir_lt W τ ts tu.\n  Proof.\n    intros div vs vvs es.\n    contradict div.\n    now exists vs.\n  Qed.\n\nEnd TermRelZeroNoDiv.\n\n\nLtac crushLRMatch :=\n  match goal with\n      [ |- _ ∧ _ ] => split\n    | [ |- context[ lev ]] => unfold lev\n    | [ H : context[ lev ] |- _ ] => unfold lev in *\n    | [ |- ⟪ _ ⊩ _ ⟦ _ , _ ⟧ _ : _ ⟫ ] => (unfold OpenLRN; split)\n    | [ H : ⟪ _ ⊩ _ ⟦ _ , _ ⟧ _ : _ ⟫ |- _ ] => (unfold OpenLRN in H; destruct_conjs)\n    | [ H : valrel ?d _ ?τ ?ts ?tu |- termrel ?d _ ?τ ?ts ?tu ] => apply valrel_in_termrel\n    | [ |- termrel _ _ _ (F.abs _ _) (I.abs _ _) ] => apply valrel_in_termrel\n    | [ |- termrel _ _ _ F.unit I.unit ] => apply valrel_in_termrel\n    | [ |- termrel _ _ _ F.false I.false ] => apply valrel_in_termrel\n    | [ |- termrel _ _ _ F.true I.true ] => apply valrel_in_termrel\n    | [ H : valrel ?d ?w ?τ ?ts ?tu |- valrel ?d ?w' ?τ ?ts ?tu ] => (refine (valrel_mono _ H); try lia)\n    | [ H : envrel ?d ?w ?τ ?ts ?tu |- envrel ?d ?w' ?τ ?ts ?tu ] => (refine (envrel_mono _ H); try lia)\n    | [ |- envrel ?d ?w (?Γ p▻ ?τ) (?γs↑ >=> beta1 ?ts) (?γu↑ >=> beta1 ?tu) ] => refine (extend_envrel _ _)\n    | [ H : valrel _ _ ?τ ?ts ?tu |- OfType ?τ ?ts ?tu ] => refine (valrel_implies_OfType H)\n    | [ |- valrel _ _ _ _ _] => rewrite -> valrel_fixp in |- *; unfold valrel' in |- *\n    | [ |- F.ECtx (F.pctx_cat _ _) ] => apply F.ectx_cat\n    | [ |- I.ECtx (I.pctx_cat _ _) ] => apply I.ectx_cat\n  end.\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/LogRelFI/LemmasLR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2581195788282526}}
{"text": "(** * JCC (rel) 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(** For convenience, the [~~b] branch is not under a [|>] operator\n    since [q] will never be equal to [p], and thus there is no risk of\n    recursion. *)\nLemma JCCrel_rule rel cc cv (b:bool) (p q: DWORD) :\n  |-- (\n      |> safe @ (b == cv /\\\\ EIP ~= (addB q rel) ** ConditionIs cc b) //\\\\\n         safe @ (b == (~~cv) /\\\\ EIP ~= q ** ConditionIs cc b) -->>\n      safe @ (EIP ~= p ** ConditionIs cc b)\n    ) <@ (p -- q :-> JCCrel cc cv (mkTgt rel)).\nProof.\n  rewrite ->(spec_later_weaken (safe @ (b == (~~ cv) /\\\\ EIP~=q ** ConditionIs cc b))).\n  rewrite <-spec_later_and. rewrite ->spec_at_and_or; last apply _.\n  apply TRIPLE_safe => R. rewrite /evalInstr.\n  triple_apply triple_letGetCondition.\n  replace (b == (~~cv)) with (~~(b == cv)); last first.\n  { case: b; case: cv; reflexivity. }\n  case: (b == cv).\n  { instrrule_triple_bazooka using do [ progress sbazooka | apply: lorR1 ]. }\n  { instrrule_triple_bazooka using do [ progress sbazooka | apply: lorR2 ]. }\nQed.\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/jccrel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.25800915632788385}}
{"text": "Require Import AST.\nRequire Import Coqlib.\n\nRequire Import sepcomp.extspec.\nRequire Import sepcomp.core_semantics.\nRequire Import sepcomp.forward_simulations.\n\nSection safety.\n  Context {G C M D Z:Type}.\n  Context (Hcore:CoreSemantics G C M).\n  Variable (Hspec:external_specification M external_function Z).\n\n  Variable ge : G.\n\n  Fixpoint safeN (n:nat) (z:Z) (c:C) (m:M) : Prop :=\n    match n with\n    | O => True\n    | S n' =>\n       match at_external Hcore c, halted Hcore c with\n       | None, None =>\n           exists c', exists m',\n             corestep Hcore ge c m c' m' /\\\n             safeN n' z c' m'\n       | Some (e,sig,args), None =>\n           exists x:ext_spec_type Hspec e,\n             ext_spec_pre Hspec e x (sig_args sig) args z m /\\\n             (forall ret m' z',\n               ext_spec_post Hspec e x (sig_res sig) ret z' m' ->\n               exists c',\n                 after_external Hcore ret c = Some c' /\\\n                 safeN n' z' c' m')\n       | None, Some i => ext_spec_exit Hspec (Some i) z m\n       | Some _, Some _ => False\n       end\n    end.\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.\n    erewrite corestep_not_at_external in H1; eauto.\n    erewrite corestep_not_halted in H1; eauto.\n    destruct H1 as [c'' [m'' [? ?]]].\n    assert ((c',m') = (c'',m'')).\n    eapply H; eauto.\n   inv H3; auto.\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    simpl; intros.\n    erewrite corestep_not_at_external; eauto.\n    erewrite corestep_not_halted; 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; simpl; intros; auto.\n    destruct (at_external Hcore c);\n      destruct (halted Hcore c).\n    destruct p; auto.\n    destruct p. destruct p.\n    destruct H as [x ?].\n    exists x.\n    destruct H. split; auto.\n    intros. specialize (H0 ret m' z' H1).\n    destruct H0 as [c' [? ?]].\n    exists c'; split; auto.\n    auto.\n    destruct H as [c' [m' [? ?]]].\n    exists c'. exists m'; split; auto.\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 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' -> 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 *; auto.\n    rewrite H in H3. rewrite H1 in H3.\n    destruct (at_external Hcore q2);\n      destruct (halted Hcore q2); auto.\n    destruct p. destruct p.\n    destruct H3 as [x ?].\n    exists x.\n    destruct H3; split; auto.\n    intros. specialize (H4 ret m' z' H5).\n    destruct H4 as [c' [? ?]].\n    exists c'; split; auto.\n    destruct H3 as [c' [m' [? ?]]].\n    exists c'. exists m'; split; auto.\n  Qed.\n\n\nLemma 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.\nProof.\n  intros.\n  destruct n.\n  hnf. auto.\n  simpl in H0.\n  replace (n-0)%nat with n in H0.\n  eapply safe_corestep_backward; eauto.\n  omega.\nQed.\n\nLemma wlog_safeN_gt0 : forall\n  n z q m,\n  (lt 0 n -> safeN n z q m) ->\n  safeN n z q m.\nProof.\n  intros. destruct n.\n  hnf. auto.\n  apply H. omega.\nQed.\n\nEnd safety.\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/step_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2580091563278838}}
{"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 RC11 *)\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 E := unknown_set \"E\".\nDefinition REL := unknown_set \"REL\".\nDefinition RLX := unknown_set \"RLX\".\nDefinition SC := unknown_set \"SC\".\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 mo := co.\nDefinition sb := po.\nDefinition myrmw := [RMW] ⊔ rmw.\nDefinition rb := rf° ⋅ mo ⊓ !id.\nDefinition eco := (rf ⊔ (mo ⊔ rb))^+.\nDefinition rs := [W] ⋅ ((sb ⊓ loc ⊔ 1) ⋅ ([(W ⊓ (RLX ⊔ (REL ⊔ (ACQ_REL ⊔ (ACQ ⊔ SC)))))] ⋅ (rf ⋅ myrmw)^*)).\nDefinition sw := [(REL ⊔ (ACQ_REL ⊔ SC))] ⋅ (([F] ⋅ sb ⊔ 1) ⋅ (rs ⋅ (rf ⋅ ([(R ⊓ (RLX ⊔ (REL ⊔ (ACQ ⊔ (ACQ_REL ⊔ SC)))))] ⋅ ((sb ⋅ [F] ⊔ 1) ⋅ [(ACQ ⊔ (ACQ_REL ⊔ SC))]))))).\nDefinition hb := (sb ⊔ sw)^+.\nDefinition sbl := sb ⊓ !loc.\nDefinition hbl := hb ⊓ loc.\nDefinition scb := sb ⊔ (sbl ⋅ (hb ⋅ sbl) ⊔ (hbl ⊔ (mo ⊔ rb))).\nDefinition pscb := ([SC] ⊔ [(F ⊓ SC)] ⋅ (hb ⊔ 1)) ⋅ (scb ⋅ ([SC] ⊔ (hb ⊔ 1) ⋅ [(F ⊓ SC)])).\nDefinition pscf := [(F ⊓ SC)] ⋅ ((hb ⊔ hb ⋅ (eco ⋅ hb)) ⋅ [(F ⊓ SC)]).\nDefinition psc := pscb ⊔ pscf.\nDefinition cnf := ([W] ⋅ top ⋅ [top] ⊔ [top] ⋅ top ⋅ [W]) ⊓ loc ⊓ !([IW] ⋅ top ⋅ [top] ⊔ [top] ⋅ top ⋅ [IW]).\nDefinition dr := cnf ⊓ ext ⊓ !(hb ⊔ (hb° ⊔ [A] ⋅ top ⋅ [A])).\nDefinition co0_0 := hb ⋅ eco ⊔ (hb ⊔ myrmw ⋅ eco).\nDefinition at0 := myrmw ⊓ rb ⋅ mo.\nDefinition sc0 := psc^* ⊓ [E].\nDefinition th0 := (sb ⊔ rf)^* ⊓ [E].\nDefinition Dr := is_empty dr.\nDefinition coherence1 := irreflexive (hb ⋅ (eco ⊔ 1)).\nDefinition coherencermw := irreflexive (myrmw ⋅ eco).\nDefinition atomicity := is_empty (myrmw ⊓ rb ⋅ mo).\nDefinition SC_0 := acyclic psc.\nDefinition no_thin_air := acyclic (sb ⊔ rf).\nDefinition witness_conditions := generate_cos cobase co.\nDefinition model_conditions := Dr /\\ (coherence1 /\\ (coherencermw /\\ (atomicity /\\ (SC_0 /\\ no_thin_air)))).\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 E REL RLX SC 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 mo sb myrmw rb eco rs sw hb sbl hbl scb pscb pscf psc cnf dr co0_0 at0 sc0 th0 Dr coherence1 coherencermw atomicity SC_0 no_thin_air 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 RC11 *)\n", "meta": {"author": "jmadiot", "repo": "cats", "sha": "d3d6cae610dbd41c8a00d8cbdc0374cb02d6de95", "save_path": "github-repos/coq/jmadiot-cats", "path": "github-repos/coq/jmadiot-cats/cats-d3d6cae610dbd41c8a00d8cbdc0374cb02d6de95/models/rc11.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.63341024983754, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2580091506902673}}
{"text": "\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import ProofIrrelevance.\nRequire Import Eqdep_dec.\n\nRequire Import foltl.\nRequire Import dec.\nRequire Import finite.\n\nSection SubInterp.\n\n  Context {Ts: Type} {Tv: Ts->Type} {Tc: Ts->Type} {Tp: Type}.\n  Variable srcSig: @Sig Ts Tv Tc Tp.\n\n  Ltac psemTac :=\n    match goal with\n      H:psem _ _ ?sa |- psem _ _ ?sa' => assert (sa' = sa) as ae;\n          try (rewrite ae; assumption); (apply functional_extensionality_dep; intros)\n    end.\n\n  Record subInterp {D1 D2: Dom srcSig} (I1: Interp D1) (I2: Interp D2): Type := {\n    si_m: forall s, ssem (Dom:=D1) s -> ssem (Dom:=D2) s;\n    si_inj: forall s d1 d2, si_m s d1 = si_m s d2 -> d1 = d2;\n    si_c: forall s c, csem (Interp:=I2) c = si_m s (csem (Interp:=I1) c);\n    si_p: forall p t a, psem (Interp:=I1) p t a <-> psem (Interp:=I2) p t (fun i => si_m _ (a i))\n  }.\n  Arguments si_m [_ _ _ _ ]_ _.\n  Arguments si_inj [_ _ _ _ ].\n  Arguments si_c [_ _ _ _ ].\n  Arguments si_p [_ _ _ _ ].\n\n  Lemma subItp_refl: forall {D: Dom srcSig} (Itp: Interp D),\n    subInterp Itp Itp.\n  Proof.\n    intros; split with (si_m:=fun s x => x); intros; auto.\n    split; intro; psemTac; auto.\n  Qed.\n\n  Definition subEnv {D1 D2: Dom srcSig} {I1: Interp D1} {I2: Interp D2} (si: subInterp I1 I2) (env1: Env srcSig D1) (env2: Env srcSig D2) :=\n    forall s v, env2 s v = si_m si s (env1 s v).\n\n  Lemma subEnv_add: forall {D1 D2: Dom srcSig} {I1: Interp D1} {I2: Interp D2} (si: subInterp I1 I2) (env1: Env srcSig D1) (env2: Env srcSig D2) s v d,\n    subEnv si env1 env2 ->\n      subEnv si (add srcSig v d env1) (add srcSig v (si_m si s d) env2).\n  Proof.\n    repeat intro.\n    unfold add.\n    destruct (eq_dec s s0).\n    subst s0.\n    destruct (eq_dec v v0); auto.\n    apply H.\n  Qed.\n  \n  Lemma subEnv_iadd: forall {D1 D2: Dom srcSig} {I1: Interp D1} {I2: Interp D2} (si: subInterp I1 I2) (env1: Env srcSig D1) (env2: Env srcSig D2)\n    `(K: Finite) (sk: K->Sort) (vk: forall k, variable (sk k)) (dk: forall k, ssem (sk k)),\n    subEnv si env1 env2 ->\n      subEnv si (iadd srcSig K sk vk dk env1)\n                (iadd srcSig K sk vk (fun k : K => si_m si (sk k) (dk k))\n                  env2).\n  Proof.\n    repeat intro.\n    unfold iadd.\n    destruct (ex_dec (fun k : K => isEq2 (sk k) (vk k) s v)).\n    destruct s0 as [k h].\n    simpl in h.\n    destruct (eq_dec (sk k) s).\n    subst s.\n    destruct (eq_dec (vk k) v).\n    subst v.\n    rewrite (proof_irrelevance _ h eq_refl); auto.\n    exfalso.\n    apply inj_pair2_eq_dec in h; auto.\n    apply eq_dec.\n    exfalso.\n    injection h; clear h; simpl; intros.\n    apply (n H1).\n    apply H.\n  Qed.\n  \n  Lemma tm_siSat: forall {D1 D2: Dom srcSig} {I1: Interp D1} {I2: Interp D2} (si: subInterp I1 I2) (env1: Env srcSig D1) (env2: Env srcSig D2) s (tm: term _ s),\n    subEnv si env1 env2 ->\n      tm_sem srcSig (Itp:=I2) env2 tm = si_m si s (tm_sem srcSig (Itp:=I1) env1 tm).\n  Proof.\n    intros.\n    destruct tm; simpl.\n    apply H.\n    apply (si_c si).\n  Qed.\n  \n  Lemma lt_siSat: forall {D1 D2: Dom srcSig} {I1: Interp D1} {I2: Interp D2} (si: subInterp I1 I2) (env1: Env srcSig D1) (env2: Env srcSig D2) a t,\n    subEnv si env1 env2 ->\n      lt_sem srcSig (Itp:=I2) env2 a t <-> lt_sem srcSig (Itp:=I1) env1 a t.\n  Proof.\n    intros.\n    destruct a; simpl in *.\n    rewrite (si_p si).\n    split; intro.\n    psemTac.\n    symmetry; apply tm_siSat; auto.\n    psemTac.\n    apply tm_siSat; auto.\n  Qed.\n\n  Lemma at_siSat: forall {D1 D2: Dom srcSig} {I1: Interp D1} {I2: Interp D2} (si: subInterp I1 I2) (env1: Env srcSig D1) (env2: Env srcSig D2) a t,\n    subEnv si env1 env2 ->\n      at_sem srcSig (Itp:=I2) env2 a t <-> at_sem srcSig (Itp:=I1) env1 a t.\n  Proof.\n    intros.\n    destruct a; simpl in *.\n    apply lt_siSat with (si0:=si); auto.\n    apply not_iff_compat.\n    apply lt_siSat with (si0:=si); now auto.\n    rewrite tm_siSat with (si0:=si) (env3:=env1); auto.\n    rewrite tm_siSat with (si0:=si) (env3:=env1); auto.\n    split; intro.\n    apply si_inj in H0; apply H0.\n    f_equal; apply H0.\n    \n    apply not_iff_compat.\n    rewrite tm_siSat with (si0:=si) (env3:=env1); auto.\n    rewrite tm_siSat with (si0:=si) (env3:=env1); auto.\n    split; intro.\n    apply si_inj in H0; apply H0.\n    f_equal; apply H0.\n  Qed.\n\n  Theorem fm_siSat: forall {D1 D2: Dom srcSig} (I1: Interp D1) (I2: Interp D2) (si: subInterp I1 I2) f (env1: Env srcSig D1) (env2: Env srcSig D2) t,\n    noEx srcSig f -> subEnv si env1 env2 ->\n      fm_sem srcSig (Itp:=I2) env2 f t -> \n        fm_sem srcSig (Itp:=I1) env1 f t.\n  Proof.\n    induction f; simpl; intros; try tauto.\n  - revert H1; apply (at_siSat si); auto.\n  - destruct H1.\n    split; [revert H1; apply IHf1 | revert H2; apply IHf2]; intros; auto; tauto.\n  - destruct H1; [left; revert H1; apply IHf1 | right; revert H1; apply IHf2]; auto; tauto.\n  - specialize H1 with (si_m si _ d).\n    revert H1; apply IHf; auto.\n    apply subEnv_add; auto.\n  - destruct H1 as [t' [h1 h2]].\n    exists t'; split; auto.\n    revert h2; apply IHf; auto.\n  - generalize (H1 t' H2); clear H1; intro.\n    revert H1; apply IHf; auto.\n  Qed.\n\nEnd SubInterp.\n", "meta": {"author": "grayswandyr", "repo": "cervino", "sha": "556fe8e07c658f925e648cca34bdf1c93453198c", "save_path": "github-repos/coq/grayswandyr-cervino", "path": "github-repos/coq/grayswandyr-cervino/cervino-556fe8e07c658f925e648cca34bdf1c93453198c/coq/subItp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2578571546726192}}
{"text": "Require Import Coq.Strings.String.\n\nRequire Export SystemFR.ScalaDepSugar.\nRequire Export SystemFR.ErasedRecGen.\nRequire Export SystemFR.StepTactics.\n\nOpaque reducible_values.\n\nLemma evaluate_list_match:\n  forall ρ v t2 t3,\n    valid_interpretation ρ ->\n    wf t2 0 ->\n    wf t3 2 ->\n    is_erased_term t2 ->\n    is_erased_term t3 ->\n    pfv t2 term_var = nil ->\n    pfv t3 term_var = nil ->\n    [ ρ ⊨ v : List ]v -> (\n      (v = tnil /\\ list_match v t2 t3 ~>* t2) \\/\n      (exists h l,\n         closed_value h /\\\n         closed_value l /\\\n         v = tcons h l /\\\n         [ ρ ⊨ h : T_top ]v /\\\n         [ ρ ⊨ l : List ]v /\\\n         [ list_match v t2 t3 ≡ open 0 (open 1 t3 h) l ]\n      )\n    ).\nProof.\n  unfold List, list_match.\n  intros.\n  apply (reducible_values_unfold_gen _ _ _ _ 0) in H6;\n    repeat step || simp_spos.\n    simp_red_top_level_hyp; repeat step.\n\n  - simp_red_top_level_hyp; left; steps; one_step.\n  - simp_red_top_level_hyp; right; steps.\n    eexists; eexists; repeat step || simp_red_goal; t_closer; eauto using reducible_value_expr.\n    apply equivalent_trans with (open 0 (open 1 t3 (pi1 (pp a b))) (pi2 (pp a b))).\n    + equivalent_star;\n        eauto 3 with erased step_tactic;\n        eauto 3 with wf step_tactic;\n        try solve [ repeat apply pfv_shift_open || step ].\n\n      apply star_one.\n      eapply scbv_step_same.\n      * apply SPBetaMatchRight; t_closer.\n      * rewrite open_shift_open3; steps; t_closer;\n          eauto 3 with wf step_tactic.\n        rewrite open_shift_open4; steps; t_closer;\n          eauto 3 with wf step_tactic.\n        rewrite no_shift_open; t_closer.\n        rewrite no_shift_open; t_closer.\n        rewrite open_twice; steps; t_closer.\n\n    + eapply equivalent_trans.\n      * apply equivalent_context; steps;\n          try solve [ apply is_erased_open; steps; t_closer ];\n          try solve [ apply wf_open; steps; t_closer ];\n          try solve [ apply fv_nils_open; steps; t_closer ].\n        apply equivalent_star; repeat step || list_utils; t_closer.\n        apply star_one.\n        constructor; t_closer.\n      * rewrite (swap_term_holes_open t3); steps; t_closer.\n        rewrite (swap_term_holes_open t3); steps; t_closer.\n        apply equivalent_context; steps;\n          try solve [ apply is_erased_open; steps; t_closer ];\n          try solve [ apply wf_open; steps; t_closer ];\n          try solve [ apply fv_nils_open; steps; t_closer ];\n          try solve [ apply wf_open; steps; t_closer; eauto with wf ].\n        apply equivalent_star; repeat step || list_utils; t_closer.\n        apply star_one.\n        constructor; t_closer.\nQed.\n\nLtac evaluate_list_match :=\n  match goal with\n  | H: valid_interpretation ?ρ |- context[list_match ?v ?t2 ?t3] =>\n    poseNew (Mark (v, t2, t3) \"evaluate_list_match\");\n    unshelve epose proof (evaluate_list_match ρ v t2 t3 _ _ _ _ _ _ _ _)\n  | H: valid_interpretation ?ρ, H2: context[list_match ?v ?t2 ?t3] |- _ =>\n    poseNew (Mark (v, t2, t3) \"evaluate_list_match\");\n    unshelve epose proof (evaluate_list_match ρ v t2 t3 _ _ _ _ _ _ _ _)\n  | H: context[list_match ?v ?t2 ?t3] |- _ =>\n    poseNew (Mark (v, t2, t3) \"evaluate_list_match\");\n    unshelve epose proof (evaluate_list_match nil v t2 t3 _ _ _ _ _ _ _ _)\n  end.\n\nLemma evaluate_list_match_scrut:\n  forall t t' t2 t3,\n    t ~>* t' ->\n    list_match t t2 t3 ~>* list_match t' t2 t3.\nProof.\n  unfold list_match; steps; eauto with cbvlemmas.\nQed.\n\nLemma evaluate_list_match2:\n  forall ρ t t2 t3,\n    valid_interpretation ρ ->\n    wf t2 0 ->\n    wf t3 2 ->\n    is_erased_term t2 ->\n    is_erased_term t3 ->\n    pfv t2 term_var = nil ->\n    pfv t3 term_var = nil ->\n    [ ρ ⊨ t : List ] -> (\n      (t ~>* tnil /\\ list_match t t2 t3 ~>* t2) \\/\n      (exists h l,\n         closed_value h /\\\n         closed_value l /\\\n         t ~>* tcons h l /\\\n         [ ρ ⊨ h : T_top ]v /\\\n         [ ρ ⊨ l : List ]v /\\\n         [ list_match t t2 t3 ≡ open 0 (open 1 t3 h) l ]\n      )\n    ).\nProof.\n  intros.\n  unfold reduces_to in * |-; steps.\n  unshelve epose proof (evaluate_list_match ρ v t2 t3 _ _ _ _ _ _ _ _); steps.\n  - left; steps; eauto using star_trans, evaluate_list_match_scrut.\n  - right; exists h, l; steps.\n    eapply equivalent_trans; eauto; equivalent_star; eauto using evaluate_list_match_scrut.\nQed.\n\nLtac evaluate_list_match2 :=\n  match goal with\n  | H: valid_interpretation ?ρ |- context[list_match ?t ?t2 ?t3] =>\n    poseNew (Mark (t, t2, t3) \"evaluate_list_match2\");\n    unshelve epose proof (evaluate_list_match2 ρ t t2 t3 _ _ _ _ _ _ _ _)\n  | H: valid_interpretation ?ρ, _: context[list_match ?t ?t2 ?t3] |- _ =>\n    poseNew (Mark (t, t2, t3) \"evaluate_list_match2\");\n    unshelve epose proof (evaluate_list_match2 ρ t t2 t3 _ _ _ _ _ _ _ _)\n  | _: context[list_match ?t ?t2 ?t3] |- _ =>\n    poseNew (Mark (t, t2, t3) \"evaluate_list_match2\");\n    unshelve epose proof (evaluate_list_match2 nil t t2 t3 _ _ _ _ _ _ _ _)\n  end.\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/EvalListMatch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2578099578615078}}
{"text": "From iris.proofmode Require Import tactics.\nFrom iris.algebra Require Import lib.excl_auth gmap agree.\nFrom iris.base_logic.lib Require Export invariants.\nFrom iris Require Import options.\nImport uPred.\n\n(** The CMRAs we need. *)\nClass boxG Σ :=\n  boxG_inG :> inG Σ (prodR\n    (excl_authR boolO)\n    (optionR (agreeR (laterO (iPropO Σ))))).\n\nDefinition boxΣ : gFunctors := #[ GFunctor (excl_authR boolO *\n                                            optionRF (agreeRF (▶ ∙)) ) ].\n\nInstance subG_boxΣ Σ : 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 : excl_authR boolO) : iProp Σ :=\n    own γ (a, None).\n\n  Definition box_own_prop (γ : slice_name) (P : iProp Σ) : iProp Σ :=\n    own γ (ε, Some (to_agree (Next P))).\n\n  Definition slice_inv (γ : slice_name) (P : iProp Σ) : iProp Σ :=\n    ∃ b, box_own_auth γ (●E b) ∗ if b then P else True.\n\n  Definition slice (γ : slice_name) (P : iProp Σ) : iProp Σ :=\n    box_own_prop γ P ∗ inv N (slice_inv γ P).\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 γ (◯E b) ∗ box_own_prop γ (Φ γ) ∗\n                         inv N (slice_inv γ (Φ γ)).\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 γ (●E b1) ∗ box_own_auth γ (◯E b2) ⊢ ⌜b1 = b2⌝.\nProof.\n  rewrite /box_own_prop -own_op own_valid prod_validI /= and_elim_l.\n  by iDestruct 1 as %?%excl_auth_agree_L.\nQed.\n\nLemma box_own_auth_update γ b1 b2 b3 :\n  box_own_auth γ (●E b1) ∗ box_own_auth γ (◯E b2)\n  ==∗ box_own_auth γ (●E b3) ∗ box_own_auth γ (◯E b3).\nProof.\n  rewrite /box_own_auth -!own_op. apply own_update, prod_update; last done.\n  apply excl_auth_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  by rewrite option_validI /= agree_validI agree_equivI later_equivI /=.\nQed.\n\nLemma box_alloc : ⊢ box N ∅ True.\nProof.\n  iIntros. iExists (λ _, True)%I. 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_cofinite (●E false ⋅ ◯E false,\n    Some (to_agree (Next Q))) (dom _ f))\n    as (γ) \"[Hdom Hγ]\"; first by (split; [apply auth_both_valid_discrete|]).\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')) ∗ 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γ _]\".\n  iDestruct (big_sepM_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  iModIntro. iSplitL \"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γ _]\".\n  iDestruct (big_sepM_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  iModIntro. iSplitL \"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]\".\n  iDestruct (big_sepM_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  iModIntro. iSplitL \"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  iEval (rewrite internal_eq_iff later_iff big_sepM_later) in \"HeqP\".\n  iDestruct (\"HeqP\" with \"HP\") as \"HP\".\n  iCombine \"Hf\" \"HP\" as \"Hf\".\n  rewrite -big_sepM_sep big_opM_fmap; iApply (big_sepM_fupd _ _ f).\n  iApply (@big_sepM_impl with \"Hf\").\n  iIntros \"!>\" (γ b' ?) \"[(Hγ' & #$ & #$) HΦ]\".\n  iInv N as (b) \"[>Hγ _]\".\n  iMod (box_own_auth_update γ with \"[Hγ Hγ']\") as \"[Hγ $]\"; first by iFrame.\n  iModIntro. iSplitL; last done. iNext; iExists true. 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 γ (◯E false) ∗  box_own_prop γ (Φ γ) ∗\n      inv N (slice_inv γ (Φ γ)))%I with \"[> Hf]\" as \"[HΦ ?]\".\n  { rewrite -big_sepM_sep -big_sepM_fupd. 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Φ]\".\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    iModIntro. iSplitL \"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_sepM_later. 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    iIntros \"!>\". 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 γ', (Q' ∗ P')%I. iIntros \"{$∗ $# $%} !>\".  do 2 iNext. iRewrite \"Heq\".\n    iIntros \"!>\". 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 _ _ (box _ _) with \"[Heq] 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 _ _ (box _ _) with \"[Heq] 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 _ _ (box _ _) with \"[Heq1 Heq2] 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 _ _ (box _ _) with \"[Heq1 Heq2] Hbox\").\n    iNext. iRewrite \"Heq1\". iRewrite \"Heq2\". by rewrite assoc.\nQed.\nEnd box.\n\nTypeclasses Opaque slice box.\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/boxes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.25780685086063115}}
{"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_s_u_prg multi_is_zero_u_prg abs_prg.\nRequire Import multi_zero_s_prg copy_s_s_prg.\n\nLocal Open Scope mips_cmd_scope.\n\n(** z <- x + y with z, x signed and y unsigned *)\nDefinition multi_add_s_s_u0 rk rz rx ry a0 a1 a2 a3 a4 ret X Z : while.cmd :=\n   lw Z four16 rz ;\n   lw X four16 rx ;\n   pick_sign rx a0 a1 ;\n   If_bgez a1 Then (* 0 <= x ? *)\n     If_beq a1, r0 Then (* x = 0 ? *)\n       copy_s_u rk rz ry a0 a1 a2 a3 ;\n       addiu a3 r0 zero16\n     Else (* 0 < x *) (* NB: a1 = 1 *)\n       multi_add_u_u rk a1 ry X Z a2 a3 a4 ;\n       mflo a3;\n       sw rk zero16 rz (* fix size *)\n   Else (* x < 0 *)\n   (multi_lt rk ry X a0 a1 ret a2 a3 a4 ; \n    If_beq ret, r0 Then (* ry >= X ? *)\n      If_beq a2, r0 Then (* Y = X *)\n        multi_zero_s rz ; (* fix size *)\n        addiu a3 r0 zero16 (* no overflow *)\n      Else (* Y > X *)\n        multi_sub_u_u rk ry X Z a0 a1 a2 a3 a4 ret;\n        sw rk zero16 rz (* fix size *)\n    Else (* ry < X *)\n     (multi_sub_u_u rk X ry Z a0 a1 ret a3 a2 a4;\n      subu a0 r0 rk ;\n      sw a0 zero16 rz\n     )).\n\nDefinition multi_add_s_s_u rk rz rx ry a0 a1 a2 a3 a4 ret X Z :=\n  multi_is_zero_u rk ry a0 a1 a2 ;\n  If_bne a2 , r0 Then (* y = 0 ? *)\n    copy_s_s rk rz rx a0 a1 a2 a3 a4 ;\n    addiu a3 r0 zero16 (* no overflow *)\n  Else (* y <> 0 *) \n    multi_add_s_s_u0 rk rz rx ry a0 a1 a2 a3 a4 ret X Z.\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_s_u_prg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.2578068443095664}}
{"text": "\nRequire Import Infrastructure.\n\n\n(* ********************************************************************** *)\n(** * Properties of disjointness *)\n\nLemma disjoint_and : forall Δ A B C,\n    lc_sty A ->\n    disjoint Δ A (sty_and B C) <->\n    disjoint Δ A B /\\ disjoint Δ A C.\nProof with eauto.\n  introv LCA.\n  induction LCA.\n\n  - splits.\n\n    introv Dis.\n    inverts Dis as WF1 WF2 TL.\n    inverts TL.\n    inverts WF2.\n    inverts TL.\n    splits...\n    splits...\n\n    introv Dis.\n    destruct Dis...\n\n  - splits.\n\n    introv Dis.\n    lets (? & Wft): disjoint_regular Dis.\n    inverts Wft...\n\n    introv Dis.\n    destruct Dis...\n\n  - splits.\n\n    introv Dis.\n    inverts Dis as WF1 WF2 TL.\n    inverts TL.\n    inverts WF2.\n    inverts TL.\n    splits...\n    splits...\n\n    introv Dis.\n    inverts Dis...\n\n  - splits.\n\n    introv Dis.\n    inverts Dis as WF1 WF2 TL.\n    inverts TL.\n    inverts WF2.\n    inverts TL.\n    splits...\n    splits...\n\n    splits...\n    forwards (c1 & c2 & Sub1 & Sub2) : sub_andr WF2...\n    forwards (c1 & c2 & Sub1 & Sub2) : sub_andr WF2...\n\n    introv Dis.\n    destruct Dis...\n\n  - splits.\n\n    introv Dis.\n    inverts Dis as WF1 WF2 TL.\n    inverts TL.\n    inverts WF1.\n    inverts WF2.\n    splits...\n    inverts TL.\n    inverts WF1.\n    inverts WF2.\n    splits...\n\n    splits...\n\n    introv Dis.\n    inverts Dis...\n\n  - splits.\n\n    introv Dis.\n    inverts Dis as WF1 WF2 TL.\n    inverts TL.\n    inverts WF1.\n    inverts WF2.\n    splits...\n    inverts TL.\n    inverts WF1.\n    inverts WF2.\n    splits...\n\n    apply IHLCA1 in WF1...\n    apply IHLCA2 in WF2...\n    destructs WF1...\n    destructs WF2...\n\n    splits...\n\n    introv Dis.\n    inverts Dis...\n\n  - splits.\n\n    introv Dis.\n    inverts Dis as WF1 WF2 TL...\n    inverts TL.\n    inverts WF1.\n    splits...\n    inverts TL.\n    inverts WF2.\n    splits...\n\n    introv Dis.\n    inverts Dis...\n\n  - splits.\n\n    introv Dis.\n    inverts Dis as WF1 WF2 TL...\n    inverts TL.\n    inverts WF1.\n    inverts WF2.\n    splits...\n    inverts TL.\n    inverts WF1.\n    inverts WF2.\n    splits...\n\n\n    introv Dis.\n    inverts Dis...\n\nQed.\n\n\nLemma disjoint_narrow : forall F X U T E A B c,\n    disjoint (F ++ X ~ U ++ E) A B ->\n    sub E T U c ->\n    uniq (F ++ X ~ U ++ E) ->\n    disjoint (F ++ X ~ T ++ E) A B.\nProof with eauto using swft_narrow, sub_narrow.\n  introv Dis.\n  remember (F ++ X ~ U ++ E) as G.\n  generalize dependent F.\n  induction Dis; introv EQ Uniq Sub; subst...\n\n  - Case \"Var1\".\n    analyze_binds_uniq H...\n    assert (sub (F ++ X ~ T ++ E) T B (co_trans c0 c)).\n      eapply S_trans...\n      rewrite_env (nil ++ (F ++ [(X, T)]) ++ E).\n      apply sub_weakening...\n      solve_uniq.\n    eapply D_tvarL...\n\n  - Case \"Var2\".\n    analyze_binds_uniq H...\n    assert (sub (F ++ X ~ T ++ E) T B (co_trans c0 c)).\n      eapply S_trans...\n      rewrite_env (nil ++ (F ++ [(X, T)]) ++ E).\n      apply sub_weakening...\n      solve_uniq.\n    eapply D_tvarR...\n\n  - Case \"forall\".\n    pick fresh Y and apply D_forall...\n    rewrite_env (([(Y, sty_and A1 A2)] ++ F) ++ [(X, T)] ++ E)...\nQed.\n\n\n\nLemma disjoint_symmetric: forall Δ A B,\n    disjoint Δ A B ->\n    uniq Δ ->\n    disjoint Δ B A.\nProof with eauto.\n  introv Dis.\n  induction Dis; introv Uniq...\n  pick fresh X and apply D_forall...\n\n  rewrite_env (nil ++ [(X, sty_and A2 A1)] ++ DD).\n  eapply disjoint_narrow...\nQed.\n\n\nInductive BotDisjoint : stctx -> sty -> Prop :=\n| bl_bot : forall Δ A,\n    TopLike A ->\n    BotDisjoint Δ A\n| bl_and : forall Δ A B,\n    BotDisjoint Δ A ->\n    BotDisjoint Δ B ->\n    BotDisjoint Δ (sty_and A B)\n| bl_tvar : forall Δ A X c,\n    binds X A Δ ->\n    sub Δ A sty_bot c ->\n    BotDisjoint Δ (sty_var_f X).\n\nHint Constructors BotDisjoint.\n\n\nLemma bot_disjoint : forall Δ A B,\n    BotDisjoint Δ A ->\n    swft Δ A ->\n    swft Δ B ->\n    disjoint Δ A B.\nProof with eauto.\n  introv Bob.\n  gen B.\n\n  induction Bob; introv SWFT1 SWFT2; simpls...\n\n  inverts SWFT1...\nQed.\n\n\nLemma disjoint_bot : forall Δ A,\n    lc_sty A ->\n    uniq Δ ->\n    disjoint Δ A sty_bot ->\n    BotDisjoint Δ A.\n\nProof with eauto.\n  introv LC.\n  gen Δ.\n  induction LC; introv Uniq Dis; simpls...\n\n  - inverts Dis as ? HH1 HH2; inverts HH2.\n  - inverts Dis as ? HH1 HH2; inverts HH2.\n  - inverts Dis as ? HH1 HH2; try solve [inverts HH2]; simpls...\n  - inverts Dis as ? HH1 HH2; try solve [inverts HH2]; simpls...\n  - inverts Dis as ? HH1 HH2; try solve [inverts HH2]; simpls...\n  - inverts Dis as ? HH1 HH2; try solve [inverts HH2]; simpls...\n  - inverts Dis as ? HH1 HH2; try solve [inverts HH2]; simpls...\nQed.\n\n\nLemma TopLike_sub : forall Δ A B c,\n    sub Δ A B c ->\n    TopLike A ->\n    TopLike B.\nProof with eauto.\n  introv Sub.\n  induction Sub; introv TT; try solve [inverts TT; auto]; simpls...\n\n  inverts TT.\n\n  pick fresh X and apply tl_all...\n\n  inverts TT as TT1 TT2.\n  inverts TT1...\n  inverts TT2...\n\n  inverts TT as TT1 TT2.\n  inverts TT1...\n  inverts TT2...\n\n  inverts TT as TT1 TT2.\n  inverts TT1.\n  inverts TT2.\n  pick fresh X and apply tl_all...\n  unfold open_sty_wrt_sty.\n  simpls...\n\n  Unshelve.\n  exact (dom DD).\nQed.\n\n\n\n\nLemma  sub_TopLike_aux : forall Δ B,\n    TopLike B ->\n    uniq Δ ->\n    swft Δ B ->\n    exists c, sub Δ sty_top B c.\nProof with eauto.\n  introv Bob.\n  gen Δ.\n\n  induction Bob; introv Uniq WFT; simpls...\n\n  - Case \"and\".\n    inverts WFT.\n    forwards (c1 & ?) : IHBob1...\n    forwards (c2 & ?) : IHBob2...\n\n  - Case \"arr\".\n    inverts WFT.\n    forwards (c & ?) : IHBob...\n\n  - Case \"all\".\n    inverts WFT.\n    pick fresh X.\n    forwards (c & ?): H0 X ([(X, A)] ++ Δ)...\n    exists (co_trans (co_forall c) co_topAll).\n    eapply S_trans...\n    pick fresh Y and apply S_forall...\n    eapply sub_renaming...\n\n  - Case \"rcd\".\n    inverts WFT...\n    forwards (c & ?) : IHBob...\nQed.\n\n\n\nLemma sub_TopLike : forall Δ A B,\n    TopLike B ->\n    uniq Δ ->\n    swft Δ A ->\n    swft Δ B ->\n    exists c, sub Δ A B c.\nProof with eauto.\n  introv TT ? ? ?.\n\n  forwards (c & ?) : sub_TopLike_aux TT...\nQed.\n\n\nLemma disjoint_sub : forall Δ Δ' A B C c,\n    sub Δ' B C c ->\n    same_stctx Δ' Δ ->\n    swfte Δ ->\n    disjoint Δ A B ->\n    disjoint Δ A C.\nProof with eauto using swft_type.\n  introv Sub.\n  gen A Δ.\n\n  induction Sub; introv Same Wfte Dis...\n\n  - Case \"top\".\n    lets (? & ?) : disjoint_regular Dis...\n\n  -Case \"bot\".\n   forwards (WFA & ?) : disjoint_regular Dis...\n   forwards : disjoint_bot Dis...\n   eapply bot_disjoint...\n\n  - Case \"topArr\".\n    forwards (WFA & ?) : disjoint_regular Dis...\n\n  - Case \"topRcd\".\n    forwards (WFA & ?) : disjoint_regular Dis...\n\n  - Case \"topAll\".\n    forwards (WFA & ?) : disjoint_regular Dis...\n\n  - Case \"arr\".\n    forwards (WFA & WFB) : disjoint_regular Dis...\n    apply sub_change with (Δ' := Δ) in Sub1...\n    apply sub_change with (Δ' := Δ) in Sub2...\n    inverts WFB.\n    forwards (? & ?) : sub_regular Sub1...\n    forwards (? & ?) : sub_regular Sub2...\n    induction WFA...\n\n    + SCase \"A is bot\".\n      inverts Dis as WF1 WF2 WF3; auto.\n      eapply D_topR...\n      inverts WF3...\n      constructor.\n      eapply TopLike_sub...\n\n    + SCase \"A is var\".\n      inverts Dis as WF1 WF2 WF3...\n      inverts WF3.\n      eapply D_topR...\n      constructor.\n      eapply TopLike_sub...\n\n    + SCase \"A is arrow\".\n      inverts Dis as WF1 WF2 WF3; auto.\n      inverts WF3...\n\n    + SCase \"A is and\".\n      inverts Dis as WF1 WF2 WF3; auto.\n\n  - Case \"andl\".\n    forwards (? & ?) : disjoint_regular Dis...\n    apply disjoint_and in Dis...\n    destruct Dis...\n\n  - Case \"andr\".\n    forwards (? & ?) : disjoint_regular Dis...\n    apply disjoint_and in Dis...\n    destruct Dis...\n\n  - Case \"forall\".\n    forwards (WFA & ?) : disjoint_regular Dis...\n    assert (Sub2 : sub DD (sty_all A1 B1) (sty_all A2 B2) (co_forall c))...\n    apply sub_change with (Δ' := Δ) in Sub...\n    apply sub_change with (Δ' := Δ) in Sub2...\n    forwards (? & ?) : sub_regular Sub...\n    lets (? & ?) : sub_regular Sub2.\n    induction WFA...\n\n    + SCase \"A is bot\".\n      inverts Dis as WF1 WF2 WF3; auto.\n      eapply D_topR...\n      eapply TopLike_sub...\n\n    + SCase \"A is var\".\n      inverts Dis as WF1 WF2 WF3...\n      eapply D_topR...\n      eapply TopLike_sub...\n\n    + SCase \"A is all\".\n      inverts Dis as WF1 WF2 WF3; auto.\n      eapply D_topR...\n      eapply TopLike_sub...\n\n      pick fresh X and apply D_forall...\n      eapply H0...\n      rewrite_env (nil ++ [(X, sty_and A A2)] ++ DD0).\n      eapply disjoint_narrow...\n\n    + SCase \"A is and\".\n      inverts Dis as WF1 WF2 WF3; auto.\n\n  - Case \"rcd\".\n    forwards (WFA & ?) : disjoint_regular Dis...\n    apply sub_change with (Δ' := Δ) in Sub...\n    forwards (? & ?) : sub_regular Sub...\n    induction WFA...\n\n    + SCase \"A is bot\".\n      inverts Dis as WF1 WF2 WF3; auto.\n      eapply D_topR...\n      eapply TopLike_sub...\n\n    + SCase \"A is var\".\n      inverts Dis as WF1 WF2 WF3...\n      eapply D_topR...\n      eapply TopLike_sub...\n\n    + SCase \"A is and\".\n      inverts Dis as WF1 WF2 WF3; auto.\n\n    + SCase \"A is record\".\n      inverts Dis as WF1 WF2 WF3; auto.\n      eapply D_topR...\n      eapply TopLike_sub...\n\n  - Case \"distArr\".\n    forwards (WFA & ?) : disjoint_regular Dis...\n    apply swft_change with (Δ' := Δ) in H...\n    apply swft_change with (Δ' := Δ) in H0...\n    apply swft_change with (Δ' := Δ) in H1...\n    induction WFA...\n\n    + SCase \"A is bot\".\n      apply disjoint_and in Dis...\n      inverts Dis as Dis1 Dis2.\n      eapply disjoint_symmetric in Dis1...\n      eapply disjoint_symmetric in Dis2...\n      eapply disjoint_bot in Dis1...\n      inverts Dis1 as Dis1.\n      eapply disjoint_bot in Dis2...\n      inverts Dis2 as Dis2.\n      inverts Dis1.\n      inverts Dis2.\n      eapply D_topR...\n\n    + SCase \"A is var\".\n\n\n      apply disjoint_and in Dis...\n      inverts Dis as WF1 WF2.\n\n      inverts WF1 as WF11 WF12 TT; auto.\n      inverts TT as TT1.\n      inverts WF2 as WF21 WF22 TT; auto.\n      inverts TT as TT2.\n      eapply D_topR...\n      forwards : binds_unique WF21 H3; auto.\n      substs.\n      forwards (c' & ?) : sub_TopLike DD0 A3 TT1...\n      assert (sub DD0 (sty_arrow A1 A3) (sty_arrow A1 (sty_and A2 A3)) (co_arr co_id (co_pair c' co_id)))...\n\n      forwards : binds_unique WF11 H3; auto.\n      substs.\n      inverts WF2 as WF21 WF22 TT; auto.\n      inverts TT as TT.\n      forwards (c' & ?) : sub_TopLike DD0 A2 TT...\n      assert (sub DD0 (sty_arrow A1 A2) (sty_arrow A1 (sty_and A2 A3)) (co_arr co_id (co_pair co_id c')))...\n\n      forwards : binds_unique WF21 H3; auto.\n      substs...\n\n\n    + SCase \"A is arrow\".\n\n      apply disjoint_and in Dis...\n      inverts Dis as WF1 WF2.\n\n      inverts WF1 as WF11 WF12 TT; auto.\n      inverts TT.\n      inverts WF2 as WF21 WF22 TT; auto.\n      inverts TT.\n      eapply D_topR...\n\n      inverts WF2 as WF21 WF22 TT1 TT2; auto.\n      inverts TT1...\n\n    + SCase \"A is and\".\n\n      apply disjoint_and in Dis...\n      inverts Dis as WF1 WF2.\n\n\n      inverts WF1 as WF11 WF12 TT; auto.\n      inverts TT.\n      inverts WF2 as WF21 WF22 TT; auto.\n      inverts TT.\n      eapply D_topR...\n      eapply D_andL...\n\n      inverts WF2 as WF21 WF22 TT; auto.\n\n  - Case \"distRcd\".\n    forwards (WFA & ?) : disjoint_regular Dis...\n    apply swft_change with (Δ' := Δ) in H...\n    apply swft_change with (Δ' := Δ) in H0...\n    induction WFA...\n\n\n    + SCase \"A is bot\".\n\n      apply disjoint_and in Dis...\n      inverts Dis as WF1 WF2.\n\n      eapply disjoint_symmetric in WF1...\n      eapply disjoint_symmetric in WF2...\n      forwards WW1: disjoint_bot WF1...\n      forwards WW2: disjoint_bot WF2...\n      inverts WW1 as WW1.\n      inverts WW2 as WW2.\n      inverts WW1.\n      inverts WW2.\n      eapply D_topR...\n\n    + SCase \"A is var\".\n\n      apply disjoint_and in Dis...\n      inverts Dis as WF1 WF2.\n\n      inverts WF1 as WF11 WF12 TT; auto.\n      inverts TT as TT1.\n      inverts WF2 as WF21 WF22 TT; auto.\n      inverts TT as TT2.\n      eapply D_topR...\n      forwards : binds_unique WF21 H2; auto.\n      substs.\n      forwards (c' & ?) : sub_TopLike DD0 B TT1...\n      assert (sub DD0 (sty_rcd l B) (sty_rcd l (sty_and A B)) (co_pair c' co_id))...\n\n      forwards : binds_unique WF11 H2; auto.\n      substs.\n      inverts WF2 as WF21 WF22 TT; auto.\n      inverts TT as TT.\n      forwards (c' & ?) : sub_TopLike DD0 A TT...\n      assert (sub DD0 (sty_rcd l A) (sty_rcd l (sty_and A B)) (co_pair co_id c'))...\n\n      forwards : binds_unique WF21 H2; auto.\n      substs...\n\n    + SCase \"A is and\".\n\n      apply disjoint_and in Dis...\n      inverts Dis as WF1 WF2.\n\n      inverts WF1 as WF11 WF12 TT; auto.\n      inverts TT.\n      inverts WF2 as WF21 WF22 TT; auto.\n      inverts TT.\n      eapply D_topR...\n      eapply D_andL...\n\n\n      inverts WF2 as WF21 WF22 TT; auto.\n\n    + SCase \"A is record\".\n\n      apply disjoint_and in Dis...\n      inverts Dis as WF1 WF2.\n\n      inverts WF1 as WF11 WF12 TT; auto.\n      inverts TT.\n      inverts WF2 as WF21 WF22 TT; auto.\n      inverts TT.\n      eapply D_topR...\n\n      inverts WF2 as WF21 WF22 TT; auto.\n      inverts TT.\n      eapply D_rcdEq...\n\n\n  - Case \"distPoly\".\n    forwards (WFA & WFB) : disjoint_regular Dis...\n    inverts WFB as WFB1 WFB2.\n    assert (swft Δ (sty_all A (sty_and B1 B2))).\n      inverts WFB2.\n      inverts WFB1.\n      pick fresh X and apply swft_all...\n      unfold open_sty_wrt_sty.\n      simpl...\n\n    induction WFA...\n\n\n    + SCase \"A is bot\".\n\n\n      apply disjoint_and in Dis...\n      inverts Dis as WF1 WF2.\n\n      eapply disjoint_symmetric in WF1...\n      eapply disjoint_symmetric in WF2...\n      forwards WW1: disjoint_bot WF1...\n      forwards WW2: disjoint_bot WF2...\n      inverts WW1 as WW1.\n      inverts WW2 as WW2.\n      inverts WW1 as WW1.\n      inverts WW2 as WW2.\n      eapply D_topR...\n      pick fresh X and apply tl_all.\n      forwards : WW1...\n      forwards : WW2...\n      unfold open_sty_wrt_sty in *.\n      simpls...\n\n    + SCase \"A is var\".\n\n      apply disjoint_and in Dis...\n      inverts Dis as WF1 WF2.\n\n      inverts WF1 as WF11 WF12 TT1; auto.\n      inverts WF2 as WF21 WF22 TT2; auto.\n      inverts TT1 as TT1.\n      inverts TT2 as TT2.\n      eapply D_topR...\n      pick fresh Y and apply tl_all...\n      forwards : TT1...\n      forwards : TT2...\n      unfold open_sty_wrt_sty in *.\n      simpls...\n\n      forwards : binds_unique WF21 H3; auto.\n      substs.\n      inverts TT1 as TT1.\n      inverts WFB1.\n      inverts WFB2.\n      pick fresh Y.\n      forwards TT : TT1 Y...\n      clear TT1.\n      forwards (c' & Imp): sub_TopLike ([(Y, A)] ++ DD0) (open_sty_wrt_sty B2 (sty_var_f Y)) TT...\n      assert (sub DD0 (sty_all A B2) (sty_all A (sty_and B1 B2)) (co_forall (co_pair c' co_id) ))...\n      pick fresh Z and apply S_forall...\n      forwards Imp' : sub_renaming Y Z Imp...\n      unfold open_sty_wrt_sty.\n      simpls...\n\n      forwards : binds_unique WF11 H3; auto.\n      substs.\n      inverts WF2 as WF21 WF22 TT; auto.\n      inverts TT as TT.\n      inverts WFB1.\n      inverts WFB2.\n      pick fresh Y.\n      forwards TT' : TT Y...\n      clear TT.\n      forwards (c' & Imp): sub_TopLike ([(Y, A)] ++ DD0) (open_sty_wrt_sty B1 (sty_var_f Y)) TT'...\n      assert (sub DD0 (sty_all A B1) (sty_all A (sty_and B1 B2)) (co_forall (co_pair co_id c' ) ))...\n      pick fresh Z and apply S_forall...\n      forwards Imp' : sub_renaming Y Z Imp...\n      unfold open_sty_wrt_sty.\n      simpls...\n\n\n      forwards : binds_unique WF21 H3; auto.\n      substs.\n\n      apply D_tvarL with (A := A0) (c := co_trans co_distPoly (co_pair c c0))...\n      eapply S_trans...\n      eapply S_distPoly...\n\n\n    + SCase \"A is all\".\n\n\n      apply disjoint_and in Dis...\n      inverts Dis as WF1 WF2.\n\n      inverts WF1 as WF11 WF12 TT1; auto.\n      inverts WF2 as WF21 WF22 TT2; auto.\n      inverts TT1 as TT1.\n      inverts TT2 as TT2.\n      eapply D_topR...\n      pick fresh Y and apply tl_all...\n      forwards : TT1...\n      forwards : TT2...\n      unfold open_sty_wrt_sty in *.\n      simpls...\n\n      inverts TT1.\n      pick fresh X and apply D_forall...\n      unfold open_sty_wrt_sty.\n      simpls...\n      eapply disjoint_and...\n      splits...\n      eapply D_topR...\n      inverts WFB1...\n      eapply swft_change...\n      econstructor...\n      eapply swft_change...\n      econstructor...\n\n      inverts WF2 as WF21 WF22 TT; auto.\n      inverts TT as TT.\n      pick fresh X and apply D_forall...\n      unfold open_sty_wrt_sty.\n      simpls.\n      eapply disjoint_and...\n      splits...\n      eapply D_topR...\n      eapply swft_change...\n      econstructor...\n      eapply swft_change...\n      econstructor...\n\n      pick fresh X and apply D_forall...\n      unfold open_sty_wrt_sty.\n      simpls...\n\n    + SCase \"A is and\".\n      apply disjoint_and in Dis...\n      inverts Dis as WF1 WF2.\n\n      inverts WF1 as WF11 WF12 TT1; auto.\n      inverts WF2 as WF21 WF22 TT2; auto.\n\n      inverts WF2 as WF21 WF22 TT; auto.\n\n      (* WTF? *)\n      Unshelve.\n      exact (dom DD).\n      exact (dom DD).\n\nQed.\n\n\n\nLemma disjoint_weakening : forall G F E A B,\n  disjoint (G ++ E) A B ->\n  uniq (G ++ F ++ E) ->\n  disjoint (G ++ F ++ E) A B.\nProof with eauto using sub_weakening, swft_weaken.\n  introv Dis.\n  remember (G ++ E) as H.\n  generalize dependent G.\n  induction Dis; introv EQ Ok; subst...\n\n  pick fresh X and apply D_forall...\n  rewrite_env (([(X, sty_and A1 A2)] ++ G) ++ F ++ E).\n  eapply H0...\n  solve_uniq.\nQed.\n\n(* Lemma disjoint_subst : forall Z E F C A B P, *)\n(*   disjoint (F ++ Z ~ C ++ E) A B -> *)\n(*   swfte (F ++ Z ~ C ++ E) -> *)\n(*   swft E P -> *)\n(*   disjoint E P C -> *)\n(*   swfte (map (subst_sty_in_sty P Z) F ++ E) -> *)\n(*   disjoint (map (subst_sty_in_sty P Z) F ++ E) (subst_sty_in_sty P Z A) (subst_sty_in_sty P Z B). *)\n(* Proof with eauto using subst_sty_in_sty_lc_sty, swft_subst_tb, swft_type, same_eq. *)\n(*   introv WT EP. *)\n(*   remember (F ++ Z ~ C ++ E) as G. *)\n(*   generalize dependent F. *)\n(*   induction WT; introv Eq Wft Dis Uniq; substs; simpl... *)\n\n(*   constructor; *)\n(*   replace (sty_all (subst_sty_in_sty P Z A1) (subst_sty_in_sty P Z B1)) with (subst_sty_in_sty P Z (sty_all A1 B1))... *)\n(*   constructor; *)\n(*   replace (sty_all (subst_sty_in_sty P Z A1) (subst_sty_in_sty P Z B1)) with (subst_sty_in_sty P Z (sty_all A1 B1))... *)\n(*   constructor; *)\n(*   replace (sty_all (subst_sty_in_sty P Z A1) (subst_sty_in_sty P Z B1)) with (subst_sty_in_sty P Z (sty_all A1 B1))... *)\n(*   constructor; *)\n(*   replace (sty_all (subst_sty_in_sty P Z A1) (subst_sty_in_sty P Z B1)) with (subst_sty_in_sty P Z (sty_all A1 B1))... *)\n(*   constructor; *)\n(*   replace (sty_all (subst_sty_in_sty P Z A1) (subst_sty_in_sty P Z B1)) with (subst_sty_in_sty P Z (sty_all A1 B1))... *)\n(*   constructor; *)\n(*   replace (sty_all (subst_sty_in_sty P Z A1) (subst_sty_in_sty P Z B1)) with (subst_sty_in_sty P Z (sty_all A1 B1))... *)\n\n\n(*   - Case \"Var1\". *)\n(*     case_if. *)\n(*     substs. *)\n(*     analyze_binds_uniq H... *)\n(*     substs... *)\n(*     apply disjoint_sub with (Δ' := (map (subst_sty_in_sty P Z) F ++ E)) (B := (subst_sty_in_sty P Z C)) (c := c)... *)\n(*     eapply sub_subst... *)\n(*     replace (subst_sty_in_sty P Z C) with C. *)\n(*     rewrite_env (nil ++ map (subst_sty_in_sty P Z) F ++ E). *)\n(*     eapply disjoint_weakening... *)\n(*     rewrite subst_sty_in_sty_fresh_eq... *)\n(*     clear Uniq. *)\n(*     eapply swfte_tvar... *)\n\n(*     analyze_binds_uniq H... *)\n(*     eapply D_tvarL... *)\n(*     eapply sub_subst... *)\n\n(*     eapply D_tvarL... *)\n(*     replace A with (subst_sty_in_sty P Z A). *)\n(*     eapply sub_subst... *)\n(*     rewrite subst_sty_in_sty_fresh_eq... *)\n(*     apply swft_tvar with (D := E)... *)\n(*     eapply swft_from_swfte... *)\n(*     eapply swfte_strength... *)\n(*     inverts BindsTacSideCond0... *)\n\n\n(*   - Case \"Var2\". *)\n(*     eapply disjoint_symmetric... *)\n(*     case_if. *)\n(*     substs. *)\n(*     analyze_binds_uniq H... *)\n(*     substs... *)\n(*     apply disjoint_sub with (Δ' := (map (subst_sty_in_sty P Z) F ++ E)) (B := (subst_sty_in_sty P Z C)) (c := c)... *)\n(*     eapply sub_subst... *)\n(*     replace (subst_sty_in_sty P Z C) with C. *)\n(*     rewrite_env (nil ++ map (subst_sty_in_sty P Z) F ++ E). *)\n(*     eapply disjoint_weakening... *)\n(*     rewrite subst_sty_in_sty_fresh_eq... *)\n(*     clear Uniq. *)\n(*     eapply swfte_tvar... *)\n\n(*     analyze_binds_uniq H... *)\n(*     eapply D_tvarL... *)\n(*     eapply sub_subst... *)\n\n(*     eapply D_tvarL... *)\n(*     replace A with (subst_sty_in_sty P Z A). *)\n(*     eapply sub_subst... *)\n(*     rewrite subst_sty_in_sty_fresh_eq... *)\n(*     apply swft_tvar with (D := E)... *)\n(*     eapply swft_from_swfte... *)\n(*     eapply swfte_strength... *)\n(*     inverts BindsTacSideCond0... *)\n\n\n(*   - Case \"forall\". *)\n\n(*     pick fresh Y and apply D_forall... *)\n(*     rewrite subst_sty_in_sty_open_sty_wrt_sty_var... *)\n(*     rewrite subst_sty_in_sty_open_sty_wrt_sty_var... *)\n(*     rewrite_env (map (subst_sty_in_sty P Z) ([(Y, sty_and A1 A2)] ++ F) ++ E). *)\n(*     apply H0... *)\n\n(*     simpl; constructor... *)\n\n(* Qed. *)\n\nLemma rel_d_tvar_disjoint : forall Δ p X A,\n    rel_d Δ p ->\n    swfte Δ ->\n    binds X A Δ ->\n    disjoint nil (mtsubst_in_sty p (sty_var_f X) ) (mtsubst_in_sty p A).\nProof with eauto.\n  introv RelD.\n  gen X A.\n  induction RelD; introv Swft Bind; simpls...\n\n  case_if.\n  + SCase \"X0 = X\".\n    substs.\n    forwards (? & ?): rel_d_uniq RelD.\n    analyze_binds_uniq Bind...\n    inverts Swft...\n    rewrite mtsubst_fresh...\n    rewrite subst_sty_in_sty_fresh_eq...\n    eapply swft_tvar...\n  + SCase \"X0 <> X\".\n    forwards (? & ?): rel_d_uniq RelD.\n    analyze_binds_uniq Bind...\n    inverts Swft as Swft ?.\n    forwards Dis : IHRelD Swft...\n    applys_eq Dis 1.\n    rewrite subst_sty_in_sty_fresh_eq...\n    eapply swft_tvar...\nQed.\n\n\n\nLemma subst_toplike : forall C x B,\n    TopLike B ->\n    lc_sty C ->\n    TopLike (subst_sty_in_sty C x B).\nProof with eauto.\n  introv TT.\n  gen C x.\n\n  induction TT; introv LC; simpls...\n\n  pick fresh X and apply tl_all...\n  rewrite subst_sty_in_sty_open_sty_wrt_sty_var...\nQed.\n\n\nLemma mtsubst_toplike : forall Δ p A,\n    rel_d Δ p ->\n    TopLike A ->\n    TopLike (mtsubst_in_sty p A).\nProof with eauto using subst_toplike.\n  introv RelD.\n  gen A.\n\n  induction RelD; introv TT; simpls...\nQed.\n\n\nLemma mtsubst_disjoint_helper : forall A B Δ1 Δ2 p,\n    rel_d Δ2 p ->\n    swfte (Δ1 ++ Δ2) ->\n    disjoint (Δ1 ++ Δ2) A B ->\n    disjoint (map (mtsubst_in_sty p) Δ1) (mtsubst_in_sty p A) (mtsubst_in_sty p B).\nProof with eauto using mtsubst_toplike.\n  introv Eq Wfte Dis.\n  gen p.\n  inductions Dis; introv Eq; simpls; autorewrite with lr_rewrite...\n\n\n  eapply D_axRcdAll...\n  rewrite <- mtsubst_forall...\n\n  eapply D_axAllRcd...\n  rewrite <- mtsubst_forall...\n\n  eapply D_axAllNat...\n  rewrite <- mtsubst_forall...\n\n  eapply D_axNatAll...\n  rewrite <- mtsubst_forall...\n\n  eapply D_axArrAll...\n  rewrite <- mtsubst_forall...\n\n  eapply D_axAllArr...\n  rewrite <- mtsubst_forall...\n\n\n  + Case \"var1\".\n    analyze_binds_uniq H...\n    rewrite mtsubst_tvar_notin...\n    apply D_tvarL with (A := (mtsubst_in_sty p A)) (c := c)...\n    eapply sub_subst_ctx...\n    eapply rel_d_notin...\n    forwards : rel_d_tvar_disjoint Eq BindsTac...\n    eapply swfte_strength...\n    apply disjoint_sub with (Δ' := (map (mtsubst_in_sty p) Δ1)) (B := (mtsubst_in_sty p A)) (c := c)...\n    eapply sub_subst_ctx...\n    eapply swfte_subst_ctx...\n    rewrite_env (nil ++ map (mtsubst_in_sty p) Δ1 ++ nil).\n    eapply disjoint_weakening...\n    solve_uniq.\n\n  + Case \"var2\".\n    analyze_binds_uniq H...\n    rewrite mtsubst_tvar_notin...\n    apply D_tvarR with (A := (mtsubst_in_sty p A)) (c := c)...\n    eapply sub_subst_ctx...\n    eapply rel_d_notin...\n    forwards : rel_d_tvar_disjoint Eq BindsTac...\n    eapply swfte_strength...\n    eapply disjoint_symmetric...\n    apply disjoint_sub with (Δ' := (map (mtsubst_in_sty p) Δ1)) (B := (mtsubst_in_sty p A)) (c := c)...\n    eapply sub_subst_ctx...\n    eapply swfte_subst_ctx...\n    rewrite_env (nil ++ map (mtsubst_in_sty p) Δ1 ++ nil).\n    eapply disjoint_weakening...\n    solve_uniq.\n    solve_uniq.\n\n  + Case \"forall\".\n    pick fresh X and apply D_forall; simpl_env...\n    lets (? & ?) : rel_d_uniq Eq.\n    forwards Imp : H0 X Δ2 ([(X, sty_and A1 A2)] ++ Δ1) p...\n    simpl_env...\n    simpls...\n    erewrite mtsubst_open in Imp...\n    rewrite mtsubst_tvar_notin in Imp...\n    erewrite mtsubst_open in Imp...\n    rewrite mtsubst_tvar_notin in Imp...\n    autorewrite with lr_rewrite in Imp...\nQed.\n\nLemma mtsubst_disjoint : forall A B Δ p,\n    rel_d Δ p ->\n    swfte Δ ->\n    disjoint Δ A B ->\n    disjoint nil (mtsubst_in_sty p A) (mtsubst_in_sty p B).\nProof with eauto.\n  intros.\n  rewrite_env (map (mtsubst_in_sty p) nil).\n  eapply mtsubst_disjoint_helper...\nQed.\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/Disjoint.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2577741972855919}}
{"text": "(** This file contains the common part of the [CNF] modules\n   built on top of the module [LLAZY] of lazy literals. *)\nRequire Import Quote List Ergo.\nRequire Import BinPos LLazy SemLazy.\nRequire Import Containers.Sets.\nRequire Import Cnf Semantics DoubleNegUtils Setoid.\n\n(** * The module type [CNFLAZY_INTERFACE]\n   \n   This module defines the interface that a [CNF] module working\n   with [LLAZY] literals should match. First, we use [Include Type]\n   to include the module [L := LLAZY] of literals, and we define\n   a formula as simply being a literal [LLAZY.t].\n*)\nModule Type CNFLAZY_INTERFACE.\n(** Doesnt work for some reason... *)\n  Include Type CNF\n    with Module L := LLAZY\n    with Module Sem := SEMLAZY\n    with Definition formula := LLAZY.t.\n\n  Axiom make_1 : \n    forall f, make f [=] singleton {f}.\n\n  Definition interp : varmaps -> formula -> Prop\n    := LLAZY.interp.\n\n  (** We also require a conversion function [mk_form] that builds\n     a formula (a proxy hierarchy) from a concrete reified formula\n     of type [Ergo.form]. This conversion should return a semantically \n     equivalent formula, as stated by the axiom [cnf].\n     Addendum (May 2010) : we now add a prerequisite on a formula for\n     the CNF to be correct, it must be well-typed in the sense of\n     [Ergo.well_typed_formula].\n     *)\n  Module Conversion.\n    Parameter mk_form : fform -> formula.\n    \n    Axiom cnf :\n      forall v f, Ergo.well_typed_formula v f -> \n        ~~(finterp v f <-> interp v (mk_form f)).\n  End Conversion.\nEnd CNFLAZY_INTERFACE.\n\n(** * The module [CNFLAZYCOMMON]\n   \n   We also define a module which is the \"basis\" of all\n   modules that match [CNFLAZY_INTERFACE]. Namely, this module\n   contains the module of literals, builds the necessary finite\n   sets and facts about these sets.\n   It also provides the [pick] function used to choose a literal.\n   Thanks to this module, we aboid duplication between the different\n   variants of [CNFLAZY_INTERFACE] that we will implement.\n*)\nModule CNFLAZYCOMMON.\n\n  Module Import L := LLAZY.\n\n  Notation lset := (@set L.t L.t_OT (@SetAVLInstance.SetAVL_FSet L.t L.t_OT)).\n  Notation clause := (@set L.t L.t_OT \n    (@SetListInstance.SetList_FSet L.t L.t_OT)).\n\n  Definition clause_OT : OrderedType clause := SOT_as_OT.\n  Existing Instance clause_OT.\n  Notation cset := (@set clause clause_OT \n    (@SetListInstance.SetList_FSet clause clause_OT)).\n(*   Module LSet := FSetList.Make(L). *)\n\n(*   Module Clause := FSetList.Make(L). *)\n(*   Module CSet := FSetList.Make(Clause). *)\n  \n(*   Module LFacts := WFacts(Clause). *)\n(*   Module CFacts := WFacts(CSet). *)\n\n  Definition formula := L.t.\n\n  (** We provide a function that picks the first literal of a problem. *)\n  Definition pick (D : cset) := \n    match choose D with \n      | None => None\n      | Some c => \n        match choose c with\n          | Some l => Some (c, l)\n          | None => None\n        end\n    end.\n\n  Fact pick_1 :\n    forall (D : cset) (C : clause) (l : L.t), \n      pick D = Some (C, l) -> C \\In D /\\ l \\In C.\n  Proof.\n    intros D c l; unfold pick; case_eq (choose D).\n    intros e Hc; case_eq (choose e).\n    intros l' Hl' Heq; inversion Heq; subst; split.\n    exact (choose_1 Hc). exact (choose_1 Hl').\n    intros; discriminate. intros; discriminate.\n  Qed.\n    \n  Fact pick_2 : \n    forall (D : cset),\n      (forall C, C \\In D -> ~Empty C) ->\n      pick D = None -> Empty D.\n  Proof.\n    intros D HD; unfold pick; case_eq (choose D).\n    intros c Hc; case_eq (choose c).\n    intros; discriminate.\n    intro abs; contradiction \n      (HD c (choose_1 Hc) (choose_2 abs)).\n    intros empty _; exact (choose_2 empty).\n  Qed.\n\n  (** And the adhoc semantics for literals with equations *)\n  Module Sem := SEMLAZY.\nEnd CNFLAZYCOMMON.\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/CNFLazyCommon.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847395, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.25777419728559187}}
{"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 Max.\nRequire Export Zpower.\nRequire Export Zlogarithm.\nRequire Export QArith.\nRequire Export Qpower.\nOpen Scope Z_scope.\nOpen Scope Q_scope.\n\nRequire Extraction.\n\nCoercion inject_Z : Z >-> Q.\nLocal Coercion Z_of_nat : nat >-> Z.\n\nLtac QpowerSimpl :=\n(repeat rewrite inj_S;\n unfold Zsucc;\n repeat rewrite Qpower_plus; try discriminate;\n simpl).\n\n\nLtac get_hd := match goal with |- ?H -> _ => H end.\nLtac get_gl := match goal with |- ?H => H end.\n\nLtac lhs H := \n match H with \n  | ?a <= _ => a\n  | ?a < _ => a \n  | ?a == _ => a\n end.\n\nLtac rhs H := \n match H with \n  | _ <= ?a => a\n  | _ < ?a => a \n  | _ == ?a => a\n end.\n\nLtac step_left t :=  let H := get_gl in let a := lhs H in setoid_replace a with t by (QpowerSimpl;ring).\nLtac step_right t :=  let H := get_gl in let a := rhs H in setoid_replace a with t by (QpowerSimpl;ring).\nLtac step_left_hd t :=  let H := get_hd in let a := lhs H in setoid_replace a with t by (QpowerSimpl;ring).\nLtac step_right_hd t := let H := get_hd in let a := rhs H in setoid_replace a with t by (QpowerSimpl;ring).\nLtac step t := let a := lhs t in step_left a; let b := rhs t in step_right b.\nLtac step_hd t := let a := lhs t in step_left_hd a; let b := rhs t in step_right_hd b.\n\nLocal Notation \" ' x \" := (Zpos x) (at level 20, no associativity) : Z_scope.\n\n(**** A quick & dirty implementation of constructive reals. ****)\n(****      Based on Pr. Schwichtenberg lecture notes.        ****)\n(****      Main objective: sqrt(2) as root of X^2 -2  in [1;2]   ****) \n\n(* First, the Cauchy property. *)\n\nDefinition Is_Cauchy (f : nat -> Q) (mo : nat -> nat) :=\n  forall k m n,  (mo k <= m)%nat -> (mo k <= n)%nat ->\n  -(1#2)^k <= f m - f n <= (1#2)^k.\n\n(* A real is given by a cauchy sequence, a modulus sequence *)\n(* and a proof of the Cauchy property of these sequences. *)\n\nRecord R : Set := {\n  cauchy : nat -> Q; \n  modulus : nat -> nat; \n  is_cauchy : Is_Cauchy cauchy modulus }.\n\n(* Recursive Extraction R. *)\n\n(* A rational is injected into R via a constant cauchy sequence. *)\n\nDefinition inject_Q : Q -> R.\nProof.\nintros q.\napply (Build_R (fun _ => q) (fun _ => O)).\nred; intros.\nassert (H1: q-q == 0) by ring.\nrewrite H1; clear H1.\nassert (0 <= (1#2)^k).\n apply Qpower_pos. \n compute; intro; discriminate.\nsplit; auto.\nreplace 0 with (-0) by auto.\napply Qopp_le_compat; auto.\nDefined.\n\n(* Extraction inject_Q. *)\n\n(* The non-computational equality upon R. *)\n\nDefinition Req : R -> R -> Prop:= \n    fun x y : R => \n      forall k, let M := modulus x (S k) in \n            let N := modulus y (S k) in \n            -(1#2)^k <= cauchy x M - cauchy y N <= (1#2)^k.         \n\n(* The informative positivity upon R. *)\n\nDefinition Rpos_k : nat -> R -> Prop :=\n  fun k x => (1#2)^k <= cauchy x (modulus x (S k)).\n\nDefinition Rpos : R -> Set := fun x => { k:nat | Rpos_k k x }.\n\n(* The logical non-negativity upon R. *)\n\nDefinition Rnonneg : R -> Prop := \n fun x => forall k:nat, -(1#2)^k <= cauchy x (modulus x k).\n\n(* The Dirty Part: *)\n\n(**** Beware! Use with caution! Not for kids! ****)\nAxiom Falsum: False.\nLtac fedup := elim Falsum.\n(*****************************************************)\n\nDefinition test : R -> R -> R.\nfedup.\nQed.\n(* Extraction test. *)\n\n(* Addition on R. *)\n(* Only the informative parts are provided. \n    The logical statement is skipped. *)\n\n(*\nLemma two_power_S : forall k, !2^(S k) = (2 *(!2^k))%Z.\nintros. \nrewrite <- two_power_nat_S; auto with zarith.\nQed.\n*)\n\nLemma max_le : forall a b c, le (max a b) c -> le a c /\\ le b c.\nProof.\neauto with arith.\nQed.\n\nLemma Qeq_Qle : forall a b:Q, a==b -> a<=b.\nProof.\nintros. setoid_replace a with b by auto. apply Qle_refl.\nQed.\n\nDefinition Rplus : R -> R -> R.\nProof.\nintros x y.\napply (Build_R (fun n => cauchy x n + cauchy y n)\n                          (fun k => max (modulus x (S k)) (modulus y (S k)))).\nunfold Is_Cauchy; intros.\nset (N := modulus x (S k)) in *.\nset (M := modulus y (S k)) in *.\nelim (max_le N M m H); elim (max_le N M n H0); intros.\nassert (H5 := is_cauchy x (S k) m n H3 H1).\nassert (H6 := is_cauchy y (S k) m n H4 H2).\nclear N M H H0 H1 H2 H3 H4.\nset (Xn := cauchy x n) in *; set (Xm := cauchy x m) in *; \nset (Yn := cauchy y n) in *; set (Ym := cauchy y m) in *.\ndestruct H5; destruct H6.\nsetoid_replace (Xm+Ym-(Xn+Yn)) with ((Xm-Xn) +(Ym-Yn)) by ring.\nsplit.\nstep_left (-(1#2)^(S k)+-(1#2)^(S k)).\napply Qplus_le_compat; auto.\nstep_right ((1#2)^(S k)+(1#2)^(S k)).\napply Qplus_le_compat; auto.\nDefined.\n\n(* Extraction Rplus. *)\n\nDefinition Ropp : R -> R.\nintros x.\napply (Build_R (fun n => -(cauchy x n)) (fun k => modulus x k)).\nunfold Is_Cauchy; intros.\nunfold Qminus.\nrewrite (Qopp_opp (cauchy x n)).\nrewrite (Qplus_comm (-(cauchy x m)) (cauchy x n)).\napply (is_cauchy x k n m); auto.\nDefined.\n\nDefinition Rminus : R -> R -> R := fun x y => Rplus x (Ropp y).\n\nDefinition Rlt : R -> R -> Set := fun x y => Rpos (Rminus y x). \n\nDefinition Rle : R -> R -> Prop := fun x y => Rnonneg (Rminus y x).\n\n(* An alternative characterization of positivity upon R. *)\n\nDefinition Rpos_alt (x:R) := \n {l:nat & { p:nat | forall n, (p<=n)%nat -> (1#2)^l <= cauchy x n}}.\n\nLemma Rpos_alt_1 : forall x:R, Rpos x -> Rpos_alt x.\nProof.\nunfold Rpos, Rpos_k, Rpos_alt.\nintros.\nelim H; intros k Hk; clear H.\nexists (S k).\nexists (modulus x (S k)).\nintros.\n(*fedup.*)\ndestruct (x.(is_cauchy) (S k) n (modulus x (S k))) as (Hx,_); auto.\ngeneralize (Qplus_le_compat _ _ _ _ Hk Hx).\nstep_hd ((1#2)^(S k)<=cauchy x n); auto.\nDefined.\n\nLemma Rpos_alt_2 : forall x, Rpos_alt x -> Rpos x.\nunfold Rpos, Rpos_k, Rpos_alt.\nintros.\nelim H; intros l Hl; elim Hl; intros p Hp; clear H Hl.\nexists (S l).\n(*fedup.*)\nset (M:=modulus x (S (S l))).\nset (N:=max p M).\ndestruct (x.(is_cauchy) (S (S l)) M N) as (Hx,_); auto. \nunfold N, M; auto with arith.\napply Qle_trans with ((1#2)^l+(-(1#2)^(S (S l)))).\nstep ((1#2)*(1#2)^l<=(3#4)*(1#2)^l).\napply Qmult_le_compat_r; [|apply Qpower_pos]; compute; intro; discriminate.\nstep_right (cauchy x N +(cauchy x M - cauchy x N)).\napply Qplus_le_compat; auto.\napply Hp; unfold N; auto with arith.\nDefined.\n\n(* The Key Lemma: comparison between three reals. *)\n\nDefinition Rcompare : forall x y, Rlt x y -> forall z, Rlt x z + Rlt z y.\nunfold Rlt; intros.\ndestruct (Rpos_alt_1 _ H) as (k,(p,Hp)); clear H.\nset (k' := S (S k)).\nset (k'' := S (S k')).\nset (q := max (modulus x k'') (max (modulus y k'') (max (modulus z k'') p))).\ndestruct (Qlt_le_dec (cauchy z q - cauchy x q)  ((1#2)^(S k))); \n [right|left]; exists k'.\n(*fedup.*)\nred; simpl cauchy; simpl cauchy in Hp.\nset (q' := max (modulus y (S (S k'))) (modulus z (S (S k')))).\ndestruct (z.(is_cauchy) k'' q q') as (Hz,_); auto. \nunfold q, k''; eauto with arith.\nunfold q', k''; auto with arith.\ndestruct (y.(is_cauchy) k'' q' q) as (Hy,_); auto. \nunfold q', k''; auto with arith.\nunfold q, k''; eauto with arith.\nassert (p <= q)%nat by (unfold q; eauto with arith).\nassert (H0:=Hp q H); clear Hp H. \nassert (H1:=Qopp_le_compat _ _ (Qlt_le_weak _ _ q0)); clear q0.\nset (Yq' := cauchy y q') in *; set (Yq := cauchy y q) in *; \n set (Zq' := cauchy z q') in *; set (Zq := cauchy z q) in *; \n set (Xq := cauchy x q) in *; clearbody q q' Yq Yq' Zq Zq' Xq.\ngeneralize (Qplus_le_compat _ _ _ _ Hy\n                   (Qplus_le_compat _ _ _ _ H0 \n                       (Qplus_le_compat _ _ _ _ H1 Hz))).\nunfold k'', k'.\nstep_hd ((3#8)*(1#2)^k <= Yq'+-Zq').\nintros.\nstep_left ((1#4)*(1#2)^k).\napply Qle_trans with ((3#8)*(1#2)^k); auto.\napply Qmult_le_compat_r; [|apply Qpower_pos]; compute; intro; discriminate.\n(*fedup.*)\nred; simpl cauchy; simpl cauchy in Hp.\nset (q' := max (modulus z (S (S k'))) (modulus x (S (S k')))).\ndestruct (z.(is_cauchy) k'' q' q) as (Hz,_); auto. \nunfold q', k''; auto with arith.\nunfold q, k''; eauto with arith.\ndestruct (x.(is_cauchy) k'' q q') as (Hx,_); auto. \nunfold q, k''; eauto with arith.\nunfold q', k''; auto with arith.\nclear Hp.\nset (Xq' := cauchy x q') in *; set (Xq := cauchy x q) in *; \n set (Zq' := cauchy z q') in *; set (Zq := cauchy z q) in *; \n clearbody q q' Xq Xq' Zq Zq'.\ngeneralize (Qplus_le_compat _ _ _ _ Hz\n                   (Qplus_le_compat _ _ _ _ q0 Hx)).\nunfold k'', k'.\nstep_hd ((3#8)*(1#2)^k <= Zq'+-Xq').\nintros.\nstep_left ((1#4)*(1#2)^k).\napply Qle_trans with ((3#8)*(1#2)^k); auto.\napply Qmult_le_compat_r; [|apply Qpower_pos]; compute; intro; discriminate.\nDefined.\n\n(* Specialized continuity components for sqr2 = X^2-2 *)\n\nDefinition sqr2 := fun a => (a * a)+(-2).\nDefinition sqr2_h := fun a (_:nat) => sqr2 a.\nDefinition sqr2_alpha := fun (_:nat) => O.\nDefinition sqr2_w := fun k => S (S (S k)).\n\n(* Specialized application of sqr2 to a real. *)\n\nDefinition sqr2_apply : R -> R. \nintros x. \napply (Build_R (fun n => sqr2_h (cauchy x n) n) \n                       (fun k => max (sqr2_alpha (S (S k))) \n                                        (modulus x (pred (sqr2_w (S k)))))).\ngeneralize x.(is_cauchy).\nunfold Is_Cauchy, sqr2_h, sqr2_alpha, sqr2_w, sqr2; simpl; intros.\n(*fedup.*)\ngeneralize (H _ _ _ H0 H1); clear H H0 H1; intro H.\ndestruct x; simpl.\nunfold cauchy; simpl.\nfedup.\nDefined.\n\n(* sqr2 is strictly increasing at least on interval [1;infinity] *)\n\nDefinition sqr2_incr : forall x y, Rle (inject_Q 1) x -> Rle (inject_Q 1) y -> \n  Rlt x y -> Rlt (sqr2_apply x) (sqr2_apply y).\nunfold Rlt; intros.\napply Rpos_alt_2.\ngeneralize (Rpos_alt_1 _ H1); clear H1.\nunfold Rpos_alt, Rminus, Ropp, Rplus; simpl; unfold sqr2_h; simpl.\nintro H1; elim H1; intros k Hk; elim Hk; intros p Hp; clear H Hk.\nexists (pred k).\nexists p.\n(*fedup*)\nintros.\ngeneralize (Hp _ H); clear Hp; intros.\nunfold sqr2.\nstep_right ((cauchy y n +-cauchy x n)*(cauchy y n + cauchy x n)).\nred in H0.\nred in H0.\nsimpl in H0.\nfedup.\nDefined.\n\nLemma One_lt_Two : Rlt (inject_Q 1) (inject_Q 2).\nexists O.\nunfold Rpos_k.\nunfold inject_Q; simpl; auto.\nunfold Qle; simpl; auto with zarith.\nDefined.\n\nRequire Import nat_log.\n\nLemma two_p_correct : forall (n:nat), 2^n == two_p n.\nProof.\ninduction n.\nreflexivity.\nQpowerSimpl.\nrewrite IHn; clear IHn.\nunfold Z_of_nat, two_p.\ndestruct n.\nreflexivity.\nsimpl.\nset (p:=P_of_succ_nat n).\nunfold two_power_pos.\ndo 2 rewrite shift_pos_nat; unfold shift_nat.\nrewrite <- Pplus_one_succ_r.\nrewrite nat_of_P_succ_morphism.\nsimpl.\nunfold Qeq.\nsimpl.\nrewrite <- Pmult_assoc.\nrewrite (Pmult_comm 2).\nrewrite Pmult_assoc.\nrewrite Pmult_comm.\nreflexivity.\nQed.\n\n(* The strict order is conserved when injecting Q in R. *)\n\nLemma Qlt_Rlt : forall a b, a<b -> Rlt (inject_Q a) (inject_Q b).\nProof.\nintros a b; exists (nat_log_sup ((Qden b)*(Qden a))).\nunfold Rpos_k.\nunfold inject_Q; simpl; auto.\nrewrite Qinv_power_n.\nrewrite  two_p_correct.\nrewrite log_sup_log_sup.\nset (ab := (Qden b * Qden a)%positive) in *.\nassert ('ab <= two_p (log_sup ab)).\n red; simpl; simpl_mult; destruct (log_sup_correct2 ab) as (_,H0); omega.\napply Qmult_lt_0_le_reg_r with (two_p (log_sup ab)).\napply Qlt_le_trans with ('ab); [compute|]; auto.\nrewrite Qmult_comm.\nrewrite Qmult_inv_r by (intro H1; rewrite H1 in H0; auto).\nrewrite Qmult_comm.\napply Qle_trans with ('ab*(b+-a)); [|\n apply Qmult_le_compat_r; auto; \n rewrite <- Qle_minus_iff; apply Qlt_le_weak; auto].\nunfold ab; red; simpl.\nset (baab := ((Qnum b)*'(Qden a)+-(Qnum a)*'(Qden b))%Z).\nassert (1 <= baab)%Z.\n unfold baab; rewrite <- Zopp_mult_distr_l; red in H; omega.\ndestruct baab.\n(*baab = 0*)\nelim H1; auto.\n(*baab>0*)\nsimpl_mult.\nrewrite Zmult_1_r.\nassert (H2:=Zmult_le_compat (' Qden b * ' Qden a) 1 (' Qden b * ' Qden a) ('p)).\nrewrite Zmult_1_r in H2.\napply H2; auto.\napply Zle_refl.\ncompute; intro; discriminate.\ncompute; intro; discriminate.\n(*baab<0*)\nelim H1; auto.\nDefined.\n\n(* Main part: we now build a sequence of nested intervals \n   containing sqrt(2). *)\n\nRecord itvl : Set := { lft : Q ; rht : Q ; lft_rht : lft<rht}.\n(*Print itvl. *)\n(*Check itvl.*)\n\nDefinition two_three: itvl.\napply (Build_itvl 2 3).\nunfold Qlt; simpl; auto with zarith.\nQed.\n\n(*Check two_three.*)\n(*Check (lft two_three).*)\n(*Check lft_rht.*)\n(*Check (lft_rht two_three).*)\n\nRecord itvl2: Set:= {lft1:Q; rht1:Q; lft2:Q; rht2:Q; lft1_rht1: lft1<rht1; lft2_rht2: lft2<rht2}.\n\nDefinition in_itvl := fun i x => lft i <= x <= rht i.\nDefinition in_itvl2 := fun i x =>  lft1 i<=x<=rht1 i /\\ lft2 i<=x<=rht2 i.\n \nRecord continuous (i:itvl) : Set := {\n   cont_h : Q -> nat -> Q; \n   cont_alpha : nat -> nat;\n   cont_w : nat -> nat; \n   cont_cauchy: forall a, Is_Cauchy (cont_h a) cont_alpha;    \n   cont_unif : forall a b n k, le n (cont_alpha k) -> in_itvl i a -> in_itvl i b ->   \n       -(1#2)^(pred (cont_w k)) <= a-b <= (1#2)^(pred (cont_w k)) -> \n       -(1#2)^k <= cont_h a n - cont_h b n <= (1#2)^k\n}.\n\nDefinition one_two : itvl. \napply (Build_itvl 1 2).\nunfold Qlt; simpl; auto with zarith.\nQed.\n\nDefinition sqr2_cont : continuous one_two.\napply (Build_continuous one_two sqr2_h sqr2_alpha sqr2_w).\nfedup. \nfedup.\nQed.\n\nRequire Zcomplements.\n\n(* Coercion Zpos : positive >-> Z. *)\n\nDefinition sqrt2_approx : nat -> itvl.\ninduction 1. \napply (Build_itvl 1 2); unfold Qlt; simpl; omega.\nelim IHnat; intros a b ab.\nset (c:= (Qred ((2#3)*a+(1#3)*b))).\nset (d:= (Qred ((1#3)*a+(2#3)*b))).\nassert (cd : c<d).\n   unfold c, d.\n   rewrite Qlt_minus_iff in ab |- *.\n   rewrite (Qred_correct ((2#3)*a+(1#3)*b)). \n   rewrite (Qred_correct ((1#3)*a+(2#3)*b)).\n   step (0*(1#3) <= (b+-a)*(1#3)).\n   apply Qmult_lt_compat_r; [compute|]; auto.\nset (fc := sqr2_apply (inject_Q c)).\nset (fd := sqr2_apply (inject_Q d)).\nassert (fcfd : Rlt fc fd).\n  unfold fc, fd; apply sqr2_incr.\n  fedup.\n  fedup.\n apply Qlt_Rlt; auto.\ncase (Rcompare fc fd fcfd (inject_Q 0)); intros.\napply (Build_itvl c b).\n  fedup.\napply (Build_itvl a d).\n  fedup.\nDefined.\n\n(* The cauchy sequence giving sqrt(2) is finally obtained \n    by the left borders of these intervals. *)\n\nDefinition sqrt2: R. \napply (Build_R (fun n => lft (sqrt2_approx n)) (fun k => plus k k)).\nfedup.\nDefined.\n\nExtraction Inline Zcompare_rec Z_lt_rec.\nExtraction \"sqrt2.ml\" sqrt2.\n\n", "meta": {"author": "coq-contribs", "repo": "qarith", "sha": "a30fd6b2fa71e35dbadf38e5c04df98b842ca479", "save_path": "github-repos/coq/coq-contribs-qarith", "path": "github-repos/coq/coq-contribs-qarith/qarith-a30fd6b2fa71e35dbadf38e5c04df98b842ca479/Sqrt2/Reals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.25777418359488}}
{"text": "From Coq Require Import Lists.List.\nFrom Coq Require Import Init.Nat.\nFrom Coq Require Import Numbers.NatInt.NZDiv.\nFrom Coq Require Import Numbers.NatInt.NZLog.\nFrom Coq Require Import Numbers.NatInt.NZBits.\nRequire Import RuntimeDefinitions.\nRequire Import AppendixD.\nRequire Import AppendixF.\n\nDefinition lt_way_ID (c1: nullable_cachelet_index) (c2: nullable_cachelet_index) : nullable_cachelet_index :=\n  match c1, c2 with\n  | cachelet_index_defined v1, cachelet_index_defined v2 =>\n    match v1, v2 with\n    | (w1, _), (w2, _) =>\n      if ltb w1 w2 then c1 else c2\n    end\n  | _, cachelet_index_none => c1\n  | _, _ => c2\n  end.\n\nDefinition nullify_cachelet_index (c: cachelet_index): nullable_cachelet_index := cachelet_index_defined c.\nDefinition nullify_cachelet_index_list (l: (list cachelet_index)): (list nullable_cachelet_index) :=\n  map (nullify_cachelet_index) l.\n\n(* Way First Allocation *)\nDefinition cachelet_min_way_ID (l: (list cachelet_index)): nullable_cachelet_index :=\n  fold_right lt_way_ID cachelet_index_none (nullify_cachelet_index_list l).\nDefinition way_first_allocation (F: CAT): nullable_cachelet_index := cachelet_min_way_ID F.\n\n(* Cachelet Invalidation*)\nDefinition cachelet_invalidation (C: way_set_cache) (ci: cachelet_index): way_set_cache :=\n  match (CacheletMap.find ci C) with\n  | Some (valid_bit_tag_and_data _ c d) => CacheletMap.add ci (valid_bit_tag_and_data dirty_bit c d) C\n  | None => C\n  end.\n\n(* Beta Function *)\nInductive set_and_tag : Type :=\n  | set_and_tag_values: set_ID -> cache_tag_value -> set_and_tag.\nDefinition block_to_set_and_tag (val: block_ID) (sets: set_indexed_PLRU) : set_and_tag :=\n  set_and_tag_values (val mod (length (NatMapProperties.to_list sets))) (shiftr val (log2 (length (NatMapProperties.to_list sets)))).\n\n\n(* Find Way ID *)\nFixpoint find_way_ID_in_mask (t: cache_tag_value) (s: set_ID) (W: way_mask) (C: way_set_cache): option way_ID :=\n  match W with\n  | nil => None\n  | w :: W' =>\n    match (CacheletMap.find (w, s) C) with\n    | None => find_way_ID_in_mask t s W' C\n    | Some cache_value =>\n      match cache_value with\n      | valid_bit_tag_and_data vb t' D =>\n        match t =? t' with\n        | true => Some w\n        | false => find_way_ID_in_mask t s W' C\n        end\n      end\n    end\n  end.\nDefinition find_way_ID_with_cache_tag (state: enclave_state) (s: set_ID) (t: cache_tag_value) (V: VPT) (C: way_set_cache): option way_ID :=\n  match state with\n  | enclave_state_value e_id _ =>\n    match e_id with\n    | enclave_ID_inactive => None\n    | enclave_ID_active e =>\n      match (NatMap.find e V) with\n      | None => None\n      | Some L =>\n        match (NatMap.find s L) with\n        | None => None\n        | Some W => find_way_ID_in_mask t s W C\n        end\n      end\n    end\n  end.\n\n\n(* CC 'Unfold' Function(s) *)\nInductive validatable_cc_unfold : Type :=\n| cc_unfold_valid: CAT -> VPT -> way_set_cache -> set_indexed_PLRU -> cachelet_index -> way_set_cache_value -> data_offset -> validatable_cc_unfold\n| cc_unfold_error: validatable_cc_unfold.\nDefinition cc_unfold (psi: single_level_cache_unit) (state: enclave_state) (l: memory_address): validatable_cc_unfold :=\n  match psi with\n  | single_level_cache F V C R =>\n    match l with\n    | address b delta =>\n      match (block_to_set_and_tag b R) with\n      | set_and_tag_values s t =>\n        match (find_way_ID_with_cache_tag state s t V C) with\n        | None => cc_unfold_error\n        | Some w =>\n          match (CacheletMap.find (w, s) C) with\n          | None => cc_unfold_error\n          | Some cache_val => cc_unfold_valid F V C R (w, s) cache_val delta\n          end\n        end\n      end\n    end\n  end.\n\n\n(* CC Hit Read *)\nInductive validatable_cc_hit_read : Type :=\n  | cc_hit_read_valid: data_block -> data_offset -> cachelet_index -> single_level_cache_unit -> validatable_cc_hit_read\n  | cc_hit_read_error: validatable_cc_hit_read.\nDefinition cc_hit_read (psi: single_level_cache_unit) (state: enclave_state) (l: memory_address): validatable_cc_hit_read :=\n  match (cc_unfold psi state l) with\n  | cc_unfold_error => cc_hit_read_error\n  | cc_unfold_valid F V C R (w, s) cache_val delta =>\n    match cache_val with\n    | valid_bit_tag_and_data _ _ D => \n      match (NatMap.find s R) with\n      | None => cc_hit_read_error\n      | Some T' => \n        match state with\n        | enclave_state_value e _ => cc_hit_read_valid D delta (w, s) (single_level_cache F V C (NatMap.add s (update T' w e) R))\n        end\n      end\n    end\n  end.\n\n\n(* CC Hit Write *)\nInductive validatable_cc_hit_write : Type :=\n  | cc_hit_write_valid: data_block -> cachelet_index -> single_level_cache_unit -> validatable_cc_hit_write\n  | cc_hit_write_error: validatable_cc_hit_write.\nDefinition cc_hit_write (psi: single_level_cache_unit) (state: enclave_state) (l: memory_address) (v: memory_value): validatable_cc_hit_write :=\n  match (cc_unfold psi state l) with\n  | cc_unfold_error => cc_hit_write_error\n  | cc_unfold_valid F V C R (w, s) cache_val delta =>\n    match cache_val with\n    | valid_bit_tag_and_data _ t D =>\n      match (NatMap.find s R) with\n      | None => cc_hit_write_error\n      | Some T' => \n        match v with\n        | memory_value_instruction _ => cc_hit_write_error\n        | memory_value_data n =>\n          match state with\n          | enclave_state_value e _ => cc_hit_write_valid D (w, s) (single_level_cache F V (CacheletMap.add (w, s) (valid_bit_tag_and_data dirty_bit t (NatMap.add delta (memory_value_data n) D)) C) (NatMap.add s (update T' w e) R))\n          end\n        end\n      end\n    end\n  end.\n\n\n(* CC Update *)\nInductive validatable_cc_update : Type :=\n  | cc_update_valid: cachelet_index -> single_level_cache_unit -> validatable_cc_update\n  | cc_update_error: validatable_cc_update.\nDefinition cc_update (psi: single_level_cache_unit) (state: enclave_state) (D: data_block) (l: memory_address): validatable_cc_update :=\n  match (cc_unfold psi state l) with\n  | cc_unfold_error => cc_update_error\n  | cc_unfold_valid F V C R (w, s) cache_val _ =>\n    match cache_val with\n    | valid_bit_tag_and_data _ t _ =>\n      match state with\n      | enclave_state_value e _ =>\n        match (NatMap.find s R) with\n        | None => cc_update_error\n        | Some T' =>\n          match (replace T' e) with\n          | None => cc_update_error\n          | Some w' => cc_update_valid (w, s) (single_level_cache F V (CacheletMap.add (w, s) (valid_bit_tag_and_data valid_bit t D) C) (NatMap.add s (update T' w e) R))\n          end\n        end\n      end\n    end\n  end.\n\n\n(* Cachelet Allocation *)\nFixpoint recursive_cachelet_allocation (n: nat) (e: raw_enclave_ID) (F: CAT) (V: VPT) (C: way_set_cache) (R: set_indexed_PLRU): option single_level_cache_unit :=\n  match n with\n  | 0 => Some (single_level_cache F V C R)\n  | S n' =>\n    match way_first_allocation F with\n    | cachelet_index_none => None\n    | cachelet_index_defined (w, s) =>\n      match (NatMap.find s R) with\n      | None => None\n      | Some T' => \n        match (NatMap.find e V) with\n        | None => recursive_cachelet_allocation n' e (remove_CAT (w, s) F) (NatMap.add e (NatMap.add s (w :: nil) (NatMap.empty (list way_ID))) V) C (NatMap.add s (update T' w (enclave_ID_active e)) R)\n        | Some L =>\n          match (NatMap.find s L) with\n          | None => recursive_cachelet_allocation n' e (remove_CAT (w, s) F) (NatMap.add e (NatMap.add s (w :: nil) L) V) C (NatMap.add s (update T' w (enclave_ID_active e)) R)\n          | Some W => recursive_cachelet_allocation n' e (remove_CAT (w, s) F) (NatMap.add e (NatMap.add s (w :: W) L) V) C (NatMap.add s (update T' w (enclave_ID_active e)) R)\n          end\n        end\n      end\n    end\n  end.\nDefinition cachelet_allocation (n: nat) (e: raw_enclave_ID) (psi: single_level_cache_unit): option single_level_cache_unit := \n  match psi with\n  | single_level_cache F V C R => recursive_cachelet_allocation n e F V C R\n  end.\n\n\n(* Cachelet Deallocation *)\nFixpoint free_cachelets (e: raw_enclave_ID) (s: set_ID) (W: way_mask) (F: CAT) (V: VPT) (C: way_set_cache) (R: set_indexed_PLRU): option single_level_cache_unit :=\n  match W with\n  | nil => Some (single_level_cache F V C R)\n  | w :: W' => \n    match (NatMap.find s R) with\n    | None => None\n    | Some T' => (free_cachelets e s W' ((w, s) :: F) V (cachelet_invalidation C (w, s)) (NatMap.add s (update T' w (enclave_ID_active e)) R))\n    end\n  end.\nFixpoint clear_remapping_list (e: raw_enclave_ID) (L: list (set_ID * way_mask % type)) (F: CAT) (V: VPT) (C: way_set_cache) (R: set_indexed_PLRU): option single_level_cache_unit :=\n  match L with\n  | nil => Some (single_level_cache F (NatMap.remove e V) C R)\n  | (s, W) :: L' =>\n    match (free_cachelets e s W F V C R) with\n    | None => None\n    | Some psi' =>\n      match psi' with\n      | single_level_cache F' V' C' R' => clear_remapping_list e L' F' V' C' R'\n      end\n    end\n  end.\nDefinition cachelet_deallocation (e: raw_enclave_ID) (psi: single_level_cache_unit): option single_level_cache_unit :=\n  match psi with\n  | single_level_cache F V C R =>\n    match (NatMap.find e V) with\n    | None => None\n    | Some L => clear_remapping_list e (NatMapProperties.to_list L) F V C R\n    end\n  end.\n", "meta": {"author": "mlc-coq", "repo": "Isolated-Execution-Coq", "sha": "856246a2ad067f7c91379ff5b749fabb10522369", "save_path": "github-repos/coq/mlc-coq-Isolated-Execution-Coq", "path": "github-repos/coq/mlc-coq-Isolated-Execution-Coq/Isolated-Execution-Coq-856246a2ad067f7c91379ff5b749fabb10522369/AppendixC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.25769933931838435}}
{"text": "\nRequire Export CatSem.CAT.ind_potype.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Transparent Obligations.\nUnset Automatic Introduction.\n\n\n(** for module M, we define [IPO_Der_Mod M], the derived module *)\n\nSection fixatype.\n\nVariable T : Type.\n\nSection Der_Module.\n\nVariable P : Monad (IPO T).\n(*\nVariable obD : Type.\nVariable morD : obD -> obD -> Type.\nVariable D: Cat morD.\n*)\nVariable D : Cat.\nSection Der_Module_def.\n\nVariable M : MOD P D.\n\nObligation Tactic := idtac.\n\nProgram Instance IPO_Der_Mod_struct (u:T) : \n        Module_struct P (fun V => M (opt_TP u V)) := {\n  mkleisli a b f := (mkleisli (M:=M)(opt_TP_def_varinj u f)) \n}.\nNext Obligation.\nProof.\n  unfold Proper; red.\n  intros u c d z y H.\n  apply mkleisli_oid.\n  simpl; intros.\n  elim_opt.\n  rewrite H;\n  auto.\nQed.\nObligation 3.\nProof.\n  intros; simpl.\n  rewrite opt_TP_def_varinj_weta.\n  mod.\nQed. \nNext Obligation.\nProof.\n  simpl; intros.\n  rewrite mkl_mkl.\n  apply mkleisli_oid.\n  unfold opt_TP_def_varinj.\n  simpl; intros.\n  elim_opt.\n  rew (lift_kleisli (M:=P)).\n  rew (kleisli_lift (M:=P)).\n  apply (kl_eq P).\n  simpl; auto.\n  \n  rew (eta_kl (Monad_struct := P)).\nQed.\n\nCanonical Structure IPO_Der_Mod (u:T) : MOD P D := \n      Build_Module (IPO_Der_Mod_struct u).\n\n\nEnd Der_Module_def.\n\n(** deriving a module wrt u:T yields a functor *)\n\nSection Der_Module_Functor.\n\nSection Der_Mod_Hom.\n\nVariables M N: MOD P D.\nVariable TT : M ---> N.\n\nObligation Tactic := simpl; mod; try apply TT.\n\nProgram Instance Der_Mod_Hom_struct (u:T) : \n  Module_Hom_struct (S:=IPO_Der_Mod M u) (T:=IPO_Der_Mod N u)\n            (fun _ => TT (*opt_TP u x*) _ ) .\n\nCanonical Structure Der_Mod_Hom (u:T) : \n     IPO_Der_Mod M u ---> IPO_Der_Mod N u :=\n           Build_Module_Hom \n           (Der_Mod_Hom_struct u).\n\nEnd Der_Mod_Hom.\n\nObligation Tactic := simpl; intros; \n    try (match goal with [|-Proper _ _ ] => unfold Proper; red end);\n    cat.\n\nProgram Instance Der_Mod_Func (u:T) : \n   Functor_struct (C:=MOD P D) (D:=MOD P D) \n        (Fobj:= fun z => IPO_Der_Mod z u) \n        (fun M N TT => Der_Mod_Hom (M:=M) (N:=N) TT u).\n\nCanonical Structure DER_MOD (u:T) := Build_Functor (Der_Mod_Func u).\n\nEnd Der_Module_Functor.\n\nEnd Der_Module.\n\nSection Fibre_module.\n\nVariable P: Monad (IPO T).\n\nSection Fibre_Module_def.\n\nVariable M : MOD P (IPO T).\n\nObligation Tactic := \n    cat; \n    try (match goal with [|- Proper _ _ ] => do 2 red end);\n    cat;\n    try apply (mkl_eq M);\n    try rew (mklmkl M); try rew (mklweta (P:=P) (M:=M)); auto.\n\nProgram Instance Fibre_Mod_struct (u:T) : \n       Module_struct P  (fun c => IP_proj u (M c)) := {\n  mkleisli a b f := #(IP_proj u) (@mkleisli _ P  _ M M  a b f)  \n}.\n\nCanonical Structure Fibre_Mod (u:T) : MOD P Ord := \n           Build_Module (Fibre_Mod_struct u).\n\nEnd Fibre_Module_def.\n\nSection Fibre_Module_Hom.\nVariables M N : MOD P (IPO T).\nVariable TT : M ---> N.\n\nObligation Tactic := simpl; intros; \n   rew (mod_hom_mkl (Module_Hom_struct := TT)).\n\nProgram Instance Fib_Mod_Hom_struct (u:T) : \n   Module_Hom_struct (S:= Fibre_Mod M u )(T:= Fibre_Mod N u)\n    (fun z => #(IP_proj u) (TT z) ).\n\nCanonical Structure Fib_Mod_Hom (u:T) : \n     Fibre_Mod M u ---> Fibre_Mod N u :=\n        Build_Module_Hom (Fib_Mod_Hom_struct u).\n\nEnd Fibre_Module_Hom.\n\nObligation Tactic := repeat red; simpl; auto.\n\nProgram Instance Fib_Mod_Func (u:T) : \n   Functor_struct (C:=MOD P (IPO T)) (D:=MOD P Ord) \n        (Fobj:= fun x => Fibre_Mod x u) \n        (fun M N TT => Fib_Mod_Hom (M:=M) (N:=N) TT u).\n\nCanonical Structure FIB_MOD (u:T) := Build_Functor (Fib_Mod_Func u).\n\nEnd Fibre_module.\n\nSection DER_PB.\n\nNotation \"Sig '*' M\" := (PB_MOD Sig _ M).\nVariables R S: Monad (IPO T).\nVariable Sig: Monad_Hom R S.\n(*\nVariable obD: Type.\nVariable morD: obD -> obD -> Type.\nVariable D: Cat morD.\n*)\nVariable D : Cat.\nVariable M: MOD S D.\n\nObligation Tactic := cat;\n    apply mkleisli_oid; simpl; intros; elim_opt;\n    try rew (monad_hom_lift Sig); \n    rew(monad_hom_weta (Monad_Hom_struct := Sig)).\n\nProgram Instance PB_DER_struct (u:T) : \n  Module_Hom_struct \n      (S:= (PB_MOD Sig _ (DER_MOD _ _ u M)))\n      (T:= DER_MOD _ _ u (PB_MOD Sig _ M))\n          (fun e => id _) .\n\nDefinition PB_DER (u:T) : PB_MOD Sig _ (DER_MOD _ _ u M) ---> \n                            DER_MOD _ _ u (PB_MOD Sig _ M) :=\n         Build_Module_Hom (PB_DER_struct u).\n\nProgram Instance DER_PB_struct (u:T) : \n  Module_Hom_struct \n    (T:= (PB_MOD Sig _ (DER_MOD _ _ u M)))\n    (S:= DER_MOD _ _ u (PB_MOD Sig _ M))\n          (fun e => id _) .\n\nDefinition DER_PB (u:T) : DER_MOD _ _ u (PB_MOD Sig _ M) ---> \n                  PB_MOD Sig _ (DER_MOD _ _ u M) :=\n         Build_Module_Hom (DER_PB_struct u).\n\nLemma DER_PB_PB_DER (u:T) : DER_PB u ;; PB_DER u == id _ .\nProof.\n  cat.\nQed.\n\nLemma PB_DER_DER_PB (u:T) : PB_DER u ;; DER_PB u == id _.\nProof.\n  cat.\nQed.\n\nEnd DER_PB.\n\nSection FIB_PB.\n\nNotation \"Sig '*' M\" := (PB_MOD Sig _ M).\nVariables R S: Monad (IPO T).\nVariable Sig: Monad_Hom R S.\n(*\nVariable obD: Type.\nVariable morD: obD -> obD -> Type.\nVariable D: Cat morD.\n*)\nVariable M: MOD S (IPO T).\n\nObligation Tactic := cat.\n\nProgram Instance PB_FIB_struct (u:T) : \n   Module_Hom_struct \n   (S:= (PB_MOD Sig _ (FIB_MOD _ u M)))\n   (T:= FIB_MOD _ u (PB_MOD Sig _ M))\n          (fun e => id _) .\n\nDefinition PB_FIB (u:T) : \nPB_MOD Sig _ (FIB_MOD _ u M) ---> FIB_MOD _ u (PB_MOD Sig _ M) :=\n          Build_Module_Hom (PB_FIB_struct u).\n\nProgram Instance FIB_PB_struct (u:T) : \n  Module_Hom_struct \n   (T:= (PB_MOD Sig _ (FIB_MOD _ u M)))\n   (S:= FIB_MOD _ u (PB_MOD Sig _ M))\n          (fun e => id _) .\n\nDefinition FIB_PB (u:T) : \nFIB_MOD _ u (PB_MOD Sig _ M) ---> PB_MOD Sig _ (FIB_MOD _ u M) :=\n          Build_Module_Hom (FIB_PB_struct u).\n\nLemma FIB_PB_PB_FIB (u:T) : \n          FIB_PB u ;; PB_FIB u == id _ .\nProof.\n  cat.\nQed.\n\nLemma PB_FIB_FIB_PB (u:T) : \n          PB_FIB u ;; FIB_PB u == id _ .\nProof.\n  cat.\nQed.\n  \nEnd FIB_PB.\n\nEnd fixatype.\n\nExisting Instance Fib_Mod_Func.\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/CAT/ipo_modules.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.3775406547908327, "lm_q1q2_score": 0.25769932975736076}}
{"text": "Require Import Bool String List Arith.Peano_dec Lia.\nRequire Import Lib.FMap Lib.Struct Lib.CommonTactics Lib.Indexer Lib.StringEq Lib.ListSupport.\nRequire Import Kami.Syntax Kami.Semantics Kami.SemFacts Kami.RefinementFacts Kami.Renaming Kami.Wf.\nRequire Import Kami.Specialize.\n\nRequire Import FunctionalExtensionality.\nRequire Import Compare_dec.\n\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\nSection Duplicate.\n  Variable m: nat -> Modules.\n\n  Fixpoint duplicate n :=\n    match n with\n    | O => specializeMod (m O) O\n    | S n' => ConcatMod (specializeMod (m n) n) (duplicate n')\n    end.\n\nEnd Duplicate.\n\nSection DuplicateFacts.\n  Variable m: nat -> Modules.\n\n  Lemma duplicate_ModEquiv:\n    forall ty1 ty2 n,\n      (forall iv, ModEquiv ty1 ty2 (m iv)) ->\n      ModEquiv ty1 ty2 (duplicate m n).\n  Proof.\n    induction n; simpl; intros;\n      [apply specializeMod_ModEquiv; auto|].\n    apply ModEquiv_modular; auto.\n    apply specializeMod_ModEquiv; auto.\n  Qed.\n\n  Lemma duplicate_validRegsModules:\n    forall n,\n      (forall iv, ValidRegsModules type (m iv)) ->\n      ValidRegsModules type (duplicate m n).\n  Proof.\n    induction n; simpl; intros.\n    - apply specializeMod_validRegsModules; auto.\n    - split; auto.\n      apply specializeMod_validRegsModules; auto.\n  Qed.\n\n  Lemma duplicate_dom_indexed:\n    (forall iv, Specializable (m iv)) ->\n    forall s n ,\n      In s (spDom (duplicate m n)) ->\n      exists t i, s = t __ i /\\ i < S n.\n  Proof.\n    induction n; simpl; intros.\n    - pose proof (specializeMod_dom_indexed (H 0) _ _ H0); dest; subst.\n      do 2 eexists; eauto.\n    - apply spDom_in in H0; destruct H0.\n      + pose proof (specializeMod_dom_indexed (H (S n)) _ _ H0); dest; subst.\n        do 2 eexists; eauto.\n      + specialize (IHn H0); dest; subst.\n        do 2 eexists; eauto.\n  Qed.\n\n  Lemma duplicate_specializeMod_disj_regs:\n    (forall iv, Specializable (m iv)) ->\n    forall n ln iv,\n      ln > n ->\n      DisjList (namesOf (getRegInits (specializeMod (m iv) ln)))\n               (namesOf (getRegInits (duplicate m n))).\n  Proof.\n    induction n; simpl; intros.\n    - apply specializeMod_disj_regs_different_indices; auto; lia.\n    - unfold namesOf in *.\n      rewrite map_app.\n      apply DisjList_comm, DisjList_app_4.\n      + apply specializeMod_disj_regs_different_indices; auto; lia.\n      + apply DisjList_comm, IHn; lia.\n  Qed.\n\n  Lemma duplicate_specializeMod_disj_defs:\n    (forall iv, Specializable (m iv)) ->\n    forall n ln iv,\n      ln > n ->\n      DisjList (getDefs (specializeMod (m iv) ln))\n               (getDefs (duplicate m n)).\n  Proof.\n    induction n; simpl; intros.\n    - apply specializeMod_disj_defs_different_indices; auto; lia.\n    - apply DisjList_comm.\n      apply DisjList_SubList with\n      (l1:= app (getDefs (specializeMod (m (S n)) (S n)))\n                (getDefs (duplicate m n))).\n      + unfold SubList; intros.\n        apply getDefs_in in H1; destruct H1;\n          apply in_or_app; auto.\n      + apply DisjList_app_4.\n        * apply specializeMod_disj_defs_different_indices; auto; lia.\n        * apply DisjList_comm, IHn; lia.\n  Qed.\n\n  Lemma duplicate_specializeMod_disj_calls:\n    (forall iv, Specializable (m iv)) ->\n    forall n ln iv,\n      ln > n ->\n      DisjList (getCalls (specializeMod (m iv) ln))\n               (getCalls (duplicate m n)).\n  Proof.\n    induction n; simpl; intros.\n    - apply specializeMod_disj_calls_different_indices; auto; lia.\n    - apply DisjList_comm.\n      apply DisjList_SubList with\n      (l1:= app (getCalls (specializeMod (m (S n)) (S n)))\n                (getCalls (duplicate m n))).\n      + unfold SubList; intros.\n        apply getCalls_in in H1; destruct H1;\n          apply in_or_app; auto.\n      + apply DisjList_app_4.\n        * apply specializeMod_disj_calls_different_indices; auto; lia.\n        * apply DisjList_comm, IHn; lia.\n  Qed.\n  \n  Lemma duplicate_disj_regs:\n    forall m1 m2,\n      (forall iv1, Specializable (m1 iv1)) ->\n      (forall iv2, Specializable (m2 iv2)) ->\n      (forall iv1 iv2, DisjList (namesOf (getRegInits (m1 iv1)))\n                                (namesOf (getRegInits (m2 iv2)))) ->\n      forall n,\n        DisjList (namesOf (getRegInits (duplicate m1 n)))\n                 (namesOf (getRegInits (duplicate m2 n))).\n  Proof.\n    induction n; simpl; intros.\n    - apply specializeMod_disj_regs_2; auto.\n    - unfold namesOf; do 2 rewrite map_app; apply DisjList_app_4.\n      + apply DisjList_comm, DisjList_app_4.\n        * apply DisjList_comm, specializeMod_disj_regs_2; auto.\n        * clear IHn.\n          assert (n < S n) by lia.\n          generalize dependent (S n); intros.\n          induction n; simpl; intros.\n          { apply DisjList_comm, specializeMod_disj_regs_2; auto. }\n          { rewrite map_app; apply DisjList_app_4.\n            { apply DisjList_comm, specializeMod_disj_regs_2; auto. }\n            { apply IHn; lia. }\n          }\n      + apply DisjList_comm, DisjList_app_4.\n        * clear IHn.\n          assert (n < S n) by lia.\n          generalize dependent (S n); intros.\n          induction n; simpl; intros.\n          { apply DisjList_comm, specializeMod_disj_regs_2; auto. }\n          { rewrite map_app; apply DisjList_comm, DisjList_app_4.\n            { apply specializeMod_disj_regs_2; auto. }\n            { apply DisjList_comm; auto.\n              apply IHn; lia.\n            }\n          }\n        * apply DisjList_comm, IHn.\n  Qed.\n\n  Lemma duplicate_noninteracting:\n    (forall iv, Specializable (m iv)) ->\n    forall n ln,\n      ln > n ->\n      forall iv,\n        NonInteracting (specializeMod (m iv) ln)\n                       (duplicate m n).\n  Proof.\n    induction n; simpl; intros.\n    - apply specializable_noninteracting_2; auto; lia.\n    - unfold NonInteracting in *.\n      assert (ln > n) by lia; specialize (IHn _ H1); clear H1; dest.\n      split.\n      + apply DisjList_comm.\n        apply DisjList_SubList with\n        (l1:= app (getCalls (specializeMod (m (S n)) (S n)))\n                  (getCalls (duplicate m n))).\n        * unfold SubList; intros.\n          apply getCalls_in in H1.\n          apply in_or_app; auto.\n        * apply DisjList_app_4.\n          { pose proof (specializable_noninteracting_2 (H (S n)) (H iv)).\n            apply H1; lia.\n          }\n          { specialize (IHn iv); dest.\n            apply DisjList_comm; auto.\n          }\n      + apply DisjList_comm.\n        apply DisjList_SubList with\n        (l1:= app (getDefs (specializeMod (m (S n)) (S n)))\n                  (getDefs (duplicate m n))).\n        * unfold SubList; intros.\n          apply getDefs_in in H1.\n          apply in_or_app; auto.\n        * apply DisjList_app_4.\n          { pose proof (specializable_noninteracting_2 (H (S n)) (H iv)).\n            apply H1; lia.\n          }\n          { specialize (IHn iv); dest.\n            apply DisjList_comm; auto.\n          }\n  Qed.\n\n  Lemma duplicate_regs_NoDup:\n    forall (Hsp: forall iv, Specializable (m iv)) n,\n      (forall iv, NoDup (namesOf (getRegInits (m iv)))) ->\n      NoDup (namesOf (getRegInits (duplicate m n))).\n  Proof.\n    induction n; simpl; intros; [apply specializeMod_regs_NoDup; auto|].\n    unfold namesOf in *; simpl in *.\n    rewrite map_app; apply NoDup_DisjList; auto.\n    - apply specializeMod_regs_NoDup, H; auto.\n    - apply duplicate_specializeMod_disj_regs; auto.\n  Qed.\n\n  Lemma getRegInits_duplicate_nil:\n    forall n,\n      (forall iv, Specializable (m iv)) ->\n      (forall iv, getRegInits (m iv) = nil) ->\n      getRegInits (duplicate m n) = nil.\n  Proof.\n    intros.\n    match goal with\n    | [ |- ?P ] => assert (namesOf (getRegInits (duplicate m n)) = nil -> P) as Hm\n    end.\n    { intros; unfold namesOf in H1; eapply map_eq_nil; eauto. }\n    apply Hm; clear Hm.\n    \n    induction n; simpl; intros.\n    - rewrite specializeMod_regs; auto.\n      rewrite H0; reflexivity.\n    - rewrite namesOf_app.\n      rewrite IHn; rewrite app_nil_r.\n      rewrite specializeMod_regs; auto.\n      rewrite H0; reflexivity.\n  Qed.\n\n  Lemma getDefs_duplicate_nil:\n    (forall iv, Specializable (m iv)) ->\n    (forall iv, getDefs (m iv) = nil) ->\n    forall n,\n      getDefs (duplicate m n) = nil.\n  Proof.\n    induction n; simpl; intros.\n    - rewrite specializeMod_defs; auto.\n      rewrite H0; reflexivity.\n    - rewrite getDefs_app.\n      rewrite IHn; rewrite app_nil_r.\n      rewrite specializeMod_defs; auto.\n      rewrite H0; reflexivity.\n  Qed.\n\n  Lemma getDefsBodies_duplicate_nil:\n    (forall iv, Specializable (m iv)) ->\n    (forall iv, getDefsBodies (m iv) = nil) ->\n    forall n,\n      getDefsBodies (duplicate m n) = nil.\n  Proof.\n    intros.\n    assert (forall iv, getDefs (m iv) = nil) by (intros; unfold getDefs; rewrite H0; reflexivity).\n    eapply getDefs_duplicate_nil with (n:= n) in H1; eauto.\n    eapply map_eq_nil with (f:= @attrName _); eauto.\n  Qed.\n\n  Lemma getRules_duplicate_in:\n    forall rn rb i,\n      (forall iv, Specializable (m iv)) ->\n      In (rn :: rb)%struct (getRules (m i)) ->\n      forall n,\n        i <= n ->\n        In ((rn __ i)\n              :: (fun ty => (Renaming.renameAction (specializer (m i) i) (rb ty))))%struct\n           (getRules (duplicate m n)).\n  Proof.\n    induction n; simpl; intros.\n    - inv H1; apply specializeMod_rules_in; auto.\n    - inv H1; [|apply in_or_app; right; auto].\n      apply in_or_app; left.\n      apply specializeMod_rules_in; auto.\n  Qed.\n\nEnd DuplicateFacts.\n\nSection TwoModules1.\n  Variables (m1 m2: Modules).\n  Hypotheses (Hsp1: Specializable m1)\n             (Hsp2: Specializable m2)\n             (Hequiv1: ModEquiv type typeUT m1)\n             (Hequiv2: ModEquiv type typeUT m2)\n             (Hvr1: ValidRegsModules type m1)\n             (Hvr2: ValidRegsModules type m2)\n             (Hexts: SubList (getExtMeths m1) (getExtMeths m2)).\n\n  Lemma specializer_equiv:\n    forall {A} (m: M.t A),\n      M.KeysSubset m (spDom m1) ->\n      M.KeysSubset m (spDom m2) ->\n      forall i,\n        renameMap (specializer m1 i) m = renameMap (specializer m2 i) m.\n  Proof. intros; do 2 (rewrite specializer_map; auto). Qed.\n\n  Lemma specializeMod_defCallSub:\n    forall i,\n      DefCallSub m1 m2 ->\n      DefCallSub (specializeMod m1 i) (specializeMod m2 i).\n  Proof.\n    unfold DefCallSub; intros; dest; split.\n    - do 2 rewrite specializeMod_defs by assumption.\n      apply SubList_map; auto.\n    - do 2 rewrite specializeMod_calls by assumption.\n      apply SubList_map; auto.\n  Qed.\n\n  Lemma specializer_two_comm:\n    forall (m: MethsT),\n      M.KeysSubset m (getExtMeths m1) ->\n      forall i,\n        m = renameMap (specializer m2 i) (renameMap (specializer m1 i) m).\n  Proof.\n    intros.\n    replace (renameMap (specializer m1 i) m) with (renameMap (specializer m2 i) m).\n    - rewrite renameMapFInvG; auto.\n      + apply specializer_bijective.\n        apply specializable_disj_dom_img; auto.\n      + apply specializer_bijective.\n        apply specializable_disj_dom_img; auto.\n    - apply eq_sym, specializer_equiv.\n      + eapply M.KeysSubset_SubList; eauto.\n        pose proof (getExtMeths_meths m1).\n        apply SubList_trans with (l2:= app (getDefs m1) (getCalls m1)); auto.\n        apply SubList_app_3; [apply spDom_defs|apply spDom_calls].\n      + apply M.KeysSubset_SubList with (d2:= getExtMeths m2) in H; auto.\n        eapply M.KeysSubset_SubList; eauto.\n        pose proof (getExtMeths_meths m2).\n        apply SubList_trans with (l2:= app (getDefs m2) (getCalls m2)); auto.\n        apply SubList_app_3; [apply spDom_defs|apply spDom_calls].\n  Qed.\n\nEnd TwoModules1.\n\nSection DuplicateTwoModules1.\n  Variables (m1 m2: nat -> Modules).\n  Hypotheses (Hsp1: forall iv, Specializable (m1 iv))\n             (Hsp2: forall iv, Specializable (m2 iv))\n             (Hequiv1: forall iv, ModEquiv type typeUT (m1 iv))\n             (Hequiv2: forall iv, ModEquiv type typeUT (m2 iv))\n             (Hvr1: forall iv, ValidRegsModules type (m1 iv))\n             (Hvr2: forall iv, ValidRegsModules type (m2 iv))\n             (Hexts: forall iv1 iv2, SubList (getExtMeths (m1 iv1)) (getExtMeths (m2 iv2))).\n\n  Lemma duplicate_defCallSub:\n    forall n,\n      (forall i, DefCallSub (m1 i) (m2 i)) ->\n      DefCallSub (duplicate m1 n) (duplicate m2 n).\n  Proof.\n    induction n; simpl; intros.\n    - apply specializeMod_defCallSub; auto.\n    - apply DefCallSub_modular.\n      + apply specializeMod_defCallSub; auto.\n      + apply IHn; auto.\n  Qed.\n\n  Lemma duplicate_traceRefines:\n    forall n,\n      (forall i, traceRefines (liftToMap1 (@idElementwise _)) (m1 i) (m2 i)) ->\n      traceRefines (liftToMap1 (@idElementwise _))\n                   (duplicate m1 n)\n                   (duplicate m2 n).\n  Proof.\n    induction n; simpl; intros.\n    - apply specialized_2 with (i:= O); auto.\n      specialize (H 0).\n      eapply traceRefines_label_map; eauto using H.\n      clear - Hsp1 Hsp2 Hexts; unfold EquivalentLabelMap; intros.\n      rewrite idElementwiseId; unfold id; simpl.\n      unfold liftPRename; simpl.\n      apply specializer_two_comm; auto.\n\n    - apply traceRefines_modular_noninteracting; auto.\n      + apply specializeMod_ModEquiv; auto.\n      + apply specializeMod_ModEquiv; auto.\n      + apply duplicate_ModEquiv; auto.\n      + apply duplicate_ModEquiv; auto.\n      + apply duplicate_specializeMod_disj_regs; auto.\n      + apply duplicate_specializeMod_disj_regs; auto.\n      + pose proof (duplicate_validRegsModules m1 (S n) Hvr1); auto.\n      + pose proof (duplicate_validRegsModules m2 (S n) Hvr2); auto.\n      + apply duplicate_specializeMod_disj_defs; auto.\n      + eapply DisjList_comm, DisjList_SubList.\n        * apply getIntCalls_getCalls.\n        * apply DisjList_comm, duplicate_specializeMod_disj_calls; auto.\n      + eapply DisjList_SubList.\n        * apply getIntCalls_getCalls.\n        * apply duplicate_specializeMod_disj_calls; auto.\n      + apply duplicate_specializeMod_disj_defs; auto.\n      + eapply DisjList_comm, DisjList_SubList.\n        * apply getIntCalls_getCalls.\n        * apply DisjList_comm, duplicate_specializeMod_disj_calls; auto.\n      + eapply DisjList_SubList.\n        * apply getIntCalls_getCalls.\n        * apply duplicate_specializeMod_disj_calls; auto.\n      + apply duplicate_noninteracting; auto.\n      + apply duplicate_noninteracting; auto.\n      + apply specialized_2 with (i:= S n); auto.\n        specialize (H (S n)).\n        eapply traceRefines_label_map; eauto using H.\n        clear - Hsp1 Hsp2 Hexts; unfold EquivalentLabelMap; intros.\n        rewrite idElementwiseId; unfold id; simpl.\n        unfold liftPRename; simpl.\n        apply specializer_two_comm; auto.\n  Qed.\n\nEnd DuplicateTwoModules1.\n\nSection TwoModules2.\n  Variables (m1 m2: Modules).\n  Hypotheses (Hsp1: Specializable m1)\n             (Hsp2: Specializable m2)\n             (Hequiv1: ModEquiv type typeUT m1)\n             (Hequiv2: ModEquiv type typeUT m2)\n             (Hvr1: ValidRegsModules type m1)\n             (Hvr2: ValidRegsModules type m2).\n\n  Variable (ds: string). (* a single label to drop *)\n\n  Hypothesis (Hexts: SubList (filter (fun s => negb (string_eq s ds)) (getExtMeths m1))\n                             (getExtMeths m2)).\n\n  Lemma specializeMod_traceRefines_drop:\n    forall i,\n      (m1 <<=[dropP ds] m2) ->\n      (specializeMod m1 i <<=[dropI ds i] specializeMod m2 i).\n  Proof.\n    intros.\n    apply specialized_2; auto.\n    apply traceRefines_label_map with (p:= liftToMap1 (dropP ds)); auto.\n\n    clear -Hsp1 Hsp2 Hexts.\n    unfold EquivalentLabelMap; intros.\n\n    unfold liftPRename.\n\n    assert (renameMap (specializer m2 i) ((liftToMap1 (dropP ds)) m) =\n            liftToMap1 (dropI ds i) (renameMap (specializer m1 i) m)).\n    { rewrite specializer_map with (m:= m1); auto;\n        [|eapply M.KeysSubset_SubList; eauto; apply spDom_getExtMeths].\n      rewrite specializer_map with (m:= m2); auto;\n        [|apply M.KeysSubset_SubList with (d1:= getExtMeths m2); [|apply spDom_getExtMeths];\n          eapply M.KeysSubset_SubList; eauto;\n          apply dropP_KeysSubset; auto].\n\n      clear; M.ext y.\n      rewrite liftToMap1_find.\n      remember (M.find y (renameMap (spf i) m)) as yiv; destruct yiv.\n      - apply eq_sym, renameFind2' in Heqyiv; [|apply spf_onto].\n        dest; subst; rewrite <-renameMapFind; [|apply spf_onto].\n        rewrite liftToMap1_find, H0.\n        unfold dropP, dropI.\n        remember (string_eq x ds) as xds; destruct xds.\n        + apply string_eq_dec_eq in Heqxds; subst.\n          rewrite string_eq_true; reflexivity.\n        + apply string_eq_dec_neq in Heqxds.\n          remember (string_eq (spf i x) (ds __ i)) as xdsi; destruct xdsi; auto.\n          apply string_eq_dec_eq, spf_onto in Heqxdsi.\n          elim Heqxds; auto.\n      - remember (M.find y (renameMap (spf i) (liftToMap1 (dropP ds) m))) as ypv;\n          destruct ypv; auto.\n        exfalso; apply eq_sym, renameFind2' in Heqypv; [|apply spf_onto].\n        dest; subst.\n        rewrite <-renameMapFind in Heqyiv; [|apply spf_onto].\n        rewrite liftToMap1_find in H0.\n        rewrite <-Heqyiv in H0; inv H0.\n    }\n\n    rewrite <-H0.\n    rewrite <-specializer_two_comm with (m1:= m2) (m2:= m2) (i:= i); auto.\n    - apply SubList_refl.\n    - eapply M.KeysSubset_SubList; eauto.\n      apply dropP_KeysSubset; auto.\n  Qed.\n\n  Lemma equivalentLabelMapElem_dropI_dropN:\n    forall n t (Ht: t > n),\n      EquivalentLabelMapElem (dropI ds t) (compLabelMaps (dropI ds t) (dropN ds n))\n                             (getExtMeths (specializeMod m1 t)).\n  Proof.\n    unfold EquivalentLabelMapElem; intros.\n    induction n.\n    - simpl; unfold compLabelMaps, dropI.\n      destruct (string_eq _ (ds __ t)).\n      + destruct (string_eq _ (ds __ 0)); auto.\n      + remember (string_eq _ _) as sv; destruct sv; auto.\n        exfalso; apply string_eq_dec_eq in Heqsv; subst.\n        apply spDom_getExtMeths in H.\n        apply specializeMod_dom_indexed in H; auto; dest.\n        apply withIndex_index_eq in H; dest; lia.\n    - simpl; assert (t > n) by lia; specialize (IHn H0); clear H0.\n      rewrite IHn; clear IHn.\n      unfold dropI, compLabelMaps.\n      remember (dropN ds n s v) as nv; destruct nv; auto.\n      destruct (string_eq s (ds __ t)).\n      + destruct (string_eq _ _); auto.\n      + remember (string_eq _ _) as sn; destruct sn; auto.\n        exfalso; apply string_eq_dec_eq in Heqsn; subst.\n        apply spDom_getExtMeths in H.\n        apply specializeMod_dom_indexed in H; auto; dest.\n        apply withIndex_index_eq in H; dest; lia.\n  Qed.\n\nEnd TwoModules2.\n\nSection DuplicateTwoModules2.\n  Variables (m1 m2: nat -> Modules).\n  Hypotheses (Hsp1: forall iv, Specializable (m1 iv))\n             (Hsp2: forall iv, Specializable (m2 iv))\n             (Hequiv1: forall iv, ModEquiv type typeUT (m1 iv))\n             (Hequiv2: forall iv, ModEquiv type typeUT (m2 iv))\n             (Hvr1: forall iv, ValidRegsModules type (m1 iv))\n             (Hvr2: forall iv, ValidRegsModules type (m2 iv)).\n\n  Variable (ds: string). (* a single label to drop *)\n\n  Hypothesis (Hexts: forall iv1 iv2,\n                 SubList (filter (fun s => negb (string_eq s ds))\n                                 (getExtMeths (m1 iv1)))\n                         (getExtMeths (m2 iv2))).\n  \n  Lemma equivalentLabelMapElem_dropN_dropI:\n    forall n u (Ht: u > n),\n      EquivalentLabelMapElem (dropN ds n) (compLabelMaps (dropI ds u) (dropN ds n))\n                             (getExtMeths (duplicate m1 n)).\n  Proof.\n    induction n; unfold EquivalentLabelMapElem; intros.\n    - simpl; unfold compLabelMaps, dropI.\n      destruct (string_eq _ (ds __ 0)); auto.\n      remember (string_eq _ _) as st; destruct st; auto.\n      apply string_eq_dec_eq in Heqst; subst.\n      simpl in H.\n      apply spDom_getExtMeths in H.\n      apply specializeMod_dom_indexed in H; auto; dest.\n      apply withIndex_index_eq in H; dest; lia.\n    - simpl; assert (u > n) by lia; specialize (IHn _ H0); clear H0.\n      simpl in H.\n      apply getExtMeths_in in H; destruct H.\n      + clear IHn.\n        unfold dropI, compLabelMaps.\n        destruct (dropN ds n s v); auto.\n        destruct (string_eq _ (ds __ (S n))); auto.\n        remember (string_eq _ _) as st; destruct st; auto.\n        exfalso; apply string_eq_dec_eq in Heqst; subst.\n        apply spDom_getExtMeths in H.\n        apply specializeMod_dom_indexed in H; auto; dest.\n        apply withIndex_index_eq in H; dest; lia.\n      + unfold compLabelMaps.\n        rewrite IHn; clear IHn; auto.\n        unfold compLabelMaps.\n        destruct (dropN ds n s v); auto.\n        destruct (dropI ds u s s0); auto.\n        destruct (dropI ds (S n) s s1); auto.\n        unfold dropI; remember (string_eq _ _) as st; destruct st; auto.\n        exfalso; apply string_eq_dec_eq in Heqst; subst.\n        apply spDom_getExtMeths in H.\n        apply duplicate_dom_indexed in H; auto; dest.\n        apply withIndex_index_eq in H; dest; lia.\n  Qed.\n\n  Lemma duplicate_traceRefines_drop:\n    forall n,\n      (forall i, (m1 i) <<=[dropP ds] (m2 i)) ->\n      (duplicate m1 n <<=[dropN ds n] duplicate m2 n).\n  Proof.\n    induction n; simpl; intros.\n    - apply specializeMod_traceRefines_drop; auto.\n    - apply traceRefines_modular_noninteracting_p; auto.\n      + apply specializeMod_ModEquiv; auto.\n      + apply specializeMod_ModEquiv; auto.\n      + apply duplicate_ModEquiv; auto.\n      + apply duplicate_ModEquiv; auto.\n      + apply duplicate_specializeMod_disj_regs; auto.\n      + apply duplicate_specializeMod_disj_regs; auto.\n      + pose proof (duplicate_validRegsModules m1 (S n) Hvr1); auto.\n      + pose proof (duplicate_validRegsModules m2 (S n) Hvr2); auto.\n      + apply duplicate_specializeMod_disj_defs; auto.\n      + eapply DisjList_comm, DisjList_SubList.\n        * apply getIntCalls_getCalls.\n        * apply DisjList_comm, duplicate_specializeMod_disj_calls; auto.\n      + eapply DisjList_SubList.\n        * apply getIntCalls_getCalls.\n        * apply duplicate_specializeMod_disj_calls; auto.\n      + apply duplicate_specializeMod_disj_defs; auto.\n      + eapply DisjList_comm, DisjList_SubList.\n        * apply getIntCalls_getCalls.\n        * apply DisjList_comm, duplicate_specializeMod_disj_calls; auto.\n      + eapply DisjList_SubList.\n        * apply getIntCalls_getCalls.\n        * apply duplicate_specializeMod_disj_calls; auto.\n      + split.\n        * apply equivalentLabelMapElem_dropI_dropN; auto; lia.\n        * apply equivalentLabelMapElem_dropN_dropI; auto; lia.\n      + apply duplicate_noninteracting; auto.\n      + apply duplicate_noninteracting; auto.\n      + apply specializeMod_traceRefines_drop; auto.\n  Qed.\n\nEnd DuplicateTwoModules2.\n\nSection DuplicateTwoModules3.\n  Variables (m1 m2: nat -> Modules).\n  Hypotheses (Hequiv1: forall iv ty, ModEquiv ty typeUT (m1 iv))\n             (Hequiv2: forall iv ty, ModEquiv ty typeUT (m2 iv))\n             (Hvr1: forall iv ty, ValidRegsModules ty (m1 iv))\n             (Hvr2: forall iv ty, ValidRegsModules ty (m2 iv))\n             (Hsp1: forall iv, Specializable (m1 iv))\n             (Hsp2: forall iv, Specializable (m2 iv)).\n\n  Lemma duplicate_regs_ConcatMod_1:\n    forall n,\n      SubList (getRegInits (duplicate (fun i => (m1 i) ++ (m2 i))%kami n))\n              (getRegInits (duplicate m1 n ++ duplicate m2 n)%kami).\n  Proof.\n    Opaque specializeMod.\n    induction n; intros.\n    - unfold duplicate.\n      rewrite specializeMod_concatMod; auto.\n      apply SubList_refl.\n    - simpl in *; apply SubList_app_3.\n      + rewrite specializeMod_concatMod; auto.\n        simpl; apply SubList_app_3.\n        * do 2 apply SubList_app_1; apply SubList_refl.\n        * apply SubList_app_2, SubList_app_1, SubList_refl.\n      + unfold SubList in *; intros.\n        specialize (IHn e H).\n        apply in_app_or in IHn; destruct IHn.\n        * apply in_or_app; left; apply in_or_app; auto.\n        * apply in_or_app; right; apply in_or_app; auto.\n          Transparent specializeMod.\n  Qed.\n\n  Lemma duplicate_regs_ConcatMod_2:\n    forall n,\n      SubList (getRegInits (duplicate m1 n ++ duplicate m2 n)%kami)\n              (getRegInits (duplicate (fun i => m1 i ++ m2 i)%kami n)).\n  Proof.\n    Opaque specializeMod.\n    induction n; intros.\n    - unfold duplicate.\n      rewrite specializeMod_concatMod; auto.\n      apply SubList_refl.\n    - simpl in *; apply SubList_app_3.\n      + rewrite specializeMod_concatMod; auto.\n        simpl; apply SubList_app_3.\n        * do 2 apply SubList_app_1; apply SubList_refl.\n        * apply SubList_app_2; apply SubList_app_4 in IHn; auto.\n      + rewrite specializeMod_concatMod; auto.\n        simpl; apply SubList_app_3.\n        * apply SubList_app_1, SubList_app_2, SubList_refl.\n        * apply SubList_app_2; apply SubList_app_5 in IHn; auto.\n          Transparent specializeMod.\n  Qed.\n\n  Corollary duplicate_regs_ConcatMod:\n    forall n,\n      EquivList (getRegInits (duplicate m1 n ++ duplicate m2 n)%kami)\n                (getRegInits (duplicate (fun i => m1 i ++ m2 i)%kami n)).\n  Proof.\n    intros; split.\n    - apply duplicate_regs_ConcatMod_2.\n    - apply duplicate_regs_ConcatMod_1.\n  Qed.\n\n  Lemma duplicate_regs_NoDup_2:\n    (forall i, NoDup (namesOf (getRegInits (m1 i ++ m2 i)%kami))) ->\n    forall n,\n      NoDup (namesOf (getRegInits (duplicate m1 n ++ duplicate m2 n)%kami)).\n  Proof.\n    Opaque specializeMod.\n    intros.\n    pose proof H; apply duplicate_regs_NoDup with (n:= n) in H0.\n    induction n; simpl; intros.\n    - simpl in *; rewrite specializeMod_concatMod in H0; auto.\n    - assert (NoDup (namesOf (getRegInits (duplicate (fun i => m1 i ++ m2 i)%kami n)))).\n      { apply duplicate_regs_NoDup; auto.\n        intros; apply specializable_concatMod; auto.\n      }\n      specialize (IHn H1); clear H1.\n      unfold namesOf; repeat rewrite map_app.\n      rewrite app_assoc.\n      rewrite <-app_assoc with (l:= map (@attrName _)\n                                        (getRegInits (specializeMod (m1 (S n)) (S n)))).\n      rewrite <-app_assoc with (l:= map (@attrName _)\n                                        (getRegInits (specializeMod (m1 (S n)) (S n)))).\n      apply NoDup_app_comm_ext.\n      rewrite app_assoc.\n      rewrite app_assoc.\n      rewrite <-app_assoc with (n:= map (@attrName _) (getRegInits (duplicate m2 n))).\n      apply NoDup_DisjList.\n      + specialize (H (S n)); apply specializeMod_regs_NoDup with (i:= S n) in H;\n          [|apply specializable_concatMod; auto].\n        rewrite specializeMod_concatMod in H; auto.\n        rewrite <-map_app; auto.\n      + rewrite <-map_app; auto.\n      + do 2 rewrite <-map_app.\n        pose proof (duplicate_regs_ConcatMod_2 n).\n        apply SubList_map with (f:= @attrName _) in H1.\n        eapply DisjList_comm, DisjList_SubList; eauto.\n        pose proof (specializeMod_concatMod (Hvr1 (S n)) (Hvr2 (S n))\n                                            (Hequiv1 (S n)) (Hequiv2 (S n)) (S n)\n                                            (Hsp1 (S n)) (Hsp2 (S n))).\n        change (getRegInits (specializeMod (m1 (S n)) (S n)) ++\n                            getRegInits (specializeMod (m2 (S n)) (S n)))\n        with (getRegInits (specializeMod (m1 (S n)) (S n) ++\n                                         (specializeMod (m2 (S n)) (S n)))%kami).\n        rewrite <-H2.\n        apply DisjList_comm.\n        change (m1 (S n) ++ m2 (S n))%kami with ((fun i => (m1 i ++ m2 i)%kami) (S n)).\n        apply duplicate_specializeMod_disj_regs; auto.\n        intros; apply specializable_concatMod; auto.\n    - intros; apply specializable_concatMod; auto.\n  Qed.\n\n  Lemma duplicate_rules_ConcatMod_1:\n    forall n,\n      SubList (getRules (duplicate (fun i => m1 i ++ m2 i)%kami n))\n              (getRules (duplicate m1 n ++ duplicate m2 n)%kami).\n  Proof.\n    Opaque specializeMod.\n    induction n; intros.\n    - unfold duplicate.\n      rewrite specializeMod_concatMod; auto.\n      apply SubList_refl.\n    - simpl in *; apply SubList_app_3.\n      + rewrite specializeMod_concatMod; auto.\n        simpl; apply SubList_app_3.\n        * do 2 apply SubList_app_1; apply SubList_refl.\n        * apply SubList_app_2, SubList_app_1, SubList_refl.\n      + unfold SubList in *; intros.\n        specialize (IHn e H).\n        apply in_app_or in IHn; destruct IHn.\n        * apply in_or_app; left; apply in_or_app; auto.\n        * apply in_or_app; right; apply in_or_app; auto.\n          Transparent specializeMod.\n  Qed.\n\n  Lemma duplicate_rules_ConcatMod_2:\n    forall n,\n      SubList (getRules (duplicate m1 n ++ duplicate m2 n)%kami)\n              (getRules (duplicate (fun i => m1 i ++ m2 i)%kami n)).\n  Proof.\n    Opaque specializeMod.\n    induction n; intros.\n    - unfold duplicate.\n      rewrite specializeMod_concatMod; auto.\n      apply SubList_refl.\n    - simpl in *; apply SubList_app_3.\n      + rewrite specializeMod_concatMod; auto.\n        simpl; apply SubList_app_3.\n        * do 2 apply SubList_app_1; apply SubList_refl.\n        * apply SubList_app_2; apply SubList_app_4 in IHn; auto.\n      + rewrite specializeMod_concatMod; auto.\n        simpl; apply SubList_app_3.\n        * apply SubList_app_1, SubList_app_2, SubList_refl.\n        * apply SubList_app_2; apply SubList_app_5 in IHn; auto.\n          Transparent specializeMod.\n  Qed.\n\n  Corollary duplicate_rules_ConcatMod:\n    forall n,\n      EquivList (getRules (duplicate m1 n ++ duplicate m2 n)%kami)\n                (getRules (duplicate (fun i => m1 i ++ m2 i)%kami n)).\n  Proof.\n    intros; split.\n    - apply duplicate_rules_ConcatMod_2.\n    - apply duplicate_rules_ConcatMod_1.\n  Qed.\n\n  Lemma duplicate_defs_ConcatMod_1:\n    forall n,\n      SubList (getDefsBodies (duplicate (fun i => m1 i ++ m2 i)%kami n))\n              (getDefsBodies (duplicate m1 n ++ duplicate m2 n)%kami).\n  Proof.\n    Opaque specializeMod.\n    induction n; intros.\n    - unfold duplicate.\n      rewrite specializeMod_concatMod; auto.\n      apply SubList_refl.\n    - simpl in *; apply SubList_app_3.\n      + rewrite specializeMod_concatMod; auto.\n        simpl; apply SubList_app_3.\n        * do 2 apply SubList_app_1; apply SubList_refl.\n        * apply SubList_app_2, SubList_app_1, SubList_refl.\n      + unfold SubList in *; intros.\n        specialize (IHn e H).\n        apply in_app_or in IHn; destruct IHn.\n        * apply in_or_app; left; apply in_or_app; auto.\n        * apply in_or_app; right; apply in_or_app; auto.\n          Transparent specializeMod.\n  Qed.\n\n  Lemma duplicate_defs_ConcatMod_2:\n    forall n,\n      SubList (getDefsBodies (duplicate m1 n ++ duplicate m2 n)%kami)\n              (getDefsBodies (duplicate (fun i => m1 i ++ m2 i)%kami n)).\n  Proof.\n    Opaque specializeMod.\n    induction n; intros.\n    - unfold duplicate.\n      rewrite specializeMod_concatMod; auto.\n      apply SubList_refl.\n    - simpl in *; apply SubList_app_3.\n      + rewrite specializeMod_concatMod; auto.\n        simpl; apply SubList_app_3.\n        * do 2 apply SubList_app_1; apply SubList_refl.\n        * apply SubList_app_2; apply SubList_app_4 in IHn; auto.\n      + rewrite specializeMod_concatMod; auto.\n        simpl; apply SubList_app_3.\n        * apply SubList_app_1, SubList_app_2, SubList_refl.\n        * apply SubList_app_2; apply SubList_app_5 in IHn; auto.\n          Transparent specializeMod.\n  Qed.\n\n  Lemma duplicate_defs_ConcatMod:\n    forall n,\n      EquivList (getDefsBodies (duplicate m1 n ++ duplicate m2 n)%kami)\n                (getDefsBodies (duplicate (fun i => m1 i ++ m2 i)%kami n)).\n  Proof.\n    intros; split.\n    - apply duplicate_defs_ConcatMod_2.\n    - apply duplicate_defs_ConcatMod_1.\n  Qed.\n\nEnd DuplicateTwoModules3.\n\nSection DuplicateTwoModules4.\n  Variables (m1 m2: nat -> Modules).\n  Hypotheses (Hsp1: forall iv, Specializable (m1 iv))\n             (Hsp2: forall iv, Specializable (m2 iv))\n             (Hequiv1: forall iv ty, ModEquiv ty typeUT (m1 iv))\n             (Hequiv2: forall iv ty, ModEquiv ty typeUT (m2 iv))\n             (Hvr1: forall iv ty, ValidRegsModules ty (m1 iv))\n             (Hvr2: forall iv ty, ValidRegsModules ty (m2 iv))\n             (HnoDup: forall iv, NoDup (namesOf (getRegInits (m1 iv ++ m2 iv)%kami))).\n\n  Lemma duplicate_concatMod_comm_1:\n    forall n,\n      duplicate (fun i => m1 i ++ m2 i)%kami n <<== ((duplicate m1 n) ++ (duplicate m2 n))%kami.\n  Proof.\n    intros; rewrite idElementwiseId.\n    apply traceRefines_same_module_structure.\n    - apply duplicate_regs_NoDup; auto.\n      intros; apply specializable_concatMod; auto.\n    - apply duplicate_regs_NoDup_2; auto.\n    - split.\n      + apply duplicate_regs_ConcatMod_1; auto.\n      + apply duplicate_regs_ConcatMod_2; auto.\n    - split.\n      + apply duplicate_rules_ConcatMod_1; auto.\n      + apply duplicate_rules_ConcatMod_2; auto.\n    - split.\n      + apply duplicate_defs_ConcatMod_1; auto.\n      + apply duplicate_defs_ConcatMod_2; auto.\n  Qed.\n\n  Lemma duplicate_concatMod_comm_2:\n    forall n,\n      ((duplicate m1 n) ++ (duplicate m2 n))%kami <<== duplicate (fun i => m1 i ++ m2 i)%kami n.\n  Proof.\n    intros; rewrite idElementwiseId.\n    apply traceRefines_same_module_structure.\n    - apply duplicate_regs_NoDup_2; auto.\n    - apply duplicate_regs_NoDup; auto.\n      intros; apply specializable_concatMod; auto.\n    - split.\n      + apply duplicate_regs_ConcatMod_2; auto.\n      + apply duplicate_regs_ConcatMod_1; auto.\n    - split.\n      + apply duplicate_rules_ConcatMod_2; auto.\n      + apply duplicate_rules_ConcatMod_1; auto.\n    - split.\n      + apply duplicate_defs_ConcatMod_2; auto.\n      + apply duplicate_defs_ConcatMod_1; auto.\n  Qed.\n\nEnd DuplicateTwoModules4.\n\n#[global] Hint Unfold specializeMod duplicate: ModuleDefs.\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/Duplicate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.2576614487850937}}
{"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.\n\nRequire Import PromiseConsistent.\nRequire Import PFConsistent.\nRequire Import MemoryProps.\nRequire Import Single.\n\nSet Implicit Arguments.\n\n\n\nModule PF.\nSection LOCALPF.\n  Variable L: Loc.t -> bool.\n\n  Definition pf_event (e: ThreadEvent.t): Prop :=\n    forall loc from to val released kind\n           (PROMISE: e = ThreadEvent.promise loc from to (Message.concrete val released) kind)\n           (LOC: L loc),\n      False.\n\n  Definition pf_consistent lang (th: Thread.t lang): Prop :=\n    exists tr_cert,\n      (<<CONSISTENT: Trace.consistent th tr_cert>>) /\\\n      (<<PFCERT: List.Forall (compose pf_event snd) tr_cert>>).\n\n  Definition pf_promises (prom: Memory.t): Prop :=\n    forall loc to from msg\n           (LOC: L loc)\n           (GET: Memory.get loc to prom = Some (from, msg)),\n      msg = Message.reserve.\n\n  Definition pf_configuration (c: Configuration.t) :=\n    forall tid lang st lc\n           (TID: IdentMap.find tid (Configuration.threads c) = Some (existT _ lang st, lc)),\n      pf_promises (Local.promises lc).\n\n  Lemma pf_consistent_consistent lang (th: Thread.t lang)\n        (CONSISTENT: pf_consistent th)\n    :\n      Thread.consistent th.\n  Proof.\n    ii. unfold pf_consistent in *. des.\n    exploit CONSISTENT0; eauto. i. des.\n    { eapply Trace.silent_steps_tau_steps in STEPS; eauto.\n      left. unfold Thread.steps_failure. esplits; eauto. }\n    { eapply Trace.silent_steps_tau_steps in STEPS; eauto. }\n  Qed.\n\n  Lemma pf_promises_promise prom0 mem0 loc from to msg prom1 mem1 kind\n        (PROMISE: Memory.promise prom0 mem0 loc from to msg prom1 mem1 kind)\n        (PF: L loc -> msg = Message.reserve)\n        (PROMISES: pf_promises prom0)\n    :\n      pf_promises prom1.\n  Proof.\n    inv PROMISE.\n    - ii. erewrite Memory.add_o in GET; eauto. des_ifs.\n      + ss. des; clarify. auto.\n      + eapply PROMISES; eauto.\n    - ii. erewrite Memory.split_o in GET; eauto. des_ifs.\n      + ss. des; clarify. auto.\n      + ss. des; clarify. exploit PF; ss.\n      + eapply PROMISES; eauto.\n    - ii. erewrite Memory.lower_o in GET; eauto. des_ifs.\n      + ss. des; clarify. auto.\n      + eapply PROMISES; eauto.\n    - ii. erewrite Memory.remove_o in GET; eauto. des_ifs.\n      eapply PROMISES; eauto.\n  Qed.\n\n  Lemma pf_promises_write prom0 mem0 loc from to val released prom1 mem1 kind\n        (WRITE: Memory.write prom0 mem0 loc from to val released prom1 mem1 kind)\n        (PROMISES: pf_promises prom0)\n    :\n      pf_promises prom1.\n  Proof.\n    inv WRITE. ii. erewrite Memory.remove_o in GET; eauto. des_ifs.\n    inv PROMISE.\n    - ii. erewrite Memory.add_o in GET; eauto. des_ifs.\n      + ss. des; clarify.\n      + eapply PROMISES; eauto.\n    - ii. erewrite Memory.split_o in GET; eauto. des_ifs.\n      + ss. des; clarify.\n      + ss. des; clarify.\n        eapply Memory.split_get0 in PROMISES0. des.\n        eapply PROMISES in GET0; eauto.\n      + eapply PROMISES; eauto.\n    - ii. erewrite Memory.lower_o in GET; eauto. des_ifs.\n      + ss. des; clarify.\n      + eapply PROMISES; eauto.\n    - ii. erewrite Memory.remove_o in GET; eauto. des_ifs.\n  Qed.\n\n  Lemma pf_promises_step lang (th0 th1: Thread.t lang) pf e\n        (STEP: Thread.step pf e th0 th1)\n        (PF: pf_event e)\n        (PROMISES: pf_promises (Local.promises (Thread.local th0)))\n    :\n      pf_promises (Local.promises (Thread.local th1)).\n  Proof.\n    inv STEP.\n    - inv STEP0; ss. inv LOCAL.\n      eapply pf_promises_promise; eauto. i.\n      destruct msg; ss. exfalso. eapply PF; eauto.\n    - inv STEP0. inv LOCAL; ss.\n      + inv LOCAL0; ss.\n      + inv LOCAL0; ss.\n        eapply pf_promises_write; eauto.\n      + inv LOCAL1. inv LOCAL2; ss.\n        eapply pf_promises_write; eauto.\n      + inv LOCAL0; ss.\n      + inv LOCAL0; ss.\n  Qed.\n\n  Lemma pf_promises_opt_step lang (th0 th1: Thread.t lang) e\n        (STEP: Thread.opt_step e th0 th1)\n        (PF: pf_event e)\n        (PROMISES: pf_promises (Local.promises (Thread.local th0)))\n    :\n      pf_promises (Local.promises (Thread.local th1)).\n  Proof.\n    inv STEP; auto.\n    eapply pf_promises_step; eauto.\n  Qed.\n\n  Lemma pf_promises_reserve_steps lang (th0 th1: Thread.t lang)\n        (STEPS: rtc (@Thread.reserve_step _) th0 th1)\n        (PROMISES: pf_promises (Local.promises (Thread.local th0)))\n    :\n      pf_promises (Local.promises (Thread.local th1)).\n  Proof.\n    ginduction STEPS; eauto. i. eapply IHSTEPS.\n    inv H. eapply pf_promises_step; eauto. ii. clarify.\n  Qed.\n\n  Lemma pf_promises_cancel_steps lang (th0 th1: Thread.t lang)\n        (STEPS: rtc (@Thread.cancel_step _) th0 th1)\n        (PROMISES: pf_promises (Local.promises (Thread.local th0)))\n    :\n      pf_promises (Local.promises (Thread.local th1)).\n  Proof.\n    ginduction STEPS; eauto. i. eapply IHSTEPS.\n    inv H. eapply pf_promises_step; eauto. ii. clarify.\n  Qed.\n\n  Lemma configuration_init_pf syn: pf_configuration (Configuration.init syn).\n  Proof.\n    ii. ss. unfold Threads.init in *.\n    erewrite IdentMap.Facts.map_o in TID.\n    unfold option_map in *. des_ifs. dep_clarify.\n    erewrite Memory.bot_get in GET. ss.\n  Qed.\n\n  Lemma pf_promises_step_event lang (th0 th1: Thread.t lang) e\n        (STEP: Thread.step true e th0 th1)\n        (PROMISES: pf_promises (Local.promises (Thread.local th0)))\n    :\n      pf_event e.\n  Proof.\n    ii. subst. inv STEP; inv STEP0; inv LOCAL. ss.\n    inv PROMISE; ss. des. subst.\n    eapply Memory.lower_get0 in PROMISES0. des.\n    eapply PROMISES in GET; eauto. clarify.\n  Qed.\n\n  Lemma pf_promises_steps_trace lang (th0 th1: Thread.t lang)\n        (STEPS: rtc (tau (Thread.step true)) th0 th1)\n        (PROMISES: pf_promises (Local.promises (Thread.local th0)))\n    :\n      exists tr,\n        (<<STEPS: Trace.steps tr th0 th1>>) /\\\n        (<<PF: List.Forall (compose pf_event snd) tr>>) /\\\n        (<<SILENT: List.Forall (fun lce => ThreadEvent.get_machine_event (snd lce) = MachineEvent.silent) tr>>).\n  Proof.\n    ginduction STEPS; eauto; i.\n    { exists []. splits; eauto. }\n    i. inv H. hexploit pf_promises_step_event; eauto. intros PF.\n    hexploit pf_promises_step; eauto. intros PROMISES0.\n    exploit IHSTEPS; eauto. i. des. esplits; eauto.\n  Qed.\n\n  Lemma pf_promises_trace_steps lang (th0 th1: Thread.t lang) tr\n        (STEPS: Trace.steps tr th0 th1)\n        (PF: List.Forall (compose pf_event snd) tr)\n        (PROMISES: pf_promises (Local.promises (Thread.local th0)))\n    :\n      pf_promises (Local.promises (Thread.local th1)).\n  Proof.\n    ginduction STEPS; eauto. i. subst.\n    inv PF. eapply IHSTEPS; eauto.\n    eapply pf_promises_step; eauto.\n  Qed.\n\n  Lemma pf_promises_consistent_consistent lang (th: Thread.t lang)\n        (CONSISTENT: Thread.consistent th)\n        (WF: Local.wf (Thread.local th) (Thread.memory th))\n        (MEM: Memory.closed (Thread.memory th))\n        (PROMISES: pf_promises (Local.promises (Thread.local th)))\n    :\n      pf_consistent th.\n  Proof.\n    eapply consistent_pf_consistent in CONSISTENT; eauto.\n    exploit Memory.cap_exists; eauto. i. des.\n    exploit Memory.max_concrete_timemap_exists.\n    { eapply Memory.cap_closed; eauto. } i. des.\n    exploit CONSISTENT; eauto. i. des.\n    { eapply pf_promises_steps_trace in STEPS; eauto. des.\n      exists tr. splits; auto. ii.\n      exploit (@Memory.cap_inj (Thread.memory th) mem2 mem1); eauto. i. subst.\n      exploit (@Memory.max_concrete_timemap_inj mem1 tm sc1); eauto. i. subst.\n      esplits; eauto.\n    }\n    { eapply pf_promises_steps_trace in STEPS; eauto. des.\n      exists tr. splits; auto. ii.\n      exploit (@Memory.cap_inj (Thread.memory th) mem2 mem1); eauto. i. subst.\n      exploit (@Memory.max_concrete_timemap_inj mem1 tm sc1); eauto. i. subst.\n      esplits; eauto.\n    }\n  Qed.\nEnd LOCALPF.\nEnd PF.\n\n(** L-PF machine **)\nModule PFConfiguration.\nSection LOCALPF.\n  Variable L: Loc.t -> bool.\n\n  Inductive step:\n    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: Thread.opt_step e e2 e3)\n      (RESERVES: rtc (@Thread.reserve_step _) e3 (Thread.mk _ st4 lc4 sc4 memory4))\n      (CONSISTENT: e <> ThreadEvent.failure -> PF.pf_consistent L (Thread.mk _ st4 lc4 sc4 memory4))\n      (PF: PF.pf_event L e)\n    :\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 machine_step: forall (e:MachineEvent.t) (tid:Ident.t) (c1 c2:Configuration.t), Prop :=\n  | machine_step_intro\n      e tid c1 c2\n      (STEP: step e tid c1 c2)\n    :\n      machine_step (ThreadEvent.get_machine_event e) tid c1 c2\n  .\n  Hint Constructors machine_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 opt_machine_step:\n    forall (e: MachineEvent.t) (tid: Ident.t) (c1 c2: Configuration.t), Prop :=\n  | opt_machine_step_none\n      tid c:\n      opt_machine_step MachineEvent.silent tid c c\n  | opt_machine_step_some\n      e tid c1 c2\n      (STEP: machine_step e tid c1 c2):\n      opt_machine_step e tid c1 c2\n  .\n  Hint Constructors opt_machine_step.\n\n  Definition tau_machine_step := union (machine_step MachineEvent.silent).\n\n  Inductive steps:\n    forall (es: list ThreadEvent.t) (tid: Ident.t) (c1 c2:Configuration.t), Prop :=\n  | steps_nil\n      tid c1\n    :\n      steps [] tid c1 c1\n  | steps_cons\n      ehd etl tid c1 c2 c3\n      (STEP: step ehd tid c1 c2)\n      (STEPS: steps etl tid c2 c3)\n    :\n      steps (ehd :: etl) tid c1 c3\n  .\n  Hint Constructors steps.\n\n  Lemma steps_rtc_all_step es tid c1 c2\n        (STEPS: steps es tid c1 c2)\n    :\n      rtc all_step c1 c2.\n  Proof.\n    induction STEPS; eauto.\n  Qed.\n\n  Lemma steps_split es0 es1 tid c0 c2\n        (STEPS: steps (es0 ++ es1) tid c0 c2)\n    :\n      exists c1,\n        (<<STEPS0: steps es0 tid c0 c1>>) /\\\n        (<<STEPS1: steps es1 tid c1 c2>>).\n  Proof.\n    ginduction es0; eauto. i. ss. inv STEPS.\n    exploit IHes0; eauto. i. des.\n    esplits; eauto.\n  Qed.\n\n  Lemma silent_steps_tau_machine_steps es tid c1 c2\n        (STEPS: steps es tid c1 c2)\n        (SILENT: List.Forall (fun e => ThreadEvent.get_machine_event e = MachineEvent.silent) es)\n    :\n      rtc (machine_step MachineEvent.silent tid) c1 c2.\n  Proof.\n    ginduction es; i.\n    { inv STEPS. eauto. }\n    { inv STEPS. inv SILENT. exploit IHes; eauto.\n      i. econs 2; eauto. rewrite <- H1. econs; eauto. }\n  Qed.\n\n  Lemma pf_configuration_step tid c1 c2 e\n        (STEP: step e tid c1 c2)\n        (PF: PF.pf_configuration L c1)\n    :\n      PF.pf_configuration L c2.\n  Proof.\n    inv STEP. unfold PF.pf_configuration in *. i. ss.\n    erewrite IdentMap.gsspec in TID0. des_ifs; eauto.\n    dep_clarify. eapply PF in TID.\n    eapply PF.pf_promises_cancel_steps in CANCELS; eauto.\n    eapply PF.pf_promises_opt_step in STEP0; eauto.\n    eapply PF.pf_promises_reserve_steps in RESERVES; eauto.\n  Qed.\n\n  Lemma event_configuration_step_step c1 c2 e tid\n        (STEP: SConfiguration.step e tid c1 c2)\n        (WF: Configuration.wf c1)\n        (PF: PF.pf_configuration L c1)\n        (EVENT: PF.pf_event L e)\n    :\n      step e tid c1 c2.\n  Proof.\n    inv STEP. econs; eauto. i.\n    exploit Thread.rtc_cancel_step_future; eauto; try eapply WF; eauto. ss. i. des.\n    exploit Thread.opt_step_future; eauto. ss. i. des.\n    exploit Thread.rtc_reserve_step_future; eauto; try eapply WF; eauto. ss. i. des.\n    hexploit PF.pf_promises_cancel_steps; eauto. i. ss.\n    hexploit PF.pf_promises_opt_step; eauto. i. ss.\n    hexploit PF.pf_promises_reserve_steps; eauto. i. ss.\n    eapply PF.pf_promises_consistent_consistent; eauto.\n  Qed.\n\n  Lemma reservation_only_step_step tid c1 c2\n        (STEP: SConfiguration.reservation_only_step tid c1 c2)\n        (WF: Configuration.wf c1)\n        (PF: PF.pf_configuration L c1)\n    :\n      step ThreadEvent.silent tid c1 c2.\n  Proof.\n    eapply SConfiguration.reservation_only_step_step in STEP.\n    eapply event_configuration_step_step; eauto. ss.\n  Qed.\n\n  Lemma step_event_configuration_step c1 c2 e tid\n        (STEP: step e tid c1 c2)\n        (WF: Configuration.wf c1)\n    :\n      (<<STEP: SConfiguration.step e tid c1 c2>>) /\\\n      (<<EVENT: PF.pf_event L e>>)\n  .\n  Proof.\n    inv STEP. splits; auto. econs; eauto.\n    i. eapply PF.pf_consistent_consistent; eauto.\n  Qed.\n\n  Lemma step_future\n        e tid c1 c2\n        (STEP: step e tid c1 c2)\n        (WF1: Configuration.wf c1)\n        (PF: PF.pf_configuration L 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    (<<PF: PF.pf_configuration L c2>>).\n  Proof.\n    exploit step_event_configuration_step; eauto. i. des.\n    exploit SConfiguration.step_future; eauto. i. des.\n    splits; auto. eapply pf_configuration_step; eauto.\n  Qed.\n\n  Lemma machine_step_future\n        e tid c1 c2\n        (STEP: machine_step e tid c1 c2)\n        (WF1: Configuration.wf c1)\n        (PF: PF.pf_configuration L 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    (<<PF: PF.pf_configuration L c2>>).\n  Proof.\n    inv STEP. eapply step_future; eauto.\n  Qed.\n\n  Lemma opt_machine_step_future\n        e tid c1 c2\n        (STEP: opt_machine_step e tid c1 c2)\n        (WF1: Configuration.wf c1)\n        (PF: PF.pf_configuration L 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    (<<PF: PF.pf_configuration L c2>>).\n  Proof.\n    inv STEP; eauto.\n    - splits; eauto. refl.\n    - eapply machine_step_future; eauto.\n  Qed.\n\n  Lemma all_step_future\n        c1 c2\n        (STEP: all_step c1 c2)\n        (WF1: Configuration.wf c1)\n        (PF: PF.pf_configuration L 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    (<<PF: PF.pf_configuration L c2>>).\n  Proof.\n    inv STEP. eapply step_future; eauto.\n  Qed.\n\n  Lemma tau_machine_step_future\n        c1 c2\n        (STEP: tau_machine_step c1 c2)\n        (WF1: Configuration.wf c1)\n        (PF: PF.pf_configuration L 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    (<<PF: PF.pf_configuration L c2>>).\n  Proof.\n    inv STEP. eapply machine_step_future; eauto.\n  Qed.\n\n  Lemma rtc_tau_machine_step_future\n        c1 c2\n        (STEPS: rtc tau_machine_step c1 c2)\n        (WF1: Configuration.wf c1)\n        (PF: PF.pf_configuration L 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    (<<PF: PF.pf_configuration L c2>>).\n  Proof.\n    ginduction STEPS; eauto.\n    - i. splits; eauto. refl.\n    - i. exploit tau_machine_step_future; eauto. i. des.\n      exploit IHSTEPS; eauto. i. des. esplits; eauto. etrans; eauto.\n  Qed.\n\n  Lemma rtc_all_step_future\n        c1 c2\n        (STEPS: rtc all_step c1 c2)\n        (WF1: Configuration.wf c1)\n        (PF: PF.pf_configuration L 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    (<<PF: PF.pf_configuration L c2>>).\nProof.\n    ginduction STEPS; eauto.\n    - i. splits; eauto. refl.\n    - i. exploit all_step_future; eauto. i. des.\n      exploit IHSTEPS; eauto. i. des. esplits; eauto. etrans; eauto.\n  Qed.\n\n  Lemma steps_future\n        es tid c1 c2\n        (STEPS: steps es tid c1 c2)\n        (WF1: Configuration.wf c1)\n        (PF: PF.pf_configuration L 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    (<<PF: PF.pf_configuration L c2>>).\n  Proof.\n    ginduction STEPS; eauto.\n    - i. splits; eauto. refl.\n    - i. exploit step_future; eauto. i. des.\n      exploit IHSTEPS; eauto. i. des. esplits; eauto. etrans; eauto.\n  Qed.\n\n  Inductive step_trace: forall (tr: Trace.t) (e:MachineEvent.t) (tid:Ident.t) (c1 c2:Configuration.t), Prop :=\n  | step_trace_intro\n      lang tr e tr' pf tid c1 st1 lc1 e2 st3 lc3 sc3 memory3\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: e <> ThreadEvent.failure),\n          PF.pf_consistent L (Thread.mk _ st3 lc3 sc3 memory3))\n      (PF: List.Forall (compose (PF.pf_event L) snd) tr)\n    :\n      step_trace tr (ThreadEvent.get_machine_event e) tid c1 (Configuration.mk (IdentMap.add tid (existT _ _ st3, lc3) (Configuration.threads c1)) sc3 memory3)\n  .\n\n  Lemma trace_step_step_trace c1 c2 tr e tid\n        (STEP: Trace.configuration_step tr e tid c1 c2)\n        (WF: Configuration.wf c1)\n        (PF: PF.pf_configuration L c1)\n        (TRACE: List.Forall (compose (PF.pf_event L) snd) tr)\n    :\n      step_trace tr e tid c1 c2.\n  Proof.\n    inv STEP. econs; eauto. i.\n    eapply Forall_app_inv in TRACE. des. inv FORALL2.\n    exploit Trace.steps_future; eauto; try eapply WF; eauto. ss. i. des.\n    exploit Thread.step_future; eauto. ss. i. des.\n    hexploit PF.pf_promises_trace_steps; eauto. i. ss.\n    hexploit PF.pf_promises_step; eauto. i. ss.\n    eapply PF.pf_promises_consistent_consistent; eauto.\n  Qed.\n\n  Lemma step_trace_trace_step c1 c2 tr e tid\n        (STEP: step_trace tr e tid c1 c2)\n        (WF: Configuration.wf c1)\n    :\n      (<<STEP: Trace.configuration_step tr e tid c1 c2>>) /\\\n      (<<TRACE: List.Forall (compose (PF.pf_event L) snd) tr>>).\n  Proof.\n    inv STEP. splits; auto. econs; eauto. i.\n    eapply PF.pf_consistent_consistent; eauto.\n  Qed.\n\n  Inductive opt_step_trace: forall (tr: Trace.t) (e:MachineEvent.t) (tid:Ident.t) (c1 c2:Configuration.t), Prop :=\n  | opt_step_trace_some\n      tr e tid c1 c2\n      (STEP: step_trace tr e tid c1 c2)\n    :\n      opt_step_trace tr e tid c1 c2\n  | opt_step_trace_none\n      tid c1\n    :\n      opt_step_trace [] MachineEvent.silent tid c1 c1\n  .\n\n  Lemma step_trace_step tr e tid c1 c2\n        (STEP: step_trace tr e tid c1 c2)\n    :\n      Configuration.step e tid c1 c2.\n  Proof.\n    inv STEP. destruct (classic (e0 = ThreadEvent.failure)).\n    { subst. econs 1; try apply STEP0; eauto.\n      eapply Trace.silent_steps_tau_steps; eauto. }\n    { econs 2; try apply STEP0; eauto.\n      { eapply Trace.silent_steps_tau_steps; eauto. }\n      { exploit CONSISTENT; eauto. i. unfold PF.pf_consistent in *. des.\n        eapply Trace.consistent_thread_consistent; eauto. }\n    }\n  Qed.\n\n  Inductive steps_trace:\n    forall (c0 c1: Configuration.t) (tr: Trace.t), Prop :=\n  | steps_trace_nil\n      c0\n    :\n      steps_trace c0 c0 []\n  | steps_trace_cons\n      c0 c1 c2 trs tr e tid\n      (STEPS: steps_trace c1 c2 trs)\n      (STEP: step_trace tr e tid c0 c1)\n    :\n      steps_trace c0 c2 (tr ++ trs)\n  .\n\n  Lemma step_trace_steps tr e tid c1 c3\n        (STEP: step_trace tr e tid c1 c3)\n        (WF: Configuration.wf c1)\n        (PF: PF.pf_configuration L c1)\n    :\n      ((<<STEPS: steps (List.filter ThreadEvent.is_normal_dec (List.map snd tr)) tid c1 c3>>) /\\\n       (<<NIL: List.filter ThreadEvent.is_normal_dec (List.map snd tr) <> []>>)) \\/\n      ((<<STEP: SConfiguration.reservation_only_step tid c1 c3>>) /\\\n       (<<NIL: List.filter ThreadEvent.is_normal_dec (List.map snd tr) = []>>)).\n  Proof.\n    eapply step_trace_trace_step in STEP; eauto. des.\n    eapply SConfiguration.trace_step_machine_step in STEP0; eauto. des; eauto.\n    left. splits; auto. clear e.\n    remember (List.filter (fun e => ThreadEvent.is_normal_dec e) (List.map snd tr)).\n    assert (EVENTS: List.Forall (PF.pf_event L) l).\n    { subst. clear - TRACE. induction tr; ss. inv TRACE. des_ifs; eauto. }\n    clear tr Heql NIL TRACE. ginduction STEPS; eauto.\n    i. inv EVENTS.\n    eapply event_configuration_step_step in STEP; eauto.\n    exploit step_future; eauto. i. des.\n    hexploit pf_configuration_step; eauto.\n  Qed.\n\n  Lemma step_trace_future\n        (tr: Trace.t) e tid c1 c2\n        (STEP: step_trace tr e tid c1 c2)\n        (WF1: Configuration.wf c1)\n        (PF: PF.pf_configuration L 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    (<<PF: PF.pf_configuration L c2>>).\n  Proof.\n    eapply step_trace_steps in STEP; eauto. des.\n    { eapply steps_future; eauto. }\n    { eapply reservation_only_step_step in STEP0; eauto.\n      eapply step_future; eauto. }\n  Qed.\n\n  Lemma opt_step_trace_future\n        (tr: Trace.t) e tid c1 c2\n        (STEP: opt_step_trace tr e tid c1 c2)\n        (WF1: Configuration.wf c1)\n        (PF: PF.pf_configuration L 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    (<<PF: PF.pf_configuration L c2>>).\n  Proof.\n    inv STEP.\n    { eapply step_trace_future; eauto. }\n    { splits; auto. refl. }\n  Qed.\n\n  Lemma steps_trace_future\n        c1 c2 tr\n        (STEPS: steps_trace c1 c2 tr)\n        (WF1: Configuration.wf c1)\n        (PF: PF.pf_configuration L 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    (<<PF: PF.pf_configuration L c2>>).\n  Proof.\n    revert WF1. induction STEPS; i.\n    - splits; ss; refl.\n    - exploit step_trace_future; eauto. i. des.\n      exploit IHSTEPS; eauto. i. des.\n      splits; ss; etrans; eauto.\n  Qed.\n\n  Lemma steps_trace_n1 c0 c1 c2 tr trs e tid\n        (STEPS: steps_trace c0 c1 trs)\n        (STEP: step_trace tr e tid c1 c2)\n    :\n      steps_trace c0 c2 (trs ++ tr).\n  Proof.\n    ginduction STEPS.\n    { i. exploit steps_trace_cons.\n      { econs 1. }\n      { eapply STEP. }\n      { i. ss. erewrite List.app_nil_r in *. auto. }\n    }\n    { i. exploit IHSTEPS; eauto. i. erewrite <- List.app_assoc. econs; eauto. }\n  Qed.\n\n  Lemma steps_trace_trans c0 c1 c2 trs0 trs1\n        (STEPS0: steps_trace c0 c1 trs0)\n        (STEPS1: steps_trace c1 c2 trs1)\n    :\n      steps_trace c0 c2 (trs0 ++ trs1).\n  Proof.\n    ginduction STEPS0.\n    { i. erewrite List.app_nil_l. eauto. }\n    { i. exploit IHSTEPS0; eauto. i. erewrite <- List.app_assoc. econs; eauto. }\n  Qed.\n\n  Lemma step_trace_steps_trace tr e tid c1 c2\n        (STEP: step_trace tr e tid c1 c2)\n    :\n      steps_trace c1 c2 tr.\n  Proof.\n    exploit steps_trace_cons.\n    { econs 1. }\n    { eauto. }\n    i. rewrite List.app_nil_r in x0. auto.\n  Qed.\n\n  Lemma opt_step_trace_steps_trace tr e tid c1 c2\n        (STEP: opt_step_trace tr e tid c1 c2)\n    :\n      steps_trace c1 c2 tr.\n  Proof.\n    inv STEP.\n    { eapply step_trace_steps_trace; eauto. }\n    { econs 1. }\n  Qed.\n\n  Inductive silent_steps_trace:\n    forall (c0 c1: Configuration.t) (tr: Trace.t), Prop :=\n  | silent_steps_trace_nil\n      c0\n    :\n      silent_steps_trace c0 c0 []\n  | silent_steps_trace_cons\n      c0 c1 c2 trs tr tid\n      (STEPS: silent_steps_trace c1 c2 trs)\n      (STEP: step_trace tr MachineEvent.silent tid c0 c1)\n    :\n      silent_steps_trace c0 c2 (tr ++ trs)\n  .\n\n  Lemma silent_steps_trace_steps_trace\n    :\n      silent_steps_trace <3= steps_trace.\n  Proof.\n    intros. induction PR.\n    { econs. }\n    { econs; eauto. }\n  Qed.\n\n  Inductive steps_trace_rev: forall (c1 c2: Configuration.t) (tr: Trace.t), Prop :=\n  | steps_trace_rev_nil\n      c:\n      steps_trace_rev c c []\n  | steps_trace_rev_cons\n      c1 c2 c3 tr1 tr2 e tid\n      (STEPS: steps_trace_rev c1 c2 tr1)\n      (STEP: step_trace tr2 e tid c2 c3):\n      steps_trace_rev c1 c3 (tr1 ++ tr2)\n  .\n  Hint Constructors steps_trace_rev.\n\n  Lemma steps_trace_rev_1n\n        c1 c2 c3 tr1 tr2 e tid\n        (STEP: step_trace tr1 e tid c1 c2)\n        (STEPS: steps_trace_rev c2 c3 tr2):\n    steps_trace_rev c1 c3 (tr1 ++ tr2).\n  Proof.\n    revert tr1 e tid c1 STEP. induction STEPS; i.\n    - replace (tr1 ++ []) with ([] ++ tr1) by (rewrite List.app_nil_r; ss).\n      econs 2; [econs 1|]. eauto.\n    - exploit IHSTEPS; eauto. i.\n      rewrite List.app_assoc.\n      econs 2; eauto.\n  Qed.\n\n  Lemma steps_trace_equiv c1 c2 tr:\n    steps_trace c1 c2 tr <-> steps_trace_rev c1 c2 tr.\n  Proof.\n    split; i.\n    - induction H; eauto.\n      eapply steps_trace_rev_1n; eauto.\n    - induction H; [econs 1|].\n      eapply steps_trace_n1; eauto.\n  Qed.\n\n  Lemma steps_trace_inv\n        c1 c2 tr lc e\n        (STEPS: steps_trace c1 c2 tr)\n        (WF: Configuration.wf c1)\n        (PF: PF.pf_configuration L c1)\n        (TRACE: List.In (lc, e) tr):\n    exists c tr1 tid lang st1 lc1,\n      (<<STEPS: steps_trace c1 c tr1>>) /\\\n      (<<FIND: IdentMap.find tid (Configuration.threads c) = Some (existT _ lang st1, lc1)>>) /\\\n      exists tr2 pf e2 e3,\n        (<<THREAD_STEPS: Trace.steps tr2 (Thread.mk _ st1 lc1 (Configuration.sc c) (Configuration.memory c)) e2>>) /\\\n        (<<SILENT: List.Forall (fun the => ThreadEvent.get_machine_event (snd the) = MachineEvent.silent) tr2>>) /\\\n        (<<PF: List.Forall (compose (PF.pf_event L) snd) tr2>>) /\\\n        (<<LC: (Thread.local e2) = lc>>) /\\\n        (<<THREAD_STEP: Thread.step pf e e2 e3>>) /\\\n        (<<CONS: Local.promise_consistent (Thread.local e3)>>).\n  Proof.\n    rewrite steps_trace_equiv in STEPS.\n    induction STEPS; ss.\n    apply List.in_app_or in TRACE. des; eauto.\n    clear IHSTEPS. inv STEP.\n    exists c2, tr1, tid, lang, st1, lc1.\n    rewrite <- steps_trace_equiv in STEPS.\n    splits; ss.\n    apply List.in_app_or in TRACE. des; cycle 1.\n    { inv TRACE; ss. inv H. esplits; eauto.\n      - apply Forall_app_inv in PF0. des. ss.\n      - destruct (classic (e = ThreadEvent.failure)).\n        + subst. inv STEP0; inv STEP. inv LOCAL. inv LOCAL0. ss.\n        + exploit CONSISTENT; eauto. i. inv x. des.\n          exploit steps_trace_future; eauto. i. des.\n          inv WF2. inv WF0. exploit THREADS; eauto. i.\n          exploit Trace.steps_future; try exact STEPS0; eauto. s. i. des.\n          exploit Thread.step_future; try exact STEP0; eauto. s. i. des.\n          hexploit consistent_promise_consistent;\n            try eapply Trace.consistent_thread_consistent; try exact CONSISTENT0; eauto.\n    }\n    exploit steps_trace_future; eauto. i. des.\n    inv WF2. inv WF0. exploit THREADS; eauto. i. clear DISJOINT THREADS.\n    exploit Trace.steps_inv; try exact STEPS0; eauto.\n    { destruct (classic (e1 = ThreadEvent.failure)).\n      - subst. inv STEP0; inv STEP. inv LOCAL. inv LOCAL0. ss.\n      - exploit CONSISTENT; ss. i. inv x0. des.\n        exploit Trace.steps_future; eauto. s. i. des.\n        exploit Thread.step_future; eauto. s. i. des.\n        eapply step_promise_consistent; eauto.\n        eapply consistent_promise_consistent; eauto.\n        eapply Trace.consistent_thread_consistent; eauto.\n    }\n    i. des. esplits; eauto; subst.\n    - apply Forall_app_inv in SILENT. des. ss.\n    - apply Forall_app_inv in PF0. des.\n      apply Forall_app_inv in FORALL1. des. ss.\n  Qed.\n\n  Inductive multi_step (e:MachineEvent.t) (tid:Ident.t) (c1 c2:Configuration.t): Prop :=\n  | multi_step_intro\n      tr\n      (STEP: step_trace tr e tid c1 c2)\n  .\n\n  Lemma multi_step_machine_step e tid c1 c3\n        (STEP: multi_step e tid c1 c3)\n        (WF: Configuration.wf c1)\n        (PF: PF.pf_configuration L c1)\n    :\n      exists c2,\n        (<<STEPS: rtc tau_machine_step c1 c2>>) /\\\n        (<<STEP: opt_machine_step e tid c2 c3>>).\n  Proof.\n    inv STEP. exploit step_trace_steps; eauto. i. des.\n    { inv STEP0.\n      rewrite List.map_app in *.\n      rewrite list_filter_app in *. ss.\n      eapply steps_split in STEPS. des. exists c0. splits.\n      { eapply rtc_implies with (R1:=(machine_step MachineEvent.silent tid)).\n        { clear. i. econs; eauto. }\n        eapply silent_steps_tau_machine_steps; eauto.\n        eapply list_filter_forall with (Q:=fun e => ThreadEvent.get_machine_event e = MachineEvent.silent); eauto.\n        eapply list_map_forall; eauto.\n      }\n      unfold proj_sumbool in *. des_ifs.\n      { inv STEPS2. inv STEPS.\n        econs 2. econs; eauto. }\n      { inv STEPS2.\n        replace (ThreadEvent.get_machine_event e0) with MachineEvent.silent; eauto.\n        apply NNPP in n.\n        unfold ThreadEvent.is_reservation_event, ThreadEvent.is_reserve, ThreadEvent.is_cancel in n.\n        des; des_ifs.\n      }\n    }\n    { eapply SConfiguration.reservation_only_step_step in STEP.\n      eapply event_configuration_step_step in STEP; eauto; ss.\n      exists c1. esplits; eauto.\n      replace e with (ThreadEvent.get_machine_event ThreadEvent.silent); eauto.\n      ss. inv STEP0.\n      rewrite List.map_app in NIL.\n      rewrite list_filter_app in NIL.\n      eapply List.app_eq_nil in NIL.\n      ss. unfold proj_sumbool in NIL. des. des_ifs.\n      apply NNPP in n.\n      unfold ThreadEvent.is_reservation_event, ThreadEvent.is_reserve, ThreadEvent.is_cancel in n.\n      des; des_ifs.\n    }\n  Qed.\n\n  Lemma multi_step_future\n        e tid c1 c2\n        (STEP: multi_step e tid c1 c2)\n        (WF1: Configuration.wf c1)\n        (PF: PF.pf_configuration L 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    (<<PF: PF.pf_configuration L c2>>).\n  Proof.\n    inv STEP. eapply step_trace_future; eauto.\n  Qed.\n\n  Lemma silent_multi_steps_trace_behaviors c0 c1 tr\n        (STEP: silent_steps_trace c0 c1 tr)\n    :\n      behaviors multi_step c1 <1= behaviors multi_step c0.\n  Proof.\n    ginduction STEP; auto.\n    i. eapply IHSTEP in PR. econs 4; eauto.\n    econs. esplits; eauto.\n  Qed.\n\n  Lemma multi_step_behavior c\n        (WF: Configuration.wf c)\n        (PF: PF.pf_configuration L c)\n    :\n      behaviors multi_step c <1= behaviors machine_step c.\n  Proof.\n    i. induction PR.\n    - econs 1; eauto.\n    - exploit multi_step_future; eauto. i. des.\n      eapply multi_step_machine_step in STEP; eauto. des.\n      eapply rtc_tau_step_behavior; eauto.\n      inv STEP0; eauto. econs 2; eauto.\n    - exploit multi_step_future; eauto. i. des.\n      eapply multi_step_machine_step in STEP; eauto. des.\n      eapply rtc_tau_step_behavior; eauto.\n      inv STEP0; eauto. econs 3; eauto.\n    - exploit multi_step_future; eauto. i. des.\n      eapply multi_step_machine_step in STEP; eauto. des.\n      eapply rtc_tau_step_behavior; eauto.\n      inv STEP0; eauto. econs 4; eauto.\n  Qed.\n\nEnd LOCALPF.\nEnd PFConfiguration.\n\n\n(** L-PF race **)\nModule PFRace.\nSection LOCALPFRACE.\n  Variable L: Loc.t -> bool.\n\n  Inductive reading_event (loc: Loc.t) (ts: Time.t):\n    forall (e: ThreadEvent.t), Prop :=\n  | reading_event_read\n      valr releasedr ordr\n    :\n      reading_event loc ts (ThreadEvent.read loc ts valr releasedr ordr)\n  | reading_event_update\n      to valr valw releasedr releasedw ordr ordw\n    :\n      reading_event loc ts (ThreadEvent.update loc ts to valr valw releasedr releasedw ordr ordw)\n  .\n\n  Inductive writing_event (loc: Loc.t) (ts: Time.t):\n    forall (e: ThreadEvent.t), Prop :=\n  | writing_event_write\n      from valw releasedw ordw\n      (ORD: Ordering.le ordw Ordering.relaxed)\n    :\n      writing_event loc ts (ThreadEvent.write loc from ts valw releasedw ordw)\n  | writing_event_update\n      from valr valw releasedr releasedw ordr ordw\n      (ORD: Ordering.le ordw Ordering.relaxed)\n    :\n      writing_event loc ts (ThreadEvent.update loc from ts valr valw releasedr releasedw ordr ordw)\n  .\n\n  Definition racy_execution (c0: Configuration.t): Prop :=\n    forall tid0 c1 tid1 c2 c3\n           loc ts e0 e1\n           (LOC: L loc)\n           (TID: tid0 <> tid1)\n           (CSTEP0: PFConfiguration.step L e0 tid0 c0 c1)\n           (WRITE: writing_event loc ts e0)\n           (STEPS: rtc (PFConfiguration.machine_step L MachineEvent.silent tid1) c1 c2)\n           (CSTEP1: PFConfiguration.step L e1 tid1 c2 c3)\n           (READ: reading_event loc ts e1),\n      False.\n\n  Definition racefree (c0: Configuration.t): Prop :=\n    forall c1\n           (CSTEPS: rtc (PFConfiguration.all_step L) c0 c1),\n      racy_execution c1.\n\n  Definition racefree_syn (syn: Threads.syntax): Prop :=\n    racefree (Configuration.init syn).\n\n  Inductive racy_state (c0: Configuration.t): Prop :=\n  | race_intro\n      c1 c2\n      tid0 tid1 e0 e1\n      lang st0 lc0 th1 th2\n      tr pf loc ts\n      (STEPS: rtc (PFConfiguration.machine_step L MachineEvent.silent tid0) c0 c1)\n      (WRITE_STEP: PFConfiguration.step L e0 tid0 c1 c2)\n      (WRITE: writing_event loc ts e0)\n      (FIND: IdentMap.find tid1 (Configuration.threads c2) = Some (existT _ lang st0, lc0))\n      (THREAD_STEPS: Trace.steps tr (Thread.mk _ st0 lc0 (Configuration.sc c2) (Configuration.memory c2)) th1)\n      (PF: List.Forall (compose (PF.pf_event L) snd) tr)\n      (CONS: Local.promise_consistent (Thread.local th1))\n      (READ_STEP: Thread.step pf e1 th1 th2)\n      (READ: reading_event loc ts e1)\n      (LOC: L loc)\n  .\n\n  Lemma step_racefree c0 c1 e tid\n        (RACEFREE: racefree c0)\n        (STEP: PFConfiguration.step L e tid c0 c1)\n    :\n      racefree c1.\n  Proof.\n    unfold racefree in *. i.\n    eapply RACEFREE. econs 2; eauto. econs; eauto.\n  Qed.\n\n  Lemma rtc_tau_machine_step_racefree c0 c1\n        (RACEFREE: racefree c0)\n        (STEP: rtc (PFConfiguration.tau_machine_step L) c0 c1)\n    :\n      racefree c1.\n  Proof.\n    ginduction STEP; eauto.\n    i. eapply IHSTEP. inv H. inv USTEP.\n    eapply step_racefree; eauto.\n  Qed.\n\n  Lemma steps_racefree es tid c0 c1\n        (RACEFREE: racefree c0)\n        (STEPS: PFConfiguration.steps L es tid c0 c1)\n    :\n      racefree c1.\n  Proof.\n    ginduction STEPS; eauto.\n    i. eapply IHSTEPS.\n    eapply step_racefree; eauto.\n  Qed.\n\n  Inductive multi_race (c0: Configuration.t): Prop :=\n  | multi_race_intro\n      c1\n      tid0 tid1 e0 e1\n      lang st0 lc0 th1 th2\n      e trs tr pf loc ts\n      (STEPS: PFConfiguration.step_trace L trs e tid0 c0 c1)\n      (TRACE: final_event_trace e0 trs)\n      (WRITE: writing_event loc ts e0)\n      (FIND: IdentMap.find tid1 (Configuration.threads c1) = Some (existT _ lang st0, lc0))\n      (THREAD_STEPS: Trace.steps tr (Thread.mk _ st0 lc0 (Configuration.sc c1) (Configuration.memory c1)) th1)\n      (PF: List.Forall (compose (PF.pf_event L) snd) tr)\n      (CONS: Local.promise_consistent (Thread.local th1))\n      (READ_STEP: Thread.step pf e1 th1 th2)\n      (READ: reading_event loc ts e1)\n      (LOC: L loc)\n  .\n\n  Definition multi_racefree_imm (c0: Configuration.t): Prop :=\n    forall tid0 c1 trs0 tid1 c2 trs1\n           loc ts lc1 te0 te1 e0 e1\n           (LOC: L loc)\n           (TID: tid0 <> tid1)\n           (CSTEP0: PFConfiguration.step_trace L trs0 e0 tid0 c0 c1)\n           (WRITE: writing_event loc ts te0)\n           (TRACE0: final_event_trace te0 trs0)\n           (CSTEP1: PFConfiguration.step_trace L trs1 e1 tid1 c1 c2)\n           (READ: reading_event loc ts te1)\n           (TRACE1: List.In (lc1, te1) trs1),\n      False.\n\n  Definition multi_racefree (c0: Configuration.t): Prop :=\n    forall c1 trs\n           (CSTEPS: PFConfiguration.steps_trace L c0 c1 trs),\n      multi_racefree_imm c1.\n\n  Lemma multi_step_multi_racefree c0 c1 tr e tid\n        (RACEFREE: multi_racefree c0)\n        (STEP: PFConfiguration.step_trace L tr e tid c0 c1)\n    :\n      multi_racefree c1.\n  Proof.\n    unfold multi_racefree in *. i.\n    eapply RACEFREE. econs 2; eauto.\n  Qed.\n\n  Lemma multi_steps_multi_racefree c0 c1 trs\n        (RACEFREE: multi_racefree c0)\n        (STEPS: PFConfiguration.steps_trace L c0 c1 trs)\n    :\n      multi_racefree c1.\n  Proof.\n    induction STEPS; auto. eapply IHSTEPS.\n    eapply multi_step_multi_racefree; eauto.\n  Qed.\n\n  Lemma racefree_multi_racefree_imm c\n        (RACEFREE: racefree c)\n        (WF: Configuration.wf c)\n        (PF: PF.pf_configuration L c)\n    :\n      multi_racefree_imm c.\n  Proof.\n    ii. exploit PFConfiguration.step_trace_future; try apply CSTEP0; eauto.  i. des.\n    exploit final_event_trace_filter; eauto.\n    { unfold ThreadEvent.is_normal, ThreadEvent.is_reservation_event.\n      inv WRITE; ss; ii; des; ss. } i. des.\n    eapply PFConfiguration.step_trace_steps in CSTEP0; eauto.\n    rewrite FILTER in *. des; cycle 1.\n    { eapply List.app_eq_nil in NIL. des; ss. }\n    eapply PFConfiguration.steps_split in STEPS. des. inv STEPS1. inv STEPS.\n    eapply List.in_split in TRACE1. des; subst.\n    dup CSTEP1. eapply PFConfiguration.step_trace_steps in CSTEP1; eauto.\n    rewrite List.map_app in *.\n    rewrite list_filter_app in *. ss. unfold proj_sumbool in *.\n    des_ifs; cycle 1.\n    { clear - READ n. apply NNPP in n.\n      unfold ThreadEvent.is_normal, ThreadEvent.is_reservation_event in *.\n      inv READ; ss; ii; des; ss. }\n    des; cycle 1.\n    { eapply List.app_eq_nil in NIL0. des; ss. }\n    eapply PFConfiguration.steps_split in STEPS. des. inv STEPS2.\n    eapply RACEFREE; try eassumption.\n    { eapply PFConfiguration.steps_rtc_all_step; eauto. }\n    { eapply PFConfiguration.silent_steps_tau_machine_steps; eauto.\n      clear - CSTEP0. inv CSTEP0.\n      destruct (list_match_rev l2); des; subst.\n      { eapply List.app_inj_tail in TR. des; clarify.\n        eapply List.Forall_forall. ii.\n        eapply List.filter_In in H. des.\n        eapply List.in_map_iff in H. des; subst.\n        eapply List.Forall_forall in SILENT; eauto. }\n      { rewrite List.app_comm_cons in TR.\n        rewrite List.app_assoc in TR.\n        eapply List.app_inj_tail in TR. des; clarify.\n        eapply Forall_app_inv in SILENT. des.\n        eapply List.Forall_forall. ii.\n        eapply List.filter_In in H. des.\n        eapply List.in_map_iff in H. des; subst.\n        eapply List.Forall_forall in FORALL1; eauto. }\n    }\n  Qed.\n\n  Lemma racefree_multi_racefree c\n        (RACEFREE: racefree c)\n        (WF: Configuration.wf c)\n        (PF: PF.pf_configuration L c)\n    :\n      multi_racefree c.\n  Proof.\n    unfold multi_racefree. i.\n    ginduction CSTEPS; eauto.\n    { i. eapply racefree_multi_racefree_imm; eauto. }\n    { i. exploit PFConfiguration.step_trace_future; eauto.\n      i. des. eapply IHCSTEPS; eauto.\n      eapply PFConfiguration.step_trace_steps in STEP; eauto. des.\n      { eapply steps_racefree; eauto. }\n      { eapply PFConfiguration.reservation_only_step_step in STEP0; eauto.\n        eapply step_racefree; eauto. }\n    }\n  Qed.\n\n  Lemma multi_race_race c\n        (RACE: multi_race c)\n        (WF: Configuration.wf c)\n        (PF: PF.pf_configuration L c)\n    :\n      racy_state c.\n  Proof.\n    inv RACE.\n    exploit PFConfiguration.step_trace_future; try apply STEPS; eauto. i. des.\n    exploit final_event_trace_filter; eauto.\n    { ii. inv WRITE; eauto. } i. des.\n    dup STEPS. eapply PFConfiguration.step_trace_steps in STEPS; eauto.\n    rewrite FILTER in *. des; cycle 1.\n    { eapply List.app_eq_nil in NIL. des; ss. }\n    eapply PFConfiguration.steps_split in STEPS1. des. inv STEPS3. inv STEPS.\n    econs; cycle 1; eauto.\n    eapply PFConfiguration.silent_steps_tau_machine_steps; eauto.\n    assert (exists trs_hd trs_tl,\n               (<<TRS: trs = trs_hd ++ [trs_tl]>>) /\\\n               (<<SILENT: List.Forall (fun the => ThreadEvent.get_machine_event (snd the) = MachineEvent.silent) trs_hd>>)).\n    { inv STEPS0. eauto. } clear STEPS0. des. subst.\n    erewrite List.map_app in FILTER. erewrite list_filter_app in FILTER.\n    assert (exists tl,\n               tr_hd ++ tl = List.filter (fun e => ThreadEvent.is_normal_dec e) (List.map snd trs_hd)).\n    { ss. des_ifs.\n      - exists []. rewrite List.app_nil_r.\n        eapply List.app_inj_tail in FILTER. des. auto.\n      - exists [e0]. rewrite <- FILTER. rewrite List.app_nil_r. auto.\n    }\n    des. exploit Forall_app_inv; cycle 1.\n    { i. des. eapply FORALL1. }\n    { rewrite H. eapply List.Forall_forall. i.\n      eapply List.filter_In in H0. des.\n      eapply List.in_map_iff in H0. des. subst.\n      eapply List.Forall_forall in SILENT; eauto.\n    }\n  Qed.\n\n  Inductive racy_read (loc: Loc.t) (ts: Time.t):\n    forall (lc: Local.t) (e: ThreadEvent.t), Prop :=\n  | racy_read_read\n      lc\n      valr releasedr ordr\n      (VIEW:\n         Time.lt (if Ordering.le Ordering.relaxed ordr\n                  then ((TView.cur (Local.tview lc)).(View.rlx) loc)\n                  else ((TView.cur (Local.tview lc)).(View.pln) loc)) ts)\n    :\n      racy_read loc ts lc (ThreadEvent.read loc ts valr releasedr ordr)\n  | racy_read_update\n      lc\n      to valr valw releasedr releasedw ordr ordw\n      (VIEW:\n         Time.lt (if Ordering.le Ordering.relaxed ordr\n                  then ((TView.cur (Local.tview lc)).(View.rlx) loc)\n                  else ((TView.cur (Local.tview lc)).(View.pln) loc)) ts)\n    :\n      racy_read loc ts lc (ThreadEvent.update loc ts to valr valw releasedr releasedw ordr ordw)\n  .\n\n  Definition multi_racefree_view (c0: Configuration.t): Prop :=\n    forall c1 trs1 c2 trs2\n      loc ts lc0 lc1 e0 e1\n      (CSTEPS1: PFConfiguration.steps_trace L c0 c1 trs1)\n      (LOC: L loc)\n      (TRACE1: List.In (lc0, e0) trs1)\n      (WRITE: writing_event loc ts e0)\n      (CSTEPS2: PFConfiguration.steps_trace L c1 c2 trs2)\n      (TRACE2: List.In (lc1, e1) trs2)\n      (READ: racy_read loc ts lc1 e1),\n      False.\n\n  Lemma multi_step_multi_racefree_view c0 c1 tr e tid\n        (RACEFREE: multi_racefree_view c0)\n        (STEP: PFConfiguration.step_trace L tr e tid c0 c1)\n    :\n      multi_racefree_view c1.\n  Proof.\n    ii. eapply RACEFREE.\n    { econs 2.\n      { eapply CSTEPS1. }\n      { eauto. }\n    }\n    { eauto. }\n    { eapply List.in_or_app. right. eapply TRACE1. }\n    { eauto. }\n    { eauto. }\n    { eauto. }\n    { eauto. }\n  Qed.\n\n  Lemma multi_steps_multi_racefree_view c0 c1 trs\n        (RACEFREE: multi_racefree_view c0)\n        (STEPS: PFConfiguration.steps_trace L c0 c1 trs)\n    :\n      multi_racefree_view c1.\n  Proof.\n    induction STEPS; auto. eapply IHSTEPS.\n    eapply multi_step_multi_racefree_view; eauto.\n  Qed.\n\n  Inductive racy_read_step:\n    forall (loc: Loc.t) (ts: Time.t)\n           (e:ThreadEvent.t) (tid:Ident.t) (c1 c2:Configuration.t), Prop :=\n  | racy_read_step_intro\n      loc ts 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: Thread.opt_step e e2 e3)\n      (RESERVES: rtc (@Thread.reserve_step _) e3 (Thread.mk _ st4 lc4 sc4 memory4))\n      (CONSISTENT: e <> ThreadEvent.failure -> PF.pf_consistent L (Thread.mk _ st4 lc4 sc4 memory4))\n      (PF: PF.pf_event L e)\n      (READ: racy_read loc ts (Thread.local e2) e)\n    :\n      racy_read_step loc ts e tid c1 (Configuration.mk (IdentMap.add tid (existT _ _ st4, lc4) (Configuration.threads c1)) sc4 memory4)\n  .\n  Hint Constructors racy_read_step.\n\n  Inductive racy_write_step:\n    forall (loc: Loc.t) (ts: Time.t)\n           (e:ThreadEvent.t) (tid:Ident.t) (c1 c2:Configuration.t), Prop :=\n  | racy_write_step_intro\n      loc ts e tid c1 c2\n      (STEP: PFConfiguration.step L e tid c1 c2)\n      (WRITE: writing_event loc ts e)\n    :\n      racy_write_step loc ts e tid c1 c2\n  .\n\n  Definition racefree_view (c0: Configuration.t): Prop :=\n    forall c1 c2 c3 c4 loc ts e0 e1 tid0 tid1\n      (LOC: L loc)\n      (CSTEPS1: rtc (PFConfiguration.all_step L) c0 c1)\n      (WRITE: racy_write_step loc ts e0 tid0 c1 c2)\n      (CSTEPS2: rtc (PFConfiguration.all_step L) c2 c3)\n      (READ: racy_read_step loc ts e1 tid1 c3 c4),\n      False.\n\n  Definition racefree_view_syn (syn: Threads.syntax): Prop :=\n    racefree_view (Configuration.init syn).\n\n  Lemma step_racefree_view c0 c1 e tid\n        (RACEFREE: racefree_view c0)\n        (STEP: PFConfiguration.step L e tid c0 c1)\n    :\n      racefree_view c1.\n  Proof.\n    ii. eapply RACEFREE; cycle 2; eauto.\n    econs; eauto. econs; eauto.\n  Qed.\n\n  Lemma steps_racefree_view c0 c1\n        (RACEFREE: racefree_view c0)\n        (STEPS: rtc (PFConfiguration.all_step L) c0 c1)\n    :\n      racefree_view c1.\n  Proof.\n    ii. eapply RACEFREE; cycle 2; eauto. etrans; eauto.\n  Qed.\n\nEnd LOCALPFRACE.\nEnd PFRace.\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/PFStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2576146831130966}}
{"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 Types.\nRequire Import Dynamics.\n\nRequire Export Types.\nRequire Export Dynamics.\n\nModule VoidnessPreservationBase (Import MyDynamics : DynamicsSig).\n\n  Inductive VoidnessPreserves : DartType -> DartType -> Prop :=\n  | vp_dynamic_any : ∀ dt,\n    VoidnessPreserves dt_dynamic dt\n  | vp_any_void : ∀ dt,\n    VoidnessPreserves dt dt_void\n  | vp_any_variable : ∀ dt n,\n    VoidnessPreserves dt (dt_variable n)\n  | vp_any_dynamic : ∀ dt,\n    MyDynamics.dynamic_is_magic ->\n    VoidnessPreserves dt dt_dynamic\n  | vp_class : ∀ ctypes1 ctypes2,\n    VoidnessClassTypesPreserve ctypes1 ctypes2 ->\n    VoidnessPreserves (dt_class ctypes1) (dt_class ctypes2)\n  | vp_class_dynamic : ∀ ctypes,\n    VoidnessPreserves (dt_class ctypes) dt_dynamic\n  | vp_function : ∀ ret1 ret2 args1 args2,\n    VoidnessPreserves ret1 ret2 ->\n    VoidnessPreservesPairwise args2 args1 ->\n    VoidnessPreserves (dt_function ret1 args1) (dt_function ret2 args2)\n  | vp_function_dynamic : ∀ ret args,\n    VoidnessPreserves (dt_function ret args) dt_dynamic\n  | vp_bottom_bottom :\n    VoidnessPreserves dt_bottom dt_bottom\n\n  with VoidnessPreservesPairwise : DartTypes -> DartTypes -> Prop :=\n  | vpp_nil : VoidnessPreservesPairwise dts_nil dts_nil\n  | vpp_cons : ∀ dt1 dt2 dts1 dts2,\n    VoidnessPreserves dt1 dt2 ->\n    VoidnessPreservesPairwise dts1 dts2 ->\n    VoidnessPreservesPairwise (dts_cons dt1 dts1) (dts_cons dt2 dts2)\n\n  with VoidnessClassTypesPreserve : NameDartTypes -> NameDartTypes -> Prop :=\n  | vctsp_nil : ∀ ctypes,\n    VoidnessClassTypesPreserve ndts_nil ctypes\n  | vctsp_cons : ∀ name dt ctypes1 ctypes2,\n    VoidnessClassTypePreserves name dt ctypes2 ->\n    VoidnessClassTypesPreserve ctypes1 ctypes2 ->\n    VoidnessClassTypesPreserve (ndts_cons name dt ctypes1) ctypes2\n\n  with VoidnessClassTypePreserves : Name -> DartTypes -> NameDartTypes -> Prop :=\n  | vctp_gone : ∀ name dt ctypes,\n    VoidnessClassTypeGone name dt ctypes ->\n    VoidnessClassTypePreserves name dt ctypes\n  | vctp_some : ∀ name dt ctypes,\n    VoidnessClassTypePreservesSome name dt ctypes ->\n    VoidnessClassTypePreserves name dt ctypes\n\n  with VoidnessClassTypeGone : Name -> DartTypes -> NameDartTypes -> Prop :=\n  | vctg_nil : ∀ name dt,\n    VoidnessClassTypeGone name dt ndts_nil\n  | vctg_cons : ∀ name1 args1 name2 args2 ctypes,\n    name1 <> name2 ->\n    VoidnessClassTypeGone name1 args1 ctypes ->\n    VoidnessClassTypeGone name1 args1 (ndts_cons name2 args2 ctypes)\n\n  with VoidnessClassTypePreservesSome : Name -> DartTypes -> NameDartTypes -> Prop :=\n  | vctps_first : ∀ name args1 args2 ctypes,\n    VoidnessPreservesPairwise args1 args2 ->\n    VoidnessClassTypePreservesSome name args1 (ndts_cons name args2 ctypes)\n  | vctps_rest : ∀ name1 dt1 name2 dt2 ctypes2,\n    VoidnessClassTypePreservesSome name1 dt1 ctypes2 ->\n    VoidnessClassTypePreservesSome name1 dt1 (ndts_cons name2 dt2 ctypes2).\n\n  Hint Constructors\n    VoidnessPreserves VoidnessPreservesPairwise\n    VoidnessClassTypesPreserve VoidnessClassTypePreserves\n    VoidnessClassTypeGone VoidnessClassTypePreservesSome.\n\nEnd VoidnessPreservationBase.\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/VoidnessPreservation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.257568691368125}}
{"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 & Mark Bickford\n\n*)\n\nRequire Export computation4.\n\nLemma isprog_inl_iff {p} :\n  forall a : @NTerm p, isprog (mk_inl a) <=> (isprog a).\nProof.\n  introv; split; intro k.\n  - allrw @isprog_eq.\n    destruct k as [c w].\n    inversion w as [| | o lnt j e ]; subst.\n    generalize (j (nobnd a)); intros i1; allsimpl.\n    repeat (autodimp i1 hyp).\n    unfold isprogram.\n    inversion c as [pp]. allrw remove_nvars_nil_l; allrw app_nil_r.\n    inversion i1; subst. sp.\n  - apply isprog_inl; sp.\nQed.\n\nLemma isprog_inr_iff {p} :\n  forall a : @NTerm p, isprog (mk_inr a) <=> (isprog a).\nProof.\n  introv; split; intro k.\n  - allrw @isprog_eq.\n    destruct k as [c w].\n    inversion w as [| | o lnt j e ]; subst.\n    generalize (j (nobnd a)); intros i1; allsimpl.\n    repeat (autodimp i1 hyp).\n    unfold isprogram.\n    inversion c as [pp]. allrw remove_nvars_nil_l; allrw app_nil_r.\n    inversion i1; subst. sp.\n  - apply isprog_inr; sp.\nQed.\n\nLemma isvalue_inl {p} :\n  forall (a : @NTerm p), isprogram a ->  isvalue (mk_inl a).\nProof.\n introv ispa.\n constructor; simpl; auto.\n apply isprogram_inl; auto.\nQed.\n\nLemma isvalue_inr {p} :\n  forall (a : @NTerm p), isprogram a ->  isvalue (mk_inr a).\nProof.\n introv ispa.\n constructor; simpl; auto.\n apply isprogram_inr; auto.\nQed.\nHint Resolve isvalue_inr isvalue_inl : slow.\n\nLemma compute_step_decide_ncan {o} :\n  forall lib n l x y b1 b2,\n    @compute_step o lib (mk_decide (oterm (NCan n) l) x b1 y b2)\n    = match compute_step lib (oterm (NCan n) l) with\n        | csuccess p => csuccess (mk_decide p x b1 y b2)\n        | cfailure str ts => cfailure str ts\n      end.\nProof. introv; csunf; simpl; sp. Qed.\n\nLemma hasvaluec_mkc_decide {q} :\n  forall lib p x y t1 t2,\n    hasvaluec lib (mkc_decide p x t1 y t2)\n    -> {a : @CTerm q $\n          computes_to_valc lib p (mkc_inl a)\n           [+]\n          computes_to_valc lib p (mkc_inr a)\n       }.\nProof.\n  introv hv.\n  destruct_cterms.\n  unfold hasvaluec in hv; allsimpl.\n  rename x0 into p.\n  rename x1 into t2.\n  rename x2 into t1.\n  unfold computes_to_valc; simpl.\n  destruct hv as [t' c].\n  destruct c as [rt iv].\n  destruct rt as [k comp].\n  revert dependent p.\n  induction k; introv isp comp.\n\n  - rw @reduces_in_atmost_k_steps_0 in comp; subst.\n    inversion iv; allsimpl; tcsp.\n\n  - rw @reduces_in_atmost_k_steps_S in comp; exrepnd.\n    destruct p as [v|f|op bs].\n\n    + inversion comp1.\n\n    + csunf comp1; allsimpl; ginv.\n\n    +  dopid op as [can | ncan | ex | abs] Case.\n\n       * Case \"Can\".\n         csunf comp1. allsimpl. apply compute_step_decide_success in comp1; exrepnd.\n         subst; cpx. repndors; exrepnd; subst; fold_terms.\n         { rw @isprog_inl_iff in isp. exists (mk_ct d isp). simpl. left.\n           apply computes_to_value_isvalue_refl; sp. eauto 3 with slow.\n         }\n         { rw @isprog_inr_iff in isp. exists (mk_ct d isp). simpl. right.\n           apply computes_to_value_isvalue_refl; sp. eauto 3 with slow.\n         }\n\n      * Case \"NCan\".\n        rw @compute_step_decide_ncan in comp1.\n        remember (compute_step lib (oterm (NCan ncan) bs)).\n        destruct c; ginv.\n\n        symmetry in Heqc.\n        allrw @isprog_eq.\n        applydup @preserve_compute_step in Heqc; auto.\n        apply IHk in comp0; auto; exrepnd; try (complete (apply isprog_eq; auto)).\n        exists a. repndors; [left | right];\n        eapply computes_to_value_step; eauto.\n\n      * Case \"Exc\".\n        simpl in comp1. csunf comp1; allsimpl; ginv.\n        apply reduces_atmost_exc in comp0; subst.\n        inversion iv; allsimpl; tcsp.\n\n      * Case \"Abs\".\n        csunf comp1; simpl in comp1; unfold on_success in comp1; csunf comp1; allsimpl.\n        remember (compute_step_lib lib abs bs) as csl.\n        destruct csl; inversion comp1; subst; GC.\n        symmetry in Heqcsl.\n        rw @isprog_eq in isp.\n        applydup @isprogram_compute_step_lib in Heqcsl; auto.\n        rw <- @isprog_eq in Heqcsl0.\n        apply IHk in comp0; auto; exrepnd.\n        exists a; repndors; [ left | right ]; eapply computes_to_value_step; eauto.\nQed.\n\n\nLemma if_computes_to_exception_decide0 {o} :\n  forall lib n (t : @NTerm o) x y u v e,\n    isprogram t\n    -> computes_to_exception lib n (mk_decide t x u y v) e\n    -> computes_to_exception lib n t e\n       [+] {a : NTerm\n            & computes_to_value lib t (mk_inl a)\n            # computes_to_exception lib n (lsubst u [(x,a)]) e}\n\n       [+] {a : NTerm\n            & computes_to_value lib t (mk_inr a)\n            # computes_to_exception lib n (lsubst v [(y,a)]) e}.\nProof.\n  unfold computes_to_exception, reduces_to.\n  introv ispt re; exrepnd.\n  revert dependent t.\n  revert x y u v.\n  induction k; introv ispt r.\n\n  - apply reduces_in_atmost_k_steps_0 in r; inversion r.\n\n  - rw @reduces_in_atmost_k_steps_S in r; exrepnd.\n    csunf r1; allsimpl.\n    destruct t as [z|f|op bs]; try (complete (inversion r1));[].\n    dopid op as [can|ncan|exc|abs] Case; try (complete (inversion r1)).\n\n    + Case \"Can\".\n      apply compute_step_decide_success in r1; exrepnd; subst; ginv.\n      right. repndors; [left | right]; repnd; subst; exists d; dands; eauto 3 with slow;\n      allrw <- @isprogram_inl_iff; repnd;\n      allrw <- @isprogram_inr_iff; repnd;\n      apply computes_to_value_isvalue_refl; eauto 3 with slow.\n\n    + Case \"NCan\".\n      remember (compute_step lib (oterm (NCan ncan) bs)) as c;\n        destruct c; allsimpl; ginv; symmetry in Heqc.\n\n      applydup @preserve_compute_step in Heqc; auto.\n      apply IHk in r0; auto.\n      repndors; exrepnd.\n\n      { left.\n        exists (S k0).\n        rw @reduces_in_atmost_k_steps_S.\n        exists n0; auto. }\n\n      { right. left.\n        exists a; sp.\n        { eapply computes_to_value_step; eauto. }\n        exists k0; auto. }\n      { right. right.\n        exists a; sp.\n        { eapply computes_to_value_step; eauto. }\n        exists k0; auto. }\n\n    + Case \"Exc\".\n      ginv.\n      left.\n      exists k; auto.\n\n    + Case \"Abs\".\n      csunf r1; allsimpl.\n      remember (compute_step_lib lib abs bs) as c;\n        destruct c; allsimpl; symmetry in Heqc; ginv.\n\n      applydup @isprogram_compute_step_lib in Heqc; auto.\n      apply IHk in r0; auto.\n      repndors; exrepnd.\n\n      { left.\n        exists (S k0).\n        rw @reduces_in_atmost_k_steps_S.\n        exists n0; auto. }\n\n      { right. left.\n        exists a; sp.\n        { eapply computes_to_value_step; eauto. }\n        exists k0; auto. }\n      { right. right.\n        exists a; sp.\n        { eapply computes_to_value_step; eauto. }\n        exists k0; auto. }\n  \nQed.\n\n(* !!MOVE *)\nLemma if_raises_exception_decide0 {o} :\n  forall lib (t : @NTerm o) x y u v,\n    isprogram t\n    -> raises_exception lib (mk_decide t x u y v)\n    -> raises_exception lib t\n       [+] {a : NTerm\n            & computes_to_value lib t (mk_inl a)\n            # raises_exception lib (lsubst u [(x,a)]) }\n       [+] {a : NTerm\n            & computes_to_value lib t (mk_inr a)\n            # raises_exception lib (lsubst v [(y,a)])}.\nProof.\n  introv isp re.\n  unfold raises_exception in re; exrepnd.\n  pose proof (if_computes_to_exception_decide0 lib a t x y u v e isp re1) as h.\n  repndors; exrepnd.\n  - left; exists a e; auto.\n  - right. left.\n    exists a0; dands; auto.\n    exists a e; auto.\n  - right. right.\n    exists a0; dands; auto.\n    exists a e; auto.\nQed.\n\n(* !!MOVE *)\nLemma if_raises_exceptionc_decide0 {o} :\n  forall lib (t : @CTerm o) x y u v,\n    raises_exceptionc lib (mkc_decide t x u y v)\n    -> raises_exceptionc lib t\n       [+] {a : CTerm\n            & computes_to_valc lib t (mkc_inl a)\n            # raises_exceptionc lib (substc a x u) }\n       [+] {a : CTerm\n            & computes_to_valc lib t (mkc_inr a)\n            # raises_exceptionc lib (substc a y v) }.\nProof.\n  introv re.\n  destruct_cterms.\n  allunfold @raises_exceptionc.\n  allunfold @computes_to_valc.\n  allsimpl.\n  pose proof (if_raises_exception_decide0 lib x0 x y x2 x1) as h.\n  repeat (autodimp h hyp); eauto 3 with slow.\n  repndors; exrepnd; tcsp; right; [left | right].\n  -\n  applydup @preserve_program in h1; eauto 3 with slow.\n  allrw <- @isprogram_inl_iff; repnd.\n  exists (mk_cterm a h2); simpl.\n  dands; auto.\n -applydup @preserve_program in h1; eauto 3 with slow.\n  allrw <- @isprogram_inr_iff; repnd.\n  exists (mk_cterm a h2); simpl.\n  dands; 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/computation_injections.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2574799024313704}}
{"text": "(*\n * Copyright (c) 2009-2011, Andrew Appel, Robert Dockins and Aquinas Hobor.\n *\n *)\n\nRequire Import VST.msl.base.\nLocal Open Scope nat_scope.\n\nRequire Import VST.msl.ageable.\nRequire Import VST.msl.functors.\nRequire Import VST.msl.predicates_hered.\n\nImport CovariantFunctor.\nImport CovariantFunctorLemmas.\nImport CovariantFunctorGenerator.\n\nModule Type TY_FUNCTOR_PROP.\n  Parameter F : functor.\n  Parameter other : Type.\nEnd TY_FUNCTOR_PROP.\n\nModule Type KNOT_HERED.\n  Declare Module TF:TY_FUNCTOR_PROP.\n  Import TF.\n\n  Parameter knot:Type.\n  Parameter ag_knot : ageable knot.\n  #[global] Existing Instance ag_knot.\n  #[global] Existing Instance ag_prod.\n  Parameter ext_knot : Ext_ord knot.\n  #[global] Existing Instance ext_knot.\n  #[global] Existing Instance Ext_prod.\n\n  Parameter hered : (knot * other -> Prop) -> Prop.\n  Definition predicate := { p:knot * other -> Prop | hered p }.\n\n  Parameter squash : (nat * F predicate) -> knot.\n  Parameter unsquash : knot -> (nat * F predicate).\n\n  Parameter approx : nat -> predicate -> predicate.\n\n  Axiom squash_unsquash : forall k:knot, squash (unsquash k) = k.\n  Axiom unsquash_squash : forall (n:nat) (f:F predicate),\n    unsquash (squash (n,f)) = (n, fmap F (approx n) f).\n\n  Axiom approx_spec : forall n p k,\n    proj1_sig (approx n p) k = (level k < n /\\ proj1_sig p k).\n\n  Axiom knot_level : forall k:knot, level k = fst (unsquash k).\n\n  Axiom knot_age1 : forall k,\n    age1 k =\n    match unsquash k with\n    | (O,_) => None\n    | (S n,x) => Some (squash (n,x))\n    end.\n\nEnd KNOT_HERED.\n\nModule KnotHered (TF':TY_FUNCTOR_PROP) : KNOT_HERED with Module TF:=TF'.\n  Module TF:=TF'.\n  Import TF.\n\n  Definition sinv_prod X := prod X (F X * other -> Prop).\n\n  Definition guppy_sig := (fun T:Type => T * (F T * other -> Prop) -> Prop).\n  Definition guppy_ty := sigT guppy_sig.\n\n  Definition guppy_step_ty (Z:guppy_ty) : Type :=\n    (sig (fun (x:sinv_prod (projT1 Z)) => projT2 Z x)).\n\n  Definition guppy_step_prop (Z:guppy_ty) (xf:sinv_prod (guppy_step_ty Z)) :=\n    forall (k:F (guppy_step_ty Z)) (o:other),\n      snd xf (k,o) -> snd (proj1_sig (fst xf)) (fmap F (@fst _ _ oo @proj1_sig _ _) k,o).\n\n  Definition guppy_step (Z:guppy_ty) : guppy_ty :=\n    existT guppy_sig (guppy_step_ty Z) (guppy_step_prop Z).\n\n  Definition guppy_base : guppy_ty :=\n    existT guppy_sig unit (fun _ => True).\n\n  Fixpoint guppy (n:nat) : guppy_ty :=\n    match n with\n    | 0    => guppy_base\n    | S n' => guppy_step (guppy n')\n    end.\n\n  Definition sinv (n:nat) : Type := projT1 (guppy n).\n  Definition sinv_prop (n:nat) : prod (sinv n) (F (sinv n) * other -> Prop) -> Prop := projT2 (guppy n).\n\n  Fixpoint floor (m:nat) (n:nat) (p:sinv (m+n)) : sinv n :=\n    match m as m' return forall (p : sinv (m'+n)), sinv n with\n    | O => fun p => p\n    | S m' => fun p => floor m' n (fst (proj1_sig p))\n    end p.\n\n  Definition knot := { n:nat & F (sinv n) }.\n\n  Definition k_age1 (k:knot) : option (knot) :=\n    match k with\n      | (existT _ 0 f) => None\n      | (existT _ (S m) f) => Some\n          (existT (F oo sinv) m (fmap F (@fst _ _ oo @proj1_sig _ _) f))\n    end.\n\n  Definition k_age (k1 k2:knot) := k_age1 k1 = Some k2.\n\n  Definition ko_age1 (x:knot * other) :=\n    match k_age1 (fst x) with\n    | None => None\n    | Some a' => Some (a',snd x)\n    end.\n  Definition ko_age x y := ko_age1 x = Some y.\n\n  Definition hered := hereditary ko_age.\n  Definition predicate := { p:knot * other -> Prop | hereditary ko_age p }.\n\n  Definition app_sinv (n:nat) (p:sinv (S n)) (x:F (sinv n) * other) :=\n    snd (proj1_sig p) x.\n\n  Lemma app_sinv_age : forall n (p:sinv (S (S n))) (f:F (sinv (S n)) * other),\n    app_sinv (S n) p f ->\n    app_sinv n (fst (proj1_sig p)) (fmap F (@fst _ _ oo @proj1_sig _ _) (fst f), snd f).\n  Proof.\n    intros.\n    unfold app_sinv in *.\n    destruct p; simpl in *; fold guppy in *.\n    apply p; auto.\n    destruct f; auto.\n  Qed.\n\n  Section stratifies.\n    Variable Q:knot * other -> Prop.\n    Variable HQ:hereditary ko_age Q.\n\n    Fixpoint stratifies (n:nat) : sinv n -> Prop :=\n    match n as n' return sinv n' -> Prop with\n    | 0 => fun _ => True\n    | S n' => fun (p:sinv (S n')) =>\n          stratifies n' (fst (proj1_sig p)) /\\\n          forall (k:F (sinv n')) (o:other), snd (proj1_sig p) (k,o) <-> Q (existT (F oo sinv) n' k,o)\n    end.\n\n    Lemma stratifies_unique : forall n p1 p2,\n      stratifies n p1 ->\n      stratifies n p2 ->\n      p1 = p2.\n    Proof.\n      induction n; simpl; intuition.\n      destruct p1; destruct p2; auto.\n      destruct p1; destruct p2.\n      simpl in *; fold guppy in *.\n      cut (x = x0).\n      intros.\n      revert p p0 H2 H3.\n      rewrite <- H0.\n      intros.\n      replace p0 with p by (apply proof_irr); auto.\n      destruct x; destruct x0; simpl in *.\n      apply injective_projections; simpl.\n      apply IHn; auto.\n      extensionality; intros.\n      simpl in *.\n      destruct (H2 (fst x) (snd x)); destruct (H3 (fst x) (snd x)).\n      apply prop_ext; destruct x; intuition.\n    Qed.\n\n    Definition stratify (n:nat) : { x:sinv n | stratifies n x }.\n    Proof.\n      induction n.\n      exists tt; simpl; exact I.\n      assert (HX:\n        projT2 (guppy n)\n        (proj1_sig IHn, fun v : F (sinv n) * other => Q (existT (F oo sinv) n (fst v),snd v))).\n      destruct n.\n      simpl; exact I.\n      simpl; intros.\n      destruct IHn; simpl.\n      simpl in s; destruct s.\n      destruct x; simpl in *; fold guppy in *.\n      destruct x; simpl in *.\n      hnf; simpl; intros.\n      rewrite H0.\n      eapply HQ.\n      2: apply H1.\n      simpl; reflexivity.\n      exists ((exist (fun x => projT2 (guppy n) x) ( proj1_sig IHn, fun v:F (sinv n) * other => Q (existT (F oo sinv) n (fst v),snd v) ) HX)).\n      simpl; split.\n      destruct IHn; auto.\n      unfold app_sinv; simpl; intros.\n      split; trivial.\n    Qed.\n  End stratifies.\n\n  Lemma decompose_nat : forall (x y:nat), { m:nat & y = (m + S x) } + { ge x y }.\n  Proof.\n    intros x y; revert x; induction y; simpl; intros.\n    right; auto with arith.\n    destruct (IHy x) as [[m H]|H].\n    left; exists (S m); lia.\n    destruct (Peano_dec.eq_nat_dec x y).\n    left; exists O; lia.\n    right; lia.\n  Qed.\n\n  Definition unstratify (n:nat) (p:sinv n) : knot * other -> Prop := fun w =>\n    match w with (existT _ nw w',o) =>\n      match decompose_nat nw n with\n        | inleft (existT _ m Hm) => snd (proj1_sig (floor m (S nw) (eq_rect  n _ p (m + S nw) Hm))) (w',o)\n        | inright H => False\n      end\n    end.\n\n  Lemma floor_shuffle:\n    forall (m1 n : nat)\n      (p1 : sinv (m1 + S n)) (H1 : (m1 + S n) = (S m1 + n)),\n      floor (S m1) n (eq_rect (m1 + S n) sinv p1 (S m1 + n) H1) = fst (proj1_sig (floor m1 (S n) p1)).\n  Proof.\n    intros.\n    remember (fst (proj1_sig (floor m1 (S n) p1))) as p.\n    fold guppy in *.\n    revert n p1 H1 p Heqp.\n    induction m1; simpl; intros.\n    replace H1 with (refl_equal (S n)) by (apply proof_irr); simpl; auto.\n    assert (m1 + S n = S m1 + n) by lia.\n    destruct p1 as [[p1 f'] Hp1]; simpl in *; fold guppy in *.\n    generalize (IHm1 n p1 H p Heqp).\n    clear.\n    revert Hp1 H1; generalize H.\n    revert p1 f'.\n    rewrite H.\n    simpl; intros.\n    replace H1 with (refl_equal (S (S (m1 + n)))) by (apply proof_irr).\n    simpl.\n    replace H0 with (refl_equal (S (m1+n))) in H2 by (apply proof_irr).\n    simpl in H2.\n    trivial.\n  Qed.\n\n  Lemma unstratify_hered : forall n p,\n    hereditary ko_age (unstratify n p).\n  Proof.\n    intros.\n    hnf; intros k k'; intros.\n    simpl in H.\n    destruct k.\n    destruct k as [x f]. destruct x.\n    discriminate.\n    destruct k' as [k' o'].\n    assert (o = o').\n    hnf in H.\n    simpl in H.\n    inv H. auto.\n    subst o'.\n    replace k' with\n      (existT (F oo sinv) x (fmap F (@fst _ _ oo @proj1_sig _ _ ) f)).\n    2: inversion H; auto.\n    clear H.\n    case_eq (decompose_nat x n); intros.\n    destruct s.\n    case_eq (decompose_nat (S x) n); intros.\n    destruct s.\n    destruct n.\n    exfalso; lia.\n    assert (S x1 = x0) by lia; subst x0.\n    revert H0.\n    unfold unstratify.\n    rewrite H; rewrite H1.\n    generalize e e0; revert p; rewrite e0; intros.\n    rewrite floor_shuffle.\n    replace e2 with (refl_equal (x1 + S (S x))) in H0;\n      simpl eq_rect in H0.\n    2: apply proof_irr.\n    change f with (fst (f,o)).\n    change o with (snd (f,o)).\n    eapply app_sinv_age; apply H0.\n\n    revert H0.\n    unfold unstratify.\n    rewrite H; rewrite H1.\n    intuition.\n\n    case_eq (decompose_nat (S x) n); intros.\n    destruct s.\n    exfalso; lia.\n    revert H0.\n    unfold unstratify.\n    rewrite H; rewrite H1; auto.\n  Qed.\n\n  Lemma unstratify_Q : forall n (p:sinv n) Q,\n    stratifies Q n p ->\n    forall (k:knot) o,\n      projT1 k < n ->\n      (unstratify n p (k,o) <-> Q (k,o)).\n  Proof.\n    intros.\n    unfold unstratify.\n    destruct k.\n    destruct (decompose_nat x n).\n    destruct s.\n    simpl in H0.\n    2: simpl in *; exfalso; lia.\n    clear H0.\n    revert p H.\n    generalize e.\n    rewrite e.\n    intros.\n    replace e0 with (refl_equal (x0 + S x)) by apply proof_irr.\n    simpl.\n    clear e e0.\n    revert p H.\n    induction x0; simpl; intros.\n    destruct H.\n    auto.\n    destruct H.\n    apply IHx0.\n    auto.\n  Qed.\n\n  Lemma stratifies_unstratify_more :\n    forall (n m1 m2:nat) (p1:sinv (m1+n)) (p2:sinv (m2+n)),\n      floor m1 n p1 = floor m2 n p2 ->\n      (stratifies (unstratify (m1+n) p1) n (floor m1 n p1) ->\n       stratifies (unstratify (m2+n) p2) n (floor m2 n p2)).\n  Proof.\n    induction n; intuition.\n    split.\n    assert (m2 + S n = S m2 + n) by lia.\n    erewrite <- floor_shuffle.\n    instantiate (1:=H1).\n    replace (unstratify (m2 + S n) p2)\n      with (unstratify (S m2 + n) (eq_rect (m2 + S n) sinv p2 (S m2 + n) H1)).\n    assert (m1 + S n = S m1 + n) by lia.\n    eapply (IHn (S m1) (S m2)\n      (eq_rect (m1 + S n) sinv p1 (S m1 + n) H2)).\n    rewrite floor_shuffle.\n    rewrite floor_shuffle.\n    rewrite H; auto.\n    clear - H0.\n    rewrite floor_shuffle.\n    simpl in H0.\n    destruct H0.\n    clear H0.\n    revert p1 H.\n    generalize H2.\n    rewrite <- H2.\n    intros.\n    replace H0 with (refl_equal (m1 + S n)) by apply proof_irr; auto.\n    clear.\n    revert p2.\n    generalize H1.\n    rewrite H1.\n    intros.\n    replace H0 with (refl_equal (S m2 + n)) by apply proof_irr; auto.\n\n    intros.\n    simpl.\n    destruct (decompose_nat n (m2 + S n)).\n    destruct s.\n    assert (m2 = x).\n    lia.\n    subst x.\n    replace e with (refl_equal (m2 + S n)).\n    simpl; tauto.\n    apply proof_irr.\n    exfalso; lia.\n  Qed.\n\n  Lemma stratify_unstratify : forall n p H,\n    proj1_sig (stratify (unstratify n p) H n) = p.\n  Proof.\n    intros.\n    apply stratifies_unique with (unstratify n p).\n    destruct (stratify _ H n).\n    simpl; auto.\n    clear H.\n    revert p; induction n.\n    simpl; intros; auto.\n    intros.\n    simpl; split.\n\n    assert (stratifies (unstratify n (fst (proj1_sig p))) n (fst (proj1_sig p))).\n    apply IHn.\n    apply (stratifies_unstratify_more n 0 1 (fst (proj1_sig p)) p).\n    simpl; auto.\n    auto.\n\n    intros.\n    destruct (decompose_nat n (S n)).\n    destruct s.\n    assert (x = 0) by lia.\n    subst x.\n    simpl.\n    simpl in e.\n    replace e with (refl_equal (S n)) by apply proof_irr.\n    simpl.\n    split; auto.\n    exfalso; lia.\n  Qed.\n\n\n  Definition strat (n:nat) (p:predicate) : sinv n :=\n    proj1_sig (stratify (proj1_sig p) (proj2_sig p) n).\n\n  Definition unstrat (n:nat) (p:sinv n) : predicate :=\n    exist (hereditary ko_age) (unstratify n p) (unstratify_hered n p).\n\n  Definition squash (x:nat * F predicate) : knot :=\n    match x with (n,f) => existT (F oo sinv) n (fmap F (strat n) f) end.\n\n  Definition unsquash (k:knot) : nat * F predicate :=\n    match k with existT _ n f => (n, fmap F (unstrat n) f) end.\n\n  Definition level (x:knot) : nat := fst (unsquash x).\n  Program Definition approx (n:nat) (p:predicate) : predicate :=\n     fun w => level (fst w) < n /\\ p w.\n  Next Obligation.\n    hnf; simpl; intros.\n    intuition.\n    unfold ko_age, ko_age1 in H.\n    destruct (k_age1 (fst a)) eqn: Hage; inv H; simpl.\n    assert (level k < level (fst a)); [|lia].\n    unfold level, unsquash.\n    destruct a as ((n', ?), ?); simpl in *.\n    destruct n'; inv Hage; simpl in *; lia.\n    destruct p; simpl in *.\n    eapply h; eauto.\n  Qed.\n\n  Lemma strat_unstrat : forall n,\n    strat n oo unstrat n = id (sinv n).\n  Proof.\n    intros; extensionality p.\n    unfold compose, id.\n    unfold strat, unstrat.\n    simpl.\n    rewrite stratify_unstratify.\n    auto.\n  Qed.\n\n  Lemma predicate_eq : forall (p1 p2:predicate),\n    proj1_sig p1 = proj1_sig p2 ->\n    p1 = p2.\n  Proof.\n    intros; destruct p1; destruct p2; simpl in H.\n    subst x0.\n    replace h0 with h by apply proof_irr.\n    auto.\n  Qed.\n\n  Lemma unstrat_strat : forall n,\n    unstrat n oo strat n = approx n.\n  Proof.\n    intros.\n    extensionality.\n    unfold compose.\n    unfold unstrat, strat.\n    unfold approx.\n    apply predicate_eq.\n    simpl.\n    extensionality k.\n    apply prop_ext; intuition.\n    unfold unstratify in H.\n    destruct a.\n    destruct (decompose_nat x0 n).\n    unfold level.\n    simpl.\n    destruct s.\n    lia.\n    elim H.\n    rewrite <- unstratify_Q.\n    apply H.\n    destruct (stratify (proj1_sig x) (proj2_sig x) n); auto.\n    unfold unstratify in H.\n    destruct a; simpl.\n    destruct (decompose_nat x0 n).\n    destruct s; lia.\n    elim H.\n    rewrite unstratify_Q.\n    apply H1.\n    destruct (stratify (proj1_sig x) (proj2_sig x) n); auto.\n    unfold level in H0.\n    destruct a; simpl in *.\n    auto.\n  Qed.\n\n  Lemma squash_unsquash : forall k, squash (unsquash k) = k.\n  Proof.\n    intros.\n    destruct k as [x f]; simpl.\n    f_equal.\n    change ((fmap F (strat x) oo fmap F (unstrat x)) f = f).\n    rewrite fmap_comp.\n    rewrite strat_unstrat.\n    rewrite fmap_id.\n    auto.\n  Qed.\n\n  Lemma unsquash_squash : forall n f,\n    unsquash (squash (n,f)) = (n, fmap F (approx n) f).\n  Proof.\n    intros.\n    unfold unsquash, squash.\n    f_equal.\n    change ((fmap F (unstrat n) oo fmap F (strat n)) f = fmap F (approx n) f).\n    rewrite fmap_comp.\n    rewrite unstrat_strat.\n    auto.\n  Qed.\n\n  Lemma strat_unstrat_Sx : forall x,\n    @fst _ _ oo @proj1_sig _ _ = strat x oo unstrat (S x).\n  Proof.\n    intros.\n    extensionality k.\n    change (sinv (S x)) in k.\n    unfold compose.\n    unfold strat, unstrat.\n    simpl.\n    apply stratifies_unique with (unstratify x (fst (proj1_sig k))).\n    revert k; induction x; simpl; auto.\n    intros.\n    split.\n    eapply (stratifies_unstratify_more x 0 1 ).\n    simpl; reflexivity.\n    simpl.\n    apply IHx.\n    intros.\n    destruct (decompose_nat x (S x)).\n    destruct s.\n    assert (x0 = 0) by lia; subst x0.\n    simpl in *.\n    replace e with (refl_equal (S x)) by apply proof_irr; simpl.\n    tauto.\n    exfalso; lia.\n    destruct (stratify (unstratify (S x) k)\n      (unstratify_hered (S x) k) x).\n    simpl; auto.\n    cut (x0 = (fst (proj1_sig k))); intros.\n    subst x0.\n    eapply (stratifies_unstratify_more x 1 0).\n    simpl; reflexivity.\n    simpl; auto.\n    eapply stratifies_unique.\n    apply s.\n    eapply (stratifies_unstratify_more x 0 1).\n    simpl; reflexivity.\n    simpl.\n    generalize (fst (proj1_sig k) : sinv x).\n    clear.\n    induction x; simpl; intuition.\n    eapply (stratifies_unstratify_more x 0 1).\n    simpl; reflexivity.\n    simpl.\n    apply IHx.\n    destruct (decompose_nat x (S x)).\n    destruct s0.\n    assert (x0 = 0) by lia; subst.\n    simpl in *.\n    replace e with (refl_equal (S x)); simpl; auto.\n    apply proof_irr.\n    lia.\n    destruct (decompose_nat x (S x)).\n    destruct s0.\n    assert (x0 = 0) by lia; subst.\n    simpl in *.\n    replace e with (refl_equal (S x)) in H; simpl; auto.\n    apply proof_irr.\n    elim H.\n  Qed.\n\n  Lemma unsquash_inj : forall k k',\n    unsquash k = unsquash k' -> k = k'.\n  Proof.\n    intros.\n    rewrite <- (squash_unsquash k).\n    rewrite <- (squash_unsquash k').\n    congruence.\n  Qed.\n\n  Lemma knot_age_age1 : forall k k',\n    k_age1 k = Some k' <->\n    match unsquash k with\n    | (O,_) => None\n    | (S n,x) => Some (squash (n,x))\n    end = Some k'.\n  Proof.\n    split; intros.\n    unfold k_age1 in H.\n    unfold unsquash in H.\n    destruct k as [x f].\n    destruct x; auto.\n    inv H.\n    simpl.\n    f_equal.\n    f_equal.\n    change (fmap F (strat x) (fmap F (unstrat (S x)) f))\n      with ((fmap F (strat x) oo fmap F (unstrat (S x))) f).\n    rewrite fmap_comp.\n    simpl.\n    f_equal.\n    symmetry.\n    apply (strat_unstrat_Sx x).\n\n    simpl in H.\n    destruct k.\n    destruct x.\n    discriminate.\n    inv H.\n    hnf; simpl.\n    unfold k_age1.\n    f_equal.\n    f_equal.\n    rewrite strat_unstrat_Sx.\n    rewrite <- fmap_comp.\n    auto.\n  Qed.\n\n  #[global] Program Instance ag_knot : ageable knot :=\n  { age1 := k_age1\n  ; level := level\n  }.\n  Next Obligation.\n    econstructor.\n    (* unage *)\n    intros.\n    destruct (unsquash x') as [n f] eqn:?H; intros.\n    exists (squash (S n, f)).\n    rewrite knot_age_age1.\n    rewrite unsquash_squash.\n    f_equal.\n    apply unsquash_inj.\n    rewrite unsquash_squash.\n    rewrite H.\n    f_equal.\n    cut (f = fmap F (approx n) f).\n    intros.\n    rewrite fmap_app.\n    pattern f at 2. rewrite H0.\n    f_equal.\n    extensionality p.\n    apply predicate_eq.\n    extensionality w.\n    simpl. apply prop_ext.\n    intuition.\n    generalize H; intro.\n    rewrite <- (squash_unsquash x') in H.\n    rewrite H0 in H.\n    rewrite unsquash_squash in H.\n    congruence.\n\n    (* level 0 *)\n    intro x. destruct x; simpl.\n    destruct x; intuition; discriminate.\n\n    (* level S *)\n    intros. destruct x; simpl in *.\n    destruct x. discriminate.\n    inv H. simpl. auto.\n  Qed.\n\n  #[global] Existing Instance ag_prod.\n\n  Lemma approx_spec : forall n p (k:knot * other),\n    proj1_sig (approx n p) k = (ageable.level k < n /\\ proj1_sig p k).\n  Proof.\n    intros.\n    apply prop_ext.\n    unfold approx; simpl.\n    intuition; simpl in *; auto.\n  Qed.\n\n  Lemma knot_level : forall k:knot, level k = fst (unsquash k).\n  Proof. reflexivity. Qed.\n\n  Lemma knot_age1 : forall k,\n    age1 k =\n    match unsquash k with\n    | (O,_) => None\n    | (S n,x) => Some (squash (n,x))\n    end.\n  Proof.\n    intros. simpl.\n    case_eq (k_age1 k). intros.\n    rewrite knot_age_age1 in H.\n    auto.\n    destruct k; simpl. destruct x. auto.\n    intros. discriminate.\n  Qed.\n\n  #[export] Program Instance ext_knot : Ext_ord knot := { ext_order := eq }.\n  Next Obligation.\n  Proof.\n    intros ?????; subst; eauto.\n  Qed.\n  Next Obligation.\n  Proof.\n    eauto.\n  Qed.\n\nEnd KnotHered.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/msl/knot_hered.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.2574799024313704}}
{"text": "(* Distributed under the terms of the MIT license. *)\nFrom MetaCoq.Utils Require Import utils.\nFrom MetaCoq.Template Require Import All.\nFrom MetaCoq.Translations Require Import translation_utils.\nImport MCMonadNotation.\n\nLocal Infix \"<=\" := Nat.leb.\n\nDefinition default_term   := tVar \"constant_not_found\".\nDefinition debug_term msg := tVar (\"debug: \" ^ msg).\n\nFixpoint tsl_rec0 (n : nat) (o : nat) (t : term) {struct t} : term :=\n  match t with\n  | tRel k => if n <= k then (* global variable *) tRel (3 * (k - n) + n + o)\n                        else (* local  variable *) t\n  | tEvar k ts   => tEvar k (map (tsl_rec0 n o) ts)\n  | tCast t c a  => tCast (tsl_rec0 n o t) c (tsl_rec0 n o a)\n  | tProd na A B => tProd na (tsl_rec0 n o A) (tsl_rec0 (n+1) o B)\n  | tLambda na A t  => tLambda na (tsl_rec0 n o A) (tsl_rec0 (n+1) o t)\n  | tLetIn na t A u => tLetIn na (tsl_rec0 n o t) (tsl_rec0 n o A) (tsl_rec0 (n+1) o u)\n  | tApp t lu       => tApp (tsl_rec0 n o t) (map (tsl_rec0 n o) lu)\n  | tCase ik t u br => tCase ik (map_predicate_k id (fun k => tsl_rec0 n k) o t) (tsl_rec0 n o u)\n                            (map_branches_k (fun x => tsl_rec0 n x) o br)\n  | tProj p t => tProj p (tsl_rec0 n o t)\n  (* | tFix : mfixpoint term -> nat -> term *)\n  (* | tCoFix : mfixpoint term -> nat -> term *)\n  | _ => t\n  end.\n\n\nDefinition suffix0 (n : name) s : name :=\n  match n with\n  | BasicAst.nAnon     => BasicAst.nAnon\n  | BasicAst.nNamed id => BasicAst.nNamed (id ^ s)\n  end.\n\nDefinition nAnon := {| binder_name := BasicAst.nAnon; binder_relevance := Relevant |}.\nDefinition nNamed n := {| binder_name := BasicAst.nNamed n; binder_relevance := Relevant |}.\n\nDefinition suffix na n := map_binder_annot (fun na => suffix0 na n) na.\n\n\nFixpoint apply (app : list term) (t : term) :=\n  match app with\n  | t' :: app =>  apply app (mkApp t (t' {3 := tRel 1} {2 := tRel 0}))\n  | [] => t\n  end.\n\nFixpoint tsl_rec1_app (app : list term) (E : tsl_table) (t : term) : term :=\n  let tsl_rec1 := tsl_rec1_app [] in\n  let debug case symbol :=\n      debug_term (\"tsl_rec1: \" ^ case ^ \" \" ^ symbol ^ \" not found\") in\n  match t with\n  | tLambda na A t =>\n      let A0 := tsl_rec0 0 2 A in\n      let A1 := tsl_rec1 E A in\n\n      tLambda (suffix na \"₁\") A0\n        (tLambda (suffix na \"₂\") A0\n          (tLambda (tsl_name tsl_ident na)\n            (subst_app (lift0 2 A1) [tRel 1; tRel 0])\n            (tsl_rec1_app (map (lift 3 3) app) E t)))\n\n  | _ => let t1 :=\n  match t with\n  | tSort s =>\n      tLambda (nNamed \"x₁\") (tSort s)\n        (tLambda (nNamed \"x₂\") (tSort s)\n          (tProd nAnon (tRel 1) (tProd nAnon (tRel 1) (tSort s))))\n\n  | tRel k => tRel (3 * k)\n\n  | tProd na A B =>\n      let A0 := tsl_rec0 0 2 A in\n      let B0 := tsl_rec0 1 2 B in\n      let A1 := tsl_rec1 E A in\n      let B1 := tsl_rec1 E B in\n      let ΠAB0 := tProd na A0 B0 in\n\n      tLambda (nNamed \"f₁\") ΠAB0\n        (tLambda (nNamed \"f₂\") ΠAB0\n          (tProd (suffix na \"₁\") (lift0 2 A0)\n            (tProd (suffix na \"₂\") (lift0 2 A0)\n              (tProd (tsl_name tsl_ident na)\n                (subst_app (lift0 4 A1) [tRel 1; tRel 0])\n                (subst_app (lift 2 3 B1) [tApp (tRel 4) [tRel 2]; tApp (tRel 3) [tRel 1]])))))\n\n  | tApp t us =>\n      let us' := concat (map (fun v => [tsl_rec0 0 2 v; tsl_rec0 0 1 v; tsl_rec1 E v]) us) in\n      mkApps (tsl_rec1 E t) us'\n\n  | tCast t c A =>\n      let t0 := tsl_rec0 0 2 t in\n      let t1 := tsl_rec1 E t in\n      let A0 := tsl_rec0 0 2 A in\n      let A1 := tsl_rec1 E A in\n      tCast t1 c (mkApps A1 [tCast t0 c A0])\n\n  | tConst s univs =>\n    match lookup_tsl_table E (ConstRef s) with\n    | Some t => t\n    | None => debug \"tConst\" (string_of_kername s)\n    end\n\n  | tInd i univs =>\n    match lookup_tsl_table E (IndRef i) with\n    | Some t => t\n    | None => debug \"tInd\" (match i with mkInd s _ => string_of_kername s end)\n    end\n\n  | tConstruct i n univs =>\n    match lookup_tsl_table E (ConstructRef i n) with\n    | Some t => t\n    | None => debug \"tConstruct\" (match i with mkInd s _ => string_of_kername s end)\n    end\n\n  | tCase ik t u brs as case =>\n    case\n    (* todo \"case\", but probably already wrong before\n      let brs' := (map_branches_k (fun x => lift x 0) 1 brs) in\n    let case1 := tCase ik (map_predicate_k id (fun x => lift x 0) 3 t) (tRel 2) brs' in\n    let case2 := tCase ik (map_predicate_k id (fun x => lift x 0) 3 t) (tRel 1) brs' in\n       match lookup_tsl_table E (IndRef ik.(ci_ind)) with\n      | Some (tInd i _univ) =>\n        let ci' := {| ci_ind := i; ci_npar := 3 * ci.(ci_npar); ci_relevance := ci.(ci_relevance) |} in\n        tCase ci'\n              (tsl_rec1_app [tsl_rec0 0 2 case1; tsl_rec0 0 1 case2] E t)\n              (tsl_rec1 E u)\n              (map (on_snd (tsl_rec1 E)) brs)\n      | _ => debug \"tCase\" (match ik.(ci_ind) with mkInd s _ => string_of_kername s end)\n      end*)\n\n  | tLetIn na t A u =>\n    let t0 := tsl_rec0 0 2 t in\n    let A0 := tsl_rec0 0 2 A in\n    let t1 := tsl_rec1 E t in\n    let A1 := tsl_rec1 E A in\n    let u1 := tsl_rec1 E u in\n    tLetIn (suffix na \"₁\") t0 A0 (\n      tLetIn (suffix na \"₂\") (lift0 1 t0) (lift0 1 A0) (\n        tLetIn (tsl_name tsl_ident na) (lift0 2 t1)\n          (subst_app (lift0 2 A1) [tRel 1; tRel 0]) u1))\n\n  | tProj _ _ => todo \"tsl\"\n  | tFix _ _ | tCoFix _ _ => todo \"tsl\"\n  | tVar _ | tEvar _ _ => todo \"tsl\"\n  | tLambda _ _ _ => tVar \"impossible\"\n  | tInt _ | tFloat _ => todo \"tsl\"\n  end\n  in apply app t1\n  end.\n\nDefinition tsl_rec1 := tsl_rec1_app [].\n\nDefinition tsl_mind_body (E : tsl_table) (mp : modpath) (kn : kername)\n           (mind : mutual_inductive_body) : tsl_table * list mutual_inductive_body.\n  refine (_, [{| ind_npars := 3 * mind.(ind_npars);\n                 ind_params := _;\n                 ind_bodies := _;\n                 ind_universes := mind.(ind_universes);\n                 ind_variance := mind.(ind_variance)|}]).  (* FIXME always ok? *)\n  - refine (let kn' : kername := (mp, tsl_ident kn.2) in\n            fold_left_i (fun E i ind => _ :: _ ++ E) mind.(ind_bodies) []).\n    + (* ind *)\n      exact (IndRef (mkInd kn i), tInd (mkInd kn' i) []).\n    + (* ctors *)\n      refine (fold_left_i (fun E k _ => _ :: E) ind.(ind_ctors) []).\n      exact (ConstructRef (mkInd kn i) k, tConstruct (mkInd kn' i) k []).\n  - exact mind.(ind_finite).\n  - (* params: 2 times the same parameters? Probably wrong *)\n    refine (mind.(ind_params) ++ mind.(ind_params) ++ mind.(ind_params)).\n  - refine (mapi _ mind.(ind_bodies)).\n    intros i ind.\n    refine {| ind_name := tsl_ident ind.(ind_name);\n              ind_indices := ind.(ind_indices);\n              ind_sort := ind.(ind_sort);\n              ind_type := _;\n              ind_kelim := ind.(ind_kelim);\n              ind_ctors := _;\n              ind_projs := [];\n              ind_relevance := ind.(ind_relevance) |}. (* UGLY HACK!!! todo *)\n    + (* arity  *)\n      refine (let ar := subst_app (tsl_rec1 E ind.(ind_type))\n                                  [tInd (mkInd kn i) []; tInd (mkInd kn i) []] in\n              ar).\n    + (* constructors *)\n      refine (mapi _ ind.(ind_ctors)).\n      intros k [name args indices type arity].\n      econstructor.\n      refine (tsl_ident name).\n      refine args.\n      refine indices.\n      refine (subst_app _ [tConstruct (mkInd kn i) k []; tConstruct (mkInd kn i) k []]).\n      refine (fold_left_i (fun t0 i u => t0 {S i := u} {S i := u}) _ (tsl_rec1 E type)).\n      (* [I_0; ... I_(n-1)] *)\n\n      refine (rev (mapi (fun i _ => tInd (mkInd kn i) [])\n                              mind.(ind_bodies))).\n      refine (3 * arity)%nat.\n\nDefined.\n\n#[global]\nInstance param : Translation :=\n  {| tsl_id := tsl_ident ;\n     tsl_tm := fun ΣE t => ret (tsl_rec1 (snd ΣE) t) ;\n     (* Implement and Implement Existing cannot be used with this translation *)\n     tsl_ty  := None ;\n     tsl_ind := fun ΣE mp kn mind => ret (tsl_mind_body (snd ΣE) mp kn mind) |}.\n\n(* EXAMPLES *)\n\nMetaCoq Run (\n  typ <- tmQuote (forall A, A -> A) ;;\n  typ' <- tmEval all (tsl_rec1 [] typ) ;;\n  tm <- tmQuote (fun A (x : A) => x) ;;\n  tm' <- tmEval all (tsl_rec1 [] tm) ;;\n  tmUnquote (tApp typ' [tm; tm]) >>= tmDebug ;;\n  tmUnquote tm' >>= tmDebug\n).\n\nSet Warnings \"-unexpected-implicit-declaration\".\nMetaCoq Run (\n  typ <- tmQuote (forall A B, B -> (A -> B -> B) -> B) ;;\n  typ' <- tmEval all (tsl_rec1 [] typ) ;;\n  t   <- tmQuote (fun {A B} (x:B) (f : A -> B -> B) => x) ;;\n  t'  <- tmEval all (tsl_rec1 [] t) ;;\n  tmUnquote (tApp typ' [t; t]) >>= tmDebug\n).\n\nMetaCoq Run (TC <- Translate emptyTC \"nat\" ;;\n                     tmDefinition \"nat_TC\" TC).\n\nMetaCoq Run (TC <- Translate nat_TC \"bool\" ;;\n                     tmDefinition \"bool_TC\" TC).\n\nMetaCoq Run (TC <- Translate bool_TC \"list\" ;;\n                     tmDefinition \"list_TC\" TC).\n\nModule FreeTheorems.\n\n  Definition HD := forall X, list X -> X.\n  MetaCoq Run (Translate list_TC \"HD\").\n\n  Definition MAP := forall X, list X -> list X.\n  MetaCoq Run (Translate list_TC \"MAP\").\n\n  (* taken from coq-community/paramcoq *)\n  Definition graph {A B} (f : A -> B) := fun x y => f x = y.\n  Definition map_rel {A B} (f : A -> B) := listᵗ A B (graph f).\n\n  Definition map_rel_map A B (f : A -> B) :\n    forall (l : list A), map_rel f l (map f l).\n  induction l; constructor; compute; auto.\n  Defined.\n\n  Lemma rel_map_map A B (f : A -> B) :\n    forall (l : list A) fl, map_rel f l fl -> fl = map f l.\n  intros l fl H. induction H; unfold graph in *; subst; auto.\n  Defined.\n\n  Definition FREE_THEOREM (F : MAP) :=\n    forall A B (f : A -> B) l,\n      F B (map f l) = map f (F A l).\n\n  Lemma param_map :\n    forall F (H : MAPᵗ F F), FREE_THEOREM F.\n  Proof.\n    repeat intro.\n    apply rel_map_map.\n    apply H.\n    apply map_rel_map.\n  Qed.\n\nEnd FreeTheorems.\n", "meta": {"author": "MetaCoq", "repo": "metacoq", "sha": "c340242b43ebe26f3bacb1c72ef82b8ca61da632", "save_path": "github-repos/coq/MetaCoq-metacoq", "path": "github-repos/coq/MetaCoq-metacoq/metacoq-c340242b43ebe26f3bacb1c72ef82b8ca61da632/translations/param_binary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.257479895177098}}
{"text": "Require Import UFO.Rel.Definitions.\nRequire Import UFO.Rel.Adequacy.\nRequire Import UFO.Rel.Compatability.\nRequire Import UFO.Rel.Parametricity.\nRequire Import UFO.Lang.BindingsFacts.\nRequire Import UFO.Lang.Static.\nRequire Import UFO.Lang.StaticFacts.\nRequire Import UFO.Lang.Xs.\nRequire Import UFO.Lang.SigFacts.\nRequire Import UFO.Lang.Context.\nRequire Import FunctionalExtensionality.\n\nImplicit Types EV LV V L : Set.\n\nSection section_congruence.\n\nHint Resolve ok_wf_lbl ok_wf_ty ok_wf_eff ok_wf_tm.\nHint Resolve XLEnv_inv_wf_XEnv.\nHint Resolve EV_map_XLEnv LV_map_XLEnv.\nHint Unfold compose.\n\nFixpoint\ncongruence_tm n EV LV V L (t₁ t₂ : tm EV LV V L)\n(Π : LEnv EV LV L) (Γ : V → ty ∅ EV LV L)\n(T : ty ∅ EV LV L) (E : eff ∅ EV LV L) (T0 : ty0)\nC (OK_C : ok_ctx C Γ Π T E T0) {struct OK_C} :\nn ⊨ 【 Π Γ ⊢ t₁ ≼ˡᵒᵍ t₂ : T # E 】 →\nn ⊨ 【 LEnv_empty ∅→ ⊢ (ctx_plug C t₁) ≼ˡᵒᵍ (ctx_plug C t₂) : T0 # [] 】\nwith\ncongruence_md n EV LV V L (m₁ m₂ : md EV LV V L)\n(Π : LEnv EV LV L) (Γ : V → ty ∅ EV LV L)\n(β : L) (σ : ms ∅ EV LV L) (T0 : ty0)\nD (OK_D : ok_dtx D Γ Π β σ T0) {struct OK_D} :\nn ⊨ 【 Π Γ ⊢ m₁ ≼ˡᵒᵍₘ m₂ : σ ^ (lbl_id (lid_b β)) 】 →\nn ⊨ 【 LEnv_empty ∅→ ⊢ (dtx_plug D m₁) ≼ˡᵒᵍ (dtx_plug D m₂) : T0 # [] 】\n.\nProof.\n{\nintro H.\ndestruct OK_C as [ | ???? D ???????? OK_D | ???? C | ???? C ?? T E | ???? C |\n  ???? C t ??????? OK_t | ???? C s ??????? OK_s | ???? C s ???????? OK_s |\n  ???? C t ???????? OK_t | ???? C E₁ | ???? C ℓ₁ |\n  ???? C s ???????? OK_s | ???? C t ???????? OK_t | ???? C\n] ; (simpl ctx_plug || simpl dtx_plug).\n+ apply H ; rewrite empty_def ; try rewrite keys_def ;\n    try rewrite map_nil ; simpl ; shelve.\n+ eapply congruence_md ; [exact OK_D|].\n  iintro Ξ ; iintro f ; iintro HΞΠ.\n  iespecialize H ; ispecialize H ; [eauto|].\n  simpl ; destruct (f β) as [|X] eqn:EQ_fβ ; [auto|].\n  eapply compat_md_res ; [ eauto using LEnv_lookup_inv_binds | ].\n  match goal with\n  | [ H : ?n ⊨ ⟦ _ ?Γ ⊢ _ ≼ˡᵒᵍ _ : _ # _ ⟧ |- ?n ⊨ ⟦ _ ?Γ' ⊢ _ ≼ˡᵒᵍ _ : _ # _ ⟧ ] =>\n    replace Γ' with Γ ; [ exact H | ]\n  end.\n  extensionality x ; crush.\n+ eapply congruence_tm ; [exact OK_C|].\n  iintro Ξ ; iintro f ; iintro HΞΠ.\n  iespecialize H ; ispecialize H ; [exact HΞΠ|].\n  simpl L_bind_ty ; simpl L_bind_tm.\n  rewrite L_bind_it_msig.\n  apply compat_tm_op.\n  apply H.\n+ eapply congruence_tm ; [exact OK_C|].\n  iintro Ξ ; iintro f ; iintro HΞΠ.\n  iespecialize H ; ispecialize H ; [exact HΞΠ|].\n  simpl ; rewrite <- L_bind_eff_app.\n  apply compat_tm_up ; exact H.\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_let ; [|exact H].\n  apply SI_LN_parametricity_tm ; [ eauto | intro ; eauto | ].\n  eapply ok_wf_tm in OK_t ; [|eauto].\n  match goal with\n  | [ H : wf_tm ?Ξ ?Γ ?t ?T ?E |- wf_tm ?Ξ ?Γ' ?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 SI_LN_parametricity_tm ; [ 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_throw ; [exact H|].\n  apply SI_LN_parametricity_tm ; [ 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_throw ; [|exact H].\n  apply SI_LN_parametricity_tm ; [ 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  simpl in H|-*.\n  erewrite <- EV_L_bind_ms ; [ eapply compat_tm_app_eff ; exact H | 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 <- LV_L_bind_ms ; [ eapply compat_tm_app_lbl ; 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  eapply compat_tm_app_tm ; [exact H|].\n  eapply SI_LN_parametricity_tm ; [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|-*.\n  eapply compat_tm_app_tm ; [|exact H].\n  eapply SI_LN_parametricity_tm ; [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 (E := L_bind_eff f E1) ; eauto using subty_st, L_bind_se.\n}\n{\nintro H.\ndestruct OK_D as [ ???? C ????? OK_C | ???? D ????? OK_D |\n  ???? D ????? OK_D | ???? D ?????? OK_D ] ; (simpl ctx_plug || simpl dtx_plug).\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  apply compat_tm_val.\n  destruct (f β) as [α|X] eqn:EQ_fβ ; simpl in H|-* ; [destruct α|].\n  apply compat_val_md ; apply H.\n+ eapply congruence_md ; [exact OK_D|].\n  iintro Ξ ; iintro f ; iintro HΞΠ ; ielim_prop HΞΠ.\n  iespecialize H ; ispecialize H ; [eauto|].\n  simpl in H|-*.\n  apply compat_md_ev.\n  match goal with\n  | [ H : ?n ⊨ ⟦ _ ?Γ ⊢ _ ≼ˡᵒᵍₘ _ : _ ^ _ ⟧ |- ?n ⊨ ⟦ _ ?Γ' ⊢ _ ≼ˡᵒᵍₘ _ : _ ^ _ ⟧ ] =>\n    replace Γ' with Γ ; [ exact H | ]\n  end.\n  extensionality x ; auto using L_bind_EV_map_ty.\n+ eapply congruence_md ; [exact OK_D|].\n  iintro Ξ ; iintro f ; iintro HΞΠ ; ielim_prop HΞΠ.\n  iespecialize H ; ispecialize H ; [eauto|].\n  simpl in H|-*.\n  apply compat_md_lv.\n  match goal with\n  | [ H : ?n ⊨ ⟦ _ ?Γ ⊢ _ ≼ˡᵒᵍₘ _ : _ ^ _ ⟧ |- ?n ⊨ ⟦ _ ?Γ' ⊢ _ ≼ˡᵒᵍₘ _ : _ ^ _ ⟧ ] =>\n    replace Γ' with Γ ; [ exact H | ]\n  end.\n  extensionality x ; auto using L_bind_LV_map_ty.\n+ eapply congruence_md ; [exact OK_D|].\n  iintro Ξ ; iintro f ; iintro HΞΠ ; ielim_prop HΞΠ.\n  iespecialize H ; ispecialize H ; [eauto|].\n  simpl in H|-*.\n  apply compat_md_tm.\n  match goal with\n  | [ H : ?n ⊨ ⟦ _ ?Γ ⊢ _ ≼ˡᵒᵍₘ _ : _ ^ _ ⟧ |- ?n ⊨ ⟦ _ ?Γ' ⊢ _ ≼ˡᵒᵍₘ _ : _ ^ _ ⟧ ] =>\n    replace Γ' with Γ ; [ exact H | ]\n  end.\n  extensionality x ; auto.\n}\nQed.\n\nEnd section_congruence.\n\nSection section_soundness.\n\nHint Rewrite dom_empty union_empty_l Xs_ctx_plug.\n\nTheorem soundness EV LV V L (t₁ t₂ : tm EV LV V L) (Closed_t₁ : Xs_tm t₁ = \\{})\n(Π : LEnv EV LV L) (Γ : V → ty ∅ EV LV L)\n(T : ty ∅ EV LV L) (E : eff ∅ EV LV L) :\n⊨ 【 Π Γ ⊢ t₁ ≼ˡᵒᵍ t₂ : T # E 】 →\n【 Π Γ ⊢ t₁ ≼ᶜᵗˣ t₂ : T # E 】.\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\nFact unfold_log_eq_I_valid EV LV V L (t₁ t₂ : tm EV LV V L)\n(Π : LEnv EV LV L) (Γ : V → ty ∅ EV LV L)\n(T : ty ∅ EV LV L) (E : eff ∅ EV LV L) :\n(⊨ 【 Π Γ ⊢ t₁ ≈ˡᵒᵍ t₂ : T # E 】) →\n(⊨ 【 Π Γ ⊢ t₁ ≼ˡᵒᵍ t₂ : T # E 】) ∧ (⊨ 【 Π Γ ⊢ t₂ ≼ˡᵒᵍ t₁ : T # E 】).\nProof.\nintro H ; split ; intro n ; specialize (H n) ; idestruct H as H1 H2 ; assumption.\nQed.\n\nTheorem soundness_eq EV LV V L (t₁ t₂ : tm EV LV V L)\n(Closed_t₁ : Xs_tm t₁ = \\{}) (Closed_t₂ : Xs_tm t₂ = \\{})\n(Π : LEnv EV LV L) (Γ : V → ty ∅ EV LV L)\n(T : ty ∅ EV LV L) (E : eff ∅ EV LV L) :\n⊨ 【 Π Γ ⊢ t₁ ≈ˡᵒᵍ t₂ : T # E 】 →\n【 Π Γ ⊢ t₁ ≈ᶜᵗˣ t₂ : T # E 】.\nProof.\nintro H.\napply unfold_log_eq_I_valid in H ; destruct H as [H1 H2].\nsplit ; apply soundness ; assumption.\nQed.\n\nEnd section_soundness.\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/Soundness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.25746918114417666}}
{"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 *)\nSet Implicit Arguments.\n\nRequire Import ZArith List.\nRequire Import Monad vgtac VocabA Syn InterCfg DStr DLat DItv DPos\n        UserInputType.\nRequire Import DomBasic DomArrayBlk DomAbs DomMem SemEval SemAbs.\n\nLocal Open Scope sumbool.\n\nInductive query' : Type :=\n| ArrayExp (lv : lval) (e : exp)\n| DerefExp (e : exp).\nDefinition query : Type := query'.\n\nInductive status' := Proven | UnProven | BotAlarm.\n\nDefinition status : Type := status'.\n\n(** ** Collect alarm expressions *)\n\nFixpoint add_offset (o : offset) (orig_offset : offset) : offset :=\n  match orig_offset with\n  | NoOffset => o\n  | FOffset f o1 => FOffset f (add_offset o o1)\n  | IOffset e o1 => IOffset e (add_offset o o1)\n  end.\n\nDefinition lval_append_field (lv : lval) (f : vid_t) : lval :=\n  match lv with\n  | lval_intro lh o pos =>\n    lval_intro lh (add_offset (FOffset f NoOffset) o) pos\n  end.\n\nDefinition lval_append_index (lv : lval) (e : exp) : lval :=\n  match lv with\n  | lval_intro lh o pos =>\n    lval_intro lh (add_offset (IOffset e NoOffset) o) pos\n  end.\n\nFixpoint c_offset (lv : lval) (ofs : offset) (pos : DPos.t)\n: list (query * DPos.t) :=\n  match ofs with\n  | NoOffset => nil\n  | FOffset f o => c_offset (lval_append_field lv f) o pos\n  | IOffset e o =>\n    (ArrayExp lv e, pos)\n      :: c_exp e ++ c_offset (lval_append_index lv e) o pos\n  end\n\nwith c_lv (lv : lval) : list (query * DPos.t) :=\n  match lv with\n  | lval_intro (VarLhost v is_g) ofs pos =>\n    c_offset (lval_intro (VarLhost v is_g) NoOffset pos) ofs pos\n  | lval_intro (MemLhost e) ofs pos =>\n    (DerefExp e, pos)\n      :: c_exp e\n      ++ c_offset (lval_intro (MemLhost e) NoOffset pos) ofs pos\n  end\n\nwith c_exp (e : exp) : list (query * DPos.t) :=\n  match e with\n  | Lval lv _ => c_lv lv\n  | AlignOfE e _ => c_exp e\n  | UnOp _ e _ => c_exp e\n  | BinOp _ e1 e2 _ => c_exp e1 ++ c_exp e2\n  | CastE _ e _ => c_exp e\n  | AddrOf lv _ => c_lv lv\n  | StartOf lv _ => c_lv lv\n  | _ => nil\n  end.\n\nDefinition c_alloc (alloc : alloc) : list (query * DPos.t) :=\n  match alloc with\n  | Array e => c_exp e\n  end.\n\nDefinition c_exps (exps : list exp) : list (query * DPos.t) :=\n  list_fold (fun e q => c_exp e ++ q) exps nil.\n\nDefinition collect_query (cmd : cmd) : list (query * DPos.t) :=\n  match cmd with\n  | Cset lv e _ => c_lv lv ++ c_exp e\n  | Cexternal lv _ => c_lv lv\n  | Calloc lv a _ => c_lv lv ++ c_alloc a\n  | Csalloc lv _ _ => c_lv lv\n  | Cassume e _ => c_exp e\n  | Ccall None e es _ => c_exp e ++ c_exps es\n  | Ccall (Some lv) e es _ => c_lv lv ++ c_exp e ++ c_exps es\n  | Creturn (Some e) _ => c_exp e\n  | _ => nil\n  end.\n\nLoad AlarmType.\n\nModule Alarm (Import M : Monad) (MB : MemBasic M) <: ALARM M MB.\n\nModule Import SemMem := SemMem.Make M MB.\n\nModule Import SemEval := SemEval.Make M MB.\n\nModule Import Run := SemAbs.Run M MB.\n\nSection Alarm.\n\nVariable mode : update_mode.\n\nDefinition check_bo arr i : list status :=\n  if ArrayBlk.eq_dec arr ArrayBlk.bot then BotAlarm :: nil else\n    let check_bo' a ofs_size lst :=\n      let '(ofs, size, _) := ofs_size in\n      let ofs := Itv.plus ofs i in\n      let status :=\n        match ofs, size with\n        | Itv.Bot, _\n        | _, Itv.Bot => BotAlarm\n        | @Itv.V (Itv.Int ol) (Itv.Int oh) _ _ _, @Itv.V (Itv.Int sl) _ _ _ _ =>\n          if Z_ge_dec ol 0%Z &&& Z_lt_dec oh sl then Proven else UnProven\n        | _, _ => UnProven\n        end in\n      status :: lst in\n    ArrayBlk.foldi check_bo' arr nil.\n\nDefinition make_bot_proven status :=\n  match status with\n    | BotAlarm => Proven\n    | _ => status\n  end.\n\nDefinition check_query (node : InterNode.t) (mem : Mem.t) (q : query)\n: m (list status) :=\n  match q with\n  | ArrayExp lv e =>\n    do lvs <- SemEval .eval_lv mode node lv mem ;\n    do v1 <- mem_lookup lvs mem ;\n    do v2 <- eval mode node e mem ;\n    ret (check_bo (array_of_val v1) (itv_of_val v2))\n  | DerefExp e =>\n    do v <- eval mode node e mem ;\n    let statuses := check_bo (array_of_val v) Itv.zero in\n    let r :=\n        if Val.eq_dec v Val.bot then statuses else\n          List.map make_bot_proven statuses\n    in\n    ret r\n  end.\n\nEnd Alarm.\n\nEnd Alarm.\n\nLocal Close Scope sumbool.\n", "meta": {"author": "ropas", "repo": "zooberry", "sha": "17b1cb1a44c2a796d6b7d85c2026b142685d291b", "save_path": "github-repos/coq/ropas-zooberry", "path": "github-repos/coq/ropas-zooberry/zooberry-17b1cb1a44c2a796d6b7d85c2026b142685d291b/spec/ItvInput/Query.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.25746918114417666}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Import Tweetnacl_verif.init_tweetnacl.\nRequire Import Tweetnacl_verif.spec_Z.\nRequire Import Tweetnacl.Libs.Export.\nRequire Import Tweetnacl.ListsOp.Export.\nRequire Import Tweetnacl.Low.Z.\n\nOpen Scope Z.\n\nDefinition Gprog : funspecs :=\n      ltac:(with_library prog [Z_spec]).\nImport Low.\n\nLemma body_Z: semax_body Vprog Gprog f_Z Z_spec.\nProof.\nstart_function.\nunfold nm_overlap_array_sep_3, nm_overlap_array_sep_3' in *.\nassert(HA: Zlength (Z a b) = 16). rewrite Zub_Zlength ; omega.\nassert(HmA: Zlength (mVI64 (Z a b)) = 16). rewrite ?Zlength_map //.\nassert(Forall (fun x : ℤ => amin - bmax < x < amax - bmin) (Z a b)).  apply Zub_bound_Zlength_lt ; trivial ; omega.\nassert(Htkdp: tkdp 16 (mVI64 (Z a b)) o = mVI64 (Z 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 (Z 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) (Z a b) ++ skipn (nat_of_Z i) a) with (tkdp i (Z 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 (Z 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) (Z a b) ++ skipn (nat_of_Z i) a) with (tkdp i (Z 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 (Z_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 (Z_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 (Z_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 (Z_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 (Z_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 ; rewrite -?HHaux1 -?HHaux2 -?HHaux3 -?HHaux4 ; [entailer!|].\nall: forward ; rewrite -?HHaux1 -?HHaux2 -?HHaux3 -?HHaux4 ; [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 Z.\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 sub64_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 /Z in HA, HmA.\nall: rewrite (upd_Znth_app_step_Zlength _ _ _ Vundef); try omega.\n\nall: f_equal ; rewrite map_map (Znth_map 0) ?Znth_nth ; try reflexivity.\nall: omega.\nQed.\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_Z.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.25746918114417666}}
{"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 RmiAux.Layer.\nRequire Import RmiAux2.Code.init_rec_rvic_state.\n\nRequire Import RmiAux2.LowSpecs.init_rec_rvic_state.\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    _set_rvic_mask_bits ↦ gensem set_rvic_mask_bits_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_set_rvic_mask_bits: block.\n    Hypothesis h_set_rvic_mask_bits_s : Genv.find_symbol ge _set_rvic_mask_bits = Some b_set_rvic_mask_bits.\n    Hypothesis h_set_rvic_mask_bits_p : Genv.find_funct_ptr ge b_set_rvic_mask_bits\n                                        = Some (External (EF_external _set_rvic_mask_bits\n                                                         (signature_of_type (Tcons Tptr (Tcons tuint (Tcons tulong Tnil))) tvoid cc_default))\n                                               (Tcons Tptr (Tcons tuint (Tcons tulong Tnil))) tvoid cc_default).\n    Local Opaque set_rvic_mask_bits_spec.\n\n    Lemma init_rec_rvic_state_body_correct:\n      forall m d d' env le rvic_base rvic_offset\n             (Henv: env = PTree.empty _)\n             (Hinv: high_level_invariant d)\n             (HPTrvic: PTree.get _rvic le = Some (Vptr rvic_base (Int.repr rvic_offset)))\n             (Hspec: init_rec_rvic_state_spec0 (rvic_base, rvic_offset) d = Some d'),\n           exists le', (exec_stmt ge env le ((m, d): mem) init_rec_rvic_state_body E0 le' (m, d') Out_normal).\n    Proof.\n      Local Opaque set_rvic_mask_bits_spec.\n      solve_code_proof Hspec init_rec_rvic_state_body; try solve [eexists; solve_proof_low].\n      get_loop_body. clear_hyp.\n      set (Hloop := C).\n      remember (PTree.set _i (Vint (Int.repr 0)) le)  as le_loop.\n      remember 8 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')).\n      set (Inv := fun le0 m0 n => exists i' adt1,\n                      init_rec_rvic_state_loop0 (Z.to_nat (num - n)) 0 (rvic_base, rvic_offset) d\n                      = Some (adt1, Int.unsigned i') /\\ Int.unsigned i' = num - n /\\\n                      m0 = (m, adt1) /\\ 0 <= n /\\ n <= num /\\ le0 ! _i = Some (Vint i') /\\\n                      le0 ! _rvic = Some (Vptr rvic_base (Int.repr rvic_offset))).\n      assert(loop_succ: forall N, Z.of_nat N <= num -> exists i' adt',\n                  init_rec_rvic_state_loop0 (Z.to_nat (num - Z.of_nat N)) 0 (rvic_base, rvic_offset) d\n                  = Some (adt', Int.unsigned i')).\n\n      { add_int Hloop z; 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' z0; repeat eexists; try somega. }\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. add_int' 0; try somega.\n          rewrite Heqnum. rewrite Heqle_loop.\n          repeat eexists; first [reflexivity|assumption|solve_proof_low].\n        - intros ? ? ? I. unfold Inv in I. 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 H8, H9 in *; eexists; eexists; split. solve_proof_low.\n              exists (n-1); split. split; solve_proof_low.\n              solve_proof_low; unfold Inv; repeat eexists; first[eassumption|solve_proof_low].\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. rewrite Post in exec.\n        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/RmiAux2/CodeProof/init_rec_rvic_state.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.25746918114417666}}
{"text": "Require Import Rupicola.Lib.Api.\nRequire Import Rupicola.Lib.Alloc.\nRequire Import Crypto.Bedrock.Specs.Field.\nRequire Import Crypto.Arithmetic.PrimeFieldTheorems.\nLocal Open Scope Z_scope.\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  Context {field_parameters : FieldParameters}\n          {field_representaton : FieldRepresentation}\n          {field_representation_ok : FieldRepresentation_ok}.\n\n  Definition maybe_bounded mbounds v :=\n    match mbounds with\n    | Some bounds => bounded_by bounds v\n    | None => True\n    end.\n\n  (* TODO: Replace uses of the old FElem with this? *)\n  Definition FElem mbounds ptr v :=\n    (Lift1Prop.ex1 (fun v' => (emp (feval v' = v /\\ maybe_bounded mbounds v') * FElem ptr v')%sep)).\n\n  Lemma drop_bounds_FElem x_ptr x bounds\n    : Lift1Prop.impl1 (FElem bounds x_ptr x)\n                      (FElem None x_ptr x).\n  Proof using mem_ok word_ok.\n    unfold FElem.\n    intros m H.\n    sepsimpl.\n    exists x0.\n    sepsimpl; simpl in *; eauto using relax_bounds.\n  Qed.\n\n  Lemma relax_bounds_FElem x_ptr x\n    : Lift1Prop.impl1 (FElem (Some tight_bounds) x_ptr x)\n                      (FElem (Some loose_bounds) x_ptr x).\n  Proof using field_representation_ok mem_ok word_ok.\n    unfold FElem.\n    intros m H.\n    sepsimpl.\n    exists x0.\n    sepsimpl; simpl in *; eauto using relax_bounds.\n  Qed.\n\n  Lemma FElem'_from_bytes\n    : forall px : word.rep,\n      Lift1Prop.iff1 (Placeholder px) (Lift1Prop.ex1 (FElem None px)).\n  Proof using mem_ok word_ok.\n    unfold FElem.\n    intros.\n    split; intros.\n    {\n      apply FElem_from_bytes in H.\n      destruct H.\n      do 2 eexists.\n      sepsimpl; simpl; eauto.\n    }\n    {\n      destruct H as [? [? ?]].\n      sepsimpl.\n\n      eapply FElem_to_bytes; eauto.\n    }\n  Qed.\n\n  #[refine]\n   Instance felem_alloc : Allocable (FElem None) :=\n    {|\n    size_in_bytes := felem_size_in_bytes;\n    size_in_bytes_mod := felem_size_in_bytes_mod;\n    |}.\n  Proof.\n    {\n      intros; intros m H.\n      apply FElem'_from_bytes.\n      eexists.\n      eapply drop_bounds_FElem; eauto.\n    }\n    {\n      intros; intros m H.\n      apply FElem'_from_bytes.\n      eauto.\n    }\n  Defined.\n\n  Local Ltac prove_field_compilation :=\n    repeat straightline';\n    handle_call;\n    lazymatch goal with\n    | |- sep _ _ _ => ecancel_assumption\n    | _ => idtac\n    end; eauto;\n    sepsimpl; repeat straightline'; subst; eauto.\n\n\n  Local Hint Extern 1 (spec_of _) => (simple refine (@spec_of_BinOp _ _ _ _ _ _ _ _ _ _)) : typeclass_instances.\n  Local Hint Extern 1 (spec_of _) => (simple refine (@spec_of_UnOp _ _ _ _ _ _ _ _ _ _)) : typeclass_instances.\n\n  Lemma compile_binop {name} {op: BinOp name}\n        {tr m l functions} x y:\n    let v := bin_model x y in\n    forall P (pred: P v -> predicate) (k: nlet_eq_k P v) k_impl\n           Rx Ry Rout out x_ptr x_var y_ptr y_var out_ptr out_var\n           bound_out,\n\n      (_: spec_of name) functions ->\n\n      map.get l out_var = Some out_ptr ->\n      (FElem bound_out out_ptr out * Rout)%sep m ->\n\n      (FElem (Some bin_xbounds) x_ptr x * Rx)%sep m ->\n      (FElem (Some bin_ybounds) y_ptr y * Ry)%sep m ->\n      map.get l x_var = Some x_ptr ->\n      map.get l y_var = Some y_ptr ->\n\n      (let v := v in\n       forall m',\n         sep (FElem (Some bin_outbounds) out_ptr v) Rout m' ->\n         (<{ Trace := tr;\n             Memory := m';\n             Locals := l;\n             Functions := functions }>\n          k_impl\n          <{ pred (k v eq_refl) }>)) ->\n      <{ Trace := tr;\n         Memory := m;\n         Locals := l;\n         Functions := functions }>\n      cmd.seq\n        (cmd.call [] name [expr.var out_var; expr.var x_var; expr.var y_var])\n        k_impl\n      <{ pred (nlet_eq [out_var] v k) }>.\n  Proof using env_ok ext_spec_ok locals_ok mem_ok word_ok.\n    repeat straightline'.\n    unfold FElem in *.\n    sepsimpl.\n    prove_field_compilation.\n    apply H6.\n\n    eapply Proper_sep_impl1; eauto.\n    2:exact(fun a b => b).\n    intros m' H'.\n    eexists.\n    sepsimpl;\n      eauto.\n  Qed.\n\n  Lemma compile_unop {name} (op: UnOp name) {tr m l functions} x:\n    let v := un_model x in\n    forall P (pred: P v -> predicate) (k: nlet_eq_k P v) k_impl\n           Rin Rout out x_ptr x_var out_ptr out_var out_bounds,\n\n      (_: spec_of name) functions ->\n\n      map.get l out_var = Some out_ptr ->\n      (FElem out_bounds out_ptr out * Rout)%sep m ->\n\n      (FElem (Some un_xbounds) x_ptr x * Rin)%sep m ->\n      map.get l x_var = Some x_ptr ->\n\n      (let v := v in\n       forall m',\n         sep (FElem (Some un_outbounds) out_ptr v) Rout m' ->\n         (<{ Trace := tr;\n             Memory := m';\n             Locals := l;\n             Functions := functions }>\n          k_impl\n          <{ pred (k v eq_refl) }>)) ->\n      <{ Trace := tr;\n         Memory := m;\n         Locals := l;\n         Functions := functions }>\n      cmd.seq\n        (cmd.call [] name [expr.var out_var; expr.var x_var])\n        k_impl\n      <{ pred (nlet_eq [out_var] v k) }>.\n  Proof using env_ok ext_spec_ok locals_ok mem_ok word_ok.\n    repeat straightline'.\n    unfold FElem in *.\n    sepsimpl.\n    prove_field_compilation.\n    apply H4.\n\n    eapply Proper_sep_impl1; eauto.\n    2:exact(fun a b => b).\n    intros m' H'.\n    eexists.\n    sepsimpl;\n      eauto.\n  Qed.\n\n\n  Ltac cleanup_op_lemma lem := (* This makes [simple apply] work *)\n    let lm := fresh in\n    let op := match lem with _ _ ?op => op end in\n    let op_hd := term_head op in\n    let simp proj :=\n        (let hd := term_head proj in\n         let reduced := (eval cbv [op_hd hd] in proj) in\n         change proj with reduced in (type of lm)) in\n    pose lem as lm;\n    first [ simp (bin_model (BinOp := op));\n            simp (bin_xbounds (BinOp := op));\n            simp (bin_ybounds (BinOp := op));\n            simp (bin_outbounds (BinOp := op))\n          | simp (un_model (UnOp := op));\n            simp (un_xbounds (UnOp := op));\n            simp (un_outbounds (UnOp := op)) ];\n    let t := type of lm in\n    let t := (eval cbv beta in t) in\n    exact (lm: t).\n\n  Notation make_bin_lemma op :=\n    ltac:(cleanup_op_lemma (@compile_binop _ op)) (only parsing).\n\n  Definition compile_mul := make_bin_lemma bin_mul.\n  Definition compile_add := make_bin_lemma bin_add.\n  Definition compile_sub := make_bin_lemma bin_sub.\n\n  Notation make_un_lemma op :=\n    ltac:(cleanup_op_lemma (@compile_unop _ op)) (only parsing).\n\n  Definition compile_square := make_un_lemma un_square.\n  Definition compile_scmula24 := make_un_lemma un_scmula24.\n\n  Local Hint Extern 1 (spec_of _) => (simple refine (@spec_of_felem_copy _ _ _ _ _ _ _ _)) : typeclass_instances.\n\n  Lemma compile_felem_copy {tr m l functions} x :\n    let v := x in\n    forall P (pred: P v -> predicate) (k: nlet_eq_k P v) k_impl\n           R x_ptr x_var out out_ptr out_var x_bound out_bound,\n\n      spec_of_felem_copy functions ->\n\n      map.get l out_var = Some out_ptr ->\n\n      (FElem x_bound x_ptr x * FElem out_bound out_ptr out * R)%sep m ->\n      map.get l x_var = Some x_ptr ->\n\n      (let v := v in\n       forall m',\n         (FElem x_bound x_ptr x * FElem x_bound out_ptr x * R)%sep m' ->\n         (<{ Trace := tr;\n             Memory := m';\n             Locals := l;\n             Functions := functions }>\n          k_impl\n          <{ pred (k v eq_refl) }>)) ->\n      <{ Trace := tr;\n         Memory := m;\n         Locals := l;\n         Functions := functions }>\n      cmd.seq\n        (cmd.call [] felem_copy [expr.var out_var; expr.var x_var])\n        k_impl\n      <{ pred (nlet_eq [out_var] v k) }>.\n  Proof using env_ok ext_spec_ok locals_ok mem_ok word_ok.\n    repeat straightline'.\n    unfold FElem in *.\n    sepsimpl.\n    prove_field_compilation.\n    apply H3.\n\n    extract_ex1_and_emp_in_goal; ssplit; eauto.\n  Qed.\n\n  Local Hint Extern 1 (spec_of _) => (simple refine (@spec_of_from_word _ _ _ _ _ _ _ _)) : typeclass_instances.\n\n  Lemma compile_from_word {tr m l functions} x:\n    let v := F.of_Z _ x in\n    forall P (pred: P v -> predicate) (k: nlet_eq_k P v) k_impl\n           R (wx : word) out out_ptr out_var out_bounds,\n\n      spec_of_from_word functions ->\n\n      map.get l out_var = Some out_ptr ->\n      (FElem out_bounds out_ptr out * R)%sep m ->\n\n      word.unsigned wx = x ->\n\n      (let v := v in\n       forall m',\n         (FElem (Some tight_bounds) out_ptr v * R)%sep m' ->\n         (<{ Trace := tr;\n             Memory := m';\n             Locals := l;\n             Functions := functions }>\n          k_impl\n          <{ pred (k v eq_refl) }>)) ->\n      <{ Trace := tr;\n         Memory := m;\n         Locals := l;\n         Functions := functions }>\n      cmd.seq\n        (cmd.call [] from_word\n                  [expr.var out_var; expr.literal x])\n        k_impl\n      <{ pred (nlet_eq [out_var] v k) }>.\n  Proof using env_ok ext_spec_ok locals_ok mem_ok word_ok.\n    repeat straightline'.\n    unfold FElem in *.\n    extract_ex1_and_emp_in H1.\n    prove_field_compilation.\n    match goal with H : _ |- _ => rewrite word.of_Z_unsigned in H end.\n    apply H3.\n    extract_ex1_and_emp_in_goal; ssplit; eauto.\n  Qed.\n\n  Local Hint Extern 1 (spec_of _) => (simple refine (@spec_of_from_bytes _ _ _ _ _ _ _ _)) : typeclass_instances.\n\n  (*\n  Lemma compile_from_bytes {tr m l functions} x :\n    let v : F _ := feval_bytes x in\n    forall P (pred: P v -> predicate) (k: nlet_eq_k P v) k_impl\n           Rx R x_ptr x_var out out_ptr out_var out_bound,\n\n      spec_of_from_bytes functions ->\n\n      map.get l out_var = Some out_ptr ->\n\n      (FElemBytes x_ptr x * Rx)%sep m ->\n      (FElem out_bound out_ptr out * R)%sep m ->\n      map.get l x_var = Some x_ptr ->\n\n      (let v := v in\n       forall m',\n         (FElem (Some tight_bounds) out_ptr v * R)%sep m' ->\n         (<{ Trace := tr;\n             Memory := m';\n             Locals := l;\n             Functions := functions }>\n          k_impl\n          <{ pred (k v eq_refl) }>)) ->\n      <{ Trace := tr;\n         Memory := m;\n         Locals := l;\n         Functions := functions }>\n      cmd.seq\n        (cmd.call [] from_bytes [expr.var out_var; expr.var x_var])\n        k_impl\n      <{ pred (nlet_eq [out_var] v k) }>.\n  Proof using env_ok ext_spec_ok locals_ok mem_ok word_ok.\n    repeat straightline'.\n    unfold FElem in *.\n    sepsimpl.\n    prove_field_compilation.\n    apply H4.\n\n    eapply Proper_sep_impl1; eauto; try reflexivity.\n    eapply Lift1Prop.impl1_ex1_r.\n    intros m' H'; ssplit; eapply sep_emp_l; ssplit; eauto.\n  Qed.\n\n  Lemma compile_to_bytes {tr m l functions} x :\n    let v : list _ := Z_to_bytes (F.to_Z x) encoded_felem_size_in_bytes in\n    forall P (pred: P v -> predicate) (k: nlet_eq_k P v) k_impl\n           Rx R x_ptr x_var out out_ptr out_var,\n\n      spec_of_to_bytes functions ->\n\n      map.get l out_var = Some out_ptr ->\n\n      (FElem (Some tight_bounds) x_ptr x * Rx)%sep m ->\n      (FElemBytes out_ptr out * R)%sep m ->\n      map.get l x_var = Some x_ptr ->\n\n      (let v := v in\n       forall m',\n         (FElemBytes out_ptr v * R)%sep m' ->\n         (<{ Trace := tr;\n             Memory := m';\n             Locals := l;\n             Functions := functions }>\n          k_impl\n          <{ pred (k v eq_refl) }>)) ->\n      <{ Trace := tr;\n         Memory := m;\n         Locals := l;\n         Functions := functions }>\n      cmd.seq\n        (cmd.call [] to_bytes [expr.var out_var; expr.var x_var])\n        k_impl\n      <{ pred (nlet_eq [out_var] v k) }>.\n  Proof using env_ok ext_spec_ok locals_ok mem_ok word_ok.\n    repeat straightline'.\n    subst v.\n    unfold FElem in *.\n    sepsimpl;\n    eapply Proper_call; [ |eapply H]; cycle 1;\n     [ ssplit;\n        lazymatch goal with\n        | |- (_ ⋆ _) _ => ecancel_assumption\n        | |- exists R, (_ ⋆ R) _ => eexists; ecancel_assumption\n        | _ => idtac\n        end\n     | cbv[postcondition_func postcondition_func_norets] in *;\n        repeat straightline; destruct_lists_of_known_length;\n        repeat straightline ].\n    { unfold maybe_bounded in *; eauto. }\n    intros ? ? ? ?; repeat straightline'.\n    subst; eauto.\n  Qed.\n   *)\nEnd Compile.\n\n\n(*must be higher priority than compile_mul*)\n#[export] Hint Extern 6 (WeakestPrecondition.cmd _ _ _ _ _ (_ (nlet_eq _ (a24 * _)%F _))) =>\nsimple eapply compile_scmula24; shelve : compiler.\n\n#[export] Hint Extern 8 (WeakestPrecondition.cmd _ _ _ _ _ (_ (nlet_eq _ (_ * _)%F _))) =>\nsimple eapply compile_mul; shelve : compiler.\n#[export] Hint Extern 8 (WeakestPrecondition.cmd _ _ _ _ _ (_ (nlet_eq _ (_ + _)%F _))) =>\nsimple eapply compile_add; shelve : compiler.\n#[export] Hint Extern 8 (WeakestPrecondition.cmd _ _ _ _ _ (_ (nlet_eq _ (_ - _)%F _))) =>\nsimple eapply compile_sub; shelve : compiler.\n#[export] Hint Extern 8 (WeakestPrecondition.cmd _ _ _ _ _ (_ (nlet_eq _ (_ ^ 2)%F _))) =>\nsimple eapply compile_square; shelve : compiler.\n#[export] Hint Extern 8 (WeakestPrecondition.cmd _ _ _ _ _ (_ (nlet_eq _ (F.of_Z M_pos _) _))) =>\nsimple eapply compile_from_word; shelve : compiler.\n#[export] Hint Extern 10 (WeakestPrecondition.cmd _ _ _ _ _ (_ (nlet_eq _ ?v _))) =>\nis_var v; simple eapply compile_felem_copy; shelve : compiler.\n\n\n#[export] Hint Immediate relax_bounds_FElem : ecancel_impl.\n#[export] Hint Immediate drop_bounds_FElem : ecancel_impl.\n\n\n#[export] Hint Extern 1 (spec_of _) => (simple refine (@spec_of_BinOp _ _ _ _ _ _ _ _ _ _)) : typeclass_instances.\n#[export] Hint Extern 1 (spec_of _) => (simple refine (@spec_of_UnOp _ _ _ _ _ _ _ _ _ _)) : typeclass_instances.\n#[export] Hint Extern 1 (spec_of felem_copy) => (simple refine (@spec_of_felem_copy _ _ _ _ _ _ _ _)) : typeclass_instances.\n#[export] Hint Extern 1 (spec_of from_word) => (simple refine (@spec_of_from_word _ _ _ _ _ _ _ _)) : typeclass_instances.\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/Interface/Compilation2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.25746918114417666}}
{"text": "Require Import Coq.Logic.Classical_Prop.\nRequire Import Lia.\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.\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 Intermediate.Machine.\nRequire Import Intermediate.GlobalEnv.\nRequire Import Intermediate.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\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 intermediate semantics *)\n\nImport Intermediate.\n\n(* NOTE: DO we have similar/redundant definitions to unify? *)\nDefinition is_prefix (s: CS.state) (p: program) t : Prop :=\n  Star (CS.sem_non_inform p) (CS.initial_machine_state p) t s.\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  \n(** TODO: Write as an inductive. *)\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\nDefinition wf_reg_wrt_t_pc (reg: Register.t) (t: trace event)\n           (pc_comp: Component.id) : Prop :=\n  forall r ptr,\n    Register.get r reg = Ptr ptr ->\n    Pointer.permission ptr = Permission.data ->\n    wf_ptr_wrt_cid_t pc_comp t ptr.\n\nDefinition reach_from_reg_wf_wrt_t_pc (reg: Register.t) (t: trace event)\n           (mem: Memory.t) (pc_comp: Component.id) :=\n  forall r ptr ptr_c ptr_b v_c v_b,\n    Register.get r reg = Ptr ptr ->\n    Pointer.permission ptr = Permission.data ->\n    Pointer.component ptr = ptr_c ->\n    Pointer.block ptr = ptr_b ->\n    Reachable mem (fset1 (ptr_c, ptr_b)) (v_c, v_b) ->\n    (forall v_o, wf_ptr_wrt_cid_t pc_comp t (Permission.data, v_c, v_b, v_o)).\n\nDefinition wf_state_t (s: CS.state) (t: trace event) : Prop :=\n  wf_mem_wrt_t_pc (CS.state_mem s) t (Pointer.component (CS.state_pc s)) /\\\n  wf_reg_wrt_t_pc (CS.state_regs s) t (Pointer.component (CS.state_pc s)).\n\n(* TODO: Move to Pointer module. *)\nRemark pointer_proj ptr :\n  ptr = (Pointer.permission ptr, Pointer.component ptr, Pointer.block ptr, Pointer.offset ptr).\nProof.\n  destruct ptr as [[[? ?] ?] ?]. reflexivity.\nQed.\n\n(* TODO: Move to Pointer module. *)\nRemark pointer_refl ptr1 ptr2 :\n  Pointer.eq ptr1 ptr2 = true ->\n  ptr1 = ptr2.\nProof.\n  destruct ptr1 as [[[P1 C1] b1] o1].\n  destruct ptr2 as [[[P2 C2] b2] o2].\n  (* Decompose pointer component equalities... *)\n  move=> /andP [[]] /andP [[]] /andP [[]] =>\n  (* Depending on the Coq version, you might need to chose one or the other\n     version of the tactic. *)\n  (* (* ... then reflect each of them and substitute the equality... *) *)\n  (* /ssrnat.eqnP -> *)\n  (* /ssrnat.eqnP -> *)\n  (* /ssrnat.eqnP -> *)\n  (* /eqP -> *)\n  (* (* ... and we're done. *) *)\n  (* //. *)\n  /Permission.eqP -> /eqnP -> /eqnP -> /Z.eqb_spec -> //=.\nQed.\n\n(* TODO: Relocate. *)\nRemark Eapp_rcons {T} l (x : T) : l ** [x] = seq.rcons l x.\nProof.\n  unfold Eapp. by rewrite <- cats1.\nQed.\n\nLemma initial_wf_mem p:\n      closed_program p ->\n      well_formed_program p ->\n      prog_main p ->\n      wf_mem_wrt_t_pc\n        (mapm (T:=nat_ordType)\n              (fun x => x.1.1)\n              (prepare_procedures_initial_memory_aux p)) E0 Component.main.\n  (**\n     (* No pointers in static buffers. *)\n      intros aptr vptr Hload Hperm.\n      \n      Check wfprog_well_formed_buffers.\n      Print Buffer.well_formed_buffer.\n   (* Should be easy once connected to the environment. *)\n   *)\nProof.\n  intros Hclosed Hwf Hmain [[[perm C] b] o] ptr Hload Hperm.\n  apply private_stuff_from_corresp_private_addr.\n  - intros Hcontra.\n    inversion Hcontra as [H1 t e H4 Hcons | H1 H2 t e H5 H6 H7 Hcons];\n      destruct t as [[| ? ?] ? |]; now inversion Hcons.\n  - intros Hcontra.\n    inversion Hcontra as [H1 t e H4 Hcons | H1 H2 t e H5 H6 H7 Hcons];\n      destruct t as [[| ? ?] ? |]; now inversion Hcons.\n  - destruct (C \\in domm (prog_interface p)) eqn:Hdomm.\n    + destruct (prepare_procedures_memory_prog_buffers Hwf Hload)\n        as [(*Cbufs [*) buf (*[HCbufs*) [Hbuf Hptr]].\n      exfalso. eapply prog_buffer_ptr; eassumption.\n    + rewrite (wfprog_defined_buffers Hwf) in Hdomm.\n      destruct (prepare_procedures_memory_prog_buffers Hwf Hload)\n        as [buf [Hbuf ?]].\n      simpl in *.\n      apply negb_true_iff in Hdomm.\n      rewrite (dommPn Hdomm) in Hbuf.\n      discriminate.\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  - (* Base case. *)\n    unfold CS.initial_machine_state. simpl.\n    (* TODO: Does this apply to closed programs only? If not, we need to handle\n       additional cases. *)\n    (** AEK: Yes, closed only. *)\n    assert (Hmain : prog_main p).\n    {\n      rewrite <- wfprog_main_component; auto.\n      specialize (cprog_main_existence Hclosed) as [? [? [Hprogproc ?]]].\n      rewrite wfprog_defined_procedures; auto.\n      apply/dommP. by eauto.\n    }\n    rewrite Hmain.\n    split; (*last split;*) simpl.\n    + apply initial_wf_mem; auto.\n      \n    + (* All registers are uninitialized. *)\n      intros reg ptr Hget.\n      destruct reg; discriminate.\n    (********************\n    + intros reg ptr ? Hget.\n      destruct reg; discriminate.\n     ***************************)\n  - (* Inductive step. *)\n    specialize (IHstar Logic.eq_refl Logic.eq_refl).\n    split (*; last split*).\n    + (* Memory. *)\n      destruct IHstar as [Hmem1 (*[Hregs1 _Hreach1]*) Hregs1].\n      inversion Hstep12 as [? ? ? ? Hstep12']; subst.\n      inversion Hstep12'; subst; simpl in *;\n        (* A few useful simplifications. *)\n        try rewrite E0_right;\n        try rewrite Pointer.inc_preserves_component;\n        (* Many goals follow directly from the IH now. *)\n        try assumption.\n      * (* Store *)\n        intros addr_load val_load Hload Hperm.\n        clear Hstar01 Hstep12 Hstep12' H.\n        destruct (Pointer.eqP ptr addr_load) as [Heq | Hneq].\n        -- (* We load from the address we just stored to. The information can\n              only come from the registers and not from the memory. *)\n           subst addr_load.\n           rewrite (Memory.load_after_store_eq _ _ _ _ H1) in Hload.\n           injection Hload as Hload.\n           destruct ptr as [[[Pptr Cptr] bptr] optr].\n           destruct val_load as [[[Pval Cval] bval] oval].\n           specialize (Memory.store_some_permission _ _ _ _ H1) as Hperm2.\n           simpl in *; subst.\n           assert (Hr1 := Hregs1 _ _ H0 Logic.eq_refl).\n           assert (Hr2 := Hregs1 _ _ Hload Logic.eq_refl).\n           inversion Hr2 as [|]; subst.\n           ++ specialize (classic (addr_shared_so_far (Pointer.component pc, bval) t1))\n               as [Hshr | Hnotshr].\n              ** apply shared_stuff_from_anywhere; assumption.\n              ** (** private_stuff *)\n                inversion Hr1 as [|]; subst.\n                ---\n                  (** private stuff of current pc from ... *)\n                  specialize (classic\n                                (addr_shared_so_far (Pointer.component pc, bptr) t1))\n                    as [Hfromshr | Hfromprivate].\n                  +++ apply private_stuff_of_current_pc_from_shared_addr; auto.\n                  +++ apply private_stuff_from_corresp_private_addr; auto.\n                ---\n                  (** shared addr *)\n                  apply private_stuff_of_current_pc_from_shared_addr; auto.\n           ++ (** shared stuff *)\n             apply shared_stuff_from_anywhere; assumption.\n        -- (* For any other address, this follows directly from the IH. *)\n           rewrite -> (Memory.load_after_store_neq _ _ _ _ _ Hneq H1) in Hload.\n           exact (Hmem1 _ _ Hload Hperm).\n      * (* IJal *)\n        intros addr_load val_load Hload.\n        clear Hstar01 Hstep12 Hstep12' H.\n        (* Since we dot change components, this follows from the IH. *)\n        rewrite <- (find_label_in_component_1 _ _ _ _ H0).\n        exact (Hmem1 _ _ Hload).\n      * (* IJump *)\n        intros addr_load val_load Hload.\n        clear Hstar01 Hstep12 Hstep12' H.\n        (* Since we dot change components, this follows from the IH. *)\n        rewrite -> H2.\n        exact (Hmem1 _ _ Hload).\n        \n      * (* IJumpFunPtr *)\n        intros addr_load val_load Hload.\n        clear Hstar01 Hstep12 Hstep12' H.\n        (* Since we dot change components, this follows from the IH. *)\n        rewrite -> H2.\n        exact (Hmem1 _ _ Hload).\n      * (* IBnz *)\n        intros addr_load val_load Hload.\n        clear Hstar01 Hstep12 Hstep12' H.\n        (* Since we dot change components, this follows from the IH. *)\n        rewrite <- (find_label_in_procedure_1 _ _ _ _ H2).\n        exact (Hmem1 _ _ Hload).\n      * (* IAlloc *)\n        intros addr_load val_load Hload.\n        clear Hstar01 Hstep12 Hstep12' H.\n        destruct\n          (addr_eqP (Pointer.component addr_load, Pointer.block addr_load)\n                    (Pointer.component ptr,       Pointer.block ptr))\n          as [Heq | Hneq].\n        -- (* If we read from the newly allocated block, the load cannot find\n             any pointers and we conclude by contradiction. *)\n           rewrite (Memory.load_after_alloc_eq _ _ _ _ _ _ H2 Heq) in Hload.\n           destruct (Permission.eqb (Pointer.permission addr_load) Permission.data);\n             last discriminate.\n           destruct ((Pointer.offset addr_load <? Z.of_nat (Z.to_nat size))%Z);\n             last discriminate.\n           destruct ((0 <=? Pointer.offset addr_load)%Z);\n             discriminate.\n        -- (* If we read from elsewhere, the result follows from the IH. *)\n           (* TODO: Rename lemma (add [_neq]).*)\n           rewrite (Memory.load_after_alloc _ _ _ _ _ _ H2 Hneq) in Hload.\n           exact (Hmem1 _ _ Hload).\n      * (* ICall *)\n        intros addr_load val_load Hload Hperm.\n        specialize (Hmem1 _ _ Hload Hperm).\n        destruct val_load as  [[[vperm vcid] vbid] voff].\n        destruct addr_load as  [[[aperm acid] abid] aoff].\n        specialize (Memory.load_some_permission _ _ _ Hload) as Hperm2.\n        simpl in *; subst.\n        clear Hstep12' Hstar01 Hstep12.\n        specialize (classic (addr_shared_so_far\n                               (vcid, vbid)\n                               (t1 ** [:: ECall\n                                          (Pointer.component pc)\n                                          P (Register.get R_COM regs) mem C']\n                               )\n                            )\n                   ) as [Hshr | Hnotshr].\n        -- (** shared stuff *)\n          apply shared_stuff_from_anywhere; auto.\n        -- (** private stuff *)\n          destruct (vcid =? C') eqn:eacid.\n          ++\n            (** private stuff of current pc from ...*)\n            assert (vcid = C'). by apply beq_nat_true. subst.\n            specialize (classic (addr_shared_so_far\n                                   (acid, abid)\n                                   (t1 ** [:: ECall\n                                              (Pointer.component pc)\n                                              P (Register.get R_COM regs) mem C']\n                                   )\n                                )\n                       ) as [Hshraddr | Hnotshraddr].\n            ** apply private_stuff_of_current_pc_from_shared_addr; auto.\n            ** apply private_stuff_from_corresp_private_addr; auto. simpl.\n               inversion Hmem1 as [| |]; simpl in *; subst; auto.\n               --- exfalso. apply Hnotshr. rewrite Eapp_rcons.\n                   eapply reachable_from_previously_shared; eauto. simpl.\n                   constructor. by rewrite in_fset1.\n               --- exfalso. apply Hnotshraddr. rewrite Eapp_rcons.\n                   eapply reachable_from_previously_shared; eauto. simpl.\n                   constructor. by rewrite in_fset1.\n          ++ (** private stuff NOT of current pc *)\n            apply private_stuff_from_corresp_private_addr; simpl in *; auto; subst.\n            ** intros Hshraddr.\n               apply Hnotshr. rewrite Eapp_rcons. rewrite Eapp_rcons in Hshraddr.\n               eapply addr_shared_so_far_load_addr_shared_so_far; simpl; eauto.\n            ** inversion Hmem1 as [| |]; simpl in *; subst; auto.\n               --- exfalso. apply Hnotshr. rewrite Eapp_rcons.\n                   eapply reachable_from_previously_shared; eauto. simpl.\n                   constructor. by rewrite in_fset1.\n               --- exfalso. apply Hnotshr.\n                   rewrite Eapp_rcons.\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          \n      * (* IReturn *)\n                intros addr_load val_load Hload Hperm.\n        specialize (Hmem1 _ _ Hload Hperm).\n        destruct val_load as  [[[vperm vcid] vbid] voff].\n        destruct addr_load as  [[[aperm acid] abid] aoff].\n        specialize (Memory.load_some_permission _ _ _ Hload) as Hperm2.\n        simpl in *; subst.\n        clear Hstep12' Hstar01 Hstep12.\n        specialize (classic (addr_shared_so_far\n                               (vcid, vbid)\n                               (t1 ** [:: ERet\n                                          (Pointer.component pc)\n                                          (Register.get R_COM regs)\n                                          mem (Pointer.component pc')]\n                               )\n                            )\n                   ) as [Hshr | Hnotshr].\n        -- (** shared stuff *)\n          apply shared_stuff_from_anywhere; auto.\n        -- (** private stuff *)\n          destruct (vcid =? Pointer.component pc') eqn:eacid.\n          ++\n            (** private stuff of current pc from ...*)\n            assert (vcid = Pointer.component pc'). by apply beq_nat_true. subst.\n            specialize (classic (addr_shared_so_far\n                                   (acid, abid)\n                                   (t1 ** [:: ERet\n                                          (Pointer.component pc)\n                                          (Register.get R_COM regs)\n                                          mem (Pointer.component pc')]\n                                   )\n                                )\n                       ) as [Hshraddr | Hnotshraddr].\n            ** apply private_stuff_of_current_pc_from_shared_addr; auto.\n            ** apply private_stuff_from_corresp_private_addr; auto. simpl.\n               inversion Hmem1 as [| |]; simpl in *; subst; auto.\n               --- exfalso. apply Hnotshr. rewrite Eapp_rcons.\n                   eapply reachable_from_previously_shared; eauto. simpl.\n                   constructor. by rewrite in_fset1.\n               --- exfalso. apply Hnotshraddr. rewrite Eapp_rcons.\n                   eapply reachable_from_previously_shared; eauto. simpl.\n                   constructor. by rewrite in_fset1.\n          ++ (** private stuff NOT of current pc *)\n            apply private_stuff_from_corresp_private_addr; simpl in *; auto; subst.\n            ** intros Hshraddr.\n               apply Hnotshr. rewrite Eapp_rcons. rewrite Eapp_rcons in Hshraddr.\n               eapply addr_shared_so_far_load_addr_shared_so_far; simpl; eauto.\n            ** inversion Hmem1 as [| |]; simpl in *; subst; auto.\n               --- exfalso. apply Hnotshr. rewrite Eapp_rcons.\n                   eapply reachable_from_previously_shared; eauto. simpl.\n                   constructor. by rewrite in_fset1.\n               --- exfalso. apply Hnotshr.\n                   rewrite Eapp_rcons.\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\n\n    + (* Registers. *)\n      destruct IHstar as [Hmem1 (*[Hregs1 _Hreach1]*) Hregs1].\n      inversion Hstep12 as [? ? ? ? Hstep12']; subst.\n      inversion Hstep12'; subst; simpl in *;\n        (* A few useful simplifications. *)\n        try rewrite E0_right;\n        try rewrite Pointer.inc_preserves_component;\n        (* A few goals follow directly from the IH. *)\n        try assumption.\n      * (* IConst *)\n        intros reg ptr Hget.\n        clear Hstar01 Hstep12 Hstep12'. (* Do we need anything in here? *)\n        destruct (Register.eqP reg r) as [Heq | Hneq].\n        -- (* If we read the register we just wrote, we get the exact immediate\n              value, here assumed to be a pointer. *)\n           subst r. rewrite Register.gss in Hget.\n           destruct v as [n | ptr']; first discriminate.\n           injection Hget as Hget; subst ptr'.\n           match goal with\n           | H: executing _ _ _ |- _ =>\n             destruct H as [procs [proc [Hprocs [Hproc [Hoff [Hperm Hnth]]]]]] end.\n           specialize (CS.genv_procedures_prog_procedures\n                             _ (Pointer.component pc) proc Hwf) as Hif.\n             assert (exists (procs' : NMap code) (bid' : nat_ordType),\n                        prog_procedures p (Pointer.component pc) = Some procs'\n                        /\\ procs' bid' = Some proc\n                    ) as [? [bid [? ?]]].\n             { by apply Hif; eauto. }\n           assert (Hwf_instr: well_formed_instruction\n                          p (Pointer.component pc) bid\n                          (IConst (IPtr ptr) reg)).\n           {\n             \n             eapply wfprog_well_formed_instructions; eauto.\n             eapply nth_error_In; eauto.\n           }\n           (* Thanks to [well_formed_instruction], we know that pointer\n              constants may only refer to their own component. *)\n           destruct ptr as [[[P C] b] o].\n           assert (C = Pointer.component pc).\n           {\n             inversion Hwf_instr. by simpl in *.\n           }\n           subst C. intros; simpl in *; subst.\n           now apply wf_ptr_own.\n        -- (* For any other register, this follows directly from the IH. *)\n           rewrite Register.gso in Hget; last assumption.\n           exact (Hregs1 _ _ Hget).\n      * (* IMov *)\n        intros reg ptr Hget.\n        clear Hstar01 Hstep12 Hstep12' H. (* Do we need anything in here? *)\n        destruct (Register.eqP reg rdest) as [Heq | Hneq].\n        -- (* The new value comes from r1, which follows from the IH. *)\n           subst rdest. rewrite Register.gss in Hget.\n           exact (Hregs1 _ _ Hget).\n        -- (* The new value comes from reg, which follows from the IH. *)\n           rewrite Register.gso in Hget; last assumption.\n           exact (Hregs1 _ _ Hget).\n      * (* IBinOp *)\n        intros reg ptr Hget.\n        clear Hstar01 Hstep12 Hstep12' H. (* Do we need anything in here? *)\n        destruct (Register.eqP reg r3) as [Heq | Hneq].\n        -- (* If we read the register we just wrote, we get the result of the\n              operation, which we then case analyze. *)\n           subst r3. rewrite Register.gss in Hget.\n           unfold result, eval_binop in Hget.\n           destruct op;\n             destruct (Register.get r1 regs) eqn:Hget1;\n             destruct (Register.get r2 regs) eqn:Hget2;\n             (* Most cases are nonsensical; a handful remain. *)\n             inversion Hget; subst.\n           (* Whenever there is a pointer and an integer, the result follows\n              from the IH on the pointer, albeit with a bit of work to account\n              for the integer offsets. *)\n           ++ assert (Hr2 := Hregs1 _ _ Hget2).\n              intros G.\n              erewrite <- Pointer.add_preserves_permission in Hr2.\n              specialize (Hr2 G).\n              inversion Hr2; subst. (* By the corresponding [constructor]. *)\n              ** now apply wf_ptr_own.\n              ** now apply wf_ptr_shared.\n           ++ assert (Hr1 := Hregs1 _ _ Hget1).\n              intros G.\n              erewrite <- Pointer.add_preserves_permission in Hr1.\n              specialize (Hr1 G).\n              inversion Hr1; subst; (* Can be picked automatically. *)\n                now constructor.\n           ++ assert (Hr1 := Hregs1 _ _ Hget1).\n              intros G.\n              erewrite <- Pointer.add_preserves_permission in Hr1.\n              specialize (Hr1 G).\n              inversion Hr1; subst;\n                now constructor.\n           (* The remaining cases are contradictions requiring some additional\n              but trivial analysis. *)\n           ++ destruct t as [[[P1 C1] b1] o1];\n                destruct t0 as [[[P2 C2] b2] o2];\n                destruct (Permission.eqb P1 P2);\n                destruct (C1 =? C2);\n                destruct (b1 =? b2);\n                discriminate.\n           ++ destruct (Pointer.leq t t0);\n                discriminate.\n        -- (* For any other register, this follows directly from the IH. *)\n           rewrite Register.gso in Hget; last assumption.\n           exact (Hregs1 _ _ Hget).\n      * (* IPtrOfLabel *)\n        intros reg ptr' Hget.\n        clear Hstar01 Hstep12 Hstep12' H. (* Do we need anything in here? *)\n        destruct (Register.eqP reg r) as [Heq | Hneq].\n        -- (* *)\n           subst r. rewrite Register.gss in Hget.\n           injection Hget as Hget; subst ptr'.\n           destruct ptr as [[[P C] b] o].\n           rewrite (find_label_in_component_1 _ _ _ _ H0). intros.\n           now apply wf_ptr_own.\n        -- (* *)\n           rewrite Register.gso in Hget; last assumption.\n           exact (Hregs1 _ _ Hget).\n      * (* ILoad *)\n        intros reg ptr' Hget Hperm'.\n        (* clear Hstar01 Hstep12 Hstep12' H. (* Do we need anything in here? *) *)\n        destruct (Register.eqP reg r2) as [Heq | Hneq].\n        -- (*  *)\n           subst r2. rewrite Register.gss in Hget. subst v.\n           (* IH *)\n           specialize (Memory.load_some_permission _ _ _ H1) as Hperm.\n           assert (Hr1 := Hregs1 _ _ H0 Hperm).\n           assert (Hptr := Hmem1 _ _ H1 Hperm').\n           destruct ptr as [[[P C] b] o].\n           destruct ptr' as [[[P' C'] b'] o'].\n           simpl in *. subst.\n           inversion Hptr as [| |]; simpl in *; subst; last by constructor.\n           ++ (** private stuff from corresp private addr *)\n             destruct (C =? Pointer.component pc) eqn:eC.\n             ** assert (C = Pointer.component pc). by apply beq_nat_true. subst.\n                by constructor.\n             ** inversion Hr1 as [|]; subst; auto.\n                --- by rewrite <- beq_nat_refl in eC.\n                --- by apply H3 in H4.\n           ++ by constructor.\n           \n        -- (* The new value comes from reg, which follows from the IH. *)\n          specialize (Register.gso v regs Hneq) as G.\n          assert (Hget' : Register.get reg regs = Ptr ptr').\n          { by rewrite Hget in G. }\n          exact (Hregs1 _ _ Hget' Hperm').\n      * (* IJal *)\n        intros reg ptr Hget.\n        clear Hstar01 Hstep12 Hstep12' H. (* Do we need anything in here? *)\n        rewrite <- (find_label_in_component_1 _ _ _ _ H0).\n        destruct (Register.eqP reg R_RA) as [Heq | Hneq].\n        -- (* *)\n           subst reg. rewrite Register.gss in Hget.\n           injection Hget as Hget; subst ptr.\n           rewrite <- Pointer.inc_preserves_component.\n           destruct (Pointer.inc pc) as [[[perm C] b] o] eqn:Heq.\n           intros.\n           now apply wf_ptr_own.\n        -- (* *)\n           rewrite Register.gso in Hget; last assumption.\n           exact (Hregs1 _ _ Hget).\n      * (* IJump *)\n        intros reg ptr Hget.\n        clear Hstar01 Hstep12 Hstep12' H. (* Do we need anything in here? *)\n        rewrite H2.\n        exact (Hregs1 _ _ Hget).\n      * (* IJumpFunPtr *)\n        intros reg ptr Hget.\n        clear Hstar01 Hstep12 Hstep12' H. (* Do we need anything in here? *)\n        rewrite H2.\n        exact (Hregs1 _ _ Hget).\n      * (* IBnz *)\n        intros reg ptr Hget.\n        clear Hstar01 Hstep12 Hstep12' H. (* Do we need anything in here? *)\n        rewrite <- (find_label_in_procedure_1 _ _ _ _ H2).\n        exact (Hregs1 _ _ Hget).\n      * (* IAlloc *)\n        intros reg ptr' Hget.\n        clear Hstar01 Hstep12 Hstep12' H. (* Do we need anything in here? *)\n        destruct (Register.eqP reg rptr) as [Heq | Hneq].\n        -- (* *)\n           subst rptr. rewrite Register.gss in Hget.\n           injection Hget as Hget; subst ptr'.\n           specialize (Memory.component_of_alloc_ptr _ _ _ _ _ H2) as rewr.\n           intros.\n           destruct ptr as [[[P C] b] o]. simpl in *. subst.\n           now apply wf_ptr_own.\n        -- (* *)\n           rewrite Register.gso in Hget; last assumption.\n           exact (Hregs1 _ _ Hget).\n      * (* ICall *)\n        intros reg ptr Hget Hperm.\n        clear Hstar01 Hstep12 Hstep12' H. (* Do we need anything in here? *)\n        rewrite Register.gi in Hget.\n        destruct (Register.eqP reg R_COM) as [Heq | Hneq];\n          last discriminate.\n        subst reg. rewrite Hget.\n        assert (Hrcom := Hregs1 _ _ Hget Hperm).\n        destruct ptr as [[[P_ C_] b_] o_].\n        simpl in *. subst.\n        apply wf_ptr_shared.\n        rewrite Eapp_rcons.\n        apply reachable_from_args_is_shared. simpl.\n        apply Reachable_refl. apply /fset1P. reflexivity.\n      * (* IReturn *)\n        intros reg ptr Hget Hperm.\n        clear Hstar01 Hstep12 Hstep12' H. (* Do we need anything in here? *)\n        rewrite Register.gi in Hget.\n        destruct (Register.eqP reg R_COM) as [Heq | Hneq];\n          last discriminate.\n        subst reg. rewrite Hget.\n        assert (Hrcom := Hregs1 _ _ Hget Hperm).\n        destruct ptr as [[[P_ C_] b_] o_].\n        simpl in *. subst.\n        apply wf_ptr_shared.\n        rewrite Eapp_rcons.\n        apply reachable_from_args_is_shared. simpl.\n        apply Reachable_refl. apply /fset1P. reflexivity.\nQed.\n\nLemma wf_state_wf_reg s regs pc pc_comp t:\n  wf_state_t s t ->\n  CS.state_regs s = regs ->\n  CS.state_pc s = pc ->\n  Pointer.component pc = pc_comp ->\n  wf_reg_wrt_t_pc regs t pc_comp.\nProof.\n    unfold wf_state_t; intros [? (*[? ?]*)?] _H1 _H2 _H3. rewrite <- _H3, <- _H2, <- _H1. auto.\nQed.\n\nLemma wf_state_wf_mem s mem pc pc_comp t:\n  wf_state_t s t ->\n  CS.state_mem s = mem ->\n  CS.state_pc s = pc ->\n  Pointer.component pc = pc_comp ->\n  wf_mem_wrt_t_pc mem t pc_comp.\nProof.\n    unfold wf_state_t; intros [? (*[? ?]*)?] _H1 _H2 _H3. rewrite <- _H3, <- _H2, <- _H1. auto.\nQed.\n\nLemma wf_reg_wf_ptr_wrt_cid_t reg t pc_comp r ptr:\n  wf_reg_wrt_t_pc reg t pc_comp ->\n  Register.get r reg = Ptr ptr ->\n  Pointer.permission ptr = Permission.data ->\n  wf_ptr_wrt_cid_t pc_comp t ptr.\nProof.\n   unfold wf_reg_wrt_t_pc. intros H Hget Hperm. apply (H r ptr Hget Hperm).\nQed.\n\nLemma wf_mem_wrt_t_pc_wf_load mem t pc_comp load_at ptr:\n  wf_mem_wrt_t_pc mem t pc_comp ->\n  Memory.load mem load_at = Some (Ptr ptr) ->\n  Pointer.permission ptr = Permission.data ->\n  wf_load pc_comp t load_at ptr.\nProof.\n    by (unfold wf_mem_wrt_t_pc; intros H Hload Hperm; eapply H).\nQed.\n\nLemma mem_comp_in_domm_prog_interface_some s p t mem cid:\n  well_formed_program p ->\n  closed_program p ->\n  is_prefix s p t ->\n  CS.state_mem s = mem ->\n  cid \\in domm (prog_interface p) <->\n  exists compMem, mem cid = Some compMem.\nProof.\n  unfold is_prefix. simpl.\n  intros Hwf Hclosed Hstar Hmem.\n  remember (CS.initial_machine_state p) as s0 eqn:Hs0.\n  remember (prepare_global_env p) as G eqn:HG.\n  revert mem Hs0 HG Hwf Hclosed Hmem.\n  apply star_iff_starR in Hstar.\n  induction Hstar as [| s0 t1 s1 t2 s2 t12 Hstar01 IHstar Hstep12 Ht12];\n    intros mem Hs0 HG Hwf Hclosed Hmem; subst.\n  - unfold CS.initial_machine_state. simpl.\n    destruct (prog_main p) as [main |] eqn:Hmain.\n    + simpl.\n      split; intros Hdomm; [apply /dommP|move : Hdomm => /dommP => Hdomm].\n      * rewrite domm_map (domm_prepare_procedures_initial_memory_aux p).\n        assumption.\n      * by rewrite domm_map (domm_prepare_procedures_initial_memory_aux p)\n          in Hdomm. \n    + destruct (cprog_main_existence Hclosed) as [_ [Hcontra _]].\n      rewrite Hmain in Hcontra. discriminate.\n  - specialize\n      (IHstar _ Logic.eq_refl Logic.eq_refl Hwf Hclosed Logic.eq_refl)\n      as Hmem.\n    inversion Hstep12 as [? ? ? ? Hstep12']; subst.\n    inversion Hstep12'; subst;\n      try (assumption); simpl in *.\n    + split; intros Hdomm; [apply /dommP|move : Hdomm => /dommP => Hdomm].\n      * erewrite <- Memory.domm_store; last eassumption.\n        apply/dommP; by eapply Hmem.\n      * erewrite <- Memory.domm_store in Hdomm; last eassumption.\n        move : Hdomm => /dommP => Hdomm. by eapply Hmem in Hdomm.\n    + split; intros Hdomm; [apply /dommP|move : Hdomm => /dommP => Hdomm].\n      * erewrite <- Memory.domm_alloc; last eassumption.\n        apply/dommP; by eapply Hmem.\n      * erewrite <- Memory.domm_alloc in Hdomm; last eassumption.\n        move : Hdomm => /dommP => Hdomm. by eapply Hmem in Hdomm.\nQed.\n\nLemma mem_comp_some_link_in_left_or_in_right s p c t mem compMem cid:\n  well_formed_program p ->\n  well_formed_program c ->\n  is_prefix s (program_link p c) t ->\n  CS.state_mem s = mem ->\n  mem cid = Some compMem ->\n  (cid \\in domm (prog_interface p) \\/ cid \\in domm (prog_interface c)).\nProof.\n  (* Set up induction on star from left to right. *)\n  unfold is_prefix. simpl.\n  intros Hwfp Hwfc Hstar Hmem HcompMem.\n  assert (Hdomm : cid \\in domm mem) by (apply /dommP; eauto).\n  clear HcompMem.\n  set prog := program_link p c. fold prog in Hstar.\n  remember (CS.initial_machine_state prog) as s0 eqn:Hs0.\n  remember (prepare_global_env prog) as G eqn:HG.\n  revert mem cid compMem Hs0 HG Hmem Hdomm.\n  apply star_iff_starR in Hstar.\n  induction Hstar as [| s0 t1 s1 t2 s2 t12 Hstar01 IHstar Hstep12 Ht12];\n    intros mem cid Hs0 HG Hmem HcompMem Hdomm; subst.\n  - (* Base case. *)\n    unfold CS.initial_machine_state in Hdomm.\n    destruct (prog_main prog) as [main |] eqn:Hmain;\n      simpl in Hdomm.\n    + (* If we assume a closed program and linkable interfaces, this is easy\n         (and the contradictory case on [prog_main] goes away). As is, we need\n         to be a little more involved. *)\n      rewrite domm_map domm_prepare_procedures_initial_memory_aux in Hdomm.\n      unfold prog, program_link in Hdomm.\n      simpl in Hdomm.\n      destruct (cid \\in domm (prog_interface p)) eqn:Hcase1;\n        destruct (cid \\in domm (prog_interface c)) eqn:Hcase2;\n        auto. (* Only the contradictory case is left. *)\n      apply negb_true_iff in Hcase1. apply negb_true_iff in Hcase2.\n      destruct (dommP Hdomm) as [v Hcontra].\n      rewrite unionmE (dommPn Hcase1) (dommPn Hcase2) in Hcontra.\n      discriminate.\n    + rewrite domm0 in Hdomm. discriminate.\n  - (* Inductive step. *)\n    inversion Hstep12 as [? ? ? ? Hstep12']; subst.\n    inversion Hstep12'; subst;\n      eapply IHstar;\n      try eauto; (* Solve most goals. *)\n      simpl; simpl in Hdomm.\n    + (* Store *)\n      erewrite Memory.domm_store; eassumption.\n    + (* Alloc *)\n      erewrite Memory.domm_alloc; eassumption.\nQed.\n\nLemma value_mem_reg_domm_partition p c st t regs mem:\n  (* \"Running\" assumptions (what could be derived from the prefix run?) *)\n  well_formed_program p ->\n  well_formed_program c ->\n  mergeable_interfaces (prog_interface p) (prog_interface c) ->\n  closed_program (program_link p c) ->\n  (* \"Proper\" assumptions *)\n  is_prefix st (program_link p c) t ->\n  regs = CS.state_regs st ->\n  mem = CS.state_mem st ->\n  (forall ptr perm cid bid off,\n      Memory.load mem ptr = Some (Ptr (perm, cid, bid, off)) ->\n      cid \\in domm (prog_interface p) \\/\n      cid \\in domm (prog_interface c)\n  )\n  /\\\n  (forall reg perm cid bid off,\n      Register.get reg regs = Ptr (perm, cid, bid, off) ->\n      cid \\in domm (prog_interface p) \\/\n      cid \\in domm (prog_interface c)\n  ).\nProof.\n  (* Set up induction on star from left to right. *)\n  unfold is_prefix. simpl.\n  intros Hwfp Hwfc Hlinkable Hclosed Hstar ? ?; subst.\n  pose proof linking_well_formedness Hwfp Hwfc (proj1 Hlinkable) as Hwf.\n  set prog := program_link p c. fold prog in Hstar.\n  remember (CS.initial_machine_state prog) as s0 eqn:Hs0.\n  remember (prepare_global_env prog) as G eqn:HG.\n  revert Hs0 HG.\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  - (* Base case. *)\n    split.\n    + (* Memory domain. *)\n      intros ptr perm cid bid off Hload.\n      unfold CS.initial_machine_state in Hload.\n      destruct (cprog_main_existence Hclosed) as [main [Hmain _]].\n      rewrite Hmain in Hload.\n      destruct (prepare_procedures_memory_prog_buffers Hwf Hload)\n        as [(*Cbufs [*)buf (*[Hbufs*) [Hbuf Hptr]].\n      (* No pointers in static buffers. *)\n      exfalso. eapply prog_buffer_ptr; eassumption.\n    + (* Registers. *)\n      intros reg perm cid bid off Hget.\n      unfold CS.initial_machine_state in Hget.\n      destruct (prog_main prog) eqn:Hcase.\n      * unfold Register.get in Hget.\n        rewrite Register.reg_in_domm_init_Undef in Hget;\n          last (\n              unfold Register.init;\n              repeat rewrite domm_set;\n              repeat rewrite in_fsetU1;\n              now destruct reg).\n        by destruct reg.\n      * discriminate.\n  - (* Inductive step. *)\n    specialize (IHstar Logic.eq_refl Logic.eq_refl) as [IHload IHget].\n    split.\n    + (* Memory domain. *)\n      intros ptr perm cid bid off Hload.\n      inversion Hstep12 as [? ? ? ? Hstep12']; subst.\n      inversion Hstep12'; subst;\n        try (by (eapply IHload; eauto)). (* Solve most goals. *)\n      * (* IStore *)\n        destruct (Pointer.eqP ptr0 ptr) as [Heq | Hneq].\n        -- subst ptr0.\n           rewrite (Memory.load_after_store_eq _ _ _ _ H1) in Hload.\n           injection Hload as Hget.\n           eapply IHget; eassumption.\n        -- rewrite (Memory.load_after_store_neq _ _ _ _ _ Hneq H1) in Hload.\n           eapply IHload; eassumption.\n      * (* IAlloc *)\n        destruct\n          (addr_eqP (Pointer.component ptr, Pointer.block ptr)\n                    (Pointer.component ptr0, Pointer.block ptr0))\n          as [Heq | Hneq].\n        -- rewrite (Memory.load_after_alloc_eq _ _ _ _ _ _ H2 Heq) in Hload.\n           destruct (Permission.eqb (Pointer.permission ptr) Permission.data);\n             last discriminate.\n           destruct (Pointer.offset ptr <? Z.of_nat (Z.to_nat size))%Z;\n             last discriminate.\n           destruct (0 <=? Pointer.offset ptr)%Z;\n             discriminate.\n        -- rewrite (Memory.load_after_alloc _ _ _ _ _ _ H2 Hneq) in Hload.\n           eapply IHload; eassumption.\n    + (* Register file domain. *)\n      intros reg perm cid bid off Hget.\n      inversion Hstep12 as [? ? ? ? Hstep12']; subst.\n      inversion Hstep12'; subst;\n        try (by (eapply IHget; eauto)). (* Solve some goals. *)\n      * (* IConst *)\n        destruct (Register.eqb reg r) eqn:Hcase;\n          move: Hcase => /Register.eqP => Hcase.\n        -- subst r. rewrite Register.gss in Hget.\n           destruct v as [| ptr]; first discriminate.\n           injection Hget as Hget; subst ptr.\n           (* By program (and instruction) well-formedness. *)\n           destruct H as [Cprocs [Pcode [HCprocs [HPcode [_ [_ Hinstr]]]]]].\n           destruct (prepare_procedures_procs_prog_procedures Hwf HCprocs HPcode)\n             as [Cprocs' [P' [HCprocs' HPcode']]].\n           pose proof wfprog_well_formed_instructions\n                Hwf HCprocs' HPcode' (nth_error_In _ _ Hinstr)\n             as [Hptr Hbufs].\n           simpl in Hptr; subst cid.\n           apply star_iff_starR in Hstar01.\n           now eapply CS.star_pc_domm_non_inform; eauto.\n        -- rewrite Register.gso in Hget; last assumption.\n           eapply IHget; eassumption.\n      * (* IMov *)\n        destruct (Register.eqb reg rdest) eqn:Hcase;\n          move: Hcase => /Register.eqP => Hcase.\n        -- subst rdest. rewrite Register.gss in Hget.\n           eapply IHget; eassumption.\n        -- rewrite Register.gso in Hget; last assumption.\n           eapply IHget; eassumption.\n      * (* IBinOp *)\n        destruct (Register.eqb reg r3) eqn:Hcase;\n          move: Hcase => /Register.eqP => Hcase.\n        -- subst r3. rewrite Register.gss in Hget. subst result.\n           unfold eval_binop in Hget;\n             destruct op;\n             destruct (Register.get r1 regs) eqn:Hcase1;\n             destruct (Register.get r2 regs) eqn:Hcase2;\n             inversion Hget; subst.\n           ++ destruct t as [[[perm' C'] b'] o'].\n              injection H1 as ? ? ? ?; subst.\n              eapply IHget; eassumption.\n           ++ destruct t as [[[perm' C'] b'] o'].\n              injection H1 as ? ? ? ?; subst.\n              eapply IHget; eassumption.\n           ++ destruct t as [[[perm' C'] b'] o'].\n              injection H1 as ? ? ? ?; subst.\n              eapply IHget; eassumption.\n           ++ destruct t as [[[perm' C'] b'] o'].\n              destruct t0 as [[[perm0' C0'] b0'] o0'].\n              destruct (Permission.eqb perm' perm0');\n                destruct (C' =? C0');\n                destruct (b' =? b0');\n                discriminate.\n           ++ destruct (Pointer.leq t t0); discriminate.\n        -- rewrite Register.gso in Hget; last assumption.\n           eapply IHget; eassumption.\n      * (* IPtrOfLabel *)\n        destruct (Register.eqb reg r) eqn:Hcase;\n          move: Hcase => /Register.eqP => Hcase.\n        -- subst r. rewrite Register.gss in Hget.\n           injection Hget as Hget. subst ptr.\n           setoid_rewrite <- (find_label_in_component_1 _ _ _ _ H0).\n           apply star_iff_starR in Hstar01.\n           now eapply CS.star_pc_domm_non_inform; eauto.\n        -- rewrite Register.gso in Hget; last assumption.\n           eapply IHget; eassumption.\n      * (* ILoad *)\n        destruct (Register.eqb reg r2) eqn:Hcase;\n          move: Hcase => /Register.eqP => Hcase.\n        -- subst r2. rewrite Register.gss in Hget. subst v.\n           eapply IHload; eassumption.\n        -- rewrite Register.gso in Hget; last assumption.\n           eapply IHget; eassumption.\n      * (* IJal *)\n        destruct (Register.eqb reg R_RA) eqn:Hcase;\n          move: Hcase => /Register.eqP => Hcase.\n        -- subst reg. rewrite Register.gss in Hget.\n           injection Hget as Hget.\n           change cid with (Pointer.component (perm, cid, bid, off)).\n           rewrite <- Hget, -> Pointer.inc_preserves_component.\n           apply star_iff_starR in Hstar01.\n           now eapply CS.star_pc_domm_non_inform; eauto.\n        -- rewrite Register.gso in Hget; last assumption.\n           eapply IHget; eassumption.\n      * (* IAlloc *)\n        destruct (Register.eqb reg rptr) eqn:Hcase;\n          move: Hcase => /Register.eqP => Hcase.\n        -- subst rptr. rewrite Register.gss in Hget.\n           injection Hget as Hget; subst ptr.\n           setoid_rewrite (Memory.component_of_alloc_ptr _ _ _ _ _ H2).\n           apply star_iff_starR in Hstar01.\n           now eapply CS.star_pc_domm_non_inform; eauto.\n        -- rewrite Register.gso in Hget; last assumption.\n           eapply IHget; eassumption.\n      * (* ICall *)\n        rewrite Register.gi in Hget.\n        destruct (Register.eqP reg R_COM) as [Heq | Hneq];\n          last discriminate.\n        eapply IHget; eassumption.\n      * (* IReturn *)\n        rewrite Register.gi in Hget.\n        destruct (Register.eqP reg R_COM) as [Heq | Hneq];\n          last discriminate.\n        eapply IHget; eassumption.\nQed.\n\nDefinition dummy_value_of_node (n: node_t) := Ptr (Permission.data, n.1, n.2, 0%Z).\n\nLemma Reachable_induction_mem_invariant mem (P: value -> Prop):\n  (forall c b perm off perm' off',\n      P (Ptr (perm, c, b, off)) -> P (Ptr (perm', c, b, off')))\n  ->\n  (forall addr v, Memory.load mem addr = Some v -> P (Ptr addr) ->  P v) ->\n  (\n    forall (aset: {fset node_t}) (a: node_t),\n      Reachable mem aset a ->\n      (forall (a': node_t),\n          a' \\in aset -> (forall perm off, P (Ptr (perm, a'.1, a'.2, off)))) ->\n      (forall perm off, P (Ptr (perm, a.1, a.2, off)))\n  ).\nProof.\n  intros Pproperty mem_invariant. intros ? ? Hreach.\n  induction Hreach as [? Hin | ? ? ? ? Hreach' IH Hin Hcomp]; intros aset_invariant.\n  - apply aset_invariant; auto.\n  - intros perm off. \n    assert (exists off offv, Memory.load mem (Permission.data, cid, bid, off) =\n                             Some (Ptr (Permission.data, b'.1, b'.2, offv))\n           ) as [offl [offv Hload]].\n    {\n      destruct b' as [b'cid b'bid]; simpl in *.\n      apply In_in in Hcomp. erewrite ComponentMemory.load_block_load in Hcomp.\n      unfold Memory.load. simpl. rewrite Hin. destruct Hcomp as [? [? ?]]. by eauto.\n    }\n\n    specialize (IH aset_invariant Permission.data offl).\n    eapply Pproperty. eapply mem_invariant; eauto.\nQed.\n    \nCorollary addr_shared_so_far_domm_partition p c st t a cid:\n  (* \"Running\" assumptions (what could be derived from the prefix run?) *)\n  well_formed_program p ->\n  well_formed_program c ->\n  mergeable_interfaces (prog_interface p) (prog_interface c) ->\n  (* \"Proper\" assumptions *)\n  is_prefix st (program_link p c) t ->\n  closed_program (program_link p c) ->\n  well_formed_program (program_link p c) ->\n  addr_shared_so_far a t ->\n  cid = a.1 ->\n  (cid \\in domm (prog_interface p) \\/ cid \\in domm (prog_interface c)).\nProof.\n  generalize st.\n  pose (P :=\n          fun v =>\n            match v with\n            | Ptr (perm, cid, b, o) =>\n              (cid \\in domm (prog_interface p) \\/ cid \\in domm (prog_interface c))\n            | _ => True\n            end\n       ).\n  assert (Pproperty: forall c b perm off perm' off',\n             P (Ptr (perm, c, b, off)) -> P (Ptr (perm', c, b, off'))).\n  {\n    by intros; auto.\n  }\n  revert a cid.\n  induction t as [|t e] using last_ind.\n  - intros ? ? ? ? ? ? ? ? ? Hshr ?; inversion Hshr; by find_nil_rcons.\n  - intros ? ? ? Hwfp Hwfc Hifaces Hpref Hclosed Hwf Hshr ?.\n    destruct a as [acid abid]. simpl in *; subst.\n    apply star_iff_starR in Hpref. \n    apply starR_rcons in Hpref as [st1 [se1 [Ht1 [He1 HE0]]]];\n      last by apply CS.singleton_traces_non_inform. \n    inversion Hshr as [? ? ? Hreach | ? ? ? ? Hshr' Hreach]; find_rcons_rcons.\n    + inversion He1 as [? ? ? ? Hstepinform Hevent]; subst.\n      inversion Hstepinform; subst; simpl in *; try discriminate;\n        inversion Hevent; subst; simpl in *;\n          apply star_iff_starR in Ht1;\n          (** TODO: specialize value_mem_reg_domm_partition more before applying it. *)\n          specialize (value_mem_reg_domm_partition\n                        _ _ _ _ _ _ Hwfp Hwfc Hifaces Hclosed\n                        Ht1 Logic.eq_refl Logic.eq_refl) as Hinvariants;\n          destruct Hinvariants as [mem_invariant reg_invariant].\n      * (** ICall *)\n        assert (mem_invariant':\n                  forall (addr : Pointer.t) (v : value),\n                    Memory.load mem addr = Some v -> P (Ptr addr) -> P v\n               ).\n        {\n          intros [[[? ?] ?] ?] v Hload _.\n          destruct v as [| [[[? ?] ?] ?] |]; unfold P; auto.\n          eapply mem_invariant; by eauto. \n        }\n        \n        specialize (Reachable_induction_mem_invariant mem P Pproperty mem_invariant')\n          as Hinduction.\n        simpl in *.\n        \n          specialize (Hinduction _ _ Hreach). apply Hinduction; auto; last exact Z0.\n          intros ? Ha' _ _.\n          destruct (Register.get R_COM regs)\n            as [| [[[perm cid] bid] off] | ] eqn:ereg;\n            simpl in *; try by rewrite in_fset0 in Ha'.\n          destruct (Permission.eqb perm Permission.data) eqn:eperm; simpl in *;\n            try by rewrite in_fset0 in Ha'.\n          rewrite in_fset1 in Ha'. move : Ha' => /eqP => Ha'; inversion Ha'; subst.\n          eapply reg_invariant; by eauto.\n          exact Permission.data. (* FIXME: New subgoal after changing permission equality, suspect. *)\n      * (** IReturn *)\n        (** CAUTION: !!!!!!!!! exactly the same proof as ICall !!!!!!!!!*)\n        assert (mem_invariant':\n                  forall (addr : Pointer.t) (v : value),\n                    Memory.load mem addr = Some v -> P (Ptr addr) -> P v\n               ).\n        {\n          intros [[[? ?] ?] ?] v Hload _.\n          destruct v as [| [[[? ?] ?] ?] |]; unfold P; auto.\n          eapply mem_invariant; by eauto. \n        }\n        \n        specialize (Reachable_induction_mem_invariant mem P Pproperty mem_invariant')\n          as Hinduction.\n\n        simpl in *.\n        specialize (Hinduction _ _ Hreach). apply Hinduction; auto; last exact Z0.\n        intros ? Ha' _ _.\n        destruct (Register.get R_COM regs)\n          as [| [[[perm cid] bid] off] | ] eqn:ereg;\n          simpl in *; try by rewrite in_fset0 in Ha'.\n        destruct (Permission.eqb perm Permission.data) eqn:eperm; simpl in *;\n          try by rewrite in_fset0 in Ha'.\n        rewrite in_fset1 in Ha'. move : Ha' => /eqP => Ha'; inversion Ha'; subst.\n        eapply reg_invariant; by eauto.\n          exact Permission.data. (* FIXME: New subgoal after changing permission equality, suspect. *)\n        \n    + inversion He1 as [? ? ? ? Hstepinform Hevent]; subst.\n      inversion Hstepinform; subst; simpl in *; try discriminate;\n        inversion Hevent; subst; simpl in *;\n          apply star_iff_starR in Ht1;\n          (** TODO: specialize value_mem_reg_domm_partition more before applying it. *)\n          specialize (value_mem_reg_domm_partition\n                        _ _ _ _ _ _ Hwfp Hwfc Hifaces Hclosed\n                        Ht1 Logic.eq_refl Logic.eq_refl) as Hinvariants;\n          destruct Hinvariants as [mem_invariant reg_invariant].\n\n      * (** ICall *)\n        assert (mem_invariant':\n                  forall (addr : Pointer.t) (v : value),\n                    Memory.load mem addr = Some v -> P (Ptr addr) -> P v\n               ).\n        {\n          intros [[[? ?] ?] ?] v Hload _.\n          destruct v as [| [[[? ?] ?] ?] |]; unfold P; auto.\n          eapply mem_invariant; by eauto. \n        }\n        \n        specialize (Reachable_induction_mem_invariant mem P Pproperty mem_invariant')\n          as Hinduction.\n        \n        specialize (IHt _ addr'.1 _ Hwfp Hwfc Hifaces Ht1 Hclosed Hwf Hshr' Logic.eq_refl).\n        specialize (Hinduction _ _ Hreach). apply Hinduction; auto; last exact Z0.\n        intros ? Ha'? ?.\n        rewrite in_fset1 in Ha'. move : Ha' => /eqP => Ha'; inversion Ha'; subst.\n        eapply IHt; eauto.\n        exact Permission.data. (* FIXME: New subgoal after changing permission equality, suspect. *)\n\n      * (** IReturn *)\n        assert (mem_invariant':\n                  forall (addr : Pointer.t) (v : value),\n                    Memory.load mem addr = Some v -> P (Ptr addr) -> P v\n               ).\n        {\n          intros [[[? ?] ?] ?] v Hload _.\n          destruct v as [| [[[? ?] ?] ?] |]; unfold P; auto.\n          eapply mem_invariant; by eauto. \n        }\n        \n        specialize (Reachable_induction_mem_invariant mem P Pproperty mem_invariant')\n          as Hinduction.\n        \n        specialize (IHt _ addr'.1 _ Hwfp Hwfc Hifaces Ht1 Hclosed Hwf Hshr' Logic.eq_refl).\n        specialize (Hinduction _ _ Hreach). apply Hinduction; auto; last exact Z0.\n        intros ? Ha'? ?.\n        rewrite in_fset1 in Ha'. move : Ha' => /eqP => Ha'; inversion Ha'; subst.\n        eapply IHt; eauto.\n        exact Permission.data. (* FIXME: New subgoal after changing permission equality, suspect. *)\nQed.\n\nLemma no_step_can_write_non_shared_content p:\n  well_formed_program p ->\n  closed_program p ->\n  forall s t t_inform s',\n  is_prefix s p t ->\n  CS.step (prepare_global_env p) s t_inform s' ->\n  (\n    (\n      forall ptr vptr,\n        Memory.load (CS.state_mem s') ptr = Some (Ptr vptr) ->\n        Memory.load (CS.state_mem s) ptr <> Some (Ptr vptr) ->\n        (\n          forall c b,\n            Pointer.permission vptr = Permission.data ->\n            c = Pointer.component vptr ->\n            b = Pointer.block vptr ->\n            (\n              c = Pointer.component (CS.state_pc s) \\/\n              addr_shared_so_far (c, b) t\n            )\n        )\n    )\n    /\\\n    (\n      forall r vptr,\n        Register.get r (CS.state_regs s') = Ptr vptr ->\n        Register.get r (CS.state_regs s) <> Ptr vptr ->\n        (\n          forall c b,\n            Pointer.permission vptr = Permission.data ->\n            c = Pointer.component vptr ->\n            b = Pointer.block vptr ->\n            (\n              c = Pointer.component (CS.state_pc s) \\/\n              addr_shared_so_far (c, b) t\n            )\n        )\n    )\n  ).\nProof.\n  intros Hwf Hclosed ? ? ? ? Hpref Hstep.\n  assert (Hpref': is_prefix s' p (t ++ project_non_inform t_inform)).\n  {\n    eapply star_trans; last eauto.\n    - exact Hpref.\n    - econstructor.\n      + by apply CS.step_inform_step_non_inform; eassumption.\n      + by econstructor.\n      + by rewrite E0_right. \n  }\n  specialize (is_prefix_wf_state_t _ _ _ Hclosed Hwf Hpref')\n    as [Hmem' (*[Hregs' _]*)Hregs'].\n  specialize (is_prefix_wf_state_t _ _ _ Hclosed Hwf Hpref)\n    as [Hmem (*[Hregs _]*)Hregs].\n\n  inversion Hstep; simpl in *; subst.\n  - split; intros ? ? Hnew Hnotold ? ? ? ? ?; subst; try congruence.\n  - split; intros ? ? Hnew Hnotold ? ? ? ? ?; subst; try congruence.\n  - split; intros loc ? Hnew Hnotold ? ? ? ? ?; subst; try congruence.\n    destruct (loc == r) eqn:eloc; move : eloc => /eqP => eloc; subst.\n    + rewrite Register.gss in Hnew.\n      specialize (CS.IConst_possible_values _ Hwf _ _ _ H)\n        as [[? ?]| [? [? [? [? [? [? [? ?]]]]]]]];\n        subst; simpl in *; first congruence.\n      inversion Hnew; subst. simpl. by left.\n    + rewrite Register.gso in Hnew; auto. congruence.\n  - split; intros loc ? Hnew Hnotold ? ? Hperm ? ?; subst;\n      try congruence.\n    destruct (loc == rdest) eqn:eloc; move : eloc => /eqP => eloc; subst.\n    + rewrite Register.gss in Hnew.\n      specialize (Hregs _ _ Hnew Hperm)\n        as [|]; subst; [by left|by right].\n    + rewrite Register.gso in Hnew; auto. congruence.\n  - split; intros loc ? Hnew Hnotold ? ? Hperm ? ?; subst;\n      try congruence.\n    destruct (loc == r3) eqn:eloc; move : eloc => /eqP => eloc; subst.\n    + rewrite Register.gss in Hnew. unfold result in *.\n      destruct vptr as [[[vperm vc] vb] voff]. simpl in *. subst.\n      specialize (eval_binop_ptr _ _ _ _ Hnew)\n        as [? [? [Hor [? [? ?]]]]]; simpl in *; subst.\n      symmetry in H0.\n      destruct Hor as [[Hgetptr _]|[Hgetptr _]];\n        specialize (Hregs _ _ Hgetptr H0) as [|]; subst;\n          try (by left); try by right.\n    + rewrite Register.gso in Hnew; auto. congruence.\n  - split; intros loc ? Hnew Hnotold ? ? Hperm ? ?; subst;\n      try congruence.\n    simpl in *. apply find_label_in_component_1 in H0.\n    destruct (loc == r) eqn:eloc; move : eloc => /eqP => eloc; subst.\n    + rewrite Register.gss in Hnew. left. congruence.\n    + rewrite Register.gso in Hnew; auto. congruence.\n  - split; intros loc ? Hnew Hnotold ? ? Hperm ? ?; subst;\n      try congruence.\n    destruct (loc == r2) eqn:eloc; move : eloc => /eqP => eloc; subst.\n    + rewrite Register.gss in Hnew. subst. simpl in *.\n      assert (Hpermptr: Pointer.permission ptr = Permission.data).\n      { by apply Memory.load_some_permission in H1. }\n      specialize (Hregs _ _ H0 Hpermptr).\n      specialize (Hmem _ _ H1 Hperm).\n      inversion Hmem; subst; simpl in *.\n      * inversion Hregs; simpl in *; subst; simpl in *; subst;\n          first (left; congruence); first (congruence).\n      * by right.\n      * by left.\n    + rewrite Register.gso in Hnew; auto. congruence.\n  - split; intros loc ? Hnew Hnotold ? ? Hperm ? ?; subst;\n      try congruence.\n    destruct (Pointer.eq loc ptr) eqn:eloc;\n      move : eloc => /Pointer.eqP => eloc; subst.\n    + apply Memory.load_after_store_eq in H1.\n      rewrite H1 in Hnew. injection Hnew => Hrewr.\n      specialize (Hregs _ _ Hrewr Hperm)\n        as [|]; subst; [by left|by right].\n    + eapply Memory.load_after_store_neq with (ptr' := loc) in H1; auto.\n      congruence.\n  - split; intros loc ? Hnew Hnotold ? ? Hperm ? ?; subst;\n      try congruence.\n    simpl in *. apply find_label_in_component_1 in H0.\n    destruct (loc == R_RA) eqn:eloc; move : eloc => /eqP => eloc; subst.\n    + rewrite Register.gss in Hnew. left. inversion Hnew.\n      by rewrite Pointer.inc_preserves_component.\n    + rewrite Register.gso in Hnew; auto. congruence.\n  - split; intros loc ? Hnew Hnotold ? ? Hperm ? ?; subst;\n      try congruence.\n  - split; intros loc ? Hnew Hnotold ? ? Hperm ? ?; subst;\n      try congruence.\n  - split; intros loc ? Hnew Hnotold ? ? Hperm ? ?; subst;\n      try congruence.\n  - split; intros loc ? Hnew Hnotold ? ? Hperm ? ?; subst;\n      try congruence.\n  - split; intros loc ? Hnew Hnotold ? ? Hperm ? ?; subst;\n      try congruence.\n    + destruct (addr_eqb \n                  (Pointer.component ptr, Pointer.block ptr)\n                  (Pointer.component loc, Pointer.block loc)) eqn:eloc;\n        move : eloc => /addr_eqP => eloc; subst.\n      * symmetry in eloc.\n        specialize (Memory.load_after_alloc_eq _ _ _ _ _ _ H2 eloc).\n        intros ?.\n        destruct (Permission.eqb (Pointer.permission loc)\n                                 Permission.data); try congruence.\n        destruct (Pointer.offset loc <? Z.of_nat (Z.to_nat size))%Z;\n          last congruence.\n        destruct (0 <=? Pointer.offset loc)%Z; congruence.\n      * erewrite Memory.load_after_alloc in Hnew; eauto.\n        congruence.\n    + destruct (loc == rptr) eqn:eloc;\n        move : eloc => /eqP => eloc; subst.\n      * rewrite Register.gss in Hnew. subst. simpl in *.\n        inversion Hnew. subst.\n        by apply Memory.component_of_alloc_ptr in H2; left.\n      * rewrite Register.gso in Hnew; auto. congruence.\n  - split; intros loc ? Hnew Hnotold ? ? Hperm ? ?; subst;\n      try congruence.\n    simpl in *.\n    destruct (loc == R_COM) eqn:eloc; move : eloc => /eqP => eloc; subst.\n    + rewrite Register.gicom in Hnew. congruence.\n    + rewrite Register.gio in Hnew; congruence.\n  - split; intros loc ? Hnew Hnotold ? ? Hperm ? ?; subst;\n      try congruence.\n    simpl in *.\n    destruct (loc == R_COM) eqn:eloc; move : eloc => /eqP => eloc; subst.\n    + rewrite Register.gicom in Hnew. congruence.\n    + rewrite Register.gio in Hnew; congruence.\nQed.    \n\nLemma no_silent_star_can_write_non_shared_content p:\n  well_formed_program p ->\n  closed_program p ->\n  forall s t s',\n  is_prefix s p t ->\n  star CS.step_non_inform (prepare_global_env p) s E0 s' ->\n  (\n    (\n      forall ptr vptr,\n        Memory.load (CS.state_mem s') ptr = Some (Ptr vptr) ->\n        Memory.load (CS.state_mem s) ptr <> Some (Ptr vptr) ->\n        (\n          forall c b,\n            Pointer.permission vptr = Permission.data ->\n            c = Pointer.component vptr ->\n            b = Pointer.block vptr ->\n            (\n              c = Pointer.component (CS.state_pc s) \\/\n              addr_shared_so_far (c, b) t\n            )\n        )\n    )\n    /\\\n    (\n      forall r vptr,\n        Register.get r (CS.state_regs s') = Ptr vptr ->\n        Register.get r (CS.state_regs s) <> Ptr vptr ->\n        (\n          forall c b,\n            Pointer.permission vptr = Permission.data ->\n            c = Pointer.component vptr ->\n            b = Pointer.block vptr ->\n            (\n              c = Pointer.component (CS.state_pc s) \\/\n              addr_shared_so_far (c, b) t\n            )\n        )\n    )\n  ).\nProof.\n  intros Hwf Hclosed ? ? ? Hpref Hstar.\n  remember E0 as t_inform.\n  revert Heqt_inform.\n  induction Hstar; intros HE0; subst.\n  - split; intros loc ? Hnew Hnotold ? ? Hperm ? ?; subst; congruence.\n  - assert (t1 = E0 /\\ t2 = E0) as [? ?]; subst.\n    { by now (destruct t1; destruct t2). }\n\n    assert (HinstIH: is_prefix s2 p t).\n    {\n      apply star_iff_starR.\n      econstructor;\n        first (by apply star_iff_starR; eauto);\n        first (eassumption);\n        first (by rewrite E0_right).\n    }\n    specialize (IHHstar HinstIH Logic.eq_refl) as [s3s2mem s3s2reg].\n    specialize (CS.step_non_inform_step_inform _ _ _ _ H)\n      as [? [Hinform HE0_]].\n    \n    specialize (no_step_can_write_non_shared_content\n                  _ Hwf Hclosed _ _ _ _ Hpref Hinform)\n      as [s2s1mem s2s1reg]; eauto.\n    assert (Hrewr: Pointer.component (CS.state_pc s1) =\n                   Pointer.component (CS.state_pc s2)).\n    { eapply CS.silent_step_non_inform_preserves_component; eauto. }\n    split; intros loc ? Hnew Hnotold ? ? Hperm ? ?; subst.\n    + specialize (s3s2mem _ _ Hnew).\n      destruct (Memory.load (CS.state_mem s2) loc == Some (Ptr vptr))\n               eqn:eloc_s2; move : eloc_s2 => /eqP => eloc_s2.\n      * specialize (s2s1mem _ _ eloc_s2 Hnotold).\n        eapply s2s1mem; by eauto.\n      * specialize (s3s2mem eloc_s2). rewrite Hrewr. by eauto.\n    + specialize (s3s2reg _ _ Hnew).\n      destruct (Register.get loc (CS.state_regs s2) == Ptr vptr)\n               eqn:eloc_s2; move : eloc_s2 => /eqP => eloc_s2.\n      * specialize (s2s1reg _ _ eloc_s2 Hnotold).\n        eapply s2s1reg; by eauto.\n      * specialize (s3s2reg eloc_s2). rewrite Hrewr. by eauto.\nQed.                                                        \n\nLemma no_silent_star_can_reach_non_shared_content p:\n  well_formed_program p ->\n  closed_program p ->\n  forall s t s',\n  is_prefix s p t ->\n  star CS.step_non_inform (prepare_global_env p) s E0 s' ->\n  forall cstart' bstart',\n    (\n      cstart' = Pointer.component (CS.state_pc s') \\/\n      exists r ostart', Register.get r (CS.state_regs s') =\n                   Ptr (Permission.data, cstart', bstart', ostart')\n    )\n    ->\n    forall cb,\n      Reachable (CS.state_mem s') (fset1 (cstart', bstart')) cb ->\n      (\n        (\n          exists cstart bstart,\n            (\n              cstart = Pointer.component (CS.state_pc s) \\/\n              exists r ostart, Register.get r (CS.state_regs s) =\n                          Ptr (Permission.data, cstart, bstart, ostart)\n            )\n            /\\\n            Reachable (CS.state_mem s) (fset1 (cstart, bstart)) cb\n        )\n        \\/\n        cb.1 = Pointer.component (CS.state_pc s)\n        \\/\n        addr_shared_so_far cb t\n      ).\nProof.\n  intros Hwf Hclosed ? ? ? Hpref Hstar ? ? Hcbstart' ? Hreach.\n  specialize (no_silent_star_can_write_non_shared_content\n                _ Hwf Hclosed _ _ _ Hpref Hstar) as [ss'mem ss'regs].\n  specialize (is_prefix_wf_state_t _ _ _ Hclosed Hwf Hpref) as [Hwfmem Hwfregs].\n  remember (fset1 (cstart', bstart')) as start. revert Heqstart.\n  induction Hreach; intros Heqstart; subst.\n  - rewrite in_fset1 in H. move : H => /eqP => H; subst.\n    destruct Hcbstart' as [G|[r [off Hget]]]; subst; [left; eexists; exists bstart'|].\n    + split; [|eapply Reachable_refl; by rewrite in_fset1].\n      left. symmetry.\n        by eapply CS.epsilon_star_non_inform_preserves_component\n          with (p := p); eauto.\n    + destruct (Register.get r (CS.state_regs s) ==\n                Ptr (Permission.data, cstart', bstart', off)) eqn:eget_s;\n        move: eget_s => /eqP => eget_s.\n      * left. exists cstart', bstart'.\n        split; [|eapply Reachable_refl; by rewrite in_fset1].\n        right. by eauto.\n      * specialize (ss'regs _ _ Hget eget_s _ _ Logic.eq_refl Logic.eq_refl\n                            Logic.eq_refl) as [G|G]; by intuition.\n  - destruct b' as [cidl bidl].\n    assert (exists ol optr,\n               Memory.load (CS.state_mem s')\n                           (Permission.data, cid, bid, optr) =\n               Some (Ptr (Permission.data, cidl, bidl, ol))\n           ) as [ol [optr Hload]].\n    {\n      unfold Memory.load. simpl. rewrite H.\n      apply ComponentMemory.load_block_load.\n        by apply (@In_in (prod_ordType nat_ordType nat_ordType)).\n    }\n    destruct (Memory.load (CS.state_mem s)\n                          (Permission.data, cid, bid, optr) == \n              Some (Ptr (Permission.data, cidl, bidl, ol))\n             ) eqn:wasLoadable; move : wasLoadable => /eqP => wasLoadable.\n    + specialize (IHHreach Logic.eq_refl) as\n          [ [cstart [bstart [Hcbstart Hreachcidbid]]] | [Hcid|Hshared]].\n      * left. exists cstart, bstart. split; first assumption.\n        unfold Memory.load in wasLoadable.\n        simpl in *.\n        destruct (CS.state_mem s cid) as [cMem|] eqn:ecMem; last discriminate.\n        eapply Reachable_step.\n        -- exact Hreachcidbid.\n        -- eassumption.\n        -- apply In_in, ComponentMemory.load_block_load. by eauto.\n      * specialize (Hwfmem _ _ wasLoadable Logic.eq_refl) as Hwfload.\n        inversion Hwfload as [| |]; simpl in *; subst; by intuition.\n      * specialize (Hwfmem _ _ wasLoadable Logic.eq_refl) as Hwfload.\n        inversion Hwfload as [| |]; simpl in *; subst; by intuition.\n    + specialize (ss'mem _ _ Hload wasLoadable _ _\n                           Logic.eq_refl Logic.eq_refl Logic.eq_refl)\n        as [G1|G2]; by auto.\nQed.\n\nInductive wf_reach (pc_comp: Component.id) (t: trace event) :\n  {fset node_t} -> node_t -> Prop\n  :=\n  | shared_reachable:           \n      forall load_at reached,\n        addr_shared_so_far reached t ->\n        wf_reach pc_comp t load_at reached\n  | private_reachable_and_exists_private:\n      forall load_at reached,\n        ~addr_shared_so_far reached t ->\n        (\n          exists priv,\n            priv \\in load_at /\\\n            ~addr_shared_so_far priv t /\\\n            priv.1 = reached.1\n        )\n        ->\n        wf_reach pc_comp t load_at reached\n  | current_pc_reachable:\n      forall load_at reached,\n      reached.1 = pc_comp ->\n      wf_reach pc_comp t load_at reached.\n\nLemma initial_wf_reach p :\n  closed_program p ->\n  well_formed_program p ->\n  prog_main p ->\n  forall (reached : node_t) (start_set : {fset node_t}),\n    Reachable (CS.state_mem (CS.initial_machine_state p)) start_set reached\n    ->\n    wf_reach Component.main E0 start_set reached.\nProof.\n  intros Hclosed Hwf Hmain.\n  assert (Hnothing_shared: forall a, ~addr_shared_so_far a E0).\n  { unfold E0. intros ? contra. by inversion contra; find_nil_rcons. }\n  intros ? ? Hreach.\n  induction Hreach; subst.\n  - apply private_reachable_and_exists_private.\n    + apply Hnothing_shared.\n    + eexists; eauto.\n  - specialize (initial_wf_mem _ Hclosed Hwf Hmain) as Hwf_mem.\n    destruct b' as [creached breached].\n    assert (exists optr oload,\n               Memory.load\n                 (CS.state_mem (CS.initial_machine_state p))\n                 (Permission.data, cid, bid, oload)\n               = Some (Ptr (Permission.data, creached, breached, optr))\n           ) as [optr [oload Hload]].\n    {\n      unfold Memory.load. simpl. rewrite H.\n      rewrite -ComponentMemory.load_block_load. by apply In_in in H0.\n    }\n    unfold CS.initial_machine_state in Hload.\n    rewrite Hmain in Hload. simpl in *.\n    specialize (Hwf_mem _ _ Hload Logic.eq_refl).\n    inversion Hwf_mem; subst; simpl in *; subst; try by intuition.\n    + inversion IHHreach; subst; simpl in *; subst; try by intuition.\n      * apply private_reachable_and_exists_private; eauto.\n      * apply current_pc_reachable; auto.    \n    (* + by apply Hnothing_shared in H1. *)\n    + by apply Hnothing_shared in H3.\nQed.\n\n\n Lemma wf_mem_Reachable_not_shared_so_far:\n   forall reached cstart bstart mem t cur_pc,\n     ~addr_shared_so_far reached t ->\n     ~addr_shared_so_far (cstart, bstart) t ->\n     Reachable mem (fset1 (cstart, bstart)) reached ->\n     reached.1 <> cur_pc ->\n     wf_mem_wrt_t_pc mem t cur_pc ->\n     cstart = reached.1.\n Proof.\n   intros ? ? ? ? ? ? Hnotshr1 Hnotshr2 Hreach Hneq Hwf.\n   revert Hnotshr1 Hneq.\n   induction Hreach; intros Hnotshr1 Hneq; subst.\n   - rewrite in_fset1 in H. move : H => /eqP => H.\n       by inversion H.\n   - destruct b' as [creached breached].\n     assert (exists optr oload,\n                Memory.load\n                  mem\n                  (Permission.data, cid, bid, oload)\n                = Some (Ptr (Permission.data,\n                             creached, breached, optr))\n            ) as [optr [oload Hload]].\n     {\n       unfold Memory.load. simpl. rewrite H.\n       rewrite -ComponentMemory.load_block_load.\n         by apply In_in in H0.\n     }\n     specialize (Hwf _ _ Hload Logic.eq_refl).\n     inversion Hwf; subst; simpl in *; subst; try congruence.\n     + by apply IHHreach. \n     + by intuition.\n Qed.\n\n\nLemma is_prefix_wf_reach s p t :\n    closed_program p ->\n    well_formed_program p ->\n    is_prefix s p t ->\n    forall reached start_set,\n      Reachable (CS.state_mem s) start_set reached ->\n      wf_reach (Pointer.component (CS.state_pc s)) t start_set reached.\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  - (* Base case. *)\n    unfold CS.initial_machine_state. simpl.\n    assert (Hmain : prog_main p).\n    {\n      rewrite <- wfprog_main_component; auto.\n      specialize (cprog_main_existence Hclosed) as [? [? [Hprogproc ?]]].\n      rewrite wfprog_defined_procedures; auto.\n      apply/dommP. by eauto.\n    }\n    rewrite Hmain. simpl.\n    by eapply initial_wf_reach; eauto. \n  - (* Inductive step. *)\n    assert (wf_state_t s1 t1) as [Hwf_mem1 Hwf_regs1].\n    {\n      eapply is_prefix_wf_state_t; eauto.\n      by apply star_iff_starR in Hstar01.\n    }\n    assert (wf_state_t s2 (t1 ** t2)) as [Hwf_mem2 Hwf_regs2].\n    {\n      eapply is_prefix_wf_state_t; eauto.\n      apply star_iff_starR. eapply starR_step; eauto.\n    }\n    specialize (IHstar Logic.eq_refl Logic.eq_refl).\n    rename H into Hreach.\n    inversion Hreach; subst.\n    + destruct (classic (addr_shared_so_far reached (t1 ** t2)))\n        as [Hshrb|Hnotshrb].\n      * apply shared_reachable; auto.\n      * apply private_reachable_and_exists_private; by eauto.\n    + inversion Hstep12 as [? ? ? ? Hstep12']; subst.\n      inversion Hstep12'; subst; simpl in *;\n        (* A few useful simplifications. *)\n        (try rewrite E0_right);\n        (try rewrite Pointer.inc_preserves_component);\n        (try rewrite <- (find_label_in_component_1 _ _ _ _ H3));\n        (try rewrite -> H5);\n        (try rewrite <- (find_label_in_procedure_1 _ _ _ _ H5));\n        (* Many goals follow directly from the IH now. *)\n        try by (eapply IHstar; eapply Reachable_step; eauto).\n      * (* Store *)\n        specialize (Reachable_Memory_store _ _ _ _ _ _ H4 Hreach)\n          as [|[cptr [bptr [optr [cv [bv [ov [eq1 [eq2 [reach1 reach2]]]]]]]]]].\n        -- by apply IHstar; auto.\n        -- assert (wf_reach (Pointer.component pc) t1 start_set (cptr, bptr))\n            as wf1.\n           { by apply IHstar. }\n           assert (wf_reach (Pointer.component pc) t1 (fset1 (cv, bv)) reached)\n             as wf2.\n           { by apply IHstar. }\n           inversion wf2; clear wf2; subst; simpl in *; subst.\n           ++ by apply shared_reachable.\n           ++ destruct reached as [creached breached].\n              destruct H6 as [[? ?] [Hin [Hnotshr Heq]]]. simpl in *.\n              rewrite in_fset1 in Hin. move : Hin => /eqP => Hin.\n              inversion Hin. subst. clear Hin.\n              (** Probably need to instantiate Hwf_regs1 to get just 1 case. *)\n              specialize (Hwf_regs1 _ _ eq1 Logic.eq_refl) as Hr2.\n              inversion Hr2 as [|contra]; subst; [|by intuition].\n              apply current_pc_reachable; auto.\n           ++ destruct reached as [creached breached]. simpl in *. subst.\n              apply current_pc_reachable; auto.\n\n      * (* IAlloc *)\n        apply IHstar.\n        eapply Reachable_Memory_alloc; eauto.\n      * (* ICall *)\n        setoid_rewrite cats1.\n        specialize (IHstar _ _ Hreach) as IHstar_start_set.\n        specialize (Reachable_exists_one_start _ _ _ Hreach)\n          as [start [Hstart_in Hreach_start]].\n        specialize (IHstar _ _ Hreach_start) as IHstar_start.\n        inversion IHstar_start; subst.\n        -- apply shared_reachable.\n           eapply reachable_from_previously_shared; eauto.\n           eapply Reachable_refl. by rewrite in_fset1.\n        -- destruct (classic (addr_shared_so_far\n                                reached\n                                (rcons t1\n                                       (ECall (Pointer.component pc)\n                                              P (Register.get R_COM regs)\n                                              mem C')\n                                )               \n                    )) as [G|G].\n           ++ apply shared_reachable; exact G.\n           ++ destruct H7 as [priv [Hin [Hnotshr Heq]]].\n              destruct priv as [cpriv bpriv].\n              destruct reached as [creached breached].\n              simpl in *; subst.\n              rewrite in_fset1 in Hin. move : Hin => /eqP => Hin. subst.\n              assert (~addr_shared_so_far (creached, bpriv)\n                       (rcons t1\n                              (ECall (Pointer.component pc)\n                                     P (Register.get R_COM regs) mem C'))\n                     ) as Hstillpriv.\n              {\n                unfold not. intros contra. exfalso. apply G.\n                inversion contra; find_rcons_rcons. simpl in *.\n                - apply reachable_from_args_is_shared. simpl.\n                  eapply Reachable_transitive; eauto.\n                - simpl in *. eapply reachable_from_previously_shared; eauto.\n                  simpl. eapply Reachable_transitive; eauto.\n              }\n              apply private_reachable_and_exists_private; eauto.\n        -- destruct (classic (addr_shared_so_far\n                                reached\n                                (rcons t1\n                                       (ECall (Pointer.component pc)\n                                              P (Register.get R_COM regs)\n                                              mem C')\n                                )               \n                    )) as [G|G].\n           ++ apply shared_reachable; exact G.\n           ++ destruct reached as [? breached]. simpl in *; subst.\n              destruct (classic (addr_shared_so_far start t1))\n                as [startshr|startnotshr].\n              ** exfalso. apply G. eapply reachable_from_previously_shared.\n                 { exact startshr. } { assumption. }\n              ** assert (~ addr_shared_so_far start\n                           (rcons t1\n                                  (ECall (Pointer.component pc) P\n                                         (Register.get R_COM regs) mem C'))\n                        ).\n                 {\n                   unfold not. intros contra.\n                   inversion contra; find_rcons_rcons; simpl in *.\n                   - exfalso. apply G. eapply reachable_from_args_is_shared.\n                     simpl. eapply Reachable_transitive; eauto.\n                   - exfalso. apply G.\n                     eapply reachable_from_previously_shared; eauto.\n                     simpl. eapply Reachable_transitive; eauto.\n                 }\n                 apply private_reachable_and_exists_private; auto.\n                 exists start. split; [assumption|split; [assumption|]].\n                 destruct start as [cstart bstart].\n                 eapply wf_mem_Reachable_not_shared_so_far; eauto.\n                   by rewrite -cats1.\n\n      * (* IReturn *)\n        setoid_rewrite cats1.\n        specialize (IHstar _ _ Hreach) as IHstar_start_set.\n        specialize (Reachable_exists_one_start _ _ _ Hreach)\n          as [start [Hstart_in Hreach_start]].\n        specialize (IHstar _ _ Hreach_start) as IHstar_start.\n        inversion IHstar_start; subst.\n        -- apply shared_reachable.\n           eapply reachable_from_previously_shared; eauto.\n           eapply Reachable_refl. by rewrite in_fset1.\n        -- destruct (classic (addr_shared_so_far\n                                reached\n                                (rcons t1\n                                       (ERet (Pointer.component pc)\n                                             (Register.get R_COM regs)\n                                             mem (Pointer.component pc'))\n                                )               \n                    )) as [G|G].\n           ++ apply shared_reachable; exact G.\n           ++ destruct H5 as [priv [Hin [Hnotshr Heq]]].\n              destruct priv as [cpriv bpriv].\n              destruct reached as [creached breached].\n              simpl in *; subst.\n              rewrite in_fset1 in Hin. move : Hin => /eqP => Hin. subst.\n              assert (~addr_shared_so_far (creached, bpriv)\n                       (rcons t1\n                              (ERet (Pointer.component pc)\n                                    (Register.get R_COM regs) mem\n                                    (Pointer.component pc')))\n                     ) as Hstillpriv.\n              {\n                unfold not. intros contra. exfalso. apply G.\n                inversion contra; find_rcons_rcons. simpl in *.\n                - apply reachable_from_args_is_shared. simpl.\n                  eapply Reachable_transitive; eauto.\n                - simpl in *. eapply reachable_from_previously_shared; eauto.\n                  simpl. eapply Reachable_transitive; eauto.\n              }\n              apply private_reachable_and_exists_private; eauto.\n        -- destruct (classic (addr_shared_so_far\n                                reached\n                                (rcons t1\n                                       (ERet (Pointer.component pc)\n                                             (Register.get R_COM regs) mem\n                                             (Pointer.component pc'))\n                                )               \n                    )) as [G|G].\n           ++ apply shared_reachable; exact G.\n           ++ destruct reached as [? breached]. simpl in *; subst.\n              destruct (classic (addr_shared_so_far start t1))\n                as [startshr|startnotshr].\n              ** exfalso. apply G. eapply reachable_from_previously_shared.\n                 { exact startshr. } { assumption. }\n              ** assert (~ addr_shared_so_far start\n                           (rcons t1\n                                  (ERet (Pointer.component pc)\n                                        (Register.get R_COM regs) mem\n                                        (Pointer.component pc')))\n                        ).\n                 {\n                   unfold not. intros contra.\n                   inversion contra; find_rcons_rcons; simpl in *.\n                   - exfalso. apply G. eapply reachable_from_args_is_shared.\n                     simpl. eapply Reachable_transitive; eauto.\n                   - exfalso. apply G.\n                     eapply reachable_from_previously_shared; eauto.\n                     simpl. eapply Reachable_transitive; eauto.\n                 }\n                 apply private_reachable_and_exists_private; auto.\n                 exists start. split; [assumption|split; [assumption|]].\n                 destruct start as [cstart bstart].\n                 eapply wf_mem_Reachable_not_shared_so_far; eauto.\n                   by rewrite -cats1.\nQed.\n\nLemma not_executing_can_not_share_ p:\n  well_formed_program p ->\n  closed_program p ->\n  forall t C s e b,\n    (forall b', ~ addr_shared_so_far (C, b') t) ->\n    is_prefix s p (rcons t e) ->\n    C <> cur_comp_of_event e ->\n    ~ addr_shared_so_far (C, b) (rcons t e).\nProof.\n  intros Hwf Hclosed t ? ? ? ? Csharednothing Hpref Cnotexec Cshared.\n  rewrite -cats1 in Hpref.\n  apply star_app_inv in Hpref as [s' [Hstar1 Hstar2]];\n    last by apply CS.singleton_traces_non_inform.\n  apply star_cons_inv in Hstar2\n    as [s1' [s2' [Hstar_before [Hstep Hstar_after]]]];\n    last by apply CS.singleton_traces_non_inform.\n\n  assert (Hstar_e: is_prefix s2' p (t ++ [:: e])).\n  {\n    eapply star_right; last reflexivity; last exact Hstep.\n    eapply star_trans with (s2 := s'); eauto. by rewrite E0_right. \n  }\n\n  assert (mem_of_event e = CS.state_mem s1' /\\\n          arg_of_event e = Register.get R_COM (CS.state_regs s1') /\\\n          cur_comp_of_event e = Pointer.component (CS.state_pc s1'))\n    as [Hrewr1 [Hrewr2 Hrewr3]].\n  {\n    inversion Hstep; subst.\n    inversion H; subst; simpl in *; try discriminate;\n      inversion H0; by subst.\n  }\n\n  rewrite Hrewr3 in Cnotexec.\n  assert (s's1'pc: Pointer.component (CS.state_pc s') =\n                   Pointer.component (CS.state_pc s1')).\n  {\n    eapply CS.epsilon_star_non_inform_preserves_component; eauto.\n  }\n  \n  specialize (no_silent_star_can_write_non_shared_content\n                _ Hwf Hclosed _ _ _ Hstar1 Hstar_before\n             ) as [s's1'mem s's1'regs].\n  specialize (no_silent_star_can_reach_non_shared_content\n                _ Hwf Hclosed _ _ _ Hstar1 Hstar_before) as Hno_new_reach.\n  specialize (is_prefix_wf_state_t _ _ _ Hclosed Hwf Hstar1)\n    as [Hwfmem_s' Hwfregs_s'].\n  specialize (is_prefix_wf_reach  _ _ _ Hclosed Hwf Hstar1) as Hwfreach_s'.\n  assert (star_s1': Star (CS.sem_non_inform p)\n                         (CS.initial_machine_state p) t s1').\n  {\n    eapply star_trans with (s2 := s'); eauto. by rewrite E0_right.\n  }\n  specialize (is_prefix_wf_reach  _ _ _ Hclosed Hwf star_s1') as Hwfreach_s1'.\n  inversion Cshared as [ ? ? ? Hreach | ? ? ? ? Hprevshared Hreach];\n    find_rcons_rcons; rewrite Hrewr1 in Hreach.\n  - destruct (Register.get R_COM (CS.state_regs s1'))\n        as [| [[[[] cstart'] bstart'] off] |] eqn:eR_COM;\n      simpl in *; rewrite Hrewr2 in Hreach; simpl in *;\n        try by apply Reachable_fset0 in Hreach.\n    specialize (s's1'regs _ _ eR_COM).\n    specialize (Hno_new_reach cstart' bstart').\n    epose proof (Hno_new_reach _ _ Hreach) as [| [|]].\n    + destruct H as [cstart [bstart [Hcbstart Hreachs']]].\n      destruct Hcbstart as [|]; simpl in *; subst.\n      * inversion Hreachs'; subst.\n        -- rewrite in_fset1 in H. move : H => /eqP => H; inversion H; subst.\n           congruence.\n        -- assert (exists ol optr,\n                      Memory.load (CS.state_mem s')\n                                  (Permission.data, cid, bid, optr) =\n                      Some (Ptr (Permission.data, C, b, ol))\n                  ) as [ol [optr Hload]].\n           {\n             unfold Memory.load. simpl. rewrite H0.\n             apply ComponentMemory.load_block_load.\n               by apply (@In_in (prod_ordType nat_ordType nat_ordType)).\n           }\n           specialize (Hwfmem_s' _ _ Hload Logic.eq_refl).\n           inversion Hwfmem_s' as [| |]; simpl in *; subst; try by intuition.\n           ++ (** Derive a contradiction from Hreachs', H2, and Cnotexec.. *)\n             specialize (Hwfreach_s' _ _ Hreachs').\n             inversion Hwfreach_s' as [| | ];\n               simpl in *; subst; try by intuition.\n             (** one case remains. *)\n             destruct H5 as [priv [Hin [Hnotshr Heq]]].\n             rewrite in_fset1 in Hin. move: Hin => /eqP => Hin. subst.\n             simpl in *. congruence.\n           ++ eapply Csharednothing; eauto.\n      * inversion Hreachs'; subst.\n        -- rewrite in_fset1 in H0. move : H0 => /eqP => H0; inversion H0; subst.\n           destruct H as [r [ostart Hget]].\n           specialize (Hwfregs_s'  _ _ Hget Logic.eq_refl).\n           inversion Hwfregs_s'; subst; simpl in *; first by intuition.\n             by apply Csharednothing in H1.\n        -- assert (exists ol optr,\n                      Memory.load (CS.state_mem s')\n                                  (Permission.data, cid, bid, optr) =\n                      Some (Ptr (Permission.data, C, b, ol))\n                  ) as [ol [optr Hload]].\n           {\n             unfold Memory.load. simpl. rewrite H1.\n             apply ComponentMemory.load_block_load.\n               by apply (@In_in (prod_ordType nat_ordType nat_ordType)).\n           }\n           destruct H as [r [ostart Hget]].\n           specialize (Hwfregs_s'  _ _ Hget Logic.eq_refl).\n           inversion Hwfregs_s'; subst; simpl in *.\n           ++ specialize (Hwfmem_s' _ _ Hload Logic.eq_refl).\n              inversion Hwfmem_s' as [| |]; simpl in *; subst; try by intuition.\n              ** (** Derive a contradiction from Hreachs', H, and Cnotexec.. *)\n                specialize (Hwfreach_s' _ _ Hreachs').\n                inversion Hwfreach_s' as [| |];\n                  simpl in *; subst; try by intuition.\n                (** one case remains. *)\n                destruct H5 as [priv [Hin [Hnotshr Heq]]].\n                rewrite in_fset1 in Hin. move: Hin => /eqP => Hin. subst.\n                simpl in *. congruence.\n              ** eapply Csharednothing; eauto.\n           ++ (** Derive a contradiction from Hreachs', and H3, which tell\n                  us that either ~Cnotexec or ~Csharednothing. *)\n             specialize (Hwfreach_s' _ _ Hreachs').\n             inversion Hwfreach_s' as [| |];\n               simpl in *; subst; try by intuition.\n             (** two cases remain. *)\n             ** by apply Csharednothing in H.\n             ** destruct H4 as [priv [Hin [Hnotshr Heq]]].\n                rewrite in_fset1 in Hin. move: Hin => /eqP => Hin. subst.\n                simpl in *. congruence.\n           \n    + simpl in *. congruence.\n    + by apply Csharednothing in H.\n  - (** Distinguish two cases of addr'.1: \n        case addr'.1 == C => contradiction to Csharednothing\n        case addr'.1 != C => contradiction to the reachability wf.\n     *)\n    destruct addr' as [addr'c addr'b].\n    destruct (addr'c =? C) eqn:eaddr'c.\n    + apply beq_nat_true in eaddr'c. subst.\n        by apply Csharednothing in Hprevshared.\n    + apply beq_nat_false in eaddr'c.\n      specialize (Hwfreach_s1' _ _ Hreach).\n      inversion Hwfreach_s1' as [| |];\n        simpl in *; subst; try by intuition.\n      * by apply Csharednothing in H.\n      * destruct H0 as [priv [Hin [Hnotshr Heq]]].\n        rewrite in_fset1 in Hin. move: Hin => /eqP => Hin. subst.\n        simpl in *. congruence.\n      Unshelve. by eauto.\nQed.\n      \n\n\nLemma not_shared_diff_comp_not_shared_call:\n  forall p s C Cb C' P b t arg mem,\n    well_formed_program p ->\n    closed_program p ->\n    CSInvariants.CSInvariants.is_prefix s p (rcons t (ECall C P arg mem C')) ->\n    C <> Cb ->\n    (forall b', ~ addr_shared_so_far (Cb, b') t) ->\n    ~ addr_shared_so_far (Cb, b) (rcons t (ECall C P arg mem C')).\nProof.\n  intros.\n  eapply not_executing_can_not_share_; eauto.\nQed.\n\nLemma load_Some_component_buffer:\n  forall p s t e ptr v,\n    well_formed_program p ->\n    closed_program p ->\n    CSInvariants.CSInvariants.is_prefix s p (rcons t e) ->\n    Memory.load (mem_of_event e) ptr = Some v ->\n    Pointer.component ptr \\in domm (prog_interface p).\n  Proof.\n    intros ? ? ? ? ? ? Hwf Hclosed Hpref Hload.\n    rewrite -cats1 in Hpref.\n    apply star_app_inv in Hpref as [s1 [Hstar1 Hstar2]];\n      last by apply CS.singleton_traces_non_inform.\n    apply star_cons_inv in Hstar2 as [s1' [s2' [Hstar_before [Hstep Hstar_after]]]];\n      last by apply CS.singleton_traces_non_inform.\n    assert (Hrewr: CS.state_mem s2' = mem_of_event e).\n    {\n      inversion Hstep as [? ? ? ? Hstep']; subst.\n      inversion Hstep'; subst; try discriminate; simpl in *; destruct e; try discriminate; try by inversion H.\n    }\n    rewrite -Hrewr in Hload.\n    unfold Memory.load in Hload.\n    destruct (Permission.eqb (Pointer.permission ptr) Permission.data);\n      last discriminate.\n    destruct (CS.state_mem s2' (Pointer.component ptr)) eqn:emem;\n      last discriminate.\n    assert (Hprefs2': Star (CS.sem_non_inform p) (CS.initial_machine_state p)\n                           (t ++ [::e]) s2').\n    {\n      eapply star_trans; eauto.\n      eapply star_trans; eauto.\n      - eapply star_step; eauto. constructor.\n      - easy.\n    }\n    assert (Hin: Pointer.component ptr \\in domm (CS.state_mem s2')).\n    { by apply/dommP; eauto. }\n    specialize (mem_comp_in_domm_prog_interface_some\n                  _ _ _ _ (Pointer.component ptr)\n                  Hwf Hclosed Hprefs2' Logic.eq_refl) as G.\n      by apply G; eauto.\n  Qed.\n    \n  Lemma not_executing_can_not_share s p t e C b:\n    well_formed_program p ->\n    closed_program p ->\n    is_prefix s p (rcons t e) ->\n    C <> cur_comp_of_event e ->\n    (forall b', ~ addr_shared_so_far (C, b') t) ->\n    ~ addr_shared_so_far (C, b) (rcons t e).\n  Proof. intros. by eapply not_executing_can_not_share_; eauto. Qed.\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/Intermediate/CSInvariants.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.25746013034107273}}
{"text": "Require Import Coqlib.\nRequire Import ITreelib.\nRequire Import Skeleton.\nRequire Import PCM.\nRequire Import Any.\nRequire Import ModSem.\nRequire Import SimSTS.\nRequire Import STSNorm.\nRequire Import STS Behavior.\n\nSet Implicit Arguments.\n\nSection CONV.\n\n  CoFixpoint decompile_STS\n             (state: Type)\n             (step: state -> option event -> state -> Prop)\n             (state_sort: state -> sort):\n    state -> itree eventE Any.t :=\n    fun st0 =>\n      match (state_sort st0) with\n      | STS.angelic =>\n        Vis (Take {st': state | @step st0 None st' })\n            (fun st1 => decompile_STS step state_sort (proj1_sig st1))\n      | STS.demonic =>\n        Vis (Choose {st': state | @step st0 None st' })\n            (fun st1 => decompile_STS step state_sort (proj1_sig st1))\n      | STS.final z =>\n        Ret (z)\n      | STS.vis =>\n        '(exist _ (event_sys fn args _) _) <-\n        trigger (Choose {ev': event | exists st1, @step st0 (Some ev') st1 });;\n        rv <- trigger (Syscall fn args (fun rv => exists st1, (@step st0 (Some (event_sys fn args rv)) st1)));;\n        Vis (Choose {st1: state | @step st0 (Some (event_sys fn args rv)) st1 })\n            (fun st1 => decompile_STS step state_sort (proj1_sig st1))\n      end\n  .\n\n\n  Lemma unfold_decompile_STS\n        (state: Type)\n        (step: state -> option event -> state -> Prop)\n        (state_sort: state -> sort)\n        (st0: state):\n    decompile_STS step state_sort st0\n    =\n    match (state_sort st0) with\n    | STS.angelic =>\n      Vis (Take {st': state | @step st0 None st' })\n          (fun st1 => decompile_STS step state_sort (proj1_sig st1))\n    | STS.demonic =>\n      Vis (Choose {st': state | @step st0 None st' })\n          (fun st1 => decompile_STS step state_sort (proj1_sig st1))\n    | STS.final z =>\n      Ret (z)\n    | STS.vis =>\n      '(exist _ (event_sys fn args _) _) <-\n      trigger (Choose {ev': event | exists st1, @step st0 (Some ev') st1 });;\n      rv <- trigger (Syscall fn args (fun rv => exists st1, (@step st0 (Some (event_sys fn args rv)) st1)));;\n      Vis (Choose {st1: state | @step st0 (Some (event_sys fn args rv)) st1 })\n          (fun st1 => decompile_STS step state_sort (proj1_sig st1))\n    end\n  .\n  Proof.\n    eapply observe_eta. reflexivity.\n  Qed.\n\n  (* Set Primitive Projections.  *)\n\nEnd CONV.\n\nSection PROOF.\n\n  Import Behavior.Beh.\n\n  Context {CONF: EMSConfig}.\n\n  Variable\n    (state: Type)\n    (st_init0: state)\n    (step0: state -> option event -> state -> Prop)\n    (state_sort0: state -> sort).\n\n  Hypothesis wf_vis0 :\n    forall (st0 : state) (ev0 ev1 : option event) (st1 st2 : state),\n      state_sort0 st0 = vis ->\n      step0 st0 ev0 st1 -> step0 st0 ev1 st2 -> ev0 = ev1 -> st1 = st2.\n\n  Hypothesis wf_vis_event0 :\n    forall (st0 : state) (ev0 : option event) (st1 : state),\n      state_sort0 st0 = vis ->\n      step0 st0 ev0 st1 -> ev0 <> None.\n\n  Hypothesis wf_angelic0 :\n    forall (st0 : state) (ev : option event) (st1 : state),\n      state_sort0 st0 = angelic -> step0 st0 ev st1 -> ev = None.\n\n  Hypothesis wf_demonic0 :\n    forall (st0 : state) (ev : option event) (st1 : state),\n      state_sort0 st0 = demonic -> step0 st0 ev st1 -> ev = None.\n\n  Hypothesis wf_final0 :\n    forall st0 ev st1 r (FIN: state_sort0 st0 = final r) (STEP: step0 st0 ev st1),\n      False.\n\n  Let L0 :=\n    {|\n    STS.state := state;\n    STS.step := step0;\n    STS.initial_state := st_init0;\n    STS.state_sort := state_sort0;\n    STS.wf_vis := wf_vis0;\n    STS.wf_vis_event := wf_vis_event0;\n    STS.wf_angelic := wf_angelic0;\n    STS.wf_demonic := wf_demonic0;\n    STS.wf_final := wf_final0;\n    |}\n  .\n\n  Let L1 := vis_normalize L0.\n\n  Let step := norm_step state_sort0 step0.\n  Let state_sort := norm_state_sort state_sort0.\n  Let st_init := norm_state st_init0.\n\n  Let wf_vis := L1.(wf_vis).\n  Let wf_angelic := L1.(wf_angelic).\n  Let wf_demonic := L1.(wf_demonic).\n\n  Let STS_itree := decompile_STS step state_sort st_init.\n  Let L1_itree := ModSemL.compile_itree STS_itree.\n\n  Hypothesis wf_syscall0 :\n    forall ev,\n      (exists st0 st1, (state_sort0 st0 = vis) /\\ (step0 st0 (Some ev) st1)) ->\n      syscall_sem ev.\n\n  Lemma wf_syscall :\n    forall ev,\n      (exists st0 st1, (state_sort st0 = vis) /\\ (step st0 (Some ev) st1)) ->\n      syscall_sem ev.\n  Proof.\n    i. des. unfold step in *. unfold state_sort in *.\n    destruct st0. destruct st1. ss; clarify.\n    destruct o; ss; clarify.\n    2:{ destruct (state_sort0 s); ss; clarify. }\n    inv H0. eapply wf_syscall0; eauto.\n  Qed.\n\n  Hypothesis wf_finalize0:\n    forall st0 rv, state_sort0 st0 = final rv -> finalize (rv) = Some rv.\n\n  Lemma wf_finalize:\n    forall st0 rv, state_sort st0 = final rv -> finalize (rv) = Some rv.\n  Proof.\n    i. unfold state_sort, norm_state_sort in H. des_ifs. eapply wf_finalize0; et.\n  Qed.\n\n(**\nof_state =\nfun L1 : semantics => paco2 (_of_state L1) bot2\n     : forall L1 : semantics, STS.state L1 -> Tr.t -> Prop\n\npaco2 has 'fixed' semantics -> needs fixed semantics to do pcofix\n **)\n  Lemma beh_preserved_L1_dir :\n    forall st0 (tr: Tr.t),\n      of_state\n        L1_itree\n        (decompile_STS step state_sort st0)\n        tr\n      ->\n      of_state\n        L1\n        st0\n        tr.\n  Proof.\n    Ltac mclo := eapply gpaco4_uclo; [eapply (@sim_mon L1 L1_itree)|eapply (@sim_indC_spec L1 L1_itree)|].\n    Ltac mbase := gstep; [eapply (@sim_mon L1 L1_itree)|eapply sim_progress; [gbase; eauto|ss|ss]].\n    intros st0. eapply adequacy_aux.\n    instantiate (1:=false). instantiate (1:=false). ginit.\n    revert st0. gcofix CIH. i. mclo.\n    destruct (state_sort st0) eqn:SRT.\n    - eapply sim_indC_angelic_src; ss; clarify. i. esplits; et.\n      mclo. eapply sim_indC_angelic_tgt; ss; clarify.\n      + rewrite unfold_decompile_STS. rewrite SRT. ss.\n      + i.\n        set (cont:= (fun st1 : {st' | step st0 None st'} => decompile_STS step state_sort (st1 $))).\n        exists (cont (exist (fun st => step st0 None st) st_src1 STEP)). eexists.\n        { rewrite unfold_decompile_STS. rewrite SRT. econs 3. }\n        esplits; et. mbase.\n    - eapply sim_indC_demonic_tgt; ss; clarify.\n      + rewrite unfold_decompile_STS. rewrite SRT. ss.\n      + i. rewrite unfold_decompile_STS in STEP. rewrite SRT in STEP.\n        dependent destruction STEP.\n        destruct x. rename x into st1.\n        esplits; et. mclo. eapply sim_indC_demonic_src; ss; clarify.\n        exists st1. eexists; auto.\n        esplits; et. mbase.\n    - eapply sim_indC_fin; eauto.\n      ss. rewrite unfold_decompile_STS. rewrite SRT.\n      unfold ModSemL.state_sort. ss.\n      erewrite wf_finalize; et.\n    - eapply sim_indC_demonic_tgt; ss; clarify.\n      + rewrite unfold_decompile_STS. rewrite SRT. ss.\n      + i. rewrite unfold_decompile_STS in STEP. rewrite SRT in STEP.\n        rewrite bind_trigger in STEP.\n        dependent destruction STEP.\n        destruct x. des. destruct x.\n        esplits; et.\n        mclo. eapply sim_indC_vis; i; ss; clarify.\n        rewrite bind_trigger in STEP.\n        dependent destruction STEP.\n        des. rename RETURN into STEP.\n        exists st2. eexists.\n        { auto. }\n        esplits. mclo. eapply sim_indC_demonic_tgt; ss; clarify.\n        i. dependent destruction STEP0.\n        destruct x.\n        esplits; et. mbase.\n        assert (st2 = x).\n        { eapply wf_vis. apply SRT. apply STEP. apply s. reflexivity. }\n        clarify.\n    Unshelve. all: try exact 0.\n  Qed.\n\n  Lemma beh_preserved_L1_inv :\n    forall st0 (tr: Tr.t),\n      of_state\n        L1\n        st0\n        tr\n      ->\n      of_state\n        L1_itree\n        (decompile_STS step state_sort st0)\n        tr.\n  Proof.\n    Ltac mclo2 := eapply gpaco4_uclo; [eapply (@sim_mon L1_itree L1)|eapply (@sim_indC_spec L1_itree L1)|].\n    Ltac mbase2 := gstep; [eapply (@sim_mon L1_itree L1)|eapply sim_progress; [gbase; eauto|ss|ss]].\n    intros st0. eapply adequacy_aux.\n    instantiate (1:=false). instantiate (1:=false). ginit.\n    revert st0.\n    gcofix CIH. i. mclo2.\n    destruct (state_sort st0) eqn:SRT.\n    - eapply sim_indC_angelic_src; ss; clarify.\n      + rewrite unfold_decompile_STS. rewrite SRT. ss.\n      + i. rewrite unfold_decompile_STS in STEP. rewrite SRT in STEP.\n        dependent destruction STEP. destruct x.\n        esplits; et. mclo2. eapply sim_indC_angelic_tgt; ss; clarify.\n        exists x. exists s. esplits; et. mbase2.\n    - eapply sim_indC_demonic_tgt; ss; clarify. i.\n      esplits; et. mclo2. eapply sim_indC_demonic_src; ss; clarify.\n      + rewrite unfold_decompile_STS. rewrite SRT. ss.\n      + i. exists (decompile_STS step state_sort st_tgt1).\n        eexists.\n        { rewrite unfold_decompile_STS in *. rewrite SRT in *.\n          apply (ModSemL.step_choose (fun st1 : {st' | step st0 None st'} => decompile_STS step state_sort (st1 $)) (exist _ st_tgt1 STEP)). }\n        esplits; et. mbase2.\n    - econs; ss.\n      + rewrite unfold_decompile_STS. rewrite SRT.\n        unfold ModSemL.state_sort. ss.\n        erewrite wf_finalize; et.\n      + auto.\n    - assert (CASE: (forall ev st1, not (step st0 (Some ev) st1)) \\/ (exists ev st1, (step st0 (Some ev) st1))).\n      { destruct (classic (exists ev st1, step st0 (Some ev) st1)); eauto.\n        left. ii. apply H. eauto. }\n      destruct CASE.\n      + eapply sim_indC_vis_stuck_tgt; eauto.\n      + set (cont := fun x_ : {ev' : event | exists st1, step st0 (Some ev') st1} =>\n                       (let (x, _) := x_ in\n                        match x with\n                        | event_sys fn args _ =>\n                          ` rv0 : Any.t <-\n                                  trigger\n                                    (Syscall fn args\n                                             (fun rv0 : Any.t =>\n                                                exists st1, step st0 (Some (event_sys fn args rv0)) st1));;\n                                  Vis\n                                    (Choose {st1 | step st0 (Some (event_sys fn args rv0)) st1})\n                                    (fun\n                                        st1 : {st1 | step st0 (Some (event_sys fn args rv0)) st1}\n                                      => decompile_STS step state_sort (st1 $))\n                        end)).\n        destruct H.\n        eapply sim_indC_demonic_src; ss; clarify.\n        { rewrite unfold_decompile_STS. rewrite SRT. ss. }\n        exists (cont (exist (fun 'ev => exists st1, step st0 (Some ev) st1) x H)).\n        destruct x. eexists.\n        { rewrite unfold_decompile_STS. rewrite SRT. ss. rewrite bind_trigger.\n          eapply (ModSemL.step_choose cont (exist (fun 'ev => exists st1, step st0 (Some ev) st1) (event_sys fn args rv) H)). }\n        esplits; et.\n        mclo2. destruct H. rename s into STEP. subst cont.\n        set (cont := fun rv0 =>\n                       Vis\n                         (Choose\n                            {st1 | step st0 (Some (event_sys fn args rv0)) st1})\n                         (fun\n                             st1 : {st1 | step st0 (Some (event_sys fn args rv0)) st1} =>\n                             decompile_STS step state_sort (st1 $))).\n        eapply sim_indC_vis; eauto.\n        i. ss.\n        exploit wf_vis_norm.\n        { instantiate (1:= L1). exists L0. reflexivity. }\n        { ss. apply SRT. }\n        { apply STEP. }\n        { apply STEP0. }\n        i. des. clarify.\n        exists (cont rv). eexists.\n        { ss. rewrite bind_trigger. subst cont. ss.\n          apply (@ModSemL.step_syscall fn args rv (fun rv0 : Any.t => exists st1, step st0 (Some (event_sys fn args rv0)) st1) (fun x : Any.t => Vis (Choose {st1 | step st0 (Some (event_sys fn args x)) st1}) (fun st1 : {st1 | step st0 (Some (event_sys fn args x)) st1} => decompile_STS step state_sort (st1 $)))).\n          2:{ exists st_tgt1. auto. }\n          apply wf_syscall.\n          exists st0, st_tgt1. auto. }\n        esplits. mclo2. eapply sim_indC_demonic_src; ss; clarify.\n        subst cont. ss.\n        set (cont :=\n               (fun\n                   st1 :\n                     {st1 | step st0\n                                 (Some (event_sys fn args rv))\n                                 st1} =>\n                   decompile_STS step state_sort (st1 $))).\n        exists (cont (exist (fun st1 => step st0 (Some (event_sys fn args rv)) st1) st_tgt1 STEP)).\n        eexists.\n        { econs. }\n        esplits; et. mbase2.\n    Unshelve. all: try exact 0.\n  Qed.\n\n  Lemma beh_preserved_L1 :\n    forall st0 (tr: Tr.t),\n      of_state L1 st0 tr\n      <->\n      of_state\n        L1_itree\n        (decompile_STS step state_sort st0)\n        tr.\n  Proof.\n    split.\n    - apply beh_preserved_L1_inv.\n    - apply beh_preserved_L1_dir.\n  Qed.\n\n  Theorem beh_preserved :\n    exists itr, forall tr,\n        of_state L0 st_init0 tr\n        <->\n        of_state (ModSemL.compile_itree itr) itr tr.\n  Proof.\n    exists STS_itree. i.\n    assert (A: of_state (ModSemL.compile_itree STS_itree) STS_itree tr\n               =\n               of_state L1_itree (decompile_STS step state_sort st_init) tr).\n    { ss. }\n    rewrite A.\n    rewrite <- (beh_preserved_L1 st_init tr).\n    rewrite STSNorm.beh_preserved. eauto.\n  Qed.\n\nEnd PROOF.\n\n(* Import Behavior.Beh. *)\n\n(* Theorem exists_itree : *)\n(*   forall (L1: semantics), *)\n(*     (forall ev, *)\n(*         (exists st0 st1, (state_sort L1 st0 = vis) /\\ (step L1 st0 (Some ev) st1)) -> *)\n(*         syscall_sem ev) -> *)\n(*     exists itr, forall tr, *)\n(*         of_state L1 L1.(initial_state) tr *)\n(*         <-> *)\n(*         of_state (interpITree itr) itr tr. *)\n(* Proof. *)\n(*   i. destruct L1. ss. *)\n(*   revert state initial_state step state_sort wf_vis wf_angelic wf_demonic H. *)\n(*   eapply PROOF.beh_preserved. *)\n\n(* (** Universe consistency *) *)\n", "meta": {"author": "alxest", "repo": "CCR", "sha": "edcda8faae6580581e8e5b28050d755bcb29f55f", "save_path": "github-repos/coq/alxest-CCR", "path": "github-repos/coq/alxest-CCR/CCR-edcda8faae6580581e8e5b28050d755bcb29f55f/ems/STS2ITree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2574064547476038}}
{"text": "(* \n * © 2019 XXX.\n * \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": "usenix21-paper58", "repo": "paper58", "sha": "e5117b0cb1d749df1768c9098aee7112ae16d8e9", "save_path": "github-repos/coq/usenix21-paper58-paper58", "path": "github-repos/coq/usenix21-paper58-paper58/paper58-e5117b0cb1d749df1768c9098aee7112ae16d8e9/src/RealWorld.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2574064547476038}}
{"text": "Require Coq.Structures.Equalities.\nRequire Coq.FSets.FSetAVL.\nRequire Coq.FSets.FSetWeakList.\nRequire Coq.FSets.FMapFacts.\nRequire Coq.Lists.List.\n\nRequire Genevan.ProtoIdentifier.\nRequire Genevan.ProtoName.\nRequire Genevan.ListExts.\nRequire Genevan.ProtoPeer.Peer.\nRequire Genevan.ProtoPeer.CollectionT.\nRequire Genevan.ProtoPeer.CollectionOfProtocolsT.\n\n(** A concrete implementation of the _CollectionOfProtocolsT_ interface. *)\n\nModule CollectionOfProtocols\n  (A     : Peer.T)\n  (ASets : Peer.SetsT A)\n  (AC    : CollectionT.S A ASets)\n  (B     : Peer.T)\n  (BSets : Peer.SetsT B)\n  (BC    : CollectionT.S B BSets)\n: CollectionOfProtocolsT.S A ASets AC B BSets BC.\n\n  Module AF := FSetFacts.WFacts ASets.\n  Module BF := FSetFacts.WFacts BSets.\n\n  Record t := {\n    peersA : ASets.t;\n    peersB : BSets.t\n  }.\n\n  Definition setsHaveName (ps : t) (n : ProtoName.t) : Prop :=\n    AC.setsHaveName (peersA ps) n /\\ BC.setsHaveName (peersB ps) n.\n\n  Definition setsEitherNonEmpty (ps : t) : Prop :=\n    AC.setsNonEmpty (peersA ps) \\/ BC.setsNonEmpty (peersB ps).\n\n  Definition setsWF (ps : t) (n : ProtoName.t) : Prop :=\n    setsHaveName ps n /\\ setsEitherNonEmpty ps.\n\n  Module ByName      := ProtoName.Maps.\n  Module ByNameFacts := ProtoName.MapsFacts.\n\n  Definition mapWF (m : ByName.t t) : Prop :=\n    forall s n, ByName.MapsTo n s m -> setsWF s n.\n\n  Definition mapInA (e : A.t) (m : ByName.t t) : Prop :=\n    exists s, ByName.MapsTo (ProtoIdentifier.name (A.supports e)) s m /\\ ASets.In e (peersA s).\n\n  Definition mapInB (e : B.t) (m : ByName.t t) : Prop :=\n    exists s, ByName.MapsTo (ProtoIdentifier.name (B.supports e)) s m /\\ BSets.In e (peersB s).\n\n  Theorem mapWFEmpty : mapWF (ByName.empty t).\n  Proof.\n    unfold mapWF.\n    intros s n H_m.\n    rewrite ProtoName.MapsFacts.empty_mapsto_iff in H_m.\n    contradiction.\n  Qed.\n\n  Theorem mapInAEmptyFalse : forall a, ~mapInA a (ByName.empty t).\n  Proof.\n    unfold mapInA.\n    intros a.\n    unfold not; intro H_contra.\n    destruct H_contra as [x [Hc0 Hc1]].\n    rewrite ProtoName.MapsFacts.empty_mapsto_iff in Hc0.\n    exact Hc0.\n  Qed.\n\n  Theorem mapInBEmptyFalse : forall a, ~mapInB a (ByName.empty t).\n  Proof.\n    unfold mapInB.\n    intros b.\n    unfold not; intro H_contra.\n    destruct H_contra as [x [Hc0 Hc1]].\n    rewrite ProtoName.MapsFacts.empty_mapsto_iff in Hc0.\n    exact Hc0.\n  Qed.\n\n  Definition singletonAT (a : A.t) : t :=\n    Build_t (ASets.singleton a) BSets.empty.\n\n  Theorem setsHaveNameSingletonAT : forall a,\n    setsHaveName (singletonAT a) (ProtoIdentifier.name (A.supports a)).\n  Proof.\n    intros a.\n    constructor. {\n      apply AC.setsHaveNameSingleton.\n    } {\n      hnf.\n      unfold singletonAT.\n      intros x H_false.\n      simpl in H_false.\n      rewrite BF.empty_iff in H_false.\n      contradiction.\n    }\n  Qed.\n\n  Theorem setsEitherNonEmptySingletonAT : forall a,\n    setsEitherNonEmpty (singletonAT a).\n  Proof.\n    intros a.\n    unfold singletonAT.\n    unfold setsEitherNonEmpty.\n    unfold AC.setsNonEmpty.\n    left.\n    simpl.\n    unfold not; intro H_contra.\n    unfold ASets.Empty in H_contra.\n    assert (ASets.In a (ASets.singleton a)) as H_in\n      by (apply ASets.singleton_2; reflexivity).\n    pose proof (H_contra a).\n    contradiction.\n  Qed.\n\n  Theorem setsWFSingletonAT : forall a,\n    setsWF (singletonAT a) (ProtoIdentifier.name (A.supports a)).\n  Proof.\n    constructor.\n    apply setsHaveNameSingletonAT.\n    apply setsEitherNonEmptySingletonAT.\n  Qed.\n\n  Definition singletonBT (b : B.t) : t :=\n    Build_t ASets.empty (BSets.singleton b).\n\n  Theorem setsHaveNameSingletonBT : forall b,\n    setsHaveName (singletonBT b) (ProtoIdentifier.name (B.supports b)).\n  Proof.\n    intros b.\n    constructor. {\n      hnf.\n      unfold singletonAT.\n      intros x H_false.\n      simpl in H_false.\n      rewrite AF.empty_iff in H_false.\n      contradiction.\n    } {\n      apply BC.setsHaveNameSingleton.\n    }\n  Qed.\n\n  Theorem setsEitherNonEmptySingletonBT : forall b,\n    setsEitherNonEmpty (singletonBT b).\n  Proof.\n    intros b.\n    unfold singletonBT.\n    unfold setsEitherNonEmpty.\n    unfold BC.setsNonEmpty.\n    right.\n    simpl.\n    unfold not; intro H_contra.\n    unfold BSets.Empty in H_contra.\n    assert (BSets.In b (BSets.singleton b)) as H_in\n      by (apply BSets.singleton_2; reflexivity).\n    pose proof (H_contra b).\n    contradiction.\n  Qed.\n\n  Theorem setsWFSingletonBT : forall b,\n    setsWF (singletonBT b) (ProtoIdentifier.name (B.supports b)).\n  Proof.\n    constructor.\n    apply setsHaveNameSingletonBT.\n    apply setsEitherNonEmptySingletonBT.\n  Qed.\n\n  Definition addPeerAT (ps : t) (a : A.t) : t :=\n    Build_t (ASets.add a (peersA ps)) (peersB ps).\n\n  Theorem setsHaveNameAddPeerAT : forall ps a n,\n    setsHaveName ps n ->\n      ProtoIdentifier.name (A.supports a) = n ->\n        setsHaveName (addPeerAT ps a) n.\n  Proof.\n    unfold setsHaveName.\n    unfold AC.setsHaveName.\n    unfold ASets.For_all.\n    unfold addPeerAT.\n    simpl in *.\n    intros ps a n [H_hnL H_hnR] H_neq.\n    constructor. {\n      intros x H_inX.\n      destruct (A.eq_dec a x) as [H_eqax|H_neqax]. {\n        subst x.\n        exact H_neq.\n      } {\n        rewrite AF.add_neq_iff in H_inX.\n        apply (H_hnL x H_inX).\n        unfold not; intro H_contra.\n        rewrite H_contra in H_neqax.\n        contradict H_neqax; reflexivity.\n      }\n    } {\n      exact H_hnR.\n    }\n  Qed.\n\n  Theorem setsEitherNonEmptyAddPeerAT : forall ps a,\n    setsEitherNonEmpty ps -> setsEitherNonEmpty (addPeerAT ps a).\n  Proof.\n    unfold setsEitherNonEmpty.\n    unfold AC.setsNonEmpty.\n    unfold BC.setsNonEmpty.\n    unfold ASets.Empty.\n    simpl.\n    intros ps a [H_ane|H_bne]. {\n      left.\n      unfold not; intro H_contra.\n      pose proof (H_contra a) as H_contra2.\n      apply H_contra2.\n      apply ASets.add_1.\n      reflexivity.\n    } {\n      right; trivial.\n    }\n  Qed.\n\n  Theorem setsWFAddPeerAT : forall ps a n,\n    setsWF ps n ->\n      ProtoIdentifier.name (A.supports a) = n ->\n        setsWF (addPeerAT ps a) n.\n  Proof.\n    intros ps a n [H_wf0L H_wf0R] H_neq.\n    constructor. {\n      apply setsHaveNameAddPeerAT.\n      exact H_wf0L.\n      exact H_neq.\n    } {\n      apply setsEitherNonEmptyAddPeerAT.\n      exact H_wf0R.\n    }\n  Qed.\n\n  Definition addPeerBT (ps : t) (b : B.t) : t :=\n    Build_t (peersA ps) (BSets.add b (peersB ps)).\n\n  Theorem setsHaveNameAddPeerBT : forall ps b n,\n    setsHaveName ps n ->\n      ProtoIdentifier.name (B.supports b) = n ->\n        setsHaveName (addPeerBT ps b) n.\n  Proof.\n    unfold setsHaveName.\n    unfold BC.setsHaveName.\n    unfold BSets.For_all.\n    unfold addPeerBT.\n    simpl in *.\n    intros ps b n [H_hnL H_hnR] H_neq.\n    constructor. {\n      exact H_hnL.\n    } {\n      intros x H_inX.\n      destruct (B.eq_dec b x) as [H_eqax|H_neqax]. {\n        subst x.\n        exact H_neq.\n      } {\n        rewrite BF.add_neq_iff in H_inX.\n        apply (H_hnR x H_inX).\n        unfold not; intro H_contra.\n        rewrite H_contra in H_neqax.\n        contradict H_neqax; reflexivity.\n      }\n    }\n  Qed.\n\n  Theorem setsEitherNonEmptyAddPeerBT : forall ps b,\n    setsEitherNonEmpty ps -> setsEitherNonEmpty (addPeerBT ps b).\n  Proof.\n    unfold setsEitherNonEmpty.\n    unfold AC.setsNonEmpty.\n    unfold BC.setsNonEmpty.\n    unfold ASets.Empty.\n    simpl.\n    intros ps b [H_ane|H_bne]. {\n      left; trivial.\n    } {\n      right.\n      unfold not; intro H_contra.\n      pose proof (H_contra b) as H_contra2.\n      apply H_contra2.\n      apply BSets.add_1.\n      reflexivity.\n    }\n  Qed.\n\n  Theorem setsWFAddPeerBT : forall ps b n,\n    setsWF ps n ->\n      ProtoIdentifier.name (B.supports b) = n ->\n        setsWF (addPeerBT ps b) n.\n  Proof.\n    intros ps b n [H_wf0L H_wf0R] H_neq.\n    constructor. {\n      apply setsHaveNameAddPeerBT.\n      exact H_wf0L.\n      exact H_neq.\n    } {\n      apply setsEitherNonEmptyAddPeerBT.\n      exact H_wf0R.\n    }\n  Qed.\n\n  Theorem addBPreservesA : forall ps a b,\n    ASets.In a (peersA ps) -> ASets.In a (peersA (addPeerBT ps b)).\n  Proof. intros; auto. Qed.\n\n  Theorem addAPreservesB : forall ps a b,\n    BSets.In b (peersB ps) -> BSets.In b (peersB (addPeerAT ps a)).\n  Proof. intros; auto. Qed.\n\n  Definition addPeerA\n    (e : A.t)\n    (m : ByName.t t)\n  : ByName.t t :=\n    let name := ProtoIdentifier.name (A.supports e) in\n      match ByName.find name m with\n      | Some ex => ByName.add name (addPeerAT ex e) m\n      | None    => ByName.add name (singletonAT e) m\n      end.\n\n  Theorem mapWFAddPeerA : forall (m : ByName.t t) (e : A.t),\n    mapWF m -> mapWF (addPeerA e m).\n  Proof.\n    unfold mapWF.\n    unfold addPeerA.\n    intros m e H_wf.\n    remember (ProtoIdentifier.name (A.supports e)) as e_name.\n    intros s n H_mapsA.\n\n    destruct (ByName.find e_name m) as [ex|] eqn:H_find. {\n      rewrite <- ByNameFacts.find_mapsto_iff in H_find.\n      rewrite ByNameFacts.add_mapsto_iff in H_mapsA.\n      destruct H_mapsA as [[HL0 HL1]|[HR0 HR1]]. {\n        rewrite <- HL0 in *.\n        rewrite <- HL1.\n        pose proof (H_wf _ _ H_find) as H_prevWF.\n        symmetry in Heqe_name.\n        apply (setsWFAddPeerAT _ _ _ H_prevWF Heqe_name).\n      } {\n        apply (H_wf _ _ HR1).\n      }\n    } {\n      rewrite ByNameFacts.add_mapsto_iff in H_mapsA.\n      destruct H_mapsA as [[HL0 HL1]|[HR0 HR1]]. {\n        rewrite <- HL0 in *.\n        rewrite <- HL1.\n        rewrite Heqe_name.\n        apply (setsWFSingletonAT e).\n      } {\n        apply (H_wf _ _ HR1).\n      }\n    }\n  Qed.\n\n  Theorem mapInAddPeerA : forall (m : ByName.t t) (e : A.t),\n    mapInA e (addPeerA e m).\n  Proof.\n    unfold mapInA.\n    unfold addPeerA.\n    intros m e.\n    remember (ProtoIdentifier.name (A.supports e)) as e_name.\n    destruct (ByName.find e_name m) as [ex|] eqn:H_find. {\n      rewrite <- ByNameFacts.find_mapsto_iff in H_find.\n      unfold addPeerAT.\n      simpl.\n      exists (Build_t (ASets.add e (peersA ex)) (peersB ex)).\n      constructor. {\n        apply ByName.add_1; reflexivity.\n      } {\n        apply ASets.add_1.\n        reflexivity.\n      }\n    } {\n      unfold singletonAT.\n      exists (Build_t (ASets.singleton e) BSets.empty).\n      constructor. {\n        apply ByName.add_1; reflexivity.\n      } {\n        apply ASets.singleton_2; reflexivity.\n      }\n    }\n  Qed.\n\n  Theorem mapAddPeerAPreservesA : forall (m : ByName.t t) (e f : A.t),\n    mapInA f m -> mapInA f (addPeerA e m).\n  Proof.\n    intros m e f H_m.\n    remember (ProtoIdentifier.name (A.supports f)) as f_name.\n    remember (ProtoIdentifier.name (A.supports e)) as e_name.\n\n    destruct (A.eq_dec e f) as [H_efEq|H_efNeq]. {\n      subst f.\n      apply mapInAddPeerA.\n    } {\n      destruct (String.string_dec e_name f_name) as [H_efnEq|H_efnNeq]. {\n        unfold mapInA in *.\n        unfold addPeerA.\n        rewrite <- Heqf_name in *.\n        rewrite <- Heqe_name in *.\n        rewrite <- H_efnEq in *.\n        destruct (ByName.find e_name m) as [sBefore|] eqn:H_find. {\n          rewrite <- ByNameFacts.find_mapsto_iff in H_find.\n          destruct H_m as [sx [H_sx0 H_sx1]].\n          pose proof (ByNameFacts.MapsTo_fun H_find H_sx0) as H_same.\n          subst sx.\n          exists (addPeerAT sBefore e).\n          constructor. {\n            rewrite ByNameFacts.add_mapsto_iff.\n            constructor. {\n              constructor; reflexivity.\n            }\n          } {\n            unfold addPeerAT.\n            apply ASets.add_2.\n            exact H_sx1.\n          }\n        } {\n          destruct H_m as [sx [H_sx0 H_sx1]].\n          pose proof (ByName.find_1 H_sx0) as H_contra.\n          rewrite H_find in H_contra.\n          inversion H_contra.\n        }\n      } {\n        unfold mapInA in *.\n        unfold addPeerA.\n        rewrite <- Heqf_name in *.\n        rewrite <- Heqe_name in *.\n        destruct H_m as [sx [H_sx0 H_sx1]].\n        exists sx.\n\n        constructor. {\n          destruct (ByName.find e_name m) as [sBefore|] eqn:H_find. {\n            apply ByName.add_2.\n            exact H_efnNeq.\n            exact H_sx0.\n          } {\n            apply ByName.add_2.\n            exact H_efnNeq.\n            exact H_sx0.\n          }\n        } {\n          exact H_sx1.\n        }\n      }\n    }\n  Qed.\n\n  Definition addPeerB\n    (e : B.t)\n    (m : ByName.t t)\n  : ByName.t t :=\n    let name := ProtoIdentifier.name (B.supports e) in\n      match ByName.find name m with\n      | Some ex => ByName.add name (addPeerBT ex e) m\n      | None    => ByName.add name (singletonBT e) m\n      end.\n\n  Theorem mapInAddPeerB : forall (m : ByName.t t) (e : B.t),\n    mapInB e (addPeerB e m).\n  Proof.\n    unfold mapInB.\n    unfold addPeerB.\n    intros m e.\n    remember (ProtoIdentifier.name (B.supports e)) as e_name.\n    destruct (ByName.find e_name m) as [ex|] eqn:H_find. {\n      rewrite <- ByNameFacts.find_mapsto_iff in H_find.\n      unfold addPeerBT.\n      simpl.\n      exists (Build_t (peersA ex) (BSets.add e (peersB ex))).\n      constructor. {\n        apply ByName.add_1; reflexivity.\n      } {\n        apply BSets.add_1.\n        reflexivity.\n      }\n    } {\n      unfold singletonBT.\n      exists (Build_t ASets.empty (BSets.singleton e)).\n      constructor. {\n        apply ByName.add_1; reflexivity.\n      } {\n        apply BSets.singleton_2; reflexivity.\n      }\n    }\n  Qed.\n\n  Theorem mapAddPeerBPreservesB : forall (m : ByName.t t) (e f : B.t),\n    mapInB f m -> mapInB f (addPeerB e m).\n  Proof.\n    intros m e f H_m.\n    remember (ProtoIdentifier.name (B.supports f)) as f_name.\n    remember (ProtoIdentifier.name (B.supports e)) as e_name.\n\n    destruct (B.eq_dec e f) as [H_efEq|H_efNeq]. {\n      subst f.\n      apply mapInAddPeerB.\n    } {\n      destruct (String.string_dec e_name f_name) as [H_efnEq|H_efnNeq]. {\n        unfold mapInB in *.\n        unfold addPeerB.\n        rewrite <- Heqf_name in *.\n        rewrite <- Heqe_name in *.\n        rewrite <- H_efnEq in *.\n        destruct (ByName.find e_name m) as [sBefore|] eqn:H_find. {\n          rewrite <- ByNameFacts.find_mapsto_iff in H_find.\n          destruct H_m as [sx [H_sx0 H_sx1]].\n          pose proof (ByNameFacts.MapsTo_fun H_find H_sx0) as H_same.\n          subst sx.\n          exists (addPeerBT sBefore e).\n          constructor. {\n            rewrite ByNameFacts.add_mapsto_iff.\n            constructor. {\n              constructor; reflexivity.\n            }\n          } {\n            unfold addPeerBT.\n            apply BSets.add_2.\n            exact H_sx1.\n          }\n        } {\n          destruct H_m as [sx [H_sx0 H_sx1]].\n          pose proof (ByName.find_1 H_sx0) as H_contra.\n          rewrite H_find in H_contra.\n          inversion H_contra.\n        }\n      } {\n        unfold mapInB in *.\n        unfold addPeerB.\n        rewrite <- Heqf_name in *.\n        rewrite <- Heqe_name in *.\n        destruct H_m as [sx [H_sx0 H_sx1]].\n        exists sx.\n\n        constructor. {\n          destruct (ByName.find e_name m) as [sBefore|] eqn:H_find. {\n            apply ByName.add_2.\n            exact H_efnNeq.\n            exact H_sx0.\n          } {\n            apply ByName.add_2.\n            exact H_efnNeq.\n            exact H_sx0.\n          }\n        } {\n          exact H_sx1.\n        }\n      }\n    }\n  Qed.\n\n  Theorem mapWFAddPeerB : forall (m : ByName.t t) (e : B.t),\n    mapWF m -> mapWF (addPeerB e m).\n  Proof.\n    unfold mapWF.\n    unfold addPeerB.\n    intros m e H_wf.\n    remember (ProtoIdentifier.name (B.supports e)) as e_name.\n    intros s n H_mapsA.\n\n    destruct (ByName.find e_name m) as [ex|] eqn:H_find. {\n      rewrite <- ByNameFacts.find_mapsto_iff in H_find.\n      rewrite ByNameFacts.add_mapsto_iff in H_mapsA.\n      destruct H_mapsA as [[HL0 HL1]|[HR0 HR1]]. {\n        rewrite <- HL0 in *.\n        rewrite <- HL1.\n        pose proof (H_wf _ _ H_find) as H_prevWF.\n        symmetry in Heqe_name.\n        apply (setsWFAddPeerBT _ _ _ H_prevWF Heqe_name).\n      } {\n        apply (H_wf _ _ HR1).\n      }\n    } {\n      rewrite ByNameFacts.add_mapsto_iff in H_mapsA.\n      destruct H_mapsA as [[HL0 HL1]|[HR0 HR1]]. {\n        rewrite <- HL0 in *.\n        rewrite <- HL1.\n        rewrite Heqe_name.\n        apply (setsWFSingletonBT e).\n      } {\n        apply (H_wf _ _ HR1).\n      }\n    }\n  Qed.\n\n  Theorem mapAddPeerAPreservesB : forall (m : ByName.t t) (e : A.t) (f : B.t),\n    mapInB f m -> mapInB f (addPeerA e m).\n  Proof.\n    intros m e f H_in.\n    unfold addPeerA.\n    remember (ProtoIdentifier.name (A.supports e)) as e_name.\n    remember (ProtoIdentifier.name (B.supports f)) as f_name.\n\n    destruct (String.string_dec e_name f_name) as [H_nameEq|H_nameNeq]. {\n      destruct H_in as [s [H_inL H_inR]].\n      unfold mapInB.\n      subst f_name.\n      rewrite <- H_nameEq in *.\n      destruct (ByName.find e_name m) as [ex|] eqn:H_find. {\n        rewrite <- ByNameFacts.find_mapsto_iff in H_find.\n        assert (s = ex) as H_exs by (apply (ByNameFacts.MapsTo_fun H_inL H_find)).\n        subst ex.\n        exists (addPeerAT s e).\n        constructor. {\n          apply ByName.add_1; reflexivity.\n        } {\n          exact H_inR.\n        }\n      } {\n        rewrite ByNameFacts.find_mapsto_iff in H_inL.\n        rewrite H_inL in H_find.\n        inversion H_find.\n      }\n    } {\n      destruct H_in as [s [H_inL H_inR]].\n      exists s.\n      destruct (ByName.find e_name m) as [ex|] eqn:H_find. {\n        constructor. {\n          apply ByName.add_2.\n          rewrite <- Heqf_name.\n          auto.\n          auto.\n        } {\n          exact H_inR.\n        }\n      } {\n        constructor. {\n          apply ByName.add_2.\n          rewrite <- Heqf_name.\n          auto.\n          auto.\n        } {\n          exact H_inR.\n        }\n      }\n    }\n  Qed.\n\n  Theorem mapAddPeerBPreservesA : forall (m : ByName.t t) (e : B.t) (f : A.t),\n    mapInA f m -> mapInA f (addPeerB e m).\n  Proof.\n    intros m e f H_in.\n    unfold addPeerB.\n    remember (ProtoIdentifier.name (B.supports e)) as e_name.\n    remember (ProtoIdentifier.name (A.supports f)) as f_name.\n\n    destruct (String.string_dec e_name f_name) as [H_nameEq|H_nameNeq]. {\n      destruct H_in as [s [H_inL H_inR]].\n      unfold mapInA.\n      subst f_name.\n      rewrite <- H_nameEq in *.\n      destruct (ByName.find e_name m) as [ex|] eqn:H_find. {\n        rewrite <- ByNameFacts.find_mapsto_iff in H_find.\n        assert (s = ex) as H_exs by (apply (ByNameFacts.MapsTo_fun H_inL H_find)).\n        subst ex.\n        exists (addPeerBT s e).\n        constructor. {\n          apply ByName.add_1; reflexivity.\n        } {\n          exact H_inR.\n        }\n      } {\n        rewrite ByNameFacts.find_mapsto_iff in H_inL.\n        rewrite H_inL in H_find.\n        inversion H_find.\n      }\n    } {\n      destruct H_in as [s [H_inL H_inR]].\n      exists s.\n      destruct (ByName.find e_name m) as [ex|] eqn:H_find. {\n        constructor. {\n          apply ByName.add_2.\n          rewrite <- Heqf_name.\n          auto.\n          auto.\n        } {\n          exact H_inR.\n        }\n      } {\n        constructor. {\n          apply ByName.add_2.\n          rewrite <- Heqf_name.\n          auto.\n          auto.\n        } {\n          exact H_inR.\n        }\n      }\n    }\n  Qed.\n\n  Definition addPeersA\n    (es : list A.t)\n    (m  : ByName.t t)\n  : ByName.t t :=\n    List.fold_right addPeerA m es.\n\n  Theorem mapWFAddPeersA : forall (m : ByName.t t) (es : list A.t),\n    mapWF m -> mapWF (addPeersA es m).\n  Proof.\n    intros m es.\n    induction es as [|x xs]. {\n      auto.\n    } {\n      intro H_m.\n      simpl.\n      apply mapWFAddPeerA.\n      apply IHxs.\n      exact H_m.\n    }\n  Qed.\n\n  Theorem mapInAddPeersA : forall (m : ByName.t t) (es : list A.t),\n    forall e, List.In e es -> mapInA e (addPeersA es m).\n  Proof.\n    intros m es.\n    induction es as [|x xs]. {\n      intros e H_nil.\n      inversion H_nil.\n    } {\n      intros e H_in.\n      simpl.\n      destruct H_in as [H_inL|H_inR]. {\n        subst x.\n        apply mapInAddPeerA.\n      } {\n        apply mapAddPeerAPreservesA.\n        apply (IHxs e H_inR).\n      }\n    }\n  Qed.\n\n  Definition addPeersB\n    (es : list B.t)\n    (m  : ByName.t t)\n  : ByName.t t :=\n    List.fold_right addPeerB m es.\n\n  Theorem mapWFAddPeersB : forall (m : ByName.t t) (es : list B.t),\n    mapWF m -> mapWF (addPeersB es m).\n  Proof.\n    intros m es.\n    induction es as [|x xs]. {\n      auto.\n    } {\n      intro H_m.\n      simpl.\n      apply mapWFAddPeerB.\n      apply IHxs.\n      exact H_m.\n    }\n  Qed.\n\n  Theorem mapInAddPeersB : forall (m : ByName.t t) (es : list B.t),\n    forall e, List.In e es -> mapInB e (addPeersB es m).\n  Proof.\n    intros m es.\n    induction es as [|x xs]. {\n      intros e H_nil.\n      inversion H_nil.\n    } {\n      intros e H_in.\n      simpl.\n      destruct H_in as [H_inL|H_inR]. {\n        subst x.\n        apply mapInAddPeerB.\n      } {\n        apply mapAddPeerBPreservesB.\n        apply (IHxs e H_inR).\n      }\n    }\n  Qed.\n\n  Theorem mapAddPeersAPreservesB : forall (m : ByName.t t) (es : list A.t) f,\n    mapInB f m -> mapInB f (addPeersA es m).\n  Proof.\n    intros m es.\n    induction es as [|x xs]. {\n      intros f H_mIn.\n      exact H_mIn.\n    } {\n      intros f H_mIn.\n      simpl.\n      apply mapAddPeerAPreservesB.\n      apply IHxs.\n      exact H_mIn.\n    }\n  Qed.\n\n  Theorem mapAddPeersBPreservesA : forall (m : ByName.t t) (es : list B.t) f,\n    mapInA f m -> mapInA f (addPeersB es m).\n  Proof.\n    intros m es.\n    induction es as [|x xs]. {\n      intros f H_mIn.\n      exact H_mIn.\n    } {\n      intros f H_mIn.\n      simpl.\n      apply mapAddPeerBPreservesA.\n      apply IHxs.\n      exact H_mIn.\n    }\n  Qed.\n\n  Theorem mapAddPeersAPreservesA : forall (m : ByName.t t) (es : list A.t) e,\n    mapInA e m -> mapInA e (addPeersA es m).\n  Proof.\n    intros m es.\n    induction es as [|x xs]. {\n      intros f H_mIn.\n      exact H_mIn.\n    } {\n      intros f H_mIn.\n      simpl.\n      apply mapAddPeerAPreservesA.\n      apply IHxs.\n      exact H_mIn.\n    }\n  Qed.\n\n  Theorem mapAddPeersBPreservesB : forall (m : ByName.t t) (es : list B.t) e,\n    mapInB e m -> mapInB e (addPeersB es m).\n  Proof.\n    intros m es.\n    induction es as [|x xs]. {\n      intros f H_mIn.\n      exact H_mIn.\n    } {\n      intros f H_mIn.\n      simpl.\n      apply mapAddPeerBPreservesB.\n      apply IHxs.\n      exact H_mIn.\n    }\n  Qed.\n\n  Definition addPeersSA\n    (es : ASets.t)\n    (m  : ByName.t t)\n  : ByName.t t :=\n    addPeersA (ASets.elements es) m.\n\n  Theorem mapWFAddPeersSA : forall (m : ByName.t t) (es : ASets.t),\n    mapWF m -> mapWF (addPeersSA es m).\n  Proof.\n    unfold addPeersSA.\n    intros m es H_m.\n    apply (mapWFAddPeersA _ _ H_m).\n  Qed.\n\n  Theorem mapInAddPeersSA : forall (m : ByName.t t) (es : ASets.t),\n    forall e, ASets.In e es -> mapInA e (addPeersSA es m).\n  Proof.\n    intros m es e H_in.\n    pose proof (ASets.elements_1 H_in) as H_sL.\n    apply mapInAddPeersA.\n    apply ListExts.InA_In.\n    exact H_sL.\n  Qed.\n\n  Definition addPeersSB\n    (es : BSets.t)\n    (m  : ByName.t t)\n  : ByName.t t :=\n    addPeersB (BSets.elements es) m.\n\n  Theorem mapWFAddPeersSB : forall (m : ByName.t t) (es : BSets.t),\n    mapWF m -> mapWF (addPeersSB es m).\n  Proof.\n    unfold addPeersSB.\n    intros m es H_m.\n    apply (mapWFAddPeersB _ _ H_m).\n  Qed.\n\n  Theorem mapInAddPeersSB : forall (m : ByName.t t) (es : BSets.t),\n    forall e, BSets.In e es -> mapInB e (addPeersSB es m).\n  Proof.\n    intros m es e H_in.\n    pose proof (BSets.elements_1 H_in) as H_sL.\n    apply mapInAddPeersB.\n    apply ListExts.InA_In.\n    exact H_sL.\n  Qed.\n\n  Theorem mapInAddPeersSAPreservesB : forall (m : ByName.t t) es f,\n    mapInB f m -> mapInB f (addPeersSA es m).\n  Proof.\n    intros m es f H_minB.\n    unfold addPeersSA.\n    apply mapAddPeersAPreservesB.\n    exact H_minB.\n  Qed.\n\n  Theorem mapInAddPeersSBPreservesA : forall (m : ByName.t t) es f,\n    mapInA f m -> mapInA f (addPeersSB es m).\n  Proof.\n    intros m es f H_minA.\n    unfold addPeersSB.\n    apply mapAddPeersBPreservesA.\n    exact H_minA.\n  Qed.\n\n  Lemma mapsToIn : forall (A : Type) (v : A) m k,\n    ByName.MapsTo k v m -> List.In (k, v) (ByName.elements m).\n  Proof.\n    intros A v m k H_maps.\n    rewrite ByNameFacts.elements_mapsto_iff in H_maps.\n    induction H_maps as [p ps [HK0 HK1]|p ps HR]. {\n      left.\n      assert (fst p = k) as H_eqK\n        by (rewrite HK0; reflexivity).\n      assert (snd p = v) as H_eqV\n        by (rewrite <- HK1; reflexivity).\n      rewrite <- H_eqK.\n      rewrite <- H_eqV.\n      destruct p; reflexivity.\n    } {\n      right.\n      exact IHHR.\n    }\n  Qed.\n\n  Theorem mapAddPeersSAPreservesA : forall (m : ByName.t t) oSet f,\n    mapInA f m -> mapInA f (addPeersSA oSet m).\n  Proof.\n    intros m oSet f H_minA.\n    unfold addPeersSA.\n    apply mapAddPeersAPreservesA.\n    exact H_minA.\n  Qed.\n\n  Theorem mapInAddPeersSBPreservesB : forall (m : ByName.t t) oSet f,\n    mapInB f m -> mapInB f (addPeersSB oSet m).\n  Proof.\n    intros m oSet f H_minB.\n    unfold addPeersSB.\n    apply mapAddPeersBPreservesB.\n    exact H_minB.\n  Qed.\n\n  Definition collectProtocols\n    (ma : ByName.t ASets.t)\n    (mb : ByName.t BSets.t)\n  : ByName.t t :=\n    let init := ByName.empty t                    in\n    let aes  := List.map snd (ByName.elements ma) in\n    let bes  := List.map snd (ByName.elements mb) in\n    let mwa  := List.fold_right addPeersSA init aes in\n      List.fold_right addPeersSB mwa bes.\n\n  Lemma collectProtocolsAL : forall (ma : ByName.t ASets.t) es,\n    mapWF (List.fold_right addPeersSA (ByName.empty t) es).\n  Proof.\n    intros ma.\n    induction es as [|y ys]. {\n      apply mapWFEmpty.\n    } {\n      simpl.\n      apply mapWFAddPeersSA.\n      auto.\n    }\n  Qed.\n\n  Lemma collectProtocolsBL : forall es m (ma : ByName.t BSets.t),\n    mapWF m -> mapWF (List.fold_right addPeersSB m es).\n  Proof.\n    intros es.\n    induction es as [|y ys]. {\n      intros m mb H_mwf.\n      exact H_mwf.\n    } {\n      intros m mb H_mwf.\n      simpl.\n      apply mapWFAddPeersSB.\n      auto.\n    }\n  Qed.\n\n  Theorem collectProtocolsWF : forall ma mb, mapWF (collectProtocols ma mb).\n  Proof.\n    intros ma mb.\n    unfold collectProtocols.\n    apply collectProtocolsBL; auto.\n    apply collectProtocolsAL; auto.\n  Qed.\n\n  Theorem collectProtocolsInAL : forall ma a m,\n    AC.mapIn a ma ->\n      mapInA a (List.fold_right addPeersSA m (List.map snd (ByName.elements ma))).\n  Proof.\n    intros ma a m H_min.\n    destruct H_min as [xSet [H_min0 H_min1]].\n    pose proof (mapsToIn _ _ _ _ H_min0) as H_in0.\n    pose proof (ListExts.InMapPair _ _ _ _ _ H_in0) as [H_in1 H_in2].\n    clear H_in0.\n    clear H_in1.\n\n    induction (List.map snd (ByName.elements ma)) as [|ySet rSets]. {\n      inversion H_in2.\n    } {\n      destruct H_in2 as [H_in0|H_in1]. {\n        subst.\n        apply mapInAddPeersSA.\n        exact H_min1.\n      } {\n        pose proof (IHrSets H_in1) as H_inRsets.\n        apply mapAddPeersSAPreservesA.\n        exact H_inRsets.\n      }\n    }\n  Qed.\n\n  Theorem collectProtocolsInBL : forall mb b m,\n    BC.mapIn b mb ->\n      mapInB b (List.fold_right addPeersSB m (List.map snd (ByName.elements mb))).\n  Proof.\n    intros mb b m H_min.\n    destruct H_min as [xSet [H_min0 H_min1]].\n    pose proof (mapsToIn _ _ _ _ H_min0) as H_in0.\n    pose proof (ListExts.InMapPair _ _ _ _ _ H_in0) as [H_in1 H_in2].\n    clear H_in0.\n    clear H_in1.\n\n    induction (List.map snd (ByName.elements mb)) as [|ySet rSets]. {\n      inversion H_in2.\n    } {\n      destruct H_in2 as [H_in0|H_in1]. {\n        subst.\n        apply mapInAddPeersSB.\n        exact H_min1.\n      } {\n        pose proof (IHrSets H_in1) as H_inRsets.\n        apply mapInAddPeersSBPreservesB.\n        exact H_inRsets.\n      }\n    }\n  Qed.\n\n  Theorem collectProtocolsInALPB : forall m a es,\n    mapInA a m -> mapInA a (List.fold_right addPeersSB m es).\n  Proof.\n    induction es as [|y ys]. {\n      intros H_in; exact H_in.\n    } {\n      intros H_in.\n      simpl.\n      apply mapInAddPeersSBPreservesA.\n      apply IHys.\n      exact H_in.\n    }\n  Qed.\n\n  Theorem collectProtocolsInA : forall ma mb (a : A.t),\n    AC.mapIn a ma -> mapInA a (collectProtocols ma mb).\n  Proof.\n    intros ma mb a H_inA.\n    destruct H_inA as [s [H_in0 H_in1]].\n    unfold collectProtocols.\n    apply collectProtocolsInALPB.\n    apply collectProtocolsInAL.\n    exists s; auto.\n  Qed.\n\n  Theorem collectProtocolsInB : forall ma mb (b : B.t),\n    BC.mapIn b mb -> mapInB b (collectProtocols ma mb).\n  Proof.\n    intros ma mb b H_inB.\n    destruct H_inB as [s [H_in0 H_in1]].\n    unfold collectProtocols.\n    apply collectProtocolsInBL.\n    exists s; auto.\n  Qed.\n\nEnd CollectionOfProtocols.\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/ProtoPeer/CollectionOfProtocols.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2573981195078216}}
{"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.  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 computation8.\n\nLemma hasvaluec_computes_to_valc_implies {o} :\n  forall lib (a : @CTerm o),\n    hasvaluec lib a -> {b : CTerm & computes_to_valc lib a b}.\nProof.\n  introv hv; destruct_cterms; unfold hasvaluec in hv; allsimpl.\n  unfold hasvalue in hv; exrepnd.\n  unfold computes_to_value in hv0; repnd.\n  applydup @isvalue_implies in hv0; repnd.\n  allrw @isprogram_eq.\n  exists (mk_ct t' hv2).\n  unfold computes_to_valc, computes_to_value; simpl; dands; 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/computation9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.25739811273162}}
{"text": "(*\nDefinition of the AM Monad + monadic helper functions.\n\nAuthor:  Adam Petz, ampetz@ku.edu\n*)\nRequire Import Maps GenStMonad Impl_vm StVM StAM.\nRequire Import Term ConcreteEvidence.\n\nRequire Import PeanoNat.\n\nRequire Import List.\nImport ListNotations.\n\nDefinition AM := St AM_St.\n\nDefinition am_newNonce (bs :BS) : AM EvidenceC :=\n  am_st <- get ;;\n  let mm := am_nonceMap am_st in\n  let i := am_nonceId am_st in\n  let appm := st_aspmap am_st in\n  let sigm := st_sigmap am_st in\n  let hshm := st_hshmap am_st in\n  let checkedm := checked am_st in\n  let tracem := am_st_trace am_st in           \n  let newMap := map_set mm i bs in\n  let newId := i + 1 in\n  put (mkAM_St newMap newId appm sigm hshm tracem checkedm) ;;         \n  ret (nnc i bs mtc).\n\nDefinition getNonceVal (nid:nat) : AM BS :=\n  m <- gets am_nonceMap ;;\n  let maybeVal := map_get m nid in\n  match maybeVal with\n  | Some bs => ret bs\n  | None => failm\n  end.\n\nDefinition add_checked (nid:nat) : AM unit :=\n  am_st <- get ;;\n  let mm := am_nonceMap am_st in\n  let i := am_nonceId am_st in\n  let appm := st_aspmap am_st in\n  let sigm := st_sigmap am_st in\n  let hshm := st_hshmap am_st in\n  let checkedm := checked am_st in\n  let tracem := am_st_trace am_st in\n  put (mkAM_St mm i appm sigm hshm tracem (checkedm ++ [nid])).\n\nDefinition am_checkNonce (nid:nat) (bs:BS) : AM BS :=\n  good_bs <- getNonceVal nid ;;\n  add_checked nid ;;\n  if (Nat.eq_dec bs good_bs) then ret 1 else ret 0.\n\nDefinition nonces_checked (nm:MapC nat BS) (l:list nat) : Prop :=\n  forall x, \n  (exists v, bound_to nm x v) ->\n  In x l.\n\nDefinition nonces_checked_st (st:AM_St) : Prop :=\n  match st with\n  | mkAM_St nm i am sm hm tr l =>\n    nonces_checked nm l\n  end.\n\nRequire Import StVM MonadVM.\n\n(** * Helper functions for Appraisal *)\n\nDefinition checkSig (x:nat) (i:ASP_ID) (e':EvidenceC) (sig:BS) : CVM BS :=\n  invokeUSM x i ([encodeEv e'] ++ [sig] (* ++ args*) ) 0 0 ;;\n  ret x.\n\nDefinition checkUSM (x:nat) (i:ASP_ID) (l:list Arg) (tpl:Plc) (tid:TARG_ID) (bs:BS) : CVM BS :=\n  invokeUSM x i ([bs] ++ l) tpl tid ;;\n  ret x.\n\nDefinition hashEvT (e:Evidence): BS.\nAdmitted.\n\nDefinition checkHSH (*(x:nat) (i:ASP_ID) (l:list Arg) (tpl:Plc) (tid:TARG_ID)*)\n           (e:Evidence) (bs:BS) : CVM BS :=\n  invokeUSM 0 1 ([hashEvT e] ++ [bs]) 42 43 ;;\n  ret 0.\n\nDefinition runAM {A:Type} (k:(AM A)) (st:AM_St) : (option A) * AM_St :=\n  runSt k st.\n\nDefinition incNonce := runAM (am_newNonce 42) empty_amst.\n\nDefinition am_run_t (t:Term) (e:EvidenceC) (et:Evidence) : AM EvidenceC :=\n  let annt := annotated t in\n  let start_st := (mk_st e et [] 0) in\n  ret (st_ev (run_cvm annt start_st)).\n\nDefinition am_run_t_anno (annt:AnnoTerm) (e:EvidenceC) (et:Evidence) : AM EvidenceC :=\n  let start_st := (mk_st e et [] 0) in\n  ret (st_ev (run_cvm annt start_st)).\n\n(** * Helper functions for Appraisal *)\n\nDefinition am_get_app_asp (p:Plc) (i:ASP_ID) : AM ASP_ID :=\n  m <- gets st_aspmap ;;\n  let maybeId := map_get m (p,i) in\n  match maybeId with\n  | Some i' => ret i'\n  | None => failm\n  end.\n\nDefinition am_get_sig_asp (p:Plc) : AM ASP_ID :=\n  m <- gets st_sigmap ;;\n  let maybeId := map_get m p in\n  match maybeId with\n  | Some i' => ret i'\n  | None => failm\n  end.\n\n\n\n\n\n(* ***  Extra  *** *)\n(*\nDefinition t1 := (att 1 (lseq (asp (ASPC 44 [])) (asp SIG))).\nDefinition t2 := (lseq (asp (ASPC 44 [])) (asp SIG)).\n*)\n\n(*\nCompute (am_run_t t2 mtc empty_amst).\n*)\n\n(*\nDefinition am_proto_1 :=\n  n2 <- am_newNonce 42 ;;\n    n <- am_newNonce 43 ;;\n    am_run_t t2 n.\n*)\n\n(*\nCompute (runAM am_proto_1 empty_amst).\n*)\n\n(*\nFixpoint nonces (e:EvidenceC) (l:list nat) : list nat :=\n  match e with\n  | nnc i _ e' => nonces e' ([i] ++ l)\n  | _ => l\n  end.\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/MonadAM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.25739811273162}}
{"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 RmiAux.Specs.init_common_sysregs.\nRequire Import RmiAux.LowSpecs.init_common_sysregs.\nRequire Import RmiAux.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       set_rec_common_sysregs_spec\n       get_rd_g_rtt_spec\n       granule_addr_spec\n    .\n\n  Lemma init_common_sysregs_spec_exists:\n    forall habd habd'  labd rec rd\n           (Hspec: init_common_sysregs_spec rec rd habd = Some habd')\n            (Hrel: relate_RData habd labd),\n    exists labd', init_common_sysregs_spec0 rec rd labd = Some labd' /\\ relate_RData habd' labd'.\n  Proof.\n    Local Opaque ptr_eq.\n    intros. destruct Hrel. inv id_rdata. destruct rec, rd.\n    unfold init_common_sysregs_spec0, init_common_sysregs_spec in *.\n    repeat autounfold in *.\n    hsimpl_hyp Hspec; inv Hspec; simpl_query_oracle;\n      extract_prop_dec; repeat destruct_con; repeat destruct_dis; bool_rel; simpl in *;\n        repeat (simpl_htarget; grewrite; try solve_ptr_eq; try unfold ref_accessible in *; simpl in *).\n    rewrite ZMap.gso.\n    repeat (simpl_htarget; grewrite; simpl).\n    repeat (solve_bool_range; grewrite).\n    repeat simpl_field. repeat simpl_update_reg.\n    eexists; (split; [reflexivity| constructor; reflexivity]).\n    red; intro T; inv T; srewrite. inv C4.\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/RmiAux/RefProof/init_common_sysregs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.25739811273161994}}
{"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 Equality.\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.LanguageFoundations.\nRequire Import ComhCoq.SoftwareLanguage.\nRequire Import ComhCoq.InterfaceLanguage.\nRequire Import ComhCoq.ModeStateLanguage.\nRequire Import ComhCoq.NetworkLanguage.\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\nOpen Scope R_scope.\n\n(* If an entity has sent a message v t time units ago, and that time is less than the \nmessage latency, then said message is in the output queue of the interface component \nwith timestamp mL - t.*)\nTheorem sent_outgoing (n : Network) (v : list BaseType) (t : Time) (i : nat)\n  (p : reachableNet n) :\n  sent v t i n p -> forall q : t < msgLatency,\n  outgoing v (minusTime msgLatency t (Rlt_le t msgLatency q)) i n.\n  (**Proof: Induction on sent.*)\n  intros. induction H.\n  (*In the base case we have that h - ioProc<v>? -> h', where h is the interface of the entity\n  in question. By analysing this interface transition we get that <v, mL> is at the head of the\n  output list of I', and so is in this list*)\n  invertClear H2.\n  addHyp (outList_received_in l2 l2' v H5).\n  (*and so we have outgoing v mL i n, which is our goal exactly since t = 0.*)\n  econstructor. rewrite <- H6 in H0.\n  apply H0. replace (minusTime msgLatency zeroTime (Rlt_le zeroTime msgLatency q))\n  with msgLatency. apply H2. apply timeEqR. simpl. ring.\n  (*In the discrete case for induction we apply the I.H.*)\n  addHyp (IHsent q). clear IHsent.\n  (*Since t hasn't changed we get outgoing v (mL - t) i n. We then observe that since\n  t < mL, then 0 < mL - t*)\n  remember (minusTime msgLatency t (Rlt_le t msgLatency q)) as t'.\n  assert (0 < t'). rewrite Heqt'. simpl. apply RltMinusBothSides. assumption.\n  (*and so by (NetAuxBasics::outgoing_disc_pres) the outgoing relation is preserved\n  from the previous to the current state, giving outgoing v (mL - t) i n' as required.*)\n  addHyp (outgoing_disc_pres n n' a v t' i w H0 H1). assumption. \n  (*In the delay case for induction, we can immediately infer from  t + d < mL\n  that t < mL and so outgoing v (mL - t) i n.*)\n  simpl in q. assert (t < msgLatency). eapply Rplus_lt_weaken_lr. apply q. apply Rlt_le.\n  delPos. addHyp (IHsent H0). clear IHsent.\n  (*Then since n -d-> n', by (NetAuxBasics::outgoing_del) we get\n  outgoing v (mL - t - d) i n = outgoing v (mL - (t + d)) i n, which is our goal exactly.*)\n  remember (minusTime msgLatency t (Rlt_le t msgLatency H0)) as t'.\n  addHyp (outgoing_del n n' d v t' i w H1). invertClear H2.\n  replace (minusTime (nonneg (time msgLatency)) (nonneg (time (delToTime (t +dt+ d))))\n  (Rlt_le (nonneg (time (delToTime (t +dt+ d)))) (nonneg (time msgLatency)) q)) with\n  (minusTime t' d x). apply H3. clear H1 H3. generalize dependent x. rewrite Heqt'.\n  intros. apply timeEqR. simpl. ring. Qed.\n\n(*If an entity is nextSince m t, then <m, l0> was sent exactly t time units ago for some l0.*)\nTheorem fst_sent (n : Network) (m : Mode) (t : Time) (i : nat)\n  (p : reachableNet n) : nextSince m t i n p ->\n  exists l0, sent [baseMode m, basePosition l0] t i n p.\n(**Proof: By induction on nextSince.*)\n  intros. induction H.\n  (*In the base case, first off let's do some inversions*)\n  state_pred_net_destr H0. state_pred_net_destr H1.\n  (*Apply a linking tactic*)\n  link_netentdisc_tac b.\n  (*Eliminate the case of equal entities by inverting different state predicates.\n  This is a hack, a proper tactic state_pred_elim_ent would be better but would\n  take ages to write.*)\n  state_pred_elim H2 H5. state_pred_elim H9 H10. state_pred_elim H9 H10.\n  state_pred_elim H16 H12.\n  (*Now we're left with the case where there is a transition from one entity to the other.\n  Then we can add an entity-level tracking result. Tracking yields that the software component\n  of the entity i outputs on io of <m, l0> which is complemented by an input of same by the\n  interface of that entity.*)\n  (*\n  lets OOTE : ovReady_ovWait_track_ent H2 H5 H11. andflat OOT.\n  (*Show that the position hasn't changed.*)\n  ent_disc_pres_pos_tac. subst.  \n  (*We show that the network action must be a tau because the software\n  term has changed.*)\n  assert (p0 <> p1) as PNE. unfold not. intros. subst. state_pred_elim H7 H4.\n  state_pred_elim H10 H8. lets PTN : procNeq_tau_net H3 H6 w PNE. subst.\n  (*There is now enough information to prove the base case for sent, with t = 0. Hence we\n  use l1 as our existential witness and satisfy the goal.*)\n  exists l1. eapply sentBase; eassumption.\n  (*In the inductive cases, we simply apply the inductive hypothesis and\n  then the appropriate constructor of sent.*)\n  invertClearAs2 IHnextSince l0 IH. exists l0. constructor.\n  assumption.\n  invertClearAs2 IHnextSince l0 IH. exists l0. constructor.\n  assumption. Qed.*)\n  Admitted. (*R*)\n\n(* If an entity has sent a message v mL time units ago, then said message is in the output\nqueue of the interface component with timestamp 0 or it has been delivered 0 time units ago.*)\nTheorem sent_out_del (n : Network) (v : list BaseType) (i : nat)\n  (p : reachableNet n) : sent v msgLatency i n p ->\n  outgoing v zeroTime i n \\/\n  exists r l, delivered ([-v, l, r-]) zeroTime i n p.\n  (**Proof: By induction on sent.*)\n  introz U. remember msgLatency as mL. induction U.\n  (*The base case fails because it gives the contradiction mL = 0, while mL\n  is assumed positive.*)\n  false. eapply Rlt_not_le. apply msgLatency_positive. rewrite <- HeqmL.\n  apply Rle_refl.\n  (*For the discrete inductive case we get from the I.H. that either\n  outgoing v 0 i n or delivered v r 0 i n.*)\n  apply IHU in HeqmL. clear IHU. elim_intro HeqmL OZ EDZ.\n  (*In the first case we know outgoing v 0 i n. In which case we can apply\n  (Basics::outgoing_timeout_disc) to obtain our goal.*)  \n  (*First we just do a little bit of pocessing to explicitly get the entity\n  and hence its position.*)\n  lets OZX : OZ. inversion OZX.\n  lets OTD : outgoing_timeout_disc OZ. or_flat.\n  (*The left subcase immediatley gives the goal.*)\n  left. eassumption.\n  (*The right sub-case gives the RHS of the goal.*)\n  ex_flat. right. exists x. exists l. eassumption.\n  (*If the latter is true, then we can immediately show by constructor\n  that delivered v r 0 i n'.*)\n  right. ex_flat. exists x x0. constructor. assumption.\n  (*Moving on to the timed case, where we get that t + d = mL and so\n  t = mL - d < mL*)\n  assert (t < msgLatency). rewrite <- HeqmL. simpl. Rplus_lt_tac.\n  delPos.\n  (*From here, by (sent_outgoing) we have outgoing v (mL - t) i n*)\n  lets SO : sent_outgoing U H. left.\n  (*Now, by some algebra and substituting for t using our recently deduced\n  equality is the same as outgoing v d i n.*)\n  assert (outgoing v d i n) as OD. my_applys_eq SO. \n  apply timeEqR. simpl. rewrite <- HeqmL. simpl.\n  destruct d. destruct delay. simpl. ring.\n  (*Now we apply (Basics::outgoing_del)*)\n  lets OGD : outgoing_del w OD. invertClear OGD.\n  (*And we get a term equivalent to outgoing v 0 i n, as required.*)  \n  my_applys_eq H0. apply timeEqR. simpl. destruct d; destruct delay.\n  simpl. ring. Qed.\n\n(* If an entity has sent a message v t time units ago, and that time is greater than the\nmessage latency, then said message was delivered to some radius, and the delivery time\nis less than the time of sending by the amount message latency.*)\nTheorem sent_delivered (n : Network) (v : list BaseType) (t : Time) (i : nat)\n  (p : reachableNet n) : sent v t i n p -> forall q : msgLatency < t,\n  exists r l,\n  delivered ([-v, l, r-]) (minusTime t msgLatency (Rlt_le msgLatency t q)) i n p.\n  (**Proof: Induction on sent. Well the base case can be immediately discarded due to the\n  contradiction of t = 0 and mL < t, given that mL is positive.*)\n  intros. induction H. contradict q. apply Rle_not_lt. simpl. timeNonneg.\n  (*In the discrete inductive case, the time parameter does not change since the previous\n  state, and so by the inductive hypothesis we have delivered v r (t - mL) i n*)\n  addHyp (IHsent q). clear IHsent. decompose [ex] H0. clear H0. rename x0 into l.\n  rename x into r.\n  (*Then by the discrete constructor of delivered we have in this state\n  delivered v r (t - mL) i n'.*)\n  exists r. exists l. constructor. assumption.\n  (*For the timed case, there are two subcases.*)\n  addHyp (Rlt_or_le msgLatency t). invertClear H0.  \n  (*If mL < t, then by the inductive hypothesis and timed constructor of delivered we get\n  our goal.*)\n  addHyp (IHsent H1). clear IHsent. decompose [ex] H0. exists x. exists x0.\n  replace (minusTime (nonneg (time (delToTime (t +dt+ d))))\n  (nonneg (time msgLatency)) (Rlt_le (nonneg (time msgLatency))\n  (nonneg (time (delToTime (t +dt+ d)))) q)) with\n  (delToTime ((minusTime t msgLatency (Rlt_le msgLatency t H1)) +dt+ d)).\n  apply deliveredDel. assumption. apply timeEqR. simpl. ring.\n  (*Else, t <= mL. We split this again into t < mL and t = mL.*)\n  apply Rle_lt_or_eq_dec in H1. invertClear H1.\n  (*t < mL gives a contradiction. We achieve the contradiction by first applying\n  (sent_outgoing) to get outgoing v (mL - t) i n.*)\n  addHyp (sent_outgoing n v t i p H H0).\n  (*Then we apply (NetAuxBasics::outgoing_del) to get d <= mL - t*)\n  remember ((minusTime msgLatency t (Rlt_le t msgLatency H0))) as t'.\n  addHyp (outgoing_del n n' d v t' i w H1).\n  (*So t + d <= mL.*)\n  invertClear H2. assert (t +dt+ d <= msgLatency). simpl. clear H3. rename x into Q.\n  rewrite Heqt' in Q. simpl in Q.\n  rewrite Rplus_comm. apply Rminus_le_swap_rr. assumption.\n  (*But from our hypothesis we have mL < t + d, so we arrive at a contradiction.*)\n  contradict q. apply Rle_not_lt. assumption.\n  (*Thus we conclude t = mL and we can apply sent_out_del to our previous case, yielding\n  outgoing v 0 i n \\/ exists r, delivered v r 0 i n.*)\n  apply timeEqR in H0. rewrite H0 in H. addHyp (sent_out_del n v i p H).\n  invertClear H1.\n  (*The LHS fails, again by contradiction via a corollary of (NetAuxBasics::outgoing_del)\n  saying that t = 0 implies no delay is possible.*)\n  addHyp (outgoing_del_contra n n' d v i w H2). inversion H1.\n  (*So we conclude that delivered v r 0 i n for some r*)\n  decompose [ex] H2. rename x0 into l. rename x into r. exists r.\n  exists l.\n  (*and then by the delay constructor of delivered we have our goal\n  delivered v r (0 + d) i n'.*)\n  replace (minusTime (nonneg (time (delToTime (t +dt+ d))))\n  (nonneg (time msgLatency)) (Rlt_le (nonneg (time msgLatency))\n  (nonneg (time (delToTime (t +dt+ d)))) q)) with\n  (delToTime (zeroTime +dt+ d)).\n  apply deliveredDel. assumption. apply timeEqR. simpl. rewrite H0. ring.\n  (*Note that there are no constraints on the radius here. This agrees with the rules for\n  message delivery as per the operational semantics of the network calculus, in which an\n  arbitrary radius may be chosen for message delivery in order to model arbitrary variations\n  in coverage.*)\n  Qed.\n\n(* If a message <m, l0> was sent t time units ago by some entity, then the distance\nbetween l0 and the position of that entity is at most Smax*t.*)\nTheorem sent_pos_bound (n : Network) (m : Mode) (t : Time) (i : nat)\n  (l l0 : Position) (p : reachableNet n) :\n  sent [baseMode m, basePosition l0] t i n p -> inPosNet l i n ->\n  dist2d l l0 <= speedMax*t.\n  (**Proof: By induction on the proof of sent.*)\n  intros. generalize dependent l. induction H; intros.\n  rename H3 into QQ. rename H2 into H3. rename H1 into H2. rename H0 into H1.\n  rename QQ into H0. swapRename l l1.\n  (*The base case would give us that the network n is reachable. From this we could\n  deduce from an important general result (...reachableProt_triple...) that the software\n  component of the entity i is P1 | P2 | P3.*)\n  addHyp (reachable_net_prot n i q l1 h k p H). apply reachableProt_triple in H4.\n  simpl in H4. invertClear H4. symmetry in H8.\n  (*We could then show via another general result [salvaged?] that one of the sub-components\n  must have been responsible for the output of v on the outProc channel.*)\n  rewrite H8 in H2.\n  assert (inPosNet l i n) as Q. erewrite inPos_pres_disc. apply H0. apply w.\n  link_partripdiscex_tac2 p1' p2' p3'. link_partripout_tac Y.\n  (*Using (...listener_outProc_out_not ...) we eliminate the listener case.*)\n  Focus 3. lets LO : listener_outProc_out_not H7 Y. false.\n  (*Now, for the broadcast case, we can infer further information with (bc_outProc_out)*)\n  lets BO : bc_outProc_out Y H5.\n  (*We then show by (bcReady_pos) that the position output is equal to the position of the sender.*)\n  remember ([|q, l1, h, k|]) as e. assert (reachableEnt e). eapply reachable_net_ent.\n  apply p. apply H. assert (bcReadyStateEnt m l0 e). rewrite Heqe. constructor.\n  rewrite H8. constructor. apply BO. lets BP : bcReady_pos H4 H9.\n  (*Then the goal is reduced to: |l - l| <= Smax*0 == 0 <= 0... which is trivial.*)\n  eapply inPos_ent_net in BP. assert (l0 = l). eapply inPos_unique. apply BP.\n  apply Q. rewrite H10. rewrite dist2D_refl. simpl. rewrite Rmult_0_r. apply Rle_refl.\n  assumption.\n  (*We use an analogous argument for the overlap case using (ovlp_outProc_out)*)\n  lets OO : ovlp_outProc_out Y H6. decompEx2 OO u r OO'.\n  remember ([|q, l1, h, k|]) as e. assert (reachableEnt e). eapply reachable_net_ent.\n  apply p. apply H. assert (ovReadyStateEnt m u l0 e).\n  rewrite Heqe. constructor. rewrite H8. constructor. apply OO'.\n  lets OP : ovReady_pos H4 H9. eapply inPos_ent_net in OP.\n  assert (l0 = l). eapply inPos_unique. apply OP. apply Q. rewrite H10.\n  rewrite dist2D_refl. simpl. rewrite Rmult_0_r. apply Rle_refl. assumption.\n  (*The inductive cases follow immediately from the definition of sent and the semantics.*)\n  (*Either a discrete action happens, in which case both t and the position of entity i don't change,\n  and so the goal carries over directly from the previous case.*)\n  assert (inPosNet l i n) as Q. erewrite inPos_pres_disc. apply H0. apply w.\n  apply IHsent. assumption.\n  (*Alternatively, a delay happens, in which case the new position l' of entity i differs from its\n  old position by at most Smax*d [salvage].*)\n  addHyp (inPos_del_bound_bkwd n n' d l i H0 w). invertClear H1. rename x into l1.\n  invertClear H2. apply IHsent in H1. clear IHsent. rewrite distSymmetric in H3.\n  (*And so by the (triangle inequality) the difference between l' and the sent position l0\n  is at most Smax*t + Smax*d = Smax*(t + d), which is exactly the goal because the time\n  parameter of sent for the current state is (t + d).*)\n  addHyp (dist_tri_ineq l l1 l0). eapply Rle_trans. apply H2. simpl. rewrite Rmult_plus_distr_l.\n  rewrite Rplus_comm. simpl in H1, H3. apply Rplus_le_compat; assumption. Qed.\n\n(* If an entity is nextSince m for t time units and t is greater than the message latency,\nthen for some l0 it has delivered a message <m, l0> to some r at t - mL time units ago,\nand the l0 in the message differs from the current position by at most Smax*t.*)\nTheorem fst_delivered (n : Network) (m : Mode) (t : Time) (i : nat)\n  (l : Position) (p : reachableNet n) :\n  nextSince m t i n p -> inPosNet l i n -> forall q : msgLatency < t,\n  exists l0 l1 r,\n  delivered ([-[baseMode m, basePosition l0], l1, r-])\n  (minusTime t msgLatency (Rlt_le msgLatency t q)) i n p /\\\n  dist2d l l0 <= speedMax*t.\n  (*Proof: We call on (fst_sent) to achieve sent <m, l0> r t i n p.*)\n  introz U. lets FS : fst_sent U. invertClearAs2 FS l0 SEN.\n  (*Now we use (sent_pos_bound) to get that |l - l0| <= Smax*t.*)\n  lets SPB : sent_pos_bound SEN U0.\n  (*Now we use sent_delivered to show that the sent message was delivered.*)\n  lets SD : sent_delivered SEN U1. ex_flat.\n  (*Now we fill in the existentials.*)\n  exists l0 x0 x.\n  (*The rest follows from assumptions.*)\n  split; assumption. Qed.\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/NARMsgPosition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.25739811273161994}}
{"text": "(* These auxiliary definitions and lemmas are used in the semantics of\nthe abstract and quasi-abstract machines. *)\n\nRequire Import List.\nRequire Import Utils.\n\nRequire Import Lattices.\nRequire Import Instr Memory.\n\nSet Implicit Arguments.\n\nLocal Open Scope Z_scope.\n\nInductive StkElmt {T S} := \n| AData : Atom T S -> StkElmt\n| ARet : PcAtom T -> bool -> StkElmt.\nArguments StkElmt T S :clear implicits. \n(* CH: not sure which variant is better, but in the Haskell version\n       the bool in ARet is labeled by the same label as the int *)\n\nRecord AS {T S}  := AState {\n  amem : memory T S;\n  aimem : list Instr;\n  astk : list (StkElmt T S);\n  apc : PcAtom T  \n}.\nArguments AS T S :clear implicits.\n\n\n(* DD -> DP: is PcAtom supposed to restrict the kind of output values?\n             at some point, I guess the code is going to be put in memory too, at\n             which point PcAtom will be also a pointer. Change it to ZAtom?\n*)\nInductive Event {T: Type} :=\n| EInt : PcAtom T -> @Event T.\nArguments Event T :clear implicits.\n\nHint Resolve flows_refl flows_join_right  flows_join_left : core.\n\n(* Same for both the abstract and quasi-abstract machines *)\nDefinition abstract_init_data T :=\n  (list Instr * list (PcAtom T) * T)%type.\n\nSection ARuleMachine.\n\nContext {T: Type}\n        {Latt: JoinSemiLattice T}\n        {S: Type}.\n\nInductive pop_to_return : list (StkElmt T S) -> list (StkElmt T S) -> Prop :=\n| sptr_done: forall a b s,\n    pop_to_return ((ARet a b)::s) ((ARet a b)::s)\n| sptr_pop: forall a s s',\n    pop_to_return s s' ->\n    pop_to_return ((AData a)::s) s'.\n\nLemma pop_to_return_ret : forall s1 s2,\n  pop_to_return s1 s2 ->\n  exists a b s, s2 = (ARet a b)::s.\nProof.\n  induction 1; intros; simpl; eauto.\nQed.\n\nLemma pop_to_return_spec : forall s1 s2,\n  pop_to_return s1 s2 ->\n  exists dstk, exists stk a b,\n    s1 = dstk++(ARet a b)::stk\n    /\\ (forall e, In e dstk -> exists a, e = AData a).\nProof.\n  induction 1; intros; simpl in *.\n  exists nil ; exists s ; exists a ; exists b.\n  simpl ; split ; eauto.\n  intuition.\n\n  destruct IHpop_to_return as [dstk [stk [a0 [b0 [Hs Hdstk]]]]].\n  subst.\n  exists ((AData a)::dstk).\n  exists stk ; eauto.\n  exists a0 ; exists b0 ; split ; eauto.\n  intros. inv H0.\n  eauto.\n  eapply Hdstk; auto.\n Qed.\n\nLemma pop_to_return_spec2: forall  s1 s2 b1 b2 a1 a2 dstk,\n pop_to_return (dstk ++ ARet a1 b1 :: s2)\n               (ARet a2 b2 :: s1) ->\n (forall e : StkElmt T S, In e dstk -> exists a : Atom T S, e = AData a) ->\n @ARet T S a1 b1 =  @ARet T S a2 b2.\nProof.\n  induction dstk; intros.\n  inv H. auto.\n  simpl in *.\n  inv H. destruct (H0 (ARet a2 b2)). intuition. inv H.\n  eapply IHdstk; eauto.\nQed.\n\nLemma pop_to_return_spec3: forall s1 s2 b1 b2 a1 a2 dstk,\n pop_to_return (dstk ++ ARet a1 b1 :: s2)\n               (ARet a2 b2 :: s1) ->\n (forall e, In e dstk -> exists a : Atom T S, e = AData a) ->\n s1 = s2 .\nProof.\n  induction dstk; intros.\n  inv H. auto.\n  simpl in *.\n  inv H. destruct (H0 (ARet a2 b2)). intuition. inv H.\n  eapply IHdstk; eauto.\nQed.\n\nEnd ARuleMachine.\n\nRecord ASysCall T : Type := {\n  asi_arity : nat;\n  asi_sem : forall S, list (Atom T S) -> option (Atom T S)\n}.\n\nDefinition ASysTable T : Type := ident -> option (ASysCall T).\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/AbstractCommon.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.2573072338537998}}
{"text": "Require Import LanguageUtil.\nRequire Import BasicProperties.\nRequire Import Properties.\nRequire Import Transitivity.\nRequire Import Extraction.\nRequire Import KindProperties.\nRequire Import BoxReasoning.\nRequire Import OccurenceReasoning.\n\nRequire Import Program.Tactics.\n\nDefinition Progressive (e : expr) : Prop := value e \\/ exists e', e ⟶ e'.\nDefinition EProgressive (e : eexpr) := evalue e \\/ exists e', e ⋆⟶ e'.\n\nHint Unfold Progressive : core.\nHint Unfold EProgressive : core.\n\nHint Rewrite extract_open_distr : reassoc.\n\nLtac find_impossible_reduction :=\n  simpl in *;\n  match goal with\n  | _ : ee_app _ _ ⋆⟶ _ |- _ => fail\n  | _ : e_app  _ _ ⟶  _ |- _ => fail\n  | _ : e_app _ _ ⟹ _ |- _ => fail\n  | H : _ ⋆⟶ _ |- _ => solve [inversion H]\n  | H : _ ⟶  _ |- _ => solve [inversion H]\n  | H : _ ⟹ _ |- _ => solve [inversion H]\n  end\n.\n\nLtac solve_impossible_reduction := try find_impossible_reduction.\n\nLemma deterministic_reduction : forall e e1 e2,\n    e ⟹ e1 -> e ⟹ e2 -> e1 = e2.\nProof.\n  intros. generalize dependent e2.\n  induction H; intros.\n  - inversion H1; subst; solve_impossible_reduction.\n    rewrite (IHdreduce e6); auto.\n  - inversion H2; subst; solve_impossible_reduction.\n    auto.\n  - inversion H1; subst; auto.\nQed.\n\nLtac conclude_refls H :=\n  match type of H with\n  | ?G ⊢ ?e1 <: ?e2 : ?A =>\n    let H1 := fresh \"H\" in\n    let H2 := fresh \"H\" in\n    assert (H1 : G ⊢ e1 : A) by eauto;\n    assert (H2 : G ⊢ e2 : A) by eauto;\n    conclude_type_refl H\n  end\n.\n\nLemma castdn_not_of_star : forall Γ e,\n    Γ ⊢ e_castdn e : * -> False.\nProof.\n  intros.\n  dependent induction H.\n  - assert (e_kind k = BOX) by (eapply star_type_inversion; eauto).\n    inversion H2; subst.\n    conclude_type_refl H1.\n    + inversion H0.\n    + eauto using expr_of_box_never_be_reduced'.\n  - apply star_sub_inversion_l in H0. subst.\n    eapply IHusub1; eauto.\nQed.\n\nLemma castup_not_of_star : forall Γ A e,\n    Γ ⊢ e_castup A e : * -> False.\nProof.\n  intros.\n  dependent induction H.\n  - inversion H0.\n  - apply star_sub_inversion_l in H0. subst.\n    eapply IHusub1; eauto.\nQed.\n\nLemma abs_le : forall Γ A b e T,\n    Γ ⊢ e_abs A b <: e : T ->\n    exists c, e = e_abs A c.\nProof.\n  intros.\n  dependent induction H.\n  - eauto.\n  - now apply abs_not_of_star in H0.\n  - now eapply IHusub1.\nQed.\n\nLemma abs_ge : forall Γ A b e T,\n    Γ ⊢ e <: e_abs A b : T ->\n    exists c, e = e_abs A c.\nProof.\n  intros.\n  dependent induction H.\n  - eauto.\n  - apply reflexivity_r in H2.\n    now apply abs_not_of_star in H2.\n  - now eapply IHusub1.\nQed.\n\nLemma bind_le : forall Γ A b e T,\n    Γ ⊢ e_bind A b <: e : T ->\n    exists c, e = e_bind A c.\nProof.\n  intros.\n  dependent induction H.\n  - eauto.\n  - now apply bind_not_of_star in H0.\n  - now eapply IHusub1.\nQed.\n\nLemma bind_ge : forall Γ A b e T,\n    Γ ⊢ e <: e_bind A b : T ->\n    exists c, e = e_bind A c.\nProof.\n  intros. dependent induction H.\n  - eauto.\n  - apply reflexivity_r in H2. now apply bind_not_of_star in H2.\n  - now eapply IHusub1.\nQed.\n\nLemma castup_le : forall Γ A b e T,\n    Γ ⊢ e_castup A b <: e : T ->\n    exists c, e = e_castup A c.\nProof.\n  intros. dependent induction H.\n  - eauto.\n  - now apply castup_not_of_star in H0.\n  - now eapply IHusub1.\nQed.\n\nLemma castup_ge : forall Γ A b e T,\n    Γ ⊢ e <: e_castup A b : T ->\n    exists c, e = e_castup A c.\nProof.\n  intros. dependent induction H.\n  - eauto.\n  - apply reflexivity_r in H2. now apply castup_not_of_star in H2.\n  - now eapply IHusub1.\nQed.\n\nLemma castdn_le : forall Γ a e T,\n    Γ ⊢ e_castdn a <: e : T ->\n    exists b, e = e_castdn b.\nProof.\n  intros. dependent induction H.\n  - eauto.\n  - now apply castdn_not_of_star in H0.\n  - now eapply IHusub1.\nQed.\n\nLemma castdn_ge : forall Γ a e T,\n    Γ ⊢ e <: e_castdn a: T ->\n    exists b, e = e_castdn b.\nProof.\n  intros. dependent induction H.\n  - eauto.\n  - apply reflexivity_r in H2. now apply castdn_not_of_star in H2.\n  - now eapply IHusub1.\nQed.\n\n\nLtac invert_sub_hyp :=\n  let b := fresh \"b\" in\n  let E := fresh \"E\" in\n  let H' := fresh \"H\" in\n  match goal with\n  | _ : _ ⊢ e_abs    ?A _ <: e_abs    ?A _ : _ |- _ => idtac\n  | _ : _ ⊢ e_bind   ?A _ <: e_bind   ?A _ : _ |- _ => idtac\n  | _ : _ ⊢ e_castdn    _ <: e_castdn    _ : _ |- _ => idtac\n  | _ : _ ⊢ e_castup ?A _ <: e_castup ?A _ : _ |- _ => idtac\n  | H : _ ⊢ e_abs _ _ <: _ : _ |- _ =>\n    pose (H' := H); apply abs_le in H' as (b & E)\n  | H : _ ⊢ _ <: e_abs _ _ : _ |- _ =>\n    pose (H' := H); apply abs_ge in H' as (b & E)\n  | H : _ ⊢ e_bind _ _ <: _ : _ |- _ =>\n    pose (H' := H); apply bind_le in H' as (b & E)\n  | H : _ ⊢ _ <: e_bind _ _ : _ |- _ =>\n    pose (H' := H); apply bind_ge in H' as (b & E)\n  | H : _ ⊢ e_castup _ _ <: _ : _ |- _ =>\n    pose (H' := H); apply castup_le in H' as (b & E)\n  | H : _ ⊢ _ <: e_castup _ _ : _ |- _ =>\n    pose (H' := H); apply castup_ge in H' as (b & E)\n  | H : _ ⊢ e_castdn _ _ <: _ : _ |- _ =>\n    pose (H' := H); apply castdn_le in H' as (b & E)\n  | H : _ ⊢ _ <: e_castdn _ _ : _ |- _ =>\n    pose (H' := H); apply castdn_ge in H' as (b & E)\n  end; inversion E; subst; simpl in *\n.\n\nLemma abs_pi_principal : forall Γ A b1 b2 T,\n    Γ ⊢ e_abs A b1 <: e_abs A b2 : T ->\n    exists B k, Γ ⊢ e_abs A b1 <: e_abs A b2 : e_pi A B /\\ Γ ⊢ e_pi A B <: T : e_kind k.\nProof.\n  intros.\n  dependent induction H.\n  - assert (Sub : G ⊢ e_abs A b1 <: e_abs A b2 : e_pi A B) by eauto.\n    conclude_type_refl Sub. eauto.\n  - edestruct IHusub1 as (B' & k' & Sub & Subpi); eauto.\n    exists B', k'. split.\n    + assumption.\n    + eapply transitivity; eauto.\nQed.\n\n\nLemma pi_sub_inversion : forall Γ A B C D k,\n    Γ ⊢ e_pi A B <: e_pi C D : e_kind k ->\n    exists k' L,\n      Γ ⊢ C <: A : e_kind k' /\\\n      forall x, x `notin` L -> Γ, x : C ⊢ B ^` x <: D ^` x : e_kind k.\nProof.\n  intros.\n  dependent induction H.\n  - exists k1, L. auto.\n  - apply IHusub1; auto.\n    apply kind_sub_inversion_l in H0. destruct_pairs. congruence.\nQed.\n\nLemma abs_inversion : forall Γ A b1 b2 T,\n    Γ ⊢ e_abs A b1 <: e_abs A b2 : T ->\n    forall B k,\n    Γ ⊢ T <: e_pi A B : e_kind k ->\n    exists L, forall x, x `notin` L -> Γ, x : A ⊢ b1 ^` x <: b2 ^` x : B ^` x.\nProof.\n  intros * Sub.\n  dependent induction Sub; intros.\n  - apply pi_sub_inversion in H3 as (k' & L' & H').\n    exists (L `union` L'). intros.\n    destruct_pairs. instantiate_cofinites. eauto.\n  - apply IHSub1 with k; eauto using transitivity.\nQed.\n\nLemma abs_principal_inversion : forall Γ A b1 b2 B,\n    Γ ⊢ e_abs A b1 <: e_abs A b2 : e_pi A B ->\n    exists L, forall x, x `notin` L -> Γ, x : A ⊢ b1 ^` x <: b2 ^` x : B ^` x.\nProof.\n  intros.\n  conclude_type_refl H.\n  now apply abs_inversion with (e_pi A B) k.\nQed.\n\nLemma castup_inversion : forall Γ e1 e2 A B,\n    Γ ⊢ e_castup A e1 <: e_castup A e2 : B ->\n    exists C k, Γ ⊢ e1 <: e2 : C /\\ A ⟶ C /\\ Γ ⊢ A <: B : e_kind k.\nProof.\n  intros. dependent induction H.\n  - eauto.\n  - edestruct IHusub1 as (C & k1 & Sub1 & R & Sub2); eauto.\n    exists C, k1; eauto using transitivity.\nQed.\n\nLtac rewrite_open_with_subst_impl G :=\n  match G with\n  | context [?e ^^ ?v] =>\n    progress\n      match v with\n      | e_var_f _ => idtac\n      | _ => erewrite (open_subst_eq e); eauto 3\n      end\n  end\n.\n\nLtac rewrite_open_with_subst :=\n  repeat\n    match goal with\n    | |- ?g => rewrite_open_with_subst_impl g\n    end\n.\n\nLemma type_preservation' : forall Γ e1 e2 A,\n    Γ ⊢ e1 <: e2 : A -> forall k n e1' e2', head_kind A k n -> e1 ⟹ e1' -> e2 ⟹ e2' -> Γ ⊢ e1' <: e2' : A.\nProof.\n  intros * Sub.\n  induction Sub; intros k' n' e1' e2' K R1 R2;\n    try solve [inversion K | inversion R1 | inversion R2].\n  - inversion R1; inversion R2; subst.\n    + box_reasoning.\n      * destruct k'; box_reasoning.\n      * conclude_type_refl Sub2.\n        apply s_app with A; auto.\n        eapply IHSub2; eauto.\n    + invert_sub_hyp. solve_impossible_reduction.\n    + invert_sub_hyp. solve_impossible_reduction.\n    + invert_sub_hyp.\n      box_reasoning.\n      * destruct k'; box_reasoning.\n      * apply abs_pi_principal in Sub2 as (B' & k2 & Sub2 & Sub3).\n        apply pi_sub_inversion in Sub3 as (k3 & L2 & Sub3 & Sub4).\n        apply abs_principal_inversion in Sub2 as (L3 & Sub2).\n        pick fresh x for (L3 `union` L2 `union` fv_expr b `union` fv_expr e0 `union` fv_expr B).\n        instantiate_cofinites.\n        rewrite (open_subst_eq b x t), (open_subst_eq e0 x t), (open_subst_eq B x t); auto.\n        eauto 4 using substitution_cons, context_narrowing_cons.\n  - inversion R1; inversion R2; subst.\n    assert (G ⊢ e_mu t s : t) by eauto.\n    instantiate_cofinites. conclude_freshes. rewrite_open_with_subst.\n    pose (t' := t); assert (t' = t) as E by auto.\n    replace (e_mu t s) with (e_mu t' s) by auto.\n    replace t with ([(e_mu t s) / x] t). rewrite E.\n    eapply substitution_cons; eauto.\n    now apply fresh_subst_eq.\n\n  - assert (head_kind A k' n') by (eapply head_kind_sub_l; eauto).\n    eauto.\nQed.\n\nCorollary type_preservation : forall Γ e1 e2 e1' e2' k,\n    Γ ⊢ e1 <: e2 : e_kind k -> e1 ⟹ e1' -> e2 ⟹ e2' -> Γ ⊢ e1' <: e2' : e_kind k.\nProof.\n  intros.\n  eapply type_preservation'; eauto.\n  Unshelve. exact 0.\nQed.\n\nHint Extern 1 (lc_expr _) => instantiate_cofinites : inst.\n\nLtac cleanup_hyps := instantiate_trivial_equals; destruct_pairs; clear_dups.\nLtac solve_progress_value := auto || left; eauto with inst.\n\nLemma pi_ge_inversion : forall Γ e A B k,\n    Γ ⊢ e <: e_pi A B : k -> (exists A' B', e = e_pi A' B') \\/ (exists C' D', e = e_all C' D').\nProof.\n  intros.\n  dependent induction H.\n  - eauto.\n  - eauto.\n  - now apply IHusub1 with A B.\nQed.\n\nLemma normal_form_forall_pi : forall Γ e A,\n    Γ ⊢ e : A -> value e ->\n    forall C D, A = e_all C D \\/ A = e_pi C D ->\n    forall E F k, Γ ⊢ A <: e_pi E F : k ->\n    (exists A' b, e = e_abs A' b) \\/ (exists A' b, e = e_bind A' b).\nProof.\n  intros * H V.\n  dependent induction H.\n    all: try solve [inversion V]. (* solving cases where `e` is not value *)\n    all: intros C' D' [E | E]; inversion E; (* solving invalid cases *)\n      subst; intros; solve_impossible_reduction; eauto. (* solving trivial base cases *)\n  - assert (G ⊢ A <: e_pi E F : (e_kind k)).\n    now apply transitivity with (e_all C' D') k0.\n    apply pi_ge_inversion in H3. destruct H3; destruct_exists; subst.\n    eapply IHusub1; eauto.\n    eapply IHusub1; auto.\n    apply transitivity with (e_all C' D') k0; eauto.\n  - assert (G ⊢ A <: e_pi E F : (e_kind k)).\n    now apply transitivity with (e_pi C' D') k0.\n    apply pi_ge_inversion in H3. destruct H3; destruct_exists; subst.\n    eapply IHusub1; eauto.\n    eapply IHusub1; auto.\n    apply transitivity with (e_pi C' D') k0; eauto.\nQed.\n\nLemma normal_form_pi : forall Γ e A B,\n    Γ ⊢ e : e_pi A B -> value e ->\n    (exists A' b, e = e_abs A' b) \\/ (exists A' b, e = e_bind A' b).\nProof.\n  intros. conclude_type_refl H.\n  eapply normal_form_forall_pi; eauto.\nQed.\n\n\nLtac invert_to_normal_forms H :=\n  match type of H with\n  | _ ⊢ _ <: _ : e_pi ?A ?B => apply normal_form_pi in H; eauto; destruct H\n  end; destruct_exists; subst\n.\n\nLtac invert_operator_to_nf :=\n  match goal with\n  | H : _ ⊢ ?e : e_pi _ _ |- ?g =>\n    match g with\n    | context [e] => invert_to_normal_forms H\n    | _ => fail\n    end\n  end\n.\n\nLtac destruct_progressive_for_app :=\n  let destruct_with_new_name H := (\n      let V := fresh \"V\" in\n      let e' := fresh \"e'\" in\n      destruct H as [V | [e' H]])\n  in\n  match goal with\n  | H : Progressive ?e |- exists e', e_app ?e _ ⟶ e' =>\n    destruct_with_new_name H\n  | H : EProgressive ?e |- exists e', ee_app ?e _ ⋆⟶ e' =>\n    destruct_with_new_name H\n  end\n.\n\nDefinition is_castup (e : expr) : Prop :=\n  match e with\n  | e_castup _ _ => True\n  | _ => False\n  end\n.\n\nLemma is_castup_dec : forall e,\n    is_castup e \\/ not (is_castup e).\nProof.\n  destruct e; simpl; eauto.\nQed.\n\nLemma is_castup_eq : forall e,\n    is_castup e -> exists A b, e = e_castup A b.\nProof.\n  intros. destruct e; solve [inversion H | eauto].\nQed.\n\nDefinition is_bind (e : expr) : Prop :=\n  match e with\n  | e_bind _ _ => True\n  | _ => False\n  end\n.\n\nLemma is_bind_dec : forall e,\n    is_bind e \\/ not (is_bind e).\nProof.\n  destruct e; simpl; auto.\nQed.\n\nLemma is_bind_eq : forall e,\n    is_bind e -> exists A b, e = e_bind A b.\nProof.\n  intros. destruct e; solve [inversion H | eauto].\nQed.\n\nLemma num_type_inversion : forall Γ n A,\n    Γ ⊢ e_num n : A -> Γ ⊢ e_int <: A : *.\nProof.\n  intros.\n  dependent induction H; eauto 3 using transitivity.\nQed.\n\nLemma int_le_inversion : forall Γ A B,\n    Γ ⊢ e_int <: A : B -> A = e_int \\/ exists B c, A = e_all B c.\nProof.\n  intros. dependent induction H; eauto.\nQed.\n\nLemma pi_le_inversion : forall Γ A B C k,\n    Γ ⊢ e_pi A B <: C : k -> (exists D E, C = e_pi D E) \\/ (exists D E, C = e_all D E).\nProof.\n  intros.\n  dependent induction H; eauto.\nQed.\n\nLemma kind_le_inversion : forall Γ kl ek k,\n    Γ ⊢ e_kind kl <: ek : k -> ek = * /\\ kl = k_star /\\ k = BOX.\nProof.\n  intros.\n  dependent induction H.\n  - auto.\n  - edestruct IHusub2; eauto. destruct H4. discriminate.\n  - edestruct IHusub1 as (E1 & E2 & E3); auto; subst.\n    apply reflexivity_l in H0. now apply box_never_welltype in H0.\nQed.\n\nLemma pi_of_kind : forall Γ A B C D E,\n    Γ ⊢ e_pi A B <: e_pi C D : E -> exists k, E = e_kind k.\nProof.\n  intros.\n  dependent induction H; eauto.\n  - edestruct IHusub1; eauto. subst.\n    apply kind_le_inversion in H0.\n    destruct_conjs; subst; eauto.\nQed.\n\nLemma forall_of_star : forall Γ A B C D E,\n    Γ ⊢ e_all A B <: e_all C D : E -> E = *.\nProof.\n  intros.\n  dependent induction H; eauto.\n  - erewrite IHusub1 in H0; eauto.\n    apply kind_le_inversion in H0. now destruct_conjs.\nQed.\n\n\nLemma reducible_type : forall Γ e A B,\n    Γ ⊢ e : A -> A ⟶ B -> not (is_castup e) -> not (is_bind e) -> value e -> False.\nProof.\n  intros * Sub R H1 H2 V.\n  inversion V; subst.\n  - apply kind_sub_inversion_l in Sub.\n    destruct_conjs. subst. inversion R.\n  - apply num_type_inversion, int_le_inversion in Sub.\n    destruct Sub; destruct_conjs; subst; inversion R.\n  - apply int_of_star in Sub. subst. inversion R.\n  - apply abs_pi_principal in Sub as (C & k & _ & Sub).\n    apply pi_le_inversion in Sub as [|]; destruct_conjs; subst; inversion R.\n  - contradict H2. simpl. auto.\n  - apply pi_of_kind in Sub as (k & E); subst.\n    inversion R.\n  - apply forall_of_star in Sub. subst. inversion R.\n  - contradict H1. simpl. auto.\nQed.\n\nTheorem generalized_progress : forall e1 e2 A,\n    nil ⊢ e1 <: e2 : A -> Progressive e1 /\\ Progressive e2.\nProof.\n  intros.\n  dependent induction H; cleanup_hyps;\n    try solve [split; solve_progress_value].\n  (* var is not value *)\n  - inversion H0.\n  (* app *)\n  - conclude_refls H1. split; right;\n    destruct_progressive_for_app;\n    eauto 3; (* solves r_app cases *)\n    invert_operator_to_nf.\n    + inversion V; subst. exists (H5 ^^ t). eauto.\n    + inversion V. inversion H11. subst.\n        pick fresh x. instantiate_cofinites.\n        exists (e_app (H5 ^` x) t). eauto.\n    + inversion V; subst. exists (H6 ^^ t). eauto.\n    + inversion V; inversion H11. subst.\n        pick fresh x. instantiate_cofinites.\n        exists (e_app (H6 ^` x) t). eauto.\n  - split; right; eauto.\n  - split.\n    + destruct H2.\n      * destruct (is_castup_dec e1), (is_bind_dec e1).\n        -- apply is_castup_eq in H5; destruct_conjs; subst; eauto.\n        -- apply is_castup_eq in H5; destruct_conjs; subst; eauto.\n        -- apply is_bind_eq in H6; destruct_conjs; subst;\n           eauto. Unshelve. exact 0.\n        -- apply reflexivity_l in H1.\n           eapply reducible_type in H1; [easy | eauto..].\n      * destruct H2. eauto.\n    + destruct H3.\n      * destruct (is_castup_dec e2), (is_bind_dec e2).\n        -- apply is_castup_eq in H5; destruct_conjs; subst; eauto.\n        -- apply is_castup_eq in H5; destruct_conjs; subst; eauto.\n        -- apply is_bind_eq in H6; destruct_conjs; subst; eauto.\n           Unshelve. exact 0.\n        -- apply reflexivity_r in H1.\n           eapply reducible_type in H1; [easy | eauto..].\n      * destruct H3. eauto.\nQed.\n\nCorollary progress : forall e A,\n    nil ⊢ e : A -> Progressive e.\nProof.\n  intros. apply generalized_progress in H.\n  now destruct H.\nQed.\n\n\nLtac solve_progress_evalue := auto || left; solve_evalue.\n\nLemma extract_abs : forall A b,\n    ee_abs (extract b) = extract (e_abs A b).\nProof.\n  easy.\nQed.\n\n\nTheorem generalized_erased_progress : forall e1 e2 A,\n    nil ⊢ e1 <: e2 : A -> forall e1' e2', extract e1 = e1' -> extract e2 = e2' ->\n    EProgressive e1' /\\ EProgressive e2'.\nProof.\n  intros * H.\n  dependent induction H; simpl; intros e1' e2' E1 E2; subst; auto;\n    try solve [split; solve_progress_evalue].\n  (* var is not value *)\n  - inversion H0.\n  (* app *)\n  - instantiate_trivial_equals.\n    destruct IHusub2 with (extract e1) (extract e2); auto.\n    conclude_refls H1;\n    split; right; destruct_progressive_for_app; eauto; (* solve r_app cases *)\n      apply evalue_value in V; auto;\n        invert_operator_to_nf; simpl.\n    + exists ((extract H4) ⋆^^ (extract t)). constructor.\n      replace (ee_abs (extract H4)) with (extract (e_abs H2 H4)) by reflexivity.\n      all: eauto using lc_extract_lc.\n    + pick fresh x. exists (ee_app (extract H4 ⋆^` x) (extract t)).\n      eapply er_elim; eauto 3.\n      replace (ee_bind (extract H4)) with (extract (e_bind H2 H4)) by reflexivity.\n      eauto using lc_extract_lc.\n    + exists ((extract H5) ⋆^^ (extract t)). constructor.\n      replace (ee_abs (extract H5)) with (extract (e_abs H3 H5)) by reflexivity.\n      all: eauto using lc_extract_lc.\n    + pick fresh x. exists (ee_app (extract H5 ⋆^` x) (extract t)).\n      eapply er_elim; eauto 3.\n      replace (ee_bind (extract H5)) with (extract (e_bind H3 H5)) by reflexivity.\n      eauto using lc_extract_lc.\n  - split; right; exists ((extract s) ⋆^^ ee_mu (extract s));\n      econstructor; replace (ee_mu (extract s)) with (extract (e_mu t s)) by auto;\n      eauto using lc_extract_lc.\n  (* castdn *)\n  - instantiate_trivial_equals.\n    destruct IHusub2 with (extract e1) (extract e2); auto.\n    split.\n    + destruct H2.\n      * apply evalue_value in H2; auto.\n        destruct (is_castup_dec e1), (is_bind_dec e1).\n        -- apply is_castup_eq in H4 as (C & e1' & E). subst.\n           simpl. right. exists (extract e1'). eauto.\n        -- apply is_castup_eq in H4 as (C & e1' & E). subst.\n           simpl. right. exists (extract e1'). eauto.\n        -- apply is_bind_eq in H5 as (C & e1' & E). subst.\n           simpl. right. pick fresh x. exists (ee_castdn (extract e1' ⋆^` x)).\n           apply er_cast_inst with empty.\n           replace (ee_bind (extract e1')) with (extract (e_bind C e1')) by reflexivity.\n           eauto using lc_extract_lc. auto.\n        -- apply reflexivity_l in H1.\n           eapply reducible_type in H1; [easy | eauto..].\n      * destruct H2; eauto.\n    + destruct H3.\n      * apply evalue_value in H3; auto.\n        destruct (is_castup_dec e2), (is_bind_dec e2).\n        -- apply is_castup_eq in H4 as (C & e2' & E). subst.\n           simpl. right. exists (extract e2'). eauto.\n        -- apply is_castup_eq in H4 as (C & e2' & E). subst.\n           simpl. right. exists (extract e2'). eauto.\n        -- apply is_bind_eq in H5 as (C & e1' & E). subst.\n           simpl. right. pick fresh x. exists (ee_castdn (extract e1' ⋆^` x)).\n           apply er_cast_inst with empty.\n           replace (ee_bind (extract e1')) with (extract (e_bind C e1')) by reflexivity.\n           eauto using lc_extract_lc. auto.\n        -- apply reflexivity_r in H1.\n           eapply reducible_type in H1; [easy | eauto..].\n      * destruct H3; eauto.\n  (* forall_l *)\n  - split.\n    + solve_progress_evalue.\n    + instantiate_trivial_equals.\n      now destruct IHusub3 with (extract (B ^^ t)) (extract C).\n  (* forall_r *)\n  - split.\n    + instantiate_trivial_equals.\n      now destruct IHusub2 with (extract A) (extract A).\n    + solve_progress_evalue.\nQed.\n\nCorollary erased_progress : forall e A,\n    nil ⊢ e : A -> EProgressive (extract e).\nProof.\n  intros.\n  apply generalized_erased_progress\n    with (e1' := extract e) (e2' := extract e) in H.\n  destruct H. all: auto.\nQed.\n\nLemma bind_extraction_inversion : forall e ee,\n    ee_bind ee = extract e ->\n    exists A e', e = e_bind A e' /\\ ee = extract e'.\nProof.\n  induction e; simpl; intros; inversion H; eauto.\nQed.\n\nLemma abs_extraction_inversion : forall e ee,\n    ee_abs ee = extract e ->\n    exists A e', e = e_abs A e' /\\ ee = extract e'.\nProof.\n  induction e; simpl; intros; inversion H; eauto.\nQed.\n\nLemma castdn_extraction_inversion : forall e ee,\n    ee_castdn ee = extract e ->\n    exists e', e = e_castdn e' /\\ ee = extract e'.\nProof.\n  induction e; simpl; intros; inversion H; eauto.\nQed.\n\nLemma castup_extraction_inversion : forall e ee,\n    ee_castup ee = extract e ->\n    exists A e', e = e_castup A e' /\\ ee = extract e'.\nProof.\n  induction e; simpl; intros; inversion H; eauto.\nQed.\n\nLtac invert_extraction :=\n  let A := fresh \"A\" in\n  let e2 := fresh \"e\" in\n  let E1 := fresh \"E\" in\n  let E2 := fresh \"E\" in\n  match goal with\n  | H : ee_bind _ = extract _ |- _ =>\n    apply bind_extraction_inversion in H as (A & e2 & E1 & E2)\n  | H : ee_abs  _ = extract _ |- _ =>\n    apply abs_extraction_inversion in H as (A & e2 & E1 & E2)\n  | H : ee_castdn _ = extract _ |- _ =>\n    apply castdn_extraction_inversion in H as (A & e2 & E1 & E2)\n  | H : ee_castup _ = extract _ |- _ =>\n    apply castup_extraction_inversion in H as (A & e2 & E1 & E2)\n  end; subst; simpl in *\n.\n\nLtac invert_extractions := repeat invert_extraction.\n\n\nLemma bind_inversion : forall Γ A b1 b2 T,\n    Γ ⊢ e_bind A b1 <: e_bind A b2 : T ->\n    exists B L, Γ ⊢ e_bind A b1 <: e_bind A b2 : e_all A B\n         /\\ Γ ⊢ e_all A B <: T : *\n         /\\ (forall x, x `notin` L -> Γ , x : A ⊢ b1 ^` x <: b2 ^` x : B ^` x)\n         /\\ (forall x, x `notin` L -> x `notin` fv_eexpr (extract (b1 ^` x)))\n         /\\ (forall x, x `notin` L -> x `notin` fv_eexpr (extract (b2 ^` x))).\nProof.\n  intros. dependent induction H.\n  - exists B. exists L. repeat split; eauto 2.\n  - specialize (IHusub1 A b1 b2). instantiate_trivial_equals.\n    destruct IHusub1 as (B' & L & IH). destruct_pairs.\n    exists B', L. repeat split; eauto 3 using transitivity.\nQed.\n\nDefinition is_forall (e : expr) : Prop :=\n  match e with\n  | e_all _ _ => True\n  | _ => False\n  end\n.\n\nLemma forall_l_sub_inversion : forall Γ A B C,\n    Γ ⊢ e_all A B <: C : * ->\n    not (is_forall C) ->\n    exists e, mono_type e /\\ Γ ⊢ e : A /\\ Γ ⊢ B ^^ e <: C : *.\nProof.\n  intros * Sub.\n  dependent induction Sub; simpl; intros.\n  + eauto.\n  + contradiction.\n  + contradiction.\n  + eapply IHSub1; eauto.\n    apply kind_sub_inversion_l in Sub2. destruct_pairs. congruence.\nQed.\n\nLtac split_all := repeat split.\n\nLtac rewrite_extract_invariant G e :=\n  match G with\n  | context [e ⋆^^ _] =>\n    erewrite (notin_open_var_notin_open e); eauto\n  end\n.\n\nLtac find_extract_invariants :=\n  repeat\n    match goal with\n    | H : ?x `notin` fv_eexpr (extract _) |- _  => autorewrite with reassoc in H; simpl in H\n    | H : ?x `notin` fv_eexpr (?e ⋆^` ?x) |- ?G => rewrite_extract_invariant G e\n    | _ => progress autorewrite with reassoc\n    end\n.\n\nLemma is_forall_eq : forall e,\n    is_forall e -> exists A b, e = e_all A b.\nProof.\n  intros. destruct e; simpl in *; inversion H; eauto.\nQed.\n\nLemma expr_of_box_never_be_reduced : forall A B a Γ1 Γ2,\n    A ⟶ B -> Γ1 ⊢ a : A -> Γ2 ⊢ B : BOX -> False.\nProof.\n  intros.\n  conclude_type_refl H0.\n  - inversion H.\n  - eauto using expr_of_box_never_be_reduced'.\nQed.\n\nTactic Notation \"absurd\" \"by\" tactic(t) :=\n  assert False by t; contradiction.\n\nLemma deterministic_type_reduction' : forall e e',\n    e ⟶ e' -> forall Γ A n k, Γ ⊢ e : A -> head_kind A k n -> e ⟹ e'.\nProof.\n  intros * R.\n  induction R; intros * Sub K; eauto.\n  (* r_app *)\n  - dependent induction Sub.\n    + box_reasoning.\n      * destruct k; box_reasoning.\n      * eauto.\n    (* or `eauto using head_kind_sub_l` *)\n    + eapply IHSub1; eauto. eapply head_kind_sub_l; eauto.\n  (* r_inst *)\n  - dependent induction Sub.\n    + box_reasoning.\n      * destruct k; box_reasoning.\n      * apply bind_inversion in Sub2. destruct_conjs.\n        eapply head_kind_sub_l in H6. inversion H6. eauto.\n    + eapply IHSub1; eauto. eapply head_kind_sub_l; eauto.\n  (* r_castdn *)\n  - dependent induction Sub.\n    + destruct k; box_reasoning.\n      absurd by eauto 3 using expr_of_box_never_be_reduced.\n    + eapply IHSub1; eauto. eapply head_kind_sub_l; eauto.\n  (* r_cast_inst *)\n  - dependent induction Sub.\n    + destruct k; box_reasoning.\n      absurd by eauto 3 using expr_of_box_never_be_reduced.\n    + eapply IHSub1; eauto. eapply head_kind_sub_l; eauto.\n  (* r_cast_elim *)\n  - dependent induction Sub.\n    + destruct k; box_reasoning.\n      absurd by eauto 3 using expr_of_box_never_be_reduced.\n    + eapply IHSub1; eauto. eapply head_kind_sub_l; eauto.\nQed.\n\nLemma deterministic_type_reduction : forall Γ e e' k,\n    e ⟶ e' -> Γ ⊢ e : e_kind k -> e ⟹ e'.\nProof.\n  intros.\n  eapply deterministic_type_reduction'; eauto.\n  Unshelve. exact 0.\nQed.\n\nLemma deterministic_type_reduction_2 : forall Γ e A A',\n    A ⟶ A' -> Γ ⊢ e : A -> A ⟹ A'.\nProof.\n  intros.\n  conclude_type_refl H0.\n  - inversion H.\n  - eapply deterministic_type_reduction; eauto.\nQed.\n\nLemma deterministic_erased_reduction : forall e e1 e2,\n    extract e ⋆⟶ e1 -> extract e ⋆⟶ e2 ->\n    forall Γ A, Γ ⊢ e : A -> e1 = e2.\nProof.\n  induction e; simpl; intros E1 E2 R1 R2 Γ A Sub;\n    solve_impossible_reduction.\n  - inversion R1; inversion R2; subst;\n      invert_extractions; solve_impossible_reduction.\n    + dependent induction Sub.\n      * assert (ee2 = ee5) by (eapply IHe1; eauto 3). now subst.\n      * eauto 2.\n    + now inversion H.\n    + inversion H.\n    + inversion H5.\n    + inversion H. dependent induction Sub; eauto 2.\n      clear IHSub1 IHSub2.\n      apply bind_inversion in Sub2; destruct_conjs.\n      pick fresh x'. instantiate_cofinites. find_extract_invariants.\n  - inversion R1; inversion R2; subst. auto.\n  - inversion R1; inversion R2; subst;\n      invert_extractions; solve_impossible_reduction.\n    + dependent induction Sub.\n      * assert (ee2 = ee3) by (eapply IHe; eauto 3). now subst.\n      * eauto 2.\n    + inversion H. dependent induction Sub; eauto 2.\n      clear IHSub1 IHSub2.\n      apply bind_inversion in Sub2; destruct_conjs.\n      pick fresh x'. instantiate_cofinites. find_extract_invariants.\n    + inversion H3.\n    + inversion H.\n    + now inversion H.\nQed.\n\nTheorem preservation : forall e1 e2 A,\n    nil ⊢ e1 <: e2 : A ->\n    forall e1'' e2'', extract e1 ⋆⟶ e1'' -> extract e2 ⋆⟶ e2''  ->\n    exists e1' e2', extract e1' = e1''\n             /\\ extract e2' = e2''\n             /\\ e1 ⟶ e1'\n             /\\ e2 ⟶ e2'\n             /\\ nil ⊢ e1' <: e2' : A.\nProof.\n  intros * Sub.\n  dependent induction Sub; simpl; intros;\n    solve_impossible_reduction;\n    instantiate_trivial_equals.\n  - inversion H0; subst.\n    + inversion H1; subst.\n      (* main case for r_app *)\n      * destruct IHSub2 with ee2 ee0 as (e1' & e2' & IH); eauto.\n        destruct_conjs. subst.\n        exists (e_app e1' t), (e_app e2' t). repeat split; eauto 3.\n      * invert_extractions. invert_sub_hyp. solve_impossible_reduction.\n      * invert_extractions. invert_sub_hyp. solve_impossible_reduction.\n    + invert_extractions. invert_sub_hyp.\n      inversion H1; subst; solve_impossible_reduction.\n      (* main case for r_beta *)\n      exists (e ^^ t), (b ^^ t).\n      autorewrite with reassoc.\n      split_all; eauto.\n      pose (B' := Sub2). apply abs_pi_principal in B'. destruct_conjs.\n      apply pi_sub_inversion in H8 as (k' & L & Sub3).\n      apply abs_principal_inversion in H5 as (L' & Sub4).\n      pick fresh x for\n           (L `union` L' `union` fv_expr e `union` fv_expr b `union` fv_expr B).\n      instantiate_cofinites. destruct_pairs.\n      rewrite_open_with_subst.\n      eapply context_narrowing_cons in Sub4; eauto 4 using substitution_cons.\n    + invert_extractions. invert_sub_hyp.\n      inversion H1; subst; solve_impossible_reduction.\n      (* main case for r_inst *)\n      apply bind_inversion in Sub2 as (F & L1 & Hb). destruct_pairs.\n      apply forall_l_sub_inversion in H6 as (m & M & Subm & Sub_inst); auto.\n      exists (e_app (e ^^ m) t), (e_app (b ^^ m) t). split_all; simpl.\n      * pick fresh x'. instantiate_cofinites. find_extract_invariants.\n      * pick fresh x'. instantiate_cofinites. find_extract_invariants.\n      * eauto.\n      * eauto.\n      * eapply s_app; eauto. apply s_sub with (F ^^ m) k_star; auto.\n        pick fresh x' for\n             (L `union` L0 `union` L1 `union`\n                fv_expr e `union` fv_expr b `union` fv_expr F).\n        rewrite_open_with_subst.\n        eauto 3 using substitution_cons.\n  - inversion H2; inversion H3; subst.\n    (* r_mu *)\n    assert (nil ⊢ e_mu t s : t) by eauto.\n    exists (s ^^ (e_mu t s)), (s ^^ (e_mu t s)). split_all.\n    + now rewrite extract_open_distr.\n    + now rewrite extract_open_distr.\n    + eauto.\n    + eauto.\n    + pick fresh x for (L `union` fv_expr t `union` fv_expr s).\n      instantiate_cofinites.\n      conclude_freshes. rewrite_open_with_subst.\n      pose (t' := t). assert (t' = t) as E by auto.\n      replace (e_mu t s) with (e_mu t' s) by auto.\n      replace t with ([(e_mu t s) / x] t) by now apply fresh_subst_eq.\n      rewrite E.\n      eapply substitution_cons; eauto 3.\n  - inversion H0; subst.\n    + inversion H1; subst.\n      (* main case for r_castdn *)\n      * destruct IHSub2 with ee2 ee0 as (e1' & e2' & IH); eauto.\n        destruct_conjs. subst.\n        exists (e_castdn e1'), (e_castdn e2'). repeat split; eauto 3.\n      * invert_extractions. invert_sub_hyp. inversion H3.\n      * invert_extractions. invert_sub_hyp. inversion H3.\n    + invert_extractions. invert_sub_hyp. inversion H1; subst; solve_impossible_reduction.\n    (* main case for r_cast_inst *)\n      apply bind_inversion in Sub2 as (F & L1 & Hb). destruct_pairs.\n      apply forall_l_sub_inversion in H8 as (m & M & Subm & Sub_inst); auto.\n      exists (e_castdn (e ^^ m)), (e_castdn (b ^^ m)). split_all; simpl.\n      * pick fresh x'. instantiate_cofinites. find_extract_invariants.\n      * pick fresh x'. instantiate_cofinites. find_extract_invariants.\n      * eauto.\n      * eauto.\n      * eapply s_castdn; eauto.\n        eapply s_sub with (F ^^ m) k_star; auto.\n        pick fresh x' for (L `union` L0 `union` L1 `union` fv_expr e `union` fv_expr b `union` fv_expr F).\n        rewrite_open_with_subst.\n        eauto 3 using substitution_cons.\n      * intro. apply is_forall_eq in H12. destruct_exists. subst. inversion H.\n    + invert_extractions. invert_sub_hyp. inversion H1; subst; solve_impossible_reduction.\n      (* main case for r_cast_elim *)\n      * exists e, b. repeat split; eauto.\n        apply castup_inversion in Sub2 as (C & k' & Sub & R & Sub').\n        apply s_sub with C k'. auto.\n        eapply type_preservation; eauto using deterministic_type_reduction. Unshelve. all: exact 0.\n  - edestruct IHSub1 as (e1' & e2' & H1); eauto.\n    destruct_pairs.\n    exists e1', e2'. repeat split; eauto.\nQed.\n", "meta": {"author": "VinaLx", "repo": "dependent-polymorphic-subtyping", "sha": "1a00b61a07e0198d417cf12727067bb1cf7187eb", "save_path": "github-repos/coq/VinaLx-dependent-polymorphic-subtyping", "path": "github-repos/coq/VinaLx-dependent-polymorphic-subtyping/dependent-polymorphic-subtyping-1a00b61a07e0198d417cf12727067bb1cf7187eb/src/proofs/Semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306515, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2573072338537998}}
{"text": "(* Multiple inputs and outputs, blocking reads *)\nRequire Import Merges.Tactics.\nRequire Import Merges.Map.\n\nRequire Import Merges.Machine.\nRequire Import Merges.Fusion.Base.\nRequire Import Merges.Fusion.Tactics.\n\n\nRequire Import Coq.Lists.List.\nImport ListNotations.\nSet Implicit Arguments.\nRequire Import Coq.Logic.FunctionalExtensionality.\n\n\n  Module B := Machine.Base.\n  Module P := Machine.Program.\n  Module F := Base.Fuse.\n  Module FT := Tactics.Tactics.\n\nSection Proof.\n  Variable C : Set.\n  Variable V1 : Set.\n  Variable L1 : Set.\n  Variable P1 : P.Program L1 C V1.\n\n  Variable V2 : Set.\n  Variable L2 : Set.\n  Variable P2 : P.Program L2 C V2.\n\n  Variable EqDec_C : EqDec C.\n\n  Theorem EvalBlockJump pL:\n   FT.EvalStep P1 P2 EqDec_C\n    (B.BlockJump _ _ pL).\n  Proof.\n    EvalStep_intros.\n    EvalStep_unfold_all.\n    jauto_set.\n      (* EvalBs P1 *)\n      - matchmaker hBlockEq; inject_all.\n\n        all: try EvalStep_Rule hEv1 hSv1.\n        all: !eapply B.EvalBs1.\n        all: try EvalStep_Rule B.EvalBJump hSv1.\n        all: try EvalStep_Rule B.EvalBRelease hSv1.\n\n      (* Sv P1 *)\n      - EvalStep_Invariant hSv1 hBlockEq.\n\n      (* EvalBs P2 *)\n      - matchmaker hBlockEq; inject_all.\n\n        all: try EvalStep_Rule hEv2 hSv2.\n        all: !eapply B.EvalBs1.\n        all: try EvalStep_Rule B.EvalBJump hSv2.\n        all: try EvalStep_Rule B.EvalBRelease hSv2.\n\n      (* Sv P2 *)\n      - EvalStep_Invariant hSv2 hBlockEq.\n    Qed.\n\nEnd Proof.\n", "meta": {"author": "amosr", "repo": "merges", "sha": "bf8cb7bca2d859977d6fb8bf4a9d07ac780b7edd", "save_path": "github-repos/coq/amosr-merges", "path": "github-repos/coq/amosr-merges/merges-bf8cb7bca2d859977d6fb8bf4a9d07ac780b7edd/proof/Merges/Fusion/EvalJump.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.25729124801816966}}
{"text": "(* We make a translation from full brunerie (any ctx) to brunerie *)\nRequire Import ssreflect ssrfun ssrbool .\n\nFrom Modules Require Import HomotopicalEquality TypesAreOmegaGroupoids.FunctionalRelation lib PreSyntaxOnlyContr .\nFrom Modules Require Import WfSyntaxBrunerieOnlyContr.\n(* gtype decl omegagroupoids fullomegagroupoids. *)\nFrom Modules Require Import WfSyntaxBrunerieAllCtx.\nSet Bullet Behavior \"Strict Subproofs\".\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* Local Notation \"⟦ X ⟧V\" := (dTm (w_va X)). *)\n\nModule B := WfSyntaxBrunerieOnlyContr.\nModule FB := WfSyntaxBrunerieAllCtx.\n\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\nModule SS  := PreSyntaxOnlyContr.\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\nOn pourrait essayer de montrer la chose suivante pour la syntaxe full brunerie :\nsi Γ ⊢ coh_Δ,A[σ] alors il existe Γ' ⊂ Γ  contractile et Γ' ⊢ δ : Δ telles que σ \nbof..\n\nOu encore: on fait une traduction Full Brunerie -> Brunerie pour la sous-syntaxe de Full Brunerie\nrestreint aux contextes contractiles.\nC'est parti\n\n\n*)\n\nFixpoint tradV Γ x  : SS.Var :=\n  match Γ,x with\n    ext empty _, v0 => vstar\n  | ext (ext Γ A) B, v0 => SS.v0\n  | ext (ext Γ A) B, vwk v0 => SS.v1\n  | ext (ext Γ A) B, vwk (vwk x) => SS.vwk (tradV Γ x)\n  (* dummy *)\n  | _,_ => vstar\n  end.\n\n(*\nFixpoint tradV Γ A x (wx : SF_WVar Γ A x) : SB.Var.\n destruct wx.\n - (* dummy *)\n   exact:vstar.\n - (* cas v0 *)\n*)\n\nLtac exfalsoinvert h := exfalso; inversion h.\n    \nFixpoint tradC (Γ : FB.Con)  (isC : isContr Γ) (wΓ: FB.WC Γ) : SS.Con\nwith tradTy (Γ : FB.Con) (A : FB.Ty) (wA : FB.WTy Γ A) : SS.Ty\nwith tradTm (Γ : FB.Con) A (t : FB.Tm) (wt : FB.Wtm Γ A t) : SS.Tm\nwith tradS Γ (Δ : FB.Con) (σ : FB.sub) (wσ : FB.WS Γ Δ σ) : SS.sub.\n- destruct wΓ as [| ? ? ? wA].\n  + by exfalsoinvert isC.\n  + destruct wΓ.\n    * destruct A ; last by exfalsoinvert isC.\n      exact:astar.\n    * destruct A; first by exfalsoinvert isC.\n      destruct t; last by  exfalsoinvert isC.\n      destruct x; last by  exfalsoinvert isC.\n      apply:SS.ext.\n    -- apply:(tradC _  (snd isC)) => //.\n    (* apply:isContr_WC => //. *)\n    -- apply:(tradTy Γ).\n      eassumption.\n    -- apply:tradTm.\n      eassumption.\n- destruct wA.\n  (* star *)\n  + exact:SS.star.\n  + apply:SS.ar.\n    * apply:tradTy.\n      exact:wA.\n    * apply:tradTm.\n      exact :w.\n    * apply:tradTm.\n      exact :w0.\n- destruct wt.\n  (* variable *)\n  + exact:(SS.va (tradV Γ x)).\n  + apply:SS.coh.\n    * apply:tradC; last by eassumption.\n      (* eassumption. *)\n    * apply:tradTy.\n      exact:w0.\n    * apply:tradS.\n      eassumption.\n- destruct wσ.\n  (* to_empty.. *)\n  + (* dummy *)\n    exact :(SS.to_star (SS.va (SS.vstar))).\n  + destruct wσ; first by exact :(SS.to_star (SS.va (SS.vstar))).\n    apply:SS.to_ext.\n    * apply:tradS.\n      eassumption.\n    * apply:tradTm.\n      exact:w2.\n    * apply:tradTm.\n      exact:w0.\nDefined.\n\n(*\nFixpoint tradC (Γ : FB.Con)  (isC : isContr Γ) : SS.Con\nwith tradTy (Γ : FB.Con) (A : FB.Ty) (wA : FB.WTy Γ A) : SS.Ty\nwith tradTm (Γ : FB.Con) A (t : FB.Tm) (wt : FB.Wtm Γ A t) : SS.Tm\nwith tradS Γ (Δ : FB.Con) (σ : FB.sub) (wσ : FB.WS Γ Δ σ) : SS.sub.\n- destruct isC.\n  + exact:astar.\n  + apply:SS.ext.\n    * apply:(tradC _  isC) => //.\n      (* apply:isContr_WC => //. *)\n    * apply:(tradTy Γ).\n      eassumption.\n    * apply:tradTm.\n      eassumption.\n- destruct wA.\n  (* star *)\n  + exact:SS.star.\n  + apply:SS.ar.\n    * apply:tradTy.\n      exact:wA.\n    * apply:tradTm.\n      exact :w.\n    * apply:tradTm.\n      exact :w0.\n- destruct wt.\n  (* variable *)\n  + exact:(SS.va (tradV Γ x)).\n  + apply:SS.coh.\n    * apply:tradC; last by eassumption.\n      (* eassumption. *)\n    * apply:tradTy.\n      exact:w0.\n    * apply:tradS.\n      eassumption.\n- destruct wσ.\n  (* to_empty.. *)\n  + (* dummy *)\n    exact :(SS.to_star (SS.va (SS.vstar))).\n  + destruct wσ; first by exact :(SS.to_star (SS.va (SS.vstar))).\n    apply:SS.to_ext.\n    * apply:tradS.\n      eassumption.\n    * apply:tradTm.\n      exact:w2.\n    * apply:tradTm.\n      exact:w0.\nDefined.\n\nLocal Notation \"⟦ X  ⟧C\" := (tradC X ).\nLocal Notation \"⟦ X ⟧T\" := (tradTy X).\nLocal Notation \"⟦ X ⟧t\" := (tradTm X).\nLocal Notation \"⟦ X ⟧S\" := (tradS X).\n\nLemma w_tradStar (Γ : FB.Con) wΓ (isC : isContr Γ)   : B.WTy ⟦ isC ⟧C ⟦ w_star (Γ := Γ) wΓ ⟧T.\nProof.\n  induction isC => /=; repeat constructor.\nAbort.\n\nFixpoint w_tradC Γ  (isC : isContr Γ) : (B.WC ⟦ isC ⟧C * B.WTy ⟦ isC ⟧C ⟦ w_star (Γ := Γ) (isContr_WC isC) ⟧T)\nwith w_tradTy (Γ : FB.Con) (isC : isContr Γ) (A : FB.Ty) (wA : FB.WTy Γ A) : B.WTy ⟦ isC ⟧C ⟦ wA ⟧T.\n- destruct isC => /=.\n  + repeat constructor.\n  + split.\n    {\n      constructor.\n    * apply:(fst (w_tradC _ _)).\n    * apply:w_tradTy.\n    * admit.\n      }\n    {\n      repeat constructor.\n      - apply:(fst (w_tradC _ _)).\n      - apply:w_tradTy.\n      - admit.\n        }\n\n- Guarded.\n    destruct wA => /=.\n  + apply:(snd (w_tradC _ isC)).\n  + Guarded.\n(*\nFixpoint tradC (Γ : FB.Con)  : SS.Con :=\n  match Γ with\n    | ext empty star => astar\n    | ext (ext Γ A) (ar _ (va v0) u) => astar\n    (* dummy *)\n    | _ => astar\n  end\nwith tradTy (Γ : FB.Con) (A : FB.Ty) : SS.Ty\nwith tradTm (Γ : FB.Con) (t : FB.Tm) : SS.Tm\nwith tradS (Δ : FB.Con) (σ : FB.sub) : SS.sub.\n  - destruct isC.\n    + exact astar.\n    + apply:SB.ext.\n      * exact:(tradC _ isC).\n      * exact:IHisC.\n*)\n\n\n(*\nLa syntaxe bien typée full brunerie s'injecte dans brunerie minimal\navec des contextes non vides\n\nTraduction Full Brunerie --> Brunerie\n\n⟦ x:* ⟧ = ⟦ x : * ⟧\n⟦ Γ , x : A ⟧ = ⟦ Γ ⟧ , x : ⟦ A ⟧, f : x -> coh_⟦Γ⟧,⟦A⟧ \n\n⟦ * ⟧ = *\n⟦ t ->_A u ⟧ = ⟦ t ⟧ ->_⟦A⟧ ⟦ u ⟧\n\n⟦ v0 ⟧ = v1\n⟦ vwk x ⟧ = vwk ⟦ x ⟧\n⟦ coh_Γ,A [σ ] ⟧ = coh_⟦Γ⟧,⟦A⟧ [ ⟦ σ ⟧ ]\n\nPour les substitutions\n⟦ (t) ⟧ = to_star ⟦ t ⟧\n⟦ (σ, t) ⟧ =  (⟦ σ ⟧, ⟦ t ⟧, coh_⟦Γ⟧,(⟦t⟧ -> coh_⟦Δ⟧,⟦A⟧[⟦σ⟧])\n\noù Γ ⊢ (σ,t) : (Δ, x : A)\n\n Γ ⊢ A implique  ⟦ Γ ⟧ ⊢ ⟦ A ⟧\n Γ ⊢ t: A -> ⟦ Γ ⟧ ⊢ ⟦ t ⟧ : ⟦ A ⟧\n Γ ⊢ σ : Δ -> ⟦ Γ ⟧ ⊢ ⟦ σ ⟧ : ⟦ Δ ⟧\n\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/FullBrunerieToBrunerie.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.25729124801816966}}
{"text": "\nRequire Export Basics.\n\nRequire Export EnvListAux7.\nRequire Export EnvListAuxT1.\n\nRequire Export Coq.Program.Equality.\nRequire Import Coq.Init.Specif.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Omega.\nRequire Import Coq.Lists.List.\n\nRequire Import TPipStaticM2.\nRequire Import TPipDynamicM2.\nRequire Import TRInductM2.\nRequire Import WeakM2.\n\nRequire Import TSoundnessRM2.\nRequire Import ReflectInterpM2. \nRequire Import IdModType.\n\nModule SOS2Gall (IdT: IdModType) <: IdModType.\nExport IdT.\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 ReflectC := Reflect IdT.\nExport ReflectC.\n\n\nProgram Definition SOS_Exp \n                   (fenv: funEnv) (env: valEnv)\n                   (e: Exp) (t: VTyp) (n: W) \n                   (k: SoundExp fenv env e t n) :\n                              prod (vtypExt t) W := _.\n\nNext Obligation.\n  unfold SoundExp in k.\n  destruct k.\n  split.\n  - inversion v; subst.\n    subst T.\n    rewrite H in H0.\n    assert (projT1 x).\n    exact (cstExt x).\n    unfold vtypExt.\n    rewrite <- H.\n    exact X.\n  - destruct s.\n    exact x0.\nDefined.    \n\n\n\nProgram Definition SOS_Fun\n        (f: Fun) (ft: FTyp) (n: W)\n        (k0: FunTyping f ft)\n        (env: valEnv)\n        (k: SoundFun env (extParType ft) f (extRetType ft) n)\n                   : prod (vtypExt (extRetType ft)) W := _.\n\nNext Obligation.\n  unfold SoundFun in k.\n  destruct ft.\n  (*simpl in m.*)\n  simpl in k.\n  simpl.\n  destruct f.\n  inversion k0; subst.  \n  specialize (k eq_refl).\n  eapply SOS_Exp.\n  exact k.\n  specialize (k eq_refl).\n  eapply SOS_Exp.\n  exact k.\nDefined.  \n  \n\nProgram Definition SOS_QFun\n         (ftenv: funTC) (fenv: funEnv)\n         (q: QFun) (ft: FTyp) (n: W)\n         (k0: QFunTyping ftenv fenv q ft)\n         (env: valEnv)  \n         (k: SoundQFun fenv env (extParType ft) q (extRetType ft) n)\n              : prod (vtypExt (extRetType ft)) W := _.\n\nNext Obligation.\n  unfold SoundQFun in k.\n  destruct k.\n  specialize (q0 n).\n  eapply SOS_Fun in s.\n  exact s.\n  inversion k0; subst.\n  inversion q0; subst.\n  exact X.\n  inversion X0.\n  inversion q0; subst.\n  inversion X0; subst.\n  inversion X; subst.\n  assert (findE ls1 x0 = None).\n  eapply ExRelValTNone in X3.\n  exact X3.\n  exact ft.\n  exact H.\n  inversion X1; subst.\n  assert (findE (overrideE ls1 ((x0, f) :: ls3)) x0 =\n                 findE ((x0, f) :: ls3) x0). \n  rewrite overrideRedux2.\n  auto.\n  exact H0.\n  unfold overrideE in H2.\n  rewrite H2 in H1.\n  simpl in H1.\n  destruct (IdT.IdEqDec x0 x0) in H1.\n  inversion H1; subst.\n  exact X2.\n  intuition n.\nDefined.  \n\n   \nProgram Fixpoint SOS_Prms\n                   (fenv: funEnv) (env: valEnv)\n                   (ps: Prms) (pt: PTyp) (n: W) \n                   (k: SoundPrms fenv env ps pt n) :\n                              prod (PTyp_Trans pt) W := _.\n\nNext Obligation.\n  unfold SoundPrms in k.\n  destruct k as [es m].\n  split.\n(**)  \n  - destruct m as [vs m1 k].\n    destruct k as [m2 k].\n    inversion m2; subst.\n    unfold PTyp_Trans.\n    revert m1.\n    revert vs.\n    revert k.\n    revert ps.\n    revert n.\n    induction X.\n    + simpl.\n      intros.\n      exact tt.\n    + intros.\n      destruct vs.\n      inversion m1; subst.\n      simpl in H.\n      inversion H.\n      destruct ps.\n      destruct es.\n      destruct k as [n2 k].\n      inversion k; subst.\n      inversion X0.\n      inversion m2; subst.\n      inversion X0; subst.\n      \n      assert (PrmsTyping emptyE emptyE emptyE (PS l) (PT l')).\n      * constructor.\n        exact X2.\n      * specialize (IHX X3).\n        inversion m1; subst.\n        simpl in H.\n        inversion H; subst.\n        clear H.\n        assert (isValueList2T (map Val vs) vs) as J1.\n        constructor.\n        auto.\n        inversion X1; subst.\n\n        eapply PrmsClos_aux1 in k.\n        destruct k.\n        destruct p.\n       \n        constructor.\n        unfold VTyp_Trans.\n        eapply (SOS_Exp fenv env e y n).\n        unfold SoundExp.\n        constructor 1 with (x:=v).\n        exact H3.\n        econstructor 1 with (x:=x).\n        exact e0.\n\n        specialize (IHX x (PS es) s vs J1).\n        exact IHX.\n  - destruct m.\n    destruct p.\n    destruct s.\n    exact x0.\n(*  Show Proof.\n  Unshelve.\n  exact fenv.\n  exact env.\n  exact n.\n*)\nDefined.\n\n\n  \n\n(*\nProgram Definition SOS_Exp (Z: Type) (PZ: PState Z)\n                   (fenv: funEnv) (env: valEnv)\n                   (e: Exp) (t: VTyp) (n: Z) \n                   (k: SoundExp Z PZ fenv env e t n) (n: Z) :\n                              prod (vtypExt t) Z := _.\n*)\n(*\nLemma InterEquivExp \n         (ftenv: funTC) (tenv: valTC) (fenv: funEnv)\n         (e: Exp) (t: VTyp) (k0: ExpTyping ftenv tenv fenv e t) \n         (k1: FEnvTyping fenv ftenv)   \n         (env: valEnv)\n         (k2: EnvTyping env tenv) (n: W) :  \n         Exp_Trans ftenv tenv fenv e t k0 k1 env k2 n = \n         SOS_Exp fenv env e t n \n                 (ExpEval ftenv tenv fenv e t k0 k1 env k2 n).\nProof.\n  unfold Exp_Trans.\n  unfold SOS_Exp.\nAdmitted.\n\n\nLemma InterEquivPrms \n         (ftenv: funTC) (tenv: valTC) (fenv: funEnv)\n         (ps: Prms) (pt: PTyp) (k0: PrmsTyping ftenv tenv fenv ps pt) \n         (k1: FEnvTyping fenv ftenv)   \n         (env: valEnv)\n         (k2: EnvTyping env tenv) (n: W) :  \n         Prms_Trans ftenv tenv fenv ps pt k0 k1 env k2 n = \n         SOS_Prms fenv env ps pt n \n                 (PrmsEval ftenv tenv fenv ps pt k0 k1 env k2 n).\nProof.\nAdmitted.\n\n\nLemma InterEquivFun \n         (f: Fun) (ft: FTyp) (k0: FunTyping f ft) \n         (env: valEnv) \n         (k1: EnvTyping env (extParType ft)) (n: W) :\n         Fun_Trans f ft k0 (WT_valEnv_Trans (extParType ft) env k1) n = \n         SOS_Fun f ft n k0 env (FunEval f ft k0 env k1 n).\nProof.\nAdmitted.\n\n\nLemma InterEquivQFun\n         (ftenv: funTC) (fenv: funEnv)\n         (q: QFun) (ft: FTyp) \n         (k0: QFunTyping ftenv fenv q ft)\n         (k1: FEnvTyping fenv ftenv)   \n         (env: valEnv) \n         (k2: EnvTyping env (extParType ft)) (n: W) :  \n  QFun_Trans ftenv fenv q ft k0 k1 \n             (WT_valEnv_Trans (extParType ft) env k2) n = \n         SOS_QFun ftenv fenv q ft n k0 env   \n                          (QFunEval ftenv fenv q ft k0 k1 env k2 n).\nProof.\nAdmitted.\n\n*)\n\n  \n\n(*************************************************************************)\n(*** superseded ******************)\n\nDefinition SoundFunB \n         (f: Fun) (ft: FTyp) \n         (k: FunTyping f ft)\n         (env: valEnv)\n         (m: EnvTyping env (extParType ft)) (n: W) :=\n  SoundFun env (extParType ft) f (extRetType ft) n. \n  \nProgram Definition SOS_FunB\n        (f: Fun) (ft: FTyp) (n: W)\n        (k0: FunTyping f ft)\n        (env: valEnv)\n        (m: EnvTyping env (extParType ft)) \n        (k: SoundFunB f ft k0 env m n)\n                   : prod (vtypExt (extRetType ft)) W := _.\n\nNext Obligation.\n  unfold SoundFunB in k.\n  destruct ft.\n  simpl in m.\n  simpl in k.\n  simpl.\n  unfold SoundFun in k.\n  destruct f.\n  inversion k0; subst.  \n  specialize (k eq_refl).\n  eapply SOS_Exp.\n  exact k.\n  specialize (k eq_refl).\n  eapply SOS_Exp.\n  exact k.\nDefined.  \n\n(*************)\n\nDefinition SoundFunC\n         (f: Fun) (ft: FTyp) (n: W)\n         (k: FunTyping f ft)\n         (env: valEnv) :=\n         (* EnvTyping env (extParType ft) -> *)\n  SoundFun env (extParType ft) f (extRetType ft) n. \n\n\nDefinition SoundQFunC\n         (ftenv: funTC) (fenv: funEnv)\n         (q: QFun) (ft: FTyp) (n: W)\n         (k: QFunTyping ftenv fenv q ft)\n         (env: valEnv) :=\n(*         EnvTyping env (extParType ft) ->  *)\n  SoundQFun fenv env (extParType ft) q (extRetType ft) n. \n\n\n\nEnd SOS2Gall.", "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/obselete - other files/B/SOS2Gallina.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.257291241538743}}
{"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_take E n ls bs :\n  enc_bits E ls bs -> enc_bits E (take n ls) (take 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 /= .\n    + by rewrite /= enc_bits_cons Hlsbshd (IH Hlsbstl n) .\nQed .\n\nLemma newer_than_lits_take g n ls :\n  newer_than_lits g ls -> newer_than_lits g (take 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]; first by rewrite /= .\n    by rewrite /= Hlshd (IH n Hlstl) .\nQed .\n\n(* ===== bit_blast_low ===== *)\n\nDefinition bit_blast_low g n ls : generator * cnf * word :=\n  (g, [::], take n ls ++ copy (n - size ls) lit_ff) .\n\nDefinition mk_env_low E g n ls : env * generator * cnf * word :=\n  (E, g, [::], take n ls ++ copy (n - size ls) lit_ff) .\n\nLemma bit_blast_low_correct E g n bs ls g' cs lr :\n  bit_blast_low g n ls = (g', cs, lr) ->\n  enc_bits E ls bs ->\n  interp_cnf E (add_prelude cs) ->\n  enc_bits E lr (low n bs) .\nProof .\n  rewrite /bit_blast_low /low /zeros .\n  case => _ _ <- Hlsbs Hcnf .\n  rewrite enc_bits_cat /=; first done .\n  - exact : enc_bits_take .\n  - rewrite /b0 (enc_bits_size Hlsbs) .\n    move : (add_prelude_enc_bit_ff Hcnf) .\n    exact : enc_bits_copy .\nQed .\n\nLemma mk_env_low_is_bit_blast_low E g n ls E' g' cs lr :\n  mk_env_low E g n ls = (E', g', cs, lr) -> bit_blast_low g n ls = (g', cs, lr) .\nProof .\n  rewrite /mk_env_low /bit_blast_low .\n  by case => _ <- <- <- .\nQed .\n\nLemma mk_env_low_newer_gen E g n ls E' g' cs lr :\n  mk_env_low E g n ls = (E', g', cs, lr) -> (g <=? g')%positive.\nProof .\n  rewrite /mk_env_low .\n  t_auto_newer .\nQed .\n\nLemma mk_env_low_newer_res E g n ls E' g' cs lrs :\n  mk_env_low E g n ls = (E', g', cs, lrs) ->\n  newer_than_lit g lit_tt -> newer_than_lits g ls ->\n  newer_than_lits g' lrs .\nProof .\n  rewrite /mk_env_low .\n  case => _ <- _ <- Htt Hls .\n  rewrite newer_than_lits_cat .\n  apply /andP; split .\n  - exact : newer_than_lits_take .\n  - exact : newer_than_lits_copy .\nQed .\n\nLemma mk_env_low_newer_cnf E g n ls E' g' cs lrs :\n  mk_env_low 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  rewrite /mk_env_low .\n  by case => _ <- <- _ .\nQed .\n\nLemma mk_env_low_preserve E g n ls E' g' cs lrs :\n  mk_env_low E g n ls = (E', g', cs, lrs) -> env_preserve E E' g .\nProof .\n  by rewrite /mk_env_low; case => <- _ _ _ .\nQed .\n\nLemma mk_env_low_sat E g n ls E' g' cs lrs :\n  mk_env_low E g n ls = (E', g', cs, lrs) ->\n  newer_than_lits g ls -> interp_cnf E' cs .\nProof .\n  by rewrite /mk_env_low; case => <- _ <- _ .\nQed .\n\nLemma mk_env_low_env_equal E1 E2 g n ls E1' E2' g1 g2 cs1 cs2 lrs1 lrs2 :\n  env_equal E1 E2 ->\n  mk_env_low E1 g n ls = (E1', g1, cs1, lrs1) ->\n  mk_env_low E2 g n ls = (E2', g2, cs2, lrs2) ->\n  env_equal E1' E2' /\\ g1 = g2 /\\ cs1 = cs2 /\\ lrs1 = lrs2.\nProof.\n  rewrite /mk_env_low => 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/BBLow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.25729123505931617}}
{"text": "Require Import Coq.Classes.DecidableClass.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Bool.Bool.\nRequire Import SquiggleEq.export.\nRequire Import SquiggleEq.UsefulTypes.\nRequire Import SquiggleEq.list.\nRequire Import SquiggleEq.LibTactics.\nRequire Import SquiggleEq.tactics.\nRequire Import SquiggleEq.AssociationList.\nRequire Import ExtLib.Structures.Monads.\nRequire Import templateCoqMisc.\nRequire Import Template.Template.\nRequire Import Template.Ast.\nRequire Import NArith.\nRequire Import Coq.Program.Program.\nOpen Scope program_scope.\nRequire Import Coq.Init.Nat.\nRequire Import SquiggleEq.varInterface.\nRequire Import SquiggleEq.varImplDummyPair.\nRequire Import ReflParam.paramDirect.\n\n\nFixpoint removeCastsInConstrType (tind : inductive) (t:STerm) : (STerm) :=\nmatch t with\n| mkPiS x A Sa B Sb \n  => let (A,Sa) := if isConstrArgRecursive tind A then (removeIndRelProps A,None) else (A,Sa) in\n    mkPiS x A Sa (removeCastsInConstrType tind B) None\n| t => t\nend.\n\n\n(*\nDefinition translateConstrArg tind (p : Arg) : (V * STerm) :=\nlet (v,t) := p in\nlet t := if isConstrArgRecursive tind (fst t) then (removeIndRelProps (fst t),None) else t in \ntranslateArg (v,t).\n *)\n\nDefinition mkConstrInfo numParams (constrLamType_R : nat*STerm) \n(* Pis converted to lams before translating *)\n: IndTrans.ConstructorInfo := \nlet (index, constrLamType_R) := constrLamType_R  in\nlet (retType_R, args_R) := getHeadLams constrLamType_R  in\n  let (_,cRetTypArgs_R) := flattenApp retType_R [] in\n  let cretIndices_R := skipn (3*numParams) cRetTypArgs_R in\n{|\n    IndTrans.index := index;\n    IndTrans.args_R := TranslatedArg.unMerge3way args_R;\n    IndTrans.retTyp := retType_R;\n    IndTrans.retTypIndices_R := TranslatedArg.unMerge3way cretIndices_R\n|}.\n\n(* before goodness has been fully generated, we need too remove the flags that inddicate\nthat A:Set and thus A's relation must be good, for A:= the mutual ind being processed now.\nThe index in tind is ignored *)\n\nDefinition mkConstrInfoBeforeGoodness (tind:inductive)\n           (numParams : nat )(translate: STerm-> STerm) (constrTypes : list STerm) :=\n      let constrTypes_R := map (translate ∘ headPisToLams ∘ (removeCastsInConstrType tind))\n                               constrTypes in\n      map (mkConstrInfo numParams) (numberElems constrTypes_R).\n\n(* for a constructor C of type T, it produces C_R : [T] C C.\nthe input args are already translated.\nBoth in C_RR and C_RRinv, the corresponding I_RR never directly occurs.\nif they occured, there relation would have to be casted. right now,\nC_RR and C_RRinv already produce the casted version *)\nDefinition translateConstructor (tind:inductive)\n(*np:nat*) (cindex:nat)\n(cargs_R cargsRR indTypeParams_R (* indTypIndices_RR*) : list Arg)\n(constrApp sigtFullConstrIndices : STerm)\n  : defSq*STerm :=\nlet cname := constrTransName tind cindex in\nlet lamArgs := (map removeSortInfo (indTypeParams_R ++ cargs_R)) in\nlet ext := sigTToExistT2 (map (vterm∘fst) cargsRR) constrApp sigtFullConstrIndices in\n({| nameSq := cname; bodySq := mkLamL lamArgs ext |}, ext).\n\n\n(* the indices_RR need not be cretIndices. \nthis one uses the index indices irrel lemma whic uses proof irrelevance *) \nDefinition translateConstructorTot (tind:inductive)\n(*np:nat*) (cindex:nat) (cretIndices_R : list STerm)\n(cargs_R  indTypeParams_R : list Arg) (indTypIndices_RR : list (V*STerm))\n(sigtFull : STerm)\n  : defSq :=\n  let cname := constrTransTotName tind cindex in\n  let constArgs := mrs (indTypeParams_R ++ cargs_R) in\n  let allArgs := constArgs ++ indTypIndices_RR in\n  let tindIArgs : list STerm :=\n      (map (vterm ∘ fst) indTypeParams_R)\n        ++ cretIndices_R\n        ++ (map (vterm ∘ fst) indTypIndices_RR) in\n  let body := mkConstApp (constrTransName tind cindex) (map (vterm ∘ fst) constArgs) in\n  let v := freshUserVar (map fst allArgs) \"eqIrr\" in\n  let tindi := mkInd (indIndicesTransName tind) 0 in\n  let o :=\n      (CCase (tindi, length constArgs) [0])%nat None in\n  let caseRet :=\n      mkLamL (snoc (indTypIndices_RR) (v, mkIndApp tindi tindIArgs))\n             sigtFull in (* sigtFull is only used here *)\n  let peq := mkConstApp (indIndicesIrrelTransName tind) tindIArgs in\n  let body := oterm o (map (bterm [])[caseRet; peq; body]) in\n({| nameSq := cname; bodySq := mkLamL (allArgs) body |}).\n\n\n(** retTyp is the retTyp applied to all the ind_RRs except the last one.\nexistT is initially sigtVar, whose type is the big sigma type.\nvars : initially null\nsigT is the type of sigtVar, the branch of I_RR *)\nFixpoint crInvMapSigT o (indicRR: list (V*STerm))(sigtVar : V) (f retTyp existt sigt: STerm)\n         (vars: list V) {struct sigt}: STerm :=\n  let sigRetTyp := (mkLam sigtVar sigt (mkApp retTyp [existt])) in\n  let finalCase (_: unit) :=\n      let mb := mkApp f (map vterm vars) in (* the constructor takes no args *)\n      (* Fix. need to have goodness here.. this will be used in matches.\nonly while generating I_RR and its goodness, we can skip goodness *)\n      let caseType := mkLamL(*S*) (indicRR) sigRetTyp in\n      let matchBody := oterm o (map (bterm []) [caseType; vterm sigtVar; mb]) in\n      mkLam sigtVar sigt matchBody in\n                  \nmatch sigt with\n| oterm (CApply _)\n ((bterm [] (mkConstInd (mkInd s _)))::\n   (bterm [] A)::(bterm [] (mkLamS a _(*A*) _ b))::[])\n  =>\n  if (decide (s=sigt_ref)) then \n    let B := (mkLam a A b) in\n    let newDepPair := mkApp (mkConstr (mkInd sigt_ref 0) 0) [A;B;vterm a;vterm sigtVar] in \n    let newExistt := ssubst_aux existt [(sigtVar,newDepPair)] in \n    let sigRet := mkLam a A (crInvMapSigT o indicRR sigtVar f retTyp newExistt b (snoc vars a)) in\n    mkSigTRectDirect A B  sigRetTyp sigRet\n  else finalCase ()\n| _ => finalCase ()\nend.\n\nDefinition translateConstructorInv \n  (tind tindConstr:inductive) (indConstrNumParams : nat)\n  (*np:nat*) (cindex:nat)\n  (C_RRBody : STerm)\n  (cretIndices_RR : list STerm)\n  (cargs_R cargsRR indTypeParams_R : list Arg)  \n  (indTypIndices_RR : list (V*STerm))\n  (sigtFull : STerm) : defSq:=\n\nlet cname := constrInvFullName tind cindex in\nlet freshVars := \n  let fvars :=  dummyVar::((map fst cargs_R)++(map fst indTypeParams_R)) in\n  freshUserVars fvars [\"sigt\", \"rett\", \"retTyp\"] in\nlet sigtVar := vrel (nth 0 freshVars dummyVar) in\nlet rettVar := vrel (nth 1 freshVars dummyVar) in\nlet retTypVar := vrel (nth 2 freshVars dummyVar) in\nlet (cargs_RR,cargsAndPrimes) := separate_Rs cargs_R in\nlet lamArgs := (map removeSortInfo (indTypeParams_R++ cargsAndPrimes))\n                ++indTypIndices_RR in \nlet cargs_RR := map removeSortInfo cargs_RR in\nlet retTypVarType : STerm := \n    let retTypVarSort : STerm\n                  (* Fix. make it template/univ poly *)\n        := mkConst \"Trecord.IndicesInvUniv\" in \n  (* dummyVar is fine, because the next item is a sort, thus has no fvars *)\n  (mkPiL (snoc indTypIndices_RR (dummyVar, sigtFull)) retTypVarSort) in\nlet rettVarType := \n  (mkPiL cargs_RR (mkApp (vterm retTypVar) (snoc cretIndices_RR C_RRBody))) in\nlet crinvBody := \n    let rettTypPartiallyApplied : STerm := \n        (mkApp (vterm retTypVar) (map (vterm∘fst) indTypIndices_RR)) in\n    let o := (CCase (tindConstr, indConstrNumParams) [O] None) in\n    mkApp (crInvMapSigT o indTypIndices_RR sigtVar (vterm rettVar) rettTypPartiallyApplied\n                 (vterm sigtVar) sigtFull []) [vterm sigtVar] in\n(*  let T := (mkConstInd (mkInd \"Coq.Init.Logic.True\" 0)) in\n  let sigt := (mkSigL cargs_RR T) in\n  let ext := sigTToExistTRect (vterm sigtVar) (vterm rettVar) sigt [] in *)\nlet lamArgs := lamArgs\n  ++ [(sigtVar, sigtFull); (retTypVar, retTypVarType); (rettVar, rettVarType)] in\n{| nameSq := cname; bodySq := mkLamL lamArgs crinvBody |}.\n\n\nDefinition translateIndInnerMatchBranch (tind : inductive )\n(indTypeParams_R (* indTypIndices_RR *) : list Arg) (indTypIndicVars : list V)\n(caseTypRet:  STerm) (argsB: bool * IndTrans.ConstructorInfo) : \n  STerm * (list defSq) :=\n  let (b,cinfo) := argsB in\n  let cargsRR := map removeSortInfo (IndTrans.argRR cinfo) in\n  let indTypeParams_RP := TranslatedArg.unMerge3way indTypeParams_R in\n  let cargs_R : list Arg := TranslatedArg.merge3way (IndTrans.args_R cinfo) in\n  let cargs := IndTrans.args cinfo in\n  let indTypIndicVarsP := (map vprime indTypIndicVars) in\n  let cretIndices843 := (IndTrans.indices cinfo) in\n  let cretIndicesPrime843 := (IndTrans.indicesPrimes cinfo) in\n  let caseTypRet := \n    ssubst_aux caseTypRet (combine indTypIndicVarsP cretIndicesPrime843) in\n  let (_,indTypIndices_RR) := getHeadPIs caseTypRet in\n  let indTypIndices_RR := map removeSortInfo indTypIndices_RR in\n  let cretIndices_R : list STerm := TranslatedArg.merge3way\n                                      (IndTrans.retTypIndices_R cinfo) in\n  let cretIndices_RR : list STerm := (IndTrans.indicesRR cinfo) in\n  let t := boolToProp b in\n  let ret (_:True):=\n    let tindIndicesName := (indIndicesTransName tind) in \n    let tindIndices := (mkInd tindIndicesName 0) in\n    let tindsConstrArgs := map (vterm ∘ fst) indTypeParams_R ++ cretIndices_R in\n    let tindsArgs :=  tindsConstrArgs ++ map (vterm ∘ fst) indTypIndices_RR in\n    let tindApplied := mkIndApp tindIndices tindsArgs in\n    let tindConstrApplied := mkApp (mkConstr tindIndices 0) tindsConstrArgs in\n    let sigtFull := mkSigL cargsRR tindApplied in\n    let (C_RR,C_RRbody) := \n      let fvars : list V:= flat_map free_vars cretIndices_RR in\n      let sigtFullR : STerm := change_bvars_alpha fvars sigtFull in\n      let sigtFullConstrIndices : STerm := \n        ssubst_aux sigtFullR (combine (map fst indTypIndices_RR) cretIndices_RR) in\n          translateConstructor tind (IndTrans.index cinfo) \n          cargs_R (IndTrans.argRR cinfo) indTypeParams_R tindConstrApplied sigtFullConstrIndices in\n    let C_RRInv := \n        translateConstructorInv tind tindIndices (length tindsConstrArgs)\n                                (IndTrans.index cinfo) \n                                C_RRbody cretIndices_RR cargs_R (IndTrans.argRR cinfo)\n                                indTypeParams_R indTypIndices_RR\n                                sigtFull in \n    let C_RRTot :=\n        let sigtFull :=\n            let cretIndices_Rpartial :=\n                (* change the indIndices and indIndicesPrimes to cretIndices and cretIndicesPrimes\n                   but don't change indIndiceRs *)\n                merge3Lists cretIndices843 cretIndicesPrime843 (map (vterm∘vrel) indTypIndicVars) in\n            let thisConstrApplied :=\n                mkApp\n                  (mkConstr tind (IndTrans.index cinfo))\n                  (fstVterms ((map (TranslatedArg.arg) indTypeParams_RP) ++ cargs)) in\n            mkConstApp\n              (indTransName tind)\n              ((fstVterms indTypeParams_R)\n                 ++ cretIndices_Rpartial\n                 ++ [thisConstrApplied; tprime thisConstrApplied]) in\n        translateConstructorTot tind (IndTrans.index cinfo)\n                                (TranslatedArg.merge3way (IndTrans.retTypIndices_R cinfo))\n                                cargs_R\n                                indTypeParams_R\n                                indTypIndices_RR\n                                sigtFull in \n    (sigtFull,  [C_RR , C_RRInv , C_RRTot  ]) in\n  (* to avoid duplicate work, only make defs if b is true *)\n  let retDefs : (STerm* list defSq) := \n    (if b  then (ret I) else (t,[])) in\n  (mkLamL (map primeArg cargs) (mkLamL indTypIndices_RR (fst retDefs)),snd retDefs).\n\n\n(* List.In  (snd lb) lcargs *)\nDefinition translateIndInnerMatchBody tind o (lcargs: list IndTrans.ConstructorInfo)\n   v (caseTypArgs : list (V*STerm))(caseTypRet:  STerm)\n   (indTypeParams_R indTypIndices_RR : list Arg) (indTypIndicVars : list V)\n    (lb: (list bool)*(IndTrans.ConstructorInfo)) :=\n  let (lb,cinfo) := lb in \n  let cretIndices := IndTrans.indices cinfo in\n  let args := IndTrans.args cinfo in\n  let caseTypRet := \n    ssubst_aux caseTypRet (combine indTypIndicVars cretIndices) in\n  let mTyInfo := mkLamL (map primeArgsOld caseTypArgs) caseTypRet in\n  let brsAndDefs := (map (translateIndInnerMatchBranch tind \n          indTypeParams_R\n          (*indTypIndices_RR  *)\n          indTypIndicVars caseTypRet)\n         (combine lb lcargs)) in\n  let branches := map fst brsAndDefs in\n  let defs := flat_map snd brsAndDefs in \n    (* _RRs and _RRinvs for ONLY the constructor where the bool is true in b*)\n  let lnt : list STerm := [mTyInfo; vterm (vprime v)] ++branches in\n  (mkLamL (map removeSortInfo args) (oterm  o (map (bterm []) lnt)), defs).\n\n\n\nSection IndTypeAnyRel.\n  Variable ienv: indEnv.\n  Let translate := translate AnyRel ienv.\n  \nDefinition translateIndMatchBody (numParams:nat) \n  tind v (caseTypArgs : list (V*STerm))(caseTypRet:  STerm) \n  (indTypeParams_R indTypIndices_RR : list Arg) (indTypIndicVars : list V)\n  (constrTypes : list STerm): STerm * list defSq :=\n  let numConstrs : nat := length constrTypes in\n  let lcargs  := mkConstrInfoBeforeGoodness tind numParams translate constrTypes in\n  let seq := (List.seq 0 numConstrs) in\n  let cargsLens : list nat := map IndTrans.argsLen lcargs in\n  let o := (CCase (tind, numParams) cargsLens) None in\n  let lb : list (list bool):= map (boolNthTrue numConstrs) seq in\n  let brsAndDefs :=\n  (map (translateIndInnerMatchBody tind o lcargs v \n          caseTypArgs caseTypRet indTypeParams_R \n            indTypIndices_RR indTypIndicVars) (combine lb lcargs)) in\n  let branches := map fst brsAndDefs in\n  let defs := flat_map snd brsAndDefs in (* _RRs and _RRinvs for constructors *)\n  let lnt : list STerm := [mkLamL caseTypArgs caseTypRet; vterm v]\n      ++branches in\n  (mkApp (oterm o (map (bterm []) lnt)) (map (vterm∘fst) indTypIndices_RR), defs).\n\n\n(*                                 \n  let typesRenamed := map snd l\n      (*let sub := combine origVars (map vterm vars) in\n      map (fun t => ssubst_aux (snd t) sub) l *)in\n  combine vars typesRenamed.\n *)\n(* generalize this to arbitrary n-ary dependent pairs. Because the indices here\nwere dependent on some of the params of the inductive type, we had to cast so that\nthe BestRs compute. \nAlso, disable this in the final true mode where the indices may be in Type\n *)\n\nDefinition translateOneInd_indicesInductive_irrel \n           (indTypArgs_R (* including indices *) indTypeIndices_RR: list (V*STerm))\n           (tindi: (*indices*) inductive) (constName : ident)\n  :  defSq :=\n  \n  let newIndicesRRVars := renameArgs (map fst indTypArgs_R) indTypeIndices_RR in\n(*  let allArgs := indTypArgs_R ++ newIndicesRR in *)\n(*  let allArgsOld := indTypArgs_R ++  indTypeIndices_RR in *)\n  (* inside the matches, lies a beautiful world where the indices coincide *)\n  let retTypCore := mkIndApp tindi (map (vterm ∘ fst) indTypArgs_R) in\n(*  let retTypOuter := mkIndApp tindi (map (vterm ∘ fst) allArgs) in *)\n  let bodyInner := mkApp (mkConstr tindi 0) (map (vterm ∘ fst) indTypArgs_R) in\n  let rwf :=\n      (* vars move from (map fst old) to doneVars as we recurs *)\n      (fix rewriteIndRRs (old: list (V*STerm)) (newVars doneVars: list V)\n          (t : STerm) {struct old}\n       : (STerm (* ret *)\n          * list (V*STerm) (* indTypeIndices_RR with new vars and accordingly substed types *)) :=\n        match old, newVars with\n        | (ov,oldT)::old, nv::newVars =>\n          let eqt: EqType STerm :=\n              {|eqType := oldT; eqLHS := (vterm ov); eqRHS := (vterm nv) |} in\n          let peq := proofIrrelEqProofSq eqt in\n          let newDoneVars := (snoc doneVars ov) in\n          let (recRet, recArgss) :=\n              rewriteIndRRs old newVars newDoneVars t in\n          let recArgssSub := (ALMapRange\n                            (fun t => ssubst_aux t [(ov, vterm nv)])\n                            (recArgss)) in\n          let newArgs :=  (nv,oldT)::recArgssSub in\n          let retType := mkApp retTypCore (map vterm (doneVars++ (map fst newArgs))) in\n          let transportP := mkLam nv oldT (mkPiL recArgssSub retType) in\n          let ret :STerm :=\n              let trRet :=\n              match recArgss with\n              | (vr,TR)::_ =>  (mkLam vr TR recRet)\n(* at the top level, transport, there is no lambda. Inner indices depend on the\nouter indices. so, there types have to be rewritten *)                                \n              | _ => recRet\n              end in\n              mkTransport transportP eqt peq trRet in\n          (ret, newArgs)\n        | _,_ => (t,[])\n        end)  indTypeIndices_RR newIndicesRRVars [] bodyInner in\n  let '(ret ,newIndicesRR) := rwf in\n  {| nameSq := constName;\n     bodySq := mkLamL (indTypArgs_R ++ newIndicesRR)\n                      (* tail, because the first index doesn't depend on previous indices *)\n                      (mkApp ret (map vterm (tail newIndicesRRVars))) |}.\n                  \n   \n(* generalize this to arbitrary n-ary dependent pairs. Because the indices here\nwere dependent on some of the params of the inductive type, we had to cast so that\nthe BestRs compute. *)\nDefinition translateOneInd_indicesInductive \n(indTypArgs_R (* including indices *) indTypeIndices_RR: list Arg)\n(srt: STerm) (tind: inductive)\n  :  list defIndSq\n :=\nlet allArgs := mrs (indTypArgs_R ++ indTypeIndices_RR) in\nlet indType := mkPiL allArgs srt in\nlet paramVars := map fst indTypArgs_R in \n  (* ensure that all of these have non-empty (unique?) names *)\nlet thisIndVar: V  := freshUserVar (freevars indType) \"thisInd\"  in\nlet ctype := mkApp (vterm thisIndVar) \n  ((map vterm paramVars)++ (map (vterm∘fst) indTypeIndices_RR)) (* no args *) in\nlet cbterm := bterm (thisIndVar::paramVars) ctype in\nlet tindiName := (indIndicesTransName tind) in \nlet oneInd : simple_one_ind STerm SBTerm := \n    (tindiName, indType,  [(indIndicesConstrTransName tindiName, cbterm)]) in\nlet indIrrel : defSq :=\n    let tindi := mkInd tindiName 0 in\n    let indIndicesIrrelName := indIndicesIrrelTransName tind in\n    translateOneInd_indicesInductive_irrel\n      (mrs indTypArgs_R)\n      (mrs indTypeIndices_RR)\n      tindi\n      indIndicesIrrelName in\n                    \n[inr (map snd paramVars, [oneInd]); inl indIrrel].\n\n(** tind is a constant denoting the inductive being processed *)\nDefinition translateOneInd (numParams:nat) \n  (tind : inductive*(simple_one_ind STerm STerm)) : ((list Arg) * fixDef True STerm) * list defIndSq :=\n  let (tind,smi) := tind in\n  let (nmT, constrs) := smi in\n  let (_, indTyp) := nmT in\n  let indTyp_R := translate (headPisToLams indTyp) in\n  let (srt, indTypArgs) := getHeadPIs indTyp in\n  let (_, indTypArgs_R) := getNHeadLams (3*length indTypArgs) indTyp_R in\n  let srt_R := \n    match srt with \n    | mkSort s => mkSort (translateSort s) \n    | _ => srt (* should never happen *)\n    end in\n  let indTypeIndices : list Arg := skipn numParams indTypArgs in\n  let numParams_R :nat := (3*numParams)%nat in \n  let indTypeIndices_R : list Arg := skipn numParams_R indTypArgs_R in\n  let indTypeParams_R : list Arg := firstn numParams_R indTypArgs_R in\n  let (indTypeIndices_RR,_) := separate_Rs indTypeIndices_R in\n  let indTypIndicVars : list V := map fst indTypeIndices in\n  let srtMatch := mkPiL (map removeSortInfo indTypeIndices_RR) srt_R in\n  let vars : list V := map fst indTypArgs in\n  let t1 : STerm := (mkIndApp tind (map vterm vars)) in\n  let t2 : STerm := (mkIndApp tind (map (vterm∘vprime) vars)) in\n  (* local section variables could be a problem. Other constants are not a problem*)\n  let v : V := fresh_var vars in\n  let caseTypArgs : list (V*STerm) \n    := (snoc (map removeSortInfo indTypeIndices) (v,t1)) in\n  let constrTypes := (map snd constrs) in\n  let (mb, defs) := translateIndMatchBody numParams tind v caseTypArgs srtMatch \n  indTypeParams_R indTypeIndices_RR\n  indTypIndicVars constrTypes in\n  let fArgs : list (V*STerm) := ((mrs indTypeIndices_R)++[(v,t1); (vprime v, t2)]) in\n  let fbody := mkLamL fArgs mb   in\n  let ftyp: STerm := mkPiL fArgs srt_R in\n  let rarg : nat := length indTypeIndices_R in\n  let indicesInductive :=\n  translateOneInd_indicesInductive indTypArgs_R indTypeIndices_RR srt_R tind in \n  (indTypeParams_R,{|fname := I ; ftype := (ftyp,None); fbody := fbody; structArg:= rarg |}, \n    indicesInductive++ map inl defs).\n\n\nDefinition translateMutInd (id:ident) (t: simple_mutual_ind STerm SBTerm) (i:nat)\n  : STerm * list defIndSq := \n  mutIndToMutFixAux false (translateOneInd) id t i.\n\nEnd IndTypeAnyRel.\n\n\n\n\nDefinition castTerm  (ienv : indEnv) (typ: V*STerm) : STerm  :=\n  let (v,typ) := typ in\n  let typ := headPisToLams typ in\n  let (ret, args) := getHeadLams typ in\n  let typ_R := translate true ienv typ in\n  let (_, args_R) := getNHeadLams (3*(length args)) typ_R in\n  match ret with\n  | mkSort s =>\n    if (negb (isPropOrSet s)) then vterm (vrel v) else\n    let bestrT1 := mkApp (vterm v) (map (vterm ∘ fst) args) in\n    let bestrT2 := tprime bestrT1 in\n    (* this is a bug? vrel needs to be applied ? *)\n    let vrapp := mkApp (vterm (vrel v)) (map (vterm ∘ fst) args_R) in\n    mkLamL (mrs args_R) (projTyRel bestrT1 bestrT2 vrapp)\n  | _ => vterm (vrel v)\n  end.\n\nDefinition transArgWithCast (ienv : indEnv) (nma : Arg) : (list (V * STerm * STerm)):=\n  let (nm,A1s) := nma in\n  let A1 := fst A1s in\n  let A2 := tprime A1 in\n  let nmp := vprime nm in\n  let nmr := vrel nm in\n  let AR := castIfNeeded true A1s  A2 (translate true ienv A1) in\n  [(nm, A1, vterm nm);\n   (nmp, A2, vterm nmp);\n   (nmr, mkAppBeta AR [vterm nm; vterm (vprime nm)], castTerm ienv (removeSortInfo nma))].\n\nDefinition mkIndTransPacket (iso:bool) (ienv: indEnv)\n           (numParams:nat) \n           (tind : inductive*(simple_one_ind STerm STerm)) :\n  IndTrans.IndInfo :=\n  let (tind,smi) := tind in\n  let (nmT, constrs) := smi in\n  let constrTypes := map snd constrs in\n  let (_, indTyp) := nmT in\n  let (retSort, indTypArgs) := getHeadPIs indTyp in\n  let indTyp_R := translate iso ienv (headPisToLams indTyp) in\n  let (retSort_R, indTypArgs_R) := getNHeadLams (3*length indTypArgs) indTyp_R  in\n  let indTypArgs_RM := TranslatedArg.unMerge3way  indTypArgs_R in\n  {|\n     IndTrans.numParams :=  numParams;\n     IndTrans.tind := tind;\n     IndTrans.constrInfo_R :=  mkConstrInfoBeforeGoodness\n                                 tind\n                                 numParams\n                                 (translate iso ienv)\n                                 constrTypes ;\n     IndTrans.indArgs_R := indTypArgs_RM;\n     IndTrans.retSort := retSort;\n     IndTrans.retSort_R := retSort_R;\n     IndTrans.castedArgs_R :=\n      let args := flat_map (transArgWithCast ienv) indTypArgs in\n      map snd args\n  |}.\n\nDefinition extractGoodRelFromApp  (t_RApp (* BestR A1 A2 AR a1 a2 *):STerm):=\n  (* need to return AR *)\n  let (_, args) := flattenApp t_RApp [] in\n  nth 2 args (oterm (CUnknown \"extractGoodRelFromApp\") []).\n\nDefinition goodijNonRec (consName : ident)\n           (typ : TranslatedArg.T Arg) : STerm:=\n  let args := [argType (TranslatedArg.arg typ);\n                 argType (TranslatedArg.argPrime typ);\n                 ((extractGoodRelFromApp ∘ argType) (TranslatedArg.argRel typ))\n              ] in\nmkConstApp consName args.\n\n(* TODO: use [goodijNonRec] from above *)\nDefinition totIJConst (consNames : ident*ident)\n           (typ : TranslatedArg.T Arg) (ti : STerm) : (STerm (*t2*)* STerm (*tr*)):=\n  let (idij, idijr) := consNames in\n  let args := [argType (TranslatedArg.arg typ);\n                 argType (TranslatedArg.argPrime typ);\n                 ((extractGoodRelFromApp ∘ argType) (TranslatedArg.argRel typ)) ;ti\n              ] in\n(mkConstApp idij args, \nmkConstApp idijr args).\n\n\n\n  Definition totConst  (b21 : bool) :=\n    if b21 then\n  (\"ReflParam.Trecord.BestTot21\",  \"ReflParam.Trecord.BestTot21R\")\n      else\n        (\"ReflParam.Trecord.BestTot12\",  \"ReflParam.Trecord.BestTot12R\").\n\nSection IndTypeIsoRel.\n  Variable (b21 : bool).\n(* give [ret: BaseType cIndices],\n   It returns a term of type [BaseType (map (vterm ∘ snd) retArgs)]\n   DoneIndices is initially [], and items shift from the front of [cIndices] \n   to the back of donIndices.\n   The types of RetArgs are OneToOne, which is used to produce the equality proofs.\n   The type of later indices may depend on the former indices. Therefore,\n   these rewrites have to be carefully threaded\n*)\nFixpoint mkOneOneRewrites (oneConst:ident) (retArgs : list (V*STerm*V))\n         (doneIndices : list STerm)\n         (cIndices : list (STerm (* js *) * STerm (* rels *)))\n         (baseType ret: STerm) {struct retArgs} : STerm :=\n  match (retArgs, cIndices) with\n  | (hi::retArgs, (hcp,hcr)::cIndices) =>\n    let (hi, vPrimehi) := hi in\n    let (vRhi , Thi) := hi in\n    let (_ (* BestR *), ThiArgs (* 5 items *)) := flattenApp Thi [] in\n    let peq := mkConstApp oneConst (ThiArgs++[hcp; vterm vRhi; hcr]) in\n    let transportType :=\n        let tindex : nat := (if b21 then 0 else 1)%nat in \n        nth tindex ThiArgs (oterm (CUnknown \"mkOneOneRewrites\") []) in\n    let eqT := {| eqType := transportType;  eqLHS := hcp;  eqRHS := vterm vPrimehi |} in\n    let rep1 := replaceOccurrences hcp (vterm vPrimehi) in\n    let rep2 := replaceOccurrences hcr (vterm vRhi) in\n    let cIndices := map (fun p => ((rep1 ∘ fst) p, (rep1 ∘ rep2 ∘ snd) p)) cIndices in\n    let transportP :=\n        let base := mkAppBetaUnsafe baseType (doneIndices++[vterm vPrimehi]++(map fst cIndices)) in\n        mkLam vPrimehi transportType base in\n    let rw := mkTransport transportP eqT peq ret in\n    mkOneOneRewrites oneConst retArgs\n                     (snoc doneIndices (vterm vPrimehi))\n                     cIndices baseType rw\n  | _ => ret\n  end.\n\nLet maybeSwap {A:Set} (p:A*A) := (if b21 then (snd p, fst p) else p).\n  Let targi {A}  := if b21 then @TranslatedArg.argPrime A else @TranslatedArg.arg A.\n  Let targj {A}  := if b21 then @TranslatedArg.arg A else @TranslatedArg.argPrime A.\n  Definition oneOneConst := if b21 then \"ReflParam.Trecord.BestOne21\"\n                     else \"ReflParam.Trecord.BestOne12\".\n\n  Definition oneOneConstijjo := if b21 then \"ReflParam.Trecord.BestOneijjo21\"\n                     else \"ReflParam.Trecord.BestOneijjo\".\n\n  Definition totalPiConst := if b21 then totalPiHalfGood21_ref else totalPiHalfGood_ref.\n  Definition oneOnePiConst := if b21 then oneOnePiHalfGood21_ref else oneOnePiHalfGood_ref.\n\n  Definition mkTotalPiHalfGood (A1 A2 AR B1 B2 BR BtotHalf: STerm) :=\n    mkConstApp totalPiConst [A1;A2;AR;B1;B2;BR;BtotHalf].\n\n  Definition mkOneOnePiHalfGood (A1 A2 AR B1 B2 BR BtotHalf: STerm) :=\n    mkConstApp oneOnePiConst [A1;A2;AR;B1;B2;BR;BtotHalf].\n\n  Definition totij (typ : TranslatedArg.T Arg) (ti : STerm) : (STerm (*tj*)* STerm (*tr*)):=\n    totIJConst (totConst b21) typ ti.\n\n  Definition totji (typ : TranslatedArg.T Arg) (ti : STerm) : (STerm (*tj*)* STerm (*tr*)):=\n    totIJConst (totConst (negb b21)) typ ti.\n\n  Variable ienv: indEnv.\n  Let translate := translate IsoRel ienv.\n\n  \n  Definition recursiveArgIff (p:TranslatedArg.T Arg) (numPiArgs:nat) t :=\n      let procLamArgOfArg (p:TranslatedArg.T Arg) (t:STerm): STerm:=\n        let (T1InAux,T2InAux, TRIn) := p in\n        let (TIni, TInj) := maybeSwap (T1InAux,T2InAux) in\n        let tji := totji p (vterm (argVar TInj)) in\n        mkLetIn (argVar TIni) (fst tji) (argType TIni)\n          (mkLetIn (argVar TRIn) (snd tji)  (* typ to t1 *)\n              (argType TRIn) t) in\n      let (T11,T22,_) := p in\n      let (Ti, Tj) := maybeSwap (T11, T22) in\n      let T1lR := (translate(*f*) (headPisToLams (argType T11))) in\n      let (ret_R, lamArgs_R) := getNHeadLams (3*numPiArgs) T1lR in\n      let lamArgs_R := TranslatedArg.unMerge3way lamArgs_R in\n      let recCall : STerm := flattenHeadApp ret_R in (* not needed? *)\n      let (vi,vj) := (argVar Ti,argVar Tj) in\n      let fi : STerm := vterm vi in\n      let recArg : STerm := mkApp fi (map (vterm∘fst∘targi) lamArgs_R) in\n      let recRet := (mkApp recCall [recArg]) in\n      let retIn := List.fold_right procLamArgOfArg recRet lamArgs_R in\n      let retIn := mkLamL (map (removeSortInfo ∘ targj) lamArgs_R) retIn in\n      mkLetIn vj retIn (argType Tj) t.\n(* (vrel v) is not needed. indices of a constr cannot mention rec args.\nonenote:https://d.docs.live.net/946e75b47b19a3b5/Documents/Postdoc/parametricity/papers/logic/isorel.one#indices%20of%20a%20constr%20cannot%20mention%20rec%20args&section-id={6FC701EE-23A1-4695-AC21-2E6CBE61463B}&page-id={A96060FB-9EFC-4F21-8C1C-44E1B3385424}&end\n*)\n\n  \n  (* returns 1) the correct translation relation for the Pi Type. Note that just\n  [argType] is not the correct relation, because it uses _iso, which is rebound here to\n  something else (iso hasn't been even fully generated yet). Also, params need to be casted\n  as this function does in the base case.\n  2) the half totality proof. *)\n  Fixpoint recursiveArgPiCombinator\n           (gPiCombinator : STerm -> STerm -> STerm -> STerm -> STerm -> STerm -> STerm -> STerm)\n           (castedParams_R : list STerm) (argType1: STerm)  : (STerm*STerm):=\n    match argType1 with\n    | mkPiS nm A Sa B _ =>\n      let A2 := (tprime A) in\n      let AR := (translate A) in \n      let brtot := gPiCombinator A A2 AR in\n      let Bl1 := (mkLam nm A B) in\n      let Bl2 := (tprime Bl1) in\n      let brtot := brtot Bl1 Bl2  in\n      let (recbr, recbrtot) := recursiveArgPiCombinator gPiCombinator\n                                                  castedParams_R B in\n      let lrecbr := transLam true translate (nm,(A,Sa)) recbr in\n      let lrecbrtot := transLam true translate (nm,(A,Sa)) recbrtot in \n      let brtot := brtot lrecbr lrecbrtot in\n        (mkRPiS A A2 (castIfNeeded true (A,Sa) A2 AR) Bl1 Bl2 lrecbr, brtot)\n    | _ =>\n      (* cast is removed because this is a recursive arg of the constructor *)\n      let argType_Rtot := translate argType1 in (* argType translate the current inductive to the \n_iso name , which will be replaced with the fixpoint var binding this fixpoint. \nWe want this for brtothalf but not BR *)\n      let argType_R :=\n          let tind_RR (* not the iso version *) :=\n              let (indt, args) := flattenApp argType1 [] in\n              let tind := extractInd indt in\n              indTransName tind in (* we will use this name instead of the _iso version *)\n          (* Also, we use  castedParams_R, because (indTransName tind) is the core (non-good) version *)\n          let (_, args_R) := flattenApp  argType_Rtot [] in\n          let args_R := skipn (length castedParams_R) args_R in\n          mkConstApp tind_RR (castedParams_R++args_R) in\n      ( argType_R, argType_Rtot)\n    end.\n\n  Definition recursiveArgTot (castedParams_R : list STerm) (p:TranslatedArg.T Arg)\n             (t: STerm) :=\n      let (T11,T22,TR) := p in\n      let (Ti,Tj) := maybeSwap (T11, T22) in\n       let (vi,vj) := (argVar Ti, argVar Tj) in\n      let fi: STerm := vterm vi in\n      let vr :V := (argVar TR) in\n      let (TR,pitot) := (recursiveArgPiCombinator mkTotalPiHalfGood\n                                            castedParams_R (argType T11)) in\n      let fjr: STerm := (mkApp pitot [fi]) in\n      let fjType: STerm := argType Tj in\n      let trApp: STerm := (mkApp TR (map (vterm ∘ argVar)[T11;T22])) in\n      let fjrType: STerm :=\n          mkSig (argVar Tj) (argType Tj) trApp in\n      let frType : STerm :=\n          mkLam (argVar Tj) (argType Tj) trApp in\n      let body: STerm :=\n          mkLetIn vr\n                  (mkConstApp projT2_ref [fjType; frType; vterm vr])\n                  trApp t in\n      let body: STerm :=\n          mkLetIn (argVar Tj)\n                  (mkConstApp projT1_ref [fjType; frType; vterm vr])\n                  (argType Tj) body in\n      mkLetIn vr fjr fjrType body.\n\n  Definition cretIndicesij  ( cinfo_RR : IndTrans.ConstructorInfo) :=\n      maybeSwap (IndTrans.indices cinfo_RR, IndTrans.indicesPrimes cinfo_RR).\n\n  Definition indIndicesij  (indPacket : IndTrans.IndInfo) :=\n  let indIndices := IndTrans.indIndices_R indPacket in\n      maybeSwap (mrs (map TranslatedArg.arg indIndices),\n                 mrs (map TranslatedArg.argPrime indIndices)).\n\n  Definition translateOnePropBranch  (iffOnly:bool (* false => total*))\n             (* v : the main (last) input to totality *)\n             (ind : inductive) (totalTj: STerm) (vi vj :V) (params: list Arg)\n             (castedParams_R : list STerm)\n           (indIndicess indPrimeIndicess indRelIndices : list (V*STerm))\n           (indAppParamsj: STerm)\n  (cinfo_RR : IndTrans.ConstructorInfo): STerm := \n  let constrIndex :=  IndTrans.index cinfo_RR in\n  let constrArgs_R := IndTrans.args_R cinfo_RR in\n  let procArg  (p: TranslatedArg.T Arg) (t:STerm): STerm:=\n    let (T11, T22,TR) := p in\n    let (Ti, Tj) := maybeSwap (T11, T22) in  \n    let isRec :=  (isConstrArgRecursive ind (argType Ti)) in\n    if isRec\n    then\n      (if iffOnly\n       then recursiveArgIff p (numPiArgs (argType Ti)) t\n       else recursiveArgTot castedParams_R p t)\n    else\n      mkLetIn (argVar Tj) (fst (totij p (vterm (argVar Ti)))) (argType Tj)\n        (mkLetIn (argVar TR) (snd (totij p (vterm (argVar Ti)))) \n                 (argType TR) t) in\n  (* todo : use IndTrans.thisConstr *)\n  let c11 := mkApp (mkConstr ind constrIndex) (map (vterm∘fst) params) in\n  let c11 := mkApp c11 (map (vterm∘fst∘TranslatedArg.arg) constrArgs_R) in\n  let c22 := tprime c11 in\n  let (ci, cj) := maybeSwap (c11, c22) in\n  let (indicesIndi, indicesIndj) := maybeSwap (indIndicess,indPrimeIndicess) in\n  let (cretIndicesi, cretIndicesj) :=\n      maybeSwap (IndTrans.indices cinfo_RR, IndTrans.indicesPrimes cinfo_RR) in\n  let thisBranchSubi :=\n      (* specialize the return type to the indices. later even the constructor is substed*)\n      (combine (map fst indicesIndi) cretIndicesi) in\n  let indRelIndices : list (V*STerm) :=\n      ALMapRange (fun t => ssubst_aux t thisBranchSubi) indRelIndices in\n  (* after rewriting with oneOnes, the indicesPrimes become (map tprime cretIndices)*)\n  let thisBranchSubj :=  (combine (map fst indicesIndj) cretIndicesj) in\n  let indRelArgsAfterRws : list (V*STerm) :=\n      ALMapRange (fun t => ssubst_aux t thisBranchSubj) indRelIndices in\n  let (c2MaybeTot, c2MaybeTotBaseType) :=\n      if iffOnly\n      then (cj,indAppParamsj)\n      else\n        let thisBranchSubFull := snoc thisBranchSubi (vi, ci) in\n        let retTRR := ssubst_aux totalTj (thisBranchSubFull) in\n        let retTRRLam := mkLamL indicesIndj (mkPiL indRelIndices retTRR)  in\n        let crr :=\n            mkConstApp (constrTransTotName ind constrIndex)\n                       (castedParams_R\n                          ++(map (vterm ∘ fst)\n                                 (TranslatedArg.merge3way constrArgs_R))\n                          ++ (map (vterm ∘ fst) indRelIndices)) in\n        (mkLamL\n           indRelArgsAfterRws\n           (sigTToExistT2 [cj] crr (ssubst_aux retTRR thisBranchSubj))\n         ,retTRRLam) in\n  (* do the rewriting with OneOne *)\n  let c2rw :=\n      let cretIndicesJRRs := combine cretIndicesj\n                                    (IndTrans.indicesRR cinfo_RR) in\n      mkOneOneRewrites oneOneConst\n                       (combine indRelIndices (map fst indicesIndj))\n                       []\n                       cretIndicesJRRs\n                       c2MaybeTotBaseType\n                       c2MaybeTot in\n  let c2rw := if iffOnly then c2rw else mkApp (c2rw) (map (vterm ∘ fst) indRelIndices) in\n  let ret := List.fold_right procArg c2rw constrArgs_R in\n  mkLamL ((map (removeSortInfo ∘ targi) constrArgs_R)\n            ++(indicesIndj++ indRelIndices)) ret.\n\n  \n  (* TODO: use mkIndTranspacket to cut down the boilerplate *)\n(** tind is a constant denoting the inductive being processed *)\nDefinition translateOnePropTotal (iffOnly:bool (* false => total*))\n           (numParams:nat)\n           (tind : inductive*(simple_one_ind STerm STerm)) : (list Arg) * fixDef True STerm :=\n  let (tind,smi) := tind in\n  let (nmT, constrs) := smi in\n  let constrTypes := map snd constrs in\n  let (_, indTyp) := nmT in\n  let (_, indTypArgs) := getHeadPIs indTyp in\n  let indTyp_R := translate(*f*) (headPisToLams indTyp) in\n  let (_, indTypArgs_R) := getNHeadLams (3*length indTypArgs) indTyp_R  in\n  let indTypArgs_RM := TranslatedArg.unMerge3way  indTypArgs_R in\n  let indTypeParams : list Arg := firstn numParams indTypArgs in\n  let indTypeIndices : list (V*STerm) := mrs (skipn numParams indTypArgs) in\n  let indTypeParams_R : list Arg := firstn (3*numParams) indTypArgs_R in\n  let indTypeIndices_R : list Arg := skipn (3*numParams) indTypArgs_R in\n  let vars : list V := map fst indTypArgs in\n  let indAppParamsj : STerm :=\n      let indAppParams : STerm := (mkIndApp tind (map (vterm ∘ fst) indTypeParams)) in\n      if b21 then indAppParams else tprime indAppParams in\n  let (Ti, Tj) :=\n        let T1 : STerm := (mkIndApp tind (map vterm vars)) in\n        let T2 : STerm := tprime T1 in maybeSwap (T1,T2) in\n  let vv : V := freshUserVar vars \"tind\" in\n  let (vi,vj) := maybeSwap (vv, vprime vv) in\n  let (totalTj, castedParams_R)   :=\n      let args := flat_map (transArgWithCast ienv) indTypArgs in\n      let args := map snd args in\n      (mkSig vj Tj (mkConstApp (indTransName tind)\n                         (args++[vterm vv; vterm (vprime vv)]))\n       , firstn (3*numParams) args)  in\n  let retTyp : STerm :=\n      if iffOnly then Tj else totalTj in\n  let indTypeIndices_RM := skipn  numParams  indTypArgs_RM in\n  (* why are we splitting the indicesPrimes and indices_RR? *)\n  let indPrimeIndices :=  map (removeSortInfo ∘ TranslatedArg.argPrime) indTypeIndices_RM in\n  let indRelIndices :=  map (removeSortInfo ∘ TranslatedArg.argRel) indTypeIndices_RM in\n  let (caseArgsi, caseArgsj) := maybeSwap (indTypeIndices, indPrimeIndices) in\n  let caseRetAllArgs :=  (caseArgsj++indRelIndices) in\n  let caseRetTyp := mkPiL caseRetAllArgs  retTyp in\n  let caseTyp := mkLamL (snoc caseArgsi (vi,Ti)) caseRetTyp in\n  let cinfo_R := mkConstrInfoBeforeGoodness tind numParams translate constrTypes in \n  let o :=\n      let cargsLens : list nat := (map IndTrans.argsLen  cinfo_R) in\n      (CCase (tind, numParams) cargsLens) None in\n  let matcht :=\n      let lnt : list STerm := [caseTyp; vterm vi]\n                                ++(map (translateOnePropBranch\n                                          iffOnly\n                                          tind\n                                          totalTj\n                                          vi\n                                          vj\n                                          indTypeParams\n                                          castedParams_R\n                                          indTypeIndices\n                                          indPrimeIndices\n                                          indRelIndices\n                                          indAppParamsj)\n                                   cinfo_R) in\n      oterm o (map (bterm []) lnt) in\n  let matchBody : STerm :=\n      mkApp matcht (map (vterm ∘ fst)  (caseArgsj++indRelIndices)) in\n  (* todo, do mkLamL indTypArgs_R just like transOneInd *)\n  let fixArgs :=  ((mrs (indTypeIndices_R))) in\n  let allFixArgs :=  (snoc fixArgs (vi,Ti)) in\n  let fbody : STerm := mkLamL allFixArgs (matchBody) in\n  let ftyp: STerm := mkPiL allFixArgs retTyp in\n  let rarg : nat := ((length fixArgs))%nat in\n  (indTypeParams_R, {|fname := I; ftype := (ftyp, None); fbody := fbody; structArg:= rarg |}).\n\n\n      \n(** OneToOne hood *)\n\n(** We need 2 vars of the J and RR classes. These are obtained\nby adding a large enough number, and appending \"o\".\nThis operation is done after doing vprime/vrel if neccessary  *)\nDefinition extraVar (add :N) (v:V):=\n  (add+fst v, nAppend \"o\" (snd v)).\n\n\n(* The last item is guaranteed to be a var. So, only the sigt applies will be \nrecursed over *)\nFixpoint sigTToInjPair2 (existTL existTR : STerm) (exEq:V)\n  {struct existTL} : STerm :=\nmatch existTL, existTR  with\n| (oterm (CApply _) lbt1), (oterm (CApply _) lbt2)  =>\n  match lbt1, lbt2 with\n  (_::A::B::x::p1::[]), (_::_::_::_::p2::[])=>\n  let A:= get_nt A in  \n  let B:= get_nt B in  \n  let x:= get_nt x in  \n  let p1:= get_nt p1 in  \n  let p2:= get_nt p2 in  \n  let eqproj2 :=  mkConstApp injpair2_ref  [A; B; x; p1; p2; (vterm exEq)] in\n  let letType :=\n      let eqt : EqType STerm :=\n          {|\n            eqType := mkApp B [x];\n            eqLHS := p1;\n            eqRHS := p2\n          |} in\n      getEqTypeSq eqt in\n  mkLetIn exEq eqproj2 letType (sigTToInjPair2 p1 p2 exEq)\n  | _,_ => vterm exEq\n  end\n| _,_ => vterm exEq\nend.\n\n\nDefinition argsVarf (f:V->V) (args: list (V*STerm)) :\n  (list (V*STerm)) * (list (V*V)) :=\n  let argsf := ALMapDom f args in\n  let sub := combine (map fst args) (map fst argsf) in\n  (ALMapRange (ssubst_auxv sub) argsf , sub).\n\n(*\nFixpoint letBindProj1s (l: list (V*STerm)) (v:V) (t:STerm) {struct l} : STerm :=\n*)\nDefinition oneOneConstrArgCombinator\n           (indPacket : IndTrans.IndInfo) (carg : TranslatedArg.T Arg) :\n  (V*STerm (*Type_R*) * STerm (*OneOne combinator *)):=\n    let (T1, T2,TR) := carg in\n    let isRec :=  (isConstrArgRecursive (IndTrans.tind indPacket) (argType T1)) in\n    if isRec\n    then\n      let (TRCorrect, TOneOneComb) :=\n          recursiveArgPiCombinator\n            mkOneOnePiHalfGood\n            (IndTrans.castedParams_R indPacket)\n            (argType T1) in\n      (fst TR, mkApp TRCorrect [vterm (argVar T1); vterm (argVar T2)] , TOneOneComb)\n    else\n      (removeSortInfo TR, goodijNonRec oneOneConstijjo carg).\n  \n\nFixpoint oneBranch3Rewrites (oneCombinators : list STerm)\n         (cargsRRo cargsjo: list (V*STerm)) (* types keep changing *)\n         (revSubj revSubRR : list V)  (* remains constant *)\n         (retTypeBase (* keeps changing during recursion *): STerm)\n         (lcargvi : list V) (* remains constant *)\n         (eqReflBaseCase : STerm) (* remains constant *)\n  : STerm  :=\n  match oneCombinators, cargsRRo, cargsjo, revSubj, revSubRR, lcargvi with\n  | oneComb::oneCombinators, cr::cargsRR, cargjo::cargsjo, vj::revSubj,\n    vrr::revSubRR, vi::lcargvi =>\n    let vjo := fst cargjo in\n    let vrro := fst cr in\n    let outerRW (t: STerm) : STerm :=\n      let eqT :=\n        {|\n          eqType := snd cargjo;\n          eqLHS := vterm vj;\n          eqRHS := vterm vjo\n        |} in\n      let peq := mkApp oneComb [vterm vi; vterm vj; vterm vjo; vterm vrr; vterm vrro] in\n        (* we need to change the type of cr. so we convoy it *)\n      let transportP := (mkPiL (cr::(merge cargsjo cargsRR)) retTypeBase) in\n      mkLamL [cargjo;cr]\n             (mkApp (mkTransportV vjo transportP eqT peq t) [vterm (fst cr)]) in\n    let subj := [(vjo,vj)] in\n    let cr := pairMapr (ssubst_auxv subj) cr in\n    let cargsRR := ALMapRange (ssubst_auxv subj) cargsRR in\n    let cargsjo := ALMapRange (ssubst_auxv subj) cargsjo in\n    let retTypeBase := ssubst_auxv subj retTypeBase in\n    let innerRW (t:STerm): STerm :=\n      let eqT :=\n        {|\n          eqType := snd cr;\n          eqLHS := vterm vrr;\n          eqRHS := vterm vrro \n        |} in\n      let peq := proofIrrelEqProofSq eqT in\n      let transportP := (mkPiL (merge cargsjo cargsRR) retTypeBase) in\n        (* we need to change the type of cr. so we convoy it *)\n      mkLamL [cr] (mkTransportV vrro transportP eqT peq t) in\n    let recCall : STerm :=\n      let cargsRR := ALMapRange (ssubst_auxv [(vrro,vrr)]) cargsRR in\n      oneBranch3Rewrites\n        oneCombinators\n        cargsRR\n        cargsjo\n        revSubj\n        revSubRR\n        retTypeBase\n        lcargvi\n        eqReflBaseCase in\n    outerRW (innerRW recCall)\n  | _,_,_,_,_,_ => eqReflBaseCase\n  end.\n                                            \n  \nDefinition translateOneBranch3 (o : CoqOpid (*to avoid recomputing*))\n           (indPacket : IndTrans.IndInfo) (vhexeq : V) (maxbv :N)\n           (vtti vttj vttjo tindAppR tindAppRo : (V*STerm))\n           ((*retTyp*) retTypFull: STerm)\n           (indIndicesi indIndicesj indIndicesRel : list (V*STerm))\n           (*cretIndicesi cretIndicesj (* cretIndicesj for outerConstrIndex*) : list STerm *)\n           (outerConstrIndex : nat) (* use False_rect for all other constructors*)\n           (cargCombinators : list  (V*STerm (*Type_R*) * STerm (*OneOne combinator *)))\n           (constrInv eqReflBaseCase: STerm)\n           (cinfo_R : IndTrans.ConstructorInfo): STerm := \n  let (_, cretIndicesj) := cretIndicesij cinfo_R in\n  let lamcjArgs := (map (removeSortInfo ∘ targj) (IndTrans.args_R cinfo_R)) in\n  let (lamcjoArgs,varjosub)  := argsVarf (extraVar maxbv) lamcjArgs in\n  let cretIndicesj : list STerm := map (ssubst_auxv varjosub) cretIndicesj in\n  let c11 := IndTrans.thisConstructor indPacket cinfo_R in\n  let (_,cj) := maybeSwap (c11, tprime c11) in (* make a maybeprime? *)\n  let cj := ssubst_auxv varjosub cj in\n  let thisBranchSubjFull :=\n      snoc (combine (map fst indIndicesj) cretIndicesj) (fst vttjo, cj) in\n  let subFullF :=  (fun t => ssubst_aux t thisBranchSubjFull) in\n  let (cargsRR, oneCombinators) := split cargCombinators in\n  let '(cargsRRo,cargsRRoSub)  := argsVarf (extraVar maxbv) cargsRR in\n  let cargsRRo := ALMapRange (ssubst_auxv varjosub) cargsRRo in\n  let tindAppRo := pairMapr subFullF tindAppRo in\n  let retTypFull := ssubst_aux retTypFull thisBranchSubjFull  in\n  let (retTypBody,retTypArgs) := getHeadPIs retTypFull in\n  let lamAllArgs :=\n      lamcjoArgs++ (mrs retTypArgs) in\n  let ret := if (decide (outerConstrIndex = (IndTrans.index cinfo_R)))\n    then\n      let constrInvf :=\n        let indIndicesRelS := ALMapRange subFullF indIndicesRel in\n        let lamIArgs :=  (snoc indIndicesRelS tindAppRo) in\n        let constrInvRetType :=\n            mkLamL lamIArgs (*vacuous bindings*) retTypBody in\n        let constrInv := ssubst_auxv varjosub constrInv in\n        (* RRs remain the same when switching direction*)\n        let body := oneBranch3Rewrites\n                      oneCombinators\n                      cargsRRo\n                      lamcjoArgs\n                      (map fst varjosub)\n                      (map fst cargsRRoSub)\n                      retTypBody\n                      (map (fst ∘ targi) (IndTrans.args_R cinfo_R))\n                      eqReflBaseCase in\n        let body := mkLamL cargsRRo\n                           (mkApp body (merge\n                                          (map (vterm ∘ fst) lamcjoArgs)\n                                          (map (vterm ∘ fst) cargsRRo))) in\n        mkApp constrInv\n              ((map (vterm ∘ fst) lamIArgs)\n                 ++[constrInvRetType;body])\n              in constrInvf\n    else\n      falseRectSq retTypBody (vterm (fst tindAppRo)) in\n  mkLamL lamAllArgs ret.\n  \n\n\nDefinition translateOneBranch2 (o : CoqOpid (*to avoid recomputing*))\n           (indPacket : IndTrans.IndInfo) (vhexeq : V) (maxbv :N)\n           (vtti vttj vttjo tindAppR tindAppRo : (V*STerm))\n           ((*retTyp*) retTypFull: STerm)\n           (indIndicesi indIndicesj indIndicesRel : list (V*STerm))\n           (*cretIndicesi cretIndicesj (* cretIndicesj for outerConstrIndex*) : list STerm *)\n           (outerConstrIndex : nat) (* use False_rect for all other constructors*)\n           (cinfo_R : IndTrans.ConstructorInfo): STerm :=\n  let (_, cretIndicesj) := cretIndicesij cinfo_R in\n  let c11 := IndTrans.thisConstructor indPacket cinfo_R in\n  let (_,cj) := maybeSwap (c11, tprime c11) in (* make a maybeprime? *)\n  let thisBranchSubjFull :=\n      snoc (combine (map fst indIndicesj) cretIndicesj) (fst vttj, cj) in\n  let subFullF :=  (fun t => ssubst_aux t thisBranchSubjFull) in\n  let retTypFull := ssubst_aux retTypFull thisBranchSubjFull  in\n  let tindAppR := pairMapr subFullF tindAppR in\n  let (retTypBody,retTypArgs) := getHeadPIs retTypFull in\n  let lamAllArgs :=\n      let lamcjArgs := (map (removeSortInfo ∘ targj) (IndTrans.args_R cinfo_R)) in\n      lamcjArgs++ (mrs retTypArgs) in\n  let ret := if (decide (outerConstrIndex = (IndTrans.index cinfo_R)))\n  then\n    let sigjType : STerm :=\n        let sigType := IndTrans.sigIndApp indPacket in\n        if b21 then sigType else tprime sigType in\n    let eqT : EqType STerm := {|\n          eqType := sigjType;\n          eqLHS := sigTToExistT2 cretIndicesj cj sigjType;\n          eqRHS := sigTToExistT2 cretIndicesj (vterm (fst vttjo)) sigjType\n        |} in\n    let eqt :STerm := getEqTypeSq eqT in\n    let injPair2:= sigTToInjPair2 (eqLHS eqT) (eqRHS eqT) vhexeq  in\n    let caseRetPiArgs :=  (snoc indIndicesRel tindAppRo) in\n    let cargCombinators :=\n         map (oneOneConstrArgCombinator indPacket) (IndTrans.args_R cinfo_R) in\n    let constrInv :=  IndTrans.constrInvApp indPacket cinfo_R in\n    let match3 :=\n        let eqTG : EqType STerm := {|\n              eqType := eqType eqT;\n              eqLHS := eqLHS eqT;\n              eqRHS := (sigTToExistT (vterm (fst vttjo)) sigjType)\n            |} in\n        let eqReflBase:= getEqRefl eqTG in\n        let lamArgs := snoc indIndicesj vttjo in\n        let retTypFull := (mkPiL caseRetPiArgs (getEqTypeSq eqTG)) in\n        let caseRetTyp := mkLamL lamArgs retTypFull  in\n        let lnt3 := map (translateOneBranch3 o\n                         indPacket\n                         vhexeq\n                         maxbv\n                         vtti\n                         vttj\n                         vttjo\n                         tindAppR\n                         tindAppRo\n                         retTypFull\n                         indIndicesi\n                         indIndicesj\n                         indIndicesRel\n                         (IndTrans.index cinfo_R)\n                         cargCombinators\n                         constrInv\n                         eqReflBase\n                        )\n                 (IndTrans.constrInfo_R indPacket) in\n        oterm o (map (bterm []) ([caseRetTyp; vterm (fst vttjo)]++lnt3)) in\n    let match3App := (mkApp match3 (map (vterm ∘ fst) caseRetPiArgs)) in\n    let constrInvf :=\n        let indIndicesRelS := ALMapRange subFullF indIndicesRel in\n        let lamIArgs :=  (snoc indIndicesRelS tindAppR) in\n        let constrInvRetType :=\n            mkLamL lamIArgs (*vacuous bindings*) eqt in\n        (* RRs remain the same when switching direction*)\n        let cargsRR := (map fst cargCombinators)  in\n        mkApp constrInv\n              ((map (vterm ∘ fst) lamIArgs)\n                 ++[constrInvRetType;mkLamL cargsRR match3App]) in\n    mkLetIn vhexeq constrInvf eqt injPair2\n  else\n    falseRectSq retTypBody (vterm (fst tindAppR)) in\n  mkLamL lamAllArgs ret.\n                 \n                                                    \nDefinition translateOneBranch1 (o : CoqOpid (*to avoid recomputing*))\n           (indPacket : IndTrans.IndInfo) (vhexeq : V) (maxbv :N)\n           (vtti vttj vttjo tindAppR tindAppRo : (V*STerm))\n           (retTypFull: STerm)\n           (indIndicesi indIndicesj indIndicesRel: list (V*STerm))\n           (cinfo_R : IndTrans.ConstructorInfo): STerm :=\n  let (cretIndicesi, _) := cretIndicesij cinfo_R in\n  let c11 := IndTrans.thisConstructor indPacket cinfo_R in\n  let (ci,_) := maybeSwap (c11, tprime c11) in\n  let thisBranchSubiFull :=\n      snoc (combine (map fst indIndicesi) cretIndicesi) (fst vtti, ci) in\n  let retTypFull := mkPiL [vttjo] retTypFull  in \n  let retTypFull := ssubst_aux retTypFull thisBranchSubiFull  in \n  let indIndicesRel := ALMapRange (fun t => ssubst_aux t thisBranchSubiFull) indIndicesRel  in \n  let tindAppR := pairMapr (fun t => ssubst_aux t thisBranchSubiFull) tindAppR  in \n  let tindAppRo := pairMapr (fun t => ssubst_aux t thisBranchSubiFull) tindAppRo  in \n  (* TODO : substitute in tindAppR tindAppRo. there, even the constructor needs to be substed*)\n  let matcht2 :=\n      let lamArgs := snoc indIndicesj vttj in\n      let retTypM2 := mkLamL lamArgs retTypFull in \n      let lnt2 := map (translateOneBranch2\n                         o\n                         indPacket\n                         vhexeq\n                         maxbv\n                         vtti\n                         vttj\n                         vttjo\n                         tindAppR\n                         tindAppRo\n                         retTypFull\n                         indIndicesi\n                         indIndicesj\n                         indIndicesRel\n                         (IndTrans.index cinfo_R))\n                 (IndTrans.constrInfo_R indPacket) in\n      oterm o (map (bterm []) ([retTypM2; vterm (fst vttj)]++lnt2)) in \n  mkLamL (map (removeSortInfo ∘ targi)\n              (IndTrans.args_R cinfo_R)) (mkApp matcht2 [vterm (fst vttjo)]).\n  \n\nDefinition translateIndOne2One\n           (numParams:nat)\n           (tind : inductive*(simple_one_ind STerm STerm)) : (list Arg) * fixDef True STerm :=\n  let indPacket : IndTrans.IndInfo\n      := mkIndTransPacket true ienv numParams tind in\n  let lv : list V := freshUserVars (IndTrans.indBVars indPacket) [\"tind\"; \"Hexeq\"; \"n\"] in\n  let vt : V := nth 0 lv dummyVar in\n  let vhexeq : V := nth 1 lv dummyVar in\n  let maxbv :N :=\n      let vn : V := nth 2 lv dummyVar in\n      (* the larger of these vars dont clash with anything. So adding\n        this to anything (0 in the worst case) will give us something that \n        is disjoint from all bvars in the inductive.*)\n      Nmax (Nmax (fst vt) (fst vn)) (fst vhexeq) in\n  let vtt : (V*STerm):= (vt, IndTrans.indApp indPacket) in\n  let vtt2 : (V*STerm) := primeArgsOld vtt in\n  let vtr :V := vrel vt in\n  let (vtti, vttj) := maybeSwap (vtt, vtt2) in\n  let vttjo : (V*STerm) := pairMapl (extraVar maxbv) vttj in\n  let tindApp : STerm := IndTrans.indAppR indPacket in\n  let tindAppR : (V*STerm) := (vtr, mkApp tindApp (map (vterm ∘ fst) [vtt; vtt2])) in\n  let tindAppRo : (V*STerm) :=\n      let vars : list (V*STerm) := if b21 then [vttjo; vtt2] else [vtt; vttjo] in\n      (extraVar maxbv vtr,\n       mkApp tindApp (map (vterm ∘ fst) vars)) in\n  let extraArgs : list (V*STerm):= [vtti;vttj;vttjo;tindAppR;tindAppRo] in \n  let fixArgs :=  mrs (TranslatedArg.merge3way (IndTrans.indIndices_R indPacket)) in\n  let allFixArgs :=  fixArgs ++ extraArgs  in\n  let retTyp :=\n      let eqt : EqType STerm :=\n          {|eqType := snd vttj; eqLHS := vterm (fst vttj); eqRHS := vterm (fst vttjo) |} in\n      getEqTypeSq eqt in\n  let o : CoqOpid:= IndTrans.matchOpid indPacket in\n  let indIndices := IndTrans.indIndices_R indPacket in\n  let (indIndicesi, indIndicesj) := indIndicesij indPacket in\n  let indIndicesRel := (map (removeSortInfo ∘ TranslatedArg.argRel) indIndices) in\n  let piArgs := indIndicesRel++[tindAppR;tindAppRo]  in\n  let retTypFull := mkPiL piArgs retTyp in\n  let match1 :=\n      let lamArgs := snoc indIndicesi vtti in\n      let retTypeM1 := mkLamL lamArgs retTypFull  in\n      let lnt := map (translateOneBranch1\n                        o\n                        indPacket\n                        vhexeq\n                        maxbv\n                        vtti\n                        vttj\n                        vttjo\n                        tindAppR\n                        tindAppRo\n                        retTypFull\n                        indIndicesi\n                        indIndicesj\n                        indIndicesRel\n                     )\n                 (IndTrans.constrInfo_R indPacket) in\n      oterm o (map (bterm []) ([retTypeM1; vterm (fst vtti)]++lnt) ) in \n  let fbody : STerm := mkLamL allFixArgs (mkApp match1 (map (vterm ∘ fst) piArgs)) in\n  let ftyp: STerm := mkPiL allFixArgs retTyp in\n  let rarg : nat := (length fixArgs)%nat in\n  (TranslatedArg.merge3way (IndTrans.indParams_R indPacket),\n   {|fname := I; ftype := (ftyp, None); fbody := fbody; structArg:= rarg |}).\n  \n  \n  \n  \n\nEnd IndTypeIsoRel.\nImport MonadNotation.\nOpen Scope monad_scope.\n\n\nRequire Import List. \n\n(*\nFixpoint castTermAux (vtyp: V*STerm) (t:STerm) : STerm  :=\n  let (v,typ) := vtyp in\n  match typ with\n  | mkSort s => projTyRel\n  |\n  end.\n *)\n\n\n(*\nDefinition castParam (a:Arg) : STerm  :=\n  castTerm (snd a) (vterm (fst a)).\n*)\n\nDefinition genIndisoWrappers  (ienv : indEnv) (numParams:nat) \n           (p : (inductive * simple_one_ind STerm STerm))\n  (oldNameFs : list (inductive -> nat -> ident)): list defIndSq :=\n  let (tind, smi) := p in\n  let (nmT, constrs) := smi in\n  let seq := List.seq 0 (length constrs) in\n  let (_, indTyp) := nmT in\n  let (_, indTypParams) := getNHeadPis numParams indTyp in\n  let bodyArgs := flat_map (transArgWithCast ienv) indTypParams in\n  let defn constrIndex oldNameF :=\n      let oldName := (oldNameF tind constrIndex) in\n      let body := mkConstApp oldName (map snd bodyArgs) in\n      let body := mkLamL (map fst bodyArgs) body in\n      inl {|nameSq := isoModeId oldName; bodySq := body  |} in\n  let defn constrIndex :=\n      map (defn constrIndex) oldNameFs in\n  flat_map defn seq.\n\n(* useful when we want to make them opaque *)\nDefinition oldOneIndNames\n           (oldNameFs : list (inductive -> nat -> ident))\n           (p : (inductive * simple_one_ind STerm STerm))\n  : list ident :=\n  let (tind, smi) := p in\n  let (nmT, constrs) := smi in\n  let seq := List.seq 0 (length constrs) in\n  let defn constrIndex oldNameF := (oldNameF tind constrIndex) in\n  let defn constrIndex :=\n      map (defn constrIndex) oldNameFs in\n  (indTransName tind)::(flat_map defn seq).\n\nDefinition crrCrrInvWrappers (ienv : indEnv) (numParams:nat) \n           (p : (inductive * simple_one_ind STerm STerm))\n  : list defIndSq :=\n genIndisoWrappers ienv numParams p [constrTransName; constrInvFullName].\n  \nDefinition  allCrrCrrInvsWrappers  (env : indEnv)\n  : list defIndSq  :=\n  flat_map\n    (fun (p: ident * (simple_mutual_ind STerm SBTerm)) =>\n       let (id, mind) := p in\n         let numParams := mindNumParams mind in\n           let ones := substMutInd id mind in\n           flat_map (crrCrrInvWrappers env numParams) ones\n           ) env.\n\nDefinition  oldIndNamesL  (env : indEnv)\n  : list ident :=\n  flat_map\n    (fun (p: ident * (simple_mutual_ind STerm SBTerm)) =>\n       let (id, mind) := p in\n           let ones := substMutInd id mind in\n           flat_map (oldOneIndNames  [constrTransName; constrInvFullName; constrTransTotName])\n                    ones\n           ) env.\n\nDefinition  oldIndNames  (env : indEnv)\n  : ident := \n  flattenDelim newLineString (oldIndNamesL env).\n\nDefinition mkBestRel_ref := \"ReflParam.Trecord.mkBestRel\".\nDefinition mkBestRelProp_ref := \"ReflParam.Trecord.mkBestRelProp\".\n\nDefinition  mkOneIndGoodPacket  (ienv: indEnv) (numParams:nat)\n            (p: inductive * STerm) : defSq :=\n  let (tind, typ) := p in\n  let (sort, indTypArgs) := getHeadPIs typ in\n  let castedParams_R : list STerm :=\n      let (_, indTypParams) := getNHeadPis numParams typ in\n      map snd (flat_map (transArgWithCast ienv) indTypParams) in\n  let indTyp_R := translate true ienv (headPisToLams typ) in\n  let (_, indTypArgs_R) := getNHeadLams (3*length indTypArgs) indTyp_R  in\n  let appArgs : list STerm := map (vterm ∘ fst) indTypArgs_R in\n  let indApp := mkIndApp tind (map (vterm ∘ fst) indTypArgs) in\n  let indApp2 := tprime indApp in\n  let iRRname := (indTransName tind) in\n  let IRR :=\n      let indIndices_RR := skipn (3*numParams) appArgs in\n      mkConstApp iRRname (castedParams_R++indIndices_RR) in\n  let tot12 := mkConstApp (indTransTotName false false tind) appArgs in\n  let tot21 := mkConstApp (indTransTotName false true tind) appArgs in\n  (* TODO: if the inductive is a Prop, skip these 2 and use a different combinator *)\n  let body := \n  match sort with\n    | mkSort sSet =>\n    \n      let one12 := mkConstApp (indTransOneName false tind) appArgs in\n      let one21 := mkConstApp (indTransOneName true tind) appArgs in\n      mkConstApp mkBestRel_ref [indApp, indApp2,\n                                        IRR, tot12, tot21,\n                                        one12, one21]\n    | mkSort sProp =>\n      mkConstApp mkBestRelProp_ref [indApp, indApp2,\n                                    IRR, tot12, tot21]\n    | _ => mkUnknown \"mkOneIndGoodPacket:expected a sort\"\n  end in\n  {|\n    nameSq := isoModeId iRRname;\n     bodySq:= mkLamL (mrs indTypArgs_R) body\n  |}.\n  \nDefinition  mkIndGoodPacket  (ienv: indEnv)\n            (id:ident) (mind: simple_mutual_ind STerm SBTerm)\n  : list defIndSq :=\n  let indTyps : list (inductive * STerm) := indTypes id mind in\n  let nump:= (mindNumParams mind) in\n  map (inl ∘ (mkOneIndGoodPacket ienv nump)) indTyps.\n\n\n\n\n(* end : translating  inductive props *)\n\nDefinition genWrappers  (ienv : indEnv) : TemplateMonad () :=\n  tmMkDefIndLSq (allCrrCrrInvsWrappers ienv).\n\nDefinition genParamInd (ienv : indEnv)  (b cr:bool) (id: ident) : TemplateMonad unit :=\n  id_s <- tmQuoteSq id true;;\n(*  _ <- tmPrint id_s;; *)\n  match id_s with\n  Some (inl t) => ret tt\n  | Some (inr t) =>\n    let (fb, defs) := translateMutInd ienv id t 0 in\n    let (defs , inds) := partition (isInl) defs in\n      (if b then ret tt else trr <- tmReduce Ast.all (fb,defs);; tmPrint trr);;\n      _ <- (if b then tmMkDefIndLSq inds else ret tt);;\n      _ <- (if b then  (tmMkDefinitionSq (indTransName (mkInd id 0)) fb) else ret tt);;\n        tmMkDefIndLSq (if cr then defs else [])\n      (* repeat for other inds in the mutual block *)\n  | _ => ret tt\n  end.\n\n\n(* indEnv is needed because the types may contain matches\nDefinition addConstrInvsToIndInv b ienv (ide:ident*(simple_mutual_ind STerm SBTerm))\n:\n(ident* ((simple_mutual_ind STerm SBTerm)\n        * list (simple_one_ind STerm (STerm -> STerm -> SBTerm))))\n :=\n let (id,t) := ide in\n let (_,ones) := substMutIndNoParams id t in\n  map (mapTermSimpleOneInd\n       (@Datatypes.id STerm)\n       (fun b: SBTerm => (b,translateConstructorInv b ienv indsT lp))) ones.\n       \n        in\n       combine inds onesS.\n \nsubstMutIndNoParams\n           (id:ident) (t: simple_mutual_ind STerm SBTerm)\n  :list (inductive* simple_one_ind STerm SBTerm) :=\n  substMutIndMap (fun b is _ => apply_bterm_partial b is) id t.\n  let (_)\nmapSimpl\n *)\n \nDefinition mkIndEnv (idEnv : ident) (lid: list ident) : TemplateMonad unit :=\n  let addIndToEnv (id: ident) (l: TemplateMonad indEnv) : TemplateMonad indEnv :=\n       l <- l;;\n       id_s <- tmQuoteSq id true;;\n       ret\n       (match id_s with\n       | Some (inl t) => l\n       | Some (inr t) => (id,t)::l\n       | _ => l\n        end) in\n    \n  ienv <- fold_right addIndToEnv (ret []) lid;;\n  tmMkDefinition false idEnv ienv.\n\n\nDefinition genParamIndTot (iffb21:list (bool * bool))\n           (ienv : indEnv) (b:bool) (id: ident) : TemplateMonad unit :=\n  id_s <- tmQuoteSq id true;;\n(*  _ <- tmPrint id_s;; *)\n  match id_s with\n  Some (inl t) => ret tt\n  | Some (inr t) =>\n    let ff (ifb: bool*bool) : TemplateMonad unit :=\n        let (iff,b21) := ifb in\n        let fb := (mutIndToMutFix true (translateOnePropTotal b21 ienv iff)) id t 0%nat in\n        if b then (tmMkDefinitionSq (indTransTotName iff b21 (mkInd id 0)) fb) else\n          (trr <- tmReduce Ast.all fb;; tmPrint trr) in\n        _ <- ExtLibMisc.flatten (map ff iffb21);; ret tt\n  | _ => ret tt\n  end.\n\nDefinition genParamIndOne (lb21: list bool)\n           (ienv : indEnv) (b:bool) (id: ident) : TemplateMonad unit :=\n  id_s <- tmQuoteSq id true;;\n(*  _ <- tmPrint id_s;; *)\n  match id_s with\n  Some (inl t) => ret tt\n  | Some (inr t) =>\n    let ff (b21: bool) : TemplateMonad unit :=\n        let fb := (mutIndToMutFix true (translateIndOne2One b21 ienv)) id t 0%nat in\n        if b then (tmMkDefinitionSq (indTransOneName b21 (mkInd id 0)) fb) else\n          (trr <- tmReduce Ast.all fb;; tmPrint trr) in\n        _ <- ExtLibMisc.flatten (map ff lb21);; ret tt\n  | _ => ret tt\n  end.\n\nDefinition genParamIso \n           (ienv : indEnv) (id: ident) : TemplateMonad unit :=\n  id_s <- tmQuoteSq id true;;\n(*  _ <- tmPrint id_s;; *)\n  match id_s with\n  Some (inl t) => ret tt\n  | Some (inr mind) =>\n      tmMkDefIndLSq (mkIndGoodPacket ienv id mind)\n  | _ => ret tt\n  end.\n\nDefinition genParamIndOneAll :=\n  genParamIndOne [false;true].\n\nDefinition genParamIndTotAllAux :=\n  genParamIndTot [(false, false); (false, true); (true, false); (true, true)].\n\nDefinition genParamIndTotAll (ienv : indEnv) (b:bool) (id: ident) :=\n  ExtLibMisc.flatten [genParamIndTotAllAux ienv b id;  genParamIndOneAll ienv b id].\n\nDefinition genParamIndAll (ienv : indEnv) (id: ident) :=\n  ExtLibMisc.flatten [\n      genParamInd ienv true true id;\n        genParamIndTotAllAux ienv true  id;  genParamIndOneAll ienv true id;\n    genParamIso ienv id].\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/indType.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.25720631918841336}}
{"text": "Require Import Ssreflect.ssreflect Ssreflect.ssrfun Ssreflect.ssrbool Ssreflect.eqtype Ssreflect.ssrnat Ssreflect.seq Ssreflect.tuple.\nRequire Import x86proved.bitsrep x86proved.bitsops x86proved.bitsopsprops x86proved.monad x86proved.writer x86proved.x86.reg x86proved.x86.instr x86proved.x86.instrsyntax x86proved.x86.program x86proved.x86.programassem x86proved.cursor.\nRequire Import x86proved.x86.win.pecoff x86proved.x86.cfunc.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nOpen Scope instr_scope.\nOpen Scope string_scope.\n\nRequire Import x86proved.x86.call.\nExample counterDLL :=\n  GLOBAL Get as \"Get\";\n  GLOBAL Inc as \"Inc\";\n  GLOBAL Counter;\n  SECTION CODE\n    Inc:;;  mkbody_toyfun (MOV ECX, Counter;; INC [ECX]);;\n    Get:;;  mkbody_toyfun (MOV ECX, Counter;; MOV EAX, [ECX]);\n  SECTION DATA\n    Counter:;; dd #0.\n\nCompute makeDLL #x\"00AC0000\" \"counter.dll\" counterDLL.\n\n(*\nRequire Import SPred septac spectac spec safe pointsto cursor instr.\nRequire Import basic basicprog program instrsyntax macros instrrules.\nRequire Import Coq.Setoids.Setoid Coq.Classes.RelationClasses Coq.Classes.Morphisms.\n\nExample counterModuleSpec IAT P Inc Get :=\n      (Forall c: DWORD, toyfun Inc (P c ** ECX? ** OSZCP?) (P (c +# 1) ** ECX? ** OSZCP?))\n    //\\\\\n      (Forall c: DWORD, toyfun Get (EAX? ** P c ** ECX? ** OSZCP?) (EAX ~= c ** P c ** ECX? ** OSZCP?))\n    <@ (IAT :-> (Inc, Get)).\n\nExample counterModuleCode (Inc Get Counter: DWORD) :=\n(*  LOCAL Inc; LOCAL Get; LOCAL Counter;*)\n    Inc:;;  mkbody_toyfun (MOV ECX, Counter;; INC [ECX]);;\n    Get:;;  mkbody_toyfun (MOV ECX, Counter;; MOV EAX, [ECX]).\n\nExample counterModuleData :=\n    dd #0.\n\nExample counterModuleIAT Inc Get :=\n    dd Inc;; dd Get.\n\nRequire Import flags.\nTheorem counterModuleCorrect (codeStart codeEnd dataStart:DWORD):\n  |-- Forall Inc, Forall Get,\n      counterModuleSpec codeStart (fun v => dataStart :-> v) Inc Get <@ (codeStart -- codeEnd :-> counterModuleCode Inc Get dataStart).\nProof.\nrewrite /counterModuleSpec.\nrewrite /counterModuleCode.\nspecintros => Inc Get. unfold_program.\n\nspecintros => i1 -> -> i2 i3 -> ->.\nrewrite !empSPL.\nspecsplit.\n(* Inc *)\nspecintros => c.\nrewrite <- spec_reads_merge.\nrewrite <- spec_reads_frame.\n  etransitivity; [|apply toyfun_mkbody]. specintro => iret.\n  rewrite /flagAny. specintros => O S Z C P. autorewrite with push_at.\n  basicapply MOV_RI_rule.\n  basicapply INC_M_rule. rewrite addB0.\n  rewrite /OSZCP. sbazooka. rewrite addB1 addB0. rewrite /regAny.\n  sbazooka.\n  rewrite /OSZCP. ssimpl. reflexivity.\n\n(* Get *)\nspecintros => c.\nrewrite spec_reads_swap.\nrewrite <- spec_reads_frame.\nrewrite <- spec_reads_merge.\nrewrite <- spec_reads_swap.\nrewrite <- spec_reads_frame.\n  etransitivity; [|apply toyfun_mkbody]. specintro => iret.\n  rewrite /flagAny. specintros => O S Z C P. autorewrite with push_at.\n  basicapply MOV_RI_rule.\n  basicapply MOV_RM0_rule. rewrite /regAny. sbazooka.\nQed.\n\nExample useCounterModule IAT : program :=\n  MOV EDI, IAT;; call_toyfun [EDI];;\n  MOV EDI, IAT;; call_toyfun [EDI];;\n  MOV EDI, IAT;; call_toyfun [EDI+4].\n\nExample useCounterModuleCorrect (codeStart codeEnd dataStart Inc Get IAT: DWORD):\n  counterModuleSpec codeStart (fun v => dataStart :-> v) Inc Get\n  |-- basic (EAX?) (useCounterModule IAT) (EAX ~= #2) @\n      (EDI? ** OSZCP? ** retreg?) <@ (IAT :-> (Inc,Get)).\nProof.\n  rewrite /useCounterModule. autorewrite with push_at.\n  rewrite <- spec_reads_frame.\n  eapply basic_seq.\n  basicapply MOV_RI_rule.\n  rewrite /counterModuleSpec.\n  apply landL1.\n  - (*apply lforallL with c.*)\n    eapply basic_basic_context.\n    - have H := toyfun_call. setoid_rewrite spec_at_basic in H. apply H.\n    - by apply spec_later_weaken.\n    - by ssimpl.\n    done.\n  apply lforallL with (a +# 2).\n  eapply basic_basic_context.\n  - have H := toyfun_call. setoid_rewrite spec_at_basic in H. apply H.\n  - by apply spec_later_weaken.\n  - by ssimpl.\n  rewrite -addB_addn. rewrite -[2+2]/4. by ssimpl.\nQed.\n\nExample useCounterSpec IAT :\n\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/win/counter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.25720631918841336}}
{"text": "(******************************************************************************)\n(** * Correctness of Program Transformations *)\n(******************************************************************************)\nRequire Import Classical List Relations Peano_dec.\nRequire Import ClassicalDescription IndefiniteDescription.\nRequire Import Hahn.\nRequire Import Basic.\nRequire Import RC11_Events RC11_Model.\n\nSet Implicit Arguments.\nRemove Hints plus_n_O.\n\nSection Transformation.\n\nVariables Gsrc Gtgt : execution.\n\n(* Target notation *)\nNotation \"'acts`'\" := Gtgt.(acts).\nNotation \"'lab`'\" := Gtgt.(lab).\nNotation \"'loc`'\" := (loc lab`).\nNotation \"'val`'\" := (val lab`).\nNotation \"'mod`'\" := (mod lab`).\n\nNotation \"'sb`'\" := Gtgt.(sb).\nNotation \"'rf`'\" := Gtgt.(rf).\nNotation \"'mo`'\" := Gtgt.(mo).\nNotation \"'rs`'\" := Gtgt.(rs).\nNotation \"'release`'\" := Gtgt.(release).\nNotation \"'sw`'\" := Gtgt.(sw).\nNotation \"'rb`'\" := Gtgt.(rb).\nNotation \"'hb`'\" := Gtgt.(hb).\nNotation \"'data`'\" := Gtgt.(data).\nNotation \"'addr`'\" := Gtgt.(addr).\nNotation \"'ctrl`'\" := Gtgt.(ctrl).\nNotation \"'deps`'\" := Gtgt.(deps).\nNotation \"'eco`'\" := Gtgt.(eco).\nNotation \"'same_loc`'\" := Gtgt.(same_loc).\nNotation \"r |loc`\" := (r ∩ same_loc`) (at level 1).\nNotation \"'psc`'\" := Gtgt.(psc).\nNotation \"'psc_base`'\" := Gtgt.(psc_base).\nNotation \"'psc_f`'\" := Gtgt.(psc_f).\nNotation \"'scb`'\" := Gtgt.(scb).\nNotation \"'conflicting`'\" := Gtgt.(conflicting).\nNotation \"'race`'\" := Gtgt.(race).\nNotation \"'racy`'\" := Gtgt.(racy).\n\nNotation \"'E`'\" := Gtgt.(E).\nNotation \"'F`'\" := (F lab`).\nNotation \"'R`'\" := (R lab`).\nNotation \"'W`'\" := (W 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\n(* Source notation *)\nNotation \"'acts'\" := Gsrc.(acts).\nNotation \"'lab'\" := Gsrc.(lab).\nNotation \"'loc'\" := (loc lab).\nNotation \"'val'\" := (val lab).\nNotation \"'mod'\" := (mod lab).\n\nNotation \"'sb'\" := Gsrc.(sb).\nNotation \"'rf'\" := Gsrc.(rf).\nNotation \"'mo'\" := Gsrc.(mo).\nNotation \"'rs'\" := Gsrc.(rs).\nNotation \"'release'\" := Gsrc.(release).\nNotation \"'sw'\" := Gsrc.(sw).\nNotation \"'rb'\" := Gsrc.(rb).\nNotation \"'hb'\" := Gsrc.(hb).\nNotation \"'data'\" := Gsrc.(data).\nNotation \"'addr'\" := Gsrc.(addr).\nNotation \"'ctrl'\" := Gsrc.(ctrl).\nNotation \"'deps'\" := Gsrc.(deps).\nNotation \"'eco'\" := Gsrc.(eco).\nNotation \"'same_loc'\" := Gsrc.(same_loc).\nNotation \"r |loc\" := (r ∩ same_loc) (at level 1).\nNotation \"'psc'\" := Gsrc.(psc).\nNotation \"'psc_base'\" := Gsrc.(psc_base).\nNotation \"'psc_f'\" := Gsrc.(psc_f).\nNotation \"'scb'\" := Gsrc.(scb).\nNotation \"'conflicting'\" := Gsrc.(conflicting).\nNotation \"'race'\" := Gsrc.(race).\nNotation \"'racy'\" := Gsrc.(racy).\n\nNotation \"'E'\" := Gsrc.(E).\nNotation \"'F'\" := (F lab).\nNotation \"'R'\" := (R lab).\nNotation \"'W'\" := (W 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\nDefinition valid_transformation :=\n  (consistent Gtgt -> consistent Gsrc) /\\\n  (racy` ⊆ racy).\n\n(* Lemma I.1: Strengthening *)\nSection Strengthening.\n\nHypothesis ACTS: acts = acts`.\nHypothesis SB: sb ≡ sb`.\nHypothesis RF: rf ≡ rf`.\nHypothesis MO: mo ≡ mo`.\nHypothesis DATA: data ≡ data`.\nHypothesis ADDR: addr ≡ addr`.\nHypothesis CTRL: ctrl ≡ ctrl`.\nHypothesis S_R: R ≡₁ R`.\nHypothesis S_W: W ≡₁ W`.\nHypothesis S_F: F ≡₁ F`.\nHypothesis S_L: loc = loc`.\nHypothesis S_V: val = val`.\nHypothesis M_Na: Na ≡₁ Na`.\nHypothesis M_RLX: Rlx ⊆₁ Rlx`.\nHypothesis M_REL: Rel ⊆₁ Rel`.\nHypothesis M_ACQ: Acq ⊆₁ Acq`.\nHypothesis M_ACQREL: Acqrel ⊆₁ Acqrel`.\nHypothesis M_SC: Sc ⊆₁ Sc`.\nHypothesis LAB_INIT: forall l : location, lab (Init l) = lab` (Init l).\n\nLemma eqv_inter A (P P' : A -> Prop) : ⦗P ∩₁ P'⦘ ≡ ⦗P⦘ ∩ ⦗P'⦘.\nProof. basic_solver. Qed.\n\nTactic Notation \"cassert\" uconstr(H) :=\n  let ID := fresh in try (assert (ID := H); crewrite ID).\n\nLtac oto_basic := rewrite ?eqv_inter;\n  crewrite ACTS; crewrite SB; crewrite RF; crewrite MO; crewrite DATA;\n  crewrite ADDR; crewrite CTRL; crewrite S_R; crewrite S_W; crewrite S_F;\n  crewrite S_L; crewrite S_V; crewrite M_Na; crewrite M_RLX; crewrite M_REL;\n  crewrite M_ACQ; crewrite M_ACQREL; crewrite M_SC; crewrite LAB_INIT.\n\n(* Lemma S_E: E ≡₁ E`.\nProof. by unfold RMW_Model.E; oto_basic. Qed.\n\nLemma S_RW: RW ≡₁ RW`.\nProof.\n  unfold RMW_Events.RW; unfolder.\n  ins; split; ins; desf; (apply S_R in H + apply S_W in H); auto.\nQed.\n\nLemma SAME_LOC: same_loc ≡ same_loc`.\nProof. by unfold RMW_Model.same_loc; oto_basic. Qed.\n \nLemma RS: rs ⊆ rs`.\nProof.\n  unfold RMW_Model.rs.\n  cassert S_E; cassert SAME_LOC.\n  by oto_basic.\nQed.\n\nLemma REL: rel ⊆ rel`.\nProof.\n  unfold RMW_Model.rel.\n  cassert RS.\n  by oto_basic.\nQed.\n\nLemma SW: sw ⊆ sw`.\nProof.\n  unfold RMW_Model.sw.\n  cassert REL.\n  by oto_basic.\nQed.\n\nLemma HB: hb ⊆ hb`.\nProof.\n  unfold RMW_Model.hb.\n  cassert SW.\n  by oto_basic.\nQed.\n\nLemma RB: rb ≡ rb`.\nProof.\n  unfold RMW_Model.rb.\n  cassert S_E.\n  by oto_basic.\nQed.\n\nLemma ECO: eco ≡ eco`.\nProof.\n  unfold RMW_Model.eco.\n  cassert RB.\n  by oto_basic.\nQed.\n\nLemma SCB: scb ⊆ scb`.\nProof.\n  unfold RMW_Model.scb, RMW_Model.sb_neq_loc, RMW_Model.sb_loc, RMW_Model.hb_loc.\n  cassert HB; cassert RB; cassert SAME_LOC; cassert S_RW.\n  by oto_basic.\nQed.\n\nLemma PSC_BASE: psc_base ⊆ psc_base`.\nProof.\n  unfold RMW_Model.psc_base.\n  cassert HB; cassert SCB.\n  by oto_basic.\nQed.\n\nLemma PSC_F: psc_f ⊆ psc_f`.\nProof.\n  unfold RMW_Model.psc_f.\n  cassert HB; cassert ECO.\n  by oto_basic.\nQed.\n\nLemma PSC: psc ⊆ psc`.\nProof.\n  unfold RMW_Model.psc.\n  cassert PSC_BASE; cassert PSC_F.\n  by oto_basic.\nQed.\n\nLtac cassert_all :=\n  cassert S_E; cassert S_RW; cassert SAME_LOC; cassert RS; cassert REL;\n  cassert SW; cassert HB; cassert RB; cassert ECO; cassert SCB;\n  cassert PSC_BASE; cassert PSC_F; cassert PSC.\n\nLtac oto := try solve [by oto_basic | cassert_all; by oto_basic].\n\nLemma strengthening : valid_transformation.\nProof with red; splits; oto.\n  split.\n  - (* Consistent *)\n    red; unfold consistent; unnw; ins; desf; splits.\n    + (* Wf *)\n      cdes H; red; splits.\n      * (* WfACTS *) cdes WF_ACTS...\n      * (* WfSB *) cdes WF_SB...\n      * (* WfRF *)\n        cdes WF_RF...\n        (* RF_TOT *)\n        oto_basic.\n        ins; specialize (RF_TOT b).\n        apply S_R in READ; intuition.\n        by desf; exists a; apply RF.\n      * (* WfMO *)\n        cdes WF_MO...\n        (* MO_TOT *)\n        oto_basic.\n        ins; specialize (MO_TOT l).\n        unfold is_total in *.\n        ins; desf; apply S_W in IWa0; apply S_W in IWb0; auto.\n      * (* WfDEPS *) cdes WF_DEPS...\n    + (* Coherent *) cdes H0...\n    + (* Atomic *) cdes H1...\n    + (* PSC *) cdes H2...\n    + (* No-thin-air *) cdes H3...\n  - (* Racy *)\n    unfold RMW_Model.racy, RMW_Model.race, RMW_Model.conflicting.\n    oto.\nQed.\n *)\nEnd Strengthening.\n\nEnd Transformation.\n\n(*\nDefinition transformation := rmw_execution -> rmw_execution.\n\nDefinition valid_transformation (Gsrc: rmw_execution) (Tr: transformation) :=\n  consistent (Tr Gsrc) -> consistent Gsrc.\n\nDefinition strengthening : transformation := fun Gsrc =>\n  Gsrc.\n\nLemma strengthening_valid : valid_transformation Gr strengthening.\nProof.\n  red.\n  unfold strengthening.\n  done.\nQed. *)\n\n(* \nDefinition mapR (g : event -> event) R := \n  (fun a b => exists a' b', g a' = a /\\ g b' = b /\\ R a' b').\n  \nDefinition add_beween R A B new := (fun a b : event => \n  R a b \\/ A a /\\ b = new \\/ a = new /\\ B b).\n\nLemma add_f_wf acts sb rmw rf mo sc\n    (WF: Wf acts sb rmw rf mo sc)\n    A B (NRMW: forall a b, A a /\\ B b -> ~ rmw a b)\n    i (TID: forall a, A a \\/ B a <-> thread a = i \\/ is_init a) \n    f (NINf: ~ In f acts) (TIDf: thread f = i)  (LABf: lab f = Afence Orel)\n    acts' (ACTS': acts' = f :: acts)\n    sb' (SB': sb' = add_beween sb A B f) :\n    Wf acts' sb' rmw rf mo sc.\nProof.\nunfold Wf, WfACTS, WfSB, WfRMW, WfRF, WfMO, WfSC in *; desc; subst; splits; eauto using in_cons.\nAdmitted.\n\nLemma add_f acts sb rmw rf mo sc\n    (COH: Coherent acts sb rmw rf mo sc)\n    A B (NRMW: forall a b, A a /\\ B b -> ~ rmw a b)\n    i (TID: forall a, A a \\/ B a <-> thread a = i \\/ is_init a) \n    f (NINf: ~ In f acts) (LABf: lab f = Afence Orel) (TIDf: thread f = i)\n    acts' (ACTS': acts' = f :: acts)\n    sb' (SB': sb' = add_beween sb A B f) :\n    Coherent acts' sb' rmw rf mo sc.\nProof.\nred; splits; red; splits.\nred; splits.\n\nLemma add_f acts sb rmw rf mo sc\n    (COH: Coherent acts sb rmw rf mo sc)\n    A B (NRMW: forall a b, A a /\\ B b -> ~ rmw a b)\n    i (forall a, A a \\/ B a <-> thread a = i \\/\n    f (NINf: ~ In f acts) (LABf: lab f = Afence Orel) (\n    acts' (ACTS': acts' = f :: acts)\n    sb' (SB': sb' = add_beween sb A B f) :\n    Coherent acts' sb' rmw rf mo sc.\nProof.\n\n\nAdmitted.\n\nLemma rel_to_rlx acts sb rmw rf mo sc\n    (COH: Coherent acts sb rmw rf mo sc)\n    g (TID: forall a, thread (g a) = thread a)\n(AAA: forall a, g a = a \\/ exists l v prev, \n        lab a = Astore l v Orel /\\ lab (g a) = Astore l v Orlx /\\\n        immediate sb prev a /\\ lab prev = Afence Orel)\n    acts' (ACTS': acts' = map g acts)\n    sb' (SB': sb' = mapR g sb)\n    rmw' (RMW': rmw' = mapR g rmw)\n    rf' (RF': rf' = mapR g rf)\n    mo' (MO': mo' = mapR g mo)\n    sc' (SC': sc' = mapR g sc) :\n    Coherent acts' sb' rmw' rf' mo' sc'.\nProof.\nAdmitted. *)", "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/Transformations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.25720631918841336}}
{"text": "Require Import Ascii Bool AutoSep Wrap Malloc SinglyLinkedList Bags NumOps Buffers.\nRequire Import StringOps XmlLex XmlSearch XmlOutput ArrayOps HttpQ.\nRequire Import RelDb RelDbCondition RelDbSelect RelDbInsert RelDbDelete.\n\nSet Implicit Arguments.\n\n\n(* Patterns matching against XML trees *)\nInductive pat :=\n\n(* Match CDATA constant. *)\n| Cdata (const : string)\n\n(* Record CDATA at this position via a variable. *)\n| Var (text : string)\n\n(* Like [Var], but for an XML subtree *)\n| TreeVar (text : string)\n\n(* Match a specific tag at this level in the XML tree, then continue into its children. *)\n| Tag (tag : string) (inner : pat)\n\n(* Match two different patterns at this level of the tree. *)\n| Both (p1 p2 : pat)\n\n(* Match one pattern and then another in the part of the XML tree right after the match of the first. *)\n| Ordered (p1 p2 : pat).\n\n(* Expressions for data queries and updates *)\nInductive exp :=\n| Const (s : string)\n| Input (text : string).\n\nDefinition equality := (string * exp)%type.\nDefinition condition := list equality.\n\n(* Language for generating XML code *)\nInductive xml :=\n| XCdata (const : string)\n| XVar (text : string)\n| XTag (tag : string) (inner : list xml)\n| XColumn (tab col : string)\n| XSelect (tab : string) (cond : condition) (inner : xml)\n| XIfEqual (tab1 col1 tab2 col2 : string) (inner : xml).\n\nSection xml_ind'.\n  Variable P : xml -> Prop.\n\n  Hypothesis H_Cdata : forall const, P (XCdata const).\n\n  Hypothesis H_Var : forall text, P (XVar text).\n\n  Hypothesis H_Tag : forall tag inner, List.Forall P inner -> P (XTag tag inner).\n\n  Hypothesis H_Column : forall tab col, P (XColumn tab col).\n\n  Hypothesis H_Select : forall tab cond inner, P inner -> P (XSelect tab cond inner).\n\n  Hypothesis H_IfEqual : forall tab1 col1 tab2 col2 inner, P inner -> P (XIfEqual tab1 col1 tab2 col2 inner).\n\n  Fixpoint xml_ind' (xm : xml) : P xm :=\n    match xm with\n      | XCdata const => H_Cdata const\n      | XVar text => H_Var text\n      | XTag 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      | XColumn tab col => H_Column tab col\n      | XSelect tab cond inner => H_Select tab cond (xml_ind' inner)\n      | XIfEqual tab1 col1 tab2 col2 inner => H_IfEqual tab1 col1 tab2 col2 (xml_ind' inner)\n    end.\nEnd xml_ind'.\n\nOpaque xml_ind'.\n\n(* Language of actions to take for matched patterns *)\nInductive action :=\n| Insert (tab : string) (es : list exp)\n| Delete (tab : string) (cond : condition)\n| Output (xm : xml)\n| Seq (a1 a2 : action)\n| IfExists (tab : string) (cond : condition) (_then _else : action)\n| Halt\n| Select (tab : string) (cond : condition) (inner : action)\n| SendTo (url data : xml).\n\n(* A full program *)\nInductive program :=\n| Rule (p : pat) (a : action)\n| PSeq (pr1 pr2 : program).\n\n\n(** * Our versions of the auxiliary functions from XmlSearch *)\n\nFixpoint freeVar (p : pat) (x : string) : Prop :=\n  match p with\n    | Cdata _ => False\n    | Var text => x = text\n    | TreeVar text => x = text\n    | Tag _ inner => freeVar inner x\n    | Both p1 p2 => freeVar p1 x \\/ freeVar p2 x\n    | Ordered p1 p2 => freeVar p1 x \\/ freeVar p2 x\n  end.\n\nFixpoint pwf (p : pat) : Prop :=\n  match p with\n    | Cdata const => goodSize (String.length const)\n    | Var _ => True\n    | TreeVar _ => True\n    | Tag tag inner => goodSize (String.length tag) /\\ pwf inner\n    | Both p1 p2 => pwf p1 /\\ pwf p2 /\\ (forall x, freeVar p1 x -> ~freeVar p2 x)\n    | Ordered p1 p2 => pwf p1 /\\ pwf p2 /\\ (forall x, freeVar p1 x -> ~freeVar p2 x)\n  end%type.\n\nFixpoint allCdatas (p : pat) : list string :=\n  match p with\n    | Cdata _ => nil\n    | Var text => text :: nil\n    | TreeVar text => text :: nil\n    | Tag _ inner => allCdatas inner\n    | Both p1 p2 => allCdatas p2 ++ allCdatas p1\n    | Ordered p1 p2 => allCdatas p2 ++ allCdatas p1\n  end.\n\n\n(** * Our versions of the auxiliary functions from XmlOutput *)\n\nDefinition ewf (e : exp) : Prop :=\n  match e with\n    | Const s => goodSize (String.length s)\n    | Input _ => True\n  end.\n\nDefinition ewfs := List.Forall ewf.\n\nDefinition eqwf (sch : schema) (e : equality) : Prop :=\n  In (fst e) sch /\\ ewf (snd e).\n\nDefinition cwf sch : condition -> Prop := List.Forall (eqwf sch).\n\nFixpoint xwf (avs ts : tables) (xm : xml) : Prop :=\n  match xm with\n    | XCdata const => goodSize (String.length const)\n    | XVar _ => True\n    | XTag tag inner => goodSize (String.length tag + 3)\n      /\\ ForallR (xwf avs ts) inner\n    | XColumn tab col => exists t, In t avs /\\ Name t = tab\n      /\\ In col (Schema t)\n    | XSelect tab cond inner => exists t, In t ts /\\ Name t = tab\n      /\\ cwf (Schema t) cond\n      /\\ xwf (t :: avs) (removeTable tab ts) inner\n    | XIfEqual tab1 col1 tab2 col2 inner => tab1 <> tab2\n      /\\ (exists t, In t avs /\\ Name t = tab1\n        /\\ In col1 (Schema t))\n      /\\ (exists t, In t avs /\\ Name t = tab2\n        /\\ In col2 (Schema t))\n      /\\ xwf avs ts inner\n  end.\n\nDefinition efreeVar (e : exp) (x : string) : Prop :=\n  match e with\n    | Const _ => False\n    | Input text => x = text\n  end.\n\nFixpoint xfreeVar (xm : xml) (x : string) : Prop :=\n  match xm with\n    | XCdata _ => False\n    | XVar text => x = text\n    | XTag _ inner => ExistsR (fun xm' => xfreeVar xm' x) inner\n    | XColumn _ _ => False\n    | XSelect _ cond inner => List.Exists (fun e => efreeVar (snd e) x) cond\n      \\/ xfreeVar inner x\n    | XIfEqual _ _ _ _ inner => xfreeVar inner x\n  end.\n\nFixpoint xbindsRowVar (xm : xml) (x : string) : Prop :=\n  match xm with\n    | XCdata _ => False\n    | XVar _ => False\n    | XTag _ inner => ExistsR (fun xm' => xbindsRowVar xm' x) inner\n    | XColumn _ _ => False\n    | XSelect tab _ inner => x = tab \\/ xbindsRowVar inner x\n    | XIfEqual _ _ _ _ inner => xbindsRowVar inner x\n  end.\n\n\n(** * Compiling to other [Xml*] modules' languages *)\n\nFixpoint compilePat (p : pat) : XmlSearch.pat :=\n  match p with\n    | Cdata const => XmlSearch.Cdata const\n    | Var text => XmlSearch.Var (text ++ \"_start\") (text ++ \"_len\")\n    | TreeVar text => XmlSearch.TreeVar (text ++ \"_start\") (text ++ \"_len\")\n    | Tag tag inner => XmlSearch.Tag tag (compilePat inner)\n    | Both p1 p2 => XmlSearch.Both (compilePat p1) (compilePat p2)\n    | Ordered p1 p2 => XmlSearch.Ordered (compilePat p1) (compilePat p2)\n  end.\n\nDefinition compileExp (e : exp) : RelDb.exp :=\n  match e with\n    | Const s => RelDb.Const s\n    | Input text => RelDb.Input (text ++ \"_start\") (text ++ \"_len\")\n  end.\n\nDefinition compileExps := map compileExp.\n\nDefinition compileEquality (e : equality) : RelDb.equality :=\n  (fst e, compileExp (snd e)).\n\nDefinition compileCondition : condition -> RelDb.condition :=\n  map compileEquality.\n\nFixpoint compileXml (p : xml) : XmlOutput.xml :=\n  match p with\n    | XCdata const => XmlOutput.Cdata const\n    | XVar text => XmlOutput.Var (text ++ \"_start\") (text ++ \"_len\")\n    | XTag tag inner => XmlOutput.Tag tag (map compileXml inner)\n    | XColumn tab col => XmlOutput.Column tab col\n    | XSelect tab cond inner => XmlOutput.Select tab\n      (tab ++ \"_row\") (tab ++ \"_data\") (compileCondition cond)\n      (compileXml inner)\n    | XIfEqual tab1 col1 tab2 col2 inner =>\n      XmlOutput.IfEqual tab1 col1 tab2 col2 (compileXml inner)\n  end.\n\n\n(** * Combined well-formedness and related lemmas *)\n\nFixpoint awf (avs ts : tables) (a : action) : Prop :=\n  match a with\n    | Insert tab es => exists t, In t ts /\\ Name t = tab\n      /\\ length es = length (Schema t) /\\ ewfs es\n    | Delete tab cond => exists t, In t ts /\\ Name t = tab\n      /\\ cwf (Schema t) cond\n    | Output xm => xwf avs ts xm\n    | Seq a1 a2 => awf avs ts a1 /\\ awf avs ts a2\n    | IfExists tab cond _then _else => exists t, In t ts /\\ Name t = tab\n      /\\ cwf (Schema t) cond\n      /\\ awf avs ts _then /\\ awf avs ts _else\n    | Halt => True\n    | Select tab cond inner => exists t, In t ts /\\ Name t = tab\n      /\\ cwf (Schema t) cond\n      /\\ awf (t :: avs) (removeTable tab ts) inner\n    | SendTo url data => xwf avs ts url /\\ xwf avs ts data\n  end.\n\nFixpoint afreeVar (a : action) (x : string) : Prop :=\n  match a with\n    | Insert _ es => List.Exists (fun e => efreeVar e x) es\n    | Delete _ cond => List.Exists (fun e => efreeVar (snd e) x) cond\n    | Output xm => xfreeVar xm x\n    | Seq a1 a2 => afreeVar a1 x \\/ afreeVar a2 x\n    | IfExists _ cond _then _else => List.Exists (fun e => efreeVar (snd e) x) cond\n      \\/ afreeVar _then x \\/ afreeVar _else x\n    | Halt => False\n    | Select _ cond inner => List.Exists (fun e => efreeVar (snd e) x) cond\n      \\/ afreeVar inner x\n    | SendTo url data => xfreeVar url x \\/ xfreeVar data x\n  end.\n\nFixpoint wf (ts : tables) (pr : program) : Prop :=\n  match pr with\n    | Rule p a => pwf p /\\ awf nil ts a\n      /\\ (forall x, afreeVar a x -> freeVar p x)\n    | PSeq pr1 pr2 => wf ts pr1 /\\ wf ts pr2\n  end.\n\nFixpoint allCdatas_both (p : pat) : list string :=\n  match p with\n    | Cdata _ => nil\n    | Var text => (text ++ \"_start\")%string :: (text ++ \"_len\")%string :: nil\n    | TreeVar text => (text ++ \"_start\")%string :: (text ++ \"_len\")%string :: nil\n    | Tag _ inner => allCdatas_both inner\n    | Both p1 p2 => allCdatas_both p2 ++ allCdatas_both p1\n    | Ordered p1 p2 => allCdatas_both p2 ++ allCdatas_both p1\n  end.\n\nFixpoint member (s : string) (ss : list string) : bool :=\n  match ss with\n    | nil => false\n    | s0 :: ss => string_eq s s0 || member s ss\n  end.\n\nFixpoint addTo (ss1 ss2 : list string) : list string :=\n  match ss1 with\n    | nil => ss2\n    | s :: ss1 => addTo ss1 (if member s ss2 then ss2 else s :: ss2)\n  end.\n\nFixpoint cdatasOf (pr : program) : list string :=\n  match pr with\n    | Rule p _ => allCdatas_both p\n    | PSeq pr1 pr2 => addTo (cdatasOf pr1) (cdatasOf pr2)\n  end.\n\nFixpoint underscore_free (s : string) : Prop :=\n  match s with\n    | \"\"%string => True\n    | String ch s' => ch <> \"_\"%char /\\ underscore_free s'\n  end.\n\nLemma no_clash' : forall s' s,\n  underscore_free (s ++ String \"_\"  s')%string\n  -> False.\n  induction s; simpl; intuition.\nQed.\n\nLemma no_clash'' : forall s,\n  underscore_free s\n  -> forall p, In s (allCdatas_both p)\n    -> False.\n  induction p; simpl; intuition (subst; eauto using no_clash');\n    match goal with\n      | [ H : _ |- _ ] => apply in_app_or in H; tauto\n    end.\nQed.\n\nLemma no_clash : forall s p,\n  In s (allCdatas_both p)\n  -> underscore_free s\n  -> False.\n  intros; eapply no_clash''; eauto.\nQed.\n\nLocal Hint Resolve no_clash.\n\nLocal Hint Extern 1 (underscore_free _) => simpl; intuition congruence.\n\nLemma append_inj : forall s1 s2 s,\n  (s ++ s1 = s ++ s2)%string\n  -> s1 = s2.\n  induction s; simpl; intuition.\nQed.\n\nLemma NoDup_app : forall A (ls2 : list A),\n  NoDup ls2\n  -> forall ls1, NoDup ls1\n    -> (forall x, In x ls1 -> In x ls2 -> False)\n    -> NoDup (ls1 ++ ls2).\n  induction 2; simpl; intuition;\n    constructor; simpl; intuition eauto;\n      match goal with\n        | [ H : _ |- _ ] => apply in_app_or in H; intuition eauto\n      end.\nQed.\n\nLemma NoDup_unapp_noclash : forall A (ls2 ls1 : list A),\n  NoDup (ls1 ++ ls2)\n  -> (forall x, In x ls1 -> In x ls2 -> False).\n  induction ls1; inversion 1; simpl in *; subst; intuition (subst; eauto using in_or_app).\nQed.\n\nLemma In_allCdatas_both : forall x p,\n  In x (allCdatas_both p)\n  -> exists y, In y (allCdatas p) /\\ (x = y ++ \"_start\" \\/ x = y ++ \"_len\")%string.\n  induction p; simpl; intuition (subst; eauto);\n    match goal with\n      | [ H : _ |- _ ] =>\n        apply in_app_or in H; post; subst; eauto 6 using in_or_app\n    end.\nQed.\n\nLemma length_append : forall s2 s1,\n  String.length (s1 ++ s2) = String.length s1 + String.length s2.\n  induction s1; simpl; intuition.\nQed.\n\nLemma append_inj' : forall s s1 s2,\n  (s1 ++ s = s2 ++ s)%string\n  -> s1 = s2.\n  induction s1; destruct s2; simpl; intuition;\n    match goal with\n      | [ H : _ |- _ ] =>\n        apply (f_equal String.length) in H; simpl in H; rewrite length_append in H; omega\n      | [ H : String _ _ = String _ _ |- _ ] =>\n        injection H; clear H; intros; f_equal; auto\n    end.\nQed.\n\nFixpoint lastChar (s : string) : ascii :=\n  match s with\n    | \"\"%string => \" \"%char\n    | String ch \"\"%string => ch\n    | String _ s' => lastChar s'\n  end.\n\nLemma lastChar_app : forall s2,\n  (String.length s2 > 0)%nat\n  -> forall s1, lastChar (s1 ++ s2) = lastChar s2.\n  induction s1; simpl; intuition;\n    destruct s1; simpl in *; auto;\n      destruct s2; simpl in *; auto; omega.\nQed.\n\nLtac injy :=\n  match goal with\n    | [ H : _ |- _ ] => solve [ apply append_inj' in H; subst; eauto ]\n    | [ H : _ |- _ ] => apply (f_equal lastChar) in H;\n      repeat rewrite lastChar_app in H by (simpl; omega); discriminate\n    | [ H : _ |- _ ] =>\n      apply (f_equal String.length) in H; simpl in H; rewrite length_append in H; simpl in H; omega\n  end.\n\nLemma allCdatas_NoDup : forall p,\n  NoDup (allCdatas p)\n  -> NoDup (allCdatas_both p).\n  induction p; simpl; intuition;\n    repeat constructor; simpl; intuition;\n      try match goal with\n            | [ H : _ |- _ ] => apply append_inj in H; discriminate\n          end;\n  match goal with\n    | [ H : NoDup _ |- _ ] =>\n      specialize (NoDup_unapp1 _ _ H);\n        specialize (NoDup_unapp2 _ _ H);\n          specialize (NoDup_unapp_noclash _ _ H);\n            clear H; intros\n  end; apply NoDup_app; auto; intros;\n  repeat match goal with\n           | [ H : _ |- _ ] => apply In_allCdatas_both in H\n         end; post; subst;\n  injy.\nQed.\n\nLocal Hint Immediate allCdatas_NoDup.\n\nLemma freeVar_compile : forall x p,\n  XmlSearch.freeVar (compilePat p) x\n  -> In x (allCdatas_both p).\n  induction p; simpl; intuition.\nQed.\n\nLocal Hint Immediate freeVar_compile.\n\nLemma allCdatas_freeVar : forall x p,\n  In x (allCdatas p)\n  -> freeVar p x.\n  induction p; simpl; intuition;\n    match goal with\n      | [ H : _ |- _ ] =>\n        apply in_app_or in H; tauto\n    end.\nQed.\n\nLocal Hint Resolve allCdatas_freeVar.\n\nLemma wf_compile : forall p,\n  pwf p\n  -> XmlSearch.wf (compilePat p).\n  induction p; simpl; intuition;\n    repeat match goal with\n             | [ H : _ |- _ ] => apply freeVar_compile in H; apply In_allCdatas_both in H\n           end; post; subst; injy.\nQed.\n\nLocal Hint Immediate wf_compile.\n\nLemma wf_NoDup : forall p,\n  pwf p\n  -> NoDup (allCdatas p).\n  induction p; simpl; intuition; try NoDup; eauto using NoDup_app.\nQed.\n\nFixpoint allCursors_both' (xm : xml) : list string :=\n  match xm with\n    | XCdata _ => nil\n    | XVar _ => nil\n    | XTag _ inners => fold_left (fun ls xm => addTo (allCursors_both' xm) ls) inners nil\n    | XColumn _ _ => nil\n    | XSelect tab _ inner => (tab ++ \"_row\")%string :: (tab ++ \"_data\")%string\n      :: allCursors_both' inner\n    | XIfEqual _ _ _ _ inner => allCursors_both' inner\n  end.\n\nFixpoint allCursors_both (a : action) : list string :=\n  match a with\n    | Insert _ _ => nil\n    | Delete tab _ => (tab ++ \"_row\")%string :: (tab ++ \"_data\")%string :: nil\n    | Output xm => allCursors_both' xm\n    | Seq a1 a2 => addTo (allCursors_both a1) (allCursors_both a2)\n    | IfExists tab _ _then _else =>\n      addTo ((tab ++ \"_row\")%string :: (tab ++ \"_data\")%string :: nil)\n      (addTo (allCursors_both _then) (allCursors_both _else))\n    | Halt => nil\n    | Select tab _ inner => addTo ((tab ++ \"_row\")%string :: (tab ++ \"_data\")%string :: nil)\n      (allCursors_both inner)\n    | SendTo url data => addTo (allCursors_both' url) (allCursors_both' data)\n  end.\n\nFixpoint cursorsOf (pr : program) : list string :=\n  match pr with\n    | Rule _ a => allCursors_both a\n    | PSeq pr1 pr2 => addTo (cursorsOf pr1) (cursorsOf pr2)\n  end.\n\n\n(** * Compiling programs *)\n\nSection compileProgram.\n  Variable pr : program.\n\n  Definition numCdatas := length (cdatasOf pr).\n  Definition numCursors := length (cursorsOf pr).\n  Definition reserved := numCdatas + numCursors + 30.\n\n  Definition preLvars := \"lex\" :: \"res\" :: \"opos\" :: \"overflowed\"\n    :: \"tagStart\" :: \"tagLen\" :: \"matched\" :: \"stack\" :: \"level\" :: \"tmp\"\n    :: \"ibuf\" :: \"row\" :: \"ilen\" :: \"ipos\"\n    :: cdatasOf pr ++ cursorsOf pr.\n  Definition lvars := \"buf\" :: \"len\" :: \"obuf\" :: \"olen\" :: \"q\" :: preLvars.\n\n  Definition db := starL (fun t => RelDb.table (Schema t) (Address t)).\n\n  Variable httpq : W -> HProp.\n  Notation http p := (Ex q, p =*> q * httpq q)%Sep.\n\n  Definition mainS ts := SPEC(\"buf\", \"len\", \"obuf\", \"olen\", \"q\") reserving reserved\n    Al bsI, Al bsO,\n    PRE[V] db ts * http (V \"q\")\n      * array8 bsI (V \"buf\") * array8 bsO (V \"obuf\") * mallocHeap 0\n      * [| length bsI = wordToNat (V \"len\") |]\n      * [| length bsO = wordToNat (V \"olen\") |]\n    POST[R] db ts * http (V \"q\")\n      * Ex bsO', array8 bsI (V \"buf\") * array8 bsO' (V \"obuf\") * mallocHeap 0\n      * [| length bsO' = length bsO |] * [| R <= V \"olen\" |].\n\n  Lemma string_eq_true : forall s1 s2,\n    string_eq s1 s2 = false -> s1 <> s2.\n    intros; intro; subst; rewrite string_eq_true in *; discriminate.\n  Qed.\n\n  Lemma member_means : forall x ls,\n    if member x ls then In x ls else ~In x ls.\n    induction ls; simpl; intuition.\n    generalize (@string_eq_false x a), (@string_eq_true x a).\n    destruct (string_eq x a); simpl; intuition.\n    destruct (member x ls); eauto.\n    destruct (string_dec x a); subst; auto.\n    apply H in n; discriminate.\n    destruct (member x ls); eauto.\n    intuition.\n  Qed.\n\n  Hint Constructors NoDup.\n\n  Lemma NoDup_addTo : forall ls1 ls2, NoDup ls2\n    -> NoDup (addTo ls1 ls2).\n    induction ls1; simpl; intuition.\n    generalize (member_means a ls2); destruct (member a ls2); intuition.\n  Qed.    \n\n  Hint Immediate NoDup_addTo.\n\n  Lemma cdatas_distinct : forall ts, wf ts pr\n    -> NoDup (cdatasOf pr).\n    induction pr; simpl in *; intuition\n      eauto using allCdatas_NoDup, wf_NoDup, NoDup_addTo.\n  Qed.\n\n  Lemma In_addTo_or : forall x ls1 ls2,\n    In x (addTo ls1 ls2)\n    -> In x ls1 \\/ In x ls2.\n    clear; induction ls1; simpl; intuition.\n    generalize (member_means a ls2); destruct (member a ls2); intuition;\n      destruct (IHls1 _ H); simpl in *; intuition.\n  Qed.\n\n  Lemma append_underscore_free : forall suff suff' tab tab0,\n    underscore_free tab\n    -> underscore_free tab0\n    -> (tab0 ++ String \"_\" suff)%string = (tab ++ String \"_\" suff')%string\n    -> tab0 = tab.\n    induction tab; destruct tab0; simpl; intuition.\n    injection H1; clear H1; intros; subst.\n    f_equal; eauto.\n  Qed.\n\n  Lemma Forall_removeTable : forall P tab ts,\n    List.Forall P ts\n    -> List.Forall P (removeTable tab ts).\n    induction 1; simpl; intuition; ift.\n  Qed.\n\n  Hint Immediate Forall_removeTable.\n\n  Hint Immediate NoDup_unapp1 NoDup_unapp2.\n\n  Definition NoDups avs ts := NoDup (Names avs ++ Names ts).\n\n  Lemma NoDups_descend : forall tab t avs ts,\n    NoDups avs ts\n    -> In t ts\n    -> Name t = tab\n    -> NoDups (t :: avs) (removeTable tab ts).\n    clear; unfold NoDups; simpl; intros; subst.\n    constructor.\n    intro.\n    apply in_app_or in H1; intuition eauto using removeTable_contra.\n    eapply NoDups_unapp_cross in H; eauto.\n    apply H.\n    apply in_map; auto.\n    apply NoDups_app; eauto using NoDup_removeTable.\n    intros.\n    intro.\n    eapply NoDups_unapp_cross in H; eauto.\n  Qed.\n\n  Hint Immediate NoDups_descend.\n\n  Lemma Forall_removeTable' : forall P tab ts,\n    List.Forall P ts\n    -> List.Forall (fun t => Name t <> tab /\\ P t) (removeTable tab ts).\n    clear; induction 1; simpl; intuition; ift.\n  Qed.\n\n  Hint Immediate Forall_removeTable'.\n  \n  Lemma unusedTable : forall tab suff, underscore_free tab\n    -> forall xm avs ts,\n      xwf avs ts xm\n      -> NoDups avs ts\n      -> List.Forall (fun t => Name t <> tab /\\ underscore_free (Name t))%type ts\n      -> In (tab ++ String \"_\" suff)%string (allCursors_both' xm)\n      -> False.\n    clear; induction xm using xml_ind'; simpl; intuition.\n    assert (~In (tab ++ String \"_\" suff)%string nil) by (simpl; tauto).\n    generalize dependent (@nil string); induction H0; simpl in *; intuition.\n    eapply H6.\n    eauto.\n    intros.\n    apply In_addTo_or in H10; intuition eauto.\n\n    eapply append_underscore_free in H4; eauto.\n    subst.\n    destruct H0; intuition.\n    eapply Forall_forall in H2; [ | eassumption ]; tauto.\n    destruct H0; intuition.\n    eapply Forall_forall in H2; [ | eassumption ]; intuition congruence.\n\n    eapply append_underscore_free in H3; eauto.\n    subst.\n    destruct H0; intuition.\n    eapply Forall_forall in H2; [ | eassumption ]; tauto.\n    destruct H0; intuition.\n    eapply Forall_forall in H2; [ | eassumption ]; intuition congruence.\n\n    destruct H0; intuition eauto.\n\n    destruct H0, H5; intuition eauto.\n  Qed.\n\n  Lemma allCursors'_both_NoDup : forall xm avs ts,\n    xwf avs ts xm\n    -> NoDups avs ts\n    -> List.Forall (fun t => underscore_free (Name t)) ts\n    -> NoDup (allCursors_both' xm).\n    clear; induction xm using xml_ind'; simpl; intuition.\n    generalize (NoDup_nil string); generalize dependent (@nil string);\n      induction H; simpl in *; intuition.\n    destruct H; intuition.\n\n    constructor.\n    simpl; intuition.\n    apply append_inj in H6; discriminate.\n    eapply unusedTable; eauto.\n    eapply Forall_forall in H1; [ | eassumption ]; eauto.\n\n    constructor.\n    simpl; intuition.\n    eapply unusedTable; eauto.\n    eapply Forall_forall in H1; [ | eassumption ]; eauto.\n\n    eauto.\n\n    destruct H, H3; eauto.\n  Qed.\n\n  Hint Immediate allCursors'_both_NoDup.\n\n  Lemma allCursors_both_NoDup : forall a avs ts,\n    awf avs ts a\n    -> NoDups avs ts\n    -> List.Forall (fun t => underscore_free (Name t)) ts\n    -> NoDup (allCursors_both a).\n    clear; induction a; try solve [ simpl; intuition eauto using NoDup_addTo ].\n\n    simpl; intuition eauto using NoDup_addTo.\n    repeat constructor; simpl; intuition.\n    apply append_inj in H3; discriminate.\n\n    intros.\n    unfold allCursors_both; fold allCursors_both.\n    repeat apply NoDup_addTo.\n    do 2 post.\n    eauto.\n\n    intros.\n    unfold allCursors_both; fold allCursors_both.\n    repeat apply NoDup_addTo.\n    do 2 post.\n    eauto.\n  Qed.\n\n  Hint Immediate allCursors_both_NoDup.\n\n  Lemma cursorsOf_NoDup : forall ts p,\n    wf ts p\n    -> NoDup (Names ts)\n    -> List.Forall (fun t => underscore_free (Name t)) ts\n    -> NoDup (cursorsOf p).\n    induction p; simpl; intuition eauto.\n  Qed.\n\n  Ltac xomega := unfold preLvars, reserved, numCdatas, numCursors; simpl;\n    try rewrite app_length; omega.\n\n  Opaque mult.\n\n  Hint Extern 1 (@eq W _ _) => words.\n\n  Ltac reger := fold (@length string) in *;\n    repeat match goal with\n             | [ H : Regs _ _ = _ |- _ ] => rewrite H\n           end; try rewrite wplus_wminus; repeat rewrite <- mult4_S in *.\n\n  Ltac prelude :=\n    intros;\n      repeat match goal with\n               | [ H : _ |- _ ] =>\n                 eapply localsInvariant_inEx; [ | apply H ]; clear H; simpl; intros\n             end;\n      eapply (@localsInvariant_in preLvars); try eassumption; try reflexivity; try xomega;\n        try solve [ repeat constructor; simpl; intuition (try congruence; eauto) ];\n          (intros ? ? Hrew; repeat rewrite Hrew by (simpl; tauto); reflexivity).\n\n  Ltac varer n s :=\n    change (Sp + n)%loc with (Sp + variablePosition (\"rp\" :: lvars) s)%loc in *;\n      assert (In s (\"rp\" :: lvars)) by (simpl; tauto).\n\n  Definition avout := map (fun av => {| Table := av; Row := Name av ++ \"_row\";\n    Data := Name av ++ \"_data\" |}).\n\n  Definition cursors V avs := cursors V (avout avs).\n\n  Lemma cursors_sel : forall V avs, cursors (sel V) avs = cursors V avs.\n    auto.\n  Qed.\n\n  Ltac prep :=\n    post;\n    try match goal with\n          | [ st : (settings * state)%type |- _ ] => destruct st; simpl in *\n        end;\n    repeat match goal with\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[XmlOutput.cursors (sel ?V) ?x] |- _ ] => rewrite (XmlOutput.cursors_sel V x) in H\n             | [ |- context[XmlOutput.cursors (sel ?V) ?x] ] => rewrite (XmlOutput.cursors_sel V x)\n           end;\n    fold (@length string) in *; varer 52 \"stack\"; varer 8 \"len\"; varer 24 \"lex\"; varer 32 \"opos\";\n      varer 36 \"overflowed\"; varer 28 \"res\"; varer 24 \"q\";\n      try match goal with\n            | [ _ : context[Assign _ (RvLval (LvMem (Sp + natToW 0)%loc))] |- _ ] => varer 0 \"rp\"\n          end;\n      try match goal with\n            | [ H : context[Binop (LvReg Rv) (RvLval (LvReg Sp)) Plus (RvImm (natToW ?X))] |- _ ] =>\n              replace X with (S (S (S (S (4 * Datatypes.length lvars)))))%nat in * by xomega\n          end;\n      try match goal with\n            | [ H : context[locals _ _ ?X _] |- _ ] =>\n              replace X with 16 in * by xomega\n          end;\n      match goal with\n        | [ H : context[locals ?ns ?vs ?avail ?p]\n          |- context[locals ?ns' _ ?avail' _] ] =>\n        match avail' with\n          | avail => fail 1\n          | _ =>\n            let offset := constr:(S (S (S (S (4 * List.length lvars))))) in\n              change (locals ns vs avail p) with (locals_call ns vs avail p ns' avail' offset) in H;\n                assert (ok_call ns ns' avail avail' offset)%nat\n                  by (hnf; intuition; xomega || NoDup)\n        end\n        | [ _ : evalInstrs _ _ ?E = None, H : context[locals ?ns ?vs ?avail ?p] |- _ ] =>\n          let ns' := slotVariables E in\n            match ns' with\n              | nil => fail 1\n              | _ =>\n                let ns' := constr:(\"rp\" :: ns') in\n                  let offset := constr:(S (S (S (S (4 * List.length lvars))))) in\n                    change (locals ns vs avail p) with (locals_call ns vs avail p ns' 0 offset) in H;\n                      assert (ok_call ns ns' avail 0 offset)%nat by\n                        (hnf; intuition; xomega || NoDup)\n            end\n        | _ => idtac\n      end;\n      try match goal with\n            | [ _ : context[Binop (LvReg Rv) _ Plus (RvImm (natToW ?N))],\n              _ : context[locals_call _ _ _ _ _ _ ?M] |- _ ] => replace N with M in * by (simpl; omega)\n          end; try rewrite inBounds_sel in *; try rewrite inputOk_sel in *;\n      unfold lvalIn, regInL, immInR in *; prep_locals.\n  \n  Ltac my_descend := unfold localsInvariant in *;\n    repeat match goal with\n             | [ H : @In string _ _ |- _ ] => clear H\n           end;\n    try match goal with\n          | [ st : (settings * state)%type |- _ ] => destruct st; simpl in *\n        end;\n    descend; reger; try rewrite inBounds_sel in *; try rewrite inputOk_sel in *;\n      repeat match goal with\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[XmlOutput.cursors (sel ?V) ?x] |- _ ] => rewrite (XmlOutput.cursors_sel V x) in H\n               | [ |- context[XmlOutput.cursors (sel ?V) ?x] ] => rewrite (XmlOutput.cursors_sel V x)\n             end.\n\n  Ltac clear_fancier :=\n    repeat match goal with\n             | [ H : importsGlobal _ |- _ ] => clear dependent H\n           end;\n    repeat match goal with\n             | [ H : LabelMap.find _ _ = _ |- _ ] => clear H\n           end.\n\n  Ltac my_evaluate := clear_fancier; evaluate SinglyLinkedList.hints.\n\n  Ltac funcall :=\n    let considerImp pre post :=\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\n                      end\n                  end\n              end\n          end\n      end;\n      progress cancel SinglyLinkedList.hints in\n        match goal with\n          | [ |- interp _ (?pre ---> ?post)%PropX ] => considerImp pre post\n        end.\n\n  Ltac my_step := funcall || step SinglyLinkedList.hints.\n\n  Ltac invoke1 :=\n    match goal with\n      | [ H : interp _ _, H' : _ |- _ ] => apply H' in H; clear H'\n      | [ H : LabelMap.find _ _ = Some _ |- _ ] => rewrite H; post\n    end.\n\n  Ltac post := PreAutoSep.post;\n    try match goal with\n          | [ H : context[findTable] |- _ ] =>\n            PreAutoSep.post; erewrite findTable_good in H by eauto; PreAutoSep.post\n        end.\n\n  Ltac match_locals :=\n    MoreArrays.match_locals;\n      try match goal with\n            | [ _ : sel ?V \"opos\" <= sel ?V \"olen\" |- context[?U < sel ?V \"opos\" -> False] ] =>\n              equate U (sel V \"olen\")\n          end.\n\n  Ltac t' := post; repeat invoke1; prep; my_evaluate; my_descend; try match_locals;\n    repeat (my_step; my_descend); eauto.\n\n  Lemma freeVar_compile' : forall x p,\n    freeVar p x\n    -> In (x ++ \"_start\", x ++ \"_len\")%string (XmlSearch.allCdatas (compilePat p)).\n    induction p; simpl; intuition.\n  Qed.\n\n  Lemma freeVar_start : forall x p,\n    freeVar p x\n    -> In (x ++ \"_start\")%string (allCdatas_both p).\n    induction p; simpl; intuition.\n  Qed.\n\n  Lemma freeVar_len : forall x p,\n    freeVar p x\n    -> In (x ++ \"_len\")%string (allCdatas_both p).\n    induction p; simpl; intuition.\n  Qed.\n\n  Hint Immediate freeVar_start freeVar_len.\n\n  Ltac easy :=\n    try match goal with\n          | [ H : XmlOutput.freeVar _ _, H' : forall start len : string, _ |- _ ] =>\n            apply H' in H; post; subst\n        end;\n    solve [ hnf; simpl in *; intuition (subst; try congruence;\n      eauto using freeVar_compile', freeVar_start, freeVar_len) ].\n\n  Ltac pre :=\n    repeat match goal with\n             | [ |- context[vcs] ] => wrap0\n           end.\n\n  Hint Resolve no_clash' Forall_app.\n\n  Lemma xall_underscore : forall p,\n    List.Forall (fun p => not (underscore_free (fst p)) /\\ not (underscore_free (snd p)))\n    (XmlSearch.allCdatas (compilePat p)).\n    induction p; simpl; intuition eauto.\n  Qed.\n\n  Lemma inBounds_swizzle : forall V V' p,\n    (forall x, x <> \"overflowed\" -> x <> \"opos\" -> sel V x = sel V' x)\n    -> XmlSearch.inBounds (XmlSearch.allCdatas (compilePat p)) V\n    -> XmlSearch.inBounds (XmlSearch.allCdatas (compilePat p)) V'.\n    intros.\n    rewrite <- inBounds_sel.\n    rewrite <- inBounds_sel in H0.\n    eapply Forall_impl2; [ apply H0 | apply xall_underscore | ].\n    simpl; intuition; match goal with\n                        | [ x : (string * string)%type |- _ ] => destruct x; simpl in *\n                      end.\n    repeat rewrite H in * by (intro; subst; simpl in *; intuition congruence).\n    auto.\n  Qed.\n\n  Hint Immediate inBounds_swizzle.\n\n  Lemma underscore_discrim : forall s1 s2,\n    s1 = s2\n    -> ~underscore_free s1\n    -> underscore_free s2\n    -> False.\n    intros; congruence.\n  Qed.\n\n  Lemma underscore_free_app_contra : forall s1 s2,\n    underscore_free (s1 ++ String \"_\" s2)\n    -> False.\n    clear; induction s1; simpl; intuition eauto.\n  Qed.\n\n  Lemma underscore_mid_discrim : forall s2 s2',\n    underscore_free s2\n    -> underscore_free s2'\n    -> forall s1 s1', (s1 ++ String \"_\" s2)%string = (s1' ++ String \"_\" s2')%string\n      -> s2 = s2'.\n    clear; induction s1; destruct s1'; simpl; intuition;\n      injection H1; clear H1; intros; subst; simpl in *; eauto;\n        exfalso; eauto using underscore_free_app_contra.\n  Qed.\n\n  Lemma Exists_map : forall A B (f : A -> B) (P : B -> Prop) ls,\n    List.Exists P (map f ls)\n    -> List.Exists (fun x => P (f x)) ls.\n    induction ls; inversion 1; subst; auto.\n  Qed.\n\n  Lemma Forall_Exists : forall A (P Q : A -> Prop) ls,\n    List.Forall P ls\n    -> List.Exists Q ls\n    -> exists x, P x /\\ Q x /\\ In x ls.\n    induction 1; inversion 1; subst; simpl; intuition eauto;\n      match goal with\n        | [ H : Logic.ex _ |- _ ] => destruct H; intuition eauto\n      end.\n  Qed.\n\n  Lemma Exists_In : forall A (P : A -> Prop) x ls,\n    In x ls\n    -> P x\n    -> List.Exists P ls.\n    induction ls; simpl; intuition.\n  Qed.\n\n  Lemma compileXml_bindsRowVar : forall rw data xm,\n    XmlOutput.bindsRowVar (compileXml xm) (rw, data)\n    -> exists tab, xbindsRowVar xm tab\n      /\\ rw = (tab ++ \"_row\")%string\n      /\\ data = (tab ++ \"_data\")%string.\n    induction xm using xml_ind'; simpl; intuition;\n      try match goal with\n            | [ H : (_, _) = (_, _) |- _ ] => injection H; clear H; intros; subst\n          end; eauto.\n\n    apply ExistsR_Exists in H0; apply Exists_map in H0.\n    eapply Forall_Exists in H; eauto.\n    destruct H; intuition; match goal with\n                             | [ H : Logic.ex _ |- _ ] => destruct H; intuition eauto\n                           end.\n    subst.\n    descend; eauto.\n    eapply Exists_ExistsR.\n    eapply Exists_In; eauto.\n\n    post; eauto.\n  Qed.\n\n  Lemma underscore_free_bindsRowVar : forall s xm,\n    underscore_free s\n    -> (forall rw data, XmlOutput.bindsRowVar (compileXml xm) (rw, data)\n      -> s <> rw /\\ s <> data).\n    intros;\n      match goal with\n        | [ H : _ |- _ ] =>\n          apply compileXml_bindsRowVar in H; post; subst; eauto\n      end.\n  Qed.\n\n  Ltac und := solve [ intuition congruence\n    | eauto 2\n    | intro Ho; apply underscore_mid_discrim in Ho; auto; discriminate\n    | intro; eapply underscore_discrim; try eassumption; solve [ eauto ]\n    | intro; eapply underscore_discrim; try (symmetry; eassumption); solve [ eauto ]\n    | apply underscore_free_bindsRowVar; solve [ auto ] ].\n\n  Ltac prove_irrel := clear_fancier;\n    repeat match goal with\n             | [ V : vals |- _ ] =>\n               match goal with\n                 | [ |- context[V ?x] ] => change (V x) with (sel V x)\n               end\n           end;\n    match goal with\n      | [ H : forall x : string, _ |- _ ] =>\n        match type of H with\n          | context[sel] =>\n            repeat rewrite H by und\n        end\n    end; reflexivity || cancel auto_ext; solve [ eauto ].\n\n  Ltac t := easy || prelude || prove_irrel || t'.\n\n  Lemma stackOk_nil : forall len, stackOk nil len.\n    constructor.\n  Qed.\n\n  Hint Immediate stackOk_nil.\n\n  Lemma freeVar_all : forall x p,\n    freeVar p x\n    -> In x (allCdatas p).\n    induction p; simpl; intuition.\n  Qed.\n\n  Hint Extern 1 (_ <= _)%nat =>\n    match goal with\n      | [ H : inBounds _ _ |- _ ] => eapply Forall_forall in H; [ | eauto using freeVar_compile' ]\n    end.\n\n  Hint Extern 1 (NoDup (_ :: _)) => repeat constructor; simpl; intuition injy.\n\n\n  Opaque mult.\n\n  Hint Constructors unit.\n  Hint Immediate freeVar_compile'.\n\n  Lemma Forall_map : forall A B (f : A -> B) (P : B -> Prop) ls,\n    List.Forall (fun x => P (f x)) ls\n    -> List.Forall P (map f ls).\n    induction 1; simpl; auto.\n  Qed.\n\n  Fixpoint cdatasOf' (pr : program) : list string :=\n    match pr with\n      | Rule p _ => allCdatas p\n      | PSeq pr1 pr2 => addTo (cdatasOf' pr1) (cdatasOf' pr2)\n    end.\n\n  Definition cdataify := map (fun s => (s ++ \"_start\", s ++ \"_len\"))%string.\n\n  Lemma dontTouch_cdataify : forall tab cds,\n    dontTouch (tab ++ \"_row\") (tab ++ \"_data\") (cdataify cds).\n    clear; induction cds; simpl; intuition;\n      apply underscore_mid_discrim in H; intuition.\n  Qed.\n\n  Hint Immediate dontTouch_cdataify.\n\n  Lemma NoDups_dontReuse : forall x ts avs,\n    NoDups avs ts\n    -> In x ts\n    -> dontReuse (Name x ++ \"_row\") (Name x ++ \"_data\") (avout avs).\n    clear; induction avs; simpl; intuition.\n\n    apply append_inj' in H1.\n    hnf in H; simpl in H.\n    inversion_clear H.\n    apply H2.\n    rewrite H1.\n    eapply in_or_app; right.\n    apply in_map; auto.\n\n    apply underscore_mid_discrim in H1; simpl; intuition.\n    apply underscore_mid_discrim in H1; simpl; intuition.\n\n    apply append_inj' in H1.\n    hnf in H; simpl in H.\n    inversion_clear H.\n    apply H2.\n    rewrite H1.\n    eapply in_or_app; right.\n    apply in_map; auto.\n\n    inversion_clear H.\n    eauto.\n  Qed.\n\n  Hint Immediate NoDups_dontReuse.\n\n  Lemma wfExp_compileExp : forall ns e,\n    ewf e\n    -> (forall text, efreeVar e text\n      -> In (text ++ \"_start\")%string ns)\n    -> (forall text, efreeVar e text\n      -> In (text ++ \"_len\")%string ns)\n    -> wfExp ns (compileExp e).\n    destruct e; simpl; intuition eauto 4 using underscore_discrim.\n  Qed.\n\n  Hint Resolve wfExp_compileExp.\n\n  Lemma allCdatas_start : forall x p,\n    In x (allCdatas p)\n    -> In (x ++ \"_start\")%string (allCdatas_both p).\n    induction p; simpl; intuition;\n      apply in_app_or in H; intuition.\n  Qed.\n\n  Hint Immediate allCdatas_start.\n\n  Lemma In_addTo2 : forall x ls1 ls2,\n    In x ls2\n    -> In x (addTo ls1 ls2).\n    induction ls1; simpl; intuition.\n    destruct (member a ls2).\n    eauto.\n    apply IHls1.\n    simpl; tauto.\n  Qed.\n\n  Lemma In_addTo1 : forall x ls1 ls2,\n    In x ls1\n    -> In x (addTo ls1 ls2).\n    induction ls1; simpl; intuition.\n    generalize (member_means a ls2); destruct (member a ls2); intuition.\n    subst; eauto using In_addTo2.\n    subst; apply In_addTo2; simpl; tauto.\n  Qed.\n\n  Hint Immediate In_addTo1 In_addTo2.\n\n  Lemma cdatasOf'_start : forall x p,\n    In x (cdatasOf' p)\n    -> In (x ++ \"_start\")%string (cdatasOf p).\n    induction p; simpl; eauto.\n    intros.\n    apply In_addTo_or in H; intuition.\n  Qed.\n\n  Hint Resolve cdatasOf'_start in_or_app.\n\n  Lemma allCdatas_len : forall x p,\n    In x (allCdatas p)\n    -> In (x ++ \"_len\")%string (allCdatas_both p).\n    induction p; simpl; intuition;\n      apply in_app_or in H; intuition.\n  Qed.\n\n  Hint Immediate allCdatas_len.\n\n  Lemma cdatasOf'_len : forall x p,\n    In x (cdatasOf' p)\n    -> In (x ++ \"_len\")%string (cdatasOf p).\n    induction p; simpl; eauto.\n    intros.\n    apply In_addTo_or in H; intuition.\n  Qed.\n\n  Hint Resolve cdatasOf'_len.\n\n  Lemma In_cdataify : forall text cds,\n    In text cds\n    -> In ((text ++ \"_start\")%string, (text ++ \"_len\")%string) (cdataify cds).\n    clear; induction cds; simpl; intuition.\n  Qed.\n\n  Hint Resolve In_cdataify.\n\n  Lemma exp_wf : forall ns cds e,\n    ewf e\n    -> (forall x, efreeVar e x -> In (x ++ \"_start\")%string ns)\n    -> (forall x, efreeVar e x -> In (x ++ \"_len\")%string ns)\n    -> (forall x, efreeVar e x -> In (x ++ \"_start\", x ++ \"_len\")%string cds)\n    -> XmlOutput.ewf ns cds (compileExp e).\n    clear; destruct e; simpl; intuition (eauto 4 using underscore_discrim; eauto).\n  Qed.\n\n  Lemma eq_wf : forall ns sch cds x,\n    eqwf sch x\n    -> (forall y, efreeVar (snd x) y -> In (y ++ \"_start\")%string ns)\n    -> (forall y, efreeVar (snd x) y -> In (y ++ \"_len\")%string ns)\n    -> (forall y, efreeVar (snd x) y -> In (y ++ \"_start\", y ++ \"_len\")%string cds)\n    -> XmlOutput.eqwf ns sch cds (compileEquality x).\n    intros; hnf in *; intuition; apply exp_wf; auto.\n  Qed.\n\n  Hint Resolve eq_wf.\n\n  Lemma cond_wf : forall ns cds sch cond,\n    cwf sch cond\n    -> (forall x, List.Exists (fun e => efreeVar (snd e) x) cond -> In (x ++ \"_start\")%string ns)\n    -> (forall x, List.Exists (fun e => efreeVar (snd e) x) cond -> In (x ++ \"_len\")%string ns)\n    -> (forall x, List.Exists (fun e => efreeVar (snd e) x) cond\n      -> In (x ++ \"_start\", x ++ \"_len\")%string cds)\n    -> XmlOutput.cwf ns sch cds (compileCondition cond).\n    clear; unfold cwf, XmlOutput.cwf; induction 1; simpl; intuition.\n  Qed.\n\n  Hint Resolve cond_wf.\n\n  Lemma In_removeTable' : forall x y ts,\n    In x (removeTable y ts)\n    -> In x ts.\n    clear; induction ts; simpl; intuition.\n    destruct (string_dec y (Name a)); subst; simpl in *; intuition.\n  Qed.\n\n  Hint Immediate In_removeTable'.\n\n  Fixpoint abindsRowVar (a : action) (x : string) : Prop :=\n    match a with\n      | Insert _ _ => False\n      | Delete tab _ => x = tab\n      | Output xm => xbindsRowVar xm x\n      | Seq a1 a2 => abindsRowVar a1 x \\/ abindsRowVar a2 x\n      | IfExists tab _ _then _else => x = tab\n        \\/ abindsRowVar _then x \\/ abindsRowVar _else x\n      | Halt => False\n      | Select tab cond inner => x = tab \\/ abindsRowVar inner x\n      | SendTo url data => xbindsRowVar url x \\/ xbindsRowVar data x\n    end.\n\n  Fixpoint bindsRowVar (pr : program) (x : string) : Prop :=\n    match pr with\n      | Rule _ a => abindsRowVar a x\n      | PSeq pr1 pr2 => bindsRowVar pr1 x \\/ bindsRowVar pr2 x\n    end.\n\n  Lemma output_wf : forall ns cds xm avs ts,\n    xwf avs ts xm\n    -> NoDups avs ts\n    -> (forall x, xfreeVar xm x -> In (x ++ \"_start\")%string ns)\n    -> (forall x, xfreeVar xm x -> In (x ++ \"_len\")%string ns)\n    -> (forall t, In t avs -> In (Name t ++ \"_data\")%string ns)\n    -> (forall tab, xbindsRowVar xm tab -> In (tab ++ \"_data\")%string ns)\n    -> (forall x, xfreeVar xm x -> In (x ++ \"_start\", x ++ \"_len\")%string (cdataify cds))\n    -> XmlOutput.wf ns (cdataify cds) (avout avs) ts (compileXml xm).\n    induction xm using xml_ind'; simpl; intuition idtac;\n      try match goal with\n            | [ H : _ |- _ ] => apply append_inj in H; discriminate\n          end; eauto 4 using underscore_discrim.\n\n    induction H; simpl in *; intuition.\n\n    destruct H; intuition subst.\n    do 2 esplit.\n    eapply in_map in H6; eauto.\n    simpl; intuition eauto using in_or_app.\n\n    destruct H; intuition (subst; eauto).\n\n    destruct H; intuition subst.\n    descend; eauto 8.\n    eapply IHxm in H9; eauto;\n      (simpl; intuition (subst; eauto)).\n\n    destruct H; intuition subst.\n    do 2 esplit.\n    eapply in_map in H8; eauto.\n    simpl; intuition eauto using in_or_app.\n\n    destruct H7; intuition subst.\n    do 2 esplit.\n    eapply in_map in H8; eauto.\n    simpl; intuition eauto using in_or_app.\n  Qed.\n\n  Hint Immediate output_wf.\n\n  Ltac discrim :=\n    match goal with\n      | _ => eapply underscore_discrim; solve [ eauto ]\n      | _ => eapply underscore_discrim; try symmetry; solve [ eauto ]\n      | [ H : _ |- _ ] => apply append_inj in H; discriminate\n      | [ H : _ |- _ ] => apply underscore_mid_discrim in H; try discriminate; solve [ eauto ]\n    end.\n\n\n  (** ** Action compilation *)\n\n  Variable bufSize : W.\n\n  Hypothesis buf_size_lower : bufSize >= natToW 2.\n  Hypothesis buf_size_upper : goodSize (4 * wordToNat bufSize).\n\n  Section compileAction.\n    Variable p : pat.\n\n    Infix \";;\" := SimpleSeq : SP_scope.\n\n    Fixpoint compileAction' (avs ts ts' : tables) (a : action) : chunk :=\n      match a with\n        | Insert tab es =>\n          match findTable tab ts with\n            | None => Fail\n            | Some t => RelDbInsert.Insert\n              (fun bsO V => cursors V avs * db (removeTable tab ts) * http (V \"q\")\n                * array8 bsO (V \"obuf\")\n                * [| length bsO = wordToNat (V \"olen\") |]\n                * [| V \"opos\" <= V \"olen\" |]%word\n                * [| XmlOutput.inBounds (XmlSearch.allCdatas (compilePat p)) V |]\n                * xmlp (V \"len\") (V \"lex\")\n                * Ex ls, sll ls (V \"stack\") * [| stackOk ls (V \"len\") |])%Sep\n              (fun bsO V R => db ts' * http (V \"q\")\n                * [| R <= V \"olen\" |]%word * mallocHeap 0\n                * Ex bsO', array8 bsO' (V \"obuf\")\n                * [| length bsO' = length bsO |])%Sep\n              (Address t) (Schema t) bufSize (compileExps es)\n          end\n\n        | Delete tab cond =>\n          match findTable tab ts with\n            | None => Fail\n            | Some t => RelDbDelete.Delete\n              (fun bsO V => cursors V avs * db (removeTable tab ts) * http (V \"q\")\n                * array8 bsO (V \"obuf\")\n                * [| length bsO = wordToNat (V \"olen\") |]\n                * [| V \"opos\" <= V \"olen\" |]%word\n                * [| XmlOutput.inBounds (XmlSearch.allCdatas (compilePat p)) V |]\n                * xmlp (V \"len\") (V \"lex\")\n                * Ex ls, sll ls (V \"stack\") * [| stackOk ls (V \"len\") |])%Sep\n              (fun bsO V R => db ts' * http (V \"q\")\n                * [| R <= V \"olen\" |]%word * mallocHeap 0\n                * Ex bsO', array8 bsO' (V \"obuf\")\n                * [| length bsO' = length bsO |])%Sep\n              (Address t) (Schema t) (tab ++ \"_row\") (tab ++ \"_data\") (compileCondition cond)\n          end\n\n        | Output xm =>\n          Out\n          (fun (_ : unit) V => http (V \"q\") * mallocHeap 0 * xmlp (V \"len\") (V \"lex\")\n            * Ex ls, sll ls (V \"stack\") * [| stackOk ls (V \"len\") |])%Sep\n          (fun _ V R => db ts' * http (V \"q\")\n            * [| R <= V \"olen\" |]%word * mallocHeap 0)%Sep\n          (XmlSearch.allCdatas (compilePat p))\n          (avout avs) ts\n          (compileXml xm)\n\n        | Seq a1 a2 =>\n          compileAction' avs ts ts' a1;;\n          compileAction' avs ts ts' a2\n\n        | IfExists tab cond _then _else =>\n          match findTable tab ts with\n            | None => Fail\n            | Some t =>\n              \"res\" <- 0;;\n              RelDbSelect.Select\n              (fun bsO V => cursors V avs * db (removeTable tab ts) * http (V \"q\")\n                * array8 bsO (V \"obuf\")\n                * [| length bsO = wordToNat (V \"olen\") |]\n                * [| V \"opos\" <= V \"olen\" |]%word\n                * [| XmlOutput.inBounds (XmlSearch.allCdatas (compilePat p)) V |]\n                * xmlp (V \"len\") (V \"lex\") * mallocHeap 0\n                * Ex ls, sll ls (V \"stack\") * [| stackOk ls (V \"len\") |])%Sep\n              (fun bsO V R => db ts' * http (V \"q\")\n                * [| R <= V \"olen\" |]%word * mallocHeap 0\n                * Ex bsO', array8 bsO' (V \"obuf\")\n                * [| length bsO' = length bsO |])%Sep\n              (Address t) (Schema t) (tab ++ \"_row\") (tab ++ \"_data\")\n              (compileCondition cond)\n              (\"res\" <- 1);;\n\n              If (\"res\" = 1) {\n                compileAction' avs ts ts' _then\n              } else {\n                compileAction' avs ts ts' _else\n              }\n          end\n\n        | Halt =>\n          Call \"sys\"!\"abort\"()\n          [PREonly[_] [| False |] ];;\n          Fail\n\n        | Select tab cond inner =>\n          match findTable tab ts with\n            | None => Fail\n            | Some t =>\n              RelDbSelect.Select\n              (fun bsO V => cursors V avs * db (removeTable tab ts) * http (V \"q\")\n                * array8 bsO (V \"obuf\")\n                * [| length bsO = wordToNat (V \"olen\") |]\n                * [| V \"opos\" <= V \"olen\" |]%word\n                * [| XmlOutput.inBounds (XmlSearch.allCdatas (compilePat p)) V |]\n                * xmlp (V \"len\") (V \"lex\") * mallocHeap 0\n                * Ex ls, sll ls (V \"stack\") * [| stackOk ls (V \"len\") |])%Sep\n              (fun bsO V R => db ts' * http (V \"q\")\n                * [| R <= V \"olen\" |]%word * mallocHeap 0\n                * Ex bsO', array8 bsO' (V \"obuf\")\n                * [| length bsO' = length bsO |])%Sep\n              (Address t) (Schema t) (tab ++ \"_row\") (tab ++ \"_data\")\n              (compileCondition cond)\n              (compileAction' (t :: avs) (removeTable tab ts) ts' inner)\n          end\n\n        | SendTo url data =>\n          (* Reset output, since we'll produce a new one to send now. *)\n          \"opos\" <- 0;;\n\n          (* Next, write the target URL at the start. *)\n          Out\n          (fun (_ : unit) V => http (V \"q\") * mallocHeap 0 * xmlp (V \"len\") (V \"lex\")\n            * Ex ls, sll ls (V \"stack\") * [| stackOk ls (V \"len\") |])%Sep\n          (fun _ V R => db ts' * http (V \"q\")\n            * [| R <= V \"olen\" |]%word * mallocHeap 0)%Sep\n          (XmlSearch.allCdatas (compilePat p))\n          (avout avs) ts\n          (compileXml url);;\n\n          (* Now write a '\\0' character as a delimiter. *)\n          Out\n          (fun (_ : unit) V => http (V \"q\") * mallocHeap 0 * xmlp (V \"len\") (V \"lex\")\n            * Ex ls, sll ls (V \"stack\") * [| stackOk ls (V \"len\") |])%Sep\n          (fun _ V R => db ts' * http (V \"q\")\n            * [| R <= V \"olen\" |]%word * mallocHeap 0)%Sep\n          (XmlSearch.allCdatas (compilePat p))\n          (avout avs) ts\n          (XmlOutput.Cdata (String (ascii_of_nat 0) \"\"));;\n\n          (* Finally, write the payload. *)\n          Out\n          (fun (_ : unit) V => http (V \"q\") * mallocHeap 0 * xmlp (V \"len\") (V \"lex\")\n            * Ex ls, sll ls (V \"stack\") * [| stackOk ls (V \"len\") |])%Sep\n          (fun _ V R => db ts' * http (V \"q\")\n            * [| R <= V \"olen\" |]%word * mallocHeap 0)%Sep\n          (XmlSearch.allCdatas (compilePat p))\n          (avout avs) ts\n          (compileXml data);;\n\n          (* Save this request in the HTTP queue. *)\n          \"res\" <-* \"q\";;\n          \"res\" <-- Call \"httpq\"!\"save\"(\"res\", \"obuf\", \"opos\")\n          [Al bsI, Al bsO, Al ls,\n            PRE[V, R'] db ts * V \"q\" =?> 1 * httpq R'\n              * array8 bsI (V \"buf\") * array8 bsO (V \"obuf\") * mallocHeap 0\n              * xmlp (V \"len\") (V \"lex\") * cursors V avs\n              * sll ls (V \"stack\") * [| stackOk ls (V \"len\") |]\n              * [| length bsI = wordToNat (V \"len\") |]\n              * [| length bsO = wordToNat (V \"olen\") |]\n              * [| V \"opos\" <= V \"olen\" |]%word\n              * [| XmlOutput.inBounds (XmlSearch.allCdatas (compilePat p)) V |]\n            POST[R] db ts' * http (V \"q\")\n              * Ex bsO', array8 bsI (V \"buf\") * array8 bsO' (V \"obuf\") * mallocHeap 0\n              * [| length bsO' = length bsO |] * [| R <= V \"olen\" |]%word ];;\n\n          \"q\" *<- \"res\";;\n          \"opos\" <- 0\n      end%SP.\n\n    Definition ainv avs ts ts' :=\n      XmlSearch.inv (fun bsO V => cursors V avs * db ts * http (V \"q\")\n        * array8 bsO (V \"obuf\")\n        * [| length bsO = wordToNat (V \"olen\") |]\n        * [| V \"opos\" <= V \"olen\" |]%word)%Sep\n      (fun bsO V R => db ts' * http (V \"q\")\n        * Ex bsO', array8 bsO' (V \"obuf\")\n        * [| length bsO' = length bsO |]\n        * [| R <= V \"olen\" |]%word)%Sep\n      (XmlSearch.allCdatas (compilePat p)).\n\n    Lemma 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      sepLemma; etransitivity; [ | apply removeTable_bwd ]; eauto; sepLemma.\n    Qed.\n\n    Lemma removeTable_fwd' : forall x ts P,\n      NoDup (Names ts)\n      -> In x ts\n      -> db ts * P\n      ===> P * (RelDb.table (Schema x) (Address x) * db (removeTable (Name x) ts)).\n      sepLemma; etransitivity; [ apply removeTable_fwd | ]; eauto; sepLemma.\n    Qed.\n\n    Lemma cursors_intro : forall V av avs P,\n      row (Schema av) (sel V (Name av ++ \"_data\"))\n      * (inv (Address av) (Schema av) (sel V (Name av ++ \"_row\"))\n        (sel V (Name av ++ \"_data\"))\n        * (cursors V avs * P))\n      ===> P * (cursors V (av :: avs)).\n      clear; sepLemma.\n      unfold cursors; simpl; unfold cursor; simpl.\n      repeat match goal with\n               | [ |- context[V ?x] ] => change (V x) with (sel V x)\n             end.\n      sepLemma.\n    Qed.\n\n    Lemma cursors_elim : forall V av avs P,\n      cursors V (av :: avs) * P\n      ===> P * (inv (Address av) (Schema av) (sel V (Name av ++ \"_row\"))\n        (sel V (Name av ++ \"_data\"))\n        * (row (Schema av) (sel V (Name av ++ \"_data\")) * cursors V avs)).\n      clear; sepLemma.\n      unfold cursors; simpl; unfold cursor; simpl.\n      repeat match goal with\n               | [ |- context[V ?x] ] => change (V x) with (sel V x)\n             end.\n      sepLemma.\n    Qed.\n\n    Lemma Weaken_cursors : forall V V',\n      (forall x, x <> \"ibuf\" -> x <> \"row\" -> x <> \"ilen\"\n        -> x <> \"tmp\" -> x <> \"ipos\" -> x <> \"overflowed\"\n        -> x <> \"opos\" -> x <> \"matched\" -> x <> \"res\"\n        -> sel V x = sel V' x)\n      -> forall avs, cursors V avs ===> cursors V' avs.\n      unfold cursors; clear; induction avs; simpl; intuition.\n      sepLemma.\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\n                  by eauto 4 using underscore_discrim\n              end; apply Himp_refl.\n    Qed.\n\n    Hint Extern 1 (himp _ (cursors _ _) (cursors _ _)) => apply Weaken_cursors.\n\n    Ltac cap' :=\n      ((apply removeTable_bwd' || apply removeTable_fwd'\n        || apply cursors_intro || apply cursors_elim); eauto)\n      || apply himp_star_comm\n      || (etransitivity; [ | apply himp_star_frame; [ | apply removeTable_bwd ] ]; assumption || my_step)\n      || (etransitivity; [ apply himp_star_frame; [ apply removeTable_fwd | ] | ]; eassumption || my_step)\n      || (apply himp_star_frame; try reflexivity; apply Weaken_cursors; solve [ descend ])\n      || my_step.\n\n    Ltac cap := abstract (t; cap').\n\n    Lemma inBounds_swizzle''' : forall V V' p,\n      (forall x, x <> \"ibuf\" -> x <> \"ilen\" -> x <> \"tmp\"\n        -> x <> \"ipos\" -> x <> \"overflowed\" -> x <> \"matched\"\n        -> x <> \"res\" -> sel V x = sel V' x)\n      -> XmlOutput.inBounds (XmlSearch.allCdatas (compilePat p)) V\n      -> XmlOutput.inBounds (XmlSearch.allCdatas (compilePat p)) V'.\n      intros.\n      rewrite <- inBounds_sel.\n      rewrite <- inBounds_sel in H0.\n      eapply Forall_impl2; [ apply H0 | apply xall_underscore | ].\n      simpl; intuition; match goal with\n                          | [ x : (string * string)%type |- _ ] => destruct x; simpl in *\n                        end.\n      repeat rewrite H in * by (intro; subst; simpl in *; intuition congruence).\n      auto.\n    Qed.\n\n    Hint Immediate inBounds_swizzle'''.\n\n    Lemma inBounds_post : forall V v,\n      XmlOutput.inBounds (XmlSearch.allCdatas (compilePat p)) V\n      -> XmlOutput.inBounds (XmlSearch.allCdatas (compilePat p))\n      (upd V \"res\" v).\n      intros; eapply inBounds_swizzle'''; [ | eauto ]; descend.\n    Qed.\n\n    Hint Immediate inBounds_post.\n\n    Lemma inBounds_swizzle_post : forall V V' p,\n      (forall x, x <> \"res\" -> x <> \"opos\" -> sel V x = sel V' x)\n      -> XmlOutput.inBounds (XmlSearch.allCdatas (compilePat p)) V\n      -> XmlOutput.inBounds (XmlSearch.allCdatas (compilePat p)) V'.\n      intros.\n      rewrite <- inBounds_sel.\n      rewrite <- inBounds_sel in H0.\n      eapply Forall_impl2; [ apply H0 | apply xall_underscore | ].\n      simpl; intuition; match goal with\n                          | [ x : (string * string)%type |- _ ] => destruct x; simpl in *\n                        end.\n      repeat rewrite H in * by (intro; subst; simpl in *; intuition congruence).\n      auto.\n    Qed.\n\n    Lemma inBounds_post' : forall V v v',\n      XmlOutput.inBounds (XmlSearch.allCdatas (compilePat p)) V\n      -> XmlOutput.inBounds (XmlSearch.allCdatas (compilePat p))\n      (upd (upd V \"res\" v) \"opos\" v').\n      intros; eapply inBounds_swizzle_post; [ | eauto ]; descend.\n    Qed.\n\n    Hint Immediate inBounds_post'.\n\n    Lemma compileAction_post : forall im mn (H : importsGlobal im) ns res,\n      ~In \"rp\" ns\n      -> In \"res\" ns\n      -> In \"q\" ns\n      -> In \"opos\" ns\n      -> forall a avs ts ts' pre,\n        (forall specs st,\n          interp specs (pre st)\n          -> interp specs (ainv avs ts ts' true (fun x : W => x) ns res st))\n        -> awf avs ts a\n        -> NoDups avs ts\n        -> forall specs st, interp specs (Postcondition (toCmd\n          (compileAction' avs ts ts' a) mn H ns res pre) st)\n        -> interp specs (ainv avs ts ts' true (fun x : W => x) ns res st).\n      induction a.\n\n      cap.\n      cap.\n      cap.\n      cap.\n      cap.\n      cap.\n      cap.\n      cap.\n    Qed.\n\n    Lemma In_ExistsR : forall A (P : A -> Prop) x ls,\n      In x ls\n      -> P x\n      -> ExistsR P ls.\n      induction ls; simpl; intuition.\n    Qed.\n\n    Hint Immediate In_ExistsR.\n\n    Lemma compile_efreeVar' : forall e text,\n      XmlOutput.efreeVar (compileExp e) (text ++ \"_start\", text ++ \"_len\")%string\n      -> efreeVar e text.\n      clear; destruct e; simpl; intuition.\n      injection H; clear H; intros.\n      apply append_inj' in H; tauto.\n    Qed.\n\n    Lemma compile_efreeVar : forall e start len,\n      XmlOutput.efreeVar (compileExp e) (start, len)\n      -> exists text, efreeVar e text /\\ start = (text ++ \"_start\")%string\n        /\\ len = (text ++ \"_len\")%string.\n      clear; destruct e; simpl; intuition.\n      injection H; eauto.\n    Qed.\n\n    Lemma Exists_impl : forall A (P P' : A -> Prop) ls,\n      List.Exists P ls\n      -> (forall x, P x -> P' x)\n      -> List.Exists P' ls.\n      induction 1; simpl; intuition.\n    Qed.\n\n    Lemma Exists_exists : forall A B (P : A -> B -> Prop) ls,\n      List.Exists (fun x => exists y, P x y) ls\n      -> exists y, List.Exists (fun x => P x y) ls.\n      clear; induction 1; simp; eauto.\n    Qed.\n\n    Lemma Exists_conj2 : forall A (P : A -> Prop) Q R ls,\n      List.Exists (fun x => P x /\\ Q /\\ R) ls\n      -> List.Exists P ls /\\ Q /\\ R.\n      clear; induction 1; simp; eauto.\n    Qed.\n\n    Lemma compileXml_freeVar : forall start len xm,\n      XmlOutput.freeVar (compileXml xm) (start, len)\n      -> exists text, xfreeVar xm text\n        /\\ start = (text ++ \"_start\")%string\n        /\\ len = (text ++ \"_len\")%string.\n      induction xm using xml_ind'; simpl; intuition;\n        try match goal with\n              | [ H : (_, _) = (_, _) |- _ ] => injection H; clear H; intros; subst\n            end; eauto.\n\n      apply ExistsR_Exists in H0; apply Exists_map in H0.\n      eapply Forall_Exists in H; eauto.\n      destruct H; intuition; match goal with\n                               | [ H : Logic.ex _ |- _ ] => destruct H; intuition eauto\n                             end.\n\n      unfold compileCondition in H0.\n      eapply Exists_map in H0.\n      eapply (@Exists_impl _ _ (fun x => exists text, efreeVar (snd x) text\n        /\\ start = (text ++ \"_start\")%string /\\ len = (text ++ \"_len\")%string)) in H0; [\n          | auto using compile_efreeVar ].\n      apply Exists_exists in H0; destruct H0.\n      apply Exists_conj2 in H; intuition eauto.\n\n      post; eauto.\n    Qed.\n\n    Lemma compilePat_cdatas : forall p0,\n      cdatasGood (XmlSearch.allCdatas (compilePat p0)).\n      unfold cdatasGood; induction p0; simpl; intuition.\n      constructor; auto; simpl; intuition (eapply underscore_discrim; eauto).\n      constructor; auto; simpl; intuition (eapply underscore_discrim; eauto).\n    Qed.\n\n    Hint Immediate compilePat_cdatas.\n\n    Lemma inputOk_compileExps : forall V cdatas es,\n      XmlOutput.inBounds cdatas V\n      -> (forall text, List.Exists (fun e => efreeVar e text) es\n        -> In (text ++ \"_start\", text ++ \"_len\")%string cdatas)\n      -> inputOk V (compileExps es).\n      unfold inputOk, XmlOutput.inBounds; induction es; simpl; intuition.\n      constructor; auto.\n      destruct a; simpl; auto.\n      specialize (H0 text); match type of H0 with\n                              | ?P -> _ => assert P by (constructor; reflexivity)\n                            end; intuition.\n      eapply Forall_forall in H; try eassumption; assumption.\n    Qed.\n\n    Hint Immediate inputOk_compileExps.\n\n    Lemma inBounds_swizzle' : forall V V' p,\n      (forall x, x <> \"ibuf\" -> x <> \"row\"\n        -> x <> \"ilen\" -> x <> \"tmp\" -> x <> \"ipos\" -> x <> \"overflowed\" -> sel V x = sel V' x)\n      -> XmlOutput.inBounds (XmlSearch.allCdatas (compilePat p)) V\n      -> XmlOutput.inBounds (XmlSearch.allCdatas (compilePat p)) V'.\n      intros.\n      rewrite <- inBounds_sel.\n      rewrite <- inBounds_sel in H0.\n      eapply Forall_impl2; [ apply H0 | apply xall_underscore | ].\n      simpl; intuition; match goal with\n                          | [ x : (string * string)%type |- _ ] => destruct x; simpl in *\n                        end.\n      repeat rewrite H in * by (intro; subst; simpl in *; intuition congruence).\n      auto.\n    Qed.\n\n    Hint Immediate inBounds_swizzle'.\n\n    Lemma goodSize_more : forall t ts,\n      twfs ts\n      -> In t ts\n      -> goodSize (S (S (length (Schema t) + length (Schema t)))).\n      intros; eapply Forall_forall in H; eauto; eassumption.\n    Qed.\n\n    Hint Immediate goodSize_more.\n\n    Lemma underscore_discrim' : forall s1 s2,\n      s1 = s2\n      -> underscore_free s1\n      -> ~underscore_free s2\n      -> False.\n      intros; congruence.\n    Qed.\n\n    Lemma wfExps_compileExps : forall ns es,\n      ewfs es\n      -> (forall text, List.Exists (fun e => efreeVar e text) es\n        -> In (text ++ \"_start\")%string ns)\n      -> (forall text, List.Exists (fun e => efreeVar e text) es\n        -> In (text ++ \"_len\")%string ns)\n      -> wfExps ns (compileExps es).\n      unfold wfExps; induction 1; simpl; intuition.\n    Qed.\n\n    Hint Immediate wfExps_compileExps.\n\n    Lemma length_compileExps : forall es, length (compileExps es) = length es.\n      intros; apply map_length.\n    Qed.\n\n    Hint Rewrite length_compileExps : sepFormula.\n\n    Lemma goodSize_base : forall ts t,\n      twfs ts\n      -> In t ts\n      -> goodSize (length (Schema t)).\n      intros; eapply goodSize_weaken; [ eapply goodSize_more | ]; eauto.\n    Qed.\n\n    Hint Immediate goodSize_base.\n\n    Notation baseVars := (\"buf\" :: \"len\" :: \"lex\" :: \"res\"\n      :: \"tagStart\" :: \"tagLen\" :: \"matched\" :: \"stack\" :: \"level\" :: nil).\n\n    Notation \"l ~~ im ~~> s\" := (LabelMap.find l%SP im = Some (Precondition s None)) (at level 0).\n\n    Lemma inputOk_compileCondition : forall V cdatas cond,\n      XmlOutput.inBounds cdatas V\n      -> (forall text, List.Exists (fun e => efreeVar (snd e) text) cond\n        -> In (text ++ \"_start\", text ++ \"_len\")%string cdatas)\n      -> inputOk V (exps (compileCondition cond)).\n      unfold inputOk, XmlOutput.inBounds; induction cond; simpl; intuition.\n      constructor; auto.\n      destruct a; simpl in *.\n      destruct e; simpl; auto.\n      specialize (H0 text); match type of H0 with\n                              | ?P -> _ => assert P by (constructor; reflexivity)\n                            end; intuition.\n      eapply Forall_forall in H; try eassumption; assumption.\n    Qed.\n\n    Hint Resolve inputOk_compileCondition.\n\n    Lemma inBounds_swizzle'' : forall V V' p,\n      (forall x, x <> \"row\"\n        -> x <> \"ibuf\" -> x <> \"ilen\" -> x <> \"tmp\"\n        -> x <> \"ipos\" -> x <> \"overflowed\" -> x <> \"matched\"\n        -> sel V x = sel V' x)\n      -> XmlOutput.inBounds (XmlSearch.allCdatas (compilePat p)) V\n      -> XmlOutput.inBounds (XmlSearch.allCdatas (compilePat p)) V'.\n      intros.\n      rewrite <- inBounds_sel.\n      rewrite <- inBounds_sel in H0.\n      eapply Forall_impl2; [ apply H0 | apply xall_underscore | ].\n      simpl; intuition; match goal with\n                          | [ x : (string * string)%type |- _ ] => destruct x; simpl in *\n                        end.\n      repeat rewrite H in * by (intro; subst; simpl in *; intuition congruence).\n      auto.\n    Qed.\n\n    Hint Immediate inBounds_swizzle''.\n\n    Lemma wfEqualities_compileCondition : forall ns sch cond,\n      cwf sch cond\n      -> (forall text,\n        List.Exists (fun e => efreeVar (snd e) text) cond ->\n        In (text ++ \"_start\")%string ns)\n      -> (forall text,\n        List.Exists (fun e => efreeVar (snd e) text) cond ->\n        In (text ++ \"_len\")%string ns)\n      -> wfEqualities ns sch (compileCondition cond).\n      unfold wfEqualities; induction 1; simpl; auto.\n      constructor; auto.\n      hnf; simpl.\n      hnf in H.\n      intuition eauto 6.\n    Qed.\n\n    Hint Resolve wfEqualities_compileCondition.\n\n    Ltac step1 := wrap0;\n      try match goal with\n            | [ |- context[findTable] ] => post; post; erewrite findTable_good by eauto; wrap0\n          end;\n      try match goal with\n            | [ |- vcs (_ :: _) ] => wrap0\n          end.\n\n    Ltac t'' :=\n      post; repeat invoke1; prep; my_evaluate; my_descend;\n        try (match_locals;\n          repeat rewrite sel_upd_ne by (intro Ho; eapply underscore_discrim; [ symmetry; apply Ho\n            | intro; eapply underscore_free_app_contra; eassumption\n            | simpl; intuition discriminate ]); cbv beta; descend);\n        repeat (my_step; my_descend); eauto.\n\n    Ltac step2 := unfold saveGS, buffer in *;\n      try match goal with\n            | [ H : interp _ _ |- _ ] => apply compileAction_post in H; auto\n          end;\n      match goal with\n        | [ |- False ] => discrim\n        | _ => solve [ subst; eauto ]\n        | [ H : _ |- _ ] =>\n          apply compileXml_freeVar in H; post; subst; solve [\n            eauto | eapply proj1; eauto | eapply proj2; eauto ]\n        | [ H : _ |- _ ] =>\n          apply compileXml_freeVar in H; post; subst; solve [ eauto ]\n        | [ H : _ |- _ ] =>\n          apply compileXml_bindsRowVar in H; post; subst; solve [ eauto ]\n        | _ => cap\n        | _ => abstract t''\n        | _ => repeat (post; intuition idtac;\n          match goal with\n            | [ H : _ |- _ ] => apply H; auto;\n              try solve [ simpl; intuition subst; eauto ]\n          end; try (apply compileAction_post; auto)); cap\n      end.\n\n    Ltac cav := abstract (step1; step2).\n\n    Lemma xall_underscore' : forall p,\n      List.Forall (fun p => exists tab, p = (tab ++ \"_start\", tab ++ \"_len\")%string)\n      (XmlSearch.allCdatas (compilePat p)).\n      clear; induction p; simpl; intuition eauto.\n    Qed.\n\n    Lemma inBounds_swizzle'''' : forall V V' p tab,\n      (forall x, x <> (tab ++ \"_row\")%string -> x <> (tab ++ \"_data\")%string\n        -> x <> \"ibuf\" -> x <> \"ilen\" -> x <> \"tmp\" -> x <> \"ipos\" -> x <> \"overflowed\"\n        -> x <> \"matched\" -> x <> \"res\"\n        -> sel V x = sel V' x)\n      -> XmlOutput.inBounds (XmlSearch.allCdatas (compilePat p)) V\n      -> XmlOutput.inBounds (XmlSearch.allCdatas (compilePat p)) V'.\n      intros.\n      rewrite <- inBounds_sel.\n      rewrite <- inBounds_sel in H0.\n      eapply Forall_impl2; [ apply H0 | apply xall_underscore' | ].\n      post; subst; simpl in *.\n      repeat rewrite H in * by und.\n      auto.\n    Qed.\n\n    Hint Immediate inBounds_swizzle''''.\n    \n    Lemma Weaken_cursors_eauto : forall V V' t,\n      (forall x, x <> (Name t ++ \"_row\")%string\n        -> x <> (Name t ++ \"_data\")%string\n        -> x <> \"ibuf\" -> x <> \"ilen\"\n        -> x <> \"tmp\" -> x <> \"ipos\" -> x <> \"overflowed\"\n        -> x <> \"matched\" -> x <> \"res\"\n        -> sel V x = sel V' x)\n      -> forall ts avs, NoDups avs ts\n        -> In t ts\n        -> cursors V avs ===> cursors V' avs.\n      unfold cursors; clear; induction avs; simpl; intuition.\n      sepLemma.\n\n      inversion_clear H0.\n      assert ((Name a ++ \"_data\")%string <> (Name t ++ \"_data\")%string).\n      intro.\n      apply append_inj' in H0.\n      apply H2.\n      rewrite H0.\n      apply in_or_app; right.\n      apply in_map; auto.\n\n      assert ((Name a ++ \"_row\")%string <> (Name t ++ \"_row\")%string).\n      intro.\n      apply append_inj' in H4.\n      apply H2.\n      rewrite H4.\n      apply in_or_app; right.\n      apply in_map; auto.\n\n      apply Himp_star_frame; auto.\n      unfold cvars in *; simpl in *; intuition idtac;\n        unfold cursor; apply Himp_star_frame; simpl;\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 und\n              end; apply Himp_refl.\n    Qed.\n\n    Hint Extern 1 (himp _ (cursors _ _) (cursors _ _)) => eapply Weaken_cursors_eauto.\n\n    Hint Extern 1 (incl (_ :: _) _) => hnf; simpl; intuition subst;\n      match goal with\n        | [ H : _ |- _ ] => apply H\n      end.\n\n    Lemma noOverlapExps_compileCondition : forall tab cond,\n      noOverlapExps (tab ++ \"_row\") (tab ++ \"_data\")\n      (exps (compileCondition cond)).\n      unfold noOverlapExps, noOverlapExp; induction cond; simpl; intuition.\n      constructor; auto.\n      destruct (snd a); simpl; auto.\n      intuition discrim.\n    Qed.\n\n    Hint Immediate noOverlapExps_compileCondition.\n\n    Lemma cdataify_app : forall ls1 ls2,\n      cdataify (ls1 ++ ls2) = cdataify ls1 ++ cdataify ls2.\n      induction ls1; simpl; intuition.\n    Qed.\n\n    Lemma cdataify_pat : forall p,\n      XmlSearch.allCdatas (compilePat p) = cdataify (allCdatas p).\n      clear; induction p; simpl; intuition;\n        rewrite cdataify_app; congruence.\n    Qed.        \n\n    Lemma allCdatas_cdataify : forall x p,\n      In x (XmlSearch.allCdatas (compilePat p))\n      -> In x (cdataify (allCdatas p)).\n      clear; induction p; simpl; intuition; rewrite cdataify_app;\n        apply in_app_or in H; intuition.\n    Qed.\n\n    Hint Resolve allCdatas_cdataify.\n\n    Lemma output_wf' : forall ns p xm avs ts,\n      xwf avs ts xm\n      -> NoDups avs ts\n      -> (forall x, xfreeVar xm x -> In (x ++ \"_start\")%string ns)\n      -> (forall x, xfreeVar xm x -> In (x ++ \"_len\")%string ns)\n      -> (forall t, In t avs -> In (Name t ++ \"_data\")%string ns)\n      -> (forall tab, xbindsRowVar xm tab -> In (tab ++ \"_data\")%string ns)\n      -> (forall x, xfreeVar xm x -> In (x ++ \"_start\", x ++ \"_len\")%string\n        (XmlSearch.allCdatas (compilePat p)))\n      -> XmlOutput.wf ns (XmlSearch.allCdatas (compilePat p)) (avout avs) ts (compileXml xm).\n      intros; rewrite cdataify_pat; eauto using output_wf.\n    Qed.\n\n    Hint Resolve output_wf'.\n\n    Lemma goodCursors_avout : forall avs,\n      twfs avs\n      -> goodCursors (avout avs).\n      unfold goodCursors; clear; induction 1; simpl; intuition.\n      constructor; simpl; auto.\n      intuition (try discrim; eauto).\n    Qed.\n\n    Hint Immediate goodCursors_avout.\n\n    Lemma map_avout : forall avs,\n      map (fun av => Name (Table av)) (avout avs) = Names avs.\n      induction avs; simpl; intuition.\n    Qed.\n\n    Lemma NoDups_avout : forall avs ts,\n      NoDups avs ts\n      -> XmlOutput.NoDups (avout avs) ts.\n      intros; hnf in *.\n      eapply NoDup_app; try rewrite map_avout; eauto.\n      eapply NoDups_unapp_cross; auto.\n    Qed.\n\n    Hint Immediate NoDups_avout.\n\n    Lemma inputOk_res_weaken : forall V sch k cond,\n      cwf sch cond\n      -> inputOk V (exps (compileCondition cond))\n      -> inputOk (upd V \"res\" k) (exps (compileCondition cond)).\n      unfold inputOk; induction 1; simpl; inversion_clear 1; auto.\n      constructor; auto.\n      unfold inputOk1 in *; destruct x; simpl in *; intuition.\n      destruct e; simpl in *; intuition.\n      rewrite sel_upd_ne.\n      rewrite sel_upd_ne.\n      rewrite sel_upd_ne.\n      assumption.\n      discriminate.\n      intuition discrim.\n      intuition discrim.\n    Qed.\n\n    Lemma inputOk_compileCondition' : forall V cdatas ns,\n      XmlOutput.inBounds cdatas V\n      -> forall cond, cwf ns cond\n        -> (forall text, List.Exists (fun e => efreeVar (snd e) text) cond\n          -> In (text ++ \"_start\", text ++ \"_len\")%string cdatas)\n        -> inputOk (upd V \"res\" 0) (exps (compileCondition cond)).\n      intros; eapply inputOk_res_weaken; eauto.\n    Qed.\n\n    Hint Resolve inputOk_compileCondition'.\n\n    Lemma inBounds_res : forall p V k,\n      XmlOutput.inBounds (XmlSearch.allCdatas (compilePat p)) V\n      -> XmlOutput.inBounds (XmlSearch.allCdatas (compilePat p)) (upd V \"res\" k).\n      clear; intros; eapply Forall_impl2; [ apply xall_underscore | eassumption |  ].\n      simpl; intuition.\n      repeat match goal with\n               | [ |- context[wordToNat (upd ?a ?b ?c ?d)] ] =>\n                 change (wordToNat (upd a b c d)) with (wordToNat (sel (upd a b c) d))\n             end.\n      repeat rewrite sel_upd_ne by eauto using underscore_discrim.\n      assumption.\n    Qed.\n\n    Hint Immediate inBounds_res.\n\n    Lemma bloop : forall V avs ts P t k,\n      NoDup (Names ts)\n      -> In t ts\n      -> cursors V avs * (db ts * P)\n      ===> P * (table (Schema t) (Address t)\n        * (cursors (upd V \"res\" k) avs * db (removeTable (Name t) ts))).\n      sepLemma.\n\n      etransitivity; [ | apply himp_star_assoc ].\n      apply himp_star_frame.\n      apply removeTable_fwd; auto.\n      apply Weaken_cursors; descend.\n    Qed.\n\n    Hint Extern 1 (himp _ _ _) => apply bloop.\n\n    Lemma inBounds_swizzle''''' : forall V V' p tab,\n      (forall x, x <> (tab ++ \"_row\")%string -> x <> (tab ++ \"_data\")%string\n        -> x <> \"ibuf\" -> x <> \"ilen\" -> x <> \"tmp\" -> x <> \"ipos\" -> x <> \"overflowed\"\n        -> x <> \"matched\"\n        -> sel V x = sel V' x)\n      -> XmlOutput.inBounds (XmlSearch.allCdatas (compilePat p)) V\n      -> XmlOutput.inBounds (XmlSearch.allCdatas (compilePat p)) V'.\n      intros.\n      rewrite <- inBounds_sel.\n      rewrite <- inBounds_sel in H0.\n      eapply Forall_impl2; [ apply H0 | apply xall_underscore' | ].\n      post; subst; simpl in *.\n      repeat rewrite H in * by und.\n      auto.\n    Qed.\n\n    Hint Immediate inBounds_swizzle'''''.\n\n    Lemma cursors_bloop : forall P V avs k,\n      cursors V avs * P ===> P * cursors (upd V \"res\" k) avs.\n      sepLemma; apply Weaken_cursors; descend.\n    Qed.\n\n    Hint Extern 1 (himp _ _ _) => apply cursors_bloop.\n\n    Lemma rdb_noOverlapExps : forall tab cond,\n      RelDbSelect.noOverlapExps (tab ++ \"_row\") (tab ++ \"_data\") (exps (compileCondition cond)).\n      clear; induction cond; simpl; intuition; constructor; auto.\n      hnf; destruct (snd a); simpl; intuition discrim.\n    Qed.\n\n    Hint Immediate rdb_noOverlapExps.\n\n    Lemma twfs_cons : forall avs av ts,\n      twfs avs\n      -> In av ts\n      -> twfs ts\n      -> twfs (av :: avs).\n      clear; constructor; auto.\n      eapply Forall_forall in H1; eauto.\n    Qed.\n\n    Hint Immediate twfs_cons.\n\n    Lemma inBounds_opos : forall V v,\n      XmlOutput.inBounds (XmlSearch.allCdatas (compilePat p)) V\n      -> XmlOutput.inBounds (XmlSearch.allCdatas (compilePat p))\n      (upd V \"opos\" v).\n      intros; eapply inBounds_swizzle; [ | eauto ]; descend.\n    Qed.\n\n    Hint Immediate inBounds_opos.\n\n    Lemma cursors_bleep : forall P V avs k,\n      cursors V avs * P ===> P * XmlOutput.cursors (upd V \"opos\" k) (avout avs).\n      sepLemma.\n      change (XmlOutput.cursors (upd V \"opos\" k) (avout avs)) with (cursors (upd V \"opos\" k) avs).\n      apply Weaken_cursors; descend.\n    Qed.\n\n    Hint Extern 1 (himp _ _ _) => apply cursors_bleep.\n\n    Lemma cursors_blop : forall P V avs k,\n      P * XmlOutput.cursors V (avout avs) ===> cursors (upd V \"res\" k) avs * P.\n      sepLemma.\n      change (XmlOutput.cursors V (avout avs)) with (cursors V avs).\n      apply Weaken_cursors; descend.\n    Qed.\n\n    Hint Extern 1 (himp _ _ _) => apply cursors_blop.\n\n    Lemma compileAction_vcs : forall im ns res,\n      ~In \"rp\" ns\n      -> In \"obuf\" ns\n      -> In \"olen\" ns\n      -> In \"opos\" ns\n      -> In \"overflowed\" ns\n      -> In \"tmp\" ns\n      -> In \"buf\" ns\n      -> In \"ibuf\" ns\n      -> In \"row\" ns\n      -> In \"ilen\" ns\n      -> In \"ipos\" ns\n      -> In \"len\" ns\n      -> In \"matched\" ns\n      -> In \"res\" ns\n      -> In \"q\" ns\n      -> incl baseVars ns\n      -> (res >= 16)%nat\n      -> \"array8\"!\"copy\" ~~ im ~~> copyS\n      -> \"array8\"!\"equal\" ~~ im ~~> equalS\n      -> \"buffers\"!\"bmalloc\" ~~ im ~~> Buffers.bmallocS\n      -> \"malloc\"!\"malloc\" ~~ im ~~> mallocS\n      -> \"numops\"!\"div4\" ~~ im ~~> div4S\n      -> \"malloc\"!\"free\" ~~ im ~~> freeS\n      -> \"buffers\"!\"bfree\" ~~ im ~~> bfreeS\n      -> \"sys\"!\"abort\" ~~ im ~~> abortS\n      -> \"httpq\"!\"save\" ~~ im ~~> (saveGS httpq)\n      -> forall a avs ts ts' pre mn (H : importsGlobal im),\n        (forall specs st,\n          interp specs (pre st)\n          -> interp specs (ainv avs ts ts' true (fun x : W => x) ns res st))\n        -> awf avs ts a\n        -> NoDups avs ts\n        -> twfs avs\n        -> twfs ts\n        -> (forall text, afreeVar a text -> In (text ++ \"_start\", text ++ \"_len\")%string\n          (XmlSearch.allCdatas (compilePat p)))\n        -> (forall text, afreeVar a text -> In (text ++ \"_start\") ns)%string\n        -> (forall text, afreeVar a text -> In (text ++ \"_len\") ns)%string\n        -> (forall tab, abindsRowVar a tab -> In (tab ++ \"_row\") ns)%string\n        -> (forall tab, abindsRowVar a tab -> In (tab ++ \"_data\") ns)%string\n        -> (forall t, In t avs -> In (Name t ++ \"_row\")%string ns)\n        -> (forall t, In t avs -> In (Name t ++ \"_data\")%string ns)\n        -> vcs (VerifCond (toCmd (compileAction' avs ts ts' a) mn H ns res pre)).\n      induction a.\n\n      step1.\n\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\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\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      step2.\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      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      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\n    Hint Resolve compileAction_post compileAction_vcs.\n\n    Notation CompileVcs avs ts a := (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 \"ibuf\" ns :: In \"row\" ns :: In \"ilen\" ns\n      :: In \"ipos\" ns :: In \"len\" ns\n      :: In \"matched\" ns :: In \"res\" ns :: In \"q\" ns\n      :: incl baseVars ns\n      :: (res >= 16)%nat\n      :: \"array8\"!\"copy\" ~~ im ~~> copyS\n      :: \"array8\"!\"equal\" ~~ im ~~> equalS\n      :: \"buffers\"!\"bmalloc\" ~~ im ~~> Buffers.bmallocS\n      :: \"malloc\"!\"malloc\" ~~ im ~~> mallocS\n      :: \"numops\"!\"div4\" ~~ im ~~> div4S\n      :: \"malloc\"!\"free\" ~~ im ~~> freeS\n      :: \"buffers\"!\"bfree\" ~~ im ~~> bfreeS\n      :: \"sys\"!\"abort\" ~~ im ~~> abortS\n      :: \"httpq\"!\"save\" ~~ im ~~> (saveGS httpq)\n      :: awf avs%list ts%list a%string\n      :: NoDups avs ts\n      :: twfs avs%list\n      :: twfs ts%list\n      :: (forall text, afreeVar a%string text -> In (text ++ \"_start\", text ++ \"_len\")%string\n        (XmlSearch.allCdatas (compilePat p)))\n      :: (forall text, afreeVar a text -> In (text ++ \"_start\") ns)%string\n      :: (forall text, afreeVar a text -> In (text ++ \"_len\") ns)%string\n      :: (forall tab, abindsRowVar a tab -> In (tab ++ \"_row\") ns)%string\n      :: (forall tab, abindsRowVar a tab -> In (tab ++ \"_data\") ns)%string\n      :: (forall t, In t avs -> In (Name t ++ \"_row\")%string ns)\n      :: (forall t, In t avs -> In (Name t ++ \"_data\")%string ns)\n      :: nil).\n\n    Definition compileAction (avs ts ts' : tables) (a : action) : chunk.\n      refine (WrapC (compileAction' avs ts ts' a)\n        (ainv avs ts ts')\n        (ainv avs ts ts')\n        (CompileVcs avs ts a) _ _); abstract (\n          intros; repeat match goal with\n                           | [ H : vcs (_ :: _) |- _ ] => inversion H; clear H; subst\n                         end; eauto).\n    Defined.\n  End compileAction.\n\n  Variable ts : tables.\n  Hypothesis wellFormed : wf ts pr.\n  Hypothesis ND : NoDup (Names ts).\n  Hypothesis goodSchema : twfs ts.\n\n  Section compileProgram.\n    Definition cpinv :=\n      Al bsI, Al bsO, Al ls,\n      PRE[V] db ts * http (V \"q\")\n        * array8 bsI (V \"buf\") * array8 bsO (V \"obuf\")\n        * [| length bsI = wordToNat (V \"len\") |]\n        * [| length bsO = wordToNat (V \"olen\") |]\n        * sll ls (V \"stack\") * mallocHeap 0\n        * xmlp (V \"len\") (V \"lex\")\n        * [| V \"opos\" <= V \"olen\" |] * [| stackOk ls (V \"len\") |]\n      POST[R] db ts * http (V \"q\")\n        * array8 bsI (V \"buf\") * Ex bsO', array8 bsO' (V \"obuf\")\n        * [| length bsO' = length bsO |]\n        * [| R <= V \"olen\" |] * mallocHeap 0.\n\n    Infix \";;\" := SimpleSeq : SP_scope.    \n\n    Fixpoint compileProgram' (pr : program) : chunk :=\n      match pr with\n        | Rule p a =>\n          Call \"xml_lex\"!\"setPosition\"(\"lex\", 0)\n          [Al bsI, Al bsO, Al ls,\n            PRE[V] db ts * http (V \"q\")\n              * array8 bsI (V \"buf\") * array8 bsO (V \"obuf\")\n              * [| length bsI = wordToNat (V \"len\") |]\n              * [| length bsO = wordToNat (V \"olen\") |]\n              * sll ls (V \"stack\") * mallocHeap 0\n              * xmlp (V \"len\") (V \"lex\")\n              * [| V \"opos\" <= V \"olen\" |]%word * [| stackOk ls (V \"len\") |]\n            POST[R] db ts * http (V \"q\")\n              * array8 bsI (V \"buf\") * Ex bsO', array8 bsO' (V \"obuf\")\n              * [| length bsO' = length bsO |]\n              * [| R <= V \"olen\" |]%word * mallocHeap 0];;\n\n          Pat (fun bsO V => db ts * http (V \"q\")\n            * array8 bsO (V \"obuf\")\n            * [| length bsO = wordToNat (V \"olen\") |]\n            * [| V \"opos\" <= V \"olen\" |]%word)%Sep\n          (fun bsO V R => db ts * http (V \"q\")\n            * Ex bsO', array8 bsO' (V \"obuf\")\n            * [| length bsO' = length bsO |]\n            * [| R <= V \"olen\" |]%word)%Sep\n          (compilePat p)\n          (compileAction p nil ts ts a)\n        | PSeq pr1 pr2 =>\n          compileProgram' pr1;;\n          compileProgram' pr2\n      end%SP.\n\n    Lemma compileProgram_post : forall im mn (H : importsGlobal im)\n      ns res pr0 pre,\n      (forall specs st,\n        interp specs (pre st)\n        -> interp specs (cpinv true (fun x : W => x) ns res st))\n      -> wf ts pr0\n      -> forall specs st, interp specs (Postcondition\n        (toCmd (compileProgram' pr0) mn H ns res pre) st)\n      -> interp specs (cpinv true (fun x : W => x) ns res st).\n      induction pr0; simpl; intros; repeat (invoke1; post); t.\n    Qed.\n\n    Lemma cursors_intro' : forall P V specs,\n      himp specs P (P * cursors V nil)%Sep.\n      sepLemma.\n    Qed.\n\n    Hint Immediate cursors_intro'.\n\n    Lemma xbindsRowVar_row : forall tab xm,\n      xbindsRowVar xm tab\n      -> In (tab ++ \"_row\")%string (allCursors_both' xm).\n      clear; induction xm using xml_ind'; simpl; intuition.\n      generalize (@nil string).\n      induction H; simpl in *; intuition.\n      assert (In (tab ++ \"_row\")%string (addTo (allCursors_both' x) l0)) by eauto.\n      generalize dependent (addTo (allCursors_both' x) l0); clear;\n        induction l; simpl; intuition (subst; eauto).\n    Qed.\n\n    Lemma xbindsRowVar_data : forall tab xm,\n      xbindsRowVar xm tab\n      -> In (tab ++ \"_data\")%string (allCursors_both' xm).\n      clear; induction xm using xml_ind'; simpl; intuition.\n      generalize (@nil string).\n      induction H; simpl in *; intuition.\n      assert (In (tab ++ \"_data\")%string (addTo (allCursors_both' x) l0)) by eauto.\n      generalize dependent (addTo (allCursors_both' x) l0); clear;\n        induction l; simpl; intuition (subst; eauto).\n    Qed.\n\n    Hint Immediate xbindsRowVar_row xbindsRowVar_data.\n\n    Lemma abindsRowVar_row : forall tab a,\n      abindsRowVar a tab\n      -> In (tab ++ \"_row\")%string (allCursors_both a).\n      clear; induction a; try solve [ simpl; intuition ].\n      unfold allCursors_both; fold allCursors_both; intros.\n      simpl in H; destruct H as [ | [ | ] ]; subst.\n      apply In_addTo1; simpl; tauto.\n      eauto using In_addTo1, In_addTo2.\n      eauto using In_addTo1, In_addTo2.\n      unfold allCursors_both; fold allCursors_both; intros.\n      simpl in H; destruct H; subst.\n      apply In_addTo1; simpl; tauto.\n      eauto using In_addTo1, In_addTo2.\n      unfold allCursors_both; fold allCursors_both; intros.\n      simpl in H; destruct H; subst;\n        eauto using In_addTo1, In_addTo2.\n    Qed.\n\n    Lemma abindsRowVar_data : forall tab a,\n      abindsRowVar a tab\n      -> In (tab ++ \"_data\")%string (allCursors_both a).\n      clear; induction a; try solve [ simpl; intuition ].\n      unfold allCursors_both; fold allCursors_both; intros.\n      simpl in H; destruct H as [ | [ | ] ]; subst.\n      apply In_addTo1; simpl; tauto.\n      eauto using In_addTo1, In_addTo2.\n      eauto using In_addTo1, In_addTo2.\n      unfold allCursors_both; fold allCursors_both; intros.\n      simpl in H; destruct H; subst.\n      apply In_addTo1; simpl; tauto.\n      eauto using In_addTo1, In_addTo2.\n      unfold allCursors_both; fold allCursors_both; intros.\n      simpl in H; destruct H; subst;\n        eauto using In_addTo1, In_addTo2.\n    Qed.\n\n    Hint Immediate abindsRowVar_row abindsRowVar_data.\n\n    Lemma compileProgram_vcs : forall im mn (H : importsGlobal im) ns res,\n      ~In \"rp\" ns\n      -> In \"obuf\" ns\n      -> In \"olen\" ns\n      -> In \"opos\" ns\n      -> In \"overflowed\" ns\n      -> In \"tmp\" ns\n      -> In \"buf\" ns\n      -> In \"ibuf\" ns\n      -> In \"row\" ns\n      -> In \"ilen\" ns\n      -> In \"ipos\" ns\n      -> In \"len\" ns\n      -> In \"matched\" ns\n      -> In \"res\" ns\n      -> In \"lex\" ns\n      -> In \"q\" ns\n      -> incl (\"buf\" :: \"len\" :: \"lex\" :: \"res\"\n        :: \"tagStart\" :: \"tagLen\" :: \"matched\" :: \"stack\" :: \"level\" :: nil)\n      ns\n      -> (res >= 16)%nat\n      -> \"array8\"!\"copy\" ~~ im ~~> copyS\n      -> \"array8\"!\"equal\" ~~ im ~~> equalS\n      -> \"buffers\"!\"bmalloc\" ~~ im ~~> Buffers.bmallocS\n      -> \"malloc\"!\"malloc\" ~~ im ~~> mallocS\n      -> \"xml_lex\"!\"next\" ~~ im ~~> nextS\n      -> \"xml_lex\"!\"position\" ~~ im ~~> positionS\n      -> \"xml_lex\"!\"setPosition\" ~~ im ~~> setPositionS\n      -> \"xml_lex\"!\"tokenStart\" ~~ im ~~> tokenStartS\n      -> \"xml_lex\"!\"tokenLength\" ~~ im ~~> tokenLengthS\n      -> \"malloc\"!\"free\" ~~ im ~~> freeS\n      -> \"sys\"!\"abort\" ~~ im ~~> abortS\n      -> \"numops\"!\"div4\" ~~ im ~~> div4S\n      -> \"buffers\"!\"bfree\" ~~ im ~~> bfreeS\n      -> \"sys\"!\"abort\" ~~ im ~~> abortS\n      -> \"httpq\"!\"save\" ~~ im ~~> (saveGS httpq)\n      -> forall pr0 pre,\n        (forall specs st,\n          interp specs (pre st)\n          -> interp specs (cpinv true (fun x : W => x) ns res st))\n        -> wf ts pr0\n        -> incl (cdatasOf pr0) ns\n        -> incl (cursorsOf pr0) ns\n        -> vcs (VerifCond (toCmd (compileProgram' pr0) mn H ns res pre)).\n      induction pr0; wrap0;\n        repeat match goal with\n                 | [ |- vcs (_ :: _) ] => wrap0\n                 | [ H : _ |- vcs _ ] => apply H;\n                   try apply compileProgram_post\n               end; try abstract t.\n    Qed.\n\n    Hint Resolve compileProgram_post compileProgram_vcs.\n\n    Notation CompileVcs pr := (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 \"ibuf\" ns :: In \"row\" ns :: In \"ilen\" ns\n      :: In \"ipos\" ns :: In \"len\" ns\n      :: In \"matched\" ns :: In \"res\" ns :: In \"lex\" ns :: In \"q\" ns\n      :: incl (\"buf\" :: \"len\" :: \"lex\" :: \"res\"\n        :: \"tagStart\" :: \"tagLen\" :: \"matched\" :: \"stack\" :: \"level\" :: nil)\n      ns\n      :: (res >= 16)%nat\n      :: \"array8\"!\"copy\" ~~ im ~~> copyS\n      :: \"array8\"!\"equal\" ~~ im ~~> equalS\n      :: \"buffers\"!\"bmalloc\" ~~ im ~~> Buffers.bmallocS\n      :: \"malloc\"!\"malloc\" ~~ im ~~> mallocS\n      :: \"xml_lex\"!\"next\" ~~ im ~~> nextS\n      :: \"xml_lex\"!\"position\" ~~ im ~~> positionS\n      :: \"xml_lex\"!\"setPosition\" ~~ im ~~> setPositionS\n      :: \"xml_lex\"!\"tokenStart\" ~~ im ~~> tokenStartS\n      :: \"xml_lex\"!\"tokenLength\" ~~ im ~~> tokenLengthS\n      :: \"malloc\"!\"free\" ~~ im ~~> freeS\n      :: \"sys\"!\"abort\" ~~ im ~~> abortS\n      :: \"numops\"!\"div4\" ~~ im ~~> div4S\n      :: \"buffers\"!\"bfree\" ~~ im ~~> bfreeS\n      :: \"sys\"!\"abort\" ~~ im ~~> abortS\n      :: \"httpq\"!\"save\" ~~ im ~~> (saveGS httpq)\n      :: incl (cdatasOf pr) ns\n      :: incl (cursorsOf pr) ns\n      :: nil).\n\n    Definition compileProgram : chunk.\n      refine (WrapC (compileProgram' pr)\n        cpinv\n        cpinv\n        (CompileVcs pr) _ _); abstract (\n          intros; repeat match goal with\n                           | [ H : vcs (_ :: _) |- _ ] => inversion H; clear H; subst\n                         end; eauto).\n    Defined.\n  End compileProgram.\n\n\n  (** Now, create a [vcgen] version that knows about [Pat] and others, with some shameless copy-and-paste. *)\n\n  Ltac vcgen_simp := cbv beta iota zeta delta [WrapC Wrap\n    compileProgram map app imps\n    LabelMap.add Entry Blocks Postcondition VerifCond\n    Straightline_ Seq_ Diverge_ Fail_ Skip_ Assert_\n    Structured.If_ Structured.While_ Goto_ Structured.Call_ IGoto\n    setArgs Programming.Reserved Programming.Formals Programming.Precondition\n    importsMap fullImports buildLocals blocks union Nplus Nsucc length N_of_nat\n    List.fold_left ascii_lt string_lt label'_lt\n    LabelKey.compare' LabelKey.compare LabelKey.eq_dec\n    LabelMap.find\n    toCmd Programming.Seq Instr Diverge Fail Skip Assert_\n    Programming.If_ Programming.While_ Goto Programming.Call_ RvImm'\n    Assign' localsInvariant localsInvariantCont\n    regInL lvalIn immInR labelIn variableSlot string_eq ascii_eq\n    andb Bool.eqb qspecOut\n    ICall_ Structured.ICall_\n    Assert_ Structured.Assert_\n    LabelMap.Raw.find LabelMap.this LabelMap.Raw.add\n    LabelMap.empty LabelMap.Raw.empty string_dec\n    Ascii.ascii_dec string_rec string_rect 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\n    fst snd labl\n    Ascii.N_of_ascii Ascii.N_of_digits N.compare Nmult Pos.compare Pos.compare_cont\n    Pos.mul Pos.add LabelMap.Raw.bal\n    Int.Z_as_Int.gt_le_dec Int.Z_as_Int.ge_lt_dec LabelMap.Raw.create\n    ZArith_dec.Z_gt_le_dec Int.Z_as_Int.plus Int.Z_as_Int.max LabelMap.Raw.height\n    ZArith_dec.Z_gt_dec Int.Z_as_Int._1 BinInt.Z.add Int.Z_as_Int._0 Int.Z_as_Int._2 BinInt.Z.max\n    ZArith_dec.Zcompare_rec 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\n    COperand1 CTest COperand2 Pos.succ\n    makeVcs\n    Note_ Note__\n    IGotoStar_ IGotoStar AssertStar_ AssertStar\n    Cond_ Cond\n  ].\n\n  Ltac vcgen := structured_auto vcgen_simp.\n\n  Definition m := bimport [[\"xml_lex\"!\"next\" @ [nextS], \"xml_lex\"!\"position\" @ [positionS],\n                            \"xml_lex\"!\"setPosition\" @ [setPositionS], \"xml_lex\"!\"tokenStart\" @ [tokenStartS],\n                            \"xml_lex\"!\"tokenLength\" @ [tokenLengthS], \"malloc\"!\"malloc\" @ [mallocS],\n                            \"malloc\"!\"free\" @ [freeS], \"sys\"!\"abort\" @ [abortS], \"sys\"!\"printInt\" @ [printIntS],\n                            \"xml_lex\"!\"init\" @ [initS], \"xml_lex\"!\"delete\" @ [deleteS],\n                            \"array8\"!\"copy\" @ [copyS], \"array8\"!\"equal\" @ [equalS],\n                            \"buffers\"!\"bmalloc\" @ [Buffers.bmallocS], \"buffers\"!\"bfree\" @ [Buffers.bfreeS],\n                            \"numops\"!\"div4\" @ [div4S], \"httpq\"!\"save\" @ [saveGS httpq] ]]\n\n    bmodule \"xml_prog\" {{\n      {|\n        FName := \"main\";\n        FVars := lvars;\n        FReserved := 16;\n        FPrecondition := Precondition (mainS ts) None;\n        FBody := Programming.Seq (Assign' ((fun _ => LvMem (Indir Sp O)):lvalue') Rp)\n        (Programming.Seq (fun _ _ =>\n          Structured nil\n          (fun im mn _ =>\n            Structured.Assert_ im mn\n            (Precondition (mainS ts) (Some lvars))))\n        (\"lex\" <-- Call \"xml_lex\"!\"init\"(\"len\")\n         [Al bsI, Al bsO,\n           PRE[V, R] db ts * http (V \"q\")\n             * array8 bsI (V \"buf\") * array8 bsO (V \"obuf\") * mallocHeap 0 * xmlp (V \"len\") R\n             * [| length bsI = wordToNat (V \"len\") |] * [| length bsO = wordToNat (V \"olen\") |]\n           POST[R'] db ts * http (V \"q\")\n             * Ex bsO', array8 bsI (V \"buf\") * array8 bsO' (V \"obuf\") * mallocHeap 0\n             * [| length bsO' = length bsO |] * [| R' <= V \"olen\" |]%word ];;\n         \"stack\" <- 0;;\n         \"opos\" <- 0;;\n         \"overflowed\" <- 0;;\n\n         compileProgram;;\n\n         Call \"xml_lex\"!\"delete\"(\"lex\")\n         [Al ls,\n           PRE[V] http (V \"q\") * [| V \"opos\" <= V \"olen\" |]%word * mallocHeap 0 * sll ls (V \"stack\")\n           POST[R] http (V \"q\") * [| R <= V \"olen\" |]%word * mallocHeap 0];;\n\n         [Al ls,\n           PRE[V] http (V \"q\") * [| V \"opos\" <= V \"olen\" |]%word * mallocHeap 0 * sll ls (V \"stack\")\n           POST[R] http (V \"q\") * [| R <= V \"olen\" |]%word * mallocHeap 0]\n         While (\"stack\" <> 0) {\n           \"lex\" <- \"stack\";;\n           \"stack\" <-* \"stack\"+4;;\n\n           Call \"malloc\"!\"free\"(0, \"lex\", 2)\n           [Al ls,\n             PRE[V] http (V \"q\") * [| V \"opos\" <= V \"olen\" |]%word * mallocHeap 0 * sll ls (V \"stack\")\n             POST[R] http (V \"q\") * [| R <= V \"olen\" |]%word * mallocHeap 0]\n         };;\n\n         If (\"overflowed\" = 1) {\n           Return 0\n         } else {\n           Return \"opos\"\n         }))%SP\n      |}\n    }}.\n\n  Section no_clash.\n    Variable s : string.\n    Hypothesis Hs : underscore_free s.\n\n    Lemma no_clash_cdatas : forall pr0,\n      In s (cdatasOf pr0)\n      -> False.\n      induction pr0; simpl; intuition eauto.\n      apply In_addTo_or in H; destruct H; auto.\n    Qed.\n\n    Hint Resolve no_clash_cdatas.\n\n    Lemma no_clash_allCursors_both'' : forall inner,\n      List.Forall (fun xm => In s (allCursors_both' xm) -> False) inner\n      -> forall ls, ~In s ls\n        -> In s (fold_left (fun ls xm => addTo (allCursors_both' xm) ls) inner ls)\n        -> False.\n      clear; induction 1; simpl; intuition.\n      apply IHForall in H2; auto.\n      intros Hi; apply In_addTo_or in Hi; intuition.\n    Qed.\n\n    Lemma no_clash_allCursors_both' : forall xm,\n      In s (allCursors_both' xm)\n      -> False.\n      induction xm using xml_ind'; simpl; intuition (try discrim).\n      eapply no_clash_allCursors_both''; try eassumption; simpl; tauto.\n    Qed.\n\n    Hint Immediate no_clash_allCursors_both'.\n\n    Lemma no_clash_allCursors_both : forall a,\n      In s (allCursors_both a)\n      -> False.\n      induction a; try solve [ simpl; intuition (try match goal with\n                                                       | [ H : _ |- _ ] =>\n                                                         apply In_addTo_or in H; intuition idtac\n                                                     end; eauto; try discrim) ].\n      unfold allCursors_both; fold allCursors_both; intros.\n      apply In_addTo_or in H; destruct H.\n      simpl in *; intuition discrim.\n      apply In_addTo_or in H; destruct H; eauto.\n      unfold allCursors_both; fold allCursors_both; intros.\n      apply In_addTo_or in H; destruct H.\n      simpl in *; intuition discrim.\n      tauto.\n    Qed.\n\n    Hint Immediate no_clash_allCursors_both.\n\n    Lemma no_clash_cursorsOf : forall pr0,\n      In s (cursorsOf pr0)\n      -> False.\n      induction pr0; simpl; intuition eauto.\n      apply In_addTo_or in H; destruct H; eauto.\n    Qed.\n    \n    Hint Immediate no_clash_cursorsOf.\n\n    Lemma no_clash_both' : forall pr0,\n      In s (cdatasOf pr0 ++ cursorsOf pr0)\n      -> False.\n      clear; intros; apply in_app_or in H; destruct H; eauto.\n    Qed.\n  End no_clash.    \n\n  Lemma no_clash_both : forall pr0 s,\n    In s (cdatasOf pr0 ++ cursorsOf pr0)\n    -> underscore_free s\n    -> False.\n    eauto using no_clash_both'.\n  Qed.\n\n  Hint Resolve no_clash_both.\n\n  Lemma In_cdatasOf' : forall x p,\n    In x (allCdatas_both p)\n    -> exists text, x = (text ++ \"_start\")%string\n      \\/ x = (text ++ \"_len\")%string.\n    clear; induction p; simpl; intuition (subst; eauto);\n      match goal with\n        | [ H : _ |- _ ] => apply in_app_or in H; intuition\n      end.\n  Qed.\n\n  Hint Immediate In_cdatasOf'.\n\n  Lemma In_cdatasOf : forall x pr0,\n    In x (cdatasOf pr0)\n    -> exists text, x = (text ++ \"_start\")%string\n      \\/ x = (text ++ \"_len\")%string.\n    clear; induction pr0; simpl; intuition eauto;\n      match goal with\n        | [ H : _ |- _ ] => apply In_addTo_or in H; intuition\n      end.\n  Qed.\n\n  Lemma In_allCursors_both'' : forall x (P : _ -> Prop) inner,\n    List.Forall (fun xm => In x (allCursors_both' xm) -> P x) inner\n    -> forall ls, (In x ls -> P x)\n      -> In x (fold_left (fun ls xm => addTo (allCursors_both' xm) ls) inner ls)\n      -> P x.\n    clear; induction 1; simpl; intuition.\n    apply IHForall in H2; auto.\n    intros Hi; apply In_addTo_or in Hi; intuition.\n  Qed.\n\n  Lemma In_allCursors_both' : forall x xm,\n    In x (allCursors_both' xm)\n    -> exists text, x = (text ++ \"_row\")%string\n      \\/ x = (text ++ \"_data\")%string.\n    clear; induction xm using xml_ind'; simpl; intuition eauto.\n    eapply In_allCursors_both''; eauto; simpl; tauto.\n  Qed.\n\n  Hint Immediate In_allCursors_both'.\n\n  Lemma In_allCursors_both : forall x a,\n    In x (allCursors_both a)\n    -> exists text, x = (text ++ \"_row\")%string\n      \\/ x = (text ++ \"_data\")%string.\n    clear; induction a; try solve [ simpl; intuition eauto;\n      match goal with\n        | [ H : _ |- _ ] => apply In_addTo_or in H; intuition\n      end ].\n    unfold allCursors_both; fold allCursors_both; intros.\n    apply In_addTo_or in H; destruct H.\n    simpl in *; intuition eauto.\n    apply In_addTo_or in H; destruct H; eauto.\n    unfold allCursors_both; fold allCursors_both; intros.\n    apply In_addTo_or in H; destruct H.\n    simpl in *; intuition eauto.\n    tauto.\n    unfold allCursors_both; fold allCursors_both; intros.\n    apply In_addTo_or in H; destruct H;\n      simpl in *; intuition eauto.\n  Qed.\n\n  Hint Immediate In_allCursors_both.\n\n  Lemma In_cursorsOf : forall x pr0,\n    In x (cursorsOf pr0)\n    -> exists text, x = (text ++ \"_row\")%string\n      \\/ x = (text ++ \"_data\")%string.\n    clear; induction pr0; simpl; intuition eauto;\n      match goal with\n        | [ H : _ |- _ ] => apply In_addTo_or in H; intuition\n      end.\n  Qed.\n\n  Definition uf := List.Forall (fun t : XmlOutput.table => underscore_free (Name t)).\n  Hypothesis UF : uf ts.\n\n  Lemma NoDup_both : NoDup (cdatasOf pr ++ cursorsOf pr).\n    intros; apply NoDup_app; eauto using cdatas_distinct, cursorsOf_NoDup; intros.\n    apply In_cdatasOf in H.\n    apply In_cursorsOf in H0.\n    post; subst; discrim.\n  Qed.\n\n  Hint Immediate NoDup_both.\n\n  Theorem ok : moduleOk m.\n    vcgen;\n      (intros; try match goal with\n                     | [ H : importsGlobal _ |- _ ] => clear H\n                   end; pre).\n\n    Ltac u := abstract t.\n\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n    u.\n  Qed.\n\nEnd compileProgram.\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/XmlLang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.25720631918841336}}
{"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 AlphaDecider.\nSet Implicit Arguments.\n\n(** printing #  $\\times$ #×# *)\n(** printing &  $\\times$ #×# *)\n\nNotation inrr := (fun x => inr (inr x)).\nNotation inlr := (fun x => inl (inr x)).\nNotation inll := (fun x => inl (inl x)).\n\n(** CatchFileBetweenTagsLetRecStart *)\n\nInductive PNonTerminal : Set :=  lasgn | asgn | asgnRhs.\nInductive VarSym : Set := vsym.\nInductive TNonTerminal : Set := term.\nInductive Terminal :Set := .\nDefinition vSubstType (_ : VarSym) : TNonTerminal := term.\n\nInductive PatProd : Set := aNil | aCons | asgnP.\nInductive TermProd : Set := app | lam | letr.\nInductive EmbedProd : Set := asgnRhsE.\nDefinition epLhsRhs  (_: EmbedProd):\n   (PNonTerminal * TNonTerminal) := (asgnRhs, term).\n\nDefinition ppLhsRhs (p:PatProd) :\n (PNonTerminal * list (PNonTerminal+ (Terminal + VarSym))):=\nmatch p with\n | aNil => (lasgn,[])\n | aCons => (lasgn, [inl lasgn, inl asgn])\n | asgnP  => (asgn, [inrr vsym, inl asgnRhs])\nend.\nDefinition tpLhsRhs (p:TermProd) :\n (TNonTerminal * list ((PNonTerminal + VarSym)\n                         + (Terminal + TNonTerminal))):=\nmatch p with\n | app => (term,[inrr term, inrr term])\n | lam => (term, [inlr vsym, inrr term])\n | letr  => (term, [inll lasgn, inrr term])\nend.\n\nDefinition bindingInfo (p:TermProd) : list (nat * nat) :=\nmatch p with\n | app => []  | lam => [(0,1)]  | letr  => [(0,0),(0,1)]\nend.\n(** CatchFileBetweenTagsLetRecEnd *)\n\nDefinition letrecCFGV : CFGV.\neapply Build_CFGV \n      with   (VarSym := VarSym)\n             (Terminal := Terminal)\n             (PNonTerminal := PNonTerminal)\n             (TNonTerminal := TNonTerminal)\n             (PatProd := PatProd)\n             (TermProd := TermProd)\n             (tpLhsRhs := tpLhsRhs)\n             (bindingInfo := bindingInfo)\n             (EmbedProd := EmbedProd).\n  - intro. exact nvarVarType.\n  - exact vSubstType.\n  - exact ppLhsRhs.\n  - exact epLhsRhs.\n  - proveBindingInfoCorrect.\n  - proveDeqInductiveNonrec. \n  - intro H. contradiction.\n  - proveDeqInductiveNonrec.\n  - proveDeqInductiveNonrec.\n  - proveDeqInductiveNonrec.\n  - proveDeqInductiveNonrec.\n  - proveDeqInductiveNonrec.\n  - proveDeqInductiveNonrec.\nGrab Existential Variables.\nintro t. inverts t.\nDefined.\n\nRequire Export Term.\n\n\n(* to catch stupid errors early, it makes sense\n  first replace Notation by Definition and revert\n  back to Notation if the Definition typechecks *)\n\nNotation SYMTN := (@gsymTN letrecCFGV).\nNotation SYMPN := (@gsymPN letrecCFGV).\nDefinition TERM := (Term (SYMTN  term)).\nDefinition PAT p := (Pattern  (SYMPN p)).\nNotation VAR := (@vType letrecCFGV (vsym)).\n\nDefinition mkAsgn : VAR -> TERM -> PAT asgn.\n  intros v t.\n  apply (@pnode letrecCFGV asgnP).\n  apply mpcons.\n  * apply pvleaf. simpl. exact v.\n  * apply (mpcons);[| apply mnil].\n    apply (@embed letrecCFGV asgnRhsE). simpl.\n    exact t.\nDefined.\n\nDefinition mkLAsgn : list (PAT asgn) -> PAT lasgn.\n  intro l. induction l as [| h tl].\n  - apply (@pnode letrecCFGV aNil). simpl. apply mnil.\n  - apply (@pnode letrecCFGV aCons); simpl.\n    apply (mpcons).\n    + exact IHtl.\n    + apply (mpcons); [| apply mnil].\n      exact h.\nDefined.\n\nDefinition mkLetr : list (PAT asgn) -> TERM -> TERM.\n  intros lp t.\n  apply (@tnode letrecCFGV letr). unfold tpRhsAugIsPat. simpl.\n  apply mpcons.\n  - apply mkLAsgn. exact lp.\n  - apply (mtcons);[| apply mnil]. exact t.\nDefined.\n\nDefinition mkVTerm : VAR -> TERM.\n  intro v.\n  apply (@vleaf letrecCFGV vsym).\n  exact v.\nDefined.\n\n(** a representation of the term \n    letrec x:=y in z\n*)\n\nDefinition letr_xyz : TERM :=\n  mkLetr [mkAsgn nvarx (mkVTerm nvary)]  (mkVTerm nvarz).\n  \n\n\n(*\nLemma letrxx_alpha_trivial :\n @tAlphaEq letrecCFGV vsym _ letrxxx letrxxx.\nProof.\n  remember (@tAlphaEqDecidable letrecCFGV vsym _ letrxxx letrxxx).\n  unfold tAlphaEqDecidable, alphaEqDecidable, GInductionS, tcase,\n  comp_ind_type in Heqd.\n  simpl in Heqd.\n*)  \n(*\n*** Local Variables:\n*** coq-load-path: (\"../\")\n*** End:\n*)\n", "meta": {"author": "aa755", "repo": "CFGV", "sha": "440965e85e0d7107a8f0cfef5d14b895979716e5", "save_path": "github-repos/coq/aa755-CFGV", "path": "github-repos/coq/aa755-CFGV/CFGV-440965e85e0d7107a8f0cfef5d14b895979716e5/LetrecEx.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.4339814648038986, "lm_q1q2_score": 0.25720631294371077}}
{"text": "Require Import Verdi.TraceRelations.\n\nRequire Import VerdiRaft.Raft.\nRequire Import VerdiRaft.CommonTheorems.\nRequire Import VerdiRaft.TraceUtil.\n\nRequire Import VerdiRaft.CausalOrderPreservedInterface.\nRequire Import VerdiRaft.OutputImpliesAppliedInterface.\nRequire Import VerdiRaft.AppliedImpliesInputInterface.\nRequire Import VerdiRaft.AppliedEntriesMonotonicInterface.\nLocal Arguments update {_} {_} {_} _ _ _ _ : simpl never.\n\nSection CausalOrderPreserved.\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  Context {aiii : applied_implies_input_interface}.\n  Context {aemi : applied_entries_monotonic_interface}.\n\n  Section inner.\n  Variable client : clientId.\n  Variable id : nat.\n  Variable client' : clientId.\n  Variable id' : nat.\n\n  Lemma output_before_input_not_key_in_input_trace :\n    forall tr tr' s s',\n      ~ output_before_input client id client' id' tr ->\n      step_failure s s' tr' ->\n      output_before_input client id client' id' (tr ++ tr') ->\n      ~ exists i, in_input_trace client' id' i (tr ++ tr').\n  Proof using. \n    intros. find_eapply_lem_hyp before_func_app_necessary; eauto.\n    intuition.\n    break_exists. unfold in_input_trace in *.\n    break_exists. do_in_app. intuition;\n      [find_apply_hyp_hyp; simpl in *; break_if; repeat (do_bool; intuition)|].\n    invcs H0; intuition.\n    - break_if; congruence.\n    - find_inversion; try congruence.\n      repeat (do_bool; intuition).\n      break_if; try congruence.\n    - find_inversion.\n  Qed.\n\n  Lemma output_before_input_key_in_output_trace :\n    forall tr,\n      output_before_input client id client' id' tr ->\n      key_in_output_trace client id tr.\n  Proof using. \n    intros. unfold output_before_input in *.\n    induction tr; simpl in *; intuition.\n    - unfold key_in_output_trace.\n      unfold is_output_with_key in *. repeat break_match; try congruence.\n      subst. do 2 eexists. intuition; eauto.\n    - unfold key_in_output_trace in *.\n      break_exists_exists. simpl; intuition.\n  Qed.\n\n  Lemma in_applied_entries_entries_ordered :\n    forall net,\n      in_applied_entries client id net ->\n      ~ in_applied_entries client' id' net ->\n      entries_ordered client id client' id' net.\n  Proof using. \n    intros. unfold in_applied_entries, entries_ordered in *.\n    induction (applied_entries (nwState net)); simpl in *; break_exists; intuition.\n    - subst. left. unfold has_key. break_match.\n      simpl. break_if; repeat (do_bool; intuition).\n    - right. intuition.\n      + apply Bool.not_true_iff_false. intuition.\n        find_false.\n        unfold has_key in *. break_match; simpl in *; break_if; repeat (do_bool; intuition); try congruence.\n        subst. eexists; intuition; eauto.\n      + eapply IHl.\n        * eexists; intuition; eauto.\n        * intuition. find_false. break_exists_exists. intuition.\n  Qed.\n\n  Lemma in_applied_entries_applied_implies_input_state :\n    forall net,\n      in_applied_entries client' id' net ->\n      exists e,\n        eClient e = client' /\\\n        eId e = id' /\\\n        applied_implies_input_state client' id' (eInput e) net.\n  Proof using. \n    intros.\n    unfold in_applied_entries in *. break_exists_exists.\n    intuition. red. exists x. intuition.\n    - red. auto.\n    - unfold applied_entries in *. break_match.\n      + find_apply_lem_hyp in_rev.\n        find_apply_lem_hyp removeAfterIndex_in.\n        eauto.\n      + simpl in *. intuition.\n  Qed.\n  \n  Program Instance TR : TraceRelation step_failure :=\n    {\n      init := step_failure_init;\n      T := output_before_input client id client' id';\n      R := fun s => entries_ordered client id client' id' (snd s)\n    }.\n  Next Obligation.\n    unfold output_before_input.\n    eapply before_func_dec.\n  Defined.\n  Next Obligation.\n    simpl in *.\n    unfold entries_ordered in *.\n    find_apply_lem_hyp step_failure_star_raft_intermediate_reachable.\n    find_eapply_lem_hyp applied_entries_monotonic'; eauto.\n    break_exists; repeat find_rewrite.\n    eauto using before_func_app.\n  Defined.\n  Next Obligation.\n    simpl in *.\n    find_copy_eapply_lem_hyp output_before_input_not_key_in_input_trace; eauto.\n    find_copy_apply_lem_hyp output_before_input_key_in_output_trace.\n    find_eapply_lem_hyp output_implies_applied;\n      [|eapply refl_trans_n1_1n_trace; econstructor; eauto using refl_trans_1n_n1_trace].\n    eapply in_applied_entries_entries_ordered; auto.\n    intuition.\n    find_false.\n    find_apply_lem_hyp in_applied_entries_applied_implies_input_state.\n    break_exists. intuition.\n    eexists. eapply applied_implies_input; eauto.\n    eapply refl_trans_n1_1n_trace; econstructor; eauto using refl_trans_1n_n1_trace.\n  Defined.\n\n  Theorem causal_order_preserved :\n    forall failed net tr,\n      step_failure_star step_failure_init (failed, net) tr ->\n      output_before_input client id client' id' tr ->\n      entries_ordered client id client' id' net.\n  Proof using aemi aiii oiai. \n    intros. pose proof (trace_relations_work (failed, net) tr).\n    concludes. intuition.\n  Qed.\n\n  End inner.\n\n  Instance copi : causal_order_preserved_interface.\n  Proof.\n    split.\n    intros.\n    eapply causal_order_preserved; eauto.\n  Qed.\nEnd CausalOrderPreserved.\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/CausalOrderPreservedProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2571033856120266}}
{"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 A B C D P Q C0 Q0 C1 A0 Y : Universe, ((wd_ P C0 /\\ (wd_ P Q /\\ (wd_ P Q0 /\\ (wd_ C0 Q0 /\\ (wd_ A B /\\ (wd_ B Q0 /\\ (wd_ A Q0 /\\ (wd_ C0 A /\\ (wd_ C0 B /\\ (wd_ Q C0 /\\ (wd_ B Q /\\ (wd_ A Q /\\ (wd_ C D /\\ (wd_ D P /\\ (wd_ C P /\\ (wd_ C A /\\ (wd_ C B /\\ (wd_ D A /\\ (wd_ D B /\\ (wd_ C1 C0 /\\ (wd_ C0 A0 /\\ (wd_ P A0 /\\ (wd_ Y P /\\ (col_ A B P /\\ (col_ C0 C D /\\ (col_ Q P Q0 /\\ (col_ C D C1 /\\ (col_ A B A0 /\\ (col_ C0 C1 Y /\\ col_ P Q0 Y))))))))))))))))))))))))))))) -> col_ P Q Y)).\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_0509.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.25709772721541296}}
{"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.\nFrom PromisingLib Require Import DenseOrder.\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 Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import Cover.\n\nSet Implicit Arguments.\n\n\nInductive sim_message: forall (msg_src msg_tgt: Message.t), Prop :=\n| sim_message_full\n    val released_src released_tgt\n    (RELEASED: View.opt_le released_src released_tgt):\n    sim_message (Message.full val released_src) (Message.full val released_tgt)\n| sim_message_reserve:\n    sim_message Message.reserve Message.reserve\n.\n#[export]\nHint Constructors sim_message: core.\n\n#[export]\nProgram Instance sim_message_PreOrder: PreOrder sim_message.\nNext Obligation.\n  ii. destruct x; econs; refl.\nQed.\nNext Obligation.\n  ii. inv H; inv H0; econs. etrans; eauto.\nQed.\n\nInductive message_same_kind: forall (msg_src msg_tgt: Message.t), Prop :=\n| message_same_kind_full\n    val_src val_tgt released_src released_tgt:\n    message_same_kind (Message.full val_src released_src) (Message.full val_tgt released_tgt)\n| same_message_kine_reserve:\n    message_same_kind Message.reserve Message.reserve\n.\n#[export]\nHint Constructors sim_message: core.\n\n#[export]\nProgram Instance message_same_kind_Equivalence: Equivalence message_same_kind.\nNext Obligation.\n  ii. destruct x; econs.\nQed.\nNext Obligation.\n  ii. inv H; econs.\nQed.\nNext Obligation.\n  ii. inv H; inv H0; econs.\nQed.\n\nLemma sim_message_message_same_kind\n      msg_src msg_tgt\n      (SIM: sim_message msg_src msg_tgt):\n  message_same_kind msg_src msg_tgt.\nProof.\n  inv SIM; econs.\nQed.\n\nInductive sim_memory (mem_src mem_tgt:Memory.t): Prop :=\n| sim_memory_intro\n    (COVER: forall loc ts, covered loc ts mem_src <-> covered loc ts mem_tgt)\n    (MSG: forall loc from_tgt to msg_tgt\n            (GET: Memory.get loc to mem_tgt = Some (from_tgt, msg_tgt)),\n        exists from_src msg_src,\n          <<GET: Memory.get loc to mem_src = Some (from_src, msg_src)>> /\\\n          <<MSG: sim_message msg_src msg_tgt>>)\n    (RESERVE: forall loc from to,\n        Memory.get loc to mem_src = Some (from, Message.reserve) <->\n        Memory.get loc to mem_tgt = Some (from, Message.reserve))\n.\n\n#[export]\nProgram Instance sim_memory_PreOrder: PreOrder sim_memory.\nNext Obligation.\n  econs; try refl. i. esplits; eauto. refl.\nQed.\nNext Obligation.\n  ii. inv H. inv H0. econs; try etrans; eauto. i.\n  exploit MSG0; eauto. i. des.\n  exploit MSG; eauto. i. des.\n  esplits; eauto. etrans; eauto.\nQed.\n\n\nLemma sim_memory_get\n      loc from_tgt to msg_tgt mem_src mem_tgt\n      (SIM: sim_memory mem_src mem_tgt)\n      (GET: Memory.get loc to mem_tgt = Some (from_tgt, msg_tgt)):\n  exists from_src msg_src,\n    <<GET: Memory.get loc to mem_src = Some (from_src, msg_src)>> /\\\n    <<MSG: sim_message msg_src msg_tgt>>.\nProof.\n  eapply SIM. eauto.\nQed.\n\nLemma sim_memory_get_message_same_kind\n      loc\n      from_src to_src msg_src mem_src\n      from_tgt to_tgt msg_tgt mem_tgt\n      ts\n      (SIM: sim_memory mem_src mem_tgt)\n      (GET_SRC: Memory.get loc to_src mem_src = Some (from_src, msg_src))\n      (GET_TGT: Memory.get loc to_tgt mem_tgt = Some (from_tgt, msg_tgt))\n      (ITV_SRC: Interval.mem (from_src, to_src) ts)\n      (ITV_TGT: Interval.mem (from_tgt, to_tgt) ts):\n  message_same_kind msg_src msg_tgt.\nProof.\n  destruct msg_src, msg_tgt; try by econs.\n  - inv SIM. rewrite <- RESERVE in GET_TGT.\n    exploit Memory.get_disjoint; [exact GET_SRC|exact GET_TGT|..]. i. des; try congr.\n    exfalso. apply (x0 ts); auto.\n  - inv SIM. rewrite RESERVE in GET_SRC.\n    exploit Memory.get_disjoint; [exact GET_SRC|exact GET_TGT|..]. i. des; try congr.\n    exfalso. apply (x0 ts); auto.\nQed.\n\nLemma sim_memory_get_inv\n      loc from_src to_src msg_src mem_src\n      mem_tgt\n      (INHABITED_SRC: Memory.inhabited mem_src)\n      (INHABITED_TGT: Memory.inhabited mem_tgt)\n      (SIM: sim_memory mem_src mem_tgt)\n      (GET_SRC: Memory.get loc to_src mem_src = Some (from_src, msg_src)):\n  exists from_tgt to_tgt msg_tgt,\n    <<FROM: Time.le from_tgt from_src>> /\\\n    <<TO: Time.le to_src to_tgt>> /\\\n    <<GET_TGT: Memory.get loc to_tgt mem_tgt = Some (from_tgt, msg_tgt)>> /\\\n    <<MSG: message_same_kind msg_src msg_tgt>>.\nProof.\n  destruct (Time.eq_dec to_src Time.bot).\n  { subst. rewrite INHABITED_SRC in GET_SRC. inv GET_SRC.\n    esplits; try refl. apply INHABITED_TGT. }\n  dup SIM. inv SIM0. dup COVER. specialize (COVER0 loc to_src). des.\n  exploit COVER0.\n  { econs; eauto. econs; try refl.\n    exploit Memory.get_ts; eauto. i. des; subst; timetac. }\n  intro x. dup x. inv x0. esplits; eauto.\n  - destruct (Time.le_lt_dec from from_src); ss.\n    dup COVER. specialize (COVER2 loc from). des. exploit COVER2.\n    { econs; eauto.\n      exploit Memory.get_ts; try exact GET_SRC. i. des; ss.\n      inv ITV. econs; eauto. econs. ss. }\n    intro x0. inv x0.\n    destruct (Time.eq_dec to0 from).\n    + subst. exploit MSG; try exact GET0. i. des.\n      exploit Memory.get_disjoint; [exact GET_SRC|exact GET1|..]. i. des.\n      * subst. inv ITV. timetac.\n      * exfalso. apply (x1 from).\n        { inv ITV. econs; eauto. s. econs; eauto. }\n        { econs; try refl. s.\n          exploit Memory.get_ts; try exact GET1. i. des; ss.\n          subst. inv ITV0. inv FROM. }\n    + exploit Memory.get_disjoint; [exact GET|exact GET0|..]. i. des.\n      * subst. inv ITV0. timetac.\n      * exfalso. destruct (Time.le_lt_dec to to0).\n        { apply (x1 to).\n          - econs; try refl.\n            exploit Memory.get_ts; try exact GET. i. des; ss.\n            subst. inv ITV0. inv FROM.\n          - econs; eauto. inv ITV0. ss.\n            exploit Memory.get_ts; try exact GET. i. des; ss.\n            + subst. inv l.\n            + eapply TimeFacts.lt_le_lt; eauto. econs; eauto. }\n        { apply (x1 to0).\n          - inv ITV0. econs; ss.\n            + inv TO; ss. inv H. congr.\n            + econs. ss.\n          - econs; try refl.\n            exploit Memory.get_ts; try exact GET0. i. des; ss.\n            subst. inv ITV0. ss. inv TO; inv H. inv FROM. }\n  - inv ITV. ss.\n  - eapply sim_memory_get_message_same_kind; eauto.\n    exploit Memory.get_ts; try exact GET_SRC. i. des; try congr.\n    econs; eauto. refl.\nQed.\n\nLemma sim_memory_max_ts\n      mem_src mem_tgt loc\n      (SIM: sim_memory mem_src mem_tgt)\n      (CLOSED_SRC: Memory.closed mem_src)\n      (CLOSED_TGT: Memory.closed mem_tgt):\n  Memory.max_ts loc mem_src = Memory.max_ts loc mem_tgt.\nProof.\n  inv SIM. inv CLOSED_SRC. inv CLOSED_TGT.\n  clear MSG RESERVE CLOSED CLOSED0.\n  apply TimeFacts.antisym.\n  - specialize (COVER loc (Memory.max_ts loc mem_src)). des.\n    exploit Memory.max_ts_spec; try eapply (INHABITED loc). i. des.\n    exploit Memory.get_ts; eauto. i. des.\n    { rewrite x1. apply Time.bot_spec. }\n    exploit COVER.\n    { econs; eauto. econs; eauto. refl. }\n    intro x. inv x. exploit Memory.max_ts_spec; try exact GET0. i. des.\n    inv ITV. ss. etrans; eauto.\n  - specialize (COVER loc (Memory.max_ts loc mem_tgt)). des.\n    exploit Memory.max_ts_spec; try eapply (INHABITED0 loc). i. des.\n    exploit Memory.get_ts; eauto. i. des.\n    { rewrite x1. apply Time.bot_spec. }\n    exploit COVER0.\n    { econs; eauto. econs; eauto. refl. }\n    intro x. inv x. exploit Memory.max_ts_spec; try exact GET0. i. des.\n    inv ITV. ss. etrans; eauto.\nQed.\n\nLemma sim_memory_max_full_ts\n      mem_src mem_tgt\n      loc mts_src mts_tgt\n      (SIM: sim_memory mem_src mem_tgt)\n      (CLOSED_SRC: Memory.closed mem_src)\n      (CLOSED_TGT: Memory.closed mem_tgt)\n      (MAX_SRC: Memory.max_full_ts mem_src loc mts_src)\n      (MAX_TGT: Memory.max_full_ts mem_tgt loc mts_tgt):\n  mts_src = mts_tgt.\nProof.\n  apply TimeFacts.antisym.\n  - inv MAX_SRC. des.\n    exploit sim_memory_get_inv; eauto.\n    { apply CLOSED_SRC. }\n    { apply CLOSED_TGT. }\n    i. des. inv MSG.\n    exploit Memory.max_full_ts_spec; eauto. i. des.\n    etrans; eauto.\n  - inv MAX_TGT. des.\n    inv SIM. exploit MSG; eauto. i. des. inv MSG0.\n    exploit Memory.max_full_ts_spec; eauto. i. des. ss.\nQed.\n\nLemma sim_memory_max_full_timemap\n      mem_src mem_tgt mtm_src mtm_tgt\n      (CLOSED_SRC: Memory.closed mem_src)\n      (CLOSED_TGT: Memory.closed mem_tgt)\n      (SIM: sim_memory mem_src mem_tgt)\n      (MAX_SRC: Memory.max_full_timemap mem_src mtm_src)\n      (MAX_TGT: Memory.max_full_timemap mem_tgt mtm_tgt):\n  mtm_src = mtm_tgt.\nProof.\n  extensionality loc.\n  specialize (MAX_SRC loc).\n  specialize (MAX_TGT loc).\n  eapply sim_memory_max_full_ts; eauto.\nQed.\n\nLemma sim_memory_max_full_view\n      mem_src mem_tgt mview_src mview_tgt\n      (CLOSED_SRC: Memory.closed mem_src)\n      (CLOSED_TGT: Memory.closed mem_tgt)\n      (SIM: sim_memory mem_src mem_tgt)\n      (MAX_SRC: Memory.max_full_view mem_src mview_src)\n      (MAX_TGT: Memory.max_full_view mem_tgt mview_tgt):\n  mview_src = mview_tgt.\nProof.\n  inv MAX_SRC. inv MAX_TGT.\n  exploit sim_memory_max_full_timemap; try exact SIM; eauto. i.\n  subst. ss.\nQed.\n\nLemma split_sim_memory\n      mem0 loc ts1 ts2 ts3 val2 released2 val3 released3 mem1\n      (SPLIT: Memory.split mem0 loc ts1 ts2 ts3 (Message.full val2 released2) (Message.full val3 released3) mem1):\n  sim_memory mem1 mem0.\nProof.\n  econs; i.\n  - eapply split_covered. eauto.\n  - exploit Memory.split_get0; eauto. i. des.\n    erewrite Memory.split_o; eauto. repeat condtac; ss.\n    + des. subst. congr.\n    + guardH o. des. subst. rewrite GET1 in GET. inv GET.\n      esplits; eauto. refl.\n    + esplits; eauto. refl.\n  - exploit Memory.split_get0; eauto. i. des.\n    erewrite Memory.split_o; eauto.\n    repeat condtac; ss; split; i; try congr.\n    + des. subst. rewrite GET in H. inv H.\n    + guardH o. des. subst. rewrite GET0 in H. inv H.\nQed.\n\nLemma lower_sim_memory\n      mem1 loc from to msg1 msg2 mem2\n      (LOWER: Memory.lower mem1 loc from to msg1 msg2 mem2)\n      (MSG: message_same_kind msg1 msg2):\n  sim_memory mem2 mem1.\nProof.\n  econs; i.\n  - eapply lower_covered. eauto.\n  - i. erewrite Memory.lower_o; eauto. condtac; ss.\n    + des. subst.\n      exploit Memory.lower_get0; eauto. i. des.\n      rewrite GET0 in GET. inv GET.\n      inv MSG_LE; inv MSG; esplits; eauto.\n    + esplits; eauto. refl.\n  - split; i.\n    + revert H. erewrite Memory.lower_o; eauto. condtac; ss.\n      i. des. subst. inv H. inv LOWER. inv LOWER0. inv MSG.\n      unfold Memory.get, Cell.get. rewrite GET2. ss.\n    + erewrite Memory.lower_o; eauto. condtac; ss.\n      des. subst. inv LOWER. inv LOWER0.\n      unfold Memory.get, Cell.get in H. rewrite H in GET2. inv GET2.\n      inv MSG. ss.\nQed.\n\nLemma promise_lower_sim_memory\n      promises1 mem1 loc from to msg1 msg2 promises2 mem2\n      (PROMISE: Memory.promise promises1 mem1 loc from to msg2 promises2 mem2 (Memory.op_kind_lower msg1))\n      (MSG: message_same_kind msg1 msg2):\n  sim_memory mem2 mem1.\nProof.\n  inv PROMISE. eapply lower_sim_memory; eauto.\nQed.\n\nLemma sim_memory_add\n      mem1_src mem1_tgt msg_src\n      mem2_src mem2_tgt msg_tgt\n      loc from to\n      (SIM_MSG: sim_message msg_src msg_tgt)\n      (SRC: Memory.add mem1_src loc from to msg_src mem2_src)\n      (TGT: Memory.add mem1_tgt loc from to msg_tgt mem2_tgt)\n      (SIM: sim_memory mem1_src mem1_tgt):\n  sim_memory mem2_src mem2_tgt.\nProof.\n  inv SIM. econs; i.\n  - rewrite add_covered; [|eauto]. rewrite (@add_covered mem2_tgt); [|eauto].\n    econs; i; des; (try by right).\n    + left. eapply COVER. eauto.\n    + left. eapply COVER. eauto.\n  - revert GET. erewrite Memory.add_o; eauto. condtac; ss.\n    + des. subst. i. inv GET. esplits; eauto.\n      erewrite Memory.add_o; eauto. condtac; ss.\n    + erewrite (@Memory.add_o mem2_src); eauto. condtac; ss. eauto.\n  - split; i.\n    + erewrite Memory.add_o in H; try exact SRC.\n      erewrite Memory.add_o; try exact TGT. condtac; ss.\n      * des. subst. inv H. inv SIM_MSG. ss.\n      * rewrite <- RESERVE. ss.\n    + erewrite Memory.add_o in H; try exact TGT.\n      erewrite Memory.add_o; try exact SRC. condtac; ss.\n      * des. subst. inv H. inv SIM_MSG. ss.\n      * rewrite RESERVE. ss.\nQed.\n\nLemma sim_memory_split\n      mem1_src mem1_tgt\n      mem2_src mem2_tgt\n      loc ts1 ts2 ts3 msg2_src msg3_src msg2_tgt msg3_tgt\n      (SIM_MSG: sim_message msg2_src msg2_tgt)\n      (SRC: Memory.split mem1_src loc ts1 ts2 ts3 msg2_src msg3_src mem2_src)\n      (TGT: Memory.split mem1_tgt loc ts1 ts2 ts3 msg2_tgt msg3_tgt mem2_tgt)\n      (SIM: sim_memory mem1_src mem1_tgt):\n  sim_memory mem2_src mem2_tgt.\nProof.\n  inv SIM. econs; i.\n  - rewrite split_covered; [|eauto]. rewrite (@split_covered mem2_tgt); [|eauto].\n    apply COVER.\n  - revert GET. erewrite Memory.split_o; eauto. repeat condtac; ss.\n    + des. subst. i. inv GET. esplits; eauto.\n      erewrite Memory.split_o; eauto. condtac; ss.\n    + erewrite (@Memory.split_o mem2_src); eauto. repeat condtac; ss.\n      i. inv GET. guardH o. guardH o0. des. subst.\n      exploit Memory.split_get0; try exact SRC; eauto. i. des.\n      exploit Memory.split_get0; try exact TGT; eauto. i. des.\n      exploit MSG; eauto. i. des. rewrite GET0 in GET7. inv GET7.\n      esplits; eauto.\n    + erewrite (@Memory.split_o mem2_src); eauto. repeat condtac; ss. eauto.\n  - split; i.\n    + erewrite Memory.split_o in H; try exact SRC.\n      erewrite Memory.split_o; try exact TGT. repeat condtac; ss.\n      * des. subst. inv H. inv SIM_MSG. ss.\n      * guardH o. des. subst. inv H.\n        exploit Memory.split_get0; try exact SRC. i. des.\n        exploit Memory.split_get0; try exact TGT. i. des.\n        rewrite RESERVE in GET0. rewrite GET0 in GET4. inv GET4. ss.\n      * rewrite <- RESERVE. ss.\n    + erewrite Memory.split_o in H; try exact TGT.\n      erewrite Memory.split_o; try exact SRC. repeat condtac; ss.\n      * des. subst. inv H. inv SIM_MSG. ss.\n      * guardH o. des. subst. inv H.\n        exploit Memory.split_get0; try exact SRC. i. des.\n        exploit Memory.split_get0; try exact TGT. i. des.\n        rewrite <- RESERVE in GET4. rewrite GET0 in GET4. inv GET4. ss.\n      * rewrite RESERVE. ss.\nQed.\n\nLemma sim_memory_lower\n      mem1_src mem1_tgt\n      mem2_src mem2_tgt\n      loc from to msg1_src msg2_src msg1_tgt msg2_tgt\n      (SIM_MSG: sim_message msg2_src msg2_tgt)\n      (SRC: Memory.lower mem1_src loc from to msg1_src msg2_src mem2_src)\n      (TGT: Memory.lower mem1_tgt loc from to msg1_tgt msg2_tgt mem2_tgt)\n      (SIM: sim_memory mem1_src mem1_tgt):\n  sim_memory mem2_src mem2_tgt.\nProof.\n  dup SIM. inv SIM0. econs; i.\n  - rewrite lower_covered; [|eauto]. rewrite (@lower_covered mem2_tgt); [|eauto].\n    apply COVER.\n  - revert GET. erewrite Memory.lower_o; eauto. condtac; ss.\n    + des. subst. i. inv GET. esplits; eauto.\n      erewrite Memory.lower_o; eauto. condtac; ss.\n    + erewrite (@Memory.lower_o mem2_src); eauto. condtac; ss. eauto.\n  - split; i.\n    + erewrite Memory.lower_o in H; try exact SRC.\n      erewrite Memory.lower_o; try exact TGT. condtac; ss.\n      * des. subst. inv H. inv SIM_MSG. ss.\n      * rewrite <- RESERVE. ss.\n    + erewrite Memory.lower_o in H; try exact TGT.\n      erewrite Memory.lower_o; try exact SRC. condtac; ss.\n      * des. subst. inv H. inv SIM_MSG. ss.\n      * rewrite RESERVE. ss.\nQed.\n\nLemma sim_memory_remove\n      mem1_src mem1_tgt\n      mem2_src mem2_tgt\n      loc from to msg_src msg_tgt\n      (SRC: Memory.remove mem1_src loc from to msg_src mem2_src)\n      (TGT: Memory.remove mem1_tgt loc from to msg_tgt mem2_tgt)\n      (SIM: sim_memory mem1_src mem1_tgt):\n  sim_memory mem2_src mem2_tgt.\nProof.\n  dup SIM. inv SIM0. econs; i.\n  - rewrite remove_covered; [|eauto]. rewrite (@remove_covered mem2_tgt); [|eauto].\n    rewrite COVER. refl.\n  - revert GET. erewrite Memory.remove_o; eauto. condtac; ss.\n    erewrite (@Memory.remove_o mem2_src); eauto. condtac; ss. eauto.\n  - split; i.\n    + erewrite Memory.remove_o in H; try exact SRC.\n      erewrite Memory.remove_o; try exact TGT. condtac; ss.\n      rewrite <- RESERVE. ss.\n    + erewrite Memory.remove_o in H; try exact TGT.\n      erewrite Memory.remove_o; try exact SRC. condtac; ss.\n      rewrite RESERVE. ss.\nQed.\n\nLemma sim_memory_closed_timemap\n      mem_src mem_tgt\n      tm\n      (SIM: sim_memory mem_src mem_tgt)\n      (TGT: Memory.closed_timemap tm mem_tgt):\n  Memory.closed_timemap tm mem_src.\nProof.\n  ii. exploit TGT; eauto. i. des.\n  exploit sim_memory_get; eauto. i. des.\n  inv MSG. eauto.\nQed.\n\nLemma sim_memory_closed_view\n      mem_src mem_tgt\n      view\n      (SIM: sim_memory mem_src mem_tgt)\n      (TGT: Memory.closed_view view mem_tgt):\n  Memory.closed_view view mem_src.\nProof.\n  econs.\n  - eapply sim_memory_closed_timemap; eauto. apply TGT.\n  - eapply sim_memory_closed_timemap; eauto. apply TGT.\nQed.\n\nLemma sim_memory_closed_opt_view\n      mem_src mem_tgt\n      view\n      (SIM: sim_memory mem_src mem_tgt)\n      (TGT: Memory.closed_opt_view view mem_tgt):\n  Memory.closed_opt_view view mem_src.\nProof.\n  inv TGT; econs. eapply sim_memory_closed_view; eauto.\nQed.\n\nLemma sim_memory_closed_message\n      mem_src mem_tgt\n      msg\n      (SIM: sim_memory mem_src mem_tgt)\n      (TGT: Memory.closed_message msg mem_tgt):\n  Memory.closed_message msg mem_src.\nProof.\n  inv TGT; ss. econs. eapply sim_memory_closed_opt_view; eauto.\nQed.\n\nLemma sim_memory_latest_val_src\n      mem_src mem_tgt loc val\n      (SIM: sim_memory mem_src mem_tgt)\n      (CLOSED_SRC: Memory.closed mem_src)\n      (CLOSED_TGT: Memory.closed mem_tgt)\n      (LATEST: Memory.latest_val loc mem_src val):\n  Memory.latest_val loc mem_tgt val.\nProof.\n  inv LATEST.\n  exploit Memory.max_full_ts_exists; try apply CLOSED_TGT. i. des.\n  exploit sim_memory_max_full_ts; eauto. i. subst.\n  dup x0. inv x1. des.\n  inv SIM. exploit MSG; eauto. i. des. inv MSG0.\n  rewrite GET1 in GET. inv GET.\n  econs; eauto.\nQed.\n\nLemma sim_memory_latest_val_tgt\n      mem_src mem_tgt loc val\n      (SIM: sim_memory mem_src mem_tgt)\n      (CLOSED_SRC: Memory.closed mem_src)\n      (CLOSED_TGT: Memory.closed mem_tgt)\n      (LATEST: Memory.latest_val loc mem_tgt val):\n  Memory.latest_val loc mem_src val.\nProof.\n  inv LATEST.\n  exploit Memory.max_full_ts_exists; try apply CLOSED_SRC. i. des.\n  exploit sim_memory_max_full_ts; eauto. i. subst.\n  dup x0. inv x1. des.\n  inv SIM. exploit MSG; eauto. i. des. inv MSG0.\n  unfold Memory.get in *. rewrite GET0 in GET1. inv GET1.\n  econs; eauto.\nQed.\n\nLemma sim_memory_adjacent_src\n      mem_src mem_tgt\n      loc from1 to1 from2 to2\n      (SIM: sim_memory mem_src mem_tgt)\n      (CLOSED_SRC: Memory.closed mem_src)\n      (CLOSED_TGT: Memory.closed mem_tgt)\n      (ADJ: Memory.adjacent loc from1 to1 from2 to2 mem_src)\n      (TS: Time.lt to1 from2):\n  exists from1' to2',\n    Memory.adjacent loc from1' to1 from2 to2' mem_tgt.\nProof.\n  dup SIM. inv SIM0. inv ADJ. clear RESERVE TS0.\n  assert (GET1_TGT: exists from1' m1', Memory.get loc to1 mem_tgt = Some (from1', m1')).\n  { exploit Memory.get_ts; try exact GET1. i. des.\n    { subst. esplits. eapply CLOSED_TGT. }\n    destruct (COVER loc to1). exploit H.\n    { econs; try exact GET1. econs; eauto. refl. }\n    intro x. inv x. inv ITV. ss. inv TO; cycle 1.\n    { inv H1. esplits; eauto. }\n    exfalso.\n    destruct (Time.le_lt_dec to from2).\n    { exploit MSG; eauto. i. des.\n      exploit (EMPTY to); eauto. i. congr. }\n    destruct (COVER loc from2). exploit H3.\n    { econs; eauto. econs; eauto. econs. ss. }\n    intro x. inv x. inv ITV. ss. inv TO.\n    - exploit Memory.get_ts; try exact GET2. i. des.\n      { subst. inv FROM0. }\n      exploit Memory.get_ts; try exact GET0. i. des.\n      { subst. inv H4. }\n      exploit Memory.get_disjoint; [exact GET2|exact GET0|..]. i. des.\n      { timetac. }\n      destruct (Time.le_lt_dec to2 to0).\n      + apply (x3 to2); econs; ss; try refl.\n        etrans; try exact FROM0. ss.\n      + apply (x3 to0); econs; ss; try refl.\n        econs. ss.\n    - inv H4. exploit (EMPTY to0); eauto; try refl. i. congr.\n  }\n  assert (GET2_TGT: exists to2' m2', Memory.get loc to2' mem_tgt = Some (from2, m2')).\n  { exploit Memory.get_ts; try exact GET2. i. des.\n    { subst. inv TS. }\n    exploit Memory.max_ts_spec; try exact GET2. i. des.\n    clear from msg GET.\n    erewrite sim_memory_max_ts in MAX; eauto.\n    exploit TimeFacts.lt_le_lt; try exact x0; try exact MAX. i.\n    exploit Memory.next_exists; try exact x1; try eapply CLOSED_TGT. i. des.\n    destruct (TimeFacts.le_lt_dec from from2).\n    - inv l; cycle 1.\n      { inv H. esplits; eauto. }\n      destruct (COVER loc from2). exploit H1.\n      { econs; try exact x2. econs; ss. econs; ss. }\n      intro x. inv x. inv ITV. ss. inv TO; cycle 1.\n      { inv H2. exploit (EMPTY to0); eauto; try refl. i. congr. }\n      exploit Memory.get_disjoint; [exact GET2|exact GET|..]. i. des.\n      { subst. timetac. }\n      exfalso.\n      destruct (TimeFacts.le_lt_dec to2 to0).\n      + apply (x5 to2); econs; ss; try refl.\n        etrans; try exact FROM. ss.\n      + apply (x5 to0); econs; ss; try refl.\n        * econs. ss.\n        * etrans; eauto.\n    - destruct (TimeFacts.le_lt_dec to2 from).\n      + destruct (COVER loc to2). exploit H.\n        { econs; eauto. econs; ss. refl. }\n        intro x. inv x. inv ITV. ss.\n        exploit (x4 to0); eauto; try congr.\n        { eapply TimeFacts.lt_le_lt; try exact TO; ss. }\n        destruct (Time.le_lt_dec to to0); ss.\n        exploit Memory.get_ts; try exact x2. i. des.\n        { subst. inv x3. }\n        exploit Memory.get_disjoint; [exact x2|exact GET|..]. i. des.\n        { subst. timetac. }\n        exfalso.\n        apply (x6 to); econs; ss; try refl.\n        etrans; try exact FROM.\n        eapply TimeFacts.le_lt_lt; try exact x5. ss.\n      + destruct (COVER loc from). exploit H.\n        { econs; try exact GET2. econs; ss. econs. ss. }\n        intro x. inv x. inv ITV. ss.\n        destruct (TimeFacts.le_lt_dec to to0).\n        * exploit Memory.get_ts; try exact x2. i. des.\n          { subst. inv x3. }\n          exploit Memory.get_ts; try exact GET. i. des.\n          { subst. timetac. }\n          exploit Memory.get_disjoint; [exact x2|exact GET|..]. i. des.\n          { subst. timetac. }\n          exfalso.\n          apply (x7 to); econs; ss; try refl.\n          eapply TimeFacts.lt_le_lt; try exact FROM. econs. ss.\n        * exploit (x4 to0); ss; try congr.\n          eapply TimeFacts.lt_le_lt; try exact TO; ss.\n  }\n  des. esplits. econs; eauto; i.\n  { exploit Memory.get_ts; try exact GET2_TGT. i. des.\n    - subst. inv TS.\n    - etrans; eauto. }\n  destruct (Memory.get loc ts mem_tgt) as [[]|] eqn:GET; ss.\n  exfalso.\n  exploit Memory.get_ts; try exact GET. i. des.\n  { subst. inv TS1. }\n  destruct (COVER loc ts). exploit H0.\n  { econs; eauto. econs; ss. refl. }\n  intro x. inv x. inv ITV. ss.\n  destruct (TimeFacts.le_lt_dec to from2).\n  { exploit (EMPTY to); try congr.\n    eapply TimeFacts.lt_le_lt; try exact TS1. ss. }\n  exploit Memory.get_ts; try exact GET2. i. des.\n  { subst. inv TS. }\n  exploit Memory.get_ts; try exact GET0. i. des.\n  { subst. inv l. }\n  exploit Memory.get_disjoint; [exact GET2|exact GET0|..]. i. des.\n  { subst. timetac. }\n  destruct (TimeFacts.le_lt_dec to2 to).\n  - apply (x3 to2); econs; ss; try refl.\n    etrans; try exact x1.\n    eapply TimeFacts.lt_le_lt; try exact TS2. ss.\n  - apply (x3 to); econs; ss; try refl. econs. ss.\nQed.\n\nLemma sim_memory_adjacent_tgt\n      mem_src mem_tgt\n      loc from1 to1 from2 to2\n      (SIM: sim_memory mem_src mem_tgt)\n      (CLOSED_SRC: Memory.closed mem_src)\n      (CLOSED_TGT: Memory.closed mem_tgt)\n      (ADJ: Memory.adjacent loc from1 to1 from2 to2 mem_tgt)\n      (TS: Time.lt to1 from2):\n  exists from1' to2',\n    Memory.adjacent loc from1' to1 from2 to2' mem_src.\nProof.\n  dup SIM. inv SIM0. inv ADJ. clear RESERVE TS0.\n  assert (GET1_SRC: exists from1' m1', Memory.get loc to1 mem_src = Some (from1', m1')).\n  { exploit MSG; try exact GET1. i. des. eauto. }\n  assert (GET2_SRC: exists to2' m2', Memory.get loc to2' mem_src = Some (from2, m2')).\n  { exploit Memory.get_ts; try exact GET2. i. des.\n    { subst. inv TS. }\n    exploit Memory.max_ts_spec; try exact GET2. i. des.\n    clear from msg GET.\n    erewrite <- sim_memory_max_ts in MAX; eauto.\n    exploit TimeFacts.lt_le_lt; try exact x0; try exact MAX. i.\n    exploit Memory.next_exists; try exact x1; try eapply CLOSED_SRC. i. des.\n    destruct (TimeFacts.le_lt_dec from from2).\n    - inv l; cycle 1.\n      { inv H. esplits; eauto. }\n      destruct (COVER loc from2). exploit H0.\n      { econs; try exact x2. econs; ss. econs; ss. }\n      intro x. inv x. inv ITV. ss. inv TO; cycle 1.\n      { inv H2. exploit (EMPTY to0); eauto; try refl. i. congr. }\n      exploit Memory.get_disjoint; [exact GET2|exact GET|..]. i. des.\n      { subst. timetac. }\n      exfalso.\n      destruct (TimeFacts.le_lt_dec to2 to0).\n      + apply (x5 to2); econs; ss; try refl.\n        etrans; try exact FROM. ss.\n      + apply (x5 to0); econs; ss; try refl.\n        * econs. ss.\n        * etrans; eauto.\n    - destruct (TimeFacts.le_lt_dec to2 from).\n      + destruct (COVER loc to2). exploit H0.\n        { econs; eauto. econs; ss. refl. }\n        intro x. inv x. inv ITV. ss.\n        exploit (x4 to0); eauto; try congr.\n        { eapply TimeFacts.lt_le_lt; try exact TO; ss. }\n        destruct (Time.le_lt_dec to to0); ss.\n        exploit Memory.get_ts; try exact x2. i. des.\n        { subst. inv x3. }\n        exploit Memory.get_disjoint; [exact x2|exact GET|..]. i. des.\n        { subst. timetac. }\n        exfalso.\n        apply (x6 to); econs; ss; try refl.\n        etrans; try exact FROM.\n        eapply TimeFacts.le_lt_lt; try exact x5. ss.\n      + destruct (COVER loc from). exploit H0.\n        { econs; try exact GET2. econs; ss. econs. ss. }\n        intro x. inv x. inv ITV. ss.\n        destruct (TimeFacts.le_lt_dec to to0).\n        * exploit Memory.get_ts; try exact x2. i. des.\n          { subst. inv x3. }\n          exploit Memory.get_ts; try exact GET. i. des.\n          { subst. timetac. }\n          exploit Memory.get_disjoint; [exact x2|exact GET|..]. i. des.\n          { subst. timetac. }\n          exfalso.\n          apply (x7 to); econs; ss; try refl.\n          eapply TimeFacts.lt_le_lt; try exact FROM. econs. ss.\n        * exploit (x4 to0); ss; try congr.\n          eapply TimeFacts.lt_le_lt; try exact TO; ss.\n  }\n  des. esplits. econs; eauto; i.\n  { exploit Memory.get_ts; try exact GET2_SRC. i. des.\n    - subst. inv TS.\n    - etrans; eauto. }\n  destruct (Memory.get loc ts mem_src) as [[]|] eqn:GET; ss.\n  exfalso.\n  exploit Memory.get_ts; try exact GET. i. des.\n  { subst. inv TS1. }\n  destruct (COVER loc ts). exploit H.\n  { econs; eauto. econs; ss. refl. }\n  intro x. inv x. inv ITV. ss.\n  destruct (TimeFacts.le_lt_dec to from2).\n  { exploit (EMPTY to); try congr.\n    eapply TimeFacts.lt_le_lt; try exact TS1. ss. }\n  exploit Memory.get_ts; try exact GET2. i. des.\n  { subst. inv TS. }\n  exploit Memory.get_ts; try exact GET0. i. des.\n  { subst. inv l. }\n  exploit Memory.get_disjoint; [exact GET2|exact GET0|..]. i. des.\n  { subst. timetac. }\n  destruct (TimeFacts.le_lt_dec to2 to).\n  - apply (x3 to2); econs; ss; try refl.\n    etrans; try exact x1.\n    eapply TimeFacts.lt_le_lt; try exact TS2. ss.\n  - apply (x3 to); econs; ss; try refl. econs. ss.\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/SimMemory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.25708451902292784}}
{"text": "(*  DEC 2.0 language specification.\n   Paolo Torrini  \n   Universite' de Lille - CRIStAL-CNRS\n*)\n\nRequire Import List.\nRequire Import Equality.\nRequire Import Eqdep.\nRequire Import PeanoNat.\nRequire Import Omega.\nRequire Import ProofIrrelevance.\n\nRequire Import AuxLibI1.\nRequire Import TypSpecI1. \nRequire Import ModTypI1. \nRequire Import LangSpecI1. \nRequire Import StaticSemI1.\nRequire Import DynamicSemI1.\nRequire Import WeakenI1.\nRequire Import UniqueTypI1.\nRequire Import DerivDynI1.\nRequire Import TransPrelimI1.\nRequire Import TSoundnessI1.\nRequire Import SReducI1.\nRequire Import DetermI1.\n\nImport ListNotations.\n\n\nModule PreRefl (IdT: ModTyp) <: ModTyp.\n\nModule DetermL := Determ IdT.\nExport DetermL.\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\nOpen Scope type_scope.\n\n(* extends the shallow environment *)\nLemma ext_senv (tenv : valTC)\n      (X : tlist2type (map sVTyp (map snd tenv))) (x: Id) (t: VTyp)\n      (sv : sVTyp t) :\n       valTC_Trans ((x, t) :: tenv).\n   unfold valTC_Trans.\n   simpl.\n   constructor.\n   exact sv.\n   exact X.\nDefined.\n\n(* extract values of x from senv *)\nLemma ExpDenotI_Var \n  (ftenv : funTC)\n  (tenv : valTC)\n  (x : Id)\n  (t : VTyp)\n  (i :  IdTyping tenv x t) :\n  (* sfenv *) tlist2type (map snd (FunTC_ListTrans ftenv)) ->\n  (* senv *) valTC_Trans tenv -> MM WW (sVTyp t).\n  intros.\n  assert (sVTyp t).\n  eapply (extract_from_valTC_TransB tenv X0 x).\n  auto.\n  unfold MM.\n  intro X2.\n  exact (X1,X2).\nDefined.  \n\n(* extract values of x from senv; \n   replaces ExpDenotI_Var *)\nLemma ExpDenI_Var \n  (tenv : valTC)\n  (x : Id)\n  (t : VTyp)\n  (i :  IdTyping tenv x t) :\n               (* senv: *) valTC_Trans tenv ->\n               MM WW (sVTyp t).\n  intros.\n  assert (sVTyp t).\n  eapply (extract_from_valTC_TransB tenv X x).\n  auto.\n  unfold MM.\n  intro X1.\n  exact (X0,X1).\nDefined.  \n\nLemma ExpDenI2_Var \n  (tenv : valTC)\n  (x : Id)\n  (t : VTyp)\n  (i :  IdTyping tenv x t) (n: nat) :\n               valTC_Trans tenv ->\n               W -> (sVTyp t * W) * (sigT (fun n0 => n0 <= n)).\n  intros.\n  assert (sVTyp t).\n  eapply (extract_from_valTC_TransB tenv X x).\n  auto.\n  split.\n  exact (X1,X0).\n  econstructor 1 with (x:=n).\n  auto.\nDefined.  \n\nLemma ExpTransAux1_Var \n    (x : Id)\n    (v : Value) \n    (t : VTyp) (mB: valueVTyp v = t)\n    (n0 : nat) (s0 : W) :\n              (sVTyp t * W) * (sigT (fun n => n <= n0)).\n  unfold valueVTyp in mB.\n  destruct v.\n  rewrite <- mB. \n  simpl.\n  destruct v.\n  split.\n  exact (v, s0).\n  econstructor 1 with (x:= n0).\n  auto.\nDefined.\n\nLemma ExpTransAux2_Var\n      (tenv: valTC) (env: valEnv)\n      (m: EnvTyping env tenv)\n      (x : Id)\n      (t : VTyp)\n      (i : IdTyping tenv x t) \n      (n0 : nat) (s0 : W) :\n              (sVTyp t * W) * (sigT (fun n => n <= n0)).\n  eapply (ExpTransAux1_Var x\n                           (ExtRelVal2A_1 valueVTyp tenv env x t m i)\n                           t           \n                           (ExtRelVal2A_4 valueVTyp tenv env x t m i)\n                           n0 s0).\nDefined.\n\n\n(*******************************************************************)\n\nDefinition ExpTrans1_def :=   \n   fun (ftenv: funTC) (tenv: valTC) (e: Exp) (t: VTyp) \n       (k: ExpTyping ftenv tenv e t) => \n     forall (sfenv: nat -> tlist2type (map snd (FunTC_ListTrans ftenv))),  \n      (valTC_Trans tenv -> MM WW (sVTyp t)).     \n\nDefinition PrmsTrans1_def :=   \n   fun (ftenv: funTC) (tenv: valTC) (ps: Prms) (pt: PTyp) \n       (k: PrmsTyping ftenv tenv ps pt) =>        \n     forall (sfenv: nat -> tlist2type (map snd (FunTC_ListTrans ftenv))),\n      (valTC_Trans tenv -> MM WW (PTyp_Trans pt)).\n\n\nDefinition Trans_ExpTyping_mut1 :=\n  ExpTyping_mut ExpTrans1_def PrmsTrans1_def. \n\nDefinition Trans_PrmsTyping_mut1 :=\n  PrmsTyping_mut ExpTrans1_def PrmsTrans1_def.\n\n  \nLemma ExpDenotK_Var :\n  forall (ftenv : funTC) (tenv : valTC) (x : StaticSemL.Id) \n    (t : VTyp) (i : IdTyping tenv x t),\n  ExpTrans1_def ftenv tenv (Var x) t (Var_Typing ftenv tenv x t i).\n     unfold ExpTrans1_def.\n     intros.\n     eapply ExpDenI_Var.\n     exact i.\n     exact X.\nDefined.\n\n\nProgram Fixpoint ExpTrans (ftenv: funTC) (tenv: valTC) (e: Exp) (t: VTyp) \n       (k: ExpTyping ftenv tenv e t) :\n  forall (sfenv: nat -> tlist2type (map snd (FunTC_ListTrans ftenv))),      \n      (valTC_Trans tenv -> MM WW (sVTyp t)) := _    \nwith PrmsTrans (ftenv: funTC) (tenv: valTC) (ps: Prms) (pt: PTyp) \n       (k: PrmsTyping ftenv tenv ps pt) :        \n  forall (sfenv: nat -> tlist2type (map snd (FunTC_ListTrans ftenv))),       \n      (valTC_Trans tenv -> MM WW (PTyp_Trans pt)) := _.              \nNext Obligation.\n   eapply Trans_ExpTyping_mut1.   \n   - unfold ExpTrans1_def.\n     intros.\n     inversion v0; subst.\n     exact (ret (sValue v)).\n   - (* apply ExpTransVar. *)\n     unfold ExpTrans1_def.\n     intros.\n     eapply ExpDenI_Var.\n     exact i.\n     exact X.\n   - unfold ExpTrans1_def.\n     intros.\n     exact (bind (X sfenv X1) (fun _ => X0 sfenv X1)).\n   - unfold ExpTrans1_def.\n     intros.\n     specialize (X sfenv X1).   \n     specialize (X0 sfenv).\n     inversion e; subst.\n     unfold valTC_Trans in X1.\n     unfold VTList_Trans in X1.\n     unfold MM.\n     unfold MM in X.\n     intro w0.\n     specialize (X w0).\n     destruct X as [sv1 w1].\n     specialize (X0 (ext_senv tenv X1 x t1 sv1)).\n     unfold MM in X0.\n     specialize (X0 w1).\n     exact X0.\n   - unfold ExpTrans1_def.\n     intros.\n     specialize (X sfenv).\n     inversion e1; subst.\n     clear H.\n     eapply extend_valTC_Trans with (env0:=env0) (tenv0:=tenv0) in X0.\n     eapply X.\n     exact X0.\n     exact e0.\n   - unfold ExpTrans1_def.\n     intros.\n     specialize (X sfenv X2).\n     specialize (X0 sfenv X2).\n     specialize (X1 sfenv X2).\n     intro w0.\n     specialize (X w0).\n     destruct X as [b w1].\n     inversion b; subst.\n     specialize (X0 w1).\n     exact X0.\n     specialize (X1 w1).\n     exact X1.\n   - unfold ExpTrans1_def, PrmsTrans1_def.\n     intros.\n     specialize (X0 sfenv X1).\n     unfold MM.\n     unfold MM in X0.\n     intro w0.\n     specialize (X0 w0).\n     destruct X0 as [nn w1].\n     destruct w1 as [s1 n1].\n     set (w2 := (s1, min nn n1)). \n     specialize (X sfenv X1).\n     assert (FTyp_Trans2 (FT pt t)).\n     eapply extract_from_funTC_Trans with\n         (sftenv:=(FunTC_ListTrans ftenv)) (ftenv:=ftenv) (x:=x).\n     exact (sfenv (snd w2)).\n     inversion i; subst.\n     reflexivity.\n     reflexivity.\n     unfold FTyp_Trans2 in X0.\n     unfold FType_mk2 in X0.\n     simpl in X0.\n     destruct pt.\n     unfold PTyp_Trans in X.\n     unfold VTList_Trans in X.\n     unfold PTyp_ListTrans in X0.\n     exact (bind X X0 w2).\n   - unfold ExpTrans1_def, PrmsTrans1_def.\n     intros.\n     unfold MM.\n     intro w0.\n     specialize (X sfenv X0).\n     assert (FTyp_Trans2 (FT pt t)).\n     eapply extract_from_funTC_Trans with\n         (sftenv:=(FunTC_ListTrans ftenv)) (ftenv:=ftenv) (x:=x).\n     exact (sfenv (snd w0)).\n     inversion i; subst.\n     reflexivity.\n     reflexivity.\n     unfold FTyp_Trans2 in X1.\n     unfold FType_mk2 in X1.\n     simpl in X1.\n     destruct pt.\n     unfold PTyp_Trans in X.\n     unfold VTList_Trans in X.\n     unfold PTyp_ListTrans in X1.\n     exact (bind X X1 w0).\n   - unfold ExpTrans1_def.\n     intros.\n     specialize (X sfenv X0).\n     unfold MM in *.\n     intro w0.\n     specialize (X w0).\n     destruct X as [v0 w1].\n     destruct w1 as [s1 n1].\n     destruct XF.\n     set (x_mod0 v0 s1) as p.\n     subst inpT0.\n     subst outT0.\n     exact (fst p, (snd p, n1)).\n   - unfold PrmsTrans1_def.\n     intros.\n     intro.\n     split.\n     constructor.\n     exact X0.\n   - unfold ExpTrans1_def, PrmsTrans1_def.\n     intros.\n     specialize (X sfenv X1).\n     specialize (X0 sfenv X1). \n     intro w0.\n     specialize (X w0).\n     destruct X as [v1 w1].\n     specialize (X0 w1).\n     destruct X0 as [vs w2].\n     split.\n     unfold PTyp_Trans in *.\n     constructor.\n     exact v1.\n     exact vs.\n     exact w2.\nDefined.     \n\nNext Obligation.\n   eapply Trans_PrmsTyping_mut1.   \n   - unfold ExpTrans1_def.\n     intros.\n     inversion v0; subst.\n     exact (ret (sValue v)).\n   - (* apply ExpTransVar. *)\n     unfold ExpTrans1_def.\n     intros.\n     eapply ExpDenI_Var.\n     exact i.\n     exact X.\n   - unfold ExpTrans1_def.\n     intros.\n     exact (bind (X sfenv X1) (fun _ => X0 sfenv X1)).\n   - unfold ExpTrans1_def.\n     intros.\n     specialize (X sfenv X1).   \n     specialize (X0 sfenv).\n     inversion e; subst.\n     unfold valTC_Trans in X1.\n     unfold VTList_Trans in X1.\n     unfold MM.\n     unfold MM in X.\n     intro w0.\n     specialize (X w0).\n     destruct X as [sv1 w1].\n     specialize (X0 (ext_senv tenv X1 x t1 sv1)).\n     unfold MM in X0.\n     specialize (X0 w1).\n     exact X0.\n   - unfold ExpTrans1_def.\n     intros.\n     specialize (X sfenv).\n     inversion e1; subst.\n     clear H.\n     eapply extend_valTC_Trans with (env0:=env0) (tenv0:=tenv0) in X0.\n     eapply X.\n     exact X0.\n     exact e0.\n   - unfold ExpTrans1_def.\n     intros.\n     specialize (X sfenv X2).\n     specialize (X0 sfenv X2).\n     specialize (X1 sfenv X2).\n     intro w0.\n     specialize (X w0).\n     destruct X as [b w1].\n     inversion b; subst.\n     specialize (X0 w1).\n     exact X0.\n     specialize (X1 w1).\n     exact X1.\n   - unfold ExpTrans1_def, PrmsTrans1_def.\n     intros.\n     specialize (X0 sfenv X1).\n     unfold MM.\n     unfold MM in X0.\n     intro w0.\n     specialize (X0 w0).\n     destruct X0 as [nn w1].\n     destruct w1 as [s1 n1].\n     set (w2 := (s1, min nn n1)). \n     specialize (X sfenv X1).\n     assert (FTyp_Trans2 (FT pt t)).\n     eapply extract_from_funTC_Trans with\n         (sftenv:=(FunTC_ListTrans ftenv)) (ftenv:=ftenv) (x:=x).\n     exact (sfenv (snd w2)).\n     inversion i; subst.\n     reflexivity.\n     reflexivity.\n     unfold FTyp_Trans2 in X0.\n     unfold FType_mk2 in X0.\n     simpl in X0.\n     destruct pt.\n     unfold PTyp_Trans in X.\n     unfold VTList_Trans in X.\n     unfold PTyp_ListTrans in X0.\n     exact (bind X X0 w2).\n   - unfold ExpTrans1_def, PrmsTrans1_def.\n     intros.\n     unfold MM.\n     intro w0.\n     specialize (X sfenv X0).\n     assert (FTyp_Trans2 (FT pt t)).\n     eapply extract_from_funTC_Trans with\n         (sftenv:=(FunTC_ListTrans ftenv)) (ftenv:=ftenv) (x:=x).\n     exact (sfenv (snd w0)).\n     inversion i; subst.\n     reflexivity.\n     reflexivity.\n     unfold FTyp_Trans2 in X1.\n     unfold FType_mk2 in X1.\n     simpl in X1.\n     destruct pt.\n     unfold PTyp_Trans in X.\n     unfold VTList_Trans in X.\n     unfold PTyp_ListTrans in X1.\n     exact (bind X X1 w0).\n   - unfold ExpTrans1_def.\n     intros.\n     specialize (X sfenv X0).\n     unfold MM in *.\n     intro w0.\n     specialize (X w0).\n     destruct X as [v0 w1].\n     destruct w1 as [s1 n1].\n     destruct XF.\n     set (x_mod0 v0 s1) as p.\n     subst inpT0.\n     subst outT0.\n     exact (fst p, (snd p, n1)).\n   - unfold PrmsTrans1_def.\n     intros.\n     intro.\n     split.\n     constructor.\n     exact X0.\n   - unfold ExpTrans1_def, PrmsTrans1_def.\n     intros.\n     specialize (X sfenv X1).\n     specialize (X0 sfenv X1). \n     intro w0.\n     specialize (X w0).\n     destruct X as [v1 w1].\n     specialize (X0 w1).\n     destruct X0 as [vs w2].\n     split.\n     unfold PTyp_Trans in *.\n     constructor.\n     exact v1.\n     exact vs.\n     exact w2.\nDefined.     \n\n\n(**********************************************************************)\n\n(* translation of d-function base case *)\nProgram Definition preZero0 (f: Fun) :\n   (* FunWT1 ftenv f ->*) FunTyp_TRN f := _.\n\nNext Obligation.\n  intros.\n  destruct f.\n  unfold FunTyp_TRN.\n  unfold FTyp_TRN2.\n  unfold FType_mk2.\n  simpl.\n  intros.\n  exact (ret (sValue v)).\nDefined.\n\n\n\nDefinition preZero (f: Fun) : FunTyp_TRN f :=\nmatch f as f0 return (FunTyp_TRN f0) with\n | FC tenv v e =>\n     fun _ : tlist2type (map sVTyp (map snd tenv)) => ret (sValue v)\nend.  \n\n\n(* translation of fenv base case *)\nProgram Definition ZeroTRN1 (fenv: funEnv) :\n  tlist2type (map snd (FunEnv_ListTrans fenv)) := _.\nNext Obligation.\n  intro fenv.\n  induction fenv.\n  intros.\n  simpl.\n  exact tt.\n  intros.\n  destruct a.\n  simpl in *.\n  split.\n  eapply preZero.\n  exact IHfenv.\nDefined.\n  \n\nLemma FunEnv_Trans_lemma (fenv: funEnv) :\n  FunEnv_ListTrans fenv = FunTC_ListTrans (funEnv2funTC fenv).\n unfold FunEnv_ListTrans.\n unfold FunTC_ListTrans.\n induction fenv.\n simpl.\n auto.\n simpl in *.\n rewrite IHfenv.\n auto.\nDefined. \n\n(* translation of fenv base case *)\nProgram Definition ZeroTRN2 (fenv: funEnv) :\n  tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv))) := _.\nNext Obligation.\n  intro fenv.\n  induction fenv.\n  intros.\n  simpl.\n  exact tt.\n  intros.\n  destruct a.\n  simpl in *.\n  split.\n  eapply preZero.\n  exact IHfenv.\nDefined.\n  \n\nProgram Definition ZeroTRN3 (fenv: funEnv) :\n  tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv))) := _.\nNext Obligation.\n  intros.\n  rewrite <- FunEnv_Trans_lemma.\n  eapply ZeroTRN1.\nDefined.\n\n(* \nNOTE: proved AFTER the translation lemma (ExpTrans). \nIn contrast, the extract_from_... lemmas are proven beforehand.\nZeroTRN1 used for the base case; then proved\ntlist2type (map snd (FunEnv_ListTrans fenv)) =\n  tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv)))\n *)\nProgram Definition preSucc (fenv: funEnv)        \n        (k: FEnvWT fenv) (x: Id) (f: Fun) :\n  findE fenv x = Some f -> \n  forall (sfenv: nat -> tlist2type\n                   (map snd (FunTC_ListTrans (funEnv2funTC fenv)))), \n  FunTyp_TRN f := _.\nNext Obligation.\n  intros.\n  set (tenv := funValTC f).\n  set (e := funSExp f).\n  set (t := funVTyp f).\n  set (ftenv := funEnv2funTC fenv).\n  assert (ExpTyping ftenv tenv e t) as k1.\n  unfold FEnvWT in k.\n  set (sftenv := FunTC_ListTrans ftenv).\n  assert (FEnvTyping fenv ftenv).\n  constructor.\n  specialize (k ftenv H0 x f H).\n  unfold FunWT in k.\n  destruct f.\n  subst e.\n  subst t.\n  subst tenv.\n  simpl in *.\n  exact k.\n  specialize (ExpTrans ftenv tenv e t k1 sfenv).\n  intro.\n  unfold FunTyp_TRN.\n  unfold FTyp_TRN2.\n  unfold FType_mk2.\n  unfold valTC_Trans in X.\n  unfold VTList_Trans in X.\n  destruct f.\n  subst tenv e t.\n  simpl in *.\n  unfold VTyp_Trans.\n  unfold TList_Type in X.\n  exact X.\nDefined.\n\n\nProgram Definition preSucc1 (fenv: funEnv)        \n        (k: FEnvWT fenv) : \n  forall (sfenv: nat -> tlist2type\n                   (map snd (FunTC_ListTrans (funEnv2funTC fenv))))\n         (x: Id) (f: Fun),\n  findE fenv x = Some f ->     \n  FunTyp_TRN f := _.\nNext Obligation.\n  intros.\n  eapply (preSucc fenv k x f H sfenv).\nDefined.\n  \n\n(* \nIf each function definition in fenv can be translated, then \neach subset of fenv can be translated. \nHere X stands for the call to preSucc.\nEssential the use of noDup (used by in_find_lemma)\n*)\nProgram Definition SuccTRN_step (fenv: funEnv) :\n  noDup fenv ->  \n  (forall (x: Id) (f: Fun),\n       findE fenv x = Some f ->     \n       FunTyp_TRN f) ->\n  forall (fenv1: funEnv),\n    (forall a, In a fenv1 -> In a fenv) ->\n     tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv1))) := _.\nNext Obligation.  \n  intros fenv D X fenv1.\n  induction fenv1.\n  intros.  \n  simpl in *.\n  exact tt.\n  intro H.\n  destruct a as [x f].\n  intros.\n  assert (forall a : LangSpecL.Id * Fun, In a fenv1 -> In a fenv).\n  {- intros.\n     specialize (H a).\n     simpl in H.\n     assert ((x, f) = a \\/ In a fenv1).\n     right; exact H0.\n     eapply H in H1.\n     exact H1.\n  }\n  specialize (IHfenv1 H0).\n  simpl in *.\n  clear H0.\n  split.\n  specialize (H (x,f)).\n  assert (In (x, f) fenv).\n  eapply H.\n  left.\n  auto.\n  apply in_find_lemma in H0.\n  eapply X.\n  exact H0.\n  exact D.\n  eapply IHfenv1.\nDefined.  \n\n\nProgram Definition preSucc2 (fenv: funEnv)        \n        (k: FEnvWT fenv) : \n  noDup fenv ->\n  forall (sfenv:\n            tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv))))\n         (fenv1: funEnv),\n    (forall a, In a fenv1 -> In a fenv) ->\n     tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv1))) := _.\nNext Obligation.\n  intros.\n  eapply (SuccTRN_step fenv H).\n  eapply (preSucc1 fenv k).\n  intro.\n  exact sfenv.\n  exact H0.\nDefined.  \n\n\nProgram Definition SuccTRN (fenv: funEnv)        \n        (k: FEnvWT fenv) :\n  noDup fenv ->\n  forall (sfenv:\n            tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv)))),\n     tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv))) := _.\nNext Obligation.\n  intros.\n  eapply (preSucc2 fenv k H).\n  exact sfenv.\n  intros.\n  exact H0.\nDefined.  \n\n\nFixpoint FunEnvTRN (fenv: funEnv)        \n        (k1: FEnvWT fenv) (k2: noDup fenv) (n: nat) :\n  tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv))) := match n with\n          | 0 => ZeroTRN3 fenv \n          | S m => SuccTRN fenv k1 k2\n                           (FunEnvTRN fenv k1 k2 m)\n          end.                 \n\nDefinition ExpTrans2 (ftenv: funTC) (tenv: valTC)\n        (e: Exp) (t: VTyp) \n        (k: ExpTyping ftenv tenv e t) :\n  forall (sfenv: nat -> tlist2type (map snd (FunTC_ListTrans ftenv))),\n    (valTC_Trans tenv) -> MM WW (sVTyp t) := fun sfenv =>\n  ExpTrans ftenv tenv e t k sfenv.     \n\nDefinition PrmsTrans2 (ftenv: funTC) (tenv: valTC)\n        (ps: Prms) (pt: PTyp) \n        (k: PrmsTyping ftenv tenv ps pt) :\n  forall (sfenv: nat -> tlist2type (map snd (FunTC_ListTrans ftenv))),\n    (valTC_Trans tenv) -> MM WW (PTyp_Trans pt) := fun sfenv =>\n  PrmsTrans ftenv tenv ps pt k sfenv.     \n\n  \nDefinition ExpEvalTRN (fenv: funEnv)        \n           (k1: FEnvWT fenv) (k2: noDup fenv)\n           (env: valEnv) (e: Exp) (t: VTyp) \n  (k: ExpTyping (funEnv2funTC fenv) (valEnv2valTC env) e t) :\n  MM WW (sVTyp t) := fun w =>\n  let senv := ValEnvTRN env in\n  let sfenv := FunEnvTRN fenv k1 k2 in\n  ExpTrans2 (funEnv2funTC fenv) (valEnv2valTC env) e t k sfenv senv w.\n\nDefinition PrmsEvalTRN (fenv: funEnv)        \n           (k1: FEnvWT fenv) (k2: noDup fenv)\n           (env: valEnv) (ps: Prms) (pt: PTyp) \n  (k: PrmsTyping (funEnv2funTC fenv) (valEnv2valTC env) ps pt) :\n  MM WW (PTyp_Trans pt) := fun w =>   \n  let senv := ValEnvTRN env in\n  let sfenv := FunEnvTRN fenv k1 k2 in\n  PrmsTrans2 (funEnv2funTC fenv) (valEnv2valTC env) ps pt k sfenv senv w.\n\n\n\n(**************************************************************************)\n(**************************************************************************)\n\n(* IMPORTANT *)\n\nLemma ExtRelVal2A_ok (env: valEnv)\n    (x: Id) (t: VTyp) (v: Value) \n    (k1: findE (valEnv2valTC env) x = Some t)\n    (k2: findE env x = Some v) :\n  v = proj1_of_sigT2 (ExtRelVal2A valueVTyp (valEnv2valTC env) env x t\n                                  eq_refl k1).\n  induction env.\n  inversion k1.\n  destruct a.\n  simpl in k1, k2.\n  simpl.\n  unfold ExtRelVal2A.\n  unfold proj1_of_sigT2.\n  unfold sigT_of_sigT2.\n  simpl.\n  destruct (IdT.IdEqDec x i).\n  inversion k2; subst.\n  reflexivity.\n  specialize (IHenv k1 k2).\n  rewrite IHenv.\n  reflexivity.\nDefined.\n\nLemma ExtRelVal2A2_ok (env: valEnv) (tenv: valTC)\n    (m: EnvTyping env tenv)  \n    (x: Id) (t: VTyp) (v: Value) \n    (k1: findE tenv x = Some t)\n    (k2: findE env x = Some v) :\n  v = proj1_of_sigT2 (ExtRelVal2A valueVTyp tenv env x t\n                                  m k1).\n  unfold EnvTyping in m.\n  unfold MatchEnvs in m.\n  inversion m; subst.\n  induction env.\n  inversion k2.\n  destruct a.\n  simpl in k1, k2.\n  simpl.\n  unfold ExtRelVal2A.\n  unfold proj1_of_sigT2.\n  unfold sigT_of_sigT2.\n  simpl.\n  destruct (IdT.IdEqDec x i).\n  inversion k2; subst.\n  reflexivity.\n  specialize (IHenv k1 k2).\n  rewrite IHenv.\n  reflexivity.\n  reflexivity.\nDefined.\n\n\nLemma ExtRelVal2A_Typ_ok (env: valEnv)\n    (x: Id) (t: VTyp) (v: Value) \n    (k1: findE (valEnv2valTC env) x = Some t)\n    (k2: findE env x = Some v) :\n    sVTyp (projT1\n       (proj1_of_sigT2\n          (ExtRelVal2A valueVTyp (valEnv2valTC env) env x t eq_refl k1))) =\n    (sVTyp (projT1 v)).\n  rewrite (ExtRelVal2A_ok env x t v k1 k2).\n  reflexivity.\nDefined.  \n\nLemma ExtRelVal2A_TypSym_ok (env: valEnv)\n    (x: Id) (t: VTyp) (v: Value) \n    (k1: findE (valEnv2valTC env) x = Some t)\n    (k2: findE env x = Some v) :\n  (sVTyp (projT1 v)) =\n      sVTyp (projT1\n       (proj1_of_sigT2\n          (ExtRelVal2A valueVTyp (valEnv2valTC env) env x t eq_refl k1))).\n  symmetry.\n  eapply (ExtRelVal2A_Typ_ok env x t v k1 k2).\nDefined.  \n\nLemma ExtRelVal2A2_Typ_ok (env: valEnv) (tenv: valTC)\n    (m: EnvTyping env tenv)  \n    (x: Id) (t: VTyp) (v: Value) \n    (k1: findE tenv x = Some t)\n    (k2: findE env x = Some v) :\n  (sVTyp (projT1 v)) =\n      sVTyp (projT1\n       (proj1_of_sigT2\n          (ExtRelVal2A valueVTyp tenv env x t m k1))).\n  rewrite (ExtRelVal2A2_ok env tenv m x t v k1 k2).\n  reflexivity.\nDefined.  \n\nLemma ExtRelVal2A2_TypSym_ok (env: valEnv) (tenv: valTC)\n    (m: EnvTyping env tenv)  \n    (x: Id) (t: VTyp) (v: Value) \n    (k1: findE tenv x = Some t)\n    (k2: findE env x = Some v) :\n    sVTyp (projT1\n       (proj1_of_sigT2\n          (ExtRelVal2A valueVTyp tenv env x t m k1))) =\n    (sVTyp (projT1 v)).\n  rewrite (ExtRelVal2A2_ok env tenv m x t v k1 k2).\n  reflexivity.\nDefined.  \n\n\nLemma ExtRelVal_aux1 (env : list (LangSpecL.Id * Value))\n  (x : Id)\n  (t : VTyp)\n  (v : sVTyp t)\n  (k2 : findE env x = Some (existT ValueI t (Cst t v)))\n  (k1 : findE (valEnv2valTC env) x = Some t)\n  (H : existT ValueI t (Cst t v) =\n       (let (a, _, _) := ExtRelVal2B env x t k1 in a))  :\n  ExtRelVal2B_Typ_ok env x t (existT ValueI t (Cst t v)) k1 k2 =\n  \n    eq_ind_r\n      (fun v0 : Value =>\n       sVTyp (projT1 v0) =\n       sVTyp (projT1 (proj1_of_sigT2 (ExtRelVal2B env x t k1)))) eq_refl\n      (eq_ind_r\n         (fun v0 : Value =>\n          v0 =\n          (let (a, _, _) :=\n             list_rect\n               (fun env0 : list (LangSpecL.Id * Value) =>\n                findE (valEnv2valTC env0) x = Some t ->\n                {v1 : Value & findE env0 x = Some v1 & projT1 v1 = t})\n               (fun H0 : None = Some t =>\n                False_rect {v1 : Value & None = Some v1 & projT1 v1 = t}\n                  (eq_ind None\n                     (fun e : option VTyp =>\n                      match e with\n                      | Some _ => False\n                      | None => True\n                      end) I (Some t) H0))\n               (fun (a : LangSpecL.Id * Value)\n                  (env0 : list (LangSpecL.Id * Value))\n                  (IHenv : findE (valEnv2valTC env0) x = Some t ->\n                           {v1 : Value & findE env0 x = Some v1 &\n                           projT1 v1 = t}) =>\n                let\n                  (i, v1) as p\n                   return\n                     ((if IdT.IdEqDec x (fst p)\n                       then Some (valueVTyp (snd p))\n                       else findE (valEnv2valTC env0) x) = \n                      Some t ->\n                      {v1 : Value &\n                      (let (k', x0) := p in\n                       if IdT.IdEqDec x k' then Some x0 else findE env0 x) =\n                      Some v1 & projT1 v1 = t}) := a in\n                if IdT.IdEqDec x i as s\n                 return\n                   ((if s\n                     then Some (valueVTyp v1)\n                     else findE (valEnv2valTC env0) x) = \n                    Some t ->\n                    {v2 : Value &\n                    (if s then Some v1 else findE env0 x) = Some v2 &\n                    projT1 v2 = t})\n                then\n                 fun H0 : Some (valueVTyp v1) = Some t =>\n                 existT2 (fun v2 : Value => Some v1 = Some v2)\n                   (fun v2 : Value => projT1 v2 = t) v1 eq_refl\n                   (f_equal\n                      (fun e0 : option VTyp =>\n                       match e0 with\n                       | Some v2 => v2\n                       | None => let (a0, _) := v1 in a0\n                       end) H0)\n                else fun H0 : findE (valEnv2valTC env0) x = Some t => IHenv H0)\n               env k1 in\n           a)) eq_refl\n         (ExtRelVal2B_ok env x t (existT ValueI t (Cst t v)) k1 k2)).\n  unfold eq_ind_r.\n  unfold eq_ind.\n  unfold eq_sym at 1.\n \n  simpl.\n  eapply proof_irrelevance.\nDefined.\n\n(* DEPTYP main idea: replace the equality parameter, and work through\nby simplifing the equality proof-term *)\nLemma ExtRelVal2B_ok2 (env: valEnv)\n    (x: Id) (t: VTyp) (v: Value) \n    (k1: findE (valEnv2valTC env) x = Some t)\n    (k2: findE env x = Some v)\n    (te: (sVTyp (projT1 v)) = sVTyp (projT1\n                            (proj1_of_sigT2 (ExtRelVal2B env x t k1)))) \n  :  sValue (proj1_of_sigT2 (ExtRelVal2B env x t k1)) =\n     match te with\n          eq_refl => sValue v\n     end.\n  replace te with (ExtRelVal2B_Typ_ok env x t v k1 k2).\n  Focus 2.\n  eapply proof_irrelevance.\n  clear te.\n  assert ( v = proj1_of_sigT2 (ExtRelVal2B env x t k1)).\n  eapply ExtRelVal2B_ok.\n  exact k2.\n  destruct v.\n  destruct v.\n  assert (x0 = t).\n  clear H.\n  eapply RelatedByEnv with (f:= valueVTyp) (env1:=env)\n                           (v1:= (existT ValueI x0 (Cst x0 v))) in k1.\n  simpl in k1.\n  exact k1.\n  constructor.\n  exact k2.\n  inversion H0; subst.\n  clear H1.\n  unfold proj1_of_sigT2 in H.\n  simpl in H.\n  revert H.\n  generalize k1.\n  generalize (ExtRelVal2B env x t k1).\n  clear k1.\n  induction env.\n  inversion k2.\n  simpl in k2.\n  destruct a.\n\n  unfold ExtRelVal2B_Typ_ok.\n  simpl.\n\n  destruct (IdT.IdEqDec x i).\n  \n  inversion e; subst.\n  clear H.\n  inversion k2; subst.\n  dependent destruction k2.\n  simpl in *.\n  intros.\n  unfold sValue.\n  unfold sValueI.\n  unfold proj1_of_sigT2.\n  unfold sigT_of_sigT2.\n  simpl.\n  reflexivity.\n\n  intros.\n  specialize (IHenv k2 X k1 H).\n\n  rewrite IHenv.\n  clear IHenv.\n\n  clear X.\n  clear n.\n  clear i.\n  clear v0.\n\n  assert (sValue (existT ValueI t (Cst t v)) = v) as E1. \n  unfold sValue.\n  unfold sValueI.\n  simpl.\n  reflexivity.\n\n  rewrite E1.\n  clear E1.\n\n  rewrite ExtRelVal_aux1.\n  reflexivity.\n  exact H.\nDefined.\n\nLemma depeq_sym {T1 T2: Type} (te: T2 = T1) (x1: T1) (x2: T2)\n        (p: x1 = match te with eq_refl => x2 end) :\n   x2 = match (eq_sym te) with eq_refl => x1 end. \n    rewrite p.\n    unfold eq_sym.\n    dependent destruction te.\n    reflexivity.\nDefined.    \n\n\nLemma ExtRelVal2B_ok1 (env: valEnv)\n    (x: Id) (t: VTyp) (v: Value) \n    (k1: findE (valEnv2valTC env) x = Some t)\n    (k2: findE env x = Some v)\n    (te: sVTyp (projT1 (proj1_of_sigT2 (ExtRelVal2B env x t k1))) =\n         (sVTyp (projT1 v))) \n  : sValue v = match te with\n      eq_refl => sValue (proj1_of_sigT2 (ExtRelVal2B env x t k1))\n               end.\n  replace te with (eq_sym (ExtRelVal2B_Typ_ok env x t v k1 k2)).\n  Focus 2.\n  eapply proof_irrelevance.\n  eapply depeq_sym.\n  eapply ExtRelVal2B_ok2.\n  exact k2.\nDefined.  \n\n\nEnd PreRefl.\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/PreReflI1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.256991519892503}}
{"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.machine2.invariant0.\nRequire Export DistributedReferenceCounting.machine2.invariant1.\nRequire Export DistributedReferenceCounting.machine2.invariant2.\nRequire Export DistributedReferenceCounting.machine2.invariant3.\nRequire Export DistributedReferenceCounting.machine2.invariant4.\n\nUnset Standard Proposition Elimination Names.\n\n(* changes:\n   only a few changes in ancestor_not_reflexive for\n   transition  6 ,  where n0->n1, n1-> n2, n2-> n3.\n*)\n\n\n\n\nSection INVARIANT6.\n\nVariable c0 : Config.\n\nFixpoint inc_dec_in_queue (s : Site) (q : queue Message) {struct q} : Prop :=\n  match q with\n  | empty => False\n  | input (inc_dec s2) q' =>\n      if eq_site_dec s2 s then True else False\n  | input _ q' => inc_dec_in_queue s q'\n  end.\n\t\n(* note that the contrary is not true ! *)\n\nLemma inc_dec_in :\n forall (s : Site) (q : queue Message),\n inc_dec_in_queue s q -> In_queue Message (inc_dec s) q.\n\nProof.\n  simple induction q.\n  simpl in |- *.\n  auto.\n  simpl in |- *.\n  intro.\n  intro.\n  intro.\n  case d.\n  intuition.\n  intro.\n  case (eq_site_dec s0 s).\n  intro.\n  rewrite e.\n  intuition.\n  intro.\n  intuition.\n  intuition.\nQed.\n\n\n\nLemma inc_dec_queue_equal :\n forall (q : queue Message) (s1 s2 : Site),\n inc_dec_in_queue s1 q -> inc_dec_in_queue s2 q -> s1 = s2.\n\nProof.\n  simple induction q.\n  simpl in |- *.\n  intuition.\n  simpl in |- *.\n  intros d q0 s1 s2.\n  intro s0.\n  case d.\n  auto.\n  intro.\n  case (eq_site_dec s s2).\n  case (eq_site_dec s s0).\n  intros.\n  rewrite <- e; rewrite e0.\n  auto.\n  intuition.\n  intuition.\n  auto.\nQed.\n\n\n\n\n(* s1 is parent of s0 *)\nInductive parent : Site -> Site -> Prop :=\n    parent_intro :\n      forall s1 s0 : Site,\n      rt c0 s0 = true -> inc_dec_in_queue s1 (bm c0 s0 owner) -> parent s1 s0.\n\n(* s1 is ancestor of s0 *)\nInductive ancestor : Site -> Site -> Prop :=\n  | short : forall s1 s0 : Site, parent s1 s0 -> ancestor s1 s0\n  | long :\n      forall s2 s1 s0 : Site,\n      ancestor s2 s1 -> parent s1 s0 -> ancestor s2 s0.\n\n\nLemma decide_rt : forall s : Site, {rt c0 s = false} + {rt c0 s = true}.\nProof.\n  intros.\n  case (rt c0 s).\n  auto.\n  auto.\nQed.\n\nLemma decide_inc_dec_in_queue :\n forall s : Site,\n {s1 : Site | inc_dec_in_queue s1 (bm c0 s owner)} +\n {(forall s1 : Site, ~ inc_dec_in_queue s1 (bm c0 s owner))}.\nProof.\n  intros.\n  elim (bm c0 s owner).\n  simpl in |- *.\n  intuition.\n  \n  intros.\n  case d.\n  simpl in |- *.\n  auto.\n  \n  simpl in |- *.\n  intros.\n  left.\n  split with s0.\n  case (eq_site_dec s0 s0).\n  auto.\n  intro; elim n; auto.\n  simpl in |- *; auto.\nQed.\n\n\n\nLemma decide_parent : forall s1 s3 : Site, {parent s1 s3} + {~ parent s1 s3}.\n\nProof.\n  intros.\n  elim (decide_rt s3).\n  intro.\n  right.\n  unfold not in |- *.\n  intro.\n  generalize a.\n  elim H.\n  intros.\n  rewrite H0 in a0.\n  discriminate.\n  \n  intro.\n  elim (decide_inc_dec_in_queue s3).\n  intros.\n  elim a.\n  intros.\n  case (eq_site_dec x s1).\n  intro.\n  left.\n  apply parent_intro.\n  auto.\n  \n  rewrite <- e.\n  auto.\n  \n  intro.\n  right.\n  unfold not in |- *.\n  intro.\n  generalize p; generalize n.\n  elim H.\n  intros.\n  elim n0.\n  apply inc_dec_queue_equal with (q := bm c0 s2 owner).\n  auto.\n  \n  auto.\n  \n  intros.\n  right.\n  unfold not in |- *.\n  intro.\n  generalize b0.\n  elim H.\n  intros.\n  generalize (b1 s0).\n  intro.\n  elim H2; auto.\nQed.\n\nInductive direct_son : Site -> Prop :=\n    direct_son_intro :\n      forall s : Site,\n      s <> owner ->\n      rt c0 s = true ->\n      (forall s1 : Site, ~ inc_dec_in_queue s1 (bm c0 s owner)) ->\n      direct_son s.\n\n\n\n\nInductive indirect_son1 : Site -> Prop :=\n    indirect_son1_intro :\n      forall s : Site,\n      s <> owner ->\n      rt c0 s = true ->\n      ~ (forall s1 : Site, ~ inc_dec_in_queue s1 (bm c0 s owner)) ->\n      indirect_son1 s.\n\n\n(*  {s1:Site | (inc_dec_in_queue s1 (bm c0 s owner))}  *)\n\nInductive indirect_son2 : Site -> Prop :=\n    indirect_son2_intro :\n      forall s s1 : Site,\n      s <> owner /\\ rt c0 s = true /\\ direct_son s1 /\\ ancestor s1 s ->\n      indirect_son2 s.\n\n(* by specifying the lemma as follows, I don't need to\n   know that there is no cycle in the relation *)\n\nLemma decide_direct_son :\n forall s1 : Site, s1 <> owner -> {direct_son s1} + {~ direct_son s1}.\nProof.\n  intros.\n  elim (decide_rt s1).\n  intros.\n  right.\n  unfold not in |- *.\n  intro.\n  generalize a.\n  elim H0.\n  intros.\n  rewrite H2 in a0.\n  discriminate.\n  \n  intro.\n  elim (decide_inc_dec_in_queue s1).\n  intro.\n  right.\n  unfold not in |- *.\n  intro.\n  generalize a.\n  elim H0.\n  intros.\n  elim a0.\n  auto.\n  \n  intro.\n  left.\n  apply direct_son_intro.\n  auto.\n  auto.\n  auto.\nQed.\n\n\n\nLemma direct_or_indirect_son1 :\n forall s : Site,\n s <> owner -> rt c0 s = true -> {direct_son s} + {indirect_son1 s}.\n\nProof.\n  intros.\n  elim (decide_inc_dec_in_queue s).\n  intro.\n  right.\n  apply (indirect_son1_intro s).\n  auto.\n  auto.\n  unfold not in |- *; intros.\n  elim a.\n  auto.\n  intros; left.\n  apply (direct_son_intro s).\n  auto.\n  auto.\n  auto.\nQed.\n\n\nLemma disjoint_case_for_site :\n forall s : Site,\n {s = owner} + {rt c0 s = false} + {direct_son s} + {indirect_son1 s}.\nProof.\n  intro.\n  case (eq_site_dec s owner).\n  intro.\n  auto.\n  intro.\n  generalize (direct_or_indirect_son1 s).\n  intro.\n  elim (decide_rt s).\n  intro.\n  auto.\n  intro.\n  auto.\n  elim H.\n  auto.\n  auto.\n  auto.\n  auto.\nQed.\n\n\nLemma ancestor_transitive :\n forall s1 s2 s3 : Site, ancestor s1 s2 -> ancestor s2 s3 -> ancestor s1 s3.\nProof.\n  intros s1 s2 s3 H.\n  intro.\n  generalize H.\n  elim H0.\n  intros.\n  apply long with (s1 := s0).\n  auto.\n  auto.\n  intros.\n  apply long with (s1 := s4).\n  auto.\n  auto.\nQed.\n\n\nLemma aux :\n forall s0 s1 s2 : Site,\n parent s0 s2 -> direct_son s0 -> ancestor s1 s2 -> s1 = s0.\nProof.\n   intros.\n  generalize H H0.\n  elim H1.\n  intros.\n  apply inc_dec_queue_equal with (q := bm c0 s4 owner).\n  elim H2; auto.\n  \n  elim H3; auto.\n  \n  intros.\n  cut (s0 = s4).\n  intro.\n  rewrite <- H7 in H2.\n  generalize H2.\n  elim H6.\n  intros.\n  generalize H10.\n  elim H11.\n  intros.\n  generalize H13.\n  elim H12.\n  intros.\n  elim (H16 s8).\n  auto.\n  \n  intros.\n  generalize H15.\n  elim H14.\n  intros.\n  elim (H18 s9).\n  auto.\n  \n  apply inc_dec_queue_equal with (q := bm c0 s5 owner).\n  elim H5; auto.\n  \n  elim H4; auto.\nQed.\n\n\n\nLemma decide_ancestor :\n forall x s s1 : Site,\n direct_son x ->\n ancestor x s ->\n indirect_son1 s1 -> (s1 = s \\/ ancestor s1 s) \\/ s1 <> s /\\ ~ ancestor s1 s.\nProof.\n  intros.\n  generalize H H1.\n  elim H0.\n  intros.\n  case (eq_site_dec s1 s2).\n  intro.\n  left; left; auto.\n  \n  intro.\n  case (eq_site_dec s0 s1).\n  intro.\n  generalize H3.\n  rewrite e.\n  elim H4.\n  intros.\n  intros.\n  generalize H7.\n  elim H8.\n  intros.\n  elim H12.\n  auto.\n  \n  intro.\n  right.\n  split; auto.\n  unfold not in |- *.\n  intro.\n  generalize (aux s0 s1 s2 H2 H3 H5).\n  intro; elim n0; auto.\n  \n  intros.\n  generalize (H3 H5 H1).\n  intro.\n  elim H7.\n  intro.\n  case (eq_site_dec s1 s3).\n  intro.\n  left; left; auto.\n  \n  intro.\n  left; right.\n  case (eq_site_dec s1 s0).\n  intro.\n  apply short.\n  rewrite e; auto.\n  \n  intro.\n  apply long with (s1 := s0).\n  elim H8.\n  intro; elim n0; auto.\n  \n  auto.\n  \n  auto.\n  \n  intro.\n  case (eq_site_dec s1 s3).\n  intro.\n  left; left; auto.\n  \n  intro.\n  right.\n  split; auto.\n  unfold not in |- *.\n  intro.\n  decompose [and] H8.\n  generalize H4 H11 H10 n.\n  elim H9.\n  intros.\n  elim H15.\n  apply inc_dec_queue_equal with (q := bm c0 s5 owner).\n  elim H12; auto.\n  \n  elim H13; auto.\n  \n  intros.\n  cut (s0 = s5).\n  intro.\n  rewrite H18 in H16.\n  elim H16; auto.\n  \n  apply inc_dec_queue_equal with (q := bm c0 s6 owner).\n  elim H15; auto.\n  \n  elim H14; auto.\nQed.\n\nEnd INVARIANT6.\n\nSection INVARIANT6_bis.\n\n\nLemma inc_dec_in_post :\n forall (b : Bag_of_message) (s0 s1 s2 s3 : Site) (m : Message),\n inc_dec_in_queue s1 (b s0 owner) ->\n (forall s4 : Site, m <> inc_dec s4) ->\n inc_dec_in_queue s1 (Post_message Message m b s2 s3 s0 owner).\nProof.\n   intros.\n   case (eq_queue_dec s2 s0 s3 owner).\n   intros.\n   decompose [and] a.\n   rewrite H1; rewrite H2.\n   rewrite post_here.\n   generalize H0.\n   case m.\n   simpl in |- *; auto.\n   \n   intro.\n   intro.\n   generalize (H3 s).\n   intro.\n   elim H4; auto.\n   \n   simpl in |- *; auto.\n   \n   intro; rewrite post_elsewhere; auto.\nQed.\n\nLemma inc_dec_in_post2 :\n forall (b : Bag_of_message) (s0 s1 s2 s3 : Site) (m : Message),\n inc_dec_in_queue s1 (Post_message Message m b s2 s3 s0 owner) ->\n m <> inc_dec s1 -> inc_dec_in_queue s1 (b s0 owner).\nProof.\n  intros.\n  generalize H.\n  case (eq_queue_dec s2 s0 s3 owner).\n  intros.\n  decompose [and] a.\n  generalize H1.\n  rewrite H2; rewrite H3.\n  rewrite post_here.\n  generalize H0.\n  elim m.\n  simpl in |- *; auto.\n  intro; intro.\n  simpl in |- *.\n  case (eq_site_dec s s1).\n  intro; elim H4.\n  rewrite e; auto.\n  intuition.\n  simpl in |- *; auto.\n  intro.\n  rewrite post_elsewhere.\n  auto.\n  auto.\nQed.\n\n\n(* these two lemmas are just negations of the previous ones *)\n\n\nLemma inc_dec_not_in_post :\n forall (b : Bag_of_message) (s0 s1 s2 s3 : Site) (m : Message),\n ~ inc_dec_in_queue s1 (b s0 owner) ->\n (forall s4 : Site, m <> inc_dec s4) ->\n ~ inc_dec_in_queue s1 (Post_message Message m b s2 s3 s0 owner).\nProof.\n  intros.\n  unfold not in |- *.\n  intro.\n  elim H.\n  apply (inc_dec_in_post2 b s0 s1 s2 s3 m).\n  auto.\n  auto.\nQed.\n\n\nLemma inc_dec_not_in_post2 :\n forall (b : Bag_of_message) (s0 s1 s2 s3 : Site) (m : Message),\n (forall s4 : Site, m <> inc_dec s4) ->\n ~ inc_dec_in_queue s1 (Post_message Message m b s2 s3 s0 owner) ->\n ~ inc_dec_in_queue s1 (b s0 owner).\nProof.\n  intros.\n  unfold not in |- *.\n  intro.\n  elim H0.\n  apply inc_dec_in_post.\n  auto.\n  auto.\nQed.\n\nLemma inc_dec_not_in_first_out :\n forall (q : queue Message) (m : Message) (s3 : Site),\n first Message q = value Message m ->\n m <> inc_dec s3 ->\n ~ inc_dec_in_queue s3 q -> ~ inc_dec_in_queue s3 (first_out Message q).\nProof.\n  simple induction q.\n  simpl in |- *.\n  auto.\n  \n  intros d q0.\n  case q0.\n  intro.\n  intros m s3.\n  simpl in |- *.\n  intros.\n  intuition.\n  \n  intros m q1 H m0 s3 H0 H1.\n  case d.\n  generalize (H m0 s3).\n  simpl in |- *.\n  auto.\n  \n  intro.\n  case (eq_site_dec s3 s).\n  intro.\n  rewrite e.\n  simpl in |- *.\n  case (eq_site_dec s s).\n  auto.\n  \n  intro.\n  elim n; auto.\n  \n  intro.\n  simpl in |- *.\n  case (eq_site_dec s s3).\n  auto.\n  \n  intro.\n  generalize (H m0 s3).\n  simpl in |- *.\n  auto.\n  \n  generalize (H m0 s3).\n  simpl in |- *.\n  auto.\nQed.\n\nLemma inc_dec_in_first_out :\n forall (q : queue Message) (m : Message) (s3 : Site),\n first Message q = value Message m ->\n m <> inc_dec s3 ->\n inc_dec_in_queue s3 q -> inc_dec_in_queue s3 (first_out Message q).\nProof.\n  simple induction q.\n  simpl in |- *.\n  auto.\n  \n  intros d q0.\n  case q0.\n  intro.\n  intros m s3.\n  simpl in |- *.\n  case d.\n  auto.\n  \n  intro.\n  case (eq_site_dec s s3).\n  intros.\n  elim H1.\n  generalize H0.\n  auto.\n  rewrite e.\n  auto.\n  generalize (inc_dec s3).\n  intro.\n  auto.\n  intro.\n  symmetry  in |- *.\n  injection H3.\n  auto.\n  \n  auto.\n  \n  intros.\n  contradiction.\n  \n  intros m q1 H m0 s3 H0 H1.\n  case d.\n  generalize (H m0 s3).\n  simpl in |- *.\n  auto.\n  \n  intro.\n  case (eq_site_dec s3 s).\n  intro.\n  rewrite e.\n  simpl in |- *.\n  case (eq_site_dec s s).\n  auto.\n  \n  intro.\n  elim n; auto.\n  \n  intro.\n  simpl in |- *.\n  case (eq_site_dec s s3).\n  auto.\n  \n  intro.\n  generalize (H m0 s3).\n  simpl in |- *.\n  auto.\n  \n  generalize (H m0 s3).\n  simpl in |- *.\n  auto.\nQed.\n\n\n\nLemma inc_dec_not_in_collect :\n forall (b : Bag_of_message) (m : Message) (s0 s1 s2 s3 : Site),\n first Message (b s1 s2) = value Message m ->\n ~ inc_dec_in_queue s3 (b s0 owner) ->\n m <> inc_dec s3 ->\n ~ inc_dec_in_queue s3 (Collect_message Message b s1 s2 s0 owner).\nProof.\n  intros.\n  case (eq_queue_dec s1 s0 s2 owner).\n  intros.\n  decompose [and] a.\n  rewrite H2; rewrite H3.\n  rewrite collect_here.\n  apply inc_dec_not_in_first_out with (m := m).\n  rewrite <- H2; rewrite <- H3; auto.\n  auto.\n  auto.\n  intro.\n  rewrite collect_elsewhere.\n  auto.\n  auto.\nQed.\n\n\nLemma inc_dec_in_collect :\n forall (b : Bag_of_message) (s0 s1 s2 s3 : Site) (m : Message),\n first Message (b s1 s2) = value Message m ->\n inc_dec_in_queue s3 (b s0 owner) ->\n m <> inc_dec s3 ->\n inc_dec_in_queue s3 (Collect_message Message b s1 s2 s0 owner).\nProof.\n  intros.\n  case (eq_queue_dec s1 s0 s2 owner).\n  intros.\n  decompose [and] a.\n  rewrite H2; rewrite H3.\n  rewrite collect_here.\n  generalize (inc_dec_not_in_first_out (b s0 owner) m s3).\n  intros.\n  apply inc_dec_in_first_out with (m := m).\n  rewrite <- H2; rewrite <- H3.\n  auto.\n  auto.\n  auto.\n  intro.\n  rewrite collect_elsewhere.\n  auto.\n  auto.\nQed.\n\nLemma inc_dec_in_collect2 :\n forall (b : Bag_of_message) (m : Message) (s0 s1 s2 s3 : Site),\n first Message (b s1 s2) = value Message m ->\n inc_dec_in_queue s3 (Collect_message Message b s1 s2 s0 owner) ->\n inc_dec_in_queue s3 (b s0 owner).\nProof.\n  intros b m s0 s1 s2 s3 H.\n  case (eq_queue_dec s1 s0 s2 owner).\n  intros.\n  decompose [and] a.\n  generalize H0.\n  rewrite H1; rewrite H2.\n  rewrite collect_here.\n  elim (b s0 owner).\n  simpl in |- *.\n  auto.\n  \n  intros d q.\n  case q.\n  simpl in |- *.\n  intuition.\n  \n  intro.\n  case d.\n  simpl in |- *.\n  auto.\n  \n  intro.\n  case (eq_site_dec s s3).\n  intro.\n  rewrite e.\n  simpl in |- *.\n  auto.\n  case (eq_site_dec s3 s3).\n  auto.\n  \n  intro.\n  elim n.\n  auto.\n  \n  intro.\n  simpl in |- *.\n  auto.\n  \n  auto.\n  \n  simpl in |- *.\n  auto.\n  \n  intro.\n  rewrite collect_elsewhere.\n  auto.\n  \n  auto.\nQed.\n\n\n\nLemma not_inc_dec_in :\n forall q : queue Message,\n (forall s : Site, ~ inc_dec_in_queue s q) ->\n forall s : Site, ~ In_queue Message (inc_dec s) q.\n\nProof.\n  simple induction q.\n  simpl in |- *.\n  auto.\n  intro.\n  case d.\n  simpl in |- *.\n  intros.\n  intuition.\n  discriminate.\n  eauto.\n  intros.\n  generalize (H0 s).\n  intro.\n  elim H1.\n  simpl in |- *.\n  case (eq_site_dec s s).\n  auto.\n  intro; elim n; auto.\n  intro; simpl in |- *.\n  intros.\n  intuition.\n  discriminate.\n  eauto.\nQed.\n\n\nLemma joining_node :\n forall (c : Config) (s2 : Site),\n legal c ->\n rt c s2 = false -> forall s3 s4 : Site, parent c s3 s4 -> s2 <> s3.\nProof.\n  intros.\n  unfold not in |- *.\n  intro.\n  rewrite H2 in H0.\n  generalize H0.\n  elim H1.\n  intros.\n  generalize (inc_dec_in s1 (bm c s0 owner) H4).\n  intro.\n  generalize (not_owner_inc3 c s0 owner H s1 H6).\n  intro.\n  generalize (positive_st c s1 s0 H7 H H6).\n  intro.\n  generalize (st_rt c s1 H H7 H8).\n  rewrite H5.\n  discriminate.\nQed.\n\n\nLemma ancestor_rt :\n forall c : Config,\n legal c -> forall s1 s2 : Site, ancestor c s1 s2 -> rt c s1 = true.\nProof.\n  intros.\n  elim H0.\n  intros.\n  elim H1.\n  intros.\n  generalize (inc_dec_in s4 (bm c s5 owner) H3).\n  intro.\n  generalize (not_owner_inc3 c s5 owner H s4 H4).\n  intro.\n  generalize (positive_st c s4 s5 H5 H H4).\n  intro.\n  generalize (st_rt c s4 H H5 H6).\n  auto.\n  intros.\n  auto.\nQed.\n\n\nLemma ancestor_rt2 :\n forall c : Config,\n legal c -> forall s1 s2 : Site, ancestor c s1 s2 -> rt c s2 = true.\nProof.\n  intros.\n  elim H0.\n  intros.\n  elim H1.\n  auto.\n  intros.\n  elim H3; auto.\nQed.\n\n(* the parent of a node cannot be the which receives \n   a gp for the first time *)\n\nLemma parent_does_not_join :\n forall (c0 : Config) (s2 s3 s4 : Site),\n legal c0 ->\n legal (rec_copy2_trans c0 s2) ->\n parent (rec_copy2_trans c0 s2) s3 s4 ->\n rt c0 s2 = false ->\n first Message (bm c0 owner s2) = value Message copy -> s3 <> s2.\nProof.\n  intros.\n  elim H1.\n  intros.\n  generalize (inc_dec_in s1 (bm (rec_copy2_trans c0 s2) s0 owner) H5).\n  intro.\n  generalize (not_reflexive (rec_copy2_trans c0 s2) H0 s1 s0 H6).\n  intro.\n  cut (s1 <> owner).\n  intro.\n  generalize (positive_st (rec_copy2_trans c0 s2) s1 s0 H8 H0 H6).\n  intro.\n  generalize (st_rt (rec_copy2_trans c0 s2) s1 H0 H8 H9).\n  intro.\n  generalize H5.\n  simpl in |- *.\n  intro.\n  generalize (inc_dec_in_collect2 (bm c0) copy s0 owner s2 s1 H3 H11).\n  intro.\n  generalize (inc_dec_in s1 (bm c0 s0 owner) H12).\n  intro.\n  generalize (positive_st c0 s1 s0 H8 H H13).\n  intro.\n  generalize (st_rt c0 s1 H H8 H14).\n  intro.\n  unfold not in |- *.\n  intro.\n  rewrite H16 in H15.\n  rewrite H15 in H2.\n  discriminate.\n  \n  apply (not_owner_inc3 (rec_copy2_trans c0 s2) s0 owner H0).\n  auto.\nQed.\n\n(* the ancestor of a node cannot be the which receives \n   a gp for the first time *)\n\nLemma ancestor_does_not_join :\n forall (c0 : Config) (s2 s3 s4 : Site),\n legal c0 ->\n legal (rec_copy2_trans c0 s2) ->\n ancestor (rec_copy2_trans c0 s2) s3 s4 ->\n rt c0 s2 = false ->\n first Message (bm c0 owner s2) = value Message copy -> s3 <> s2.\nProof.\n  intros.\n  elim H1.\n  intros.\n  apply (parent_does_not_join c0 s2 s1 s0).\n  auto.\n  auto.\n  auto.\n  auto.\n  auto.\n  intros.\n  auto.\nQed.\n\nLemma parent_does_not_join2 :\n forall (c0 : Config) (s1 s2 s3 s4 : Site),\n legal c0 ->\n legal (rec_copy3_trans c0 s1 s2) ->\n parent (rec_copy3_trans c0 s1 s2) s3 s4 ->\n rt c0 s2 = false ->\n first Message (bm c0 s1 s2) = value Message copy -> s3 <> s2.\nProof.\n  intros.\n  elim H1.\n  intros.\n  generalize (inc_dec_in s0 (bm (rec_copy3_trans c0 s1 s2) s5 owner) H5).\n  intro.\n  generalize (not_reflexive (rec_copy3_trans c0 s1 s2) H0 s0 s5 H6).\n  intro.\n  cut (s0 <> owner).\n  intro.\n  generalize (positive_st (rec_copy3_trans c0 s1 s2) s0 s5 H8 H0 H6).\n  intro.\n  generalize (st_rt (rec_copy3_trans c0 s1 s2) s0 H0 H8 H9).\n  intro.\n  generalize H5.\n  simpl in |- *.\n  intro.\n  case (eq_site_dec s2 s5).\n  intro.\n  rewrite e; auto.\n  \n  intro.\n  generalize H11.\n  rewrite post_elsewhere.\n  intro.\n  generalize (inc_dec_in_collect2 (bm c0) copy s5 s1 s2 s0 H3 H12).\n  intro.\n  generalize (inc_dec_in s0 (bm c0 s5 owner) H13).\n  intro.\n  generalize (positive_st c0 s0 s5 H8 H H14).\n  intro.\n  generalize (st_rt c0 s0 H H8 H15).\n  intro.\n  unfold not in |- *.\n  intro.\n  rewrite H17 in H16.\n  rewrite H16 in H2.\n  discriminate.\n  \n  left; auto.\n  \n  apply (not_owner_inc3 (rec_copy3_trans c0 s1 s2) s5 owner H0).\n  auto.\nQed.\n\nLemma ancestor_does_not_join2 :\n forall (c0 : Config) (s1 s2 s3 s4 : Site),\n legal c0 ->\n legal (rec_copy3_trans c0 s1 s2) ->\n ancestor (rec_copy3_trans c0 s1 s2) s3 s4 ->\n rt c0 s2 = false ->\n first Message (bm c0 s1 s2) = value Message copy -> s3 <> s2.\nProof.\n  intros.\n  elim H1.\n  intros.\n  apply (parent_does_not_join2 c0 s1 s2 s0 s5).\n  auto.\n  auto.\n  auto.\n  auto.\n  auto.\n  intros; auto.\nQed.\n\n\nLemma ancestor_not_reflexive :\n forall c : Config,\n legal c -> forall s1 s2 : Site, ancestor c s1 s2 -> s1 <> s2.\nProof.\n  intros c H.\n  generalize H.\n  elim H.\n  simpl in |- *.\n  intros.\n  elim H1.\n  intros.\n  elim H2.\n  simpl in |- *.\n  intuition.\n  \n  simpl in |- *.\n  intros.\n  elim H4.\n  simpl in |- *.\n  intuition.\n  \n  simple induction t.\n\n(*  1*)\n  intros.\n  apply H1.\n  auto.\n  \n  elim H3.\n  simpl in |- *.\n  intros.\n  apply short.\n  elim H4.\n  intros.\n  apply parent_intro.\n  generalize H5; simpl in |- *; auto.\n  \n  apply (inc_dec_in_post2 (bm c0) s7 s6 s1 s2 copy).\n  generalize H6; simpl in |- *; auto.\n  \n  discriminate.\n  \n  intros.\n  apply long with (s1 := s5).\n  auto.\n  \n  elim H6.\n  intros.\n  apply parent_intro.\n  generalize H7; simpl in |- *; auto.\n  \n  apply (inc_dec_in_post2 (bm c0) s8 s7 s1 s2 copy).\n  generalize H8; simpl in |- *; auto.\n  \n  discriminate.\n  \n(* 2 *)\n  intros.\n  apply H1.\n  auto.\n  \n  elim H3.\n  simpl in |- *.\n  intros.\n  apply short.\n  elim H4.\n  intros.\n  apply parent_intro.\n  generalize H5; simpl in |- *; auto.\n  \n  apply (inc_dec_in_collect2 (bm c0) dec s7 s1 s2 s6).\n  auto.\n  \n  generalize H6; simpl in |- *; auto.\n  \n  intros.\n  apply long with (s1 := s5).\n  auto.\n  \n  elim H6.\n  intros.\n  apply parent_intro.\n  generalize H7; simpl in |- *; auto.\n  \n  apply (inc_dec_in_collect2 (bm c0) dec s8 s1 s2 s7).\n  auto.\n  \n  generalize H8; simpl in |- *; auto.\n  \n(* 3 *)\n  intros.\n  apply H1.\n  auto.\n  \n  elim H3.\n  simpl in |- *.\n  intros.\n  apply short.\n  elim H4.\n  intros.\n  apply parent_intro.\n  generalize H5; simpl in |- *; auto.\n  \n  apply (inc_dec_in_collect2 (bm c0) (inc_dec s3) s7 s1 owner s6).\n  auto.\n  \n  apply\n   (inc_dec_in_post2 (Collect_message Message (bm c0) s1 owner) s7 s6 owner\n      s3 dec).\n  generalize H6; simpl in |- *; auto.\n  \n  discriminate.\n  \n  intros.\n  apply long with (s1 := s5).\n  auto.\n  \n  elim H6.\n  intros.\n  apply parent_intro.\n  generalize H7; simpl in |- *; auto.\n  \n  apply (inc_dec_in_collect2 (bm c0) (inc_dec s3) s8 s1 owner s7).\n  auto.\n  \n  apply\n   (inc_dec_in_post2 (Collect_message Message (bm c0) s1 owner) s8 s7 owner\n      s3 dec).\n  generalize H8; simpl in |- *; auto.\n  \n  discriminate.\n  \n(* 4 *)\n  intros.\n  apply H1.\n  auto.\n  \n  elim H3.\n  simpl in |- *.\n  intros.\n  apply short.\n  elim H4.\n  intros.\n  apply parent_intro.\n  generalize H5; simpl in |- *; auto.\n  \n  apply (inc_dec_in_collect2 (bm c0) copy s7 s1 s2 s6).\n  auto.\n  \n  apply\n   (inc_dec_in_post2 (Collect_message Message (bm c0) s1 s2) s7 s6 s2 s1 dec).\n  generalize H6; simpl in |- *; auto.\n  \n  discriminate.\n  \n  intros.\n  apply long with (s1 := s5).\n  auto.\n  \n  elim H6.\n  intros.\n  apply parent_intro.\n  generalize H7; simpl in |- *; auto.\n  \n  apply (inc_dec_in_collect2 (bm c0) copy s8 s1 s2 s7).\n  auto.\n  \n  apply\n   (inc_dec_in_post2 (Collect_message Message (bm c0) s1 s2) s8 s7 s2 s1 dec).\n  generalize H8; simpl in |- *; auto.\n  \n  discriminate.\n  \n\n  (*  5 *)\n  simpl in |- *.\n  intros.\n  case (eq_site_dec s0 s2).\n  intro.\n  generalize e e0 e1.\n  elim H3.\n  intro; intro; intro.\n  elim H4.\n  intros.\n  rewrite e4 in H5.\n  rewrite e4 in H6.\n  rewrite e4.\n  generalize (inc_dec_in s5 (bm (rec_copy2_trans c0 s2) s2 owner) H6).\n  intro.\n  apply not_reflexive with (c := rec_copy2_trans c0 s2).\n  auto.\n  auto.\n  intros.\n\n  apply (ancestor_does_not_join c0 s5 s3 s4).\n  auto.\n  rewrite e4; auto.\n  rewrite e4; auto.\n  rewrite e4; auto.\n  rewrite e4; auto.\n\n\n   (* base case when s0!=s2*)\n  \n  intro.\n  apply H1.\n  auto.\n  \n  generalize e.\n  generalize n.\n  elim H3.\n  intros.\n  apply short.\n  generalize n0.\n  elim H4.\n  intros.\n  apply parent_intro.\n  generalize H5; simpl in |- *.\n  unfold Set_rec_table in |- *; rewrite other_site; auto.\n  \n  generalize H6; simpl in |- *.\n  intro.\n  apply (inc_dec_in_collect2 (bm c0) copy s6 owner s2 s5).\n  auto.\n  \n  auto.\n\n      (* inductive case when s0!=s1*)\n  \n  intros.\n  apply long with (s1 := s4).\n  apply H5.\n  apply (parent_does_not_join c0 s2 s4 s5).\n  auto.\n  auto.\n  auto.\n  auto.\n  auto.\n  auto.\n\n  \n  generalize n0; elim H6.\n  intros.\n  apply parent_intro.\n  generalize H7; simpl in |- *.\n  unfold Set_rec_table in |- *; rewrite other_site; auto.\n  \n  generalize H8; simpl in |- *.\n  intro.\n  apply (inc_dec_in_collect2 (bm c0) copy s7 owner s2 s6).\n  auto.\n  \n  auto.\n \n\n  (*  6 *)\n\n  \n  simpl in |- *.\n  intros.\n  case (eq_site_dec s2 s3).\n  intro.\n  generalize e e0 e1.\n  elim H3.\n  intro; intro; intro.\n  elim H4.\n  intros.\n  generalize (inc_dec_in s6 (bm (rec_copy3_trans c0 s1 s2) s7 owner) H6).\n  intro.\n  apply not_reflexive with (c := rec_copy3_trans c0 s1 s2).\n  auto.\n  \n  auto.\n  \n  intros.\n  rewrite <- e4.\n  apply (ancestor_does_not_join2 c0 s1 s2 s4 s5).\n  auto.\n  auto.\n  auto.\n  auto.\n  auto.\n  intro.\n  apply H1.\n  auto.\n  \n  generalize e.\n  generalize n.\n  generalize n1.\n  elim H3.\n  intros.\n  apply short.\n  generalize n2 n3 e1.\n  elim H4.\n  intros.\n  apply parent_intro.\n  generalize H5; simpl in |- *.\n  unfold Set_rec_table in |- *; rewrite other_site; auto.\n  \n  generalize H6; simpl in |- *.\n  rewrite post_elsewhere.\n  intro.\n  apply (inc_dec_in_collect2 (bm c0) copy s7 s1 s2 s6).\n  auto.\n  \n  auto.\n  \n  left; auto.\n  \n  intros.\n  apply long with (s1 := s5).\n  apply H5.\n  generalize (parent_does_not_join2 c0 s1 s2 s5 s6 H0 H2 H6 e1 e0).\n  auto.\n  \n  auto.\n  \n  auto.\n  \n  generalize n2.\n  elim H6.\n  intros.\n  apply parent_intro.\n  generalize H7; simpl in |- *.\n  unfold Set_rec_table in |- *; rewrite other_site; auto.\n  \n  generalize H8; simpl in |- *.\n  rewrite post_elsewhere.\n  intro.\n  apply (inc_dec_in_collect2 (bm c0) copy s8 s1 s2 s7).\n  auto.\n  \n  auto.\n  \n  left; auto.\n\n  (* 7 *)\n  \n  intros.\n  apply H1.\n  auto.\n  \n  elim H3.\n  simpl in |- *.\n  intros.\n  apply short.\n  elim H4.\n  intros.\n  apply parent_intro.\n  generalize H5; simpl in |- *; auto.\n  unfold Reset_rec_table in |- *.\n  case (eq_site_dec s s5).\n  intro; rewrite e1.\n  rewrite that_site; auto.\n  intro; discriminate.\n  \n  intro; rewrite other_site; auto.\n  \n  generalize H6; simpl in |- *.\n  intro.\n  apply (inc_dec_in_post2 (bm c0) s5 s4 s owner dec).\n  auto.\n  \n  discriminate.\n  \n  intros.\n  apply long with (s1 := s3).\n  auto.\n  \n  elim H6.\n  intros.\n  apply parent_intro.\n  generalize H7; simpl in |- *; auto.\n  case (eq_site_dec s s6).\n  intro; rewrite e1; unfold Reset_rec_table in |- *; rewrite that_site.\n  intro; discriminate.\n  \n  intro; unfold Reset_rec_table in |- *; rewrite other_site; auto.\n  \n  generalize H8; simpl in |- *; intro.\n  apply (inc_dec_in_post2 (bm c0) s6 s5 s owner dec).\n  auto.\n  \n  discriminate.\nQed.\n\nLemma ancestor_has_positive_st :\n forall c : Config,\n legal c -> forall s1 s2 : Site, ancestor c s1 s2 -> (st c s1 > 0)%Z.\nProof.\n  intros.\n  elim H0.\n  intros.\n  elim H1.\n  intros.\n  generalize (inc_dec_in s4 (bm c s5 owner) H3).\n  intro.\n  apply positive_st with (s5 := s5).\n  apply not_owner_inc3 with (s1 := s5) (s2 := owner) (c := c).\n  auto.\n  auto.\n  auto.\n  auto.\n  intros; auto.\nQed.\n\n\nEnd INVARIANT6_bis.\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/invariant6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621764862150636, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2569915131859715}}
{"text": "Require Import Coq.Logic.Classical_Prop.\n\nRequire Import SpecCert.Equality.\nRequire Import SpecCert.Map.\nRequire Import SpecCert.Address.\nRequire Import SpecCert.Cache.\nRequire Import SpecCert.Interval.\nRequire Import SpecCert.Memory.\nRequire Import SpecCert.Smm.Delta.Invariant.\nRequire Import SpecCert.Smm.Software.\nRequire Import SpecCert.x86.\n\nLemma pa1_not_in_interval_pa2_in_interval_pa1_neq_pa2\n      (pa pa': PhysicalAddress)\n      (i:      Interval)\n      (not_in: ~ address_offset pa ∈ i)\n      (is_in:  address_offset pa' ∈ i)\n  : ~ eq pa pa'.\n  simpl.\n  unfold addr_eq.\n  intros [Heq Heq'].\n  assert (address_offset pa <> address_offset pa').\n  + apply (x1_not_in_interval_x2_in_interval_x1_neq_x2 (address_offset pa) (address_offset pa') i not_in is_in).\n  + apply H in Heq.\n    exact Heq.\nQed.\n\nLemma neq_dram_vga_cast\n      (pa pa': PhysicalAddress)\n  : ~ eq (dram pa) (vga pa').\nProof.\n  unfold not.\n  simpl.\n  unfold addr_eq.\n  unfold vga, dram.\n  induction pa; induction pa'.\n  simpl.\n  intros [_H H].\n  apply eq_equal in H.\n  discriminate H.\nQed.\n\nLemma hardware_dram_cast\n      (pa pa': PhysicalAddress)\n      : eq (dram pa) (dram pa') <-> eq pa pa'.\nProof.\n  split.\n  + intro Heq.\n    induction pa; induction pa'; unfold dram in *; unfold addr_eq in *;\n      unfold address_offset in *; unfold address_scope in *.\n    destruct Heq as [Heq Heq'].\n    split.\n    * exact Heq.\n    * simpl.\n      apply mm_singleton.\n  + intro Heq.\n    induction pa; induction pa'; unfold dram in *; unfold addr_eq in *;\n      unfold address_offset in *; unfold address_scope in *.\n    destruct Heq as [Heq Heq'].\n    split.\n    * exact Heq.\n    * apply eq_refl.\nQed.\n\nLemma update_memory_content_with_cache_content_preserves_smram_code_inv\n      (a a': Architecture Software)\n      (pa:   PhysicalAddress)\n  : let cont := find_in_cache_location (cache a) pa\n    in inv a\n       -> a' = update_memory_content a\n                                     (phys_to_hard a (cache_location_address (cache a) pa))\n                                     cont\n       -> smram_code_inv a'.\nProof.\n  simpl.\n  remember (cache_location_address (cache a) pa) as pa'.\n  remember (find_in_cache_location (cache a) pa) as c'.\n  remember (phys_to_hard a pa') as ha.\n  intros [Hsmramc [Hsmram [Hsmrr [Hclean [Hip Hsmbase]]]]] Heqa'.\n  destruct (is_inside_smram_dec pa') as [Hinside|Houtside].\n  + rewrite (cache_location_cache_location (cache a) pa pa') in Heqc'; [\n    | apply x86_cache_is_well_formed\n    | trivial\n    ].\n    symmetry in Heqc'.\n    apply find_in_cache_cache_location in Heqc'; [\n      | apply x86_cache_is_well_formed ].\n    assert (cache_hit (cache a) pa') as Hhit.\n    rewrite Heqpa';\n      apply cache_hit_cache_location_address;\n      apply x86_cache_is_well_formed.\n    rewrite <- cache_hit_cache_location_cache_find in Heqc'; [\n      | trivial\n      ].\n    unfold cache_clean_inv in *.\n    unfold find_cache_content in Hclean.\n    induction c' as [v s].\n    assert (s = smm).\n    apply (Hclean pa' v s Hinside Hhit Heqc').\n    unfold smram_code_inv.\n    intros addr val s' Hinside' Hfind.\n    rewrite H in Heqa'.\n    destruct (eq_dec ha (dram addr)) as [Heq|Hneq].\n    * apply eq_equal in Heq.\n      rewrite Heqa' in Hfind.\n      rewrite Heq in Hfind.\n      rewrite update_ha_in_memory_is_ha in Hfind.\n      inversion Hfind.\n      reflexivity.\n    * rewrite Heqa' in Hfind.\n      unfold find_memory_content, find_in_memory, update_memory_content, update_in_memory in Hfind.\n      simpl in Hfind.\n      rewrite <- add_2 in Hfind; [| exact Hneq].\n      unfold smram_code_inv in Hsmram.\n      apply (Hsmram addr val s' Hinside' Hfind).\n  + unfold smram_code_inv.\n    intros addr val s Haddr.\n    unfold phys_to_hard, translate_physical_address in Heqha.\n    destruct (is_inside_smram_dec pa') as [_H|_H']; [ intuition |].\n    rewrite Heqha in *.\n    rewrite Heqa'.\n    assert (~ eq (dram pa') (dram addr)) as Hneqdram.\n    * unfold not; intro Hfalse.\n      assert (~ eq pa' addr).\n      unfold is_inside_smram in *.\n      apply hardware_dram_cast in Hfalse.\n      apply (pa1_not_in_interval_pa2_in_interval_pa1_neq_pa2 pa' addr smram_space Houtside Haddr).\n      apply hardware_dram_cast in Hfalse.\n      apply H in Hfalse.\n      exact Hfalse.\n    * rewrite <- update_ha_in_memory_changes_only_ha.\n      apply Hsmram; trivial.\n      trivial.\nQed.\n\nLemma update_memory_content_with_cache_content_preserves_cache_clean_inv\n      (a a':  Architecture Software)\n      (pa:    PhysicalAddress)\n      (Hinv:  inv a)\n      (Heqa': a' = update_memory_content a\n                                         (phys_to_hard a (cache_location_address (cache a) pa))\n                                         (find_in_cache_location (cache a) pa))\n  : cache_clean_inv a'.\nProof.\n  remember (cache_location_address (cache a) pa) as pa'.\n  remember (find_in_cache_location (cache a) pa) as c'.\n  remember (phys_to_hard a pa') as ha'.\n  destruct Hinv as [Hsmramc [Hsmram [Hsmrr [Hclean [Hip Hsmbase]]]]].\n  unfold cache_clean_inv.\n  unfold find_cache_content.\n  apply update_memory_changes_only_memory in Heqa'.\n  destruct Heqa' as [Hmc [Hproc Hcache]].\n  rewrite <- Hcache.\n  apply Hclean.\nQed.\n\nLemma update_memory_content_with_cache_content_preserves_smrr_inv:\n  forall a a' :Architecture Software,\n  forall pa   :PhysicalAddress,\n    inv a\n    -> a' = update_memory_content a\n                                 (phys_to_hard a (cache_location_address (cache a) pa))\n                                 (find_in_cache_location (cache a) pa)\n    -> smrr_inv a'.\nProof.\n  intros a a' pa.\n  remember (cache_location_address (cache a) pa) as pa'.\n  remember (find_in_cache_location (cache a) pa) as c'.\n  remember (phys_to_hard a pa') as ha'.\n  intros [Hsmramc [Hsmram [Hsmrr [Hclean [Hip Hsmbase]]]]] Heqa'.\n  unfold smrr_inv.\n  apply update_memory_changes_only_memory in Heqa'.\n  destruct Heqa' as [Hmc [Hproc Hcache]].\n  rewrite <- Hproc.\n  apply Hsmrr.\nQed.\n\nLemma update_memory_content_with_cache_content_preserves_smramc_inv:\n  forall a a' :Architecture Software,\n  forall pa   :PhysicalAddress,\n    inv a\n    -> a' = update_memory_content a\n                                 (phys_to_hard a (cache_location_address (cache a) pa))\n                                 (find_in_cache_location (cache a) pa)\n    -> smramc_inv a'.\nProof.\n  intros a a' pa.\n  remember (cache_location_address (cache a) pa) as pa'.\n  remember (find_in_cache_location (cache a) pa) as c'.\n  remember (phys_to_hard a pa') as ha'.\n  intros [Hsmramc [Hsmram [Hsmrr [Hclean [Hip Hsmbase]]]]] Heqa'.\n  unfold smramc_inv.\n  apply update_memory_changes_only_memory in Heqa'.\n  destruct Heqa' as [Hmc [Hproc Hcache]].\n  rewrite <- Hmc.\n  apply Hsmramc.\nQed.\n\nLemma context_is_preserves:\n  forall h h': Architecture Software,\n    proc h = proc h'\n    -> smm_context h = smm_context h'.\nProof.\n  intros h h' Heqp.\n  unfold smm_context.\n  rewrite Heqp.\n  reflexivity.\nQed.\n\nLemma update_memory_content_with_cache_content_preserves_ip_inv:\n  forall a a' :Architecture Software,\n  forall pa   :PhysicalAddress,\n    inv a\n    -> a' = update_memory_content a\n                                 (phys_to_hard a (cache_location_address (cache a) pa))\n                                 (find_in_cache_location (cache a) pa)\n    -> ip_inv a'.\nProof.\n  intros a a' pa.\n  remember (cache_location_address (cache a) pa) as pa'.\n  remember (find_in_cache_location (cache a) pa) as c'.\n  remember (phys_to_hard a pa') as ha'.\n  intros [Hsmramc [Hsmram [Hsmrr [Hclean [Hip Hsmbase]]]]] Heqa'.\n  apply update_memory_changes_only_memory in Heqa'.\n  destruct Heqa' as [Hmc [Hproc Hcache]].\n  unfold ip_inv in *.\n  rewrite <- Hproc.\n  rewrite <- (context_is_preserves a a' Hproc).\n  apply Hip.\nQed.\n\nLemma update_memory_content_with_cache_content_preserves_smbase_inv:\n  forall a a' :Architecture Software,\n  forall pa   :PhysicalAddress,\n    inv a\n    -> a' = update_memory_content a\n                                 (phys_to_hard a (cache_location_address (cache a) pa))\n                                 (find_in_cache_location (cache a) pa)\n    -> smbase_inv a'.\nProof.\n  intros a a' pa.\n  remember (cache_location_address (cache a) pa) as pa'.\n  remember (find_in_cache_location (cache a) pa) as c'.\n  remember (phys_to_hard a pa') as ha'.\n  intros [Hsmramc [Hsmram [Hsmrr [Hclean [Hip Hsmbase]]]]] Heqa'.\n  apply update_memory_changes_only_memory in Heqa'.\n  destruct Heqa' as [Hmc [Hproc Hcache]].\n  unfold smbase_inv in *.\n  rewrite <- Hproc.\n  apply Hsmbase.\nQed.\n\nLemma update_memory_content_with_cache_content_preserves_inv:\n  forall a a' :Architecture Software,\n  forall pa   :PhysicalAddress,\n    inv a\n    -> a' = update_memory_content a\n                                 (phys_to_hard a (cache_location_address (cache a) pa))\n                                 (find_in_cache_location (cache a) pa)\n    -> inv a'.\nProof.\n  intros a a' pa.\n  intros Hinv Heqa'.\n  unfold inv.\n  split; [| split; [| split; [| split; [| split]]]]; [\n      eapply (update_memory_content_with_cache_content_preserves_smramc_inv a a' pa)\n    | eapply (update_memory_content_with_cache_content_preserves_smram_code_inv a a' pa)\n    | eapply (update_memory_content_with_cache_content_preserves_smrr_inv a a' pa)\n    | eapply (update_memory_content_with_cache_content_preserves_cache_clean_inv a a' pa)\n    | eapply (update_memory_content_with_cache_content_preserves_ip_inv a a' pa)\n    | eapply (update_memory_content_with_cache_content_preserves_smbase_inv a a' pa) ]; trivial.\nQed.\n\nLemma update_memory_content_with_context_preserves_smram_code_inv\n      (a a':   Architecture Software)\n      (pa:     PhysicalAddress)\n      (val:    Value)\n      (Hinv:   inv a)\n      (Heqa': a' = update_memory_content a (phys_to_hard a pa) (val, smm_context a))\n    : smram_code_inv a'.\nProof.\n  destruct Hinv as [Hsmramc [Hsmram [Hclean [Hsmrr [Hip Hsmbase]]]]].\n  unfold smram_code_inv.\n  intros pa' val' s Hinside' Hfind.\n  unfold update_memory_content in Heqa'.\n  unfold update_in_memory in Heqa'.\n  unfold find_memory_content, find_in_memory.\n  rewrite Heqa' in Hfind.\n  unfold find_memory_content, find_in_memory in Hfind.\n  simpl in Hfind.\n  unfold phys_to_hard, translate_physical_address in Hfind.\n  destruct is_inside_smram_dec as [Hinside|Houtside].\n  + destruct can_access_smram_dec as [Hcan|Hcannot].\n    * assert (smm_context a = smm) as Hcontext.\n      - unfold can_access_smram in Hcan.\n        destruct Hcan as [Hsmm|Hfalse].\n        unfold smm_context.\n        destruct is_in_smm_dec as [Hin|Hnotin]; try reflexivity.\n        unfold is_in_smm in Hnotin.\n        apply Hnotin in Hsmm.\n        destruct Hsmm.\n        unfold smramc_inv in Hsmramc.\n        unfold smramc_is_locked in Hsmramc.\n        unfold smramc_is_ro in Hsmramc.\n        apply (lock_is_close (smramc (memory_controller a))) in Hsmramc.\n        rewrite Hsmramc in Hfalse.\n        discriminate.\n      - rewrite Hcontext in Hfind.\n        destruct (eq_dec pa pa').\n        apply eq_equal in e.\n        rewrite e in Hfind.\n        rewrite add_1 in Hfind.\n        inversion Hfind.\n        reflexivity.\n        rewrite <- add_2 in Hfind.\n        unfold smram_code_inv in Hsmram.\n        apply (Hsmram pa' val' s Hinside' Hfind).\n        intro Hfalse.\n        apply hardware_dram_cast in Hfalse.\n        apply n in Hfalse.\n        exact Hfalse.\n    * rewrite <- add_2 in Hfind.\n      apply (Hsmram pa' val' s Hinside' Hfind).\n      intro H.\n      apply eq_sym in H.\n      assert (~ eq (dram pa') (vga pa)).\n      apply (neq_dram_vga_cast pa' pa).\n      apply H0 in H.\n      exact H.\n  + assert (~ eq pa pa') as Hneqpapa'.\n    apply (pa1_not_in_interval_pa2_in_interval_pa1_neq_pa2 pa pa' smram_space Houtside Hinside').\n    rewrite <- (add_2 (memory a) (dram pa) (dram pa')) in Hfind.\n    * apply (Hsmram pa' val' s Hinside' Hfind).\n    * intro Hfalse.\n      apply hardware_dram_cast in Hfalse.\n      apply Hneqpapa' in Hfalse.\n      exact Hfalse.\nQed.\n\nLemma update_memory_content_with_context_preserves_smramc_inv\n      (a a':  Architecture Software)\n      (pa:    PhysicalAddress)\n      (val:   Value)\n      (Hinv:  inv a)\n      (Heqa': a' = update_memory_content a (phys_to_hard a pa) (val, smm_context a))\n  : smramc_inv a'.\nProof.\n  destruct Hinv as [Hsmramc [Hsmram [Hsmrr [Hclean [Hip Hsmbase]]]]].\n  apply update_memory_changes_only_memory in Heqa' as [Hmc [Hproc Hother]].\n  unfold smramc_inv.\n  rewrite <- Hmc.\n  exact Hsmramc.\nQed.\n\nLemma update_memory_content_with_context_preserves_smbase_inv\n      (a a':  Architecture Software)\n      (pa:    PhysicalAddress)\n      (val:   Value)\n      (Hinv:  inv a)\n      (Heqa': a' = update_memory_content a (phys_to_hard a pa) (val, smm_context a))\n  : smbase_inv a'.\nProof.\n  destruct Hinv as [Hsmramc [Hsmram [Hsmrr [Hclean [Hip Hsmbase]]]]].\n  apply update_memory_changes_only_memory in Heqa' as [Hmc [Hproc Hother]].\n  unfold smbase_inv.\n  rewrite <- Hproc.\n  exact Hsmbase.\nQed.\n\nLemma update_memory_content_with_context_preserves_cache_clean_inv\n      (a a':  Architecture Software)\n      (pa:    PhysicalAddress)\n      (val:   Value)\n      (Hinv:  inv a)\n      (Heqa': a' = update_memory_content a (phys_to_hard a pa) (val, smm_context a))\n  : cache_clean_inv a'.\nProof.\n  destruct Hinv as [Hsmramc [Hsmram [Hsmrr [Hclean Hip]]]].\n  apply update_memory_changes_only_memory in Heqa' as [Hmc [Hproc Hother]].\n  unfold cache_clean_inv.\n  unfold find_cache_content.\n  rewrite <- Hother.\n  exact Hclean.\nQed.\n\nLemma update_memory_content_with_context_preserves_smrr_inv\n      (a a':  Architecture Software)\n      (pa:    PhysicalAddress)\n      (val:   Value)\n      (Hinv:  inv a)\n      (Heqa': a' = update_memory_content a (phys_to_hard a pa) (val, smm_context a))\n  : smrr_inv a'.\nProof.\n  destruct Hinv as [Hsmramc [Hsmram [Hsmrr [Hclean Hip]]]].\n  apply update_memory_changes_only_memory in Heqa' as [Hmc [Hproc Hother]].\n  unfold smrr_inv.\n  rewrite <- Hproc.\n  exact Hsmrr.\nQed.\n\nLemma update_memory_content_with_context_preserves_ip_inv\n      (a a':  Architecture Software)\n      (pa:    PhysicalAddress)\n      (val:   Value)\n      (Hinv:  inv a)\n      (Heqa': a' = update_memory_content a (phys_to_hard a pa) (val, smm_context a))\n  : ip_inv a'.\nProof.\n  destruct Hinv as [Hsmramc [Hsmram [Hsmrr [Hclean [Hip Hsmbase]]]]].\n  apply update_memory_changes_only_memory in Heqa' as [Hmc [Hproc Hother]].\n  unfold ip_inv.\n  rewrite <- Hproc.\n  rewrite <- (context_is_preserves a a' Hproc).\n  exact Hip.\nQed.\n\nLemma update_memory_content_with_context_preserves_inv\n      (a a':  Architecture Software)\n      (pa:    PhysicalAddress)\n      (val:   Value)\n      (Hinv:  inv a)\n      (Heqa': a' = update_memory_content a (phys_to_hard a pa) (val, smm_context a))\n  : inv a'.\nProof.\n  unfold inv.\n  split; [| split; [| split; [| split; [| split]]]]; [\n      eapply (update_memory_content_with_context_preserves_smramc_inv a a' pa val)\n    | eapply (update_memory_content_with_context_preserves_smram_code_inv a a' pa val)\n    | eapply (update_memory_content_with_context_preserves_smrr_inv a a' pa val)\n    | eapply (update_memory_content_with_context_preserves_cache_clean_inv a a' pa val)\n    | eapply (update_memory_content_with_context_preserves_ip_inv a a' pa val)\n    | eapply (update_memory_content_with_context_preserves_smbase_inv a a' pa val) ]; trivial.\nQed.\n\nLemma load_in_cache_from_memory_preserves_smram_code_inv\n      (a a':    Architecture Software)\n      (pa:      PhysicalAddress)\n      (Hinv:    inv a)\n      (Heqa':   a' = load_in_cache_from_memory a pa)\n  : smram_code_inv a'.\nProof.\n  destruct Hinv as [Hsmramc [Hsmram [Hsmrr [Hclean [Hip Hsmbase]]]]].\n  assert (inv a) as Hinv.\n  split; [ exact Hsmramc\n         | split; [ exact Hsmram\n                  | split ; [ exact Hsmrr\n                            | split ; [ exact Hclean\n                                      | split; [ exact Hip\n                                               | exact Hsmbase ]]]]].\n  unfold load_in_cache_from_memory in Heqa'.\n  destruct (cache_location_is_dirty_dec (cache a) pa) as [Hdirty|Hndirty].\n  + remember (update_memory_content a\n                                    (phys_to_hard a (cache_location_address (cache a) pa))\n                                    (find_in_cache_location (cache a) pa)) as ax.\n    assert (inv ax).\n    apply (update_memory_content_with_cache_content_preserves_inv a ax pa); trivial.\n    apply update_cache_changes_only_cache in Heqa'.\n    destruct Heqa' as [Hproc' [Hmc' Hmem']].\n    unfold smram_code_inv, find_memory_content.\n    rewrite <- Hmem'.\n    destruct H as [Hsmramcx [Hsmramx Hrest]].\n    exact Hsmramx.\n  + apply update_cache_changes_only_cache in Heqa'.\n    destruct Heqa' as [Hproc' [Hmc' Hmem']].\n    unfold smram_code_inv, find_memory_content.\n    rewrite <- Hmem'.\n    exact Hsmram.\nQed.\n\nLemma update_cache_with_memory_cache_clean_inv\n      (a a':  Architecture Software)\n      (pa:    PhysicalAddress)\n      (Hinv:  inv a)\n      (Hin_smm: (is_inside_smram pa -> is_in_smm (proc a)))\n      (Heqa': a' = update_cache_content a pa (find_memory_content a (phys_to_hard a pa)))\n  : cache_clean_inv a'.\nProof.\n  destruct Hinv as [Hsmramc [Hsmram [Hsmrr [Hclean [Hip Hsmbase]]]]].\n  unfold cache_clean_inv, find_cache_content.\n  intros pa' v' s Hinside' Hcache_hit Hfind.\n  remember (find_memory_content a (phys_to_hard a pa)) as c'.\n  unfold update_cache_content in Heqa'.\n  rewrite Heqa' in Hfind.\n  simpl in Hfind.\n  unfold global_update_in_cache in Hfind.\n  destruct (cache_hit_dec (cache a) pa) as [Hcache_hit_pa|Hnot_cache_hit_pa].\n  * unfold update_in_cache, find_in_cache in Hfind.\n    destruct (eq_dec pa pa') as [Heqpapa'|Hneqpapa'].\n    - apply eq_equal in Heqpapa'.\n      rewrite Heqpapa' in Hfind.\n      assert (cache_hit\n                (add_in_map (cache a) (phys_to_index pa')\n                            {| dirty := true; content := c'; tag := pa' |}) pa') as Hcache_hit_add.\n      unfold cache_hit.\n      rewrite add_1.\n      apply eq_refl.\n      destruct (cache_hit_dec\n                (add_in_map (cache a) (phys_to_index pa')\n                            {| dirty := true; content := c'; tag := pa' |}) pa');\n        [| intuition].\n      rewrite add_1 in Hfind.\n      simpl in Hfind.\n      rewrite Heqpapa' in Heqc'.\n      unfold phys_to_hard, translate_physical_address in Heqc'.\n      destruct (is_inside_smram_dec pa') as [Hinside|_H]; [| intuition ].\n      assert (is_in_smm (proc a)); [\n          rewrite <- Heqpapa' in Hinside;\n          apply (Hin_smm Hinside) |].\n      destruct (can_access_smram_dec (memory_controller a) (in_smm (proc a))) as [Hcan|Hcannot]; [\n        |  unfold can_access_smram in Hcannot;\n          intuition ].\n      destruct c'.\n      apply (Hsmram pa' v s Hinside).\n      rewrite <- Heqc'.\n      inversion Hfind.\n      reflexivity.\n    - destruct (eq_dec (phys_to_index pa) (phys_to_index pa')) as [Heqi|Hneqi].\n      assert (cache_hit (cache a') pa); [\n          rewrite Heqa';\n          simpl;\n          apply global_update_in_cache_cache_hit |].\n      assert (~ cache_hit (cache a') pa'); [\n          apply (cache_hit_same_index_cache_miss (cache a') pa); trivial\n        | intuition ].\n      assert (cache_hit\n                (add_in_map (cache a) (phys_to_index pa)\n                            {| dirty := true; content := c'; tag := pa |}) pa').\n      unfold cache_hit.\n      rewrite <- add_2; [| exact Hneqi ].\n      rewrite Heqa' in Hcache_hit.\n      simpl in Hcache_hit.\n      unfold cache_hit, global_update_in_cache in Hcache_hit.\n      destruct (cache_hit_dec (cache a) pa) as [Hcache_hit_x_pa|Hncache_hit_x_pa].\n      unfold update_in_cache in Hcache_hit.\n      rewrite <- add_2 in Hcache_hit; [| exact Hneqi ].\n      exact Hcache_hit.\n      apply Hncache_hit_x_pa in Hcache_hit_pa.\n      destruct Hcache_hit_pa.\n      destruct (cache_hit_dec\n                  (add_in_map (cache a) (phys_to_index pa)\n                              {| dirty := true; content := c'; tag := pa |}) pa') as [Hcache_add|Hncache_add].\n      rewrite <- add_2 in Hfind.\n      unfold cache_clean_inv in Hclean.\n      assert (cache_hit (cache a) pa') as Hcache_hit_x_pa'; [\n          apply (cache_hit_is_preserve_by_non_conflicted_update (cache a)\n                                                                (cache a')\n                                                                pa\n                                                                pa'\n                                                                c'); [\n          exact Hneqi |\n          rewrite Heqa'; simpl; reflexivity |\n          exact Hcache_hit ] |].\n      assert (find_cache_content a pa' = Some (content (find_in_map (cache a) (phys_to_index pa')))) as Hfind'.\n      unfold find_cache_content, find_in_cache.\n      destruct (cache_hit_dec (cache a) pa') as [_H|_H]; [ reflexivity | intuition ].\n      apply (Hclean pa' v' s Hinside' Hcache_hit_x_pa').\n      inversion Hfind.\n      exact Hfind'.\n      exact Hneqi.\n      discriminate Hfind.\n  * destruct (eq_dec (phys_to_index pa) (phys_to_index pa')) as [Heqi|Hneqi].\n    - assert (cache a'=global_update_in_cache (cache a) pa c') as Heqcache'; [\n        rewrite Heqa';\n        simpl;\n        reflexivity |].\n      assert (cache_hit (global_update_in_cache (cache a) pa c') pa); [\n          apply (global_update_in_cache_cache_hit (cache a) pa) |].\n      rewrite <- Heqcache' in H.\n      destruct (eq_dec pa pa') as [Heq|Hneq].\n      (* case addr_eq *)\n      apply eq_equal in Heq.\n      rewrite Heq in Heqc'.\n      unfold smram_code_inv in Hsmram.\n      assert (is_inside_smram pa'); try exact Hinside'.\n      rewrite <- Heq in Hinside'.\n      apply Hin_smm in Hinside'.\n      unfold is_in_smm in Hinside'.\n      unfold phys_to_hard, translate_physical_address in Heqc'.\n      rewrite <- Heq in Heqc'.\n      destruct (is_inside_smram_dec pa).\n      rewrite Hinside' in Heqc'.\n      destruct (can_access_smram_dec (memory_controller a) true).\n      destruct c' as [v l].\n      assert (l = smm).\n      apply (Hsmram pa v l i).\n      symmetry; exact Heqc'.\n      rewrite H1 in *.\n      unfold find_in_cache, load_in_cache in Hfind.\n      rewrite <- Heq in Hfind.\n      destruct cache_hit_dec.\n      rewrite add_1 in Hfind.\n      simpl in Hfind.\n      inversion Hfind.\n      reflexivity.\n      unfold cache_hit in n.\n      rewrite add_1 in n.\n      simpl in n.\n      unfold not in n.\n      assert (eq pa pa) by (apply eq_refl).\n      apply n in H2.\n      destruct H2.\n      unfold can_access_smram in n.\n      apply not_or_and in n.\n      destruct n as [G1 G2].\n      intuition.\n      rewrite <- Heq in H0.\n      intuition.\n      (* case ~ addr_eq *)\n      apply (global_update_not_cache_hit (cache a) (cache a') pa pa' c') in Heqcache'; try intuition.\n    - unfold find_in_cache, load_in_cache in Hfind.\n      destruct cache_hit_dec.\n      rewrite <- add_2 in Hfind.\n      assert (cache_hit (cache a) pa') as Hcache_hit_before; [\n          apply (cache_hit_is_preserve_by_non_conflicted_update (cache a)\n                                                                (cache a')\n                                                                pa\n                                                                pa'\n                                                                c'); [\n            exact Hneqi\n          | rewrite Heqa'; reflexivity\n          | exact Hcache_hit ] |].\n      unfold cache_clean_inv in Hclean.\n      inversion Hfind.\n      apply (Hclean pa' v' s Hinside' Hcache_hit_before).\n      unfold find_cache_content.\n      unfold find_in_cache.\n      destruct cache_hit_dec; intuition.\n      exact Hneqi.\n      discriminate Hfind.\nQed.\n\nLemma load_in_cache_from_memory_preserves_cache_clean_inv\n      (a a':  Architecture Software)\n      (pa:    PhysicalAddress)\n      (Hinv:  inv a)\n      (Hin_smm: (is_inside_smram pa -> is_in_smm (proc a)))\n      (Heqa': a' = load_in_cache_from_memory a pa)\n  : cache_clean_inv a'.\nProof.\n  destruct Hinv as [Hsmramc [Hsmram [Hsmrr [Hclean [Hip Hsmbase]]]]].\n  assert (inv a) as Hinv.\n  split; [ exact Hsmramc\n         | split; [ exact Hsmram\n                  | split ; [ exact Hsmrr\n                            | split ; [ exact Hclean\n                                      | split; [ exact Hip\n                                               | exact Hsmbase ]]]]].\n  unfold load_in_cache_from_memory in Heqa'.\n  destruct (cache_location_is_dirty_dec (cache a) pa) as [Hdirty|Hndirty].\n  + remember (update_memory_content a\n                                    (phys_to_hard a (cache_location_address (cache a) pa))\n                                    (find_in_cache_location (cache a) pa)) as ax.\n    assert (inv ax) as Hinvx.\n    apply (update_memory_content_with_cache_content_preserves_inv a ax pa); trivial.\n    apply (update_cache_with_memory_cache_clean_inv ax a' pa Hinvx);\n      destruct Hinvx as [Hsmramcx [Hsmramx [Hsmrrx [Hcleanx [Hipx Hsmbasex]]]]].\n    - apply update_memory_changes_only_memory in Heqax.\n      destruct Heqax as [_Hmc [Hproc _Hcache]].\n      rewrite <- Hproc.\n      exact Hin_smm.\n    - exact Heqa'.\n  + apply (update_cache_with_memory_cache_clean_inv a a' pa Hinv Hin_smm Heqa').\nQed.\n\nLemma load_in_cache_from_memory_preserves_smrr_inv\n      (a a':    Architecture Software)\n      (pa:      PhysicalAddress)\n      (Hinv:    inv a)\n      (Hin_smm: is_inside_smram pa -> is_in_smm (proc a))\n      (Heqa':   a' = load_in_cache_from_memory a pa)\n  : smrr_inv a'.\nProof.\n  destruct Hinv as [Hsmramc [Hsmram [Hsmrr [Hclean [Hip Hsmbase]]]]].\n  apply load_in_cache_from_memory_changes_only_mem_and_cache in Heqa' as [Hproc Hother].\n  unfold smrr_inv.\n  rewrite <- Hproc.\n  exact Hsmrr.\nQed.\n\nLemma load_in_cache_from_memory_preserves_smramc_inv\n      (a a':    Architecture Software)\n      (pa:      PhysicalAddress)\n      (Hinv:    inv a)\n      (Hin_smm: is_inside_smram pa -> is_in_smm (proc a))\n      (Heqa':   a' = load_in_cache_from_memory a pa)\n  : smramc_inv a'.\nProof.\n  destruct Hinv as [Hsmramc [Hsmram [Hsmrr [Hclean [Hip Hsmbase]]]]].\n  apply load_in_cache_from_memory_changes_only_mem_and_cache in Heqa' as [Hproc Hother].\n  unfold smramc_inv.\n  rewrite <- Hother.\n  exact Hsmramc.\nQed.\n\nLemma load_in_cache_from_memory_preserves_smbase_inv\n      (a a':    Architecture Software)\n      (pa:      PhysicalAddress)\n      (Hinv:    inv a)\n      (Hin_smm: is_inside_smram pa -> is_in_smm (proc a))\n      (Heqa':   a' = load_in_cache_from_memory a pa)\n  : smbase_inv a'.\nProof.\n  destruct Hinv as [Hsmramc [Hsmram [Hsmrr [Hclean [Hip Hsmbase]]]]].\n  apply load_in_cache_from_memory_changes_only_mem_and_cache in Heqa' as [Hproc Hother].\n  unfold smbase_inv.\n  rewrite <- Hproc.\n  exact Hsmbase.\nQed.\n\nLemma load_in_cache_from_memory_preserves_ip_inv\n      (a a':    Architecture Software)\n      (pa:      PhysicalAddress)\n      (Hinv:    inv a)\n      (Hin_smm: is_inside_smram pa -> is_in_smm (proc a))\n      (Heqa':   a' = load_in_cache_from_memory a pa)\n  : ip_inv a'.\nProof.\n  destruct Hinv as [Hsmramc [Hsmram [Hsmrr [Hclean [Hip Hsmbase]]]]].\n  apply load_in_cache_from_memory_changes_only_mem_and_cache in Heqa' as [Hproc Hother].\n  unfold ip_inv.\n  rewrite <- Hproc.\n  rewrite <- (context_is_preserves a a' Hproc).\n  exact Hip.\nQed.\n\nLemma load_in_cache_from_memory_preserves_inv\n      (a a':    Architecture Software)\n      (pa:      PhysicalAddress)\n      (Hinv:    inv a)\n      (Hin_smm: is_inside_smram pa -> is_in_smm (proc a))\n      (Heqa':   a' = load_in_cache_from_memory a pa)\n  : inv a'.\nProof.\n  unfold inv.\n  split; [| split; [| split; [| split; [| split]]]]; [\n      eapply (load_in_cache_from_memory_preserves_smramc_inv a a' pa)\n    | eapply (load_in_cache_from_memory_preserves_smram_code_inv a a' pa)\n    | eapply (load_in_cache_from_memory_preserves_smrr_inv a a' pa)\n    | eapply (load_in_cache_from_memory_preserves_cache_clean_inv a a' pa)\n    | eapply (load_in_cache_from_memory_preserves_ip_inv a a' pa)\n    | eapply (load_in_cache_from_memory_preserves_smbase_inv a a' pa) ]; trivial.\nQed.\n\nLemma update_cache_content_with_context_preserves_smramc_inv\n      (a a':    Architecture Software)\n      (pa:      PhysicalAddress)\n      (val:     Value)\n      (Hinv:    inv a)\n      (Hin_smm: is_inside_smram pa -> is_in_smm (proc a))\n      (Heqa':   a' = update_cache_content a pa (val, (smm_context a)))\n  : smramc_inv a'.\nProof.\n  destruct Hinv as [Hsmramc [Hsmram [Hsmrr [Hclean [Hip Hsmbase]]]]].\n  apply update_cache_changes_only_cache in Heqa' as [Hproc [Hmc Hother]].\n  unfold smramc_inv.\n  rewrite <- Hmc.\n  exact Hsmramc.\nQed.\n\nLemma update_cache_content_with_context_preserves_smrr_inv\n      (a a':    Architecture Software)\n      (pa:      PhysicalAddress)\n      (val:     Value)\n      (Hinv:    inv a)\n      (Hin_smm: is_inside_smram pa -> is_in_smm (proc a))\n      (Heqa':   a' = update_cache_content a pa (val, (smm_context a)))\n  : smrr_inv a'.\nProof.\n  destruct Hinv as [Hsmramc [Hsmram [Hsmrr [Hclean [Hip Hsmbase]]]]].\n  apply update_cache_changes_only_cache in Heqa' as [Hproc [Hmc Hother]].\n  unfold smrr_inv.\n  rewrite <- Hproc.\n  exact Hsmrr.\nQed.\n\nLemma update_cache_content_with_context_preserves_smram_code_inv\n      (a a':    Architecture Software)\n      (pa:      PhysicalAddress)\n      (val:     Value)\n      (Hinv:    inv a)\n      (Hin_smm: is_inside_smram pa -> is_in_smm (proc a))\n      (Heqa':   a' = update_cache_content a pa (val, (smm_context a)))\n  : smram_code_inv a'.\nProof.\n  destruct Hinv as [Hsmramc [Hsmram [Hsmrr [Hclean [Hip Hsmbase]]]]].\n  apply update_cache_changes_only_cache in Heqa' as [Hproc [Hmc Hmem]].\n  unfold smram_code_inv.\n  unfold find_memory_content.\n  rewrite <- Hmem.\n  exact Hsmram.\nQed.\n\nLemma update_cache_content_with_context_preserves_ip_inv\n      (a a':    Architecture Software)\n      (pa:      PhysicalAddress)\n      (val:     Value)\n      (Hinv:    inv a)\n      (Hin_smm: is_inside_smram pa -> is_in_smm (proc a))\n      (Heqa':   a' = update_cache_content a pa (val, (smm_context a)))\n  : ip_inv a'.\nProof.\n  destruct Hinv as [Hsmramc [Hsmram [Hsmrr [Hclean [Hip Hsmbase]]]]].\n  apply update_cache_changes_only_cache in Heqa' as [Hproc [Hmc Hmem]].\n  unfold ip_inv.\n  rewrite <- Hproc.\n  rewrite <- (context_is_preserves a a' Hproc).\n  exact Hip.\nQed.\n\nLemma update_cache_content_with_context_preserves_smbase_inv\n      (a a':    Architecture Software)\n      (pa:      PhysicalAddress)\n      (val:     Value)\n      (Hinv:    inv a)\n      (Hin_smm: is_inside_smram pa -> is_in_smm (proc a))\n      (Heqa':   a' = update_cache_content a pa (val, (smm_context a)))\n  : smbase_inv a'.\nProof.\n  destruct Hinv as [Hsmramc [Hsmram [Hsmrr [Hclean [Hip Hsmbase]]]]].\n  apply update_cache_changes_only_cache in Heqa' as [Hproc [Hmc Hmem]].\n  unfold smbase_inv.\n  rewrite <- Hproc.\n  exact Hsmbase.\nQed.\n\nLemma update_cache_content_with_context_preserves_cache_clean_inv\n      (a a':    Architecture Software)\n      (pa:      PhysicalAddress)\n      (val:     Value)\n      (Hinv:    inv a)\n      (Hin_smm: is_inside_smram pa -> is_in_smm (proc a))\n      (Heqa':   a' = update_cache_content a pa (val, (smm_context a)))\n  : cache_clean_inv a'.\nProof.\n  destruct Hinv as [Hsmramc [Hsmram [Hsmrr [Hclean [Hip Hsmbase]]]]].\n  unfold cache_clean_inv.\n  intros pa' val' s' Hinside' Hcache_hit' Hfind'.\n  assert (cache a' = global_update_in_cache (cache a) pa (val, smm_context a))\n    as Heqcache\n      by (rewrite Heqa'; reflexivity).\n  unfold global_update_in_cache in Heqcache.\n  destruct (cache_hit_dec (cache a) pa).\n  + unfold update_in_cache in Heqcache.\n    unfold find_cache_content in Hfind'.\n    unfold find_in_cache in Hfind'.\n    destruct cache_hit_dec; [| intuition ].\n    rewrite Heqa' in Hfind'; simpl.\n    destruct (eq_dec pa pa') as [Heq|Hneq].\n    * apply eq_equal in Heq.\n      rewrite <- Heq in Hfind'.\n      unfold update_cache_content, global_update_in_cache in Hfind'.\n      simpl in Hfind'.\n      destruct cache_hit_dec; [| intuition ].\n      unfold update_in_cache in Hfind'.\n      rewrite add_1 in Hfind'.\n      simpl in Hfind'.\n      inversion Hfind'.\n      rewrite <- Heq in Hinside'.\n      apply Hin_smm in Hinside'.\n      unfold smm_context.\n      destruct is_in_smm_dec.\n      reflexivity.\n      apply n in Hinside'.\n      destruct Hinside'.\n    * destruct (eq_dec (phys_to_index pa) (phys_to_index pa')) as [Heqi|Hneqi].\n      - assert (~ cache_hit (cache a') pa'); [| intuition ].\n        assert (cache_hit (cache a') pa) as Hcache_hit_pa.\n        unfold cache_hit.\n        rewrite Heqa'.\n        unfold update_cache_content, global_update_in_cache, update_in_cache.\n        simpl.\n        destruct cache_hit_dec; [| intuition ].\n        rewrite add_1.\n        simpl.\n        apply addr_eq_refl.\n        apply (cache_hit_same_index_cache_miss (cache a') pa pa' Hcache_hit_pa Hneq Heqi).\n      - simpl in Hfind'.\n        unfold global_update_in_cache, update_in_cache in Hfind'.\n        destruct cache_hit_dec; [| intuition].\n        rewrite <- add_2 in Hfind' ; [| exact Hneqi ].\n        assert (cache_hit (cache a) pa').\n        apply (cache_hit_is_preserve_by_non_conflicted_update (cache a)\n                                                              (cache a')\n                                                              pa pa'\n                                                              (val, smm_context a)\n                                                              Hneqi).\n        rewrite Heqa'.\n        simpl.\n        reflexivity.\n        exact Hcache_hit'.\n        inversion Hfind'.\n        unfold cache_clean_inv in Hclean.\n        apply (Hclean pa' val' s' Hinside' H).\n        unfold find_cache_content, find_in_cache.\n        destruct cache_hit_dec; [| intuition].\n        rewrite H1.\n        reflexivity.\n  + unfold load_in_cache in Heqcache.\n    unfold find_cache_content in Hfind'.\n    unfold find_in_cache in Hfind'.\n    destruct cache_hit_dec; [| intuition ].\n    rewrite Heqa' in Hfind'; simpl in Hfind'.\n    inversion Hfind'.\n    destruct (eq_dec pa pa') as [Heqpa|Hneqpa].\n    * apply eq_equal in Heqpa.\n      rewrite <- Heqpa in H0.\n      unfold global_update_in_cache in H0.\n      destruct cache_hit_dec; [intuition|].\n      unfold load_in_cache in H0.\n      rewrite add_1 in H0.\n      simpl in H0.\n      inversion H0.\n      rewrite <- Heqpa in Hinside'.\n      apply Hin_smm in Hinside'.\n      unfold smm_context.\n      destruct is_in_smm_dec.\n      reflexivity.\n      apply n1 in Hinside'.\n      destruct Hinside'.\n    * destruct (eq_dec (phys_to_index pa) (phys_to_index pa')) as [Heqi|Hneqi].\n      - assert (~ cache_hit (cache a') pa'); [| intuition ].\n        assert (cache_hit (cache a') pa).\n        unfold cache_hit.\n        rewrite Heqa'.\n        unfold update_cache_content, global_update_in_cache, load_in_cache.\n        simpl.\n        destruct cache_hit_dec; [intuition|].\n        rewrite add_1.\n        simpl.\n        apply addr_eq_refl.\n        apply (cache_hit_same_index_cache_miss (cache a') pa pa' H Hneqpa Heqi).\n      - unfold update_cache_content, global_update_in_cache, load_in_cache in H0.\n        destruct cache_hit_dec; [intuition|].\n        rewrite <- add_2 in H0; [| exact Hneqi ].\n        assert (cache_hit (cache a) pa').\n        apply (cache_hit_is_preserve_by_non_conflicted_update (cache a)\n                                                              (cache a')\n                                                              pa pa'\n                                                              (val, smm_context a)\n                                                              Hneqi).\n        rewrite Heqa'.\n        simpl.\n        reflexivity.\n        exact Hcache_hit'.\n        unfold cache_clean_inv in Hclean.\n        apply (Hclean pa' val' s' Hinside' H).\n        unfold find_cache_content, find_in_cache.\n        destruct cache_hit_dec; [|intuition].\n        rewrite H0.\n        reflexivity.\nQed.\n\nLemma update_cache_content_with_context_preserves_inv\n      (a a':    Architecture Software)\n      (pa:      PhysicalAddress)\n      (val:     Value)\n      (Hinv:    inv a)\n      (Hin_smm: is_inside_smram pa -> is_in_smm (proc a))\n      (Heqa':   a' = update_cache_content a pa (val, (smm_context a)))\n  : inv a'.\nProof.\n  unfold inv.\n  split; [| split; [| split; [| split; [| split]]]]; [\n      eapply (update_cache_content_with_context_preserves_smramc_inv a a' pa val)\n    | eapply (update_cache_content_with_context_preserves_smram_code_inv a a' pa val)\n    | eapply (update_cache_content_with_context_preserves_smrr_inv a a' pa val)\n    | eapply (update_cache_content_with_context_preserves_cache_clean_inv a a' pa val)\n    | eapply (update_cache_content_with_context_preserves_ip_inv a a' pa val)\n    | eapply (update_cache_content_with_context_preserves_smbase_inv a a' pa val) ]; trivial.\nQed.\n\nLemma load_then_update_cache_with_context_preserves_inv\n      (a a'':   Architecture Software)\n      (pa:      PhysicalAddress)\n      (val:     Value)\n      (Hinv:    inv a)\n      (Hin_smm: is_inside_smram pa -> is_in_smm (proc a))\n      (Heqa'':  a'' = update_cache_content (load_in_cache_from_memory a pa) pa (val, smm_context a))\n  : inv a''.\nProof.\n  remember (load_in_cache_from_memory a pa) as a'.\n  assert (inv a')\n    as Hinv'\n      by (apply (load_in_cache_from_memory_preserves_inv a a' pa Hinv Hin_smm Heqa')).\n  assert (proc a = proc a').\n  apply load_in_cache_from_memory_changes_only_mem_and_cache in Heqa' as [Hproc _H].\n  exact Hproc.\n  rewrite H in Hin_smm.\n  rewrite (context_is_preserves a a' H) in Heqa''.\n  apply (update_cache_content_with_context_preserves_inv a' a'' pa val Hinv' Hin_smm Heqa'').\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/Architecture.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947290421276, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2569393220855357}}
{"text": "Require Import coqutil.Macros.unique.\nRequire Import coqutil.Decidable.\nRequire Import compiler.FlatImp.\nRequire Import Coq.Lists.List.\nImport ListNotations.\nRequire Import Coq.ZArith.ZArith.\nRequire Import riscv.Spec.Machine.\nRequire Import riscv.Spec.PseudoInstructions.\nRequire Import riscv.Utility.InstructionCoercions.\nRequire Import coqutil.Z.Lia.\nRequire Import riscv.Spec.Primitives.\nRequire Import riscv.Utility.Utility.\nRequire Import coqutil.Datatypes.ListSet.\nRequire Import riscv.Utility.Encode.\nRequire Import riscv.Utility.RegisterNames.\nRequire Import bedrock2.Syntax.\nRequire Import coqutil.Map.Interface.\nRequire Import compiler.SeparationLogic.\nRequire Import riscv.Spec.Decode.\nRequire Import compiler.Registers.\nRequire Import compiler.FlatImpConstraints.\n\nLocal Open Scope ilist_scope.\nLocal Open Scope Z_scope.\n\nSet Implicit Arguments.\n\nNotation Register0 := 0%Z (only parsing).\n\nDefinition valid_instructions(iset: InstructionSet)(prog: list Instruction): Prop :=\n  forall instr, In instr prog -> verify instr iset.\n\n(* x0 is the constant 0, x1 is ra, x2 is sp, the others are usable *)\nDefinition valid_FlatImp_var(x: Z): Prop := 3 <= x < 32.\n\nLemma sp_not_valid_FlatImp_var: ~ valid_FlatImp_var RegisterNames.sp.\nProof. unfold valid_FlatImp_var, RegisterNames.sp. clear. blia. Qed.\n\nLemma ra_not_valid_FlatImp_var: ~ valid_FlatImp_var RegisterNames.ra.\nProof. unfold valid_FlatImp_var, RegisterNames.ra. clear. blia. Qed.\n\nLemma valid_FlatImp_var_implies_valid_register: forall (x: Z),\n    valid_FlatImp_var x -> valid_register x.\nProof. unfold valid_FlatImp_var, valid_register. intros. blia. Qed.\n\nSection FlatToRiscv1.\n\n  (* Part 1: Definitions needed to state when compilation outputs valid code *)\n\n  Definition valid_registers_bcond: bcond Z -> Prop := ForallVars_bcond valid_register.\n  Definition valid_FlatImp_vars_bcond: bcond Z -> Prop := ForallVars_bcond valid_FlatImp_var.\n\n  Lemma valid_FlatImp_vars_bcond_implies_valid_registers_bcond: forall b,\n      valid_FlatImp_vars_bcond b -> valid_registers_bcond b.\n  Proof.\n    unfold valid_FlatImp_vars_bcond, valid_registers_bcond.\n    intros. eauto using ForallVars_bcond_impl, valid_FlatImp_var_implies_valid_register.\n  Qed.\n\n  Definition valid_FlatImp_vars: stmt Z -> Prop := Forall_vars_stmt valid_FlatImp_var.\n\n  Definition valid_FlatImp_fun: list Z * list Z * stmt Z -> Prop :=\n    fun '(argnames, retnames, body) =>\n      argnames = List.firstn (List.length argnames) (reg_class.all reg_class.arg) /\\\n      retnames = List.firstn (List.length retnames) (reg_class.all reg_class.arg) /\\\n      valid_FlatImp_vars body /\\\n      uses_standard_arg_regs body.\n\n\n  Context (iset: InstructionSet).\n\n  (* Part 2: compilation *)\n\n  (* load & store depend on the bitwidth: on 32-bit machines, Lw just loads 4 bytes,\n     while on 64-bit machines, it loads 4 bytes and sign-extends them.\n     If we want a command which always loads 4 bytes without sign-extending them,\n     we need to make a case distinction on the bitwidth and choose Lw on 32-bit,\n     but Lwu on 64-bit.\n     We can't just always choose Lwu, because Lwu is not available on 32-bit machines. *)\n\n  Definition compile_load(sz: access_size):\n    Z -> Z -> Z -> Instruction :=\n    match sz with\n    | access_size.one => Lbu\n    | access_size.two => Lhu\n    | access_size.four => if bitwidth iset =? 32 then Lw else Lwu\n    | access_size.word => if bitwidth iset =? 32 then Lw else Ld\n    end.\n\n  Definition compile_store(sz: access_size):\n    Z -> Z -> Z -> Instruction :=\n    match sz with\n    | access_size.one => Sb\n    | access_size.two => Sh\n    | access_size.four => Sw\n    | access_size.word => if bitwidth iset =? 32 then Sw else Sd\n    end.\n\n  Definition compile_op_imm(rd: Z)(op: Syntax.bopname)(rs1: Z)(c2: Z): list Instruction :=\n    match op with\n    | Syntax.bopname.add => [[Addi rd rs1 c2]]\n    | Syntax.bopname.and => [[Andi rd rs1 c2]]\n    | Syntax.bopname.or  => [[Ori  rd rs1 c2]]\n    | Syntax.bopname.xor => [[Xori rd rs1 c2]]\n    | Syntax.bopname.sru => [[Srli rd rs1 c2]]\n    | Syntax.bopname.slu => [[Slli rd rs1 c2]]\n    | Syntax.bopname.srs => [[Srai rd rs1 c2]]\n    | Syntax.bopname.lts => [[Slti rd rs1 c2]]\n    | Syntax.bopname.ltu => [[Sltiu rd rs1 c2]]\n    | _ => [InvalidInstruction (-1)]\n    end.\n\n  Definition compile_op_register(rd: Z)(op: Syntax.bopname)(rs1 rs2: Z): list Instruction :=\n    match op with\n    | Syntax.bopname.add => [[Add rd rs1 rs2]]\n    | Syntax.bopname.sub => [[Sub rd rs1 rs2]]\n    | Syntax.bopname.mul => [[Mul rd rs1 rs2]]\n    | Syntax.bopname.mulhuu => [[Mulhu rd rs1 rs2]]\n    | Syntax.bopname.divu => [[Divu rd rs1 rs2]]\n    | Syntax.bopname.remu => [[Remu rd rs1 rs2]]\n    | Syntax.bopname.and => [[And rd rs1 rs2]]\n    | Syntax.bopname.or  => [[Or  rd rs1 rs2]]\n    | Syntax.bopname.xor => [[Xor rd rs1 rs2]]\n    | Syntax.bopname.sru => [[Srl rd rs1 rs2]]\n    | Syntax.bopname.slu => [[Sll rd rs1 rs2]]\n    | Syntax.bopname.srs => [[Sra rd rs1 rs2]]\n    | Syntax.bopname.lts => [[Slt rd rs1 rs2]]\n    | Syntax.bopname.ltu => [[Sltu rd rs1 rs2]]\n    | Syntax.bopname.eq  => [[Sub rd rs1 rs2; Seqz rd rd]]\n    end.\n  Definition compile_op(rd: Z)(op: Syntax.bopname)(op1 : Z)(op2: operand): list Instruction :=\n    match  op2 with\n    | Var v2 => compile_op_register rd op op1 v2\n    | Const c2 => compile_op_imm rd op op1 c2\n    end.\n\n  Definition compile_lit_12bit(rd: Z)(v: Z): list Instruction :=\n    [[ Addi rd Register0 (signExtend 12 v) ]].\n\n  (* On a 64bit machine, loading a constant -2^31 <= v < 2^31 is not always possible with\n     a Lui followed by an Addi:\n     If the constant is of the form 0x7ffffXXX, and XXX has its highest bit set, we would\n     have to put 0x80000--- into the Lui, but then that value will be sign-extended.\n\n     Or spelled differently:\n     If we consider all possible combinations of a Lui followed by an Addi, we get 2^32\n     different values, but some of them are not in the range -2^31 <= v < 2^31.\n     On the other hand, this property holds for combining Lui followed by a Xori.\n\n     Or yet differently:\n     Lui 0x80000--- ; Addi 0xXXX\n     where XXX has the highest bit set,\n     loads a value < 2^31, so some Lui+Addi pairs do not load a value in the range\n     -2^31 <= v < 2^31, so some Lui+Addi pairs are \"wasted\" and we won't find a\n     Lui+Addi pairs for all desired values in the range -2^31 <= v < 2^31\n *)\n\n  Definition compile_lit_32bit(rd: Z)(v: Z): list Instruction :=\n    let lo := signExtend 12 v in\n    let hi := Z.lxor (signExtend 32 v) lo in\n    [[ Lui rd hi ; Xori rd rd lo ]].\n\n  Definition compile_lit_64bit(rd: Z)(v: Z): list Instruction :=\n    let v0 := bitSlice v  0 11 in\n    let v1 := bitSlice v 11 22 in\n    let v2 := bitSlice v 22 32 in\n    let hi := bitSlice v 32 64 in\n    compile_lit_32bit rd (signExtend 32 hi) ++\n    [[ Slli rd rd 10 ;\n       Xori rd rd v2 ;\n       Slli rd rd 11 ;\n       Xori rd rd v1 ;\n       Slli rd rd 11 ;\n       Xori rd rd v0 ]].\n\n  Definition compile_lit(rd: Z)(v: Z): list Instruction :=\n    if ((-2^11 <=? v)%Z && (v <? 2^11)%Z)%bool then\n      compile_lit_12bit rd v\n    else if ((bitwidth iset =? 32)%Z || (- 2 ^ 31 <=? v)%Z && (v <? 2 ^ 31)%Z)%bool then\n      compile_lit_32bit rd v\n    else compile_lit_64bit rd v.\n\n  (* Inverts the branch condition. *)\n  Definition compile_bcond_by_inverting\n             (cond: bcond Z) (amt: Z) : Instruction:=\n    match cond with\n    | CondBinary op x y =>\n        match op with\n        | BEq  => Bne x y amt\n        | BNe  => Beq x y amt\n        | BLt  => Bge x y amt\n        | BGe  => Blt x y amt\n        | BLtu => Bgeu x y amt\n        | BGeu => Bltu x y amt\n        end\n    | CondNez x =>\n        Beq x Register0 amt\n    end.\n\n  Local Notation bytes_per_word := (Memory.bytes_per_word (bitwidth iset)).\n\n  Fixpoint save_regs(regs: list Z)(offset: Z): list Instruction :=\n    match regs with\n    | nil => nil\n    | r :: regs => compile_store access_size.word sp r offset\n                   :: (save_regs regs (offset + bytes_per_word))\n    end.\n\n  Fixpoint load_regs(regs: list Z)(offset: Z): list Instruction :=\n    match regs with\n    | nil => nil\n    | r :: regs => compile_load access_size.word r sp offset\n                   :: (load_regs regs (offset + bytes_per_word))\n    end.\n\n  (* number of words of stack allocation space needed within current frame *)\n  Fixpoint stackalloc_words(s: stmt Z): Z :=\n    match s with\n    | SLoad _ _ _ _ | SStore _ _ _ _ | SInlinetable _ _ _ _ | SLit _ _ | SOp _ _ _ _ | SSet _ _\n    | SSkip | SCall _ _ _ | SInteract _ _ _ => 0\n    | SIf _ s1 s2 | SLoop s1 _ s2 | SSeq s1 s2 => Z.max (stackalloc_words s1) (stackalloc_words s2)\n    (* ignore negative values, and round up values that are not divisible by bytes_per_word *)\n    | SStackalloc x n body => (Z.max 0 n + bytes_per_word - 1) / bytes_per_word\n                              + stackalloc_words body\n    end.\n\n  Definition compile4bytes(l: list byte): Instruction :=\n    InvalidInstruction (LittleEndian.combine 4 (HList.tuple.of_list [\n      nth 0 l Byte.x00;\n      nth 1 l Byte.x00;\n      nth 2 l Byte.x00;\n      nth 3 l Byte.x00\n    ])).\n\n  Fixpoint compile_byte_list(l: list byte): list Instruction :=\n    match l with\n    | b0 :: b1 :: b2 :: b3 :: rest => compile4bytes l :: compile_byte_list rest\n    | nil => nil\n    | _ => [compile4bytes l]\n    end.\n\n  (* All positions are relative to the beginning of the progam, so we get completely\n     position independent code. *)\n\n  Context {env: map.map String.string (list Z * list Z * stmt Z)}.\n  Context {pos_map: map.map String.string Z}.\n  Context (compile_ext_call: pos_map -> Z -> Z -> stmt Z -> list Instruction).\n\n  Section WithEnv.\n    Variable e: pos_map.\n\n    (* mypos: position of the code relative to the positions in e\n       stackoffset: $sp + stackoffset is the (last) highest used stack address (for SStackalloc)\n       s: statement to be compiled *)\n    Fixpoint compile_stmt(mypos: Z)(stackoffset: Z)(s: stmt Z): list Instruction :=\n      match s with\n      | SLoad  sz x y ofs => [[compile_load  sz x y ofs]]\n      | SStore sz x y ofs => [[compile_store sz x y ofs]]\n      | SInlinetable sz x t i =>\n        let bs := compile_byte_list t in\n        [[ Jal x (4 + Z.of_nat (length bs) * 4) ]] ++ bs ++ [[ Add x x i; compile_load sz x x 0 ]]\n      | SStackalloc x n body =>\n          [[Addi x sp (stackoffset-n)]] ++ compile_stmt (mypos + 4) (stackoffset-n) body\n      | SLit x v => compile_lit x v\n      | SOp x op y z => compile_op x op y z\n      | SSet x y => [[Add x Register0 y]]\n      | SIf cond bThen bElse =>\n          let bThen' := compile_stmt (mypos + 4) stackoffset bThen in\n          let bElse' := compile_stmt (mypos + 4 + 4 * Z.of_nat (length bThen') + 4) stackoffset bElse in\n          (* only works if branch lengths are < 2^12 *)\n          [[compile_bcond_by_inverting cond ((Z.of_nat (length bThen') + 2) * 4)]] ++\n          bThen' ++\n          [[Jal Register0 ((Z.of_nat (length bElse') + 1) * 4)]] ++\n          bElse'\n      | SLoop body1 cond body2 =>\n          let body1' := compile_stmt mypos stackoffset body1 in\n          let body2' := compile_stmt (mypos + (Z.of_nat (length body1') + 1) * 4) stackoffset body2 in\n          (* only works if branch lengths are < 2^12 *)\n          body1' ++\n          [[compile_bcond_by_inverting cond ((Z.of_nat (length body2') + 2) * 4)]] ++\n          body2' ++\n          [[Jal Register0 (- Z.of_nat (length body1' + 1 + length body2') * 4)]]\n      | SSeq s1 s2 =>\n          let s1' := compile_stmt mypos stackoffset s1 in\n          let s2' := compile_stmt (mypos + 4 * Z.of_nat (length s1')) stackoffset s2 in\n          s1' ++ s2'\n      | SSkip => nil\n      | SCall resvars f argvars =>\n        let fpos := match map.get e f with\n                    | Some pos => pos\n                    (* don't fail so that we can measure the size of the resulting code *)\n                    | None => 42\n                    end in\n        [[ Jal ra (fpos - mypos) ]]\n      | SInteract _ _ _ => compile_ext_call e mypos stackoffset s\n      end.\n\n    (*\n     Stack layout:\n\n     high addresses              ...\n                      old sp --> begin of stack scratch space of previous function\n                                 ra\n                                 mod_var_n\n                                 ...\n                                 mod_var_0\n                                 end of stack scratch space of current function\n                                 ...  (stack scratch space also grows downwards, from \"end\" to \"begin\")\n                      new sp --> begin of stack scratch space of current function\n     low addresses               ...\n\n     Expected stack layout at beginning of function call: like above, but only filled up to arg0.\n     Stack grows towards low addresses.\n    *)\n    Definition compile_function(mypos: Z):\n      (list Z * list Z * stmt Z) -> list Instruction :=\n      fun '(argvars, resvars, body) =>\n        let need_to_save := list_diff Z.eqb (modVars_as_list Z.eqb body) resvars in\n        let scratchwords := stackalloc_words body in\n        let framesize := bytes_per_word *\n                         (Z.of_nat (1 + length need_to_save) + scratchwords) in\n        [[ Addi sp sp (-framesize) ]] ++\n        [[ compile_store access_size.word sp ra\n                         (bytes_per_word * (Z.of_nat (length need_to_save) + scratchwords)) ]] ++\n        save_regs need_to_save (bytes_per_word * scratchwords) ++\n        compile_stmt (mypos + 4 * (2 + Z.of_nat (length need_to_save)))\n                     (bytes_per_word * scratchwords) body ++\n        load_regs need_to_save (bytes_per_word * scratchwords) ++\n        [[ compile_load access_size.word ra sp\n                        (bytes_per_word * (Z.of_nat (length need_to_save) + scratchwords)) ]] ++\n        [[ Addi sp sp framesize ]] ++\n        [[ Jalr zero ra 0 ]].\n\n    Definition add_compiled_function(state: list Instruction * pos_map)(fname: String.string)\n               (fimpl: list Z * list Z * stmt Z): list Instruction * pos_map :=\n      let '(old_insts, infomap) := state in\n      let pos := 4 * Z.of_nat (length (old_insts)) in\n      let new_insts := compile_function pos fimpl in\n      let '(argnames, retnames, fbody) := fimpl in\n      (old_insts ++ new_insts,\n       map.put infomap fname pos).\n\n    Definition compile_funs: env -> list Instruction * pos_map :=\n      map.fold add_compiled_function (nil, map.empty).\n  End WithEnv.\n\n  (* compiles all functions just to obtain their code size *)\n  Definition build_fun_pos_env(e_impl: env): pos_map :=\n    (* since we pass map.empty as the fun_pos_env into compile_funs, the instrs\n       returned don't jump to the right positions yet (they all jump to 42),\n       but the instructions have the right size, so the posmap we return is correct *)\n    snd (compile_funs map.empty e_impl).\n\nEnd FlatToRiscv1.\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/FlatToRiscvDef.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7520125737597974, "lm_q2_score": 0.34158250614097546, "lm_q1q2_score": 0.25687433959439676}}
{"text": "(* Testing robustness of typing for a fixpoint with evars in its type *)\n\nInductive foo (n : nat) : Type := .\nDefinition foo_denote {n} (x : foo n) : Type := match x with end.\n\nDefinition baz : forall n (x : foo n), foo_denote x.\nrefine (fix go n (x : foo n) : foo_denote x := _).\nAbort.  \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/5077.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.25674588324701014}}
{"text": "Require Import VST.msl.msl_standard.\nRequire Import VST.msl.corable.\nRequire Import RamifyCoq.msl_ext.ramify_tactics.\nRequire Import RamifyCoq.msl_ext.msl_ext.\nRequire Import RamifyCoq.msl_ext.sepalg.\n\nLocal Open Scope pred.\n\nLemma join_age {A}{JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A}:\n  forall h1 h2 h12 h1' h2' h12', join h1 h2 h12 -> join h1' h2' h12' -> age h1 h1' -> age h2 h2' -> age h12 h12'.\nProof.\n  intros; destruct (age1_join _ H H1) as [w2 [w12 [? [? ?]]]];\n  equate_age h2' w2; equate_join h12' w12; auto.\nQed.\n\nProgram Definition ocon {A: Type}{JA: Join A}{PA : Perm_alg A}{AG : ageable A} {AA : Age_alg A} (p q:pred A) : pred A :=\n  fun h:A => exists h1 h2 h3 h12 h23, join h1 h2 h12 /\\ join h2 h3 h23 /\\ join h12 h3 h /\\ p h12 /\\ q h23.\nNext Obligation.\n  destruct H0 as [h1 [h2 [h3 [h12 [h23 [? [? [? [? ?]]]]]]]]].\n  try_join h2 h3 h23'; equate_join h23 h23'.\n  destruct (age1_join2 _ H2 H) as [w12 [w3 [? [? ?]]]].\n  destruct (age1_join2 _ H0 H7) as [w1 [w2 [? [? ?]]]].\n  try_join w2 w3 w23.\n  exists w1, w2, w3, w12, w23.\n  repeat split; auto.\n  apply pred_hereditary with h12; auto.\n  apply pred_hereditary with h23; auto.\n  apply (join_age h2 h3 _ w2 w3 _); auto.\nQed.\n\nNotation \"P ⊗ Q\" := (ocon P Q) (at level 40, left associativity) : pred.\n\nProgram Definition owand {A: Type}{JA: Join A}{PA : Perm_alg A}{AG : ageable A} {AA : Age_alg A} (p q:pred A) : pred A :=\n  fun h23':A => forall h23 h1 h2 h3 h12 h123, necR h23' h23 -> join h1 h2 h12 -> join h2 h3 h23 -> join h12 h3 h123 -> p h12 -> q h123.\nNext Obligation.\n  rename a' into h23'.\n  eapply (H0 h23 h1 h2 h3 h12 h123); eauto.\n  apply necR_power_age.\n  apply necR_power_age in H1.\n  destruct H1 as [n ?H].\n  exists (S n).\n  exists h23'; auto.\nQed.\n\nLemma ocon_emp_i {A}{JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{CA: Canc_alg A}{AG : ageable A} {AA : Age_alg A}: forall P: pred A, P ⊗ emp = P.\nProof.\n  intros; apply pred_ext; hnf; intros; simpl in *; intros.\n  destruct_ocon H h; try_join h2 h3 h23'; equate_join h23 h23'.\n  rewrite (H3 _ _ (join_comm H5)) in H.\n  generalize (join_positivity H H1); intro; rewrite H4; trivial.\n  exists a, (core a), (core a), a, (core a).\n  generalize (core_unit a); intro.\n  unfold unit_for in H0.\n  repeat split; auto.\n  apply core_duplicable.\n  apply core_identity.\nQed.\n\nLemma ocon_TT_i {A}{JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{CA: Canc_alg A}{AG : ageable A} {AA : Age_alg A}: forall P: pred A, P ⊗ TT = P * TT.\nProof.\n  intros; apply pred_ext; hnf; intros; simpl in *; intros.\n  + destruct_ocon H h.\n    exists h12, h3; auto.\n  + destruct H as [? [? [? [? ?]]]].\n    exists x, (core x), x0, x, x0.\n    repeat split; auto.\n    - apply join_comm, core_unit.\n    - apply join_core2 in H.\n      rewrite H.\n      apply core_unit.\nQed.\n\nLemma andp_ocon_i {A}{JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG : ageable A} {AA : Age_alg A}: forall P Q, P && Q |-- P ⊗ Q.\nProof.\n  intros.\n  hnf; intros; simpl in *; intros.\n  destruct H.\n  remember (core a) as u.\n  exists u, a, u, a, a.\n  repeat split; try rewrite Hequ; auto;\n  try apply core_unit;\n  apply join_comm; apply core_unit.\nQed.\n\nLemma ocon_andp_prop_i {A}{JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG : ageable A} {AA : Age_alg A}: forall P Q R, P ⊗ (!!Q && R) = !!Q && (P ⊗ R).\nProof.\n  intros; apply pred_ext; hnf; intros; simpl in *.\n  + destruct H as [h1 [h2 [h3 [h12 [h23 [? [? [? [? [? ?]]]]]]]]]].\n    split; auto. exists h1, h2, h3, h12, h23. intuition.\n  + destruct H as [? [h1 [h2 [h3 [h12 [h23 [? [? [? [? ?]]]]]]]]]].\n    exists h1, h2, h3, h12, h23. intuition.\nQed.\n\nLemma sepcon_ocon_i {A}{JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG : ageable A} {AA : Age_alg A}: forall P Q, P * Q |-- P ⊗ Q.\nProof.\n  intros; hnf; intros; simpl in *; intros.\n  destruct H as [y [z [? [? ?]]]].\n  remember (core z) as u.\n  exists y, u, z, y, z.\n  repeat split; auto.\n  generalize (join_core H); intro.\n  generalize (join_core (join_comm H)); intro.\n  rewrite Hequ.\n  replace (core z) with (core y).\n  apply join_comm, core_unit.\n  rewrite H2, H3; trivial.\n  rewrite Hequ. apply core_unit.\nQed.\n\nLemma join_necR {A}{JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A}:\n  forall h1 h2 h12 h1' h2' h12', join h1 h2 h12 -> join h1' h2' h12' -> necR h1 h1' -> necR h2 h2' -> necR h12 h12'.\nProof.\n  intros; destruct (nec_join H H1) as [w2 [w12 [? [? ?]]]];\n  destruct (join_level _ _ _ H3); rewrite <- H7 in H6;\n  destruct (join_level _ _ _ H0); rewrite <- H9 in H8;\n  rewrite H8 in H6; generalize (necR_linear' H2 H4 H6); intro;\n  rewrite <- H10 in H3; equate_join h12' w12; auto.\nQed.\n\nLemma ocon_wand_i {A}{JA: Join A}{PA: Perm_alg A}{AG : ageable A} {AA : Age_alg A}: forall P Q, P ⊗ Q = EX R : pred A, (R -* P) * (R -* Q) * R.\nProof.\n  intros; apply pred_ext; hnf; intros; simpl in *.\n  destruct H as [h1 [h2 [h3 [h12 [h23 [? [? [? [? ?]]]]]]]]].\n  try_join h2 h3 h23'; equate_join h23 h23'; try_join h1 h3 h13.\n  exists (exactly h2), h13, h2; repeat split; simpl; auto; exists h1, h3; repeat split; auto.\n  intros h1' h2' h12'; intros; apply (pred_nec_hereditary P h12); auto; apply (join_necR h1 h2 _ h1' h2' _); auto.\n  intros h3' h2' h23'; intros; apply (pred_nec_hereditary Q h23); auto; apply (join_necR h2 h3 _ h2' h3' _); auto.\n  (* another direction *)\n  destruct H as [R [w13 [w2 [? [[w1 [w3 [? [HP HQ]]]] HR]]]]].\n  try_join w2 w3 w23; try_join w1 w2 w12.\n  exists w1, w2, w3, w12, w23; repeat split; auto.\n  apply (HP w1 w2); auto. apply (HQ w3 w2); auto.\nQed.\n\nLemma ocon_comm_i {A}{JA: Join A}{PA: Perm_alg A}{AG : ageable A} {AA : Age_alg A}: forall P Q, P ⊗ Q = Q ⊗ P.\nProof.\n  intros; apply pred_ext; hnf; intros; simpl in *; intros;\n  destruct_ocon H h; exists h3, h2, h1, h23, h12;\n  repeat split; auto; try_join h2 h3 h23'; equate_join h23 h23'; auto.\nQed.\n\nLemma cross_rev {A}{JA: Join A}{PA: Perm_alg A}{AG : ageable A} {AA : Age_alg A}: forall h1 h2 h3 h4\n  h12 h34 h13 h24 h1234, join h1 h2 h12 -> join h1 h3 h13 -> join h3 h4\n  h34 -> join h2 h4 h24 -> join h12 h34 h1234 -> join h13 h24 h1234.\nProof.\n  intros; try_join h2 h34 h234;\n  try_join h2 h4 h24'; equate_join h24 h24';\n  try_join h1 h3 h13'; equate_join h13 h13'; auto.\nQed.\n\nLemma ocon_assoc_i {A}{JA: Join A}{PA: Perm_alg A}{CA: Cross_alg A}{AG : ageable A} {AA : Age_alg A}:\n  forall P Q R: pred A, P ⊗ Q ⊗ R = P ⊗ (Q ⊗ R).\nProof.\n  intros; apply pred_ext; hnf; intros; simpl in *; intros.\n  destruct H as [w124 [w567 [w3 [w124567 [w3567 [? [? [? [[w15 [w47 [w26 [w1457 [w2467 [? [? [? [? ?]]]]]]]]] ?]]]]]]]]].\n  destruct (cross_split _ _ _ _ _ H H4) as [[[[w14 w2] w57] w6] [? [? [? ?]]]].\n  destruct (cross_split _ _ _ _ _ H2 H10) as [[[[w1 w5] w4] w7] [? [? [? ?]]]].\n  try_join w5 w47 w457; try_join w3 w26 w236; try_join w236 w457 w234567.\n  exists w1, w457, w236, w1457, w234567; repeat split; auto.\n  try_join w2 w4 w24; try_join w6 w7 w67; try_join w3 w5 w35.\n  exists w24, w67, w35, w2467, w3567; repeat split; auto.\n  apply (cross_rev w2 w6 w4 w7 w26 w47); auto. apply (cross_rev w47 w5 w26 w3 w457 w236); auto.\n  (* another direction *)\n  destruct H as [w1 [w457 [w236 [w1457 [w234567 [? [? [? [? [w24 [w67 [w35 [w2467 [w3567 [? [? [? [? ?]]]]]]]]]]]]]]]]]].\n  destruct (cross_split _ _ _ _ _ H0 H5) as [[[[w47 w5] w26] w3] [? [? [? ?]]]].\n  destruct (cross_split _ _ _ _ _ H3 H10) as [[[[w4 w2] w7] w6] [? [? [? ?]]]].\n  try_join w26 w1457 w124567; try_join w5 w67 w567; try_join w5 w7 w57; try_join w1 w4 w14;\n  try_join w14 w26 w1246; try_join w2 w14 w124.\n  exists w124, w567, w3, w124567, w3567; repeat split; auto.\n  apply join_comm; apply (cross_rev w6 w2 w57 w14 w26 w1457); auto.\n  try_join_through w67 w5 w7 w57'; equate_join w57 w57'; auto.\n  try_join w1 w5 w15; exists w15, w47, w26, w1457, w2467;\n  repeat split; auto.\nQed.\n\nLemma ocon_derives_i {A} {JA: Join A}{PA: Perm_alg A}{AG : ageable A} {AA : Age_alg A}: forall p q p' q', (p |-- p') -> (q |-- q') -> (p ⊗ q |-- p' ⊗ q').\nProof.\n  repeat (intros; hnf).\n  simpl in H1.\n  destruct_ocon H1 w.\n  exists w1,w2,w3,w12,w23.\n  repeat split; auto.\nQed.\n\nLemma owand_ocon_adjoint_i {A} {JA: Join A}{PA: Perm_alg A}{AG : ageable A} {AA : Age_alg A}: forall P Q R, ocon P Q |-- R <-> P |-- owand Q R.\nProof.\n  intros.\n  rewrite ocon_comm_i.\n  unfold ocon, owand, derives.\n  simpl.\n  split; intros.\n  + apply H.\n    exists h1, h2, h3, h12, h23.\n    repeat split; auto.\n    inversion P.\n    apply pred_nec_hereditary with a; auto.\n  + destruct H0 as [h1 [h2 [h3 [h12 [h23 [? [? [? [? ?]]]]]]]]].\n    specialize (H h23 H4).\n    specialize (H h23 h1 h2 h3 h12 a).\n    apply H; auto.\nQed.\n\nLemma ocon_contain_i {A} {JA: Join A} {PA: Perm_alg A} {SA: Sep_alg A}{AG : ageable A} {AA : Age_alg A}: forall P Q, Q |-- P * TT -> Q |-- ocon P Q.\nProof.\n  unfold ocon, owand, derives; simpl; intros.\n  destruct (H a H0) as [y [z [? [? ?]]]].\n  exists (core y), y, z, y, a.\n  repeat split; auto.\n  apply core_unit.\nQed.\n\nLemma precise_ocon_contain_i {A} {JA: Join A} {PA: Perm_alg A} {SA: Sep_alg A} {CA: Canc_alg A} {DA: Disj_alg A} {AG : ageable A} {AA : Age_alg A}: forall P Q, precise P -> Q |-- P * TT -> Q = ocon P Q.\nProof.\n  intros; apply pred_ext; [apply ocon_contain_i; auto |].\n  unfold ocon, owand, derives in *; simpl in *.\n  intros.\n  destruct H1 as [h1 [h2 [h3 [h12 [h23 [? [? [? [? ?]]]]]]]]].\n  destruct (H0 _ H5) as [y [z [? [? ?]]]].\n  try_join h2 h3 h23'. equate_join h23 h23'. assertSub y a HS1.\n  equate_precise y h12.\n  try_join z h1 h3'. equate_canc h3 h3'.\n  assert (identity h1).\n  1: {\n    try_join h1 h3 h_temp.\n    assertSub h1 h3 H12.\n    eapply join_sub_joins_identity; eauto.\n  }\n  apply join_comm in H4.\n  apply H9 in H10; apply H9 in H4.\n  subst.\n  auto.\nQed.\n\nDefinition disjointed {A: Type} {JA: Join A} {AG : ageable A} (P Q: pred A):=\n  forall h1 h2 h3 h12 h23,\n  join h1 h2 h12 -> join h2 h3 h23 -> P h12 -> Q h23 -> identity h2 /\\ joins h1 h3.\n\nLemma ocon_sepcon_i {A: Type} {JA: Join A} {SA: Sep_alg A} {PA : Perm_alg A} {AG : ageable A} {AA : Age_alg A}:\n  forall P Q, disjointed P Q -> ocon P Q |-- P * Q.\nProof.\n  unfold ocon, sepcon, disjointed, derives; simpl.\n  intros.\n  destruct H0 as [h1 [h2 [h3 [h12 [h23 [? [? [? [? ?]]]]]]]]].\n  destruct (H h1 h2 h3 h12 h23 H0 H1 H3 H4) as [? ?].\n  apply join_comm in H0.\n  apply H5 in H0.\n  apply H5 in H1.\n  subst.\n  exists h12, h23.\n  auto.\nQed.\n\nLemma disj_emp_i {A: Type} {JA: Join A} {SA: Sep_alg A} {PA : Perm_alg A} {CA: Canc_alg A} {AG : ageable A} {AA : Age_alg A}: forall P, disjointed P emp.\nProof.\n  intros.\n  unfold disjointed, emp; simpl; intros.\n  pose proof split_identity _ _ H0 H2.\n  pose proof split_identity _ _ (join_comm H0) H2.\n  pose proof identities_unique H3 H4 (ex_intro _ h23 H0).\n  subst.\n  split; eauto.\nQed.\n\nLemma disj_comm_i {A: Type} {JA: Join A} {PA: Perm_alg A} {AG : ageable A}: forall P Q, disjointed P Q -> disjointed Q P.\nProof.\n  unfold disjointed; intros.\n  specialize (H h3 h2 h1 h23 h12).\n  do 2 (spec H; [apply join_comm; auto |]).\n  do 2 (spec H; [auto |]).\n  destruct H; split; auto.\n  apply joins_comm; auto.\nQed.\n\nLemma disj_derives_i {A: Type} {JA: Join A} {PA: Perm_alg A} {AG : ageable A}:\n  forall P P' Q Q', P |-- P' -> Q |-- Q' -> disjointed P' Q' -> disjointed P Q.\nProof.\n  unfold derives, disjointed.\n  intros.\n  apply H1 with h12 h23; auto.\nQed.\n\n(**************************************************************************\n\n\n\n          |------------------------------------------|\n          |                                          | \n          |                                          | \n          |                                          | \n          |                     P                    | \n          |                                          | \n          |                                          | \n|---------|----------|-----------------------|-------|------------|\n|         |          |                       |       |            |\n|         |    p1    |         p2            |   p3  |            |\n|         |          |                       |       |            |\n|         |------------------------------------------|            |\n|                    |                       |                    |\n|                    |                       |                    |\n|        r1          |          r2           |         r3         |\n|                    |                       |                    |\n|                    |                       |                    |\n|                    |                       |                    |\n|--------------------|-----------------------|--------------------|\n\n\n\n\n**************************************************************************)\n\nLemma disj_ocon_right_i {A: Type} {JA: Join A} {SA: Sep_alg A} {PA : Perm_alg A} {CA: Canc_alg A} {CrA: Cross_alg A} {TA: Trip_alg A} {AG : ageable A} {AA : Age_alg A}:\n  forall P Q R, disjointed P Q -> disjointed P R -> disjointed P (ocon Q R).\nProof.\n  unfold ocon, disjointed, precise; simpl.\n  intros P Q R ? ? hP hp1p2p3 hr1r2r3 hPp h123.\n  intros.\n  destruct H4 as [h1 [h2 [h3 [h12 [h23 [? [? [? [? ?]]]]]]]]].\n  destruct (join_assoc H4 H6) as [h23' [? ?]]; equate_join h23 h23'.\n  destruct (cross_split _ _ _ _ _ H10 H2) as [[[[hp1 hr1] hp2p3] hr2r3] [? [? [? ?]]]].\n  destruct (cross_split _ _ _ _ _ H5 H11) as [[[[hp2 hr2] hp3] hr3] [? [? [? ?]]]].\n  try_join hp1 hp2 hp1p2.\n  try_join hr1 hr2 hr1r2.\n  assert (join hp1p2 hr1r2 h12).\n  1: {\n    try_join hp1 h2 hp1p2r2.\n    destruct (join_assoc (join_comm H14) (join_comm H22)) as [hp1p2' [? ?]].\n    equate_join hp1p2 hp1p2'.\n    destruct (join_assoc (join_comm H25) (join_comm H23)) as [hr1r2' [? ?]].\n    equate_join hr1r2 hr1r2'.\n    auto.\n  }\n\n  try_join hP hp3 hPp3.\n  assert (identity hp1p2 /\\ joins hPp3 hr1r2) as [? ?] by (apply H with hPp h12; auto).\n  try_join hP hp1 hPp1.\n  assert (identity hp2p3 /\\ joins hPp1 hr2r3) as [? ?] by (apply H0 with hPp h23; auto).\n\n  assert (identity hp1) by (apply split_identity with hp2 hp1p2; auto).\n  assert (identity hp3) by (apply split_identity with hp2 hp2p3; auto).\n  split.\n  + apply join_identity with hp1 hp2p3; auto.\n  + apply H31 in H27.\n    apply H32 in H23.\n    subst hPp1 hPp3.\n    destruct H26 as [hPr1r2 ?].\n    destruct H30 as [hPr1r3 ?].\n    destruct (join_assoc H20 (join_comm H23)) as [hPr1 [? ?]].\n    destruct (triple_join_exists _ _ _ _ _ _ H13 (join_comm H26) H27) as [hPr1r2r3 ?H].\n    apply joins_comm; eauto.\nQed.\n\nDefinition covariant {B A : Type} {AG: ageable A} (F: (B -> pred A) -> (B -> pred A)) : Prop :=\nforall (P Q: B -> pred A), (forall x, P x |-- Q x) -> (forall x, F P x |-- F Q x).\n\nLemma covariant_ocon {B}{A} {JA: Join A}{PA: Perm_alg A}{AG : ageable A} {AA : Age_alg A}:\n   forall F1 F2 : (B -> pred A) -> (B -> pred A),\n    covariant F1 -> covariant F2 ->\n    covariant (fun (x : B -> pred A) b => F1 x b ⊗ F2 x b).\nProof.\n  intros; hnf.\n  intros P Q ? ?.\n  eapply ocon_derives_i.\n  apply H, H1.\n  apply H0, H1.\nQed.\n\nDefinition contravariant {B A : Type} {AG: ageable A} (F: (B -> pred A) -> (B -> pred A)) : Prop :=\nforall (P Q: B -> pred A), (forall x, P x |-- Q x) -> (forall x, F Q x |-- F P x).\n\nLemma contravariant_ocon {B}{A} {JA: Join A}{PA: Perm_alg A}{AG : ageable A} {AA : Age_alg A}:\n   forall F1 F2 : (B -> pred A) -> (B -> pred A),\n    contravariant F1 -> contravariant F2 ->\n    contravariant (fun (x : B -> pred A) b => F1 x b ⊗ F2 x b).\nProof.\n  intros; hnf.\n  intros P Q ? ?.\n  eapply ocon_derives_i.\n  apply H, H1.\n  apply H0, H1.\nQed.\n\nLemma later_ocon {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)) = |> Q ⊗ |> P).\nProof.\n  intros; repeat rewrite later_age; apply pred_ext; hnf; intros; simpl in *.\n  case_eq (age1 a); intros.\n  destruct (H a0) as [h1' [h2' [h3' [h12' [h23' [? [? [? [? ?]]]]]]]]]; auto.\n  destruct (unage_join2 _ H3 H0) as [x12 [x3 [? [? ?]]]].\n  destruct (unage_join2 _ H1 H7) as [x1 [x2 [? [? ?]]]].\n  try_join x2 x3 x23; exists x3, x2, x1, x23, x12; repeat (split; auto).\n  assert (age x23 h23') by (apply (join_age x2 x3 _ h2' h3' _); auto); intro h23; intros; equate_age h23' h23; auto.\n  assert (age x12 h12') by (apply (join_age x1 x2 _ h1' h2' _); auto); intro h12; intros; equate_age h12' h12; auto.\n  exists (core a), a, (core a), a, a. repeat split.\n  apply core_unit. apply join_comm, core_unit. apply join_comm, core_unit.\n  intros; unfold age in H1; rewrite H0 in H1; discriminate H1.\n  intros; unfold age in H1; rewrite H0 in H1; discriminate H1.\n  (* another direction *)\n  destruct H as [x1 [x2 [x3 [x12 [x23 [? [? [? [? ?]]]]]]]]]; intros.\n  destruct (age1_join2 _ H1 H4) as [h12 [h3 [? [? ?]]]].\n  destruct (age1_join2 _ H H6) as [h1 [h2 [? [? ?]]]].\n  try_join h2 h3 h23; exists h3, h2, h1, h23, h12; repeat (split; auto).\n  apply H3; apply (join_age x2 x3 _ h2 h3 _); auto.\nQed.\n\nLemma precise_ocon_i {A} {JA : Join A} {PA : Perm_alg A} {SA: Sep_alg A}{CaA : Canc_alg A}{CrA : Cross_alg A}{DA : Disj_alg A}{AG : ageable A} {AA : Age_alg A} :\n  forall P Q, precise P -> precise Q -> precise (P ⊗ Q).\nProof.\n  intros; intro; intros.\n  destruct_ocon H1 h; destruct_ocon H2 i.\n  generalize (join_join_sub H6); intro; generalize (join_sub_trans H13 H3); intro.\n  generalize (join_join_sub H10); intro; generalize (join_sub_trans H15 H4); intro.\n  generalize (H w h12 i12 H7 H11 H14 H16); intro.\n  try_join h2 h3 h23'; equate_join h23 h23'; try_join i2 i3 i23'; equate_join i23 i23'.\n  generalize (join_join_sub' H19); intro; generalize (join_sub_trans H18 H3); intro.\n  generalize (join_join_sub' H20); intro; generalize (join_sub_trans H22 H4); intro.\n  generalize (H0 w h23 i23 H8 H12 H21 H23); intro.\n  rewrite H17 in *; rewrite H24 in *. clear h12 h23 H7 H8 H11 H12 H13 H14 H15 H16 H17 H18 H21 H22 H23 H24.\n  apply (overlapping_eq h1 h2 h3 i1 i2 i3 i12 i23); trivial.\nQed.\n\nLemma precise_tri_exp_ocon {A} {JA : Join A} {PA : Perm_alg A} {SA: Sep_alg A} {CaA : Canc_alg A}\n      {CrA : Cross_alg A} {DA : Disj_alg A}{AG : ageable A} {AA : Age_alg A} B:\n  forall (P : B -> B -> B -> pred A) (Q R: B -> pred A),\n    precise (EX x : B, EX y : B, EX z : B, P x y z) -> precise (exp Q) -> precise (exp R) ->\n    precise (EX x : B, EX y : B, EX z : B, P x y z ⊗ Q y ⊗ R z).\nProof.\n  repeat intro.\n  destruct H2 as [x1 [y1 [z1 ?]]]; destruct_ocon H2 h; destruct_ocon H8 j;\n  destruct H3 as [x2 [y2 [z2 ?]]]; destruct_ocon H3 i; destruct_ocon H16 k.\n  assert (j12 = k12) by (hnf in H; apply H with (w := w);\n                         [exists x1, y1, z1 | exists x2, y2, z2 | assertSub j12 w Hsub | assertSub k12 w Hsub]; auto).\n  assert (j23 = k23) by (hnf in H0; apply H0 with (w := w);\n                         [exists y1 | exists y2 | try_join j2 j3 j23'; equate_join j23 j23'; assertSub j23 w Hsub |\n                                 try_join k2 k3 k23'; equate_join k23 k23'; assertSub k23 w Hsub]; auto).\n  rewrite H22 in *; rewrite H23 in *; assert (h12 = i12) by (apply (overlapping_eq j1 j2 j3 k1 k2 k3 k12 k23); trivial).\n  assert (h23 = i23) by (hnf in H1; apply H1 with (w := w);\n                         [exists z1 | exists z2 | try_join h2 h3 h23'; equate_join h23 h23'; assertSub h23 w Hsub |\n                                 try_join i2 i3 i23'; equate_join i23 i23'; assertSub i23 w Hsub]; auto).\n  rewrite H24 in *; rewrite H25 in *; apply (overlapping_eq h1 h2 h3 i1 i2 i3 i12 i23); trivial.\nQed.\n\nLemma extract_andp_ocon_ocon_left {A} {JA : Join A} {PA : Perm_alg A} {SA: Sep_alg A}{AG : ageable A} {AA : Age_alg A}:\n  forall (w : A) P Q R S, (P && Q ⊗ R ⊗ S) w -> exists w', P w'.\nProof. repeat intro; destruct_ocon H h; destruct_ocon H2 i; destruct H6; exists i12; trivial. Qed.\n\nLemma ocon_precise_elim  {A}{JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{CA: Canc_alg A}{DA : Disj_alg A}{AG : ageable A} {AA : Age_alg A}:\n  forall P : pred A, precise P -> P ⊗ P = P.\nProof.\n  intros; apply pred_ext; intro w; intro. destruct_ocon H0 h. try_join h2 h3 h23'; equate_join h23 h23'. equate_precise h12 h23.\n  assert (emp h1). assertSub h1 h12 HS. assert (joins h1 h12). exists w; auto. apply (join_sub_joins_identity HS H4).\n  equate_canc h1 h3. apply (join_unit1_e _ _ H4) in H6. subst. auto. hnf. exists (core w), w, (core w), w, w. split.\n  apply core_unit. split. apply join_comm, core_unit. split. apply join_comm, core_unit. split; auto.\nQed.\n\nLemma corable_ocon_i: forall {A}{JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG : ageable A} {AA : Age_alg A} P Q, corable P -> corable Q -> corable (ocon P Q).\nProof.\n  intros.\n  rewrite corable_spec in H, H0 |- *.\n  unfold ocon.\n  intros.\n  simpl in H2 |- *.\n  destruct H2 as [h1 [h2 [h3 [h12 [h23 [? [? [? [? ?]]]]]]]]].\n  exists (core y), (core y), y, (core y), y.\n  pose proof join_core H2.\n  pose proof join_core (join_comm H2).\n  pose proof join_core H3.\n  pose proof join_core (join_comm H3).\n  pose proof join_core H4.\n  pose proof join_core (join_comm H4).\n  repeat split.\n  + rewrite <- core_idem at 1.\n    apply core_unit.\n  + apply core_unit.\n  + apply core_unit.\n  + apply H with h12; auto.\n    rewrite core_idem.\n    congruence.\n  + apply H0 with h23; auto.\n    congruence.\nQed.\n\nLemma corable_andp_ocon1_i {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{agA: ageable A}{AgeA: Age_alg A}:\n   forall P Q R, corable P ->  ocon (P && Q) R = P && (ocon Q R).\nProof.\n  intros.\n  apply pred_ext.\n  + intros h [h1 [h2 [h3 [h12 [h23 [? [? [? [[? ?] ?]]]]]]]]].\n    split.\n    - apply join_core in H2.\n      rewrite corable_spec in H.\n      apply H with h12; [congruence | auto].\n    - exists h1, h2, h3, h12, h23.\n      tauto.\n  + intros h [? [h1 [h2 [h3 [h12 [h23 [? [? [? [? ?]]]]]]]]]].\n    exists h1, h2, h3, h12, h23.\n    rewrite corable_spec in H.\n    repeat split; auto.\n    apply join_core in H3.\n    apply H with h; [congruence | auto].\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/RamifyCoq/msl_ext/overlapping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030761371502, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.25674587683958777}}
{"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 ARM operators *)\n\nDefinition eval_static_shift (s: shift) (v: aval): aval :=\n  match s with\n  | Slsl x => shl v (I x)\n  | Slsr x => shru v (I x)\n  | Sasr x => shr v (I x)\n  | Sror x => ror v (I x)\n  end.\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  | Ccompshift c s, v1 :: v2 :: nil => cmp_bool c v1 (eval_static_shift s v2)\n  | Ccompushift c s, v1 :: v2 :: nil => cmpu_bool c v1 (eval_static_shift s 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  | Ccompfzero c, v1 :: nil => cmpf_bool c v1 (F Float.zero)\n  | Cnotcompfzero c, v1 :: nil => cnot (cmpf_bool c v1 (F Float.zero))\n  | Ccompfs c, v1 :: v2 :: nil => cmpfs_bool c v1 v2\n  | Cnotcompfs c, v1 :: v2 :: nil => cnot (cmpfs_bool c v1 v2)\n  | Ccompfszero c, v1 :: nil => cmpfs_bool c v1 (FS Float32.zero)\n  | Cnotcompfszero c, v1 :: nil => cnot (cmpfs_bool c v1 (FS Float32.zero))\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, v1::v2::nil => add v1 v2\n  | Aindexed2shift s, v1::v2::nil => add v1 (eval_static_shift s v2)\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  | Oaddrsymbol id ofs, nil => Ptr (Gl id ofs)\n  | Oaddrstack ofs, nil => Ptr (Stk ofs)\n  | Ocast8signed, v1 :: nil => sign_ext 8 v1\n  | Ocast16signed, v1 :: nil => sign_ext 16 v1\n  | Oadd, v1::v2::nil => add v1 v2\n  | Oaddshift s, v1::v2::nil => add v1 (eval_static_shift s v2)\n  | Oaddimm n, v1::nil => add v1 (I n)\n  | Osub, v1::v2::nil => sub v1 v2\n  | Osubshift s, v1::v2::nil => sub v1 (eval_static_shift s v2)\n  | Orsubshift s, v1::v2::nil => sub (eval_static_shift s v2) v1\n  | Orsubimm n, v1::nil => sub (I n) v1\n  | Omul, v1::v2::nil => mul v1 v2\n  | Omla, v1::v2::v3::nil => add (mul v1 v2) v3\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  | Oand, v1::v2::nil => and v1 v2\n  | Oandshift s, v1::v2::nil => and v1 (eval_static_shift s v2)\n  | Oandimm n, v1::nil => and v1 (I n)\n  | Oor, v1::v2::nil => or v1 v2\n  | Oorshift s, v1::v2::nil => or v1 (eval_static_shift s v2)\n  | Oorimm n, v1::nil => or v1 (I n)\n  | Oxor, v1::v2::nil => xor v1 v2\n  | Oxorshift s, v1::v2::nil => xor v1 (eval_static_shift s v2)\n  | Oxorimm n, v1::nil => xor v1 (I n)\n  | Obic, v1::v2::nil => and v1 (notint v2)\n  | Obicshift s, v1::v2::nil => and v1 (notint (eval_static_shift s v2))\n  | Onot, v1::nil => notint v1\n  | Onotshift s, v1::nil => notint (eval_static_shift s v1)\n  | Oshl, v1::v2::nil => shl v1 v2\n  | Oshr, v1::v2::nil => shr v1 v2\n  | Oshru, v1::v2::nil => shru v1 v2\n  | Oshift s, v1::nil => eval_static_shift s v1\n  | Oshrximm n, v1::nil => shrx v1 (I n)\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  | Ointuoffloat, v1::nil => intuoffloat v1\n  | Ofloatofint, v1::nil => floatofint v1\n  | Ofloatofintu, v1::nil => floatofintu v1\n  | Ointofsingle, v1::nil => intofsingle v1\n  | Ointuofsingle, v1::nil => intuofsingle v1\n  | Osingleofint, v1::nil => singleofint v1\n  | Osingleofintu, v1::nil => singleofintu 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\nLemma eval_static_shift_sound:\n  forall s v a,\n  vmatch bc v a ->\n  vmatch bc (eval_shift s v) (eval_static_shift s a).\nProof.\n  intros. unfold eval_shift, eval_static_shift. destruct s; eauto with va.\nQed.\n\nHint Resolve eval_static_shift_sound: va.\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  rewrite Int.add_zero_l; eauto with va.\n  fold (Val.sub (Vint i) x). auto with va.\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/arm/ValueAOp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2567405116641796}}
{"text": "From Equations Require Import Equations.\n\nRequire Import Psatz.\n\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\n\nRequire Export SystemFR.OpenTOpen.\nRequire Export SystemFR.EqualWithRelation.\nRequire Export SystemFR.ReducibilityCandidate.\nRequire Export SystemFR.ReducibilityDefinition.\nRequire Export SystemFR.SubstitutionLemmas.\nRequire Export SystemFR.TOpenTClose.\nRequire Export SystemFR.NoTypeFVar.\nRequire Export SystemFR.PolarityLemmas.\nRequire Export SystemFR.FVLemmasLists.\nRequire Export SystemFR.NoTypeFVarLemmas.\nRequire Export SystemFR.TypeErasureLemmas.\nRequire Export SystemFR.AnnotatedTermLemmas.\n\nOpaque makeFresh.\nOpaque PeanoNat.Nat.eq_dec.\n\nLemma erase_type_topen2:\n  forall T1 T2 k,\n    is_annotated_type T1 ->\n    erase_type T2 = T2 ->\n    erase_type (topen k T1 T2) = topen k (erase_type T1) T2.\nProof.\n  induction T1;\n    repeat step || rewrite erase_term_topen in * || t_equality || rewrite topen_erase_term in *.\nQed.\n\nLemma has_polarities_erase_aux:\n  forall n T pols,\n    type_nodes T < n ->\n    is_annotated_type T ->\n    has_polarities T pols ->\n    has_polarities (erase_type T) pols.\nProof.\n  induction n; destruct T; steps; try lia;\n    repeat\n      step || step_inversion has_polarities || constructor || exists X || t_fv_erase ||\n      rewrite <- erase_type_topen2 || apply_any || autorewrite with bsize in *;\n        eauto with lia;\n        eauto 2 with annot step_tactic.\nQed.\n\nLemma has_polarities_erase:\n  forall T pols,\n    is_annotated_type T ->\n    has_polarities T pols ->\n    has_polarities (erase_type T) pols.\nProof.\n  eauto using has_polarities_erase_aux.\nQed.\n\nLemma has_polarities_subst_aux:\n  forall n T pols l,\n    type_nodes T < n ->\n    has_polarities T pols ->\n    pclosed_mapping l type_var ->\n    twfs l 0 ->\n    has_polarities (psubstitute T l term_var) pols.\nProof.\n  induction n; destruct T;\n    repeat step || constructor || step_inversion has_polarities || exists X || t_pfv_in_subst || eapply_any ||\n           autorewrite with bsize in * ||\n           (rewrite substitute_topen2 by steps);\n      eauto with lia.\nQed.\n\nLemma has_polarities_subst:\n  forall T pols l,\n    has_polarities T pols ->\n    pclosed_mapping l type_var ->\n    twfs l 0 ->\n    has_polarities (psubstitute T l term_var) pols.\nProof.\n  eauto using has_polarities_subst_aux.\nQed.\n\nLemma has_polarities_subst_erase:\n  forall (X : nat) (Γ : map nat tree) (Ts : tree) (ρ : interpretation) l pols,\n    is_annotated_type Ts ->\n    has_polarities (topen 0 Ts (fvar X type_var)) pols ->\n    satisfies (reducible_values ρ) (erase_context Γ) l ->\n    has_polarities (topen 0 (psubstitute (erase_type Ts) l term_var) (fvar X type_var)) pols.\nProof.\n  steps.\n  apply has_polarities_erase in H0;\n    repeat step || rewrite erase_type_topen in * by steps; eauto 2 with annot step_tactic.\n  rewrite substitute_topen2; steps; eauto with twf.\n  apply has_polarities_subst; steps; eauto with fv 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/PolarityErase.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.25674050566027795}}
{"text": "(** VCFloat: A Unified Coq Framework for Verifying C Programs with\n Floating-Point Computations. Application to SAR Backprojection.\n \n Version 1.0 (2015-12-04)\n \n Copyright (C) 2015 Reservoir Labs Inc.\n All rights reserved.\n \n This file, which is part of VCFloat, is free software. You can\n redistribute it and/or modify it under the terms of the GNU General\n Public License as published by the Free Software Foundation, either\n version 3 of the License (GNU GPL v3), or (at your option) any later\n version. A verbatim copy of the 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 VCFloat 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 VCFloat in your work, please consider\n 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 VCFloat requires third-party libraries listed in ACKS along with their\n copyright information.\n \n VCFloat depends on third-party libraries listed in ACKS along with\n their copyright and licensing information.\n*)\n(**\nAuthor: Tahina Ramananandro <ramananandro@reservoir.com>\n\nVCFloat: helpers for correct optimization of rounding error terms in\nthe real-number semantics of floating-point computations.\n**)\n\nRequire Export vcfloat.Float_lemmas.\nRequire Export vcfloat.FPLang.\nRequire Import vcfloat.klist.\nImport RAux.\nImport vcfloat.IEEE754_extra.\n(*Import compcert.lib.Floats. *)\nRequire Export vcfloat.LibTac.\nRequire Export vcfloat.BigRAux.\nSet Bullet Behavior \"Strict Subproofs\". (* because LibTac screws it up *)\n\nDefinition rounded_binop_eqb (r1 r2: rounded_binop): bool :=\n  match r1, r2 with\n    | PLUS, PLUS => true\n    | MINUS, MINUS => true\n    | MULT, MULT => true\n    | DIV, DIV => true\n    | _, _ => false\n  end.\n\nLemma rounded_binop_eqb_eq r1 r2:\n  (rounded_binop_eqb r1 r2 = true <-> r1 = r2).\nProof.\n  destruct r1; destruct r2; simpl; intuition congruence.\nQed.\n\nDefinition rounding_knowledge_eqb (r1 r2: rounding_knowledge): bool :=\n  match r1, r2 with\n    | Normal, Normal => true\n    | Denormal, Denormal => true\n    | _, _ => false\n  end.\n\nLemma rounding_knowledge_eqb_eq r1 r2:\n  (rounding_knowledge_eqb r1 r2 = true <-> r1 = r2).\nProof.\n  destruct r1; destruct r2; simpl; try intuition congruence.\nQed.\n\nExport Bool.\n\nDefinition binop_eqb b1 b2 :=\n  match b1, b2 with\n    | Rounded2 op1 k1, Rounded2 op2 k2 =>\n      rounded_binop_eqb op1 op2 && option_eqb rounding_knowledge_eqb k1 k2\n    | SterbenzMinus, SterbenzMinus => true\n    | PlusZero minus1 zero_left1, PlusZero minus2 zero_left2 =>\n      Bool.eqb minus1 minus2 && Bool.eqb zero_left1 zero_left2\n    | _, _ => false\n  end.\n\nLemma binop_eqb_eq b1 b2:\n  (binop_eqb b1 b2 = true <-> b1 = b2).\nProof.\n  destruct b1; destruct b2; simpl; (try intuition congruence);\n  rewrite andb_true_iff;\n    (try rewrite rounded_binop_eqb_eq);\n    (try rewrite (option_eqb_eq rounding_knowledge_eqb_eq));\n    (repeat rewrite Bool.eqb_true_iff);\n  intuition congruence.\nQed.\n\nSection WITHNAN.\nContext {NANS: Nans}.\n\nDefinition fcval_nonrec {ty} (e: expr ty): option (ftype ty) :=\n  match e with\n    | Const _ f => Some f\n    | _ => None\n  end.\n\nLemma fcval_nonrec_correct ty e:\n  forall (v: ftype ty), fcval_nonrec e = Some v ->\n            forall env, fval env e = v.\nProof.\n  destruct e; simpl; try discriminate.\n  intros; congruence.\nQed.\n\nDefinition option_pair_of_options {A B} (a: option A) (b: option B) :=\n  match a, b with\n    | Some a', Some b' => Some (a', b')\n    | _, _ => None\n  end.\n\nLemma option_pair_of_options_correct {A B} (a: option A) (b: option B) a' b':\n  option_pair_of_options a b = Some (a', b') ->\n  a = Some a' /\\ b = Some b'.\nProof.\n  unfold option_pair_of_options.\n  destruct a; destruct b; intuition congruence.\nQed.\n\n(* Partial evaluation of constants *)\n\nFixpoint fcval {ty} (e: expr ty) {struct e}: expr ty :=\n  match e with\n    | Binop b e1 e2 =>\n      let e'1 := fcval e1 in\n      let e'2 := fcval e2 in\n      match option_pair_of_options (fcval_nonrec e'1) (fcval_nonrec e'2) with\n        | Some (v1, v2) =>\n          Const _ (fop_of_binop b _ v1 v2)\n        | None => Binop b e'1 e'2\n      end\n    | Unop b e =>\n      let e' := fcval e in\n      match fcval_nonrec e' with\n        | Some v => Const _ (fop_of_unop b _ v)\n        | _ => Unop b e'\n      end\n    | Func _ ff el =>\n       let fix fcval_klist {tys: list type} (l': klist expr tys) {struct l'}: klist expr tys :=\n          match  l' in (klist _ l) return (klist expr l)\n          with\n          | Knil => Knil\n          | Kcons h tl => Kcons (fcval h) (fcval_klist tl)\n          end \n          in Func _ ff (fcval_klist el)\n    | _ => e\n  end.\n\nFixpoint fcval_klist  {tys: list type} (l': klist expr tys) {struct l'}: klist expr tys :=\n          match  l' in (klist _ l) return (klist expr l)\n          with\n          | Knil => Knil\n          | Kcons h tl => Kcons (fcval h) (fcval_klist tl)\n          end.\n\nLemma fcval_correct_bool env ty (e: expr ty):\n  binary_float_eqb (fval env (fcval e)) (fval env e) = true.\nProof.\n  induction e; simpl.\n  - apply binary_float_eqb_eq. reflexivity.\n  - apply binary_float_eqb_eq. reflexivity.\n  - destruct (option_pair_of_options (fcval_nonrec (fcval e1)) (fcval_nonrec (fcval e2))) eqn:OPT.\n    +\n      destruct p.\n      apply option_pair_of_options_correct in OPT.\n      destruct OPT as (V1 & V2).\n      apply fcval_nonrec_correct with (env := env) in V1.\n      apply fcval_nonrec_correct with (env := env) in V2.\n      simpl.\n      subst.\n      revert IHe1 IHe2.\n      generalize (fval env (fcval e1)).\n      generalize (fval env e1).\n      generalize (fval env (fcval e2)).\n      generalize (fval env e2).\n      intros ? ? ? ? .\n      repeat rewrite binary_float_eqb_eq.\n      congruence.\n    +\n    clear OPT.\n    simpl.\n    revert IHe1 IHe2.\n    generalize (fval env (fcval e1)).\n    generalize (fval env e1).\n    generalize (fval env (fcval e2)).\n    generalize (fval env e2).\n    intros ? ? ? ? .\n    repeat rewrite binary_float_eqb_eq.\n    congruence.\n -\n  destruct (fcval_nonrec (fcval e)) eqn:V_.\n  +\n    apply fcval_nonrec_correct with (env := env) in V_.\n    subst.\n    revert IHe.\n    generalize (fval env (fcval e)).\n    generalize (fval env e).\n    intros ? ? .\n    simpl.\n    repeat rewrite binary_float_eqb_eq.\n    congruence.\n  +\n  simpl.\n  revert IHe.\n  generalize (fval env (fcval e)).\n  generalize (fval env e).\n  intros ? ? .\n  simpl.\n  repeat rewrite binary_float_eqb_eq.\n  congruence.\n-\n    revert IHe.\n    generalize (fval env (fcval e)).\n    generalize (fval env e).\n    intros ? ? .\n    simpl.\n    repeat rewrite binary_float_eqb_eq.\n    congruence.  \n- \n match goal with |- binary_float_eqb _ (?G _ _ _) = _ =>  change G with (@fval_klist _ env (ftype ty)) end.\n\n  set (func := ff_func _). clearbody func.\n  set (tys := ff_args f4) in *. clearbody tys.\n  fold (@fcval_klist tys args).\n rewrite binary_float_eqb_eq.\n  induction args. simpl. reflexivity.\n simpl.\n  apply Kforall_inv in IH. destruct IH.\n  apply binary_float_eqb_eq in H. rewrite H.\n  specialize (IHargs H0). apply IHargs.\nQed.\n\nLemma fcval_correct env ty (e: expr ty):\n  fval env (fcval e) = (fval env e).\nProof.\n  apply binary_float_eqb_eq.\n  apply fcval_correct_bool.\nQed.\n\nImport Qreals.\nOpen Scope R_scope.\n\n(* Identification of shifts *)\nDefinition F2BigQ (beta : Zaux.radix) (f : Defs.float beta) :=\n  match f with\n    | {| Defs.Fnum := Fnum; Defs.Fexp := Fexp |} =>\n      BigQ.mul (BigQ.Qz (BigZ.of_Z Fnum)) (BigQ.power (BigQ.Qz (BigZ.of_Z (Zaux.radix_val beta))) Fexp)\n  end.\n\nLemma Q2R_Qpower_positive p:\n  forall q,\n    Q2R (Qpower_positive q p) = Q2R q ^ Pos.to_nat p.\nProof.\n  induction p.\n  {\n    intros.\n    rewrite Pos2Nat.inj_xI.\n    simpl.\n    repeat rewrite pow_add.\n    simpl.\n    repeat rewrite Q2R_mult.\n    repeat rewrite IHp.\n    ring.\n  }\n  {\n    intros.\n    rewrite Pos2Nat.inj_xO.\n    simpl.\n    repeat rewrite pow_add.\n    simpl.\n    repeat rewrite Q2R_mult.\n    repeat rewrite IHp.\n    ring.\n  }\n  simpl.\n  intros.\n  ring.\nQed.\n\nLemma Q2R_pow q z:\n  ~ q == 0%Q ->\n  Q2R (q ^ z) = powerRZ (Q2R q) z.\nProof.\n  intros.\n  unfold powerRZ, Qpower.\n  destruct z.\n  {\n    unfold Q2R. simpl. field.\n  }\n  {\n    apply Q2R_Qpower_positive.\n  }\n  rewrite Q2R_inv.\n  {\n    f_equal.\n    apply Q2R_Qpower_positive.\n  }\n  apply Qpower.Qpower_not_0_positive.\n  assumption.\nQed.\n\nLemma F2BigQ2R beta f:\n  BigQ2R (F2BigQ beta f) = F2R beta f.\nProof.\n  destruct f; cbn -[BigQ.mul].\n  unfold BigQ2R.\n  rewrite BigQ.spec_mul.\n  rewrite BigQ.spec_power.\n  repeat rewrite to_Q_bigZ.\n  repeat rewrite BigZ.spec_of_Z.\n  rewrite Q2R_mult.\n  rewrite Q2R_pow.\n  {\n    repeat rewrite Q2R_inject_Z.\n    repeat rewrite <- Z2R_IZR.\n    rewrite <- bpow_powerRZ.\n    reflexivity.\n  }\n  replace 0%Q with (inject_Z 0) by reflexivity.\n  rewrite inject_Z_injective.\n  generalize (Zaux.radix_gt_0 beta).\n  lia.\nQed.\n\nDefinition B2BigQ {prec emax} b := F2BigQ _ (@B2F prec emax b).\n\nLemma B2BigQ2R {prec emax} b:\n  Binary.B2R prec emax b = BigQ2R (B2BigQ b).\nProof.\n  unfold B2BigQ.\n  rewrite F2BigQ2R.\n  rewrite B2F_F2R_B2R.\n  rewrite F2R_eq.\n  reflexivity.\nQed.\n\nFixpoint blog (base: bigZ) (accu: nat) (z: bigZ) (fuel: nat) {struct fuel}: nat :=\n  match fuel with\n    | O => O\n    | S fuel' =>\n      if BigZ.eqb z BigZ.one\n      then accu\n      else\n        let '(q, r) := BigZ.div_eucl z base in\n        if BigZ.eqb r BigZ.zero\n        then blog base (S accu) q fuel'\n        else O\n  end.\n\nDefinition to_power_2 {prec emax} (x: Binary.binary_float prec emax) :=\n  let y := B2BigQ x in\n  let '(q, r) := BigZ.div_eucl (Bnum y) (BigZ.Pos (Bden y)) in\n  N.of_nat (blog (BigZ.of_Z 2) O q (Z.to_nat emax))\n.\n\nDefinition to_inv_power_2 {prec emax} (x: Binary.binary_float prec emax) :=\n  let y := BigQ.inv (B2BigQ x) in\n  let '(q, r) := BigZ.div_eucl (Bnum y) (BigZ.Pos (Bden y)) in\n  Pos.of_nat (blog (BigZ.of_Z 2) O q (Z.to_nat emax))\n.\n\nDefinition fshift_mult {ty} (e'1 e'2: expr ty ) :=\n        match fcval_nonrec e'1 with\n          | Some c1 =>\n            if Binary.Bsign _ _ c1 then Binop (Rounded2 MULT None) e'1 e'2\n            else\n            let n := to_power_2 c1 in\n            if binary_float_eqb c1 (B2 ty (Z.of_N n))\n            then Unop (Exact1 (Shift n false)) e'2\n            else\n              let n := to_inv_power_2 c1 in\n              if binary_float_eqb c1 (B2 ty (- Z.pos n))\n              then Unop (Rounded1 (InvShift n false) None) e'2\n              else Binop (Rounded2 MULT None) e'1 e'2\n          | None =>\n            match fcval_nonrec e'2 with\n              | Some c2 =>\n                if Binary.Bsign _ _ c2 then Binop (Rounded2 MULT None) e'1 e'2\n                else\n                let n := to_power_2 c2 in\n                if binary_float_eqb c2 (B2 ty (Z.of_N n))\n                then Unop (Exact1 (Shift n true)) e'1\n                else\n                  let n := to_inv_power_2 c2 in\n                  if binary_float_eqb c2 (B2 ty (- Z.pos n))\n                  then Unop (Rounded1 (InvShift n true) None) e'1\n                  else Binop (Rounded2 MULT None) e'1 e'2\n              | None => Binop (Rounded2 MULT None) e'1 e'2\n            end                  \n        end.\n\nFixpoint fshift {ty} (e: expr ty) {struct e}: expr ty :=\n  match e with\n    | Binop b e1 e2 =>\n      let e'1 := fshift e1 in\n      let e'2 := fshift e2 in\n      if binop_eqb b (Rounded2 MULT None)\n      then fshift_mult e'1 e'2\n      else Binop b e'1 e'2\n    | Unop b e => Unop b (fshift e)\n    | Func _ ff el =>\n       let fix fshift_klist {tys: list type} (l': klist expr tys) {struct l'}: klist expr tys :=\n          match  l' in (klist _ l) return (klist expr l)\n          with\n          | Knil => Knil\n          | Kcons h tl => Kcons (fshift h) (fshift_klist tl)\n          end \n          in Func _ ff (fshift_klist el)\n    | _ => e\n  end.\n\nLemma fshift_correct' env ty (e: expr ty):\n binary_float_eqb (fval env (fshift e)) (fval env e) = true.\nProof.\n  induction e; simpl; unfold fshift_mult.\n- apply binary_float_eqb_eq. reflexivity.\n- apply binary_float_eqb_eq. reflexivity.\n- (* binop case *)\n  assert (DEFAULT:    binary_float_eqb\n         (fval env (Binop b (fshift e1) (fshift e2)))\n         (fop_of_binop b _ (fval env e1) (fval env e2))\n     = true). {\n      revert IHe1 IHe2.\n      simpl.\n      generalize (fval env (fshift e1)).\n      generalize (fval env (fshift e2)).\n      repeat rewrite fshift_type.\n      intros.\n      apply binary_float_eqb_eq in IHe1. subst.\n      apply binary_float_eqb_eq in IHe2. subst.\n      apply binary_float_eqb_eq.\n      reflexivity.\n   }\n  destruct (binop_eqb b (Rounded2 MULT None)) eqn:ISMULT; [ | auto].\n  apply binop_eqb_eq in ISMULT.\n  subst.\n  destruct (fcval_nonrec (fshift e1)) eqn:E1; [ |  destruct (fcval_nonrec (fshift e2)) eqn:E2].\n  +  \n     destruct (Binary.Bsign _ _ _); [ auto | ].\n     destruct (fshift e1); try discriminate.\n     simpl in E1.\n     simpl in f.\n     inversion E1; clear E1; subst.\n     simpl in IHe1.\n     simpl.\n     intros.\n     subst.\n     apply binary_float_eqb_eq in IHe1.\n     subst.\n     match goal with\n       |- binary_float_eqb (fval env (if ?b then _ else _)) _ = _ =>\n          destruct b eqn:FEQ\n     end;\n     simpl.\n   *    revert IHe2.\n          generalize (fval env (fshift e2)).\n          revert FEQ.\n          intros.\n          apply binary_float_eqb_eq in IHe2.\n          subst.\n          apply binary_float_eqb_eq in FEQ.\n          rewrite <- FEQ.\n          apply binary_float_eqb_eq.\n          reflexivity.\n    *\n        clear FEQ.\n        match goal with\n            |- binary_float_eqb (fval env (if ?b then _ else _)) _ = _ =>\n            destruct b eqn:FEQ\n        end;\n          simpl.\n       --\n          revert IHe2.\n          generalize (fval env (fshift e2)).\n          revert FEQ.\n          intros.\n          apply binary_float_eqb_eq in IHe2.\n          subst.\n          apply binary_float_eqb_eq in FEQ.\n          rewrite <- FEQ.\n          apply binary_float_eqb_eq.\n          reflexivity.\n       --\n        clear FEQ.\n        revert IHe2.\n        generalize (fval env (fshift e2)).\n        intros.\n        apply binary_float_eqb_eq in IHe2.\n        subst.\n        apply binary_float_eqb_eq.\n        reflexivity.\n   +\n     destruct (Binary.Bsign _ _ _); [ auto | ].\n     destruct (fshift e2); try discriminate.\n     simpl in E2.\n     simpl in f.\n     inversion E2; clear E2; subst.\n     simpl in IHe2.\n     simpl.\n     intros.\n     subst.\n     apply binary_float_eqb_eq in IHe2.\n     subst.\n     match goal with\n         |- binary_float_eqb (fval env (if ?b then _ else _)) _ = _ =>\n         destruct b eqn:FEQ\n     end;\n       simpl.\n    *    revert IHe1.\n          generalize (fval env (fshift e1)).\n          revert FEQ.\n          intros.\n          apply binary_float_eqb_eq in IHe1.\n          subst.\n          apply binary_float_eqb_eq in FEQ.\n          rewrite <- FEQ.\n          apply binary_float_eqb_eq.\n          reflexivity.\n    *\n        clear FEQ.\n        match goal with\n            |- binary_float_eqb (fval env (if ?b then _ else _)) _ = _ =>\n            destruct b eqn:FEQ\n        end;\n          simpl.\n       --\n          revert IHe1.\n          generalize (fval env (fshift e1)).\n          revert FEQ.\n          intros.\n          apply binary_float_eqb_eq in IHe1.\n          subst.\n          apply binary_float_eqb_eq in FEQ.\n          rewrite <- FEQ.\n          apply binary_float_eqb_eq.\n          reflexivity.\n     --\n        clear FEQ.\n        revert IHe1.\n        generalize (fval env (fshift e1)).\n        intros.\n        apply binary_float_eqb_eq in IHe1.\n        subst.\n        apply binary_float_eqb_eq.\n        reflexivity.\n  +\n      clear E1 E2.\n      revert IHe1 IHe2.\n      simpl.\n      generalize (fval env (fshift e1)).\n      generalize (fval env (fshift e2)).\n      repeat rewrite fshift_type.\n      intros.\n      apply binary_float_eqb_eq in IHe1. subst.\n      apply binary_float_eqb_eq in IHe2. subst.\n      apply binary_float_eqb_eq.\n      reflexivity.\n- (* unop case *)\n  revert IHe.\n  generalize (fval env (fshift e)).\n  intros.\n  apply binary_float_eqb_eq in IHe.\n  subst.\n  apply binary_float_eqb_eq.\n  reflexivity.\n- (* cast case *)\n  revert IHe.\n  generalize (fval env (fshift e)).\n  intros.\n  apply binary_float_eqb_eq in IHe.\n  subst.\n  apply binary_float_eqb_eq.\n  reflexivity.\n-\n  set (func := ff_func _). clearbody func.\n  set (tys := ff_args f4) in *. clearbody tys.\n rewrite binary_float_eqb_eq.\n  induction args. simpl. reflexivity.\n simpl.\n  apply Kforall_inv in IH. destruct IH.\n  apply binary_float_eqb_eq in H. rewrite H.\n  specialize (IHargs H0). apply IHargs.\nQed.\n\nLemma fshift_correct env ty (e: expr ty):\n  fval env (fshift e) =  (fval env e).\nProof.\n  apply binary_float_eqb_eq.\n  apply fshift_correct'.\nQed.\n\nDefinition to_power_2_pos {prec emax} (x: Binary.binary_float prec emax) :=\n  let y := B2BigQ x in\n  let '(q, r) := BigZ.div_eucl (Bnum y) (BigZ.Pos (Bden y)) in\n  Pos.of_nat (blog (BigZ.of_Z 2) O q (Z.to_nat emax))\n.\n\nFixpoint fshift_div {ty} (e: expr ty) {struct e}: expr ty :=\n  match e with\n    | Binop b e1 e2 =>\n      let e'1 := fshift_div e1 in\n      let e'2 := fshift_div e2 in\n      if binop_eqb b (Rounded2 DIV None) then\n      match (fcval_nonrec e'2) with\n            | Some c2 =>\n                match (Bexact_inverse (fprec ty) (femax ty) (fprec_gt_0 ty) (fprec_lt_femax ty) c2) with\n                  | Some z' => \n                    let n1 := to_power_2_pos c2 in\n                    if binary_float_eqb z' (B2 ty (Z.neg n1))\n                    then Unop (Rounded1 (InvShift n1 true) None) e'1\n                    else\n                    let n2 := to_inv_power_2 c2 in\n                    if binary_float_eqb z' (B2 ty (Z.pos n2))\n                    then Unop (Exact1 (Shift (N.of_nat (Pos.to_nat n2)) true)) e'1\n                    else Binop b e'1 e'2\n                  | None => Binop b e'1 e'2\n                end\n             | None => Binop b e'1 e'2\n         end\n      else\n        Binop b e'1 e'2\n    | Unop b e => Unop b (fshift_div e)\n    | Func _ ff el =>\n       let fix fshift_div_klist {tys: list type} (l': klist expr tys) {struct l'}: klist expr tys :=\n          match  l' in (klist _ l) return (klist expr l)\n          with\n          | Knil => Knil\n          | Kcons h tl => Kcons (fshift_div h) (fshift_div_klist tl)\n          end \n          in Func _ ff (fshift_div_klist el)\n    | _ => e\n  end.\n\nFixpoint fshift_div_klist {tys: list type} (l': klist expr tys) {struct l'}: klist expr tys :=\n          match  l' in (klist _ l) return (klist expr l)\n          with\n          | Knil => Knil\n          | Kcons h tl => Kcons (fshift_div h) (fshift_div_klist tl)\n          end.\n\nLocal Lemma binary_float_equiv_refl : forall prec emax x, \n   @binary_float_equiv prec emax x x.\nProof. intros. destruct x; hnf; try reflexivity. repeat split; reflexivity. Qed.\nLocal Hint Resolve binary_float_equiv_refl : vcfloat.\n\nLocal Hint Extern 2 (Binary.is_finite _ _ _ = true) => \n   match goal with EINV: Bexact_inverse _ _ _ _ _ = Some _ |- _ =>\n             apply is_finite_strict_finite; \n         apply (Bexact_inverse_correct _ _ _ _ _ _ EINV)\n   end : vcfloat.\n\nLemma cast_preserves_bf_equiv tfrom tto (b1 b2: Binary.binary_float (fprec tfrom) (femax tfrom)) :\n  binary_float_equiv b1 b2 -> \n  binary_float_equiv (@cast _ tto tfrom b1) (@cast _ tto tfrom b2).\nProof.\nintros.\ndestruct b1, b2; simpl; inversion H; clear H; subst; auto;\ntry solve [apply binary_float_eq_equiv; auto].\n-\nunfold cast; simpl.\ndestruct (type_eq_dec tfrom tto); auto.\nunfold eq_rect.\ndestruct e1.\nreflexivity.\nreflexivity.\n-\ndestruct H1; subst m0 e1.\nunfold cast; simpl.\ndestruct (type_eq_dec tfrom tto); subst; auto.\nunfold eq_rect.\nsimpl. split; auto.\napply binary_float_eq_equiv.\nf_equal.\nQed.\n\nImport Binary.\n\nLemma binary_float_equiv_BDIV ty (b1 b2 b3 b4: binary_float (fprec ty) (femax ty)):\nbinary_float_equiv b1 b2 ->\nbinary_float_equiv b3 b4 ->\nbinary_float_equiv (BDIV b1 b3) (BDIV b2 b4).\nProof.\nintros.\ndestruct b1.\nall : (destruct b3; destruct b4; try contradiction; try discriminate).\nall :\nmatch goal with \n  |- context [\nbinary_float_equiv (BDIV ?a ?b)\n _] =>\nmatch a with \n| B754_nan _ _ _ _ _ => destruct b2; try contradiction; try discriminate;\n    cbv [BDIV BINOP Bdiv build_nan binary_float_equiv]; try reflexivity\n  | _ => apply binary_float_equiv_eq in H; try rewrite <- H;\n  match b with \n  | B754_nan _ _ _ _ _ => \n      cbv [BDIV BINOP Bdiv build_nan binary_float_equiv]; try reflexivity\n  | _ => apply binary_float_equiv_eq in H0; try rewrite <- H0;\n          try apply binary_float_eq_equiv; try reflexivity\nend\nend\nend.\nQed.\n\nLemma binary_float_equiv_BOP ty (b1 b2 b3 b4: binary_float (fprec ty) (femax ty)):\nforall b: binop ,\nbinary_float_equiv b1 b2 ->\nbinary_float_equiv b3 b4 ->\nbinary_float_equiv (fop_of_binop b ty b1 b3) (fop_of_binop b ty b2 b4).\nProof.\nintros.\ndestruct b1.\nall :\nmatch goal with \n  |- context [\nbinary_float_equiv (fop_of_binop ?bo ?ty ?a ?b)\n _] =>\nmatch a with \n| B754_zero _ _ _ => \napply binary_float_equiv_eq in H; try simpl; try reflexivity\n| B754_infinity _ _ _ => \napply binary_float_equiv_eq in H; try simpl; try reflexivity\n| B754_finite _ _ _ _ _ _ => \napply binary_float_equiv_eq in H; try simpl; try reflexivity\n| _ => try simpl\nend\nend.\nall :(\ndestruct b2; simpl in H; try contradiction; try discriminate;\ndestruct b3; destruct b4; try contradiction; try discriminate;\nmatch goal with \n  |- context [ binary_float_equiv (fop_of_binop ?bo ?ty ?a ?b)  _] =>\nmatch a with \n| B754_nan _ _ _ _ _  => try simpl\n| _ => try (rewrite H); \n      match b with \n      | B754_nan _ _ _ _ _ => try simpl\n      | _ => try (apply binary_float_equiv_eq in H);\n             try (rewrite H);\n             try (apply binary_float_equiv_eq in H0);\n             try (rewrite H0);\n             try (apply binary_float_eq_equiv); try reflexivity\n      end\nend\nend\n).\n\nall: (\ntry (destruct b);\ntry( cbv [fop_of_binop]);\ntry destruct op;\ntry (cbv [fop_of_rounded_binop]);\ntry (cbv [fop_of_rounded_binop]);\ntry(\nmatch goal with \n|- context [ binary_float_equiv ((if ?m then ?op1 else ?op2)  ?ty ?a ?b) _] =>\ndestruct m\nend;\ncbv [BPLUS BMINUS BDIV BMULT BINOP \nBplus Bminus Bdiv Bmult build_nan binary_float_equiv]);\ntry (reflexivity)\n).\nQed.\n\nLemma binary_float_equiv_UOP ty (b1 b2: binary_float (fprec ty) (femax ty)):\nforall u: unop ,\nbinary_float_equiv b1 b2 ->\nbinary_float_equiv (fop_of_unop u ty b1) (fop_of_unop u ty b2).\nProof.\nintros.\ndestruct b1.\nall: (\nmatch goal with |- context [binary_float_equiv \n(fop_of_unop ?u ?ty ?a) _]  =>\nmatch a with \n| Binary.B754_nan _ _ _ _ _  => simpl \n| _ => try apply binary_float_equiv_eq in H; try rewrite  <-H; \n  try apply binary_float_eq_equiv; try reflexivity\nend\nend).\ndestruct b2; try discriminate; try contradiction.\ntry (destruct u).\nall: (\ntry( cbv [fop_of_unop fop_of_exact_unop]);\ntry destruct op;\ntry destruct o;\ntry destruct ltr;\ntry (cbv [fop_of_rounded_unop]);\ntry (cbv [Bsqrt Binary.Bsqrt build_nan]);\ntry reflexivity\n).\n+ destruct (B2 ty (- Z.pos pow)) .\nall: try (\n (cbv [ BMULT BINOP Bmult build_nan]);\n reflexivity).\n+ destruct (B2 ty (Z.of_N pow)).\nall: try (\n (cbv [ BMULT BINOP Bmult build_nan]);\n reflexivity).\nQed.\n\n\nLocal Hint Resolve cast_preserves_bf_equiv : vcfloat.\nLocal Hint Resolve binary_float_eq_equiv : vcfloat.\nLocal Ltac inv  H := inversion H; clear H; subst.\n\nLemma general_eqb_neq:\n  forall {A} {f: A -> A -> bool} (H: forall x y, f x y = true <-> x=y),\n    forall x y,  f x y = false <-> x<>y.\nProof.\nintros.\nrewrite <- H.\ndestruct (f x y); split; congruence.\nQed.\n\nLocal Ltac destruct_ifb H := \n    lazymatch type of H with\n    | forall x y, ?f x y = true <-> x=y =>\n         match goal with |- context [if f ?b ?c then _ else _] =>\n                  let FEQ := fresh \"FEQ\" in \n                     destruct (f b c) eqn:FEQ; \n             [apply H in FEQ; rewrite FEQ in *\n             | apply (general_eqb_neq H) in FEQ]\n         end\n    | _ => fail \"argument of destruct_ifb must be a lemma of the form,  forall x y, ?f x y = true <-> x=y\"\n    end.\n\nLocal Lemma ifb_cases_lem: \n  forall {A} {f: A -> A -> bool} (H: forall x y, f x y = true <-> x=y),\n  forall (x y: A) {B} (b c: B) (P: B -> Prop),\n  (x=y -> P b) -> (x<>y -> P c) ->\n  P (if f x y then b else c).\nProof.\nintros.\ndestruct (f x y) eqn:?H.\napply H in H2; auto.\napply (general_eqb_neq H) in H2; auto.\nQed.\n\nLocal Lemma binary_float_eqb_lem1:\n  forall prec emax b c {A} (y z: A) (P: A -> Prop) ,\n    (b=c -> P y) -> P z ->\n    P (if @binary_float_eqb prec emax prec emax b c then y else z).\nProof.\nintros.\n destruct (binary_float_eqb b c) eqn:H1.\n apply H. apply binary_float_eqb_eq. auto. auto.\nQed.\n\nLocal Ltac binary_float_eqb_cases := \n  let H := fresh in \n  apply binary_float_eqb_lem1; [intro H; rewrite H in *; clear H | ].\n\nLocal Lemma Bmult_div_inverse_equiv ty:\n  forall x y z: (Binary.binary_float (fprec ty) (femax ty)),\n  Binary.is_finite _ _ y = true ->\n  Binary.is_finite _ _ z = true ->\n  Bexact_inverse (fprec ty) (femax ty) (fprec_gt_0 ty) (fprec_lt_femax ty) y = Some z -> \n  binary_float_equiv\n  (Binary.Bmult _ _ _ (fprec_lt_femax ty) (mult_nan ty) BinarySingleNaN.mode_NE x z) \n  (Binary.Bdiv _ _ _ (fprec_lt_femax ty) (div_nan ty) BinarySingleNaN.mode_NE x y) .\nProof. intros. apply binary_float_equiv_sym; apply Bdiv_mult_inverse_equiv; auto. Qed.\n\nTheorem Bmult_div_inverse_equiv2 ty:\n  forall x1 x2 y z: (Binary.binary_float (fprec ty) (femax ty)),\n  binary_float_equiv x1 x2 ->\n  Binary.is_finite _ _ y = true ->\n  Binary.is_finite _ _ z = true ->\n  Bexact_inverse (fprec ty) (femax ty) (fprec_gt_0 ty) (fprec_lt_femax ty) y = Some z -> \n  binary_float_equiv\n  (Binary.Bmult _ _ _ (fprec_lt_femax ty) (mult_nan ty) BinarySingleNaN.mode_NE x2 z)\n  (Binary.Bdiv _ _ _ (fprec_lt_femax ty) (div_nan ty) BinarySingleNaN.mode_NE x1 y) .\nProof. intros. apply binary_float_equiv_sym; apply Bdiv_mult_inverse_equiv2; auto. Qed.\n\nLemma uncast_finite_strict:\n  forall t t2 f, Binary.is_finite_strict (fprec t) (femax t) (@cast _ t t2 f) = true ->\n        Binary.is_finite_strict _ _ f = true.\nProof.\nintros.\nunfold cast in H.\ndestruct (type_eq_dec t2 t).\nsubst. \ndestruct f; simpl in *; auto.\ndestruct f; simpl in *; auto.\nQed.\n\nLemma is_finite_strict_not_nan:\n  forall prec emax f, Binary.is_finite_strict prec emax f = true -> Binary.is_nan prec emax f = false.\nProof.\nintros.\ndestruct f; auto; discriminate.\nQed.\n\nLemma binary_float_equiv_nan:\n  forall prec emax f1 f2,\n  Binary.is_nan prec emax f1= true  ->\n   Binary.is_nan prec emax f2 = true ->\n    binary_float_equiv f1 f2.\nProof.\nintros.\ndestruct f1; inv H.\ndestruct f2; inv H0.\napply I.\nQed.\n\nLemma binary_float_equiv_nan1:\n  forall b prec emax f1 f2,\n  Binary.is_nan prec emax f1= b  ->\n    binary_float_equiv f1 f2 ->\n   Binary.is_nan prec emax f2 = b.\nProof.\nintros.\ndestruct b.\ndestruct f1; inv H.\ndestruct f2; inv H0.\nreflexivity.\ndestruct f1; inv H;\ndestruct f2; inv H0;\nreflexivity.\nQed.\n\nLemma binary_float_equiv_nan2:\n  forall b prec emax f1 f2,\n  Binary.is_nan prec emax f2= b  ->\n    binary_float_equiv f1 f2 ->\n   Binary.is_nan prec emax f1 = b.\nProof.\nintros.\ndestruct b.\ndestruct f2; inv H.\ndestruct f1; inv H0.\nreflexivity.\ndestruct f2; inv H;\ndestruct f1; inv H0;\nreflexivity.\nQed.\n\nLemma Bmult_nan1:\n  forall fprec emax H H0 H1 H2 f1 f2,\n   Binary.is_nan fprec emax f1 = true -> Binary.is_nan _ _  (Binary.Bmult _ _ H H0 H1 H2 f1 f2) = true.\nProof.\nintros.\ndestruct f1; try discriminate. reflexivity.\nQed.\n\nLemma Bmult_nan2:\n  forall fprec emax H H0 H1 H2 f1 f2,\n   Binary.is_nan fprec emax f2 = true -> Binary.is_nan _ _  (Binary.Bmult _ _ H H0 H1 H2 f1 f2) = true.\nProof.\nintros. \ndestruct f2; try discriminate.\ndestruct f1; reflexivity.\nQed.\n\nLemma Bdiv_nan1:\n  forall fprec emax H H0 H1 H2 f1 f2,\n   Binary.is_nan fprec emax f1 = true -> Binary.is_nan _ _  (Binary.Bdiv _ _ H H0 H1 H2 f1 f2) = true.\nProof.\nintros.\ndestruct f1; try discriminate. reflexivity.\nQed.\n\nLemma Bdiv_nan2:\n  forall fprec emax H H0 H1 H2 f1 f2,\n   Binary.is_nan fprec emax f2 = true -> Binary.is_nan _ _  (Binary.Bdiv _ _ H H0 H1 H2 f1 f2) = true.\nProof.\nintros. \ndestruct f2; try discriminate.\ndestruct f1; reflexivity.\nQed.\n\nLocal Hint Resolve Bmult_nan1 Bmult_nan2 Bdiv_nan1 Bdiv_nan2 cast_is_nan : vcfloat.\n\nLtac unfold_fval := cbv [fop_of_unop fop_of_exact_unop fop_of_rounded_unop\n                      fop_of_binop fop_of_rounded_binop \n                      BDIV BMULT BINOP BPLUS BMINUS].\n\nLtac binary_float_equiv_tac :=\n      repeat (first [ apply Bmult_div_inverse_equiv\n                          | apply Bmult_div_inverse_equiv2\n                          | apply cast_preserves_bf_equiv;\n                               (assumption || apply binary_float_equiv_sym; assumption)\n                          | apply binary_float_equiv_BDIV\n                          | apply binary_float_equiv_BOP];\n                   auto with vcfloat).\n\nLtac binary_float_equiv_tac2 env e1 e2 :=\n         simpl;\n         repeat match goal with\n                    | H: binary_float_equiv _ _ |- _ => revert H \n                    end;\n         generalize (fval env (fshift_div  e1));\n         generalize (fval env (fshift_div  e2));\n         intros;\n         binary_float_equiv_tac.\n\nLemma fshift_div_correct' env ty (e: expr ty) :\n binary_float_equiv (fval env (fshift_div e))  (fval env e).\nProof.\ninduction e; cbn [fshift_div]; auto with vcfloat; unfold fval; fold (@fval _ env ty);\ntry (set (x1 := fval env e1) in *; clearbody x1);\ntry (set (x2 := fval env e2) in *; clearbody x2).\n- (* binop case *)\n apply (ifb_cases_lem binop_eqb_eq); intros ?OP; subst;\n               [ | binary_float_equiv_tac2 env e1 e2].\n destruct (fcval_nonrec (fshift_div e2)) eqn:E2;\n               [ | binary_float_equiv_tac2 env e1 e2].\n destruct (fshift_div e2); try discriminate.\n simpl in *|-. inv E2.\n simpl in IHe2; intros; subst.\n destruct (Bexact_inverse _ ) eqn:EINV; [ | clear EINV];\n               [ | binary_float_equiv_tac2 env e1 e2]. \n assert (H := proj1 (Bexact_inverse_correct _ _ _ _ _ _ EINV)).\n destruct f; inversion H; clear H.\n rewrite positive_nat_N.\n destruct (fcval_nonrec (fshift_div e1)) eqn:E1.\n + destruct (fshift_div e1); try discriminate.\n     simpl in f, E1, IHe1; inv E1.\n     intros.\n     destruct (Binary.is_nan _ _ f) eqn:?NAN.\n    * pose proof (binary_float_equiv_nan1 true _ _ _ _ NAN IHe1).\n       apply binary_float_equiv_nan; repeat binary_float_eqb_cases;\n       unfold fval; unfold_fval; auto with vcfloat.\n    * apply binary_float_equiv_eq in IHe1; [ subst | assumption].\n       apply binary_float_equiv_eq in IHe2; [ subst | reflexivity ].\n       repeat binary_float_eqb_cases;\n       binary_float_equiv_tac.\n+ repeat binary_float_eqb_cases; [ .. | clear EINV];\n    simpl;\n    try (apply binary_float_equiv_eq in IHe2; [subst x2 | reflexivity]);\n    try revert EINV;\n    revert IHe1;\n    generalize (fval env (fshift_div e1));\n    intros;\n    (destruct (Binary.is_nan _ _ f) eqn:?NAN;\n       [pose proof (binary_float_equiv_nan1 true _ _ _ _ NAN IHe1);\n        unfold fval; fold (@fval _ env ty); unfold_fval;\n        apply binary_float_equiv_nan; auto with vcfloat\n      | apply binary_float_equiv_eq in IHe1; [ subst | assumption ];\n        binary_float_equiv_tac; pose (y:=True)\n     ]).\n- (* unop case *)\n simpl.\nrevert IHe.\ngeneralize (fval env (fshift_div e)).\nintros.\napply binary_float_equiv_UOP; apply IHe.\n-\n  set (func := ff_func _). clearbody func.\n  set (tys := ff_args f4) in *. clearbody tys.\n  fold @fshift_div_klist.\n match goal with |- binary_float_equiv (?G _ _ _) _ =>  change G with (@fval_klist _ env (ftype ty)) end.\n  induction args. simpl. apply binary_float_equiv_refl.\n simpl.\n  apply Kforall_inv in IH. destruct IH.\n  specialize (IHargs H0).\n  simpl in func.\n  specialize (IHargs (func (fval env k))).\n  eapply binary_float_equiv_trans; [ | apply IHargs].\n  admit.  (* This looks OK but will take some work.  Perhaps use the Morphism congruence\n                 system for binary_float_equiv; or (maybe) base this whole thing on binary_float_eqb\n               instead of binary_float_equiv? *)\nAdmitted.\n\nLemma fshift_div_correct env ty (e: expr ty):\n  Binary.is_nan _ _ (fval env (fshift_div e)) = false -> \n  fval env (fshift_div e) = fval env e.\nProof.\n  intros.\n  apply binary_float_equiv_eq. \n  - apply fshift_div_correct'.\n  - apply H. \nQed.\n\nDefinition is_zero_expr (env: forall ty, FPLang.V -> ftype ty) {ty} (e: expr ty)\n : bool :=  \nmatch (fval env e) with\n| Binary.B754_zero _ _ b1 => true\n| _ => false\nend.\n\n(* Erasure of rounding annotations *)\n\nFixpoint erase {ty} (e: expr ty) {struct e}: expr ty :=\n  match e with\n    | Binop (Rounded2 u k) e1 e2 => Binop (Rounded2 u None) (erase e1) (erase e2)\n    | Binop SterbenzMinus e1 e2 => Binop (Rounded2 MINUS None) (erase e1) (erase e2)\n    | Binop (PlusZero minus_ _) e1 e2 => Binop (Rounded2 (if minus_ then MINUS else PLUS) None) (erase e1) (erase e2)\n    | Unop (Rounded1 u k) e => Unop (Rounded1 u None) (erase e)\n    | Cast _ u _ e => Cast _ u None (erase e)\n    | Unop u e => Unop u (erase e)\n    | Func _ ff args => \n       let fix erase_klist {tys: list type} (l': klist expr tys) {struct l'}: klist expr tys :=\n          match  l' in (klist _ l) return (klist expr l)\n          with\n          | Knil => Knil\n          | Kcons h tl => Kcons (erase h) (erase_klist tl)\n          end \n       in Func _ ff (erase_klist args)\n    | _ => e\n  end.\n\nFixpoint erase_klist  {tys: list type} (l': klist expr tys) {struct l'}: klist expr tys :=\n          match  l' in (klist _ l) return (klist expr l)\n          with\n          | Knil => Knil\n          | Kcons h tl => Kcons (erase h) (erase_klist tl)\n          end.\n\nLemma erase_correct' env ty (e: expr ty):\n binary_float_eqb (fval env (erase e)) (fval env e) = true.\nProof.\n  induction e; simpl.\n  - apply binary_float_eqb_eq; reflexivity.\n  - apply binary_float_eqb_eq; reflexivity.\n  - revert IHe1.\n    revert IHe2.\n    generalize (fval env e1).\n    generalize (fval env e2).\n    destruct b; simpl;\n      generalize (fval env (erase e1));\n      generalize (fval env (erase e2));\n      repeat rewrite erase_type;\n      intros until 2;\n      apply binary_float_eqb_eq in IHe1; subst;\n      apply binary_float_eqb_eq in IHe2; subst;\n      apply binary_float_eqb_eq;\n      try reflexivity.\n    destruct minus; reflexivity.\n  -\n  revert IHe.\n  generalize (fval env e).\n  destruct u; simpl;\n  generalize (fval env (erase e));\n  intros until 1;\n  apply binary_float_eqb_eq in IHe; subst;\n  apply binary_float_eqb_eq;\n  reflexivity.\n- \n  revert IHe.\n  generalize (fval env e).\n  generalize (fval env (erase e));\n  intros until 1;\n  apply binary_float_eqb_eq in IHe; subst;\n  apply binary_float_eqb_eq;\n  reflexivity.\n-\n  set (func := ff_func _). clearbody func.\n  set (tys := ff_args f4) in *. clearbody tys.\n  fold @erase_klist.\n match goal with |- binary_float_eqb (?G _ _ _) _ = true =>  change G with (@fval_klist _ env (ftype ty)) end.\n  induction args. simpl. apply binary_float_eqb_eq. reflexivity.\n simpl.\n  apply Kforall_inv in IH. destruct IH.\n  specialize (IHargs H0).\n  specialize (IHargs (func (fval env k))).\n  apply binary_float_eqb_eq in IHargs.  \n  apply binary_float_eqb_eq.\n  rewrite <- IHargs. f_equal.\n  apply binary_float_eqb_eq in H. rewrite H. auto.\nQed.\n\nLemma erase_correct env ty (e: expr ty):\n  fval env (erase e) = fval env e.\nProof.\n  apply binary_float_eqb_eq.\n  apply erase_correct'.\nQed.\n\nEnd WITHNAN.\n", "meta": {"author": "VeriNum", "repo": "vcfloat", "sha": "9cad8c4b48fe4353d01f02f6dc5bd03e1ea4eb5c", "save_path": "github-repos/coq/VeriNum-vcfloat", "path": "github-repos/coq/VeriNum-vcfloat/vcfloat-9cad8c4b48fe4353d01f02f6dc5bd03e1ea4eb5c/vcfloat/FPLangOpt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.25674050566027795}}
{"text": "From RecoveryRefinement Require Import Lib.\nRequire Import Spec.HoareTactics.\n\nRequire Import Examples.Logging.Impl.\nRequire Import Examples.Logging.LogLayout.\nRequire Import Examples.Logging.LogicalLog.\n\nLocal Notation proc_rspec := (Hoare.proc_rspec D.ODLayer.(sem)).\nLocal Arguments Hoare.proc_rspec {Op State} sem {T R}.\n\nDefinition logical_abstraction (d: D.State) ps ls :=\n  PhyDecode d ps /\\\n  LogDecode ps ls /\\\n  ls.(ls_committed) = false.\n\nLocal Hint Resolve recovery_ok : core.\nLocal Hint Resolve log_apply_spec_idempotent_notxn' : core.\nLocal Hint Resolve log_apply_spec_idempotent' : core.\n\nDefinition general_rspec ls0 T (p_hspec: Specification T unit D.State) :=\n  proc_hspec_to_rspec\n    (sem:=D.ODLayer.(sem))\n    (p_hspec:=p_hspec)\n    (rec_hspec:=fun (a: Recghost (fun ls =>\n                                  if ls.(ls_committed) then\n                                    massign ls.(ls_log) ls.(ls_disk) =\n                                    massign ls0.(ls_log) ls0.(ls_disk)\n                                  else ls.(ls_disk) = ls0.(ls_disk) \\/\n                                       ls.(ls_disk) = massign ls0.(ls_log) ls0.(ls_disk))) =>\n                  let 'recghost ps ls _ := a in\n                  log_apply_spec ps ls ls.(ls_disk) ls.(ls_committed)).\n\n\nDefinition mk_rspec ls0 T (p_hspec: Specification T unit D.State) :=\n  proc_hspec_to_rspec\n    (sem:=D.ODLayer.(sem))\n    (p_hspec:=p_hspec)\n    (rec_hspec:=fun (a: Recghost (fun ls => ls.(ls_disk) = ls0.(ls_disk))) =>\n                  let 'recghost ps ls _ := a in\n                  log_apply_spec ps ls ls.(ls_disk) false).\n\nLocal Hint Resolve log_read_ok : core.\n\nTheorem log_read_rec_ok ps ls a :\n  proc_rspec\n    (log_read a)\n    (recovery)\n    (fun state =>\n       {| pre := logical_abstraction state ps ls;\n          post state' r :=\n            state' = state /\\\n            index ls.(ls_disk) a ?|= eq r;\n          alternate state' r :=\n            exists ps',\n              logical_abstraction\n                state' ps'\n                {| ls_committed := false;\n                   ls_log := nil;\n                   ls_disk := ls.(ls_disk); |}\n       |}).\nProof.\n  eapply mk_rspec; eauto; simpl in *; propositional;\n    repeat match goal with\n           | [ x: Recghost _ |- _ ] => destruct x\n           end;\n    eauto.\n  - eexists (recghost _ _ _); simpl; intuition eauto.\n  - simpl in H0; propositional.\n    unfold logical_abstraction.\n    descend; intuition eauto.\n    rewrite <- pf.\n    eassumption.\n\n    Unshelve.\n    simpl; auto.\nQed.\n\nLocal Hint Resolve log_write_ok : core.\n\nTheorem log_write_rec_ok ps ls a v :\n  proc_rspec\n    (log_write a v)\n    (recovery)\n    (fun state =>\n       {| pre := logical_abstraction state ps ls;\n          post state' r :=\n            exists ps',\n              match r with\n              | TxnD.WriteOK =>\n                logical_abstraction\n                  state' ps'\n                  {| ls_committed := false;\n                     ls_log := ls.(ls_log) ++ (a,v)::nil;\n                     ls_disk := ls.(ls_disk); |}\n              | TxnD.WriteErr =>\n                logical_abstraction\n                  state' ps'\n                  {| ls_committed := false;\n                     ls_log := ls.(ls_log);\n                     ls_disk := ls.(ls_disk); |}\n              end;\n          alternate state' r :=\n            exists ps',\n              logical_abstraction state' ps'\n                                  {| ls_committed := false;\n                                     ls_log := nil;\n                                     ls_disk := ls.(ls_disk) |};\n       |}).\nProof.\n  eapply mk_rspec; eauto; simpl in *; propositional;\n    repeat match goal with\n           | [ x: Recghost _ |- _ ] => destruct x\n           end;\n    eauto.\n  - unfold logical_abstraction in *; intuition eauto.\n    destruct v0; propositional; descend; intuition eauto.\n    destruct ls; simpl in *; congruence.\n  - inv_clear H1.\n    eexists (recghost _ _ _); simpl; intuition eauto.\n  - simpl in H0; propositional.\n    unfold logical_abstraction.\n    descend; intuition eauto.\n    rewrite <- pf; eassumption.\n\n    Unshelve.\n    simpl; auto.\nQed.\n\nLocal Hint Resolve log_commit_ok : core.\n\nTheorem log_commit_rec_ok ps ls :\n  proc_rspec\n    (commit)\n    (recovery)\n    (fun state =>\n       {| pre := logical_abstraction state ps ls;\n          post state' r :=\n            exists ps',\n              logical_abstraction\n                state' ps'\n                {| ls_committed := false;\n                   ls_log := nil;\n                   ls_disk := massign ls.(ls_log) ls.(ls_disk) |};\n          alternate state' r :=\n            exists ps',\n              logical_abstraction\n                state' ps'\n                {| ls_committed := false;\n                   ls_log := nil;\n                   ls_disk := ls.(ls_disk) |} \\/\n              logical_abstraction\n                state' ps'\n                {| ls_committed := false;\n                   ls_log := nil;\n                   ls_disk := massign ls.(ls_log) ls.(ls_disk) |};\n       |}).\nProof.\n  eapply general_rspec; eauto; simpl; propositional.\n  - destruct a; eauto.\n  - unfold logical_abstraction in *; intuition eauto.\n    propositional.\n    descend; intuition eauto.\n    destruct ls'; simpl in *; congruence.\n  - split_cases;\n      lazymatch goal with\n      | [ H: PhyDecode state' ?ps,\n             H': LogDecode ?ps ?ls |- _ ] =>\n        unshelve eexists (recghost ps ls _); simpl; eauto\n      end.\n  - destruct a; simpl in *; propositional.\n    exists ps'.\n    destruct_with_eqn (ls0.(ls_committed));\n      unfold logical_abstraction in *; simpl; propositional.\n    + right; split_cases; finish.\n    + split_cases.\n      * left; split_cases; finish.\n      * right; split_cases; finish.\nQed.\n\nLocal Hint Resolve log_size_ok : core.\n\nTheorem log_size_rec_ok ps ls :\n  proc_rspec\n    (log_size)\n    (recovery)\n    (fun state =>\n       {| pre := logical_abstraction state ps ls;\n          post state' r :=\n            r = length ls.(ls_disk) /\\\n            state' = state;\n          alternate state' r :=\n            exists ps',\n              logical_abstraction\n                state' ps'\n                {| ls_committed := false;\n                   ls_log := nil;\n                   ls_disk := ls.(ls_disk) |};\n       |}).\nProof.\n  eapply mk_rspec; eauto; simpl in *; propositional;\n    repeat match goal with\n           | [ x: Recghost _ |- _ ] => destruct x\n           end;\n    eauto.\n  - eexists (recghost _ _ _); simpl; intuition eauto.\n  - simpl in H0; propositional.\n    unfold logical_abstraction.\n    descend; intuition eauto.\n    rewrite <- pf; eassumption.\n\n    Unshelve.\n    simpl; auto.\nQed.\n\nLocal Hint Resolve recovery_ok : core.\n\nTheorem recovery_rec_ok ps ls :\n  proc_rspec\n    (recovery)\n    (recovery)\n    (fun state =>\n       {| pre := logical_abstraction state ps ls;\n          post state' _ :=\n            exists ps,\n              logical_abstraction\n                state' ps\n                {| ls_committed := false;\n                   ls_log := nil;\n                   ls_disk := ls.(ls_disk) |};\n          alternate state' _ :=\n            exists ps,\n              logical_abstraction\n                state' ps\n                {| ls_committed := false;\n                   ls_log := nil;\n                   ls_disk := ls.(ls_disk) |};\n       |}).\nProof.\n  eapply mk_rspec; simpl; intros;\n    repeat match goal with\n           | [ x: Recghost _ |- _ ] => destruct x\n           end.\n  - eapply (recovery_ok ps ls false).\n  - unfold logical_abstraction in *; simplify; intuition eauto.\n  - eauto.\n  - simpl; unfold logical_abstraction in *; simplify; intuition eauto.\n  - simpl in *; propositional.\n    lazymatch goal with\n    | [ H: PhyDecode state' ?ps,\n           H': LogDecode ?ps ?ls |- _ ] =>\n      unshelve eexists (recghost ps ls _); simpl; eauto\n    end.\n  - unfold logical_abstraction; simpl in *; propositional.\n    exists ps'; intuition eauto.\n    congruence.\nQed.\n\nDefinition abstraction (txnd: TxnD.State) (d: D.State) (u: unit) : Prop :=\n  exists ps ls,\n    logical_abstraction d ps ls /\\\n    txnd = (ls.(ls_disk), massign ls.(ls_log) ls.(ls_disk)).\n\nNotation proc_refines p spec :=\n  (forall txnd, proc_rspec p recovery (refine_spec abstraction spec txnd))\n    (only parsing).\n\nLtac rspec_impl :=\n  eapply proc_rspec_impl;\n  [ unfold spec_impl | solve [ eauto ] ];\n  simpl; propositional.\n\nLocal Hint Resolve log_read_rec_ok : core.\n\nLtac destruct_txnd :=\n  let t H :=\n      (let d_old := fresh \"d_old\" in\n       let d := fresh \"d\" in\n       destruct H as [d_old d]) in\n  repeat match goal with\n         | [ H: TxnD.State |- _ ] => t H\n         | [ H: TxnD.l.(State) |- _ ] => t H\n         end.\n\nTheorem log_read_abs_ok a :\n  proc_refines (log_read a)\n               (fun '(d_old, d) =>\n                  {| pre := True;\n                     post '(d_old', d') r :=\n                       d_old' = d_old /\\\n                       d' = d /\\\n                       index d_old a ?|= eq r;\n                     alternate '(d_old', d') _ :=\n                       d_old' = d_old /\\\n                       d' = d_old; |}).\nProof.\n  unfold refine_spec, abstraction;\n    intros; destruct_txnd; intros.\n  spec_intros; simpl in *; simplify.\n  rspec_impl; (intuition eauto); simplify.\n  - eexists (_, _); intuition eauto.\n  - eexists (_, _); intuition eauto.\nQed.\n\nLocal Hint Resolve log_write_rec_ok : core.\n\nTheorem log_write_abs_ok a v :\n  proc_refines (log_write a v)\n               (fun '(d_old, d) =>\n                  {| pre := True;\n                     post '(d_old', d') r :=\n                       d_old' = d_old /\\\n                       match r with\n                       | TxnD.WriteOK =>\n                         d' = assign d a v\n                       | TxnD.WriteErr =>\n                         d' = d\n                       end;\n                     alternate '(d_old', d') _ :=\n                       d_old' = d_old /\\\n                       d' = d_old; |}).\nProof.\n  unfold refine_spec, abstraction;\n    intros; destruct_txnd; intros.\n  spec_intros; simpl in *; simplify.\n  rspec_impl; (intuition eauto); simplify.\n  - destruct v0.\n    + eexists (_, _); (intuition eauto); simpl.\n      array.\n    + eexists (_, _); (intuition eauto); simpl.\n  - eexists (_, _); (intuition eauto); simpl.\nQed.\n\nLocal Hint Resolve log_size_rec_ok : core.\n\nTheorem log_size_abs_ok :\n  proc_refines (log_size)\n               (fun '(d_old, d) =>\n                  {| pre := True;\n                     post '(d_old', d') r :=\n                       d_old' = d_old /\\\n                       d' = d /\\\n                       r = length d;\n                     alternate '(d_old', d') _ :=\n                       d_old' = d_old /\\\n                       d' = d_old; |}).\nProof.\n  unfold refine_spec, abstraction;\n    intros; destruct_txnd; intros.\n  spec_intros; simpl in *; simplify.\n  rspec_impl; (intuition eauto); simplify.\n  - eexists (_, _); intuition eauto.\n    array.\n  - eexists (_, _); intuition eauto.\nQed.\n\nLocal Hint Resolve log_commit_rec_ok : core.\n\nTheorem log_commit_abs_ok :\n  proc_refines (commit)\n               (fun '(d_old, d) =>\n                  {| pre := True;\n                     post '(d_old', d') r :=\n                       r = tt /\\\n                       d_old' = d /\\\n                       d' = d;\n                     alternate '(d_old', d') _ :=\n                       (d_old' = d_old /\\\n                        d' = d_old) \\/\n                       (d_old' = d /\\\n                        d' = d); |}).\nProof.\n  unfold refine_spec, abstraction;\n    intros; destruct_txnd; intros.\n  spec_intros; simpl in *; simplify.\n  rspec_impl; (intuition eauto); simplify; split_cases.\n  - eexists (_, _); intuition eauto.\n  - eexists (_, _); intuition eauto.\n  - eexists (_, _); intuition eauto.\nQed.\n\nLocal Hint Resolve recovery_rec_ok : core.\n\nTheorem recovery_abs_ok :\n  proc_refines (recovery)\n               (fun '(d_old, d) =>\n                  {| pre := True;\n                     post '(d_old', d') r :=\n                       r = tt /\\\n                       d_old' = d_old /\\\n                       d' = d_old;\n                     alternate '(d_old', d') _ :=\n                       d_old' = d_old /\\\n                       d' = d_old; |}).\nProof.\n  unfold refine_spec, abstraction;\n    intros; destruct_txnd; intros.\n  spec_intros; simpl in *; simplify.\n  rspec_impl; (intuition eauto); simplify.\n  - eexists (_, _); intuition eauto.\n  - eexists (_, _); intuition eauto.\nQed.\n\nModule LoggingRefinement.\n\n  Definition Impl: LayerImpl D.Op TxnD.Op :=\n    {| compile_op := fun (T : Type) (op : TxnD.Op T) =>\n                       match op with\n                       | TxnD.op_read a => log_read a\n                       | TxnD.op_write a b => log_write a b\n                       | TxnD.op_commit => commit\n                       | TxnD.op_size => log_size\n                       end;\n       init := log_init;\n       Layer.recover := recovery |}.\n\n  Lemma l_compile_refines :\n    compile_op_refines_step D.ODLayer TxnD.l Impl abstraction.\n  Proof.\n    unfold compile_op_refines_step; intros.\n    destruct op; cbn [Impl compile_op recover].\n    - eapply proc_rspec_crash_refines_op; intros;\n        eauto using log_commit_abs_ok; destruct_txnd; simpl in *; simplify; finish.\n      { constructor. }\n      split_cases; eauto.\n      right.\n      exists (d0, d0), tt; simpl.\n      eauto using TxnD.op_step.\n    - eapply proc_rspec_crash_refines_op; intros;\n        eauto using log_read_abs_ok; destruct_txnd; simpl in *; simplify; finish.\n      constructor.\n      destruct_with_eqn (index d_old0 a); simpl in *; eauto.\n    - eapply proc_rspec_crash_refines_op; intros;\n        eauto using log_write_abs_ok; destruct_txnd; simpl in *; simplify; finish.\n      destruct v; subst; constructor; auto.\n    - eapply proc_rspec_crash_refines_op; intros;\n        eauto using log_size_abs_ok; destruct_txnd; simpl in *; simplify; finish.\n      constructor.\n  Qed.\n\n  Lemma l_recovery_refines_crash:\n    recovery_refines_crash_step D.ODLayer TxnD.l Impl abstraction.\n  Proof.\n    unfold recovery_refines_crash_step.\n    eapply proc_rspec_recovery_refines_crash_step.\n    - intros; eapply recovery_abs_ok.\n    - intros; destruct_txnd; simpl in *.\n      inv_clear H0; (intuition eauto); simpl; eauto.\n    - intros; destruct_txnd; simpl in *.\n      inv_clear H0.\n      split_cases; destruct_txnd; propositional.\n      eexists (_, _); simpl; eauto.\n  Qed.\n\n  Import RelationNotations.\n\n  Lemma  l_init_ok :\n    _ <- test D.ODLayer.(initP); exec D.ODLayer Impl.(init)\n                                                                  --->\n                                                                  (_ <- any (T:=unit); _ <- test TxnD.l.(initP); _ <- abstraction; pure Initialized) +\n                                      (_ <- any (T:=unit); pure InitFailed).\n  Proof.\n    eapply proc_hspec_init_ok; unfold abstraction.\n    + eapply log_init_ok.\n    + simplify.\n    + simplify.\n      eexists (ls.(ls_disk), ls.(ls_disk)); simpl; intuition eauto.\n      unfold logical_abstraction; descend; intuition eauto.\n      f_equal.\n      rewrite H2; simpl; auto.\n  Qed.\n\n  Lemma rf : LayerRefinement D.ODLayer TxnD.l.\n  Proof.\n    unshelve (econstructor).\n    - exact Impl.\n    - exact abstraction.\n    - exact l_compile_refines.\n    - exact l_recovery_refines_crash.\n    - exact l_init_ok.\n  Defined.\n\nEnd LoggingRefinement.\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/HoareProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.4148988457967689, "lm_q1q2_score": 0.2567312877619474}}
{"text": "Require Import include_frm.\nRequire Import sep_auto.\nRequire Import math_auto.\n\nImport DeprecatedTactic.\n\nSet Implicit Arguments.\n\n(* separation line *)\n\n\nLemma map_get_join_val :\n  forall  (x y z: mem) t b v, \n    join x y z ->\n    HalfPermMap.get x t = Some (b, v) ->\n    exists b, HalfPermMap.get z t = Some (b, v).\nProof.\n  intros.\n  unfold join in H.\n  unfold memMap in H.\n  unfold HalfPermMap.join in H.\n  unfold HalfPermMap.disjoint in H.\n  unfold HalfPermMap.merge in H.\n  destruct H.\n  rewrite H1.\n  unfold HalfPermMap.get in *.\n  lets aa: H t.\n  rewrite H0 in *.\n  destruct b.\n  destruct (y t).\n  inversion aa.\n  eauto.\n  destruct (y t).\n  destruct b.\n  destruct b.\n  inversion aa.\n  inverts aa.\n  unfold HalfPermMap.rjoin.\n  2:eauto.\n  destruct (HalfPermMap.dec_C c c ).\n  eauto.\n  eauto.\nQed.\n\n\nLemma loadbytes_mono: \n  forall m M m' l n v ,  \n    join m M m' -> \n    loadbytes m l n = Some v ->\n    loadbytes m' l n = loadbytes m l n.\nProof.\n  intros.\n  generalize dependent l.\n  generalize dependent v.\n  induction n.\n  intros.\n  simpl.\n  auto.\n  intros.\n  destruct l.\n  simpl.\n  simpl in H0.\n  change (match get m (b, o) with\n               | Some (_, u) =>\n                 match loadbytes m (b, (o + 1)%Z) n with\n                   | Some bl => Some (u :: bl)\n                   | None => None\n                 end\n               | None => None\n             end\n         ) with ((fun x =>    match x with\n                                | Some (_, u) =>\n                                  match loadbytes m (b, (o + 1)%Z) n with\n                                    | Some bl => Some (u :: bl)\n                                    | None => None\n                                  end\n                                | None => None\n                              end\n                 ) (get m (b,o))) in *.\n\n  remember (get m ( b, o)) as bb.\n  unfold get in Heqbb.\n  simpl in Heqbb.\n  assert (HalfPermMap.get m (b,o) = bb).\n  auto.\n  destruct bb.\n  destruct p.\n  lets ff: map_get_join_val H.\n  apply ff in H1.\n  unfold HalfPermMap.get in Heqbb.\n  mytac.\n  unfold get.\n  simpl.\n  rewrite H1.\n  remember (   loadbytes m (b, (o + 1)%Z) ).\n  rewrite Heqo0.\n  remember (o0 n).\n  assert ((exists bl, o1 = Some bl) \\/ o1 = None).\n  destruct o1.\n  left; eauto.\n  right; auto.\n  destruct H2; intros.\n  destruct H2.\n  erewrite IHn.\n  auto.\n  rewrite <- Heqo0.\n  rewrite <- Heqo1.\n  eauto.\n  rewrite H2 in H0.\n  inversion H0.\n  inversion H0.\nQed.\n\n\nLemma ptomvallist_loadbytes : \n  forall l vl m perm, \n    ptomvallist l perm  vl m -> \n    loadbytes m l (length vl) = Some vl.\nProof.\n  intros.\n  gen l m H.\n  inductions vl; intros.\n  simpl.\n  auto.\n  simpl.\n  destruct l.\n  simpl in H.\n  do 3 destruct H.\n  destruct H0.\n  apply IHvl in H1.\n  clear IHvl.\n  unfolds in H0.\n  pose proof loadbytes_mono.\n  pose proof (H2 x0 x m (b, (o + 1)%Z) (length vl) vl).\n  clear H2.\n  apply map_join_comm in H.\n  pose proof (H3 H H1).\n  clear H3.\n  rewrite <- H2 in H1.\n  clear H2.\n  rewrite H1.\n  subst.\n  apply map_join_comm in H.\n  lets fff:  map_get_join_val H (map_get_sig (b,o) (perm, a)).\n  destruct fff.\n  unfold get.\n  simpl.\n  rewrite H0.\n  auto.\nQed.\n\nOpen Scope nat_scope.\n\nLemma type_val_mach_encode_val_decode_val : \n  forall t v, rule_type_val_match t v =true -> \n              decode_val t (encode_val t v) = v.\nProof.\n  intros.\n  destruct t; destruct v; simpl in H; tryfalse; simpl; auto.\n\n  unfolds.\n  simpl.\n  destruct ((Int.unsigned i <=? Byte.max_unsigned)%Z) eqn : eq1; tryfalse.\n  replace (Byte.unsigned (Byte.repr (Int.unsigned i)) + 0)%Z with (Byte.unsigned (Byte.repr (Int.unsigned i))).\n  pose proof Int.unsigned_range i.\n  destruct H0.\n  rewrite Z.leb_le in eq1.\n  rewrite Byte.unsigned_repr.\n  rewrite Int.repr_unsigned.\n  assert (Int.zero_ext 8 i = i).\n  pose proof Int.zero_ext_mod 8 i.\n  assert ((0 <= 8 < Int.zwordsize)%Z).\n  unfold Int.zwordsize.\n  unfold Int.wordsize.\n  unfold Wordsize_32.wordsize.\n  simpl.\n  omega.\n  apply H2 in H3; clear H2.\n  rewrite Coqlib.Zmod_small in H3.\n  assert (Int.repr (Int.unsigned (Int.zero_ext 8 i)) = Int.repr (Int.unsigned i)).\n  rewrite H3.\n  auto.\n  rewrite Int.repr_unsigned in H2.\n  rewrite Int.repr_unsigned in H2.\n  auto.\n  unfold Byte.max_unsigned in eq1.\n  unfold Byte.modulus in eq1.\n  unfold Byte.wordsize in eq1.\n  unfold Wordsize_8.wordsize in eq1.\n  unfold two_power_nat in eq1.\n  unfold two_p.\n  unfold two_power_pos.\n  rewrite shift_pos_nat.\n  assert (Pos.to_nat 8 = 8).\n  auto.\n  rewrite H2.\n  omega.\n  rewrite H2.\n  auto.\n  omega.\n  omega.\n\n  unfolds.\n  simpl.\n  destruct ((Int.unsigned i <=? Int16.max_unsigned)%Z) eqn : eq1; tryfalse.\n  replace (Byte.unsigned (Byte.repr (Int.unsigned i / 256)) + 0)%Z with (Byte.unsigned (Byte.repr (Int.unsigned i / 256))).\n  pose proof Int.unsigned_range i.\n  destruct H0.\n  rewrite Z.leb_le in eq1.\n  replace (Byte.unsigned (Byte.repr (Int.unsigned i / 256))) with (Int.unsigned i / 256)%Z.\n  replace (Byte.unsigned (Byte.repr (Int.unsigned i))) with ((Int.unsigned i) mod Byte.modulus)%Z.\n  rewrite Z.add_comm.\n  unfold Byte.modulus.\n  unfold Byte.wordsize.\n  unfold Wordsize_8.wordsize.\n  unfold two_power_nat.\n  unfold shift_nat.\n  simpl.\n  rewrite Z.mul_comm.\n  rewrite <- Z.div_mod.\n  rewrite Int.repr_unsigned.\n  assert (Int.zero_ext 16 i = i).\n  pose proof Int.zero_ext_mod 16 i.\n  assert ((0 <= 16 < Int.zwordsize)%Z).\n  unfold Int.zwordsize.\n  unfold Int.wordsize.\n  unfold Wordsize_32.wordsize.\n  simpl.\n  omega.\n  apply H2 in H3; clear H2.\n  rewrite Coqlib.Zmod_small in H3.\n  assert (Int.repr (Int.unsigned (Int.zero_ext 16 i)) = Int.repr (Int.unsigned i)).\n  rewrite H3.\n  auto.\n  rewrite Int.repr_unsigned in H2.\n  rewrite Int.repr_unsigned in H2.\n  auto.\n  unfold Int16.max_unsigned in eq1.\n  unfold Int16.modulus in eq1.\n  unfold Int16.wordsize in eq1.\n  unfold Wordsize_16.wordsize in eq1.\n  unfold two_power_nat in eq1.\n  unfold two_p.\n  unfold two_power_pos.\n  rewrite shift_pos_nat.\n  assert (Pos.to_nat 16 = 16).\n  auto.\n  rewrite H2.\n  omega.\n  rewrite H2.\n  auto.\n  omega.\n  rewrite <- Byte.unsigned_repr_eq.\n  auto.\n  rewrite Byte.unsigned_repr.\n  auto.\n  unfold Byte.max_unsigned.\n  unfold Byte.modulus.\n  simpl.\n  unfold Int16.max_unsigned in eq1.\n  unfold Int16.modulus in eq1.\n  simpl in eq1.\n  split.\n  apply Z.div_pos.\n  auto.\n  omega.\n  assert (255 = 65535 / 256)%Z.\n  compute.\n  auto.\n  rewrite H2.\n  assert (256 > 0)%Z.\n  omega.\n  pose proof Z_div_le (Int.unsigned i) 65535 256 H3 eq1.\n  auto.\n  omega.\n\n  unfolds.\n  simpl.\n  replace (Byte.unsigned (Byte.repr (Int.unsigned i / 256 / 256 / 256)) + 0)%Z with (Byte.unsigned (Byte.repr (Int.unsigned i / 256 / 256 / 256))).\n  pose proof Int.unsigned_range i.\n  destruct H0.\n  replace (Byte.unsigned (Byte.repr (Int.unsigned i / 256 / 256 / 256))) with (Int.unsigned i / 256 / 256 / 256)%Z.\n  replace (Byte.unsigned (Byte.repr (Int.unsigned i))) with (Int.unsigned i mod Byte.modulus)%Z.\n  replace (Byte.unsigned (Byte.repr (Int.unsigned i / 256))) with (Int.unsigned i / 256 mod Byte.modulus)%Z.\n  replace (Byte.unsigned (Byte.repr (Int.unsigned i / 256 / 256))) with (Int.unsigned i / 256 / 256 mod Byte.modulus)%Z.\n  rewrite Z.add_comm.\n  unfold Byte.modulus.\n  unfold Byte.wordsize.\n  unfold Wordsize_8.wordsize.\n  unfold two_power_nat.\n  unfold shift_nat.\n  simpl.\n  assert (((Int.unsigned i / 256 / 256) mod 256 + Int.unsigned i / 256 / 256 / 256 * 256) =\n          (Int.unsigned i / 256 / 256))%Z.\n  rewrite Z.add_comm.\n  rewrite Z.mul_comm.\n  rewrite <- Z_div_mod_eq.\n  auto.\n  omega.\n  rewrite H2.\n  assert (((Int.unsigned i / 256) mod 256 + Int.unsigned i / 256 / 256 * 256) = (Int.unsigned i / 256))%Z.\n  rewrite Z.add_comm.\n  rewrite Z.mul_comm.\n  rewrite <- Z_div_mod_eq.\n  auto.\n  omega.\n  rewrite H3.\n  assert ((Int.unsigned i mod 256 + Int.unsigned i / 256 * 256) = Int.unsigned i)%Z.\n  rewrite Z.add_comm.\n  rewrite Z.mul_comm.\n  rewrite <- Z_div_mod_eq.\n  auto.\n  omega.\n  rewrite Z.add_comm.\n  rewrite H4.\n  rewrite Int.repr_unsigned.\n  auto.\n  rewrite Byte.unsigned_repr_eq.\n  auto.\n  rewrite Byte.unsigned_repr_eq.\n  auto.\n  rewrite Byte.unsigned_repr_eq.\n  auto.\n  rewrite Byte.unsigned_repr_eq.\n  rewrite Coqlib.Zmod_small.\n  auto.\n  split.\n  apply Z.div_pos.\n  apply Z.div_pos.\n  apply Z.div_pos.\n  auto.\n  omega.\n  omega.\n  omega.\n  unfold Int.modulus in H1.\n  unfold Int.wordsize in H1.\n  unfold Wordsize_32.wordsize in H1.\n  unfold two_power_nat in H1.\n  unfold shift_nat in H1.\n  simpl in H1.\n  unfold Byte.modulus.\n  unfold two_power_nat.\n  unfold shift_nat.\n  simpl.\n  apply Zdiv_lt_upper_bound.\n  omega.\n  apply Zdiv_lt_upper_bound.\n  omega.\n  apply Zdiv_lt_upper_bound.\n  omega.\n  simpl.\n  auto.\n  omega.\n\n  unfolds.\n  destruct a.\n  simpl.\n  unfold Coqlib.proj_sumbool.\n  rewrite Coqlib.peq_true.\n  destruct (Int.eq_dec i i) eqn : eq1.\n  simpl.\n  auto.\n  false.\n\n  unfolds.\n  destruct a.\n  simpl.\n  unfold Coqlib.proj_sumbool.\n  rewrite Coqlib.peq_true.\n  destruct (Int.eq_dec i0 i0) eqn : eq1.\n  simpl.\n  auto.\n  false.\nQed.\n\n\nLemma mapstoval_loadbytes: \n  forall b i t v m perm, \n    rule_type_val_match t v = true -> \n    mapstoval (b,i) t perm v m -> \n    exists bls, loadbytes m (b,i) (typelen t) = Some bls /\\ (decode_val t bls = v).\nProof.\n  intros.\n  unfolds in H0.\n  destruct H0.\n  destruct H0.\n  substs.\n  apply ptomvallist_loadbytes in H1.\n  rewrite encode_val_length in H1.\n  exists (encode_val t v).\n  split.\n  auto.\n\n  apply type_val_mach_encode_val_decode_val.\n  auto.\nQed.\n\nLemma loadm_mono : \nforall m M m' t l v,  \n   join m M m' ->\n   loadm t m l = Some v -> \n   loadm t m' l = loadm t m l .\nProof.\n  intros.\n  destruct l.\n  simpl in *.\n  remember (loadbytes m (b, o) (typelen t)) as bb.\n  destruct bb.\n  symmetry in Heqbb.\n  assert (loadbytes m' (b, o) (typelen t) = Some l).\n  erewrite loadbytes_mono;eauto.\n  rewrite H1.\n  auto.\n  inversion H0.\nQed.\n\nLemma load_mono: forall m M m' t l v,  join m M m' ->\n                                       load t m l = Some v -> load t m' l = load t m l .\nProof.\n  unfold load;intros;destruct t;try eapply loadm_mono;eauto.\nQed.\n\nLemma load_local:\n  forall m t l v m1 m2, join m1 m2 m ->\n                        load t m1 l = Some v ->\n                        load t m l = Some v.\nProof.\n  intros.\n  erewrite load_mono;eauto.\nQed.\n\nLemma mapstoval_load: \n  forall l t v m perm, rule_type_val_match t v = true -> mapstoval l t perm v m -> load t m l = Some v.\nProof.\n  intros.\n  unfold load.\n  destruct l.\n  destruct t;simpl in H;tryfalse;unfold loadm.\n\n  pose proof @mapstoval_loadbytes b o Tnull v m perm H H0.\n  destruct H1.\n  destruct H1.\n  rewrite H1.\n  rewrite H2.\n  auto.\n\n  pose proof @mapstoval_loadbytes b o Tint8 v m perm H H0.\n  destruct H1.\n  destruct H1.\n  rewrite H1.\n  rewrite H2.\n  auto.\n\n  pose proof @mapstoval_loadbytes b o Tint16 v m perm H H0.\n  destruct H1.\n  destruct H1.\n  rewrite H1.\n  rewrite H2.\n  auto.\n\n  pose proof @mapstoval_loadbytes b o Tint32 v m perm H H0.\n  destruct H1.\n  destruct H1.\n  rewrite H1.\n  rewrite H2.\n  auto.\n\n  pose proof @mapstoval_loadbytes b o (Tptr t) v m perm H H0.\n  destruct H1.\n  destruct H1.\n  rewrite H1.\n  rewrite H2.\n  auto.\n\n  pose proof @mapstoval_loadbytes b o (Tcom_ptr i) v m perm H H0.\n  destruct H1.\n  destruct H1.\n  rewrite H1.\n  rewrite H2.\n  auto.\nQed.\n\n\nLemma mapstoval_load_vptr : \n  forall l tp v v' m perm, \n    (forall t n,tp<> Tarray t n) -> \n    mapstoval l tp perm (Vptr v)  m -> \n    load tp m l = Some (Vptr v') -> v = v'.\nProof.\n  introv Hx.\n  intros.\n  apply mapstoval_load in H.\n  rewrite H in H0.\n  inv H0.\n  auto.\n  unfolds in H.\n  destruct H.\n  destruct H.\n  unfolds in H0.\n  destruct l.\n  unfold loadm in H0.\n  destruct tp.\n\n  destruct ( loadbytes m (b, o) (typelen Tnull)) eqn : eq1; tryfalse.\n  inv H0.\n  unfolds in H3.\n  destruct (proj_bytes l).\n  tryfalse.\n  destruct l; tryfalse; simpl; auto.\n  repeat (destruct m0; tryfalse;\n          destruct l; tryfalse).\n\n\n  destruct ( loadbytes m (b, o) (typelen Tvoid)) eqn : eq1; tryfalse.\n  inv H0.\n  unfolds in H3.\n  destruct (proj_bytes l).\n  tryfalse.\n  destruct l; tryfalse; simpl; auto.\n  repeat (destruct m0; tryfalse;\n          destruct l; tryfalse).\n\n\n  destruct ( loadbytes m (b, o) (typelen Tint8)) eqn : eq1; tryfalse.\n  inv H0.\n  unfolds in H3.\n  destruct (proj_bytes l).\n  tryfalse.\n  destruct l; tryfalse; simpl; auto.\n  repeat (destruct m0; tryfalse;\n          destruct l; tryfalse).\n\n\n\n  destruct ( loadbytes m (b, o) (typelen Tint16)) eqn : eq1; tryfalse.\n  inv H0.\n  unfolds in H3.\n  destruct (proj_bytes l).\n  tryfalse.\n  destruct l; tryfalse; simpl; auto.\n  repeat (destruct m0; tryfalse;\n          destruct l; tryfalse).\n\n\n  destruct ( loadbytes m (b, o) (typelen Tint32)) eqn : eq1; tryfalse.\n  inv H0.\n  unfolds in H3.\n  destruct (proj_bytes l).\n  tryfalse.\n  destruct l; tryfalse; simpl; auto.\n  repeat (destruct m0; tryfalse;\n          destruct l; tryfalse).\n\n\n  destruct ( loadbytes m (b, o) (typelen (Tptr tp))) eqn : eq1; tryfalse.\n  inv H0.\n  unfolds in H3.\n  destruct (proj_bytes l).\n  tryfalse.\n  destruct l; tryfalse; simpl; auto.\n  repeat (destruct m0; tryfalse;\n          destruct l; tryfalse).\n\n  lets Ha:Hx Tvoid 0.\n  tryfalse.\n\n\n  destruct ( loadbytes m (b, o) (typelen (Tcom_ptr i))) eqn : eq1; tryfalse.\n  inv H0.\n  unfolds in H3.\n  destruct (proj_bytes l).\n  tryfalse.\n  destruct l; tryfalse; simpl; auto.\n  repeat (destruct m0; tryfalse;\n          destruct l; tryfalse).\n\n  lets Ha:Hx Tvoid 0.\n  tryfalse.\n\n  destruct ( loadbytes m (b, o) (typelen (Tstruct i d))) eqn : eq1; tryfalse.\n  inv H0.\n  unfolds in H3.\n  destruct (proj_bytes l).\n  tryfalse.\n  destruct l; tryfalse; simpl; auto.\n  repeat (destruct m0; tryfalse;\n          destruct l; tryfalse).\n\nQed.\n\n(*\nLemma nindom_get : forall (a : env) x, ~indom a x -> get a x = None.\nProof.\n  intros.\n  unfold indom in H.\n  simpl in H.\n  unfold EnvMod.indom in H.\n  unfold get.\n  simpl.\n  destruct (EnvMod.get a x).\n  false.\n  apply H.\n  eauto.\n  auto.\nQed.\n *)\n\nLemma loadbytes_local: forall m1 m2 m bls b i t, join m1 m2 m -> loadbytes m1 (b,i) (typelen t) = Some bls -> loadbytes m (b,i) (typelen t) = Some bls.\nProof.\n  intros.\n  rewrite <- H0.\n  eapply loadbytes_mono.\n  eauto.\n  eauto.\nQed.\n\n(* separation line *)\n\nLemma nth_id_some_in_decllist_true : forall n dls id, nth_id n dls = Some id -> in_decllist id dls = true.\nProof.\n  intro.\n  induction n; intros.\n  destruct dls; simpl in H; tryfalse.\n  inversion H.\n  substs.\n  simpl.\n  apply Bool.orb_true_iff.\n  left.\n  apply Zbool.Zeq_is_eq_bool.\n  auto.\n  destruct dls; simpl in H; tryfalse.\n  simpl.\n  apply Bool.orb_true_iff.\n  right.\n  eapply IHn.\n  auto.\nQed.\n\nLemma in_decllist_field_offsetfld_some : forall dls id, in_decllist id dls = true -> forall n, exists off, field_offsetfld id dls n = Some off.\nProof.\n  intro.\n  induction dls; intros.\n  simpl in H.\n  inversion H.\n  simpl in H.\n  apply Bool.orb_true_iff in H.\n  destruct H.\n  apply Zbool.Zeq_is_eq_bool in H.\n  substs.\n  eexists.\n  simpl.\n  assert (Zbool.Zeq_bool i i = true).\n  apply Zbool.Zeq_is_eq_bool.\n  auto.\n  rewrite H.\n  auto.\n  simpl.\n  destruct (Zbool.Zeq_bool id i).\n  eauto.\n  eapply IHdls.\n  auto.\nQed.\n\nLemma field_offsetfld_pos_mono : forall dls id pos1 off1,\n                                   field_offsetfld id dls pos1 = Some off1\n                                   -> forall pos2 off2, field_offsetfld id dls pos2 = Some off2\n                                                        -> forall n, Int.add n pos1 = pos2\n                                                                     -> Int.add n off1 = off2.\nProof.\n  intro.\n  induction dls; intros.\n  simpl in H.\n  inversion H.\n  simpl in H.\n  simpl in H0.\n  destruct (Zbool.Zeq_bool id i).\n  inversion H.\n  inversion H0.\n  substs.\n  auto.\n  eapply IHdls.\n  apply H.\n  apply H0.\n  substs.\n  rewrite Int.add_commut.\n  rewrite Int.add_assoc.\n  replace (Int.add pos1 n) with (Int.add n pos1).\n  auto.\n  apply Int.add_commut.\nQed.\n\nLemma nth_id_field_offsetfld_some : forall decl n id, nth_id n decl = Some id -> forall pos, exists off, field_offsetfld id decl pos = Some off.\nProof.\n  intros.\n  apply nth_id_some_in_decllist_true in H.\n  apply in_decllist_field_offsetfld_some.\n  auto.\nQed.\n\n\nLemma nth_id_exists_off: forall decl n id, nth_id n decl = Some id -> exists off, field_offset id decl = Some off.\nProof.\n  intro.\n  destruct decl; intros.\n  simpl in H.\n  inversion H.\n  destruct n.\n  inversion H.\n  unfold field_offset.\n  simpl.\n  simpl in H.\n  assert (Zbool.Zeq_bool id id = true).\n  apply Zbool.Zeq_is_eq_bool.\n  auto.\n  rewrite H0.\n  eauto.\n  simpl in H.\n  unfold field_offset.\n  simpl.\n  destruct ( Zbool.Zeq_bool id i).\n  eauto.\n  eapply nth_id_field_offsetfld_some.\n  eauto.\nQed.\n\n\nLemma field_asrt_impl: \n  forall p id x tid decl b i off tp perm, \n    ftype id decl = Some tp ->\n    field_offset id decl = Some off -> \n    ((LV x @ Tptr (Tstruct tid decl) |=> Vptr (b, i) @ perm) ** p) ==> (Lv (efield (ederef (evar x)) id) @ tp == (b,Int.add i off)).\nProof.\n  intros.\n  unfold sat.\n  destruct  s as [[]].\n  destruct t as [[[[]]]].\n  unfold sat in H1;fold sat in H1;mytac.\n  simpl in H5;mytac.\n  simpl.\n  rewrite H8.\n  apply mapstoval_loadbytes in H9.\n  destruct H9 as (bls&H9).\n  destruct H9.\n  simpl in H2.\n  lets Hl:loadbytes_local H2 H1.\n  rewrite Int.unsigned_zero in Hl.\n  assert (loadbytes m (x11, BinNums.Z0) (typelen (Tptr (Tstruct tid decl))) = Some bls).\n  auto.\n  unfold load.\n  unfold loadm.\n  rewrite H4.\n  rewrite H3.\n  unfold getoff.\n  simpl.\n  rewrite H8.\n  rewrite H0.\n  rewrite Int.repr_unsigned.\n  auto.\n  simpl;auto.\n  simpl.\n  simpl in H5;mytac.\n  rewrite H8.\n  auto.\nQed.\n\nLemma field_asrt_impl_g: \n  forall p id x tid decl b i off tp perm, \n    ftype id decl = Some tp ->\n    field_offset id decl = Some off -> \n    ((A_notin_lenv x ** GV x @ Tptr (Tstruct tid decl) |=> Vptr (b, i) @ perm) ** p) ==> (Lv (efield (ederef (evar x)) id) @ tp == (b,Int.add i off)).\nProof.\n  intros.\n  unfold sat.\n  destruct  s as [[]].\n  destruct t as [[[[]]]].\n  unfold sat in H1;fold sat in H1;mytac.\n  simpl in *;mytac.\n  rewrite H11.\n  apply (EnvMod.nindom_get )in H10.\n  change (  (fun xxx => match\n                 match\n                   match xxx with\n                     | Some (_, t) => Some t\n                     | None => Some (Tptr (Tstruct tid decl))\n                   end\n                 with\n                   | Some _ =>\n                     match xxx with\n                       | Some (a0, t0) => load t0 m (a0, 0%Z)\n                       | None => load (Tptr (Tstruct tid decl)) m (x15, 0%Z)\n                     end\n                   | None => None\n                 end\n               with\n                 | Some Vundef => None\n                 | Some Vnull => None\n                 | Some (Vint32 _) => None\n                 | Some (Vptr (b0, i1)) =>\n                   match getoff b0 (Int.unsigned i1) id (ederef (evar x)) (e, e0, m) with\n                     | Some ad => Some (Vptr ad)\n                     | None => None\n                   end\n                 | None => None\n               end = Some (Vptr (b, Int.add i off))\n            ) (get e0 x) ).\n  rewrite H10.\n  apply mapstoval_loadbytes in H13.\n  destruct H13 as (bls&H13).\n  destruct H13.\n  simpl in H2.\n  lets Hl:loadbytes_local H2 H1.\n  rewrite Int.unsigned_zero in Hl.\n  assert (loadbytes m (x15, BinNums.Z0) (typelen (Tptr (Tstruct tid decl))) = Some bls).\n  auto.\n  unfold load;unfold loadm.\n  rewrite H4.\n  rewrite H3.\n  unfold getoff.\n  simpl.\n  change ( ( fun xxx =>\n               match\n                 match\n                   match\n                     match xxx with\n                       | Some (_, t) => Some t\n                       | None =>\n                         match get e x with\n                           | Some (_, t) => Some t\n                           | None => None\n                         end\n                     end\n                   with\n                     | Some Tnull => None\n                     | Some Tvoid => None\n                     | Some Tint8 => None\n                     | Some Tint16 => None\n                     | Some Tint32 => None\n                     | Some (Tptr t) => Some t\n                     | Some (Tcom_ptr _) => None\n                     | Some (Tarray _ _) => None\n                     | Some (Tstruct _ _) => None\n                     | None => None\n                   end\n                 with\n                   | Some Tnull => None\n                   | Some Tvoid => None\n                   | Some Tint8 => None\n                   | Some Tint16 => None\n                   | Some Tint32 => None\n                   | Some (Tptr _) => None\n                   | Some (Tcom_ptr _) => None\n                   | Some (Tarray _ _) => None\n                   | Some (Tstruct _ dl) =>\n                     match field_offset id dl with\n                       | Some off0 => Some (b, Int.add (Int.repr (Int.unsigned i)) off0)\n                       | None => None\n                     end\n                   | None => None\n                 end\n               with\n                 | Some ad => Some (Vptr ad)\n                 | None => None\n               end = Some (Vptr (b, Int.add i off))\n           ) (get e0 x) ).\n  rewrite H10.\n  rewrite H11.\n  rewrite Int.repr_unsigned.\n  auto.\n  simpl.\n  rewrite H0.\n  auto.\n  simpl;auto.\n  simpl in *;mytac.\n  apply EnvMod.nindom_get in H10.\n  change ( (fun xxx =>    match\n                match\n                  match xxx with\n                    | Some (_, t) => Some t\n                    | None =>\n                      match get e x with\n                        | Some (_, t) => Some t\n                        | None => None\n                      end\n                  end\n                with\n                  | Some Tnull => None\n                  | Some Tvoid => None\n                  | Some Tint8 => None\n                  | Some Tint16 => None\n                  | Some Tint32 => None\n                  | Some (Tptr t) => Some t\n                  | Some (Tcom_ptr _) => None\n                  | Some (Tarray _ _) => None\n                  | Some (Tstruct _ _) => None\n                  | None => None\n                end\n              with\n                | Some Tnull => None\n                | Some Tvoid => None\n                | Some Tint8 => None\n                | Some Tint16 => None\n                | Some Tint32 => None\n                | Some (Tptr _) => None\n                | Some (Tcom_ptr _) => None\n                | Some (Tarray _ _) => None\n                | Some (Tstruct _ dl) => ftype id dl\n                | None => None\n              end = Some tp\n           ) (get e0 x) ).\n  rewrite H10.\n  rewrite H11.\n  auto.\nQed.\nLemma nth_id_Some_imply_in_decllist :\n  forall n id dls,\n    nth_id n dls = Some id ->\n    in_decllist id dls = true.\nProof.\n  intros.\n  gen n id.\n  induction dls;intros.\n  inverts H.\n  destruct n;tryfalse.\n  simpl in *.\n  inverts H.\n  apply Bool.orb_true_intro.\n  left.\n  apply Zbool.Zeq_is_eq_bool.\n  auto.\n  simpl in *.\n  apply Bool.orb_true_intro.\n  right.\n  eapply IHdls.\n  eauto.\nQed.\n\nLemma gooddecl_neq: \n  forall i t dls n id,\n    good_decllist (dcons i t dls)=true -> nth_id n dls = Some id -> \n    Zbool.Zeq_bool id i = false.\nProof.\n  intros.\n  simpl in H.\n  apply andb_prop in H.\n  destruct H.\n  remember (Zbool.Zeq_bool id i) as b.\n  destruct b.\n  symmetry in Heqb.\n  apply Zbool.Zeq_bool_eq in Heqb.\n  inverts Heqb.\n  apply nth_id_Some_imply_in_decllist in H0.\n  rewrite H0 in H.\n  tryfalse.\n  auto.\nQed.\n\n\nLemma struct_rm_update_eq:\n  forall s b i decl vl id v vi n,\n    good_decllist decl =true -> nth_id n decl = Some id -> nth_val n vl = Some vi -> s |= Astruct_rm (b,i) decl vl id -> s |= Astruct_rm (b,i) decl (update_nth_val n vl v) id.\nProof.\n  intros.\n  generalize dependent s.\n  generalize dependent b.\n  generalize dependent i.\n  generalize dependent vi.\n  generalize dependent n.\n  generalize dependent vl.\n  generalize dependent id.\n  generalize dependent v.\n  induction decl.\n  intros.\n  destruct n;tryfalse.\n  intros.\n  destruct vl.\n  destruct n;tryfalse.\n  destruct n.\n  simpl.\n  simpl in H.\n  inverts H.\n  simpl in H0;inverts H0.\n  assert (Zbool.Zeq_bool id id=true).\n  apply Zbool.Zeq_is_eq_bool;auto.\n  rewrite H.\n  simpl in H1.\n  inverts H1.\n  simpl in H2.\n  rewrite H in H2.\n  auto.\n  simpl.\n  assert (Zbool.Zeq_bool id i = false).\n  eapply gooddecl_neq;eauto.\n  rewrite H3.\n  simpl in H2.\n  rewrite H3 in H2.\n  inverts H0.\n  inverts H1.\n  destruct t;sep_auto;\n  simpl in H;\n  apply Bool.andb_true_iff  in H;\n  destruct H;\n  lets IH: IHdecl H0;clear IHdecl;\n  lets IH':IH H5 H4;\n  eapply IH' in H2;eauto.\nQed.\n\nLemma array_rm_update_eq': forall s b i vl v vi n m t,  m < n -> nth_val m vl = Some vi -> s |= Aarray_rm (b,i) n t (update_nth_val m vl v) m  -> s |= Aarray_rm (b,i) n t vl m.\nProof.\n  intros.\n  generalize dependent s.\n  generalize dependent b.\n  generalize dependent i.\n  generalize dependent vi.\n  generalize dependent n.\n  generalize dependent vl.\n  generalize dependent v.\n  induction m.\n  intros.\n  destruct vl;tryfalse.\n  simpl in H0;inverts H0.\n  simpl in *.\n  auto.\n  intros.\n  destruct n;tryfalse.\n  omega.\n  destruct vl;tryfalse.\n  simpl in H0.\n  assert (m<n).\n  omega.\n  unfold Aarray_rm;fold Aarray_rm.\n  lets IH:IHm H2 H0.\n  unfold update_nth_val in H1;fold update_nth_val in H1.\n  unfold Aarray_rm in H1;fold Aarray_rm in H1.\n  sep_auto.\n  apply IH.\n  eauto.\nQed.\n(*\nLemma arrayelem_asrt_impl_g: \n  forall n m p p' b i t e2 x te2, \n    te2 = Tint8 \\/ te2 = Tint16 \\/ te2 = Tint32 ->\n    p <==>\n      (A_notin_lenv x ** Agvarenv x (Tarray t n) (addrval_to_addr (b, i))) ** p' ->\n    p ==> Rv e2 @ te2 == Vint32 (Int.repr (BinInt.Z.of_nat m)) ->\n    p ==>\n      (Lv (earrayelem (evar x) e2) @ t == (b,Int.add i (Int.mul (Int.repr (BinInt.Z.of_nat (typelen t)))  (Int.repr (BinInt.Z.of_nat m))))).\nProof.\n  introv Ht.\n  intros.\n  destruct H with s.\n  destruct H0 with s;auto.\n  clear H H0.\n  apply H2 in H1.\n  clear H2 H3.\n  destruct H5.\n  destruct s as [[]].\n  destruct t0 as [[[[]]]].\n  simpl in *;mytac.\n  apply EnvMod.nindom_get in H11.\n  rewrite H11.\n  rewrite H12.\n  rewrite H4.\n  rewrite <- Int.unsigned_zero in H3.\n  apply aux_for_hoare_lemmas.unsigned_zero in H3.\n  subst i.\n  auto.\n  apply EnvMod.nindom_get in H11.\n  rewrite H11.\n  rewrite H12.\n  rewrite H.\n  simpl in H3.\n  simpl in *.\n  destruct Ht;subst;auto.\n  destruct H1;subst;auto.\nQed.\n *)\n\n\nLemma int_count_eq: forall i t m, Int.add (Int.add i (Int.repr (BinInt.Z.of_nat (typelen t))))\n                                          (Int.mul (Int.repr (BinInt.Z.of_nat (typelen t)))\n                                                   (Int.repr (BinInt.Z.of_nat m))) =  Int.add i\n                                                                                              (Int.mul (Int.repr (BinInt.Z.of_nat (typelen t)))\n                                                                                                       (Int.repr (BinInt.Z.of_nat (S m)))).\nProof.\n  intros.\n  rewrite Int.add_assoc.\n  assert ((Int.repr (Z.of_nat (S m))) = Int.add (Int.repr (Z.of_nat m)) Int.one).\n  assert (S m = m + 1).\n  omega.\n  rewrite H.\n  rewrite Nat2Z.inj_add.\n  simpl.\n  unfold Int.add.\n  rewrite Int.unsigned_one.\n  rewrite Int.unsigned_repr_eq.\n  assert (1 = 1 mod Int.modulus)%Z.\n  compute.\n  auto.\n  rewrite H0 at 2.\n  apply Int.eqm_samerepr.\n  unfold Int.eqm.\n  apply Int.eqmod_add.\n  apply Int.eqmod_mod.\n  compute.\n  auto.\n  apply Int.eqmod_mod.\n  compute.\n  auto.\n  rewrite H.\n  rewrite Int.mul_add_distr_r.\n  rewrite Int.mul_one.\n  replace (Int.add (Int.repr (Z.of_nat (typelen t)))\n                   (Int.mul (Int.repr (Z.of_nat (typelen t))) (Int.repr (Z.of_nat m)))) with\n  (Int.add\n     (Int.mul (Int.repr (Z.of_nat (typelen t))) (Int.repr (Z.of_nat m)))\n     (Int.repr (Z.of_nat (typelen t)))).\n  auto.\n  rewrite Int.add_commut.\n  auto.\nQed.\n\n\nLemma array_asrt_eq: \n  forall n vl b i v t m,\n    m < n ->\n    nth_val m vl = Some v ->\n    Aarray' (b,i) n t vl <==> PV (b,Int.add i (Int.mul (Int.repr (BinInt.Z.of_nat (typelen t))) (Int.repr (BinInt.Z.of_nat m)))) @ t |-> v ** (Aarray_rm (b,i) n t vl m).\nProof.\n  intros.\n  generalize dependent s.\n  generalize dependent b.\n  generalize dependent i.\n  generalize dependent n.\n  generalize dependent m.\n  induction vl.\n  intros.\n  destruct m;tryfalse.\n  intros.\n  destruct m;  \n    simpl in H0;inverts H0.\n  destruct n.\n  inverts H.\n  unfold Aarray_rm.\n  unfold Aarray';fold Aarray'.\n  assert(Int.repr (BinInt.Z.of_nat 0)=Int.zero).\n  auto.\n  rewrite H0.\n  rewrite Int.mul_zero.\n  rewrite Int.add_zero.\n  split;intros;auto.\n  lets IH: IHvl H2.\n  destruct n.\n  inversion H.\n  assert (m<n).\n  omega.\n  lets IH': IH H0.\n  unfold Aarray';fold Aarray'.\n  unfold Aarray_rm;fold Aarray_rm.\n  clear IH.\n  assert (Int.add (Int.add i (Int.repr (BinInt.Z.of_nat (typelen t))))\n                  (Int.mul (Int.repr (BinInt.Z.of_nat (typelen t)))\n                           (Int.repr (BinInt.Z.of_nat m))) =  Int.add i\n                                                                      (Int.mul (Int.repr (BinInt.Z.of_nat (typelen t)))\n                                                                               (Int.repr (BinInt.Z.of_nat (S m))))).\n  apply int_count_eq.\n  assert ( Aarray' (b, (Int.add i (Int.repr (BinInt.Z.of_nat (typelen t))))) n t vl <==>\n                   PV (b,\n                       Int.add (Int.add i (Int.repr (BinInt.Z.of_nat (typelen t))))\n                               (Int.mul (Int.repr (BinInt.Z.of_nat (typelen t)))\n                                        (Int.repr (BinInt.Z.of_nat m)))) @ t |-> v **\n                   Aarray_rm (b, (Int.add i (Int.repr (BinInt.Z.of_nat (typelen t))))) n t vl m).\n  apply IH'.\n  clear IH'.\n  split;intros;  sep_auto;  destruct H3 with s.\n  apply H5 in H4.\n  rewrite <- H1;sep_auto.\n  rewrite <- H1 in H4.\n  apply H6;sep_auto.\nQed.\n\n\nLemma gooddecl_gettype: \n  forall i t dls n t' id,\n    good_decllist (dcons i t dls)=true -> nth_id n dls = Some id -> ftype id (dcons i t dls) = Some t' -> ftype id dls = Some t'.\nProof.\n  intros.\n  simpl in *.\n  apply andb_prop in H.\n  destruct H.\n  remember (Zbool.Zeq_bool id i) as b.\n  destruct b.\n  symmetry in Heqb.\n  apply Zbool.Zeq_bool_eq in Heqb.\n  rewrite Heqb in H0.\n  inverts Heqb.\n  apply nth_id_Some_imply_in_decllist in H0.\n  rewrite H0 in H.\n  tryfalse.\n  auto.\nQed.\n\nClose Scope Z_scope.\nOpen Scope nat_scope.\n\nLemma id_nth_ge:forall decl n id m, id_nth' id decl n = Some m -> m>=n.\nProof.\n  intros.\n  generalize dependent n.\n  generalize dependent m.\n  induction decl.\n  intros.\n  simpl in H.\n  false.\n  intros.\n  simpl in H.\n  assert (Zbool.Zeq_bool id i =true \\/ Zbool.Zeq_bool id i = false).\n  destruct (Zbool.Zeq_bool id i).\n  left;auto.\n  right;auto.\n  destruct H0.\n  rewrite H0 in H.\n  inverts H.\n  omega.\n  rewrite H0 in H.\n  assert (m>= S n).\n  eapply IHdecl;eauto.\n  omega.\nQed.\n\nLemma id_nth'_suc: forall id decl n m, id_nth' id decl (S n) = Some (S m) -> \n                                       id_nth' id decl n = Some m .\nProof.\n  intros.\n  generalize dependent n.\n  generalize dependent m.\n  induction decl.\n  intros.\n  simpl in H.\n  false.\n  intros.\n  simpl in *.\n  assert (Zbool.Zeq_bool id i =true \\/ Zbool.Zeq_bool id i = false).\n  destruct (Zbool.Zeq_bool id i).\n  left;auto.\n  right;auto.\n  destruct H0.\n  rewrite H0 in *.\n  inversion H.\n  auto.\n  rewrite H0 in *.\n  apply IHdecl;auto.\nQed.\n\nLemma id_nth_eq: \n  forall n id decl, \n    good_decllist decl = true -> id_nth id decl = Some n -> nth_id n decl = Some id.\nProof.\n  intros.\n  generalize dependent id.\n  generalize dependent n.\n  induction decl.\n  intros.\n  simpl in *.\n  unfold id_nth in H0.\n  simpl in H0.\n  false.\n  intros.\n  destruct n.\n  simpl in *.\n  clear IHdecl.\n  unfold id_nth in H0.\n  simpl in H0.\n  assert (Zbool.Zeq_bool id i =true \\/ Zbool.Zeq_bool id i = false).\n  destruct (Zbool.Zeq_bool id i).\n  left;auto.\n  right;auto.\n  destruct H1;rewrite H1 in H0.\n  apply Zbool.Zeq_bool_eq in H1.\n  subst;auto.\n  apply id_nth_ge in H0.\n  omega.\n  simpl.\n  apply IHdecl.\n  simpl in H.\n  apply  Bool.andb_true_iff in H.\n  destruct H;auto.\n  unfold id_nth in *.\n  simpl in H0.\n  assert (Zbool.Zeq_bool id i =true \\/ Zbool.Zeq_bool id i = false).\n  destruct (Zbool.Zeq_bool id i).\n  left;auto.\n  right;auto.\n  destruct H1.\n  rewrite H1 in H0.\n  inverts H0.\n  rewrite H1 in H0.\n  eapply id_nth'_suc;eauto.\nQed.\n\n\nLemma up_val_op_ex: forall vl v n vl' , update_nth_val_op n vl v = Some vl' -> update_nth_val n vl v = vl'  /\\ (exists vi, nth_val n vl = Some vi).\nProof.\n  intros.\n  unfold update_nth_val_op in H.\n  destruct (NPeano.Nat.ltb n (length vl)) eqn : eq1; tryfalse.\n  inversion H; clear H.\n  split.\n  auto.\n  gen v n vl'.\n  inductions vl; intros.\n  simpl in H1.\n  substs.\n  simpl in eq1.\n  destruct n; simpl in eq1; tryfalse.\n  simpl.\n  destruct n.\n  eauto.\n  simpl in eq1.\n  unfold NPeano.Nat.ltb in eq1.\n  unfold NPeano.Nat.ltb in eq1.\n  simpl in eq1.\n  destruct (length vl) eqn : eq2.\n  inversion eq1.\n  simpl in H1.\n  destruct (update_nth_val n vl v) eqn : eq3.\n  eapply IHvl.\n  auto.\n  eapply eq3.\n  eapply IHvl.\n  auto.\n  eapply eq3.\nQed.\n\n\nLemma eval_type_addr_eq : forall e ge le m t, evaltype (eaddrof e) (ge, le, m) = Some (Tptr t) -> evaltype e (ge, le, m) = Some t.\nProof.\n  intros.\n  simpl in *;destruct e;tryfalse;auto.\n  destruct (evaltype (evar v) (ge, le, m));tryfalse.\n  inversion H;auto.\n  simpl.\n  destruct (evaltype e (ge, le, m));tryfalse.\n  destruct t0;tryfalse.\n  inversion H;auto.\n  destruct (evaltype (efield e i) (ge, le, m));tryfalse.\n  inversion H;auto.\n  destruct (evaltype (earrayelem e1 e2) (ge, le, m));tryfalse.\n  inversion H;auto.\nQed.\n\nLemma eval_addr_eq: forall e ge le m b i, evalval (eaddrof e) (ge, le, m) = Some (Vptr (b, i)) -> evaladdr e (ge,le,m) = Some (Vptr (b,i)).\nProof.\n  intros.\n  simpl in *.\n  destruct e;tryfalse.\n  destruct (evaltype (evar v) (ge, le, m));tryfalse;auto.\n  destruct (evaltype e (ge, le, m));tryfalse;auto.\n  destruct t;tryfalse;auto.\n  destruct (evaltype (efield e i0) (ge, le, m));tryfalse;auto.\n  destruct (evaltype (earrayelem e1 e2) (ge, le, m));tryfalse;auto.\nQed.\n\nLemma gooddecl_off_add: \n  forall i t dls n  id off,\n    good_decllist (dcons i t dls)=true -> nth_id n dls = Some id -> \n    field_offset id (dcons i t dls) = Some off ->\n    exists off', field_offset id dls = Some off' /\\ Int.add (Int.repr (BinInt.Z_of_nat (typelen t))) off'= off.\nProof.\n  intros.\n  unfolds in H1.\n  simpl in H1.\n  destruct (Zbool.Zeq_bool id i) eqn : eq1.\n  inversion H1.\n  substs.\n  simpl in H.\n  apply Bool.andb_true_iff in H.\n  destruct H.\n  apply Bool.negb_true_iff in H.\n  apply Zbool.Zeq_bool_eq in eq1.\n  substs.\n  clear H1.\n  false.\n  gen i t n.\n  induction dls; intros.\n  simpl in H0.\n  inversion H0.\n  destruct n.\n  simpl in H0.\n  inversion H0.\n  substs.\n  simpl in H.\n  apply Bool.orb_false_iff in H.\n  destruct H.\n  assert (Zbool.Zeq_bool i0 i0 = true).\n  apply Zbool.Zeq_is_eq_bool.\n  auto.\n  rewrite H3 in H.\n  inversion H.\n  eapply IHdls.\n  simpl in H2.\n  apply Bool.andb_true_iff in H2.\n  destruct H2.\n  apply Bool.negb_true_iff in H1.\n  auto.\n  simpl in H.\n  apply Bool.orb_false_iff in H.\n  destruct H.\n  eapply H1.\n  auto.\n  simpl in H0.\n  eapply H0.\n\n  destruct n.\n  destruct dls.\n  simpl in H0.\n  inversion H0.\n  simpl in H0.\n  inversion H0.\n  substs.\n  simpl in H1.\n  assert (Zbool.Zeq_bool id id = true).\n  apply Zbool.Zeq_is_eq_bool.\n  auto.\n  rewrite H2 in H1.\n  inversion H1.\n  exists Int.zero.\n  split.\n  unfolds.\n  simpl.\n  rewrite H2.\n  auto.\n  auto.\n  destruct dls.\n  simpl in H0.\n  inversion H0.\n  simpl in H0.\n  simpl in H.\n  apply Bool.andb_true_iff in H.\n  destruct H.\n  apply Bool.negb_true_iff in H.\n  apply Bool.orb_false_iff in H.\n  destruct H.\n  apply Bool.andb_true_iff in H2.\n  destruct H2.\n  apply Bool.negb_true_iff in H2.\n  simpl in H1.\n\n\n\n  apply nth_id_some_in_decllist_true in H0.\n  destruct (Zbool.Zeq_bool id i0) eqn : eq2.\n  apply Zbool.Zeq_is_eq_bool in eq2.\n  substs.\n  false.\n  pose proof in_decllist_field_offsetfld_some dls id H0.\n  pose proof H5 (Int.add (Int.repr (BinInt.Z.of_nat (typelen t0))) Int.zero).\n  destruct H6.\n  unfold field_offset.\n  simpl.\n  rewrite eq2.\n  exists x.\n  split.\n  auto.\n  pose proof field_offsetfld_pos_mono dls id H6 H1.\n  apply H7.\n  apply Int.add_permut.\nQed.\n\n\nLemma struct_asrt_eq: \n  forall n dls vl id off b i v t,\n    (forall ids dl, t <> Tstruct ids dl)->\n    (forall t' n, t <> Tarray t' n)->\n    nth_id n dls = Some id ->\n    nth_val n vl = Some v ->\n    ftype id dls = Some t ->\n    good_decllist dls = true ->\n    field_offset id dls = Some off -> \n    Astruct' (b,i) dls vl <==> PV (b,Int.add i off) @ t |-> v ** (Astruct_rm (b,i) dls vl id).\nProof.\n  introv Hstr.\n  introv Harr.\n  intros.\n  generalize dependent s.\n  generalize dependent b.\n  generalize dependent i.\n  generalize dependent n.\n  generalize dependent vl.\n  generalize dependent id.\n  generalize dependent off.\n  generalize dependent t.\n  induction dls.\n  intros.\n  destruct n;tryfalse.\n  rename t into t0.\n  intros.\n  assert(good_decllist dls=true).\n  simpl in H2.\n  apply Bool.andb_true_iff  in H2.\n  destruct H2;auto.\n  lets IH : IHdls H4.\n  clear IHdls.\n  destruct n.\n  simpl in H.\n  inverts H.\n  destruct vl;tryfalse.\n  simpl in H0.\n  inverts H0.\n  unfold Astruct_rm;fold Astruct_rm.\n  assert (Zbool.Zeq_bool id id=true).\n  apply Zbool.Zeq_is_eq_bool;auto.\n  rewrite H.\n  simpl in H1.\n  rewrite H in H1.\n  inverts H1.\n  unfold Astruct';fold Astruct'.\n\n  assert(Int.add i0 Int.zero = i0).\n  apply Int.add_zero;auto.\n\n  destruct t;auto;tryfalse;\n  unfold field_offset in H3;\n  simpl in H3;\n  rewrite H in H3;\n  inverts H3;\n  rewrite H0;auto;\n  splits;auto.\n  simpl in H.\n  destruct vl.\n  simpl in H0;tryfalse.\n  simpl in H0.\n  lets Hft: gooddecl_gettype H2 H H1.\n  lets Hoff: gooddecl_off_add H2 H H3.\n  destruct Hoff.\n  destruct H5.\n  lets IHn: IH Hft H5;clear IH.\n  auto.\n  auto.\n  lets IHn': IHn H H0.\n  clear IHn.\n  unfold Astruct';fold Astruct'.\n  unfold Astruct_rm;fold Astruct_rm.\n  assert(Zbool.Zeq_bool id i=false).\n  eapply gooddecl_neq;eauto.\n  rewrite H7.\n  lets IH:IHn' (Int.add i0 (Int.repr (BinInt.Z.of_nat (typelen t0)))) b.\n  clear IHn'.\n\n  assert (Int.add (Int.add i0 (Int.repr (BinInt.Z.of_nat (typelen t0)))) x = Int.add i0 (Int.add (Int.repr (BinInt.Z.of_nat (typelen t0))) x)).\n  apply Int.add_assoc;auto.\n  rewrite H8 in IH.\n  rewrite H6 in IH.\n  destruct t0.\n  eapply insert_star with (p:=Astruct' (b, Int.add i0 (Int.repr (BinInt.Z.of_nat (typelen Tnull)))) dls\n                                       vl) (r:=Astruct_rm (b, Int.add i0 (Int.repr (BinInt.Z.of_nat (typelen Tnull))))\n                                                          dls vl id) (l:=PV (b, i0) @ Tnull |-> v0 ) (q:=PV (b, Int.add i0 off) @ t |-> v) (s:=s);eauto.\n  eapply insert_star with (p:=Astruct' (b, Int.add i0 (Int.repr (BinInt.Z.of_nat (typelen Tvoid)))) dls\n                                       vl) (r:=Astruct_rm (b, Int.add i0 (Int.repr (BinInt.Z.of_nat (typelen Tvoid))))\n                                                          dls vl id) (l:=PV (b, i0) @ Tvoid |-> v0 ) (q:=PV (b, Int.add i0 off) @ t |-> v) (s:=s);eauto.\n  eapply insert_star with (p:=Astruct' (b, Int.add i0 (Int.repr (BinInt.Z.of_nat (typelen Tint8)))) dls\n                                       vl) (r:=Astruct_rm (b, Int.add i0 (Int.repr (BinInt.Z.of_nat (typelen Tint8))))\n                                                          dls vl id) (l:=PV (b, i0) @ Tint8 |-> v0 ) (q:=PV (b, Int.add i0 off) @ t |-> v) (s:=s);eauto.\n  eapply insert_star with (p:=Astruct' (b, Int.add i0 (Int.repr (BinInt.Z.of_nat (typelen Tint16)))) dls\n                                       vl) (r:=Astruct_rm (b, Int.add i0 (Int.repr (BinInt.Z.of_nat (typelen Tint16))))\n                                                          dls vl id) (l:=PV (b, i0) @ Tint16 |-> v0 ) (q:=PV (b, Int.add i0 off) @ t |-> v) (s:=s);eauto.\n  eapply insert_star with (p:=Astruct' (b, Int.add i0 (Int.repr (BinInt.Z.of_nat (typelen Tint32)))) dls\n                                       vl) (r:=Astruct_rm (b, Int.add i0 (Int.repr (BinInt.Z.of_nat (typelen Tint32))))\n                                                          dls vl id) (l:=PV (b, i0) @ Tint32 |-> v0 ) (q:=PV (b, Int.add i0 off) @ t |-> v) (s:=s);eauto.\n  eapply insert_star with (p:=Astruct' (b, Int.add i0 (Int.repr (BinInt.Z.of_nat (typelen (Tptr t0))))) dls\n                                       vl) (r:=Astruct_rm (b, Int.add i0 (Int.repr (BinInt.Z.of_nat (typelen (Tptr t0)))))\n                                                          dls vl id) (l:=PV (b, i0) @ (Tptr t0) |-> v0 ) (q:=PV (b, Int.add i0 off) @ t |-> v) (s:=s);eauto.\n  eapply insert_star with (p:=Astruct' (b, Int.add i0 (Int.repr (BinInt.Z.of_nat (typelen (Tcom_ptr i1))))) dls\n                                       vl) (r:=Astruct_rm (b, Int.add i0 (Int.repr (BinInt.Z.of_nat (typelen (Tcom_ptr i1)))))\n                                                          dls vl id) (l:=PV (b, i0) @ (Tcom_ptr i1) |-> v0 ) (q:=PV (b, Int.add i0 off) @ t |-> v) (s:=s);eauto.\n  unfold Astruct';fold Astruct'.\n  destruct IH with s.\n  splits;auto.\n  destruct IH with s.\n  splits;auto.\nQed.\n\n\n(*---------------------------------------*)\n\n(** sep get rv *)\n\nTheorem lvar_to_lv : \n  forall x l t P,\n    L& x @ t == l ** P ==> Lv (evar x) @ t == l.\nProof.\n  intros.\n  destruct s as [ [ [ [ [ [ ] ] ] ] ] ]; simpl in *; mytac.\n  rewrite H3; auto.\n  cut (l = (x6, Int.zero)).\n  intros; subst l; auto.\n  destruct l; simpl in H5.\n  inversion H5.\n  assert (Int.repr (Int.unsigned i0) = i0) by apply Int.repr_unsigned.\n  rewrite <- H.\n  rewrite H1.\n  auto.\n  rewrite H3; auto.\nQed.\n\nTheorem gvar_to_lv : \n  forall x l t P,\n    A_notin_lenv x ** G& x @ t == l ** P ==> Lv (evar x) @ t == l.\nProof.\n  intros.\n  destruct s as [ [ [ [ [ [ ] ] ] ] ] ]; simpl in *; mytac.\n  unfold get in H8.\n  simpl in H8.\n  apply EnvMod.nindom_get in H3.\n  change ( (fun xxx =>\n              match xxx with\n                | Some (a0, _) => Some (Vptr (a0, Int.zero))\n                | None =>\n                  match get e x with\n                    | Some (a0, _) => Some (Vptr (a0, Int.zero))\n                    | None => None\n                  end\n              end = Some (Vptr l)\n           ) (get e0 x)).\n  rewrite H3.\n  change (( fun xx =>    match xx with\n                           | Some (a0, _) => Some (Vptr (a0, Int.zero))\n                           | None => None\n                         end = Some (Vptr l)\n          ) (get e x)).\n  rewrite H8; auto.\n  cut (l = (x12, Int.zero)).\n  intros; subst l; auto.\n  destruct l; simpl in H10.\n  inversion H10.\n  assert (Int.repr (Int.unsigned i0) = i0) by apply Int.repr_unsigned.\n  rewrite <- H.\n  rewrite H1.\n  auto.\n  apply EnvMod.nindom_get in H3.\n  rewrite H8.\n  unfold get.\n  simpl.\n  rewrite H3.\n  auto.\nQed.\n\nLemma rule_type_val_match_nvundef:\n  forall v t, rule_type_val_match t v = true -> v<> Vundef.\nProof.\n  intros.\n  destruct v,t;auto; tryfalse; intro; tryfalse.\nQed.\n\nLemma lv_mapsto_to_rv :\n  forall l t e s P v perm, \n    rule_type_val_match t v = true ->\n    (*v <> Vundef ->*)\n    s |= Lv e @ t == l ->\n    s |=  (addrval_to_addr l)  # t |=> v @ perm ** P ->\n    s |= Rv e @ t == v.\nProof.\n  introv H.\n  assert (v<>Vundef).\n  eapply rule_type_val_match_nvundef;eauto.\n  intros.\n  destruct s as [[]].\n  destruct t0 as [[[[]]]].\n  simpl in *;mytac;auto.\n  destruct e;simpl in *;auto;tryfalse.\n  destruct (get e1 v0).\n  destruct p.\n  destruct t0;inverts H1;inverts H9;eapply mapstoval_loadbytes in H6;eauto;destruct H6;destruct H1; unfold load;unfold loadm.\n\n  eapply loadbytes_local in H1;eauto;rewrite Int.unsigned_zero in H1;\n  assert (loadbytes m (b, BinNums.Z0) (typelen Tnull) = Some x1);auto;\n  rewrite H4;\n  rewrite H2;auto.\n\n\n  eapply loadbytes_local in H1;eauto;rewrite Int.unsigned_zero in H1.\n  assert (loadbytes m (b, BinNums.Z0) (typelen Tvoid) = Some x1);auto;\n  rewrite H4;\n  rewrite H2;auto.\n\n\n  eapply loadbytes_local in H1;eauto;rewrite Int.unsigned_zero in H1.\n  assert (loadbytes m (b, BinNums.Z0) (typelen Tint8) = Some x1);auto;\n  rewrite H4;\n  rewrite H2;auto.\n\n  eapply loadbytes_local in H1;eauto;rewrite Int.unsigned_zero in H1.\n  assert (loadbytes m (b, BinNums.Z0) (typelen Tint16) = Some x1);auto;\n  rewrite H4;\n  rewrite H2;auto.\n\n  eapply loadbytes_local in H1;eauto;rewrite Int.unsigned_zero in H1.\n  assert (loadbytes m (b, BinNums.Z0) (typelen Tint32) = Some x1);auto;\n  rewrite H4;\n  rewrite H2;auto.\n\n  eapply loadbytes_local in H1;eauto;rewrite Int.unsigned_zero in H1.\n  assert (loadbytes m (b, BinNums.Z0) (typelen (Tptr t0)) = Some x1);auto;\n  rewrite H4;\n  rewrite H2;auto.\n\n  eapply loadbytes_local in H1;eauto;rewrite Int.unsigned_zero in H1.\n  assert (loadbytes m (b, BinNums.Z0) (typelen (Tcom_ptr i0)) = Some x1);auto;\n  rewrite H4;\n  rewrite H2;auto.\n\n  unfold decode_val in H2.\n  destruct (proj_bytes x1) in H2;false.\n\n\n  eapply loadbytes_local in H1;eauto;rewrite Int.unsigned_zero in H1.\n  assert (loadbytes m (b, BinNums.Z0) (typelen (Tstruct i0 d)) = Some x1);auto;\n  rewrite H4;\n  rewrite H2;auto.\n\n  destruct (get e0 v0).\n  destruct p.\n  destruct t0;inverts H1;inverts H9;eapply mapstoval_loadbytes in H6;eauto;destruct H6;destruct H1;unfold load ;unfold loadm.\n\n  eapply loadbytes_local in H1;eauto;rewrite Int.unsigned_zero in H1;\n  assert (loadbytes m (b, BinNums.Z0) (typelen Tnull) = Some x1);auto;\n  rewrite H4;\n  rewrite H2;auto.\n\n  eapply loadbytes_local in H1;eauto;rewrite Int.unsigned_zero in H1.\n  assert (loadbytes m (b, BinNums.Z0) (typelen Tvoid) = Some x1);auto;\n  rewrite H4;\n  rewrite H2;auto.\n\n\n  eapply loadbytes_local in H1;eauto;rewrite Int.unsigned_zero in H1.\n  assert (loadbytes m (b, BinNums.Z0) (typelen Tint8) = Some x1);auto;\n  rewrite H4;\n  rewrite H2;auto.\n\n  eapply loadbytes_local in H1;eauto;rewrite Int.unsigned_zero in H1.\n  assert (loadbytes m (b, BinNums.Z0) (typelen Tint16) = Some x1);auto;\n  rewrite H4;\n  rewrite H2;auto.\n\n  eapply loadbytes_local in H1;eauto;rewrite Int.unsigned_zero in H1.\n  assert (loadbytes m (b, BinNums.Z0) (typelen Tint32) = Some x1);auto;\n  rewrite H4;\n  rewrite H2;auto.\n\n  eapply loadbytes_local in H1;eauto;rewrite Int.unsigned_zero in H1.\n  assert (loadbytes m (b, BinNums.Z0) (typelen (Tptr t0)) = Some x1);auto;\n  rewrite H4;\n  rewrite H2;auto.\n\n\n  eapply loadbytes_local in H1;eauto;rewrite Int.unsigned_zero in H1.\n  assert (loadbytes m (b, BinNums.Z0) (typelen (Tcom_ptr i0)) = Some x1);auto;\n  rewrite H4;\n  rewrite H2;auto.\n\n  unfold decode_val in H2.\n  destruct (proj_bytes x1) in H2;false.\n\n  eapply loadbytes_local in H1;eauto;rewrite Int.unsigned_zero in H1.\n  assert (loadbytes m (b, BinNums.Z0) (typelen (Tstruct i0 d)) = Some x1);auto;\n  rewrite H4;\n  rewrite H2;auto.\n\n  false.\n\n  destruct (evaltype e (e0, e1, m)).\n  destruct t0;tryfalse.\n  inverts H9.\n  rewrite H1.\n\n\n  destruct l.\n  simpl in *.\n  apply mapstoval_loadbytes in H6.\n  destruct H6.\n  destruct H2.\n  eapply loadbytes_local in H2;eauto.\n\n  unfold load;unfold loadm.\n  assert ( loadbytes m (b, Int.unsigned i0) (typelen t) = Some x1);auto.\n  rewrite H5.\n  rewrite H4;auto.\n  destruct t;auto.\n  simpl in H;tryfalse.\n  auto.\n  false.\n\n  destruct (evaltype e (e0, e1, m) );tryfalse.\n  destruct t0;tryfalse;auto.\n  rewrite H9.\n  destruct ( evaladdr e (e0, e1, m) );tryfalse;auto.\n  destruct v0;auto;tryfalse.\n  destruct a0.\n  destruct (getoff b (Int.unsigned i2) i0 e (e0, e1, m));auto;tryfalse.\n  inverts H1.\n  destruct l;simpl in *.\n  eapply mapstoval_loadbytes in H6;eauto.\n  destruct H6.\n  destruct H1.\n  eapply loadbytes_local in H1;eauto.\n  assert ( loadbytes m (b0, Int.unsigned i3) (typelen t) = Some x1);auto.\n  unfold load;unfold loadm.\n  rewrite H4.\n  rewrite H2;auto.\n  destruct t;auto.\n  simpl in H;tryfalse.\n\n  destruct (evaltype e2 (e0, e1, m));auto;tryfalse.\n  destruct t0;auto;tryfalse.\n  destruct (evaltype e3 (e0, e1, m));auto;tryfalse.\n  destruct t1;auto;tryfalse.\n  destruct (evalval e2 (e0, e1, m));auto;tryfalse.\n  inverts H9.\n  destruct v0;auto;tryfalse.\n  destruct a0.\n  destruct ( evalval e3 (e0, e1, m) );auto;tryfalse.\n  destruct v0;auto;tryfalse.\n  inverts H1.\n  simpl in *.\n\n  apply mapstoval_loadbytes in H6.\n  destruct H6.\n  destruct H1.\n  eapply loadbytes_local in H1;eauto.\n  assert (loadbytes m\n                    (b,\n                     Int.unsigned\n                       (Int.add i0 (Int.mul (Int.repr (BinInt.Z.of_nat (typelen t))) i1)))\n                    (typelen t) = Some x1);auto.\n  unfold load ;unfold loadm.\n  rewrite H4.\n  rewrite H2;auto.\n  auto.\n\n  destruct t;auto.\n  simpl in H;tryfalse.\n  auto.\n\n  inverts H9.\n  destruct (evalval e2 (e0, e1, m));auto;tryfalse.\n  destruct v0;auto;tryfalse.\n  destruct a0.\n  destruct ( evalval e3 (e0, e1, m) );auto;tryfalse.\n  destruct v0;auto;tryfalse.\n  inverts H1.\n  simpl in *.\n\n  apply mapstoval_loadbytes in H6.\n  destruct H6.\n  destruct H1.\n  eapply loadbytes_local in H1;eauto.\n  assert (loadbytes m\n                    (b,\n                     Int.unsigned\n                       (Int.add i0 (Int.mul (Int.repr (BinInt.Z.of_nat (typelen t))) i1)))\n                    (typelen t) = Some x1);auto.\n  unfold load;unfold loadm.\n  rewrite H4.\n  rewrite H2;auto.\n\n  destruct t;auto.\n  simpl in H;tryfalse.\n  auto.\n\n  inverts H9.\n  destruct (evalval e2 (e0, e1, m));auto;tryfalse.\n  destruct v0;auto;tryfalse.\n  destruct a0.\n  destruct ( evalval e3 (e0, e1, m) );auto;tryfalse.\n  destruct v0;auto;tryfalse.\n  inverts H1.\n  simpl in *.\n\n  apply mapstoval_loadbytes in H6.\n  destruct H6.\n  destruct H1.\n  eapply loadbytes_local in H1;eauto.\n  assert (loadbytes m\n                    (b,\n                     Int.unsigned\n                       (Int.add i0 (Int.mul (Int.repr (BinInt.Z.of_nat (typelen t))) i1)))\n                    (typelen t) = Some x1);auto.\n  unfold load;unfold loadm.\n  rewrite H4.\n  rewrite H2;auto.\n\n  destruct t;auto.\n  simpl in H;tryfalse.\n  auto.\n\n  destruct (evaltype e3 (e0, e1, m));auto;tryfalse.\n  destruct t1;auto;tryfalse.\n  destruct (evalval e2 (e0, e1, m));auto;tryfalse.\n  inverts H9.\n  destruct v0;auto;tryfalse.\n  destruct a0.\n  destruct ( evalval e3 (e0, e1, m) );auto;tryfalse.\n  destruct v0;auto;tryfalse.\n  inverts H1.\n  simpl in *.\n\n  apply mapstoval_loadbytes in H6.\n  destruct H6.\n  destruct H1.\n  eapply loadbytes_local in H1;eauto.\n  assert (loadbytes m\n                    (b,\n                     Int.unsigned\n                       (Int.add i0 (Int.mul (Int.repr (BinInt.Z.of_nat (typelen t))) i1)))\n                    (typelen t) = Some x1);auto.\n  unfold load ;unfold loadm.\n  rewrite H4.\n  rewrite H2;auto.\n  auto.\n\n  destruct t;auto.\n  simpl in H;tryfalse.\n  auto.\n\n  inverts H9.\n  destruct (evalval e2 (e0, e1, m));auto;tryfalse.\n  destruct v0;auto;tryfalse.\n  destruct a0.\n  destruct ( evalval e3 (e0, e1, m) );auto;tryfalse.\n  destruct v0;auto;tryfalse.\n  inverts H1.\n  simpl in *.\n\n  apply mapstoval_loadbytes in H6.\n  destruct H6.\n  destruct H1.\n  eapply loadbytes_local in H1;eauto.\n  assert (loadbytes m\n                    (b,\n                     Int.unsigned\n                       (Int.add i0 (Int.mul (Int.repr (BinInt.Z.of_nat (typelen t))) i1)))\n                    (typelen t) = Some x1);auto.\n  unfold load;unfold loadm.\n  rewrite H4.\n  rewrite H2;auto.\n\n  destruct t;auto.\n  simpl in H;tryfalse.\n  auto.\n\n  inverts H9.\n  destruct (evalval e2 (e0, e1, m));auto;tryfalse.\n  destruct v0;auto;tryfalse.\n  destruct a0.\n  destruct ( evalval e3 (e0, e1, m) );auto;tryfalse.\n  destruct v0;auto;tryfalse.\n  inverts H1.\n  simpl in *.\n\n  apply mapstoval_loadbytes in H6.\n  destruct H6.\n  destruct H1.\n  eapply loadbytes_local in H1;eauto.\n  assert (loadbytes m\n                    (b,\n                     Int.unsigned\n                       (Int.add i0 (Int.mul (Int.repr (BinInt.Z.of_nat (typelen t))) i1)))\n                    (typelen t) = Some x1);auto.\n  unfold load;unfold loadm.\n  rewrite H4.\n  rewrite H2;auto.\n\n  destruct t;auto.\n  simpl in H;tryfalse.\n  auto.\n\nQed.\n\n\n\nTheorem cast_rv_tptr :\n  forall s e v t1 t2,\n    s |= Rv e @ (Tptr t1) == v ->\n    rule_type_val_match (Tptr t1) v = true ->\n    s |= Rv (ecast e (Tptr t2)) @ (Tptr t2) == v.\nProof.\n  intros.\n  unfold sat;fold sat.\n  destruct_s s.\n  simpl in H.\n  destructs H.\n  splits;auto.\n  simpl.\n  rewrite H1.\n  simpl.\n  auto.\n  simpl.\n  rewrite H1.\n  auto.\nQed.\n\nTheorem cast_rv_struct_tptr :\n  forall s e v t1 t2,\n    s |= Rv e @ (Tcom_ptr t1) == v ->\n    rule_type_val_match (Tcom_ptr t1) v = true ->\n    s |= Rv (ecast e (Tptr t2)) @ (Tptr t2) == v.\nProof.\n  intros.\n  unfold sat;fold sat.\n  destruct_s s.\n  simpl in H.\n  destructs H.\n  splits;auto.\n  simpl.\n  rewrite H1.\n  simpl.\n  auto.\n  simpl.\n  rewrite H1.\n  auto.\nQed.\n\nTheorem cast_rv_tnull :\n  forall s e v t,\n    s |= Rv e @ Tnull == v ->\n    rule_type_val_match Tnull v = true ->\n    s |= Rv (ecast e (Tptr t)) @ (Tptr t) == v.\nProof.\n  intros.\n  unfold sat;fold sat.\n  destruct_s s.\n  simpl in H.\n  destructs H.\n  splits;auto.\n  simpl.\n  rewrite H1.\n  auto.\n  simpl.\n  rewrite H1.\n  auto.\nQed.\n\nTheorem cast_rv_ptr :\n  forall (s : RstateOP) (e : expr) (v : val) t1  (t2 : type),\n    s |= Rv e @ t1  == v ->\n    rule_type_val_match t1 v = true ->\n    (exists t1', t1 = Tcom_ptr t1' )  \\/ (exists t1', t1 =  Tptr t1' ) \\/ t1 = Tnull  ->\n    s |= Rv (ecast e (Tptr t2))  @ (Tptr t2)  == v.\nProof.\n  intros.\n  destruct H1; simpljoin.\n  eapply cast_rv_struct_tptr; eauto.\n  destruct H1; simpljoin.\n  eapply cast_rv_tptr; eauto.\n  eapply cast_rv_tnull; eauto.\nQed.\n\n\nTheorem cast_rv_tint32_tint8 :\n  forall s e v v',\n    s |= Rv e @ Tint32 == (Vint32 v) ->\n    cast_eval v Tint32 Tint8 = Some v' ->\n    s |= Rv (ecast e (Tint8)) @ (Tint8) == (Vint32 v').\nProof.\n  intros.\n  unfold sat;fold sat.\n  destruct_s s.\n  simpl in H.\n  destructs H.\n  splits;auto.\n  simpl.\n  rewrite H1.\n  auto.\n  simpl.\n  rewrite H.\n  simpl in H0.\n  inverts H0.\n  auto.\n  simpl.\n  rewrite H1.\n\n  auto.\n  intro; tryfalse.\nQed.\n\n\nTheorem cast_rv_tint8_tint16 :\n  forall s e v v',\n    s |= Rv e @ Tint8 == (Vint32 v) ->\n    cast_eval v Tint8 Tint16 = Some v' ->\n    s |= Rv (ecast e (Tint16)) @ (Tint16) == (Vint32 v').\nProof.\n  intros.\n  unfold sat;fold sat.\n  destruct_s s.\n  simpl in H.\n  destructs H.\n  splits;auto.\n  simpl.\n  rewrite H1.\n  simpl.\n  rewrite H.\n  simpl in H0.\n  inverts H0.\n  auto.\n  simpl.\n  rewrite H1.\n  auto.\n  intro; tryfalse.\nQed.\n\n(*\nDefinition val_inj (v : option val) : val :=\n  match v with\n    | Some v' => v'\n    | None => Vundef\n  end.\n*)\n\n\nTheorem bop_rv :\n  forall s bop e1 e2 v1 t1 v2 t2 v t,\n    s |= Rv e1 @ t1 == v1 ->\n    s |= Rv e2 @ t2 == v2 ->\n    val_inj (bop_eval v1 v2 t1 t2 bop) = v ->\n    v <> Vundef ->\n    bop_type t1 t2 bop = Some t ->\n    s |= Rv (ebinop bop e1 e2) @ t == v.\nProof.\n  intros.\n  destruct s as [ [ [ [ [ [ ] ] ] ] ] ].\n  simpl in *; mytac; auto.\n  rewrite H.\n  rewrite H6.\n  rewrite H4.\n  rewrite H3.\n  rewrite H0.\n  destruct (bop_eval v1 v2 t1 t2 bop); simpl in H2; tryfalse.\n  destruct v; tryfalse || auto.\n  rewrite H6.\n  rewrite H4.\n  auto.\nQed.\n\nTheorem uop_rv :\n  forall s uop e v t v' t',\n    s |= Rv e @ t == v ->\n    val_inj (uop_eval v uop) = v' ->\n    v' <> Vundef ->\n    uop_type t uop = Some t' ->\n    s |= Rv (eunop uop e) @ t' == v'.\nProof.\n  intros.\n  destruct s as [ [ [ [ [ [ ] ] ] ] ] ].\n  simpl in *; mytac; auto.\n  rewrite H.\n  rewrite H3.\n  rewrite H2.\n  destruct (uop_eval v uop); simpl in H1; tryfalse.\n  destruct v0; tryfalse || auto.\n  rewrite H3.\n  auto.\nQed.\n\n\nLemma nth_val_imp_nth_val'_1 :\n  forall m vl,\n    (Int.unsigned m < Z.of_nat (length vl))%Z ->\n    nth_val (Z.abs_nat (Int.unsigned m)) vl = Some (nth_val' (Z.to_nat (Int.unsigned m)) vl).\nProof.\n  intros.\n  cut (exists n, m = Int.repr (Z.of_nat n) /\\(0 <= Z.of_nat n <= Int.max_unsigned)%Z).\n  intros; mytac.\n  rewrite Int.unsigned_repr in H; auto.\n  rewrite Int.unsigned_repr; auto.\n  rewrite Zabs2Nat.id.\n  rewrite Nat2Z.id.\n  apply Nat2Z.inj_lt in H.\n  gen H; clear; intros.\n  gen vl x; induction vl, x; intros; simpl in *.\n  omega.\n  omega.\n  auto.\n  apply IHvl.\n  omega.\n  destruct m.\n  exists (Z.to_nat intval).\n  split.\n  2 : rewrite Z2Nat.id.\n  2 : unfold Int.max_unsigned; omega.\n  2 : omega.\n  rewrite Z2Nat.id.\n  2 : omega.\n  rewrite <- Int.repr_unsigned at 1.\n  simpl; auto.\nQed.\n\nLemma nth_val_imp_nth_val'_2 :\n  forall n vl,\n    n < length vl ->\n    nth_val n vl = Some (nth_val' n vl).\nProof.\n  intros.\n  gen vl n.\n  induction vl, n; intros; simpl in *.\n  omega.\n  omega.\n  auto.\n  apply IHvl.\n  omega.\nQed.\n\nTheorem deref_rv :\n  forall s e l t v' P perm,\n    s |= Rv e @ Tptr t == Vptr l ->\n    s |= PV l @ t |=> v' @ perm  ** P ->\n    rule_type_val_match t v' = true ->\n    (*  v' <> Vundef ->*)\n    s |= Rv (ederef e) @ t == v'.\nProof.\n  introv Hm.\n  introv H.\n  introv H0.\n  assert (v'<>Vundef).\n  eapply rule_type_val_match_nvundef;eauto.\n  intros.\n  destruct s as [[]].\n  destruct t0 as [[[[]]]].\n  simpl in *.\n  mytac; auto.\n  rewrite H9.\n  rewrite H8.\n  eapply mapstoval_load in H5; auto.\n  eapply load_local ;eauto.\n  rewrite H9; auto.\nQed.\n\n\n\nLemma array_type_vallist_match_imp_rule_type_val_match :\n  forall vl n t,\n    n < length vl ->\n    array_type_vallist_match t vl ->\n    rule_type_val_match t (nth_val' n vl) = true.\nProof.\n  induction vl, n; intros; simpl in *; mytac.\n  omega.\n  omega.\n  auto.\n  apply IHvl; auto.\n  omega.\nQed.\n\nLemma ge0_z_nat_le:\n  forall z n,\n    (0<=z)%Z ->\n    (z < Z.of_nat n)%Z -> \n    ((Z.to_nat z) < n)%nat.\nProof.\n  intros.\n  rewrite <- Nat2Z.id.\n  apply Z2Nat.inj_lt; omega.\nQed.\n\n\nLemma sub_mul_eq_add_mul:\n  forall i i0 x n, \n    Int.sub i i0 = Int.mul x (Int.repr (Z.of_nat n)) ->\n    (0 <= Int.unsigned i - Int.unsigned i0 <= Int.max_unsigned)%Z ->\n    i = Int.add i0 (Int.mul (Int.repr (Z.of_nat n))\n                            (Int.repr (Int.unsigned x))).\nProof.\n  intros.\n  rewrite Int.repr_unsigned.\n  rewrite Int.mul_commut.\n  rewrite <- H.\n  unfold Int.add.\n  unfold Int.sub.\n  rewrite Int.unsigned_repr.\n  assert (Int.unsigned i0 + (Int.unsigned i - Int.unsigned i0) = Int.unsigned i)%Z.\n  omega.\n  rewrite  H1.\n  rewrite Int.repr_unsigned;auto.\n  simpl.\n  auto.\nQed.\n\nTheorem deref_ptr_of_array_member_rv':\n  forall P s t' t vl e i0 b i x v n,\n    s |= Aarray (b,i0) t' vl ** P->\n    t' = Tarray t n ->\n    s |= Rv e @ (Tptr t)  == Vptr (b,i) ->\n    Int.sub i i0 = Int.mul x (Int.repr (Z_of_nat (typelen t )))->\n    (0 <= Int.unsigned i - Int.unsigned i0 <= 4294967295)%Z  ->\n    (Z.of_nat n < 4294967295)%Z -> \n    (Int.unsigned x < Z.of_nat n)%Z ->\n    (Int.unsigned x < Z.of_nat (length vl))%Z ->\n    rule_type_val_match t v = true ->\n    nth_val' (Z.to_nat (Int.unsigned x)) vl = v ->\n    s |= Rv (ederef e) @ t == v.\nProof.\n  intros.\n  eapply deref_rv;eauto.\n  instantiate (1:= Aarray_rm (b, i0) n t vl (Z.to_nat (Int.unsigned x)) ** P).\n  lets H100:H.\n  sep auto.\n  unfold Aarray in H100.\n  clear H1 H.\n  apply array_asrt_eq with (v:=nth_val' (Z.to_nat (Int.unsigned x)) vl) (m:=((Z.to_nat (Int.unsigned x)))) in H100.\n\n  2:eapply ge0_z_nat_le;eauto.\n  Focus 2.\n  lets H1000:Int.unsigned_range x.\n  omega.\n  Focus 2.\n  rewrite <- Zabs2Nat.abs_nat_nonneg at 1.\n  eapply nth_val_imp_nth_val'_1;eauto.\n  lets H1000:Int.unsigned_range x.\n  omega.\n  sep auto.\n  rewrite Z2Nat.id in H100.\n  2:lets H1000:Int.unsigned_range x;\n    omega.\n  assert (i=Int.add i0\n                    (Int.mul (Int.repr (Z.of_nat (typelen t)))\n                             (Int.repr (Int.unsigned x)))).\n  eapply sub_mul_eq_add_mul;eauto.\n  subst i.\n  eauto.\nQed.\n(*\n  subst v.\n  apply array_type_vallist_match_imp_rule_type_val_match; auto.\n  apply Nat2Z.inj_lt.\n  rewrite Z2Nat.id.\n  auto.\n  lets H100 : Int.unsigned_range x.\n  omega.\nQed.\n *)\nLemma max_unsigned_val : Int.max_unsigned = 4294967295%Z.\nProof.\n  auto.\nQed.\n\nLemma unsigned_minus_le_max :\n  forall a b, \n    (Int.unsigned a - Int.unsigned b <= 4294967295)%Z.\nProof.\n  intros.\n  generalize (Int.unsigned_range_2 a).\n  generalize (Int.unsigned_range_2 b).\n  rewrite max_unsigned_val.\n  intros; omega.\nQed.\n\nLemma sub_zero_eq :\n  forall i1 i2,\n    Int.sub i1 i2 = Int.zero ->\n    i1 = i2.\nProof.\n  intros.\n  assert (Int.add (Int.sub i1 i2) i2 = Int.add Int.zero i2) as H100.\n  rewrite H; auto.\n  rewrite <- Int.sub_add_l in H100.\n  assert (Int.sub (Int.add i1 i2) (Int.add Int.zero i2) = Int.add Int.zero i2) as H200.\n  rewrite Int.add_zero_l at 1; auto.\n  rewrite Int.sub_shifted in H200.\n  rewrite Int.sub_zero_l in H200.\n  rewrite Int.add_zero_l in H200.\n  auto.\nQed.\n\n\nTheorem deref_ptr_of_array_member_rv'' :\n  forall P s t' t vl e l l' x v n,\n    s |= Aarray l t' vl ** P->\n    t' = Tarray t n ->\n    (Z.of_nat n < 4294967295)%Z -> \n    s |= Rv e @ (Tptr t)  == Vptr l' ->\n    typelen t <> 0 ->\n    (Z.of_nat (typelen t) < 4294967295)%Z ->\n    fst l = fst l' ->\n    (Int.unsigned (snd l) <= Int.unsigned (snd l'))%Z ->\n    Int.divu (Int.sub (snd l') (snd l)) (Int.repr (Z_of_nat (typelen t))) = x ->\n    Int.modu (Int.sub (snd l') (snd l)) (Int.repr (Z_of_nat (typelen t))) = Int.zero ->\n    (Int.unsigned x < Z.of_nat n)%Z ->\n    (Int.unsigned x < Z.of_nat (length vl))%Z ->\n    rule_type_val_match t v = true ->\n    nth_val' (Z.to_nat (Int.unsigned x)) vl = v ->\n    s |= Rv (ederef e) @ t == v.\nProof.\n  intros.\n  destruct l, l'.\n  simpl fst in *; simpl snd in *; subst.\n  eapply deref_ptr_of_array_member_rv'; eauto.\n  Focus 2.\n  split.\n  apply Zle_minus_le_0; auto.\n  apply unsigned_minus_le_max.\n  remember (Int.repr (Z.of_nat (typelen t))) as x100.\n  assert (x100 <> Int.zero) as H100.\n  subst x100.\n  clear - H3 H4.\n  intro; apply H3.\n  assert (Int.unsigned (Int.repr (Z.of_nat (typelen t))) = Int.unsigned Int.zero) as H100.\n  rewrite H; auto.\n  rewrite Int.unsigned_repr in H100.\n  change (Int.unsigned Int.zero) with 0%Z in H100.\n  apply Nat2Z.inj.\n  auto.\n  split.\n  omega.\n  change Int.max_unsigned with  4294967295%Z.\n  omega.\n  remember (Int.sub i0 i) as x200.\n  clear Heqx100 Heqx200.\n  lets H200 : Int.modu_divu x200 x100 H100.\n  rewrite H8 in H200.\n  apply sub_zero_eq; auto.\nQed.\n\nClose Scope nat_scope.\nOpen Scope Z_scope.\n\nLemma Int_div_to_Z_div :\n  forall i1 i2 z1 z2,\n    (Int.unsigned i2 <= Int.unsigned i1)%Z ->\n    (0 < z1)%Z ->\n    (z1 < 4294967295)%Z ->\n    (Int.unsigned i1 - Int.unsigned i2) / z1 = z2 ->\n    Int.unsigned (Int.divu (Int.sub i1 i2) (Int.repr z1)) = z2.\nProof.\n  intros.\n  unfold Int.divu.\n  rewrite Int.unsigned_repr.\n  rewrite Int.unsigned_repr.\n  unfold Int.sub.\n  rewrite Int.unsigned_repr.\n  auto.\n  split.\n  apply Zle_minus_le_0; auto.\n  apply unsigned_minus_le_max.\n  rewrite max_unsigned_val; omega.\n  assert (Int.unsigned (Int.repr z1) >= 1)%Z as H100.\n  rewrite Int.unsigned_repr; auto.\n  omega.\n  rewrite max_unsigned_val; omega.\n  split.\n  apply Z.div_pos.\n  remember (Int.sub i1 i2); clear; int auto.\n  omega.\n  apply Z.div_le_upper_bound.\n  omega.\n  assert (1 * Int.max_unsigned <= Int.unsigned (Int.repr z1) * Int.max_unsigned)%Z as H200.\n  apply Z.mul_le_mono_nonneg_r.\n  clear; int auto.\n  omega.\n  assert (Int.unsigned (Int.sub i1 i2) <= 1 * Int.max_unsigned)%Z as H300.\n  remember (Int.sub i1 i2); clear; int auto.\n  eapply Z.le_trans; eauto.\nQed.\n\nLemma Int_modu_to_Z_mod :\n  forall i1 i2 z1 z2,\n    (Int.unsigned i2 <= Int.unsigned i1)%Z ->\n    (0 < z1)%Z ->\n    (z1 < 4294967295)%Z ->\n    (0 <= z2)%Z ->\n    (z2 <= 4294967295)%Z ->\n    (Int.unsigned i1 - Int.unsigned i2) mod z1 = z2 ->\n    Int.modu (Int.sub i1 i2) (Int.repr z1) = Int.repr z2.\nProof.\n  intros.\n  unfold Int.modu.\n  rewrite Int.unsigned_repr.\n  2 : int auto.\n  unfold Int.sub.\n  rewrite Int.unsigned_repr.\n  Focus 2.\n  split.\n  apply Zle_minus_le_0; auto.\n  apply unsigned_minus_le_max.\n  apply unsigned_inj.\n  rewrite Int.unsigned_repr.\n  rewrite Int.unsigned_repr.\n  auto.\n  int auto.\n  lets H100 : Z_mod_lt (Int.unsigned i1 - Int.unsigned i2)%Z z1.\n  int auto.\nQed.\n\nOpen Scope nat_scope.\n\nTheorem deref_ptr_of_array_member_rv''' :\n  forall P s t' t vl e l l' x v n,\n    s |= Aarray l t' vl ** P->\n    t' = Tarray t n ->\n    (Z.of_nat n < 4294967295)%Z -> \n    s |= Rv e @ (Tptr t)  == Vptr l' ->\n    typelen t <> 0 ->\n    fst l = fst l' ->\n    (Z.of_nat (typelen t) < 4294967295)%Z ->\n    fst l = fst l' ->\n    (Int.unsigned (snd l) <= Int.unsigned (snd l'))%Z ->\n    ((Int.unsigned (snd l') - Int.unsigned (snd l)) / (Z_of_nat (typelen t)) = x)%Z ->\n    ((Int.unsigned (snd l') - Int.unsigned (snd l)) mod (Z_of_nat (typelen t)) = 0)%Z ->\n    (x < Z.of_nat n)%Z ->\n    (x < Z.of_nat (length vl))%Z ->\n    rule_type_val_match t v = true ->\n    nth_val' (Z.to_nat x) vl = v ->\n    s |= Rv (ederef e) @ t == v.\nProof.\n  intros.\n  cut (x = Int.unsigned (Int.divu (Int.sub (snd l') (snd l)) (Int.repr (Z.of_nat (typelen t))))).\n  intro H100.\n  eapply deref_ptr_of_array_member_rv''; eauto.\n  apply Int_modu_to_Z_mod; auto || omega.\n  rewrite <- H100; auto.\n  rewrite <- H100; auto.\n  rewrite <- H100; auto.\n  symmetry; apply Int_div_to_Z_div; auto.\n  remember (typelen t) as len.\n  clear - H3.\n  omega.\nQed.\n\nTheorem deref_ptr_of_array_member_rv :\n  forall P s t' t vl e b i i' x v n,\n    s |= Rv e @ (Tptr t)  == Vptr (b,i') ->\n    s |= Aarray (b,i) t' vl ** P->\n    t' = Tarray t n ->\n    (Z.of_nat n < 4294967295)%Z ->    \n    typelen t <> 0 ->\n    (Z.of_nat (typelen t) < 4294967295)%Z ->\n    (Int.unsigned i <= Int.unsigned i')%Z ->\n    ((Int.unsigned i' - Int.unsigned i) / (Z_of_nat (typelen t)) = x)%Z ->\n    (Z_of_nat (typelen t) * x = (Int.unsigned i' - Int.unsigned i))%Z ->\n    (x < Z.of_nat n)%Z ->\n    (x < Z.of_nat (length vl))%Z ->\n    rule_type_val_match t v = true ->\n    nth_val' (Z.to_nat x) vl = v ->\n    s |= Rv (ederef e) @ t == v.\nProof.\n  intros.\n  eapply deref_ptr_of_array_member_rv'''; eauto.\n  apply Z_div_exact_full_1; subst; auto.\nQed.\n\nTheorem var_rv :\n  forall s x t l v P perm,    \n    s |= Rv (eaddrof (evar x)) @ Tptr t == Vptr l ->\n    s |= PV l @ t |=> v  @ perm ** P ->\n    (*v<>Vundef ->*)\n    rule_type_val_match t v = true->\n    s |= Rv (evar x) @ t == v.\nProof.\n  introv H.\n  introv H0.\n  introv H2.\n  assert(v<>Vundef).\n  eapply rule_type_val_match_nvundef;eauto.\n\n  destruct s as [[]].\n  destruct t0 as [[[[]]]].\n  simpl in *.\n  destruct l.\n  splits;auto.\n  destruct (get e0 x);auto;tryfalse.\n  destruct p.\n  mytac.\n  inverts H.\n  inverts H9.\n  simpl in H6.\n  rewrite Int.unsigned_zero in H6.\n  destruct t;auto;tryfalse.\n\n\n  eapply mapstoval_loadbytes in H6;eauto.\n  destruct H6.\n  destruct H.\n  eapply loadbytes_local in H;eauto.\n  assert (loadbytes m (b, 0%Z) (typelen Tnull)=Some x2);auto.\n  unfold load;unfold loadm.\n  rewrite H4.\n  rewrite H0;auto.\n\n  eapply mapstoval_loadbytes in H6;eauto.\n  destruct H6.\n  destruct H.\n  eapply loadbytes_local in H;eauto.\n  assert ( loadbytes m (b, BinNums.Z0) (typelen Tint8) = Some x2);auto.\n  unfold load;unfold loadm.\n  rewrite H4.\n  rewrite H0;auto.\n\n\n  eapply mapstoval_loadbytes in H6;eauto.\n  destruct H6.\n  destruct H.\n  eapply loadbytes_local in H;eauto.\n  assert ( loadbytes m (b, BinNums.Z0) (typelen Tint16) = Some x2);auto.\n  unfold load;unfold loadm.\n  rewrite H4.\n  rewrite H0;auto.\n\n\n  eapply mapstoval_loadbytes in H6;eauto.\n  destruct H6.\n  destruct H.\n  eapply loadbytes_local in H;eauto.\n  assert ( loadbytes m (b, BinNums.Z0) (typelen Tint32) = Some x2);auto.\n  unfold load;unfold loadm.\n  rewrite H4.\n  rewrite H0;auto.\n\n  eapply mapstoval_loadbytes in H6;eauto.\n  destruct H6.\n  destruct H.\n  eapply loadbytes_local in H;eauto.\n  assert ( loadbytes m (b, BinNums.Z0) (typelen (Tptr t)) = Some x2);auto.\n  unfold load;unfold loadm.\n  rewrite H4.\n  rewrite H0;auto.\n\n\n  eapply mapstoval_loadbytes in H6;eauto.\n  destruct H6.\n  destruct H.\n  eapply loadbytes_local in H;eauto.\n  assert ( loadbytes m (b, BinNums.Z0) (typelen (Tcom_ptr i0)) = Some x2);auto.\n  unfold load;unfold loadm.\n  rewrite H4.\n  rewrite H0;auto.\n\n\n\n  destruct (get e x);auto;tryfalse.\n  destruct p.\n  mytac.\n  inverts H.\n  inverts H9.\n  simpl in H6.\n  rewrite Int.unsigned_zero in H6.\n  destruct t;auto;tryfalse.\n\n  eapply mapstoval_loadbytes in H6;eauto.\n  destruct H6.\n  destruct H.\n  eapply loadbytes_local in H;eauto.\n  assert ( loadbytes m (b, BinNums.Z0) (typelen Tnull) = Some x2);auto.\n  unfold load;unfold loadm.\n  rewrite H4.\n  rewrite H0;auto.\n\n  eapply mapstoval_loadbytes in H6;eauto.\n  destruct H6.\n  destruct H.\n  eapply loadbytes_local in H;eauto.\n  assert ( loadbytes m (b, BinNums.Z0) (typelen Tint8) = Some x2);auto.\n  unfold load;unfold loadm.\n  rewrite H4.\n  rewrite H0;auto.\n\n\n  eapply mapstoval_loadbytes in H6;eauto.\n  destruct H6.\n  destruct H.\n  eapply loadbytes_local in H;eauto.\n  assert ( loadbytes m (b, BinNums.Z0) (typelen Tint16) = Some x2);auto.\n  unfold load;unfold loadm.\n  rewrite H4.\n  rewrite H0;auto.\n\n\n  eapply mapstoval_loadbytes in H6;eauto.\n  destruct H6.\n  destruct H.\n  eapply loadbytes_local in H;eauto.\n  assert ( loadbytes m (b, BinNums.Z0) (typelen Tint32) = Some x2);auto.\n  unfold load;unfold loadm.\n  rewrite H4.\n  rewrite H0;auto.\n\n  eapply mapstoval_loadbytes in H6;eauto.\n  destruct H6.\n  destruct H.\n  eapply loadbytes_local in H;eauto.\n  assert ( loadbytes m (b, BinNums.Z0) (typelen (Tptr t)) = Some x2);auto.\n  unfold load;unfold loadm.\n  rewrite H4.\n  rewrite H0;auto.\n\n  eapply mapstoval_loadbytes in H6;eauto.\n  destruct H6.\n  destruct H.\n  eapply loadbytes_local in H;eauto.\n  assert ( loadbytes m (b, BinNums.Z0) (typelen (Tcom_ptr i0)) = Some x2);auto.\n  unfold load;unfold loadm.\n  rewrite H4.\n  rewrite H0;auto.\n\n  destruct H;tryfalse.\n\n  destruct (get e0 x).\n  destruct p.\n  mytac.\n  inverts H9;auto.\n\n  destruct ( get e x).\n  destruct p.\n  mytac.\n  inverts H9;auto.\n\n  mytac; tryfalse.\nQed.\n\n(**\nAxiom expr_struct_rv :\n  forall s e t l id t' v' P,\n    s |= Rv (eaddrof e) @ Tptr t == Vptr l ->\n    s |= SP l @ t # id @ t' |-> v' ** P ->\n    s |= Rv (efield e id) @ t' == v'.\n *)\n\nTheorem addrof_deref_rv :\n  forall s e t l,\n    s |= Rv e @ (Tptr t) == (Vptr l) ->\n    s |= Rv (eaddrof (ederef e)) @ (Tptr t) == (Vptr l).\nProof.\n  intros.\n  destruct s as [[]].\n  destruct t0 as [[[[]]]].\n  simpl in *.\n  destruct H.\n  destruct H0.\n  rewrite H0.\n  destruct t;auto;tryfalse.\nQed.\n\n\n\nTheorem addrof_lvar_rv :\n  forall s x t l P,\n    s |= L& x @ t == l ** P ->\n    s |= Rv (eaddrof (evar x)) @ Tptr t == Vptr l.\nProof.\n  intros.\n  destruct s as [[]].\n  destruct t0 as [[[[]]]].\n  simpl in *;mytac.\n  rewrite H3.\n  destruct l.\n  simpl in H5.\n  inverts H5.\n  rewrite <- Int.unsigned_zero in H1.\n  apply unsigned_inj in H1.\n  subst.\n  auto.\n  rewrite H3.\n  auto.\n  intro.\n  inverts H.\nQed.\n\n\n\nTheorem addrof_array_elem_rv :\n  forall s e1 e2 t1 t2 b i j t,\n    s |= Rv e1 @ t1 == (Vptr (b,i)) ->\n    s |= Rv e2 @ t2 == Vint32 j ->\n    t2 = Tint8 \\/ t2 = Tint16 \\/ t2 = Tint32 ->\n    (t1 = Tptr t \\/ exists n, t1 = Tarray t n) ->\n    s |= Rv (eaddrof (earrayelem e1 e2)) @ (Tptr t) == (Vptr (b,(Int.add i\n                                                                         (Int.mul (Int.repr (Z.of_nat (typelen t))) j)))).\nProof.\n  intros.\n  destruct s as [[]].\n  destruct t0 as [[[[]]]].\n  destruct H2.\n\n  simpl in *;mytac.\n  rewrite H5.\n  rewrite H0.\n  rewrite H3.\n  destruct t2;destruct H1;tryfalse;destruct H1;tryfalse.\n  rewrite H.\n  auto.\n  rewrite H;auto.\n  rewrite H;auto.\n  rewrite H5.\n  rewrite H3.\n  destruct t2;destruct H1;tryfalse;destruct H1;tryfalse;auto.\n  intro; tryfalse.\n\n  simpl in *;mytac.\n  rewrite H5.\n  rewrite H0.\n  rewrite H3.\n  destruct t2;destruct H1;tryfalse;destruct H1;tryfalse.\n  rewrite H.\n  auto.\n  rewrite H;auto.\n  rewrite H;auto.\n  rewrite H5.\n  rewrite H3.\n  destruct t2;destruct H1;tryfalse;destruct H1;tryfalse;auto.\n  intro; tryfalse.\nQed.\n\nTheorem lvar_rv :\n  forall s x t v P perm,\n    s |= LV x @ t |=> v @ perm ** P ->\n    (* v <> Vundef ->*)\n    rule_type_val_match t v = true ->\n    s |= Rv (evar x) @ t == v.\nProof.\n  intros.\n  unfold Alvarmapsto in H.\n  sep normal in H.\n  sep_destruct H.\n  eapply var_rv; auto.\n  eapply addrof_lvar_rv.\n  eauto.\n  sep lift 2 in H; eauto.\nQed.\n\nTheorem addrof_gvar_rv :\n  forall s x t l P,\n    s |= A_notin_lenv x ** G& x @ t == l ** P ->\n    s |= Rv (eaddrof (evar x)) @ Tptr t == Vptr l.\nProof.\n  intros.\n  destruct s as [[]].\n  destruct t0 as [[[[]]]].\n  simpl in *;mytac.\n  unfold get in *; simpl in *.\n  lets H100 : EnvMod.nindom_get H3.\n  rewrite H100.\n  rewrite H8.\n  destruct l.\n  simpl in H10.\n  inverts H10.\n  rewrite <- Int.unsigned_zero in H1.\n  apply unsigned_inj in H1.\n\n  subst.\n  auto.\n  lets H100 : EnvMod.nindom_get H3.\n  unfold get in *; simpl in *.\n  rewrite H100.\n  rewrite H8.\n  auto.\n  intro.\n  inverts H.\nQed.\n\nTheorem gvar_rv' :\n  forall s x t v P perm,\n    s |= A_notin_lenv x ** GV x @ t |=> v @ perm ** P ->\n    (*v <> Vundef ->*)\n    rule_type_val_match t v = true ->\n    s |= Rv (evar x) @ t == v.\nProof.\n  intros.\n  unfold Agvarmapsto in H.\n  sep normal in H; sep_destruct H.\n  eapply var_rv; auto.\n  eapply addrof_gvar_rv.\n  sep lifts (3::1::nil)%list in H; eauto.\n  sep lift 2 in H; eauto.\nQed.\n\nOpen Scope list_scope.\n\nFixpoint var_notin_dom (x:var) (l:edom) :=\n  match l with\n    | nil => true\n    | (y,t)::l' => if BinInt.Z.eqb x y then false else (var_notin_dom x l')\n  end.\n\nClose Scope list_scope.\n\nLemma dom_lenv_imp_notin_lenv :\n  forall l P x,\n    var_notin_dom x l = true ->\n    A_dom_lenv l ** P ==> A_notin_lenv x ** P.\nProof.\n  intros.\n  simpl in *; mytac.\n  destruct_s s; simpl in *; mytac.\n  do 6 eexists; mytac; eauto.\n  unfold eq_dom_env in *.\n  intro.\n  apply EnvMod.indom_get in H0.\n  mytac.\n  destruct x0.\n  assert (exists b, EnvMod.get e0 x = Some (b, t)) by eauto.\n  apply H4 in H1.\n  gen H H1; clear; intros.\n  induction l; simpl in *.\n  auto.\n  destruct a.\n  remember (BinInt.Z.eqb x v) as bool; destruct bool.\n  tryfalse.\n  symmetry in Heqbool; apply BinInt.Z.eqb_neq in Heqbool.\n  destruct H1.\n  inverts H0; tryfalse.\n  lets IHl1 : IHl H H0; auto.\nQed.\n\n\nTheorem gvar_rv :\n  forall s x t v l P perm,\n    s |= A_dom_lenv l ** GV x @ t |=> v @ perm ** P ->\n    var_notin_dom x l = true ->\n    (* v <> Vundef ->*)\n    rule_type_val_match t v = true ->\n    s |= Rv (evar x) @ t == v.\nProof.\n  intros.\n  eapply gvar_rv'; auto.\n  eapply dom_lenv_imp_notin_lenv; eauto.\nQed.\n\nTheorem null_rv :\n  forall s,\n    s |= Rv enull @ Tnull == Vnull.\nProof.\n  intros.\n  destruct s as [ [ [ [ [ [ ] ] ] ] ] ]; simpl.\n  splits.\n  auto.\n  auto.\n  intro; tryfalse.\nQed.\n\nTheorem const_rv :\n  forall s i,\n    s |= Rv econst32 i @ Tint32 == Vint32 i.\nProof.\n  intros.\n  destruct s as [ [ [ [ [ [ ] ] ] ] ] ]; simpl.\n  splits.\n  auto.\n  auto.\n  intro; tryfalse.\nQed.\n\nLemma struct_member_rv':\n  forall s x t l vl tid decl n id t' v P perm,\n    (forall ids dl, t' <> Tstruct ids dl) ->\n    (forall (t'0 : type) (n0 : nat), t' <> Tarray t'0 n0) ->\n    rule_type_val_match t' v =true->\n    (*v<> Vundef ->*)\n    good_decllist decl = true ->\n    s |= LV x @ (Tptr t) |=> Vptr l @ perm ** Astruct l t vl ** P->\n    t = Tstruct tid decl ->\n    nth_id n decl = Some id ->\n    ftype id decl = Some t' ->\n    nth_val n vl = Some v ->\n    s |= Rv (efield (ederef (evar x)) id) @ t' == v.\nProof.\n  introv Hnstr.\n  introv Hnarr.\n  introv Htv.\n  assert (v<> Vundef) as Hvn.\n  eapply rule_type_val_match_nvundef;eauto.\n  introv Hgooddecl.\n  intros.\n  destruct s as ((o&O)&aop).\n  unfold sat in *;fold sat in *;mytac.\n  unfold substmo in *.\n  destruct o as [[[[]]]].\n  unfold substaskst in *.\n  unfold getsmem in *.\n  unfold getmem in *.\n  unfold get_smem in *.\n  unfold get_mem in *.\n  simpl in *;mytac.\n  rewrite H8.\n  rewrite H2.\n  rewrite Int.unsigned_zero in H10.\n  lets Hf: mapstoval_loadbytes H10.\n  simpl;auto.\n  destruct Hf.\n  destruct H.\n  lets Hf: loadbytes_local H4 H.\n  assert ( loadbytes m (x15, BinNums.Z0) (typelen (Tptr (Tstruct tid decl))) = Some x2);auto.\n  unfold load;unfold loadm.\n  rewrite H5.\n  rewrite H0.\n  clear H.\n  destruct l.\n  unfold getoff.\n  unfold evaltype.\n  rewrite H8.\n  lets Hoff: nth_id_exists_off H1.\n  destruct Hoff.\n  rewrite H.\n  assert (load t' x6 (addrval_to_addr (b, Int.add (Int.repr (Int.unsigned i0)) x3)) =\n          Some v).\n  unfold addrval_to_addr.\n  rewrite struct_asrt_eq with (n:=n) in H12;eauto.\n  unfold sat in H12;fold sat in H12;mytac.\n  simpl in H15.\n  rewrite Int.repr_unsigned.\n  simpl in H7.\n  eapply load_local;eauto.\n  eapply mapstoval_load;eauto.\n  simpl;eauto.\n  destruct H15;eauto.\n  auto.\n  apply map_join_comm in H4.\n  eapply load_local;eauto.\n  eapply load_local;eauto.\n  destruct o as [[[[]]]].\n  simpl in *;mytac.\n  rewrite H8.\n  auto.\n  auto.\nQed.\n\nTheorem struct_member_rv'':\n  forall s x t l vl tid decl n id t' v P perm,\n    s |= LV x @ (Tptr t) |=> Vptr l @ perm ** Astruct l t vl ** P->\n    t = Tstruct tid decl ->\n    good_decllist decl = true ->\n    ftype id decl = Some t' ->\n    (forall ids dl, t' <> Tstruct ids dl) ->\n    (forall (t'0 : type) (n0 : nat), t' <> Tarray t'0 n0) ->\n    id_nth id decl = Some n ->\n    nth_val n vl = Some v ->\n    (*v <> Vundef ->*)\n    rule_type_val_match t' v = true ->    \n    s |= Rv (efield (ederef (evar x)) id) @ t' == v.\nProof.\n  intros.\n  eapply struct_member_rv';eauto.\n  eapply id_nth_eq;eauto.\nQed.\n\n\nLemma id_nth_eq_0 :\n  forall id i t decl,\n    id_nth id (dcons i t decl) = Some 0 -> Zeq_bool id i = true.\nProof.\n  intros.\n  unfold id_nth in *.\n  unfold1 id_nth' in *.\n  remember (Zeq_bool id i) as X.\n  destruct X;tryfalse.\n  auto.\n  apply id_nth_ge in H.\n  omega.\nQed.\n\n\nLemma id_nth_ueq_0 :\n  forall id i t n decl,\n    id_nth id (dcons i t decl) = Some (S n) -> Zeq_bool id i = false /\\ id_nth id decl = Some n.\nProof.\n  intros.\n  unfold id_nth in *.\n  assert (Zeq_bool id i = false).\n  unfold1 id_nth' in *.\n  remember (Zeq_bool id i ) as X.\n  destruct X.\n  inverts H.\n  auto.\n  split;auto.\n  clear -H.\n  unfold1 id_nth' in H.\n  remember (Zeq_bool id i) as X.\n  destruct X;tryfalse.\n  apply id_nth'_suc;auto.\nQed.\n\n\n\nTheorem struct_member_rv:\n  forall s x t l vl tid decl n id t' v P perm,\n    s |= LV x @ (Tptr t) |=> Vptr l @ perm ** Astruct l t vl ** P ->\n    t = Tstruct tid decl ->\n    good_decllist decl = true ->\n    ftype id decl = Some t' ->\n    (forall ids dl, t' <> Tstruct ids dl) ->\n    (forall (t'0 : type) (n0 : nat), t' <> Tarray t'0 n0) ->\n    id_nth id decl = Some n ->\n    n < length vl ->\n    struct_type_vallist_match t vl ->\n    nth_val' n vl = v ->\n    s |= Rv (efield (ederef (evar x)) id) @ t' == v.\nProof.\n  intros.\n  subst v.\n  assert (rule_type_val_match t' (nth_val' n vl) = true).\n  subst t.\n  unfold struct_type_vallist_match in H7.\n  clear l x s H P tid.\n  gen vl decl n id t'.\n  induction vl,decl, n; intros; simpl in *; tryfalse.\n  apply id_nth_eq_0 in H5; subst.\n  rewrite H5 in H2.\n  inverts H2.\n  destruct t'; intuition auto.\n  false.\n  exact (H4 t' n eq_refl).\n  false.\n  eapply H3; eauto.\n  eapply IHvl; eauto.\n  4 : instantiate (1 := decl).\n  4 : instantiate (1 := id).\n  apply andb_true_iff in H1; mytac; auto.\n  destruct t; intuition auto.\n  omega.\n  apply id_nth_ueq_0 in H5; intuition auto.\n  apply id_nth_ueq_0 in H5; mytac.\n  rewrite H in H2.\n  auto.\n  eapply struct_member_rv''; eauto.\n  apply nth_val_imp_nth_val'_2; auto.\nQed.\n\nLemma struct_member_rv_g':\n  forall s x t l vl tid decl n id t' v P perm ,\n    (forall ids dl, t' <> Tstruct ids dl) ->\n    (forall (t'0 : type) (n0 : nat), t' <> Tarray t'0 n0) ->\n    rule_type_val_match t' v =true->\n    (*v<> Vundef ->*)\n    good_decllist decl = true ->\n    s |= (A_notin_lenv x ** GV x @ (Tptr t) |=> Vptr l @ perm) ** Astruct l t vl ** P->\n    t = Tstruct tid decl ->\n    nth_id n decl = Some id ->\n    ftype id decl = Some t' ->\n    nth_val n vl = Some v ->\n    s |= Rv (efield (ederef (evar x)) id) @ t' == v.\nProof.\n  introv Hnstr.\n  introv Hnarr.\n  introv Htv.\n  assert (v<> Vundef) as Hvn.\n  eapply rule_type_val_match_nvundef;eauto.\n  introv Hgooddecl.\n  intros.\n  destruct s as ((o&O)&aop).\n  unfold sat in *;fold sat in *;mytac.\n  unfold substmo in *.\n  destruct o as [[[[]]]].\n  unfold substaskst in *.\n  unfold getsmem in *.\n  unfold getmem in *.\n  unfold get_smem in *.\n  unfold get_mem in *.\n  simpl in *;mytac.\n  unfold get in *; simpl in *.\n  apply EnvMod.nindom_get in H17.\n  rewrite H17.\n  rewrite H8.\n  rewrite Int.unsigned_zero in H10.\n  lets Hf: mapstoval_loadbytes H10.\n  simpl;auto.\n  destruct Hf.\n  destruct H.\n  lets Hf: loadbytes_local H4 H.\n  assert ( loadbytes m (x19, BinNums.Z0) (typelen (Tptr (Tstruct tid decl))) = Some x2);auto.\n  unfold load;unfold loadm.\n  rewrite H2.\n  rewrite H5.\n  rewrite H0.\n  clear H.\n  destruct l.\n  unfold getoff.\n  unfold evaltype.\n  unfold get in *; simpl in *.\n  rewrite H17.\n  rewrite H8.\n  lets Hoff: nth_id_exists_off H1.\n  destruct Hoff.\n  rewrite H.\n\n  assert (load t' x1 (addrval_to_addr (b, Int.add (Int.repr (Int.unsigned i0)) x3)) =\n          Some v).\n  unfold addrval_to_addr.\n  rewrite struct_asrt_eq with (n:=n) in H12;eauto.\n  unfold sat in H12;fold sat in H12;mytac.\n  simpl in H7.\n  rewrite Int.repr_unsigned.\n  simpl in H15.\n  eapply load_local;eauto.\n  eapply load_local;eauto.\n  eapply mapstoval_load;auto.\n  destruct H15;eauto.\n  apply map_join_comm in H4.\n  eapply load_local;eauto.\n  destruct o as [[[[]]]].\n  simpl in *;mytac.\n  apply EnvMod.nindom_get in  H17.\n  unfold get in *; simpl in *.\n  rewrite H17.\n  rewrite H8.\n  auto.\n  auto.\nQed.\n\nTheorem struct_member_rv_g'':\n  forall s x t l vl tid decl n id t' v P perm,\n    s |= (A_notin_lenv x ** GV x @ (Tptr t) |=> Vptr l @ perm) ** Astruct l t vl ** P ->\n    t = Tstruct tid decl ->\n    good_decllist decl = true ->\n    ftype id decl = Some t' ->\n    (forall ids dl, t' <> Tstruct ids dl) ->\n    (forall (t'0 : type) (n0 : nat), t' <> Tarray t'0 n0) ->\n    id_nth id decl = Some n ->\n    nth_val n vl = Some v ->\n    (*v <> Vundef ->*)\n    rule_type_val_match t' v = true ->    \n    s |= Rv (efield (ederef (evar x)) id) @ t' == v.\nProof.\n  intros.\n  eapply struct_member_rv_g';eauto.\n  eapply id_nth_eq;eauto.\nQed.\n\nTheorem struct_member_rv_g''':\n  forall s ls x t l vl tid decl n id t' v P perm,\n    s |= A_dom_lenv ls ** GV x @ (Tptr t) |=> Vptr l @ perm ** Astruct l t vl ** P->\n    var_notin_dom x ls = true ->\n    t = Tstruct tid decl ->\n    good_decllist decl = true ->\n    ftype id decl = Some t' ->\n    (forall ids dl, t' <> Tstruct ids dl) ->\n    (forall (t'0 : type) (n0 : nat), t' <> Tarray t'0 n0) ->\n    id_nth id decl = Some n ->\n    nth_val n vl = Some v ->\n    (*v <> Vundef ->*)\n    rule_type_val_match t' v = true ->    \n    s |= Rv (efield (ederef (evar x)) id) @ t' == v.\nProof.\n  intros.\n  eapply struct_member_rv_g''; eauto.\n  sep normal.\n  eapply dom_lenv_imp_notin_lenv; eauto.\nQed.\n\nLemma struct_tvmatch_imp_rule_tvmatch:\n  forall (vl : list val) (decl : decllist),\n   good_decllist decl = true ->\n   struct_type_vallist_match' decl vl ->\n   forall n : nat,\n   n < length vl ->\n   forall id : ident,\n   id_nth id decl = Some n ->\n   forall t' : type,\n   ftype id decl = Some t' ->\n   (forall (ids : ident) (dl : decllist), t' <> Tstruct ids dl) ->\n   (forall (t'0 : type) (n0 : nat), t' <> Tarray t'0 n0) ->\n   rule_type_val_match t' (nth_val' n vl) = true.\nProof.\n  induction vl,decl, n; intros; simpl in *; tryfalse.\n  apply id_nth_eq_0 in H2; subst.\n  rewrite H2 in H3.\n  inverts H3.\n  destruct t'; intuition auto.\n  false.\n  exact (H5 t' n eq_refl).\n  false.\n  eapply H4; eauto.\n  eapply IHvl; eauto.\n  4 : instantiate (1 := decl).\n  4 : instantiate (1 := id).\n  apply andb_true_iff in H; mytac; auto.\n  destruct t; intuition auto.\n  omega.\n  apply id_nth_ueq_0 in H2; intuition auto.\n  apply id_nth_ueq_0 in H2; mytac.\n  rewrite H2 in H3.\n  auto.\nQed.\n\nTheorem struct_member_rv_g:\n  forall s ls x t l vl tid decl n id t' v P perm,\n    s |= A_dom_lenv ls ** GV x @ (Tptr t) |=> Vptr l @ perm ** Astruct l t vl ** P->\n    var_notin_dom x ls = true ->\n    t = Tstruct tid decl ->\n    good_decllist decl = true ->\n    ftype id decl = Some t' ->\n    (forall ids dl, t' <> Tstruct ids dl) ->\n    (forall (t'0 : type) (n0 : nat), t' <> Tarray t'0 n0) ->\n    id_nth id decl = Some n ->\n    n < length vl ->\n    struct_type_vallist_match t vl ->\n    nth_val' n vl = v ->\n    s |= Rv (efield (ederef (evar x)) id) @ t' == v.\nProof.\n  intros.\n  subst v.\n  assert (rule_type_val_match t' (nth_val' n vl) = true).\n  subst t.\n  unfold struct_type_vallist_match in H8.\n  clear l x s H H0 P tid ls.\n  gen vl decl n id t'.\n  induction vl,decl, n; intros; simpl in *; tryfalse.\n  apply id_nth_eq_0 in H6; subst.\n  rewrite H6 in H3.\n  inverts H3.\n  destruct t'; intuition auto.\n  false.\n  exact (H5 t' n eq_refl).\n  false.\n  eapply H4; eauto.\n  eapply IHvl; eauto.\n  4 : instantiate (1 := decl).\n  4 : instantiate (1 := id).\n  apply andb_true_iff in H2; mytac; auto.\n  destruct t; intuition auto.\n  omega.\n  apply id_nth_ueq_0 in H6; intuition auto.\n  apply id_nth_ueq_0 in H6; mytac.\n  rewrite H in H3.\n  auto.\n  eapply struct_member_rv_g'''; eauto.\n  apply nth_val_imp_nth_val'_2; auto.\nQed.\n\nFixpoint sub_decllist (d1 d2: decllist){struct d1} : bool :=\n match d1 with\n    | dnil => true\n    | dcons x1 t1 d1' =>\n      match d2 with\n         | dnil => false\n         | dcons x2 t2 d2' => andb (andb (Zeq_bool x1 x2) (type_eq t1 t2)) (sub_decllist d1' d2')\n      end\nend.\n\nLemma sub_decllist_ftype:\n  forall d1 d2 t id, \n    sub_decllist d1 d2 =true -> \n    ftype id d1 = Some t -> \n    ftype id d2 = Some t. \nProof.\n  inductions d1.\n  simpl; intros; tryfalse. \n  intros.\n  simpl in H.\n  destruct d2; tryfalse.\n apply andb_true_iff in H.\n destruct H.\n apply andb_true_iff in H.\n destruct H.\n apply type_eq_true_eq in H2.\n subst.\n apply Zeq_bool_eq in H.\n subst.\n simpl.\n simpl in H0.\n  remember (Zeq_bool id i0) as Ha.\n  destruct Ha; auto.\nQed.\n\nLemma sub_decllist_offsetfld:\n  forall d1 d2 t id i,\n    sub_decllist d1 d2 =true -> \n    field_offsetfld id d1 i = Some t  -> \n    field_offsetfld id d2 i= Some t. \nProof.\ninductions d1.\n  simpl; intros; tryfalse. \n  intros.\n  simpl in H.\n  destruct d2; tryfalse.\n apply andb_true_iff in H.\n destruct H.\n apply andb_true_iff in H.\n destruct H.\n apply type_eq_true_eq in H2.\n subst.\n apply Zeq_bool_eq in H.\n subst.\n unfold field_offset in *.\n simpl in *.\n  remember (Zeq_bool id i1) as Ha.\n  destruct Ha; auto.\nQed.\n\n\nLemma sub_decllist_offset:\n  forall d1 d2 t id,\n    sub_decllist d1 d2 =true -> \n    field_offset id d1 = Some t  -> \n    field_offset  id d2 = Some t. \nProof.\n  intros.\n  eapply sub_decllist_offsetfld; eauto.\nQed.\n\n\n\n(*\nTheorem struct_member_rv_g:\n  forall s ls x t l vl tid decl n id t' v P perm,\n    s |= A_dom_lenv ls ** GV x @ (Tptr t) |=> Vptr l @ perm ** Astruct l t vl ** P->\n    var_notin_dom x ls = true ->\n    t = Tstruct tid decl ->\n    good_decllist decl = true ->\n    ftype id decl = Some t' ->\n    (forall ids dl, t' <> Tstruct ids dl) ->\n    (forall (t'0 : type) (n0 : nat), t' <> Tarray t'0 n0) ->\n    id_nth id decl = Some n ->\n    n < length vl ->\n    struct_type_vallist_match t vl ->\n    nth_val' n vl = v ->\n    s |= Rv (efield (ederef (evar x)) id) @ t' == v.\nProof.\n  intros.\n  subst v.\n  assert (rule_type_val_match t' (nth_val' n vl) = true).\n  subst t.\n  unfold struct_type_vallist_match in H8.\n  clear l x s H H0 P tid ls.\n  gen vl decl n id t'.\n  induction vl,decl, n; intros; simpl in *; tryfalse.\n  apply id_nth_eq_0 in H6; subst.\n  rewrite H6 in H3.\n  inverts H3.\n  destruct t'; intuition auto.\n  false.\n  exact (H5 t' n eq_refl).\n  false.\n  eapply H4; eauto.\n  eapply IHvl; eauto.\n  4 : instantiate (1 := decl).\n  4 : instantiate (1 := id).\n  apply andb_true_iff in H2; mytac; auto.\n  destruct t; intuition auto.\n  omega.\n  apply id_nth_ueq_0 in H6; intuition auto.\n  apply id_nth_ueq_0 in H6; mytac.\n  rewrite H in H3.\n  auto.\n  eapply struct_member_rv_g'''; eauto.\n  apply nth_val_imp_nth_val'_2; auto.\nQed.*)\n\n\nTheorem struct_member_array_rv_g:\n  forall s ls x t l vl tid decl id t' n P ad perm,\n    s |=   A_dom_lenv ls **  GV x @ (Tptr t) |=> Vptr l @ perm ** Astruct l t vl ** P->\n    var_notin_dom x ls = true ->\n    t = Tstruct tid decl ->\n    good_decllist decl = true ->\n    ftype id decl = Some (Tarray t' n) ->\n    id_addrval l id t = Some ad ->\n    s |= Rv (efield (ederef (evar x)) id) @ (Tarray t' n) == Vptr ad.\nProof.\n  intros.\n  destruct_s s.\n  eapply dom_lenv_imp_notin_lenv in H; eauto.\n  simpl in *;mytac.\n  apply EnvMod.nindom_get in H8;auto.\n  unfold get in *; simpl in *.\n  rewrite H8.\n  rewrite H23.\n  rewrite H3.\n  unfold load;unfold loadm.\n  rewrite Int.unsigned_zero in H24.\n  lets Hf: mapstoval_loadbytes H24.\n  simpl;auto.\n  destruct Hf.\n  destruct H.\n  lets Hf: loadbytes_local H10 H.\n  assert ( loadbytes m (x25, 0%Z) (typelen (Tptr (Tstruct tid decl))) = Some x0);auto.\n  rewrite H5.\n  rewrite H1.\n  destruct l.\n  unfold getoff.\n  unfold evaltype.\n  unfold get in *; simpl in *.\n  rewrite H8;rewrite H23.\n  unfold id_addrval in H4.\n  remember (field_offset id decl ) as X.\n  destruct X;tryfalse.\n  rewrite Int.repr_unsigned.\n  simpl.\n  rewrite Int.repr_unsigned.\n  inverts H4;auto.\n  apply EnvMod.nindom_get in H8;auto.\n  unfold get in *; simpl in *.\n  rewrite H8;rewrite H23.\n  auto.\n  intro; tryfalse.\nQed.\n\n\n\nDefinition isarray_type t:= exists t'' n, \n                              t = Tarray t'' n.\n\nTheorem struct_member_rv_g_general:\n  forall s ls x t l vl tid decl id P v t' perm,\n    s |=   A_dom_lenv ls **  GV x @ (Tptr t) |=> Vptr l @ perm ** Astruct l t vl ** P->\n    var_notin_dom x ls = true ->\n    t = Tstruct tid decl ->\n    good_decllist decl = true ->\n    ftype id decl = Some t' -> \n    (\n      isarray_type t'-> \n      exists ad, id_addrval l id t = Some ad /\\ v = Vptr ad\n    ) ->\n    (\n      ~ isarray_type t' ->\n      (\n        exists n,\n          (forall a b, t' <> Tstruct a b) /\\\n          id_nth id decl = Some n /\\\n          n < length vl /\\\n          struct_type_vallist_match t vl /\\\n          nth_val' n vl = v \n      )\n    ) -> \n    s |= Rv (efield (ederef (evar x)) id) @ t' == v.\nProof.\n  intros.\n  mytac.\n  assert (isarray_type t' \\/ ~isarray_type t' ).\n  tauto.\n  destruct H1.\n  lets Hx: H4 H1.\n  mytac.\n  unfolds in H1;mytac.\n  eapply struct_member_array_rv_g;eauto.\n  lets Hx : H5 H1.\n  mytac.\n  eapply struct_member_rv_g;eauto.\n  unfold isarray_type in H1.\n  intros.\n  introv.\n  introv Hf.\n  apply H1;eauto.\nQed.\n\n\n\n(*\nTheorem struct_member_array_rv_ro:\n  forall s x t l vl tid decl id t' n P ad,\n    s |=  LV x @ (Tptr t) |-r-> Vptr l ** Astruct l t vl ** P->\n    t = Tstruct tid decl ->\n    good_decllist decl = true ->\n    ftype id decl = Some (Tarray t' n) ->\n    id_addrval l id t = Some ad ->\n    s |= Rv (efield (ederef (evar x)) id) @ (Tarray t' n) == Vptr ad.\nProof.\n  intros.\n  destruct_s s.\n  simpl in *;mytac.\n  rewrite H17.\n  rewrite H2.\n  unfold load;unfold loadm.\n  rewrite Int.unsigned_zero in H18.\n  lets Hf: mapstoval_loadbytes H18.\n  simpl;auto.\n  destruct Hf.\n  destruct H.\n  lets Hf: loadbytes_local H4 H.\n  assert ( loadbytes m (x19, 0%Z) (typelen (Tptr (Tstruct tid decl))) = Some x2);auto.\n  rewrite H5.\n  rewrite H0.\n  destruct l.\n  unfold getoff.\n  unfold evaltype.\n  rewrite H17.\n  unfold id_addrval in H3.\n  remember (field_offset id decl ) as X.\n  destruct X;tryfalse.\n  rewrite Int.repr_unsigned.\n  simpl.\n  rewrite Int.repr_unsigned.\n  inverts H3;auto.\n  rewrite H17.\n  auto.\n  intro; tryfalse.\nQed.\n*)\n\n\nTheorem struct_member_array_rv:\n  forall s x t l vl tid decl id t' n P ad perm,\n    s |=  LV x @ (Tptr t) |=> Vptr l @ perm  ** Astruct l t vl ** P->\n    t = Tstruct tid decl ->\n    good_decllist decl = true ->\n    ftype id decl = Some (Tarray t' n) ->\n    id_addrval l id t = Some ad ->\n    s |= Rv (efield (ederef (evar x)) id) @ (Tarray t' n) == Vptr ad.\nProof.\n  intros.\n  destruct_s s.\n  simpl in *;mytac.\n  rewrite H17.\n  rewrite H2.\n  unfold load;unfold loadm.\n  rewrite Int.unsigned_zero in H18.\n  lets Hf: mapstoval_loadbytes H18.\n  simpl;auto.\n  destruct Hf.\n  destruct H.\n  lets Hf: loadbytes_local H4 H.\n  assert ( loadbytes m (x19, 0%Z) (typelen (Tptr (Tstruct tid decl))) = Some x2);auto.\n  rewrite H5.\n  rewrite H0.\n  destruct l.\n  unfold getoff.\n  unfold evaltype.\n  rewrite H17.\n  unfold id_addrval in H3.\n  remember (field_offset id decl ) as X.\n  destruct X;tryfalse.\n  rewrite Int.repr_unsigned.\n  simpl.\n  rewrite Int.repr_unsigned.\n  inverts H3;auto.\n  rewrite H17.\n  auto.\n  intro; tryfalse.\nQed.\n\n\n\nTheorem struct_offset_rv :\n  forall s e t tid decl a id t' off,\n    s |= Rv eaddrof e @ Tptr t ==  Vptr a ->\n    t = Tstruct tid decl ->\n    field_offset id decl = Some off ->\n    ftype id decl = Some t' ->\n    s |= Rv eaddrof (efield e id) @ Tptr t' == Vptr (fst a, Int.add (snd a) off).\nProof.\n  intros.\n  unfold sat in *.\n  destruct H.\n  destruct H3.\n  subst t.\n  destruct s as [[]].\n  destruct t as [[[[]]]].\n  unfold getsmem in *.\n  unfold get_smem in *.\n  splits;auto.\n  assert (evaltype e (e0, e1, m) = Some (Tstruct tid decl)).\n  eapply eval_type_addr_eq;eauto.\n  simpl.\n  rewrite H0.\n  rewrite H2.\n  destruct a.\n  apply eval_addr_eq in H.\n  rewrite H.\n  simpl.\n  unfold getoff.\n  rewrite H0.\n  rewrite H1.\n  simpl.\n  assert (Int.repr (Int.unsigned i0)=i0).\n  apply Int.repr_unsigned.\n  rewrite H5.\n  auto.\n  simpl.\n  assert (evaltype e (e0, e1, m) = Some (Tstruct tid decl)).\n  eapply eval_type_addr_eq;eauto.\n  rewrite H0.\n  rewrite H2.\n  auto.\n  intro; tryfalse.\nQed.\n\nTheorem struct_member_rv_general:\n  forall s  x t l vl tid decl id P v t' perm,\n    s |=  LV x @ (Tptr t) |=> Vptr l @ perm ** Astruct l t vl ** P->\n    t = Tstruct tid decl ->\n    good_decllist decl = true ->\n    ftype id decl = Some t' -> \n    (\n      isarray_type t'-> \n      exists ad, id_addrval l id t = Some ad /\\ v = Vptr ad\n    ) ->\n    (\n      ~ isarray_type t' ->\n      (\n        exists n,\n          (forall a b, t' <> Tstruct a b) /\\\n          id_nth id decl = Some n /\\\n          n < length vl /\\\n          struct_type_vallist_match t vl /\\\n          nth_val' n vl = v \n      )\n    ) -> \n    s |= Rv (efield (ederef (evar x)) id) @ t' == v.\nProof.\n  intros.\n  mytac.\n  assert (isarray_type t' \\/ ~isarray_type t' ).\n  tauto.\n  destruct H0.\n  lets Hx: H3 H0.\n  mytac.\n  unfolds in H0;mytac.\n  eapply struct_member_array_rv;eauto.\n  lets Hx : H4 H0.\n  mytac.\n  eapply struct_member_rv;eauto.\n  unfold isarray_type in H0.\n  intros.\n  introv.\n  introv Hf.\n  apply H0;eauto.\nQed.\n\n\n\nLemma int_Z_ltu: \n  forall m n,\n    Int.ltu m (Int.repr (Z.of_nat n)) = true->\n    BinInt.Z.abs_nat (Int.unsigned m) < n.\nProof.\n  intros.\n  unfold Int.ltu in H.\n  destruct (Coqlib.zlt (Int.unsigned m) (Int.unsigned (Int.repr (Z.of_nat n)))); tryfalse.\n  clear H.\n  rewrite Zabs2Nat.abs_nat_nonneg.\n\n  rewrite Int.unsigned_repr_eq in l.\n  pose proof Zmod_le (Z.of_nat n) Int.modulus.\n  assert (0 < Int.modulus)%Z.\n  unfold Int.modulus.\n  unfold Int.wordsize.\n  unfold Wordsize_32.wordsize.\n  unfold two_power_nat.\n  unfold shift_nat.\n  simpl.\n  omega.\n  assert (0 <= Z.of_nat n)%Z.\n  omega.\n  pose proof H H0 H1; clear H H0 H1.\n  assert (Int.unsigned m < Z.of_nat n)%Z.\n  omega.\n  rewrite <- Nat2Z.id.\n  apply Z2Nat.inj_lt.\n  pose proof Int.unsigned_range m.\n  destruct H0.\n  auto.\n  omega.\n  auto.\n  pose proof Int.unsigned_range m.\n  destruct H.\n  auto.\nQed.\n\nTheorem array_member_rv' :\n  forall s x t te2 l vl n m v e2 P,\n    s |= Alvarenv x (Tarray t n) (addrval_to_addr l) ** Aarray l (Tarray t n) vl ** P ->\n    s |= Rv e2 @ te2  == Vint32 m ->\n    te2 = Tint8 \\/ te2 = Tint16 \\/ te2 = Tint32 ->\n    Int.ltu m Int.zero = false ->\n    Int.ltu m (Int.repr (BinInt.Z_of_nat n)) = true  ->\n    (*  Int.cmp Cge m Int.zero = true ->\n    Int.cmp Clt m (Int.repr (BinInt.Z_of_nat n)) =true  ->*)\n    nth_val (BinInt.Z.abs_nat (Int.unsigned m)) vl = Some v ->\n    (*v<> Vundef ->*)\n    rule_type_val_match t v =true->\n    s |= Rv (earrayelem (evar x) e2) @ t == v.\nProof.\n  intros.\n  rename H5 into Htv.\n  assert (v<> Vundef).\n  eapply rule_type_val_match_nvundef;eauto.\n  destruct s as ((o&O)&aop).\n  destruct l as (b&i).\n  unfold sat in *;fold sat in *;mytac.\n  unfold substmo in *.\n  destruct o as [[[[]]]].\n  unfold substaskst in *.\n  unfold getsmem in *.\n  unfold getmem in *.\n  unfold get_smem in *.\n  unfold get_mem in *.\n  simpl in *;mytac.\n  rewrite H11.\n  rewrite H6.\n  destruct H1.\n  rewrite H.\n  rewrite H0.\n  erewrite array_asrt_eq in H16;eauto.\n  unfold sat in H16;fold sat in H16;mytac.\n  simpl in H16.\n  destruct H14.\n  rewrite <- Int.unsigned_zero in H12.\n  apply unsigned_inj in H12.\n  subst i.\n  assert (Int.repr\n            (BinInt.Z.of_nat (BinInt.Z.abs_nat (Int.unsigned m))) = m).\n  rewrite Nat2Z.inj_abs_nat.\n  rewrite Z.abs_eq.\n  apply Int.repr_unsigned.\n  lets H100:Int.unsigned_range m.\n  omega.\n\n  rewrite H9 in H.\n  lets Hf: mapstoval_loadbytes H.\n  auto.\n  destruct Hf.\n  destruct H12.\n  assert (loadbytes m0\n                    (x12,\n                     Int.unsigned\n                       (Int.add Int.zero\n                                (Int.mul (Int.repr (BinInt.Z.of_nat (typelen t))) m)))\n                    (typelen t) = Some x2).\n  eapply loadbytes_local;eauto.\n  eapply loadbytes_local;eauto.\n  unfold load;unfold loadm.\n  simpl addr_to_addrval.\n  simpl.\n  rewrite Int.repr_unsigned.\n  rewrite H18.\n\n  destruct t;auto;simpl in Htv;tryfalse; rewrite H14;auto.\n  eapply int_Z_ltu;eauto.\n  destruct H.\n  rewrite H.\n  rewrite H0.\n  erewrite array_asrt_eq in H16;eauto.\n  unfold sat in H16;fold sat in H16;mytac.\n  simpl in H16.\n  destruct H14.\n  rewrite <- Int.unsigned_zero in H12.\n  apply unsigned_inj in H12.\n  subst i.\n  assert (Int.repr\n            (BinInt.Z.of_nat (BinInt.Z.abs_nat (Int.unsigned m))) = m).\n  rewrite Nat2Z.inj_abs_nat.\n  rewrite Z.abs_eq.\n  apply Int.repr_unsigned.\n  lets H100:Int.unsigned_range m.\n  omega.\n  rewrite H9 in H.\n  lets Hf: mapstoval_loadbytes H.\n  auto.\n  destruct Hf.\n  destruct H12.\n  assert (loadbytes m0\n                    (x12,\n                     Int.unsigned\n                       (Int.add Int.zero\n                                (Int.mul (Int.repr (BinInt.Z.of_nat (typelen t))) m)))\n                    (typelen t) = Some x2).\n  eapply loadbytes_local;eauto.\n  eapply loadbytes_local;eauto.\n  unfold load;unfold loadm.\n  simpl addr_to_addrval.\n  simpl.\n  rewrite Int.repr_unsigned.\n  rewrite H18.\n  destruct t;auto;simpl in Htv;tryfalse; rewrite H14;auto.\n  eapply int_Z_ltu;eauto.\n  rewrite H.\n  rewrite H0.\n  erewrite array_asrt_eq in H16;eauto.\n  unfold sat in H16;fold sat in H16;mytac.\n  simpl in H16.\n  destruct H14.\n  rewrite <- Int.unsigned_zero in H12.\n  apply unsigned_inj in H12.\n  subst i.\n  assert (Int.repr\n            (BinInt.Z.of_nat (BinInt.Z.abs_nat (Int.unsigned m))) = m).\n  rewrite Nat2Z.inj_abs_nat.\n  rewrite Z.abs_eq.\n  apply Int.repr_unsigned.\n  lets H100:Int.unsigned_range m.\n  omega.\n\n  rewrite H9 in H.\n  lets Hf: mapstoval_loadbytes H.\n  auto.\n  destruct Hf.\n  destruct H12.\n  assert (loadbytes m0\n                    (x12,\n                     Int.unsigned\n                       (Int.add Int.zero\n                                (Int.mul (Int.repr (BinInt.Z.of_nat (typelen t))) m)))\n                    (typelen t) = Some x2).\n  eapply loadbytes_local;eauto.\n  eapply loadbytes_local;eauto.\n  unfold load;unfold loadm.\n  simpl addr_to_addrval.\n  simpl.\n  rewrite Int.repr_unsigned.\n  rewrite H18.\n  destruct t;auto;simpl in Htv;tryfalse; rewrite H14;auto.\n  eapply int_Z_ltu;eauto.\n  destruct o as [[[[]]]].\n  simpl in *;mytac.\n  rewrite H11.\n  rewrite H6.\n  destruct H1.\n  rewrite H.\n  auto.\n  destruct H;rewrite H;auto.\n  auto.\nQed.\n\nTheorem array_member_rv'' :\n  forall s x t t' te2 vl n m v e2 P,\n    s |= LAarray x t' vl ** P ->\n    t' = Tarray t n ->\n    s |= Rv e2 @ te2  == Vint32 m ->\n    te2 = Tint8 \\/ te2 = Tint16 \\/ te2 = Tint32 ->\n    Int.ltu m (Int.repr (BinInt.Z_of_nat n)) = true  ->\n    nth_val (BinInt.Z.abs_nat (Int.unsigned m)) vl = Some v ->\n    (*v<> Vundef ->*)\n    rule_type_val_match t v =true->\n    s |= Rv (earrayelem (evar x) e2) @ t == v.\nProof.\n  intros.\n  unfold LAarray in H.\n  unfold Alvarenv' in H.\n  sep normal in H; sep destruct H.\n  subst t'.\n  eapply array_member_rv'; eauto.\n  unfold Int.ltu.\n  rewrite Int.unsigned_zero.\n  remember (zlt (Int.unsigned m) 0 ) as X.\n  destruct X.\n  clear -l.\n  lets H100:Int.unsigned_range m.\n  omega.\n  auto.\nQed.\n\n\nTheorem array_member_rv :\n  forall s x t t' te2 vl n m e2 v P,\n    s |= LAarray x t' vl ** P ->\n    t' = Tarray t n ->\n    s |= Rv e2 @ te2  == Vint32 m ->\n    te2 = Tint8 \\/ te2 = Tint16 \\/ te2 = Tint32 ->\n    (Z.of_nat n < 4294967295)%Z -> \n    (Int.unsigned m < Z.of_nat n)%Z ->\n    (Int.unsigned m < Z.of_nat (length vl))%Z ->\n    rule_type_val_match t v = true ->\n    nth_val' (Z.to_nat (Int.unsigned m)) vl = v ->\n    s |= Rv (earrayelem (evar x) e2) @ t == v.\nProof.\n  intros.\n  subst v.\n  eapply array_member_rv''; eauto.\n  unfold Int.ltu.\n  rewrite Int.unsigned_repr.\n  apply zlt_true.\n  auto.\n  split; try omega.\n  unfold Int.max_unsigned.\n  unfold Int.modulus.\n  unfold two_power_nat, Int.wordsize.\n  unfold shift_nat, Wordsize_32.wordsize.\n  unfold nat_rect.\n  omega.\n  apply nth_val_imp_nth_val'_1; auto.\nQed.\n(*\n  apply array_type_vallist_match_imp_rule_type_val_match; auto.\n  apply Nat2Z.inj_lt.\n  rewrite Z2Nat.id.\n  auto.\n  lets H100 : Int.unsigned_range m.\n  omega.\nQed.\n *)\n\nTheorem array_member_rv_g' :\n  forall s x t te2 l vl n m v e2 P,\n    s |= (A_notin_lenv x ** Agvarenv x (Tarray t n) (addrval_to_addr l)) ** Aarray l (Tarray t n) vl ** P->\n    s |= Rv e2 @ te2  == Vint32 m ->\n    te2 = Tint8 \\/ te2 = Tint16 \\/ te2 = Tint32 ->\n    Int.ltu m Int.zero = false ->\n    Int.ltu m (Int.repr (BinInt.Z_of_nat n)) =true  ->\n    nth_val (BinInt.Z.abs_nat (Int.unsigned m)) vl = Some v ->\n    (*    v<> Vundef -> *)\n    rule_type_val_match t v = true->\n    s |= Rv (earrayelem (evar x) e2) @ t == v.\nProof.\n  intros.\n  rename H5 into Htv.\n  assert (v<>Vundef).\n  eapply rule_type_val_match_nvundef;eauto.\n  destruct s as ((o&O)&aop).\n  destruct l as (b&i).\n  unfold sat in *;fold sat in *;mytac.\n  unfold substmo in *.\n  destruct o as [[[[]]]].\n  unfold substaskst in *.\n  unfold getsmem in *.\n  unfold getmem in *.\n  unfold get_smem in *.\n  unfold get_mem in *.\n  simpl in *;mytac.\n  apply EnvMod.nindom_get in  H21.\n  unfold get in *; simpl in *.\n  rewrite H21.\n  rewrite H22.\n  rewrite H6.\n  destruct H1.\n  rewrite H.\n  rewrite H0.\n  erewrite array_asrt_eq in H16;eauto.\n  unfold sat in H16;fold sat in H16;mytac.\n  simpl in H12.\n  destruct H12.\n  rewrite <- Int.unsigned_zero in H9.\n  apply unsigned_inj in H9.\n\n  subst i.\n  assert (Int.repr\n            (BinInt.Z.of_nat (BinInt.Z.abs_nat (Int.unsigned m))) = m).\n  rewrite Nat2Z.inj_abs_nat.\n  rewrite Z.abs_eq.\n  apply Int.repr_unsigned.\n  lets H100:Int.unsigned_range m.\n  omega.\n  rewrite H9 in H.\n  lets Hf: mapstoval_loadbytes H.\n  auto.\n  destruct Hf.\n  destruct H10.\n  assert (loadbytes m0\n                    (x18,\n                     Int.unsigned\n                       (Int.add Int.zero\n                                (Int.mul (Int.repr (BinInt.Z.of_nat (typelen t))) m)))\n                    (typelen t) = Some x2).\n  eapply loadbytes_local;eauto.\n  eapply loadbytes_local;eauto.\n  unfold load;unfold loadm.\n  simpl addr_to_addrval.\n  simpl.\n  rewrite Int.repr_unsigned.\n  rewrite H16.\n  destruct t;auto;simpl in Htv;tryfalse; rewrite H12;auto.\n\n  eapply int_Z_ltu;eauto.\n  destruct H.\n  rewrite H.\n  rewrite H0.\n  erewrite array_asrt_eq in H16;eauto.\n  unfold sat in H16;fold sat in H16;mytac.\n  simpl in H12.\n  destruct H12.\n  rewrite <- Int.unsigned_zero in H9.\n  apply unsigned_inj in H9.\n  subst i.\n  assert (Int.repr\n            (BinInt.Z.of_nat (BinInt.Z.abs_nat (Int.unsigned m))) = m).\n  rewrite Nat2Z.inj_abs_nat.\n  rewrite Z.abs_eq.\n  apply Int.repr_unsigned.\n  lets H100:Int.unsigned_range m.\n  omega.\n  rewrite H9 in H.\n  lets Hf: mapstoval_loadbytes H.\n  auto.\n  destruct Hf.\n  destruct H10.\n  assert (loadbytes m0\n                    (x18,\n                     Int.unsigned\n                       (Int.add Int.zero\n                                (Int.mul (Int.repr (BinInt.Z.of_nat (typelen t))) m)))\n                    (typelen t) = Some x2).\n  eapply loadbytes_local;eauto.\n  eapply loadbytes_local;eauto.\n  unfold load;unfold loadm.\n  simpl addr_to_addrval.\n  simpl.\n  rewrite Int.repr_unsigned.\n  rewrite H16.\n  destruct t;auto;simpl in Htv;tryfalse; rewrite H12;auto.\n  eapply int_Z_ltu;eauto.\n  rewrite H.\n  rewrite H0.\n  erewrite array_asrt_eq in H16;eauto.\n  unfold sat in H16;fold sat in H16;mytac.\n  simpl in H12.\n  destruct H12.\n  rewrite <- Int.unsigned_zero in H9.\n  apply unsigned_inj in H9.\n  subst i.\n  assert (Int.repr\n            (BinInt.Z.of_nat (BinInt.Z.abs_nat (Int.unsigned m))) = m).\n  rewrite Nat2Z.inj_abs_nat.\n  rewrite Z.abs_eq.\n  apply Int.repr_unsigned.\n  lets H100:Int.unsigned_range m.\n  omega.\n  rewrite H9 in H.\n  lets Hf: mapstoval_loadbytes H.\n  auto.\n  destruct Hf.\n  destruct H10.\n  assert (loadbytes m0\n                    (x18,\n                     Int.unsigned\n                       (Int.add Int.zero\n                                (Int.mul (Int.repr (BinInt.Z.of_nat (typelen t))) m)))\n                    (typelen t) = Some x2).\n  eapply loadbytes_local;eauto.\n  eapply loadbytes_local;eauto.\n  unfold load;unfold loadm.\n  simpl addr_to_addrval.\n  simpl.\n  rewrite Int.repr_unsigned.\n  rewrite H16.\n  destruct t;auto;simpl in Htv;tryfalse; rewrite H12;auto.\n  eapply int_Z_ltu;eauto.\n  destruct o as [[[[]]]].\n  simpl in *;mytac.\n  apply EnvMod.nindom_get in  H21.\n  unfold get in *; simpl in *.\n  rewrite H21.\n  rewrite H22.\n  rewrite H6.\n  destruct H1.\n  rewrite H.\n  auto.\n  destruct H;rewrite H;auto.\n  auto.\nQed.\n\n\n\n\nTheorem array_member_rv_g'' :\n  forall s ls x t t' te2 vl n m v e2 P,\n    s |= A_dom_lenv ls ** GAarray x t' vl ** P->\n    var_notin_dom x ls = true ->\n    t' = Tarray t n ->\n    s |= Rv e2 @ te2  == Vint32 m ->\n    te2 = Tint8 \\/ te2 = Tint16 \\/ te2 = Tint32 ->\n    Int.ltu m (Int.repr (BinInt.Z_of_nat n)) =true  ->\n    nth_val (BinInt.Z.abs_nat (Int.unsigned m)) vl = Some v ->\n    (*v<> Vundef ->*)\n    rule_type_val_match t v = true->\n    s |= Rv (earrayelem (evar x) e2) @ t == v.\nProof.\n  intros.\n  unfold GAarray in H; unfold Agvarenv' in H.\n  sep normal in H; sep destruct H.\n  subst t'.\n  eapply array_member_rv_g'; eauto.\n  sep normal.\n  eapply dom_lenv_imp_notin_lenv; eauto.\n  sep auto.\n  unfold Int.ltu.\n  rewrite Int.unsigned_zero.\n  remember (zlt (Int.unsigned m) 0 ) as X.\n  destruct X.\n  clear -l.\n  lets H100:Int.unsigned_range m.\n  omega.\n  auto.\nQed.\n\n\nTheorem array_member_rv_g :\n  forall s ls x t t' te2 vl n m e2 v P vm,\n    s |= A_dom_lenv ls ** GAarray x t' vl ** P->\n    var_notin_dom x ls = true ->\n    t' = Tarray t n ->\n    s |= Rv e2 @ te2  == vm ->\n    vm = Vint32 m ->\n    te2 = Tint8 \\/ te2 = Tint16 \\/ te2 = Tint32 ->\n    (Z.of_nat n < 4294967295)%Z ->\n    (Int.unsigned m < Z.of_nat n)%Z ->\n    (Int.unsigned m < Z.of_nat (length vl))%Z ->\n    rule_type_val_match t v = true ->\n    nth_val' (Z.to_nat (Int.unsigned m)) vl = v ->\n    s |= Rv (earrayelem (evar x) e2) @ t == v.\nProof.\n  intros.\n  subst vm.\n  subst v.\n  eapply array_member_rv_g''; eauto.\n  unfold Int.ltu.\n  rewrite Int.unsigned_repr.\n  apply zlt_true.\n  auto.\n  auto.\n  split; try omega.\n  unfold Int.max_unsigned.\n  unfold Int.modulus.\n  unfold two_power_nat, Int.wordsize.\n  unfold shift_nat, Wordsize_32.wordsize.\n  unfold nat_rect.\n  omega.\n  apply nth_val_imp_nth_val'_1; auto.\nQed.\n(*\n  apply array_type_vallist_match_imp_rule_type_val_match; auto.\n  apply Nat2Z.inj_lt.\n  rewrite Z2Nat.id.\n  auto.\n  lets H100 : Int.unsigned_range m.\n  omega.\nQed.\n *)\nTheorem expr_array_member_rv' :\n  forall s e1 t te1 te2 l vl n m v e2 P,\n    s |= Aarray l (Tarray t n) vl ** P ->\n    s |= Rv e1 @ te1  == Vptr l ->\n    s |= Rv e2 @ te2  == Vint32 m ->\n    te2 = Tint8 \\/ te2 = Tint16 \\/ te2 = Tint32 ->\n    Int.ltu m Int.zero = false ->\n    Int.ltu m (Int.repr (BinInt.Z_of_nat n)) = true  ->\n    nth_val (BinInt.Z.abs_nat (Int.unsigned m)) vl = Some v ->\n    rule_type_val_match t v =true->\n    te1 = Tarray t n \\/ te1 = Tptr t ->\n    s |= Rv (earrayelem e1 e2) @ t == v.\nProof.\n  intros.\n  rename H6 into Htv.\n  rename H7 into Hte1.\n  assert (v<> Vundef).\n  eapply rule_type_val_match_nvundef;eauto.\n  destruct s as ((o&O)&aop).\n  destruct l as (b&i).\n  unfold sat in *;fold sat in *;mytac.\n  unfold substmo in *.\n  destruct o as [[[[]]]].\n  unfold substaskst in *.\n  unfold getsmem in *.\n  unfold getmem in *.\n  unfold get_smem in *.\n  unfold get_mem in *.\n  simpl in *;mytac.\n  rewrite H9.\n  rewrite H7.\n  rewrite H0.\n  rewrite H1.\n\n  destruct Hte1;destruct te1;tryfalse.\n  destruct H2.\n  subst te2.\n  inverts H.\n  erewrite array_asrt_eq in H14;eauto.\n  unfold sat in H14;fold sat in H14;mytac.\n  simpl in H17.\n  destruct H16.\n  simpl in H.\n\n  lets Hf: mapstoval_loadbytes H.\n  auto.\n  destruct Hf.\n  destruct H16.\n  assert (loadbytes m0\n                    (b,\n                     Int.unsigned\n                       (Int.add i\n                                (Int.mul (Int.repr (Z.of_nat (typelen t)))\n                                         (Int.repr (Z.of_nat (Z.abs_nat (Int.unsigned m)))))))\n                    (typelen t) = Some x5 ).\n  eapply loadbytes_local;eauto.\n  eapply loadbytes_local;eauto.\n  rewrite Nat2Z.inj_abs_nat in H19.\n  rewrite Z.abs_eq in H19.\n  rewrite Int.repr_unsigned in H19.\n  unfold load;unfold loadm.\n  simpl addr_to_addrval.\n  simpl.\n  rewrite Int.repr_unsigned.\n  rewrite H19.\n  destruct t;auto;simpl in Htv;tryfalse; rewrite H18;auto.\n  lets H100:Int.unsigned_range m.\n  omega.\n  eapply int_Z_ltu;eauto.\n\n  destruct H2;subst te2.\n  inverts H.\n  erewrite array_asrt_eq in H14;eauto.\n  unfold sat in H14;fold sat in H14;mytac.\n  simpl in H17.\n  destruct H16.\n  simpl in H.\n\n  lets Hf: mapstoval_loadbytes H.\n  auto.\n  destruct Hf.\n  destruct H16.\n  assert (loadbytes m0\n                    (b,\n                     Int.unsigned\n                       (Int.add i\n                                (Int.mul (Int.repr (Z.of_nat (typelen t)))\n                                         (Int.repr (Z.of_nat (Z.abs_nat (Int.unsigned m)))))))\n                    (typelen t) = Some x5 ).\n  eapply loadbytes_local;eauto.\n  eapply loadbytes_local;eauto.\n  rewrite Nat2Z.inj_abs_nat in H19.\n  rewrite Z.abs_eq in H19.\n  rewrite Int.repr_unsigned in H19.\n  unfold load;unfold loadm.\n  simpl addr_to_addrval.\n  simpl.\n  rewrite Int.repr_unsigned.\n  rewrite H19.\n  destruct t;auto;simpl in Htv;tryfalse; rewrite H18;auto.\n  lets H100:Int.unsigned_range m.\n  omega.\n  eapply int_Z_ltu;eauto.\n\n  inverts H.\n  erewrite array_asrt_eq in H14;eauto.\n  unfold sat in H14;fold sat in H14;mytac.\n  simpl in H17.\n  destruct H16.\n  simpl in H.\n\n  lets Hf: mapstoval_loadbytes H.\n  auto.\n  destruct Hf.\n  destruct H16.\n  assert (loadbytes m0\n                    (b,\n                     Int.unsigned\n                       (Int.add i\n                                (Int.mul (Int.repr (Z.of_nat (typelen t)))\n                                         (Int.repr (Z.of_nat (Z.abs_nat (Int.unsigned m)))))))\n                    (typelen t) = Some x5 ).\n  eapply loadbytes_local;eauto.\n  eapply loadbytes_local;eauto.\n  rewrite Nat2Z.inj_abs_nat in H19.\n  rewrite Z.abs_eq in H19.\n  rewrite Int.repr_unsigned in H19.\n  unfold load;unfold loadm.\n  simpl addr_to_addrval.\n  simpl.\n  rewrite Int.repr_unsigned.\n\n  rewrite H19.\n\n  destruct t;auto;simpl in Htv;tryfalse; rewrite H18;auto.\n  lets H100:Int.unsigned_range m.\n  omega.\n  eapply int_Z_ltu;eauto.\n\n  destruct H2.\n  subst te2.\n  inverts H.\n  erewrite array_asrt_eq in H14;eauto.\n  unfold sat in H14;fold sat in H14;mytac.\n  simpl in H17.\n  destruct H16.\n  simpl in H.\n\n  lets Hf: mapstoval_loadbytes H.\n  auto.\n  destruct Hf.\n  destruct H16.\n  assert (loadbytes m0\n                    (b,\n                     Int.unsigned\n                       (Int.add i\n                                (Int.mul (Int.repr (Z.of_nat (typelen t)))\n                                         (Int.repr (Z.of_nat (Z.abs_nat (Int.unsigned m)))))))\n                    (typelen t) = Some x5 ).\n  eapply loadbytes_local;eauto.\n  eapply loadbytes_local;eauto.\n  rewrite Nat2Z.inj_abs_nat in H19.\n  rewrite Z.abs_eq in H19.\n  rewrite Int.repr_unsigned in H19.\n  unfold load;unfold loadm.\n  simpl addr_to_addrval.\n  simpl.\n  rewrite Int.repr_unsigned.\n\n  rewrite H19.\n\n  destruct t;auto;simpl in Htv;tryfalse; rewrite H18;auto.\n  lets H100:Int.unsigned_range m.\n  omega.\n  eapply int_Z_ltu;eauto.\n\n  destruct H2;subst te2.\n  inverts H.\n  erewrite array_asrt_eq in H14;eauto.\n  unfold sat in H14;fold sat in H14;mytac.\n  simpl in H17.\n  destruct H16.\n  simpl in H.\n\n  lets Hf: mapstoval_loadbytes H.\n  auto.\n  destruct Hf.\n  destruct H16.\n  assert (loadbytes m0\n                    (b,\n                     Int.unsigned\n                       (Int.add i\n                                (Int.mul (Int.repr (Z.of_nat (typelen t)))\n                                         (Int.repr (Z.of_nat (Z.abs_nat (Int.unsigned m)))))))\n                    (typelen t) = Some x5 ).\n  eapply loadbytes_local;eauto.\n  eapply loadbytes_local;eauto.\n  rewrite Nat2Z.inj_abs_nat in H19.\n  rewrite Z.abs_eq in H19.\n  rewrite Int.repr_unsigned in H19.\n  unfold load;unfold loadm.\n  simpl addr_to_addrval.\n  simpl.\n  rewrite Int.repr_unsigned.\n\n  rewrite H19.\n\n  destruct t;auto;simpl in Htv;tryfalse; rewrite H18;auto.\n  lets H100:Int.unsigned_range m.\n  omega.\n  eapply int_Z_ltu;eauto.\n\n\n\n\n  inverts H.\n  erewrite array_asrt_eq in H14;eauto.\n  unfold sat in H14;fold sat in H14;mytac.\n  simpl in H17.\n  destruct H16.\n  simpl in H.\n\n  lets Hf: mapstoval_loadbytes H.\n  auto.\n  destruct Hf.\n  destruct H16.\n  assert (loadbytes m0\n                    (b,\n                     Int.unsigned\n                       (Int.add i\n                                (Int.mul (Int.repr (Z.of_nat (typelen t)))\n                                         (Int.repr (Z.of_nat (Z.abs_nat (Int.unsigned m)))))))\n                    (typelen t) = Some x5 ).\n  eapply loadbytes_local;eauto.\n  eapply loadbytes_local;eauto.\n  rewrite Nat2Z.inj_abs_nat in H19.\n  rewrite Z.abs_eq in H19.\n  rewrite Int.repr_unsigned in H19.\n  unfold load;unfold loadm.\n  simpl addr_to_addrval.\n  simpl.\n  rewrite Int.repr_unsigned.\n\n  rewrite H19.\n\n  destruct t;auto;simpl in Htv;tryfalse; rewrite H18;auto.\n  lets H100:Int.unsigned_range m.\n  omega.\n  eapply int_Z_ltu;eauto.\n\n\n  destruct o as [[[[]]]].\n  simpl in *;mytac.\n  rewrite H9.\n  rewrite H7.\n  destruct Hte1;destruct H2;subst;auto.\n  destruct H2;subst;auto.\n  destruct H2;subst;auto.\n  auto.\nQed.\n\n\nTheorem expr_array_member_rv :\n  forall  s e1 t te1 te2 l vl n m v e2 P,\n    s |= Rv e1 @ te1  == Vptr l ->\n    s |= Aarray l (Tarray t n) vl ** P ->\n    s |= Rv e2 @ te2  == Vint32 m ->\n    te1 = Tarray t n \\/ te1 = Tptr t ->\n    te2 = Tint8 \\/ te2 = Tint16 \\/ te2 = Tint32 ->\n    (Z.of_nat n < 4294967295)%Z -> \n    (Int.unsigned m < Z.of_nat n)%Z ->\n    (Int.unsigned m < Z.of_nat (length vl))%Z ->\n    rule_type_val_match t v = true ->\n    nth_val' (Z.to_nat (Int.unsigned m)) vl = v ->\n    s |= Rv (earrayelem e1 e2) @ t == v.\nProof.\n  intros.\n  subst v.\n  eapply expr_array_member_rv'; eauto.\n  unfold Int.ltu.\n  rewrite Int.unsigned_zero.\n  apply zlt_false.\n  lets Hx:Int.unsigned_range m.\n  omega.\n  unfold Int.ltu.\n  apply zlt_true.\n  rewrite Int.unsigned_repr;auto.\n  split; try omega.\n  unfold Int.max_unsigned.\n  unfold Int.modulus.\n  unfold two_power_nat, Int.wordsize.\n  unfold shift_nat, Wordsize_32.wordsize.\n  unfold nat_rect.\n  omega.\n  apply nth_val_imp_nth_val'_1; auto.\nQed.\n\n(*************************************************************)\n(*************************************************************)\n(*************************************************************)\nLemma struct_member_rv_flag: \n  forall s x id l off t t' P perm decl tid v perm1,\n    s |= LV x @ Tptr t |=> Vptr l @ perm1 ** PV (get_off_addr l off) @ t' |=> v @ perm ** P ->\n    t = Tstruct tid decl ->\n    good_decllist decl = true ->\n    ftype id decl = Some t' ->\n    field_offset id decl = Some off->\n    rule_type_val_match t' v = true ->\n    s |= Rv efield (ederef (evar x)) id @ t' == v.\nProof.\n  introv Hsa Ht Hg Hfi Hfs Hss.\n  destruct_s s.\n  simpl in *; mytac.\n  rewrite H14.\n  lets Hxx :  mapstoval_load  H15.\n  simpl; auto.\n  rewrite Hfi.\n  lets Hl : load_local H0 Hxx.\n  assert (Int.unsigned Int.zero = 0%Z).\n  clear. int auto.\n  rewrite H in Hl.\n  rewrite Hl.\n  destruct l.\n  lets Hxxx :  mapstoval_load H8; eauto.\n  unfold getoff.\n  simpl.\n  rewrite H14.\n  rewrite Hfs.\n  simpl.\n  simpl in Hxxx.\n  assert (Int.repr (Int.unsigned i2) = i2).\n  clear .\n  int auto.\n  rewrite H1.\n  assert (exists xx, join x6 xx m).\n  clear -H5 H0.\n  join auto.\n  clear H5 H0.\n  mytac.\n  eapply load_local; eauto.\n  rewrite H14; auto.\n  eapply rule_type_val_match_nvundef; eauto.\nQed.\n\n\nLemma struct_member_rv_flag_g:\n  forall s x id l off t t' P perm decl tid v ls perm1,\n    s |= A_dom_lenv ls ** GV x @ Tptr t |=> Vptr l @ perm1 ** PV (get_off_addr l off) @ t' |=> v @ perm ** P ->\n    var_notin_dom x ls = true ->\n    t = Tstruct tid decl ->\n    good_decllist decl = true ->\n    ftype id decl = Some t' ->\n    field_offset id decl = Some off->\n    rule_type_val_match t' v = true ->\n    s |= Rv efield (ederef (evar x)) id @ t' == v.\nProof.\n  introv Hsa Ht Hg Hfi Hfs Hss .\n  introv Hsf.\n  lets Hx :  dom_lenv_imp_notin_lenv Ht Hsa.\n  clear Hsa.\n  destruct_s s.\n  simpl in *; mytac.\n  apply EnvMod.nindom_get in H3;auto.\n  unfold get in *;simpl in *.\n  rewrite H3.\n  rewrite H19.\n  rewrite Hfs.\n  lets Hxx :  mapstoval_load  H20.\n  simpl; auto.\n  lets Hl : load_local H5 Hxx.\n  assert (Int.unsigned Int.zero = 0%Z).\n  clear. int auto.\n  rewrite H in Hl.\n  rewrite Hl.\n  destruct l.\n  lets Hxxx :  mapstoval_load H13; eauto.\n  unfold getoff.\n  simpl.\n  unfold get in *; simpl.\n  rewrite H3.\n  rewrite H19.\n  rewrite Hss.\n  assert (Int.repr (Int.unsigned i2) = i2).\n  clear .\n  int auto.\n  rewrite H0.\n  assert (exists xx, join x12 xx m).\n  clear -H5 H10.\n  join auto.\n  clear H5 H10.\n  mytac.\n  eapply load_local; eauto.\n  unfold get; simpl.\n  apply EnvMod.nindom_get in H3;auto.\n  rewrite H3; auto.\n  unfold get in *; simpl in H19.\n  rewrite H19.\n  auto.\n  eapply rule_type_val_match_nvundef; eauto.\nQed.  \n\n(*\n  apply array_type_vallist_match_imp_rule_type_val_match; auto.\n  apply Nat2Z.inj_lt.\n  rewrite Z2Nat.id.\n  auto.\n  lets H100 : Int.unsigned_range m.\n  omega.\nQed.\n *)\n\n\n(*************************************************************)\n(*************************************************************)\n(*************************************************************)\nTheorem struct_member_rv_g_typeneq:\n  forall s ls x t l vl tid decl n id t' v P perm tp  tid' decl',\n    s |= A_dom_lenv ls ** GV x @ (Tptr tp) |=> Vptr l @ perm ** Astruct l t vl ** P->\n    var_notin_dom x ls = true ->\n    tp = Tstruct tid' decl' -> \n    t = Tstruct tid decl ->\n    sub_decllist decl decl' =true -> \n    good_decllist decl = true ->\n    ftype id decl = Some t' ->\n    (forall ids dl, t' <> Tstruct ids dl) ->\n    (forall (t'0 : type) (n0 : nat), t' <> Tarray t'0 n0) ->\n    id_nth id decl = Some n ->\n    n < length vl ->\n    struct_type_vallist_match t vl ->\n    nth_val' n vl = v ->\n    s |= Rv (efield (ederef (evar x)) id) @ t' == v.\nProof.\n  intros.\n  destruct_s s.\n  eapply dom_lenv_imp_notin_lenv in H; eauto.\n  simpl in *;mytac.\n  apply EnvMod.nindom_get in H15;auto.\n  unfold get in *; simpl in *.\n  rewrite H15.\n  rewrite H30.\n  lets Hfs : sub_decllist_ftype H5; eauto.\n  rewrite Hfs.\n  unfold load;unfold loadm.\n  rewrite Int.unsigned_zero in H31.\n  lets Hf: mapstoval_loadbytes H31.\n  simpl;auto.\n  destruct Hf.\n  destruct H.\n  lets Hf: loadbytes_local H17 H.\n  assert (loadbytes m (x25, 0%Z) (typelen (Tptr (Tstruct tid' decl'))) = Some x0) by auto.\n  rewrite H2.\n  rewrite H1.\n  destruct l.\n  unfold getoff.\n  unfold evaltype.\n  unfold get ; simpl.\n  rewrite H15.\n  rewrite H30.\n  lets Hx : id_nth_eq H4 H8.\n  lets Hoff: nth_id_exists_off Hx.\n  destruct Hoff.\n  lets Hy: sub_decllist_offset H3 H11.\n  rewrite Hy.\n  assert (load t' x7 (addrval_to_addr (b, Int.add (Int.repr (Int.unsigned i2)) x1)) =\n          Some  (nth_val' n vl)).\n  unfold addrval_to_addr.\n  lets Hz: nth_val_imp_nth_val'_2 H9.\n  rewrite struct_asrt_eq with (n:=n) in H25;eauto.\n  unfold sat in H25;fold sat in H25;mytac.\n  simpl in H13.\n  rewrite Int.repr_unsigned.\n  simpl in H18.\n  eapply load_local;eauto.\n  eapply load_local;eauto.\n  eapply mapstoval_load;auto.\n  eapply struct_tvmatch_imp_rule_tvmatch;eauto.\n  destruct H18;eauto.\n  apply map_join_comm in H17.\n  eapply load_local;eauto.\n  apply EnvMod.nindom_get in  H15.\n  unfold get in *; simpl in *.\n  rewrite H15.\n  rewrite H30.\n  eapply sub_decllist_ftype;eauto.\n  eapply rule_type_val_match_nvundef;eauto.\n  eapply struct_tvmatch_imp_rule_tvmatch;eauto.\nQed.\n\n\n\n\nTheorem struct_member_rv_typeneq:\n  forall s x t l vl tid decl n id t' v P perm tp  tid' decl',\n    s |= LV x @ (Tptr tp) |=> Vptr l @ perm ** Astruct l t vl ** P->\n    tp = Tstruct tid' decl' -> \n    t = Tstruct tid decl ->\n    sub_decllist decl decl' =true -> \n    good_decllist decl = true ->\n    ftype id decl = Some t' ->\n    (forall ids dl, t' <> Tstruct ids dl) ->\n    (forall (t'0 : type) (n0 : nat), t' <> Tarray t'0 n0) ->\n    id_nth id decl = Some n ->\n    n < length vl ->\n    struct_type_vallist_match t vl ->\n    nth_val' n vl = v ->\n    s |= Rv (efield (ederef (evar x)) id) @ t' == v.\nProof.\n  intros.\n  destruct_s s.\n  simpl in *;mytac.\n  unfold get in *; simpl in *.\n  rewrite H24.\n  lets Hfs : sub_decllist_ftype H4; eauto.\n  rewrite Hfs.\n  unfold load;unfold loadm.\n  rewrite Int.unsigned_zero in H25.\n  lets Hf: mapstoval_loadbytes H25.\n  simpl;auto.\n  destruct Hf.\n  destruct H.\n  lets Hf: loadbytes_local H11 H.\n  assert (loadbytes m (x19, 0%Z) (typelen (Tptr (Tstruct tid' decl'))) = Some x2) by auto.\n  rewrite H1.\n  rewrite H0.\n  destruct l.\n  unfold getoff.\n  unfold evaltype.\n  unfold get ; simpl.\n  rewrite H24.\n  lets Hx : id_nth_eq H3 H7.\n  lets Hoff: nth_id_exists_off Hx.\n  destruct Hoff.\n  lets Hy: sub_decllist_offset H2 H10.\n  rewrite Hy.\n  assert (load t' x1 (addrval_to_addr (b, Int.add (Int.repr (Int.unsigned i2)) x3)) =\n          Some  (nth_val' n vl)).\n  unfold addrval_to_addr.\n  lets Hz: nth_val_imp_nth_val'_2 H8.\n  rewrite struct_asrt_eq with (n:=n) in H19;eauto.\n  unfold sat in H19;fold sat in H19;mytac.\n  simpl in H13.\n  rewrite Int.repr_unsigned.\n  simpl in H17.\n  apply map_join_comm in H11.\n  eapply load_local;eauto.\n  eapply load_local;eauto.\n  eapply mapstoval_load;auto.\n  eapply struct_tvmatch_imp_rule_tvmatch;eauto.\n  destruct H17;eauto.\n  apply map_join_comm in H11.\n  eapply load_local;eauto.\n  rewrite H24.\n  eapply sub_decllist_ftype;eauto.\n  eapply rule_type_val_match_nvundef;eauto.\n  eapply struct_tvmatch_imp_rule_tvmatch;eauto.\nQed.\n\n\nTheorem struct_member_array_rv_g_typeneq:\n  forall s ls x t l vl tid decl id t' n P ad perm tt tid' decl',\n    s |=   A_dom_lenv ls **  GV x @ (Tptr tt) |=> Vptr l @ perm ** Astruct l t vl ** P->\n    var_notin_dom x ls = true ->\n    tt = Tstruct tid' decl' -> \n    t = Tstruct tid decl ->\n    sub_decllist decl decl'  = true-> \n    ftype id decl = Some (Tarray t' n) ->\n    id_addrval l id t = Some ad ->\n    s |= Rv (efield (ederef (evar x)) id) @ (Tarray t' n) == Vptr ad.\nProof.\n  intros.\n  destruct_s s.\n  eapply dom_lenv_imp_notin_lenv in H; eauto.\n  simpl in *;mytac.\n  apply EnvMod.nindom_get in H9;auto.\n  unfold get in *; simpl in *.\n  rewrite H9.\n  rewrite H24.\n  lets Hfs : sub_decllist_ftype H4; eauto.\n  rewrite Hfs.\n  unfold load;unfold loadm.\n  rewrite Int.unsigned_zero in H25.\n  lets Hf: mapstoval_loadbytes H25.\n  simpl;auto.\n  destruct Hf.\n  destruct H.\n  lets Hf: loadbytes_local H11 H.\n  assert ( loadbytes m (x25, 0%Z) (typelen (Tptr (Tstruct tid' decl'))) = Some x0);auto.\n  rewrite H2.\n  rewrite H1.\n  destruct l.\n  unfold getoff.\n  unfold evaltype.\n  unfold get ; simpl.\n  rewrite H9;rewrite H24.\n  unfold id_addrval in H5.\n  remember (field_offset id decl ) as X.\n  destruct X;tryfalse.\n  apply eq_sym in HeqX.\n  lets Hac :  sub_decllist_offset HeqX; eauto.\n  rewrite Hac.\n  rewrite Int.repr_unsigned.\n  simpl.\n  rewrite Int.repr_unsigned.\n  inverts H5;auto.\n  apply EnvMod.nindom_get in H9;auto.\n  unfold get in *; simpl in *.\n  rewrite H9;rewrite H24.\n  eapply sub_decllist_ftype; eauto.\n  intro; tryfalse.\nQed.\n\n\nLemma struct_member_array_rv_typeneq\n     : forall s x t l vl tid decl id t' n P ad perm tt decl' tid',\n       s\n       |= LV x @ Tptr tt |=> Vptr l @ perm ** Astruct l t vl ** P ->\n       tt = Tstruct tid' decl' ->\n       t = Tstruct tid decl ->\n       sub_decllist decl decl' = true ->\n       ftype id decl = Some (Tarray t' n) ->\n       id_addrval l id t = Some ad ->\n       s |= Rv efield (ederef (evar x)) id @ Tarray t' n == Vptr ad.\nProof.\n  intros.\n  destruct_s s.\n  simpl in *;mytac.\n  rewrite H18.\n  lets Hx: sub_decllist_ftype H2 H3.\n  rewrite Hx.\n  unfold load;unfold loadm.\n  rewrite Int.unsigned_zero in H19.\n  lets Hf: mapstoval_loadbytes H19.\n  simpl;auto.\n  destruct Hf.\n  destruct H.\n  lets Hf: loadbytes_local H5 H.\n  assert ( loadbytes m (x19, 0%Z) (typelen (Tptr (Tstruct tid' decl'))) = Some x2);auto.\n  rewrite H1.\n  rewrite H0.\n  destruct l.\n  unfold getoff.\n  unfold evaltype.\n  rewrite H18.\n  unfold id_addrval in H4.\n  remember (field_offset id decl ) as X.\n  destruct X;tryfalse.\n  rewrite Int.repr_unsigned.\n  symmetry in HeqX.\n  lets Hy: sub_decllist_offset H2 HeqX.\n  rewrite Hy.\n  simpl.\n  rewrite Int.repr_unsigned.\n  inverts H4;auto.\n  rewrite H18.\n  eapply sub_decllist_ftype;eauto.\n  intro; tryfalse.\nQed.\n\nTheorem struct_member_rv_general_typeneq:\n  forall s  x t l vl tid decl id P v t' perm tp tid' decl',\n    s |=  LV x @ (Tptr tp) |=> Vptr l @ perm ** Astruct l t vl ** P->\n    t = Tstruct tid decl ->\n\n    tp = Tstruct tid' decl' ->\n    sub_decllist decl decl' = true ->\n    \n    good_decllist decl = true ->\n    ftype id decl = Some t' -> \n    (\n      isarray_type t'-> \n      exists ad, id_addrval l id t = Some ad /\\ v = Vptr ad\n    ) ->\n    (\n      ~ isarray_type t' ->\n      (\n        exists n,\n          (forall a b, t' <> Tstruct a b) /\\\n          id_nth id decl = Some n /\\\n          n < length vl /\\\n          struct_type_vallist_match t vl /\\\n          nth_val' n vl = v \n      )\n    ) -> \n    s |= Rv (efield (ederef (evar x)) id) @ t' == v.\nProof.\n  intros.\n  mytac.\n  assert (isarray_type t' \\/ ~isarray_type t' ).\n  tauto.\n  destruct H0.\n  lets Hx: H5 H0.\n  mytac.\n  unfolds in H0;mytac.\n  eapply struct_member_array_rv_typeneq;eauto.\n  lets Hx : H6 H0.\n  mytac.\n  eapply struct_member_rv_typeneq;eauto.\n  unfold isarray_type in H0.\n  intros.\n  introv.\n  introv Hf.\n  apply H0;eauto.\nQed.\n\n\nTheorem struct_member_rv_g_general_typeneq:\n  forall s ls x t l vl tid decl id P v t' perm tp tid' decl',\n    s |=   A_dom_lenv ls **  GV x @ (Tptr tp) |=> Vptr l @ perm ** Astruct l t vl ** P->\n    var_notin_dom x ls = true ->\n    t = Tstruct tid decl ->\n    \n    tp = Tstruct tid' decl' ->\n    sub_decllist decl decl' = true ->\n    \n    good_decllist decl = true ->\n    ftype id decl = Some t' -> \n    (\n      isarray_type t'-> \n      exists ad, id_addrval l id t = Some ad /\\ v = Vptr ad\n    ) ->\n    (\n      ~ isarray_type t' ->\n      (\n        exists n,\n          (forall a b, t' <> Tstruct a b) /\\\n          id_nth id decl = Some n /\\\n          n < length vl /\\\n          struct_type_vallist_match t vl /\\\n          nth_val' n vl = v \n      )\n    ) -> \n    s |= Rv (efield (ederef (evar x)) id) @ t' == v.\nProof.\n  intros.\n  mytac.\n  assert (isarray_type t' \\/ ~isarray_type t' ).\n  tauto.\n  destruct H1.\n  lets Hx: H6 H1.\n  mytac.\n  unfolds in H1;mytac.\n  eapply struct_member_array_rv_g_typeneq;eauto.\n  lets Hx : H7 H1.\n  mytac.\n  eapply struct_member_rv_g_typeneq;eauto.\n  unfold isarray_type in H1.\n  intros.\n  introv.\n  introv Hf.\n  apply H1;eauto.\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/tactics/hoareforward/symbolic_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.25673128776194737}}
{"text": "Require Import compcert.lib.Axioms.\nRequire Export compcert.common.Errors.\nRequire Import liblayers.lib.ExtensionalityAxioms.\nRequire Export liblayers.lib.Functor.\nRequire Export liblayers.lib.Monad.\nRequire Import liblayers.lib.Decision.\nRequire Import liblayers.logic.Structures.\nRequire Import liblayers.logic.LayerData.\n\n\n(** * [res] is a monad *)\n\nGlobal Instance res_functor_ops: FunctorOps res :=\n  {\n    fmap A B f x := Errors.bind x (fun x => Errors.OK (f x))\n  }.\n\nGlobal Instance res_functor_prf: Functor res.\nProof.\n  split.\n  * intros A x.\n    destruct x; reflexivity.\n  * intros A B C f g x.\n    destruct x; reflexivity.\nQed.\n\nGlobal Instance res_monad_ops: MonadOps res :=\n  {\n    ret := Errors.OK;\n    bind A B f x := Errors.bind x f\n  }.\n\nGlobal Instance res_monad_prf: Monad res.\nProof.\n  split; try typeclasses eauto.\n  * intros A B f.\n    extensionality mx.\n    destruct mx; reflexivity.\n  * intros A B f x.\n    reflexivity.\n  * intros A mx.\n    destruct mx; reflexivity.\n  * intros A B C f g mx.\n    destruct mx; reflexivity.\nQed.\n\nGlobal Instance res_monad_inv_ret:\n  MonadInvRet res.\nProof.\n  intros A x y Hxy.\n  inversion Hxy.\n  reflexivity.\nQed.\n\nGlobal Instance res_monad_inv_bind:\n  MonadInvBind res.\nProof.\n  intros A B f ma b H.\n  unfold ret, bind in H; simpl in *.\n  destruct ma; try discriminate.\n  eauto.\nQed.\n\nLemma res_bind_error {A B} (f: A -> res B) msg:\n  bind f (Error msg) = Error msg.\nProof.\n  reflexivity.\nQed.\n\nHint Rewrite @res_bind_error : monad.\n\n(** * Lifting orders on [res] *)\n\n(** TODO: define [res_rel] as well? *)\n\n(** We need failure on top: <explain>. *)\n\nInductive res_le {A B} (R: rel A B): rel (res A) (res B) :=\n  | res_le_ok_def:\n      (R ++> res_le R)%rel (@OK A) (@OK B)\n  | res_le_error (msg: errmsg):\n      UpperBound (res_le R) (Error msg).\n\nGlobal Existing Instance res_le_error.\n\nGlobal Instance res_le_ok:\n  Monotonic (@OK) (forallr R, R ++> res_le R).\nProof.\n  exact @res_le_ok_def.\nQed.\n\nGlobal Instance res_le_bind:\n  Monotonic\n    (@Errors.bind)\n    (forallr RA, forallr RB, res_le RA ++> (RA ++> res_le RB) ++> res_le RB).\nProof.\n  unfold Errors.bind.\n  rauto.\nQed.\n\nGlobal Instance res_le_monad:\n  MonadRel (@res_le).\nProof.\n  split; simpl; rauto.\nQed.\n\nLocal Instance res_le_op `(Le): Le (res A) :=\n  { le := res_le (≤) }.\n\nGlobal Instance res_le_monotonic {A B}:\n  Monotonic (@res_le A B) (subrel ++> subrel).\nProof.\n  intros R1 R2 HR x y H.\n  destruct H; constructor.\n  apply HR; assumption.\nQed.\n\nGlobal Instance res_le_monotonic_params:\n  Params (@res_le) 3.\n\nLemma res_le_refl `(Reflexive):\n  Reflexive (res_le R).\nProof.\n  intros [x | msg].\n  - constructor; reflexivity.\n  - constructor.\nQed.\n\nHint Extern 1 (Reflexive (res_le _)) =>\n  apply res_le_refl : typeclass_instances.\n\nLemma res_le_trans `(Transitive):\n  Transitive (res_le R).\nProof.\n  intros x y z Hxy Hyz.\n  destruct Hxy as [x y Hxy | x msg].\n  - inversion Hyz.\n    + constructor.\n      transitivity y; trivial.\n    + constructor.\n  - inversion Hyz.\n    constructor.\nQed.\n\nHint Extern 1 (Transitive (res_le _)) =>\n  apply res_le_trans : typeclass_instances.\n\nGlobal Instance res_le_htrans {A B C} RAB RBC RAC:\n  HTransitive (A:=A) (B:=B) (C:=C) RAB RBC RAC ->\n  HTransitive (res_le RAB) (res_le RBC) (res_le RAC).\nProof.\n  intros HR x y z Hxy Hyz.\n  destruct Hyz as [ y z Hyz | ]; try constructor.\n  inversion Hxy as [ x' y' Hxy' | ]; subst; try constructor.\n  htransitivity y; assumption.\nQed.\n\nGlobal Instance res_le_rtrans {A B C} RAB RBC RAC:\n  RTransitive (A:=A) (B:=B) (C:=C) RAB RBC RAC ->\n  RTransitive (res_le RAB) (res_le RBC) (res_le RAC).\nProof.\n  intros HR x z Hxz.\n  destruct Hxz as [ a c Hac | ].\n  * apply rtransitivity in Hac.\n    destruct Hac as (b & Hab & Hbc).\n    exists (OK b).\n    split; constructor; assumption.\n  * exists (Error msg).\n    split; constructor.\nQed.\n\nGlobal Instance res_lower_bound {A B} (R: rel A B) (x: A):\n  LowerBound R x ->\n  LowerBound (res_le R) (OK x).\nProof.\n  intros H [y|m]; constructor.\n  apply lower_bound.\nQed.\n\n(** ** Data-indexed version *)\n\nLocal Instance res_sim_op `(Tsim: Sim): Sim _ (fun D => res (T D)) :=\n  { simRR D1 D2 R := res_le (sim R) }.\n\n(** I'm not sure if those are still necessary now that we use the\n  generalized [rel]. *)\n\nGlobal Instance OK_sim_monotonic `(Tsim: Sim):\n  Monotonic\n    (fun D => @OK (T D))\n    (forallr R, sim R ++> sim R).\nProof.\n  intros D1 D2 R.\n  apply res_le_ok.\nQed.\n\nGlobal Instance res_sim_bind {V E} {A B: V -> Type}:\n  forall (RA: sim_relation E A) (RB: sim_relation E B),\n    Monotonic\n      (fun (v : V) => bind (A := A v) (B := B v))\n      (forallr e @ v1 v2 : E,\n         (RA v1 v2 e ++> res_le (RB v1 v2 e)) ++>\n         (res_le (RA v1 v2 e) ++> res_le (RB v1 v2 e))).\nProof.\n  intros RA RB v1 v2 e.\n  intros f g Hfg x y Hxy.\n  destruct Hxy as [x y Hxy | y msg].\n  * monad_norm.\n    apply Hfg.\n    assumption.\n  * monad_norm.\n    constructor.\nQed.\n\nGlobal Instance res_sim_fmap {V E} {A B: V -> Type}:\n  forall (RA: sim_relation E A) (RB: sim_relation E B),\n    Monotonic\n      (fun (v : V) => fmap (A := A v) (B := B v))\n      (forallr e @ v1 v2 : E,\n         (RA v1 v2 e ++> RB v1 v2 e) ++>\n         (res_le (RA v1 v2 e) ++> res_le (RB v1 v2 e))).\nProof.\n  intros RA RB v1 v2 e.\n  intros f g Hfg x y Hxy.\n  destruct Hxy as [x y Hxy | y msg].\n  * monad_norm.\n    constructor.\n    apply Hfg.\n    assumption.\n  * monad_norm.\n    constructor.\nQed.\n\n\n(** * Orders for [res ∘ option] *)\n\nRequire Import OptionOrders.\n\nLemma res_option_le_ok_none {A} (R: relation A) (y: res (option A)):\n  res_le (option_le R) (OK None) y.\nProof.\n  apply lower_bound.\nQed.\n\nHint Resolve res_option_le_ok_none: liblayers.\n\n\n(** * Decision-related definitions *)\n\n(** ** The [res] version of [assert]. *)\n\nDefinition eassert (e: errmsg) P `{HP: Decision P}: res P :=\n  match decide P with\n    | left H => ret H\n    | right H => Error e\n  end.\n\nLemma eassert_inv `{Pdec: Decision} {A} m (f: P -> res A) (r: A):\n  bind f (eassert m P) = ret r <->\n  exists H, f H = ret r.\nProof.\n  unfold eassert.\n  destruct (decide P) as [HP | HP];\n  unfold bind; simpl.\n  * split; eauto.\n    intros [H Hf].\n    assert (H = HP) by apply proof_irr; congruence.\n  * split; try discriminate.\n    intros [H Hf].\n    tauto.\nQed.\n\nInstance eassert_le:\n  Monotonic eassert (⊤ ++> forallr P Q : flip impl, ⊤ ++> res_le ⊤).\nProof.\n  intros msg1 msg2 _ P Q HPQ Pdec Qdec _.\n  unfold eassert, flip, impl in *.\n  destruct (decide Q) as [HQ | HQ]; try constructor.\n  destruct (decide P) as [HP | HP]; try tauto.\n  constructor.\n  apply I.\nQed.\n\nHint Rewrite @eassert_inv using typeclasses eauto : monad.\n\n(** These tactics make it easy to reduce subexpressions of the form\n  [H <- eassert msg P; M] in the goal by proving or disproving [P]. *)\n\nLemma eassert_true msg P `{Pdec: Decision P}:\n  P -> exists H, eassert msg P = OK H.\nProof.\n  intros.\n  unfold eassert.\n  destruct (decide P); try contradiction.\n  eauto.\nDefined.\n\nLtac eassert_true_aux msg P Pdec :=\n  let H := fresh \"Hasserted\" in\n  let HH := fresh \"Hassert_eq\" in\n  destruct (eassert_true msg P (Pdec := Pdec)) as [H HH];\n    [ idtac (* The user will prove [P] *)\n    | rewrite !HH in *;\n      clear HH;\n      monad_norm;\n      try clear H ].\n\nLtac eassert_true :=\n  lazymatch goal with\n    | |- context [@eassert ?msg ?P ?Pdec] =>\n      eassert_true_aux msg P Pdec\n  end.\n\nLemma eassert_false msg P `{Pdec: Decision P}:\n  ~P -> eassert msg P = Error msg.\nProof.\n  intros.\n  unfold eassert.\n  destruct (decide P); try contradiction.\n  eauto.\nDefined.\n\nLtac eassert_false_aux msg P Pdec :=\n  let H := fresh in\n  assert (H: ~P);\n    [ idtac (* The user will prove [~P] *)\n    | rewrite !(eassert_false msg P (Pdec:=Pdec) H);\n      monad_norm;\n      clear H ].\n\nLtac eassert_false :=\n  lazymatch goal with\n    | |- context [@eassert ?msg ?P ?Pdec] =>\n      eassert_false_aux msg P Pdec\n  end.\n\n(** ** Whether a [res A] is [OK] or [Error] *)\n\nDefinition isOK {A} (x: res A): Prop :=\n  exists (a: A), x = OK a.\n\nDefinition isError {A} (x: res A): Prop :=\n  exists (m: errmsg), x = Error m.\n\nDefinition isOKNone {A} (x: res (option A)) :=\n  x = OK None.\n\nGlobal Instance isOK_dec {A} (x: res A): Decision (isOK x) :=\n  match x with\n    | OK _ => left _\n    | Error _ => right _\n  end.\nProof.\n  abstract (red; eauto).\n  abstract (intros [a Ha]; discriminate).\nDefined.\n\nGlobal Instance isError_dec {A} (x: res A): Decision (isError x) :=\n  match x with\n    | OK _ => right _\n    | Error _ => left _\n  end.\nProof.\n  abstract (intros [msg Hmsg]; discriminate).\n  abstract (red; eauto).\nDefined.\n\nGlobal Instance isOKNone_dec {A} (x: res (option A)):\n  Decision (isOKNone x) :=\n  match x with\n    | OK None => left _\n    | _ => right _\n  end.\nProof.  \n  abstract (unfold isOKNone; simpl; congruence).\n  abstract reflexivity.\n  abstract (unfold isOKNone; simpl; congruence).\nDefined.\n\nGlobal Instance isOK_le:\n  Monotonic (@isOK) (forallr R, res_le R --> impl).\nProof.\n  intros B A R x y Hxy [x' Hx].\n  subst.\n  inversion Hxy.\n  exists x.\n  reflexivity.\nQed.\n\nGlobal Instance isError_le:\n  Monotonic (@isError) (forallr R, res_le R ++> impl).\nProof.\n  intros A B R x y Hxy Hx.\n  destruct Hx as [err Hx]; subst.\n  inversion Hxy as [| err' x]; subst.\n  eexists.\n  reflexivity.\nQed.\n\nInstance isOKNone_le:\n  Monotonic (@isOKNone) (forallr R, res_le (option_le R) --> impl).\nProof.\n  unfold isOKNone.\n  intros A1 A2 RA x y Hxy Hx.\n  destruct Hxy as [x y Hxy | ]; try discriminate.\n  destruct Hxy as [x y Hxy | ]; try discriminate.\n  reflexivity.\nQed.\n\n(** *** Some lemmas and [eauto] hints. *)\n\nLemma isOK_OK {A} (a: A):\n  isOK (OK a).\nProof.\n  eexists.\n  reflexivity.\nQed.\n\nLemma isOK_Error {A} msg:\n  ~ isOK (@Error A msg).\nProof.\n  intros [a Ha].\n  discriminate.\nQed.\n\nHint Resolve isOK_OK.\n\nLemma isOKNone_OKNone {A}:\n  isOKNone (OK (@None A)).\nProof.\n  reflexivity.\nQed.\n\nHint Resolve isOKNone_OKNone.\n\nLemma isError_Error {A} msg:\n  isError (@Error A msg).\nProof.\n  eexists.\n  reflexivity.\nQed.\n\nHint Resolve isError_Error.\n\n\n(** * Miscellaneous helpers *)\n\nDefinition fallback {A} (x: A) (y: res A): A :=\n  match y with\n    | OK a => a\n    | Error _ => x\n  end.\n\n(** ** Flip [option (res -)] <-> [res (option -)] *)\n\n(** Overall, [res ∘ option] is more convenient to manipulate and\n  that's what we have in most places. However, it is more\n  straightforward to store into [PTree]s as [option ∘ res].\n  Fortunately these wrappers can be used to flip between the two\n  representations. *)\n\nDefinition res_option_flip {A} (roa: res (option A)): option (res A) :=\n  match roa with\n    | OK None => None\n    | OK (Some a) => Some (OK a)\n    | Error msg => Some (Error msg)\n  end.\n\nGlobal Instance res_option_flip_le:\n  Monotonic\n    (@res_option_flip)\n    (forallr R, res_le (option_le R) ++> option_le (res_le R)).\nProof.\n  intros A1 A2 RA _ _ [_ _ [y | x y Hxy] | msg [[|]|]];\n  simpl;\n  rauto.\nQed.\n\nDefinition option_res_flip {A} (ora: option (res A)): res (option A) :=\n  match ora with\n    | None => OK None\n    | Some (OK a) => OK (Some a)\n    | Some (Error msg) => Error msg\n  end.\n\nLemma option_res_le_flip {A B} (R: rel A B) x y:\n  res_le (option_le R) (option_res_flip x) (option_res_flip y) <->\n  option_le (res_le R) x y.\nProof.\n  destruct x as [[|]|];\n  destruct y as [[|]|];\n  split; intro H;\n  inversion H; subst;\n  try (inversion H2; subst);\n  repeat (constructor || assumption).\nQed.\n\nGlobal Instance option_res_flip_le:\n  Monotonic\n    (@option_res_flip)\n    (forallr R, option_le (res_le R) ++> res_le (option_le R)).\nProof.\n  intros A1 A2 RA x y Hxy.\n  apply option_res_le_flip.\n  assumption.\nQed.\n\nLemma res_option_flip_inv {A} (x: res (option A)):\n  option_res_flip (res_option_flip x) = x.\nProof.\n  destruct x as [[x|] | msg]; reflexivity.\nQed.\n\nLemma option_res_flip_inv {A} (x: option (res A)):\n  res_option_flip (option_res_flip x) = x.\nProof.\n  destruct x as [[x|msg] | ]; reflexivity.\nQed.\n\nLemma res_option_le_flip {A B} (R: rel A B) x y:\n  option_le (res_le R) (res_option_flip x) (res_option_flip y) <->\n  res_le (option_le R) x y.\nProof.\n  rewrite <- option_res_le_flip.\n  repeat rewrite res_option_flip_inv.\n  tauto.\nQed.\n\n(** * [PseudoJoin] structure for [res (option -)] *)\n\nRequire Import PseudoJoin.\n\nSection RES_OPTION_PSEUDO_JOIN.\n  Global Instance res_option_oplus_op (A: Type): Oplus (res (option A)) | 10 :=\n    { oplus rox roy :=\n    ox <- rox;\n    oy <- roy;\n    match ox, oy with\n      | None, None => ret None\n      | Some x, None => ret (Some x)\n      | None, Some y => ret (Some y)\n      | Some x, Some y => Error nil\n    end }.\n\n  Global Instance res_option_oplus_monotonic {A} (R: relation A):\n    Monotonic\n      (⊕)\n      (res_le (option_le R) ++> res_le (option_le R) ++> res_le (option_le R)).\n  Proof.\n    simpl.\n    unfold Errors.bind.\n    repeat rstep.\n    destruct H3 as [[y1|] | x1 y1 H1];\n    destruct H4 as [[y2|] | x2 y2 H2];\n    repeat rstep.\n  Qed.\n\n  Existing Instance res_le_op.\n  Existing Instance option_le_op.\n\n  Local Hint Extern 4 => reflexivity.\n\n  Global Instance res_option_oplus_prf (A: Type) `{Ale: Le A}:\n    @PreOrder A (≤) ->\n    PseudoJoin (res (option A)) (OK None).\n  Proof with simpl; monad_norm; repeat constructor; reflexivity.\n    intros Hpre.\n    split; try typeclasses eauto.\n    * simpl (≤).\n      split; typeclasses eauto.\n    * red; rauto.\n    * intros [[y|]|err]...\n    * intros [[x|]|xerr] [[y|]|yerr] [[z|]|zerr]...\n    * intros [[x|]|xerr] [[y|]|yerr]...\n    * intros [[x|]|xerr] [[y|]|yerr]...\n  Qed.\n\n  (** In addition, we have stronger versions of those. *)\n\n  Global Instance res_option_oplus_id_left A:\n    @LeftIdentity (res (option A)) eq (⊕) (OK None).\n  Proof.\n    intros [[|]|]; reflexivity.\n  Qed.\n\n  Global Instance res_option_oplus_comm A:\n    @RightIdentity (res (option A)) eq (⊕) (OK None).\n  Proof.\n    intros [[|]|]; reflexivity.\n  Qed.\nEnd RES_OPTION_PSEUDO_JOIN.\n\nSection OPTION_RES_PSEUDO_JOIN.\n  Global Instance option_res_oplus_op (A: Type): Oplus (option (res A)) | 10 :=\n    {\n      oplus orx ory :=\n        match orx, ory with\n          | None, None => None\n          | Some x, None => Some x\n          | None, Some y => Some y\n          | Some (Error e), Some y => Some (Error e)\n          | Some (OK x), Some (Error e) => Some (Error e)\n          | Some (OK x), Some (OK y) => Some (Error nil)\n        end\n    }.\n\n  Existing Instance option_le_op.\n  Existing Instance res_le_op.\n\n  Global Instance option_res_oplus_prf (A: Type) `{Ale: Le A} `{Hle: PreOrder A (≤)}:\n    PseudoJoin (option (res A)) None.\n  Proof with simpl; eauto with liblayers; intros; try solve_monotonic.\n    split; try typeclasses eauto.\n    * simpl (≤); split; typeclasses eauto.\n    * intros x1 x2 Hx y1 y2 Hy; simpl.\n      destruct Hx as [ [[x2|xerr]|] | _ _ [x1 x2 Hx | xerr [x|xe]]];\n      destruct Hy as [ [[y2|yerr]|] | _ _ [y1 y2 Hy | yerr [y|ye]]]...\n    * intros [[?|?]|]...\n    * intros [[?|?]|] [[?|?]|] [[?|?]|]...\n    * intros [[?|?]|] [[?|?]|]...\n    * intros [[?|?]|] [[?|?]|]...\n  Qed.\n\n  (** In addition, we have a top element. *)\n  Global Instance option_res_top {A B} (R: rel A B) errmsg:\n    UpperBound (option_le (res_le R)) (Some (Error errmsg)).\n  Proof.\n    intro x.\n    destruct x as [|]; repeat constructor.\n  Qed.\nEnd OPTION_RES_PSEUDO_JOIN.\n\n(* Decidable equality *)\n\nGlobal Instance decide_res_eq `{EqDec}:\n  EqDec (res A).\nProof.\n  repeat red.\n  repeat decide equality.\n  apply (decide _).\nDefined.\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/ErrorMonad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.25673128776194737}}
{"text": "\nRequire Import Coq.ZArith.BinInt.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Bool.Bool.\nImport ListNotations.\n\nRequire Import Util.\n\n(*TODO: where do we need this? See. Also should we use Interval package?*)\nRecord int_range := mk_intrng { ir_lower : Z; ir_upper: Z}.\n\n(* TODO: should really be machine-length integers *)\nRecord float_format := mk_floatfmt {\n    fp_exponent_digits : Z;\n    fp_significand_digits : Z\n}.\n\n(*TODO: do we need attributes or tag?*)\n(* Need tag for comparison (use as key in map) *)\nRecord ident : Type := mk_ident {\n    id_string : string;\n    id_tag : Z (*We just use the concrete type, not hashtable tag*)\n}.\n\nDefinition ident_eq_dec: forall (i1 i2: ident), {i1 = i2} + {i1 <> i2}.\nProof.\n    solve_eq_dec.\nDefined.\n\n(*In the real implementation, there is a mutable counter for the tags of\n    each ident that is registered (in id_register in ident.ml). Instead,\n    we assume the existence of an injective string -> Z function (which\n    does exist and we may write it later), and just use the fact that the\n    string names are unique.*)\nSection MakeTag.\n\nAxiom string_to_Z : string -> Z.\nAxiom string_to_Z_inj: forall s1 s2, string_to_Z s1 = string_to_Z s2 -> s1 = s2.\n    \nEnd MakeTag.\n\nDefinition mk_id (s: string) : ident := mk_ident s (string_to_Z s).\n    \n(*Types*)\n\nRecord tvsymbol : Type :=\n    mk_tvsym { tv_name : ident }.\n\nDefinition tvsymbol_eq_dec: forall (t1 t2: tvsymbol), {t1 = t2} + {t1 <> t2}.\nProof.\n    solve_eq_dec.\nDefined.\n\n(*Simplified version of types with no mutual recursion.\n  We do not include Range/Float because they are not used\n  in the frama-C translation.\n  Frama-C does ues Alias, which we represent with an option type.*)\n\nInductive ty : Type :=\n    | Tyvar : (ident * list tvsymbol * option ty) -> ty\n    | Tyapp : (ident * list tvsymbol * option ty) -> list ty -> ty\n    | Alias : ty -> ty.\n\nNotation tysymbol := (ident * list tvsymbol * option ty)%type.\n\n(*A more faithful (but annoying to use) version would be: \n\nInductive type_def (A: Type) : Type :=\n    | NoDef : type_def A\n    | Alias : A -> type_def A\n    | Range : int_range -> type_def A\n    | Float : float_format -> type_def A.\n\nInductive tysymbol : Type :=\n    | mk_tysym : ident -> list tvsymbol -> type_def ty -> tysymbol\n(*simplified version - ignore tags, combine ty and ty_node into 1*)\nwith ty : Type := (*ignoring tag*)\n    | mk_ty : ty_node -> ty\nwith ty_node : Type :=\n    | Tyvar : tvsymbol -> ty_node\n    | Tyapp : tysymbol -> list ty -> ty_node.\n*)    \n\n(*The default induction principle is useless, we need a better one:*)\n\nDefinition p_opt {A: Type} (P: A -> Prop) (o: option A) : Prop :=\n    match o with\n    | None => True\n    | Some x => P x\n    end.\n\nSection TyInd.\n\nVariable P: ty -> Prop.\nVariable Hvar: forall (i: ident) (l: list tvsymbol) (o: option ty), \n    p_opt P o -> P (Tyvar (i, l, o)).\nVariable Happ: forall (i: ident) (l: list tvsymbol) (o: option ty) (lty: list ty),\n    p_opt P o -> Forall P lty ->P (Tyapp (i, l, o) lty).\nVariable Halias: forall (t: ty), P t -> P (Alias t).\n\nFixpoint ty_ind' (t: ty): P t :=\nlet f := (fix list_ty_ind (ls: list ty) : Forall P ls :=\n    match ls with\n    | nil => (@Forall_nil ty P)\n    | (x :: tl) => @Forall_cons ty P _ _ (ty_ind' x) (list_ty_ind tl)\n    end) in\nmatch t with\n| Tyvar (i, l, (Some t)) => Hvar i l (Some t) (ty_ind' t)\n| Tyvar (i, l, None) => Hvar i l None I\n| Tyapp (i, l, Some t) lty => Happ i l (Some t) lty (ty_ind' t) (f lty)\n| Tyapp (i, l, None) lty => Happ i l None lty I (f lty)\n| Alias t' => Halias t' (ty_ind' t')\nend.\n\nEnd TyInd.\n\n(* Decidable Equality on Types *)\n\n(*Writing functions over this type is quite annoying, due to the nested\n  options/lists*)\nFixpoint ty_eqb (t1 t2: ty) : bool :=\n    match t1, t2 with\n    | Tyvar (i1, l1, o1), Tyvar (i2, l2, o2) =>\n        (ident_eq_dec i1 i2) &&\n        (list_eq_dec tvsymbol_eq_dec l1 l2) &&\n        match o1, o2 with\n        | Some t1', Some t2' => ty_eqb t1' t2'\n        | None, None => true\n        | _, _ => false\n        end\n    | Tyapp (i1, l1, o1) tyl1, Tyapp (i2, l2, o2) tyl2 =>\n        (ident_eq_dec i1 i2) &&\n        (list_eq_dec tvsymbol_eq_dec l1 l2) &&\n        match o1, o2 with\n        | Some t1', Some t2' => ty_eqb t1' t2'\n        | None, None => true\n        | _, _ => false\n        end &&\n        ((fix eqb_ty_list (l1: list ty) (l2: list ty) : bool :=\n            match l1, l2 with\n            | nil, nil => true\n            | t1 :: tl1, t2 :: tl2 => (ty_eqb t1 t2) && (eqb_ty_list tl1 tl2)\n            | _, _ => false\n            end) tyl1 tyl2)\n    | Alias t1', Alias t2' => ty_eqb t1' t2'\n    | _, _ => false\n    end.\n\nLtac contra :=\n    let C := fresh in\n    intro C; inversion C; subst; contradiction.\n\nLtac destruct_eq x :=\n    destruct x; simpl; [|contra]. \n\nLemma eqb_ty_list_simpl: forall l l',\n(fix eqb_ty_list (l1 l2 : list ty) {struct l1} : bool :=\nmatch l1 with\n| [] => match l2 with\n        | [] => true\n        | _ :: _ => false\n        end\n| t1 :: tl1 =>\n    match l2 with\n    | [] => false\n    | t2 :: tl2 => ty_eqb t1 t2 && eqb_ty_list tl1 tl2\n    end\nend) l l' = (Nat.eqb (length l) (length l')) && forallb id (map2 l l' (fun x y => ty_eqb x y)).\nProof.\n    intros l. induction l as [|h t IH]; intros l'; simpl.\n    - destruct l'; reflexivity.\n    - destruct l' as [|h1 t1]; simpl; auto.\n      rewrite IH; simpl. rewrite andb_comm, andb_assoc.\n      unfold id at 2. rewrite <- andb_assoc.\n      rewrite (andb_comm _ (ty_eqb _ _)), andb_assoc.\n      reflexivity.\nQed.\n      \nLemma ty_eqb_eq: forall (t1 t2: ty),\n    ty_eqb t1 t2 = true ->\n    t1 = t2.\nProof.\n    intros t1. induction t1 using ty_ind'.\n    - intros t2. destruct t2; simpl; try contra.\n      destruct p as [[i2 l2] o2]; simpl.\n      destruct_eq (ident_eq_dec i i2).\n      destruct_eq (list_eq_dec tvsymbol_eq_dec l l2).\n      subst.\n      destruct o as [t1|]; destruct o2 as [t2|]; try contra;[|reflexivity].\n      simpl in H. intro Heq. subst. rewrite (H t2); auto.\n    - intros t2. destruct t2; simpl; try contra.\n      destruct p as [[i2 l2] o2]; simpl.\n      destruct_eq (ident_eq_dec i i2).\n      destruct_eq (list_eq_dec tvsymbol_eq_dec l l2).\n      subst. intros Heq; apply andb_prop in Heq; destruct Heq.\n      assert (lty = l0). {\n          rewrite eqb_ty_list_simpl in H2.\n          apply andb_prop in H2; destruct H2.\n          apply EqNat.beq_nat_true in H2.\n          rewrite map2_combine, forallb_forall in H3.\n          apply list_combine_eq; auto.\n          intros x y Hinxy. assert(Hmap:=Hinxy).\n          eapply in_map in Hmap. apply H3 in Hmap.\n          simpl in Hmap. unfold id in Hmap.\n          apply in_combine_l in Hinxy.\n          rewrite Forall_forall in H0. apply H0; assumption.\n      } subst; clear H2.\n      destruct o as [t1|]; destruct o2 as [t2|]; try solve[inversion H1].\n      rewrite (H t2) by assumption. all: reflexivity.\n    - simpl. intros t2; destruct t2; try contra; intros Heq.\n      rewrite (IHt1 t2); auto. \nQed.\n\nLemma ty_eqb_refl: forall (t: ty),\n    ty_eqb t t = true.\nProof.\n    intros t; induction t using ty_ind'; simpl.\n    - destruct (ident_eq_dec i i); auto.\n      destruct (list_eq_dec tvsymbol_eq_dec l l); auto.\n      simpl. destruct o; simpl in *; auto.\n    - destruct (ident_eq_dec i i); auto.\n      destruct (list_eq_dec tvsymbol_eq_dec l l); auto.\n      simpl. \n      (*Need nested lemma for fixpoint here:*)\n      assert (\n      (fix eqb_ty_list (l1 l2 : list ty) {struct l1} : bool :=\n      match l1 with\n      | [] => match l2 with\n              | [] => true\n              | _ :: _ => false\n              end\n      | t1 :: tl1 =>\n          match l2 with\n          | [] => false\n          | t2 :: tl2 => ty_eqb t1 t2 && eqb_ty_list tl1 tl2\n          end\n      end) lty lty = true). {\n        rewrite eqb_ty_list_simpl. apply andb_true_intro.\n        split.\n        - apply PeanoNat.Nat.eqb_refl.\n        - rewrite map2_combine; apply forallb_forall. intros x Hin.\n          rewrite in_map_iff in Hin. destruct Hin as [[t1 t2] [Heq Hin]].\n          simpl in *; subst. assert (Heq:=Hin).\n          apply in_combine_same in Heq; subst. apply in_combine_l in Hin.\n          rewrite Forall_forall in H0. apply H0. assumption.\n      }\n      rewrite H1; clear H1.\n      destruct o; simpl in *; auto.\n      rewrite H. reflexivity.\n    - assumption.\nQed.\n\nLemma ty_eqb_eq_iff: forall (t1 t2: ty),\n  Bool.reflect (t1 = t2) (ty_eqb t1 t2).\nProof.\n    intros t1 t2. destruct (ty_eqb t1 t2) eqn : Heq.\n    - apply ReflectT. apply ty_eqb_eq. assumption.\n    - apply ReflectF. intro C; subst.\n      rewrite ty_eqb_refl in Heq. inversion Heq.\nQed.\n\nDefinition ty_eq_dec: forall (t1 t2: ty), {t1 = t2} + {t1 <> t2} :=\n    fun t1 t2 => reflect_dec _ _ (ty_eqb_eq_iff t1 t2).\n\nDefinition tysymbol_eq_dec: forall (t1 t2: tysymbol), {t1 = t2} + {t1 <> t2}.\nProof.\n    intros t1 t2. decide equality.\n    - apply option_eq_dec. intros a1 a2. apply ty_eq_dec.\n    - solve_eq_dec.\nQed. \n\n(* Type constructors *)\nDefinition mk_ts (name: string) (args: list tvsymbol) (def: option ty) : tysymbol :=\n    ((mk_id name), args, def).\n\n(* Built in type symbols *)\nDefinition ts_int : tysymbol :=\n    mk_ts \"int\" nil None.\n\nDefinition ts_real : tysymbol :=\n    mk_ts \"real\" nil None.\n\nDefinition ts_bool : tysymbol :=\n    mk_ts \"bool\" nil None.\n\nDefinition ts_str : tysymbol :=\n    mk_ts \"string\" nil None.\n\n(*Their implementation uses mutable hashtables and lots of exceptions.\n    This is a simpler version for the types we need*)\nDefinition ty_app (s: tysymbol) (tl : list ty) : ty :=\n    (*TODO: ignoring alias for now, may need*)\n    Tyapp s tl.\n\nDefinition ty_int : ty := ty_app ts_int nil.\nDefinition ty_real : ty := ty_app ts_real nil.\nDefinition ty_bool : ty := ty_app ts_bool nil.\nDefinition ty_str : ty := ty_app ts_str nil.\n\nDefinition ts_func : tysymbol :=\n    let tv_a := mk_tvsym (mk_id \"a\") in\n    let tv_b := mk_tvsym (mk_id \"b\") in\n    mk_ts \"->\" [tv_a; tv_b] None.\n\nDefinition ty_func (ty_a ty_b : ty) : ty :=\n    ty_app ts_func [ty_a; ty_b].\n\n(*a -> bool function*)\nDefinition ty_pred (ty_a : ty) : ty :=\n    ty_app ts_func [ty_a; ty_bool].\n\n(*Tuples*)\n\nDefinition nat_to_string (n: nat) : string :=\n    (String (Ascii.ascii_of_nat n) EmptyString).\n\n(*In the OCaml impl, each element gets a different id. We model\n  that by giving each a different name (technically, this means that\n  tuples cannot have more than 256 elements)\n  Do these have to be globally unique?*)\nDefinition ts_tuple (n: nat) : tysymbol :=\n    let vl := fold_left (fun acc m => mk_tvsym (mk_id (nat_to_string m)) :: acc)\n        (seq 0 n) nil in\n    mk_ts (\"tuple\" ++ nat_to_string n) vl None.\n    \nDefinition ty_tuple (tyl: list ty) : ty :=\n    ty_app (ts_tuple (length tyl)) tyl.\n\n\n", "meta": {"author": "joscoh", "repo": "why3-semantics", "sha": "d4d1801e43728a599ffd5442e3b6701797e61774", "save_path": "github-repos/coq/joscoh-why3-semantics", "path": "github-repos/coq/joscoh-why3-semantics/why3-semantics-d4d1801e43728a599ffd5442e3b6701797e61774/proofs/Ty.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2566025040195623}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.floyd.VSU.\nRequire Import apile.\nRequire Import spec_stdlib.\nRequire Import spec_pile.\nRequire Import spec_pile_private.\nRequire Import spec_apile.\n\n#[export] Instance APileCompSpecs : compspecs. make_compspecs prog. Defined.\n\nSection Apile_VSU.\nVariable M: MallocFreeAPD.\nVariable PILEPRIV: PilePrivateAPD M. (*apile is parametric in a PRIVATE pile predicate structure*)\n\nDefinition apile (sigma: list Z) (gv: globals): mpred :=\n  !!(headptr (gv _a_pile)) && 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 size_t nullval (gv apile._a_pile) |-- apile nil gv.\nProof.\nintros. unfold apile. rewrite pile_rep_exposed. (*HERE*) \nunfold prep.\nassert_PROP (headptr (gv _a_pile)) by entailer!.\nExists nullval.\nunfold listrep. entailer!.\nunfold_data_at (data_at _ spec_pile.tpile _ _).\nrewrite field_at_data_at. simpl.\nrewrite field_compatible_field_address\n   by auto with field_compatible.\nsimpl. normalize.\nrewrite <- data_at_nullptr.\ncancel.\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\nDefinition APILE: APileAPD := Build_APileAPD apile (*APileCompSpecs make_apile*) (*_ apile_Init*).\n\n  Definition Apile_ASI: funspecs := ApileASI M APILE.\n\n  Definition apile_imported_specs:funspecs := \n     [ Pile_add_spec M PILEPRIV; Pile_count_spec PILEPRIV].\n\n  Definition apile_internal_specs: funspecs := Apile_ASI.\n\n  Definition ApileVprog: varspecs. mk_varspecs prog. Defined.\n  Definition 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; Intros.\nforward_call (gv _a_pile, n,sigma,gv).\nentailer!. simpl. unfold apile. entailer!.\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 *; Intros.\nforward_call (gv _a_pile, sigma).\nforward.\nentailer!. simpl. unfold apile. entailer!.\nQed. \n\nDefinition ApileVSU: @VSU NullExtension.Espec\n      nil apile_imported_specs ltac:(QPprog prog) Apile_ASI (apile nil).\nProof.\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", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs/VSUpile/verif_apile.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4726834766204329, "lm_q1q2_score": 0.2566025040195623}}
{"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| Nop\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\nDefinition pop f n :=\n    Frame (arg f) (self f) (skipn n (stack f)).\n\nDefinition pop_push f n v :=\n    push (pop f n) v.\n\nDefinition top f :=\n    match stack f with\n    | [] => Constr 0 []\n    | v :: _ => v\n    end.\n\n\n\nInductive cont :=\n| Kret (code : list insn) (f : frame) (k : cont)\n(* keeping the original `stk` lets us enforce that each branch pushes\n * exactly one value before running SContSwitch *)\n| Kswitch (code : list insn) (stk : list value) (k : cont)\n| Kstop.\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| SNop : forall is f k,\n        sstep E (Run (Nop :: is) f k)\n                (Run is f k)\n\n| SArg : forall is f k,\n        sstep E (Run (Arg :: is) f k)\n                (Run is (push f (arg f)) k)\n| SSelf : forall is f k,\n        sstep E (Run (Self :: is) f k)\n                (Run is (push f (self f)) k)\n\n| SDerefinateConstr : forall off is f k  tag args v,\n        length (stack f) >= 1 ->\n        top f = Constr tag args ->\n        nth_error args off = Some v ->\n        sstep E (Run (Deref off :: is) f k)\n                (Run is (pop_push f 1 v) k)\n| SDerefinateClose : forall off is f k  fname free v,\n        length (stack f) >= 1 ->\n        top f = Close fname free ->\n        nth_error free off = Some v ->\n        sstep E (Run (Deref off :: is) f k)\n                (Run is (pop_push f 1 v) k)\n\n| SConstrDone : forall tag nargs is f k,\n        length (stack f) >= nargs ->\n        sstep E (Run (MkConstr tag nargs :: is) f k)\n                (Run is (pop_push f nargs (Constr tag (rev (firstn nargs (stack f))))) k)\n| SCloseDone : forall fname nfree is f k,\n        length (stack f) >= nfree ->\n        sstep E (Run (MkClose fname nfree :: is) f k)\n                (Run is (pop_push f nfree (Close fname (rev (firstn nfree (stack f))))) k)\n| SOpaqueOpDone : forall op nargs is f k v,\n        length (stack f) >= nargs ->\n        opaque_oper_denote_higher op (rev (firstn nargs (stack f))) = Some v ->\n        sstep E (Run (OpaqueOp op nargs :: is) f k)\n                (Run is (pop_push f nargs v) k)\n\n| SMakeCall : forall is f k  fname free body,\n        length (stack f) >= 2 ->\n        nth_error (stack f) 1 = Some (Close fname free) ->\n        nth_error E fname = Some body ->\n        sstep E (Run (Call :: is) f k)\n                (Run body (Frame (top f) (Close fname free) [])\n                    (Kret is (pop f 2) k))\n\n(* NB: `Switch` still has an implicit target of `Arg` *)\n| SSwitchinate : forall cases is f k  tag args case,\n        arg f = Constr tag args ->\n        nth_error cases tag = Some case ->\n        sstep E (Run (Switch cases :: is) f k)\n                (Run case f (Kswitch is (stack f) k))\n\n| SContRet : forall code f f' k,\n        length (stack f) = 1 ->\n        sstep E (Run [] f (Kret code f' k))\n                (Run code (push f' (top f)) k)\n| SContSwitch : forall code f stk k v,\n        stack f = v :: stk ->\n        sstep E (Run [] f (Kswitch code stk k))\n                (Run code f k)\n| SContStop : forall f,\n        length (stack f) = 1 ->\n        sstep E (Run [] f Kstop)\n                (Stop (top f))\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                 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 (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 * 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    (HNop :     P Nop)\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        | Nop => HNop\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    (HNop :     P Nop)\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        HNop 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    (HNop :     P Nop)\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            HNop 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/StackFlatter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961016, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.25655460727394686}}
{"text": "Require Import Coq.Strings.String.\n\nRequire Import ByteData.\nRequire Import DiskSubset.\nRequire Import File.\nRequire Import FileData.\nRequire Import FileTypes.\nRequire Import Tar.\n\nVariable gunzip: File->Disk->File.\n\nLocal Open Scope bool.\n\nDefinition borland_rootkit (disk: Disk) :=\n  exists file: File,\n    isOnDisk file disk\n    /\\ isDeleted file\n    /\\ isGzip file disk\n    /\\ Tar.looksLikeRootkit (gunzip file disk) disk.\n\nDefinition borland_rootkit_witness (disk: Disk) (file: File):=\n  isOnDisk file disk\n  /\\ isDeleted file\n  /\\ isGzip file disk\n  /\\ Tar.looksLikeRootkit (gunzip file disk) disk.\n\nDefinition borland_rootkit_witness_param (disk: Disk) (file gunzipped: File):=\n  isOnDisk file disk\n  /\\ isDeleted file\n  /\\ isGzip file disk\n  /\\ Tar.looksLikeRootkit gunzipped disk.\n\n\nLemma borland_rootkit_witness_impl :\n  forall (file: File) (disk: Disk),\n    borland_rootkit_witness disk file ->\n      borland_rootkit disk.\nProof.\n  intros file disk H.\n  unfold borland_rootkit_witness in H.\n  unfold borland_rootkit.\n  exists file. assumption.\nQed.\n\nLemma borland_rootkit_fsubset :\n  forall (gzippedFile gunzipped: File) (disk:Disk),\n    gunzipped f⊆ (gunzip gzippedFile disk) ->\n      borland_rootkit_witness_param disk gzippedFile gunzipped ->\n        borland_rootkit_witness disk gzippedFile.\nProof.\n  intros gzippedFile gunzipped disk subset H.\n  unfold borland_rootkit_witness_param in H.\n  unfold borland_rootkit_witness.\n  destruct H as [H0 H]. destruct H as [H1 H]. destruct H as [H2 H].\n  split. assumption.\n  split. assumption.\n  split. assumption.\n  apply looksLikeRootkit_fsubset with (1:=subset).\n  assumption.\nQed.\n\n\nDefinition borland_compute (disk: Disk) (file gunzipped: File)\n  (filename1 filename2: string) :=\n  (isOnDisk_compute file disk)\n  && file.(deleted)\n  && (isGzip_compute file disk)\n  (*&& File.eqb gunzipped (gunzip file) *)\n  && Tar.looksLikeRootkit_compute gunzipped disk filename1 filename2.\n\nLemma borland_reflection (disk: Disk) \n  (file gunzipped: File) (filename1 filename2: string) :\n  borland_compute disk file gunzipped filename1 filename2 = true\n    -> (gunzip file disk) = gunzipped\n      -> borland_rootkit disk.\nProof.\n  intros. unfold borland_compute in H.\n  apply Bool.andb_true_iff in H. destruct H.\n  apply Bool.andb_true_iff in H. destruct H.\n  apply Bool.andb_true_iff in H. destruct H.\n\n  unfold borland_rootkit. exists file.\n  split. apply isOnDisk_reflection. auto.\n  split. unfold isDeleted. auto.\n  split. apply isGzip_reflection. auto.\n  rewrite H0. apply looksLikeRootkit_reflection in H1. auto.\nQed.\n\nLemma borland_witness_param_reflection:\n  forall (disk: Disk) (file gunzipped: File) (filename1 filename2: string),\n    borland_compute disk file gunzipped filename1 filename2 = true ->\n      borland_rootkit_witness_param disk file gunzipped.\nProof.\n  intros. unfold borland_compute in H.\n  apply Bool.andb_true_iff in H. destruct H.\n  apply Bool.andb_true_iff in H. destruct H.\n  apply Bool.andb_true_iff in H. destruct H.\n\n  unfold borland_rootkit_witness_param.\n  split. apply isOnDisk_reflection. auto.\n  split. unfold isDeleted. auto.\n  split. apply isGzip_reflection. auto.\n         apply looksLikeRootkit_reflection in H0. auto.\nQed.\n\nLemma borland_rootkit_witness_subset:\n  forall (sub super: Disk) (gzippedFile gunzipped: File),\n    borland_rootkit_witness_param sub gzippedFile gunzipped ->\n      sub ⊆ super ->\n        gunzipped f⊆ (gunzip gzippedFile super) ->\n            borland_rootkit super.\nProof.\n  intros sub super gzippedFile gunzipped H subset fsubset.\n  unfold borland_rootkit_witness_param in H.\n  apply borland_rootkit_witness_impl with (file:=gzippedFile).\n  unfold borland_rootkit_witness.\n  destruct H as [HonDisk H]. destruct H as [Hdeleted H].\n  destruct H as [Hgzip Hlooks].\n  split. apply isOnDisk_subset with (1:=subset). assumption.\n  split. assumption.\n  split. apply isGzip_subset with (1:=subset). assumption.\n         apply looksLikeRootkit_subset with (1:=subset) in Hlooks.\n         apply looksLikeRootkit_fsubset with (1:=fsubset). assumption.\nQed.\n", "meta": {"author": "cmc333333", "repo": "forensics-thesis-code", "sha": "3a6ddf2bc2f6627a865d17e40ce83670fb4ca744", "save_path": "github-repos/coq/cmc333333-forensics-thesis-code", "path": "github-repos/coq/cmc333333-forensics-thesis-code/forensics-thesis-code-3a6ddf2bc2f6627a865d17e40ce83670fb4ca744/HoneynetDefinitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.25655460727394686}}
{"text": "Definition Effect { S : Type } := S -> S.\n\nDefinition Predicate { T : Type } := T -> Prop.\n\nDefinition Specification { T U : Type } := T -> U -> Prop.\n\nNotation \"T >> U\" := (@Specification T U) (at level 0).\n\n\nInductive Stmt { T : Type } : Type := \n| Void \n| Assignment : @Effect T -> @Stmt T\n| Seq : @Stmt T -> @Stmt T -> @Stmt T\n| If : @Predicate T -> @Stmt T -> @Stmt T -> @Stmt T \n| While : @Predicate T -> @Stmt T -> @Stmt T \n| Spec : @Specification T T -> @Stmt T\n| Block : @Stmt T -> @Stmt T -> @Stmt T.\n\nDefinition Skip { T : Type } := @Assignment T (fun s => s).\n\nFixpoint BlockFree { T : Type } (s : @Stmt T) :=\n  match s with\n  | Void => True\n  | Assignment _ => True\n  | Seq S1 S2 => BlockFree S1 /\\ BlockFree S2\n  | If _ S1 S2 => BlockFree S1 /\\ BlockFree S2\n  | While _ S1 => BlockFree S1\n  | Spec _ => True\n  | Block _ _ => False\n  end.\n\nNotation \"' x := y\" := (Assignment (fun x => y)) (at level 50, x pattern, format \"' x  :=  y\") : stmt_scope.\nNotation \"x ; y\" := (Seq x y) (at level 51, format \"'[v' x ; '/' y ']'\", right associativity) : stmt_scope.\nNotation \"'IIf' c 'Then' p 'Else' q 'End'\" :=\n  (If c p q) (at level 52, format \"'[v' IIf  c   Then '/'  p '/' Else '/'  q '/' End ']'\") : stmt_scope.\nNotation \"'IIf' c 'Then' p 'End'\" :=\n  (If c p Skip) (at level 52, format \"'[v' IIf  c  Then  p  End ']'\") : stmt_scope.\nNotation \"'WWhile' c 'Do' p 'Done'\" :=\n  (While c p) (at level 52, format \"'[v' WWhile  c  Do '/'  p '/' Done ']'\") : stmt_scope.\nNotation \"⟨ x ⟩\" := (Spec x) (at level 0, format \"⟨ x ⟩\") : stmt_scope.\n\nBind Scope stmt_scope with Stmt.", "meta": {"author": "bsall", "repo": "AMToPR-ICFEM-2019", "sha": "980d6d6ef5c9ad72a6b2cbd4fa549bc4705f0bed", "save_path": "github-repos/coq/bsall-AMToPR-ICFEM-2019", "path": "github-repos/coq/bsall-AMToPR-ICFEM-2019/AMToPR-ICFEM-2019-980d6d6ef5c9ad72a6b2cbd4fa549bc4705f0bed/src/theory/Statement.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.25655460727394686}}
{"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\nFrom Coq Require Import List Syntax Derive.\nFrom Coq.ssr Require Import ssreflect.\nRequire Automaton.\nRequire Import Alphabet Validator_classes.\n\nModule Make(Import A:Automaton.T).\n\n(** We instantiate some sets/map. **)\nModule TerminalComparableM <: ComparableM.\n  Definition t := terminal.\n  Instance tComparable : Comparable t := _.\nEnd TerminalComparableM.\nModule TerminalOrderedType := OrderedType_from_ComparableM TerminalComparableM.\nModule StateProdPosComparableM <: ComparableM.\n  Definition t := (state*production*nat)%type.\n  Instance tComparable : Comparable t := _.\nEnd StateProdPosComparableM.\nModule StateProdPosOrderedType :=\n  OrderedType_from_ComparableM StateProdPosComparableM.\n\nModule TerminalSet := FSetAVL.Make TerminalOrderedType.\nModule StateProdPosMap := FMapAVL.Make StateProdPosOrderedType.\n\n(** Nullable predicate for symbols and list of symbols. **)\nDefinition nullable_symb (symbol:symbol) :=\n  match symbol with\n  | NT nt => nullable_nterm nt\n  | _ => false\n  end.\n\nDefinition nullable_word (word:list symbol) :=\n  forallb nullable_symb word.\n\n(** First predicate for non terminal, symbols and list of symbols, given as FSets. **)\nDefinition first_nterm_set (nterm:nonterminal) :=\n  fold_left (fun acc t => TerminalSet.add t acc)\n    (first_nterm nterm) TerminalSet.empty.\n\nDefinition first_symb_set (symbol:symbol) :=\n  match symbol with\n  | NT nt => first_nterm_set nt\n  | T t => TerminalSet.singleton t\n  end.\n\nFixpoint first_word_set (word:list symbol) :=\n  match word with\n  | [] => TerminalSet.empty\n  | t::q =>\n    if nullable_symb t then\n      TerminalSet.union (first_symb_set t) (first_word_set q)\n    else\n      first_symb_set t\n  end.\n\n(** Small helper for finding the part of an item that is after the dot. **)\nDefinition future_of_prod prod dot_pos : list symbol :=\n  (fix loop n lst :=\n    match n with\n    | O => lst\n    | S x => match loop x lst with [] => [] | _::q => q end\n    end)\n  dot_pos (rev' (prod_rhs_rev prod)).\n\n(** We build a fast map to store all the items of all the states. **)\nDefinition items_map (_:unit): StateProdPosMap.t TerminalSet.t :=\n  fold_left (fun acc state =>\n    fold_left (fun acc item =>\n      let key := (state, prod_item item, dot_pos_item item) in\n        let data := fold_left (fun acc t => TerminalSet.add t acc)\n          (lookaheads_item item) TerminalSet.empty\n        in\n        let old :=\n          match StateProdPosMap.find key acc with\n          | Some x => x | None => TerminalSet.empty\n          end\n        in\n        StateProdPosMap.add key (TerminalSet.union data old) acc\n    ) (items_of_state state) acc\n  ) all_list (StateProdPosMap.empty TerminalSet.t).\n\n(** We need to avoid computing items_map each time we need it. To that\n  purpose, we declare a typeclass specifying that some map is equal to\n  items_map. *)\nClass IsItemsMap m := is_items_map : m = items_map ().\n\n(** Accessor. **)\nDefinition find_items_map items_map state prod dot_pos : TerminalSet.t :=\n  match StateProdPosMap.find (state, prod, dot_pos) items_map with\n  | None => TerminalSet.empty\n  | Some x => x\n  end.\n\nDefinition state_has_future state prod (fut:list symbol) (lookahead:terminal) :=\n  exists dot_pos:nat,\n    fut = future_of_prod prod dot_pos /\\\n    TerminalSet.In lookahead (find_items_map (items_map ()) state prod dot_pos).\n\n(** Iterator over items. **)\nDefinition forallb_items items_map (P:state -> production -> nat -> TerminalSet.t -> bool): bool:=\n  StateProdPosMap.fold (fun key set acc =>\n    match key with (st, p, pos) => (acc && P st p pos set)%bool end\n  ) items_map true.\n\n(** Typeclass instances for synthetizing the validator. *)\n\nInstance is_validator_subset S1 S2 :\n  IsValidator (TerminalSet.Subset S1 S2) (TerminalSet.subset S1 S2).\nProof. intros ?. by apply TerminalSet.subset_2. Qed.\n\n(* While the specification of the validator always quantify over\n   possible lookahead tokens individually, the validator usually\n   handles lookahead sets directly instead, for better performances.\n\n   For instance, the validator for [state_has_future], which speaks\n   about one single lookahead token is a subset operation:\n*)\nLemma is_validator_state_has_future_subset st prod pos lookahead lset im fut :\n  TerminalSet.In lookahead lset ->\n  fut = future_of_prod prod pos ->\n  IsItemsMap im ->\n  IsValidator (state_has_future st prod fut lookahead)\n              (TerminalSet.subset lset (find_items_map im st prod pos)).\nProof.\n  intros ? -> -> HSS%TerminalSet.subset_2. exists pos. split=>//. by apply HSS.\nQed.\n(* We do not declare this lemma as an instance, and use [Hint Extern]\n   instead, because the typeclass mechanism has trouble instantiating\n   some evars if we do not explicitely call [eassumption]. *)\nHint Extern 2 (IsValidator (state_has_future _ _ _ _) _) =>\n  eapply is_validator_state_has_future_subset; [eassumption|eassumption || reflexivity|]\n: typeclass_instances.\n\n(* As said previously, we manipulate lookahead terminal sets instead of\n  lookahead individually. Hence, when we quantify over a lookahead set\n  in the specification, we do not do anything in the executable\n  validator.\n\n  This instance is used for [non_terminal_closed]. *)\nInstance is_validator_forall_lookahead_set lset P b:\n  (forall lookahead, TerminalSet.In lookahead lset -> IsValidator (P lookahead) b) ->\n  IsValidator (forall lookahead, TerminalSet.In lookahead lset -> P lookahead) b.\nProof. unfold IsValidator. firstorder. Qed.\n\n\n(* Dually, we sometimes still need to explicitelly iterate over a\n  lookahead set. This is what this lemma allows.\n  Used only in [end_reduce]. *)\nLemma is_validator_iterate_lset P b lookahead lset :\n  TerminalSet.In lookahead lset ->\n  IsValidator P (b lookahead) ->\n  IsValidator P (TerminalSet.fold (fun lookahead acc =>\n    if acc then b lookahead else false) lset true).\nProof.\n  intros Hlset%TerminalSet.elements_1 Hval Val. apply Hval.\n  revert Val. rewrite TerminalSet.fold_1. generalize true at 1. clear -Hlset.\n  induction Hlset as [? l <-%compare_eq|? l ? IH]=> /= b' Val.\n  - destruct (b lookahead). by destruct b'. exfalso. by induction l; destruct b'.\n  - eauto.\nQed.\nHint Extern 100 (IsValidator _ _) =>\n  match goal with\n  | H : TerminalSet.In ?lookahead ?lset |- _ =>\n    eapply (is_validator_iterate_lset _ (fun lookahead => _) _ _ H); clear H\n  end\n: typeclass_instances.\n\n(* We often quantify over all the items of all the states of the\n   automaton. This lemma and the accompanying [Hint Resolve]\n   declaration allow generating the corresponding executable\n   validator.\n\n   Note that it turns out that, in all the uses of this pattern, the\n   first thing we do for each item is pattern-matching over the\n   future. This lemma also embbed this pattern-matching, which makes\n   it possible to get the hypothesis [fut' = future_of_prod prod (S pos)]\n   in the non-nil branch.\n\n   Moreover, note, again, that while the specification quantifies over\n   lookahead terminals individually, the code provides lookahead sets\n   instead. *)\nLemma is_validator_forall_items P1 b1 P2 b2 im :\n  IsItemsMap im ->\n\n  (forall st prod lookahead lset pos,\n      TerminalSet.In lookahead lset ->\n      [] = future_of_prod prod pos ->\n      IsValidator (P1 st prod lookahead) (b1 st prod pos lset)) ->\n\n  (forall st prod pos lookahead lset s fut',\n      TerminalSet.In lookahead lset ->\n      fut' = future_of_prod prod (S pos) ->\n      IsValidator (P2 st prod lookahead s fut') (b2 st prod pos lset s fut')) ->\n\n  IsValidator (forall st prod fut lookahead,\n                  state_has_future st prod fut lookahead ->\n                  match fut with\n                  | [] => P1 st prod lookahead\n                  | s :: fut' => P2 st prod lookahead s fut'\n                  end)\n              (forallb_items im (fun st prod pos lset =>\n                 match future_of_prod prod pos with\n                 | [] => b1 st prod pos lset\n                 | s :: fut' => b2 st prod pos lset s fut'\n                 end)).\nProof.\n  intros -> Hval1 Hval2 Val st prod fut lookahead (pos & -> & Hlookahead).\n  rewrite /forallb_items StateProdPosMap.fold_1 in Val.\n  assert (match future_of_prod prod pos with\n          | [] => b1 st prod pos (find_items_map (items_map ()) st prod pos)\n          | s :: fut' => b2 st prod pos (find_items_map (items_map ()) st prod pos) s fut'\n          end = true).\n  - unfold find_items_map in *.\n    assert (Hfind := @StateProdPosMap.find_2 _ (items_map ()) (st, prod, pos)).\n    destruct StateProdPosMap.find as [lset|]; [|by edestruct (TerminalSet.empty_1); eauto].\n    specialize (Hfind _ eq_refl). apply StateProdPosMap.elements_1 in Hfind.\n    revert Val. generalize true at 1.\n    induction Hfind as [[? ?] l [?%compare_eq ?]|??? IH]=>?.\n    + simpl in *; subst.\n      match goal with |- _ -> ?X = true => destruct X end; [done|].\n      rewrite Bool.andb_false_r. clear. induction l as [|[[[??]?]?] l IH]=>//.\n    + apply IH.\n  - destruct future_of_prod eqn:EQ. by eapply Hval1; eauto.\n    eapply Hval2 with (pos := pos); eauto; [].\n    revert EQ. unfold future_of_prod=>-> //.\nQed.\n(* We need a hint for expplicitely instantiating b1 and b2 with lambdas. *)\nHint Extern 0 (IsValidator\n                 (forall st prod fut lookahead,\n                     state_has_future st prod fut lookahead -> _)\n                 _) =>\n    eapply (is_validator_forall_items _ (fun st prod pos lset => _)\n                                      _ (fun st prod pos lset s fut' => _))\n  : typeclass_instances.\n\n(* Used in [start_future] only. *)\nInstance is_validator_forall_state_has_future im st prod :\n  IsItemsMap im ->\n  IsValidator\n    (forall look, state_has_future st prod (rev' (prod_rhs_rev prod)) look)\n    (let lookaheads := find_items_map im st prod 0 in\n     forallb (fun t => TerminalSet.mem t lookaheads) all_list).\nProof.\n  move=> -> /forallb_forall Val look.\n  specialize (Val look (all_list_forall _)). exists 0. split=>//.\n  by apply TerminalSet.mem_2.\nQed.\n\n(** * Validation for completeness **)\n\n(** The nullable predicate is a fixpoint : it is correct. **)\nDefinition nullable_stable :=\n  forall p:production,\n    if nullable_word (prod_rhs_rev p) then\n      nullable_nterm (prod_lhs p) = true\n    else True.\n\n(** The first predicate is a fixpoint : it is correct. **)\nDefinition first_stable:=\n  forall (p:production),\n    TerminalSet.Subset (first_word_set (rev' (prod_rhs_rev p)))\n                       (first_nterm_set (prod_lhs p)).\n\n(** The initial state has all the S=>.u items, where S is the start non-terminal **)\nDefinition start_future :=\n  forall (init:initstate) (p:production),\n    prod_lhs p = start_nt init ->\n  forall (t:terminal),\n    state_has_future init p (rev' (prod_rhs_rev p)) t.\n\n(** If a state contains an item of the form A->_.av[[b]], where a is a\n    terminal, then reading an a does a [Shift_act], to a state containing\n    an item of the form A->_.v[[b]]. **)\nDefinition terminal_shift :=\n  forall (s1:state) prod fut lookahead,\n    state_has_future s1 prod fut lookahead ->\n    match fut with\n    | T t::q =>\n      match action_table s1 with\n      | Lookahead_act awp =>\n        match awp t with\n        | Shift_act s2 _ =>\n          state_has_future s2 prod q lookahead\n        | _ => False\n        end\n      | _ => False\n      end\n    | _ => True\n    end.\n\n(** If a state contains an item of the form A->_.[[a]], then either we do a\n    [Default_reduce_act] of the corresponding production, either a is a\n    terminal (ie. there is a lookahead terminal), and reading a does a\n    [Reduce_act] of the corresponding production. **)\nDefinition end_reduce :=\n  forall (s:state) prod fut lookahead,\n    state_has_future s prod fut lookahead ->\n    match fut with\n    | [] =>\n      match action_table s with\n      | Default_reduce_act p => p = prod\n      | Lookahead_act awt =>\n        match awt lookahead with\n        | Reduce_act p => p = prod\n        | _ => False\n        end\n      end\n    | _ => True\n    end.\n\nDefinition is_end_reduce items_map :=\n  forallb_items items_map (fun s prod pos lset =>\n    match future_of_prod prod pos with\n    | [] =>\n      match action_table s with\n      | Default_reduce_act p => compare_eqb p prod\n      | Lookahead_act awt =>\n        TerminalSet.fold (fun lookahead acc =>\n          match awt lookahead with\n          | Reduce_act p => (acc && compare_eqb p prod)%bool\n          | _ => false\n          end) lset true\n      end\n    | _ => true\n    end).\n\n(** If a state contains an item of the form A->_.Bv[[b]], where B is a\n    non terminal, then the goto table says we have to go to a state containing\n    an item of the form A->_.v[[b]]. **)\nDefinition non_terminal_goto :=\n  forall (s1:state) prod fut lookahead,\n    state_has_future s1 prod fut lookahead ->\n    match fut with\n    | NT nt::q =>\n      match goto_table s1 nt with\n      | Some (exist _ s2 _) =>\n        state_has_future s2 prod q lookahead\n      | None => False\n      end\n    | _ => True\n    end.\n\nDefinition start_goto :=\n  forall (init:initstate),\n    match goto_table init (start_nt init) with\n    | None => True\n    | Some _ => False\n    end.\n\n(** Closure property of item sets : if a state contains an item of the form\n    A->_.Bv[[b]], then for each production B->u and each terminal a of\n    first(vb), the state contains an item of the form B->_.u[[a]] **)\nDefinition non_terminal_closed :=\n  forall s1 prod fut lookahead,\n    state_has_future s1 prod fut lookahead ->\n    match fut with\n    | NT nt::q =>\n      forall p, prod_lhs p = nt ->\n        (if nullable_word q then\n           state_has_future s1 p (future_of_prod p 0) lookahead\n         else True) /\\\n        (forall lookahead2,\n           TerminalSet.In lookahead2 (first_word_set q) ->\n             state_has_future s1 p (future_of_prod p 0) lookahead2)\n      | _ => True\n    end.\n\n(** The automaton is complete **)\nDefinition complete :=\n  nullable_stable /\\ first_stable /\\ start_future /\\ terminal_shift\n  /\\ end_reduce /\\ non_terminal_goto /\\ start_goto /\\ non_terminal_closed.\n\nDerive is_complete_0\nSuchThat (forall im, IsItemsMap im -> IsValidator complete (is_complete_0 im))\nAs complete_0_is_validator.\nProof. intros im. subst is_complete_0. instantiate (1:=fun im => _). apply _. Qed.\n\nDefinition is_complete (_:unit) := is_complete_0 (items_map ()).\nLemma complete_is_validator : IsValidator complete (is_complete ()).\nProof. by apply complete_0_is_validator. Qed.\n\nEnd Make.\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/CompCert/MenhirLib/Validator_complete.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.25655460727394686}}
{"text": "(*********************************************************************************************************************************)\n(* HaskProofToStrong: convert HaskProof to HaskStrong                                                                            *)\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.\nRequire Import Coq.Init.Specif.\nRequire Import HaskKinds.\nRequire Import HaskStrongTypes.\nRequire Import HaskStrong.\nRequire Import HaskProof.\n\nSection HaskProofToStrong.\n\n  Context {VV:Type} {eqdec_vv:EqDecidable VV} {freshM:FreshMonad VV}.\n\n  Definition fresh := FMT_fresh freshM.\n  Definition FreshM := FMT freshM.\n  Definition FreshMon := FMT_Monad freshM.\n  Existing Instance FreshMon.\n\n  Definition ExprVarResolver Γ := VV -> LeveledHaskType Γ ★.\n\n  Definition judg2exprType (j:Judg) : Type :=\n    match j with\n      (Γ > Δ > Σ |- τ @ l) => forall (ξ:ExprVarResolver Γ) vars, Σ = mapOptionTree ξ vars ->\n        FreshM (ITree _ (fun t => Expr Γ Δ ξ t l) τ)\n      end.\n\n  Definition justOne Γ Δ ξ τ l : ITree _ (fun t => Expr Γ Δ ξ t l) [τ] -> Expr Γ Δ ξ τ l.\n    intros.\n    inversion X; auto.\n    Defined.\n\n  Definition ileaf `(it:ITree X F [t]) : F t.\n    inversion it.\n    apply X0.\n    Defined.\n\n  Lemma update_branches : forall Γ (ξ:VV -> LeveledHaskType Γ ★) lev l1 l2 q,\n    update_xi ξ lev (app l1 l2) q = update_xi (update_xi ξ lev l2) lev l1 q.\n    intros.\n    induction l1.\n      reflexivity.\n      simpl.\n      destruct a; simpl.\n      rewrite IHl1.\n      reflexivity.\n      Qed.\n\n   Lemma quark {T} (l1:list T) l2 vf :\n      (In vf (app l1 l2)) <->\n       (In vf l1) \\/ (In vf l2).\n     induction l1.\n     simpl; auto.\n     split; intro.\n     right; auto.\n     inversion H.\n     inversion H0.\n     auto.\n     split.\n\n     destruct IHl1.\n     simpl in *.\n     intro.\n     destruct H1.\n     left; left; auto.\n     set (H H1) as q.\n     destruct q.\n     left; right; auto.\n     right; auto.\n     simpl.\n\n     destruct IHl1.\n     simpl in *.\n     intro.\n     destruct H1.\n     destruct H1.\n     left; auto.\n     right; apply H0; auto.\n     right; apply H0; auto.\n   Qed.\n\n  Lemma splitter {T} (l1:list T) l2 vf :\n      (In vf (app l1 l2) → False)\n      -> (In vf l1 → False)  /\\ (In vf l2 → False).\n    intros.\n    split; intros; apply H; rewrite quark.\n    auto.\n    auto.\n    Qed.\n\n  Lemma helper\n    : forall T Z {eqdt:EqDecidable T}(tl:Tree ??T)(vf:T) ξ (q:Z),\n      (In vf (leaves tl) -> False) ->\n      mapOptionTree (fun v' => if eqd_dec vf v' then q else ξ v') tl = \n      mapOptionTree ξ tl.\n    intros.\n    induction tl;\n      try destruct a;\n        simpl in *.\n    set (eqd_dec vf t) as x in *.\n    destruct x.\n    subst.\n      assert False.\n      apply H.\n      left; auto.\n      inversion H0.\n    auto.\n    auto.\n    apply splitter in H.\n    destruct H.\n    rewrite (IHtl1 H).\n    rewrite (IHtl2 H0).\n    reflexivity.\n    Qed.\n    \n  Lemma fresh_lemma'' Γ \n    : forall types ξ lev, \n    FreshM { varstypes : _\n      |  mapOptionTree (update_xi(Γ:=Γ)   ξ lev (leaves varstypes)) (mapOptionTree (@fst _ _) varstypes) = (types @@@ lev)\n      /\\ distinct (leaves (mapOptionTree (@fst _ _) varstypes)) }.\n  admit.\n  Defined.\n\n  Lemma fresh_lemma' Γ \n    : forall types vars Σ ξ lev, Σ = mapOptionTree ξ vars ->\n    FreshM { varstypes : _\n      |  mapOptionTree (update_xi(Γ:=Γ) ξ lev (leaves varstypes)) vars = Σ\n      /\\ mapOptionTree (update_xi       ξ lev (leaves varstypes)) (mapOptionTree (@fst _ _) varstypes) = (types @@@ lev)\n      /\\ distinct (leaves (mapOptionTree (@fst _ _) varstypes)) }.\n    induction types.\n      intros; destruct a.\n        refine (bind vf = fresh (leaves vars) ; return _).\n          apply FreshMon.\n          destruct vf as [ vf vf_pf ].\n          exists [(vf,h)].\n          split; auto.\n          simpl.\n          set (helper VV _ vars vf ξ (h@@lev) vf_pf) as q.\n          rewrite q.\n          symmetry; auto.\n          simpl.\n          destruct (eqd_dec vf vf); [ idtac | set (n (refl_equal _)) as n'; inversion n' ]; auto.\n          split; auto.\n          apply distinct_cons.\n          intro.\n          inversion H0.\n          apply distinct_nil.\n        refine (return _).\n          exists []; auto.\n          split.\n          simpl.\n          symmetry; auto.\n          split.\n          simpl.\n          reflexivity.\n          simpl.\n          apply distinct_nil.\n        intros vars Σ ξ lev pf; refine (bind x2 = IHtypes2 vars Σ ξ lev pf; _).\n          apply FreshMon.\n          destruct x2 as [vt2 [pf21 [pf22 pfdist]]].\n          refine (bind x1 = IHtypes1 (vars,,(mapOptionTree (@fst _ _) vt2)) (Σ,,(types2@@@lev)) (update_xi ξ lev\n            (leaves vt2)) _ _; return _).\n          apply FreshMon.\n          simpl.\n          rewrite pf21.\n          rewrite pf22.\n          reflexivity.\n          clear IHtypes1 IHtypes2.\n          destruct x1 as [vt1 [pf11 pf12]].\n          exists (vt1,,vt2); split; auto.\n\n          set (update_branches Γ ξ lev (leaves vt1) (leaves vt2)) as q.\n          set (mapOptionTree_extensional _ _ q) as q'.\n          rewrite q'.\n          clear q' q.\n          inversion pf11.\n          reflexivity.\n\n          simpl.\n          set (update_branches Γ ξ lev (leaves vt1) (leaves vt2)) as q.\n          set (mapOptionTree_extensional _ _ q) as q'.\n          rewrite q'.\n          rewrite q'.\n          clear q' q.\n          rewrite <- mapOptionTree_compose.\n          rewrite <- mapOptionTree_compose.\n          rewrite <- mapOptionTree_compose in *.\n          split.\n          destruct pf12.\n          rewrite H.\n          inversion pf11.\n          rewrite <- mapOptionTree_compose.\n          reflexivity.\n\n          admit.\n        Defined.\n\n  Lemma fresh_lemma Γ ξ vars Σ Σ' lev\n    : Σ = mapOptionTree ξ vars ->\n    FreshM { vars' : _\n      |  mapOptionTree (update_xi(Γ:=Γ) ξ lev ((vars',Σ')::nil)) vars = Σ\n      /\\ mapOptionTree (update_xi ξ lev ((vars',Σ')::nil)) [vars'] = [Σ' @@ lev] }.\n    intros.\n    set (fresh_lemma' Γ [Σ'] vars Σ ξ lev H) as q.\n    refine (q >>>= fun q' => return _).\n    apply FreshMon.\n    clear q.\n    destruct q' as [varstypes [pf1 [pf2 pfdist]]].\n    destruct varstypes; try destruct o; try destruct p; simpl in *.\n      destruct (eqd_dec v v); [ idtac | set (n (refl_equal _)) as n'; inversion n' ].    \n      inversion pf2; subst.\n      exists v.\n      destruct (eqd_dec v v); [ idtac | set (n (refl_equal _)) as n'; inversion n' ].\n      split; auto.\n      inversion pf2.\n      inversion pf2.\n    Defined.\n\n  Definition ujudg2exprType Γ (ξ:ExprVarResolver Γ)(Δ:CoercionEnv Γ) Σ τ l : Type :=\n    forall vars, Σ = mapOptionTree ξ vars -> FreshM (ITree _ (fun t => Expr Γ Δ ξ t l) τ).\n\n  Definition urule2expr  : forall Γ Δ h j t l (r:@Arrange _ h j) (ξ:VV -> LeveledHaskType Γ ★),\n    ujudg2exprType Γ ξ Δ h t l ->\n    ujudg2exprType Γ ξ Δ j t l\n    .\n    intros Γ Δ.\n      refine (fix urule2expr h j t l (r:@Arrange _ h j) ξ {struct r} : \n    ujudg2exprType Γ ξ Δ h t l ->\n    ujudg2exprType Γ ξ Δ j t l :=\n        match r as R in Arrange H C return\n    ujudg2exprType Γ ξ Δ H t l ->\n    ujudg2exprType Γ ξ Δ C t l\n with\n          | ALeft   h c ctx r => let case_ALeft  := tt in (fun e => _) (urule2expr _ _ _ _ r)\n          | ARight  h c ctx r => let case_ARight := tt in (fun e => _) (urule2expr _ _ _ _ r)\n          | AId     a       => let case_AId    := tt in _\n          | ACanL   a       => let case_ACanL  := tt in _\n          | ACanR   a       => let case_ACanR  := tt in _\n          | AuCanL  a       => let case_AuCanL := tt in _\n          | AuCanR  a       => let case_AuCanR := tt in _\n          | AAssoc  a b c   => let case_AAssoc := tt in _\n          | AuAssoc  a b c   => let case_AuAssoc := tt in _\n          | AExch   a b     => let case_AExch  := tt in _\n          | AWeak   a       => let case_AWeak  := tt in _\n          | ACont   a       => let case_ACont  := tt in _\n          | AComp   a b c f g => let case_AComp  := tt in (fun e1 e2 => _) (urule2expr _ _ _ _ f) (urule2expr _ _ _ _ g)\n          end); clear urule2expr; intros.\n\n      destruct case_AId.\n        apply X.\n\n      destruct case_ACanL.\n        simpl; unfold ujudg2exprType; intros.\n        simpl in X.\n        apply (X ([],,vars)).\n        simpl; rewrite <- H; auto.\n\n      destruct case_ACanR.\n        simpl; unfold ujudg2exprType; intros.\n        simpl in X.\n        apply (X (vars,,[])).\n        simpl; rewrite <- H; auto.\n\n      destruct case_AuCanL.\n        simpl; unfold ujudg2exprType; intros.\n        destruct vars; try destruct o; inversion H.\n        simpl in X.\n        apply (X vars2); auto.\n\n      destruct case_AuCanR.\n        simpl; unfold ujudg2exprType; intros.\n        destruct vars; try destruct o; inversion H.\n        simpl in X.\n        apply (X vars1); auto.\n\n      destruct case_AAssoc.\n        simpl; unfold ujudg2exprType; intros.\n        simpl in X.\n        destruct vars; try destruct o; inversion H.\n        destruct vars1; try destruct o; inversion H.\n        apply (X (vars1_1,,(vars1_2,,vars2))).\n        subst; auto.\n\n      destruct case_AuAssoc.\n        simpl; unfold ujudg2exprType; intros.\n        simpl in X.\n        destruct vars; try destruct o; inversion H.\n        destruct vars2; try destruct o; inversion H.\n        apply (X ((vars1,,vars2_1),,vars2_2)).\n        subst; auto.\n\n      destruct case_AExch.\n        simpl; unfold ujudg2exprType ; intros.\n        simpl in X.\n        destruct vars; try destruct o; inversion H.\n        apply (X (vars2,,vars1)).\n        inversion H; subst; auto.\n        \n      destruct case_AWeak.\n        simpl; unfold ujudg2exprType; intros.\n        simpl in X.\n        apply (X []).\n        auto.\n        \n      destruct case_ACont.\n        simpl; unfold ujudg2exprType ; intros.\n        simpl in X.\n        apply (X (vars,,vars)).\n        simpl.\n        rewrite <- H.\n        auto.\n\n      destruct case_ALeft.\n        intro vars; unfold ujudg2exprType; intro H.\n        destruct vars; try destruct o; inversion H.\n        apply (fun q => e ξ q vars2 H2).\n        clear r0 e H2.\n          simpl in X.\n          simpl.\n          unfold ujudg2exprType.\n          intros.\n          apply X with (vars:=vars1,,vars).\n          rewrite H0.\n          rewrite H1.\n          simpl.\n          reflexivity.\n\n      destruct case_ARight.\n        intro vars; unfold ujudg2exprType; intro H.\n        destruct vars; try destruct o; inversion H.\n        apply (fun q => e ξ q vars1 H1).\n        clear r0 e H2.\n          simpl in X.\n          simpl.\n          unfold ujudg2exprType.\n          intros.\n          apply X with (vars:=vars,,vars2).\n          rewrite H0.\n          inversion H.\n          simpl.\n          reflexivity.\n\n      destruct case_AComp.\n        apply e2.\n        apply e1.\n        apply X.\n        Defined.\n\n  Definition letrec_helper Γ Δ l (varstypes:Tree ??(VV * HaskType Γ ★)) ξ' :\n    ITree (HaskType Γ ★)\n         (fun t : HaskType Γ ★ => Expr Γ Δ ξ' t l)\n         (mapOptionTree (unlev ○ ξ' ○ (@fst _ _)) varstypes)\n         -> ELetRecBindings Γ Δ ξ' l varstypes.\n    intros.\n    induction varstypes.\n    destruct a; simpl in *.\n    destruct p.\n    simpl.\n    apply ileaf in X. simpl in X.\n      apply ELR_leaf.\n      rename h into τ.\n      destruct (eqd_dec (unlev (ξ' v)) τ).\n      rewrite <- e.\n      destruct (ξ' v).\n      simpl.\n      destruct (eqd_dec h0 l).\n        rewrite <- e0.\n        simpl in X.\n        subst.\n        apply X.\n      apply (Prelude_error \"level mismatch; should never happen\").\n      apply (Prelude_error \"letrec type mismatch; should never happen\").\n\n    apply ELR_nil.\n    apply ELR_branch.\n      apply IHvarstypes1; inversion X; auto.\n      apply IHvarstypes2; inversion X; auto.\n    Defined.\n\n  Definition unindex_tree {V}{F} : forall {t:Tree ??V}, ITree V F t -> Tree ??{ v:V & F v }.\n    refine (fix rec t it := match it as IT return Tree ??{ v:V & F v } with\n      | INone => T_Leaf None\n      | ILeaf x y => T_Leaf (Some _)\n      | IBranch _ _ b1 b2 => (rec _ b1),,(rec _ b2)\n            end).\n    exists x; auto.\n    Defined.\n\n  Definition fix_indexing X Y (J:X->Type)(t:Tree ??(X*Y))\n    :  ITree (X * Y) (fun x => J (fst x))                                t\n    -> ITree X       (fun x:X => J x)   (mapOptionTree (@fst _ _) t).\n    intro it.\n    induction it; simpl in *.\n    apply INone.\n    apply ILeaf.\n    apply f.\n    simpl; apply IBranch; auto.\n    Defined.\n\n  Definition fix2 {X}{F} : Tree ??{ x:X & FreshM (F x) } -> Tree ??(FreshM { x:X & F x }).\n    refine (fix rec t := match t with\n      | T_Leaf None => T_Leaf None\n      | T_Leaf (Some x) => T_Leaf (Some _)\n      | T_Branch b1 b2 => T_Branch (rec b1) (rec b2)\n            end).\n    destruct x as [x fx].\n    refine (bind fx' = fx ; return _).\n    apply FreshMon.\n    exists x.\n    apply fx'.\n    Defined.\n  \n  Definition case_helper tc Γ Δ lev tbranches avars ξ :\n    forall pcb:(StrongAltCon * Tree ??(LeveledHaskType Γ ★)),\n     prod (judg2exprType (@pcb_judg tc Γ Δ lev tbranches avars (fst pcb) (snd pcb)))\n     {vars' : Tree ??VV & (snd pcb) = mapOptionTree ξ vars'} ->\n     ((fun sac => FreshM\n       { scb : StrongCaseBranchWithVVs VV eqdec_vv tc avars sac\n         & Expr (sac_gamma sac Γ) (sac_delta sac Γ avars (weakCK'' Δ)) (scbwv_xi scb ξ lev)\n         (weakT' tbranches) (weakL' lev) }) (fst pcb)).\n    intro pcb.\n    intro X.\n    simpl in X.\n    simpl.\n    destruct pcb as [sac pcb].\n    simpl in *.\n\n    destruct X.\n    destruct s as [vars vars_pf].\n\n    refine (bind localvars = fresh_lemma' _ (unleaves  (vec2list (sac_types sac _ avars))) vars \n      (mapOptionTree weakLT' pcb) (weakLT' ○ ξ) (weakL' lev) _  ; _).\n      apply FreshMon.\n      rewrite vars_pf.\n      rewrite <- mapOptionTree_compose.\n      reflexivity.\n      destruct localvars as [localvars [localvars_pf1 [localvars_pf2 localvars_dist ]]].\n      set (mapOptionTree (@fst _ _) localvars) as localvars'.\n\n    set (list2vec (leaves localvars')) as localvars''.\n    cut (length (leaves localvars') = sac_numExprVars sac). intro H''.\n      rewrite H'' in localvars''.\n    cut (distinct (vec2list localvars'')). intro H'''.\n    set (@Build_StrongCaseBranchWithVVs _ _ _ _ avars sac localvars'' H''') as scb.\n\n    refine (bind q = (f (scbwv_xi scb ξ lev) (vars,,(unleaves (vec2list (scbwv_exprvars scb)))) _) ; return _).\n      apply FreshMon.\n      simpl.\n      unfold scbwv_xi.\n      rewrite vars_pf.\n      rewrite <- mapOptionTree_compose.\n      clear localvars_pf1.\n      simpl.\n      rewrite mapleaves'.\n\n    admit.\n\n    exists scb.\n    apply ileaf in q.\n    apply q.\n\n    admit.\n    admit.\n    Defined.\n\n  Definition gather_branch_variables\n    Γ Δ\n    (ξ:VV -> LeveledHaskType Γ ★) tc avars tbranches lev\n    (alts:Tree ??(@StrongAltCon tc * Tree ??(LeveledHaskType Γ ★)))\n    :\n    forall vars,\n    mapOptionTreeAndFlatten (fun x => snd x) alts = mapOptionTree ξ vars\n    -> ITree Judg judg2exprType (mapOptionTree (fun x => @pcb_judg tc Γ Δ lev avars tbranches (fst x) (snd x)) alts)\n    -> ITree _ (fun q => prod (judg2exprType (@pcb_judg tc Γ Δ lev avars tbranches (fst q) (snd q))) \n      { vars' : _ & (snd q) = mapOptionTree ξ vars' })\n  alts.\n    induction alts;\n    intro vars;\n    intro pf;\n    intro source.\n    destruct a; [ idtac | apply INone ].\n    simpl in *.\n    apply ileaf in source.\n    apply ILeaf.\n    destruct p as [sac pcb].\n    simpl in *.\n    split.\n    intros.\n    eapply source.\n    apply H.\n    clear source.\n\n    exists vars.\n    auto.\n\n    simpl in pf.\n    destruct vars; try destruct o; simpl in pf; inversion pf.\n    simpl in source.\n    inversion source.\n    subst.\n    apply IBranch.\n    apply (IHalts1 vars1 H0 X); auto.\n    apply (IHalts2 vars2 H1 X0); auto.\n\n    Defined.\n\n  Lemma manyFresh : forall Γ Σ (ξ0:VV -> LeveledHaskType Γ ★),\n    FreshM { vars : _ & { ξ : VV -> LeveledHaskType Γ ★ & Σ = mapOptionTree ξ vars } }.\n    intros Γ Σ.\n    induction Σ; intro ξ.\n    destruct a.\n    destruct l as [τ l].\n    set (fresh_lemma' Γ [τ] [] [] ξ l (refl_equal _)) as q.\n    refine (q >>>= fun q' => return _).\n    apply FreshMon.\n    clear q.\n    destruct q' as [varstypes [pf1 [pf2 distpf]]].\n    exists (mapOptionTree (@fst _ _) varstypes).\n    exists (update_xi ξ l (leaves varstypes)).\n    symmetry; auto.\n    refine (return _).\n    exists [].\n    exists ξ; auto.\n    refine (bind f1 = IHΣ1 ξ ; _).\n    apply FreshMon.\n    destruct f1 as [vars1 [ξ1 pf1]].\n    refine (bind f2 = IHΣ2 ξ1 ; _).\n    apply FreshMon.\n    destruct f2 as [vars2 [ξ2 pf22]].\n    refine (return _).\n    exists (vars1,,vars2).\n    exists ξ2.\n    simpl.\n    rewrite pf22.\n    rewrite pf1.\n    admit.         (* freshness assumption *)\n    Defined.\n\n  Definition rlet Γ Δ Σ₁ Σ₂ σ₁ σ₂ p :\n    forall (X_ : ITree Judg judg2exprType\n         ([Γ > Δ > Σ₁ |- [σ₁] @ p],, [Γ > Δ > [σ₁ @@  p],, Σ₂ |- [σ₂] @ p])),\n   ITree Judg judg2exprType [Γ > Δ > Σ₁,, Σ₂ |- [σ₂] @ p].\n    intros.\n    apply ILeaf.\n    simpl in *; intros.\n    destruct vars; try destruct o; inversion H.\n\n    refine (fresh_lemma _ ξ _ _ σ₁ p H2 >>>= (fun pf => _)).\n    apply FreshMon.\n\n    destruct pf as [ vnew [ pf1 pf2 ]].\n    set (update_xi ξ p (((vnew, σ₁ )) :: nil)) as ξ' in *.\n    inversion X_.\n    apply ileaf in X.\n    apply ileaf in X0.\n    simpl in *.\n\n    refine (X ξ vars1 _ >>>= fun X0' => _).\n    apply FreshMon.\n    simpl.\n    auto.\n\n    refine (X0 ξ' ([vnew],,vars2) _ >>>= fun X1' => _).\n    apply FreshMon.\n    simpl.\n    rewrite pf2.\n    rewrite pf1.\n    reflexivity.\n    apply FreshMon.\n\n    apply ILeaf.\n    apply ileaf in X1'.\n    apply ileaf in X0'.\n    simpl in *.\n    apply ELet with (ev:=vnew)(tv:=σ₁).\n    apply X0'.\n    apply X1'.\n    Defined.\n\n  Definition vartree Γ Δ Σ lev ξ :\n    forall vars, Σ @@@ lev = mapOptionTree ξ vars ->\n    ITree (HaskType Γ ★) (fun t : HaskType Γ ★ => Expr Γ Δ ξ t lev) Σ.\n    induction Σ; intros.\n    destruct a.\n    intros; simpl in *.\n    apply ILeaf.\n    destruct vars; try destruct o; inversion H.\n    set (EVar Γ Δ ξ v) as q.\n    rewrite <- H1 in q.\n    apply q.\n    intros.\n    apply INone.\n    intros.\n    destruct vars; try destruct o; inversion H.\n    apply IBranch.\n    eapply IHΣ1.\n    apply H1.\n    eapply IHΣ2.\n    apply H2.\n    Defined.\n\n\n  Definition rdrop  Γ Δ Σ₁ Σ₁₂ a lev :\n    ITree Judg judg2exprType [Γ > Δ > Σ₁ |- a,,Σ₁₂ @ lev] ->\n    ITree Judg judg2exprType [Γ > Δ > Σ₁ |- a @ lev].\n    intros.\n    apply ileaf in X.\n    apply ILeaf.\n    simpl in *.\n    intros.\n    set (X ξ vars H) as q.\n    simpl in q.\n    refine (q >>>= fun q' => return _).\n    apply FreshMon.\n    inversion q'.\n    apply X0.\n    Defined.\n\n  Definition rdrop'  Γ Δ Σ₁ Σ₁₂ a lev :\n    ITree Judg judg2exprType [Γ > Δ > Σ₁ |- Σ₁₂,,a @ lev] ->\n    ITree Judg judg2exprType [Γ > Δ > Σ₁ |- a @ lev].\n    intros.\n    apply ileaf in X.\n    apply ILeaf.\n    simpl in *.\n    intros.\n    set (X ξ vars H) as q.\n    simpl in q.\n    refine (q >>>= fun q' => return _).\n    apply FreshMon.\n    inversion q'.\n    auto.\n    Defined.\n\n  Definition rdrop''  Γ Δ Σ₁ Σ₁₂ lev :\n    ITree Judg judg2exprType [Γ > Δ > [],,Σ₁ |- Σ₁₂ @ lev] ->\n    ITree Judg judg2exprType [Γ > Δ > Σ₁ |- Σ₁₂ @ lev].\n    intros.\n    apply ileaf in X.\n    apply ILeaf.\n    simpl in *; intros.\n    eapply X with (vars:=[],,vars).\n    rewrite H; reflexivity.\n    Defined.\n\n  Definition rdrop'''  Γ Δ a Σ₁ Σ₁₂ lev :\n    ITree Judg judg2exprType [Γ > Δ > Σ₁ |- Σ₁₂ @ lev] ->\n    ITree Judg judg2exprType [Γ > Δ > a,,Σ₁ |- Σ₁₂ @ lev].\n    intros.\n    apply ileaf in X.\n    apply ILeaf.\n    simpl in *; intros.\n    destruct vars; try destruct o; inversion H.\n    eapply X with (vars:=vars2).\n    auto.\n    Defined.\n\n  Definition rassoc  Γ Δ Σ₁ a b c lev :\n    ITree Judg judg2exprType [Γ > Δ > ((a,,b),,c) |- Σ₁ @ lev] ->\n    ITree Judg judg2exprType [Γ > Δ > (a,,(b,,c)) |- Σ₁ @ lev].\n    intros.\n    apply ileaf in X.\n    apply ILeaf.\n    simpl in *; intros.\n    destruct vars; try destruct o; inversion H.\n    destruct vars2; try destruct o; inversion H2.\n    apply X with (vars:=(vars1,,vars2_1),,vars2_2).\n    subst; reflexivity.\n    Defined.\n\n  Definition rassoc'  Γ Δ Σ₁ a b c lev :\n    ITree Judg judg2exprType [Γ > Δ > (a,,(b,,c)) |- Σ₁ @ lev] ->\n    ITree Judg judg2exprType [Γ > Δ > ((a,,b),,c) |- Σ₁ @ lev].\n    intros.\n    apply ileaf in X.\n    apply ILeaf.\n    simpl in *; intros.\n    destruct vars; try destruct o; inversion H.\n    destruct vars1; try destruct o; inversion H1.\n    apply X with (vars:=vars1_1,,(vars1_2,,vars2)).\n    subst; reflexivity.\n    Defined.\n\n  Definition swapr  Γ Δ Σ₁ a b c lev :\n    ITree Judg judg2exprType [Γ > Δ > ((a,,b),,c) |- Σ₁ @ lev] ->\n    ITree Judg judg2exprType [Γ > Δ > ((b,,a),,c) |- Σ₁ @ lev].\n    intros.\n    apply ileaf in X.\n    apply ILeaf.\n    simpl in *; intros.\n    destruct vars; try destruct o; inversion H.\n    destruct vars1; try destruct o; inversion H1.\n    apply X with (vars:=(vars1_2,,vars1_1),,vars2).\n    subst; reflexivity.\n    Defined.\n\n  Definition rdup  Γ Δ Σ₁ a  c lev :\n    ITree Judg judg2exprType [Γ > Δ > ((a,,a),,c) |- Σ₁ @ lev] ->\n    ITree Judg judg2exprType [Γ > Δ > (a,,c) |- Σ₁ @ lev].\n    intros.\n    apply ileaf in X.\n    apply ILeaf.\n    simpl in *; intros.\n    destruct vars; try destruct o; inversion H.\n    apply X with (vars:=(vars1,,vars1),,vars2).    (* is this allowed? *)\n    subst; reflexivity.\n    Defined.\n\n  (* holy cow this is ugly *)\n  Definition rcut Γ Δ  Σ₃ lev  Σ₁₂  :\n    forall Σ₁ Σ₂,\n    ITree Judg judg2exprType [Γ > Δ > Σ₁ |-  Σ₁₂ @ lev] ->\n    ITree Judg judg2exprType [Γ > Δ >  Σ₁₂ @@@ lev,,Σ₂ |- [Σ₃] @ lev] ->\n    ITree Judg judg2exprType [Γ > Δ > Σ₁,,Σ₂ |- [Σ₃] @ lev].\n\n    induction Σ₁₂.\n    intros.\n    destruct a.\n\n    eapply rlet.\n    apply IBranch.\n    apply X.\n    apply X0.\n\n    simpl in X0.\n    apply rdrop'' in X0.\n    apply rdrop'''.\n    apply X0.\n\n    intros.\n    simpl in X0.\n    apply rassoc in X0.\n    set (IHΣ₁₂1 _ _ (rdrop  _ _ _ _ _ _ X) X0) as q.\n    set (IHΣ₁₂2 _ (Σ₁,,Σ₂) (rdrop' _ _ _ _ _ _ X)) as q'.\n    apply rassoc' in q.\n    apply swapr in q.\n    apply rassoc in q.\n    set (q' q) as q''.\n    apply rassoc' in q''.\n    apply rdup in q''.\n    apply q''.\n    Defined.\n\n  Definition rule2expr : forall h j (r:Rule h j), ITree _ judg2exprType h -> ITree _ judg2exprType j.\n\n    intros h j r.\n\n      refine (match r as R in Rule H C return ITree _ judg2exprType H -> ITree _ judg2exprType C with\n      | RArrange a b c d e l r        => let case_RURule := tt        in _\n      | RNote   Γ Δ Σ τ l n           => let case_RNote := tt         in _\n      | RLit    Γ Δ l     _           => let case_RLit := tt          in _\n      | RVar    Γ Δ σ         p       => let case_RVar := tt          in _\n      | RGlobal Γ Δ σ l wev           => let case_RGlobal := tt       in _\n      | RLam    Γ Δ Σ tx te     x     => let case_RLam := tt          in _\n      | RCast   Γ Δ Σ σ τ γ     x     => let case_RCast := tt         in _\n      | RAbsT   Γ Δ Σ κ σ a n         => let case_RAbsT := tt         in _\n      | RAppT   Γ Δ Σ κ σ τ     y     => let case_RAppT := tt         in _\n      | RAppCo  Γ Δ Σ κ σ₁ σ₂ γ σ l   => let case_RAppCo := tt        in _\n      | RAbsCo  Γ Δ Σ κ σ  σ₁ σ₂  y   => let case_RAbsCo := tt        in _\n      | RApp    Γ Δ Σ₁ Σ₂ tx te p     => 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   Σ a b c n m           => let case_RBrak := tt         in _\n      | REsc    Σ a b c n m           => 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); intro X_; try apply ileaf in X_; simpl in X_.\n\n    destruct case_RURule.\n      apply ILeaf. simpl. intros.\n      set (@urule2expr a b _ _ e l r0 ξ) as q.\n      unfold ujudg2exprType.\n      unfold ujudg2exprType in q.\n      apply q with (vars:=vars).\n      intros.\n      apply X_ with (vars:=vars0).\n      auto.\n      auto.\n\n  destruct case_RBrak.\n    apply ILeaf; simpl; intros; refine (X_ ξ vars H >>>= fun X => return ILeaf _ _). apply FreshMon.\n    apply EBrak.\n    apply (ileaf X).\n\n  destruct case_REsc.\n    apply ILeaf; simpl; intros; refine (X_ ξ vars H >>>= fun X => return ILeaf _ _). apply FreshMon.\n    apply EEsc.\n    apply (ileaf X).\n\n  destruct case_RNote.\n    apply ILeaf; simpl; intros; refine (X_ ξ vars H >>>= fun X => return ILeaf _ _). apply FreshMon.\n    apply ENote; auto.\n    apply (ileaf X).\n\n  destruct case_RLit.\n    apply ILeaf; simpl; intros; refine (return ILeaf _ _).\n    apply ELit.\n\n  destruct case_RVar.\n    apply ILeaf; simpl; intros; refine (return ILeaf _ _).\n    destruct vars; simpl in H; inversion H; destruct o. inversion H1.\n    set (@EVar _ _ _ Δ ξ v) as q.\n    rewrite <- H2 in q.\n    simpl in q.\n    apply q.\n    inversion H.\n\n  destruct case_RGlobal.\n    apply ILeaf; simpl; intros; refine (return ILeaf _ _).\n    apply EGlobal.\n\n  destruct case_RLam.\n    apply ILeaf.\n    simpl in *; intros.\n    refine (fresh_lemma _ ξ vars _ tx x H >>>= (fun pf => _)).\n    apply FreshMon.\n    destruct pf as [ vnew [ pf1 pf2 ]].\n    set (update_xi ξ x (((vnew, tx  )) :: nil)) as ξ' in *.\n    refine (X_ ξ' (vars,,[vnew]) _ >>>= _).\n    apply FreshMon.\n    simpl.\n    rewrite pf1.\n    rewrite <- pf2.\n    simpl.\n    reflexivity.\n    intro hyp.\n    refine (return _).\n    apply ILeaf.\n    apply ELam with (ev:=vnew).\n    apply ileaf in hyp.\n    simpl in hyp.\n    unfold ξ' in hyp.\n    apply hyp.\n\n  destruct case_RCast.\n    apply ILeaf; simpl; intros; refine (X_ ξ vars H >>>= fun X => return ILeaf _ _). apply FreshMon.\n    eapply ECast.\n    apply x.\n    apply ileaf in X. simpl in X.\n    apply X.\n\n  destruct case_RApp.    \n    apply ILeaf.\n    inversion X_.\n    inversion X.\n    inversion X0.\n    simpl in *.\n    intros.\n    destruct vars. try destruct o; inversion H.\n    simpl in H.\n    inversion H.\n    set (X1 ξ vars1 H5) as q1.\n    set (X2 ξ vars2 H6) as q2.\n    refine (q1 >>>= fun q1' => q2 >>>= fun q2' => return _).\n    apply FreshMon.\n    apply FreshMon.\n    apply ILeaf.\n    apply ileaf in q1'.\n    apply ileaf in q2'.\n    simpl in *.\n    apply (EApp _ _ _ _ _ _ q1' q2').\n\n  destruct case_RCut.\n    apply rassoc.\n    apply swapr.\n    apply rassoc'.\n\n    inversion X_.\n    subst.\n    clear X_.\n\n    apply rassoc' in X0.\n    apply swapr in X0.\n    apply rassoc in X0.\n\n    induction Σ₃.\n    destruct a.\n    subst.\n    eapply rcut.\n    apply X.\n    apply X0.\n\n    apply ILeaf.\n    simpl.\n    intros.\n    refine (return _).\n    apply INone.\n    set (IHΣ₃1 (rdrop  _ _ _ _ _ _ X0)) as q1.\n    set (IHΣ₃2 (rdrop' _ _ _ _ _ _ X0)) as q2.\n    apply ileaf in q1.\n    apply ileaf in q2.\n    simpl in *.\n    apply ILeaf.\n    simpl.\n    intros.\n    refine (q1 _ _ H >>>= fun q1' => q2 _ _ H >>>= fun q2' => return _).\n    apply FreshMon.\n    apply FreshMon.\n    apply IBranch; auto.\n\n  destruct case_RLeft.\n    apply ILeaf.\n    simpl; intros.\n    destruct vars; try destruct o; inversion H.\n    refine (X_ _ _ H2 >>>= fun X' => return _).\n    apply FreshMon.\n    apply IBranch.\n    eapply vartree.\n    apply H1.\n    apply X'.\n\n  destruct case_RRight.\n    apply ILeaf.\n    simpl; intros.\n    destruct vars; try destruct o; inversion H.\n    refine (X_ _ _ H1 >>>= fun X' => return _).\n    apply FreshMon.\n    apply IBranch.\n    apply X'.\n    eapply vartree.\n    apply H2.\n\n  destruct case_RVoid.\n    apply ILeaf; simpl; intros.\n    refine (return _).\n    apply INone.\n\n  destruct case_RAppT.\n    apply ILeaf; simpl; intros; refine (X_ ξ vars H >>>= fun X => return ILeaf _ _). apply FreshMon.\n    apply ETyApp.\n    apply (ileaf X).\n\n  destruct case_RAbsT.\n    apply ILeaf; simpl; intros; refine (X_ (weakLT_ ○ ξ) vars _ >>>= fun X => return ILeaf _ _). apply FreshMon.\n    rewrite mapOptionTree_compose.\n    rewrite <- H.\n    reflexivity.\n    apply ileaf in X. simpl in *.\n    apply (ETyLam _ _ _ _ _ _ n).\n    apply X.\n\n  destruct case_RAppCo.\n    apply ILeaf; simpl; intros; refine (X_ ξ vars _ >>>= fun X => return ILeaf _ _). apply FreshMon.\n    auto.\n    eapply ECoApp.\n    apply γ.\n    apply (ileaf X).\n\n  destruct case_RAbsCo.\n    apply ILeaf; simpl; intros; refine (X_ ξ vars _ >>>= fun X => return ILeaf _ _). apply FreshMon.\n    auto.\n    eapply ECoLam.\n    apply (ileaf X).\n\n  destruct case_RLetRec.\n    apply ILeaf; simpl; intros.\n    refine (bind ξvars = fresh_lemma' _ y _ _ _ t H; _). apply FreshMon.\n    destruct ξvars as [ varstypes [ pf1[ pf2 pfdist]]].\n    refine (X_ ((update_xi ξ t (leaves varstypes)))\n      ((mapOptionTree (@fst _ _) varstypes),,vars) _ >>>= fun X => return _); clear X_.  apply FreshMon.\n    simpl.\n    rewrite pf2.\n    rewrite pf1.\n    auto.\n    apply ILeaf.\n    inversion X; subst; clear X.\n\n    apply (@ELetRec _ _ _ _ _ _ _ varstypes).\n    auto.\n    apply (@letrec_helper Γ Δ t varstypes).\n    rewrite mapOptionTree_compose.\n    rewrite mapOptionTree_compose.\n    rewrite pf2.\n    replace ((mapOptionTree unlev (y @@@ t))) with y.\n      apply X0.\n      clear pf1 X0 X1 pfdist pf2 vars varstypes.\n      induction y; try destruct a; auto.\n      rewrite IHy1 at 1.\n      rewrite IHy2 at 1.\n      reflexivity.\n    apply ileaf in X1.\n    simpl in X1.\n    apply X1.\n\n  destruct case_RCase.\n    apply ILeaf; simpl; intros.\n    inversion X_.\n    clear X_.\n    subst.\n    apply ileaf in X0.\n    simpl in X0.\n\n    (* body_freevars and alts_freevars are the types of variables in the body and alternatives (respectively) which are free\n     * from the viewpoint just outside the case block -- i.e. not bound by any of the branches *)\n    rename Σ into body_freevars_types.\n    rename vars into all_freevars.\n    rename X0 into body_expr.\n    rename X  into alts_exprs.\n\n    destruct all_freevars; try destruct o; inversion H.\n    rename all_freevars2 into body_freevars.\n    rename all_freevars1 into alts_freevars.\n\n    set (gather_branch_variables _ _ _ _ _ _ _ _ _ H1 alts_exprs) as q.\n    set (itmap (fun pcb alt_expr => case_helper tc Γ Δ lev tbranches avars ξ pcb alt_expr) q) as alts_exprs'.\n    apply fix_indexing in alts_exprs'.\n    simpl in alts_exprs'.\n    apply unindex_tree in alts_exprs'.\n    simpl in alts_exprs'.\n    apply fix2 in alts_exprs'.\n    apply treeM in alts_exprs'.\n\n    refine ( alts_exprs' >>>= fun Y =>\n      body_expr ξ _ _\n      >>>= fun X => return ILeaf _ (@ECase _ _ _ _ _ _ _ _ _ (ileaf X) Y)); auto.\n      apply FreshMon.\n      apply FreshMon.\n      apply H2.\n    Defined.\n\n  Fixpoint closed2expr h j (pn:@SIND _ Rule h j) {struct pn} : ITree _ judg2exprType h -> ITree _ judg2exprType j :=\n    match pn in @SIND _ _ H J return ITree _ judg2exprType H -> ITree _ judg2exprType J with\n    | scnd_weak   _             => let case_nil    := tt in fun _ => INone _ _\n    | scnd_comp   x h c cnd' r  => let case_rule   := tt in fun q => rule2expr _ _ r (closed2expr _ _ cnd' q)\n    | scnd_branch _ _ _ c1 c2   => let case_branch := tt in fun q => IBranch _ _ (closed2expr _ _ c1 q) (closed2expr _ _ c2 q)\n    end.\n\n  Definition proof2expr Γ Δ τ l Σ (ξ0: VV -> LeveledHaskType Γ ★)\n    {zz:ToString VV} : ND Rule [] [Γ > Δ > Σ |- [τ] @ l] ->\n    FreshM (???{ ξ : _ & Expr Γ Δ ξ τ l}).\n    intro pf.\n    set (mkSIND systemfc_all_rules_one_conclusion _ _ _ pf (scnd_weak [])) as cnd.\n    apply closed2expr in cnd.\n    apply ileaf in cnd.\n    simpl in *.\n    clear pf.\n    refine (bind ξvars = manyFresh _ Σ ξ0; _).\n    apply FreshMon.\n    destruct ξvars as [vars ξpf].\n    destruct ξpf as [ξ pf].\n    refine (cnd ξ vars _ >>>= fun it => _).\n    apply FreshMon.\n    auto.\n    refine (return OK _).\n    exists ξ.\n    apply ileaf in it.\n    simpl in it.\n    apply it.\n    apply INone.\n    Defined.\n\nEnd HaskProofToStrong.\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/HaskProofToStrong.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4532618480153862, "lm_q1q2_score": 0.25655460727394686}}
{"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.\nRequire Import MemoryFacts.\n\nRequire Import Cover.\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_split_same\n        mem0 loc ts1 ts2 ts3 msg2 msg3 mem1 mem2\n        (ADD1: Memory.add mem0 loc ts1 ts3 msg3 mem1)\n        (SPLIT2: Memory.split mem1 loc ts1 ts2 ts3 msg2 msg3 mem2):\n    exists mem1',\n      <<ADD1: Memory.add mem0 loc ts1 ts2 msg2 mem1'>> /\\\n      <<ADD2: Memory.add mem1' loc ts2 ts3 msg3 mem2>>.\n  Proof.\n    exploit (@Memory.add_exists mem0 loc ts1 ts2 msg2); eauto.\n    { i. inv ADD1. inv ADD. hexploit DISJOINT; eauto. i.\n      eapply Interval.le_disjoint; eauto. econs; [refl|].\n      inv SPLIT2. inv SPLIT. left. auto.\n    }\n    { inv SPLIT2. inv SPLIT. auto. }\n    { inv SPLIT2. inv SPLIT. auto. }\n    i. des.\n    exploit (@Memory.add_exists mem3 loc ts2 ts3 msg3); eauto.\n    { i. revert GET2. erewrite Memory.add_o; eauto. condtac; ss.\n      - des. subst. i. inv GET2.\n        symmetry. apply Interval.disjoint_imm.\n      - i. inv ADD1. inv ADD. hexploit DISJOINT; eauto. i.\n        eapply Interval.le_disjoint; eauto. econs; [|refl].\n        inv SPLIT2. inv SPLIT. left. auto.\n    }\n    { inv SPLIT2. inv SPLIT. auto. }\n    { inv ADD1. inv ADD. auto. }\n    i. des.\n    cut (mem4 = mem2); [by i; subst; eauto|].\n    apply Memory.ext. i.\n    erewrite Memory.add_o; eauto. erewrite Memory.add_o; eauto.\n    erewrite (@Memory.split_o mem2); eauto. erewrite (@Memory.add_o mem1); eauto.\n    repeat (condtac; ss). des. repeat subst.\n    inv SPLIT2. inv SPLIT. exfalso. eapply Time.lt_strorder. eauto.\n  Qed.\n\n  Lemma add_split\n        mem0 loc1 from1 to1 msg1\n        mem1 loc2 ts21 ts22 ts23 msg22 msg23\n        mem2\n        (ADD1: Memory.add mem0 loc1 from1 to1 msg1 mem1)\n        (SPLIT2: Memory.split mem1 loc2 ts21 ts22 ts23 msg22 msg23 mem2):\n    (loc1 = loc2 /\\ from1 = ts21 /\\ to1 = ts23 /\\ msg1 = msg23 /\\\n     exists mem1',\n       <<ADD1: Memory.add mem0 loc2 ts21 ts22 msg22 mem1'>> /\\\n       <<ADD2: Memory.add mem1' loc2 ts22 ts23 msg23 mem2>>) \\/\n    (<<LOCTS1: (loc1, to1) <> (loc2, ts23)>> /\\\n     exists mem1',\n       <<SPLIT1: Memory.split mem0 loc2 ts21 ts22 ts23 msg22 msg23 mem1'>> /\\\n       <<ADD2: Memory.add mem1' loc1 from1 to1 msg1 mem2>>).\n  Proof.\n    exploit Memory.split_get0; eauto. i. des.\n    revert GET0. erewrite Memory.add_o; eauto. condtac; ss.\n    { des. i. inv GET0. left. splits; eauto.\n      eapply add_split_same; eauto.\n    }\n    guardH o. i. right. splits.\n    { ii. inv H. unguardH o. des; congr. }\n    exploit (@Memory.split_exists mem0 loc2 ts21 ts22 ts23);\n      try by inv SPLIT2; inv SPLIT; eauto.\n    i. des.\n    exploit (@Memory.add_exists mem3 loc1 from1 to1);\n      try by inv ADD1; inv ADD; eauto.\n    { i. revert GET3. erewrite Memory.split_o; eauto. repeat condtac; ss.\n      - des. subst. i. inv GET3.\n        inv ADD1. inv ADD. hexploit DISJOINT; eauto. i. symmetry in H.\n        symmetry. eapply Interval.le_disjoint; eauto. econs; [refl|].\n        inv SPLIT2. inv SPLIT. left. auto.\n      - guardH o0. i. des. inv GET3.\n        inv ADD1. inv ADD. hexploit DISJOINT; eauto. i. symmetry in H.\n        symmetry. eapply Interval.le_disjoint; eauto. econs; [|refl].\n        inv SPLIT2. inv SPLIT. left. auto.\n      - guardH o0. i. inv ADD1. inv ADD. eapply DISJOINT; eauto.\n    }\n    i. des.\n    esplits; eauto.\n    cut (mem4 = mem2); [by i; subst; eauto|].\n    apply Memory.ext. i.\n    erewrite Memory.add_o; eauto. erewrite Memory.split_o; eauto.\n    setoid_rewrite Memory.split_o; cycle 1; eauto.\n    erewrite (@Memory.add_o mem1); eauto.\n    repeat (condtac; ss).\n    - des. repeat subst.\n      exploit Memory.add_get0; try exact ADD1; eauto. i. des.\n      exploit Memory.split_get0; try exact SPLIT2; eauto. i. des.\n      congr.\n    - guardH o0. des. repeat subst. unguardH o. des; congr.\n  Qed.\n\n  Lemma add_lower\n        mem0 loc1 from1 to1 msg1\n        mem1 loc2 from2 to2 msg2 msg2'\n        mem2\n        (ADD1: Memory.add mem0 loc1 from1 to1 msg1 mem1)\n        (LOWER2: Memory.lower mem1 loc2 from2 to2 msg2 msg2' mem2):\n    (loc1 = loc2 /\\ from1 = from2 /\\ to1 = to2 /\\ msg1 = msg2 /\\\n     Memory.add mem0 loc1 from1 to1 msg2' mem2) \\/\n    (<<LOCTS1: (loc1, to1) <> (loc2, to2)>> /\\\n     exists mem1',\n       <<LOWER1: Memory.lower mem0 loc2 from2 to2 msg2 msg2' mem1'>> /\\\n       <<ADD2: Memory.add mem1' loc1 from1 to1 msg1 mem2>>).\n  Proof.\n    exploit Memory.lower_get0; eauto.\n    erewrite Memory.add_o; eauto. condtac; ss.\n    - des. subst. i. des. inv GET. left. splits; eauto.\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    - guardH o. i. des. right. splits.\n      { ii. inv H. unguardH o. des; congr. }\n      exploit (@Memory.lower_exists mem0 loc2 from2 to2);\n        try by inv LOWER2; inv LOWER; eauto.\n      i. des.\n      exploit (@Memory.add_exists mem3 loc1 from1 to1).\n      { i. revert GET2. erewrite Memory.lower_o; eauto. condtac; ss.\n        - des. subst. i. inv GET2.\n          exploit Memory.lower_get0; eauto. i. des.\n          inv ADD1. inv ADD. eapply DISJOINT. eauto.\n        - guardH o0. 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.\n      cut (mem4 = mem2); [by i; subst; eauto|].\n      apply Memory.ext. i.\n      erewrite Memory.add_o; eauto. erewrite Memory.lower_o; eauto.\n      setoid_rewrite Memory.lower_o; cycle 1; eauto.\n      erewrite (@Memory.add_o mem1); eauto.\n      repeat (condtac; ss). des. repeat subst.\n      unguardH o. des; 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 split_add\n        mem0 loc1 ts11 ts12 ts13 msg12 msg13\n        mem1 loc2 from2 to2 msg2\n        mem2\n        (SPLIT1: Memory.split mem0 loc1 ts11 ts12 ts13 msg12 msg13 mem1)\n        (ADD2: Memory.add mem1 loc2 from2 to2 msg2 mem2):\n    <<LOCTS1: (loc1, ts12) <> (loc2, to2)>> /\\\n    <<LOCTS2: (loc1, ts13) <> (loc2, to2)>> /\\\n    exists mem1',\n      <<ADD1: Memory.add mem0 loc2 from2 to2 msg2 mem1'>> /\\\n      <<SPLIT2: Memory.split mem1' loc1 ts11 ts12 ts13 msg12 msg13 mem2>>.\n  Proof.\n    exploit (@Memory.add_exists mem0 loc2 from2 to2);\n      try by inv ADD2; inv ADD; eauto.\n    { apply covered_disjoint_get_disjoint. i. rewrite <- split_covered in H; eauto.\n      eapply get_disjoint_covered_disjoint; eauto. inv ADD2. inv ADD. auto.\n    }\n    i. des.\n    exploit (@Memory.split_exists mem3 loc1 ts11 ts12 ts13);\n      try by inv SPLIT1; inv SPLIT; eauto.\n    { erewrite Memory.add_o; eauto. condtac; ss.\n      - des. subst.\n        hexploit Memory.add_get0; try exact ADD2; eauto. i. des.\n        revert GET. erewrite Memory.split_o; eauto. repeat condtac; ss.\n      - guardH o. hexploit Memory.split_get0; eauto. i. des. eauto.\n    }\n    i. des.\n    splits.\n    { ii. inv H.\n      hexploit Memory.add_get0; try exact ADD2; eauto. i. des.\n      revert GET. erewrite Memory.split_o; eauto. repeat condtac; ss.\n      guardH o0. des; congr.\n    }\n    { ii. inv H.\n      hexploit Memory.add_get0; try exact ADD2; eauto. i. des.\n      revert GET. erewrite Memory.split_o; eauto. repeat condtac; ss.\n      guardH o. des; congr.\n    }\n    cut (mem4 = mem2); [by i; subst; eauto|].\n    apply Memory.ext. i.\n    erewrite Memory.split_o; eauto. erewrite Memory.add_o; eauto.\n    erewrite (@Memory.add_o mem2); eauto. erewrite (@Memory.split_o mem1); eauto.\n    repeat (condtac; ss).\n    - des. repeat subst.\n      hexploit Memory.add_get0; try exact ADD2; eauto. i. des.\n      revert GET. erewrite Memory.split_o; eauto. repeat condtac; ss.\n    - guardH o. des. repeat subst.\n      hexploit Memory.add_get0; try exact ADD2; eauto. i. des.\n      revert GET. erewrite Memory.split_o; eauto. repeat condtac; ss.\n  Qed.\n\n  Lemma split_split\n        mem0 loc1 ts11 ts12 ts13 msg12 msg13\n        mem1 loc2 ts21 ts22 ts23 msg22 msg23\n        mem2\n        (LOCTS1: (loc1, ts13) <> (loc2, ts23))\n        (SPLIT1: Memory.split mem0 loc1 ts11 ts12 ts13 msg12 msg13 mem1)\n        (SPLIT2: Memory.split mem1 loc2 ts21 ts22 ts23 msg22 msg23 mem2):\n    (loc1 = loc2 /\\ ts21 = ts11 /\\ ts23 = ts12 /\\\n     exists mem1',\n       <<SPLIT1: Memory.split mem0 loc2 ts21 ts22 ts13 msg22 msg13 mem1'>> /\\\n       <<SPLIT2: Memory.split mem1' loc1 ts22 ts12 ts13 msg12 msg13 mem2>>) \\/\n    ((loc2, ts21, ts23) <> (loc1, ts11, ts12) /\\\n     exists mem1',\n       <<SPLIT1: Memory.split mem0 loc2 ts21 ts22 ts23 msg22 msg23 mem1'>> /\\\n       <<SPLIT2: Memory.split mem1' loc1 ts11 ts12 ts13 msg12 msg13 mem2>>).\n  Proof.\n    exploit Memory.split_get0; try exact SPLIT2; eauto. i. des.\n    revert GET0. erewrite Memory.split_o; eauto. repeat condtac; ss.\n    - i. des. inv GET0. left. splits; auto.\n      exploit Memory.split_get0; try exact SPLIT1; eauto. i. des.\n      exploit Memory.split_get0; try exact SPLIT2; eauto. i. des.\n      revert GET4. erewrite Memory.split_o; eauto. condtac; ss.\n      exploit (@Memory.split_exists mem0 loc1 ts21 ts22 ts13);\n        try by inv SPLIT2; inv SPLIT; eauto.\n      { etrans.\n        - inv SPLIT2. inv SPLIT. eauto.\n        - inv SPLIT1. inv SPLIT. eauto.\n      }\n      i. des.\n      exploit (@Memory.split_exists mem3 loc1 ts22 ts12 ts13);\n        (try by inv SPLIT1; inv SPLIT; eauto);\n        (try by inv SPLIT2; inv SPLIT; eauto).\n      { erewrite Memory.split_o; eauto. repeat condtac; ss.\n        - des. subst. inv x0. inv SPLIT.\n          exfalso. eapply Time.lt_strorder. eauto.\n        - guardH o. des; congr.\n      }\n      i. des.\n      cut (mem4 = mem2); [by i; subst; eauto|].\n      apply Memory.ext. i.\n      erewrite Memory.split_o; eauto. erewrite Memory.split_o; eauto.\n      erewrite (@Memory.split_o mem2); eauto. erewrite (@Memory.split_o mem1); eauto.\n      repeat (condtac; ss).\n      + des. repeat subst. inv x1. inv SPLIT.\n        exfalso. eapply Time.lt_strorder. eauto.\n      + guardH o. des. repeat subst. inv x0. inv SPLIT.\n        exfalso. eapply Time.lt_strorder. eauto.\n    - guardH o. i. des. inv GET0. congr.\n    - guardH o. guardH o0. i. right.\n      exploit (@Memory.split_exists mem0 loc2 ts21 ts22 ts23);\n        try by inv SPLIT2; inv SPLIT; eauto. i. des.\n      exploit (@Memory.split_exists mem3 loc1 ts11 ts12 ts13);\n        try by inv SPLIT1; inv SPLIT; eauto.\n      { erewrite Memory.split_o; eauto. repeat condtac; ss.\n        - des. subst. hexploit Memory.split_get0; try exact SPLIT2; eauto. i. des.\n          revert GET3. erewrite Memory.split_o; eauto. repeat condtac; ss.\n        - guardH o1. des. subst. unguardH o0. des; congr.\n        - guardH o1. guardH o2. hexploit Memory.split_get0; try exact SPLIT1; eauto. i. des. eauto.\n      }\n      i. des. splits.\n      { ii. inv H. unguardH o. des; congr. }\n      cut (mem4 = mem2); [by i; subst; eauto|].\n      apply Memory.ext. i.\n      erewrite Memory.split_o; eauto. erewrite Memory.split_o; eauto.\n      erewrite (@Memory.split_o mem2); eauto. erewrite (@Memory.split_o mem1); eauto.\n      repeat (condtac; ss).\n      + des. repeat subst.\n        exploit Memory.split_get0; try exact SPLIT2; eauto. i. des.\n        revert GET3. erewrite Memory.split_o; eauto. repeat condtac; ss.\n      + guardH o1. des. repeat subst. unguardH o. des; congr.\n      + guardH o1. des. repeat subst.\n        exploit Memory.split_get0; try exact SPLIT2; eauto. i. des.\n        revert GET3. erewrite Memory.split_o; eauto. repeat condtac; ss.\n      + guardH o1. guardH o2. des. repeat subst. unguardH o0. des; congr.\n  Qed.\n\n  Lemma split_lower_diff\n        mem0 loc1 ts11 ts12 ts13 msg12 msg13\n        mem1 loc2 from2 to2 msg2 msg2'\n        mem2\n        (LOCTS1: (loc1, ts13) <> (loc2, to2))\n        (SPLIT1: Memory.split mem0 loc1 ts11 ts12 ts13 msg12 msg13 mem1)\n        (LOWER2: Memory.lower mem1 loc2 from2 to2 msg2 msg2' mem2):\n    (loc1 = loc2 /\\ ts11 = from2 /\\ ts12 = to2 /\\ msg12 = msg2 /\\\n     Memory.split mem0 loc1 ts11 ts12 ts13 msg2' msg13 mem2) \\/\n    ((loc1, ts12) <> (loc2, to2) /\\\n     exists mem1',\n        <<LOWER1: Memory.lower mem0 loc2 from2 to2 msg2 msg2' mem1'>> /\\\n        <<SPLIT2: Memory.split mem1' loc1 ts11 ts12 ts13 msg12 msg13 mem2>>).\n  Proof.\n    exploit Memory.lower_get0; eauto. i. des.\n    revert GET. erewrite Memory.split_o; eauto. repeat condtac; ss.\n    - des. subst. i. inv GET. left. splits; auto.\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    - guardH o. des. subst. congr.\n    - guardH o. guardH o0. i. right.\n      exploit (@Memory.lower_exists mem0 loc2 from2 to2);\n        try by inv LOWER2; inv LOWER; eauto. i. des.\n      exploit (@Memory.split_exists mem3 loc1 ts11 ts12 ts13);\n        try by inv SPLIT1; inv SPLIT; eauto.\n      { erewrite Memory.lower_o; eauto. condtac; ss.\n        - des. subst. congr.\n        - guardH o1. hexploit Memory.split_get0; try exact SPLIT1; eauto. i. des. eauto.\n      }\n      i. des.\n      splits.\n      { ii. inv H. exploit Memory.split_get0; try exact SPLIT1; eauto. i. des.\n        exploit Memory.lower_get0; eauto. i. des. congr.\n      }\n      cut (mem4 = mem2); [by i; subst; eauto|].\n      apply Memory.ext. i.\n      erewrite Memory.split_o; eauto. erewrite Memory.lower_o; eauto.\n      erewrite (@Memory.lower_o mem2); eauto. erewrite (@Memory.split_o mem1); eauto.\n      repeat (condtac; ss).\n      + des. repeat subst. congr.\n      + guardH o1. des. repeat subst. congr.\n  Qed.\n\n  Lemma split_lower_same\n        loc\n        mem0 ts11 ts12 ts13 msg12 msg13\n        mem1 from2 msg2 msg2'\n        mem2\n        (SPLIT1: Memory.split mem0 loc ts11 ts12 ts13 msg12 msg13 mem1)\n        (LOWER2: Memory.lower mem1 loc from2 ts13 msg2 msg2' mem2):\n    from2 = ts12 /\\ msg13 = msg2 /\\\n    exists mem1',\n      <<LOWER1: Memory.lower mem0 loc ts11 ts13 msg2 msg2' mem1'>> /\\\n      <<SPLIT2: Memory.split mem1' loc ts11 ts12 ts13 msg12 msg2' mem2>>.\n  Proof.\n    exploit Memory.lower_get0; eauto. erewrite Memory.split_o; eauto. repeat condtac; ss; cycle 2.\n    { clear -o0. des; congr. }\n    { des. subst. inv SPLIT1. inv SPLIT. exfalso. eapply Time.lt_strorder. eauto. }\n    clear o a COND COND0. i. des. inv GET. splits; ss.\n    exploit Memory.split_get0; eauto. i. des.\n    exploit (@Memory.lower_exists mem0 loc ts11 ts13);\n      try by inv LOWER2; inv LOWER; eauto.\n    { inv SPLIT1. inv SPLIT. etrans; eauto. }\n    i. des.\n    exploit (@Memory.split_exists mem3 loc ts11 from2 ts13);\n      try by inv SPLIT1; inv SPLIT; eauto.\n    { erewrite Memory.lower_o; eauto. condtac; ss. des; congr. }\n    i. des.\n    cut (mem4 = mem2); [by i; subst; esplits; eauto|].\n    apply Memory.ext. i.\n    erewrite Memory.split_o; eauto. erewrite Memory.lower_o; eauto.\n    erewrite (@Memory.lower_o mem2); eauto. erewrite (@Memory.split_o mem1); eauto.\n    repeat (condtac; ss).\n    des. repeat subst. congr.\n  Qed.\n\n  Lemma split_remove\n        mem0 loc1 ts11 ts12 ts13 msg12 msg13\n        mem1 loc2 from2 to2 msg2\n        mem2\n        (LOCTS1: (loc1, ts12) <> (loc2, to2))\n        (LOCTS2: (loc1, ts13) <> (loc2, to2))\n        (SPLIT1: Memory.split mem0 loc1 ts11 ts12 ts13 msg12 msg13 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      <<SPLIT2: Memory.split mem1' loc1 ts11 ts12 ts13 msg12 msg13 mem2>>.\n  Proof.\n    exploit (@Memory.remove_exists mem0 loc2 from2 to2).\n    { hexploit Memory.remove_get0; eauto.\n      erewrite Memory.split_o; eauto. repeat condtac; ss.\n      { des. subst. congr. }\n      { guardH o. des. subst. congr. }\n      guardH o. guardH o0. i. des. eauto.\n    }\n    i. des.\n    exploit (@Memory.split_exists mem3 loc1 ts11 ts12 ts13);\n      try by inv SPLIT1; inv SPLIT; eauto.\n    { erewrite Memory.remove_o; eauto. condtac; ss.\n      { des. subst. congr. }\n      guardH o. hexploit Memory.split_get0; eauto. i. des. eauto.\n    }\n    i. des.\n    cut (mem4 = mem2); [by i; subst; eauto|].\n    apply Memory.ext. i.\n    erewrite Memory.split_o; eauto. erewrite Memory.remove_o; eauto.\n    erewrite (@Memory.remove_o mem2); eauto. erewrite (@Memory.split_o mem1); eauto.\n    repeat (condtac; ss).\n    - des. repeat subst. congr.\n    - guardH o. des. repeat subst. congr.\n  Qed.\n\n  Lemma split_remove_same\n        mem0 loc1 ts11 ts12 ts13 msg12 msg13\n        mem1 from2 msg2\n        mem2\n        (SPLIT1: Memory.split mem0 loc1 ts11 ts12 ts13 msg12 msg13 mem1)\n        (REMOVE2: Memory.remove mem1 loc1 from2 ts13 msg2 mem2):\n    from2 = ts12 /\\ msg13 = msg2 /\\\n    exists mem1',\n      <<REMOVE1: Memory.remove mem0 loc1 ts11 ts13 msg13 mem1'>> /\\\n      <<ADD2: Memory.add mem1' loc1 ts11 ts12 msg12 mem2>>.\n  Proof.\n    exploit Memory.split_get0; eauto. i. des.\n    exploit Memory.remove_get0; eauto. i. des.\n    rewrite GET3 in *. inv GET2. splits; auto.\n    exploit (@Memory.remove_exists mem0 loc1 ts11 ts13 msg13); eauto. i. des.\n    exploit (@Memory.add_exists mem3 loc1 ts11 ts12 msg12); eauto.\n    { ii. revert GET2.\n      erewrite Memory.remove_o; eauto. condtac; ss. i. des; ss.\n      exploit Memory.get_disjoint; [exact GET0|exact GET2|..]. i. des.\n      { subst. ss. }\n      inv LHS. inv RHS. ss.\n      apply (x2 x); econs; ss.\n      inv SPLIT1. inv SPLIT.\n      etrans; try exact TO. econs; ss. }\n    { inv SPLIT1. inv SPLIT. ss. }\n    { inv SPLIT1. inv SPLIT. ss. }\n    i. des. esplits; eauto.\n    cut (mem4 = mem2); [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.split_o mem1); eauto.\n    repeat (condtac; ss).\n    des. subst. congr.\n  Qed.\n\n  Lemma lower_add\n        mem0 loc1 from1 to1 msg1 msg1'\n        mem1 loc2 from2 to2 msg2\n        mem2\n        (LOWER1: Memory.lower mem0 loc1 from1 to1 msg1 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      <<LOWER2: Memory.lower mem1' loc1 from1 to1 msg1 msg1' mem2>> /\\\n      <<LOCTS: (loc1, to1) <> (loc2, to2)>>.\n  Proof.\n    exploit (@Memory.add_exists mem0 loc2 from2 to2);\n      try by inv ADD2; inv ADD; eauto.\n    { apply covered_disjoint_get_disjoint. i. rewrite <- lower_covered in H; eauto.\n      eapply get_disjoint_covered_disjoint; eauto. inv ADD2. inv ADD. auto.\n    }\n    i. des.\n    exploit (@Memory.lower_exists mem3 loc1 from1 to1);\n      try by inv LOWER1; inv LOWER; eauto.\n    { erewrite Memory.add_o; eauto. condtac; ss.\n      - des. subst. hexploit Memory.lower_get0; eauto. i. des.\n        hexploit Memory.add_get0; eauto. i. des. congr.\n      - guardH o. hexploit Memory.lower_get0; eauto. i. des. eauto.\n    }\n    i. des.\n    esplits; eauto; cycle 1.\n    { ii. inv H.\n      exploit Memory.lower_get0; try exact LOWER1; eauto. i. des.\n      exploit Memory.add_get0; eauto. i. des. congr.\n    }\n    cut (mem4 = mem2); [by i; subst; eauto|].\n    apply Memory.ext. i.\n    erewrite Memory.lower_o; eauto. erewrite Memory.add_o; eauto.\n    erewrite (@Memory.add_o mem2); eauto. erewrite (@Memory.lower_o mem1); eauto.\n    repeat (condtac; ss). des. repeat subst.\n    exploit Memory.add_get0; try exact ADD2; eauto. i. des.\n    revert GET. erewrite Memory.lower_o; eauto. condtac; ss.\n  Qed.\n\n  Lemma lower_split\n        mem0 loc1 from1 to1 msg1 msg1'\n        mem1 loc2 ts21 ts22 ts23 msg22 msg23\n        mem2\n        (LOWER1: Memory.lower mem0 loc1 from1 to1 msg1 msg1' mem1)\n        (SPLIT2: Memory.split mem1 loc2 ts21 ts22 ts23 msg22 msg23 mem2):\n    exists from1' msg23' mem1',\n      <<SPLIT1: Memory.split mem0 loc2 ts21 ts22 ts23 msg22 msg23' mem1'>> /\\\n      <<LOWER2: Memory.lower mem1' loc1 from1' to1 msg1 msg1' mem2>> /\\\n      <<FROM1: __guard__ ((loc1, to1, from1', msg1', msg23') = (loc2, ts23, ts22, msg23, msg1) \\/\n                          ((loc1, to1) <> (loc2, ts23) /\\ (from1', msg23') = (from1, msg23)))>>.\n  Proof.\n    destruct (loc_ts_eq_dec (loc1, to1) (loc2, ts23)); ss.\n    - des. subst.\n      exploit Memory.split_get0; eauto. i. des.\n      revert GET0. erewrite Memory.lower_o; eauto. condtac; ss; cycle 1.\n      { des; congr. }\n      i. inv GET0.\n      exploit (@Memory.split_exists mem0 loc2 ts21 ts22 ts23);\n        try by inv SPLIT2; inv SPLIT; eauto.\n      { hexploit Memory.lower_get0; eauto. i. des. eauto. }\n      i. des.\n      exploit (@Memory.lower_exists mem3 loc2 ts22 ts23);\n        try by inv LOWER1; inv LOWER; eauto.\n      { erewrite Memory.split_o; eauto. repeat condtac; ss.\n        ss. des. subst. inv SPLIT2. inv SPLIT.\n        exfalso. eapply Time.lt_strorder. eauto.\n      }\n      { inv SPLIT2. inv SPLIT. auto. }\n      i. des.\n      esplits; eauto; cycle 1.\n      { left. eauto. }\n      cut (mem4 = mem2); [by i; subst; eauto|].\n      apply Memory.ext. i.\n      erewrite Memory.lower_o; eauto. erewrite Memory.split_o; eauto.\n      erewrite (@Memory.split_o mem2); eauto. erewrite (@Memory.lower_o mem1); eauto.\n      repeat (condtac; ss).\n      des. repeat subst.\n      revert GET. erewrite Memory.lower_o; eauto. condtac; ss.\n    - guardH o.\n      exploit Memory.split_get0; eauto. i. des.\n      exploit (@Memory.split_exists mem0 loc2 ts21 ts22 ts23);\n        try by inv SPLIT2; inv SPLIT; eauto.\n      { revert GET0. erewrite Memory.lower_o; eauto. condtac; eauto.\n        ss. i. des. inv GET0. unguardH o. des; congr.\n      }\n      i. des.\n      exploit (@Memory.lower_exists mem3 loc1 from1 to1);\n        try by inv LOWER1; inv LOWER; eauto.\n      { erewrite Memory.split_o; eauto. repeat condtac; ss.\n        - des. subst. hexploit Memory.split_get0; eauto.\n          hexploit Memory.lower_get0; eauto. i. des. congr.\n        - guardH o0. des. subst.\n          unguardH o. des; congr.\n        - guardH o0. guardH o1. hexploit Memory.lower_get0; eauto. i. des. eauto.\n      }\n      i. des.\n      esplits; eauto; cycle 1.\n      { right. splits; eauto. ii. inv H. unguardH o. des; congr. }\n      cut (mem4 = mem2); [by i; subst; eauto|].\n      apply Memory.ext. i.\n      erewrite Memory.lower_o; eauto. erewrite Memory.split_o; eauto.\n      erewrite (@Memory.split_o mem2); eauto. erewrite (@Memory.lower_o mem1); eauto.\n      repeat (condtac; ss).\n      + des. repeat subst.\n        revert GET. erewrite Memory.lower_o; eauto. condtac; ss.\n      + guardH o0. des. repeat subst. unguardH o. des; congr.\n  Qed.\n\n  Lemma lower_lower\n        mem0 loc1 from1 to1 msg1 msg1'\n        mem1 loc2 from2 to2 msg2 msg2'\n        mem2\n        (LOWER1: Memory.lower mem0 loc1 from1 to1 msg1 msg1' mem1)\n        (LOWER2: Memory.lower mem1 loc2 from2 to2 msg2 msg2' mem2):\n    (loc1 = loc2 /\\ from1 = from2 /\\ to1 = to2 /\\ msg1' = msg2 /\\\n     Memory.lower mem0 loc1 from1 to1 msg1 msg2' mem2) \\/\n    (<<LOCTS1: (loc1, to1) <> (loc2, to2)>> /\\\n     exists mem1',\n       <<LOWER1: Memory.lower mem0 loc2 from2 to2 msg2 msg2' mem1'>> /\\\n       <<LOWER2: Memory.lower mem1' loc1 from1 to1 msg1 msg1' mem2>>).\n  Proof.\n    exploit Memory.lower_get0; eauto. i. des.\n    revert GET. erewrite Memory.lower_o; eauto. condtac; ss.\n    - des. subst. i. inv GET. left. splits; eauto.\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    - guardH o. i. right. splits.\n      { ii. inv H. unguardH o. des; congr. }\n      exploit (@Memory.lower_exists mem0 loc2 from2 to2);\n        try by inv LOWER2; inv LOWER; eauto.\n      i. des.\n      exploit (@Memory.lower_exists mem3 loc1 from1 to1);\n        try by inv LOWER1; inv LOWER; eauto.\n      { erewrite Memory.lower_o; eauto. condtac; ss.\n        - des. subst. unguardH o. des; congr.\n        - guardH o0. hexploit Memory.lower_get0; try exact LOWER1; eauto. i. des. eauto.\n      }\n      i. des.\n      esplits; eauto.\n      cut (mem4 = mem2); [by i; subst; eauto|].\n      apply Memory.ext. i.\n      erewrite Memory.lower_o; eauto. erewrite Memory.lower_o; eauto.\n      erewrite (@Memory.lower_o mem2); eauto. erewrite (@Memory.lower_o mem1); eauto.\n      repeat (condtac; ss). des. repeat subst.\n      unguardH o. des; congr.\n  Qed.\n\n  Lemma lower_remove\n        mem0 loc1 from1 to1 msg1 msg1'\n        mem1 loc2 from2 to2 msg2\n        mem2\n        (LOCTS1: (loc1, to1) <> (loc2, to2))\n        (LOWER1: Memory.lower mem0 loc1 from1 to1 msg1 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      <<LOWER2: Memory.lower mem1' loc1 from1 to1 msg1 msg1' mem2>>.\n  Proof.\n    exploit (@Memory.remove_exists mem0 loc2 from2 to2).\n    { hexploit Memory.remove_get0; eauto. i. des.\n      revert GET. erewrite Memory.lower_o; eauto. condtac; ss.\n      { des. subst. congr. }\n      eauto.\n    }\n    i. des.\n    exploit (@Memory.lower_exists mem3 loc1 from1 to1);\n      try by inv LOWER1; inv LOWER; eauto.\n    { erewrite Memory.remove_o; eauto. condtac; ss.\n      { des. subst. congr. }\n      inv LOWER1. inv LOWER. eauto.\n    }\n    i. des.\n    cut (mem4 = mem2); [by i; subst; eauto|].\n    apply Memory.ext. i.\n    erewrite Memory.lower_o; eauto. erewrite Memory.remove_o; eauto.\n    erewrite (@Memory.remove_o mem2); eauto. erewrite (@Memory.lower_o mem1); eauto.\n    repeat (condtac; ss). des. repeat subst. congr.\n  Qed.\n\n  Lemma lower_remove_same\n        mem0 loc1 from1 to1 msg1 msg1'\n        mem1 from2 msg2\n        mem2\n        (LOWER1: Memory.lower mem0 loc1 from1 to1 msg1 msg1' mem1)\n        (REMOVE2: Memory.remove mem1 loc1 from2 to1 msg2 mem2):\n    from1 = from2 /\\ msg1' = msg2 /\\\n    <<REMOVE1: Memory.remove mem0 loc1 from1 to1 msg1 mem2>>.\n  Proof.\n    exploit Memory.lower_get0; eauto. i. des.\n    exploit Memory.remove_get0; eauto. i. des.\n    rewrite GET1 in *. inv GET0. splits; auto.\n    exploit (@Memory.remove_exists mem0 loc1 from1 to1 msg1); eauto. i. des.\n    cut (mem3 = mem2); [i; subst; eauto|].\n    apply Memory.ext. i.\n    erewrite Memory.remove_o; eauto.\n    erewrite (@Memory.remove_o mem2); try exact REMOVE2.\n    erewrite (@Memory.lower_o mem1); eauto.\n    repeat (condtac; ss).\n  Qed.\n\n  Lemma remove_add\n        mem0 loc1 from1 to1 msg1\n        mem1 loc2 from2 to2 msg2\n        mem2\n        mem1'\n        (REMOVE1: Memory.remove mem0 loc1 from1 to1 msg1 mem1)\n        (ADD2: Memory.add mem1 loc2 from2 to2 msg2 mem2)\n        (ADD1: Memory.add mem0 loc2 from2 to2 msg2 mem1'):\n    Memory.remove mem1' loc1 from1 to1 msg1 mem2.\n  Proof.\n    exploit Memory.remove_get0; try eexact REMOVE1; eauto. i. des.\n    exploit (@Memory.remove_exists mem1' loc1 from1 to1 msg1); eauto.\n    { erewrite Memory.add_o; eauto. condtac; ss; eauto.\n      des. subst. exploit Memory.add_get0; eauto. i. des. congr.\n    }\n    i. des.\n    cut (mem3 = mem2); [by i; subst|].\n    apply Memory.ext. i.\n    erewrite Memory.remove_o; eauto. erewrite Memory.add_o; eauto.\n    erewrite (@Memory.add_o mem2); eauto. erewrite (@Memory.remove_o mem1); eauto.\n    repeat (condtac; ss). des. subst. subst.\n    exploit Memory.add_get0; try eexact ADD1; eauto. i. des. congr.\n  Qed.\n\n  Lemma remove_split\n        mem0 loc1 from1 to1 msg1\n        mem1 loc2 ts21 ts22 ts23 msg22 msg23\n        mem2\n        mem1'\n        (REMOVE1: Memory.remove mem0 loc1 from1 to1 msg1 mem1)\n        (SPLIT2: Memory.split mem1 loc2 ts21 ts22 ts23 msg22 msg23 mem2)\n        (SPLIT1: Memory.split mem0 loc2 ts21 ts22 ts23 msg22 msg23 mem1'):\n    Memory.remove mem1' loc1 from1 to1 msg1 mem2.\n  Proof.\n    exploit Memory.remove_get0; try eexact REMOVE1; eauto. i. des.\n    exploit Memory.split_get0; try exact SPLIT1; eauto. i. des.\n    exploit (@Memory.remove_exists mem1' loc1 from1 to1 msg1); eauto.\n    { erewrite Memory.split_o; eauto. repeat condtac; ss.\n      - des. subst. congr.\n      - guardH o. des. subst. rewrite GET0 in GET0. inv GET0.\n        exploit Memory.split_get0; try exact SPLIT2; eauto. i. des.\n        revert GET5. erewrite Memory.remove_o; eauto. condtac; ss.\n    }\n    i. des.\n    cut (mem3 = mem2); [by i; subst|].\n    apply Memory.ext. i.\n    erewrite Memory.remove_o; eauto. erewrite Memory.split_o; eauto.\n    erewrite (@Memory.split_o mem2); eauto. erewrite (@Memory.remove_o mem1); eauto.\n    repeat (condtac; ss).\n    - des; congr.\n    - guardH o. des. subst. rewrite GET in GET2. inv GET2.\n      exploit Memory.remove_get0; try exact GET1; eauto. i. des.\n      revert GET2. erewrite Memory.split_o; eauto. repeat condtac; ss. i. inv GET2.\n      inv SPLIT1. inv SPLIT. exfalso. eapply Time.lt_strorder. eauto.\n  Qed.\n\n  Lemma remove_lower\n        mem0 loc1 from1 to1 msg1\n        mem1 loc2 from2 to2 msg2' msg2\n        mem2\n        mem1'\n        (REMOVE1: Memory.remove mem0 loc1 from1 to1 msg1 mem1)\n        (LOWER2: Memory.lower mem1 loc2 from2 to2 msg2' msg2 mem2)\n        (LOWER1: Memory.lower mem0 loc2 from2 to2 msg2' msg2 mem1'):\n    Memory.remove mem1' loc1 from1 to1 msg1 mem2.\n  Proof.\n    exploit Memory.remove_get0; try eexact REMOVE1; eauto. i. des.\n    exploit (@Memory.remove_exists mem1' loc1 from1 to1 msg1); eauto.\n    { erewrite Memory.lower_o; eauto. condtac; ss.\n      des. subst.\n      exploit Memory.lower_get0; try exact LOWER2; eauto. i. des.\n      revert GET1. erewrite Memory.remove_o; eauto. condtac; ss.\n    }\n    i. des.\n    cut (mem3 = mem2); [by i; subst|].\n    apply Memory.ext. i.\n    erewrite Memory.remove_o; eauto. erewrite Memory.lower_o; eauto.\n    erewrite (@Memory.lower_o mem2); eauto. erewrite (@Memory.remove_o mem1); eauto.\n    repeat (condtac; ss). des. repeat subst.\n    exploit Memory.lower_get0; try exact LOWER2; eauto. i. des.\n    revert GET1. erewrite Memory.remove_o; eauto. condtac; ss.\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.\n\n\n  (* Lemmas on promise *)\n\n  Lemma promise_add_remove\n        loc1 from1 to1 msg1\n        loc2 from2 to2 msg2\n        promises0 mem0\n        promises1 mem1\n        promises2\n        (LOCTS1: (loc1, to1) <> (loc2, to2))\n        (PROMISE1: Memory.promise promises0 mem0 loc1 from1 to1 msg1 promises1 mem1 Memory.op_kind_add)\n        (REMOVE2: Memory.remove promises1 loc2 from2 to2 msg2 promises2):\n    exists promises1',\n      <<REMOVE1: Memory.remove promises0 loc2 from2 to2 msg2 promises1'>> /\\\n      <<PROMISE2: Memory.promise promises1' mem0 loc1 from1 to1 msg1 promises2 mem1 Memory.op_kind_add>>.\n  Proof.\n    inv PROMISE1.\n    exploit add_remove; try exact PROMISES; eauto. i. des.\n    esplits; eauto.\n  Qed.\n\n  Lemma promise_split_remove\n        loc1 from1 to1 msg1\n        loc2 from2 to2 msg2\n        to3 msg3\n        promises0 mem0\n        promises1 mem1\n        promises2\n        (LOCTS1: (loc1, to1) <> (loc2, to2))\n        (LOCTS2: (loc1, to3) <> (loc2, to2))\n        (PROMISE1: Memory.promise promises0 mem0 loc1 from1 to1 msg1 promises1 mem1 (Memory.op_kind_split to3 msg3))\n        (REMOVE2: Memory.remove promises1 loc2 from2 to2 msg2 promises2):\n    exists promises1',\n      <<REMOVE1: Memory.remove promises0 loc2 from2 to2 msg2 promises1'>> /\\\n      <<PROMISE2: Memory.promise promises1' mem0 loc1 from1 to1 msg1 promises2 mem1 (Memory.op_kind_split to3 msg3)>>.\n  Proof.\n    inv PROMISE1.\n    exploit split_remove; try exact PROMISES; eauto. i. des.\n    esplits; eauto.\n  Qed.\n\n  Lemma promise_lower_remove\n        loc1 from1 to1 msg0 msg1\n        loc2 from2 to2 msg2\n        promises0 mem0\n        promises1 mem1\n        promises2\n        (LOCTS1: (loc1, to1) <> (loc2, to2))\n        (PROMISE1: Memory.promise promises0 mem0 loc1 from1 to1 msg1 promises1 mem1 (Memory.op_kind_lower msg0))\n        (REMOVE2: Memory.remove promises1 loc2 from2 to2 msg2 promises2):\n    exists promises1',\n      <<REMOVE1: Memory.remove promises0 loc2 from2 to2 msg2 promises1'>> /\\\n      <<PROMISE2: Memory.promise promises1' mem0 loc1 from1 to1 msg1 promises2 mem1 (Memory.op_kind_lower msg0)>>.\n  Proof.\n    inv PROMISE1.\n    exploit lower_remove; try exact PROMISES; eauto. i. des.\n    esplits; eauto.\n  Qed.\n\n  Lemma remove_promise\n        promises1 loc1 from1 to1 msg1\n        promises2 loc2 from2 to2 msg2\n        promises3\n        mem1 mem3\n        kind\n        (LE: Memory.le promises1 mem1)\n        (REMOVE: Memory.remove promises1 loc1 from1 to1 msg1 promises2)\n        (PROMISE: Memory.promise promises2 mem1 loc2 from2 to2 msg2 promises3 mem3 kind):\n    exists promises2',\n      Memory.promise promises1 mem1 loc2 from2 to2 msg2 promises2' mem3 kind /\\\n      Memory.remove promises2' loc1 from1 to1 msg1 promises3.\n  Proof.\n    inv PROMISE.\n    - exploit Memory.add_exists_le; eauto. i. des.\n      exploit remove_add; eauto.\n    - exploit Memory.split_get0; try eexact PROMISES; eauto. i. des.\n      revert GET0. erewrite Memory.remove_o; eauto. condtac; ss. i. guardH o.\n      exploit Memory.split_exists; try exact GET0; try by inv PROMISES; inv SPLIT; eauto. i. des.\n      exploit remove_split; eauto.\n    - exploit Memory.lower_get0; try eexact PROMISES; eauto. i. des.\n      revert GET. erewrite Memory.remove_o; eauto. condtac; ss. i. guardH o.\n      exploit Memory.lower_exists; try exact GET; try by inv PROMISES; inv LOWER; eauto. i. des.\n      exploit remove_lower; eauto.\n    - exploit remove_remove; try exact REMOVE; eauto. i. des. eauto.\n  Qed.\n\n  Lemma promise_add_promise_split_same\n        promises0 mem0 loc ts1 ts2 ts3 msg2 msg3\n        promises1 mem1\n        promises2 mem2\n        (ADD1: Memory.promise promises0 mem0 loc ts1 ts3 msg3 promises1 mem1 Memory.op_kind_add)\n        (SPLIT2: Memory.promise promises1 mem1 loc ts1 ts2 msg2 promises2 mem2 (Memory.op_kind_split ts3 msg3)):\n    exists promises1' mem1',\n      <<ADD1: Memory.promise promises0 mem0 loc ts1 ts2 msg2 promises1' mem1' Memory.op_kind_add>> /\\\n      <<ADD2: Memory.promise promises1' mem1' loc ts2 ts3 msg3 promises2 mem2 Memory.op_kind_add>>.\n  Proof.\n    inv ADD1. inv SPLIT2.\n    exploit add_split; try exact PROMISES; eauto. i. des; [|congr].\n    exploit add_split; try exact MEM; eauto. i. des; [|congr].\n    esplits.\n    - econs; eauto.\n      i. exploit Memory.add_get0; try exact MEM. i. des.\n      exploit Memory.add_get1; try exact GET; try exact MEM. i.\n      exploit Memory.get_ts; try exact GET1. i. des.\n      { subst. inv ADD3. inv ADD. inv TO. }\n      exploit Memory.get_ts; try exact x8. i. des.\n      { subst. inv ADD0. inv ADD. inv TO. }\n      exploit Memory.get_disjoint; [exact GET1|exact x8|..]. i. des.\n      { subst. inv ADD0. inv ADD. timetac. }\n      destruct (TimeFacts.le_lt_dec ts3 to').\n      + apply (x11 ts3); econs; ss; try refl.\n        inv ADD3. inv ADD. ss.\n      + apply (x11 to'); econs; ss; try refl.\n        { etrans; try exact x10. inv ADD0. inv ADD. ss. }\n        { econs. ss. }\n    - econs; eauto.\n      i. revert GET.\n      erewrite Memory.add_o; eauto. condtac; ss; eauto.\n      i. des. subst. inv GET. inv MEM. inv ADD. timetac.\n  Qed.\n\n  Lemma promise_split_promise_split_same\n        promises0 mem0 loc ts1 ts2 ts3 ts4 val2 released2 msg3 msg4\n        promises1 mem1\n        promises2 mem2\n        (SPLIT1: Memory.promise promises0 mem0 loc ts1 ts3 msg3 promises1 mem1 (Memory.op_kind_split ts4 msg4))\n        (SPLIT2: Memory.promise promises1 mem1 loc ts1 ts2 (Message.concrete val2 released2) promises2 mem2 (Memory.op_kind_split ts3 msg3)):\n    exists promises1' mem1',\n      <<SPLIT1: Memory.promise promises0 mem0 loc ts1 ts2 (Message.concrete val2 released2) promises1' mem1' (Memory.op_kind_split ts4 msg4)>> /\\\n      <<SPLIT2: Memory.promise promises1' mem1' loc ts2 ts3 msg3 promises2 mem2 (Memory.op_kind_split ts4 msg4)>>.\n  Proof.\n    assert (LOCTS: (loc, ts4) <> (loc, ts3)).\n    { intro X. inv X. inv SPLIT1. inv MEM. inv SPLIT. timetac. }\n    inv SPLIT1. inv SPLIT2.\n    exploit split_split; try exact PROMISES; eauto. i. des; [|congr].\n    exploit split_split; try exact MEM; eauto. i. des; [|congr].\n    esplits.\n    - econs; eauto; congr.\n    - econs; eauto.\n  Qed.\n\n  Lemma promise_lower_promise_split_same\n        promises0 mem0 loc ts1 ts2 ts3 msg0 val2 released2 msg3\n        promises1 mem1\n        promises2 mem2\n        (LOWER1: Memory.promise promises0 mem0 loc ts1 ts3 msg3 promises1 mem1 (Memory.op_kind_lower msg0))\n        (SPLIT2: Memory.promise promises1 mem1 loc ts1 ts2 (Message.concrete val2 released2) promises2 mem2 (Memory.op_kind_split ts3 msg3)):\n    exists promises1' mem1',\n      <<SPLIT1: Memory.promise promises0 mem0 loc ts1 ts2 (Message.concrete val2 released2) promises1' mem1' (Memory.op_kind_split ts3 msg0)>> /\\\n      <<LOWER2: Memory.promise promises1' mem1' loc ts2 ts3 msg3 promises2 mem2 (Memory.op_kind_lower msg0)>>.\n  Proof.\n    inv LOWER1. inv SPLIT2.\n    exploit lower_split; try exact PROMISES; eauto. i. des.\n    unguard. des; [|congr]. inv FROM1.\n    exploit lower_split; try exact MEM; eauto. i. des.\n    unguard. des; [|congr]. inv FROM1.\n    esplits.\n    - econs; eauto. inv MEM. inv LOWER. inv MSG_LE; ss.\n    - econs; eauto.\n  Qed.\n\n  Lemma promise_cancel\n        promises0 mem0\n        promises1 mem1\n        promises2 mem2\n        loc1 from1 to1 msg1 kind1\n        loc2 from2 to2 msg2\n        (PROMISE1: Memory.promise promises0 mem0 loc1 from1 to1 msg1 promises1 mem1 kind1)\n        (CANCEL2: Memory.promise promises1 mem1 loc2 from2 to2 msg2 promises2 mem2 Memory.op_kind_cancel):\n    (loc1 = loc2 /\\ from1 = from2 /\\ to1 = to2 /\\ msg1 = Message.reserve /\\ msg2 = Message.reserve /\\\n     kind1 = Memory.op_kind_add /\\ promises0 = promises2 /\\ mem0 = mem2) \\/\n    exists promises1' mem1',\n      (<<CANCEL1: Memory.promise promises0 mem0 loc2 from2 to2 msg2 promises1' mem1' Memory.op_kind_cancel>>) /\\\n      (<<PROMISE2: Memory.promise promises1' mem1' loc1 from1 to1 msg1 promises2 mem2 kind1>>).\n  Proof.\n    inv CANCEL2. inv PROMISE1; ss.\n    - destruct (classic ((loc1, to1) = (loc2, to2))).\n      + inv H.\n        exploit add_remove_same; try exact PROMISES0; eauto. i. des. subst.\n        exploit add_remove_same; try exact MEM0; eauto. i. des. subst.\n        left. splits; auto.\n      + exploit add_remove; try exact PROMISES0; eauto. i. des.\n        exploit add_remove; try exact MEM0; eauto. i. des.\n        right. esplits; eauto. econs; eauto.\n        i. revert GET.\n        erewrite Memory.remove_o; eauto. condtac; ss. eauto.\n    - des. destruct (classic ((loc1, ts3) = (loc2, to2))).\n      + clarify.\n        exploit split_remove_same; try exact PROMISES0; eauto. i. des. subst.\n        exploit split_remove_same; try exact MEM1; eauto. i. des. subst. ss.\n      + destruct (classic ((loc1, to1) = (loc2, to2))).\n        { des. inv H0.\n          exploit Memory.split_get0; try exact MEM0. i. des.\n          exploit Memory.remove_get0; try exact MEM. i. des. congr. }\n        exploit split_remove; try exact PROMISES0; eauto. i. des.\n        exploit split_remove; try exact MEM0; eauto. i. des.\n        right. esplits; eauto.\n    - des. subst.\n      destruct (classic ((loc1, to1) = (loc2, to2))).\n      + inv H.\n        exploit lower_remove_same; try exact PROMISES0; eauto. i. des. subst.\n        exploit lower_remove_same; try exact MEM1; eauto. i. des. subst.\n        exploit Memory.lower_get0; try exact MEM0. i. des. inv MSG_LE. ss.\n      + exploit lower_remove; try exact PROMISES0; eauto. i. des.\n        exploit lower_remove; try exact MEM0; eauto. i. des.\n        right. esplits; eauto.\n    - exploit remove_remove; try apply PROMISES0; eauto. i. des.\n      exploit remove_remove; try apply MEM0; eauto. i. des.\n      right. esplits; eauto.\n  Qed.\n\n  Lemma write_cancel\n        promises0 mem0\n        promises1 mem1\n        promises2 mem2\n        loc1 from1 to1 msg1 kind1\n        loc2 from2 to2 msg2\n        (WRITE1: Memory.write promises0 mem0 loc1 from1 to1 msg1 promises1 mem1 kind1)\n        (CANCEL2: Memory.promise promises1 mem1 loc2 from2 to2 msg2 promises2 mem2 Memory.op_kind_cancel):\n    exists promises1' mem1',\n      (<<CANCEL1: Memory.promise promises0 mem0 loc2 from2 to2 msg2 promises1' mem1' Memory.op_kind_cancel>>) /\\\n      (<<WRITE2: Memory.write promises1' mem1' loc1 from1 to1 msg1 promises2 mem2 kind1>>).\n  Proof.\n    inv WRITE1. inv CANCEL2.\n    exploit remove_remove; [exact REMOVE|exact PROMISES|]. i. des.\n    exploit promise_cancel; try exact PROMISE; eauto. i. des.\n    { subst.\n      exploit Memory.remove_get0; try exact REMOVE1. i. des.\n      exploit Memory.remove_get0; try exact REMOVE2. i. des. congr.\n    }\n    esplits; eauto.\n  Qed.\n\n  Lemma write_na_cancel\n        promises0 mem0\n        promises1 mem1\n        promises2 mem2\n        ts loc1 from1 to1 val1 msgs1 kinds1 kind1\n        loc2 from2 to2 msg2\n        (WRITE1: Memory.write_na ts promises0 mem0 loc1 from1 to1 val1 promises1 mem1 msgs1 kinds1 kind1)\n        (CANCEL2: Memory.promise promises1 mem1 loc2 from2 to2 msg2 promises2 mem2 Memory.op_kind_cancel):\n    exists promises1' mem1',\n      (<<CANCEL1: Memory.promise promises0 mem0 loc2 from2 to2 msg2 promises1' mem1' Memory.op_kind_cancel>>) /\\\n      (<<WRITE2: Memory.write_na ts promises1' mem1' loc1 from1 to1 val1 promises2 mem2 msgs1 kinds1 kind1>>).\n  Proof.\n    induction WRITE1.\n    { exploit write_cancel; eauto. i. des. esplits; eauto. }\n    exploit IHWRITE1; eauto. i. des.\n    exploit write_cancel; eauto. i. des. esplits; eauto.\n  Qed.\n\n  Lemma 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 /\\\n     kind2 = Memory.op_kind_cancel /\\ 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>>)).\n  Proof.\n    inv STEP1. inv STEP2; ss.\n    - (* reserve/add *)\n      exploit add_add; try exact PROMISES; try exact PROMISES0; eauto. i. des.\n      exploit 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.\n    - (* reserve/split *)\n      exploit add_split; try exact PROMISES; try exact PROMISES0; eauto. i.\n      des; clarify.\n      exploit add_split; try exact MEM; try exact MEM0; eauto. i. des; [congr|].\n      right. esplits.\n      + econs 2; eauto.\n      + econs; eauto.\n    - (* reserve/lower *)\n      des. subst.\n      exploit add_lower; try exact PROMISES; try exact PROMISES0; eauto. i.\n      des; subst.\n      + left. inv PROMISES0. inv LOWER. inv MSG_LE. ss.\n      + exploit add_lower; try exact MEM; try exact MEM0; eauto. i. des; [congr|].\n        right. esplits.\n        * econs; eauto.\n        * econs; eauto.\n    - (* reserve/cancel *)\n      destruct (classic ((loc1, to1) = (loc2, to2))).\n      + inv H.\n        exploit add_remove_same; try exact PROMISES0; eauto. i. des. subst.\n        exploit add_remove_same; try exact MEM0; eauto. i. des. subst.\n        left. splits; auto.\n      + exploit add_remove; try exact PROMISES0; eauto. i. des.\n        exploit add_remove; try exact MEM0; eauto. i. des.\n        right. esplits; eauto.\n  Qed.\n\n  Lemma reserve_write\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.write prom1 mem1 loc2 from2 to2 msg2 prom2 mem2 kind2)\n        (MSG: msg2 <> Message.reserve):\n    exists prom1' mem1',\n      (<<STEP1: Memory.write 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>>).\n  Proof.\n    inv STEP2.\n    exploit reserve_promise; try eauto. i. des; ss.\n    inv STEP2.\n    exploit add_remove; try exact PROMISES; eauto.\n    { ii. inv H.\n      exploit Memory.add_get0; try exact PROMISES. i. des.\n      exploit Memory.remove_get0; try exact REMOVE. i. des.\n      rewrite GET0 in *. inv GET1. ss.\n    }\n    i. des. esplits; eauto.\n  Qed.\n\n  Lemma reserve_write_na\n        prom0 mem0\n        prom1 mem1\n        prom2 mem2\n        loc1 from1 to1\n        ts loc2 from2 to2 val2 msgs2 kinds2 kind2\n        (STEP1: Memory.promise prom0 mem0 loc1 from1 to1 Message.reserve prom1 mem1 Memory.op_kind_add)\n        (STEP2: Memory.write_na ts prom1 mem1 loc2 from2 to2 val2 prom2 mem2 msgs2 kinds2 kind2):\n    exists prom1' mem1',\n      (<<STEP1: Memory.write_na ts prom0 mem0 loc2 from2 to2 val2 prom1' mem1' msgs2 kinds2 kind2>>) /\\\n      (<<STEP2: Memory.promise prom1' mem1' loc1 from1 to1 Message.reserve prom2 mem2 Memory.op_kind_add>>).\n  Proof.\n    revert prom0 mem0 STEP1. induction STEP2; i.\n    { exploit reserve_write; eauto; ss. i. des. esplits; eauto. }\n    exploit reserve_write; eauto.\n    { unguard. des; subst; ss. }\n    i. des.\n    exploit IHSTEP2; eauto. i. des. esplits; eauto.\n  Qed.\nEnd MemoryReorder.\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/MemoryReorder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.256554600637569}}
{"text": "Require Import Common Lia List ListSupport HVector FMap.\nRequire Import Syntax Topology Semantics SemFacts StepM Invariant Serial.\n\nRequire Export RqRsTopo RqRsFacts.\nRequire Export RqRsInvMsg RqRsInvLock RqRsInvSep RqRsInvAtomic.\nRequire Export RqRsMsgPred RqRsUtil.\n\nSet Implicit Arguments.\n\nOpen Scope list.\nOpen Scope hvec.\nOpen Scope fmap.\n\nDefinition AtomicMsgOutsInv `{DecValue} `{OStateIfc} (mp: MsgOutPred)\n           (eouts: list (Id Msg)) (nst: State): Prop :=\n  Forall (fun eout => mp eout nst.(st_oss) nst.(st_orqs) nst.(st_msgs)) eouts.\n\nDefinition AtomicInv `{DecValue} `{OStateIfc} (mp: MsgOutPred):\n  list (Id Msg) (* inits *) ->\n  State (* starting state *) ->\n  History (* atomic history *) ->\n  list (Id Msg) (* eouts *) ->\n  State (* ending state *) -> Prop :=\n  fun inits st1 hst eouts st2 =>\n    AtomicMsgOutsInv mp eouts st2.\n\nLtac disc_AtomicInv :=\n  repeat\n    match goal with\n    | [H: AtomicInv _ _ _ _ _ _ |- _] => red in H; dest\n    end.\n\nClose Scope list.\nClose Scope hvec.\nClose Scope fmap.\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/Dsl/RqRsLang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.25655414264571175}}
{"text": "      \nRequire Import OrderedType OrderedTypeEx OrderedTypeAlt DecidableType DecidableTypeEx.\nRequire Import RelationClasses.\nFrom bcv Require Import vmtype dvm ovm.\nRequire bcv.heritage.\n\nModule Offensive_correcte (H:heritage.Herit).\n\n  Module D:= D(H).\n  Module O:= O(H).\n\n  (** Calcul de la valeur offensive d'une valeur défensive: on enlève\n  le tag de type,et on met zéro là où il n'y a pas de valeur, de toute\n  façon si le bcv est correct et accepte une applet, ces valeurs\n  n'apparaitront jamais. *)\n  Definition d2o (v:DefVal.Val): OffVal.Val :=\n    match v with\n      | DefVal.Vint i => i\n      | DefVal.Vref (_,i) => i\n      | DefVal.Vrefnull => 0\n      | DefVal.Error => 0\n      | DefVal.NonInit => 0\n    end.\n\n\n  (* Ceci permet de faire rewrite à l'intérieur l'argument de (map d2o).\n     TODO: faire de ceci un proper generique du moment que la fonction\n     est proper avec objfields. *)\n  Instance map_d2o_morph:\n    Proper (D.obj_eq ==> O.obj_eq)\n           (fun obj : D.Obj =>\n              {| O.objclass := D.objclass obj;\n                 O.objfields := Dico.map d2o (D.objfields obj) |}).\n  Proof.\n    red. red.\n    intros.\n    inversion H.\n    constructor;simpl;auto.\n    rewrite H0.\n    reflexivity.\n  Qed.\n\n\n  (** * Les fonctions d'offensivisation: on applique d2o partout. *)\n\n\n  Definition offensive_regs rgs: O.Registers := Dico.map d2o rgs.\n\n  Definition offensive_stack st: O.Stack := List.map d2o st.\n\n  Definition offensive_heap hp: O.Heap :=\n    Dico.map (fun obj =>\n                {| O.objclass:= obj.(D.objclass) ; O.objfields := Dico.map d2o (obj.(D.objfields)) |}) hp.\n\n  Definition offensive_state (s:D.State) : O.State :=\n    let fr :=\n        {| O.mdef := s.(D.frame).(D.mdef);\n           O.regs := offensive_regs (s.(D.frame).(D.regs));\n           O.stack := offensive_stack (s.(D.frame).(D.stack));\n           O.pc:=s.(D.frame).(D.pc) |} in\n    {| O.frame := fr;\n       O.framestack := nil;\n       O.heap := offensive_heap s.(D.heap) |}.\n\n\n  Definition offensive_opt_state (s:option D.State) : option O.State :=\n    match s with\n      | None => None\n      | Some x => Some (offensive_state x)\n    end.\n\n\n  Lemma pc_ok: forall s,  (s.(D.frame)).(D.pc) = (O.frame (offensive_state s)).(O.pc).\n    destruct s;simpl;reflexivity.\n  Qed.\n\n  Lemma mdef_ok: forall s, D.mdef(s.(D.frame)) = O.mdef(O.frame(offensive_state s)).\n  Proof.\n    destruct s;simpl;reflexivity.\n  Qed.\n\n  Definition d2o_opt := option_map d2o.\n\n\n  Add Morphism offensive_regs with signature Dico.Equal ==> Dico.Equal as off_regs_m.\n  Proof.\n    intros rgs1 rgs2 H.\n    unfold offensive_regs.\n    apply Dicomore.map_m with (x:= d2o) (y:= d2o) in H.\n    - assumption.\n    - reflexivity.\n  Qed.\n\n\n  Lemma find_offensive_ok : forall rgs ridx, \n                              Dico.find ridx (offensive_regs rgs) \n                              = d2o_opt (Dico.find ridx rgs).\n  Proof.\n    intros rgs.\n    induction rgs using  Dicomore.map_induction_bis;simpl;intros.\n    - rewrite <- H.\n      apply IHrgs1.\n    - vm_compute.\n      reflexivity. \n    - unfold offensive_regs.\n      rewrite Dicomore.map_o.    \n      reflexivity.\n  Qed.\n  Import D.\n\n  Axiom maxkey_off_ok: forall hp, maxkey (offensive_heap hp) = (maxkey hp).\n\n  Lemma new_ok:\n    forall clid (hp:D.Heap) x y x' y' z,\n      Some (x,y) = O.new clid (offensive_heap hp) ->\n      Some (z,x',y') = D.new clid hp ->\n      x = x' /\\\n      Dico.Equal y \n                (Dico.map (fun obj : D.Obj =>\n                            {| O.objclass  := D.objclass obj;\n                               O.objfields := Dico.map d2o (D.objfields obj) |})\n                          y').\nProof.\n  Admitted.\n\nLemma eq_built : forall t:ClasseDef , Dico.Equal (Dico.map d2o (build_flds t)) (O.build_flds t).\nProof. \n  intros.\n  induction t using  Dicomore.map_induction_bis;simpl;intros.\n  - assert (Dico.Equal (build_flds t1) (build_flds t2)). {\n      unfold build_flds.\n      setoid_rewrite H.\n      reflexivity.\n    }\n   setoid_rewrite <- H0.\n   assert (Dico.Equal (O.build_flds t1) (O.build_flds t2)). {\n      unfold build_flds.\n      setoid_rewrite H.\n      reflexivity.\n    }\n   setoid_rewrite <- H1.\n    assumption. \n  - simpl. apply O.build_flds_empty.\n  - unfold build_flds.\n    unfold O.build_flds.\n    destruct e;\n      rewrite Dicomore.add_map;\n      rewrite Dicomore.add_map;\n      rewrite Dicomore.add_map;\n    simpl;\n    apply Dicomore.F.add_m;try reflexivity;assumption.\n\n Qed.\n\n  (** Diagramme de commutation entre D et O.*)\n  Lemma offensive_ok : \n    forall (s s':D.State) (os os' os'':O.State),\n      offensive_state s = os ->\n      offensive_state s' = os' ->\n      D.exec_step s = Some s' ->\n      O.exec_step os = Some os'' -> \n      O.state_eq os' os''.\n  Proof.\n    intros.\n    unfold exec_step in H1.\n    unfold O.exec_step in H2.\n    subst.\n    rewrite <- pc_ok in H2.\n    rewrite <- mdef_ok in H2.\n    destruct (FIND (pc (frame s)) (instrs (mdef (frame s)))) eqn:heq_instrpc; try now inversion H1.\n    - destruct i eqn:heq_instr; try now inversion H1.\n      + inversion H1.\n        inversion H2.\n        unfold offensive_state. simpl. reflexivity.\n\n\n      + destruct (stack (frame s)) eqn:heq_add;try now inversion H1.\n      destruct d eqn:heq_1;try now inversion H1.\n      destruct l eqn:heq_2;try now inversion H1.\n      destruct d0 eqn:heq_3;try now inversion H1.\n      unfold offensive_state in H2. simpl in H2.  rewrite heq_add in H2. simpl in H2. subst.\n      inversion H1.\n      inversion H2. clear H1 H2.\n      unfold offensive_state .\n      simpl.\n      reflexivity.\n\n  \n     + destruct_with_eqn (FIND ridx (regs (frame s))) ; try now inversion H1.\n       destruct_with_eqn d ; try now inversion H1.\n       unfold offensive_state in H2.\n       simpl in H2.\n      unfold offensive_regs in H2.\n        Search Dico.map.\n      rewrite Dicomore.map_o in H2. simpl.\n      setoid_rewrite  Heqo in H2.\n      simpl in H2.\n      inversion H1.\n      inversion H2. clear H1 H2.\n      subst.\n      reflexivity.\n    + destruct_with_eqn (FIND ridx (regs (frame s))) ; try now inversion H1.\n      destruct_with_eqn d ; try now inversion H1.\n      destruct clrf.\n      destruct (H.sub c cl) ; try now inversion H1.\n      unfold offensive_state in H2.\n      simpl in H2.\n      unfold offensive_regs in H2.\n      Search Dico.map.\n      rewrite Dicomore.map_o in H2. simpl.\n      setoid_rewrite  Heqo in H2.\n      inversion H1.\n      inversion H2.  clear H1 H2.\n      subst.\n      reflexivity.\n   + destruct_with_eqn (stack (frame s)); try now inversion H1.\n     destruct_with_eqn d; try now inversion H1.\n     unfold offensive_state in H2.\n      simpl in H2.\n      setoid_rewrite  Heql in H2.\n    inversion H1.\n      inversion H2.  clear H1 H2. simpl.\n    unfold offensive_regs. simpl.\n  \n    apply O.state_eq_C;try reflexivity. \n    * simpl. \n      apply O.frame_eq_C;try reflexivity.\n      -- simpl. Search Dico.map.\n          apply Dicomore.add_map.\n    \n  + destruct_with_eqn (stack (frame s)); try now inversion H1.\n    destruct_with_eqn d; try now inversion H1.\n    unfold offensive_state in H2. simpl in H2.\n    setoid_rewrite Heql in H2. \n    destruct clrf.\n    destruct (H.sub c cl).\n    * inversion H1.\n      inversion H2. clear H1 H2.\n      unfold offensive_regs. simpl.\n      apply O.state_eq_C;try reflexivity.\n      -- simpl. apply O.frame_eq_C;try reflexivity.\n        ++ simpl. unfold offensive_regs.\n           rewrite Dicomore.add_map.\n           simpl. reflexivity.\n    * inversion H1.\n  + destruct_with_eqn (stack (frame s)); try now inversion H1.\n    destruct_with_eqn d; try now inversion H1.\n    destruct_with_eqn i0; try now inversion H1. \n    *\n     unfold offensive_state in H2. simpl in H2. \n     setoid_rewrite Heql in H2. simpl in H2.\n     inversion H1. inversion H2. clear H1 H2.\n     unfold offensive_state. simpl. reflexivity.\n\n    * unfold offensive_state in H2. simpl in H2. \n      setoid_rewrite Heql in H2. simpl in H2.\n      inversion H1. inversion H2. clear H1 H2.\n      unfold offensive_state. simpl. reflexivity.\n  + inversion H1. inversion H2. clear H1 H2.\n     unfold offensive_state. simpl. reflexivity.\n  + destruct_with_eqn (stack (frame s)); try now inversion H1.\n    destruct_with_eqn d; try now inversion H1.\n    destruct clrf.\n    case_eq (H.sub c cl);\n    intros; subst;\n    rewrite H in H1; try now inversion H1.\n    destruct_with_eqn (FIND h (heap s) ); try now inversion H1.\n    destruct_with_eqn o; try now inversion H1.\n    case_eq (H.sub objclass0 cl);\n    intros; subst;\n    rewrite H0 in H1; try now  inversion H1.\n    destruct_with_eqn (FIND fldrf objfields0); try now inversion H1. subst.\n    unfold offensive_state in H2. simpl in H2.\n    setoid_rewrite Heql in H2. simpl in H2. subst.\n    unfold offensive_heap in H2. simpl in H2.\n    rewrite Dicomore.F.map_o in H2.\n    rewrite Heqo in H2. simpl in H2.\n    rewrite Dicomore.F.map_o in H2.\n    unfold objfields in H2. inversion Heqo.\n    setoid_rewrite Heqo0 in H2. simpl in H2.\n    * inversion H1. inversion H2. clear H1 H2.\n      unfold offensive_state; simpl.\n      reflexivity.\n\n  + destruct_with_eqn (stack (frame s)); try now inversion H1.\n    destruct_with_eqn d; try now inversion H1.\n    destruct_with_eqn clrf. destruct l; try now inversion H1.\n    destruct_with_eqn (H.sub c cl); try now inversion H1.\n    destruct_with_eqn (FIND cl H.allcl); try now inversion H1.\n    destruct_with_eqn (FIND fldrf t); try now inversion H1.\n    destruct_with_eqn (compat (v2t d0) v); try now inversion H1.\n    destruct_with_eqn (FIND h (heap s)); try now inversion H1.\n    destruct_with_eqn o.\n    unfold offensive_state in H2. simpl in H2.\n    setoid_rewrite Heql in H2. simpl in H2.\n    unfold offensive_heap in H2.\n    rewrite Dicomore.F.map_o in H2.\n    rewrite Heqo1 in H2. simpl in H2.\n    inversion H1. inversion H2. clear H1 H2.\n    unfold offensive_state; simpl.\n    unfold offensive_heap.\napply O.state_eq_C; try reflexivity. simpl. \nconstructor.\nrewrite Dicomore.add_map_equiv; try eauto with typeclass_instances. simpl.\nrewrite Dicomore.add_map_equiv; try eauto with typeclass_instances. simpl.\nreflexivity.\n  + unfold new in H1;simpl in H1.\n    \n    destruct_with_eqn (FIND clid allcl ); try now inversion H1.\n    unfold offensive_state in H2.\n    unfold O.new in H2. simpl in H2.\n    rewrite Heqo in H2. simpl in H2. subst.\nrewrite maxkey_off_ok in H2. \nunfold offensive_heap in H2.\n\n    simpl in H2.  \nunfold offensive_stack in H2.  simpl in H2. \n inversion H1. inversion H2. clear H1 H2.\n   unfold offensive_state; simpl. unfold offensive_stack. subst.\nsimpl. apply O.state_eq_C; try reflexivity. simpl. unfold offensive_heap. simpl. \napply O.heap_eq_C. rewrite Dicomore.add_map_equiv; try eauto with typeclass_instances.\nsimpl.\nrewrite eq_built. reflexivity.\n  + \n   inversion H1. inversion H2. rewrite H0. reflexivity.\nQed.\n\n\n\nEnd Offensive_correcte.\n", "meta": {"author": "aglotrex", "repo": "Coq-BCV", "sha": "4c4dc3494a83d94bc0f7516095a215df02ad3412", "save_path": "github-repos/coq/aglotrex-Coq-BCV", "path": "github-repos/coq/aglotrex-Coq-BCV/Coq-BCV-4c4dc3494a83d94bc0f7516095a215df02ad3412/offensive_correct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2565541364744409}}
{"text": "Require Import Definitions Algebra.Monoid Expr Algebra.SetoidCat Algebra.SetoidCat.MaybeUtils Algebra.Monad.Maybe Tactics Algebra.SetoidCat.ListUtils Algebra.Functor Algebra.Applicative Algebra.Alternative Algebra.FoldableFunctor Algebra.SetoidCat.PairUtils Algebra.Monad Algebra.Lens.Lens Algebra.Lens.MaybeLens ListLens Utils SetoidUtils SQL Pointed Lista Matrixp GenUtils Algebra.Monoid.MaybeUtils Algebra.SetoidCat.NatUtils.\nRequire Import Coq.Structures.DecidableTypeEx List SetoidClass PeanoNat FMapWeakList Basics Coq.Arith.Compare_dec.\n\nExisting Instance maybe_Monad.\nInstance maybeFunctor : @Functor maybe (@maybeS) := monadFunctor.\nInstance maybe_Applicative : @Applicative maybe (@maybeS) _ := monad_Applicative.\nExisting Instance maybe_mappend_PointedFunction2.\n\nDefinition unionRows : listaS (maybeS rowS) ~> listaS (maybeS rowS) ~~> listaS (maybeS rowS) :=\n  lista_zipWithS maybe_first_mappend.\n\nDefinition minS := injF2 min _.\n\nExisting Instance sqlVal_Pointed.\n\nDefinition _unionTables (tab1 tab2 : matrixp sqlVal) : matrixp sqlVal :=\n  matrixpConsS @ (unionRows @ (tableRowsGetter @ tab1) @ (tableRowsGetter @ tab2)).\n\nInstance _unionTables_Proper : Proper (equiv ==> equiv ==> equiv) _unionTables.\nProof.\n  autounfold. intros. unfold _unionTables. rewritesr.\nQed.\n\nDefinition unionTables := injF2 _unionTables _.\n\nDefinition unionDatabases : databaseS ~> databaseS ~~> databaseS :=\n  list_zipWithS' @ unionTables.\n\n\n\nDefinition caseSqlVal {A} {AS : Setoid A} (nat1 : natS ~> AS) (addr1 : natS ~*~ natS ~> AS) (func1 : sqlFuncS ~> AS) (nil1 : A) (row1 : sqlValS ~> sqlValS ~~> AS) val1 : A :=\n  match val1 with\n    | vNat n => nat1 @ n\n    | vAddr n => addr1 @ n\n    | vFunc a => func1 @ a\n    | vRow a b => row1 @ a @ b\n    | vNil => nil1\n  end\n.\n\nInstance caseSqlVal_Proper A AS : Proper (equiv ==> equiv ==> equiv ==> equiv ==> equiv ==> equiv ==> equiv) (@caseSqlVal A AS).\nProof.\n  autounfold. intros. simpl in H4.  rewrite H4. induction y4.\n  - simpl. rewritesr.\n  - simpl. rewritesr.\n  - auto. \n  - simpl. rewritesr.\n  - simpl. rewritesr. \nQed.\n\nDefinition caseSqlValS {A AS} := injF6 (@caseSqlVal A AS) _.\n\nDefinition extractAddrS : sqlValS ~> maybeS (natS ~*~ natS) :=\n  caseSqlValS\n    @ (constS _ @ None)\n    @ (SomeS)\n    @ (constS _ @ None)\n    @ None\n    @ (constS _ @ (constS _ @ None)).\n\nDefinition extractNatS : sqlValS ~> maybeS natS :=\n  caseSqlValS\n    @ (SomeS)\n    @ (constS _ @ None)\n    @ (constS _ @ None)    @ None\n    @ (constS _ @ (constS _ @ None)).\n\nInstance vNat_Proper : Proper (equiv ==> equiv) vNat.\nProof.\n  solve_proper.    \nQed.\n\nDefinition vNatS : natS ~> sqlValS := injF vNat _.\n\nInstance vAddr_Proper : Proper (equiv ==> equiv) vAddr.\nProof.\n  autounfold. intros. destruct x,y. simpl in *. f_equal. f_equal. tauto.  tauto. \nQed.\n\nDefinition vAddrS : sqlAddrS ~> sqlValS := injF vAddr _.\n\n\nLemma row_equiv_dec : forall (r1 r2 : row) ,  {r1 == r2} + {~r1 == r2}.\nProof.\n  intros. apply lista_equiv_dec.  apply SQLValType.equiv_dec.\nDefined.\n\nLemma maybe_row_equiv_dec : forall r1 r2 : maybe row, {r1 == r2} + {~r1 == r2}.\nProof.\n  intros. apply maybe_equiv_dec. apply row_equiv_dec. \nDefined.\n\n  \n", "meta": {"author": "xu-hao", "repo": "CertifiedQueryArrow", "sha": "8db512e0ebea8011b0468d83c9066e4a94d8d1c4", "save_path": "github-repos/coq/xu-hao-CertifiedQueryArrow", "path": "github-repos/coq/xu-hao-CertifiedQueryArrow/CertifiedQueryArrow-8db512e0ebea8011b0468d83c9066e4a94d8d1c4/SQL/SQLUtils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2565541364744409}}
{"text": "From lrust.lang Require Import proofmode memcpy.\nFrom lrust.typing Require Export type lft_contexts type_context cont_context.\nFrom iris.prelude Require Import options.\n\nSection typing.\n  Context `{!typeGS Σ}.\n\n  (** Function Body *)\n  (* This is an iProp because it is also used by the function type. *)\n  Definition typed_body (E : elctx) (L : llctx) (C : cctx) (T : tctx)\n                        (e : expr) : iProp Σ :=\n    (∀ tid (qmax : Qp), lft_ctx -∗ elctx_interp E -∗ na_own tid ⊤ -∗ llctx_interp qmax L -∗\n               cctx_interp tid qmax C -∗ tctx_interp tid T -∗\n               WP e {{ _, cont_postcondition }})%I.\n  Global Arguments typed_body _ _ _ _ _%E.\n\n  Global Instance typed_body_llctx_permut E :\n    Proper ((≡ₚ) ==> eq ==> eq ==> eq ==> (⊢)) (typed_body E).\n  Proof.\n    intros L1 L2 HL C ? <- T ? <- e ? <-. rewrite /typed_body.\n    by setoid_rewrite HL.\n  Qed.\n\n  Global Instance typed_body_elctx_permut :\n    Proper ((≡ₚ) ==> eq ==> eq ==> eq ==> eq ==> (⊢)) typed_body.\n  Proof.\n    intros E1 E2 HE L ? <- C ? <- T ? <- e ? <-. rewrite /typed_body.\n    by setoid_rewrite HE.\n  Qed.\n\n  Global Instance typed_body_mono E L:\n    Proper (flip (cctx_incl E) ==> flip (tctx_incl E L) ==> eq ==> (⊢))\n           (typed_body E L).\n  Proof.\n    intros C1 C2 HC T1 T2 HT e ? <-. iIntros \"H\".\n    iIntros (tid qmax) \"#LFT #HE Htl HL HC HT\".\n    iDestruct (llctx_interp_acc_noend with \"HL\") as \"[HL HLclose]\".\n    iMod (HT with \"LFT HE HL HT\") as \"(HL & HT)\".\n    iDestruct (\"HLclose\" with \"HL\") as \"HL\".\n    iApply (\"H\" with \"LFT HE Htl HL [HC] HT\").\n    by iApply (HC with \"LFT HE HC\").\n  Qed.\n\n  Lemma typed_body_tctx_incl E L T2 T1 C e :\n    tctx_incl E L T1 T2 →\n    (⊢ typed_body E L C T2 e) →\n    ⊢ typed_body E L C T1 e.\n  Proof.\n    intros Hincl He2. iApply typed_body_mono; last done; done.\n  Qed.\n\n  Global Instance typed_body_mono_flip E L:\n    Proper (cctx_incl E ==> tctx_incl E L ==> eq ==> flip (⊢))\n           (typed_body E L).\n  Proof. intros ?????????. by eapply typed_body_mono. Qed.\n\n  (** Instruction *)\n  Definition typed_instruction (E : elctx) (L : llctx)\n             (T1 : tctx) (e : expr) (T2 : val → tctx) : iProp Σ :=\n    (∀ tid qmax, lft_ctx -∗ elctx_interp E -∗ na_own tid ⊤ -∗\n              llctx_interp qmax L -∗ tctx_interp tid T1 -∗\n              WP e {{ v, na_own tid ⊤ ∗\n                         llctx_interp qmax L ∗ tctx_interp tid (T2 v) }})%I.\n  Global Arguments typed_instruction _ _ _ _%E _.\n\n  (** Writing and Reading **)\n  Definition typed_write_def (E : elctx) (L : llctx) (ty1 ty ty2 : type) : iProp Σ :=\n    (□ ∀ v tid F qmax qL, ⌜↑lftN ∪ (↑lrustN) ⊆ F⌝ →\n      lft_ctx -∗ elctx_interp E -∗ llctx_interp_noend qmax L qL -∗ ty1.(ty_own) tid [v] ={F}=∗\n        ∃ (l : loc) vl, ⌜length vl = ty.(ty_size) ∧ v = #l⌝ ∗ l ↦∗ vl ∗\n          (▷ l ↦∗: ty.(ty_own) tid ={F}=∗\n            llctx_interp_noend qmax L qL ∗ ty2.(ty_own) tid [v]))%I.\n  Definition typed_write_aux : seal (@typed_write_def). Proof. by eexists. Qed.\n  Definition typed_write := typed_write_aux.(unseal).\n  Definition typed_write_eq : @typed_write = @typed_write_def := typed_write_aux.(seal_eq).\n  Global Arguments typed_write _ _ _%T _%T _%T.\n\n  Global Instance typed_write_persistent (E : elctx) (L : llctx) (ty1 ty ty2 : type) :\n    Persistent (typed_write E L ty1 ty ty2).\n  Proof. rewrite typed_write_eq. apply _. Qed.\n\n  (* Technically speaking, we could remvoe the vl quantifiaction here and use\n     mapsto_pred instead (i.e., l ↦∗: ty.(ty_own) tid). However, that would\n     make work for some of the provers way harder, since they'd have to show\n     that nobody could possibly have changed the vl (because only half the\n     fraction was given). So we go with the definition that is easier to prove. *)\n  Definition typed_read_def (E : elctx) (L : llctx) (ty1 ty ty2 : type) : iProp Σ :=\n    (□ ∀ v tid F qmax qL, ⌜↑lftN ∪ ↑lrustN ⊆ F⌝ →\n      lft_ctx -∗ elctx_interp E -∗ na_own tid F -∗\n      llctx_interp_noend qmax L qL -∗ ty1.(ty_own) tid [v] ={F}=∗\n        ∃ (l : loc) vl q, ⌜v = #l⌝ ∗ l ↦∗{q} vl ∗ ▷ ty.(ty_own) tid vl ∗\n              (l ↦∗{q} vl ={F}=∗ na_own tid F ∗\n                              llctx_interp_noend qmax L qL ∗ ty2.(ty_own) tid [v]))%I.\n  Definition typed_read_aux : seal (@typed_read_def). Proof. by eexists. Qed.\n  Definition typed_read := typed_read_aux.(unseal).\n  Definition typed_read_eq : @typed_read = @typed_read_def := typed_read_aux.(seal_eq).\n  Global Arguments typed_read _ _ _%T _%T _%T.\n\n  Global Instance typed_read_persistent (E : elctx) (L : llctx) (ty1 ty ty2 : type) :\n    Persistent (typed_read E L ty1 ty ty2).\n  Proof. rewrite typed_read_eq. apply _. Qed.\nEnd typing.\n\nDefinition typed_instruction_ty `{!typeGS Σ} (E : elctx) (L : llctx) (T : tctx)\n    (e : expr) (ty : type) : iProp Σ :=\n  typed_instruction E L T e (λ v, [v ◁ ty]).\nGlobal Arguments typed_instruction_ty {_ _} _ _ _ _%E _%T.\n\nDefinition typed_val `{!typeGS Σ} (v : val) (ty : type) : Prop :=\n  ∀ E L, ⊢ typed_instruction_ty E L [] (of_val v) ty.\nGlobal Arguments typed_val _ _ _%V _%T.\n\nSection typing_rules.\n  Context `{!typeGS Σ}.\n\n  (* This lemma is helpful when switching from proving unsafe code in Iris\n     back to proving it in the type system. *)\n  Lemma type_type E L C T e :\n    typed_body E L C T e -∗ typed_body E L C T e.\n  Proof. done. Qed.\n\n  (** This lemma can replace [κ1] by [κ2] and vice versa in positions that\n  respect \"semantic lifetime equivalence\"; in particular, lifetimes of\n  references can be adjusted this way.  However, it cannot replace lifetimes in\n  other type constructors, as those might only respect *syntactic* lifetime\n  equivalence. This lemma is *weaker* than what was in the original paper where\n  lifetimes could be replaced everywhere; it had to be adjusted for GhostCell.\n  See [typing.lib.diverging_static] for an example of how\n  [type_equivalize_lft_static] without this restriction ciuld be used to subvert\n  branding.\n\n  This is technically not a proper typing rule since the type system has no way\n  to express \"subtyping wrt semantic lifetime inclusion\".  However, there is no\n  fundamental reason that we could not also reflect all these semantic facts on\n  the syntactic side, it would just be very clunky (and note that in Coq we do\n  not reflect this syntactic side anway). *)\n  Lemma type_equivalize_lft E L C T1 T2 κ1 κ2 e :\n    (∀ tid, lft_ctx -∗ κ1 ⊑ κ2 -∗ κ2 ⊑ κ1 -∗ tctx_interp tid T1 -∗ tctx_interp tid T2) →\n    (⊢ typed_body E L C T2 e) →\n    ⊢ typed_body E ((κ1 ⊑ₗ [κ2]) :: L) C T1 e.\n  Proof.\n    iIntros (Hswitch He tid qmax) \"#LFT #HE Htl [Hκ HL] HC HT\".\n    iMod (lctx_equalize_lft_sem with \"LFT Hκ\") as \"[Hκ1 Hκ2]\".\n    iApply (He with \"LFT HE Htl HL HC [-]\").\n    iApply (Hswitch with \"LFT Hκ1 Hκ2\"). done.\n  Qed.\n  Lemma type_equivalize_lft_static E L C T1 T2 κ e :\n    (∀ tid, lft_ctx -∗ static ⊑ κ -∗ tctx_interp tid T1 -∗ tctx_interp tid T2) →\n    (⊢ typed_body E L C T2 e) →\n    ⊢ typed_body E ((κ ⊑ₗ []) :: L) C T1 e.\n  Proof.\n    iIntros (Hswitch He tid qmax) \"#LFT #HE Htl [Hκ HL] HC HT\".\n    iMod (lctx_equalize_lft_sem_static with \"LFT Hκ\") as \"Hκ\".\n    iApply (He with \"LFT HE Htl HL HC [-]\").\n    iApply (Hswitch with \"LFT Hκ\"). done.\n  Qed.\n\n  Lemma type_let' E L T1 T2 (T : tctx) C xb e e' :\n    Closed (xb :b: []) e' →\n    typed_instruction E L T1 e T2 -∗\n    (∀ v : val, typed_body E L C (T2 v ++ T) (subst' xb v e')) -∗\n    typed_body E L C (T1 ++ T) (let: xb := e in e').\n  Proof.\n    iIntros (Hc) \"He He'\". iIntros (tid qmax) \"#LFT #HE Htl HL HC HT\". rewrite tctx_interp_app.\n    iDestruct \"HT\" as \"[HT1 HT]\". wp_bind e. iApply (wp_wand with \"[He HL HT1 Htl]\").\n    { iApply (\"He\" with \"LFT HE Htl HL HT1\"). }\n    iIntros (v) \"/= (Htl & HL & HT2)\". wp_let.\n    iApply (\"He'\" with \"LFT HE Htl HL HC [HT2 HT]\").\n    rewrite tctx_interp_app. by iFrame.\n  Qed.\n\n  (* We do not make the [typed_instruction] hypothesis part of the\n     Iris hypotheses, because we want to preserve the order of the\n     hypotheses. The is important, since proving [typed_instruction]\n     will instantiate [T1] and [T2], and hence we know what to search\n     for the following hypothesis. *)\n  Lemma type_let E L T T' T1 T2 C xb e e' :\n    Closed (xb :b: []) e' →\n    (⊢ typed_instruction E L T1 e T2) →\n    tctx_extract_ctx E L T1 T T' →\n    (∀ v : val, typed_body E L C (T2 v ++ T') (subst' xb v e')) -∗\n    typed_body E L C T (let: xb := e in e').\n  Proof.\n    unfold tctx_extract_ctx. iIntros (? He ->) \"?\". iApply type_let'; last done.\n    iApply He.\n  Qed.\n\n  Lemma type_seq E L T T' T1 T2 C e e' :\n    Closed [] e' →\n    (⊢ typed_instruction E L T1 e (λ _, T2)) →\n    tctx_extract_ctx E L T1 T T' →\n    typed_body E L C (T2 ++ T') e' -∗\n    typed_body E L C T (e ;; e').\n  Proof. iIntros. iApply (type_let E L T T' T1 (λ _, T2)); auto. Qed.\n\n  Lemma type_newlft {E L C T} κs e :\n    Closed [] e →\n    (∀ κ, typed_body E ((κ ⊑ₗ κs) :: L) C T e) -∗\n    typed_body E L C T (Newlft ;; e).\n  Proof.\n    iIntros (Hc) \"He\". iIntros (tid qmax) \"#LFT #HE Htl HL HC HT\".\n    iMod (lft_create with \"LFT\") as (Λ) \"[Htk #Hinh]\"; first done.\n    set (κ' := lft_intersect_list κs). wp_seq.\n    iApply (\"He\" $! (κ' ⊓ Λ) with \"LFT HE Htl [HL Htk] HC HT\").\n    rewrite /llctx_interp /=. iFrame \"HL\".\n    iExists Λ. iSplit; first done.\n    destruct (decide (1 ≤ qmax)%Qp) as [_|Hlt%Qp_lt_nge].\n    - by iFrame \"#∗\".\n    - apply Qp_lt_sum in Hlt as [q' ->]. iDestruct \"Htk\" as \"[$ Htk]\".\n      iIntros \"Htk'\". iApply \"Hinh\". iFrame.\n  Qed.\n\n  (* TODO: It should be possible to show this while taking only one step.\n     Right now, we could take two. *)\n  Lemma type_endlft E L C T1 T2 κ κs e :\n    Closed [] e → UnblockTctx κ T1 T2 →\n    typed_body E L C T2 e -∗ typed_body E ((κ ⊑ₗ κs) :: L) C T1 (Endlft ;; e).\n  Proof.\n    iIntros (Hc Hub) \"He\". iIntros (tid qmax) \"#LFT #HE Htl [Hκ HL] HC HT\".\n    iDestruct \"Hκ\" as (Λ) \"(% & Htok & Hend)\".\n    iSpecialize (\"Hend\" with \"Htok\"). wp_bind Endlft.\n    iApply (wp_mask_mono _ (↑lftN ∪ lft_userE)); first done.\n    iApply (wp_step_fupd with \"Hend\"); first set_solver+. wp_seq.\n    iIntros \"#Hdead !>\". wp_seq. iApply (\"He\" with \"LFT HE Htl HL HC [> -]\").\n    iApply (Hub with \"[] HT\"). simpl in *. subst κ. rewrite -lft_dead_or. auto.\n  Qed.\n\n  Lemma type_path_instr {E L} p ty :\n    ⊢ typed_instruction_ty E L [p ◁ ty] p ty.\n  Proof.\n    iIntros (??) \"_ _ $$ [? _]\".\n    iApply (wp_hasty with \"[-]\"); first done. iIntros (v) \"_ Hv\".\n    rewrite tctx_interp_singleton. iExists v. iFrame. by rewrite eval_path_of_val.\n  Qed.\n\n  Lemma type_letpath {E L} ty C T T' x p e :\n    Closed (x :b: []) e →\n    tctx_extract_hasty E L p ty T T' →\n    (∀ (v : val), typed_body E L C ((v ◁ ty) :: T') (subst' x v e)) -∗\n    typed_body E L C T (let: x := p in e).\n  Proof. iIntros. iApply type_let; [by apply type_path_instr|solve_typing|done]. Qed.\n\n  Lemma type_assign_instr {E L} ty ty1 ty1' p1 p2 :\n    (⊢ typed_write E L ty1 ty ty1') →\n    (⊢ typed_instruction E L [p1 ◁ ty1; p2 ◁ ty] (p1 <- p2) (λ _, [p1 ◁ ty1'])).\n  Proof.\n    iIntros (Hwrt tid ?) \"#LFT #HE $ HL\".\n    rewrite tctx_interp_cons tctx_interp_singleton. iIntros \"[Hp1 Hp2]\".\n    wp_bind p1. iApply (wp_hasty with \"Hp1\"). iIntros (v1) \"% Hown1\".\n    wp_bind p2. iApply (wp_hasty with \"Hp2\"). iIntros (v2) \"_ Hown2\".\n    rewrite typed_write_eq in Hwrt.\n    iDestruct (llctx_interp_acc_noend with \"HL\") as \"[HL HLclose]\".\n    iMod (Hwrt with \"[] LFT HE HL Hown1\") as (l vl) \"([% %] & Hl & Hclose)\"; first done.\n    subst v1. iDestruct (ty_size_eq with \"Hown2\") as \"#Hsz\". iDestruct \"Hsz\" as %Hsz.\n    rewrite <-Hsz in *. destruct vl as [|v[|]]; try done.\n    rewrite heap_mapsto_vec_singleton. iApply wp_fupd. wp_write.\n    rewrite -heap_mapsto_vec_singleton.\n    iMod (\"Hclose\" with \"[Hl Hown2]\") as \"(HL & Hown)\".\n    { iExists _. iFrame. }\n    iDestruct (\"HLclose\" with \"HL\") as \"$\".\n    rewrite tctx_interp_singleton tctx_hasty_val' //.\n  Qed.\n\n  Lemma type_assign {E L} ty1 ty ty1' C T T' p1 p2 e:\n    Closed [] e →\n    tctx_extract_ctx E L [p1 ◁ ty1; p2 ◁ ty] T T' →\n    (⊢ typed_write E L ty1 ty ty1') →\n    typed_body E L C ((p1 ◁ ty1') :: T') e -∗\n    typed_body E L C T (p1 <- p2 ;; e).\n  Proof. iIntros. by iApply type_seq; first apply type_assign_instr. Qed.\n\n  Lemma type_deref_instr {E L} ty ty1 ty1' p :\n    ty.(ty_size) = 1%nat → (⊢ typed_read E L ty1 ty ty1') →\n    (⊢ typed_instruction E L [p ◁ ty1] (!p) (λ v, [p ◁ ty1'; v ◁ ty])).\n  Proof.\n    iIntros (Hsz Hread tid qmax) \"#LFT #HE Htl HL Hp\".\n    rewrite tctx_interp_singleton. wp_bind p. iApply (wp_hasty with \"Hp\").\n    iIntros (v) \"% Hown\".\n    rewrite typed_read_eq in Hread.\n    iDestruct (llctx_interp_acc_noend with \"HL\") as \"[HL HLclose]\".\n    iMod (Hread with \"[] LFT HE Htl HL Hown\") as\n        (l vl q) \"(% & Hl & Hown & Hclose)\"; first done.\n    subst v. iDestruct (ty_size_eq with \"Hown\") as \"#>%\". rewrite ->Hsz in *.\n    destruct vl as [|v [|]]; try done.\n    rewrite heap_mapsto_vec_singleton. iApply wp_fupd. wp_read.\n    iMod (\"Hclose\" with \"Hl\") as \"($ & HL & Hown2)\".\n    iDestruct (\"HLclose\" with \"HL\") as \"$\".\n    rewrite tctx_interp_cons tctx_interp_singleton tctx_hasty_val tctx_hasty_val' //.\n    by iFrame.\n  Qed.\n\n  Lemma type_deref {E L} ty1 C T T' ty ty1' x p e:\n    Closed (x :b: []) e →\n    tctx_extract_hasty E L p ty1 T T' →\n    (⊢ typed_read E L ty1 ty ty1') →\n    ty.(ty_size) = 1%nat →\n    (∀ (v : val), typed_body E L C ((p ◁ ty1') :: (v ◁ ty) :: T') (subst' x v e)) -∗\n    typed_body E L C T (let: x := !p in e).\n  Proof. iIntros. by iApply type_let; [apply type_deref_instr|solve_typing|]. Qed.\n\n  Lemma type_memcpy_iris E L qmax qL tid ty ty1 ty1' ty2 ty2' (n : Z) p1 p2 :\n    Z.of_nat (ty.(ty_size)) = n →\n    typed_write E L ty1 ty ty1' -∗ typed_read E L ty2 ty ty2' -∗\n    {{{ lft_ctx ∗ elctx_interp E ∗ na_own tid ⊤ ∗ llctx_interp_noend qmax L qL ∗\n        tctx_elt_interp tid (p1 ◁ ty1) ∗ tctx_elt_interp tid (p2 ◁ ty2) }}}\n      (p1 <-{n} !p2)\n    {{{ RET #☠; na_own tid ⊤ ∗ llctx_interp_noend qmax L qL ∗\n                 tctx_elt_interp tid (p1 ◁ ty1') ∗ tctx_elt_interp tid (p2 ◁ ty2') }}}.\n  Proof.\n    iIntros (<-) \"#Hwrt #Hread !>\".\n    iIntros (Φ) \"(#LFT & #HE & Htl & [HL1 HL2] & [Hp1 Hp2]) HΦ\".\n    wp_bind p1. iApply (wp_hasty with \"Hp1\"). iIntros (v1) \"% Hown1\".\n    wp_bind p2. iApply (wp_hasty with \"Hp2\"). iIntros (v2) \"% Hown2\".\n    rewrite typed_write_eq typed_read_eq.\n    iMod (\"Hwrt\" with \"[] LFT HE HL1 Hown1\")\n      as (l1 vl1) \"([% %] & Hl1 & Hcl1)\"; first done.\n    iMod (\"Hread\" with \"[] LFT HE Htl HL2 Hown2\")\n      as (l2 vl2 q2) \"(% & Hl2 & Hown2 & Hcl2)\"; first done.\n    iDestruct (ty_size_eq with \"Hown2\") as \"#>%\". subst v1 v2. iApply wp_fupd.\n    iApply (wp_memcpy with \"[$Hl1 $Hl2]\"); try congruence; [].\n    iNext. iIntros \"[Hl1 Hl2]\". iApply (\"HΦ\" with \"[> -]\"). rewrite !tctx_hasty_val' //.\n    iMod (\"Hcl1\" with \"[Hl1 Hown2]\") as \"($ & $)\".\n    { iExists _. iFrame. }\n    iMod (\"Hcl2\" with \"Hl2\") as \"($ & $ & $)\". done.\n  Qed.\n\n  Lemma type_memcpy_instr {E L} ty ty1 ty1' ty2 ty2' (n : Z) p1 p2 :\n    Z.of_nat (ty.(ty_size)) = n →\n    (⊢ typed_write E L ty1 ty ty1') →\n    (⊢ typed_read E L ty2 ty ty2') →\n    ⊢ typed_instruction E L [p1 ◁ ty1; p2 ◁ ty2] (p1 <-{n} !p2)\n                      (λ _, [p1 ◁ ty1'; p2 ◁ ty2']).\n  Proof.\n    iIntros (Hsz Hwrt Hread tid qmax) \"#LFT #HE Htl HL HT\".\n    iDestruct (llctx_interp_acc_noend with \"HL\") as \"[HL HLclose]\".\n    iApply (type_memcpy_iris with \"[] [] [$LFT $Htl $HE $HL HT]\"); try done.\n    { by rewrite tctx_interp_cons tctx_interp_singleton. }\n    rewrite tctx_interp_cons tctx_interp_singleton.\n    iIntros \"!> ($ & HL & $ & $)\". by iApply \"HLclose\".\n  Qed.\n\n  Lemma type_memcpy {E L} ty ty1 ty2 (n : Z) C T T' ty1' ty2' p1 p2 e:\n    Closed [] e →\n    tctx_extract_ctx E L [p1 ◁ ty1; p2 ◁ ty2] T T' →\n    (⊢ typed_write E L ty1 ty ty1') →\n    (⊢ typed_read E L ty2 ty ty2') →\n    Z.of_nat (ty.(ty_size)) = n →\n    typed_body E L C ((p1 ◁ ty1') :: (p2 ◁ ty2') :: T') e -∗\n    typed_body E L C T (p1 <-{n} !p2;; e).\n  Proof. iIntros. by iApply type_seq; first eapply (type_memcpy_instr ty ty1 ty1'). Qed.\nEnd typing_rules.\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/programs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.25655413647444086}}
{"text": "Require Import compcert.lib.Coqlib.\nRequire Export compcert.lib.Maps.\nRequire Import compcert.common.Errors.\nRequire Import liblayers.lib.Decision.\nRequire Import liblayers.lib.OptionMonad.\nRequire Import liblayers.logic.Structures.\nRequire Import liblayers.logic.OptionOrders.\nRequire Import liblayers.logic.PseudoJoin.\nRequire Import liblayers.logic.LayerData.\n\n(** * Generic operations on [PTree]s *)\n\nDefinition ptree_rel {A B} (R: rel (option A) (option B)): rel _ _ :=\n  fun t1 t2 => forall i, R (t1!i) (t2!i).\n\nGlobal Instance ptree_subrel A B:\n  Proper (subrel ++> subrel) (@ptree_rel A B).\nProof.\n  firstorder.\nQed.\n\nGlobal Instance ptree_subrel_params:\n  Params (@ptree_rel) 3.\n\nGlobal Instance ptree_get_rel:\n  Monotonic\n    (@PTree.get)\n    (forallr R : fun A B => rel (option A) (option B), - ==> ptree_rel R ++> R).\nProof.\n  intros A B R i t1 t2 H.\n  apply H.\nQed.\n\n(** Structures on [option A] can be extended to [PTree.t A] *)\n\nLocal Instance ptree_emptyset A : Emptyset (PTree.t A) :=\n  { emptyset := PTree.empty A }.\n\nLocal Instance ptree_mapsto A : Mapsto positive A (PTree.t A) :=\n  { mapsto i a := PTree.set i a (PTree.empty A) }.\n\nLocal Instance ptree_le_op {A} `(Ale: Le (option A)): Le (PTree.t A) :=\n  { le := ptree_rel (≤) }.\n\nLemma ptree_refl A (R: relation (option A)):\n  Reflexive R ->\n  Reflexive (ptree_rel R).\nProof.\n  intros HA.\n  intros t i.\n  reflexivity.\nQed.\n\nHint Extern 1 (Reflexive (ptree_rel _)) =>\n  eapply ptree_refl : typeclass_instances.\n\nLemma ptree_trans A (R: relation (option A)):\n  Transitive R ->\n  Transitive (ptree_rel R).\nProof.\n  intros HA.\n  intros t1 t2 t3 H12 H23 i.\n  transitivity (t2 ! i); now trivial.\nQed.\n\nHint Extern 1 (Transitive (ptree_rel _)) =>\n  eapply ptree_trans : typeclass_instances.\n\nGlobal Instance ptree_rel_htrans {A B C} RAB RBC RAC:\n  HTransitive (A:=option A) (B:=option B) (C:=option C) RAB RBC RAC ->\n  HTransitive (ptree_rel RAB) (ptree_rel RBC) (ptree_rel RAC).\nProof.\n  intros HR x y z Hxy Hyz.\n  intros i.\n  ehtransitivity; eauto.\nQed.\n\n(** To show that [RTransitive] carries through [ptree_rel] is tricky\n  because we need to construct the intermediate tree. To make our job\n  easier we only consider the [option_le] case. *)\nSection RTRANSITIVE.\n  Context `{HR: RTransitive}.\n\n  (** We need Hilbert's epsilon. *)\n  Require Import ClassicalEpsilon.\n  Require Import List.\n\n  (** Then we can construct the middle ptree by eliminating the\n    existential from the [rtransitivity] of the underlying relation. *)\n\n  Definition rtrans_midval a c (Hac: option_le RAC a c) :=\n    proj1_sig (constructive_indefinite_description _ (rtransitivity a c Hac)).\n\n  Lemma rtrans_midval_correct a c Hac:\n    option_le RAB a (rtrans_midval a c Hac) /\\\n    option_le RBC (rtrans_midval a c Hac) c.\n  Proof.\n    unfold rtrans_midval.\n    destruct (constructive_indefinite_description _ _) as [b Hb].\n    simpl.\n    assumption.\n  Qed.\n\n  Definition ptree_rtrans_midval tA tC (Ht: ptree_rel (option_le RAC) tA tC) i :=\n    rtrans_midval (tA!i) (tC!i) (Ht i).\n\n  Lemma ptree_rtrans_midval_correct tA tC Ht i:\n    option_le RAB (tA!i) (ptree_rtrans_midval tA tC Ht i) /\\\n    option_le RBC (ptree_rtrans_midval tA tC Ht i) (tC!i).\n  Proof.\n    unfold ptree_rtrans_midval.\n    apply rtrans_midval_correct.\n  Qed.\n\n  Definition ptree_option_set i (x: option B) t :=\n    match x with\n      | Some b => PTree.set i b t\n      | None => PTree.remove i t\n    end.\n\n  Definition ptree_rtrans_midtree tA tC Ht :=\n    fold_right (fun i => ptree_option_set i (ptree_rtrans_midval tA tC Ht i))\n               (PTree.empty B)\n               (map fst (PTree.elements tC)).\n\n  Lemma ptree_rtrans_midtree_correct tA tC Ht i:\n    option_le RAB (tA!i) ((ptree_rtrans_midtree tA tC Ht) ! i) /\\\n    option_le RBC ((ptree_rtrans_midtree tA tC Ht) ! i) (tC!i).\n  Proof.\n    pose proof (ptree_rtrans_midval_correct tA tC Ht i) as Hb.\n    unfold ptree_rtrans_midtree.\n    unfold ptree_option_set.\n    assert (HCi: tC!i = None \\/ (exists c, In (i, c) (PTree.elements tC))).\n    {\n      destruct (tC ! i) as [c|] eqn:HtC.\n      * eauto using PTree.elements_correct.\n      * eauto.\n    }\n    induction (PTree.elements tC); simpl in *.\n    + destruct HCi as [HCi | [c Hc]].\n      - rewrite PTree.gempty, HCi in *.\n        destruct Hb as [Hab Hbc].\n        inversion Hbc as [? Hmv | ]; subst.\n        rewrite <- Hmv in *.\n        eauto.\n      - elim Hc.\n    + destruct a as [j cj]; simpl in *.\n      destruct (decide (i = j)).\n      - subst.\n        simpl in *.\n        destruct (ptree_rtrans_midval tA tC Ht j) as [b|].\n        rewrite PTree.gss; assumption.\n        rewrite PTree.grs; assumption.\n      - destruct HCi as [Hnone | [c [Hc|Hc]]]; try congruence;\n        destruct (ptree_rtrans_midval tA tC Ht j) as [b|];\n        rewrite ?PTree.gso, ?PTree.gro; now eauto.\n  Qed.\n\n  Global Instance ptree_rel_rtrans:\n    RTransitive (ptree_rel (option_le RAB))\n                (ptree_rel (option_le RBC))\n                (ptree_rel (option_le RAC)).\n  Proof.\n    intros tA tC Ht.\n    exists (ptree_rtrans_midtree tA tC Ht).\n    pose proof (ptree_rtrans_midtree_correct tA tC Ht).\n    split; intro i; destruct (H i); eauto.\n  Qed.\nEnd RTRANSITIVE.\n\nLocal Instance ptree_oplus A `{Aoplus: Oplus (option A)}: Oplus (PTree.t A) :=\n  { oplus := PTree.combine (⊕) }.\n\nGlobal Instance ptree_emptyset_lb A B (R: rel (option A) (option B)):\n  LowerBound R None ->\n  LowerBound (ptree_rel R) (PTree.empty A).\nProof.\n  intros H t2 i.\n  rewrite PTree.gempty.\n  apply lower_bound.\nQed.\n\nLemma ptree_combine_rel:\n  forall\n    {A1 A2} (RA: rel (option A1) (option A2))\n    {B1 B2} (RB: rel (option B1) (option B2))\n    {C1 C2} (RC: rel (option C1) (option C2))\n    (f: option A1 -> option B1 -> option C1)\n    (g: option A2 -> option B2 -> option C2),\n  f None None = None ->\n  g None None = None ->\n  (RA ++> RB ++> RC)%rel f g ->\n  (ptree_rel RA ++> ptree_rel RB ++> ptree_rel RC)%rel (PTree.combine f) (PTree.combine g).\nProof.\n  intros A1 A2 RA B1 B2 RB C1 C2 RC f g.\n  intros Hf Hg Hfg x1 x2 Hx y1 y2 Hy i.\n  rewrite !PTree.gcombine by assumption.\n  apply Hfg; eauto.\nQed.\n\nLemma ptree_combine_id_left {A} R f:\n  f None None = None ->\n  LeftIdentity R f None ->\n  LeftIdentity (ptree_rel R) (PTree.combine f) (PTree.empty A).\nProof.\n  intros Hf H.\n  intros y i.\n  rewrite PTree.gcombine by assumption.\n  rewrite PTree.gempty.\n  apply id_left.\nQed.\n\nLemma ptree_combine_assoc {A} (R: relation (option A)) f:\n  f None None = None ->\n  Associative R f ->\n  Associative (ptree_rel R) (PTree.combine f).\nProof.\n  intros Hf H.\n  intros x y z i.\n  rewrite !PTree.gcombine by assumption.\n  apply associativity.\nQed.\n\nLemma ptree_combine_comm {A} (R: relation (option A)) f:\n  f None None = None ->\n  Commutative R f ->\n  Commutative (ptree_rel R) (PTree.combine f).\nProof.\n  intros Hf H.\n  intros x y i.\n  rewrite !PTree.gcombine by assumption.\n  apply commutativity.\nQed.\n\nLemma ptree_combine_left_upper_bound {A} (R: relation (option A)) f:\n  f None None = None ->\n  LeftUpperBound R f ->\n  LeftUpperBound (ptree_rel R) (PTree.combine f).\nProof.\n  intros Hf H.\n  intros x y i.\n  rewrite !PTree.gcombine by assumption.\n  apply left_upper_bound.\nQed.\n\nGlobal Instance ptree_pseudojoin A:\n  forall `{Ale: Le (option A)} `{Aoplus: Oplus (option A)},\n    None ⊕ None = None ->\n    PseudoJoin (option A) None ->\n    PseudoJoin (PTree.t A) ∅.\nProof with try (assumption || typeclasses eauto).\n  intros Hnone Hop.\n  split; simpl...\n  * split; typeclasses eauto.\n  * apply ptree_combine_rel...\n    solve_monotonic.\n  * apply ptree_combine_id_left...\n  * apply ptree_combine_assoc...\n  * apply ptree_combine_comm...\n  * apply ptree_combine_left_upper_bound...\nQed.\n\n(** Same thing, indexed by layer data *)\n\nSection SIM.\n  Context {V E T} `{Hsim: CategorySim V E (fun v => option (T v))}.\n\n  Local Instance ptree_sim_op: Sim E (fun D => PTree.t (T D)) :=\n    {\n      simRR D1 D2 R := ptree_rel (simRR (Sim:=cat_sim) D1 D2 R)\n    }.\n\n  Local Instance ptree_rg_sim:\n    CategorySim V E (fun D => PTree.t (T D)).\n  Proof.\n    (** Those will be expressed in terms of [(fun u => option (T u)) v]\n      instead of [option (T v)], so we need to get them explicitely in\n      the context, and reduce. *)\n    Set Printing All.\n    pose proof (fun v => cat_sim_preorder v) as Hle_preorder.\n    pose proof (fun v1 v2 e => cat_sim_trans v1 v2 e) as Hsim_trans.\n    simpl in *.\n    Unset Printing All.\n\n    split.\n    * apply cat_sim_cat.\n    * simpl.\n      solve_monotonic.\n    * simpl.\n      typeclasses eauto.\n    * simpl.\n      intros v1 v2 v3 e12 e23 x1 x2 x3 H12 H23 i.\n      specialize (H12 i).\n      specialize (H23 i).\n      htransitivity (x2 ! i);\n      assumption.\n  Qed.\n\n  Ltac eta_option :=\n    repeat\n      lazymatch goal with\n        | |- context [option (?T ?v)] =>\n          change (option (T v)) with ((fun u => option (T u)) v)\n      end.\n\n  Local Instance ptree_sim_pseudojoin:\n    forall `{Aoplus: forall v, Oplus ((fun v => option (T v)) v)},\n      (forall v, None ⊕ None = @None (T v)) ->\n      SimPseudoJoin _ _ _ (Toplus := Aoplus) (fun v => @None (T v)) ->\n      SimPseudoJoin _ _ _ (Toplus := fun v => ptree_oplus (T v)) (fun v => PTree.empty (T v)).\n  Proof with eta_option; try (typeclasses eauto || simpl; eauto).\n    intros.\n    split; intros...\n    * red in H1; subst.\n      apply ptree_emptyset_lb.\n      eta_option.\n      eapply @oplus_sim_lower_bound.\n      + eassumption.\n      + typeclasses eauto.\n    * intros v1 v2 R.\n      apply ptree_combine_rel...\n      eta_option.\n      apply oplus_sim_monotonic.\n    * red in H1; subst.\n      apply ptree_combine_id_left...\n    * apply ptree_combine_assoc...\n      eta_option.\n      apply oplus_sim_assoc_le.\n    * apply ptree_combine_comm...\n      eta_option.\n      apply oplus_sim_comm_le.\n    * apply ptree_combine_left_upper_bound...\n  Qed.\nEnd SIM.\n\n(** * Decidable properties of [PTree]s *)\n\n(** ** Some property holds for all bindings *)\n\nDefinition ptree_forall {A} (P: positive -> A -> Prop) (t: PTree.t A) :=\n  forall i a, t!i = Some a -> P i a.\n\nProgram Instance ptree_forall_decision {A} (P: positive -> A -> Prop):\n  (forall i a, Decision (P i a)) ->\n  (forall t, Decision (ptree_forall P t)) :=\n  fun HP t =>\n    match (decide (Forall (fun b => P (fst b) (snd b)) (PTree.elements t))) with\n      | left HPt => left _\n      | right HPt => right _\n    end.\n\nNext Obligation.\n  clear Heq_anonymous.\n  intros i a Hia.\n  apply PTree.elements_correct in Hia.\n  rewrite Forall_forall in HPt.\n  specialize (HPt (i, a)); simpl in *.\n  tauto.\nQed.\n\nNext Obligation.\n  clear Heq_anonymous.\n  intros H.\n  apply HPt; clear HPt.\n  rewrite Forall_forall.\n  intros [i a] Hia; simpl.\n  apply H.\n  apply PTree.elements_complete.\n  assumption.\nQed.\n\n(** ** Two [PTree]s have disjoint domains *)\n\nDefinition ptree_disjoint {A B} (ta: PTree.t A) (tb: PTree.t B) :=\n  ptree_forall (fun i _ => tb ! i = None) ta.\n\nLemma ptree_disjoint_sym {A B} (ta: PTree.t A) (tb: PTree.t B):\n  ptree_disjoint ta tb ->\n  ptree_disjoint tb ta.\nProof.\n  unfold ptree_disjoint, ptree_forall. intros.\n  destruct (ta ! i) eqn:?; try reflexivity.\n  exploit H; eauto. congruence.\nQed.\n\nLemma ptree_disjoint_combine {A B}\n      (ta: PTree.t A) (tb1 tb2: PTree.t B)\n      (f: option B -> option B -> option B)\n:\n  f None None = None ->\n  ptree_disjoint ta tb1 ->\n  ptree_disjoint ta tb2 ->\n  ptree_disjoint ta (PTree.combine f tb1 tb2).\nProof.\n  unfold ptree_disjoint.\n  unfold ptree_forall.\n  intros H H0 H1 i a H2.\n  rewrite PTree.gcombine by assumption.\n  erewrite H0 by eassumption.\n  erewrite H1 by eassumption.\n  assumption.\nQed.\n\n(** * Applying a partial function to all data of a tree. *)\n\n(** For now, I disable. I suspect we can redo this in a more\n  straightforward way, closer to where it's actually used. Will need\n  to see when we update CompCertiKOS. *)\n\n\n(** If it fails on one element, then it fails on the whole tree.  If\n    it succeeds on all elements, then it succeeds on the whole tree.\n*)\n\nModule PTree.\nExport Maps.PTree.\n\n(*\n    Fixpoint xmap_error {A B : Type} (f : positive -> A -> res B) (m : t A) (i : positive)\n             {struct m} : res (t B) :=\n      match m with\n      | Leaf => OK Leaf\n      | Node l o r =>\n        match xmap_error f l (append i (xO xH)) with\n            | Error msg => Error msg\n            | OK l' =>\n              match xmap_error f r (append i (xI xH)) with\n                | Error msg => Error msg\n                | OK r' =>\n                  match o with\n                    | None => OK (Node l' None r')\n                    | Some a =>\n                      match f i a with\n                        | Error msg => Error msg\n                        | OK b => OK (Node l' (Some b) r')\n                      end\n                  end\n              end\n        end\n      end.\n\n  Definition map_error {A B : Type} (f : positive -> A -> res B) m := xmap_error f m xH.\n\n    Lemma xgmap_error_ok:\n      forall (A B: Type) (f: positive -> A -> res B) (i j : positive) (m: t A),\n        forall (m': t B),\n          xmap_error f m j = OK m' ->\n          match get i m with\n            | None => get i m' = None\n            | Some a => exists b, f (append j i) a = OK b /\\ get i m' = Some b\n          end. \n    Proof.\n      induction i; intros until m'; destruct m; simpl; auto.\n      + inversion 1; subst; reflexivity.\n      + destruct (xmap_error f m1 (append j 2)) eqn:?; try discriminate.\n        destruct (xmap_error f m2 (append j 3)) eqn:?; try discriminate.\n        destruct o.\n        - destruct (f j a) eqn:?; try discriminate.\n          inversion 1; subst.\n          rewrite (append_assoc_1 j i). eapply IHi; eauto.\n        - inversion 1; subst.\n          rewrite (append_assoc_1 j i). eapply IHi; eauto.\n      + inversion 1; subst; reflexivity.\n      + destruct (xmap_error f m1 (append j 2)) eqn:?; try discriminate.\n        destruct (xmap_error f m2 (append j 3)) eqn:?; try discriminate.\n        destruct o.\n        - destruct (f j a) eqn:?; try discriminate.\n          inversion 1; subst.\n          rewrite (append_assoc_0 j i). eapply IHi; eauto.\n        - inversion 1; subst.\n          rewrite (append_assoc_0 j i). eapply IHi; eauto.\n      + inversion 1; subst; reflexivity.\n      + destruct (xmap_error f m1 (append j 2)) eqn:?; try discriminate.\n        destruct (xmap_error f m2 (append j 3)) eqn:?; try discriminate.\n        destruct o.\n        - destruct (f j a) eqn:?; try discriminate.\n          inversion 1; subst.\n          rewrite (append_neutral_r j). eauto.\n        - inversion 1; subst.\n          reflexivity.\n    Qed.\n\n    Theorem gmap_error_ok:\n      forall (A B: Type) (f: positive -> A -> res B) (i: positive) (m: t A),\n        forall (m': t B),\n          map_error f m = OK m' ->\n          match get i m with\n            | None => get i m' = None\n            | Some a => exists b, f i a = OK b /\\ get i m' = Some b\n          end. \n    Proof.\n      unfold map_error.\n      intros.\n      replace (f i) with (f (append xH i)).\n      apply xgmap_error_ok; auto.\n      rewrite append_neutral_l; auto.\n    Qed.\n\n    Lemma xgmap_error_error:\n      forall (A B: Type) (f: positive -> A -> res B) (m: t A) (j : positive),\n        forall msg,\n          xmap_error f m j = Error msg ->\n          exists k, exists a, exists msg',\n            get k m = Some a /\\\n            f (append j k) a = Error msg'.\n    Proof.\n      induction m; simpl; try discriminate.\n      intros.\n      destruct (xmap_error f m1 (append j 2)) eqn:?.\n      destruct (xmap_error f m2 (append j 3)) eqn:?.\n      destruct o; try discriminate.\n      destruct (f j a) eqn:?; try discriminate.\n      + exists xH; simpl. rewrite append_neutral_r. eauto.\n      + exploit IHm2; eauto.\n        destruct 1 as [? [? [? [? ?]]]].\n        exists (xI x); simpl. rewrite append_assoc_1. eauto.\n      + exploit IHm1; eauto.\n        destruct 1 as [? [? [? [? ?]]]].\n        exists (xO x); simpl. rewrite append_assoc_0. eauto.\n    Qed.\n\n    Theorem gmap_error_error:\n      forall (A B: Type) (f: positive -> A -> res B) (i: positive) (m: t A),\n        forall msg,\n          map_error f m = Error msg ->\n          exists k, exists a, exists msg',\n          get k m = Some a /\\\n          f k a = Error msg'.\n    Proof.\n      unfold map_error.\n      intros.\n      exploit xgmap_error_error; eauto.\n    Qed.\n\n    Lemma xmap_compose_ok:\n      forall (A B C: Type) (fab: positive -> A -> res B) (fbc: positive -> B -> res C) (fac: positive -> A -> res C) (ma: t A) (j: positive),\n        forall (mb: t B) (mc: t C),\n          xmap_error fab ma j = OK mb ->\n          xmap_error fbc mb j = OK mc ->\n          (forall i a, get i ma = Some a ->\n                       forall b, fab (append j i) a = OK b ->\n                                 forall c,\n                                 fbc (append j i) b = OK c ->\n                                 fac (append j i) a = OK c) ->\n          xmap_error fac ma j = OK mc.\n    Proof.\n      induction ma; simpl; intros.\n      * inv H. inv H0. reflexivity.\n      * destruct (xmap_error fab ma1 (append j 2)) eqn:?; try discriminate.\n        destruct (xmap_error fab ma2 (append j 3)) eqn:?; try discriminate.        \n        destruct o.\n        + destruct (fab j a) eqn:?; try discriminate.\n          inv H.\n          simpl in H0.\n          destruct (xmap_error fbc t0 (append j 2)) eqn:?; try discriminate.\n          destruct (xmap_error fbc t1 (append j 3)) eqn:?; try discriminate.\n          destruct (fbc j b) eqn:?; try discriminate.\n          inv H0.\n          generalize (H1 xH _ (refl_equal _) b).\n          rewrite append_neutral_r.\n          intro.\n          erewrite H; eauto.\n          erewrite IHma1.\n          erewrite IHma2.\n          reflexivity.\n          eassumption.\n          assumption.\n          intros until 1. intro.\n          rewrite <- append_assoc_1.\n          eauto.\n          eassumption.\n          assumption.\n          intros until 1. intro.\n          rewrite <- append_assoc_0.\n          eauto.\n        + inv H.\n          simpl in H0.\n          destruct (xmap_error fbc t0 (append j 2)) eqn:?; try discriminate.\n          destruct (xmap_error fbc t1 (append j 3)) eqn:?; try discriminate.\n          inv H0.\n          erewrite IHma1.\n          erewrite IHma2.\n          reflexivity.\n          eassumption.\n          assumption.\n          intros until 1. intro.\n          rewrite <- append_assoc_1.\n          eauto.\n          eassumption.\n          assumption.\n          intros until 1. intro.\n          rewrite <- append_assoc_0.\n          eauto.\n    Qed.\n\n    Lemma map_compose_ok:\n      forall (A B C: Type) (fab: positive -> A -> res B) (fbc: positive -> B -> res C) (fac: positive -> A -> res C) (ma: t A),\n        forall (mb: t B) (mc: t C),\n          map_error fab ma = OK mb ->\n          map_error fbc mb = OK mc ->\n          (forall i a, get i ma = Some a ->\n                       forall b, fab i a = OK b ->\n                                 forall c,\n                                 fbc i b = OK c ->\n                                 fac i a = OK c) ->\n          map_error fac ma = OK mc.\n    Proof.\n      intros.\n      eapply xmap_compose_ok; eauto.\n    Qed.\n *)\n\nFixpoint xmap_option {A B : Type} (f : positive -> A -> option B) (m : t A) (i : positive) {struct m} :\n  t B :=\n  match m with\n  | Leaf => Leaf\n  | Node l o r =>\n    Node (xmap_option f l (i~0)%positive) match o with\n                                                | Some x => (f (prev i) x)\n                                                | None => None\n                                                end (xmap_option  f r (i~1)%positive)\n  end.\n\n\nDefinition map_option {A B: Type} (f: positive -> A -> option B) (m: t A): t B :=\n  xmap_option f m 1.\n\nLemma xgmap_option_some:\n  forall (A B: Type) (f: positive -> A -> option B) (i j : positive) (m: t A),\n  forall a,\n    get i m = Some a ->\n    get i (xmap_option f m j) = f (prev (prev_append i j)) a.\nProof.\n  induction i; destruct m; simpl; intros; try discriminate.\n  + apply IHi. auto.\n  + apply IHi; auto.\n  + subst. auto.\nQed.\n\nTheorem gmap_option_some:\n  forall (A B: Type) (f: positive -> A -> option B) (i: positive) (m: t A),\n  forall a,\n    get i m = Some a ->\n    get i (map_option f m) = f i a.\nProof.\n  unfold map_option.\n  intros.\n  erewrite xgmap_option_some; eauto.\n  rewrite prev_append_prev. simpl. reflexivity.\nQed.\n\nLemma xgmap_option_none:\n  forall (A B: Type) (f: positive -> A -> option B) (i: positive) (m: t A) (j : positive),\n    get i m = None ->\n    get i (xmap_option f m j) = None.\nProof.\n  induction i; destruct m; simpl; intros; try reflexivity; eauto.\n  subst. reflexivity.\nQed.\n\nTheorem gmap_option_none:\n  forall (A B: Type) (f: positive -> A -> option B) (i: positive) (m: t A),\n    get i m = None ->\n    get i (map_option f m) = None.\nProof.\n  unfold map_option.\n  intros.\n  exploit xgmap_option_none; eauto.\nQed.\n\nLemma gmap_option {A B} (f: positive -> A -> option B) (i: positive) m:\n  (map_option f m) ! i = x <- m ! i; f i x.\nProof.\n  case_eq (m ! i).\n  * apply gmap_option_some.\n  * apply gmap_option_none.\nQed.\n\n\nEnd PTree.\n\n(** A PTree is never completely full... *)\n\nTheorem ptree_get_none_ex {A} (m: _ A):\n  exists i, PTree.get i m = None.\nProof.\n  induction m; simpl.\n  * exists xH. reflexivity.\n  * destruct IHm1 as (x & ?).\n    exists (xO x); simpl.\n    assumption.\nQed.\n\nTheorem ptree_forall_decision_strong {A}\n        (P: positive -> A -> Prop)\n        (Q: Prop):\n  (forall i a, Decision (P i a)) ->\n  Decision Q ->\n  (forall t, Decision (forall i,\n                         match t ! i with\n                           | Some a => P i a\n                           | None => Q\n                         end)).\nProof.\n  intros DP DQ t.\n  apply (decide_discr (fun i => t ! i = None) (fun i => t ! i <> None)).\n  + intro. apply OptionMonad.isNone_dec.\n  + revert DQ.\n    apply decide_rewrite.\n    split.\n    - intros until i. intro Li.\n      rewrite Li.\n      assumption.\n    - intro J.\n      destruct (ptree_get_none_ex t) as (? & Hx).\n      generalize (J _ Hx).\n      rewrite Hx.\n      tauto.\n  + generalize (ptree_forall_decision _ DP t).\n    apply decide_rewrite.\n    unfold ptree_forall.\n    split.\n    - intros J i Hi.\n      destruct (t ! i) eqn:Ti; try congruence.\n      auto.\n    - intros J i a Ha.\n      generalize (J i).\n      rewrite Ha.\n      intro K.\n      apply K; congruence.\nDefined.\n\n(** ** Monotonicity wrt. [ptree_rel] *)\n\nGlobal Instance ptree_map_monotonic:\n  Monotonic\n    PTree.map\n    (forallr RA, forallr RB,\n      (- ==> RA ++> RB) ++>\n      ptree_rel (option_le RA) ++>\n      ptree_rel (option_le RB)).\nProof.\n  intros A1 A2 RA B1 B2 RB f g Hfg t1 t2 Ht i.\n  rewrite !PTree.gmap.\n  solve_monotonic.\nQed.\n\nGlobal Instance: Params (@PTree.map) 4.\n\n(*\nGlobal Instance ptree_map_option_monotonic {A B} (RA: relation A) (RB: relation B):\n  Proper ((- ==> RA ++> option_le RB) ++> (ptree_rel (option_le RA) ++> ptree_rel (option_le RB)))\n    PTree.map_option.\nProof.\n  intros f g Hfg t1 t2 Ht i.\n  specialize (Ht i).\n  inversion Ht as [x2 Hx1 Hx2 | x1 x2 Hx Hx1 Hx2].\n  * rewrite PTree.gmap_option_none by congruence.\n    constructor.\n  * symmetry in Hx1, Hx2.\n    erewrite !PTree.gmap_option_some by eassumption.\n    apply Hfg.\n    assumption.\nQed.\n\nGlobal Instance: Params (@PTree.map_option) 2.\n*)\n\n(** FIXME: those could actually be strengthened to use [option_rel] if\n  we had the appropriate subrelation infrastructure. *)\n\nInstance ptree_set_le:\n  Monotonic\n    (@PTree.set)\n    (forallr R, - ==> R ++> ptree_rel (option_le R) ++> ptree_rel (option_le R)).\nProof.\n  intros A1 A2 RA i x1 x2 Hx t1 t2 Ht j.\n  destruct (decide (j = i)) as [Hij | Hij]; subst.\n  * rewrite !PTree.gss.\n    solve_monotonic.\n  * rewrite !PTree.gso by assumption.\n    solve_monotonic.\nQed.\n\nGlobal Instance: Params (@PTree.set) 4.\n\nInstance ptree_empty_le:\n  Monotonic (@PTree.empty) (forallr R, ptree_rel (option_le R)).\nProof.\n  intros A1 A2 RA i.\n  rewrite !PTree.gempty.\n  constructor.\nQed.\n\nGlobal Instance: Params (@PTree.empty) 1.\n\nGlobal Instance ptree_elements_rel:\n  Monotonic\n    (@PTree.elements)\n    (forallr R, ptree_rel (option_rel R) ++> list_rel (eq * R)).\nProof.\n  intros A B R t1 t2 Ht.\n  cut (list_forall2 (eq * R)%rel (PTree.elements t1) (PTree.elements t2)).\n  - induction 1; constructor; eauto.\n  - eapply PTree.elements_canonical_order.\n    + intros i.\n      destruct (Ht i); inversion 1; subst; eauto.\n    + intros i.\n      destruct (Ht i); inversion 1; subst; eauto.\nQed.\n\nGlobal Instance: Params (@PTree.elements) 2.\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/logic/PTrees.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.25655413030316987}}
{"text": "From HTTP2.HPACK Require Import HPACKTypes.\nFrom HTTP2 Require Import Types.\nFrom HTTP2.Util Require Import Parser.\nFrom Coq Require Import Strings.String BinNat Lists.List Basics.\nFrom ExtLib Require Import Monad MonadExc.\nImport ListNotations MonadNotation.\nRequire Coq.Structures.OrderedTypeEx Program.Wf.\nOpen Scope list_scope.\nOpen Scope string_scope.\nOpen Scope N_scope.\nOpen Scope program_scope.\nOpen Scope monad_scope.\n\n(* https://tools.ietf.org/html/rfc7541#appendix-A *)\n(* https://tools.ietf.org/html/rfc7541#section-2.3.1 *)\nDefinition static_table : Table :=\n  [ (\":authority\", \"\");\n    (\":method\", \"GET\");\n    (\":method\", \"POST\");\n    (\":path\", \"/\");\n    (\":path\", \"/index.html\");\n    (\":scheme\", \"http\");\n    (\":scheme\", \"https\");\n    (\":status\", \"200\");\n    (\":status\", \"204\");\n    (\":status\", \"206\");\n    (\":status\", \"304\");\n    (\":status\", \"400\");\n    (\":status\", \"404\");\n    (\":status\", \"500\");\n    (\"accept-charset\", \"\");\n    (\"accept-encoding\", \"gzip, deflate\");\n    (\"accept-language\", \"\");\n    (\"accept-ranges\", \"\");\n    (\"accept\", \"\");\n    (\"access-control-allow-origin\", \"\");\n    (\"age\", \"\");\n    (\"allow\", \"\");\n    (\"authorization\", \"\");\n    (\"cache-control\", \"\");\n    (\"content-disposition\", \"\");\n    (\"content-encoding\", \"\");\n    (\"content-language\", \"\");\n    (\"content-length\", \"\");\n    (\"content-location\", \"\");\n    (\"content-range\", \"\");\n    (\"content-type\", \"\");\n    (\"cookie\", \"\");\n    (\"date\", \"\");\n    (\"etag\", \"\");\n    (\"expect\", \"\");\n    (\"expires\", \"\");\n    (\"from\", \"\");\n    (\"host\", \"\");\n    (\"if-match\", \"\");\n    (\"if-modified-since\", \"\");\n    (\"if-none-match\", \"\");\n    (\"if-range\", \"\");\n    (\"if-unmodified-since\", \"\");\n    (\"last-modified\", \"\");\n    (\"link\", \"\");\n    (\"location\", \"\");\n    (\"max-forwards\", \"\");\n    (\"proxy-authenticate\", \"\");\n    (\"proxy-authorization\", \"\");\n    (\"range\", \"\");\n    (\"referer\", \"\");\n    (\"refresh\", \"\");\n    (\"retry-after\", \"\");\n    (\"server\", \"\");\n    (\"set-cookie\", \"\");\n    (\"strict-transport-security\", \"\");\n    (\"transfer-encoding\", \"\");\n    (\"user-agent\", \"\");\n    (\"vary\", \"\");\n    (\"via\", \"\");\n    (\"www-authenticate\", \"\")].\n\n(* https://tools.ietf.org/html/rfc7541#section-2.3.3 *)\nDefinition index_into_tables `{Monad Err} `{MonadExc HPACKError Err} (i:N)\n           (dynamic_table:DTable) : Err HeaderField :=\n  if i =? 0 then raise (IndexOverrun i)\n  else if i <=? N.of_nat (length static_table)\n       then opt_err (IndexOverrun i)\n                    (nth_error static_table (N.to_nat i))\n       else opt_err (IndexOverrun i)\n                    (nth_error (snd dynamic_table)\n                               (N.to_nat i - (length static_table + 1))%nat).\n\n(* https://tools.ietf.org/html/rfc7541#section-2.3.2 *)\n(* https://tools.ietf.org/html/rfc7541#section-2.3.3 *)\nDefinition eqb_hf (s1 s2:HeaderField) : bool :=\n  match s1, s2 with\n  | (fs1, ss1), (fs2, ss2) => andb (if string_dec fs1 fs2 then true else false)\n                                  (if string_dec ss1 ss2 then true else false)\n  end.\n\nDefinition find_table (h:HeaderField) (t:Table) : option N :=\n  let fix loop i l :=\n      match l with\n      | [] => None\n      | a :: tl =>\n        if eqb_hf h a then Some i else loop (N.succ i) (tl)\n      end in\n  loop 1 t.\n\n(* The size of an entry is the sum of its name's length in octets (as defined in\n   https://tools.ietf.org/html/rfc7541#section-5.2), its value's length in\n   octets, and 32. *)\nDefinition size_hf (hf:HeaderField) : N :=\n  N.of_nat (String.length (fst hf)) + 32.\n\n(* https://tools.ietf.org/html/rfc7541#section-4.1 *)\nDefinition size_dtable (dynamic_table:DTable) : N :=\n  fold_left N.add (map size_hf (snd dynamic_table)) 0.\n\n\n(* https://tools.ietf.org/html/rfc7541#section-4.3 *)\n(* https://tools.ietf.org/html/rfc7541#section-4.4 *)\nLemma removelast_decreasing : forall A (l:list A),\n    l <> [] -> (length (removelast l) < length l)%nat.\nProof.\n  intros. specialize exists_last with (l:=l); intros exists_last.\n  apply exists_last in H. inversion H. inversion X. rewrite H0.\n    rewrite removelast_app; try congruence. simpl. repeat rewrite app_length.\n    simpl. rewrite PeanoNat.Nat.add_0_r. rewrite PeanoNat.Nat.add_1_r.\n    apply PeanoNat.Nat.lt_succ_diag_r.\nQed.\n\nProgram Fixpoint dtable_entry_eviction (dynamic_table:DTable)\n        {measure (length (snd dynamic_table))}: DTable :=\n  match size_dtable dynamic_table <=? fst (fst dynamic_table) with\n  | true => dynamic_table\n  | false => dtable_entry_eviction (fst dynamic_table,\n                                   removelast (snd dynamic_table))\n  end.\nObligation 1.\n  symmetry in Heq_anonymous; rewrite N.leb_gt in Heq_anonymous.\n  destruct dynamic_table; destruct t.\n  - simpl in *. compute in Heq_anonymous. destruct p; destruct n; inversion Heq_anonymous.\n  - cut (snd (p, h :: t) <> []); intros; try solve [simpl; congruence].\n    apply removelast_decreasing; auto.\nDefined.\n\nDefinition change_dtable_size (i:N) (dynamic_table:DTable) : DTable :=\n  dtable_entry_eviction (i, snd (fst dynamic_table), snd dynamic_table).\n\nDefinition cons_dtable (entry:HeaderField) (dynamic_table:DTable) : DTable :=\n  (fst dynamic_table, entry :: snd dynamic_table).\n\nDefinition add_dtable_entry (dynamic_table:DTable) (entry:HeaderField)\n  : DTable :=\n  (* First, evict entries so that the table can add the entry (removes elements\n     if table is non empty and adding element pushes table over max size), add\n     entry to table, and finally evict entries if table is now too large\n     (removes just entry added only when entry is larger than max table size) *)\n  let evict1 := change_dtable_size (fst (fst dynamic_table) - size_hf entry)\n                                   dynamic_table in\n  (change_dtable_size (fst (fst dynamic_table))) (cons_dtable entry evict1).\n\n(* Maps an ascii (+ 256) to a huffman encoded binary number *)\nDefinition huffman_table : list (N * list bool) :=\n  [ ( 0, [true;true;true;true;true;true;true;true;true;true;false;false;false]);\n      ( 1, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;false;false;false]);\n      ( 2, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;true;false]);\n      ( 3, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;true;true]);\n      ( 4, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;false;false]);\n      ( 5, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;false;true]);\n      ( 6, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;true;false]);\n      ( 7, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;true;true]);\n      ( 8, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;false;false]);\n      ( 9, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;true;false]);\n      (10, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false]);\n      (11, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;false;true]);\n      (12, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;true;false]);\n      (13, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true]);\n      (14, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;true;true]);\n      (15, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;false;false]);\n      (16, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;false;true]);\n      (17, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;true;false]);\n      (18, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;true;true]);\n      (19, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;false]);\n      (20, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;true]);\n      (21, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;false]);\n      (22, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false]);\n      (23, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;true]);\n      (24, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;false]);\n      (25, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;true]);\n      (26, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;false]);\n      (27, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;true]);\n      (28, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false]);\n      (29, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true]);\n      (30, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false]);\n      (31, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true]);\n      (32, [false;true;false;true;false;false]);\n      (33, [true;true;true;true;true;true;true;false;false;false]);\n      (34, [true;true;true;true;true;true;true;false;false;true]);\n      (35, [true;true;true;true;true;true;true;true;true;false;true;false]);\n      (36, [true;true;true;true;true;true;true;true;true;true;false;false;true]);\n      (37, [false;true;false;true;false;true]);\n      (38, [true;true;true;true;true;false;false;false]);\n      (39, [true;true;true;true;true;true;true;true;false;true;false]);\n      (40, [true;true;true;true;true;true;true;false;true;false]);\n      (41, [true;true;true;true;true;true;true;false;true;true]);\n      (42, [true;true;true;true;true;false;false;true]);\n      (43, [true;true;true;true;true;true;true;true;false;true;true]);\n      (44, [true;true;true;true;true;false;true;false]);\n      (45, [false;true;false;true;true;false]);\n      (46, [false;true;false;true;true;true]);\n      (47, [false;true;true;false;false;false]);\n      (48, [false;false;false;false;false]);\n      (49, [false;false;false;false;true]);\n      (50, [false;false;false;true;false]);\n      (51, [false;true;true;false;false;true]);\n      (52, [false;true;true;false;true;false]);\n      (53, [false;true;true;false;true;true]);\n      (54, [false;true;true;true;false;false]);\n      (55, [false;true;true;true;false;true]);\n      (56, [false;true;true;true;true;false]);\n      (57, [false;true;true;true;true;true]);\n      (58, [true;false;true;true;true;false;false]);\n      (59, [true;true;true;true;true;false;true;true]);\n      (60, [true;true;true;true;true;true;true;true;true;true;true;true;true;false;false]);\n      (61, [true;false;false;false;false;false]);\n      (62, [true;true;true;true;true;true;true;true;true;false;true;true]);\n      (63, [true;true;true;true;true;true;true;true;false;false]);\n      (64, [true;true;true;true;true;true;true;true;true;true;false;true;false]);\n      (65, [true;false;false;false;false;true]);\n      (66, [true;false;true;true;true;false;true]);\n      (67, [true;false;true;true;true;true;false]);\n      (68, [true;false;true;true;true;true;true]);\n      (69, [true;true;false;false;false;false;false]);\n      (70, [true;true;false;false;false;false;true]);\n      (71, [true;true;false;false;false;true;false]);\n      (72, [true;true;false;false;false;true;true]);\n      (73, [true;true;false;false;true;false;false]);\n      (74, [true;true;false;false;true;false;true]);\n      (75, [true;true;false;false;true;true;false]);\n      (76, [true;true;false;false;true;true;true]);\n      (77, [true;true;false;true;false;false;false]);\n      (78, [true;true;false;true;false;false;true]);\n      (79, [true;true;false;true;false;true;false]);\n      (80, [true;true;false;true;false;true;true]);\n      (81, [true;true;false;true;true;false;false]);\n      (82, [true;true;false;true;true;false;true]);\n      (83, [true;true;false;true;true;true;false]);\n      (84, [true;true;false;true;true;true;true]);\n      (85, [true;true;true;false;false;false;false]);\n      (86, [true;true;true;false;false;false;true]);\n      (87, [true;true;true;false;false;true;false]);\n      (88, [true;true;true;true;true;true;false;false]);\n      (89, [true;true;true;false;false;true;true]);\n      (90, [true;true;true;true;true;true;false;true]);\n      (91, [true;true;true;true;true;true;true;true;true;true;false;true;true]);\n      (92, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;false]);\n      (93, [true;true;true;true;true;true;true;true;true;true;true;false;false]);\n      (94, [true;true;true;true;true;true;true;true;true;true;true;true;false;false]);\n      (95, [true;false;false;false;true;false]);\n      (96, [true;true;true;true;true;true;true;true;true;true;true;true;true;false;true]);\n      (97, [false;false;false;true;true]);\n      (98, [true;false;false;false;true;true]);\n      (99, [false;false;true;false;false]);\n      (100, [true;false;false;true;false;false]);\n      (101, [false;false;true;false;true]);\n      (102, [true;false;false;true;false;true]);\n      (103, [true;false;false;true;true;false]);\n      (104, [true;false;false;true;true;true]);\n      (105, [false;false;true;true;false]);\n      (106, [true;true;true;false;true;false;false]);\n      (107, [true;true;true;false;true;false;true]);\n      (108, [true;false;true;false;false;false]);\n      (109, [true;false;true;false;false;true]);\n      (110, [true;false;true;false;true;false]);\n      (111, [false;false;true;true;true]);\n      (112, [true;false;true;false;true;true]);\n      (113, [true;true;true;false;true;true;false]);\n      (114, [true;false;true;true;false;false]);\n      (115, [false;true;false;false;false]);\n      (116, [false;true;false;false;true]);\n      (117, [true;false;true;true;false;true]);\n      (118, [true;true;true;false;true;true;true]);\n      (119, [true;true;true;true;false;false;false]);\n      (120, [true;true;true;true;false;false;true]);\n      (121, [true;true;true;true;false;true;false]);\n      (122, [true;true;true;true;false;true;true]);\n      (123, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;false]);\n      (124, [true;true;true;true;true;true;true;true;true;false;false]);\n      (125, [true;true;true;true;true;true;true;true;true;true;true;true;false;true]);\n      (126, [true;true;true;true;true;true;true;true;true;true;true;false;true]);\n      (127, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false]);\n      (128, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;true;false]);\n      (129, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;false;true;false]);\n      (130, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;true;true]);\n      (131, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;false;false]);\n      (132, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;false;true;true]);\n      (133, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;true;false;false]);\n      (134, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;true;false;true]);\n      (135, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;false;false;true]);\n      (136, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;true;true;false]);\n      (137, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;false;true;false]);\n      (138, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;false;true;true]);\n      (139, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;true;false;false]);\n      (140, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;true;false;true]);\n      (141, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;true;true;false]);\n      (142, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;true;true]);\n      (143, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;true;true;true]);\n      (144, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;false;false]);\n      (145, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;false;true]);\n      (146, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;true;true;true]);\n      (147, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;false;false]);\n      (148, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;true;false]);\n      (149, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;false;true]);\n      (150, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;true;false]);\n      (151, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;true;true]);\n      (152, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;false;false]);\n      (153, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;true;false;false]);\n      (154, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;false;false;false]);\n      (155, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;false;true]);\n      (156, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;false;false;true]);\n      (157, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;true;false]);\n      (158, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;true;true]);\n      (159, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;true;true]);\n      (160, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;false;true;false]);\n      (161, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;true;false;true]);\n      (162, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;false;true]);\n      (163, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;false;true;true]);\n      (164, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;true;false;false]);\n      (165, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;false;false]);\n      (166, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;false;true]);\n      (167, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;true;true;false]);\n      (168, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;true;false]);\n      (169, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;true;false;true]);\n      (170, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;true;true;false]);\n      (171, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;false]);\n      (172, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;true;true;true]);\n      (173, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;true;true;true]);\n      (174, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;true;true]);\n      (175, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;false;false]);\n      (176, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;false;false]);\n      (177, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;false;true]);\n      (178, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;false;false]);\n      (179, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;true;false]);\n      (180, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;false;true]);\n      (181, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;false;true]);\n      (182, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;true;false]);\n      (183, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;true;true]);\n      (184, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;true;false]);\n      (185, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;true;false]);\n      (186, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;true;true]);\n      (187, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;false;false]);\n      (188, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;false]);\n      (189, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;false;true]);\n      (190, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;true;false]);\n      (191, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;true]);\n      (192, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;false;false]);\n      (193, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;false;true]);\n      (194, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;true;true]);\n      (195, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;true]);\n      (196, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;true;true]);\n      (197, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;false]);\n      (198, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;false;false]);\n      (199, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;false;false]);\n      (200, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;true;false]);\n      (201, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;true;true]);\n      (202, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;false;false]);\n      (203, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;true;true;false]);\n      (204, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;true;true;true]);\n      (205, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;false;true]);\n      (206, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;true]);\n      (207, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;false;true]);\n      (208, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;false]);\n      (209, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;true;true]);\n      (210, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;true;false]);\n      (211, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;false;false]);\n      (212, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;false;true]);\n      (213, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;true;true]);\n      (214, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;true;false]);\n      (215, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;false]);\n      (216, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;false;false]);\n      (217, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;false;true]);\n      (218, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;false;false]);\n      (219, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;false;true]);\n      (220, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true]);\n      (221, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;true;true]);\n      (222, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;false;false]);\n      (223, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;false;true]);\n      (224, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;false;false]);\n      (225, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;true]);\n      (226, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;false;true]);\n      (227, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;true;false]);\n      (228, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;false;true]);\n      (229, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;true;true]);\n      (230, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;false;false]);\n      (231, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;true]);\n      (232, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;true;false]);\n      (233, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;true;true]);\n      (234, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;true;false]);\n      (235, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;true;true]);\n      (236, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;false]);\n      (237, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;true]);\n      (238, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;true;false]);\n      (239, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;false]);\n      (240, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;true;true]);\n      (241, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;true;false]);\n      (242, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;false;false]);\n      (243, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;false;true]);\n      (244, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;true;true;true]);\n      (245, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;false;false]);\n      (246, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;false;true]);\n      (247, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;true;false]);\n      (248, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;false;true;true]);\n      (249, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false]);\n      (250, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;false;false]);\n      (251, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;false;true]);\n      (252, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;true;false]);\n      (253, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;true;true]);\n      (254, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;false;false;false]);\n      (255, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;false;true;true;true;false]);\n      (256, [true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true;true])].\n", "meta": {"author": "liyishuai", "repo": "coq-http2", "sha": "23a08abb61f159c38765a71db7a550d4c4e4a920", "save_path": "github-repos/coq/liyishuai-coq-http2", "path": "github-repos/coq/liyishuai-coq-http2/coq-http2-23a08abb61f159c38765a71db7a550d4c4e4a920/src/HPACK/HPACKTables.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.25655413030316987}}
{"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 PBFTprops2.\nRequire Export PBFTtactics.\nRequire Export PBFTwf_prepared_info.\nRequire Export PBFTordering.\nRequire Export PBFTtactics3.\n\nRequire Export List.\nRequire Export Peano.\n\n\nSection PBFTwf_checkpoint_state.\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  Definition wf_checkpoint_entry_same_seq_and_digest (entry : PBFTcheckpointEntry) : bool :=\n    forallb\n      (fun c =>\n         (same_seq_nums (cp_sn entry) (checkpoint2seq c))\n           && (same_digests (cp_d entry) (checkpoint2digest c)))\n      (cp_checkpoint entry).\n\n  Definition wf_checkpoint_entry_no_repeats (entry : PBFTcheckpointEntry) : bool :=\n    norepeatsb rep_deq (map checkpoint2sender (cp_checkpoint entry)).\n\n  Definition wf_checkpoint_entry (entry : PBFTcheckpointEntry) : bool :=\n    (wf_checkpoint_entry_same_seq_and_digest entry)\n      && (wf_checkpoint_entry_no_repeats entry).\n\n  Definition wf_stable_checkpoint_entry_same_seq_and_digest (entry : PBFTstableCheckpointEntry) : bool :=\n    forallb\n      (fun c =>\n         (same_seq_nums (scp_sn entry) (checkpoint2seq c))\n           && (same_digests (scp_d entry) (checkpoint2digest c)))\n      (scp_checkpoint entry).\n\n  Definition wf_stable_checkpoint_entry_no_repeats (entry : PBFTstableCheckpointEntry) : bool :=\n    norepeatsb rep_deq (map checkpoint2sender (scp_checkpoint entry)).\n\n  Definition wf_stable_checkpoint_entry (entry : PBFTstableCheckpointEntry) : bool :=\n    (wf_stable_checkpoint_entry_same_seq_and_digest entry)\n      && (wf_stable_checkpoint_entry_no_repeats entry).\n\n  Fixpoint wf_checkpoint_log (s : PBFTcheckpoint_log) : bool :=\n    match s with\n    | [] => true\n    | entry :: entries => wf_checkpoint_entry entry && wf_checkpoint_log entries\n    end.\n\n  Definition wf_stable_checkpoint (entry : PBFTstableCheckpointEntry) : bool :=\n    (* either the initial stable checkpoint *)\n    (length (scp_checkpoint entry) =? 0)\n    ||\n    (* or a stable checkpoint *)\n    ((F + 1) <=? length (scp_checkpoint entry)).\n\n  Definition wf_checkpoint_state (s : PBFTcheckpointState) : bool :=\n    (wf_stable_checkpoint_entry (chk_state_stable s))\n      && (wf_stable_checkpoint  (chk_state_stable s))\n      && (wf_checkpoint_log (chk_state_others s)).\n\n  Lemma check_send_replies_preserves_cp_state :\n    forall i v keys giop s1 n msgs s2,\n      check_send_replies i v keys giop s1 n = (msgs, s2)\n      -> cp_state s2 = cp_state s1.\n  Proof.\n    introv check; unfold check_send_replies in check; smash_pbft.\n    destruct x; simpl in *; smash_pbft.\n  Qed.\n\n  Lemma check_send_replies_update_log_preserves_wf_checkpoint_state :\n    forall i v keys giop s1 L n msgs s2,\n      check_send_replies i v keys giop (update_log s1 L) n = (msgs, s2)\n      -> wf_checkpoint_state (cp_state s1) = true\n      -> wf_checkpoint_state (cp_state s2) = true.\n  Proof.\n    introv check wf.\n    apply check_send_replies_preserves_cp_state in check; simpl in check.\n    allrw; tcsp.\n  Qed.\n  Hint Resolve check_send_replies_update_log_preserves_wf_checkpoint_state : pbft.\n\n  Definition wf_checkpoint_entry_op (eop : option PBFTcheckpointEntry) : bool :=\n    match eop with\n    | Some entry => wf_checkpoint_entry entry\n    | None => true\n    end.\n\n  Lemma implies_wf_checkpoint_log_trim_checkpoint_log :\n    forall n L,\n      wf_checkpoint_log L = true\n      -> wf_checkpoint_log (trim_checkpoint_log n L) = true.\n  Proof.\n    induction L; introv wf; simpl in *; tcsp; smash_pbft.\n  Qed.\n  Hint Resolve implies_wf_checkpoint_log_trim_checkpoint_log : pbft.\n\n  Lemma is_stable_checkpoint_entry_implies_wf_stable_checkpoint :\n    forall e se,\n      is_stable_checkpoint_entry e = true\n      -> checkpoint_entry2stable e = Some se\n      -> wf_stable_checkpoint se = true.\n  Proof.\n    introv h check; unfold is_stable_checkpoint_entry in h.\n    destruct e; simpl in *; smash_pbft.\n    unfold wf_stable_checkpoint; smash_pbft.\n  Qed.\n  Hint Resolve is_stable_checkpoint_entry_implies_wf_stable_checkpoint : pbft.\n\n  Lemma checkpoint_entry2stable_implies_wf_stable_checkpoint_entry :\n    forall e se,\n      checkpoint_entry2stable e = Some se\n      -> wf_checkpoint_entry e = true\n      -> wf_stable_checkpoint_entry se = true.\n  Proof.\n    introv check wf.\n    destruct e; simpl in *; smash_pbft.\n  Qed.\n  Hint Resolve checkpoint_entry2stable_implies_wf_stable_checkpoint_entry : pbft.\n\n  Lemma check_stable_preserves_wf_checkpoint_state :\n    forall i s1 e s2,\n      check_stable i s1 e = Some s2\n      -> wf_checkpoint_entry e = true\n      -> wf_checkpoint_state (cp_state s1) = true\n      -> wf_checkpoint_state (cp_state s2) = true.\n  Proof.\n    introv check wf1 wf2.\n    unfold check_stable in check; smash_pbft.\n    unfold wf_checkpoint_state; simpl; smash_pbft; dands; eauto 3 with pbft.\n    apply implies_wf_checkpoint_log_trim_checkpoint_log; tcsp.\n    unfold wf_checkpoint_state in *.\n    allrw andb_true; tcsp.\n  Qed.\n  Hint Resolve check_stable_preserves_wf_checkpoint_state : pbft.\n\n  Lemma same_seq_nums_same :\n    forall n, same_seq_nums n n = true.\n  Proof.\n    introv; unfold same_seq_nums; smash_pbft.\n  Qed.\n  Hint Resolve same_seq_nums_same : pbft.\n  Hint Rewrite same_seq_nums_same : pbft.\n\n  Lemma same_digests_same :\n    forall d, same_digests d d = true.\n  Proof.\n    introv; unfold same_digests; smash_pbft.\n  Qed.\n  Hint Resolve same_digests_same : pbft.\n  Hint Rewrite same_digests_same : pbft.\n\n  Lemma in_sender_of_add_checkpoint2checkpoint_implies :\n    forall c l k s,\n      add_checkpoint2checkpoint c l = Some k\n      -> In s (map checkpoint2sender k)\n      -> s = checkpoint2sender c\n         \\/ In s (map checkpoint2sender l).\n  Proof.\n    induction l; introv add i; repeat (simpl in *; tcsp; smash_pbft).\n    repndors; subst; tcsp.\n    pose proof (IHl x s) as q; repeat (autodimp q hyp); tcsp.\n  Qed.\n\n  Lemma add_checkpoint2entry_preserves_wf_checkpoint_entry :\n    forall a c sm lastr x,\n      add_checkpoint2entry a c sm lastr = Some x\n      -> is_checkpoint_for_entry a c = true\n      -> wf_checkpoint_entry a = true\n      -> wf_checkpoint_entry x = true.\n  Proof.\n    introv add isc wf.\n    unfold is_checkpoint_for_entry in isc.\n    unfold similar_sn_and_checkpoint_sn in isc; smash_pbft.\n    destruct a; simpl in *.\n    smash_pbft.\n    unfold wf_checkpoint_entry in *; simpl in *.\n    unfold wf_checkpoint_entry_same_seq_and_digest in *; simpl in *.\n    unfold wf_checkpoint_entry_no_repeats in *; simpl in *.\n    smash_pbft.\n    revert dependent x0.\n    induction cp_checkpoint; introv add; simpl in *; ginv; simpl in *; smash_pbft;\n      dands; tcsp;\n        try (complete (repeat (autodimp IHcp_checkpoint hyp); tcsp; apply IHcp_checkpoint; auto)).\n    eapply in_sender_of_add_checkpoint2checkpoint_implies in i;[|eauto]; tcsp.\n  Qed.\n  Hint Resolve add_checkpoint2entry_preserves_wf_checkpoint_entry : pbft.\n\n  Lemma add_new_checkpoint2cp_log_preserves_wf_checkpoint_entry_op :\n    forall L smstate R c eop K,\n      add_new_checkpoint2cp_log L smstate R c = (eop, K)\n      -> wf_checkpoint_log L = true\n      -> wf_checkpoint_entry_op eop = true.\n  Proof.\n    induction L; introv add wf; simpl in *; tcsp; ginv; smash_pbft.\n\n    unfold wf_checkpoint_entry_op; simpl.\n    unfold wf_checkpoint_entry; simpl.\n    unfold wf_checkpoint_entry_same_seq_and_digest; simpl.\n    unfold wf_checkpoint_entry_no_repeats; simpl.\n    unfold same_seq_nums, same_digests; simpl; smash_pbft.\n  Qed.\n  Hint Resolve add_new_checkpoint2cp_log_preserves_wf_checkpoint_entry_op : pbft.\n\n  Lemma add_new_checkpoint2cp_log_preserves_wf_checkpoint_log :\n    forall L smstate R c eop K,\n      add_new_checkpoint2cp_log L smstate R c = (eop, K)\n      -> wf_checkpoint_log L = true\n      -> wf_checkpoint_log K = true.\n  Proof.\n    induction L; introv add wf; simpl in *; tcsp; ginv; smash_pbft.\n\n    unfold wf_checkpoint_log; simpl.\n    unfold wf_checkpoint_entry; simpl.\n    unfold wf_checkpoint_entry_same_seq_and_digest; simpl.\n    unfold wf_checkpoint_entry_no_repeats; simpl.\n    unfold same_seq_nums, same_digests; simpl; smash_pbft.\n  Qed.\n  Hint Resolve add_new_checkpoint2cp_log_preserves_wf_checkpoint_log : pbft.\n\n  Lemma add_new_checkpoint2cp_state_preserves_wf_checkpoint_entry_op :\n    forall s1 smstate R c eop s2,\n      add_new_checkpoint2cp_state s1 smstate R c = (eop, s2)\n      -> wf_checkpoint_state s1 = true\n      -> wf_checkpoint_entry_op eop = true.\n  Proof.\n    introv add wf.\n    unfold add_new_checkpoint2cp_state in add; smash_pbft.\n    destruct s1; simpl in *.\n    unfold wf_checkpoint_state in *; simpl in *.\n    allrw andb_true; repnd; smash_pbft.\n  Qed.\n  Hint Resolve add_new_checkpoint2cp_state_preserves_wf_checkpoint_entry_op : pbft.\n\n  Lemma add_new_checkpoint2cp_state_preserves_wf_checkpoint_state :\n    forall s1 smstate R c eop s2,\n      add_new_checkpoint2cp_state s1 smstate R c = (eop, s2)\n      -> wf_checkpoint_state s1 = true\n      -> wf_checkpoint_state s2 = true.\n  Proof.\n    introv add wf.\n    unfold add_new_checkpoint2cp_state in add; smash_pbft.\n    destruct s1; simpl in *.\n    unfold wf_checkpoint_state in *; simpl in *; smash_pbft; dands; eauto 3 with pbft.\n  Qed.\n  Hint Resolve add_new_checkpoint2cp_state_preserves_wf_checkpoint_state : pbft.\n\n  Lemma cp_state_decrement_requests_in_progress_if_primary :\n    forall i v s,\n      cp_state (decrement_requests_in_progress_if_primary i v s) = cp_state s.\n  Proof.\n    introv; destruct s; simpl.\n    unfold decrement_requests_in_progress_if_primary; simpl; smash_pbft.\n  Qed.\n  Hint Rewrite cp_state_decrement_requests_in_progress_if_primary : pbft.\n\n  Lemma implies_wf_checkpoint_state_cp_state_decrement_requests_in_progress_if_primary :\n    forall i v s,\n      wf_checkpoint_state (cp_state s) = true\n      -> wf_checkpoint_state (cp_state (decrement_requests_in_progress_if_primary i v s)) = true.\n  Proof.\n    introv wf; smash_pbft.\n  Qed.\n  Hint Resolve implies_wf_checkpoint_state_cp_state_decrement_requests_in_progress_if_primary : pbft.\n\n  Lemma execute_requests_preserves_wf_checkpoint_state :\n    forall R i v keys s1 msgs l s2,\n      execute_requests i v keys s1 R = (msgs, l, s2)\n      -> wf_checkpoint_state (cp_state s1) = true\n      -> wf_checkpoint_state (cp_state s2) = true.\n  Proof.\n    induction R; introv exec wf; simpl in *; smash_pbft.\n    unfold check_broadcast_checkpoint in *; simpl in *; smash_pbft.\n  Qed.\n  Hint Resolve execute_requests_preserves_wf_checkpoint_state : pbft.\n\n  Lemma find_and_execute_requests_preserves_wf_checkpoint_state :\n    forall i v keys s1 msgs s2,\n      find_and_execute_requests i v keys s1 = (msgs, s2)\n      -> wf_checkpoint_state (cp_state s1) = true\n      -> wf_checkpoint_state (cp_state s2) = true.\n  Proof.\n    introv find wf.\n    unfold find_and_execute_requests in find; smash_pbft.\n  Qed.\n  Hint Resolve find_and_execute_requests_preserves_wf_checkpoint_state : pbft.\n\n  Lemma implies_wf_checkpoint_state_trim_checkpoint_state :\n    forall n s,\n      wf_checkpoint_state s = true\n      -> wf_checkpoint_state (trim_checkpoint_state n s) = true.\n  Proof.\n    introv wf; destruct s; simpl in *.\n    unfold wf_checkpoint_state in *; simpl in *; smash_pbft; dands; eauto 3 with pbft.\n  Qed.\n  Hint Resolve implies_wf_checkpoint_state_trim_checkpoint_state : pbft.\n\n(*  Lemma implies_forallb_add_own_checkpoint_to_certificate_true :\n    forall F c C,\n      F c = true\n      -> forallb F C = true\n      -> forallb F (add_own_checkpoint_to_certificate c C) = true.\n  Proof.\n    introv h q; destruct C; simpl in *; smash_pbft.\n  Qed.*)\n\n  Lemma correct_view_change_cert_one_implies_same_seq_nums :\n    forall s v S e,\n      correct_view_change_cert_one s v S e = true\n      -> same_seq_nums s (checkpoint2seq e) = true.\n  Proof.\n    introv cor.\n    unfold correct_view_change_cert_one in cor; smash_pbft.\n  Qed.\n  Hint Resolve correct_view_change_cert_one_implies_same_seq_nums : pbft.\n\n  Definition view_change2digest (vc : ViewChange) : PBFTdigest :=\n    StableChkPt2digest (view_change2stable vc).\n\n  Lemma correct_view_change_cert_one_implies_same_digests :\n    forall s v S e,\n      correct_view_change_cert_one s v S e = true\n      -> same_digests (StableChkPt2digest S) (checkpoint2digest e) = true.\n  Proof.\n    introv cor.\n    unfold correct_view_change_cert_one in cor; smash_pbft.\n    unfold same_digests in *; smash_pbft.\n  Qed.\n  Hint Resolve correct_view_change_cert_one_implies_same_digests : pbft.\n\n  Lemma correct_view_change_implies_all_same_seq_nums :\n    forall v vc,\n      correct_view_change v vc = true\n      -> forallb\n           (fun c =>\n              (same_seq_nums (view_change2seq vc) (checkpoint2seq c))\n                && (same_digests (view_change2digest vc) (checkpoint2digest c)))\n           (view_change2cert vc) = true.\n  Proof.\n    introv cor.\n    unfold correct_view_change in cor; smash_pbft.\n    unfold correct_view_change_cert in *; smash_pbft.\n    allrw forallb_forall.\n    introv xx; apply cor0 in xx; smash_pbft.\n    dands; unfold view_change2digest; eauto 2 with pbft.\n  Qed.\n  Hint Resolve correct_view_change_implies_all_same_seq_nums : pbft.\n\n  Lemma correct_view_change_cert_one_implies_eq_digests :\n    forall s v S e,\n      correct_view_change_cert_one s v S e = true\n      -> StableChkPt2digest S = checkpoint2digest e.\n  Proof.\n    introv cor.\n    unfold correct_view_change_cert_one in cor; smash_pbft.\n    unfold same_digests in *; smash_pbft.\n  Qed.\n  Hint Resolve correct_view_change_cert_one_implies_eq_digests : pbft.\n\n  Lemma extract_seq_and_digest_from_checkpoint_certificate_implies_eq_seq_and_digest :\n    forall vc n d view,\n      extract_seq_and_digest_from_checkpoint_certificate (view_change2cert vc) = Some (n, d)\n      -> correct_view_change view vc = true\n      -> view_change2seq vc = n\n         /\\ view_change2digest vc = d.\n  Proof.\n    introv h cor.\n    destruct vc, v; simpl in *.\n    destruct C; simpl in *; ginv.\n    unfold correct_view_change in cor; simpl in cor.\n    unfold view_change2prep in cor; simpl in cor.\n    allrw andb_true; repnd.\n    unfold correct_view_change_cert, view_change2digest in *; dands; smash_pbft.\n  Qed.\n\n  Lemma correct_view_change_implies_norepeatsb :\n    forall v vc,\n      correct_view_change v vc = true\n      -> norepeatsb rep_deq (map checkpoint2sender (view_change2cert vc)) = true.\n  Proof.\n    introv cor.\n    unfold correct_view_change in cor; smash_pbft.\n    unfold correct_view_change_cert in *; smash_pbft.\n  Qed.\n  Hint Resolve correct_view_change_implies_norepeatsb : pbft.\n\n  Lemma in_senders_implies_contains_our_own_checkpoint_message :\n    forall i l,\n      In i (map checkpoint2sender l)\n      -> contains_our_own_checkpoint_message i l = true.\n  Proof.\n    induction l; introv j; simpl in *; tcsp; repndors; subst; smash_pbft.\n  Qed.\n  Hint Resolve in_senders_implies_contains_our_own_checkpoint_message : pbft.\n\n(*  Lemma implies_norepeatsb_add_own_checkpoint_to_certificate :\n    forall cp l,\n      contains_our_own_checkpoint_message (checkpoint2sender cp) l = false\n      -> norepeatsb rep_deq (map checkpoint2sender l) = true\n      -> norepeatsb rep_deq (map checkpoint2sender (add_own_checkpoint_to_certificate cp l)) = true.\n  Proof.\n    induction l; introv own norep; simpl in *; tcsp; smash_pbft.\n  Qed.\n  Hint Resolve implies_norepeatsb_add_own_checkpoint_to_certificate : pbft.*)\n\n  Lemma correct_view_change_implies_stable :\n    forall v vc,\n      correct_view_change v vc = true\n      -> F + 1 <= length (view_change2cert vc).\n  Proof.\n    introv cor; unfold correct_view_change in cor; smash_pbft.\n    unfold correct_view_change_cert in cor0; smash_pbft.\n  Qed.\n  Hint Resolve correct_view_change_implies_stable : pbft.\n\n  Lemma view_change_cert2max_seq_vc_implies_stable :\n    forall nv n vc,\n      correct_new_view nv = true\n      -> view_change_cert2max_seq_vc (new_view2cert nv) = Some (n, vc)\n      -> F + 1 <= length (view_change2cert vc).\n  Proof.\n    introv cor mseq.\n    apply view_change_cert2_max_seq_vc_some_in in mseq.\n    apply correct_new_view_implies_correct_view_change in mseq; auto; eauto 3 with pbft.\n  Qed.\n  Hint Resolve view_change_cert2max_seq_vc_implies_stable : pbft.\n\n  Lemma update_state_new_view_preserves_wf_checkpoint_state :\n    forall i s1 nv s2 msgs,\n      correct_new_view nv = true\n      -> update_state_new_view i s1 nv = (s2, msgs)\n      -> wf_checkpoint_state (cp_state s1) = true\n      -> wf_checkpoint_state (cp_state s2) = true.\n  Proof.\n    introv cor upd wf.\n    unfold update_state_new_view in upd; smash_pbft.\n    unfold update_checkpoint_from_new_view; smash_pbft;\n      apply implies_wf_checkpoint_state_trim_checkpoint_state.\n\n    - unfold log_checkpoint_cert_from_new_view in *; smash_pbft.\n\n      + unfold update_stable_sp_log; simpl.\n        unfold wf_checkpoint_state in *; smash_pbft.\n        unfold wf_stable_checkpoint in *; smash_pbft.\n        dands; auto; eauto 3 with pbft;[].\n\n        unfold wf_stable_checkpoint_entry; simpl.\n\n        match goal with\n        | [ H : context[view_change_cert2max_seq_vc] |- _ ] => rename H into vcert\n        end.\n        applydup view_change_cert2_max_seq_vc_some_in in vcert.\n        applydup correct_new_view_implies_correct_cert in cor.\n        rewrite forallb_forall in cor0.\n\n        applydup cor0 in vcert0.\n\n        match goal with\n        | [ H : context[extract_seq_and_digest_from_checkpoint_certificate] |- _ ] => rename H into ext\n        end.\n\n        dup ext as ext'.\n        eapply extract_seq_and_digest_from_checkpoint_certificate_implies_eq_seq_and_digest in ext; auto; repnd.\n        subst; eauto 3 with pbft.\n        unfold wf_stable_checkpoint_entry_same_seq_and_digest; simpl.\n        unfold wf_stable_checkpoint_entry_no_repeats; simpl.\n        smash_pbft; dands; eauto 2 with pbft.\n\n      + unfold update_stable_sp_log; simpl.\n        unfold wf_checkpoint_state in *; smash_pbft.\n        unfold wf_stable_checkpoint in *; smash_pbft.\n        dands; auto; eauto 3 with pbft;[].\n        unfold wf_stable_checkpoint_entry; simpl.\n\n        match goal with\n        | [ H : context[view_change_cert2max_seq_vc] |- _ ] => rename H into vcert\n        end.\n\n        match goal with\n        | [ H : context[extract_seq_and_digest_from_checkpoint_certificate] |- _ ] => rename H into ext\n        end.\n\n        applydup sn_of_view_change_cert2max_seq_vc in vcert; subst.\n\n        applydup view_change_cert2_max_seq_vc_some_in in vcert.\n        applydup correct_new_view_implies_correct_cert in cor.\n        rewrite forallb_forall in cor0.\n\n        applydup cor0 in vcert0.\n\n        dup ext as ext'.\n        eapply extract_seq_and_digest_from_checkpoint_certificate_implies_eq_seq_and_digest in ext; auto; repnd.\n        subst.\n\n        unfold wf_stable_checkpoint_entry_same_seq_and_digest,\n        wf_stable_checkpoint_entry_no_repeats; simpl; smash_pbft;\n          dands; eauto 3 with pbft;\n            eapply correct_view_change_implies_all_same_seq_nums; eauto.\n\n    - unfold log_checkpoint_cert_from_new_view in *; smash_pbft.\n\n      + unfold update_stable_sp_log; simpl.\n        unfold wf_checkpoint_state in *; smash_pbft.\n        unfold wf_stable_checkpoint in *; smash_pbft.\n        dands; auto; eauto 3 with pbft;[].\n        unfold wf_stable_checkpoint_entry; simpl.\n\n        match goal with\n        | [ H : context[view_change_cert2max_seq_vc] |- _ ] => rename H into vcert\n        end.\n        applydup view_change_cert2_max_seq_vc_some_in in vcert.\n        applydup correct_new_view_implies_correct_cert in cor.\n        rewrite forallb_forall in cor0.\n\n        applydup cor0 in vcert0.\n\n        match goal with\n        | [ H : context[extract_seq_and_digest_from_checkpoint_certificate] |- _ ] => rename H into ext\n        end.\n\n        dup ext as ext'.\n        eapply extract_seq_and_digest_from_checkpoint_certificate_implies_eq_seq_and_digest in ext; auto; repnd.\n        subst; eauto 3 with pbft.\n        unfold wf_stable_checkpoint_entry_same_seq_and_digest; simpl.\n        unfold wf_stable_checkpoint_entry_no_repeats; simpl.\n        smash_pbft; dands; eauto 2 with pbft.\n\n      + unfold update_stable_sp_log; simpl.\n        unfold wf_checkpoint_state in *; smash_pbft.\n        unfold wf_stable_checkpoint in *; smash_pbft.\n        dands; auto; eauto 3 with pbft;[].\n        unfold wf_stable_checkpoint_entry; simpl.\n\n        match goal with\n        | [ H : context[view_change_cert2max_seq_vc] |- _ ] => rename H into vcert\n        end.\n\n        match goal with\n        | [ H : context[extract_seq_and_digest_from_checkpoint_certificate] |- _ ] => rename H into ext\n        end.\n\n        applydup sn_of_view_change_cert2max_seq_vc in vcert; subst.\n\n        applydup view_change_cert2_max_seq_vc_some_in in vcert.\n        applydup correct_new_view_implies_correct_cert in cor.\n        rewrite forallb_forall in cor0.\n\n        applydup cor0 in vcert0.\n\n        dup ext as ext'.\n        eapply extract_seq_and_digest_from_checkpoint_certificate_implies_eq_seq_and_digest in ext; auto; repnd.\n        subst.\n        unfold wf_stable_checkpoint_entry_same_seq_and_digest; simpl.\n        unfold wf_stable_checkpoint_entry_no_repeats; simpl.\n        smash_pbft; dands; eauto 3 with pbft;\n          eapply correct_view_change_implies_all_same_seq_nums; eauto.\n  Qed.\n  Hint Resolve update_state_new_view_preserves_wf_checkpoint_state : pbft.\n\n  Lemma add_prepares_to_log_from_new_view_pre_prepares_preserves_cp_state :\n    forall i L s1 s2 msgs,\n      add_prepares_to_log_from_new_view_pre_prepares i s1 L = (s2, msgs)\n      -> cp_state s2 = cp_state s1.\n  Proof.\n    induction L; introv add; simpl in *; smash_pbft.\n    match goal with\n    | [ H : context[add_prepares_to_log_from_new_view_pre_prepares] |- _ ] =>\n      apply IHL in H; allrw\n    end.\n\n    unfold add_prepare_to_log_from_new_view_pre_prepare in *; smash_pbft.\n\n    match goal with\n    | [ H : context[check_send_replies] |- _ ] =>\n      apply check_send_replies_preserves_cp_state in H\n    end.\n    allrw; simpl; auto.\n  Qed.\n\n  Lemma add_prepares_to_log_from_new_view_pre_prepares_preserves_wf_checkpoint_state :\n    forall i L s1 s2 msgs,\n      add_prepares_to_log_from_new_view_pre_prepares i s1 L = (s2, msgs)\n      -> wf_checkpoint_state (cp_state s1) = true\n      -> wf_checkpoint_state (cp_state s2) = true.\n  Proof.\n    introv add wf.\n    apply add_prepares_to_log_from_new_view_pre_prepares_preserves_cp_state in add.\n    allrw; auto.\n  Qed.\n  Hint Resolve add_prepares_to_log_from_new_view_pre_prepares_preserves_wf_checkpoint_state : pbft.\n\n  Lemma wf_checkpoint_state_check_one_stable :\n    forall i s l,\n      wf_checkpoint_state (cp_state s) = true\n      -> wf_checkpoint_log l = true\n      -> wf_checkpoint_state (cp_state (check_one_stable i s l)) = true.\n  Proof.\n    induction l; introv wf1 wf2; simpl in *; smash_pbft.\n  Qed.\n  Hint Resolve wf_checkpoint_state_check_one_stable : pbft.\n\n  Lemma wf_checkpoint_state_implies_wf_checkpoint_log :\n    forall s,\n      wf_checkpoint_state s = true\n      -> wf_checkpoint_log (chk_state_others s) = true.\n  Proof.\n    introv wf.\n    unfold wf_checkpoint_state in wf; smash_pbft.\n  Qed.\n  Hint Resolve wf_checkpoint_state_implies_wf_checkpoint_log : pbft.\n\n  Lemma implies_wf_checkpoint_state_cp_state_log_new_view_state :\n    forall s nv,\n      wf_checkpoint_state (cp_state s) = true\n      -> wf_checkpoint_state (cp_state (log_new_view_state s nv)) = true.\n  Proof.\n    tcsp.\n  Qed.\n  Hint Resolve implies_wf_checkpoint_state_cp_state_log_new_view_state : pbft.\n\n  Lemma implies_wf_checkpoint_state_cp_state :\n    forall s v,\n      wf_checkpoint_state (cp_state s) = true\n      -> wf_checkpoint_state (cp_state (update_view s v)) = true.\n  Proof.\n    tcsp.\n  Qed.\n  Hint Resolve implies_wf_checkpoint_state_cp_state : pbft.\n\n  Lemma wf_checkpoint_state_state_preserved_on_event :\n    forall (eo  : EventOrdering)\n           (e   : Event)\n           (slf : Rep)\n           (st  : PBFTstate),\n      state_sm_on_event (PBFTreplicaSM slf) e = Some st\n      -> wf_checkpoint_state (cp_state st) = true.\n  Proof.\n    prove_by_ind ind h eqst sop p m eqtrig trig smash_handlers3 smash_pbft_ind6_7.\n  Qed.\n\n  Lemma wf_checkpoint_state_state_preserved_before_event :\n    forall (eo  : EventOrdering)\n           (e   : Event)\n           (slf : Rep)\n           (st  : PBFTstate),\n      state_sm_before_event (PBFTreplicaSM slf) e = Some st\n      -> wf_checkpoint_state (cp_state st) = true.\n  Proof.\n    introv eqst.\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 *;tcsp;[].\n    eapply wf_checkpoint_state_state_preserved_on_event in eqst; eauto.\n  Qed.\n\nEnd PBFTwf_checkpoint_state.\n\n\nHint Resolve check_send_replies_update_log_preserves_wf_checkpoint_state : pbft.\nHint Resolve wf_checkpoint_state_state_preserved_on_event : pbft.\nHint Resolve wf_checkpoint_state_state_preserved_before_event : pbft.\nHint Resolve correct_view_change_cert_one_implies_same_seq_nums : pbft.\nHint Resolve correct_view_change_cert_one_implies_same_digests : pbft.\nHint Resolve correct_view_change_implies_all_same_seq_nums : pbft.\nHint Resolve correct_view_change_cert_one_implies_eq_digests : pbft.\nHint Resolve same_seq_nums_same : pbft.\nHint Resolve same_digests_same : pbft.\nHint Resolve in_senders_implies_contains_our_own_checkpoint_message : pbft.\n(*Hint Resolve implies_norepeatsb_add_own_checkpoint_to_certificate : pbft.*)\nHint Resolve is_stable_checkpoint_entry_implies_wf_stable_checkpoint : pbft.\nHint Resolve correct_view_change_implies_stable : pbft.\nHint Resolve view_change_cert2max_seq_vc_implies_stable : pbft.\nHint Resolve checkpoint_entry2stable_implies_wf_stable_checkpoint_entry : pbft.\nHint Resolve wf_checkpoint_state_check_one_stable : pbft.\nHint Resolve wf_checkpoint_state_implies_wf_checkpoint_log : pbft.\n\n\nHint Rewrite @same_seq_nums_same : pbft.\nHint Rewrite @same_digests_same : 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/PBFTwf_checkpoint_state.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2565282377574783}}
{"text": "(* Stream programs with blocking pull.\n   No option of pull finished or not, just wait until something new comes along.\n *)\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  (* Pred input_seen input_left output *)\n  (* I don't think predicate needs the peek of the stream before pull *)\n  Definition Pred := list Value -> list Value -> Prop.\n\n  (* No heap or variables, just constant values *)\n  Inductive Block : Type :=\n   (* Pull, ignore value, but note whether something was pulled *)\n   | BlockPull   : Label -> Block\n   (* Push a constant value *)\n   | BlockPush   : Value -> Label -> Block\n   (* Jump to another label without doing anything *)\n   | BlockJump   : Label -> Block.\n  Hint Constructors Block.\n\n  Variable Blocks : Label -> Block.\n  Variable LabelPre  : Label -> Pred.\n\n  Inductive EvalB : list Value -> list Value -> Label\n                 -> list Value -> list Value -> Label -> Prop :=\n   | EvalBPull l lok i iss os\n      : Blocks l = BlockPull lok\n     -> EvalB iss os l\n              (iss++[i])  os lok\n\n   | EvalBPush l push l' iss os\n      : Blocks l = BlockPush push l'\n     -> EvalB iss os l\n              iss (os ++ [push]) l'\n\n   | EvalBJump l l' iss os\n      : Blocks l = BlockJump l'\n     -> EvalB iss os l\n              iss os l'\n   .\n\n  Variable Init : Label.\n  Variable InitPre : LabelPre Init [] [].\n\n  Inductive EvalBs : list Value -> list Value -> Label -> Prop :=\n   | EvalBs0\n      : EvalBs [] [] Init\n   | EvalBs1 l l' iss iss' os os'\n      : EvalBs iss os l\n     -> EvalB  iss os l iss' os' l'\n     -> EvalBs iss' os' l'\n   .\n  Definition BlocksPreT :=\n    forall iss iss' os os' l l',\n    EvalBs iss os l ->\n    LabelPre l iss os ->\n    EvalB  iss os l iss' os' l' ->\n    LabelPre l' iss' os'.\n\n  Hypothesis BlocksPre: BlocksPreT.\n\n  Theorem EvalBs_Hoare l iss os\n   (hEvB : EvalBs iss    os l)\n         : LabelPre l iss os.\n  Proof.\n   !induction hEvB.\n  Qed.\nEnd Machine.\n\nEnd Base.\n\nModule Program.\n Module B := Base.\n Record Program (Label : Set) : Type\n  := mkProgram\n   { Init     : Label\n   ; Blocks   : Label -> B.Block Label\n   ; LabelPre : Label -> B.Pred\n   ; BlocksPre: B.BlocksPreT Blocks LabelPre Init\n   ; InitPre  : LabelPre Init [] []\n   }.\n\n  Definition EvalBs (Label : Set) (P : Program Label)\n   := B.EvalBs (Blocks P) (Init P).\n  (*\n  Ltac Program_Block_destruct p l :=\n    let pre := fresh \"block_pre\" in\n    let eq  := fresh \"block_eq\" in\n    destruct (Blocks p l) eqn:eq;\n    lets pre: (BlocksPre p l);\n    simpl;\n    rewrite eq in *. *)\nEnd Program.\n\n\nModule Fuse.\n  Module B := Base.\n  Module P := Program.\n\n  Parameter L1 : Set.\n  Parameter P1 : P.Program L1.\n\n  Parameter L2 : Set.\n  Parameter P2 : P.Program L2.\n\n  Inductive State :=\n    | Waiting\n    | Ok\n    .\n  Hint Constructors State.\n\n  Inductive L' :=\n    | LX (l1 : L1) (l2 : L2) (s1 : State) (s2 : State).\n  Hint Constructors L'.\n\n  Definition Blocks (l : L') : B.Block L' :=\n   match l with\n   | LX l1 l2 s1 s2\n   => match P.Blocks P1 l1, P.Blocks P2 l2, s1, s2 with\n      (* try to run 1. for most it doesn't matter what state is, *)\n      (* as state can only be 'Waiting' if stuck on a push. *)\n      (* pulling is normal. *)\n      | B.BlockPull lok, _, _, _\n      => B.BlockPull (LX lok l2 Ok s2)\n\n      (* trying to push while in 'Ok' marks this as 'Waiting' for other to pull *)\n      | B.BlockPush _ _, _, Ok, _\n      => B.BlockJump (LX l1 l2 Waiting s2)\n\n      (* jump is normal *)\n      | B.BlockJump l', _, _, _\n      => B.BlockJump (LX l' l2 Ok s2)\n\n\n      (* try to run 2 *)\n      (* pulling while 'Ok' marks as waiting. *)\n      | _, B.BlockPull _, _, Ok\n      => B.BlockJump (LX l1 l2 s1 Waiting)\n\n      (* pushing is normal *)\n      | _, B.BlockPush f l', _, _\n      => B.BlockPush f (LX l1 l' s1 Ok)\n\n      (* jump is normal *)\n      | _, B.BlockJump l', _, _\n      => B.BlockJump (LX l1 l' s1 Ok)\n\n\n      (* Both machines are waiting on other one, so can progress *)\n      | B.BlockPush f1 l1', B.BlockPull lok, Waiting, Waiting\n      => B.BlockJump (LX l1' lok Ok Ok)\n\n      end\n   end.\n\n  Check P.EvalBs.\n  Definition listOfOption (o : option nat) : list nat :=\n  match o with\n  | Some v => [v]\n  | None   => []\n  end.\n  Definition LabelPre (l : L') : B.Pred :=\n   match l with\n   | LX l1 l2 s1 s2\n   => fun iss os\n   => exists (iss' : list nat),\n      P.EvalBs P1 iss  iss' l1\n   /\\ P.EvalBs P2 iss' os l2\n   end.\n  Hint Unfold LabelPre.\n\n\n  Program Definition r := {| P.Blocks := Blocks; P.LabelPre := LabelPre; P.Init := LX (P.Init P1) (P.Init P2) Ok Ok |}.\n  Next Obligation.\n   unfolds B.BlocksPreT.\n   introv hEvBs hLbl hEvB.\n   destruct l; destruct l'.\n   !inverts hEvB; simpls\n  ; destruct (P.Blocks P1 l1) eqn:P1Block\n  ; destruct (P.Blocks P2 l2) eqn:P2Block\n  ; destruct s1; destruct s2\n  ; (!inject_all; simpls; tryfalse)\n  ; try solve [(!jauto_set)\n  ;   (!eapply B.EvalBs1)\n  ;   try solve [!eapply B.EvalBPull]\n  ;   try solve [!eapply B.EvalBPush]\n  ;   try solve [!eapply B.EvalBJump]\n  ].\n  Qed.\n  Next Obligation.\n   jauto_set; eapply B.EvalBs0.\n  Qed.\n\n  Theorem fuse_ok (l1 : L1) (l2 : L2) (s1 s2 : State) iss oss:\n   P.EvalBs r iss oss (LX l1 l2 s1 s2)\n  ->\n   exists (iss' : list nat),\n      P.LabelPre P1 l1 iss  iss' /\\ P.LabelPre P2 l2 iss' oss.\n  Proof.\n   introv hEvBs.\n   apply B.EvalBs_Hoare with (LabelPre := LabelPre) in hEvBs.\n   simpls; jauto_set.\n   !apply B.EvalBs_Hoare with (LabelPre := P.LabelPre P1) in H.\n   apply (P.InitPre P1).\n   apply (P.BlocksPre P1).\n\n   !apply B.EvalBs_Hoare with (LabelPre := P.LabelPre P2) in H0.\n   apply (P.InitPre P2).\n   apply (P.BlocksPre P2).\n\n   apply (P.InitPre r).\n   apply (P.BlocksPre r).\n  Qed.\nEnd Fuse.", "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/HoareGoto4_notsure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2565282320966306}}
{"text": "(* begin hide *)\nRequire Import Psatz.\n\nFrom Coq Require Import\n     Lists.List\n     Strings.String\n     Morphisms\n     ZArith\n     Setoid\n     RelationClasses.\n\nFrom ITree Require Import\n     Basics.Category\n     Basics.HeterogeneousRelations\n     Basics.Monad\n     ITree\n     ITreeMonad\n     ITreeFacts\n     Events.StateFacts\n     Events.MapDefault\n     Events.MapDefaultFacts\n     Events.State.\n\nImport ITreeNotations.\n\nFrom ExtLib Require Import\n     Core.RelDec\n     Structures.Monad\n     Structures.Maps\n     Programming.Show\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\nFrom ITreeTutorial Require Import Fin Asm AsmCombinators Utils_tutorial.\n\n(* end hide *)\n\n(* optimizations ------------------------------------------------------------ *)\n\n(** A (simple) optimization is just a function from asm units to asm units. *)\n\nDefinition optimization {A B} := asm A B -> asm A B.\n\n(** An optimization is correct if it yields an equivalent computation.\n\n    - Note that eq_asm requires that resulting register environment and\n      the resulting heap must be equivalent, so this formulation of\n      correctness does not permit the elimination of local variables or\n      differences in the state.  Those optimizations would require\n      more contextual information.\n*)\n\n(** We define an appropriate notion of equivalence on these state components.\n    This will be useful for defining optimizations at the [Asm] level. *)\n\nDefinition EQ_registers (d:value) (regs1 regs2 : registers) : Prop :=\n  @eq_map _ _ _ _ d regs1 regs2.\n\nGlobal Instance EQ_registers_refl {d} : Reflexive (EQ_registers d).\nunfold EQ_registers. typeclasses eauto.\nQed.\n\nGlobal Instance EQ_registers_sym {d} : Symmetric (EQ_registers d).\nunfold EQ_registers. typeclasses eauto.\nQed.\n\nGlobal Instance EQ_registers_trans {d} : Transitive (EQ_registers d).\nunfold EQ_registers. typeclasses eauto.\nQed.\n\nGlobal Instance EQ_registers_eqv {d} : Equivalence (EQ_registers d).\nconstructor; typeclasses eauto.\nQed.\n\n\n\nDefinition EQ_memory (mem1 mem2 : memory) : Prop :=\n  @eq_map _ _ _ _ 0 mem1 mem2.\n\nGlobal Instance EQ_memory_refl : Reflexive (EQ_memory).\nunfold EQ_memory. typeclasses eauto.\nQed.\n\nGlobal Instance EQ_memory_sym : Symmetric (EQ_memory).\nunfold EQ_memory. typeclasses eauto.\nQed.\n\nGlobal Instance EQ_memory_trans : Transitive (EQ_memory).\nunfold EQ_memory. typeclasses eauto.\nQed.\n\nGlobal Instance EQ_memory_eqv : Equivalence (EQ_memory).\nconstructor; typeclasses eauto.\nQed.\n\nDefinition rel_asm {B} : memory * (registers * B) -> memory * (registers * B) -> Prop :=\n  prod_rel EQ_memory (prod_rel (EQ_registers 0) eq).\n\nGlobal Hint Unfold rel_asm: core.\n\n(** The definition [interp_asm] also induces a notion of equivalence (open)\n    _asm_ programs, which is just the equivalence of the ktree category *)\nDefinition eq_asm_denotations_EQ {E A B} (t1 t2 : Kleisli (itree (Reg +' Memory +' E)) A B) : Prop :=\n  forall a mem1 mem2 regs1 regs2,\n    EQ_memory mem1 mem2 ->\n    EQ_registers 0 regs1 regs2 ->\n    (eutt rel_asm)\n      (interp_asm (t1 a) mem1 regs1)\n      (interp_asm (t2 a) mem2 regs2).\n\nDefinition eq_asm_EQ {E} `{Exit -< E} {A B} (p1 p2 : asm A B) : Prop :=\n  eq_asm_denotations_EQ (E := E) (denote_asm p1) (denote_asm p2).\n\nDefinition optimization_correct {E} `{Exit -< E} A B (opt:optimization) : Prop :=\n  forall (p : asm A B),\n    eq_asm_EQ (E := E) p (opt p).\n\nDefinition EQ_asm {E A} (f g : memory -> registers -> itree E (memory * (registers * A))) : Prop :=\n  forall mem1 mem2 regs1 regs2,\n    EQ_memory mem1 mem2 ->\n    EQ_registers 0 regs1 regs2 ->\n    eutt (@rel_asm A) (f mem1 regs1) (g mem2 regs2).\n\nInfix \"≡\" := EQ_asm (at level 70).\n\nLemma interp_asm_ret_tt {E} : forall (t : itree (Reg +' Memory +' E) unit),\n    (interp_asm t) ≡ (interp_asm (t ;; Ret tt)).\nProof.\n  intros t mem1 mem2 regs1 regs2 H1 H2.\n  rewrite interp_asm_bind.\n  rewrite <- bind_ret_r at 1.\n  apply (@eutt_clo_bind _ _ _ _ _ _ rel_asm).\n  { unfold interp_asm.\n    unfold rel_asm.\n    eapply interp_map_proper; try typeclasses eauto; auto.\n    eapply interp_map_proper; try typeclasses eauto; auto.\n    reflexivity.\n  }\n  intros.\n  destruct H as [J1 [J2 J3]]; subst.\n  unfold interp_asm.\n  unfold interp_map.\n  destruct u2 as [? [? []]].\n  rewrite interp_ret.\n  do 2 rewrite interp_state_ret.\n  apply eqit_Ret. auto.\nQed.\n\nLemma interp_asm_ret {E A} (x:A) mem reg :\n  interp_asm (Ret x) mem reg ≈ (Ret (mem, (reg, x)) : itree E _).\nProof.\n  unfold interp_asm, interp_map.\n  rewrite interp_ret.\n  repeat rewrite interp_state_ret.\n  reflexivity.\nQed.\n\nGlobal Instance rel_asm_eqv :\n  forall A, Equivalence (@rel_asm A).\nProof.\n  intros.\n  unfold rel_asm. eapply prod_rel_eqv; try typeclasses eauto.\nQed.\n\nLemma interp_asm_GetReg {E A} f r mem reg :\n  @eutt E _ _ (@rel_asm A)\n       (interp_asm (val <- trigger (GetReg r) ;; f val) mem reg)\n       ((interp_asm (f (lookup_default r 0 reg))) mem reg).\nProof.\n  unfold interp_asm, interp_map.\n  rewrite interp_bind.\n  setoid_rewrite interp_trigger.\n  repeat rewrite interp_state_bind. cbn.\n  unfold subevent, resum, ReSum_inl, resum, ReSum_id, id_.\n  unfold Id_IFun.\n  unfold CategoryOps.cat, Cat_Handler, Handler.cat. cbn.\n  unfold lookup_def.\n  unfold embed, Embeddable_forall, embed, Embeddable_itree.\n  unfold trigger. rewrite interp_vis. setoid_rewrite interp_ret.\n  unfold subevent, resum.\n  repeat rewrite interp_state_bind.\n  repeat setoid_rewrite interp_state_ret.\n  unfold inl_, Inl_sum1_Handler, Handler.inl_, Handler.htrigger.\n  rewrite interp_state_trigger_eqit. cbn.\n  rewrite !bind_ret_l, !tau_eutt.\n  rewrite interp_state_ret.\n  rewrite !bind_ret_l, !tau_eutt.\n  rewrite !interp_state_ret; cbn.\n  rewrite bind_ret_l; cbn.\n  reflexivity.\nQed.\n\nLemma interp_asm_SetReg {E A} f r v mem reg :\n  @eutt E _ _ (@rel_asm A)\n       (interp_asm (trigger (SetReg r v) ;; f) mem reg)\n       ((interp_asm f) mem (Maps.add r v reg)).\nProof.\n  unfold interp_asm, interp_map.\n  rewrite interp_bind.\n  unfold trigger.\n  rewrite interp_vis.\n  unfold subevent, resum, ReSum_inl, resum, ReSum_id, id_. cbn.\n  setoid_rewrite interp_ret.\n  rewrite bind_bind.\n  setoid_rewrite tau_eutt.\n  setoid_rewrite bind_ret_l.\n  repeat rewrite interp_state_bind.\n  unfold Id_IFun.\n  unfold CategoryOps.cat, Cat_Handler, Handler.cat. cbn.\n  unfold inl_, Inl_sum1_Handler, Handler.inl_, Handler.htrigger.\n  unfold insert.\n  setoid_rewrite interp_trigger.\n  repeat rewrite interp_state_trigger_eqit.  cbn.\n  rewrite bind_ret_l, tau_eutt.\n  setoid_rewrite interp_state_ret.\n  rewrite bind_ret_l. cbn.\n  reflexivity.\nQed.\n\nLemma interp_asm_Load {E A} f a mem reg :\n  @eutt E _ _ (@rel_asm A)\n       (interp_asm (val <- trigger (Load a) ;; f val) mem reg)\n       ((interp_asm (f (lookup_default a 0 mem))) mem reg).\nProof.\n  unfold interp_asm, interp_map.\n  rewrite interp_bind.\n  rewrite interp_trigger.\n  unfold subevent, resum, ReSum_inr, resum, ReSum_inl, resum, ReSum_id, id_. cbn.\n  repeat rewrite interp_state_bind.\n  unfold Id_IFun.\n  unfold CategoryOps.cat, Cat_Handler, Handler.cat. cbn.\n  unfold CategoryOps.cat, Cat_Handler, Handler.cat. cbn.\n  unfold inl_, Inl_sum1_Handler, Handler.inl_, Handler.htrigger.\n  unfold inr_, Inr_sum1_Handler, Handler.inr_, Handler.htrigger.\n  unfold lookup_def.\n  repeat (setoid_rewrite interp_trigger; rewrite tau_eutt).\n  repeat rewrite interp_state_trigger_eqit.\n  cbn. unfold pure_state, embed, Embeddable_forall, embed, Embeddable_itree, trigger.\n  do 2 rewrite interp_vis, bind_vis.\n  rewrite interp_state_vis. cbn. rewrite bind_vis, interp_state_vis. cbn.\n  rewrite !bind_ret_l, !tau_eutt. rewrite !interp_ret, !interp_state_ret.\n  rewrite bind_ret_l; cbn.\n  reflexivity.\nQed.\n\nLemma interp_asm_Store {E A} f a v mem reg :\n  @eutt E _ _ (@rel_asm A)\n       (interp_asm (trigger (Store a v) ;; f) mem reg)\n       ((interp_asm f) (Maps.add a v mem) reg).\nProof.\n  unfold interp_asm, interp_map.\n  rewrite interp_bind.\n  rewrite interp_trigger.\n  unfold subevent, resum, ReSum_inr, resum, ReSum_inl, resum, ReSum_id, id_. cbn.\n  repeat rewrite interp_state_bind.\n  unfold Id_IFun.\n  unfold CategoryOps.cat, Cat_Handler, Handler.cat. cbn.\n  unfold CategoryOps.cat, Cat_Handler, Handler.cat. cbn.\n  unfold inl_, Inl_sum1_Handler, Handler.inl_, Handler.htrigger.\n  unfold inr_, Inr_sum1_Handler, Handler.inr_, Handler.htrigger.\n  unfold insert, embed, Embeddable_forall, embed, Embeddable_itree.\n  rewrite interp_trigger.\n  setoid_rewrite interp_trigger.\n  rewrite interp_state_trigger_eqit. cbn.\n  cbn. unfold pure_state, embed, Embeddable_forall, embed, Embeddable_itree, trigger.\n  rewrite bind_vis, interp_state_vis. cbn. rewrite !bind_ret_l, !tau_eutt.\n  rewrite interp_state_ret, bind_ret_l; cbn.\n  reflexivity.\nQed.\n\nLemma interp_state_iter' {E F } S (f : E ~> Monads.stateT S (itree F)) {I A}\n      (t  : I -> itree E (I + A))\n  : forall i, state_eq (State.interp_state f (ITree.iter t i))\n                       (Basics.iter (fun i => State.interp_state f (t i)) i).\nProof.\n  eapply interp_state_iter.\n  intros i.\n  red. reflexivity.\nQed.\n\n(* peephole optimizations --------------------------------------------------- *)\n\n(** A (simple) peephole optmization transforms one instruction into a\n   (possibly empty) list of equivalent instructions. *)\nDefinition peephole_optimization := instr -> list instr.\n\n(** We lift peephole optimizations to _asm_ pointwise through the structures. *)\nFixpoint peephole_optimize_block {lbl} (ph : peephole_optimization) (b:block lbl) : block lbl :=\n  match b with\n  | bbi i k => blk_append (ph i) (peephole_optimize_block ph k)\n  | bbb l => bbb l\n  end.\n\nDefinition peephole_optimize_bks {A B} (ph : peephole_optimization) (bs : A -> block B) :=\n  fun (a:A) => peephole_optimize_block ph (bs a).\n\nDefinition peephole_optimize_asm {A B} (ph : peephole_optimization) (p : asm A B) : asm A B :=\n  Build_asm A B (p.(internal)) (peephole_optimize_bks ph (p.(code))).\n\n\n(* peephole correctness ----------------------------------------------------- *)\n\nSection Correctness.\n\n  (** A peephole optimizer is correct if it replaces an instruction with\n    a semantically equivalent sequence of instructions. *)\nDefinition ph_correct (ph : peephole_optimization) :=\n  forall E (i:instr),\n    @eq_asm_denotations_EQ E unit _ (fun _ => denote_instr i) (fun _ => denote_list (ph i)).\n\nLemma ph_blk_append_correct {E} {HasExit : Exit -< E} :\n  forall (ph : peephole_optimization) (H : ph_correct ph)\n    lbl1 lbl2 b1 b2 i,\n    (@eq_asm_denotations_EQ E (fin lbl1) (fin lbl2) (fun _ => denote_bk b1) (fun _ => denote_bk b2)) ->\n    (@eq_asm_denotations_EQ E (fin lbl1) (fin lbl2)\n                         (fun _ => denote_instr i ;; denote_bk b1)\n                         (fun _ => denote_bk (blk_append (ph i) b2))).\n  Proof.\n    intros ph H lbl1 lbl2 b1 b2 i HP.\n    unfold eq_asm_denotations_EQ.\n    intros a mem1 mem2 regs1 regs2 EQ_mem EQ_reg.\n    rewrite denote_blk_append.\n    unfold ph_correct in H.\n    unfold eq_asm_denotations_EQ in H.\n    specialize H with (i:=i).\n    pose proof (H E tt) as H2.\n    do 2 rewrite interp_asm_bind.\n    eapply eutt_clo_bind.\n    apply H2; auto.\n    intros.\n    destruct H0 as [J1 [J2 J3]].\n    destruct u1 as [? [? []]], u2 as [? [? []]]. cbn in *.\n    apply HP; auto.\n  Qed.\n\n\nLemma peephole_block_correct {E} {HasExit : Exit -< E} :\n  forall (ph : peephole_optimization)\n    (H : ph_correct ph)\n    (lbl1 lbl2 : nat)\n    (b : block (fin lbl2)),\n    @eq_asm_denotations_EQ E (fin lbl1) (fin lbl2)\n                        (fun _ => denote_bk b)\n                        (fun _ => denote_bk (peephole_optimize_block ph b)).\nProof.\n  intros ph H lbl1 lbl2 b.\n  induction b.\n  - simpl.\n    unfold eq_asm_denotations_EQ.\n    intros.\n    eapply ph_blk_append_correct; try assumption. exact IHb. assumption.\n  - unfold eq_asm_denotations_EQ.\n    intros.\n    destruct b; simpl.\n    + unfold interp_asm.\n      rewrite interp_ret.\n      unfold interp_map.\n      repeat rewrite interp_state_ret.\n      apply eqit_Ret. constructor; auto; constructor; auto.\n    + setoid_rewrite interp_asm_GetReg.\n      rewrite H1.\n      unfold value in *.\n      remember (lookup_default r 0 regs2) as x.\n      destruct x.\n      repeat rewrite interp_asm_ret.\n      apply eqit_Ret. constructor; auto.\n      repeat rewrite interp_asm_ret.\n      apply eqit_Ret. constructor; auto. \n    + unfold interp_asm, interp_map.\n      unfold id_, Id_Handler, Handler.id_.\n      unfold exit.\n      rewrite interp_vis.\n      cbn. rewrite interp_state_bind.\n      unfold CategoryOps.cat, Cat_Handler, Handler.cat, inr_, Inr_sum1_Handler, Handler.inr_, Handler.htrigger.\n      setoid_rewrite interp_trigger.\n      unfold inr_.\n      rewrite interp_trigger.\n      rewrite interp_state_trigger_eqit.\n      rewrite interp_state_bind.\n      cbn. unfold pure_state.\n      rewrite bind_vis, interp_state_vis. cbn.\n      repeat rewrite bind_vis.\n      rewrite interp_state_bind.\n      rewrite interp_state_trigger_eqit. cbn.\n      rewrite !bind_vis, interp_state_vis. cbn.\n      rewrite bind_vis.\n      apply eqit_Vis; intros [].\nQed.\n\n\nLemma peephole_optimization_correct {E} {HasExit : Exit -< E}\n  : forall A B (ph : peephole_optimization) (H : ph_correct ph),\n      optimization_correct (E := E) A B (peephole_optimize_asm ph).\nProof.\n  intros A B ph H.\n  unfold optimization_correct.\n  intros p.\n  unfold eq_asm, eq_asm_denotations, denote_asm.\n  intros a mem1 mem2 regs1 regs2 H1 H2.\n  unfold interp_asm, interp_map.\n  repeat setoid_rewrite interp_bind.\n  repeat rewrite interp_state_bind.\n  apply (@eutt_clo_bind _ _ _ _ _ _ rel_asm).\n\n  { apply (@eutt_clo_bind _ _ _ _ _ _ rel_asm).\n    -  unfold inr_, Inr_Kleisli, lift_ktree_.\n       unfold ret, Monad_itree.\n       repeat rewrite interp_ret.\n       repeat rewrite interp_state_ret.\n       apply eqit_Ret. constructor; auto. \n    -  intros. destruct H0 as [J1 [J2 J3]].\n       subst. cbn.\n       unfold CategorySub.from_bif, FromBifunctor_ktree_fin.\n       repeat rewrite interp_ret.\n       repeat rewrite interp_state_ret.\n       apply eqit_Ret.\n       constructor; cbn; auto. constructor; cbn; auto.\n       rewrite J3. reflexivity. }\n\n  intros.\n  destruct H0 as [J1 [J2 J3]]; subst.\n  simpl in *.\n  unfold denote_bks.\n  unfold iter, CategorySub.Iter_sub.\n  repeat rewrite interp_iter.\n  unfold iter, Iter_Kleisli.\n  cbn.\n  assert (JJ := @interp_state_iter').\n  red in JJ.\n  unfold Basics.iter, MonadIter_stateT0, Basics.iter, MonadIter_itree in *.\n  cbn in *.\n  repeat rewrite JJ.\n\n  eapply eutt_iter' with (RI := rel_asm); cbn; auto.\n  intros j1 j2 [K1 [K2 ->]]; cbn.\n  rewrite !interp_bind, !interp_state_bind, !bind_bind. (* Slow! *)\n\n  apply (@eutt_clo_bind _ _ _ _ _ _ rel_asm);\n    [|intros ? ? [? [? ->]]]; cbn.\n  { refine (peephole_block_correct _ _ _ _ _ _ _ _ _ _ _ _); eauto. }\n\n  unfold CategorySub.to_bif, ToBifunctor_ktree_fin.\n  apply (@eutt_clo_bind _ _ _ _ _ _ rel_asm);\n    [|intros ? ? [? [? ->]]]; cbn.\n  {\n    rewrite bind_ret_l.\n    unfold case_, Case_sum1, Case_Kleisli, case_sum.\n    unfold CategoryOps.cat, CategorySub.Cat_sub, CategoryOps.cat, Cat_Kleisli.\n    unfold inl_, CategorySub.Inl_sub, inl_, Inl_Kleisli, lift_ktree_.\n    unfold inr_, CategorySub.Inr_sub, inr_, Inr_Kleisli, lift_ktree_.\n    unfold id_, CategorySub.Id_sub, id_, Id_Kleisli, lift_ktree_.\n    cbn.\n    unfold CategorySub.from_bif, FromBifunctor_ktree_fin.\n    destruct split_fin_sum.\n    all: rewrite !bind_ret_l, interp_ret, !interp_state_ret.\n    all: apply eqit_Ret; auto; constructor; auto.\n    all : constructor; auto.\n  }\n\n  rewrite interp_ret, !interp_state_ret, !bind_ret_l.\n  rewrite !interp_state_ret, !bind_ret_l; cbn.\n  apply eqit_Ret.\n  destruct split_fin_sum; auto; constructor; auto.\n  all : econstructor; auto.\n  all : constructor; auto.\nQed.\n\n\n(* concrete optimizations --------------------------------------------------- *)\n\nDefinition simple (i:instr) : list instr :=\n  match i with\n  | Imov dest (Oreg src) =>\n    if Nat.eqb dest src then [] else [i]\n  | _ => [i]\n  end.\n\n(* SAZ: Belongs in the utilities? (but depends on EQ_registers)\n   EQ_Registers is now just an alias for eq_map, so this can be moved to MapDefaultFacts.\n*)\nLemma EQ_registers_add:\n  forall (r : reg) (d:value) (regs1 regs2 : registers),\n    EQ_registers d regs1 regs2 ->\n    EQ_registers d (alist_add r (lookup_default r d regs1) regs1) regs2.\nProof.\n  intros r d regs1 regs2 H.\n  unfold EQ_registers.\n  unfold eq_map.\n  intros.\n  unfold lookup_default at 1, lookup, Map_alist.\n  destruct (Nat.eq_dec k r).\n  - subst. rewrite In_add_eq.\n    apply H.\n  - unfold lookup_default, lookup, Map_alist.\n    rewrite alist_find_neq; auto.\n    apply H.\nQed.\n\nLemma simple_correct : ph_correct simple.\nProof.\n  unfold ph_correct.\n  intros E i.\n  unfold eq_asm_denotations_EQ.\n  intros.\n  destruct i; simpl; try apply interp_asm_ret_tt; auto; try reflexivity.\n\n  destruct src.\n  + simpl. rewrite !bind_ret_l.\n    apply interp_asm_ret_tt; auto; try reflexivity.\n\n  + simpl.\n    destruct (Nat.eq_dec dest r).\n    * subst.\n      rewrite Nat.eqb_refl.\n      simpl.\n      rewrite interp_asm_ret.\n      rewrite interp_asm_GetReg.\n\n      unfold trigger.\n      unfold interp_asm, interp_map.\n      rewrite interp_vis.\n      cbn.\n      repeat rewrite interp_state_bind.\n      unfold CategoryOps.cat, Cat_Handler, Handler.cat. simpl.\n      unfold inl_, Inl_sum1_Handler, Handler.inl_, Handler.htrigger.\n      unfold insert.\n      unfold embed, Embeddable_itree, Embeddable_forall, inl_, 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, bind_ret_l, interp_ret. cbn.\n      rewrite tau_eutt, 2 interp_state_ret.\n      apply eqit_Ret.\n      constructor; auto; constructor; auto.\n      cbn; auto using EQ_registers_add.\n    * apply Nat.eqb_neq in n.\n      rewrite n.\n      apply interp_asm_ret_tt; auto.\nQed.\n\nEnd Correctness.\n", "meta": {"author": "DeepSpec", "repo": "InteractionTrees", "sha": "8e28e2ee08496c696e03916a22d93c39559a9715", "save_path": "github-repos/coq/DeepSpec-InteractionTrees", "path": "github-repos/coq/DeepSpec-InteractionTrees/InteractionTrees-8e28e2ee08496c696e03916a22d93c39559a9715/tutorial/AsmOptimization.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.25652823209663056}}
{"text": "From iris.base_logic Require Import lib.invariants.\nFrom iris.algebra Require Import cmra auth list agree csum excl.\nRequire Import SegmentQueue.lib.concurrent_linked_list.infinite_array.sqsegment_impl.\nRequire Import SegmentQueue.lib.concurrent_linked_list.segment_spec.\nFrom SegmentQueue.util Require Import local_updates cmra count_matching everything.\n\nSection infinite_array_segment_proof.\n\nContext `{heapG Σ}.\n\nVariable segment_size: positive.\nVariable pointer_shift: positive.\nVariable pointer_shift_bound:\n  Pos.to_nat segment_size < 2 ^ Pos.to_nat pointer_shift.\n\nNotation cell_algebra := (csumR (agreeR unitO) (* cell is cancelled *)\n                                (exclR unitO)) (* cancellation permit exists *).\n\nRecord immutableValues :=\n  ImmutableValues {\n      segmentId: nat;\n      segmentNextLocation: loc;\n      segmentPrevLocation: loc;\n      segmentCleanedAndPointersLocation: loc;\n      segmentDataLocation: loc;\n    }.\n\nInductive cellState := cellAlive\n                     | cellCancelled.\n\nCanonical Structure immutableValuesO := leibnizO immutableValues.\n\nNotation segment_algebra :=\n  (prodR\n     (authUR (listUR (optionUR cell_algebra))) (* Cells *)\n     (optionUR (agreeR immutableValuesO) (* Immutable contents of the segment *)\n  )).\n\nClass iSegmentG Σ := ISegmentG { iarray_inG :> inG Σ segment_algebra }.\nDefinition iSegmentΣ : gFunctors := #[GFunctor segment_algebra].\nInstance subG_iSegmentΣ : subG iSegmentΣ Σ -> iSegmentG Σ.\nProof. solve_inG. Qed.\nContext `{iSegmentG Σ}.\n\nNotation iProp := (iProp Σ).\n\nLet segment_size_nat := Pos.to_nat segment_size.\n\nDefinition cell_algebra_from_state (state: cellState): cell_algebra :=\n  if state then Cinr (Excl ()) else Cinl (to_agree ()).\n\nDefinition algebra_from_list\n           (values: immutableValues)\n           (state: list cellState): segment_algebra :=\n  (● ((fun (v: cellState) => Some (cell_algebra_from_state v)) <$> state),\n   Some (to_agree values)).\n\nDefinition cell_is_cancelled γ id :=\n  own γ (◯ {[ id := Some (cell_algebra_from_state cellCancelled) ]}, ε).\n\nGlobal Instance cell_is_cancelled_persistent γ id:\n  Persistent (cell_is_cancelled γ id).\nProof. apply _. Qed.\n\nDefinition cell_cancellation_handle γ id :=\n  own γ (◯ {[ id := Some (cell_algebra_from_state cellAlive) ]}, ε).\n\nTheorem cell_cancellation_handle_exclusive γ id:\n  cell_cancellation_handle γ id -∗ cell_cancellation_handle γ id -∗ False.\nProof.\n  iIntros \"H1 H2\".\n  iDestruct (own_valid_2 with \"H1 H2\") as %HValid. exfalso. move: HValid.\n  rewrite -pair_op. case=> /=.\n  rewrite -auth_frag_op auth_frag_valid list_singletonM_op list_singletonM_valid//.\nQed.\n\nTheorem cell_with_handle_not_cancelled γ id:\n  cell_is_cancelled γ id -∗ cell_cancellation_handle γ id -∗ False.\n  iIntros \"H1 H2\".\n  iDestruct (own_valid_2 with \"H1 H2\") as %HValid. exfalso. move: HValid.\n  rewrite -pair_op. case=> /=.\n  rewrite -auth_frag_op auth_frag_valid list_singletonM_op list_singletonM_valid//.\nQed.\n\nLemma auth_cancel_cell values state γ id:\n  cell_cancellation_handle γ id -∗\n  own γ (algebra_from_list values state) ==∗\n  own γ (algebra_from_list values (<[ id := cellCancelled ]> state)) ∗\n  cell_is_cancelled γ id.\nProof.\n  iIntros \"HHandle Hγ\".\n  iMod (own_update_2 with \"Hγ HHandle\") as \"[$ $]\"; last done.\n  apply prod_update; simpl; last done.\n  apply auth_update, list_lookup_local_update=> i.\n  rewrite list_fmap_insert.\n  destruct (lt_eq_lt_dec i id) as [[HLt| ->]|HGt].\n  - rewrite !list_lookup_singletonM_lt; try lia.\n    rewrite list_lookup_insert_ne //; last lia.\n  - rewrite !list_lookup_singletonM list_lookup_fmap.\n    destruct (decide (id < length state)%nat) as [HLt|HGe].\n    * rewrite list_lookup_insert; last by rewrite fmap_length.\n      apply lookup_lt_is_Some in HLt.\n      destruct HLt as [x ->]. simpl.\n      apply option_local_update, option_local_update.\n      rewrite /cell_algebra_from_state.\n      destruct x.\n      + apply replace_local_update; [apply _|done].\n      + apply local_update_valid. intros _ _.\n        case; first by intros HContra; inversion HContra.\n        rewrite csum_included.\n        case; first done.\n        by case; intros (? & ? & ? & ? & ?).\n    * apply local_update_valid.\n      intros _ _.\n      rewrite !lookup_ge_None_2; last lia.\n      2: by rewrite insert_length fmap_length; lia.\n      simpl.\n      case; first by intros HContra; inversion HContra.\n      intros HContra. by apply included_None in HContra.\n  - rewrite !list_lookup_singletonM_gt; try lia.\n    rewrite list_lookup_insert_ne //; last lia.\nQed.\n\nInstance uniqueValue_fmap E: FMap (@uniqueValue Σ E).\nProof.\n  intros A B f HUnique.\n  eapply UniqueValue with\n      (has_value := (fun γ v => ∃ v', has_value HUnique γ v' ∗ ⌜f v' = v⌝)%I);\n    try apply _.\n  iIntros (γ value1 value2) \"H1 H2\".\n  iDestruct \"H1\" as (values1) \"[H1 %]\".\n  iDestruct \"H2\" as (values2) \"[H2 %]\".\n  iDestruct (has_value_agrees with \"H1 H2\") as \"<-\".\n  by simplify_eq.\nDefined.\n\nTheorem immutableValues_uniqueValue: @uniqueValue Σ gname immutableValues.\nProof.\n  eapply UniqueValue with\n      (has_value := (fun γ values => own γ (ε, Some (to_agree values)))%I);\n    try apply _.\n  iIntros (γ v1 v2) \"H1 H2\".\n  iDestruct (own_valid_2 with \"H1 H2\") as %[_ HValid]%pair_valid.\n  iPureIntro. move: HValid; simpl. rewrite -Some_op Some_valid.\n  intros HAgree. apply agree_op_invL' in HAgree. by inversion HAgree.\nDefined.\n\nDefinition prev_uniqueValue :=\n  segmentPrevLocation <$> immutableValues_uniqueValue.\n\nDefinition next_uniqueValue :=\n  segmentNextLocation <$> immutableValues_uniqueValue.\n\nDefinition cleanedAndPointers_uniqueValue :=\n  segmentCleanedAndPointersLocation <$> immutableValues_uniqueValue.\n\nDefinition id_uniqueValue :=\n  segmentId <$> immutableValues_uniqueValue.\n\nDefinition dataLocation_uniqueValue :=\n  segmentDataLocation <$> immutableValues_uniqueValue.\n\nVariable (N: namespace).\n\nVariable (cell_is_owned: nat -> iProp).\n\nDefinition segment_invariant (γ: gname) (values: immutableValues): iProp :=\n  [∗ list] i ∈ seq 0 segment_size_nat,\n  (cell_is_owned (segmentId values * segment_size_nat + i) ∨\n   (segmentDataLocation values +ₗ i) ↦ NONEV ∗ cell_cancellation_handle γ i)%I.\n\nDefinition is_node γ (node: val): iProp :=\n  ∃ (ℓ: loc), ⌜node = #ℓ⌝ ∧\n              ∃ (values: immutableValues),\n                inv N (segment_invariant γ values) ∗\n                own γ (ε, Some (to_agree values)) ∗\n                inv_heap_inv ∗\n                ℓ ↦□ (fun v => v = (#(segmentId values),\n                                    #(segmentCleanedAndPointersLocation values),\n                                    #(segmentPrevLocation values),\n                                    #(segmentNextLocation values),\n                                    #(segmentDataLocation values))%V).\n\nGlobal Instance is_node_persistent γ node: Persistent (is_node γ node).\nProof. apply _. Qed.\n\nTheorem getPrevLoc_spec γ node:\n  {{{ is_node γ node }}}\n    getPrevLoc SQSegmentListNode node\n  {{{ pℓ, RET #pℓ; has_value prev_uniqueValue γ pℓ }}}.\nProof.\n  iIntros (Φ) \"#HNode HΦ\".\n  iDestruct \"HNode\" as (ℓ -> values) \"#(HInv & HValues & #HHeapInv & HLoc)\".\n  wp_lam. wp_bind (! _)%E.\n  iMod (inv_mapsto_acc with \"HHeapInv HLoc\") as (?) \"(-> & Hℓ & HℓRestore)\";\n    first done.\n  wp_load. iMod (\"HℓRestore\" with \"Hℓ\") as \"_\". iModIntro. wp_pures.\n  iApply \"HΦ\". iExists _. by iFrame \"HValues\".\nQed.\n\nTheorem getNextLoc_spec γ node:\n  {{{ is_node γ node }}}\n    getNextLoc SQSegmentListNode node\n  {{{ nℓ, RET #nℓ; has_value next_uniqueValue γ nℓ }}}.\nProof.\n  iIntros (Φ) \"#HNode HΦ\".\n  iDestruct \"HNode\" as (ℓ -> values) \"#(HInv & HValues & #HHeapInv & HLoc)\".\n  wp_lam. wp_bind (! _)%E.\n  iMod (inv_mapsto_acc with \"HHeapInv HLoc\") as (?) \"(-> & Hℓ & HℓRestore)\";\n    first done.\n  wp_load. iMod (\"HℓRestore\" with \"Hℓ\") as \"_\". iModIntro. wp_pures.\n  iApply \"HΦ\". iExists _. by iFrame \"HValues\".\nQed.\n\nLet impl := (SQSegment segment_size pointer_shift).\n\nTheorem getCleanedAndPointersLoc_spec γ node:\n  {{{ is_node γ node }}}\n    getCleanedAndPointersLoc impl node\n  {{{ cℓ, RET #cℓ; has_value cleanedAndPointers_uniqueValue γ cℓ }}}.\nProof.\n  iIntros (Φ) \"#HNode HΦ\".\n  iDestruct \"HNode\" as (ℓ -> values) \"#(HInv & HValues & #HHeapInv & HLoc)\".\n  wp_lam. wp_bind (! _)%E.\n  iMod (inv_mapsto_acc with \"HHeapInv HLoc\") as (?) \"(-> & Hℓ & HℓRestore)\";\n    first done.\n  wp_load. iMod (\"HℓRestore\" with \"Hℓ\") as \"_\". iModIntro. wp_pures.\n  iApply \"HΦ\". iExists _. by iFrame \"HValues\".\nQed.\n\nTheorem getId_spec γ node:\n  {{{ is_node γ node }}}\n    getId impl node\n  {{{ id, RET #id; has_value id_uniqueValue γ id }}}.\nProof.\n  iIntros (Φ) \"#HNode HΦ\".\n  iDestruct \"HNode\" as (ℓ -> values) \"#(HInv & HValues & #HHeapInv & HLoc)\".\n  wp_lam. wp_bind (! _)%E.\n  iMod (inv_mapsto_acc with \"HHeapInv HLoc\") as (?) \"(-> & Hℓ & HℓRestore)\";\n    first done.\n  wp_load. iMod (\"HℓRestore\" with \"Hℓ\") as \"_\". iModIntro. wp_pures.\n  iApply \"HΦ\". iExists _. by iFrame \"HValues\".\nQed.\n\nTheorem node_unboxed γ node:\n  is_node γ node -∗ ⌜val_is_unboxed node⌝.\nProof. iIntros \"#HNode\". by iDestruct \"HNode\" as (ℓ ->) \"_\". Qed.\n\nTheorem node_induces_id γ γ' node id id':\n  has_value id_uniqueValue γ id -∗\n  has_value id_uniqueValue γ' id' -∗\n  is_node γ  node -∗\n  is_node γ' node ==∗\n  ⌜id = id'⌝.\nProof.\n  iIntros \"HId HId' HNode HNode'\".\n  iDestruct \"HNode\" as (ℓ -> values) \"#(HInv & HValues & #HHeapInv & HLoc)\".\n  iDestruct \"HNode'\" as (ℓ' HEq values') \"#(HInv' & HValues' & #HHeapInv' & HLoc')\".\n  iDestruct \"HId\" as (?) \"[HId <-]\". iDestruct \"HId'\" as (?) \"[HId' <-]\".\n  iDestruct (has_value_agrees with \"HId HValues\") as \"->\".\n  iDestruct (has_value_agrees with \"HId' HValues'\") as \"->\".\n  iDestruct (own_valid_2 with \"HLoc HLoc'\") as %HH.\n  iPureIntro. move: HH.\n  simplify_eq.\n  rewrite -auth_frag_op auth_frag_valid.\n  rewrite gmap.singleton_op gmap.singleton_valid pair_valid.\n  case=>_/=HH.\n  apply (@agree_op_inv' (option val -d> PropO)) in HH.\n  specialize (HH (Some (#(segmentId values),\n                        #(segmentCleanedAndPointersLocation values),\n                        #(segmentPrevLocation values),\n                        #(segmentNextLocation values),\n                        #(segmentDataLocation values)))%V).\n  simpl in *. inversion HH as [HH1 _]. specialize (HH1 eq_refl).\n  destruct values; destruct values'; simpl in *. by simplify_eq.\nQed.\n\nInstance cellStateDecidable (v v': cellState): Decision (v = v').\nProof. case v; case v'; by constructor. Defined.\n\nDefinition segment_content γ alive_slots: iProp :=\n  ∃ values state,\n    ⌜count_matching (fun v => v = cellAlive) state = alive_slots ∧\n    length state = segment_size_nat⌝ ∧\n    own γ (algebra_from_list values state).\n\nTheorem cancel_cell γ id alive_slots:\n  cell_cancellation_handle γ id -∗\n  segment_content γ alive_slots ==∗\n  cell_is_cancelled γ id ∗ ∃ alive_slots',\n      ⌜alive_slots = S alive_slots'⌝ ∧ segment_content γ alive_slots'.\nProof.\n  iIntros \"HHandle HContent\".\n  iDestruct \"HContent\" as (values state [HCount HLength]) \"Hγ\".\n  iAssert (⌜state !! id = Some cellAlive⌝)%I as %HLookup.\n  {\n    rewrite /algebra_from_list.\n    iDestruct (own_valid_2 with \"Hγ HHandle\") as\n        %[[(seg & HLookup & HIncluded)%list_singletonM_included\n                                      _]%auth_both_valid _]%pair_valid.\n    iPureIntro.\n    rewrite map_lookup in HLookup.\n    destruct (state !! id) as [state'|] eqn:HLookup'; last done.\n    simpl in *. simplify_eq.\n    destruct state'; first done.\n    move: HIncluded=> /=. rewrite Some_included. case.\n      + intros HContra. inversion HContra.\n      + rewrite csum_included. case; first done.\n        case; by intros (? & ? & ? & ? & ?).\n  }\n  destruct alive_slots as [|alive_slots'].\n  { exfalso. move: HCount HLookup. clear. move: id.\n    induction state as [|x xs]; first done. simpl.\n    destruct x; simpl; first done. by case. }\n  iMod (auth_cancel_cell with \"HHandle Hγ\") as \"[Hγ $]\".\n  iExists alive_slots'. iSplitR; first done.\n  iExists _, _. iFrame \"Hγ\". iPureIntro.\n  rewrite insert_length; split; last done.\n  rewrite list_insert_alter. erewrite count_matching_alter; last done.\n  rewrite HCount /=. lia.\nQed.\n\nTheorem newSegment_spec (id: nat) (prev: val) (pointers: nat):\n  {{{ inv_heap_inv }}}\n    newSegment impl #id prev #pointers\n    {{{ γ node pℓ nℓ cℓ, RET node;\n        is_node γ node\n        ∗ segment_content γ (maxSlots impl)\n        ∗ has_value id_uniqueValue γ id\n        ∗ has_value cleanedAndPointers_uniqueValue γ cℓ\n        ∗ has_value prev_uniqueValue γ pℓ\n        ∗ has_value next_uniqueValue γ nℓ\n        ∗ pℓ ↦ prev ∗ nℓ ↦ NONEV ∗ cℓ ↦ #(pointers ≪ pointerShift impl)\n    }}}.\nProof.\n  iIntros (Φ) \"#HInv HΦ\". wp_lam. wp_pures.\n  wp_alloc dℓ as \"Hdℓ\"; first lia. wp_alloc nℓ as \"Hnℓ\".\n  wp_alloc pℓ as \"Hpℓ\". wp_alloc cℓ as \"Hcℓ\".\n  rewrite -wp_fupd.\n  wp_alloc ℓ as \"Hℓ\".\n  pose values := {|\n      segmentId := id;\n      segmentNextLocation := nℓ;\n      segmentPrevLocation := pℓ;\n      segmentCleanedAndPointersLocation := cℓ;\n      segmentDataLocation := dℓ;\n    |}.\n  iMod (own_alloc (\n            algebra_from_list values (replicate segment_size_nat cellAlive) ⋅\n            (ε, Some (to_agree values)) ⋅\n            (◯ replicate segment_size_nat\n               (Some (cell_algebra_from_state cellAlive)), ε)))\n    as (γ) \"[[H● #HValues] HCancellation]\".\n  {\n    rewrite /algebra_from_list -!pair_op /= pair_valid.\n    split.\n    - apply auth_both_valid. rewrite fmap_replicate.\n      split; first done.\n      apply list_lookup_valid=> i.\n      destruct (_ !! i) eqn:E; last done.\n      apply lookup_replicate in E. by destruct E as [-> _].\n    - apply Some_valid. rewrite agree_idemp. done.\n  }\n  iApply \"HΦ\".\n  replace (Z.pos pointer_shift) with (Z.of_nat (pointerShift impl));\n    last by rewrite /impl /=; lia.\n  iFrame \"Hpℓ Hnℓ Hcℓ\".\n  iSplitL \"Hℓ HCancellation Hdℓ\"; last iSplitL \"H●\".\n  - iExists _. iSplitR; first done. iExists values.\n    iFrame \"HInv HValues\".\n    iMod (make_inv_mapsto with \"HInv Hℓ\") as \"Hℓ'\"; first done;\n      last iDestruct (inv_mapsto_own_inv with \"Hℓ'\") as \"$\"; first done.\n    iMod (inv_alloc N _ (segment_invariant γ values) with \"[-]\") as \"$\";\n      last done.\n    rewrite /segment_invariant /segment_size_nat Z2Nat.inj_pos /array.\n    iAssert ([∗ list] i ∈ seq 0 (Pos.to_nat segment_size),\n             cell_cancellation_handle γ i)%I\n      with \"[HCancellation]\" as \"HCancellation\".\n    {\n      rewrite /cell_cancellation_handle.\n      iClear \"HInv HValues\".\n      remember (Pos.to_nat segment_size) as n. clear.\n      remember (Some _) as state. clear.\n      replace (replicate _ _) with (replicate 0 ε ++ replicate n state);\n        last done.\n      remember 0 as start. clear.\n      iInduction n as [|n'] \"IH\" forall (start); first done.\n      simpl.\n      assert ((replicate start ε ++ state :: replicate n' state)\n                ≡ (replicate (S start) ε ++ replicate n' state) ⋅\n                {[ start := state ]}) as ->.\n      {\n        replace (S start) with (start + 1) by lia.\n        rewrite replicate_plus /= -app_assoc /=.\n        apply list_equiv_lookup=> i. rewrite list_lookup_op.\n        destruct (lt_eq_lt_dec i start) as [[HLt| ->]|HGt].\n        - rewrite list_lookup_singletonM_lt; last lia.\n          rewrite !lookup_app_l; try rewrite replicate_length //.\n          by rewrite lookup_replicate_2; last lia.\n        - rewrite list_lookup_singletonM.\n          rewrite !lookup_app_r; try rewrite replicate_length //.\n          rewrite Nat.sub_diag /=. rewrite -Some_op ucmra_unit_left_id //.\n        - rewrite list_lookup_singletonM_gt; last lia.\n          rewrite !lookup_app_r replicate_length; try lia.\n          rewrite ucmra_unit_right_id.\n          destruct (i - start) eqn:E; first lia. done.\n      }\n      rewrite auth_frag_op pair_op_1 own_op.\n      iDestruct \"HCancellation\" as \"[HCancellation $]\".\n      iApply (\"IH\" with \"HCancellation\").\n    }\n    assert (([∗ list] i ↦ v ∈ seq 0 (Pos.to_nat segment_size),\n             (dℓ +ₗ i) ↦ InjLV #())%I ≡\n            ([∗ list] i↦v ∈ replicate (Pos.to_nat segment_size) (InjLV #()),\n              (dℓ +ₗ i) ↦ v)%I) as <-.\n    {\n      apply big_opL_gen_proper_2. done. by apply _.\n      intros k.\n      destruct (seq _ _ !! k) eqn:E.\n      - apply lookup_seq in E. destruct E as [-> Hk].\n        by rewrite lookup_replicate_2; last lia.\n      - apply lookup_ge_None in E. rewrite seq_length in E.\n        rewrite lookup_ge_None_2 // replicate_length. lia.\n    }\n    iCombine \"Hdℓ\" \"HCancellation\" as \"H\".\n    rewrite -big_sepL_sep.\n    iApply (big_sepL_mono with \"H\").\n    intros ? ? HEq. apply lookup_seq in HEq. destruct HEq as [-> Hk].\n    iIntros \"[Hdℓ HCancHandle]\". iRight. iFrame.\n  - rewrite /segment_content. iExists values, _. iFrame \"H●\".\n    iPureIntro. rewrite /impl /segment_size_nat /=.\n    rewrite replicate_length; split; last done.\n    remember (Pos.to_nat _) as listLen. clear.\n    induction listLen; first done. rewrite /= IHlistLen //.\n  - repeat iSplitR; iExists _; iFrame \"HValues\"; done.\nQed.\n\nLemma max_slots_bound: (0 < maxSlots impl < 2 ^ pointerShift impl)%nat.\nProof. rewrite /impl /=. split; first lia; last done. Qed.\n\nEnd infinite_array_segment_proof.\n\nSection segment_specs.\n\nVariable (segment_size pointer_shift: positive).\nVariable (limit: Pos.to_nat segment_size < 2 ^ Pos.to_nat pointer_shift).\nVariable (N: namespace).\n\nDefinition node_linkedListNode `{!heapG Σ} `{!iSegmentG Σ}:\n  linkedListNodeSpec Σ (base (SQSegment segment_size pointer_shift)) :=\n  {| segment_spec.getPrevLoc_spec := getPrevLoc_spec segment_size N;\n     segment_spec.getNextLoc_spec := getNextLoc_spec segment_size N;\n     segment_spec.linkedListNode_unboxed := node_unboxed segment_size N;\n     segment_spec.is_linkedListNode_persistent :=\n       is_node_persistent segment_size N;\n  |}.\n\nCanonical Structure node_segment `{!heapG Σ}\n          `{!iSegmentG Σ}: segmentSpec Σ (SQSegment segment_size pointer_shift)\n  := {|\n  segment_spec.linkedListNode_base := node_linkedListNode;\n  segment_spec.getId_spec :=\n    getId_spec segment_size pointer_shift N;\n  segment_spec.getCleanedAndPointersLoc_spec :=\n    getCleanedAndPointersLoc_spec segment_size pointer_shift N;\n  segment_spec.newSegment_spec :=\n    newSegment_spec segment_size pointer_shift N;\n  segment_spec.max_slots_bound :=\n    max_slots_bound segment_size pointer_shift limit;\n  segment_spec.node_induces_id :=\n    node_induces_id segment_size N;\n  |}.\n\nEnd segment_specs.\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/concurrent_linked_list/infinite_array/sqsegment_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.25645992167162496}}
{"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 A B C D E Eprime T Eprimeprime Cprime Dprime R Y : Universe, ((wd_ C D /\\ (wd_ A B /\\ (wd_ A C /\\ (wd_ A D /\\ (wd_ Eprime A /\\ (wd_ A T /\\ (wd_ Eprimeprime T /\\ (wd_ D Eprimeprime /\\ (wd_ C Eprimeprime /\\ (wd_ A Eprimeprime /\\ (wd_ Dprime B /\\ (wd_ Cprime B /\\ (wd_ A Y /\\ (wd_ A R /\\ (wd_ R Cprime /\\ (wd_ Cprime Dprime /\\ (wd_ Eprimeprime B /\\ (wd_ B C /\\ (wd_ B D /\\ (wd_ D Dprime /\\ (wd_ C Cprime /\\ (wd_ A Dprime /\\ (wd_ A Cprime /\\ (wd_ R Dprime /\\ (wd_ A E /\\ (wd_ Cprime D /\\ (wd_ D Eprime /\\ (wd_ Dprime C /\\ (col_ C D E /\\ (col_ T A B /\\ (col_ T C D /\\ (col_ B D Dprime /\\ (col_ B C Cprime /\\ (col_ D Eprimeprime C /\\ (col_ R Cprime Dprime /\\ (col_ A Eprimeprime Eprime /\\ (col_ A Y R /\\ (col_ A Y A /\\ (col_ A Eprimeprime R /\\ col_ A R A))))))))))))))))))))))))))))))))))))))) -> col_ A Y Eprimeprime)).\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_0394.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.25645991687098485}}
{"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 Aprime Cprime T BB : Universe, ((wd_ P Q /\\ (wd_ P Aprime /\\ (wd_ P B /\\ (wd_ P Cprime /\\ (wd_ A Aprime /\\ (wd_ A C /\\ (wd_ A B /\\ (wd_ C Cprime /\\ (wd_ Aprime Cprime /\\ (wd_ Cprime T /\\ (wd_ T B /\\ (wd_ Cprime B /\\ (wd_ Aprime T /\\ (wd_ Aprime B /\\ (wd_ Q A /\\ (wd_ P A /\\ (wd_ T P /\\ (wd_ C P /\\ (wd_ T A /\\ (wd_ Cprime A /\\ (wd_ T C /\\ (wd_ B C /\\ (wd_ Q T /\\ (col_ P Q Aprime /\\ (col_ P Q B /\\ (col_ P Q Cprime /\\ (col_ BB T B /\\ (col_ Aprime BB Cprime /\\ col_ A B C)))))))))))))))))))))))))))) -> col_ Aprime Cprime B)).\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_0739.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.2564336644579752}}
{"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: PQueueIntro                              *)\n(*                                                                     *)\n(*          Provide abstraction of thread queue                        *)\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 PQueueIntro 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.\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.\n\nRequire Import AbstractDataType.\n\nRequire Export PThreadInit.\n\n(** * Abstract Data and Primitives at this layer*)\n\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        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        tcb: TCBPool; (*r thread control blocks pool*)                 \n        tdq: TDQueuePool (**r thread queue 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 set_head_inv: PreservesInvariants set_head_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; auto 2.\n    Qed.\n\n    Global Instance set_tail_inv: PreservesInvariants set_tail_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; auto 2.\n    Qed.\n\n    Global Instance tdq_init_inv: PreservesInvariants tdq_init_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; auto 2.\n    Qed.\n\n  End INV.\n\n  (** * Layer Definition *)\n  Definition pqueueintro_fresh : compatlayer (cdata RData) :=\n    get_head ↦ gensem get_head_spec\n             ⊕ get_tail ↦ gensem get_tail_spec\n             ⊕ set_head ↦ gensem set_head_spec\n             ⊕ set_tail ↦ gensem set_tail_spec\n             ⊕ tdq_init ↦ gensem tdq_init_spec.\n\n  Definition pqueueintro_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          ⊕ kctxt_new ↦ dnew_compatsem ObjThread.kctxt_new_spec\n          (*⊕ pt_free ↦ gensem pt_free_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          ⊕ 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 _ _ Hmwd); \n                           exec_store := (@exec_storeex _ _ Hmwd) |}          \n          ⊕ thread_init ↦ gensem thread_init_spec.\n\n  Definition pqueueintro : compatlayer (cdata RData) := pqueueintro_fresh ⊕ pqueueintro_passthrough.\n\n  (*Definition pqueueintro_impl : compatlayer (cdata RData) :=\n    thread_init ↦ gensem thread_init_spec\n      ⊕ tdq_init ↦ gensem tdq_init_spec\n      ⊕ set_prev ↦ gensem set_prev_spec\n      ⊕ set_next ↦ gensem set_next_spec\n      ⊕ get_head ↦ gensem get_head_spec\n      ⊕ get_tail ↦ gensem get_tail_spec\n      ⊕ get_prev ↦ gensem get_prev_spec\n      ⊕ get_next ↦ gensem get_next_spec\n      ⊕ set_head ↦ gensem set_head_spec\n      ⊕ set_tail ↦ gensem set_tail_spec.\n  \n  Definition pqueueintro_rest : compatlayer (cdata RData) :=\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      ⊕ trap_out ↦ primcall_general_compatsem (prim_generic:= trapout_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      ⊕ kctxt_switch ↦ primcall_kctxt_switch_compatsem (kctxt_switch:= kctxt_switch_spec)\n      ⊕ kctxt_new ↦ dnew_compatsem (dnew := kctxt_new_spec)\n      ⊕ get_state ↦ gensem get_state_spec\n      ⊕ set_state ↦ gensem set_state_spec\n      ⊕ thread_free ↦ gensem thread_free_spec\n      ⊕ accessors ↦ {| exec_load := @exec_loadex; exec_store := @exec_storeex |}.\n\n  Lemma pqueueintro_impl_eq : pqueueintro ≡ pqueueintro_impl ⊕ pqueueintro_rest.\n  Proof. reflexivity. Qed.\n\n  Definition semantics := LAsm.Lsemantics pqueueintro.*)\n\nEnd WITHMEM.\n\nSection WITHPARAM.\n\n  Context `{real_params: RealParams}.\n\n  Local Open Scope Z_scope.\n\n  Section Impl.\n\n    (** primitve: enqueue*)\n    Function enqueue_spec (n i: Z) (adt: RData): option RData :=\n      match (ikern adt, pg adt, ihost adt, ipt adt) with\n        | (true, true, true, true) =>\n          if Queue_arg n i then\n            match (ZMap.get n (tdq adt), ZMap.get i (tcb adt))  with \n              | (TDQValid h t, TCBValid st _ _) =>\n                if zeq t num_proc then\n                  Some adt {tcb: ZMap.set i (TCBValid st num_proc num_proc) (tcb adt)}\n                       {tdq: ZMap.set n (TDQValid i i) (tdq adt)}\n                else\n                  if zle_lt 0 t num_proc then\n                    match (ZMap.get t (tcb adt)) with\n                      | TCBValid st' prev' _ =>\n                        let tcb':= ZMap.set t (TCBValid st' prev' i) (tcb adt) in\n                        Some adt {tcb: ZMap.set i (TCBValid st t num_proc) tcb'}\n                             {tdq: ZMap.set n (TDQValid h i) (tdq adt)}\n                      | _ => None\n                    end\n                  else None\n              | _ => None\n            end\n          else None\n        | _ => None\n      end.\n\n    (** primitve: dequeue*)\n    Function dequeue_spec (n: Z) (adt: RData): option (RData* Z) :=\n      match (ikern adt, pg adt, ihost adt, ipt adt) with\n        | (true, true, true, true) =>\n          if zle_le 0 n num_chan then\n              match (ZMap.get n (tdq adt)) with \n                | TDQValid h t =>\n                  if zeq h num_proc then\n                    Some (adt, num_proc)\n                  else\n                    if zle_lt 0 h num_proc then\n                      match (ZMap.get h (tcb adt)) with\n                        | TCBValid st _ next =>\n                          if zeq next num_proc then\n                            Some (adt {tdq: ZMap.set n (TDQValid num_proc num_proc) (tdq adt)}, h)\n                            else\n                              match (ZMap.get next (tcb adt)) with\n                                | TCBValid st' _ next' =>\n                                  Some (adt {tcb: ZMap.set next (TCBValid st' num_proc next') (tcb adt)}\n                                            {tdq: ZMap.set n (TDQValid next t) (tdq adt)} , h)\n                                | _ => None\n                              end\n                        | _ => None\n                      end\n                    else None\n                | _ => None\n              end\n          else None\n        | _ => None\n      end.\n        \n    (** primitive: initialize the allocation table, set up the paging mechanism, and initialize the page table pool*)   \n    Function tdqueue_init_spec (mbi_adr:Z) (abd: RData): option RData :=\n      match thread_init_spec mbi_adr abd  with\n        | Some adt =>\n          Some adt {tdq: real_tdq (tdq adt)}\n        | _ => None\n      end.\n\n  End Impl.\n\nEnd WITHPARAM.\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/PQueueIntro.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.256417585223462}}
{"text": "(* Written by Sosuke Moriguchi (chiguri), Kwansei Gakuin University *)\n\n(** * Functor from Network Topology with Protocol Setting to a CCN protocol on the network complying content managements. *)\n\nRequire Import List.\nImport ListNotations.\n\nRequire CCNTopology.\nRequire CCNContentManagement.\n\n\nModule CCN_Protocol_CM (N : CCNContentManagement.CCN_Content_Management).\nImport N.\nExport OldProtocol.\nImport Topology.\n\n\n\n(** Exists ForwardInterest or not *)\nFixpoint In_ForwardInterest (v : Node) (c : Content_Name) (es : list Event) : bool :=\nmatch es with\n| nil => false\n| ForwardInterest v' c' :: es' =>\n    match Node_eq_dec v v' with\n    | left _ => match Content_Name_eq_dec c c' with\n                | left _ => true\n                | right _ => In_ForwardInterest v c es'\n                end\n    | right _ => In_ForwardInterest v c es'\n    end\n| StoreData v' c' _ :: es' =>\n    match Node_eq_dec v v' with\n    | left _ => match Content_Name_eq_dec c c' with\n                | left _ => false\n                | right _ => In_ForwardInterest v c es'\n                end\n    | right _ => In_ForwardInterest v c es'\n    end\n| _ :: es' => In_ForwardInterest v c es'\nend.\n\n\n\n(** Exists Request or not *)\nFixpoint In_Request (v : Node) (c : Content_Name) (es : list Event) : bool :=\nmatch es with\n| nil => false\n| Request v' c' :: es' =>\n    match Node_eq_dec v v' with\n    | left _ => match Content_Name_eq_dec c c' with\n                | left _ => true\n                | right _ => In_Request v c es'\n                end\n    | right _ => In_Request v c es'\n    end\n| StoreData v' c' _ :: es' =>\n    match Node_eq_dec v v' with\n    | left _ => match Content_Name_eq_dec c c' with\n                | left _ => false\n                | right _ => In_Request v c es'\n                end\n    | right _ => In_Request v c es'\n    end\n| _ :: es' => In_Request v c es'\nend.\n\n\n\n\n\n(** Definition of behaviors of the CCN protocol *)\nInductive CCNprotocol : list Event -> list Packet -> Prop :=\n| ccn_init : CCNprotocol nil nil\n| ccn_request : forall (v : Node) (c : Content_Name) (es : list Event) (ps ps' : list Packet),\n   CCNprotocol es ps ->\n    CMF v c es = None ->\n    ps' = Broadcast_Interest v c ++ ps ->\n    CCNprotocol (Request v c :: es) ps'\n| ccn_forward_interest : forall (v v' : Node) (c : Content_Name) (es : list Event) (ps1 ps2 ps' : list Packet),\n   CCNprotocol es (ps1 ++ Interest v v' c :: ps2) ->\n    CMF v' c es = None ->\n    PIT_list v' c es = nil ->\n    FIB_list v' c <> nil ->\n    ps' = FIB_Interest v' c ++ ps1 ++ ps2 ->\n    CCNprotocol (ForwardInterest v' c :: AddPIT v' v c :: es) ps'\n| ccn_add_pit : forall (v v' : Node) (c : Content_Name) (es : list Event) (ps1 ps2 ps' : list Packet),\n   CCNprotocol es (ps1 ++ Interest v v' c :: ps2) ->\n    CMF v' c es = None ->\n    PIT_list v' c es <> nil ->\n    ~ In v (PIT_list v' c es) ->\n    FIB_list v' c <> nil ->\n    ps' = ps1 ++ ps2 ->\n    CCNprotocol (AddPIT v' v c :: es) ps'\n| ccn_drop_interest_fib : forall (v v' : Node) (c : Content_Name) (es : list Event) (ps1 ps2 ps' : list Packet),\n   CCNprotocol es (ps1 ++ Interest v v' c :: ps2) ->\n    CMF v' c es = None ->\n    FIB_list v' c = nil ->\n    ps' = ps1 ++ ps2 ->\n    CCNprotocol es ps'\n| ccn_drop_interest_pit : forall (v v' : Node) (c : Content_Name) (es : list Event) (ps1 ps2 ps' : list Packet),\n   CCNprotocol es (ps1 ++ Interest v v' c :: ps2) ->\n    CMF v' c es = None ->\n    In v (PIT_list v' c es) ->\n    ps' = ps1 ++ ps2 ->\n    CCNprotocol es ps'\n| ccn_reply_data : forall (v v' : Node) (c : Content_Name) (C : Content c) (es : list Event) (ps1 ps2 ps' : list Packet),\n   CCNprotocol es (ps1 ++ Interest v v' c :: ps2) ->\n    CMF v' c es = Some C ->\n    ps' = Data v' v c C :: ps1 ++ ps2 ->\n    CCNprotocol (ReplyData v' c :: es) ps'\n| ccn_store_data : forall (v v' : Node) (c : Content_Name) (C : Content c) (es : list Event) (ps1 ps2 ps' : list Packet),\n   CCNprotocol es (ps1 ++ Data v v' c C :: ps2) ->\n    CMF v' c es = None ->\n    In_Request v' c es = true ->\n    PIT_list v' c es = nil ->\n    ps' = ps1 ++ ps2 ->\n    CCNprotocol (StoreData v' c C :: es) ps'\n| ccn_forward_data : forall (v v' : Node) (c : Content_Name) (C : Content c) (es : list Event) (ps1 ps2 ps' : list Packet),\n   CCNprotocol es (ps1 ++ Data v v' c C :: ps2) ->\n    CMF v' c es = None ->\n    In_Request v' c es = false ->\n    PIT_list v' c es <> nil ->\n    ps' = (PIT_Data v' c C es) ++ ps1 ++ ps2 ->\n    CCNprotocol (StoreData v' c C :: ForwardData v' c :: es) ps'\n| ccn_store_forward : forall (v v' : Node) (c : Content_Name) (C : Content c) (es : list Event) (ps1 ps2 ps' : list Packet),\n   CCNprotocol es (ps1 ++ Data v v' c C :: ps2) ->\n    CMF v' c es = None ->\n    In_Request v' c es = true ->\n    PIT_list v' c es <> nil ->\n    ps' = (PIT_Data v' c C es) ++ ps1 ++ ps2 ->\n    CCNprotocol (StoreData v' c C :: ForwardData v' c :: es) ps'\n| ccn_drop_data : forall (v v' : Node) (c : Content_Name) (C : Content c) (es : list Event) (ps1 ps2 ps' : list Packet),\n   CCNprotocol es (ps1 ++ Data v v' c C :: ps2) ->\n    In_Request v' c es = false ->\n    PIT_list v' c es = nil ->\n    ps' = ps1 ++ ps2 ->\n    CCNprotocol es ps'.\n\n\nEnd CCN_Protocol_CM.\n\n", "meta": {"author": "chiguri", "repo": "CCNprotocol", "sha": "931b4ee775b2ef95c03bd99fe02fbe1ec5038ac0", "save_path": "github-repos/coq/chiguri-CCNprotocol", "path": "github-repos/coq/chiguri-CCNprotocol/CCNprotocol-931b4ee775b2ef95c03bd99fe02fbe1ec5038ac0/CCNProtocolWithCM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.2564175803201323}}
{"text": "From Mtac2 Require Import Base Datatypes List MTele MTeleMatch MTeleMatchDef MFixDef Sorts tactics.Tactics.\nRequire Import Strings.String.\nImport Sorts.\nImport Mtac2.lib.List.ListNotations.\nImport ProdNotations.\nImport Tactics.T.\nImport M.\nImport M.notations.\n\nSet Universe Polymorphism.\nUnset Universe Minimization ToSet.\n\nLocal Inductive msigT {A} (P : A -> Type) : Type := | mexistT x : P x -> msigT P.\nLocal Notation \"'{$'  x .. y  &  P }\" := (msigT (fun x => .. (msigT (fun y => P)) .. )) (x binder, y binder).\nLocal Definition mprojT1 {A} {P} : @msigT A P -> A := fun '(mexistT _ x _) => x.\nLocal Definition mprojT2 {A} {P} : forall s : @msigT A P, P (mprojT1 s) := fun '(mexistT _ _ p) => p.\n\nLocal Inductive TTele : Type :=\n| ttbase (X : Type) : TTele\n| tttele {X} : (X -> TTele) -> TTele.\nFixpoint TTele_ty (M : Type -> Type) t :=\n  match t with\n  | ttbase X => M X\n  | tttele F => forall x, TTele_ty M (F x)\n  end.\n\nLocal Fixpoint TTele_bind {X} {t} : (X -> TTele_ty M t) -> (TTele_ty M.t t) :=\n  match t with\n  | ttbase X => M.bind (M.evar _)\n  | tttele F => fun f (t : _) => @TTele_bind X (F t) (fun x : X => f x t)\n  end\n.\n\nLocal Fixpoint func_of (l : mlist Prop) :=\n  match l with\n  | mnil => True\n  | mcons T l => prod T (func_of l)\nend.\n\nLocal Notation \"x -*> y\" := (prod (func_of x) y) (only parsing, at level 91).\n\nLocal Notation tty := (TTele_ty (fun T => msigT (fun l => M (l -*> T)))).\n\nLocal Fixpoint TTele_bind' {X : Prop} (x : X) {t} : (TTele_ty (fun T => msigT (fun l => X -> M (l -*> T))) t) -> (tty t) :=\n  match t with\n  | ttbase B => fun '(mexistT _ l f) => mexistT _ (X :m: l) (\n                  H <- M.evar X;\n                  '(goals, R) <- f H;\n                  M.ret ((H,goals), R))\n  | tttele F => fun f t =>\n                  TTele_bind' x (f t)\n  end\n.\n\nDefinition lift_lemma : forall (A : Prop), A ->\n      M (msigT tty) :=\n  let m := (mTele (fun (A : Prop) => (mTele (fun (a:A) => mBase)))) in\n  @mfix' m\n         (fun A (a:A) => msigT tty)\n        (fun rec (A : Prop) =>\n           let m (A : Prop) := mTele (fun a:A => mBase) in\n           mtmmatch'\n             _ m (fun A a => msigT tty) A\n             [m:\n              (mtptele (fun B:Prop => mtptele (fun (C:Prop) => (mtpbase ( m:=fun A:Prop => A -> M _)) _ (\n              fun (f : B -> C) =>\n                M.nu (FreshFrom A) mNone (fun b : B =>\n                               '(mexistT _ t X) <- rec C (f b);\n                               match t as t return tty t -> M (_) with\n                               | tttele _ =>\n                                 fun _ =>\n                                   M.failwith \"Lemma to be lifted has dependent quantifiers after non-dependent ones. This is not supported.\"\n                               | ttbase P => fun f =>\n                                               let '(mexistT _ l f) := f in\n                                               f' <- M.abs_fun b f;\n                                               f' <- M.coerce f';\n                                               let T' := reduce (RedWhd RedAll)\n                                                                (TTele_bind' b (t0:=ttbase _) (mexistT _ l f')) in\n                                          M.ret (mexistT tty (ttbase P) T')\n                               end X\n                     )\n              ) UniMatchNoRed)))%mtpattern\n             |\n             (mtptele (fun B:Type => mtptele (fun (C:B -> Prop) => (mtpbase ( m:=fun A:Prop => A -> M _)) _ (\n              fun (f : forall b:B, C b) =>\n                M.nu (FreshFrom A) mNone (fun b : B =>\n                               '(mexistT _ t X) <- rec _ (f b);\n                               t' <- M.abs_fun b t;\n                               X <- M.coerce X;\n                               X' <- M.abs_fun (P:=fun b => tty (t' b)) b X;\n                               M.ret (mexistT tty (tttele t') (fun x => X' x))\n                     )\n              ) UniMatchNoRed)))%mtpattern\n              |\n              (mtpbase ( m:=fun A:Prop => A -> M _) A\n                       (fun a:A =>\n                          M.ret (mexistT tty (ttbase A) (mexistT _ mnil (M.ret (I,a))))\n                       )\n                       UniCoq\n              )%mtpattern\n             ]%with_mtpattern\n        )\n.\n\n\nLocal Fixpoint TTele_App {P1} {t} (P2 : forall T (H : P1 T), Type) : TTele_ty P1 t -> Type :=\n  match t with\n  | ttbase P => fun x => P2 _ x\n  | tttele F => fun g => forall x, TTele_App P2 (g x)\n  end.\n\nLocal Fixpoint TTele_app {P1} {t} P2 (f : forall T PT, P2 T PT) : forall tt, TTele_App (P1:=P1) (t:=t) P2 tt :=\nmatch t with\n| ttbase T => fun tt : P1 T => f _ _\n| tttele F => fun (tt : forall t, TTele_ty P1 (F t)) t => @TTele_app _ (F t) _ f (tt t)\nend.\n\nDefinition do_def n {A:Prop} (a:A) :=\n  '(mexistT _ t f) <- lift_lemma A (a);\n  (* let f := reduce (RedStrong [rl: RedBeta; RedZeta; RedFix; RedMatch; RedDeltaOnly [rl: Dyn (@M.type_of); Dyn (@TTele_ty)] ]) (f) in *)\n  let x := reduce (RedStrong [rl: RedFix; RedMatch; RedBeta; RedDeltaOnly [rl: Dyn (@TTele_app)]]) (TTele_app (fun T PT => let '(mexistT _ l _) := PT in M (l -*> T))\n                                                (fun T PT => let '(mexistT _ l X) := PT in\n                                                             X\n                                                ) f) in\n  let T := reduce (RedStrong [rl: RedBeta; RedZeta; RedFix; RedMatch;\n                           RedDeltaOnly [rl: Dyn (@M.type_of); Dyn (@TTele_ty); Dyn (@TTele_App); Dyn (@TTele_app); Dyn (@func_of)] ]) (M.type_of x) in\n               @M.declare dok_Definition n false T x;; M.ret tt.\n\n(** We use a synonim to prod to emulate typed goals. The idea *)\n(*     is that at the left we have the hypotheses, and at the right *)\n(*     the goal type. A goal H1, ..., Hn |- G is then written *)\n(*     (H1 * ... * Hn) =m> G *)\n\n(*     A lemma lifted to this type will produce an element of type G given *)\n(*     promises (evars) for H1, ..., Hn. *)\n(* *)\n\nDefinition myprod := prod.\nArguments myprod _%type _%type.\n\nNotation \"T1 '|m-' G\" := (myprod T1 G)\n  (at level 98, no associativity,\n   format \"T1  |m-  G\") : type_scope.\n\n\n(** composes on the left of the arrow *)\nDefinition compl {A} {B} (f: M (A |m- B)) (g : M A) : M B :=\n  '(a, b) <- f;\n  a' <- g;\n  mif unify a a' UniCoq then\n    ret b\n  else failwith \"nope\".\n\n(** composes a product *)\nDefinition compi {A} {B} (g : M A) (h : M B) : M (A * B) :=\n  g >>= fun xg=> h >>= fun xh => ret (xg, xh).\n\n(** Solves goal A provided tactic t *)\nDefinition Mby' {A} (t: tactic) : M A :=\n  e <- evar A;\n  l <- t (Goal Typeₛ e);\n  l' <- T.filter_goals l;\n  match l' with mnil => ret e | _ => failwith \"couldn't solve\" end.\n\nMtac Do New Exception NotAProp.\nDefinition Muse {A} (t: tactic) : M A :=\n  mtry\n    P <- evar Prop;\n    of <- unify_univ P A UniMatchNoRed;\n    match of with\n    | mSome f => e <- M.evar P;\n                 t (Goal Propₛ e);;\n                 let e := reduce (RedOneStep [rl: RedBeta]) (f e) in\n                 ret e\n    | mNone => raise NotAProp\n    end\n  with | NotAProp =>\n    e <- evar A;\n    t (Goal Typeₛ e);;\n    ret e\n  end.\n\nDefinition is_prod T :=\n  mmatch T with\n  | [? A B] (A * B)%type => ret true\n  | _ => ret false\n  end.\n\nDefinition dest_pair {T} (x:T) : M (dyn * dyn) :=\n  mmatch Dyn x with\n  | [? A B a b] @Dyn (A*B) (a, b) => ret (Dyn a, Dyn b)\n  end.\n\n(** Given an element with type of the form (A1 * ... * An), *)\n(*     it generates a goal for each unsolved variable in the pair. *)\nProgram Definition to_goals : forall {A}, A -> M (mlist (unit *m goal)) :=\n  mfix2 to_goals (A: Type) (a: A) : M _ :=\n  mif is_evar a then ret [m: (m: tt, Goal Typeₛ a)]\n  else\n    mif is_prod A then\n      '(d1, d2) <- dest_pair a;\n      dcase d1 as x in\n      dcase d2 as y in\n      t1s <- to_goals _ x;\n      t2s <- to_goals _ y;\n      ret (t1s +m+ t2s)\n    else\n      ret [m:].\n\n(** From a typed tactic with type A |m- B, it generates an untyped one *)\nDefinition to_tactic {A B} (f: M (A |m- B)) : tactic := fun g=>\n  gT <- goal_type g;\n  mif unify gT B UniCoq then\n    '(a, b) <- f;\n    al <- to_goals a;\n    ls <- T.filter_goals al;\n    T.exact b g;;\n    ret ls\n  else\n    failwith \"nope\".\n\nDefinition pass := evar.\nArguments pass {_}.\n\nImport Strings.Ascii.\nLocal Open Scope string.\n\nDefinition doTT {A:Prop} (x:A) :=\n  s <- pretty_print x;\n  let s :=\n      match String.get 0 s with\n      | Some \"@\"%char => String.substring 1 (String.length s -1) s\n      | _ => s\n      end  ++ \"T\" in\n  print s;;\n  do_def s x.\n", "meta": {"author": "Mtac2", "repo": "Mtac2", "sha": "d16c2e682d5ab18ed77b13b4fd60a42a65c4f958", "save_path": "github-repos/coq/Mtac2-Mtac2", "path": "github-repos/coq/Mtac2-Mtac2/Mtac2-d16c2e682d5ab18ed77b13b4fd60a42a65c4f958/theories/ideas/Pre-typedtactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.25641757541680255}}
{"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.\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 Global.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import BoolMap.\nRequire Import Promises.\n\nRequire Import OrdStep.\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 msg,\n        (<<GET: Memory.get loc to mem = Some (from, msg)>>) /\\\n        (<<NRESERVE: msg <> Message.reserve>>) /\\\n        (<<TS: Time.lt ((TView.cur (Local.tview lc)).(View.rlx) loc) to>>)\n    .\n\n    Inductive read_step (lc1:Local.t) (gl1:Global.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 gl1 loc to val released ord' lc2)\n        (MAXIMAL: forall (LOC: L loc)\n                         from' to' val' released' na\n                         (GET: Memory.get loc to' gl1.(Global.memory) = Some (from', Message.message val' released' na)),\n            Time.le to' to)\n    .\n    Hint Constructors read_step: core.\n\n    Inductive write_step (lc1:Local.t) (gl1:Global.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) (gl2:Global.t): 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 gl1 loc from to val releasedm released ord' lc2 gl2)\n        (MAXIMAL: forall (LOC: L loc)\n                         from' to' val' released' na\n                         (GET: Memory.get loc to' gl1.(Global.memory) = Some (from', Message.message val' released' na)),\n            Time.lt to' to)\n    .\n    Hint Constructors write_step: core.\n\n    Variant program_step:\n      forall (e: ThreadEvent.t) (lc1: Local.t) (gl1: Global.t) (lc2: Local.t) (gl2: Global.t), Prop :=\n      | program_step_silent\n          lc1 gl1:\n        program_step ThreadEvent.silent lc1 gl1 lc1 gl1\n      | program_step_read\n          lc1 gl1\n          loc to val released ord lc2\n          (LOCAL: read_step lc1 gl1 loc to val released ord lc2):\n        program_step (ThreadEvent.read loc to val released ord) lc1 gl1 lc2 gl1\n      | program_step_write\n          lc1 gl1\n          loc from to val released ord lc2 gl2\n          (LOCAL: write_step lc1 gl1 loc from to val None released ord lc2 gl2):\n        program_step (ThreadEvent.write loc from to val released ord) lc1 gl1 lc2 gl2\n      | program_step_update\n          lc1 gl1\n          loc ordr ordw\n          tsr valr releasedr releasedw lc2\n          tsw valw lc3 gl3\n          (LOCAL1: read_step lc1 gl1 loc tsr valr releasedr ordr lc2)\n          (LOCAL2: write_step lc2 gl1 loc tsr tsw valw releasedr releasedw ordw lc3 gl3):\n        program_step (ThreadEvent.update loc tsr tsw valr valw releasedr releasedw ordr ordw)\n                     lc1 gl1 lc3 gl3\n      | program_step_fence\n          lc1 gl1\n          ordr ordw lc2 gl2\n          (LOCAL: Local.fence_step lc1 gl1 ordr ordw lc2 gl2):\n        program_step (ThreadEvent.fence ordr ordw) lc1 gl1 lc2 gl2\n      | program_step_syscall\n          lc1 gl1\n          e lc2 gl2\n          (LOCAL: Local.fence_step lc1 gl1 Ordering.seqcst Ordering.seqcst lc2 gl2):\n        program_step (ThreadEvent.syscall e) lc1 gl1 lc2 gl2\n      | program_step_failure\n          lc1 gl1\n          (LOCAL: Local.failure_step lc1):\n        program_step ThreadEvent.failure lc1 gl1 lc1 gl1\n      | program_step_racy_read\n          lc1 gl1\n          loc to val ord\n          (LOCAL: Local.racy_read_step lc1 gl1 loc to val ord):\n        program_step (ThreadEvent.racy_read loc to val ord) lc1 gl1 lc1 gl1\n      | program_step_racy_write\n          lc1 gl1\n          loc to val ord\n          (LOCAL: Local.racy_write_step lc1 gl1 loc to ord):\n        program_step (ThreadEvent.racy_write loc to val ord) lc1 gl1 lc1 gl1\n      | program_step_racy_update\n          lc1 gl1\n          loc to valr valw ordr ordw\n          (LOCAL: Local.racy_update_step lc1 gl1 loc to ordr ordw):\n        program_step (ThreadEvent.racy_update loc to valr valw ordr ordw) lc1 gl1 lc1 gl1\n    .\n\n\n    (* step_future *)\n\n    Lemma program_step_future\n          e lc1 gl1 lc2 gl2\n          (STEP: program_step e lc1 gl1 lc2 gl2)\n          (WF1: Local.wf lc1 gl1)\n          (GL1: Global.wf gl1):\n      <<WF2: Local.wf lc2 gl2>> /\\\n      <<GL2: Global.wf gl2>> /\\\n      <<TVIEW_FUTURE: TView.le lc1.(Local.tview) lc2.(Local.tview)>> /\\\n      <<GL_FUTURE: Global.future gl1 gl2>>.\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.\n        { ss. eapply Time.bot_spec. }\n        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.\n        { etrans; eauto. inv STEP0. inv WRITE. inv ADD. left. auto. }\n        i. des.\n        esplits; eauto. etrans; eauto.\n      - exploit Local.fence_step_future; eauto.\n      - exploit Local.fence_step_future; eauto.\n      - esplits; eauto; try refl.\n      - esplits; eauto; try refl.\n      - esplits; eauto; try refl.\n      - esplits; eauto; try refl.\n    Qed.\n\n\n    (* step_disjoint *)\n\n    Lemma program_step_disjoint\n          e lc1 gl1 lc2 gl2 lc\n          (STEP: program_step e lc1 gl1 lc2 gl2)\n          (WF1: Local.wf lc1 gl1)\n          (GL1: Global.wf gl1)\n          (DISJOINT1: Local.disjoint lc1 lc)\n          (WF: Local.wf lc gl1):\n      <<DISJOINT2: Local.disjoint lc2 lc>> /\\\n      <<WF: Local.wf lc gl2>>.\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      - esplits; eauto.\n      - esplits; eauto.\n      - esplits; eauto.\n    Qed.\n\n    Lemma program_step_promises\n          e lc1 gl1 lc2 gl2\n          (STEP: program_step e lc1 gl1 lc2 gl2):\n      BoolMap.le (Local.promises lc2) (Local.promises lc1) /\\\n      BoolMap.le (Global.promises gl2) (Global.promises gl1).\n    Proof.\n      inv STEP; ss; try by (inv LOCAL; ss).\n      - inv LOCAL. inv STEP. ss.\n      - inv LOCAL. inv STEP. inv FULFILL; ss.\n        split; eauto using BoolMap.remove_le.\n      - inv LOCAL1. inv LOCAL2. inv STEP. inv STEP0. inv FULFILL; ss.\n        split; eauto using BoolMap.remove_le.\n    Qed.\n\n    Lemma program_step_promises_minus\n          e lc1 gl1 lc2 gl2\n          (STEP: program_step e lc1 gl1 lc2 gl2):\n      BoolMap.minus (Global.promises gl1) (Local.promises lc1) =\n      BoolMap.minus (Global.promises gl2) (Local.promises lc2).\n    Proof.\n      inv STEP; ss; try by (inv LOCAL; ss).\n      - inv LOCAL. inv STEP. ss.\n      - inv LOCAL. inv STEP. ss.\n        eapply Promises.fulfill_minus; eauto.\n      - inv LOCAL1. inv LOCAL2. inv STEP. inv STEP0. ss.\n        eapply Promises.fulfill_minus; eauto.\n    Qed.\n\n    Lemma program_step_promises_bot\n          e lc1 gl1 lc2 gl2\n          (STEP: program_step e lc1 gl1 lc2 gl2)\n          (PROMISES: Local.promises lc1 = BoolMap.bot):\n      Local.promises lc2 = BoolMap.bot.\n    Proof.\n      inv STEP; try inv LOCAL; ss; try inv STEP; ss.\n      - inv FULFILL; ss.\n        exploit BoolMap.remove_get0; try exact REMOVE. i. des.\n        rewrite PROMISES in *. ss.\n      - inv LOCAL1. inv LOCAL2. inv STEP. inv STEP0. ss.\n        inv FULFILL; ss.\n        exploit BoolMap.remove_get0; try exact REMOVE. i. des.\n        rewrite PROMISES in *. ss.\n    Qed.\n\n    Lemma program_step_gpromises_bot\n          e lc1 gl1 lc2 gl2\n          (STEP: program_step e lc1 gl1 lc2 gl2)\n          (PROMISES: Global.promises gl1 = BoolMap.bot):\n      Global.promises gl2 = BoolMap.bot.\n    Proof.\n      inv STEP; try inv LOCAL; ss; try inv STEP; ss.\n      - inv FULFILL; ss.\n        exploit BoolMap.remove_get0; try exact GREMOVE. i. des.\n        rewrite PROMISES in *. ss.\n      - inv LOCAL1. inv LOCAL2. inv STEP. inv STEP0. ss.\n        inv FULFILL; ss.\n        exploit BoolMap.remove_get0; try exact GREMOVE. i. des.\n        rewrite PROMISES in *. ss.\n    Qed.\n\n    Lemma program_step_reserves\n          e lc1 gl1 lc2 gl2\n          (STEP: program_step e lc1 gl1 lc2 gl2):\n      Local.reserves lc2 = Local.reserves lc1.\n    Proof.\n      inv STEP; try inv LOCAL; ss; try inv STEP; ss.\n      inv LOCAL1. inv LOCAL2. inv STEP. inv STEP0. ss.\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 step (e:ThreadEvent.t): forall (e1 e2:Thread.t lang), Prop :=\n    | step_intro\n        st1 lc1 gl1\n        st2 lc2 gl2\n        (STATE: (Language.step lang) (ThreadEvent.get_program_event e) st1 st2)\n        (LOCAL: SCLocal.program_step L e lc1 gl1 lc2 gl2):\n        step e (Thread.mk lang st1 lc1 gl1) (Thread.mk lang st2 lc2 gl2)\n    .\n    Hint Constructors step: core.\n\n    Definition all_step := union step.\n    Hint Unfold all_step: core.\n\n\n    (* future *)\n\n    Lemma step_future\n          e e1 e2\n          (STEP: step 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. ss. eapply SCLocal.program_step_future; eauto.\n    Qed.\n\n    Lemma rtc_all_step_future\n          e1 e2\n          (STEPS: rtc all_step 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      revert LC_WF1 GL_WF1. 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\n    (* disjoint *)\n\n    Lemma step_disjoint\n          e e1 e2 lc\n          (STEP: step 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.\n      eapply SCLocal.program_step_disjoint; eauto.\n    Qed.\n\n\n    (* promises *)\n\n    Lemma step_promises\n          e th1 th2\n          (STEP: step e th1 th2):\n      BoolMap.le (Local.promises (Thread.local th2)) (Local.promises (Thread.local th1)) /\\\n      BoolMap.le (Global.promises (Thread.global th2)) (Global.promises (Thread.global th1)).\n    Proof.\n      inv STEP. s.\n      eapply SCLocal.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 SCLocal.program_step_promises_minus; eauto.\n    Qed.\n  End SCThread.\nEnd SCThread.\n\n\nModule SCConfiguration.\n  Section SCConfiguration.\n    Variable L: Loc.t -> bool.\n\n    Variant estep: forall (e: ThreadEvent.t) (tid: Ident.t) (c1 c2: Configuration.t), Prop :=\n    | estep_intro\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: SCThread.step L e\n                             (Thread.mk _ st1 lc1 (Configuration.global c1))\n                             (Thread.mk _ st2 lc2 gl2)):\n      estep e tid c1 (Configuration.mk (IdentMap.add tid (existT _ _ st2, lc2) (Configuration.threads c1)) gl2)\n    .\n    Hint Constructors estep: core.\n\n    Variant step: forall (e: MachineEvent.t) (tid: Ident.t) (c1 c2: Configuration.t), Prop :=\n    | step_instro\n        e tid c1 c2\n        (STEP: estep e tid c1 c2):\n        step (ThreadEvent.get_machine_event_pf e) tid c1 c2\n    .\n    Hint Constructors step: core.\n\n    Variant all_step (c1 c2: Configuration.t): Prop :=\n    | all_step_intro\n        e tid\n        (STEP: estep e tid c1 c2)\n    .\n    Hint Constructors all_step: core.\n\n    Lemma estep_future\n          e tid c1 c2\n          (STEP: estep e tid c1 c2)\n          (WF1: Configuration.wf c1):\n      <<WF2: Configuration.wf c2>> /\\\n      <<GL_FUTURE: Global.future (Configuration.global c1) (Configuration.global c2)>>.\n    Proof.\n      inv WF1. inv WF. inv STEP; s.\n      exploit THREADS; ss; eauto. i.\n      exploit SCThread.step_future; eauto. s. i. des.\n      splits; eauto.\n      econs; ss. econs.\n      - i. Configuration.simplify.\n        + exploit THREADS; try apply TH1; eauto. i. des.\n          exploit SCThread.step_disjoint; eauto. s. i. des.\n          symmetry. auto.\n        + exploit THREADS; try apply TH2; eauto. i. des.\n          exploit SCThread.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.step_disjoint; eauto. s. i. des.\n        auto.\n      - i. destruct (Local.promises lc2 loc) eqn:LGET.\n        + exists tid, lang, st2, lc2. splits; ss.\n          rewrite IdentMap.Facts.add_o. condtac; ss.\n        + exploit SCThread.step_promises_minus; try exact STEP0. s. i.\n          eapply equal_f in x1.\n          revert x1. unfold BoolMap.minus. rewrite GET, LGET. s. i.\n          destruct (Global.promises (Configuration.global c1) loc) eqn:GET1; ss.\n          destruct (Local.promises lc1 loc) eqn:LGET1; ss.\n          exploit PROMISES; eauto. i. des.\n          exists tid0, lang0, st, lc. splits; ss.\n          rewrite IdentMap.Facts.add_o. condtac; ss. subst. congr.\n    Qed.\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      <<GL_FUTURE: Global.future (Configuration.global c1) (Configuration.global c2)>>.\n    Proof.\n      inv STEP. eauto using estep_future.\n    Qed.\n\n    Lemma all_step_future\n          c1 c2\n          (STEP: all_step c1 c2)\n          (WF1: Configuration.wf c1):\n      <<WF2: Configuration.wf c2>> /\\\n      <<GL_FUTURE: Global.future (Configuration.global c1) (Configuration.global c2)>>.\n    Proof.\n      inv STEP. eapply step_future; eauto.\n    Qed.\n\n    Lemma rtc_all_step_future\n          c1 c2\n          (STEPS: rtc all_step c1 c2)\n          (WF1: Configuration.wf c1):\n      <<WF2: Configuration.wf c2>> /\\\n      <<GL_FUTURE: Global.future (Configuration.global c1) (Configuration.global c2)>>.\n    Proof.\n      revert WF1. induction STEPS; i.\n      { splits; auto. refl. }\n      { hexploit all_step_future; eauto.\n        i. des. hexploit IHSTEPS; eauto. i. des. splits; eauto. etrans; eauto.\n      }\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 th.(Thread.local) th.(Thread.global).(Global.memory) loc>>).\n\n    Definition race_steps (c: Configuration.t) (tid: Ident.t): Prop :=\n      exists lang st1 lc1,\n        (<<TID: IdentMap.find tid (Configuration.threads c) = Some (existT _ lang st1, lc1)>>) /\\\n        (<<SCRACE: race (Thread.mk _ st1 lc1 c.(Configuration.global))>>).\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. inv STEP. econs; eauto.\n    Qed.\n  End SCRace.\nEnd SCRace.\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/ldrfsc/SCStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.3522017752483203, "lm_q1q2_score": 0.2563942495990356}}
{"text": "Require Import NArith.\nRequire Import Word.\n\n(* This module can be instantiated into some concrete ways and some more abstract ways. *)\n(* A word can be a tuple of 256 booleans. *)\n(* Alternatively a word can be thought of as some abstract values.\n * This would be interesting in bytecode analysis tools.\n *)\n(* Many aspects of the EVM semantics do not care how words are represented. *)\nModule Make (W : Word).\nExport W.\n\nDefinition bool_to_word (b : bool) :=\n  if b then word_one else word_zero.\n\nArguments bool_to_word b /.\n\nOpen Scope list_scope.\n\nDefinition drop_one_element {A : Type} (lst : list A) :=\n  match lst with\n  | nil => nil\n  | _ :: tl => tl\n  end.\n\n(***\n *** Some abstract view over EVM\n ***)\n\n(** This part is hugely incomplete.  It misses many instructions and\n    gas economy.  They will be added as necessary. *)\n\n(* An element of type [call_arguments] describes\n   arguments that an execution can attach to\n   [CALL] *)\nRecord call_arguments :=\n    { callarg_gaslimit    : word\n    ; callarg_code        : address\n    ; callarg_recipient   : address\n    ; callarg_value       : word\n    ; callarg_data        : list byte\n    ; callarg_output_begin : word\n    ; callarg_output_size : word\n    }.\n\n(* An element of type [return_result] is a sequence of bytes that\n   [RETURN] can return. *)\nRecord return_result :=\n  { return_data : list byte;\n    return_balance : address -> word\n  }.\n\n(* TODO: add something similar to return_balance to\n   failures *)\n\n(* An element of type [call_env] describes\n   an environment where contract is executed\n *)\nRecord call_env :=\n  { callenv_gaslimit : word\n  ; callenv_value : word\n  ; callenv_data : list byte\n  ; callenv_caller : address\n  ; callenv_timestap : word\n  ; callenv_blocknum : word\n  ; callenv_balance : address -> word\n  }.\n\n\nInductive contract_action :=\n| ContractCall : call_arguments -> contract_action\n  (* [Call args continuation] is the behavior of [CALL] instruction\n      together with all behaviors shown by the account after the [CALL].\n     [args] represents the parameters of a call.\n     [continuation] represents the behavior shown after the [CALL]\n     instruction.  See the comment at [after_call_behavior].\n   *)\n| ContractFail : contract_action\n  (* [Fail] is the behavior of runtime errors (e.g. jumping to an invalid\n     program counter / lack of gas *)\n| ContractSuicide : contract_action\n| ContractReturn : list byte (* returned data *) -> contract_action.\n  (* [Return ret next] is the behavior of a [RETURN], [STOP] instruction.\n     Upon the next call with [env], [next env] will be the contract behavior.\n   *)\n\n\n(* An element of type [response_to_world] describes a strategy of a contract\n   that can respond when\n   1. it is called from the world\n   2. it receives a callee return from the world\n   3. it receives a callee failure from the world.\n   Initially, when the contract has not called any other accounts,\n   the points 2. and 3. are useless.\n *)\nCoInductive response_to_world :=\n| Respond :\n    (call_env -> contract_behavior) (* what to do if called / or re-entered *) ->\n    (return_result -> contract_behavior) (* what to do if the callee returns (if exists) *) ->\n    (contract_behavior) (* what to do if the callee's execution fails *) ->\n    response_to_world\n\n\n(* An element of type [contract_behavior] describes a behavior of an\n   already called contract.  A contract has four ways of giving the\n   control back to the world.\n   1. returning\n   2. failing\n   3. commiting suicide\n   4. calling some account\n *)\nwith contract_behavior :=\n| ContractAction : contract_action -> response_to_world -> contract_behavior\n.\n\n\n(* A useful function for reasoning.\n   I was looking at http://adam.chlipala.net/cpdt/html/Coinductive.html\n   around [frob].\n *)\nDefinition contract_action_expander (ca : contract_behavior) :=\n  match ca with ContractAction a b => ContractAction a b end.\n\nDefinition response_expander (r : response_to_world) :=\n  match r with Respond f g h => Respond f g h end.\n\nLemma contract_action_expander_eq :\n  forall ca, contract_action_expander ca = ca.\nProof.\n  intro ca.\n  case ca.\n  auto.\nQed.\n\nLemma response_expander_eq :\n  forall r, r = response_expander r.\nProof.\n  intro r.\n  case r.\n  auto.\nQed.\n\n(********* What the world does on an account ***********)\n\nInductive world_action :=\n| WorldCall : call_env -> world_action\n| WorldRet  : return_result -> world_action\n| WorldFail : world_action\n.\n\nDefinition world := list world_action.\n\n\n(********\n When [world] and [respond_to_world] meet,\n they produce a sequence of events *)\n\nInductive action :=\n| ActionByWorld : world_action -> action\n| ActionByContract : contract_action -> action.\n\nDefinition history := list action.\n\n\n(******** World and the contract interact to produce a history ****)\n\nFixpoint specification_run (w : world) (r : response_to_world) : history :=\n  match w, r with\n  | nil, _ => nil\n  | WorldCall call :: world_cont, Respond f _ _ =>\n    match f call with\n    | ContractAction cact contract_cont =>\n      ActionByWorld (WorldCall call) ::\n      ActionByContract cact ::\n      specification_run world_cont contract_cont\n    end\n  | WorldRet ret :: world_cont, Respond _ r _ =>\n    match (r ret) with\n      ContractAction cact contract_cont =>\n      ActionByWorld (WorldRet ret) ::\n      ActionByContract cact ::\n      specification_run world_cont contract_cont\n    end\n  | WorldFail :: world_cont, Respond _ _ (ContractAction cact contract_cont) =>\n    ActionByWorld WorldFail ::\n    ActionByContract cact ::\n    specification_run world_cont contract_cont\n  end.\n\n(***\n *** Some more concrete view on EVM.\n *** This part is for interpreting bytecodes in terms of the abstract view above.\n ***)\n\n(**\n ** Instructions\n **)\n\nInductive instruction :=\n| PUSH1 : word -> instruction\n| PUSH2 : word -> instruction\n| PUSH32 : word -> instruction\n| SLOAD\n| SSTORE\n| JUMP\n| JUMPI\n| JUMPDEST\n| CALLDATASIZE\n| CALLDATALOAD\n| CALLVALUE\n| CALLER\n| ADD\n| SUB\n| ISZERO\n| CALL\n| RETURN\n| STOP\n| DUP1\n| POP\n| GASLIMIT\n| instr_GT\n| instr_EQ\n.\n\n(**\n ** Program\n **)\n\nDefinition program := list instruction.\n\nRequire Import Recdef.\n\nFunction drop_bytes (prog : list instruction) (bytes : N)\n         :=\n  match prog, bytes with\n  | _, N0 => prog\n  | PUSH1 v :: tl, _ =>\n    drop_bytes tl (bytes - 2)\n  | PUSH2 v :: tl, _ =>\n    drop_bytes tl (bytes - 3)\n  | _ :: tl, _ =>\n    drop_bytes tl (bytes - 1)\n  | nil, _ => nil\n  end.\n\n\n(**\n ** Execution Environments\n **)\n\nRecord variable_env :=\n  { venv_stack : list word\n  ; venv_memory : memory_state\n  ; venv_storage : storage\n  ; venv_prg_sfx : list instruction\n  ; venv_balance : address -> word (* does this blong here?*)\n  ; venv_caller : address\n  ; venv_value_sent : word\n  ; venv_data_sent : list byte\n  (* TODO: add the sequence of executed instructions.\n     would be useful for calculating the gas *)\n\n  (* These are necessary when throwing. *)\n  ; venv_storage_at_call : storage\n  ; venv_balance_at_call : address -> word\n\n  (* TODO: use venv_balance_at_call somewhere *)\n  }.\n\n(* [update_balance adr v original] is similar to [original] except\n   that [adr] is mapped to [v].\n*)\nDefinition update_balance (a : address) (newbal : word -> word)\n           (orig : address -> word) : (address -> word) :=\n  fun (query : address) =>\n    if address_eq a query then newbal (orig query) else orig query.\n\nLemma get_update_balance :\n  forall addr f original,\n    update_balance addr f original addr = f (original addr).\nProof.\n  intros addr value original.\n  unfold update_balance.\n  rewrite address_eq_refl.\n  auto.\nQed.\n\nRecord constant_env :=\n  { cenv_program : list instruction;\n    cenv_this : address\n  }.\n\n\n(** Initialize variable_env variable_env . *)\nDefinition init_variable_env (s : storage) (bal : address -> word)\n           (caller : address)\n           (cenv : constant_env) (value : word) (data : list byte) :=\n  {|\n    venv_stack := nil ;\n    venv_memory := empty_memory ;\n    venv_prg_sfx := cenv.(cenv_program) ;\n    venv_storage := s ;\n    venv_balance := bal ;\n    venv_caller := caller ;\n    venv_value_sent := value ;\n    venv_data_sent := data ;\n    venv_storage_at_call := s ;\n    venv_balance_at_call := bal ;\n  |}.\n\n\n(**\n **  Meaning of an instruction.\n **)\n\nInductive instruction_result :=\n| InstructionContinue : variable_env -> instruction_result\n| InstructionToWorld : contract_action -> option variable_env (* to be pushed into the call stack *) -> instruction_result\n| InstructionInvalid : instruction_result (* PUSH1 with more than 255 *)\n.\n\nDefinition instruction_failure_result :=\n  InstructionToWorld ContractFail None.\n\nDefinition instruction_return_result (x: list byte) :=\n  InstructionToWorld (ContractReturn x) None.\n\n\nDefinition venv_update_stack (new_stack : list word) (v : variable_env) :=\n  {|\n    venv_stack := new_stack ;\n    venv_memory := v.(venv_memory) ;\n    venv_storage := v.(venv_storage) ;\n    venv_prg_sfx := v.(venv_prg_sfx) ;\n    venv_balance := v.(venv_balance) ;\n    venv_caller := v.(venv_caller) ;\n    venv_value_sent := v.(venv_value_sent) ;\n    venv_data_sent := v.(venv_data_sent) ;\n    venv_storage_at_call := v.(venv_storage_at_call) ;\n    venv_balance_at_call := v.(venv_balance_at_call)\n  |}.\n\nArguments venv_update_stack new_stack v /.\n\nDefinition venv_update_balance (new_balance : address -> word) (v : variable_env) :=\n  {|\n    venv_stack := v.(venv_stack) ;\n    venv_memory := v.(venv_memory) ;\n    venv_storage := v.(venv_storage) ;\n    venv_prg_sfx := v.(venv_prg_sfx) ;\n    venv_balance := new_balance ;\n    venv_caller := v.(venv_caller) ;\n    venv_value_sent := v.(venv_value_sent) ;\n    venv_data_sent := v.(venv_data_sent) ;\n    venv_storage_at_call := v.(venv_storage_at_call) ;\n    venv_balance_at_call := v.(venv_balance_at_call)\n  |}.\n\nDefinition venv_advance_pc (v : variable_env) :=\n  {|\n    venv_stack := v.(venv_stack) ;\n    venv_memory := v.(venv_memory) ;\n    venv_storage := v.(venv_storage) ;\n    venv_prg_sfx := drop_one_element v.(venv_prg_sfx) ;\n    venv_balance := v.(venv_balance) ;\n    venv_caller := v.(venv_caller) ;\n    venv_value_sent := v.(venv_value_sent) ;\n    venv_data_sent := v.(venv_data_sent) ;\n    venv_storage_at_call := v.(venv_storage_at_call) ;\n    venv_balance_at_call := v.(venv_balance_at_call)\n  |}.\n\nArguments venv_advance_pc v /.\n\nRequire Import List.\n\nFixpoint venv_pop_stack (n : nat) (v : variable_env) :=\n  match n with\n  | O => v\n  | S m =>\n  venv_pop_stack m\n    (venv_update_stack\n      (tl v.(venv_stack)) v)\n  end.\n\nDefinition venv_stack_top (v : variable_env) : option word :=\n  match v.(venv_stack) with\n  | h :: _ => Some h\n  | _ => None\n  end.\n\nDefinition venv_change_sfx (pos : N) (v : variable_env)\n  (c : constant_env) : variable_env :=\n  {|\n    venv_stack := v.(venv_stack) ;\n    venv_memory := v.(venv_memory);\n    venv_storage := v.(venv_storage);\n    venv_prg_sfx := drop_bytes c.(cenv_program) pos ;\n    venv_balance := v.(venv_balance);\n    venv_caller := v.(venv_caller);\n    venv_value_sent := v.(venv_value_sent);\n    venv_data_sent := v.(venv_data_sent);\n    venv_storage_at_call := v.(venv_storage_at_call) ;\n    venv_balance_at_call := v.(venv_balance_at_call)\n  |}.\n\nArguments venv_change_sfx pos v c /.\n\nDefinition function_update (addr : word) (val : word) (f : word -> word) : (word -> word) :=\n  fun x => (if word_eq x addr then val else f x).\n\nDefinition venv_update_storage (idx : word) (val : word) (v : variable_env)\n           : variable_env :=\n  {|\n    venv_stack := v.(venv_stack) ;\n    venv_memory := v.(venv_memory);\n    venv_storage := storage_store idx val v.(venv_storage);\n    venv_prg_sfx := v.(venv_prg_sfx);\n    venv_balance := v.(venv_balance);\n    venv_caller := v.(venv_caller);\n    venv_value_sent := v.(venv_value_sent);\n    venv_data_sent := v.(venv_data_sent);\n    venv_storage_at_call := v.(venv_storage_at_call) ;\n    venv_balance_at_call := v.(venv_balance_at_call)\n  |}.\n\nDefinition venv_update_whole_storage (new_storage : storage) (v : variable_env)\n           : variable_env :=\n  {|\n    venv_stack := v.(venv_stack) ;\n    venv_memory := v.(venv_memory);\n    venv_storage := new_storage;\n    venv_prg_sfx := v.(venv_prg_sfx);\n    venv_balance := v.(venv_balance);\n    venv_caller := v.(venv_caller);\n    venv_value_sent := v.(venv_value_sent);\n    venv_data_sent := v.(venv_data_sent);\n    venv_storage_at_call := v.(venv_storage_at_call) ;\n    venv_balance_at_call := v.(venv_balance_at_call)\n  |}.\n\nDefinition venv_first_instruction (v : variable_env) : option instruction :=\n  hd_error v.(venv_prg_sfx).\n\n(** a general functoin for defining an instruction that\n    pushes one element to the stack *)\n\nDefinition stack_0_0_op (v : variable_env) (c : constant_env)\n  : instruction_result :=\n  InstructionContinue (venv_advance_pc v).\n\nDefinition stack_0_1_op (v : variable_env) (c : constant_env) (w : word) : instruction_result :=\n  InstructionContinue\n    (venv_advance_pc (venv_update_stack (w :: v.(venv_stack)) v)).\n\n\n(* These are just assumed for my laziness. *)\nDefinition stack_1_1_op (v: variable_env) (c : constant_env)\n                    (f : word -> word) : instruction_result :=\n  match v.(venv_stack) with\n    | nil => instruction_failure_result\n    | h :: t =>\n      InstructionContinue\n        (venv_advance_pc (venv_update_stack (f h :: t) v))\n  end.\n\nDefinition stack_1_2_op (v: variable_env) (c : constant_env)\n           (f : word -> (word (* new head *) * word (* new second*) ))\n  : instruction_result :=\n  match v.(venv_stack) with\n    | nil => instruction_failure_result\n    | h :: t =>\n      match f h with\n        (new0, new1) =>\n        InstructionContinue\n          (venv_advance_pc (venv_update_stack (new0 :: new1 :: t) v))\n      end\n  end.\n\nDefinition stack_2_1_op (v : variable_env) (c : constant_env)\n                    (f : word -> word -> word) : instruction_result :=\n  match v.(venv_stack) with\n    | operand0 :: operand1 :: rest =>\n      InstructionContinue (venv_advance_pc\n                             (venv_update_stack (f operand0 operand1 :: rest) v))\n    | _ => instruction_failure_result\n  end.\n\nDefinition sload (v : variable_env) (idx : word) : word :=\n  storage_load idx v.(venv_storage).\n\nArguments sload v idx /.\n\nDefinition sstore (v : variable_env) (c : constant_env) : instruction_result :=\n  match v.(venv_stack) with\n    | addr :: val :: stack_tail =>\n      InstructionContinue\n        (venv_advance_pc\n           (venv_update_stack stack_tail\n                              (venv_update_storage addr val v)))\n    | _ => instruction_failure_result\n  end.\n\nDefinition jump (v : variable_env) (c : constant_env) : instruction_result :=\n  match venv_stack_top v with\n  | None => instruction_failure_result\n  | Some pos =>\n    let v_new := venv_change_sfx (N_of_word pos) (venv_pop_stack 1 v) c in\n    match venv_first_instruction v_new with\n    | Some JUMPDEST =>\n        InstructionContinue v_new\n    | _ => instruction_failure_result\n    end\n  end.\n\nArguments jump v c /.\n\nDefinition jumpi (v : variable_env) (c : constant_env) : instruction_result :=\n  match v.(venv_stack) with\n  | pos :: cond :: rest =>\n    if word_iszero cond then\n      InstructionContinue (venv_advance_pc (venv_pop_stack 2 v))\n    else\n      jump (venv_update_stack (pos :: rest) v) c (* this has to change when gas is considered  *)\n  | _ => instruction_failure_result\n  end.\n\nArguments jumpi v c /.\n\n\nDefinition datasize (v : variable_env) : word :=\n  word_of_nat (List.length v.(venv_data_sent)).\n\nAxiom list_slice : N -> N -> list byte -> word.\n\nDefinition cut_data (v : variable_env) (idx: word) : word :=\n  list_slice (N_of_word idx) 32 v.(venv_data_sent).\n\n(* currently this is not very true: to fix, add the sequence of executed instructions in venv. *)\nAxiom gas_limit : variable_env -> word.\n\n(* TODO: this should fail for various reasons.  lack of balance. *)\nDefinition call (v : variable_env) (c : constant_env) : instruction_result :=\n  match v.(venv_stack) with\n  | e0 :: e1 :: e2 :: e3 :: e4 :: e5 :: e6 :: rest =>\n    if word_smaller (v.(venv_balance) (c.(cenv_this))) e2 then\n      InstructionToWorld ContractFail None\n    else\n    InstructionToWorld\n      (ContractCall\n         {|\n           callarg_gaslimit := e0 ;\n           callarg_code := address_of_word e1 ;\n           callarg_recipient := address_of_word e1 ;\n           callarg_value := e2 ;\n           callarg_data := cut_memory e3 e4 v.(venv_memory) ;\n           callarg_output_begin := e5 ;\n           callarg_output_size := e6 ;\n         |})\n      (Some (* TODO: this part should be abstracted away *)\n         {|\n           venv_stack := rest;\n           venv_memory := v.(venv_memory);\n           venv_storage := v.(venv_storage);\n           venv_prg_sfx := drop_one_element (v.(venv_prg_sfx));\n           venv_balance :=\n             (* This is dealt in build_venv_called.\n                (update_balance (address_of_word e1)\n                             (fun orig => word_add orig e2) *)\n             (update_balance c.(cenv_this)\n                (fun orig => word_sub orig e2) v.(venv_balance));\n           venv_caller := v.(venv_caller);\n           venv_value_sent := v.(venv_value_sent) ;\n           venv_data_sent := v.(venv_data_sent) ;\n           venv_storage_at_call := v.(venv_storage_at_call) ;\n           venv_balance_at_call := v.(venv_balance_at_call)\n         |}\n      )\n  | _ =>\n    InstructionToWorld ContractFail None (* this environment should disappear *)\n  end.\n\nArguments call v c /.\n\n\nDefinition venv_returned_bytes v :=\n  match v.(venv_stack) with\n    | e0 :: e1 :: _ => cut_memory e0 e1 (v.(venv_memory))\n    | _ => nil\n  end.\n\nArguments venv_returned_bytes v /.\n\nDefinition ret (v : variable_env) (c : constant_env) : instruction_result :=\n  InstructionToWorld (ContractReturn (venv_returned_bytes v) )\n                     None.\n\nDefinition stop (v : variable_env) (c : constant_env) : instruction_result :=\n  InstructionToWorld (ContractReturn nil)\n                     None.\n\nDefinition pop (v : variable_env) (c : constant_env) : instruction_result :=\n  InstructionContinue\n    (venv_advance_pc (venv_update_stack\n       (tail v.(venv_stack))\n       v)).\n\nRequire Import Coq.Program.Basics.\n\nDefinition instruction_sem (v : variable_env) (c : constant_env) (i : instruction)\n  : instruction_result :=\n  match i with\n  | PUSH1 w =>\n    stack_0_1_op v c (word_mod w (word_of_N 256%N))\n  | PUSH2 w =>\n    stack_0_1_op v c (word_mod w (word_mul (word_of_N 256%N) (word_of_N 256%N)))\n  | PUSH32 w =>\n    stack_0_1_op v c w\n  | SLOAD => stack_1_1_op v c (sload v)\n  | SSTORE => sstore v c\n  | JUMPI => jumpi v c\n  | JUMP => jump v c\n  | JUMPDEST => stack_0_0_op v c\n  | CALLDATASIZE => stack_0_1_op v c (datasize v)\n  | CALLDATALOAD => stack_1_1_op v c (cut_data v)\n  | CALLVALUE => stack_0_1_op v c v.(venv_value_sent)\n  | CALLER => stack_0_1_op v c (word_of_address v.(venv_caller))\n  | ADD => stack_2_1_op v c word_add\n  | SUB => stack_2_1_op v c word_sub\n  | ISZERO => stack_1_1_op v c (compose bool_to_word word_iszero)\n  | CALL => call v c\n  | RETURN => ret v c\n  | STOP => stop v c\n  | DUP1 => stack_1_2_op v c (fun a => (a, a))\n  | POP => pop v c\n  | GASLIMIT => stack_0_1_op v c (gas_limit v)\n  | instr_GT => stack_2_1_op v c (fun a b => bool_to_word (word_smaller b a))\n  | instr_EQ => stack_2_1_op v c (fun a b => bool_to_word (word_eq a b))\n  end.\n\nInductive program_result :=\n| ProgramStepRunOut : program_result\n| ProgramToWorld : contract_action ->\n                   storage (* updated storage *) ->\n                   (address -> word) (* updated balance *) ->\n                   option variable_env (* to be pushed in the call stack *) -> program_result\n| ProgramInvalid : program_result\n.\n\n\nFixpoint program_sem (v : variable_env) (c :constant_env) (steps : nat)\n  : program_result :=\n  match steps with\n    | O => ProgramStepRunOut\n    | S remaining_steps =>\n      match v.(venv_prg_sfx) with\n      | nil => ProgramToWorld ContractFail v.(venv_storage_at_call) v.(venv_balance_at_call) None\n      | i :: _ =>\n        match instruction_sem v c i with\n        | InstructionContinue new_v =>\n          program_sem new_v c remaining_steps\n        | InstructionToWorld ContractFail opt_pushed_v =>\n          ProgramToWorld ContractFail v.(venv_storage_at_call) v.(venv_balance_at_call) opt_pushed_v\n        | InstructionToWorld (ContractCall args) (Some new_v) =>\n          ProgramToWorld (ContractCall args) new_v.(venv_storage) new_v.(venv_balance) (Some new_v)\n        | InstructionToWorld a opt_pushed_v =>\n          ProgramToWorld a v.(venv_storage) v.(venv_balance) opt_pushed_v\n        (* TODO: change the balance when suicide *)\n        | InstructionInvalid => ProgramInvalid\n        end\n      end\n  end.\n\n\n(****** This program semantics has to be lifted to a history *****)\n\nRecord account_state :=\n  { account_address : address\n  ; account_storage : storage\n  ; account_code : list instruction\n  ; account_balance : word\n    (* this duplicates from the global balance function, but this field\n       is necessary for writing invariants involving the balance.\n       The balance of the account does not change unless it is called.\n     *)\n  ; account_ongoing_calls : list variable_env\n  }.\n\nDefinition account_state_update_storage new_st orig :=\n  {| account_address := orig.(account_address);\n     account_code    := orig.(account_code);\n     account_storage := new_st;\n     account_balance := orig.(account_balance);\n     account_ongoing_calls := orig.(account_ongoing_calls)\n  |}.\n\nArguments account_state_update_storage new_st orig /.\n\n(** The ideas is that an account state defines a response_to_world **)\n\nDefinition build_venv_called (a : account_state) (env : call_env) :\n  variable_env :=\n  {|\n      venv_stack := nil ;\n      venv_memory := empty_memory;\n      venv_prg_sfx := a.(account_code) ;\n      venv_storage := a.(account_storage) ;\n      venv_balance :=\n        update_balance a.(account_address)\n                           (fun _ => (word_add a.(account_balance) env.(callenv_value)))\n                           env.(callenv_balance) ;\n      venv_caller := env.(callenv_caller) ;\n      venv_value_sent := env.(callenv_value) ;\n      venv_data_sent := env.(callenv_data) ;\n      venv_storage_at_call := a.(account_storage) ;\n      venv_balance_at_call :=\n        (* although there shouldn't be an update,\n         * the environment cannot change the account's balance.\n         * this 'update_balance' should be a NO-OP\n         *)\n        update_balance a.(account_address)\n                           (fun _ => a.(account_balance))\n                           env.(callenv_balance) ;\n    |}.\n\nArguments build_venv_called a env /.\n\nDefinition build_cenv (a : account_state) :\n    constant_env :=\n    {|\n      cenv_program := a.(account_code) ;\n      cenv_this := a.(account_address)\n   |}.\n\n\n(* TODO: update the storage according to a *)\n(* TODO: udpate the balance according to return_result *)\nDefinition build_venv_returned\n  (a : account_state) (r : return_result) : option variable_env :=\n  match a.(account_ongoing_calls) with\n  | nil => None\n  | recovered :: _ =>\n    Some\n      (venv_update_whole_storage a.(account_storage)\n      (venv_update_balance\n         (update_balance a.(account_address) (fun _ => a.(account_balance)) r.(return_balance))\n      (venv_update_stack (word_one :: recovered.(venv_stack))\n                         recovered)))\n         (* TODO: actually, need to update the memory *)\n  end.\n\nArguments build_venv_returned a r /.\n\n(* Since the callee failed, the balance should not be updated. *)\nDefinition build_venv_fail\n           (a : account_state) : option variable_env :=\n  match a.(account_ongoing_calls) with\n  | nil => None\n  | recovered :: _ =>\n    Some\n      (* TODO: the balance should be recovered.\n       * When a call fails, the sent-along value\n       * should be returned.\n       *)\n      (venv_update_stack (word_zero :: recovered.(venv_stack)) recovered)\n  end.\n\nArguments build_venv_fail a /.\n\nDefinition account_state_pop_ongoing_call (orig : account_state) :=\n  {| account_address := orig.(account_address);\n     account_storage := orig.(account_storage);\n     account_code := orig.(account_code);\n     account_balance := orig.(account_balance);\n     account_ongoing_calls := tail (orig.(account_ongoing_calls))\n  |}.\n\nArguments account_state_pop_ongoing_call orig /.\n\n(* TODO: use venv widely and remove other arguments *)\nDefinition update_account_state (prev : account_state) (act: contract_action)\n           (st : storage) (bal : address -> word)\n           (v_opt : option variable_env) : account_state :=\n        match v_opt with\n        | None =>\n          {|\n            account_address := prev.(account_address) ;\n            account_storage := st ;\n            account_balance := bal (prev.(account_address));\n            account_code := prev.(account_code) ;\n            account_ongoing_calls := prev.(account_ongoing_calls)\n          |}\n        | Some pushed =>\n          {|\n            account_address := prev.(account_address) ;\n            account_storage := st ;\n            account_balance := bal (prev.(account_address));\n            account_code := prev.(account_code) ;\n            account_ongoing_calls := pushed :: prev.(account_ongoing_calls)\n          |}\n        end.\n\nDefinition program_goes_to_world_and (r : program_result) P :=\n  match r with\n  | ProgramStepRunOut => True\n  | ProgramToWorld act st bal pushed_venv =>\n    P act st bal pushed_venv\n  | _ => False\n  end.\n\nDefinition respond_to_call_correctly c a I account_state_responds_to_world :=\n      forall (callenv : call_env)\n          act continuation,\n          I (build_venv_called a callenv) (build_cenv a) /\\\n          (I (build_venv_called a callenv) (build_cenv a) ->\n           c callenv = ContractAction act continuation ->\n           forall steps,\n               let r := program_sem (build_venv_called a callenv) (build_cenv a) steps in\n               r = ProgramStepRunOut \\/\n               exists st, exists bal, exists pushed_venv,\n                       r = ProgramToWorld act st bal pushed_venv /\\\n                       account_state_responds_to_world\n                         (account_state_update_storage st (update_account_state a act st bal pushed_venv))\n                         continuation I).\n\n\nCheck respond_to_call_correctly.\n\nDefinition respond_to_return_correctly (r : return_result -> contract_behavior)\n           (a : account_state) (I :variable_env -> constant_env -> Prop)\n           account_state_responds_to_world :=\n  forall (rr : return_result) venv continuation act,\n     Some venv = build_venv_returned a rr ->\n     r rr = ContractAction act continuation ->\n     (forall steps,\n          let r := program_sem venv (build_cenv a) steps in\n          r = ProgramStepRunOut \\/\n          exists pushed_venv, exists st, exists bal,\n                  r = ProgramToWorld act st bal pushed_venv /\\\n                  account_state_responds_to_world\n                    (update_account_state (account_state_pop_ongoing_call a) act st bal pushed_venv)\n                    continuation I).\n\nDefinition respond_to_fail_correctly (f : contract_behavior)\n           (a : account_state) (I : variable_env -> constant_env -> Prop)\n           account_state_responds_to_world :=\n  forall venv continuation act,\n     Some venv = build_venv_fail a ->\n     f = ContractAction act continuation ->\n     forall steps,\n       let r := (program_sem venv (build_cenv a) steps) in\n       r = ProgramStepRunOut \\/\n       exists pushed_venv, exists st, exists bal,\n               r = ProgramToWorld act st bal pushed_venv /\\\n               account_state_responds_to_world\n                 (update_account_state (account_state_pop_ongoing_call a) act st bal pushed_venv)\n                 continuation I.\n\nCoInductive account_state_responds_to_world :\n  account_state -> response_to_world -> (variable_env -> constant_env -> Prop (*invariant*)) -> Prop :=\n| AccountStep :\n    forall (a : account_state)\n           (c : call_env -> contract_behavior)\n           (r : return_result -> contract_behavior)\n           (I : variable_env -> constant_env -> Prop)\n           f,\n      respond_to_call_correctly c a I account_state_responds_to_world ->\n      respond_to_return_correctly r a I account_state_responds_to_world ->\n      respond_to_fail_correctly f a I account_state_responds_to_world ->\n    account_state_responds_to_world a (Respond c r f) I\n.\n\n\nEnd Make.\n", "meta": {"author": "pirapira", "repo": "evmverif", "sha": "cb1e478f73facb82b60f2d12c3c5bc34a23f2cf1", "save_path": "github-repos/coq/pirapira-evmverif", "path": "github-repos/coq/pirapira-evmverif/evmverif-cb1e478f73facb82b60f2d12c3c5bc34a23f2cf1/coq/ContractSem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2563057277938281}}
{"text": "Require Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Lists.List.\n\nClass Monad(M: Type -> Type) := mkMonad {\n  Bind: forall {A B}, M A -> (A -> M B) -> M B;\n  Return: forall {A}, A -> M A;\n\n  left_identity: forall {A B} (a: A) (f: A -> M B),\n    Bind (Return a) f = f a;\n  right_identity: forall {A} (m: M A),\n    Bind m Return = m;\n  associativity: forall {A B C} (m: M A) (f: A -> M B) (g: B -> M C),\n    Bind (Bind m f) g = Bind m (fun x => Bind (f x) g)\n}.\n\n\nNotation \"x <- m1 ; m2\" := (Bind m1 (fun x => m2))\n  (right associativity, at level 60) : monad_scope.\nNotation \"m1 ;; m2\" := (Bind m1 (fun _ => m2))\n  (right associativity, at level 60) : monad_scope.\n\nOpen Scope monad_scope.\n\nInstance option_Monad: Monad option := {|\n  Bind := fun {A B: Type} (o: option A) (f: A -> option B) => match o with\n          | Some x => f x\n          | None => None\n          end;\n  Return := fun {A: Type} (a: A) => Some a\n|}.\n- intros. reflexivity.\n- intros. destruct m; reflexivity.\n- intros. destruct m; reflexivity.\nDefined.\n\n\n(* Monad which also supports failure (mzero) and choice (mplus), typically used to chose\n   the first successful one *)\nClass MonadPlus(M: Type -> Type){MM: Monad M} := mkMonadPlus {\n  mzero: forall {A}, M A;\n  mplus: forall {A}, M A -> M A -> M A;\n\n  mzero_left: forall {A} (f: A -> M A), Bind mzero f = mzero;\n  mzero_right: forall {A B} (v: M A), Bind v (fun (_: A) => @mzero B) = @mzero B;\n  mplus_assoc: forall {A} (m1 m2 m3: M A), mplus m1 (mplus m2 m3) = mplus (mplus m1 m2) m3;\n}.\n\nDefinition msum{A}{M: Type -> Type}{MM: Monad M}{MP: MonadPlus M}: list (M A) -> M A :=\n  fold_right mplus mzero.\n\n\nInstance OptionMonadPlus: MonadPlus option := {|\n  mzero := @None;\n  mplus A m1 m2 := match m1 with\n                   | Some x => m1\n                   | None => m2\n                   end;\n|}.\n- intros. reflexivity.\n- intros. destruct v; reflexivity.\n- intros. destruct m1; reflexivity.\nDefined.\n\n\nDefinition State(S A: Type) := S -> (A * S).\n\nInstance State_Monad(S: Type): Monad (State S) := {|\n  Bind := fun {A B: Type} (m: State S A) (f: A -> State S B) =>\n            fun (s: S) => let (a, s') := m s in f a s' ;\n  Return := fun {A: Type} (a: A) =>\n              fun (s: S) => (a, s)\n|}.\n- intros. reflexivity.\n- intros. extensionality s. destruct (m s). reflexivity.\n- intros. extensionality s. destruct (m s). reflexivity.\nDefined.\n\nModule StateM.\nDefinition get{S: Type}: State S S := fun (s: S) => (s, s).\nDefinition gets{S A: Type}(f: S -> A): State S A := fun (s: S) => (f s, s).\nDefinition put{S: Type}(s: S): State S unit := fun _ => (tt, s).\nEnd StateM.\n\n(*\nInductive StateOutcome(S A: Type) :=\n| Success: S -> A -> StateOutcome S A\n| Break: S -> StateOutcome S A\n| Unhandled: StateOutcome S A.\n\nDefinition OState(S A: Type) := S -> StateOutcome S A.\n\nInstance OState_Monad(S: Type): Monad (OState S) := {|\n  Bind := fun {A B: Type} (m: OState S A) (f: A -> OState S B) =>\n            fun (s: S) => match m s with\n              | Success _ _ s' a => f a s'\n              | Break _ _ s' => Break S B s'\n              | Unhandled _ _ => Unhandled S B\n              end;\n  Return := fun {A: Type} (a: A) =>\n              fun (s: S) => Success S A s a\n|}.\n- intros. reflexivity.\n- intros. extensionality s. destruct (m s); reflexivity.\n- intros. extensionality s. destruct (m s); reflexivity.\nDefined.\n\nInstance OState_MonadPlus(S: Type): MonadPlus (OState S) := {|\n  mzero A s := Unhandled S A;\n  mplus A m1 m2 s := match m1 s with\n    | Success _ _ s' a => Success _ _ s' a\n    | Break _ _ s' => Break _ _ s'\n    | Unhandled _ _ => m2 s\n    end\n|}.\n- intros. reflexivity.\n- intros. Close Scope monad_scope.\n  unfold Bind, OState_Monad.\n  extensionality s. destruct (v s); try reflexivity.\n  (* Note: does not hold: If after break, we find out that actually it's unhandled,\n     it's still break, because after break, nothing more is run. *)\nAbort.\n\nDefinition get{S: Type}: OState S S := fun (s: S) => Some (s, s).\nDefinition gets{S A: Type}(f: S -> A): OState S A := fun (s: S) => Some (f s, s).\nDefinition put{S: Type}(s: S): OState S unit := fun _ => Some (tt, s).\n\n*)\n\n\n\n(* Note: This one is not what we want either, because it throws away all the state\n   on endCycle/raiseException:\n\nDefinition OState(S A: Type) := S -> option (A * S).\n\nInstance OState_Monad(S: Type): Monad (OState S) := {|\n  Bind := fun {A B: Type} (m: OState S A) (f: A -> OState S B) =>\n            fun (s: S) => match m s with\n            | Some (a, s') => f a s'\n            | None => None\n            end;\n  Return := fun {A: Type} (a: A) =>\n              fun (s: S) => Some (a, s)\n|}.\n- intros. reflexivity.\n- intros. extensionality s. destruct (m s); [|reflexivity]. destruct p. reflexivity.\n- intros. extensionality s. destruct (m s); [|reflexivity]. destruct p. reflexivity.\nDefined.\n\nInstance OState_MonadPlus(S: Type): MonadPlus (OState S) := {|\n  mzero A s := @None (A * S);\n  mplus A m1 m2 s := match m1 s with\n    | Some p => Some p\n    | None => m2 s\n    end;\n|}.\n- intros. reflexivity.\n- intros. simpl. extensionality s. destruct (v s); [|reflexivity]. destruct p. reflexivity.\n- intros. extensionality s. destruct (m1 s); reflexivity.\nDefined.\n\nDefinition get{S: Type}: OState S S := fun (s: S) => Some (s, s).\nDefinition gets{S A: Type}(f: S -> A): OState S A := fun (s: S) => Some (f s, s).\nDefinition put{S: Type}(s: S): OState S unit := fun _ => Some (tt, s).\n *)\n\n\n(* Note: This one is not what we want because in \"mplus m1 m2\", if m1 throws an exception,\n   m2 is run, instead of keeping m1's exception.\n   The problem is that \"None\" can mean both \"unhandled, please try next\" or\n   \"handled, but exception\"\n*)\nDefinition OState(S A: Type) := S -> (option A) * S.\n\nInstance OState_Monad(S: Type): Monad (OState S) := {|\n  Bind := fun {A B: Type} (m: OState S A) (f: A -> OState S B) =>\n            fun (s: S) => match m s with\n            | (Some a, s') => f a s'\n            | (None, s') => (None, s')\n            end;\n  Return := fun {A: Type} (a: A) =>\n              fun (s: S) => (Some a, s)\n|}.\n- intros. reflexivity.\n- intros. extensionality s. destruct (m s). destruct o; reflexivity.\n- intros. extensionality s. destruct (m s). destruct o; reflexivity.\nDefined.\n\n(* TODO if we want to use MonadPlus, we'd have to define a custom equivalence on\n   the state monad which only considers A, but not S *)\nAxiom OStateEq_to_eq: forall {S A: Type} (s1 s2: S) (a1 a2: option A),\n  a1 = a2 -> (a1, s1) = (a2, s2).\n\nInstance OState_MonadPlus(S: Type): MonadPlus (OState S) := {|\n  mzero A s := (@None A, s);\n  mplus A m1 m2 s := match m1 s with\n    | (Some a, s') => (Some a, s')\n    | (None, s') => m2 s\n    end;\n|}.\n- intros. reflexivity.\n- intros. simpl. extensionality s. destruct (v s).\n  destruct o; apply OStateEq_to_eq; reflexivity.\n- intros. simpl. extensionality s. destruct (m1 s). destruct o; reflexivity.\nDefined.\n\nDefinition get{S: Type}: OState S S := fun (s: S) => (Some s, s).\nDefinition gets{S A: Type}(f: S -> A): OState S A := fun (s: S) => (Some (f s), s).\nDefinition put{S: Type}(s: S): OState S unit := fun _ => (Some tt, s).\n\nDefinition execState{S A: Type}(m: OState S A)(initial: S): S :=\n  snd (m initial).\n\n(* T for transformer, corresponds to Haskell's MaybeT: *)\nDefinition optionT(M: Type -> Type)(A: Type) := M (option A).\n\nInstance OptionT_is_Monad(M: Type -> Type){MM: Monad M}: Monad (optionT M) := {|\n  Bind{A}{B}(m: M (option A))(f: A -> M (option B)) :=\n    Bind m (fun (o: option A) =>\n      match o with\n      | Some a => f a\n      | None => Return None\n      end);\n  Return{A}(a: A) := Return (Some a);\n|}.\n- intros. rewrite left_identity. reflexivity.\n- intros. rewrite <- right_identity. f_equal. extensionality o. destruct o; reflexivity.\n- intros. rewrite associativity. f_equal. extensionality o. destruct o.\n  + reflexivity.\n  + rewrite left_identity. reflexivity.\nDefined.\n\nLemma discard_left: forall {M : Type -> Type} {MM : Monad M} {A B : Type} (m: M A) (b: B),\n  Bind m (fun _  => Return b) = Return b.\nProof.\n  intros. (* Note: This does not hold for the state monad! *)\nAdmitted.\n\nDefinition OpSt(S: Type): Type -> Type := optionT (State S).\n\nDefinition OpSt_Monad(S: Type): Monad (OpSt S).\n  unfold OpSt. apply OptionT_is_Monad. apply State_Monad.\nDefined.\n\nGoal forall (S: Type), False. intro S. set (b := @Bind (OpSt S) (OpSt_Monad S)).\nAbort.\n\nInstance optionT_is_MonadPlus(M: Type -> Type){MM: Monad M}: MonadPlus (optionT M) := {|\n  mzero A := Return None : M (option A);\n  mplus A m1 m2 := @Bind _ _ (option A) _ m1 (fun (o1: option A) => match o1 with\n    | Some a1 => Return (Some a1)\n    | None => m2\n    end) : M (option A);\n|}.\n- intros. simpl. rewrite left_identity. reflexivity.\n- intros. simpl.\n  transitivity (Bind v (fun o : option A => Return (@None B))).\n  + f_equal. extensionality o. destruct o; reflexivity.\n  + apply discard_left.\n- intros.\n  rewrite associativity. f_equal. extensionality o1. destruct o1.\n  + rewrite left_identity. reflexivity.\n  + reflexivity.\nDefined.\n\nClass MonadTrans(T: (Type -> Type) -> (Type -> Type)) := mkMonadTrans {\n  lift{M: Type -> Type}{MM: Monad M}{A: Type}: M A -> T M A;\n  transformed_monad{M: Type -> Type}{MM: Monad M}: Monad (T M);\n  lift_return{M: Type -> Type}{MM: Monad M}{A: Type}:\n    forall a: A, lift (Return a) = Return a;\n  lift_bind{M: Type -> Type}{MM: Monad M}{A B: Type}:\n    forall (m: M A) (f: A -> M B), lift (Bind m f) = Bind (lift m) (fun x => lift (f x));\n}.\n\n(* Promote a function to a monad. *)\nDefinition liftM{M: Type -> Type}{MM: Monad M}{A B: Type}(f: A -> B): M A -> M B :=\n  fun m => x <- m; Return (f x).\n\nInstance optionT_is_MonadTrans: MonadTrans optionT := {|\n  lift M MM A := liftM Some;\n  transformed_monad := OptionT_is_Monad;\n|}.\n- intros. unfold liftM. simpl. rewrite left_identity. reflexivity.\n- intros. unfold liftM. simpl. rewrite? associativity. f_equal. extensionality a.\n  rewrite left_identity. reflexivity.\nDefined.\n", "meta": {"author": "samuelgruetter", "repo": "riscv-coq", "sha": "bd89fbff49704b4476633a88abdedb4e410c200b", "save_path": "github-repos/coq/samuelgruetter-riscv-coq", "path": "github-repos/coq/samuelgruetter-riscv-coq/riscv-coq-bd89fbff49704b4476633a88abdedb4e410c200b/src/util/Monads.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2563057208693416}}
{"text": "From iris.proofmode Require Import tactics.\nFrom iris.program_logic Require Export weakestpre.\nFrom iris.base_logic Require Export invariants.\nFrom F_mu_ref_conc_sub Require Export rules_binary typing.\nFrom iris.algebra Require Import list.\nFrom stdpp 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 (discrete_iff _ _) in H\n  | H : _ ≡ _ |-  _ => apply leibniz_equiv 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\nLtac solve_proper ::= (repeat intros ?; simpl; 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 := (prodO (valO F_mu_ref_conc_lang) (valO F_mu_ref_conc_lang)\n                 -n> iProp Σ).\n  Implicit Types τi : D.\n  Implicit Types Δ : listO D.\n  Implicit Types interp : listO D → D.\n\n  Definition interp_expr (τi : listO D -n> D) (Δ : listO 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. unfold interp_expr; solve_proper. Qed.\n\n  Program Definition env_lookup (x : var) : listO D -n> D := λne Δ,\n    from_option id (cconst False)%I (Δ !! x).\n  Solve Obligations with solve_proper.\n\n  Definition interp_top : listO D -n> D := λne Δ ww, True%I.\n\n  Program Definition interp_unit : listO 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 : listO D -n> D := λne Δ ww,\n    (∃ n : nat, ⌜ww.1 = #nv n⌝ ∧ ⌜ww.2 = #nv n⌝)%I.\n  Solve Obligations with solve_proper.\n\n  Program Definition interp_bool : listO 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 : listO D -n> D) : listO 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 : listO D -n> D) : listO 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 : listO D -n> D) : listO 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_bound interp : listO D -n> D) : listO D -n> D := λne Δ ww,\n    (□ ∀ τi,\n          ⌜∀ ww, Persistent (τi ww)⌝ → □ (∀ vv, τi vv -∗ interp_bound Δ vv) →\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 : listO D -n> D) (Δ : listO 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 : listO D -n> D) (Δ : listO D) : Contractive (interp_rec1 interp Δ).\n  Proof. solve_contractive. Qed.\n\n  Lemma fixpoint_interp_rec1_eq (interp : listO D -n> D) Δ x :\n    fixpoint (interp_rec1 interp Δ) x ≡ interp_rec1 interp Δ (fixpoint (interp_rec1 interp Δ)) x.\n  Proof. exact: (fixpoint_unfold (interp_rec1 interp Δ) x). Qed.\n\n  Program Definition interp_rec (interp : listO D -n> D) : listO 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 : listO D -n> D) : listO 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) : listO D -n> D :=\n    match τ return _ with\n    | Top => interp_top\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 => env_lookup x\n    | TForall σ τ' => interp_forall (interp σ) (interp τ')\n    | TRec τ' => interp_rec (interp τ')\n    | Tref τ' => interp_ref (interp τ')\n    end.\n  Notation \"⟦ τ ⟧\" := (interp τ).\n\n  Definition interp_env (Γ : list type)\n      (Δ : listO D) (vvs : list (val * val)) : iProp Σ :=\n    (⌜length Γ = length vvs⌝ ∗ [∗] zip_with (λ τ, ⟦ τ ⟧ Δ) Γ vvs)%I.\n  Notation \"⟦ Γ ⟧*\" := (interp_env Γ).\n\n  Class env_Persistent Δ :=\n    env_persistentP : Forall (λ τi, ∀ vv, Persistent (τi vv)) Δ.\n  Global Instance env_persistent_nil : env_Persistent [].\n  Proof. by constructor. Qed.\n  Global Instance env_persistent_cons τi Δ :\n    (∀ vv, Persistent (τi vv)) → env_Persistent Δ → env_Persistent (τi :: Δ).\n  Proof. by constructor. Qed.\n  Global Instance env_persistent_lookup Δ x vv :\n    env_Persistent Δ → Persistent (env_lookup x Δ vv).\n  Proof. intros HΔ; revert x; induction HΔ=>-[|?] /=; apply _. Qed.\n  Global Instance interp_persistent τ Δ vv :\n    env_Persistent Δ → Persistent (⟦ τ ⟧ Δ vv).\n  Proof.\n    revert vv Δ; induction τ=> vv Δ HΔ; simpl; try apply _.\n    rewrite /Persistent fixpoint_interp_rec1_eq /interp_rec1 /= intuitionistically_into_persistently.\n    by apply persistently_intro'.\n  Qed.\n  Global Instance interp_env_base_persistent Δ Γ vs :\n  env_Persistent Δ → TCForall Persistent (zip_with (λ τ, ⟦ τ ⟧ Δ) Γ vs).\n  Proof.\n    intros HΔ. revert vs.\n    induction Γ => vs; simpl; destruct vs; constructor; apply _.\n  Qed.\n  Global Instance interp_env_persistent Γ Δ vvs :\n    env_Persistent Δ → Persistent (⟦ Γ ⟧* Δ 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. 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      (* FIXME: Ideally we wouldn't have to do this kinf of surgery. *)\n      change (bi_ofeO (uPredI (iResUR Σ))) with (uPredO (iResUR Σ)).\n      rewrite !lookup_app_r; [|lia ..]. do 2 f_equiv. lia.\n    - unfold interp_expr.\n      intros ww; simpl; properness; auto. by apply IHτ. by apply (IHτ0 (_ :: _)).\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. 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      (* FIXME: Ideally we wouldn't have to do this kinf of surgery. *)\n      change (bi_ofeO (uPredI (iResUR Σ))) with (uPredO (iResUR Σ)).\n      rewrite !lookup_app_r; [|lia ..].\n      case EQ: (x - length Δ1) => [|n]; simpl.\n      { symmetry. asimpl. apply (interp_weaken [] Δ1 Δ2 τ'). }\n      change (bi_ofeO (uPredI (iResUR Σ))) with (uPredO (iResUR Σ)).\n      rewrite !lookup_app_r; [|lia ..]. do 2 f_equiv. lia.\n    - unfold interp_expr.\n      intros ww; simpl; properness; auto. by apply IHτ. by apply (IHτ0 (_ :: _)).\n    - intros ww; simpl; properness; auto. by apply IHτ.\n  Qed.\n\n  Lemma interp_subst Δ2 τ τ' v : ⟦ τ ⟧ (⟦ τ' ⟧ Δ2 :: Δ2) v ≡ ⟦ τ.[τ'/] ⟧ Δ2 v.\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_sepL_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 Δ : ⟦ [] ⟧* Δ [].\n  Proof. iSplit; simpl; 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; lia|].\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_ref_pointsto_neq E Δ τ l w (l1 l2 l3 l4 : loc) :\n    ↑logN.@(l1, l2) ⊆ E →\n    l2 ≠ l4 →\n    l ↦ᵢ w -∗ interp (Tref τ) Δ (LocV l1, LocV l2) -∗\n      |={E ∖ ↑logN.@(l3, l4)}=> l ↦ᵢ w ∗ ⌜l ≠ l1⌝.\n  Proof.\n    intros Hnin Hneq.\n    destruct (decide (l = l1)); subst; last auto.\n    iIntros \"Hl1\"; simpl; iDestruct 1 as ((l5, l6)) \"[% Hl2]\"; simplify_eq.\n    iInv (logN.@(l5, l6)) as \"Hi\" \"Hcl\"; simpl.\n    iDestruct \"Hi\" as ((v1, v2))  \"(Hl3 & Hl2' & ?)\".\n    iMod \"Hl3\".\n    by iDestruct (@mapsto_valid_2 with \"Hl1 Hl3\") as %?.\n  Qed.\n\n  Lemma interp_ref_pointsto_neq' E Δ τ l w (l1 l2 l3 l4 : loc) :\n    ↑logN.@(l1, l2) ⊆ E →\n    l1 ≠ l3 →\n    l ↦ₛ w -∗ interp (Tref τ) Δ (LocV l1, LocV l2) -∗\n      |={E ∖ ↑logN.@(l3, l4)}=> l ↦ₛ w ∗ ⌜l ≠ l2⌝.\n  Proof.\n    intros Hnin Hneq.\n    destruct (decide (l = l2)); subst; last auto.\n    iIntros \"Hl1\"; simpl; iDestruct 1 as ((l5, l6)) \"[% Hl2]\"; simplify_eq.\n    iInv (logN.@(l5, l6)) as \"Hi\" \"Hcl\"; simpl.\n    iDestruct \"Hi\" as ((v1, v2))  \"(Hl3 & Hl2' & ?)\".\n    iMod \"Hl2'\"; simpl.\n    unfold heapS_mapsto.\n    iDestruct (@own_valid_2 _ _ _ cfg_name with \"Hl1 Hl2'\") as %[_ Hvl].\n    exfalso.\n    specialize (Hvl l6); revert Hvl. simpl.\n    rewrite /= gmap.lookup_op !lookup_singleton -Some_op. by intros [? _].\n  Qed.\n\n  Lemma interp_ref_open' Δ τ l l' :\n    env_Persistent Δ → EqType τ →\n    ⟦ Tref τ ⟧ Δ (LocV l, LocV l') -∗\n               |={⊤, ⊤ ∖ ↑logN.@(l, l')}=>\n  ∃ w w', ▷ l ↦ᵢ w ∗ ▷ l' ↦ₛ w' ∗ ▷ ⟦ τ ⟧ Δ (w, w') ∗\n            ▷ (∀ z z' u u' v v',\n                  l ↦ᵢ z -∗ l' ↦ₛ z' -∗ ⟦ τ ⟧ Δ (u, u') -∗ ⟦ τ ⟧ Δ (v, v') -∗\n                    |={⊤ ∖ ↑logN.@(l, l')}=> l ↦ᵢ z ∗\n                                              l' ↦ₛ z' ∗ ⌜v = u ↔ v' = u'⌝)\n            ∗ (▷ (∃ vv : val * val, l ↦ᵢ vv.1 ∗ l' ↦ₛ vv.2 ∗ ⟦ τ ⟧ Δ vv)\n          ={⊤ ∖ ↑logN.@(l, l'), ⊤}=∗ True).\n  Proof.\n    iIntros (HΔ Heqt); simpl.\n    iDestruct 1 as ((l1, l1')) \"[% H1]\"; simplify_eq.\n    iInv (logN.@(l1, l1')) as \"Hi\" \"$\"; simpl.\n    iDestruct \"Hi\" as ((v1, v2))  \"(Hl1 & Hl1' & Hrl)\"; simpl in *.\n    destruct Heqt; simpl in *.\n    - iModIntro; iExists _, _; iFrame.\n      iNext. iIntros (??????) \"? ?\". iIntros ([??] [??]); subst.\n      by iModIntro; iFrame.\n    - iModIntro; iExists _, _; iFrame.\n      iNext. iIntros (??????) \"? ?\".\n      iDestruct 1 as (?) \"[% %]\". iDestruct 1 as (?) \"[% %]\".\n      simplify_eq. by iModIntro; iFrame.\n    - iModIntro; iExists _, _; iFrame.\n      iNext. iIntros (??????) \"? ?\".\n      iDestruct 1 as (?) \"[% %]\". iDestruct 1 as (?) \"[% %]\".\n      simplify_eq. by iModIntro; iFrame.\n    - iModIntro; iExists _, _; iFrame; iFrame \"#\". iNext.\n      iIntros (z z' u u' v v') \"Hl1 Hl1' Huu\". iDestruct 1 as ((l2, l2')) \"[% #Hl2]\";\n        simplify_eq; simpl in *.\n      iDestruct \"Huu\" as ((l3, l3')) \"[% #Hl3]\";\n        simplify_eq; simpl in *.\n      destruct (decide ((l1, l1') = (l2, l2'))); simplify_eq.\n      + destruct (decide ((l2, l2') = (l3, l3'))); simplify_eq; first by iFrame.\n        destruct (decide (l2 = l3)); destruct (decide (l2' = l3')); subst.\n        * iMod (interp_ref_pointsto_neq with \"Hl1 []\")\n               as \"[Hl1 %]\"; simpl; eauto.\n             { by iExists (_, _); iFrame \"#\". }\n             by iFrame.\n        * iMod (interp_ref_pointsto_neq with \"Hl1 []\")\n               as \"[Hl1 %]\"; simpl; eauto.\n             { by iExists (_, _); iFrame \"#\". }\n             by iFrame.\n        * iMod (interp_ref_pointsto_neq' with \"Hl1' []\")\n               as \"[Hl1' %]\";\n               simpl; eauto.\n             { by iExists (_, _); iFrame \"#\". }\n             by iFrame.\n        * iFrame; iModIntro; iPureIntro; split; by inversion 1.\n      + destruct (decide ((l1, l1') = (l3, l3'))); simplify_eq.\n        * destruct (decide (l2 = l3)); destruct (decide (l2' = l3')); subst.\n          -- iMod (interp_ref_pointsto_neq with \"Hl1 []\")\n              as \"[Hl1 %]\"; simpl; eauto.\n             { by iExists (_, _); iFrame \"#\". }\n             by iFrame.\n          -- iMod (interp_ref_pointsto_neq with \"Hl1 []\")\n               as \"[Hl1 %]\"; simpl; eauto.\n             { iExists (_, _); iSplit; first eauto. iFrame \"#\". }\n             by iFrame.\n          -- iMod (interp_ref_pointsto_neq' with \"Hl1' []\")\n               as \"[Hl1' %]\";\n               simpl; eauto.\n             { iExists (_, _); iSplit; first eauto. iFrame \"#\". }\n             by iFrame.\n          -- iFrame; iModIntro; iPureIntro; split; by inversion 1.\n        * destruct (decide ((l2, l2') = (l3, l3'))); simplify_eq.\n          -- destruct (decide (l1 = l3)); destruct (decide (l1' = l3')); subst.\n             ++ iMod (interp_ref_pointsto_neq with \"Hl1 []\")\n                 as \"[Hl1 %]\"; simpl; eauto.\n                { by iExists (_, _); iFrame \"#\". }\n                  by iFrame.\n             ++ iMod (interp_ref_pointsto_neq with \"Hl1 []\")\n               as \"[Hl1 %]\"; simpl; eauto.\n                { by iExists (_, _); iFrame \"#\". }\n                  by iFrame.\n             ++ iMod (interp_ref_pointsto_neq' with \"Hl1' []\")\n                 as \"[Hl1' %]\";\n                  simpl; eauto.\n                { by iExists (_, _); iFrame \"#\". }\n                  by iFrame.\n             ++ iFrame; iModIntro; iPureIntro; split; by inversion 1.\n          -- iFrame.\n             { destruct (decide (l2 = l3)); destruct (decide (l2' = l3'));\n                 simplify_eq; auto.\n               + iInv (logN.@(l3, l2')) as \"Hib1\" \"Hcl1\".\n                 iInv (logN.@(l3, l3')) as \"Hib2\" \"Hcl2\".\n                 iDestruct \"Hib1\" as ((v11, v12)) \"(Hlx1' & Hlx2 & Hr1)\".\n                 iDestruct \"Hib2\" as ((v11', v12')) \"(Hl1'' & Hl2' & Hr2)\".\n                 simpl.\n                 iMod \"Hlx1'\"; iMod \"Hl1''\".\n                   by iDestruct (@mapsto_valid_2 with \"Hlx1' Hl1''\") as %?.\n               + iInv (logN.@(l2, l3')) as \"Hib1\" \"Hcl1\".\n                 iInv (logN.@(l3, l3')) as \"Hib2\" \"Hcl2\".\n                 iDestruct \"Hib1\" as ((v11, v12)) \"(Hl1 & Hl2' & Hr1)\".\n                 iDestruct \"Hib2\" as ((v11', v12')) \"(Hl1' & Hl2'' & Hr2)\".\n                 simpl.\n                 iMod \"Hl2'\"; iMod \"Hl2''\".\n                 unfold heapS_mapsto.\n                 iDestruct (@own_valid_2 _ _ _ cfg_name with \"Hl2' Hl2''\") as %[_ Hvl].\n                 exfalso.\n                 specialize (Hvl l3'); revert Hvl.\n                 rewrite /= gmap.lookup_op !lookup_singleton -Some_op. by intros [? _].\n               + iModIntro; iPureIntro; split; intros; simplify_eq. }\n  Qed.\n\n  Definition interp_Tenv (Δ : listO D) (Ξ : list type) : iProp Σ:=\n    (⌜length Δ = length Ξ⌝ ∧ ∀ x τ, ⌜Ξ !! x = Some τ⌝ →\n                                    □ (∀ v, env_lookup x Δ v -∗ interp τ Δ v))%I.\n\n  Lemma interp_Tenv_weaken Δ Ξ τ τi :\n    □ (∀ v, τi v -∗ interp τ Δ v) ∧ interp_Tenv Δ Ξ\n    ⊣⊢ interp_Tenv (τi :: Δ) (τ.[ren (+1)] :: (subst (ren (+1)) <$> Ξ)).\n  Proof.\n    iSplit.\n    - iIntros \"#[Hτ [Hlen HΞ]]\". iDestruct \"Hlen\" as %Hlen.\n      iSplit.\n      { rewrite /= fmap_length; auto. }\n      iIntros (x σ Hσ) \"!#\". iIntros (v) \"Hv\".\n      destruct x; simpl in *; simplify_eq.\n      + rewrite (interp_weaken [] [τi] Δ τ _) /=.\n        by iApply \"Hτ\".\n      + rewrite list_lookup_fmap in Hσ.\n        destruct (Ξ !! x) as [δ|]eqn:Hxeq; last done.\n        simpl in *; simplify_eq.\n        rewrite (interp_weaken [] [τi] Δ δ _) /=.\n        iApply \"HΞ\"; eauto.\n    - iIntros \"#[Hlen HΞ]\". iDestruct \"Hlen\" as %Hlen.\n      iSplit.\n      { iAlways. iIntros (v) \"Hv\".\n        rewrite -(interp_weaken [] [τi] Δ τ _) /=.\n        by iApply (\"HΞ\" $! 0). }\n      iSplit.\n      { rewrite /= fmap_length in Hlen; auto. }\n      iIntros (x σ Hσ) \"!#\". iIntros (v) \"Hv\".\n      rewrite -(interp_weaken [] [τi] Δ σ _) /=.\n      iApply (\"HΞ\" $! (S x)); last done.\n      rewrite /= list_lookup_fmap Hσ //.\n  Qed.\n\n  Lemma logrel_subtyp Δ Ξ τ τ' v :\n    env_Persistent Δ →\n    subtype Ξ τ τ' →\n    interp_Tenv Δ Ξ ⊢ □ (interp τ Δ v -∗ interp τ' Δ v).\n  Proof.\n    iIntros (HΔ Hsb) \"#HΞ\".\n    iIntros \"!# #Hτ\".\n    iInduction Hsb as [] \"IH\" forall (Δ HΔ v) \"HΞ Hτ\"; simpl; auto.\n    - iDestruct \"HΞ\" as \"[% HΞ]\".\n      iApply (\"HΞ\" $! x); eauto.\n    - iApply \"IH1\"; eauto.\n      iAlways. iApply \"IH\"; eauto.\n    - rewrite -/interp.\n      iAlways. iIntros (w) \"#Hw\". iIntros (j K) \"Hj\".\n      iApply wp_wand_r; iSplitL.\n      + iApply \"Hτ\". iApply \"IH\"; auto. simpl; iFrame.\n      + iIntros (?). iDestruct 1 as (u) \"[Hu #Hτu]\"; iExists _; iFrame.\n        iApply \"IH1\"; eauto.\n    - rewrite -/interp.\n      iAlways. iIntros (τi Hτi) \"#Hτi\". iIntros (j K) \"Hj\".\n      iApply wp_wand_r; iSplitL; first by iApply \"Hτ\"; eauto.\n      iIntros (?). iDestruct 1 as (u) \"[Hu #Hτu]\"; iExists _; iFrame.\n      iApply \"IH\"; eauto.\n      + by iPureIntro; apply env_persistent_cons.\n      + iAlways. rewrite -interp_Tenv_weaken; auto.\n    - iLöb as \"ILH\" forall (v) \"Hτ\".\n      rewrite (fixpoint_unfold (interp_rec1 ⟦ σ ⟧ Δ) v).\n      rewrite (fixpoint_unfold (interp_rec1 ⟦ τ ⟧ Δ) v).\n      simpl.\n      iAlways.\n      iDestruct \"Hτ\" as ([w1 w2] ?) \"Hτ\".\n      iExists _; iSplit; first done.\n      iNext.\n      iSpecialize (\"IH\" $! (fixpoint (interp_rec1 ⟦ σ ⟧ Δ) ::\n                            fixpoint (interp_rec1 ⟦ τ ⟧ Δ) :: Δ) with \"[]\").\n      { iPureIntro.\n        constructor; last constructor; last done.\n        - intros; by apply (interp_persistent (TRec σ)).\n        - intros; by apply (interp_persistent (TRec τ)). }\n      iSpecialize (\"IH\" $! (w1, w2) with \"[]\").\n      { iAlways.\n        iDestruct \"HΞ\" as \"[HΞ1 HΞ2]\".\n        iSplit.\n        { rewrite /= fmap_length. by iDestruct \"HΞ1\" as %->. }\n        iIntros (x ρ Hx).\n        destruct x as [|[|x]]; simpl in *; simplify_eq; simpl.\n        - change (fixpoint (interp_rec1 ⟦ σ ⟧ Δ)) with (⟦ TRec σ ⟧ Δ).\n          iAlways. by iIntros (u) \"#?\"; iApply \"ILH\".\n        - change (fixpoint (interp_rec1 ⟦ τ ⟧ Δ)) with (⟦ TRec τ ⟧ Δ).\n          change (fixpoint (interp_rec1 ⟦ σ ⟧ Δ)) with (⟦ TRec σ ⟧ Δ).\n          iAlways. by iIntros (u) \"#?\".\n        - iAlways.\n          rewrite list_lookup_fmap in Hx.\n          iIntros (u) \"Hu\".\n          destruct (Δ !! x) as [δ|] eqn:HΔx; rewrite HΔx; last done.\n          destruct (Ξ !! x) as [δ'|] eqn:HΞx; last done.\n          iSpecialize (\"HΞ2\" $! x δ' with \"[]\"); first done.\n          rewrite HΔx; simpl.\n          iSpecialize (\"HΞ2\" $! u with \"Hu\").\n          simpl in *; simplify_eq.\n          change (δ'.[ren (+2)]) with (δ'.[upn 0 (ren (+2))]).\n          by rewrite (interp_weaken [] [_; _] _ _ _). }\n      rewrite (interp_weaken [] [_] (_ :: _) _ _).\n      rewrite (interp_weaken [_] [_] _ _ _).\n      by iApply \"IH\".\n  Qed.\n\nEnd logrel.\n\nTypeclasses Opaque interp_env.\nNotation \"⟦ τ ⟧\" := (interp τ).\nNotation \"⟦ τ ⟧ₑ\" := (interp_expr (interp τ)).\nNotation \"⟦ Γ ⟧*\" := (interp_env Γ).\n", "meta": {"author": "amintimany", "repo": "F_mu_ref_conc_sub", "sha": "d5c154e11bc646c8e474e87b6a9959db93ec733e", "save_path": "github-repos/coq/amintimany-F_mu_ref_conc_sub", "path": "github-repos/coq/amintimany-F_mu_ref_conc_sub/F_mu_ref_conc_sub-d5c154e11bc646c8e474e87b6a9959db93ec733e/logrel_binary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2563057208693416}}
{"text": "From Coq Require Import\n     ssreflect\n     String\n.\n\nFrom ExtensibleCompiler.Hacks Require Import\n     TypeClassResolutionForHave\n.\n\nFrom ExtensibleCompiler.Semantics Require Import\n     Dynamic.Eval.If2\n     Static.TypeEquality\n     Static.TypeEqualityCorrectness\n     Static.TypeOf\n     Static.TypeOf.If2\n     Static.WellTyped.Bool\n     Static.WellTyped.If2\n.\n\nFrom ExtensibleCompiler.Syntax Require Import\n     Terms.Bool\n     Terms.If2\n     Terms.Stuck\n     Types.BoolType\n.\n\nFrom ExtensibleCompiler.Theory Require Import\n     Algebra\n     Eval\n     Functor\n     IndexedAlgebra\n     IndexedFunctor\n     IndexedProofAlgebra\n     IndexedSubFunctor\n     ProgramAlgebra\n     ProofAlgebra\n     SubFunctor\n     Types\n     TypeSoundness\n     UniversalProperty\n.\n\nLocal Open Scope SubFunctor.\n\nSection If2.\n\n  Context\n\n    {V}\n    `{Functor V}\n    `{! V supports Bool}\n    `{! V supports Stuck}\n\n    {T}\n    `{Functor T}\n    `{! T supports BoolType}\n\n    {E}\n    `{Functor E}\n    `{! E supports If2}\n\n    {typeEqualityForT : forall R, ProgramAlgebra ForTypeEquality T R (TypeEqualityResult T)}\n  .\n\n  Lemma Soundness__if2\n\n        (WTV : (TypedExpr T V)-indexedPropFunctor)\n        `(IndexedFunctor (TypedExpr T V) WTV)\n        `((WellTypedValue__Bool <= WTV)%IndexedSubFunctor)\n\n        `{! forall {R}, ProgramAlgebra    ForEval E R (EvalResult V)}\n\n        (Eval__R : Set)\n        {F} `{Functor F} `{F supports If2}\n        recEval\n\n        (TypeOf__R : Set)\n        recTypeOf\n\n        `{PA__TEC :\n            ! ProofAlgebra ForTypeEqualityCorrectness T\n              (sig (UniversalPropertyP typeEqualityCorrectnessStatement))}\n        `{! WellFormedProofAlgebra PA__TEC }\n\n        `{! IndexedProofAlgebra ForWellTypedValueProjection__Bool WTV\n            (WellTypedValueProjectionStatement__Bool WTV)}\n        `{! IndexedProofAlgebra ForWellTypedProj1Type WTV\n            (PropertyStatement__WellTypedProj1Type WTV)\n         }\n\n    : forall Gamma (c t e : TypeOf__R) (c' t' e' : Eval__R),\n\n      (forall tau,\n          recTypeOf c = Some tau ->\n          WellTyped WTV tau (recEval c' Gamma)\n      ) ->\n\n      (forall tau,\n          recTypeOf t = Some tau ->\n          WellTyped WTV tau (recEval t' Gamma)\n      ) ->\n\n      (forall tau,\n          recTypeOf e = Some tau ->\n          WellTyped WTV tau (recEval e' Gamma)\n      ) ->\n\n      forall tau,\n        typeOf__If2 TypeOf__R recTypeOf (MkIf2 c t e) = Some tau ->\n        WellTyped WTV tau\n                  (eval__If2 Eval__R recEval (MkIf2 c' t' e') Gamma).\n  Proof.\n    rewrite /=.\n    move => Gamma c t e c' t' e'.\n    case TO__c : (recTypeOf c) => [ tau__c | ] // IH__c.\n    move : IH__c (IH__c _ eq_refl) => _ WT__c.\n    case BT : (isBoolType (proj1_sig tau__c)) => //.\n    case TO__t : (recTypeOf t) => [ [ tau__t UP'__tau__t ] | ] // IH__t.\n    move : IH__t (IH__t _ eq_refl) => _ WT__t.\n    case TO__e : (recTypeOf e) => [ tau__e | ] // IH__e.\n    move : IH__e (IH__e _ eq_refl) => _ WT__e.\n    move => tau.\n    case TE : (typeEquality tau__t tau__e) => //.\n    move => [] <-.\n    move : BT.\n    rewrite / isBoolType.\n    case p__c : (projectUP' (proj1_sig tau__c)) => [ [] | ] // _.\n    {\n      have := (project_successUP' _ _ (proj2_sig tau__c) p__c) => {}p__c.\n      have := !! wellTypedValueProjection__Bool _ _ WT__c p__c.\n      elim / @WellTypedValueInversionClear__Bool => _ _ b [] -> -> -> _.\n      rewrite / isBoolean / projectUP' / if2F' / if2 /=.\n      rewrite unwrapUP'_wrapF.\n      rewrite wellFormedSubFunctor.\n      rewrite wellFormedSubFunctor.\n      rewrite project_inject /=.\n      move : b => [].\n      {\n        apply WT__t.\n      }\n      {\n        have := !! typeEqualityCorrectness (exist _ _ _) _ TE => TEC.\n        have := !! wellTypedProj1Type _ _ WT__e _ UP'__tau__t TEC => //.\n      }\n    }\n  Defined.\n\n  Global Instance Soundness__If2\n\n         (WTV : (TypedExpr T V)-indexedPropFunctor)\n         `(IndexedFunctor (TypedExpr T V) WTV)\n         `((WellTypedValue__Bool  <= WTV)%IndexedSubFunctor)\n\n         `{Eval__E : ! forall R, ProgramAlgebra ForEval E R (EvalResult V)}\n         `{! forall R, WellFormedCompoundProgramAlgebra (Eval__E R) (Eval__If2 R)}\n         (recEval : WellFormedValue E -> EvalResult   V)\n\n         `{TypeOf__E : ! forall R, ProgramAlgebra ForTypeOf E R (TypeOfResult T)}\n         `{! forall R, WellFormedCompoundProgramAlgebra (TypeOf__E R) (TypeOf__If2 R)}\n         (recTypeOf : WellFormedValue E -> TypeOfResult T)\n\n        `{PA__TEC :\n            ! ProofAlgebra ForTypeEqualityCorrectness T\n              (sig (UniversalPropertyP typeEqualityCorrectnessStatement))}\n        `{! WellFormedProofAlgebra PA__TEC}\n\n        `{! IndexedProofAlgebra ForWellTypedValueProjection__Bool WTV\n            (WellTypedValueProjectionStatement__Bool WTV)}\n\n        `{! IndexedProofAlgebra ForWellTypedProj1Type WTV\n            (PropertyStatement__WellTypedProj1Type WTV)\n         }\n\n    : ProofAlgebra\n        ForSoundness If2\n        (sig (UniversalPropertyP2\n                (AbstractSoundnessStatement' WTV recEval recTypeOf))).\n  Proof.\n    constructor.\n    apply Induction2__If2.\n    rewrite / AbstractSoundnessStatement' / AbstractSoundnessStatement.\n    rewrite / UniversalPropertyP2 /=.\n    move => [c1 c2] [t1 t2] [e1 e2] /=.\n    move => [[UP'__c1 UP'__c2] IH__c] [[UP'__t1 UP'__t2] IH__t] [[UP'__e1 UP'__e2] IH__e].\n    constructor.\n    {\n      apply conj; exact (proj2_sig (if2 _ _ _)).\n    }\n    {\n      move => Gamma.\n      rewrite / if2F' / if2F / if2 / inject /=.\n      rewrite !unwrapUP'_wrapF /=.\n      rewrite !fmapFusion /=.\n      rewrite / compose /=.\n      rewrite !wellFormedSubFunctor => //=.\n      rewrite / programAlgebra'.\n      rewrite ! wellFormedCompoundProgramAlgebra.\n      move => IH tau.\n      eapply Soundness__if2 => //.\n\n      (* condition *)\n      {\n        move => ?.\n        apply (IH Gamma (exist _ _ UP'__c1, _)) => /=.\n        {\n          move => A B.\n          apply (IH__c Gamma IH).\n          now rewrite <- (wrapUP'_unwrapUP' c2).\n        }\n      }\n\n      (* then branch *)\n      {\n        move => ?.\n        apply (IH Gamma (exist _ _ UP'__t1, _)) => /=.\n        {\n          move => A B.\n          apply (IH__t Gamma IH).\n          now rewrite <- (wrapUP'_unwrapUP' t2).\n        }\n      }\n\n      (* else branch *)\n      {\n        move => ?.\n        apply (IH Gamma (exist _ _ UP'__e1, _)) => /=.\n        {\n          move => A B.\n          apply (IH__e Gamma IH).\n          now rewrite <- (wrapUP'_unwrapUP' e2).\n        }\n      }\n\n    }\n  Defined.\n\nEnd If2.\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/Semantics/Dynamic/Soundness/If2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.705785040214066, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.2561782450412165}}
{"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 O E Eprime S U1 A AX B BX C CX BXMAX CXMAX AB AC IAC T A1 A2 BXprime CXprime ABXprimeprime ACXprimeprime : Universe, ((wd_ A B /\\ (wd_ A C /\\ (wd_ B C /\\ (wd_ A1 A2 /\\ (wd_ C CXprime /\\ (wd_ B BXprime /\\ (wd_ A BXprime /\\ (wd_ O E /\\ (wd_ E Eprime /\\ (wd_ O Eprime /\\ (wd_ S U1 /\\ (col_ O E AX /\\ (col_ O E BX /\\ (col_ O E CX /\\ (col_ O E BXMAX /\\ (col_ O E CXMAX /\\ (col_ O E T /\\ (col_ O E AB /\\ (col_ O E AC /\\ (col_ O E IAC /\\ (col_ A A1 A2 /\\ (col_ O E ABXprimeprime /\\ (col_ O E ACXprimeprime /\\ (col_ A1 A2 BXprime /\\ (col_ S U1 BXprime /\\ (col_ A1 A2 C /\\ (col_ S U1 CXprime /\\ col_ A B C))))))))))))))))))))))))))) -> col_ A B BXprime)).\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_1449.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.2561782308216406}}
{"text": "(* \n  Author(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-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/HilbertCalculi/HSC_undec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850154599562, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.25617822632915077}}
{"text": "Require Import Coq.omega.Omega.\nRequire Import Bedrock.Examples.AutoSepExt.\nExport AutoSepExt.\n\nLtac refold' A :=\n  progress change (fix length (l : list A) : nat :=\n    match l with\n      | nil => 0\n      | _ :: l' => S (length l')\n    end) with (@length A) in *\n  || (progress change (fix app (l0 m : list A) : list A :=\n    match l0 with\n      | nil => m\n      | a1 :: l1 => a1 :: app l1 m\n    end) with (@app A) in *)\n  || (progress change (fix rev (l : list W) : list W :=\n    match l with\n      | nil => nil\n      | x8 :: l' => (rev l' ++ x8 :: nil)%list\n    end) with (@rev A) in *)\n  || (progress change (fix rev_append (l l' : list A) : list A :=\n    match l with\n      | nil => l'\n      | a1 :: l0 => rev_append l0 (a1 :: l')\n    end) with (@rev_append A) in *).\n\nLtac refold :=\n  fold plus in *; fold minus in *;\n    repeat match goal with\n             | [ _ : list ?A |- _ ] =>\n               match A with\n                 | _ => refold' A\n                 | W => refold' (word 32)\n               end\n             | [ |- context[match ?X with nil => ?D | x :: _ => x end] ] =>\n               change (match X with nil => D | x :: _ => x end) with (List.hd D X)\n             | [ |- context[match ?X with nil => nil | _ :: x => x end] ] =>\n               change (match X with nil => nil | _ :: x => x end) with (List.tl X)\n           end.\n\nModule Import Coq8485_workaround_nat_dec_uses_f_equal_nat.\n  Module Coq.\n    Module Init.\n      Module Peano.\n        Definition f_equal_nat := f_equal (A:=nat).\n        Definition f_equal_pred := f_equal pred.\n        Definition f_equal2_plus := f_equal2 plus.\n        Definition f_equal2_nat := f_equal2 (A1:=nat) (A2:=nat).\n        Definition f_equal2_mult := f_equal2 mult.\n      End Peano.\n    End Init.\n  End Coq.\nEnd Coq8485_workaround_nat_dec_uses_f_equal_nat.\n\nRequire Import Coq.Bool.Bool.\nRequire Import Bedrock.Examples.Conditional Bedrock.Examples.Lambda.\nExport Conditional Lambda.\n\nLtac vcgen_simp := cbv beta iota zeta delta [map app imps\n  LabelMap.add Entry Blocks Postcondition VerifCond\n  Straightline_ Seq_ Diverge_ Fail_ Skip_ Assert_\n  Structured.If_ Structured.While_ Goto_ Structured.Call_ IGoto\n  setArgs Programming.Reserved Programming.Formals Programming.Precondition\n  importsMap fullImports buildLocals blocks union Nplus Nsucc length N_of_nat\n  List.fold_left ascii_lt string_lt label'_lt\n  LabelKey.compare' LabelKey.compare LabelKey.eq_dec\n  LabelMap.find\n  toCmd Seq Instr Diverge Fail Skip Assert_\n  Programming.If_ Programming.While_ Goto Programming.Call_ RvImm'\n  Assign' localsInvariant\n  regInL lvalIn immInR labelIn variableSlot string_eq ascii_eq\n  andb eqb qspecOut\n  ICall_ Structured.ICall_\n  Assert_ Structured.Assert_\n  LabelMap.Raw.find LabelMap.this LabelMap.Raw.add\n  LabelMap.empty LabelMap.Raw.empty string_dec\n  Ascii.ascii_dec string_rec string_rect 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\n  fst snd labl\n  Ascii.N_of_ascii Ascii.N_of_digits N.compare Nmult Pos.compare Pos.compare_cont\n  Pos.mul Pos.add LabelMap.Raw.bal\n  Int.Z_as_Int.gt_le_dec Int.Z_as_Int.ge_lt_dec LabelMap.Raw.create\n  ZArith_dec.Z_gt_le_dec Int.Z_as_Int.plus Int.Z_as_Int.max LabelMap.Raw.height\n  ZArith_dec.Z_gt_dec Int.Z_as_Int._1 BinInt.Z.add Int.Z_as_Int._0 Int.Z_as_Int._2 BinInt.Z.max\n  ZArith_dec.Zcompare_rec ZArith_dec.Z_ge_lt_dec BinInt.Z.compare BinInt.Z.ltb ZArith_dec.Zcompare_rect\n  ZArith_dec.Z_ge_dec label'_eq label'_rec label'_rect\n  COperand1 CTest COperand2 Pos.succ\n  makeVcs\n\n  Cond_ Cond\n  Lambda__ Lambda_\n].\n\nLtac vcgen :=\n(*TIME time \"vcgen:structured_auto\" ( *)\n  structured_auto vcgen_simp\n(*TIME ) *);\n(*TIME time \"vcgen:finish\" ( *)\n  autorewrite with sepFormula in *; simpl in *;\n    unfold starB, hvarB, hpropB in *; fold hprop in *; refold\n(*TIME ) *).\n\nHint Extern 1 => tauto : contradiction.\nHint Extern 1 => congruence : contradiction.\n\nLtac sep_easy := auto with contradiction.\n\nLemma frame_reflexivity : forall pcT stateT p q specs,\n  q = (fun pr => p (fst pr) (snd pr))\n  -> himp (pcType := pcT) (stateType := stateT) specs p (fun st m => q (st, m)).\n  intros; hnf; simpl; intros; subst.\n  apply Imply_I; eauto.\nQed.\n\nLtac rereg :=\n  repeat match goal with\n           | [ _ : context[Regs (match ?st with\n                                   | (_, y) => y\n                                 end) ?r] |- _ ] =>\n             change (Regs (let (_, y) := st in y) r) with (st#r) in *\n           | [ |- context[Regs (match ?st with\n                                  | (_, y) => y\n                                end) ?r] ] =>\n             change (Regs (let (_, y) := st in y) r) with (st#r) in *\n         end.\n\nLtac sep_firstorder := sep_easy;\n  repeat match goal with\n           | [ H : Logic.ex _ |- _ ] => destruct H\n           | [ H : _ /\\ _ |- _ ] => destruct H\n           | [ |- Logic.ex _ ] => sep_easy; eexists\n           | [ |- _ /\\ _ ] => split\n           | [ |- forall x, _ ] => intro\n           | [ |- _ = _ ] => reflexivity\n           | [ |- himp _ _ _ ] => reflexivity\n             || (apply frame_reflexivity; try match goal with\n                                                | [ |- _ = ?X ] => instantiate (1 := X)\n                                              end; apply refl_equal)\n         end; sep_easy; autorewrite with sepFormula; rereg; try subst.\n\nRequire Import Coq.NArith.NArith.\nImport TacPackIL.\n\nLtac hints_ext_simplifier hints := fun s1 s2 s3 H =>\n  match H with\n  | tt =>\n      cbv beta iota zeta\n       delta [s1 s2 s3 hints\n         (** Symbolic Evaluation **)\n         SymIL.MEVAL.PredEval.fold_args\n         SymIL.MEVAL.PredEval.fold_args_update SymIL.MEVAL.PredEval.pred_read_word\n         SymIL.MEVAL.PredEval.pred_write_word SymIL.MEVAL.PredEval.pred_read_byte SymIL.MEVAL.PredEval.pred_write_byte\n         SymIL.MEVAL.LearnHookDefault.LearnHook_default\n         SymIL.IL_ReadWord SymIL.IL_WriteWord SymIL.IL_ReadByte SymIL.IL_WriteByte\n         SymILTac.unfolder_LearnHook\n         SymIL.MEVAL.Composite.MemEvaluator_composite\n         SymIL.MEVAL.Default.smemeval_read_word_default\n         SymIL.MEVAL.Default.smemeval_write_word_default\n         SymIL.sym_evalInstrs\n         SymIL.sym_evalInstr SymIL.sym_evalLval SymIL.sym_evalRval\n         SymIL.sym_evalLoc SymIL.sym_evalStream SymIL.sym_assertTest\n         SymIL.sym_setReg SymIL.sym_getReg\n         SymIL.SymMem SymIL.SymRegs SymIL.SymPures\n(*         SymIL.SymVars SymIL.SymUVars *)\n         SymIL.stateD\n         SymILTac.quantifyNewVars\n         SymILTac.unfolder_LearnHook\n         ILAlgoTypes.Hints ILAlgoTypes.Prover\n         SymIL.MEVAL.sread_word SymIL.MEVAL.swrite_word SymIL.MEVAL.sread_byte SymIL.MEVAL.swrite_byte\n         ILAlgoTypes.MemEval ILAlgoTypes.Env ILAlgoTypes.Algos\n         (*SymIL.quantifyNewVars*)\n         ILAlgoTypes.Algos ILAlgoTypes.Hints ILAlgoTypes.Prover\n\n         SymEval.quantD SymEval.appendQ\n         SymEval.qex SymEval.qall\n         SymEval.gatherAll SymEval.gatherEx\n         SymILTac.sym_eval\n\n         (** ILEnv **)\n         ILEnv.comparator ILEnv.fPlus ILEnv.fMinus ILEnv.fMult\n         ILEnv.bedrock_types_r ILEnv.bedrock_funcs_r\n         ILEnv.bedrock_types\n         ILEnv.BedrockCoreEnv.core\n         ILEnv.BedrockCoreEnv.pc ILEnv.BedrockCoreEnv.st\n         ILEnv.bedrock_type_W ILEnv.bedrock_type_nat\n         ILEnv.bedrock_type_setting_X_state\n         ILEnv.bedrock_type_state\n(*         ILEnv.bedrock_type_test *)\n         ILEnv.bedrock_type_reg\n\n(*         ILEnv.test_seq *)\n         ILEnv.reg_seq\n         ILEnv.W_seq\n\n         ILEnv.word_nat_r\n         ILEnv.word_state_r\n(*         ILEnv.word_test_r *)\n\n         ILEnv.wplus_r\n         ILEnv.wminus_r\n         ILEnv.wmult_r\n(*         ILEnv.word_test_r *)\n(*         ILEnv.wcomparator_r *)\n         ILEnv.Regs_r\n         ILEnv.wlt_r\n         ILEnv.natToW_r\n\n\n         (** Env **)\n         Env.repr_combine Env.default Env.footprint Env.repr'\n         Env.updateAt Env.nil_Repr Env.repr Env.updateAt\n         Env.repr_combine Env.footprint Env.default Env.repr\n\n         (** Expr **)\n         Expr.Range Expr.Domain Expr.Denotation Expr.Impl Expr.Eqb\n         Expr.exists_subst Expr.forallEach Expr.existsEach\n         Expr.AllProvable Expr.AllProvable_gen\n         Expr.AllProvable_and Expr.AllProvable_impl\n         Expr.tvarD Expr.exprD Expr.applyD Expr.Impl_ Expr.EqDec_tvar\n         Expr.liftExpr Expr.lookupAs\n         Expr.Provable Expr.tvar_val_seqb\n         Expr.Provable Expr.tvarD\n         Expr.tvar_rec Expr.tvar_rect\n         Expr.Default_signature Expr.EmptySet_type\n         Expr.expr_seq_dec\n         Expr.Eqb Expr.liftExpr Expr.exprSubstU\n         Expr.typeof Expr.typeof_env\n         Expr.typeof_sig Expr.typeof_funcs\n         Expr.expr_ind\n         Expr.get_Eq\n         Expr.const_seqb\n         Expr.tvar_seqb\n         Expr.tvar_val_seqb_correct\n         Expr.tvar_seqb_correct\n         Expr.mentionsU\n         ReifyExpr.default_type\n\n         (** ExprUnify **)\n         CancelIL.U.exprUnify CancelIL.U.exprUnify_recursor\n         CancelIL.U.exprInstantiate CancelIL.U.subst_exprInstantiate\n         CancelIL.U.Subst_lookup CancelIL.U.subst_lookup\n         CancelIL.U.Subst_empty CancelIL.U.subst_empty\n         CancelIL.U.Subst_set CancelIL.U.subst_set\n         CancelIL.U.Subst_equations\n         CancelIL.U.Subst_size\n         CancelIL.U.dep_in\n\n         CancelIL.U.FM.Raw.height CancelIL.U.FM.Raw.cardinal CancelIL.U.FM.Raw.assert_false CancelIL.U.FM.Raw.create\n         CancelIL.U.FM.Raw.bal CancelIL.U.FM.Raw.remove_min CancelIL.U.FM.Raw.merge CancelIL.U.FM.Raw.join\n         CancelIL.U.FM.Raw.t_left CancelIL.U.FM.Raw.t_opt CancelIL.U.FM.Raw.t_right\n         CancelIL.U.FM.Raw.cardinal CancelIL.U.FM.Raw.empty CancelIL.U.FM.Raw.is_empty\n         CancelIL.U.FM.Raw.mem CancelIL.U.FM.Raw.find\n         CancelIL.U.FM.Raw.add  CancelIL.U.FM.Raw.remove\n         CancelIL.U.FM.Raw.fold CancelIL.U.FM.Raw.map CancelIL.U.FM.Raw.mapi CancelIL.U.FM.Raw.map2\n\n         CancelIL.U.FM.this CancelIL.U.FM.is_bst\n         CancelIL.U.FM.empty CancelIL.U.FM.is_empty\n         CancelIL.U.FM.add CancelIL.U.FM.remove\n         CancelIL.U.FM.mem CancelIL.U.FM.find\n         CancelIL.U.FM.map CancelIL.U.FM.mapi CancelIL.U.FM.map2\n         CancelIL.U.FM.elements CancelIL.U.FM.cardinal CancelIL.U.FM.fold\n         CancelIL.U.FM.equal\n         CancelIL.U.FM.E.eq_dec\n\n         (** Unfolder **)\n         Unfolder.FM.empty Unfolder.FM.add Unfolder.FM.remove\n         Unfolder.FM.fold Unfolder.FM.map\n         Unfolder.FM.find\n         UNF.Vars UNF.UVars UNF.Heap\n         UNF.LEM.Foralls UNF.LEM.Hyps UNF.LEM.Lhs UNF.LEM.Rhs\n         UNF.Forward UNF.forward UNF.unfoldForward\n         UNF.Backward UNF.backward UNF.unfoldBackward\n         UNF.findWithRest UNF.find equiv_dec\n         UNF.findWithRest'\n         Folds.allb\n         UNF.find UNF.default_hintsPayload\n         UNF.openForUnification\n         UNF.quant\n         UNF.liftInstantiate\n         SH.applySHeap\n         UNF.applicable UNF.checkAllInstantiated\n\n\n         (** NatMap **)\n         NatMap.singleton\n         NatMap.IntMap.Raw.height NatMap.IntMap.Raw.cardinal NatMap.IntMap.Raw.assert_false NatMap.IntMap.Raw.create\n         NatMap.IntMap.Raw.bal NatMap.IntMap.Raw.remove_min NatMap.IntMap.Raw.merge NatMap.IntMap.Raw.join\n         NatMap.IntMap.Raw.t_left NatMap.IntMap.Raw.t_opt NatMap.IntMap.Raw.t_right\n         NatMap.IntMap.Raw.cardinal NatMap.IntMap.Raw.empty NatMap.IntMap.Raw.is_empty\n         NatMap.IntMap.Raw.mem NatMap.IntMap.Raw.find\n         NatMap.IntMap.Raw.add  NatMap.IntMap.Raw.remove\n         NatMap.IntMap.Raw.fold NatMap.IntMap.Raw.map NatMap.IntMap.Raw.mapi NatMap.IntMap.Raw.map2\n\n         NatMap.IntMap.this NatMap.IntMap.is_bst\n         NatMap.IntMap.empty NatMap.IntMap.is_empty\n         NatMap.IntMap.add NatMap.IntMap.remove\n         NatMap.IntMap.mem NatMap.IntMap.find\n         NatMap.IntMap.map NatMap.IntMap.mapi NatMap.IntMap.map2\n         NatMap.IntMap.elements NatMap.IntMap.cardinal NatMap.IntMap.fold\n         NatMap.IntMap.equal\n\n         Int.Z_as_Int._0 Int.Z_as_Int._1 Int.Z_as_Int._2 Int.Z_as_Int._3\n         Int.Z_as_Int.plus Int.Z_as_Int.max\n         Int.Z_as_Int.gt_le_dec Int.Z_as_Int.ge_lt_dec\n\n         ZArith_dec.Z_gt_le_dec ZArith_dec.Z_ge_lt_dec ZArith_dec.Z_ge_dec\n         ZArith_dec.Z_gt_dec\n         ZArith_dec.Zcompare_rec ZArith_dec.Zcompare_rect\n\n         BinInt.Z.add BinInt.Z.max BinInt.Z.pos_sub\n         BinInt.Z.double BinInt.Z.succ_double BinInt.Z.pred_double\n\n         BinInt.Z.compare\n         BinInt.Z.ltb\n\n         BinPos.Pos.add BinPos.Pos.compare\n         BinPos.Pos.succ BinPos.Pos.compare_cont\n\n         Compare_dec.nat_compare CompOpp\n\n         NatMap.Ordered_nat.compare\n\n         sumor_rec sumor_rect\n         sumbool_rec sumbool_rect\n         eq_ind_r\n\n         (** Prover **)\n         Prover.Prove Prover.Prover Prover.Facts Prover.Learn Prover.Summarize\n         Prover.composite_ProverT\n\n         (** Provers **)\n         Provers.ComboProver\n\n(*\n         (** TransitivityProver **)\n         provers.TransitivityProver.transitivitySummarize\n         provers.TransitivityProver.transitivityLearn\n         provers.TransitivityProver.transitivityProve\n         provers.TransitivityProver.groupsOf\n         provers.TransitivityProver.addEquality\n         provers.TransitivityProver.proveEqual\n         provers.TransitivityProver.transitivityLearn\n         provers.TransitivityProver.inSameGroup\n         provers.TransitivityProver.in_seq\n         provers.TransitivityProver.groupWith\n         provers.TransitivityProver.transitivityProver\n*)\n\n         (** AssumptionProver **)\n         provers.AssumptionProver.assumptionProver\n         provers.AssumptionProver.assumptionSummarize\n         provers.AssumptionProver.assumptionLearn\n         provers.AssumptionProver.assumptionProve\n\n         (** ReflexivityProver **)\n         provers.ReflexivityProver.reflexivityProver\n         provers.ReflexivityProver.reflexivitySummarize\n         provers.ReflexivityProver.reflexivityLearn\n         provers.ReflexivityProver.reflexivityProve\n\n         (** WordProver **)\n         provers.WordProver.wordProver provers.WordProver.Source provers.WordProver.Destination provers.WordProver.Difference\n         provers.WordProver.pow32 provers.WordProver.wplus' provers.WordProver.wneg' provers.WordProver.wminus' wordBin NToWord Nplus minus\n         provers.WordProver.decompose combine Expr.expr_seq_dec provers.WordProver.combineAll provers.WordProver.combine app\n         provers.WordProver.alreadyCovered provers.WordProver.alreadyCovered' andb orb provers.WordProver.merge provers.WordProver.wordLearn1 provers.WordProver.wordLearn\n         provers.WordProver.equalitysEq ILEnv.W_seq Word.weqb weq provers.WordProver.equalityMatches provers.WordProver.wordProve provers.WordProver.wordSummarize\n         provers.WordProver.types ILEnv.bedrock_type_W provers.WordProver.zero Bool.bool_dec wzero' posToWord bool_rec bool_rect\n         Nminus wordToN Nsucc Nmult Pos.mul Pos.add Pos.sub_mask Pos.succ_double_mask Pos.double_mask Pos.pred_double\n         provers.WordProver.natToWord' mod2 Div2.div2 whd wtl Pos.double_pred_mask\n         provers.WordProver.Equalities provers.WordProver.LessThans provers.WordProver.NotEquals\n         provers.WordProver.lessThanMatches\n\n         (** ArrayBoundProver **)\n         provers.ArrayBoundProver.boundProver\n         provers.ArrayBoundProver.deupd provers.ArrayBoundProver.factIn\n         provers.ArrayBoundProver.boundLearn1 provers.ArrayBoundProver.boundLearn\n         provers.ArrayBoundProver.boundSummarize provers.ArrayBoundProver.hypMatches\n         provers.ArrayBoundProver.boundProve\n         provers.ArrayBoundProver.types\n\n         (** Induction **)\n         list_ind list_rec list_rect\n         sumbool_rect sumbool_rec\n         nat_rect nat_ind\n         eq_rect_r eq_rec_r eq_rec eq_rect eq_ind\n         eq_sym f_equal\n         sumbool_rec sumbool_rect\n         sumbool_rec sumbool_rect\n         sumor_rec sumor_rect\n         nat_rec nat_rect\n\n         (** Comparisons **)\n         Compare_dec.lt_dec Compare_dec.le_dec Compare_dec.le_gt_dec\n         Compare_dec.le_lt_dec Compare_dec.lt_eq_lt_dec\n         Compare_dec.lt_dec Compare_dec.le_dec Compare_dec.le_gt_dec\n         Compare_dec.le_lt_dec Compare_dec.lt_eq_lt_dec\n         Compare_dec.lt_eq_lt_dec\n         Peano_dec.eq_nat_dec\n         EquivDec_nat equiv_dec seq_dec\n         nat_eq_eqdec\n         EquivDec_SemiDec\n         Compare_dec.nat_compare\n         NPeano.leb NPeano.ltb\n         (* we fully qualify these names to work around the fact that they are new to 8.5 *)\n         Coq.Init.Peano.f_equal_nat Coq.Init.Peano.f_equal_pred Coq.Init.Peano.f_equal2_plus Coq.Init.Peano.f_equal2_nat Coq.Init.Peano.f_equal2_mult\n\n         (** SepExpr **)\n         SEP.SDomain SEP.SDenotation\n         SEP.Default_predicate\n         SEP.himp SEP.sexprD\n         SEP.heq\n         SEP.liftSExpr\n         SEP.typeof_pred SEP.typeof_preds\n\n         (** SepHeap **)\n         SH.impures SH.pures SH.other\n         SH.liftSHeap UNF.HEAP_FACTS.sheapSubstU\n         SH.starred SH.hash\n         SH.star_SHeap\n         SH.SHeap_empty\n         SH.sheapD\n\n         SepHeap.FM.empty\n         SepHeap.FM.map\n         SepHeap.FM.find\n         SepHeap.FM.add\n         SepHeap.FM.remove\n         SepHeap.FM.fold\n\n         (** SepCancel **)\n         CancelIL.CANCEL.sepCancel\n         CancelIL.CANCEL.expr_count_meta\n         CancelIL.CANCEL.exprs_count_meta\n         CancelIL.CANCEL.expr_size\n         CancelIL.CANCEL.meta_order_funcs\n         CancelIL.CANCEL.meta_order_args\n         CancelIL.CANCEL.order_impures\n         CancelIL.CANCEL.cancel_in_order\n         CancelIL.CANCEL.unify_remove CancelIL.CANCEL.unifyArgs\n         CancelIL.CANCEL.expr_size\n\n         CancelIL.canceller\n         CancelIL.substInEnv\n         CancelIL.existsMaybe\n         CancelIL.existsSubst\n\n         (** Ordering **)\n         Ordering.insert_in_order Ordering.list_lex_cmp Ordering.sort\n\n         (** Multimaps **)\n         SepHeap.MM.mmap_add SepHeap.MM.mmap_extend SepHeap.MM.mmap_join\n         SepHeap.MM.mmap_mapi SepHeap.MM.mmap_map\n         SepHeap.MM.empty\n\n         (** PtsTo Plugin **)\n         Plugin_PtsTo.ptsto32_ssig\n         Plugin_PtsTo.expr_equal Plugin_PtsTo.sym_read_word_ptsto32\n         Plugin_PtsTo.sym_write_word_ptsto32 Plugin_PtsTo.ptsto32_types_r\n         Plugin_PtsTo.types\n         Plugin_PtsTo.MemEval_ptsto32\n         Plugin_PtsTo.MemEvaluator_ptsto32\n\n         (** General Recursion **)\n         Fix Fix_F GenRec.wf_R_pair GenRec.wf_R_nat\n         GenRec.guard Acc_rect well_founded_ind\n         well_founded_induction_type Acc_inv ExprUnify.wf_R_expr\n\n         (** Folds **)\n         Folds.fold_left_2_opt Folds.fold_left_3_opt\n\n         (** List Functions **)\n         tl hd_error value error hd\n         nth_error Datatypes.length fold_right firstn skipn rev\n         rev_append map app fold_left\n\n         (** Aux Functions **)\n         fst snd projT1 projT2 Basics.impl value error\n         projT1 projT2 andb orb\n         plus minus\n\n         (** Reflection **)\n         (* Reflection.Reflect_eqb_nat *)\n\n         (** Array *)\n         Array.ssig Array.types_r Array.types\n         Array.MemEval Array.MemEvaluator\n         Array.div4 Array.deref Array.sym_read Array.sym_write\n         Array.wlength_r Array.sel_r Array.upd_r\n\n         (** Locals *)\n         Locals.bedrock_type_string Locals.bedrock_type_listString Locals.bedrock_type_vals\n         Locals.ssig Locals.types_r Locals.types\n         Locals.MemEval Locals.MemEvaluator\n         Locals.ascii_eq Locals.string_eq Bool.eqb\n         Locals.nil_r Locals.cons_r Locals.sel_r Locals.upd_r\n         Locals.deref Locals.listIn Locals.sym_sel Locals.sym_read Locals.sym_write\n\n         (** ?? **)\n         DepList.hlist_hd DepList.hlist_tl\n         eq_sym eq_trans\n         EqNat.beq_nat\n\n\n         (** TODO: sort these **)\n          ILAlgoTypes.Env ILAlgoTypes.Algos ILAlgoTypes.Algos_correct\n          ILAlgoTypes.PACK.Types ILAlgoTypes.PACK.Preds ILAlgoTypes.PACK.Funcs\n          ILAlgoTypes.PACK.applyTypes\n          ILAlgoTypes.PACK.applyFuncs\n          ILAlgoTypes.PACK.applyPreds\n\n          ILAlgoTypes.BedrockPackage.bedrock_package\n          Env.repr_combine Env.footprint Env.nil_Repr\n          Env.listToRepr\n          app map\n\n          ILEnv.bedrock_funcs_r ILEnv.bedrock_types_r\n          ILAlgoTypes.AllAlgos_composite\n          ILAlgoTypes.oplus Prover.composite_ProverT\n          (*TacPackIL.MEVAL.Composite.MemEvaluator_composite*) Env.listToRepr\n\n          Plugin_PtsTo.ptsto32_ssig Bedrock.sep.Array.ssig\n       ]\n  | _ =>\n    cbv beta iota zeta\n       delta [s1 s2 s3 hints\n         (** Symbolic Evaluation **)\n         SymIL.MEVAL.PredEval.fold_args\n         SymIL.MEVAL.PredEval.fold_args_update SymIL.MEVAL.PredEval.pred_read_word\n         SymIL.MEVAL.PredEval.pred_write_word SymIL.MEVAL.PredEval.pred_read_byte SymIL.MEVAL.PredEval.pred_write_byte\n         SymIL.MEVAL.LearnHookDefault.LearnHook_default\n         SymIL.IL_ReadWord SymIL.IL_WriteWord SymIL.IL_ReadByte SymIL.IL_WriteByte\n         SymILTac.unfolder_LearnHook\n         SymIL.MEVAL.Composite.MemEvaluator_composite\n         SymIL.MEVAL.Default.smemeval_read_word_default\n         SymIL.MEVAL.Default.smemeval_write_word_default\n         SymIL.sym_evalInstrs\n         SymIL.sym_evalInstr SymIL.sym_evalLval SymIL.sym_evalRval\n         SymIL.sym_evalLoc SymIL.sym_evalStream SymIL.sym_assertTest\n         SymIL.sym_setReg SymIL.sym_getReg\n         SymIL.SymMem SymIL.SymRegs SymIL.SymPures\n(*         SymIL.SymVars SymIL.SymUVars *)\n         SymIL.stateD SymIL.qstateD\n         SymILTac.quantifyNewVars\n         SymILTac.unfolder_LearnHook\n         ILAlgoTypes.Hints ILAlgoTypes.Prover\n         SymIL.MEVAL.sread_word SymIL.MEVAL.swrite_word SymIL.MEVAL.sread_byte SymIL.MEVAL.swrite_byte\n         ILAlgoTypes.MemEval ILAlgoTypes.Env ILAlgoTypes.Algos\n         (*SymIL.quantifyNewVars*)\n         ILAlgoTypes.Algos ILAlgoTypes.Hints ILAlgoTypes.Prover\n\n         SymEval.quantD SymEval.appendQ\n         SymEval.qex SymEval.qall\n         SymEval.gatherAll SymEval.gatherEx\n         SymILTac.sym_eval\n\n         (** ILEnv **)\n         ILEnv.comparator ILEnv.fPlus ILEnv.fMinus ILEnv.fMult\n         ILEnv.bedrock_types_r ILEnv.bedrock_funcs_r\n         ILEnv.bedrock_types\n         ILEnv.BedrockCoreEnv.core\n         ILEnv.BedrockCoreEnv.pc ILEnv.BedrockCoreEnv.st\n         ILEnv.bedrock_type_W ILEnv.bedrock_type_nat\n         ILEnv.bedrock_type_setting_X_state\n         ILEnv.bedrock_type_state\n(*         ILEnv.bedrock_type_test *)\n         ILEnv.bedrock_type_reg\n\n(*         ILEnv.test_seq *)\n         ILEnv.reg_seq\n         ILEnv.W_seq\n\n         ILEnv.word_nat_r\n         ILEnv.word_state_r\n(*         ILEnv.word_test_r *)\n\n         ILEnv.wplus_r\n         ILEnv.wminus_r\n         ILEnv.wmult_r\n(*         ILEnv.word_test_r *)\n(*         ILEnv.wcomparator_r *)\n         ILEnv.Regs_r\n         ILEnv.wlt_r\n         ILEnv.natToW_r\n\n         (** Env **)\n         Env.repr_combine Env.default Env.footprint Env.repr'\n         Env.updateAt Env.nil_Repr Env.repr Env.updateAt\n         Env.repr_combine Env.footprint Env.default Env.repr\n\n         (** Expr **)\n         Expr.Range Expr.Domain Expr.Denotation Expr.Impl\n         Expr.exists_subst Expr.forallEach Expr.existsEach\n         Expr.AllProvable_and Expr.AllProvable_impl Expr.AllProvable_gen\n         Expr.tvarD Expr.exprD Expr.applyD Expr.Impl_ Expr.EqDec_tvar\n         Expr.tvar_rec Expr.tvar_rect Expr.liftExpr Expr.lookupAs Expr.Eqb\n         Expr.Provable Expr.tvar_val_seqb\n         Expr.applyD Expr.exprD Expr.Range Expr.Domain Expr.Denotation\n         Expr.lookupAs Expr.AllProvable Expr.AllProvable_gen\n         Expr.Provable Expr.tvarD\n         Expr.expr_seq_dec\n         Expr.applyD Expr.exprD Expr.Range Expr.Domain Expr.Denotation\n         Expr.lookupAs\n         Expr.tvarD Expr.Eqb\n         Expr.EqDec_tvar Expr.tvar_rec Expr.tvar_rect\n         Expr.Default_signature Expr.EmptySet_type Expr.Impl Expr.EqDec_tvar Expr.tvar_rec Expr.tvar_rect\n         Expr.expr_seq_dec  Expr.expr_seq_dec\n         Expr.tvar_val_seqb  Expr.liftExpr Expr.exprSubstU\n         Expr.typeof Expr.typeof_env\n         Expr.typeof_sig Expr.typeof_funcs\n         Expr.Impl_ Expr.exprD\n         Expr.expr_ind\n         Expr.expr_seq_dec\n         Expr.get_Eq\n         Expr.const_seqb\n         Expr.tvar_seqb\n         Expr.tvar_val_seqb_correct\n         Expr.tvar_seqb_correct\n         Expr.mentionsU\n         ReifyExpr.default_type\n\n\n         (** ExprUnify **)\n         CancelIL.U.exprUnify CancelIL.U.exprUnify_recursor\n         CancelIL.U.exprInstantiate CancelIL.U.subst_exprInstantiate\n         CancelIL.U.Subst_lookup CancelIL.U.subst_lookup\n         CancelIL.U.Subst_empty CancelIL.U.subst_empty\n         CancelIL.U.Subst_set CancelIL.U.subst_set\n         CancelIL.U.Subst_equations\n         CancelIL.U.Subst_size\n         CancelIL.U.dep_in\n\n         CancelIL.U.FM.Raw.height CancelIL.U.FM.Raw.cardinal CancelIL.U.FM.Raw.assert_false CancelIL.U.FM.Raw.create\n         CancelIL.U.FM.Raw.bal CancelIL.U.FM.Raw.remove_min CancelIL.U.FM.Raw.merge CancelIL.U.FM.Raw.join\n         CancelIL.U.FM.Raw.t_left CancelIL.U.FM.Raw.t_opt CancelIL.U.FM.Raw.t_right\n         CancelIL.U.FM.Raw.cardinal CancelIL.U.FM.Raw.empty CancelIL.U.FM.Raw.is_empty\n         CancelIL.U.FM.Raw.mem CancelIL.U.FM.Raw.find\n         CancelIL.U.FM.Raw.add  CancelIL.U.FM.Raw.remove\n         CancelIL.U.FM.Raw.fold CancelIL.U.FM.Raw.map CancelIL.U.FM.Raw.mapi CancelIL.U.FM.Raw.map2\n\n         CancelIL.U.FM.this CancelIL.U.FM.is_bst\n         CancelIL.U.FM.empty CancelIL.U.FM.is_empty\n         CancelIL.U.FM.add CancelIL.U.FM.remove\n         CancelIL.U.FM.mem CancelIL.U.FM.find\n         CancelIL.U.FM.map CancelIL.U.FM.mapi CancelIL.U.FM.map2\n         CancelIL.U.FM.elements CancelIL.U.FM.cardinal CancelIL.U.FM.fold\n         CancelIL.U.FM.equal\n         CancelIL.U.FM.E.eq_dec\n\n         (** Unfolder **)\n         Unfolder.FM.empty Unfolder.FM.add Unfolder.FM.remove\n         Unfolder.FM.fold Unfolder.FM.map\n         Unfolder.FM.find\n         UNF.LEM.Foralls UNF.Vars\n         UNF.UVars UNF.Heap UNF.LEM.Hyps UNF.LEM.Lhs UNF.LEM.Rhs\n         UNF.Forward UNF.forward UNF.unfoldForward UNF.Backward\n         UNF.backward UNF.unfoldBackward  equiv_dec\n         UNF.find UNF.findWithRest UNF.findWithRest'\n         Folds.allb\n         UNF.openForUnification\n         UNF.quant\n         UNF.liftInstantiate\n         SH.applySHeap\n         UNF.find UNF.default_hintsPayload\n         UNF.applicable UNF.checkAllInstantiated\n\n         (** NatMap **)\n         NatMap.singleton\n         NatMap.IntMap.Raw.height NatMap.IntMap.Raw.cardinal NatMap.IntMap.Raw.assert_false NatMap.IntMap.Raw.create\n         NatMap.IntMap.Raw.bal NatMap.IntMap.Raw.remove_min NatMap.IntMap.Raw.merge NatMap.IntMap.Raw.join\n         NatMap.IntMap.Raw.t_left NatMap.IntMap.Raw.t_opt NatMap.IntMap.Raw.t_right\n         NatMap.IntMap.Raw.cardinal NatMap.IntMap.Raw.empty NatMap.IntMap.Raw.is_empty\n         NatMap.IntMap.Raw.mem NatMap.IntMap.Raw.find\n         NatMap.IntMap.Raw.add  NatMap.IntMap.Raw.remove\n         NatMap.IntMap.Raw.fold NatMap.IntMap.Raw.map NatMap.IntMap.Raw.mapi NatMap.IntMap.Raw.map2\n\n         NatMap.IntMap.this NatMap.IntMap.is_bst\n         NatMap.IntMap.empty NatMap.IntMap.is_empty\n         NatMap.IntMap.add NatMap.IntMap.remove\n         NatMap.IntMap.mem NatMap.IntMap.find\n         NatMap.IntMap.map NatMap.IntMap.mapi NatMap.IntMap.map2\n         NatMap.IntMap.elements NatMap.IntMap.cardinal NatMap.IntMap.fold\n         NatMap.IntMap.equal\n\n         Int.Z_as_Int._0 Int.Z_as_Int._1 Int.Z_as_Int._2 Int.Z_as_Int._3\n         Int.Z_as_Int.plus Int.Z_as_Int.max\n         Int.Z_as_Int.gt_le_dec Int.Z_as_Int.ge_lt_dec\n\n         ZArith_dec.Z_gt_le_dec ZArith_dec.Z_ge_lt_dec ZArith_dec.Z_ge_dec\n         ZArith_dec.Z_gt_dec\n         ZArith_dec.Zcompare_rec ZArith_dec.Zcompare_rect\n\n         BinInt.Z.add BinInt.Z.max BinInt.Z.pos_sub\n         BinInt.Z.double BinInt.Z.succ_double BinInt.Z.pred_double\n\n         BinInt.Z.compare\n         BinInt.Z.ltb\n\n         BinPos.Pos.add BinPos.Pos.compare\n         BinPos.Pos.succ BinPos.Pos.compare_cont\n\n         Compare_dec.nat_compare CompOpp\n\n         NatMap.Ordered_nat.compare\n\n         sumor_rec sumor_rect\n         sumbool_rec sumbool_rect\n         eq_ind_r\n\n         (** Prover **)\n         Prover.Prove Prover.Prover Prover.Facts Prover.Learn Prover.Summarize\n         Prover.composite_ProverT\n\n         (** Provers **)\n         Provers.ComboProver\n\n(*\n         (** TransitivityProver **)\n         provers.TransitivityProver.transitivitySummarize\n         provers.TransitivityProver.transitivityLearn\n         provers.TransitivityProver.transitivityProve\n         provers.TransitivityProver.groupsOf\n         provers.TransitivityProver.addEquality\n         provers.TransitivityProver.proveEqual\n         provers.TransitivityProver.transitivityLearn\n         provers.TransitivityProver.inSameGroup\n         provers.TransitivityProver.in_seq\n         provers.TransitivityProver.groupWith\n         provers.TransitivityProver.transitivityProver\n*)\n\n         (** AssumptionProver **)\n         provers.AssumptionProver.assumptionProver\n         provers.AssumptionProver.assumptionSummarize\n         provers.AssumptionProver.assumptionLearn\n         provers.AssumptionProver.assumptionProve\n\n         (** ReflexivityProver **)\n         provers.ReflexivityProver.reflexivityProver\n         provers.ReflexivityProver.reflexivitySummarize\n         provers.ReflexivityProver.reflexivityLearn\n         provers.ReflexivityProver.reflexivityProve\n\n         (** WordProver **)\n         provers.WordProver.wordProver provers.WordProver.Source provers.WordProver.Destination provers.WordProver.Difference\n         provers.WordProver.pow32 provers.WordProver.wplus' provers.WordProver.wneg' provers.WordProver.wminus' wordBin NToWord Nplus minus\n         provers.WordProver.decompose combine Expr.expr_seq_dec provers.WordProver.combineAll provers.WordProver.combine app\n         provers.WordProver.alreadyCovered provers.WordProver.alreadyCovered' andb orb provers.WordProver.merge provers.WordProver.wordLearn1 provers.WordProver.wordLearn\n         provers.WordProver.equalitysEq ILEnv.W_seq Word.weqb weq provers.WordProver.equalityMatches provers.WordProver.wordProve provers.WordProver.wordSummarize\n         provers.WordProver.types ILEnv.bedrock_type_W provers.WordProver.zero Bool.bool_dec wzero' posToWord bool_rec bool_rect\n         Nminus wordToN Nsucc Nmult Pos.mul Pos.add Pos.sub_mask Pos.succ_double_mask Pos.double_mask Pos.pred_double\n         provers.WordProver.natToWord' mod2 Div2.div2 whd wtl Pos.double_pred_mask\n         provers.WordProver.Equalities provers.WordProver.LessThans provers.WordProver.NotEquals\n         provers.WordProver.lessThanMatches\n\n         (** ArrayBoundProver **)\n         provers.ArrayBoundProver.boundProver\n         provers.ArrayBoundProver.deupd provers.ArrayBoundProver.factIn\n         provers.ArrayBoundProver.boundLearn1 provers.ArrayBoundProver.boundLearn\n         provers.ArrayBoundProver.boundSummarize provers.ArrayBoundProver.hypMatches\n         provers.ArrayBoundProver.boundProve\n         provers.ArrayBoundProver.types\n\n         (** Induction **)\n         list_ind list_rec list_rect\n         sumbool_rect sumbool_rec\n         sumor_rec sumor_rect\n         nat_rec nat_rect nat_ind\n         eq_rect_r eq_rec_r eq_rec eq_rect\n         eq_sym f_equal\n         nat_rect eq_ind eq_rec eq_rect\n         eq_rec_r eq_rect eq_rec nat_rec nat_rect\n         sumbool_rec sumbool_rect\n         sumbool_rec sumbool_rect\n         sumor_rec sumor_rect\n         nat_rec nat_rect\n\n         (** Comparisons **)\n         Compare_dec.lt_dec Compare_dec.le_dec Compare_dec.le_gt_dec\n         Compare_dec.le_lt_dec Compare_dec.lt_eq_lt_dec\n         Compare_dec.lt_dec Compare_dec.le_dec Compare_dec.le_gt_dec\n         Compare_dec.le_lt_dec Compare_dec.lt_eq_lt_dec\n         Compare_dec.lt_eq_lt_dec\n         Peano_dec.eq_nat_dec\n         EquivDec_nat  equiv_dec seq_dec\n         nat_eq_eqdec\n         EquivDec_SemiDec\n         Compare_dec.nat_compare\n         NPeano.leb NPeano.ltb\n         (* we fully qualify these names to work around the fact that they are new to 8.5 *)\n         Coq.Init.Peano.f_equal_nat Coq.Init.Peano.f_equal_pred Coq.Init.Peano.f_equal2_plus Coq.Init.Peano.f_equal2_nat Coq.Init.Peano.f_equal2_mult\n\n         (** SepExpr **)\n         SEP.SDomain SEP.SDenotation\n         SEP.Default_predicate\n         SEP.himp SEP.sexprD\n         SEP.heq\n         nat_eq_eqdec\n         SEP.liftSExpr\n\n         (** SepHeap **)\n         SH.impures SH.pures SH.other\n         SH.liftSHeap UNF.HEAP_FACTS.sheapSubstU\n         SH.starred SH.hash\n         SH.star_SHeap\n         SH.SHeap_empty\n         SH.sheapD\n\n         SepHeap.FM.empty\n         SepHeap.FM.map\n         SepHeap.FM.find\n         SepHeap.FM.add\n         SepHeap.FM.remove\n         SepHeap.FM.fold\n\n         (** SepCancel **)\n         CancelIL.CANCEL.sepCancel\n         CancelIL.CANCEL.expr_count_meta\n         CancelIL.CANCEL.exprs_count_meta\n         CancelIL.CANCEL.expr_size\n         CancelIL.CANCEL.meta_order_funcs\n         CancelIL.CANCEL.meta_order_args\n         CancelIL.CANCEL.order_impures\n         CancelIL.CANCEL.cancel_in_order\n         CancelIL.CANCEL.unify_remove\n         CancelIL.CANCEL.unifyArgs\n         CancelIL.CANCEL.expr_size\n\n         CancelIL.canceller\n         CancelIL.substInEnv\n         CancelIL.existsMaybe\n         CancelIL.existsSubst\n\n         (** Ordering **)\n         Ordering.insert_in_order Ordering.list_lex_cmp Ordering.sort\n\n         (** Multimaps **)\n         SepHeap.MM.mmap_add SepHeap.MM.mmap_extend SepHeap.MM.mmap_join\n         SepHeap.MM.mmap_mapi SepHeap.MM.mmap_map\n         SepHeap.MM.empty\n\n         (** PtsTo Plugin **)\n         Plugin_PtsTo.ptsto32_ssig\n         Plugin_PtsTo.expr_equal Plugin_PtsTo.sym_read_word_ptsto32\n         Plugin_PtsTo.sym_write_word_ptsto32 Plugin_PtsTo.ptsto32_types_r\n         Plugin_PtsTo.types\n         Plugin_PtsTo.MemEval_ptsto32\n         Plugin_PtsTo.MemEvaluator_ptsto32\n\n         (** General Recursion **)\n         Fix Fix_F GenRec.wf_R_pair GenRec.wf_R_nat\n         GenRec.guard Acc_rect well_founded_ind\n         well_founded_induction_type Acc_inv ExprUnify.wf_R_expr\n\n         (** Folds **)\n         Folds.fold_left_2_opt Folds.fold_left_3_opt\n\n         (** List Functions **)\n         tl hd_error value error hd\n         nth_error Datatypes.length fold_right firstn skipn rev\n         rev_append List.map app fold_left\n\n         (** Aux Functions **)\n         fst snd projT1 projT2 Basics.impl value error\n         projT1 projT2 andb orb\n         plus minus\n\n         (** Reflection **)\n         (* Reflection.Reflect_eqb_nat *)\n\n         (** Array *)\n         Array.ssig Array.types_r Array.types\n         Array.MemEval Array.MemEvaluator\n         Array.div4 Array.deref Array.sym_read Array.sym_write\n         Array.wlength_r Array.sel_r Array.upd_r\n\n         (** Locals *)\n         Locals.bedrock_type_string Locals.bedrock_type_listString Locals.bedrock_type_vals\n         Locals.ssig Locals.types_r Locals.types\n         Locals.MemEval Locals.MemEvaluator\n         Locals.ascii_eq Locals.string_eq Bool.eqb\n         Locals.nil_r Locals.cons_r Locals.sel_r Locals.upd_r\n         Locals.deref Locals.listIn Locals.sym_sel Locals.sym_read Locals.sym_write\n\n         (** ?? **)\n         DepList.hlist_hd DepList.hlist_tl\n         eq_sym eq_trans\n         EqNat.beq_nat\n\n         (** TODO: sort these **)\n         ILAlgoTypes.Env ILAlgoTypes.Algos ILAlgoTypes.Algos_correct\n         ILAlgoTypes.PACK.Types ILAlgoTypes.PACK.Preds ILAlgoTypes.PACK.Funcs\n         ILAlgoTypes.PACK.applyTypes\n         ILAlgoTypes.PACK.applyFuncs\n         ILAlgoTypes.PACK.applyPreds\n\n         ILAlgoTypes.BedrockPackage.bedrock_package\n         Env.repr_combine Env.footprint Env.nil_Repr\n         Env.listToRepr\n         app map\n\n         ILEnv.bedrock_funcs_r ILEnv.bedrock_types_r\n         ILAlgoTypes.AllAlgos_composite\n         ILAlgoTypes.oplus Prover.composite_ProverT\n         (*TacPackIL.MEVAL.Composite.MemEvaluator_composite*) Env.listToRepr\n\n         Plugin_PtsTo.ptsto32_ssig Bedrock.sep.Array.ssig\n\n       ] in H\n  end; refold.\n\nLtac clear_junk := repeat match goal with\n                            | [ H : True |- _ ] => clear H\n                            | [ H : ?X = ?X |- _ ] => clear H\n                                | [ H : ?X, H' : ?X |- _ ] => clear H'\n                          end.\n\nLtac evaluate ext :=\n  repeat match goal with\n           | [ H : ?P -> False |- _ ] => change (not P) in H\n         end;\n  ILTac.sym_eval ltac:(ILTacCommon.isConst) ext ltac:(hints_ext_simplifier ext);\n  clear_junk.\n\nLtac cancel ext := sep_canceller ltac:(ILTacCommon.isConst) ext ltac:(hints_ext_simplifier ext); sep_firstorder; clear_junk.\n\nLtac unf := unfold substH.\nLtac reduce := Programming.reduce unf.\nLtac ho := Programming.ho unf; reduce.\n\nTheorem implyR : forall pc state specs (P Q R : PropX pc state),\n  interp specs (P ---> R)\n  -> interp specs (P ---> Q ---> R)%PropX.\n  intros.\n  do 2 apply Imply_I.\n  eapply Imply_E.\n  eauto.\n  constructor; simpl; tauto.\nQed.\n\nInductive pureConsequences : HProp -> list Prop -> Prop :=\n| PurePure : forall P, pureConsequences [| P |]%Sep (P :: nil)\n| PureStar : forall P P' Q Q', pureConsequences P P'\n  -> pureConsequences Q Q'\n  -> pureConsequences (P * Q)%Sep (P' ++ Q')\n| PureOther : forall P, pureConsequences P nil.\n\nTheorem pureConsequences_correct : forall P P',\n  pureConsequences P P'\n  -> forall specs stn st, interp specs (P stn st ---> [| List.Forall (fun p => p) P' |]%PropX).\n  induction 1; intros.\n\n  unfold injB, inj.\n  apply Imply_I.\n  eapply Inj_E.\n  eapply And_E1; apply Env; simpl; eauto.\n  intro; apply Inj_I; repeat constructor; assumption.\n\n  unfold starB, star.\n  apply Imply_I.\n  eapply Exists_E.\n  apply Env; simpl; eauto.\n  simpl; intro.\n  eapply Exists_E.\n  apply Env; simpl; left; eauto.\n  simpl; intro.\n  eapply Inj_E.\n  eapply Imply_E.\n  apply interp_weaken; apply IHpureConsequences1.\n  eapply And_E1; eapply And_E2; apply Env; simpl; eauto.\n  intro.\n  eapply Inj_E.\n  eapply Imply_E.\n  apply interp_weaken; apply IHpureConsequences2.\n  do 2 eapply And_E2; apply Env; simpl; eauto.\n  intro.\n  apply Inj_I.\n  apply Forall_app; auto.\n\n  apply Imply_I; apply Inj_I; auto.\nQed.\n\nTheorem extractPure : forall specs P Q Q' R st,\n  pureConsequences Q Q'\n  -> (List.Forall (fun p => p) Q' -> interp specs (P ---> R))\n  -> interp specs (P ---> ![Q] st ---> R)%PropX.\n  intros.\n  do 2 apply Imply_I.\n  eapply Inj_E.\n  eapply Imply_E.\n  apply interp_weaken.\n  apply pureConsequences_correct; eauto.\n  rewrite sepFormula_eq.\n  unfold sepFormula_def.\n  apply Env; simpl; eauto.\n  intro.\n  eapply Imply_E.\n  eauto.\n  apply Env; simpl; eauto.\nQed.\n\nLtac words := repeat match goal with\n                       | [ H : _ = _ |- _ ] => rewrite H\n                     end; W_eq.\n\nDefinition locals_return ns vs avail p (ns' : list string) (avail' offset : nat) :=\n  locals ns vs avail p.\n\nTheorem create_locals_return : forall ns' avail' ns avail offset vs p,\n  locals ns vs avail p = locals_return ns vs avail p ns' avail' offset.\n  reflexivity.\nQed.\n\nDefinition ok_return (ns ns' : list string) (avail avail' offset : nat) :=\n  (avail >= avail' + length ns')%nat\n  /\\ offset = 4 * length ns.\n\nLtac peelPrefix ls1 ls2 :=\n  match ls1 with\n    | nil => ls2\n    | ?x :: ?ls1' =>\n      match ls2 with\n        | x :: ?ls2' => peelPrefix ls1' ls2'\n      end\n  end.\n\nGlobal Opaque merge.\n\nTheorem use_HProp_extensional : forall p, HProp_extensional p\n  -> (fun st sm => p st sm) = p.\n  auto.\nQed.\n\nLtac descend :=\n  (*TIME time \"descend:descend\" *)\n  Programming.descend;\n  (*TIME time \"descend:reduce\" *)\n  reduce;\n  (*TIME time \"descend:unfold_simpl\" ( *)\n  unfold hvarB; simpl; rereg\n  (*TIME ) *);\n  (*TIME time \"descend:loop\" *)\n    (repeat match goal with\n             | [ |- context[fun stn0 sm => ?f stn0 sm] ] =>\n               rewrite (@use_HProp_extensional f) by auto\n             | [ |- context[fun stn0 sm => ?f ?a stn0 sm] ] =>\n               rewrite (@use_HProp_extensional (f a)) by auto\n             | [ |- context[fun stn0 sm => ?f ?a ?b stn0 sm] ] =>\n               rewrite (@use_HProp_extensional (f a b)) by auto\n             | [ |- context[fun stn0 sm => ?f ?a ?b ?c stn0 sm] ] =>\n               rewrite (@use_HProp_extensional (f a b c)) by auto\n             | [ |- context[fun stn0 sm => ?f ?a ?b ?c ?d stn0 sm] ] =>\n               rewrite (@use_HProp_extensional (f a b c d)) by auto\n             | [ |- context[fun stn0 sm => ?f ?a ?b ?c ?d ?e stn0 sm] ] =>\n               rewrite (@use_HProp_extensional (f a b c d e)) by auto\n             | [ |- context[fun stn0 sm => ?f ?a ?b ?c ?d ?e ?f stn0 sm] ] =>\n               rewrite (@use_HProp_extensional (f a b c d e f)) by auto\n           end);\n    try match goal with\n          | [ p : (ST.settings * state)%type |- _ ] => destruct p; simpl in *\n        end.\n\nDefinition locals_call ns vs avail p (ns' : list string) (avail' : nat) (offset : nat) :=\n  locals ns vs avail p.\n\nDefinition ok_call (ns ns' : list string) (avail avail' : nat) (offset : nat) :=\n  (length ns' <= avail)%nat\n  /\\ (avail' <= avail - length ns')%nat\n  /\\ NoDup ns'\n  /\\ offset = 4 * length ns.\n\nDefinition excessStack (p : W) (ns : list string) (avail : nat) (ns' : list string) (avail' : nat) :=\n  reserved (p ^+ natToW (4 * (length ns + length ns' + avail')))\n  (avail - length ns' - avail').\n\nLemma make_call : forall ns ns' vs avail avail' p offset,\n  ok_call ns ns' avail avail' offset\n  -> locals_call ns vs avail p ns' avail' offset ===>\n  locals ns vs 0 p\n  * Ex vs', locals ns' vs' avail' (p ^+ natToW offset)\n  * excessStack p ns avail ns' avail'.\n  unfold ok_call; intuition; subst; eapply do_call; eauto.\nQed.\n\nLemma make_return : forall ns ns' vs avail avail' p offset,\n  ok_return ns ns' avail avail' offset\n  -> (locals ns vs 0 p\n    * Ex vs', locals ns' vs' avail' (p ^+ natToW offset)\n    * excessStack p ns avail ns' avail')\n  ===> locals_return ns vs avail p ns' avail' offset.\n  unfold ok_return; intuition; subst; apply do_return; omega || words.\nQed.\n\nDefinition locals_in ns vs avail p (ns' ns'' : list string) (avail' : nat) :=\n  locals ns vs avail p.\n\nOpen Scope list_scope.\n\nDefinition ok_in (ns : list string) (avail : nat) (ns' ns'' : list string) (avail' : nat) :=\n  ns ++ ns' = ns'' /\\ (length ns' <= avail)%nat /\\ NoDup (ns ++ ns')\n  /\\ avail' = avail - length ns'.\n\nTheorem init_in : forall ns ns' ns'' vs avail p avail',\n  ok_in ns avail ns' ns'' avail'\n  -> locals_in ns vs avail p ns' ns'' avail' ===>\n  Ex vs', locals ns'' (merge vs vs' ns) avail' p.\n  unfold ok_in; intuition; subst; apply prelude_in; auto.\nQed.\n\nDefinition locals_out ns vs avail p (ns' ns'' : list string) (avail' : nat) :=\n  locals ns vs avail p.\n\nDefinition ok_out (ns : list string) (avail : nat) (ns' ns'' : list string) (avail' : nat) :=\n  ns ++ ns' = ns'' /\\ (length ns' <= avail)%nat\n  /\\ avail' = avail - length ns'.\n\nTheorem init_out : forall ns ns' ns'' vs avail p avail',\n  ok_out ns avail ns' ns'' avail'\n  -> locals ns'' vs avail' p\n  ===> locals_out ns vs avail p ns' ns'' avail'.\n  unfold ok_out; intuition; subst; apply prelude_out; auto.\nQed.\n\nLtac prepare fwd bwd :=\n  let the_unfold_tac x :=\n    eval unfold empB, injB, injBX, starB, exB, hvarB in x\n  in\n  ILAlgoTypes.Tactics.Extension.extend the_unfold_tac\n    ILTacCommon.isConst auto_ext' tt tt (make_call, init_in, fwd) (make_return, init_out, bwd).\n\nDefinition auto_ext : TacPackage.\n  prepare tt tt.\nDefined.\n\nTheorem create_locals_out : forall ns' ns'' avail' ns avail vs p,\n  locals ns vs avail p = locals_out ns vs avail p ns' ns'' avail'.\n  reflexivity.\nQed.\n\nLtac step ext :=\n  let considerImp pre post :=\n    try 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;\n                                generalize dependent vs'; intros\n                        end\n                    end\n                end\n              | context[locals ?ns' ?vs' ?avail' _] =>\n                match avail' with\n                  | avail => fail 1\n                  | _ =>\n                    match vs' with\n                      | vs => constr_eq vs' vs; fail 1\n                      | _ => let ns'' := peelPrefix ns ns' in\n                        rewrite (create_locals_out ns'' ns' avail' ns avail);\n                          assert (ok_out ns avail ns'' ns' avail')%nat by (split; [\n                            reflexivity\n                            | split; [\n                              simpl; omega\n                              | reflexivity ] ] )\n                    end\n                end\n            end\n        end;\n    progress cancel ext in\n\n  match goal with\n    | [ |- _ _ = Some _ ] => solve [ eauto ]\n    | [ _ : interp _ (![ ?pre ] _) |- interp _ (![ ?post ] _) ] => considerImp pre post\n    | [ |- interp _ (![?pre]%PropX _ ---> ![?post]%PropX _) ] => considerImp pre post\n    | [ |- himp _ ?pre ?post ] => considerImp pre post\n    | [ |- interp _ (_ _ _ ?x ---> _ _ _ ?y ---> _ ?x)%PropX ] =>\n      match y with\n        | x => fail 1\n        | _ => eapply extractPure; [ repeat constructor\n          | cbv zeta; simpl; intro; repeat match goal with\n                                             | [ H : List.Forall _ nil |- _ ] => clear H\n                                             | [ H : List.Forall _ (_ :: _) |- _ ] => inversion H; clear H; subst\n                                           end; clear_junk ]\n        | _ => apply implyR\n      end\n    | _ => ho; rereg\n  end.\n\nLtac slotVariable E :=\n  match E with\n    | 4 => constr:(\"0\")\n    | 8 => constr:(\"1\")\n    | 12 => constr:(\"2\")\n    | 16 => constr:(\"3\")\n    | 20 => constr:(\"4\")\n    | 24 => constr:(\"5\")\n    | 28 => constr:(\"6\")\n    | 32 => constr:(\"7\")\n    | 36 => constr:(\"8\")\n    | 40 => constr:(\"9\")\n  end.\n\nLtac slotVariables E :=\n  match E with\n    | Binop (LvReg Rv) (RvLval (LvReg Sp)) Plus (RvImm (natToW _))\n      :: Assign (LvMem (Indir Rv (natToW ?slot))) _\n      :: ?E' =>\n      let v := slotVariable slot in\n        let vs := slotVariables E' in\n          constr:(v :: vs)\n    | _ :: ?E' => slotVariables E'\n    | nil => constr:(@nil string)\n  end.\n\nLtac post :=\n  (*TIME time \"post:propxFo\" *)\n  propxFo;\n  (*TIME time \"post:autorewrite\" ( *)\n  autorewrite with sepFormula in *\n  (*TIME ) *) ;\n  unfold substH in *;\n  (*TIME time \"post:simpl\" ( *)\n  simpl in *; rereg; autorewrite with IL;\n    try match goal with\n          | [ H : context[locals ?ns ?vs ?avail ?p]\n              |- context[locals ?ns' _ ?avail' _] ] =>\n            match avail' with\n              | avail => fail 1\n              | _ =>\n                (let ns'' := peelPrefix ns ns' in\n                 let exposed := eval simpl in (avail - avail') in\n                 let new := eval simpl in (List.length ns' - List.length ns) in\n                 match new with\n                   | exposed =>\n                     let avail' := eval simpl in (avail - List.length ns'') 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; [simpl; omega\n                             | split; [ repeat constructor; simpl; intuition congruence\n                               | reflexivity ] ] ])\n                 end)\n                || (let offset := eval simpl in (4 * List.length ns) in\n                  change (locals ns vs avail p) with (locals_call ns vs avail p ns' avail' offset) in H;\n                  assert (ok_call ns ns' avail avail' offset)%nat\n                    by (split; [ simpl; omega\n                      | split; [ simpl; omega\n                        | split; [ repeat constructor; simpl; intuition congruence\n                          | reflexivity ] ] ]))\n            end\n          | [ _ : evalInstrs _ _ ?E = None, H : context[locals ?ns ?vs ?avail ?p] |- _ ] =>\n            let ns' := slotVariables E in\n            match ns' with\n              | nil => fail 1\n              | _ =>\n                let ns' := constr:(\"rp\" :: ns') in\n                  let offset := eval simpl in (4 * List.length ns) in\n                    change (locals ns vs avail p) with (locals_call ns vs avail p ns' 0 offset) in H;\n                      assert (ok_call ns ns' avail 0 offset)%nat\n                        by (split; [ simpl; omega\n                          | split; [ simpl; omega\n                            | split; [ repeat constructor; simpl; intuition congruence\n                              | reflexivity ] ] ])\n            end\n        end\n  (*TIME ) *).\n\nLtac sep' ext :=\n  post; evaluate ext; descend; repeat (step ext; descend).\n\nLtac sep ext :=\n  match goal with\n    | [ |- context[Assign (LvMem (Indir Sp (natToW 0))) (RvLval (LvReg Rp)) :: nil] ] =>\n      sep' auto_ext (* Easy case; don't bring the hints into it *)\n    | _ => sep' ext\n  end.\n\nLtac sepLemma := unfold Himp in *; simpl; intros; cancel auto_ext.\n\nLtac sepLemmaLhsOnly :=\n  let sllo Q := remember Q;\n    match goal with\n      | [ H : ?X = Q |- _ ] => let H' := fresh in\n        assert (H' : bool -> X = Q) by (intro; assumption);\n          clear H; rename H' into H;\n            sepLemma; rewrite (H true); clear H\n    end in\n    simpl; intros;\n      match goal with\n        | [ |- _ ===> ?Q ] => sllo Q\n        | [ |- himp _ _ ?Q ] => sllo Q\n      end.\n\nLtac sep_auto := sep' auto_ext.\n\nHint Rewrite sel_upd_eq sel_upd_ne using congruence : sepFormula.\n\nLemma sel_merge : forall vs vs' ns nm,\n  In nm ns\n  -> sel (merge vs vs' ns) nm = sel vs nm.\n  intros.\n  generalize (merge_agree vs vs' ns); intro Hl.\n  eapply Forall_forall in Hl; eauto.\nQed.\n\nHint Rewrite sel_merge using (simpl; tauto) : sepFormula.\n\nTheorem lift0 : forall P, lift nil P = P.\n  reflexivity.\nQed.\n\nHint Rewrite lift0 : sepFormula.\n\n(* Within [H], find a conjunct [P] such that [which P] doesn't fail, and reassocate [H]\n * to put [P] in front. *)\nLtac toFront which H :=\n  let rec toFront' P k :=\n    match P with\n      | SEP.ST.star ?Q ?R =>\n        toFront' Q ltac:(fun it P' => k it (SEP.ST.star P' R))\n        || toFront' R ltac:(fun it P' => k it (SEP.ST.star P' Q))\n          || fail 2\n      | _ => which P; k P (@SEP.ST.emp W (settings * state) nil)\n    end in\n    match type of H with\n      | interp ?specs (![ ?P ] ?st) => toFront' P ltac:(fun it P' =>\n        let H' := fresh in\n          assert (H' : interp specs (![ SEP.ST.star it P' ] st)) by step auto_ext;\n            clear H; rename H' into H)\n    end.\n\n(* Handle a VC for an indirect function call, given the callee's formal arguments list. *)\nLtac icall formals :=\n  match goal with\n    | [ H : context[locals ?ns ?vs ?avail ?p] |- exists pre', _ (Regs _ Rv) = Some pre' /\\ _ ] =>\n      let ns' := constr:(\"rp\" :: formals) in\n        let avail' := constr:(0) in\n          let offset := eval simpl in (4 * List.length ns) in\n            change (locals ns vs avail p) with (locals_call ns vs avail p ns' avail' offset) in H;\n              assert (ok_call ns ns' avail avail' offset)%nat\n                by (split; [ simpl; omega\n                  | split; [ simpl; omega\n                    | split; [ repeat constructor; simpl; intuition congruence\n                      | reflexivity ] ] ])\n  end.\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/Examples/PreAutoSep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.25617104100410054}}
{"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.\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": "snu-sf", "repo": "fairness", "sha": "170bd1ade88d32ac6ab661ed0c272af8a00d9ea1", "save_path": "github-repos/coq/snu-sf-fairness", "path": "github-repos/coq/snu-sf-fairness/fairness-170bd1ade88d32ac6ab661ed0c272af8a00d9ea1/src/example/WMM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.25613367224028083}}
{"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 Maps Integers Floats Lattice Kildall.\nRequire Import AST Linking.\nRequire Compopts Machregs.\nRequire Import Op Registers RTL.\nRequire Import Liveness ValueDomain ValueAOp ValueAnalysis.\nRequire Import ConstpropOp.\n\n(** The code transformation builds on the results of the static analysis\n  of values from module [ValueAnalysis].  It proceeds instruction by\n  instruction.\n- Operators whose arguments are all statically known are turned into\n  ``load integer constant'', ``load float constant'' or ``load\n  symbol address'' operations.  Likewise for loads whose result can\n  be statically predicted.\n- Operators for which some but not all arguments are known are subject\n  to strength reduction (replacement by cheaper operators) and\n  similarly for the addressing modes of load and store instructions.\n- Cast operators that have no effect (because their arguments are\n  already normalized to the destination type) are removed.\n- Conditional branches and multi-way branches are statically resolved\n  into [Inop] instructions when possible.\n- Other instructions are unchanged.\n\n  In addition, we try to jump over conditionals whose condition can\n  be statically resolved based on the abstract state \"after\" the\n  instruction that branches to the conditional.  A typical example is:\n<<\n          1: x := 0 and goto 2\n          2: if (x == 0) goto 3 else goto 4\n>>\n    where other instructions branch into 2 with different abstract values\n    for [x].  We transform this code into:\n<<\n          1: x := 0 and goto 3\n          2: if (x == 0) goto 3 else goto 4\n>>\n*)\n\nDefinition transf_ros (ae: AE.t) (ros: reg + ident) : reg + ident :=\n  match ros with\n  | inl r =>\n      match areg ae r with\n      | Ptr(Gl symb ofs) => if Ptrofs.eq ofs Ptrofs.zero then inr _ symb else ros\n      | _ => ros\n      end\n  | inr s => ros\n  end.\n\nFixpoint successor_rec (n: nat) (f: function) (ae: AE.t) (pc: node) : node :=\n  match n with\n  | O => pc\n  | S n' =>\n      match f.(fn_code)!pc with\n      | Some (Inop s) =>\n          successor_rec n' f ae s\n      | Some (Icond cond args s1 s2) =>\n          match resolve_branch (eval_static_condition cond (aregs ae args)) with\n          | Some b => successor_rec n' f ae (if b then s1 else s2)\n          | None => pc\n          end\n      | _ => pc\n      end\n  end.\n\nDefinition num_iter := 10%nat.\n\nDefinition successor (f: function) (ae: AE.t) (pc: node) : node :=\n  successor_rec num_iter f ae pc.\n\nFixpoint builtin_arg_reduction (ae: AE.t) (a: builtin_arg reg) :=\n  match a with\n  | BA r =>\n      match areg ae r with\n      | I n => BA_int n\n      | L n => BA_long n\n      | F n => if Compopts.generate_float_constants tt then BA_float n else a\n      | FS n => if Compopts.generate_float_constants tt then BA_single n else a\n      | _ => a\n      end\n  | BA_splitlong hi lo =>\n      match builtin_arg_reduction ae hi, builtin_arg_reduction ae lo with\n      | BA_int nhi, BA_int nlo => BA_long (Int64.ofwords nhi nlo)\n      | hi', lo' => BA_splitlong hi' lo'\n      end\n  | BA_addptr a1 a2 =>\n      BA_addptr (builtin_arg_reduction ae a1) (builtin_arg_reduction ae a2)\n  | _ => a\n  end.\n\nDefinition builtin_arg_strength_reduction\n      (ae: AE.t) (a: builtin_arg reg) (c: builtin_arg_constraint) :=\n  let a' := builtin_arg_reduction ae a in\n  if builtin_arg_ok a' c then a' else a.\n\nFixpoint builtin_args_strength_reduction\n      (ae: AE.t) (al: list (builtin_arg reg)) (cl: list builtin_arg_constraint) :=\n  match al with\n  | nil => nil\n  | a :: al =>\n      builtin_arg_strength_reduction ae a (List.hd OK_default cl)\n      :: builtin_args_strength_reduction ae al (List.tl cl)\n  end.\n\n(** For debug annotations, add constant values to the original info\n    instead of replacing it. *)\n\nFixpoint debug_strength_reduction (ae: AE.t) (al: list (builtin_arg reg)) :=\n  match al with\n  | nil => nil\n  | a :: al =>\n      let a' := builtin_arg_reduction ae a in\n      let al' := a :: debug_strength_reduction ae al in\n      match a, a' with\n      | BA _, (BA_int _ | BA_long _ | BA_float _ | BA_single _) => a' :: al'\n      | _, _ => al'\n      end\n  end.\n\nDefinition builtin_strength_reduction\n             (ae: AE.t) (ef: external_function) (al: list (builtin_arg reg)) :=\n  match ef with\n  | EF_debug _ _ _ => debug_strength_reduction ae al\n  | _ => builtin_args_strength_reduction ae al (Machregs.builtin_constraints ef)\n  end.\n\nDefinition transf_instr (f: function) (an: PMap.t VA.t) (rm: romem)\n                        (pc: node) (instr: instruction) :=\n  match an!!pc with\n  | VA.Bot =>\n      instr\n  | VA.State ae am =>\n      match instr with\n      | Iop op args res s =>\n          let aargs := aregs ae args in\n          let a := eval_static_operation op aargs in\n          let s' := successor f (AE.set res a ae) s 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 aargs in\n              Iop op' args' res s'\n          end\n      | Iload chunk addr args dst s =>\n          let aargs := aregs ae args in\n          let a := ValueDomain.loadv chunk rm am (eval_static_addressing addr aargs) 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 aargs in\n              Iload chunk addr' args' dst s\n          end\n      | Istore chunk addr args src s =>\n          let aargs := aregs ae args in\n          let (addr', args') := addr_strength_reduction addr args aargs in\n          Istore chunk addr' args' src s\n      | Icall sig ros args res s =>\n          Icall sig (transf_ros ae ros) args res s\n      | Itailcall sig ros args =>\n          Itailcall sig (transf_ros ae ros) args\n      | Ibuiltin ef args res s =>\n          Ibuiltin ef (builtin_strength_reduction ae ef args) res s\n      | Icond cond args s1 s2 =>\n          let aargs := aregs ae args in\n          match resolve_branch (eval_static_condition cond aargs) with\n          | Some b =>\n              if b then Inop s1 else Inop s2\n          | None =>\n              let (cond', args') := cond_strength_reduction cond args aargs in\n              Icond cond' args' s1 s2\n          end\n      | Ijumptable arg tbl =>\n          match areg ae 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  end.\n\nDefinition transf_function (rm: romem) (f: function) : function :=\n  let an := ValueAnalysis.analyze rm f in\n  mkfunction\n    f.(fn_sig)\n    f.(fn_params)\n    f.(fn_stacksize)\n    (PTree.map (transf_instr f an rm) f.(fn_code))\n    f.(fn_entrypoint).\n\nDefinition transf_fundef (rm: romem) (fd: fundef) : fundef :=\n  AST.transf_fundef (transf_function rm) fd.\n\nSection WITHROMEMFOR.\nContext `{romem_for_instance: ROMemFor}.\n\nDefinition transf_program (p: program) : program :=\n  let rm := romem_for p in\n  transform_program (transf_fundef rm) p.\n\nEnd WITHROMEMFOR.\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/Constprop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2560875908415096}}
{"text": "(** STG in COQ by Maciej Piróg, University of Wrocław, 2010 *)\n\n(** This library contains the definition of the argument-accumulating\nsemantics and proof of its equivalence with the STG natural semantics. *)\n\nRequire Export Heaps.\nRequire Export Sem01.\nRequire Import Arith.Max.\nRequire Import Arith.Gt.\nRequire Import Wf_nat.\n\n(** * Argument Accumulating Semantics *)\n\nReserved Notation \"($ a $ b $ e ↓↓ c $ d $ f )\"\n  (at level 70, no associativity).\n\nInductive AAS : heapA -> expr -> vars -> heapA -> expr -> vars -> Prop :=\n\n| A_Con : forall Gamma C pi,\n  ($ Gamma $ Constr C pi $ nil ↓↓ Gamma $ Constr C pi $ nil) \n\n| A_Accum : forall Gamma Delta p pm qn w rs,\n  pm <> nil ->\n  ($ Gamma $ App p nil $ pm ++ qn ↓↓ Delta $ w $ rs) ->\n  ($ Gamma $ App p pm  $ qn ↓↓ Delta $ w $ rs)\n\n| A_App1 : forall Gamma p pn m e,\n  Gamma p = Some (Lf_n m e) ->\n  m > length pn ->\n  ($ Gamma $ App p nil $ pn ↓↓ Gamma $ App p nil $ pn)\n\n| A_App2_5 : forall Gamma Delta m e p pn w rs,\n  Gamma p = Some (Lf_n m e) ->\n  m <= length pn ->\n  ($ Gamma $ e~[zip_var_list m (firstn m pn)] $ skipn m pn\n    ↓↓ Delta $ w $ rs) ->\n  ($ Gamma $ App p nil $ pn ↓↓ Delta $ w $ rs)\n\n| A_App4 : forall Gamma Delta e p C qs,\n  Gamma p = Some (Lf_u e) ->\n  ($ Gamma $ e $ nil ↓↓ Delta $ Constr C qs $ nil) ->\n  ($ Gamma $ App p nil $ nil\n    ↓↓ setA Delta p (Lf_n 0 (Constr C qs)) $ Constr C qs $ nil)\n\n| A_App5 : forall Gamma Delta Theta p pn q qk e f n w rs,\n  Gamma p = Some (Lf_u e) ->\n  Delta q = Some (Lf_n n f) ->\n  length qk < n ->\n  ($ Gamma $ e $ nil ↓↓ Delta $ App q nil $ qk) ->\n  ($ setA Delta p (Lf_n (n - length qk) (f~[zip_var_list n qk])) $\n    App q nil $ qk ++ pn ↓↓ Theta $ w $ rs) ->\n  ($Gamma $ App p nil $ pn ↓↓ Theta $ w $ rs)\n\n| A_Let : forall Gamma Delta lfs e w ats rs ss,\n  length ats = length lfs ->\n  are_atoms ats ->\n  (forall a : var, In a ats -> Gamma a = None) -> \n  ($ allocA Gamma ats\n      (map (subst_lf (zip_var_list (length lfs) ats)) lfs)\n    $ e~[zip_var_list (length lfs) ats] $ rs\n    ↓↓ Delta $ w $ ss) ->\n  ($ Gamma $ Letrec lfs e $ rs ↓↓ Delta $ w $ ss)\n\n| A_Case_of : forall Gamma Delta Theta b e e0 als w c c0 ps rs qs,\n  length ps = b ->\n  select_case als c = Some (Alt c0 b e0) ->\n  ($ Gamma $ e $ nil ↓↓ Delta $ Constr c ps $ nil) ->\n  ($ Delta $ e0~[zip_var_list b ps] $ qs ↓↓ Theta $ w $ rs) ->\n  ($ Gamma $ Case e als $ qs ↓↓ Theta $ w $ rs)\n\nwhere \"($ a $ b $ e ↓↓ c $ d $ f )\" := (AAS a b e c d f).\n\nHint Resolve A_Con A_Accum A_App1 A_App2_5 A_App4 A_App5 A_Let A_Case_of.\n\n(** * Completeness *)\n\nProposition app_accum_right :\nforall Gamma Delta p pm qn w rs,\n  ($ Gamma $ App p nil $ pm ++ qn ↓↓ Delta $ w $ rs) ->\n  ($ Gamma $ App p pm  $ qn ↓↓ Delta $ w $ rs).\nProof.\ninduction pm; isa.\nconstructor; intuition; try discriminate.\nQed.\n\nHint Resolve app_accum_right.\n\nProposition app_accum_left :\nforall Gamma Delta p pm qn w rs,\n  ($ Gamma $ App p pm  $ qn ↓↓ Delta $ w $ rs) ->\n  ($ Gamma $ App p nil $ pm ++ qn ↓↓ Delta $ w $ rs).\nProof.\nintros.\ninversion H; isa; subst; intuition.\nQed.\n\nHint Resolve app_accum_left.\n\nProposition app_accum :\nforall Gamma Delta p pm qn w rs,\n  ($ Gamma $ App p nil $ pm ++ qn ↓↓ Delta $ w $ rs) <->\n  ($ Gamma $ App p pm  $ qn ↓↓ Delta $ w $ rs).\nProof.\nintros; split; auto.\nQed.\n\nProposition AAS_complete :\nforall Xi Psi a b, ($ Xi $ a ↓ Psi $ b) ->\nforall Omega c Cs Ds, ($ Psi $ b $ Ds ↓↓ Omega $ c $ Cs) ->\n  ($ Xi $ a $ Ds ↓↓ Omega $ c $ Cs).\nProof with intuition; auto with arith; eauto.\nintros Xi Psi a b ast.\ninduction ast; intros Omega cc Cs Ds astast; isa; subst...\n(* Case App2 *)\napply IHast in astast.\nremember_destruct pn;\n[ rewrite <- X in *\n| rewrite -> X in *;\n    apply A_Accum; try intuition; try rewrite H1 in X; try discriminate ];\neapply A_App2_5...\nsimpl; rewrite app_length; omega.\nrewrite firstn_length_app.\nrewrite skipn_length_app...\n(* Case App3 *)\napply -> app_accum.\neapply A_App2_5...\nrewrite app_length...\nrewrite skipn_app...\nrewrite firstn_app...\napply IHast1.\napply -> app_accum.\nrewrite <- app_ass...\n(* Case App4 *)\ninversion astast; subst...\n(* Case App5 *)\napply app_accum_right.\neapply A_App5; eauto.\napply IHast1.\napply app_accum_right.\nrewrite <- app_nil_end.\neapply A_App1...\nrewrite <- app_ass...\nQed.\n\nLemma app_value_heap :\nforall Delta e Xi x xs b,\n  ($ Delta $ e ↓ Xi $ b) ->\n  b = App x xs ->\n  exists f, exists m, Xi x = Some (Lf Dont_update m f) /\\ m > length xs.\nProof with isa.\nintros.\ninduction H; try discriminate...\ninversion H0; subst.\nexists e.\nexists m...\nQed.\n\nProposition AAS_complete2 :\nforall Xi a,\n  (forall x xs, ($ emptyA $ a ↓ Xi $ App x xs) -> ($ emptyA $ a $ nil ↓↓ Xi $ App x nil $ xs))\n  /\\\n  (forall C xs, ($ emptyA $ a ↓ Xi $ Constr C xs) -> ($ emptyA $ a $ nil ↓↓ Xi $ Constr C xs $ nil)).\nProof with isa.\nintros.\nsplit.\n(* left *)\nintros.\napply AAS_complete with (Psi := Xi) (b := App x xs) (Omega := Xi)\n  (c := App x nil) (Cs := xs) (Ds := nil) in H...\napply app_value_heap with (x := x) (xs := xs) in H...\ndestruct H as [f [m []]].\ndestruct xs.\n  (* nil *)\neapply A_App1; eauto.\n  (* cons *)\napply A_Accum.\ndiscriminate.\nrewrite <- app_nil_end.\neapply A_App1; eauto.\n(* right *)\nintros.\napply AAS_complete with (Psi := Xi) (b := Constr C xs) (Omega := Xi)\n  (c := Constr C xs) (Cs := nil) (Ds := nil) in H...\nQed.\n\n\n(** * Soundness *)\n\nProposition AAS_value :\nforall Xi Omega Pn Rs b d,\n  ($ Xi $ b $ Pn ↓↓ Omega $ d $ Rs) ->\n  ((exists c, exists ps, d = Constr c ps /\\ Rs = nil))\n  \\/ (exists p, exists ps, d = App p ps).\nProof.\nintros.\ninduction H; eauto.\nQed.\n\nReserved Notation \"($ a $ b $ e ↓↓ c $ d $ f ^^ n )\"\n  (at level 70, no associativity).\n\nInductive AASN : heapA -> expr -> vars -> heapA -> expr -> vars ->\n  nat -> Prop :=\n\n| A_ConN : forall Gamma C pi,\n  ($ Gamma $ Constr C pi $ nil ↓↓ Gamma $ Constr C pi $ nil ^^ 0) \n\n| A_AccumN : forall Gamma Delta p pm qn w rs N,\n  pm <> nil ->\n  ($ Gamma $ App p nil $ pm ++ qn ↓↓ Delta $ w $ rs ^^ N) ->\n  ($ Gamma $ App p pm  $ qn ↓↓ Delta $ w $ rs ^^ S N)\n\n| A_App1N : forall Gamma p pn m e,\n  Gamma p = Some (Lf_n m e) ->\n  m > length pn ->\n  ($ Gamma $ App p nil $ pn ↓↓ Gamma $ App p nil $ pn ^^ 0)\n\n| A_App2_5N : forall Gamma Delta m e p pn w rs N,\n  Gamma p = Some (Lf_n m e) ->\n  m <= length pn ->\n  ($ Gamma $ e~[zip_var_list m (firstn m pn)] $ skipn m pn\n    ↓↓ Delta $ w $ rs ^^ N) ->\n  ($ Gamma $ App p nil $ pn ↓↓ Delta $ w $ rs ^^ S N)\n\n| A_App4N : forall Gamma Delta e p C qs N,\n  Gamma p = Some (Lf_u e) ->\n  ($ Gamma $ e $ nil ↓↓ Delta $ Constr C qs $ nil ^^ N) ->\n  ($ Gamma $ App p nil $ nil\n    ↓↓ setA Delta p (Lf_n 0 (Constr C qs)) $ Constr C qs $ nil ^^ S N)\n\n| A_App5N : forall Gamma Delta Theta p pn q qk e f n w rs M N,\n  Gamma p = Some (Lf_u e) ->\n  Delta q = Some (Lf_n n f) ->\n  length qk < n ->\n  ($ Gamma $ e $ nil ↓↓ Delta $ App q nil $ qk ^^ N) ->\n  ($ setA Delta p (Lf_n (n - length qk) (f~[zip_var_list n qk])) $\n    App q nil $ qk ++ pn ↓↓ Theta $ w $ rs ^^ M) ->\n  ($ Gamma $ App p nil $ pn ↓↓ Theta $ w $ rs ^^ S (max M N))\n\n| A_LetN : forall Gamma Delta lfs e w ats rs ss N,\n  length ats = length lfs ->\n  are_atoms ats ->\n  (forall a : var, In a ats -> Gamma a = None) -> \n  ($ allocA Gamma ats\n      (map (subst_lf (zip_var_list (length lfs) ats)) lfs)\n    $ e~[zip_var_list (length lfs) ats] $ rs\n    ↓↓ Delta $ w $ ss ^^ N) ->\n  ($ Gamma $ Letrec lfs e $ rs ↓↓ Delta $ w $ ss ^^ S N)\n\n| A_Case_ofN : forall Gamma Delta Theta b e e0 als w c c0 ps rs qs N M,\n  length ps = b ->\n  select_case als c = Some (Alt c0 b e0) ->\n  ($ Gamma $ e $ nil ↓↓ Delta $ Constr c ps $ nil ^^ N) ->\n  ($ Delta $ e0~[zip_var_list b ps] $ qs ↓↓ Theta $ w $ rs ^^ M) ->\n  ($ Gamma $ Case e als $ qs ↓↓ Theta $ w $ rs ^^ S (max M N))\n\nwhere \"($ a $ b $ e ↓↓ c $ d $ f ^^ n )\" := (AASN a b e c d f n ).\n\nLtac caseA x := case x; isa.\n\nLemma aasn_complete :\nforall Gamma e ps Delta w qs,\n  ($ Gamma $ e $ ps ↓↓ Delta $ w $ qs) ->\n  exists N, ($ Gamma $ e $ ps ↓↓ Delta $ w $ qs ^^ N).\nProof with eauto.\nintros.\ninduction H.\nexists 0; constructor.\ncaseA IHAAS; exists (S x); constructor...\nexists 0; econstructor...\ncaseA IHAAS; exists (S x); eapply A_App2_5N...\ncaseA IHAAS; exists (S x); eapply A_App4N...\ncaseA IHAAS1; caseA IHAAS2; exists (S (max x0 x)); eapply A_App5N...\ncaseA IHAAS; exists (S x); eapply A_LetN...\ncaseA IHAAS1; caseA IHAAS2; exists (S (max x0 x)); eapply A_Case_ofN...\nQed.\n\nLemma aasn_sound :\nforall Gamma e ps Delta w qs N,\n  ($ Gamma $ e $ ps ↓↓ Delta $ w $ qs ^^ N) ->\n  ($ Gamma $ e $ ps ↓↓ Delta $ w $ qs).\nProof.\nintros.\ninduction H; eauto.\nQed.\n\nProposition AAS_split :\nforall N (Xi Psi Omega : heapA) (b c d : expr) (Rs Pt Ptn Qs : vars),\n  ($ Xi $ b $ Pt ++ Ptn ↓↓ Omega $ d $ Rs ^^ N) ->\n  exists Psi, exists c, exists Qs, exists N0, exists N1,\n  ($ Xi $ b $ Pt ↓↓ Psi $ c $ Qs ^^ N0) /\\\n  ($ Psi $ c $ Qs ++ Ptn ↓↓ Omega $ d $ Rs ^^ N1) /\\\n  N0 <= N /\\ N1 <= N.\nProof with try split; try omega; simpl; auto.\nintro N.\ninduction N using lt_wf_ind; isa.\ndestruct N;\n  inversion H0; subst;\n  try (rewrite <- plus_n_Sm in *; discriminate).\n(* Case *)\nrewrite <- H4 in *.\nexists Omega.\nexists (Constr C pi).\nexists nil.\nexists 0.\nexists 0.\nsymmetry in H4.\napply app_eq_nil in H4.\ninversion_clear H4...\nrewrite H1...\nsplit...\nrewrite H2...\n(* Case *)\nexists Omega.\nexists (App p nil).\nexists Pt.\nexists 0.\nexists 0...\neapply A_App1N; eauto.\nrewrite app_length in H2...\n(* Case *)\ndupl_apply Xi H; auto.\ndestruct H1 as [x [x0 [x1 [x2 [x3 [H H1]]]]]].\ndestruct H1 as [H1 []].\nexists x.\nexists x0.\nexists x1.\nexists (S x2).\nexists x3.\nsplit.\napply A_AccumN...\napply H.\nsplit...\napply H1...\nrewrite app_ass...\n(* Case *)\ncaseA (le_lt_dec m (length Pt)).\n  (* m <= length Pt *)\nrewrite firstn_app in *...\nrewrite skipn_app in *...\ndupl_apply H10 H...\ndestruct H1 as [x [x0 [x1 [x2 [x3 [H H1]]]]]].\ndestruct H1 as [H1 []].\napply A_App2_5N with (p := p) in H...\nexists x.\nexists x0.\nexists x1.\nexists (S x2).\nexists x3.\nsplit...\n  (* length Pt < m *)\nexists Xi.\nexists (App p nil).\nexists Pt.\nexists 0.\nexists (S N).\nsplit.\neapply A_App1N; eauto.\nsplit; intuition.\n(* Case *)\nsymmetry in H1.\napply app_eq_nil in H1.\ninversion_clear H1.\nsubst.\nsimpl in H0.\nexists (setA Delta p (Lf_n 0 (Constr C qs))).\nexists (Constr C qs).\nexists nil.\nexists (S N).\nexists 0.\nsplit...\nsimpl.\napply A_ConN.\nintuition.\n(* Case *)\nrewrite <- app_ass in H12.\ndupl_apply H12 H...\ndestruct H1 as [x [x0 [x1 [x2 [x3 [H H1]]]]]].\ndestruct H1 as [H1 []].\nexists x.\nexists x0.\nexists x1.\nexists (S (max x2 N0)).\nexists x3.\nsplit.\neapply A_App5N.\napply H2.\napply H3.\napply H4.\napply H5.\napply H.\nsplit.\napply H1.\nsplit.\napply le_n_S.\ndestruct (max_dec x2 N0); apply max_c_inv_to_le; auto.\n  eapply le_trans.\n  apply H7.\n  eapply le_trans.\n  eapply le_max_l.\n  apply le_n_Sn.\n    eapply le_lt_trans.\n    apply le_max_l.\n    apply lt_n_Sn.\n(* Case Let *)\ndupl_apply H11 H...\ndestruct H1 as [x [x0 [x1 [x2 [x3 [H H1]]]]]].\ndestruct H1 as [H1 []].\nexists x.\nexists x0.\nexists x1.\nexists (S x2).\nexists x3.\nsplit.\neapply A_LetN.\neauto.\nauto.\neauto.\neauto.\nsplit...\n(* Case Case *)\ndupl_apply H11 H...\ndestruct H1 as [x [x0 [x1 [x2 [x3 [H H1]]]]]].\ndestruct H1 as [H1 []].\nexists x.\nexists x0.\nexists x1.\nexists (S (max x2 N0)).\nexists x3.\nsplit.\neapply A_Case_ofN.\ninstantiate (2 := ps); eauto.\ninstantiate (1 := e0).\ninstantiate (1 := c1).\ninstantiate (1 := c0).\nrewrite <- plus_n_O...\napply H4.\nrewrite <- plus_n_O...\nsplit.\napply H1.\nsplit.\napply le_n_S.\napply max_c_inv_to_le; isa.\napply le_trans with (m := M)...\nrewrite max_SS.\napply le_trans with (m := S M)...\nauto with arith.\nauto with arith.\nQed.\n\nFixpoint join_expr (Ds : list atom) (e : expr) {struct e} :\n  expr :=\nmatch e with\n| App v vs => App v (vs ++ map Atom Ds)\n| Constr c vs => Constr c vs\n| Letrec dfs f => Letrec dfs (join_expr Ds f)\n| Case e als => Case e (map (join_alt Ds) als)\nend\nwith join_alt (Ds : list atom) (a : alt)\n  {struct a} : alt :=\nmatch a with\n| Alt c b f => Alt c b (join_expr Ds f)\nend.\n\nNotation \" e >< d \" := (join_expr d e) (at level 70).\nNotation \" e ><' d \" := (join_alt d e) (at level 70).\n\nProposition join_nil :\nforall (e : expr), e >< nil = e.\nProof with isa.\ninduction e using expr_ind2 with\n  (P1 := fun (lf : lambda_form) => True)\n  (P2 := fun (al : alt) => al ><' nil = al)...\nrewrite <- app_nil_end...\nrewrite IHe...\nf_equal; induction als; isa; f_equal...\nrewrite IHe...\nQed.\n\nLemma closed_AAS_atoms :\nforall N Xi Omega e f ps ds,\n  (forall s lf, Xi s = Some lf -> closed_lf 0 lf) ->\n  closed_expr 0 e ->\n  ($ Xi $ e $ ps ↓↓ Omega $ f $ ds ^^ N) -> are_atoms ps ->\n  are_atoms ds /\\ closed_expr 0 f /\\\n  (forall s lf, Omega s = Some lf -> closed_lf 0 lf).\nProof with isa; eauto.\nintro NN.\nintros Xi Omega e f ps ds H J X A.\ninduction X...\n(* Case *)\ndupl J.\napply atoms_closed_app in J.\ninversion_clear J...\n(* Case *)\napply IHX...\neapply open_inv_to_closed.\n  apply atoms_firstn...\n  rewrite firstn_length.\n  auto with arith.\napply H with (s := p).\napply H0.\n  unfold are_atoms in *.\n  intros.\n  intuition.\n  apply A.\n  eapply In_skipn.\n  apply H2.\n(* Case *)\nassert (closed_lf 0 (Lf_u e))...\ninversion H1; subst...\necase IHX...\ndestruct H4.\nsplit...\nsplit...\nunfold setA in *.\ndestruct eq_var_dec...\ninversion H6.\nconstructor...\n(* Case *)\nassert (closed_expr 0 e).\n  apply H in H0; inversion H0; subst...\ncase IHX1...\nunfold are_atoms; isa; contradiction.\ndestruct H5.\napply IHX2...\nunfold setA in *.\ndestruct eq_var_dec...\ninversion H7.\nconstructor...\neapply open_inv_to_closed0.\napply H4.\nintuition.\ncase H6 with (s := q) (lf := Lf_n n f)...\n(* Case *)\ninversion J; subst...\ncase IHX...\ndestruct (In_dec eq_var_dec s ats).\n  (* in *)\napply allocA_in in H3; auto.\napply in_map_iff in H3.\ndestruct H3.\nrename x into lf0.\ndestruct H3.\nassert (closed_lf (length lfs) lf0).\n  apply H5; auto.\nsubst.\ndestruct lf0.\ninversion_clear H7.\nconstructor; simpl.\nfold map_expr.\nrewrite <- H0 in *.\neapply open_inv_to_closed2...\nrewrite map_length...\n  (* not in *)\nrewrite allocA_nin in H3; auto.\neapply H; auto.\napply H3.\napply open_inv_to_closed1...\n(* Case *)\ninversion J; subst.\nassert (closed_expr 0 e).\n  apply H4.\ncase IHX1...\nunfold are_atoms; isa; contradiction.\ndestruct H3.\napply IHX2...\neapply open_inv_to_closed...\napply atoms_closed_constr in H3...\ninstantiate (1 := Update).\nconstructor...\nassert (XX : closed_by_alt nil 0 (Alt c0 (length ps) e0))...\n  apply H5.\n  eapply In_select_case.\n  apply H1.\ninversion XX; subst...\nQed.\n\nLemma join_open :\nforall Ds xs e, (e >< Ds)~[xs] = (e~[xs] >< Ds).\nProof with isa; intuition.\nintros Ds xs.\nassert (forall e n,\n   map_expr (subst_var xs) n (e >< Ds) =\n  (map_expr (subst_var xs) n  e >< Ds)).\n  intro e.\n  induction e using expr_ind2 with\n  (P1 := fun (lf : lambda_form) => True)\n  (P2 := fun (al : alt) => forall n,\n     map_alt (subst_var xs) n (al ><' Ds) =\n    (map_alt (subst_var xs) n  al ><' Ds))...\n  (* Case App *)\n  f_equal.\n  induction vs...\n  induction Ds...\n  f_equal...\n  f_equal...\n  (* Case Letrec *)\n  f_equal...\n  (* Case Case *)\n  f_equal.\n  induction als...\n  f_equal...\n  (* Case Alt *)\n  f_equal...\nintro.\napply H with (n := 0).\nQed.\n\nLemma AAS_value_lemma :\nforall Xi Omega b c ps qs N,\n  ($ Xi $ b $ ps ↓↓ Omega $ c $ qs ^^ N) -> is_value c.\nProof with isa.\nintros.\ninduction H...\nQed.\n\nProposition AAS_sound :\nforall (N : nat) Xi Omega b c Ds Cs,\n  (forall s lf, Xi s = Some lf -> closed_lf 0 lf) ->\n  closed_expr 0 b ->\n  ($ Xi $ b $ map Atom Ds ↓↓ Omega $ c $ map Atom Cs ^^ N) ->\n  ($ Xi $ b >< Ds ↓ Omega $ c >< Cs).\nProof with intros; auto with arith.\nintro N.\ninduction N using lt_wf_ind; isa.\ndestruct N;\n  inversion H2; subst;\n  try (rewrite <- plus_n_Sm in *; discriminate).\n(* Case *)\nisa.\n(* Case *)\ninversion H2; subst.\napply atoms_map_injection in H6.\nsubst.\neapply App1; simpl.\napply H8.\napply H12.\n(* Case *)\ndupl H11.\napply closed_AAS_atoms in H3...\ndestruct H3.\ndestruct H5.\ndupl H1.\napply closed_0_args in H1.\napply atoms_exists in H1.\ndestruct H1.\nrewrite H1 in *.\nsimpl.\nrewrite <- map_app in *.\napply H in H11...\napply H0 with (s := s)...\neapply closed_rem_args; apply H7.\napply H0 with (s := s)...\neapply closed_rem_args; apply H1.\napply closed_0_args in H1.\napply atoms_app...\nunfold are_atoms...\napply in_map_iff in H5.\ndestruct H5.\ndestruct H5.\nunfold is_atom.\ndestruct a...\ndiscriminate.\n(* Case *)\ncaseA (le_lt_dec (length Ds) m).\n  (* subcase eq *) \neapply App2.\napply H4.\nrewrite map_length in *.\napply le_antisym...\nassert (QQ : forall xs, e~[xs] = (e~[xs] >< nil)).\n  intro.\n  symmetry.\n  apply join_nil.\nrewrite QQ.\neapply H.\nFocus 4.\nrewrite firstn_length_eq_id in H12.\nrewrite skipn_length_eq_nil in H12.\nsimpl.\napply H12.\nrewrite map_length in *.\napply le_antisym...\nrewrite map_length in *.\napply le_antisym...\nomega.\nauto.\neapply open_inv_to_closed.\napply atoms_map_atom.\nrewrite map_length in *.\napply le_antisym...\ninstantiate (1 := Dont_update).\napply H0 with (s := p)...\n  (* subcase lt *)\nassert (m < length Ds)...\nreplace (skipn m (map Atom Ds)) with (nil ++ skipn m (map Atom Ds))\n  in H12...\napply AAS_split in H12; (try exact nil)...\ndestruct H12.\ndestruct H6.\ndestruct H6.\ndestruct H6.\ndestruct H6.\ndestruct H6.\ndestruct H7.\ndestruct H8.\ndupl H6.\napply closed_AAS_atoms in H10; auto.\nFocus 2.\neapply open_inv_to_closed.\n  rewrite firstn_map.\n  apply atoms_map_atom. \n  erewrite <- map_length in l.\n  apply firstn_lt_length.\n  apply l.\ninstantiate (1 := Dont_update).\napply H0 with (s := p)...\ndestruct H10.\ndestruct H11.\napply atoms_exists in H10.\ndestruct H10.\nrewrite H10 in H6.\nreplace (nil (A := var)) with (map Atom nil) in H6...\ndupl H6.\napply H in H6...\nrewrite skipn_map in H7.\nrewrite H10 in H7.\nrewrite <- map_app in H7.\ndupl H7.\nrename H14 into HHH.\napply H in H7...\nassert (is_value x0).\n  eapply AAS_value_lemma; eauto.\ninversion H14.\n  subst.\nsimpl in *.\neapply App3.\napply H4.\nrewrite map_length...\nrewrite join_nil in H6; apply H6.\nrewrite app_ass; rewrite skipn_map; rewrite <- map_app; auto.\n  subst.\ninversion HHH; subst.\napply skipn_lt_length_nil in H3.\nrewrite map_app in H18.\nassert (XX : map Atom x4 = nil).\n  symmetry in H18.\n  apply app_eq_nil in H18.\n  destruct H18.\n  auto.\nrewrite XX in H18.\nsimpl in H18.\nassert (nil = skipn m Ds).\n  induction (skipn m Ds).\nintuition.\nsimpl in *; discriminate.\nintuition.\napply H12 with (s := s)...\napply H0 with (s := s)...\neapply open_inv_to_closed.\nrewrite firstn_map.\napply atoms_map_atom.\nrewrite firstn_lt_length...\nrewrite map_length...\ninstantiate (1 := Dont_update).\napply H0 with (s := p)...\nunfold are_atoms.\nintuition.\ninversion H11.\n(* Case *)\nsimpl.\nrewrite <- H3.\neapply App4.\napply H10.\nrewrite <- join_nil.\nrewrite <- join_nil with (e := e).\neapply H.\ninstantiate (1 := N).\nomega.\napply H0.\nrewrite <- empty_subst.\nassert (QQ : forall m, zip_var_list m nil = nil).\n  intros.\n  simpl...\nrewrite <- QQ with (m := 0).\neapply open_inv_to_closed...\napply atoms_nil.\ninstantiate (1 := Update).\napply H0 with (s := p)...\nauto.\n(* Case *)\ndupl H7.\napply closed_AAS_atoms in H3.\ndestruct H3.\napply atoms_exists in H3.\ndestruct H3.\nrewrite H3 in *.\nrewrite <- map_app in H14.\napply H in H14.\nassert (nil = map Atom nil).\n  isa.\nrewrite H9 in H7.\napply H in H7.\neapply App5.\napply H4.\napply H5.\napply H6.\n  rewrite join_nil in H7.\n  simpl in *.\napply H7.\n  simpl.\n  rewrite <- map_app.\napply H14.\nauto with arith.\nauto.\nrewrite <- empty_subst.\nassert (QQ : forall m, zip_var_list m nil = nil).\n  intros.\n  simpl...\nrewrite <- QQ with (m := 0).\neapply open_inv_to_closed...\napply atoms_nil.\neapply H0.\napply H4.\nauto with arith.\ndestruct H8.\nisa.\ndestruct (eq_var_dec p s).\nsubst.\nrewrite setA_eq in H10.\ninversion H10.\nconstructor.\nsimpl.\neapply open_inv_to_closed0.\napply atoms_map_atom.\nintuition.\ninstantiate (1 := Dont_update).\neapply H9.\napply H5.\nrewrite setA_neq in H10.\neapply H9; apply H10.\nauto.\ntauto.\ntrivial.\nrewrite <- empty_subst.\nassert (QQ : forall m, zip_var_list m nil = nil).\n  intros.\n  simpl...\nrewrite <- QQ with (m := 0).\neapply open_inv_to_closed...\napply atoms_nil.\neapply H0.\napply H4.\nunfold are_atoms...\ncontradiction.\n(* Case *)\neapply Let.\napply H4.\napply H5.\napply H6.\nfold join_expr.\nrewrite join_open.\neapply H.\ninstantiate (1 := N).\nomega.\nisa.\ndestruct (In_dec eq_var_dec s ats).\n  (* subcase in *)\napply allocA_in in H3; auto.\napply in_map_iff in H3.\ndestruct H3.\nrename x into lf0.\ndestruct H3.\nassert (closed_lf (length lfs) lf0).\n  inversion H1.\n  subst.\n  simpl in *.\n  apply H10; auto.\nsubst.\ndestruct lf0.\ninversion_clear H8.\nconstructor.\nsimpl.\nfold map_expr.\nrewrite <- H4 in *.\neapply open_inv_to_closed2...\nrewrite map_length.\nauto.\n  (* subcase not in *)\nrewrite allocA_nin in H3.\neapply H0.\napply H3.\napply n.\ninversion H1; subst; isa.\napply open_inv_to_closed1; isa.\napply H13.\n(* Case *)\ndupl H6.\nrename H3 into AAA.\napply closed_AAS_atoms in AAA...\nassert (nil = map Atom nil).\n  isa.\nrewrite H3 in H6.\napply H in H6.\napply H in H13.\nsimpl in *.\neapply Case_of.\nFocus 3.\nrewrite join_nil in H6.\napply H6.\nFocus 3.\ninstantiate (1 := e0 >< Ds).\ninstantiate (1 := length ps).\ninversion H1; subst.\nclear H3.\nassert (In (Alt c1 (length ps) e0) als).\n  eapply In_select_case.\n  apply H5.\nassert (closed_alt 0 (Alt c1 (length ps) e0)).\n  apply H9...\ninversion H4; subst; simpl in *.\nassert (QWE : forall e Ds ps, closed_expr (length ps) e ->\n  (e >< Ds)~[zip_var_list (length ps) ps] = \n  ((e~[zip_var_list (length ps) ps]) >< Ds)).\n  intros.\n  apply join_open.\nrewrite QWE...\nauto.\ninstantiate (1 := c1).\nclear H6 H1 H2 H13 AAA.\ninduction als.\nsimpl in *.\ndiscriminate H5.\ndestruct a.\ndestruct (eq_nat_dec c0 c2).\nsubst.\nsimpl in H5 |- *.\ndestruct eq_nat_dec.\nf_equal.\ninversion H5.\nsubst.\nf_equal.\ndestruct n...\nsimpl in H5 |- *.\ndestruct (eq_nat_dec c0 c2) in H5 |- *.\nsubst.\ndestruct n...\napply IHals.\napply H5.\nauto with arith.\ntauto.\nintuition.\ninversion H1; subst.\nassert (In (Alt c1 (length ps) e0) als).\n  eapply In_select_case.\n  apply H5.\nassert (BBB : closed_alt 0 (Alt c1 (length ps) e0)).\n  apply H12.\n  auto.\ninversion BBB; subst.\nsimpl in *.\napply open_inv_to_closed1...\napply atoms_closed_constr in H8...\nauto with arith.\ntrivial.\ninversion H1...\napply H0 with (s := s)...\ninversion H1...\nunfold are_atoms.\nintuition.\ninversion H3.\nQed.\n\nProposition AAS_sound2 :\nforall b c Omega Cs,\n  closed_expr 0 b ->\n  ($ emptyA $ b $ nil ↓↓ Omega $ c $ map Atom Cs) ->\n  ($ emptyA $ b ↓ Omega $ c >< Cs).\nProof with isa.\nintros.\nassert (BNIL : (b >< nil) = b).\n  apply join_nil.\nrewrite <- BNIL.\ndupl H0.\napply aasn_complete in H0.\ndestruct H0.\napply AAS_sound with (N := x)...\nunfold emptyA in H1; discriminate.\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/Sem02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2560875842757364}}
{"text": "Require Import erasure.  \nRequire Import NonSpecPureStep. \nRequire Import eraseRollbackIdempotent. \nRequire Import IndependenceCommon.\nRequire Import SpecImpliesNonSpec.\nRequire Import progStepWF. \n\n(*H; T ->+ H'; T'*)\nInductive pstepPlus : pHeap -> pPool -> pHeap -> pPool -> Prop :=\n|stepPlus' : forall H H' H'' T T'' t t',\n              pstep H T t (pOK H' T t') ->\n              pmultistep H' (pUnion T t') (Some(H'', T'')) ->\n              pstepPlus H (pUnion T t) H'' T''. \n\nTheorem AddUnion : forall A T t, Add A T t = Union A T (Single A t). \nreflexivity. \nQed. \n\nTheorem raw_lookupEraseCommitEmpty : forall x H,\n                                   raw_heap_lookup x H = Some(sempty COMMIT) ->\n                                   raw_heap_lookup x (raw_eraseHeap H) = Some pempty. \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   {destruct i0. destruct s; eauto. simpl. rewrite eq. auto. \n    destruct s; auto. destruct s0; simpl; rewrite eq; auto. }\n  }\nQed. \n\nTheorem lookupEraseCommitEmpty : forall x H,\n                                   heap_lookup x H = Some(sempty COMMIT) ->\n                                   heap_lookup x (eraseHeap H) = Some pempty. \nProof.\n  intros. destruct H. simpl. eapply raw_lookupEraseCommitEmpty; eauto. \nQed. \n \nTheorem raw_eraseCommitWrite : forall x H ds TID N, \n                             raw_heap_lookup x H = Some (sempty COMMIT) ->\n                             raw_eraseHeap (raw_replace x (sfull COMMIT ds COMMIT TID N) H) = \n                             raw_replace x (pfull (eraseTerm N)) (raw_eraseHeap H). \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   {simpl. erewrite IHlist; eauto. destruct i0. destruct s; auto. \n    simpl. rewrite eq. auto. destruct s; auto. destruct s0; simpl; rewrite eq. \n    auto. auto. }\n  }\nQed.\n\nTheorem eraseCommitWrite : forall x H ds TID N, \n                             heap_lookup x H = Some (sempty COMMIT) ->\n                             eraseHeap (replace x (sfull COMMIT ds COMMIT TID N) H) = \n                             replace x (pfull (eraseTerm N)) (eraseHeap H). \nProof.\n  intros. destruct H. simpl. apply rawHeapsEq. eapply raw_eraseCommitWrite; eauto.\nQed.\n\nTheorem unspecEmpty : forall tid s2 M s1, \n                        unspecPool(tSingleton(tid,locked s1, s2, M)) = \n                        Empty_set thread. auto. Qed. \n\nTheorem raw_lookupEraseNoneNone : forall x H, \n                                raw_heap_lookup x H = None ->\n                                raw_heap_lookup x (raw_eraseHeap H) = None. \nProof.\n  induction H; intros. \n  {auto. }\n  {simpl in *. destruct a. destruct (beq_nat x i) eqn:eq. \n   {inv H0. }\n   {destruct i0. destruct s; auto. simpl. rewrite eq; auto. \n    destruct s; auto. destruct s0; simpl; rewrite eq; auto. }\n  }\nQed. \n\nTheorem lookupEraseNoneNone : forall x H, \n                                heap_lookup x H = None ->\n                                heap_lookup x (eraseHeap H) = None. \nProof.\n  intros. destruct H. simpl. eapply raw_lookupEraseNoneNone; eauto. \nQed. \n\nTheorem prog_specImpliesNonSpec : forall H H' T t t', \n                               prog_step H T t (OK H' T t') -> wellFormed H (tUnion T t) ->\n                               exists PH' T', pstepPlus (eraseHeap H) (erasePool (tUnion T t)) PH' T' /\\\n                                               eraseHeap H' = PH' /\\ erasePool (tUnion T t') = T'. \nProof.\n  intros. inv H0. \n  {exists (eraseHeap H'). econstructor. split; auto. repeat rewrite eraseUnionComm. \n   simpl. apply simBasicStep in H6. econstructor. eapply PBasicStep. eauto. \n   constructor. }\n  {apply rollbackIdempotent in H7. invertHyp. copy d.\n   erewrite <- decomposeErase in H3; eauto. econstructor. econstructor. split. \n   unfoldTac. rewrite AddUnion. rewrite Union_associative. rewrite eraseUnionComm.\n   econstructor. eapply PPut. simpl in *. copy H3. apply pdecomposeEq in H3. \n   rewrite H3 in H7. rewrite eraseFill; eauto. eapply lookupEraseSpecFull; eauto. \n   auto. constructor. split. rewrite H2. eapply eraseCommitWrite; eauto. \n   unfoldTac. rewrite AddUnion. rewrite Union_associative. rewrite eraseUnionComm. \n   simpl. rewrite eraseFill; eauto. repeat rewrite eraseUnionComm. rewrite H0. \n   auto. }\n  {inv H1. unfoldTac. rewrite coupleUnion in H0. \n   repeat rewrite unspecUnionComm in H0. econstructor. econstructor. split; auto. \n   rewrite coupleUnion. repeat rewrite eraseUnionComm. rewrite eraseEmptySpec. \n   unfold pUnion. rewrite union_empty_r. repeat rewrite Union_associative in H0. \n   econstructor. eapply pSpecRun. copy p. erewrite <- decomposeErase in H; eauto. \n   simpl. auto. copy p. apply decomposeWF in H. rewrite eraseCtxtWF in H. \n   simpl in H. copy p. rewrite <- decomposeErase in H1; eauto. simpl in H1. \n   destructLast s1. \n   {simpl. rewrite eraseFill. unfoldTac. rewrite UnionSwap in H0.\n    rewrite Union_associative in H0. rewrite UnionSwap in H0.\n    rewrite spec_multi_unused in H0. eapply simSpecJoinSteps; eauto. simpl in *.\n    eassumption. }\n   {unfoldTac. rewrite UnionSwap in H0. rewrite Union_associative in H0. \n    rewrite UnionSwap in H0. rewrite spec_multi_unused in H0. invertHyp. \n    rewrite wrapDistributeApp. destruct x.\n    {simpl (wrapActs [rAct x t E0 d] N1 E (specRun (ret N1) N0)(decomposeWF t0 E (specRun (ret N1) N0) p)).\n     erewrite eraseLastAct; eauto. eauto. rewrite eraseFill. \n     eapply simSpecJoinSteps';[idtac|eauto|simpl in *; eauto]. constructor. }\n    {simpl (wrapActs [wAct x t E0 M0 d] N1 E (specRun (ret N1) N0)(decomposeWF t0 E (specRun (ret N1) N0) p)).\n     erewrite eraseLastAct; eauto. rewrite eraseFill. \n     eapply simSpecJoinSteps';[idtac|eauto|simpl in *; eauto]. constructor. }\n    {simpl (wrapActs [nAct t E0 d i] N1 E (specRun (ret N1) N0)(decomposeWF t0 E (specRun (ret N1) N0) p)).\n     erewrite eraseLastAct; eauto. rewrite eraseFill. \n     eapply simSpecJoinSteps'; [idtac|eauto|simpl in *; eauto]. constructor. }\n    {simpl (wrapActs [fAct t E0 M0 d n] N1 E (specRun (ret N1) N0)(decomposeWF t0 E (specRun (ret N1) N0) p)).\n     erewrite eraseLastAct; eauto. rewrite eraseFill. \n     eapply simSpecJoinSteps';[idtac|eauto|simpl in *; eauto]. constructor. }\n    {simpl (wrapActs [srAct t E0 M0 N d] N1 E (specRun (ret N1) N0)(decomposeWF t0 E (specRun (ret N1) N0) p)).\n     erewrite eraseLastAct; eauto. rewrite eraseFill. \n     eapply simSpecJoinSteps'; [idtac|eauto|simpl in *; eauto]. constructor. }\n   }\n  }\n  {apply rollbackIdempotent in H10. invertHyp.\n   erewrite <- decomposeErase in H4; eauto. econstructor. econstructor. split. \n   unfoldTac. rewrite Union_associative. rewrite coupleUnion. \n   repeat rewrite eraseUnionComm. simpl. econstructor. eapply pSpecRunRaise. \n   simpl in *; eauto. constructor. split. auto. unfoldTac. rewrite AddUnion. \n   rewrite Union_associative. repeat rewrite eraseUnionComm. simpl. \n   repeat rewrite AddUnion in H0. rewrite Union_commutative in H0. simpl in H0. \n   rewrite Union_commutative in H0. simpl in H0. rewrite H0.\n   rewrite eraseFill; eauto. }\n  {exists (eraseHeap H). econstructor. split. Focus 2. split; auto. \n   erewrite eraseHeapDependentRead. auto. eauto. inv H1. eraseTrmTac s1' M. \n   rewrite eraseUnionComm. erewrite eraseLastAct; eauto. econstructor. \n   eapply PGet; eauto. eapply lookupEraseCommitFull; eauto. copy d. \n   erewrite <- decomposeErase in H0; eauto. rewrite unspecUnionComm in H2. \n   erewrite unspecLastActPool in H2. Focus 2. constructor. \n   eapply specStepRead in H2; eauto. invertHyp. eapply simPureSteps in H0; eauto.\n   rewrite eraseFill in H0. simpl in H0. rewrite eraseUnionComm. \n   erewrite eraseEraseTrm; eauto. eapply unspecHeapLookupFull; eauto. }\n  {exists (replace x (pfull (eraseTerm M'')) (eraseHeap H)). econstructor. split. \n   Focus 2. split; eauto. erewrite eraseHeapCommitWrite; eauto. inv H1. \n   repeat rewrite eraseUnionComm. erewrite eraseLastAct. Focus 2. constructor. \n   rewrite unspecUnionComm in H2. erewrite unspecLastActPool in H2. Focus 2. \n   constructor. eraseTrmTac s1' M. erewrite eraseEraseTrm; eauto.\n   eapply specStepWrite in H2; eauto. invertHyp. eapply simPureSteps in H0; eauto. \n   rewrite eraseFill in H0. simpl in H0. econstructor. eapply PPut; eauto. copy d. \n   erewrite <- decomposeErase in H2; eauto. simpl. auto. \n   eapply lookupEraseSpecFull; eauto. eassumption.\n   eapply lookupUnspecSpecFullEmpty; eauto. }\n  {inv H1. assert(heap_lookup i (eraseHeap H) = None). \n   eapply lookupEraseSpecNone; eauto. exists (Heap.extend i pempty (eraseHeap H) H0). \n   econstructor. split. Focus 2. split; eauto. eapply eraseHeapCommitNewFull; eauto. \n   repeat rewrite eraseUnionComm. erewrite eraseLastAct. Focus 2. constructor. \n   econstructor. eapply PNew with(x:=i)(p:=H0); eauto. copy d. \n   erewrite <- decomposeErase in H1; eauto. rewrite unspecUnionComm in H2. \n   erewrite unspecLastActPool in H2. Focus 2. constructor. eraseTrmTac s1' M. \n   eapply specStepNewFull in H2; eauto. invertHyp. eapply simPureSteps in H1; eauto.\n   rewrite eraseFill in H1. erewrite eraseEraseTrm; eauto. \n   eapply lookupUnspecSpecNone; eauto. }\n  {inv H1. assert(heap_lookup i (eraseHeap H) = None). \n   eapply lookupEraseSpecNoneEmpty; eauto. \n   exists (Heap.extend i pempty (eraseHeap H) H0). econstructor. split. Focus 2. \n   split;eauto. eapply eraseHeapCommitNewEmpty; eauto. repeat rewrite eraseUnionComm.\n   erewrite eraseLastAct. Focus 2. constructor. econstructor. \n   eapply PNew with (x:=i)(p:=H0); eauto. copy d.\n   erewrite <- decomposeErase in H1; eauto. eraseTrmTac s1' M.\n   erewrite eraseEraseTrm; eauto. rewrite unspecUnionComm in H2. \n   erewrite unspecLastActPool in H2. Focus 2. constructor.\n   eapply specStepNewEmpty in H2; eauto. invertHyp.\n   eapply simPureSteps in H1; eauto. rewrite eraseFill in H1. eassumption. \n   eapply lookupUnspecSpecEmptyNone; eauto. }\n  {exists (eraseHeap H'). econstructor. split; auto. inv H1.\n   unfoldTac. rewrite coupleUnion. repeat rewrite eraseUnionComm. rewrite eraseEmpty. \n   unfold pUnion. rewrite union_empty_r. erewrite eraseLastAct. Focus 2. constructor. \n   econstructor. eapply pFork. copy d. erewrite <- decomposeErase in H; eauto. \n   simpl. auto. rewrite coupleUnion in H0. repeat rewrite unspecUnionComm in H0. \n   rewrite unspecEmpty in H0. erewrite unspecLastActPool in H0. Focus 2. constructor. \n   unfoldTac. rewrite union_empty_r in H0. rewrite <- coupleUnion in H0. \n   eapply specStepFork in H0; eauto. invertHyp. rewrite eraseUnspecHeapIdem in H1. \n   rewrite <- H1. eraseTrmTac s1' M. eraseTrmTac s1'' N. unfoldTac.\n   repeat rewrite coupleUnion in H. repeat rewrite Union_associative in H. \n   repeat rewrite coupleUnion. rewrite eraseUnionComm.\n   repeat erewrite eraseEraseTrm;eauto. unfold pUnion. repeat rewrite <- coupleUnion. \n   copy H. eapply simPureStepsCouple' with(H'':=eraseHeap x)(PT:=erasePool T)\n    (N:=pfill (eraseCtxt E)(pret punit)) in H; eauto. unfold pCouple. rewrite couple_swap. \n   eapply pmulti_trans. eassumption. rewrite UnionSwap in H0. rewrite <- Union_associative in H0. \n   rewrite UnionSwap in H0. rewrite Union_associative in H0.\n   eapply simPureStepsCouple in H0; eauto. rewrite eraseFill in H0; eauto.\n   unfold pCouple in *. rewrite couple_swap in H0. eauto. }\n  {exists (eraseHeap H'). econstructor. split; auto. inv H1. unfoldTac. \n   rewrite coupleUnion in *. repeat rewrite unspecUnionComm in H0.\n   rewrite unspecEmpty in H0. unfoldTac. rewrite union_empty_r in H0. \n   repeat rewrite eraseUnionComm. rewrite eraseEmpty. erewrite eraseLastAct. Focus 2. \n   constructor. unfold pUnion. rewrite union_empty_r. econstructor. \n   eapply pSpec. copy d. rewrite <- decomposeErase in H; eauto. simpl. auto. \n   rewrite <- coupleUnion in H0. erewrite unspecLastActPool in H0. Focus 2. constructor. \n   eapply specStepSpec in H0; eauto. invertHyp. eraseTrmTac s1' M'. rewrite coupleUnion. \n   rewrite eraseUnionComm. erewrite eraseEraseTrm; eauto. simpl. unfoldTac.\n   flipCouplesIn H.  repeat rewrite coupleUnion in H. repeat rewrite Union_associative in H. \n   eapply simPureSteps in H; eauto. rewrite eraseFill in H. eassumption. }\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/progStepImpliesSpec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2560875842757364}}
{"text": "(**\nCoLoR, a Coq library on rewriting and termination.\nSee the COPYRIGHTS and LICENSE files.\n\n- Sebastien Hinderer, 2004-02-09\n\ngeneral definitions and results about relations on terms\n*)\n\nSet Implicit Arguments.\n\nFrom CoLoR Require Import SN ASubstitution ATerm RelUtil AContext LogicUtil\n     VecUtil NaryFunction.\nFrom Coq Require Import List.\n\nSection S.\n\n  Variable Sig : Signature.\n\n  Notation term := (term Sig).\n\n(***********************************************************************)\n(** basic definitions *)\n\n  Section basic.\n\n    Variable R : relation term.\n\n    Definition preserve_vars := forall t u, R t u -> incl (vars u) (vars t).\n\n    Definition substitution_closed :=\n      forall t1 t2 s, R t1 t2 -> R (sub s t1) (sub s t2).\n\n    Definition context_closed :=\n      forall t1 t2 c, R t1 t2 -> R (fill c t1) (fill c t2).\n\n    Definition rewrite_ordering := substitution_closed /\\ context_closed.\n\n    Definition reduction_ordering := WF R /\\ rewrite_ordering.\n\n  End basic.\n\n  Record Rewrite_ordering : Type := mkRewrite_ordering {\n    rew_ord_rel :> relation term;\n    rew_ord_subs : substitution_closed rew_ord_rel;\n    rew_ord_cont : context_closed rew_ord_rel\n  }.\n\n(***********************************************************************)\n(** closure by substitution *)\n\n  Lemma substitution_closed_rtc : forall R,\n    substitution_closed R -> substitution_closed (R #).\n\n  Proof.\n    intros R h t u s. induction 1. apply rt_step. apply h. hyp.\n    apply rt_refl. apply rt_trans with (sub s y); hyp.\n  Qed.\n\n  Lemma substitution_closed_transp : forall R,\n    substitution_closed R -> substitution_closed (transp R).\n\n  Proof.\n    intros R hR t u s. unfold transp. apply hR.\n  Qed.\n\n(***********************************************************************)\n(** closure by context *)\n\n  Lemma context_closed_rtc : forall R, context_closed R -> context_closed (R #).\n\n  Proof.\n    intros R h t u c. induction 1. apply rt_step. apply h. hyp.\n    apply rt_refl. apply rt_trans with (fill c y); hyp.\n  Qed.\n\n  Lemma context_closed_tc : forall R, context_closed R -> context_closed (R !).\n\n  Proof.\n    intros R h t u c. induction 1. apply t_step. apply h. hyp.\n    apply t_trans with (fill c y); hyp.\n  Qed.\n\n  Lemma context_closed_comp : forall R S,\n    context_closed R -> context_closed S -> context_closed (R @ S).\n\n  Proof.\n    intros R S hR hS t v c [u [h1 h2]]. exists (fill c u). split.\n    apply hR. hyp. apply hS. hyp.\n  Qed.\n\n  Lemma context_closed_fun : forall R, context_closed R ->\n    forall f i v1 t u j v2 (e : i+S j=arity f),\n      R t u -> R (Fun f (Vcast (Vapp v1 (Vcons t v2)) e))\n                 (Fun f (Vcast (Vapp v1 (Vcons u v2)) e)).\n\n  Proof.\n    intros. set (c := Cont f e v1 Hole v2). change (R (fill c t) (fill c u)).\n    apply H. hyp.\n  Qed.\n\n  Lemma Vmonotone_context_closed : forall R,\n    (forall f : Sig, Vmonotone (Fun f) R R) <-> context_closed R.\n\n  Proof.\n    split; intro.\n    unfold context_closed. induction c; simpl; intros. hyp. apply H. auto.\n    unfold Vmonotone, Vmonotone_i, RelUtil.monotone. intros.\n    set (c := Cont f H0 vi Hole vj). change (R (fill c x) (fill c y)).\n    apply H. hyp.\n  Qed.\n\n(***********************************************************************)\n(** reduction pair *)\n\n  Section reduction_pair.\n\n    Variables R E : relation term.\n\n    Definition reduction_pair :=\n      reduction_ordering R /\\ absorbs_left R E /\\ rewrite_ordering E.\n\n  End reduction_pair.\n\n(*FIXME: defined as weak_reduction_pair + something*)\n  Record Reduction_pair : Type := mkReduction_pair {\n    rp_succ : relation term;\n    rp_succ_eq : relation term;\n    rp_subs : substitution_closed rp_succ;\n    rp_subs_eq : substitution_closed rp_succ_eq;\n    rp_cont : context_closed rp_succ;\n    rp_cont_eq : context_closed rp_succ_eq;\n    rp_absorb : absorbs_left rp_succ rp_succ_eq;\n    rp_succ_wf : WF rp_succ\n  }.\n\n(***********************************************************************)\n(** weak reduction pair *)\n\n  Section weak_reduction_pair.\n\n    Variables R E : relation term.\n\n    Definition weak_context_closed :=\n      forall t1 t2 c, R t1 t2 -> E (fill c t1) (fill c t2).\n\n    Definition weak_rewrite_ordering :=\n      substitution_closed R /\\ weak_context_closed.\n\n    Definition weak_reduction_ordering := WF R /\\ weak_rewrite_ordering.\n\n    Definition weak_reduction_pair :=\n      weak_reduction_ordering /\\ absorbs_left R E /\\ rewrite_ordering E.\n\n  End weak_reduction_pair.\n\n  Record Weak_reduction_pair : Type := mkWeak_reduction_pair {\n    wp_succ : relation term;\n    wp_succ_eq : relation term;\n    wp_subs : substitution_closed wp_succ;\n    wp_subs_eq : substitution_closed wp_succ_eq;\n    wp_cont_eq : context_closed wp_succ_eq;\n    wp_absorb : absorbs_left wp_succ wp_succ_eq;\n    wp_succ_wf : WF wp_succ\n  }.\n\n(***********************************************************************)\n(** reflexive closure *)\n\n  Section clos_refl.\n\n    Variable R : relation term.\n\n    Notation E := (R %).\n\n    Lemma rc_context_closed :\n      weak_context_closed R E -> context_closed E.\n\n    Proof.\n      intro. unfold context_closed. intros. unfold clos_refl, union in H0.\n      decomp H0. subst t2. unfold clos_refl, union. auto. apply H. hyp.\n    Qed.\n\n    Lemma rc_substitution_closed :\n      substitution_closed R -> substitution_closed E.\n\n    Proof.\n      intro. unfold substitution_closed, clos_refl, union. intros. decomp H0.\n      subst t2. auto. right. apply H. hyp.\n    Qed.\n\n    Lemma rc_rewrite_ordering :\n      weak_rewrite_ordering R E -> rewrite_ordering E.\n\n    Proof.\n      intros (Hsubs,Hcont). split. apply rc_substitution_closed. hyp.\n      apply rc_context_closed. hyp.\n    Qed.\n\n  End clos_refl.\n\n(***********************************************************************)\n(** when R is the strict part of E *)\n\n  Section strict.\n\n    Variables (E : relation term) (E_trans : transitive E).\n\n    Notation R := (strict_part E).\n\n    Lemma absorb_strict : absorbs_left R E.\n\n    Proof.\n      unfold absorbs_left, inclusion, RelUtil.compose, strict_part.\n      intros; split; decomp H. eapply E_trans. apply H1. hyp.\n      unfold not; intro. ded (E_trans H H1). contr.\n    Qed.\n\n  End strict.\n\n(***********************************************************************)\n(** subterm relation *)\n\n  Lemma substitution_closed_subterm_eq : substitution_closed (@subterm_eq Sig).\n\n  Proof.\n    intros t u s h. destruct h as [C h]. subst. rewrite sub_fill.\n    exists (subc s C). refl.\n  Qed.\n\n  Lemma substitution_closed_subterm : substitution_closed (@subterm Sig).\n\n  Proof.\n    intros t u s h. destruct h as [C h]. destruct h as [C0 h]. subst.\n    rewrite sub_fill.\n    exists (subc s C). split; try refl. destruct C. simpl. auto. discr.\n  Qed.\n\nEnd S.\n", "meta": {"author": "fblanqui", "repo": "color", "sha": "f2ef98f7d13c5d71dd2a614ed2e6721703a34532", "save_path": "github-repos/coq/fblanqui-color", "path": "github-repos/coq/fblanqui-color/color-f2ef98f7d13c5d71dd2a614ed2e6721703a34532/Term/WithArity/ARelation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2560875842757364}}
{"text": "\nSection General_Definitions.\n\n  Definition approx := (env * (term * list term))%type.\n\n  Fixpoint app_list (args : list term) : term -> term :=\n    fun t =>\n    match args with\n    | nil => t\n    | hd :: tl => app_list tl (App t hd)\n    end.\n\nEnd General_Definitions.\n\nSection Beta_Reduction.\n\n  Inductive beta : env -> term -> term -> Prop :=\n      beta_intro :\n        forall (e : env) (M N T : term), beta e (App (Abs T M) N) (subst N M).\n\n  Hint Resolve beta_intro: pts.\n\n\n  Lemma beta_rule : Basic_rule.\napply Build_Basic_rule with beta.\nred in |- *.\nsimple induction 1; simpl in |- *; intros.\nrewrite distr_lift_subst; auto with arith pts.\n\nred in |- *.\nsimple induction 1; simpl in |- *; intros.\nrewrite distr_subst; auto with arith pts.\n\nred in |- *; intros.\nelim H; auto with arith pts.\nDefined.\n\n\n  Lemma sort_beta_norm : forall (e : env) (s : sort), normal beta e (Srt s).\nred in |- *; red in |- *; intros.\ninversion_clear H.\nQed.\n\n  Lemma prod_beta_norm :\n   forall (e : env) (A B : term), normal beta e (Prod A B).\nred in |- *; red in |- *; intros.\ninversion_clear H.\nQed.\n\nEnd Beta_Reduction.\n\n  Hint Resolve beta_intro: pts.\n\n\n\n\nSection Delta_Reduction.\n\n\n  Inductive delta : env -> term -> term -> Prop :=\n      delta_intro :\n        forall (e : env) (n : nat) (d T : term),\n        item (Def d T) e n -> delta e (Ref n) (lift (S n) d).\n\n\n  Lemma delta_rule : Basic_rule.\napply Build_Basic_rule with delta.\nred in |- *.\nsimple induction 1; simpl in |- *; intros.\nelim (le_gt_dec k n); intros.\nunfold lift in |- *.\nrewrite simpl_lift_rec; simpl in |- *; auto with arith pts.\nchange (delta f (Ref (S n)) (lift (S (S n)) d)) in |- *.\napply delta_intro with T; auto with arith pts.\napply ins_item_ge with (1 := H1); auto with arith pts.\n\nunfold lift in |- *.\nreplace k with (S n + (k - S n)); auto with arith pts.\nelim permute_lift_rec with d 1 (k - S n) (S n) 0; auto with arith pts.\nchange (delta f (Ref n) (lift (S n) (lift_rec 1 d (k - S n)))) in |- *.\napply delta_intro with (lift_rec 1 T (k - S n)).\nchange (item (lift_decl 1 (Def d T) (k - S n)) f n) in |- *.\napply ins_item_lt with (1 := H1); auto with arith pts.\n\nred in |- *.\nsimple induction 1; simpl in |- *; intros.\nelim (lt_eq_lt_dec n0 n); intros.\nred in |- *.\nelim a.\ngeneralize H0.\nclear H0.\ncase n; simpl in |- *; intros.\ninversion_clear a0.\n\nrewrite simpl_subst; auto with arith pts.\napply rt_step.\napply delta_intro with T.\napply nth_sub_sup with (1 := H1); auto with arith pts.\n\nintro.\nrewrite b.\nrewrite simpl_subst.\nrewrite b in H1.\ngeneralize H1.\nrewrite nth_sub_eq with (1 := H1) (2 := H0).\nintro.\nelim sub_decl_eq_def with (1 := H2).\nauto with arith pts.\n\nauto with arith pts.\n\nred in |- *; apply rt_step.\nreplace n0 with (S n + (n0 - S n)); auto with arith pts.\nunfold lift in |- *.\nelim commut_lift_subst_rec with d s (S n) (n0 - S n) 0; auto with arith pts.\nchange (delta f (Ref n) (lift (S n) (subst_rec s d (n0 - S n)))) in |- *.\napply delta_intro with (subst_rec s T (n0 - S n)).\nchange (item (subst_decl s (Def d T) (n0 - S n)) f n) in |- *.\napply nth_sub_inf with (1 := H1); auto with arith pts.\n\nred in |- *; intros.\ninversion_clear H.\nelim red_item with R' n (Def d T) e f; intros; auto with arith pts.\napply delta_intro with T; auto with arith pts.\n\nelim item_trunc with decl n e (Def d T); intros; auto with arith pts.\nelim H with x0; intros; auto with arith pts.\ninversion_clear H3.\ngeneralize H6.\ninversion_clear H5; intros.\napply delta_intro with U; auto with arith pts.\nDefined.\n\n\n  Lemma delta_reduce :\n   forall (n : nat) (e : env),\n   {def : term | delta e (Ref n) def} +\n   {(forall x : term, ~ delta e (Ref n) x)}.\n(*Realizer [n:nat][e:env]Cases (list_item ? e n) of\n             (inleft (Ax T)) => (inright term)\n           | (inleft (Def d T)) => (inleft term (lift (S n) d))\n           | _ => (inright term)\n           end.\n*)\nintros.\ncase (list_item e n); [ intros ([T| d T], is_dcl) | intros ].\nright; red in |- *; intros.\ninversion_clear H.\nabsurd (Ax T = Def d T0).\ndiscriminate.\n\napply fun_item with e n; auto with arith pts.\n\nleft; exists (lift (S n) d).\napply delta_intro with T; auto with arith pts.\n\nright; red in |- *; intros.\ninversion_clear H.\nelim n0 with (Def d T); auto with arith pts.\nQed.\n\n  Lemma sort_delta_norm : forall (e : env) (s : sort), normal delta e (Srt s).\nred in |- *; red in |- *; intros.\ninversion_clear H.\nQed.\n\n  Lemma prod_delta_norm :\n   forall (e : env) (A B : term), normal delta e (Prod A B).\nred in |- *; red in |- *; intros.\ninversion_clear H.\nQed.\n\nEnd Delta_Reduction.", "meta": {"author": "coq-contribs", "repo": "pts", "sha": "10a0c39b7e62f8a7ec2afbbe516a21289d065be5", "save_path": "github-repos/coq/coq-contribs-pts", "path": "github-repos/coq/coq-contribs-pts/pts-10a0c39b7e62f8a7ec2afbbe516a21289d065be5/Lambda_Rules.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4493926344647596, "lm_q1q2_score": 0.25608758427573636}}
{"text": "From ITree Require Import\n     Basics\n     Subevent\n     Indexed.Sum.\n\nFrom Coq Require Import\n     Fin\n     Lia\n     Vector\n     String.\n\nFrom ExtLib Require Import\n     RelDec\n     Maps\n     FMapAList\n     Reducible\n     Traversable\n     Monads\n     Option.\n\nFrom Coinduction Require Import\n     coinduction rel tactics.\n\nFrom CTree Require Import\n     CTree\n     Interp\n     State\n     Eq\n     SBisim.\n\nFrom DSL Require Import\n     System\n     Network\n     Utils\n     Vectors.\n\nFrom Equations Require Import Equations.\n\nImport MonadNotation.\nLocal Open Scope monad_scope.\nLocal Open Scope string_scope.\nLocal Open Scope vector_scope.\n\nSet Implicit Arguments.\nSet Strict Implicit.\nSet Asymmetric Patterns.\n\nModule Examples.\n  Module Network := Network(DistrSystem).                               \n  Import Network DistrSystem.\n\n  (** Some uids *)\n  Program Definition alice : uid 2 := @of_nat_lt 0 2 _.\n  Program Definition bob : uid 2 := @of_nat_lt 1 2 _.\n  \n  (** Some programs *)\n  Definition example_alice :=\n    a <- load \"a\";;\n    send {| principal := bob; payload := default a 0 |};;\n    a' <- recv;;\n    store \"b\" (payload a').\n\n  Definition example_bob: ctree (Storage +' Net 2) unit :=\n    m <- recv ;;\n    send {| principal := principal m; payload := S (payload m) |}.\n\n  (** A Single agent program *)\n  Definition example: ctree (Storage +' Net 2) unit :=\n    a <- load \"a\";;\n    store \"b\" (S (default a 0)).\n\n  Definition example_skip: ctree (Storage +' Net 2) unit :=\n    Ret tt.\n\n  (** Here we are evaluating two distributed systems to CTrees C1, C2.\n      We will show they are equivalent by some sort of Applicative Bisimulation\n      using the leaf equivalence below. *) \n Definition init_heap := (List.cons (\"a\", 0) List.nil).\n\n  Definition C1 := run_network (map voidR (run_storage [example; example_skip] init_heap)).\n  Definition C2 := run_network (map voidR (run_storage [example_alice; example_bob] init_heap)).\n\n  Check (run_storage [example] init_heap).\n  \n\n  Definition final_heap1: heap := List.cons (\"b\", 1) (List.cons (\"a\", 0)   List.nil).\n  Definition final_heap2: heap := List.cons (\"a\", 0) List.nil.\n\n  Lemma left_tree_simpl: C1 ~ Ret (Some\n                                     [(final_heap1, tt, List.nil); (final_heap2, tt, List.nil)]). \n  Proof.\n    unfold C1, final_heap1, final_heap2, init_heap, run_storage.\n    rewrite Vector.map_map.\n    cbn.\n    unfold run_state.\n    Search interp_state.\n    s\n    rewrite interp_state_bind.\n    cbn.\n    replace (map voidR (run_storage [example; example_skip] init_heap)) with\n      ([run_storage example init_heap; run_storage example_skip init_heap]).\n        \n    Search map.\n    \n    sb_fwd_I.\n    Check run_state.\n    time repeat (sb_fwd_I; try reflexivity).\n  Qed.\n    \n  Lemma sb_c1_c2: C1 ~ C2.\n  Proof.\n    rewrite left_tree_simpl.\n    unfold C1, C2, init_heap.\n    time repeat (sb_fwd_I; try reflexivity).\n    (**  Takes 6035.167 secs ~ 1.7h *)\n  Qed.\n    \nEnd Examples.\n    \n", "meta": {"author": "elefthei", "repo": "reasoning-about-distributed-systems", "sha": "f85bccad8ce15dcac10ecdd9f6cec39a8e98a2d7", "save_path": "github-repos/coq/elefthei-reasoning-about-distributed-systems", "path": "github-repos/coq/elefthei-reasoning-about-distributed-systems/reasoning-about-distributed-systems-f85bccad8ce15dcac10ecdd9f6cec39a8e98a2d7/denotational/Examples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.25598374265404206}}
{"text": "\nRequire Export Iron.Language.SystemF2Cap.Value.\nRequire Export Iron.Language.SystemF2Cap.Store.\nRequire Export Iron.Language.SystemF2Cap.Step.Frame.\nRequire Export Iron.Language.SystemF2Cap.Step.TypeF.\n\n\n(********************************************************************)\n(* Type of an expression in a frame context. *)\nInductive TypeC \n   :  kienv -> tyenv \n   -> stenv -> stprops \n   -> stack -> exp \n   -> ty    -> ty -> Prop :=\n | TcExp\n   :  forall ke te se sp fs x1 t1 e1 t2 e2 e3\n   ,  EquivT ke sp (TSum e1 e2) e3 KEffect\n   -> TypeX  ke te se sp x1 t1 e1\n   -> TypeF  ke te se sp fs t1 t2 e2\n   -> TypeC  ke te se sp fs x1 t2 e3.\n\nHint Constructors TypeC.\n\n\nLtac inverts_typec :=\n repeat\n  (try (match goal with\n        | [H: TypeC _ _ _ _ _ _ _ _ |- _ ] => inverts H\n        end);\n   try inverts_typef).\n\n\n(********************************************************************)\nLemma typeC_kindT_effect\n :  forall ke te se sp fs x t e\n ,  TypeC  ke te se sp fs x t e\n -> KindT  ke sp e KEffect.\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/TypeC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.25598374265404206}}
{"text": "From stdpp Require Export namespaces.\nFrom iris.algebra Require Import gmap.\nFrom iris.proofmode Require Import tactics.\nFrom iris.base_logic.lib Require Export fancy_updates.\nFrom iris.base_logic.lib Require Import wsat.\nFrom iris.prelude Require Import options.\nImport uPred.\n\n(** Semantic Invariants *)\nDefinition inv_def `{!invG Σ} (N : namespace) (P : iProp Σ) : iProp Σ :=\n  □ ∀ E, ⌜↑N ⊆ E⌝ → |={E,E ∖ ↑N}=> ▷ P ∗ (▷ P ={E ∖ ↑N,E}=∗ True).\nDefinition inv_aux : seal (@inv_def). Proof. by eexists. Qed.\nDefinition inv := inv_aux.(unseal).\nGlobal Arguments inv {Σ _} N P.\nDefinition inv_eq : @inv = @inv_def := inv_aux.(seal_eq).\nGlobal Instance: Params (@inv) 3 := {}.\n\n(** * Invariants *)\nSection inv.\n  Context `{!invG Σ}.\n  Implicit Types i : positive.\n  Implicit Types N : namespace.\n  Implicit Types E : coPset.\n  Implicit Types P Q R : iProp Σ.\n\n  (** ** Internal model of invariants *)\n  Definition own_inv (N : namespace) (P : iProp Σ) : iProp Σ :=\n    ∃ i, ⌜i ∈ (↑N:coPset)⌝ ∧ ownI i P.\n\n  Lemma own_inv_acc E N P :\n    ↑N ⊆ E → own_inv N P ={E,E∖↑N}=∗ ▷ P ∗ (▷ P ={E∖↑N,E}=∗ True).\n  Proof.\n    rewrite uPred_fupd_eq /uPred_fupd_def. iDestruct 1 as (i) \"[Hi #HiP]\".\n    iDestruct \"Hi\" as % ?%elem_of_subseteq_singleton.\n    rewrite {1 4}(union_difference_L (↑ N) E) // ownE_op; last set_solver.\n    rewrite {1 5}(union_difference_L {[ i ]} (↑ N)) // ownE_op; last set_solver.\n    iIntros \"(Hw & [HE $] & $) !> !>\".\n    iDestruct (ownI_open i with \"[$Hw $HE $HiP]\") as \"($ & $ & HD)\".\n    iIntros \"HP [Hw $] !> !>\". iApply (ownI_close _ P). by iFrame.\n  Qed.\n\n  Lemma fresh_inv_name (E : gset positive) N : ∃ i, i ∉ E ∧ i ∈ (↑N:coPset).\n  Proof.\n    exists (coPpick (↑ N ∖ gset_to_coPset E)).\n    rewrite -elem_of_gset_to_coPset (comm and) -elem_of_difference.\n    apply coPpick_elem_of=> Hfin.\n    eapply nclose_infinite, (difference_finite_inv _ _), Hfin.\n    apply gset_to_coPset_finite.\n  Qed.\n\n  Lemma own_inv_alloc N E P : ▷ P ={E}=∗ own_inv N P.\n  Proof.\n    rewrite uPred_fupd_eq. iIntros \"HP [Hw $]\".\n    iMod (ownI_alloc (.∈ (↑N : coPset)) P with \"[$HP $Hw]\")\n      as (i ?) \"[$ ?]\"; auto using fresh_inv_name.\n    do 2 iModIntro. iExists i. auto.\n  Qed.\n\n  (* This does not imply [own_inv_alloc] due to the extra assumption [↑N ⊆ E]. *)\n  Lemma own_inv_alloc_open N E P :\n    ↑N ⊆ E → ⊢ |={E, E∖↑N}=> own_inv N P ∗ (▷P ={E∖↑N, E}=∗ True).\n  Proof.\n    rewrite uPred_fupd_eq. iIntros (Sub) \"[Hw HE]\".\n    iMod (ownI_alloc_open (.∈ (↑N : coPset)) P with \"Hw\")\n      as (i ?) \"(Hw & #Hi & HD)\"; auto using fresh_inv_name.\n    iAssert (ownE {[i]} ∗ ownE (↑ N ∖ {[i]}) ∗ ownE (E ∖ ↑ N))%I\n      with \"[HE]\" as \"(HEi & HEN\\i & HE\\N)\".\n    { rewrite -?ownE_op; [|set_solver..].\n      rewrite assoc_L -!union_difference_L //. set_solver. }\n    do 2 iModIntro. iFrame \"HE\\N\". iSplitL \"Hw HEi\"; first by iApply \"Hw\".\n    iSplitL \"Hi\".\n    { iExists i. auto. }\n    iIntros \"HP [Hw HE\\N]\".\n    iDestruct (ownI_close with \"[$Hw $Hi $HP $HD]\") as \"[$ HEi]\".\n    do 2 iModIntro. iSplitL; [|done].\n    iCombine \"HEi HEN\\i HE\\N\" as \"HEN\".\n    rewrite -?ownE_op; [|set_solver..].\n    rewrite assoc_L -!union_difference_L //; set_solver.\n  Qed.\n\n  Lemma own_inv_to_inv M P: own_inv M P -∗ inv M P.\n  Proof.\n    iIntros \"#I\". rewrite inv_eq. iIntros (E H).\n    iPoseProof (own_inv_acc with \"I\") as \"H\"; eauto.\n  Qed.\n\n  (** ** Public API of invariants *)\n  Global Instance inv_contractive N : Contractive (inv N).\n  Proof. rewrite inv_eq. solve_contractive. Qed.\n\n  Global Instance inv_ne N : NonExpansive (inv N).\n  Proof. apply contractive_ne, _. Qed.\n\n  Global Instance inv_proper N : Proper (equiv ==> equiv) (inv N).\n  Proof. apply ne_proper, _. Qed.\n\n  Global Instance inv_persistent N P : Persistent (inv N P).\n  Proof. rewrite inv_eq. apply _. Qed.\n\n  Lemma inv_alter N P Q : inv N P -∗ ▷ □ (P -∗ Q ∗ (Q -∗ P)) -∗ inv N Q.\n  Proof.\n    rewrite inv_eq. iIntros \"#HI #HPQ !>\" (E H).\n    iMod (\"HI\" $! E H) as \"[HP Hclose]\".\n    iDestruct (\"HPQ\" with \"HP\") as \"[$ HQP]\".\n    iIntros \"!> HQ\". iApply \"Hclose\". iApply \"HQP\". done.\n  Qed.\n\n  Lemma inv_iff N P Q : inv N P -∗ ▷ □ (P ↔ Q) -∗ inv N Q.\n  Proof.\n    iIntros \"#HI #HPQ\". iApply (inv_alter with \"HI\").\n    iIntros \"!> !> HP\". iSplitL \"HP\".\n    - by iApply \"HPQ\".\n    - iIntros \"HQ\". by iApply \"HPQ\".\n  Qed.\n\n  Lemma inv_alloc N E P : ▷ P ={E}=∗ inv N P.\n  Proof.\n    iIntros \"HP\". iApply own_inv_to_inv.\n    iApply (own_inv_alloc N E with \"HP\").\n  Qed.\n\n  Lemma inv_alloc_open N E P :\n    ↑N ⊆ E → ⊢ |={E, E∖↑N}=> inv N P ∗ (▷P ={E∖↑N, E}=∗ True).\n  Proof.\n    iIntros (?). iMod own_inv_alloc_open as \"[HI $]\"; first done.\n    iApply own_inv_to_inv. done.\n  Qed.\n\n  Lemma inv_acc E N P :\n    ↑N ⊆ E → inv N P ={E,E∖↑N}=∗ ▷ P ∗ (▷ P ={E∖↑N,E}=∗ True).\n  Proof.\n    rewrite inv_eq /inv_def; iIntros (?) \"#HI\". by iApply \"HI\".\n  Qed.\n\n  Lemma inv_combine N1 N2 N P Q :\n    N1 ## N2 →\n    ↑N1 ∪ ↑N2 ⊆@{coPset} ↑N →\n    inv N1 P -∗ inv N2 Q -∗ inv N (P ∗ Q).\n  Proof.\n    rewrite inv_eq. iIntros (??) \"#HinvP #HinvQ !>\"; iIntros (E ?).\n    iMod (\"HinvP\" with \"[%]\") as \"[$ HcloseP]\"; first set_solver.\n    iMod (\"HinvQ\" with \"[%]\") as \"[$ HcloseQ]\"; first set_solver.\n    iMod (fupd_intro_mask' _ (E ∖ ↑N)) as \"Hclose\"; first set_solver.\n    iIntros \"!> [HP HQ]\".\n    iMod \"Hclose\" as %_. iMod (\"HcloseQ\" with \"HQ\") as %_. by iApply \"HcloseP\".\n  Qed.\n\n  Lemma inv_combine_dup_l N P Q :\n    □ (P -∗ P ∗ P) -∗\n    inv N P -∗ inv N Q -∗ inv N (P ∗ Q).\n  Proof.\n    rewrite inv_eq. iIntros \"#HPdup #HinvP #HinvQ !>\" (E ?).\n    iMod (\"HinvP\" with \"[//]\") as \"[HP HcloseP]\".\n    iDestruct (\"HPdup\" with \"HP\") as \"[$ HP]\".\n    iMod (\"HcloseP\" with \"HP\") as %_.\n    iMod (\"HinvQ\" with \"[//]\") as \"[$ HcloseQ]\".\n    iIntros \"!> [HP HQ]\". by iApply \"HcloseQ\".\n  Qed.\n\n  (** ** Proof mode integration *)\n  Global Instance into_inv_inv N P : IntoInv (inv N P) N := {}.\n\n  Global Instance into_acc_inv N P E:\n    IntoAcc (X := unit) (inv N P)\n            (↑N ⊆ E) True (fupd E (E ∖ ↑N)) (fupd (E ∖ ↑N) E)\n            (λ _ : (), (▷ P)%I) (λ _ : (), (▷ P)%I) (λ _ : (), None).\n  Proof.\n    rewrite inv_eq /IntoAcc /accessor bi.exist_unit.\n    iIntros (?) \"#Hinv _\". iApply \"Hinv\"; done.\n  Qed.\n\n  (** ** Derived properties *)\n  Lemma inv_acc_strong E N P :\n    ↑N ⊆ E → inv N P ={E,E∖↑N}=∗ ▷ P ∗ ∀ E', ▷ P ={E',↑N ∪ E'}=∗ True.\n  Proof.\n    iIntros (?) \"Hinv\".\n    iPoseProof (inv_acc (↑ N) N with \"Hinv\") as \"H\"; first done.\n    rewrite difference_diag_L.\n    iPoseProof (fupd_mask_frame_r _ _ (E ∖ ↑ N) with \"H\") as \"H\"; first set_solver.\n    rewrite left_id_L -union_difference_L //. iMod \"H\" as \"[$ H]\"; iModIntro.\n    iIntros (E') \"HP\".\n    iPoseProof (fupd_mask_frame_r _ _ E' with \"(H HP)\") as \"H\"; first set_solver.\n    by rewrite left_id_L.\n  Qed.\n\n  Lemma inv_acc_timeless E N P `{!Timeless P} :\n    ↑N ⊆ E → inv N P ={E,E∖↑N}=∗ P ∗ (P ={E∖↑N,E}=∗ True).\n  Proof.\n    iIntros (?) \"Hinv\". iMod (inv_acc with \"Hinv\") as \"[>HP Hclose]\"; auto.\n    iIntros \"!> {$HP} HP\". iApply \"Hclose\"; auto.\n  Qed.\n\n  Lemma inv_split_l N P Q : inv N (P ∗ Q) -∗ inv N P.\n  Proof.\n    iIntros \"#HI\". iApply inv_alter; eauto.\n    iIntros \"!> !> [$ $] $\".\n  Qed.\n  Lemma inv_split_r N P Q : inv N (P ∗ Q) -∗ inv N Q.\n  Proof.\n    rewrite (comm _ P Q). eapply inv_split_l.\n  Qed.\n  Lemma inv_split N P Q : inv N (P ∗ Q) -∗ inv N P ∗ inv N Q.\n  Proof.\n    iIntros \"#H\".\n    iPoseProof (inv_split_l with \"H\") as \"$\".\n    iPoseProof (inv_split_r with \"H\") as \"$\".\n  Qed.\n\nEnd inv.\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/invariants.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2559782363036992}}
{"text": "(* Celsius project *)\n(* Clément Blaudeau - Lamp@EPFL & Inria 2020-2022 *)\n(* ------------------------------------------------------------------------ *)\n(* This file defines and proves the soundess of the type system. *)\n\nFrom Celsius Require Export LocalReasoning Eval.\nImplicit Type (ρ: Env).\n\n(* ------------------------------------------------------------------------ *)\nLocal Hint Constructors evalP expr_typing expr_list_typing: typ.\n\n(* We assume the class table is well typed : *)\n\nParameter typable_classes : T_Classes.\n\n(* ------------------------------------------------------------------------ *)\n(** ** Weakening *)\n\nLemma S_Typs_weakening:\n  forall Γ Γ',\n    S_Typs Γ' Γ ->\n    forall x T__x, typeLookup Γ x = Some T__x -> exists T__x', typeLookup Γ' x = Some T__x' /\\ T__x' <: T__x.\nProof with (meta; eauto with typ).\n  intros. gen x T__x. unfold S_Typs in *.\n  induction H; steps.\n  - destruct x; steps.\n  - destruct x0; steps...\nQed.\nGlobal Hint Resolve S_Typs_weakening: typ.\n\n(* Our typing enjoys a weakening lemma *)\nTheorem weakening: forall Γ Γ' U e T,\n    S_Typs Γ' Γ ->\n    ((Γ, U) ⊢ e : T) ->\n    ((Γ', U) ⊢ e : T).\nProof with (meta; eauto using expr_typing with typ lia).\n  intros.\n  lets: S_Typs_weakening H. clear H. gen Γ'.\n  induction H0 using typing_ind with\n    (Pl := fun Γ0 T0 el Ul _ =>\n             forall Γ',\n               (forall x T__x, typeLookup Γ0 x = Some T__x -> exists T__x', typeLookup Γ' x = Some T__x' /\\ T__x' <: T__x) ->\n               ((Γ0, T0) ⊩ el : Ul) ->\n               ((Γ', T0) ⊩ el : Ul));\n    intros ...\n  eapply H1 in H__lkp as [T__x' [ ]]...\nQed.\n\n(* ------------------------------------------------------------------------ *)\n(** ** Soundness statements *)\n\nDefinition expr_soundness n e ρ σ ψ r Γ Σ U T :=\n    ((Γ, U) ⊢ e : T) ->\n    Σ ⊨ ρ : Γ ->\n    Σ ⊨ σ ->\n    (Σ ⊨ ψ : U) ->\n    wf σ ->\n    (codom ρ ∪ {ψ} ⪽ σ) ->\n    ⟦e⟧(σ, ρ, ψ, n) = r ->\n    r <> Timeout ->\n    exists Σ' v σ',\n      r = Success v σ' /\\\n        Σ ≼ Σ' /\\ Σ ≪ Σ' /\\ Σ ▷ Σ' /\\ (Σ' ⊨ σ') /\\ wf σ' /\\\n        Σ' ⊨ v : T.\n\nDefinition expr_list_soundness n el ρ σ ψ r Γ Σ U Tl :=\n    ((Γ, U) ⊩ el : Tl) ->\n    Σ ⊨ ρ : Γ ->\n    Σ ⊨ σ ->\n    (Σ ⊨ ψ : U) ->\n    wf σ ->\n    (codom ρ ∪ {ψ} ⪽ σ) ->\n    ⟦_ el _⟧(σ, ρ, ψ, n) = r ->\n    r <> Timeout_l ->\n    exists Σ' vl σ',\n      r = Success_l vl σ' /\\\n        Σ ≼ Σ' /\\ Σ ≪ Σ' /\\ Σ ▷ Σ' /\\ (Σ' ⊨ σ') /\\ wf σ' /\\\n        Σ' ⊨ vl : Tl.\n\nDefinition init_soundness n C ψ i i' ρ σ Γ Σ r :=\n  forall Args Flds Mtds,\n    Σ ⊨ ρ : Γ ->\n    Σ ⊨ σ ->\n\n    wf σ ->\n    (codom ρ ∪ {ψ} ⪽ σ) ->\n\n    ct C = class Args Flds Mtds ->\n    getType Σ ψ = Some (C, cool i') ->\n    S_Typs Γ Args ->\n    i' >= i ->\n\n    init C ψ i ρ σ n = r ->\n    r <> Timeout_i ->\n\n    exists Σ' σ',\n      r = Success_i σ' /\\\n        Σ ≼ Σ' /\\ Σ ≪ Σ' /\\ ([ψ↦(C,cool (dom Flds))]Σ ▷ Σ') /\\ (Σ' ⊨ σ') /\\ wf σ'.\n\n(* We then prove several cases as lemmas *)\n\n(* ------------------------------------------------------------------------ *)\n(** ** Soundness of field access *)\n\nLemma soundness_fld:\n  forall n,\n    (forall e ρ σ ψ r Γ Σ U T,\n        expr_soundness n e ρ σ ψ r Γ Σ U T) /\\\n    (forall el ρ σ ψ r Γ Σ U Tl,\n      expr_list_soundness n el ρ σ ψ r Γ Σ U Tl) /\\\n    (forall C I n1 n2 ρ σ Γ Σ r,\n        init_soundness n C I n1 n2 ρ σ Γ Σ r) ->\n    (forall e f ρ σ ψ r Γ Σ U T,\n        expr_soundness (S n) (e_fld e f) ρ σ ψ r Γ Σ U T).\nProof with (meta; meta_clean; eauto 2 with typ;\n            try match goal with\n                | |- ?Σ ⊨ ?l : ?T => try solve [eapply vt_sub; eauto with typ]\n                end) using.\n  intros n [IH__expr [IH__list IH__init]];\n    unfold expr_soundness, expr_list_soundness, init_soundness; intros.\n  simpl in *...\n\n  (* Induction on the typing judgment *)\n  eapply t_fld_inv in H as\n      (D & μ__e & μ__f & HT__e & H__fieldType & H__mode) ...\n  destruct (ct D) as [Args Flds Mtds] eqn:H__ct.\n\n  (* Destruct evaluation of e *)\n  destruct_eval H__eval v' σ';\n    lets (Σ0 & v0 & σ0 & H__r & H__mn0 & H__stk0 & H__aty0 & H__st0 & H__wf0 & H__v0) :\n    IH__expr HT__e H0 H1 H3 H__eval; try inverts H__r; try congruence ...\n  eapply eval_implies_evalP_expr in H__eval.\n  lets (?C & ?ω & ?μ & H__obj & ? & H__ot): (proj2 H__st0) v0 ...\n  rewrite H__obj in H5 |- *.\n\n  (* Case analysis *)\n  destruct H__mode as [ ? | [Ω [? [? ?]]]]; subst...\n  + (* hot *)\n    inverts H__ot...\n    lets (v1 & ?D & ?μ & ? & ? & ?): H13 f... rewrite_any.\n    exists Σ0, v1, σ0; splits ...\n  + (* cool Ω *)\n    inversion H12; subst;\n      inverts H__ot.\n    * (* cool Ω *)\n      lets (v1 & ?D & ?μ & ? & ? & ?): H17 f...\n      exists Σ0, v1, σ0; splits ... steps.\n    * (* hot *)\n      lets (v1 & ?D & ?μ & ? & ? & ?): H16 f... rewrite_any.\n      exists Σ0, v1, σ0; splits ...\n    * (* warm *)\n      lets (v1 & ?D & ?μ & ? & ? & ?): H16 f... rewrite_any.\n      exists Σ0, v1, σ0; splits ...\n    * (* cool Ω1 + Ω2 *)\n      lets (v1 & ?D & ?μ & ? & ? & ?): H18 f...\n      exists Σ0, v1, σ0; splits ... steps.\nQed.\n\n\n(* ------------------------------------------------------------------------ *)\n(** ** Soundness of method call *)\n\nLemma soundness_mtd:\n  forall n,\n    (forall e ρ σ ψ r Γ Σ U T,\n        expr_soundness n e ρ σ ψ r Γ Σ U T) /\\\n      (forall el ρ σ ψ r Γ Σ U Tl,\n          expr_list_soundness n el ρ σ ψ r Γ Σ U Tl) /\\\n      (forall C I n1 n2 ρ σ Γ Σ r,\n          init_soundness n C I n1 n2 ρ σ Γ Σ r) ->\n    (forall e m args ρ σ ψ r Γ Σ U T,\n        expr_soundness (S n) (e_mtd e m args) ρ σ ψ r Γ Σ U T).\nProof with (meta; meta_clean; eauto 2 with typ;\n            try match goal with\n                | |- ?Σ ⊨ ?l : ?T => try solve [eapply vt_sub; eauto 4 with typ]\n                end) using.\n  intros n [IH__expr [IH__list IH__init]];\n    unfold expr_soundness, expr_list_soundness, init_soundness; intros.\n  simpl in *...\n\n  (* Induction on the typing judgment *)\n  eapply t_mtd_inv in H as\n      (?C & ?C & ?e__m & ?Args & ?Flds & ?μ__m & ?μ' & ?μ__r &\n         HT__e0 & H__mtdinfo & ? & HT__args & HS__args & H__sub & H__hots) ...\n\n  (* Destruct evaluation of e0 *)\n  destruct_eval H__eval0 v σ';\n    lets (Σ0 & v0 & σ0 & H__r & H__mn0 & H__stk0 & H__aty0 & H__st0 & H__wf0 & H__v0) :\n    IH__expr HT__e0 H0 H1 H3 H__eval0; try inverts H__r; try congruence ...\n  eapply eval_implies_evalP_expr in H__eval0.\n  lets H__pM0: pM_theorem_expr H__eval0.\n  lets (?C & ?ω & ?μ & H__obj & ? & ?): (proj2 H__st0) v0 ...\n  rewrite H__obj in H5 |- *.\n\n  (* Destruct method fetch*)\n  unfold methodInfo in H__mtdinfo.\n  destruct (ct C) as [Args1 Flds1 Mtds1] eqn:H__ct1.\n  destruct (Mtds1 m) as [[?μ__r Ts retT ?] |] eqn:H__Mtds1; [| steps] . inverts H__mtdinfo...\n  eval_dom.\n\n  (* Destruct evaluation of arguments *)\n  lets H__env0: env_typing_monotonicity H__mn0 H0.\n  eval_dom. eval_wf...\n  lets (?T & ?T & ? & ? & ?): H__mn0 ψ ...\n  destruct_eval H__eval1 vl σ';\n    lets (Σ1 & args_val & σ1 & H__r & H__mn1 & H__stk1 & H__aty1 & H__st1 & H__wf1 & H__v1) :\n    IH__list HT__args H__env0 H__st0 H__wf0 H__eval1; try inverts H__r; try congruence ...\n  eapply eval_implies_evalP_list in H__eval1. eval_dom; eval_wf.\n\n  (* Extract typing for method body from Ξ (well-typed) *)\n  pose proof (typable_classes C) as HT__em.\n  rewrite H__ct1 in HT__em.\n  destruct HT__em as [_ HT__em].\n  specialize (HT__em m _ _ _ _ H__Mtds1).\n\n  (* Destruct evaluation of method body *)\n  lets (?T & ?T & ? & ? & ?): H__mn1 ψ...\n  lets (?T & ?T & ? & ? & ?): H__mn1 v0...\n  assert (HT__em': (Args, (C, μ__m)) ⊢ e__m : (C0, μ__r)) by (eapply weakening with (Γ := Flds); eauto with typ).\n  assert (codom args_val ∪ {v0} ⪽ σ1). { ss... eapply wf_theorem_list... }\n  destruct (⟦ e__m ⟧ (σ1, args_val, v0 ,  n)) as [ | | σ' v' ] eqn:H__eval2; try congruence;\n    lets (Σ2 & v2 & σ2 & H__r & H__mn2 & H__stk2 & H__aty2 & H__st2 & H__wf2 & H__v2) :\n    IH__expr HT__em' H__v1 H__st1 H__wf1 H__eval2; try inverts H__r; try congruence ...\n  eapply eval_implies_evalP in H__eval2. subst.\n\n  (* Result *)\n  eval_dom; eval_wf.\n  destruct H__hots as [? | [ H__hots ?] ]...\n\n  - exists Σ2, v2, σ2; splits...\n    all: eauto with typ.\n\n  - (* Local reasoning *)\n    subst; meta.\n    destruct (Local_reasoning_for_typing Σ1 Σ2 σ1 σ2 (codom args_val ∪ { v0 }) {v2} ) as\n      (Σ3 & ? & ? & ? & ? & H__v2); ss => //.\n    + apply scp_theorem_expr with (e:=e__m); eauto with wf lia.\n    + intros l' [l H__l | l H__l]; rch_set; [| exists C]...\n    + lets: H__v2 v2 In_singleton. clear H__v2...\n      lets (?T & ?T & ? &?&?): H13 v2...\n      exists Σ3, v2, σ2; splits ; auto; [ | | | eexists ]; eauto with typ.\nQed.\n\n(* ------------------------------------------------------------------------ *)\n(** ** Soundness of instance creation *)\n\nLemma soundness_new:\n  forall n,\n    (forall e ρ σ ψ r Γ Σ U T,\n        expr_soundness n e ρ σ ψ r Γ Σ U T) /\\\n      (forall el ρ σ ψ r Γ Σ U Tl,\n          expr_list_soundness n el ρ σ ψ r Γ Σ U Tl) /\\\n      (forall C I n1 n2  ρ σ Γ Σ r,\n          init_soundness n C I n1 n2 ρ σ Γ Σ r) ->\n    (forall C args ρ σ ψ r Γ Σ U T,\n        expr_soundness (S n) (e_new C args) ρ σ ψ r Γ Σ U T).\nProof with (meta; meta_clean; eauto 2 with typ;\n            try match goal with\n                | |- ?Σ ⊨ ?l : ?T => try solve [eapply vt_sub; eauto with typ]\n                end) using.\n  intros n [IH__expr [IH__list IH__init]];\n    unfold expr_soundness, expr_list_soundness, init_soundness; intros.\n  simpl in *...\n\n  (* Induction on the typing judgment *)\n  eapply t_new_inv in H as\n      (Args & Flds & Mtds & argsTs & ?μ & ? & H__ct & HT__args & HS__args & H__mode) ...\n\n  (* Destruct evaluation of arguments *)\n  destruct_eval H__eval1 vl σ';\n    lets (Σ1 & args_val & σ1 & H__r & H__mn1 & H__stk1 & H__aty1 & H__st1 & H__wf1 & H__argsval) :\n    IH__list HT__args H0 H1 H3 H__eval1; try inverts H__r; try congruence ...\n  inverts H...\n  eapply eval_implies_evalP_list in H__eval1...\n\n  (* Destruct result of initialization *)\n  remember (Σ1 ++ [(C, cool 0)]) as Σ2.\n  remember (σ1 ++ [(C, [])]) as σ2...\n  assert ((codom args_val ∪ {dom σ1}) ⪽ σ2). {\n    subst; ss; updates... apply ss_trans with σ1; updates...\n    eapply wf_theorem_list... }\n  assert (H__mn2:  Σ1 ≼ Σ2). {\n    subst. intros l0 H__l0.\n    lets [T ?]: getType_Some H__l0. exists T, T; splits...\n    rewrite getType_last2... }\n  lets H__env2: env_typing_monotonicity H__mn2 H__argsval.\n  assert (H__st2: Σ2 ⊨ σ2). { (* could be a lemma *)\n    subst. split; updates...\n    intros l H__l.\n    destruct_eq (l = dom σ1); subst; updates.\n    - rewrite (proj1 H__st1) getType_last.\n      exists C ([]:Env) (cool 0); splits...\n      eapply ot_cool ...\n    - rewrite getObj_last2...\n      rewrite getType_last2...\n      lets (?C & ?ω & ?μ & ? & ? & ?): (proj2 H__st1) l...\n      repeat eexists... }\n  lets H__wf2: wf_add_empty C H__wf1. rewrite -Heqσ2 in H__wf2.\n  lets: getObj_last σ1 C ([]: Env).\n  destruct (init C dom σ1 0 args_val σ2 n) as [ | | σ3] eqn:Heq;\n    try rewrite Heq in H5 |- *; try congruence;\n    specialize (IH__init C (dom σ1) 0 0 args_val σ2 argsTs Σ2);\n  lets (Σ4 & σ4 & H__r & H__mn4 & H__stk4 & H__aty4 & H__st4 & H__wf4):\n     IH__init H__st2 H__wf2 H__ct ; subst; simpl in *...\n  all: try solve [intros; discriminate].\n  all: try solve [rewrite (proj1 H__st1) getType_last; simpl; reflexivity].\n  inverts H__r.\n  eapply init_implies_initP in Heq...\n\n  (* Promotion *)\n  remember ([dom σ1 ↦ (C, warm)] (Σ4)) as Σ5.\n  assert (H__aty4': Σ1 ▷ Σ4). {\n    intros l ? ? H__getType.\n    lets: getType_dom H__getType.\n    assert (l <> dom Σ1) by lia.\n    apply H__aty4...\n    rewrite getType_update_diff...\n    rewrite getType_last2... }\n  assert (H__stk5: Σ1 ≪ [dom σ1 ↦ (C, warm)] (Σ4)). {\n    intros l H__l. updates...\n    assert (l < dom σ1 \\/ l = dom σ1 \\/ dom σ1 <> l) as [ |[|] ] by lia; subst...\n    + left. exists C, (C, warm); updates...\n    + destruct (H__stk4 l); updates...\n      left; exists C0, (C0, μ0); updates...\n  }\n  lets: H__aty4 (dom σ1) C (dom Flds). rewrite getType_update_same in H5...\n  specialize (H5 eq_refl).\n  lets (H__aty5 & H__mn5' & H__stk5' & H__st5) : promotion Σ1 Σ4 (dom σ1) σ4 HeqΣ5...\n\n  (* Case analysis : warm or hot *)\n  destruct H__mode as [H__warm | H__hots].\n  + (* warm *)\n    exists Σ5, (dom σ1), σ4; splits...\n    exists (C, warm); subst; updates...\n\n  + (* hot *)\n    eval_dom. updates...\n    destruct (Local_reasoning_for_typing Σ1 Σ5 σ1 σ4 (codom args_val) {dom σ1} ) as\n      (Σ6 & ? & ? & ? & ? & H__vnew)...\n    * eapply wf_theorem_list...\n    * lets: scp_theorem_init Heq; eauto with scp...\n      apply scp_trans with σ4 (codom args_val ∪ {dom σ1}); ss... {\n        eapply ss_trans with (σ1++[(C,[])]); updates...\n      }\n      ++ apply scp_trans with (σ1 ++ [(C, [])]) (codom args_val ∪ {dom σ1}); updates...\n         intros ? ? l ? H__rch.\n         apply rch_add_empty_set in H__rch as [ [x [ [ ] H__rch]] |]; rch_set...\n         eexists...\n         apply rch_dom2 in H__rch...\n      ++ apply scp_refl2; intros ? [ ]. apply Union_intror, In_singleton.\n    * intros l H__l.\n      eapply P_Hots_env...\n    * exists Σ6, (dom σ1), σ4; splits;\n        eauto 3 with typ.\n      exists (C, hot)...\n      lets (? & ? & ? & ? & ?): H14 (dom σ1); subst...\n      rewrite getType_update_same in H17... inverts H17...\n      lets: H__vnew (dom σ1) In_singleton... inverts H17... inverts H19...\nQed.\n\n(* ------------------------------------------------------------------------ *)\n(** ** Soundness of assignment *)\n\nLemma soundness_asgn:\n  forall n,\n    (forall e ρ σ ψ r Γ Σ U T,\n        expr_soundness n e ρ σ ψ r Γ Σ U T) /\\\n      (forall el ρ σ ψ r Γ Σ U Tl,\n          expr_list_soundness n el ρ σ ψ r Γ Σ U Tl) /\\\n      (forall C I n1 n2 ρ σ Γ Σ r,\n          init_soundness n C I n1 n2 ρ σ Γ Σ r) ->\n    (forall e1 f e2 e' ρ σ ψ r Γ Σ U T,\n        expr_soundness (S n) (e_asgn e1 f e2 e') ρ σ ψ r Γ Σ U T).\nProof with (meta; meta_clean; eauto 2 with typ;\n            try match goal with\n                | |- ?Σ ⊨ ?l : ?T => try solve [eapply vt_sub; eauto with typ]\n                end) using.\n  intros n [IH__expr [IH__list IH__init]];\n    unfold expr_soundness, expr_list_soundness, init_soundness; intros.\n  simpl in *...\n  (* Induction on typing derivation *)\n  eapply t_asgn_inv in H as\n      (D & ? & ? & HT__e1 & HT__e2 & ? & HT__e3) ...\n  eapply t_fld_inv in HT__e1 as\n      (?D & μ__e & μ__f & HT__e1 & H__fieldType & H__mode) ...\n\n  (* Destruct evaluation of e1 *)\n  destruct_eval H__eval1 v' σ';\n    lets (Σ1 & v1 & σ1 & H__r & H__mn1 & H__stk1 & H__aty1 & H__st1 & H__wf1 & H__v1) :\n    IH__expr HT__e1 H0 H1 H3 H__eval1; try inverts H__r; try congruence ...\n  eapply eval_implies_evalP_expr in H__eval1.\n  lets (?C & ?ω & ?μ & H__obj & ? & H__ot): (proj2 H__st1) v1 ...\n\n  (* Destruct evaluation of e2 *)\n  lets (?T & ?T & ? & ? & ?): H__mn1 ψ ...\n  lets H__env1: env_typing_monotonicity H__mn1 H0.\n  eval_dom. eval_wf...\n  destruct_eval H__eval2 v' σ';\n    lets (Σ2 & v2 & σ2 & H__r & H__mn2 & H__stk2 & H__aty2 & H__st2 & H__wf2 & H__v2) :\n    IH__expr HT__e2 H__env1 H__st1 H__wf1 H__eval2; try inverts H__r; try congruence ...\n  eapply eval_implies_evalP_expr in H__eval2. eval_dom; eval_wf.\n  lets (?T & ?T & ? & ? & ?): H__mn2 ψ ...\n\n  (* Destruct assignment *)\n  unfold assign in *.\n  destruct (getObj σ2 v1) as [[?C ?ω] |] eqn:H__getObj.\n\n  + (* Useful assignment *)\n    remember ([v1 ↦ (C, [f ↦ v2] (ω0))] (σ2)) as σ2'. rewrite Heqσ2' in H6.\n    assert (H__st2': Σ2 ⊨ σ2'). {\n      subst. rename v1 into l, v2 into v.\n      lets [?ω [H__obj2 _]]: pM_theorem_expr H__eval2 H__obj.\n      lets (?T & ?T & ? & ? & ?): H__mn2 l...\n      lets [v0 [H__v0 ?]]: cool_selection  l H__st2 H__obj2... {\n        exists (C, μ5)... apply s_typ_mode.\n        destruct H__mode as [|]; flatten; subst...\n        eapply s_mode_trans with (cool Ω)...\n      }\n      eapply storeTyping_assgn...\n    }\n    assert (H__wf2': wf σ2') by (subst; eapply wf_assign; eauto).\n    assert (H__codom' : (codom ρ ∪ {ψ}) ⪽ σ2'). by (subst; ss).\n    destruct (⟦ e' ⟧ (σ2', ρ, ψ ,  n)) as [ | | σ' v' ] eqn:H__eval3; try congruence;\n      lets (Σ3 & v3 & σ3 & H__r & H__mn3 & H__stk3 & H__aty3 & H__st3 & H__wf3 & H__v3) :\n      IH__expr HT__e3 H__st2' H__eval3; try inverts H__r; try congruence ...\n    (* eapply eval_implies_evalp in H__eval3. eval_dom; eval_wf.*)\n    subst.\n    exists Σ3, v3, σ3; subst; splits...\n    all: eauto with typ.\n\n  + (* Useless assignment *)\n    destruct (⟦ e' ⟧ (σ2, ρ, ψ ,  n)) as [ | | σ' v' ] eqn:H__eval3; try congruence;\n      lets (Σ3 & v3 & σ3 & H__r & H__mn3 & H__stk3 & H__aty3 & H__st3 & H__wf3 & H__v3) :\n      IH__expr HT__e3 H__st2 H__wf2 H__eval3; try inverts H__r; try congruence ...\n    eapply eval_implies_evalP_expr in H__eval3. eval_dom; eval_wf.\n    exists Σ3, v3, σ3; splits...\n    all: eauto with typ.\nQed.\n\n(* ------------------------------------------------------------------------ *)\n(** ** Soundness of initialization of a field *)\n\nLemma soundness_init_cons:\n  forall n,\n    (forall e ρ σ ψ r Γ Σ U T,\n        expr_soundness n e ρ σ ψ r Γ Σ U T) /\\\n      (forall el ρ σ ψ r Γ Σ U Tl,\n          expr_list_soundness n el ρ σ ψ r Γ Σ U Tl) /\\\n      (forall C I n1 n2 ρ σ Γ Σ r,\n          init_soundness n C I n1 n2 ρ σ Γ Σ r) ->\n    (forall C I n1 n2 ρ σ Γ Σ r,\n        init_soundness (S n) C I n1 n2 ρ σ Γ Σ r).\nProof with (meta; meta_clean; eauto 2 with typ;\n            try match goal with\n                | |- ?Σ ⊨ ?l : ?T => try solve [eapply vt_sub; eauto with typ]\n                end) using.\n  intros n [IH__expr [IH__list IH__init]];\n    unfold expr_soundness, expr_list_soundness, init_soundness; intros.\n  simpl in *...\n  rewrite H3 in H7.\n\n  (* Retrieve current field *)\n  assert (n2 <= dom Flds). {\n    lets (?C&?ω&?&?&?&?): (proj2 H0) I...\n    lets [? _]: H1 H10.\n    lets: ot_cool_dom H12...\n    lets: H4 H3...\n  }\n  destruct (nth_error Flds n1) as [[T e]|] eqn:?.\n  2:{ (* no fields left*)\n    apply nth_error_None in Heqo.\n    assert (n1 = dom Flds) by lia; subst.\n    assert (n2 = dom Flds) by lia; subst.\n    rewrite Nat.eqb_refl in H8 |- *.\n    exists Σ σ; splits...\n    intros l D Ω ?. destruct_eq (I = l); subst; updates...\n    rewrite getType_update_same in H7... inverts H7...\n  }\n  lets (DoneFlds&LeftFlds&?&?): nth_error_split Heqo; subst.\n\n  (* Extract typing info from the well-typed classes *)\n  pose proof (typable_classes C) as HT__C. rewrite H3 in HT__C.\n  destruct HT__C as [HT__Field _].\n  eapply T_Fields_In in HT__Field. simpl in HT__Field.\n  eapply weakening with (Γ' := Γ) in HT__Field...\n  rename HT__Field into HT__e.\n\n  (* Destruct evaluation of e *)\n  destruct_eval H__eval v' σ';\n    lets (Σ0 & v0 & σ0 & H__r & H__mn0 & H__stk0 & H__aty0 & H__st0 & H__wf0 & H__v0) :\n    IH__expr HT__e H0 H1 H2 H__eval; try inverts H__r; try congruence ...\n  eapply eval_implies_evalP_expr in H__eval.\n  lets: monotonicity_dom H__mn0.\n  lets (? & ? & ? & ? & ?): H__mn0 I...\n  lets (?C & ?ω & ?μ & ? & ? & ?): (proj2 H__st0) I...\n  eval_dom; eval_wf.\n\n  destruct (assign_new I dom DoneFlds v0 σ0) as [σ1 |] eqn:H__assign;\n    [| unfold assign_new in H__assign; steps].\n  lets: wf_assign_new H__assign... {updates... }\n  lets: assign_new_dom H__assign.\n\n  (* Use field initialization lemma *)\n  lets H__env0: env_typing_monotonicity H__mn0 H.\n  clear IH__expr IH__list.\n  lets: H__aty0 I H13.\n  assert (H__field: fieldType C (dom DoneFlds) = Some (C0, μ)). {\n    unfold fieldType. rewrite H3.\n    rewrite nth_error_app2... subst.\n    rewrite -minus_diag_reverse...\n  }\n  cross_rewrites.\n\n  (* Case analysis : is it the updating point ? *)\n  destruct_eq (n2 = dom DoneFlds); subst.\n  - (* Updating point, using the field initialization lemma *)\n    remember ([I ↦ (C, cool (S (dom DoneFlds)))] (Σ0)) as Σ1.\n    lets (H__st1 & H__mn1 & H__stk1): field_initialization I σ0 H__st0 H__field Σ1 ...\n    { lets: ot_cool_dom σ0 H18... }\n\n    (* Use induction hypothesis *)\n    lets: env_typing_monotonicity H__mn1 H__env0.\n    specialize (IH__init\n                  C I (S dom DoneFlds) (S dom DoneFlds) ρ\n                  σ1 Γ Σ1\n                  (init C I (S dom DoneFlds) ρ σ1 n)\n                  Args (DoneFlds++(field (C0,μ) e)::LeftFlds) Mtds).\n    subst; modus.\n    destruct IH__init\n      as (Σ2 & σ2 & H__r & H__mn2 & H__stk2 & H__aty2 & H__st2 & H__wf2)...\n    + apply ss_trans with σ0...\n    + updates...\n    + (* Result *)\n      updates.\n      lets H__initP: H__r.\n      eapply init_implies_initP in H__initP;\n        updates; try rewrite app_assoc_reverse...\n      lets H__scpInit: scp_theorem_init H__initP.\n      lets: scp_theorem_expr H__eval H1...\n      exists Σ2, σ2; splits...\n      * eauto with typ.\n      * eauto with typ.\n      * intros l ?C Ω H__getType.\n        destruct_eq (I = l); subst;\n           eapply H__aty2; updates...\n        rewrite getType_update_same in H__getType...\n\n  - (* Not an updating point, we keep Σ *)\n    lets H__mn1: mn_refl Σ0.\n    lets H__stk1: stk_st_refl Σ0.\n\n    specialize (IH__init C I (S dom DoneFlds) n2 ρ σ1 Γ Σ0\n                  (init C I (S dom DoneFlds) ρ σ1 n)\n                  Args (DoneFlds++(field (C0,μ) e)::LeftFlds) Mtds).\n    destruct IH__init\n      as (Σ2 & σ2 & H__r & H__mn2 & H__stk2 & H__aty2 & H__st2 & H__wf2 )...\n    + (* assign_new *)\n      rewrite /assign_new H4 in H__assign.\n      destruct_if_eqb; inverts H__assign.\n      * lets (?&?&?&?&?&?): (proj2 H__st0) I...\n        inverts H22. lets (?v&?C&?μ&?&?&?): H26 (dom ω)...\n        lets: getVal_dom H16...\n      * remember (dom DoneFlds) as x.\n        assert (x < dom ω). { lets: ot_cool_dom Σ0 σ0 H18... }\n        lets (v__old&?): getVal_Some ω x; auto.\n        lets (?&?&?&?&?&?): (proj2 H__st0) I...\n        inverts H24. lets (?v&?C&?μ&?&?&?): H28 x...\n        split...\n        intros.\n        destruct_eq (l = I); [inverts Heq1|] ...\n        -- rewrite getObj_update_same... repeat eexists...\n           eapply ot_cool... intros.\n           destruct_eq (f = x).\n           ++ inverts Heq1; rewrite getVal_update_same...\n              repeat eexists...\n           ++ rewrite getVal_update_diff...\n        -- rewrite getObj_update_diff...\n           lets (?C&?ω&?): getObj_Some l...\n           lets (?&?&?&?&?&?): (proj2 H__st0) l...\n           repeat eexists...\n    + apply ss_trans with σ0...\n    + (* Result *)\n      updates.\n      lets H__initP: H__r.\n      eapply init_implies_initP in H__initP;\n        updates; try rewrite app_assoc_reverse...\n      lets H__scpInit: scp_theorem_init H__initP.\n      lets: scp_theorem_expr H__eval H1...\n      exists Σ2, σ2; splits...\n      intros l ?C Ω H__getType.\n      destruct_eq (I = l); subst;\n        eapply H__aty2; updates...\n      rewrite getType_update_same in H__getType...\nQed.\n\n\n(* ------------------------------------------------------------------------ *)\n(** ** Final soundness theorem *)\n\nTheorem soundness:\n  forall n,\n    (forall e ρ σ ψ r Γ Σ U T,\n        expr_soundness n e ρ σ ψ r Γ Σ U T) /\\\n    (forall el ρ σ ψ r Γ Σ U Tl,\n      expr_list_soundness n el ρ σ ψ r Γ Σ U Tl) /\\\n    (forall C I n1 n2 ρ σ Γ Σ r,\n       init_soundness n C I n1 n2 ρ σ Γ Σ r).\nProof with (\n    meta;\n    meta_clean;\n    eauto 4 with typ wf lia;\n    try match goal with\n        | |- ?Σ ⊨ ?l : ?T => try solve [eapply vt_sub; eauto with typ]\n        end\n  ).\n  induction n as [n IHn] using lt_wf_ind. destruct n;\n    intros; unfold expr_soundness, expr_list_soundness, init_soundness; splits; intros;\n    [steps | steps | steps | destruct e | destruct el | ]; subst;\n    simpl in *;\n    try specialize (IHn n ltac:(lia)) as [IH__expr [IH__list IH__init]]...\n\n  - (* e = var x *)\n    eapply env_regularity in H as (?l & ?H__get & ?)...\n    rewrite H__get in H6 |- * ...\n    exists Σ, l, σ; steps...\n\n  - (* e = this *)\n    eapply t_this_inv in H.\n    exists Σ, ψ, σ; steps...\n\n  - eapply soundness_fld...\n\n  - eapply soundness_mtd...\n\n  - eapply soundness_new...\n\n  - eapply soundness_asgn...\n\n  - (* el = nil *)\n    inverts H.\n    exists Σ, ([]: list Loc), σ; splits...\n    apply et_nil.\n\n  - (* el = e::el *)\n    inverts H ...\n\n    (* Destruct evaluation of head *)\n    destruct_eval H__eval v' σ';\n      lets (Σ0 & v & σ0 & H__r & H__mn0 & H__stk0 & H__aty0 & H__st0 & H__wf0 & H__v0) :\n      IH__expr H14 H0 H1 H3 H__eval; try inverts H__r; try congruence ...\n    eapply eval_implies_evalP_expr in H__eval. eval_dom.\n\n    (* Destruct evaluation of tail *)\n    lets (?T & ?T & ? & ? & ?): H__mn0 ψ...\n    lets H__env0: env_typing_monotonicity H__mn0 H0.\n    destruct (⟦_ el _⟧ (σ0, ρ, ψ, n)) as [ | | σ' vl' ] eqn:H__eval1; try congruence;\n    lets (Σ1 & vl & σ1 & H__r & H__mn1 & H__stk1 & H__aty1 & H__st1 & H__wf1 & H__v1):\n      IH__list H12 H__env0 H__st0 H__wf0 H__eval1; try inverts H__r; try congruence ...\n\n    (* Result *)\n    exists Σ1, (v::vl), σ1; splits...\n    lets (?T & ?T & ? & ? & ?): H__mn1 v ...\n    apply et_cons...\n\n  - (* init_cons *)\n    eapply soundness_init_cons...\nQed.\n\n\n(* ------------------------------------------------------------------------ *)\n(** ** Soundness corollaries *)\n\nTheorem Soundness :\n  forall n e ρ σ ψ r Γ Σ Tthis T,\n    ⟦e⟧(σ, ρ, ψ, n) = r ->\n    r <> Timeout ->\n    Σ ⊨ σ ->\n    (Σ ⊨ ρ : Γ) ->\n    (Σ ⊨ ψ : Tthis) ->\n    ((Γ, Tthis) ⊢ e : T) ->\n    wf σ ->\n    (codom ρ ∪ {ψ} ⪽ σ) ->\n    exists Σ' v σ',\n      r = Success v σ' /\\\n        (Σ' ⊨ σ') /\\\n        (Σ' ⊨ v : T) /\\\n        Σ ≼ Σ' /\\\n        Σ ▷ Σ' /\\\n        Σ ≪ Σ'.\nProof with (eauto with typ).\n  intros.\n  lets [(Σ'& v& σ'& ?) _]: soundness n... steps.\n  exists Σ', v, σ'; splits...\nQed.\n\nCorollary Program_soundness :\n  T_Prog ->\n  forall n, eval_prog n <> Error.\nProof with (meta; eauto 2 with typ).\n  unfold eval_prog, T_Prog.\n  lets H__ct: EntryClass_ct. rewrite H__ct.\n  destruct EntryClass.\n  steps...\n  specialize (H1 Entry). steps.\n  specialize (H2 main hot [] (c,m) e matched).\n  lets: Soundness [(Entry, hot)] H0 H2; eauto with typ; steps.\n  + split; steps.\n    ct_lookup Entry.\n    assert (l = 0) by lia; steps.\n    exists Entry, ([]: Env), hot; steps.\n    eapply ot_hot...\n    simpl; intros; lia.\n  + eapply vt_sub; steps.\n  + lets (? & ? & ?): H1; steps...\n    intros l C ω ?H.\n    lets: getObj_dom H3; simpl in *.\n    assert (l=0) by lia; steps.\n    lets: getVal_dom H6; simpl in *; try lia...\nQed.\n", "meta": {"author": "clementblaudeau", "repo": "celsius", "sha": "33a7f479025f94551b6c7a96807f05469dcae595", "save_path": "github-repos/coq/clementblaudeau-celsius", "path": "github-repos/coq/clementblaudeau-celsius/celsius-33a7f479025f94551b6c7a96807f05469dcae595/src/Soundness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2559782363036992}}
{"text": "Require Export low_mods.\nRequire Import Rep_Pred_FOv.\n\nLemma Pred_in_SO_rep_pred : forall (alpha cond : SecOrder) (x : FOvariable)\n                              (P P2 : predicate),\n  FO_frame_condition cond = true ->\n    Pred_in_SO (replace_pred alpha P x cond) P2 ->\n      Pred_in_SO alpha P2.\nProof.\n  intros alpha cond x P P2 Hunary HPocc.\n  unfold Pred_in_SO in *.\n  induction alpha; try (    apply IHalpha; auto); try auto;\n    try (    simpl in *; apply in_app_or in HPocc;\n    apply in_or_app; firstorder).\n\n  simpl in *. destruct (predicate_dec P p).\n    subst. rewrite preds_in_rep_FOv in HPocc.\n    rewrite FO_frame_condition_preds_in in HPocc.\n    firstorder.  auto.\n    simpl in *. auto. \n\n    simpl in *. destruct (predicate_dec P p) as [H1 | H1].\n    subst. right. firstorder.\n    simpl in HPocc. destruct HPocc. auto.\n    right. apply IHalpha. auto.\n\n    simpl in *. destruct (predicate_dec P p) as [H1 | H1].\n    subst. right. firstorder.\n    simpl in HPocc. destruct HPocc. auto.\n    right. apply IHalpha. auto.\nQed.\n\nLemma Pred_in_SO_rep_pred_f : forall (alpha cond : SecOrder) (x : FOvariable)\n                                    (Q : predicate),\n  FO_frame_condition cond = true ->\n   ~ Pred_in_SO (replace_pred alpha Q x cond) Q.\nProof.\n  intros alpha cond x Q Hcond.\n  induction alpha; intros H; try contradiction.\n\n  simpl in *. destruct (predicate_dec Q p) as [H1 | H1].\n  subst. apply Pred_in_SO_FO_frame_condition in H. contradiction.\n  apply rep_FOv_FO_frame_condition. auto.\n  inversion H as [H2 | H2]; subst; contradiction.\n\n  rewrite rep_pred_conjSO in H.\n  apply Pred_in_SO_conjSO in H.\n  destruct H; contradiction.\n\n  rewrite rep_pred_disjSO in H.\n  apply Pred_in_SO_conjSO in H.\n  destruct H; contradiction.\n\n  rewrite rep_pred_implSO in H.\n  apply Pred_in_SO_conjSO in H.\n  destruct H; contradiction.\n\n  simpl in *. destruct (predicate_dec Q p) as [H1 | H1].\n  subst. contradiction. inversion H as [H2 | H2].\n  subst. contradiction.\n  apply In_preds_in_rep_pred in H2.\n  eapply Pred_in_SO_FO_frame_condition in H2. contradiction.\n  auto.\n\n  simpl in *. destruct (predicate_dec Q p) as [H1 | H1].\n  subst. contradiction. inversion H as [H2 | H2].\n  subst. contradiction.\n  apply In_preds_in_rep_pred in H2.\n  eapply Pred_in_SO_FO_frame_condition in H2. contradiction.\n  auto.\nQed.", "meta": {"author": "caitlindabrera", "repo": "Sahlqvist", "sha": "d0a755fb663a6cabc0babb691564cdf575fc8b36", "save_path": "github-repos/coq/caitlindabrera-Sahlqvist", "path": "github-repos/coq/caitlindabrera-Sahlqvist/Sahlqvist-d0a755fb663a6cabc0babb691564cdf575fc8b36/vsSahlq/coq_code/Pred_in_SO_rep_pred.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.255978229447095}}
{"text": "Require Import Coq.Arith.Arith.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Strings.String.\n\n(* Import functions from framework. *)\nRequire Import Hapsl.Ascii.Class.\nRequire Import Hapsl.Bool.Bool.\nRequire Import Hapsl.Checkers.Types.\nRequire Import Hapsl.Nat.Notations.\nRequire Import Hapsl.String.Distance.\nRequire Import Hapsl.String.Transform.\nRequire Import Hapsl.String.Palindrome.\nRequire Import Hapsl.String.Equality.\nRequire Import Hapsl.String.Search.\nRequire Import Hapsl.String.Sequence.\n\nLocal Open Scope string_scope.\n\n(* Import required notations. *)\nImport StringEqualityNotations.\nImport NatNotations.\n\n(* Utility function to deal with old passwords that might not exist. *)\nDefinition old_is_undefined (pt : PasswordTransition) : bool :=\n  match pt with\n  | PwdTransition old new =>\n    match old with\n    | None => true\n    | Some str => false\n    end\n  end.\n\n(* Extracts the new password from a password transition. *)\nDefinition new_pwd (pt : PasswordTransition) : Password :=\n  match pt with\n  | PwdTransition old new => new\n  end.\n\n(* Notations for checkers. *)\nModule CheckerNotations.\n\n  (* A check being disabled is the same as no error message. *)\n  Notation DISABLE_CHECK := None.\n\n  (* A 'good password' result is the same as no error message. *)\n  Notation GOODPWD := None.\n\n  (* A 'bad password' result is the same as some error message. *)\n  Notation \"BADPWD: msg\" := (Some msg) (at level 80).\n\n  (* Needs syntax to enable a check only when we have an old password. *)\n  Notation \"'NEEDS' old_pwd 'FROM' pt statement\" :=\n    (let old_pwd := (fun (pt : PasswordTransition) =>\n                     match pt with\n                       PwdTransition old new =>\n                       match old with\n                       | None => \"\"\n                       | Some str => str\n                       end\n                     end) in\n    if old_is_undefined pt then\n      DISABLE_CHECK\n    else\n      statement) (at level 80).\n  \nEnd CheckerNotations.\n\nImport CheckerNotations.\n\n(* Some Basic Checkers *)\n\n(* The new password must be different from old password *)\nDefinition diff_from_old_pwd (pt : PasswordTransition) : CheckerResult :=\n  NEEDS old_pwd FROM pt\n        if old_pwd(pt) ==_s new_pwd(pt) then\n          BADPWD: \"The new password is the same as the old password\"\n        else\n          GOODPWD.\n\n(* Prove that diff_from_old_password gives an error when old and new passwords are identical. *)\nTheorem diff_from_old_pwd_correct : forall (old new : string),\n    old = new -> diff_from_old_pwd (PwdTransition (Some old) new) <> None.\nProof.\n  intros.\n  unfold diff_from_old_pwd.\n  simpl.\n  rewrite H.\n  rewrite beq_string_reflexive.\n  congruence.\nQed.\n\n(* The new password must not be a prefix of the old password (and vice-versa). *)\nDefinition prefix_of_old_pwd (pt : PasswordTransition) : CheckerResult :=\n  NEEDS old_pwd FROM pt\n        if prefix (old_pwd pt) (new_pwd pt) || prefix (new_pwd pt) (old_pwd pt) then\n          BADPWD: \"The new password is a prefix of the old password\"\n        else\n          GOODPWD.\n\n(* Prove that prefix_of_old_password gives an error when new password is prefix of the old one. *)\nDefinition prefix_of_old_pwd_correct : forall (old: string) (new : string),\n    (prefix old new) = true \\/ (prefix new old) = true ->\n    prefix_of_old_pwd (PwdTransition (Some old) new) <> None.\nProof.\n  intros.\n  decompose [or] H.\n  + unfold prefix_of_old_pwd.\n    simpl.\n    rewrite H0.\n    rewrite orb_true_l.\n    congruence.\n  + unfold prefix_of_old_pwd.\n    simpl.\n    rewrite H0.\n    rewrite orb_true_r.\n    congruence.\nQed.\n\n(* The new password must not be a palindrome *)\nDefinition not_palindrome (pt : PasswordTransition) : CheckerResult :=\n  if palindrome (string_to_lower (new_pwd pt)) then\n    BADPWD: \"The new password is a palindrome.\"\n  else\n    GOODPWD.\n\n(* Prove that not_palindrome gives an error when the new password is a palindrome. *)\nTheorem not_palindrome_correct : forall (pt : PasswordTransition),\n    palindrome (string_to_lower (new_pwd pt)) = true -> not_palindrome pt <> None.\nProof.\n  intros.\n  unfold not_palindrome.\n  rewrite H.\n  congruence.\nQed.\n    \n(* The new password must not be a rotated version of the old password. *)\nDefinition not_rotated (pt : PasswordTransition) : CheckerResult :=\n  NEEDS old_pwd FROM pt\n        if string_is_rotated (string_to_lower (old_pwd pt)) (string_to_lower (new_pwd pt)) then\n\t  BADPWD: \"The new password is a rotated version of the old password.\"\n\telse\n\t  GOODPWD.\n\n(* Prove that not_rotated gives an error when the new password is a rotated version of the old. *)\nTheorem not_rotated_correct : forall (old new : string),\n    string_is_rotated (string_to_lower old) (string_to_lower new) = true ->\n    not_rotated (PwdTransition (Some old) new) <> None.\nProof.\n  intros.\n  unfold not_rotated.\n  simpl.\n  rewrite H.\n  congruence.\nQed.\n\n(* The new password must not just contain case changes in relation to the old password. *)\nDefinition not_case_changes_only (pt : PasswordTransition) : CheckerResult :=\n  NEEDS old_pwd FROM pt\n        if (string_to_lower (old_pwd pt)) ==_s (string_to_lower (new_pwd pt)) then\n          BADPWD: \"The new password contains case changes only compared to the old password.\"\n        else\n          GOODPWD.\n\n(* Prove that not_case_changes_only gives an error when old and new passwords differ in case. *)\nTheorem not_case_changes_only_correct : forall (old new : string),\n    (string_to_lower old) = (string_to_lower new) ->\n    not_case_changes_only (PwdTransition (Some old) new) <> None.\nProof.\n  intros.\n  unfold not_case_changes_only.\n  simpl.\n  rewrite <- H.\n  rewrite beq_string_reflexive.\n  congruence.\nQed.\n\n(* The new password must have a certain Levenshtein distance from the old password. *)\nDefinition levenshtein_distance_gt (dist : nat) (pt : PasswordTransition) : CheckerResult :=\n  NEEDS old_pwd FROM pt\n        let old := string_to_lower (old_pwd pt) in\n        let new := string_to_lower (new_pwd pt) in\n        if levenshtein_distance old new <=? dist then\n          BADPWD: \"The new password is too similar to the old password.\"\n        else\n          GOODPWD.\n\n(* Prove that levenshtein_distance_gt gives an error for passwords that are too similar. *)\nTheorem levenshtein_distance_gt_correct : forall (dist : nat) (old new : string),\n    levenshtein_distance (string_to_lower old) (string_to_lower (new)) <=? dist = true ->\n    levenshtein_distance_gt dist (PwdTransition (Some old) new) <> None.\nProof.\n  intros.\n  unfold levenshtein_distance_gt.\n  simpl.\n  rewrite H.\n  congruence.\nQed.\n\n(* The new password must be long enough, taking into account number of character classes. *)\nDefinition credits_length_check (len : nat) (pt : PasswordTransition) : CheckerResult :=\n  if length (new_pwd pt) >=? (len - string_count_character_classes (new_pwd pt)) then\n    GOODPWD\n  else\n    BADPWD: \"The new password is too short.\".\n\nDefinition credits_length_check_correct : forall (len : nat) (old new : string),\n    length new >=? (len - string_count_character_classes new) = false ->\n    credits_length_check len (PwdTransition (Some old) new) <> None.\nProof.\n  intros.\n  unfold credits_length_check.\n  simpl.\n  rewrite H.\n  congruence.\nQed.\n\n(* The new password must be long enough. *)\nDefinition plain_length_check (len : nat) (pt : PasswordTransition) : CheckerResult :=\n  if length (new_pwd pt) >=? len then\n    GOODPWD\n  else\n    BADPWD: \"The new password is too short.\".\n\n(* Prove that plain_length_check is correct for all lengths and password transitions. *)\nTheorem plain_length_check_correct : forall (len : nat) (pt : PasswordTransition),\n  plain_length_check len pt = GOODPWD <-> length (new_pwd pt) >=? len = true.\nProof.\n  intros.\n  split.\n  + unfold plain_length_check.\n    destruct (length (new_pwd pt) >=? len).\n    (* Case 1: Premise is false. *)\n    - simpl. congruence.\n    (* Case 2: Trivial. *)\n    - simpl. congruence.\n  + unfold plain_length_check.\n    destruct (length (new_pwd pt) <=? len).\n    - unfold is_true. intros. rewrite H. reflexivity.\n    - unfold is_true. intros. rewrite H. reflexivity.\nQed.\n\n(* The new password must not contain more than a certain number of characters of the same class in\n   a row. *)\nDefinition max_class_repeat (m : nat) (pt : PasswordTransition) : CheckerResult :=\n  if m <=? (sequence_of (new_pwd pt) is_same_class 0) then\n    GOODPWD\n  else\n    BADPWD: \"The new password contains too many of the same character class in a row\".\n\n(* Prove that max_class_repeat gives an error appropriately. *)\nTheorem max_class_repeat_correct : forall (m : nat) (pt : PasswordTransition),\n    m <=? (sequence_of (new_pwd pt) is_same_class 0) = false -> max_class_repeat m pt <> None.\nProof.\n  intros.\n  unfold max_class_repeat.\n  simpl.\n  rewrite H.\n  congruence.\nQed. \n\n(* Some proofs on the behaviour of checkers (not the functional logic). *)\n\n(* Returns true if the old password is undefined (none) otherwise returns false. *)\nDefinition old_pwd_is_undefined (pt : PasswordTransition): bool :=\n  match pt with\n  | PwdTransition old _ =>\n    match old with\n    | None => true\n    | Some _ => false\n    end\n  end.\n\n\n(* If the old password is undefined, then the checker prefix_of_old_pwd \n   accepts any password (i.e. the prefix check is essentially disabled). *)\nLemma prefix_old_pwd_undefined: forall (pt: PasswordTransition),\n    old_pwd_is_undefined(pt) = true -> prefix_of_old_pwd(pt) = GOODPWD.\nProof.\n  intros.\n  unfold old_pwd_is_undefined in H. \n  (* Case analysis. *)\n  destruct pt. destruct o.\n   (* Case 1 (trivial): old password is defined. *)\n   - congruence.\n   (* Case 2: old password is undefined. *)\n   - unfold prefix_of_old_pwd. simpl. auto.\nQed.", "meta": {"author": "sr-lab", "repo": "verified-pam-cracklib", "sha": "f2fe95c54c1085a9577490f06a22e797c3697375", "save_path": "github-repos/coq/sr-lab-verified-pam-cracklib", "path": "github-repos/coq/sr-lab-verified-pam-cracklib/verified-pam-cracklib-f2fe95c54c1085a9577490f06a22e797c3697375/src/Checkers/Basic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.255978229447095}}
{"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_mmio_emulation_spec (rec: Pointer) (adt: RData) : option (RData * Z) :=\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 is_emul := (rec_run (priv adt)) @ 13 in\n    let read_val := ((rec_run (priv adt)) @ 14) in\n    rely is_int64 is_emul; rely is_int64 read_val;\n    if is_emul =? 0 then\n      Some (adt, 1)\n    else\n      let esr := g_esr (grec gn) in\n      let rt := __esr_srt esr in\n      let mask := __access_mask esr in\n      rely is_int64 esr; rely is_int rt; rely is_int64 mask;\n      if (negb (Z.land esr ESR_EL2_EC_MASK =? ESR_EL2_EC_DATA_ABORT) ||\n            (Z.land esr ESR_EL2_ABORT_ISV_BIT =? 0))\n      then\n        Some (adt, 0)\n      else\n        rely is_int64 (g_pc (grec gn)); rely is_int64 (g_pc (grec gn) + 4);\n        if (negb (__esr_is_write esr)) && (negb (rt =? 31)) then\n          let val := Z.land read_val mask in\n          let extend := __esr_sign_extend esr in\n          rely is_int extend;\n          if extend =? 0 then\n            let g' := gn {grec: (grec gn) {g_regs: set_reg rt val (g_regs (grec gn))} {g_pc: (g_pc (grec gn)) + 4}} in\n            Some (adt {share: (share adt) {gs: (gs (share adt)) # gidx == g'}}, 1)\n          else\n            let len := __access_len esr in\n            rely is_int len;\n            let bitcount := len * 8 in\n            rely is_int bitcount; rely is_int (bitcount - 1);\n            let mask := Z.shiftl 1 (bitcount - 1) in\n            rely is_int64 mask; rely is_int64 (Z.lxor val mask);\n            let val := (Z.lxor val mask) - mask in\n            rely is_int64 val;\n            if __esr_sixty_four esr then\n              let g' := gn {grec: (grec gn) {g_regs: set_reg rt val (g_regs (grec gn))} {g_pc: (g_pc (grec gn)) + 4}} in\n              Some (adt {share: (share adt) {gs: (gs (share adt)) # gidx == g'}}, 1)\n            else\n              let val := Z.land val 4294967295 in\n              let g' := gn {grec: (grec gn) {g_regs: set_reg rt val (g_regs (grec gn))} {g_pc: (g_pc (grec gn)) + 4}} in\n              Some (adt {share: (share adt) {gs: (gs (share adt)) # gidx == g'}}, 1)\n        else\n          let g' := gn {grec: (grec gn)  {g_pc: (g_pc (grec gn)) + 4}} in\n          Some (adt {share: (share adt) {gs: (gs (share adt)) # gidx == g'}}, 1).\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_mmio_emulation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.25589979671206836}}
{"text": "From Coq Require Export Reals Psatz.\nFrom iris.proofmode Require Import base proofmode classes.\nFrom iris.base_logic.lib Require Export fancy_updates.\nFrom iris.algebra Require Import big_op.\nFrom iris.bi Require Export weakestpre fixpoint big_op.\nFrom iris.prelude Require Import options.\n\nFrom self.prelude Require Import stdpp_ext.\nFrom self.prob Require Export couplings distribution.\nFrom self.program_logic Require Export language exec.\n\nImport uPred.\n\nLocal Open Scope R.\n\n(** [irisGS] specifies the interface for the resource algebras implementing the\n    [state] and [cfg] of a [language] [Λ]. For the purposes of defining the\n    weakest precondition, we only need [irisGS] to give meaning to invariants,\n    and provide predicates describing valid states via [state_interp] and valid\n    specification configurations via [spec_interp]. *)\nClass irisGS (Λ : language) (Σ : gFunctors) := IrisG {\n  iris_invGS :> invGS_gen HasNoLc Σ;\n  state_interp : state Λ → iProp Σ;\n  spec_interp : cfg Λ → iProp Σ;\n}.\nGlobal Opaque iris_invGS.\nGlobal Arguments IrisG {Λ Σ}.\n\n(* TODO: upstream? *)\nLemma least_fixpoint_ne_outer {PROP : bi} {A : ofe}\n    (F1 : (A → PROP) → (A → PROP)) (F2 : (A → PROP) → (A → PROP)) n :\n  (∀ Φ x, F1 Φ x ≡{n}≡ F2 Φ x) → ∀ x1 x2,\n  x1 ≡{n}≡ x2 → bi_least_fixpoint F1 x1 ≡{n}≡ bi_least_fixpoint F2 x2.\nProof.\n  intros HF x1 x2 Hx. rewrite /bi_least_fixpoint /=.\n  do 3 f_equiv; last solve_proper. repeat f_equiv. apply HF.\nQed.\n\n(** * The coupling modality [exec_coupl]  *)\nSection exec_coupl.\n  Context `{!irisGS Λ Σ}.\n\n  Definition exec_coupl_pre (Z : cfg Λ → cfg Λ → iProp Σ) (Φ : cfg Λ * cfg Λ → iProp Σ) :=\n    (λ (x : cfg Λ * cfg Λ),\n      let '((e1, σ1), (e1', σ1')) := x in\n      (* [prim_step] on both sides *)\n      (∃ R, ⌜reducible e1 σ1⌝ ∗\n            ⌜Rcoupl (prim_step e1 σ1) (prim_step e1' σ1') R⌝ ∗\n            ∀ ρ2 ρ2', ⌜R ρ2 ρ2'⌝ ={∅}=∗ Z ρ2 ρ2') ∨\n      (* [prim_step] only on the left *)\n      (∃ R, ⌜reducible e1 σ1⌝ ∗\n            ⌜Rcoupl (prim_step e1 σ1) (dret (e1', σ1')) R⌝ ∗\n            ∀ ρ2, ⌜R ρ2 (e1', σ1')⌝ ={∅}=∗ Z ρ2 (e1', σ1')) ∨\n      (* an arbitrary amount of [prim_step]s on the right *)\n      (∃ R n, ⌜Rcoupl (dret (e1, σ1)) (exec n (e1', σ1')) R⌝ ∗\n            ∀ e2' σ2', ⌜R (e1, σ1) (e2', σ2')⌝ ={∅}=∗ Φ ((e1, σ1), (e2', σ2'))) ∨\n      (* [prim_step] on the left, [state_step] on the right *)\n      ([∨ list] α' ∈ get_active σ1',\n        (∃ R, ⌜reducible e1 σ1⌝ ∗\n              ⌜Rcoupl (prim_step e1 σ1) (state_step σ1' α')  R⌝ ∗\n              ∀ e2 σ2 σ2', ⌜R (e2, σ2) σ2'⌝ ={∅}=∗ Z (e2, σ2) (e1', σ2'))) ∨\n      (* [state_step] on the left, a [prim_step] on the right *)\n      ([∨ list] α ∈ get_active σ1,\n        (∃ R, ⌜Rcoupl (state_step σ1 α) (prim_step e1' σ1') R⌝ ∗\n              ∀ σ2 e2' σ2', ⌜R σ2 (e2', σ2')⌝ ={∅}=∗ Φ ((e1, σ2), (e2', σ2')))) ∨\n      (* [state_step] on both sides - a case for all combinations of 'active' indicies on both sides *)\n      ([∨ list] αs ∈ list_prod (get_active σ1) (get_active σ1'),\n        (∃ R, ⌜Rcoupl (state_step σ1 αs.1) (state_step σ1' αs.2) R⌝ ∗\n              (∀ σ2 σ2', ⌜R σ2 σ2'⌝ ={∅}=∗ Φ ((e1, σ2), (e1', σ2')))))\n    )%I.\n\n  Local Instance exec_state_coupl_pre_NonExpansive Z Φ :\n    NonExpansive (exec_coupl_pre Z Φ).\n  Proof.\n    rewrite /exec_coupl_pre.\n    intros n ((?&?)&(?&?)) ((?&?)&(?&?)) [[[=] [=]] [[=] [=]]].\n    by simplify_eq.\n  Qed.\n\n  Local Instance exec_coupl_pre_mono Z : BiMonoPred (exec_coupl_pre Z).\n  Proof.\n    split; [|apply _].\n    iIntros (Φ Ψ HNEΦ HNEΨ) \"#Hwand\".\n    rewrite /exec_coupl_pre.\n    iIntros (((e1 & σ1) & (e1' & σ1'))) \"Hexec\".\n    iDestruct \"Hexec\" as \"[H | [H | [(% & % & % & HZ) | [Hl | [Hl | Hl]]]]]\".\n    - by iLeft.\n    - by iRight; iLeft.\n    - iRight; iRight; iLeft.\n      iExists _, _. iSplit; [done|].\n      iIntros. iApply \"Hwand\". by iApply \"HZ\".\n    - iRight; iRight; iRight; iLeft.\n      iInduction (get_active σ1') as [| l] \"IH\" forall \"Hl\".\n      { rewrite big_orL_nil //. }\n      rewrite !big_orL_cons.\n      iDestruct \"Hl\" as \"[(% & % & % & HZ) | H]\".\n      + iLeft. iExists _. do 2 (iSplit; [done|]).\n        iIntros. by iApply \"HZ\".\n      + iRight. by iApply \"IH\".\n    - iRight; iRight; iRight; iRight; iLeft.\n      iInduction (get_active σ1) as [| l] \"IH\" forall \"Hl\".\n      { rewrite big_orL_nil //. }\n      rewrite !big_orL_cons.\n      iDestruct \"Hl\" as \"[(% & % & HZ) | H]\".\n      + iLeft. iExists _. iSplit; [done|].\n        iIntros. iApply \"Hwand\". by iApply \"HZ\".\n      + iRight. by iApply \"IH\".\n    - iRight; iRight; iRight; iRight; iRight.\n      iInduction (list_prod (get_active σ1) (get_active σ1')) as [| l] \"IH\" forall \"Hl\".\n      { rewrite big_orL_nil //. }\n      rewrite !big_orL_cons.\n      iDestruct \"Hl\" as \"[(% & % & HZ) | H]\".\n      + iLeft. iExists _. iSplit; [done|].\n        iIntros. iApply \"Hwand\". by iApply \"HZ\".\n      + iRight. by iApply \"IH\".\n  Qed.\n\n  Definition exec_coupl' Z := bi_least_fixpoint (exec_coupl_pre Z).\n  Definition exec_coupl e σ e' σ' Z := exec_coupl' Z ((e, σ), (e', σ')).\n\n  Lemma exec_coupl_unfold e1 σ1 e1' σ1' Z :\n    exec_coupl e1 σ1 e1' σ1' Z ≡\n      ((∃ R, ⌜reducible e1 σ1⌝ ∗\n            ⌜Rcoupl (prim_step e1 σ1) (prim_step e1' σ1') R⌝ ∗\n            ∀ ρ2 ρ2', ⌜R ρ2 ρ2'⌝ ={∅}=∗ Z ρ2 ρ2') ∨\n      (∃ R, ⌜reducible e1 σ1⌝ ∗\n            ⌜Rcoupl (prim_step e1 σ1) (dret (e1', σ1')) R⌝ ∗\n            ∀ ρ2, ⌜R ρ2 (e1', σ1')⌝ ={∅}=∗ Z ρ2 (e1', σ1')) ∨\n      (∃ R n, ⌜Rcoupl (dret (e1, σ1)) (exec n (e1', σ1')) R⌝ ∗\n              ∀ e2' σ2', ⌜R (e1, σ1) (e2', σ2')⌝ ={∅}=∗ exec_coupl e1 σ1 e2' σ2' Z) ∨\n      ([∨ list] α' ∈ get_active σ1',\n        (∃ R, ⌜reducible e1 σ1⌝ ∗\n              ⌜Rcoupl (prim_step e1 σ1) (state_step σ1' α')  R⌝ ∗\n              ∀ e2 σ2 σ2', ⌜R (e2, σ2) σ2'⌝ ={∅}=∗ Z (e2, σ2) (e1', σ2'))) ∨\n      ([∨ list] α ∈ get_active σ1,\n        (∃ R, ⌜Rcoupl (state_step σ1 α) (prim_step e1' σ1') R⌝ ∗\n              ∀ σ2 e2' σ2', ⌜R σ2 (e2', σ2')⌝ ={∅}=∗ exec_coupl e1 σ2 e2' σ2' Z)) ∨\n      ([∨ list] αs ∈ list_prod (get_active σ1) (get_active σ1'),\n        (∃ R, ⌜Rcoupl (state_step σ1 αs.1) (state_step σ1' αs.2) R⌝ ∗\n              (∀ σ2 σ2', ⌜R σ2 σ2'⌝ ={∅}=∗ exec_coupl e1 σ2 e1' σ2' Z))))%I.\n  Proof. rewrite /exec_coupl/exec_coupl' least_fixpoint_unfold //. Qed.\n\n  Local Definition cfgO := (prodO (exprO Λ) (stateO Λ)).\n\n  Lemma exec_coupl_strong_mono e1 σ1 e1' σ1' (Z1 Z2 : cfg Λ → cfg Λ → iProp Σ) :\n    (∀ e2 σ2 ρ', (⌜∃ σ, prim_step e1 σ (e2, σ2) > 0⌝ ∗ Z1 (e2, σ2) ρ' -∗ Z2 (e2, σ2) ρ')) -∗\n    exec_coupl e1 σ1 e1' σ1' Z1 -∗ exec_coupl e1 σ1 e1' σ1' Z2.\n  Proof.\n    iIntros \"HZ Hcpl\". iRevert \"HZ\".\n    rewrite /exec_coupl /exec_coupl'.\n    set (Φ := (λ x,\n      (∀ e2 σ2 ρ', ⌜∃ σ, prim_step x.1.1 σ (e2, σ2) > 0⌝ ∗ Z1 (e2, σ2) ρ' -∗ Z2 (e2, σ2) ρ') -∗\n                  (bi_least_fixpoint (exec_coupl_pre Z2) x ))%I : prodO cfgO cfgO → iPropI Σ).\n    assert (NonExpansive Φ).\n    { intros n ((?&?)&(?&?)) ((?&?)&(?&?)) [[[=] [=]] [[=] [=]]]. by simplify_eq. }\n    iPoseProof (least_fixpoint_iter (exec_coupl_pre Z1) Φ with \"[]\") as \"H\"; last first.\n    { iIntros \"HZ\". by iApply (\"H\" with \"Hcpl\"). }\n    iIntros \"!#\" ([[? σ] [? σ']]). rewrite /exec_coupl_pre.\n    iIntros \"[(% & % & % & H) | [(% & % & % & H) | [(% & % & % & H) | [H | [H | H]]]]] HZ\".\n    - rewrite least_fixpoint_unfold.\n      iLeft. iExists _.\n      iSplit; [done|].\n      iSplit.\n      { iPureIntro. by apply Rcoupl_pos_R. }\n      iIntros ([] [] (?&?&?)). iMod (\"H\" with \"[//]\").\n      iModIntro. iApply \"HZ\". eauto.\n    - rewrite least_fixpoint_unfold.\n      iRight. iLeft. iExists _.\n      iSplit; [done|].\n      iSplit.\n      { iPureIntro. by apply Rcoupl_pos_R. }\n      iIntros ([] (?&?&?)). iMod (\"H\" with \"[//]\").\n      iModIntro. iApply \"HZ\". eauto.\n    - rewrite least_fixpoint_unfold.\n      iRight. iRight. iLeft. iExists _, _.\n      iSplit; [done|]. iIntros.\n      by iApply (\"H\" with \"[//]\").\n    - rewrite least_fixpoint_unfold.\n      iRight; iRight; iRight; iLeft.\n      iInduction (get_active σ') as [| l] \"IH\".\n      { rewrite big_orL_nil //. }\n      rewrite 2!big_orL_cons.\n      iDestruct \"H\" as \"[(% & % & % & H) | Ht]\".\n      + iLeft. iExists _. iSplit; [done|].\n        iSplit.\n        { iPureIntro. by apply Rcoupl_pos_R. }\n        iIntros (??? (?&?&?)). iMod (\"H\" with \"[//]\").\n        iModIntro. iApply \"HZ\". eauto.\n      + iRight. by iApply (\"IH\" with \"Ht\").\n    - rewrite least_fixpoint_unfold.\n      iRight; iRight; iRight; iRight; iLeft.\n      iInduction (get_active σ) as [| l] \"IH\".\n      { rewrite big_orL_nil //. }\n      rewrite 2!big_orL_cons.\n      iDestruct \"H\" as \"[(% & % & H) | Ht]\".\n      + iLeft. iExists _. iSplit; [done|].\n        iIntros. by iApply (\"H\" with \"[//]\").\n      + iRight. by iApply (\"IH\" with \"Ht\").\n    - rewrite least_fixpoint_unfold.\n      do 5 iRight.\n      iInduction (list_prod (get_active σ) (get_active σ')) as [| l] \"IH\".\n      { rewrite big_orL_nil //. }\n      rewrite 2!big_orL_cons.\n      iDestruct \"H\" as \"[(% & ? & H) | Ht]\".\n      + iLeft. iExists _. iSplit; [done|].\n        iIntros. by iApply (\"H\" with \"[//]\").\n      + iRight. by iApply (\"IH\" with \"Ht\").\n  Qed.\n\n  Lemma exec_coupl_mono (Z1 Z2 : cfg Λ → cfg Λ → iProp Σ) e1 σ1 e1' σ1' :\n    (∀ ρ ρ', Z1 ρ ρ' -∗ Z2 ρ ρ') -∗ exec_coupl e1 σ1 e1' σ1' Z1 -∗ exec_coupl e1 σ1 e1' σ1' Z2.\n  Proof.\n    iIntros \"HZ\". iApply exec_coupl_strong_mono.\n    iIntros (???) \"[_ ?]\". by iApply \"HZ\".\n  Qed.\n\n  Lemma exec_coupl_strengthen e1 σ1 e1' σ1' (Z : cfg Λ → cfg Λ → iProp Σ) :\n    exec_coupl e1 σ1 e1' σ1' Z -∗\n    exec_coupl e1 σ1 e1' σ1' (λ '(e2, σ2) ρ', ⌜∃ σ, prim_step e1 σ (e2, σ2) > 0⌝ ∧ Z (e2, σ2) ρ').\n  Proof.\n    iApply exec_coupl_strong_mono.\n    iIntros (???) \"[[% ?] ?]\". iSplit; [|done]. by iExists _.\n  Qed.\n\n  Lemma exec_coupl_bind K `{!LanguageCtx K} e1 σ1 e1' σ1' (Z : cfg Λ → cfg Λ → iProp Σ) :\n    to_val e1 = None →\n    exec_coupl e1 σ1 e1' σ1' (λ '(e2, σ2) ρ2', Z (K e2, σ2) ρ2') -∗ exec_coupl (K e1) σ1 e1' σ1' Z.\n  Proof.\n    iIntros (Hv) \"Hcpl\".\n    iAssert (⌜to_val e1 = None⌝)%I as \"-#H\"; [done|].\n    iRevert \"H\".\n    rewrite /exec_coupl /exec_coupl'.\n    set (Φ := (λ x, ⌜to_val x.1.1 = None⌝ -∗\n                     bi_least_fixpoint (exec_coupl_pre Z) ((K x.1.1, x.1.2), (x.2.1, x.2.2)))%I\n           : prodO cfgO cfgO → iPropI Σ).\n    assert (NonExpansive Φ).\n    { intros n ((?&?)&(?&?)) ((?&?)&(?&?)) [[[=] [=]] [[=] [=]]]. by simplify_eq. }\n    iPoseProof (least_fixpoint_iter\n                  (exec_coupl_pre (λ '(e2, σ2) ρ2', Z (K e2, σ2) ρ2')) Φ\n                 with \"[]\") as \"H\"; last first.\n    { iIntros (?). iApply (\"H\" $! ((_, _), (_, _)) with \"Hcpl [//]\"). }\n    iIntros \"!#\" ([[? σ] [? σ']]). rewrite {1}/exec_coupl_pre.\n    iIntros \"[(% & % & % & H) | [(% & % & % & H) | [(% & %n & % & H) | [H | [H | H]]]]] %Hv'\".\n    - rewrite least_fixpoint_unfold.\n      iLeft. iExists (λ '(e2, σ2) ρ', ∃ e2', e2 = K e2' ∧ R2 (e2', σ2) ρ').\n      rewrite fill_dmap //=.\n      iSplit; [eauto using reducible_fill|].\n      iSplit.\n      { iPureIntro. rewrite -(dret_id_right (prim_step _ σ')).\n        eapply Rcoupl_dbind; [|done].\n        intros [] ?? =>/=. apply Rcoupl_dret. eauto. }\n      iIntros ([] [] (? & -> & ?)).\n      by iMod (\"H\" with \"[//]\").\n    - rewrite least_fixpoint_unfold /=.\n      iRight. iLeft. iExists (λ '(e2, σ2) ρ', ∃ e2', e2 = K e2' ∧ R2 (e2', σ2) ρ').\n      iSplit; [eauto using reducible_fill|].\n      iSplit.\n      { iPureIntro.\n        rewrite fill_dmap //=.\n        rewrite -(dret_id_right (dret _)).\n        eapply Rcoupl_dbind; [|done].\n        intros [] ?? =>/=. apply Rcoupl_dret. eauto. }\n      iIntros ([] (? & -> & ?)).\n      by iMod (\"H\" with \"[//]\").\n    - rewrite least_fixpoint_unfold.\n      iRight. iRight. iLeft.\n      iExists (λ '(e2, σ2) ρ', ∃ e2', e2 = K e2' ∧ R2 (e2', σ2) ρ'), n. simpl.\n      iSplit.\n      { iPureIntro.\n        rewrite -(dret_id_right (exec _ _)).\n        rewrite -(dret_id_left (λ ρ, dret (K ρ.1, ρ.2)) (_, σ)).\n        eapply Rcoupl_dbind; [|done].\n        intros [] [] ?. apply Rcoupl_dret. eauto. }\n      iIntros (?? (? & <-%(inj _) & ?)).\n      iMod (\"H\" with \"[//] [//]\") as \"H\".\n      iModIntro. iApply \"H\".\n    - rewrite least_fixpoint_unfold.\n      iRight; iRight; iRight; iLeft. simpl.\n      iInduction (get_active σ') as [| l] \"IH\".\n      { rewrite big_orL_nil //. }\n      rewrite 2!big_orL_cons.\n      iDestruct \"H\" as \"[(% & % & % & H) | Ht]\".\n      + iLeft. iExists (λ '(e2, σ2) σ2', ∃ e2', e2 = K e2' ∧ R2 (e2', σ2) σ2').\n        iSplit; [eauto using reducible_fill|].\n        iSplit.\n        { iPureIntro.\n          rewrite fill_dmap //.\n          rewrite -(dret_id_right (state_step _ _)).\n          eapply Rcoupl_dbind; [|done].\n          intros [] ?? =>/=.\n          apply Rcoupl_dret. eauto. }\n        iIntros (??? (?& -> & ?)).\n        iApply (\"H\" with \"[//]\").\n      + iRight. by iApply (\"IH\" with \"Ht\").\n    - rewrite least_fixpoint_unfold /=.\n      iRight; iRight; iRight; iRight; iLeft.\n      iInduction (get_active σ) as [| l] \"IH\".\n      { rewrite big_orL_nil //. }\n      rewrite 2!big_orL_cons.\n      iDestruct \"H\" as \"[(% & % & H) | Ht]\".\n      + iLeft. iExists _. iSplit; [done|].\n        iIntros. by iApply (\"H\" with \"[//]\").\n      + iRight. by iApply (\"IH\" with \"Ht\").\n    - rewrite least_fixpoint_unfold /=.\n      do 5 iRight.\n      iInduction (list_prod (get_active σ) (get_active σ')) as [| l] \"IH\".\n      { rewrite big_orL_nil //. }\n      rewrite 2!big_orL_cons.\n      iDestruct \"H\" as \"[(% & ? & H) | Ht]\".\n      + iLeft. iExists _. iSplit; [done|].\n        iIntros. iMod (\"H\" with \"[//]\") as \"H\".\n        iModIntro. by iApply \"H\".\n      + iRight. by iApply (\"IH\" with \"Ht\").\n  Qed.\n\n  Lemma exec_coupl_prim_steps e1 σ1 e1' σ1' Z :\n    (∃ R, ⌜reducible e1 σ1⌝ ∗\n          ⌜Rcoupl (prim_step e1 σ1) (prim_step e1' σ1') R⌝ ∗\n          ∀ ρ2 ρ2', ⌜R ρ2 ρ2'⌝ ={∅}=∗ Z ρ2 ρ2')\n    ⊢ exec_coupl e1 σ1 e1' σ1' Z.\n  Proof.\n    iIntros \"H\".\n    rewrite {1}exec_coupl_unfold.\n    by iLeft.\n  Qed.\n\n  Lemma exec_coupl_prim_step_l e1 σ1 e1' σ1' Z :\n    (∃ R, ⌜reducible e1 σ1⌝ ∗\n          ⌜Rcoupl (prim_step e1 σ1) (dret (e1', σ1')) R⌝ ∗\n          ∀ ρ2, ⌜R ρ2 (e1', σ1')⌝ ={∅}=∗ Z ρ2 (e1', σ1'))\n    ⊢ exec_coupl e1 σ1 e1' σ1' Z.\n  Proof.\n    iIntros \"H\".\n    rewrite {1}exec_coupl_unfold.\n    iRight; iLeft.\n    done.\n  Qed.\n\n  Lemma exec_coupl_exec_r e1 σ1 e1' σ1' Z :\n    (∃ R n, ⌜Rcoupl (dret (e1, σ1)) (exec n (e1', σ1')) R⌝ ∗\n            ∀ e2' σ2', ⌜R (e1, σ1) (e2', σ2')⌝ ={∅}=∗ exec_coupl e1 σ1 e2' σ2' Z)\n    ⊢ exec_coupl e1 σ1 e1' σ1' Z.\n  Proof.\n    iIntros \"H\".\n    rewrite {1}exec_coupl_unfold.\n    iRight; iRight; iLeft.\n    done.\n  Qed.\n\n  Lemma exec_coupl_prim_state α' e1 σ1 e1' σ1' Z :\n    α' ∈ get_active σ1' →\n    (∃ R, ⌜reducible e1 σ1⌝ ∗\n          ⌜Rcoupl (prim_step e1 σ1) (state_step σ1' α')  R⌝ ∗\n          ∀ e2 σ2 σ2', ⌜R (e2, σ2) σ2'⌝ ={∅}=∗ Z (e2, σ2) (e1', σ2'))\n    ⊢ exec_coupl e1 σ1 e1' σ1' Z.\n  Proof.\n    iIntros (?) \"H\".\n    rewrite {1}exec_coupl_unfold.\n    iRight; iRight; iRight; iLeft.\n    by iApply big_orL_elem_of.\n  Qed.\n\n  Lemma exec_coupl_state_prim α e1 σ1 e1' σ1' Z :\n    α ∈ get_active σ1 →\n    (∃ R, ⌜Rcoupl (state_step σ1 α) (prim_step e1' σ1') R⌝ ∗\n          ∀ σ2 e2' σ2', ⌜R σ2 (e2', σ2')⌝ ={∅}=∗ exec_coupl e1 σ2 e2' σ2' Z)\n    ⊢ exec_coupl e1 σ1 e1' σ1' Z.\n  Proof.\n    iIntros (?) \"H\".\n    rewrite {1}exec_coupl_unfold.\n    iRight; iRight; iRight; iRight; iLeft.\n    by iApply big_orL_elem_of.\n  Qed.\n\n  Lemma exec_coupl_state_steps α α' e1 σ1 e1' σ1' Z :\n    (α, α') ∈ list_prod (get_active σ1) (get_active σ1') →\n    (∃ R, ⌜Rcoupl (state_step σ1 α) (state_step σ1' α') R⌝ ∗\n          (∀ σ2 σ2', ⌜R σ2 σ2'⌝ ={∅}=∗ exec_coupl e1 σ2 e1' σ2' Z))\n    ⊢ exec_coupl e1 σ1 e1' σ1' Z.\n  Proof.\n    iIntros (?) \"H\".\n    rewrite {1}exec_coupl_unfold.\n    do 5 iRight.\n    by iApply big_orL_elem_of.\n  Qed.\n\n  Lemma exec_coupl_reducible e e' σ σ' Z :\n    exec_coupl e σ e' σ' Z ={∅}=∗ ⌜reducible e σ⌝.\n  Proof.\n    rewrite /exec_coupl /exec_coupl'.\n    set (Φ := (λ x, |={∅}=> ⌜reducible x.1.1 x.1.2⌝)%I : prodO cfgO cfgO → iPropI Σ).\n    assert (NonExpansive Φ).\n    { intros n ((?&?)&(?&?)) ((?&?)&(?&?)) [[[=] [=]] [[=] [=]]]. by simplify_eq. }\n    iPoseProof (least_fixpoint_iter (exec_coupl_pre Z) Φ\n                 with \"[]\") as \"H\"; last first.\n    { done. }\n    iIntros \"!>\" (([e1 σ1] & [e1' σ1'])). rewrite /exec_coupl_pre.\n    iIntros \"[(% & % & % & H) | [(% & % & % & H) | [(% & % & %Hcpl & H) | [H | [H | H]]]]] /=\";\n      [done|done| | | |].\n    - eapply Rcoupl_pos_R in Hcpl.\n      eapply Rcoupl_inhabited_l in Hcpl as ([] & [] & ? & [= -> ->]%dret_pos & ?); last first.\n      { rewrite dret_mass; lra. }\n      by iMod (\"H\" with \"[//]\").\n    - iDestruct (big_orL_mono _ (λ n αs, |={∅}=> ⌜reducible e1 σ1⌝)%I  with \"H\") as \"H\".\n      { iIntros (? α' ?%elem_of_list_lookup_2) \"(% & % & _)\". eauto. }\n      iInduction (get_active σ1') as [| α'] \"IH\"; [done|].\n      rewrite big_orL_cons.\n      iDestruct \"H\" as \"[? | H]\"; [done|].\n      by iApply \"IH\".\n    - iDestruct (big_orL_mono _ (λ n αs, |={∅}=> ⌜reducible e1 σ1⌝)%I  with \"H\") as \"H\".\n      { iIntros (? α' ?%elem_of_list_lookup_2) \"(% & %Hcpl & H)\".\n        eapply Rcoupl_pos_R in Hcpl.\n        eapply Rcoupl_inhabited_l in Hcpl as (σ2 & [] & ? & ? & ?); last first.\n        { rewrite state_step_mass //. lra. }\n        iApply (pure_impl_1 (reducible e1 σ2)).\n        { iPureIntro. by eapply state_step_reducible. }\n        by iMod (\"H\" with \"[//]\"). }\n      iInduction (get_active σ1) as [| α] \"IH\"; [done|].\n      rewrite big_orL_cons.\n      iDestruct \"H\" as \"[? | H]\"; [done|].\n      by iApply \"IH\".\n    - iDestruct (big_orL_mono _ (λ n αs, |={∅}=> ⌜reducible e1 σ1⌝)%I  with \"H\") as \"H\".\n      { iIntros (? [α1 α2] [? ?]%elem_of_list_lookup_2%elem_of_list_prod_1) \"(% & %Hcpl & H)\".\n        eapply Rcoupl_pos_R in Hcpl.\n        eapply Rcoupl_inhabited_l in Hcpl as (σ2 &?&?& Hs &?); last first.\n        { rewrite state_step_mass //. lra. }\n        iApply (pure_impl_1 (reducible e1 σ2)).\n        { iPureIntro. by eapply state_step_reducible. }\n        by iMod (\"H\" with \"[//]\"). }\n      iInduction (list_prod (get_active σ1) (get_active σ1')) as [| [α α']] \"IH\"; [done|].\n      rewrite big_orL_cons.\n      iDestruct \"H\" as \"[? | H]\"; [done|].\n      by iApply \"IH\".\n  Qed.\n\n  Lemma exec_coupl_det_r n e1 σ1 e1' σ1' e2' σ2' Z :\n    exec n (e1', σ1') (e2', σ2') = 1 →\n    exec_coupl e1 σ1 e2' σ2' Z -∗\n    exec_coupl e1 σ1 e1' σ1' Z.\n  Proof.\n    iIntros (Hexec%pmf_1_eq_dret) \"Hcpl\".\n    iApply exec_coupl_exec_r.\n    iExists _, n. iSplit.\n    { iPureIntro. apply Rcoupl_pos_R, Rcoupl_trivial.\n      - apply dret_mass.\n      - rewrite Hexec; apply dret_mass. }\n    iIntros (e2'' σ2'' (_ & _ & H)).\n    rewrite Hexec in H. by apply dret_pos in H as [= -> ->].\n  Qed.\n\nEnd exec_coupl.\n\n(** * The weakest precondition  *)\nDefinition wp_pre `{!irisGS Λ Σ}\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 e1' σ1',\n      state_interp σ1 ∗ spec_interp (e1', σ1') ={E,∅}=∗\n      exec_coupl e1 σ1 e1' σ1' (λ '(e2, σ2) '(e2', σ2'),\n        ▷ |={∅,E}=> state_interp σ2 ∗ spec_interp (e2', σ2') ∗ wp E e2 Φ)\nend%I.\n\nLocal Instance wp_pre_contractive `{!irisGS Λ Σ} : Contractive wp_pre.\nProof.\n  rewrite /wp_pre /= => n wp wp' Hwp E e1 Φ.\n  do 9 f_equiv.\n  apply least_fixpoint_ne_outer; [|done].\n  intros ? [[] []]. rewrite /exec_coupl_pre.\n  do 10 f_equiv.\n  { f_equiv. do 2 case_match. f_contractive. do 3 f_equiv. apply Hwp. }\n  { case_match. f_contractive. do 3 f_equiv. apply Hwp. }\n  { do 9 f_equiv. f_contractive. do 3 f_equiv. apply Hwp. }\nQed.\n\n(* TODO: get rid of stuckness in notation [iris/bi/weakestpre.v] so that we don't have to do this *)\nLocal Definition wp_def `{!irisGS Λ Σ} : Wp (iProp Σ) (expr Λ) (val Λ) stuckness :=\n  λ (s : stuckness), fixpoint (wp_pre).\nLocal Definition wp_aux : seal (@wp_def). Proof. by eexists. Qed.\nDefinition wp' := wp_aux.(unseal).\nGlobal Arguments wp' {Λ Σ _}.\nGlobal Existing Instance wp'.\nLocal Lemma wp_unseal `{!irisGS Λ Σ} : wp = @wp_def Λ Σ _.\nProof. rewrite -wp_aux.(seal_eq) //. Qed.\n\nSection wp.\nContext `{!irisGS Λ Σ}.\nImplicit Types P : iProp Σ.\nImplicit Types Φ : val Λ → iProp Σ.\nImplicit Types v : val Λ.\nImplicit Types e : expr Λ.\nImplicit Types σ : state Λ.\nImplicit Types ρ : cfg Λ.\n\n(* Weakest pre *)\nLemma wp_unfold s E e Φ :\n  WP e @ s; E {{ Φ }} ⊣⊢ wp_pre (wp (PROP:=iProp Σ) s) E e Φ.\nProof. rewrite wp_unseal. apply (fixpoint_unfold wp_pre). 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  do 9 f_equiv.\n  apply least_fixpoint_ne_outer; [|done].\n  intros ? [[] []]. rewrite /exec_coupl_pre.\n  do 10 f_equiv.\n  { f_equiv. do 2 case_match. f_contractive. do 3 f_equiv.\n    rewrite IH; [done|lia|]. intros ?. eapply dist_S, HΦ. }\n  { case_match. f_contractive. do 3 f_equiv.\n    rewrite IH; [done|lia|]. intros ?. eapply dist_S, HΦ. }\n  { do 9 f_equiv. f_contractive. do 3 f_equiv. rewrite IH; [done|lia|].\n    intros ?. eapply dist_S, HΦ. }\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  do 8 f_equiv.\n  apply least_fixpoint_ne_outer; [|done].\n  intros ? [[] []]. rewrite /exec_coupl_pre.\n  do 10 f_equiv.\n  { f_equiv. do 2 case_match. f_contractive. do 6 f_equiv.  }\n  { case_match. f_contractive. do 6 f_equiv. }\n  { do 9 f_equiv. f_contractive. do 6 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 e1' σ1') \"[Hσ Hs]\".\n  iMod (fupd_mask_subseteq E1) as \"Hclose\"; first done.\n  iMod (\"H\" with \"[$]\") as \"H\".\n  iModIntro.\n  iApply (exec_coupl_mono with \"[Hclose HΦ] H\").\n  iIntros ([e2 σ2] [e2' σ2']) \"H\".\n  iModIntro.\n  iMod \"H\" as \"(?&?& Hwp)\". iFrame.\n  iMod \"Hclose\" as \"_\". iModIntro.\n  iApply (\"IH\" with \"[] Hwp\"); 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 e1' σ1') \"Hi\". 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 WeaklyAtomic 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 e1' σ1') \"[Hσ Hs]\". iMod \"H\".\n  iMod (\"H\" with \"[$]\") as \"H\".\n  iModIntro.\n  iDestruct (exec_coupl_strengthen with \"H\") as \"H\".\n  iApply (exec_coupl_mono with \"[] H\").\n  iIntros ([e2 σ2] [e2' σ2']) \"[[% %Hstep] H]\".\n  iModIntro.\n  iMod \"H\" as \"(Hσ & Hρ & H)\".\n  (* destruct s *)\n  rewrite !wp_unfold /wp_pre.\n  destruct (to_val e2) as [v2|] eqn:He2.\n  + iDestruct \"H\" as \">> $\". by iFrame.\n  + iMod (\"H\" with \"[$]\") as \"H\".\n    iMod (exec_coupl_reducible with \"H\") as %[ρ ?].\n    pose proof (atomic _ _ _ Hstep ρ). lra.\n  (* destruct (atomic _ _ _ Hstep) as [v <-%of_to_val]. *)\n  (* rewrite wp_value_fupd'. iMod \"H\" as \">H\". *)\n  (* iModIntro. iFrame. 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 e1' σ1') \"[Hσ Hs]\". iMod \"HR\".\n  iMod (\"H\" with \"[$Hσ $Hs]\") as \"H\".\n  iModIntro.\n  iApply (exec_coupl_mono with \"[HR] H\").\n  iIntros ([e2 σ2] [e2' σ2']) \"H\".\n  iModIntro.\n  iMod \"H\" as \"(Hσ & Hρ & H)\".\n  iMod \"HR\".\n  iFrame \"Hσ Hρ\".\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 /=; [|done].\n  iIntros (σ1 e1' σ1') \"[Hσ Hs]\".\n  iMod (\"H\" with \"[$Hσ $Hs]\") as \"H\".\n  iModIntro.\n  iApply exec_coupl_bind; [done|].\n  iApply (exec_coupl_mono with \"[] H\").\n  iIntros ([e2 σ2] [e2' σ2']) \"H\".\n  iModIntro.\n  iMod \"H\" as \"(Hσ & Hρ & H)\".\n  iModIntro. iFrame \"Hσ Hρ\". by iApply \"IH\".\nQed.\n\n(* Lemma 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 {{ Φ }} }}. *)\n(* Proof. *)\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 ns κ κs nt) \"Hσ\". iMod (\"H\" with \"[$]\") as \"[% H]\". *)\n(*   iModIntro; iSplit. *)\n(*   { destruct s; eauto using reducible_fill_inv. } *)\n(*   iIntros (e2 σ2 efs Hstep) \"Hcred\". *)\n(*   iMod (\"H\" $! _ _ _ with \"[] Hcred\") as \"H\"; first eauto using fill_step. *)\n(*   iIntros \"!> !>\". iMod \"H\". iModIntro. iApply (step_fupdN_wand with \"H\"). *)\n(*   iIntros \"H\". iMod \"H\" as \"($ & H & $)\". iModIntro. by iApply \"IH\". *)\n(* Qed. *)\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 s E e Φ R :\n  R -∗ WP e @ s; E {{ v, R -∗ Φ v }} -∗ WP e @ s; E {{ Φ }}.\nProof.\n  iIntros \"HR 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 `{!irisGS Λ Σ}.\n  Implicit Types P Q : iProp Σ.\n  Implicit Types Φ : val Λ → iProp Σ.\n  Implicit Types v : val Λ.\n  Implicit Types e : expr Λ.\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 {{ Ψ }}) | 2.\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 WeaklyAtomic 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 WeaklyAtomic 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": "logsem", "repo": "clutch", "sha": "35144f9b1fe9c913b4bd24106a12ac7f02b20ec5", "save_path": "github-repos/coq/logsem-clutch", "path": "github-repos/coq/logsem-clutch/clutch-35144f9b1fe9c913b4bd24106a12ac7f02b20ec5/theories/program_logic/weakestpre.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.25589979671206836}}
{"text": "(* Proof of correctness of constant propagation *)\n\nRequire Export List.\nRequire Export Coqlib.\nRequire Export Maps.\nRequire Export common.\nRequire Export ir_properties.\nRequire Export internal_simulations.\nRequire Export interpreter_proof.\nRequire Export specIR.\nRequire Export interpreter.\nRequire Export const_prop.\n\n(** * Abstract Values and equivalence *)\n(* Matching a value with an abstract value *)\nDefinition match_abs_value (v:value) (av:abs_value): Prop :=\n  match av with\n  | FlatValue.Top => True\n  | FlatValue.Bot => False\n  | FlatValue.Inj v1 => v = v1\n  end.\n\nDefinition match_value (ov:option value) (av:abs_value) : Prop :=\n  match ov with\n  | None => match av with\n           | FlatValue.Top => True\n           | _ => False\n           end\n  | Some v => match_abs_value v av\n  end.\n\n(* If an abstraction matches a value, a bigger abstraction also does *)\nLemma match_abs_value_increasing:\n  forall v abs1 abs2,\n    FlatValue.ge abs1 abs2 ->\n    match_abs_value v abs2 ->\n    match_abs_value v abs1.\nProof.\n  intros. destruct abs1; destruct abs2; inv H0; inv H; simpl; auto.\nQed.\n\nLemma match_value_increasing:\n  forall v abs1 abs2,\n    FlatValue.ge abs1 abs2 ->\n    match_value v abs2 ->\n    match_value v abs1.\nProof.\n  intros. destruct abs1; destruct abs2; destruct v; try inv H0; try inv H; simpl; auto.\nQed.\n\nLemma match_val_lub_left:\n  forall v absl absr,\n    match_abs_value v absl ->\n    match_abs_value v (FlatValue.lub absl absr).\nProof.\n  intros. destruct absl; inv H; destruct absr; simpl; auto.\n  destruct (ValueEq.eq t t0); simpl; auto.\nQed.\n\nLemma match_val_lub_right:\n  forall v absl absr,\n    match_abs_value v absr ->\n    match_abs_value v (FlatValue.lub absl absr).\nProof.\n  intros. destruct absr; inv H; destruct absl; simpl; auto.\n  destruct (ValueEq.eq t0 t); simpl; auto.\nQed.\n\n(** * Abstract regmaps properties *)\n(* A regmap matches an approximation if all registers do *)\nDefinition match_regmap (rm:reg_map) (arm:abs_regmap): Prop :=\n  forall r, match_value (rm!r) (MapFlatValue.get r arm).\n\nLemma match_regmap_increasing:\n  forall rm arm1 arm2,\n    MapFlatValue.ge arm1 arm2 ->\n    match_regmap rm arm2 ->\n    match_regmap rm arm1.\nProof.\n  unfold match_regmap. intros.\n  assert (HM: match_value rm # r (MapFlatValue.get r arm2)) by apply H0.\n  eapply match_value_increasing; eauto.\nQed.\n\n(* Updating a regmap with a good approximation yields a good approximation *)\nLemma match_regmap_update:\n  forall rm arm v av r,\n    match_value (Some v) av ->\n    match_regmap rm arm ->\n    match_regmap (rm # r <- v) (regmap_set r av arm).\nProof.\n  intros. unfold match_regmap. intros.\n  rewrite MapFlatValue.gsspec; auto.\n  destruct (peq r0 r).\n  - subst r. rewrite PTree.gss. auto.\n  - rewrite PTree.gso; auto.\n  - red. intros. specialize (H0 xH). subst arm. simpl in H0. destruct rm. inv H0.  unfold match_value in H0. simpl in H0.\n    destruct o; inv H0.\n  - unfold FlatValue.eq. red. intros. subst av. inv H.\nQed.\n\nLemma match_regmap_not_bot:\n  forall rm arm,\n    match_regmap rm arm ->\n    arm <> MapFlatValue.Bot.\nProof.\n  intros. red. intros. unfold match_regmap in H. specialize (H xH). subst arm. \n  destruct (rm # 1) eqn:HGET. simpl in H. auto. simpl in H. auto.\nQed.\n\n\nLemma match_regmap_generate_true:\n  forall rm arm e v,\n    match_regmap rm arm ->\n    specIR.eval_expr e rm (Vint v) ->\n    Zne v 0 ->\n    match_regmap rm (generate_true arm e).\nProof.\n  intros rm arm e v MATCHRM EVAL ZNE. unfold generate_true.\n  destruct e.\n  - destruct b; auto.           (* Binexpr *)\n    destruct o; destruct o0; auto.\n    + inv EVAL. inv EVAL0. inv EVALL. inv EVALR.\n      assert (v1 = v2).\n      { inv EVALV; f_equal.\n        destruct (v0 =? v3) eqn:HEQ. apply Z.eqb_eq in HEQ. auto. inv H. omega. }\n        subst. unfold match_regmap. intros. poseq_destr r0 r.\n      * rewrite MapFlatValue.gsspec; auto. rewrite peq_true.\n           rewrite GETRM. constructor. eapply match_regmap_not_bot; eauto. unfold not; intros. inv H.\n      * rewrite MapFlatValue.gsspec; auto. rewrite peq_false; auto.\n           eapply match_regmap_not_bot; eauto. unfold not; intros. inv H.\n    + inv EVAL. inv EVAL0. inv EVALL. inv EVALR.\n      assert (v1 = v2).\n      { inv EVALV; f_equal.\n        destruct (v0 =? v3) eqn:HEQ. apply Z.eqb_eq in HEQ. auto. inv H. omega. }\n      subst. unfold match_regmap. intros. poseq_destr r0 r.\n      * rewrite MapFlatValue.gsspec; auto. rewrite peq_true.\n        rewrite GETRM. constructor. eapply match_regmap_not_bot; eauto. unfold not; intros. inv H.\n      * rewrite MapFlatValue.gsspec; auto. rewrite peq_false; auto.\n        eapply match_regmap_not_bot; eauto. unfold not; intros. inv H.\n  - destruct u; auto.           (* Unexpr *)\n    destruct o; auto. inv EVAL. inv EVAL0. inv EVALV.\n    assert (v1 = 0).\n    { inv EVAL. unfold int_neg in ZNE. destruct v1; auto; omega. }\n    subst. unfold match_regmap. intros. poseq_destr r0 r.\n    + inv EVAL. rewrite GETRM.\n      rewrite MapFlatValue.gsspec; auto. rewrite peq_true. constructor.\n      eapply match_regmap_not_bot; eauto. unfold not; intros. inv H.\n    + rewrite MapFlatValue.gsspec; auto. rewrite peq_false; auto.\n      eapply match_regmap_not_bot; eauto. unfold not; intros. inv H.\nQed.\n\n\nLemma match_regmap_assert:\n  forall rm arm le,\n    match_regmap rm arm ->\n    specIR.eval_list_expr le rm true ->\n    match_regmap rm (generate_true_list arm le).\nProof.\n  intros. generalize dependent arm. induction le; auto.\n  simpl. intros. inv H0.\n  eapply IHle; auto.\n  eapply match_regmap_generate_true; eauto.\nQed.  \n\n(** * Preservation of evaluation  *)\n(* Replacing with a good approximations evaluates to the same result *)\nLemma eval_op_abs_correct:\n  forall o rm arm v,\n    specIR.eval_op o rm v ->\n    match_regmap rm arm ->\n    match_value (Some v) (eval_op_abs o arm).\nProof.\n  intros. destruct o; inv H; simpl; auto.\n  unfold match_abs_value. specialize (H0 r). rewrite GETRM in H0.\n  unfold eval_reg_abs.\n  destruct (MapFlatValue.get r arm); inv H0; auto.\nQed.\n\n\n(* If an abstract regmap is correct, then the real value is matched with the abstract evaluation *)\nLemma eval_binop_abs_correct:\n  forall b o1 o2 rm v arm,\n    specIR.eval_binop b o1 o2 rm v ->\n    match_regmap rm arm ->\n    match_abs_value v (eval_binop_abs b o1 o2 arm).\nProof.\n  intros b o1 o2 rm v arm EVALB MATCHRM.\n  unfold match_regmap in MATCHRM. inv EVALB.\n  destruct o1; destruct o2; inv EVALL; inv EVALR; try apply MATCHRM in H1; try apply MATCHRM in H4.\n  - unfold eval_binop_abs. simpl. unfold eval_reg_abs.\n    assert (match_value (Some v1) (MapFlatValue.get r arm)).\n    { specialize (MATCHRM r). rewrite GETRM in MATCHRM. auto. }\n    assert (match_value (Some v2) (MapFlatValue.get r0 arm)).\n    { specialize (MATCHRM r0). rewrite GETRM0 in MATCHRM. auto. }\n    destruct (MapFlatValue.get r arm); inv H; destruct (MapFlatValue.get r0 arm); inv H0; simpl; auto.\n    rewrite eval_binop_values_correct in EVALV. rewrite EVALV. constructor.\n  - unfold eval_binop_abs. simpl.\n    unfold eval_reg_abs.\n    assert (match_value (Some v1) (MapFlatValue.get r arm)).\n    { specialize (MATCHRM r). rewrite GETRM in MATCHRM. auto. }\n    destruct (MapFlatValue.get r arm); inv H; simpl; auto.\n    rewrite eval_binop_values_correct in EVALV. rewrite EVALV. constructor. \n  - unfold eval_binop_abs. simpl.\n    assert (match_value (Some v2) (MapFlatValue.get r arm)).\n    { specialize (MATCHRM r). rewrite GETRM in MATCHRM. auto. }\n    unfold eval_reg_abs. destruct (MapFlatValue.get r arm); inv H; simpl; auto.\n    rewrite eval_binop_values_correct in EVALV. rewrite EVALV. constructor.\n  - inv EVALV; simpl; auto.\nQed.\n\nLemma eval_unop_abs_correct:\n  forall u o rm v arm,\n    specIR.eval_unop u o rm v ->\n    match_regmap rm arm ->\n    match_abs_value v (eval_unop_abs u o arm).\nProof.\n  intros u o rm v arm EVAL MATCHRM.  unfold match_regmap in MATCHRM. inv EVAL.\n  destruct o; inv EVAL0.\n  - unfold eval_unop_abs. simpl. unfold eval_reg_abs.\n    assert (match_value (Some v0) (MapFlatValue.get r arm)).\n    { specialize (MATCHRM r). rewrite GETRM in MATCHRM. auto. }\n    destruct (MapFlatValue.get r arm); inv GETRM; simpl; auto.\n    inv H. inv EVALV; simpl; auto.\n  - unfold eval_unop_abs. simpl. inv EVALV; simpl; auto.\nQed.\n\nLemma eval_expr_abs_correct:\n  forall e rm v arm,\n    specIR.eval_expr e rm v ->\n    match_regmap rm arm ->\n    match_abs_value v (eval_expr_abs e arm).\nProof.\n  intros. inv H.\n  - simpl. eapply eval_binop_abs_correct; eauto.\n  - simpl. eapply eval_unop_abs_correct; eauto.\nQed.\n\n(* Updating with a movelist in both concrete and abstract regmap *)\nLemma match_regmap_update_movelist:\n  forall ml rm arm newrm,\n    match_regmap rm arm ->\n    specIR.update_movelist ml rm newrm ->\n    match_regmap newrm (list_transf ml arm).\nProof.\n  intros vm. induction vm; intros.\n  - unfold list_transf. simpl. inv H0. auto.\n  - unfold list_transf. simpl. destruct a as [r ex]. inv H0.\n    apply match_regmap_update.\n    + simpl. eapply eval_expr_abs_correct; eauto.\n    + eapply IHvm; eauto.\nQed.\n\n(** * Correctness of replacing  *)\n(* Replacing operands does not affect the evaluation *)\nLemma replace_binop_correct:\n  forall b o1 o2 ro1 ro2 v rm arm,\n    specIR.eval_binop b o1 o2 rm v ->\n    match_regmap rm arm ->\n    replace_op arm o1 = ro1 ->\n    replace_op arm o2 = ro2 ->\n    specIR.eval_binop b ro1 ro2 rm v.\nProof.\n  intros b o1 o2 ro1 ro2 v rm arm EVALB MATCHRM REPLACE1 REPLACE2.\n  destruct o1; destruct o2.\n  - inv REPLACE1. unfold replace_op. simpl. unfold eval_reg_abs. unfold match_regmap in MATCHRM. inv EVALB.\n    assert (MR: match_value (Some v1) (MapFlatValue.get r arm)).\n    { specialize (MATCHRM r). inv EVALL. rewrite GETRM in MATCHRM. auto. }\n    assert (MR0: match_value (Some v2) (MapFlatValue.get r0 arm)).\n    { specialize (MATCHRM r0). inv EVALR. rewrite GETRM in MATCHRM. auto. }\n    inv EVALL. inv EVALR.\n    destruct (MapFlatValue.get r arm) eqn:HR;\n      destruct (MapFlatValue.get r0 arm) eqn:HR0; auto; inv MR; inv MR0; econstructor; eauto; constructor; auto.\n  - inv REPLACE2. unfold replace_op. simpl. unfold eval_reg_abs. unfold match_regmap in MATCHRM. inv EVALB.\n    assert (MR: match_value (Some v1) (MapFlatValue.get r arm)).\n    { specialize (MATCHRM r). inv EVALL. rewrite GETRM in MATCHRM. auto. }\n    inv EVALL. inv EVALR.\n    destruct (MapFlatValue.get r arm) eqn:HR; auto; inv MR; econstructor; eauto; constructor; auto.\n  - inv REPLACE1. unfold replace_op. simpl. unfold eval_reg_abs. unfold match_regmap in MATCHRM. inv EVALB.\n    assert (MR: match_value (Some v2) (MapFlatValue.get r arm)).\n    { specialize (MATCHRM r). inv EVALR. rewrite GETRM in MATCHRM. auto. }\n    inv EVALL. inv EVALR.\n    destruct (MapFlatValue.get r arm) eqn:HR; auto; inv MR; econstructor; eauto; constructor; auto.\n  - inv REPLACE1. unfold replace_op. simpl. auto.\nQed.\n\nLemma replace_unop_correct:\n  forall u o ro v rm arm,\n    specIR.eval_unop u o rm v ->\n    match_regmap rm arm ->\n    replace_op arm o = ro ->\n    specIR.eval_unop u ro rm v.\nProof.\n  intros u o ro v rm arm EVAL MATCHRM REPLACE. destruct o.\n  - inv EVAL. inv EVAL0.\n    assert (MR: match_value (Some v0) (MapFlatValue.get r arm)).\n    { specialize (MATCHRM r). rewrite GETRM in MATCHRM. auto. }\n    unfold replace_op. unfold eval_op_abs, eval_reg_abs.\n    destruct (MapFlatValue.get r arm) eqn:HR; inv MR.\n    + econstructor; eauto. constructor.\n    + econstructor; eauto. constructor. auto.\n  - inv REPLACE. inv EVAL. unfold replace_op. simpl.\n    inv EVAL0. inv EVALV; econstructor; try constructor; auto.\nQed.\n\nLemma replace_op_correct:\n  forall o ro v rm arm,\n    specIR.eval_op o rm v ->\n    match_regmap rm arm ->\n    replace_op arm o = ro ->\n    specIR.eval_op ro rm v.\nProof.\n  intros. destruct o.\n  - inv H.\n    assert (MR: match_value (Some v) (MapFlatValue.get r arm)).\n    { specialize (H0 r). rewrite GETRM in H0. auto. }\n    unfold replace_op, eval_op_abs, eval_reg_abs.\n    destruct (MapFlatValue.get r arm); inv MR; constructor. auto.\n  - inv H. unfold replace_op. simpl. constructor.\nQed.\n\nTheorem replace_expr_correct:\n  forall e re v rm arm,\n    specIR.eval_expr e rm v ->\n    match_regmap rm arm ->\n    transf_expr (replace_op arm) e = re ->\n    specIR.eval_expr re rm v.\nProof.\n  intros. destruct e.\n  - inv H. inv EVAL. eapply replace_op_correct in EVALL; eauto.\n    eapply replace_op_correct in EVALR; eauto. simpl.\n    constructor. econstructor; eauto.\n  - inv H. inv EVAL. eapply replace_op_correct in EVAL0; eauto.\n    simpl. constructor. econstructor; eauto.\nQed.\n\nTheorem replace_expr_list_correct:\n  forall le rle v rm arm,\n    specIR.eval_list_expr le rm v ->\n    match_regmap rm arm ->\n    transf_expr_list (replace_op arm) le = rle ->\n    specIR.eval_list_expr rle rm v.\nProof.\n  intros. generalize dependent rle. induction le; intros.\n  - inv H. simpl. constructor.\n  - inv H.\n    + simpl. apply eval_cons_false. eapply replace_expr_correct; eauto.\n    + simpl. eapply eval_cons_true; eauto. eapply replace_expr_correct; eauto.\nQed.\n\nTheorem replace_expr_evalist_correct:\n  forall le v rm arm,\n    specIR.eval_list le rm v ->\n    match_regmap rm arm ->\n    specIR.eval_list (map (transf_expr (replace_op arm)) le) rm v.\nProof.\n  intros. generalize dependent v. induction le; intros.\n  - inv H. simpl. constructor.\n  - inv H. simpl. constructor.\n    + eapply replace_expr_correct; eauto.\n    + apply IHle. auto.\nQed.\n\nTheorem transf_vm_correct:\n  forall vm rm newrm arm,\n    specIR.update_regmap vm rm newrm ->\n    match_regmap rm arm ->\n    specIR.update_regmap (transf_vm (transf_expr (replace_op arm)) vm) rm newrm.\nProof.\n  intros. induction H.\n  - constructor.\n  - simpl. constructor.\n    eapply replace_expr_correct; eauto.\n    apply IHupdate_regmap. auto.\nQed.\n\nTheorem transf_ml_correct':\n  forall ml rm newrm arm rmeval,\n    specIR.update_movelist' ml rmeval rm newrm ->\n    match_regmap rmeval arm ->\n    specIR.update_movelist' (transf_ml (transf_expr (replace_op arm)) ml) rmeval rm newrm.\nProof.\n  intros. induction H.\n  - constructor.\n  - simpl. constructor.\n    eapply replace_expr_correct; eauto.\n    apply IHupdate_movelist'. auto.\nQed.\n\nTheorem transf_ml_correct:\n  forall ml rm newrm arm,\n    specIR.update_movelist ml rm newrm ->\n    match_regmap rm arm ->\n    specIR.update_movelist (transf_vm (transf_expr (replace_op arm)) ml) rm newrm.\nProof.\n  intros. unfold specIR.update_movelist in *.\n  apply transf_ml_correct'; auto.\nQed.\n    \n(* Same operands evaluate to the same result *)\nLemma op_eqb_same:\n  forall o1 o2 rm v,\n    op_eqb o1 o2 = true ->\n    (specIR.eval_op o1 rm v <->\n    specIR.eval_op o2 rm v).\nProof.\n  intros. split; intros.\n  - inv H0; inv H; destruct o2; inv H1.\n    + destruct v; destruct v0; inv H0. apply Z.eqb_eq in H1. subst. constructor.\n    + apply Pos.eqb_eq in H0. subst. constructor. auto.\n  - inv H0; inv H; destruct o1; inv H1.\n    + destruct v; destruct v0; inv H0. apply Z.eqb_eq in H1. subst. constructor.\n    + apply Pos.eqb_eq in H0. subst. constructor. auto.\nQed.\n\nLemma Zgtb_irrefl:\n  forall n,\n    (n >? n) = false.\nProof.\n  intros. rewrite Z.gtb_ltb. rewrite Z.ltb_irrefl. auto.\nQed.\n\nLemma Zgeb_refl:\n  forall n,\n    (n >=? n) = true.\nProof.\n  intros. rewrite Z.geb_leb. rewrite Z.leb_refl. auto.\nQed.\n\nLtac ok_str:=\n  repeat (econstructor; eauto).\n\n(** * Correctness of strength reduction  *)\n(* Strength reduction does not change evaluation *)\nTheorem strength_reduction_correct:\n  forall e rm v,\n    specIR.eval_expr e rm v -> specIR.eval_expr (strength_reduction e) rm v.\nProof.\n  intros. inv H.\n  - inv EVAL. inv EVALV; simpl.\n    + destruct o1; destruct o2; inv EVALL; inv EVALR; ok_str.\n      * destruct v3; ok_str. rewrite Z.add_0_r. ok_str.\n      * destruct v0; ok_str.\n      * destruct v0; destruct v3; try rewrite Z.add_0_l; try rewrite Z.add_0_r; ok_str.\n    + destruct o1; destruct o2; inv EVALL; inv EVALR; ok_str.\n      * destruct (reg_eqb r r0) eqn:HEQ. apply Pos.eqb_eq in HEQ. subst. simpl.\n        rewrite Pos.eqb_refl. rewrite GETRM0 in GETRM. inv GETRM. rewrite Z.sub_diag. ok_str.\n        simpl. rewrite HEQ. ok_str.\n      * destruct v3; ok_str. rewrite Z.sub_0_r; ok_str.\n      * destruct v0; ok_str.\n      * destruct v0; destruct v3; try rewrite Z.sub_0_r; try rewrite Z.sub_0_l; ok_str.\n        ** destruct (Pos.eqb p p0) eqn:HEQ; simpl; rewrite HEQ; ok_str.\n           apply Pos.eqb_eq in HEQ. subst. rewrite Z.pos_sub_diag. ok_str.\n        ** destruct (Pos.eqb p p0) eqn:HEQ; simpl; rewrite HEQ; ok_str.\n           apply Pos.eqb_eq in HEQ. subst. rewrite Z.pos_sub_diag. ok_str.\n    + destruct o1; destruct o2; inv EVALL; inv EVALR; ok_str.\n      * destruct v3; ok_str. rewrite Z.mul_0_r. ok_str. destruct p; ok_str.\n        rewrite Z.mul_1_r. ok_str.\n      * destruct v0; ok_str. destruct p; ok_str. rewrite Z.mul_1_l. ok_str.\n      * destruct v0; destruct v3; ok_str.\n        destruct p; ok_str. destruct p; destruct p0; try rewrite Z.mul_1_r; ok_str.\n        destruct p; ok_str. destruct p; ok_str; destruct p0; ok_str; rewrite Z.mul_1_r; ok_str.\n    + destruct o1; destruct o2; inv EVALL; inv EVALR; ok_str.\n      * destruct (reg_eqb r r0) eqn:HEQ. apply Pos.eqb_eq in HEQ. subst. simpl.\n        rewrite Pos.eqb_refl. rewrite GETRM0 in GETRM. inv GETRM. rewrite Zgtb_irrefl. ok_str.\n        simpl. rewrite HEQ. ok_str.\n      * destruct (Z.eqb v0 v3) eqn:HEQ. apply Z.eqb_eq in HEQ. subst. simpl.\n        rewrite Z.eqb_refl. rewrite Zgtb_irrefl. ok_str.\n        simpl. rewrite HEQ. ok_str.\n    + destruct o1; destruct o2; inv EVALL; inv EVALR; ok_str.\n      * destruct (reg_eqb r r0) eqn:HEQ. apply Pos.eqb_eq in HEQ. subst. simpl.\n        rewrite Pos.eqb_refl. rewrite GETRM0 in GETRM. inv GETRM. rewrite Z.ltb_irrefl. ok_str.\n        simpl. rewrite HEQ. ok_str.\n      * destruct (Z.eqb v0 v3) eqn:HEQ. apply Z.eqb_eq in HEQ. subst. simpl.\n        rewrite Z.eqb_refl. rewrite Z.ltb_irrefl. ok_str.\n        simpl. rewrite HEQ. ok_str.\n    + destruct o1; destruct o2; inv EVALL; inv EVALR; ok_str.\n      * destruct (reg_eqb r r0) eqn:HEQ. apply Pos.eqb_eq in HEQ. subst. simpl.\n        rewrite Pos.eqb_refl. rewrite GETRM0 in GETRM. inv GETRM. rewrite Zgeb_refl. ok_str.\n        simpl. rewrite HEQ. ok_str.\n      * destruct (Z.eqb v0 v3) eqn:HEQ. apply Z.eqb_eq in HEQ. subst. simpl.\n        rewrite Z.eqb_refl. rewrite Zgeb_refl. ok_str.\n        simpl. rewrite HEQ. ok_str.\n    + destruct o1; destruct o2; inv EVALL; inv EVALR; ok_str.\n      * destruct (reg_eqb r r0) eqn:HEQ. apply Pos.eqb_eq in HEQ. subst. simpl.\n        rewrite Pos.eqb_refl. rewrite GETRM0 in GETRM. inv GETRM. rewrite Z.leb_refl. ok_str.\n        simpl. rewrite HEQ. ok_str.\n      * destruct (Z.eqb v0 v3) eqn:HEQ. apply Z.eqb_eq in HEQ. subst. simpl.\n        rewrite Z.eqb_refl. rewrite Z.leb_refl. ok_str.\n        simpl. rewrite HEQ. ok_str.\n    + destruct o1; destruct o2; inv EVALL; inv EVALR; ok_str.\n      * destruct (reg_eqb r r0) eqn:HEQ. apply Pos.eqb_eq in HEQ. subst. simpl.\n        rewrite Pos.eqb_refl. rewrite GETRM0 in GETRM. inv GETRM. rewrite Z.eqb_refl. ok_str.\n        simpl. rewrite HEQ. ok_str.\n      * destruct (Z.eqb v0 v3) eqn:HEQ. apply Z.eqb_eq in HEQ. subst. simpl.\n        rewrite Z.eqb_refl. ok_str.\n        simpl op_eqb. rewrite HEQ at 1. rewrite <- HEQ. ok_str.        \n  - inv EVAL. inv EVALV; inv EVAL0; ok_str.\nQed.\n\nTheorem strength_reduction_list_correct:\n  forall le rm v,\n    specIR.eval_list_expr le rm v ->\n    specIR.eval_list_expr (map strength_reduction le) rm v.\nProof.\n  intros. induction le; simpl; auto. inv H.\n  - apply eval_cons_false. apply strength_reduction_correct. auto.\n  - eapply eval_cons_true; eauto. apply strength_reduction_correct. auto.\nQed.\n\nTheorem strength_reduction_evalist_correct:\n  forall le rm v,\n    specIR.eval_list le rm v ->\n    specIR.eval_list (map strength_reduction le) rm v.\nProof.\n  intros. generalize dependent v. induction le; intros; simpl; auto. inv H.\n  constructor. apply strength_reduction_correct. auto.\n  apply IHle. auto.\nQed.\n\nTheorem strength_reduction_transf_vm_correct:\n  forall vm rm newrm,\n    specIR.update_regmap vm rm newrm ->\n    specIR.update_regmap (transf_vm strength_reduction vm) rm newrm.\nProof.\n  intros. induction H.\n  - simpl. constructor.\n  - simpl. constructor.\n    apply strength_reduction_correct. auto.\n    apply IHupdate_regmap.\nQed.\n\nTheorem strength_reduction_transf_ml_correct':\n  forall ml rm newrm rmeval,\n    specIR.update_movelist' ml rmeval rm newrm ->\n    specIR.update_movelist' (transf_vm strength_reduction ml) rmeval rm newrm.\nProof.\n  intros. induction H.\n  - simpl. constructor.\n  - simpl. constructor.\n    apply strength_reduction_correct. auto.\n    apply IHupdate_movelist'.\nQed.\n\nTheorem strength_reduction_transf_ml_correct:\n  forall ml rm newrm,\n    specIR.update_movelist ml rm newrm ->\n    specIR.update_movelist (transf_vm strength_reduction ml) rm newrm.\nProof.\n  intros. unfold specIR.update_movelist in *.\n  apply strength_reduction_transf_ml_correct'. auto.\nQed.\n\nLtac strength_simpl:=\n  match goal with\n  | [ H: specIR.eval_op (Cst ?v) ?rm ?r |- _ ] => inv H\n  | [ H: specIR.eval_unop ?u ?o ?rm ?v |- _ ] => inv H\n  | [ H: specIR.eval_unop_value ?u ?o ?v |- _ ] => inv H\n  | [ H: specIR.eval_binop ?b ?o1 ?o2 ?rm ?v |- _ ] => inv H\n  | [ H: specIR.eval_binop_values ?b ?o1 ?o2 ?v |- _ ] => inv H\n  | [ H: specIR.eval_expr ?e ?rm ?v |- _ ] => inv H\n  end.\n\nLtac op_determ' :=\n  match goal with\n  | H:specIR.eval_op ?o ?rm ?r1, H1:specIR.eval_op ?o ?rm ?r2\n    |- _ => apply eval_op_determ with (v1 := r2) in H; inv H; subst; auto\n  end.\n\nLtac str:=\n  repeat strength_simpl; repeat op_determ'; repeat match_some; try omega; auto.\n\nLemma reg_eqb_true:\n  forall r r0,\n    reg_eqb r r0 = true -> r = r0.\nProof.\n  intros. unfold reg_eqb in H. poseq_destr r r0. auto. inv H.\nQed.\n  \n(* Because of behavior improving, we need the source to evaluate *)\nTheorem correct_strength_reduction:\n  forall e rm v1 v2,\n    specIR.eval_expr e rm v1 ->\n    specIR.eval_expr (strength_reduction e) rm v2 ->\n    v1 = v2.\nProof.\n  intros e rm v1 v2 EVAL1 EVAL2.  \n  inv EVAL1; inv EVAL.\n  - destruct binop; inv EVALV.\n    + inv EVAL2.\n      * destruct o1; destruct o2; try destruct v; inv H0; inv EVAL; try solve[str].\n        ** destruct z; inv H1; inv EVALV; str.\n        ** destruct z; inv H1; inv EVALV; str.\n        ** destruct z; destruct v0; try destruct z; inv H1; str.\n      * destruct o1; destruct o2; try destruct v; try destruct z; inv H0;\n          inv EVAL; str; try destruct v5; try inv H1; inv EVAL0; auto.\n        rewrite Z.add_0_r. auto.        \n    + inv EVAL2.\n      * destruct o1; destruct o2; inv H0; inv EVAL; try solve[str].\n        ** destruct v0. destruct v1. destruct v2.\n           destruct (reg_eqb r r0); inv H1. inv EVALV.\n           inv EVALL. inv EVALL0. match_some. inv EVALR. inv EVALR0. match_some. auto.\n        ** destruct v; inv H1. destruct z; inv H0; str.\n        ** destruct v; inv H1. destruct z; inv H0; str.\n        ** destruct v; inv H1. destruct v0. inv EVALR. inv EVALL.\n           destruct v4; destruct v5; inv H0; try solve [str]; poseq_destr p p0; inv H1; str.\n      * destruct o1; destruct o2.\n        ** destruct (op_eqb (Reg r) (Reg r0)) eqn:HEQ; inv H0. inv HEQ. apply reg_eqb_true in H0. subst.\n           inv EVALL. inv EVALR. str. rewrite Z.sub_diag. auto.\n        ** destruct v. destruct z; inv H0. str. rewrite Z.sub_0_r. auto.\n        ** destruct v. destruct z; inv H0. str.\n        ** destruct v. destruct z; inv H0; destruct v0; destruct z; inv H1; try solve[str].\n           poseq_destr p p0; inv H0; str. rewrite Z.sub_diag. auto.\n           poseq_destr p p0; inv H0; str. rewrite Z.sub_diag. auto.\n    + inv EVAL2.\n      * destruct o1; destruct o2; simpl in H0.\n        ** destruct (reg_eqb r r0); inv H0; inv EVAL; str.\n        ** destruct v. destruct z; inv H0. destruct p; inv H1; str. str.\n        ** destruct v. destruct z; inv H0. destruct p; inv H1; str. str.\n        ** destruct v; destruct v0; try destruct z; try destruct z0; inv H0; try solve[str];\n             destruct p; try destruct p0; inv H1; str.\n      * destruct o1; destruct o2; inv H0.\n        ** destruct v; inv H1. destruct z; inv H0. inv EVAL. str. rewrite Z.mul_0_r. auto.\n           destruct p; inv H1. inv EVAL. str. rewrite Z.mul_1_r. auto.\n        ** destruct v; inv H1. destruct z; inv H0; inv EVAL. str.\n           destruct p; inv H1. str. rewrite Z.mul_1_l. auto.\n        ** destruct v; destruct v0; try destruct z; try destruct z0; try destruct p; try destruct p0; inv H1; inv EVAL; str; rewrite Z.mul_1_r; auto.\n    + inv EVAL2.\n      * destruct (op_eqb o1 o2) eqn:HEQ; inv H0. inv EVAL. str.\n      * destruct (op_eqb o1 o2) eqn:HEQ; inv H0. inv EVAL. str. rewrite op_eqb_same in EVALL; eauto.\n        str. rewrite Zgtb_irrefl. auto.\n    + inv EVAL2.\n      * destruct (op_eqb o1 o2) eqn:HEQ; inv H0. inv EVAL. str.\n      * destruct (op_eqb o1 o2) eqn:HEQ; inv H0. inv EVAL. str. rewrite op_eqb_same in EVALL; eauto.\n        str. rewrite Z.ltb_irrefl. auto.\n    + inv EVAL2.\n      * destruct (op_eqb o1 o2) eqn:HEQ; inv H0. inv EVAL. str.\n      * destruct (op_eqb o1 o2) eqn:HEQ; inv H0. inv EVAL. str. rewrite op_eqb_same in EVALL; eauto.\n        str. rewrite Zgeb_refl. auto.\n    + inv EVAL2.\n      * destruct (op_eqb o1 o2) eqn:HEQ; inv H0. inv EVAL. str.\n      * destruct (op_eqb o1 o2) eqn:HEQ; inv H0. inv EVAL. str. rewrite op_eqb_same in EVALL; eauto.\n        str. rewrite Z.leb_refl. auto.\n    + inv EVAL2.\n      * destruct (op_eqb o1 o2) eqn:HEQ; inv H0. inv EVAL. str.\n      * destruct (op_eqb o1 o2) eqn:HEQ; inv H0. inv EVAL. str. rewrite op_eqb_same in EVALL; eauto.\n        str. rewrite Z.eqb_refl. auto.\n  - inv EVAL2. inv EVAL. op_determ'. unop_value_determ.\nQed.\n\n(** * Correctness of simplifying expressions  *)\n(* simp_expr does not change the result of an evaluation *)\nLemma simpl_expr_correct:\n  forall rm e v,\n    specIR.eval_expr e rm v <-> specIR.eval_expr (simpl_expr e) rm v.\nProof.\n  intros rm e v. split; intros.\n  - inv H; inv EVAL.\n    + destruct o1 eqn:HO1; destruct o2 eqn:HO2; simpl; inv HO1; try inv HO3; try constructor; try econstructor; eauto.\n      inv EVALR. inv EVALL. \n      apply eval_binop_values_correct in EVALV. rewrite EVALV. constructor. econstructor; econstructor; eauto.\n    + destruct o eqn:HO; simpl; try constructor; try econstructor; eauto.\n      apply eval_unop_value_correct in EVALV. inv EVAL0. rewrite EVALV.\n      constructor. econstructor; econstructor; eauto.\n  - inv H; inv H1.\n    + destruct e; inv H0; destruct o; inv H1; constructor; inv EVAL.\n      * econstructor; eauto.\n      * destruct o0; inv H0. econstructor; eauto. destruct (eval_binop_values b v0 v3); inv H1.\n        inv EVALL. inv EVALR. econstructor; try econstructor; eauto.\n      * destruct (eval_unop_value u v0); inv H0.\n    + destruct e; inv H0; destruct o0; inv H1; try destruct o1; try inv H0; constructor.\n      * inv EVAL. destruct (eval_binop_values b v0 v1) eqn:H; inv H1. inv EVAL0.\n        econstructor; try econstructor; eauto. apply eval_binop_values_correct. inv EVALV. auto.\n      * inv EVAL. econstructor; eauto.\n      * inv EVAL. destruct (eval_unop_value u v0) eqn:H; inv H1; inv EVAL0.\n        inv EVALV. apply eval_unop_value_correct in H. econstructor; try econstructor; eauto.\n        econstructor; eauto. econstructor.\nQed.\n\n(** * Correctness of the analysis  *)\n(* The iterative analysis is correct *)\nLemma analyze_successor:\n  forall v pc i pc' abs params,\n    kildall_constprop_analysis (ver_code v) params (ver_entry v) = Some abs ->\n    (ver_code v)#pc = Some i ->\n    In pc' (instr_succ i) ->\n    MapFlatValue.ge (absstate_get pc' abs) (constprop_transf (ver_code v) pc (absstate_get pc abs)).\nProof.\n  intros. unfold kildall_constprop_analysis in H.\n  eapply const_prop.DS.fixpoint_solution; eauto.\n  intros.\n  unfold constprop_transf.\n  assert (@PTree.get (list positive) pc (PTree.map1 instr_succ (ver_code v)) = Some (instr_succ i)).\n  { rewrite PTree.gmap1. unfold option_map. rewrite H0. auto. }\n  unfold successors_list. rewrite H2.\n  simpl. auto.\nQed.\n\nTheorem analyze_correct:\n  forall v pc i pc' abs params rm,\n    kildall_constprop_analysis (ver_code v) params (ver_entry v) = Some abs ->\n    (ver_code v)#pc = Some i ->\n    In pc' (instr_succ i) ->\n    match_regmap rm (constprop_transf (ver_code v) pc (absstate_get pc abs)) ->\n    match_regmap rm (absstate_get pc' abs).\nProof.\n  intros. eapply analyze_successor in H; eauto.\n  eapply match_regmap_increasing; eauto.\nQed.\n\nTheorem analyze_init':\n  forall rm params valist,\n    specIR.init_regs valist params = Some rm ->\n    match_regmap rm (init_arm_params params).\nProof.\n  intros. replace (init_arm_params params) with (MapFlatValue.top) by (destruct params; simpl; auto).\n  unfold match_regmap. intros r. simpl. rewrite PTree.gempty. unfold match_value. simpl.\n  destruct (rm # r); auto.\nQed.  \n  \nTheorem analyze_init:\n  forall rm v params abs valist,\n    kildall_constprop_analysis (ver_code v) params (ver_entry v) = Some abs ->\n    specIR.init_regs valist params = Some rm ->\n    match_regmap rm (absstate_get (ver_entry v) abs).\nProof.\n  unfold kildall_constprop_analysis. intros rm v params abs valist FIX INIT.\n  assert (A: MapFlatValue.ge (absstate_get (ver_entry v) abs) (init_arm_params params)).\n  { eapply const_prop.DS.fixpoint_entry; eauto. left. auto. }\n  eapply match_regmap_increasing; eauto.\n  eapply analyze_init'; eauto.\nQed.\n  \n(** *  Matching stacks and properties *)\n(* identical stackframes except that the unoptimized version MAY be replaced with the optimized one *)\nInductive match_stackframe (v:version) (params:list reg): stackframe -> stackframe -> Prop :=\n| frame_same:\n    forall sf, (match_stackframe v params) sf sf\n| frame_opt:\n    forall r vopt lbl rm abs,\n      constant_propagation_version v params = OK vopt ->\n      kildall_constprop_analysis (ver_code v) params (ver_entry v) = Some abs ->\n      (forall val, match_regmap (rm # r <- val) (absstate_get lbl abs)) ->\n      (match_stackframe v params) (Stackframe r v lbl rm) (Stackframe r vopt lbl rm).\n\n(* Generalizing match_stackframe to the entire stack *)\nInductive match_stack (v:version) (params:list reg): stack -> stack -> Prop :=\n| match_nil:\n    (match_stack v params) nil nil\n| match_cons:\n    forall s s' sf sf'\n      (MS: (match_stack v params) s s')\n      (MSF: (match_stackframe v params) sf sf'),\n      (match_stack v params) (sf::s) (sf'::s').\n\n(* Creating synth frames in the new program yields matching results *)\nLemma match_synth_frames:\n  forall p rm sl synth fidoptim func currver vopt synthopt,\n    specIR.synthesize_frame p rm sl synth ->\n    find_function fidoptim p = Some func ->\n    current_version func = currver ->\n    constant_propagation_version currver (fn_params func) = OK vopt ->\n    specIR.synthesize_frame (set_version p fidoptim vopt) rm sl synthopt ->\n    (match_stack currver (fn_params func)) synth synthopt.\nProof.\n  intros p rm sl synth fidoptim func currver vopt synthopt SYNTH FINDF CURRVER CSTPROP SYNTHOPT.\n  generalize dependent synthopt.\n  induction SYNTH; intros. inv SYNTHOPT. constructor.\n  inv SYNTHOPT. constructor.\n  - apply IHSYNTH; auto.\n  - eapply update_regmap_determ in UPDATE; eauto. subst.\n    erewrite <- base_version_unchanged in FINDV0; eauto. rewrite FINDV in FINDV0. inv FINDV0. constructor.\nQed.\n\nLemma match_stack_same:\n  forall s v params,\n    match_stack v params s s.\nProof.\n  intros s v params. induction s.\n  - constructor.\n  - constructor. auto. constructor.\nQed.\n\nLemma match_synth:\n  forall p rm sl synth fidoptim func currver vopt,\n    specIR.synthesize_frame p rm sl synth ->\n    find_function fidoptim p = Some func ->\n    current_version func = currver ->\n    constant_propagation_version currver (fn_params func) = OK vopt ->\n    exists synthopt, specIR.synthesize_frame (set_version p fidoptim vopt) rm sl synthopt /\\\n                (match_stack currver (fn_params func)) synth synthopt.\nProof.\n  intros. exists synth. erewrite synth_frame_unchanged in H. split. eauto.\n  apply match_stack_same.\nQed.\n\n(* Adding the same synthesized frames to the stack preserves match_stack *)\nLemma match_app:\n  forall synth s s' v params,\n    (match_stack v params) s s' ->\n    (match_stack v params) (synth++s) (synth++s').\nProof.\n  intros. induction synth.\n  - simpl. auto.\n  - repeat rewrite <- app_comm_cons. apply match_cons. auto. constructor.\nQed.\n\nLemma app_match:\n  forall synth synthopt s s' v params,\n    (match_stack v params) s s' ->\n    (match_stack v params) synth synthopt ->\n    (match_stack v params) (synth++s) (synthopt++s').\nProof.\n  intros. induction H0.\n  - simpl. auto.\n  - repeat rewrite <- app_comm_cons. apply match_cons; auto.\nQed.\n\n(** * Match states relation  *)\n(* This proof is a lockstep forward internal loud simulation.\n   Each step of the source is matched with a step of the optimized program.\n   No index is needed for the match_states invariant.\n\n<<\n                 \n       st1 --------------- st2\n        |                   |\n       t|                   |t\n        |                   |\n        v                   v\n       st1'--------------- st2'\n                 \n>>\n*)\n\n(* The mixed lockstep simulation relation *)\nInductive match_states (p:program) (v:version) (params:list reg) : unit -> specIR.state -> specIR.state -> Prop :=\n| lock_match:\n    forall s s' vopt pc rm ms abs\n      (CST_PROP: constant_propagation_version v params = OK vopt)\n      (ANALYSIS: kildall_constprop_analysis (ver_code v) params (ver_entry v) = Some abs)\n      (MATCHSTACK: (match_stack v params) s s')\n      (MATCHRM: match_regmap rm (absstate_get pc abs)),\n      (match_states p v params) tt (State s v pc rm ms) (State s' vopt pc rm ms)\n| lock_refl_state:\n    forall s s' l rm ms v'\n      (MATCHSTACK: (match_stack v params) s s'),\n      (match_states p v params) tt (State s v' l rm ms) (State s' v' l rm ms)\n| lock_refl_final:\n    forall retval ms,\n      (match_states p v params) tt (Final retval ms) (Final retval ms).\n\nLemma lock_refl:\n  forall s p v params,\n    (match_states p v params) tt s s.\nProof.\n  intros. destruct s.\n  eapply lock_refl_state. apply match_stack_same.\n  constructor.\nQed.\n\n(** * Code preservation *)\n(* Code is preserved by the optimization *)\nLemma code_preserved:\n  forall v params vopt i pc abs,\n    constant_propagation_version v params = OK vopt ->\n    kildall_constprop_analysis (ver_code v) params (ver_entry v) = Some abs ->\n    (ver_code v) # pc = Some i ->\n    (ver_code vopt) # pc = Some (transf_instr abs pc i).\nProof.\n  intros. unfold constant_propagation_version in H. repeat do_ok. inv H0. simpl.\n  rewrite PTree.gmap. unfold option_map. rewrite H1. auto.\nQed.\n\nLtac code_preserved:=\n  match goal with\n  | [ H: (ver_code ?v)#?pc = Some ?i |- _ ] => eapply code_preserved in H; eauto; try unfold transf_instr in H\n  end.\n\n(** * Order and index of the simulation  *)\nInductive order : unit -> unit -> Prop := .\n\nLemma wfounded:\n  well_founded order.\nProof.\n  unfold well_founded. intros. destruct a. constructor. intros. inv H.\nQed.  \n\n(** * Preservation of deopt conditions  *)\nLemma deopt_cond_preserved_refl:\n  forall s v pc rm ms s' p fidoptim vopt next synth newver la newrm params v',\n    deopt_conditions p (State s v' pc rm ms) next synth newver la newrm ->\n    match_stack v params s s' ->\n    deopt_conditions (set_version p fidoptim vopt) (State s' v' pc rm ms) next synth newver la newrm.\nProof.\n  intros s v pc rm ms s' p fidoptim vopt next synth newver la newrm params v' COND MS. inv COND.    \n  eapply synth_frame_unchanged with (f:=fidoptim) (v:=vopt) in SYNTH.\n  econstructor; eauto.\n  erewrite <- base_version_unchanged. auto.\nQed.\n\nLemma deopt_cond_preserved_match:\n  forall p s v pc rm ms next synth newver la newrm s' vopt abs params fidoptim,\n    deopt_conditions p (State s v pc rm ms) next synth newver la newrm ->\n    constant_propagation_version v params = OK vopt ->\n    kildall_constprop_analysis (ver_code v) params (ver_entry v) = Some abs ->\n    match_regmap rm (absstate_get pc abs) ->\n    deopt_conditions (set_version p fidoptim vopt) (State s' vopt pc rm ms) next synth newver la newrm.\nProof.\n  intros p s v pc rm ms next synth newver la newrm s' vopt abs params fidoptim COND CONSPROP KILDALL MRM.\n  inv COND. eapply synth_frame_unchanged with (f:=fidoptim) (v:=vopt) in SYNTH.\n  econstructor.\n  - code_preserved. simpl in CODE. eauto.\n  - rewrite <- base_version_unchanged. auto.\n  - eapply strength_reduction_transf_vm_correct.\n    eapply transf_vm_correct; eauto.\n  - eauto.\nQed.\n\nLemma deopt_cond_preserved:\n  forall p v fidoptim vopt params s s' next synth newver la newrm i\n    (COND: deopt_conditions p s next synth newver la newrm)\n    (CONSTPROP: constant_propagation_version v params = OK vopt)\n    (MATCH: (match_states p v params) i s s'),\n    deopt_conditions (set_version p fidoptim vopt) s' next synth newver la newrm.\nProof.\n  intros p v fidoptim vopt params s s' next synth newver la newrm i COND CONSTPROP MATCH.\n  inv MATCH.\n  - rewrite CST_PROP in CONSTPROP. inv CONSTPROP. eapply deopt_cond_preserved_match; eauto.\n  - eapply deopt_cond_preserved_refl; eauto.\n  - inv COND.\nQed.\n\n(** * Lowered forward diagram  *)\nLemma lowered_fwd:\n  forall s1 s2 p t s1' fidoptim f vopt\n    (MATCH: (match_states p (current_version f) (fn_params f) tt) s1 s2)\n    (CST : constant_propagation_version (current_version f) (fn_params f) = OK vopt)\n    (FINDF : find_function fidoptim p = Some f)\n    (STEP: lowered_step p s1 t s1'),\n  exists s2', lowered_step (set_version p fidoptim vopt) s2 t s2' /\\ (match_states p (current_version f) (fn_params f) tt) s1' s2'.\nProof.\n  intros s1 s2 p t s1' fidoptim f vopt MATCH CST FINDF STEP.\n  assert (CSTV: constant_propagation_version (current_version f) (fn_params f) = OK vopt) by auto.\n  unfold constant_propagation_version in CST. repeat do_ok. rename HDO0 into KILDALL.\n  inv MATCH.\n  -                             (* match *)\n    (* In that case we relate the execution of the optimized version to the execution of the source *)\n    rewrite KILDALL in ANALYSIS. inv ANALYSIS.\n    inv STEP.\n    + exists (State s' vopt next rm ms). split. (* Nop *)\n      * eapply exec_Nop; eauto. code_preserved. simpl in CODE. eauto.\n      * eapply lock_match; eauto. eapply analyze_correct; eauto. simpl; auto.\n        unfold constprop_transf. rewrite CODE. auto.\n    + exists (State s' vopt next (rm # reg <- v) ms). split. (* Op *)\n      * code_preserved.\n        assert (R: exists expr', replace_ops (absstate_get pc abs) (Op expr reg next) = Op expr' reg next /\\ specIR.eval_expr expr' rm v).\n        { eapply replace_expr_correct in EVAL; eauto.\n          exists (transf_expr (replace_op (absstate_get pc abs)) expr). simpl. split; auto. }\n        destruct R as [expr' [REPLACE EVAL']]. rewrite REPLACE in CODE. eapply exec_Op. simpl in CODE.\n        eapply CODE. apply strength_reduction_correct. apply simpl_expr_correct in EVAL'. auto.\n      * econstructor; eauto. eapply analyze_correct; eauto. simpl; auto.\n        unfold constprop_transf. rewrite CODE. apply match_regmap_update; auto.\n        eapply eval_expr_abs_correct; eauto.\n    + exists (State s' vopt next newrm ms). split. (* MoveList *)\n      * code_preserved.\n        assert (R: exists vm', replace_ops (absstate_get pc abs) (Move ml next) = Move vm' next /\\ specIR.update_movelist vm' rm newrm).\n        { eapply transf_ml_correct in UPDATE; eauto.\n          exists (transf_ml (transf_expr (replace_op (absstate_get pc abs))) ml). simpl. split; auto. }\n        destruct R as [vm' [REPLACE EVAL']]. rewrite REPLACE in CODE. eapply exec_Move. simpl in CODE. eapply CODE.\n        apply strength_reduction_transf_ml_correct. auto.\n      * econstructor; eauto. eapply analyze_correct; eauto. simpl; auto.\n        unfold constprop_transf. rewrite CODE.\n        eapply match_regmap_update_movelist; eauto.\n    + exists (State s' vopt (pc_cond v iftrue iffalse) rm ms). split. (* Cond *)\n      * code_preserved.\n        assert (R: exists expr', replace_ops (absstate_get pc abs) (Cond expr iftrue iffalse) = Cond expr' iftrue iffalse /\\ specIR.eval_expr expr' rm v).\n        { eapply replace_expr_correct in EVAL; eauto.\n          exists (transf_expr (replace_op (absstate_get pc abs)) expr). simpl. split; auto. }\n        destruct R as [expr' [REPLACE EVAL']]. rewrite REPLACE in CODE. simpl in CODE.\n        { destruct (simpl_expr expr') as [binexpr|[ | | ]] eqn:SIMPL.\n          - eapply exec_Cond; eauto. rewrite <- SIMPL; auto. apply strength_reduction_correct.\n            rewrite <- simpl_expr_correct. auto.\n          - eapply exec_Cond; eauto. rewrite <- SIMPL; auto. apply strength_reduction_correct.\n            rewrite <- simpl_expr_correct. auto.\n          - eapply exec_Cond; eauto. rewrite <- SIMPL; auto. apply strength_reduction_correct.\n            rewrite <- simpl_expr_correct; auto.\n          - destruct o.\n            + eapply exec_Cond; eauto. rewrite <- SIMPL. apply strength_reduction_correct.\n              rewrite <- simpl_expr_correct. auto.\n            + destruct v0. destruct z.\n              * simpl in CODE. apply simpl_expr_correct in EVAL'. rewrite SIMPL in EVAL'.\n                inv EVAL'. inv EVAL0. inv EVALV. inv EVAL1. eapply exec_Nop; eauto.\n              * simpl in CODE. apply simpl_expr_correct in EVAL'. rewrite SIMPL in EVAL'.\n                inv EVAL'. inv EVAL0. inv EVALV. inv EVAL1. eapply exec_Nop; eauto.\n              * simpl in CODE. apply simpl_expr_correct in EVAL'. rewrite SIMPL in EVAL'.\n                inv EVAL'. inv EVAL0. inv EVALV. inv EVAL1. eapply exec_Nop; eauto. }\n      * econstructor; eauto. eapply analyze_correct; eauto. simpl; auto.\n        destruct v; simpl; destruct z; auto. \n        unfold constprop_transf. rewrite CODE. auto.\n    + { poseq_destr fid fidoptim. (* Call *)\n        - (* calling the optimized function *)\n          exists (State (Stackframe retreg vopt next rm :: s') vopt (ver_entry vopt) newrm ms).\n          rewrite FINDF0 in FINDF. inv FINDF.\n          split.\n          + code_preserved. simpl in CODE.\n            eapply exec_Call. apply CODE.\n            eapply find_function_same; eauto.\n            rewrite CSTV in CST_PROP. inv CST_PROP.\n            apply current_version_same.\n            eapply strength_reduction_evalist_correct; eauto.\n            eapply replace_expr_evalist_correct; eauto.\n            simpl. auto.\n          + assert (H0: ver_entry vopt = ver_entry (current_version f)).\n            { rewrite CSTV in CST_PROP. inv CST_PROP. simpl. auto. } rewrite H0. \n            eapply lock_match; eauto. constructor; auto.\n            econstructor; eauto.\n            intros. eapply analyze_correct; eauto; simpl; auto.\n            unfold constprop_transf. rewrite CODE.\n            eapply match_regmap_update; eauto. constructor.\n            eapply analyze_init; eauto.            \n        - (* calling another function *)\n          exists (State (Stackframe retreg vopt next rm :: s') (current_version func) (ver_entry (current_version func)) newrm ms). split.\n          + code_preserved. simpl in CODE.\n            eapply exec_Call; eauto. erewrite <- find_function_unchanged; eauto.\n            apply strength_reduction_evalist_correct.\n            apply replace_expr_evalist_correct; auto.\n          + econstructor; eauto; constructor; auto. econstructor; eauto.\n            intros. eapply analyze_correct; eauto; simpl; auto.\n            unfold constprop_transf. rewrite CODE.\n            eapply match_regmap_update; eauto. constructor. }\n    + destruct s' as [|sf s0']. inv MATCHSTACK. (* Return *)\n      assert (R: exists retex', (replace_ops (absstate_get pc abs) (IReturn retex)) = IReturn retex' /\\ specIR.eval_expr retex' rm retval).\n      { eapply replace_expr_correct in EVAL; eauto.\n        exists (transf_expr (replace_op (absstate_get pc abs)) retex). split; auto. }\n      destruct R as [retex' [REPLACE EVAL']]. inv MATCHSTACK. inv MSF.\n      * { exists (State s0' fprev next (rmprev # retreg <- retval) ms). split.\n          * code_preserved.\n            rewrite REPLACE in CODE. simpl in CODE.\n            eapply exec_Return; eauto. eapply strength_reduction_correct; eauto.\n          * constructor; auto. }\n      * { exists (State s0' vopt0 next (rmprev # retreg <- retval) ms). split.\n          * code_preserved. rewrite KILDALL in H5. inv H5.\n            rewrite REPLACE in CODE. simpl in CODE.\n            rewrite CST_PROP in H4. inv H4.\n            eapply exec_Return; eauto. eapply strength_reduction_correct; eauto.\n          * eapply lock_match; eauto. }\n    + exists (Final retval ms). split. \n      code_preserved. inv MATCHSTACK.\n      assert (R: exists retex', (replace_ops (absstate_get pc abs) (IReturn rex)) = IReturn retex' /\\ specIR.eval_expr retex' rm retval).\n      { eapply replace_expr_correct in EVAL; eauto.\n        exists (transf_expr (replace_op (absstate_get pc abs)) rex). split; auto. }\n      destruct R as [retex' [REPLACE EVAL']]. rewrite REPLACE in CODE. simpl in CODE.\n      eapply exec_Return_Final; eauto. eapply strength_reduction_correct; eauto.\n      constructor.\n    + exists (State s' vopt next rm ms). split. (* Printexpr *)\n      * code_preserved.\n        assert (R: exists expr', replace_ops (absstate_get pc abs) (Printexpr expr next) = Printexpr expr' next /\\ specIR.eval_expr expr' rm printval).\n        { eapply replace_expr_correct in EVAL; eauto.\n          exists (transf_expr (replace_op (absstate_get pc abs)) expr). simpl. split; auto. }\n        destruct R as [expr' [REPLACE EVAL']].\n        rewrite REPLACE in CODE. simpl in CODE. eapply exec_Printexpr; eauto.\n        apply strength_reduction_correct. auto.\n      * econstructor; eauto.\n        eapply analyze_correct; eauto.\n        simpl; auto. unfold constprop_transf. rewrite CODE. auto.\n    + exists (State s' vopt next rm ms). split. (* Printstring *)\n      * constructor; auto. code_preserved.\n      * eapply lock_match; eauto. eapply analyze_correct; eauto. simpl; auto.\n        unfold constprop_transf. rewrite CODE. auto.\n    + exists (State s' vopt next rm newms). split. (* Store *)\n      * assert (R: exists expr1', exists expr2', (replace_ops (absstate_get pc abs) (Store expr1 expr2 next)) = Store expr1' expr2' next /\\ specIR.eval_expr expr1' rm val /\\ specIR.eval_expr expr2' rm  addr).\n        { eapply replace_expr_correct in EVAL_ST; eauto. eapply replace_expr_correct in EVAL_AD; eauto.\n          exists (transf_expr (replace_op (absstate_get pc abs)) expr1).\n          exists (transf_expr (replace_op (absstate_get pc abs)) expr2).\n          split; auto. }\n        destruct R as [expr1' [expr2' [REPLACE [EVAL1 EVAL2]]]].\n        code_preserved. rewrite REPLACE in CODE. simpl in CODE.\n        eapply exec_Store; eauto; eapply strength_reduction_correct; eauto.\n      * econstructor; eauto. eapply analyze_correct; eauto. simpl; auto.\n        unfold constprop_transf. rewrite CODE. auto.      \n    + exists (State s' vopt next (rm # reg <- val) ms). split. (* Load *)\n      * code_preserved.\n        assert (R: exists expr', (replace_ops (absstate_get pc abs) (Load expr reg next)) = Load expr' reg next /\\ specIR.eval_expr expr' rm addr).\n        { eapply replace_expr_correct in EVAL; eauto.\n          exists (transf_expr (replace_op (absstate_get pc abs)) expr). simpl; auto. }\n        destruct R as [expr' [REPLACE EVAL']]. rewrite REPLACE in CODE; simpl in CODE.\n        eapply exec_Load; eauto. eapply strength_reduction_correct; eauto.\n      * econstructor; eauto. eapply analyze_correct; eauto; simpl; auto.\n        unfold constprop_transf. rewrite CODE.\n        apply match_regmap_update; auto. constructor.\n    + exists (State s' vopt next rm ms). split. (* Assume holds *)\n      * code_preserved.\n        assert (R: exists le', (replace_ops (absstate_get pc abs) (Assume le tgt vm sl next)) = Assume le' tgt (transf_vm (transf_expr (replace_op (absstate_get pc abs))) vm) sl next /\\ specIR.eval_list_expr le' rm true).\n        { eapply replace_expr_list_correct in ASSUME_TRUE; eauto.\n          exists (transf_expr_list (replace_op (absstate_get pc abs)) le). destruct tgt. simpl; auto. }\n        destruct R as [le' [REPLACE EVAL]]. rewrite REPLACE in CODE. simpl in CODE.\n        { destruct le' as [| e' le']; simpl in CODE.\n          - eapply exec_Nop; eauto. destruct tgt. simpl in CODE. eauto.\n          - destruct tgt. eapply exec_Assume_holds; eauto.\n            apply strength_reduction_list_correct in EVAL. simpl in EVAL. auto. }\n      * econstructor; eauto. eapply analyze_correct; eauto. simpl; auto.\n        unfold constprop_transf. rewrite CODE. destruct tgt. apply match_regmap_assert; auto.\n    + eapply match_synth in SYNTH; try eapply CONST_PROP; eauto. (* Assume fails *)\n      destruct SYNTH as [synthopt [SYN MATCH]].\n      exists (State (synthopt ++ s') newver la newrm ms). split.\n      * assert (R: exists le', (replace_ops (absstate_get pc abs) (Assume le (fa,la) vm sl next)) = Assume le' (fa,la) (transf_vm (transf_expr (replace_op (absstate_get pc abs))) vm) sl next /\\ specIR.eval_list_expr le' rm false).\n        { eapply replace_expr_list_correct in ASSUME_FAILS; eauto.\n          exists (transf_expr_list (replace_op (absstate_get pc abs)) le). simpl; split; auto. }\n        destruct R as [le' [REPLACE EVAL]]. code_preserved. rewrite REPLACE in CODE. simpl in CODE.\n        destruct le' as [|e' le']. inv EVAL.\n        eapply exec_Assume_fails; eauto.\n        ** apply strength_reduction_list_correct in EVAL. simpl in EVAL. auto.\n        ** rewrite <- base_version_unchanged. auto.\n        ** apply strength_reduction_transf_vm_correct.\n           apply transf_vm_correct. auto. auto.\n        ** rewrite CSTV in CST_PROP. inv CST_PROP. auto.\n      * econstructor; eauto. apply app_match; auto.      \n      \n  -                             (* refl *)\n    (* Here, both programs are in the same state (except parts of the stackframe) *)\n    inv STEP.\n    + exists (State s' v' next rm ms). split. eapply exec_Nop; eauto. constructor; auto.\n    + exists (State s' v' next (rm # reg <- v) ms). split. eapply exec_Op; eauto. constructor; auto.\n    + exists (State s' v' next newrm ms). split. eapply exec_Move; eauto. constructor; auto.\n    + exists (State s' v' (pc_cond v iftrue iffalse) rm ms). split. eapply exec_Cond; eauto. constructor; auto.\n    + {\n        poseq_destr fid fidoptim.\n        - (* calling the optimized function *)\n          set (vopt := {| ver_code := PTree.map (transf_instr a) (ver_code (current_version f)); ver_entry := ver_entry (current_version f) |}).\n          rewrite FINDF0 in FINDF. inv FINDF.\n          exists (State (Stackframe retreg v' next rm::s') vopt (ver_entry (current_version f)) newrm ms). split.\n          + assert (ver_entry vopt = ver_entry (current_version f)).\n            { unfold vopt. simpl. auto. } rewrite <- H.\n            eapply exec_Call. apply CODE.\n            eapply find_function_same; eauto.\n            apply current_version_same.\n            apply EVALL. simpl. auto.\n          + eapply lock_match; eauto. constructor; auto.\n            constructor; auto. eapply analyze_init; eauto.\n        - (* calling another function *)\n          exists (State (Stackframe retreg v' next rm ::s') (current_version func) (ver_entry (current_version func)) newrm ms).\n          split.\n          + eapply exec_Call; eauto. erewrite <- find_function_unchanged; eauto.\n          + constructor; auto. constructor; auto. constructor. }\n    + destruct s' as [|sf' s']; inv MATCHSTACK. inv MSF.\n      * exists (State s' fprev next (rmprev # retreg <- retval) ms). split. \n        eapply exec_Return; eauto. constructor; auto.\n      * exists (State s' vopt next (rmprev # retreg <- retval) ms). split.\n        eapply exec_Return; eauto. eapply lock_match; eauto.\n    + exists (Final retval ms). split. inv MATCHSTACK. eapply exec_Return_Final; eauto. constructor. \n    + exists (State s' v' next rm ms). split. eapply exec_Printexpr; eauto. constructor; auto.\n    + exists (State s' v' next rm ms). split. eapply exec_Printstring; auto. constructor; auto.\n    + exists (State s' v' next rm newms). split. eapply exec_Store; eauto. constructor; auto.\n    + exists (State s' v' next (rm # reg <- val) ms). split. eapply exec_Load; eauto. constructor; auto.\n    + exists (State s' v' next rm ms). split. eapply exec_Assume_holds; eauto. constructor; auto.\n    + eapply match_synth in SYNTH; eauto.\n      * destruct SYNTH as [synthopt [SYN MATCH]].\n        exists (State (synthopt ++ s') newver la newrm ms). split. \n        eapply exec_Assume_fails with (synth:=synthopt); eauto.\n        rewrite <- base_version_unchanged. auto.\n        constructor; auto. apply app_match; auto.\n  - inv STEP.                   (* final *)\nQed.\n\n(** * Loud Forward simulation  *)\nLemma loud_fwd:\n  forall s1 s2 p t s1' fidoptim f vopt\n    (MATCH: (match_states p (current_version f) (fn_params f) tt) s1 s2)\n    (CST : constant_propagation_version (current_version f) (fn_params f) = OK vopt)\n    (FINDF : find_function fidoptim p = Some f)\n    (STEP: loud_step p s1 t s1'),\n  exists s2', loud_step (set_version p fidoptim vopt) s2 t s2' /\\ (match_states p (current_version f) (fn_params f) tt) s1' s2'.\nProof.\n  intros s1 s2 p t s1' fidoptim f vopt MATCH CST FINDF STEP.\n  assert (CSTV: constant_propagation_version (current_version f) (fn_params f) = OK vopt) by auto.\n  unfold constant_propagation_version in CST. repeat do_ok. rename HDO0 into KILDALL.\n  inv STEP.\n  - eapply lowered_fwd in STEP0 as [s2' [STEP MATCH']]; eauto.\n    exists s2'. split; auto. constructor; eauto.\n  -                             (* Framestate Go_on *)\n    eapply deopt_cond_preserved with (fidoptim:=fidoptim) in DEOPT_COND as COND_OPT; eauto.\n    inv MATCH.\n    +                           (* match *)\n      rewrite ANALYSIS in KILDALL. inv KILDALL.\n      exists (State s' vopt next rm ms). rewrite CST_PROP in CSTV. inv CSTV. split.\n      * eapply loud_exec_Framestate_go_on; eauto.\n      * inv DEOPT_COND. eapply lock_match; eauto. eapply analyze_correct; eauto.\n        simpl. left. auto. unfold constprop_transf. rewrite CODE. auto.\n    +                           (* refl *)\n      exists (State s' f0 next rm ms). split.\n      * eapply loud_exec_Framestate_go_on; eauto.\n      * eapply lock_refl_state; eauto.\n  -                             (* Framestate_Deopt *)\n    eapply deopt_cond_preserved with (fidoptim:=fidoptim) in DEOPT_COND as COND_OPT; eauto.\n    inv MATCH.\n    +                           (* match *)\n      rewrite ANALYSIS in KILDALL. inv KILDALL.\n      exists (State (synth++s') newver la newrm ms). rewrite CST_PROP in CSTV. inv CSTV. split.\n      * eapply loud_exec_Framestate_deopt; eauto.\n      * inv DEOPT_COND. eapply lock_refl_state; eauto. apply match_app. auto.\n    +                           (* refl *)\n      exists (State (synth++s') newver la newrm ms). split.\n      * eapply loud_exec_Framestate_deopt; eauto.\n      * eapply lock_refl_state; auto. apply match_app. auto.\nQed.\n \n\n(** * Forward Loud Simulation  *)\nTheorem constprop_correct_loud:\n  forall p fid newp,\n    constant_propagation fid p = OK newp ->\n    forward_internal_loud_simulation p newp.\nProof.\n  intros p fidoptim newp CST. unfold constant_propagation in CST. repeat do_ok.\n  rename HDO1 into FINDF. rename HDO0 into CST.\n  apply Forward_internal_loud_simulation with (fsim_index:=unit) (fsim_order:=order) (fsim_match_states:=match_states p (current_version f) (fn_params f)).\n  - apply wfounded.\n  - assert (CSTV: constant_propagation_version (current_version f) (fn_params f) = OK v) by auto.\n    unfold constant_propagation_version in CST. repeat do_ok. rename HDO0 into KILDALL.\n    unfold reflexive_forge. intros synchro stack r1 s1 ms FORGE.\n    destruct synchro; simpl in FORGE; repeat do_ok; simpl.\n    + poseq_destr f0 fidoptim.  (* is the called function the optimized one? *)\n      * erewrite find_function_same; eauto. simpl. rewrite HDO0. simpl. repeat (esplit; eauto).\n        simpl. rewrite current_version_same. rewrite FINDF in HDO1. inv HDO1.\n        eapply lock_match; eauto. apply match_stack_same. eapply analyze_init; eauto.\n        apply init_regs_correct in HDO0. eauto.\n      * erewrite <- find_function_unchanged; eauto. rewrite HDO1. simpl. rewrite HDO0. simpl.\n        repeat (esplit; eauto). constructor. apply match_stack_same.\n    + destruct stack; try destruct s; inv FORGE.\n      * repeat (esplit; eauto). constructor.\n      * repeat (esplit; eauto). simpl. constructor. apply match_stack_same.\n    + destruct d. repeat do_ok. simpl. rewrite <- base_version_unchanged. rewrite HDO0. simpl.\n      repeat (esplit; eauto). simpl. constructor. apply match_stack_same.\n    + inv FORGE. exists r1. exists s1. split; auto. exists tt. destruct r1; constructor. apply match_stack_same.\n  - intros i s1 s2 r H H0. inv H0. inv H. constructor.\n  - intros s1 t s1' STEP i s2 MATCH. exists tt. destruct i.\n    eapply loud_fwd in STEP as [s2' [STEP' MATCH']]; eauto.\n    exists s2'. split.\n    + left. apply plus_one. auto.\n    + apply MATCH'.\nQed.\n\n(** * Backward Simulation *)\nTheorem constprop_correct:\n  forall p fidoptim newp,\n    constant_propagation fidoptim p = OK (newp) ->\n    backward_internal_simulation p newp.\nProof.\n  intros p fidoptim newp CST. apply fwd_loud. eapply constprop_correct_loud; eauto.\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/const_prop_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.25589979671206836}}
{"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 := Semantics.Make E.\n\n  Section TopSection.\n\n    Require Import Bedrock.Platform.Cito.SemanticsExpr.\n\n    Local Infix \";;\" := Syntax.Seq (right associativity, at level 95).\n    Local Notation skip := Syntax.Skip.\n\n    Hint Constructors Semantics.RunsTo.\n    Hint Unfold Safe RunsTo.\n\n    Require Import Bedrock.Platform.AutoSep.\n\n    Ltac invert :=\n      match goal with\n        | [ H : Safe _ _ _ |- _ ] => inversion_clear H; []\n        | [ H : RunsTo _ _ _ _ |- _ ] => inversion_clear H; []\n        | [ H : Semantics.Safe _ _ _ |- _ ] => inversion_clear H; []\n        | [ H : Semantics.RunsTo _ _ _ _ |- _ ] => inversion_clear H; []\n      end; intuition (subst; unfold vals in *; try congruence).\n\n    Ltac t := intros; repeat invert; repeat (eauto; econstructor).\n\n    Lemma Safe_Seq_Skip : forall fs k v, Safe fs (skip ;; k) v -> Safe fs k v.\n      t.\n    Qed.\n\n    Lemma RunsTo_Seq_Skip : forall fs k v v', RunsTo fs k v v' -> RunsTo fs (skip ;; k) v v'.\n      t.\n    Qed.\n\n    Lemma Safe_Seq_assoc : forall fs a b c v, Safe fs ((a ;; b) ;; c) v -> Safe fs (a ;; b;; c) v.\n      t.\n    Qed.\n\n    Lemma RunsTo_Seq_assoc : forall fs a b c v v', RunsTo fs (a ;; b ;; c) v v' -> RunsTo fs ((a ;; b) ;; c) v v'.\n      t.\n    Qed.\n\n    Lemma Safe_Seq_If_true : forall fs e t f k v, Safe fs (Syntax.If e t f ;; k) v -> wneb (eval (fst v) e) $0 = true -> Safe fs (t ;; k) v.\n      t.\n    Qed.\n\n    Lemma RunsTo_Seq_If_true : forall fs e t f k v v', RunsTo fs (t ;; k) v v' -> wneb (eval (fst v) e) $0 = true -> RunsTo fs (Syntax.If e t f ;; k) v v'.\n      t.\n    Qed.\n\n    Lemma Safe_Seq_If_false : forall fs e t f k v, Safe fs (Syntax.If e t f ;; k) v -> wneb (eval (fst v) e) $0 = false -> Safe fs (f ;; k) v.\n      t.\n    Qed.\n\n    Lemma RunsTo_Seq_If_false : forall fs e t f k v v', RunsTo fs (f ;; k) v v' -> wneb (eval (fst v) e) $0 = false -> RunsTo fs (Syntax.If e t f ;; k) v v'.\n      t.\n    Qed.\n\n    Lemma Safe_Seq_While_false : forall fs e s k v, Safe fs (Syntax.While e s ;; k) v -> wneb (eval (fst v) e) $0 = false -> Safe fs k v.\n      t.\n    Qed.\n\n    Lemma RunsTo_Seq_While_false : forall fs e s k v v', RunsTo fs k v v' -> wneb (eval (fst v) e) $0 = false -> RunsTo fs (Syntax.While e s ;; k) v v'.\n      t.\n    Qed.\n\n    Lemma RunsTo_Seq_While_true : forall fs e s k v v', RunsTo fs (s ;; Syntax.While e s ;; k) v v' -> wneb (eval (fst v) e) $0 = true -> RunsTo fs (Syntax.While e s ;; k) v v'.\n      t.\n    Qed.\n\n    Lemma Safe_Seq_While_true : forall fs e s k v, Safe fs (Syntax.While e s ;; k) v -> wneb (eval (fst v) e) $0 = true -> Safe fs (s ;; Syntax.While e s ;; k) v.\n      intros.\n      invert.\n      inversion H1; clear H1; intros.\n      subst loop0 loop1; subst.\n      econstructor; eauto.\n      intros.\n      econstructor; eauto.\n      rewrite H5 in H0; intuition.\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/SemanticsFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.25588953187816704}}
{"text": "(* Distributed under the terms of the MIT license. *)\nRequire Import ssreflect ssrbool.\nRequire PeanoNat.\nFrom MetaCoq.Template Require Import config utils Ast AstUtils Induction\n     UnivSubst WfAst Reflect Typing.\nFrom Equations Require Import Equations.\n\nImplicit Types (cf : checker_flags).\n\nExisting Class wf.\n\n(** * Well-formedness of terms and types in typing derivations\n\n  The internal representation of terms is not canonical, so we show\n  that only well-formed terms and types can appear in typing derivations\n  and the global context.\n*)\n\nLemma All_local_env_wf_decl Σ :\n  forall (Γ : context),\n    All (wf_decl Σ) Γ -> All_local_env (wf_decl_pred Σ) Γ.\nProof.\n  intros Γ X.\n  induction Γ in X |- *.\n  - constructor; eauto.\n  - destruct a as [na [body|] ty].\n    + econstructor.\n      * apply IHΓ. inv X; eauto.\n      * red. inv X. split.\n        -- apply X0.\n        -- constructor.\n      * red. inv X. eauto.\n    + econstructor.\n      * apply IHΓ. inv X; eauto.\n      * red. inv X. split.\n        -- apply X0.\n        -- constructor.\nQed.\n\nLemma on_global_decl_impl `{checker_flags} Σ P Q kn d :\n  (forall Σ Γ t T, on_global_env cumul_gen P Σ.1 -> P Σ Γ t T -> Q Σ Γ t T) ->\n  on_global_env cumul_gen P Σ.1 ->\n  on_global_decl cumul_gen P Σ kn d -> on_global_decl cumul_gen Q Σ kn d.\nProof. intros; now eapply (on_global_decl_impl cumul_gen P). Qed.\n\nLemma on_global_env_impl `{checker_flags} Σ P Q :\n  (forall Σ Γ t T, on_global_env cumul_gen P Σ.1 -> P Σ Γ t T -> Q Σ Γ t T) ->\n  on_global_env cumul_gen P Σ -> on_global_env cumul_gen Q Σ.\nProof. intros; now eapply (on_global_env_impl cumul_gen P). Qed.\n\nLemma All_local_env_wf_decl_inv Σ (a : context_decl) (Γ : list context_decl)\n         (X : All_local_env (wf_decl_pred Σ) (a :: Γ)) :\n    on_local_decl (wf_decl_pred Σ) Γ a * All_local_env (wf_decl_pred Σ) Γ.\nProof.\n  inv X; intuition; red; simpl; eauto.\nQed.\n\nLemma unfold_fix_wf:\n  forall Σ (mfix : mfixpoint term) (idx : nat) (narg : nat) (fn : term),\n    unfold_fix mfix idx = Some (narg, fn) ->\n    WfAst.wf Σ (tFix mfix idx) ->\n    WfAst.wf Σ fn.\nProof.\n  intros Σ mfix idx narg fn Hf Hwf.\n  unfold unfold_fix in Hf. inv Hwf.\n  destruct nth_error eqn:eqnth; try congruence.\n  pose proof (nth_error_all eqnth X) as [ _ wfd].\n  injection Hf. intros <- <-.\n  apply wf_subst; auto. clear wfd Hf eqnth.\n  assert(forall n, WfAst.wf Σ (tFix mfix n)). constructor; auto.\n  unfold fix_subst. generalize #|mfix|; intros. induction n; auto.\nQed.\n\nLemma unfold_cofix_wf Σ:\n  forall (mfix : mfixpoint term) (idx : nat) (narg : nat) (fn : term),\n    unfold_cofix mfix idx = Some (narg, fn) ->\n    WfAst.wf Σ (tCoFix mfix idx) -> WfAst.wf Σ fn.\nProof.\n  intros mfix idx narg fn Hf Hwf.\n  unfold unfold_cofix in Hf. inv Hwf.\n  destruct nth_error eqn:eqnth; try congruence.\n  pose proof (nth_error_all eqnth X) as [_ wfd].\n  injection Hf. intros <- <-.\n  apply wf_subst; auto. clear wfd Hf eqnth.\n  assert(forall n, WfAst.wf Σ (tCoFix mfix n)). constructor; auto.\n  unfold cofix_subst. generalize #|mfix|; intros. induction n; auto.\nQed.\n\nLemma red1_isLambda Σ Γ t u :\n  red1 Σ Γ t u -> isLambda t -> isLambda u.\nProof.\n  induction 1 using red1_ind_all; simpl; try discriminate; auto.\nQed.\n\nLemma OnOne2_All_All {A} {P Q} {l l' : list A} :\n  OnOne2 P l l' ->\n  (forall x y, P x y -> Q x -> Q y) ->\n  All Q l -> All Q l'.\nProof. intros Hl H. induction Hl; intros H'; inv H'; constructor; eauto. Qed.\n\nLemma All_mapi {A B} (P : B -> Type) (l : list A) (f : nat -> A -> B) :\n  Alli (fun i x => P (f i x)) 0 l -> All P (mapi f l).\nProof.\n  unfold mapi. generalize 0.\n  induction 1; constructor; auto.\nQed.\n\nLemma Alli_id {A} (P : nat -> A -> Type) n (l : list A) :\n  (forall n x, P n x) -> Alli P n l.\nProof.\n  intros H. induction l in n |- *; constructor; auto.\nQed.\n\n\nLemma All_Alli {A} {P : A -> Type} {Q : nat -> A -> Type} {l n} :\n  All P l ->\n  (forall n x, P x -> Q n x) ->\n  Alli Q n l.\nProof. intro H. revert n. induction H; constructor; eauto. Qed.\n\n\nLtac wf := intuition try (eauto with wf || congruence || solve [constructor]).\n#[global]\nHint Unfold wf_decl vass vdef : wf.\n#[global]\nHint Extern 10 => progress simpl : wf.\n#[global]\nHint Unfold snoc : wf.\n#[global]\nHint Extern 3 => apply wf_lift || apply wf_subst || apply wf_subst_instance : wf.\n#[global]\nHint Extern 10 => constructor : wf.\n#[global]\nHint Resolve All_skipn : wf.\n\nLemma on_global_decls_extends_not_fresh {cf} {univs retro} k (Σ : global_declarations) k' (Σ' : global_declarations) P :\n  on_global_decls cumul_gen P univs retro ((k :: Σ) ++ [k'] ++ Σ') -> k.1 = k'.1 -> False.\nProof.\n  intros H eq.\n  depelim H. destruct o as [f ? ? ?].\n  eapply Forall_app in f as [_ f].\n  depelim f. cbn in *. subst. contradiction.\nQed.\n\nLemma lookup_env_extends {cf : checker_flags} (Σ : global_env) k d (Σ' : global_env) P :\n  on_global_env cumul_gen P Σ' ->\n  lookup_env Σ k = Some d ->\n  extends_decls Σ Σ' -> lookup_env Σ' k = Some d.\nProof.\n  destruct Σ as [univs Σ]; cbn in *.\n  rewrite /lookup_env /on_global_env /=.\n  induction Σ in univs, Σ', k, d |- *; cbn => //.\n  destruct (eqb_spec k a.1) as [e|e].\n  * move=> wfΣ' [=]. intros <- ext.\n    destruct ext as [univeq [Σ'' eq]] => /=. cbn in *.\n    subst univs. rewrite eq in wfΣ'.\n    destruct Σ' as [univs' Σ']; cbn in *.\n    subst Σ'. destruct wfΣ' as [cu wfΣ'].\n    induction Σ''.\n    + cbn. now rewrite e eq_kername_refl.\n    + cbn. destruct (eqb_spec k a0.1) => //. subst.\n      { apply on_global_decls_extends_not_fresh in wfΣ'; eauto. }\n      subst. apply IHΣ''. now depelim wfΣ'.\n  * intros HΣ' Hl [univeq [Σ'' eq]]; cbn in *. subst univs.\n    rewrite eq in HΣ'. destruct HΣ'.\n    eapply IHΣ; tea. split; eauto. now rewrite eq.\n    red. split; eauto. reflexivity.\n    exists (Σ'' ++ [a]).\n    now rewrite -app_assoc.\nQed.\n\nLemma wf_extends {cf} {Σ : global_env} T {Σ' : global_env} P :\n  on_global_env cumul_gen P Σ' -> WfAst.wf Σ T -> extends_decls Σ Σ' -> WfAst.wf Σ' T.\nProof.\n  intros wfΣ'.\n  induction 1 using term_wf_forall_list_ind; try solve [econstructor; eauto; solve_all].\n  - intros. destruct H. destruct X0.\n    eapply lookup_env_extends in H; tea.\n    econstructor; repeat split; eauto; solve_all.\nQed.\n\nLemma wf_decl_extends {cf} {Σ : global_env} T {Σ' : global_env} P :\n  on_global_env cumul_gen P Σ' -> wf_decl Σ T -> extends_decls Σ Σ' -> wf_decl Σ' T.\nProof.\n  intros wf [] ext. red. destruct decl_body; split; eauto using wf_extends.\nQed.\n\nArguments lookup_on_global_env {H} {Pcmp P Σ c decl}.\n\nLemma declared_inductive_wf {cf:checker_flags} {Σ : global_env} ind\n         (mdecl : mutual_inductive_body) (idecl : one_inductive_body) :\n  on_global_env cumul_gen wf_decl_pred Σ ->\n  declared_inductive Σ ind mdecl idecl -> WfAst.wf Σ (ind_type idecl).\nProof.\n  intros.\n  destruct H as [Hmdecl Hidecl]. red in Hmdecl.\n  destruct (lookup_on_global_env X Hmdecl) as [Σ' [wfΣ' [ext prf]]]; eauto.\n  apply onInductives in prf.\n  eapply nth_error_alli in Hidecl; eauto.\n  eapply onArity in Hidecl.\n  destruct Hidecl.\n  eapply wf_extends in w; tea.\nQed.\n\nLemma wf_it_mkProd_or_LetIn Σ Γ t\n  : WfAst.wf Σ (it_mkProd_or_LetIn Γ t) -> All (wf_decl Σ) Γ * WfAst.wf Σ t.\nProof.\n  revert t. induction Γ; [simpl; auto with wf|]. intros t XX.\n  destruct a, decl_body; simpl in *.\n  apply IHΓ in XX as []. depelim w; simpl in *; split; auto with wf.\n  apply IHΓ in XX as []. depelim w. simpl in *.\n  split; auto. constructor; auto with wf.\nQed.\n\nLemma declared_inductive_wf_indices {cf:checker_flags} {Σ : global_env} {ind mdecl idecl} :\n  on_global_env cumul_gen wf_decl_pred Σ ->\n  declared_inductive Σ ind mdecl idecl -> All (wf_decl Σ) (ind_indices idecl).\nProof.\n  intros.\n  destruct H as [Hmdecl Hidecl]. red in Hmdecl.\n  destruct (lookup_on_global_env X Hmdecl) as [Σ' [wfΣ' [ext prf]]]; eauto.\n  apply onInductives in prf.\n  eapply nth_error_alli in Hidecl; eauto.\n  pose proof (onArity Hidecl).\n  rewrite Hidecl.(ind_arity_eq) in X0.\n  destruct X0 as [s Hs]; wf.\n  eapply wf_it_mkProd_or_LetIn in s as [? H].\n  eapply wf_it_mkProd_or_LetIn in H as [].\n  solve_all. now eapply wf_decl_extends.\nQed.\n\nLemma declared_inductive_wf_ctors {cf:checker_flags} {Σ} {ind} {mdecl idecl} :\n  on_global_env cumul_gen wf_decl_pred Σ ->\n  declared_inductive Σ ind mdecl idecl ->\n  All (fun ctor => All (wf_decl Σ) ctor.(cstr_args)) (ind_ctors idecl).\nProof.\n  intros.\n  destruct H as [Hmdecl Hidecl]. red in Hmdecl.\n  destruct (lookup_on_global_env X Hmdecl) as [Σ' [wfΣ' [ext prf]]]; eauto.\n  apply onInductives in prf.\n  eapply nth_error_alli in Hidecl; eauto.\n  pose proof (onConstructors Hidecl). red in X0.\n  solve_all. destruct X0.\n  clear -X ext on_cargs.\n  induction (cstr_args x) as [|[na [b|] ty] args] in on_cargs, y |- * ;\n    try destruct on_cargs;\n   constructor; unfold wf_decl in *; cbn in *; intuition eauto using wf_extends; simpl in *.\n   destruct b0. intuition eauto using wf_extends.\n   destruct a. intuition eauto using wf_extends.\n   destruct y => //. destruct on_cargs. destruct w; eauto using wf_extends.\n   destruct y => //. eapply IHargs; intuition eauto.\nQed.\n\nLemma All_local_env_wf_decls Σ ctx :\n  TemplateEnvTyping.All_local_env (wf_decl_pred Σ) ctx ->\n  All (wf_decl Σ) ctx.\nProof.\n  induction 1; constructor; auto.\n  destruct t0 as [s Hs]. split; simpl; intuition auto.\nQed.\n\nLemma on_global_inductive_wf_params {cf:checker_flags} {Σ : global_env_ext} {kn mdecl} :\n  on_global_decl cumul_gen (fun Σ : global_env_ext => wf_decl_pred Σ) Σ kn (InductiveDecl mdecl) ->\n  All (wf_decl Σ) (ind_params mdecl).\nProof.\n  intros prf.\n  apply onParams in prf. red in prf.\n  apply All_local_env_wf_decls in prf.\n  solve_all.\nQed.\n\nLemma destArity_spec ctx T :\n  match destArity ctx T with\n  | Some (ctx', s) => it_mkProd_or_LetIn ctx T = it_mkProd_or_LetIn ctx' (tSort s)\n  | None => True\n  end.\nProof.\n  induction T in ctx |- *; simpl; try easy.\n  - specialize (IHT2 (ctx,, vass na T1)). now destruct destArity.\n  - specialize (IHT3 (ctx,, vdef na T1 T2)). now destruct destArity.\nQed.\n\nLemma destArity_it_mkProd_or_LetIn ctx ctx' t :\n  destArity ctx (it_mkProd_or_LetIn ctx' t) =\n  destArity (ctx ,,, ctx') t.\nProof.\n  induction ctx' in ctx, t |- *; simpl; auto.\n  rewrite IHctx'. destruct a as [na [b|] ty]; reflexivity.\nQed.\n\nLemma it_mkProd_or_LetIn_inj ctx s ctx' s' :\n  it_mkProd_or_LetIn ctx (tSort s) = it_mkProd_or_LetIn ctx' (tSort s') ->\n  ctx = ctx' /\\ s = s'.\nProof.\n  move/(f_equal (destArity [])).\n  rewrite !destArity_it_mkProd_or_LetIn /=.\n  now rewrite !app_context_nil_l => [= -> ->].\nQed.\n\n(*\nLemma case_predicate_contextP ind mdecl idecl params uinst pctx :\n  build_case_predicate_context ind mdecl idecl params uinst = Some pctx <~>\n  case_predicate_context ind mdecl idecl params uinst pctx.\nProof.\n  unfold build_case_predicate_context.\n  unfold instantiate_params.\n  destruct instantiate_params_subst as [[ictx p]|] eqn:ipars => /= //.\n  2:{ split => //. intros H. depelim H.\n      eapply instantiate_params_substP in i.\n      rewrite ipars in i. discriminate. }\n  move: (destArity_spec [] (subst0 ictx p)).\n  destruct destArity as [[idctx inds]|] eqn:da => //.\n  simpl. intros eqs.\n  split.\n  eapply instantiate_params_substP in ipars.\n  intros [= <-]. econstructor. eauto. eauto.\n  intros H. depelim H. subst sty.\n  eapply instantiate_params_substP in i.\n  rewrite ipars in i. noconf i. rewrite eqs in e.\n  eapply it_mkProd_or_LetIn_inj in e as [<- <-].\n  reflexivity.\n  split => // [] [] s ty ictxt inds.\n  move/instantiate_params_substP.\n  rewrite ipars /= => [=] <- <- H.\n  rewrite H destArity_it_mkProd_or_LetIn in da.\n  noconf da.\nQed.\n*)\n\nLemma wf_subst_context Σ s k Γ : All (wf_decl Σ) Γ -> All (WfAst.wf Σ) s -> All (wf_decl Σ) (subst_context s k Γ).\nProof.\n  intros wfΓ. induction wfΓ in s |- *.\n  - intros. constructor.\n  - rewrite subst_context_snoc. constructor; auto.\n    destruct p. destruct x as [? [] ?]; constructor; simpl in *; wf.\nQed.\n\nLemma wf_smash_context Σ Γ Δ : All (wf_decl Σ) Γ -> All (wf_decl Σ) Δ ->\n  All (wf_decl Σ) (smash_context Δ Γ).\nProof.\n  intros wfΓ; induction wfΓ in Δ |- *; intros wfΔ; simpl; auto.\n  destruct x as [? [] ?]; simpl. apply IHwfΓ.\n  eapply wf_subst_context; auto. constructor; auto. apply p.\n  eapply IHwfΓ. apply All_app_inv; auto.\nQed.\n\nSection WfAst.\n  Context {cf:checker_flags}.\n  Context {Σ : global_env}.\n\n  Lemma wf_reln n acc Γ : All (WfAst.wf Σ) acc -> All (WfAst.wf Σ) (reln acc n Γ).\n  Proof using Type.\n    induction Γ in acc, n |- * => wfacc /= //.\n    destruct a as [? [|] ?] => //. now eapply IHΓ.\n    eapply IHΓ. constructor; auto. constructor.\n  Qed.\n\n  #[local]\n  Hint Resolve wf_reln : wf.\n\n  (* Lemma wf_instantiate_params_subst_spec params pars s ty s' ty' :\n    instantiate_params_subst_spec params pars s ty s' ty' ->\n    All (wf_decl Σ) params ->\n    WfAst.wf Σ ty ->\n    All (WfAst.wf Σ) pars ->\n    All (WfAst.wf Σ) s ->\n    All (WfAst.wf Σ) s' * WfAst.wf Σ ty'.\n  Proof.\n    intros ipars. induction ipars; intros wfparams wfty wfpars wfs => //.\n    depelim wfparams. depelim wfpars. depelim wfty.\n    apply IHipars; auto.\n    depelim wfparams. depelim wfty. destruct H; simpl in *.\n    apply IHipars; auto with wf.\n  Qed. *)\n\n  Lemma wf_map2_set_binder_name l l' :\n    All (wf_decl Σ) l' ->\n    All (wf_decl Σ) (map2 set_binder_name l l').\n  Proof using Type.\n    induction 1 in l |- *; destruct l; simpl; constructor.\n    apply p. apply IHX.\n  Qed.\n\n  Definition lift_context_snoc0 n k Γ d : lift_context n k (d :: Γ) = lift_context n k Γ ,, lift_decl n (#|Γ| + k) d.\n  Proof using Type. unfold lift_context. now rewrite fold_context_k_snoc0. Qed.\n  Hint Rewrite lift_context_snoc0 : lift.\n\n  Lemma lift_context_snoc n k Γ d : lift_context n k (Γ ,, d) = lift_context n k Γ ,, lift_decl n (#|Γ| + k) d.\n  Proof using Type.\n    unfold snoc. apply lift_context_snoc0.\n  Qed.\n  Hint Rewrite lift_context_snoc : lift.\n\n\n  Lemma wf_lift_context n k Γ : All (wf_decl Σ) Γ -> All (wf_decl Σ) (lift_context n k Γ).\n  Proof using Type.\n    intros wfΓ. induction wfΓ in n, k |- *.\n    - intros. constructor.\n    - rewrite lift_context_snoc0. constructor; auto.\n      destruct p. destruct x as [? [] ?]; constructor; simpl in *; wf.\n  Qed.\n\n  Lemma wf_subst_instance_context u Γ :\n    All (wf_decl Σ) Γ ->\n    All (wf_decl Σ) (subst_instance u Γ).\n  Proof using Type.\n    induction 1; constructor; auto.\n    destruct x as [na [b|] ty]; simpl in *.\n    destruct p. now split; apply wf_subst_instance.\n    destruct p. now split; auto; apply wf_subst_instance.\n  Qed.\n\n  Lemma wf_extended_subst Γ n :\n    All (wf_decl Σ) Γ ->\n    All (WfAst.wf Σ) (extended_subst Γ n).\n  Proof using Type.\n    induction 1 in n |- *.\n    - simpl; constructor.\n    - destruct x as [na [b|] ty]; simpl; constructor; auto.\n      2:constructor.\n      eapply wf_subst; auto.\n      eapply wf_lift. apply p.\n  Qed.\n\n  Lemma wf_case_predicate_context ind mdecl idecl p :\n    declared_inductive Σ ind mdecl idecl ->\n    All (wf_decl Σ) mdecl.(ind_params) ->\n    All (wf_decl Σ) (ind_indices idecl) ->\n    All (WfAst.wf Σ) p.(pparams) ->\n    All (wf_decl Σ) (case_predicate_context ind mdecl idecl p).\n  Proof using Type.\n    intros decl wfparams wfindty wfpars.\n    unfold case_predicate_context. destruct p.\n    apply wf_map2_set_binder_name.\n    unfold pre_case_predicate_context_gen. cbn [Ast.pparams Ast.puinst].\n    unfold inst_case_context.\n    eapply wf_subst_context => //.\n    2:now eapply All_rev.\n    apply wf_subst_instance_context.\n    rewrite /ind_predicate_context.\n    constructor.\n    simpl; split; auto. simpl. auto. simpl.\n    eapply wf_mkApps. now econstructor.\n    apply wf_reln. constructor.\n    eapply wf_subst_context.\n    now apply wf_lift_context.\n    now apply wf_extended_subst.\n  Qed.\n\n  Lemma Forall_decls_on_global_wf :\n    Forall_decls_typing\n      (fun (Σ : global_env_ext) (_ : context) (t T : term) =>\n      WfAst.wf Σ t * WfAst.wf Σ T) Σ ->\n    on_global_env cumul_gen wf_decl_pred Σ.\n  Proof using Type.\n    apply on_global_env_impl => Σ' Γ t []; simpl; unfold wf_decl_pred;\n    intros; auto. destruct X0 as [s []]; intuition auto.\n  Qed.\n\n  (* Hint Resolve on_global_wf_Forall_decls : wf. *)\n  Lemma wf_inds mind u mdecl :\n    All (WfAst.wf Σ) (inds mind u mdecl.(ind_bodies)).\n  Proof using Type.\n    unfold inds. induction #|ind_bodies mdecl|; constructor; auto.\n    now constructor.\n  Qed.\n\n  Hint Resolve wf_inds : wf.\n\n  Lemma on_inductive_wf_params {Σ' : global_env_ext} {kn mdecl} :\n      forall (oib : on_inductive cumul_gen wf_decl_pred Σ'  kn mdecl),\n      All (wf_decl Σ') (ind_params mdecl).\n  Proof using Type.\n    intros oib. apply onParams in oib.\n    red in oib.\n    induction (ind_params mdecl) as [|[? [] ?] ?]; simpl in oib; inv oib; constructor;\n      try red in X0; try red in X1; try red; simpl; intuition auto.\n  Qed.\n\n  Lemma declared_inductive_wf_params {ind mdecl idecl} :\n    on_global_env cumul_gen wf_decl_pred Σ ->\n    declared_inductive Σ ind mdecl idecl -> All (wf_decl Σ) (ind_params mdecl).\n  Proof using Type.\n    intros.\n    destruct H as [Hmdecl Hidecl]. red in Hmdecl.\n    destruct (lookup_on_global_env X Hmdecl) as [Σ' [wfΣ' [ext prf]]]; eauto.\n    eapply on_global_inductive_wf_params in prf.\n    solve_all. eapply wf_decl_extends; tea.\n  Qed.\n\n  Lemma declared_constructor_wf\n    (ind : inductive) (i : nat) (u : list Level.t)\n          (mdecl : mutual_inductive_body) (idecl : one_inductive_body) (cdecl : constructor_body) :\n      on_global_env cumul_gen wf_decl_pred Σ ->\n      declared_constructor Σ (ind, i) mdecl idecl cdecl ->\n      WfAst.wf Σ (cstr_type cdecl).\n  Proof using Type.\n    intros X isdecl.\n    destruct isdecl as [[Hmdecl Hidecl] Hcdecl]. red in Hmdecl.\n    destruct (lookup_on_global_env X Hmdecl) as [Σ' [wfΣ' [ext prf]]]; eauto. red in prf.\n    apply onInductives in prf.\n    eapply nth_error_alli in Hidecl; eauto. simpl in *.\n    pose proof (onConstructors Hidecl) as h. unfold on_constructors in h.\n    eapply All2_nth_error_Some in Hcdecl. 2: eassumption.\n    destruct Hcdecl as [cs [Hnth [? ? [? ?]]]].\n    eapply wf_extends; eauto.\n  Qed.\n\n  Lemma wf_case_branch_context_gen {ind mdecl idecl cdecl p br} :\n    on_global_env cumul_gen wf_decl_pred Σ ->\n    declared_constructor Σ ind mdecl idecl cdecl ->\n    All (WfAst.wf Σ) (pparams p) ->\n    All (fun ctor => All (wf_decl Σ) (cstr_args ctor)) (ind_ctors idecl) ->\n    All (wf_decl Σ) (case_branch_context (fst ind) mdecl cdecl p br).\n  Proof using Type.\n    intros ong decli wfpars.\n    intros Hforall.\n    destruct decli as [decli hcstr].\n    eapply nth_error_all in Hforall; tea. cbn in Hforall.\n    unfold case_branch_context, case_branch_context_gen.\n    eapply wf_map2_set_binder_name.\n    apply wf_subst_context; auto.\n    apply wf_subst_instance_context.\n    rewrite /cstr_branch_context.\n    unfold expand_lets_ctx, expand_lets_k_ctx.\n    eapply wf_subst_context.\n    eapply wf_lift_context.\n    eapply wf_subst_context => //.\n    eapply wf_inds.\n    apply wf_extended_subst.\n    eapply declared_inductive_wf_params in decli => //.\n    now eapply All_rev.\n  Qed.\n\n  Lemma wf_case_branches_context ind mdecl idecl p brs :\n    on_global_env cumul_gen wf_decl_pred Σ ->\n    declared_inductive Σ ind mdecl idecl ->\n    All (WfAst.wf Σ) (pparams p) ->\n    All (fun ctor => All (wf_decl Σ) (cstr_args ctor)) (ind_ctors idecl) ->\n    All (fun ctx => All (wf_decl Σ) ctx) (case_branches_contexts ind mdecl idecl p brs).\n  Proof using Type.\n    intros ong decli wfpars.\n    unfold case_branches_contexts.\n    intros Hforall.\n    induction Hforall in brs |- *; destruct brs; cbn; constructor; auto.\n    unfold case_branch_context_gen.\n    eapply wf_map2_set_binder_name.\n    apply wf_subst_context; auto.\n    apply wf_subst_instance_context.\n    2:now eapply All_rev.\n    rewrite /cstr_branch_context.\n    unfold expand_lets_ctx, expand_lets_k_ctx.\n    eapply wf_subst_context.\n    eapply wf_lift_context.\n    eapply wf_subst_context => //.\n    eapply wf_inds.\n    apply wf_extended_subst.\n    now eapply declared_inductive_wf_params in decli.\n  Qed.\n\nEnd WfAst.\n\nRecord wf_inductive_body Σ idecl := {\n  wf_ind_type : WfAst.wf Σ (ind_type idecl);\n  wf_ind_indices : All (WfAst.wf_decl Σ) (ind_indices idecl);\n  wf_ind_ctors : All (fun cdecl => WfAst.wf Σ (cstr_type cdecl)) (ind_ctors idecl);\n  wf_ind_ctor_args : All (fun cs => All (wf_decl Σ) (cstr_args cs)) idecl.(ind_ctors);\n  wf_ind_ctors_indices : All (fun cdecl => All (WfAst.wf Σ) (cstr_indices cdecl)) (ind_ctors idecl);\n  wf_ind_projs : All (fun pdecl => WfAst.wf Σ pdecl.(proj_type)) (ind_projs idecl)\n}.\n\nSection WfLookup.\n  Context {cf:checker_flags}.\n  Context {Σ : global_env_ext}.\n\n  Lemma wf_projs ind npars p : All (WfAst.wf Σ) (projs ind npars p).\n  Proof using Type.\n    unfold projs. induction p; constructor; wf.\n  Qed.\n\n  Lemma on_global_inductive_wf_bodies {kn mdecl} :\n    on_global_decl cumul_gen wf_decl_pred Σ kn (InductiveDecl mdecl) ->\n    All (wf_inductive_body Σ) mdecl.(ind_bodies).\n  Proof using Type.\n    cbn. intros oni.\n    have wfpars : All (wf_decl Σ) (ind_params mdecl).\n    { now eapply on_inductive_wf_params in oni. }\n    eapply onInductives in oni.\n    solve_all.\n    induction oni; constructor; auto.\n    clear oni IHoni.\n    destruct p.\n\n    have wfargs : All (fun cs => All (wf_decl Σ) (cstr_args cs)) hd.(ind_ctors).\n    { unfold on_constructors in onConstructors.\n      clear -onConstructors.\n      induction onConstructors; constructor; auto.\n      destruct r.\n      clear -on_cargs.\n      revert on_cargs. revert y. generalize (cstr_args x).\n      induction c as [|[? [] ?] ?]; simpl;\n        destruct y; intuition auto;\n        constructor;\n        try red; simpl; try red in a0, b0; intuition eauto.\n        now red in b. }\n    split => //.\n    - now destruct onArity.\n    - rewrite ind_arity_eq in onArity .\n      destruct onArity as [ona _].\n      eapply wf_it_mkProd_or_LetIn in ona as [_ ona].\n      now eapply wf_it_mkProd_or_LetIn in ona as [].\n    - unfold on_constructors in onConstructors.\n      clear -onConstructors.\n      induction onConstructors; constructor; auto.\n      destruct r.\n      eapply on_ctype.\n    - unfold on_constructors in onConstructors.\n      clear -onConstructors.\n      induction onConstructors; constructor; auto.\n      destruct r.\n      rewrite cstr_eq in on_ctype.\n      destruct on_ctype as [wf _].\n      eapply wf_it_mkProd_or_LetIn in wf as [_ wf].\n      eapply wf_it_mkProd_or_LetIn in wf as [_ wf].\n      rewrite /cstr_concl in wf.\n      eapply wf_mkApps_inv in wf.\n      now apply All_app in wf as [].\n    - rename onProjections into on_projs.\n      destruct (ind_projs hd) eqn:eqprojs. constructor.\n      destruct (ind_ctors hd) as [|? [|]] eqn:Heq; try contradiction.\n      destruct on_projs. rewrite eqprojs in on_projs.\n      solve_all. eapply Alli_All; tea.\n      intros. red in H.\n      destruct (nth_error (smash_context _ _) _) eqn:Heq'; try contradiction.\n      simpl in Heq. inv wfargs. clear X0.\n      destruct H as [onna ->].\n      eapply wf_subst.\n      eapply wf_inds. eapply wf_subst.\n      eapply wf_projs.\n      eapply wf_lift.\n      eapply All_app_inv in wfpars; [|eapply X].\n      eapply (wf_smash_context _ _ []) in wfpars.\n      2:constructor.\n      eapply nth_error_all in Heq'; eauto.\n      apply Heq'.\n  Qed.\n\nEnd WfLookup.\n\nLemma OnOne2All_All2_All2 (A B C : Type) (P : B -> A -> A -> Type) (Q : C -> A -> Type)\n\t(i : list B) (j : list C) (R : B -> Type) (l l' : list A) :\n  OnOne2All P i l l' ->\n  All2 Q j l ->\n  All R i ->\n  (forall x y a b, R x -> P x a b -> Q y a -> Q y b) ->\n  All2 Q j l'.\nProof.\n  induction 1 in j |- *; intros.\n  depelim X. depelim X0. constructor; eauto.\n  depelim X0. depelim X1.\n  constructor; auto.\nQed.\n\nSection WfRed.\n  Context {cf:checker_flags}.\n  Context {Σ : global_env}.\n\n  Lemma wf_red1 Γ M N :\n    on_global_env cumul_gen wf_decl_pred Σ ->\n    All (wf_decl Σ) Γ ->\n    WfAst.wf Σ M ->\n    red1 Σ Γ M N ->\n    WfAst.wf Σ N.\n  Proof using Type.\n    intros wfΣ wfΓ wfM H.\n    induction H using red1_ind_all in wfM, wfΓ |- *.\n    all: inv wfM.\n    all: try solve[ constructor; intuition auto with wf ].\n    all:auto.\n\n    - inv X. inv X0.\n      eauto with wf.\n    - auto with wf.\n    - apply wf_lift.\n      unfold option_map in H. destruct nth_error eqn:Heq; try discriminate.\n      eapply nth_error_all in wfΓ; eauto. unfold wf_decl in *.\n      apply some_inj in H; rewrite H in wfΓ; apply wfΓ.\n    - unfold iota_red.\n      eapply wf_mkApps_inv in X2.\n      apply wf_subst. eapply All_rev. now eapply All_skipn.\n      rewrite /expand_lets /expand_lets_k.\n      apply wf_subst. apply wf_extended_subst. rewrite /bctx.\n      eapply (wf_case_branch_context_gen (ind := (ci_ind ci, c))); tea.\n      eapply declared_inductive_wf_ctors; tea. apply H0.\n      eapply wf_lift. solve_all.\n      now eapply All2_nth_error_Some_r in X3 as [cb [? []]]; tea.\n    - eapply unfold_fix_wf in H; eauto. eapply wf_mkApps; auto.\n    - econstructor; eauto. apply wf_mkApps_napp in X2 as [Hcof Hargs]; auto.\n      eapply unfold_cofix_wf in H; eauto.\n      apply wf_mkApps; intuition auto.\n    - constructor; auto. apply wf_mkApps_napp in X as [Hcof Hargs]; auto.\n      eapply unfold_cofix_wf in H; eauto.\n      apply wf_mkApps; intuition auto.\n    - apply wf_subst_instance.\n      unfold declared_constant in H.\n      eapply lookup_on_global_env in H as [Σ' [onΣ' [ext prf]]]; eauto.\n      destruct decl; simpl in *.\n      subst cst_body0; simpl in *; unfold on_constant_decl in prf; cbn in prf.\n      unfold wf_decl_pred in prf. intuition eauto using wf_extends.\n    - apply wf_mkApps_inv in X.\n      eapply nth_error_all in X; eauto.\n    - simpl in *. econstructor; eauto. cbn.\n      now rewrite -(OnOne2_length X).\n      cbn. clear H1. induction X; constructor; inv X1; intuition auto.\n    - econstructor; eauto; simpl in *.\n      apply IHred1; eauto.\n      apply All_app_inv => //.\n      apply wf_case_predicate_context; auto.\n      eapply declared_inductive_wf_params in isdecl; eauto.\n      eapply declared_inductive_wf_indices; eauto; wf.\n    - econstructor; eauto.\n    - econstructor; eauto.\n      assert (wf := wf_case_branches_context _ _ _ _ brs wfΣ isdecl X1).\n      forward wf.\n      eapply declared_inductive_wf_ctors; eauto; wf.\n      solve_all.\n      eapply OnOne2All_All2_All2; tea. cbn. intuition auto.\n      now rewrite b0 in a1.\n      apply b2 => //.\n      apply All_app_inv => //.\n    - now eapply wf_mkApps.\n    - constructor; auto. induction X; auto; congruence.\n      clear H X0 H0. induction X; inv X1; constructor; intuition auto; try congruence.\n    - constructor.\n      induction X; inv X0; constructor; intuition auto.\n    - constructor; auto.\n      induction X; inv X0; constructor; intuition auto; congruence.\n    - constructor; auto. solve_all.\n      pose proof X0 as H'. revert X0.\n      apply (OnOne2_All_All X). clear X.\n      intros [na bo ty ra] [nb bb tb rb] [[r ih] e] [? ?].\n      simpl in *.\n      inversion e. subst. clear e.\n      intuition eauto.\n      eapply ih. 2: assumption.\n      solve_all.\n      apply All_app_inv. 2: assumption.\n      unfold fix_context. apply All_rev. eapply All_mapi.\n      eapply All_Alli. 1: exact H'.\n      cbn. unfold wf_decl. simpl.\n      intros ? [? ? ? ?] ?. simpl in *.\n      intuition eauto with wf.\n    - constructor; auto.\n      induction X; inv X0; constructor; intuition auto; congruence.\n    - constructor; auto. solve_all.\n      pose proof X0 as H'. revert X0.\n      apply (OnOne2_All_All X). clear X.\n      intros [na bo ty ra] [nb bb tb rb] [[r ih] e] [? ?].\n      simpl in *.\n      inversion e. subst. clear e.\n      intuition eauto.\n      eapply ih. 2: assumption.\n      solve_all. apply All_app_inv. 2: assumption.\n      unfold fix_context. apply All_rev. eapply All_mapi.\n      eapply All_Alli. 1: exact H'.\n      cbn. unfold wf_decl. simpl.\n      intros ? [? ? ? ?] ?. simpl in *.\n      intuition eauto with wf.\n  Qed.\n\n\n  Lemma wf_lift_wf n k t : WfAst.wf Σ (lift n k t) -> WfAst.wf Σ t.\n  Proof using Type.\n    induction t in n, k |- * using term_forall_list_rect; simpl in *;\n      intros Hwf; inv Hwf; try constructor; eauto;\n        repeat (unfold snd, on_snd in *; simpl in *; solve_all).\n\n    - destruct t; try reflexivity. discriminate.\n    - destruct l; simpl in *; congruence.\n    - eapply All2_map_right_inv in X5. econstructor; eauto; solve_all.\n      now rewrite map_length in H1.\n  Qed.\n\n  Lemma declared_projection_wf (p : projection)\n          (mdecl : mutual_inductive_body) (idecl : one_inductive_body) cdecl pdecl :\n      declared_projection Σ p mdecl idecl cdecl pdecl ->\n      on_global_env cumul_gen wf_decl_pred Σ ->\n      WfAst.wf Σ pdecl.(proj_type).\n  Proof using Type.\n    intros isdecl X.\n    destruct isdecl as [[[Hmdecl Hidecl] Hcdecl] Hpdecl].\n    destruct (lookup_on_global_env X Hmdecl) as [Σ' [wfΣ' [ext prf]]]; eauto.\n    assert (wfpars := on_inductive_wf_params prf).\n    eapply on_global_inductive_wf_bodies in prf => //.\n    eapply nth_error_all in Hidecl; eauto. intuition auto.\n    destruct Hidecl.\n    eapply nth_error_all in wf_ind_projs0; eauto. intuition auto.\n    eauto using wf_extends.\n  Qed.\n\n  Lemma declared_constant_wf cst decl :\n    on_global_env cumul_gen wf_decl_pred Σ ->\n    declared_constant Σ cst decl ->\n    WfAst.wf Σ decl.(cst_type) *\n    on_some_or_none (WfAst.wf Σ) decl.(cst_body).\n  Proof using Type.\n    intros wΣ h.\n    unfold declared_constant in h.\n    destruct (lookup_on_global_env wΣ h) as [Σ' [wΣ' [ext h']]].\n    simpl in h'.\n    destruct decl as [ty [bo|]]. all: cbn in *.\n    - destruct h'. intuition eauto using wf_extends.\n    - destruct h'. intuition eauto using wf_extends.\n  Qed.\n\n  Lemma wf_it_mkProd_or_LetIn_inv (Σ' : global_env_ext) Γ (wfΓ : wf_local Σ' Γ)\n    : All_local_env_over typing\n    (fun (Σ : global_env_ext) (Γ : context) (_ : wf_local Σ Γ)\n      (t T : term) (_ : Σ;;; Γ |- t : T) => WfAst.wf Σ t * WfAst.wf Σ T) Σ'\n          Γ wfΓ\n  -> forall t, WfAst.wf Σ' t -> WfAst.wf Σ' (it_mkProd_or_LetIn Γ t).\n  Proof using Type.\n    induction 1; simpl.\n    - trivial.\n    - intros t0 Ht0. apply IHX. constructor. apply Hs. assumption.\n    - intros t0 Ht0. apply IHX. constructor. apply Hc. apply Hc. assumption.\n  Qed.\n\n  Lemma wf_Lambda_or_LetIn {d t} :\n    wf_decl Σ d ->\n    WfAst.wf Σ t ->\n    WfAst.wf Σ (mkLambda_or_LetIn d t).\n  Proof using Type.\n    destruct d as [? [|] ?]; simpl; wf;\n    unfold wf_decl, mkLambda_or_LetIn in *; simpl in *.\n    constructor; intuition auto.\n    constructor; intuition auto.\n  Qed.\n\n  Lemma wf_it_mkLambda_or_LetIn {Γ t} :\n    All (wf_decl Σ) Γ ->\n    WfAst.wf Σ t ->\n    WfAst.wf Σ (it_mkLambda_or_LetIn Γ t).\n  Proof using Type.\n    intros wfΓ wft; induction wfΓ in t, wft |- *; simpl.\n    - trivial.\n    - apply IHwfΓ. now apply wf_Lambda_or_LetIn.\n  Qed.\n\nEnd WfRed.\n\n#[global]\nHint Resolve wf_extends : wf.\n\nLemma All2i_All2 {A B} {P : nat -> A -> B -> Type} {Q : A -> B -> Type} n l l' :\n  All2i P n l l' ->\n  (forall i x y, P i x y -> Q x y) ->\n  All2 Q l l'.\nProof.\n  induction 1; constructor; eauto.\nQed.\n\nLemma cstr_branch_context_length ind mdecl cdecl :\n  #|cstr_branch_context ind mdecl cdecl| = #|cdecl.(cstr_args)|.\nProof. rewrite /cstr_branch_context. now len. Qed.\n\nGlobal Hint Rewrite cstr_branch_context_length : len.\n\n(* Lemma case_branch_context_gen_length ind mdecl p puinst pctx :\n  #|case_branch_context_gen ind mdecl p puinst pctx | = #|pctx|. *)\n\nSection TypingWf.\n  Context {cf}.\n\n  Ltac specialize_goal :=\n    repeat match goal with\n    | H : ?P -> _, H' : ?P |- _ => specialize (H H')\n    end.\n\n  Lemma typing_wf_gen :\n    env_prop\n      (fun Σ Γ t T => WfAst.wf Σ t * WfAst.wf Σ T)\n      (fun Σ Γ wfΓ => All (wf_decl Σ) Γ).\n  Proof using Type.\n    apply typing_ind_env; intros; auto with wf;\n      specialize_goal;\n      try solve [split; try constructor; intuition auto with wf].\n\n    - eapply All_local_env_wf_decls.\n      induction X; constructor; auto; red; intuition auto.\n    - split; wf. apply wf_lift.\n      apply (nth_error_all H X).\n    - split. constructor; auto. wf.\n      clear -X1.\n      induction X1; constructor; now auto.\n      destruct X0 as [_ X0].\n      clear X H H0.\n      induction X1; auto. apply IHX1.\n      apply wf_subst. now destruct p0. destruct p. now inv w.\n    - split. wf. apply wf_subst_instance. wf.\n      destruct (lookup_on_global_env X H) as [Σ' [wfΣ' [ext prf]]]; eauto.\n      red in prf. destruct decl; destruct cst_body0; red in prf; simpl in *; wf.\n      destruct prf as [s []]. wf.\n\n    - split. wf. apply wf_subst_instance.\n      eapply declared_inductive_wf; eauto.\n      now eapply Forall_decls_on_global_wf.\n\n    - split. wf. unfold type_of_constructor.\n      apply wf_subst; auto with wf.\n      apply wf_inds.\n      apply wf_subst_instance.\n      eapply declared_constructor_wf; eauto.\n      now eapply Forall_decls_on_global_wf.\n\n    - destruct X3 as [wfret wps].\n      destruct X6 as [wfc wfapps].\n      eapply wf_mkApps_inv in wfapps.\n      eapply All_app in wfapps as [wfp wfindices].\n      assert (All (wf_decl Σ) predctx).\n      { now apply All_app in X4 as [? ?]. }\n      split; [econstructor; simpl; eauto; solve_all|].\n      eapply All2i_All2; tea; repeat intuition auto.\n      apply wf_mkApps. subst ptm. wf. apply wf_it_mkLambda_or_LetIn; auto.\n      apply All_app_inv; auto.\n    - split. wf. apply wf_subst. solve_all. constructor. wf.\n      apply wf_mkApps_inv in b. apply All_rev. solve_all.\n      eapply declared_projection_wf in isdecl; eauto.\n      now eapply wf_subst_instance.\n      now eapply Forall_decls_on_global_wf.\n\n    - subst types.\n      clear H.\n      split.\n      + constructor.\n        solve_all; destruct a, b.\n        all: intuition.\n      + eapply All_nth_error in X0; eauto.\n        destruct X0 as [s ?]; intuition.\n\n    - subst types.\n      split.\n      + constructor.\n        solve_all; destruct a, b.\n        all: intuition.\n      + eapply All_nth_error in X0; eauto. destruct X0 as [s ?]; intuition.\n  Qed.\n\n  Lemma typing_all_wf_decl Σ (wfΣ : wf Σ.1) Γ (wfΓ : wf_local Σ Γ) :\n    All (wf_decl Σ.1) Γ.\n  Proof using Type.\n    eapply (env_prop_wf_local typing_wf_gen); eauto.\n  Qed.\n  Hint Resolve typing_all_wf_decl : wf.\n\n  Lemma typing_wf_sigma Σ (wfΣ : wf Σ) :\n    on_global_env cumul_gen wf_decl_pred Σ.\n  Proof using Type.\n    intros.\n    pose proof (env_prop_sigma typing_wf_gen _ wfΣ). red in X.\n    do 2 red in wfΣ.\n    eapply on_global_env_impl; eauto; simpl; intros.\n    destruct T. red. apply X1. red. destruct X1 as [x [a wfs]]. split; auto.\n  Qed.\n\n  Lemma typing_wf Σ (wfΣ : wf Σ.1) Γ t T :\n    Σ ;;; Γ |- t : T -> WfAst.wf Σ.1 t * WfAst.wf Σ.1 T.\n  Proof using Type.\n    intros. eapply typing_wf_gen in X; intuition eauto with wf.\n  Qed.\n\n  Lemma declared_minductive_wf {Σ : global_env} {mind mdecl} {wfΣ : wf Σ} :\n    declared_minductive Σ mind mdecl ->\n    All (wf_decl Σ) (ind_params mdecl) *\n    All (@wf_inductive_body Σ) (ind_bodies mdecl).\n  Proof using Type.\n    intros declm.\n    pose proof (typing_wf_gen (Env.empty_ext Σ) wfΣ _ localenv_nil _ _ (type_Prop _)) as [X _].\n    eapply Forall_decls_on_global_wf in X.\n    destruct (lookup_on_global_env X declm) as [? [? [ext ?]]]; eauto.\n    split. eapply on_global_inductive_wf_params in o0. solve_all. eauto using wf_decl_extends.\n    eapply on_global_inductive_wf_bodies in o0. solve_all.\n    destruct X0; split; solve_all; eauto using wf_extends, wf_decl_extends.\n  Qed.\n\n  Lemma declared_inductive_wf_case_predicate_context\n     {Σ : global_env} {wfΣ : wf Σ} {ind mdecl idecl p} :\n    declared_inductive Σ ind mdecl idecl ->\n    All (WfAst.wf Σ) p.(pparams) ->\n    All (wf_decl Σ) (case_predicate_context ind mdecl idecl p).\n  Proof using Type.\n    intros decli.\n    destruct (declared_minductive_wf (proj1 decli)) as [wfp wfb].\n    intros wfpars.\n    eapply wf_case_predicate_context => //.\n    destruct decli as [declm hi].\n    eapply nth_error_all in wfb; tea. apply wfb.\n  Qed.\n\n  Lemma declared_constructor_wf_case_branch_context\n    {Σ} {wfΣ : wf Σ} {ind mdecl idecl cdecl p br} :\n    declared_constructor Σ ind mdecl idecl cdecl ->\n    All (WfAst.wf Σ) (pparams p) ->\n    All (wf_decl Σ) (case_branch_context (fst ind) mdecl cdecl p br).\n  Proof using Type.\n    intros.\n    eapply wf_case_branch_context_gen; tea => //.\n    now apply typing_wf_sigma.\n    destruct (declared_minductive_wf (proj1 (proj1 H))).\n    destruct H as [[hm hnth] hnth'].\n    eapply nth_error_all in a0; tea.\n    now eapply wf_ind_ctor_args.\n  Qed.\n\n  Lemma mkApp_ex_wf Σ t u : WfAst.wf Σ (mkApp t u) ->\n    exists f args, mkApp t u = tApp f args /\\ ~~ isApp f.\n  Proof using Type.\n    induction t; simpl; try solve [eexists _, _; split; reflexivity].\n    intros wf.\n    eapply wf_inv in wf as [[[appt _] wft] wfargs].\n    eapply All_app in wfargs as [wfargs wfu]. depelim wfu.\n    forward IHt. eapply wf_mkApp; intuition auto.\n    destruct IHt as [f [ar [eqf isap]]].\n    eexists _, _; split; auto. rewrite appt //.\n  Qed.\n\n  Lemma decompose_app_mkApp f u :\n    (decompose_app (mkApp f u)).2 <> [].\n  Proof using Type.\n    induction f; simpl; auto; try congruence.\n    destruct args; simpl; congruence.\n  Qed.\n\n  Lemma mkApps_tApp' f u f' u' :\n    ~~ isApp f' ->\n    mkApp f u = tApp f' u' -> mkApps f [u] = mkApps f' u'.\n  Proof using Type.\n    intros.\n    rewrite -(mkApp_mkApps f u []).\n    simpl. rewrite H0.\n    rewrite -(mkApps_tApp f') // ?H //.\n    destruct u' => //.\n    eapply (f_equal decompose_app) in H0.\n    simpl in H0. pose proof (decompose_app_mkApp f u).\n    rewrite H0 /= in H1. congruence.\n  Qed.\n\n  Lemma eq_decompose_app Σ x y :\n    WfAst.wf Σ x -> WfAst.wf Σ y ->\n    decompose_app x = decompose_app y -> x = y.\n  Proof using Type.\n    intros wfx; revert y.\n    induction wfx using term_wf_forall_list_ind; intros [] wfy;\n    eapply wf_inv in wfy; simpl in wfy; simpl;\n    intros [= ?]; try intuition congruence.\n  Qed.\n\n  Lemma mkApp_ex t u : ∑ f args, mkApp t u = tApp f args.\n  Proof using Type.\n    induction t; simpl; try solve [eexists _, _; reflexivity].\n  Qed.\n\n  Lemma strip_casts_decompose_app Σ t :\n    WfAst.wf Σ t ->\n    forall f l, decompose_app t = (f, l) ->\n    strip_casts t = mkApps (strip_casts f) (map strip_casts l).\n  Proof using Type.\n    intros wf.\n    induction wf using term_wf_forall_list_ind; simpl; intros; auto; noconf H;\n    try noconf H0;\n      rewrite ?map_map_compose  ?compose_on_snd ?compose_map_def ?map_length;\n        f_equal; solve_all; eauto.\n    - now noconf H1.\n    - now noconf H1.\n    - now noconf H2.\n  Qed.\n\n  Lemma mkApps_tApp f args :\n    ~~ isApp f ->\n    ~~ is_empty args ->\n    tApp f args = mkApps f args.\n  Proof using Type.\n    intros.\n    destruct args, f; try discriminate; auto.\n  Qed.\n\n  Lemma strip_casts_mkApps_napp_wf Σ f u :\n    ~~ isApp f -> WfAst.wf Σ f -> All (WfAst.wf Σ) u ->\n    strip_casts (mkApps f u) = mkApps (strip_casts f) (map strip_casts u).\n  Proof using Type.\n    intros nisapp wf wf'.\n    destruct u.\n    simpl. auto.\n    rewrite -(mkApps_tApp f (t :: u)) //.\n  Qed.\n\n  Lemma mkApp_mkApps f u : mkApp f u = mkApps f [u].\n  Proof using Type. reflexivity. Qed.\n\n  Lemma decompose_app_inv Σ f l hd args :\n    WfAst.wf Σ f ->\n    decompose_app (mkApps f l) = (hd, args) ->\n    ∑ n, ~~ isApp hd /\\ l = skipn n args /\\ f = mkApps hd (firstn n args).\n  Proof using Type.\n    destruct (isApp f) eqn:Heq.\n    revert l args hd.\n    induction f; try discriminate. intros.\n    simpl in X.\n    move/wf_inv: X => /= [[[isAppf Hargs] wff] wfargs].\n    rewrite mkApps_tApp ?isAppf in H => //. destruct args => //.\n    rewrite -mkApps_app in H.\n    rewrite decompose_app_mkApps ?isAppf in H; auto. noconf H.\n    exists #|args|; split; auto. now rewrite isAppf.\n    rewrite skipn_all_app.\n    rewrite firstn_app. rewrite firstn_all2. lia.\n    rewrite Nat.sub_diag firstn_O app_nil_r. split; auto.\n    rewrite mkApps_tApp ?isAppf //. now destruct args.\n\n    intros wff fl.\n    rewrite decompose_app_mkApps in fl; auto. now apply negbT.\n    inversion fl. subst; exists 0.\n    split; auto. now eapply negbT.\n  Qed.\n\n  Lemma eq_tip_skipn {A} (x : A) n l : [x] = skipn n l ->\n    exists l', l = l' ++ [x] /\\ n = #|l'|.\n  Proof using Type.\n    induction l in n |- *. rewrite skipn_nil //.\n    destruct n. simpl. destruct l => //.\n    intros eq. noconf eq. exists []; split; auto.\n    rewrite skipn_S. intros Hx.\n    destruct (IHl _ Hx) as [l' [-> ->]].\n    exists (a :: l'); split; reflexivity.\n  Qed.\n\n  Lemma strip_casts_mkApp_wf Σ f u :\n    WfAst.wf Σ f -> WfAst.wf Σ u ->\n    strip_casts (mkApp f u) = mkApp (strip_casts f) (strip_casts u).\n  Proof using Type.\n    intros wf wf'.\n    assert (wfa : WfAst.wf Σ (mkApp f u)). now apply wf_mkApp.\n    destruct (mkApp_ex_wf Σ f u wfa) as [f' [args [eq isapp]]].\n    eapply (f_equal decompose_app) in eq. simpl in eq.\n    epose proof (strip_casts_decompose_app Σ _ wfa _ _ eq).\n    rewrite H.\n    rewrite mkApp_mkApps in eq.\n    destruct (decompose_app_inv Σ _ _ _ _ wf eq) as [n [ng [stripeq stripf]]].\n    apply eq_tip_skipn in stripeq. destruct stripeq as [l' [eqargs eqn]].\n    subst n args. rewrite firstn_app_left // in stripf. subst f.\n    eapply wf_mkApps_napp in wf as [wff' wfl] => //.\n    rewrite (strip_casts_mkApps_napp_wf Σ) //.\n    now rewrite mkApp_mkApps -mkApps_app map_app.\n  Qed.\n\n  Lemma strip_casts_mkApps_wf Σ f u :\n    WfAst.wf Σ f -> All (WfAst.wf Σ) u ->\n    strip_casts (mkApps f u) = mkApps (strip_casts f) (map strip_casts u).\n  Proof using Type.\n    intros wf wf'. induction wf' in f, wf |- *.\n    simpl. auto.\n    rewrite -mkApps_mkApp IHwf'.\n    apply wf_mkApp; auto with wf.\n    rewrite (strip_casts_mkApp_wf Σ) //.\n    now rewrite mkApps_mkApp.\n  Qed.\nEnd TypingWf.\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/template-coq/theories/TypingWf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.25588953187816704}}
{"text": "Require Import Blech.Defaults.\n\nRequire Import Coq.Setoids.Setoid.\nRequire Import Coq.Classes.SetoidClass.\nRequire Import Coq.Strings.String.\n\nRequire Import Blech.Bishop.\nRequire Import Blech.Type.Some.\nRequire Import Blech.Functor.\nRequire Import Blech.Category.\nRequire Import Blech.Category.Funct.\nRequire Import Blech.Category.Prod.\nRequire Import Blech.Category.Bsh.\nRequire Import Blech.Category.Op.\nRequire Import Blech.Category.El.\nRequire Import Blech.Groupoid.\nRequire Import Blech.Groupoid.Core.\n\nImport BishopNotations.\nImport SomeNotations.\nImport CategoryNotations.\nImport GroupoidNotations.\nImport CoreNotations.\nImport OpNotations.\nImport FunctorNotations.\n\nOpen Scope category_scope.\nOpen Scope bishop_scope.\n\nImport IfNotations.\n\nDefinition Decidable (T: Type) := ∀ (x y: T), {x = y} + {x ≠ y}.\nExisting Class Decidable.\n\nDefinition eq_dec {T: Type} `{D:Decidable T} := D.\n\n\nDefinition ns (A: Type): nat → Type :=\n  fix loop n :=\n    match n with\n    | O => True\n    | S n' => prod A (loop n')\n    end.\n\n#[universes(cumulative)]\nInductive sort {V} :=\n| true | false\n\n| prod (_ _: sort)\n| Forall (_: V → sort)\n| span {E} (_: E → sort)\n.\nArguments sort: clear implicits.\n\nInductive prop {V}: sort V → Type :=\n| prop_true: prop true\n| prop_false: prop false\n| prop_prod {A B}: prop A → prop B → prop (prod A B)\n.\n\nFixpoint pnf {V} (n: nat) (S: sort V): Type :=\n  match n with\n  | O => prop S\n  | S n' =>\n    if S is Forall P\n    then\n      forall x, pnf n' (P x)\n    else\n      False\n  end.\n\nDefinition app {V n} {S: sort V} (p:pnf n S): ns V n → sort V.\nProof.\n  generalize dependent p.\n  generalize dependent S.\n  induction n.\n  - cbn in *.\n    intros.\n    apply S.\n  - cbn in *.\n    destruct S.\n    all: try contradiction.\n    intro p.\n    intro HT.\n    destruct HT as [H T].\n    apply (IHn (s H) (p _) T).\nDefined.\n\n\n\nFixpoint eqb {V} `{Decidable V} (x y: @sort V _): bool :=\n  match (x, y) with\n  | (true, true) => Datatypes.true\n  | (false, false) => Datatypes.true\n  | (prod A B, prod A' B') => eqb A A' && eqb B B'\n  | (Forsome F, Forsome F') => λ x, eqb (F x) (F x)\n  | _ => Datatypes.false\n  end.\nInstance sort_Decidable V `(Decidable V): Decidable (@sort V _) :=\n  λ x y :=\nProof.\n  unfold Decidable in *.\n  intros x y.\n  induction x, y.\n  all: try (left; reflexivity).\n  all: try (right; discriminate).\n  \n}.\n\nDefinition eq {V: Decidable} (x y: V): sort V := if eq_dec x y then true else false.\n\nDefinition η {V: Decidable} (x: V): sort V := Forsome (eq x).\n\nDefinition foo {V: Decidable}: sort V := Forall (λ p, prod p p).\n\nDefinition st (λ x, η x).\n\n  Inductive term {Var Val: sort → Type}: sort → Type :=\n| bang: term pt\n| true: term bool | false: term bool\n\n| tuple {A B}: term A → term B → term (prod A B)\n| fst {A B}: term (prod A B) → term A\n| snd {A B}: term (prod A B) → term B\n\n| app {A B}: term (exp A B) → term A → term B\n\n| var {A}: Var A → term A\n| lam {A B}: Var A → (Val A → term B) → term (exp A B)\n.\n\nInductive xs: sort → Type :=\n| x: xs pt .\nCheck lam x (λ x', var x).\n\nInductive form {V}: nat → Type :=\n| η (_: V): form 0\n| d {p} (_: form p): form (p + 1)\n| wedge {p q} (_: form p) (_: form q): form (p + q)\n.\nArguments form: clear implicits.\nInfix \"∧\" := wedge.\n\nRecord subset A := sup {\n  s: Type ;\n  π: s → A ;\n}.\n\nArguments sup {A s}.\nArguments s {A}.\nArguments π {A}.\n\nNotation \"'lim' x .. y , P\" := (sup (λ x, .. (sup (λ y,  P)) .. )) (at level 200, x binder, y binder).\n\n(* FIXME add complicated setoid relations *)\n.\nNotation \"!\" := bang.\n\nNotation \"·\" := point.\nInfix \"×\" := prod (at level 30, right associativity).\n\nOpen Scope nat_scope.\n\nDefinition bangRule: subset (form term 1) :=\n  lim (x: unit), η ! ∧ d (η ·).\n\nDefinition tupleRule: form (subset term) 1 :=\n  η (lim (x: unit), !) ∧ d (η (lim (x: unit), ·)).\n\nDefinition tupleRule := lim '(e0, e1, A, B), tuple e0 e1 ∈ prod A B.\n\nDefinition appRule := λ e0 e1, app e0 e1 ∈ (\n                                     η (λ Γ, Γ e0) ∧ η (λ Γ, Γ e1)\n                                   ).\n#[local]\nObligation Tactic := Reflect.category_simpl.\n\nReserved Notation \"f ◃ g\" (at level 30, no associativity).\nReserved Notation \"f ▹ g\" (at level 30, no associativity).\nReserved Notation \"f ▵ g\" (at level 30, no associativity).\nReserved Notation \"i ~ j\" (at level 30, no associativity).\n\n#[universes(cumulative)]\nClass Cylinder := {\n  Obj: Type ;\n  Mor: string → Obj → Obj → Bishop ;\n\n  id [s] A: Mor s A A ;\n  compose [s] [A B C]: Mor s B C -> Mor s A B -> Mor s A C\n  where \"f ∘ g\" := (compose f g) ;\n\n  compose_assoc [s A B C D] (f: Mor s C D) (g: Mor s B C) (h: Mor s A B):\n    (f ∘ (g ∘ h)) == ((f ∘ g) ∘ h );\n  compose_id_left [s A B] (f: Mor s A B): (id B ∘ f) == f ;\n  compose_id_right [s A B] (f: Mor s A B): (f ∘ id A) == f ;\n\n  compose_compat [s A B C]: Proper (equiv ==> equiv ==> equiv) (@compose s A B C) ;\n\n  left_commute [A B C] [i j]: Mor i B C -> Mor j A B -> Mor j B C\n  where \"f ◃ g\" := (left_commute f g) ;\n\n  right_commute [A B C] [i j]: Mor i B C -> Mor j A B -> Mor i A B\n  where \"f ▹ g\" := (right_commute f g) ;\n\n  left_right_commute [A B C] [i j]: Mor i B C -> Mor j A B -> (Mor j B C * Mor i A B) :=\n   λ f g, (f ◃ g, f ▹ g) ;\n\n     (* FIXME figure out the rest of the laws *)\n  left_id [s t A B] (f: Mor t A B): (@id s B ◃ f) == @id t B ;\n  right_id [s t A B] (f: Mor s A B): (f ▹ @id t A) == @id s A ;\n\n  left_Proper [s t A B C]: Proper (equiv ==> equiv ==> equiv) (@left_commute s t A B C) ;\n  right_Proper [s t A B C]: Proper (equiv ==> equiv ==> equiv) (@right_commute s t A B C) ;\n\n  diag (i j: string): Obj\n  where \"i ~ j\" := (diag i j);\n\n  refl {i A}: Mor i A (i ~ i) ;\n  sym {i j}: Mor i (i ~ j) (j ~ i) ;\n  trans {i j k A}:\n    Mor j A (i ~ j) → Mor j A (j ~ k) → Mor j A (i ~ k) ;\n}.\n\nArguments Obj: clear implicits.\nArguments Mor: clear implicits.\n\nCoercion Obj: Cylinder >-> Sortclass.\nCoercion Mor: Cylinder >-> Funclass.\n\nExisting Instance compose_compat.\nExisting Instance left_Proper.\nExisting Instance right_Proper.\n\nModule Import CylinderNotations.\n  Bind Scope category_scope with Cylinder.\n  Bind Scope object_scope with Obj.\n  Bind Scope morphism_scope with Mor.\n\n  Notation \"f ∘ g\" := (compose f g) : morphism_scope.\n  Notation \"f ◃ g\" := (left_commute f g) : morphism_scope.\n  Notation \"f ▹ g\" := (right_commute f g) : morphism_scope.\n  Notation \"f ▵ g\" := (left_right_commute f g) : morphism_scope.\n\n  Notation \"i ~ j\" := (diag i j) : object_scope.\n\n  Notation \"A → B\" := (Mor _ A B) (only parsing) : bishop_scope.\n  Notation \"A ~> B\" := (Mor _ A B) (only parsing) : bishop_scope.\nEnd CylinderNotations.\n\nCheck trans (id _) _.\n\n#[universes(cumulative)]\nClass Closed := {\n  C: Category ;\n\n  pt: C ;\n  prod: Functor (C * C) C ;\n  exp: Functor (C ᵒᵖ * C) C ;\n\n  (* FIXME laws *)\n  bang x: C x pt ;\n  fanout {x y z}: C z x → C z y → C z (prod (x, y)) ;\n  π1 {x y}: C (prod (x, y)) x ;\n  π2 {x y}: C (prod (x, y)) y ;\n}.\nCoercion C: Closed >-> Category.\nExisting Instance C.\n\nNotation \"⊤\" := pt.\nNotation \"A × B\" := (prod (A, B)) (at level 30, right associativity).\nNotation \"[ A , B ]\" := (exp (A, B)).\n\nNotation \"!\" := bang.\n\n#[universes(cumulative)]\nClass Cylinder := {\n  H (s: string): Closed ;\n\n  diag (x y: string): Bsh ;\n\n  alpha {i j}: Functor (H i) (H j) ;\n\n  (* Seems absurdly wrong *)\n  assoc i j: H i b c → H j a b ;\n}.\nCoercion H: Cylinder >-> Funclass.\nExisting Instance H.\n\nInfix \"∝\" := assoc (at level 30, no associativity).\nInfix \"~\" := diag (at level 30, no associativity).\n\nSection open.\n  Context `{C:Cylinder}.\n\n  Check (\"x\" ∝ \"y\") (⊤, ⊤).\n  Check map (\"x\" ∝ \"y\") (id _,  _).\n  (! ⊤).\n#[universes(cumulative)]\nRecord Var (C: Category) := {\n  pt: C ;\n  prod: Functor (C * C) C ;\n  exp: Functor (C ᵒᵖ * C) C ;\n\n  (* FIXME laws *)\n\n  bang x: C x pt ;\n  push {x y}: C pt x → C y (prod (x, y)) ;\n\n  (* Doesn't seem quite right *)\n  π1 {x y}: C (prod (x, y)) x ;\n  π2 {x y}: C (prod (x, y)) y ;\n\n  pass {x y}: C pt x → C (exp (x, y)) y ;\n\n  curr {x y z}:\n    C (prod (x, y)) z → C y (exp (x, z)) ;\n  ev {x y}: C (prod (x, exp (x, y))) y ;\n}.\n\nArguments pt {C}.\nArguments prod {C}.\nArguments exp {C}.\n\nArguments bang {C}.\nArguments push {C} v {x y}.\nArguments π1 {C} v {x y}.\nArguments π2 {C} v {x y}.\n\nArguments curr {C} v {x y z}.\nArguments ev {C} v {x y}.\n\n#[universes(cumulative)]\nClass Variadic := {\n  C: Category;\n  (* FIXME require finite ? *)\n  α: Type;\n\n  var: α → Var C ;\n\n  diag: α → α → C ;\n\n  assoc {i j} {A B C}:\n    prod (var i) (A, prod (var j) (B, C)) ~> prod (var j) (prod (var i) (A, B), C) ;\n\n  (* Just for playing with *)\n  Z: C ;\n  z i: nat → C (pt (var i)) Z ;\n}.\n\nCoercion C: Variadic >-> Category.\nExisting Instance C.\n\nCoercion var: α >-> Var.\n\nNotation \"⊤\" := pt.\nNotation \"A [ i ]× B\" := (prod i (A, B)) (at level 30, right associativity).\nNotation \"A ~[ i ]> B\" := (exp i (A, B)) (at level 90, right associativity).\nNotation \"!\" := bang.\n\nSection open.\n  Context `{V:Variadic}.\n\n  Definition foo (i j: α) A: A ~> Z [i]× Z [j]× A :=\n    push i (z i 4) ∘ push j (z j 5).\n\n  Definition ident (i j: α) A B: A ~> (B ~[i]> B) :=\n    curr i (π1 i).\n\n  Check λ (i: α), curr i (π1 i).\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/Cylinder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.25587326324589693}}
{"text": "(** MetaLan.v *)\nFrom Babel Require Import TerminalDogma \n                          ExtraDogma.Extensionality\n                          EpsilonDescription\n                          SetFacility\n                          POrderFacility.\n\nFrom Babel Require Import Ranko\n                            ExtensionalityCharacter\n                            ClassicalCharacter.\n\nFrom Babel Require Import MetaLanguage.Notations\n                            MetaType.\n\nFrom Coq Require Import Relations Classical.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\n\n(****************************************)\n(*                                      *)\n(*       AxSem                          *)\n(*       (Axiomatic Semantics)          *)\n(*                                      *)\n(****************************************)\n\n\nModule AxSem.\n\nSection ClassDef.\n\nRecord mixin_of (mT : dMT) (syn : Type) : Type := Mixin {\n    ax_sys : mT -> syn -> mT -> Prop;\n}.\n\nNotation class_of := mixin_of (only parsing).\n\nRecord type (mT : dMT) := Pack {\n    syn : Type;\n    class : class_of mT syn;\n}.\n\n\nEnd ClassDef.\n\nModule Exports.\n\n#[reversible]\nCoercion syn : type >-> Sortclass.\nCoercion class : type >-> mixin_of.\n\nNotation axSem := type.\nNotation AxSem s m:= (@Pack _ s m).\n\nNotation \" ⊢ { P } s { Q } \" := (ax_sys _ P s Q) (only printing)\n    : MetaLan_scope.\nNotation \" ⊢ { P } s { Q } \" := (ax_sys (class _) P s Q) \n    : MetaLan_scope.\nNotation \" ⊢ < ax > { P } s { Q } \" := (ax_sys (class ax) P s Q) \n    : MetaLan_scope.\n\nEnd Exports.\n\nEnd AxSem.\nExport AxSem.Exports.\n\n\n(****************************************)\n(*                                      *)\n(*       DeSem                          *)\n(*       (Backward Transformer)         *)\n(*                                      *)\n(****************************************)\nModule DeSem.\nSection ClassDef.\n\nRecord mixin_of (mT : Type) (syn : Type) : Type := Mixin {\n    de_fun : syn -> mT -> mT;\n}.\n\nNotation class_of := mixin_of (only parsing).\n\nRecord type (mT : Type) : Type := Pack {\n    syn : Type;\n    class : class_of mT syn;\n}.\n\nEnd ClassDef.\n\nModule Exports.\n\n#[reversible]\nCoercion syn : type >-> Sortclass.\nCoercion class : type >-> mixin_of.\n\nNotation deSem := type.\nNotation DeSem s m := (@Pack _ s m).\n\nNotation \" ⟦ s ⟧ < de > \" := (de_fun de s) : MetaLan_scope.\n\nEnd Exports.\nEnd DeSem.\n\nExport DeSem.Exports.\n\n\n(****************************************)\n(*                                      *)\n(*       DeSemM                         *)\n(*       (Backward Transformer)         *)\n(*       (monotonic)                    *)\n(****************************************)\n\n\nModule DeSemM.\nSection ClassDef.\n\nRecord mixin_of (mT : poset) (syn : Type)\n        (b : DeSem.mixin_of mT syn) : Type := Mixin {\n    mono_mixin : forall s, \n        MonotonicFun.mixin_of (DeSem.de_fun b s);\n}.\n\nRecord class_of (mT : poset) (syn : Type) := Class {\n    base_de : DeSem.mixin_of mT syn;\n    mixin : mixin_of base_de;\n}.\n\nRecord type (mT : poset) : Type := Pack {\n    syn : Type;\n    class : class_of mT syn;\n}.\n\nLocal Coercion class : type >-> class_of.\n\nDefinition de_monot (mT : poset) (cT : type mT) (s : syn cT)\n    : MonotonicFun.mixin_of (DeSem.de_fun (base_de cT) s) :=\n        mono_mixin (mixin cT) s.\n\nDefinition to_deSem (mT : poset) (cT : type mT) : deSem mT :=\n    DeSem (syn cT) (base_de cT).\n\nEnd ClassDef.\n\nModule Exports.\n\n#[reversible]\nCoercion syn : type >-> Sortclass.\nCoercion class : type >-> class_of.\nCoercion mixin : class_of >-> mixin_of.\nCoercion base_de : class_of >-> DeSem.mixin_of.\n\nCoercion to_deSem : type >-> deSem.\n\nNotation deSemM := type.\nNotation DeSemM s m := (@Pack _ s (Class m)).\n\n\nEnd Exports.\n\nEnd DeSemM.\nExport DeSemM.Exports.\n\n\n(****************************************)\n(*                                      *)\n(*       DeSemC                         *)\n(*       (Backward Transformer)         *)\n(*       (Continuous)                   *)\n(****************************************)\n\n\nModule DeSemC.\nSection ClassDef.\n\nRecord mixin_of (mT : cpo) (syn : Type)\n        (b : DeSemM.class_of mT syn) : Type := Mixin {\n    conti_mixin : forall s, \n        ContinuousFun.mixin_of (DeSemM.mono_mixin b s);\n}.\n\nRecord class_of (mT : cpo) (syn : Type) := Class {\n    base_deM : DeSemM.class_of mT syn;\n    mixin : mixin_of base_deM;\n}.\n\nRecord type (mT : cpo) : Type := Pack {\n    syn : Type;\n    class : class_of mT syn;\n}.\n\nLocal Coercion class : type >-> class_of.\n\nDefinition de_conti (mT : cpo) (cT : type mT) (s : syn cT)\n    : ContinuousFun.mixin_of (DeSemM.mono_mixin (base_deM cT) s) :=\n        conti_mixin (mixin cT) s.\n\nDefinition to_deSemM (mT : cpo) (cT : type mT) : deSemM mT :=\n    DeSemM (syn cT) (base_deM cT).\n\nEnd ClassDef.\n\nModule Exports.\n\n#[reversible]\nCoercion syn : type >-> Sortclass.\nCoercion class : type >-> class_of.\nCoercion mixin : class_of >-> mixin_of.\nCoercion base_deM : class_of >-> DeSemM.class_of.\n\nCoercion to_deSemM : type >-> deSemM.\n\nNotation deSemC := type.\nNotation DeSemC s m := (@Pack _ s (Class m)).\n\n\nEnd Exports.\n\nEnd DeSemC.\nExport DeSemC.Exports.\n\n(****************************************)\n(*                                      *)\n(*       VeriModS                       *)\n(*       (Verification Module)          *)\n(*                                      *)\n(****************************************)\n\n(* only soundness is required *)\nModule VeriModS.\nSection ClassDef.\n\nDefinition axiom (mT : cpoDMT) (syn : Type)\n    (ax_m : AxSem.mixin_of mT syn) (de_m : DeSem.mixin_of mT syn) \n    (base_de := DeSem syn de_m) (base_ax := AxSem syn ax_m):=\n\n        forall (s : syn) (P Q : [cpo of mT]),\n        ⊢ <base_ax> { P } s { Q } -> P ⊑ ⟦ s ⟧ <base_de> Q.\n\nRecord mixin_of (mT : cpoDMT) (syn : Type)\n    (ax_m : AxSem.mixin_of mT syn) (de_m : DeSem.mixin_of mT syn) : Type \n        := Mixin {\n    soundness : axiom ax_m de_m;\n}.\n\nRecord class_of (mT : cpoDMT) (syn : Type) : Type := Class {\n    base_ax : AxSem.mixin_of mT syn;\n    base_de : DeSem.mixin_of mT syn;\n    mixin : mixin_of base_ax base_de;\n}.\n\nRecord type (mT : cpoDMT) := Pack {\n    syn : Type;\n    class : class_of mT syn;\n}.\n\nLocal Coercion syn : type >-> Sortclass.\nLocal Coercion class : type >-> class_of.\n\nDefinition to_axSem (mT : cpoDMT) (cT : type mT) :=\n    AxSem (syn cT) (base_ax cT).\n\nDefinition to_deSem (mT : cpoDMT) (cT : type mT) :=\n    DeSem (syn cT) (base_de cT).\n\nDefinition soundness_of (mT : cpoDMT) (cT : type mT) :=\n    soundness (mixin cT).\n    \n\nEnd ClassDef.\n\nModule Exports.\n\n#[reversible]\nCoercion syn : type >-> Sortclass.\nCoercion class : type >-> class_of.\nCoercion mixin : class_of >-> mixin_of.\n\nCoercion to_axSem : type >-> axSem.\nCoercion to_deSem : type >-> deSem.\n\nNotation veriModS := type.\nNotation VeriModS s m := (@Pack _ s (Class m)).\n\nArguments soundness_of [_] _.\nNotation soundness_of := soundness_of.\n\nEnd Exports.\n\nEnd VeriModS.\nExport VeriModS.Exports.\n\n\n(****************************************)\n(*                                      *)\n(*       VeriModC                       *)\n(*       (Verification Module)          *)\n(*                                      *)\n(****************************************)\n\n\n(* complete *)\nModule VeriModC.\nSection ClassDef.\n\nDefinition axiom (mT : cpoDMT) (syn : Type)\n    (ax_m : AxSem.mixin_of mT syn) (de_m : DeSem.mixin_of mT syn) \n    (base_ax := AxSem syn ax_m) (base_de := DeSem syn de_m) :=\n        forall (s : syn) (P Q : [cpo of mT]),\n        P ⊑ ⟦ s ⟧ <base_de> Q -> ⊢ <base_ax> { P } s { Q }.\n\n\nRecord mixin_of (mT : cpoDMT) (syn : Type)\n    (ax_m : AxSem.mixin_of mT syn) (de_m : DeSem.mixin_of mT syn) \n        : Type := Mixin {\n    completeness : axiom ax_m de_m;\n}.\n\nRecord class_of (mT : cpoDMT) (syn : Type) : Type := Class {\n    base_ax : AxSem.mixin_of mT syn;\n    base_de : DeSem.mixin_of mT syn;\n    mixin : mixin_of base_ax base_de;\n}.\n\nRecord type (mT : cpoDMT) := Pack {\n    syn : Type;\n    class : class_of mT syn;\n}.\n\nLocal Coercion syn : type >-> Sortclass.\nLocal Coercion class : type >-> class_of.\n\nDefinition to_axSem (mT : cpoDMT) (cT : type mT) :=\n    AxSem (syn cT) (base_ax cT).\n\nDefinition to_deSem (mT : cpoDMT) (cT : type mT) :=\n    DeSem (syn cT) (base_de cT).\n\nDefinition completeness_of (mT : cpoDMT) (cT : type mT) :=\n    completeness (mixin cT).\n\nEnd ClassDef.\n\nModule Exports.\n\n#[reversible]\nCoercion syn : type >-> Sortclass.\nCoercion class : type >-> class_of.\nCoercion mixin : class_of >-> mixin_of.\n\nCoercion to_axSem : type >-> axSem.\nCoercion to_deSem : type >-> deSem.\n\nNotation veriModC := type.\nNotation VeriModC s m := (@Pack _ s (Class m)).\n\nArguments completeness_of [_] _.\nNotation completeness_of := completeness_of.\n\nEnd Exports.\n\nEnd VeriModC.\nExport VeriModC.Exports.\n\n\n    \n(****************************************)\n(*                                      *)\n(*       VeriModSC                      *)\n(*       (Verification Module)          *)\n(*                                      *)\n(****************************************)\n\n\n(* sound and complete *)\nModule VeriModSC.\nSection ClassDef.\n\nDefinition axiom (mT : cpoDMT) (syn : Type)\n    (ax_m : AxSem.mixin_of mT syn) (de_m : DeSem.mixin_of mT syn) \n    (base_ax := AxSem syn ax_m) (base_de := DeSem syn de_m) :=\n        forall (s : syn) (P Q : [cpo of mT]),\n        P ⊑ ⟦ s ⟧ <base_de> Q <-> ⊢ <base_ax> { P } s { Q }.\n\n\nLemma to_soundness (mT : cpoDMT) (syn : Type)\n    (ax_m : AxSem.mixin_of mT syn) (de_m : DeSem.mixin_of mT syn) \n    (base_ax := AxSem syn ax_m) (base_de := DeSem syn de_m):\n\n    axiom base_ax base_de -> VeriModS.axiom base_ax base_de.\nProof. rewrite /axiom /VeriModS.axiom => H s P Q.\n    by rewrite H.\nQed.\n\n\nLemma to_completeness (mT : cpoDMT) (syn : Type)\n    (ax_m : AxSem.mixin_of mT syn) (de_m : DeSem.mixin_of mT syn) \n    (base_ax := AxSem syn ax_m) (base_de := DeSem syn de_m):\n\n    axiom base_ax base_de -> VeriModC.axiom base_ax base_de.\nProof. rewrite /axiom /VeriModC.axiom => H s P Q.\n    by rewrite H.\nQed.\n\n\nRecord mixin_of (mT : cpoDMT) (syn : Type)\n    (ax_m : AxSem.mixin_of mT syn) (de_m : DeSem.mixin_of mT syn)\n    (veriS_m : VeriModS.mixin_of ax_m de_m) \n    (veriC_m : VeriModC.mixin_of ax_m de_m) \n        : Type := Mixin {\n}.\n\n\nLemma combine (mT : cpoDMT) (syn : Type)\n    (ax_m : AxSem.mixin_of mT syn) (de_m : DeSem.mixin_of mT syn) \n    (veriS_m : VeriModS.mixin_of ax_m de_m) \n    (veriC_m : VeriModC.mixin_of ax_m de_m) :\n\n    axiom ax_m de_m.\n\nProof. rewrite /axiom => s P Q. split.\n    destruct veriC_m as [H_C]. by apply H_C. \n    destruct veriS_m as [H_S]. by apply H_S.\nQed.\n\n\nRecord class_of (mT : cpoDMT) (syn : Type) : Type := Class {\n    base_ax : AxSem.mixin_of mT syn;\n    base_de : DeSem.mixin_of mT syn;\n    equiv : axiom base_ax base_de;\n}.\n\nRecord type (mT : cpoDMT) := Pack {\n    syn : Type;\n    class : class_of mT syn;\n}.\n\nLocal Coercion syn : type >-> Sortclass.\nLocal Coercion class : type >-> class_of.\n\nDefinition pack (mT : cpoDMT) (syn : Type) \n    (ax_m : AxSem.mixin_of mT syn) (de_m : DeSem.mixin_of mT syn)\n    (veriS_m : VeriModS.mixin_of ax_m de_m) \n    (veriC_m : VeriModC.mixin_of ax_m de_m) \n    (m : mixin_of veriS_m veriC_m) : type mT :=\n        Pack (Class (combine veriS_m veriC_m)).\n\nDefinition to_veriModS (mT : cpoDMT) (cT : type mT) :=\n    VeriModS (syn cT) (VeriModS.Mixin (to_soundness (equiv cT))).\n\nDefinition to_veriModC (mT : cpoDMT) (cT : type mT) :=\n    VeriModC (syn cT) (VeriModC.Mixin (to_completeness (equiv cT))).\n\nEnd ClassDef.\n\nModule Exports.\n\n#[reversible]\nCoercion syn : type >-> Sortclass.\nCoercion class : type >-> class_of.\n\nCoercion to_veriModS : type >-> veriModS.\nCoercion to_veriModC : type >-> veriModC.\n\nNotation veriModSC := type.\nNotation VeriModSC s m := (@pack _ s _ _ _ _ m).\n\nEnd Exports.\n\nEnd VeriModSC.\nExport VeriModSC.Exports.\n\n\n(****************************************)\n(*                                      *)\n(*       FlowCtrl                       *)\n(*       (flow contrl)                  *)\n(*                                      *)\n(****************************************)\n\nModule FlowCtrl.\n\n\n\nRecord join (mT : cpo) := {\n\n    join_op : mT -> mT -> mT;\n    join_monot1 : forall x, MonotonicFun.mixin_of (join_op x);\n    join_monot0 : forall y, MonotonicFun.mixin_of (join_op ^~ y);\n    join_conti0 : forall x, ContinuousFun.mixin_of (join_monot0 x);\n    join_conti1 : forall x, ContinuousFun.mixin_of (join_monot1 x);\n    (*\n    join_conti : \n        forall (g f : [mT ↦ mT]) (ch : chain mT),\n        join_op (⊔ᶜᵖᵒ (f [<] ch)) (⊔ᶜᵖᵒ (g [<] ch)) = \n        ⊔ᶜᵖᵒ ((fun x => join_op (f x) (g x)) [<] ch);\n    *)\n}.\n\nRecord split (mT : cpo) (Hj : join mT) := {\n    M0 : [ mT ↦ mT ];\n    M1 : [ mT ↦ mT ];\n    split_join_consistency : \n        forall x, join_op Hj (M0 x) (M1 x) = x;\n}.\n\nModule Exports.\n\nNotation \" x ⊕[ Hj ] y \" := (join_op Hj x y) : MetaLan_scope.\n\nEnd Exports.\n\nEnd FlowCtrl.\n\nExport FlowCtrl.Exports.\n\nLemma flow_join_comp_chain_mixin (mT : cpo) (Hj : FlowCtrl.join mT) \n        (f g : [mT ↦ mT]) (ch : chain mT):\n        Chain.mixin_of ((fun x => (f x) ⊕[Hj] (g x)) [<] ch).\nProof.\n    rewrite /Chain.mixin_of.\n    porder_level.\n    case (Chain.class ch _ a _ a0) => Hle.\n    - left. \n        transitivity (ContinuousFun.obj f x0 ⊕[ Hj] ContinuousFun.obj g x1).\n        apply FlowCtrl.join_monot1. by apply MonotonicFun.class.\n        apply FlowCtrl.join_monot0. by apply MonotonicFun.class.\n    - right.\n        transitivity (ContinuousFun.obj f x0 ⊕[ Hj] ContinuousFun.obj g x1).\n        apply FlowCtrl.join_monot0. by apply MonotonicFun.class.\n        apply FlowCtrl.join_monot1. by apply MonotonicFun.class.\nQed.\n\n    \n\nLemma flow_join_conti (mT : cpo) (Hj : FlowCtrl.join mT) (f g : [mT ↦ mT]) :\n\n    forall (x : chain mT), (⊔ᶜᵖᵒ (f [<] x)) ⊕[Hj] (⊔ᶜᵖᵒ (g [<] x))\n        = ⊔ᶜᵖᵒ (Chain ((fun x => (f x) ⊕[Hj] (g x)) [<] x)\n             (@flow_join_comp_chain_mixin _ Hj _ _ x)).\n\nProof. move => ch. (* symmetry. apply cpo_join_eqP. *)\n\n(*\n    have Hconti0 := (FlowCtrl.join_conti0 Hj).\n    rewrite /ContinuousFun.mixin_of in Hconti0. simpl in Hconti0.\n    rewrite {}Hconti0.\n    apply cpo_join_eqP.\n\n\n    have Hconti1 := (FlowCtrl.join_conti1 Hj).\n    rewrite /ContinuousFun.mixin_of in Hconti1. simpl in Hconti1.\n    rewrite {}Hconti1.\n    \n    porder_level.\n\n    apply /lubP. split.\n    \n    porder_level.\n    \n    transitivity (\n        ContinuousFun.obj f x ⊕[ Hj] \n        CPO.join_of (CPO.class mT) (monotonic_mapR_chain g ch)\n    ).\n    \n    + apply FlowCtrl.join_monot0.\n        apply CPO.join_prop. porder_level.\n    + apply FlowCtrl.join_monot1.\n        apply CPO.join_prop. porder_level.\n        \n    move => U H.\n\n\n\n    have Hconti0 := (FlowCtrl.join_conti0 Hj).\n    rewrite /ContinuousFun.mixin_of in Hconti0. simpl in Hconti0.\n    rewrite {}Hconti0.\n    apply CPO.join_prop.\n    porder_level.\n\n    \n    have Hconti1 := (FlowCtrl.join_conti1 Hj).\n    rewrite /ContinuousFun.mixin_of in Hconti1. simpl in Hconti1.\n    rewrite {}Hconti1.\n    apply CPO.join_prop.\n    porder_level.\n    apply H. porder_level.\n*)\nAdmitted.", "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/MetaLan.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883592602051, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.25587325714827586}}
{"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 View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import Behavior.\n\nSet Implicit Arguments.\n\n\nSection Simulation.\n  Definition SIM := forall (c1_src c1_tgt: Configuration.t), Prop.\n\n  Definition _sim (sim: SIM) (c1_src c1_tgt:Configuration.t): Prop :=\n    forall (WF_SRC: Configuration.wf c1_src)\n      (WF_TGT: Configuration.wf c1_tgt),\n      <<TERMINAL:\n        forall (TERMINAL_TGT: Threads.is_terminal (Configuration.threads c1_tgt)),\n        exists c2_src,\n          <<STEPS_SRC: rtc Configuration.tau_step c1_src c2_src>> /\\\n          <<TERMINAL_SRC: Threads.is_terminal (Configuration.threads c2_src)>>>> /\\\n      <<STEP:\n        forall e tid c2_tgt\n          (STEP_TGT: Configuration.step e tid c1_tgt c2_tgt),\n        exists c2_src,\n          <<STEP_SRC: Configuration.opt_step e tid c1_src c2_src>> /\\\n          <<SIM: sim c2_src c2_tgt>>>>\n  .\n\n  Lemma _sim_mon: monotone2 _sim.\n  Proof.\n    ii. exploit IN; eauto. i. des.\n    econs; eauto. ii.\n    exploit STEP; eauto. i. des. eauto.\n  Qed.\n  Hint Resolve _sim_mon: paco.\n\n  Definition sim: SIM := paco2 _sim bot2.\nEnd Simulation.\n#[export] Hint Resolve _sim_mon: paco.\n\n\nLemma sim_adequacy\n      c_src c_tgt\n      (WF_SRC: Configuration.wf c_src)\n      (WF_TGT: Configuration.wf c_tgt)\n      (SIM: sim c_src c_tgt):\n  behaviors Configuration.step c_tgt <2= behaviors Configuration.step c_src.\nProof.\n  i. revert c_src WF_SRC WF_TGT SIM.\n  induction PR; i.\n  - punfold SIM0. exploit SIM0; eauto. i. des.\n    hexploit TERMINAL0; eauto. i. des.\n    eapply rtc_tau_step_behavior; eauto.\n    econs 1. eauto.\n  - punfold SIM0. exploit SIM0; eauto. i. des.\n    exploit STEP0; eauto. i. des.\n    exploit Configuration.step_future; try exact STEP; eauto. i. des.\n    exploit Configuration.opt_step_future; try exact STEP_SRC; eauto. i. des.\n    inv SIM1; ss. inv STEP_SRC.\n    econs 2; eauto.\n  - punfold SIM0. exploit SIM0; eauto. i. des.\n    exploit STEP0; eauto. i. des.\n    exploit Configuration.step_future; try exact STEP; eauto. i. des.\n    exploit Configuration.opt_step_future; try exact STEP_SRC; eauto. i. des.\n    inv SIM1; ss. inv STEP_SRC.\n    econs 3; eauto.\n  - punfold SIM0. exploit SIM0; eauto. i. des.\n    exploit STEP0; eauto. i. des.\n    exploit Configuration.step_future; try exact STEP; eauto. i. des.\n    exploit Configuration.opt_step_future; try exact STEP_SRC; eauto. i. des.\n    inv SIM1; ss. inv STEP_SRC; eauto.\n    econs 4; eauto.\n  - econs 5.\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/SimpleSimulation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2558729150264261}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Basic.\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\nSet Implicit Arguments.\n\n\nLemma read_read_tview\n      loc ts released ord\n      tview0\n      (WF0: TView.wf tview0)\n      (WF_REL: View.opt_wf released):\n  TView.le\n    (TView.read_tview (TView.read_tview tview0 loc ts released ord) loc ts released ord)\n    (TView.read_tview tview0 loc ts released ord).\nProof.\n  econs; aggrtac;\n    (try by apply WF0);\n    repeat condtac; aggrtac.\nQed.\n\nLemma write_read_tview\n      loc ts ord1 ord2\n      tview0 sc0\n      (ORD: Ordering.le Ordering.seqcst ord2 -> Ordering.le Ordering.seqcst ord1)\n      (WF0: TView.wf tview0):\n  TView.le\n    (TView.read_tview (TView.write_tview tview0 sc0 loc ts ord1) loc ts\n                        (Some ((TView.rel (TView.write_tview tview0 sc0 loc ts ord1)) loc))\n                        ord2)\n    (TView.write_tview tview0 sc0 loc ts ord1).\nProof.\n  econs; repeat (try condtac; aggrtac; try apply WF0).\nQed.\n\nLemma write_write_tview\n      loc ts1 ts2 ord\n      (TS: Time.lt ts1 ts2)\n      tview0 sc0\n      (WF0: TView.wf tview0):\n  TView.le\n    (TView.write_tview (TView.write_tview tview0 sc0 loc ts1 ord)\n                         sc0\n                         loc ts2 ord)\n    (TView.write_tview tview0 sc0 loc ts2 ord).\nProof.\n  econs; repeat (try condtac; aggrtac).\n  all: try by apply WF0.\nQed.\n\nLemma read_fence_read_fence_tview\n      ord\n      tview0\n      (WF0: TView.wf tview0):\n  TView.le\n    (TView.read_fence_tview (TView.read_fence_tview tview0 ord) ord)\n    (TView.read_fence_tview tview0 ord).\nProof.\n  econs; aggrtac;\n    (try by apply WF0).\n  repeat condtac; viewtac.\nQed.\n\nLemma write_fence_write_fence_sc\n      ord\n      tview0 sc0\n      (WF0: TView.wf tview0):\n  TimeMap.le\n    (TView.write_fence_sc (TView.write_fence_tview tview0 sc0 ord) (TView.write_fence_sc tview0 sc0 ord) ord)\n    (TView.write_fence_sc tview0 sc0 ord).\nProof.\n  unfold TView.write_fence_tview, TView.write_fence_sc.\n  repeat (condtac; aggrtac).\nQed.\n\nLemma write_fence_write_fence_tview\n      ord\n      tview0 sc0\n      (WF0: TView.wf tview0):\n  TView.le\n    (TView.write_fence_tview (TView.write_fence_tview tview0 sc0 ord) (TView.write_fence_sc tview0 sc0 ord) ord)\n    (TView.write_fence_tview tview0 sc0 ord).\nProof.\n  econs; aggrtac;\n    (try by apply WF0);\n    (repeat condtac; aggrtac);\n    rewrite <- ? View.join_r; viewtac.\n  - apply write_fence_write_fence_sc; auto.\n  - apply write_fence_write_fence_sc; auto.\n  - apply write_fence_write_fence_sc; auto.\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/MergeTView.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.25587290981687844}}
{"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(** A persistent union-find data structure. *)\n\nRequire Import Wf.\nRequire Recdef.\nRequire Setoid.\nRequire Coq.Program.Wf.\nRequire Import Coqlib.\n\nOpen Scope nat_scope.\nSet Implicit Arguments.\n\nModule Type MAP.\n  Variable elt: Type.\n  Variable elt_eq: forall (x y: elt), {x=y} + {x<>y}.\n  Variable t: Type -> Type.\n  Variable empty: forall (A: Type), t A.\n  Variable get: forall (A: Type), elt -> t A -> option A.\n  Variable set: forall (A: Type), elt -> A -> t A -> t A.\n  Hypothesis gempty: forall (A: Type) (x: elt), get x (empty A) = None.\n  Hypothesis gsspec: forall (A: Type) (x y: elt) (v: A) (m: t A),\n    get x (set y v m) = if elt_eq x y then Some v else get x m.\nEnd MAP.\n\nUnset Implicit Arguments.\n\nModule Type UNIONFIND.\n  Variable elt: Type.\n  Variable elt_eq: forall (x y: elt), {x=y} + {x<>y}.\n  Variable t: Type.\n\n  Variable repr: t -> elt -> elt.\n  Hypothesis repr_canonical: forall uf a, repr uf (repr uf a) = repr uf a.\n\n  Definition sameclass (uf: t) (a b: elt) : Prop := repr uf a = repr uf b.\n  Hypothesis sameclass_refl:\n    forall uf a, sameclass uf a a.\n  Hypothesis sameclass_sym:\n    forall uf a b, sameclass uf a b -> sameclass uf b a.\n  Hypothesis sameclass_trans:\n    forall uf a b c,\n    sameclass uf a b -> sameclass uf b c -> sameclass uf a c.\n  Hypothesis sameclass_repr:\n    forall uf a, sameclass uf a (repr uf a).\n\n  Variable empty: t.\n  Hypothesis repr_empty:\n    forall a, repr empty a = a.\n  Hypothesis sameclass_empty:\n    forall a b, sameclass empty a b -> a = b.\n\n  Variable find: t -> elt -> elt * t.\n  Hypothesis find_repr:\n    forall uf a, fst (find uf a) = repr uf a.\n  Hypothesis find_unchanged:\n    forall uf a x, repr (snd (find uf a)) x = repr uf x.\n  Hypothesis sameclass_find_1:\n    forall uf a x y, sameclass (snd (find uf a)) x y <-> sameclass uf x y.\n  Hypothesis sameclass_find_2:\n    forall uf a, sameclass uf a (fst (find uf a)).\n  Hypothesis sameclass_find_3:\n    forall uf a, sameclass (snd (find uf a)) a (fst (find uf a)).\n\n  Variable union: t -> elt -> elt -> t.\n  Hypothesis repr_union_1:\n    forall uf a b x, repr uf x <> repr uf a -> repr (union uf a b) x = repr uf x.\n  Hypothesis repr_union_2:\n    forall uf a b x, repr uf x = repr uf a -> repr (union uf a b) x = repr uf b.\n  Hypothesis repr_union_3:\n    forall uf a b, repr (union uf a b) b = repr uf b.\n  Hypothesis sameclass_union_1:\n    forall uf a b, sameclass (union uf a b) a b.\n  Hypothesis sameclass_union_2:\n    forall uf a b x y, sameclass uf x y -> sameclass (union uf a b) x y.\n  Hypothesis sameclass_union_3:\n    forall uf a b x y,\n    sameclass (union uf a b) x y ->\n       sameclass uf x y \n    \\/ sameclass uf x a /\\ sameclass uf y b\n    \\/ sameclass uf x b /\\ sameclass uf y a.\n\n  Variable merge: t -> elt -> elt -> t.\n  Hypothesis repr_merge:\n    forall uf a b x, repr (merge uf a b) x = repr (union uf a b) x.\n  Hypothesis sameclass_merge:\n    forall uf a b x y, sameclass (merge uf a b) x y <-> sameclass (union uf a b) x y.\n\n  Variable path_ord: t -> elt -> elt -> Prop.\n  Hypothesis path_ord_wellfounded:\n    forall uf, well_founded (path_ord uf).\n  Hypothesis path_ord_canonical:\n    forall uf x y, repr uf x = x -> ~path_ord uf y x.\n  Hypothesis path_ord_merge_1:\n    forall uf a b x y,\n    path_ord uf x y -> path_ord (merge uf a b) x y.\n  Hypothesis path_ord_merge_2:\n    forall uf a b,\n    repr uf a <> repr uf b -> path_ord (merge uf a b) b (repr uf a).\n\n  Variable pathlen: t -> elt -> nat.\n  Hypothesis pathlen_zero:\n    forall uf a, repr uf a = a <-> pathlen uf a = O.\n  Hypothesis pathlen_merge:\n    forall uf a b x,\n    pathlen (merge uf a b) x =\n      if elt_eq (repr uf a) (repr uf b) then\n        pathlen uf x\n      else if elt_eq (repr uf x) (repr uf a) then \n        pathlen uf x + pathlen uf b + 1\n      else\n        pathlen uf x.\n  Hypothesis pathlen_gt_merge:\n    forall uf a b x y,\n    repr uf x = repr uf y ->\n    pathlen uf x > pathlen uf y ->\n    pathlen (merge uf a b) x > pathlen (merge uf a b) y.\n\nEnd UNIONFIND.\n\nModule UF (M: MAP) : UNIONFIND with Definition elt := M.elt.\n\nDefinition elt := M.elt.\nDefinition elt_eq := M.elt_eq.\n\n(* A set of equivalence classes over elt is represented by a map m.\n   M.get a m = Some a' means that a is in the same class as a'.\n   M.get a m = None means that a is the canonical representative\n     for its equivalence class. *)\n\n(* The ordering over elt induced by such a map.\n   repr_order m a a' iff M.get a' m = Some a.\n   This ordering must be well founded. *)\n\nDefinition order (m: M.t elt) (a a': elt) : Prop :=\n  M.get a' m = Some a.\n\nRecord unionfind : Type := mk { m: M.t elt; mwf: well_founded (order m) }.\n\nDefinition t := unionfind.\n\n(* The canonical representative of an element *)\n\nSection REPR.\n\nVariable uf: t.\n\nFunction repr (a: elt) {wf (order uf.(m)) a} : elt :=\n  match M.get a uf.(m) with\n  | Some a' => repr a'\n  | None => a\n  end.\nProof.\n  intros. auto.\n  apply mwf. \nQed.\n\nLemma repr_none:\n  forall a,\n  M.get a uf.(m) = None ->\n  repr a = a.\nProof.\n  intros.\n  functional induction (repr a). congruence. auto.\nQed.\n\nLemma repr_some:\n  forall a a', \n  M.get a uf.(m) = Some a' ->\n  repr a = repr a'.\nProof.\n  intros.\n  functional induction (repr a). congruence. congruence.\nQed.\n\nLemma repr_res_none:\n  forall (a: elt), M.get (repr a) uf.(m) = None.\nProof.\n  intros. functional induction (repr a). auto. auto.\nQed.\n\nLemma repr_canonical:\n  forall (a: elt), repr (repr a) = repr a.\nProof.\n  intros. apply repr_none. apply repr_res_none. \nQed.\n\nLemma repr_some_diff:\n  forall a a', M.get a uf.(m) = Some a' -> a <> repr a'.\nProof.\n  intros; red; intros. \n  assert (repr a = a). rewrite (repr_some a a'); auto. \n  assert (M.get a uf.(m) = None). rewrite <- H1. apply repr_res_none. \n  congruence.\nQed.\n\nEnd REPR.\n\nDefinition sameclass (uf: t) (a b: elt) : Prop :=\n  repr uf a = repr uf b.\n\nLemma sameclass_refl:\n  forall uf a, sameclass uf a a.\nProof.\n  intros. red. auto.\nQed.\n\nLemma sameclass_sym:\n  forall uf a b, sameclass uf a b -> sameclass uf b a.\nProof.\n  intros. red. symmetry. exact H.\nQed.\n\nLemma sameclass_trans:\n  forall uf a b c,\n  sameclass uf a b -> sameclass uf b c -> sameclass uf a c.\nProof.\n  intros. red. transitivity (repr uf b). exact H. exact H0.\nQed.\n\nLemma sameclass_repr:\n  forall uf a, sameclass uf a (repr uf a).\nProof.\n  intros. red. symmetry. rewrite repr_canonical. auto.\nQed.\n\n(* The empty unionfind structure (each element in its own class) *)\n\nLemma wf_empty:\n  well_founded (order (M.empty elt)).\nProof.\n  red. intros. apply Acc_intro. intros b RO. red in RO.\n  rewrite M.gempty in RO. discriminate.\nQed.\n\nDefinition empty : t := mk (M.empty elt) wf_empty.\n\nLemma repr_empty:\n  forall a, repr empty a = a.\nProof.\n  intros. apply repr_none. simpl. apply M.gempty.\nQed.\n\nLemma sameclass_empty:\n  forall a b, sameclass empty a b -> a = b.\nProof.\n  intros. red in H. repeat rewrite repr_empty in H. auto.\nQed.\n\n(* Merging two equivalence classes *)\n\nSection IDENTIFY.\n\nVariable uf: t.\nVariables a b: elt.\nHypothesis a_canon: M.get a uf.(m) = None.\nHypothesis not_same_class: repr uf b <> a.\n\nLemma identify_order:\n  forall x y,\n  order (M.set a b uf.(m)) y x <->\n  order uf.(m) y x \\/ (x = a /\\ y = b).\nProof.\n  intros until y. unfold order. rewrite M.gsspec.\n  destruct (M.elt_eq x a). intuition congruence. intuition congruence.\nQed.\n\nRemark identify_Acc_b:\n  forall x,\n  Acc (order uf.(m)) x -> repr uf x <> a -> Acc (order (M.set a b uf.(m))) x.\nProof.\n  induction 1; intros. constructor; intros.\n  rewrite identify_order in H2. destruct H2 as [A | [A B]].\n  apply H0; auto. rewrite <- (repr_some uf _ _ A). auto. \n  subst. elim H1. apply repr_none. auto.\nQed.  \n\nRemark identify_Acc:\n  forall x,\n  Acc (order uf.(m)) x -> Acc (order (M.set a b uf.(m))) x.\nProof.\n  induction 1. constructor; intros.\n  rewrite identify_order in H1. destruct H1 as [A | [A B]].\n  auto.\n  subst. apply identify_Acc_b; auto. apply uf.(mwf). \nQed.\n\nLemma identify_wf:\n  well_founded (order (M.set a b uf.(m))).\nProof.\n  red; intros. apply identify_Acc. apply uf.(mwf). \nQed.\n\nDefinition identify := mk (M.set a b uf.(m)) identify_wf.\n\nLemma repr_identify_1:\n  forall x, repr uf x <> a -> repr identify x = repr uf x.\nProof.\n  intros. functional induction (repr uf x).\n\n  rewrite <- IHe; auto. apply repr_some. simpl. rewrite M.gsspec. \n  destruct (M.elt_eq a0 a). congruence. auto.\n\n  apply repr_none. simpl. rewrite M.gsspec. rewrite dec_eq_false; auto.\nQed.\n\nLemma repr_identify_2:\n  forall x, repr uf x = a -> repr identify x = repr uf b.\nProof.\n  intros. functional induction (repr uf x).\n\n  rewrite <- IHe; auto. apply repr_some. simpl. rewrite M.gsspec. \n  rewrite dec_eq_false; auto. congruence. \n\n  transitivity (repr identify b). apply repr_some. simpl. \n  rewrite M.gsspec. apply dec_eq_true. \n  apply repr_identify_1. auto.\nQed.\n\nEnd IDENTIFY.\n\n(* Union *)\n\nRemark union_not_same_class:\n  forall uf a b, repr uf a <> repr uf b -> repr uf (repr uf b) <> repr uf a.\nProof.\n  intros. rewrite repr_canonical. auto. \nQed.\n\nDefinition union (uf: t) (a b: elt) : t :=\n  let a' := repr uf a in\n  let b' := repr uf b in\n  match M.elt_eq a' b' with\n  | left EQ => uf\n  | right NEQ => identify uf a' b' (repr_res_none uf a) (union_not_same_class uf a b NEQ)\n  end.\n\nLemma repr_union_1:\n  forall uf a b x, repr uf x <> repr uf a -> repr (union uf a b) x = repr uf x.\nProof.\n  intros. unfold union. destruct (M.elt_eq (repr uf a) (repr uf b)).\n  auto.\n  apply repr_identify_1. auto.\nQed.\n\nLemma repr_union_2:\n  forall uf a b x, repr uf x = repr uf a -> repr (union uf a b) x = repr uf b.\nProof.\n  intros. unfold union. destruct (M.elt_eq (repr uf a) (repr uf b)).\n  congruence.\n  rewrite <- (repr_canonical uf b). apply repr_identify_2. auto.\nQed.\n\nLemma repr_union_3:\n  forall uf a b, repr (union uf a b) b = repr uf b.\nProof.\n  intros. unfold union. destruct (M.elt_eq (repr uf a) (repr uf b)).\n  auto. apply repr_identify_1. auto.\nQed.\n\nLemma sameclass_union_1:\n  forall uf a b, sameclass (union uf a b) a b.\nProof.\n  intros; red. rewrite repr_union_2; auto. rewrite repr_union_3. auto.\nQed.\n\nLemma sameclass_union_2:\n  forall uf a b x y, sameclass uf x y -> sameclass (union uf a b) x y.\nProof.\n  unfold sameclass; intros.\n  destruct (M.elt_eq (repr uf x) (repr uf a));\n  destruct (M.elt_eq (repr uf y) (repr uf a)).\n  repeat rewrite repr_union_2; auto.\n  congruence. congruence.\n  repeat rewrite repr_union_1; auto.\nQed.\n\nLemma sameclass_union_3:\n  forall uf a b x y,\n  sameclass (union uf a b) x y ->\n     sameclass uf x y \n  \\/ sameclass uf x a /\\ sameclass uf y b\n  \\/ sameclass uf x b /\\ sameclass uf y a.\nProof.\n  intros until y. unfold sameclass.\n  destruct (M.elt_eq (repr uf x) (repr uf a));\n  destruct (M.elt_eq (repr uf y) (repr uf a)).\n  intro. left. congruence.\n  rewrite repr_union_2; auto. rewrite repr_union_1; auto.\n  rewrite repr_union_1; auto. rewrite repr_union_2; auto.\n  repeat rewrite repr_union_1; auto.\nQed.\n\n(* Merge *)\n\nDefinition merge (uf: t) (a b: elt) : t :=\n  let a' := repr uf a in\n  let b' := repr uf b in\n  match M.elt_eq a' b' with\n  | left EQ => uf\n  | right NEQ => identify uf a' b (repr_res_none uf a) (sym_not_equal NEQ)\n  end.\n\nLemma repr_merge:\n  forall uf a b x, repr (merge uf a b) x = repr (union uf a b) x.\nProof.\n  intros. unfold merge, union. destruct (M.elt_eq (repr uf a) (repr uf b)).\n  auto.\n  destruct (M.elt_eq (repr uf x) (repr uf a)).\n  repeat rewrite repr_identify_2; auto. rewrite repr_canonical; auto.\n  repeat rewrite repr_identify_1; auto.\nQed.\n\nLemma sameclass_merge:\n  forall uf a b x y, sameclass (merge uf a b) x y <-> sameclass (union uf a b) x y.\nProof.\n  unfold sameclass; intros. repeat rewrite repr_merge. tauto.\nQed.\n\n(* Path order and merge *)\n\nDefinition path_ord (uf: t) : elt -> elt -> Prop := order uf.(m).\n\nLemma path_ord_wellfounded:\n  forall uf, well_founded (path_ord uf).\nProof.\n  intros. apply mwf. \nQed.\n\nLemma path_ord_canonical:\n  forall uf x y, repr uf x = x -> ~path_ord uf y x.\nProof.\n  intros; red; intros. hnf in H0.\n  assert (M.get x (m uf) = None). rewrite <- H. apply repr_res_none. \n  congruence.\nQed.\n\nLemma path_ord_merge_1:\n  forall uf a b x y,\n  path_ord uf x y -> path_ord (merge uf a b) x y.\nProof.\n  intros. unfold merge. \n  destruct (M.elt_eq (repr uf a) (repr uf b)).\n  auto.\n  red. simpl. red. rewrite M.gsspec. rewrite dec_eq_false. apply H. \n  red; intros. hnf in H. generalize (repr_res_none uf a). congruence.\nQed.\n\nLemma path_ord_merge_2:\n  forall uf a b,\n  repr uf a <> repr uf b -> path_ord (merge uf a b) b (repr uf a).\nProof.\n  intros. unfold merge.\n  destruct (M.elt_eq (repr uf a) (repr uf b)).\n  congruence.\n  red. simpl. red. rewrite M.gsspec. rewrite dec_eq_true; auto.\nQed.\n\n(* Path length and merge *)\n\nSection PATHLEN.\n\nVariable uf: t.\n\nFunction pathlen (a: elt) {wf (order uf.(m)) a} : nat :=\n  match M.get a uf.(m) with\n  | Some a' => S (pathlen a')\n  | None => O\n  end.\nProof.\n  intros. auto.\n  apply mwf. \nQed.\n\nLemma pathlen_none:\n  forall a,\n  M.get a uf.(m) = None ->\n  pathlen a = 0.\nProof.\n  intros.\n  functional induction (pathlen a). congruence. auto.\nQed.\n\nLemma pathlen_some:\n  forall a a', \n  M.get a uf.(m) = Some a' ->\n  pathlen a = S (pathlen a').\nProof.\n  intros.\n  functional induction (pathlen a). congruence. congruence.\nQed.\n\nLemma pathlen_zero:\n  forall a, repr uf a = a <-> pathlen a = O.\nProof.\n  intros; split; intros.\n  apply pathlen_none. rewrite <- H. apply repr_res_none. \n  functional induction (pathlen a).\n  congruence.\n  apply repr_none. auto.\nQed.\n\nEnd PATHLEN.\n\n(* Path length and merge *)\n\nLemma pathlen_merge:\n  forall uf a b x,\n  pathlen (merge uf a b) x =\n    if M.elt_eq (repr uf a) (repr uf b) then\n      pathlen uf x\n    else if M.elt_eq (repr uf x) (repr uf a) then \n      pathlen uf x + pathlen uf b + 1\n    else\n      pathlen uf x.\nProof.\n  intros. unfold merge. \n  destruct (M.elt_eq (repr uf a) (repr uf b)).\n  auto.\n  functional induction (pathlen (identify uf (repr uf a) b (repr_res_none uf a) (sym_not_equal n)) x).\n  simpl in e. rewrite M.gsspec in e. \n  destruct (M.elt_eq a0 (repr uf a)). \n  inversion e; subst a'; clear e. \n  replace (repr uf a0) with (repr uf a). rewrite dec_eq_true.\n  rewrite IHn0. rewrite dec_eq_false; auto. \n  rewrite (pathlen_none uf a0). omega. subst a0. apply repr_res_none. \n  subst a0. rewrite repr_canonical; auto.\n  rewrite (pathlen_some uf a0 a'); auto.\n  rewrite IHn0. \n  replace (repr uf a0) with (repr uf a').\n  destruct (M.elt_eq (repr uf a') (repr uf a)); omega.\n  symmetry. apply repr_some; auto.\n\n  simpl in e. rewrite M.gsspec in e. destruct (M.elt_eq a0 (repr uf a)). \n  congruence. rewrite (repr_none uf a0); auto. \n  rewrite dec_eq_false; auto. symmetry. apply pathlen_none; auto.\nQed.\n\nLemma pathlen_gt_merge:\n  forall uf a b x y,\n  repr uf x = repr uf y ->\n  pathlen uf x > pathlen uf y ->\n  pathlen (merge uf a b) x > pathlen (merge uf a b) y.\nProof.\n  intros. repeat rewrite pathlen_merge. \n  destruct (M.elt_eq (repr uf a) (repr uf b)). auto.\n  rewrite H. destruct (M.elt_eq (repr uf y) (repr uf a)).\n  omega. auto.\nQed.\n\n(* Path compression *)\n\nSection COMPRESS.\n\nVariable uf: t.\nVariable a b: elt.\nHypothesis a_diff_b: a <> b.\nHypothesis a_repr_b: repr uf a = b.\n\nLemma compress_order:\n  forall x y,\n  order (M.set a b uf.(m)) y x ->\n  order uf.(m) y x \\/ (x = a /\\ y = b).\nProof.\n  intros until y. unfold order. rewrite M.gsspec.\n  destruct (M.elt_eq x a).\n  intuition congruence.\n  auto.\nQed.\n\nRemark compress_Acc:\n  forall x,\n  Acc (order uf.(m)) x -> Acc (order (M.set a b uf.(m))) x.\nProof.\n  induction 1. constructor; intros.\n  destruct (compress_order _ _ H1) as [A | [A B]].\n  auto.\n  subst x y. constructor; intros. \n  destruct (compress_order _ _ H2) as [A | [A B]].\n  red in A. generalize (repr_res_none uf a). congruence.\n  congruence.\nQed.\n\nLemma compress_wf:\n  well_founded (order (M.set a b uf.(m))).\nProof.\n  red; intros. apply compress_Acc. apply uf.(mwf). \nQed.\n\nDefinition compress := mk (M.set a b uf.(m)) compress_wf.\n\nLemma repr_compress:\n  forall x, repr compress x = repr uf x.\nProof.\n  intros. functional induction (repr compress x).\n  simpl in e. rewrite M.gsspec in e. destruct (M.elt_eq a0 a).\n  subst a0. injection e; intros. subst a'. rewrite IHe. rewrite <- a_repr_b.\n  apply repr_canonical.\n  rewrite IHe. symmetry. apply repr_some; auto.\n  simpl in e. rewrite M.gsspec in e. destruct (M.elt_eq a0 a).\n  congruence. symmetry. apply repr_none. auto.\nQed.\n\nEnd COMPRESS.\n\n(* Find with path compression *)\n\nSection FIND.\n\nVariable uf: t.\n\nProgram Fixpoint find_x (a: elt) {wf (order uf.(m)) a} : \n    { r: elt * t | fst r = repr uf a /\\ forall x, repr (snd r) x = repr uf x } :=\n  match M.get a uf.(m) with\n  | Some a' =>\n      match find_x a' with\n      | pair b uf' => (b, compress uf' a b _ _)\n      end\n  | None => (a, uf)\n  end.\nNext Obligation.\n  red. auto.\nQed.\nNext Obligation.\n  (* a <> b*)\n  destruct (find_x a')\n  as [[b' uf''] [A B]]. simpl in *. inv Heq_anonymous0.\n  apply repr_some_diff. auto.\nQed.\nNext Obligation.\n  destruct (find_x a') as [[b' uf''] [A B]]. simpl in *. inv Heq_anonymous0.\n  rewrite B. apply repr_some. auto.\nQed.\nNext Obligation.\n  split.\n  destruct (find_x a')\n  as [[b' uf''] [A B]]. simpl in *. inv Heq_anonymous0.\n  symmetry. apply repr_some. auto.\n  intros. rewrite repr_compress. \n  destruct (find_x a')\n  as [[b' uf''] [A B]]. simpl in *. inv Heq_anonymous0. auto.\nQed.\nNext Obligation.\n  split; auto. symmetry. apply repr_none. auto.\nQed.\nNext Obligation.\n  apply mwf. \nDefined.\n\nDefinition find (a: elt) : elt * t := proj1_sig (find_x a).\n\nLemma find_repr:\n  forall a, fst (find a) = repr uf a.\nProof.\n  unfold find; intros. destruct (find_x a) as [[b uf'] [A B]]. simpl. auto. \nQed.\n\nLemma find_unchanged:\n  forall a x, repr (snd (find a)) x = repr uf x.\nProof.\n  unfold find; intros. destruct (find_x a) as [[b uf'] [A B]]. simpl. auto. \nQed.\n \nLemma sameclass_find_1:\n  forall a x y, sameclass (snd (find a)) x y <-> sameclass uf x y.\nProof.\n  unfold sameclass; intros. repeat rewrite find_unchanged. tauto.\nQed.\n\nLemma sameclass_find_2:\n  forall a, sameclass uf a (fst (find a)).\nProof.\n  intros. rewrite find_repr. apply sameclass_repr.\nQed.\n\nLemma sameclass_find_3:\n  forall a, sameclass (snd (find a)) a (fst (find a)).\nProof.\n  intros. rewrite sameclass_find_1. apply sameclass_find_2.\nQed.\n\nEnd FIND.\n\nEnd UF.\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/lib/UnionFind.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2558583023520827}}
{"text": "From Undecidability Require Import TM.Util.Prelim.\nFrom Undecidability Require Import TM.Code.Code.\nFrom Undecidability Require Import LM_heap_def.\n\n(* * Alphabets *)\n\nInductive ACom : Type := retAT | lamAT | appAT.\n\nCoercion ACom2Com (a : ACom) : Tok :=\n  match a with\n  | retAT => retT\n  | lamAT => lamT\n  | appAT => appT\n  end.\n\n\n#[global]\nInstance ACom_eq_dec : eq_dec ACom.\nProof. intros x y; hnf. decide equality. Defined. (* because instance *)\n\n#[global]\nInstance ACom_finType : finTypeC (EqType ACom).\nProof. split with (enum := [retAT; lamAT; appAT]). intros [ | | ]; cbn; reflexivity. Defined. (* because instance *)\n\n#[global]\nInstance ACom_inhab : inhabitedC ACom := ltac:(repeat constructor).\n\n#[global]\nInstance Encode_ACom : codable ACom ACom := Encode_Finite (FinType(EqType ACom)).\n\n\nCoercion Com_to_sum (t : Tok) : (nat + ACom) :=\n  match t with\n  | varT x => inl x\n  | appT => inr appAT\n  | lamT => inr lamAT\n  | retT => inr retAT\n  end.\n\nDefinition sigCom := sigSum sigNat ACom.\nDefinition sigCom_fin := FinType (EqType sigCom).\n\n#[global]\nInstance Encode_Com : codable sigCom Tok :=\n  {|\n    encode x := encode (Com_to_sum x)\n  |}.\n\nDefinition Encode_Com_size (t : Tok) : nat :=\n  size (Com_to_sum t).\n\nLemma Encode_Com_hasSize (t : Tok) :\n  size t = Encode_Com_size t.\nProof. reflexivity. Qed.\n\n\nDefinition sigHAdd := sigNat.\nDefinition sigHAdd_fin := FinType(EqType sigHAdd).\n\nDefinition sigPro := sigList sigCom.\n#[global]\nInstance Encode_Prog : codable sigPro Pro := _.\nDefinition sigPro_fin := FinType(EqType sigPro).\n\nDefinition sigHClos := sigPair sigHAdd sigPro.\nDefinition sigHClos_fin := FinType(EqType sigHClos).\n#[global]\nInstance Encode_HClos : codable sigHClos HClos := _.\n\nDefinition sigHEntr' := sigPair sigHClos sigHAdd.\n#[global]\nInstance Encode_HEntr' : codable (sigHEntr') (HClos*HAdd) := _.\nDefinition sigHEntr'_fin := FinType(EqType sigHEntr').\n\nDefinition sigHEntr := sigOption sigHEntr'.\n#[global]\nInstance Encode_HEntr : codable (sigHEntr) HEntr := _.\nDefinition sigHEntr_fin := FinType(EqType sigHEntr).\n\nDefinition sigHeap := sigList sigHEntr.\n#[global]\nInstance Encode_Heap : codable (sigHeap) Heap := _.\nDefinition sigHeap_fin := FinType(EqType sigHeap).\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/Alphabets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2557958585425036}}
{"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 Compopts.\nRequire Import AST.\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 ValueDomain.\nRequire Import ConstpropOp.\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 bc: block_classification.\nVariable ge: genv.\nHypothesis GENV: genv_match bc ge.\nVariable sp: block.\nHypothesis STACK: bc sp = BCstack.\nVariable ae: AE.t.\nVariable rs: regset.\nVariable m: mem.\nHypothesis MATCH: ematch bc rs ae.\n\nLemma match_G:\n  forall r id ofs,\n  AE.get r ae = Ptr(Gl id ofs) -> Val.lessdef rs#r (symbol_address ge id ofs).\nProof.\n  intros. apply vmatch_ptr_gl with bc; auto. rewrite <- H. apply MATCH. \nQed.\n\nLemma match_S:\n  forall r ofs,\n  AE.get r ae = Ptr(Stk ofs) -> Val.lessdef rs#r (Vptr sp ofs).\nProof.\n  intros. apply vmatch_ptr_stk with bc; auto. rewrite <- H. apply MATCH.\nQed.\n\nLtac InvApproxRegs :=\n  match goal with\n  | [ H: _ :: _ = _ :: _ |- _ ] => \n        injection H; clear H; intros; InvApproxRegs\n  | [ H: ?v = AE.get ?r ae |- _ ] => \n        generalize (MATCH r); rewrite <- H; clear H; intro; InvApproxRegs\n  | _ => idtac\n  end.\n\nLtac SimplVM :=\n  match goal with\n  | [ H: vmatch _ ?v (I ?n) |- _ ] =>\n      let E := fresh in\n      assert (E: v = Vint n) by (inversion H; auto);\n      rewrite E in *; clear H; SimplVM\n  | [ H: vmatch _ ?v (F ?n) |- _ ] =>\n      let E := fresh in\n      assert (E: v = Vfloat n) by (inversion H; auto);\n      rewrite E in *; clear H; SimplVM\n  | [ H: vmatch _ ?v (Ptr(Gl ?id ?ofs)) |- _ ] =>\n      let E := fresh in\n      assert (E: Val.lessdef v (Op.symbol_address ge id ofs)) by (eapply vmatch_ptr_gl; eauto); \n      clear H; SimplVM\n  | [ H: vmatch _ ?v (Ptr(Stk ?ofs)) |- _ ] =>\n      let E := fresh in\n      assert (E: Val.lessdef v (Vptr sp ofs)) by (eapply vmatch_ptr_stk; eauto); \n      clear H; SimplVM\n  | _ => idtac\n  end.\n\nLemma eval_static_shift_correct:\n  forall s n, eval_shift s (Vint n) = Vint (eval_static_shift s n).\nProof.\n  intros. destruct s; simpl; rewrite s_range; auto.\nQed.\n\nLemma cond_strength_reduction_correct:\n  forall cond args vl,\n  vl = map (fun r => AE.get r ae) 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; SimplVM.\n- apply Val.swap_cmp_bool.\n- auto.\n- apply Val.swap_cmpu_bool.\n- auto.\n- rewrite eval_static_shift_correct. auto.\n- rewrite eval_static_shift_correct. auto. \n- destruct (Float.eq_dec n1 Float.zero).\n  subst n1. simpl. destruct (rs#r2); simpl; auto. rewrite Float.cmp_swap. auto.\n  simpl. rewrite H1; auto. \n- destruct (Float.eq_dec n2 Float.zero).\n  subst n2. simpl. auto.\n  simpl. rewrite H1; auto.\n- destruct (Float.eq_dec n1 Float.zero).\n  subst n1. simpl. destruct (rs#r2); simpl; auto. rewrite Float.cmp_swap. auto.\n  simpl. rewrite H1; auto. \n- destruct (Float.eq_dec n2 Float.zero); simpl; auto.\n  subst n2; auto.\n  rewrite H1; auto. \n- auto.\nQed.\n\nLemma make_cmp_base_correct:\n  forall c args vl,\n  vl = map (fun r => AE.get r ae) args ->\n  let (op', args') := make_cmp_base c args vl in\n  exists v, eval_operation ge (Vptr sp Int.zero) op' rs##args' m = Some v \n         /\\ Val.lessdef (Val.of_optbool (eval_condition c rs##args m)) v.\nProof.\n  intros. unfold make_cmp_base. \n  generalize (cond_strength_reduction_correct c args vl H). \n  destruct (cond_strength_reduction c args vl) as [c' args']. intros EQ.\n  econstructor; split. simpl; eauto. rewrite EQ. auto. \nQed.\n\nLemma make_cmp_correct:\n  forall c args vl,\n  vl = map (fun r => AE.get r ae) args ->\n  let (op', args') := make_cmp c args vl in\n  exists v, eval_operation ge (Vptr sp Int.zero) op' rs##args' m = Some v \n         /\\ Val.lessdef (Val.of_optbool (eval_condition c rs##args m)) v.\nProof.\n  intros c args vl.\n  assert (Y: forall r, vincl (AE.get r ae) (Uns 1) = true ->\n             rs#r = Vundef \\/ rs#r = Vint Int.zero \\/ rs#r = Vint Int.one).\n  { intros. apply vmatch_Uns_1 with bc. eapply vmatch_ge. eapply vincl_ge; eauto. apply MATCH. }\n  unfold make_cmp. case (make_cmp_match c args vl); intros.\n- destruct (Int.eq_dec n Int.one && vincl v1 (Uns 1)) eqn:E1.\n  simpl in H; inv H. InvBooleans. subst n. \n  exists (rs#r1); split; auto. simpl.\n  exploit Y; eauto. intros [A | [A | A]]; rewrite A; simpl; auto.\n  destruct (Int.eq_dec n Int.zero && vincl v1 (Uns 1)) eqn:E0.\n  simpl in H; inv H. InvBooleans. subst n. \n  exists (Val.xor rs#r1 (Vint Int.one)); split; auto. simpl.\n  exploit Y; eauto. intros [A | [A | A]]; rewrite A; simpl; auto.\n  apply make_cmp_base_correct; auto.\n- destruct (Int.eq_dec n Int.zero && vincl v1 (Uns 1)) eqn:E0.\n  simpl in H; inv H. InvBooleans. subst n. \n  exists (rs#r1); split; auto. simpl.\n  exploit Y; eauto. intros [A | [A | A]]; rewrite A; simpl; auto.\n  destruct (Int.eq_dec n Int.one && vincl v1 (Uns 1)) eqn:E1.\n  simpl in H; inv H. InvBooleans. subst n. \n  exists (Val.xor rs#r1 (Vint Int.one)); split; auto. simpl.\n  exploit Y; eauto. intros [A | [A | A]]; rewrite A; simpl; auto.\n  apply make_cmp_base_correct; auto.\n- apply make_cmp_base_correct; 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 (Vptr sp Int.zero) 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 r2,\n  rs#r2 = Vint n ->\n  let (op, args) := make_shlimm n r1 r2 in\n  exists v, eval_operation ge (Vptr sp Int.zero) op rs##args m = Some v /\\ Val.lessdef (Val.shl rs#r1 (Vint n)) v.\nProof.\n  Opaque mk_shift_amount.\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  destruct (Int.ltu n Int.iwordsize) eqn:?; intros.\n  econstructor; split. simpl; eauto.  rewrite mk_shift_amount_eq; auto. \n  econstructor; split; eauto. simpl. congruence.\nQed.\n\nLemma make_shrimm_correct:\n  forall n r1 r2,\n  rs#r2 = Vint n ->\n  let (op, args) := make_shrimm n r1 r2 in\n  exists v, eval_operation ge (Vptr sp Int.zero) 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  destruct (Int.ltu n Int.iwordsize) eqn:?; intros.\n  econstructor; split. simpl; eauto.  rewrite mk_shift_amount_eq; auto. \n  econstructor; split; eauto. simpl. congruence.\nQed.\n\nLemma make_shruimm_correct:\n  forall n r1 r2,\n  rs#r2 = Vint n ->\n  let (op, args) := make_shruimm n r1 r2 in\n  exists v, eval_operation ge (Vptr sp Int.zero) 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  destruct (Int.ltu n Int.iwordsize) eqn:?; intros.\n  econstructor; split. simpl; eauto.  rewrite mk_shift_amount_eq; auto. \n  econstructor; split; eauto. simpl. congruence.\nQed.\n\nLemma make_mulimm_correct:\n  forall n r1 r2,\n  rs#r2 = Vint n ->\n  let (op, args) := make_mulimm n r1 r2 in\n  exists v, eval_operation ge (Vptr sp Int.zero) 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  exploit Int.is_power2_range; eauto. intros R.\n  econstructor; split. simpl; eauto. rewrite mk_shift_amount_eq; auto.  \n  rewrite (Val.mul_pow2 rs#r1 _ _ Heqo). auto.\n  econstructor; split; eauto. simpl. congruence.\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 (Vptr sp Int.zero) 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 (Vptr sp Int.zero) 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  econstructor; split. simpl. rewrite mk_shift_amount_eq. eauto. \n  eapply Int.is_power2_range; eauto. auto.\n  eapply Val.divu_pow2; eauto. congruence.\n  exists v; auto.\nQed.\n\nLemma make_andimm_correct:\n  forall n r x,\n  vmatch bc rs#r x ->\n  let (op, args) := make_andimm n r x in\n  exists v, eval_operation ge (Vptr sp Int.zero) 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  destruct (match x with Uns k => Int.eq (Int.zero_ext k (Int.not n)) Int.zero\n                       | _ => false end) eqn:UNS.\n  destruct x; try congruence. \n  exists (rs#r); split; auto.\n  inv H; auto. simpl. replace (Int.and i n) with i; auto.\n  generalize (Int.eq_spec (Int.zero_ext n0 (Int.not n)) Int.zero); rewrite UNS; intro EQ.\n  Int.bit_solve. destruct (zlt i0 n0).\n  replace (Int.testbit n i0) with (negb (Int.testbit Int.zero i0)).\n  rewrite Int.bits_zero. simpl. rewrite andb_true_r. auto. \n  rewrite <- EQ. rewrite Int.bits_zero_ext by omega. rewrite zlt_true by auto. \n  rewrite Int.bits_not by auto. apply negb_involutive. \n  rewrite H5 by auto. 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 (Vptr sp Int.zero) 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 (Vptr sp Int.zero) 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  predSpec Int.eq Int.eq_spec n Int.mone; intros.\n  subst n. exists (Val.notint (rs#r)); split. auto.\n  destruct (rs#r); simpl; 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 (Vptr sp Int.zero) 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 (Vptr sp Int.zero) 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 make_cast8signed_correct:\n  forall r x,\n  vmatch bc rs#r x ->\n  let (op, args) := make_cast8signed r x in\n  exists v, eval_operation ge (Vptr sp Int.zero) op rs##args m = Some v /\\ Val.lessdef (Val.sign_ext 8 rs#r) v.\nProof.\n  intros; unfold make_cast8signed. destruct (vincl x (Sgn 8)) eqn:INCL. \n  exists rs#r; split; auto. \n  assert (V: vmatch bc rs#r (Sgn 8)).\n  { eapply vmatch_ge; eauto. apply vincl_ge; auto. }\n  inv V; simpl; auto. rewrite is_sgn_sign_ext in H3 by auto. rewrite H3; auto.\n  econstructor; split; simpl; eauto.\nQed.\n\nLemma make_cast16signed_correct:\n  forall r x,\n  vmatch bc rs#r x ->\n  let (op, args) := make_cast16signed r x in\n  exists v, eval_operation ge (Vptr sp Int.zero) op rs##args m = Some v /\\ Val.lessdef (Val.sign_ext 16 rs#r) v.\nProof.\n  intros; unfold make_cast16signed. destruct (vincl x (Sgn 16)) eqn:INCL. \n  exists rs#r; split; auto. \n  assert (V: vmatch bc rs#r (Sgn 16)).\n  { eapply vmatch_ge; eauto. apply vincl_ge; auto. }\n  inv V; simpl; auto. rewrite is_sgn_sign_ext in H3 by auto. rewrite H3; auto.\n  econstructor; split; simpl; eauto.\nQed.\n\nLemma make_singleoffloat_correct:\n  forall r x,\n  vmatch bc rs#r x ->\n  let (op, args) := make_singleoffloat r x in\n  exists v, eval_operation ge (Vptr sp Int.zero) op rs##args m = Some v /\\ Val.lessdef (Val.singleoffloat rs#r) v.\nProof.\n  intros; unfold make_singleoffloat. \n  destruct (vincl x Fsingle && generate_float_constants tt) eqn:INCL. \n  InvBooleans. exists rs#r; split; auto. \n  assert (V: vmatch bc rs#r Fsingle).\n  { eapply vmatch_ge; eauto. apply vincl_ge; auto. }\n  inv V; simpl; auto. rewrite Float.singleoffloat_of_single by auto. auto.\n  econstructor; split; simpl; eauto.\nQed.\n\nLemma op_strength_reduction_correct:\n  forall op args vl v,\n  vl = map (fun r => AE.get r ae) args ->\n  eval_operation ge (Vptr sp Int.zero) op rs##args m = Some v ->\n  let (op', args') := op_strength_reduction op args vl in\n  exists w, eval_operation ge (Vptr sp Int.zero) 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(* cast8signed *)\n  InvApproxRegs; SimplVM; inv H0. apply make_cast8signed_correct; auto.\n(* cast8signed *)\n  InvApproxRegs; SimplVM; inv H0. apply make_cast16signed_correct; auto.\n(* add *)\n  InvApproxRegs; SimplVM. inv H0. \n  fold (Val.add (Vint n1) rs#r2). rewrite Val.add_commut. apply make_addimm_correct.\n  InvApproxRegs; SimplVM. inv H0. apply make_addimm_correct.\n(* addshift *)\n  InvApproxRegs; SimplVM. inv H0. rewrite eval_static_shift_correct. apply make_addimm_correct.\n(* sub *)\n  InvApproxRegs; SimplVM. inv H0. econstructor; split; eauto. \n  InvApproxRegs; SimplVM. inv H0. rewrite Val.sub_add_opp. apply make_addimm_correct.\n(* subshift *)\n  InvApproxRegs; SimplVM. inv H0. rewrite eval_static_shift_correct. rewrite Val.sub_add_opp. apply make_addimm_correct.\n(* rsubshift *)\n  InvApproxRegs; SimplVM. inv H0. rewrite eval_static_shift_correct. econstructor; split; eauto.\n(* mul *)\n  InvApproxRegs; SimplVM. inv H0. fold (Val.mul (Vint n1) rs#r2).\n  rewrite Val.mul_commut. apply make_mulimm_correct; auto.\n  InvApproxRegs; SimplVM. inv H0. apply make_mulimm_correct; auto.\n(* divs *)\n  assert (rs#r2 = Vint n2). clear H0. InvApproxRegs; SimplVM; auto.\n  apply make_divimm_correct; auto.\n(* divu *)\n  assert (rs#r2 = Vint n2). clear H0. InvApproxRegs; SimplVM; auto.\n  apply make_divuimm_correct; auto.\n(* and *)\n  InvApproxRegs; SimplVM. inv H0. fold (Val.and (Vint n1) rs#r2). rewrite Val.and_commut. apply make_andimm_correct; auto.\n  InvApproxRegs; SimplVM. inv H0. apply make_andimm_correct; auto.\n(* andshift *)\n  InvApproxRegs; SimplVM. inv H0. rewrite eval_static_shift_correct. apply make_andimm_correct; auto.\n(* or *)\n  InvApproxRegs; SimplVM. inv H0. fold (Val.or (Vint n1) rs#r2). rewrite Val.or_commut. apply make_orimm_correct.\n  InvApproxRegs; SimplVM. inv H0. apply make_orimm_correct.\n(* orshift *)\n  InvApproxRegs; SimplVM. inv H0. rewrite eval_static_shift_correct. apply make_orimm_correct.\n(* xor *)\n  InvApproxRegs; SimplVM. inv H0. fold (Val.xor (Vint n1) rs#r2). rewrite Val.xor_commut. apply make_xorimm_correct.\n  InvApproxRegs; SimplVM. inv H0. apply make_xorimm_correct.\n(* xorshift *)\n  InvApproxRegs; SimplVM. inv H0. rewrite eval_static_shift_correct. apply make_xorimm_correct.\n(* bic *)\n  InvApproxRegs; SimplVM. inv H0. apply make_andimm_correct; auto.\n(* bicshift *)\n  InvApproxRegs; SimplVM. inv H0. rewrite eval_static_shift_correct. apply make_andimm_correct; auto.\n(* shl *)\n  InvApproxRegs; SimplVM. inv H0. apply make_shlimm_correct; auto.\n(* shr *)\n  InvApproxRegs; SimplVM. inv H0. apply make_shrimm_correct; auto.\n(* shru *)\n  InvApproxRegs; SimplVM. inv H0. apply make_shruimm_correct; auto.\n(* singleoffloat *)\n  InvApproxRegs; SimplVM; inv H0. apply make_singleoffloat_correct; auto.\n(* cmp *)\n  inv H0. apply make_cmp_correct; auto.\n(* mulf *)\n  InvApproxRegs; SimplVM; inv H0. rewrite <- H2. apply make_mulfimm_correct; auto.\n  InvApproxRegs; SimplVM; inv H0. fold (Val.mulf (Vfloat n1) rs#r2).\n  rewrite <- H2. apply make_mulfimm_correct_2; auto.\n(* default *)\n  exists v; auto.\nQed.\n\nLemma addr_strength_reduction_correct:\n  forall addr args vl res,\n  vl = map (fun r => AE.get r ae) args ->\n  eval_addressing ge (Vptr sp Int.zero) addr rs##args = Some res ->\n  let (addr', args') := addr_strength_reduction addr args vl in\n  exists res', eval_addressing ge (Vptr sp Int.zero) addr' rs##args' = Some res' /\\ Val.lessdef res res'.\nProof.\n  intros until res. unfold addr_strength_reduction.\n  destruct (addr_strength_reduction_match addr args vl); simpl;\n  intros VL EA; InvApproxRegs; SimplVM; try (inv EA).\n- rewrite Int.add_zero_l. \n  change (Vptr sp (Int.add n1 n2)) with (Val.add (Vptr sp n1) (Vint n2)).\n  econstructor; split; eauto. apply Val.add_lessdef; auto.\n- fold (Val.add (Vint n1) rs#r2).  rewrite Int.add_zero_l. rewrite Int.add_commut.\n  change (Vptr sp (Int.add n2 n1)) with (Val.add (Vptr sp n2) (Vint n1)).\n  rewrite Val.add_commut. econstructor; split; eauto. apply Val.add_lessdef; auto.\n- fold (Val.add (Vint n1) rs#r2).\n  rewrite Val.add_commut. econstructor; split; eauto.\n- econstructor; split; eauto.\n- rewrite eval_static_shift_correct. rewrite Int.add_zero_l. \n  change (Vptr sp (Int.add n1 (eval_static_shift s n2)))\n    with (Val.add (Vptr sp n1) (Vint (eval_static_shift s n2))).\n  econstructor; split; eauto. apply Val.add_lessdef; auto.\n- rewrite eval_static_shift_correct. econstructor; split; eauto. \n- rewrite Int.add_zero_l. change (Vptr sp (Int.add n1 n)) with (Val.add (Vptr sp n1) (Vint n)). \n  econstructor; split; eauto. apply Val.add_lessdef; auto.\n- exists res; auto.\nQed.\n\nEnd STRENGTH_REDUCTION.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/compcert/arm/ConstpropOpproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2557958585425036}}
{"text": "(* This file contains the formalisation of lemma 19 and corollary 20 *)\n\nRequire Import general.\nRequire Import lterms.\nRequire Import erase_facts.\nRequire Import svars.\nRequire Import subterms.\nRequire Import standard.\nRequire Import sred.\nRequire Import ared.\nRequire Import sexpand_std.\n\nLemma lem_a_root_commute :\n  forall x y z, RootContr_clc_a x y -> RootContr_clc_s x z -> Standard y ->\n                exists u, (RootContr_clc_a z u \\/ z = u) /\\ Red_clc_s y u.\nProof.\n  intros.\n  invert_rcontr_clc_a.\n  yintuition; yintuition; try yelles 1.\n  invert_rcontr_clc_s.\n  yintuition; yintuition; yelles 1.\nQed.\n\nLemma lem_standard_implies_glue_iterms_l :\n  forall y, Standard y -> forall z, In z (tuple_of_lterm y) -> R_glue_iterms_l Contr_clc_s z.\nProof.\n  unfold R_glue_iterms_l.\n  intros.\n  assert (HStd_z: Std z).\n  unfold Standard in *; pose_subterm; ydestruct y; simpl in *; ycrush.\n  assert (HH: is_iterm z = true \\/ Sterm z).\n  assert (is_ltup z = false).\n  assert (Std y).\n  apply lem_standard_implies_std; ycrush.\n  ydestruct y; simpl in *; yisolve.\n  ydestruct z; simpl in *; yisolve.\n  destruct HH.\n  destruct z, x', y0; pose lem_contr_s_basic; pose_contr_s; ycrush.\n  assert (Sterm x').\n  unfold Std in *; pose_red_s; ycrush.\n  destruct z, x'; pose_contr_s; ycrush.\nQed.\n\nLemma lem_standard_implies_glue_iterms_r :\n  forall y, Standard y -> forall z, In z (tuple_of_lterm y) -> R_glue_iterms_r Contr_clc_s z.\nProof.\n  unfold R_glue_iterms_r.\n  intros.\n  assert (HStd_z: Std z).\n  unfold Standard in *; pose_subterm; ydestruct y; simpl in *; ycrush.\n  assert (HH: is_iterm z = true \\/ Sterm z).\n  assert (is_ltup z = false).\n  assert (Std y).\n  apply lem_standard_implies_std; ycrush.\n  ydestruct y; simpl in *; yisolve.\n  ydestruct z; simpl in *; yisolve.\n  destruct HH.\n  destruct z, y', x; pose lem_contr_s_basic; pose_contr_s; ycrush.\n  assert (Sterm y').\n  unfold Std in *; pose_red_s; ycrush.\n  destruct z, y', x; pose_contr_s; ycrush.\nQed.\n\nLemma lem_standard_red_s_preserves_not_ltup :\n  forall x y, Standard x -> Red_clc_s x y -> is_ltup x = false -> is_ltup y = false.\nProof.\n  intros.\n  assert (Std x).\n  unfold Standard in *; pose_subterm; ycrush.\n  assert (HH: is_iterm x = true \\/ Sterm x).\n  ydestruct x; unfold Std in *; yisolve.\n  destruct HH.\n  assert (is_iterm y = true).\n  assert (lterm_basic x).\n  ydestruct x; ycrush.\n  assert (x = y).\n  pose lem_red_s_basic; ycrush.\n  ycrush.\n  ydestruct y; ycrush.\n  assert (Sterm y).\n  unfold Std in *; ycrush.\n  ydestruct y; ycrush.\nQed.\n\nLemma lem_standard_contr_s_preserves_no_nested_tuple :\n  forall y y', Standard y -> Contr_clc_s y y' ->\n               (forall x, In x (tuple_of_lterm y) -> is_ltup x = false) ->\n               forall x, In x (tuple_of_lterm y') -> is_ltup x = false.\nProof.\n  intros.\n  assert (is_ltup y' = true \\/ is_ltup y' = false) by ycrush.\n  yintuition.\n  ydestruct y'; yisolve; simpl in *.\n  yinversion H0; fold Contr_clc_s in *; simpl in *.\n  ydestruct y; yisolve; simpl in *.\n  ydestruct y1; yisolve; simpl in *.\n  assert (Red_clc_s (I1 @l y2) y2).\n  apply lem_rcontr_s_to_red_s; ycrush.\n  assert (is_ltup y2 = false).\n  eapply lem_standard_red_s_preserves_not_ltup; ycrush.\n  ycrush.\n  ydestruct y1_1; yisolve; simpl in *.\n  assert (Red_clc_s (K1 @l y1_2 @l y2) y1_2).\n  apply lem_rcontr_s_to_red_s; ycrush.\n  assert (is_ltup y1_2 = false).\n  eapply lem_standard_red_s_preserves_not_ltup; ycrush.\n  ycrush.\n  ydestruct y1_1_1; yisolve; simpl in *.\n  ydestruct y1_1_2; yisolve; simpl in *.\n  assert (Red_clc_s (C1 @l T1 @l y1_2 @l y2) y1_2).\n  apply lem_rcontr_s_to_red_s; ycrush.\n  assert (is_ltup y1_2 = false).\n  eapply lem_standard_red_s_preserves_not_ltup; ycrush.\n  ycrush.\n  assert (Red_clc_s (C1 @l F1 @l y1_2 @l y2) y2).\n  apply lem_rcontr_s_to_red_s; ycrush.\n  assert (is_ltup y2 = false).\n  eapply lem_standard_red_s_preserves_not_ltup; ycrush.\n  ycrush.\n  simp_hyps.\n  destruct H0.\n  assert (Red_clc_s (C2 @l y1_1_2 @l y1_2 @l y2) y1_2).\n  apply lem_rcontr_s_to_red_s; ycrush.\n  assert (is_ltup y1_2 = false).\n  eapply lem_standard_red_s_preserves_not_ltup; ycrush.\n  ycrush.\n  assert (Red_clc_s (C2 @l y1_1_2 @l y1_2 @l y2) y2).\n  apply lem_rcontr_s_to_red_s; ycrush.\n  assert (is_ltup y2 = false).\n  eapply lem_standard_red_s_preserves_not_ltup; ycrush.\n  ycrush.\n  simp_hyps.\n  unfold build_s_result in *.\n  assert (exists a b s, split_in_groups l0 (tuple_of_lterm y2) = a :: b :: s).\n  ydestruct l0.\n  generalize (lem_tuple_len_nonzero y1_2); simpl in *; omega.\n  pose lem_split_result; ycrush.\n  ycrush.\n  destruct H2; subst.\n  assert (Standard x0).\n  pose lem_subterm_standard; pose_subterm; ycrush.\n  eapply lem_standard_red_s_preserves_not_ltup; pose_red_s; ycrush.\n  ycrush.\n  destruct H2; subst.\n  ycrush.\n  destruct H0; subst.\n  assert (Standard y0).\n  pose lem_subterm_standard; pose_subterm; ycrush.\n  eapply lem_standard_red_s_preserves_not_ltup; pose_red_s; ycrush.\n  ycrush.\n  destruct H2; subst.\n  ycrush.\n  destruct H0; subst.\n  ycrush.\n  induction l0; simpl in *.\n  destruct H0; subst.\n  assert (Standard z).\n  assert (HH: z :: l' = nil ++ z :: l') by ycrush.\n  rewrite HH in *; clear HH.\n  pose lem_subterm_standard; pose_subterm; ycrush.\n  eapply lem_standard_red_s_preserves_not_ltup; pose_red_s; ycrush.\n  ycrush.\n  destruct H0; subst.\n  ycrush.\n  assert (Standard (ltup y'1 y'2 (l0 ++ z :: l'))).\n  eapply lem_standard_ltup; ycrush.\n  apply IHl0; ycrush.\n  assert (HH: tuple_of_lterm y' = y' :: nil).\n  ydestruct y'; ycrush.\n  rewrite HH in *; clear HH; simpl in *.\n  ycrush.\nQed.\n\nLemma lem_a_commute_0 :\n  forall x y z, RootContr_clc_a x y -> Contr_clc_s x z -> Standard y ->\n                exists u, (RootContr_clc_a z u \\/ z = u) /\\ Red_clc_s y u.\nProof.\n  intros.\n  yinversion H0; fold Contr_clc_s in *; try yelles 1.\n  \n  pose lem_a_root_commute; ycrush.\n  \n  invert_rcontr_clc_a; yintuition; yintuition.\n  yinversion H; repeat invert_contr_clc_s; [ yelles 2 | yelles 2 | racrush ].\n  yinversion H; repeat invert_contr_clc_s; [ yelles 2 | yelles 2 |\n                                             ydestruct x; yisolve; yelles 2 ].\n  yinversion H; repeat invert_contr_clc_s.\n  yelles 2.\n  ydestruct x2; yisolve; yelles 2.\n  assert (ErasedEqv y' x1) by\n      (eauto 8 using lem_red_s_implies_erased_eqv, lem_erased_eqv_trans,\n       lem_erased_eqv_sym, lem_contr_s_to_red_s).\n  racrush.\n  yinversion H3; yinversion H2; yinversion H.\n  yinversion H; repeat invert_contr_clc_s; [ yelles 2 | racrush ].\n  ydestruct x0; yisolve.\n  ydestruct x0_1; yisolve.\n  ydestruct x0_1_1; yisolve; simp_hyps.\n  repeat invert_contr_clc_s.\n  clear -H12; yelles 2.\n  assert (is_nonempty l).\n  ydestruct l; ycrush.\n  assert (Red_clc_s (build_s_result l x0_1_2 (tuple_of_lterm x0_2) (tuple_of_lterm y0))\n                      (build_s_result l y' (tuple_of_lterm x0_2) (tuple_of_lterm y0))).\n  pose lem_contr_s_s_result_1; pose_red_s; ycrush.\n  assert (RootContr_clc_a (S1 l @l y' @l x0_2 @l y0)\n                          (build_s_result l y' (tuple_of_lterm x0_2) (tuple_of_lterm y0))).\n  racrush.\n  ycrush.\n  assert (is_nonempty l).\n  ydestruct l; ycrush.\n  assert (forall z, In z (tuple_of_lterm x0_2) -> R_glue_iterms_l Contr_clc_s z).\n  assert (Standard x0_2).\n  assert (RootContr_S (S1 l @l x0_1_2 @l x0_2 @l y0)\n                      (build_s_result l x0_1_2 (tuple_of_lterm x0_2) (tuple_of_lterm y0))) by ycrush.\n  eapply lem_standard_expand_below_S_redex; pose_subterm; ycrush.\n  apply lem_standard_implies_glue_iterms_l; ycrush.\n  assert (Red_clc_s (build_s_result l x0_1_2 (tuple_of_lterm x0_2) (tuple_of_lterm y0))\n                      (build_s_result l x0_1_2 (tuple_of_lterm y') (tuple_of_lterm y0))).\n  pose lem_contr_s_s_result_2; pose_red_s; ycrush.\n  assert (is_ltup y' = true).\n  pose lem_contr_s_preserves_is_ltup; ycrush.\n  assert (length (tuple_of_lterm y') = length l).\n  rewrite <- lem_contr_s_length with (x := x0_2); ycrush.\n  assert (All_pairs (tuple_of_lterm y') ErasedEqv).\n  pose lem_contr_s_all_pairs_erased_eqv; ycrush.\n  assert (RootContr_clc_a (S1 l @l x0_1_2 @l y' @l y0)\n                          (build_s_result l x0_1_2 (tuple_of_lterm y') (tuple_of_lterm y0))).\n  racrush.\n  ycrush.\n  repeat invert_contr_clc_s.\n  clear -H10; yelles 2.\n  exists (y' @l lterm_of_tuple (firstn n (tuple_of_lterm y0)) @l\n             (glue_iterms x0_2 (lterm_of_tuple (skipn n (tuple_of_lterm y0))))).\n  racrush.\n  exists (x0_1_2 @l lterm_of_tuple (firstn n (tuple_of_lterm y0)) @l\n                 (glue_iterms y' (lterm_of_tuple (skipn n (tuple_of_lterm y0))))).\n  assert (Standard x0_2).\n  apply lem_standard_expand_below_S_redex with\n  (r1 := S2 n @l x0_1_2 @l x0_2 @l y0)\n    (r2 := x0_1_2 @l lterm_of_tuple (firstn n (tuple_of_lterm y0)) @l\n                  (glue_iterms x0_2 (lterm_of_tuple (skipn n (tuple_of_lterm y0)))));\n    pose lem_s2_discriminate_y; pose_subterm; ycrush.\n  assert (Red_clc_s\n            (x0_1_2 @l lterm_of_tuple (firstn n (tuple_of_lterm y0)) @l\n                    (glue_iterms x0_2 (lterm_of_tuple (skipn n (tuple_of_lterm y0)))))\n            (x0_1_2 @l lterm_of_tuple (firstn n (tuple_of_lterm y0)) @l\n                    (glue_iterms y' (lterm_of_tuple (skipn n (tuple_of_lterm y0)))))).\n  assert (RootContr_S\n            (S2 n @l x0_1_2 @l x0_2 @l y0)\n            (x0_1_2 @l lterm_of_tuple (firstn n (tuple_of_lterm y0)) @l\n                    (glue_iterms x0_2 (lterm_of_tuple (skipn n (tuple_of_lterm y0)))))).\n  ycrush.\n  pose lem_standard_implies_glue_iterms_l.\n  unfold R_glue_iterms_l in *.\n  assert (Contr_clc_s (glue_iterms x0_2 (lterm_of_tuple (skipn n (tuple_of_lterm y0))))\n                      (glue_iterms y' (lterm_of_tuple (skipn n (tuple_of_lterm y0))))).\n  assert (tuple_of_lterm x0_2 = x0_2 :: nil) by ycrush.\n  eapply r; ycrush.\n  pose_red_s; ycrush.\n  assert (is_ltup y' = false).\n  pose lem_standard_not_reduces_to_tuple; pose_red_s; ycrush.\n  assert (RootContr_clc_a (S2 n @l x0_1_2 @l y' @l y0)\n                          (x0_1_2 @l lterm_of_tuple (firstn n (tuple_of_lterm y0)) @l\n                                  (glue_iterms y' (lterm_of_tuple (skipn n (tuple_of_lterm y0)))))).\n  racrush.\n  ycrush.\n\n  invert_rcontr_clc_a; yintuition; yintuition.\n  yinversion H; repeat invert_contr_clc_s; ydestruct x1; yisolve; yelles 2.\n  yinversion H; repeat invert_contr_clc_s; racrush.\n  yinversion H; repeat invert_contr_clc_s.\n  assert (ErasedEqv x y') by\n      (eauto 8 using lem_red_s_implies_erased_eqv, lem_erased_eqv_trans,\n       lem_erased_eqv_sym, lem_contr_s_to_red_s).\n  racrush.\n  yinversion H3; racrush.\n  yinversion H; repeat invert_contr_clc_s; ydestruct x1; yisolve; yelles 2.\n  ydestruct x0; yisolve.\n  ydestruct x0_1; yisolve.\n  ydestruct x0_1_1; yisolve; simp_hyps.\n  assert (is_nonempty l).\n  ydestruct l; ycrush.\n  assert (Standard y0).\n  assert (RootContr_S (S1 l @l x0_1_2 @l x0_2 @l y0)\n                      (build_s_result l x0_1_2 (tuple_of_lterm x0_2) (tuple_of_lterm y0))) by ycrush.\n  eapply lem_standard_expand_below_S_redex; pose_subterm; ycrush.\n  assert (forall z, In z (tuple_of_lterm y0) -> R_glue_iterms_r Contr_clc_s z).\n  apply lem_standard_implies_glue_iterms_r; ycrush.\n  assert (Red_clc_s (build_s_result l x0_1_2 (tuple_of_lterm x0_2) (tuple_of_lterm y0))\n                      (build_s_result l x0_1_2 (tuple_of_lterm x0_2) (tuple_of_lterm y'))).\n  pose lem_contr_s_s_result_3; pose_red_s; ycrush.\n  assert (is_ltup y' = true).\n  pose lem_contr_s_preserves_is_ltup; ycrush.\n  assert (lst_sum l < length (tuple_of_lterm y')).\n  rewrite <- lem_contr_s_length with (x := y0); ycrush.\n  assert (All_pairs (tuple_of_lterm y') ErasedEqv).\n  pose lem_contr_s_all_pairs_erased_eqv; ycrush.\n  assert (forall x : lterm, In x (tuple_of_lterm y') -> is_ltup x = false).\n  pose lem_standard_contr_s_preserves_no_nested_tuple; ycrush.\n  assert (RootContr_clc_a (S1 l @l x0_1_2 @l x0_2 @l y')\n                          (build_s_result l x0_1_2 (tuple_of_lterm x0_2) (tuple_of_lterm y'))).\n  racrush.\n  ycrush.\n  assert (Standard y0).\n  assert (RootContr_S (S2 n @l x0_1_2 @l x0_2 @l y0)\n                      (x0_1_2 @l lterm_of_tuple (firstn n (tuple_of_lterm y0)) @l\n                              glue_iterms x0_2 (lterm_of_tuple (skipn n (tuple_of_lterm y0))))).\n  ycrush.\n  eapply lem_standard_expand_below_S_redex; pose_subterm; ycrush.\n  assert (forall z, In z (tuple_of_lterm y0) -> R_glue_iterms_r Contr_clc_s z).\n  apply lem_standard_implies_glue_iterms_r; ycrush.\n  assert (Red_clc_s (x0_1_2 @l lterm_of_tuple (firstn n (tuple_of_lterm y0)) @l\n                            (glue_iterms x0_2 (lterm_of_tuple (skipn n (tuple_of_lterm y0)))))\n                    (x0_1_2 @l lterm_of_tuple (firstn n (tuple_of_lterm y')) @l\n                            (glue_iterms x0_2 (lterm_of_tuple (skipn n (tuple_of_lterm y')))))).\n  pose lem_contr_s_s2_result; pose_red_s; ycrush.\n  assert (is_ltup y' = true).\n  pose lem_contr_s_preserves_is_ltup; ycrush.\n  assert (n < length (tuple_of_lterm y')).\n  rewrite <- lem_contr_s_length with (x := y0); ycrush.\n  assert (All_pairs (tuple_of_lterm y') ErasedEqv).\n  pose lem_contr_s_all_pairs_erased_eqv; ycrush.\n  assert (forall x : lterm, In x (tuple_of_lterm y') -> is_ltup x = false).\n  pose lem_standard_contr_s_preserves_no_nested_tuple; ycrush.\n  assert (RootContr_clc_a (S2 n @l x0_1_2 @l x0_2 @l y')\n                          (x0_1_2 @l lterm_of_tuple (firstn n (tuple_of_lterm y')) @l\n                                  (glue_iterms x0_2 (lterm_of_tuple (skipn n (tuple_of_lterm y')))))).\n  racrush.\n  ycrush.\nQed.\n\nLemma lem_a_commute_1 :\n  forall x y z, Contr_clc_a x y -> RootContr_clc_s x z -> Standard y ->\n                exists u, (Contr_clc_a z u \\/ z = u) /\\ Red_clc_s y u.\nProof.\n  intros.\n  yinversion H; fold Contr_clc_a in *; try yelles 1.\n\n  pose lem_a_root_commute; pose_contr_a; ycrush.\n\n  invert_rcontr_clc_s; yintuition; yintuition.\n  yinversion H; repeat invert_contr_clc_a.\n  racrush.\n  racrush.\n  yinversion H3; racrush.\n  yinversion H3; racrush.\n  exists y'; pose_red_s; ycrush.\n  yinversion H; repeat invert_contr_clc_a.\n  racrush.\n  racrush.\n  yinversion H3; racrush.\n  yinversion H3; racrush.\n  exists x1; pose_red_s; ycrush.\n  yinversion H; repeat invert_contr_clc_a.\n  racrush.\n  racrush.\n  yinversion H4; racrush.\n  exists x; intuition; apply lem_rcontr_s_to_red_s; ycrush.\n  assert (ErasedEqv y' x1) by\n      (eauto 8 using lem_contr_a_to_erased_eqv, lem_erased_eqv_trans,\n       lem_erased_eqv_sym, lem_contr_s_to_red_s).\n  exists y'; intuition; apply lem_rcontr_s_to_red_s; ycrush.\n  yinversion H; repeat invert_contr_clc_a.\n  racrush.\n  racrush.\n  yinversion H4; racrush.\n  exists x1; intuition; apply lem_rcontr_s_to_red_s; ycrush.\n  assert (ErasedEqv y' x1) by\n      (eauto 8 using lem_contr_a_to_erased_eqv, lem_erased_eqv_trans,\n       lem_erased_eqv_sym, lem_contr_s_to_red_s).\n  exists x1; intuition; apply lem_rcontr_s_to_red_s; ycrush.\n  yinversion H; repeat invert_contr_clc_a.\n  yinversion H2; racrush.\n  yinversion H; repeat invert_contr_clc_a.\n  racrush.\n  yinversion H4; racrush.\n  exists y'; intuition; apply lem_rcontr_s_to_red_s; ycrush.\n  rename x into l.\n  yinversion H; repeat invert_contr_clc_a.\n  racrush.\n  racrush.\n  yinversion H11; racrush.\n  assert (is_nonempty l).\n  ydestruct l; ycrush.\n  assert (Contr_clc_a (build_s_result l x1 (tuple_of_lterm x2) (tuple_of_lterm x3))\n                      (build_s_result l y' (tuple_of_lterm x2) (tuple_of_lterm x3))).\n  pose lem_contr_a_s_result_1; ycrush.\n  assert (Red_clc_s (S1 l @l y' @l x2 @l x3)\n                    (build_s_result l y' (tuple_of_lterm x2) (tuple_of_lterm x3))).\n  apply lem_rcontr_s_to_red_s; ycrush.\n  ycrush.\n  assert (is_nonempty l).\n  ydestruct l; ycrush.\n  assert (Contr_clc_a (build_s_result l x1 (tuple_of_lterm x2) (tuple_of_lterm x3))\n                      (build_s_result l x1 (tuple_of_lterm y') (tuple_of_lterm x3))).\n  pose lem_contr_a_s_result_2; ycrush.\n  assert (is_ltup y' = true).\n  pose lem_contr_a_preserves_is_ltup; ycrush.\n  assert (length (tuple_of_lterm y') = length l).\n  rewrite <- lem_contr_a_length with (x := x2); ycrush.\n  assert (All_pairs (tuple_of_lterm y') ErasedEqv).\n  pose lem_contr_a_all_pairs_erased_eqv; ycrush.\n  assert (Red_clc_s (S1 l @l x1 @l y' @l x3)\n                    (build_s_result l x1 (tuple_of_lterm y') (tuple_of_lterm x3))).\n  apply lem_rcontr_s_to_red_s; ycrush.\n  assert (Sterm (build_s_result l x1 (tuple_of_lterm y') (tuple_of_lterm x3))).\n  pose lem_standard_sterm; pose_sterm; ycrush.\n  ycrush.\n  rename x into n.\n  yinversion H; repeat invert_contr_clc_a.\n  racrush.\n  racrush.\n  yinversion H9; racrush.\n  exists (y' @l lterm_of_tuple (firstn n (tuple_of_lterm x3)) @l\n             (glue_iterms x2 (lterm_of_tuple (skipn n (tuple_of_lterm x3))))).\n  split; [ pose_contr_a; ycrush | apply lem_rcontr_s_to_red_s; ycrush ].\n  exists (x1 @l lterm_of_tuple (firstn n (tuple_of_lterm x3)) @l\n             (glue_iterms y' (lterm_of_tuple (skipn n (tuple_of_lterm x3))))).\n  assert (Contr_clc_a\n            (x1 @l lterm_of_tuple (firstn n (tuple_of_lterm x3)) @l\n                (glue_iterms x2 (lterm_of_tuple (skipn n (tuple_of_lterm x3)))))\n            (x1 @l lterm_of_tuple (firstn n (tuple_of_lterm x3)) @l\n                (glue_iterms y' (lterm_of_tuple (skipn n (tuple_of_lterm x3)))))).\n  pose lem_contr_a_glue_l.\n  unfold R_glue_iterms_l in *.\n  pose_contr_a; ycrush.\n  assert (is_ltup y' = false).\n  yinversion H10; try yelles 1.\n  assert (HH: Sterm y') by racrush.\n  yinversion HH; ycrush.\n  assert (Red_clc_s (S2 n @l x1 @l y' @l x3)\n                    (x1 @l lterm_of_tuple (firstn n (tuple_of_lterm x3)) @l\n                        (glue_iterms y' (lterm_of_tuple (skipn n (tuple_of_lterm x3)))))).\n  apply lem_rcontr_s_to_red_s; ycrush.\n  ycrush.\n\n  invert_rcontr_clc_s; yintuition; yintuition.\n  yinversion H; repeat invert_contr_clc_a; exists x; pose_red_s; ycrush.\n  yinversion H; repeat invert_contr_clc_a; exists y'; pose_red_s; ycrush.\n  yinversion H; repeat invert_contr_clc_a.\n  assert (ErasedEqv x y') by\n      (eauto 8 using lem_contr_a_to_erased_eqv, lem_erased_eqv_trans,\n       lem_erased_eqv_sym, lem_contr_s_to_red_s).\n  exists x; intuition; apply lem_rcontr_s_to_red_s; ycrush.\n  yinversion H; repeat invert_contr_clc_a.\n  assert (ErasedEqv x y') by\n      (eauto 8 using lem_contr_a_to_erased_eqv, lem_erased_eqv_trans,\n       lem_erased_eqv_sym, lem_contr_s_to_red_s).\n  exists y'; intuition; apply lem_rcontr_s_to_red_s; ycrush.\n  yinversion H.\n  exists y'; pose_red_s; ycrush.\n  yinversion H; repeat invert_contr_clc_a; exists x; pose_red_s; ycrush.\n  rename x into l.\n  yinversion H; repeat invert_contr_clc_a.\n  assert (is_nonempty l).\n  ydestruct l; ycrush.\n  assert (Contr_clc_a (build_s_result l x1 (tuple_of_lterm x2) (tuple_of_lterm x3))\n                      (build_s_result l x1 (tuple_of_lterm x2) (tuple_of_lterm y'))).\n  pose lem_contr_a_s_result_3; ycrush.\n  assert (is_ltup y' = true).\n  pose lem_contr_a_preserves_is_ltup; ycrush.\n  assert (lst_sum l < length (tuple_of_lterm y')).\n  rewrite <- lem_contr_a_length with (x := x3); ycrush.\n  assert (All_pairs (tuple_of_lterm y') ErasedEqv).\n  pose lem_contr_a_all_pairs_erased_eqv; ycrush.\n  assert (forall x : lterm, In x (tuple_of_lterm y') -> is_ltup x = false).\n  assert (Standard y').\n  pose lem_subterm_standard; pose_subterm; ycrush.\n  Reconstr.hobvious (@H14)\n\t            (@standard.lem_standard_no_nested_tuple)\n\t\t    Reconstr.Empty.\n  assert (Red_clc_s (S1 l @l x1 @l x2 @l y')\n                    (build_s_result l x1 (tuple_of_lterm x2) (tuple_of_lterm y'))).\n  apply lem_rcontr_s_to_red_s; ycrush.\n  ycrush.\n  rename x into n.\n  yinversion H; repeat invert_contr_clc_a.\n  assert (Contr_clc_a (x1 @l lterm_of_tuple (firstn n (tuple_of_lterm x3)) @l\n                          (glue_iterms x2 (lterm_of_tuple (skipn n (tuple_of_lterm x3)))))\n                      (x1 @l lterm_of_tuple (firstn n (tuple_of_lterm y')) @l\n                          (glue_iterms x2 (lterm_of_tuple (skipn n (tuple_of_lterm y')))))).\n  pose lem_contr_a_s2_result; ycrush.\n  assert (is_ltup y' = true).\n  pose lem_contr_a_preserves_is_ltup; ycrush.\n  assert (n < length (tuple_of_lterm y')).\n  rewrite <- lem_contr_a_length with (x := x3); ycrush.\n  assert (All_pairs (tuple_of_lterm y') ErasedEqv).\n  pose lem_contr_a_all_pairs_erased_eqv; ycrush.\n  assert (forall x : lterm, In x (tuple_of_lterm y') -> is_ltup x = false).\n  assert (Standard y').\n  pose lem_subterm_standard; pose_subterm; ycrush.\n  Reconstr.hobvious (@H11)\n\t            (@standard.lem_standard_no_nested_tuple)\n\t\t    Reconstr.Empty.\n  assert (Red_clc_s (S2 n @l x1 @l x2 @l y')\n                    (x1 @l lterm_of_tuple (firstn n (tuple_of_lterm y')) @l\n                        (glue_iterms x2 (lterm_of_tuple (skipn n (tuple_of_lterm y')))))).\n  apply lem_rcontr_s_to_red_s; ycrush.\n  ycrush.\nQed.\n\n(* lemma 19 *)\nLemma lem_a_commute :\n  forall x y z, Contr_clc_a x y -> Contr_clc_s x z -> Standard y ->\n                exists u, (Contr_clc_a z u \\/ z = u) /\\ Red_clc_s y u.\nProof.\n  assert (forall x z, Contr_clc_s x z ->\n                      forall y, Contr_clc_a x y -> Standard y ->\n                                exists u, (Contr_clc_a z u \\/ z = u) /\\ Red_clc_s y u).\n  intros x z H.\n  induction H; fold Contr_clc_s in *; yintros.\n  \n  pose lem_a_commute_1; ycrush.\n  \n  invert_contr_clc_a.\n  assert (Contr_clc_s (x @l y) (x' @l y)).\n  pose_contr_s; ycrush.\n  pose lem_a_commute_0; pose_contr_a; ycrush.\n  assert (Standard x'0).\n  pose lem_subterm_standard; pose_subterm; ycrush.\n  pose_contr_a; pose_red_s; ycrush.\n  assert (Standard y').\n  pose lem_subterm_standard; pose_subterm; ycrush.\n  pose_contr_a; pose_red_s; ycrush.\n\n  invert_contr_clc_a.\n  assert (Contr_clc_s (x @l y) (x @l y')).\n  pose_contr_s; ycrush.\n  pose lem_a_commute_0; pose_contr_a; ycrush.\n  assert (Standard x').\n  pose lem_subterm_standard; pose_subterm; ycrush.\n  pose_contr_a; pose_red_s; ycrush.\n  assert (Standard y'0).\n  pose lem_subterm_standard; pose_subterm; ycrush.\n  pose_contr_a; pose_red_s; ycrush.\n\n  yinversion H0; fold Contr_clc_a in *; yisolve.\n  racrush.\n  assert (Standard x'0).\n  pose lem_subterm_standard; pose_subterm; ycrush.\n  pose_contr_a; pose_red_s; ycrush.  \n  pose_contr_a; pose_red_s; ycrush.\n  pose_contr_a; pose_red_s; ycrush.\n\n  yinversion H0; fold Contr_clc_a in *; yisolve.\n  racrush.\n  pose_contr_a; pose_red_s; ycrush.\n  assert (Standard y'0).\n  pose lem_subterm_standard; pose_subterm; ycrush.\n  pose_contr_a; pose_red_s; ycrush.  \n  pose_contr_a; pose_red_s; ycrush.\n\n  yinversion H0; fold Contr_clc_a in *; yisolve.\n  racrush.\n  pose_contr_a; pose_red_s; ycrush.\n  pose_contr_a; pose_red_s; ycrush.\n  assert (Standard z'0).\n  pose lem_subterm_standard; pose_subterm; ycrush.\n  generalize l0 l'0 H5.\n  clear l0 l'0 H1 H5.\n  induction l; intros.\n  ydestruct l0.\n  simpl in *.\n  yinversion H5.\n  assert (exists u : lterm, (Contr_clc_a z' u \\/ z' = u) /\\ Red_clc_s z'0 u).\n  pose_contr_a; pose_red_s; ycrush.\n  assert (exists u : lterm,\n             (Contr_clc_a (ltup x y (nil ++ z' :: l')) u \\/ ltup x y (nil ++ z' :: l') = u) /\\\n             Red_clc_s (ltup x y (nil ++ z'0 :: l')) u).\n  pose_contr_a; pose_red_s; ycrush.\n  ycrush.\n  assert (l = z).\n  yinversion H5; trivial.\n  assert (l' = (l0 ++ z0 :: l'0)).\n  yinversion H5; trivial.\n  subst; simpl; clear H5.\n  assert (Contr_clc_a (ltup x y ((z' :: l0) ++ z0 :: l'0)) (ltup x y ((z' :: l0) ++ z'0 :: l'0))).\n  pose_contr_a; ycrush.\n  assert (Red_clc_s (ltup x y (nil ++ z :: l0 ++ z'0 :: l'0)) (ltup x y (nil ++ z' :: l0 ++ z'0 :: l'0))).\n  clear -H; pose_red_s; ycrush.\n  ycrush.\n  ydestruct l0; simpl in *.\n  assert (a = z0).\n  yinversion H5; trivial.\n  assert (l'0 = l ++ z :: l').\n  yinversion H5; trivial.\n  subst; simpl in *.\n  assert (Contr_clc_a (ltup x y (nil ++ z0 :: l ++ z' :: l'))\n                      (ltup x y (nil ++ z'0 :: l ++ z' :: l'))).\n  pose_contr_a; ycrush.\n  assert (Red_clc_s (ltup x y ((z'0 :: l) ++ z :: l')) (ltup x y ((z'0 :: l) ++ z' :: l'))).\n  pose_red_s; ycrush.\n  ycrush.\n  yinversion H5.\n  yforwarding.\n  assert (is_ltup (ltup x y (l1 ++ z'0 :: l'0)) = true) by ycrush.\n  assert (is_ltup x0 = true).\n  pose lem_red_s_preserves_is_ltup; ycrush.\n  ydestruct x0; yisolve.\n  yintuition.\n  pose lem_contr_a_ltup_extend; pose lem_red_s_ltup_extend; ycrush.\n  yinversion H4.\n  pose lem_red_s_ltup_extend; ycrush.\n  ycrush.\nQed.\n\n(* corollary 20 *)\nLemma lem_a_commute_red :\n  forall x y z, Contr_clc_a x y -> Red_clc_s x z -> StronglyStandard y ->\n                exists u, (Contr_clc_a z u \\/ z = u) /\\ Red_clc_s y u.\nProof.\n  assert (forall x z, Red_clc_s x z ->\n                      forall y, Contr_clc_a x y -> StronglyStandard y ->\n                                exists u, (Contr_clc_a z u \\/ z = u) /\\ Red_clc_s y u).\n  intros x z H.\n  induction H; fold Red_clc_s in *; yintros.\n  pose lem_a_commute; pose_red_s; ycrush.\n  ycrush.\n  assert (exists u : lterm, (Contr_clc_a y u \\/ y = u) /\\ Red_clc_s y0 u) by ycrush.\n  yintuition.\n  assert (exists u : lterm, (Contr_clc_a z u \\/ z = u) /\\ Red_clc_s x0 u).\n  assert (StronglyStandard x0).\n  pose lem_reduce_subterm_strongly_standard; pose_subterm; ycrush.\n  ycrush.\n  pose_red_s; ycrush.\n  pose_red_s; ycrush.\n  ycrush.\nQed.\n", "meta": {"author": "lukaszcz", "repo": "clc", "sha": "caf1a030f1b6e148aab87ab9af0f1efef8e0c594", "save_path": "github-repos/coq/lukaszcz-clc", "path": "github-repos/coq/lukaszcz-clc/clc-caf1a030f1b6e148aab87ab9af0f1efef8e0c594/acommute.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2557958585425036}}
{"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\nRequire Export computation5.\nRequire Export atom_ren.\n\n\nLemma computes_to_val_like_in_max_k_steps_preserves_program {p} :\n  forall lib k (t1 t2 : @NTerm p),\n    computes_to_val_like_in_max_k_steps lib t1 t2 k\n    -> isprogram t1\n    -> isprogram t2.\nProof.\n  unfold computes_to_val_like_in_max_k_steps, reduces_in_atmost_k_steps;\n  introv comp isp; repnd.\n  apply computek_preserves_program in comp0; sp.\nQed.\n\nLemma isprogram_subst_if_bt {p} :\n  forall t v a,\n    @isprogram p a\n    -> isprogram_bt (bterm [v] t)\n    -> isprogram (subst t v a).\nProof.\n  introv ispa ispt.\n  apply subst_preserves_program; auto.\n  destruct ispt as [c w].\n  inversion w; sp.\n  introv i.\n  destruct ispt as [c w].\n  unfold closed_bt in c; allsimpl.\n  rw <- null_iff_nil in c; rw null_remove_nvars in c.\n  discover; allsimpl; sp.\nQed.\n\nLemma wf_atom_eq_iff {p} :\n  forall a b c d : @NTerm p,\n    (wf_term a # wf_term b # wf_term c # wf_term d) <=> wf_term (mk_atom_eq a b c d).\nProof.\n  introv; split; intro i.\n  apply wf_atom_eq; sp.\n  allrw @wf_term_eq.\n  inversion i as [|?| o lnt k e]; subst; allsimpl.\n  generalize (k (nobnd a)) (k (nobnd b)) (k (nobnd c)) (k (nobnd d)); intros k1 k2 k3 k4.\n  repeat (dest_imp k1 hyp).\n  repeat (dest_imp k2 hyp).\n  repeat (dest_imp k3 hyp).\n  repeat (dest_imp k4 hyp).\n  inversion k1; subst.\n  inversion k2; subst.\n  inversion k3; subst.\n  inversion k4; subst; sp.\nQed.\n\nLemma isprog_vars_mk_atom_eq {p} :\n  forall (a b c d : @NTerm p) vs,\n    isprog_vars vs (mk_atom_eq a b c d)\n    <=> (isprog_vars vs a\n         # isprog_vars vs b\n         # isprog_vars vs c\n         # isprog_vars vs d).\nProof.\n  introv.\n  repeat (rw @isprog_vars_eq; simpl).\n  repeat (rw remove_nvars_nil_l).\n  repeat (rw app_nil_r).\n  repeat (rw subvars_app_l).\n  repeat (rw <- @wf_term_eq).\n  allrw <- @wf_atom_eq_iff; split; sp.\nQed.\n\nLemma isprogram_mk_atom_eq {p} :\n  forall (a b c d : @NTerm p),\n    isprogram (mk_atom_eq a b c d)\n    <=> (isprogram a\n         # isprogram b\n         # isprogram c\n         # isprogram d).\nProof.\n  introv.\n  pose proof (isprog_vars_mk_atom_eq a b c d []) as h.\n  allrw <- @isprog_vars_nil_iff_isprog.\n  allrw @isprogram_eq; auto.\nQed.\n\nLemma computes_to_val_like_in_max_k_steps_can_iff {p} :\n  forall lib c bterms a k,\n    computes_to_val_like_in_max_k_steps lib (oterm (@Can p c) bterms) a k\n    <=> a = oterm (Can c) bterms.\nProof.\n  introv; split; intro comp; subst.\n  apply computes_to_val_like_in_max_k_steps_can in comp; auto.\n  unfold computes_to_val_like_in_max_k_steps, reduces_in_atmost_k_steps.\n  dands; try (complete (left; sp)).\n  induction k; simpl; sp.\n  rw IHk; simpl; sp.\nQed.\n\nLemma computes_to_val_like_in_max_k_steps_sleep_implies {p} :\n  forall lib k t v,\n    computes_to_val_like_in_max_k_steps lib (mk_sleep t) v k\n    -> {x : NTerm\n        & {m : nat\n           & k = S m\n           # computes_to_val_like_in_max_k_steps lib t x m\n           # ({z : Z & v = mk_axiom # x = @mk_integer p z}\n              [+]\n              (isexc x # x = v))}}.\nProof.\n  induction k; introv comp; simpl.\n\n  - allunfold @computes_to_val_like_in_max_k_steps.\n    rw @reduces_in_atmost_k_steps_0 in comp; repnd; subst.\n    unfold isvalue_like in comp; allsimpl; sp.\n\n  - rw @computes_to_val_like_in_max_k_steps_S in comp; exrepnd.\n    destruct t; ginv.\n    dopid o as [can|ncan|exc|abs] Case; try (complete (inversion comp1)).\n\n    + Case \"Can\".\n      destruct l; try (complete (inversion comp1)).\n      destruct can; inversion comp1; subst.\n      apply computes_to_val_like_in_max_k_steps_can_iff in comp0; subst.\n      exists (@mk_integer p z) k; dands; auto.\n      apply computes_to_val_like_in_max_k_steps_can_iff; sp.\n      left; exists z; sp.\n\n    + Case \"NCan\".\n      rw @computes_step_sleep_ncan in comp1.\n      remember (compute_step lib (oterm (NCan ncan) l)); destruct c; inversion comp1; subst; GC.\n      apply IHk in comp0; clear IHk; exrepnd; subst.\n      exists x (S m); dands; auto.\n      rw @computes_to_val_like_in_max_k_steps_S.\n      exists n; auto.\n\n    + Case \"Exc\".\n      inversion comp1; subst; GC.\n      apply computes_to_val_like_in_max_k_steps_exc in comp0; subst.\n      exists (oterm Exc l) k; dands; auto.\n      apply computes_to_val_like_in_max_k_steps_exc_iff; sp.\n\n    + Case \"Abs\".\n      rw @computes_step_sleep_abs in comp1.\n      remember (compute_step lib (oterm (Abs abs) l)); destruct c; inversion comp1; subst; GC.\n      apply IHk in comp0; clear IHk; exrepnd; subst.\n      exists x (S m); dands; auto.\n      rw @computes_to_val_like_in_max_k_steps_S.\n      exists n; auto.\nQed.\n\nLemma computes_to_val_like_in_max_k_steps_tuni_implies {p} :\n  forall lib k t v,\n    computes_to_val_like_in_max_k_steps lib (mk_tuni t) v k\n    -> {x : NTerm\n        & {m : nat\n           & k = S m\n           # computes_to_val_like_in_max_k_steps lib t x m\n           # ({n : nat & v = mk_uni n # x = @mk_integer p (Z.of_nat n)}\n              [+]\n              (isexc x # x = v))}}.\nProof.\n  induction k; introv comp; simpl.\n\n  - allunfold @computes_to_val_like_in_max_k_steps.\n    rw @reduces_in_atmost_k_steps_0 in comp; repnd; subst.\n    unfold isvalue_like in comp; allsimpl; sp.\n\n  - rw @computes_to_val_like_in_max_k_steps_S in comp; exrepnd.\n    destruct t; ginv.\n    dopid o as [can|ncan|exc|abs] Case; try (complete (inversion comp1)).\n\n    + Case \"Can\".\n      destruct l; try (complete (inversion comp1)).\n      csunf comp1; simpl in comp1.\n      unfold compute_step_tuni in comp1; simpl in comp1.\n      destruct can; allsimpl; try (complete (inversion comp1)).\n      destruct (Z_le_gt_dec 0 z); inversion comp1; subst; GC.\n      apply computes_to_val_like_in_max_k_steps_can_iff in comp0; subst.\n      exists (@mk_integer p z) k; dands; auto.\n      apply computes_to_val_like_in_max_k_steps_can_iff; sp.\n      left; exists (Z.to_nat z); sp.\n      rw Znat.Z2Nat.id; sp.\n\n    + Case \"NCan\".\n      rw @computes_step_tuni_ncan in comp1.\n      remember (compute_step lib (oterm (NCan ncan) l)); destruct c; inversion comp1; subst; GC.\n      apply IHk in comp0; clear IHk; exrepnd; subst.\n      exists x (S m); dands; auto.\n      rw @computes_to_val_like_in_max_k_steps_S.\n      exists n; auto.\n\n    + Case \"Exc\".\n      inversion comp1; subst; GC.\n      apply computes_to_val_like_in_max_k_steps_exc in comp0; subst.\n      exists (oterm Exc l) k; dands; auto.\n      apply computes_to_val_like_in_max_k_steps_exc_iff; sp.\n\n    + rw @computes_step_tuni_abs in comp1.\n      remember (compute_step lib (oterm (Abs abs) l)); destruct c; inversion comp1; subst; GC.\n      apply IHk in comp0; clear IHk; exrepnd; subst.\n      exists x (S m); dands; auto.\n      rw @computes_to_val_like_in_max_k_steps_S.\n      exists n; auto.\nQed.\n\nLemma alphaeqbt_nilv_r {o}:\n  forall (b : @BTerm o) t,\n    alpha_eq_bterm b (bterm [] t)\n    -> {t' : NTerm $ b = bterm [] t' # alpha_eq t' t}.\nProof.\n  introv aeq.\n  apply alpha_eq_bterm_sym in aeq.\n  apply alphaeqbt_nilv in aeq; exrepnd; subst.\n  exists nt2; dands; eauto with slow.\nQed.\n\nLemma computes_step_minus_ncan {p} :\n  forall lib n l,\n    compute_step lib (mk_minus (oterm (@NCan p n) l))\n    = match compute_step lib (oterm (NCan n) l) with\n        | csuccess t => csuccess (mk_minus t)\n        | cfailure m t => cfailure m t\n      end.\nProof.\n  introv; csunf; simpl; auto.\nQed.\n\nLemma computes_step_minus_abs {p} :\n  forall lib o l,\n    compute_step lib (mk_minus (oterm (@Abs p o) l))\n    = match compute_step lib (oterm (Abs o) l) with\n        | csuccess t => csuccess (mk_minus t)\n        | cfailure m t => cfailure m t\n      end.\nProof. sp. Qed.\n\nLemma computes_to_val_like_in_max_k_steps_minus_implies {p} :\n  forall lib k t v,\n    computes_to_val_like_in_max_k_steps lib (mk_minus t) v k\n    -> {x : NTerm\n        & {m : nat\n           & k = S m\n           # computes_to_val_like_in_max_k_steps lib t x m\n           # ({z : Z & v = mk_integer (- z) # x = @mk_integer p z}\n              [+]\n              (isexc x # x = v))}}.\nProof.\n  induction k; introv comp; simpl.\n\n  - allunfold @computes_to_val_like_in_max_k_steps.\n    rw @reduces_in_atmost_k_steps_0 in comp; repnd; subst.\n    unfold isvalue_like in comp; allsimpl; sp.\n\n  - rw @computes_to_val_like_in_max_k_steps_S in comp; exrepnd.\n    destruct t; ginv.\n    dopid o as [can|ncan|exc|abs] Case; try (complete (inversion comp1)).\n\n    + Case \"Can\".\n      destruct l; try (complete (inversion comp1)).\n      csunf comp1; simpl in comp1.\n      unfold compute_step_minus in comp1; simpl in comp1.\n      destruct can; allsimpl; ginv.\n      apply computes_to_val_like_in_max_k_steps_can_iff in comp0; subst.\n      exists (@mk_integer p z) k; dands; auto.\n      * apply computes_to_val_like_in_max_k_steps_can_iff; sp.\n      * left; exists z; sp.\n\n    + Case \"NCan\".\n      rw @computes_step_minus_ncan in comp1.\n      remember (compute_step lib (oterm (NCan ncan) l)); destruct c; inversion comp1; subst; GC.\n      apply IHk in comp0; clear IHk; exrepnd; subst.\n      exists x (S m); dands; auto.\n      rw @computes_to_val_like_in_max_k_steps_S.\n      exists n; auto.\n\n    + Case \"Exc\".\n      inversion comp1; subst; GC.\n      apply computes_to_val_like_in_max_k_steps_exc in comp0; subst.\n      exists (oterm Exc l) k; dands; auto.\n      apply computes_to_val_like_in_max_k_steps_exc_iff; sp.\n\n    + rw @computes_step_minus_abs in comp1.\n      remember (compute_step lib (oterm (Abs abs) l)); destruct c; inversion comp1; subst; GC.\n      apply IHk in comp0; clear IHk; exrepnd; subst.\n      exists x (S m); dands; auto.\n      rw @computes_to_val_like_in_max_k_steps_S.\n      exists n; auto.\nQed.\n\nLemma computes_to_val_like_in_max_k_steps_parallel_implies {o} :\n  forall lib k (bs : list (@BTerm o)) v,\n    computes_to_val_like_in_max_k_steps lib (oterm (NCan NParallel) bs) v k\n    -> {x : NTerm\n        & {u : NTerm\n        & {bs' : list BTerm\n        & {m : nat\n        & k = S m\n        # bs = nobnd u :: bs'\n        # computes_to_val_like_in_max_k_steps lib u x m\n        # (iscan x # v = mk_axiom)\n          [+]\n          (isexc x # x = v)}}}}.\nProof.\n  induction k; introv comp; simpl.\n\n  - allunfold @computes_to_val_like_in_max_k_steps.\n    rw @reduces_in_atmost_k_steps_0 in comp; repnd; subst.\n    unfold isvalue_like in comp; allsimpl; sp.\n\n  - rw @computes_to_val_like_in_max_k_steps_S in comp; exrepnd.\n    csunf comp1; allsimpl.\n    destruct bs as [|b bs]; ginv.\n    destruct b as [l t].\n    destruct l; ginv.\n    destruct t as [z|f|op bts]; ginv;[].\n    dopid op as [can|ncan|exc|abs] Case; ginv.\n\n    + Case \"Can\".\n      apply compute_step_parallel_success in comp1; subst.\n      apply computes_to_val_like_in_max_k_steps_can_iff in comp0; subst.\n      exists (oterm (Can can) bts) (oterm (Can can) bts) bs k; dands; auto.\n      apply computes_to_val_like_in_max_k_steps_can_iff; sp.\n\n    + Case \"NCan\".\n      remember (compute_step lib (oterm (NCan ncan) bts)) as comp'; destruct comp'; ginv.\n      apply IHk in comp0; clear IHk; exrepnd; subst; allunfold @nobnd; ginv.\n      exists x (oterm (NCan ncan) bts) bs' (S m); dands; auto.\n      rw @computes_to_val_like_in_max_k_steps_S.\n      exists u; auto.\n\n    + Case \"Exc\".\n      apply computes_to_val_like_in_max_k_steps_exc in comp0; subst.\n      exists (oterm Exc bts) (oterm Exc bts) bs k; dands; auto.\n      apply computes_to_val_like_in_max_k_steps_exc_iff; sp.\n\n    + Case \"Abs\".\n      remember (compute_step lib (oterm (Abs abs) bts)) as comp'; destruct comp'; ginv.\n      apply IHk in comp0; clear IHk; exrepnd; subst.\n      allunfold @nobnd; ginv.\n      exists x (oterm (Abs abs) bts) bs' (S m); dands; auto.\n      rw @computes_to_val_like_in_max_k_steps_S.\n      exists u; auto.\nQed.\n\nLemma isvalue_vterm {o} : forall v, !@isvalue o (vterm v).\nProof.\n  introv h.\n  inversion h; subst; allsimpl; tcsp.\nQed.\n\nLemma computes_to_value_implies_val_like {p} :\n  forall lib (a b : @NTerm p),\n    computes_to_value lib a b\n    -> computes_to_val_like lib a b.\nProof.\n  introv comp.\n  unfold computes_to_val_like, computes_to_val_like_in_max_k_steps.\n  unfold computes_to_value, reduces_to in comp.\n  exrepnd.\n  exists k; dands; auto.\n  left.\n  destruct b as [v|f|op bs]; allsimpl; tcsp;[allapply @isvalue_vterm;tcsp|].\n  allapply @isvalue_implies; repnd; auto.\nQed.\n\nLemma computes_to_exception_implies_val_like {p} :\n  forall lib en (a b : @NTerm p),\n    computes_to_exception lib en a b\n    -> computes_to_val_like lib a (mk_exception en b).\nProof.\n  introv comp.\n  unfold computes_to_val_like, computes_to_val_like_in_max_k_steps.\n  unfold computes_to_exception, reduces_to in comp.\n  exrepnd.\n  exists k; dands; auto.\n  right.\n  constructor.\nQed.\n\nLemma computes_to_val_like_in_max_k_steps_0 {p} :\n  forall lib (t u : @NTerm p),\n    computes_to_val_like_in_max_k_steps lib t u 0 <=> (t = u # isvalue_like u).\nProof.\n  introv; unfold computes_to_val_like_in_max_k_steps.\n  rw @reduces_in_atmost_k_steps_0; sp.\nQed.\n\nDefinition has_value_like_k {p} lib k (t : @NTerm p) :=\n  {u : NTerm & computes_to_val_like_in_max_k_steps lib t u k}.\n\nLemma has_value_like_0 {o} :\n  forall lib (t : @NTerm o),\n    has_value_like_k lib 0 t <=> isvalue_like t.\nProof.\n  introv; unfold has_value_like_k; split; intro k; exrepnd.\n  - allrw @computes_to_val_like_in_max_k_steps_0; repnd; subst; auto.\n  - exists t; allrw @computes_to_val_like_in_max_k_steps_0; auto.\nQed.\n\nLemma has_value_like_S {o} :\n  forall lib k (t : @NTerm o),\n    has_value_like_k lib (S k) t\n    <=> {u : NTerm\n         & compute_step lib t = csuccess u\n         # has_value_like_k lib k u}.\nProof.\n  introv; unfold has_value_like_k; split; intro h; exrepnd.\n  - allrw @computes_to_val_like_in_max_k_steps_S; exrepnd.\n    eexists; eauto.\n  - exists u0; dands; auto.\n    allrw @computes_to_val_like_in_max_k_steps_S.\n    eexists; eauto.\nQed.\n\nLemma if_has_value_like_k_ncompop_can1 {o} :\n  forall lib c can bs k (t : @NTerm o) l,\n    has_value_like_k\n      lib k\n      (oterm (NCan (NCompOp c))\n             (bterm [] (oterm (Can can) bs)\n                    :: bterm [] t\n                    :: l))\n    -> {j : nat & j < k # has_value_like_k lib j t}.\nProof.\n  induction k; introv r.\n  - allrw @has_value_like_0; repnd.\n    unfold isvalue_like in r; allsimpl; sp.\n  - allrw @has_value_like_S; exrepnd.\n    destruct t as [v|f|op bs1]; try (complete (csunf r1; allsimpl; dcwf h)).\n    dopid op as [can2|ncan2|exc2|abs2] Case.\n    + exists 0; dands; try omega.\n      rw @has_value_like_0; dands; eauto 3 with slow.\n    + rw @compute_step_ncompop_ncan2 in r1.\n      dcwf h.\n      remember (compute_step lib (oterm (NCan ncan2) bs1)) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @has_value_like_S.\n      exists n; tcsp.\n    + csunf r1; simpl in r1; ginv.\n      dcwf h; ginv.\n      exists k; sp.\n    + csunf r1; simpl in r1; csunf r1; allsimpl.\n      dcwf h.\n      unfold on_success in r1.\n      remember (compute_step_lib lib abs2 bs1) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @has_value_like_S.\n      exists n; tcsp.\nQed.\n\nLemma if_has_value_like_k_narithop_can1 {o} :\n  forall lib c can bs k (t : @NTerm o) l,\n    has_value_like_k\n      lib k\n      (oterm (NCan (NArithOp c))\n             (bterm [] (oterm (Can can) bs)\n                    :: bterm [] t\n                    :: l))\n    -> {j : nat & j < k # has_value_like_k lib j t}.\nProof.\n  induction k; introv r.\n  - allrw @has_value_like_0; repnd.\n    unfold isvalue_like in r; allsimpl; sp.\n  - allrw @has_value_like_S; exrepnd.\n    destruct t as [v|f|op bs1]; try (complete (csunf r1; allsimpl; dcwf h)).\n    dopid op as [can2|ncan2|exc2|abs2] Case.\n    + exists 0; dands; try omega.\n      rw @has_value_like_0; dands; eauto 3 with slow.\n    + rw @compute_step_narithop_ncan2 in r1.\n      dcwf h.\n      remember (compute_step lib (oterm (NCan ncan2) bs1)) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @has_value_like_S.\n      exists n; tcsp.\n    + csunf r1; simpl in r1; ginv.\n      dcwf h; ginv.\n      exists k; sp.\n    + csunf r1; simpl in r1; csunf r1; allsimpl.\n      dcwf h.\n      unfold on_success in r1.\n      remember (compute_step_lib lib abs2 bs1) as comp1.\n      symmetry in Heqcomp1.\n      destruct comp1; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @has_value_like_S.\n      exists n; tcsp.\nQed.\n\nLemma has_value_like_k_lt {o} :\n  forall lib k1 k2 (t : @NTerm o),\n    has_value_like_k lib k1 t\n    -> k1 < k2\n    -> has_value_like_k lib k2 t.\nProof.\n  unfold has_value_like_k; introv r l; exrepnd.\n  exists u; dands; auto.\n  pose proof (no_change_after_value_like lib t k1 u) as h.\n  allunfold @computes_to_val_like_in_max_k_steps; repnd; dands; auto.\n  repeat (autodimp h hyp); tcsp.\n  pose proof (h (k2 - k1)) as hh.\n  assert (k2 - k1 + k1 = k2) as e by omega.\n  rw e in hh; auto.\nQed.\n\nLemma computes_to_val_like_in_max_k_steps_if_isvalue_like {o} :\n  forall lib (t u : @NTerm o) k,\n    computes_to_val_like_in_max_k_steps lib t u k\n    -> isvalue_like t\n    -> t = u.\nProof.\n  introv comp isv.\n  unfold computes_to_val_like_in_max_k_steps in comp; repnd.\n  apply reduces_in_atmost_k_steps_if_isvalue_like in comp0; auto.\nQed.\n\nLemma if_has_value_like_k_cbv_primarg {o} :\n  forall lib k (t : @NTerm o) bs,\n    has_value_like_k lib k (oterm (NCan NCbv) (bterm [] t :: bs))\n    -> {j : nat & j < k # has_value_like_k lib j t}.\nProof.\n  induction k; introv r.\n\n  - allrw @has_value_like_0; repnd.\n    unfold isvalue_like in r; allsimpl; sp.\n\n  - allrw @has_value_like_S; exrepnd.\n    destruct t as [v|f|op l].\n\n    { simpl in r1; ginv. }\n\n    { exists 0; dands; try omega.\n      rw @has_value_like_0; dands; eauto 3 with slow; simpl; sp. }\n\n    dopid op as [can1|ncan1|exc1|abs1] Case.\n\n    + Case \"Can\".\n      exists 0; dands; try omega.\n      rw @has_value_like_0; dands; eauto 3 with slow; simpl; sp.\n\n    + Case \"NCan\".\n      rw @compute_step_ncan_ncan in r1.\n      remember (compute_step lib (oterm (NCan ncan1) l)) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @has_value_like_S; exists n; sp.\n\n    + Case \"Exc\".\n      csunf r1; allsimpl; ginv.\n      unfold has_value_like_k in r0; exrepnd.\n      apply computes_to_val_like_in_max_k_steps_if_isvalue_like in r1; subst; tcsp.\n      exists 0; dands; try omega.\n      rw @has_value_like_0; dands; eauto 3 with slow.\n\n    + Case \"Abs\".\n      csunf r1; allsimpl; csunf r1; allsimpl.\n      unfold on_success in r1.\n      remember (compute_step_lib lib abs1 l) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply IHk in r0; exrepnd.\n      exists (S j); dands; try omega.\n      rw @has_value_like_S; exists n; sp.\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 if_has_value_like_k_ncan_primarg {o} :\n  forall lib ncan k (t : @NTerm o) bs,\n    has_value_like_k lib k (oterm (NCan ncan) (bterm [] t :: bs))\n    -> {j : nat & j < k # has_value_like_k lib j t}.\nProof.\n  induction k; introv r.\n\n  - allrw @has_value_like_0.\n    unfold isvalue_like in r; allsimpl; sp.\n\n  - allrw @has_value_like_S; exrepnd.\n    destruct t as [v|f|op l].\n\n    { simpl in r1; ginv. }\n\n    { exists 0; dands; try omega.\n      rw @has_value_like_0; eauto 3 with slow. }\n\n    dopid op as [can1|ncan1|exc1|abs1] Case.\n\n    + Case \"Can\".\n      exists 0; dands; try omega.\n      rw @has_value_like_0; eauto 3 with slow.\n\n    + Case \"NCan\".\n      rw @compute_step_ncan_ncan in r1.\n      remember (compute_step lib (oterm (NCan ncan1) l)) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply IHk in r0; exrepnd; auto.\n      exists (S j); dands; try omega.\n      rw @has_value_like_S.\n      exists n; sp.\n\n    + Case \"Exc\".\n      csunf r1; allsimpl.\n      apply compute_step_catch_success in r1.\n      dorn r1; exrepnd; subst; allsimpl.\n\n      * exists 0; dands; try omega.\n        rw @has_value_like_0; eauto 3 with slow.\n\n      * exists 0; dands; try omega.\n        unfold has_value_like_k in r0; exrepnd.\n        apply computes_to_val_like_in_max_k_steps_if_isvalue_like in r1; eauto 3 with slow; subst.\n        rw @has_value_like_0; eauto 3 with slow.\n\n    + Case \"Abs\".\n      csunf r1; allsimpl; csunf r1; allsimpl.\n      unfold on_success in r1.\n      remember (compute_step_lib lib abs1 l) as comp.\n      symmetry in Heqcomp; destruct comp; ginv.\n      apply IHk in r0; exrepnd; auto.\n      exists (S j); dands; try omega.\n      rw @has_value_like_S.\n      exists n; sp.\nQed.\n\nLemma closed_mk_vbot {o} :\n  forall v, @closed o (mk_vbot v).\nProof.\n  introv.\n  unfold closed, mk_vbot; simpl.\n  rw remove_nvars_eq; simpl; auto.\nQed.\nHint Resolve closed_mk_vbot : slow.\n\nLemma alphaeq_preserves_computes_to_val_like_in_max_k_steps {o} :\n  forall lib k (t1 t2 : @NTerm o) u,\n    nt_wf t1\n    -> alpha_eq t1 t2\n    -> computes_to_val_like_in_max_k_steps lib t1 u k\n    -> {v : NTerm & computes_to_val_like_in_max_k_steps lib t2 v k # alpha_eq u v}.\nProof.\n  introv wf aeq hv.\n  allunfold @computes_to_val_like_in_max_k_steps; repnd.\n  pose proof (reduces_in_atmost_k_steps_alpha lib t1 t2) as h; repeat (autodimp h hyp).\n  applydup h in hv0; exrepnd.\n  exists t2'; dands; auto.\n  eapply alpha_eq_preserves_isvalue_like; eauto.\nQed.\n\nLemma alphaeq_preserves_has_value_like_k {o} :\n  forall lib k (t1 t2 : @NTerm o),\n    nt_wf t1\n    -> alpha_eq t1 t2\n    -> has_value_like_k lib k t1\n    -> has_value_like_k lib k t2.\nProof.\n  introv wf aeq hv.\n  allunfold @has_value_like_k; exrepnd.\n  eapply alphaeq_preserves_computes_to_val_like_in_max_k_steps in hv0; eauto.\n  exrepnd.\n  exists v; auto.\nQed.\n\nLemma has_value_like_k_ren_utokens {o} :\n  forall lib k (t : @NTerm o) ren,\n    nt_wf t\n    -> no_repeats (range_utok_ren ren)\n    -> disjoint (range_utok_ren ren) (diff (get_patom_deq o) (dom_utok_ren ren) (get_utokens t))\n    -> has_value_like_k lib k t\n    -> has_value_like_k lib k (ren_utokens ren t).\nProof.\n  introv wf norep disj hvl.\n  allunfold @has_value_like_k; exrepnd.\n  allunfold @computes_to_val_like_in_max_k_steps; repnd.\n  apply (reduces_in_atmost_k_steps_ren_utokens _ _ _ _ ren) in hvl1; auto.\n  exists (ren_utokens ren u); dands; eauto with slow.\nQed.\n\nLemma reduces_in_atmost_k_steps_refl {o} :\n  forall (lib : library) (k : nat) (t : @NTerm o),\n    isvalue_like t\n    -> reduces_in_atmost_k_steps lib t t k.\nProof.\n  induction k; introv isvl.\n  - rw @reduces_in_atmost_k_steps_0; auto.\n  - rw @reduces_in_atmost_k_steps_S.\n    exists t; dands; tcsp.\n    apply compute_step_value_like; auto.\nQed.\n\nLemma eqset_free_vars_disjoint {o} :\n  forall (t : @NTerm o) (sub : Substitution),\n  eqset (free_vars (lsubst t sub))\n        (remove_nvars (dom_sub sub) (free_vars t)\n                      ++ sub_free_vars (sub_keep_first sub (free_vars t))).\nProof.\n  introv; pose proof (eqvars_free_vars_disjoint t sub) as h; rw eqvars_prop in h; auto.\nQed.\n\nLemma has_value_like_k_fresh_implies {o} :\n  forall lib k a v (t : @NTerm o),\n    wf_term t\n    -> !LIn a (get_utokens t)\n    -> has_value_like_k lib k (mk_fresh v t)\n    -> has_value_like_k lib k (subst t v (mk_utoken a)).\nProof.\n  introv wt nia hvl.\n  allunfold @has_value_like_k; exrepnd.\n  allunfold @computes_to_val_like_in_max_k_steps; exrepnd.\n  revert dependent u.\n  revert dependent t.\n  revert dependent a.\n  induction k; introv wt nia r isvl.\n\n  - allrw @reduces_in_atmost_k_steps_0; subst.\n    unfold isvalue_like in isvl; repndors; inversion isvl.\n\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    apply compute_step_ncan_bterm_cons_success in r1; repnd; subst; GC.\n    repndors; exrepnd; subst; allsimpl; GC.\n    + apply reduces_in_atmost_k_steps_implies_reduces_to in r0.\n      apply reduces_in_atmost_k_step_fresh_id in r0; tcsp.\n    + apply computation3.reduces_in_atmost_k_steps_if_isvalue_like in r0; eauto 3 with slow; subst.\n      exists (subst t v (mk_utoken a)); dands; eauto 4 with slow.\n      apply reduces_in_atmost_k_steps_refl; eauto with slow.\n    + repnd; subst.\n      pose proof (compute_step_subst_utoken lib t x [(v,mk_utoken (get_fresh_atom t))]) as h.\n      allrw @get_utokens_sub_cons; allrw @get_utokens_sub_nil; allsimpl.\n      allrw disjoint_singleton_l.\n      repeat (autodimp h hyp); try (apply get_fresh_atom_prop); eauto 3 with slow.\n      { apply nr_ut_sub_cons; eauto 3 with slow.\n        intro i; apply get_fresh_atom_prop. }\n      exrepnd.\n      pose proof (h0 [(v,mk_utoken a)]) as q; clear h0; allsimpl.\n      allrw @get_utokens_sub_cons; allrw @get_utokens_sub_nil; allsimpl.\n      allrw disjoint_singleton_l.\n      repeat (autodimp q hyp); exrepnd.\n      allrw @fold_subst.\n\n      assert (wf_term x) as wfx.\n      { eapply compute_step_preserves_wf;[exact r3|].\n        apply wf_term_subst; eauto with slow. }\n\n      assert (!LIn v (free_vars x)) as nivx.\n      { intro j; apply compute_step_preserves in r3; repnd; eauto 3 with slow.\n        rw subvars_prop in r2; apply r2 in j; clear r2.\n        apply eqset_free_vars_disjoint in j; allsimpl.\n        allrw in_app_iff; allrw in_remove_nvars; allsimpl; boolvar; allsimpl; tcsp. }\n\n      pose proof (IHk a (subst_utokens x [(get_fresh_atom t, mk_var v)])) as q; clear IHk.\n      repeat (autodimp q hyp).\n      { apply wf_subst_utokens; eauto 3 with slow. }\n      { intro j; apply get_utokens_subst_utokens_subset in j; allsimpl.\n        unfold get_utokens_utok_ren in j; allsimpl; allrw app_nil_r.\n        rw in_remove in j; repnd.\n        apply alphaeq_preserves_utokens in h1; rw h1 in j.\n        apply get_utokens_subst in j; boolvar; allsimpl; allrw in_app_iff; tcsp; allsimpl.\n        repndors; tcsp. }\n\n      pose proof (q u) as ih; clear q.\n      repeat (autodimp ih hyp); exrepnd.\n\n      pose proof (simple_subst_subst_utokens_aeq x (get_fresh_atom t) v) as aeq1.\n      repeat (autodimp aeq1 hyp).\n\n      pose proof (alpha_eq_ren_utokens\n                    (subst (subst_utokens x [(get_fresh_atom t, mk_var v)]) v\n                           (mk_utoken (get_fresh_atom t)))\n                    x [(get_fresh_atom t, a)] aeq1) as aeq2.\n      rw @subst_ren_utokens in aeq2; allsimpl; fold_terms.\n      unfold ren_atom in aeq2; allsimpl; boolvar; tcsp.\n      rw @ren_utokens_trivial in aeq2;\n        [|simpl; apply disjoint_singleton_l; intro i;\n          apply get_utokens_subst_utokens_subset in i; allsimpl;\n          unfold get_utokens_utok_ren in i; allsimpl; rw app_nil_r in i;\n          rw in_remove in i; repnd; GC;\n          apply alphaeq_preserves_utokens in h1; rw h1 in i;\n          apply get_utokens_subst in i; allsimpl; boolvar; allrw app_nil_r;\n          allrw in_app_iff; repndors; tcsp].\n\n      clear aeq1.\n\n      pose proof (alpha_eq_ren_utokens\n                    x (subst w v (mk_utoken (get_fresh_atom t)))\n                    [(get_fresh_atom t, a)] h1) as aeq3.\n      rw @subst_ren_utokens in aeq3; allsimpl; fold_terms.\n      unfold ren_atom in aeq3; allsimpl; boolvar; tcsp.\n      rw (ren_utokens_trivial [(get_fresh_atom t, a)] w) in aeq3;\n        [|simpl; apply disjoint_singleton_l; intro i; apply h4 in i;\n          apply get_fresh_atom_prop in i; sp]; GC.\n\n      eapply alpha_eq_trans in aeq3;[|exact aeq2]; clear aeq2.\n      apply alpha_eq_sym in aeq3.\n      eapply alpha_eq_trans in aeq3;[|exact q0]; clear q0.\n\n      dup ih1 as ih2.\n      eapply reduces_in_atmost_k_steps_alpha in ih2;\n        [|apply nt_wf_subst; eauto 3 with slow;\n          apply nt_wf_eq; apply wf_subst_utokens;\n          eauto 3 with slow\n         |apply alpha_eq_sym in aeq3; apply aeq3];[];exrepnd.\n      rename t2' into s'.\n\n      exists s'; dands; eauto 2 with slow.\n      rw @reduces_in_atmost_k_steps_S.\n      eexists; dands; eauto.\nQed.\n\nLemma has_value_like_k_vbot {o} :\n  forall (lib : @library o) k v,\n    !has_value_like_k lib k (mk_vbot v).\nProof.\n  introv hv.\n  unfold has_value_like_k, computes_to_val_like_in_max_k_steps in hv; exrepnd.\n  apply reduces_in_atmost_k_steps_vbot in hv1; tcsp.\nQed.\n\nLemma has_value_like_k_fresh_id {o} :\n  forall (lib : @library o) k v,\n    !has_value_like_k lib k (mk_fresh v (mk_var v)).\nProof.\n  introv hv.\n  unfold has_value_like_k, computes_to_val_like_in_max_k_steps in hv; exrepnd.\n  pose proof (reduces_in_atmost_k_step_fresh_id lib v u) as h.\n  autodimp h hyp.\n  eauto 3 with slow.\nQed.\n\nDefinition computes_to_can {p} lib (t1 t2 : @NTerm p) :=\n  reduces_to lib t1 t2\n  # iscan t2.\n\nLemma computes_to_exception_mk_less {o} :\n  forall lib (a b c d : @NTerm o) n e,\n    wf_term a\n    -> wf_term b\n    -> wf_term c\n    -> wf_term d\n    -> computes_to_exception lib n (mk_less a b c d) e\n    -> {k1 : Z\n        & {k2 : Z\n        & reduces_to lib a (mk_integer k1)\n        # reduces_to lib b (mk_integer k2)\n        # (((k1 < k2)%Z # computes_to_exception lib n c e)\n           [+]\n           ((k2 <= k1)%Z # computes_to_exception lib n d e)\n          )}}\n       [+] computes_to_exception lib n a e\n       [+] {z : Z\n            & reduces_to lib a (mk_integer z)\n            # computes_to_exception lib n b e}.\nProof.\n  introv wfa wfb wfc wfd comp.\n  unfold computes_to_exception, reduces_to in comp; exrepnd.\n  pose proof (computes_to_val_like_in_max_k_steps_comp_implies\n                lib k CompOpLess a b c d (mk_exception n e)) as h.\n  repeat (autodimp h hyp).\n  { unfold computes_to_val_like_in_max_k_steps; dands; eauto 3 with slow. }\n\n  repndors; exrepnd; repndors; exrepnd; ginv.\n\n  - left.\n    allunfold @computes_to_can_in_max_k_steps; repnd.\n    allunfold @spcan; fold_terms.\n    exists i1 i2; dands; eauto with slow.\n    boolvar;[left|right]; dands; auto;\n    allunfold @computes_to_val_like_in_max_k_steps; repnd;\n    exists (k - (k1 + k2 + 1)); auto.\n\n  - right; left.\n    exists k1; auto.\n\n  - right; right; allsimpl.\n    exists i; dands; auto.\n    + allunfold @computes_to_can_in_max_k_steps; repnd.\n      unfold computes_to_can; dands; eauto with slow.\n    + exists k2; auto.\nQed.\n\nLemma computes_to_can_in_max_k_steps_implies_reduces_in_atmost_k_steps {o} :\n  forall lib k (t : @NTerm o) u,\n    computes_to_can_in_max_k_steps lib k t u\n    -> reduces_in_atmost_k_steps lib t u k.\nProof.\n  introv comp.\n  unfold computes_to_can_in_max_k_steps in comp; sp.\nQed.\nHint Resolve computes_to_can_in_max_k_steps_implies_reduces_in_atmost_k_steps : slow.\n\nLemma computes_to_val_like_in_max_k_steps_implies_has_value_like_k {o} :\n  forall lib (t u : @NTerm o) k,\n    computes_to_val_like_in_max_k_steps lib t u k\n    -> has_value_like_k lib k t.\nProof.\n  introv comp.\n  unfold has_value_like_k.\n  exists u; sp.\nQed.\nHint Resolve computes_to_val_like_in_max_k_steps_implies_has_value_like_k : slow.\n\nLemma has_value_like_k_mk_less {o} :\n  forall lib k (a b c d : @NTerm o),\n    wf_term a\n    -> wf_term b\n    -> wf_term c\n    -> wf_term d\n    -> has_value_like_k lib k (mk_less a b c d)\n    -> ({k1 : nat\n         & {u : NTerm\n         & {e : NTerm\n         & k1 + 1 <= k\n         # computes_to_exception_in_max_k_steps lib u a e k1\n         # reduces_in_atmost_k_steps\n             lib\n             (mk_less a b c d)\n             (mk_less (mk_exception u e) b c d) k1 }}}\n        [+]\n        {k1 : nat\n         & {k2 : nat\n         & {z : Z\n         & {u : NTerm\n         & {e : NTerm\n         & k1 + k2 + 1 <= k\n         # reduces_in_atmost_k_steps lib a (mk_integer z) k1\n         # computes_to_exception_in_max_k_steps lib u b e k2\n         # reduces_in_atmost_k_steps\n             lib\n             (mk_less a b c d)\n             (mk_less (mk_integer z) (mk_exception u e) c d)\n             (k1 + k2)}}}}}\n        [+]\n        {k1 : nat\n         & {k2 : nat\n         & {i1 : Z\n         & {i2 : Z\n         & k1 + k2 + 1 <= k\n         # reduces_in_atmost_k_steps lib a (mk_integer i1) k1\n         # reduces_in_atmost_k_steps lib b (mk_integer i2) k2\n         # has_value_like_k\n             lib\n             (k - (k1 + k2 + 1))\n             (if Z_lt_le_dec i1 i2 then c else d)\n         # reduces_in_atmost_k_steps\n             lib\n             (mk_less a b c d)\n             (mk_less (mk_integer i1) (mk_integer i2) c d)\n             (k1 + k2) }}}}).\nProof.\n  introv wa wb wc wd hv.\n  unfold has_value_like_k in hv; exrepnd.\n  apply computes_to_val_like_in_max_k_steps_comp_implies in hv0;\n    repndors; exrepnd; auto;[|idtac|].\n\n  - repndors; exrepnd; tcsp;ginv;[].\n    allunfold @spcan; fold_terms.\n    right; right.\n    exists k1 k2 i1 i2.\n    dands; eauto 3 with slow.\n    boolvar; eauto 3 with slow.\n\n  - subst; fold_terms.\n    left.\n    exists k1 en e; sp.\n\n  - subst; fold_terms.\n    right; left.\n    repndors; exrepnd; ginv; allsimpl.\n    exists k1 k2 i en e; dands; eauto 3 with slow.\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/computation6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2557022309188039}}
{"text": "From stdpp Require Import prelude.\nFrom VLSM.Lib Require Import Preamble.\nFrom VLSM.Core Require Import VLSM VLSMProjections Composition Equivocation.\n\n(** * VLSM No Equivocation Composition Constraints *)\n\nSection sec_no_equivocations.\n\nContext\n  {message : Type}\n  (vlsm : VLSM message)\n  .\n\n(**\n  An equivocating transition can be prevented by checking that the message\n  to be received [has_been_sent] previously in the state about to receive it.\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\nDefinition no_equivocations_except_from\n  `{HasBeenSentCapability message vlsm}\n  (exception : message -> Prop)\n  (l : vlabel vlsm)\n  (som : state * option message)\n  :=\n  let (s, om) := som in\n  from_option (fun m => has_been_sent vlsm s m \\/ exception m) True om.\n\n(**\n  The [no_equivocations] constraint does not allow any exceptions\n  (messages being received must have been previously sent).\n*)\nDefinition no_equivocations\n  `{HasBeenSentCapability message vlsm}\n  (l : vlabel vlsm)\n  (som : state * option message)\n  : Prop\n  :=\n  no_equivocations_except_from (fun m => False) l som.\n\nEnd sec_no_equivocations.\n\n(** ** No-Equivocation Invariants\n\n  In this section we show that under [no_equivocations] assumptions:\n\n  - for any valid state all messages [directly_observed_were_sent].\n  - the [pre_loaded_with_all_messages_vlsm] is equal to the [no_equivocations] VLSM.\n*)\n\nSection sec_no_equivocation_invariants.\n\nContext\n  message\n  (X : VLSM message)\n  `{HasBeenSentCapability message X}\n  `{HasBeenDirectlyObservedCapability message X}\n  (Henforced : forall l s om, input_valid (pre_loaded_with_all_messages_vlsm X) l (s, om) ->\n    no_equivocations X l (s, om))\n  .\n\n(**\n  A VLSM that enforces the [no_equivocations] constraint and also supports\n  [has_been_directly_observed] obeys the [directly_observed_were_sent] invariant which states that\n  any message that [has_been_directly_observed] in a state, [has_been_sent] in\n  the same state, too.\n*)\n\nDefinition directly_observed_were_sent (s : state) : Prop :=\n  forall msg, has_been_directly_observed X s msg -> has_been_sent X s msg.\n\nLemma directly_observed_were_sent_initial s :\n  vinitial_state_prop X s ->\n  directly_observed_were_sent s.\nProof.\n  intros Hinitial msg Hsend.\n  by apply has_been_directly_observed_no_inits in Hsend.\nQed.\n\nLemma directly_observed_were_sent_preserved l s im s' om :\n  input_valid_transition X l (s, im) (s', om) ->\n  directly_observed_were_sent s ->\n  directly_observed_were_sent s'.\nProof.\n  intros Hptrans Hprev msg Hobs.\n  specialize (Hprev msg).\n  apply preloaded_weaken_input_valid_transition in Hptrans.\n  eapply (oracle_step_update (has_been_directly_observed_stepwise_props X) _ _ _ _ _ Hptrans)\n    in Hobs; simpl in Hobs.\n  specialize (Henforced l s (Some msg)).\n  rewrite (has_been_sent_step_update Hptrans).\n  destruct Hptrans as [Hv _].\n  destruct Hobs as [[Hin | Hout] | Hobs]; subst.\n  - (* by [no_equivocations], the incoming message [im] was previously sent *)\n    specialize (Henforced Hv).\n    by destruct Henforced; [right |].\n  - by left.\n  - by right; apply Hprev.\nQed.\n\n(* TODO(wkolowski): make notation uniform accross the file. *)\nLemma directly_observed_were_sent_invariant s:\n  valid_state_prop X s ->\n  directly_observed_were_sent s.\nProof.\n  intro Hproto.\n  induction Hproto using valid_state_prop_ind.\n  - by apply directly_observed_were_sent_initial.\n  - by eapply directly_observed_were_sent_preserved.\nQed.\n\n(**\n  If the [valid]ity function satisfies the [no_equivocations] constraint then\n  it doesn't matter if we preload the composition with some initial messages,\n  since all messages must be sent before being received, which means that\n  one cannot use the new messages to create additional traces.\n*)\nLemma no_equivocations_preloaded_traces\n  (is : state)\n  (tr : list transition_item)\n  : finite_valid_trace (pre_loaded_with_all_messages_vlsm X) is tr -> finite_valid_trace X is tr.\nProof.\n  intro Htr.\n  induction Htr using finite_valid_trace_rev_ind.\n  - split; [| done].\n    rapply @finite_valid_trace_from_empty.\n    by apply initial_state_is_valid.\n  - destruct IHHtr as [IHtr His].\n    split; [| done].\n    rapply extend_right_finite_trace_from; [done |].\n    apply finite_valid_trace_last_pstate in IHtr as Hs.\n    cut (option_valid_message_prop X iom); [by firstorder |].\n    destruct iom as [m |]; [| by apply option_valid_message_None].\n    destruct Hx as [Hv _].\n    apply Henforced in Hv.\n    destruct Hv as [Hbsm | []].\n    by eapply sent_valid.\nQed.\n\nLemma preloaded_incl_no_equivocations\n  : VLSM_incl (pre_loaded_with_all_messages_vlsm X) X.\nProof.\n  specialize no_equivocations_preloaded_traces.\n  clear -X. destruct X as [T [S M]].\n  by apply VLSM_incl_finite_traces_characterization.\nQed.\n\nLemma preloaded_eq_no_equivocations\n  : VLSM_eq (pre_loaded_with_all_messages_vlsm X) X.\nProof.\n  split.\n  - by apply preloaded_incl_no_equivocations.\n  - by apply (vlsm_incl_pre_loaded_with_all_messages_vlsm X).\nQed.\n\nEnd sec_no_equivocation_invariants.\n\nSection sec_composite_no_equivocation.\n\nContext\n  {message : Type}\n  `{finite.Finite index}\n  (IM : index -> VLSM message)\n  `{forall i, HasBeenSentCapability (IM i)}\n  (constraint : composite_label IM -> composite_state IM * option message -> Prop)\n  .\n\nDefinition sent_except_from exception es iom : Prop :=\n  from_option (fun im => composite_has_been_sent IM es im \\/ exception im) True iom.\n\nDefinition composite_no_equivocations_except_from\n  (exception : message -> Prop)\n  (l : composite_label IM)\n  (som : composite_state IM * option message)\n  :=\n  sent_except_from exception som.1 som.2.\n\n(**\n  The [composite_no_equivocations] constraint requires that\n  messages being received must have been previously sent by a\n  machine in the composition.\n*)\nDefinition composite_no_equivocations\n  (l : composite_label IM)\n  (som : composite_state IM * option message)\n  : Prop\n  :=\n  composite_no_equivocations_except_from (fun m => False) l som.\n\n(** ** Composite No-Equivocation Invariants\n\n  A VLSM composition whose constraint subsumes the [no_equivocations] constraint\n  and also supports [has_been_received] (or [has_been_directly_observed]) obeys an\n  invariant that any message that tests as [has_been_received]\n  (resp. [has_been_directly_observed]) in a state also tests as [has_been_sent]\n  in the same state.\n*)\n\nSection sec_composite_no_equivocation_invariants.\n\nContext\n  `{forall i, HasBeenReceivedCapability (IM i)}\n  (X := composite_vlsm IM constraint)\n  (Hsubsumed : preloaded_constraint_subsumption IM constraint composite_no_equivocations)\n  .\n\nDefinition composite_directly_observed_were_sent (s : state) : Prop :=\n  forall msg, composite_has_been_directly_observed IM s msg -> composite_has_been_sent IM s msg.\n\nLemma composite_directly_observed_were_sent_invariant s :\n  valid_state_prop X s ->\n  composite_directly_observed_were_sent s.\nProof.\n  intros Hs m.\n  rewrite composite_has_been_directly_observed_sent_received_iff.\n  intros Hobs.\n  cut (has_been_sent X s m); [done |].\n  apply (directly_observed_were_sent_invariant message X); [| done ..].\n  by intros l s0 om; apply Hsubsumed.\nQed.\n\nEnd sec_composite_no_equivocation_invariants.\n\nSection sec_seeded_composite_vlsm_no_equivocation.\n\n(** ** Pre-loading a VLSM composition with no equivocations constraint\n\n  When adding initial messages to a VLSM composition with a no equivocation\n  constraint, we cannot simply use the [pre_loaded_vlsm] construct\n  because the no-equivocation constraint must also be altered to reflect that\n  the newly added initial messages are safe to be received at all times.\n*)\n\nContext\n  (X := free_composite_vlsm IM)\n  .\n\nSection sec_seeded_composite_vlsm_no_equivocation_definition.\n\nContext\n  (seed : message -> Prop)\n  .\n\n(** Constraint is updated to also allow seeded messages. *)\n\nDefinition no_equivocations_additional_constraint_with_pre_loaded\n  (l : composite_label IM)\n  (som : composite_state IM * option message)\n  :=\n  composite_no_equivocations_except_from seed l som\n  /\\ constraint l som.\n\nDefinition 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\nLemma seeded_no_equivocation_incl_preloaded :\n  VLSM_incl composite_no_equivocation_vlsm_with_pre_loaded\n    (pre_loaded_with_all_messages_vlsm (free_composite_vlsm IM)).\nProof.\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  destruct Hprev as [_ Hprev].\n  match type of Hprev with\n  | VLSM_incl (mk_vlsm ?m) _ => apply VLSM_incl_trans with m\n  end.\n  - cbn; clear Hprev.\n    by apply (@pre_loaded_vlsm_incl message\n      (composite_vlsm IM no_equivocations_additional_constraint_with_pre_loaded)).\n  - match type of Hprev with\n    | VLSM_incl _ (mk_vlsm ?m) => apply VLSM_incl_trans with m\n    end\n    ; [done |].\n    unfold free_composite_vlsm; cbn.\n    by apply preloaded_constraint_subsumption_incl.\nQed.\n\nEnd sec_seeded_composite_vlsm_no_equivocation_definition.\n\n(** Adds a no-equivocations condition on top of an existing constraint. *)\nDefinition no_equivocations_additional_constraint\n  (l : composite_label IM)\n  (som : composite_state IM * option message)\n  :=\n  composite_no_equivocations l som\n  /\\ constraint l som.\n\nContext\n  (SeededNoeqvFalse := composite_no_equivocation_vlsm_with_pre_loaded (fun m => False))\n  (Noeqv := composite_vlsm IM no_equivocations_additional_constraint)\n  (SeededNoeqvTrue := composite_no_equivocation_vlsm_with_pre_loaded (fun m => True))\n  (PreFree := pre_loaded_with_all_messages_vlsm (free_composite_vlsm IM))\n  .\n\nLemma false_composite_no_equivocation_vlsm_with_pre_loaded\n  : VLSM_eq SeededNoeqvFalse Noeqv.\nProof.\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  ; [done |].\n  specialize (constraint_subsumption_incl IM) as Hincl.\n  unfold no_equivocations_additional_constraint_with_pre_loaded.\n  by split; apply Hincl; intros l [s [m |]] Hpv; apply Hpv.\nQed.\n\nEnd sec_seeded_composite_vlsm_no_equivocation.\n\nEnd sec_composite_no_equivocation.\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/Equivocation/NoEquivocation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2556201947680135}}
{"text": "(**#+TITLE: galoisSolution.v\n\nProph\n\nhttps://github.com/1337777/galois/blob/master/galoisSolution.v\n\nsolves some question of Galois [fn:1] which is how to program grammatical (\"classifying\")\nfunctors-topos of some graph.\n\nThis starting lemma of polymorph mathematics (\"categories\") :\n\nCoreflections( Set , Funtors( C* , Prop ) ) <=> Funtors( C , Set )\n\nsays that the senses (\"functors models\") onfrom some given primitive-syntax graph may be\ninstead dually-usefully-viewed as senses (\"coreflective-functors models\") into some\nmore-complete-grammatical (\"classifying\") functors-topos. And this starting lemma may be\nupgraded such to perceive flat functors via geometric morphisms into some presheaf\nfunctors-topos. Also this starting lemma may be upgraded such to perceive continuous flat\nfunctors via geometric morphisms into some sheaf functors-topos ...\n\nThe question is whether these new more-complete-grammatical functors-topos are relatively\ncomputational/decidable ? Some promised COQ program shall/may OK these. Promise only ...\n\n\n[fn:1] ~Galois~ «Théorie des topos et cohomologie étale des schémas»\n\n**)\n\n(**\n\n#+BEGIN_SRC coq :exports both :results silent **)\n\nRequire Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp Require Import ssrbool ssrfun eqtype ssrnat seq fintype.\nRequire Import Setoid.\nRequire Omega. \n\n(**#+END_SRC\n\n#+BEGIN_SRC coq :exports both :results silent **)\n\nModule METAFUNCTORS.\n\nGlobal Set Implicit Arguments.\nGlobal Unset Strict Implicit.\nGlobal Unset Printing Implicit Defensive.\n \nParameter obIndexer : Type (* regular cardinal *).\nParameter Indexer : obIndexer -> obIndexer -> Type (* regular cardinal *).\nNotation \"''Indexer' (0 A1 ~> A2 )0\" :=\n  (@Indexer A1 A2) (at level 25, format \"''Indexer' (0  A1  ~>  A2  )0\").\nParameter polyIndexer : forall (A2 A1 : obIndexer),\n    Indexer A2 A1 -> forall A1' : obIndexer, (Indexer A1 A1') -> (Indexer A2 A1').\nNotation \"a_ o>Indexer a'\" :=\n  (@polyIndexer _ _ a_ _ a') (at level 25, right associativity).\nParameter unitIndexer : forall {A : obIndexer}, Indexer A A.\nParameter convIndexer : forall (A1 A2 : obIndexer),\n    'Indexer(0 A1 ~> A2 )0 -> 'Indexer(0 A1 ~> A2 )0 -> Prop.\nNotation \"a2 ~~ a1\" := (@convIndexer _ _ a2 a1) (at level 70).\n\nInductive obTopos : Type (* larger cardinal *) :=\n| View0 : forall A : obIndexer, obTopos\n| MetaFunctor : forall (func0 : obIndexer -> Type (* regular cardinal *))  \n                  (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n    obTopos.\n\nReserved Notation \"''Topos' (0 F1 ~> F2 )0\"\n         (at level 25, format \"''Topos' (0  F1  ~>  F2  )0\").\n\nInductive Topos00 : obTopos -> obTopos -> Type (* larger cardinal, possible *) :=\n\n| UnitTopos : forall {F : obTopos}, 'Topos(0 F ~> F )0\n\n| PolyTopos : forall (F2 : obTopos) (F1 : obTopos)\n  , 'Topos(0 F2 ~> F1 )0 -> forall F1' : obTopos,\n      'Topos(0 F1 ~> F1' )0 -> 'Topos(0 F2 ~> F1' )0\n\n| View1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 ->\n                                'Topos(0 (View0 A) ~> (View0 A') )0\n\n| PolyMetaFunctor :\n    forall (func0 : obIndexer -> Type (* same, regular cardinal *))\n      (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n      (forall (A : obIndexer), func0 A -> 'Topos(0 (View0 A) ~> (MetaFunctor func1) )0)\n\n| PolyMetaTransf :\n    forall (func0 : obIndexer -> Type)\n      (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n    forall (func'0 : obIndexer -> Type)\n      (func'1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func'0 A' -> func'0 A),\n    forall (transf : forall (A : obIndexer), func0 A -> func'0 A),\n      (forall (A : obIndexer), 'Topos(0 (View0 A) ~> (MetaFunctor func1) )0\n                          -> 'Topos(0 (View0 A) ~> (MetaFunctor func'1) )0)\n\n| CoLimitator :\n    forall (func0 : obIndexer -> Type)\n      (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n    forall F : obTopos,\n    forall (v_ : forall (A : obIndexer), func0 A -> 'Topos(0 (View0 A) ~> F )0),\n      (* cocone func1 v_ ->    cocone erased *)\n      'Topos(0 (MetaFunctor func1) ~> F )0\n\nwhere \"''Topos' (0 F1 ~> F2 )0\" := (@Topos00 F1 F2).\n\nNotation \"'uTopos'\" := (@UnitTopos _)(at level 0).\nNotation \"@ 'uTopos' F\" :=\n  (@UnitTopos F) (at level 11, only parsing).\n\nNotation \"f_ o>Topos f'\" :=\n  (@PolyTopos _ _ f_ _ f') (at level 25, right associativity).\n\nNotation \"f o>Topos_ transf @ func'1\" :=\n  (@PolyMetaTransf _ _ _ func'1 transf _ f) (at level 25, transf at level 0, right associativity).\n\nNotation \"f o>Topos_ transf\" :=\n  (@PolyMetaTransf _ _ _ _ transf _ f) (at level 25, transf at level 0, right associativity).\n\nNotation \"[[ v_ @ func1 ]]\" :=\n  (@CoLimitator _ func1 _ v_ ) (at level 0).\n\nNotation \"[[ v_ ]]\" :=\n  (@CoLimitator _ _ _ v_ ) (at level 0).\n\nLtac rewriterTopos :=\n  repeat match goal with\n         | [ HH : @eq (Topos00 _ _) _ _  |- _ ] =>\n           try rewrite -> HH in *; clear HH\n         end. \n\nReserved Notation \"f2 ~~~ f1\"  (at level 70).\n\nInductive convTopos : forall (F1 F2 : obTopos),\n    'Topos(0 F1 ~> F2 )0 -> 'Topos(0 F1 ~> F2 )0 -> Prop :=\n\n(* equivalence *)\n  \n| Topos_Refl : forall (F1 F2 : obTopos) (f : 'Topos(0 F1 ~> F2 )0),\n    f ~~~ f\n      \n| Topos_Trans : forall (F1 F2 : obTopos) (uTrans f : 'Topos(0 F1 ~> F2 )0),\n    uTrans ~~~ f -> forall (f0 : 'Topos(0 F1 ~> F2 )0),\n      f0 ~~~ uTrans -> f0 ~~~ f\n                         \n| Topos_Sym : forall (F1 F2 : obTopos) (f f0 : 'Topos(0 F1 ~> F2 )0),\n    f ~~~ f0 -> f0 ~~~ f\n\n(* congruences *)\n                  \n| PolyTopos_cong :\n    forall (F F' : obTopos) (f_ f_0 : 'Topos(0 F ~> F' )0),\n    forall (F'' : obTopos) (f' f'0 : 'Topos(0 F' ~> F'' )0),\n      f_0 ~~~ f_ -> f'0 ~~~ f' -> ( f_0 o>Topos f'0 ) ~~~ ( f_ o>Topos f' )\n\n| View_cong : forall (A A' : obIndexer) (a a0 : 'Indexer(0 A ~> A' )0),\n    a0 ~~ a -> View1 a0 ~~~ ( View1 a\n                             : 'Topos(0 View0 A ~> View0 A' )0 )\n\n| PolyMetaFunctor_cong :\n    forall (func0 : obIndexer -> Type)\n      (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n    forall (A : obIndexer) (x x0 : func0 A),\n      x0 = x -> PolyMetaFunctor func1 x0 ~~~ ( (PolyMetaFunctor func1 x)\n                                              : 'Topos(0 (View0 A) ~> (MetaFunctor func1) )0)\n                               \n| PolyMetaTransf_cong :\n    forall (func0 : obIndexer -> Type)\n      (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n    forall (func'0 : obIndexer -> Type)\n      (func'1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func'0 A' -> func'0 A),\n    forall (transf : forall (A : obIndexer), func0 A -> func'0 A),\n    forall (A : obIndexer) (v v0 : 'Topos(0 (View0 A) ~> (MetaFunctor func1) )0),\n      (* none lack to hold changes to transf because no such changes and uniform *)\n      v0 ~~~ v -> v0 o>Topos_transf ~~~ ( v o>Topos_transf\n                                          : 'Topos(0 (View0 A) ~> (MetaFunctor func'1) )0 )\n\n| CoLimitator_cong :\n    forall (func0 : obIndexer -> Type)\n      (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n    forall F : obTopos,\n    forall (v_ v_0 : forall (A : obIndexer), func0 A -> 'Topos(0 (View0 A) ~> F )0),\n      (* cocone func1 f_ ->    cocone erased *)\n      ( forall (A : obIndexer) (x : func0 A), v_0 A x ~~~ v_ A x ) \n      ->  [[ v_0 @ func1 ]] ~~~ ( [[ v_ @ func1 ]]\n                                 : 'Topos(0 MetaFunctor func1 ~> F )0 )\n\n(* units *)\n\n| Topos_unit :\n    forall (F F' : obTopos) (f : 'Topos(0 F ~> F' )0),\n      ( f )\n        ~~~ ( ( uTopos ) o>Topos f\n              : 'Topos(0 F ~> F' )0 )\n\n| Topos_inputUnitTopos :\n    forall (G F : obTopos) (g : 'Topos(0 G ~> F )0),\n      ( g )\n        ~~~  ( g o>Topos ( uTopos )\n               : 'Topos(0 G ~> F )0 )\n\n(* for sense only, non-necessary for reduction *)\n| View_unitIndexer : forall (A : obIndexer),\n    ( @UnitTopos (View0 A) )\n      ~~~ ( View1 (@unitIndexer A)\n            : 'Topos(0 View0 A ~> View0 A )0 )\n\n(* polymorphism *)\n\n(* non for reduction *)\n| Topos_morphism :\n    forall (G F : obTopos) (g : 'Topos(0 G ~> F )0)\n      (F' : obTopos) (f_ : 'Topos(0 F ~> F' )0)\n      (F'' : obTopos) (f' : 'Topos(0 F' ~> F'' )0),\n      ( g o>Topos ( f_ o>Topos f' ) )\n        ~~~ ( ( g o>Topos f_ ) o>Topos f'\n              : 'Topos(0 G ~> F'' )0 )\n\n| View_polyIndexer : forall (A A' : obIndexer) (a : 'Indexer(0 A ~> A' )0)\n                       (A'' : obIndexer) (a' : 'Indexer(0 A' ~> A'' )0),\n    (View1 (a o>Indexer a'))\n      ~~~ ( (View1 a) o>Topos (View1 a')\n            : 'Topos(0 View0 A ~> View0 A'' )0 )\n\n(* functoriality-polymorphism follows from this _cocone property and\nassociativity-polymorphism of PolyTopos and functoriality-polymorphism\nof View1 *)\n| PolyMetaFunctor_cocone :\n    forall (func0 : obIndexer -> Type)\n      (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n    forall (A : obIndexer) (x : func0 A) (A' : obIndexer) (a : 'Indexer(0 A' ~> A )0),\n      ( PolyMetaFunctor func1 (func1 _ _ a x) )\n        ~~~ ( (View1 a) o>Topos (PolyMetaFunctor func1 x)\n              : 'Topos(0 View0 A' ~> MetaFunctor func1 )0 )\n\n(* naturality-polymorphism is this, which is in operational form *)\n| PolyMetaTransf_poly :\n    forall (func0 : obIndexer -> Type)\n      (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n    forall (func'0 : obIndexer -> Type)\n      (func'1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func'0 A' -> func'0 A)\n      (transf : forall A : obIndexer, func0 A -> func'0 A),\n    forall (A : obIndexer) (v : 'Topos(0 (View0 A) ~> (MetaFunctor func1) )0)\n      (A' : obIndexer) (a : 'Indexer(0 A' ~> A )0),\n      ( ((View1 a) o>Topos v) o>Topos_transf )\n        ~~~ ( (View1 a) o>Topos (v o>Topos_transf)\n              : 'Topos(0 View0 A' ~> MetaFunctor func'1 )0 )\n\n(* naturality-polymorphism of the bijection*)\n| CoLimitator_morphism :\n    forall (func0 : obIndexer -> Type)\n      (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n    forall (F : obTopos) (v_ : forall (A : obIndexer), func0 A -> 'Topos(0 (View0 A) ~> F )0),\n    forall (F' : obTopos) (f : 'Topos(0 F ~> F' )0),\n      ( [[ (fun A x => (v_ A x) o>Topos f) @ func1 ]] )\n        ~~~ ( [[ v_ @ func1 ]] o>Topos f\n              : 'Topos(0 MetaFunctor func1 ~> F' )0 )\n\n| PolyMetaFunctor_CoLimitator :\n    forall (func0 : obIndexer -> Type)\n      (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n    forall F : obTopos,\n    forall (v_ : forall (A : obIndexer), func0 A -> 'Topos(0 (View0 A) ~> F )0),\n    forall (A : obIndexer) (x : func0 A),\n      ( v_ A x )\n        ~~~ ( (PolyMetaFunctor func1 x) o>Topos [[ v_ @ func1 ]]\n              : 'Topos(0 View0 A ~> F )0 )\n\n| PolyMetaTransf_CoLimitator :\n    forall (func'0 : obIndexer -> Type)\n      (func'1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func'0 A' -> func'0 A),\n    forall F : obTopos,\n    forall (v_ : forall (A : obIndexer), func'0 A -> 'Topos(0 (View0 A) ~> F )0),\n    forall (func0 : obIndexer -> Type)\n      (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n    forall (transf : forall (A : obIndexer), func0 A -> func'0 A)\n      (A : obIndexer) (w : 'Topos(0 (View0 A) ~> (MetaFunctor func1) )0),\n      (w o>Topos [[ (fun A0 => (v_ A0) \\o (transf A0)) @ func1 ]])\n        ~~~ (w o>Topos_transf) o>Topos [[ v_ @ func'1 ]]\n\n(* for sense only, non-necessary for reduction *)\n| PolyMetaTransf_PolyMetaFunctor :\n    forall (func0 : obIndexer -> Type)\n      (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n    forall (func'0 : obIndexer -> Type)\n      (func'1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func'0 A' -> func'0 A)\n      (transf : forall A : obIndexer, func0 A -> func'0 A),\n    forall (A : obIndexer) (x : func0 A),\n      ( PolyMetaFunctor func'1 (transf A x) )\n        ~~~ ( (PolyMetaFunctor func1 x o>Topos_transf)\n              : 'Topos(0 View0 A ~> MetaFunctor func'1 )0 )\n\n(* for sense only, non-necessary for reduction *)\n| CoLimitator_PolyMetaFunctor :\n    forall (func0 : obIndexer -> Type)\n      (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n      ( @UnitTopos (MetaFunctor func1) )\n        ~~~ ( [[ PolyMetaFunctor func1 ]]\n              : 'Topos(0 (MetaFunctor func1) ~> (MetaFunctor func1) )0 )\n        \nwhere \"f2 ~~~ f1\" := (@convTopos _ _ f2 f1).\n\nHint Constructors convTopos.\n\nDefinition cocone_def := \n    forall (func0 : obIndexer -> Type)\n      (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n    forall (F : obTopos)\n      (v_ : forall (A : obIndexer), func0 A -> 'Topos(0 (View0 A) ~> F )0),\n      forall (A : obIndexer) (x : func0 A) (A' : obIndexer) (a : 'Indexer(0 A' ~> A )0),\n      ( v_ A' (func1 _ _ a x) )\n        ~~~ ( (View1 a) o>Topos (v_ A x)\n              : 'Topos(0 View0 A' ~> F )0 ) .\n\nNotation cocone func1 v_ :=\n  (forall (A : obIndexer) (x : _ A) (A' : obIndexer) (a : 'Indexer(0 A' ~> A )0),\n      ( v_ A' (func1 _ _ a x) )\n        ~~~ ( (View1 a) o>Topos (v_ A x)\n              : 'Topos(0 View0 A' ~> _ )0 )) .\n\nCheck \n    forall (func0 : obIndexer -> Type)\n      (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n    forall (F : obTopos)\n      (v_ : forall (A : obIndexer), func0 A -> 'Topos(0 (View0 A) ~> F )0),\n      cocone func1 v_ ->\n      'Topos(0 (MetaFunctor func1) ~> F )0.\n\nModule Sol.\n\n  Section Section1.\n\n    Inductive Topos00 : obTopos -> obTopos -> Type :=\n\n    | UnitTopos : forall {F : obTopos}, 'Topos(0 F ~> F )0\n\n    | View1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 ->\n                                    'Topos(0 (View0 A) ~> (View0 A') )0\n\n    | PolyMetaFunctor :\n        forall (func0 : obIndexer -> Type)\n          (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n          (forall (A : obIndexer), func0 A -> 'Topos(0 (View0 A) ~> (MetaFunctor func1) )0)\n\n    | PolyMetaTransf :\n        forall (func0 : obIndexer -> Type)\n          (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n        forall (func'0 : obIndexer -> Type)\n          (func'1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func'0 A' -> func'0 A),\n        forall (transf : forall (A : obIndexer), func0 A -> func'0 A),\n          (forall (A : obIndexer), 'Topos(0 (View0 A) ~> (MetaFunctor func1) )0\n                              -> 'Topos(0 (View0 A) ~> (MetaFunctor func'1) )0)\n\n    | CoLimitator :\n        forall (func0 : obIndexer -> Type)\n          (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n        forall F : obTopos,\n        forall (v_ : forall (A : obIndexer), func0 A -> 'Topos(0 (View0 A) ~> F )0),\n          (* cocone func1 v_ ->    cocone erased *)\n          'Topos(0 (MetaFunctor func1) ~> F )0\n\n    where \"''Topos' (0 F1 ~> F2 )0\" := (@Topos00 F1 F2).\n\n  End Section1.\n\n  Module Import Ex_Notations.\n    Delimit Scope sol_scope with sol.\n    Notation \"''Topos' (0 F1 ~> F2 )0\" := (@Topos00 F1 F2) : sol_scope.\n    Notation \"'uTopos'\" := (@UnitTopos _)(at level 0) : sol_scope. \n    Notation \"@ 'uTopos' F\" :=\n      (@UnitTopos F) (at level 11, only parsing) : sol_scope.\n\n\n    Notation \"f o>Topos_ transf @ func'1\" :=\n      (@PolyMetaTransf _ _ _ func'1 transf _ f) (at level 25, transf at level 0, right associativity) : sol_scope.\n\n    Notation \"f o>Topos_ transf\" :=\n      (@PolyMetaTransf _ _ _ _ transf _ f) (at level 25, transf at level 0, right associativity) : sol_scope.\n\n    Notation \"[[ v_ @ func1 ]]\" :=\n      (@CoLimitator _ func1 _ v_ ) (at level 0) : sol_scope.\n\n    Notation \"[[ v_ ]]\" :=\n      (@CoLimitator _ _ _ v_ ) (at level 0) : sol_scope.\n  End Ex_Notations.\n\n  Definition toTopos :\n    forall (F1 F2 : obTopos), 'Topos(0 F1 ~> F2 )0 %sol -> 'Topos(0 F1 ~> F2 )0.\n  Proof.\n    (move => F1 F2 f); elim : F1 F2 / f =>\n    [ F\n    | A A' a\n    | func0 func1 A x\n    | func0 func1 func'0 func'1 transf A fSol fSol_toMod\n    | func0 func1 F vSol_ vSol_toMod ];\n      [ apply: (@uTopos F)\n      | apply: (METAFUNCTORS.View1 a)\n      | apply: (METAFUNCTORS.PolyMetaFunctor func1 x)\n      | apply: (fSol_toMod o>Topos_transf)\n      | apply: [[ vSol_toMod ]]\n      ].\n  Defined.\n\n  Module Destruct_domView.\n\n    Inductive Topos00_domView : forall (A : obIndexer) (F2 : obTopos),\n      ( 'Topos(0 View0 A ~> F2 )0 %sol ) -> Type :=\n\n    | UnitTopos : forall {A : obIndexer}, Topos00_domView (@uTopos (View0 A))%sol\n\n    | View1 : forall (A A' : obIndexer) (a : 'Indexer(0 A ~> A' )0),\n        Topos00_domView (Sol.View1 a)%sol\n\n    | PolyMetaFunctor :\n        forall (func0 : obIndexer -> Type)\n          (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n        forall (A : obIndexer) (x : func0 A),\n          Topos00_domView (Sol.PolyMetaFunctor func1 x)%sol\n\n    | PolyMetaTransf :\n        forall (func0 : obIndexer -> Type)\n          (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n        forall (func'0 : obIndexer -> Type)\n          (func'1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func'0 A' -> func'0 A),\n        forall (transf : forall (A : obIndexer), func0 A -> func'0 A),\n          forall (A : obIndexer) (f : 'Topos(0 (View0 A) ~> (MetaFunctor func1) )0 %sol),\n              Topos00_domView (f o>Topos_transf @ func'1)%sol .\n\n    Lemma Topos00_domViewP : forall F1 F2 ( f : 'Topos(0 F1 ~> F2 )0 %sol ),\n           match F1 as o return (forall F2 : obTopos, ('Topos(0 o ~> F2 )0)%sol -> Type) with\n           | View0 A => fun F2 : obTopos => [eta Topos00_domView (F2:=F2)]\n           | @MetaFunctor func0 func1 =>\n             fun _ _  => unit\n           end F2 f.\n    Proof.\n      intros. case: F1 F2 / f.\n      - destruct F. constructor 1.  exact: tt.\n      - constructor 2.\n      - constructor 3.\n      - constructor 4.\n      - intros. exact: tt.\n    Defined.\n\n  End Destruct_domView.\n\n  Module Destruct_domMetaFunctor.\n\n    Inductive Topos00_domMetaFunctor :\n      forall (func0 : obIndexer -> Type)\n        (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n      forall (F2 : obTopos),\n        ( 'Topos(0 MetaFunctor func1 ~> F2 )0 %sol ) -> Type :=\n\n    | UnitTopos : forall (func0 : obIndexer -> Type)\n                    (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n        Topos00_domMetaFunctor (@uTopos (MetaFunctor func1))%sol\n\n    | CoLimitator :\n        forall (func0 : obIndexer -> Type)\n          (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n        forall F : obTopos,\n        forall (v_ : forall (A : obIndexer), func0 A -> 'Topos(0 (View0 A) ~> F )0 %sol),\n          Topos00_domMetaFunctor ([[ v_ @ func1 ]] %sol).\n\n    Lemma Topos00_domMetaFunctorP : forall F1 F2 ( f : 'Topos(0 F1 ~> F2 )0 %sol ),\n           match F1 as o return (forall F2 : obTopos, ('Topos(0 o ~> F2 )0)%sol -> Type) with\n           | View0 A => fun _ _  => unit\n           | @MetaFunctor func0 func1 =>\n             fun F2 : obTopos => [eta Topos00_domMetaFunctor (F2:=F2)]\n           end F2 f.\n    Proof.\n      intros. case: F1 F2 / f.\n      - destruct F.  exact: tt. constructor 1.\n      - intros. exact: tt.\n      - intros. exact: tt.\n      - intros. exact: tt.\n      - constructor 2.\n    Defined.\n\n  End Destruct_domMetaFunctor.\n\nEnd Sol.\n\nModule isSol.\n\n  Inductive isSol : forall (F1 F2 : obTopos),\n    'Topos(0 F1 ~> F2 )0 -> Prop :=\n\n  | UnitTopos : forall {F : obTopos}, isSol (@uTopos F)\n\n  | View1 : forall (A A' : obIndexer), forall (a : 'Indexer(0 A ~> A' )0),\n        isSol (METAFUNCTORS.View1 a)\n\n  | PolyMetaFunctor :\n      forall (func0 : obIndexer -> Type)\n        (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n      forall (A : obIndexer), forall (x : func0 A), isSol (METAFUNCTORS.PolyMetaFunctor func1 x)\n\n  | PolyMetaTransf :\n      forall (func0 : obIndexer -> Type)\n        (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n      forall (func'0 : obIndexer -> Type)\n        (func'1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func'0 A' -> func'0 A),\n      forall (transf : forall (A : obIndexer), func0 A -> func'0 A),\n      forall (A : obIndexer), forall (f : 'Topos(0 (View0 A) ~> (MetaFunctor func1) )0),\n          isSol f -> isSol (f o>Topos_transf : 'Topos(0 (View0 A) ~> (MetaFunctor func'1) )0 )\n\n  | CoLimitator :\n      forall (func0 : obIndexer -> Type)\n        (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n      forall F : obTopos,\n      forall (v_ : forall (A : obIndexer), func0 A -> 'Topos(0 (View0 A) ~> F )0),\n        (* cocone func1 v_ ->    cocone erased *)\n        (forall A x, isSol (v_ A x)) -> isSol ([[v_ @ func1 ]]).\n\n  Definition regularCardinalAll : forall (obIndexer : Type) (func0 : obIndexer -> Type),\n      (forall (A : obIndexer), func0 A -> bool) -> bool.\n  Admitted.\n\n  Lemma regularCardinalAllP : forall (obIndexer : Type) (func0 : obIndexer -> Type)\n                                (b_ : forall (A : obIndexer), func0 A -> bool),\n      reflect (exists A, exists x, ~~ b_ A x) (~~ regularCardinalAll b_).\n  Admitted.\n  \n  Definition isSolbb : forall (F1 F2 : obTopos), forall (f : 'Topos(0 F1 ~> F2 )0), bool.\n    move => F1 F2 f. elim: F1 F2 /f.\n    - intros. exact: true.\n    - intros. exact: false.\n    - intros. exact: true.\n    - intros. exact: true.\n    - intros. assumption.\n    - intros func0 func1 F v_ IH_v_. exact: (regularCardinalAll IH_v_). \n  Defined.\n\n  Lemma isSolbbP : forall (F1 F2 : obTopos), forall (f : 'Topos(0 F1 ~> F2 )0),\n        reflect (isSol f) (isSolbb f).\n  Admitted.\n\n  Import Sol.Ex_Notations.\n  Lemma isSolbbP2 : forall (F1 F2 : obTopos), forall (f : 'Topos(0 F1 ~> F2 )0),\n        reflect (exists fSol : 'Topos(0 F1 ~> F2 )0 %sol , Sol.toTopos fSol = f) (isSolbb f).\n  Admitted.\n\n  Lemma topos_functional_extensionality :\n    forall (func0 : obIndexer -> Type)\n      (func1 : forall A A' : obIndexer, 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A)\n      (F : obTopos)\n      (f_ g_ : forall A : obIndexer, func0 A -> ('Topos(0 View0 A ~> F )0)),\n      (forall A x, f_ A x = g_ A x ) -> f_ = g_ .\n  Admitted.\n\n  Lemma isSolbb_isSol : forall (F1 F2 : obTopos) (f : 'Topos(0 F1 ~> F2 )0),\n      isSolbb f -> ({ fSol : 'Topos(0 F1 ~> F2 )0 %sol | Sol.toTopos fSol = f}).\n  Proof.\n    move => F1 F2 f ; elim : F1 F2 / f => \n    [ F _  (* @uTopos F %sol*)\n    | //\n    | A A' a (* Sol.View1 a *)\n    | func0 func1 A x _ (* Sol.PolyMetaFunctor func1 x *)\n    | func0 func1 func'0 func'1 transf A f  (* f o>Topos_transf %sol *)\n    | func0 func1 F f_ ] (* [[ f_ @ func1 ]] %sol *).\n    - exists ((@uTopos F)%sol). reflexivity.\n    - exists ((Sol.View1 a)%sol). reflexivity.\n    - exists ((Sol.PolyMetaFunctor func1 x)%sol). reflexivity.\n    - move => H /H [fSol fSol_prop].\n      exists ((fSol o>Topos_transf)%sol). by subst.\n    - move => IH /= /regularCardinalAllP f_isSolbb.\n      have f_isSolbb' : (forall (A : obIndexer) (x : func0 A), isSolbb (f_ A x))\n        by intros; clear -f_isSolbb; apply/negPn/negP; intuition eauto.\n      set fSol_ := (fun A x => projT1(IH A x (f_isSolbb' A x))).\n      set fSol_prop := (fun A x => projT2(IH A x (f_isSolbb' A x))).\n      exists ([[ fSol_ ]] %sol). simpl; apply: congr1.\n      apply: (topos_functional_extensionality func1).\n        by move => A x; move: fSol_prop => <- .\n  Qed.\n\n  Lemma isSolbbN_isSolN : forall (F1 F2 : obTopos),\n      forall fSol : 'Topos(0 F1 ~> F2 )0 %sol, forall (f : 'Topos(0 F1 ~> F2 )0), (Sol.toTopos fSol) = f -> isSolbb f.\n  Proof.\n    move => F1 F2 fSol ; elim : F1 F2 / fSol ; try (intros; subst; reflexivity).\n    intros; subst; simpl. intuition.\n    intros; subst; simpl. apply/regularCardinalAllP.\n    move => [A [x isSolbb_v_] ]. move: isSolbb_v_. apply/negP/negPn. eapply H; reflexivity.\n  Qed.\n\n  Lemma isSolbbN_isSolN_alt : forall (F1 F2 : obTopos) (f : 'Topos(0 F1 ~> F2 )0),\n      ~~ isSolbb f ->  ~ ( exists fSol : 'Topos(0 F1 ~> F2 )0 %sol , (Sol.toTopos fSol) = f ).\n  Proof.\n    intros F1 F2 f f_isSolbbN []. move: f_isSolbbN. apply/negP/negPn. apply: isSolbbN_isSolN.\n    eauto.\n  Qed.\n\nEnd isSol.\n\n\nDefinition regularCardinalMax : forall (obIndexer : Type (* regular cardinal *))\n                                  (func0 : obIndexer -> Type (* same, regular cardinal *))\n                                  (filter : (forall (A : obIndexer), func0 A -> Prop)),\n    (forall (A : obIndexer), func0 A -> nat) -> nat.\nAdmitted.\nLemma regularCardinalMax_falsefilter : forall (obIndexer : Type) (func0 : obIndexer -> Type)\n                                         (filter : (forall (A : obIndexer), func0 A -> Prop)),\n    forall (v_ : forall (A : obIndexer), func0 A -> nat),\n      (forall A x, filter A x <-> False) ->\n      regularCardinalMax filter v_ = 0 .\nAdmitted.\nLemma regularCardinalMax_subfilter : forall (obIndexer : Type) (func0 : obIndexer -> Type)\n                                       (filter : (forall (A : obIndexer), func0 A -> Prop)),\n    forall (v_ : forall (A : obIndexer), func0 A -> nat),\n    forall (filter' : (forall (A : obIndexer), func0 A -> Prop)),\n      (forall A x, filter' A x -> filter A x) ->\n      ( regularCardinalMax filter' v_ <= regularCardinalMax filter v_ )%coq_nat.\nAdmitted.\nLemma regularCardinalMax_samefilter : forall (obIndexer : Type) (func0 : obIndexer -> Type)\n                                       (filter : (forall (A : obIndexer), func0 A -> Prop)),\n    forall (v_ : forall (A : obIndexer), func0 A -> nat),\n    forall (filter' : (forall (A : obIndexer), func0 A -> Prop)),\n      (forall A x, filter' A x <-> filter A x) ->\n      ( regularCardinalMax filter' v_ = regularCardinalMax filter v_ )%coq_nat.\nAdmitted.\nLemma regularCardinalMax_unionfilter : forall (obIndexer : Type) (func0 : obIndexer -> Type)\n                                       (filter filter' : (forall (A : obIndexer), func0 A -> Prop)),\n    forall (v_ : forall (A : obIndexer), func0 A -> nat),\n      ( regularCardinalMax (fun A x => filter A x \\/ filter' A x) v_ <= (regularCardinalMax filter v_ + regularCardinalMax filter' v_)%coq_nat )%coq_nat.\nAdmitted.\nLemma regularCardinalMax_congr : forall (obIndexer : Type) (func0 : obIndexer -> Type)\n                            (filter : (forall (A : obIndexer), func0 A -> Prop)),\n    forall (w_ v_ : forall (A : obIndexer), func0 A -> nat),\n      (forall A x, filter A x -> ( w_ A x = v_ A x )%coq_nat) ->\n      ( regularCardinalMax filter w_ = regularCardinalMax filter v_ )%coq_nat.\nAdmitted.\nLemma regularCardinalMax_monotone_ge : forall (obIndexer : Type) (func0 : obIndexer -> Type)\n                            (filter : (forall (A : obIndexer), func0 A -> Prop)),\n    forall (w_ v_ : forall (A : obIndexer), func0 A -> nat),\n      (forall A x, filter A x -> ( w_ A x <= v_ A x )%coq_nat) ->\n      ( regularCardinalMax filter w_ <= regularCardinalMax filter v_ )%coq_nat.\nAdmitted.\nLemma regularCardinalMax_monotone_gt : forall (obIndexer : Type) (func0 : obIndexer -> Type)\n                            (filter : (forall (A : obIndexer), func0 A -> Prop)),\n    forall (w_ v_ : forall (A : obIndexer), func0 A -> nat),\n      (forall A x, filter A x -> ( w_ A x < v_ A x )%coq_nat) ->\n      forall A x, filter A x -> ( w_ A x < v_ A x )%coq_nat ->\n             ( regularCardinalMax filter w_ < regularCardinalMax filter v_ )%coq_nat.\nAdmitted.\nLemma regularCardinalMax_addr_const : forall (obIndexer : Type) (func0 : obIndexer -> Type)\n                            (filter : (forall (A : obIndexer), func0 A -> Prop)),\n    forall (v_ : forall (A : obIndexer), func0 A -> nat) (n : nat),\n      regularCardinalMax filter (fun A x => (v_ A x + n)%coq_nat) = ((regularCardinalMax filter v_) + n)%coq_nat.\nAdmitted.\nLemma regularCardinalMax_addl_const : forall (obIndexer : Type) (func0 : obIndexer -> Type)\n                            (filter : (forall (A : obIndexer), func0 A -> Prop)),\n    forall (v_ : forall (A : obIndexer), func0 A -> nat) (n : nat),\n      regularCardinalMax filter (fun A x => (n + v_ A x)%coq_nat) = (n + (regularCardinalMax filter v_))%coq_nat.\nAdmitted.\nLemma regularCardinalMax_add_succ : forall (obIndexer : Type) (func0 : obIndexer -> Type)\n                            (filter : (forall (A : obIndexer), func0 A -> Prop)),\n    forall (v_ : forall (A : obIndexer), func0 A -> nat),\n      regularCardinalMax filter (fun A x => S (v_ A x)%coq_nat) = (S (regularCardinalMax filter v_))%coq_nat.\nAdmitted.\nLemma regularCardinalMax_add_le : forall (obIndexer : Type) (func0 : obIndexer -> Type)\n                       (filter : (forall (A : obIndexer), func0 A -> Prop)),\n    forall (w_ v_ : forall (A : obIndexer), func0 A -> nat),\n      (regularCardinalMax filter (fun A x => (w_ A x + v_ A x)%coq_nat) <= ((regularCardinalMax filter w_) + (regularCardinalMax filter v_))%coq_nat)%coq_nat.\nAdmitted.\nLemma regularCardinalMax_ge : forall (obIndexer : Type) (func0 : obIndexer -> Type)\n                   (filter : (forall (A : obIndexer), func0 A -> Prop)),\n    forall (v_ : forall (A : obIndexer), func0 A -> nat) A (x : func0 A),\n      filter A x -> ( (v_ A x) <= (regularCardinalMax filter v_) )%coq_nat .\nAdmitted.\nLemma regularCardinalMax_transf : forall (obIndexer : Type) (func0 : obIndexer -> Type)\n                       (filter : (forall (A : obIndexer), func0 A -> Prop)),\n    forall (v_ : forall (A : obIndexer), func0 A -> nat),\n    forall (func'0 : obIndexer -> Type) (transf : forall (A : obIndexer), func'0 A -> func0 A),\n      ( regularCardinalMax (fun A => filter A \\o transf A) (fun A => v_ A \\o transf A) <= regularCardinalMax filter v_ )%coq_nat .\nAdmitted.\n  \nFixpoint grade (F1 F2 : obTopos) (f : 'Topos(0 F1 ~> F2 )0) {struct f} : nat\nwith gradeMaxCom (F1 F2 : obTopos) (f : 'Topos(0 F1 ~> F2 )0) {struct f} : nat\nwith gradeTotal (F1 F2 : obTopos) (f : 'Topos(0 F1 ~> F2 )0) {struct f} : nat.\nProof. (* non-really mutual at the end *)\n  case : F1 F2 / f.\n  - intros F.\n    exact (S O). (* UnitTopos *)\n  - intros F2 F1 f_ F1' f'.\n    refine ((S  (S (grade _ _ f_ + grade _ _ f')%coq_nat)) (* +\n            (S  (S (gradeMaxCom _ _ f_ + (gradeMaxCom _ _ f' (* + (S (S (grade _ _ f_ + grade _ _ f')%coq_nat)) *))%coq_nat)%coq_nat)) *))%coq_nat. (* PolyTopos *)\n  - intros A A' a.\n    exact (S (S O)). (* View1 *)\n  - intros func0 func1 A x.\n    exact (S (S O)). (* PolyMetaFunctor *)\n  - intros func0 func1 func'0 func'1 transf A f.\n    refine ((S (S (grade _ _ f))) (* + (gradeMaxCom _ _ f) *))%coq_nat. (* PolyMetaTransf *)\n  - intros func0 func1 F f_.\n    refine (S (S ((regularCardinalMax (fun A x => ~~ isSol.isSolbb (f_ A x)) (fun A x => (  grade _ _ (f_ A x) (* +  gradeMaxCom _ _ (f_ A x) *) )%coq_nat)) +\n                  (regularCardinalMax (fun A x => isSol.isSolbb (f_ A x)) (fun A x => (  grade _ _ (f_ A x) (* +  gradeMaxCom _ _ (f_ A x) *) )%coq_nat)))%coq_nat )). (* CoLimitator *)\nProof.\n  case : F1 F2 / f.\n  - intros F.\n    exact (O). (* UnitTopos *)\n  - intros F2 F1 f_ F1' f'.\n    refine (  ( (gradeMaxCom _ _ f_ + (gradeMaxCom _ _ f' + (S (S (grade _ _ f_ + grade _ _ f')%coq_nat)))%coq_nat)%coq_nat)). (* PolyTopos *)\n  - intros A A' a.\n    exact (O). (* View1 *)\n  - intros func0 func1 A x.\n    exact (O). (* PolyMetaFunctor *)\n  - intros func0 func1 func'0 func'1 transf A f.\n    refine (gradeMaxCom _ _ f). (* PolyMetaTransf *)\n  - intros func0 func1 F f_.\n    refine ( ( ((regularCardinalMax (fun A x => ~~ isSol.isSolbb (f_ A x)) (fun A x => ( (* grade _ _ (f_ A x) + *) gradeMaxCom _ _ (f_ A x))%coq_nat)) +\n             (regularCardinalMax (fun A x => isSol.isSolbb (f_ A x)) (fun A x => ( (* grade _ _ (f_ A x) + *) gradeMaxCom _ _ (f_ A x))%coq_nat)))%coq_nat)). (* CoLimitator *)\nProof.\n  case : F1 F2 / f.\n  - intros F.\n    exact ((S O))%coq_nat. (* UnitTopos *)\n  - intros F2 F1 f_ F1' f'.\n    refine ((S  (S (gradeTotal _ _ f_ + gradeTotal _ _ f')%coq_nat)) +\n            (  ( ((*gradeMaxCom _ _ f_ +*) ((*gradeMaxCom _ _ f' + *) (S (S (grade _ _ f_ + grade _ _ f')%coq_nat)) )%coq_nat)%coq_nat)) )%coq_nat. (* PolyTopos *)\n  - intros A A' a.\n    exact (S (S O)). (* View1 *)\n  - intros func0 func1 A x.\n    exact (S (S O)). (* PolyMetaFunctor *)\n  - intros func0 func1 func'0 func'1 transf A f.\n    refine ((S (S (gradeTotal _ _ f)))  (* + (gradeMaxCom _ _ f)*) )%coq_nat. (* PolyMetaTransf *)\n  - intros func0 func1 F f_.\n    refine (S (S ((regularCardinalMax (fun A x => ~~ isSol.isSolbb (f_ A x)) (fun A x => (  gradeTotal _ _ (f_ A x) )%coq_nat)) +\n                 (regularCardinalMax (fun A x => isSol.isSolbb (f_ A x)) (fun A x => (  gradeTotal _ _ (f_ A x) )%coq_nat)) )%coq_nat)). (* CoLimitator *)\nDefined.\n\n(**TODO : make func'1 of PolyMetaTransf maximally implicit *)\nModule Red.\n\n  Import Sol.Ex_Notations.\n  Reserved Notation \"f2 <~~ f1\" (at level 70).\n\n  Inductive convTopos : forall (F1 F2 : obTopos),\n      'Topos(0 F1 ~> F2 )0 -> 'Topos(0 F1 ~> F2 )0 -> Prop :=\n\n  (* equivalence *)\n        \n  | Topos_Trans : forall (F1 F2 : obTopos) (uTrans f : 'Topos(0 F1 ~> F2 )0),\n      uTrans <~~ f -> forall (f0 : 'Topos(0 F1 ~> F2 )0),\n        f0 <~~ uTrans -> f0 <~~ f\n                         \n  (* congruences *)\n                  \n  | PolyTopos_cong_Pre :\n      forall (F F' : obTopos) (f_ f_0 : 'Topos(0 F ~> F' )0),\n      forall (F'' : obTopos) (f' : 'Topos(0 F' ~> F'' )0),\n        f_0 <~~ f_ -> ( f_0 o>Topos f' ) <~~ ( f_ o>Topos f' )\n\n  | PolyTopos_cong_Post :\n      forall (F F' : obTopos) (f_ : 'Topos(0 F ~> F' )0),\n      forall (F'' : obTopos) (f' f'0 : 'Topos(0 F' ~> F'' )0),\n        f'0 <~~ f' -> ( f_ o>Topos f'0 ) <~~ ( f_ o>Topos f' )\n\n  | PolyMetaTransf_cong :\n      forall (func0 : obIndexer -> Type)\n        (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n      forall (func'0 : obIndexer -> Type)\n        (func'1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func'0 A' -> func'0 A),\n      forall (transf : forall (A : obIndexer), func0 A -> func'0 A),\n      forall (A : obIndexer) (v v0 : 'Topos(0 (View0 A) ~> (MetaFunctor func1) )0),\n        (* none lack to hold changes to transf because no such changes and uniform *)\n        v0 <~~ v -> v0 o>Topos_transf <~~ ( v o>Topos_transf\n                                        : 'Topos(0 (View0 A) ~> (MetaFunctor func'1) )0 )\n\n  | CoLimitator_cong :\n      forall (func0 : obIndexer -> Type)\n        (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n      forall F : obTopos,\n      forall (v_ v_0 : forall (A : obIndexer), func0 A -> 'Topos(0 (View0 A) ~> F )0),\n        (* cocone func1 f_ ->    cocone erased *)\n        (forall (A : obIndexer) (x : func0 A), ~~ isSol.isSolbb (v_ A x) -> v_0 A x <~~ v_ A x) ->\n        (forall (A : obIndexer) (x : func0 A), isSol.isSolbb (v_ A x) -> v_0 A x = v_ A x) ->\n        (forall (A : obIndexer) (x : func0 A), isSol.isSolbb (v_0 A x)) ->\n        forall (A : obIndexer) (x : func0 A), ~~ isSol.isSolbb (v_ A x) ->\n        [[ v_0 @ func1 ]] <~~ ( [[ v_ @ func1 ]]\n                              : 'Topos(0 MetaFunctor func1 ~> F )0 )\n\n  (* units *)\n\n  | Topos_unit :\n      forall (F F' : obTopos) (f : 'Topos(0 F ~> F' )0),\n        ( f )\n          <~~ ( ( uTopos ) o>Topos f\n              : 'Topos(0 F ~> F' )0 )\n\n  | Topos_inputUnitTopos :\n      forall (G F : obTopos) (g : 'Topos(0 G ~> F )0),\n        ( g )\n          <~~  ( g o>Topos ( uTopos )\n               : 'Topos(0 G ~> F )0 )\n\n  (* polymorphism *)\n\n  | View_polyIndexer : forall (A A' : obIndexer) (a : 'Indexer(0 A ~> A' )0)\n                         (A'' : obIndexer) (a' : 'Indexer(0 A' ~> A'' )0),\n      (View1 (a o>Indexer a'))\n        <~~ ( (View1 a) o>Topos (View1 a')\n            : 'Topos(0 View0 A ~> View0 A'' )0 )\n\n  (* functoriality-polymorphism follows from this _cocone property and\nassociativity-polymorphism of PolyTopos and functoriality-polymorphism\nof View1 *)\n  | PolyMetaFunctor_cocone :\n      forall (func0 : obIndexer -> Type)\n        (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n      forall (A : obIndexer) (x : func0 A) (A' : obIndexer) (a : 'Indexer(0 A' ~> A )0),\n        ( PolyMetaFunctor func1 (func1 _ _ a x) )\n          <~~ ( (View1 a) o>Topos (PolyMetaFunctor func1 x)\n              : 'Topos(0 View0 A' ~> MetaFunctor func1 )0 )\n\n  (* naturality-polymorphism is this, which is in operational form *)\n  | PolyMetaTransf_poly :\n      forall (func0 : obIndexer -> Type)\n        (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n      forall (func'0 : obIndexer -> Type)\n        (func'1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func'0 A' -> func'0 A)\n        (transf : forall A : obIndexer, func0 A -> func'0 A),\n      forall (A : obIndexer) (v : 'Topos(0 (View0 A) ~> (MetaFunctor func1) )0)\n        (A' : obIndexer) (a : 'Indexer(0 A' ~> A )0),\n        ( ((View1 a) o>Topos v) o>Topos_transf )\n          <~~ ( (View1 a) o>Topos (v o>Topos_transf)\n              : 'Topos(0 View0 A' ~> MetaFunctor func'1 )0 )\n\n  (* naturality-polymorphism of the bijection*)\n  | CoLimitator_morphism :\n      forall (func0 : obIndexer -> Type)\n        (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n      forall (F : obTopos) (v_ : forall (A : obIndexer), func0 A -> 'Topos(0 (View0 A) ~> F )0),\n      forall (F' : obTopos) (f : 'Topos(0 F ~> F' )0),\n        ( [[ (fun A x => (v_ A x) o>Topos f) @ func1 ]] )\n          <~~ ( [[ v_ @ func1 ]] o>Topos f\n              : 'Topos(0 MetaFunctor func1 ~> F' )0 )\n\n  | PolyMetaFunctor_CoLimitator :\n      forall (func0 : obIndexer -> Type)\n        (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n      forall F : obTopos,\n      forall (v_ : forall (A : obIndexer), func0 A -> 'Topos(0 (View0 A) ~> F )0),\n      forall (A : obIndexer) (x : func0 A),\n        ( v_ A x )\n          <~~ ( (PolyMetaFunctor func1 x) o>Topos [[ v_ @ func1 ]]\n              : 'Topos(0 View0 A ~> F )0 )\n\n  | PolyMetaTransf_CoLimitator :\n      forall (func'0 : obIndexer -> Type)\n        (func'1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func'0 A' -> func'0 A),\n      forall F : obTopos,\n      forall (v_ : forall (A : obIndexer), func'0 A -> 'Topos(0 (View0 A) ~> F )0),\n      forall (func0 : obIndexer -> Type)\n        (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n      forall (transf : forall (A : obIndexer), func0 A -> func'0 A)\n        (A : obIndexer) (w : 'Topos(0 (View0 A) ~> (MetaFunctor func1) )0),\n        (w o>Topos [[ (fun A0 => (v_ A0) \\o (transf A0)) @ func1 ]])\n          <~~ (w o>Topos_transf) o>Topos [[ v_ @ func'1 ]]\n(*\n  (* for sense only, non-necessary for reduction *)\n  | CoLimitator_PolyMetaFunctor :\n      forall (func0 : obIndexer -> Type)\n        (func1 : forall (A A' : obIndexer), 'Indexer(0 A ~> A' )0 -> func0 A' -> func0 A),\n        ( @UnitTopos (MetaFunctor func1) )\n          <~~ ( [[ PolyMetaFunctor func1 ]]\n              : 'Topos(0 (MetaFunctor func1) ~> (MetaFunctor func1) )0 ) *)\n          \n  where \"f2 <~~ f1\" := (@convTopos _ _ f2 f1).\n\n  Module Export Ex_Notations.\n\n    Notation \"f2 <~~ f1\" := (@convTopos _ _ f2 f1).\n    Hint Constructors convTopos.\n\n    (* help PolyMetaFunctor_CoLimitator to decompose \n       the double-applications in (v_ A x) *)\n    Hint Extern 0 (_ <~~ _) =>\n    ( apply: Red.PolyMetaFunctor_CoLimitator ) .\n\n  End Ex_Notations.\n  \n  Lemma Red_convTopos_convTopos :\n  forall (F1 F2 : obTopos) (fDeg f : 'Topos(0 F1 ~> F2 )0),\n    fDeg <~~ f -> fDeg ~~~ f.\n  Proof.\n    move => F1 F2 f fDeg. elim; rewriterTopos; try eauto.\n    intros.\n    apply: METAFUNCTORS.CoLimitator_cong. intros. \n  Admitted.\n\n  Lemma degrade :\n    forall (F1 F2 : obTopos) (fDeg f : 'Topos(0 F1 ~> F2 )0),\n      fDeg <~~ f ->  ((grade fDeg) <= (grade f))%coq_nat\n                  (* /\\  ((gradeMaxCom fDeg) <= (gradeMaxCom f))%coq_nat*)\n                 /\\ ((gradeTotal fDeg) < (gradeTotal f))%coq_nat.\n  Proof.\n    move => F1 F2 fDeg f red_f; elim : F1 F2 fDeg f / red_f;\n             try solve [ rewrite (* /gradeTotal *)  /= => * ;\n                                                    abstract intuition Omega.omega ].\n    - (* CoLimitator_cong *)\n      move => func0 func1 F v_ v_0 red_v_ IH_red_v iden_v_ sol_v0 A x red_v_A_x.\n\n      move: (IH_red_v _ _ red_v_A_x) => IH_red_v_A_x.\n\n      move: (fun A x p => congr1 (@grade _ _) (iden_v_ A x p)).\n      move => /(@regularCardinalMax_congr _ _ (fun A x => isSol.isSolbb (v_ A x)) (fun A x => grade (v_0 A x)) (fun A x => grade (v_ A x))).\n      move: (fun A x p => congr1 (@gradeTotal _ _) (iden_v_ A x p)).\n      move => /(@regularCardinalMax_congr _ _ (fun A x => isSol.isSolbb (v_ A x)) (fun A x => gradeTotal (v_0 A x)) (fun A x => gradeTotal (v_ A x))).\n\n      move: (fun A x p => proj1 (IH_red_v A x p)).\n      move => /(@regularCardinalMax_monotone_ge _ _ (fun A x => ~~ isSol.isSolbb (v_ A x)) (fun A x => grade (v_0 A x)) (fun A x => grade (v_ A x))).\n\n      move: (fun A x p => proj2 (IH_red_v A x p)).\n      move => /(@regularCardinalMax_monotone_gt _ _ (fun A x => ~~ isSol.isSolbb (v_ A x)) (fun A x => gradeTotal (v_0 A x)) (fun A x => gradeTotal (v_ A x))) /(_ _ _ red_v_A_x (proj2 IH_red_v_A_x)) .\n\n      have Hlogical : forall (A : obIndexer) (x : func0 A), ~~ isSol.isSolbb (v_0 A x) <-> False .\n      { move => A0 x0. move: (sol_v0 A0 x0) -> => //. }\n      move : (Hlogical) => /(regularCardinalMax_falsefilter (fun A x => grade (v_0 A x))).\n      move : Hlogical => /(regularCardinalMax_falsefilter (fun A x => gradeTotal (v_0 A x))).\n      \n      have Hlogical2 : forall (A : obIndexer) (x : func0 A), isSol.isSolbb (v_0 A x) <-> (~~ isSol.isSolbb (v_ A x) \\/ isSol.isSolbb (v_ A x)) .\n      { move => A0 x0. by case: ( isSol.isSolbb (v_ A0 x0)); intuition. }\n      move : (Hlogical2) => /(regularCardinalMax_samefilter (fun A x => grade (v_0 A x))).\n      move : Hlogical2 => /(regularCardinalMax_samefilter (fun A x => gradeTotal (v_0 A x))).\n\n      move: (regularCardinalMax_unionfilter (fun A x => ~~ isSol.isSolbb (v_ A x))\n                                            (fun A x => isSol.isSolbb (v_ A x))\n               (fun A x => grade (v_0 A x)) ).\n      move: (regularCardinalMax_unionfilter (fun A x => ~~ isSol.isSolbb (v_ A x))\n                                            (fun A x => isSol.isSolbb (v_ A x))\n                                            (fun A x => gradeTotal (v_0 A x)) ).\n\n      simpl; abstract intuition Omega.omega.\n      \n    - (* CoLimitator_morphism *)\n      move => func0 func1 F v_ F' f .\n\n      have Hlogical : forall (A : obIndexer) (x : func0 A), isSol.isSolbb (v_ A x o>Topos f) <-> False .\n      { move => A0 x0 //= . }\n      move : (Hlogical) => /(regularCardinalMax_falsefilter (fun A x => grade (v_ A x o>Topos f))).\n      move : Hlogical => /(regularCardinalMax_falsefilter (fun A x => gradeTotal (v_ A x o>Topos f))).\n\n      have Hlogical2 : forall (A : obIndexer) (x : func0 A), ~~ isSol.isSolbb (v_ A x o>Topos f) <-> (~~ isSol.isSolbb (v_ A x) \\/ isSol.isSolbb (v_ A x)) .\n      { move => A0 x0 /=. by case: ( isSol.isSolbb (v_ A0 x0)); intuition. }\n      move : (Hlogical2) => /(regularCardinalMax_samefilter (fun A x => grade (v_ A x o>Topos f))).\n      move : Hlogical2 => /(regularCardinalMax_samefilter (fun A x => gradeTotal (v_ A x o>Topos f))).\n\n      move: (regularCardinalMax_unionfilter (fun A x => ~~ isSol.isSolbb (v_ A x))\n                                            (fun A x => isSol.isSolbb (v_ A x))\n               (fun A x => grade (v_ A x o>Topos f)) ).\n      move: (regularCardinalMax_unionfilter (fun A x => ~~ isSol.isSolbb (v_ A x))\n                                            (fun A x => isSol.isSolbb (v_ A x))\n                                            (fun A x => gradeTotal (v_ A x o>Topos f)) ).\n      \n      rewrite /= !(regularCardinalMax_add_succ , regularCardinalMax_addl_const , regularCardinalMax_addr_const) /=.\n      move: (regularCardinalMax_add_le (fun A x => ~~ isSol.isSolbb (v_ A x)) (fun (A : obIndexer) (x : func0 A) => (gradeTotal (v_ A x) + gradeTotal f)%coq_nat)\n                          (fun (A : obIndexer) (x : func0 A) => (grade (v_ A x) + grade f)%coq_nat.+2) ).\n      move: (regularCardinalMax_add_le (fun A x => isSol.isSolbb (v_ A x)) (fun (A : obIndexer) (x : func0 A) => (gradeTotal (v_ A x) + gradeTotal f)%coq_nat)\n                          (fun (A : obIndexer) (x : func0 A) => (grade (v_ A x) + grade f)%coq_nat.+2) ).\n      rewrite /= !(regularCardinalMax_add_succ , regularCardinalMax_addl_const , regularCardinalMax_addr_const) /=.\n      simpl; abstract intuition Omega.omega. (* YES /!\\ ONCE *)\n    - (* PolyMetaFunctor_CoLimitator *)\n      move => func0 func1 F v_ A x .\n\n      move: (regularCardinalMax_unionfilter (fun A x => ~~ isSol.isSolbb (v_ A x))\n                                            (fun A x => isSol.isSolbb (v_ A x))\n               (fun A x => grade (v_ A x)) ).\n      move: (regularCardinalMax_unionfilter (fun A x => ~~ isSol.isSolbb (v_ A x))\n                                            (fun A x => isSol.isSolbb (v_ A x))\n                                            (fun A x => gradeTotal (v_ A x)) ).\n\n      have Hlogical: (~~ isSol.isSolbb (v_ A x) \\/ isSol.isSolbb (v_ A x)).\n      { by case: ( isSol.isSolbb (v_ A x)); intuition. }\n      move: (Hlogical) => /(@regularCardinalMax_ge _ _ (fun A x => ~~ isSol.isSolbb (v_ A x) \\/ isSol.isSolbb (v_ A x))\n                                                 (fun (A0 : obIndexer) (x0 : func0 A0) => grade (v_ A0 x0)) ).\n      move: Hlogical => /(@regularCardinalMax_ge _ _ (fun A x => ~~ isSol.isSolbb (v_ A x) \\/ isSol.isSolbb (v_ A x))\n                                              (fun (A0 : obIndexer) (x0 : func0 A0) => gradeTotal (v_ A0 x0)) ).\n      simpl; abstract intuition Omega.omega.\n    - (* PolyMetaTransf_CoLimitator *)\n      move => func'0 func'1 F v_ func0 func1 transf A w /=.  \n      move: (regularCardinalMax_transf (fun A0 x => ~~ isSol.isSolbb (v_ A0 x)) (fun A0 x => grade (v_ A0 x)) transf)\n              (regularCardinalMax_transf (fun A0 x => isSol.isSolbb (v_ A0 x)) (fun A0 x => grade (v_ A0 x)) transf)\n              (regularCardinalMax_transf (fun A0 x => ~~ isSol.isSolbb (v_ A0 x)) (fun A0 x => gradeTotal (v_ A0 x)) transf)\n              (regularCardinalMax_transf (fun A0 x => isSol.isSolbb (v_ A0 x)) (fun A0 x => gradeTotal (v_ A0 x)) transf).\n      rewrite /funcomp => /= . abstract intuition Omega.omega.\nDefined.\n\n  Lemma degradeTotal :\n    forall (F1 F2 : obTopos) (fDeg f : 'Topos(0 F1 ~> F2 )0),\n      fDeg <~~ f ->  ((gradeTotal fDeg) < (gradeTotal f))%coq_nat.\n  Proof.\n    eapply degrade.\n  Qed.\n\n  Lemma degrade_gt0 :\n    forall (F1 F2 : obTopos) (f : 'Topos(0 F1 ~> F2 )0),\n      ((S O) <= (grade f))%coq_nat.\n  Proof.\n    move=> F1 F2 f; apply/leP; case : f; simpl; auto. (* alt: Omega.omega. *)\n  Qed.\n\n  Lemma degradeTotal_gt0 :\n    forall (F1 F2 : obTopos) (f : 'Topos(0 F1 ~> F2 )0),\n      ((S O) <= (gradeTotal f))%coq_nat.\n  Proof.\n    move=> F1 F2 f; case : f => /= * ; Omega.omega.\n  Qed.\n\n  Lemma isSolbb_isRed_False_alt : forall (F1 F2 : obTopos) (f : 'Topos(0 F1 ~> F2 )0),\n      forall fRed, fRed <~~ f ->\n              isSol.isSolbb f -> False.\n  Proof.\n    induction 1; move => //= .\n    move/isSol.regularCardinalAllP. move => J. apply: J. exists A , x. assumption.\n  Qed.\n  \n  Lemma isSolbb_isRed_False : forall (F1 F2 : obTopos) (f : 'Topos(0 F1 ~> F2 )0),\n      forall fSol : 'Topos(0 F1 ~> F2 )0 %sol,  Sol.toTopos fSol = f ->\n                                           forall fRed, fRed <~~ f -> False.\n    intros ? ? ? ? ? ? Hred. apply: (isSolbb_isRed_False_alt Hred).\n    apply: isSol.isSolbbN_isSolN. eassumption.\n  Qed.\n\nEnd Red.\n\n\nSection Section1.\n\n  Import Sol.Ex_Notations.\n  Import Red.Ex_Notations.\n\n  Ltac rewriterTopos := repeat match goal with | [ HH : @eq (Topos00 _ _) _ _  |- _ ] =>  try rewrite -> HH in *; clear HH end. \n  \n  Ltac tac_reduce :=\n    simpl in *; abstract (\n                    intuition (eauto; try subst; rewriterTopos; try congruence;\n                               eauto 12)).\n\n  Ltac tac_degrade H_gradeTotal a_Sol_prop a'Sol_prop :=\n    destruct a_Sol_prop as [a_Sol_prop |a_Sol_prop];\n    [ move : (Red.degrade a_Sol_prop);\n      destruct a'Sol_prop as [a'Sol_prop |a'Sol_prop];\n      [ move : (Red.degrade a'Sol_prop)\n      | subst ]\n    | subst;\n      destruct a'Sol_prop as [a'Sol_prop |a'Sol_prop];\n      [ move : (Red.degrade a'Sol_prop)\n      | subst ]\n    ];\n    move : H_gradeTotal; clear; rewrite /= ;\n    move => * ; abstract intuition Omega.omega.\n\n  Ltac tac_degrade_union v_ A x :=\n    move: (regularCardinalMax_unionfilter\n             (fun A x => ~~ isSol.isSolbb (v_ A x))\n             (fun A x => isSol.isSolbb (v_ A x))\n             (fun A x => grade (v_ A x)));\n    move: (regularCardinalMax_unionfilter\n             (fun A x => ~~ isSol.isSolbb (v_ A x))\n             (fun A x => isSol.isSolbb (v_ A x))\n             (fun A x => gradeTotal (v_ A x)));\n    (have: (~~ isSol.isSolbb (v_ A x) \\/ isSol.isSolbb (v_ A x))\n      by (case: (isSol.isSolbb (v_ A x)); intuition)); intros Hlogical;\n    move: (Hlogical) =>\n    /(@regularCardinalMax_ge\n        _ _ (fun A x => ~~ isSol.isSolbb (v_ A x) \\/ isSol.isSolbb (v_ A x))\n        (fun (A0 : obIndexer) (x0 : func0 A0) => grade (v_ A0 x0)) );\n    move: Hlogical =>\n    /(@regularCardinalMax_ge\n        _ _ (fun A x => ~~ isSol.isSolbb (v_ A x) \\/ isSol.isSolbb (v_ A x))\n        (fun (A0 : obIndexer) (x0 : func0 A0) => gradeTotal (v_ A0 x0)) ).\n\n  Ltac tac_degrade_transf v_ transf :=\n    move: (regularCardinalMax_transf\n             (fun A0 x => ~~ isSol.isSolbb (v_ A0 x))\n             (fun A0 x => grade (v_ A0 x)) transf)\n            (regularCardinalMax_transf\n               (fun A0 x => isSol.isSolbb (v_ A0 x))\n               (fun A0 x => grade (v_ A0 x)) transf)\n            (regularCardinalMax_transf\n               (fun A0 x => ~~ isSol.isSolbb (v_ A0 x))\n               (fun A0 x => gradeTotal (v_ A0 x)) transf)\n            (regularCardinalMax_transf\n               (fun A0 x => isSol.isSolbb (v_ A0 x))\n               (fun A0 x => gradeTotal (v_ A0 x)) transf);\n    rewrite !/funcomp.\n\n  Fixpoint solveTopos len {struct len} :\n    forall (F1 F2 : obTopos) (f : 'Topos(0 F1 ~> F2 )0)\n      (H_gradeTotal : (gradeTotal f <= len)%coq_nat),\n      { fSol : 'Topos(0 F1 ~> F2 )0 %sol\n      & {( (Sol.toTopos fSol) <~~ f )} + {( (Sol.toTopos fSol) = f )} }.\n  Proof.\n    case : len => [ | len ].\n\n    (* n is O *)\n    - clear; ( move => F1 F2 f H_gradeTotal ); exfalso;\n        move : (Red.degradeTotal_gt0 f) => H_degradeTotal_gt0; abstract Omega.omega.\n\n    (* n is (S n) *)\n    - move => F1 F2 f; case : F1 F2 / f =>\n      [ F  (* @uTopos F *)\n      | F1 F2 f_ F1' f' (* f_ o>Topos f' *)\n      | A A' a (* View1 a *)\n      | func0 func1 A x (* PolyMetaFunctor func1 x *)\n      | func0 func1 func'0 func'1 transf A f (* f o>Topos_transf *)\n      | func0 func1 F v_ ] (* [[ v_ @ func1 ]] *).\n\n      (* f is @uTopos F *)\n      + move => H_gradeTotal. exists (@uTopos F)%sol. right. reflexivity.\n\n      (* f id f_ o>Topos f' *)\n      + all: cycle 1. \n        \n      (* f is View1 a *)\n      + move => H_gradeTotal. exists (Sol.View1 a). right. reflexivity.\n      \n      (* f is PolyMetaFunctor func1 x *)\n      + move => H_gradeTotal. exists (Sol.PolyMetaFunctor func1 x). right. reflexivity.\n\n      (* f is f o>Topos_transf *)\n      + move => H_gradeTotal.\n        case : (solveTopos len _ _ f) =>\n        [ | fSol fSol_prop ].\n        * move : H_gradeTotal; clear;\n            rewrite /gradeTotal /=; move => *; abstract Omega.omega.\n        * exists (fSol o>Topos_transf)%sol.\n          clear -fSol_prop. tac_reduce.\n\n      (* f is [[ v_ @ func1 ]] *)\n      + move => H_gradeTotal.\n        have gradeTotal_v_ : forall A x , (gradeTotal (v_ A x) <= len)%coq_nat.\n        { move => A x.\n          clear -H_gradeTotal.\n          tac_degrade_union v_ A x.\n          move: H_gradeTotal; clear; simpl;\n            abstract intuition Omega.omega.\n        }\n        \n        set solveTopos_v_ := (fun A x => solveTopos len (View0 A) F (v_ A x) (gradeTotal_v_ A x)).\n        set vSol_ := (fun A x => projT1 (solveTopos_v_ A x)).\n        set vSol_prop_ := (fun A x => projT2 (solveTopos_v_ A x)).\n        set vSol_propb_ := (fun A x => ~~ ((projT2 (solveTopos_v_ A x)) : bool)).\n\n        case: (isSol.regularCardinalAllP (fun A x => isSol.isSolbb (v_ A x))) => H_someRed.\n        * have vSol_prop_isRed_: forall (A : obIndexer) (x : func0 A),\n            ~~ isSol.isSolbb (v_ A x) ->\n            Sol.toTopos (vSol_ A x) <~~ v_ A x .\n          { clear - vSol_prop_. intros A x.\n            (case: (vSol_prop_ A x) => //= ) ;\n              ( case (isSol.isSolbbP2 (v_ A x)) => //= ).\n            move: (solveTopos_v_ A x) vSol_. clear. intros; exfalso.\n            intuition eauto.\n          }\n\n          have vSol_prop_isSol_: forall (A : obIndexer) (x : func0 A),\n              isSol.isSolbb (v_ A x) ->\n              Sol.toTopos (vSol_ A x) = v_ A x .\n          { clear - vSol_prop_. intros A x. (case: (vSol_prop_ A x) => //= ) .\n            ( case (isSol.isSolbbP2 (v_ A x)) => //= ).\n            intros [v_A_x_Sol v_A_x_Sol_prop] v_A_x_Red; exfalso;\n            apply: Red.isSolbb_isRed_False; eassumption.\n          }\n\n          exists [[ fun A x => (vSol_ A x) ]]%sol. left.\n          clear - H_someRed vSol_prop_isRed_ vSol_prop_isSol_ .\n          simpl. move: H_someRed  => [A [x H_someRed_prop] ].\n          apply: Red.CoLimitator_cong; [assumption | assumption | | eassumption].\n          intros; apply/(introT (isSol.isSolbbP2 (_))); eexists; reflexivity.\n\n        * (* have v_A_x_allSol' : (forall (A : obIndexer) (x : func0 A), isSol.isSolbb (v_ A x)).\n          { intros. case E : (isSol.isSolbb _) => //=. exfalso; apply: H_someRed.\n            exists A , x . by move: E => -> . } *)\n\n          have v_A_x_allSol : forall A x,  ({ fSol  | Sol.toTopos fSol = v_ A x}).\n          { intros. apply: isSol.isSolbb_isSol.\n            case E : (isSol.isSolbb _) => //=. exfalso; apply: H_someRed.\n            exists A , x . by move: E => -> . }\n\n          set v_A_x_allSol_data := (fun A x => projT1 (v_A_x_allSol A x)).\n          set v_A_x_allSol_prop := (fun A x => projT2 (v_A_x_allSol A x)).\n\n          exists [[ fun A x => (v_A_x_allSol_data A x) ]]%sol. right.\n          simpl. simpl in v_A_x_allSol_prop.\n          About congr1. apply: congr1.\n          Require FunctionalExtensionality.\n          apply: Coq.Logic.FunctionalExtensionality.functional_extensionality_dep.\n          intros A. apply: Coq.Logic.FunctionalExtensionality.functional_extensionality.\n          intros x. apply: v_A_x_allSol_prop.\n\n          (** TODO ADD functional extensionality for indexer obIndexer and elements of functors **)\n\n\n    - (* f is f_ o>Topos f' *)\n      move => H_gradeTotal.\n      case : (solveTopos len _ _ f_) =>\n        [ | f_Sol f_Sol_prop ];\n          [ move : H_gradeTotal; clear;\n            rewrite /gradeTotal /=; move => *; abstract Omega.omega | ].\n        case : (solveTopos len _ _ f') =>\n        [ | f'Sol f'Sol_prop ];\n          [ move : H_gradeTotal; clear;\n            rewrite /gradeTotal /=; move => *; abstract Omega.omega | ].\n\n        (* f is (f_ o>Mod f') , to (f_Sol o>Mod f'Sol) *)\n        destruct f_Sol as\n            [ F  (* @uTopos F %sol*)\n            | A A' f_a (* Sol.View1 f_a *)\n            | func0 func1 A x (* Sol.PolyMetaFunctor func1 x *)\n            | func0 func1 func'0 func'1 transf A f_Sol' (* f_Sol' o>Topos_transf %sol *)\n            | func0 func1 F f_Sol_ ] (* [[ f_Sol_ @ func1 ]] %sol *).\n\n\n      (* f is (f_ o>Topos f') , to (f_Sol o>Topos f'Sol)  , is ((@uTopos F) o>Topos f'Sol) *)\n      + case : (solveTopos len _ _ ((Sol.toTopos f'Sol))) =>\n        [ | f_Sol_o_f'Sol f_Sol_o_f'Sol_prop ].\n        * tac_degrade H_gradeTotal f_Sol_prop f'Sol_prop.\n        * exists (f_Sol_o_f'Sol).\n          clear -f_Sol_prop f'Sol_prop f_Sol_o_f'Sol_prop. tac_reduce.\n\n      (* f is (f_ o>Topos f') , to (f_Sol o>Topos f'Sol)  , is (View1 f_a o>Topos f'Sol) *)\n      + clear - solveTopos H_gradeTotal f_Sol_prop f'Sol_prop.\n        move: (Sol.Destruct_domView.Topos00_domViewP f'Sol) => f'Sol_domViewP.\n        destruct f'Sol_domViewP as\n            [ _A  (* @uTopos F %sol*)\n            | _A A' f'a (* Sol.View1 f'a *)\n            | func0 func1 _A x (* Sol.PolyMetaFunctor func1 x *)\n            | func0 func1 func'0 func'1 transf _A f'Sol' ] (* f'Sol' o>Topos_transf %sol *).\n\n        (* f is (f_ o>Topos f') , to (f_Sol o>Topos f'Sol)  , is (View1 f_a o>Topos f'Sol) , is  (View1 f_a o>Topos (@uTopos _A)) *)\n        * exists ( (Sol.View1 f_a)%sol ) .\n          clear -f_Sol_prop f'Sol_prop. tac_reduce.\n\n        (* f is (f_ o>Topos f') , to (f_Sol o>Topos f'Sol)  , is (View1 f_a o>Topos f'Sol) , is  (View1 f_a o>Topos View1 f'a) *)            \n        * exists (Sol.View1 (f_a o>Indexer f'a)%sol).\n          clear -f_Sol_prop f'Sol_prop. tac_reduce.\n\n        (* f is (f_ o>Topos f') , to (f_Sol o>Topos f'Sol)  , is (View1 f_a o>Topos f'Sol) , is  (View1 f_a o>Topos Sol.PolyMetaFunctor func1 x) *)\n        * exists (Sol.PolyMetaFunctor func1 (func1 _ _ f_a x)%sol).\n          clear -f_Sol_prop f'Sol_prop. tac_reduce.\n\n        (* f is (f_ o>Topos f') , to (f_Sol o>Topos f'Sol)  , is (View1 f_a o>Topos f'Sol) , is  (View1 f_a o>Topos (f'Sol' o>Topos_transf) *)\n        * { case : (solveTopos len _ _ ((Sol.toTopos (Sol.View1 f_a) o>Topos (Sol.toTopos f'Sol')))) =>\n            [ | f_Sol_o_f'Sol f_Sol_o_f'Sol_prop ].\n            - tac_degrade H_gradeTotal f_Sol_prop f'Sol_prop.\n            - exists (f_Sol_o_f'Sol o>Topos_transf)%sol.\n              clear -f_Sol_prop f'Sol_prop f_Sol_o_f'Sol_prop. tac_reduce.\n              (*OLD [ | f_Sol_o_f'Sol' f_Sol_o_f'Sol'_prop ].\n            - tac_degrade H_gradeTotal f_Sol_prop f'Sol_prop.\n            - exists (f_Sol_o_f'Sol' o>Topos_transf)%sol.\n              clear -f_Sol_prop f'Sol_prop f_Sol_o_f'Sol'_prop. tac_reduce.*)\n          }\n\n      (* f is (f_ o>Topos f') , to (f_Sol o>Topos f'Sol)  , is (Sol.PolyMetaFunctor func1 x o>Topos f'Sol) *)\n      + clear - solveTopos H_gradeTotal f_Sol_prop f'Sol_prop.\n        move: (Sol.Destruct_domMetaFunctor.Topos00_domMetaFunctorP f'Sol) => f'Sol_domMetaFunctorP.\n        destruct f'Sol_domMetaFunctorP as\n            [ func0 func1  (* @uTopos (MetaFunctor func1) %sol*)\n            | func0 func1 F f'Sol_ ] (* [[ f'Sol_ @ func1 ]] *).\n\n        (* f is (f_ o>Topos f') , to (f_Sol o>Topos f'Sol)  , is (Sol.PolyMetaFunctor func1 x o>Topos (@uTopos (MetaFunctor func1))) *)\n        * exists ( Sol.PolyMetaFunctor func1 x )%sol .\n          clear -f_Sol_prop f'Sol_prop. tac_reduce.\n\n        (* f is (f_ o>Topos f') , to (f_Sol o>Topos f'Sol)  , is (Sol.PolyMetaFunctor func1 x o>Topos [[ f'Sol_ ]]) *)\n        * exists ((f'Sol_ A x))%sol.\n          clear -f_Sol_prop f'Sol_prop. tac_reduce.\n\n      (* f is (f_ o>Topos f') , to (f_Sol o>Topos f'Sol)  , is ((f_Sol' o>Topos_transf) o>Topos f'Sol) *)\n      + clear - solveTopos H_gradeTotal f_Sol_prop f'Sol_prop.\n        move: (Sol.Destruct_domMetaFunctor.Topos00_domMetaFunctorP f'Sol) => f'Sol_domMetaFunctorP.\n        destruct f'Sol_domMetaFunctorP as\n            [ _func0 _func1  (* @uTopos (MetaFunctor _func1) %sol*)\n            | _func0 _func1 F f'Sol_ ] (* [[ f'Sol_ @ func1 ]] *).\n\n        (* f is (f_ o>Topos f') , to (f_Sol o>Topos f'Sol)  , is ((f_Sol' o>Topos_transf) o>Topos (@uTopos (MetaFunctor _func1))) *)\n        * exists ( f_Sol' o>Topos_transf )%sol .\n          clear -f_Sol_prop f'Sol_prop. tac_reduce.\n\n        (* f is (f_ o>Topos f') , to (f_Sol o>Topos f'Sol)  , is ((f_Sol' o>Topos_transf) o>Topos [[ f'Sol_ ]]) *)\n        * { case : (solveTopos len _ _ ((Sol.toTopos f_Sol') o>Topos [[ (fun A0 => ((fun A1 x1 => Sol.toTopos (f'Sol_ A1 x1)) A0) \\o (transf A0)) @ func1 ]] )) =>\n            [ | f_Sol_o_f'Sol f_Sol_o_f'Sol_prop ].\n            - (* copy-paste degrade lemma case PolyMetaTransf_CoLimitator *)\n              tac_degrade_transf (fun A1 x1 => Sol.toTopos (f'Sol_ A1 x1)) transf.\n              tac_degrade H_gradeTotal f_Sol_prop f'Sol_prop.\n            - exists (f_Sol_o_f'Sol).\n              clear -f_Sol_prop f'Sol_prop f_Sol_o_f'Sol_prop. tac_reduce.\n          }\n\n      (* f is (f_ o>Topos f') , to (f_Sol o>Topos f'Sol)  , is ( [[ f_Sol_ ]] o>Topos f'Sol) *)\n      + \n        have gradeTotal_f_Sol_o_f'Sol : forall A x , (gradeTotal (((fun A1 x1 => Sol.toTopos (f_Sol_ A1 x1)) A x) o>Topos (Sol.toTopos f'Sol)) <= len)%coq_nat.\n        { move => A x.\n          clear -H_gradeTotal f_Sol_prop f'Sol_prop.\n          tac_degrade_union (fun A1 x1 => Sol.toTopos (f_Sol_ A1 x1)) A x.\n          tac_degrade H_gradeTotal f_Sol_prop f'Sol_prop.\n        }\n\n        set v_ := (fun A x => (((fun A1 x1 => Sol.toTopos (f_Sol_ A1 x1)) A x) o>Topos (Sol.toTopos f'Sol))).\n        set solveTopos_v_ := (fun A x => solveTopos len (View0 A) F1' (v_ A x) (gradeTotal_f_Sol_o_f'Sol A x)).\n        set f_Sol_o_f'Sol := (fun A x => projT1 (solveTopos_v_ A x)).\n        set f_Sol_o_f'Sol_prop := (fun A x => projT2 (solveTopos_v_ A x)).\n        set f_Sol_o_f'Sol_propb := (fun A x => ~~ ((projT2 (solveTopos_v_ A x)) : bool)).\n\n        exists ([[ f_Sol_o_f'Sol ]])%sol. left.\n\n        (* now similar as the above congruence case:  f is [[ v_ @ func1 ]] *)\n        case: (isSol.regularCardinalAllP (fun A x => isSol.isSolbb (v_ A x))) => H_someRed.\n        * { apply: (Red.Topos_Trans (uTrans := [[ v_ ]] ));\n            first by clear -f_Sol_prop f'Sol_prop; subst v_; tac_reduce.\n\n            clear -H_someRed f_Sol_o_f'Sol_prop.\n            have f_Sol_o_f'Sol_prop_isRed_ : forall (A : obIndexer) (x : func0 A),\n                ~~ isSol.isSolbb (v_ A x) ->\n                Sol.toTopos (f_Sol_o_f'Sol A x) <~~ (v_ A x) .\n            { intros A x.  (case: (f_Sol_o_f'Sol_prop A x) => // ) ;\n              ( case (isSol.isSolbbP2 (v_ A x)) => //= ) .\n              move: (f_Sol_o_f'Sol A x) ((solveTopos_v_ A x)). move: (v_ A x).\n              clear. intros. exfalso. intuition eauto.\n            }\n\n            have f_Sol_o_f'Sol_prop_isSol_ : forall (A : obIndexer) (x : func0 A),\n                isSol.isSolbb (v_ A x) ->\n                Sol.toTopos (f_Sol_o_f'Sol A x) = v_ A x .\n            { by []. (* shorter exfalso on form of v_ *)\n            }\n\n            clear - H_someRed f_Sol_o_f'Sol_prop_isRed_ f_Sol_o_f'Sol_prop_isSol_ .\n            move: H_someRed  => [A [x H_someRed_prop] ].\n            apply: Red.CoLimitator_cong;\n              [assumption | assumption | | eassumption].\n            intros A1 x1; apply/(introT (isSol.isSolbbP2 (_))); eexists; reflexivity.\n          }\n        * (* memo: contradictory context [ H_someRed constrast form of v_ ] \n             when the elements (A , x) of functor are non-empty *)\n          suff: Sol.toTopos [[f_Sol_o_f'Sol]]%sol = [[ v_ @ func1 ]]\n            by move ->; clear -f_Sol_prop f'Sol_prop; subst v_; tac_reduce.\n\n          clear -H_someRed. simpl; apply: congr1.\n          (* MEMO ONLY PARTICULAR FUNCTIONAL EXTENTIONALITY REQUIRED *)\n          apply: Coq.Logic.FunctionalExtensionality.functional_extensionality_dep. intros A.\n          apply: Coq.Logic.FunctionalExtensionality.functional_extensionality. intros x.\n          (* here the elements (A , x) of functor are non-empty *)\n          exfalso. apply: H_someRed. exists A , x. reflexivity.\n  Defined.\n\nEnd Section1.\n\nEnd METAFUNCTORS.\n  \n(**#+END_SRC\n\nVoila. **)\n", "meta": {"author": "1337777", "repo": "galois", "sha": "7dbe103d25374abc918f254e2ed3c9eec98696d6", "save_path": "github-repos/coq/1337777-galois", "path": "github-repos/coq/1337777-galois/galois-7dbe103d25374abc918f254e2ed3c9eec98696d6/galoisSolution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2556201879798585}}
{"text": "Require Import Monad.\n\nClass MonadPlus (M : Type -> Type) : Type := {\n  monad :> Monad M\n  ; mzero : forall {A}, M A\n  ; mplus : forall {A:Type}, M A -> M A -> M A\n  (* laws *)\n  ; mzero_left : forall A f, bind (@mzero A) f = @mzero A\n  ; mzero_right : forall A B (m: M A),\n      bind m (fun x => (@mzero B)) = mzero\n  ; monoid_left_unit : forall A (m : M A),\n      mplus mzero m = m\n  ; monoid_right_unit : forall A (m : M A),\n      mplus m mzero = m\n  ; monoid_assoc : forall A (ma mb mc : M A),\n      mplus (mplus ma mb) mc = mplus ma (mplus mb mc)\n}.\n\nInstance OptionMonadPlus : MonadPlus option := {\n  monad := OptionMonad\n  ; mzero A := @None A\n  ; mplus A m1 m2 :=\n      match m1 with\n      | None => m2\n      | Some x => m1\n      end\n}.\nProof.\n reflexivity.\n\n destruct m; reflexivity.\n\n reflexivity.\n\n destruct m; reflexivity.\n\n destruct ma; reflexivity.\nDefined.\n", "meta": {"author": "yoshihiro503", "repo": "coqio", "sha": "f58fa40d69a2ab213d935dcaf5f82d42f1a8f60a", "save_path": "github-repos/coq/yoshihiro503-coqio", "path": "github-repos/coq/yoshihiro503-coqio/coqio-f58fa40d69a2ab213d935dcaf5f82d42f1a8f60a/src/MonadPlus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.25562018797985847}}
{"text": "Require Import UNIVERSE.\n(* Require Import EventsC. *)\n(* Require Import Values. *)\n(* Require Import AST. *)\n(* Require Import Memory. *)\n(* Require Import Globalenvs. *)\nRequire Import Smallstep.\nFrom Paco Require Import paco.\nRequire Import sflib.\n(* Require Import Skeleton. *)\nRequire Import CoqlibC.\nRequire Import Simulation.\nRequire Import ModSem.\n\nSet Implicit Arguments.\n\n\n\nLemma spread_dstar\n      ms st0 tr st1\n      (DTM: forall st0, determinate_at ms st0)\n      (STAR: Star ms st0 tr st1):\n    <<DSTAR: DStar ms st0 tr st1>>.\nProof. ginduction STAR; ii; ss; econs; eauto. eapply IHSTAR; eauto. Qed.\n\nLemma spread_dplus\n      ms st0 tr st1\n      (DTM: forall st0, determinate_at ms st0)\n      (PLUS: Plus ms st0 tr st1):\n    <<DPLUS: DPlus ms st0 tr st1>>.\nProof. inv PLUS. econs; eauto. eapply spread_dstar; eauto. Qed.\n\nLemma at_external_receptive_at\n      ms_src lst_src\n      (CALL: ModSem.is_call ms_src lst_src):\n    <<RCP: receptive_at ms_src lst_src>>.\nProof. econs; ii; ModSem.tac. Qed.\n\nLemma at_external_determinate_at\n      ms_src lst_src\n      (CALL: ModSem.is_call ms_src lst_src):\n    <<RCP: determinate_at ms_src lst_src>>.\nProof. econs; ii; ModSem.tac. Qed.\n\nLemma final_frame_receptive_at\n      ms_src lst_src\n      (CALL: ModSem.is_return ms_src lst_src):\n    <<RCP: receptive_at ms_src lst_src>>.\nProof. econs; ii; ModSem.tac. Qed.\n\nLemma final_frame_determinate_at\n      ms_src lst_src\n      (CALL: ModSem.is_return ms_src lst_src):\n    <<RCP: determinate_at ms_src lst_src>>.\nProof. econs; ii; ModSem.tac. Qed.\n\n(* Lemma atomic_step_continue_star *)\n(*     (ms: ModSem.t) st0 tr *)\n(*     (WBT: output_trace tr): *)\n(*     <<STEP: Star (ModSem.Atomic.trans ms) (tr, st0) tr ([], st0)>>. *)\n(* Proof. *)\n(*   i. ginduction tr; ii; ss; econs; eauto. *)\n(*   { econs; eauto. } *)\n(*   { eapply IHtr; eauto. des; ss. } *)\n(*   ss. *)\n(* Qed. *)\n\n(* Lemma step_atomic_step *)\n(*       (ms: ModSem.t) st0 tr st1 *)\n(*       (WBT: well_behaved_traces ms) *)\n(*       (STEP: Step ms st0 tr st1): *)\n(*     <<STEP: Plus (ModSem.Atomic.trans ms) ([], st0) tr ([], st1)>>. *)\n(* Proof. *)\n(*   destruct tr. *)\n(*   { apply plus_one. econs; eauto. } *)\n(*   s. econs; eauto; swap 2 3. *)\n(*   { econs 2; eauto. } *)\n(*   { ss. } *)\n(*   exploit WBT; eauto. i; ss. hexploit atomic_step_continue_star; eauto. ss. eauto. *)\n(* Qed. *)\n\n(* Lemma star_atomic_star *)\n(*       (ms: ModSem.t) st0 tr st1 *)\n(*       (WBT: well_behaved_traces ms) *)\n(*       (STAR: Star ms st0 tr st1): *)\n(*     <<STAR: Star (ModSem.Atomic.trans ms) ([], st0) tr ([], st1)>>. *)\n(* Proof. *)\n(*   ginduction STAR; ii. *)\n(*   - econs; eauto. *)\n(*   - clarify. eapply star_trans. *)\n(*     { exploit step_atomic_step; eauto. i. eapply plus_star; eauto. } *)\n(*     { exploit IHSTAR; eauto. } *)\n(*     ss. *)\n(* Qed. *)\n\n(* Lemma plus_atomic_plus *)\n(*       (ms: ModSem.t) st0 tr st1 *)\n(*       (WBT: well_behaved_traces ms) *)\n(*       (PLUS: Plus ms st0 tr st1): *)\n(*     <<PLUS: Plus (ModSem.Atomic.trans ms) ([], st0) tr ([], st1)>>. *)\n(* Proof. *)\n(*   inv PLUS. eapply plus_star_trans. *)\n(*   { exploit step_atomic_step; eauto. } *)\n(*   { eapply star_atomic_star; eauto. } *)\n(*   ss. *)\n(* Qed. *)\n\n(* Lemma determ_atomic_determ *)\n(*       (ms: ModSem.t) st0 tr *)\n(*       (* (WBT: well_behaved_traces ms) *) *)\n(*       (DTM: determinate_at ms st0) *)\n(*       (WBT: output_trace tr): *)\n(*     <<DTM: determinate_at (ModSem.Atomic.trans ms) (tr, st0)>>. *)\n(* Proof. *)\n(*   ii. inv DTM. econs; eauto; ii; ss; inv H; ss; try xomega; inv H0. *)\n(*   - determ_tac sd_determ_at. esplits; eauto. i. exploit H0; eauto. i; des. clarify. *)\n(*   - determ_tac sd_determ_at. inv H. *)\n(*   - determ_tac sd_determ_at. inv H. *)\n(*   - determ_tac sd_determ_at. esplits; eauto. *)\n(*     { inv H; econs; eauto. } *)\n(*     i; des. clarify. exploit H0; inv H; i; des; clarify; eauto. *)\n(*   - esplits; eauto. ss. des. destruct ev; ss; econs; eauto. *)\n(* Qed. *)\n\n\n\n\n\n(* Lemma output_trace_determinate_at *)\n(*       (ms: ModSem.t) *)\n(*       ev tr st0 *)\n(*       (WBT: output_event ev): *)\n(*     determinate_at (ModSem.Atomic.trans ms) (ev :: tr, st0). *)\n(* Proof. *)\n(*   econs; eauto; ii; ss; inv H; ss; try xomega. inv H0. split; ss. destruct ev; ss; econs; eauto. *)\n(* Qed. *)\n\n(* Lemma atomic_dstep_continue_dstar *)\n(*     (ms: ModSem.t) st0 tr *)\n(*     (WBT: output_trace tr): *)\n(*     <<STEP: DStar (ModSem.Atomic.trans ms) (tr, st0) tr ([], st0)>>. *)\n(* Proof. *)\n(*   i. ginduction tr; ii; ss. *)\n(*   { econs; eauto. } *)\n(*   (* exploit determ_atomic_determ; eauto. *) *)\n(*   (* { instantiate (1:= []). ss. } *) *)\n(*   (* intro DTM0; des. *) *)\n(*   econs; eauto. *)\n(*   { rr. des. esplits; eauto. *)\n(*     - eapply output_trace_determinate_at; eauto. *)\n(*     - econs; eauto. ss. *)\n(*   } *)\n(*   { eapply IHtr; eauto. des; ss. } *)\n(*   ss. *)\n(* Qed. *)\n\n(* Lemma dstep_atomic_dstep *)\n(*       (ms: ModSem.t) st0 tr st1 *)\n(*       (* (SINGLE: single_events ms) *) *)\n(*       (WBT: well_behaved_traces ms) *)\n(*       (STEP: DStep ms st0 tr st1): *)\n(*     <<STEP: DPlus (ModSem.Atomic.trans ms) ([], st0) tr ([], st1)>>. *)\n(* Proof. *)\n(*   rr in STEP. des. *)\n(*   exploit determ_atomic_determ; eauto. *)\n(*   { instantiate (1:= []). ss. } *)\n(*   intro DTM; des. destruct tr. *)\n(*   { apply plus_one. econs; eauto. econs; eauto. } *)\n(*   s. econs; eauto; swap 2 3. *)\n(*   { rr. split; ss. instantiate (1:= (_, _)). econs 2; eauto. } *)\n(*   { ss. } *)\n(*   eapply atomic_dstep_continue_dstar; eauto. exploit WBT; eauto. *)\n(* Qed. *)\n\n(* Lemma dstar_atomic_dstar *)\n(*       (ms: ModSem.t) st0 tr st1 *)\n(*       (* (SINGLE: single_events ms) *) *)\n(*       (WBT: well_behaved_traces ms) *)\n(*       (STAR: DStar ms st0 tr st1): *)\n(*     <<STAR: DStar (ModSem.Atomic.trans ms) ([], st0) tr ([], st1)>>. *)\n(* Proof. *)\n(*   ginduction STAR; ii; ss. *)\n(*   - econs; eauto. *)\n(*   - exploit IHSTAR; eauto. i. eapply star_trans; eauto. apply plus_star. exploit dstep_atomic_dstep; eauto. *)\n(* Qed. *)\n\n(* Lemma dplus_atomic_dplus *)\n(*       (ms: ModSem.t) st0 tr st1 *)\n(*       (* (SINGLE: single_events ms) *) *)\n(*       (WBT: well_behaved_traces ms) *)\n(*       (PLUS: DPlus ms st0 tr st1): *)\n(*     <<PLUS: DPlus (ModSem.Atomic.trans ms) ([], st0) tr ([], st1)>>. *)\n(* Proof. *)\n(*   inv PLUS. eapply plus_star_trans. *)\n(*   { exploit dstep_atomic_dstep; eauto. } *)\n(*   { eapply dstar_atomic_dstar; eauto. } *)\n(*   ss. *)\n(* Qed. *)\n\n(* Lemma atomic_single_events_at: forall (ms: ModSem.t), *)\n(*     <<SINGLE: forall st, single_events_at (ModSem.Atomic.trans ms) st>>. *)\n(* Proof. ii. inv H; ss. xomega. Qed. *)\n\n(* Lemma atomic_single_evnents: forall (ms: ModSem.t), *)\n(*     <<SINGLE: single_events (ModSem.Atomic.trans ms)>>. *)\n(* Proof. ii. inv H; ss. xomega. Qed. *)\n\n(* Lemma atomic_receptive_at *)\n(*       (ms: ModSem.t) st0 *)\n(*       (SSR: strongly_receptive_at ms st0): *)\n(*     <<RCP: forall tr, receptive_at (ModSem.Atomic.trans ms) (tr, st0)>>. *)\n(* Proof. *)\n(*   generalize (@atomic_single_evnents ms); eauto. intro SINGLE. *)\n(*   inv SSR. econs; ss. *)\n(*   { ii. ss. destruct t1; ss. *)\n(*     { inv H. inv H0. esplits; eauto. econs; eauto. } *)\n(*     exploit SINGLE; eauto. intro LEN. ss. destruct t1; ss; try xomega. destruct t2; ss. *)\n(*     { inv H0. } *)\n(*     destruct t2; ss; cycle 1. *)\n(*     { inv H0. } *)\n(*     inv H; ss. *)\n(*     - exploit ssr_receptive_at; eauto. i; des. esplits; eauto. econs; eauto. *)\n(*     - esplits; eauto. instantiate (1:= (_, _)). *)\n(*       assert(e0 = e) by (des; inv H0; ss). clarify. econs 3; eauto. *)\n(*   } *)\n(*   eapply atomic_single_events_at; eauto. *)\n(* Qed. *)\n\n(* Lemma atomic_receptive_at_nonnil: forall (ms: ModSem.t), *)\n(*     <<RCP: forall st0 ev tr, receptive_at (ModSem.Atomic.trans ms) (ev :: tr, st0)>>. *)\n(* Proof. *)\n(*   i. generalize (@atomic_single_evnents ms); eauto. intro SINGLE. ii. econs; ss. *)\n(*   { ii. ss. destruct t1; ss. *)\n(*     { inv H. } *)\n(*     exploit SINGLE; eauto. intro LEN. ss. destruct t1; ss; try xomega. destruct t2; ss. *)\n(*     { inv H0. } *)\n(*     destruct t2; ss; cycle 1. *)\n(*     { inv H0. } *)\n(*     inv H; ss. des. assert(e = e0). { inv H0; ss. } clarify. *)\n(*     esplits; eauto. econs; eauto. ss. *)\n(*   } *)\n(*   eapply atomic_single_events_at; eauto. *)\n(* Qed. *)\n\n(* Lemma atomic_receptive *)\n(*       (ms: ModSem.t) *)\n(*       (SSR: strongly_receptive ms): *)\n(*     <<RCP: receptive (ModSem.Atomic.trans ms)>>. *)\n(* Proof. *)\n(*   generalize (@atomic_single_evnents ms); eauto. intro SINGLE. *)\n(*   inv SSR. econs; ss. *)\n(*   { ii. ss. destruct t1; ss. *)\n(*     { inv H. inv H0. esplits; eauto. econs; eauto. } *)\n(*     exploit SINGLE; eauto. intro LEN. ss. destruct t1; ss; try xomega. *)\n(*     destruct t2; ss. *)\n(*     { inv H0. } *)\n(*     destruct t2; ss; cycle 1. *)\n(*     { inv H0. } *)\n(*     inv H; ss. *)\n(*     - exploit ssr_receptive; eauto. i; des. esplits; eauto. econs; eauto. *)\n(*     - esplits; eauto. instantiate (1:= (_, _)). *)\n(*       assert(e0 = e) by (des; inv H0; ss). clarify. econs 3; eauto. *)\n(*   } *)\n(* Qed. *)\n\nLemma DStep_Step\n      L st0 tr st1\n      (STEP: DStep L st0 tr st1):\n    <<STEP: Step L st0 tr st1>>.\nProof. rr in STEP. des. ss. Qed.\n\nLemma DStar_Star\n      L st0 tr st1\n      (STAR: DStar L st0 tr st1):\n    <<STAR: Star L st0 tr st1>>.\nProof.\n  ginduction STAR; ii; ss.\n  { eapply star_refl. }\n  clarify. eapply star_trans; eauto. eapply star_one. eapply DStep_Step; eauto.\nQed.\n\nLemma DPlus_Plus\n      L st0 tr st1\n      (PLUS: DPlus L st0 tr st1):\n    <<PLUS: Plus L st0 tr st1>>.\nProof.\n  inv PLUS.\n  econs; eauto.\n  { eapply DStep_Step; eauto. }\n  { eapply DStar_Star; eauto. }\nQed.\n\nDefinition safe_modsem (ms: ModSem.t) (st0: ms.(ModSem.state)): Prop :=\n  forall st1 (STAR: Star ms st0 E0 st1),\n    (<<EVCALL: ms.(ModSem.is_call) st1>>) \\/\n    (<<EVRET: ms.(ModSem.is_return) st1>>) \\/\n    (<<EVSTEP: exists tr st2, Step ms st1 tr st2>>).\nHint Unfold safe_modsem.\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/ModSemProps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.25562018797985847}}
{"text": "From stdpp Require Export namespaces.\nFrom iris.proofmode Require Import tactics.\nFrom iris.algebra Require Import auth gmap frac agree gset.\nFrom Perennial.base_logic.lib Require Export own.\nFrom Perennial.algebra Require Import gen_heap_names.\nSet Default Proof Using \"Type\".\nImport uPred.\n\nClass partitionG (L V: Type) (Σ: gFunctors) `{Countable L, Infinite L, Countable V, Infinite V} := {\n  partition_heap_inG :> gen_heapGS L (gset V) Σ;\n}.\n\nClass partition_preG (L V: Type) Σ `{Countable L, Infinite L, Countable V, Infinite V} := {\n  partition_heap_preG :> gen_heapGpreS L (gset V) Σ;\n}.\n\n\nDefinition partitionΣ (L V: Type) `{Countable L, Infinite L, Countable V, Infinite V} : gFunctors :=\n    #[gen_heapΣ L (gset V)].\n\nInstance subG_partitionG L V {Σ} `{Countable L, Infinite L, Countable V, Infinite V}:\n  subG (partitionΣ L V) Σ → partition_preG L V Σ.\nProof. solve_inG. Qed.\n\nLocal Notation \"l ↦{ q } v\" := (mapsto l q v)\n  (at level 20, q at level 50, format \"l  ↦{ q }  v\") : bi_scope.\nLocal Notation \"l ↦ v\" := (mapsto l 1 v) (at level 20) : bi_scope.\n\nLocal Notation \"l ↦{ q } -\" := (∃ v, l ↦{q} v)%I\n  (at level 20, q at level 50, format \"l  ↦{ q }  -\") : bi_scope.\nLocal Notation \"l ↦ -\" := (l ↦{1} -)%I (at level 20) : bi_scope.\n\nSection definitions.\nContext `{Countable L, Infinite L, Countable V, Infinite V, hG : !partitionG L V Σ}.\n\nImplicit Types l : L.\nImplicit Types s : gset V.\n\nDefinition disjoint_images (σ: gmap L (gset V)) : Prop :=\n  ∀ i1 i2 s1 s2, i1 ≠ i2 → σ !! i1 = Some s1 → σ !! i2 = Some s2 →\n                 s1 ## s2.\n\nDefinition partition_ctx (σ: gmap L (gset V)) : iProp Σ :=\n  (⌜ disjoint_images σ ⌝ ∗ gen_heap_ctx σ).\n\nDefinition union_partition (σ: gmap L (gset V)) : gset V :=\n  map_fold (λ _ s1 s2, s1 ∪ s2) ∅ σ.\n\nLemma union_partition_elem_of_1 σ (v: V):\n  v ∈ union_partition σ → ∃ i s, σ !! i = Some s ∧ v ∈ s.\nProof.\n  revert v.\n  eapply (map_fold_ind (λ b σ, ∀ v, v ∈ b → ∃ i s, σ !! i = Some s ∧ v ∈ s) _ ∅).\n  - set_solver.\n  - intros i s1 m s2 Hlookup HP v Hin.\n    apply elem_of_union in Hin as [Hs1|Hs2].\n    * exists i, s1. rewrite lookup_insert; auto.\n    * edestruct (HP) as (i'&s'&?&?); eauto.\n      exists i', s'. rewrite lookup_insert_ne //=. congruence.\nQed.\n\nLemma union_partition_elem_of_2 σ (v: V) i s:\n  σ !! i = Some s → v ∈ s → v ∈ union_partition σ.\nProof.\n  revert v i s.\n  eapply (map_fold_ind (λ b σ, ∀ v i s, σ !! i = Some s → v ∈ s → v ∈ b) _ ∅).\n  - set_solver.\n  - intros i s1 m s2 Hlookup HP v i' s Hlookup2 Hin.\n    destruct (decide (i = i')).\n    * subst. rewrite lookup_insert in Hlookup2. apply elem_of_union_l.\n      inversion Hlookup2; subst; eauto.\n    * rewrite lookup_insert_ne in Hlookup2 * => //=.\n      apply elem_of_union_r. eapply HP; eauto.\nQed.\n\nLemma union_partition_subset σ i s:\n  σ !! i = Some s → s ⊆ union_partition σ.\nProof. set_unfold. intros. by eapply union_partition_elem_of_2. Qed.\n\nDefinition fresh_partition_value (σ: gmap L (gset V)) : V :=\n  fresh (union_partition σ).\n\nLemma not_elem_of_union_partition σ x :\n  x ∉ union_partition σ → ∀ i s, σ !! i = Some s → x ∉ s.\nProof.\n  intros Hin1 i s Hlookup.\n  intros Hin. eapply union_partition_elem_of_2 in Hlookup; eauto.\nQed.\n\nLemma fresh_partition_value_spec σ :\n  ∀ i s, σ !! i = Some s → fresh_partition_value σ ∉ s.\nProof.\n  rewrite /fresh_partition_value.\n  apply not_elem_of_union_partition, is_fresh.\nQed.\n\nLemma partition_alloc σ:\n  partition_ctx σ ==∗ ∃ l v (Hfresh1: σ !! l = None) (Hfresh2: v ∉ union_partition σ),\n        partition_ctx (<[l := {[v]}]>σ) ∗ l ↦ {[v]} ∗ meta_token l ⊤.\nProof.\n  iIntros \"(Hdisj&Hctx)\". iDestruct \"Hdisj\" as %Hdisj.\n  iMod (gen_heap_alloc σ (fresh (dom σ)) ({[fresh_partition_value σ]}) with \"Hctx\")\n       as \"(Hctx&Hl&Hmeta)\".\n  { rewrite -(not_elem_of_dom (D := gset L)). apply is_fresh. }\n  iModIntro. unshelve (iExists _, _, _, _; iFrame).\n  { eapply (not_elem_of_dom (D := gset L)). apply is_fresh. }\n  { rewrite /fresh_partition_value. eapply is_fresh. }\n  iPureIntro.\n  intros i j s1 s2 Hneq.\n  destruct (decide (i = fresh (dom σ))) as [He1|Hne1].\n  { subst. rewrite lookup_insert lookup_insert_ne //.\n    inversion 1; subst. intros Hlookup.\n    specialize (fresh_partition_value_spec σ j s2). set_solver. }\n  destruct (decide (j = fresh (dom σ))) as [He2|Hne2].\n  { subst. rewrite lookup_insert lookup_insert_ne //.\n    inversion 1; subst. intros Hlookup.\n    specialize (fresh_partition_value_spec σ i s1). set_solver. }\n  rewrite ?lookup_insert_ne //. by eapply Hdisj.\nQed.\n\nLemma partition_valid_disj σ (l1 l2: L) (s1 s2: gset V):\n  partition_ctx σ -∗ l1 ↦ s1 -∗ l2 ↦ s2 -∗ ⌜ l1 ≠ l2 ∧ s1 ## s2 ⌝.\nProof.\n  iDestruct 1 as (Hdisj) \"Hctx\". iIntros \"Hl1 Hl2\".\n  iDestruct (gen_heap_valid with \"Hctx Hl1\") as %Hin1.\n  iDestruct (gen_heap_valid with \"Hctx Hl2\") as %Hin2.\n  iAssert (⌜l1 ≠ l2⌝)%I with \"[-]\" as %Hneq.\n  { iIntros (?). subst. iDestruct (mapsto_valid_2 with \"[$] [$]\") as %Hval.\n    rewrite frac_valid in Hval * => Hlt. by apply Qp.not_plus_q_ge_1 in Hlt.\n  }\n  iPureIntro. split; auto. eapply Hdisj; eauto.\nQed.\n\nLemma union_partition_move σ (l1 l2: L) (s1 s1' s2: gset V):\n  l1 ≠ l2 →\n  s1 ## s1' →\n  σ !! l1 = Some (s1 ∪ s1') →\n  σ !! l2 = Some s2 →\n  union_partition σ = union_partition (<[l1:=s1]> (<[l2:=s2 ∪ s1']> σ)).\nProof.\n  intros Hneq Hdisj Hl1 Hl2.\n  assert (<[l1:=s1]> (<[l2:=s2 ∪ s1']> σ) =\n          <[l1:=s1]> (delete l1 (<[l2:=s2 ∪ s1']> (delete l2 σ)))) as Heq.\n  { by rewrite ?insert_delete_insert. }\n  rewrite Heq.\n\n  assert (σ = <[l1:=s1 ∪ s1']> (delete l1 (<[l2:=s2]> (delete l2 σ)))) as Heq'.\n  { rewrite ?insert_delete_insert ?insert_id //. }\n  rewrite {1}Heq'.\n\n  rewrite /union_partition ?map_fold_insert ?lookup_delete //; try set_solver+.\n  rewrite ?delete_insert_ne //.\n  assert (delete l1 (delete l2 σ) !! l2 = None).\n  { rewrite lookup_delete_ne // lookup_delete //. }\n  rewrite ?map_fold_insert //; set_solver+.\nQed.\n\nLemma partition_move σ (l1 l2: L) (s1 s1' s2: gset V):\n  s1 ## s1' →\n  partition_ctx σ -∗ l1 ↦ (s1 ∪ s1') -∗ l2 ↦ s2 ==∗\n  partition_ctx (<[l1 := s1]>(<[l2 := s2 ∪ s1']>σ)) ∗ l1 ↦ s1 ∗ l2 ↦ (s2 ∪ s1').\nProof.\n  iIntros (Hdisjs1) \"Hpart Hl1 Hl2\".\n  iDestruct (partition_valid_disj with \"Hpart Hl1 Hl2\") as %Hdisj_s1s2.\n  iDestruct \"Hpart\" as (Hdisj) \"Hctx\".\n  iDestruct (gen_heap_valid with \"Hctx Hl1\") as %Hin1.\n  iDestruct (gen_heap_valid with \"Hctx Hl2\") as %Hin2.\n  iMod (gen_heap_update σ l2 _ (s2 ∪ s1') with \"[$] [$]\") as \"(Hctx&Hl2)\".\n  iMod (gen_heap_update _ l1 _ (s1) with \"[$] [$]\") as \"(Hctx&Hl1)\".\n  iModIntro. iFrame. iPureIntro.\n  intros i j si sj Hneq.\n  destruct (decide (i = l1)) as [He1|Hne1].\n  { subst.\n    rewrite lookup_insert. inversion 1; subst.\n    rewrite lookup_insert_ne //.\n    destruct (decide (j = l2)) as [He2|Hne2].\n    {\n      subst. rewrite lookup_insert. inversion 1; subst.\n      set_solver.\n    }\n    rewrite lookup_insert_ne //; intros; eauto.\n    cut (si ∪ s1' ## sj); first by set_solver.\n    eapply Hdisj; [ | apply Hin1 | eauto ]; eauto.\n  }\n  rewrite lookup_insert_ne //.\n  destruct (decide (i = l2)) as [He2|Hne2].\n  {\n    subst.\n    rewrite lookup_insert.\n    destruct (decide (j = l1)) as [He2|Hne2].\n    {\n      subst. rewrite lookup_insert. inversion 1; subst.\n      set_solver.\n    }\n    inversion 1; subst.\n    rewrite ?lookup_insert_ne //; intros; eauto.\n    cut (s1 ∪ s1' ## sj ∧ s2 ## sj); first by set_solver.\n    split.\n    * eapply Hdisj; [ | apply Hin1 | eauto ]; eauto.\n    * eapply Hdisj; [ | apply Hin2 | eauto ]; eauto.\n  }\n  rewrite lookup_insert_ne // => ?.\n  destruct (decide (j = l1)) as [He3|Hne3].\n  {\n    subst. rewrite lookup_insert. inversion 1; subst.\n    cut (sj ∪ s1' ## si); first by set_solver.\n    eapply Hdisj; [ | apply Hin1 | eauto ]; eauto.\n  }\n  rewrite lookup_insert_ne //.\n  destruct (decide (j = l2)) as [He4|Hne4].\n  {\n    subst. rewrite lookup_insert. inversion 1; subst.\n    cut (s1 ∪ s1' ## si ∧ s2 ## si); first by set_solver.\n    split.\n    * eapply Hdisj; [ | apply Hin1 | eauto ]; eauto.\n    * eapply Hdisj; [ | apply Hin2 | eauto ]; eauto.\n  }\n  rewrite lookup_insert_ne // => Hin4.\n  eapply Hdisj; [ | | apply Hin4 ]; eauto.\nQed.\n\nLemma partition_move_1 σ (l1 l2: L) (v: V) (s: gset V):\n  partition_ctx σ -∗ l1 ↦ {[v]} -∗ l2 ↦ s ==∗\n  partition_ctx (<[l1 := ∅]>(<[l2 := s ∪ {[v]}]>σ)) ∗ l1 ↦ ∅ ∗ l2 ↦ (s ∪ {[v]}).\nProof.\n  replace {[v]} with (∅ ∪ {[v]} : gset V) at 1 by set_solver.\n  iApply partition_move; set_solver.\nQed.\n\nLemma partition_join σ (l1 l2: L) (s1 s2: gset V):\n  partition_ctx σ -∗ l1 ↦ s1 -∗ l2 ↦ s2 ==∗\n  partition_ctx (<[l1 := ∅]>(<[l2 := s2 ∪ s1]>σ)) ∗ l1 ↦ ∅ ∗ l2 ↦ (s2 ∪ s1).\nProof.\n  replace s1 with (∅ ∪ s1) at 1 by set_solver.\n  iApply partition_move; set_solver.\nQed.\n\nEnd definitions.\n\nLemma partition_init `{hP: partition_preG L V Σ}:\n  ⊢ |==> ∃ names : gen_heap_names,\n        let _ := {| partition_heap_inG :=\n                      gen_heapG_update_pre (@partition_heap_preG _ _ _ _ _ _ _ _ _ hP) names |} in\n        partition_ctx (∅: gmap L (gset V)).\nProof.\n  iMod (gen_heap_name_init ∅) as (names) \"H\".\n  iModIntro. iExists names. iFrame. rewrite //=.\nQed.\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/partition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.25562018797985847}}
{"text": "Require Import\n  Hask.Control.Monad\n  Hask.Data.Maybe\n  Coq.Lists.List.\n\nGeneralizable All Variables.\nSet Primitive Projections.\nSet Universe Polymorphism.\nUnset Transparent Obligations.\n\nImport ListNotations.\n\nDefinition Effect := (Type -> Type) -> Type.\n\nInductive Effects (m : Type -> Type) : list Effect -> Type :=\n  | NilE : Effects m []\n  | ConsE effects : forall effect : Effect,\n      effect m -> Effects m effects -> Effects m (effect :: effects).\n\nArguments ConsE : default implicits.\n\nDefinition combine `(e : effect m) `(xs : Effects m effects) :\n  Effects m (effect :: effects) := ConsE _ e xs.\n\nInfix \".:\" := combine (at level 48, right associativity).\n\nClass Handles (fs : list Effect) (effect : Effect) := {\n  getEffect : forall m, Effects m fs -> effect m\n}.\n\n#[export]\nInstance Handles_hd {fs : list Effect}  {f : Effect} :\n  Handles (f :: fs) f.\nProof.\n  constructor; intros.\n  inversion X.\n  exact X0.\nDefined.\n\n#[export]\nInstance Handles_tl `{_ : Handles fs f} : Handles (x :: fs) f.\nProof.\n  constructor; intros.\n  inversion H.\n  apply getEffect0.\n  inversion X.\n  exact X1.\nDefined.\n\nDefinition TFree `(xs : list Effect) m a :=\n  Effects m xs -> m a.\n\nDefinition Eff := TFree.\n\nDefinition liftF `{Handles effects effect} `{Monad m}\n  `(getOp : effect m -> m a) : Eff effects m a :=\n  fun effects => getOp (getEffect m effects).\n\nDefinition interpret `{H : Monad m} `(interpreter : Effects m effects)\n  `(program : Eff effects m a) : m a := program interpreter.\n\n#[export]\nInstance TFree_Functor `(xs : list Effect) `{Monad m} : Functor (TFree xs m) := {\n  fmap := fun A B f run => fun xs => fmap f (run xs)\n}.\n\n#[export]\nInstance TFree_Applicative `(xs : list Effect) `{Monad m} : Applicative (TFree xs m) := {\n  pure := fun _ x => fun xs => pure x;\n  ap   := fun A B runf runx => fun xs => runf xs <*> runx xs\n}.\n\n#[export]\nInstance TFree_Monad `(xs : list Effect) `{Monad m} : Monad (TFree xs m) := {\n  join := fun A run => fun xs => run xs >>= fun f => f xs\n}.\n\nRecord Abortive (m : Type -> Type) := {\n  abortE : m unit\n}.\n\nDefinition abort `{Handles r Abortive} : Eff r unit :=\n  liftF abortE.\n\nRecord Reader (e : Type) (m : Type -> Type) := {\n  askE : m e\n}.\n\nDefinition ask `{Handles r (Reader e)} : Eff r e :=\n  liftF (askE e).\n\nRequire Import Arith.\n\nSet Printing Universes.\n\nDefinition example1 `{Handles r (Reader nat)} `{Handles r Abortive} :\n  Eff r nat :=\n  (fun x y => y + 15) <$> abort <*> ask.\n\nDefinition maybeInterpreter : Effects Maybe [Reader nat; Abortive] :=\n  combine {| askE   := Just 10 |} (combine {| abortE := Nothing |} (NilE _)).\n\nDefinition run {a} : Eff [Reader nat; Abortive] a -> Maybe a :=\n  interpret maybeInterpreter.\n\nExample run_example1 : run example1 = Nothing.\nProof. reflexivity. Qed.\n\nDefinition example2 `{Handles r (Reader nat)} : Eff r nat :=\n  fmap (plus 15) ask.\n\nExample run_example2 : run example2 = Just 25.\nProof. reflexivity. Qed.\n\n(*\nDefinition example3 `{Handles r (Reader nat)} `{Handles r Abortive} :\n  Eff r nat :=\n  v <- ask;\n  if leb v 15\n  then abort ;; pure 0\n  else pure (v+1).\n\nExample run_example3 : run example3 = None.\nProof. reflexivity. Qed.\n*)\n", "meta": {"author": "jwiegley", "repo": "coq-haskell", "sha": "56a185af5767177d410113a03bd765135e07c9ca", "save_path": "github-repos/coq/jwiegley-coq-haskell", "path": "github-repos/coq/jwiegley-coq-haskell/coq-haskell-56a185af5767177d410113a03bd765135e07c9ca/src/Control/Monad/Eff.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2555906806293091}}
{"text": "(* Correctness of the Assume Insertion pass *)\n(* A pass of the middle-end optimizer *)\n(* Inserts an Assume insertion just after an Anchor *)\n\nRequire Import internal_simulations.\nRequire Import sem_properties.\nRequire Import assume_insertion.\nRequire Import Coq.MSets.MSetPositive.\nRequire Import def_regs.\nRequire Import common.\nRequire Import IR.\nRequire Import IRinterpreter.\nRequire Import Errors.\nRequire Import monad.\nRequire Import monad_impl.\nRequire Import mixed_sem.\nRequire Import sem_properties.\nRequire Import customSmallstep.\n\nRequire Import IRtoRTLblock_proof.\n(* so we can resue the addstk typing of the monads *)\n(* TODO: We could get that in another file *)\n\n\n(** * Matching the stack and properties  *)\n(* Matching stackframes: a version may have been replaced with its optimized version *)\nInductive match_stackframe (v:version) (fid:fun_id) (guard:expr) (ancl:label) (params:list reg): stackframe -> stackframe -> Prop :=\n| frame_same:\n    forall sf, (match_stackframe v fid guard ancl params) sf sf\n| frame_opt:\n    forall r lbl rm vins abs\n      (AS_INSERT: insert_assume_version v fid guard ancl params = OK vins)\n      (DEFREGS: defined_regs_analysis (ver_code v) params (ver_entry v) = Some abs)\n      (DEF: forall retval, defined (rm#r<-retval) (def_absstate_get lbl abs)),\n      (match_stackframe v fid guard ancl params) (IR_SF (r, v, lbl, rm)) (IR_SF (r, vins, lbl, rm)).\n\n(* Generalizing match_stackframe to the entire stack *)\nInductive match_stack (v:version) (fid:fun_id) (guard:expr) (ancl:label) (params:list reg): stack -> stack -> Prop :=\n| match_nil:\n    (match_stack v fid guard ancl params) nil nil\n| match_cons:\n    forall s s' sf sf'\n      (MS: (match_stack v fid guard ancl params) s s')\n      (MSF: (match_stackframe v fid guard ancl params) sf sf'),\n      (match_stack v fid guard ancl params) (sf::s) (sf'::s').\n\nLemma match_stack_same:\n  forall s v fid guard ancl params,\n    (match_stack v fid guard ancl params) s s.\nProof.\n  intros s v fid guard ancl. induction s; constructor. auto. constructor.\nQed.\n\nLemma match_app:\n  forall synth s s' v fid guard ancl params,\n    (match_stack v fid guard ancl params) s s' ->\n    (match_stack v fid guard ancl params) (synth++s) (synth++s').\nProof.\n  intros. induction synth.\n  - simpl. auto.\n  - repeat rewrite <- app_comm_cons. apply match_cons. auto. constructor.\nQed.\n\nLemma app_match:\n  forall synth synthopt s s' v fid guard ancl params,\n    (match_stack v fid guard ancl params) s s' ->\n    (match_stack v fid guard ancl params) synth synthopt ->\n    (match_stack v fid guard ancl params) (synth++s) (synthopt++s').\nProof.\n  intros. induction H0.\n  - simpl. auto.\n  - repeat rewrite <- app_comm_cons. apply match_cons; auto.\nQed.\n\n(** * Index and order used in the simulation *)\n(* There is one stuttering step for each inserted Anchor *)\nInductive as_index: Type :=\n| One : as_index\n| Zero: as_index.\n\nInductive as_order: as_index -> as_index -> Type :=\n| order: as_order Zero One.\n\nLemma wfounded: well_founded as_order.\nProof.\n  unfold well_founded. intros a. constructor. intros y H. inv H. constructor. intros y H. inv H.\nQed.\n\nLemma trans: Relation_Definitions.transitive _ as_order.\nProof.\n  unfold Relation_Definitions.transitive. intros x y z H H0. inv H. inv H0.\nQed.\n\n\n(** * The match_states relation  *)\n(* This proof is a backward internal simulation.\n   At the Anchor instruction, we take a stuttering step if the Assume succeeds\n   If it fails, we take a single step to the target version.\n\n<<\n                 \n       st1 --------------- st2\n        |                   |\n       t|(1 or 2 steps)     |t\n        |                   |\n        v                   v\n       st1'--------------- st2'\n                 \n>>\n*)\n\nInductive match_states (p:program) (v:version) (fid:fun_id) (guard: expr) (ancl:label) (params:list reg): as_index -> mixed_state -> mixed_state -> Prop :=\n                                        \n| assume_match:                     (* matching at the assume instruction *)\n    forall vins stk stk' top heap rm fresh fa la vm next (* newver *) newrm abs\n      (MATCHSTACK: (match_stack v fid guard ancl params) stk stk')\n      (OPT: insert_assume_version v fid guard ancl params = OK vins)\n      (DEFREGS: defined_regs_analysis (ver_code v) params (ver_entry v) = Some abs)\n      (DEF: defined rm (def_absstate_get ancl abs))\n      (VALIDATE: validator v ancl guard params = OK tt)\n      (FS_OPT: (ver_code vins) # ancl = Some (Anchor (fa,la) vm fresh))\n      (AS_OPT: (ver_code vins) # fresh = Some (Assume guard (fa,la) vm next))\n      (FS_SRC: (ver_code v) # ancl = Some (Anchor (fa,la) vm next))\n      (* (FINDF: find_base_version fa p = Some newver) *)\n      (UPDATE: update_regmap vm rm = OK newrm),\n      (match_states p v fid guard ancl params) Zero\n        (Halt_IR (v, ancl, rm), mkmut stk top heap)\n        (Halt_IR (vins, fresh, rm), mkmut stk' top heap)\n      \n| opt_match:           (* matching inside the optimized version *)\n    forall vins stk stk' top heap lbl rm abs\n      (MATCHSTACK: (match_stack v fid guard ancl params) stk stk')\n      (OPT: insert_assume_version v fid guard ancl params = OK vins)\n      (DEFREGS: defined_regs_analysis (ver_code v) params (ver_entry v) = Some abs)\n      (DEF: defined rm (def_absstate_get lbl abs)),\n      (match_states p v fid guard ancl params) One\n        (Halt_IR (v, lbl, rm), mkmut stk top heap)\n        (Halt_IR (vins, lbl, rm), mkmut stk' top heap)\n                                        \n| refl_match:                   (* matching outside of the optimized version *)\n    forall synchro stk stk' top heap\n      (MATCHSTACK: (match_stack v fid guard ancl params) stk stk'),\n      (match_states p v fid guard ancl params) Zero (synchro, mkmut stk top heap) (synchro, mkmut stk' top heap).\n                                        \n(* | final_match:                  (* matching final states -> should be taken care of by refl*) *)\n(*     forall retval ms, *)\n(*       (match_states p v fid guard ancl params) One (Final retval ms) (Final retval ms). *)\n\n(** * Code preservation properties  *)\nLemma code_preservation':\n  forall vsrc vins fid guard ancl lbl params,\n    insert_assume_version vsrc fid guard ancl params = OK vins ->\n    lbl <> ancl ->\n    forall iopt isrc,\n      (ver_code vins) # lbl = Some iopt ->\n      (ver_code vsrc) # lbl = Some isrc ->\n      iopt = isrc.\nProof.\n  intros vsrc vins fid guard ancl lbl params OPT NOTFS iopt isrc CODEOPT CODESRC.\n  unfold insert_assume_version in OPT. repeat do_ok.\n  destruct (c!ancl) eqn:CODEFS; inv H1. destruct i; inv H0. repeat do_ok. destruct u.\n  simpl in CODEOPT. inv HDO.\n  poseq_destr (fresh_sug (Pos.succ ancl) (ver_code vsrc)) lbl.\n  - erewrite fresh_sug_correct in CODESRC; auto. inv CODESRC.\n  - rewrite PTree.gso in CODEOPT; auto. rewrite PTree.gso in CODEOPT; auto.\n    rewrite CODESRC in CODEOPT. inv CODEOPT. auto.\nQed.\n\nLemma safe_step_ir:\n  forall p rtl nc anc ms v pc rm,\n    safe (mixed_sem p rtl nc anc) (Halt_IR (v, pc, rm), ms) ->\n    exists t s', (mixed_step anc p rtl nc) (Halt_IR (v, pc, rm), ms) t s'.\nProof.\n  intros p rtl nc anc ms v pc rm H. specialize (H (Halt_IR (v,pc,rm), ms) (star_refl _ _ _)).\n  destruct H as [[r FINAL]|[t [s'' STEP]]]; eauto. inv FINAL.\nQed.\n\nLemma safe_step:\n  forall p rtl nc anc synchro ms,\n    safe (mixed_sem p rtl nc anc) (synchro, ms) ->\n    (exists t s', (mixed_step anc p rtl nc) (synchro, ms) t s') \\/ (exists r, synchro = EOE r).\nProof.\n  intros p rtl nc anc synchro ms H.\n  specialize (H (synchro, ms) (star_refl _ _ _)). destruct H as [[r FINAL]|[t [s'' STEP]]]; eauto. inv FINAL.\n  right. eauto.\nQed.\n\nLemma step_code_ir:\n  forall p rtl nc anc v pc rm ms news t,\n    Step (mixed_sem p rtl nc anc) (Halt_IR (v, pc, rm), ms) t news ->\n    exists i, (ver_code v) ! pc = Some i.\nProof.\n  intros. inv H; eauto.\n  unfold ir_step in STEP. repeat sdo_ok. unfold ir_int_step in HDO. repeat sdo_ok. eauto.\nQed.\n\n\nLemma safe_code:\n  forall p rtl nc anc s v pc rm ms top,\n    safe (mixed_sem p rtl nc anc) (Halt_IR (v, pc, rm), mkmut s top ms) ->\n    exists i, (ver_code v) ! pc = Some i.\nProof.\n  intros. apply safe_step_ir in H as [s' [t STEP]].\n  eapply step_code_ir; simpl; eauto.\nQed.\n\n\nLemma code_preservation:        (* use at opt_match *)\n  forall p p' rtl nc s s' rm top ms t news vsrc vins fid guard ancl lbl params,\n    insert_assume_version vsrc fid guard ancl params = OK vins ->\n    lbl <> ancl ->\n    safe (mixed_sem p rtl nc AnchorOn) (Halt_IR (vsrc, lbl, rm), mkmut s top ms) ->\n    Step (mixed_sem p' rtl nc AnchorOn) (Halt_IR (vins, lbl, rm), mkmut s' top ms) t news ->\n    (ver_code vsrc) # lbl = (ver_code vins) # lbl.\nProof.\n  intros p p' rtl nc s s' rm top ms t news vsrc vins fid guard ancl lbl params H H0 H1 H2.\n  apply safe_code in H1 as [isrc CODESRC]. apply step_code_ir in H2 as [iopt CODEOPT].\n  rewrite CODESRC. rewrite CODEOPT. f_equal. symmetry. eapply code_preservation'; eauto.\nQed.\n\n(* The anchor instruction has been changed to point to the Assume *)\nLemma anchor_changed:\n  forall vsrc fid guard vins ancl params,\n    insert_assume_version vsrc fid guard ancl params = OK vins ->\n    exists tgt vm fresh next,\n      (ver_code vins) # ancl = Some (Anchor tgt vm fresh) /\\\n      (ver_code vsrc) # ancl = Some (Anchor tgt vm next) /\\\n      (ver_code vins) # fresh = Some (Assume guard tgt vm next).\nProof.\n  intros vsrc fid guard vins ancl params OPT. unfold insert_assume_version in OPT. repeat do_ok.\n  inv HDO. destruct ((ver_code vsrc)!ancl) eqn:FS_SRC; inv H1.\n  destruct i eqn:ANCHOR; inv H0. repeat do_ok. exists d. exists v.\n  exists (fresh_sug (Pos.succ ancl) (ver_code vsrc)). exists l. simpl.\n  split; auto; try split; auto. \n  - poseq_destr (fresh_sug (Pos.succ ancl) (ver_code vsrc)) ancl.\n    + erewrite fresh_sug_correct in FS_SRC; eauto. inv FS_SRC.\n    + rewrite PTree.gso; auto. rewrite PTree.gss. auto.\n  - rewrite PTree.gss. auto.\nQed.\n\n\nLemma preservation_code:\n  forall vsrc vins fid guard ancl lbl params i,\n    insert_assume_version vsrc fid guard ancl params = OK vins ->\n    lbl <> ancl ->\n    (ver_code vsrc) # lbl = Some i ->\n    (ver_code vins) # lbl = Some i.\nProof.\n  intros vsrc vins fid guard ancl lbl params i H H0 H1. unfold insert_assume_version in H. repeat do_ok.\n  destruct (c!ancl) eqn:CODEFS. 2: inv H2. destruct i0; inv H2. repeat do_ok. simpl. inv HDO.\n  rewrite PTree.gso. rewrite PTree.gso; auto. poseq_destr lbl (fresh_sug (Pos.succ ancl) (ver_code vsrc)); auto.\n  erewrite fresh_sug_correct in H1; auto. inv H1.\nQed.\n  \n\n(** * Progress Preservation  *)\nLemma evaluate_reg:\n  forall rm rs r,\n    defined rm (DefFlatRegset.Inj rs) ->\n    check_reg r rs = true ->\n    exists v, eval_reg r rm = OK v.\nProof.\n  intros rm rs r H H0.\n  unfold check_reg in H0. rewrite PositiveSet.mem_spec in H0.\n  unfold defined in H. apply H in H0. destruct H0. exists x. unfold eval_reg. rewrite H0. auto.\nQed.\n\nLemma evaluate_expr:\n  forall rm rs e,\n    defined rm (DefFlatRegset.Inj rs) ->\n    check_expr e rs = true ->\n    exists v, eval_expr e rm = OK v.\nProof.\n  intros rm rs e H H0. destruct e; simpl in H0.\n  - assert (H': exists v, eval_reg r rm = OK v /\\ exists v0, eval_reg r0 rm = OK v0).\n    { destruct b; try solve[inv H0]; apply andb_prop in H0; destruct H0; eauto;\n        eapply evaluate_reg in H0; eapply evaluate_reg in H1; eauto; destruct H0; destruct H1; eauto. }\n    destruct H' as [v [EV [v' EV']]]. destruct b; simpl; rewrite EV; rewrite EV'; simpl; eauto.\n    inv H0.\n  - eapply evaluate_reg in H0; eauto. destruct H0. destruct u; simpl; rewrite H0; simpl; eauto.\n  - destruct z; simpl; eauto.\nQed.\n\nLemma base_version_set_version:\n  forall vins f,\n    fn_base (set_version_function vins f) = fn_base f.\nProof.\n  intros vins f. unfold set_version_function. simpl. auto.\nQed.\n\nLemma current_version_set_version:\n  forall vins f,\n    current_version (set_version_function vins f) = vins.\nProof.\n  intros vins f. unfold set_version_function, current_version. simpl. auto.\nQed.\n\n\n\n\n(* Evaluating a guard if it uses defined registers should be defined *)\n(* Lemma evaluate_succeeds: *)\n(*   forall rm guard rs, *)\n(*     defined rm (DefFlatRegset.Inj rs) -> *)\n(*     check_guard guard rs = true -> *)\n(*     exists v, eval_list_expr guard rm v. *)\n(* Proof. *)\n(*   intros rm guard rs H H0. induction guard; intros. *)\n(*   - exists true. constructor. *)\n(*   - simpl in H0. apply andb_prop in H0. destruct H0. eapply evaluate_expr in H0; eauto. *)\n(*     destruct H0. destruct x. apply IHguard in H1. destruct H1. destruct z. *)\n(*     + esplit. eapply eval_cons_false; eauto. *)\n(*     + esplit. eapply eval_cons_true; eauto. unfold Zne. unfold not. intro. inv H1; inv H2. *)\n(*     + esplit. eapply eval_cons_true; eauto. unfold Zne. unfold not. intro. inv H1; inv H2. *)\n(* Qed. *)\n(* DEPRECATED until we use lists *)\n\nLtac def_ok :=\n  match goal with\n  | [CODE: (ver_code ?vsrc) ! ?lbl = Some ?i |- _] =>\n    eapply def_analyze_correct; eauto; simpl; auto; unfold def_dr_transf; try rewrite CODE; auto\n  end.\n\nLemma progress_preserved:\n  forall f vsrc vins fid guard ancl params s1 s2 p nc i,\n    insert_assume_version vsrc fid guard ancl params = OK vins ->\n    find_function_ir fid p = Some f ->\n    vsrc = current_version f ->\n    match_states p vsrc fid guard ancl params i s1 s2 ->\n    safe (mixed_sem p None nc AnchorOn) s1 ->\n    (exists r : Integers.Int.int, final_mixed_state (set_version p fid vins) s2 r) \\/\n    (exists (t : trace) (s2' : mixed_state),\n        Step (mixed_sem (set_version p fid vins) None nc AnchorOn) s2 t s2').\nProof.\n  intros f vsrc vins fid guard ancl params s1 s2 p nc i OPTV FINDOPT CURVER MATCH SAFE.\n  inv MATCH.\n  - unfold validator in VALIDATE. rewrite FS_SRC in VALIDATE. repeat do_ok.\n    destruct (def_absstate_get ancl d) eqn:ABSDR; inv H0.\n    destruct (check_expr guard r) eqn:CHECK; inv H1.\n    inv DEFREGS. rewrite ABSDR in DEF. eapply evaluate_expr in CHECK as [v EVAL]; eauto.\n    right. exists E0. rewrite OPT in OPTV. inv OPTV. destruct (bool_of_int v) eqn:BOOL.\n    + econstructor. apply IR_step. unfold ir_step. rewrite exec_bind2. unfold sbind2, sbind.\n      unfold ir_int_step. rewrite AS_OPT. simpl. rewrite exec_bind. unfold sbind, fret'.\n      rewrite EVAL. simpl. rewrite BOOL. simpl. eauto.\n    + econstructor. apply IR_step. unfold ir_step. rewrite exec_bind2. unfold sbind2, sbind.\n      unfold ir_int_step. rewrite AS_OPT. simpl. rewrite exec_bind. unfold sbind, fret'.\n      rewrite EVAL. simpl. rewrite BOOL. rewrite UPDATE. simpl. eauto.\n      \n  - poseq_destr lbl ancl.\n    + rewrite OPT in OPTV. inv OPTV. unfold insert_assume_version in OPT. repeat do_ok.\n      destruct (c!ancl) eqn:CODEFS; inv H1. destruct i; inv H0.\n      right. exists E0. exists (Halt_IR (vins, (fresh_sug (Pos.succ ancl) c), rm), mkmut stk' top heap). \n      repeat do_ok. simpl. destruct d as [ftgt ltgt].\n      apply safe_step_ir in SAFE as STEP. destruct STEP as [t [s'' STEP]].\n      inv HDO. inv STEP.\n      * exfalso. eapply ir_noanchor in STEP0; eauto.\n      * rewrite ANCHOR in CODEFS. inv CODEFS. eapply Anchor_go_on; eauto. simpl. rewrite PTree.gso.\n        rewrite PTree.gss. eauto. unfold not; intros H.\n        symmetry in H. apply fresh_sug_correct in H. rewrite H in ANCHOR. inv ANCHOR.\n      * rewrite ANCHOR in CODEFS. inv CODEFS. eapply Anchor_go_on; eauto. simpl. rewrite PTree.gso.\n        rewrite PTree.gss. eauto. unfold not; intros H.\n        symmetry in H. apply fresh_sug_correct in H. rewrite H in ANCHOR. inv ANCHOR.\n      \n    + apply safe_step_ir in SAFE as STEP. destruct STEP as [t [s'' STEP]].\n      right. rewrite OPT in OPTV. inv OPTV.\n      apply safe_code in SAFE. destruct SAFE as [i CODESRC].\n      eapply preservation_code in HEQ as SAME_CODE; eauto. \n      inv STEP.\n      * exists t. unfold ir_step in STEP0. repeat sdo_ok. unfold ir_int_step in HDO.\n        rewrite CODESRC in HDO. repeat sdo_ok. inv HDO1.\n        { destruct i0; repeat sdo_ok.\n          - econstructor. eapply IR_step. unfold ir_step, ir_int_step. rewrite SAME_CODE. simpl. eauto.\n          - econstructor. eapply IR_step. unfold ir_step, ir_int_step. rewrite SAME_CODE. simpl.\n            unfold fret'. rewrite HDO. simpl. eauto.\n          - poseq_destr f0 fid.\n            + simpl in HDO. repeat sdo_ok.\n              unfold n_push_interpreter_stackframe in HDO0. simpl in HDO0. destruct top; inv HDO0.\n              econstructor. eapply IR_step. unfold ir_step, ir_int_step. rewrite SAME_CODE. simpl.\n              unfold sbind. unfold n_push_interpreter_stackframe. simpl. rewrite HDO. simpl. eauto.\n            + simpl in HDO. repeat sdo_ok.\n              unfold n_push_interpreter_stackframe in HDO0. simpl in HDO0. destruct top; inv HDO0.\n              econstructor. eapply IR_step. unfold ir_step, ir_int_step. rewrite SAME_CODE. simpl.\n              unfold sbind. unfold n_push_interpreter_stackframe. simpl. rewrite HDO. simpl. eauto.\n          - destruct (bool_of_int i) eqn:BOOL; repeat sdo_ok.\n            + econstructor. eapply IR_step. unfold ir_step, ir_int_step. rewrite SAME_CODE. simpl.\n              rewrite HDO1. simpl. rewrite BOOL. simpl. eauto.\n            + econstructor. eapply IR_step. unfold ir_step, ir_int_step. rewrite SAME_CODE. simpl.\n              rewrite HDO1. simpl. rewrite BOOL. simpl. eauto.\n          - econstructor. eapply IR_step. unfold ir_step, ir_int_step. rewrite SAME_CODE. simpl.\n            rewrite HDO. simpl. eauto.\n          - econstructor. eapply IR_step. unfold ir_step, ir_int_step. rewrite SAME_CODE. simpl.\n            rewrite HDO. simpl. eauto.\n          - econstructor. eapply IR_step. unfold ir_step, ir_int_step. rewrite SAME_CODE. simpl.\n            rewrite HDO1. simpl. rewrite HDO. simpl. unfold sbind. unfold n_memset in HDO2.\n            unfold n_memset. destruct (Integers.Int.lt i mem_size). inv HDO2. eauto. inv HDO2.\n          - econstructor. eapply IR_step. unfold ir_step, ir_int_step. rewrite SAME_CODE. simpl.\n            rewrite HDO. simpl. unfold sbind. unfold n_memget in HDO1.\n            unfold n_memget. destruct (Integers.Int.lt i mem_size). inv HDO1. 2: inv HDO1.\n            simpl. destruct (heap ! (intpos.pos_of_int i)); inv H0. eauto.\n          - destruct d. repeat sdo_ok. destruct (bool_of_int i) eqn:BOOL; repeat sdo_ok.\n            + econstructor. eapply IR_step. unfold ir_step, ir_int_step. rewrite SAME_CODE. simpl.\n              rewrite HDO1. simpl. rewrite BOOL. simpl. eauto.\n            + econstructor. eapply IR_step. unfold ir_step, ir_int_step. rewrite SAME_CODE. simpl.\n              rewrite HDO1. simpl. rewrite BOOL. simpl. rewrite HDO. simpl. eauto.\n          - destruct d. repeat sdo_ok. inv HDO. }\n\n      * exists E0. rewrite CODESRC in ANCHOR. inv ANCHOR.\n        exists (Halt_IR (vins, next, rm), mkmut stk' top heap). eapply Anchor_go_on; eauto.\n      * exists E0. rewrite CODESRC in ANCHOR. inv ANCHOR.\n        exists (Halt_IR (vins, next, rm), mkmut stk' top heap). eapply Anchor_go_on; eauto.\n                  \n  - apply safe_step in SAFE. destruct SAFE as [[t [s'' STEP]]| [r FINAL]].\n    2: { inv FINAL. left. exists r. constructor. }\n    right. inv STEP.\n    + destruct ms1. eapply addstk_same in STEP0 as [s [APP SAME]]; eauto.\n      2: apply addstk_irstep.\n      exists t. econstructor. eapply IR_step. simpl. eauto.\n    + destruct ms1. eapply addstk_same in STEP0 as [s [APP SAME]]; eauto.\n      2: apply addstk_asmstep.\n      exists t. econstructor. eapply x86_step. simpl. eauto.\n    + econstructor. econstructor. eapply rtl_step; eauto.\n    + destruct ms2, ms3. eapply addstk_same in CALLEE as [s [APP SAME]]; eauto.\n      2: apply addstk_callee.\n      eapply addstk_prim_same in NOT_COMPILED as [stk2 [APP2 SAME2]]; try constructor.\n      apply app_same in APP2. subst.\n      eapply addstk_same in ARGS as [s3 [APP3 SAME3]]; eauto.\n      2: apply addstk_get_args.\n      poseq_destr fid fid0.\n      * econstructor. econstructor.\n        eapply Call_IR with (func:=set_version_function vins func) (ver:=vins); eauto.\n        unfold set_version, set_version_funlist. simpl. rewrite GETF. rewrite PTree.gss. auto.\n      * econstructor. econstructor.\n        eapply Call_IR; eauto. unfold set_version, set_version_funlist. simpl.\n        unfold find_function_ir in FINDOPT. rewrite FINDOPT. rewrite PTree.gso; auto.\n    + destruct ms2, ms3, ms4. eapply addstk_same in CALLEE as [s [APP SAME]]; eauto.\n      2: apply addstk_callee.\n      eapply addstk_prim_same in COMPILED as [stk2 [APP2 SAME2]]; try constructor.\n      apply app_same in APP2. subst.\n      eapply addstk_same in ARGS as [stk3 [APP3 SAME3]]. 2: apply addstk_set_args. subst.\n      eapply addstk_prim_same in LOAD as [stk4 [APP4 SAME4]]; try constructor. subst.\n      exists E0. econstructor. eapply Call_x86; eauto.\n    + inv RTL. \n    + inv RTL_BLOCK. \n    + destruct ms1. unfold jit.get_retval in RETVAL. destruct loc eqn:LOC.\n      * destruct top eqn:TOP; inv RETVAL.\n        simpl in OPEN_SF. unfold n_open_stackframe in OPEN_SF. simpl in OPEN_SF.\n        destruct state_stacktop; inv OPEN_SF.\n        inv MATCHSTACK; inv H0. destruct sf; inv H1.\n        2: { destruct a, p, p0, p. inv H0. }\n        inv MSF.\n        ** econstructor. econstructor. eapply Return_IR; eauto.\n           simpl. unfold sbind. simpl. eauto.\n           simpl. unfold n_open_stackframe. simpl. eauto.\n        ** econstructor. econstructor. eapply Return_IR; eauto.\n           simpl. unfold sbind. simpl. eauto.\n           simpl. unfold n_open_stackframe. simpl. eauto.\n      * inv RETVAL.\n        simpl in OPEN_SF. unfold n_open_stackframe in OPEN_SF. simpl in OPEN_SF.\n        destruct state_stacktop; inv OPEN_SF.\n        inv MATCHSTACK; inv H0. destruct sf; inv H1.\n        2: { destruct a, p, p0, p. inv H0. }\n        inv MSF.\n        ** econstructor. econstructor. eapply Return_IR; eauto.\n           simpl. unfold sbind. simpl. eauto.\n           simpl. unfold n_open_stackframe. simpl. eauto.\n        ** econstructor. econstructor. eapply Return_IR; eauto.\n           simpl. unfold sbind. simpl. eauto.\n           simpl. unfold n_open_stackframe. simpl. eauto.\n    + destruct loc.\n      * simpl in RETVAL.  repeat sdo_ok.  unfold n_load in HDO. simpl in HDO.\n        destruct top; inv HDO.\n        simpl in OPEN_SF. unfold n_open_stackframe in OPEN_SF. simpl in OPEN_SF.\n        destruct top; inv OPEN_SF. destruct stk; inv H0. destruct s; inv H1.\n        destruct a, p, p0, p. inv H0. inv MATCHSTACK. inv MSF.\n        simpl in SET_RETVAL. unfold n_save in SET_RETVAL. inv SET_RETVAL.\n        simpl in LOAD_CONT. repeat sdo_ok. unfold n_load_prog_code in HDO. simpl in HDO.\n        destruct (nc ! (intpos.pos_of_int caller_fid)) eqn:LOADC; inv HDO.\n        destruct a. simpl in LOAD_CONT.\n        destruct (t ! (intpos.pos_of_int cont_lbl)) eqn:LOAD; inv LOAD_CONT.\n        econstructor. econstructor. eapply Return_x86.\n        ** simpl. unfold sbind. unfold n_load. simpl. eauto.\n        ** simpl. unfold n_open_stackframe. simpl. eauto.\n        ** simpl. unfold n_save. simpl. eauto.\n        ** simpl. unfold sbind. unfold n_load_prog_code. simpl. rewrite LOADC. simpl. rewrite LOAD. eauto.\n        ** eauto.\n      * inv RETVAL. simpl in OPEN_SF. unfold n_open_stackframe in OPEN_SF. simpl in OPEN_SF.\n        destruct top; inv OPEN_SF. destruct stk; inv H0. destruct s; inv H1.\n        destruct a, p, p0, p. inv H0. inv MATCHSTACK. inv MSF.\n        simpl in SET_RETVAL. unfold n_save in SET_RETVAL. inv SET_RETVAL.\n        simpl in LOAD_CONT. repeat sdo_ok. unfold n_load_prog_code in HDO. simpl in HDO.\n        destruct (nc ! (intpos.pos_of_int caller_fid)) eqn:LOADC; inv HDO.\n        destruct a. simpl in LOAD_CONT.\n        destruct (t ! (intpos.pos_of_int cont_lbl)) eqn:LOAD; inv LOAD_CONT.\n        econstructor. econstructor. eapply Return_x86.\n        ** simpl. auto.\n        ** simpl. unfold n_open_stackframe. simpl. eauto.\n        ** simpl. unfold n_save. simpl. eauto.\n        ** simpl. unfold sbind. unfold n_load_prog_code. simpl. rewrite LOADC. simpl. rewrite LOAD. eauto.\n        ** eauto.\n    + inv RTL. \n    + inv RTL_BLOCK. \n    + destruct loc.\n      * destruct top; inv RETVAL. inv OPEN_SF. unfold n_open_stackframe in H0. simpl in H0.\n        destruct top; inv H0. destruct stk; inv H1.\n        2: { destruct s; inv H0. destruct a, p, p0, p; inv H1. }\n        inv MATCHSTACK. econstructor. econstructor. eapply Return_EOE; eauto.\n        simpl. unfold sbind. simpl. eauto.\n        simpl. unfold n_open_stackframe. simpl. eauto.\n      * inv RETVAL. inv OPEN_SF. unfold n_open_stackframe in H0. simpl in H0.\n        destruct top; inv H0. destruct stk; inv H1.\n        2: { destruct s; inv H0. destruct a, p, p0, p; inv H1. }\n        inv MATCHSTACK. econstructor. econstructor. eapply Return_EOE; eauto.\n        simpl. unfold sbind. simpl. eauto.\n        simpl. unfold n_open_stackframe. simpl. eauto.\n    + destruct ms1, ms2. eapply addstk_same in TARGET as [s [APP SAME]].\n      2: apply addstk_target.\n      eapply addstk_same in BUILD_RM as [s2 [APP2 SAME2]].\n      2: apply addstk_build.\n      poseq_destr fid ftgt.\n      * econstructor. econstructor. eapply Deopt; eauto.\n        unfold set_version, set_version_funlist. simpl. unfold find_function_ir in FINDOPT. rewrite FINDOPT.\n        rewrite PTree.gss; auto.\n      * econstructor. econstructor. eapply Deopt; eauto.\n        unfold set_version, set_version_funlist. simpl. unfold find_function_ir in FINDOPT. rewrite FINDOPT.\n        rewrite PTree.gso; eauto.\n    + destruct ms1. eapply addstk_same in PRIM_CALL as [s [APP SAME]].\n      2: { unfold ASMinterpreter.prim_sem_dec. repeat addstk_auto. }\n      econstructor. econstructor. eapply RTL_prim; eauto.\n    + econstructor. econstructor. eapply RTL_end; eauto.\n    + econstructor. econstructor. eapply RTL_block_end; eauto.\n    + econstructor. econstructor. eapply Anchor_go_on; eauto.\n    + econstructor. econstructor. eapply Anchor_deopt; eauto.\nQed.\n\n(** * The Internal Backward Simulation  *)\nTheorem assume_insertion_correct:\n  forall p nc fid guard fs_lbl newp,\n    insert_assume fid guard fs_lbl p = OK newp ->\n    backward_internal_simulation p newp None None nc nc AnchorOn AnchorOn.\nProof.\n  intros p nc fid guard fs_lbl newp OPT. unfold insert_assume in OPT. repeat do_ok.\n  rename HDO1 into FINDOPTF. rename v into vins. set (vsrc:=current_version f).\n  assert (OPTV: insert_assume_version vsrc fid guard fs_lbl (fn_params f) = OK vins) by auto.\n  unfold insert_assume_version in HDO0. repeat do_ok. inv HDO. destruct u.\n  set (c:=ver_code vsrc).  rename HDO0 into VALIDATE. fold vsrc in VALIDATE.\n  fold vsrc in H1. fold c in H1. destruct (c!fs_lbl) eqn:CODE_FS; inv H1.\n  destruct i; inv H0. repeat do_ok. rename d into tgt. rename v into vm_fs. rename l into next_fs.\n  rename HDO0 into CODE_NEXT.\n  set (vins := {| ver_code := (c # fs_lbl <- (Anchor tgt vm_fs (fresh_sug (Pos.succ fs_lbl) c))) #  (fresh_sug (Pos.succ fs_lbl) c) <- (Assume guard tgt vm_fs next_fs); ver_entry := ver_entry vsrc |}). fold vins in OPTV.\n  apply Backward_internal_simulation with (bsim_order:=as_order) (bsim_match_states:=match_states p vsrc fid guard fs_lbl (fn_params f)).\n  - apply wfounded.\n  - unfold call_refl. unfold p_reflexive. intros s H. inv H. exists Zero. destruct ms. apply refl_match.\n    apply match_stack_same.\n\n  - intros. inv H1. inv H. econstructor. split. apply star_refl. constructor.\n\n  - intros. eapply progress_preserved; eauto. \n\n  - intros s2 t s2' STEP i0 s1 MATCH SAFE.\n    inv MATCH.\n\n    + rewrite OPT in OPTV. inv OPTV. (* assume_match *)\n      inv STEP.\n      2: { rewrite ANCHOR in AS_OPT. inv AS_OPT. }\n      2: { rewrite ANCHOR in AS_OPT. inv AS_OPT. }\n      simpl in STEP0. unfold ir_step, ir_int_step in STEP0.\n      rewrite AS_OPT in STEP0. simpl in STEP0. repeat sdo_ok.\n      destruct (bool_of_int i0) eqn:GUARD. inv HDO.\n      * exists One. econstructor. split.    (* Assume holds *)\n        ** left. apply plus_one. eapply Anchor_go_on; eauto.\n        ** simpl. eapply opt_match; eauto.\n           eapply def_analyze_correct; eauto. simpl; auto. unfold def_dr_transf. rewrite FS_SRC. auto.\n      * repeat sdo_ok. exists Zero. econstructor. split. (* Assume fails *)\n        ** left. apply plus_one. eapply Anchor_deopt; eauto.\n        ** simpl. eapply refl_match. auto.\n        \n    + rewrite OPT in OPTV. inv OPTV. (* opt_match *)\n      poseq_destr lbl fs_lbl.\n      (* We are at the anchor used for insertion*)\n      { assert (OPT': insert_assume_version vsrc fid guard fs_lbl (fn_params f)= OK vins) by auto.\n        apply anchor_changed in OPT as [[fa la][vm [fresh [next [CODE_INS_FS [CODE_SRC_FS CODE_INS_AS]]]]]].\n        unfold c in CODE_FS. rewrite CODE_FS in CODE_SRC_FS. inv CODE_SRC_FS. inv STEP.\n        - unfold ir_step, ir_int_step in STEP0. rewrite CODE_INS_FS in STEP0. simpl in STEP0. inv STEP0.\n        - rewrite ANCHOR in CODE_INS_FS. inv CODE_INS_FS.\n        (* The Anchor goes on in OPT. In SRC, it will depend on how the Assume evaluates *)\n        (* So we take a stuttering step in the SRC *)\n          exists Zero. econstructor. split.\n          + right. split. apply star_refl. constructor.\n          + eapply assume_match; eauto.\n        - rewrite ANCHOR in CODE_INS_FS. inv CODE_INS_FS.\n        (* The Anchor deopts in both OPT and SRC *)\n          exists Zero. econstructor. split.\n          + left. apply plus_one. eapply Anchor_deopt; eauto.\n          + eapply refl_match; eauto. }\n      \n      (* We are not at the Anchor used for insertion *)\n      { eapply code_preservation in OPT as SAME_CODE; eauto.\n        inv STEP.\n        - unfold ir_step, ir_int_step in STEP0. repeat sdo_ok. destruct p0 as [t it].\n          destruct i0; repeat sdo_ok.\n          + exists One. econstructor. split.\n            * left. apply plus_one. eapply IR_step. unfold ir_step, ir_int_step.\n              rewrite SAME_CODE. simpl. eauto.\n            * simpl. eapply opt_match; eauto. def_ok. rewrite SAME_CODE. auto.\n          + exists One. econstructor. split.\n            * left. apply plus_one. eapply IR_step. unfold ir_step, ir_int_step.\n              rewrite SAME_CODE. simpl. rewrite HDO. simpl. eauto.\n            * eapply opt_match; eauto. def_ok. rewrite SAME_CODE. auto.\n\n          + simpl in HDO. repeat sdo_ok. unfold n_push_interpreter_stackframe in HDO0.\n            simpl in HDO0. destruct top; inv HDO0.\n            exists Zero. econstructor. split.\n            * left. apply plus_one. eapply IR_step; eauto. unfold ir_step, ir_int_step.\n              rewrite SAME_CODE. simpl. unfold sbind. unfold n_push_interpreter_stackframe.\n              simpl. rewrite HDO. simpl. eauto.\n            * simpl. eapply refl_match; eauto. constructor; auto.\n              eapply frame_opt; eauto. intros. def_ok. rewrite SAME_CODE. apply define_insert. auto.\n          + destruct (bool_of_int i0) eqn:BOOL; repeat sdo_ok.\n            * exists One. econstructor. split.\n              ** left. apply plus_one. eapply IR_step. unfold ir_step, ir_int_step.\n                 rewrite SAME_CODE. simpl. rewrite HDO2. simpl. rewrite BOOL. simpl. eauto.\n              ** eapply opt_match; eauto. def_ok. rewrite SAME_CODE. auto.\n            * exists One. econstructor. split.\n              ** left. apply plus_one. eapply IR_step. unfold ir_step, ir_int_step.\n                 rewrite SAME_CODE. simpl. rewrite HDO2. simpl. rewrite BOOL. simpl. eauto.\n              ** eapply opt_match; eauto. def_ok. rewrite SAME_CODE. auto.\n          + exists Zero. econstructor. split.\n            * left. apply plus_one. eapply IR_step. unfold ir_step, ir_int_step.\n              rewrite SAME_CODE. simpl. rewrite HDO. simpl. eauto.\n            * simpl. eapply refl_match; eauto.\n          + exists One. econstructor. split.\n            * left. apply plus_one. eapply IR_step. unfold ir_step, ir_int_step.\n              rewrite SAME_CODE. simpl. rewrite HDO. simpl. eauto.\n            * eapply opt_match; eauto. def_ok. rewrite SAME_CODE. apply define_insert. auto.\n          + unfold n_memset in HDO3. destruct (Integers.Int.lt i0 mem_size) eqn:RANGE; inv HDO3.\n            exists One. econstructor. split.\n            * left. apply plus_one. eapply IR_step. unfold ir_step, ir_int_step.\n              rewrite SAME_CODE. simpl. rewrite HDO. simpl. rewrite HDO2. simpl.\n              unfold n_memset. rewrite RANGE. unfold sbind. simpl. eauto.\n            * eapply opt_match; eauto. def_ok. rewrite SAME_CODE. auto.\n          + unfold n_memget in HDO2. destruct (Integers.Int.lt i0 mem_size) eqn:RANGE; inv HDO2.\n            destruct (heap ! (intpos.pos_of_int i0)) eqn:HEAP; inv H0.\n            exists One. econstructor. split.\n            * left. apply plus_one. eapply IR_step. unfold ir_step, ir_int_step.\n              rewrite SAME_CODE. simpl. rewrite HDO. simpl. \n              unfold n_memget. rewrite RANGE. unfold sbind. simpl. rewrite HEAP. eauto.\n            * eapply opt_match; eauto. def_ok. rewrite SAME_CODE. apply define_insert. auto.\n          + destruct d. repeat sdo_ok. destruct (bool_of_int i0) eqn:BOOL; repeat sdo_ok.\n            * exists One. econstructor. split.\n              ** left. apply plus_one. eapply IR_step. unfold ir_step, ir_int_step.\n                 rewrite SAME_CODE. simpl. rewrite HDO2. simpl. rewrite BOOL. simpl. eauto.\n              ** eapply opt_match; eauto. def_ok. rewrite SAME_CODE. auto.\n            * exists Zero. econstructor. split.\n              ** left. apply plus_one. eapply IR_step. unfold ir_step, ir_int_step.\n                 rewrite SAME_CODE. simpl. rewrite HDO2. simpl. rewrite BOOL. rewrite HDO. simpl. eauto.\n              ** simpl. eapply refl_match; eauto.\n          + destruct d. inv HDO.\n        \n        - exists One. econstructor. split.\n          + left. apply plus_one. eapply Anchor_go_on; eauto. rewrite SAME_CODE. apply ANCHOR.\n          + eapply opt_match; eauto. clear CODE_NEXT CODE_FS. def_ok. rewrite ANCHOR in SAME_CODE.\n            eauto. simpl; auto. rewrite SAME_CODE. rewrite ANCHOR. auto.\n        - exists Zero. econstructor. split.\n          + left. apply plus_one. eapply Anchor_deopt; eauto. rewrite SAME_CODE. eauto.\n          + eapply refl_match. auto.\n      }\n            \n\n    + { inv STEP.                 (* refl_match *)\n        - destruct ms1. eapply addstk_same in STEP0 as [s [APP SAME]]; eauto.\n          2: apply addstk_irstep.\n          exists Zero. econstructor. split.\n          + left. apply plus_one. eapply IR_step; eauto.\n          + apply refl_match. subst. apply app_match; auto. apply match_stack_same.\n        - destruct ms1. eapply addstk_same in STEP0 as [s [APP SAME]]; eauto.\n          2: apply addstk_asmstep.\n          exists Zero. econstructor. split.\n          + left. apply plus_one. eapply x86_step; eauto.\n          + apply refl_match. subst. apply app_match; auto. apply match_stack_same.\n        - exists Zero. econstructor. split.\n          + left. apply plus_one. eapply rtl_step; eauto.\n          + apply refl_match; auto.\n        - unfold find_function_ir in FINDOPTF.\n          unfold set_version, set_version_funlist in GETF. simpl in GETF. rewrite FINDOPTF in GETF.\n          poseq_destr fid fid0.\n          +                     (* Calling the optimized function *)\n            destruct ms2. eapply addstk_same in CALLEE as [s [APP SAME]].\n            2: apply addstk_callee.\n            simpl in NOT_COMPILED. unfold n_check_compiled in NOT_COMPILED. simpl in NOT_COMPILED.\n            destruct (nc!fid0) eqn:NOT; inv NOT_COMPILED.\n            destruct ms3. eapply addstk_same in ARGS as [s2 [APP2 SAME2]].\n            rewrite PTree.gss in GETF. inv GETF.\n            2: apply addstk_get_args.\n            exists One. econstructor. split.\n            * left. apply plus_one. eapply Call_IR; eauto; simpl.\n              ** unfold n_check_compiled. simpl. rewrite NOT. eauto.\n            * unfold validator in VALIDATE. fold c in VALIDATE. rewrite CODE_FS in VALIDATE. repeat do_ok.\n              simpl.  rewrite current_version_set_version. eapply opt_match; eauto.\n              ** apply app_match. apply app_match; auto. apply match_stack_same. apply match_stack_same.\n              ** eapply def_analyze_init; eauto.\n          +   (* calling another function *)\n            rewrite PTree.gso in GETF; auto.\n            destruct ms2. eapply addstk_same in CALLEE as [s [APP SAME]].\n            2: apply addstk_callee.\n            simpl in NOT_COMPILED. unfold n_check_compiled in NOT_COMPILED. simpl in NOT_COMPILED.\n            destruct (nc!fid0) eqn:NOT; inv NOT_COMPILED.\n            destruct ms3. eapply addstk_same in ARGS as [s2 [APP2 SAME2]].\n            2: apply addstk_get_args.\n            exists Zero. econstructor. split.\n            * left. apply plus_one. eapply Call_IR; eauto; simpl.\n              ** unfold n_check_compiled. simpl. rewrite NOT. eauto.\n            * eapply refl_match. subst. apply match_app. apply match_app. auto.\n        - destruct loc.\n          + simpl in CALLEE. repeat sdo_ok. unfold n_load in HDO. simpl in HDO. destruct top; inv HDO.\n            simpl in COMPILED. unfold n_check_compiled in COMPILED. simpl in COMPILED.\n            destruct (nc ! (intpos.pos_of_int i0)) eqn:COMP; inv COMPILED.\n            destruct ms3. eapply addstk_same in ARGS as [s [APP SAME]]; eauto.\n            2: apply addstk_set_args.\n            simpl in LOAD. repeat sdo_ok. unfold n_load_prog_code in HDO. simpl in HDO.\n            rewrite COMP in HDO. inv HDO.\n            exists Zero. econstructor. split.\n            * left. apply plus_one. eapply Call_x86; eauto; simpl.\n              ** unfold n_load, sbind. simpl. eauto.\n              ** unfold n_check_compiled. simpl. rewrite COMP. eauto.\n              ** unfold n_load_prog_code, sbind. simpl. rewrite COMP. eauto.\n            * eapply refl_match. apply app_match; auto. apply match_stack_same.\n          + simpl in CALLEE. inv CALLEE.\n            simpl in COMPILED. unfold n_check_compiled in COMPILED. simpl in COMPILED.\n            destruct (nc ! fid0) eqn:COMP; inv COMPILED.\n            destruct ms3. eapply addstk_same in ARGS as [s [APP SAME]]; eauto.\n            2: apply addstk_set_args.\n            simpl in LOAD. repeat sdo_ok. unfold n_load_prog_code in HDO. simpl in HDO.\n            rewrite COMP in HDO. inv HDO.\n            exists Zero. econstructor. split.\n            * left. apply plus_one. eapply Call_x86; eauto; simpl.\n              ** unfold n_load, sbind. simpl. eauto.\n              ** unfold n_check_compiled. simpl. rewrite COMP. eauto.\n              ** unfold n_load_prog_code, sbind. simpl. rewrite COMP. eauto.\n            * eapply refl_match. apply app_match; auto. apply match_stack_same.\n        - inv RTL. \n        - inv RTL_BLOCK. \n        - destruct loc.\n          + simpl in RETVAL; repeat sdo_ok. unfold n_load in HDO. simpl in HDO. destruct top; inv HDO.\n            simpl in OPEN_SF. unfold n_open_stackframe in OPEN_SF. simpl in OPEN_SF.\n            destruct top; inv OPEN_SF. destruct stk'; inv H0. destruct s; inv H1.\n            2: { destruct a,p,p0,p. inv H0. }\n            inv MATCHSTACK. inv MSF.\n            * exists Zero. econstructor. split. (* Returning to the same function *)\n              ** left. apply plus_one. eapply Return_IR; eauto.\n                 *** simpl. unfold n_load, sbind. simpl. eauto.\n                 *** simpl. unfold n_open_stackframe. simpl. eauto.\n              ** eapply refl_match; eauto.\n            * exists One. econstructor. split. (* Returning to the optimized IR *)\n              ** left. apply plus_one. eapply Return_IR; eauto.\n                 *** simpl. unfold n_load, sbind. simpl. eauto.\n                 *** simpl. unfold n_open_stackframe. simpl. eauto.\n              ** eapply opt_match; eauto.\n          + simpl in RETVAL. inv RETVAL.\n            simpl in OPEN_SF. unfold n_open_stackframe in OPEN_SF. simpl in OPEN_SF.\n            destruct top; inv OPEN_SF. destruct stk'; inv H0. destruct s; inv H1.\n            2: { destruct a,p,p0,p. inv H0. }\n            inv MATCHSTACK. inv MSF.\n            * exists Zero. econstructor. split. (* Returning to the same function *)\n              ** left. apply plus_one. eapply Return_IR; eauto.\n                 *** simpl. eauto.\n                 *** simpl. unfold n_open_stackframe. simpl. eauto.\n              ** eapply refl_match; eauto.\n            * exists One. econstructor. split. (* Returning to the optimized IR *)\n              ** left. apply plus_one. eapply Return_IR; eauto.\n                 *** simpl. eauto.\n                 *** simpl. unfold n_open_stackframe. simpl. eauto.\n              ** eapply opt_match; eauto.\n        - destruct loc.\n          + simpl in RETVAL. repeat sdo_ok. unfold n_load in HDO. simpl in HDO. destruct top; inv HDO.\n            simpl in OPEN_SF. unfold n_open_stackframe in OPEN_SF. simpl in OPEN_SF.\n            destruct top; inv OPEN_SF. destruct stk'; inv H0. destruct s; inv H1. destruct a, p, p0, p.\n            inv H0. simpl in SET_RETVAL. unfold n_save in SET_RETVAL. simpl in SET_RETVAL. inv SET_RETVAL.\n            simpl in LOAD_CONT. repeat sdo_ok. destruct a.\n            unfold n_load_prog_code in HDO. simpl in HDO. destruct (nc!(intpos.pos_of_int caller_fid)) eqn:LOAD; inv HDO.\n            simpl in LOAD_CONT.\n            destruct (t!(intpos.pos_of_int cont_lbl)) eqn:LOAD2; inv LOAD_CONT.\n            inv MATCHSTACK. inv MSF.\n            exists Zero. econstructor. split.\n            * left. apply plus_one. eapply Return_x86; eauto; simpl.\n              ** unfold n_load, sbind. simpl. eauto.\n              ** unfold n_open_stackframe. simpl. eauto.\n              ** unfold n_save. simpl. eauto.\n              ** unfold n_load_prog_code, sbind. simpl.  rewrite LOAD. simpl. rewrite LOAD2. eauto.\n            * eapply refl_match. auto.\n          + simpl in RETVAL. inv RETVAL.\n            simpl in OPEN_SF. unfold n_open_stackframe in OPEN_SF. simpl in OPEN_SF.\n            destruct top; inv OPEN_SF. destruct stk'; inv H0. destruct s; inv H1. destruct a, p, p0, p.\n            inv H0. simpl in SET_RETVAL. unfold n_save in SET_RETVAL. simpl in SET_RETVAL. inv SET_RETVAL.\n            simpl in LOAD_CONT. repeat sdo_ok. destruct a.\n            unfold n_load_prog_code in HDO. simpl in HDO. destruct (nc!(intpos.pos_of_int caller_fid)) eqn:LOAD; inv HDO.\n            simpl in LOAD_CONT.\n            destruct (t!(intpos.pos_of_int cont_lbl)) eqn:LOAD2; inv LOAD_CONT.\n            inv MATCHSTACK. inv MSF.\n            exists Zero. econstructor. split.\n            * left. apply plus_one. eapply Return_x86; eauto; simpl.\n              ** unfold n_load, sbind. simpl. eauto.\n              ** unfold n_open_stackframe. simpl. eauto.\n              ** unfold n_save. simpl. eauto.\n              ** unfold n_load_prog_code, sbind. simpl.  rewrite LOAD. simpl. rewrite LOAD2. eauto.\n            * eapply refl_match. auto.\n        - inv RTL. \n        - inv RTL_BLOCK. \n        - destruct loc.\n          + simpl in RETVAL. repeat sdo_ok. unfold n_load in HDO. simpl in HDO. destruct top; inv HDO.\n            simpl in OPEN_SF. unfold n_open_stackframe in OPEN_SF. simpl in OPEN_SF.\n            destruct top; inv OPEN_SF. destruct stk'; inv H0.\n            2: { destruct s; inv H1. destruct a, p, p0, p. inv H0. }\n            inv MATCHSTACK.\n            exists Zero. econstructor. split.\n            * left. apply plus_one. eapply Return_EOE; eauto; simpl.\n              ** unfold n_load, sbind. simpl. eauto.\n              ** unfold n_open_stackframe. simpl. eauto.\n            * eapply refl_match; eauto. constructor.\n          + simpl in RETVAL. inv RETVAL.\n            simpl in OPEN_SF. unfold n_open_stackframe in OPEN_SF. simpl in OPEN_SF.\n            destruct top; inv OPEN_SF. destruct stk'; inv H0.\n            2: { destruct s; inv H1. destruct a, p, p0, p. inv H0. }\n            inv MATCHSTACK.\n            exists Zero. econstructor. split.\n            * left. apply plus_one. eapply Return_EOE; eauto; simpl.\n              ** unfold n_load, sbind. simpl. eauto.\n              ** unfold n_open_stackframe. simpl. eauto.\n            * eapply refl_match; eauto. constructor.\n        - destruct ms1, ms2. eapply addstk_same in TARGET as [s [APP SAME]]; eauto.\n          2: apply addstk_target.\n          eapply addstk_same in BUILD_RM as [s2 [APP2 SAME2]]; eauto.\n          2: apply addstk_build.\n          unfold find_function_ir in FINDOPTF.\n          unfold set_version, set_version_funlist in FINDF. simpl in FINDF.\n          rewrite FINDOPTF in FINDF.\n          poseq_destr ftgt fid.\n          + exists Zero. econstructor. split.\n            * left. apply plus_one. eapply Deopt; eauto; simpl.\n            * rewrite PTree.gss in FINDF. inv FINDF. rewrite base_version_set_version.\n              eapply refl_match; eauto. apply match_app. apply match_app. auto.\n          + exists Zero. econstructor. split.\n            * left. apply plus_one. eapply Deopt; eauto; simpl.\n              ** rewrite PTree.gso in FINDF; eauto.\n            * eapply refl_match; eauto. subst. apply match_app. apply match_app. auto.\n        - destruct ms1. eapply addstk_same in PRIM_CALL as [s [APP SAME]].\n          2: { unfold ASMinterpreter.prim_sem_dec. repeat addstk_auto. }\n          exists Zero. econstructor. split.\n          + left. apply plus_one. eapply RTL_prim; eauto.\n          + eapply refl_match. subst. apply match_app. auto.\n        - exists Zero. econstructor. split.\n          + left. apply plus_one. eapply RTL_end; eauto.\n          + eapply refl_match. auto.\n        - exists Zero. econstructor. split.\n          + left. apply plus_one. eapply RTL_block_end; eauto.\n          + eapply refl_match. auto.\n        - exists Zero. econstructor. split.\n          + left. apply plus_one. eapply Anchor_go_on; eauto.\n          + eapply refl_match. auto.\n        - exists Zero. econstructor. split.\n          + left. apply plus_one. eapply Anchor_deopt; eauto.\n          + eapply refl_match. auto.\n      }\nQed.\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/assume_insertion_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2555906741345592}}
{"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. \nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(*\n\nI'm not sure whether the I/O automata is the right model for this\ntask. Perhaps, we shoudl instead rethink the model in terms of\ncall/receive automata, which are similar to Disel's protocols in a way\nthey handle message passing. The only difference is that here we don't\nhave consider several communicating nodes, and instead work with just\none.\n\nThus, only \"well-formed\" messages get reacted to.\n\nFurthermore, any transition can end with zero to n send messages\n(i.e., calls), which will be sent in a non-deterministic order.\n\nThis should give enough space to implement the systems of\ncommunicating contracts.\n\nNext, we can proceed on making assertions for composing contracts ans\nbuild on the research from the I/O automata community.\n\nFinally, we will have to come up with a way to represent SC automata\nin a language with exceptions and cost semantics, and compile it down\nto EVM.\n\n*)\n\n(* Implementation of a simple state *)\n\nSection State.\n\nDefinition value_type := nat.\nDefinition acc_id_type := nat.\nDefinition method_tag_type := nat.\nDefinition payload_type := (seq (nat * seq nat)).\n\n(* Message with a payload *)\nRecord message :=\n  Msg { value : value_type;\n        sender : acc_id_type;\n        method_tag : method_tag_type;\n        payload :  payload_type\n    }.\n\n(* State of a contract *)\nRecord cstate (T : Type) :=\n  CState {\n      acc_id : acc_id_type;\n      balance : value_type;\n      state : T  \n    }.\n\nEnd State.\n\nSection Protocol.\n\n(* Protocol operates on states of a predefined type T *)\n\nSection Transitions.\n\n(* State type *)\nVariable S: Type.\n\nDefinition input_filter_type := message -> cstate S -> bool.\n\nDefinition resp_type :=\n  (acc_id_type * value_type * method_tag_type * payload_type)%type.\n\nDefinition msg_bal (rt : resp_type) : value_type := rt.1.1.2.\nDefinition msg_bals outs := sumn (map msg_bal outs).\n\nDefinition trans_rel_type (input_filter : input_filter_type) :=\n  forall m st1, input_filter m st1 ->\n         forall (s2 : S) (outs : seq resp_type), Prop.\n\n(* Contract transition in the spirit of I/O automata *)\nRecord ctransition :=\n  CTrans {\n      (* Unique tag of a transition in the protocol *)\n      tag : method_tag_type;\n      \n      (* Decidable filter on incoming messages *)\n      input_filter : input_filter_type;\n\n      (* Relation between input and output state *)\n      trans_rel : trans_rel_type input_filter;\n    }.\n\nEnd Transitions.\n\nRecord Protocol (S : Type) :=\n  CProt {\n      (*Account id *)\n      acc_num : nat;\n      (* Initial balance *)\n      init_bal : nat;\n      (* Initial state of a protocol *)\n      init_state : S;      \n      (* Protocol comes with a set of transitions *)\n      transitions : seq (ctransition S);\n      (* All transitions have unique tags *)\n      _ : uniq (map (@tag _) transitions)\n    }.\n\n(* TODO: Should we also say something about exclusivity of\n         transition's preconditions? *)\n\n(* TODO: Next, a program will have to be shown to refine a\n         corresponding protocol. *)\n\nEnd Protocol.\n\n(***********************************************************)\n(***              Protocol properties                    ***)\n(***********************************************************)\n\nSection Invariants.\n\nVariable (S : Type) (p : Protocol S).\n\nNotation s0 := (init_state p).\nNotation acc := (acc_num p).\nNotation b0 := (init_bal p).\nNotation trans := (transitions p).\n\n(* Definition of an inductive invariant with respect to a protocol p *)\n(* Notice that the invariant updates the balance *)\n\nNotation State := (cstate S).\n\nDefinition inductive (I : State -> Prop) :=\n  (* A. Invariant holds in the initial state *)\n  I (CState acc b0 s0) /\\ \n  (* B. Any transition preserves the invariant *)\n  forall ts, ts \\In transitions p ->\n  forall st1, I st1 ->\n    forall m (pf : input_filter ts m st1) s2 outs,\n    trans_rel pf s2 outs ->\n  let bal' := (balance st1) - (msg_bals outs) + (value m) in\n  I (CState acc bal' s2).\n\n(* Here we assume that we always dispatch the messages, i.e., one\n   cannot just transfer us money. *)\n\n(* Determining whether we can reach s2 from s1 in one step *)\nDefinition can_step (st1 st2 : State) :=\n  let: CState acc b1 s1 := st1 in\n  exists ts m (pf : input_filter ts m st1) outs s2,\n    [/\\ ts \\In transitions p,\n     trans_rel pf s2 outs &\n     let b2 := b1 - (msg_bals outs) + (value m) in\n     st2 = CState acc b2 s2].\n  \nFixpoint reachable' st1 st2 n :=\n  if n is n'.+1\n  then exists st, can_step st1 st /\\ reachable' st st2 n'\n  else st1 = st2.\n\nDefinition reachable st1 st2 := exists n, reachable' st1 st2 n.\n\n(*****************************************************)\n(*            Some modal connectives                 *)\n(*****************************************************)\n\n(* q holds since p becomes true *)\nDefinition since (p : State -> Prop) (q : State -> State -> Prop) :=\n  forall st, p st -> forall st', reachable st st'-> q st st'.\n\n(* TODO: can we come up with more sorts of invariants that have\n   somewhat \"temporal flavour?\", e.g., in the spirit of eventual\n   consistency. For instance, one should be able to prove that it's\n   possible to withdraw money from th eaccount. *)\n\nEnd Invariants.\n\n(*************************************\n\nGreat story for compositionality: verify the \"library\" and then link\nanother contract against it and show that the joined interaction\nalways produces the same traces as it were only a client contract with\ninternal function.\n\nThis is still not equivalent to the usual execution because of limited\nstack size. Thus, a call to library contract can fail, even if\neverything is implemented correctly!\n\nWow.\n\nJust wow.\n\n **************************************)\n\n(************\n\nSome more things to discuss or implement in the future:\n\n* Formulate other sorts invariants for outgoing messages.\n\n* Do we have to model the return value explicitly, or can we just\n  represent it via message passing?\n\n* How to fomulate the property that shouldn't be violated by the\n  Puzzle contract from the Luu-al:CCS'16 paper?\n\n  Perhaps, for this, we need a more \"Concurrent\" semantics, in which\n  message sends are disparate from the corresponding contracts.\n\n* Formalize the protocol of KoET contract and state the trace property\n  that a previous king always gets correctly reimbursed. This would\n  require to state properties over interactions between several\n  parties.\n\n* Start discussing a compiler from a back-end, verified with respect\n  to a protocol.\n\n*)\n\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/Core/Automata.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2555906741345592}}
{"text": "\n\nRequire Import String. Import StringSyntax.          \nFrom Ling Require Import BSm2. \nImport Ling.\nFrom Ling Require Import Parasitic.\nFrom Ling Require Import Covariance.\n\n\n(* John scratched his arm, and bob did too *)\n\n(* An analysis of sloppy identity that's similar to the covariance one *)\n\nDefinition scratched : TV := mkTV \"scratched\".\n\nParameter Of : DP -> DP -> DP.\n\n\nDefinition his : (DP >> S) || S -- (DP / DP) :=\n  (fun k x => k (fun y => Of x y)).\n\nDefinition arm : DP := e \"arm\".\nDefinition bob : DP := e \"bob\".\n\n(* strict reading *)\nEval compute in (lower ((lower (bind (lift john) <| ant1 (lift scratched |> (his |> lift arm))))\n         <| (lift and |> (FOC bob <| did)))).\n\n\n(* sloppy reading *)\n\nEval compute in (lower ((lower (lift john <| (ant0 (fill_dp (lift scratched |> (his |> lift arm)))))) <| (lift and |> (FOC bob <| did)))).\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/SI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.25559067413455916}}
{"text": "Require Import  Algebra.Utils Algebra.SetoidCat Algebra.Monad Algebra.Monoid  Algebra.Alternative Algebra.NearSemiRing  Algebra.Monad.ContT Algebra.Alternative Algebra.Functor Algebra.Applicative PairUtils SetoidUtils Tactics Algebra.SetoidCat.UnitUtils Algebra.Monoid.ArrUtils Algebra.Monad.Utils.\n\nRequire Import RelationClasses Relation_Definitions Morphisms SetoidClass.\n\nOpen Scope type_scope.\n\n\n  \n\nSection StoreHeap.\n  Context\n    {H : Type} {SH : Setoid H}\n    {R : Type} {SR : Setoid R}\n    {l lS}\n    {alt : @Alternative l lS}\n  .\n\n  Definition storeHeap A {AS} := SH ~> SR ~~> SH ~*~ lS (R * A) (SR ~*~ AS).\n  Instance storeHeapS {A} AS : Setoid (@storeHeap A AS) := SH ~~> SR ~~> SH ~*~ lS (R * A) (SR ~*~ AS).\n\n  Definition sh {B} (BS : Setoid B) A {SA : Setoid A} := contT BS (@storeHeapS) A.\n  Definition shS {B}  (BS : Setoid B) { A} (SA : Setoid A):= contTS BS (@storeHeapS) SA.\n\n  Definition runSh {A B} {SA : Setoid A} {BS : Setoid B} : shS BS SA ~> (SA ~~> storeHeapS BS) ~~> storeHeapS BS := runContT.\n\n  Existing Instance contT_Monad.\n  \n  Definition storeHeap_empty {A} {AS : Setoid A} : storeHeap A.\n    simple refine (injF (fun h : H => constS SR @ (h, empty)) _).\n    exact lS.\n    exact alt.\n    Lemma storeHeap_empty_1: forall {A} {AS : Setoid A}, Proper (equiv ==> equiv) (fun h : H => constS SR @ (h, empty)).\n    Proof.\n      intros. solve_proper.\n    Qed.\n    apply storeHeap_empty_1.\n  Defined.\n\n  Definition storeHeap_append {A} {AS : Setoid A} : storeHeapS AS ~> storeHeapS AS ~~> storeHeapS AS.\n    simple refine (injF4 (fun (s1 s2 : storeHeap A) h r =>\n                           let (h', l1) := s1 @ h @ r in\n                           let (h'', l2) := s2 @ h' @ r in\n                           (h'', l1 <|> l2)) _).\n    exact lS.\n    exact alt.\n    Lemma storeHeap_append_1 : forall {A} {AS : Setoid A}, Proper (equiv ==> equiv ==> equiv ==> equiv ==> equiv)\n     (fun (s1 s2 : storeHeap A) (h : H) (r : R) =>\n      let (h', l1) := s1 @ h @ r in\n      let (h'', l2) := s2 @ h' @ r in (h'', l1 <|> l2)).\n    Proof.\n      autounfold. intros. simpl_let. split. rewritesr. rewritesr.\n    Qed.\n    apply storeHeap_append_1.\n  Defined.\n\n  Instance storeHeap_Alternative : @Alternative (@storeHeap) (@storeHeapS).\n  Proof.\n    exists (@storeHeap_empty) (@storeHeap_append).\n    intros. simpl. arrequiv. simpl_let. destruct (a @ a0 @ a1). rewrite left_unit_alt. split. reflexivity. reflexivity.\n    intros. simpl. arrequiv. simpl_let. destruct (a @ a0 @ a1). rewrite right_unit_alt. split. reflexivity. reflexivity.\n    intros. simpl. arrequiv. simpl_let. destruct (a @ a0 @ a1). simpl. destruct (b @ h @ a1).  simpl. split . reflexivity. rewrite associativity_alt. reflexivity.\n  Defined. \n  \n  Instance sh_Monad {B} {BS : Setoid B} : @Monad (@sh B BS) (@shS B BS) := contT_Monad BS (@storeHeapS).\n\n  Instance sh_Alternative {B} {BS : Setoid B} : @Alternative (@sh B BS) (@shS B BS) := contT_Alternative BS (@storeHeapS).\n\n  Context\n    {func : @Functor l lS}\n    {app : @Applicative l lS func}.\n\n  Definition getStore  {B} {BS : Setoid B} : sh BS R.\n    simple refine (injF3 (fun (c : SR ~> storeHeapS BS) (h : H) (s : R)  => c @ s @ h @ s) _).\n    Lemma getStore_1 : forall {B} {BS : Setoid B}, Proper (equiv ==> equiv ==> equiv ==> equiv)\n                                 (fun (c : SR ~> storeHeapS BS) (h : H) (s : R) => c @ s @ h @ s).\n    Proof.\n      intros. solve_proper.\n    Qed.\n    apply getStore_1.\n  Defined.\n\n  Definition getHeap  {B} {BS : Setoid B} : sh BS H.\n    simple refine (injF3 (fun (c : SH ~> storeHeapS BS) (h : H) (s : R)  => c @ h @ h @ s) _).\n    Lemma getHeap_1 : forall {B} {BS : Setoid B}, Proper (equiv ==> equiv ==> equiv ==> equiv)\n                                 (fun (c : SH ~> storeHeapS BS) (h : H) (s : R) => c @ h @ h @ s).\n    Proof.\n      intros. solve_proper.\n    Qed.\n    apply getHeap_1.\n  Defined.\n\n  Definition putStore  {B} {BS : Setoid B} : SR ~> shS BS unitS.\n    simple refine (injF4 (fun (s : R) (c : unitS ~> storeHeapS BS) (h : H) (_ : R)  => c @ tt @ h @ s) _).\n    Lemma putStore_1 : forall {B} {BS : Setoid B}, Proper (equiv ==> equiv ==> equiv ==> equiv ==> equiv)\n     (fun (s : R) (c : unitS ~> storeHeapS BS) (h : H) (_ : R) =>\n      c @ tt @ h @ s).\n    Proof.\n      autounfold. intros. rewritesr. \n    Qed.\n    apply putStore_1.\n  Defined.\n  \n  Definition updateStore {B} {BS : Setoid B} : (SR ~~> SR) ~> shS BS unitS := (bind @ getStore) ∘ (flipS @ compS @ putStore).  \n             \n  Definition putHeap  {B} {BS : Setoid B} : SH ~> shS BS unitS.\n    simple refine (injF4 (fun (h : H) (c : unitS ~> storeHeapS BS) (_ : H) (s : R)  => c @ tt @ h @ s) _).\n    Lemma putHeap_1 : forall {B} {BS : Setoid B}, Proper (equiv ==> equiv ==> equiv ==> equiv ==> equiv)\n     (fun (h : H) (c : unitS ~> storeHeapS BS) (_ : H) (s : R) =>\n      c @ tt @ h @ s).\n    Proof.\n      autounfold. intros. rewritesr. \n    Qed.\n    apply putHeap_1.\n  Defined.\n\n  Definition updateHeap {B} {BS : Setoid B} : (SH ~~> SH) ~> shS BS unitS := (bind @ getHeap) ∘ (flipS @ compS @ putHeap).  \n\n  Existing Instance arr_Monoid.\n  Existing Instance contT_A_Monoid.\n\n  Section Sh_SS_unitS_NearSemiRing.\n    Definition sh_times {S : Type} {SS : Setoid S} : shS SS unitS ~> shS SS unitS ~~> shS SS unitS := andThen.\n\n    Definition sh_plus {S : Type} {SS : Setoid S} : shS SS unitS ~> shS SS unitS ~~> shS SS unitS := mappend.\n\n    Definition sh_zero {S : Type} {SS : Setoid S} : sh SS unit := mempty.\n\n    Definition sh_one {S : Type} {SS : Setoid S}: sh SS unit := ret @ tt.\n\n    \n  Instance sh_NearSemiRing {S : Type} {SS : Setoid S} : @NearSemiRing _ (shS SS unitS).\n  Proof.\n    exists (sh_one) (sh_zero) (sh_times) (sh_plus).\n    intros. simpl. arrequiv.    \n    intros. unfold sh_times, sh_one. unfold andThen. normalizecomp. unfold constS. normalize. apply (@right_unit_equiv (sh SS) (@shS _ SS) sh_Monad). simpl. arrequiv. destruct a0. reflexivity.\n    intros. unfold sh_times. unfold andThen. normalizecomp. rewrite (@associativity (@sh S SS) (@shS _ SS) sh_Monad _ _ _ _ _ _ a (constS unitS @ b) (constS unitS @ c)). evalproper. simpl_equiv. reflexivity.\n    intros. apply left_unit_monoid.\n    intros. apply right_unit_monoid.\n    intros. apply associativity_monoid.\n    intros. simpl. arrequiv.\n    intros. unfold sh_times at 1. unfold sh_plus at 1.  unfold andThen. normalizecomp. rewrite (@contT_left_distributivity _ _ _ _ _ _ _ _ _ a b (constS _ @ c)). reflexivity.\n    Grab Existential Variables.\n    solve_proper.\n  Defined.\n  \nEnd Sh_SS_unitS_NearSemiRing.\n  (* Proof. *)\n\n  \n  (* Proof. *)\n\n(*  \n  \n  Lemma concatMapM_cons : forall m0 (mnd : @Monad m0) A B (SA : Setoid A) (SB : Setoid B) (f : SA ~> m (listS SB)) (a : A) (l : list A), concatMapM @ f @ (a :: l) == appProper <$> f @ a <*> concatMapM @ f @ l.\n  Proof.\n    intros. simpl. repeat rewrite associativity_2. bindproper. unfold compM, injF2. simpl. arrequiv.\nrewrite left_unit. simpl. normalize_monad. bindproper. normalize_monad.  reflexivity.\nGrab Existential Variables.\nsolve_proper.\nsolve_proper.\n  Qed.\n\n  Lemma sequence_map_ret : forall m0 (mnd : @Monad m0) A B (SA : Setoid A) (SB : Setoid B) (l : list A) (f : A -> B), sequence (map (fun a => ret @ f a) l) == ret @ map f l.  \n  Proof.\n    intros. induction l.\n    simpl. reflexivity.\n    intros. simpl. normalize_monad. rewrite IHl. rewrite left_unit. simpl. reflexivity.\n  Qed.\n\n  \n  Lemma concatMapM_ret : forall m0 (mnd : @Monad m0) A  (SA : Setoid A)  pr (l : list A) (s : H), injective (listS SA) (m (listS SA)) ret -> concatMapM @ injF (fun a => ret @ (a :: nil)) pr  == ret .\n  Proof.\n    intros. simpl. arrequiv. induction a. simpl. normalize_monad. reflexivity.\n    simpl. normalize_monad. rewrite <- associativity0. rewrite ret_ret. rewrite <- ret_ret with (f:=@concat A) (g:=app (a::nil)).\n    assert (forall pr, injF (fun a1 => ret @ concat a1) pr == ret ∘ concatProper). intros. apply fun_ext. intros. reflexivity. rewrite H1.\n    rewrite IHa. normalize_monad. reflexivity. solve_proper. solve_proper. solve_proper. solve_proper.\n    Grab Existential Variables.\n    solve_proper.\n    solve_proper.\n    solve_proper.\n    solve_proper.\n    solve_proper.\n  Qed.\n\n    Lemma concatMapM_nil : forall m0 (mnd : @Monad m0) A B (SA : Setoid A) (SB : Setoid B) (f : SA ~> m (listS SB)), concatMapM @ f @ nil == ret @ nil.\n  Proof.\n    intros. simpl. rewrite left_unit. simpl. reflexivity.\n  Qed. *)  \n\nEnd StoreHeap.\n", "meta": {"author": "xu-hao", "repo": "CertifiedQueryArrow", "sha": "8db512e0ebea8011b0468d83c9066e4a94d8d1c4", "save_path": "github-repos/coq/xu-hao-CertifiedQueryArrow", "path": "github-repos/coq/xu-hao-CertifiedQueryArrow/CertifiedQueryArrow-8db512e0ebea8011b0468d83c9066e4a94d8d1c4/Algebra/Monad/StoreHeap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.25559067413455916}}
{"text": "(* PREAMBLE *)\n\nFrom compcert.common             Require Events Builtins.\nFrom trancert.properties         Require State Env.\nFrom trancert.properties.memory  Require Alloc BindParameters Free.\nFrom trancert.analysis           Require StateQuant.\nFrom trancert.lib                Require All.\nFrom trancert.simulations.memory.bijection\n                                 Require Def AST Symbols.\n\n\nImport common.AST Coqlib Csyntax Csem Events compcert.common.Memory.Mem\n       compcert.common.Values properties.State Globalenvs Globalenvs.Genv\n       properties.Env StateQuant lib.All Builtins ContinuationQuant memory.Alloc\n       BindParameters bijection.Def bijection.AST bijection.Symbols.\n\nDefinition biject_extcall (sem: extcall_sem) (sg: signature) : Prop :=\n        forall ge1 ge2 vargs m1 t vres m2 M m1' vargs',\n          symbols_biject M ge1 ge2 ->\n          sem ge1 vargs m1 t vres m2 ->\n          biject M m1 m1' ->\n          list_forall2 (biject_value (m_fwd M)) vargs vargs' ->\n          exists M' vres' m2',\n                sem ge2 vargs' m1' t vres' m2'\n                /\\ mapping_evolve M M'\n                /\\ biject_value (m_fwd M) vres vres'\n                /\\ biject M' m2 m2'\n                /\\ unchanged_on (loc_unmapped (m_fwd M)) m1 m2\n                /\\ unchanged_on (loc_out_of_reach (m_fwd M) m1) m1' m2'\n                /\\ inject_separated (m_fwd M) (m_fwd M') m1 m1'\n                /\\ inject_separated (m_bwd M) (m_bwd M') m1' m1\n.\n\n(** This record is used as a hypothesis in our proofs. It states that both builtin functions and external functions satisfy the additional constraints introduced above. *)\n\nDefinition biject_extcall_axiom := forall ef, biject_extcall (external_call ef) (ef_sig ef).\n", "meta": {"author": "sayon", "repo": "trancert", "sha": "eb5c94c75067782158522f61bdd7cc902bf74185", "save_path": "github-repos/coq/sayon-trancert", "path": "github-repos/coq/sayon-trancert/trancert-eb5c94c75067782158522f61bdd7cc902bf74185/axioms/Biject.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2555669738401612}}
{"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 Actions.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* Framing with respect to the world *)\n\nModule Injection.\nSection Injection.\n\nVariable W : world.\n\nStructure injects (U V : world) (K : hooks) := Inject {\n  (* The \"delta world\" *)\n  E : world;\n                                       \n  _ : hook_complete U /\\ hook_complete E;\n\n  (* Additional hooks are included with an empty world *)\n  _ : V = U \\+ E \\+ (Unit, K);\n\n  (* Additional hooks are well-formed with respect to the world *)\n  _ : hooks_consistent (getc (U \\+ E)) K;\n  \n  (* These all should be easy to prove given a standard world disentanglement *)\n  _ : forall s, Coh V s <-> exists s1 s2,\n        [/\\ s = s1 \\+ s2, Coh U s1 & Coh E s2];\n\n  (* Framing wrt. worlds and hooks *)\n  _ : forall s1 s2 s this,\n      s1 \\+ s \\In Coh V -> network_step U this s1 s2 ->\n      network_step V this (s1 \\+ s) (s2 \\+ s);\n\n  _ : forall s1 s2 s1' s2' this,\n      s1 \\In Coh U -> s2 \\In Coh U ->\n      network_step V this (s1 \\+ s1') (s2 \\+ s2') ->\n      (network_step U this s1 s2   /\\ s1' = s2') \\/\n      (network_step E this s1' s2' /\\ s1 = s2); }.\n\nEnd Injection.\n\nModule Exports.\nSection Exports.\n\nDefinition inj_ext := E.\nDefinition injects := injects. \nDefinition Inject := Inject.\n\nLemma cohK (U V : world) (K : hooks) (w : injects U V K) :\n  V = U \\+ inj_ext w \\+ (Unit, K).\nProof. by case: w=>E/=. Qed.\n\nLemma cohE (U V : world) (K : hooks) (w : injects U V K) s :\n  Coh V s <-> exists s1 s2,\n      [/\\ s = s1 \\+ s2, Coh U s1 & Coh (inj_ext w) s2].\nProof. by case: w=>W ??? cohE sL sR; apply: cohE. Qed.\n\nLemma sem_extend (U V : world) (K : hooks) (w : injects U V K) s1 s2 s this: \n      s1 \\+ s \\In Coh V -> s2 \\+ s \\In Coh V ->\n      network_step U this s1 s2 -> network_step V this (s1 \\+ s) (s2 \\+ s).\nProof.\nby case: w=>W _ _ _ cohE sL sR C G; apply: sL=>//.\nQed.\n\nLemma sem_split (U V : world) (K : hooks) (w : injects U V K) s1 s1' s2 s2' this: \n      s1 \\In Coh U -> s2 \\In Coh U ->\n      network_step V this (s1 \\+ s1') (s2 \\+ s2') ->\n      (network_step U this s1 s2   /\\ s1' = s2') \\/\n      (network_step (inj_ext w) this s1' s2' /\\ s1 = s2).\nProof. by case: w=>W ??? cohE sl sR; apply: sR. Qed.\n\nDefinition extends (U V : world) (K : hooks) (w : injects U V K) s s1 := \n  exists s2, [/\\ s = s1 \\+ s2, s1 \\In Coh U & s \\In Coh V].\n\nNotation dom_filt W := (fun k => k \\in dom W).\n\n(* TODO: prove something about hooks K being irrelevant for coherence *)\n\n(* TODO: remove all irrelevant hooks *)\n\nDefinition projectS (W : world) (s : state) :=\n  um_filter (dom_filt (getc W)) s.\n\nLemma projectS_cohL W1 W2 s :\n  s \\In Coh (W1 \\+ W2) -> hook_complete W1 -> projectS W1 s \\In Coh W1.\nProof.\ncase=>V1 V2 G1 D H G2; split=>//; first by move/validL: V1.\n- by rewrite valid_umfilt.\n- move=>z; case B: (z \\in dom (getc W1)).\n  + by rewrite dom_umfilt !inE B/= -D/=domUn !inE B/=; case/andP:V1=>->.\n  by rewrite dom_umfilt !inE B.\nmove=>l; move: (H l)=>{H}H.\ncase B: (l \\in dom (getc W1)); last first.\n- rewrite /getProtocol /getStatelet; move: (B).\n  case: dom_find=>//-> _.\n  suff X: ~~(l \\in dom (projectS W1 s)) by case: dom_find X=>//-> _. \n  by rewrite /projectS dom_umfilt inE/= B.\nhave E1: find l s = find l (projectS W1 s).\n- by rewrite /projectS/= find_umfilt B.\nhave E2: getProtocol (W1 \\+ W2) l = getProtocol W1 l.\n  - rewrite /getProtocol findUnL//?B//.\n    by rewrite /valid/= in V1; case/andP: V1.\nby rewrite -E2 /getStatelet -E1 in H *.  \nQed.\n\nLemma projectS_cohR W1 W2 s :\n  s \\In Coh (W1 \\+ W2) -> hook_complete W2 -> projectS W2 s \\In Coh W2.\nProof. by rewrite joinC; apply: projectS_cohL. Qed.\n\nLemma projectSE W1 W2 s :\n  s \\In Coh (W1 \\+ W2) ->\n  s = projectS W1 s \\+ projectS W2 s.\nProof.\ncase=>Vw Vs G D H; rewrite /projectS.\nhave X: {in dom s, dom_filt (getc W2) =1 predD (dom_filt (getc W2)) (dom_filt (getc W1))}.\n- move=>z _/=; case I : (z \\in dom (W1.1 \\+ W2.1)).\n  + move: I; rewrite domUn !inE/==>/andP[V']/orP[]Z; rewrite Z/=.\n    - by case: validUn V'=>//_ _/(_ z Z)/=G' _;apply/negbTE. \n    rewrite joinC in V'; case: validUn V'=>//_ _/(_ z Z)G' _.\n    by rewrite andbC.\n  move: I; rewrite domUn inE/==>/negbT; rewrite negb_and negb_or/=.\n  have X: valid (W1 \\+ W2) by [].\n  by case/andP: X=>->/=_/andP[]->.\nrewrite (eq_in_umfilt X) -umfilt_predU/=; clear X.\nsuff X: {in dom s, predU (dom_filt (getc W1)) (dom_filt (getc W2)) =1 predT}.\n- by rewrite (eq_in_umfilt X) umfilt_predT. \nby move=>z; rewrite/= -D domUn inE=>/andP[].\nQed.\n\nLemma coh_split W1 W2 s :\n  s \\In Coh (W1 \\+ W2) ->\n  hook_complete W1 -> hook_complete W2 ->\n  exists s1 s2 : state,\n    [/\\ s1 \\In Coh W1, s2 \\In Coh W2 & s = s1 \\+ s2].\nProof.\nmove=>C G1 G2; move/projectSE: (C)->.\nexists (projectS W1 s), (projectS W2 s).\nsplit=>//; [by apply: projectS_cohL C G1| by apply: projectS_cohR C G2].\nQed.\n\nLemma injExtL' (W1 W2 : world) K (pf : injects W1 (W1 \\+ W2) K) :\n  valid (W1 \\+ W2) -> inj_ext pf \\+ (Unit, K) = W2.\nProof.\nmove=>H; case: pf=>W2' _ E/=_ _ _ _.\nrewrite -joinA in E.\ncase/andP: H=>H1 H2.\nrewrite /PCM.join/= in H1 H2 E *.\ncase: W2 H1 H2 E=>/=c2 h2 H1 H2 [E1 E2].\nby rewrite (joinxK H1 E1) (joinxK H2 E2).\nQed.\n\nLemma injExtR' W1 W2 K (pf : injects W2 (W1 \\+ W2) K) :\n  valid (W1 \\+ W2) -> inj_ext pf \\+ (Unit, K) = W1.\nProof.\nmove=>H; case: pf=>W2' _ E/= _ _ _ _.\nrewrite -(joinC W2) in E H.\ncase/andP: H=>H1 H2; rewrite -joinA in E.\nrewrite /PCM.join/= in H1 H2 E *.\ncase: W1 H1 H2 E=>/=c1 h1 H1 H2 [E1 E2].\nby rewrite (joinxK H1 E1) (joinxK H2 E2).\nQed.\n\nLemma injExtL W1 W2 (pf : injects W1 (W1 \\+ W2) Unit) :\n  valid (W1 \\+ W2) -> inj_ext pf = W2.\nProof. by move/(injExtL' pf); rewrite unitR. Qed.\n\nLemma injExtR W1 W2 (pf : injects W2 (W1 \\+ W2) Unit) :\n  valid (W1 \\+ W2) -> inj_ext pf  = W1.\nProof. by move/(injExtR' pf); rewrite unitR. Qed.\n\nEnd Exports.\nEnd Exports.\n\nEnd Injection.\n\nExport Injection.Exports.\n\nModule InjectExtra.\n\nLemma cohUnKR U W s s':\n  s \\+ s' \\In Coh (U \\+ W) -> s \\In Coh U ->\n  hook_complete W -> s' \\In Coh W.\nProof.\nmove=>H C G2; move: (cohH C) => G1.\nsuff X: s' = projectS W (s \\+ s').\n- by rewrite X; apply: (projectS_cohR H).\nsuff X: s = projectS U (s \\+ s').\n- move: (cohS H)=>V; move/projectSE: (H)=>E.\n  rewrite E in V.\n  rewrite {1}X in E.\n  by rewrite (joinxK V (sym_eq E)).\nrewrite /projectS.\nsuff X: {in dom (s \\+ s'), dom U.1 =i dom s}.\n- by rewrite (eq_in_umfilt X) umfilt_dom ?(cohS H)//.\nby move=>z _; move: (cohD C z); rewrite /in_mem.\nQed.\n\nLemma cohUnKL U W s s':\n  s \\+ s' \\In Coh (U \\+ W) -> s' \\In Coh W ->\n  hook_complete U -> s \\In Coh U .\nProof.\nby move=>H C G1; rewrite [U \\+ W]joinC [s\\+_]joinC in H; apply: (cohUnKR H).\nQed.\n\nLemma getPUn (U W : world) l :\n  valid (U \\+ W) -> l \\in dom U.1 ->\n  getProtocol U l = getProtocol (U \\+ W) l.\nProof.\nmove=>V; rewrite /getProtocol=>D.\ncase/andP: (V)=>V1 V2.\nby rewrite findUnL ?V1// D.\nQed.\n\nLemma getSUn s1 s2 l :\n  valid (s1 \\+ s2) -> l \\in dom s1 ->\n  getStatelet s1 l = getStatelet (s1 \\+ s2) l.\nProof.\nmove=>V; rewrite /getStatelet=>D.\nby rewrite findUnL ?V// D.\nQed.\n\nLemma hook_completeL (U : world) K :\n  valid (U \\+ (Unit, K)) ->\n  hook_complete (U \\+ (Unit, K)) -> hook_complete U.\nProof.\ncase: U=>c h=> V H z lc ls st D.\nmove: (H z lc ls st); rewrite domUn inE/= D/=.\ncase/andP: V=>_->/==>/(_ is_true_true)=>/andP[].\nby rewrite !unitR=>->->.\nQed.\n\nLemma get_protocol_hooks (U: world) K l:\n  valid U -> getProtocol (U \\+ (Unit, K)) l = getProtocol U l.\nProof.\nmove=>V; rewrite /getProtocol.\nby rewrite findUnR ?dom0 ?inE//; rewrite unitR; case/andP: V.\nQed.\n\nLemma coh_hooks (U : world) K s :\n  s \\In (Coh (U \\+ (Unit, K))) -> s \\In (Coh U).\nProof.\ncase=>V Vs Hk D L.\nsplit=>//; first by move/validL: V.\n- by apply: hook_completeL V Hk.\n- move=>z; rewrite -D domUn !inE/= unitR dom0 orbC/=.\n  by move/validL:V=>/andP[]->_.\nby move=>l; move: (L l); rewrite (get_protocol_hooks K l (validL V)).\nQed.\n\nLemma inj_hooks_complete (U W : world) K:\n  valid (U \\+ W \\+ (Unit, K)) ->\n  hook_complete U -> hook_complete W ->\n  hooks_consistent (U \\+ W).1 K ->\n  hook_complete (U \\+ W \\+ (Unit, K)).\nProof.\nmove=>V G1 G2 G.\nmove=>z lc ls st; rewrite domUn !inE/= !unitR.\nmove/andP: (V)=>[_]->/=; case/orP; last by move/G.\nrewrite !domUn !inE; case/validL/andP:V=>->->/=.\ncase/orP; first by case/G1/andP=>->->.\nby case/G2/andP=>->->; rewrite -!(orbC true).\nQed.\n\nLemma inject_step U W K this s1 s2 s1' s2' :\n  valid (U \\+ W) ->\n  s1 \\In Coh U -> s2 \\In Coh U ->\n  hook_complete U -> hook_complete W ->\n  network_step (U \\+ W \\+ (Unit, K)) this (s1 \\+ s1') (s2 \\+ s2') ->\n  network_step U this s1 s2 /\\ s1' = s2' \\/\n  network_step W this s1' s2' /\\ s1 = s2.\nProof.\nmove=>V C1 C2 Hu Hw S; move/step_coh: (S)=>[C1' C2'].\nmove: (cohW C1')=>V1.\nmove: (coh_hooks C1')(coh_hooks C2')=>{C1'}C1'{C2'}C2'.\nmove: (cohUnKR C1' C1 Hw) (cohUnKR C2' C2 Hw)=>D1 D2.\ncase: S; first 2 last.\n\n(* Receive Step *)\nmove=>l rt R i from H1.\nrewrite domUn inE=>/andP[Vs]/=/orP; case=>D C msg H2 [H3 H4]/=;\n[rewrite updUnL D|rewrite updUnR D]=>G;[left|right].\n- have X: s1' = s2'.\n  + move: (C2'); rewrite (joinC U) G -[upd _ _ _ \\+ s1'](joinC s1'). \n    move/cohUnKR/(_ D1)/(_ Hu)=>C1''.\n    move: (coh_prec (cohS C2') C2 C1'' G)=>Z; rewrite -Z in G; clear Z.\n    by rewrite (joinxK (cohS C2') G).\n  split=>//; subst s2'; rewrite -![_ \\+ s1'](joinC s1') in G C2'.\n  rewrite -[upd _ _ _ \\+ s1'](joinC s1') in G; rewrite (joinC U) in C2'.\n  move: (joinxK (cohS C2') G)=>{G}G. \n  have E: getProtocol U l = getProtocol (U \\+ W) l.\n    by rewrite (getPUn V)// (cohD C1).\n  have E': getStatelet s1 l = getStatelet (s1 \\+ s1') l.\n    by rewrite (getSUn (cohS C1')). \n  rewrite /get_rt /InMem/= in R. \n  move: (getStatelet (s1 \\+ s1') l) E' C (coh_s l C) H1 G H3 H4=>_<-_.\n  move: (getProtocol (U \\+ W \\+ (Unit, K)) l)\n        (get_protocol_hooks K l V) E rt R H2=>_-><-rt R H2 coh_s H1 G H3 H4.\n  apply: (ReceiveMsg R D H2 (i := i) (from := from) (s2 := s2) (C := C1)). \n  split=>//=; move: (NetworkSem.coh_s l C1)=>coh_s';\n  by rewrite -(pf_irr coh_s coh_s').\n\n(* Second part or receive-step *)\nmove: U W V {V1} Hw Hu s1 s2 s1' s2' C1 C2 C1' C2' D1 D2 rt H1 H2 Vs D C R H3 H4 G.\nmove=>W U V Hw Hu s1' s2' s1 s2 D1 D2.\nrewrite !(joinC W) -!(joinC s1) -!(joinC s2)=> C1' C2' C1 C2.\nmove=>rt H1 H2 Vs D C R H3 H4 G.\nhave X: s1' = s2'.\n- move: (C2'); rewrite (joinC U) G. \n  move/cohUnKR/(_ D1)/(_ Hw)=>C1''; rewrite (joinC s1') in G.\n  move: (coh_prec (cohS C2') C2 C1'' G)=>Z; rewrite -Z in G; clear Z.\n  by rewrite (joinxK (cohS C2') G).\nsplit=>//; subst s2'; rewrite -!(joinC s1') in G C2'.\nrewrite (joinC U) in C2'; move: (joinxK (cohS C2') G)=>{G}G.\nrewrite joinC in V.\nhave E: getProtocol U l = getProtocol (U \\+ W) l.\n  by rewrite (getPUn V)// (cohD C1).\nhave E': getStatelet s1 l = getStatelet (s1 \\+ s1') l.\n  by rewrite (getSUn (cohS C1')). \nrewrite /get_rt /InMem/= in R. \nmove: (getStatelet (s1 \\+ s1') l) E' C (coh_s l C) H1 G H3 H4=>_<-_.\nmove: (getProtocol (U \\+ W \\+ (Unit, K)) l)\n      (get_protocol_hooks K l V) E rt R H2=>_-><-rt R H2 coh_s H1 G H3 H4.\napply: (ReceiveMsg R D H2 (i := i) (from := from) (s2 := s2) (C := C1)). \nsplit=>//=; move: (NetworkSem.coh_s l C1)=>coh_s';\nby rewrite -(pf_irr coh_s coh_s').\n\n(* Idle Step *)\n- case=>_ E; move: (coh_prec (cohS C1') C1 C2 E)=>Z; subst s2.\n  rewrite (joinC U) (joinC s1) in C1'; rewrite !(joinC s1) in E.\n  move: (coh_prec (cohS C1') D1 D2 E)=>Z; subst s2'.\n  by left; split=>//; apply: Idle.\n\n(* Send Step *)\n- move=>l st H1 to msg h H2.\n  rewrite domUn inE=>/andP[Vs]/orP; case=> D _ S Hk H3;\n  [rewrite updUnL D|rewrite updUnR D]=>G;[left|right];\n  [| move: U W V1 Hu Hw V s1 s2 s1' s2' C1 C2 C1' C2' D1 D2 st Hk H1 H2 Vs D S H3 G;\n    move=> W U V1 Hw Hu V s1' s2' s1 s2 D1 D2 C1' C2' C1 C2 st Hk H1 H2 Vs D S H3 G;\n     rewrite (joinC W) in V C1' C2' st H1 S H3 G H2 Hk;\n     rewrite -?(joinC s1) -?(joinC s2) in C1' C2' S G H3 Vs].\n  + have X: s1' = s2'.\n    - move: (C2'); rewrite (joinC U) G -[upd _ _ _ \\+ s1'](joinC s1'). \n      move/cohUnKR/(_ D1)/(_ Hu)=>C1''.\n      move: (coh_prec (cohS C2') C2 C1'' G)=>Z; rewrite -Z in G; clear Z.\n      by rewrite (joinxK (cohS C2') G).\n    split=>//; subst s2'; rewrite -!(joinC s1') in G C2'.\n    rewrite (joinC U) in C2'; move: (joinxK (cohS C2') G)=>{G}G.\n    rewrite (joinC s1') in G.\n    have E: getProtocol U l = getProtocol (U \\+ W) l.\n      by rewrite (getPUn V)// (cohD C1).\n    have E': getStatelet s1 l = getStatelet (s1 \\+ s1') l.\n      by rewrite (getSUn Vs). \n    rewrite /get_st /InMem in H1.\n    move: (getStatelet (s1 \\+ s1') l) (E') H2 S H3 G=>_<- H2 S H3 G.\n    move: (getProtocol (U \\+ W \\+ (Unit, K)) l)\n     (get_protocol_hooks K l V) E st H1 S H2 H3 G Hk=>_-><- st H1 S H2 H3 G Hk.\n    apply: (SendMsg H1 H2 D C1 _ H3 G).\n\n    (* Now proving the obligation about all_hooks_fire *)\n    move=>z lc hk F A1 A2.\n    apply sym_eq in F.\n    move: (Hk z lc hk).\n    rewrite -F -joinA !domUn !inE !Vs A1 A2 findUnL ?E' ?(find_some F)/=;\n      last by case/andP:V1; rewrite-joinA =>_->.\n    move/(_ erefl is_true_true is_true_true).\n    by rewrite {1 3}/getStatelet findUnL// A1.\n\n  have X: s1' = s2'.\n  - move: (C2'); rewrite (joinC U) G. \n    move/cohUnKR/(_ D1)/(_ Hu)=>C1''; rewrite (joinC s1') in G.\n    move: (coh_prec (cohS C2') C2 C1'' G)=>Z; rewrite -Z in G; clear Z.\n    by rewrite (joinxK (cohS C2') G).\n  split=>//; subst s2'; rewrite -!(joinC s1') in G C2'.\n  rewrite (joinC U) in C2'; move: (joinxK (cohS C2') G)=>{G}G.\n  rewrite (joinC s1') in G.\n  have E: getProtocol U l = getProtocol (U \\+ W) l.\n    by rewrite (getPUn V)// (cohD C1).\n  have E': getStatelet s1 l = getStatelet (s1 \\+ s1') l.\n    by rewrite (getSUn Vs). \n  rewrite /get_st /InMem in H1; rewrite (joinC s1') in H2.\n    move: (getStatelet (s1 \\+ s1') l) (E') H2 S H3 G=>_<- H2 S H3 G.\n    move: (getProtocol (U \\+ W \\+ (Unit, K)) l)\n     (get_protocol_hooks K l V) E st H1 S H2 H3 G Hk=>_-><- st H1 S H2 H3 G Hk.\n    apply: (SendMsg H1 H2 D C1 _ H3 G).\n\n    (* Now proving the obligation about all_hooks_fire *)\n    move=>z lc hk F A1 A2.\n    apply sym_eq in F.\n    move: (Hk z lc hk).\n    rewrite -F -joinA !domUn !inE A1 A2 findUnL ?E' ?(find_some F)/=;\n      last by rewrite joinA (joinC U.2); case/andP:V1=>_->.\n    rewrite !(joinC s1') !Vs/= -!(orbC true).\n    move/(_ erefl is_true_true is_true_true).\n    by rewrite {1 3}/getStatelet findUnL// A1.\nQed.\n\n(* The following two definitions are central for framing with respect\nto the hooks. In essence. we can add more hooks via the frame rule, if\nnone of the protocols in the \"core\" world (i.e., the world, to which\nwe attach the frame with more hooks) are going to become constrained\nby the newly added hooks.\n\nIn other words, the new hooks only constrain the world \"to be\nattached\" but not our \"core\" world. *)\n\nDefinition not_hooked_by (K : hooks) l :=\n  forall z lc l' st, (z, lc, (l', st)) \\in dom K -> l != l'.\n\nDefinition world_not_hooked (W: world) K :=\n  forall l, l \\in dom W.1 -> not_hooked_by K l.\n\nLemma hooks_frame (U W : world) (K : hooks) l st s s' n msg to :\n  hook_complete U -> hook_complete W ->\n  hooks_consistent (U \\+ W).1 K ->\n  l \\in dom s -> s \\In Coh U -> s \\+ s' \\In Coh (U \\+ W \\+ (Unit, K)) ->\n  not_hooked_by K l ->        \n  all_hooks_fire (geth U) l st s n msg to ->\n  all_hooks_fire (geth (U \\+ W \\+ (Unit, K))) l st (s \\+ s') n msg to.\nProof.\nmove=>G1 G2 G D' C1 C' N A z lc hk F D1 D2; move: F.\ncase/andP: (cohW C')=>/=V1 V2.\nmove: (cohUnKR (coh_hooks C') C1 G2) => C2.\nrewrite findUnL ?V2//=; case: ifP=>D3; last first.\n- move => F; apply sym_eq in F; move: F.\n  by move/find_some/N/negP; rewrite eqxx. \nrewrite findUnR ?(validL V2)//; case: ifP=>[D|_].\n+ case/G2/andP: D=>_ D; rewrite (cohD C2) in D.\n  by case: validUn (cohS C')=>//_ _/(_ _ D'); rewrite D.\nmove => F.\napply sym_eq in F.\nhave D'': lc \\in dom s by case/andP:(G1 _ _ _ _ (find_some F)); rewrite (cohD C1).\nhave E: getStatelet s l = getStatelet (s \\+ s') l\n  by rewrite (getSUn (cohS C'))// -?(cohD C1').\nhave E': getStatelet s lc = getStatelet (s \\+ s') lc.\n  by rewrite (getSUn (cohS C'))// -?(cohD C1').\nmove: (getStatelet (s \\+ s') l) (getStatelet (s \\+ s') lc) E E'.\nby move=>y1 y2 Z1 Z2; subst y1 y2; apply sym_eq in F; apply: (A z).\nQed.\n\n(********************************************************************)\n(*                      Framing result                              *)\n(********************************************************************)\n\nLemma inject_frame U W K this s1 s2 s:\n  s1 \\+ s \\In Coh (U \\+ W \\+ (Unit, K)) ->\n  network_step U this s1 s2 ->\n  hook_complete U -> hook_complete W ->\n  hooks_consistent (U \\+ W).1 K ->\n  (* State something about hook direction *)\n  world_not_hooked U K ->\n  network_step (U \\+ W \\+ (Unit, K)) this (s1 \\+ s) (s2 \\+ s).\nProof.\nmove=>C1 S Ku Kw Hk N; move/step_coh: (S)=>[C1' C2'].\ncase: S; first by move=>[_ <-]; apply: Idle. \n\n(* Send-transition *)\n- move=>l st H1 to msg h H2 H3 _ S A H4 G.\n  have E: getProtocol U l = getProtocol (U \\+ W \\+ (Unit, K)) l.\n  have Y: getProtocol U l = getProtocol (U \\+ W) l.\n    + by rewrite (getPUn (validL (cohW C1)))// (cohD C1').\n    rewrite Y; rewrite (getPUn (cohW C1))// domUn inE (cohD C1') H3/=.\n    by case/andP: (validL (cohW C1))=>->.\n  have E': getStatelet s1 l = getStatelet (s1 \\+ s) l.\n    by rewrite (getSUn (cohS C1))// -?(cohD C1').\n  have X: l \\in dom (s1 \\+ s) by rewrite domUn inE H3 (cohS C1).\n  move: (getProtocol U) (E) H2=>_ -> H2.\n  rewrite /get_st /InMem/= in H1.\n  rewrite E' in H2 G S H4; clear E'.\n  move: (getProtocol U l) E st H1 S H4 G H2 A=>_->st H1 S H4 G H2 A.\n  apply: (SendMsg H1 H2 X C1 _ H4 (s2 := s2 \\+ s)); last first.\n  - by rewrite updUnL H3; congr (_ \\+ _).\n  by apply: hooks_frame=>//; apply: N; rewrite -(cohD C1') in H3.\n \n    \n(* Receive-transition *)\nmove=> l rt H1 msg from H2 H3 C tms G [G1 G2/= G3].\nhave E: getProtocol U l = getProtocol (U \\+ W \\+ (Unit, K)) l.\n  have Y: getProtocol U l = getProtocol (U \\+ W) l.\n  - by rewrite (getPUn (validL (cohW C1)))// (cohD C1').\n  rewrite Y; rewrite (getPUn (cohW C1))// domUn inE (cohD C1') H3/=.\n  by case/andP: (validL (cohW C1))=>->.\nhave E': getStatelet s1 l = getStatelet (s1 \\+ s) l.\n  by rewrite (getSUn (cohS C1))// -?(cohD C1').\nhave X: l \\in dom (s1 \\+ s) by rewrite domUn inE (cohS C1) H3.\nrewrite /get_rt /InMem /= in H1.\nmove: (getProtocol U l) (getStatelet s1 l) E E' C H2\n      (coh_s l C) rt G3 G G2 H1 G1=>z1 z2 Z1 Z2.\nsubst z1 z2=>C pf C' G3 G G2 H1 H2 G1.\napply: (ReceiveMsg H2 X G2 (i := msg) (from := from) (s2 := s2 \\+ s)).\nsplit=>//=; first by rewrite (pf_irr (coh_s l C1) C').\nrewrite updUnL H3; congr (_ \\+ _); move: (NetworkSem.coh_s l C1)=>pf'. \nby rewrite (pf_irr pf' C').\nQed.\n\n\nLemma injectL (U W : world) K :\n  valid (U \\+ W \\+ (Unit, K)) ->\n  hook_complete U -> hook_complete W ->\n  hooks_consistent (getc (U \\+ W)) K ->\n  world_not_hooked U K ->\n  injects U (U \\+ W \\+ (Unit, K)) K.\nProof.\nmove=>H G1 G2 G N.\nexists W=>//[s|s1 s2 s this|s1 s2 s1' s2' this]; [split | |].\n- move/coh_hooks=>C; exists (projectS U s), (projectS W s).\n  split; [by apply projectSE|by apply: (projectS_cohL C)|\n          by apply: (projectS_cohR C)].\n- case=>s1[s2][Z]C1 C2; subst s.\n  have W1 : valid (s1 \\+ s2).\n  + case: validUn; rewrite ?(cohS C1) ?(cohS C2)//.\n    move=>l; rewrite -(cohD C1)-(cohD C2).\n    case/validL/andP: H=>H _;\n    by case: validUn H=>//_ _/(_ l) G' _/G'; move/negbTE=>->.\n  split=>//[||l].\n  + by apply: inj_hooks_complete.\n  + move=>l; rewrite !domUn !inE !unitR dom0 orbC/=.\n    rewrite W1/= -(cohD C1)-(cohD C2) domUn !inE//=.\n    by move/validL/andP:H=>[->]_.\n  + rewrite (get_protocol_hooks K l (validL H)).\n    rewrite /getProtocol/getStatelet !findUnL//; last by case/validL/andP:H.\n    by rewrite (cohD C1); case B: (l \\in dom s1)=>//; apply: coh_coh.\n- by move=>C1 C2; apply: inject_frame. \nby move=>C1 C2; apply: (inject_step (validL H)).\nQed.\n\n\nLemma injectR (U W : world) K :\n  valid (W \\+ U \\+ (Unit, K)) ->\n  hook_complete U -> hook_complete W ->\n  hooks_consistent (getc (U \\+ W)) K ->\n  world_not_hooked U K ->\n  injects U (W \\+ U \\+ (Unit, K)) K.\nProof. by rewrite (joinC W); apply: injectL. Qed.\n\nLemma locProjL (W1 W2 : world) l s1 s2:\n  (s1 \\+ s2) \\In Coh (W1 \\+ W2) -> l \\in dom W1.1 ->\n  s1 \\In Coh W1 -> getStatelet (s1 \\+ s2) l = getStatelet s1 l.\nProof.\nmove=>C D C1; rewrite (cohD C1) in D.\nby rewrite (getSUn (cohS C) D).\nQed.\n\nLemma locProjR (W1 W2 : world) l s1 s2:\n  (s1 \\+ s2) \\In Coh (W1 \\+ W2) -> l \\in dom W2.1 ->\n  s2 \\In Coh W2 -> getStatelet (s1 \\+ s2) l = getStatelet s2 l.\nProof. by rewrite !(joinC W1) !(joinC s1); apply: locProjL. Qed.\n\nEnd InjectExtra.\n\nExport InjectExtra.\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/Core/Injection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2555669675777183}}
{"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.\nRequire Import Wfsimpl.\nRequire Import Errors.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Globalenvs.\nRequire Import Op.\nRequire Import Registers.\nRequire Import RTL.\nRequire Import Inlining.\n\n(** ** Soundness of function environments. *)\n\n(** A (compile-time) function environment is compatible with a\n  (run-time) global environment if the following condition holds. *)\n\nDefinition fenv_compat (ge: genv) (fenv: funenv) : Prop :=\n  forall id b f,\n  fenv!id = Some f -> Genv.find_symbol ge id = Some b ->\n  Genv.find_funct_ptr ge b = Some (Internal f).\n\nRemark add_globdef_compat:\n  forall ge fenv idg,\n  fenv_compat ge fenv ->\n  fenv_compat (Genv.add_global ge idg) (Inlining.add_globdef fenv idg).\nProof.\n  intros. destruct idg as [id gd]. red; simpl; intros.\n  unfold Genv.find_symbol in H1; simpl in H1. \n  unfold Genv.find_funct_ptr; simpl.\n  rewrite PTree.gsspec in H1. destruct (peq id0 id).\n  (* same *)\n(** [CompCertX:test-compcert-void-symbols] We now allow a symbol to be\nassociated to no variable or function. *)\n  subst id0. inv H1. destruct gd. destruct g. destruct f0. \n  destruct (should_inline id f0).\n  rewrite PTree.gss in H0. rewrite PTree.gss. inv H0; auto.\n  rewrite PTree.grs in H0; discriminate.\n  rewrite PTree.grs in H0; discriminate.\n  rewrite PTree.grs in H0; discriminate.\n(** [CompCertX:test-compcert-void-symbols] case none *)\n  rewrite PTree.grs in H0; discriminate.\n  (* different *)\n  destruct gd. destruct g. rewrite PTree.gso. eapply H; eauto. \n  destruct f0. destruct (should_inline id f0).\n  rewrite PTree.gso in H0; auto.\n  rewrite PTree.gro in H0; auto.\n  rewrite PTree.gro in H0; auto.\n  red; intros; subst b. eelim Plt_strict. eapply Genv.genv_symb_range; eauto.\n  rewrite PTree.gro in H0; auto. eapply H; eauto. \n(** [CompCertX:test-compcert-void-symbols] case none *)\n  rewrite PTree.gro in H0; auto. eapply H; eauto. \nQed.\n\nLemma funenv_program_compat:\n  forall p, fenv_compat (Genv.globalenv p) (funenv_program p).\nProof.\n  intros.\n  unfold Genv.globalenv, funenv_program.\n  assert (forall gl ge fenv,\n         fenv_compat ge fenv ->\n         fenv_compat (Genv.add_globals ge gl) (fold_left add_globdef gl fenv)).\n    induction gl; simpl; intros. auto. apply IHgl. apply add_globdef_compat; auto. \n  apply H. red; intros. rewrite PTree.gempty in H0; discriminate.\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.  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      Ple res ctx.(mreg) ->\n      c!(spc ctx pc) = Some (Ibuiltin ef (sregs ctx args) (sreg 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(* 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\n(** ** Relational specification of the translation of a function *)\n\nInductive tr_function: function -> function -> Prop :=\n  | tr_function_intro: forall f f' ctx,\n      tr_funbody 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' < Int.max_unsigned ->\n      tr_function f f'.\n\nLemma transf_function_spec:\n  forall f f', transf_function fenv f = OK f' -> tr_function f f'.\nProof.\n  intros. unfold transf_function in H.\n  destruct (expand_function fenv f initstate) as [ctx s i] eqn:?. \n  destruct (zlt (st_stksize s) Int.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 ctx; auto.\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\nEnd INLINING_SPEC.\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/Inliningspec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2555669613152753}}
{"text": "Require Import LibTactics.\nRequire Import Metalib.Metatheory.\n\nRequire Import\n        syntax_ott\n        syntaxb_ott\n        rules_inf\n        rulesb_inf\n        Infrastructure\n        Infrastructure_b\n        Deterministic\n        Typing_b\n        Type_Safety\n        ttyping.\n\nRequire Import List. Import ListNotations.\nRequire Import Arith Omega.\nRequire Import Strings.String.\n\nRequire Import Omega.\n\nLtac size_ind_auto :=\n  ( eapply_first_lt_hyp ;\n    try reflexivity;\n    try omega ;\n    try eauto ).\n\nLemma principle_if: forall v A t,\n    value v -> ttyping nil v Inf A t -> principal_type v = A.\nProof.\n     introv H typ.\n     inductions H; inverts* typ; eauto.\nQed.\n\n\nLemma value_valueb: forall e t A,\n ttyping nil e Inf A t -> value e ->\n valueb t.\nProof.\n  introv typ H. gen t A.\n  inductions H; intros; \n  try solve [inverts* typ].\n  - inverts typ. \n    pick fresh x.\n    forwards*: H2.\n    forwards*: lc_lcb H. \n  - inverts typ.\n    forwards*: value_lc H.\n    forwards*: lc_lcb H3.  \n    inverts* H3. \n    forwards*: IHvalue.\n    forwards*: principle_if H4.\n    rewrite H7 in H0. inverts H0.\n    eapply valueb_fanno; eauto.\n  - inverts typ.\n    inverts* H3.\n    forwards*: IHvalue.\n    forwards*: principle_if H1.\n    rewrite H5 in H.\n    apply valueb_dyn; eauto.\nQed.\n\nLemma sim_refl: forall A,\n sim A A.\nProof.\n  intros.\n  inductions A; eauto.\nQed.\n\nLemma fillb_cast: forall v A B,\n  (trm_cast v A B) = (fillb (castCtxb A B)  v).\nProof.\n  introv.\n  eauto.\nQed.\n\nLemma Tred_soundness: forall v t v' A,\n  ttyping nil (e_anno v A) Inf A t->\n  value v ->\n  TypedReduce v A (e_exp v') ->\n  exists t', t ->* (t_term t') /\\ ttyping nil v' Inf A t'.\nProof.\n  introv  Typ val Red. gen t.\n  inductions Red; intros.\n  - inverts Typ.\n    inverts H3; try solve[inverts val].\n    exists*.\n    forwards*: principle_if H1.\n  - inverts Typ.\n    inverts H2.\n    exists* (trm_cast (trm_abs t_dyn t0) (t_arrow t_dyn t_dyn) t_dyn).\n    forwards*: principle_if H0.\n  - inverts Typ.\n    inverts H1.\n    inverts H.\n    exists. split.\n    apply star_one.\n    apply bStep_lit; eauto. \n    apply ttyp_lit; eauto.\n  - inverts Typ.\n    inverts H2.\n    inverts H0.\n    inverts H5.\n    exists* (trm_cast (trm_abs t_dyn t) (t_arrow t_dyn t_dyn) t_dyn).\n    splits*.\n    apply star_one.\n    apply bStep_dd; eauto.\n    apply valueb_dyn; eauto.\n    forwards*: value_valueb val.\n    inverts* H2.\n    inverts val.\n    exists. split.\n    apply star_one.\n    apply bStep_dd; eauto.\n    apply valueb_dyn; eauto.\n    forwards*: value_valueb H0.\n    forwards*: principle_if H0.\n    rewrite H5 in H6.\n    auto.\n    simpl.\n    apply ttyp_anno; eauto.\n  - inverts Typ.\n    inverts H2.\n    exists.\n    splits*.\n    apply ttyp_anno; eauto.\n    apply ttyp_sim; eauto.\n    unfold not; intros nt; inverts* nt. inverts H1.\n    forwards*: principle_if H0.\n    rewrite H2 in H.\n    inverts* H.\n    inverts H5.\n    inverts H6.\n    rewrite <- TEMP in H.\n    rewrite <- TEMP in H4.\n    exists. split.\n    apply star_one.\n    apply bStep_anyd; eauto.\n    forwards*: value_valueb val.\n    simpl.\n    apply ttyp_anno; eauto.\n    apply ttyp_sim; eauto.\n    apply ttyp_anno; eauto.\n    apply ttyp_sim; eauto.\n    rewrite <- TEMP in H0. auto.\n    unfold not; intros nt; inverts nt. inverts H2.\n    rewrite <- TEMP in H4.\n    exfalso. apply H4. reflexivity.\n  -\n    inverts Typ. inverts H2. inverts H0.\n    inverts H6.\n    +\n    inverts H. inverts H2. inverts* H6.\n    destruct(eq_type A0); destruct(eq_type B); substs;\n    try solve[exfalso; apply H; eauto].\n    exists.\n    splits.\n    eapply star_trans.\n    apply star_one.\n    apply bStep_dyna; eauto.\n    forwards*: value_valueb val.\n    apply star_one.\n    rewrite fillb_cast.\n    apply do_stepb; eauto.\n    apply bStep_vany; eauto.\n    forwards*: value_valueb val. inverts* H2.\n    simpl.\n    apply ttyp_anno; eauto.\n    eapply ttyp_sim; eauto.\n    unfold not; intros nt; inverts nt. inverts H2.\n    exists.\n    splits.\n    eapply star_trans.\n    apply star_one.\n    apply bStep_dyna; eauto.\n    forwards*: value_valueb val.\n    apply star_one.\n    rewrite fillb_cast.\n    apply do_stepb; eauto.\n    apply bStep_vany; eauto.\n    forwards*: value_valueb val. inverts* H6.\n    simpl.\n    apply ttyp_anno; eauto.\n    eapply ttyp_sim; eauto.\n    unfold not; intros nt; inverts nt. inverts H6.\n    exists.\n    splits.\n    eapply star_trans.\n    apply star_one.\n    apply bStep_dyna; eauto.\n    forwards*: value_valueb val.\n    apply star_one.\n    rewrite fillb_cast.\n    apply do_stepb; eauto.\n    apply bStep_vany; eauto.\n    forwards*: value_valueb val. inverts* H7.\n    simpl.\n    apply ttyp_anno; eauto.\n    eapply ttyp_sim; eauto.\n    unfold not; intros nt; inverts nt. inverts H7.\n    +\n    exfalso; apply H5; eauto.\n  -\n    inverts Typ. inverts* H1. inverts* H.\n    inverts* H4.\n    exists. splits.\n    apply star_one.\n    apply bStep_vany; eauto.\n    forwards*: value_valueb val. inverts* H.\n    apply ttyp_anno; eauto.\n    exfalso; apply H3; eauto.\n  - inverts Typ. inverts val.\n    inverts H4. inverts H2. inverts H10.\n    exfalso; apply H1; eauto.\n    forwards*: principle_if H2.\n    rewrite H10 in H0.\n    rewrite H10 in H3.\n    exists. split.\n    eapply bstep_n.\n    apply bStep_dyna; eauto.\n    apply valueb_dyn; eauto.\n    forwards*: value_valueb H5.\n    inverts* H. inverts* H. inverts* H.\n    rewrite fillb_cast.\n    eapply bstep_n.\n    apply do_stepb; eauto.\n    inverts H. inverts H12. inverts* H13.\n    inverts H0. rewrite <- TEMP in H3. inverts H3.\n    apply bStep_vany; eauto.\n    forwards*: value_valueb H5.\n    rewrite <- TEMP in H3. inverts H3.\n    apply bstep_refl.\n    apply ttyp_anno; eauto.\n    inverts H. inverts H12. inverts* H13.\n    inverts H0. rewrite <- TEMP in H3. inverts H3.\n    rewrite <- TEMP in H2.\n    apply ttyp_sim; eauto. \n    rewrite <- TEMP in H3. inverts H3.\n  - inverts Typ. inverts val.\n    inverts H2.\n    inverts H0. inverts H7.\n    exfalso; apply H; eauto.\n    forwards*: principle_if H0.\n    exists. split.\n    apply star_one.\n    rewrite H7. rewrite H7 in H1.\n    apply bStep_vany; eauto.\n    forwards*: value_valueb H3.\n    rewrite H7. auto.\nQed.\n\n\n\nTheorem soundness_mul_two: forall e t e' A dir ,\n  ttyping nil e dir A t->\n  step e (e_exp e') ->\n  exists t', t ->* (t_term t') /\\ ttyping nil e' dir A t' .\nProof.\n  introv Typ Red. gen A t dir.\n  inductions Red; intros.\n  - destruct E; unfold fill in *.\n    + inverts Typ.\n      forwards*: IHRed H3. inverts H0. inverts H1.\n      exists. split.\n      apply multi_red_app2; eauto.\n      inverts H.\n      forwards*: lc_lcb H4.\n      eapply ttyp_app; eauto.\n      inverts H0.\n      forwards*: IHRed H6. inverts H0. inverts H3.\n      exists. split.\n      apply star_trans with (b:= trm_cast (trm_app x t2) A0 A).\n      apply multi_red_cast; auto.\n      apply multi_red_app2; auto.\n      inverts H.\n      forwards*: lc_lcb H5. \n      apply bstep_refl.\n      apply ttyp_sim; eauto.\n      unfold not; intros nt; inverts nt. inverts H3.\n      forwards*: IHRed H6. inverts H0. inverts H3.\n      exists. split.\n      apply multi_red_cast.\n      apply multi_red_app2.\n      inverts H.\n      forwards*: lc_lcb H5.\n      apply multi_red_cast.\n      apply H0.\n      eapply ttyp_sim;eauto.\n      unfold not; intros nt; inverts nt. inverts H3.\n      forwards*: IHRed H3. inverts H0. inverts H1.\n      exists. split.\n      apply multi_red_app2.\n      inverts H.\n      forwards*: lc_lcb H4.\n      apply multi_red_cast.\n      apply H0.\n      eapply ttyp_appd;eauto.\n    + inverts Typ. \n      *\n      inverts H.\n      forwards*: value_valueb H2.\n      forwards*: IHRed H7. inverts H0. inverts H4.\n      exists. split.\n      forwards: multi_red_app H H0.\n      apply H4.\n      eapply ttyp_app; eauto.\n      *\n      inverts H. inverts H0. \n      forwards*: value_valueb H5.\n      forwards*: IHRed H8. inverts H0. inverts H3.\n      exists. split.\n      apply multi_red_cast.\n      forwards: multi_red_app H H0.\n      apply H3.\n      eapply ttyp_sim; eauto.\n      unfold not; intros nt; inverts nt. inverts H3.\n      forwards* h1: principle_if H7.\n      rewrite h1 in H4. inverts H4.\n      *\n      inverts H.\n      forwards* h1: principle_if H3.\n      rewrite h1 in H1. inverts H1.\n    + inverts Typ. \n      * forwards*: IHRed H6. inverts H0. inverts H1.\n        exists. split.\n        apply H0.\n        apply ttyp_anno; eauto.\n      * inverts H0.\n        forwards*: IHRed H5. inverts H0. inverts H3.\n        exists. split.\n        apply multi_red_cast.\n        apply H0.\n        apply ttyp_sim;eauto.\n        unfold not; intros nt; inverts nt. inverts H3.\n  - inverts* Typ.\n    * inverts H5.\n      assert(ttyping nil (e_anno v t_dyn) Inf t_dyn t2).\n      apply ttyp_anno; auto. \n      inverts H9; try solve[inverts H0].\n       \n      forwards*: lc_lcb H.\n      inverts H1;\n      try solve[inverts* H8]. \n      exists. splits.\n      apply star_one.\n      apply bStep_beta; eauto.\n      forwards*: value_valueb H0.\n      apply ttyp_anno; auto.\n      pick fresh y.\n      forwards*: H7.\n      rewrite (subst_exp_intro y); auto.\n      rewrite (subst_term_intro y); auto.\n      eapply ttyping_c_subst_simpl; auto.\n      apply H1.\n      eapply ttyp_anno; eauto.\n      unfold not; intros nt; inverts nt; inverts H5.\n      \n      forwards*: value_valueb H0.\n      forwards*: Tred_soundness H1.\n      destruct H8. destruct H8.\n      exists. split.\n      apply star_trans with (b:= (trm_app (trm_abs t_dyn t) x)).\n      apply multi_red_app; eauto. forwards*: lc_lcb H.\n      apply star_one. \n      apply bStep_beta; eauto.\n      forwards*: lc_lcb H.\n      forwards*: Tred_value H1.\n      forwards*: value_valueb H9.\n      apply ttyp_anno; eauto.\n      pick fresh y.\n      forwards*: H7.\n      rewrite (subst_exp_intro y); auto.\n      rewrite (subst_term_intro y); auto.\n      eapply ttyping_c_subst_simpl; auto.\n      apply H10. auto.\n      forwards*: TypedReduce_nlambda2 H1.\n    * inverts H2. inverts H8.\n      assert(ttyping nil (e_anno v t_dyn) Inf t_dyn t2).\n      apply ttyp_anno; auto. inverts H9; try solve[inverts H0].\n      \n      exists. split.\n      apply star_one.\n      rewrite fillb_cast.\n      apply do_stepb; eauto.\n      apply bStep_beta; eauto.\n      forwards*: lc_lcb H.\n      forwards*: value_valueb H0.\n      apply ttyp_sim; eauto.\n      apply ttyp_anno; eauto.\n      inverts H1; try solve[inverts* H8].\n      pick fresh y.\n      forwards*: H10.\n      rewrite (subst_exp_intro y); auto.\n      rewrite (subst_term_intro y); auto.\n      eapply ttyping_c_subst_simpl; auto.\n      apply H1.\n      apply ttyp_anno; eauto.\n      unfold not; intros nt; inverts nt. inverts H6.\n      unfold not; intros nt; inverts nt. inverts H6.\n\n      forwards*: value_valueb H5.\n      forwards*: Tred_soundness H1.\n      destruct H9. destruct H9.\n      exists. split.\n      apply star_trans with (b:= trm_cast (trm_app (trm_abs t_dyn t) x) t_dyn A).\n      apply multi_red_cast; eauto.\n      apply multi_red_app; eauto. forwards*: lc_lcb H.\n      apply star_trans with (b := trm_cast (t ^^' x) t_dyn A).\n      apply multi_red_cast; auto.\n      apply star_one. \n      apply bStep_beta; eauto.\n      forwards*: lc_lcb H.\n      forwards*: Tred_value H1.\n      forwards*: value_valueb H11.\n      apply bstep_refl.\n      apply ttyp_sim; eauto.\n      apply ttyp_anno; eauto.\n      pick fresh y.\n      forwards*: H10.\n      rewrite (subst_exp_intro y); auto.\n      rewrite (subst_term_intro y); auto.\n      eapply ttyping_c_subst_simpl; auto.\n      apply H12. auto.\n      forwards*: TypedReduce_nlambda2 H1.\n      unfold not; intros nt; inverts nt. inverts H12.\n      inverts H8.\n    *\n       inverts* H5.\n  -  inverts* Typ.\n    * inverts* H5. forwards*: lc_lcb H.\n      inverts* H10.\n      assert(ttyping nil (e_anno v A1) Inf A1 t2).\n      apply ttyp_anno; auto.\n      inverts* H9.\n      forwards*: value_lc H0. \n      forwards*: lc_lcb H5.\n      exists*. split.\n      apply star_one. \n      apply bStep_beta; eauto.\n      apply ttyp_anno; eauto.\n      pick fresh y.\n      forwards*: H7.\n      rewrite (subst_exp_intro y); auto.\n      rewrite (subst_term_intro y); auto.\n      eapply ttyping_c_subst_simpl; auto.\n      apply H8. inverts H1.\n      apply ttyp_anno; eauto.\n      inverts* H1.\n      unfold not; intros nt; inverts nt. inverts H1.\n\n      forwards*: lc_lcb H.\n      inverts H1;\n      try solve[inverts* H8]. \n      exists. splits.\n      apply star_one.\n      apply bStep_beta; eauto.\n      forwards*: value_valueb H0.\n      apply ttyp_anno; auto.\n      pick fresh y.\n      forwards*: H7.\n      rewrite (subst_exp_intro y); auto.\n      rewrite (subst_term_intro y); auto.\n      eapply ttyping_c_subst_simpl; auto.\n      apply H1.\n      eapply ttyp_anno; eauto.\n      unfold not; intros nt; inverts nt; inverts H6.\n      inverts* H9.\n\n      forwards*: value_valueb H4.\n      forwards*: Tred_soundness H3.\n      destruct H9. destruct H9.\n      exists. split.\n      apply star_trans with (b:= trm_app (trm_abs A1 t) x ).\n      apply multi_red_app; eauto.  \n      apply star_one. \n      apply bStep_beta; eauto. forwards*: value_valueb H10. \n      forwards*: Tred_value H1.\n      apply ttyp_anno; eauto.\n      pick fresh y.\n      forwards*: H7.\n      rewrite (subst_exp_intro y); auto.\n      rewrite (subst_term_intro y); auto.\n      eapply ttyping_c_subst_simpl; auto.\n      apply H11. auto.\n      forwards*: TypedReduce_nlambda2 H1.\n      exfalso. apply H5. exists*.\n    * inverts* H2. inverts H8. forwards*: lc_lcb H.\n      inverts* H12. \n      assert(ttyping nil (e_anno v A2) Inf A2 t2).\n      apply ttyp_anno; auto.\n      inverts* H9.\n      forwards*: value_lc H0. \n      forwards*: lc_lcb H7.\n      exists. split.\n      apply multi_red_cast.\n      apply star_one. \n      apply bStep_beta; eauto.\n      eapply ttyp_sim; eauto.\n      apply ttyp_anno; eauto.\n      pick fresh y.\n      forwards*: H10.\n      rewrite (subst_exp_intro y); auto.\n      rewrite (subst_term_intro y); auto.\n      eapply ttyping_c_subst_simpl; auto.\n      apply H9. inverts H1.\n      apply ttyp_anno; eauto.\n      inverts* H1. \n      unfold not; intros nt; inverts nt. inverts H1.\n      unfold not; intros nt; inverts nt. inverts H9.\n\n      exists. split.\n      apply multi_red_cast.\n      eapply star_trans.\n      apply multi_red_app; eauto.  \n      apply star_one. \n      apply bStep_beta; eauto. \n      forwards*: value_valueb H0. \n      eapply ttyp_sim; eauto.\n      apply ttyp_anno; eauto.\n      pick fresh y.\n      forwards*: H10.\n      rewrite (subst_exp_intro y); auto.\n      rewrite (subst_term_intro y); auto.\n      eapply ttyping_c_subst_simpl; auto.\n      apply H7.\n      inverts* H1; try solve[inverts* H11].\n      inverts* H1; try solve[inverts* H11].\n      unfold not; intros nt; inverts nt. inverts H1.\n      unfold not; intros nt; inverts nt. inverts H7.\n\n      forwards*: value_valueb H6.\n      forwards*: Tred_soundness H1.\n      destruct H11. destruct H11.\n      exists. split.\n      apply multi_red_cast.\n      apply star_trans with (b:= trm_app (trm_abs A2 t) x ).\n      apply multi_red_app; eauto.  \n      apply star_one. \n      apply bStep_beta; eauto. forwards*: value_valueb H12. \n      forwards*: Tred_value H1.\n      eapply ttyp_sim; eauto.\n      apply ttyp_anno; eauto.\n      pick fresh y.\n      forwards*: H10.\n      rewrite (subst_exp_intro y); auto.\n      rewrite (subst_term_intro y); auto.\n      eapply ttyping_c_subst_simpl; auto.\n      apply H13. auto.\n      forwards*: TypedReduce_nlambda2 H1.\n      unfold not; intros nt; inverts nt. inverts H13.\n      exfalso; apply H7; exists*.\n      inverts* H8.\n    *\n     inverts* H5.\n  - inverts Typ.\n    + inverts H4. inverts H9. inverts H1.\n      assert (ttyping nil (e_anno v A1) Inf A1 t2).\n      apply ttyp_anno; eauto. \n      inverts H8. forwards*: value_lc H.\n      forwards*: lc_lcb H6.\n      exists. split.\n      apply star_one.\n      apply bStep_abeta; eauto. inverts H2.\n      apply ttyp_anno; eauto. apply ttyp_sim; eauto.\n      eapply ttyp_app; eauto. \n      inverts H0.\n      apply ttyp_sim; eauto. apply BA_AB; auto. \n      unfold not; intros nt; inverts nt. inverts H0.\n      unfold not; intros nt; inverts nt. inverts H2.\n\n     \n      exists. split.\n      eapply star_trans.\n      apply multi_red_app; eauto. \n     apply star_one.\n     apply bStep_abeta; eauto.\n     forwards*: value_valueb H.\n     apply ttyp_anno; eauto.\n     apply ttyp_sim; eauto.\n     eapply ttyp_app; eauto.\n     inverts* H0; try solve[inverts* H8].\n     apply ttyp_sim; eauto.\n     unfold not; intros nt; inverts nt. inverts H0.\n     inverts* H2.\n     unfold not; intros nt; inverts nt. inverts H6.\n\n      forwards*: Tred_soundness H0. inverts* H8. inverts H9. \n      exists. split.\n      eapply star_trans.\n      apply multi_red_app; eauto. \n     apply star_one.\n     apply bStep_abeta; eauto.\n     forwards*: value_valueb H10.\n     forwards*: Tred_value H0.  inverts* H2.\n     apply ttyp_anno; eauto.\n     apply ttyp_sim; eauto.\n     eapply ttyp_app; eauto.\n     apply ttyp_sim; eauto.\n     apply BA_AB; auto.\n     forwards*: TypedReduce_nlambda2 H0.\n     unfold not; intros nt; inverts nt. inverts H2.\n    +\n      inverts H1. inverts H7. inverts H11. inverts H1. inverts H4.\n      assert (ttyping nil (e_anno v A2) Inf A2 t2).\n      apply ttyp_anno; eauto. \n      inverts H8. forwards*: value_lc H.\n      forwards*: lc_lcb H7.\n      exists. split. apply multi_red_cast.\n      apply star_one.\n      apply bStep_abeta; eauto. \n      apply ttyp_sim; eauto.\n      apply ttyp_anno; eauto. apply ttyp_sim; eauto.\n      eapply ttyp_app; eauto. apply ttyp_sim; eauto.\n      inverts H0.\n      apply ttyp_anno; eauto. apply BA_AB; auto.\n      inverts H0. \n      unfold not; intros nt; inverts nt. inverts H0.\n      unfold not; intros nt; inverts nt. inverts H9.\n      unfold not; intros nt; inverts nt. inverts H9.\n\n      exists. split. apply multi_red_cast.\n      eapply star_trans.\n      apply multi_red_app; eauto. \n     apply star_one.\n     apply bStep_abeta; eauto.\n     forwards*: value_valueb H.\n     inverts* H0; try solve[inverts* H9].\n     apply ttyp_sim; eauto.\n     apply ttyp_anno; eauto.\n     apply ttyp_sim; eauto.\n     eapply ttyp_app; eauto.\n     apply ttyp_sim; eauto.\n     unfold not; intros nt; inverts nt. inverts H0.\n     unfold not; intros nt; inverts nt. inverts H0.\n     unfold not; intros nt; inverts nt. inverts H0.\n    \n      forwards*: Tred_soundness H0. inverts* H8. inverts H11. \n      exists. split. apply multi_red_cast.\n      eapply star_trans.\n      apply multi_red_app; eauto. \n     apply star_one.\n     apply bStep_abeta; eauto.\n     forwards*: value_valueb H13.\n     forwards*: Tred_value H0.\n     apply ttyp_sim; eauto.\n     apply ttyp_anno; eauto.\n     apply ttyp_sim; eauto.\n     eapply ttyp_app; eauto.\n     apply ttyp_sim; eauto.\n     apply BA_AB; auto.\n     forwards*: TypedReduce_nlambda2 H0.\n     unfold not; intros nt; inverts nt. inverts H11.\n     unfold not; intros nt; inverts nt. inverts H11.\n     inverts* H7.\n    +\n    inverts* H4.\n  - inverts Typ.\n    + inverts H4. inverts H9. inverts H1.\n      assert (ttyping nil (e_anno v A1) Inf A1 t2).\n      apply ttyp_anno; eauto. \n      inverts H8. forwards*: value_lc H.\n      forwards*: lc_lcb H5.\n      exists. split.\n      apply star_one.\n      apply bStep_abeta; eauto. inverts H2.\n      apply ttyp_anno; eauto. apply ttyp_sim; eauto.\n      eapply ttyp_app; eauto. \n      inverts H0.\n      apply ttyp_sim; eauto. apply BA_AB; auto. \n      unfold not; intros nt; inverts nt. inverts H0.\n      unfold not; intros nt; inverts nt. inverts H2.\n\n      exists. split.\n      eapply star_trans.\n      apply multi_red_app; eauto. \n     apply star_one.\n     apply bStep_abeta; eauto.\n     forwards*: value_valueb H.\n     inverts H0; try solve[inverts* H8].  \n     apply ttyp_anno; eauto.\n     apply ttyp_sim; eauto.\n     eapply ttyp_app; eauto.\n     apply ttyp_sim; eauto.\n     unfold not; intros nt; inverts nt. inverts H0.\n     inverts* H2.\n     unfold not; intros nt; inverts nt. inverts H0.\n\n\n      forwards*: Tred_soundness H0. inverts* H8. inverts H9. \n      exists. split.\n      eapply star_trans.\n      apply multi_red_app; eauto. \n     apply star_one.\n     apply bStep_abeta; eauto.\n     forwards*: value_valueb H10.\n     forwards*: Tred_value H0.  inverts* H2.\n     apply ttyp_anno; eauto.\n     apply ttyp_sim; eauto.\n     eapply ttyp_app; eauto.\n     apply ttyp_sim; eauto.\n     apply BA_AB; auto.\n     forwards*: TypedReduce_nlambda2 H0.\n     unfold not; intros nt; inverts nt. inverts H2.\n    +\n      inverts H1. inverts H7. inverts H11. inverts H1. inverts H4.\n      assert (ttyping nil (e_anno v A2) Inf A2 t2).\n      apply ttyp_anno; eauto. \n      inverts H8. forwards*: value_lc H.\n      forwards*: lc_lcb H6.\n      exists. split. apply multi_red_cast.\n      apply star_one.\n      apply bStep_abeta; eauto. \n      apply ttyp_sim; eauto.\n      apply ttyp_anno; eauto. apply ttyp_sim; eauto.\n      eapply ttyp_app; eauto. apply ttyp_sim; eauto.\n      inverts H0.\n      apply ttyp_anno; eauto. apply BA_AB; auto.\n      inverts H0. \n      unfold not; intros nt; inverts nt. inverts H0.\n      unfold not; intros nt; inverts nt. inverts H8.\n      unfold not; intros nt; inverts nt. inverts H8.\n\n      forwards*: Tred_soundness H0. inverts* H6. inverts H7. \n      exists. split. apply multi_red_cast.\n      eapply star_trans.\n      apply multi_red_app; eauto. \n     apply star_one.\n     apply bStep_abeta; eauto.\n     forwards*: value_valueb H8.\n     forwards*: Tred_value H0.\n     apply ttyp_sim; eauto.\n     apply ttyp_anno; eauto.\n     apply ttyp_sim; eauto.\n     eapply ttyp_app; eauto.\n     apply ttyp_sim; eauto.\n     forwards*: TypedReduce_nlambda2 H0.\n     unfold not; intros nt; inverts nt. inverts H7.\n     unfold not; intros nt; inverts nt. inverts H7.\n\n\n      forwards*: Tred_soundness H0. inverts* H8. inverts H11. \n      exists. split. apply multi_red_cast.\n      eapply star_trans.\n      apply multi_red_app; eauto. \n     apply star_one.\n     apply bStep_abeta; eauto.\n     forwards*: value_valueb H13.\n     forwards*: Tred_value H0.\n     apply ttyp_sim; eauto.\n     apply ttyp_anno; eauto.\n     apply ttyp_sim; eauto.\n     eapply ttyp_app; eauto.\n     apply ttyp_sim; eauto.\n     apply BA_AB; auto.\n     forwards*: TypedReduce_nlambda2 H0.\n     unfold not; intros nt; inverts nt. inverts H11.\n     unfold not; intros nt; inverts nt. inverts H11.\n     inverts* H7.\n     +\n     inverts* H4.\n  - inverts Typ.\n    assert (ttyping nil (e_anno v A0) Inf A0 t).\n    eauto.\n    forwards*: Tred_soundness H2.\n    inverts H2.\n    assert (ttyping nil (e_anno v A1) Inf A1 t0).\n    eauto.\n    forwards*: Tred_soundness H0.\n    inverts H5. inverts H6.\n    exists. split.\n    apply multi_red_cast; eauto.\n    apply ttyp_sim;eauto.\n    forwards*: TypedReduce_nlambda2 H0.\n  - inverts Typ. \n    * inverts H4.\n    inverts H8. \n    assert(ttyping nil (e_anno v1 t_int) Inf t_int (trm_cast t A t_int)).\n    apply ttyp_anno; auto. \n    forwards*: value_valueb H1.  \n    forwards*: Tred_soundness H0. inverts* H7. inverts H8. inverts H9.\n     exists. split.\n    apply star_trans with (b := (trm_app trm_add (trm_lit i1))).\n    apply multi_red_app; eauto. apply star_one.\n    apply bStep_add; eauto. \n    eapply ttyp_addl; eauto.\n    * inverts H1. inverts H7. inverts H8. \n    assert(ttyping nil (e_anno v1 t_int) Inf t_int (trm_cast t A0 t_int)).\n    apply ttyp_anno; auto. \n    forwards*: value_valueb H.  \n    forwards*: Tred_soundness H0. inverts* H9. inverts H10. inverts H11.\n     exists. split.\n    apply star_trans with (b := trm_cast (trm_app trm_add (trm_lit i1)) (t_arrow t_int t_int) A).\n    apply multi_red_cast; eauto.\n    apply multi_red_app; eauto.\n    apply star_trans with (b := trm_cast ((trm_addl i1)) (t_arrow t_int t_int) A).\n    apply multi_red_cast; auto.\n    apply bstep_refl.\n    apply ttyp_sim; eauto.\n    unfold not ; intros nt ; inverts nt. inverts H10.\n    inverts* H7.\n    *\n    inverts* H4.\n  - inverts Typ.\n    *\n    inverts H4. inverts H8.\n    assert(ttyping nil (e_anno v2 t_int) Inf t_int (trm_cast t A t_int)).\n    apply ttyp_anno; auto. \n    forwards*: value_valueb H1.  \n    forwards*: Tred_soundness H0. inverts* H7. inverts H8. \n    exists. split.\n    apply star_trans with (b := (trm_app (trm_addl i1) x)).\n    apply multi_red_app; eauto. apply star_one. inverts H9.\n    apply bStep_addl; eauto. \n    eapply ttyp_lit; eauto.\n    *\n    inverts H1. inverts H7. inverts H8.\n    assert(ttyping nil (e_anno v2 t_int) Inf t_int (trm_cast t A0 t_int)).\n    apply ttyp_anno; auto. \n    forwards*: value_valueb H.  \n    forwards*: Tred_soundness H0. inverts* H8. inverts H10. \n    exists. split. \n    apply star_trans with (b := (trm_cast (trm_app (trm_addl i1) x) t_int A)).\n    apply multi_red_cast; eauto.\n    apply multi_red_app; eauto.\n    apply star_trans with (b:= (trm_cast (trm_lit (i1 + i2)) t_int A)).\n    apply multi_red_cast; eauto. inverts H11.\n    apply star_one.\n    apply bStep_addl; eauto. apply bstep_refl.\n    apply ttyp_sim; eauto.\n    unfold not ; intros nt ; inverts nt. inverts H10.\n    inverts* H7.\n    *\n    inverts* H4.\n  - \n    inverts Typ. \n    * inverts H5. \n    assert(ttyping nil (e_anno v2 A1) Inf A1 t2).\n    apply ttyp_anno; auto. inverts H10; try solve[inverts H2].\n    inverts H3. inverts H8.\n    forwards*: Tred_soundness H0.\n    destruct H3. destruct H3.\n    inverts H. forwards*: value_lc H10. forwards*: lc_lcb H.  \n    exists. split.\n    apply star_trans with (b:= (trm_app (trm_cast (trm_abs A t0) (t_arrow A B) (t_arrow A1 A0)) x)).\n    apply multi_red_app; eauto.\n    apply star_one. \n    apply bStep_abeta; eauto. forwards*: value_valueb H6. \n    forwards*: Tred_value H0.\n    inverts H4.\n    apply ttyp_anno; eauto. apply ttyp_sim; eauto. eapply ttyp_app; eauto.\n    apply ttyp_sim; eauto. apply BA_AB; auto.\n    forwards*: TypedReduce_nlambda2 H0.\n    unfold not ; intros nt ; inverts nt. inverts H4.\n    inverts H.\n    forwards*: value_valueb H3.\n    forwards*: Tred_soundness H2.\n    destruct H8. destruct H8.\n    forwards*: principle_if H3. rewrite H12 in H13. inverts H13.\n    exists. split.\n    apply star_trans with (b:= (trm_app (trm_cast (trm_cast t0 (t_arrow C D) (t_arrow A B)) (t_arrow A B) (t_arrow A1 A0)) x)).\n    apply multi_red_app; eauto.  \n    apply star_one. \n    apply bStep_abeta; eauto. forwards*: value_valueb H10. \n    forwards*: Tred_value H1.\n    inverts H4.\n    apply ttyp_anno; eauto. apply ttyp_sim; eauto. eapply ttyp_app; eauto.\n    apply ttyp_sim; eauto. apply BA_AB; auto.\n    forwards*: TypedReduce_nlambda2 H0.\n    unfold not ; intros nt ; inverts nt. inverts H4.\n    * \n    inverts H2. inverts H8. inverts H12. inverts H2. \n    assert(ttyping nil (e_anno v2 A2) Inf A2 t2).\n    apply ttyp_anno; auto. \n    inverts H10; try solve[inverts H2].\n    forwards*: Tred_soundness H0.\n    destruct H7. destruct H7.\n    inverts H. forwards*: value_lc H12. forwards*: lc_lcb H.  \n    exists. split.\n    apply multi_red_cast.\n    apply star_trans with (b:= (trm_app (trm_cast (trm_abs A t0) (t_arrow A B) (t_arrow A2 A1)) x)).\n    apply multi_red_app; eauto.\n    apply star_one. \n    apply bStep_abeta; eauto. forwards*: value_valueb H8. \n    forwards*: Tred_value H0.\n    inverts H5.\n    apply ttyp_sim; eauto.\n    apply ttyp_anno; eauto. apply ttyp_sim; eauto. eapply ttyp_app; eauto.\n    apply ttyp_sim; eauto. apply BA_AB; auto.\n    forwards*: TypedReduce_nlambda2 H0.\n    unfold not ; intros nt ; inverts nt. inverts H5.\n    unfold not ; intros nt ; inverts nt. inverts H5.\n    inverts H.\n    forwards*: value_valueb H13.\n    forwards*: Tred_soundness H0.\n    destruct H10. destruct H10.\n    forwards*: principle_if H7. rewrite H14 in H15. inverts H15.\n    exists. split.\n    apply multi_red_cast.\n    apply star_trans with (b:= (trm_app (trm_cast (trm_cast t0 (t_arrow C D) (t_arrow A B)) (t_arrow A B) (t_arrow A2 A1)) x)).\n    apply multi_red_app; eauto.  \n    apply star_one. \n    apply bStep_abeta; eauto. forwards*: value_valueb H12. \n    forwards*: Tred_value H1.\n    inverts H5.\n    apply ttyp_sim; eauto.\n    apply ttyp_anno; eauto. apply ttyp_sim; eauto. eapply ttyp_app; eauto.\n    apply ttyp_sim; eauto. apply BA_AB; auto.\n    forwards*: TypedReduce_nlambda2 H0.\n    unfold not ; intros nt ; inverts nt. inverts H5.\n    unfold not ; intros nt ; inverts nt. inverts H5.\n    inverts* H8.\n    *\n    inverts* H5.\n  -\n    inverts* Typ; try solve[inverts* H3].\n    +\n    inverts* H0; try solve[inverts* H6].\n    exists. splits*.\n    eapply ttyp_sim;eauto.\n    eapply ttyp_app; eauto.\n    eapply ttyp_anno;eauto.\n    eapply ttyp_sim;eauto.\n    unfold not ; intros nt ; inverts nt. inverts H0.\n    unfold not ; intros nt ; inverts nt. inverts H0.\n    +\n    exists. splits*.\n    eapply ttyp_app; eauto.\n    eapply ttyp_anno;eauto.\n    eapply ttyp_sim;eauto.\n    unfold not ; intros nt ; inverts nt. inverts H0.\nQed. \n\n\n", "meta": {"author": "YeWenjia", "repo": "TypedDirectedGradualTypingWithBlame", "sha": "99210b5208555d4ea729738ea4a959c59b0646d0", "save_path": "github-repos/coq/YeWenjia-TypedDirectedGradualTypingWithBlame", "path": "github-repos/coq/YeWenjia-TypedDirectedGradualTypingWithBlame/TypedDirectedGradualTypingWithBlame-99210b5208555d4ea729738ea4a959c59b0646d0/JFP-Artifact/\\Bg/coq/soundness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.25555050822756714}}
{"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(*          Refinement proof for PTIntro layer                         *)\n(*                                                                     *)\n(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)\n(*                                                                     *)\n(*          Yale Flint Group                                           *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** This file provide the contextual refinement proof between MAL layer and MPTIntro layer*)\nRequire Import PTIntroGenDef.\n\n(** * Definition of the refinement relation*)\nSection Refinement.\n\n  Context `{real_params: RealParams}.\n\n  Section WITHMEM.\n\n    Context `{Hstencil: Stencil}.\n    Context `{Hmem: Mem.MemoryModel}.\n    Context `{Hmwd: UseMemWithData mem}.\n\n    Lemma flatmem_store_exists:\n      forall hadt ladt hadt' t v v' f m s ofs,\n        flatmem_store hadt t ofs v = Some hadt'\n        -> relate_RData f hadt ladt\n        -> match_RData s hadt m f\n        -> val_inject f v v'\n        -> ofs mod PgSize <= PgSize - size_chunk t\n        -> exists ladt',\n             flatmem_store ladt t ofs v' = Some ladt'\n             /\\ relate_RData f hadt' ladt'\n             /\\ PT hadt' = PT hadt\n             /\\ ptpool hadt' = ptpool hadt\n             /\\ CR3 ladt' = CR3 ladt\n             /\\ pperm hadt' = pperm hadt\n             /\\ idpde hadt' = idpde hadt.\n    Proof.\n      unfold flatmem_store, flatmem_store. intros.\n      revert H. inv H0. subrewrite. pose proof pperm_re as Hpp.\n      specialize (pperm_re (PageI ofs)).\n      destruct (ZMap.get (PageI ofs) (pperm hadt)) eqn:Hp'; contra_inv.\n      assert (HW: ZMap.get (PageI ofs) (pperm ladt) = PGAlloc (*PGFreeable*)).\n      {\n        inv pperm_re; reflexivity.\n      }\n      rewrite HW. inv HQ; simpl.\n      refine_split'; eauto.\n      constructor; trivial; simpl. \n      - (* flatmem *)\n        eapply (FlatMem.store_mapped_inj f); eauto 1.\n      - (* PMap *)\n        constructor; intros. inv relate_PMap_re.\n        erewrite FlatMem.load_store_other; eauto 2. simpl.\n        assert (~ pi * PgSize + vadr * 4 - size_chunk t < ofs < pi * PgSize + vadr * 4 + 4).\n        {\n          red; intros.\n          assert (PageI ofs = pi).\n          {\n            revert H7 H5 H3. clear; intros.\n            exploit  (Z_mod_lt ofs PgSize). omega.\n            intros Hofs.\n            rewrite (Z_div_mod_eq ofs PgSize) in H7 |-*; try omega.\n            assert (HW: (ofs / 4096) = pi).\n            {\n              destruct (zeq pi (ofs / 4096)); subst; trivial.\n              destruct (zle (pi + 1) (ofs / 4096)); rewrite_omega.\n            }\n            subst. unfold PageI.\n            replace (PgSize * (ofs / PgSize)) with ((ofs / PgSize) * PgSize) by omega.\n            rewrite Z_div_plus_full_l; [| omega].\n            rewrite (Zdiv_small (ofs mod PgSize) PgSize); omega.\n          }\n          subst.\n          inv H1. inv H8.\n          specialize (H1 _ H). inv H1.\n          specialize (H8 _ H0). destruct H8 as (v0 & _ & _ & HMAT).\n          unfold PMap, ZMap.t, PMap.t in H4, HMAT. rewrite H4 in HMAT.\n          inv HMAT. congruence.\n        }\n        omega.\n    Qed.\n\n    Lemma fstore_exist:\n      forall habd habd' labd i v f m s,\n        fstore_spec i v habd = Some habd'\n        -> relate_RData f habd labd\n        -> match_RData s habd m f\n        -> exists labd', fstore0_spec i v labd = Some labd' /\\ relate_RData f habd' labd'\n                         /\\ PT habd' = PT habd\n                         /\\ ptpool habd' = ptpool habd\n                         /\\ CR3 labd' = CR3 labd\n                         /\\ pperm habd' = pperm habd\n                         /\\ idpde habd' = idpde habd.\n    Proof.\n      unfold fstore_spec, fstore0_spec; intros.\n      revert H. pose proof H0 as HR.\n      inv H0. subrewrite. \n      subdestruct.  \n      eapply flatmem_store_exists; eauto. \n      change 4096 with (1024 * 4).\n      rewrite Zmult_mod_distr_r. \n      apply mod_chunk.\n    Qed.\n\n    Global Instance: (LoadStoreProp (hflatmem_store:= flatmem_store) (lflatmem_store:= flatmem_store)).\n    Proof.\n      accessor_prop_tac.\n      - exploit flatmem_store_exists; eauto.  \n        intros (ladt' & HST & Hre & _).\n        refine_split'; eauto.\n      - functional inversion H6. constructor; simpl; assumption.\n    Qed.\n\n  End WITHMEM.\n\nEnd Refinement.", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/mm/PTIntroGenAccessorDef.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2555505029170056}}
{"text": "\nDefinition rs2 :=\nlet mo' := (`mo)%rel in\n  ⦗IsRel⦘ ⨾ mo'^? \\ (mo' \\ sb^⋈) ⨾ ⦗set_compl IsRMW⦘ ⨾ mo'^?.\n\nDefinition rs3 :=\nlet mo' := (` (immediate mo))%rel in\nfun x =>\n  (⦗eq x⦘ ⨾ ⦗IsRel⦘ ⨾ (((mo' ⨾ ⦗IsRMW⦘)＊ ⨾ mo') ⨾ ⦗sb^⋈ x⦘)＊ ⨾ (mo' ⨾ ⦗IsRMW⦘)＊) x.\n\nLemma rs_rs2: rs ≡ rs2.\nProof.\nunfold rs, rs2, same_relation, inclusion, seq, minus_rel, eqv_rel, not, clos_refl, set_compl.\nall: repeat (intros; des; try split).\n1,4: exists z; auto.\n1-4: specialize (H0 z0); subst z z1; tauto.\n1,4: shelve.\nall: subst z.\nall: apply NNPP; unfold not; intros; apply H0.\nall: exists z0; split; auto; exists z0; tauto.\nUnshelve.\nall: subst z.\nall: exists x.\nall: tauto.\nQed.\n\nLemma rs_rs3: rs ≡ rs3.\nProof.\nunfold rs, rs3.\nall: autounfold with unfolderDb.\nset (mo' := (`mo)%rel).\nassert (mo_mo': forall x y, mo x y <-> mo' (`x) (`y)).\n  split.\n  intros moxy.\n  eexists; eexists; split; try split.\n  1-3: eauto.\n  intros moxy.\n  destruct moxy as (e' & f' & moxy' & ex & fy).\n  apply sig_ext in ex.\n  apply sig_ext in fy.\n  subst e' f'.\n  auto.\nassert (mo'_mo: forall x y, mo' x y <-> exists x' y', `x' = x /\\ `y' = y /\\ mo x' y').\n  intros x y.\n  split.\n  intros moxy.\n  destruct moxy as (e' & f' & moxy' & <- & <-).\n  eexists; esplit; try esplit; eauto.\n  intros (e & f & <- & <- & moxy).\n  apply mo_mo'; auto.\nassert (spo: strict_partial_order mo).\n  specialize (mo_total_order_per_loc (0)).\n  intros sto; apply sto.\nassert (spo': strict_partial_order mo').\n  destruct spo as [irr tra].\n  split.\n  intros x mxx.\n  apply mo'_mo in mxx.\n  destruct mxx as (e & f & ex & <- & moxy).\n  apply sig_ext in ex; subst f.\n  eapply irr; eauto.\n  intros x y z moxy moyz.\n  apply mo'_mo in moxy as (e & f & <- & <- & moxy).\n  apply mo'_mo in moyz as (f' & g & ff & <- & moyz).\n  apply sig_ext in ff.\n  subst f'.\n  apply mo_mo'.\n  eapply tra; eauto.\nsplit.\n- intros x y [[z [[xz xIsRel] moxy]] rsCond].\n  subst z.\n  eexists; split; try split; auto;\n    eexists; split; try split; auto.\n  destruct moxy as [xy|(x' & y' & moxy & <- & <-)].\n  eexists; esplit; rewrite clos_refl_transE.\n  1, 2: left; auto.\n  clear xIsRel.\n  apply mo_mo' in moxy.\n  apply (imm_trans mo' spo') in moxy.\n  set (base := x') in rsCond at 2 3.\n  fold base.\n  unfold base at 3.\n  assert (base_x: (`base) = (`x') \\/\n                  mo' (`base) (`x') /\\ (sb^⋈ (`base) (`x') \\/\n                                        IsRMW (`x'))).\n    constructor 1; auto.\n  clearbody base.\n  induction moxy.\n  destruct H as [moxy' imm].\n  pose (moxy := moxy'); apply mo'_mo in moxy; destruct moxy as (x'' & y'' & <- & <- & moxy'').\n  assert (sb^⋈ (`base) (`y'') \\/ IsRMW (`y'')).\n    eapply rsCond.\n    eexists; eexists; split; try split.\n    2,3: eauto.\n    auto.\n    destruct base_x as [bx|[mobx]].\n    apply sig_ext in bx; subst x''; auto.\n    apply mo'_mo in mobx; destruct mobx as (e & f & e1 & e2 & mobx).\n    apply sig_ext in e1; subst e.\n    apply sig_ext in e2; subst f.\n    left; auto.\n  destruct H, base_x as [bx|[mobx [x_sb|x_rmw]]].\n  1-6: eexists; esplit; erewrite clos_refl_transE.\n\n  (* base = x, sb x y*)\n  right; econstructor 1; esplit.\n  eexists; esplit.\n  erewrite clos_refl_transE; esplit.\n  left; auto.\n  eexists; eexists; split; split.\n  1-5: eauto.\n  intros c moxc mocy.\n  eapply imm.\n  1-2: eapply mo_mo'; eauto.\n  auto.\n  left; auto.\n\n  (* mo base x, sb base x, sb base y*)\n  right; econstructor 1; eexists; esplit; try erewrite clos_refl_transE; try esplit.\n  1, 2: eexists; try esplit; try esplit; try esplit;\n    try erewrite clos_refl_transE; try left; try esplit.\n  3,4,5: eauto.\n  auto.\n  intros c moxc mocy.\n  eapply imm.\n  1-2: eapply mo_mo'; eauto.\n  left; auto.\n\n  (*  mo base x, isrmw x, sb base y*)\n  right; econstructor 1; eexists; esplit; try erewrite clos_refl_transE; try esplit.\n  1, 2: eexists; try esplit; try esplit; try esplit;\n    try erewrite clos_refl_transE; try left; try esplit.\n  3,4,5: eauto.\n  auto.\n  intros c moxc mocy.\n  eapply imm.\n  1-2: eapply mo_mo'; eauto.\n  left; auto.\n\n  (* base = x, isrmw y *)\n  left; auto.\n  right; econstructor 1; esplit; eexists; esplit; try eexists; try esplit; try esplit;\n    try esplit.\n  1-3: auto.\n  intros c moxc mocy.\n  eapply imm.\n  1-2: eapply mo_mo'; eauto.\n\n  (* mo base x, sb base x, isrmw y *)\n  left; auto.\n  right; econstructor 1; eexists; esplit; try erewrite clos_refl_transE; try esplit.\n  1, 2: eexists; try esplit; try esplit; try esplit;\n    try erewrite clos_refl_transE; try left; try esplit.\n  1-3: eauto.\n  intros c moxc mocy.\n  eapply imm.\n  1-2: eapply mo_mo'; eauto.\n\n  (* mo base x, isrmw x, isrmw y *)\n  left; auto.\n  right; econstructor 1; eexists; esplit; try erewrite clos_refl_transE; try esplit.\n  1, 2: eexists; try esplit; try esplit; try esplit;\n    try erewrite clos_refl_transE; try left; try esplit.\n  1-3: eauto.\n  intros c moxc mocy.\n  eapply imm.\n  1-2: eapply mo_mo'; eauto.\n\n  apply imm_trans in moxy1.\n  apply mo'_mo in moxy1 as (e & f & <- & <- & moxy1).\n  apply mo_mo' in moxy1.\n  apply imm_trans in moxy2.\n  apply mo'_mo in moxy2 as (e' & f' & ef & fz & moxy2).\n  apply sig_ext in ef.\n  subst e' z.\n  apply mo_mo' in moxy2.\n\n  eassert (s1 := IHmoxy1 ?[f] ?[g]).\n  [f]: {\n    intros z' (e'' & f'' & moef & ee & fz) [fz'|(e''' & f''' & moef' & ez & fy)].\n    all: subst z'.\n    all: apply sig_ext in ee.\n    apply sig_ext in fz'.\n    subst e'' f''.\n    apply rsCond.\n    eexists; eexists; esplit; try esplit.\n    1-4: eauto.\n    apply sig_ext in ez.\n    apply sig_ext in fy.\n    subst e'' e''' f'''.\n    apply rsCond.\n    eexists; eexists; esplit; try esplit.\n    2-3: eauto.\n    auto.\n    right.\n    eexists; eexists; esplit; try esplit.\n    2-3: eauto.\n    apply spo with f; auto.\n    apply mo_mo'; auto.\n  }\n  [g]: {\n    apply base_x.\n  }\n  eassert (s2 := IHmoxy2 ?[f]).\n  [f]: {\n    intros z' (e'' & f'' & moef & ee' & fz) [fz'|(e''' & f''' & moef' & ez & fy)].\n    all: subst z'.\n    all: apply sig_ext in ee'.\n    apply sig_ext in fz'.\n    2: apply sig_ext in ez; apply sig_ext in fy.\n    all: subst e'' f''.\n    apply rsCond.\n    eexists; eexists; esplit; try esplit.\n    2-3: eauto.\n    apply mo_mo'; apply spo' with (`f); auto.\n    left; auto.\n    subst f'''.\n    apply rsCond.\n    eexists; eexists; esplit; try esplit.\n    2-3: eauto.\n    apply mo_mo' in moef.\n    apply mo_mo'.\n    apply spo' with (`f); auto.\n    right.\n    eexists; eexists; esplit; try esplit.\n    2-3: eauto.\n    auto.\n  }\n  2-3: auto.\n\n  destruct s1 as [e' [s11 s12]].\n  apply clos_refl_transE in s11.\n  apply clos_refl_transE in s12.\n  destruct s11 as [ee|s11], s12 as [ef|s12].\n  1-3: subst e'.\n  apply sig_ext in ef.\n  subst f.\n  exfalso; revert moxy1; apply spo'.\n\n  all: lapply s2; clear s2.\n  1,3,5: intros s2.\n  1-3: destruct s2 as [e'' [s21 s22]].\n  1-3: apply clos_refl_transE in s21.\n  1-3: apply clos_refl_transE in s22.\n  1-3: destruct s21 as [ee|s21], s22 as [ef|s22].\n  1-3,5-7,9-11: subst e''.\n  1,4,7: apply sig_ext in ef.\n  1-3: subst f.\n  1-3: exfalso; revert moxy2; apply spo'.\n\n  (* left: rmw. right: rmw *)\n  eexists; esplit; apply clos_refl_transE.\n  left; auto.\n  right; econstructor 2.\n  apply s12.\n  apply s22.\n\n  (* left: rmw. right: sb *)\n  eexists; esplit; apply clos_refl_transE.\n  2: left; auto.\n  right.\n  apply t_step_rt in s21 as [e' [[y'' [[e'' [s21p (p & p' & [mopp ppimm] & xe & yy)]] [ey sbb]]] s21]].\n  subst e' e'' y''.\n  apply clos_refl_transE in s21p; destruct s21p as [pp|s21p].\n  apply sig_ext in pp; subst p.\n  1-2: apply clos_refl_transE in s21; destruct s21 as [pp|s21].\n  1,3: apply sig_ext in pp; subst p'.\n  econstructor 1; repeat esplit.\n  apply clos_refl_transE; right; apply s12.\n  1-3: auto.\n  econstructor 1; repeat esplit.\n  apply clos_refl_transE; right; econstructor 2.\n  apply s12.\n  apply s21p.\n  1-3: auto.\n  econstructor 2.\n  econstructor 1; repeat esplit.\n  apply clos_refl_transE; right.\n  apply s12.\n  apply mopp.\n  1-3: auto.\n  econstructor 2.\n  2: apply s21.\n  econstructor 1; repeat esplit.\n  apply clos_refl_transE; right; econstructor 2.\n  apply s12.\n  apply s21p.\n  1-3: auto.\n\n  (* left: sb. right: rmw *)\n  eexists; esplit; apply clos_refl_transE; right.\n  apply s11.\n  apply s22.\n\n  (* left: sb. right: sb *)\n  eexists; esplit; apply clos_refl_transE.\n  right; econstructor 2.\n  apply s11.\n  apply s21.\n  auto.\n\n  (* left: sb;rmw. right: rmw *)\n  eexists; esplit; apply clos_refl_transE.\n  right.\n  apply s11.\n  right.\n  econstructor 2.\n  apply s12.\n  apply s22.\n  \n  (* left: sb;rmw. right: sb *)\n  apply t_step_rt in s21 as [e''' [[y'' [[e'' [s21p (p & p' & [mopp ppimm] & xe & yy)]] [ey sbb]]] s21]].\n  subst e''' e'' y''.\n  apply clos_refl_transE in s21p; destruct s21p as [pp|s21p].\n  apply sig_ext in pp; subst p.\n  1-2: apply clos_refl_transE in s21; destruct s21 as [pp|s21].\n  1,3: apply sig_ext in pp; subst p'.\n  1-4: eexists; esplit; eapply clos_refl_transE.\n  2,4,6,8: left; auto.\n  1-4: right; econstructor 2.\n  apply s11.\n  econstructor 1; repeat esplit.\n  apply clos_refl_transE; right; apply s12.\n  1-3: auto.\n  apply s11.\n  econstructor 1; repeat esplit.\n  apply clos_refl_transE; right; econstructor 2.\n  apply s12.\n  apply s21p.\n  1-3: auto.\n  2: apply s21.\n  econstructor 2.\n  apply s11.\n  econstructor 1; repeat esplit.\n  apply clos_refl_transE; right.\n  apply s12.\n  1-3: auto.\n  2: apply s21.\n  econstructor 2.\n  apply s11.\n  econstructor 1; repeat esplit.\n  apply clos_refl_transE; right; econstructor 2.\n  apply s12.\n  apply s21p.\n  1-3: auto.\n\n  (* left: rmw. right: sb;rmw *)\n  apply t_step_rt in s21 as [e''' [[y'' [[e' [s21p (p & p' & [mopp ppimm] & xe & yy)]] [ey sbb]]] s21]].\n  subst e''' e' y''.\n  apply clos_refl_transE in s21p; destruct s21p as [pp|s21p].\n  apply sig_ext in pp; subst p.\n  1-2: apply clos_refl_transE in s21; destruct s21 as [pp|s21].\n  1,3: subst e''.\n  1-4: eexists; esplit; eapply clos_refl_transE.\n  right; econstructor 1; repeat esplit.\n  apply clos_refl_transE; right.\n  apply s12.\n  apply mopp.\n  1-2: auto.\n  right; apply s22.\n  right; econstructor 1; repeat esplit.\n  apply clos_refl_transE; right; econstructor 2.\n  apply s12.\n  apply s21p.\n  apply mopp.\n  1-2: auto.\n  right; apply s22.\n  right; econstructor 2.\n  2: apply s21.\n  econstructor 1; repeat esplit.\n  apply clos_refl_transE; right.\n  apply s12.\n  apply mopp.\n  1-2: auto.\n  right; apply s22.\n  right; econstructor 2.\n  2: apply s21.\n  econstructor 1; repeat esplit.\n  apply clos_refl_transE; right; econstructor 2.\n  apply s12.\n  apply s21p.\n  1-3: auto.\n  right; apply s22.\n  \n  (* left: sb. right: sb;rmw *)\n  eexists; esplit; apply clos_refl_transE; right.\n  econstructor 2.\n  apply s11.\n  apply s21.\n  apply s22.\n\n  (* left: sb;rmw. right: sb;rmw *)\n  apply t_step_rt in s21 as [e''' [[y'' [[e'''' [s21p (p & p' & [mopp ppimm] & xe & yy)]] [ey sbb]]] s21]].\n  subst e''' e'''' y''.\n  apply clos_refl_transE in s21p; destruct s21p as [pp|s21p].\n  apply sig_ext in pp; subst p.\n  1-2: apply clos_refl_transE in s21; destruct s21 as [pp|s21].\n  1,3: subst e''.\n  1-4: eexists; esplit; eapply clos_refl_transE.\n  right; econstructor 2.\n  apply s11.\n  econstructor 1; repeat esplit.\n  apply clos_refl_transE; right.\n  apply s12.\n  apply mopp.\n  1-2: auto.\n  right; apply s22.\n  right; econstructor 2.\n  apply s11.\n  econstructor 1; repeat esplit.\n  apply clos_refl_transE; right; econstructor 2.\n  apply s12.\n  apply s21p.\n  apply mopp.\n  1-2: auto.\n  right; apply s22.\n  right; econstructor 2.\n  2: apply s21.\n  econstructor 2.\n  apply s11.\n  econstructor 1; repeat esplit.\n  apply clos_refl_transE; right.\n  apply s12.\n  apply mopp.\n  1-2: auto.\n  right; apply s22.\n  right; econstructor 2.\n  2: apply s21.\n  econstructor 2.\n  apply s11.\n  econstructor 1; repeat esplit.\n  apply clos_refl_transE; right; econstructor 2.\n  apply s12.\n  apply s21p.\n  1-3: auto.\n  right; apply s22.\n\n  apply t_rt_step in s12 as [p [_ [p' [_ [pf rmwf]]]]].\n  subst p'.\n  destruct base_x as [be | [mobe]].\n  apply sig_ext in be; subst base.\n  right; split.\n  auto.\n  right; auto.\n  right; split.\n  apply spo' with (`e); auto.\n  right; auto.\n\n  apply t_rt_step in s11 as [p [_ [p' [_ [pf sbf]]]]].\n  subst p'.\n  destruct base_x as [be | [mobe]].\n  apply sig_ext in be; subst base.\n  right; split.\n  auto.\n  auto.\n  right; split.\n  apply spo' with (`e); auto.\n  auto.\n\n  apply t_rt_step in s12 as [p [_ [p' [_ [pf rmwf]]]]].\n  subst p'.\n  destruct base_x as [be | [mobe]].\n  apply sig_ext in be; subst base.\n  right; split.\n  auto.\n  right; auto.\n  right; split.\n  apply spo' with (`e); auto.\n  right; auto.\n\n- assert (tot_mo:\n    forall x i c,\n      mo'^⋈ x i -> mo'^⋈ x c ->\n      i <> c -> mo' i c \\/ mo' c i). {\n    intros x i c moxi moxc inc.\n    destruct moxi as [moxi|moxi], moxc as [moxc|moxc].\n    all: apply mo'_mo in moxi as (e & f & xx & yy & moxi).\n    all: apply mo'_mo in moxc as (e' & f' & xx' & yy' & moxc).\n    all: subst c i x.\n    all: try apply sig_ext in xx'.\n    all: try apply sig_ext in yy'.\n    all: try subst e.\n    all: try subst f.\n    all: apply mo_same_loc_only in moxi.\n    all: apply mo_same_loc_only in moxc.\n    all: destruct moxi as [moxi xi], moxc as [moxc xc].\n    1,2: rewrite xi in xc; clear xi.\n    3,4: rewrite <- xi in xc; clear xi.\n    1,3: destruct (mo_total_order_per_loc ((loc ∘ Write_To_ReadWrite) f')) as [_ tot].\n    3,4: destruct (mo_total_order_per_loc ((loc ∘ Write_To_ReadWrite) e')) as [_ tot].\n    all: edestruct tot.\n    2,7,12,17: reflexivity.\n    1,5,9,13: try apply xc; try apply (eq_sym xc).\n    all: apply mo_mo' in moxi.\n    all: apply mo_mo' in moxc.\n    1,4,7,10: intros conn; apply inc; apply f_equal; auto.\n    all: apply mo_mo' in H.\n    all: eauto.\n  }\n  intros x y [x' [[xz xx] [x'' [[xz' xisrel] [z [xzsb zyrmw]]]]]].\n  subst x' x''.\n  clear xx.\n  remember x as base.\n  replace base in xzsb at 1 |-.\n  assert (mo_rmw_mo:\n    let imo' := (` (immediate mo))%rel in\n      (imo' ⨾ ⦗IsRMW⦘)⁺ ⊆ mo' \\ (mo' ⨾ ⦗set_compl IsRMW⦘ ⨾ mo'^?)). {\n    clear x y z xisrel Heqbase xzsb zyrmw.\n    intros imo' x y xyrmw.\n    induction xyrmw.\n    destruct H as [z' ((x'' & y'' & (moxy & xyimm) & <- & <-) & <- & yrmw)].\n    split.\n    apply mo_mo'; auto.\n    intros (z & moxz & z'' & [<- zrmw] & [->|mozy]).\n    auto.\n    apply mo'_mo in moxz as (x' & z' & xx & <- & moxz).\n    apply mo'_mo in mozy as (z'' & y' & zz & yy & mozy).\n    apply sig_ext in xx.\n    apply sig_ext in yy.\n    apply sig_ext in zz.\n    subst x'' y'' z''.\n    eapply xyimm; eauto.\n    destruct IHxyrmw1 as [moxy yrmw].\n    destruct IHxyrmw2 as [moyz zrmw].\n    split.\n    eapply spo'; eauto.\n    intros (y' & moxy' & z'' & [<- allrmw] & [->|moyz']).\n    apply zrmw; esplit; esplit.\n    2: esplit; esplit.\n    3: left; auto.\n    2: esplit; eauto.\n    auto.\n    destruct (classic (y = y')) as [<-|yneq].\n    apply yrmw; esplit; esplit.\n    2: esplit; esplit.\n    3: left; auto.\n    2: esplit; eauto.\n    auto.\n    destruct (tot_mo x y y'); unfold clos_sym; auto.\n    apply zrmw; esplit; esplit.\n    2: esplit; esplit.\n    3: right.\n    2: esplit; eauto.\n    1-2: eauto.\n    apply yrmw; esplit; esplit.\n    2: esplit; esplit.\n    3: right.\n    2: esplit; eauto.\n    1-2: eauto.\n  }\n  assert (mo_sb_mo:\n    let imo' := (` (immediate mo))%rel in\n      (((imo' ⨾ ⦗IsRMW⦘)＊ ⨾ imo') ⨾ ⦗sb^⋈ base⦘)⁺ ⊆\n      mo' \\ (mo' ⨾ ⦗set_compl (IsRMW ∪₁ sb^⋈ base)⦘ ⨾ mo'^?)). {\n    clear x y z xisrel Heqbase xzsb zyrmw.\n    intros imo' x y xyrmw.\n    induction xyrmw.\n    destruct H as [z' [[z'' [zrmw (z & y' & [moxy imm] & <- & <-)]] [<- zsb]]].\n    apply clos_refl_transE in zrmw as [->|zrmw].\n    split.\n    apply mo_mo'; auto.\n    intros (e & moxy' & z'' & [<- allrmw] & [->|moyz']).\n    apply allrmw.\n    right; auto.\n    apply mo'_mo in moxy' as (z' & e' & xx & <- & moxy').\n    apply mo'_mo in moyz' as (e'' & y'' & zz & yy & moyz').\n    apply sig_ext in xx.\n    apply sig_ext in yy.\n    apply sig_ext in zz.\n    subst z' e'' y''.\n    eapply imm; eauto.\n    lapply (mo_rmw_mo x (`z)).\n    intros (z' & moxz).\n    split.\n    eapply spo'.\n    apply z'.\n    apply mo_mo'; auto.\n    intros (e & moxy' & z'' & [<- allrmw] & [->|moyz']).\n    apply allrmw.\n    right; auto.\n    destruct (classic (e = `z)) as [->|yneq].\n    apply moxz; esplit; esplit.\n    2: esplit; esplit.\n    3: left; auto.\n    2: esplit; eauto.\n    2: intros nrmw; apply allrmw; left; auto.\n    auto.\n    destruct (tot_mo x e (`z)); unfold clos_sym; auto.\n    apply moxz; esplit; esplit.\n    2: esplit; esplit.\n    3: right.\n    2: esplit; eauto.\n    apply moxy'.\n    intros nrmw; apply allrmw; left; auto.\n    auto.\n    apply mo'_mo in H as (z'' & e' & xx & <- & H).\n    apply mo'_mo in moyz' as (e'' & y'' & zz & yy & moyz').\n    apply sig_ext in xx.\n    apply sig_ext in yy.\n    apply sig_ext in zz.\n    subst e'' y'' z''.\n    eapply imm; eauto.\n    auto.\n    destruct IHxyrmw1 as [moxy yrmw].\n    destruct IHxyrmw2 as [moyz zrmw].\n    split.\n    eapply spo'; eauto.\n    intros (y' & moxy' & z'' & [<- allrmw] & [->|moyz']).\n    apply zrmw; esplit; esplit.\n    2: esplit; esplit.\n    3: left; auto.\n    2: esplit; eauto.\n    auto.\n    destruct (classic (y = y')) as [<-|yneq].\n    apply yrmw; esplit; esplit.\n    2: esplit; esplit.\n    3: left; auto.\n    2: esplit; eauto.\n    auto.\n    destruct (tot_mo x y y'); unfold clos_sym; auto.\n    apply zrmw; esplit; esplit.\n    2: esplit; esplit.\n    3: right.\n    2: esplit; eauto.\n    1-2: eauto.\n    apply yrmw; esplit; esplit.\n    2: esplit; esplit.\n    3: right.\n    2: esplit; eauto.\n    1-2: eauto.\n  }\n  apply clos_refl_transE in xzsb.\n  apply clos_refl_transE in zyrmw.\n  destruct xzsb as [<-|xzsb], zyrmw as [<-|zyrmw].\n\n  all: repeat try esplit.\n  all: auto.\n  1,3,5,7: intros z' (e & f & moxy & ee & ff) [<-|(e' & f' & moyz & ff' & gg)].\n  1-8:subst base z'.\n\n  apply sig_ext in ff; subst e.\n  exfalso; eapply spo; eauto.\n\n  subst x.\n  apply sig_ext in ff'; subst e'.\n  apply sig_ext in gg; subst e.\n  exfalso; eapply spo; eapply spo; eauto.\n\n  subst x.\n  lapply (mo_rmw_mo (`e) (`f)).\n  intros (moef & allzyrmw).\n  apply NNPP; intros nrmw.\n  apply allzyrmw.\n  esplit; esplit.\n  eauto.\n  esplit; esplit.\n  esplit; eauto.\n  intros nrmw2; apply nrmw; auto.\n  left; auto.\n  auto.\n\n  subst x y.\n  apply sig_ext in ff'; subst e'.\n  lapply (mo_rmw_mo (`e) (`f')).\n  intros (moef & allzyrmw).\n  apply NNPP; intros nrmw.\n  apply allzyrmw.\n  esplit; esplit.\n  eapply mo_mo'; eauto.\n  esplit; esplit.\n  esplit; eauto.\n  intros nrmw2; apply nrmw; auto.\n  right; eapply mo_mo'; eauto.\n  auto.\n  \n  subst x.\n  lapply (mo_sb_mo (`e) (`f)).\n  intros (moef & allxzsb).\n  apply NNPP; intros nrmw.\n  apply allxzsb.\n  esplit; esplit.\n  eauto.\n  esplit; esplit.\n  esplit; eauto.\n  intros [nrmw2|nrmw2]; apply nrmw; auto.\n  left; auto.\n  auto.\n\n  subst x z.\n  apply sig_ext in ff'; subst e'.\n  lapply (mo_sb_mo (`e) (`f')).\n  intros (moef & allxzsb).\n  apply NNPP; intros nrmw.\n  apply allxzsb.\n  esplit; esplit.\n  eapply mo_mo'; eauto.\n  esplit; esplit.\n  esplit; eauto.\n  intros [nrmw2|nrmw2]; apply nrmw; auto.\n  right; eapply mo_mo'; eauto.\n  auto.\n\n  subst x.\n  lapply (mo_sb_mo (`e) z).\n  intros (moez & allxzsb).\n  lapply (mo_rmw_mo z (`f)).\n  intros (mozf & allzyrmw).\n  apply NNPP; intros nrmw.\n  apply allzyrmw.\n  esplit; esplit.\n  eauto.\n  esplit; esplit.\n  esplit; eauto.\n  intros nrmw2; apply nrmw; auto.\n  left; auto.\n  1-2: auto.\n\n  subst x y.\n  apply sig_ext in ff'; subst e'.\n  lapply (mo_sb_mo (`e) z).\n  intros (moez & allxzsb).\n  lapply (mo_rmw_mo z (`f')).\n  intros (mozf & allzyrmw).\n  apply NNPP; intros nrmw.\n  destruct (classic (`f = z)) as [<-|neq].\n\n  apply allxzsb.\n  esplit; esplit.\n  eauto.\n  esplit; esplit.\n  esplit; eauto.\n  intros [nrmw2|nrmw2]; apply nrmw; auto.\n  left; auto.\n\n  destruct (tot_mo (`e) z (`f)); unfold clos_sym; auto.\n  left; apply mo_mo'; auto.\n  apply allzyrmw.\n  esplit; esplit.\n  eauto.\n  esplit; esplit.\n  esplit; eauto.\n  intros nrmw2; apply nrmw; auto.\n  right; apply mo_mo'; auto.\n\n  apply allxzsb.\n  esplit; esplit.\n  eapply mo_mo'; eauto.\n  esplit; esplit.\n  esplit; eauto.\n  intros [nrmw2|nrmw2]; apply nrmw; auto.\n  right; auto.\n  1-2: auto.\n\n  right.\n  lapply (mo_rmw_mo x y).\n  intros (moxy & allzyrmw).\n  apply mo'_mo in moxy as (z' & e' & <- & <- & moxy).\n  eauto.\n  auto.\n\n  right.\n  lapply (mo_sb_mo x z).\n  intros (moxz & allxzsb).\n  apply mo'_mo in moxz as (z' & e' & <- & <- & moxy).\n  eauto.\n  auto.\n\n  right.\n  lapply (mo_rmw_mo z y).\n  intros (mozy & allzyrmw).\n  apply mo'_mo in mozy as (z' & f' & <- & <- & mozy).\n  lapply (mo_sb_mo x (`z')).\n  intros (moxz & allxzsb).\n  apply mo'_mo in moxz as (e' & z'' & <- & yy & moxz).\n  apply sig_ext in yy; subst z''.\n  cut (mo e' f').\n  intros moef; eauto.\n  eapply spo; eauto.\n  1-2: auto.\nQed.\n", "meta": {"author": "datanorris", "repo": "ayam", "sha": "33412ac684c419f4aa08953e785fbc8659c5d5fa", "save_path": "github-repos/coq/datanorris-ayam", "path": "github-repos/coq/datanorris-ayam/ayam-33412ac684c419f4aa08953e785fbc8659c5d5fa/c17alt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2555505029170056}}
{"text": "(** * PHOAS interpretation function for any retract of [var:=interp_base_type] *)\nRequire Import Crypto.Compilers.Syntax.\nRequire Import Crypto.Compilers.ExprInversion.\nRequire Import Crypto.Compilers.SmartMap.\n\nSection language.\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 src dst, op src dst -> interp_flat_type interp_base_type src -> interp_flat_type interp_base_type dst)\n          {var : base_type_code -> Type}\n          (var_of_interp : forall t, interp_base_type t -> var t)\n          (interp_of_var : forall t, var t -> interp_base_type t)\n          (var_is_retract : forall t x, interp_of_var t (var_of_interp t x) = x).\n\n  Fixpoint interpf_retr {t} (e : @exprf base_type_code op var t)\n    : interp_flat_type interp_base_type t\n    := match e in exprf _ _ t return interp_flat_type interp_base_type t with\n       | TT => tt\n       | Var t v => interp_of_var _ v\n       | Op t1 tR opc args => interp_op _ _ opc (@interpf_retr _ args)\n       | LetIn tx ex tC eC\n         => let ev := @interpf_retr _ ex in\n            @interpf_retr _ (eC (SmartVarfMap var_of_interp ev))\n       | Pair tx ex ty ey => (@interpf_retr _ ex, @interpf_retr _ ey)\n       end.\n\n  Definition interp_retr {t} (e : @expr base_type_code op var t)\n    : interp_type interp_base_type t\n    := fun x => interpf_retr (invert_Abs e (SmartVarfMap var_of_interp x)).\nEnd language.\n\nGlobal Arguments interp_retr _ _ _ _ _ _ _ _ !_ / _ .\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/InterpByIso.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.25542162923152334}}
{"text": "(** This file contains record definitions for\n ** type, function and predicate environments.\n **)\nRequire Import Expr SepExpr.\nRequire Import Env.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nModule Type CoreEnv.\n  Parameter core : Repr type.\n  Parameter pc : tvar.\n  Parameter st : tvar.\nEnd CoreEnv.\n\nModule Type Package (ST : SepTheory.SepTheory) (SEP : SepExpr ST).\n  Declare Module CE : CoreEnv.\n\n  Record TypeEnv : Type :=\n  { Types : Repr type\n  ; Funcs : forall ts, Repr (signature (repr CE.core (repr Types ts)))\n  ; Preds : forall ts, \n    Repr (SEP.predicate (repr CE.core (repr Types ts)))\n  }.\n\n  Section Apps.\n    Variable TE : TypeEnv.\n    \n    Definition applyTypes (ls : list type) : list type :=\n      repr CE.core (repr (Types TE) ls).\n    Definition applyFuncs ts (ls : functions (applyTypes ts)) : functions (applyTypes ts) :=\n      repr (Funcs TE ts) ls.\n    Definition applyPreds ts (ls : SEP.predicates (applyTypes ts)) : SEP.predicates (applyTypes ts) :=\n      repr (Preds TE ts) ls.\n  End Apps.\n\n  \n  (** These are reducible by [simpl] **)\n  Definition applyTypes_red TE (ls : list type) : list type :=\n    match TE with\n      | {| Types := ts |} =>\n        repr CE.core (repr ts ls)\n    end.\n  Definition applyFuncs_red TE ts : functions (applyTypes TE ts) -> functions (applyTypes TE ts) :=\n    match TE with\n      | {| Types := ts' ; Funcs := fs |} => fun ls =>\n        repr (fs ts) ls\n    end.\n  Definition applyPreds_red TE ts : SEP.predicates (applyTypes TE ts) -> SEP.predicates (applyTypes TE ts) :=\n    match TE with\n      | {| Types := ts' ; Preds := ps |} => fun ls =>\n        repr (ps ts) ls\n    end.\n\n  Ltac glue_env l r ret :=\n    let res := constr:(\n      let types := Env.repr_combine (Types l) (Types r) in\n      {| Types := types\n       ; Funcs := fun ts => Env.repr_combine (Funcs l (Env.repr types ts)) (Funcs r (Env.repr types ts))\n       ; Preds := fun ts => Env.repr_combine (Preds l (Env.repr types ts)) (Preds r (Env.repr types ts))\n       |})\n    in\n    ret res.\n    \nEnd Package.\n\nModule Type AlgoTypes (ST : SepTheory.SepTheory) (SEP : SepExpr ST) (CE : CoreEnv).\n  Parameter AlgoImpl  : list type -> Type.\n  Parameter AlgoProof : forall ts : list type, \n    functions (repr CE.core ts) -> \n    SEP.predicates (repr CE.core ts) ->\n    AlgoImpl ts -> Type.\nEnd AlgoTypes.\n\nModule Make (ST : SepTheory.SepTheory) (SEP : SepExpr ST) (CE' : CoreEnv) \n  <: Package ST SEP with Module CE := CE'.\n  Module CE := CE'.\n\n  Section TypeEnv.\n    Record TypeEnv : Type :=\n    { Types : Repr type\n    ; Funcs : forall ts, Repr (signature (repr CE.core (repr Types ts)))\n    ; Preds : forall ts, Repr (SEP.predicate (repr CE.core (repr Types ts)))\n    }.\n\n    Variable TE : TypeEnv.\n\n    Definition applyTypes (ls : list type) : list type :=\n      repr CE.core (repr (Types TE) ls).\n    Definition applyFuncs ts (ls : functions (applyTypes ts)) : functions (applyTypes ts) :=\n      repr (Funcs TE ts) ls.\n    Definition applyPreds ts (ls : SEP.predicates (applyTypes ts)) : SEP.predicates (applyTypes ts) :=\n      repr (Preds TE ts) ls.\n\n  End TypeEnv.\n\n  Definition applyTypes_red TE (ls : list type) : list type :=\n    match TE with\n      | {| Types := ts |} =>\n        repr CE.core (repr ts ls)\n    end.\n  Definition applyFuncs_red TE ts : functions (applyTypes TE ts) -> functions (applyTypes TE ts) :=\n    match TE with\n      | {| Types := ts' ; Funcs := fs |} => fun ls =>\n        repr (fs ts) ls\n    end.\n  Definition applyPreds_red TE ts : SEP.predicates (applyTypes TE ts) -> SEP.predicates (applyTypes TE ts) :=\n    match TE with\n      | {| Types := ts' ; Preds := ps |} => fun ls =>\n        repr (ps ts) ls\n    end.\n    \nEnd Make.\n\nModule AlgoPack (ST : SepTheory.SepTheory) (SEP : SepExpr ST) (P : Package ST SEP) (A : AlgoTypes ST SEP P.CE).\n\n  Record TypedPackage : Type :=\n  { Env   : P.TypeEnv \n  ; Algos : forall ts, A.AlgoImpl ts\n  ; Algos_correct : forall ts (fs : functions (P.applyTypes Env ts)) ps, \n    @A.AlgoProof (repr (P.Types Env) ts) (P.applyFuncs Env ts fs) (P.applyPreds Env ts ps) (Algos _)\n  }.\n\n  (** given to [TypedPackage]s, combines them and passes the combined [TypedPackage]\n   ** to [k].\n   ** This tactic will fail if any of the environments are not compatible.\n   **)\n  Ltac glue_pack composite composite_correct l r ret :=\n    P.glue_env (Env l) (Env r) ltac:(fun nenv' =>\n      let res := constr:(\n        let nenv := nenv' in\n        let types := P.Types nenv in\n        {| Env   := nenv \n         ; Algos := fun ts => composite (Algos l (P.applyTypes nenv ts)) (Algos r (Env.repr types ts))\n         ; Algos_correct := fun ts fs ps =>\n           composite_correct \n             (Algos_correct l (P.applyTypes nenv ts) (P.applyFuncs nenv fs) (P.applyPreds nenv ps))\n             (Algos_correct r (P.applyTypes nenv ts) (P.applyFuncs nenv fs) (P.applyPreds nenv ps))\n         |})\n      in\n      ret res).\n(*\n(**\n      let algosL := constr:(fun ts => Algos l (applyTypes nenvEnv.repr ntypesV ts)) in\n      let algosR := constr:(fun ts => Algos r (Env.repr ntypesV ts)) in\n      let algosCL :=\n        constr:(fun ts fs ps =>\n          Algos_correct l (Env.repr ntypesV ts)\n          (Env.repr (nfuncsV ts) fs)\n          (Env.repr (npredsV ts) ps)) in\n      let algosCR :=\n        constr:(fun ts fs ps =>\n          Algos_correct r (Env.repr ntypesV ts)\n          (Env.repr (nfuncsV ts) fs)\n          (Env.repr (npredsV ts) ps)) in\n      let pf := constr:(fun ts fs ps => AllAlgos_correct_composite (algosCL ts fs ps) (algosCR ts fs ps)) in\n      opaque pf ltac:(fun pf =>\n      let res :=\n        constr:{|\n          Types := ntypesV;\n          Funcs := nfuncsV;\n          Preds := npredsV;\n          Algos := fun ts => AllAlgos_composite (algosL ts) (algosR ts);\n          Algos_correct := pf\n        |} in\n        ret res)).\n**)\n  \n  Ltac refine_glue_pack l r :=\n    let reduce_repr e := e in\n    let opaque v k := k v in\n    match eval hnf in l with\n      | @Build_TypedPackage ?CT ?PC ?ST ?SAT ?READ ?WRITE ?tl ?fl ?pl ?al ?acl =>\n        match eval hnf in r with\n        | @Build_TypedPackage _ _ _ _ _ _ ?tr ?fr ?pr ?ar ?acr =>\n          refine (\n              let types := repr_combine tl tr in\n              let funcs := fun ts => repr_combine (fl (repr types ts)) (fr (repr types ts)) in\n              let preds := fun ts => repr_combine (pl (repr types ts)) (pr (repr types ts)) in\n              @Build_TypedPackage CT PC ST SAT READ WRITE \n                types funcs preds\n                (fun ts => AllAlgos_composite (al (repr types ts)) (ar (repr types ts)))\n                _ \n               ); \n          (subst; abstract exact (fun ts fs ps => AllAlgos_correct_composite \n                  (acl (repr (repr_combine tl tr) ts) \n                       (repr (repr_combine (fl (repr (repr_combine tl tr) ts)) (fr (repr (repr_combine tl tr) ts))) fs)\n                       (repr (repr_combine (pl (repr (repr_combine tl tr) ts)) (pr (repr (repr_combine tl tr) ts))) ps))\n                  (acr (repr (repr_combine tl tr) ts)\n                       (repr (repr_combine (fl (repr (repr_combine tl tr) ts)) (fr (repr (repr_combine tl tr) ts))) fs)\n                       (repr (repr_combine (pl (repr (repr_combine tl tr) ts)) (pr (repr (repr_combine tl tr) ts))) ps))))\n      end\n  end.\n\n(*\nLtac hlist_from_tuple tpl acc := \n  match tpl with\n    | tt => acc\n    | (?L, ?R) => \n      let acc := hlist_from_tuple R acc in\n      hlist_from_tuple L acc\n    | _ => constr:(@HCons _ _ _ _ tpl acc)\n  end.\n*)\n\n(** given a tuple or list of [TypedPackage]s, this tactic combines them all and calls [k] with \n ** the result.\n **)\nLtac glue_packs packs k :=\n  match type of packs with\n    | TypedPackage _ _ _ _ _ _ => k packs\n    | _ =>\n      match packs with\n        | tt => k BedrockPackage.bedrock_package\n        | nil => k BedrockPackage.bedrock_package\n        | ?L :: ?R =>\n          glue_packs R ltac:(fun R => glue_pack L)\n        | (?L, ?R) =>\n          glue_packs L ltac:(fun L => \n          glue_packs R ltac:(fun R => \n            glue_pack L R k))\n      end\n  end.\n\n(** TODO: is there a way to make this more efficient? **)\nLtac opaque_pack pack :=\n  match eval hnf in pack with\n    | @Build_TypedPackage ?CT ?PC ?ST ?SAT ?READ ?WRITE ?tl ?fl ?pl ?al ?acl =>\n      refine ({|\n        Types := tl ;\n        Funcs := fl ;\n        Preds := pl ;\n        Algos := al ;\n        Algos_correct := _\n      |});\n      abstract (exact acl)\n  end.\n*)\n\nEnd AlgoPack.", "meta": {"author": "gmalecha", "repo": "mirror-shard", "sha": "24f34dee2f78de731f4ef398733ff2c1f1551375", "save_path": "github-repos/coq/gmalecha-mirror-shard", "path": "github-repos/coq/gmalecha-mirror-shard/mirror-shard-24f34dee2f78de731f4ef398733ff2c1f1551375/src/TypedPackage.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4843800842769843, "lm_q1q2_score": 0.2554216220352411}}
{"text": "From CoqMTL Require Import Control.\n\n(** This module contains proofs that various definitions of monads are\n    equivalent. More precisely, we prove that these definitions are\n    equivalent in the sense of the ability to construct  an instance of\n    each of them from the other:\n    - the main definition used throughout the library (from Control.Monad),\n      which says that a monad is an [Applicative] functor with [bind],\n      satisfying the laws [bind_pure_l], [bind_pure_r], [bind_assoc] and\n      [bind_ap], which relates the [Applicative] and [Monad] structure\n\n    - the join-based definition (from Theory.Equivs.MonadJoin), which says\n      that a monad is an [Applicative] functor with [join] that satisfies\n      the laws [join_fmap_join], [join_pure], [join_fmap_pure],\n      [join_fmap_fmap] and [join_ap]\n    - the Kleisli Triple definition, which is very similar to that of\n      Theory.Equivs.MonadBind, but has different operation names and\n      some arguments flipped\n\n    As of now, I can't prove that these are equivalent to the compM-based\n    definition (from Theory.Equivs.MonadComp), which says that a monad is\n    something that has monadic composition which is associative and has\n    a neutral element. *)\n\n(** First we require all the necessary modules and repack them so as to\n    refer to them by nonconflicting names. *)\n\nFrom CoqMTL Require MonadJoin.\nFrom CoqMTL Require MonadBind.\nFrom CoqMTL Require MonadComp.\n\nModule Join.\nInclude MonadJoin.\nEnd Join.\n\nModule Bind.\nInclude MonadBind.\nEnd Bind.\n\nModule Comp.\nInclude MonadComp.\nEnd Comp.\n\n(** Each proof consists of two instances, one deriving [Monad] from the\n    definition at hand and the other one deriving an instance for that\n    definition from [Monad]. *)\n\n(** * join-based definition *)\n\n#[refine]\n#[export]\nInstance Join_to_Monad\n  (M : Type -> Type) (inst : Join.Monad M) : Monad M :=\n{\n  is_applicative := @Join.is_applicative M inst;\n  bind := @Join.bind M inst\n}.\nProof.\n  1, 2, 4: MonadJoin.mjoin.\n  apply Join.assoc.\nDefined.\n\n#[refine]\n#[export]\nInstance Monad_to_Join (M : Type -> Type) (inst : Monad M)\n  : Join.Monad M :=\n{\n  is_applicative := @is_applicative M inst;\n  join := @join M inst\n}.\nProof.\n  all: intros; unfold join, compose; try ext x.\n    rewrite bind_assoc, bind_fmap. unfold compose, id. reflexivity.\n    rewrite bind_pure_l. reflexivity.\n    rewrite bind_fmap, <- bind_pure_r. f_equal.\n    rewrite bind_fmap, fmap_bind. f_equal.\n    rewrite !bind_ap. monad.\nDefined.\n\n(** * bind-based definition *)\n\n#[refine]\n#[export]\nInstance MonadBind_to_Monad\n  (M : Type -> Type) (inst : Bind.Monad M) : Monad M :=\n{\n  is_applicative := @MonadBind.Applicative_MonadBind M inst;\n  bind := @MonadBind.bind M inst;\n}.\nProof. all: MonadBind.mbind. Defined.\n\n#[refine]\n#[export]\nInstance Monad_to_MonadBind\n  (M : Type -> Type) (inst : Monad M) : MonadBind.Monad M :=\n{\n  pure := @pure M inst;\n  bind := @bind M inst;\n}.\nProof. all: monad. Defined.\n\n(** * Kleisli triple *)\n\nFrom CoqMTL Require Import KleisliTriple.\n\n#[refine]\n#[export]\nInstance Monad_to_KleisliTriple\n  (M : Type -> Type) (inst : Monad M) : KleisliTriple M :=\n{\n  eta := @pure M inst;\n  star := fun A B => flip (@bind M inst A B);\n}.\nProof.\n  all: unfold flip; monad.\nDefined.\n\n#[refine]\n#[export]\nInstance KleisliTriple_to_Monad\n  (M : Type -> Type) (inst : KleisliTriple M) : Monad M :=\n{\n  is_applicative := Applicative_Kleisli M inst;\n  bind := @bind_Kleisli M inst;\n}.\nProof. all: kleisli. Defined.\n\n(** * compM-based definition *)\n\n#[refine]\n#[export]\nInstance Monad_to_MonadComp\n  (M : Type -> Type) (inst : Monad M) : MonadComp.Monad M :=\n{\n  is_applicative := is_applicative;\n  compM := @compM M inst;\n}.\nProof. all: unfold compM; monad. Defined.\n\n(** TODO: MonadComp_to_Monad *)", "meta": {"author": "wkolowski", "repo": "coq-mtl", "sha": "e3ecb0cf0378e62816d391783e7421d769aec26b", "save_path": "github-repos/coq/wkolowski-coq-mtl", "path": "github-repos/coq/wkolowski-coq-mtl/coq-mtl-e3ecb0cf0378e62816d391783e7421d769aec26b/Theory/Equivs/MonadEquiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.25523478461707483}}
{"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 model_lst\n     model_gst model_update_lhst model_update_lst.\n\nSection Gst_update.\n  Context `{!anerisG Mdl Σ, !DB_params}.\n\n   (** Global and local state coherence *)\n\n  Lemma DBM_gs_ls_coh (i: nat) (gs : Gst) (ls : Lst) :\n    i < length DB_addresses →\n    DBM_Gst_valid gs →\n    DBM_Lst_valid i ls →\n    gs.(Gst_hst) !! i = Some ls.(Lst_hst) →\n    dom ls.(Lst_mem) ⊆ dom gs.(Gst_mem) ∧\n    ∀ k v, k ∈ DB_keys → ls.(Lst_mem) !! k = Some v →\n           ∃ a h, gs.(Gst_mem) !! k = Some h ∧ a ∈ h ∧ a.(we_val) = v.\n  Proof.\n    intros.\n    split.\n    {  erewrite DBM_GstValid_dom; last done; by eapply DBM_LSTV_dom_keys. }\n    intros k v Hk Hkv.\n    eapply DBM_LSTV_vals_Some in Hkv as [Hv1 Hkv2]; eauto.\n    set (Observe_lhst (restrict_key k (Lst_hst ls))) as e in *.\n    apply compute_maximals_correct in Hkv2 as ([He Hem2]%elem_of_filter & Hem').\n    eapply DBM_GV_hst_in_mem in Hem2 as (h & Hh & Heh);\n      eauto using elem_of_list_lookup_2.\n    simplify_eq/=.\n    eexists (erase e), h; split_and!;\n      [by rewrite -He|done|by rewrite -erase_val].\n  Qed.\n\nLemma DBM_mem_dom_update {A: Type} k (v : A) (d: gmap Key A) :\n    k ∈ DB_keys →\n    dom d = DB_keys →\n    dom (<[k:=v]> d) = DB_keys.\n  Proof. by set_solver. Qed.\n\n  Lemma DBM_gs_hst_valid_update gs i s m:\n    DBM_Gst_valid gs →\n    DBM_lhst_valid i s →\n    DBM_gs_hst_valid\n      {| Gst_mem := m; Gst_hst := <[i:=s]> (Gst_hst gs) |}.\n  Proof.\n    intros Hgv Hsv j sj Hgs; simpl.\n    destruct (decide (j = i)) as [-> | ].\n    - rewrite list_lookup_insert in Hgs.\n      + by simplify_eq.\n      + pose proof (DBM_GV_hst_size Hgv).\n        epose proof DBM_LHV_bound_at.\n        erewrite (DBM_GV_hst_size Hgv); eauto.\n    - rewrite list_lookup_insert_ne in Hgs; last done.\n      eapply DBM_GV_hst_lst_valid; eauto.\n  Qed.\n\nLemma DBM_gs_hst_size_update gs i s m:\n    DBM_Gst_valid gs →\n    DBM_gs_hst_size\n      {| Gst_mem := m; Gst_hst := <[i:=s]> (Gst_hst gs) |}.\n  Proof.\n    intros Hgv. rewrite /DBM_gs_hst_size //=.\n    rewrite insert_length.\n    by eapply DBM_GV_hst_size.\n  Qed.\n\n  Lemma DBM_system_write_update_gst\n        (k : Key) (v : val) (i : nat) (gs : Gst) (ls : Lst) mk :\n    k ∈ DB_keys →\n    DBM_Lst_valid i ls →\n    DBM_Gst_valid gs →\n    gs.(Gst_hst) !! i = Some ls.(Lst_hst) →\n    gs.(Gst_mem) !! k = Some mk →\n    let t := incr_time ls.(Lst_time) i  in\n    let e := ApplyEvent k v t i (S (size ls.(Lst_hst))) in\n    let s := ls.(Lst_hst) ∪ {[ e ]} in\n    let m := (<[ k := mk ∪ {[erase e]} ]> gs.(Gst_mem)) in\n    let Ss := <[i := s]> gs.(Gst_hst) in\n    DBM_Gst_valid (GST m Ss).\n   Proof.\n    intros Hk Hvl Hvg Hgs Hgm t e s m Ss.\n    pose proof (DBM_LSTV_at Hvl) as Hi.\n    pose proof DBM_LSTV_hst_valid Hvl as Hvlh.\n    assert (update_condition i e (Lst_time ls)) as Hcond.\n    eapply update_condition_write; eauto.\n    pose proof Hcond as\n            (Hi' & Htlen & Hetlen & Hkey & Heorig & Het & Het' & Het'').\n    split.\n    - by eapply DBM_mem_dom_update; eauto; eapply DBM_GV_dom.\n    - eapply DBM_gs_hst_size_update; eauto.\n    - eapply DBM_gs_hst_valid_update; eauto.\n      rewrite /DBM_lst_hst_valid in Hvlh.\n      eapply DBM_lhst_update.\n      + eauto.\n      + eauto.\n      + eauto.\n      + eauto using DBM_Lst_valid_time_le; eauto.\n      + rewrite (DBM_LSTV_time Hvl (ae_orig e) Heorig).\n        symmetry.\n        pose proof (lsec_lsup_length (ae_orig e)); eauto.\n      + intros ? j0 Hj0.\n        rewrite (DBM_LSTV_time Hvl j0 Hj0).\n        symmetry.\n        pose proof (lsec_lsup_length (ae_orig e)); eauto.\n      + intros j0 Hj0.\n        rewrite (DBM_LSTV_time Hvl j0 Hj0).\n        pose proof (lsec_lsup_length\n                      i j0 (Lst_hst ls) Hvlh Hj0)\n          as Hll. rewrite Hll.\n        eauto with lia.\n    - intros s1 Hs1 e1 He1. simpl in Hs1.\n      subst Ss. apply elem_of_list_lookup in Hs1 as (j & Hs1).\n      destruct (decide (i = j)) as [<-|Hneqij].\n      + rewrite list_lookup_insert in Hs1. inversion Hs1. subst s1.\n        clear Hs1. apply elem_of_union in He1 as [He1|?%elem_of_singleton_1].\n        * destruct (λ H, DBM_GV_hst_in_mem Hvg (Lst_hst ls) H e1)\n            as (h' & Hh' & He''h'); eauto using elem_of_list_lookup_2.\n          destruct (decide (k = ae_key e1)) as [->|Hneq].\n          ** subst m; setoid_rewrite lookup_insert.\n             exists (mk ∪ {[erase e]}); split; first done.\n             rewrite Hgm // in Hh'. set_solver.\n          ** subst m; setoid_rewrite lookup_insert_ne; last done.\n             eexists; eauto.\n        * simpl. subst e1 m.\n          assert (k = ae_key e) as <- by eauto.\n          setoid_rewrite lookup_insert.\n          exists (mk ∪ {[erase e]}); split; first done.\n          set_solver.\n        * rewrite (DBM_GV_hst_size Hvg) //.\n      + rewrite list_lookup_insert_ne in Hs1.\n        destruct (λ H, DBM_GV_hst_in_mem Hvg s1 H e1)\n          as (h' & Hh' & He''h'); eauto using elem_of_list_lookup_2.\n        destruct (decide (k = ae_key e1)) as [->|Hneq]; simpl.\n        * subst m.\n          setoid_rewrite lookup_insert.\n          rewrite Hh' in Hgm.\n          eexists _. split_and!; eauto with set_solver.\n        * exists h'; split_and!; eauto.\n          by rewrite lookup_insert_ne; last done.\n        * done.\n    - intros a h Hm Hah.\n      subst m Ss s. simpl in Hm. simpl.\n      destruct (decide ((we_key a) = k)) as [ <- | Hneq0 ].\n      + rewrite lookup_insert in Hm.\n        simplify_eq.\n        apply elem_of_union in Hah as[ Hamk| Ha1%elem_of_singleton_1].\n        * destruct (DBM_GV_mem_in_hst Hvg a mk Hgm Hamk)\n            as (sa & saa & ea & Hsa & Hsaa & Hea & Hear).\n          destruct (decide (i = we_orig a)) as [Heq|Hneq].\n          ** eexists (Lst_hst ls ∪ {[e]}), (saa ∪ {[e]}), ea.\n             split_and!.\n             *** subst; rewrite list_lookup_insert; first done.\n                 rewrite (DBM_GV_hst_size Hvg) //.\n             *** subst; rewrite //. set_solver.\n             *** set_solver.\n             *** done.\n          ** eexists _, _, _.\n             split_and!; eauto.\n             by rewrite list_lookup_insert_ne.\n        * eexists _, _, e.\n          split_and!; eauto.\n          ** rewrite Ha1. rewrite list_lookup_insert //=.\n             rewrite (DBM_GV_hst_size Hvg) //.\n          ** rewrite DBM_lsec_union DBM_lsec_singleton_in.\n             *** set_solver.\n             *** by rewrite Ha1.\n      + rewrite lookup_insert_ne //= in Hm.\n        destruct (decide (i = we_orig a)) as [Heq|Hneq].\n       * assert\n         (∃ (s0 si : gset apply_event) (e0 : apply_event),\n             Gst_hst gs !! we_orig a =\n             Some s0 ∧ DBM_lsec (we_orig a) s0 = si\n             ∧ e0 ∈ si ∧ erase e0 = a)\n           as (s0 & si & e0 & Hs0 & Hs1 & Hs2 & Hs3)\n             by by eapply DBM_GV_mem_in_hst.\n         rewrite -!Heq. rewrite -!Heq in Hs0 Hs1.\n         rewrite list_lookup_insert.\n         ** do 3 eexists. repeat split; eauto.\n           rewrite /s0. set_solver.\n         ** eapply lookup_lt_is_Some_1; eauto.\n       * rewrite //=.\n         simpl in Hm.\n         rewrite list_lookup_insert_ne; eauto.\n         eapply DBM_GV_mem_in_hst; eauto.\n    - intros k1 h1 a1 Hh1 Ha1.\n      rewrite /m //= in Hh1.\n      destruct (decide (k1 = k)) as [-> | ].\n      + rewrite lookup_insert //= in Hh1.\n        simplify_eq.\n        apply elem_of_union in Ha1 as [| ?%elem_of_singleton_1];\n          [|set_solver].\n        eapply DBM_GV_mem_elements_key; eauto.\n      + rewrite lookup_insert_ne //= in Hh1.\n        eapply DBM_GV_mem_elements_key; eauto.\n   Qed.\n\n   Lemma DBM_system_apply_update_gst\n        (i : nat) (gs : Gst) (ls : Lst)\n        (a : write_event) (h: gset write_event) :\n    DBM_Gst_valid gs →\n    DBM_Lst_valid i ls →\n    gs.(Gst_hst) !! i = Some ls.(Lst_hst) →\n    gs.(Gst_mem) !! a.(we_key) = Some h →\n    a ∈ h →\n    a.(we_orig) ≠ i →\n    let t := incr_time ls.(Lst_time) a.(we_orig) in\n    let e := ApplyEvent (we_key a) (we_val a) (we_time a) (we_orig a)\n                        (S (size ls.(Lst_hst))) in\n    let s := ls.(Lst_hst) ∪ {[ e ]} in\n    let d := (<[ a.(we_key) := a.(we_val) ]> ls.(Lst_mem)) in\n    let Ss := (<[i := s]> gs.(Gst_hst)) in\n    update_condition i e ls.(Lst_time) →\n    DBM_Gst_valid (GST gs.(Gst_mem) Ss).\n   Proof.\n     intros Hvg Hvl Hgsi ?????????.\n     split.\n     - apply (DBM_GV_dom Hvg); eauto.\n     - eapply DBM_gs_hst_size_update; eauto.\n     - eapply DBM_gs_hst_valid_update; eauto.\n       assert (DBM_Lst_valid i {|Lst_mem := d; Lst_time := t; Lst_hst := s|})\n         as Hvlst.\n       { apply (DBM_lst_update e i ls Hvl); eauto. }\n       eapply (DBM_LSTV_hst_valid Hvlst).\n     - intros s1 Hs1 e1 He1. simpl in Hs1.\n       subst Ss. apply elem_of_list_lookup in Hs1 as (j & Hs1).\n      destruct (decide (i = j)) as [<-|Hneqij].\n      + rewrite list_lookup_insert in Hs1. inversion Hs1. subst s1.\n        clear Hs1. apply elem_of_union in He1 as [He1|?%elem_of_singleton_1].\n        * destruct (λ H, DBM_GV_hst_in_mem Hvg (Lst_hst ls) H e1)\n            as (h' & Hh' & He''h'); eauto using elem_of_list_lookup_2.\n        * simpl. subst e1.\n          assert (a = erase e) as <- by by destruct a.\n          eauto.\n        * rewrite (DBM_GV_hst_size Hvg)  //.\n          by eapply DBM_LSTV_at.\n      + rewrite list_lookup_insert_ne in Hs1.\n        destruct (λ H, DBM_GV_hst_in_mem Hvg s1 H e1)\n          as (h' & Hh' & He''h'); eauto using elem_of_list_lookup_2.\n        done.\n     - intros a1 h1 Hm Ha1.\n       destruct (decide (i = we_orig a1)) as [Heq|Hneq].\n       + assert\n         (∃ (s0 si : gset apply_event) (e0 : apply_event),\n             Gst_hst gs !! we_orig a1 =\n             Some s0 ∧ DBM_lsec (we_orig a1) s0 = si\n             ∧ e0 ∈ si ∧ erase e0 = a1)\n           as (s0 & si & e0 & Hs0 & Hs1 & Hs2 & Hs3)\n             by by eapply DBM_GV_mem_in_hst.\n         rewrite -!Heq. rewrite -!Heq in Hs0 Hs1.\n         rewrite list_lookup_insert.\n         * do 3 eexists. repeat split; eauto.\n           rewrite /s. set_solver.\n         * eapply lookup_lt_is_Some_1; eauto.\n       + rewrite /Ss //=.\n         simpl in Hm.\n         rewrite list_lookup_insert_ne; eauto.\n         eapply DBM_GV_mem_in_hst; eauto.\n     - rewrite /DBM_gs_gmem_elements_key /=.\n       eapply DBM_GV_mem_elements_key; eauto.\n   Qed.\n\nEnd Gst_update.\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_gst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2552347774852795}}
{"text": "(**\nCreates functorial lemmas that the parametricity translation\nbehaves like a functor in respect to its parameters\n\nApplication: When proving the induction lemma, \none encounters the problem that the parametricity translation argument\nlistᵗ rose roseᵗ H is given stating that the property roseᵗ holds for all rose\ntrees in the list. But we want the nested inductive hypothesis\nlistᵗ rose P H that the property P under consideration in the induction\nholds for all trees in the list.\nTherefore, we need to translate the proofs of roseᵗ to P.\nThis is possible for two reasons:\n* The inductive proof transforms roseᵗ instances into proofs of P\n    (we state that P holds for all roseᵗ)\n* Secondly, the parametricity translation of a container simply boundles\n    all proofs for the elements in it.\n  Therefore, all proofs can be replaced for another property, and thus,\n  the parametricity translation of a container behaves like a functor.\n\nNote: The substitution of P for roseᵗ makes it clear why\n    the induction does not carry the roseᵗ instances in the predicate\n    as such handling for nested types would no longer be possible.\n    Additionally, the generates lemma is less cluttered as it is ultimately\n    a lemma for rose not roseᵗ.\n\nexample:\nlistᵗ A Aᵗ x\nwith A:Type, Aᵗ:A->Type, x:list A\n\nthe functorial lemma has type:\n∀ A (Aᵗ:A->Type) (Aᵗ':A->Type) (F_A: ∀ (a:A), Aᵗ a -> Aᵗ' a)\n(x:list A),\nlistᵗ A Aᵗ x -> listᵗ A Aᵗ' x\n\nNote:\nA->Type can be viewed as (Typeᵗ A)\n\nFor each pair of parameter and translation another translation as destination\nis introduced together with a function stating the translation property for this paramter.\nThis property will be recursively instantiated in the proofs.\nIf the parameter has no arguments or does not result in a sort, a dummy value like True\nis introduced as each parametricity translated argument contains the same information.\n\nThe indices contain no further information needed to be transferred between instances.\nThey do not possess a functorial nature as they are dictated by inversion.\nTherefore, they are carried over.\nA special indice is the instance of the original type (list in the example above).\nBut this instance does not need any special care.\n\n*)\nRequire Import util.\n\nFrom MetaCoq.Template Require Import All.\n\nFrom MetaCoq Require Import All.\nRequire Import String List.\n(* Local Open Scope string. *)\nImport ListNotations Nat.\nImport MCMonadNotation.\n\nFrom MetaCoq.PCUIC Require Import \n     PCUICAst PCUICAstUtils PCUICInduction\n     PCUICLiftSubst PCUICEquality\n     PCUICUnivSubst PCUICTyping PCUICGeneration.\n\nFrom MetaCoq.PCUIC Require Import TemplateToPCUIC.\nFrom MetaCoq.PCUIC Require Import PCUICToTemplate.\n\nSection Functorial.\n\n    Variable \n        (inductive:inductive)\n        (uinst:Instance.t)\n        (mind:mutual_inductive_body)\n        (ind:one_inductive_body).\n\n    Definition ind_term := tInd inductive uinst.\n\n    Definition non_uniform_param_count := 0. (* should not matter here *)\n    Definition ind_type := ind.(ind_type). (* type of the inductive *)\n    Definition ctx_retTy := decompose_prod_assum [] ind_type. (* get params and indices and inner retTy *)\n    Definition ctx := ctx_retTy.1.\n    Definition retTy := ctx_retTy.2.\n        (* for list: ctx=[Type], retTy=Type *)\n    Definition indice_ctx := ind_indices ind.\n    Definition all_param_ctx := skipn #|indice_ctx| ctx. (* parameters and non-uniform parameter *)\n    Definition non_uni_param_ctx := firstn non_uniform_param_count all_param_ctx. (* non-uniform are behind => at the front *)\n    Definition param_ctx := skipn #|non_uni_param_ctx| all_param_ctx. \n\n    Definition TrueQ :=\n        TemplateToPCUIC.trans [] <% True %>.\n\n\n    (*\n    given an argument Aᵗ generates the functorial property term\n    for ∀, copy the binder and remember to apply the arguments\n    for Sort, generate Aᵗ args -> Aᵗ' args \n    Otherwise generate True\n     *)\n        (* this is something like parametricity itself *)\n    Fixpoint func x y args t :=\n        match t with\n        | tSort univ => \n            tProd rAnon (mkApps x args) (mkApps (lift0 1 y) (map (lift0 1) args))\n        | tProd na a b =>\n            tProd na a (\n                func (lift0 1 x) (lift0 1 y) (map (lift0 1) args ++ [tRel 0]) b\n            )\n        | _ => TrueQ\n        end.\n\n\n    Definition app_arg_list num args := map (fun x => x+num) args++mkNums num.\n\n    (* no context but list of params *)\n    (* \n    for params A, Aᵗ add Aᵗ' and F_A\n    takes list of param applications for the original and transformed term\n    returns the number of parameter groups, the list of argument applications\n    as number for the binder and lastly the list of new arguments (params & indices)\n     *)\n    Fixpoint augment (params:context) (arg1 arg2:list nat):= \n        match params with\n        | x::xᵗ::xr => \n            let '((groups,arg1,arg2), aug_args) := \n                augment xr \n                    (map (fun x => x+4) arg1++[3;2])\n                    (map (fun x => x+4) arg2++[3;1]) in\n                ((S groups, arg1,arg2),\n                    x::xᵗ::\n                    (map_decl (lift0 1) xᵗ)::\n                    (vass rAnon (func (tRel 1) (tRel 0) [] (lift0 2 xᵗ.(decl_type))))::\n                    (mapi (fun i a => map_decl (lift 2 i) a) aug_args))\n        | _ => \n        let indices := rev (indice_ctx) in\n        ((0,\n            app_arg_list (#|params|+#|indices|) arg1, \n            app_arg_list (#|params|+#|indices|) arg2),params++indices)\n        end.\n\n        (* computes number of param groups and type of the functorial property *)\n    Definition type_ := \n        let '((groups,arg1,arg2),aug_args) := augment (rev param_ctx) [] [] in\n        let aug_args_ctx := rev (aug_args) in\n        (groups,\n        it_mkProd_or_LetIn \n            aug_args_ctx\n        (tProd rAnon\n        (mkApps ind_term (map tRel arg1))\n        (lift0 1 (mkApps ind_term (map tRel arg2)))\n        ))\n        .\n\n    Definition functorial_type_groups :=\n        on_snd PCUICToTemplate.trans type_.\n\n    Definition type := snd type_.\n\n    Definition functorial_type :=\n    PCUICToTemplate.trans type.\n\n    (*\n    Generation of the functorial property \n    currently, the properties are only realized \n    using obligations\n     *)\n    (* Definition functorial :=\n    tCast \n    (PCUICToTemplate.trans\n        placeholder\n        (* (it_mkLambda_or_LetIn\n        lemma_argument_ctx\n        ) *)\n    )\n    Cast\n    (PCUICToTemplate.trans type). *)\n    \nEnd Functorial.\n\n\nLtac ind_on_last :=\n  lazymatch goal with\n  | |- forall x y, ?H => intros ?;ind_on_last\n  | |- forall y, ?H => \n      let inst := fresh \"x\" in\n      intros inst;induction inst (* using database *)\n  | _ => fail \"not applicable\"\n  end.\nGlobal Obligation Tactic := cbn;ind_on_last;econstructor;auto.\n\n", "meta": {"author": "NeuralCoder3", "repo": "nested_induction_v2", "sha": "6e6f8a01c24ac7d04c59e2cad8ede21b169cd711", "save_path": "github-repos/coq/NeuralCoder3-nested_induction_v2", "path": "github-repos/coq/NeuralCoder3-nested_induction_v2/nested_induction_v2-6e6f8a01c24ac7d04c59e2cad8ede21b169cd711/functorial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2552347774852795}}
{"text": "(* Do not edit this file, it was generated automatically *)\nRequire Import VST.floyd.proofauto.\nRequire Import VST.progs64.message.\n\n#[export] Instance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\n(* This program, and its verification, are described in Chapter 29\n   of _Program Logics for Certified Compilers_, by Appel et al., 2014 *)\n\nLocal Open Scope Z.\nLocal Open Scope logic.\n\n(*   mf_assert msgfmt sh buf len data  := the [data] is formatted into a message\n         at most [len] bytes,  stored starting at address [buf] with share [sh] *)\n\nRecord message_format (t: type) : Type :=\nmf_build {\n   mf_size: Z;\n   mf_data_assert: forall (data: reptype t), Prop;\n   mf_assert: forall (sh: share) (buf: val) (len: Z) (data: reptype t), mpred;\n   mf_size_range:  0 <= mf_size <= Int.max_signed;\n   mf_bufprop: forall sh buf len data,\n           mf_assert sh buf len data |--\n                 !!(0 <= len <= mf_size) && memory_block sh len buf;\n   mf_restbuf := fun (sh: share) (buf: val) (len: Z) =>\n          memory_block sh (mf_size-len) (offset_val len buf)\n}.\n\nArguments mf_build {t}.\nArguments mf_size {t}.\nArguments mf_data_assert {t}.\nArguments mf_assert {t}.\nArguments mf_bufprop {t}.\nArguments mf_size_range {t}.\nArguments mf_restbuf {t}.\n\nLemma mf_assert_local_facts: forall t (mf: message_format t) sh buf len (data: reptype t),\n   mf_assert mf sh buf len data |-- \n    !! (0 <= len <= mf_size mf /\\ isptr buf).\nProof.\nintros.\neapply derives_trans;[ apply mf_bufprop | ].\nentailer!.\nQed.\n\n#[export] Hint Resolve mf_assert_local_facts : saturate_local.\n\n\nDefinition t_struct_intpair := Tstruct _intpair noattr.\nDefinition t_struct_message := Tstruct _message noattr.\n\nProgram Definition intpair_message: message_format t_struct_intpair :=\n  mf_build 8 (fun data => is_int I32 Signed (fst data) /\\ is_int I32 Signed (snd data))\n             (fun sh buf len data => !!(len=8/\\ is_int I32 Signed (fst data) /\\ is_int I32 Signed (snd data))\n                           && data_at sh (tarray tint 2) [fst data; snd data] buf)\n      _ _.\nNext Obligation.\ncompute; split; congruence.\nQed.\nNext Obligation.\n  entailer!!.\n  change 8 with (sizeof (tarray tint 2)).\n  apply data_at_memory_block.\nQed.\n\nDefinition serialize_spec {t: type} (format: message_format t) :=\n  WITH data: reptype t, p: val, buf: val, sh: share, sh': share\n  PRE [ tptr tvoid, tptr tuchar ]\n          PROP (readable_share sh; writable_share sh';\n                mf_data_assert format data;\n                align_compatible tint buf)\n          PARAMS (p; buf)\n          SEP (data_at sh t data p;\n                 memory_block sh' (mf_size format) buf)\n  POST [ tint ]\n         EX len: Z,\n          PROP() RETURN (Vint (Int.repr len))\n          SEP( data_at sh t data p;\n                 mf_assert format sh' buf len data;\n                 mf_restbuf format sh' buf len).\n\nDefinition deserialize_spec {t: type} (format: message_format t) :=\n  WITH data: reptype t, p: val, buf: val, sh: share, sh': share, len: Z\n  PRE [ tptr tvoid, tptr tuchar, tint ]\n          PROP (readable_share sh'; writable_share sh;\n                0 <= len <= mf_size format)\n          PARAMS (p; buf; Vint (Int.repr len))\n          SEP (mf_assert format sh' buf len data;\n                 data_at_ sh t p)\n  POST [ tvoid ]\n          PROP (mf_data_assert format data)  RETURN ()\n          SEP (mf_assert format sh' buf len data;\n                 data_at sh t data p).\n\nDefinition intpair_serialize_spec :=\n DECLARE _intpair_serialize (serialize_spec intpair_message).\n\nDefinition intpair_deserialize_spec :=\n DECLARE _intpair_deserialize (deserialize_spec intpair_message).\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 message (sh: share) {t: type} (format: message_format t) (m: val) : mpred :=\n  EX fg: val*val,\n          func_ptr' (serialize_spec format) (fst fg) *\n          func_ptr' (deserialize_spec format) (snd fg) *\n       data_at sh t_struct_message (Vint (Int.repr (mf_size format)), (fst fg, snd fg)) m.\n\nDefinition Gprog : funspecs :=   ltac:(with_library prog [\n    intpair_serialize_spec; intpair_deserialize_spec; main_spec]).\n\nLemma body_intpair_serialize: semax_body Vprog Gprog f_intpair_serialize intpair_serialize_spec.\nProof.\nunfold intpair_serialize_spec.\nunfold serialize_spec.\nstart_function.\ndestruct H as [Dx Dy].\ndestruct data as [[|x1 | | | | ] [|y1 | | | | ]]; try contradiction. clear Dx Dy.\n\nchange (mf_size intpair_message) with (sizeof (tarray tint 2)).\nassert_PROP (field_compatible (tarray tint 2) [] buf).\n  entailer!.\n  hnf in H; decompose[and] H; repeat split; auto.\n  (* TODO: abstract the following proof. *)  \n  unfold align_compatible in H0 |- *.\n  destruct buf; auto.\n  constructor.\n  intros.\n  eapply align_compatible_rec_by_value_inv in H0; [| reflexivity].\n  econstructor; [reflexivity |].\n  apply Z.divide_add_r; auto.\n  exists i0; rewrite Z.mul_comm; auto.\nrewrite memory_block_data_at_; auto.\nchange (data_at_ sh' (tarray tint 2) buf) with\n   (data_at sh' (tarray tint 2) [Vundef;Vundef] buf).\nforward. (* x = p->x; *)\nforward. (* y = p->y; *)\nforward. (*  ((int * )buf)[0]=x; *)\nforward. (*  ((int * )buf)[1]=y; *)\nforward. (* return 8; *)\nExists 8.\nunfold mf_restbuf. simpl.\nrewrite memory_block_zero.\nentailer!!.\nQed.\n\nLemma body_intpair_deserialize: semax_body Vprog Gprog f_intpair_deserialize intpair_deserialize_spec.\nProof.\nunfold intpair_deserialize_spec, deserialize_spec.\nstart_function.\nhnf in data; simpl in data. (* This speeds things up dramatically *)\nsimpl. Intros. subst len.\ndestruct data as [[|x1 | | | | ] [|y1 | | | | ]]; try contradiction.\nclear H H1 H2.\nforward. (* x = ((int * )buf)[0]; *)\nforward. (* y = ((int * )buf)[1]; *)\nforward. (* p->x = x; *)\nforward. (* p->y = y; *)\nentailer!.\nsplit; simpl; auto.\nunfold mf_assert.\nsimpl.\nentailer!!.\nQed.\n\nLemma body_main: semax_body Vprog Gprog f_main main_spec.\nProof.\nfunction_pointers.\nstart_function.\nset (ipm := gv _intpair_message).\nfold cc_default noattr.\nmake_func_ptr _intpair_deserialize.\nmake_func_ptr _intpair_serialize.\nset (des := gv _intpair_deserialize).\nset (ser := gv _intpair_serialize).\nmatch goal with \n |- context [mapsto_zeros 4 Ews _] => \n  (* 64-bit mode *)\n  sep_apply mapsto_zeros_memory_block; auto;\n  gather_SEP (mapsto _ _ _ (offset_val 0 des))\n      (mapsto _ _ _ (offset_val 0 ser))\n      (memory_block Ews 4 _)\n      (data_at _ _ _ ipm)\n | _ => (*32-bit mode *)\n  gather_SEP (mapsto _ _ _ (offset_val 0 des))\n      (mapsto _ _ _ (offset_val 0 ser))\n      (data_at _ _ _ ipm)\nend.\nreplace_SEP 0 \n    (data_at Ews t_struct_message\n      (Vint (Int.repr (mf_size intpair_message)), (ser, des)) ipm). {\n entailer!.\n unfold_data_at (data_at _ t_struct_message _ ipm).\n rewrite (field_at_data_at _ _ _ _ ipm).\nrewrite data_at_tuint_tint.\n(* rewrite <- (mapsto_field_at _ _ [StructField _bufsize] (Vint (Int.repr 8))) by auto with field_compatible. *)\n rewrite <- (mapsto_field_at _ _ [StructField _deserialize] des) by auto with field_compatible.\n rewrite <- (mapsto_field_at _ _ [StructField _serialize] ser) by auto with field_compatible.\n rewrite !field_compatible_field_address by auto with field_compatible.\n simpl.\n normalize.\n unfold spacer, at_offset; simpl.\n cancel.\n}\nforward. (* p.x = 1; *)\nforward. (* p.y = 2; *)\nforward. (* ser = intpair_message.serialize; *)\n\nrewrite <- memory_block_data_at__tarray_tuchar_eq by computable.\nchange (memory_block Tsh 8 v_buf)\nwith (memory_block Tsh (mf_size intpair_message) v_buf).\n\nassert_PROP (align_compatible tint v_buf).\n  entailer!.\n  destruct HPv_buf; subst; simpl.\n  econstructor; [reflexivity | apply Z.divide_0_r].\nforward_call (* len = ser(&p, buf); *)\n      ((Vint (Int.repr 1), Vint (Int.repr 2)), v_p, v_buf, Tsh, Tsh).\n  split3; auto.\n  repeat split; auto.\nIntros rest.\nsimpl.\nIntros. subst rest.\n\nforward. (* des = intpair_message.deserialize; *)\nforward_call (* des(&q, buf, 8); *)\n        ((Vint (Int.repr 1), Vint (Int.repr 2)), v_q, v_buf, Tsh, Tsh, 8).\n  simpl. fold t_struct_intpair. entailer!.\n  simpl; computable.\n(* after the call *)\nforward. (* x = q.x; *)\nforward. (* y = q.y; *)\nforward. (* return x+y; *)\nsimpl.\nentailer!.\nsep_apply (data_at_memory_block Tsh (tarray tint 2) [Vint (Int.repr 1); Vint (Int.repr 2)] v_buf).\nunfold sizeof; simpl Ctypes.sizeof.\nsep_apply (memory_block_data_at__tarray_tuchar Tsh v_buf 8).\n   computable.\nentailer!!.\nQed.\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_message.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2552347774852795}}
{"text": "Require Import Coq.Logic.FunctionalExtensionality.\nRequire Import ExtLib.Data.HList.\nRequire Import ExtLib.Tactics.\nRequire Import MirrorCore.Util.Compat.\nRequire Import MirrorCore.ExprI.\nRequire Import MirrorCore.AbsAppI.\nRequire Import MirrorCore.Lambda.ExprCore.\nRequire Import MirrorCore.Lambda.ExprD.\nRequire Import MirrorCore.Lambda.ExprDFacts.\nRequire Import MirrorCore.Lambda.Red.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nSection some_lemmas.\n  Variable typ : Set.\n  Variable sym : Set.\n  Variable RType_typ : RType typ.\n  Variable RTypeOk : RTypeOk.\n  Variable Typ2_arr : Typ2 _ RFun.\n  Variable Typ2Ok_arr : Typ2Ok Typ2_arr.\n  Variable RSym_sym : RSym sym.\n  Variable RSymOk_sym : RSymOk RSym_sym.\n\n  Lemma lambda_exprD_typeof_not_None\n  : forall tus tvs (e : expr typ sym) (t : typ) val,\n      lambda_exprD tus tvs t e = Some val ->\n      typeof_expr tus tvs e <> None.\n  Proof.\n    intros.\n    generalize (lambda_exprD_typeof_expr _ (or_introl H)).\n    congruence.\n  Qed.\n\n  Lemma lambda_exprD_typeof_Some\n  : forall tus tvs e t val,\n      lambda_exprD tus tvs t e = Some val ->\n      typeof_expr tus tvs e = Some t.\n  Proof.\n    intros.\n    generalize (lambda_exprD_typeof_expr _ (or_introl H)).\n    congruence.\n  Qed.\n\n  Lemma lambda_exprD_typeof_eq\n  : forall tus tvs e t t' val,\n      lambda_exprD tus tvs t e = Some val ->\n      typeof_expr tus tvs e = Some t' ->\n      t = t'.\n  Proof.\n    intros.\n    generalize (lambda_exprD_typeof_expr _ (or_introl H)).\n    congruence.\n  Qed.\n\n  Global Instance Injective_typ2 {F : Type -> Type -> Type}\n         {Typ2_F : Typ2 RType_typ F} {Typ2Ok_F : Typ2Ok Typ2_F} a b c d :\n    Injective (typ2 a b = typ2 c d) :=\n  { result := a = c /\\ b = d }.\n  abstract (\n      eapply typ2_inj; eauto ).\n  Defined.\n\n  Global Instance Injective_typ1 {F : Type -> Type}\n         {Typ1_F : Typ1 RType_typ F} {Typ2Ok_F : Typ1Ok Typ1_F} a b\n  : Injective (typ1 a = typ1 b) :=\n  { result := a = b }.\n  abstract (\n      eapply typ1_inj; eauto ).\n  Defined.\n\n  Lemma lambda_exprD_AppI tus tvs (t : typ) (e1 e2 : expr typ sym)\n        (P : option (exprT tus tvs (typD t)) -> Prop)\n        (H : exists u v1 v2, lambda_exprD tus tvs (typ2 u t) e1 = Some v1 /\\\n                             lambda_exprD tus tvs u e2 = Some v2 /\\\n                             P (Some (exprT_App v1 v2))) :\n    P (lambda_exprD tus tvs t (App e1 e2)).\n  Proof.\n    autorewrite with exprD_rw; simpl.\n    destruct H as [u [v1 [v2 [H1 [H2 HP]]]]].\n    pose proof (lambda_exprD_typeof_Some _ _ H1).\n    pose proof (lambda_exprD_typeof_Some _ _ H2).\n    repeat (forward; inv_all; subst).\n  Qed.\n\n  Lemma lambda_exprD_InjI tus tvs (t : typ) (f : sym)\n        (P : option (exprT tus tvs (typD t)) -> Prop)\n        (H : exists v, symAs f t = Some v /\\ P (Some (fun _ _ => v))) :\n    P (lambda_exprD tus tvs t (Inj f)).\n  Proof.\n    autorewrite with exprD_rw; simpl.\n    destruct (symAs f t); simpl; destruct H as [v [H1 H2]]; try intuition congruence.\n    inv_all; subst. apply H2.\n  Qed.\n\n  Lemma lambda_exprD_beta tus tvs e t P\n        (H : exists v, lambda_exprD tus tvs t e = Some v /\\ P (Some v)) :\n    P (lambda_exprD tus tvs t (beta e)).\n  Proof.\n    destruct H as [v [H1 H2]].\n    pose proof (beta_sound tus tvs e t).\n    forward; inv_all; subst.\n    assert (v = e1).\n    do 2 (apply functional_extensionality; intro).\n    apply H3. subst. apply H2.\n  Qed.\n\n  Global Instance Injective_lambda_exprD_App tus tvs (e1 e2 : expr typ sym) (t : typ)\n         (v : exprT tus tvs (typD t)):\n    Injective (ExprDsimul.ExprDenote.lambda_exprD tus tvs t (App e1 e2) = Some v) := {\n      result := exists u v1 v2, ExprDsimul.ExprDenote.lambda_exprD tus tvs (typ2 u t) e1 = Some v1 /\\\n                                ExprDsimul.ExprDenote.lambda_exprD tus tvs u e2 = Some v2 /\\\n                                v = exprT_App v1 v2;\n      injection := fun H => _\n    }.\n  Proof.\n    autorewrite with exprD_rw in H.\n    simpl in H. forward; inv_all; subst.\n    do 3 eexists; repeat split; eassumption.\n  Defined.\n\n  Global Instance Injective_lambda_exprD_Inj tus tvs (f : sym) (t : typ) (v : exprT tus tvs (typD t)):\n    Injective (ExprDsimul.ExprDenote.lambda_exprD tus tvs t (Inj f) = Some v) := {\n      result := exists v', symAs f t = Some v' /\\ v = exprT_Inj _ _ v';\n      injection := fun H => _\n    }.\n  Proof.\n    autorewrite with exprD_rw in H.\n    simpl in H. forward; inv_all; subst.\n    eexists; repeat split.\n  Defined.\n\n  Lemma lambda_exprD_AppL : forall tus tvs tx ty f x fD,\n      lambda_exprD tus tvs (typ2 (F:=RFun) tx ty) f = Some fD ->\n      lambda_exprD tus tvs ty (App f x) =\n      match lambda_exprD tus tvs tx x with\n      | None => None\n      | Some xD => Some (AbsAppI.exprT_App fD xD)\n      end.\n  Proof.\n    simpl; intros.\n    rewrite lambda_exprD_App.\n    destruct (lambda_exprD tus tvs tx x) eqn:?.\n    { erewrite lambda_exprD_typeof_Some by eassumption.\n      rewrite H. rewrite Heqo. reflexivity. }\n    { destruct (typeof_expr tus tvs x) eqn:?; auto.\n      destruct (lambda_exprD tus tvs (typ2 t ty) f) eqn:?; auto.\n      assert (t = tx).\n      { destruct (ExprFacts.lambda_exprD_single_type H Heqo1).\n        clear H0. eapply typ2_inj in x0; eauto.\n        destruct x0. symmetry. apply H0. }\n      { subst. rewrite Heqo. reflexivity. } }\n  Qed.\n\n  Lemma lambda_exprD_AppR : forall tus tvs tx ty f x xD,\n      lambda_exprD tus tvs tx x = Some xD ->\n      lambda_exprD tus tvs ty (App f x) =\n      match lambda_exprD tus tvs (typ2 tx ty) f with\n      | None => None\n      | Some fD => Some (AbsAppI.exprT_App fD xD)\n      end.\n  Proof.\n    simpl; intros.\n    rewrite lambda_exprD_App.\n    erewrite lambda_exprD_typeof_Some by eassumption.\n    rewrite H.\n    reflexivity.\n  Qed.\n\n  Lemma lambda_exprD_App_both_cases : forall tus tvs tx ty f x fD xD,\n      lambda_exprD tus tvs (typ2 (F:=RFun) tx ty) f = Some fD ->\n      lambda_exprD tus tvs tx x = Some xD ->\n      lambda_exprD tus tvs ty (App f x) = Some (AbsAppI.exprT_App fD xD).\n  Proof.\n    intros. erewrite lambda_exprD_AppR by eassumption.\n    rewrite H. reflexivity.\n  Qed.\n\n  Lemma lambda_exprD_App\n    : forall tus tvs td tr f x fD xD,\n      lambda_exprD tus tvs (typ2 (F:=RFun) td tr) f = Some fD ->\n      lambda_exprD tus tvs td x = Some xD ->\n      lambda_exprD tus tvs tr (App f x) = Some (AbsAppI.exprT_App fD xD).\n  Proof using Typ2Ok_arr RSymOk_sym RTypeOk.\n    intros.\n    autorewrite with exprD_rw; simpl.\n    erewrite lambda_exprD_typeof_Some by eauto.\n    rewrite H. rewrite H0. reflexivity.\n  Qed.\n\n  Lemma lambda_exprD_Abs_prem\n    : forall tus tvs t t' x xD,\n      ExprDsimul.ExprDenote.lambda_exprD tus tvs t (Abs t' x) = Some xD ->\n      exists t'' (pf : typ2 t' t'' = t) bD,\n        ExprDsimul.ExprDenote.lambda_exprD tus (t' :: tvs) t'' x = Some bD /\\\n        xD = match pf with\n             | eq_refl => AbsAppI.exprT_Abs bD\n             end.\n  Proof using Typ2Ok_arr RSymOk_sym RTypeOk.\n    intros.\n    autorewrite with exprD_rw in H.\n    destruct (typ2_match_case t); forward_reason.\n    { rewrite H0 in H; clear H0.\n      red in x2; subst. simpl in *.\n      autorewrite_with_eq_rw_in H.\n      destruct (type_cast x0 t'); subst; try congruence.\n      red in r; subst.\n      forward. inv_all; subst.\n      eexists; exists eq_refl.\n      eexists; split; eauto. inversion H.\n      unfold AbsAppI.exprT_Abs.\n      autorewrite_with_eq_rw.\n      reflexivity. }\n    { rewrite H0 in H. congruence. }\n  Qed.\n\n\nEnd some_lemmas.\n\nHint Rewrite lambda_exprD_App_both_cases using eassumption : exprD_rw.\nHint Rewrite lambda_exprD_AppL using eassumption : exprD_rw.\nHint Rewrite lambda_exprD_AppR using eassumption : exprD_rw.\n\nLtac red_exprD :=\n  autorewrite with exprD_rw; simpl. (** TODO: this should be restricted **)\n\nLtac forward_exprD :=\n  repeat match goal with\n           | H : _ = _ , H' : _ = _ |- _ =>\n             let x := constr:(@lambda_exprD_typeof_eq _ _ _ _ _ _ _ _ _ _ _ _ _ _ H H') in\n             match type of x with\n               | ?X = ?X => fail 1\n               | _ => specialize x ; intro ; try inv_all ; try subst\n             end\n           | H : lambda_exprD _ _ ?T ?X = _ , H' : lambda_exprD _ _ ?T' ?X = _ |- _ =>\n             match T with\n               | T' => fail 1\n               | _ =>\n                 generalize (@lambda_exprD_deterministic _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H H');\n                   let X := fresh in intro X; red in X;\n                   try inv_all; try subst\n             end\n         end.\n\nLtac arrow_case t :=\n  let H := fresh in\n  destruct (@typ2_match_case _ _ _ _ _ t) as [ [ ? [ ? [ ? H ] ] ] | H ];\n    ( try rewrite H in * ).\n\nLtac arrow_case_any :=\n  match goal with\n    | H : context [ @typ2_match _ _ _ _ _ ?X ] |- _ =>\n      arrow_case X\n  end.\n\nSection lemmas.\n  Variable typ : Set.\n  Variable RType_typ : RType typ.\n  Variable RTypeOk : RTypeOk.\n\n  Theorem Relim_const\n  : forall T a b (pf : Rty a b),\n      Relim (fun _ => T) pf = fun x => x.\n  Proof.\n    clear. destruct pf. reflexivity.\n  Qed.\n\n  Lemma type_cast_sym_Some\n  : forall a b pf,\n      type_cast a b = Some pf ->\n      type_cast b a = Some (Rsym pf).\n  Proof.\n    intros. destruct pf.\n    rewrite type_cast_refl; eauto.\n  Qed.\n\n  Lemma type_cast_sym_None\n  : forall a b,\n      type_cast a b = None ->\n      type_cast b a = None.\n  Proof.\n    intros.\n    destruct (type_cast b a); auto.\n    destruct r.\n    rewrite type_cast_refl in H; eauto.\n  Qed.\nEnd lemmas.\n\n(** TODO: This needs to move *)\nSection thing.\n  Variable typ : Set.\n  Variable RType_typ : RType typ.\n  Variable RTypeOk_typ : RTypeOk.\n  Variable F : Type@{Urefl} -> Type@{Urefl} -> Type@{Urefl}.\n  Variable Typ2_F : Typ2 _ F.\n  Variable Typ2Ok_F : Typ2Ok Typ2_F.\n\n\n  Definition typ2_Rty (a b c d : typ) (pf : Rty a b) (pf' : Rty c d)\n  : Rty (typ2 a c) (typ2 b d) :=\n    match pf , pf' with\n    | eq_refl , eq_refl => eq_refl\n    end.\n\n  Lemma decompose_Rty_typ2 : forall {a b c d : typ} (pf : Rty (typ2  a b) (typ2 c d)),\n      exists pf' pf'', pf = typ2_Rty pf' pf''.\n  Proof.\n    intros. generalize pf.\n    intros. inv_all.\n    subst. exists eq_refl. exists eq_refl. simpl.\n    apply UIP_refl.\n  Defined.\n\n  Lemma symAs_D :\n    forall (Typ2_Fun : Typ2 RType_typ RFun)\n      (func : Set) (RSym_func : RSym func),\n      forall (f : func) (t : typ) (v : typD t),\n        symAs f t = Some v ->\n        match typeof_sym f as X return match X with\n                                       | None => unit\n                                       | Some t => typD t\n                                       end -> Prop with\n        | None => fun _ => False\n        | Some t' => fun d =>\n                      exists pf : Rty t' t,\n                        Rcast_val pf d = v\n        end (symD f).\n  Proof.\n    clear. intros.\n    unfold symAs in H.\n    generalize dependent (symD f).\n    destruct (typeof_sym f).\n    { intros. destruct (type_cast t t0).\n      { exists (Rsym r). inv_all. unfold Rcast_val, Rcast, Relim in *.\n        unfold Rsym. rewrite eq_sym_involutive. assumption. }\n      { exfalso. clear - H. discriminate H. } }\n    { clear. intros. discriminate H. }\n  Defined.\n\n  Lemma Rcast_val_eq_refl : forall a pf x, @Rcast_val _ _ a a pf x = x.\n  Proof.\n    intros. rewrite (UIP_refl pf). reflexivity.\n  Defined.\n\n\n\nEnd thing.\n\n\nLtac lambda_exprD_fwd :=\n  repeat match goal with\n         | H : symAs _ _ = Some _ |- _ =>\n           (eapply symAs_D in H; eauto); [] ; simpl in H; destruct H\n         | pf : Rty _ _ |- _ =>\n           destruct (decompose_Rty_typ2 _ _ pf) as [ ? [ ? ? ] ] ; subst pf\n         | pf : lambda_exprD _ _ _ (Abs _ _) = Some _ |- _ =>\n           apply lambda_exprD_Abs_prem in pf ; eauto ; [ ] ; destruct pf as [ ? [ ? [ ? [ ? ? ] ] ] ]\n         | pf : Rty _ ?X |- _ => is_var X ; destruct pf\n         | pf : Rty ?X _ |- _ => is_var X ; red in pf ; subst X\n         | |- _ => progress inv_all ; subst\n         end.\n\nRequire Import MirrorCore.ExprI.\nSection exprT.\n  Context {typ : Set}.\n  Context {RType_typ : RType typ}.\n  (** TODO(gmalecha): These should go somewhere else since they are generic\n   ** to exprT.\n   **)\n  Lemma exprT_Inj_castR\n  : forall (tus tvs : tenv typ) (T : Type@{Urefl}) (Ty0 : Typ0 _ T) (v : T),\n    @exprT_Inj _ _ _ _ (typD _) (castR (@id Type@{Urefl}) T v) = castR (exprT tus tvs) _ (exprT_Inj _ _ v).\n  Proof.\n    clear. unfold exprT_Inj, castR. intros.\n    generalize dependent (typ0_cast (F:=T)).\n    intro e. generalize dependent (typD (typ0 (F:=T))).\n    intros; subst. reflexivity.\n  Defined.\n\n  Theorem exprT_App_castRl\n    : forall (tus tvs : tenv typ) (T U : Type@{Urefl})\n        (Ty2 : Typ2 _ RFun) (Ty0T : Typ0 _ T) (Ty0U : Typ0 _ U)\n        e1 e2,\n      AbsAppI.exprT_App (castR (exprT tus tvs) (RFun T U) e1) e2 =\n      castR (exprT tus tvs) U (Applicative.ap e1 (castD (exprT tus tvs) T e2)).\n  Proof.\n    unfold AbsAppI.exprT_App, castR, castD. simpl; intros.\n    generalize dependent (typ0_cast (F:=U)).\n    generalize dependent (typ0_cast (F:=T)).\n    generalize dependent (typ2_cast (typ0 (F:=T)) (typ0 (F:=U))).\n    clear.\n    intros.\n    generalize dependent (typD (typ0 (F:=T))).\n    generalize dependent (typD (typ0 (F:=U))).\n    intros; subst. simpl.\n    generalize dependent (typD (typ2 (typ0 (F:=T)) (typ0 (F:=U)))).\n    intros; subst. reflexivity.\n  Defined.\nEnd exprT.\n\nLtac simpl_exprT :=\n  repeat match goal with\n         | |- context [ (fun a b => ?F a b) ] =>\n           change (fun a b => F a b) with F\n         | |- _ => rewrite castDR\n         | |- _ => rewrite castRD\n         | |- context [ exprT_Inj ?tus ?tvs (@castR _ _ _ _ ?T ?v) ] =>\n           let H := fresh in\n           pose proof (@exprT_Inj_castR _ _ tus tvs _ T v) as H ; change_rewrite H ; clear H\n         | |- context [ @AbsAppI.exprT_App _ _ _ ?tus ?tvs ?d ?c (@castR _ _ _ ?T _ ?f) ?x] =>\n           let H := fresh in\n           pose proof (@exprT_App_castRl _ _ tus tvs _ _ _ _ _ f x) as H ; change_rewrite H ; clear H\n         end.\n\n\n\n(* TODO(gmalecha): Remove this. It appears to be duplicated.\nSection ExprDInject.\n  Context {typ func : Set}.\n  Context {RType_typ : RType typ} {RTypeOk_typ : RTypeOk}.\n  Context {RSym_func : RSym func} {RSymOk_func : RSymOk RSym_func}.\n  Context {Typ2_tyArr : Typ2 _ RFun} {Typ2Ok_tyArr : Typ2Ok Typ2_tyArr}.\n\n  Let tyArr : typ -> typ -> typ := @typ2 _ _ _ Typ2_tyArr.\n\n  Global Instance Injective_lambda_exprD_App tus tvs (e1 e2 : expr typ func) (t : typ)\n         (v : exprT tus tvs (typD t)):\n    Injective (ExprDsimul.ExprDenote.lambda_exprD tus tvs t (App e1 e2) = Some v) := {\n      result := exists u v1 v2, ExprDsimul.ExprDenote.lambda_exprD tus tvs (tyArr u t) e1 = Some v1 /\\\n                                ExprDsimul.ExprDenote.lambda_exprD tus tvs u e2 = Some v2 /\\\n                                v = AbsAppI.exprT_App v1 v2;\n      injection := fun H => _\n    }.\n  Proof.\n    autorewrite with exprD_rw in H.\n    simpl in H. forward; inv_all; subst.\n    do 3 eexists; repeat split; eassumption.\n  Defined.\n\n  Global Instance Injective_lambda_exprD_Inj tus tvs (f : func) (t : typ) (v : exprT tus tvs (typD t)):\n    Injective (ExprDsimul.ExprDenote.lambda_exprD tus tvs t (Inj f) = Some v) := {\n      result := exists v', symAs f t = Some v' /\\ v = exprT_Inj _ _ v' ;\n      injection := fun H => _\n    }.\n  Proof.\n    autorewrite with exprD_rw in H.\n    simpl in H. forward; inv_all; subst.\n    eexists; repeat split.\n  Defined.\n\nEnd ExprDInject.\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/ExprTac.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.2552317758258073}}
{"text": "Require Import Utils.\nRequire Import Maps.\nRequire Import PropertyGraph.\nRequire Import Cypher.\nRequire Import BindingTable.\nRequire Import Semantics.\nRequire Import PatternE.\n\nImport PartialMap.Notations.\nImport PropertyGraph.\n\nModule FilterMode.\n  Inductive t : Type :=\n  | Vertices\n  | Edges\n  .\nEnd FilterMode.\n\nModule ExpandMode .\n  Inductive t : Type :=\n  | All\n  | Into\n  .\nEnd ExpandMode.\n\n(* r' is expanded from r by traversing one edge *)\nDefinition expansion_of' (g : PropertyGraph.t) (r' r : Rcd.t)\n                         (mode : ExpandMode.t)\n                         (v_from : vertex) (e : edge) (v_to : vertex)\n                         (n_from n_edge n_to : Name.t)\n                         (d : Pattern.direction) :=\n  << HIn_e : In e (edges g) >> /\\\n  << Hdir : Path.matches_direction g v_from v_to e d >> /\\\n  << Hval_from : r n_from = Some (Value.GVertex v_from) >> /\\\n  << Hval_edge : r n_edge = None >> /\\\n  << Hval' : r' = (n_to |-> Value.GVertex v_to; n_edge |-> Value.GEdge e; r) >> /\\\n  match mode with\n  | ExpandMode.All =>\n    << Hval_to : r n_to = None >>\n  | ExpandMode.Into =>\n    << Hval_to : r n_to = Some (Value.GVertex v_to) >>\n  end.\n\n(* r' is expanded from r by traversing one edge *)\nDefinition expansion_of (g : PropertyGraph.t) (r' r : Rcd.t)\n                        (mode : ExpandMode.t)\n                        (n_from n_edge n_to : Name.t)\n                        (d : Pattern.direction) :=\n  exists v_from e v_to,\n    expansion_of' g r' r mode v_from e v_to n_from n_edge n_to d.\n\nImport FilterMode.\nImport ExpandMode.\n\nModule ExecutionPlan.\n  Definition step0 := PropertyGraph.t -> option BindingTable.t.\n  Definition step1 := PropertyGraph.t -> BindingTable.t -> option BindingTable.t.\n\n  Module Type Spec.\n    (* scan_vertices (n : Name.t) : step0 *)\n    Parameter scan_vertices : Name.t -> step0.\n\n    (* filter_by_label (mode : FilterMode.t) (n : Name.t) (l : label) : step1 *)\n    Parameter filter_by_label : FilterMode.t -> Name.t -> label -> step1.\n\n    (* expand (mode : ExpandMode.t) (n_from n_edge n_to : Name.t) (d : Pattern.direction) : step1 *)\n    Parameter expand : ExpandMode.t -> Name.t -> Name.t -> Name.t -> Pattern.direction -> step1.\n\n    (* return_all : step1 *)\n    Parameter return_all : step1.\n\n    (* traverse (slice : PatternSlice.t) (n_from : Name.t) : step1 *)\n    Parameter traverse : PatternSlice.t -> Name.t -> step1.\n\n    Section axioms.\n      Variable graph : PropertyGraph.t.\n      Variable table : BindingTable.t.\n      Variable table' : BindingTable.t.\n      Variable ty : BindingTable.T.\n\n      (** If the inputs are well-formed then the operation will return the result *)\n\n      Axiom scan_vertices_wf : forall n,\n        PropertyGraph.wf graph ->\n          exists table', scan_vertices n graph = Some table'.\n\n      Axiom filter_vertices_by_label_wf : forall n l,\n        PropertyGraph.wf graph -> BindingTable.of_type table ty ->\n          ty n = Some Value.GVertexT ->\n            exists table', filter_by_label Vertices n l graph table = Some table'.\n\n      Axiom filter_edges_by_label_wf : forall n l,\n        PropertyGraph.wf graph -> BindingTable.of_type table ty ->\n          ty n = Some Value.GEdgeT ->\n            exists table', filter_by_label Edges n l graph table = Some table'.\n\n      Axiom expand_all_wf : forall n_from n_edge n_to d,\n        PropertyGraph.wf graph -> BindingTable.of_type table ty ->\n          ty n_from = Some Value.GVertexT -> ty n_edge = None -> ty n_to = None ->\n              exists table', expand All n_from n_edge n_to d graph table = Some table'.\n      \n      Axiom expand_into_wf : forall n_from n_edge n_to d,\n        PropertyGraph.wf graph -> BindingTable.of_type table ty ->\n          ty n_from = Some Value.GVertexT -> ty n_edge = None -> ty n_to = Some Value.GVertexT ->\n            exists table', expand Into n_from n_edge n_to d graph table = Some table'.\n\n      Axiom return_all_wf :\n        exists table', return_all graph table = Some table'.\n\n      Axiom traverse_wf : forall slice n_from,\n        PropertyGraph.wf graph -> BindingTable.of_type table ty ->\n          PatternSlice.wf ty slice -> ty n_from = Some Value.GVertexT ->\n            exists table', traverse slice n_from graph table = Some table'.\n\n      (** If the operation returned some table then the type of the table is correct *)\n\n      Axiom scan_vertices_type : forall n,\n        scan_vertices n graph = Some table' ->\n          BindingTable.of_type table' (n |-> Value.GVertexT).\n      \n      Axiom filter_by_label_type : forall mode n l,\n        filter_by_label mode n l graph table = Some table' ->\n          BindingTable.of_type table ty ->\n            BindingTable.of_type table' ty.\n\n      Axiom expand_type : forall mode n_from n_edge n_to d,\n        expand mode n_from n_edge n_to d graph table = Some table' ->\n          BindingTable.of_type table ty ->\n            BindingTable.of_type table'\n              (n_to |-> Value.GVertexT; n_edge |-> Value.GEdgeT; ty).\n\n      Axiom return_all_type :\n        return_all graph table = Some table' ->\n          BindingTable.of_type table ty ->\n            BindingTable.of_type table' (Rcd.explicit_projT ty).\n\n      Axiom traverse_type : forall slice n_from,\n        traverse slice n_from graph table = Some table' ->\n          BindingTable.of_type table ty ->\n            BindingTable.of_type table' (PatternSlice.type_of ty slice).\n\n      (** scan_vertices specification *)\n\n      Axiom scan_vertices_spec : forall n v,\n        scan_vertices n graph = Some table' ->\n          In v (vertices graph) ->\n            In (n |-> Value.GVertex v) table'.\n\n      Axiom scan_vertices_spec' : forall n r',\n        scan_vertices n graph = Some table' ->\n          In r' table' -> exists v,\n            r' = (n |-> Value.GVertex v) /\\ In v (vertices graph).\n\n      (** filter_by_label specification *)\n\n      Axiom filter_vertices_by_label_spec : forall n l v r,\n        filter_by_label Vertices n l graph table = Some table' ->\n          r n = Some (Value.GVertex v) -> In l (vlabels graph v) ->\n            In r table -> In r table'.\n      \n      Axiom filter_vertices_by_label_spec' : forall n l r',\n        filter_by_label Vertices n l graph table = Some table' ->\n           In r' table' -> In r' table /\\\n            exists v, r' n = Some (Value.GVertex v) /\\ In l (vlabels graph v).\n\n      Axiom filter_edges_by_label_spec : forall n l e r,\n        filter_by_label Edges n l graph table = Some table' ->\n          r n = Some (Value.GEdge e) -> elabel graph e = l ->\n            In r table -> In r table'.\n\n      Axiom filter_edges_by_label_spec' : forall n l r',\n        filter_by_label Edges n l graph table = Some table' ->\n          In r' table' -> In r' table /\\\n            exists e, r' n = Some (Value.GEdge e) /\\ elabel graph e = l.\n\n      (** expand specification *)\n\n      Axiom expand_spec : forall r r' mode n_from n_edge n_to d,\n        expand mode n_from n_edge n_to d graph table = Some table' ->\n          expansion_of graph r' r mode n_from n_edge n_to d ->\n            In r table -> In r' table'.\n\n      Axiom expand_spec' : forall r' mode n_from n_edge n_to d,\n        expand mode n_from n_edge n_to d graph table = Some table' -> In r' table' ->\n            exists r, In r table /\\ expansion_of graph r' r mode n_from n_edge n_to d.\n\n      (** return_all specification *)\n\n      Axiom return_all_spec : forall r,\n        return_all graph table = Some table' ->\n          In r table -> In (Rcd.explicit_proj r) table'.\n\n      Axiom return_all_spec' : forall r',\n        return_all graph table = Some table' ->\n          In r' table' -> exists r, In r table /\\ r' = Rcd.explicit_proj r.\n\n      (** traverse specification *)\n\n      Axiom traverse_spec : forall path r r' slice n_from,\n        traverse slice n_from graph table = Some table' ->\n          PathSlice.matches graph r n_from r' path slice ->\n            In r table -> In r' table'.\n\n      Axiom traverse_spec' : forall r' slice n_from,\n        traverse slice n_from graph table = Some table' ->\n          In r' table' -> exists r path, In r table /\\\n            PathSlice.matches graph r n_from r' path slice.\n    End axioms.\n  End Spec.\n\n  Inductive t :=\n  | ScanVertices (n : Name.t)\n  | FilterByLabel (mode : FilterMode.t) (n : Name.t) (l : label) (plan : t) \n  | Expand (mode : ExpandMode.t) (n_from n_edge n_to : Name.t) (d : Pattern.direction) (plan : t)\n  | ReturnAll (plan : t)\n  | Traverse (slice : PatternSlice.t) (n_from : Name.t) (plan : t)\n  .\n\n  Fixpoint type_of (plan : t) : BindingTable.T :=\n    match plan with\n    | ScanVertices n => n |-> Value.GVertexT\n    | FilterByLabel mode n l plan => type_of plan\n    | Expand mode n_from n_edge n_to d plan => n_to |-> Value.GVertexT; n_edge |-> Value.GEdgeT; type_of plan\n    | ReturnAll plan => Rcd.explicit_projT (type_of plan)\n    | Traverse slice n_from plan => PatternSlice.type_of (type_of plan) slice\n    end.\n\n  Lemma type_of_types plan k :\n    type_of plan k = Some Value.GVertexT \\/\n    type_of plan k = Some Value.GEdgeT \\/\n    type_of plan k = None.\n  Proof using.\n    induction plan; simpl in *.\n    all: unfold Rcd.explicit_projT.\n    all: autounfold with unfold_pat.\n    all: desf.\n    all: auto using PatternSlice.type_of__types.\n  Qed.\n\n  Fixpoint wf (plan : t) :=\n    match plan with\n    | ScanVertices n => True\n    | FilterByLabel Vertices n l plan =>\n      << Htype : type_of plan n = Some Value.GVertexT >> /\\\n      << Hwf : wf plan >>\n    | FilterByLabel Edges n l plan =>\n      << Htype : type_of plan n = Some Value.GEdgeT >> /\\\n      << Hwf : wf plan >>\n    | Expand All n_from n_edge n_to d plan =>\n      << Htype_from : type_of plan n_from = Some Value.GVertexT >> /\\\n      << Htype_edge : type_of plan n_edge = None >> /\\\n      << Htype_to : type_of plan n_to = None >> /\\\n      << Hneq_from : n_from =/= n_edge >> /\\\n      << Hneq_to : n_to =/= n_edge >> /\\\n      << Hwf : wf plan >>\n    | Expand Into n_from n_edge n_to d plan =>\n      << Htype_from : type_of plan n_from = Some Value.GVertexT >> /\\\n      << Htype_edge : type_of plan n_edge = None >> /\\\n      << Htype_to : type_of plan n_to = Some Value.GVertexT >> /\\\n      << Hneq_from : n_from =/= n_edge >> /\\\n      << Hneq_to : n_to =/= n_edge >> /\\\n      << Hwf : wf plan >>\n    | ReturnAll plan =>\n      << Hwf : wf plan >>\n    | Traverse slice n_from plan =>\n      << Htype : type_of plan n_from = Some Value.GVertexT >> /\\\n      << Hwf_slice : PatternSlice.wf (type_of plan) slice >> /\\\n      << Hwf : wf plan >>\n    end.\n\n  Module EvalPlan (S : Spec).\n    Import S.\n\n    #[local]\n    Hint Resolve scan_vertices_type filter_by_label_type\n                expand_type return_all_type traverse_type : type_axioms.\n\n    #[local]\n    Hint Resolve scan_vertices_wf filter_vertices_by_label_wf filter_edges_by_label_wf\n                 expand_all_wf expand_into_wf return_all_wf traverse_wf : wf_axioms.\n\n    Section eval.\n      Variable graph : PropertyGraph.t.\n      Fixpoint eval (plan : ExecutionPlan.t) :=\n        match plan with\n        | ScanVertices n => scan_vertices n graph\n        | FilterByLabel mode n l plan =>\n          eval plan >>= filter_by_label mode n l graph\n        | Expand mode n_from n_edge n_to d plan => \n          eval plan >>= expand mode n_from n_edge n_to d graph\n        | ReturnAll plan => eval plan >>= return_all graph\n        | Traverse slice n_from plan =>\n          eval plan >>= traverse slice n_from graph\n        end.\n    End eval.\n\n    Theorem eval_type_of plan graph table'\n                         (Heval : eval graph plan = Some table') :\n        BindingTable.of_type table' (type_of plan).\n    Proof using.\n      generalize dependent table'.\n      induction plan; intros; simpl in *.\n      { apply scan_vertices_type with graph. assumption. }\n      all: destruct (eval graph plan); try discriminate.\n\n      2: destruct mode.\n      all: eauto with type_axioms.\n    Qed.\n\n    Theorem eval_wf plan graph (Hwf : wf plan) (Hwf' : PropertyGraph.wf graph) :\n        exists table', eval graph plan = Some table'.\n    Proof with (try eassumption).\n      induction plan. all: simpl in *; desf; desf.\n      { apply scan_vertices_wf... }\n      all: destruct IHplan as [table IH]...\n      all: rewrite IH; simpl.\n      all: eauto using eval_type_of with wf_axioms.\n    Qed.\n  End EvalPlan.\nEnd ExecutionPlan.\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/ExecutionPlan.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.25523176910663636}}
{"text": "Require Import\n        Coq.Vectors.Vector\n        Coq.ZArith.ZArith\n        Coq.Strings.Ascii\n        Coq.Strings.String\n        Coq.Bool.Bool\n        Coq.Vectors.Vector\n        Coq.Lists.List.\n\nRequire Import\n        Fiat.Common.BoundedLookup\n        Fiat.Common.SumType\n        Fiat.Common.EnumType\n        Fiat.Narcissus.Formats.DomainNameOpt\n        Fiat.QueryStructure.Specification.Representation.Notations\n        Fiat.QueryStructure.Specification.Representation.Heading\n        Fiat.QueryStructure.Specification.Representation.Tuple.\n\nRequire Import\n        Bedrock.Word\n        Bedrock.Memory.\n\nImport Lists.List.ListNotations.\nImport Vectors.Vector.VectorNotations.\n\nLocal Open Scope string_scope.\nLocal Open Scope Tuple_scope.\nLocal Open Scope vector_scope.\n\nRequire Export Fiat.Narcissus.Examples.DNS.RRecordTypes.\n\nSection QTypes.\n\n  (* DNS packet Query Types are a superset of RR Types. *)\n  Definition QTypes :=\n    [\"TKEY\"; (* Transaction Key \t[RFC2930] *)\n     \"TSIG\"; (* Transaction Signature \t[RFC2845] *)\n     \"IXFR\"; (* incremental transfer \t[RFC1995] *)\n     \"AXFR\"; (* transfer of an entire zone \t[RFC1035][RFC5936] *)\n     \"MAILB\"; (* mailbox-related RRs (MB, MG or MR) \t[RFC1035] *)\n     \"MAILA\"; (* mail agent RRs (OBSOLETE - see MX) \t[RFC1035] *)\n     \"STAR\" (*A request for all records the server/cache has available \t[RFC1035][RFC6895] *)\n    ].\n\n  Definition QType_Ws : t (word 16) 17 :=\n    Eval simpl in RRecordType_Ws ++ Vector.map (natToWord 16)\n                             [249; (*\"TKEY\" *)\n                                250; (*\"TSIG\" *)\n                                251; (*\"IXFR\" *)\n                                252; (*\"AXFR\" *)\n                                253;(*\"MAILB\" *)\n                                254;(*\"MAILA\" *)\n                                255 (* \"STAR\" *)].\n\n  Definition QType := EnumType ((OurRRecordTypes(* ++ ExtraRRecordTypes) *) ++ QTypes)).\n\n  Definition QType_inj (rr : RRecordType) : QType :=\n    Fin.L _ rr.\n\n  Definition beq_QType (a b : QType) : bool :=\n    fin_beq a b.\n\n  Definition QType_dec (a b : QType) :=\n    fin_eq_dec a b.\n\n  Lemma beq_QType_sym :\n    forall rrT rrT', beq_QType rrT rrT' = beq_QType rrT' rrT.\n  Proof.\n    intros; eapply fin_beq_sym.\n  Qed.\n\n  Coercion QType_inj : RRecordType >-> QType.\n\n  Definition QType_match (rtype : RRecordType) (qtype : QType) :=\n    qtype = ```\"STAR\" \\/ qtype = rtype.\n\nEnd QTypes.\n\nSection RRecordClass.\n\n  Definition RRecordClasses :=\n    [ \"Internet\"; (* (IN) \t[RFC1035] *)\n        \"Chaos\"; (* (CH) \t[D. Moon, \"Chaosnet\", A.I. Memo 628, Massachusetts Institute of Technology Artificial Intelligence Laboratory, June 1981.] *)\n        \"Hesiod\" (* (HS) \t[Dyer, S., and F. Hsu, \"Hesiod\", Project Athena Technical Plan - Name Service, April 1987.] *)\n    ].\n\n  Definition RRecordClass_Ws : t (word 16) 3 :=\n    Eval simpl in Vector.map (natToWord 16)\n                             [1; (* \"IN\" *)\n                                3; (* \"CH\" *)\n                                4 (* \"Hesiod\" *)].\n\n  Definition RRecordClass := EnumType RRecordClasses.\n\n  Definition beq_RRecordClass (a b : RRecordClass) : bool\n    := fin_beq a b.\n\n  Definition RRecordClass_dec (a b : RRecordClass) :=\n    fin_eq_dec a b.\n\n  (* DNS Packet Question Classes *)\n  Definition QClass := EnumType (RRecordClasses ++ [\"Any\"]).\n\n  Definition QClass_Ws : t (word 16) 4 :=\n    Eval simpl in Vector.append\n                    RRecordClass_Ws\n                    [natToWord 16 255 (* \"Any\"*)].\n\n  Definition QClass_inj (qclass : RRecordClass) : QClass :=\n    Fin.L _ qclass.\n\n  Definition beq_QClass (a b : QClass) : bool\n    := fin_beq a b.\n\n  Definition QClass_dec (a b : QClass) :=\n    fin_eq_dec a b.\n\nEnd RRecordClass.\n\nSection ResponseCode.\n\n    Definition ResponseCodes :=\n    [\"NoError\";  (* No Error [RFC1035] *)\n       \"FormErr\";  (* Format Error [RFC1035] *)\n       \"ServFail\"; (* Server Failure [RFC1035] *)\n       \"NXDomain\"; (* Non-Existent  Domain \t[RFC1035] *)\n       \"NotImp\";   (* Not Implemented [RFC1035] *)\n       \"Refused\";  (* Query Refused [RFC1035] *)\n       \"YXDomain\"; (* Name Exists when it should not [RFC2136][RFC6672] *)\n       \"YXRRSet\";  (* RR Set Exists when it should not \t[RFC2136] *)\n       \"NXRRSet\";  (* RR Set that should exist does not \t[RFC2136] *)\n       \"NotAuth\";  (* Server Not Authoritative for zone \t[RFC2136] *)\n                   (* and Not Authorized [RFC2845] *)\n       \"NotZone\" \t (* Name not  contained in zone \t[RFC2136] *)\n    ].\n\n  Definition RCODE_Ws : t (word 4) 11 :=\n    Eval simpl in Vector.map (natToWord 4)\n    [0;  (* No Error [RFC1035] *)\n     1;  (* Format Error [RFC1035] *)\n     2; (* Server Failure [RFC1035] *)\n     3; (* Non-Existent  Domain \t[RFC1035] *)\n     4;   (* Not Implemented [RFC1035] *)\n     5;  (* Query Refused [RFC1035] *)\n     6; (* Name Exists when it should not [RFC2136][RFC6672] *)\n     7;  (* RR Set Exists when it should not \t[RFC2136] *)\n     8;  (* RR Set that should exist does not \t[RFC2136] *)\n     9;  (* Server Not Authoritative for zone \t[RFC2136] *)\n         (* and Not Authorized [RFC2845] *)\n     10 \t (* Name not  contained in zone \t[RFC2136] *)\n    ].\n\n  Definition ResponseCode := EnumType ResponseCodes.\n\n  Definition beq_ResponseCode (a b : ResponseCode) : bool\n    := fin_beq a b.\n\n  Definition ResponseCode_dec (a b : ResponseCode) :=\n    fin_eq_dec a b.\nEnd ResponseCode.\n\nSection OpCode.\n\n  Definition OpCodes :=\n    [\"Query\";    (* RFC1035] *)\n     \"IQuery\"; (* Inverse Query  OBSOLETE) [RFC3425] *)\n     \"Status\"; (* [RFC1035] *)\n     \"Notify\"  (* [RFC1996] [RFC2136] *)\n    ].\n\n  Definition OpCode := EnumType OpCodes.\n\n  Definition Opcode_Ws : t (word 4) 4 :=\n    Eval simpl in Vector.map (natToWord 4)\n                             [0;    (* RFC1035] *)\n                              1; (* Inverse Query  OBSOLETE) [RFC3425] *)\n                              2; (* [RFC1035] *)\n                              4  (* [RFC1996] [RFC2136] *)].\n\n  Definition beq_OpCode (a b : OpCode) : bool\n    := fin_beq a b.\n\n  Definition OpCode_dec (a b : OpCode) :=\n    fin_eq_dec a b.\n\nEnd OpCode.\n\nSection Packet.\n\n  (* The question section of a DNS packet. *)\n  Definition question :=\n    @Tuple <\n    \"qname\" :: DomainName,\n    \"qtype\" :: QType,\n    \"qclass\" :: QClass >%Heading.\n  (* [\"google\", \"com\"] *)\n\n  (* DNS Resource Records. *)\n  Definition sRRecords := \"ResourceRecords\".\n  Definition sNAME := \"Name\".\n  Definition sTTL := \"TTL\".\n  Definition sCLASS := \"Class\".\n  Definition sTYPE := \"Type\".\n  Definition sRDATA := \"rdata\".\n  Definition sRLENGTH := \"rlength\".\n\n  Definition resourceRecordHeading :=\n    < sNAME :: DomainName,\n      sTTL :: timeT,\n      sCLASS :: RRecordClass,\n      sRDATA :: RDataType>%Heading.\n\n  Definition resourceRecord := @Tuple resourceRecordHeading.\n\n  (* Variant headings for each RDataType *)\n  Definition VariantResourceRecordHeading RDATAT :=\n    < sNAME :: DomainName,\n      sTTL :: timeT,\n      sCLASS :: RRecordClass,\n      sRDATA :: RDATAT >%Heading.\n\n  Definition VariantResourceRecord RDATAT := @Tuple (VariantResourceRecordHeading RDATAT).\n\n  (* Aliases for the Common Record Types *)\n  Definition CNAME_Record :=\n    VariantResourceRecord ResourceRecordTypeTypes[@ OurCNAME].\n  Definition A_Record :=\n    VariantResourceRecord ResourceRecordTypeTypes[@ OurA ].\n  Definition NS_Record :=\n    VariantResourceRecord ResourceRecordTypeTypes[@ OurNS].\n  Definition MX_Record :=\n    VariantResourceRecord ResourceRecordTypeTypes[@ OurMX].\n  Definition SOA_Record :=\n    VariantResourceRecord ResourceRecordTypeTypes[@ OurSOA].\n\n  Definition RRecord2VariantResourceRecord\n             (rr : resourceRecord)\n    : VariantResourceRecord ResourceRecordTypeTypes[@(SumType_index ResourceRecordTypeTypes (rr!sRDATA))] :=\n    < sNAME :: rr!sNAME,\n      sTTL :: rr!sTTL,\n      sCLASS :: rr!sCLASS,\n      sRDATA :: SumType_proj _ (rr!sRDATA)>.\n\n  Definition VariantResourceRecord2RRecord\n             {idx}\n             (vrr : VariantResourceRecord ResourceRecordTypeTypes[@idx])\n    : resourceRecord :=\n    < sNAME :: vrr!sNAME,\n      sTTL :: vrr!sTTL,\n      sCLASS :: vrr!sCLASS,\n      sRDATA :: inj_SumType _ idx (vrr!sRDATA)>.\n\n  Definition CNAME_Record2RRecord\n             (vrr : CNAME_Record)\n    : resourceRecord := VariantResourceRecord2RRecord vrr.\n  Definition A_Record2RRecord\n             (vrr : A_Record)\n    : resourceRecord := VariantResourceRecord2RRecord vrr.\n  Definition NS_Record2RRecord\n             (vrr : NS_Record)\n    : resourceRecord := VariantResourceRecord2RRecord vrr.\n  Definition MX_Record2RRecord\n             (vrr : MX_Record)\n    : resourceRecord := VariantResourceRecord2RRecord vrr.\n  Definition SOA_Record2RRecord\n             (vrr : SOA_Record)\n    : resourceRecord := VariantResourceRecord2RRecord vrr.\n\n  (* Binary Format of DNS Header:\n                              1  1  1  1  1  1\n0  1  2  3  4  5  6  7  8  9  0  1  2  3  4  5\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n|                      ID                       |\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n|QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n|                    QDCOUNT                    |\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n|                    ANCOUNT                    |\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n|                    NSCOUNT                    |\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n|                    ARCOUNT                    |\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n   *)\n\n  (* DNS Packet Layout:\n+---------------------+\n|        Header       |\n+---------------------+\n|       Question      |\n+---------------------+\n|        Answer       |\n+---------------------+\n|      Authority      |\n+---------------------+\n|      Additional     |\n+---------------------+\n   *)\n\n(* Unique Request IDs *)\nDefinition ID : Type := word 16.\n\n  Definition packetHeading :=\n    < \"id\" :: ID, (* 16 bit Word. *)\n      \"QR\" :: bool, (* is packet a query (0), or a response (1) *)\n      \"Opcode\" :: OpCode, (* kind of query in packet *)\n      \"AA\" :: bool, (* is responding server authorative *)\n      \"TC\" :: bool, (* is packet truncated *)\n      \"RD\" :: bool, (* are recursive queries desired *)\n      \"RA\" :: bool, (* are recursive queries supported by responding server *)\n      \"RCODE\" :: ResponseCode, (* response code *)\n      \"question\" :: question, (* `list question` in case we can have multiple questions? *)\n      \"answers\" :: list resourceRecord,\n      \"authority\" :: list resourceRecord,\n      \"additional\" :: list resourceRecord >%Heading.\n\n  Definition packet := @Tuple packetHeading.\n\n  Definition buildempty\n             (is_authority : bool)\n             (rcode : BoundedIndex ResponseCodes)\n             (p : packet)\n    : packet :=\n    p ○ [ \"AA\" ::= is_authority; (* Update Authority field *)\n          \"QR\" ::= true; (* Set response flag to true *)\n          \"RCODE\" ::= ibound (indexb rcode);\n          \"answers\" ::= nil;\n          \"authority\"  ::= nil;\n          \"additional\" ::= nil ].\n\n  (* add a resource record to a packet's answers *)\n  Definition add_answer\n             (p : packet)\n             (t : resourceRecord)\n    : packet :=\n    p ○ [o !! \"answers\" / t :: o].\n\n  (* add a resource record authority to a packet's authorities\n   (ns = name server). *)\n  Definition add_ns\n             (p : packet)\n             (t : resourceRecord)\n    : packet :=\n    p ○ [o !! \"authority\" / t :: o].\n\n  (* combine with above? *)\n  Definition add_additional\n             (p : packet)\n             (t : resourceRecord)\n    : packet :=\n    p ○ [o !! \"additional\" / t :: o].\n\n  Definition updateRecords\n             (p : packet)\n             answers' authority' additional'\n    : packet :=\n    p ○ [\"answers\" ::= answers';\n           \"authority\" ::= authority';\n           \"additional\" ::= additional'].\n\n  Definition get_name (r : resourceRecord) := r!sNAME.\n  Definition name_length (r : resourceRecord) := String.length (get_name r).\n\n  Definition isQuestion (p : packet) :=\n    match p!\"answers\", p!\"authority\", p!\"additional\" with\n    | nil, nil, nil => true\n    | _, _, _ => false\n    end.\n\n  Definition is_empty {A} (l : list A) : bool :=\n    match l with\n    | nil => true\n    | _ => false\n    end.\n\n  Lemma is_empty_app {A} :\n    forall (l l' : list A),\n      is_empty (l ++ l') = andb (is_empty l) (is_empty l').\n  Proof.\n    induction l; simpl; eauto.\n  Qed.\n\n  Definition isAnswer (p : packet) := negb (is_empty (p!\"answers\")).\n\n  Definition isReferral (p : packet) :=\n    is_empty (p!\"answers\")\n             && (negb (is_empty (p!\"authority\")))\n             && (negb (is_empty (p!\"additional\"))).\n\n  Definition add_answers := List.fold_left add_answer.\n  Definition add_nses := List.fold_left add_ns.\n  Definition add_additionals := List.fold_left add_additional.\n\nEnd Packet.\n\nCoercion CNAME_Record2RRecord : CNAME_Record >-> resourceRecord.\nCoercion A_Record2RRecord : A_Record >-> resourceRecord.\nCoercion NS_Record2RRecord : NS_Record >-> resourceRecord.\nCoercion MX_Record2RRecord : MX_Record >-> resourceRecord.\nCoercion SOA_Record2RRecord : SOA_Record >-> resourceRecord.\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/DNSPacket.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.25523176910663636}}
{"text": "Set Bullet Behavior \"Strict Subproofs\".\nSet Implicit Arguments.\n\nRequire Export FcEtt.tactics.\nRequire Export FcEtt.imports.\nRequire Export FcEtt.ett_inf.\nRequire Export FcEtt.ett_ott.\nRequire Export FcEtt.ett_ind.\n\n\nRequire Export FcEtt.ext_context_fv.\n\nRequire Import FcEtt.ext_wf.\nImport ext_wf.\n\nRequire Import FcEtt.utils.\nRequire Import FcEtt.erase_syntax.\nRequire Export FcEtt.toplevel.\n\n\n(* ------------------------------------------ *)\n\n(* Paths *)\n\n(*\nLemma Path_tm_subst_tm_tm : forall T a x b, Path T a -> lc_tm b -> Path T (tm_subst_tm_tm b x a).\nProof. induction 1; try destruct rho; simpl; eauto with lngen.\nQed.\n\nLemma Path_co_subst_co_tm : forall T a x b, Path T a -> lc_co b -> Path T (co_subst_co_tm b x a).\nProof. induction 1; try destruct rho; simpl; eauto with lngen.\nQed.\n\nHint Resolve Path_tm_subst_tm_tm Path_co_subst_co_tm : lngen.\n\nLemma Path_unique : forall T1 T2 a, Path T1 a -> Path T2 a -> T1 = T2.\nProof.\n  induction 1; intros P; inversion P; auto.\nQed.\n\n(* DataTy *)\n\nLemma DataTy_tm_subst_tm_tm : forall b x A,\n    DataTy A a_Star -> lc_tm b -> DataTy (tm_subst_tm_tm b x A) a_Star.\nProof.\n  intros. dependent induction H; simpl; eauto.\n  - pick fresh y and apply DT_Pi.\n    eauto with lngen.\n    autorewrite with subst_open_var; eauto.\n  - pick fresh y and apply DT_CPi.\n    eauto with lngen.\n    autorewrite with subst_open_var; eauto.\nQed.\n\nLemma DataTy_co_subst_co_tm : forall b x A,\n    DataTy A a_Star -> lc_co b -> DataTy (co_subst_co_tm b x A) a_Star.\nProof.\n  intros. dependent induction H; simpl; eauto.\n  - pick fresh y and apply DT_Pi.\n    eauto with lngen.\n    autorewrite with subst_open_var; eauto.\n  - pick fresh y and apply DT_CPi.\n    eauto with lngen.\n    autorewrite with subst_open_var; eauto.\nQed.\n\nHint Resolve DataTy_tm_subst_tm_tm DataTy_co_subst_co_tm : lngen.\n*)\n(* ------------------------------------------- *)\n(*\nDefinition decide_Path : forall a, lc_tm a -> (exists T, Path T a) \\/ (forall T, not (Path T a)).\nProof.\n  induction a; intro lc.\n  all: try solve [left; eauto].\n  all: try solve [right; move => T h1; inversion h1].\n  - lc_inversion c. destruct IHa1 as [[T h0]|n].\n    auto.\n    left; eauto.\n    right. move => T h1. inversion h1.\n    subst. unfold not in n. eauto.\n  - lc_inversion c. destruct IHa as [[T h0]|n].\n    auto.\n    left; eauto.\n    right. intros T h; inversion h; subst; unfold not in n; eauto.\n  - lc_inversion c. destruct IHa as [[T h0]|n].\n    auto.\n    left. exists T. auto.\n    right. intros T h; inversion h; subst; unfold not in n; eauto.\nQed.\n*)\n(* ------------------------------------------- *)\n\n(* Values and CoercedValues *)\n\nLemma tm_subst_tm_tm_Value_mutual :\n  (forall v,  CoercedValue v -> forall b x,  lc_tm b -> CoercedValue (tm_subst_tm_tm b x v)) /\\\n  (forall v, Value v -> forall b x,  lc_tm b -> Value (tm_subst_tm_tm b x v)).\nProof.\n  apply CoercedValue_Value_mutual; simpl.\n  all: try solve [inversion 1 | econstructor; eauto]; eauto.\n  all: try solve [intros;\n                  eauto using tm_subst_tm_tm_lc_tm,\n                  tm_subst_tm_constraint_lc_constraint,\n                  tm_subst_tm_co_lc_co].\n  all: try solve [intros;\n    constructor; eauto using tm_subst_tm_tm_lc_tm,  tm_subst_tm_constraint_lc_constraint;\n    match goal with [H: lc_tm (?a1 ?a2), K : lc_tm ?b |- _ ] =>\n                    move: (tm_subst_tm_tm_lc_tm _ _ x H K) => h0; auto end].\n\n  - intros L a v H b x H0.\n    econstructor; eauto.\n    instantiate (1 := L \\u singleton x) => x0 h0.\n    rewrite tm_subst_tm_tm_open_tm_wrt_tm_var; auto.\n  - intros L A a l c H b x H0.\n    econstructor; eauto.\n    apply tm_subst_tm_tm_lc_tm; auto.\n    instantiate (1 := L \\u singleton x) => x0 h0.\n    rewrite tm_subst_tm_tm_open_tm_wrt_tm_var; auto.\nQed.\n\nLemma Value_tm_subst_tm_tm :\n  (forall v b x, Value v -> lc_tm b -> Value (tm_subst_tm_tm b x v)).\nProof.\n  intros v b x H H0.\n  apply tm_subst_tm_tm_Value_mutual; auto.\nQed.\n\nLemma CoercedValue_tm_subst_tm_tm :\n  (forall v b x, CoercedValue v -> lc_tm b -> CoercedValue (tm_subst_tm_tm b x v)).\nProof.\n  intros v b x H H0.\n  destruct (tm_subst_tm_tm_Value_mutual); auto.\nQed.\n\n(* ------------------------------------------------- *)\n\nLemma Value_UAbsIrrel_exists : ∀ x (a : tm),\n    x `notin` fv_tm a\n    → (Value (open_tm_wrt_tm a (a_Var_f x)))\n    → Value (a_UAbs Irrel a).\nProof.\n  intros.\n  eapply (Value_UAbsIrrel ({{x}})); eauto.\n  intros.\n  rewrite (tm_subst_tm_tm_intro x); eauto.\n  eapply Value_tm_subst_tm_tm; auto.\nQed.\n\nLemma Value_AbsIrrel_exists : ∀ x (A a : tm),\n    x `notin` fv_tm a\n    -> lc_tm A\n    → (CoercedValue (open_tm_wrt_tm a (a_Var_f x)))\n    → Value (a_Abs Irrel A a).\nProof.\n  intros.\n  eapply (Value_AbsIrrel ({{x}})); eauto.\n  intros.\n  rewrite (tm_subst_tm_tm_intro x); eauto.\n  eapply CoercedValue_tm_subst_tm_tm; auto.\nQed.\n\n(* ----- *)\n\nLemma co_subst_co_tm_Value_mutual :\n  (forall v,  CoercedValue v -> forall b x,  lc_co b -> CoercedValue (co_subst_co_tm b x v)) /\\\n  (forall v, Value v -> forall b x,  lc_co b -> Value (co_subst_co_tm b x v)).\nProof.\n  apply CoercedValue_Value_mutual; simpl.\n  all: try solve [inversion 1 | econstructor; eauto]; eauto.\n  all: try solve [intros;\n                  eauto using co_subst_co_tm_lc_tm,\n                  co_subst_co_constraint_lc_constraint,\n                  co_subst_co_co_lc_co].\n  all: try solve [intros;\n    constructor; eauto using co_subst_co_tm_lc_tm,\n                              co_subst_co_constraint_lc_constraint;\n    match goal with [H: lc_tm (?a1 ?a2), K : lc_co ?b |- _ ] =>\n                    move: (co_subst_co_tm_lc_tm _ _ x H K) => h0; auto end].\n  - intros.\n    pick fresh y.\n    eapply Value_UAbsIrrel_exists with (x:=y).\n    eapply fv_tm_tm_tm_co_subst_co_tm_notin; eauto.\n    move: (H y ltac:(eauto) b x H0) => h0.\n    rewrite co_subst_co_tm_open_tm_wrt_tm in h0.\n    simpl in h0. auto. auto.\n  - intros.\n    pick fresh y.\n    eapply Value_AbsIrrel_exists with (x:=y).\n    eapply fv_tm_tm_tm_co_subst_co_tm_notin; eauto.\n    eapply co_subst_co_tm_lc_tm; eauto.\n    move: (H y ltac:(eauto) b x H0) => h0.\n    rewrite co_subst_co_tm_open_tm_wrt_tm in h0; auto.\nQed.\n\nLemma Value_co_subst_co_tm :\n  (forall v b x, Value v -> lc_co b -> Value (co_subst_co_tm b x v)).\nProof.\n  intros v b x H H0.\n  apply co_subst_co_tm_Value_mutual; auto.\nQed.\n\nLemma CoercedValue_co_subst_co_tm :\n  (forall v b x, CoercedValue v -> lc_co b -> CoercedValue (co_subst_co_tm b x v)).\nProof.\n  intros v b x H H0.\n  destruct (co_subst_co_tm_Value_mutual); auto.\nQed.\n\n\n\n(* ------------------------------------------ *)\n\n(*\nLemma decide_Value_mutual : forall a,\n    lc_tm a ->\n    (Value a \\/ not (Value a)) /\\ (CoercedValue a \\/ (not (CoercedValue a))).\nProof.\n  induction 1; try destruct rho.\n  all: try solve [split; left; auto].\n  all: try solve [split; right; intro h; inversion h; try inversion H;\n                  try inversion H1].\n  - pick fresh x.\n    destruct (H1 x) as [[V|NV][CV|NCV]].\n    all: try solve [split; left; eauto using Value_AbsIrrel_exists].\n    + split;\n      right; intro h; inversion h; try inversion H2; subst;\n      apply NCV;\n      pick fresh y;\n      rewrite (tm_subst_tm_tm_intro y); eauto;\n      eapply CoercedValue_tm_subst_tm_tm; eauto.\n  - pick fresh x.\n    destruct (H0 x) as [[V|NV]_].\n    all: try solve [split; left; eauto using Value_UAbsIrrel_exists].\n    split.\n    all: right; intro h; inversion h; try inversion H1; subst; apply NV;\n      pick fresh y;\n      rewrite (tm_subst_tm_tm_intro y); eauto;\n        eapply Value_tm_subst_tm_tm; eauto.\n  - destruct (IHlc_tm) as [[V|NV][CV|NCV]].\n    all: split.\n    all: try solve [left; eauto].\n    all: try solve [right; intro h; inversion h; try inversion H1; eapply NP; eauto].\n    all: try solve [right; intro h; inversion h; try inversion H1; done].\nQed.\n\n\nLemma decide_Value : forall a, lc_tm a -> (Value a \\/ not (Value a)).\nProof.\n  intros a.\n  eapply decide_Value_mutual.\nQed.\n\nLemma decide_CoercedValue : forall a, lc_tm a -> (CoercedValue a \\/ not (CoercedValue a)).\nProof.\n  intros a.\n  eapply decide_Value_mutual.\nQed.\n*)\n\n  (* ------------------------------------------ *)\n(*\nLemma DataTy_value_type : forall A, DataTy A a_Star -> value_type A.\nProof.\n  intros A H.\n  dependent induction H; eauto with lc.\nQed. *)\n", "meta": {"author": "sweirich", "repo": "corespec", "sha": "ee2d477fb26f3d0155be438a93a2c1427511cb24", "save_path": "github-repos/coq/sweirich-corespec", "path": "github-repos/coq/sweirich-corespec/corespec-ee2d477fb26f3d0155be438a93a2c1427511cb24/src/FcEtt/ett_value.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2552317623874653}}
{"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\nRequire Export Pcomb.\nRequire Export Pcrit.\nRequire Export Fred.\nRequire Import moreCoefStructure.\nSection BuchAux.\nLoad \"hCoefStructure\".\nLoad \"hOrderStructure\".\nLoad \"hComb\".\n \nDefinition red (a : poly A0 eqA ltM) (P : list (poly A0 eqA ltM)) :=\n  reducestar A A0 A1 eqA invA minusA multA divA eqA_dec n ltM ltM_dec P\n    (s2p A A0 eqA n ltM a) (pO A n).\n \nDefinition addEnd :\n  poly A0 eqA ltM -> list (poly A0 eqA ltM) -> list (poly A0 eqA ltM).\nintros a H'0; elim H'0.\nexact (a :: nil).\nintros b L1 Rec; exact (b :: Rec).\nDefined.\n \nTheorem addEnd_cons :\n forall (a b : poly A0 eqA ltM) (aL : list (poly A0 eqA ltM)),\n In a (addEnd b aL) -> a = b \\/ In a aL.\nintros a b aL; elim aL; simpl in |- *; auto.\nintros H'; case H'; [ intros H'0; rewrite <- H'0 | intros H'0; clear H' ];\n auto.\nintros a0 l H' H'0; case H'0;\n [ intros H'1; rewrite <- H'1; clear H'0 | intros H'1; clear H'0 ]; \n auto.\ncase (H' H'1); auto.\nQed.\n \nTheorem addEnd_id1 :\n forall (a : poly A0 eqA ltM) (aL : list (poly A0 eqA ltM)),\n In a (addEnd a aL).\nintros a aL; elim aL; simpl in |- *; auto.\nQed.\n \nTheorem addEnd_id2 :\n forall (a b : poly A0 eqA ltM) (aL : list (poly A0 eqA ltM)),\n In a aL -> In a (addEnd b aL).\nintros a b aL; elim aL; simpl in |- *; auto.\nintros a0 l H' H'0; case H'0; auto.\nQed.\n \nLemma addEnd_app :\n forall (a : poly A0 eqA ltM) (P : list (poly A0 eqA ltM)),\n addEnd a P = P ++ a :: nil.\nintros a P; elim P; simpl in |- *; auto.\nintros a0 l H'; elim H'; auto.\nQed.\n \nDefinition spolyp : poly A0 eqA ltM -> poly A0 eqA ltM -> poly A0 eqA ltM.\nintros p q; case p; case q.\nintros x Cpx x0 Cpx0;\n exists\n  (spolyf A A0 A1 eqA invA minusA multA divA eqA_dec n ltM ltM_dec x x0 Cpx\n     Cpx0); auto.\napply spolyf_canonical with (1 := cs); auto.\nDefined.\n \nTheorem red_com :\n forall (a b : poly A0 eqA ltM) (aL : list (poly A0 eqA ltM)),\n red (spolyp a b) aL -> red (spolyp b a) aL.\nintros a b; case a; case b; simpl in |- *.\nunfold red in |- *; simpl in |- *.\nintros x Cx x0 Cx0 aL H'1; inversion H'1.\ncut\n (canonical A0 eqA ltM\n    (spolyf A A0 A1 eqA invA minusA multA divA eqA_dec n ltM ltM_dec x x0 Cx\n       Cx0)); [ intros Op1 | apply spolyf_canonical with (1 := cs) ]; \n auto.\ncut\n (canonical A0 eqA ltM\n    (spolyf A A0 A1 eqA invA minusA multA divA eqA_dec n ltM ltM_dec x0 x Cx0\n       Cx)); [ intros Op2 | apply spolyf_canonical with (1 := cs) ]; \n auto.\napply reducestar0; auto.\napply\n reduceplus_eqp_com\n  with\n    (1 := cs)\n    (p := mults (A:=A) multA (n:=n) (invTerm (A:=A) invA (n:=n) (T1 A1 n))\n            (spolyf A A0 A1 eqA invA minusA multA divA eqA_dec n ltM ltM_dec\n               x x0 Cx Cx0))\n    (q := mults (A:=A) multA (n:=n) (invTerm (A:=A) invA (n:=n) (T1 A1 n))\n            (pO A n)); auto.\napply reduceplus_mults with (1 := cs); auto.\ninversion H; auto.\napply (eqp_sym _ _ _ _ _ _ _ _ _ cs n); auto.\napply spolyf_com with (1 := cs); auto.\napply (eqp_sym _ _ _ _ _ _ _ _ _ cs n); auto.\napply spolyf_com with (1 := cs); auto.\nQed.\n \nTheorem rstar_rtopO :\n forall (Q : list (poly A0 eqA ltM)) (p : list (Term A n)),\n canonical A0 eqA ltM p ->\n reduceplus A A0 A1 eqA invA minusA multA divA eqA_dec n ltM ltM_dec Q p\n   (pO A n) ->\n reducestar A A0 A1 eqA invA minusA multA divA eqA_dec n ltM ltM_dec Q p\n   (pO A n).\nintros Q p H' H'0.\nelim\n reduce0_reducestar\n  with\n    (1 := cs)\n    (eqA_dec := eqA_dec)\n    (ltM_dec := ltM_dec)\n    (Q := Q)\n    (p := pO A n); auto.\nintros t E; apply reducestar0; auto.\napply pO_irreducible; auto.\nQed.\n \nDefinition spO : poly A0 eqA ltM.\nexists (pO A n); simpl in |- *; auto.\nDefined.\n \nDefinition sp1 : poly A0 eqA ltM.\nexists (pX (A1, M1 n) nil); auto.\nDefined.\n \nDefinition sgen : nat -> poly A0 eqA ltM.\nintros m; exists (pX (A1, gen_mon n m) (pO A n)).\napply canonicalp1; auto.\nDefined.\n \nDefinition sscal : A -> poly A0 eqA ltM -> poly A0 eqA ltM.\nintros a p; case p.\nintros x H'1; exists (tmults A0 multA eqA_dec (a, M1 n) x); auto.\nunfold tmults in |- *; case (zeroP_dec A A0 eqA eqA_dec n (a, M1 n));\n simpl in |- *; auto.\nQed.\n \nTheorem red_cons :\n forall (a : poly A0 eqA ltM) (p : list (poly A0 eqA ltM)), In a p -> red a p.\nintros a; case (seqp_dec A A0 eqA eqA_dec n ltM a spO).\ncase a; unfold red, spO, seqP in |- *; simpl in |- *.\nintros x c H' p H'0; inversion H'; auto.\napply reducestar_pO_is_pO with (p := x); auto.\ncase a; unfold red, spO, seqP in |- *; simpl in |- *.\nintros x c H' p H'0.\napply rstar_rtopO; auto.\napply Rstar_n with (y := pO A n); auto.\napply reduce_in_pO with (1 := cs); auto.\nchange\n  (inPolySet A A0 eqA n ltM\n     (s2p A A0 eqA n ltM\n        (exist (fun l : list (Term A n) => canonical A0 eqA ltM l) x c)) p)\n in |- *; apply In_inp_inPolySet; auto.\nred in |- *; intros H'2; apply H'; apply (eqp_sym _ _ _ _ _ _ _ _ _ cs n);\n auto.\napply Rstar_0; auto.\nQed.\n \nTheorem red_id :\n forall (a : poly A0 eqA ltM) (aL : list (poly A0 eqA ltM)),\n red (spolyp a a) aL.\nintros a P; case a.\nunfold red in |- *; simpl in |- *; auto.\nintros x H'.\napply rstar_rtopO; auto.\napply spolyf_canonical with (1 := cs); auto.\napply Rstar_0; auto.\napply spolyf_pO with (1 := cs); auto.\nQed.\n \nTheorem inP_reduce :\n forall P Q : list (poly A0 eqA ltM),\n (forall a : list (Term A n),\n  inPolySet A A0 eqA n ltM a Q -> inPolySet A A0 eqA n ltM a P) ->\n forall a b : list (Term A n),\n reduce A A0 A1 eqA invA minusA multA divA eqA_dec n ltM ltM_dec Q a b ->\n reduce A A0 A1 eqA invA minusA multA divA eqA_dec n ltM ltM_dec P a b.\nintros P Q H' a b H'0; elim H'0; auto.\nintros a0 b0 nZb p q r H'1 H'2 H'3; auto.\napply reducetop with (b := b0) (nZb := nZb) (q := q); auto.\nQed.\n \nTheorem inP_reduceplus :\n forall P Q : list (poly A0 eqA ltM),\n (forall a : list (Term A n),\n  inPolySet A A0 eqA n ltM a Q -> inPolySet A A0 eqA n ltM a P) ->\n forall a b : list (Term A n),\n reduceplus A A0 A1 eqA invA minusA multA divA eqA_dec n ltM ltM_dec Q a b ->\n reduceplus A A0 A1 eqA invA minusA multA divA eqA_dec n ltM ltM_dec P a b.\nintros P Q H' a b H'0; elim H'0; auto.\nintros; apply Rstar_0; auto.\nintros x y z H'1 H'2 H'3.\napply Rstar_n with (y := y); auto.\napply inP_reduce with (Q := Q); auto.\nQed.\n \nTheorem inP_reducestar :\n forall P Q : list (poly A0 eqA ltM),\n (forall a : list (Term A n),\n  inPolySet A A0 eqA n ltM a Q -> inPolySet A A0 eqA n ltM a P) ->\n forall a b : list (Term A n),\n reducestar A A0 A1 eqA invA minusA multA divA eqA_dec n ltM ltM_dec Q a b ->\n reduceplus A A0 A1 eqA invA minusA multA divA eqA_dec n ltM ltM_dec P a b.\nintros P Q H' a b H'0; inversion H'0; auto.\napply inP_reduceplus with (Q := Q); auto.\nQed.\n \nTheorem red_incl :\n forall (a : poly A0 eqA ltM) (p q : list (poly A0 eqA ltM)),\n incl p q -> red a p -> red a q.\nunfold red in |- *.\nintros a p q H' H'0.\ninversion H'0.\napply rstar_rtopO; auto.\ncase a; auto.\napply inP_reducestar with (Q := p); auto.\nintros a0 H'1.\napply Incl_inp_inPolySet with (P := p); auto.\nQed.\n \nDefinition zerop : poly A0 eqA ltM -> Prop.\nintros H'; case H'.\nintros x; case x.\nintros H'0; exact True.\nintros a l H'0; exact False.\nDefined.\n \nTheorem zerop_dec : forall a : poly A0 eqA ltM, {zerop a} + {~ zerop a}.\nintros H'; case H'.\nintros x; case x.\nintros c; left; simpl in |- *; auto.\nintros a l c; right; red in |- *; intros H'0; inversion H'0.\nQed.\n \nDefinition divp : poly A0 eqA ltM -> poly A0 eqA ltM -> Prop.\nintros H'; case H'.\nintros x; case x.\nintros H'0 H'1; exact False.\nintros a l H'0 H'1; case H'1.\nintros x0; case x0.\nintros H'2; exact False.\nintros a0 l0 H'2.\nexact (divP A A0 eqA multA divA n a a0).\nDefined.\n \nTheorem divp_trans : transitive (poly A0 eqA ltM) divp.\nred in |- *.\nintros x y z; case x; case y; case z.\nintros x0 c x1 c0 x2 c1; generalize c c0 c1; case x0; case x1; case x2;\n simpl in |- *; auto.\nintros a l a0 l0 H' H'0 H'1 H'2; elim H'2.\nintros a l a0 l0 a1 l1 H' H'0 H'1 H'2 H'3.\napply (divP_trans _ _ _ _ _ _ _ _ _ cs n) with (y := a0); auto.\nQed.\n \nTheorem divp_dec : forall a b : poly A0 eqA ltM, {divp a b} + {~ divp a b}.\nintros a b; case a; case b.\nintros x c x0 c0; generalize c c0; case x; case x0; simpl in |- *.\nintros H' H'0; right; red in |- *; intros H'1; elim H'1.\nintros a0 l H' H'0; right; red in |- *; intros H'1; elim H'1.\nintros a0 l H' H'0; right; red in |- *; intros H'1; elim H'1.\nintros a0 l a1 l0 H' H'0.\napply divP_dec with (1 := cs); auto.\napply canonical_nzeroP with (ltM := ltM) (p := l); auto.\napply canonical_nzeroP with (ltM := ltM) (p := l0); auto.\nQed.\n \nDefinition ppcp : poly A0 eqA ltM -> poly A0 eqA ltM -> poly A0 eqA ltM.\nintros H'; case H'.\nintros x; case x.\nintros H'0 H'1; exists (pO A n); auto.\nintros a l H'0 H'1; case H'1.\nintros x0; case x0.\nintros H'2; exists (pO A n); auto.\nintros a0 l0 H'2; exists (ppc (A:=A) A1 (n:=n) a a0 :: pO A n).\nchange (canonical A0 eqA ltM (pX (ppc (A:=A) A1 (n:=n) a a0) (pO A n)))\n in |- *; apply canonicalp1; auto.\napply ppc_nZ with (1 := cs); auto.\napply canonical_nzeroP with (ltM := ltM) (p := l); auto.\napply canonical_nzeroP with (ltM := ltM) (p := l0); auto.\nDefined.\n \nTheorem divp_ppc :\n forall a b c : poly A0 eqA ltM, divp (ppcp a b) c -> divp (ppcp b a) c.\nintros a b c; (case a; case b; case c).\nintros x c0 x0 c1 x1 c2; generalize c0 c1 c2; case x; case x0; case x1;\n simpl in |- *; auto.\nintros a0 l a1 l0 a2 l1 H' H'0 H'1 H'2.\napply divP_eqTerm_comp with (1 := cs) (a := ppc (A:=A) A1 (n:=n) a0 a1); auto.\nQed.\n \nTheorem zerop_ddivp_ppc :\n forall a b : poly A0 eqA ltM, ~ zerop a -> ~ zerop b -> divp (ppcp a b) b.\nintros a b; (case a; case b).\nintros x c0 x0 c1; generalize c0 c1; case x; case x0; simpl in |- *; auto.\nintros a0 l a1 l0 H' H'0 H'1 H'2.\napply divP_ppcr with (1 := cs); auto.\napply canonical_nzeroP with (ltM := ltM) (p := l); auto.\napply canonical_nzeroP with (ltM := ltM) (p := l0); auto.\nQed.\n \nTheorem divp_nzeropl : forall a b : poly A0 eqA ltM, divp a b -> ~ zerop a.\nintros a b; (case a; case b).\nintros x c0 x0 c1; generalize c0 c1; case x; case x0; simpl in |- *; auto.\nQed.\n \nTheorem divp_nzeropr : forall a b : poly A0 eqA ltM, divp a b -> ~ zerop b.\nintros a b; (case a; case b).\nintros x c0 x0 c1; generalize c0 c1; case x; case x0; simpl in |- *; auto.\nQed.\nHint Resolve pO_irreducible.\n \nTheorem reducetopO_pO :\n forall Q : list (poly A0 eqA ltM),\n reducestar A A0 A1 eqA invA minusA multA divA eqA_dec n ltM ltM_dec Q\n   (pO A n) (pO A n).\nintros Q; apply reducestar0; auto.\napply Rstar_0; auto.\nQed.\nHint Resolve reducetopO_pO.\n \nTheorem zerop_red_spoly_l :\n forall a b : poly A0 eqA ltM,\n zerop a -> forall Q : list (poly A0 eqA ltM), red (spolyp a b) Q.\nintros a b; (case a; case b).\nintros x c0 x0 c1; generalize c0 c1; case x; case x0; simpl in |- *; auto.\nintros c2 c3 H' Q; unfold red in |- *; simpl in |- *; auto.\nintros a0 l c2 c3 H'; elim H'.\nintros a0 l c2 c3 H' Q; unfold red in |- *; simpl in |- *; auto.\nintros a0 l a1 l0 c2 c3 H'; elim H'.\nQed.\n \nTheorem zerop_red_spoly_r :\n forall a b : poly A0 eqA ltM,\n zerop b -> forall Q : list (poly A0 eqA ltM), red (spolyp a b) Q.\nintros a b; (case a; case b).\nintros x c0 x0 c1; generalize c0 c1; case x; case x0; simpl in |- *; auto.\nintros c2 c3 H' Q; unfold red in |- *; simpl in |- *; auto.\nintros a0 l c2 c3 H' Q; unfold red in |- *; simpl in |- *; auto.\nintros a0 l c2 c3 H'; elim H'.\nintros a0 l a1 l0 c2 c3 H'; elim H'.\nQed.\n \nTheorem divP_ppc :\n forall a b c : poly A0 eqA ltM, divp a b -> divp a c -> divp a (ppcp b c).\nintros a b c; (case a; case b; case c).\nintros x c0 x0 c1 x1 c2; generalize c0 c1 c2; case x; case x0; case x1;\n simpl in |- *; auto.\nintros a0 l a1 l0 a2 l1 H' H'0 H'1 H'2 H'3.\nelim ppc_is_ppcm with (1 := cs) (a := a1) (b := a2); auto.\napply canonical_nzeroP with (ltM := ltM) (p := l0); auto.\napply canonical_nzeroP with (ltM := ltM) (p := l1); auto.\nQed.\n \nDefinition Cb : poly A0 eqA ltM -> list (poly A0 eqA ltM) -> Prop.\nintros H'; case H'.\nintros x H'0 Q;\n exact (CombLinear A A0 eqA plusA multA eqA_dec n ltM ltM_dec Q x).\nDefined.\n \nTheorem Cb_id :\n forall (a : poly A0 eqA ltM) (Q : list (poly A0 eqA ltM)), In a Q -> Cb a Q.\nintros a; case a; simpl in |- *.\nintros x; case x; auto.\nintros c Q H'.\nreplace (nil (A:=Term A n)) with (pO A n); auto; apply CombLinear_0; auto.\nintros a0 l c Q H'.\napply CombLinear_id with (1 := cs); auto.\nchange\n  (inPolySet A A0 eqA n ltM\n     (s2p A A0 eqA n ltM (mks A A0 eqA n ltM (pX a0 l) c)) Q) \n in |- *; apply in_inPolySet; auto.\nred in |- *; intros H'4; inversion H'4.\nQed.\n \nTheorem inPolySet_addEnd :\n forall (a : list (Term A n)) (p : poly A0 eqA ltM)\n   (l : list (poly A0 eqA ltM)),\n inPolySet A A0 eqA n ltM a (addEnd p l) ->\n a = s2p A A0 eqA n ltM p \\/ inPolySet A A0 eqA n ltM a l.\nintros a p l; elim l; simpl in |- *; auto.\nintros H'; inversion H'; auto.\nintros a0 l0 H' H'0; inversion H'0; auto.\nright.\nexact (incons A A0 eqA n ltM a1 p0 H l0).\ncase H'; auto.\nintros H3; right; try assumption.\napply inskip; auto.\nQed.\n \nRemark CombLinear_trans1 :\n forall (a : list (Term A n)) (R : list (poly A0 eqA ltM)),\n CombLinear A A0 eqA plusA multA eqA_dec n ltM ltM_dec R a ->\n forall (b : poly A0 eqA ltM) (Q : list (poly A0 eqA ltM)),\n R = addEnd b Q ->\n CombLinear A A0 eqA plusA multA eqA_dec n ltM ltM_dec Q\n   (s2p A A0 eqA n ltM b) ->\n CombLinear A A0 eqA plusA multA eqA_dec n ltM ltM_dec Q a.\nintros a R H'; elim H'; auto.\nintros b Q H'0 H'1.\napply CombLinear_0; auto.\nintros a0 p q s H'0 H'1 H'2 H'3 H'4 b Q H'5 H'6.\napply\n CombLinear_comp\n  with\n    (1 := cs)\n    (p := pluspf (A:=A) A0 (eqA:=eqA) plusA eqA_dec (n:=n) (ltM:=ltM) ltM_dec\n            (mults (A:=A) multA (n:=n) a0 q) p); auto.\n2: apply\n    eqp_imp_canonical\n     with\n       (1 := cs)\n       (p := pluspf (A:=A) A0 (eqA:=eqA) plusA eqA_dec (n:=n) (ltM:=ltM)\n               ltM_dec (mults (A:=A) multA (n:=n) a0 q) p); \n    auto.\n2: apply (eqp_sym _ _ _ _ _ _ _ _ _ cs n); auto.\n2: apply canonical_pluspf with (1 := os); auto.\n2: apply canonical_mults with (1 := cs); auto.\n2: apply inPolySet_imp_canonical with (L := R); auto.\n2: apply\n    CombLinear_canonical\n     with (eqA_dec := eqA_dec) (ltM_dec := ltM_dec) (1 := cs) (Q := R); \n    auto.\n2: apply (eqp_sym _ _ _ _ _ _ _ _ _ cs n); auto.\napply CombLinear_pluspf with (1 := cs); auto.\napply CombLinear_mults1 with (1 := cs); auto.\n2: apply H'3 with (b := b); auto.\ncase (inPolySet_addEnd q b Q); auto.\nrewrite <- H'5; auto.\nintros H'7; rewrite H'7; auto.\nintros; (apply CombLinear_id with (1 := cs); auto).\nQed.\n \nTheorem Cb_trans :\n forall (a b : poly A0 eqA ltM) (Q : list (poly A0 eqA ltM)),\n Cb a (addEnd b Q) -> Cb b Q -> Cb a Q.\nintros a b; case a; case b; simpl in |- *; auto.\nintros x c x0 H' Q H'0 H'1.\napply\n CombLinear_trans1\n  with\n    (R := addEnd\n            (exist (fun l : list (Term A n) => canonical A0 eqA ltM l) x c) Q)\n    (b := exist (fun l : list (Term A n) => canonical A0 eqA ltM l) x c);\n auto.\nQed.\n \nTheorem Cb_incl :\n forall (a : poly A0 eqA ltM) (P Q : list (poly A0 eqA ltM)),\n (forall a : poly A0 eqA ltM, In a P -> In a Q) -> Cb a P -> Cb a Q.\nintros a; case a; simpl in |- *; auto.\nintros x H' P Q H'0 H'1.\napply CombLinear_incl with (1 := cs) (P := P); auto.\nintros a0 H'2.\napply Incl_inp_inPolySet with (P := P); auto.\nQed.\n \nTheorem Cb_in1 :\n forall (a b : poly A0 eqA ltM) (Q : list (poly A0 eqA ltM)),\n Cb a Q -> Cb a (b :: Q).\nintros a b Q H'.\napply Cb_incl with (P := Q); simpl in |- *; auto.\nQed.\n \nTheorem Cb_in :\n forall (a b : poly A0 eqA ltM) (Q : list (poly A0 eqA ltM)),\n Cb a Q -> Cb a (addEnd b Q).\nintros a b Q H'.\napply Cb_incl with (P := Q); simpl in |- *; auto.\nintros a0 H'0; apply addEnd_id2; auto.\nQed.\n \nTheorem Cb_sp :\n forall (a b : poly A0 eqA ltM) (Q : list (poly A0 eqA ltM)),\n Cb a Q -> Cb b Q -> Cb (spolyp a b) Q.\nintros a b; case a; case b; simpl in |- *; auto.\nintros x; case x; auto.\nintros a0 l H' x0; case x0; auto.\nintros a1 l0 H'0 Q H'1 H'2.\ncut (~ zeroP (A:=A) A0 eqA (n:=n) a0);\n [ intros Z0 | apply canonical_nzeroP with (ltM := ltM) (p := l); auto ].\ncut (~ zeroP (A:=A) A0 eqA (n:=n) a1);\n [ intros Z1 | apply canonical_nzeroP with (ltM := ltM) (p := l0); auto ].\napply\n CombLinear_comp\n  with\n    (1 := cs)\n    (p := minuspf A A0 A1 eqA invA minusA multA eqA_dec n ltM ltM_dec\n            (mults (A:=A) multA (n:=n)\n               (divTerm (A:=A) (A0:=A0) (eqA:=eqA) divA (n:=n)\n                  (ppc (A:=A) A1 (n:=n) a0 a1) (b:=a0) Z0) \n               (pX a0 l))\n            (mults (A:=A) multA (n:=n)\n               (divTerm (A:=A) (A0:=A0) (eqA:=eqA) divA (n:=n)\n                  (ppc (A:=A) A1 (n:=n) a0 a1) (b:=a1) Z1) \n               (pX a1 l0))); auto.\napply CombLinear_minuspf with (1 := cs); auto.\napply CombLinear_mults1 with (1 := cs); auto.\napply CombLinear_mults1 with (1 := cs); auto.\napply spolyf_canonical with (1 := cs); auto.\napply (eqp_sym _ _ _ _ _ _ _ _ _ cs n); auto.\nchange\n  (eqP A eqA n\n     (spolyf A A0 A1 eqA invA minusA multA divA eqA_dec n ltM ltM_dec\n        (pX a0 l) (pX a1 l0) H' H'0)\n     (minuspf A A0 A1 eqA invA minusA multA eqA_dec n ltM ltM_dec\n        (mults (A:=A) multA (n:=n)\n           (divTerm (A:=A) (A0:=A0) (eqA:=eqA) divA (n:=n)\n              (ppc (A:=A) A1 (n:=n) a0 a1) (b:=a0) Z0) \n           (pX a0 l))\n        (mults (A:=A) multA (n:=n)\n           (divTerm (A:=A) (A0:=A0) (eqA:=eqA) divA (n:=n)\n              (ppc (A:=A) A1 (n:=n) a0 a1) (b:=a1) Z1) \n           (pX a1 l0)))) in |- *.\napply spoly_is_minus with (1 := cs); auto.\nQed.\n \nDefinition unit : poly A0 eqA ltM -> Term A n.\nintros p; case p.\nintros x; case x.\nintros H'; exact (T1 A1 n).\nintros a l; case a.\nintros co m H'; cut (~ eqA co A0).\nintros H'0; exact (divA A1 co H'0, M1 n).\ninversion H'; auto.\nsimpl in H0.\nintuition.\nDefined.\n \nTheorem unit_T1 : forall p : poly A0 eqA ltM, eqT (unit p) (T1 A1 n).\nunfold eqT in |- *; intros p; case p.\nintros x; case x; simpl in |- *; auto.\nintros a l; case a; simpl in |- *; auto.\nQed.\n \nTheorem divA_nZ :\n forall a b : A,\n ~ eqA b A0 -> forall nZa : ~ eqA a A0, ~ eqA (divA b a nZa) A0.\nintros a b H' nZa; red in |- *; intros H'1; auto.\ncase H';\n apply (eqA_trans _ _ _ _ _ _ _ _ _ cs) with (y := multA (divA b a nZa) a);\n auto.\napply divA_is_multA with (1 := cs); auto.\napply (eqA_trans _ _ _ _ _ _ _ _ _ cs) with (y := multA A0 a); auto.\napply multA_eqA_comp with (1 := cs); auto.\napply (eqA_ref _ _ _ _ _ _ _ _ _ cs); auto.\napply multA_A0_l with (1 := cs); auto.\nQed.\nHint Resolve divA_nZ.\n \nTheorem unit_nZ :\n forall p : poly A0 eqA ltM, ~ zeroP (A:=A) A0 eqA (n:=n) (unit p).\nintros p; case p.\nintros x; case x; simpl in |- *; auto.\nintros a l; case a; simpl in |- *; auto.\nQed.\n \nDefinition nf : poly A0 eqA ltM -> list (poly A0 eqA ltM) -> poly A0 eqA ltM.\nintros p L.\ncase\n (Reducef A A0 A1 eqA plusA invA minusA multA divA cs eqA_dec n ltM ltM_dec\n    os L p).\nintros x H'.\napply LetP with (A := poly A0 eqA ltM) (h := x).\nintros u H'1; case u.\nintros x0 H'2;\n exists (mults (A:=A) multA (n:=n) (unit (mks A A0 eqA n ltM x0 H'2)) x0);\n auto.\napply canonical_mults with (1 := cs); auto.\napply unit_nZ; auto.\nDefined.\n \nTheorem nf_irreducible :\n forall (p : poly A0 eqA ltM) (aP : list (poly A0 eqA ltM)),\n irreducible A A0 A1 eqA invA minusA multA divA eqA_dec n ltM ltM_dec aP\n   (s2p A A0 eqA n ltM (nf p aP)).\nunfold nf in |- *.\nintros p aP;\n case\n  (Reducef A A0 A1 eqA plusA invA minusA multA divA cs eqA_dec n ltM ltM_dec\n     os aP p).\nintros x; case x; simpl in |- *; auto.\nintros x0 c H'; inversion H'.\nred in H0.\nred in |- *; red in |- *.\nintros q0; intros H'0; auto.\ncut (~ zeroP (A:=A) A0 eqA (n:=n) (unit (mks A A0 eqA n ltM x0 c)));\n [ intros nZd | idtac ]; auto.\napply\n H0\n   with\n     (q := mults (A:=A) multA (n:=n)\n             (divTerm (A:=A) (A0:=A0) (eqA:=eqA) divA (n:=n) \n                (T1 A1 n) (b:=unit (mks A A0 eqA n ltM x0 c)) nZd) q0);\n auto.\napply reduce_mults_invf with (1 := cs); auto.\napply unit_T1; auto.\napply unit_nZ; auto.\nQed.\n \nTheorem nf_red :\n forall (a : poly A0 eqA ltM) (aP aQ : list (poly A0 eqA ltM)),\n incl aP aQ -> red (nf a aP) aQ -> red a aQ.\nintros a; case a; simpl in |- *.\nunfold red in |- *; unfold nf in |- *; simpl in |- *; auto.\nintros x c aP aQ H';\n case\n  (Reducef A A0 A1 eqA plusA invA minusA multA divA cs eqA_dec n ltM ltM_dec\n     os aP (exist (fun a => canonical A0 eqA ltM a) x c)); \n simpl in |- *; auto.\nintros x0; case x0; simpl in |- *; auto.\nintros x1 c0 H'0 H'1.\napply rstar_rtopO; auto.\napply reduceplus_trans with (Q := aQ) (1 := cs) (y := x1); auto.\ninversion H'0; auto.\napply inP_reduceplus with (Q := aP); auto.\nintros a0 H'3.\napply Incl_inp_inPolySet with (P := aP); auto.\napply\n reduceplus_mults_inv with (1 := cs) (a := unit (mks A A0 eqA n ltM x1 c0));\n auto.\napply unit_nZ; auto.\napply unit_T1; auto.\ninversion H'1; inversion H; auto.\nQed.\n \nTheorem red_zerop :\n forall (a : poly A0 eqA ltM) (P : list (poly A0 eqA ltM)),\n red (nf a P) P -> zerop (nf a P).\nunfold nf in |- *.\nintros p aP; case p.\nintros x c.\ncase\n (Reducef A A0 A1 eqA plusA invA minusA multA divA cs eqA_dec n ltM ltM_dec\n    os aP (exist (fun l => canonical A0 eqA ltM l) x c)); \n auto.\nunfold red in |- *; auto.\nintros x0; case x0.\nintros x1; case x1.\nsimpl in |- *; auto.\nintros a l c0 H' H'0; inversion H'.\nsimpl in |- *.\nchange\n  (reducestar A A0 A1 eqA invA minusA multA divA eqA_dec n ltM ltM_dec aP\n     (mults (A:=A) multA (n:=n) (unit (mks A A0 eqA n ltM (a :: l) c0))\n        (a :: l)) (pO A n)) in H'0.\ninversion H'0.\ninversion H3.\ninversion H7.\nsimpl in H0.\ncut (~ zeroP (A:=A) A0 eqA (n:=n) (unit (mks A A0 eqA n ltM (pX a l) c0)));\n [ intros nZd | idtac ]; auto.\ncase\n (H0\n    (mults (A:=A) multA (n:=n)\n       (divTerm (A:=A) (A0:=A0) (eqA:=eqA) divA (n:=n) \n          (T1 A1 n) (b:=unit (mks A A0 eqA n ltM (pX a l) c0)) nZd) y)); \n auto.\napply reduce_mults_invf with (1 := cs); auto.\napply unit_T1; auto.\napply unit_nZ; auto.\nQed.\n \nTheorem zerop_red :\n forall (a : poly A0 eqA ltM) (aP : list (poly A0 eqA ltM)),\n zerop (nf a aP) -> red a aP.\nintros a aP H'.\napply nf_red with (aP := aP); auto with datatypes.\ngeneralize H'; case (nf a aP); simpl in |- *; auto.\nintros x; case x; simpl in |- *; auto.\nintros c H'0; red in |- *; simpl in |- *; auto.\nintros a0 l H'0 H'1; elim H'1; auto.\nQed.\n \nTheorem canonical_s2p :\n forall x : poly A0 eqA ltM, canonical A0 eqA ltM (s2p A A0 eqA n ltM x).\nintros x; case x; auto.\nQed.\nHint Resolve canonical_s2p.\n \nTheorem nf_Cb :\n forall (a : poly A0 eqA ltM) (aP : list (poly A0 eqA ltM)),\n Cb a aP -> Cb (nf a aP) aP.\nintros a; case a; unfold nf, Cb in |- *; auto.\nintros x c Q H';\n case\n  (Reducef A A0 A1 eqA plusA invA minusA multA divA cs eqA_dec n ltM ltM_dec\n     os Q (exist (fun l : list (Term A n) => canonical A0 eqA ltM l) x c));\n auto.\nintros x0; case x0.\nintros x1 H'0 H'1.\nchange\n  (CombLinear A A0 eqA plusA multA eqA_dec n ltM ltM_dec Q\n     (mults (A:=A) multA (n:=n) (unit (mks A A0 eqA n ltM x1 H'0)) x1))\n in |- *.\napply CombLinear_mults1 with (1 := cs); auto.\napply unit_nZ; auto.\napply reducestar_cb with (a := x) (1 := cs); auto.\nQed.\n \nDefinition foreigner : poly A0 eqA ltM -> poly A0 eqA ltM -> Prop.\nintros a b; case a; case b.\nintros x; case x.\nintros H' x0 H'0; exact True.\nintros a0 l H' x0; case x0.\nintros H'0; exact True.\nintros a1 l0 H'0;\n exact\n  (eqT (ppc (A:=A) A1 (n:=n) a0 a1) (multTerm (A:=A) multA (n:=n) a0 a1)).\nDefined.\n \nDefinition foreigner_dec :\n  forall a b : poly A0 eqA ltM, {foreigner a b} + {~ foreigner a b}.\nintros a b; case a; case b.\nintros x; case x.\nsimpl in |- *; auto.\nintros a0 l c x0; case x0; simpl in |- *; auto.\nintros a1 l0 H'.\napply eqT_dec; auto.\nDefined.\n \nTheorem foreigner_red :\n forall (a b : poly A0 eqA ltM) (P : list (poly A0 eqA ltM)),\n foreigner a b -> In a P -> In b P -> red (spolyp a b) P.\nintros a b; case a; case b.\nintros x; case x.\nsimpl in |- *; auto.\nunfold red in |- *; simpl in |- *; auto.\nintros a0 l c x0; case x0.\nunfold red in |- *; simpl in |- *; auto.\nunfold red in |- *; simpl in |- *; auto.\nintros a1 l0 c0 P H' H'0 H'1.\nunfold LetP in |- *; simpl in |- *; auto.\napply\n reducestar_eqp_com\n  with\n    (1 := cs)\n    (p := spolyf A A0 A1 eqA invA minusA multA divA eqA_dec n ltM ltM_dec\n            (pX a0 l) (pX a1 l0) c c0)\n    (q := pO A n); auto.\napply spoly_Reducestar_ppc with (1 := cs); auto.\nchange\n  (inPolySet A A0 eqA n ltM\n     (s2p A A0 eqA n ltM (mks A A0 eqA n ltM (pX a1 l0) c0)) P) \n in |- *.\napply in_inPolySet; auto.\nred in |- *; intros H'3; inversion H'3; auto.\nchange\n  (inPolySet A A0 eqA n ltM\n     (s2p A A0 eqA n ltM (mks A A0 eqA n ltM (pX a0 l) c)) P) \n in |- *.\napply in_inPolySet; auto.\nred in |- *; intros H'3; inversion H'3; auto.\napply spolyf_canonical with (1 := cs); auto.\nQed.\nEnd BuchAux.", "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/buchberger/BuchAux.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2551992471721474}}
{"text": "From Equations Require Import Equations.\n\nInductive t (u : unit) :=\n| strange : t tt  -> t u.\n\nDerive NoConfusionHom for t.\nFail Derive Subterm for t.\n\nInductive t' (u : unit) : Set :=\n| strange' : t' tt  -> t' u.\n\nDerive NoConfusionHom for t'.\nDerive Subterm for t'.\nDefinition test := well_founded_t'_subterm.\n", "meta": {"author": "mattam82", "repo": "Coq-Equations", "sha": "5603bfff39f3866eed8f010591b5503d5776fa4e", "save_path": "github-repos/coq/mattam82-Coq-Equations", "path": "github-repos/coq/mattam82-Coq-Equations/Coq-Equations-5603bfff39f3866eed8f010591b5503d5776fa4e/test-suite/issues/issue246.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878696277512, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.25519924717214737}}
{"text": "From Coq.Lists Require Import List.\nFrom Equations Require Import Equations.\n\n(* This type is from VST: \n * https://github.com/PrincetonUniversity/VST/blob/v2.1/floyd/compact_prod_sum.v#L13 *)\nFixpoint compact_sum (T: list Type): Type :=\n  match T with\n  | nil => unit\n  | t :: nil => t\n  | t :: T0 => (t + compact_sum T0)%type\nend.\n\n(* The rest is a nonsensical, just to give a minimalistic reproducible example *)\nInductive Foo :=\n| Sum : list Foo -> Foo.\n\nEquations foo_type (t : Foo) : Type :=\n  foo_type (Sum u) := compact_sum (List.map foo_type u).\n\n(* Moving val into the return type, rather than having it as an argument might be\n * unnecessary if https://github.com/mattam82/Coq-Equations/issues/73 was fixed *)\nFail Equations do_foo (f : Foo) : forall (val : foo_type f), nat := {\n  do_foo (Sum u) := fun val => do_foo_sum u val }\n\n  where\n  do_foo_sum (fs : list Foo) : forall val : compact_sum (List.map foo_type fs), nat\n     by struct fs := {\n    do_foo_sum nil := fun val => 0;\n    (* Attempting to work around https://github.com/mattam82/Coq-Equations/issues/78 *)\n    do_foo_sum (cons hd tl) with (fun val => do_foo_sum tl val) => {\n      do_foo_sum (cons var nil) := fun val => do_foo var val;\n      do_foo_sum (cons hd tl) do_foo_tl := fun val =>\n        match val with\n        | inl v => do_foo hd v\n        | inr vs => do_foo_tl vs\n        end }}.", "meta": {"author": "mattam82", "repo": "Coq-Equations", "sha": "5603bfff39f3866eed8f010591b5503d5776fa4e", "save_path": "github-repos/coq/mattam82-Coq-Equations", "path": "github-repos/coq/mattam82-Coq-Equations/Coq-Equations-5603bfff39f3866eed8f010591b5503d5776fa4e/test-suite/issues/issue100.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2551992413172257}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom Tweetnacl_verif Require Import init_tweetnacl.\nFrom Tweetnacl.Low Require Import Car25519.\nFrom Tweetnacl.Low Require Import Car25519_bounds.\nFrom Tweetnacl_verif Require Import spec_set25519.\nFrom Tweetnacl_verif Require Import spec_sel25519.\nFrom Tweetnacl_verif Require Import spec_car25519.\nFrom Tweetnacl_verif Require Import spec_pack25519.\n\nOpen Scope Z.\n\nDefinition Gprog : funspecs :=\n      ltac:(with_library prog [pack25519_spec; car25519_spec; set25519_spec; sel25519_spec]).\n\nLemma bound_impl_247_262: forall x : ℤ, 38 * - 2 ^ 47 <= x < 2 ^ 16 + 38 * 2 ^ 47 -> - 2 ^ 62 < x < 2 ^ 62.\nProof. intros. solve_bounds_by_values. Qed.\n\nLemma verif_pack25519_1: forall Tsh n,\n  writable_share Tsh ->\n  Zlength n = 16 ->\n  Forall (fun x : ℤ => - 2 ^ 62 < x < 2 ^ 62) n ->\n  writable_share Tsh /\\ Forall (fun x : ℤ => - 2 ^ 62 < x < 2 ^ 62) (car25519 n) /\\ Zlength (car25519 n) = 16.\nProof.\nintros Tsh n HTsh Hln Hbn.\nrepeat match goal with\n| _ => assumption\n| _ => apply bound_impl_247_262\n| [ |- _ /\\ _ ] => split\n| _ => solve[rewrite car25519_Zlength ; auto]\n| _ => apply Zcar25519_bounds_length_1\n| _ => solve[rewrite Zlength_correct in Hln ; omega]\n| _ => eapply list.Forall_impl\nend.\nQed.\n\nLemma verif_pack25519_2:\nforall Tsh n,\n  writable_share Tsh ->\n  Zlength n = 16 ->\n  Forall (fun x : ℤ => - 2 ^ 62 < x < 2 ^ 62) n ->\nwritable_share Tsh /\\\nForall (fun x : ℤ => - 2 ^ 62 < x < 2 ^ 62) (car25519 (car25519 n)) /\\ Zlength (car25519 (car25519 n)) = 16.\nProof.\nintros Tsh n HTsh Hln Hbn.\nrepeat match goal with\n| _ => assumption\n| _ => apply bound_impl_247_262\n| [ |- _ /\\ _ ] => split\n| _ => solve[rewrite ?car25519_Zlength ; auto]\n| _ => apply Zcar25519_bounds_length_1\n| _ => solve[rewrite Zlength_correct in Hln ; omega]\n| _ => eapply list.Forall_impl\n| _ => rewrite ?car25519_length\nend.\nQed.\n\nLemma verif_pack25519_4:\nforall t',\nZlength t' = 16 ->\nForall (fun x : ℤ => 0 <= x < 2 ^ 16) t'->\nInt64.min_signed <= Znth 0 t' 0 - 65517 <= Int64.max_signed.\nProof.\nintros.\nassert(Int64.min_signed + 65517 <= Znth 0 t' 0  <= Int64.max_signed  + 65517).\nsolve_bounds_by_values_Znth.\nomega.\nQed.\n\nLemma verif_pack25519_5':\nforall t' : list ℤ,\nZlength t' = 16 ->\nForall (fun x : ℤ => 0 <= x < 2 ^ 16) t' ->\nforall i : ℤ,\n1 <= i < 15 ->\nforall m''' : list ℤ,\nZlength m''' = 16 ->\nZlength (mVI64 m''') = 16 ->\nZlength (mVI64 t') = 16 ->\nInt64.min_signed <=\nZnth i t' 0 - 65535 -\nInt64.signed (Int64.and (Int64.shr (Int64.repr (Znth (i - 1) m''' 0)) (Int64.repr 16)) (Int64.repr 1)) <=\nInt64.max_signed /\\ Int64.min_signed <= Int64.signed (Int64.repr (Znth i t' 0)) - 65535 <= Int64.max_signed.\nProof.\nsplit.\n2: solve_bounds_by_values_Znth.\nrewrite and64_repr.\nremember (Z.shiftr (Int64.signed (Int64.repr (Znth (i - 1) m''' 0))) (Int64.unsigned (Int64.repr 16))) as mi1.\nassert(0 <= Z.land mi1 1 <= 1) by apply and_0_or_1.\nassert(HZland: Z.land mi1 1 = 0 \\/ Z.land mi1 1 = 1) by omega.\ndestruct HZland as [HZland | HZland]; rewrite HZland.\n1,2: assert(Int64.min_signed + 65536 <= Znth i t' 0 <= Int64.max_signed  + 65535) by\nsolve_bounds_by_values_Znth.\nall: rewrite ?Int64.signed_repr.\nall: solve_bounds_by_values.\nQed.\n\nLemma verif_pack25519_8:\nforall t' : list ℤ,\nZlength t' = 16 ->\nForall (fun x : ℤ => 0 <= x < 2 ^ 16) t' ->\nZlength (mVI64 t') = 16 ->\nforall mi1 : ℤ,\nInt64.min_signed <=\nZnth 15 t' 0 - 32767 -\nInt64.signed (Int64.and (Int64.shr (Int64.repr mi1) (Int64.repr 16)) (Int64.repr 1)) <= Int64.max_signed /\\\nInt64.min_signed <= Int64.signed (Int64.repr (Znth 15 t' 0)) - 32767 <= Int64.max_signed.\nProof.\nintros.\nassert(0 <= Z.land (Z.shiftr (Int64.signed (Int64.repr mi1)) (Int64.unsigned (Int64.repr 16))) 1 <= 1).\napply and_0_or_1.\nrewrite and64_repr.\nassert(HZland: Z.land (Z.shiftr (Int64.signed (Int64.repr mi1)) (Int64.unsigned (Int64.repr 16))) 1 = 0 \\/\n  Z.land (Z.shiftr (Int64.signed (Int64.repr mi1)) (Int64.unsigned (Int64.repr 16))) 1 = 1) by omega.\ndestruct HZland as [HZland | HZland]; rewrite HZland.\n1,2: assert(Int64.min_signed + 32767 <= Znth 15 t' 0 <= Int64.max_signed  + 32767).\n2,4: repeat rewrite Int64.signed_repr.\n2,6: split.\nall: try solve[apply Forall_Znth ; [omega|]; eapply list.Forall_impl ; [eassumption |];\nintros x Hx ; simpl in Hx ; solve_bounds_by_values].\nall: solve_bounds_by_values.\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_pack25519_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2551992413172257}}
{"text": "From cap_machine Require Export rules_binary_base rules_Store.\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 iFailStep_alt fail_type :=\n    iMod (exprspec_mapsto_update _ _ (fill _ (Instr Failed)) with \"Hown Hj\") as \"[Hown Hj]\";\n    iMod (\"Hclose\" with \"[Hown]\") as \"_\";\n    [iNext;iExists _,_;iFrame;iPureIntro;eapply rtc_r;eauto;prim_step_from_exec|];\n    iExists (FailedV),_,_; iFrame;iModIntro;iFailCore fail_type.\n\n  Lemma step_store Ep K\n     pc_p pc_g pc_b pc_e pc_a\n     r1 (r2 : Z + RegName) w mem regs :\n   decodeInstrW w = Store 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 (Store r1 r2) ⊆ dom _ regs →\n   mem !! pc_a = Some w →\n   allow_store_map_or_true r1 r2 regs mem →\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' mem', ⌜ Store_spec regs r1 r2 regs' mem mem' retv⌝ ∗\n                           ⤇ fill K (of_val retv) ∗ ([∗ map] a↦w ∈ mem', a ↣ₐ w) ∗ [∗ map] k↦y ∈ regs', k ↣ᵣ y.\n  Proof.\n    iIntros (Hinstr Hvpc HPC Dregs Hmem_pc HaStore 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\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 r1) as [r1v [Hr'1 Hr1]]. by set_solver+.\n    pose proof (regs_lookup_eq _ _ _ Hr'1) as Hr''1.\n    iDestruct (memspec_heap_valid_inSepM _ _ _ _ pc_a with \"Hown Hmem\") as %Hma; eauto.\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     simpl in Hr1, Hma. option_locate_mr σm σr.\n     assert (Hstep':=Hstep). cbn in Hstep. rewrite Hσrr1 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 r1v as  [| (([[p g] b] & e) & a) ] eqn:Hr1v.\n     { (* Failure: r1 is not a capability *)\n       assert (c = Failed ∧ σ2 = (σr, σm)) as (-> & ->)\n           by (destruct r2; inversion Hstep; auto).\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.\n       iPureIntro. econstructor; eauto. econstructor; eauto.\n     }\n\n     destruct (writeAllowed p && withinBounds (p, g, b, e, a)) eqn:HWA; rewrite HWA in Hstep.\n     2 : { (* Failure: r2 is either not within bounds or doesnt allow reading *)\n        assert (c = Failed ∧ σ2 = (σr, σm)) as (-> & ->)\n         by (destruct r2; inversion Hstep; auto).\n       apply andb_false_iff in HWA.\n       iFailStep_alt Store_fail_bounds.\n     }\n     apply andb_true_iff in HWA; destruct HWA as (Hwa & Hwb).\n\n     destruct (word_of_argument regs r2) as [ storev | ] eqn:HSV.\n     2: {\n       destruct r2 as [z | r2].\n       - cbn in HSV; inversion HSV.\n       - destruct (Hri r2) as [r0v [Hr0 _] ]. by set_solver+.\n         cbn in HSV. rewrite Hr0 in HSV. inversion HSV.\n     }\n     assert (word_of_argument σr r2 = Some(storev)) as HSVr.\n     { destruct r2; cbn in HSV. inversion HSV; simpl in H3;auto;by rewrite H3.\n       destruct (Hri r) as [r0v [Hregs0 Hr0] ].  by set_solver+.\n       rewrite -Hr0 in Hregs0; rewrite Hregs0 in HSV. exact HSV.\n     }\n\n     case_eq (canStore p a storev); intro HcanStore.\n     2:{ destruct r2.\n         - simpl in HSV; inv HSV. simpl in HcanStore; congruence.\n         - assert (c = Failed ∧ σ2 = (σr, σm)) as (-> & ->).\n           { simpl in HSV; inv HSV. rewrite /= in HSVr.\n             rewrite /= /RegLocate in Hstep.\n             destruct (σr !! r); try congruence. inv HSVr.\n             rewrite HcanStore in Hstep. inv Hstep; auto. }\n           iFailStep_alt Store_fail_invalid_locality.\n     }\n\n     (* Prove that a is in the memory map now, otherwise we cannot continue *)\n     pose proof (allow_store_implies_storev r1 r2 mem regs p g b e a storev) as (oldv & Hmema); auto.\n\n     (* Given this, prove that a is also present in the memory itself *)\n     iDestruct (memspec_v_implies_m_v mem (σr,σm) _ b e a oldv with \"Hmem Hown\" ) as %Hma ; auto.\n\n     (* Regardless of whether we increment the PC, the memory will change: destruct on the PC later *)\n     assert (updatePC (update_mem (σr, σm) a storev) = (c, σ2)) as HH.\n      { destruct r2.\n       - cbv in HSVr; inversion HSVr; subst storev. done.\n       - destruct (σr !r! r) eqn:Hr0.\n         * destruct (Hri r) as [r0v [Hregs01 Hr01] ]. by set_solver+.\n           assert(is_Some( σr !! r )) as Hrr0. by exists r0v.\n           pose proof (regs_lookup_inl_eq σr r z Hrr0 Hr0) as Hr0'.\n           simpl in HSVr; rewrite Hr0' in HSVr.\n           inversion HSVr; subst storev. done.\n         * destruct_cap c0.\n           epose proof (regs_lookup_inr_eq σr r _ _ _ _ _ Hr0) as Hr0'.\n           simpl in HSVr; rewrite Hr0' in HSVr; inversion HSVr.\n           subst storev; clear HSVr.\n           rewrite HcanStore /= in Hstep.\n           auto.\n      }\n      iMod ((memspec_heap_update_inSepM _ _ _ a storev) with \"Hown Hmem\") as \"[Hown Hmem]\"; eauto.\n\n      destruct (incrementPC regs ) as [ regs' |] eqn:Hregs'.\n      2: { (* Failure: the PC could not be incremented correctly *)\n        assert (incrementPC σr = None).\n        { eapply incrementPC_overflow_mono; first eapply Hregs'; eauto. }\n        rewrite incrementPC_fail_updatePC /= in HH; auto.\n        inversion HH. subst.\n        iMod (exprspec_mapsto_update _ _ (fill _ (Instr Failed)) with \"Hown Hj\") as \"[Hown Hj]\";\n          iMod (\"Hclose\" with \"[Hown]\") as \"_\";\n          [iNext;iExists _,_;iFrame;iPureIntro;eapply rtc_r;eauto;prim_step_from_exec|];\n          iExists (FailedV),_,_; iFrame;iModIntro.\n        iPureIntro. econstructor. eapply Store_fail_invalid_PC. eauto.\n      }\n\n     (* Success *)\n      clear Hstep. rewrite /update_mem /= in HH.\n      eapply (incrementPC_success_updatePC _ (<[a:=storev]> σm)) in Hregs'\n        as (p1 & g1 & b1 & e1 & a1 & a_pc1 & HPC'' & Hincr & HuPC & -> & ?).\n      eapply (updatePC_success_incl _ (<[a:=storev]> σm)) in HuPC. 2: by eauto.\n      rewrite HuPC in HH; clear HuPC; inversion HH; clear HH; subst c σ2. cbn.\n      iMod ((regspec_heap_update_inSepM _ _ _ PC) 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\n      iPureIntro. eapply Store_spec_success; eauto.\n        * split; auto. exact Hr'1. all: auto.\n        * unfold incrementPC. rewrite HPC'' Hincr. destruct p1; naive_solver.\n  Qed.\n\n  Lemma step_store_success_reg E K pc_p pc_g pc_b pc_e pc_a pc_a' w dst src w'\n         p g b e a w'' :\n      decodeInstrW w = Store dst (inr src) →\n     isCorrectPC (inr (pc_p,pc_g,pc_b,pc_e,pc_a)) →\n     (pc_a + 1)%a = Some pc_a' →\n     writeAllowed p = true ∧ withinBounds (p, g, b, e, a) = true →\n     canStore p a w'' = true ->\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              ∗ ▷ src ↣ᵣ w''\n              ∗ ▷ dst ↣ᵣ 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         ∗ pc_a ↣ₐ w\n         ∗ src ↣ᵣ w''\n         ∗ dst ↣ᵣ inr (p,g,b,e,a)\n         ∗ a ↣ₐ w''.\n  Proof.\n    iIntros (Hinstr Hvpc Hpca' [Hwa Hwb] Hcanstore Hnclose)\n            \"(Hown & Hj & >HPC & >Hi & >Hsrc & >Hdst & >Hsrca)\".\n    iDestruct (rules_binary_base.map_of_regs_3 with \"HPC Hsrc Hdst\") as \"[Hmap (%&%&%)]\".\n    iDestruct (spec_memMap_resource_2ne_apply with \"Hi Hsrca\") as \"[Hmem %]\"; auto.\n\n    iMod (step_store _ _ pc_p with \"[$Hown $Hj $Hmap $Hmem]\") as (retv regs' mem' Hspec) \"(Hj & Hmem & Hregs)\";\n      eauto; simplify_map_eq_alt; try rewrite lookup_insert; eauto.\n    { by rewrite !dom_insert; set_solver+. }\n    { eapply mem_neq_implies_allow_store_map with (a := a); eauto.\n      rewrite lookup_insert_ne// lookup_insert_ne// lookup_insert;eauto.\n      rewrite /word_of_argument. rewrite lookup_insert_ne// lookup_insert. eauto.\n    }\n\n    destruct Hspec.\n     { (* Success *)\n       destruct H7 as [Hrr2 _]. simpl in *. simplify_map_eq_alt. simplify_map_eq.\n       rewrite insert_commute // insert_insert.\n       iDestruct (rules_binary_base.memMap_resource_2ne with \"Hmem\") as \"[Hpc_a Ha]\";auto.\n       incrementPC_inv.\n       simplify_map_eq_alt.\n       rewrite insert_insert.\n       iDestruct (rules_binary_base.regs_of_map_3 with \"[$Hregs]\") as \"[HPC [Hsrc Hdst] ]\"; eauto. iFrame. done. }\n     { (* Failure (contradiction) *)\n       destruct X; simpl in *; simplify_map_eq_alt.\n       destruct o. all: try congruence.\n       incrementPC_inv;[|rewrite lookup_insert;eauto]. \n       destruct e0; try congruence. inv Hvpc; naive_solver.\n     }\n    Qed.\n\n  Lemma step_store_success_z E K pc_p pc_g pc_b pc_e pc_a pc_a' w dst z w'\n         p g b e a :\n     decodeInstrW w = Store dst (inl z) →\n     isCorrectPC (inr (pc_p,pc_g,pc_b,pc_e,pc_a)) →\n     (pc_a + 1)%a = Some pc_a' →\n     writeAllowed p = true ∧ withinBounds (p, g, b, e, a) = true →\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              ∗ ▷ dst ↣ᵣ 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         ∗ pc_a ↣ₐ w\n         ∗ dst ↣ᵣ inr (p,g,b,e,a)\n         ∗ a ↣ₐ inl z.\n  Proof.\n    iIntros (Hinstr Hvpc Hpca' [Hwa Hwb] Hnclose)\n            \"(Hown & Hj & >HPC & >Hi & >Hdst & >Hsrca)\".\n    iDestruct (rules_binary_base.map_of_regs_2 with \"HPC Hdst\") as \"[Hmap %]\".\n    iDestruct (spec_memMap_resource_2ne_apply with \"Hi Hsrca\") as \"[Hmem %]\"; auto.\n\n    iMod (step_store _ _ pc_p with \"[$Hown $Hj $Hmap $Hmem]\") as (retv regs' mem' Hspec) \"(Hj & Hmem & Hregs)\";\n      eauto; simplify_map_eq_alt; try rewrite lookup_insert; eauto.\n    { by rewrite !dom_insert; set_solver+. }\n    { eapply mem_neq_implies_allow_store_map with (a := a); eauto.\n      rewrite lookup_insert_ne// lookup_insert. eauto. }\n    \n    destruct Hspec. \n     { (* Success *)\n       iFrame. \n       destruct H5 as [Hrr2 _]. simplify_map_eq_alt.\n       rewrite insert_commute // insert_insert.\n       iDestruct (rules_binary_base.memMap_resource_2ne with \"Hmem\") as \"[Hpc_a Ha]\";auto.\n       incrementPC_inv. simpl in *. \n       simplify_map_eq_alt.\n       rewrite insert_insert.\n       iDestruct (rules_binary_base.regs_of_map_2 with \"[$Hregs]\") as \"[HPC Hdst]\"; eauto. by iFrame. }\n     { (* Failure (contradiction) *)\n       destruct X; simplify_map_eq_alt.\n       destruct o. all: try congruence. inversion e2. subst. rewrite /canStore in e3. congruence.\n       incrementPC_inv;[|rewrite lookup_insert;eauto].\n       destruct e0; try congruence. inv Hvpc; naive_solver.\n     }\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_Store.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2551992413172257}}
{"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.\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(*\nfunction terminator() public {\n        require(msg.pubkey() == tvm.pubkey() || msg.sender == address(this), Errors.IS_NOT_OWNER_OR_SELF_CALL);\n        require(!m_poolClosed, Errors.DEPOOL_IS_CLOSED);\n        m_poolClosed = true;\n        tvm.commit();\n        tvm.accept();\n\n        Round roundPre0 = getRoundPre0();\n        Round round0 = getRound0();\n        Round round1 = getRound1();\n\n        roundPre0 = startRoundCompleting(roundPre0, CompletionReason.PoolClosed);\n        round0 = startRoundCompleting(round0, CompletionReason.PoolClosed);\n        if (round1.step == RoundStep.WaitingValidatorRequest) {\n            round1 = startRoundCompleting(round1, CompletionReason.PoolClosed);\n        }\n        emit DePoolClosed();\n        setRoundPre0(roundPre0);\n        setRound0(round0);\n        setRound1(round1);\n    }\n*)\n\nLtac remDestructIf :=\n  match goal with\n    | |- ?x =>\n      match x with\n        | context [if ?b then _ else _] => case_eq b ; intros\n        | _ => idtac\n      end\n  end.\n\n  Lemma letIf: forall X Y (b: bool) (f g: X*Ledger) (h: X -> Ledger -> Y), \n(let (x, t) := if b then f else g in h x t)=\nif b then let (x, t) := f in h x t else\n          let (x, t) := g in h x t .\nProof.\n  intros.\n  destruct b; auto.\nQed.\n\nLemma matchIf: forall X (b: bool) (f g: LedgerT X) (l: Ledger), \n(match (if b then f else g) with | SimpleState c => c end l)=\nif b then match f with | SimpleState c => c end l else \nmatch g with | SimpleState c => c end l.\nProof.\n  intros.\n  destruct b; auto.\nQed.\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\nOpaque DePoolContract_Ф_startRoundCompleting roundStepEqb.\n\n\nDefinition DePoolContract_Ф_terminator_header f : LedgerT ( XErrorValue True XInteger ) := \n(*require(msg.pubkey() == tvm.pubkey() || msg.sender == address(this), Errors.IS_NOT_OWNER_OR_SELF_CALL);*)\t\nRequire2 {{ msg_pubkey () ?== tvm_pubkey () !| msg_sender () ?== tvm_address () , ↑7 D2!  Errors_ι_IS_NOT_OWNER_OR_SELF_CALL }} ; \n(*require(!m_poolClosed, Errors.DEPOOL_IS_CLOSED);*)\nRequire {{ !¬ ↑12 D2! DePoolContract_ι_m_poolClosed , ↑7 D2! Errors_ι_DEPOOL_IS_CLOSED }} ; \n(* m_poolClosed = true; *)\n(↑12 U1! DePoolContract_ι_m_poolClosed := $xBoolTrue) >>\n(* tvm.commit(); *)\ntvm_commit () >>\n(* tvm.accept(); *)\ntvm_accept () >>\n\n\n(* Round roundPre0 = getRoundPre0(); *)\nU0! Л_roundPre0 := RoundsBase_Ф_getRoundPre0 ();\n(* Round round0 = getRound0(); *)\nU0! Л_round0 := RoundsBase_Ф_getRound0 ();\n(*Round round1 = getRound1();*)\n(↑↑17 U2! LocalState_ι_terminator_Л_round1 := RoundsBase_Ф_getRound1 () ) >>\n\n(* roundPre0 = startRoundCompleting(roundPre0, CompletionReason.PoolClosed); *)\nU0! Л_roundPre0 := DePoolContract_Ф_startRoundCompleting  (! $ Л_roundPre0 , \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t$ RoundsBase_ι_CompletionReasonP_ι_PoolClosed !) ;\n(*round0 = startRoundCompleting(round0, CompletionReason.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 (round1.step == RoundStep.WaitingValidatorRequest) {\n\tround1 = startRoundCompleting(round1, CompletionReason.PoolClosed);\n} *)\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}) >> f Л_roundPre0 Л_round0.\n\n\nDefinition DePoolContract_Ф_terminator_tailer Л_roundPre0 Л_round0 : LedgerT True := \n(* emit DePoolClosed(); *)\n->emit $ DePoolClosed >>\n(* setRoundPre0(roundPre0); *)\n(RoundsBase_Ф_setRoundPre0 (! $ Л_roundPre0 !) ) >>\n(*  setRound0(round0);  *)\n(RoundsBase_Ф_setRound0 (! $ Л_round0 !)  ) >>\n(* setRound1(round1); *)\n(RoundsBase_Ф_setRound1 (! ↑17 D2! LocalState_ι_terminator_Л_round1 !) ) .\n\n\nLemma DePoolContract_Ф_terminator_eval : forall (l : Ledger),\neval_state DePoolContract_Ф_terminator l =\n\nlet isOwner := eval_state msg_pubkey l =? eval_state tvm_pubkey l in\nlet isSelfCall := eval_state msg_sender l =? eval_state tvm_address l in\nlet isNotClosed := negb (eval_state (↑12 ε DePoolContract_ι_m_poolClosed) l) in\n\nlet closedDePool := {$ l With (DePoolContract_ι_m_poolClosed, true) $} in\n                                       \nif (isOwner || isSelfCall)%bool then \n    if isNotClosed then Value I\n                   else Error  (eval_state ( ↑7 ε Errors_ι_DEPOOL_IS_CLOSED) l) else Error (eval_state ( ↑7 ε Errors_ι_IS_NOT_OWNER_OR_SELF_CALL) l).\nProof.     \n  intros. destruct l. compute.\n\n  repeat remDestructIf; auto.              \n\n  match goal with \n  | |- ?x  => match x with \n              | context [DePoolContract_Ф_startRoundCompleting ?a ?b] => remember (DePoolContract_Ф_startRoundCompleting a b)\n              end\n  end. idtac.\n  \n  destruct l. idtac.\n  \n  match goal with \n  | |- ?x  => match x with \n              | context [p ?a] => remember (p a)\n              end\n  end. idtac.\n  \n  destruct p0. auto. idtac.\n\n  match goal with \n  | |- ?x  => match x with \n              | context [DePoolContract_Ф_startRoundCompleting ?a ?b] => remember (DePoolContract_Ф_startRoundCompleting a b)\n              end\n  end. idtac.\n  \n  destruct l0. idtac.\n  \n  match goal with \n  | |- ?x  => match x with \n              | context [p0 ?a] => remember (p0 a)\n              end\n  end. idtac.\n  \n  destruct p1. auto. idtac.\n\n  match goal with\n  | |- ?x =>\n    match x with\n      | context [if ?b then _ else _] => remember b\n      | _ => idtac\n    end\n  end.\n  symmetry. idtac.\n\n  destruct x; auto.\nQed. \n\n\nLemma DePoolContract_Ф_terminator_header_exec : forall f (l : Ledger),\nexec_state (DePoolContract_Ф_terminator_header f) l =\n\nlet isOwner := eval_state msg_pubkey l =? eval_state tvm_pubkey l in\nlet isSelfCall := eval_state msg_sender l =? eval_state tvm_address 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\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) commited 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 (f srcPre0 src0) {$ l_1 With (LocalState_ι_terminator_Л_round1, src1) $} in                                        \nif (isOwner || isSelfCall)%bool then \n    if isNotClosed then l'\n                   else l else l.\n\nProof.\n    intros. destruct l. compute.\n\n    repeat remDestructIf; auto.\n\nmatch goal with \n| |- ?x  => match x with \n            | context [DePoolContract_Ф_startRoundCompleting ?a ?b] => remember (DePoolContract_Ф_startRoundCompleting a b)\n            end\nend. idtac.\n\ndestruct l. idtac.\n\nmatch goal with \n| |- ?x  => match x with \n            | context [p ?a] => remember (p a)\n            end\nend.\n\ndestruct p0. auto.\n\nmatch goal with \n| |- ?x  => match x with \n            | context [DePoolContract_Ф_startRoundCompleting ?a ?b] => remember (DePoolContract_Ф_startRoundCompleting a b)\n            end\nend. idtac.\n\ndestruct l0. idtac.\n\nmatch goal with \n| |- ?x  => match x with \n            | context [p0 ?a] => remember (p0 a)\n            end\nend.\n\ndestruct p1. auto.\n\nTransparent roundStepEqb.\nmatch goal with\n| |- ?x =>\n  match x with\n    | context [if ?b then _ else _] => remember b\n    | _ => idtac\n  end\nend.\nrewrite H1. idtac.\n\n\nmatch goal with \n| |- ?x  => match x with \n            | context [DePoolContract_Ф_startRoundCompleting ?a ?b] => remember (DePoolContract_Ф_startRoundCompleting a b)\n            end\nend. idtac.\n\nsymmetry. idtac.\n\ndestruct l1. idtac.\n\nmatch goal with \n| |- ?x  => match x with \n            | context [p1 ?a] => remember (p1 a)\n            end\nend.\n\ndestruct p2. auto. idtac.\n\nmatch goal with \n| |- ?x  => match x with \n            | context [f ?a ?b] => remember (f a b)\n            end\nend. idtac.\n\ndestruct s. auto. idtac.\n\nmatch goal with \n| |- ?x  => match x with \n            | context [p2 ?a] => remember (p2 a)\n            end\nend. idtac.\n\n\ndestruct p3. auto.\n\n\n\nmatch goal with \n| |- ?x  => match x with \n            | context [DePoolContract_Ф_startRoundCompleting ?a ?b] => remember (DePoolContract_Ф_startRoundCompleting a b)\n            end\nend. idtac.\n\nsymmetry. idtac.\n\ndestruct l. idtac.\n\nmatch goal with \n| |- ?x  => match x with \n            | context [p ?a] => remember (p a)\n            end\nend. idtac.\n\ndestruct p0. auto. idtac.\n\n\nmatch goal with \n| |- ?x  => match x with \n            | context [DePoolContract_Ф_startRoundCompleting ?a ?b] => remember (DePoolContract_Ф_startRoundCompleting a b)\n            end\nend. idtac.\n\ndestruct l0. idtac.\n\nmatch goal with \n| |- ?x  => match x with \n            | context [p0 ?a] => remember (p0 a)\n            end\nend. idtac.\n\ndestruct p1. auto. idtac.\n\nsymmetry. idtac.\n\nrewrite matchIf. idtac.\nrepeat rewrite letIf. idtac.\n\nrewrite H1. idtac.\n\n\nmatch goal with \n| |- ?x  => match x with \n            | context [f ?a ?b] => remember (f a b)\n            end\nend. idtac.\n\ndestruct s. auto. idtac.\n\nmatch goal with \n| |- ?x  => match x with \n            | context [p1 ?a] => remember (p1 a)\n            end\nend. idtac.\n\n\ndestruct p2. auto.\n\nQed.\n\n(* Definition DePoolContract_Ф_terminator_tailer Л_roundPre0 Л_round0 : LedgerT True := \n(* emit DePoolClosed(); *)\n->emit $ DePoolClosed >>\n(* setRoundPre0(roundPre0); *)\n(RoundsBase_Ф_setRoundPre0 (! $ Л_roundPre0 !) ) >>\n(*  setRound0(round0);  *)\n(RoundsBase_Ф_setRound0 (! $ Л_round0 !)  ) >>\n(* setRound1(round1); *)\n(RoundsBase_Ф_setRound1 (! ↑17 D2! LocalState_ι_terminator_Л_round1 !) ) . *)\n\nLemma DePoolContract_Ф_terminator_tailer_exec : forall Л_roundPre0 Л_round0 (l : Ledger),\nexec_state (DePoolContract_Ф_terminator_tailer Л_roundPre0 Л_round0) l =\n\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\nl_set1.\n\nProof.\n  intros. destruct l. compute. auto.\nQed.\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/DePoolContract_terminator.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878414043816, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2551992354623039}}
{"text": "Require Import Coq.omega.Omega.\nRequire Import Platform.AutoSep Platform.Wrap Platform.StringOps Platform.Malloc Platform.ArrayOps Platform.Buffers Platform.Bags.\nRequire Import Platform.SinglyLinkedList Platform.Buffers Platform.NumOps Platform.RelDb Platform.RelDbCondition.\n\nSet Implicit Arguments.\n\nLocal Hint Extern 1 (@eq W _ _) => words.\n\n\n(** * Iterating over matching rows of a table *)\n\nLocal Infix \";;\" := SimpleSeq : SP_scope.\nOpaque mult.\n\nSection CompileEqualities.\n  Variable A : Type.\n  Variable invPre : A -> vals -> HProp.\n  Variable invPost : A -> vals -> W -> HProp.\n  Variable tptr : W.\n  Variable sch : schema.\n  Variable data : string.\n  Variable cond : condition.\n\n  Notation EqVcs := (fun im ns res =>\n    (~In \"rp\" ns)\n    :: incl baseVars ns\n    :: (res >= 10)%nat\n    :: wfEqualities ns sch cond\n    :: (forall a V V',\n        (forall x, x <> \"ibuf\" ->\n          x <> \"ilen\" ->\n          x <> \"tmp\" ->\n          x <> \"ipos\" ->\n          x <> \"overflowed\" -> x <> \"matched\" -> sel V x = sel V' x) ->\n        invPre a V ===> invPre a V')\n    :: (forall a V V' R,\n        (forall x, x <> \"ibuf\" ->\n          x <> \"ilen\" ->\n          x <> \"tmp\" ->\n          x <> \"ipos\" ->\n          x <> \"overflowed\" -> x <> \"matched\" -> sel V x = sel V' x) ->\n        invPost a V R = invPost a V' R)\n    :: (\"matched\" <> data)%type\n    :: (labl \"array8\" \"equal\") ~~ im ~~> (equalS)\n    :: (data <> \"rp\")%type\n    :: (data <> \"ibuf\")%type\n    :: (data <> \"ipos\")%type\n    :: (data <> \"ilen\")%type\n    :: (data <> \"tmp\")%type\n    :: In data ns\n    :: goodSize (Datatypes.length sch)\n    :: nil).\n\n  Hint Immediate incl_refl.\n\n  Definition CompileEqualities : chunk.\n    refine (WrapC\n      (compileEqualities invPre invPost sch data cond cond)\n      (eqinv' invPre invPost sch data cond)\n      (eqinv' invPre invPost sch data cond)\n      EqVcs\n      _ _); [ abstract (intros;\n        repeat match goal with\n                 | [ H : vcs (_ :: _) |- _ ] => inversion_clear H; subst\n               end; eapply compileEqualities_post; try eassumption)\n        | abstract (intros;\n          repeat match goal with\n                   | [ H : vcs (_ :: _) |- _ ] => inversion_clear H; subst\n                 end; eapply compileEqualities_vcs; try eassumption; eauto) ].\n  Defined.\nEnd CompileEqualities.\n\nSection Delete.\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\n  (* Store a pointer to the current linked list node and actual row data, respectively,\n   * in these variables. *)\n  Variables rw data : string.\n\n  (* Test to use in filtering rows *)\n  Variable cond : condition.\n\n  Definition Delete' : chunk := (\n    rw <-* tptr;;\n    \"res\" <- 0;;\n\n    [Al bs, Al a : A, Al done, Al remaining, Al head,\n      PRE[V] array8 bs (V \"buf\") * [| length bs = wordToNat (V \"len\") |] * [| inputOk V (exps cond) |]\n        * tptr =*> head * sll done (V \"res\") * sll remaining (V rw)\n        * rows sch head done * rows sch head remaining * invPre a V * mallocHeap 0\n      POST[R] array8 bs (V \"buf\") * invPost a V R]\n    While (rw <> 0) {\n      data <-* rw;;\n\n      Assert [Al bs, Al a : A, Al done, Al remaining, Al head,\n        PRE[V] array8 bs (V \"buf\") * [| length bs = wordToNat (V \"len\") |] * [| inputOk V (exps cond) |]\n          * [| V rw <> 0 |] * tptr =*> head * sll done (V \"res\") * sll (V data :: remaining) (V rw)\n          * rows sch head remaining * rows sch head done * row sch (V data) * invPre a V * mallocHeap 0\n        POST[R] array8 bs (V \"buf\") * invPost a V R];;\n\n      CompileEqualities\n      (fun a V => invPre a V\n        * Ex head, Ex done, Ex remaining,\n          [| V rw <> 0 |] * tptr =*> head * sll done (V \"res\") * sll (V data :: remaining) (V rw)\n          * rows sch head remaining * rows sch head done * mallocHeap 0)%Sep\n      invPost\n      sch data cond;;\n\n      If (\"matched\" = 0) {\n        (* No match.  This row survives. *)\n        \"matched\" <- rw;;\n        \"tmp\" <-* \"matched\" + 4;;\n        \"matched\" + 4 *<- \"res\";;\n        \"res\" <- \"matched\";;\n        rw <- \"tmp\"\n      } else {\n        (* Match.  Delete this row. *)\n        \"tmp\" <- rw;;\n        rw <-* \"tmp\" + 4;;\n        Call \"malloc\"!\"free\"(0, \"tmp\", 2)\n        [Al bs, Al a : A, Al done, Al remaining, Al head,\n          PRE[V] array8 bs (V \"buf\") * [| length bs = wordToNat (V \"len\") |] * [| inputOk V (exps cond) |]\n            * tptr =*> head * sll done (V \"res\") * sll remaining (V rw)\n            * rows sch head remaining * rows sch head done * row sch (V data) * invPre a V * mallocHeap 0\n          POST[R] array8 bs (V \"buf\") * invPost a V R];;\n\n        \"matched\" <- data;;\n        \"tmp\" <-* \"matched\";;\n        \"matched\" <-* \"matched\"+4;;\n\n        \"matched\" <-- Call \"numops\"!\"div4\"(\"matched\")\n        [Al bs, Al a : A, Al done, Al remaining, Al head,\n          PRE[V, R'] array8 bs (V \"buf\") * [| length bs = wordToNat (V \"len\") |] * [| inputOk V (exps cond) |]\n            * tptr =*> head * sll done (V \"res\") * sll remaining (V rw)\n            * rows sch head remaining * rows sch head done * invPre a V * mallocHeap 0\n            * Ex cols, Ex rbs,\n            (V data ==*> V \"tmp\", R' ^* $4)\n            * array (posl cols) (V data ^+ $8) * array (lenl cols) (V data ^+ $8 ^+ $ (length sch * 4))\n            * array8 rbs (V \"tmp\")\n            * [| length rbs = wordToNat R' * 4 |]%nat\n            * [| length cols = length sch |] * [| inBounds (wordToNat R' * 4) cols |]%nat\n            * [| V data <> 0 |] * [| freeable (V data) (2 + length sch + length sch) |]\n            * [| V \"tmp\" <> 0 |] * [| freeable (V \"tmp\") (wordToNat R') |]\n          POST[R] array8 bs (V \"buf\") * invPost a V R];;\n\n        Call \"buffers\"!\"bfree\"(\"tmp\", \"matched\")\n        [Al bs, Al a : A, Al done, Al remaining, Al head,\n          PRE[V] array8 bs (V \"buf\") * [| length bs = wordToNat (V \"len\") |] * [| inputOk V (exps cond) |]\n            * tptr =*> head * sll done (V \"res\") * sll remaining (V rw)\n            * rows sch head remaining * rows sch head done * invPre a V * mallocHeap 0\n            * Ex cols,\n            (V data ==*> V \"tmp\", V \"matched\" ^* $4)\n            * array (posl cols) (V data ^+ $8) * array (lenl cols) (V data ^+ $8 ^+ $ (length sch * 4))\n            * [| length cols = length sch |] * [| inBounds (wordToNat (V \"matched\") * 4) cols |]%nat\n            * [| V data <> 0 |] * [| freeable (V data) (2 + length sch + length sch) |]\n          POST[R] array8 bs (V \"buf\") * invPost a V R];;\n\n        Call \"malloc\"!\"free\"(0, data, (2 + length sch + length sch)%nat)\n        [Al bs, Al a : A, Al done, Al remaining, Al head,\n          PRE[V] array8 bs (V \"buf\") * [| length bs = wordToNat (V \"len\") |] * [| inputOk V (exps cond) |]\n            * tptr =*> head * sll done (V \"res\") * sll remaining (V rw)\n            * rows sch head remaining * rows sch head done * invPre a V * mallocHeap 0\n          POST[R] array8 bs (V \"buf\") * invPost a V R]\n      }\n    };;\n\n    tptr *<- \"res\"\n  )%SP.\n\n  (* This is a clone of the normal 'platform' VC simplifier, but without the [delta]\n   * rules for label map operations, which we can't resolve concretely when the imports\n   * are a variable. *)\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 labl 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 CompileEqualities SimpleSeq].\n\n  Definition dinvar :=\n    Al bs, Al a : A,\n    PRE[V] array8 bs (V \"buf\") * [| length bs = wordToNat (V \"len\") |] * [| inputOk V (exps cond) |]\n      * table sch tptr * mallocHeap 0 * invPre a V\n    POST[R] array8 bs (V \"buf\") * invPost a V R.\n\n  Notation svars := (rw :: data :: nil).\n\n  Definition noOverlapExp (e : exp) :=\n    match e with\n      | Const _ => True\n      | Input pos len => pos <> rw /\\ pos <> data /\\ len <> rw /\\ len <> data\n        /\\ pos <> \"res\" /\\ len <> \"res\"\n    end.\n\n  Definition noOverlapExps := List.Forall noOverlapExp.\n\n  Notation DeleteVcs := (fun im ns res =>\n    (~In \"rp\" ns) :: incl svars ns :: (rw <> \"rp\")%type :: (data <> \"rp\")%type\n    :: incl baseVars ns :: In \"res\" ns\n    :: (rw <> data)%type\n    :: (forall a V V', (forall x, x <> rw -> x <> data\n      -> x <> \"ibuf\" -> x <> \"ilen\" -> x <> \"tmp\"\n      -> x <> \"ipos\" -> x <> \"overflowed\" -> x <> \"matched\"\n      -> x <> \"res\" -> sel V x = sel V' x)\n      -> invPre a V ===> invPre a V')\n    :: (forall a V V' R, (forall x, x <> rw -> x <> data\n      -> x <> \"ibuf\" -> x <> \"ilen\" -> x <> \"tmp\"\n      -> x <> \"ipos\" -> x <> \"overflowed\" -> x <> \"matched\"\n      -> x <> \"res\" -> sel V x = sel V' x)\n      -> invPost a V R = invPost a V' R)\n    :: \"array8\"!\"equal\" ~~ im ~~> ArrayOps.equalS\n    :: \"numops\"!\"div4\" ~~ im ~~> div4S\n    :: \"malloc\"!\"free\" ~~ im ~~> freeS\n    :: \"buffers\"!\"bfree\" ~~ im ~~> bfreeS\n    :: (res >= 10)%nat\n    :: wfEqualities ns sch cond\n    :: (\"matched\" <> rw)%type\n    :: (\"matched\" <> data)%type\n    :: (data <> \"ibuf\")%type\n    :: (data <> \"overflowed\")%type\n    :: (data <> \"ipos\")%type\n    :: (data <> \"ilen\")%type\n    :: (data <> \"tmp\")%type\n    :: (data <> \"len\")%type\n    :: (data <> \"buf\")%type\n    :: (data <> \"res\")%type\n    :: In data ns\n    :: (rw <> \"rp\")%type\n    :: (rw <> \"ibuf\")%type\n    :: (rw <> \"ipos\")%type\n    :: (rw <> \"ilen\")%type\n    :: (rw <> \"tmp\")%type\n    :: (rw <> \"len\")%type\n    :: (rw <> \"buf\")%type\n    :: (rw <> \"overflowed\")%type\n    :: (rw <> \"res\")%type\n    :: goodSize (length sch)\n    :: goodSize (2 + length sch + length sch)\n    :: noOverlapExps (exps cond)\n    :: nil).\n\n  Hint Immediate incl_refl.\n\n  Theorem Forall_impl3 : forall A (P Q R S : A -> Prop) ls,\n    List.Forall P ls\n    -> List.Forall Q ls\n    -> List.Forall R ls\n    -> (forall x : A, P x -> Q x -> R x -> S x)\n    -> List.Forall S ls.\n    induction 1; inversion 1; inversion 1; auto.\n  Qed.\n\n  Theorem inputOk_weaken_params : forall ns V V' es,\n    inputOk V es\n    -> noOverlapExps es\n    -> wfExps ns es\n    -> (forall x, x <> rw -> x <> data -> sel V x = sel V' x)\n    -> rw <> \"len\"\n    -> data <> \"len\"\n    -> inputOk V' es.\n    intros; eapply Forall_impl3; [ apply H | apply H0 | apply H1 | ].\n    intro e; destruct e; simpl; intuition idtac.\n    repeat rewrite <- H2 by (simpl; congruence); assumption.\n  Qed.\n\n  Hint Extern 2 (inputOk _ _) => eapply inputOk_weaken_params; try eassumption;\n    try (eapply wfEqualities_wfExps; eassumption); [ descend ].\n\n  Lemma finish_rows : forall P sch head ls head',\n    P * (rows sch head ls * rows sch head nil) ===> P * rows sch head' ls.\n    sepLemma.\n  Qed.\n\n  Hint Extern 1 (himp _ _ _) => apply finish_rows.\n\n  Lemma inputOk_weaken_delete : forall V V' es ns,\n    inputOk V es\n    -> wfExps ns es\n    -> noOverlapExps es\n    -> (forall x, x <> rw -> x <> \"res\" -> x <> \"matched\" -> x <> \"tmp\" -> sel V x = sel V' x)\n    -> rw <> \"len\"\n    -> inputOk V' es.\n    induction 1; do 2 inversion_clear 1; subst; simpl; intuition; constructor; auto.\n    destruct x; simpl in *; intuition idtac.\n    repeat rewrite <- H1 by congruence; assumption.\n  Qed.\n\n  Hint Extern 1 (inputOk _ _) => eapply inputOk_weaken_delete; try eassumption;\n    [ solve [ eauto 1 ] | solve [ descend ] ].\n\n  Lemma four_shimmy : forall a b c,\n    c = a\n    -> c = 4 * b\n    -> a = b * 4.\n    intros; omega.\n  Qed.\n\n  Hint Immediate four_shimmy.\n\n  Lemma derows : forall P Q P' sch head,\n    P ===> P'\n    -> P * Q ===> Q * (P' * rows sch head nil).\n    sepLemma.\n  Qed.\n\n  Lemma row_free' : forall p n m,\n    (p ^+ natToW 8) =?> n * (p ^+ natToW 8 ^+ natToW (n * 4)) =?> m\n    ===> allocated p 8 (n + m).\n    sepLemma.\n    eapply Himp_trans; [ | apply allocated_join ].\n    apply Himp_star_frame; apply allocated_shift_base; eauto.\n    words.\n    rewrite natToW_plus.\n    Require Import Coq.Arith.Arith.\n    rewrite (mult_comm 4).\n    rewrite natToW_times4.\n    rewrite natToW_times4.\n    rewrite plus_0_r.\n    words.\n    omega.\n    omega.\n  Qed.\n\n  Lemma row_free : forall p n m,\n    (Ex ls1, Ex ls2, array ls1 (p ^+ natToW 8) * [| length ls1 = n |]\n      * array ls2 (p ^+ natToW 8 ^+ natToW (n * 4)) * [| length ls2 = m |])\n    ===> allocated p 8 (n + m).\n    intros; eapply Himp_trans; [ | apply row_free' ].\n    sepLemma; apply Himp_star_frame;\n      (eapply Himp_trans; [ | apply MoreArrays.free_array' ]; sepLemma).\n  Qed.\n\n  Lemma rhints : TacPackage.\n    prepare tt row_free.\n  Defined.\n\n  Hint Rewrite length_posl length_lenl : sepFormula.\n\n  Hint Extern 1 (@eq nat _ _) => omega.\n\n  Lemma inBounds_times4 : forall m w ls r,\n    inBounds w ls\n    -> m = wordToNat w\n    -> m = 4 * r\n    -> inBounds (natToW (r * 4)) ls.\n    intros; subst.\n    rewrite mult_comm in H1.\n    apply (f_equal natToW) in H1.\n    rewrite natToW_wordToNat in *; subst.\n    auto.\n  Qed.\n\n  Hint Immediate inBounds_times4.\n\n  Lemma div4_out : forall n w r,\n    n = wordToNat w\n    -> n = 4 * wordToNat r\n    -> w = r ^* natToW 4.\n    intros; subst.\n    match goal with\n      | [ |- ?x = ?y ] => assert (wordToNat x = wordToNat y)\n    end.\n    rewrite H0.\n    rewrite wordToNat_wmult.\n    apply mult_comm.\n    apply goodSize_weaken with (wordToNat w).\n    eauto.\n    change (wordToNat (natToW 4)) with 4.\n    omega.\n    apply (f_equal natToW) in H.\n    repeat rewrite natToW_wordToNat in H; assumption.\n  Qed.\n\n  Hint Immediate div4_out.\n\n  Theorem Delete_post : forall im mn (H : importsGlobal im) ns res pre specs st,\n    (forall (specs0 : codeSpec W (settings * state)) (st0 : settings * state),\n      interp specs0 (pre st0)\n      -> interp specs0 (dinvar true (fun x : W => x) ns res st0))\n    -> vcs (DeleteVcs im ns res)\n    -> interp specs (Postcondition (toCmd Delete' mn H ns res pre) st)\n    -> interp specs (dinvar true (fun x : W => x) ns res st).\n    simpl; wrap0; t.\n  Qed.\n\n  Theorem Delete_vcs : forall im mn (H : importsGlobal im) ns res pre,\n    (forall (specs : codeSpec W (settings * state)) (st : settings * state),\n      interp specs (pre st)\n      -> interp specs (dinvar true (fun x : W => x) ns res st))\n    -> vcs (DeleteVcs im ns res)\n    -> vcs (VerifCond (toCmd Delete' mn H ns res pre)).\n    intros.\n    cbv beta in H1.\n    repeat match goal with\n             | [ H : vcs (_ :: _) |- _ ] => inversion H; clear H; subst\n             | [ H : vcs nil |- _ ] => clear H\n           end.\n    unfold Delete'; vcgen_simp.\n    match goal with\n      | |- vcs ?Ps => apply (vcsImp_correct Ps)\n    end; fold (@length B); fold (@length string); fold (@length (W * W)); intros; auto 1.\n\n    v.\n    v.\n\n    pre.\n    prep.\n    evalu.\n    my_descend.\n    my_step.\n    apply derows.\n    weaken_invPre'.\n    my_descend; my_step.\n    repeat (my_descend; my_step).\n\n    v.\n\n    pre.\n\n    prep.\n    evalu.\n    do 2 eexists; eexists (_ :: _).\n    my_descend; repeat (my_descend; my_step).\n\n    t.\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\n    unfold labl in *.\n    pre; prep; evalu; my_descend.\n    my_descend; repeat (my_step; my_descend).\n    my_descend; repeat (my_step; my_descend).\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n\n    v.\n    v.\n    v.\n    v.\n    v.\n\n    unfold labl in *.\n    pre.\n    prep.\n    evalu.\n    match goal with\n      | [ H : freeable8 _ _ |- _ ] => destruct H; intuition idtac\n    end.\n    my_descend.\n    my_step.\n    eauto.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    auto.\n    eauto.\n    my_descend; my_step.\n    replace (Regs x18 Rv ^* natToW 4) with x15.\n    my_descend; my_step.\n    my_descend; my_step.\n    eauto.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n\n    v.\n    v.\n\n    unfold labl in *.\n    pre; prep; evalu; my_descend.\n    my_step.\n    eauto.\n    my_step.\n    my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n\n    v.\n    v.\n\n    unfold labl in *.\n    pre.\n    prep.\n    evalu.\n    my_descend.\n    my_step.\n    auto.\n    descend; step rhints.\n    auto.\n    auto.\n    my_step.\n    my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n    my_descend; my_step.\n\n    v.\n    v.\n  Qed.\n\n  Hint Immediate Delete_post Delete_vcs.\n\n  Definition Delete : chunk.\n    refine (WrapC Delete'\n      dinvar\n      dinvar\n      DeleteVcs\n      _ _); abstract eauto.\n  Defined.\nEnd Delete.\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/RelDbDelete.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.37022539954425293, "lm_q1q2_score": 0.2551984473824894}}
{"text": "(* The concrete machine is deterministic. *)\n\nRequire Import Relations.\nRequire Import EqNat.\nRequire Import ZArith.\nRequire Import List.\nRequire Import Utils.\n\nRequire Import Instr Memory.\n\nRequire Import Concrete ConcreteMachine ConcreteExecutions.\n\nSet Implicit Arguments.\nLocal Open Scope Z_scope.\n\nSection Determinism.\n\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 cache_hit_read_mem_determ: forall cblock m rl1 rpcl1 rl2 rpcl2,\n  cache_hit_read_mem cblock m rl1 rpcl1 ->\n  cache_hit_read_mem cblock m rl2 rpcl2 ->\n  rl1 = rl2 /\\ rpcl1 = rpcl2.\nProof.\n  unfold cache_hit_read_mem; intros.\n  destruct Mem.get_frame.\n  + eapply cache_hit_read_determ; eauto.\n  + intuition.\nQed.\n\nLemma c_pop_to_return_determ : forall s s1,\n  c_pop_to_return s s1 -> forall s2,\n  c_pop_to_return s s2 -> s1 = s2.\nProof.\n  induction 1; intros s2 H2; inv H2; auto; congruence.\nQed.\n\nLemma cmach_determ:\n  forall cblock t s e s' e' s''\n         (STEP1: cstep cblock t s e s')\n         (STEP2: cstep cblock t s e' s''),\n    s' = s'' /\\ e = e'.\nProof.\n  intros.\n  destruct STEP1;\n  rewrite CS1 in *; rewrite CA in *; rewrite CS2 in *;\n  clear CS1 CA CS2; destruct STEP2; try discriminate;\n  match goal with\n    | H1 : read_m _ _ = Some ?instr1,\n      H2 : read_m _ _ = Some ?instr2 |- _ =>\n      match constr:((instr1, instr2)) with\n        | (?instr, ?instr) => idtac\n        | _ =>\n          assert (H : instr1 = instr2) by congruence; try discriminate;\n          inversion H\n      end\n  end;\n  inv CS1;\n  try (match goal with\n    | [H1 : cache_hit_read_mem ?cb ?m ?rl _,\n       H2 : cache_hit_read_mem ?cb ?m ?rl0 _ |- _ ] =>\n  (exploit (@cache_hit_read_mem_determ cb m rl); eauto; intros [Heq Heq'])\n  end);\n  try match goal with\n        | [H1: c_pop_to_return ?s ?s1,\n           H2: c_pop_to_return ?s ?s2 |- _ ] =>\n          let EQ := fresh in\n          assert (EQ:=@c_pop_to_return_determ _ _ POP _ POP0); inv EQ\n      end;\n  try match goal with\n        | [H1: ~ ?P, H2: ?P |- _] => elim H1; exact H2\n      end;\n  subst; split; try congruence.\n\n  - (* Call user *)\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    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  - (* SysCall *)\n    assert (sys_info0 = sys_info) by congruence. subst.\n    assert (args0 = args /\\ s0 = s1).\n    { assert (LENGTHS : length args0 = length args) by congruence.\n      clear - LENGTHS H5.\n      gdep args0.\n      induction args as [|arg args IH]; intros; destruct args0; simpl in *; inv LENGTHS; auto.\n      inv H5.\n      exploit IH; eauto.\n      intros. intuition. subst. reflexivity. }\n    intuition. subst. reflexivity.\nQed.\n\nLemma runsUntilUser_determ :\n  forall cblock t s1 s21 s22\n         (RUN1 : runsUntilUser cblock t s1 s21)\n         (RUN2 : runsUntilUser cblock t s1 s22),\n    s21 = s22.\nProof.\n  intros.\n  induction RUN1; inv RUN2;\n  try match goal with\n        | [ H1 : cstep _ _ ?s _ _,\n            H2 : cstep _ _ ?s _ _\n            |- _ ] =>\n          let H := fresh \"H\" in\n          generalize (cmach_determ H1 H2);\n          intros [? ?]; subst\n      end; eauto;\n  try match goal with\n        | [ H : runsUntilUser _ _ _ _ |- _ ] =>\n          generalize (runsUntilUser_l H);\n          intros\n      end;\n  congruence.\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/extended_machines/Determinism.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.255163998861049}}
{"text": "Require Import Logic.lib.Ensembles_ext.\nRequire Import Logic.lib.Bisimulation.\nRequire Import Logic.GeneralLogic.Base.\nRequire Import Logic.MinimumLogic.Syntax.\nRequire Import Logic.PropositionalLogic.Syntax.\nRequire Import Logic.ModalLogic.Syntax.\nRequire Import Logic.MinimumLogic.ProofTheory.Minimum.\nRequire Import Logic.PropositionalLogic.ProofTheory.Intuitionistic.\nRequire Import Logic.ModalLogic.ProofTheory.ModalLogic.\nRequire Import Logic.Extensions.ProofTheory.Stable.\nRequire Import Logic.GeneralLogic.KripkeModel.\nRequire Import Logic.ModalLogic.Model.KripkeModel.\nRequire Import Logic.ModalLogic.Model.OrderedKripkeModel.\nRequire Import Logic.SeparationLogic.Model.SeparationAlgebra.\nRequire Import Logic.SeparationLogic.Model.OrderedSA.\nRequire Import Logic.Extensions.Semantics.SemanticStable.\nRequire Import Logic.ModalLogic.Semantics.Flat.\nRequire Import Logic.SeparationLogic.Semantics.FlatSemantics.\nRequire Import Logic.Extensions.Sound.StableSound.\nRequire Import Logic.GeneralLogic.ShallowEmbedded.MonoPredicateAsLang.\nRequire Import Logic.PropositionalLogic.ShallowEmbedded.MonoPredicatePropositionalLogic.\nRequire Import Logic.ModalLogic.ShallowEmbedded.MonoPredicateModalLogic.\nRequire Import Logic.SeparationLogic.ShallowEmbedded.MonoPredicateSeparationLogic.\n\nDefinition MonoPred_stable (A: Type) {R1: KI.Relation A} {po_R1: PreOrder KI.Krelation} {R2: SS.Relation A}: expr -> Prop := fun x => Semantics.stable (@Kdenotation _ (Build_Model A) (unit_kMD _) tt _ x).\n\nInstance MonoPred_stableSM (A: Type) {R1: KI.Relation A} {po_R1: PreOrder KI.Krelation} {R2: SS.Relation A}: @SemanticStable (MonoPred_L A) (Build_Model A) (unit_kMD _) tt R2 (MonoPred_SM A).\nProof.\n  refine (Build_SemanticStable _ _ _ _ _ _ (MonoPred_stable A) _).\n  intros. reflexivity.\nDefined.\n\nInstance MonoPred_pstable (A: Type) {R1: KI.Relation A} {po_R1: PreOrder KI.Krelation} {R2: SS.Relation A} {R1_bis: Bisimulation SS.Krelation KI.Krelation}: PropositionalStable (MonoPred_L A) (MonoPred_Gamma A) (MonoPred_stable A).\nProof.\n  constructor.\n  + intros x y.\n    exact (@Sound_KripkeIntuitionistic.sound_impp_stable (MonoPred_L A) _ _ (Build_Model A) (unit_kMD _) tt R1 _ _ (MonoPred_SM A) (MonoPred_kiSM A) (MonoPred_kminSM A) (MonoPred_kpSM A) (MonoPred_stableSM A) x y).\n  + intros x y.\n    exact (@Sound_KripkeIntuitionistic.sound_andp_stable (MonoPred_L A) _ _ (Build_Model A) (unit_kMD _) tt R1 _ (MonoPred_SM A) (MonoPred_kiSM A) (MonoPred_kminSM A) (MonoPred_kpSM A) (MonoPred_stableSM A) x y).\n  + intros x y.\n    exact (@Sound_KripkeIntuitionistic.sound_orp_stable (MonoPred_L A) _ _ (Build_Model A) (unit_kMD _) tt R1 _ (MonoPred_SM A) (MonoPred_kiSM A) (MonoPred_kminSM A) (MonoPred_kpSM A) (MonoPred_stableSM A) x y).\n  + exact (@Sound_KripkeIntuitionistic.sound_falsep_stable (MonoPred_L A) _ _ (Build_Model A) (unit_kMD _) tt R1 _ (MonoPred_SM A) (MonoPred_kiSM A) (MonoPred_kminSM A) (MonoPred_kpSM A) (MonoPred_stableSM A)).\n  + hnf; intros x y.\n    exact (@Sound_KripkeIntuitionistic.sound_stable_proper_iffp (MonoPred_L A) _ _ (Build_Model A) (unit_kMD _) tt R1 _ _ (MonoPred_SM A) (MonoPred_kiSM A) (MonoPred_kminSM A) (MonoPred_kpSM A) (MonoPred_stableSM A) x y).\nQed.\n\nInstance MonoPred_mstable (A: Type) {R1: KI.Relation A} {po_R1: PreOrder KI.Krelation} {R2: KM.Relation A} {R3: SS.Relation A} {ukmM: UpwardsClosedOrderedKripkeModel A} {R2_bis: Bisimulation SS.Krelation KM.Krelation}: ModalStable (MonoPred_L A) (MonoPred_Gamma A) (MonoPred_stable A).\nProof.\n  constructor.\n  intros x.\n  exact (@Sound_KripkeIntuitionistic.sound_boxp_stable (MonoPred_L A) _ _ _ (Build_Model A) (unit_kMD _) tt R1 _ _ _ (MonoPred_SM A) (MonoPred_fmSM A) (MonoPred_stableSM A) x).\nQed.\n\nInstance MonoPred_MAS (A: Type) {R1: KI.Relation A} {po_R1: PreOrder KI.Krelation} {R2: KM.Relation A} {R3: SS.Relation A} {ukmM: UpwardsClosedOrderedKripkeModel A} {R2_incl: Inclusion KM.Krelation SS.Krelation}: ModalAbsorbStable (MonoPred_L A) (MonoPred_Gamma A) (MonoPred_stable A).\nProof.\n  constructor.\n  intros x.\n  exact (@Sound_KripkeIntuitionistic.sound_boxp_absorb_stable (MonoPred_L A) _ _ _ (Build_Model A) (unit_kMD _) tt R1 _ _ _ (MonoPred_SM A) (MonoPred_kiSM A) (MonoPred_kminSM A) (MonoPred_kpSM A) (MonoPred_fmSM A) (MonoPred_stableSM A) x).\nQed.\n\nInstance MonoPred_sstable (A: Type) {R1: KI.Relation A} {po_R1: PreOrder KI.Krelation} {J: Join A} {SA: SeparationAlgebra A} {uSA: UpwardsClosedSeparationAlgebra A} {dSA: DownwardsClosedSeparationAlgebra A} {R2: SS.Relation A} {SA_bis_R2: SeparationAlgebraBisStable A}: SeparationStable (MonoPred_L A) (MonoPred_Gamma A) (MonoPred_stable A).\nProof.\n  constructor.\n  + intros x y.\n    exact (@Sound_KripkeIntuitionistic.sound_sepcon_stable (MonoPred_L A) _ _ _ (Build_Model A) (unit_kMD _) tt R1 _ _ _ (MonoPred_SM A) (MonoPred_fsepconSM A) (MonoPred_stableSM A) x y).\n  + intros x y.\n    exact (@Sound_KripkeIntuitionistic.sound_wand_stable (MonoPred_L A) _ _ _ (Build_Model A) (unit_kMD _) tt R1 _ _ _ (MonoPred_SM A) (MonoPred_fwandSM A) (MonoPred_stableSM A) x y).\nQed.\n\nInstance MonoPred_SAS (A: Type) {R1: KI.Relation A} {po_R1: PreOrder KI.Krelation} {J: Join A} {SA: SeparationAlgebra A} {uSA: UpwardsClosedSeparationAlgebra A} {dSA: DownwardsClosedSeparationAlgebra A} {R2: SS.Relation A} {SA_abs_R2: SeparationAlgebraAbsorbStable A}: SeparationAbsorbStable (MonoPred_L A) (MonoPred_Gamma A) (MonoPred_stable A).\nProof.\n  constructor.\n  intros x y z.\n  exact (@Sound_KripkeIntuitionistic.sound_stable_andp_sepcon1 (MonoPred_L A) _ _ _ (Build_Model A) (unit_kMD _) tt R1 _ _ _ (MonoPred_SM A) (MonoPred_kiSM A) (MonoPred_kminSM A) (MonoPred_kpSM A) (MonoPred_fsepconSM A) (MonoPred_stableSM A) x y z).\nQed.\n", "meta": {"author": "QinxiangCao", "repo": "UnifySL", "sha": "cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d", "save_path": "github-repos/coq/QinxiangCao-UnifySL", "path": "github-repos/coq/QinxiangCao-UnifySL/UnifySL-cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d/Extensions/ShallowEmbedded/MonoPredicateStable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.2551286243494424}}
{"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 Behavior.\nRequire Import NPConfiguration.\nRequire Import NPBehavior.\n\nRequire Import LibTactics.\nRequire Import Reordering.\nRequire Import LocalSim.\nRequire Import ps_to_np_thread.\n\nSet Implicit Arguments.\n\nLemma na_step_to_thread_step\n      lang lo e1 e2\n      (NA_STEP: @Thread.na_step lang lo e1 e2):\n  exists te, @Thread.step lang lo true te e1 e2 /\\ ThreadEvent.is_na_step te.\nProof.\n  inv NA_STEP.\n  - (* read *)\n    eexists. split.\n    eapply Thread.step_program; eauto. ss.\n  - (* write *)\n    eexists. split.\n    eapply Thread.step_program; eauto. ss.\n  - (* tau *)\n    eexists. split.\n    eapply Thread.step_program; eauto. ss.\nQed.\n\nLemma at_step_to_thread_step\n      lang lo e1 e2\n      (AT_STEP: @Thread.at_step lang lo e1 e2):\n  exists te, @Thread.step lang lo true te e1 e2 /\\ ThreadEvent.is_at_or_out_step te /\\\n        (~ (exists e, te = ThreadEvent.syscall e)).\nProof.\n  inv AT_STEP.\n  des.\n  inv AT_STEP0; eexists; split; [eapply Thread.step_program; eauto | eauto..]; ss.\n  destruct o; ss; eauto; try solve [split; eauto; ii; des; ss].\n  inv AT_STEP0; eexists; split; [eapply Thread.step_program; eauto | eauto..]; ss.\n  destruct o; ss; eauto; try solve [split; eauto; ii; des; ss].\n  inv AT_STEP0; eexists; split; [eapply Thread.step_program; eauto | eauto..]; ss.\n  try solve [split; eauto; ii; des; ss].\n  inv AT_STEP0; eexists; split; [eapply Thread.step_program; eauto | eauto..]; ss.\n  try solve [split; eauto; ii; des; ss].\nQed. \n\nLemma prc_step_to_thread_step\n      lang lo e1 e2\n      (PRC_STEP: @Thread.prc_step lang lo e1 e2):\n  exists pf te, @Thread.step lang lo pf te e1 e2 /\\\n           (exists loc t, ThreadEvent.is_promising te = Some (loc, t)).\nProof.\n  inv PRC_STEP.\n  do 2 eexists.\n  split.\n  econs. eauto.\n  ss.\n  eauto.\nQed.\n\nLemma program_step_to_NPThread_tau_step\n      lang lo e e' te b\n      (STEP: @Thread.program_step lang te lo e e')\n      (NOT_OUT: ~ (exists e, ThreadEvent.syscall e = te)):\n  exists b', NPAuxThread.tau_step lang lo (NPAuxThread.mk lang e b) (NPAuxThread.mk lang e' b') /\\\n        (ThreadEvent.is_na_step te -> b' = false) /\\\n        (ThreadEvent.is_at_or_out_step te -> b' = true).\nProof.\n  destruct te; ss.\n  - inv STEP. inv LOCAL.\n  - exists false. split; eauto.\n    unfold NPAuxThread.tau_step.\n    left.\n    econs; eauto.\n    eapply Thread.na_tau_step_intro; eauto.\n  - destruct ord; ss;\n      try solve [exists true; split; eauto;\n                   [unfold NPAuxThread.tau_step;\n                    right; left;\n                    econs; eauto;\n                    econs; eauto; left; eauto;\n                    econs; eauto | split; ii; ss; eauto]].\n    + exists false. split; eauto.\n      unfold NPAuxThread.tau_step.\n      left.\n      econs; eauto.\n      eapply Thread.na_plain_read_step_intro; eauto.\n  - destruct ord; ss;\n      try solve [exists true; split; eauto;\n                   [unfold NPAuxThread.tau_step;\n                    right; left; econs; eauto;\n                    econs; eauto; right; left; eauto;\n                    econs; eauto | split; ii; ss; eauto]].\n    + exists false. split; eauto;\n      unfold NPAuxThread.tau_step.\n      left.\n      econs; eauto.\n      eapply Thread.na_plain_write_step_intro; eauto.\n  - exists true; split; eauto.\n    unfold NPAuxThread.tau_step.\n    right; left; econs; eauto.\n    econs; eauto.\n    right. right. left.\n    econs; eauto.\n    split; eauto; ii; des; ss.\n  - exists true; split; eauto.\n    unfold NPAuxThread.tau_step.\n    right; left; econs; eauto.\n    econs; eauto.\n    right. right. right.\n    econs; eauto.\n    split; eauto; ii; des; ss.\n  - contradiction NOT_OUT.\n    eauto.\nQed. \n\nLemma NPThread_tau_step_to_program_step\n      lang lo e b e' b'\n      (TAU_STEP: NPAuxThread.tau_step lang lo (NPAuxThread.mk lang e b) (NPAuxThread.mk lang e' b')):\n  exists te, (@Thread.program_step lang te lo e e' \\/ (exists pf, @Thread.promise_step lang pf te e e')) /\\\n         ~ (exists e, ThreadEvent.syscall e = te).\nProof.\n  unfold NPAuxThread.tau_step in *.\n  des.\n  - (* na step *)\n    inv TAU_STEP; ss; subst.\n    inv H; try solve [eexists; split; [left; eauto | ii; des; ss]].\n  - (* at step *)\n    inv TAU_STEP; ss; subst.\n    inv H.\n    des; inv AT_STEP; try solve [eexists; split; [left; eauto | ii; des; ss]].\n  - (* prc step *)\n    inv TAU_STEP; ss; subst.\n    des; subst.\n    inv H.\n    eexists.\n    split.\n    right. eexists. eauto.\n    ii; des; ss.\nQed.\n\nLemma NPThread_tau_step_to_thread_all_step\n      lang lo e b e' b'\n      (TAU_STEP: NPAuxThread.tau_step lang lo (NPAuxThread.mk lang e b) (NPAuxThread.mk lang e' b')):\n  @Thread.all_step lang lo e e'.\nProof.\n  eapply NPThread_tau_step_to_program_step in TAU_STEP.\n  des.\n  econs. econs.\n  eapply Thread.step_program; eauto.\n  econs. econs.\n  econs. eauto.\nQed.\n\nLemma NPThread_tau_steps_to_thread_all_steps\n      lang lo e b e' b'\n      (TAU_STEPS: rtc (NPAuxThread.tau_step lang lo) (NPAuxThread.mk lang e b) (NPAuxThread.mk lang e' b')):\n  rtc (@Thread.all_step lang lo) e e'.\nProof.\n  eapply rtc_rtcn in TAU_STEPS. des.\n  ginduction n; ii.\n  - inv TAU_STEPS. eauto.\n  - inv TAU_STEPS. destruct a2.\n    eapply NPThread_tau_step_to_thread_all_step in A12.\n    eapply IHn in A23; eauto.\nQed.\n\nLemma NPConfig_abort_to_Config_abort\n      lo npc\n      (NPCONFIG_ABORT: NPConfiguration.is_abort npc lo):\n  Configuration.is_abort (NPConfiguration.cfg npc) lo.\nProof.\n  destruct npc; ss.\n  inv NPCONFIG_ABORT; ss. des; subst; ss.\n  eapply NPAuxThread_tau_steps_2_Thread_tau_steps in H2; ss.\n  econs; eauto.\n  do 3 eexists.\n  split; eauto.\nQed.\n\nLemma Thread_na_step_to_nprm_step\n      lang lo e e'\n      (NA_STEP: @Thread.na_step lang lo e e'):\n  @Thread.nprm_step lang lo e e'.\nProof.\n  inv NA_STEP; econs; eauto.\nQed.\n\nLemma Thread_na_steps_to_nprm_steps\n      lang lo e e'\n      (NA_STEPS: rtc (@Thread.na_step lang lo) e e'):\n  rtc (@Thread.nprm_step lang lo) e e'.\nProof.\n  induction NA_STEPS; eauto.\n  eapply Thread_na_step_to_nprm_step in H.\n  eapply Relation_Operators.rt1n_trans; eauto.\nQed. \n\nLemma Thread_pf_promise_step_is_nprm_step\n      lang lo e e'\n      (PF_PROMISE_STEP: @Thread.pf_promise_step lang e e'):\n  @Thread.nprm_step lang lo e e'.\nProof.\n  inv PF_PROMISE_STEP.\n  eapply Thread.nprm_step_pf_step; eauto.\nQed.\n\nLemma Thread_pf_promise_steps_is_nprm_steps\n      lang lo e e'\n      (PF_PROMISE_STEPS: rtc (@Thread.pf_promise_step lang) e e'):\n  rtc (@Thread.nprm_step lang lo) e e'.\nProof.\n  induction PF_PROMISE_STEPS; eauto.\n  eapply Thread_pf_promise_step_is_nprm_step in H.\n  eapply Relation_Operators.rt1n_trans; eauto.\nQed.\n\nLemma NPThread_all_step_to_Thread_all_step\n      lang lo e1 b1 e2 b2\n      (STEP: @NPAuxThread.all_step lang lo (NPAuxThread.mk lang e1 b1) (NPAuxThread.mk lang e2 b2)):\n  @Thread.all_step lang lo e1 e2.\nProof.\n  unfold NPAuxThread.all_step in STEP. des.\n  eapply NPThread_tau_step_to_thread_all_step in STEP.\n  eauto.\n  eapply NPAuxThread_out_step_is_Thread_program_step in STEP. ss.\nQed.\n  \nLemma NPThread_all_steps_to_Thread_all_steps':\n  forall n lang lo e1 b1 e2 b2\n    (STEPS: rtcn (@NPAuxThread.all_step lang lo) n (NPAuxThread.mk lang e1 b1) (NPAuxThread.mk lang e2 b2)),\n  rtc (@Thread.all_step lang lo) e1 e2.\nProof.\n  induction n; ii.\n  inv STEPS. eauto.\n  inv STEPS. destruct a2.\n  eapply IHn in A23.\n  eapply Relation_Operators.rt1n_trans. 2: eapply A23.\n  eapply NPThread_all_step_to_Thread_all_step; eauto.\nQed.\n\nLemma NPThread_all_steps_to_Thread_all_steps\n      lang lo e1 b1 e2 b2\n      (STEPS: rtc (@NPAuxThread.all_step lang lo) (NPAuxThread.mk lang e1 b1) (NPAuxThread.mk lang e2 b2)):\n  rtc (@Thread.all_step lang lo) e1 e2.\nProof.\n  eapply rtc_rtcn in STEPS. des.\n  eapply NPThread_all_steps_to_Thread_all_steps'; eauto.\nQed.\n\nLemma Thread_atmblk_step_is_tau_steps\n      lang lo (e e': Thread.t lang)\n      (ATMBLK_STEP: Thread.atmblk_step lo e e'):\n  rtc (Thread.tau_step lo) e e'.\nProof.\n  inv ATMBLK_STEP. des.\n  eapply na_steps_is_tau_steps in NA_STEPS.\n  eapply at_step_is_tau_step in AT_STEP.\n  eapply prc_steps_is_tau_steps in PRC_STEPS.\n  eapply rtc_compose. eapply NA_STEPS.\n  eapply Relation_Operators.rt1n_trans; eauto.\nQed.\n\nLemma Thread_atmblk_steps_is_tau_steps:\n  forall n lang lo (e e': Thread.t lang)\n    (ATMBLK_STEPS: rtcn (Thread.atmblk_step lo) n e e'),\n    rtc (Thread.tau_step lo) e e'.\nProof.\n  induction n; ii.\n  inv ATMBLK_STEPS. eauto.\n  inv ATMBLK_STEPS.\n  eapply IHn in A23.\n  eapply Thread_atmblk_step_is_tau_steps in A12.\n  eapply rtc_compose; 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/proofs/ps-np-equivalence/np_to_ps_thread.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953797290152, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2550641201223484}}
{"text": "Require Export Db.Inst.\nRequire Export Db.Lemmas.\nRequire Export Db.WellScoping.\nRequire Export Utlc.SpecSyntax.\nRequire Export Utlc.SpecScoping.\n\n#[refine] Instance vrUTm : Vr UTm := {| vr := var |}.\nProof. inversion 1; auto. Defined.\n\nLocal Ltac crush :=\n  intros; cbn in * |-;\n  repeat\n    (cbn;\n     repeat crushUtlcSyntaxMatchH;\n     repeat crushDbSyntaxMatchH;\n     repeat crushDbLemmasMatchH;\n     rewrite ?comp_up, ?up_liftSub, ?up_comp_lift\n    );\n  auto.\n\nModule UTmKit <: Kit.\n\n  Definition TM := UTm.\n  Definition inst_vr := vrUTm.\n\n  Section Application.\n\n    Context {Y: Type}.\n    Context {vrY : Vr Y}.\n    Context {wkY: Wk Y}.\n    Context {liftY: Lift Y UTm}.\n\n    #[refine] Global Instance inst_ap : Ap UTm Y := {| ap := apUTm |}.\n    Proof. induction x; crush. Defined.\n\n    #[refine] Global Instance inst_ap_vr : LemApVr UTm Y := {}.\n    Proof. reflexivity. Qed.\n\n  End Application.\n\n  #[refine] Instance inst_ap_inj: LemApInj UTm Ix := {}.\n  Proof.\n    intros m Inj_m x. revert m Inj_m.\n    induction x; destruct y; simpl; try discriminate;\n    inversion 1; subst; f_equal; eauto using InjSubIxUp.\n  Qed.\n\n  #[refine] Instance inst_ap_comp (Y Z: Type)\n    {vrY: Vr Y} {wkY: Wk Y} {liftY: Lift Y UTm}\n    {vrZ: Vr Z} {wkZ: Wk Z} {liftZ: Lift Z UTm}\n    {apYZ: Ap Y Z} {compUpYZ: LemCompUp Y Z}\n    {apLiftYUTmZ: LemApLift Y Z UTm} :\n    LemApComp UTm Y Z := {}.\n  Proof. induction x; crush. Qed.\n\n  #[refine] Instance inst_ap_liftSub (Y: Type)\n    {vrY: Vr Y} {wkY: Wk Y} {liftY: Lift Y UTm} :\n    LemApLiftSub UTm Y := {}.\n  Proof. induction t; crush. Qed.\n\n  Lemma inst_ap_ixComp (t: UTm) :\n    ∀ (ξ: Sub Ix) (ζ: Sub UTm), t[ξ][ζ] = t[⌈ξ⌉ >=> ζ].\n  Proof. pose proof up_comp_lift. induction t; crush. Qed.\n\nEnd UTmKit.\n\nModule InstUTm := Inst UTmKit.\n(* Instances are visible simply by creating the module on the previous line, but\n   we export the contents anyway so that the implicits have shorter names in\n   unambiguous contexts. *)\nExport InstUTm.\n\nInstance wsVrUTm: WsVr UTm.\nProof.\n  constructor.\n  - now constructor.\n  - now inversion 1.\nQed.\n\nSection Application.\n\n  Context {Y: Type}.\n  Context {vrY : Vr Y}.\n  Context {wkY: Wk Y}.\n  Context {liftY: Lift Y UTm}.\n  Context {wsY: Ws Y}.\n  Context {wsVrY: WsVr Y}.\n  Context {wsWkY: WsWk Y}.\n  Context {wsLiftY: WsLift Y UTm}.\n\n  Hint Resolve wsLift : ws.\n  Hint Resolve wsSub_up : ws.\n\n  Global Instance wsApUTm : WsAp UTm Y.\n  Proof.\n    constructor.\n    - intros ξ γ δ t wξ wt; revert ξ δ wξ.\n      induction wt; intros ξ δ wξ; crush;\n        try econstructor;\n        try match goal with\n              | |- wsUTm ?δ ?t =>\n                change (wsUTm δ t) with ⟨ δ ⊢ t ⟩\n            end; eauto with ws.\n    - intros γ t wt.\n      induction wt; crush.\n      + apply IHwt; inversion 1; crush.\n      + apply IHwt2; inversion 1; crush.\n      + apply IHwt3; inversion 1; crush.\n  Qed.\n\nEnd Application.\n\nInstance wsWkUTm: WsWk UTm.\nProof.\n  constructor; crush.\n  - refine (wsAp _ H); eauto.\n    constructor; eauto.\nQed.\n(*   - admit. *)\n(* Admitted. *)\n\nSection ApplicationPCtx.\n\n  Context {Y: Type}.\n  Context {vrY : Vr Y}.\n  Context {wkY: Wk Y}.\n  Context {liftYUTm: Lift Y UTm}.\n\n  #[refine] Global Instance ApPCtx : Ap PCtx Y := {| ap := apPCtx |}.\n  Proof. induction x; crush. Defined.\n\nEnd ApplicationPCtx.\n", "meta": {"author": "dominiquedevriese", "repo": "facomp-stlc-coq", "sha": "77043e68813d3a7ed8926802191638f063de1544", "save_path": "github-repos/coq/dominiquedevriese-facomp-stlc-coq", "path": "github-repos/coq/dominiquedevriese-facomp-stlc-coq/facomp-stlc-coq-77043e68813d3a7ed8926802191638f063de1544/Utlc/Inst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.25506411369900805}}
{"text": "From iris.program_logic Require Export language ectx_language ectxi_language.\nFrom iris_io.prelude Require Export base.\nFrom iris_io Require Export proph_erasure lang_proph_erased\n     lang_fully_erased.\nFrom stdpp Require Import gmap.\n\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Logic.PropExtensionality.\nRequire Import Coq.Logic.Classical.\n\nDefinition prefix_closed (M : ioSpec) :=\n  ∀ τ τ', M (τ ++ τ') → M τ.\n\nDefinition IO_performed\n           (σ : language.state PE_lang) (σ' : language.state PFE_lang) M\n  := (EHeap σ) = (FEHeap σ') ∧ (EProph σ) = (FEProph σ') ∧\n     (EioState σ) = (λ τ, M ((FEIO σ') ++ τ)) ∧ (∃ τ, M ((FEIO σ') ++ τ)).\n\nDefinition make_ioSpec (σ : language.state PFE_lang) M :\n  language.state PE_lang :=\n  {| EHeap := FEHeap σ; EProph := FEProph σ;\n     EioState := λ τ, M ((FEIO σ) ++ τ) |}.\n\nLemma make_ioSpec_IO_performed σ (M : ioSpec):\n  M (FEIO σ) → IO_performed (make_ioSpec σ M) σ M.\nProof.\n  destruct σ as [h p i]; repeat split; simpl in *; eauto.\n  by eexists nil; rewrite app_nil_r.\nQed.\n\nLemma fully_erased_reachable_reachable th1 h1 th2 σ2 (M : ioSpec) :\n  prefix_closed M →\n  M (FEIO σ2) →\n  rtc (@step PFE_lang) (th1, {| FEHeap := h1; FEProph := ∅; FEIO := [] |})\n      (th2, σ2) →\n  rtc (@step PE_lang)\n      (th1, {| EHeap := h1; EProph := ∅; EioState := M |})\n      (th2, make_ioSpec σ2 M).\nProof.\n  intros Mpc.\n  remember (th1, {| FEHeap := h1; FEProph := ∅; FEIO := [] |}) as cfg.\n  remember (th2, σ2) as cfg'.\n  intros HM Hrtc; revert HM.\n  revert th1 h1 th2 σ2 Heqcfg Heqcfg'.\n  simpl in *.\n  eapply (rtc_ind_r_weak\n            (λ z z', ∀ (th1 : list (language.expr PFE_lang))\n                       (h1 : gmap loc val)\n                       (th2 : list (language.expr PFE_lang))\n                       (σ2 : language.state PFE_lang),\n                z = (th1,\n                     {| FEHeap := h1; FEProph := ∅; FEIO := [] |})\n                → z' = (th2, σ2) →\n                M (FEIO σ2) →\n                rtc (@step PE_lang)\n                    (th1, {| EHeap := h1; EProph := ∅; EioState := M |})\n                    (th2, make_ioSpec σ2 M)));\n    last eauto.\n  - intros x th1 h1 th2 σ2 Heqcfg Heqcfg'; simplify_eq.\n    left; split; simpl; eauto; econstructor.\n  - intros x y z Hxy Hyz IH th1 h1 th2 σ2 Heqcfg Heqcfg' HM;\n      simplify_eq; simpl in *.\n    destruct y as [yh yp].\n    inversion Hyz as [? ? ? ? ? ? ? ? ? Hpr]; simplify_eq.\n    inversion Hpr as [? ? ? ? ? Hestp]; simpl in *; simplify_eq.\n    inversion Hestp; simplify_eq;\n      repeat match goal with\n      | H : is_Some _ |- _ => destruct H\n      end;\n      try (by eapply rtc_r; first (by apply IH); repeat econstructor; eauto).\n    eapply rtc_r; first apply IH; eauto.\n    + simpl in HM; eapply Mpc; eauto.\n    + unfold make_ioSpec; simpl.\n      replace (λ τ, M ((FEIO σ1 ++ [(t, v, v')]) ++ τ)) with\n        (λ τ, M (FEIO σ1 ++ [(t, v, v')] ++ τ)); last first.\n    { extensionality τ. by rewrite -assoc. }\n    repeat econstructor; eauto; simpl.\n    apply (EIOS t e v v' {| EioState := λ τ, M (FEIO σ1 ++ τ) |}); eauto.\nQed.\n\nDefinition fully_erased_safe e (M : ioSpec) :=\n  ∀ th2 σ2,\n    M (FEIO σ2) →\n    rtc (@step PFE_lang) ([e], {| FEHeap := ∅; FEProph := ∅; FEIO := [] |})\n        (th2, σ2) →\n    ∀ e, e ∈ th2 → AsVal e ∨\n                   (∃ e' σ'' efs,\n                       @language.prim_step PFE_lang e σ2 e' σ'' efs\n                       ∧ ∀ t v v', FEIO σ'' = FEIO σ2 ++ [(t, v, v')] →\n                                   ∃ v'', M (FEIO σ2 ++ [(t, v, v'')])).\n\nInstance fully_erased_safe_impl e :\n  Proper ((≡) ==> impl) (fully_erased_safe e).\nProof.\n  intros M M' HMM HM th2 σ2 HM' Hrtc e' He'.\n  destruct (HM th2 σ2 (proj2 (HMM _) HM') Hrtc e' He') as\n      [| (e'' & σ'' & efs & Hstp & Hrd)];\n    first auto.\n  right. eexists _, _, _; split; eauto.\n  intros t v v' Hvv'. destruct (Hrd _ _ _ Hvv') as [v'' Hrd'].\n  eexists; eapply HMM; eauto.\nQed.\n\nInstance fully_erased_safe_equiv e :\n  Proper ((≡) ==> iff) (fully_erased_safe e).\nProof.\n  intros M M' HMM; split => HL.\n  - eapply fully_erased_safe_impl; eauto.\n  - symmetry in HMM. eapply fully_erased_safe_impl; eauto.\nQed.\n\nLemma fully_erased_safe_union e (F : ioSpec → Prop) :\n  (∀ M, F M → fully_erased_safe e M) →\n  fully_erased_safe e (λ io, ∃ M, F M ∧ M io).\nProof.\n  intros Hfa th2 σ2 [M [HFM HMσ2]] Hrtc e' He'.\n  destruct (Hfa M HFM th2 σ2 HMσ2 Hrtc e' He') as\n      [?|(e'' & σ'' & efs & Hstp & Hrd)];\n    first auto; simpl in *.\n  right; do 3 eexists; split; eauto.\n  intros t v v' Ht.\n  destruct (Hrd t v v' Ht) as [v'' HM].\n  exists v'', M; split; auto.\nQed.\n\nLemma reducible_fully_erase_reducible e σ σ' M :\n  IO_performed σ σ' M →\n  @language.reducible PE_lang e σ →\n  ∃ e' σ'' efs,\n    @language.prim_step PFE_lang e σ' e' σ'' efs\n    ∧ ∀ t v v', FEIO σ'' = FEIO σ' ++ [(t, v, v')] →\n                ∃ v'', M (FEIO σ' ++ [(t, v, v'')]).\nProof.\n  intros Hsp (e'&σ2&efs&Hrd); simpl in *.\n  inversion Hrd as [K e1' e2' ? ? Hhrd]; simpl in *; subst.\n  destruct σ as [σh σp]; destruct σ' as [σ'h σ'p];\n    destruct Hsp as [? [? [? ?]]]; simpl in *; simplify_eq.\n  inversion Hhrd; subst;\n    repeat match goal with A : is_Some _ |- _ => destruct A as [? ?] end;\n    simpl in *;\n    try (by (unshelve (repeat econstructor; eauto)); simpl in *;\n            try match goal with\n                | H : ?A = ?A ++ [_] |- _ =>\n                  let H' := fresh in\n                  pose proof (f_equal length H) as H';\n                  rewrite app_length in H'; simpl in H'; omega\n                end).\n  - eexists _, _, _; split; first by unshelve (repeat econstructor; eauto).\n    intros ? ? ? ?; simpl in *;\n      match goal with\n      | H: ?A ++ [_] = ?A ++ [_] |- _ =>\n        apply app_inv_head in H; simplify_eq; simpl in *; eauto\n      end.\nQed.\n\nLemma soundness_io e M :\n  prefix_closed M → erased_safe e M → fully_erased_safe e M.\nProof.\n  intros Hpc Hs th2 σ2 HMσ2 Hrtc re Hre.\n  assert (rtc (@language.step PE_lang)\n              ([e], {| EHeap := ∅; EProph := ∅; EioState := M |})\n              (th2, make_ioSpec σ2 M)) as Hrtc'.\n  { eapply fully_erased_reachable_reachable; eauto. }\n  edestruct Hs as [?|Hred]; eauto.\n  right. eapply reducible_fully_erase_reducible; eauto.\n  by apply make_ioSpec_IO_performed.\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/full_erasure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.25506411369900805}}
{"text": "(* A variant of bug #1302 that must fail *)\n\nModule Type T.\n\n Parameter A : Type.\n\n Inductive L : Prop :=\n | L0\n | L1 :  (A -> Prop) -> L.\n\nEnd T.\n\nModule TT : T.\n\n Parameter A : Type.\n\n Inductive L : Type :=\n | L0\n | L1 :  (A -> Prop) -> L.\n\nFail End TT.\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/failure/subtyping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.255064113699008}}
{"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.Spec.\nRequire Import RVIC4.Specs.rvic_set_pending.\nRequire Import RVIC4.LowSpecs.rvic_set_pending.\nRequire Import RVIC4.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_rvic_pending_bits_spec\n       rvic_set_flag_spec\n    .\n\n  Lemma rvic_set_pending_spec_exists:\n    forall habd habd'  labd rvic intid\n      (Hspec: rvic_set_pending_spec rvic intid habd = Some habd')\n      (Hrel: relate_RData habd labd),\n    exists labd', rvic_set_pending_spec0 rvic intid labd = Some labd' /\\ relate_RData habd' labd'.\n  Proof.\n    intros. destruct Hrel. destruct rvic.\n    unfold rvic_set_pending_spec, rvic_set_pending_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        repeat (solve_bool_range; grewrite);\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/RVIC4/RefProof/rvic_set_pending.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953506426082, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2550641072756676}}
{"text": "\nDefinition x2 :=  (f\n          [pk (N 1); pk (N 2);\n          if_then_else_M (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)\n            (enc (N 3, pk (N 1)) (m x1) (sr 1))\n            (if_then_else_M (EQ_M (to x1) (i 2))\n               (enc (pi1 (dec x1 (sk (N 2))), (N 4, pk (N 2))) \n                  (pk (N 1)) (sr 2)) O)]).\nDefinition x3 := (f\n         [pk (N 1); pk (N 2);\n         if_then_else_M (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)\n           (enc (N 3, pk (N 1)) (m x1) (sr 1))\n           (if_then_else_M (EQ_M (to x1) (i 2))\n              (enc (pi1 (dec x1 (sk (N 2))), (N 4, pk (N 2))) \n                 (pk (N 1)) (sr 2)) O);\n         if_then_else_M (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)\n           (if_then_else_M\n              ((EQ_M (to x2) (i 1)) & (EQ_M (pi1 (dec x2 (sk (N 1)))) (N 3))) &\n              (EQ_M (pi2 (pi2 (dec x2 (sk (N 1))))) (m x1))\n              (enc (pi1 (pi2 (dec x2 (sk (N 1))))) (m x1) (sr 3))\n              (if_then_else_M (EQ_M (to x2) (i 2))\n                 (enc (pi1 (dec x2 (sk (N 2))), (N 4, pk (N 2))) \n                    (pk (N 1)) (sr 4)) O))\n           (if_then_else_M (EQ_M (to x1) (i 2))\n              (if_then_else_M (EQ_M (to x2) (i 1)) & (EQ_M (act x2) new)\n                 (enc (N 3, pk (N 1)) (m x2) (sr 5))\n                 (if_then_else_M\n                    (EQ_M (to x2) (i 2)) & (EQ_M (dec x2 (sk (N 2))) (N 4))\n                    acc O)) O)]).\nDefinition x4 :=  (f\n         [pk (N 1); pk (N 2);\n         if_then_else_M (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)\n           (enc (N 3, pk (N 1)) (m x1) (sr 1))\n           (if_then_else_M (EQ_M (to x1) (i 2))\n              (enc (pi1 (dec x1 (sk (N 2))), (N 4, pk (N 2))) \n                 (pk (N 1)) (sr 2)) O);\n         if_then_else_M (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)\n           (if_then_else_M\n              ((EQ_M (to x2) (i 1)) & (EQ_M (pi1 (dec x2 (sk (N 1)))) (N 3))) &\n              (EQ_M (pi2 (pi2 (dec x2 (sk (N 1))))) (m x1))\n              (enc (pi1 (pi2 (dec x2 (sk (N 1))))) (m x1) (sr 3))\n              (if_then_else_M (EQ_M (to x2) (i 2))\n                 (enc (pi1 (dec x2 (sk (N 2))), (N 4, pk (N 2))) \n                    (pk (N 1)) (sr 4)) O))\n           (if_then_else_M (EQ_M (to x1) (i 2))\n              (if_then_else_M (EQ_M (to x2) (i 1)) & (EQ_M (act x2) new)\n                 (enc (N 3, pk (N 1)) (m x2) (sr 5))\n                 (if_then_else_M\n                    (EQ_M (to x2) (i 2)) & (EQ_M (dec x2 (sk (N 2))) (N 4))\n                    acc O)) O);\n         if_then_else_M (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)\n           (if_then_else_M\n              ((EQ_M (to x2) (i 1)) & (EQ_M (pi1 (dec x2 (sk (N 1)))) (N 3))) &\n              (EQ_M (pi2 (pi2 (dec x2 (sk (N 1))))) (m x1))\n              (if_then_else_M (EQ_M (to x3) (i 2))\n                 (enc (pi1 (dec x3 (sk (N 2))), (N 4, pk (N 2))) \n                    (pk (N 1)) (sr 6)) O)\n              (if_then_else_M (EQ_M (to x2) (i 2))\n                 (if_then_else_M\n                    ((EQ_M (to x3) (i 1)) &\n                     (EQ_M (pi1 (dec x3 (sk (N 1)))) (N 3))) &\n                    (EQ_M (pi2 (pi2 (dec x3 (sk (N 1))))) (m x1))\n                    (enc (pi1 (pi2 (dec x3 (sk (N 1))))) (m x1) (sr 7))\n                    (if_then_else_M\n                       (EQ_M (to x3) (i 2)) &\n                       (EQ_M (dec x3 (sk (N 2))) (N 4)) acc O)) O))\n           (if_then_else_M (EQ_M (to x1) (i 2))\n              (if_then_else_M (EQ_M (to x2) (i 1)) & (EQ_M (act x2) new)\n                 (if_then_else_M\n                    ((EQ_M (to x3) (i 1)) &\n                     (EQ_M (pi1 (dec x3 (sk (N 1)))) (N 3))) &\n                    (EQ_M (pi2 (pi2 (dec x3 (sk (N 1))))) (m x1))\n                    (enc (pi1 (pi2 (dec x3 (sk (N 1))))) (m x1) (sr 7))\n                    (if_then_else_M\n                       (EQ_M (to x3) (i 2)) &\n                       (EQ_M (dec x3 (sk (N 2))) (N 4)) acc O))\n                 (if_then_else_M\n                    (EQ_M (to x2) (i 2)) & (EQ_M (dec x2 (sk (N 2))) (N 4))\n                    (if_then_else_M\n                       (EQ_M (to x3) (i 1)) & (EQ_M (act x3) new)\n                       (enc (N 3, pk (N 1)) (m x1) (sr 8)) O) O)) O)]).\nDefinition x5 :=  (f\n         [pk (N 1); pk (N 2); t12; t13;\n         if_then_else_M (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)\n           (if_then_else_M\n              ((EQ_M (to x2) (i 1)) & (EQ_M (pi1 (dec x2 (sk (N 1)))) (N 3))) &\n              (EQ_M (pi2 (pi2 (dec x2 (sk (N 1))))) (m x1))\n              (if_then_else_M (EQ_M (to x3) (i 2))\n                 (enc (pi1 (dec x3 (sk (N 2))), (N 4, pk (N 2))) \n                    (pk (N 1)) (sr 6)) O)\n              (if_then_else_M (EQ_M (to x2) (i 2))\n                 (if_then_else_M\n                    ((EQ_M (to x3) (i 1)) &\n                     (EQ_M (pi1 (dec x3 (sk (N 1)))) (N 3))) &\n                    (EQ_M (pi2 (pi2 (dec x3 (sk (N 1))))) (m x1))\n                    (enc (pi1 (pi2 (dec x3 (sk (N 1))))) (m x1) (sr 7))\n                    (if_then_else_M\n                       (EQ_M (to x3) (i 2)) &\n                       (EQ_M (dec x3 (sk (N 2))) (N 4)) acc O)) O))\n           (if_then_else_M (EQ_M (to x1) (i 2))\n              (if_then_else_M (EQ_M (to x2) (i 1)) & (EQ_M (act x2) new)\n                 (if_then_else_M\n                    ((EQ_M (to x3) (i 1)) &\n                     (EQ_M (pi1 (dec x3 (sk (N 1)))) (N 3))) &\n                    (EQ_M (pi2 (pi2 (dec x3 (sk (N 1))))) (m x1))\n                    (enc (pi1 (pi2 (dec x3 (sk (N 1))))) (m x1) (sr 7))\n                    (if_then_else_M\n                       (EQ_M (to x3) (i 2)) &\n                       (EQ_M (dec x3 (sk (N 2))) (N 4)) acc O))\n                 (if_then_else_M\n                    (EQ_M (to x2) (i 2)) & (EQ_M (dec x2 (sk (N 2))) (N 4))\n                    (if_then_else_M\n                       (EQ_M (to x3) (i 1)) & (EQ_M (act x3) new)\n                       (enc (N 3, pk (N 1)) (m x1) (sr 8)) O) O)) O);\n         if_then_else_M (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)\n           (if_then_else_M\n              ((EQ_M (to x2) (i 1)) & (EQ_M (pi1 (dec x2 (sk (N 1)))) (N 3))) &\n              (EQ_M (pi2 (pi2 (dec x2 (sk (N 1))))) (m x1))\n              (if_then_else_M (EQ_M (to x3) (i 2))\n                 (if_then_else_M\n                    (EQ_M (to x4) (i 2)) & (EQ_M (dec x4 (sk (N 2))) (N 4))\n                    acc O) O)\n              (if_then_else_M (EQ_M (to x2) (i 2))\n                 (if_then_else_M\n                    ((EQ_M (to x3) (i 1)) &\n                     (EQ_M (pi1 (dec x3 (sk (N 1)))) (N 3))) &\n                    (EQ_M (pi2 (pi2 (dec x3 (sk (N 1))))) (m x1))\n                    (if_then_else_M\n                       (EQ_M (to x4) (i 2)) &\n                       (EQ_M (dec x4 (sk (N 2))) (N 4)) acc O)\n                    (if_then_else_M\n                       (EQ_M (to x3) (i 2)) &\n                       (EQ_M (dec x3 (sk (N 2))) (N 4))\n                       (if_then_else_M\n                          ((EQ_M (to x4) (i 1)) &\n                           (EQ_M (pi1 (dec x4 (sk (N 1)))) (N 3))) &\n                          (EQ_M (pi2 (pi2 (dec x4 (sk (N 1))))) (m x1))\n                          (enc (pi1 (pi2 (dec x4 (sk (N 1))))) (m x1) (sr 9))\n                          O) O)) O))\n           (if_then_else_M (EQ_M (to x1) (i 2))\n              (if_then_else_M (EQ_M (to x2) (i 1)) & (EQ_M (act x2) new)\n                 (if_then_else_M\n                    ((EQ_M (to x3) (i 1)) &\n                     (EQ_M (pi1 (dec x3 (sk (N 1)))) (N 3))) &\n                    (EQ_M (pi2 (pi2 (dec x3 (sk (N 1))))) (m x1))\n                    (if_then_else_M\n                       (EQ_M (to x4) (i 2)) &\n                       (EQ_M (dec x4 (sk (N 2))) (N 4)) acc O)\n                    (if_then_else_M\n                       (EQ_M (to x3) (i 2)) &\n                       (EQ_M (dec x3 (sk (N 2))) (N 4))\n                       (if_then_else_M\n                          ((EQ_M (to x4) (i 1)) &\n                           (EQ_M (pi1 (dec x4 (sk (N 1)))) (N 3))) &\n                          (EQ_M (pi2 (pi2 (dec x4 (sk (N 1))))) (m x1))\n                          (enc (pi1 (pi2 (dec x4 (sk (N 1))))) (m x1) (sr 9))\n                          O) O))\n                 (if_then_else_M\n                    (EQ_M (to x2) (i 2)) & (EQ_M (dec x2 (sk (N 2))) (N 4))\n                    (if_then_else_M\n                       (EQ_M (to x3) (i 1)) & (EQ_M (act x3) new)\n                       (if_then_else_M\n                          ((EQ_M (to x4) (i 1)) &\n                           (EQ_M (pi1 (dec x4 (sk (N 1)))) (N 3))) &\n                          (EQ_M (pi2 (pi2 (dec x4 (sk (N 1))))) (m x1))\n                          (enc (pi1 (pi2 (dec x4 (sk (N 1))))) (m x1) (sr 9))\n                          O) O) O)) O)]).\nDefinition t12 := (if_then_else_M (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)\n          (enc (N 3, pk (N 1)) (m x1) (sr 1))\n          (if_then_else_M (EQ_M (to x1) (i 2))\n             (enc (pi1 (dec x1 (sk (N 2))), (N 4, pk (N 2))) \n                (pk (N 1)) (sr 2)) O)).\nDefinition t13 :=    (if_then_else_M (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)\n         (if_then_else_M\n            ((EQ_M (to x2) (i 1)) & (EQ_M (pi1 (dec x2 (sk (N 1)))) (N 3))) &\n            (EQ_M (pi2 (pi2 (dec x2 (sk (N 1))))) (m x1))\n            (enc (pi1 (pi2 (dec x2 (sk (N 1))))) (m x1) (sr 3))\n            (if_then_else_M (EQ_M (to x2) (i 2))\n               (enc (pi1 (dec x2 (sk (N 2))), (N 4, pk (N 2))) \n                  (pk (N 1)) (sr 4)) O))\n         (if_then_else_M (EQ_M (to x1) (i 2))\n            (if_then_else_M (EQ_M (to x2) (i 1)) & (EQ_M (act x2) new)\n               (enc (N 3, pk (N 1)) (m x2) (sr 5))\n               (if_then_else_M\n                  (EQ_M (to x2) (i 2)) & (EQ_M (dec x2 (sk (N 2))) (N 4)) acc\n                  O)) O)).\nDefinition t14 :=(if_then_else_M (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)\n         (if_then_else_M\n            ((EQ_M (to x2) (i 1)) & (EQ_M (pi1 (dec x2 (sk (N 1)))) (N 3))) &\n            (EQ_M (pi2 (pi2 (dec x2 (sk (N 1))))) (m x1))\n            (if_then_else_M (EQ_M (to x3) (i 2))\n               (enc (pi1 (dec x3 (sk (N 2))), (N 4, pk (N 2))) \n                  (pk (N 1)) (sr 6)) O)\n            (if_then_else_M (EQ_M (to x2) (i 2))\n               (if_then_else_M\n                  ((EQ_M (to x3) (i 1)) &\n                   (EQ_M (pi1 (dec x3 (sk (N 1)))) (N 3))) &\n                  (EQ_M (pi2 (pi2 (dec x3 (sk (N 1))))) (m x1))\n                  (enc (pi1 (pi2 (dec x3 (sk (N 1))))) (m x1) (sr 7))\n                  (if_then_else_M\n                     (EQ_M (to x3) (i 2)) & (EQ_M (dec x3 (sk (N 2))) (N 4))\n                     acc O)) O))\n         (if_then_else_M (EQ_M (to x1) (i 2))\n            (if_then_else_M (EQ_M (to x2) (i 1)) & (EQ_M (act x2) new)\n               (if_then_else_M\n                  ((EQ_M (to x3) (i 1)) &\n                   (EQ_M (pi1 (dec x3 (sk (N 1)))) (N 3))) &\n                  (EQ_M (pi2 (pi2 (dec x3 (sk (N 1))))) (m x1))\n                  (enc (pi1 (pi2 (dec x3 (sk (N 1))))) (m x1) (sr 7))\n                  (if_then_else_M\n                     (EQ_M (to x3) (i 2)) & (EQ_M (dec x3 (sk (N 2))) (N 4))\n                     acc O))\n               (if_then_else_M\n                  (EQ_M (to x2) (i 2)) & (EQ_M (dec x2 (sk (N 2))) (N 4))\n                  (if_then_else_M (EQ_M (to x3) (i 1)) & (EQ_M (act x3) new)\n                     (enc (N 3, pk (N 1)) (m x1) (sr 8)) O) O)) O)).\nDefinition t15 := (if_then_else_M (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)\n         (if_then_else_M\n            ((EQ_M (to x2) (i 1)) & (EQ_M (pi1 (dec x2 (sk (N 1)))) (N 3))) &\n            (EQ_M (pi2 (pi2 (dec x2 (sk (N 1))))) (m x1))\n            (if_then_else_M (EQ_M (to x3) (i 2))\n               (if_then_else_M\n                  (EQ_M (to x4) (i 2)) & (EQ_M (dec x4 (sk (N 2))) (N 4)) acc\n                  O) O)\n            (if_then_else_M (EQ_M (to x2) (i 2))\n               (if_then_else_M\n                  ((EQ_M (to x3) (i 1)) &\n                   (EQ_M (pi1 (dec x3 (sk (N 1)))) (N 3))) &\n                  (EQ_M (pi2 (pi2 (dec x3 (sk (N 1))))) (m x1))\n                  (if_then_else_M\n                     (EQ_M (to x4) (i 2)) & (EQ_M (dec x4 (sk (N 2))) (N 4))\n                     acc O)\n                  (if_then_else_M\n                     (EQ_M (to x3) (i 2)) & (EQ_M (dec x3 (sk (N 2))) (N 4))\n                     (if_then_else_M\n                        ((EQ_M (to x4) (i 1)) &\n                         (EQ_M (pi1 (dec x4 (sk (N 1)))) (N 3))) &\n                        (EQ_M (pi2 (pi2 (dec x4 (sk (N 1))))) (m x1))\n                        (enc (pi1 (pi2 (dec x4 (sk (N 1))))) (m x1) (sr 9)) O)\n                     O)) O))\n         (if_then_else_M (EQ_M (to x1) (i 2))\n            (if_then_else_M (EQ_M (to x2) (i 1)) & (EQ_M (act x2) new)\n               (if_then_else_M\n                  ((EQ_M (to x3) (i 1)) &\n                   (EQ_M (pi1 (dec x3 (sk (N 1)))) (N 3))) &\n                  (EQ_M (pi2 (pi2 (dec x3 (sk (N 1))))) (m x1))\n                  (if_then_else_M\n                     (EQ_M (to x4) (i 2)) & (EQ_M (dec x4 (sk (N 2))) (N 4))\n                     acc O)\n                  (if_then_else_M\n                     (EQ_M (to x3) (i 2)) & (EQ_M (dec x3 (sk (N 2))) (N 4))\n                     (if_then_else_M\n                        ((EQ_M (to x4) (i 1)) &\n                         (EQ_M (pi1 (dec x4 (sk (N 1)))) (N 3))) &\n                        (EQ_M (pi2 (pi2 (dec x4 (sk (N 1))))) (m x1))\n                        (enc (pi1 (pi2 (dec x4 (sk (N 1))))) (m x1) (sr 9)) O)\n                     O))\n               (if_then_else_M\n                  (EQ_M (to x2) (i 2)) & (EQ_M (dec x2 (sk (N 2))) (N 4))\n                  (if_then_else_M (EQ_M (to x3) (i 1)) & (EQ_M (act x3) new)\n                     (if_then_else_M\n                        ((EQ_M (to x4) (i 1)) &\n                         (EQ_M (pi1 (dec x4 (sk (N 1)))) (N 3))) &\n                        (EQ_M (pi2 (pi2 (dec x4 (sk (N 1))))) (m x1))\n                        (enc (pi1 (pi2 (dec x4 (sk (N 1))))) (m x1) (sr 9)) O)\n                     O) O)) O)).\nDefinition t16 :=  (if_then_else_M (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)\n         (if_then_else_M\n            ((EQ_M (to x2) (i 1)) & (EQ_M (pi1 (dec x2 (sk (N 1)))) (N 3))) &\n            (EQ_M (pi2 (pi2 (dec x2 (sk (N 1))))) (m x1))\n            (if_then_else_M (EQ_M (to x3) (i 2))\n               (if_then_else_M\n                  (EQ_M (to x4) (i 2)) & (EQ_M (dec x4 (sk (N 2))) (N 4))\n                  (if_then_else_M\n                     (EQ_M (reveal x5) (i 1)) & (EQ_M (m x1) (pk (N 2)))\n                     (N 3)\n                     (if_then_else_M\n                        (EQ_M (reveal x5) (i 2)) & (EQ_M (m x1) (pk (N 2)))\n                        (N 4) O)) O) O)\n            (if_then_else_M (EQ_M (to x2) (i 2))\n               (if_then_else_M\n                  ((EQ_M (to x3) (i 1)) &\n                   (EQ_M (pi1 (dec x3 (sk (N 1)))) (N 3))) &\n                  (EQ_M (pi2 (pi2 (dec x3 (sk (N 1))))) (m x1))\n                  (if_then_else_M\n                     (EQ_M (to x4) (i 2)) & (EQ_M (dec x4 (sk (N 2))) (N 4))\n                     (if_then_else_M\n                        (EQ_M (reveal x5) (i 1)) & (EQ_M (m x1) (pk (N 2)))\n                        (N 3)\n                        (if_then_else_M\n                           (EQ_M (reveal x5) (i 2)) &\n                           (EQ_M (m x1) (pk (N 2))) \n                           (N 4) O)) O)\n                  (if_then_else_M\n                     (EQ_M (to x3) (i 2)) & (EQ_M (dec x3 (sk (N 2))) (N 4))\n                     (if_then_else_M\n                        ((EQ_M (to x4) (i 1)) &\n                         (EQ_M (pi1 (dec x4 (sk (N 1)))) (N 3))) &\n                        (EQ_M (pi2 (pi2 (dec x4 (sk (N 1))))) (m x1))\n                        (if_then_else_M\n                           (EQ_M (reveal x5) (i 1)) &\n                           (EQ_M (m x1) (pk (N 2))) \n                           (N 3)\n                           (if_then_else_M\n                              (EQ_M (reveal x5) (i 2)) &\n                              (EQ_M (m x1) (pk (N 2))) \n                              (N 4) O)) O) O)) O))\n         (if_then_else_M (EQ_M (to x1) (i 2))\n            (if_then_else_M (EQ_M (to x2) (i 1)) & (EQ_M (act x2) new)\n               (if_then_else_M\n                  ((EQ_M (to x3) (i 1)) &\n                   (EQ_M (pi1 (dec x3 (sk (N 1)))) (N 3))) &\n                  (EQ_M (pi2 (pi2 (dec x3 (sk (N 1))))) (m x1))\n                  (if_then_else_M\n                     (EQ_M (to x4) (i 2)) & (EQ_M (dec x4 (sk (N 2))) (N 4))\n                     (if_then_else_M\n                        (EQ_M (reveal x5) (i 1)) & (EQ_M (m x1) (pk (N 2)))\n                        (N 3)\n                        (if_then_else_M\n                           (EQ_M (reveal x5) (i 2)) &\n                           (EQ_M (m x1) (pk (N 2))) \n                           (N 4) O)) O)\n                  (if_then_else_M\n                     (EQ_M (to x3) (i 2)) & (EQ_M (dec x3 (sk (N 2))) (N 4))\n                     (if_then_else_M\n                        ((EQ_M (to x4) (i 1)) &\n                         (EQ_M (pi1 (dec x4 (sk (N 1)))) (N 3))) &\n                        (EQ_M (pi2 (pi2 (dec x4 (sk (N 1))))) (m x1))\n                        (if_then_else_M\n                           (EQ_M (reveal x5) (i 1)) &\n                           (EQ_M (m x1) (pk (N 2))) \n                           (N 3)\n                           (if_then_else_M\n                              (EQ_M (reveal x5) (i 2)) &\n                              (EQ_M (m x1) (pk (N 2))) \n                              (N 4) O)) O) O))\n               (if_then_else_M\n                  (EQ_M (to x2) (i 2)) & (EQ_M (dec x2 (sk (N 2))) (N 4))\n                  (if_then_else_M (EQ_M (to x3) (i 1)) & (EQ_M (act x3) new)\n                     (if_then_else_M\n                        ((EQ_M (to x4) (i 1)) &\n                         (EQ_M (pi1 (dec x4 (sk (N 1)))) (N 3))) &\n                        (EQ_M (pi2 (pi2 (dec x4 (sk (N 1))))) (m x1))\n                        (if_then_else_M\n                           (EQ_M (reveal x5) (i 1)) &\n                           (EQ_M (m x1) (pk (N 2))) \n                           (N 3)\n                           (if_then_else_M\n                              (EQ_M (reveal x5) (i 2)) &\n                              (EQ_M (m x1) (pk (N 2))) \n                              (N 4) O)) O) O) O)) O)).\nDefinition t26 :=  (if_then_else_M (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)\n         (if_then_else_M\n            ((EQ_M (to x2) (i 1)) & (EQ_M (pi1 (dec x2 (sk (N 1)))) (N 3))) &\n            (EQ_M (pi2 (pi2 (dec x2 (sk (N 1))))) (m x1))\n            (if_then_else_M (EQ_M (to x3) (i 2))\n               (if_then_else_M\n                  (EQ_M (to x4) (i 2)) & (EQ_M (dec x4 (sk (N 2))) (N 4))\n                  (if_then_else_M\n                     (EQ_M (reveal x5) (i 1)) & (EQ_M (m x1) (pk (N 2)))\n                     (N 14)\n                     (if_then_else_M\n                        (EQ_M (reveal x5) (i 2)) & (EQ_M (m x1) (pk (N 2)))\n                        (N 14)\n                        (if_then_else_M\n                           (EQ_M (reveal x5) (i 1)) &\n                           (EQ_M (m x1) (pk (N 2))) \n                           (N 3)\n                           (if_then_else_M\n                              (EQ_M (reveal x5) (i 1)) &\n                              (EQ_M (m x1) (pk (N 2))) \n                              (N 4) O)))) O) O)\n            (if_then_else_M (EQ_M (to x2) (i 2))\n               (if_then_else_M\n                  ((EQ_M (to x3) (i 1)) &\n                   (EQ_M (pi1 (dec x3 (sk (N 1)))) (N 3))) &\n                  (EQ_M (pi2 (pi2 (dec x3 (sk (N 1))))) (m x1))\n                  (if_then_else_M\n                     (EQ_M (to x4) (i 2)) & (EQ_M (dec x4 (sk (N 2))) (N 4))\n                     (if_then_else_M\n                        (EQ_M (reveal x5) (i 1)) & (EQ_M (m x1) (pk (N 2)))\n                        (N 14)\n                        (if_then_else_M\n                           (EQ_M (reveal x5) (i 2)) &\n                           (EQ_M (m x1) (pk (N 2))) \n                           (N 14)\n                           (if_then_else_M\n                              (EQ_M (reveal x5) (i 1)) &\n                              (EQ_M (m x1) (pk (N 2))) \n                              (N 3)\n                              (if_then_else_M\n                                 (EQ_M (reveal x5) (i 1)) &\n                                 (EQ_M (m x1) (pk (N 2))) \n                                 (N 4) O)))) O)\n                  (if_then_else_M\n                     (EQ_M (to x3) (i 2)) & (EQ_M (dec x3 (sk (N 2))) (N 4))\n                     (if_then_else_M\n                        ((EQ_M (to x4) (i 1)) &\n                         (EQ_M (pi1 (dec x4 (sk (N 1)))) (N 3))) &\n                        (EQ_M (pi2 (pi2 (dec x4 (sk (N 1))))) (m x1))\n                        (if_then_else_M\n                           (EQ_M (reveal x5) (i 1)) &\n                           (EQ_M (m x1) (pk (N 2))) \n                           (N 14)\n                           (if_then_else_M\n                              (EQ_M (reveal x5) (i 2)) &\n                              (EQ_M (m x1) (pk (N 2))) \n                              (N 14)\n                              (if_then_else_M\n                                 (EQ_M (reveal x5) (i 1)) &\n                                 (EQ_M (m x1) (pk (N 2))) \n                                 (N 3)\n                                 (if_then_else_M\n                                    (EQ_M (reveal x5) (i 1)) &\n                                    (EQ_M (m x1) (pk (N 2))) \n                                    (N 4) O)))) O) O)) O))\n         (if_then_else_M (EQ_M (to x1) (i 2))\n            (if_then_else_M (EQ_M (to x2) (i 1)) & (EQ_M (act x2) new)\n               (if_then_else_M\n                  ((EQ_M (to x3) (i 1)) &\n                   (EQ_M (pi1 (dec x3 (sk (N 1)))) (N 3))) &\n                  (EQ_M (pi2 (pi2 (dec x3 (sk (N 1))))) (m x1))\n                  (if_then_else_M\n                     (EQ_M (to x4) (i 2)) & (EQ_M (dec x4 (sk (N 2))) (N 4))\n                     (if_then_else_M\n                        (EQ_M (reveal x5) (i 1)) & (EQ_M (m x1) (pk (N 2)))\n                        (N 14)\n                        (if_then_else_M\n                           (EQ_M (reveal x5) (i 2)) &\n                           (EQ_M (m x1) (pk (N 2))) \n                           (N 14)\n                           (if_then_else_M\n                              (EQ_M (reveal x5) (i 1)) &\n                              (EQ_M (m x1) (pk (N 2))) \n                              (N 3)\n                              (if_then_else_M\n                                 (EQ_M (reveal x5) (i 1)) &\n                                 (EQ_M (m x1) (pk (N 2))) \n                                 (N 4) O)))) O)\n                  (if_then_else_M\n                     (EQ_M (to x3) (i 2)) & (EQ_M (dec x3 (sk (N 2))) (N 4))\n                     (if_then_else_M\n                        ((EQ_M (to x4) (i 1)) &\n                         (EQ_M (pi1 (dec x4 (sk (N 1)))) (N 3))) &\n                        (EQ_M (pi2 (pi2 (dec x4 (sk (N 1))))) (m x1))\n                        (if_then_else_M\n                           (EQ_M (reveal x5) (i 1)) &\n                           (EQ_M (m x1) (pk (N 2))) \n                           (N 14)\n                           (if_then_else_M\n                              (EQ_M (reveal x5) (i 2)) &\n                              (EQ_M (m x1) (pk (N 2))) \n                              (N 14)\n                              (if_then_else_M\n                                 (EQ_M (reveal x5) (i 1)) &\n                                 (EQ_M (m x1) (pk (N 2))) \n                                 (N 3)\n                                 (if_then_else_M\n                                    (EQ_M (reveal x5) (i 1)) &\n                                    (EQ_M (m x1) (pk (N 2))) \n                                    (N 4) O)))) O) O))\n               (if_then_else_M\n                  (EQ_M (to x2) (i 2)) & (EQ_M (dec x2 (sk (N 2))) (N 4))\n                  (if_then_else_M (EQ_M (to x3) (i 1)) & (EQ_M (act x3) new)\n                     (if_then_else_M\n                        ((EQ_M (to x4) (i 1)) &\n                         (EQ_M (pi1 (dec x4 (sk (N 1)))) (N 3))) &\n                        (EQ_M (pi2 (pi2 (dec x4 (sk (N 1))))) (m x1))\n                        (if_then_else_M\n                           (EQ_M (reveal x5) (i 1)) &\n                           (EQ_M (m x1) (pk (N 2))) \n                           (N 14)\n                           (if_then_else_M\n                              (EQ_M (reveal x5) (i 2)) &\n                              (EQ_M (m x1) (pk (N 2))) \n                              (N 14)\n                              (if_then_else_M\n                                 (EQ_M (reveal x5) (i 1)) &\n                                 (EQ_M (m x1) (pk (N 2))) \n                                 (N 3)\n                                 (if_then_else_M\n                                    (EQ_M (reveal x5) (i 1)) &\n                                    (EQ_M (m x1) (pk (N 2))) \n                                    (N 4) O)))) O) O) O)) O)).\n", "meta": {"author": "ajayeeralla", "repo": "compSoundProofsWOracleMoves", "sha": "8480855887a9092d16dc183ce6ed19315a3ffa96", "save_path": "github-repos/coq/ajayeeralla-compSoundProofsWOracleMoves", "path": "github-repos/coq/ajayeeralla-compSoundProofsWOracleMoves/compSoundProofsWOracleMoves-8480855887a9092d16dc183ce6ed19315a3ffa96/var_trms_nsl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.25504128996136544}}
{"text": "Require Import Coq.Program.Equality.\nRequire Import Coq.Sets.Ensembles.\nRequire Import Coq.FSets.FMapAVL. \nRequire Import Coq.Structures.OrderedTypeEx.\nRequire Import Coq.Arith.Peano_dec.\nRequire Import Ascii String.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.Arith.Mult.\nRequire Import Coq.Arith.Plus.\nRequire Import Coq.Arith.Minus.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import Keys.\nRequire Import Heap.\nRequire Import Environment.\nRequire Import Definitions2.\nRequire Import CorrectnessLemmas.\n\nLemma Seq_Left_Pres :\n  forall phi1 phi1' heap1 heap1' n1 phi2,\n    (phi1, heap1) =a=>* (phi1', heap1', n1) ->\n    (Phi_Seq phi1 phi2, heap1) =a=>* (Phi_Seq phi1' phi2, heap1', n1).\nProof.\n  intros phi1 phi1' heap1 heap1' n1 phi2 HSteps.\n  dependent induction HSteps; repeat econstructor; eassumption.\nQed.\n\nLemma Seq_Right_Pres :\n  forall phi2 phi2' heap2 heap2' n2,\n    (phi2, heap2) =a=>* (phi2', heap2', n2) ->\n    (Phi_Seq Phi_Nil phi2, heap2) =a=>* (Phi_Seq Phi_Nil phi2', heap2', n2).\nProof.\n  intros phi2 phi2' heap2 heap2' n2 HSteps.\n  dependent induction HSteps; repeat econstructor; eassumption.\nQed.\n\nLemma Par_Left_Pres :\n  forall phi1 phi1' heap1 heap1' n1 phi2,\n    (phi1, heap1) =a=>* (phi1', heap1', n1) ->\n    (Phi_Par phi1 phi2, heap1) =a=>* (Phi_Par phi1' phi2, heap1', n1).\nProof.\n  intros phi1 phi1' heap1 heap1' n1 phi2 HSteps.\n  dependent induction HSteps; repeat econstructor; eassumption.\nQed.\n\nLemma Par_Right_Pres :\n  forall phi2 phi2' heap2 heap2' n2 phi1 ,\n    (phi2, heap2) =a=>* (phi2', heap2', n2) ->\n    (Phi_Par phi1 phi2, heap2) =a=>* (Phi_Par phi1 phi2', heap2', n2).\nProof.\n  intros phi2 phi2' heap2 heap2' n2 phi1 HSteps.\n  dependent induction HSteps; repeat econstructor; eassumption.\nQed.\n\n\n\nLemma H_same_key:\n  forall t x v e, \n    H.find (elt := t) x (H.add x v e) = Some v.\nProof.\n  intros. rewrite <- HMapP.find_mapsto_iff. rewrite -> HMapP.add_mapsto_iff.\n  left. intuition. \nQed.  \n\nLemma H_diff_key_1:\n  forall t a b v v' e,   \n    a <> b ->\n    H.find (elt := t) a (H.add b v e) = Some v' -> \n    H.find (elt := t) a e = Some v'.\nProof.\n  intros. \n  rewrite <- HMapP.find_mapsto_iff in H0. rewrite -> HMapP.add_mapsto_iff in H0.\n  destruct H0 as [ [[? ?] ?] |  [ ? ?]].\n  - destruct a. destruct b. simpl in *. destruct H. subst. reflexivity.\n  - rewrite -> HMapP.find_mapsto_iff in H1. assumption. \nQed.\n\nLemma H_diff_key_2:\n  forall t a b v v' e,   \n    b <> a ->\n    H.find (elt := t) a e = Some v' ->\n    H.find (elt := t) a (H.add b v e) = Some v'.\nProof.\n  intros. \n  rewrite <- HMapP.find_mapsto_iff.  rewrite -> HMapP.add_mapsto_iff.\n  right; split.\n  - intuition. apply H. destruct a. destruct b. simpl in *. subst. reflexivity.\n  - now rewrite HMapP.find_mapsto_iff.\nQed.\n\nLemma H_same_key_add_twice_1 :\n  forall r0 l0 r l v v0 heap, \n    H.find (elt:=Val) (r0, l0) (H.add (r0, l0) v0 (H.add (r, l) v heap)) = H.find (elt:=Val) (r0, l0) (H.add (r0, l0) v0 heap).\nProof.\n  intros. rewrite H_same_key. rewrite H_same_key. reflexivity.\nQed. \n\nLemma H_same_key_add_twice_2 :\n  forall k k0 v v0 heap,\n    k <> k0 ->\n    H.find (elt:=Val) k0 (H.add k v (H.add k0 v0 heap)) = H.find (elt:=Val) k0 (H.add k0 v0 heap).\nProof.\n  intros. rewrite H_same_key. apply H_diff_key_2; [assumption | apply H_same_key]. \nQed.\n\nLemma H_same_key_add_twice_3 :\n  forall k k0 v v0 heap,\n    H.find (elt:=Val) k0 (H.add k0 v0 (H.add k v heap)) = H.find (elt:=Val) k0 (H.add k0 v0 heap).\nProof.\n  intros. rewrite H_same_key. symmetry. apply H_same_key. \nQed. \n\nLemma H_diff_key_add_twice_1 :\n  forall k0 k heap (v v0 e: Val), \n    H.find (elt:=Val) k0 (H.add k0 v0 heap) = Some e ->\n    H.find (elt:=Val) k0 (H.add k0 v0 (H.add k v heap)) = Some e.\nProof.\n  intros k0 k heap v v0 e H.\n  rewrite H_same_key_add_twice_3. assumption.\nQed.\n\nLemma H_diff_key_add_twice_2 :\n  forall k0 k heap (v v0 e: Val),\n    k <> k0 ->\n    H.find (elt:=Val) k (H.add k v heap) = Some e ->\n    H.find (elt:=Val) k (H.add k v (H.add k0 v0 heap)) = Some e.\nProof.\n  intros k0 k heap v v0 e H. intro. \n  rewrite H_same_key_add_twice_3. auto. \nQed.\n\nLemma H_diff_key_add_comm_1:\n  forall k k1 k0 heap e v v0,\n    k1 <> k ->\n    k <> k0 ->\n    H.find (elt:=Val) k (H.add k0 v0 (H.add k1 v heap)) = Some e ->\n    H.find (elt:=Val) k (H.add k1 v heap) = Some e. \nProof.\n  intros  k k1 k0 heap e v v0 H1 H2 H3.\n  rewrite <- HMapP.find_mapsto_iff.  rewrite -> HMapP.add_mapsto_iff.\n  right. split.\n  - contradict H1. destruct k1; destruct k.  unfold fst, snd in *. intuition.\n  - apply  H_diff_key_1 in H3; auto. apply  H_diff_key_1 in H3; auto. now rewrite HMapP.find_mapsto_iff.\nQed.\n\nLemma H_diff_key_add_comm_2:\n  forall k k1 k0 heap e v v0,\n    k1 <> k ->\n    k <> k0 ->\n    H.find (elt:=Val) k (H.add k1 v heap) = Some e ->\n    H.find (elt:=Val) k (H.add k1 v (H.add k0 v0 heap)) = Some e. \nProof.\n  intros  k k1 k0 heap e v v0 H1 H2 H3.\n  rewrite <- HMapP.find_mapsto_iff.  rewrite -> HMapP.add_mapsto_iff.\n  right. split.\n  - contradict H1. destruct k1; destruct k.  unfold fst, snd in *. intuition.\n  - apply  H_diff_key_1 in H3; auto. rewrite HMapP.find_mapsto_iff. apply  H_diff_key_2; auto. \nQed.\n\n\nLemma H_diff_keys_same_outer_k_2 :\n  forall r r0 r1 l l0 l1 v v0  heap e, \n    (r0, l0) <> (r, l) -> \n    H.find (elt:=Val) (r1, l1) (H.add (r, l) v (H.add (r0, l0) v0 heap)) = Some e ->\n    H.find (elt:=Val) (r1, l1) (update_H (r0, l0, v0) (update_H (r, l, v) heap)) = Some e.\nProof.\n  intros  r r0 r1 l l0 l1 v v0 heap e H1 H2. \n  destruct (RegionVars.eq_dec (r1, l1) (r0, l0)); destruct (RegionVars.eq_dec (r1, l1) (r, l)).\n  - destruct e0. simpl in *. subst. unfold update_H in *; simpl in *.\n    apply  H_diff_key_add_twice_2; auto.\n    apply  H_diff_key_1 in H2; auto.\n  - destruct e0. simpl in *. rewrite H in *.  rewrite H0 in *.\n    apply  H_diff_key_1 in H2; auto. apply H_diff_key_add_twice_2; auto.\n  - destruct e0. simpl in *. rewrite H in *.  rewrite H0 in *.\n    apply  H_diff_key_2; auto.\n    rewrite  H_same_key_add_twice_3 in H2; auto.\n  - apply  H_diff_key_2; auto. \n    + unfold  RegionVars.eq in n. contradict n. inversion n. intuition.\n    + apply  H_diff_key_2; auto.\n      * unfold  RegionVars.eq in n0. contradict n0. inversion n0. intuition.\n      * apply  H_diff_key_1 in H2. apply  H_diff_key_1 in H2; auto.\n        { unfold  RegionVars.eq in n. contradict n. inversion n. intuition. }\n        { unfold  RegionVars.eq in n0. contradict n0. inversion n0. intuition. }\nQed.\n\nLemma Read_Preserved :\n  forall r1 l1 v1 phi2 phi2' heap0 heap2',\n    H.find (r1, l1) heap0 = Some v1 ->\n    Disjoint_Traces (phi_as_list (Phi_Elem (DA_Read r1 l1 v1))) (phi_as_list phi2) ->\n    (phi2, heap0) ===> (phi2', heap2') ->\n    H.find (r1, l1) heap2' = Some v1.\nProof.\n  intros r1 l1 v1 phi2 phi2' heap0 heap2' HFind HDisj HStep.\n  dependent induction HStep.\n  - assert (Disjoint_Dynamic (DA_Read r1 l1 v1) (DA_Alloc r l v))\n      by (inversion HDisj; apply H; simpl; intuition).\n    inversion H; subst.\n    apply H_diff_key_2; auto.\n  - assumption.\n  - assert (Disjoint_Dynamic (DA_Read r1 l1 v1) (DA_Write r l v))\n      by (inversion HDisj; apply H0; simpl; intuition).\n    inversion H0; subst.\n    apply H_diff_key_2; auto.\n  - eapply IHHStep; try reflexivity.\n    + eassumption.\n    + replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0) in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj; intuition.\n  - eapply IHHStep; try reflexivity.\n    + eassumption.\n    + replace (phi_as_list (Phi_Seq Phi_Nil phi0)) with (phi_as_list Phi_Nil ++ phi_as_list phi0) in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj; intuition.\n  - assumption.\n  - eapply IHHStep; try reflexivity.\n    + eassumption.\n    + replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0) in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj; intuition.\n  - eapply IHHStep; try reflexivity.\n    + eassumption.\n    + replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0) in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj; intuition.\n  - assumption.\nQed.\n\nLemma Disjointness_Preserves_Update_Alloc:\n  forall phi1 phi1' heap heap' r l v, \n  (phi1, heap) ===> (phi1', heap') ->\n  Disjoint_Traces (DA_Alloc r l v :: nil) (phi_as_list phi1) ->\n  exists heapA,\n    H.Equal heapA (update_H (r, l, v) heap') /\\\n    (phi1, update_H (r, l, v) heap) ===> (phi1', heapA).\nProof.\n  intros phi1 phi1' heap heap' r l v H1 H2.\n  generalize dependent r.\n  generalize dependent l.\n  generalize dependent v. \n  dependent induction H1; intros; inversion H2; subst; simpl in H.\n  - assert (Disjoint_Dynamic (DA_Alloc r0 l0 v0) (DA_Alloc r l v)) by (apply H; intuition).\n    inversion H0; subst. \n    exists (update_H (r, l, v) (update_H (r0, l0, v0) heap)). split. \n    + apply HMapP.Equal_mapsto_iff; intros. split; intros. \n      * apply HMapP.find_mapsto_iff. apply HMapP.find_mapsto_iff in H1.\n        destruct k; apply H_diff_keys_same_outer_k_2; auto.\n      * apply HMapP.find_mapsto_iff. apply HMapP.find_mapsto_iff in H1.\n        destruct k.  apply H_diff_keys_same_outer_k_2; auto.\n    + constructor.\n  - assert (Disjoint_Dynamic (DA_Alloc r0 l0 v0) (DA_Read r l v)) by (apply H0; apply in_eq).\n    inversion H1; subst. exists ( update_H (r0, l0, v0) heap'). split.\n    + apply HMapP.Equal_refl.\n    + constructor.\n      apply  H_diff_key_2; [ simpl | ]; assumption.\n  - assert (Disjoint_Dynamic (DA_Alloc r0 l0 v0) (DA_Write r l v)) by (apply H0; apply in_eq).\n    inversion H1; subst. unfold update_H; simpl. \n    exists (H.add (r, l) v ( H.add (r0, l0) v0 heap)). split. \n    + apply HMapP.Equal_mapsto_iff; intros. split; intros. \n      * apply HMapP.find_mapsto_iff. apply HMapP.find_mapsto_iff in H3.\n        destruct k; apply H_diff_keys_same_outer_k_2; auto.\n      * apply HMapP.find_mapsto_iff. apply HMapP.find_mapsto_iff in H3.\n        destruct k; apply H_diff_keys_same_outer_k_2; auto.\n    + constructor.\n      apply HMapP.add_neq_in_iff; auto. simpl. intuition.\n      (*eapply H_diff_key_2; eauto.*)\n  - simpl in H2. replace (DA_Alloc r l v :: nil) with (phi_as_list (Phi_Elem (DA_Alloc r l v))) in H2\n      by (simpl; reflexivity).\n    apply Disjointness_app_app_and_l in H2. destruct H2.\n    destruct (IHPhi_Heap_Step  v l r H0). exists x; intuition.\n    constructor; assumption.\n  - destruct (IHPhi_Heap_Step  v l r H2). exists x; intuition.\n    constructor; assumption.\n  - exists (update_H (r, l, v) heap'). split; [apply HMapP.Equal_refl | constructor ].\n  - simpl in H2. replace (DA_Alloc r l v :: nil) with (phi_as_list (Phi_Elem (DA_Alloc r l v))) in H2\n      by (simpl; reflexivity).\n    apply Disjointness_app_app_and_l in H2. destruct H2.\n    destruct (IHPhi_Heap_Step  v l r H0). exists x; intuition.\n    constructor; assumption.\n  -  simpl in H2. replace (DA_Alloc r l v :: nil) with (phi_as_list (Phi_Elem (DA_Alloc r l v))) in H2\n      by (simpl; reflexivity).\n    apply Disjointness_app_app_and_l in H2. destruct H2.\n    destruct (IHPhi_Heap_Step  v l r H2). exists x; intuition.\n    constructor; assumption.\n  - exists (update_H (r, l, v) heap'). split; [apply HMapP.Equal_refl | constructor ].\nQed.\n\nLemma Disjointness_Preserves_Update_Write:\n  forall phi1 phi1' heap heap' r l v, \n  (phi1, heap) ===> (phi1', heap') ->\n  Disjoint_Traces (DA_Write r l v :: nil) (phi_as_list phi1) ->\n  exists heapA,\n    H.Equal heapA (update_H (r, l, v) heap') /\\\n    (phi1, update_H (r, l, v) heap) ===> (phi1', heapA).\nProof.\n  intros phi1 phi1' heap heap' r l v H1 H2.\n  generalize dependent r.\n  generalize dependent l.\n  generalize dependent v.\n  dependent induction H1; intros; inversion H2; subst; simpl in H.\n  - assert (Disjoint_Dynamic (DA_Write r0 l0 v0) (DA_Alloc r l v)) by (apply H; intuition).\n    inversion H0; subst. \n    exists (update_H (r, l, v) (update_H (r0, l0, v0) heap)). split. \n    + apply HMapP.Equal_mapsto_iff; intros. split; intros. \n      * apply HMapP.find_mapsto_iff. apply HMapP.find_mapsto_iff in H1.\n        destruct k; apply H_diff_keys_same_outer_k_2; auto.\n      * apply HMapP.find_mapsto_iff. apply HMapP.find_mapsto_iff in H1.\n        destruct k.  apply H_diff_keys_same_outer_k_2; auto.\n    + constructor.\n  - assert (Disjoint_Dynamic (DA_Write r0 l0 v0) (DA_Read r l v)) by (apply H0; apply in_eq).\n    inversion H1; subst. exists ( update_H (r0, l0, v0) heap'). split.\n    + apply HMapP.Equal_refl.\n    + constructor.\n      apply  H_diff_key_2; [ intuition | assumption ]. \n  - assert (Disjoint_Dynamic (DA_Write r0 l0 v0) (DA_Write r l v)) by (apply H0; apply in_eq).\n    inversion H1; subst. unfold update_H; simpl. \n    exists (H.add (r, l) v ( H.add (r0, l0) v0 heap)). split. \n    + apply HMapP.Equal_mapsto_iff; intros. split; intros. \n      * apply HMapP.find_mapsto_iff. apply HMapP.find_mapsto_iff in H3.\n        destruct k; apply H_diff_keys_same_outer_k_2; auto.\n      * apply HMapP.find_mapsto_iff. apply HMapP.find_mapsto_iff in H3.\n        destruct k; apply H_diff_keys_same_outer_k_2; auto.\n    + constructor.\n      apply HMapP.add_neq_in_iff; auto. simpl. intuition.\n      (*eapply H_diff_key_2; eauto.*)\n  - simpl in H2. replace (DA_Write r l v :: nil) with (phi_as_list (Phi_Elem (DA_Write r l v))) in H2\n      by (simpl; reflexivity).\n    apply Disjointness_app_app_and_l in H2. destruct H2.\n    destruct (IHPhi_Heap_Step  v l r H0). exists x; intuition.\n    constructor; assumption.\n  - destruct (IHPhi_Heap_Step  v l r H2). exists x; intuition.\n    constructor; assumption.\n  - exists (update_H (r, l, v) heap'). split; [apply HMapP.Equal_refl | constructor ].\n  - simpl in H2. replace (DA_Write r l v :: nil) with (phi_as_list (Phi_Elem (DA_Write r l v))) in H2\n      by (simpl; reflexivity).\n    apply Disjointness_app_app_and_l in H2. destruct H2.\n    destruct (IHPhi_Heap_Step  v l r H0). exists x; intuition.\n    constructor; assumption.\n  -  simpl in H2. replace (DA_Write r l v :: nil) with (phi_as_list (Phi_Elem (DA_Write r l v))) in H2\n      by (simpl; reflexivity).\n    apply Disjointness_app_app_and_l in H2. destruct H2.\n    destruct (IHPhi_Heap_Step  v l r H2). exists x; intuition.\n    constructor; assumption.\n  - exists (update_H (r, l, v) heap'). split; [apply HMapP.Equal_refl | constructor ].\nQed.\n\nLemma Aux_Aux_Step_Ext_Heap :\nforall phi heapA heapB phi' heapA',\n   (phi, heapA) ===> (phi', heapA') ->\n   H.Equal heapA heapB ->\n   exists heapB',\n     H.Equal heapA' heapB' /\\\n     (phi, heapB) ===> (phi', heapB').\nProof.\n  intros phi heapA heapB phi' heapA' HStep.\n  generalize dependent heapB.\n  dependent induction HStep; intros heapB HEqual.\n  - { exists (update_H (r, l, v) heapB). split.\n      - unfold H.Equal in *; unfold update_H in *; simpl in *.\n        intros [r' l'].\n        destruct (RegionVars.eq_dec (r', l') (r, l)).\n        * inversion_clear e; simpl in *; subst.\n          do 2 rewrite H_same_key_1. reflexivity.\n        * unfold RegionVars.eq in *; simpl in *.\n          rewrite HMapP.add_neq_o by (contradict n; intuition).\n          rewrite HMapP.add_neq_o by (contradict n; intuition).\n          apply HEqual.\n      - constructor. }\n  - { exists heapB. split.\n      - assumption.\n      - constructor.\n        unfold find_H in *. unfold H.Equal in HEqual.\n        rewrite <- H. symmetry. apply HEqual. }\n  - { exists (update_H (r, l, v) heapB). split.\n      - unfold H.Equal in *; unfold update_H in *; simpl in *.\n        intros [r' l'].\n        destruct (RegionVars.eq_dec (r', l') (r, l)).\n        * inversion_clear e; simpl in *; subst.\n          do 2 rewrite H_same_key_1. reflexivity.\n        * unfold RegionVars.eq in *; simpl in *.\n          rewrite HMapP.add_neq_o by (contradict n; intuition).\n          rewrite HMapP.add_neq_o by (contradict n; intuition).\n          apply HEqual.\n      - constructor.\n        eapply Heap.HMapP.In_m; eauto using HMapP.Equal_sym. }\n  - destruct (IHHStep heapB HEqual) as [heapB' [? ?]].\n    exists heapB'; split; [assumption | constructor; auto].\n  - destruct (IHHStep heapB HEqual) as [heapB' [? ?]].\n    exists heapB'; split; [assumption | constructor; auto].\n  - exists heapB; split; [assumption | constructor].\n  - destruct (IHHStep heapB HEqual) as [heapB' [? ?]].\n    exists heapB'; split; [assumption | constructor; auto].\n  - destruct (IHHStep heapB HEqual) as [heapB' [? ?]].\n    exists heapB'; split; [assumption | constructor; auto].\n  - exists heapB; split; [assumption | constructor].\nQed.\n\nLemma Aux_Step_Ext_Heap :\nforall phi heapA heapB phi' heapA' n',\n   (phi, heapA) =a=>* (phi', heapA', n') ->\n   H.Equal heapA heapB ->\n   exists heapB',\n     H.Equal heapA' heapB' /\\\n     (phi, heapB) =a=>* (phi', heapB', n').\nProof.\n  intros  phi heapA heapB phi' heapA' n' H1 H2 .  \n  generalize dependent heapB. \n  dependent induction H1; intros.\n  - { exists heapB. intuition. constructor. }\n  - edestruct Aux_Aux_Step_Ext_Heap as [heapB' [? ?]]; eauto.\n    exists heapB'; split; [assumption | constructor; assumption].\n  - edestruct (IHPhi_Heap_StepsAux1 heapB H2) as [heap1 [? ?]].\n    edestruct (IHPhi_Heap_StepsAux2 heap1 H) as [heap2 [? ?]].\n    exists heap2. intuition.\n    replace (S (n'0 + n'')) with (1 + n'0 + n'') by (simpl; reflexivity).\n    econstructor. eassumption. assumption.\nQed.\n\nLemma Par_Step_Alloc_Alloc :\n  forall phi1 r1 l1 v1 phi2 r2 l2 v2 phi1' phi2' heapa heapb heap1' heap2',\n    phi1 = Phi_Elem (DA_Alloc r1 l1 v1) ->\n    phi2 = Phi_Elem (DA_Alloc r2 l2 v2) ->\n    Det_Trace phi1 ->\n    Det_Trace phi2 ->\n    Disjoint_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    H.Equal heapa heapb ->\n    (phi1, heapa) ===> (phi1', heap1') ->\n    (phi2, heapb) ===> (phi2', heap2') ->\n    exists heapA, exists heapB,\n      H.Equal heapA heapB /\\\n      (Phi_Par phi1' phi2, heap1') ===> (Phi_Par phi1' phi2', heapA) /\\\n      (Phi_Par phi1 phi2', heap2') ===> (Phi_Par phi1' phi2', heapB).\nProof.\n  intros  phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2'\n          H1 H2 Det1 HDet2 HDisj HConf HEqual HStep1 HStep2; subst.\n  inversion HStep1; inversion HStep2; subst.\n  exists (update_H (r0, l0, v0) (update_H (r, l, v) heapa)). exists (update_H (r, l, v) (update_H (r0, l0, v0) heapb)). repeat split. \n  - inversion HDisj; subst. simpl in H. \n    assert (Disjoint_Dynamic (DA_Alloc r l v) (DA_Alloc r0 l0 v0)) by (apply H; left; reflexivity).\n    inversion H0; subst. unfold update_H in *. simpl in *.\n    inversion H0; subst. unfold update_H in *. simpl in *. \n\n    destruct (RegionVars.eq_dec (r, l) (r0, l0)).\n    + inversion e. unfold fst, snd in *; subst.\n      destruct H2. reflexivity.\n    + clear n. \n      apply HMapP.Equal_mapsto_iff; intros. destruct k.\n      destruct (RegionVars.eq_dec (n, n0) (r0, l0)); destruct (RegionVars.eq_dec (n, n0) (r, l)); split.\n      * inversion e0; inversion e1. unfold fst, snd in *; subst.\n        destruct H2. subst; reflexivity.\n      * inversion e0; inversion e1. unfold fst, snd in *; subst.\n        destruct H2. subst; reflexivity.\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.\n        intro. apply  HMapP.find_mapsto_iff in H1.\n        rewrite H_same_key_add_twice_1 in H1. rewrite H_same_key in H1.\n        apply HMapP.add_mapsto_iff. right; simpl. split; [ intuition | ].\n        apply HMapP.find_mapsto_iff. rewrite H_same_key. assumption.\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst. \n        intro. apply  HMapP.find_mapsto_iff in H1. rewrite H_same_key_add_twice_2 in H1; [| assumption].\n        { rewrite H_same_key in H1.  apply  HMapP.find_mapsto_iff.\n          inversion H1; subst. rewrite H_same_key_add_twice_1. rewrite H_same_key. assumption. }\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.  \n        intro. apply HMapP.add_mapsto_iff. left. simpl. split; auto.   \n        apply  HMapP.find_mapsto_iff in H1.  rewrite H_same_key_add_twice_2 in H1; [| intuition].\n        rewrite HMapP.add_o in H1. \n        destruct (HMapP.eq_dec (r, l) (r, l)) in H1. \n        { inversion H1; subst. auto.  }\n        { simpl in *. contradict n. auto. } \n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst. \n        intro.  apply HMapP.add_mapsto_iff. right. split; simpl; [intuition |].\n        apply HMapP.add_mapsto_iff. left; simpl; split; auto.\n        apply HMapP.add_mapsto_iff in H1.\n        destruct H1 as [[? ?]| ?]; [assumption | destruct H1 as [? ?  ?]; contradict H1; auto].\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst.\n        intro. apply  HMapP.find_mapsto_iff in H1.\n        apply  HMapP.find_mapsto_iff.\n        { eapply H_diff_key_add_comm_2.\n          - contradict n2. inversion n2. auto.\n          - contradict n1. inversion n1. auto.\n          - apply H_diff_key_2.\n            + contradict n2. inversion n2. auto.\n            + rewrite <- H1. unfold H.Equal in HEqual. rewrite <- HEqual.\n              rewrite H1. apply H_diff_key_1 in H1.\n              * apply H_diff_key_1 in H1; [assumption | contradict n1; inversion n1; intuition].\n              * contradict n1; inversion n1; intuition.\n        }\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst.\n        intro. apply  HMapP.find_mapsto_iff in H1.\n        apply  HMapP.find_mapsto_iff.\n        { eapply H_diff_key_add_comm_2.\n          - contradict n1. inversion n1. auto.\n          - contradict n2. inversion n2. auto.\n          - apply H_diff_key_2.\n            + contradict n1. inversion n1. auto.\n            + rewrite <- H1. unfold H.Equal in HEqual. rewrite HEqual.\n              rewrite H1. apply H_diff_key_1 in H1.\n              * apply H_diff_key_1 in H1; [assumption | contradict n1; inversion n1; intuition].\n              * contradict n1; inversion n1; intuition.\n        }\n  - do 2 constructor.    \n  - econstructor. inversion HDisj; subst.\n    assert (Disjoint_Dynamic (DA_Alloc r l v) (DA_Alloc r0 l0 v0)) by (apply H; simpl; auto).\n    inversion H0; subst. \n    eapply Disjointness_Preserves_Update_Alloc in HStep2; eauto.\n    destruct HStep2 as [heap' [? ?]]. inversion H0; subst. unfold H.Equal in H1.\n    inversion H3; subst.\n    unfold update_H in *; simpl in *.\n    admit.  \nQed.\n\nLemma Par_Step_Write_Write :\n  forall phi1 r1 l1 v1 phi2 r2 l2 v2 phi1' phi2' heapa heapb heap1' heap2',\n    phi1 = Phi_Elem (DA_Write r1 l1 v1) ->\n    phi2 = Phi_Elem (DA_Write r2 l2 v2) ->\n    Det_Trace phi1 ->\n    Det_Trace phi2 ->\n    Disjoint_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    H.Equal heapa heapb ->\n    (phi1, heapa) ===> (phi1', heap1') ->\n    (phi2, heapb) ===> (phi2', heap2') ->\n    exists heapA, exists heapB,\n      H.Equal heapA heapB /\\\n      (Phi_Par phi1' phi2, heap1') ===> (Phi_Par phi1' phi2', heapA) /\\\n      (Phi_Par phi1 phi2', heap2') ===> (Phi_Par phi1' phi2', heapB).\nProof.\n  intros  phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2'\n          H1 H2 Det1 HDet2 HDisj HConf HEqual HStep1 HStep2; subst.\n  inversion HStep1; inversion HStep2; subst.\n  exists (update_H (r0, l0, v0) (update_H (r, l, v) heapa)). exists (update_H (r, l, v) (update_H (r0, l0, v0) heapb)). repeat split. \n  -  inversion HDisj; subst. simpl in H. \n    assert (Disjoint_Dynamic (DA_Write r l v) (DA_Write r0 l0 v0)) by (apply H; left; reflexivity).\n    inversion H1; subst. unfold update_H in *. simpl in *.\n    inversion H1; subst. unfold update_H in *. simpl in *. \n    destruct (RegionVars.eq_dec (r, l) (r0, l0)).\n    + inversion e. unfold fst, snd in *; subst.\n      inversion H1; subst. contradict H5. intuition.\n    + clear n. \n      apply HMapP.Equal_mapsto_iff; intros. destruct k.\n      destruct (RegionVars.eq_dec (n, n0) (r0, l0)); destruct (RegionVars.eq_dec (n, n0) (r, l)); split.\n      * inversion e0; inversion e1. unfold fst, snd in *; subst.\n        inversion H1; subst. contradict H5. intuition.\n      * inversion e0; inversion e1. unfold fst, snd in *; subst.\n        inversion H1; subst. contradict H5. intuition.\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.\n        intro. apply  HMapP.find_mapsto_iff in H2.\n        rewrite H_same_key_add_twice_1 in H2. rewrite H_same_key in H2.\n        apply HMapP.add_mapsto_iff. right; simpl. split; [ intuition | ].\n        apply HMapP.find_mapsto_iff. rewrite H_same_key. assumption.\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.\n        intro. apply  HMapP.find_mapsto_iff in H2. rewrite H_same_key_add_twice_2 in H2.\n        { rewrite H_same_key in H2.  apply  HMapP.find_mapsto_iff.\n          inversion H2; subst. rewrite H_same_key_add_twice_1. rewrite H_same_key. assumption. }\n        { contradict n1. inversion n1. intuition. }\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.\n        intro. apply  HMapP.find_mapsto_iff in H2. rewrite H_same_key_add_twice_2 in H2.\n        { apply HMapP.add_mapsto_iff. left. simpl. split; auto.\n          rewrite HMapP.add_o in H2. \n          destruct (HMapP.eq_dec (r, l) (r, l)) in H2;\n          [inversion H2; subst;  reflexivity |  simpl in n; contradict n; auto]. }\n        { contradict n1. inversion n1. intuition. }\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.\n        intro. apply  HMapP.find_mapsto_iff in H2. rewrite H_same_key_add_twice_1 in H2. apply  HMapP.find_mapsto_iff in H2.  \n        apply  HMapP.find_mapsto_iff.\n        apply H_diff_key_2; [contradict H3; assumption | ].\n        apply HMapP.find_mapsto_iff.\n        apply HMapP.add_mapsto_iff. left; simpl. split; auto.\n        apply HMapP.add_mapsto_iff in H2.\n        destruct H2 as [ [ ?  ?] | [? ?] ]; [assumption | contradict H2; intuition]. \n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst.\n        intro. apply  HMapP.find_mapsto_iff in H2.\n        apply  HMapP.find_mapsto_iff.\n        { eapply H_diff_key_add_comm_2.\n          - contradict n2. inversion n2. auto.\n          - contradict n1. inversion n1. auto.\n          - apply H_diff_key_2.\n            + contradict n2. inversion n2. auto.\n            + unfold H.Equal in HEqual. rewrite <- HEqual.\n              apply H_diff_key_1 in H2.\n              * apply H_diff_key_1 in H2; [assumption | contradict n2; inversion n2; auto]. \n              * contradict n1; inversion n1; auto.\n        }\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst.\n        intro. apply  HMapP.find_mapsto_iff in H2.\n        apply  HMapP.find_mapsto_iff.\n        { eapply H_diff_key_add_comm_2.\n          - contradict n1. inversion n1. auto.\n          - contradict n2. inversion n2. auto.\n          - apply H_diff_key_2.\n            + contradict n1. inversion n1. auto.\n            +unfold H.Equal in HEqual. rewrite HEqual.\n              apply H_diff_key_1 in H2.\n              * apply H_diff_key_1 in H2; [assumption | contradict n1; inversion n1; intuition].\n              * contradict n1; inversion n1; intuition.\n        }        \n  - do 2 constructor.\n    inversion HDisj; subst. simpl in H. \n    assert (Disjoint_Dynamic (DA_Write r l v) (DA_Write r0 l0 v0)) by (apply H; left; reflexivity).\n    inversion H1; subst. apply HMapP.add_neq_in_iff; auto; [simpl; intuition | ].\n    apply HMapP.Equal_Equiv in HEqual. inversion HEqual. apply H2. assumption.\n  - do 2 constructor.\n    inversion HDisj; subst. simpl in H. \n    assert (Disjoint_Dynamic (DA_Write r l v) (DA_Write r0 l0 v0)) by (apply H; left; reflexivity).\n    inversion H1; subst. apply HMapP.add_neq_in_iff; auto; [simpl; intuition | ].\n    apply HMapP.Equal_Equiv in HEqual. inversion HEqual. apply H2. assumption.\nQed.\n\nLemma Par_Step_Alloc_Read :\n  forall phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2',\n    phi1 = Phi_Elem (DA_Alloc r l v) ->\n    phi2 = Phi_Elem (DA_Read r0 l0 v0) -> \n    Det_Trace phi1 ->\n    Det_Trace phi2 ->\n    Disjoint_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    H.Equal heapa heapb ->\n    (phi1, heapa) ===> (phi1', heap1') ->\n    (phi2, heapb) ===> (phi2', heap2') ->\n    exists heapA heapB,\n      H.Equal heapA heapB /\\\n      (Phi_Par phi1' phi2, heap1') ===> (Phi_Par phi1' phi2', heapA) /\\\n      (Phi_Par phi1 phi2', heap2') ===> (Phi_Par phi1' phi2', heapB).\nProof.\n  intros  phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2'\n          H1 H2 Det1 HDet2 HDisj HConf HEqual HStep1 HStep2; subst.\n  inversion HStep1; inversion HStep2; subst.\n  edestruct Aux_Aux_Step_Ext_Heap as [heapB' [? ?]]; eauto. \n  exists (update_H (r, l, v) heapa); exists heapB'; repeat split.\n  - assumption.\n  - do 2 constructor.\n    inversion HDisj; subst. simpl in H. \n    assert (Disjoint_Dynamic (DA_Alloc r l v) (DA_Read r0 l0 v0)) by (apply H1; left; reflexivity).\n    inversion H2; subst. eapply H_diff_key_2; eauto.\n    unfold H.Equal in HEqual. rewrite HEqual. assumption.\n  - constructor. assumption.\nQed.\n\nLemma Par_Step_Write_Read :\n  forall phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2',\n    phi1 = Phi_Elem (DA_Write r l v) ->\n    phi2 = Phi_Elem (DA_Read r0 l0 v0) -> \n    Det_Trace phi1 ->\n    Det_Trace phi2 ->\n    Disjoint_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    H.Equal heapa heapb ->\n    (phi1, heapa) ===> (phi1', heap1') ->\n    (phi2, heapb) ===> (phi2', heap2') ->\n    exists heapA heapB,\n      H.Equal heapA heapB /\\\n      (Phi_Par phi1' phi2, heap1') ===> (Phi_Par phi1' phi2', heapA) /\\\n      (Phi_Par phi1 phi2', heap2') ===> (Phi_Par phi1' phi2', heapB).\nProof.\n  intros  phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2'\n          H1 H2 Det1 HDet2 HDisj HConf HEqual HStep1 HStep2; subst.\n  inversion HStep1; inversion HStep2; subst.\n  edestruct Aux_Aux_Step_Ext_Heap as [heapB' [? ?]]; eauto. \n  exists (update_H (r, l, v) heapa); exists heapB'; repeat split.\n  - assumption.\n  - do 2 constructor. \n    inversion HDisj; subst. simpl in H. \n    assert (Disjoint_Dynamic (DA_Write r l v) (DA_Read r0 l0 v0)) by (apply H2; left; reflexivity).\n    inversion H3; subst. eapply H_diff_key_2; eauto.\n    unfold H.Equal in HEqual. rewrite HEqual. assumption.\n  - constructor. assumption.\nQed.\n\nLemma Par_Step_Read_Alloc :\n  forall phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2',\n    phi1 = Phi_Elem (DA_Read r l v) ->\n    phi2 = Phi_Elem (DA_Alloc r0 l0 v0) -> \n    Det_Trace phi1 ->\n    Det_Trace phi2 ->\n    Disjoint_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    H.Equal heapa heapb ->\n    (phi1, heapa) ===> (phi1', heap1') ->\n    (phi2, heapb) ===> (phi2', heap2') ->\n    exists heapA heapB,\n      H.Equal heapA heapB /\\\n      (Phi_Par phi1' phi2, heap1') ===> (Phi_Par phi1' phi2', heapA) /\\\n      (Phi_Par phi1 phi2', heap2') ===> (Phi_Par phi1' phi2', heapB).\nProof.\n  intros  phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2'\n          H1 H2 Det1 HDet2 HDisj HConf HEqual HStep1 HStep2; subst.\n  inversion HStep1; inversion HStep2; subst. \n  edestruct Aux_Aux_Step_Ext_Heap as [heapB' [? ?]]; eauto.\n  apply HMapP.Equal_sym in HEqual. assert (H.Equal heapb heapB') by (eapply HMapP.Equal_trans; eauto).\n  exists (update_H (r0, l0, v0) heap1'); exists (update_H (r0, l0, v0) heapb); repeat split.\n  - unfold H.Equal; intros [r1 l1]. apply HMapP.Equal_sym in HEqual. unfold H.Equal in HEqual.\n    destruct (RegionVars.eq_dec (r1, l1) (r0, l0));  unfold update_H; simpl.\n    + inversion e; simpl in *; subst. rewrite H_same_key. rewrite H_same_key. reflexivity.\n    + unfold RegionVars.eq in n.  simpl in n.\n      rewrite HMapP.add_neq_o.\n      * rewrite HMapP.add_neq_o; simpl; [apply HEqual | contradict n; intuition].\n      * contradict n; intuition.\n  - inversion HDisj; subst. simpl in H. \n    assert (Disjoint_Dynamic (DA_Read r l v) (DA_Alloc r0 l0 v0)) by (apply H3; left; reflexivity).\n    inversion H4; subst. constructor. constructor.\n  - do 2 constructor. inversion HStep2; subst.\n    inversion HDisj; subst. simpl in H. \n    assert (Disjoint_Dynamic (DA_Read r l v) (DA_Alloc r0 l0 v0)) by (apply H3; left; reflexivity).\n    inversion H4; subst.\n    eapply H_diff_key_2; auto.\n    unfold H.Equal in HEqual. rewrite HEqual. assumption.\nQed.\n\nLemma Par_Step_Read_Write :\n  forall phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2',\n    phi1 = Phi_Elem (DA_Read r l v) ->\n    phi2 = Phi_Elem (DA_Write r0 l0 v0) -> \n    Det_Trace phi1 ->\n    Det_Trace phi2 ->\n    Disjoint_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    H.Equal heapa heapb ->\n    (phi1, heapa) ===> (phi1', heap1') ->\n    (phi2, heapb) ===> (phi2', heap2') ->\n    exists heapA heapB,\n      H.Equal heapA heapB /\\\n      (Phi_Par phi1' phi2, heap1') ===> (Phi_Par phi1' phi2', heapA) /\\\n      (Phi_Par phi1 phi2', heap2') ===> (Phi_Par phi1' phi2', heapB).\nProof.\n  intros  phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2'\n          H1 H2 Det1 HDet2 HDisj HConf HEqual HStep1 HStep2; subst.\n  inversion HStep1; inversion HStep2; subst.\n  edestruct Aux_Aux_Step_Ext_Heap as [heapB' [? ?]]; eauto.\n  exists (update_H (r0, l0, v0) heap1'); exists (update_H (r0, l0, v0) heapb); repeat split.\n  -  unfold H.Equal; intros [r1 l1]. unfold H.Equal in HEqual.\n    destruct (RegionVars.eq_dec (r1, l1) (r0, l0));  unfold update_H; simpl.\n    + inversion e; simpl in *; subst. rewrite H_same_key. rewrite H_same_key. reflexivity.\n    + unfold RegionVars.eq in n.  simpl in n.\n      rewrite HMapP.add_neq_o.\n      * rewrite HMapP.add_neq_o; simpl; [apply HEqual | contradict n; intuition].\n      * contradict n; intuition.\n  - inversion HDisj; subst. simpl in H. \n    assert (Disjoint_Dynamic (DA_Read r l v) (DA_Write r0 l0 v0)) by (apply H2; left; reflexivity).\n    inversion H3; subst. constructor.  constructor.\n    apply HMapP.Equal_sym in HEqual.\n    apply HMapP.Equal_Equiv in HEqual. inversion HEqual. now apply HEqual.\n  - do 2 constructor. inversion HStep2; subst.\n    inversion HDisj; subst. simpl in H. \n    assert (Disjoint_Dynamic (DA_Read r l v) (DA_Write r0 l0 v0)) by (apply H2; left; reflexivity).\n    inversion H4; subst.\n    eapply H_diff_key_2; auto. unfold H.Equal in HEqual. rewrite <- H0.\n    symmetry; apply HEqual.\nQed.\n\nLemma Par_Step_Alloc_Write :\n  forall phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2',\n    phi1 = Phi_Elem (DA_Alloc r l v) ->\n    phi2 = Phi_Elem (DA_Write r0 l0 v0) -> \n    Det_Trace phi1 ->\n    Det_Trace phi2 ->\n    Disjoint_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    H.Equal heapa heapb ->\n    (phi1, heapa) ===> (phi1', heap1') ->\n    (phi2, heapb) ===> (phi2', heap2') ->\n    exists heapA heapB,\n      H.Equal heapA heapB /\\\n      (Phi_Par phi1' phi2, heap1') ===> (Phi_Par phi1' phi2', heapA) /\\\n      (Phi_Par phi1 phi2', heap2') ===> (Phi_Par phi1' phi2', heapB).\nProof.\n  intros  phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2'\n          H1 H2 Det1 HDet2 HDisj HConf HEqual HStep1 HStep2; subst.\n  inversion HStep1; inversion HStep2; subst. \n  exists (update_H (r0, l0, v0) (update_H (r, l, v) heapa)). exists (update_H (r, l, v) (update_H (r0, l0, v0) heapb)). repeat split.\n  - inversion HDisj; subst. \n    assert (Disjoint_Dynamic (DA_Alloc r l v) (DA_Write r0 l0 v0)) by (apply H; left; reflexivity).\n    inversion H0; subst. unfold update_H in *. simpl in *. \n    destruct (RegionVars.eq_dec (r, l) (r0, l0)).\n    + inversion e. unfold fst, snd in *; subst.\n      contradict H2. intuition.\n    + clear n. \n      apply HMapP.Equal_mapsto_iff; intros. destruct k.\n      destruct (RegionVars.eq_dec (n, n0) (r0, l0)); destruct (RegionVars.eq_dec (n, n0) (r, l)); split.\n      * inversion e0; inversion e1. unfold fst, snd in *; do 2 subst. \n        contradict H2. intuition.\n      * inversion e0; inversion e1. unfold fst, snd in *; do 2subst.\n        contradict H2. intuition.\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.\n        intro. apply  HMapP.find_mapsto_iff in H1.\n        rewrite H_same_key_add_twice_1 in H1. rewrite H_same_key in H1.\n        apply HMapP.add_mapsto_iff. right. intuition. inversion H1; subst.\n        apply HMapP.find_mapsto_iff. apply H_same_key.\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.\n        intro. apply  HMapP.find_mapsto_iff in H1. rewrite H_same_key_add_twice_2 in H1.\n        rewrite H_same_key in H1.\n        apply HMapP.find_mapsto_iff. inversion H1. rewrite <- H4.\n        apply H_same_key. assumption.\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.\n        intro. apply  HMapP.find_mapsto_iff in H1. rewrite H_same_key_add_twice_2 in H1.\n        { apply HMapP.add_mapsto_iff. left; simpl. split; auto.\n          rewrite HMapP.add_o in H1. \n          destruct (HMapP.eq_dec (r, l) (r, l)) in H1; [inversion H1; subst |  simpl in n; contradict n; auto].\n          reflexivity.\n        }\n        { contradict n1. inversion n1. intuition. }\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.\n        intro. apply  HMapP.find_mapsto_iff in H1. rewrite H_same_key_add_twice_1 in H1. \n        apply  HMapP.find_mapsto_iff in H1.  \n        apply  HMapP.find_mapsto_iff. \n        apply H_diff_key_2; [ contradict H2; auto | ].\n        apply HMapP.find_mapsto_iff.\n        apply HMapP.add_mapsto_iff. left; simpl. split; auto.\n        apply HMapP.add_mapsto_iff in H1.\n        destruct H1 as [ [ ?  ?] | [? ?] ]; [assumption | contradict H2; intuition]. \n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst.\n        intro. apply  HMapP.find_mapsto_iff in H1.\n        apply  HMapP.find_mapsto_iff.\n        { eapply H_diff_key_add_comm_2. \n          - contradict n1. inversion n1. intuition.\n          - contradict n2. inversion n2. intuition.\n          - apply H_diff_key_2.\n            + contradict n1. inversion n1. intuition.\n            + unfold H.Equal in HEqual. rewrite <- HEqual.\n              apply H_diff_key_1 in H1.\n              * apply H_diff_key_1 in H1; [assumption | contradict n2; inversion n2; auto]. \n              * contradict n1; inversion n1; auto.\n        }\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst.\n        intro. apply  HMapP.find_mapsto_iff in H1.\n        apply  HMapP.find_mapsto_iff.\n        { eapply H_diff_key_add_comm_2.\n          - contradict n1. inversion n1. auto.\n          - contradict n2. inversion n2. auto.\n          - apply H_diff_key_2.\n            + contradict n1. inversion n1. auto.\n            +unfold H.Equal in HEqual. rewrite HEqual.\n              apply H_diff_key_1 in H1.\n              * apply H_diff_key_1 in H1; [assumption | contradict n1; inversion n1; intuition].\n              * contradict n1; inversion n1; intuition.\n        }  \n  - inversion HDisj; subst.\n    assert (Disjoint_Dynamic (DA_Alloc r l v) (DA_Write r0 l0 v0)) by (apply H; left; reflexivity).\n    inversion H0; subst. unfold update_H in *. simpl in *. \n    constructor. constructor.\n    apply HMapP.Equal_sym in HEqual. apply HMapP.Equal_Equiv in HEqual. inversion HEqual.\n    apply HEqual in H6. apply HMapP.add_neq_in_iff; intuition.\n  - inversion HDisj; subst. simpl in H. constructor. constructor.\nQed.    \n\nLemma Par_Step_Write_Alloc :\n  forall phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2',\n    phi1 = Phi_Elem (DA_Write r l v) ->\n    phi2 = Phi_Elem (DA_Alloc r0 l0 v0) -> \n    Det_Trace phi1 ->\n    Det_Trace phi2 ->\n    Disjoint_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    H.Equal heapa heapb ->\n    (phi1, heapa) ===> (phi1', heap1') ->\n    (phi2, heapb) ===> (phi2', heap2') ->\n    exists heapA heapB,\n      H.Equal heapA heapB /\\\n      (Phi_Par phi1' phi2, heap1') ===> (Phi_Par phi1' phi2', heapA) /\\\n      (Phi_Par phi1 phi2', heap2') ===> (Phi_Par phi1' phi2', heapB).\nProof.\n  intros  phi1 r l v phi2 r0 l0 v0 phi1' phi2' heapa heapb heap1' heap2'\n          H1 H2 Det1 HDet2 HDisj HConf HEqual HStep1 HStep2; subst.\n  inversion HStep1; inversion HStep2; subst. \n  exists (update_H (r0, l0, v0) (update_H (r, l, v) heapa)). exists (update_H (r, l, v) (update_H (r0, l0, v0) heapb)). repeat split.\n  - inversion HDisj; subst. \n    assert (Disjoint_Dynamic (DA_Write r l v) (DA_Alloc r0 l0 v0)) by (apply H; left; reflexivity).\n    inversion H1; subst. unfold update_H in *. simpl in *. \n    destruct (RegionVars.eq_dec (r, l) (r0, l0)).\n    + inversion e. simpl in *. subst. contradict H3. reflexivity.\n    + clear n. \n      apply HMapP.Equal_mapsto_iff; intros. destruct k. \n      destruct (RegionVars.eq_dec (n, n0) (r0, l0)); destruct (RegionVars.eq_dec (n, n0) (r, l)); split.\n      * inversion e0; inversion e1.  unfold fst, snd in *; subst. rewrite H6 in *. rewrite H5 in *.\n        inversion H1; subst. contradict H4. intuition.\n      * inversion e0; inversion e1. unfold fst, snd in *; subst. rewrite H6 in H1. rewrite H5 in H1.\n        inversion H1; subst. contradict H4. intuition.\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.\n        intro. apply  HMapP.find_mapsto_iff in H2. rewrite H_same_key_add_twice_1 in H2. rewrite H_same_key in H2.\n        apply HMapP.add_mapsto_iff. right; simpl. split; [ intuition | ].\n        apply HMapP.find_mapsto_iff. rewrite H_same_key. assumption.\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.\n        intro. apply  HMapP.find_mapsto_iff in H2. rewrite H_same_key_add_twice_2 in H2.\n        { rewrite H_same_key in H2.  apply  HMapP.find_mapsto_iff.\n          inversion H2; subst. rewrite H_same_key_add_twice_1. rewrite H_same_key. assumption. }\n        { contradict n1. inversion n1. intuition. }\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.\n        intro. apply  HMapP.find_mapsto_iff in H2. rewrite H_same_key_add_twice_2 in H2. \n        { apply HMapP.add_mapsto_iff. left; simpl. split; auto.\n          rewrite HMapP.add_o in H2. \n          destruct (HMapP.eq_dec (r, l) (r, l)) in H2; [inversion H2; subst |  simpl in n; contradict n; auto].\n          reflexivity.\n        }\n        { contradict n1. inversion n1. intuition. }\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst. destruct e0; subst.\n        intro. apply  HMapP.find_mapsto_iff in H2. rewrite H_same_key_add_twice_1 in H2. \n        apply  HMapP.find_mapsto_iff in H2.  \n        apply  HMapP.find_mapsto_iff. \n        apply H_diff_key_2; [ contradict H2; auto | ].\n        apply HMapP.find_mapsto_iff.\n        apply HMapP.add_mapsto_iff. left; simpl. split; auto.\n        apply HMapP.add_mapsto_iff in H2.\n        destruct H2 as [ [ ?  ?] | [? ?] ]; [assumption | contradict H2; intuition]. \n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst.\n        intro. apply  HMapP.find_mapsto_iff in H2.\n        apply  HMapP.find_mapsto_iff.\n        { eapply H_diff_key_add_comm_2.\n          - contradict n2. inversion n2. auto.\n          - contradict n1. inversion n1. auto.\n          - apply H_diff_key_2.\n            + contradict n1. inversion n1. intuition.\n            + unfold H.Equal in HEqual. rewrite <- HEqual.\n              apply H_diff_key_1 in H2.\n              * apply H_diff_key_1 in H2; [assumption | contradict n2; inversion n2; auto]. \n              * contradict n1; inversion n1; auto.\n        }\n      * unfold RegionVars.eq in *. unfold fst, snd in *; subst.\n        intro. apply  HMapP.find_mapsto_iff in H2.\n        apply  HMapP.find_mapsto_iff.\n        { eapply H_diff_key_add_comm_2.\n          - contradict n1. inversion n1. auto.\n          - contradict n2. inversion n2. auto.\n          - apply H_diff_key_2.\n            + contradict n1. inversion n1. auto.\n            +unfold H.Equal in HEqual. rewrite HEqual.\n              apply H_diff_key_1 in H2.\n              * apply H_diff_key_1 in H2; [assumption | contradict n1; inversion n1; intuition].\n              * contradict n1; inversion n1; intuition.\n        }\n  - inversion HDisj; subst. \n    assert (Disjoint_Dynamic (DA_Write r l v)  (DA_Alloc r0 l0 v0)) by (apply H; left; reflexivity).\n    inversion H1; subst. unfold update_H in *. simpl in *.\n    constructor. constructor.\n  - constructor. constructor.\n    inversion HDisj; subst. \n    assert (Disjoint_Dynamic (DA_Write r l v)  (DA_Alloc r0 l0 v0)) by (apply H; left; reflexivity).\n    inversion H1; subst. unfold update_H in *. simpl in *.\n    apply HMapP.Equal_sym in HEqual. apply HMapP.Equal_Equiv in HEqual. inversion HEqual.\n    apply HEqual in H0. apply HMapP.add_neq_in_iff; intuition.\nQed.    \n    \nLemma Phi_Heap_Step_Progress :\n  forall phi heap heap',\n    (phi, heap) ===> (phi, heap') ->\n    False.\nProof.\n  induction phi; intros heap heap' HStep.\n  + inversion HStep.\n  + inversion HStep.\n  + inversion HStep; subst.\n    - eapply IHphi1; eassumption.\n    - eapply IHphi2; eassumption.\n  + inversion HStep; subst.\n    - eapply IHphi1; eassumption.\n    - eapply IHphi2; eassumption.\nQed.\n\n\nLemma Par_Step_Equal :\n   forall phi1 phi2 phi1' phi2' heap0 heap1' heap2',\n    Det_Trace phi1 ->\n    Det_Trace phi2 ->\n    Disjoint_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    (phi1, heap0) ===> (phi1', heap1') ->\n    (phi2, heap0) ===> (phi2', heap2') ->\n    exists heapA, exists heapB,\n      H.Equal heapA heapB /\\\n      (Phi_Par phi1' phi2, heap1') ===> (Phi_Par phi1' phi2', heapA) /\\\n      (Phi_Par phi1 phi2', heap2') ===> (Phi_Par phi1' phi2', heapB).\nProof.\n  intros phi1 phi2 phi1' phi2' heap0 heap1' heap2' HDet1 HDet2 HDisj HConf HStep1 HStep2.\n  generalize dependent phi2.\n  dependent induction HStep1; intros.\n  - dependent destruction HStep2. \n    + eapply Par_Step_Alloc_Alloc; eauto || econstructor.\n    + eapply Par_Step_Alloc_Read; eauto  || econstructor; assumption.\n    + eapply Par_Step_Alloc_Write; eauto || econstructor; assumption.\n    + replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Alloc in HStep2; eauto.\n      destruct HStep2 as [? [? ?]].\n      { exists x. exists (update_H (r, l, v) heap2'); repeat split.\n        - assumption.\n        - do 2 constructor; assumption.\n        - do 2 constructor. }\n    + replace (phi_as_list (Phi_Seq Phi_Nil phi0)) with (phi_as_list Phi_Nil ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Alloc in HStep2; eauto.\n      destruct HStep2 as [? [? ?]].\n      { exists x. exists (update_H (r, l, v) heap2'); repeat split.\n        - assumption.\n        - do 2 constructor; assumption.\n        - do 2 constructor. }\n    + { exists (update_H (r, l, v) heap2'). exists (update_H (r, l, v) heap2'); repeat split; do 2  constructor. }\n    + replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Alloc in HStep2; eauto.\n      destruct HStep2 as [? [? ?]].\n      { exists x. exists (update_H (r, l, v) heap2'); repeat split.\n        - assumption.\n        - do 2 constructor; assumption.\n        - do 2 constructor.   }\n    + replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Alloc in HStep2; eauto.\n      destruct HStep2 as [? [? ?]].\n      { exists x. exists  (update_H (r, l, v) heap2'); repeat split.\n        - assumption.\n        - do 2 constructor; assumption.\n        - do 2 constructor.  }            \n    + { exists (update_H (r, l, v) heap2'). exists (update_H (r, l, v) heap2'); repeat split; do 2  constructor. }\n  - dependent destruction HStep2. \n    + eapply Par_Step_Read_Alloc; eauto || econstructor; assumption.\n    + { exists heap2'. exists heap2'; repeat split; do 2 constructor; assumption. }\n    + eapply Par_Step_Read_Write; eauto || econstructor; assumption.\n    + { exists heap2'. exists heap2'. repeat split.\n        - do 2 constructor; assumption.\n        - do 2 constructor.\n          replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n            in HDisj by (simpl; reflexivity).\n          apply Disjointness_app_app_and_l in HDisj. destruct HDisj as [HD1 ?].\n          replace (phi_as_list (Phi_Elem (DA_Read r l v))) with (DA_Read r l v :: nil)\n            in HD1 by (simpl; reflexivity).\n          eapply Read_Preserved.\n          eapply H.\n          eapply HD1.\n          eapply HStep2. }\n    + { exists heap2'. exists heap2'. repeat split.\n        - do 2 constructor; assumption.\n        - do 2 constructor.\n          replace (phi_as_list (Phi_Seq Phi_Nil phi0)) with (phi_as_list Phi_Nil ++ phi_as_list phi0)\n            in HDisj by (simpl; reflexivity).\n          apply Disjointness_app_app_and_l in HDisj. destruct HDisj as [? HD1].\n          replace (phi_as_list (Phi_Elem (DA_Read r l v))) with (DA_Read r l v :: nil)\n            in HD1 by (simpl; reflexivity).\n          eapply Read_Preserved.\n          eapply H.\n          eapply HD1.\n          eapply HStep2. }\n    + exists heap2'. exists heap2'. repeat split; do 2 constructor. assumption.\n    + { exists heap2'. exists heap2'. repeat split.\n        - do 2 constructor; assumption.\n        - do 2 constructor.\n          replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n            in HDisj by (simpl; reflexivity).\n          apply Disjointness_app_app_and_l in HDisj. destruct HDisj as [HD1 ?].\n          replace (phi_as_list (Phi_Elem (DA_Read r l v))) with (DA_Read r l v :: nil)\n            in HD1 by (simpl; reflexivity).\n          eapply Read_Preserved.\n          eapply H.\n          eapply HD1.\n          eapply HStep2. }\n    + { exists heap2'. exists heap2'. repeat split.\n        - do 2 constructor; assumption.\n        - do 2 constructor.\n          replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n            in HDisj by (simpl; reflexivity).\n          apply Disjointness_app_app_and_l in HDisj. destruct HDisj as [? HD1].\n          replace (phi_as_list (Phi_Elem (DA_Read r l v))) with (DA_Read r l v :: nil)\n            in HD1 by (simpl; reflexivity).\n          eapply Read_Preserved.\n          eapply H.\n          eapply HD1.\n          eapply HStep2. }\n    + { exists heap2'. exists heap2'. repeat split; do 2 constructor. assumption. }\n  - dependent destruction HStep2. \n    + eapply Par_Step_Write_Alloc; eauto || econstructor; assumption.\n    + eapply Par_Step_Write_Read; eauto || econstructor; assumption.\n    + eapply Par_Step_Write_Write; eauto || econstructor; assumption.\n    + eapply monotonic_heap_updates in H; eauto.\n      replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Write in HStep2; eauto.\n      destruct HStep2 as [? [? ?]].   \n      { exists x. exists (update_H (r, l, v) heap2'); repeat split.\n        - assumption.\n        - do 2 constructor. assumption.\n        - constructor. constructor. assumption.\n      }\n    + eapply monotonic_heap_updates in H; eauto.\n      replace (phi_as_list (Phi_Seq Phi_Nil phi0)) with (phi_as_list Phi_Nil ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Write in HStep2; eauto.\n      destruct HStep2 as [? [? ?]].\n      { exists x.  exists (update_H (r, l, v) heap2'); repeat split.\n        - assumption.\n        - do 2 constructor; assumption.\n        - constructor. constructor. assumption. }\n    + { exists (update_H (r, l, v) heap2'). exists (update_H (r, l, v) heap2'); repeat split; do 2  constructor; assumption. }\n    + eapply monotonic_heap_updates in H; eauto.\n      replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Write in HStep2; eauto.\n      destruct HStep2 as [? [? ?]].\n      { exists x. exists (update_H (r, l, v) heap2'); repeat split.\n        - assumption.\n        - do 2 constructor; assumption.\n        - constructor. constructor. assumption. }\n    + eapply monotonic_heap_updates in H; eauto.\n      replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Write in HStep2; eauto.\n      destruct HStep2 as [? [? ?]].\n      { exists x. exists (update_H (r, l, v) heap2'); repeat split.\n        - assumption.\n        - do 2 constructor; assumption.\n        - constructor. constructor. assumption.  }            \n    + { exists (update_H (r, l, v) heap2'). exists (update_H (r, l, v) heap2'); repeat split; do 2  constructor; assumption. }\n  - inversion HDet1; subst. \n    edestruct (IHHStep1 H1 phi1 HDet2) as [heapA [heapB [? [? ?]]]].\n    + simpl in HDisj. apply Disjointness_app_app_and_r in HDisj. destruct HDisj. assumption.\n    + simpl in HConf. inversion HDet1.\n      apply Conflictness_app_and_r in HConf; [ destruct HConf  | | | ]; assumption.\n    + assumption.\n    + exists heapA. exists heapB. repeat split.\n      * assumption.\n      * inversion H0; subst.\n        { apply Phi_Heap_Step_Progress in HStep2. contradiction. }\n        { constructor. assumption. }\n      * inversion H3; subst.\n        { constructor. constructor. assumption. }\n        { apply Phi_Heap_Step_Progress in H3. contradiction. }\n  - inversion HDet1; subst.\n    edestruct (IHHStep1 H2 phi0 HDet2) as [heapA [heapB [? [? ?]]]].\n    + simpl in HDisj. assumption.\n    + simpl in HConf. assumption.\n    + assumption.\n    + exists heapA. exists heapB. repeat split.\n      * assumption.\n      * inversion H0; subst.\n        { apply Phi_Heap_Step_Progress in HStep2. contradiction. }\n        { constructor. assumption. }\n      * inversion H3; subst.\n        { constructor. constructor. assumption. }\n        { apply Phi_Heap_Step_Progress in H3. contradiction. }\n  - exists heap2'. exists heap2'. repeat split.\n     * constructor; assumption.\n     * constructor; constructor.\n  - inversion HDet1; subst.\n    edestruct (IHHStep1 H1 phi1 HDet2) as [heapA [heapB [? [? ?]]]].\n    + simpl in HDisj. apply Disjointness_app_app_and_r in HDisj. destruct HDisj. assumption.\n    + simpl in HConf. inversion HDet1.\n      apply Conflictness_app_and_r in HConf; [ destruct HConf  | | | ]; assumption.\n    + assumption.\n    + exists heapA. exists heapB. repeat split.\n      * assumption.\n      * inversion H0; subst.\n        { apply Phi_Heap_Step_Progress in HStep2. contradiction. }\n        { constructor. assumption. }\n      * inversion H4; subst.\n        { constructor. constructor. assumption. }\n        { apply Phi_Heap_Step_Progress in H4. contradiction. }\n  - inversion HDet1; subst.\n    edestruct (IHHStep1 H2 phi1 HDet2) as [heapA [heapB [? [? ?]]]].\n    + simpl in HDisj. apply Disjointness_app_app_and_r in HDisj. destruct HDisj. assumption.\n    + simpl in HConf. inversion HDet1.\n      apply Conflictness_app_and_r in HConf; [ destruct HConf  | | | ]; assumption.\n    + assumption.\n    + exists heapA. exists heapB. repeat split.\n      * assumption.\n      * inversion H0; subst.\n        { apply Phi_Heap_Step_Progress in HStep2. contradiction. }\n        { constructor. assumption. }\n      * inversion H4; subst.\n        { constructor. constructor. assumption. }\n        { apply Phi_Heap_Step_Progress in H4. contradiction. }\n  - exists heap2'. exists heap2'. repeat split.\n     * constructor; assumption.\n     * constructor; constructor.\nQed.\n\nLemma Par_Step_Equal_new :\n   forall phi1 phi2 phi1' phi2' heapa heapb heap1' heap2',\n    Det_Trace phi1 ->\n    Det_Trace phi2 ->\n    Disjoint_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1) (phi_as_list phi2) ->\n    H.Equal heapa heapb ->\n    (phi1, heapa) ===> (phi1', heap1') ->\n    (phi2, heapb) ===> (phi2', heap2') ->\n    exists heapA, exists heapB,\n      H.Equal heapA heapB /\\\n      (Phi_Par phi1' phi2, heap1') ===> (Phi_Par phi1' phi2', heapA) /\\\n      (Phi_Par phi1 phi2', heap2') ===> (Phi_Par phi1' phi2', heapB).\nProof.\n  intros phi1 phi2 phi1' phi2' heapa heapb heap1' heap2' HDet1 HDet2 HDisj HConf HEqual HStep1 HStep2.\n  generalize dependent phi2.\n  dependent induction HStep1; intros.\n  - dependent destruction HStep2.  \n    + eapply Par_Step_Alloc_Alloc; eauto || econstructor.\n    + eapply Par_Step_Alloc_Read; eauto  || econstructor; assumption.\n    + eapply Par_Step_Alloc_Write; eauto || econstructor; assumption.\n    + apply HMapP.Equal_sym in HEqual. \n      edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n       as [heap2'' [HEqual' HStep2']]. clear HStep2.\n      replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Alloc in HStep2'; eauto.  \n      destruct HStep2' as [heapa' [? ?]]. \n      { exists heapa'. exists (update_H (r, l, v) heap2'); repeat split. \n        - unfold H.Equal in *; unfold update_H in *; simpl in *.\n          intros [r' l'].\n          destruct (RegionVars.eq_dec (r', l') (r, l)).\n          * inversion_clear e; simpl in *; subst.\n            rewrite H1. do 2 rewrite H_same_key. reflexivity.\n          * unfold RegionVars.eq in *; simpl in *.\n            rewrite HMapP.add_neq_o. \n            { rewrite H1. rewrite HEqual'. rewrite HMapP.add_neq_o; [reflexivity | contradict n; intuition]. }\n            { simpl. contradict n. intuition. } \n        - do 2 constructor. assumption.\n        - do 2 constructor. }\n    + apply HMapP.Equal_sym in HEqual.\n      edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n       as [heap2'' [HEqual' HStep2']]. clear HStep2.\n      replace (phi_as_list (Phi_Seq Phi_Nil phi0)) with (phi_as_list Phi_Nil ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Alloc in HStep2'; eauto.\n      destruct HStep2' as [? [? ?]].\n      { exists x. exists (update_H (r, l, v) heap2'); repeat split.\n        - unfold H.Equal in *; unfold update_H in *; simpl in *.\n          intros [r' l'].\n          destruct (RegionVars.eq_dec (r', l') (r, l)).\n          * inversion_clear e; simpl in *; subst.\n            rewrite H1. do 2 rewrite H_same_key. reflexivity.\n          * unfold RegionVars.eq in *; simpl in *.\n            rewrite HMapP.add_neq_o. \n            { rewrite H1. rewrite HEqual'. rewrite HMapP.add_neq_o; [reflexivity | contradict n; intuition]. }\n            { simpl. contradict n. intuition. } \n        - do 2 constructor; assumption.\n        - do 2 constructor. }\n    + { exists (update_H (r, l, v) heapa). exists (update_H (r, l, v) heap2'); repeat split.\n        - unfold H.Equal in *; unfold update_H in *; simpl in *.\n          intros [r' l']. \n          destruct (RegionVars.eq_dec (r', l') (r, l)).\n          * inversion_clear e; simpl in *; subst.\n            do 2 rewrite H_same_key. reflexivity.\n          * unfold RegionVars.eq in *; simpl in *.\n            rewrite HMapP.add_neq_o. \n            { rewrite HEqual. rewrite HMapP.add_neq_o; [reflexivity | contradict n; intuition]. }\n            { simpl. contradict n. intuition. } \n        - do 2  constructor.\n        - do 2 constructor. }\n    + apply HMapP.Equal_sym in HEqual.\n      edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n        as [heap2'' [HEqual' HStep2']]. clear HStep2.\n      replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Alloc in HStep2'; eauto.\n      destruct HStep2' as [? [? ?]].\n      { exists x. exists (update_H (r, l, v) heap2'); repeat split.\n        - unfold H.Equal in *; unfold update_H in *; simpl in *.\n          intros [r' l'].\n          destruct (RegionVars.eq_dec (r', l') (r, l)).\n          * inversion_clear e; simpl in *; subst.\n            rewrite H1. do 2 rewrite H_same_key. reflexivity.\n          * unfold RegionVars.eq in *; simpl in *.\n            rewrite HMapP.add_neq_o. \n            { rewrite H1. rewrite HEqual'. rewrite HMapP.add_neq_o; [reflexivity | contradict n; intuition]. }\n            { simpl. contradict n. intuition. } \n        - do 2 constructor; assumption.\n        - do 2 constructor.   }\n    + apply HMapP.Equal_sym in HEqual.\n      edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n        as [heap2'' [HEqual' HStep2']]. clear HStep2.\n      replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Alloc in HStep2'; eauto.\n      destruct HStep2' as [? [? ?]].\n      { exists x. exists  (update_H (r, l, v) heap2'); repeat split.\n        -  unfold H.Equal in *; unfold update_H in *; simpl in *.\n          intros [r' l'].\n          destruct (RegionVars.eq_dec (r', l') (r, l)).\n          * inversion_clear e; simpl in *; subst.\n            rewrite H1. do 2 rewrite H_same_key. reflexivity.\n          * unfold RegionVars.eq in *; simpl in *.\n            rewrite HMapP.add_neq_o. \n            { rewrite H1. rewrite HEqual'. rewrite HMapP.add_neq_o; [reflexivity | contradict n; intuition]. }\n            { simpl. contradict n. intuition. } \n        - do 2 constructor; assumption.\n        - do 2 constructor.  }            \n    + { exists (update_H (r, l, v) heapa). exists (update_H (r, l, v) heap2'); repeat split; try (do 2  constructor). \n        unfold H.Equal in *; unfold update_H in *; simpl in *.\n          intros [r' l']. \n          destruct (RegionVars.eq_dec (r', l') (r, l)).\n          * inversion_clear e; simpl in *; subst.\n            do 2 rewrite H_same_key. reflexivity.\n          * unfold RegionVars.eq in *; simpl in *.\n            rewrite HMapP.add_neq_o. \n            { rewrite HEqual. rewrite HMapP.add_neq_o; [reflexivity | contradict n; intuition]. }\n            { simpl. contradict n. intuition. }\n       }  \n  - dependent destruction HStep2. \n    + eapply Par_Step_Read_Alloc; eauto || econstructor; assumption.\n    + { exists heap1'; exists heap2'; repeat split.\n        - assumption.\n        - constructor. constructor. unfold H.Equal in HEqual. rewrite <- H0. apply HEqual.\n        - constructor. constructor. unfold H.Equal in HEqual. rewrite <- HEqual. assumption.\n      }\n    + eapply Par_Step_Read_Write; eauto || econstructor; assumption.\n    + { apply HMapP.Equal_sym in HEqual.\n        edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n        as [heap2'' [HEqual' HStep2']].\n        exists heap2''. exists heap2'. repeat split.\n        - apply HMapP.Equal_sym. assumption.\n        - do 2 constructor. assumption.\n        - do 2 constructor. \n          replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n            in HDisj by (simpl; reflexivity).\n          apply Disjointness_app_app_and_l in HDisj. destruct HDisj as [HD1 ?].\n          replace (phi_as_list (Phi_Elem (DA_Read r l v))) with (DA_Read r l v :: nil)\n            in HD1 by (simpl; reflexivity).\n          unfold H.Equal in HEqual'. rewrite HEqual'.\n          eapply Read_Preserved.\n          eapply H.\n          eapply HD1.\n          eapply HStep2'. }\n    + { apply HMapP.Equal_sym in HEqual.\n        edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n          as [heap2'' [HEqual' HStep2']]. clear HStep2.\n        exists heap2''. exists heap2'. repeat split.\n        - apply HMapP.Equal_sym. assumption.\n        - do 2 constructor; assumption.\n        - do 2 constructor.\n          replace (phi_as_list (Phi_Seq Phi_Nil phi0)) with (phi_as_list Phi_Nil ++ phi_as_list phi0)\n            in HDisj by (simpl; reflexivity).\n          apply Disjointness_app_app_and_l in HDisj. destruct HDisj as [? HD1].\n          replace (phi_as_list (Phi_Elem (DA_Read r l v))) with (DA_Read r l v :: nil)\n            in HD1 by (simpl; reflexivity).\n          unfold H.Equal in HEqual'. rewrite HEqual'. eapply Read_Preserved.\n          eapply H.\n          eapply HD1.\n          eapply HStep2'. }\n    + { exists heap1'. exists heap2'. repeat split; auto.\n        - do 2 constructor.\n        - do 2 constructor.\n          rewrite <- H. unfold H.Equal in HEqual. symmetry; apply HEqual.\n      }\n    + { apply HMapP.Equal_sym in HEqual.\n        edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n           as [heap2'' [HEqual' HStep2']]. clear HStep2.\n        exists heap2''. exists heap2'. repeat split.\n        - apply HMapP.Equal_sym. assumption.\n        - do 2 constructor; assumption.\n        - do 2 constructor.\n          replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n            in HDisj by (simpl; reflexivity).\n          apply Disjointness_app_app_and_l in HDisj. destruct HDisj as [HD1 ?].\n          replace (phi_as_list (Phi_Elem (DA_Read r l v))) with (DA_Read r l v :: nil)\n            in HD1 by (simpl; reflexivity).\n          unfold H.Equal in HEqual'. rewrite HEqual'.  eapply Read_Preserved.\n          eapply H.\n          eapply HD1.\n          eapply HStep2' . }\n    + { apply HMapP.Equal_sym in HEqual.\n        edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n          as [heap2'' [HEqual' HStep2']]. clear HStep2.\n        exists heap2''. exists heap2'. repeat split.\n        - apply HMapP.Equal_sym. assumption.\n        - do 2 constructor; assumption.\n        - do 2 constructor.\n          replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n            in HDisj by (simpl; reflexivity).\n          apply Disjointness_app_app_and_l in HDisj. destruct HDisj as [? HD1].\n          replace (phi_as_list (Phi_Elem (DA_Read r l v))) with (DA_Read r l v :: nil)\n            in HD1 by (simpl; reflexivity).\n          unfold H.Equal in HEqual'. rewrite HEqual'. eapply Read_Preserved.\n          eapply H.\n          eapply HD1.\n          eapply HStep2'. }\n    + { exists heap1'. exists heap2'. repeat split; auto.\n        - do 2 constructor.\n        - do 2 constructor.\n          rewrite <- H. unfold H.Equal in HEqual. symmetry; apply HEqual.\n      }\n  - dependent destruction HStep2. \n    + eapply Par_Step_Write_Alloc; eauto || econstructor; assumption.\n    + eapply Par_Step_Write_Read; eauto || econstructor; assumption.\n    + eapply Par_Step_Write_Write; eauto || econstructor; assumption.\n    + apply HMapP.Equal_sym in HEqual.\n      edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n        as [heap2'' [HEqual' HStep2']]. clear HStep2.\n      eapply monotonic_heap_updates in H; eauto.\n      replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Write in HStep2'; eauto.\n      destruct HStep2' as [? [? ?]].   \n      { exists x. exists (update_H (r, l, v) heap2'); repeat split.\n        -  unfold H.Equal in *; unfold update_H in *; simpl in *.\n          intros [r' l'].\n          destruct (RegionVars.eq_dec (r', l') (r, l)).\n          * inversion_clear e; simpl in *; subst.\n            rewrite H2. do 2 rewrite H_same_key. reflexivity.\n          * unfold RegionVars.eq in *; simpl in *.\n            rewrite HMapP.add_neq_o. \n            { rewrite H2. rewrite HEqual'. rewrite HMapP.add_neq_o; [reflexivity | contradict n; intuition]. }\n            { simpl. contradict n. intuition. } \n        - do 2 constructor. assumption.\n        - constructor. constructor.  apply HMapP.Equal_Equiv in HEqual'. inversion HEqual'. apply H4. assumption. \n      }\n    + apply HMapP.Equal_sym in HEqual.\n      edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n         as [heap2'' [HEqual' HStep2']]. clear HStep2.\n      eapply monotonic_heap_updates in H; eauto.\n      replace (phi_as_list (Phi_Seq Phi_Nil phi0)) with (phi_as_list Phi_Nil ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Write in HStep2'; eauto.\n      destruct HStep2' as [? [? ?]].\n      { exists x.  exists (update_H (r, l, v) heap2'); repeat split.\n        -  unfold H.Equal in *; unfold update_H in *; simpl in *.\n          intros [r' l'].\n          destruct (RegionVars.eq_dec (r', l') (r, l)).\n          * inversion_clear e; simpl in *; subst.\n            rewrite H2. do 2 rewrite H_same_key. reflexivity.\n          * unfold RegionVars.eq in *; simpl in *.\n            rewrite HMapP.add_neq_o. \n            { rewrite H2. rewrite HEqual'. rewrite HMapP.add_neq_o; [reflexivity | contradict n; intuition]. }\n            { simpl. contradict n. intuition. } \n        - do 2 constructor; assumption.\n        - constructor. constructor.  apply HMapP.Equal_Equiv in HEqual'. inversion HEqual'. apply H4. assumption. }\n    + { exists (update_H (r, l, v) heapa). exists (update_H (r, l, v) heap2'); repeat split.\n        -  unfold H.Equal in *; unfold update_H in *; simpl in *.\n          intros [r' l'].\n          destruct (RegionVars.eq_dec (r', l') (r, l)).\n          * inversion_clear e; simpl in *; subst.\n            do 2 rewrite H_same_key. reflexivity.\n          * unfold RegionVars.eq in *; simpl in *.\n            rewrite HMapP.add_neq_o. \n            { rewrite HEqual. rewrite HMapP.add_neq_o; [reflexivity | contradict n; intuition]. }\n            { simpl. contradict n. intuition. } \n        - constructor. constructor.\n        - do 2 constructor. apply HMapP.Equal_Equiv in HEqual. inversion HEqual. apply H0. assumption.  }\n    + apply HMapP.Equal_sym in HEqual.\n      edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n        as [heap2'' [HEqual' HStep2']]. clear HStep2.\n      eapply monotonic_heap_updates in H; eauto.\n      replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Write in HStep2'; eauto.\n      destruct HStep2' as [? [? ?]].\n      { exists x. exists (update_H (r, l, v) heap2'); repeat split.\n        -  unfold H.Equal in *; unfold update_H in *; simpl in *.\n          intros [r' l'].\n          destruct (RegionVars.eq_dec (r', l') (r, l)).\n          * inversion_clear e; simpl in *; subst.\n             rewrite H2. do 2 rewrite H_same_key. reflexivity.\n          * unfold RegionVars.eq in *; simpl in *.\n            rewrite HMapP.add_neq_o. \n            { rewrite H2. rewrite HEqual'. rewrite HMapP.add_neq_o; [reflexivity | contradict n; intuition]. }\n            { simpl. contradict n. intuition. } \n        - do 2 constructor; assumption.\n        - constructor. constructor. apply HMapP.Equal_Equiv in HEqual'. inversion HEqual'. apply H4. assumption. }\n    +  apply HMapP.Equal_sym in HEqual.\n      edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n         as [heap2'' [HEqual' HStep2']]. clear HStep2.\n      eapply monotonic_heap_updates in H; eauto.\n      replace (phi_as_list (Phi_Seq phi1 phi0)) with (phi_as_list phi1 ++ phi_as_list phi0)\n        in HDisj by (simpl; reflexivity).\n      apply Disjointness_app_app_and_l in HDisj. destruct HDisj.\n      eapply Disjointness_Preserves_Update_Write in HStep2'; eauto.\n      destruct HStep2' as [? [? ?]].\n      { exists x. exists (update_H (r, l, v) heap2'); repeat split.\n        - unfold H.Equal in *; unfold update_H in *; simpl in *.\n          intros [r' l'].\n          destruct (RegionVars.eq_dec (r', l') (r, l)).\n          * inversion_clear e; simpl in *; subst.\n             rewrite H2. do 2 rewrite H_same_key. reflexivity.\n          * unfold RegionVars.eq in *; simpl in *.\n            rewrite HMapP.add_neq_o. \n            { rewrite H2. rewrite HEqual'. rewrite HMapP.add_neq_o; [reflexivity | contradict n; intuition]. }\n            { simpl. contradict n. intuition. } \n        - do 2 constructor; assumption.\n        - constructor. constructor. apply HMapP.Equal_Equiv in HEqual'. inversion HEqual'. apply H4. assumption.  }            \n    +  { exists (update_H (r, l, v) heapa). exists (update_H (r, l, v) heap2'); repeat split.\n        -  unfold H.Equal in *; unfold update_H in *; simpl in *.\n          intros [r' l'].\n          destruct (RegionVars.eq_dec (r', l') (r, l)).\n          * inversion_clear e; simpl in *; subst.\n            do 2 rewrite H_same_key. reflexivity.\n          * unfold RegionVars.eq in *; simpl in *.\n            rewrite HMapP.add_neq_o. \n            { rewrite HEqual. rewrite HMapP.add_neq_o; [reflexivity | contradict n; intuition]. }\n            { simpl. contradict n. intuition. } \n        - constructor. constructor.\n        - do 2 constructor. apply HMapP.Equal_Equiv in HEqual. inversion HEqual. apply H0. assumption.  }\n  - inversion HDet1; subst. clear H2.\n    edestruct IHHStep1 with (phi2:=phi1)  as [heapA [heapB [? [? ?]]]]; eauto.\n    + simpl in HDisj. apply Disjointness_app_app_and_r in HDisj. destruct HDisj. assumption.\n    + simpl in HConf. inversion HDet1.\n      apply Conflictness_app_and_r in HConf; [ destruct HConf  | | | ]; assumption.\n    + exists heapA. exists heapB. repeat split.\n      * assumption.\n      * inversion H0; subst.\n        { apply Phi_Heap_Step_Progress in HStep2. contradiction. }\n        { constructor. assumption. }\n      * inversion H2; subst.\n        { constructor. constructor. assumption. }\n        { apply Phi_Heap_Step_Progress in H2. contradiction. }\n  - inversion HDet1; subst. clear H1.\n    edestruct IHHStep1 with (phi2:=phi0) as [heapA [heapB [? [? ?]]]]; eauto.\n    + exists heapA. exists heapB. repeat split.\n      * assumption.\n      * inversion H0; subst.\n        { apply Phi_Heap_Step_Progress in HStep2. contradiction. }\n        { constructor. assumption. }\n      * inversion H1; subst.\n        { constructor. constructor. assumption. }\n        { apply Phi_Heap_Step_Progress in H1. contradiction. }\n  -  apply HMapP.Equal_sym in HEqual.\n     edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n       as [heap2'' [HEqual' HStep2']]. clear HStep2.\n     exists heap2''. exists heap2'. repeat split.\n     * apply HMapP.Equal_sym. assumption.\n     * constructor; assumption.\n     * constructor; constructor.\n  - inversion HDet1; subst. clear H2.\n    edestruct IHHStep1 with (phi2:=phi1) as [heapA [heapB [? [? ?]]]]; eauto.\n    + simpl in HDisj. apply Disjointness_app_app_and_r in HDisj. destruct HDisj. assumption.\n    + simpl in HConf. inversion HDet1.\n      apply Conflictness_app_and_r in HConf; [ destruct HConf  | | | ]; assumption.\n    + exists heapA. exists heapB. repeat split.\n      * assumption.\n      * inversion H0; subst.\n        { apply Phi_Heap_Step_Progress in HStep2. contradiction. }\n        { constructor. assumption. }\n      * inversion H2; subst.\n        { constructor. constructor. assumption. }\n        { apply Phi_Heap_Step_Progress in H2. contradiction. }\n  - inversion HDet1; subst. \n    edestruct IHHStep1 with (phi2:=phi1) as [heapA [heapB [? [? ?]]]]; eauto.\n    + simpl in HDisj. apply Disjointness_app_app_and_r in HDisj. destruct HDisj. assumption.\n    + simpl in HConf. inversion HDet1.\n      apply Conflictness_app_and_r in HConf; [ destruct HConf  | | | ]; assumption.\n    + exists heapA. exists heapB. repeat split.\n      * assumption.\n      * inversion H0; subst.\n        { apply Phi_Heap_Step_Progress in HStep2. contradiction. }\n        { constructor. assumption. }\n      * inversion H4; subst.\n        { constructor. constructor. assumption. }\n        { apply Phi_Heap_Step_Progress in H4. contradiction. }\n   -  apply HMapP.Equal_sym in HEqual.\n      edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ HStep2 HEqual)\n        as [heap2'' [HEqual' HStep2']]. clear HStep2.\n      exists heap2''. exists heap2'. repeat split.\n     * apply HMapP.Equal_sym. assumption. \n     * constructor; assumption.\n     * constructor; constructor.\nQed.\n\n\n\nLemma Diamond_Step :\n  forall phi0 phi1 phi2 heap0 heap1 heap2,\n    Det_Trace phi0 ->\n    (phi0, heap0) ===> (phi1, heap1) ->\n    (phi0, heap0) ===> (phi2, heap2) ->\n    exists phi3, exists heap3, exists heap4, exists n13, exists n23,\n      H.Equal heap3 heap4 /\\                                                     \n      (phi1, heap1) =a=>* (phi3, heap3, n13) /\\\n      (phi2, heap2) =a=>* (phi3, heap4, n23) /\\\n      (n13 <= 1) /\\ (n23 <= 1).\nProof.\n  induction phi0; intros phi1 phi2 heap0 heap1 heap2 HDet H0_1 H0_2.\n  + inversion H0_1.\n  + destruct d; inversion H0_1; subst; inversion H0_2; subst;\n    repeat eexists; repeat econstructor.\n  + inversion H0_1; subst; inversion H0_2; subst.\n  - inversion HDet; subst.\n      edestruct (IHphi0_1 phi1' phi1'0) as [phi3 [heap3 [heap4 [n13 [n23 [? [? [? ?]]]]]]]]; try eassumption.\n      exists (Phi_Par phi3 phi0_2). exists heap3. exists heap4.  exists n13. exists n23; repeat split;\n         try (solve [assumption | destruct H7; eassumption | eapply Par_Left_Pres; assumption]) .\n    - inversion HDet; subst. destruct H5.\n      edestruct (Par_Step_Equal phi0_1 phi0_2) as [heap3 [heap4 [? [? ?]]]]; try eassumption.\n      exists (Phi_Par phi1' phi2'). exists heap3. exists heap4.\n      repeat eexists; try (eapply PHT_Step; eassumption); repeat constructor. assumption.\n    - inversion H0.\n    - inversion HDet; subst. destruct H5.\n      edestruct (Par_Step_Equal phi0_1 phi0_2 phi1' phi2') as [heap3 [heap4 [? [? ?]]]]; try eassumption.\n      exists (Phi_Par phi1' phi2'). exists heap4. exists heap3. \n      repeat eexists; try (eapply PHT_Step; eassumption); repeat constructor.\n      apply HMapP.Equal_sym; assumption.\n    - inversion HDet; subst.\n      edestruct (IHphi0_2 phi2' phi2'0) as [phi3 [heap3 [heap4 [n13 [n23 [? [? [? ?]]]]]]]]; try eassumption.\n      exists (Phi_Par phi0_1 phi3). exists heap3. exists heap4. exists n13. exists n23; repeat split;\n        try (solve [assumption | destruct H7; eassumption | eapply Par_Right_Pres; assumption]) .\n    - inversion H0.\n    - inversion H0.\n    - inversion H0.\n    - exists Phi_Nil. exists heap2. repeat eexists; repeat econstructor.\n  + inversion H0_1; subst; inversion H0_2; subst.\n    - inversion HDet; subst.\n      edestruct (IHphi0_1 phi1' phi1'0) as [phi3 [heap3 [heap4 [n13 [n23 [? [? [? ?]]]]]]]]; try eassumption.\n      exists (Phi_Seq phi3 phi0_2). exists heap3. exists heap4. exists n13. exists n23. repeat split;\n        try (solve [assumption | destruct H6; eassumption | eapply Seq_Left_Pres; assumption]) .\n    - inversion H0.\n    - inversion H0.\n    - inversion H1.\n    - inversion HDet; subst.\n      edestruct (IHphi0_2 phi2' phi2'0) as [phi3 [heap3 [heap4 [n13 [n23 [? [? [? ?]]]]]]]]; try eassumption.\n      exists (Phi_Seq Phi_Nil phi3). exists heap3. exists heap4. exists n13. exists n23; repeat split;\n        try (solve [assumption | destruct H6; eassumption | eapply Seq_Right_Pres; assumption]) .\n    - inversion H0.\n    - inversion H0.\n    - inversion H0.\n    - exists Phi_Nil. exists heap2. repeat eexists; repeat econstructor.\nQed.\n\nLemma Diamond_Step_new :\n  forall phi0 phi1 phi2 heapa heapb heap1 heap2,\n    Det_Trace phi0 ->\n    H.Equal heapa heapb ->\n    (phi0, heapa) ===> (phi1, heap1) ->\n    (phi0, heapb) ===> (phi2, heap2) ->\n    exists phi3, exists heap3, exists heap4, exists n13, exists n23,\n      H.Equal heap3 heap4 /\\                                                     \n      (phi1, heap1) =a=>* (phi3, heap3, n13) /\\\n      (phi2, heap2) =a=>* (phi3, heap4, n23) /\\\n      (n13 <= 1) /\\ (n23 <= 1).\nProof.\n  induction phi0; intros phi1 phi2 heapa heapb heap1 heap2 HDet HEqual H0_1 H0_2.\n  + inversion H0_1.\n  + destruct d; inversion H0_1; subst; inversion H0_2; subst; exists Phi_Nil.\n    - exists (update_H (r, n, v) heapa); exists (update_H (r, n, v) heapb).\n      repeat eexists; repeat econstructor.\n      unfold H.Equal in *; unfold update_H in *; simpl in *.\n      intros [r' n'].\n      destruct (RegionVars.eq_dec (r', n') (r, n)).\n        * inversion_clear e; simpl in *; subst.\n          do 2 rewrite H_same_key_1. reflexivity.\n        * unfold RegionVars.eq in *; simpl in *.\n          rewrite HMapP.add_neq_o by (contradict n0; intuition).\n          rewrite HMapP.add_neq_o by (contradict n0; intuition).\n          apply HEqual.\n    - exists heap1; exists heap2; repeat eexists; repeat econstructor.\n      assumption.\n    - exists (update_H (r, n, v) heapa); exists (update_H (r, n, v) heapb).\n      repeat eexists; repeat econstructor.\n      unfold H.Equal in *; unfold update_H in *; simpl in *.\n      intros [r' n'].\n      destruct (RegionVars.eq_dec (r', n') (r, n)).\n        * inversion_clear e; simpl in *; subst.\n          do 2 rewrite H_same_key_1. reflexivity.\n        * unfold RegionVars.eq in *; simpl in *.\n          rewrite HMapP.add_neq_o by (contradict n0; intuition).\n          rewrite HMapP.add_neq_o by (contradict n0; intuition).\n          apply HEqual.\n  + inversion H0_1; subst; inversion H0_2; subst.\n  - inversion HDet; subst.\n      edestruct (IHphi0_1 phi1' phi1'0) as [phi3 [heap3 [heap4 [n13 [n23 [? [? [? ?]]]]]]]]; try eassumption.\n      exists (Phi_Par phi3 phi0_2). exists heap3. exists heap4.  exists n13. exists n23; repeat split;\n         try (solve [assumption | destruct H7; eassumption | eapply Par_Left_Pres; assumption]) .\n    - inversion HDet; subst. destruct H5.\n      edestruct (Par_Step_Equal_new phi0_1 phi0_2) as [heap3 [heap4 [? [? ?]]]]; try eassumption.\n      exists (Phi_Par phi1' phi2'). exists heap3. exists heap4.\n      repeat eexists; try (eapply PHT_Step; eassumption); repeat constructor. assumption.\n    - inversion H0.\n    - inversion HDet; subst. destruct H5.\n      assert (HEqual': H.Equal heapb heapa) by (eauto using HMapP.Equal_sym).\n      edestruct (Par_Step_Equal_new phi0_1 phi0_2 phi1' phi2') as [heap3 [heap4 [? [? ?]]]]; try eassumption.\n      exists (Phi_Par phi1' phi2'). exists heap4. exists heap3. \n      repeat eexists; try (eapply PHT_Step; eassumption); repeat constructor.\n      apply HMapP.Equal_sym; assumption.\n    - inversion HDet; subst.\n      edestruct (IHphi0_2 phi2' phi2'0) as [phi3 [heap3 [heap4 [n13 [n23 [? [? [? ?]]]]]]]]; try eassumption.\n      exists (Phi_Par phi0_1 phi3). exists heap3. exists heap4. exists n13. exists n23; repeat split;\n        try (solve [assumption | destruct H7; eassumption | eapply Par_Right_Pres; assumption]) .\n    - inversion H0.\n    - inversion H0.\n    - inversion H0.\n    - exists Phi_Nil. exists heap1. exists heap2. repeat eexists; repeat econstructor; assumption.\n  + inversion H0_1; subst; inversion H0_2; subst.\n    - inversion HDet; subst.\n      edestruct (IHphi0_1 phi1' phi1'0) as [phi3 [heap3 [heap4 [n13 [n23 [? [? [? ?]]]]]]]]; try eassumption.\n      exists (Phi_Seq phi3 phi0_2). exists heap3. exists heap4. exists n13. exists n23. repeat split;\n        try (solve [assumption | destruct H6; eassumption | eapply Seq_Left_Pres; assumption]) .\n    - inversion H0.\n    - inversion H0.\n    - inversion H1.\n    - inversion HDet; subst.\n      edestruct (IHphi0_2 phi2' phi2'0) as [phi3 [heap3 [heap4 [n13 [n23 [? [? [? ?]]]]]]]]; try eassumption.\n      exists (Phi_Seq Phi_Nil phi3). exists heap3. exists heap4. exists n13. exists n23; repeat split;\n        try (solve [assumption | destruct H6; eassumption | eapply Seq_Right_Pres; assumption]) .\n    - inversion H0.\n    - inversion H0.\n    - inversion H0.\n    - exists Phi_Nil. exists heap1. exists heap2. repeat eexists; repeat econstructor; assumption.\nQed.\n\nTheorem Phi_Heap_Step__Preserves_DAs :\n  forall phi phi' heap heap',\n    (phi, heap) ===> (phi', heap') ->\n    (forall da,\n       In da (phi_as_list phi') ->\n       In da (phi_as_list phi)).\nProof.\n  intros phi phi' heap heap' HStep.\n  dependent induction HStep; intros da HIn; simpl phi_as_list in *.\n  - inversion HIn.\n  - inversion HIn.\n  - inversion HIn.\n  - apply in_or_app.\n    apply in_app_or in HIn; destruct HIn.\n    + left; apply IHHStep; assumption.\n    + right; assumption.\n  - apply IHHStep; assumption.\n  - assumption.\n  - apply in_or_app.\n    apply in_app_or in HIn; destruct HIn.\n    + left; apply IHHStep; assumption.\n    + right; assumption.\n  - apply in_or_app.\n    apply in_app_or in HIn; destruct HIn.\n    + left; assumption.\n    + right; apply IHHStep; assumption.\n  - assumption.\nQed.\n\nLemma Det_Pres_Par_Conf_1:\n  forall phi1 phi1' phi2 heap heap',\n    (phi1, heap) ===> (phi1', heap') ->\n    Det_Trace (Phi_Par phi1 phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1') (phi_as_list phi2).\nProof.\n  intros. inversion H0; subst. destruct H5.\n  intro. inversion H5; subst. apply H1.\n  econstructor; eauto using Phi_Heap_Step__Preserves_DAs.\nQed.\n\nLemma Det_Pres_Par_Conf_1_aux:\n  forall phi1 phi1' phi2 heap heap',\n    (phi1, heap) ===> (phi1', heap') ->\n    Det_Trace phi1' ->\n    Det_Trace (Phi_Par phi1 phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1') (phi_as_list phi2).\nProof.\n  intros phi1 phi1' phi2 heap heap' H1 H2 H3.\n  inversion_clear H3; subst. destruct H4. clear H4.\n  generalize dependent phi2.  \n  dependent induction H1; intros; subst; simpl in *.\n  - intro. inversion H1. trivial.\n  - intro. inversion H4. trivial.\n  - intro. inversion H4. trivial.\n  - inversion H2; inversion H; subst.  \n    apply Conflictness_app_and_r in H3; auto. destruct H3.\n    apply Conflictness_and_app_r; auto.\n  - apply IHPhi_Heap_Step; auto; inversion H2; inversion H; assumption.\n  - apply H3.\n  - inversion H2; inversion H; subst.\n    apply Conflictness_app_and_r in H3; auto. destruct H3.\n    apply Conflictness_and_app_r; auto.\n  - inversion H2; inversion H; subst.\n    destruct H8.\n    apply Conflictness_app_and_r in H3; auto. destruct H3.\n    apply Conflictness_and_app_r; auto.\n  - intro; now apply H3.\nQed.\n\nLemma Det_Pres_Par_Conf_2:\n  forall phi1 phi1' phi2 heap heap',\n    (phi1, heap) ===> (phi1', heap') ->\n    Det_Trace (Phi_Par phi1 phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1') (phi_as_list phi2).\nProof.\n  intros. inversion H0; subst. destruct H5.\n  intro. inversion H5; subst. apply H1. \n  econstructor; eauto using Phi_Heap_Step__Preserves_DAs.\nQed.\n\nLemma Det_Pres_Par_Conf_2_aux:\n  forall phi1 phi2 phi2' heap heap',\n    (phi2, heap) ===> (phi2', heap') ->\n    Det_Trace phi2' ->\n    Det_Trace (Phi_Par phi1 phi2) ->\n    ~ Conflict_Traces (phi_as_list phi1) (phi_as_list phi2').\nProof.\n  intros phi1 phi2 phi2' heap heap' H1 H2 H3.\n   inversion_clear H3; subst. destruct H4. clear H4.  \n   generalize dependent phi1. \n   dependent induction H1; intros; inversion H0; subst; simpl in *.\n   - intro. inversion H1; trivial.\n   - intro. inversion H4; trivial.\n   - intro. inversion H4; trivial.\n   - inversion H2; inversion H0; subst.\n     eapply Conflictness_app_and_l in H3; auto.  destruct H3. \n     apply Conflictness_and_app_l; auto.\n   - apply IHPhi_Heap_Step; auto. inversion H2; inversion H0; assumption.\n   - apply H3.\n   - inversion H2; inversion H0; subst.\n     destruct H8.\n     apply Conflictness_app_and_l in H3; auto. destruct H3.\n     apply Conflictness_and_app_l; auto. \n   - inversion H2; inversion H0; subst.\n     destruct H8.\n     apply Conflictness_app_and_l in H3; auto. destruct H3.\n     apply Conflictness_and_app_l; auto. \n   - intro. inversion H1; trivial.\nQed.\n\n\nLemma Det_Pres_Par_Disj_1:\n  forall phi1 phi1' phi2 heap heap',\n    (phi1, heap) ===> (phi1', heap') ->\n    Det_Trace phi1' ->\n    Det_Trace (Phi_Par phi1 phi2) ->\n    Disjoint_Traces (phi_as_list phi1') (phi_as_list phi2).\nProof.\n  intros phi1 phi1' phi2 heap heap' H1 H2 H3.\n  inversion H3; subst; simpl. destruct H6.\n  inversion H0; subst. econstructor; intros. apply H6; auto.\n  eapply Phi_Heap_Step__Preserves_DAs; eauto.\nQed.    \n \nLemma Det_Pres_Par_Disj_1_aux:\n  forall phi1 phi1' phi2 heap heap',\n    (phi1, heap) ===> (phi1', heap') ->\n    Det_Trace phi1' ->\n    Det_Trace (Phi_Par phi1 phi2) ->\n    Disjoint_Traces (phi_as_list phi1') (phi_as_list phi2).\nProof.\n  intros phi1 phi1' phi2 heap heap' H1 H2 H3.\n  inversion_clear H3; subst. destruct H4. clear H3.\n  generalize dependent phi2.     \n  dependent induction H1; intros; simpl; try (solve [constructor]).\n  inversion H4; subst;\n  simpl in *; try (solve [econstructor ]).\n  - econstructor; intros. apply H1; [inversion H3 | assumption].\n  - econstructor; intros. inversion H3.\n  - econstructor; intros. inversion H3.\n  - inversion H2; inversion H; subst.\n    apply Disjointness_and_app_r. simpl in H4.\n    apply Disjointness_app_app_and_r in H4. destruct H4.\n    split; [ apply IHPhi_Heap_Step; eauto | assumption].\n  - inversion H2; inversion H. simpl in H4.\n    apply IHPhi_Heap_Step; eauto.\n  - econstructor; intros. inversion H1. \n  - inversion H2; inversion H; subst.\n    apply Disjointness_and_app_r. simpl in H4.\n    apply Disjointness_app_app_and_r in H4. destruct H4.\n    split; [ apply IHPhi_Heap_Step; eauto | assumption].\n  - inversion H2; inversion H; subst.\n    apply Disjointness_and_app_r. simpl in H4.\n    apply Disjointness_app_app_and_r in H4. destruct H4.\n    split; [ assumption | apply IHPhi_Heap_Step; eauto].\n  -  econstructor; intros. inversion H1.    \nQed.\n\nLemma Det_Pres_Par_Disj_2:\n  forall phi2 phi2' phi1 heap heap',\n    (phi2, heap) ===> (phi2', heap') ->\n    Det_Trace phi2' ->\n    Det_Trace (Phi_Par phi1 phi2) ->\n    Disjoint_Traces (phi_as_list phi1) (phi_as_list phi2').\nProof.\n  intros phi2 phi2' phi1 heap heap' H1 H2 H3.\n   inversion H3; subst; simpl. destruct H6.\n  inversion H0; subst. econstructor; intros. apply H6; auto.\n  eapply Phi_Heap_Step__Preserves_DAs; eauto.\nQed.   \n\nLemma Det_Pres_Par_Disj_2_aux:\n  forall phi2 phi2' phi1 heap heap',\n    (phi2, heap) ===> (phi2', heap') ->\n    Det_Trace phi2' ->\n    Det_Trace (Phi_Par phi1 phi2) ->\n    Disjoint_Traces (phi_as_list phi1) (phi_as_list phi2').\nProof.\n  intros phi2 phi2' phi1 heap heap' H1 H2 H3.\n  inversion_clear H3; subst. destruct H4. clear H3.\n  generalize dependent phi1.     \n  dependent induction H1; intros; simpl in *;\n  try (solve [constructor |\n              econstructor; intros; inversion H5 |\n              econstructor; intros; inversion H3\n             ]).\n  - inversion H2; inversion H0; subst.\n    apply Disjointness_and_app_l. simpl in H4.\n    apply Disjointness_app_app_and_l in H4. destruct H4.\n    split; [apply IHPhi_Heap_Step; eauto | assumption].\n  - inversion H2; inversion H0. \n    apply IHPhi_Heap_Step; eauto.\n  - inversion H2; inversion H0; subst.\n    apply Disjointness_and_app_l. simpl in H4.\n    apply Disjointness_app_app_and_l in H4. destruct H4.\n    split; [apply IHPhi_Heap_Step; eauto | assumption].\n  -  inversion H2; inversion H0; subst.\n    apply Disjointness_and_app_l. simpl in H4.\n    apply Disjointness_app_app_and_l in H4. destruct H4.\n    split; [assumption | apply IHPhi_Heap_Step; eauto].\nQed.\n\nTheorem Det_Pres_Aux :\n   forall phi phi' heap heap',\n     (phi, heap) ===> (phi', heap') ->\n     Det_Trace phi ->\n     Det_Trace phi'.\nProof.\n  intros phi phi' heap heap' H1 H2.\n  dependent induction H1; intros; try (solve [constructor]).\n  - inversion H2; econstructor; [ apply IHPhi_Heap_Step; assumption | assumption].\n  - inversion H2; econstructor. constructor. apply IHPhi_Heap_Step; assumption. \n  - inversion H2; subst; econstructor; [ apply IHPhi_Heap_Step; assumption | inversion H2; assumption |].\n    destruct H5. split.\n    + intro; inversion H5; subst.\n      apply H; econstructor; eauto using Phi_Heap_Step__Preserves_DAs.\n    + constructor; intros.\n      inversion H0; subst.\n      apply H7; eauto using Phi_Heap_Step__Preserves_DAs.\n  - inversion H2; subst; econstructor; [assumption | apply IHPhi_Heap_Step; assumption |].\n    destruct H5. split.\n    + intro; inversion H5; subst.\n      apply H; econstructor; eauto using Phi_Heap_Step__Preserves_DAs.\n    + constructor; intros.\n      inversion H0; subst.\n      apply H7; eauto using Phi_Heap_Step__Preserves_DAs.\nQed.    \n\nTheorem Det_Pres :\n   forall phi phi' heap heap' n',\n     (phi, heap) =a=>* (phi', heap', n') ->\n     Det_Trace phi ->\n     Det_Trace phi'.\nProof.\n   intros phi phi' heap heap' n' HSteps.\n   dependent induction HSteps; intro HDet.\n   - assumption.\n   - eapply Det_Pres_Aux; eassumption.\n   - apply IHHSteps2; apply IHHSteps1; assumption.\nQed.\n\n\n    \nTheorem Diamond_Walk_Aux : \n  forall n n1 n2,\n    n = n1 + n2 ->\n    forall phi0 phi1 phi2 heap0 heap1 heap2,\n    forall (H0_1: (phi0, heap0) =a=>* (phi1, heap1, n1)),\n    forall (H0_2: (phi0, heap0) =a=>* (phi2, heap2, n2)),\n      Det_Trace phi0 ->\n      exists phi3, exists heap3, exists heap4, exists n13, exists n23,\n        H.Equal heap3 heap4 /\\                                                             \n        (phi1, heap1) =a=>* (phi3, heap3, n13) /\\\n        (phi2, heap2) =a=>* (phi3, heap4, n23) /\\\n        (n13 <= n2) /\\ (n23 <= n1).\nProof.\n  induction n using Wf_nat.lt_wf_ind.\n  intros n1 n2 HSum.\n  intros phi0 phi1 phi2 heap0 heap1 heap2 H0_1 H0_2 HDet. \n  dependent destruction H0_1.\n  - exists phi2; exists heap2; exists heap2; exists n2; exists 0.\n   repeat split; try (solve [omega]).\n   + assumption.  (* phi1 walks into phi1 in n2 steps *)\n   + apply PHT_Refl.  (* phi2 takes 0 steps *)\n  -  rename H0 into H0_1.  \n    dependent destruction H0_2.\n    + exists phi1. exists heap1. exists heap1. exists 0. exists 1.\n      repeat split; try (solve [omega]).\n      * apply PHT_Refl. (* phi1 takes 0 steps *)\n      * apply PHT_Step; assumption. (* phi2 walks into phi1 in 1 step *)\n    + rename H0 into H0_2.\n      destruct (Diamond_Step phi0 phi1 phi2 heap0 heap1 heap2 HDet H0_1 H0_2)\n        as [phi3 [heap3 [heap4 [n13 [n23 [Heq [H1_3 [H2_3 [? ?]]]]]]]]].\n      exists phi3. exists heap3. exists heap4. exists n13. exists n23. (* n13 and n23 are the remaining steps *)\n      repeat split;  try (solve [omega]). \n      * assumption. (* context provided by Diamond_Step *)\n      * assumption. (* context provided by Diamond_Step *)\n      * assumption.\n    + rename phi' into phi2'. rename heap' into heap2'. \n      rename H0_2_1 into H0_2'. rename H0_2_2 into H2'_2. \n      edestruct (H (1 + n')) as [phi3 [heap3 [heap4 [n1_3 [n2'_3 [Heq [H1_3 [H2'_3 [? ?]]]]]]]]]. (* transitivity on phi2 *)\n      * omega. (* phi2 took n' intermediate steps *)\n      * reflexivity.\n      * eapply PHT_Step; eassumption.  (* phi1 steps 1 *)\n      * eassumption. (* by induction *)\n      * eassumption. (* by induction *)  \n      * { edestruct (H (n2'_3 + n'')) as [phi4 [heap5 [heap6 [n3_4 [n2_4 [Heq' [H3_4 [H2_4 [? ?]]]]]]]]].\n          - omega.  (* phi2 took n'' intermediate steps *)\n          - reflexivity.\n          - eassumption. (* by induction *)\n          - eassumption. (* by induction *)\n          - eapply Det_Pres; eassumption.\n          - apply Aux_Step_Ext_Heap with (heapB:=heap3) in H3_4; [ | apply HMapP.Equal_sym; assumption].\n            destruct H3_4 as [heap5' [? ?]].\n            exists phi4. exists heap5'. exists heap6. exists (1 + n1_3 + n3_4). exists n2_4.\n            repeat split; try (solve [omega]).\n            + eapply HMapP.Equal_trans in Heq'; eauto. apply HMapP.Equal_sym; assumption.  \n            + eapply PHT_Trans. eassumption. assumption.\n            + assumption. }\n  - rename phi' into phi1'. rename heap' into heap1'.\n    rename H0_1_1 into H0_1'. rename H0_1_2 into H1'_1.\n    edestruct (H (n' + n2)) as [phi3 [heap3 [heap4 [n1'_3 [n2_3 [Heq [H1'_3 [H2_3 [? ?]]]]]]]]].\n    + omega.  (* phi1 took n' intermediate steps *)\n    + reflexivity.\n    + eassumption.\n    + eassumption.\n    + assumption.\n    + edestruct (H (n'' + n1'_3)) as [phi4 [heap5 [heap6 [n1_4 [n3_4 [Heq' [H1_4 [H3_4 [? ?]]]]]]]]].\n      * omega. (* phi1 took the remaining n'' intermediate steps *)\n      * reflexivity. \n      * eassumption.\n      * eassumption.\n      * eapply Det_Pres; eassumption.\n      * apply Aux_Step_Ext_Heap with (heapB:=heap4) in H3_4; [ |assumption].\n        destruct H3_4 as [heap6' [? ?]]. \n        exists phi4. exists heap5. exists heap6'. exists n1_4. exists (1 + n2_3 + n3_4).\n        repeat split;  try (solve [omega]).\n        { eapply HMapP.Equal_trans in H4; eauto. }\n        { assumption. }\n        { eapply PHT_Trans. eassumption. assumption. }\nQed.\n\nTheorem Diamond_Walk_Aux_new : \n  forall n n1 n2,\n    n = n1 + n2 ->\n    forall phi0 phi1 phi2 heapa heapb heap1 heap2,\n    H.Equal heapa heapb ->\n    forall (H0_1: (phi0, heapa) =a=>* (phi1, heap1, n1)),\n    forall (H0_2: (phi0, heapb) =a=>* (phi2, heap2, n2)),\n      Det_Trace phi0 ->\n      exists phi3, exists heap3, exists heap4, exists n13, exists n23,\n        H.Equal heap3 heap4 /\\\n        (phi1, heap1) =a=>* (phi3, heap3, n13) /\\\n        (phi2, heap2) =a=>* (phi3, heap4, n23) /\\\n        (n13 <= n2) /\\ (n23 <= n1).\nProof.\n  induction n using Wf_nat.lt_wf_ind.\n  intros n1 n2 HSum.\n  intros phi0 phi1 phi2 heapa heapb heap1 heap2 HEqual H0_1 H0_2 HDet. \n  dependent destruction H0_1.\n  - assert (HEqual' : H.Equal heapb heap1) by (eauto using HMapP.Equal_sym).\n    edestruct (Aux_Step_Ext_Heap _ _ _ _ _ _ H0_2 HEqual')\n     as [heap2' [HEqual'' ?]].\n    exists phi2; exists heap2'; exists heap2; exists n2; exists 0.\n    repeat split; try (solve [omega]).\n    + eauto using HMapP.Equal_sym.  \n    + assumption. (* phi1 walks into phi2 in n2 steps *)\n    + apply PHT_Refl.  (* phi2 takes 0 steps *)\n  - rename H0 into H0_1.  \n    dependent destruction H0_2.\n    + edestruct (Aux_Aux_Step_Ext_Heap _ _ _ _ _ H0_1 HEqual)\n       as [heap1' [HEqual' H0_1']].\n      exists phi1. exists heap1. exists heap1'. exists 0. exists 1.\n      repeat split; try (solve [omega]).\n      * assumption.\n      * apply PHT_Refl. (* phi1 takes 0 steps *)\n      * apply PHT_Step; assumption. (* phi2 walks into phi1 in 1 step *)\n    + rename H0 into H0_2.\n      destruct (Diamond_Step_new phi0 phi1 phi2 heapa heapb heap1 heap2 HDet HEqual H0_1 H0_2)\n        as [phi3 [heap3 [heap4 [n13 [n23 [Heq [H1_3 [H2_3 [? ?]]]]]]]]].\n      exists phi3. exists heap3. exists heap4. exists n13. exists n23. (* n13 and n23 are the remaining steps *)\n      repeat split;  try (solve [omega]). \n      * assumption.\n      * assumption. (* context provided by Diamond_Step *)\n      * assumption. (* context provided by Diamond_Step *)\n    + rename phi' into phi2'. rename heap' into heap2'. \n      rename H0_2_1 into H0_2'. rename H0_2_2 into H2'_2. \n      edestruct (H (1 + n')) as [phi3 [heap3 [heap4 [n1_3 [n2'_3 [Heq [H1_3 [H2'_3 [? ?]]]]]]]]]. (* transitivity on phi2 *)\n      * omega. (* phi2 took n' intermediate steps *)\n      * reflexivity.\n      * eassumption.\n      * eapply PHT_Step; eassumption.  (* phi1 steps 1 *)\n      * eassumption. (* by induction *)\n      * eassumption. (* by induction *)  \n      * { edestruct (H (n2'_3 + n'')) as [phi4 [heap5 [heap6 [n3_4 [n2_4 [Heq' [H3_4 [H2_4 [? ?]]]]]]]]].\n          - omega.  (* phi2 took n'' intermediate steps *)\n          - reflexivity.\n          - apply HMapP.Equal_refl.\n          - eassumption. (* by induction *)\n          - eassumption. (* by induction *)\n          - eapply Det_Pres; eassumption.\n          - apply Aux_Step_Ext_Heap with (heapB:=heap3) in H3_4; [ | apply HMapP.Equal_sym; assumption].\n            destruct H3_4 as [heap5' [? ?]].\n            exists phi4. exists heap5'. exists heap6. exists (1 + n1_3 + n3_4). exists n2_4.\n            repeat split; try (solve [omega]).\n            + eapply HMapP.Equal_trans in Heq'; eauto. apply HMapP.Equal_sym; assumption.  \n            + eapply PHT_Trans. eassumption. assumption.\n            + assumption. }\n  - rename phi' into phi1'. rename heap' into heap1'.\n    rename H0_1_1 into H0_1'. rename H0_1_2 into H1'_1.\n    edestruct (H (n' + n2)) as [phi3 [heap3 [heap4 [n1'_3 [n2_3 [Heq [H1'_3 [H2_3 [? ?]]]]]]]]].\n    + omega.  (* phi1 took n' intermediate steps *)\n    + reflexivity.\n    + eassumption.\n    + eassumption.\n    + eassumption.\n    + assumption.\n    + edestruct (H (n'' + n1'_3)) as [phi4 [heap5 [heap6 [n1_4 [n3_4 [Heq' [H1_4 [H3_4 [? ?]]]]]]]]].\n      * omega. (* phi1 took the remaining n'' intermediate steps *)\n      * reflexivity. \n      * apply HMapP.Equal_refl.\n      * eassumption.\n      * eassumption.\n      * eapply Det_Pres; eassumption.\n      * apply Aux_Step_Ext_Heap with (heapB:=heap4) in H3_4; [ |assumption].\n        destruct H3_4 as [heap6' [? ?]]. \n        exists phi4. exists heap5. exists heap6'. exists n1_4. exists (1 + n2_3 + n3_4).\n        repeat split;  try (solve [omega]).\n        { eapply HMapP.Equal_trans in H4; eauto. }\n        { assumption. }\n        { eapply PHT_Trans. eassumption. assumption. }\nQed.\n\nTheorem Diamond_Walk : \n  forall phi0 phi1 phi2 heap0 heap1 heap2,\n    (phi0, heap0) ==>* (phi1, heap1) ->\n    (phi0, heap0) ==>* (phi2, heap2) ->\n    Det_Trace phi0 ->\n    exists phi3, exists heap3, exists heap4,\n      H.Equal heap3 heap4 /\\                           \n      (phi1, heap1) ==>* (phi3, heap3) /\\\n      (phi2, heap2) ==>* (phi3, heap4).\nProof.\n  intros phi0 phi1 phi2 heap0 heap1 heap2 H0_1 H0_2 HDet.\n  unfold Phi_Heap_Steps in *.\n  destruct H0_1 as [n0_1 H0_1].\n  destruct H0_2 as [n0_2 H0_2].\n  edestruct (Diamond_Walk_Aux (n0_1 + n0_2) n0_1 n0_2) as [phi3 [heap3 [heap4 [n1_3 [n2_3 [Heq [H1_3 [H2_3 [? ?]]]]]]]]]; eauto.\n  exists phi3. exists heap3. exists heap4. repeat split;[ assumption | |]; eexists; eassumption.\nQed.\n\nTheorem Diamond_Walk_new : \n  forall phi0 phi1 phi2 heapa heapb heap1 heap2,\n    H.Equal heapa heapb ->\n    (phi0, heapa) ==>* (phi1, heap1) ->\n    (phi0, heapb) ==>* (phi2, heap2) ->\n    Det_Trace phi0 ->\n    exists phi3, exists heap3, exists heap4,\n      H.Equal heap3 heap4 /\\                           \n      (phi1, heap1) ==>* (phi3, heap3) /\\\n      (phi2, heap2) ==>* (phi3, heap4).\nProof.\n  intros phi0 phi1 phi2 heapa heapb heap1 heap2 HEqual H0_1 H0_2 HDet.\n  unfold Phi_Heap_Steps in *.\n  destruct H0_1 as [n0_1 H0_1].\n  destruct H0_2 as [n0_2 H0_2].\n  edestruct (Diamond_Walk_Aux_new (n0_1 + n0_2) n0_1 n0_2) as [phi3 [heap3 [heap4 [n1_3 [n2_3 [Heq [H1_3 [H2_3 [? ?]]]]]]]]]; eauto.\n  exists phi3. exists heap3. exists heap4. repeat split;[ assumption | |]; eexists; eassumption.\nQed.\n\nLemma Term_Walk_Idemp :\n  forall heap phi' heap' n,\n    (Phi_Nil, heap) =a=>* (phi', heap', n) ->\n    phi' = Phi_Nil /\\ heap = heap'.\nProof.\n  intros heap phi' heap' n HStep.\n  dependent induction HStep.\n  + split; reflexivity.\n  + inversion H.\n  + eapply IHHStep2.\n    - destruct IHHStep1; subst; reflexivity.\n    - reflexivity.\nQed.\n\nTheorem Diamond_Term_Walk : \n  forall phi0 heap0 heap1 heap2,\n    (phi0, heap0) ==>* (Phi_Nil, heap1) ->\n    (phi0, heap0) ==>* (Phi_Nil, heap2) ->\n    Det_Trace phi0 ->\n    H.Equal heap1 heap2.\nProof.\n  intros phi0 heap0 heap1 heap2 HDet HStep1 HStep2.\n  edestruct (Diamond_Walk phi0 Phi_Nil Phi_Nil heap0 heap1 heap2) as [phi3 [heap3 [heap4 [Heq [H1 H2]]]]]; try eassumption.\n  destruct H1 as [n1 H1]. destruct H2 as [n2 H2].\n  edestruct (Term_Walk_Idemp heap1 phi3 heap3 n1) as [? ?]; try eassumption.\n  edestruct (Term_Walk_Idemp heap2 phi3 heap4 n2) as [? ?]; try eassumption.\n  subst. assumption.\nQed.\n\nTheorem Diamond_Term_Walk_new : \n  forall phi0 heapa heapb heap1 heap2,\n    H.Equal heapa heapb ->\n    (phi0, heapa) ==>* (Phi_Nil, heap1) ->\n    (phi0, heapb) ==>* (Phi_Nil, heap2) ->\n    Det_Trace phi0 ->\n    H.Equal heap1 heap2.\nProof.\n  intros phi0 heapa heapb heap1 heap2 HEqual HStep1 HStep2 HDet.\n  edestruct (Diamond_Walk_new phi0 Phi_Nil Phi_Nil heapa heapb heap1 heap2) as [phi3 [heap3 [heap4 [Heq [H1 H2]]]]]; try eassumption.\n  destruct H1 as [n1 H1]. destruct H2 as [n2 H2].\n  edestruct (Term_Walk_Idemp heap1 phi3 heap3 n1) as [? ?]; try eassumption.\n  edestruct (Term_Walk_Idemp heap2 phi3 heap4 n2) as [? ?]; try eassumption.\n  subst. assumption.\nQed.\n\nLemma Ext_disjoint_sets :\n  forall e1 acts a,\n    Disjoint_Sets_Computed_Actions e1 (set_union acts a) ->\n    Disjoint_Sets_Computed_Actions e1 acts /\\ Disjoint_Sets_Computed_Actions e1 a.\nProof.\n  intros e1 acts a H. \n  split; inversion H; subst.\n  - econstructor; intros. apply H0; auto. unfold set_elem, set_union. apply Union_introl. assumption.\n  - econstructor. intros. apply H0; auto. unfold set_elem, set_union. apply Union_intror. assumption.\nQed.\n\nLemma Ext_disjoint_sets_2 :\n  forall e1 acts a,\n    Disjoint_Sets_Computed_Actions (set_union acts a) e1 ->\n    Disjoint_Sets_Computed_Actions acts e1 /\\ Disjoint_Sets_Computed_Actions a e1.\nProof.\n  intros e1 acts a H. \n  split; inversion H; subst.\n  - econstructor; intros. apply H0; auto. unfold set_elem, set_union. apply Union_introl. assumption.\n  - econstructor. intros. apply H0; auto. unfold set_elem, set_union. apply Union_intror. assumption.\nQed.\n\nLemma Disjoint_da_in_theta :\n  forall e1 e2 p1 p2,\n    Disjoint_Sets_Computed_Actions e1 e2 ->\n    DA_in_Theta p1 (Some e1) ->\n    DA_in_Theta p2 (Some e2) ->\n    Disjoint_Dynamic p1 p2.\nProof.\n  intros e1 e2 p1 p2 H1 H2 H3.\n  generalize dependent p2. \n  dependent induction H2; intros.\n  - generalize dependent e1. \n    dependent induction H3; intros; inversion H1; subst.  \n    + assert (HD : Disjoint_Computed_Actions (CA_AllocAbs s) (CA_AllocAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H5. inversion H5. reflexivity.\n    + assert (HD : Disjoint_Computed_Actions (CA_AllocAbs s) (CA_ReadAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H5; inversion H5; reflexivity.\n    + assert (HD : Disjoint_Computed_Actions (CA_AllocAbs s) (CA_ReadConc s0 l0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor; contradict H5; inversion H5; reflexivity.\n    + assert (HD : Disjoint_Computed_Actions (CA_AllocAbs s) (CA_WriteAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H5. inversion H5. reflexivity.\n    + assert (HD : Disjoint_Computed_Actions (CA_AllocAbs s) (CA_WriteConc s0 l0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H5. inversion H5. reflexivity.\n    + eapply IHDA_in_Theta; eauto.\n      apply Ext_disjoint_sets in H1; destruct H1; assumption.\n    + eapply IHDA_in_Theta; eauto.\n      apply Ext_disjoint_sets in H1; destruct H1; assumption.\n  - generalize dependent e1.  \n    dependent induction H3; intros; inversion H1; subst.\n    + assert (HD : Disjoint_Computed_Actions (CA_ReadAbs s) (CA_AllocAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H5; inversion H5; reflexivity.\n    + assert (HD : Disjoint_Computed_Actions (CA_ReadAbs s) (CA_ReadAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. \n    + assert (HD : Disjoint_Computed_Actions (CA_ReadAbs s) (CA_ReadConc s0 l0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor.\n    + assert (HD : Disjoint_Computed_Actions (CA_ReadAbs s) (CA_WriteAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H5; inversion H5; reflexivity.\n    + assert (HD : Disjoint_Computed_Actions (CA_ReadAbs s) (CA_WriteConc s0 l0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H5; inversion H5; reflexivity.\n    + eapply IHDA_in_Theta; eauto.\n      apply Ext_disjoint_sets in H1; destruct H1; assumption.\n    + eapply IHDA_in_Theta; eauto.\n      apply Ext_disjoint_sets in H1; destruct H1; assumption. \n  - generalize dependent e1.  \n    dependent induction H3; intros; inversion H1; subst.\n    + assert (HD : Disjoint_Computed_Actions (CA_ReadConc s l) (CA_AllocAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H4; inversion H4; reflexivity.\n    + assert (HD : Disjoint_Computed_Actions (CA_ReadConc s l) (CA_ReadAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor.\n    + assert (HD : Disjoint_Computed_Actions (CA_ReadConc s l) (CA_ReadConc s0 l0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor.\n    + assert (HD : Disjoint_Computed_Actions (CA_ReadConc s l) (CA_WriteAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H4; inversion H4; reflexivity.\n    + assert (HD : Disjoint_Computed_Actions (CA_ReadConc s l) (CA_WriteConc s0 l0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H6; inversion H6; reflexivity.\n    + eapply IHDA_in_Theta; eauto.\n      apply Ext_disjoint_sets in H1; destruct H1; assumption.\n    + eapply IHDA_in_Theta; eauto.\n      apply Ext_disjoint_sets in H1; destruct H1; assumption.  \n  - generalize dependent e1.  \n    dependent induction H3; intros; inversion H1; subst.\n    + assert (HD : Disjoint_Computed_Actions (CA_WriteAbs s) (CA_AllocAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H5; inversion H5; reflexivity.\n    + assert (HD : Disjoint_Computed_Actions (CA_WriteAbs s) (CA_ReadAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H5; inversion H5; reflexivity.\n    + assert (HD : Disjoint_Computed_Actions (CA_WriteAbs s) (CA_ReadConc s0 l0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H5; inversion H5; reflexivity.\n    + assert (HD : Disjoint_Computed_Actions (CA_WriteAbs s) (CA_WriteAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H5; inversion H5; reflexivity.\n    + assert (HD : Disjoint_Computed_Actions (CA_WriteAbs s) (CA_WriteConc s0 l0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H5; inversion H5; reflexivity.\n    + eapply IHDA_in_Theta; eauto.\n      apply Ext_disjoint_sets in H1; destruct H1; assumption.\n    + eapply IHDA_in_Theta; eauto.\n      apply Ext_disjoint_sets in H1; destruct H1; assumption.\n  - generalize dependent e1.  \n    dependent induction H3; intros; inversion H1; subst.\n    + assert (HD : Disjoint_Computed_Actions (CA_WriteConc s l) (CA_AllocAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H4; inversion H4; reflexivity.\n    +  assert (HD : Disjoint_Computed_Actions (CA_WriteConc s l) (CA_ReadAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H4; inversion H4; reflexivity. \n    + assert (HD : Disjoint_Computed_Actions (CA_WriteConc s l) (CA_ReadConc s0 l0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H6. inversion H6. reflexivity.\n    + assert (HD : Disjoint_Computed_Actions (CA_WriteConc s l) (CA_WriteAbs s0)) by (apply H2; auto).\n      inversion HD; subst.\n    + assert (HD : Disjoint_Computed_Actions (CA_WriteConc s l) (CA_WriteConc s0 l0)) by (apply H2; auto).\n      inversion HD; subst.\n      constructor. contradict H6. inversion H6. reflexivity.\n    + eapply IHDA_in_Theta; eauto.\n      apply Ext_disjoint_sets in H1; destruct H1; assumption.\n    + eapply IHDA_in_Theta; eauto.\n      apply Ext_disjoint_sets in H1; destruct H1; assumption.\n  -  apply Ext_disjoint_sets_2 in H1; destruct H1.\n     eapply IHDA_in_Theta with (e1:=acts); eauto.\n  -  apply Ext_disjoint_sets_2 in H1; destruct H1.\n     eapply IHDA_in_Theta with (e1:=acts); eauto.  \nQed.\n    \nLemma Disjoint_computed_disjoint_dynamic_action:\n  forall e1 e2 phi1 phi2 p1 p2,\n    phi1 ⊑ Some e1 ->\n    phi2 ⊑ Some e2 ->\n    Disjoint_Sets_Computed_Actions e1 e2 -> \n    In p1 (phi_as_list phi1) ->\n    In p2 (phi_as_list phi2) -> \n    Disjoint_Dynamic p1 p2.\nProof.\n  intros e1 e2 phi1 phi2 p1 p2 H1 H2 H3 H4 H5.\n  generalize dependent phi2.\n  dependent induction H1; intros; simpl in *.\n  - contradiction.\n  - destruct H4; subst.\n    + dependent induction H2; simpl in H5.\n      * contradiction.\n      * destruct H5; [subst | contradiction ].\n        eapply Disjoint_da_in_theta; eauto.\n      * apply in_app_or in H5. destruct H5.\n        { eapply  IHPhi_Theta_Soundness1; eauto. }\n        { eapply  IHPhi_Theta_Soundness2; eauto. }\n      * apply in_app_or in H5. destruct H5.\n        { eapply  IHPhi_Theta_Soundness1; eauto. }\n        { eapply  IHPhi_Theta_Soundness2; eauto. }\n    + contradiction.\n  - apply in_app_or in H4. destruct H4.\n    + eapply  IHPhi_Theta_Soundness1; eauto.\n    + eapply  IHPhi_Theta_Soundness2; eauto.\n  - apply in_app_or in H4. destruct H4.\n    + eapply  IHPhi_Theta_Soundness1; eauto.\n    + eapply  IHPhi_Theta_Soundness2; eauto.\nQed.\n\n\nLemma Ext_Conflict_sets_1 :\n  forall e acts a,\n    Conflict_Sets_Computed_Actions e acts \\/ Conflict_Sets_Computed_Actions e a ->\n    Conflict_Sets_Computed_Actions e (set_union acts a).\nProof.\n  intros e acts a H. destruct H.\n  - inversion H; subst.\n    econstructor; eauto. apply Union_introl. assumption.\n  - inversion H; subst.\n    econstructor; eauto. apply Union_intror. assumption. \nQed.\n\nLemma Ext_Conflict_sets_2 :\n  forall e acts a,\n    Conflict_Sets_Computed_Actions acts e \\/ Conflict_Sets_Computed_Actions a e ->\n    Conflict_Sets_Computed_Actions (set_union acts a) e.\nProof.\n  intros e acts a H. destruct H.\n  - inversion H; subst.\n    econstructor; eauto. apply Union_introl. assumption.\n  - inversion H; subst.\n    econstructor; eauto. apply Union_intror. assumption. \nQed.\n\nLemma Conflict_da_in_theta_read :\n  forall r l v e0 e,\n    DA_in_Theta (DA_Write r l v) (Some e0) ->\n    DA_in_Theta (DA_Read r l v) (Some e) ->\n    Conflict_Sets_Computed_Actions e e0. \nProof.\n  intros.\n  generalize dependent e0.\n  dependent induction H0; intros.\n  - dependent induction H0; intros.\n    + econstructor; eauto. constructor.\n    + econstructor; eauto. constructor. \n    + apply Ext_Conflict_sets_1. left. eapply IHDA_in_Theta; eauto.\n    + apply Ext_Conflict_sets_1. right. eapply IHDA_in_Theta; eauto.\n  - dependent induction H0; intros.\n    + econstructor; eauto. constructor.\n    + econstructor; eauto. constructor. \n    + apply Ext_Conflict_sets_1. left. eapply IHDA_in_Theta; eauto.\n    + apply Ext_Conflict_sets_1. right. eapply IHDA_in_Theta; eauto.\n  - apply Ext_Conflict_sets_2.  left. eapply IHDA_in_Theta; eauto.\n  - apply Ext_Conflict_sets_2.  right. eapply IHDA_in_Theta; eauto.\nQed.\n\nLemma Conflict_da_in_theta_write :\n  forall r l v e0 e,\n    DA_in_Theta (DA_Write r l v) (Some e0) ->\n    DA_in_Theta (DA_Write r l v) (Some e) ->\n    Conflict_Sets_Computed_Actions e e0. \nProof.\n  intros.\n  generalize dependent e0.\n  dependent induction H0; intros.\n  - dependent induction H0; intros.\n    + econstructor; eauto. constructor.\n    + econstructor; eauto. constructor. \n    + apply Ext_Conflict_sets_1. left. eapply IHDA_in_Theta; eauto.\n    + apply Ext_Conflict_sets_1. right. eapply IHDA_in_Theta; eauto.\n  - dependent induction H0; intros.\n    + econstructor; eauto. constructor.\n    + econstructor; eauto. constructor. \n    + apply Ext_Conflict_sets_1. left. eapply IHDA_in_Theta; eauto.\n    + apply Ext_Conflict_sets_1. right. eapply IHDA_in_Theta; eauto.\n  - apply Ext_Conflict_sets_2.  left. eapply IHDA_in_Theta; eauto.\n  - apply Ext_Conflict_sets_2.  right. eapply IHDA_in_Theta; eauto.\nQed.\n\nLemma Conflict_computed_conflict_dynamic_action_write:\n  forall phi1 phi2 e e0 r l v,\n  phi1 ⊑ Some e ->\n  phi2 ⊑ Some e0 ->\n  In (DA_Write r l v) (phi_as_list phi1) ->\n  In (DA_Write r l v) (phi_as_list phi2) ->\n  Conflict_Sets_Computed_Actions e e0.\nProof.\n  intros. generalize dependent phi2.\n  dependent induction phi1; simpl in *.\n  - contradiction.\n  - intuition; subst.\n    dependent induction H1; simpl in *.\n    + contradiction.\n    + intuition; subst. inversion H0; subst.\n      eapply Conflict_da_in_theta_write; eauto.\n    + apply in_app_or in H2. destruct H2; [eapply IHPhi_Theta_Soundness1 | eapply IHPhi_Theta_Soundness2] ; eauto.\n    + apply in_app_or in H2. destruct H2; [eapply IHPhi_Theta_Soundness1 | eapply IHPhi_Theta_Soundness2] ; eauto.   \n  - inversion H; apply in_app_or in H1. destruct H1; [eapply IHphi1_1 | eapply IHphi1_2] ; eauto.\n  - inversion H; apply in_app_or in H1. destruct H1; [eapply IHphi1_1 | eapply IHphi1_2] ; eauto.\nQed.\n\nLemma Conflict_computed_conflict_dynamic_action_read:\n  forall phi1 phi2 e e0 r l v,\n  phi1 ⊑ Some e ->\n  phi2 ⊑ Some e0 ->\n  In (DA_Write r l v) (phi_as_list phi2) ->\n  In (DA_Read r l v) (phi_as_list phi1) ->\n  Conflict_Sets_Computed_Actions e e0.\nProof.\n  intros. generalize dependent phi2.\n  dependent induction phi1; simpl in *.\n  - contradiction.\n  - intuition; subst.\n    dependent induction H1; simpl in *.\n    + contradiction.\n    + intuition; subst. inversion H0; subst.\n      eapply Conflict_da_in_theta_read; eauto.\n    + apply in_app_or in H2. destruct H2; [eapply IHPhi_Theta_Soundness1 | eapply IHPhi_Theta_Soundness2] ; eauto.\n    + apply in_app_or in H2. destruct H2; [eapply IHPhi_Theta_Soundness1 | eapply IHPhi_Theta_Soundness2] ; eauto.   \n  - inversion H; apply in_app_or in H2. destruct H2; [eapply IHphi1_1 | eapply IHphi1_2] ; eauto.\n  - inversion H; apply in_app_or in H2. destruct H2; [eapply IHphi1_1 | eapply IHphi1_2] ; eauto.\nQed.\n\nLemma Det_trace_from_readonly :\n  forall phi,\n    ReadOnlyPhi phi ->\n    Det_Trace phi.\nProof.\n  intros phi H.\n  dependent induction H.\n  - constructor.\n  - constructor.\n  - constructor; auto.\n  - constructor; auto. split. \n    + generalize dependent phi2.\n      dependent induction IHReadOnlyPhi1; intros.\n      * intro. inversion H1. inversion H2.\n      * { dependent induction IHReadOnlyPhi2.\n          - intro. inversion H1. inversion H3.\n          - inversion H; inversion H0; subst.\n            intro. simpl in H1. inversion H1; subst.\n            inversion H2; subst; [ | inversion H5].  inversion H3; subst; [ | inversion H5].\n            inversion H4.\n          - simpl in *. replace (da :: nil) with (phi_as_list (Phi_Elem da))  by (simpl; reflexivity).\n            inversion H0; subst.\n            apply Conflictness_and_app_l. split; [apply IHIHReadOnlyPhi2_1 | apply IHIHReadOnlyPhi2_2]; assumption.\n          - simpl in *. replace (da :: nil) with (phi_as_list (Phi_Elem da))  by (simpl; reflexivity).\n            inversion H0; subst.\n            apply Conflictness_and_app_l. split; [apply IHIHReadOnlyPhi2_1 | apply IHIHReadOnlyPhi2_2]; assumption. }\n      * inversion H; subst.\n        apply Conflictness_and_app_r. split; [apply IHIHReadOnlyPhi1_1 | apply IHIHReadOnlyPhi1_2]; assumption.\n      * inversion H; subst.\n        apply Conflictness_and_app_r. split; [apply IHIHReadOnlyPhi1_1 | apply IHIHReadOnlyPhi1_2]; assumption.\n    + generalize dependent phi2.\n      dependent induction IHReadOnlyPhi1; intros.\n      * constructor. intros. inversion H1.\n      * { dependent induction IHReadOnlyPhi2.\n          - constructor. intros. inversion H2.\n          - inversion H; inversion H0; subst.\n            constructor. intros. simpl in *. intuition; subst.\n            constructor.\n          - simpl.  replace (da :: nil) with (phi_as_list (Phi_Elem da))  by (simpl; reflexivity).\n            inversion H0; subst.\n            apply Disjointness_and_app_l.  split; [apply IHIHReadOnlyPhi2_1 | apply IHIHReadOnlyPhi2_2]; assumption.\n          - simpl.  replace (da :: nil) with (phi_as_list (Phi_Elem da))  by (simpl; reflexivity).\n            inversion H0; subst.\n            apply Disjointness_and_app_l.  split; [apply IHIHReadOnlyPhi2_1 | apply IHIHReadOnlyPhi2_2]; assumption. }\n      * inversion H; subst.\n        apply Disjointness_and_app_r. split; [apply IHIHReadOnlyPhi1_1 | apply IHIHReadOnlyPhi1_2]; assumption.\n      * inversion H; subst.\n        apply Disjointness_and_app_r. split; [apply IHIHReadOnlyPhi1_1 | apply IHIHReadOnlyPhi1_2]; assumption.  \nQed.\n\nLemma Read_only_no_conflicts:\n  forall phi1 phi2,\n    ReadOnlyPhi phi1 ->\n    ReadOnlyPhi phi2 ->\n   ~ Conflict_Traces (phi_as_list phi1) (phi_as_list phi2).\nProof.\n  intros phi1 phi2 H1 H2.\n  generalize dependent phi2.\n  dependent induction phi1; intros.\n  - intro. dependent destruction H. inversion H.\n  - generalize dependent d.\n    dependent induction H2; intros.\n    + intro. inversion H. inversion H2.\n    + intro. inversion H1; subst. simpl in H.\n      inversion H; subst.\n      inversion H0; subst; [ | inversion H4].\n      inversion H2; subst; [ | inversion H4].\n      inversion H3.\n    + simpl. replace (d :: nil) with (phi_as_list (Phi_Elem d)) by (simpl; reflexivity).\n      apply Conflictness_and_app_l. split; [apply IHReadOnlyPhi1 | apply IHReadOnlyPhi2]; assumption.\n    + simpl. replace (d :: nil) with (phi_as_list (Phi_Elem d)) by (simpl; reflexivity).\n      apply Conflictness_and_app_l. split; [apply IHReadOnlyPhi1 | apply IHReadOnlyPhi2]; assumption.\n  - simpl. apply Conflictness_and_app_r.\n    inversion H1; subst.\n    split; [apply IHphi1_1 | apply IHphi1_2]; assumption.  \n  - simpl. apply Conflictness_and_app_r.\n    inversion H1; subst.\n    split; [apply IHphi1_1 | apply IHphi1_2]; assumption.\nQed.\n\nLemma Read_only_disjointness:\n  forall phi1 phi2,\n    ReadOnlyPhi phi1 ->\n    ReadOnlyPhi phi2 ->\n    Disjoint_Traces (phi_as_list phi1) (phi_as_list phi2).\nProof.\n  intros phi1 phi2 H. generalize phi2.\n  dependent induction H; intros.\n  - constructor. intros. inversion H0.\n  - constructor. dependent induction H; intros; simpl in *.\n    + inversion H0.\n    + intuition; subst. constructor.\n    + intuition; subst. apply in_app_or in H2. destruct H2; [apply IHReadOnlyPhi1 | apply IHReadOnlyPhi2]; intuition.\n    + intuition; subst. apply in_app_or in H2. destruct H2; [apply IHReadOnlyPhi1 | apply IHReadOnlyPhi2]; intuition.\n  - simpl. apply Disjointness_and_app_r. split; auto.\n  - simpl. apply Disjointness_and_app_r. split; auto.\nQed.    \n  \nLemma Det_par_trace_from_readonly :\n  forall phi1 phi2,\n    ReadOnlyPhi phi1 ->\n    ReadOnlyPhi phi2 ->\n    Det_Trace (Phi_Par phi1 phi2).\nProof.\n  intros phi1 phi2 H1 H2.\n  generalize dependent phi2.\n  dependent induction H1; intros; constructor.\n  - constructor.\n  - dependent induction phi2.\n    + constructor.\n    + constructor; assumption.\n    + inversion H2; constructor; [apply IHphi2_1 | apply IHphi2_2 |]; try assumption.\n      split; [apply Read_only_no_conflicts | apply Read_only_disjointness]; assumption.\n    + inversion H2; constructor; [apply IHphi2_1 | apply IHphi2_2 ]; assumption.\n  - split; simpl.\n    + intro. inversion H; subst. inversion H0.\n    + econstructor; intros. inversion H.\n  - constructor.\n  - dependent induction H2; try (solve [constructor; auto]).\n    constructor; auto.\n    split; [apply Read_only_no_conflicts | apply Read_only_disjointness]; assumption.\n  - split; simpl.\n    + dependent induction H2.\n      * intro. inversion H. inversion H1.\n      * intro. simpl in H. inversion H; subst.\n        { inversion H2; subst.\n          - inversion H1; inversion H3.\n          - inversion H1; inversion H3. }\n      * simpl. replace (DA_Read r a v :: nil) with (phi_as_list (Phi_Elem (DA_Read r a v))) by (simpl; reflexivity).\n        apply Conflictness_and_app_l. split; auto.\n      * simpl. replace (DA_Read r a v :: nil) with (phi_as_list (Phi_Elem (DA_Read r a v))) by (simpl; reflexivity).\n        apply Conflictness_and_app_l. split; auto.\n    + dependent induction H2; simpl.\n      * constructor; intros. inversion H0.\n      * econstructor; intros.\n        inversion H; subst; [| inversion H1]. inversion H0; subst; [| inversion H1]. constructor.\n      * simpl. replace (DA_Read r a v :: nil) with (phi_as_list (Phi_Elem (DA_Read r a v))) by (simpl; reflexivity).\n        apply Disjointness_and_app_l.  split; auto.\n      * simpl. replace (DA_Read r a v :: nil) with (phi_as_list (Phi_Elem (DA_Read r a v))) by (simpl; reflexivity).\n        apply Disjointness_and_app_l.  split; auto.\n  - constructor; apply Det_trace_from_readonly; auto.\n  - apply Det_trace_from_readonly; auto.\n  - split; simpl.\n    + dependent induction H2.\n      * intro. inversion H. inversion H1.\n      * intro. simpl in H. inversion H; subst.\n        { inversion H2; subst.\n          - inversion H1; inversion H3.\n          - inversion H1; inversion H3. }\n      * replace (phi_as_list phi1 ++ phi_as_list phi2) with (phi_as_list (Phi_Seq phi1 phi2)) by (simpl; reflexivity).\n        apply Conflictness_and_app_l. split; auto.\n      * replace (phi_as_list phi1 ++ phi_as_list phi2) with (phi_as_list (Phi_Seq phi1 phi2)) by (simpl; reflexivity).\n        apply Conflictness_and_app_l. split; auto.\n    + dependent induction H2; simpl.\n      * constructor; intros. inversion H0.\n      * replace (DA_Read r a v :: nil) with (phi_as_list (Phi_Elem (DA_Read r a v))) by (simpl; reflexivity). \n        assert (ReadOnlyPhi (Phi_Elem (DA_Read r a v))) by constructor.\n        apply IHReadOnlyPhi1 in H. inversion H; subst.\n        destruct H4; apply  Disjointness_and_app_r. split; [ auto | ].\n        assert (ReadOnlyPhi (Phi_Elem (DA_Read r a v))) by constructor.\n        apply IHReadOnlyPhi2 in H4. inversion H4; subst.\n        destruct H9. auto.\n      * replace (phi_as_list phi1 ++ phi_as_list phi2) with (phi_as_list (Phi_Seq phi1 phi2)) by (simpl; reflexivity).\n        apply Disjointness_and_app_l.  split; auto.\n      * replace (phi_as_list phi1 ++ phi_as_list phi2) with (phi_as_list (Phi_Seq phi1 phi2)) by (simpl; reflexivity).\n        apply Disjointness_and_app_l.  split; auto.\n  - apply IHReadOnlyPhi1 in H1_0. assumption.\n  - apply Det_trace_from_readonly; auto.\n  - split; simpl. \n    + dependent induction H2.\n      * intro. inversion H. inversion H1.\n      * intro. simpl in H. inversion H; subst.\n        { inversion H2; subst.\n          - inversion H1; inversion H3.\n          - inversion H1; inversion H3. }\n      * replace (phi_as_list phi1 ++ phi_as_list phi2) with (phi_as_list (Phi_Par phi1 phi2)) by (simpl; reflexivity).\n        apply Conflictness_and_app_l. split; auto.\n      * replace (phi_as_list phi1 ++ phi_as_list phi2) with (phi_as_list (Phi_Par phi1 phi2)) by (simpl; reflexivity).\n        apply Conflictness_and_app_l. split; auto.\n     + dependent induction H2; simpl.\n      * constructor; intros. inversion H0.\n      * replace (DA_Read r a v :: nil) with (phi_as_list (Phi_Elem (DA_Read r a v))) by (simpl; reflexivity).\n        assert (ReadOnlyPhi (Phi_Elem (DA_Read r a v))) by constructor.\n        apply IHReadOnlyPhi1 in H. inversion H; subst. destruct H4.\n        apply Disjointness_and_app_r. split; [auto |].\n        assert (ReadOnlyPhi (Phi_Elem (DA_Read r a v))) by constructor.\n        apply IHReadOnlyPhi2 in H4. inversion H4; subst. destruct H9.\n        assumption.        \n      * replace (phi_as_list phi1 ++ phi_as_list phi2) with (phi_as_list (Phi_Par phi1 phi2)) by (simpl; reflexivity).\n        apply Disjointness_and_app_l.  split; auto.\n      * replace (phi_as_list phi1 ++ phi_as_list phi2) with (phi_as_list (Phi_Par phi1 phi2)) by (simpl; reflexivity).\n        apply Disjointness_and_app_l.  split; auto.\nQed.\n     \n\nLemma Det_trace_from_theta :\n  forall theta1 theta2 phi1 phi2,\n    phi1 ⊑ theta1 ->\n    phi2 ⊑ theta2 ->\n    Disjointness theta1 theta2 /\\ not (Conflictness theta1 theta2) -> \n    Det_Trace phi1 ->\n    Det_Trace phi2 ->\n    Det_Trace (Phi_Par phi1 phi2).\nProof.\n  intros theta1 theta2 phi1 phi2 H1 H2 [HDisj HConf] HDet1 HDet2.\n  constructor; [assumption | assumption | split].\n  - intro. dependent induction H. inversion H3; subst. apply HConf.\n    + destruct theta1; destruct theta2; constructor.\n      eapply Conflict_computed_conflict_dynamic_action_read; eauto. \n    + destruct theta1 ; [ | apply HConf; constructor ].\n      destruct theta2 ; [ | apply HConf; constructor ].    \n      apply HConf. constructor. eapply Conflict_computed_conflict_dynamic_action_write; eauto.\n  - destruct theta1; [ | dependent destruction HDisj].\n    destruct theta2; [ | dependent destruction HDisj]. \n    dependent destruction HDisj. constructor; intros.\n    eapply Disjoint_computed_disjoint_dynamic_action with (e1:=e) (e2:=e0); eauto.\nQed.\n\nLemma unique_heap :\n  forall (heap heap1 heap2: Heap) (acts_mu1 acts_mu2: Phi) (theta1 theta2 : Theta),\n    acts_mu1 ⊑ theta1 ->\n    acts_mu2 ⊑ theta2 ->\n    Disjointness theta1 theta2 /\\ not (Conflictness theta1 theta2) ->\n    Det_Trace acts_mu1 ->\n    Det_Trace acts_mu2 ->\n    (Phi_Par acts_mu1 acts_mu2, heap) ==>* (Phi_Nil, heap2) ->\n    (Phi_Par acts_mu1 acts_mu2, heap) ==>* (Phi_Nil, heap1) ->\n    H.Equal heap1 heap2.\nProof.\n  intros.\n  eapply Diamond_Term_Walk; eauto.\n  eapply Det_trace_from_theta; eauto.\nQed.\n\nLemma unique_heap_new :\n  forall (heapa heapb heap1 heap2: Heap) (acts_mu1 acts_mu2: Phi) (theta1 theta2 : Theta),\n    acts_mu1 ⊑ theta1 ->\n    acts_mu2 ⊑ theta2 ->\n    Disjointness theta1 theta2 /\\ not (Conflictness theta1 theta2) ->\n    Det_Trace acts_mu1 ->\n    Det_Trace acts_mu2 ->\n    H.Equal heapa heapb ->\n    (Phi_Par acts_mu1 acts_mu2, heapa) ==>* (Phi_Nil, heap1) ->\n    (Phi_Par acts_mu1 acts_mu2, heapb) ==>* (Phi_Nil, heap2) ->\n    H.Equal heap1 heap2.\nProof.\n  intros.\n  eapply Diamond_Term_Walk_new; eauto.\n  eapply Det_trace_from_theta; eauto.\nQed.\n\n\nTheorem Dynamic_DetTrace :\n  forall heap rgns env exp heap' val' phi',\n    (heap, rgns, env, exp) ⇓ (heap', val', phi') ->\n    Det_Trace phi'.\nProof.\n  intros heap rgs evn exp heap' val' phi' HStep.\n  dependent induction HStep;\n  try (solve [repeat constructor; try (eapply IHHStep; reflexivity); try (eapply IHHStep1; reflexivity); try (eapply IHHStep2; reflexivity); try (eapply IHHStep3; reflexivity); try assumption]).\n  constructor.\n  * eapply Det_par_trace_from_readonly; try eassumption.\n  * eapply Det_trace_from_theta; try eassumption.\n    + eapply IHHStep3; reflexivity.\n    + eapply IHHStep4; reflexivity.\nQed.\n\nLemma Equal_heap_equal:\n  forall (heap1 heap2 : Heap),\n    heap1 = heap2 -> H.Equal heap1 heap2.\nProof.\n  intros heap1 heap2 H. subst. apply HMapP.Equal_refl.\nQed.\n\nTheorem DynamicDeterminism_ext : \n  forall heap_a heap_b rgns env exp heap1 heap2 val1 val2 acts1 acts2,\n    H.Equal heap_a heap_b ->\n    (heap_a, rgns, env, exp) ⇓ (heap1, val1, acts1) ->\n    (heap_b, rgns, env, exp) ⇓ (heap2, val2, acts2) ->\n    H.Equal heap1 heap2 /\\ val1 = val2 /\\ acts1 = acts2.\nProof.\n  intros heap_a heap_b rgns env exp heap1 heap2 val1 val2 acts1 acts2 Heq Dyn1. \n  generalize dependent acts2; generalize dependent val2; generalize dependent heap2. generalize dependent heap_b;\n  dependent induction Dyn1; intros heap_b Heq heap2 val2 acts2 Dyn2; inversion Dyn2; subst;\n  try (solve [intuition]).\n  - intuition. rewrite H in H1. inversion H1; subst. reflexivity.\n  - assert ( RH1 : H.Equal fheap fheap0 /\\ Cls (env', rho', Mu f x ec' ee') = Cls (env'0, rho'0, Mu f0 x0 ec'0 ee'0) /\\ facts = facts0 )\n      by (eapply IHDyn1_1; eauto).\n    destruct RH1 as [h_eq_1 [v_eq_1 a_eq_1]]. inversion v_eq_1. subst.\n    assert ( RH2 : H.Equal aheap aheap0 /\\ v = v0 /\\ aacts = aacts0) by (eapply IHDyn1_2; eauto).\n    destruct RH2 as [h_eq_2 [v_eq_2 a_eq_2]]; subst. \n    \n    assert ( RH3 : H.Equal heap1 heap2 /\\ val1 = val2 /\\ bacts = bacts0).\n    eapply IHDyn1_3; eauto. \n    destruct RH3 as [h_eq_3 [v_eq_3 a_eq_3]]; subst.\n    auto.\n  - admit.\n  - admit.\n  - assert (HR1 : H.Equal heap_a heap_b /\\ Eff theta1 = Eff theta0 /\\ acts_eff1 = acts_eff0) by (eapply IHDyn1_1; eauto).\n    destruct HR1 as [h_eq_1 [v_eq_1 a_eq_1]]. inversion v_eq_1. subst.\n    assert (HR2 : H.Equal heap_a heap_b /\\ Eff theta2 = Eff theta3 /\\ acts_eff2 = acts_eff3) by (eapply IHDyn1_2; eauto).\n    destruct HR2 as [h_eq_2 [v_eq_2 a_eq_2]]. inversion v_eq_2. subst.\n    assert (HR3 : H.Equal heap_mu1 heap_mu0 /\\ Num v1 = Num v0 /\\ acts_mu1 = acts_mu0)  by (eapply IHDyn1_3; eauto). \n    inversion HR3 as [h_eq_3 [v_eq_3 a_eq_3]]. inversion v_eq_3. \n    assert (HR4 : H.Equal heap_mu2 heap_mu3 /\\ Num v2 = Num v3 /\\ acts_mu2 = acts_mu3)  by (eapply IHDyn1_4; eauto). \n    inversion HR4 as [h_eq_4 [v_eq_4 a_eq_4]]. inversion v_eq_4. subst.\n    intuition. eapply unique_heap_new with (heapa := heap_a) (heapb := heap_b) (theta1:=theta0) (theta2:=theta3); eauto.\n    + assert (Det_Trace (Phi_Par acts_mu0 acts_mu3))\n                  by (eapply Det_trace_from_theta; eauto; [ apply Dynamic_DetTrace in Dyn1_3 | apply Dynamic_DetTrace in Dyn1_4]; assumption);\n      now inversion H11.\n    + assert (Det_Trace (Phi_Par acts_mu0 acts_mu3))\n                  by (eapply Det_trace_from_theta; eauto; [ apply Dynamic_DetTrace in Dyn1_3 | apply Dynamic_DetTrace in Dyn1_4]; assumption);\n      now inversion H11.\n  - \nAdmitted.\n    \nTheorem DynamicDeterminism :\n  forall heap rgns env exp heap1 heap2 val1 val2 acts1 acts2,\n    (heap, rgns, env, exp) ⇓ (heap1, val1, acts1) ->\n    (heap, rgns, env, exp) ⇓ (heap2, val2, acts2) ->\n    (heap1, val1, acts1) = (heap2, val2, acts2).\nProof.\n  intros heap rgns env exp heap1 heap2 val1 val2 acts1 acts2 Dyn1.\n  generalize dependent acts2; generalize dependent val2; generalize dependent heap2.\n  dependent induction Dyn1; intros heap2 val2 acts2 Dyn2; inversion Dyn2; subst;\n  try reflexivity.   \n  - rewrite H in H1. inversion H1. reflexivity.\n  -  assert ( RH1 : (fheap, Cls (env', rho', Mu f x ec' ee'), facts) = (fheap0, Cls (env'0, rho'0, Mu f0 x0 ec'0 ee'0), facts0) )\n      by (eapply IHDyn1_1; [ reflexivity | assumption]). inversion RH1. subst.\n    assert ( RH2 : (aheap, v, aacts) = (aheap0, v0, aacts0) ) by (apply IHDyn1_2; assumption); inversion RH2; subst.\n    assert ( RH3 :  (heap1, val1, bacts) = (heap2, val2, bacts0) ) by (eapply IHDyn1_3; [ reflexivity | reflexivity |  assumption]). \n    now inversion_clear RH3.\n  -  assert ( RH1 : (fheap, Cls (env', rho', Lambda x eb), facts) = (fheap0, Cls (env'0, rho'0, Lambda x0 eb0), facts0) )\n      by (eapply IHDyn1_1; [ reflexivity | assumption]); inversion RH1; subst. \n     rewrite H in H9. inversion H9; subst.\n     assert ( RH2 : (heap1, val1, bacts) = (heap2, val2, bacts0)) by (eapply IHDyn1_2; eauto); inversion RH2; subst; auto.\n  - assert (HR1 : (heap2, Cls (env'0, rho'0, Mu f0 x0 ec'0 ee'0), facts0) = (heap2, Cls (env', rho', Mu f x ec' ee'), facts)) \n      by (eapply IHDyn1_1; eauto); inversion HR1; subst.\n    assert ( HR2 : (heap2, v', aacts) =  (heap2, v'0, aacts0)) by (eapply IHDyn1_2; eauto); inversion HR2; subst.\n    assert ( HR3 : (heap2, val1, bacts) = (heap2, val2, bacts0)) by (eapply IHDyn1_3; eauto); inversion HR3; subst.\n     reflexivity.\n  - assert (HR1 : (heap, Eff theta1, acts_eff1) =  (heap, Eff theta0, acts_eff0)) by (eapply IHDyn1_1; eauto); inversion HR1; subst.\n    assert (HR2 : (heap, Eff theta2, acts_eff2) = (heap, Eff theta3, acts_eff3)) by (eapply IHDyn1_2; eauto); inversion HR2; subst.\n    assert (HR3 : (heap_mu1, Num v1, acts_mu1) = (heap_mu0, Num v0, acts_mu0))  by (eapply IHDyn1_3; eauto); inversion HR3; subst.\n    assert (HR4 :  (heap_mu2, Num v2, acts_mu2) = (heap_mu3, Num v3, acts_mu3)) by (eapply IHDyn1_4; eauto); inversion HR4; subst.\n    \n    do 3 f_equal.\n\n    assert (H.Equal heap1 heap2) by\n    (eapply unique_heap with (theta1:=theta0) (theta2:=theta3); eauto;\n     try (solve [assert (Det_Trace (Phi_Par acts_mu0 acts_mu3))\n                  by (eapply Det_trace_from_theta; eauto; [ apply Dynamic_DetTrace in Dyn1_3 | apply Dynamic_DetTrace in Dyn1_4]; assumption);\n                  now inversion H5\n                ])).\n    \n    admit.\n    \n  - assert ( RH1 : (cheap, Bit true, cacts) = (cheap0, Bit true, cacts0))\n      by (eapply IHDyn1_1; [ reflexivity | assumption] ); inversion RH1; subst.\n    assert ( RH2 : (heap1, val1, tacts) = (heap2, val2, tacts0)) by (apply IHDyn1_2; assumption).\n    now inversion_clear RH2.\n  -  assert ( RH1 : (cheap, Bit true, cacts) = (cheap0, Bit false, cacts0) ). apply IHDyn1_1; auto.\n     discriminate RH1.\n  - assert ( RH1 : (cheap, Bit false, cacts) = (cheap0, Bit true, cacts0) ). apply IHDyn1_1; auto.\n    discriminate RH1.\n  - assert ( RH1 : (cheap, Bit false, cacts) = (cheap0, Bit false, cacts0))\n      by (eapply IHDyn1_1; [ reflexivity | assumption] ); inversion RH1; subst.\n    assert ( RH2 : (heap1, val1, facts) = (heap2, val2, facts0)) by (apply IHDyn1_2; assumption).\n    now inversion_clear RH2.\n  - assert (HR1 : (heap', v, vacts) = (heap'0, v0, vacts0)) by (eapply IHDyn1; eauto); inversion HR1; subst.\n    rewrite H in H10. inversion H10; subst.\n    rewrite <- H11 in H0. unfold find_H in H0. assert (Hl : l = l0) by admit. rewrite Hl.\n    reflexivity.\n  - assert ( RH1 : (heap1, Loc w l, aacts) = (heap2, Loc w l0, aacts0))\n      by (apply IHDyn1; [reflexivity | assumption]); inversion RH1; subst.\n    rewrite H in H10. inversion H10; subst.\n    rewrite H11 in H0. now inversion_clear H0.\n  - assert ( RH1 : (heap', Loc w l, aacts) = (heap'0, Loc w l0, aacts0))\n      by (apply IHDyn1_1 ; [reflexivity | assumption]); inversion RH1; subst.\n    assert ( RH2 : (heap'', v, vacts) = (heap''0, v0, vacts0))\n      by (apply IHDyn1_2; assumption).\n    rewrite H11 in H. inversion H; subst.\n    now inversion_clear RH2.\n  - assert ( RH1 : (lheap, Num va, lacts) = (lheap0, Num va0, lacts0) )\n      by (apply IHDyn1_1 ;  [reflexivity | assumption]); inversion RH1; subst.\n    assert ( RH2 :  (heap1, Num vb, racts) = (heap2, Num vb0, racts0))\n      by (apply IHDyn1_2;  [reflexivity | assumption]); now inversion_clear RH2.\n  - assert ( RH1 : (lheap, Num va, lacts) = (lheap0, Num va0, lacts0) )\n      by (apply IHDyn1_1 ;  [reflexivity | assumption]); inversion RH1; subst.\n    assert ( RH2 :  (heap1, Num vb, racts) = (heap2, Num vb0, racts0))\n      by (apply IHDyn1_2;  [reflexivity | assumption]); now inversion_clear RH2.\n  - assert ( RH1 : (lheap, Num va, lacts) = (lheap0, Num va0, lacts0) )\n      by (apply IHDyn1_1 ;  [reflexivity | assumption]); inversion RH1; subst.\n    assert ( RH2 :  (heap1, Num vb, racts) = (heap2, Num vb0, racts0))\n      by (apply IHDyn1_2;  [reflexivity | assumption]); now inversion_clear RH2.\n  -  assert ( RH1 : (lheap, Num va, lacts) = (lheap0, Num va0, lacts0) )\n      by (apply IHDyn1_1 ;  [reflexivity | assumption]); inversion RH1; subst.\n    assert ( RH2 :  (heap1, Num vb, racts) = (heap2, Num vb0, racts0))\n       by (apply IHDyn1_2;  [reflexivity | assumption]); now inversion_clear RH2.\n  - rewrite H in H1. inversion H1; subst. reflexivity.\n  - rewrite H in H1. inversion H1; subst. reflexivity.\n  - rewrite H in H1. inversion H1; subst. reflexivity.\n  - assert (HR1 : (heap1, Loc (Rgn2_Const true false r) l, Phi_Nil) =  (heap2, Loc (Rgn2_Const true false r0) l0, Phi_Nil)) by\n        (apply IHDyn1; auto); inversion HR1.\n    reflexivity.\n  -  assert (HR1 : (heap1, Loc (Rgn2_Const true false r) l, Phi_Nil) =  (heap2, Loc (Rgn2_Const true false r0) l0, Phi_Nil)) by\n        (apply IHDyn1; auto); inversion HR1.\n     reflexivity.\n  - assert ( HR1 :  (heap2, Eff effa0, phia0) = (heap2, Eff effa, phia) ) by (apply IHDyn1_1; auto).\n    assert ( HR2 :  (heap2, Eff effb0, phib0) = (heap2, Eff effb, phib) ) by (apply IHDyn1_2; auto).\n    inversion HR1; inversion HR2; now subst.\nQed.\n\n\n", "meta": {"author": "esmifro", "repo": "surface-effects", "sha": "ee3a0c769c7d9f5ac17fde22971fe8d39c2e527e", "save_path": "github-repos/coq/esmifro-surface-effects", "path": "github-repos/coq/esmifro-surface-effects/surface-effects-ee3a0c769c7d9f5ac17fde22971fe8d39c2e527e/Determinism.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.25501702946618826}}
{"text": "Require Export DevCoq.Dev.lemmas_automation_g.\n\nLemma harmonic_conjugate : forall P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13 P14,\nrk(P1 :: P2 :: P3 :: nil) = 2 ->\nrk(P1 :: P2 :: nil) = 2 -> rk(P1 :: P3 :: nil) = 2 -> rk(P2 :: P3 :: nil) = 2 ->\nrk(P4 :: P5 :: P6 :: nil) = 3 -> rk(P8 :: P9 :: P10 :: nil) = 3 ->\nrk(P1 :: P2 :: P4 :: P8 :: nil) = 4 ->\nrk(P1 :: P2 :: P4 :: nil) = 3 -> rk(P1 :: P2 :: P5 :: nil) = 3 -> \nrk(P1 :: P4 :: P5 :: nil) = 2 -> rk(P2 :: P4 :: P6 :: nil) = 2 -> rk(P3 :: P5 :: P6 :: nil) = 2 -> \nrk(P1 :: P6 :: P7 :: nil) = 2 -> rk(P2 :: P5 :: P7 :: nil) = 2 -> rk(P4 :: P7 :: P12 :: nil) = 2 ->\nrk(P1 :: P2 :: P8 :: nil) = 3 -> rk(P1 :: P2 :: P9 :: nil) = 3 -> \nrk(P1 :: P8 :: P9 :: nil) = 2 -> rk(P2 :: P8 :: P10 :: nil) = 2 -> rk(P3 :: P9 :: P10 :: nil) = 2 -> \nrk(P1 :: P10 :: P11 :: nil) = 2 -> rk(P2 :: P9 :: P11 :: nil) = 2 -> rk(P8 :: P11 :: P13 :: nil) = 2 ->\nrk(P1 :: P2 :: P3 :: P12 :: P13 :: nil) = 2 ->\nrk(P6 :: P10 :: P14 :: nil) = 2 -> rk(P5 :: P9 :: P14 :: nil) = 2 ->\nrk(P12 :: P13 :: nil) = 1.\nProof.\n\nintros P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13 P14 \nHP1P2P3eq HP1P2eq HP1P3eq HP2P3eq HP4P5P6eq HP8P9P10eq HP1P2P4P8eq HP1P2P4eq \nHP1P2P5eq HP1P4P5eq HP2P4P6eq HP3P5P6eq HP1P6P7eq HP2P5P7eq HP4P7P12eq HP1P2P8eq HP1P2P9eq HP1P8P9eq HP2P8P10eq HP3P9P10eq HP1P10P11eq HP2P9P11eq HP8P11P13eq HP1P2P3P12P13eq HP6P10P14eq HP5P9P14eq.\n\nassert(HP1P2P4P6M3 : rk(P1 :: P2 :: P4 :: P6 :: nil) <= 3).\n{\n\tassert(HP1Mtmp : rk(P1 :: nil) <= 1) by (solve_hyps_max HP1eq HP1M1).\n\tassert(HP2P4P6Mtmp : rk(P2 :: P4 :: P6 :: nil) <= 2) by (solve_hyps_max HP2P4P6eq HP2P4P6M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P1 :: nil) (P2 :: P4 :: P6 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P6 :: nil) (P1 :: P2 :: P4 :: P6 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P4 :: P6 :: nil) ((P1 :: nil) ++ (P2 :: P4 :: P6 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: nil) (P2 :: P4 :: P6 :: nil) (nil) 1 2 0 HP1Mtmp HP2P4P6Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P2P4P6M4. \n\nassert(HP1P2P4P6m2 : rk(P1 :: P2 :: P4 :: P6 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P6 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P6 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P6m1. \n\nassert(HP1P2P4P6m3 : rk(P1 :: P2 :: P4 :: P6 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P6 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P6 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P6m2. \n\nassert(HP4P6m2 : rk(P4 :: P6 :: nil) >= 2).\n{\n\tassert(HP5Mtmp : rk(P5 :: nil) <= 1) by (solve_hyps_max HP5eq HP5M1).\n\tassert(HP4P5P6mtmp : rk(P4 :: P5 :: P6 :: nil) >= 3) by (solve_hyps_min HP4P5P6eq HP4P5P6m3).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P5 :: nil) (P4 :: P6 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P4 :: P5 :: P6 :: nil) (P5 :: P4 :: P6 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P5 :: P4 :: P6 :: nil) ((P5 :: nil) ++ (P4 :: P6 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP4P5P6mtmp;try rewrite HT2 in HP4P5P6mtmp.\n\tassert(HT := rule_4 (P5 :: nil) (P4 :: P6 :: nil) (nil) 3 0 1 HP4P5P6mtmp Hmtmp HP5Mtmp Hincl); apply HT.\n}\ntry clear HP4P6m1. \n\nassert(HP1P4m2 : rk(P1 :: P4 :: nil) >= 2).\n{\n\tassert(HP2Mtmp : rk(P2 :: nil) <= 1) by (solve_hyps_max HP2eq HP2M1).\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P2 :: nil) (P1 :: P4 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: nil) (P2 :: P1 :: P4 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P1 :: P4 :: nil) ((P2 :: nil) ++ (P1 :: P4 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4mtmp;try rewrite HT2 in HP1P2P4mtmp.\n\tassert(HT := rule_4 (P2 :: nil) (P1 :: P4 :: nil) (nil) 3 0 1 HP1P2P4mtmp Hmtmp HP2Mtmp Hincl); apply HT.\n}\ntry clear HP1P4m1. \n\nassert(HP1P4P6m2 : rk(P1 :: P4 :: P6 :: nil) >= 2).\n{\n\tassert(HP1P4mtmp : rk(P1 :: P4 :: nil) >= 2) by (solve_hyps_min HP1P4eq HP1P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: nil) (P1 :: P4 :: P6 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: nil) (P1 :: P4 :: P6 :: nil) 2 2 HP1P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P6m1. \n\nassert(HP1P4P6m3 : rk(P1 :: P4 :: P6 :: nil) >= 3).\n{\n\tassert(HP2P4P6Mtmp : rk(P2 :: P4 :: P6 :: nil) <= 2) by (solve_hyps_max HP2P4P6eq HP2P4P6M2).\n\tassert(HP1P2P4P6mtmp : rk(P1 :: P2 :: P4 :: P6 :: nil) >= 3) by (solve_hyps_min HP1P2P4P6eq HP1P2P4P6m3).\n\tassert(HP4P6mtmp : rk(P4 :: P6 :: nil) >= 2) by (solve_hyps_min HP4P6eq HP4P6m2).\n\tassert(Hincl : incl (P4 :: P6 :: nil) (list_inter (P1 :: P4 :: P6 :: nil) (P2 :: P4 :: P6 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P6 :: nil) (P1 :: P4 :: P6 :: P2 :: P4 :: P6 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P6 :: P2 :: P4 :: P6 :: nil) ((P1 :: P4 :: P6 :: nil) ++ (P2 :: P4 :: P6 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P6mtmp;try rewrite HT2 in HP1P2P4P6mtmp.\n\tassert(HT := rule_2 (P1 :: P4 :: P6 :: nil) (P2 :: P4 :: P6 :: nil) (P4 :: P6 :: nil) 3 2 2 HP1P2P4P6mtmp HP4P6mtmp HP2P4P6Mtmp Hincl);apply HT.\n}\ntry clear HP1P4P6m2. \n\nassert(HP1P4P6P7M3 : rk(P1 :: P4 :: P6 :: P7 :: nil) <= 3).\n{\n\tassert(HP4Mtmp : rk(P4 :: nil) <= 1) by (solve_hyps_max HP4eq HP4M1).\n\tassert(HP1P6P7Mtmp : rk(P1 :: P6 :: P7 :: nil) <= 2) by (solve_hyps_max HP1P6P7eq HP1P6P7M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P4 :: nil) (P1 :: P6 :: P7 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P4 :: P6 :: P7 :: nil) (P4 :: P1 :: P6 :: P7 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P4 :: P1 :: P6 :: P7 :: nil) ((P4 :: nil) ++ (P1 :: P6 :: P7 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P4 :: nil) (P1 :: P6 :: P7 :: nil) (nil) 1 2 0 HP4Mtmp HP1P6P7Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P4P6P7M4. \n\nassert(HP1P4P6P7m2 : rk(P1 :: P4 :: P6 :: P7 :: nil) >= 2).\n{\n\tassert(HP1P4mtmp : rk(P1 :: P4 :: nil) >= 2) by (solve_hyps_min HP1P4eq HP1P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: nil) (P1 :: P4 :: P6 :: P7 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: nil) (P1 :: P4 :: P6 :: P7 :: nil) 2 2 HP1P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P6P7m1. \n\nassert(HP1P4P6P7m3 : rk(P1 :: P4 :: P6 :: P7 :: nil) >= 3).\n{\n\tassert(HP1P4P6mtmp : rk(P1 :: P4 :: P6 :: nil) >= 3) by (solve_hyps_min HP1P4P6eq HP1P4P6m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: P6 :: nil) (P1 :: P4 :: P6 :: P7 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: P6 :: nil) (P1 :: P4 :: P6 :: P7 :: nil) 3 3 HP1P4P6mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P6P7m2. \n\nassert(HP1P2P5P7M3 : rk(P1 :: P2 :: P5 :: P7 :: nil) <= 3).\n{\n\tassert(HP1Mtmp : rk(P1 :: nil) <= 1) by (solve_hyps_max HP1eq HP1M1).\n\tassert(HP2P5P7Mtmp : rk(P2 :: P5 :: P7 :: nil) <= 2) by (solve_hyps_max HP2P5P7eq HP2P5P7M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P1 :: nil) (P2 :: P5 :: P7 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P5 :: P7 :: nil) (P1 :: P2 :: P5 :: P7 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P5 :: P7 :: nil) ((P1 :: nil) ++ (P2 :: P5 :: P7 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: nil) (P2 :: P5 :: P7 :: nil) (nil) 1 2 0 HP1Mtmp HP2P5P7Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P2P5P7M4. \n\nassert(HP1P2P5P7m2 : rk(P1 :: P2 :: P5 :: P7 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P5 :: P7 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P5 :: P7 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P5P7m1. \n\nassert(HP1P2P5P7m3 : rk(P1 :: P2 :: P5 :: P7 :: nil) >= 3).\n{\n\tassert(HP1P2P5mtmp : rk(P1 :: P2 :: P5 :: nil) >= 3) by (solve_hyps_min HP1P2P5eq HP1P2P5m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P5 :: nil) (P1 :: P2 :: P5 :: P7 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P5 :: nil) (P1 :: P2 :: P5 :: P7 :: nil) 3 3 HP1P2P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P5P7m2. \n\nassert(HP1P7m2 : rk(P1 :: P7 :: nil) >= 2).\n{\n\tassert(HP2P5P7Mtmp : rk(P2 :: P5 :: P7 :: nil) <= 2) by (solve_hyps_max HP2P5P7eq HP2P5P7M2).\n\tassert(HP1P2P5P7mtmp : rk(P1 :: P2 :: P5 :: P7 :: nil) >= 3) by (solve_hyps_min HP1P2P5P7eq HP1P2P5P7m3).\n\tassert(HP7mtmp : rk(P7 :: nil) >= 1) by (solve_hyps_min HP7eq HP7m1).\n\tassert(Hincl : incl (P7 :: nil) (list_inter (P1 :: P7 :: nil) (P2 :: P5 :: P7 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P5 :: P7 :: nil) (P1 :: P7 :: P2 :: P5 :: P7 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P7 :: P2 :: P5 :: P7 :: nil) ((P1 :: P7 :: nil) ++ (P2 :: P5 :: P7 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P5P7mtmp;try rewrite HT2 in HP1P2P5P7mtmp.\n\tassert(HT := rule_2 (P1 :: P7 :: nil) (P2 :: P5 :: P7 :: nil) (P7 :: nil) 3 1 2 HP1P2P5P7mtmp HP7mtmp HP2P5P7Mtmp Hincl);apply HT.\n}\ntry clear HP1P7m1. \n\nassert(HP1P4P7m2 : rk(P1 :: P4 :: P7 :: nil) >= 2).\n{\n\tassert(HP1P4mtmp : rk(P1 :: P4 :: nil) >= 2) by (solve_hyps_min HP1P4eq HP1P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: nil) (P1 :: P4 :: P7 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: nil) (P1 :: P4 :: P7 :: nil) 2 2 HP1P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P7m1. \n\nassert(HP1P4P7m3 : rk(P1 :: P4 :: P7 :: nil) >= 3).\n{\n\tassert(HP1P6P7Mtmp : rk(P1 :: P6 :: P7 :: nil) <= 2) by (solve_hyps_max HP1P6P7eq HP1P6P7M2).\n\tassert(HP1P4P6P7mtmp : rk(P1 :: P4 :: P6 :: P7 :: nil) >= 3) by (solve_hyps_min HP1P4P6P7eq HP1P4P6P7m3).\n\tassert(HP1P7mtmp : rk(P1 :: P7 :: nil) >= 2) by (solve_hyps_min HP1P7eq HP1P7m2).\n\tassert(Hincl : incl (P1 :: P7 :: nil) (list_inter (P1 :: P4 :: P7 :: nil) (P1 :: P6 :: P7 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P4 :: P6 :: P7 :: nil) (P1 :: P4 :: P7 :: P1 :: P6 :: P7 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P7 :: P1 :: P6 :: P7 :: nil) ((P1 :: P4 :: P7 :: nil) ++ (P1 :: P6 :: P7 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P4P6P7mtmp;try rewrite HT2 in HP1P4P6P7mtmp.\n\tassert(HT := rule_2 (P1 :: P4 :: P7 :: nil) (P1 :: P6 :: P7 :: nil) (P1 :: P7 :: nil) 3 2 2 HP1P4P6P7mtmp HP1P7mtmp HP1P6P7Mtmp Hincl);apply HT.\n}\ntry clear HP1P4P7m2. try clear HP1P4P6P7M3. try clear HP1P4P6P7m3. \n\nassert(HP1P4P7P12M3 : rk(P1 :: P4 :: P7 :: P12 :: nil) <= 3).\n{\n\tassert(HP1Mtmp : rk(P1 :: nil) <= 1) by (solve_hyps_max HP1eq HP1M1).\n\tassert(HP4P7P12Mtmp : rk(P4 :: P7 :: P12 :: nil) <= 2) by (solve_hyps_max HP4P7P12eq HP4P7P12M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P1 :: nil) (P4 :: P7 :: P12 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P4 :: P7 :: P12 :: nil) (P1 :: P4 :: P7 :: P12 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P7 :: P12 :: nil) ((P1 :: nil) ++ (P4 :: P7 :: P12 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: nil) (P4 :: P7 :: P12 :: nil) (nil) 1 2 0 HP1Mtmp HP4P7P12Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P4P7P12M4. \n\nassert(HP1P4P7P12m2 : rk(P1 :: P4 :: P7 :: P12 :: nil) >= 2).\n{\n\tassert(HP1P4mtmp : rk(P1 :: P4 :: nil) >= 2) by (solve_hyps_min HP1P4eq HP1P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: nil) (P1 :: P4 :: P7 :: P12 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: nil) (P1 :: P4 :: P7 :: P12 :: nil) 2 2 HP1P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P7P12m1. \n\nassert(HP1P4P7P12m3 : rk(P1 :: P4 :: P7 :: P12 :: nil) >= 3).\n{\n\tassert(HP1P4P7mtmp : rk(P1 :: P4 :: P7 :: nil) >= 3) by (solve_hyps_min HP1P4P7eq HP1P4P7m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: P7 :: nil) (P1 :: P4 :: P7 :: P12 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: P7 :: nil) (P1 :: P4 :: P7 :: P12 :: nil) 3 3 HP1P4P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P7P12m2. \n\nassert(HP1P12m2 : rk(P1 :: P12 :: nil) >= 2).\n{\n\tassert(HP4P7P12Mtmp : rk(P4 :: P7 :: P12 :: nil) <= 2) by (solve_hyps_max HP4P7P12eq HP4P7P12M2).\n\tassert(HP1P4P7P12mtmp : rk(P1 :: P4 :: P7 :: P12 :: nil) >= 3) by (solve_hyps_min HP1P4P7P12eq HP1P4P7P12m3).\n\tassert(HP12mtmp : rk(P12 :: nil) >= 1) by (solve_hyps_min HP12eq HP12m1).\n\tassert(Hincl : incl (P12 :: nil) (list_inter (P1 :: P12 :: nil) (P4 :: P7 :: P12 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P4 :: P7 :: P12 :: nil) (P1 :: P12 :: P4 :: P7 :: P12 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P12 :: P4 :: P7 :: P12 :: nil) ((P1 :: P12 :: nil) ++ (P4 :: P7 :: P12 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P4P7P12mtmp;try rewrite HT2 in HP1P4P7P12mtmp.\n\tassert(HT := rule_2 (P1 :: P12 :: nil) (P4 :: P7 :: P12 :: nil) (P12 :: nil) 3 1 2 HP1P4P7P12mtmp HP12mtmp HP4P7P12Mtmp Hincl);apply HT.\n}\ntry clear HP1P12m1. try clear HP1P4P7P12M3. try clear HP1P4P7P12m3. \n\nassert(HP1P12P13m2 : rk(P1 :: P12 :: P13 :: nil) >= 2).\n{\n\tassert(HP1P12mtmp : rk(P1 :: P12 :: nil) >= 2) by (solve_hyps_min HP1P12eq HP1P12m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P12 :: nil) (P1 :: P12 :: P13 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P12 :: nil) (P1 :: P12 :: P13 :: nil) 2 2 HP1P12mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P12P13m1. \n\nassert(HP1P12P13M2 : rk(P1 :: P12 :: P13 :: nil) <= 2).\n{\n\tassert(HP1P2P3P12P13Mtmp : rk(P1 :: P2 :: P3 :: P12 :: P13 :: nil) <= 2) by (solve_hyps_max HP1P2P3P12P13eq HP1P2P3P12P13M2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P12 :: P13 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (P1 :: P12 :: P13 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil) 2 2 HP1P2P3P12P13Mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P12P13M3. \n\nassert(HP1P2P4P8P12P13P14m2 : rk(P1 :: P2 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P8P12P13P14m1. \n\nassert(HP1P2P4P8P12P13P14m3 : rk(P1 :: P2 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P8P12P13P14m2. \n\nassert(HP1P2P4P8P12P13P14m4 : rk(P1 :: P2 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil) >= 4).\n{\n\tassert(HP1P2P4P8mtmp : rk(P1 :: P2 :: P4 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8eq HP1P2P4P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil) 4 4 HP1P2P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P8P12P13P14m3. \n\nassert(HP1P2P12m2 : rk(P1 :: P2 :: P12 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P12 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P12 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P12m1. \n\nassert(HP1P2P12M2 : rk(P1 :: P2 :: P12 :: nil) <= 2).\n{\n\tassert(HP1P2P3P12P13Mtmp : rk(P1 :: P2 :: P3 :: P12 :: P13 :: nil) <= 2) by (solve_hyps_max HP1P2P3P12P13eq HP1P2P3P12P13M2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P12 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (P1 :: P2 :: P12 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil) 2 2 HP1P2P3P12P13Mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P12M3. \n\nassert(HP1P4P8m3 : rk(P1 :: P4 :: P8 :: nil) >= 3).\n{\n\tassert(HP2Mtmp : rk(P2 :: nil) <= 1) by (solve_hyps_max HP2eq HP2M1).\n\tassert(HP1P2P4P8mtmp : rk(P1 :: P2 :: P4 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8eq HP1P2P4P8m4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P2 :: nil) (P1 :: P4 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P8 :: nil) (P2 :: P1 :: P4 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P1 :: P4 :: P8 :: nil) ((P2 :: nil) ++ (P1 :: P4 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P8mtmp;try rewrite HT2 in HP1P2P4P8mtmp.\n\tassert(HT := rule_4 (P2 :: nil) (P1 :: P4 :: P8 :: nil) (nil) 4 0 1 HP1P2P4P8mtmp Hmtmp HP2Mtmp Hincl); apply HT.\n}\ntry clear HP1P4P8m1. \n\nassert(HP1P4P8P12P13P14m2 : rk(P1 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P4mtmp : rk(P1 :: P4 :: nil) >= 2) by (solve_hyps_min HP1P4eq HP1P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: nil) (P1 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: nil) (P1 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil) 2 2 HP1P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P8P12P13P14m1. \n\nassert(HP1P4P8P12P13P14m3 : rk(P1 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P4P8mtmp : rk(P1 :: P4 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P4P8eq HP1P4P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: P8 :: nil) (P1 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: P8 :: nil) (P1 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil) 3 3 HP1P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P8P12P13P14m2. \n\nassert(HP1P4P8P12P13P14m4 : rk(P1 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil) >= 4).\n{\n\tassert(HP1P2P12Mtmp : rk(P1 :: P2 :: P12 :: nil) <= 2) by (solve_hyps_max HP1P2P12eq HP1P2P12M2).\n\tassert(HP1P2P4P8P12P13P14mtmp : rk(P1 :: P2 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8P12P13P14eq HP1P2P4P8P12P13P14m4).\n\tassert(HP1P12mtmp : rk(P1 :: P12 :: nil) >= 2) by (solve_hyps_min HP1P12eq HP1P12m2).\n\tassert(Hincl : incl (P1 :: P12 :: nil) (list_inter (P1 :: P2 :: P12 :: nil) (P1 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil) (P1 :: P2 :: P12 :: P1 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P12 :: P1 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil) ((P1 :: P2 :: P12 :: nil) ++ (P1 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P8P12P13P14mtmp;try rewrite HT2 in HP1P2P4P8P12P13P14mtmp.\n\tassert(HT := rule_4 (P1 :: P2 :: P12 :: nil) (P1 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil) (P1 :: P12 :: nil) 4 2 2 HP1P2P4P8P12P13P14mtmp HP1P12mtmp HP1P2P12Mtmp Hincl); apply HT.\n}\ntry clear HP1P4P8P12P13P14m3. try clear HP1P2P4P8P12P13P14M4. try clear HP1P2P4P8P12P13P14m4. \n\nassert(HP1P2P4P5P8m2 : rk(P1 :: P2 :: P4 :: P5 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P5 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P5 :: P8 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P5P8m1. \n\nassert(HP1P2P4P5P8m3 : rk(P1 :: P2 :: P4 :: P5 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P5 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P5 :: P8 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P5P8m2. \n\nassert(HP1P2P4P5P8m4 : rk(P1 :: P2 :: P4 :: P5 :: P8 :: nil) >= 4).\n{\n\tassert(HP1P2P4P8mtmp : rk(P1 :: P2 :: P4 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8eq HP1P2P4P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P5 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P5 :: P8 :: nil) 4 4 HP1P2P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P5P8m3. \n\nassert(HP1P2P4P5P7P8P12m2 : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: P12 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: P12 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: P12 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P5P7P8P12m1. \n\nassert(HP1P2P4P5P7P8P12m3 : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: P12 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: P12 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: P12 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P5P7P8P12m2. \n\nassert(HP1P2P4P5P7P8P12m4 : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: P12 :: nil) >= 4).\n{\n\tassert(HP1P2P4P8mtmp : rk(P1 :: P2 :: P4 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8eq HP1P2P4P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: P12 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: P12 :: nil) 4 4 HP1P2P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P5P7P8P12m3. \n\nassert(HP1P5m2 : rk(P1 :: P5 :: nil) >= 2).\n{\n\tassert(HP2Mtmp : rk(P2 :: nil) <= 1) by (solve_hyps_max HP2eq HP2M1).\n\tassert(HP1P2P5mtmp : rk(P1 :: P2 :: P5 :: nil) >= 3) by (solve_hyps_min HP1P2P5eq HP1P2P5m3).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P2 :: nil) (P1 :: P5 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P5 :: nil) (P2 :: P1 :: P5 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P1 :: P5 :: nil) ((P2 :: nil) ++ (P1 :: P5 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P5mtmp;try rewrite HT2 in HP1P2P5mtmp.\n\tassert(HT := rule_4 (P2 :: nil) (P1 :: P5 :: nil) (nil) 3 0 1 HP1P2P5mtmp Hmtmp HP2Mtmp Hincl); apply HT.\n}\ntry clear HP1P5m1. \n\nassert(HP1P2P4P5P7m2 : rk(P1 :: P2 :: P4 :: P5 :: P7 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P5P7m1. \n\nassert(HP1P2P4P5P7m3 : rk(P1 :: P2 :: P4 :: P5 :: P7 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P5P7m2. \n\nassert(HP1P2P4P5P7M3 : rk(P1 :: P2 :: P4 :: P5 :: P7 :: nil) <= 3).\n{\n\tassert(HP1P4P5Mtmp : rk(P1 :: P4 :: P5 :: nil) <= 2) by (solve_hyps_max HP1P4P5eq HP1P4P5M2).\n\tassert(HP2P5P7Mtmp : rk(P2 :: P5 :: P7 :: nil) <= 2) by (solve_hyps_max HP2P5P7eq HP2P5P7M2).\n\tassert(HP5mtmp : rk(P5 :: nil) >= 1) by (solve_hyps_min HP5eq HP5m1).\n\tassert(Hincl : incl (P5 :: nil) (list_inter (P1 :: P4 :: P5 :: nil) (P2 :: P5 :: P7 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P5 :: P7 :: nil) (P1 :: P4 :: P5 :: P2 :: P5 :: P7 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P5 :: P2 :: P5 :: P7 :: nil) ((P1 :: P4 :: P5 :: nil) ++ (P2 :: P5 :: P7 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: P4 :: P5 :: nil) (P2 :: P5 :: P7 :: nil) (P5 :: nil) 2 2 1 HP1P4P5Mtmp HP2P5P7Mtmp HP5mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P2P4P5P7M4. \n\nassert(HP1P2P4P7m2 : rk(P1 :: P2 :: P4 :: P7 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P7 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P7 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P7m1. \n\nassert(HP1P2P4P7m3 : rk(P1 :: P2 :: P4 :: P7 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P7 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P7 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P7m2. \n\nassert(HP1P2P4P7M3 : rk(P1 :: P2 :: P4 :: P7 :: nil) <= 3).\n{\n\tassert(HP1P2P4P5P7Mtmp : rk(P1 :: P2 :: P4 :: P5 :: P7 :: nil) <= 3) by (solve_hyps_max HP1P2P4P5P7eq HP1P2P4P5P7M3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: P7 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (P1 :: P2 :: P4 :: P7 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: nil) 3 3 HP1P2P4P5P7Mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P7M4. \n\nassert(HP1P4P5P7P12m2 : rk(P1 :: P4 :: P5 :: P7 :: P12 :: nil) >= 2).\n{\n\tassert(HP1P4mtmp : rk(P1 :: P4 :: nil) >= 2) by (solve_hyps_min HP1P4eq HP1P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: nil) (P1 :: P4 :: P5 :: P7 :: P12 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: nil) (P1 :: P4 :: P5 :: P7 :: P12 :: nil) 2 2 HP1P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P5P7P12m1. \n\nassert(HP1P4P5P7P12M3 : rk(P1 :: P4 :: P5 :: P7 :: P12 :: nil) <= 3).\n{\n\tassert(HP1P4P5Mtmp : rk(P1 :: P4 :: P5 :: nil) <= 2) by (solve_hyps_max HP1P4P5eq HP1P4P5M2).\n\tassert(HP4P7P12Mtmp : rk(P4 :: P7 :: P12 :: nil) <= 2) by (solve_hyps_max HP4P7P12eq HP4P7P12M2).\n\tassert(HP4mtmp : rk(P4 :: nil) >= 1) by (solve_hyps_min HP4eq HP4m1).\n\tassert(Hincl : incl (P4 :: nil) (list_inter (P1 :: P4 :: P5 :: nil) (P4 :: P7 :: P12 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P4 :: P5 :: P7 :: P12 :: nil) (P1 :: P4 :: P5 :: P4 :: P7 :: P12 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P5 :: P4 :: P7 :: P12 :: nil) ((P1 :: P4 :: P5 :: nil) ++ (P4 :: P7 :: P12 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: P4 :: P5 :: nil) (P4 :: P7 :: P12 :: nil) (P4 :: nil) 2 2 1 HP1P4P5Mtmp HP4P7P12Mtmp HP4mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P4P5P7P12M4. \n\nassert(HP1P4P5P7P12m3 : rk(P1 :: P4 :: P5 :: P7 :: P12 :: nil) >= 3).\n{\n\tassert(HP1P4P7mtmp : rk(P1 :: P4 :: P7 :: nil) >= 3) by (solve_hyps_min HP1P4P7eq HP1P4P7m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: P7 :: nil) (P1 :: P4 :: P5 :: P7 :: P12 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: P7 :: nil) (P1 :: P4 :: P5 :: P7 :: P12 :: nil) 3 3 HP1P4P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P5P7P12m2. \n\nassert(HP1P2P4P5P7P12m2 : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P5P7P12m1. \n\nassert(HP1P2P4P5P7P12m3 : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P5P7P12m2. \n\nassert(HP1P2P4P5P7P12M3 : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil) <= 3).\n{\n\tassert(HP1P2P4P7Mtmp : rk(P1 :: P2 :: P4 :: P7 :: nil) <= 3) by (solve_hyps_max HP1P2P4P7eq HP1P2P4P7M3).\n\tassert(HP1P4P5P7P12Mtmp : rk(P1 :: P4 :: P5 :: P7 :: P12 :: nil) <= 3) by (solve_hyps_max HP1P4P5P7P12eq HP1P4P5P7P12M3).\n\tassert(HP1P4P7mtmp : rk(P1 :: P4 :: P7 :: nil) >= 3) by (solve_hyps_min HP1P4P7eq HP1P4P7m3).\n\tassert(Hincl : incl (P1 :: P4 :: P7 :: nil) (list_inter (P1 :: P2 :: P4 :: P7 :: nil) (P1 :: P4 :: P5 :: P7 :: P12 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil) (P1 :: P2 :: P4 :: P7 :: P1 :: P4 :: P5 :: P7 :: P12 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P4 :: P7 :: P1 :: P4 :: P5 :: P7 :: P12 :: nil) ((P1 :: P2 :: P4 :: P7 :: nil) ++ (P1 :: P4 :: P5 :: P7 :: P12 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: P2 :: P4 :: P7 :: nil) (P1 :: P4 :: P5 :: P7 :: P12 :: nil) (P1 :: P4 :: P7 :: nil) 3 3 3 HP1P2P4P7Mtmp HP1P4P5P7P12Mtmp HP1P4P7mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P4P5P7P12M3. try clear HP1P4P5P7P12m3. try clear HP1P4P7M3. try clear HP1P4P7m3. try clear HP1P2P4P5P7P12M4. \n\nassert(HP1P5P8m2 : rk(P1 :: P5 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P5mtmp : rk(P1 :: P5 :: nil) >= 2) by (solve_hyps_min HP1P5eq HP1P5m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P5 :: nil) (P1 :: P5 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P5 :: nil) (P1 :: P5 :: P8 :: nil) 2 2 HP1P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P5P8m1. \n\nassert(HP1P5P8m3 : rk(P1 :: P5 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P2P4P5P7P12Mtmp : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil) <= 3) by (solve_hyps_max HP1P2P4P5P7P12eq HP1P2P4P5P7P12M3).\n\tassert(HP1P2P4P5P7P8P12mtmp : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: P12 :: nil) >= 4) by (solve_hyps_min HP1P2P4P5P7P8P12eq HP1P2P4P5P7P8P12m4).\n\tassert(HP1P5mtmp : rk(P1 :: P5 :: nil) >= 2) by (solve_hyps_min HP1P5eq HP1P5m2).\n\tassert(Hincl : incl (P1 :: P5 :: nil) (list_inter (P1 :: P5 :: P8 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: P12 :: nil) (P1 :: P5 :: P8 :: P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P5 :: P8 :: P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil) ((P1 :: P5 :: P8 :: nil) ++ (P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P5P7P8P12mtmp;try rewrite HT2 in HP1P2P4P5P7P8P12mtmp.\n\tassert(HT := rule_2 (P1 :: P5 :: P8 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil) (P1 :: P5 :: nil) 4 2 3 HP1P2P4P5P7P8P12mtmp HP1P5mtmp HP1P2P4P5P7P12Mtmp Hincl);apply HT.\n}\ntry clear HP1P5P8m2. \n\nassert(HP1P4P5P8m2 : rk(P1 :: P4 :: P5 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P4mtmp : rk(P1 :: P4 :: nil) >= 2) by (solve_hyps_min HP1P4eq HP1P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: nil) (P1 :: P4 :: P5 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: nil) (P1 :: P4 :: P5 :: P8 :: nil) 2 2 HP1P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P5P8m1. \n\nassert(HP1P4P5P8M3 : rk(P1 :: P4 :: P5 :: P8 :: nil) <= 3).\n{\n\tassert(HP1P4P5Mtmp : rk(P1 :: P4 :: P5 :: nil) <= 2) by (solve_hyps_max HP1P4P5eq HP1P4P5M2).\n\tassert(HP8Mtmp : rk(P8 :: nil) <= 1) by (solve_hyps_max HP8eq HP8M1).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P1 :: P4 :: P5 :: nil) (P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P4 :: P5 :: P8 :: nil) (P1 :: P4 :: P5 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P5 :: P8 :: nil) ((P1 :: P4 :: P5 :: nil) ++ (P8 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: P4 :: P5 :: nil) (P8 :: nil) (nil) 2 1 0 HP1P4P5Mtmp HP8Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P4P5P8M4. \n\nassert(HP1P4P5P8m3 : rk(P1 :: P4 :: P5 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P4P8mtmp : rk(P1 :: P4 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P4P8eq HP1P4P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: P8 :: nil) (P1 :: P4 :: P5 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: P8 :: nil) (P1 :: P4 :: P5 :: P8 :: nil) 3 3 HP1P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P5P8m2. \n\nassert(HP1P2P5P8m2 : rk(P1 :: P2 :: P5 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P5 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P5 :: P8 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P5P8m1. \n\nassert(HP1P2P5P8m3 : rk(P1 :: P2 :: P5 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P2P5mtmp : rk(P1 :: P2 :: P5 :: nil) >= 3) by (solve_hyps_min HP1P2P5eq HP1P2P5m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P5 :: nil) (P1 :: P2 :: P5 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P5 :: nil) (P1 :: P2 :: P5 :: P8 :: nil) 3 3 HP1P2P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P5P8m2. \n\nassert(HP1P2P5P8m4 : rk(P1 :: P2 :: P5 :: P8 :: nil) >= 4).\n{\n\tassert(HP1P4P5P8Mtmp : rk(P1 :: P4 :: P5 :: P8 :: nil) <= 3) by (solve_hyps_max HP1P4P5P8eq HP1P4P5P8M3).\n\tassert(HP1P2P4P5P8mtmp : rk(P1 :: P2 :: P4 :: P5 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P5P8eq HP1P2P4P5P8m4).\n\tassert(HP1P5P8mtmp : rk(P1 :: P5 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P5P8eq HP1P5P8m3).\n\tassert(Hincl : incl (P1 :: P5 :: P8 :: nil) (list_inter (P1 :: P2 :: P5 :: P8 :: nil) (P1 :: P4 :: P5 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P5 :: P8 :: nil) (P1 :: P2 :: P5 :: P8 :: P1 :: P4 :: P5 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P5 :: P8 :: P1 :: P4 :: P5 :: P8 :: nil) ((P1 :: P2 :: P5 :: P8 :: nil) ++ (P1 :: P4 :: P5 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P5P8mtmp;try rewrite HT2 in HP1P2P4P5P8mtmp.\n\tassert(HT := rule_2 (P1 :: P2 :: P5 :: P8 :: nil) (P1 :: P4 :: P5 :: P8 :: nil) (P1 :: P5 :: P8 :: nil) 4 3 3 HP1P2P4P5P8mtmp HP1P5P8mtmp HP1P4P5P8Mtmp Hincl);apply HT.\n}\ntry clear HP1P2P5P8m3. \n\nassert(HP1P2P3P5P8P9m2 : rk(P1 :: P2 :: P3 :: P5 :: P8 :: P9 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P5 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P5 :: P8 :: P9 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P5P8P9m1. \n\nassert(HP1P2P3P5P8P9m3 : rk(P1 :: P2 :: P3 :: P5 :: P8 :: P9 :: nil) >= 3).\n{\n\tassert(HP1P2P5mtmp : rk(P1 :: P2 :: P5 :: nil) >= 3) by (solve_hyps_min HP1P2P5eq HP1P2P5m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P5 :: nil) (P1 :: P2 :: P3 :: P5 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P5 :: nil) (P1 :: P2 :: P3 :: P5 :: P8 :: P9 :: nil) 3 3 HP1P2P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P5P8P9m2. \n\nassert(HP1P2P3P5P8P9m4 : rk(P1 :: P2 :: P3 :: P5 :: P8 :: P9 :: nil) >= 4).\n{\n\tassert(HP1P2P5P8mtmp : rk(P1 :: P2 :: P5 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P5P8eq HP1P2P5P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P5 :: P8 :: nil) (P1 :: P2 :: P3 :: P5 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P5 :: P8 :: nil) (P1 :: P2 :: P3 :: P5 :: P8 :: P9 :: nil) 4 4 HP1P2P5P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P5P8P9m3. \n\nassert(HP1P2P3P4P5P8m2 : rk(P1 :: P2 :: P3 :: P4 :: P5 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P4 :: P5 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P4 :: P5 :: P8 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P4P5P8m1. \n\nassert(HP1P2P3P4P5P8m3 : rk(P1 :: P2 :: P3 :: P4 :: P5 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P3 :: P4 :: P5 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P3 :: P4 :: P5 :: P8 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P4P5P8m2. \n\nassert(HP1P2P3P4P5P8m4 : rk(P1 :: P2 :: P3 :: P4 :: P5 :: P8 :: nil) >= 4).\n{\n\tassert(HP1P2P4P8mtmp : rk(P1 :: P2 :: P4 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8eq HP1P2P4P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P3 :: P4 :: P5 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P3 :: P4 :: P5 :: P8 :: nil) 4 4 HP1P2P4P8mtmp Hcomp Hincl);apply HT.\n}\n\n\nassert(HP1P2P3P5P8m2 : rk(P1 :: P2 :: P3 :: P5 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P5 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P5 :: P8 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P5P8m1. \n\nassert(HP1P2P3P5P8m3 : rk(P1 :: P2 :: P3 :: P5 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P2P5mtmp : rk(P1 :: P2 :: P5 :: nil) >= 3) by (solve_hyps_min HP1P2P5eq HP1P2P5m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P5 :: nil) (P1 :: P2 :: P3 :: P5 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P5 :: nil) (P1 :: P2 :: P3 :: P5 :: P8 :: nil) 3 3 HP1P2P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P5P8m2. \n\nassert(HP1P2P3P5P8m4 : rk(P1 :: P2 :: P3 :: P5 :: P8 :: nil) >= 4).\n{\n\tassert(HP1P4P5P8Mtmp : rk(P1 :: P4 :: P5 :: P8 :: nil) <= 3) by (solve_hyps_max HP1P4P5P8eq HP1P4P5P8M3).\n\tassert(HP1P2P3P4P5P8mtmp : rk(P1 :: P2 :: P3 :: P4 :: P5 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P3P4P5P8eq HP1P2P3P4P5P8m4).\n\tassert(HP1P5P8mtmp : rk(P1 :: P5 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P5P8eq HP1P5P8m3).\n\tassert(Hincl : incl (P1 :: P5 :: P8 :: nil) (list_inter (P1 :: P2 :: P3 :: P5 :: P8 :: nil) (P1 :: P4 :: P5 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P4 :: P5 :: P8 :: nil) (P1 :: P2 :: P3 :: P5 :: P8 :: P1 :: P4 :: P5 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P3 :: P5 :: P8 :: P1 :: P4 :: P5 :: P8 :: nil) ((P1 :: P2 :: P3 :: P5 :: P8 :: nil) ++ (P1 :: P4 :: P5 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P3P4P5P8mtmp;try rewrite HT2 in HP1P2P3P4P5P8mtmp.\n\tassert(HT := rule_2 (P1 :: P2 :: P3 :: P5 :: P8 :: nil) (P1 :: P4 :: P5 :: P8 :: nil) (P1 :: P5 :: P8 :: nil) 4 3 3 HP1P2P3P4P5P8mtmp HP1P5P8mtmp HP1P4P5P8Mtmp Hincl);apply HT.\n}\n\n\nassert(HP1P5P8P9M3 : rk(P1 :: P5 :: P8 :: P9 :: nil) <= 3).\n{\n\tassert(HP5Mtmp : rk(P5 :: nil) <= 1) by (solve_hyps_max HP5eq HP5M1).\n\tassert(HP1P8P9Mtmp : rk(P1 :: P8 :: P9 :: nil) <= 2) by (solve_hyps_max HP1P8P9eq HP1P8P9M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P5 :: nil) (P1 :: P8 :: P9 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P5 :: P8 :: P9 :: nil) (P5 :: P1 :: P8 :: P9 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P5 :: P1 :: P8 :: P9 :: nil) ((P5 :: nil) ++ (P1 :: P8 :: P9 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P5 :: nil) (P1 :: P8 :: P9 :: nil) (nil) 1 2 0 HP5Mtmp HP1P8P9Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P5P8P9M4. \n\nassert(HP1P5P8P9m2 : rk(P1 :: P5 :: P8 :: P9 :: nil) >= 2).\n{\n\tassert(HP1P5mtmp : rk(P1 :: P5 :: nil) >= 2) by (solve_hyps_min HP1P5eq HP1P5m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P5 :: nil) (P1 :: P5 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P5 :: nil) (P1 :: P5 :: P8 :: P9 :: nil) 2 2 HP1P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P5P8P9m1. \n\nassert(HP1P5P8P9m3 : rk(P1 :: P5 :: P8 :: P9 :: nil) >= 3).\n{\n\tassert(HP1P2P3P5P8Mtmp : rk(P1 :: P2 :: P3 :: P5 :: P8 :: nil) <= 4) by (solve_hyps_max HP1P2P3P5P8eq HP1P2P3P5P8M4).\n\tassert(HP1P2P3P5P8P9mtmp : rk(P1 :: P2 :: P3 :: P5 :: P8 :: P9 :: nil) >= 4) by (solve_hyps_min HP1P2P3P5P8P9eq HP1P2P3P5P8P9m4).\n\tassert(HP1P5P8mtmp : rk(P1 :: P5 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P5P8eq HP1P5P8m3).\n\tassert(Hincl : incl (P1 :: P5 :: P8 :: nil) (list_inter (P1 :: P2 :: P3 :: P5 :: P8 :: nil) (P1 :: P5 :: P8 :: P9 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P5 :: P8 :: P9 :: nil) (P1 :: P2 :: P3 :: P5 :: P8 :: P1 :: P5 :: P8 :: P9 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P3 :: P5 :: P8 :: P1 :: P5 :: P8 :: P9 :: nil) ((P1 :: P2 :: P3 :: P5 :: P8 :: nil) ++ (P1 :: P5 :: P8 :: P9 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P3P5P8P9mtmp;try rewrite HT2 in HP1P2P3P5P8P9mtmp.\n\tassert(HT := rule_4 (P1 :: P2 :: P3 :: P5 :: P8 :: nil) (P1 :: P5 :: P8 :: P9 :: nil) (P1 :: P5 :: P8 :: nil) 4 3 4 HP1P2P3P5P8P9mtmp HP1P5P8mtmp HP1P2P3P5P8Mtmp Hincl); apply HT.\n}\ntry clear HP1P5P8P9m2. \n\nassert(HP1P9m2 : rk(P1 :: P9 :: nil) >= 2).\n{\n\tassert(HP2Mtmp : rk(P2 :: nil) <= 1) by (solve_hyps_max HP2eq HP2M1).\n\tassert(HP1P2P9mtmp : rk(P1 :: P2 :: P9 :: nil) >= 3) by (solve_hyps_min HP1P2P9eq HP1P2P9m3).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P2 :: nil) (P1 :: P9 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P9 :: nil) (P2 :: P1 :: P9 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P1 :: P9 :: nil) ((P2 :: nil) ++ (P1 :: P9 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P9mtmp;try rewrite HT2 in HP1P2P9mtmp.\n\tassert(HT := rule_4 (P2 :: nil) (P1 :: P9 :: nil) (nil) 3 0 1 HP1P2P9mtmp Hmtmp HP2Mtmp Hincl); apply HT.\n}\ntry clear HP1P9m1. \n\nassert(HP1P5P9m2 : rk(P1 :: P5 :: P9 :: nil) >= 2).\n{\n\tassert(HP1P5mtmp : rk(P1 :: P5 :: nil) >= 2) by (solve_hyps_min HP1P5eq HP1P5m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P5 :: nil) (P1 :: P5 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P5 :: nil) (P1 :: P5 :: P9 :: nil) 2 2 HP1P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P5P9m1. \n\nassert(HP1P5P9m3 : rk(P1 :: P5 :: P9 :: nil) >= 3).\n{\n\tassert(HP1P8P9Mtmp : rk(P1 :: P8 :: P9 :: nil) <= 2) by (solve_hyps_max HP1P8P9eq HP1P8P9M2).\n\tassert(HP1P5P8P9mtmp : rk(P1 :: P5 :: P8 :: P9 :: nil) >= 3) by (solve_hyps_min HP1P5P8P9eq HP1P5P8P9m3).\n\tassert(HP1P9mtmp : rk(P1 :: P9 :: nil) >= 2) by (solve_hyps_min HP1P9eq HP1P9m2).\n\tassert(Hincl : incl (P1 :: P9 :: nil) (list_inter (P1 :: P5 :: P9 :: nil) (P1 :: P8 :: P9 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P5 :: P8 :: P9 :: nil) (P1 :: P5 :: P9 :: P1 :: P8 :: P9 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P5 :: P9 :: P1 :: P8 :: P9 :: nil) ((P1 :: P5 :: P9 :: nil) ++ (P1 :: P8 :: P9 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P5P8P9mtmp;try rewrite HT2 in HP1P5P8P9mtmp.\n\tassert(HT := rule_2 (P1 :: P5 :: P9 :: nil) (P1 :: P8 :: P9 :: nil) (P1 :: P9 :: nil) 3 2 2 HP1P5P8P9mtmp HP1P9mtmp HP1P8P9Mtmp Hincl);apply HT.\n}\ntry clear HP1P5P9m2. try clear HP1P5P8P9M3. try clear HP1P5P8P9m3. \n\nassert(HP1P5P9P14M3 : rk(P1 :: P5 :: P9 :: P14 :: nil) <= 3).\n{\n\tassert(HP1Mtmp : rk(P1 :: nil) <= 1) by (solve_hyps_max HP1eq HP1M1).\n\tassert(HP5P9P14Mtmp : rk(P5 :: P9 :: P14 :: nil) <= 2) by (solve_hyps_max HP5P9P14eq HP5P9P14M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P1 :: nil) (P5 :: P9 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P5 :: P9 :: P14 :: nil) (P1 :: P5 :: P9 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P5 :: P9 :: P14 :: nil) ((P1 :: nil) ++ (P5 :: P9 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: nil) (P5 :: P9 :: P14 :: nil) (nil) 1 2 0 HP1Mtmp HP5P9P14Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P5P9P14M4. \n\nassert(HP1P5P9P14m2 : rk(P1 :: P5 :: P9 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P5mtmp : rk(P1 :: P5 :: nil) >= 2) by (solve_hyps_min HP1P5eq HP1P5m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P5 :: nil) (P1 :: P5 :: P9 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P5 :: nil) (P1 :: P5 :: P9 :: P14 :: nil) 2 2 HP1P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P5P9P14m1. \n\nassert(HP1P5P9P14m3 : rk(P1 :: P5 :: P9 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P5P9mtmp : rk(P1 :: P5 :: P9 :: nil) >= 3) by (solve_hyps_min HP1P5P9eq HP1P5P9m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P5 :: P9 :: nil) (P1 :: P5 :: P9 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P5 :: P9 :: nil) (P1 :: P5 :: P9 :: P14 :: nil) 3 3 HP1P5P9mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P5P9M3. try clear HP1P5P9m3. try clear HP1P5P9P14m2. \n\nassert(HP1P14m2 : rk(P1 :: P14 :: nil) >= 2).\n{\n\tassert(HP5P9P14Mtmp : rk(P5 :: P9 :: P14 :: nil) <= 2) by (solve_hyps_max HP5P9P14eq HP5P9P14M2).\n\tassert(HP1P5P9P14mtmp : rk(P1 :: P5 :: P9 :: P14 :: nil) >= 3) by (solve_hyps_min HP1P5P9P14eq HP1P5P9P14m3).\n\tassert(HP14mtmp : rk(P14 :: nil) >= 1) by (solve_hyps_min HP14eq HP14m1).\n\tassert(Hincl : incl (P14 :: nil) (list_inter (P1 :: P14 :: nil) (P5 :: P9 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P5 :: P9 :: P14 :: nil) (P1 :: P14 :: P5 :: P9 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P14 :: P5 :: P9 :: P14 :: nil) ((P1 :: P14 :: nil) ++ (P5 :: P9 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P5P9P14mtmp;try rewrite HT2 in HP1P5P9P14mtmp.\n\tassert(HT := rule_2 (P1 :: P14 :: nil) (P5 :: P9 :: P14 :: nil) (P14 :: nil) 3 1 2 HP1P5P9P14mtmp HP14mtmp HP5P9P14Mtmp Hincl);apply HT.\n}\ntry clear HP1P14m1. try clear HP1P5P9P14M3. try clear HP1P5P9P14m3. \n\nassert(HP1P4P8P9M3 : rk(P1 :: P4 :: P8 :: P9 :: nil) <= 3).\n{\n\tassert(HP4Mtmp : rk(P4 :: nil) <= 1) by (solve_hyps_max HP4eq HP4M1).\n\tassert(HP1P8P9Mtmp : rk(P1 :: P8 :: P9 :: nil) <= 2) by (solve_hyps_max HP1P8P9eq HP1P8P9M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P4 :: nil) (P1 :: P8 :: P9 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P4 :: P8 :: P9 :: nil) (P4 :: P1 :: P8 :: P9 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P4 :: P1 :: P8 :: P9 :: nil) ((P4 :: nil) ++ (P1 :: P8 :: P9 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P4 :: nil) (P1 :: P8 :: P9 :: nil) (nil) 1 2 0 HP4Mtmp HP1P8P9Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P4P8P9M4. \n\nassert(HP1P4P8P9m2 : rk(P1 :: P4 :: P8 :: P9 :: nil) >= 2).\n{\n\tassert(HP1P4mtmp : rk(P1 :: P4 :: nil) >= 2) by (solve_hyps_min HP1P4eq HP1P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: nil) (P1 :: P4 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: nil) (P1 :: P4 :: P8 :: P9 :: nil) 2 2 HP1P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P8P9m1. \n\nassert(HP1P4P8P9m3 : rk(P1 :: P4 :: P8 :: P9 :: nil) >= 3).\n{\n\tassert(HP1P4P8mtmp : rk(P1 :: P4 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P4P8eq HP1P4P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: P8 :: nil) (P1 :: P4 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: P8 :: nil) (P1 :: P4 :: P8 :: P9 :: nil) 3 3 HP1P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P8P9m2. \n\nassert(HP1P4P9m2 : rk(P1 :: P4 :: P9 :: nil) >= 2).\n{\n\tassert(HP1P4mtmp : rk(P1 :: P4 :: nil) >= 2) by (solve_hyps_min HP1P4eq HP1P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: nil) (P1 :: P4 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: nil) (P1 :: P4 :: P9 :: nil) 2 2 HP1P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P9m1. \n\nassert(HP1P4P9m3 : rk(P1 :: P4 :: P9 :: nil) >= 3).\n{\n\tassert(HP1P8P9Mtmp : rk(P1 :: P8 :: P9 :: nil) <= 2) by (solve_hyps_max HP1P8P9eq HP1P8P9M2).\n\tassert(HP1P4P8P9mtmp : rk(P1 :: P4 :: P8 :: P9 :: nil) >= 3) by (solve_hyps_min HP1P4P8P9eq HP1P4P8P9m3).\n\tassert(HP1P9mtmp : rk(P1 :: P9 :: nil) >= 2) by (solve_hyps_min HP1P9eq HP1P9m2).\n\tassert(Hincl : incl (P1 :: P9 :: nil) (list_inter (P1 :: P4 :: P9 :: nil) (P1 :: P8 :: P9 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P4 :: P8 :: P9 :: nil) (P1 :: P4 :: P9 :: P1 :: P8 :: P9 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P9 :: P1 :: P8 :: P9 :: nil) ((P1 :: P4 :: P9 :: nil) ++ (P1 :: P8 :: P9 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P4P8P9mtmp;try rewrite HT2 in HP1P4P8P9mtmp.\n\tassert(HT := rule_2 (P1 :: P4 :: P9 :: nil) (P1 :: P8 :: P9 :: nil) (P1 :: P9 :: nil) 3 2 2 HP1P4P8P9mtmp HP1P9mtmp HP1P8P9Mtmp Hincl);apply HT.\n}\ntry clear HP1P4P9m2. try clear HP1P4P8P9M3. try clear HP1P4P8P9m3. \n\nassert(HP1P4P5P9P14m2 : rk(P1 :: P4 :: P5 :: P9 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P4mtmp : rk(P1 :: P4 :: nil) >= 2) by (solve_hyps_min HP1P4eq HP1P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: nil) (P1 :: P4 :: P5 :: P9 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: nil) (P1 :: P4 :: P5 :: P9 :: P14 :: nil) 2 2 HP1P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P5P9P14m1. \n\nassert(HP1P4P5P9P14M3 : rk(P1 :: P4 :: P5 :: P9 :: P14 :: nil) <= 3).\n{\n\tassert(HP1P4P5Mtmp : rk(P1 :: P4 :: P5 :: nil) <= 2) by (solve_hyps_max HP1P4P5eq HP1P4P5M2).\n\tassert(HP5P9P14Mtmp : rk(P5 :: P9 :: P14 :: nil) <= 2) by (solve_hyps_max HP5P9P14eq HP5P9P14M2).\n\tassert(HP5mtmp : rk(P5 :: nil) >= 1) by (solve_hyps_min HP5eq HP5m1).\n\tassert(Hincl : incl (P5 :: nil) (list_inter (P1 :: P4 :: P5 :: nil) (P5 :: P9 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P4 :: P5 :: P9 :: P14 :: nil) (P1 :: P4 :: P5 :: P5 :: P9 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P5 :: P5 :: P9 :: P14 :: nil) ((P1 :: P4 :: P5 :: nil) ++ (P5 :: P9 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: P4 :: P5 :: nil) (P5 :: P9 :: P14 :: nil) (P5 :: nil) 2 2 1 HP1P4P5Mtmp HP5P9P14Mtmp HP5mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P4P5P9P14M4. \n\nassert(HP1P4P5P9P14m3 : rk(P1 :: P4 :: P5 :: P9 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P4P9mtmp : rk(P1 :: P4 :: P9 :: nil) >= 3) by (solve_hyps_min HP1P4P9eq HP1P4P9m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: P9 :: nil) (P1 :: P4 :: P5 :: P9 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: P9 :: nil) (P1 :: P4 :: P5 :: P9 :: P14 :: nil) 3 3 HP1P4P9mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P9M3. try clear HP1P4P9m3. try clear HP1P4P5P9P14m2. \n\nassert(HP1P4P5P8P9P14m2 : rk(P1 :: P4 :: P5 :: P8 :: P9 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P4mtmp : rk(P1 :: P4 :: nil) >= 2) by (solve_hyps_min HP1P4eq HP1P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: nil) (P1 :: P4 :: P5 :: P8 :: P9 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: nil) (P1 :: P4 :: P5 :: P8 :: P9 :: P14 :: nil) 2 2 HP1P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P5P8P9P14m1. \n\nassert(HP1P4P5P8P9P14m3 : rk(P1 :: P4 :: P5 :: P8 :: P9 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P4P8mtmp : rk(P1 :: P4 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P4P8eq HP1P4P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: P8 :: nil) (P1 :: P4 :: P5 :: P8 :: P9 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: P8 :: nil) (P1 :: P4 :: P5 :: P8 :: P9 :: P14 :: nil) 3 3 HP1P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P5P8P9P14m2. \n\nassert(HP1P4P5P8P9P14M3 : rk(P1 :: P4 :: P5 :: P8 :: P9 :: P14 :: nil) <= 3).\n{\n\tassert(HP1P8P9Mtmp : rk(P1 :: P8 :: P9 :: nil) <= 2) by (solve_hyps_max HP1P8P9eq HP1P8P9M2).\n\tassert(HP1P4P5P9P14Mtmp : rk(P1 :: P4 :: P5 :: P9 :: P14 :: nil) <= 3) by (solve_hyps_max HP1P4P5P9P14eq HP1P4P5P9P14M3).\n\tassert(HP1P9mtmp : rk(P1 :: P9 :: nil) >= 2) by (solve_hyps_min HP1P9eq HP1P9m2).\n\tassert(Hincl : incl (P1 :: P9 :: nil) (list_inter (P1 :: P8 :: P9 :: nil) (P1 :: P4 :: P5 :: P9 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P4 :: P5 :: P8 :: P9 :: P14 :: nil) (P1 :: P8 :: P9 :: P1 :: P4 :: P5 :: P9 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P8 :: P9 :: P1 :: P4 :: P5 :: P9 :: P14 :: nil) ((P1 :: P8 :: P9 :: nil) ++ (P1 :: P4 :: P5 :: P9 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: P8 :: P9 :: nil) (P1 :: P4 :: P5 :: P9 :: P14 :: nil) (P1 :: P9 :: nil) 2 3 2 HP1P8P9Mtmp HP1P4P5P9P14Mtmp HP1P9mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P4P5P9P14M3. try clear HP1P4P5P9P14m3. try clear HP1P4P5P8P9P14M4. \n\nassert(HP1P4P8P14m2 : rk(P1 :: P4 :: P8 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P4mtmp : rk(P1 :: P4 :: nil) >= 2) by (solve_hyps_min HP1P4eq HP1P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: nil) (P1 :: P4 :: P8 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: nil) (P1 :: P4 :: P8 :: P14 :: nil) 2 2 HP1P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P8P14m1. \n\nassert(HP1P4P8P14m3 : rk(P1 :: P4 :: P8 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P4P8mtmp : rk(P1 :: P4 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P4P8eq HP1P4P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: P8 :: nil) (P1 :: P4 :: P8 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: P8 :: nil) (P1 :: P4 :: P8 :: P14 :: nil) 3 3 HP1P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P8P14m2. \n\nassert(HP1P4P8P14M3 : rk(P1 :: P4 :: P8 :: P14 :: nil) <= 3).\n{\n\tassert(HP1P4P5P8P9P14Mtmp : rk(P1 :: P4 :: P5 :: P8 :: P9 :: P14 :: nil) <= 3) by (solve_hyps_max HP1P4P5P8P9P14eq HP1P4P5P8P9P14M3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: P8 :: P14 :: nil) (P1 :: P4 :: P5 :: P8 :: P9 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (P1 :: P4 :: P8 :: P14 :: nil) (P1 :: P4 :: P5 :: P8 :: P9 :: P14 :: nil) 3 3 HP1P4P5P8P9P14Mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P8P14M4. try clear HP1P4P5P8P9P14M3. try clear HP1P4P5P8P9P14m3. \n\nassert(HP1P12P13P14m2 : rk(P1 :: P12 :: P13 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P12mtmp : rk(P1 :: P12 :: nil) >= 2) by (solve_hyps_min HP1P12eq HP1P12m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P12 :: nil) (P1 :: P12 :: P13 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P12 :: nil) (P1 :: P12 :: P13 :: P14 :: nil) 2 2 HP1P12mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P12M2. try clear HP1P12m2. try clear HP1P12P13P14m1. \n\nassert(HP1P12P13P14M3 : rk(P1 :: P12 :: P13 :: P14 :: nil) <= 3).\n{\n\tassert(HP1P12P13Mtmp : rk(P1 :: P12 :: P13 :: nil) <= 2) by (solve_hyps_max HP1P12P13eq HP1P12P13M2).\n\tassert(HP14Mtmp : rk(P14 :: nil) <= 1) by (solve_hyps_max HP14eq HP14M1).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P1 :: P12 :: P13 :: nil) (P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P12 :: P13 :: P14 :: nil) (P1 :: P12 :: P13 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P12 :: P13 :: P14 :: nil) ((P1 :: P12 :: P13 :: nil) ++ (P14 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: P12 :: P13 :: nil) (P14 :: nil) (nil) 2 1 0 HP1P12P13Mtmp HP14Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P12P13P14M4. \n\nassert(HP1P12P13P14m3 : rk(P1 :: P12 :: P13 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P4P8P14Mtmp : rk(P1 :: P4 :: P8 :: P14 :: nil) <= 3) by (solve_hyps_max HP1P4P8P14eq HP1P4P8P14M3).\n\tassert(HP1P4P8P12P13P14mtmp : rk(P1 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P4P8P12P13P14eq HP1P4P8P12P13P14m4).\n\tassert(HP1P14mtmp : rk(P1 :: P14 :: nil) >= 2) by (solve_hyps_min HP1P14eq HP1P14m2).\n\tassert(Hincl : incl (P1 :: P14 :: nil) (list_inter (P1 :: P4 :: P8 :: P14 :: nil) (P1 :: P12 :: P13 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil) (P1 :: P4 :: P8 :: P14 :: P1 :: P12 :: P13 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P8 :: P14 :: P1 :: P12 :: P13 :: P14 :: nil) ((P1 :: P4 :: P8 :: P14 :: nil) ++ (P1 :: P12 :: P13 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P4P8P12P13P14mtmp;try rewrite HT2 in HP1P4P8P12P13P14mtmp.\n\tassert(HT := rule_4 (P1 :: P4 :: P8 :: P14 :: nil) (P1 :: P12 :: P13 :: P14 :: nil) (P1 :: P14 :: nil) 4 2 3 HP1P4P8P12P13P14mtmp HP1P14mtmp HP1P4P8P14Mtmp Hincl); apply HT.\n}\ntry clear HP1P12P13P14m2. \n\nassert(HP2P4P8m3 : rk(P2 :: P4 :: P8 :: nil) >= 3).\n{\n\tassert(HP1Mtmp : rk(P1 :: nil) <= 1) by (solve_hyps_max HP1eq HP1M1).\n\tassert(HP1P2P4P8mtmp : rk(P1 :: P2 :: P4 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8eq HP1P2P4P8m4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P1 :: nil) (P2 :: P4 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P4 :: P8 :: nil) ((P1 :: nil) ++ (P2 :: P4 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P8mtmp;try rewrite HT2 in HP1P2P4P8mtmp.\n\tassert(HT := rule_4 (P1 :: nil) (P2 :: P4 :: P8 :: nil) (nil) 4 0 1 HP1P2P4P8mtmp Hmtmp HP1Mtmp Hincl); apply HT.\n}\ntry clear HP2P4P8m1. \n\nassert(HP2P4m2 : rk(P2 :: P4 :: nil) >= 2).\n{\n\tassert(HP1Mtmp : rk(P1 :: nil) <= 1) by (solve_hyps_max HP1eq HP1M1).\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P1 :: nil) (P2 :: P4 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P4 :: nil) ((P1 :: nil) ++ (P2 :: P4 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4mtmp;try rewrite HT2 in HP1P2P4mtmp.\n\tassert(HT := rule_4 (P1 :: nil) (P2 :: P4 :: nil) (nil) 3 0 1 HP1P2P4mtmp Hmtmp HP1Mtmp Hincl); apply HT.\n}\ntry clear HP2P4m1. \n\nassert(HP2P4P6P8P10m2 : rk(P2 :: P4 :: P6 :: P8 :: P10 :: nil) >= 2).\n{\n\tassert(HP2P4mtmp : rk(P2 :: P4 :: nil) >= 2) by (solve_hyps_min HP2P4eq HP2P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P4 :: nil) (P2 :: P4 :: P6 :: P8 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P4 :: nil) (P2 :: P4 :: P6 :: P8 :: P10 :: nil) 2 2 HP2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P4P6P8P10m1. \n\nassert(HP2P4P6P8P10M3 : rk(P2 :: P4 :: P6 :: P8 :: P10 :: nil) <= 3).\n{\n\tassert(HP2P4P6Mtmp : rk(P2 :: P4 :: P6 :: nil) <= 2) by (solve_hyps_max HP2P4P6eq HP2P4P6M2).\n\tassert(HP2P8P10Mtmp : rk(P2 :: P8 :: P10 :: nil) <= 2) by (solve_hyps_max HP2P8P10eq HP2P8P10M2).\n\tassert(HP2mtmp : rk(P2 :: nil) >= 1) by (solve_hyps_min HP2eq HP2m1).\n\tassert(Hincl : incl (P2 :: nil) (list_inter (P2 :: P4 :: P6 :: nil) (P2 :: P8 :: P10 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P4 :: P6 :: P8 :: P10 :: nil) (P2 :: P4 :: P6 :: P2 :: P8 :: P10 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P4 :: P6 :: P2 :: P8 :: P10 :: nil) ((P2 :: P4 :: P6 :: nil) ++ (P2 :: P8 :: P10 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P2 :: P4 :: P6 :: nil) (P2 :: P8 :: P10 :: nil) (P2 :: nil) 2 2 1 HP2P4P6Mtmp HP2P8P10Mtmp HP2mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP2P4P6P8P10M4. \n\nassert(HP2P4P6P8P10m3 : rk(P2 :: P4 :: P6 :: P8 :: P10 :: nil) >= 3).\n{\n\tassert(HP2P4P8mtmp : rk(P2 :: P4 :: P8 :: nil) >= 3) by (solve_hyps_min HP2P4P8eq HP2P4P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P4 :: P8 :: nil) (P2 :: P4 :: P6 :: P8 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P4 :: P8 :: nil) (P2 :: P4 :: P6 :: P8 :: P10 :: nil) 3 3 HP2P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P4P6P8P10m2. \n\nassert(HP1P2P3P4P5P6P8m2 : rk(P1 :: P2 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P4P5P6P8m1. \n\nassert(HP1P2P3P4P5P6P8m3 : rk(P1 :: P2 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P4P5P6P8m2. \n\nassert(HP1P2P3P4P5P6P8m4 : rk(P1 :: P2 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) >= 4).\n{\n\tassert(HP1P2P4P8mtmp : rk(P1 :: P2 :: P4 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8eq HP1P2P4P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) 4 4 HP1P2P4P8mtmp Hcomp Hincl);apply HT.\n}\n\n\nassert(HP1P2P3P4P8P9m2 : rk(P1 :: P2 :: P3 :: P4 :: P8 :: P9 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P4 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P4 :: P8 :: P9 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P4P8P9m1. \n\nassert(HP1P2P3P4P8P9m3 : rk(P1 :: P2 :: P3 :: P4 :: P8 :: P9 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P3 :: P4 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P3 :: P4 :: P8 :: P9 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P4P8P9m2. \n\nassert(HP1P2P3P4P8P9m4 : rk(P1 :: P2 :: P3 :: P4 :: P8 :: P9 :: nil) >= 4).\n{\n\tassert(HP1P2P4P8mtmp : rk(P1 :: P2 :: P4 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8eq HP1P2P4P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P3 :: P4 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P3 :: P4 :: P8 :: P9 :: nil) 4 4 HP1P2P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P4P8P9m3. \n\nassert(HP1P2P3P8P12P13m2 : rk(P1 :: P2 :: P3 :: P8 :: P12 :: P13 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P8 :: P12 :: P13 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P8 :: P12 :: P13 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P8P12P13m1. \n\nassert(HP1P2P3P8P12P13M3 : rk(P1 :: P2 :: P3 :: P8 :: P12 :: P13 :: nil) <= 3).\n{\n\tassert(HP8Mtmp : rk(P8 :: nil) <= 1) by (solve_hyps_max HP8eq HP8M1).\n\tassert(HP1P2P3P12P13Mtmp : rk(P1 :: P2 :: P3 :: P12 :: P13 :: nil) <= 2) by (solve_hyps_max HP1P2P3P12P13eq HP1P2P3P12P13M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P8 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P8 :: P12 :: P13 :: nil) (P8 :: P1 :: P2 :: P3 :: P12 :: P13 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P8 :: P1 :: P2 :: P3 :: P12 :: P13 :: nil) ((P8 :: nil) ++ (P1 :: P2 :: P3 :: P12 :: P13 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P8 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil) (nil) 1 2 0 HP8Mtmp HP1P2P3P12P13Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P2P3P8P12P13M4. \n\nassert(HP1P2P3P8P12P13m3 : rk(P1 :: P2 :: P3 :: P8 :: P12 :: P13 :: nil) >= 3).\n{\n\tassert(HP1P2P8mtmp : rk(P1 :: P2 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P2P8eq HP1P2P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P8 :: nil) (P1 :: P2 :: P3 :: P8 :: P12 :: P13 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P8 :: nil) (P1 :: P2 :: P3 :: P8 :: P12 :: P13 :: nil) 3 3 HP1P2P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P8P12P13m2. \n\nassert(HP1P3P8m2 : rk(P1 :: P3 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P3mtmp : rk(P1 :: P3 :: nil) >= 2) by (solve_hyps_min HP1P3eq HP1P3m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P3 :: nil) (P1 :: P3 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P3 :: nil) (P1 :: P3 :: P8 :: nil) 2 2 HP1P3mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P3P8m1. \n\nassert(HP1P3P8m3 : rk(P1 :: P3 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P2P3P12P13Mtmp : rk(P1 :: P2 :: P3 :: P12 :: P13 :: nil) <= 2) by (solve_hyps_max HP1P2P3P12P13eq HP1P2P3P12P13M2).\n\tassert(HP1P2P3P8P12P13mtmp : rk(P1 :: P2 :: P3 :: P8 :: P12 :: P13 :: nil) >= 3) by (solve_hyps_min HP1P2P3P8P12P13eq HP1P2P3P8P12P13m3).\n\tassert(HP1P3mtmp : rk(P1 :: P3 :: nil) >= 2) by (solve_hyps_min HP1P3eq HP1P3m2).\n\tassert(Hincl : incl (P1 :: P3 :: nil) (list_inter (P1 :: P3 :: P8 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P8 :: P12 :: P13 :: nil) (P1 :: P3 :: P8 :: P1 :: P2 :: P3 :: P12 :: P13 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P3 :: P8 :: P1 :: P2 :: P3 :: P12 :: P13 :: nil) ((P1 :: P3 :: P8 :: nil) ++ (P1 :: P2 :: P3 :: P12 :: P13 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P3P8P12P13mtmp;try rewrite HT2 in HP1P2P3P8P12P13mtmp.\n\tassert(HT := rule_2 (P1 :: P3 :: P8 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil) (P1 :: P3 :: nil) 3 2 2 HP1P2P3P8P12P13mtmp HP1P3mtmp HP1P2P3P12P13Mtmp Hincl);apply HT.\n}\ntry clear HP1P3P8m2. \n\nassert(HP1P2P3P8P9m2 : rk(P1 :: P2 :: P3 :: P8 :: P9 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P8 :: P9 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P8P9m1. \n\nassert(HP1P2P3P8P9M3 : rk(P1 :: P2 :: P3 :: P8 :: P9 :: nil) <= 3).\n{\n\tassert(HP1P2P3Mtmp : rk(P1 :: P2 :: P3 :: nil) <= 2) by (solve_hyps_max HP1P2P3eq HP1P2P3M2).\n\tassert(HP1P8P9Mtmp : rk(P1 :: P8 :: P9 :: nil) <= 2) by (solve_hyps_max HP1P8P9eq HP1P8P9M2).\n\tassert(HP1mtmp : rk(P1 :: nil) >= 1) by (solve_hyps_min HP1eq HP1m1).\n\tassert(Hincl : incl (P1 :: nil) (list_inter (P1 :: P2 :: P3 :: nil) (P1 :: P8 :: P9 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P8 :: P9 :: nil) (P1 :: P2 :: P3 :: P1 :: P8 :: P9 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P3 :: P1 :: P8 :: P9 :: nil) ((P1 :: P2 :: P3 :: nil) ++ (P1 :: P8 :: P9 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: P2 :: P3 :: nil) (P1 :: P8 :: P9 :: nil) (P1 :: nil) 2 2 1 HP1P2P3Mtmp HP1P8P9Mtmp HP1mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P2P3P8P9M4. \n\nassert(HP1P2P3P8P9m3 : rk(P1 :: P2 :: P3 :: P8 :: P9 :: nil) >= 3).\n{\n\tassert(HP1P2P8mtmp : rk(P1 :: P2 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P2P8eq HP1P2P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P8 :: nil) (P1 :: P2 :: P3 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P8 :: nil) (P1 :: P2 :: P3 :: P8 :: P9 :: nil) 3 3 HP1P2P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P8P9m2. \n\nassert(HP1P2P3P4P8m2 : rk(P1 :: P2 :: P3 :: P4 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P4 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P4 :: P8 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P4P8m1. \n\nassert(HP1P2P3P4P8m3 : rk(P1 :: P2 :: P3 :: P4 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P3 :: P4 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P3 :: P4 :: P8 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P4P8m2. \n\nassert(HP1P2P3P4P12P13m2 : rk(P1 :: P2 :: P3 :: P4 :: P12 :: P13 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P4 :: P12 :: P13 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P4 :: P12 :: P13 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P4P12P13m1. \n\nassert(HP1P2P3P4P12P13M3 : rk(P1 :: P2 :: P3 :: P4 :: P12 :: P13 :: nil) <= 3).\n{\n\tassert(HP4Mtmp : rk(P4 :: nil) <= 1) by (solve_hyps_max HP4eq HP4M1).\n\tassert(HP1P2P3P12P13Mtmp : rk(P1 :: P2 :: P3 :: P12 :: P13 :: nil) <= 2) by (solve_hyps_max HP1P2P3P12P13eq HP1P2P3P12P13M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P4 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P4 :: P12 :: P13 :: nil) (P4 :: P1 :: P2 :: P3 :: P12 :: P13 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P4 :: P1 :: P2 :: P3 :: P12 :: P13 :: nil) ((P4 :: nil) ++ (P1 :: P2 :: P3 :: P12 :: P13 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P4 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil) (nil) 1 2 0 HP4Mtmp HP1P2P3P12P13Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P2P3P4P12P13M4. \n\nassert(HP1P2P3P4P12P13m3 : rk(P1 :: P2 :: P3 :: P4 :: P12 :: P13 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P3 :: P4 :: P12 :: P13 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P3 :: P4 :: P12 :: P13 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P4P12P13m2. \n\nassert(HP1P3P4m2 : rk(P1 :: P3 :: P4 :: nil) >= 2).\n{\n\tassert(HP1P3mtmp : rk(P1 :: P3 :: nil) >= 2) by (solve_hyps_min HP1P3eq HP1P3m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P3 :: nil) (P1 :: P3 :: P4 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P3 :: nil) (P1 :: P3 :: P4 :: nil) 2 2 HP1P3mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P3P4m1. \n\nassert(HP1P3P4m3 : rk(P1 :: P3 :: P4 :: nil) >= 3).\n{\n\tassert(HP1P2P3P12P13Mtmp : rk(P1 :: P2 :: P3 :: P12 :: P13 :: nil) <= 2) by (solve_hyps_max HP1P2P3P12P13eq HP1P2P3P12P13M2).\n\tassert(HP1P2P3P4P12P13mtmp : rk(P1 :: P2 :: P3 :: P4 :: P12 :: P13 :: nil) >= 3) by (solve_hyps_min HP1P2P3P4P12P13eq HP1P2P3P4P12P13m3).\n\tassert(HP1P3mtmp : rk(P1 :: P3 :: nil) >= 2) by (solve_hyps_min HP1P3eq HP1P3m2).\n\tassert(Hincl : incl (P1 :: P3 :: nil) (list_inter (P1 :: P3 :: P4 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P4 :: P12 :: P13 :: nil) (P1 :: P3 :: P4 :: P1 :: P2 :: P3 :: P12 :: P13 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P3 :: P4 :: P1 :: P2 :: P3 :: P12 :: P13 :: nil) ((P1 :: P3 :: P4 :: nil) ++ (P1 :: P2 :: P3 :: P12 :: P13 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P3P4P12P13mtmp;try rewrite HT2 in HP1P2P3P4P12P13mtmp.\n\tassert(HT := rule_2 (P1 :: P3 :: P4 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil) (P1 :: P3 :: nil) 3 2 2 HP1P2P3P4P12P13mtmp HP1P3mtmp HP1P2P3P12P13Mtmp Hincl);apply HT.\n}\ntry clear HP1P3P4m2. \n\nassert(HP1P2P3P4m2 : rk(P1 :: P2 :: P3 :: P4 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P4 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P4 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P4m1. \n\nassert(HP1P2P3P4M3 : rk(P1 :: P2 :: P3 :: P4 :: nil) <= 3).\n{\n\tassert(HP1P2P3Mtmp : rk(P1 :: P2 :: P3 :: nil) <= 2) by (solve_hyps_max HP1P2P3eq HP1P2P3M2).\n\tassert(HP4Mtmp : rk(P4 :: nil) <= 1) by (solve_hyps_max HP4eq HP4M1).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P1 :: P2 :: P3 :: nil) (P4 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P4 :: nil) (P1 :: P2 :: P3 :: P4 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P3 :: P4 :: nil) ((P1 :: P2 :: P3 :: nil) ++ (P4 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: P2 :: P3 :: nil) (P4 :: nil) (nil) 2 1 0 HP1P2P3Mtmp HP4Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P2P3P4M4. \n\nassert(HP1P2P3P4m3 : rk(P1 :: P2 :: P3 :: P4 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P3 :: P4 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P3 :: P4 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P4m2. \n\nassert(HP1P3P4P8m2 : rk(P1 :: P3 :: P4 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P3mtmp : rk(P1 :: P3 :: nil) >= 2) by (solve_hyps_min HP1P3eq HP1P3m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P3 :: nil) (P1 :: P3 :: P4 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P3 :: nil) (P1 :: P3 :: P4 :: P8 :: nil) 2 2 HP1P3mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P3P4P8m1. \n\nassert(HP1P3P4P8m3 : rk(P1 :: P3 :: P4 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P2P3P4Mtmp : rk(P1 :: P2 :: P3 :: P4 :: nil) <= 3) by (solve_hyps_max HP1P2P3P4eq HP1P2P3P4M3).\n\tassert(HP1P2P3P4P8mtmp : rk(P1 :: P2 :: P3 :: P4 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P2P3P4P8eq HP1P2P3P4P8m3).\n\tassert(HP1P3P4mtmp : rk(P1 :: P3 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P3P4eq HP1P3P4m3).\n\tassert(Hincl : incl (P1 :: P3 :: P4 :: nil) (list_inter (P1 :: P2 :: P3 :: P4 :: nil) (P1 :: P3 :: P4 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P4 :: P8 :: nil) (P1 :: P2 :: P3 :: P4 :: P1 :: P3 :: P4 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P3 :: P4 :: P1 :: P3 :: P4 :: P8 :: nil) ((P1 :: P2 :: P3 :: P4 :: nil) ++ (P1 :: P3 :: P4 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P3P4P8mtmp;try rewrite HT2 in HP1P2P3P4P8mtmp.\n\tassert(HT := rule_4 (P1 :: P2 :: P3 :: P4 :: nil) (P1 :: P3 :: P4 :: P8 :: nil) (P1 :: P3 :: P4 :: nil) 3 3 3 HP1P2P3P4P8mtmp HP1P3P4mtmp HP1P2P3P4Mtmp Hincl); apply HT.\n}\ntry clear HP1P3P4P8m2. \n\nassert(HP1P3P4P8m4 : rk(P1 :: P3 :: P4 :: P8 :: nil) >= 4).\n{\n\tassert(HP1P2P3P8P9Mtmp : rk(P1 :: P2 :: P3 :: P8 :: P9 :: nil) <= 3) by (solve_hyps_max HP1P2P3P8P9eq HP1P2P3P8P9M3).\n\tassert(HP1P2P3P4P8P9mtmp : rk(P1 :: P2 :: P3 :: P4 :: P8 :: P9 :: nil) >= 4) by (solve_hyps_min HP1P2P3P4P8P9eq HP1P2P3P4P8P9m4).\n\tassert(HP1P3P8mtmp : rk(P1 :: P3 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P3P8eq HP1P3P8m3).\n\tassert(Hincl : incl (P1 :: P3 :: P8 :: nil) (list_inter (P1 :: P3 :: P4 :: P8 :: nil) (P1 :: P2 :: P3 :: P8 :: P9 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P4 :: P8 :: P9 :: nil) (P1 :: P3 :: P4 :: P8 :: P1 :: P2 :: P3 :: P8 :: P9 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P3 :: P4 :: P8 :: P1 :: P2 :: P3 :: P8 :: P9 :: nil) ((P1 :: P3 :: P4 :: P8 :: nil) ++ (P1 :: P2 :: P3 :: P8 :: P9 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P3P4P8P9mtmp;try rewrite HT2 in HP1P2P3P4P8P9mtmp.\n\tassert(HT := rule_2 (P1 :: P3 :: P4 :: P8 :: nil) (P1 :: P2 :: P3 :: P8 :: P9 :: nil) (P1 :: P3 :: P8 :: nil) 4 3 3 HP1P2P3P4P8P9mtmp HP1P3P8mtmp HP1P2P3P8P9Mtmp Hincl);apply HT.\n}\ntry clear HP1P3P4P8m3. try clear HP1P3P8M3. try clear HP1P3P8m3. try clear HP1P2P3P4P8P9M4. try clear HP1P2P3P4P8P9m4. \n\nassert(HP1P2P3P4P8m4 : rk(P1 :: P2 :: P3 :: P4 :: P8 :: nil) >= 4).\n{\n\tassert(HP1P2P4P8mtmp : rk(P1 :: P2 :: P4 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8eq HP1P2P4P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P3 :: P4 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P3 :: P4 :: P8 :: nil) 4 4 HP1P2P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P4P8m3. \n\nassert(HP1P3P4P5P6P8m2 : rk(P1 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P3mtmp : rk(P1 :: P3 :: nil) >= 2) by (solve_hyps_min HP1P3eq HP1P3m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P3 :: nil) (P1 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P3 :: nil) (P1 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) 2 2 HP1P3mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P3P4P5P6P8m1. \n\nassert(HP1P3P4P5P6P8m3 : rk(P1 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P2P3P4Mtmp : rk(P1 :: P2 :: P3 :: P4 :: nil) <= 3) by (solve_hyps_max HP1P2P3P4eq HP1P2P3P4M3).\n\tassert(HP1P2P3P4P5P6P8mtmp : rk(P1 :: P2 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P2P3P4P5P6P8eq HP1P2P3P4P5P6P8m3).\n\tassert(HP1P3P4mtmp : rk(P1 :: P3 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P3P4eq HP1P3P4m3).\n\tassert(Hincl : incl (P1 :: P3 :: P4 :: nil) (list_inter (P1 :: P2 :: P3 :: P4 :: nil) (P1 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) (P1 :: P2 :: P3 :: P4 :: P1 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P3 :: P4 :: P1 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) ((P1 :: P2 :: P3 :: P4 :: nil) ++ (P1 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P3P4P5P6P8mtmp;try rewrite HT2 in HP1P2P3P4P5P6P8mtmp.\n\tassert(HT := rule_4 (P1 :: P2 :: P3 :: P4 :: nil) (P1 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) (P1 :: P3 :: P4 :: nil) 3 3 3 HP1P2P3P4P5P6P8mtmp HP1P3P4mtmp HP1P2P3P4Mtmp Hincl); apply HT.\n}\ntry clear HP1P3P4P5P6P8m2. \n\nassert(HP1P3P4P5P6P8m4 : rk(P1 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) >= 4).\n{\n\tassert(HP1P2P3P4P8Mtmp : rk(P1 :: P2 :: P3 :: P4 :: P8 :: nil) <= 4) by (solve_hyps_max HP1P2P3P4P8eq HP1P2P3P4P8M4).\n\tassert(HP1P2P3P4P5P6P8mtmp : rk(P1 :: P2 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P3P4P5P6P8eq HP1P2P3P4P5P6P8m4).\n\tassert(HP1P3P4P8mtmp : rk(P1 :: P3 :: P4 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P3P4P8eq HP1P3P4P8m4).\n\tassert(Hincl : incl (P1 :: P3 :: P4 :: P8 :: nil) (list_inter (P1 :: P2 :: P3 :: P4 :: P8 :: nil) (P1 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) (P1 :: P2 :: P3 :: P4 :: P8 :: P1 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P3 :: P4 :: P8 :: P1 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) ((P1 :: P2 :: P3 :: P4 :: P8 :: nil) ++ (P1 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P3P4P5P6P8mtmp;try rewrite HT2 in HP1P2P3P4P5P6P8mtmp.\n\tassert(HT := rule_4 (P1 :: P2 :: P3 :: P4 :: P8 :: nil) (P1 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) (P1 :: P3 :: P4 :: P8 :: nil) 4 4 4 HP1P2P3P4P5P6P8mtmp HP1P3P4P8mtmp HP1P2P3P4P8Mtmp Hincl); apply HT.\n}\ntry clear HP1P2P3P4P5P6P8M4. try clear HP1P2P3P4P5P6P8m4. \n\nassert(HP4P5m2 : rk(P4 :: P5 :: nil) >= 2).\n{\n\tassert(HP6Mtmp : rk(P6 :: nil) <= 1) by (solve_hyps_max HP6eq HP6M1).\n\tassert(HP4P5P6mtmp : rk(P4 :: P5 :: P6 :: nil) >= 3) by (solve_hyps_min HP4P5P6eq HP4P5P6m3).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P4 :: P5 :: nil) (P6 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P4 :: P5 :: P6 :: nil) (P4 :: P5 :: P6 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P4 :: P5 :: P6 :: nil) ((P4 :: P5 :: nil) ++ (P6 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP4P5P6mtmp;try rewrite HT2 in HP4P5P6mtmp.\n\tassert(HT := rule_2 (P4 :: P5 :: nil) (P6 :: nil) (nil) 3 0 1 HP4P5P6mtmp Hmtmp HP6Mtmp Hincl);apply HT.\n}\ntry clear HP4P5m1. \n\nassert(HP4P5P8m2 : rk(P4 :: P5 :: P8 :: nil) >= 2).\n{\n\tassert(HP4P5mtmp : rk(P4 :: P5 :: nil) >= 2) by (solve_hyps_min HP4P5eq HP4P5m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P4 :: P5 :: nil) (P4 :: P5 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P4 :: P5 :: nil) (P4 :: P5 :: P8 :: nil) 2 2 HP4P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP4P5P8m1. \n\nassert(HP4P5P8m3 : rk(P4 :: P5 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P2P4P5P7P12Mtmp : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil) <= 3) by (solve_hyps_max HP1P2P4P5P7P12eq HP1P2P4P5P7P12M3).\n\tassert(HP1P2P4P5P7P8P12mtmp : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: P12 :: nil) >= 4) by (solve_hyps_min HP1P2P4P5P7P8P12eq HP1P2P4P5P7P8P12m4).\n\tassert(HP4P5mtmp : rk(P4 :: P5 :: nil) >= 2) by (solve_hyps_min HP4P5eq HP4P5m2).\n\tassert(Hincl : incl (P4 :: P5 :: nil) (list_inter (P4 :: P5 :: P8 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: P12 :: nil) (P4 :: P5 :: P8 :: P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P4 :: P5 :: P8 :: P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil) ((P4 :: P5 :: P8 :: nil) ++ (P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P5P7P8P12mtmp;try rewrite HT2 in HP1P2P4P5P7P8P12mtmp.\n\tassert(HT := rule_2 (P4 :: P5 :: P8 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil) (P4 :: P5 :: nil) 4 2 3 HP1P2P4P5P7P8P12mtmp HP4P5mtmp HP1P2P4P5P7P12Mtmp Hincl);apply HT.\n}\ntry clear HP4P5P8m2. \n\nassert(HP3P4m2 : rk(P3 :: P4 :: nil) >= 2).\n{\n\tassert(HP1P2P3P12P13Mtmp : rk(P1 :: P2 :: P3 :: P12 :: P13 :: nil) <= 2) by (solve_hyps_max HP1P2P3P12P13eq HP1P2P3P12P13M2).\n\tassert(HP1P2P3P4P12P13mtmp : rk(P1 :: P2 :: P3 :: P4 :: P12 :: P13 :: nil) >= 3) by (solve_hyps_min HP1P2P3P4P12P13eq HP1P2P3P4P12P13m3).\n\tassert(HP3mtmp : rk(P3 :: nil) >= 1) by (solve_hyps_min HP3eq HP3m1).\n\tassert(Hincl : incl (P3 :: nil) (list_inter (P3 :: P4 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P4 :: P12 :: P13 :: nil) (P3 :: P4 :: P1 :: P2 :: P3 :: P12 :: P13 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P3 :: P4 :: P1 :: P2 :: P3 :: P12 :: P13 :: nil) ((P3 :: P4 :: nil) ++ (P1 :: P2 :: P3 :: P12 :: P13 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P3P4P12P13mtmp;try rewrite HT2 in HP1P2P3P4P12P13mtmp.\n\tassert(HT := rule_2 (P3 :: P4 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil) (P3 :: nil) 3 1 2 HP1P2P3P4P12P13mtmp HP3mtmp HP1P2P3P12P13Mtmp Hincl);apply HT.\n}\ntry clear HP3P4m1. try clear HP1P2P3P4P12P13M3. try clear HP1P2P3P4P12P13m3. \n\nassert(HP3P4P5P6P8m2 : rk(P3 :: P4 :: P5 :: P6 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P2P3P4Mtmp : rk(P1 :: P2 :: P3 :: P4 :: nil) <= 3) by (solve_hyps_max HP1P2P3P4eq HP1P2P3P4M3).\n\tassert(HP1P2P3P4P5P6P8mtmp : rk(P1 :: P2 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P2P3P4P5P6P8eq HP1P2P3P4P5P6P8m3).\n\tassert(HP3P4mtmp : rk(P3 :: P4 :: nil) >= 2) by (solve_hyps_min HP3P4eq HP3P4m2).\n\tassert(Hincl : incl (P3 :: P4 :: nil) (list_inter (P1 :: P2 :: P3 :: P4 :: nil) (P3 :: P4 :: P5 :: P6 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) (P1 :: P2 :: P3 :: P4 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P3 :: P4 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) ((P1 :: P2 :: P3 :: P4 :: nil) ++ (P3 :: P4 :: P5 :: P6 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P3P4P5P6P8mtmp;try rewrite HT2 in HP1P2P3P4P5P6P8mtmp.\n\tassert(HT := rule_4 (P1 :: P2 :: P3 :: P4 :: nil) (P3 :: P4 :: P5 :: P6 :: P8 :: nil) (P3 :: P4 :: nil) 3 2 3 HP1P2P3P4P5P6P8mtmp HP3P4mtmp HP1P2P3P4Mtmp Hincl); apply HT.\n}\ntry clear HP3P4P5P6P8m1. try clear HP3P4M2. try clear HP3P4m2. try clear HP1P2P3P4P5P6P8M4. try clear HP1P2P3P4P5P6P8m3. \n\nassert(HP3P4P5P6P8m3 : rk(P3 :: P4 :: P5 :: P6 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P4P5Mtmp : rk(P1 :: P4 :: P5 :: nil) <= 2) by (solve_hyps_max HP1P4P5eq HP1P4P5M2).\n\tassert(HP1P3P4P5P6P8mtmp : rk(P1 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P3P4P5P6P8eq HP1P3P4P5P6P8m3).\n\tassert(HP4P5mtmp : rk(P4 :: P5 :: nil) >= 2) by (solve_hyps_min HP4P5eq HP4P5m2).\n\tassert(Hincl : incl (P4 :: P5 :: nil) (list_inter (P1 :: P4 :: P5 :: nil) (P3 :: P4 :: P5 :: P6 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) (P1 :: P4 :: P5 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P5 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) ((P1 :: P4 :: P5 :: nil) ++ (P3 :: P4 :: P5 :: P6 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P3P4P5P6P8mtmp;try rewrite HT2 in HP1P3P4P5P6P8mtmp.\n\tassert(HT := rule_4 (P1 :: P4 :: P5 :: nil) (P3 :: P4 :: P5 :: P6 :: P8 :: nil) (P4 :: P5 :: nil) 3 2 2 HP1P3P4P5P6P8mtmp HP4P5mtmp HP1P4P5Mtmp Hincl); apply HT.\n}\ntry clear HP3P4P5P6P8m2. try clear HP1P3P4P5P6P8M4. try clear HP1P3P4P5P6P8m3. \n\nassert(HP3P4P5P6P8m4 : rk(P3 :: P4 :: P5 :: P6 :: P8 :: nil) >= 4).\n{\n\tassert(HP1P4P5P8Mtmp : rk(P1 :: P4 :: P5 :: P8 :: nil) <= 3) by (solve_hyps_max HP1P4P5P8eq HP1P4P5P8M3).\n\tassert(HP1P3P4P5P6P8mtmp : rk(P1 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P3P4P5P6P8eq HP1P3P4P5P6P8m4).\n\tassert(HP4P5P8mtmp : rk(P4 :: P5 :: P8 :: nil) >= 3) by (solve_hyps_min HP4P5P8eq HP4P5P8m3).\n\tassert(Hincl : incl (P4 :: P5 :: P8 :: nil) (list_inter (P1 :: P4 :: P5 :: P8 :: nil) (P3 :: P4 :: P5 :: P6 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) (P1 :: P4 :: P5 :: P8 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P5 :: P8 :: P3 :: P4 :: P5 :: P6 :: P8 :: nil) ((P1 :: P4 :: P5 :: P8 :: nil) ++ (P3 :: P4 :: P5 :: P6 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P3P4P5P6P8mtmp;try rewrite HT2 in HP1P3P4P5P6P8mtmp.\n\tassert(HT := rule_4 (P1 :: P4 :: P5 :: P8 :: nil) (P3 :: P4 :: P5 :: P6 :: P8 :: nil) (P4 :: P5 :: P8 :: nil) 4 3 3 HP1P3P4P5P6P8mtmp HP4P5P8mtmp HP1P4P5P8Mtmp Hincl); apply HT.\n}\ntry clear HP3P4P5P6P8m3. try clear HP1P3P4P5P6P8M4. try clear HP1P3P4P5P6P8m4. \n\nassert(HP1P2P4P6P7P8P12m2 : rk(P1 :: P2 :: P4 :: P6 :: P7 :: P8 :: P12 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P6 :: P7 :: P8 :: P12 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P6 :: P7 :: P8 :: P12 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P6P7P8P12m1. \n\nassert(HP1P2P4P6P7P8P12m3 : rk(P1 :: P2 :: P4 :: P6 :: P7 :: P8 :: P12 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P6 :: P7 :: P8 :: P12 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P6 :: P7 :: P8 :: P12 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P6P7P8P12m2. \n\nassert(HP1P2P4P6P7P8P12m4 : rk(P1 :: P2 :: P4 :: P6 :: P7 :: P8 :: P12 :: nil) >= 4).\n{\n\tassert(HP1P2P4P8mtmp : rk(P1 :: P2 :: P4 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8eq HP1P2P4P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P6 :: P7 :: P8 :: P12 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P6 :: P7 :: P8 :: P12 :: nil) 4 4 HP1P2P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P6P7P8P12m3. \n\nassert(HP2P4P5P7M3 : rk(P2 :: P4 :: P5 :: P7 :: nil) <= 3).\n{\n\tassert(HP4Mtmp : rk(P4 :: nil) <= 1) by (solve_hyps_max HP4eq HP4M1).\n\tassert(HP2P5P7Mtmp : rk(P2 :: P5 :: P7 :: nil) <= 2) by (solve_hyps_max HP2P5P7eq HP2P5P7M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P4 :: nil) (P2 :: P5 :: P7 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P4 :: P5 :: P7 :: nil) (P4 :: P2 :: P5 :: P7 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P4 :: P2 :: P5 :: P7 :: nil) ((P4 :: nil) ++ (P2 :: P5 :: P7 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P4 :: nil) (P2 :: P5 :: P7 :: nil) (nil) 1 2 0 HP4Mtmp HP2P5P7Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP2P4P5P7M4. \n\nassert(HP2P4P5P7m2 : rk(P2 :: P4 :: P5 :: P7 :: nil) >= 2).\n{\n\tassert(HP2P4mtmp : rk(P2 :: P4 :: nil) >= 2) by (solve_hyps_min HP2P4eq HP2P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P4 :: nil) (P2 :: P4 :: P5 :: P7 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P4 :: nil) (P2 :: P4 :: P5 :: P7 :: nil) 2 2 HP2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P4P5P7m1. \n\nassert(HP2P4P5P7m3 : rk(P2 :: P4 :: P5 :: P7 :: nil) >= 3).\n{\n\tassert(HP1P4P5Mtmp : rk(P1 :: P4 :: P5 :: nil) <= 2) by (solve_hyps_max HP1P4P5eq HP1P4P5M2).\n\tassert(HP1P2P4P5P7mtmp : rk(P1 :: P2 :: P4 :: P5 :: P7 :: nil) >= 3) by (solve_hyps_min HP1P2P4P5P7eq HP1P2P4P5P7m3).\n\tassert(HP4P5mtmp : rk(P4 :: P5 :: nil) >= 2) by (solve_hyps_min HP4P5eq HP4P5m2).\n\tassert(Hincl : incl (P4 :: P5 :: nil) (list_inter (P1 :: P4 :: P5 :: nil) (P2 :: P4 :: P5 :: P7 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P5 :: P7 :: nil) (P1 :: P4 :: P5 :: P2 :: P4 :: P5 :: P7 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P5 :: P2 :: P4 :: P5 :: P7 :: nil) ((P1 :: P4 :: P5 :: nil) ++ (P2 :: P4 :: P5 :: P7 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P5P7mtmp;try rewrite HT2 in HP1P2P4P5P7mtmp.\n\tassert(HT := rule_4 (P1 :: P4 :: P5 :: nil) (P2 :: P4 :: P5 :: P7 :: nil) (P4 :: P5 :: nil) 3 2 2 HP1P2P4P5P7mtmp HP4P5mtmp HP1P4P5Mtmp Hincl); apply HT.\n}\ntry clear HP2P4P5P7m2. try clear HP1P2P4P5P7M3. try clear HP1P2P4P5P7m3. \n\nassert(HP1P2P3P5P6m2 : rk(P1 :: P2 :: P3 :: P5 :: P6 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P5 :: P6 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P5 :: P6 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P5P6m1. \n\nassert(HP1P2P3P5P6M3 : rk(P1 :: P2 :: P3 :: P5 :: P6 :: nil) <= 3).\n{\n\tassert(HP1P2P3Mtmp : rk(P1 :: P2 :: P3 :: nil) <= 2) by (solve_hyps_max HP1P2P3eq HP1P2P3M2).\n\tassert(HP3P5P6Mtmp : rk(P3 :: P5 :: P6 :: nil) <= 2) by (solve_hyps_max HP3P5P6eq HP3P5P6M2).\n\tassert(HP3mtmp : rk(P3 :: nil) >= 1) by (solve_hyps_min HP3eq HP3m1).\n\tassert(Hincl : incl (P3 :: nil) (list_inter (P1 :: P2 :: P3 :: nil) (P3 :: P5 :: P6 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P5 :: P6 :: nil) (P1 :: P2 :: P3 :: P3 :: P5 :: P6 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P3 :: P3 :: P5 :: P6 :: nil) ((P1 :: P2 :: P3 :: nil) ++ (P3 :: P5 :: P6 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: P2 :: P3 :: nil) (P3 :: P5 :: P6 :: nil) (P3 :: nil) 2 2 1 HP1P2P3Mtmp HP3P5P6Mtmp HP3mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P2P3P5P6M4. \n\nassert(HP1P2P3P5P6m3 : rk(P1 :: P2 :: P3 :: P5 :: P6 :: nil) >= 3).\n{\n\tassert(HP1P2P5mtmp : rk(P1 :: P2 :: P5 :: nil) >= 3) by (solve_hyps_min HP1P2P5eq HP1P2P5m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P5 :: nil) (P1 :: P2 :: P3 :: P5 :: P6 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P5 :: nil) (P1 :: P2 :: P3 :: P5 :: P6 :: nil) 3 3 HP1P2P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P5P6m2. \n\nassert(HP1P2P3P5P12P13m2 : rk(P1 :: P2 :: P3 :: P5 :: P12 :: P13 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P5 :: P12 :: P13 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P5 :: P12 :: P13 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P5P12P13m1. \n\nassert(HP1P2P3P5P12P13M3 : rk(P1 :: P2 :: P3 :: P5 :: P12 :: P13 :: nil) <= 3).\n{\n\tassert(HP5Mtmp : rk(P5 :: nil) <= 1) by (solve_hyps_max HP5eq HP5M1).\n\tassert(HP1P2P3P12P13Mtmp : rk(P1 :: P2 :: P3 :: P12 :: P13 :: nil) <= 2) by (solve_hyps_max HP1P2P3P12P13eq HP1P2P3P12P13M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P5 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P5 :: P12 :: P13 :: nil) (P5 :: P1 :: P2 :: P3 :: P12 :: P13 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P5 :: P1 :: P2 :: P3 :: P12 :: P13 :: nil) ((P5 :: nil) ++ (P1 :: P2 :: P3 :: P12 :: P13 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P5 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil) (nil) 1 2 0 HP5Mtmp HP1P2P3P12P13Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P2P3P5P12P13M4. \n\nassert(HP1P2P3P5P12P13m3 : rk(P1 :: P2 :: P3 :: P5 :: P12 :: P13 :: nil) >= 3).\n{\n\tassert(HP1P2P5mtmp : rk(P1 :: P2 :: P5 :: nil) >= 3) by (solve_hyps_min HP1P2P5eq HP1P2P5m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P5 :: nil) (P1 :: P2 :: P3 :: P5 :: P12 :: P13 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P5 :: nil) (P1 :: P2 :: P3 :: P5 :: P12 :: P13 :: nil) 3 3 HP1P2P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P5P12P13m2. \n\nassert(HP2P3P5m2 : rk(P2 :: P3 :: P5 :: nil) >= 2).\n{\n\tassert(HP2P3mtmp : rk(P2 :: P3 :: nil) >= 2) by (solve_hyps_min HP2P3eq HP2P3m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P3 :: nil) (P2 :: P3 :: P5 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P3 :: nil) (P2 :: P3 :: P5 :: nil) 2 2 HP2P3mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P3P5m1. \n\nassert(HP2P3P5m3 : rk(P2 :: P3 :: P5 :: nil) >= 3).\n{\n\tassert(HP1P2P3P12P13Mtmp : rk(P1 :: P2 :: P3 :: P12 :: P13 :: nil) <= 2) by (solve_hyps_max HP1P2P3P12P13eq HP1P2P3P12P13M2).\n\tassert(HP1P2P3P5P12P13mtmp : rk(P1 :: P2 :: P3 :: P5 :: P12 :: P13 :: nil) >= 3) by (solve_hyps_min HP1P2P3P5P12P13eq HP1P2P3P5P12P13m3).\n\tassert(HP2P3mtmp : rk(P2 :: P3 :: nil) >= 2) by (solve_hyps_min HP2P3eq HP2P3m2).\n\tassert(Hincl : incl (P2 :: P3 :: nil) (list_inter (P2 :: P3 :: P5 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P5 :: P12 :: P13 :: nil) (P2 :: P3 :: P5 :: P1 :: P2 :: P3 :: P12 :: P13 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P3 :: P5 :: P1 :: P2 :: P3 :: P12 :: P13 :: nil) ((P2 :: P3 :: P5 :: nil) ++ (P1 :: P2 :: P3 :: P12 :: P13 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P3P5P12P13mtmp;try rewrite HT2 in HP1P2P3P5P12P13mtmp.\n\tassert(HT := rule_2 (P2 :: P3 :: P5 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil) (P2 :: P3 :: nil) 3 2 2 HP1P2P3P5P12P13mtmp HP2P3mtmp HP1P2P3P12P13Mtmp Hincl);apply HT.\n}\ntry clear HP2P3P5m2. try clear HP1P2P3P5P12P13M3. try clear HP1P2P3P5P12P13m3. \n\nassert(HP1P2P3P5m2 : rk(P1 :: P2 :: P3 :: P5 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P5 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P5 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P5m1. \n\nassert(HP1P2P3P5M3 : rk(P1 :: P2 :: P3 :: P5 :: nil) <= 3).\n{\n\tassert(HP1P2P3Mtmp : rk(P1 :: P2 :: P3 :: nil) <= 2) by (solve_hyps_max HP1P2P3eq HP1P2P3M2).\n\tassert(HP5Mtmp : rk(P5 :: nil) <= 1) by (solve_hyps_max HP5eq HP5M1).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P1 :: P2 :: P3 :: nil) (P5 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P5 :: nil) (P1 :: P2 :: P3 :: P5 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P3 :: P5 :: nil) ((P1 :: P2 :: P3 :: nil) ++ (P5 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: P2 :: P3 :: nil) (P5 :: nil) (nil) 2 1 0 HP1P2P3Mtmp HP5Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P2P3P5M4. \n\nassert(HP1P2P3P5m3 : rk(P1 :: P2 :: P3 :: P5 :: nil) >= 3).\n{\n\tassert(HP1P2P5mtmp : rk(P1 :: P2 :: P5 :: nil) >= 3) by (solve_hyps_min HP1P2P5eq HP1P2P5m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P5 :: nil) (P1 :: P2 :: P3 :: P5 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P5 :: nil) (P1 :: P2 :: P3 :: P5 :: nil) 3 3 HP1P2P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P5m2. \n\nassert(HP2P3P5P6M3 : rk(P2 :: P3 :: P5 :: P6 :: nil) <= 3).\n{\n\tassert(HP2Mtmp : rk(P2 :: nil) <= 1) by (solve_hyps_max HP2eq HP2M1).\n\tassert(HP3P5P6Mtmp : rk(P3 :: P5 :: P6 :: nil) <= 2) by (solve_hyps_max HP3P5P6eq HP3P5P6M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P2 :: nil) (P3 :: P5 :: P6 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P3 :: P5 :: P6 :: nil) (P2 :: P3 :: P5 :: P6 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P3 :: P5 :: P6 :: nil) ((P2 :: nil) ++ (P3 :: P5 :: P6 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P2 :: nil) (P3 :: P5 :: P6 :: nil) (nil) 1 2 0 HP2Mtmp HP3P5P6Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP2P3P5P6M4. \n\nassert(HP2P3P5P6m2 : rk(P2 :: P3 :: P5 :: P6 :: nil) >= 2).\n{\n\tassert(HP2P3mtmp : rk(P2 :: P3 :: nil) >= 2) by (solve_hyps_min HP2P3eq HP2P3m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P3 :: nil) (P2 :: P3 :: P5 :: P6 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P3 :: nil) (P2 :: P3 :: P5 :: P6 :: nil) 2 2 HP2P3mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P3P5P6m1. \n\nassert(HP2P3P5P6m3 : rk(P2 :: P3 :: P5 :: P6 :: nil) >= 3).\n{\n\tassert(HP1P2P3P5Mtmp : rk(P1 :: P2 :: P3 :: P5 :: nil) <= 3) by (solve_hyps_max HP1P2P3P5eq HP1P2P3P5M3).\n\tassert(HP1P2P3P5P6mtmp : rk(P1 :: P2 :: P3 :: P5 :: P6 :: nil) >= 3) by (solve_hyps_min HP1P2P3P5P6eq HP1P2P3P5P6m3).\n\tassert(HP2P3P5mtmp : rk(P2 :: P3 :: P5 :: nil) >= 3) by (solve_hyps_min HP2P3P5eq HP2P3P5m3).\n\tassert(Hincl : incl (P2 :: P3 :: P5 :: nil) (list_inter (P1 :: P2 :: P3 :: P5 :: nil) (P2 :: P3 :: P5 :: P6 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P5 :: P6 :: nil) (P1 :: P2 :: P3 :: P5 :: P2 :: P3 :: P5 :: P6 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P3 :: P5 :: P2 :: P3 :: P5 :: P6 :: nil) ((P1 :: P2 :: P3 :: P5 :: nil) ++ (P2 :: P3 :: P5 :: P6 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P3P5P6mtmp;try rewrite HT2 in HP1P2P3P5P6mtmp.\n\tassert(HT := rule_4 (P1 :: P2 :: P3 :: P5 :: nil) (P2 :: P3 :: P5 :: P6 :: nil) (P2 :: P3 :: P5 :: nil) 3 3 3 HP1P2P3P5P6mtmp HP2P3P5mtmp HP1P2P3P5Mtmp Hincl); apply HT.\n}\ntry clear HP2P3P5P6m2. try clear HP1P2P3P5P6M3. try clear HP1P2P3P5P6m3. \n\nassert(HP2P6m2 : rk(P2 :: P6 :: nil) >= 2).\n{\n\tassert(HP3P5P6Mtmp : rk(P3 :: P5 :: P6 :: nil) <= 2) by (solve_hyps_max HP3P5P6eq HP3P5P6M2).\n\tassert(HP2P3P5P6mtmp : rk(P2 :: P3 :: P5 :: P6 :: nil) >= 3) by (solve_hyps_min HP2P3P5P6eq HP2P3P5P6m3).\n\tassert(HP6mtmp : rk(P6 :: nil) >= 1) by (solve_hyps_min HP6eq HP6m1).\n\tassert(Hincl : incl (P6 :: nil) (list_inter (P2 :: P6 :: nil) (P3 :: P5 :: P6 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P3 :: P5 :: P6 :: nil) (P2 :: P6 :: P3 :: P5 :: P6 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P6 :: P3 :: P5 :: P6 :: nil) ((P2 :: P6 :: nil) ++ (P3 :: P5 :: P6 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP2P3P5P6mtmp;try rewrite HT2 in HP2P3P5P6mtmp.\n\tassert(HT := rule_2 (P2 :: P6 :: nil) (P3 :: P5 :: P6 :: nil) (P6 :: nil) 3 1 2 HP2P3P5P6mtmp HP6mtmp HP3P5P6Mtmp Hincl);apply HT.\n}\ntry clear HP2P6m1. try clear HP2P3P5P6M3. try clear HP2P3P5P6m3. \n\nassert(HP1P2P6m2 : rk(P1 :: P2 :: P6 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P6 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P6 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P6m1. \n\nassert(HP1P2P6m3 : rk(P1 :: P2 :: P6 :: nil) >= 3).\n{\n\tassert(HP2P4P6Mtmp : rk(P2 :: P4 :: P6 :: nil) <= 2) by (solve_hyps_max HP2P4P6eq HP2P4P6M2).\n\tassert(HP1P2P4P6mtmp : rk(P1 :: P2 :: P4 :: P6 :: nil) >= 3) by (solve_hyps_min HP1P2P4P6eq HP1P2P4P6m3).\n\tassert(HP2P6mtmp : rk(P2 :: P6 :: nil) >= 2) by (solve_hyps_min HP2P6eq HP2P6m2).\n\tassert(Hincl : incl (P2 :: P6 :: nil) (list_inter (P1 :: P2 :: P6 :: nil) (P2 :: P4 :: P6 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P6 :: nil) (P1 :: P2 :: P6 :: P2 :: P4 :: P6 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P6 :: P2 :: P4 :: P6 :: nil) ((P1 :: P2 :: P6 :: nil) ++ (P2 :: P4 :: P6 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P6mtmp;try rewrite HT2 in HP1P2P4P6mtmp.\n\tassert(HT := rule_2 (P1 :: P2 :: P6 :: nil) (P2 :: P4 :: P6 :: nil) (P2 :: P6 :: nil) 3 2 2 HP1P2P4P6mtmp HP2P6mtmp HP2P4P6Mtmp Hincl);apply HT.\n}\ntry clear HP1P2P6m2. \n\nassert(HP1P2P6P7M3 : rk(P1 :: P2 :: P6 :: P7 :: nil) <= 3).\n{\n\tassert(HP2Mtmp : rk(P2 :: nil) <= 1) by (solve_hyps_max HP2eq HP2M1).\n\tassert(HP1P6P7Mtmp : rk(P1 :: P6 :: P7 :: nil) <= 2) by (solve_hyps_max HP1P6P7eq HP1P6P7M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P2 :: nil) (P1 :: P6 :: P7 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P6 :: P7 :: nil) (P2 :: P1 :: P6 :: P7 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P1 :: P6 :: P7 :: nil) ((P2 :: nil) ++ (P1 :: P6 :: P7 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P2 :: nil) (P1 :: P6 :: P7 :: nil) (nil) 1 2 0 HP2Mtmp HP1P6P7Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P2P6P7M4. \n\nassert(HP1P2P6P7m2 : rk(P1 :: P2 :: P6 :: P7 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P6 :: P7 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P6 :: P7 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P6P7m1. \n\nassert(HP1P2P6P7m3 : rk(P1 :: P2 :: P6 :: P7 :: nil) >= 3).\n{\n\tassert(HP1P2P6mtmp : rk(P1 :: P2 :: P6 :: nil) >= 3) by (solve_hyps_min HP1P2P6eq HP1P2P6m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P6 :: nil) (P1 :: P2 :: P6 :: P7 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P6 :: nil) (P1 :: P2 :: P6 :: P7 :: nil) 3 3 HP1P2P6mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P6P7m2. \n\nassert(HP2P7m2 : rk(P2 :: P7 :: nil) >= 2).\n{\n\tassert(HP1P6P7Mtmp : rk(P1 :: P6 :: P7 :: nil) <= 2) by (solve_hyps_max HP1P6P7eq HP1P6P7M2).\n\tassert(HP1P2P6P7mtmp : rk(P1 :: P2 :: P6 :: P7 :: nil) >= 3) by (solve_hyps_min HP1P2P6P7eq HP1P2P6P7m3).\n\tassert(HP7mtmp : rk(P7 :: nil) >= 1) by (solve_hyps_min HP7eq HP7m1).\n\tassert(Hincl : incl (P7 :: nil) (list_inter (P2 :: P7 :: nil) (P1 :: P6 :: P7 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P6 :: P7 :: nil) (P2 :: P7 :: P1 :: P6 :: P7 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P7 :: P1 :: P6 :: P7 :: nil) ((P2 :: P7 :: nil) ++ (P1 :: P6 :: P7 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P6P7mtmp;try rewrite HT2 in HP1P2P6P7mtmp.\n\tassert(HT := rule_2 (P2 :: P7 :: nil) (P1 :: P6 :: P7 :: nil) (P7 :: nil) 3 1 2 HP1P2P6P7mtmp HP7mtmp HP1P6P7Mtmp Hincl);apply HT.\n}\ntry clear HP2P7m1. try clear HP1P2P6P7M3. try clear HP1P2P6P7m3. \n\nassert(HP2P4P7m2 : rk(P2 :: P4 :: P7 :: nil) >= 2).\n{\n\tassert(HP2P4mtmp : rk(P2 :: P4 :: nil) >= 2) by (solve_hyps_min HP2P4eq HP2P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P4 :: nil) (P2 :: P4 :: P7 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P4 :: nil) (P2 :: P4 :: P7 :: nil) 2 2 HP2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P4P7m1. \n\nassert(HP2P4P7m3 : rk(P2 :: P4 :: P7 :: nil) >= 3).\n{\n\tassert(HP2P5P7Mtmp : rk(P2 :: P5 :: P7 :: nil) <= 2) by (solve_hyps_max HP2P5P7eq HP2P5P7M2).\n\tassert(HP2P4P5P7mtmp : rk(P2 :: P4 :: P5 :: P7 :: nil) >= 3) by (solve_hyps_min HP2P4P5P7eq HP2P4P5P7m3).\n\tassert(HP2P7mtmp : rk(P2 :: P7 :: nil) >= 2) by (solve_hyps_min HP2P7eq HP2P7m2).\n\tassert(Hincl : incl (P2 :: P7 :: nil) (list_inter (P2 :: P4 :: P7 :: nil) (P2 :: P5 :: P7 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P4 :: P5 :: P7 :: nil) (P2 :: P4 :: P7 :: P2 :: P5 :: P7 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P4 :: P7 :: P2 :: P5 :: P7 :: nil) ((P2 :: P4 :: P7 :: nil) ++ (P2 :: P5 :: P7 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP2P4P5P7mtmp;try rewrite HT2 in HP2P4P5P7mtmp.\n\tassert(HT := rule_2 (P2 :: P4 :: P7 :: nil) (P2 :: P5 :: P7 :: nil) (P2 :: P7 :: nil) 3 2 2 HP2P4P5P7mtmp HP2P7mtmp HP2P5P7Mtmp Hincl);apply HT.\n}\ntry clear HP2P4P7m2. \n\nassert(HP2P4P6P7P12m2 : rk(P2 :: P4 :: P6 :: P7 :: P12 :: nil) >= 2).\n{\n\tassert(HP2P4mtmp : rk(P2 :: P4 :: nil) >= 2) by (solve_hyps_min HP2P4eq HP2P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P4 :: nil) (P2 :: P4 :: P6 :: P7 :: P12 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P4 :: nil) (P2 :: P4 :: P6 :: P7 :: P12 :: nil) 2 2 HP2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P4P6P7P12m1. \n\nassert(HP2P4P6P7P12M3 : rk(P2 :: P4 :: P6 :: P7 :: P12 :: nil) <= 3).\n{\n\tassert(HP2P4P6Mtmp : rk(P2 :: P4 :: P6 :: nil) <= 2) by (solve_hyps_max HP2P4P6eq HP2P4P6M2).\n\tassert(HP4P7P12Mtmp : rk(P4 :: P7 :: P12 :: nil) <= 2) by (solve_hyps_max HP4P7P12eq HP4P7P12M2).\n\tassert(HP4mtmp : rk(P4 :: nil) >= 1) by (solve_hyps_min HP4eq HP4m1).\n\tassert(Hincl : incl (P4 :: nil) (list_inter (P2 :: P4 :: P6 :: nil) (P4 :: P7 :: P12 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P4 :: P6 :: P7 :: P12 :: nil) (P2 :: P4 :: P6 :: P4 :: P7 :: P12 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P4 :: P6 :: P4 :: P7 :: P12 :: nil) ((P2 :: P4 :: P6 :: nil) ++ (P4 :: P7 :: P12 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P2 :: P4 :: P6 :: nil) (P4 :: P7 :: P12 :: nil) (P4 :: nil) 2 2 1 HP2P4P6Mtmp HP4P7P12Mtmp HP4mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP2P4P6P7P12M4. \n\nassert(HP2P4P6P7P12m3 : rk(P2 :: P4 :: P6 :: P7 :: P12 :: nil) >= 3).\n{\n\tassert(HP2P4P7mtmp : rk(P2 :: P4 :: P7 :: nil) >= 3) by (solve_hyps_min HP2P4P7eq HP2P4P7m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P4 :: P7 :: nil) (P2 :: P4 :: P6 :: P7 :: P12 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P4 :: P7 :: nil) (P2 :: P4 :: P6 :: P7 :: P12 :: nil) 3 3 HP2P4P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P4P6P7P12m2. \n\nassert(HP1P2P4P6P7P12m2 : rk(P1 :: P2 :: P4 :: P6 :: P7 :: P12 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P6 :: P7 :: P12 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P6 :: P7 :: P12 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P6P7P12m1. \n\nassert(HP1P2P4P6P7P12m3 : rk(P1 :: P2 :: P4 :: P6 :: P7 :: P12 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P6 :: P7 :: P12 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P6 :: P7 :: P12 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P6P7P12m2. \n\nassert(HP1P2P4P6P7P12M3 : rk(P1 :: P2 :: P4 :: P6 :: P7 :: P12 :: nil) <= 3).\n{\n\tassert(HP1P2P4P7Mtmp : rk(P1 :: P2 :: P4 :: P7 :: nil) <= 3) by (solve_hyps_max HP1P2P4P7eq HP1P2P4P7M3).\n\tassert(HP2P4P6P7P12Mtmp : rk(P2 :: P4 :: P6 :: P7 :: P12 :: nil) <= 3) by (solve_hyps_max HP2P4P6P7P12eq HP2P4P6P7P12M3).\n\tassert(HP2P4P7mtmp : rk(P2 :: P4 :: P7 :: nil) >= 3) by (solve_hyps_min HP2P4P7eq HP2P4P7m3).\n\tassert(Hincl : incl (P2 :: P4 :: P7 :: nil) (list_inter (P1 :: P2 :: P4 :: P7 :: nil) (P2 :: P4 :: P6 :: P7 :: P12 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P6 :: P7 :: P12 :: nil) (P1 :: P2 :: P4 :: P7 :: P2 :: P4 :: P6 :: P7 :: P12 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P4 :: P7 :: P2 :: P4 :: P6 :: P7 :: P12 :: nil) ((P1 :: P2 :: P4 :: P7 :: nil) ++ (P2 :: P4 :: P6 :: P7 :: P12 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: P2 :: P4 :: P7 :: nil) (P2 :: P4 :: P6 :: P7 :: P12 :: nil) (P2 :: P4 :: P7 :: nil) 3 3 3 HP1P2P4P7Mtmp HP2P4P6P7P12Mtmp HP2P4P7mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP2P4P6P7P12M3. try clear HP2P4P6P7P12m3. try clear HP2P4P7M3. try clear HP2P4P7m3. try clear HP1P2P4P6P7P12M4. \n\nassert(HP6P8m2 : rk(P6 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P2P4P6P7P12Mtmp : rk(P1 :: P2 :: P4 :: P6 :: P7 :: P12 :: nil) <= 3) by (solve_hyps_max HP1P2P4P6P7P12eq HP1P2P4P6P7P12M3).\n\tassert(HP1P2P4P6P7P8P12mtmp : rk(P1 :: P2 :: P4 :: P6 :: P7 :: P8 :: P12 :: nil) >= 4) by (solve_hyps_min HP1P2P4P6P7P8P12eq HP1P2P4P6P7P8P12m4).\n\tassert(HP6mtmp : rk(P6 :: nil) >= 1) by (solve_hyps_min HP6eq HP6m1).\n\tassert(Hincl : incl (P6 :: nil) (list_inter (P6 :: P8 :: nil) (P1 :: P2 :: P4 :: P6 :: P7 :: P12 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P6 :: P7 :: P8 :: P12 :: nil) (P6 :: P8 :: P1 :: P2 :: P4 :: P6 :: P7 :: P12 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P6 :: P8 :: P1 :: P2 :: P4 :: P6 :: P7 :: P12 :: nil) ((P6 :: P8 :: nil) ++ (P1 :: P2 :: P4 :: P6 :: P7 :: P12 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P6P7P8P12mtmp;try rewrite HT2 in HP1P2P4P6P7P8P12mtmp.\n\tassert(HT := rule_2 (P6 :: P8 :: nil) (P1 :: P2 :: P4 :: P6 :: P7 :: P12 :: nil) (P6 :: nil) 4 1 3 HP1P2P4P6P7P8P12mtmp HP6mtmp HP1P2P4P6P7P12Mtmp Hincl);apply HT.\n}\ntry clear HP6P8m1. try clear HP1P2P4P6P7P12M3. try clear HP1P2P4P6P7P12m3. try clear HP1P2P4P6P7P8P12M4. try clear HP1P2P4P6P7P8P12m4. \n\nassert(HP1P3P4P5P8m2 : rk(P1 :: P3 :: P4 :: P5 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P3mtmp : rk(P1 :: P3 :: nil) >= 2) by (solve_hyps_min HP1P3eq HP1P3m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P3 :: nil) (P1 :: P3 :: P4 :: P5 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P3 :: nil) (P1 :: P3 :: P4 :: P5 :: P8 :: nil) 2 2 HP1P3mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P3P4P5P8m1. \n\nassert(HP1P3P4P5P8m3 : rk(P1 :: P3 :: P4 :: P5 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P2P3P4Mtmp : rk(P1 :: P2 :: P3 :: P4 :: nil) <= 3) by (solve_hyps_max HP1P2P3P4eq HP1P2P3P4M3).\n\tassert(HP1P2P3P4P5P8mtmp : rk(P1 :: P2 :: P3 :: P4 :: P5 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P2P3P4P5P8eq HP1P2P3P4P5P8m3).\n\tassert(HP1P3P4mtmp : rk(P1 :: P3 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P3P4eq HP1P3P4m3).\n\tassert(Hincl : incl (P1 :: P3 :: P4 :: nil) (list_inter (P1 :: P2 :: P3 :: P4 :: nil) (P1 :: P3 :: P4 :: P5 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P4 :: P5 :: P8 :: nil) (P1 :: P2 :: P3 :: P4 :: P1 :: P3 :: P4 :: P5 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P3 :: P4 :: P1 :: P3 :: P4 :: P5 :: P8 :: nil) ((P1 :: P2 :: P3 :: P4 :: nil) ++ (P1 :: P3 :: P4 :: P5 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P3P4P5P8mtmp;try rewrite HT2 in HP1P2P3P4P5P8mtmp.\n\tassert(HT := rule_4 (P1 :: P2 :: P3 :: P4 :: nil) (P1 :: P3 :: P4 :: P5 :: P8 :: nil) (P1 :: P3 :: P4 :: nil) 3 3 3 HP1P2P3P4P5P8mtmp HP1P3P4mtmp HP1P2P3P4Mtmp Hincl); apply HT.\n}\ntry clear HP1P3P4P5P8m2. try clear HP1P2P3P4P5P8M4. try clear HP1P2P3P4P5P8m3. \n\nassert(HP1P3P4P5P8m4 : rk(P1 :: P3 :: P4 :: P5 :: P8 :: nil) >= 4).\n{\n\tassert(HP1P2P3P4P8Mtmp : rk(P1 :: P2 :: P3 :: P4 :: P8 :: nil) <= 4) by (solve_hyps_max HP1P2P3P4P8eq HP1P2P3P4P8M4).\n\tassert(HP1P2P3P4P5P8mtmp : rk(P1 :: P2 :: P3 :: P4 :: P5 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P3P4P5P8eq HP1P2P3P4P5P8m4).\n\tassert(HP1P3P4P8mtmp : rk(P1 :: P3 :: P4 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P3P4P8eq HP1P3P4P8m4).\n\tassert(Hincl : incl (P1 :: P3 :: P4 :: P8 :: nil) (list_inter (P1 :: P2 :: P3 :: P4 :: P8 :: nil) (P1 :: P3 :: P4 :: P5 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P4 :: P5 :: P8 :: nil) (P1 :: P2 :: P3 :: P4 :: P8 :: P1 :: P3 :: P4 :: P5 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P3 :: P4 :: P8 :: P1 :: P3 :: P4 :: P5 :: P8 :: nil) ((P1 :: P2 :: P3 :: P4 :: P8 :: nil) ++ (P1 :: P3 :: P4 :: P5 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P3P4P5P8mtmp;try rewrite HT2 in HP1P2P3P4P5P8mtmp.\n\tassert(HT := rule_4 (P1 :: P2 :: P3 :: P4 :: P8 :: nil) (P1 :: P3 :: P4 :: P5 :: P8 :: nil) (P1 :: P3 :: P4 :: P8 :: nil) 4 4 4 HP1P2P3P4P5P8mtmp HP1P3P4P8mtmp HP1P2P3P4P8Mtmp Hincl); apply HT.\n}\ntry clear HP1P2P3P4P8M4. try clear HP1P2P3P4P8m4. try clear HP1P3P4P5P8m3. try clear HP1P3P4P8M4. try clear HP1P3P4P8m4. try clear HP1P2P3P4P5P8M4. try clear HP1P2P3P4P5P8m4. \n\nassert(HP5P8m2 : rk(P5 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P2P4P5P7P12Mtmp : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil) <= 3) by (solve_hyps_max HP1P2P4P5P7P12eq HP1P2P4P5P7P12M3).\n\tassert(HP1P2P4P5P7P8P12mtmp : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: P12 :: nil) >= 4) by (solve_hyps_min HP1P2P4P5P7P8P12eq HP1P2P4P5P7P8P12m4).\n\tassert(HP5mtmp : rk(P5 :: nil) >= 1) by (solve_hyps_min HP5eq HP5m1).\n\tassert(Hincl : incl (P5 :: nil) (list_inter (P5 :: P8 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: P12 :: nil) (P5 :: P8 :: P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P5 :: P8 :: P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil) ((P5 :: P8 :: nil) ++ (P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P5P7P8P12mtmp;try rewrite HT2 in HP1P2P4P5P7P8P12mtmp.\n\tassert(HT := rule_2 (P5 :: P8 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil) (P5 :: nil) 4 1 3 HP1P2P4P5P7P8P12mtmp HP5mtmp HP1P2P4P5P7P12Mtmp Hincl);apply HT.\n}\ntry clear HP5P8m1. try clear HP1P2P4P5P7P8P12M4. try clear HP1P2P4P5P7P8P12m4. \n\nassert(HP1P2P3P4P5m2 : rk(P1 :: P2 :: P3 :: P4 :: P5 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P4 :: P5 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P4 :: P5 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P4P5m1. \n\nassert(HP1P2P3P4P5M3 : rk(P1 :: P2 :: P3 :: P4 :: P5 :: nil) <= 3).\n{\n\tassert(HP1P2P3Mtmp : rk(P1 :: P2 :: P3 :: nil) <= 2) by (solve_hyps_max HP1P2P3eq HP1P2P3M2).\n\tassert(HP1P4P5Mtmp : rk(P1 :: P4 :: P5 :: nil) <= 2) by (solve_hyps_max HP1P4P5eq HP1P4P5M2).\n\tassert(HP1mtmp : rk(P1 :: nil) >= 1) by (solve_hyps_min HP1eq HP1m1).\n\tassert(Hincl : incl (P1 :: nil) (list_inter (P1 :: P2 :: P3 :: nil) (P1 :: P4 :: P5 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P4 :: P5 :: nil) (P1 :: P2 :: P3 :: P1 :: P4 :: P5 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P3 :: P1 :: P4 :: P5 :: nil) ((P1 :: P2 :: P3 :: nil) ++ (P1 :: P4 :: P5 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: P2 :: P3 :: nil) (P1 :: P4 :: P5 :: nil) (P1 :: nil) 2 2 1 HP1P2P3Mtmp HP1P4P5Mtmp HP1mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P2P3P4P5M4. \n\nassert(HP1P2P3P4P5m3 : rk(P1 :: P2 :: P3 :: P4 :: P5 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P3 :: P4 :: P5 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P3 :: P4 :: P5 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P4P5m2. \n\nassert(HP1P3P4P5M3 : rk(P1 :: P3 :: P4 :: P5 :: nil) <= 3).\n{\n\tassert(HP3Mtmp : rk(P3 :: nil) <= 1) by (solve_hyps_max HP3eq HP3M1).\n\tassert(HP1P4P5Mtmp : rk(P1 :: P4 :: P5 :: nil) <= 2) by (solve_hyps_max HP1P4P5eq HP1P4P5M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P3 :: nil) (P1 :: P4 :: P5 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P3 :: P4 :: P5 :: nil) (P3 :: P1 :: P4 :: P5 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P3 :: P1 :: P4 :: P5 :: nil) ((P3 :: nil) ++ (P1 :: P4 :: P5 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P3 :: nil) (P1 :: P4 :: P5 :: nil) (nil) 1 2 0 HP3Mtmp HP1P4P5Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P3P4P5M4. \n\nassert(HP1P3P4P5m2 : rk(P1 :: P3 :: P4 :: P5 :: nil) >= 2).\n{\n\tassert(HP1P3mtmp : rk(P1 :: P3 :: nil) >= 2) by (solve_hyps_min HP1P3eq HP1P3m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P3 :: nil) (P1 :: P3 :: P4 :: P5 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P3 :: nil) (P1 :: P3 :: P4 :: P5 :: nil) 2 2 HP1P3mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P3P4P5m1. \n\nassert(HP1P3P4P5m3 : rk(P1 :: P3 :: P4 :: P5 :: nil) >= 3).\n{\n\tassert(HP1P2P3P4Mtmp : rk(P1 :: P2 :: P3 :: P4 :: nil) <= 3) by (solve_hyps_max HP1P2P3P4eq HP1P2P3P4M3).\n\tassert(HP1P2P3P4P5mtmp : rk(P1 :: P2 :: P3 :: P4 :: P5 :: nil) >= 3) by (solve_hyps_min HP1P2P3P4P5eq HP1P2P3P4P5m3).\n\tassert(HP1P3P4mtmp : rk(P1 :: P3 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P3P4eq HP1P3P4m3).\n\tassert(Hincl : incl (P1 :: P3 :: P4 :: nil) (list_inter (P1 :: P2 :: P3 :: P4 :: nil) (P1 :: P3 :: P4 :: P5 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P4 :: P5 :: nil) (P1 :: P2 :: P3 :: P4 :: P1 :: P3 :: P4 :: P5 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P3 :: P4 :: P1 :: P3 :: P4 :: P5 :: nil) ((P1 :: P2 :: P3 :: P4 :: nil) ++ (P1 :: P3 :: P4 :: P5 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P3P4P5mtmp;try rewrite HT2 in HP1P2P3P4P5mtmp.\n\tassert(HT := rule_4 (P1 :: P2 :: P3 :: P4 :: nil) (P1 :: P3 :: P4 :: P5 :: nil) (P1 :: P3 :: P4 :: nil) 3 3 3 HP1P2P3P4P5mtmp HP1P3P4mtmp HP1P2P3P4Mtmp Hincl); apply HT.\n}\ntry clear HP1P2P3P4M3. try clear HP1P2P3P4m3. try clear HP1P3P4P5m2. try clear HP1P3P4M3. try clear HP1P3P4m3. try clear HP1P2P3P4P5M3. try clear HP1P2P3P4P5m3. \n\nassert(HP3P5m2 : rk(P3 :: P5 :: nil) >= 2).\n{\n\tassert(HP1P4P5Mtmp : rk(P1 :: P4 :: P5 :: nil) <= 2) by (solve_hyps_max HP1P4P5eq HP1P4P5M2).\n\tassert(HP1P3P4P5mtmp : rk(P1 :: P3 :: P4 :: P5 :: nil) >= 3) by (solve_hyps_min HP1P3P4P5eq HP1P3P4P5m3).\n\tassert(HP5mtmp : rk(P5 :: nil) >= 1) by (solve_hyps_min HP5eq HP5m1).\n\tassert(Hincl : incl (P5 :: nil) (list_inter (P3 :: P5 :: nil) (P1 :: P4 :: P5 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P3 :: P4 :: P5 :: nil) (P3 :: P5 :: P1 :: P4 :: P5 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P3 :: P5 :: P1 :: P4 :: P5 :: nil) ((P3 :: P5 :: nil) ++ (P1 :: P4 :: P5 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P3P4P5mtmp;try rewrite HT2 in HP1P3P4P5mtmp.\n\tassert(HT := rule_2 (P3 :: P5 :: nil) (P1 :: P4 :: P5 :: nil) (P5 :: nil) 3 1 2 HP1P3P4P5mtmp HP5mtmp HP1P4P5Mtmp Hincl);apply HT.\n}\ntry clear HP3P5m1. \n\nassert(HP3P5P8m2 : rk(P3 :: P5 :: P8 :: nil) >= 2).\n{\n\tassert(HP3P5mtmp : rk(P3 :: P5 :: nil) >= 2) by (solve_hyps_min HP3P5eq HP3P5m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P3 :: P5 :: nil) (P3 :: P5 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P3 :: P5 :: nil) (P3 :: P5 :: P8 :: nil) 2 2 HP3P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP3P5P8m1. \n\nassert(HP3P5P8m3 : rk(P3 :: P5 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P4P5P8Mtmp : rk(P1 :: P4 :: P5 :: P8 :: nil) <= 3) by (solve_hyps_max HP1P4P5P8eq HP1P4P5P8M3).\n\tassert(HP1P3P4P5P8mtmp : rk(P1 :: P3 :: P4 :: P5 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P3P4P5P8eq HP1P3P4P5P8m4).\n\tassert(HP5P8mtmp : rk(P5 :: P8 :: nil) >= 2) by (solve_hyps_min HP5P8eq HP5P8m2).\n\tassert(Hincl : incl (P5 :: P8 :: nil) (list_inter (P3 :: P5 :: P8 :: nil) (P1 :: P4 :: P5 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P3 :: P4 :: P5 :: P8 :: nil) (P3 :: P5 :: P8 :: P1 :: P4 :: P5 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P3 :: P5 :: P8 :: P1 :: P4 :: P5 :: P8 :: nil) ((P3 :: P5 :: P8 :: nil) ++ (P1 :: P4 :: P5 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P3P4P5P8mtmp;try rewrite HT2 in HP1P3P4P5P8mtmp.\n\tassert(HT := rule_2 (P3 :: P5 :: P8 :: nil) (P1 :: P4 :: P5 :: P8 :: nil) (P5 :: P8 :: nil) 4 2 3 HP1P3P4P5P8mtmp HP5P8mtmp HP1P4P5P8Mtmp Hincl);apply HT.\n}\ntry clear HP3P5P8m2. \n\nassert(HP3P5P6P8m2 : rk(P3 :: P5 :: P6 :: P8 :: nil) >= 2).\n{\n\tassert(HP3P5mtmp : rk(P3 :: P5 :: nil) >= 2) by (solve_hyps_min HP3P5eq HP3P5m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P3 :: P5 :: nil) (P3 :: P5 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P3 :: P5 :: nil) (P3 :: P5 :: P6 :: P8 :: nil) 2 2 HP3P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP3P5M2. try clear HP3P5m2. try clear HP3P5P6P8m1. \n\nassert(HP3P5P6P8M3 : rk(P3 :: P5 :: P6 :: P8 :: nil) <= 3).\n{\n\tassert(HP3P5P6Mtmp : rk(P3 :: P5 :: P6 :: nil) <= 2) by (solve_hyps_max HP3P5P6eq HP3P5P6M2).\n\tassert(HP8Mtmp : rk(P8 :: nil) <= 1) by (solve_hyps_max HP8eq HP8M1).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P3 :: P5 :: P6 :: nil) (P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P3 :: P5 :: P6 :: P8 :: nil) (P3 :: P5 :: P6 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P3 :: P5 :: P6 :: P8 :: nil) ((P3 :: P5 :: P6 :: nil) ++ (P8 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P3 :: P5 :: P6 :: nil) (P8 :: nil) (nil) 2 1 0 HP3P5P6Mtmp HP8Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP3P5P6P8M4. \n\nassert(HP3P5P6P8m3 : rk(P3 :: P5 :: P6 :: P8 :: nil) >= 3).\n{\n\tassert(HP3P5P8mtmp : rk(P3 :: P5 :: P8 :: nil) >= 3) by (solve_hyps_min HP3P5P8eq HP3P5P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P3 :: P5 :: P8 :: nil) (P3 :: P5 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P3 :: P5 :: P8 :: nil) (P3 :: P5 :: P6 :: P8 :: nil) 3 3 HP3P5P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP3P5P8M3. try clear HP3P5P8m3. try clear HP3P5P6P8m2. \n\nassert(HP4P6P8m2 : rk(P4 :: P6 :: P8 :: nil) >= 2).\n{\n\tassert(HP4P6mtmp : rk(P4 :: P6 :: nil) >= 2) by (solve_hyps_min HP4P6eq HP4P6m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P4 :: P6 :: nil) (P4 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P4 :: P6 :: nil) (P4 :: P6 :: P8 :: nil) 2 2 HP4P6mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP4P6P8m1. \n\nassert(HP4P6P8m3 : rk(P4 :: P6 :: P8 :: nil) >= 3).\n{\n\tassert(HP3P5P6P8Mtmp : rk(P3 :: P5 :: P6 :: P8 :: nil) <= 3) by (solve_hyps_max HP3P5P6P8eq HP3P5P6P8M3).\n\tassert(HP3P4P5P6P8mtmp : rk(P3 :: P4 :: P5 :: P6 :: P8 :: nil) >= 4) by (solve_hyps_min HP3P4P5P6P8eq HP3P4P5P6P8m4).\n\tassert(HP6P8mtmp : rk(P6 :: P8 :: nil) >= 2) by (solve_hyps_min HP6P8eq HP6P8m2).\n\tassert(Hincl : incl (P6 :: P8 :: nil) (list_inter (P4 :: P6 :: P8 :: nil) (P3 :: P5 :: P6 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P3 :: P4 :: P5 :: P6 :: P8 :: nil) (P4 :: P6 :: P8 :: P3 :: P5 :: P6 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P4 :: P6 :: P8 :: P3 :: P5 :: P6 :: P8 :: nil) ((P4 :: P6 :: P8 :: nil) ++ (P3 :: P5 :: P6 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP3P4P5P6P8mtmp;try rewrite HT2 in HP3P4P5P6P8mtmp.\n\tassert(HT := rule_2 (P4 :: P6 :: P8 :: nil) (P3 :: P5 :: P6 :: P8 :: nil) (P6 :: P8 :: nil) 4 2 3 HP3P4P5P6P8mtmp HP6P8mtmp HP3P5P6P8Mtmp Hincl);apply HT.\n}\ntry clear HP4P6P8m2. try clear HP3P4P5P6P8M4. try clear HP3P4P5P6P8m4. \n\nassert(HP4P6P8P10m2 : rk(P4 :: P6 :: P8 :: P10 :: nil) >= 2).\n{\n\tassert(HP4P6mtmp : rk(P4 :: P6 :: nil) >= 2) by (solve_hyps_min HP4P6eq HP4P6m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P4 :: P6 :: nil) (P4 :: P6 :: P8 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P4 :: P6 :: nil) (P4 :: P6 :: P8 :: P10 :: nil) 2 2 HP4P6mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP4P6P8P10m1. \n\nassert(HP4P6P8P10m3 : rk(P4 :: P6 :: P8 :: P10 :: nil) >= 3).\n{\n\tassert(HP4P6P8mtmp : rk(P4 :: P6 :: P8 :: nil) >= 3) by (solve_hyps_min HP4P6P8eq HP4P6P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P4 :: P6 :: P8 :: nil) (P4 :: P6 :: P8 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P4 :: P6 :: P8 :: nil) (P4 :: P6 :: P8 :: P10 :: nil) 3 3 HP4P6P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP4P6P8P10m2. \n\nassert(HP4P6P8P10M3 : rk(P4 :: P6 :: P8 :: P10 :: nil) <= 3).\n{\n\tassert(HP2P4P6P8P10Mtmp : rk(P2 :: P4 :: P6 :: P8 :: P10 :: nil) <= 3) by (solve_hyps_max HP2P4P6P8P10eq HP2P4P6P8P10M3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P4 :: P6 :: P8 :: P10 :: nil) (P2 :: P4 :: P6 :: P8 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (P4 :: P6 :: P8 :: P10 :: nil) (P2 :: P4 :: P6 :: P8 :: P10 :: nil) 3 3 HP2P4P6P8P10Mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP4P6P8P10M4. try clear HP2P4P6P8P10M3. try clear HP2P4P6P8P10m3. \n\nassert(HP1P2P3P5P6P8m2 : rk(P1 :: P2 :: P3 :: P5 :: P6 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P5 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P5 :: P6 :: P8 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P5P6P8m1. \n\nassert(HP1P2P3P5P6P8m3 : rk(P1 :: P2 :: P3 :: P5 :: P6 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P2P5mtmp : rk(P1 :: P2 :: P5 :: nil) >= 3) by (solve_hyps_min HP1P2P5eq HP1P2P5m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P5 :: nil) (P1 :: P2 :: P3 :: P5 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P5 :: nil) (P1 :: P2 :: P3 :: P5 :: P6 :: P8 :: nil) 3 3 HP1P2P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P5P6P8m2. \n\nassert(HP1P2P3P5P6P8m4 : rk(P1 :: P2 :: P3 :: P5 :: P6 :: P8 :: nil) >= 4).\n{\n\tassert(HP1P2P5P8mtmp : rk(P1 :: P2 :: P5 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P5P8eq HP1P2P5P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P5 :: P8 :: nil) (P1 :: P2 :: P3 :: P5 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P5 :: P8 :: nil) (P1 :: P2 :: P3 :: P5 :: P6 :: P8 :: nil) 4 4 HP1P2P5P8mtmp Hcomp Hincl);apply HT.\n}\n\n\nassert(HP2P3P8m2 : rk(P2 :: P3 :: P8 :: nil) >= 2).\n{\n\tassert(HP2P3mtmp : rk(P2 :: P3 :: nil) >= 2) by (solve_hyps_min HP2P3eq HP2P3m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P3 :: nil) (P2 :: P3 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P3 :: nil) (P2 :: P3 :: P8 :: nil) 2 2 HP2P3mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P3P8m1. \n\nassert(HP2P3P8m3 : rk(P2 :: P3 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P2P3P12P13Mtmp : rk(P1 :: P2 :: P3 :: P12 :: P13 :: nil) <= 2) by (solve_hyps_max HP1P2P3P12P13eq HP1P2P3P12P13M2).\n\tassert(HP1P2P3P8P12P13mtmp : rk(P1 :: P2 :: P3 :: P8 :: P12 :: P13 :: nil) >= 3) by (solve_hyps_min HP1P2P3P8P12P13eq HP1P2P3P8P12P13m3).\n\tassert(HP2P3mtmp : rk(P2 :: P3 :: nil) >= 2) by (solve_hyps_min HP2P3eq HP2P3m2).\n\tassert(Hincl : incl (P2 :: P3 :: nil) (list_inter (P2 :: P3 :: P8 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P8 :: P12 :: P13 :: nil) (P2 :: P3 :: P8 :: P1 :: P2 :: P3 :: P12 :: P13 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P3 :: P8 :: P1 :: P2 :: P3 :: P12 :: P13 :: nil) ((P2 :: P3 :: P8 :: nil) ++ (P1 :: P2 :: P3 :: P12 :: P13 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P3P8P12P13mtmp;try rewrite HT2 in HP1P2P3P8P12P13mtmp.\n\tassert(HT := rule_2 (P2 :: P3 :: P8 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil) (P2 :: P3 :: nil) 3 2 2 HP1P2P3P8P12P13mtmp HP2P3mtmp HP1P2P3P12P13Mtmp Hincl);apply HT.\n}\ntry clear HP2P3P8m2. try clear HP1P2P3P8P12P13M3. try clear HP1P2P3P8P12P13m3. \n\nassert(HP2P3P5P8m2 : rk(P2 :: P3 :: P5 :: P8 :: nil) >= 2).\n{\n\tassert(HP2P3mtmp : rk(P2 :: P3 :: nil) >= 2) by (solve_hyps_min HP2P3eq HP2P3m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P3 :: nil) (P2 :: P3 :: P5 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P3 :: nil) (P2 :: P3 :: P5 :: P8 :: nil) 2 2 HP2P3mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P3P5P8m1. \n\nassert(HP2P3P5P8m3 : rk(P2 :: P3 :: P5 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P2P3P5Mtmp : rk(P1 :: P2 :: P3 :: P5 :: nil) <= 3) by (solve_hyps_max HP1P2P3P5eq HP1P2P3P5M3).\n\tassert(HP1P2P3P5P8mtmp : rk(P1 :: P2 :: P3 :: P5 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P2P3P5P8eq HP1P2P3P5P8m3).\n\tassert(HP2P3P5mtmp : rk(P2 :: P3 :: P5 :: nil) >= 3) by (solve_hyps_min HP2P3P5eq HP2P3P5m3).\n\tassert(Hincl : incl (P2 :: P3 :: P5 :: nil) (list_inter (P1 :: P2 :: P3 :: P5 :: nil) (P2 :: P3 :: P5 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P5 :: P8 :: nil) (P1 :: P2 :: P3 :: P5 :: P2 :: P3 :: P5 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P3 :: P5 :: P2 :: P3 :: P5 :: P8 :: nil) ((P1 :: P2 :: P3 :: P5 :: nil) ++ (P2 :: P3 :: P5 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P3P5P8mtmp;try rewrite HT2 in HP1P2P3P5P8mtmp.\n\tassert(HT := rule_4 (P1 :: P2 :: P3 :: P5 :: nil) (P2 :: P3 :: P5 :: P8 :: nil) (P2 :: P3 :: P5 :: nil) 3 3 3 HP1P2P3P5P8mtmp HP2P3P5mtmp HP1P2P3P5Mtmp Hincl); apply HT.\n}\ntry clear HP2P3P5P8m2. try clear HP1P2P3P5P8M4. try clear HP1P2P3P5P8m3. \n\nassert(HP2P3P5P8m4 : rk(P2 :: P3 :: P5 :: P8 :: nil) >= 4).\n{\n\tassert(HP1P2P3P8P9Mtmp : rk(P1 :: P2 :: P3 :: P8 :: P9 :: nil) <= 3) by (solve_hyps_max HP1P2P3P8P9eq HP1P2P3P8P9M3).\n\tassert(HP1P2P3P5P8P9mtmp : rk(P1 :: P2 :: P3 :: P5 :: P8 :: P9 :: nil) >= 4) by (solve_hyps_min HP1P2P3P5P8P9eq HP1P2P3P5P8P9m4).\n\tassert(HP2P3P8mtmp : rk(P2 :: P3 :: P8 :: nil) >= 3) by (solve_hyps_min HP2P3P8eq HP2P3P8m3).\n\tassert(Hincl : incl (P2 :: P3 :: P8 :: nil) (list_inter (P2 :: P3 :: P5 :: P8 :: nil) (P1 :: P2 :: P3 :: P8 :: P9 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P5 :: P8 :: P9 :: nil) (P2 :: P3 :: P5 :: P8 :: P1 :: P2 :: P3 :: P8 :: P9 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P3 :: P5 :: P8 :: P1 :: P2 :: P3 :: P8 :: P9 :: nil) ((P2 :: P3 :: P5 :: P8 :: nil) ++ (P1 :: P2 :: P3 :: P8 :: P9 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P3P5P8P9mtmp;try rewrite HT2 in HP1P2P3P5P8P9mtmp.\n\tassert(HT := rule_2 (P2 :: P3 :: P5 :: P8 :: nil) (P1 :: P2 :: P3 :: P8 :: P9 :: nil) (P2 :: P3 :: P8 :: nil) 4 3 3 HP1P2P3P5P8P9mtmp HP2P3P8mtmp HP1P2P3P8P9Mtmp Hincl);apply HT.\n}\ntry clear HP2P3P5P8m3. try clear HP1P2P3P8P9M3. try clear HP1P2P3P8P9m3. try clear HP2P3P8M3. try clear HP2P3P8m3. try clear HP1P2P3P5P8P9M4. try clear HP1P2P3P5P8P9m4. \n\nassert(HP2P3P5P6P8m2 : rk(P2 :: P3 :: P5 :: P6 :: P8 :: nil) >= 2).\n{\n\tassert(HP2P3mtmp : rk(P2 :: P3 :: nil) >= 2) by (solve_hyps_min HP2P3eq HP2P3m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P3 :: nil) (P2 :: P3 :: P5 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P3 :: nil) (P2 :: P3 :: P5 :: P6 :: P8 :: nil) 2 2 HP2P3mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P3P5P6P8m1. \n\nassert(HP2P3P5P6P8m3 : rk(P2 :: P3 :: P5 :: P6 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P2P3P5Mtmp : rk(P1 :: P2 :: P3 :: P5 :: nil) <= 3) by (solve_hyps_max HP1P2P3P5eq HP1P2P3P5M3).\n\tassert(HP1P2P3P5P6P8mtmp : rk(P1 :: P2 :: P3 :: P5 :: P6 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P2P3P5P6P8eq HP1P2P3P5P6P8m3).\n\tassert(HP2P3P5mtmp : rk(P2 :: P3 :: P5 :: nil) >= 3) by (solve_hyps_min HP2P3P5eq HP2P3P5m3).\n\tassert(Hincl : incl (P2 :: P3 :: P5 :: nil) (list_inter (P1 :: P2 :: P3 :: P5 :: nil) (P2 :: P3 :: P5 :: P6 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P5 :: P6 :: P8 :: nil) (P1 :: P2 :: P3 :: P5 :: P2 :: P3 :: P5 :: P6 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P3 :: P5 :: P2 :: P3 :: P5 :: P6 :: P8 :: nil) ((P1 :: P2 :: P3 :: P5 :: nil) ++ (P2 :: P3 :: P5 :: P6 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P3P5P6P8mtmp;try rewrite HT2 in HP1P2P3P5P6P8mtmp.\n\tassert(HT := rule_4 (P1 :: P2 :: P3 :: P5 :: nil) (P2 :: P3 :: P5 :: P6 :: P8 :: nil) (P2 :: P3 :: P5 :: nil) 3 3 3 HP1P2P3P5P6P8mtmp HP2P3P5mtmp HP1P2P3P5Mtmp Hincl); apply HT.\n}\ntry clear HP1P2P3P5M3. try clear HP1P2P3P5m3. try clear HP2P3P5P6P8m2. try clear HP2P3P5M3. try clear HP2P3P5m3. try clear HP1P2P3P5P6P8M4. try clear HP1P2P3P5P6P8m3. \n\nassert(HP2P3P5P6P8m4 : rk(P2 :: P3 :: P5 :: P6 :: P8 :: nil) >= 4).\n{\n\tassert(HP1P2P3P5P8Mtmp : rk(P1 :: P2 :: P3 :: P5 :: P8 :: nil) <= 4) by (solve_hyps_max HP1P2P3P5P8eq HP1P2P3P5P8M4).\n\tassert(HP1P2P3P5P6P8mtmp : rk(P1 :: P2 :: P3 :: P5 :: P6 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P3P5P6P8eq HP1P2P3P5P6P8m4).\n\tassert(HP2P3P5P8mtmp : rk(P2 :: P3 :: P5 :: P8 :: nil) >= 4) by (solve_hyps_min HP2P3P5P8eq HP2P3P5P8m4).\n\tassert(Hincl : incl (P2 :: P3 :: P5 :: P8 :: nil) (list_inter (P1 :: P2 :: P3 :: P5 :: P8 :: nil) (P2 :: P3 :: P5 :: P6 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P5 :: P6 :: P8 :: nil) (P1 :: P2 :: P3 :: P5 :: P8 :: P2 :: P3 :: P5 :: P6 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P3 :: P5 :: P8 :: P2 :: P3 :: P5 :: P6 :: P8 :: nil) ((P1 :: P2 :: P3 :: P5 :: P8 :: nil) ++ (P2 :: P3 :: P5 :: P6 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P3P5P6P8mtmp;try rewrite HT2 in HP1P2P3P5P6P8mtmp.\n\tassert(HT := rule_4 (P1 :: P2 :: P3 :: P5 :: P8 :: nil) (P2 :: P3 :: P5 :: P6 :: P8 :: nil) (P2 :: P3 :: P5 :: P8 :: nil) 4 4 4 HP1P2P3P5P6P8mtmp HP2P3P5P8mtmp HP1P2P3P5P8Mtmp Hincl); apply HT.\n}\ntry clear HP1P2P3P5P8M4. try clear HP1P2P3P5P8m4. try clear HP2P3P5P6P8m3. try clear HP2P3P5P8M4. try clear HP2P3P5P8m4. try clear HP1P2P3P5P6P8M4. try clear HP1P2P3P5P6P8m4. \n\nassert(HP2P6P8m2 : rk(P2 :: P6 :: P8 :: nil) >= 2).\n{\n\tassert(HP2P6mtmp : rk(P2 :: P6 :: nil) >= 2) by (solve_hyps_min HP2P6eq HP2P6m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P6 :: nil) (P2 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P6 :: nil) (P2 :: P6 :: P8 :: nil) 2 2 HP2P6mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P6P8m1. \n\nassert(HP2P6P8m3 : rk(P2 :: P6 :: P8 :: nil) >= 3).\n{\n\tassert(HP3P5P6P8Mtmp : rk(P3 :: P5 :: P6 :: P8 :: nil) <= 3) by (solve_hyps_max HP3P5P6P8eq HP3P5P6P8M3).\n\tassert(HP2P3P5P6P8mtmp : rk(P2 :: P3 :: P5 :: P6 :: P8 :: nil) >= 4) by (solve_hyps_min HP2P3P5P6P8eq HP2P3P5P6P8m4).\n\tassert(HP6P8mtmp : rk(P6 :: P8 :: nil) >= 2) by (solve_hyps_min HP6P8eq HP6P8m2).\n\tassert(Hincl : incl (P6 :: P8 :: nil) (list_inter (P2 :: P6 :: P8 :: nil) (P3 :: P5 :: P6 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P3 :: P5 :: P6 :: P8 :: nil) (P2 :: P6 :: P8 :: P3 :: P5 :: P6 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P6 :: P8 :: P3 :: P5 :: P6 :: P8 :: nil) ((P2 :: P6 :: P8 :: nil) ++ (P3 :: P5 :: P6 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP2P3P5P6P8mtmp;try rewrite HT2 in HP2P3P5P6P8mtmp.\n\tassert(HT := rule_2 (P2 :: P6 :: P8 :: nil) (P3 :: P5 :: P6 :: P8 :: nil) (P6 :: P8 :: nil) 4 2 3 HP2P3P5P6P8mtmp HP6P8mtmp HP3P5P6P8Mtmp Hincl);apply HT.\n}\ntry clear HP2P6P8m2. try clear HP2P3P5P6P8M4. try clear HP2P3P5P6P8m4. \n\nassert(HP2P6P8P10M3 : rk(P2 :: P6 :: P8 :: P10 :: nil) <= 3).\n{\n\tassert(HP6Mtmp : rk(P6 :: nil) <= 1) by (solve_hyps_max HP6eq HP6M1).\n\tassert(HP2P8P10Mtmp : rk(P2 :: P8 :: P10 :: nil) <= 2) by (solve_hyps_max HP2P8P10eq HP2P8P10M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P6 :: nil) (P2 :: P8 :: P10 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P6 :: P8 :: P10 :: nil) (P6 :: P2 :: P8 :: P10 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P6 :: P2 :: P8 :: P10 :: nil) ((P6 :: nil) ++ (P2 :: P8 :: P10 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P6 :: nil) (P2 :: P8 :: P10 :: nil) (nil) 1 2 0 HP6Mtmp HP2P8P10Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP2P6P8P10M4. \n\nassert(HP2P6P8P10m2 : rk(P2 :: P6 :: P8 :: P10 :: nil) >= 2).\n{\n\tassert(HP2P6mtmp : rk(P2 :: P6 :: nil) >= 2) by (solve_hyps_min HP2P6eq HP2P6m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P6 :: nil) (P2 :: P6 :: P8 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P6 :: nil) (P2 :: P6 :: P8 :: P10 :: nil) 2 2 HP2P6mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P6P8P10m1. \n\nassert(HP2P6P8P10m3 : rk(P2 :: P6 :: P8 :: P10 :: nil) >= 3).\n{\n\tassert(HP2P6P8mtmp : rk(P2 :: P6 :: P8 :: nil) >= 3) by (solve_hyps_min HP2P6P8eq HP2P6P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P6 :: P8 :: nil) (P2 :: P6 :: P8 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P6 :: P8 :: nil) (P2 :: P6 :: P8 :: P10 :: nil) 3 3 HP2P6P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P6P8P10m2. \n\nassert(HP6P10m2 : rk(P6 :: P10 :: nil) >= 2).\n{\n\tassert(HP2P8P10Mtmp : rk(P2 :: P8 :: P10 :: nil) <= 2) by (solve_hyps_max HP2P8P10eq HP2P8P10M2).\n\tassert(HP2P6P8P10mtmp : rk(P2 :: P6 :: P8 :: P10 :: nil) >= 3) by (solve_hyps_min HP2P6P8P10eq HP2P6P8P10m3).\n\tassert(HP10mtmp : rk(P10 :: nil) >= 1) by (solve_hyps_min HP10eq HP10m1).\n\tassert(Hincl : incl (P10 :: nil) (list_inter (P6 :: P10 :: nil) (P2 :: P8 :: P10 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P6 :: P8 :: P10 :: nil) (P6 :: P10 :: P2 :: P8 :: P10 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P6 :: P10 :: P2 :: P8 :: P10 :: nil) ((P6 :: P10 :: nil) ++ (P2 :: P8 :: P10 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP2P6P8P10mtmp;try rewrite HT2 in HP2P6P8P10mtmp.\n\tassert(HT := rule_2 (P6 :: P10 :: nil) (P2 :: P8 :: P10 :: nil) (P10 :: nil) 3 1 2 HP2P6P8P10mtmp HP10mtmp HP2P8P10Mtmp Hincl);apply HT.\n}\ntry clear HP6P10m1. try clear HP2P6P8P10M3. try clear HP2P6P8P10m3. \n\nassert(HP4P6P8P10P14m2 : rk(P4 :: P6 :: P8 :: P10 :: P14 :: nil) >= 2).\n{\n\tassert(HP4P6mtmp : rk(P4 :: P6 :: nil) >= 2) by (solve_hyps_min HP4P6eq HP4P6m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P4 :: P6 :: nil) (P4 :: P6 :: P8 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P4 :: P6 :: nil) (P4 :: P6 :: P8 :: P10 :: P14 :: nil) 2 2 HP4P6mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP4P6M2. try clear HP4P6m2. try clear HP4P6P8P10P14m1. \n\nassert(HP4P6P8P10P14m3 : rk(P4 :: P6 :: P8 :: P10 :: P14 :: nil) >= 3).\n{\n\tassert(HP4P6P8mtmp : rk(P4 :: P6 :: P8 :: nil) >= 3) by (solve_hyps_min HP4P6P8eq HP4P6P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P4 :: P6 :: P8 :: nil) (P4 :: P6 :: P8 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P4 :: P6 :: P8 :: nil) (P4 :: P6 :: P8 :: P10 :: P14 :: nil) 3 3 HP4P6P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP4P6P8P10P14m2. \n\nassert(HP4P6P8P10P14M3 : rk(P4 :: P6 :: P8 :: P10 :: P14 :: nil) <= 3).\n{\n\tassert(HP4P6P8P10Mtmp : rk(P4 :: P6 :: P8 :: P10 :: nil) <= 3) by (solve_hyps_max HP4P6P8P10eq HP4P6P8P10M3).\n\tassert(HP6P10P14Mtmp : rk(P6 :: P10 :: P14 :: nil) <= 2) by (solve_hyps_max HP6P10P14eq HP6P10P14M2).\n\tassert(HP6P10mtmp : rk(P6 :: P10 :: nil) >= 2) by (solve_hyps_min HP6P10eq HP6P10m2).\n\tassert(Hincl : incl (P6 :: P10 :: nil) (list_inter (P4 :: P6 :: P8 :: P10 :: nil) (P6 :: P10 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P4 :: P6 :: P8 :: P10 :: P14 :: nil) (P4 :: P6 :: P8 :: P10 :: P6 :: P10 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P4 :: P6 :: P8 :: P10 :: P6 :: P10 :: P14 :: nil) ((P4 :: P6 :: P8 :: P10 :: nil) ++ (P6 :: P10 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P4 :: P6 :: P8 :: P10 :: nil) (P6 :: P10 :: P14 :: nil) (P6 :: P10 :: nil) 3 2 2 HP4P6P8P10Mtmp HP6P10P14Mtmp HP6P10mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP4P6P8P10M3. try clear HP4P6P8P10m3. try clear HP6P10M2. try clear HP6P10m2. try clear HP4P6P8P10P14M4. \n\nassert(HP1P2P4P6P8m2 : rk(P1 :: P2 :: P4 :: P6 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P6 :: P8 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P6P8m1. \n\nassert(HP1P2P4P6P8m3 : rk(P1 :: P2 :: P4 :: P6 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P6 :: P8 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P6P8m2. \n\nassert(HP1P2P4P6P8m4 : rk(P1 :: P2 :: P4 :: P6 :: P8 :: nil) >= 4).\n{\n\tassert(HP1P2P4P8mtmp : rk(P1 :: P2 :: P4 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8eq HP1P2P4P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P6 :: P8 :: nil) 4 4 HP1P2P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P6P8m3. \n\nassert(HP2P4P6P8m2 : rk(P2 :: P4 :: P6 :: P8 :: nil) >= 2).\n{\n\tassert(HP2P4mtmp : rk(P2 :: P4 :: nil) >= 2) by (solve_hyps_min HP2P4eq HP2P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P4 :: nil) (P2 :: P4 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P4 :: nil) (P2 :: P4 :: P6 :: P8 :: nil) 2 2 HP2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P4P6P8m1. \n\nassert(HP2P4P6P8M3 : rk(P2 :: P4 :: P6 :: P8 :: nil) <= 3).\n{\n\tassert(HP2P4P6Mtmp : rk(P2 :: P4 :: P6 :: nil) <= 2) by (solve_hyps_max HP2P4P6eq HP2P4P6M2).\n\tassert(HP8Mtmp : rk(P8 :: nil) <= 1) by (solve_hyps_max HP8eq HP8M1).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P2 :: P4 :: P6 :: nil) (P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P4 :: P6 :: P8 :: nil) (P2 :: P4 :: P6 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P4 :: P6 :: P8 :: nil) ((P2 :: P4 :: P6 :: nil) ++ (P8 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P2 :: P4 :: P6 :: nil) (P8 :: nil) (nil) 2 1 0 HP2P4P6Mtmp HP8Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP2P4P6P8M4. \n\nassert(HP2P4P6P8m3 : rk(P2 :: P4 :: P6 :: P8 :: nil) >= 3).\n{\n\tassert(HP2P4P8mtmp : rk(P2 :: P4 :: P8 :: nil) >= 3) by (solve_hyps_min HP2P4P8eq HP2P4P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P4 :: P8 :: nil) (P2 :: P4 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P4 :: P8 :: nil) (P2 :: P4 :: P6 :: P8 :: nil) 3 3 HP2P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P4P6P8m2. \n\nassert(HP1P4P6P8m2 : rk(P1 :: P4 :: P6 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P4mtmp : rk(P1 :: P4 :: nil) >= 2) by (solve_hyps_min HP1P4eq HP1P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: nil) (P1 :: P4 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: nil) (P1 :: P4 :: P6 :: P8 :: nil) 2 2 HP1P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P6P8m1. \n\nassert(HP1P4P6P8m3 : rk(P1 :: P4 :: P6 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P4P6mtmp : rk(P1 :: P4 :: P6 :: nil) >= 3) by (solve_hyps_min HP1P4P6eq HP1P4P6m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: P6 :: nil) (P1 :: P4 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: P6 :: nil) (P1 :: P4 :: P6 :: P8 :: nil) 3 3 HP1P4P6mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P6P8m2. \n\nassert(HP1P4P6P8m4 : rk(P1 :: P4 :: P6 :: P8 :: nil) >= 4).\n{\n\tassert(HP2P4P6P8Mtmp : rk(P2 :: P4 :: P6 :: P8 :: nil) <= 3) by (solve_hyps_max HP2P4P6P8eq HP2P4P6P8M3).\n\tassert(HP1P2P4P6P8mtmp : rk(P1 :: P2 :: P4 :: P6 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P6P8eq HP1P2P4P6P8m4).\n\tassert(HP4P6P8mtmp : rk(P4 :: P6 :: P8 :: nil) >= 3) by (solve_hyps_min HP4P6P8eq HP4P6P8m3).\n\tassert(Hincl : incl (P4 :: P6 :: P8 :: nil) (list_inter (P1 :: P4 :: P6 :: P8 :: nil) (P2 :: P4 :: P6 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P6 :: P8 :: nil) (P1 :: P4 :: P6 :: P8 :: P2 :: P4 :: P6 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P6 :: P8 :: P2 :: P4 :: P6 :: P8 :: nil) ((P1 :: P4 :: P6 :: P8 :: nil) ++ (P2 :: P4 :: P6 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P6P8mtmp;try rewrite HT2 in HP1P2P4P6P8mtmp.\n\tassert(HT := rule_2 (P1 :: P4 :: P6 :: P8 :: nil) (P2 :: P4 :: P6 :: P8 :: nil) (P4 :: P6 :: P8 :: nil) 4 3 3 HP1P2P4P6P8mtmp HP4P6P8mtmp HP2P4P6P8Mtmp Hincl);apply HT.\n}\ntry clear HP1P4P6P8m3. try clear HP4P6P8M3. try clear HP4P6P8m3. \n\nassert(HP1P4P6P8P10P14m2 : rk(P1 :: P4 :: P6 :: P8 :: P10 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P4mtmp : rk(P1 :: P4 :: nil) >= 2) by (solve_hyps_min HP1P4eq HP1P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: nil) (P1 :: P4 :: P6 :: P8 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: nil) (P1 :: P4 :: P6 :: P8 :: P10 :: P14 :: nil) 2 2 HP1P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P6P8P10P14m1. \n\nassert(HP1P4P6P8P10P14m3 : rk(P1 :: P4 :: P6 :: P8 :: P10 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P4P6mtmp : rk(P1 :: P4 :: P6 :: nil) >= 3) by (solve_hyps_min HP1P4P6eq HP1P4P6m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: P6 :: nil) (P1 :: P4 :: P6 :: P8 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: P6 :: nil) (P1 :: P4 :: P6 :: P8 :: P10 :: P14 :: nil) 3 3 HP1P4P6mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P6M3. try clear HP1P4P6m3. try clear HP1P4P6P8P10P14m2. \n\nassert(HP1P4P6P8P10P14m4 : rk(P1 :: P4 :: P6 :: P8 :: P10 :: P14 :: nil) >= 4).\n{\n\tassert(HP1P4P6P8mtmp : rk(P1 :: P4 :: P6 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P4P6P8eq HP1P4P6P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: P6 :: P8 :: nil) (P1 :: P4 :: P6 :: P8 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: P6 :: P8 :: nil) (P1 :: P4 :: P6 :: P8 :: P10 :: P14 :: nil) 4 4 HP1P4P6P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P6P8M4. try clear HP1P4P6P8m4. try clear HP1P4P6P8P10P14m3. \n\nassert(HP4P8m2 : rk(P4 :: P8 :: nil) >= 2).\n{\n\tassert(HP2Mtmp : rk(P2 :: nil) <= 1) by (solve_hyps_max HP2eq HP2M1).\n\tassert(HP2P4P8mtmp : rk(P2 :: P4 :: P8 :: nil) >= 3) by (solve_hyps_min HP2P4P8eq HP2P4P8m3).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P2 :: nil) (P4 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P4 :: P8 :: nil) (P2 :: P4 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P4 :: P8 :: nil) ((P2 :: nil) ++ (P4 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP2P4P8mtmp;try rewrite HT2 in HP2P4P8mtmp.\n\tassert(HT := rule_4 (P2 :: nil) (P4 :: P8 :: nil) (nil) 3 0 1 HP2P4P8mtmp Hmtmp HP2Mtmp Hincl); apply HT.\n}\ntry clear HP4P8m1. \n\nassert(HP4P8P14m2 : rk(P4 :: P8 :: P14 :: nil) >= 2).\n{\n\tassert(HP4P8mtmp : rk(P4 :: P8 :: nil) >= 2) by (solve_hyps_min HP4P8eq HP4P8m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P4 :: P8 :: nil) (P4 :: P8 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P4 :: P8 :: nil) (P4 :: P8 :: P14 :: nil) 2 2 HP4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP4P8M2. try clear HP4P8m2. try clear HP4P8P14m1. \n\nassert(HP4P8P14M2 : rk(P4 :: P8 :: P14 :: nil) <= 2).\n{\n\tassert(HP1P4P8P14Mtmp : rk(P1 :: P4 :: P8 :: P14 :: nil) <= 3) by (solve_hyps_max HP1P4P8P14eq HP1P4P8P14M3).\n\tassert(HP4P6P8P10P14Mtmp : rk(P4 :: P6 :: P8 :: P10 :: P14 :: nil) <= 3) by (solve_hyps_max HP4P6P8P10P14eq HP4P6P8P10P14M3).\n\tassert(HP1P4P6P8P10P14mtmp : rk(P1 :: P4 :: P6 :: P8 :: P10 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P4P6P8P10P14eq HP1P4P6P8P10P14m4).\n\tassert(Hincl : incl (P4 :: P8 :: P14 :: nil) (list_inter (P1 :: P4 :: P8 :: P14 :: nil) (P4 :: P6 :: P8 :: P10 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P4 :: P6 :: P8 :: P10 :: P14 :: nil) (P1 :: P4 :: P8 :: P14 :: P4 :: P6 :: P8 :: P10 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P8 :: P14 :: P4 :: P6 :: P8 :: P10 :: P14 :: nil) ((P1 :: P4 :: P8 :: P14 :: nil) ++ (P4 :: P6 :: P8 :: P10 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P4P6P8P10P14mtmp;try rewrite HT2 in HP1P4P6P8P10P14mtmp.\n\tassert(HT := rule_3 (P1 :: P4 :: P8 :: P14 :: nil) (P4 :: P6 :: P8 :: P10 :: P14 :: nil) (P4 :: P8 :: P14 :: nil) 3 3 4 HP1P4P8P14Mtmp HP4P6P8P10P14Mtmp HP1P4P6P8P10P14mtmp Hincl);apply HT.\n}\ntry clear HP4P6P8P10P14M3. try clear HP4P6P8P10P14m3. try clear HP4P8P14M3. try clear HP1P4P6P8P10P14M4. try clear HP1P4P6P8P10P14m4. \n\nassert(HP1P2P4P5P7P8m2 : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P5P7P8m1. \n\nassert(HP1P2P4P5P7P8m3 : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P5P7P8m2. \n\nassert(HP1P2P4P5P7P8m4 : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: nil) >= 4).\n{\n\tassert(HP1P2P4P8mtmp : rk(P1 :: P2 :: P4 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8eq HP1P2P4P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: nil) 4 4 HP1P2P4P8mtmp Hcomp Hincl);apply HT.\n}\n\n\nassert(HP2P4P5P7P8m2 : rk(P2 :: P4 :: P5 :: P7 :: P8 :: nil) >= 2).\n{\n\tassert(HP2P4mtmp : rk(P2 :: P4 :: nil) >= 2) by (solve_hyps_min HP2P4eq HP2P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P4 :: nil) (P2 :: P4 :: P5 :: P7 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P4 :: nil) (P2 :: P4 :: P5 :: P7 :: P8 :: nil) 2 2 HP2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P4P5P7P8m1. \n\nassert(HP2P4P5P7P8m3 : rk(P2 :: P4 :: P5 :: P7 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P4P5Mtmp : rk(P1 :: P4 :: P5 :: nil) <= 2) by (solve_hyps_max HP1P4P5eq HP1P4P5M2).\n\tassert(HP1P2P4P5P7P8mtmp : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P2P4P5P7P8eq HP1P2P4P5P7P8m3).\n\tassert(HP4P5mtmp : rk(P4 :: P5 :: nil) >= 2) by (solve_hyps_min HP4P5eq HP4P5m2).\n\tassert(Hincl : incl (P4 :: P5 :: nil) (list_inter (P1 :: P4 :: P5 :: nil) (P2 :: P4 :: P5 :: P7 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: nil) (P1 :: P4 :: P5 :: P2 :: P4 :: P5 :: P7 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P5 :: P2 :: P4 :: P5 :: P7 :: P8 :: nil) ((P1 :: P4 :: P5 :: nil) ++ (P2 :: P4 :: P5 :: P7 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P5P7P8mtmp;try rewrite HT2 in HP1P2P4P5P7P8mtmp.\n\tassert(HT := rule_4 (P1 :: P4 :: P5 :: nil) (P2 :: P4 :: P5 :: P7 :: P8 :: nil) (P4 :: P5 :: nil) 3 2 2 HP1P2P4P5P7P8mtmp HP4P5mtmp HP1P4P5Mtmp Hincl); apply HT.\n}\ntry clear HP2P4P5P7P8m2. try clear HP1P2P4P5P7P8M4. try clear HP1P2P4P5P7P8m3. \n\nassert(HP2P4P5P7P8m4 : rk(P2 :: P4 :: P5 :: P7 :: P8 :: nil) >= 4).\n{\n\tassert(HP1P4P5P8Mtmp : rk(P1 :: P4 :: P5 :: P8 :: nil) <= 3) by (solve_hyps_max HP1P4P5P8eq HP1P4P5P8M3).\n\tassert(HP1P2P4P5P7P8mtmp : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P5P7P8eq HP1P2P4P5P7P8m4).\n\tassert(HP4P5P8mtmp : rk(P4 :: P5 :: P8 :: nil) >= 3) by (solve_hyps_min HP4P5P8eq HP4P5P8m3).\n\tassert(Hincl : incl (P4 :: P5 :: P8 :: nil) (list_inter (P1 :: P4 :: P5 :: P8 :: nil) (P2 :: P4 :: P5 :: P7 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P5 :: P7 :: P8 :: nil) (P1 :: P4 :: P5 :: P8 :: P2 :: P4 :: P5 :: P7 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P5 :: P8 :: P2 :: P4 :: P5 :: P7 :: P8 :: nil) ((P1 :: P4 :: P5 :: P8 :: nil) ++ (P2 :: P4 :: P5 :: P7 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P5P7P8mtmp;try rewrite HT2 in HP1P2P4P5P7P8mtmp.\n\tassert(HT := rule_4 (P1 :: P4 :: P5 :: P8 :: nil) (P2 :: P4 :: P5 :: P7 :: P8 :: nil) (P4 :: P5 :: P8 :: nil) 4 3 3 HP1P2P4P5P7P8mtmp HP4P5P8mtmp HP1P4P5P8Mtmp Hincl); apply HT.\n}\ntry clear HP2P4P5P7P8m3. try clear HP1P2P4P5P7P8M4. try clear HP1P2P4P5P7P8m4. \n\nassert(HP1P2P4P7P8P12m2 : rk(P1 :: P2 :: P4 :: P7 :: P8 :: P12 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P7 :: P8 :: P12 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P7 :: P8 :: P12 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P7P8P12m1. \n\nassert(HP1P2P4P7P8P12m3 : rk(P1 :: P2 :: P4 :: P7 :: P8 :: P12 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P7 :: P8 :: P12 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P7 :: P8 :: P12 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P7P8P12m2. \n\nassert(HP1P2P4P7P8P12m4 : rk(P1 :: P2 :: P4 :: P7 :: P8 :: P12 :: nil) >= 4).\n{\n\tassert(HP1P2P4P8mtmp : rk(P1 :: P2 :: P4 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8eq HP1P2P4P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P7 :: P8 :: P12 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P7 :: P8 :: P12 :: nil) 4 4 HP1P2P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P7P8P12m3. \n\nassert(HP4P7m2 : rk(P4 :: P7 :: nil) >= 2).\n{\n\tassert(HP2P5P7Mtmp : rk(P2 :: P5 :: P7 :: nil) <= 2) by (solve_hyps_max HP2P5P7eq HP2P5P7M2).\n\tassert(HP2P4P5P7mtmp : rk(P2 :: P4 :: P5 :: P7 :: nil) >= 3) by (solve_hyps_min HP2P4P5P7eq HP2P4P5P7m3).\n\tassert(HP7mtmp : rk(P7 :: nil) >= 1) by (solve_hyps_min HP7eq HP7m1).\n\tassert(Hincl : incl (P7 :: nil) (list_inter (P4 :: P7 :: nil) (P2 :: P5 :: P7 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P4 :: P5 :: P7 :: nil) (P4 :: P7 :: P2 :: P5 :: P7 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P4 :: P7 :: P2 :: P5 :: P7 :: nil) ((P4 :: P7 :: nil) ++ (P2 :: P5 :: P7 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP2P4P5P7mtmp;try rewrite HT2 in HP2P4P5P7mtmp.\n\tassert(HT := rule_2 (P4 :: P7 :: nil) (P2 :: P5 :: P7 :: nil) (P7 :: nil) 3 1 2 HP2P4P5P7mtmp HP7mtmp HP2P5P7Mtmp Hincl);apply HT.\n}\ntry clear HP4P7m1. try clear HP2P4P5P7M3. try clear HP2P4P5P7m3. \n\nassert(HP1P2P4P7P12m2 : rk(P1 :: P2 :: P4 :: P7 :: P12 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P7 :: P12 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P7 :: P12 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P7P12m1. \n\nassert(HP1P2P4P7P12m3 : rk(P1 :: P2 :: P4 :: P7 :: P12 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P7 :: P12 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P7 :: P12 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P7P12m2. \n\nassert(HP1P2P4P7P12M3 : rk(P1 :: P2 :: P4 :: P7 :: P12 :: nil) <= 3).\n{\n\tassert(HP1P2P4P7Mtmp : rk(P1 :: P2 :: P4 :: P7 :: nil) <= 3) by (solve_hyps_max HP1P2P4P7eq HP1P2P4P7M3).\n\tassert(HP4P7P12Mtmp : rk(P4 :: P7 :: P12 :: nil) <= 2) by (solve_hyps_max HP4P7P12eq HP4P7P12M2).\n\tassert(HP4P7mtmp : rk(P4 :: P7 :: nil) >= 2) by (solve_hyps_min HP4P7eq HP4P7m2).\n\tassert(Hincl : incl (P4 :: P7 :: nil) (list_inter (P1 :: P2 :: P4 :: P7 :: nil) (P4 :: P7 :: P12 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P7 :: P12 :: nil) (P1 :: P2 :: P4 :: P7 :: P4 :: P7 :: P12 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P4 :: P7 :: P4 :: P7 :: P12 :: nil) ((P1 :: P2 :: P4 :: P7 :: nil) ++ (P4 :: P7 :: P12 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: P2 :: P4 :: P7 :: nil) (P4 :: P7 :: P12 :: nil) (P4 :: P7 :: nil) 3 2 2 HP1P2P4P7Mtmp HP4P7P12Mtmp HP4P7mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P2P4P7M3. try clear HP1P2P4P7m3. try clear HP1P2P4P7P12M4. \n\nassert(HP7P8m2 : rk(P7 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P2P4P7P12Mtmp : rk(P1 :: P2 :: P4 :: P7 :: P12 :: nil) <= 3) by (solve_hyps_max HP1P2P4P7P12eq HP1P2P4P7P12M3).\n\tassert(HP1P2P4P7P8P12mtmp : rk(P1 :: P2 :: P4 :: P7 :: P8 :: P12 :: nil) >= 4) by (solve_hyps_min HP1P2P4P7P8P12eq HP1P2P4P7P8P12m4).\n\tassert(HP7mtmp : rk(P7 :: nil) >= 1) by (solve_hyps_min HP7eq HP7m1).\n\tassert(Hincl : incl (P7 :: nil) (list_inter (P7 :: P8 :: nil) (P1 :: P2 :: P4 :: P7 :: P12 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P7 :: P8 :: P12 :: nil) (P7 :: P8 :: P1 :: P2 :: P4 :: P7 :: P12 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P7 :: P8 :: P1 :: P2 :: P4 :: P7 :: P12 :: nil) ((P7 :: P8 :: nil) ++ (P1 :: P2 :: P4 :: P7 :: P12 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P7P8P12mtmp;try rewrite HT2 in HP1P2P4P7P8P12mtmp.\n\tassert(HT := rule_2 (P7 :: P8 :: nil) (P1 :: P2 :: P4 :: P7 :: P12 :: nil) (P7 :: nil) 4 1 3 HP1P2P4P7P8P12mtmp HP7mtmp HP1P2P4P7P12Mtmp Hincl);apply HT.\n}\ntry clear HP7P8m1. try clear HP1P2P4P7P12M3. try clear HP1P2P4P7P12m3. try clear HP1P2P4P7P8P12M4. try clear HP1P2P4P7P8P12m4. \n\nassert(HP2P5m2 : rk(P2 :: P5 :: nil) >= 2).\n{\n\tassert(HP1Mtmp : rk(P1 :: nil) <= 1) by (solve_hyps_max HP1eq HP1M1).\n\tassert(HP1P2P5mtmp : rk(P1 :: P2 :: P5 :: nil) >= 3) by (solve_hyps_min HP1P2P5eq HP1P2P5m3).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P1 :: nil) (P2 :: P5 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P5 :: nil) (P1 :: P2 :: P5 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P5 :: nil) ((P1 :: nil) ++ (P2 :: P5 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P5mtmp;try rewrite HT2 in HP1P2P5mtmp.\n\tassert(HT := rule_4 (P1 :: nil) (P2 :: P5 :: nil) (nil) 3 0 1 HP1P2P5mtmp Hmtmp HP1Mtmp Hincl); apply HT.\n}\ntry clear HP2P5m1. \n\nassert(HP2P5P8m2 : rk(P2 :: P5 :: P8 :: nil) >= 2).\n{\n\tassert(HP2P5mtmp : rk(P2 :: P5 :: nil) >= 2) by (solve_hyps_min HP2P5eq HP2P5m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P5 :: nil) (P2 :: P5 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P5 :: nil) (P2 :: P5 :: P8 :: nil) 2 2 HP2P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P5P8m1. \n\nassert(HP2P5P8m3 : rk(P2 :: P5 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P4P5P8Mtmp : rk(P1 :: P4 :: P5 :: P8 :: nil) <= 3) by (solve_hyps_max HP1P4P5P8eq HP1P4P5P8M3).\n\tassert(HP1P2P4P5P8mtmp : rk(P1 :: P2 :: P4 :: P5 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P5P8eq HP1P2P4P5P8m4).\n\tassert(HP5P8mtmp : rk(P5 :: P8 :: nil) >= 2) by (solve_hyps_min HP5P8eq HP5P8m2).\n\tassert(Hincl : incl (P5 :: P8 :: nil) (list_inter (P2 :: P5 :: P8 :: nil) (P1 :: P4 :: P5 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P5 :: P8 :: nil) (P2 :: P5 :: P8 :: P1 :: P4 :: P5 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P5 :: P8 :: P1 :: P4 :: P5 :: P8 :: nil) ((P2 :: P5 :: P8 :: nil) ++ (P1 :: P4 :: P5 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P5P8mtmp;try rewrite HT2 in HP1P2P4P5P8mtmp.\n\tassert(HT := rule_2 (P2 :: P5 :: P8 :: nil) (P1 :: P4 :: P5 :: P8 :: nil) (P5 :: P8 :: nil) 4 2 3 HP1P2P4P5P8mtmp HP5P8mtmp HP1P4P5P8Mtmp Hincl);apply HT.\n}\ntry clear HP2P5P8m2. try clear HP1P2P4P5P8M4. try clear HP1P2P4P5P8m4. \n\nassert(HP2P5P7P8m2 : rk(P2 :: P5 :: P7 :: P8 :: nil) >= 2).\n{\n\tassert(HP2P5mtmp : rk(P2 :: P5 :: nil) >= 2) by (solve_hyps_min HP2P5eq HP2P5m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P5 :: nil) (P2 :: P5 :: P7 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P5 :: nil) (P2 :: P5 :: P7 :: P8 :: nil) 2 2 HP2P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P5P7P8m1. \n\nassert(HP2P5P7P8M3 : rk(P2 :: P5 :: P7 :: P8 :: nil) <= 3).\n{\n\tassert(HP2P5P7Mtmp : rk(P2 :: P5 :: P7 :: nil) <= 2) by (solve_hyps_max HP2P5P7eq HP2P5P7M2).\n\tassert(HP8Mtmp : rk(P8 :: nil) <= 1) by (solve_hyps_max HP8eq HP8M1).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P2 :: P5 :: P7 :: nil) (P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P5 :: P7 :: P8 :: nil) (P2 :: P5 :: P7 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P5 :: P7 :: P8 :: nil) ((P2 :: P5 :: P7 :: nil) ++ (P8 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P2 :: P5 :: P7 :: nil) (P8 :: nil) (nil) 2 1 0 HP2P5P7Mtmp HP8Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP2P5P7P8M4. \n\nassert(HP2P5P7P8m3 : rk(P2 :: P5 :: P7 :: P8 :: nil) >= 3).\n{\n\tassert(HP2P5P8mtmp : rk(P2 :: P5 :: P8 :: nil) >= 3) by (solve_hyps_min HP2P5P8eq HP2P5P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P5 :: P8 :: nil) (P2 :: P5 :: P7 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P5 :: P8 :: nil) (P2 :: P5 :: P7 :: P8 :: nil) 3 3 HP2P5P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P5P8M3. try clear HP2P5P8m3. try clear HP2P5P7P8m2. \n\nassert(HP4P7P8m2 : rk(P4 :: P7 :: P8 :: nil) >= 2).\n{\n\tassert(HP4P7mtmp : rk(P4 :: P7 :: nil) >= 2) by (solve_hyps_min HP4P7eq HP4P7m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P4 :: P7 :: nil) (P4 :: P7 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P4 :: P7 :: nil) (P4 :: P7 :: P8 :: nil) 2 2 HP4P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP4P7P8m1. \n\nassert(HP4P7P8m3 : rk(P4 :: P7 :: P8 :: nil) >= 3).\n{\n\tassert(HP2P5P7P8Mtmp : rk(P2 :: P5 :: P7 :: P8 :: nil) <= 3) by (solve_hyps_max HP2P5P7P8eq HP2P5P7P8M3).\n\tassert(HP2P4P5P7P8mtmp : rk(P2 :: P4 :: P5 :: P7 :: P8 :: nil) >= 4) by (solve_hyps_min HP2P4P5P7P8eq HP2P4P5P7P8m4).\n\tassert(HP7P8mtmp : rk(P7 :: P8 :: nil) >= 2) by (solve_hyps_min HP7P8eq HP7P8m2).\n\tassert(Hincl : incl (P7 :: P8 :: nil) (list_inter (P4 :: P7 :: P8 :: nil) (P2 :: P5 :: P7 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P4 :: P5 :: P7 :: P8 :: nil) (P4 :: P7 :: P8 :: P2 :: P5 :: P7 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P4 :: P7 :: P8 :: P2 :: P5 :: P7 :: P8 :: nil) ((P4 :: P7 :: P8 :: nil) ++ (P2 :: P5 :: P7 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP2P4P5P7P8mtmp;try rewrite HT2 in HP2P4P5P7P8mtmp.\n\tassert(HT := rule_2 (P4 :: P7 :: P8 :: nil) (P2 :: P5 :: P7 :: P8 :: nil) (P7 :: P8 :: nil) 4 2 3 HP2P4P5P7P8mtmp HP7P8mtmp HP2P5P7P8Mtmp Hincl);apply HT.\n}\ntry clear HP4P7P8m2. try clear HP2P4P5P7P8M4. try clear HP2P4P5P7P8m4. \n\nassert(HP4P7P8P12P14m2 : rk(P4 :: P7 :: P8 :: P12 :: P14 :: nil) >= 2).\n{\n\tassert(HP4P7mtmp : rk(P4 :: P7 :: nil) >= 2) by (solve_hyps_min HP4P7eq HP4P7m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P4 :: P7 :: nil) (P4 :: P7 :: P8 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P4 :: P7 :: nil) (P4 :: P7 :: P8 :: P12 :: P14 :: nil) 2 2 HP4P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP4P7M2. try clear HP4P7m2. try clear HP4P7P8P12P14m1. \n\nassert(HP4P7P8P12P14m3 : rk(P4 :: P7 :: P8 :: P12 :: P14 :: nil) >= 3).\n{\n\tassert(HP4P7P8mtmp : rk(P4 :: P7 :: P8 :: nil) >= 3) by (solve_hyps_min HP4P7P8eq HP4P7P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P4 :: P7 :: P8 :: nil) (P4 :: P7 :: P8 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P4 :: P7 :: P8 :: nil) (P4 :: P7 :: P8 :: P12 :: P14 :: nil) 3 3 HP4P7P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP4P7P8M3. try clear HP4P7P8m3. try clear HP4P7P8P12P14m2. \n\nassert(HP4P7P8P12P14M3 : rk(P4 :: P7 :: P8 :: P12 :: P14 :: nil) <= 3).\n{\n\tassert(HP4P7P12Mtmp : rk(P4 :: P7 :: P12 :: nil) <= 2) by (solve_hyps_max HP4P7P12eq HP4P7P12M2).\n\tassert(HP4P8P14Mtmp : rk(P4 :: P8 :: P14 :: nil) <= 2) by (solve_hyps_max HP4P8P14eq HP4P8P14M2).\n\tassert(HP4mtmp : rk(P4 :: nil) >= 1) by (solve_hyps_min HP4eq HP4m1).\n\tassert(Hincl : incl (P4 :: nil) (list_inter (P4 :: P7 :: P12 :: nil) (P4 :: P8 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P4 :: P7 :: P8 :: P12 :: P14 :: nil) (P4 :: P7 :: P12 :: P4 :: P8 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P4 :: P7 :: P12 :: P4 :: P8 :: P14 :: nil) ((P4 :: P7 :: P12 :: nil) ++ (P4 :: P8 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P4 :: P7 :: P12 :: nil) (P4 :: P8 :: P14 :: nil) (P4 :: nil) 2 2 1 HP4P7P12Mtmp HP4P8P14Mtmp HP4mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP4P8P14M2. try clear HP4P8P14m2. try clear HP4P7P8P12P14M4. \n\nassert(HP1P2P5P7P8m2 : rk(P1 :: P2 :: P5 :: P7 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P5 :: P7 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P5 :: P7 :: P8 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P5P7P8m1. \n\nassert(HP1P2P5P7P8m3 : rk(P1 :: P2 :: P5 :: P7 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P2P5mtmp : rk(P1 :: P2 :: P5 :: nil) >= 3) by (solve_hyps_min HP1P2P5eq HP1P2P5m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P5 :: nil) (P1 :: P2 :: P5 :: P7 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P5 :: nil) (P1 :: P2 :: P5 :: P7 :: P8 :: nil) 3 3 HP1P2P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P5P7P8m2. \n\nassert(HP1P2P5P7P8m4 : rk(P1 :: P2 :: P5 :: P7 :: P8 :: nil) >= 4).\n{\n\tassert(HP1P2P5P8mtmp : rk(P1 :: P2 :: P5 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P5P8eq HP1P2P5P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P5 :: P8 :: nil) (P1 :: P2 :: P5 :: P7 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P5 :: P8 :: nil) (P1 :: P2 :: P5 :: P7 :: P8 :: nil) 4 4 HP1P2P5P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P5P7P8m3. \n\nassert(HP1P2P6P8m2 : rk(P1 :: P2 :: P6 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P6 :: P8 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P6P8m1. \n\nassert(HP1P2P6P8m3 : rk(P1 :: P2 :: P6 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P2P6mtmp : rk(P1 :: P2 :: P6 :: nil) >= 3) by (solve_hyps_min HP1P2P6eq HP1P2P6m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P6 :: nil) (P1 :: P2 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P6 :: nil) (P1 :: P2 :: P6 :: P8 :: nil) 3 3 HP1P2P6mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P6P8m2. \n\nassert(HP1P2P6P8m4 : rk(P1 :: P2 :: P6 :: P8 :: nil) >= 4).\n{\n\tassert(HP2P4P6P8Mtmp : rk(P2 :: P4 :: P6 :: P8 :: nil) <= 3) by (solve_hyps_max HP2P4P6P8eq HP2P4P6P8M3).\n\tassert(HP1P2P4P6P8mtmp : rk(P1 :: P2 :: P4 :: P6 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P6P8eq HP1P2P4P6P8m4).\n\tassert(HP2P6P8mtmp : rk(P2 :: P6 :: P8 :: nil) >= 3) by (solve_hyps_min HP2P6P8eq HP2P6P8m3).\n\tassert(Hincl : incl (P2 :: P6 :: P8 :: nil) (list_inter (P1 :: P2 :: P6 :: P8 :: nil) (P2 :: P4 :: P6 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P6 :: P8 :: nil) (P1 :: P2 :: P6 :: P8 :: P2 :: P4 :: P6 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P6 :: P8 :: P2 :: P4 :: P6 :: P8 :: nil) ((P1 :: P2 :: P6 :: P8 :: nil) ++ (P2 :: P4 :: P6 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P6P8mtmp;try rewrite HT2 in HP1P2P4P6P8mtmp.\n\tassert(HT := rule_2 (P1 :: P2 :: P6 :: P8 :: nil) (P2 :: P4 :: P6 :: P8 :: nil) (P2 :: P6 :: P8 :: nil) 4 3 3 HP1P2P4P6P8mtmp HP2P6P8mtmp HP2P4P6P8Mtmp Hincl);apply HT.\n}\ntry clear HP1P2P6P8m3. \n\nassert(HP1P2P6P7P8m2 : rk(P1 :: P2 :: P6 :: P7 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P6 :: P7 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P6 :: P7 :: P8 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P6P7P8m1. \n\nassert(HP1P2P6P7P8m3 : rk(P1 :: P2 :: P6 :: P7 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P2P6mtmp : rk(P1 :: P2 :: P6 :: nil) >= 3) by (solve_hyps_min HP1P2P6eq HP1P2P6m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P6 :: nil) (P1 :: P2 :: P6 :: P7 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P6 :: nil) (P1 :: P2 :: P6 :: P7 :: P8 :: nil) 3 3 HP1P2P6mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P6P7P8m2. \n\nassert(HP1P2P6P7P8m4 : rk(P1 :: P2 :: P6 :: P7 :: P8 :: nil) >= 4).\n{\n\tassert(HP1P2P6P8mtmp : rk(P1 :: P2 :: P6 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P6P8eq HP1P2P6P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P6 :: P8 :: nil) (P1 :: P2 :: P6 :: P7 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P6 :: P8 :: nil) (P1 :: P2 :: P6 :: P7 :: P8 :: nil) 4 4 HP1P2P6P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P6P7P8m3. \n\nassert(HP1P6m2 : rk(P1 :: P6 :: nil) >= 2).\n{\n\tassert(HP2P4P6Mtmp : rk(P2 :: P4 :: P6 :: nil) <= 2) by (solve_hyps_max HP2P4P6eq HP2P4P6M2).\n\tassert(HP1P2P4P6mtmp : rk(P1 :: P2 :: P4 :: P6 :: nil) >= 3) by (solve_hyps_min HP1P2P4P6eq HP1P2P4P6m3).\n\tassert(HP6mtmp : rk(P6 :: nil) >= 1) by (solve_hyps_min HP6eq HP6m1).\n\tassert(Hincl : incl (P6 :: nil) (list_inter (P1 :: P6 :: nil) (P2 :: P4 :: P6 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P6 :: nil) (P1 :: P6 :: P2 :: P4 :: P6 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P6 :: P2 :: P4 :: P6 :: nil) ((P1 :: P6 :: nil) ++ (P2 :: P4 :: P6 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P6mtmp;try rewrite HT2 in HP1P2P4P6mtmp.\n\tassert(HT := rule_2 (P1 :: P6 :: nil) (P2 :: P4 :: P6 :: nil) (P6 :: nil) 3 1 2 HP1P2P4P6mtmp HP6mtmp HP2P4P6Mtmp Hincl);apply HT.\n}\ntry clear HP1P6m1. try clear HP1P2P4P6M3. try clear HP1P2P4P6m3. \n\nassert(HP1P6P8m2 : rk(P1 :: P6 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P6mtmp : rk(P1 :: P6 :: nil) >= 2) by (solve_hyps_min HP1P6eq HP1P6m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P6 :: nil) (P1 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P6 :: nil) (P1 :: P6 :: P8 :: nil) 2 2 HP1P6mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P6P8m1. \n\nassert(HP1P6P8m3 : rk(P1 :: P6 :: P8 :: nil) >= 3).\n{\n\tassert(HP2P4P6P8Mtmp : rk(P2 :: P4 :: P6 :: P8 :: nil) <= 3) by (solve_hyps_max HP2P4P6P8eq HP2P4P6P8M3).\n\tassert(HP1P2P4P6P8mtmp : rk(P1 :: P2 :: P4 :: P6 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P6P8eq HP1P2P4P6P8m4).\n\tassert(HP6P8mtmp : rk(P6 :: P8 :: nil) >= 2) by (solve_hyps_min HP6P8eq HP6P8m2).\n\tassert(Hincl : incl (P6 :: P8 :: nil) (list_inter (P1 :: P6 :: P8 :: nil) (P2 :: P4 :: P6 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P6 :: P8 :: nil) (P1 :: P6 :: P8 :: P2 :: P4 :: P6 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P6 :: P8 :: P2 :: P4 :: P6 :: P8 :: nil) ((P1 :: P6 :: P8 :: nil) ++ (P2 :: P4 :: P6 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P6P8mtmp;try rewrite HT2 in HP1P2P4P6P8mtmp.\n\tassert(HT := rule_2 (P1 :: P6 :: P8 :: nil) (P2 :: P4 :: P6 :: P8 :: nil) (P6 :: P8 :: nil) 4 2 3 HP1P2P4P6P8mtmp HP6P8mtmp HP2P4P6P8Mtmp Hincl);apply HT.\n}\ntry clear HP1P6P8m2. try clear HP1P2P4P6P8M4. try clear HP1P2P4P6P8m4. \n\nassert(HP1P6P7P8m2 : rk(P1 :: P6 :: P7 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P6mtmp : rk(P1 :: P6 :: nil) >= 2) by (solve_hyps_min HP1P6eq HP1P6m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P6 :: nil) (P1 :: P6 :: P7 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P6 :: nil) (P1 :: P6 :: P7 :: P8 :: nil) 2 2 HP1P6mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P6P7P8m1. \n\nassert(HP1P6P7P8M3 : rk(P1 :: P6 :: P7 :: P8 :: nil) <= 3).\n{\n\tassert(HP1P6P7Mtmp : rk(P1 :: P6 :: P7 :: nil) <= 2) by (solve_hyps_max HP1P6P7eq HP1P6P7M2).\n\tassert(HP8Mtmp : rk(P8 :: nil) <= 1) by (solve_hyps_max HP8eq HP8M1).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P1 :: P6 :: P7 :: nil) (P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P6 :: P7 :: P8 :: nil) (P1 :: P6 :: P7 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P6 :: P7 :: P8 :: nil) ((P1 :: P6 :: P7 :: nil) ++ (P8 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: P6 :: P7 :: nil) (P8 :: nil) (nil) 2 1 0 HP1P6P7Mtmp HP8Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P6P7P8M4. \n\nassert(HP1P6P7P8m3 : rk(P1 :: P6 :: P7 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P6P8mtmp : rk(P1 :: P6 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P6P8eq HP1P6P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P6 :: P8 :: nil) (P1 :: P6 :: P7 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P6 :: P8 :: nil) (P1 :: P6 :: P7 :: P8 :: nil) 3 3 HP1P6P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P6P7P8m2. \n\nassert(HP2P7P8m2 : rk(P2 :: P7 :: P8 :: nil) >= 2).\n{\n\tassert(HP2P7mtmp : rk(P2 :: P7 :: nil) >= 2) by (solve_hyps_min HP2P7eq HP2P7m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P7 :: nil) (P2 :: P7 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P7 :: nil) (P2 :: P7 :: P8 :: nil) 2 2 HP2P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P7P8m1. \n\nassert(HP2P7P8m3 : rk(P2 :: P7 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P6P7P8Mtmp : rk(P1 :: P6 :: P7 :: P8 :: nil) <= 3) by (solve_hyps_max HP1P6P7P8eq HP1P6P7P8M3).\n\tassert(HP1P2P6P7P8mtmp : rk(P1 :: P2 :: P6 :: P7 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P6P7P8eq HP1P2P6P7P8m4).\n\tassert(HP7P8mtmp : rk(P7 :: P8 :: nil) >= 2) by (solve_hyps_min HP7P8eq HP7P8m2).\n\tassert(Hincl : incl (P7 :: P8 :: nil) (list_inter (P2 :: P7 :: P8 :: nil) (P1 :: P6 :: P7 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P6 :: P7 :: P8 :: nil) (P2 :: P7 :: P8 :: P1 :: P6 :: P7 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P7 :: P8 :: P1 :: P6 :: P7 :: P8 :: nil) ((P2 :: P7 :: P8 :: nil) ++ (P1 :: P6 :: P7 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P6P7P8mtmp;try rewrite HT2 in HP1P2P6P7P8mtmp.\n\tassert(HT := rule_2 (P2 :: P7 :: P8 :: nil) (P1 :: P6 :: P7 :: P8 :: nil) (P7 :: P8 :: nil) 4 2 3 HP1P2P6P7P8mtmp HP7P8mtmp HP1P6P7P8Mtmp Hincl);apply HT.\n}\ntry clear HP2P7P8m2. try clear HP1P2P6P7P8M4. try clear HP1P2P6P7P8m4. \n\nassert(HP1P2P7m2 : rk(P1 :: P2 :: P7 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P7 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P7 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7m1. \n\nassert(HP1P2P7m3 : rk(P1 :: P2 :: P7 :: nil) >= 3).\n{\n\tassert(HP2P5P7Mtmp : rk(P2 :: P5 :: P7 :: nil) <= 2) by (solve_hyps_max HP2P5P7eq HP2P5P7M2).\n\tassert(HP1P2P5P7mtmp : rk(P1 :: P2 :: P5 :: P7 :: nil) >= 3) by (solve_hyps_min HP1P2P5P7eq HP1P2P5P7m3).\n\tassert(HP2P7mtmp : rk(P2 :: P7 :: nil) >= 2) by (solve_hyps_min HP2P7eq HP2P7m2).\n\tassert(Hincl : incl (P2 :: P7 :: nil) (list_inter (P1 :: P2 :: P7 :: nil) (P2 :: P5 :: P7 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P5 :: P7 :: nil) (P1 :: P2 :: P7 :: P2 :: P5 :: P7 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P7 :: P2 :: P5 :: P7 :: nil) ((P1 :: P2 :: P7 :: nil) ++ (P2 :: P5 :: P7 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P5P7mtmp;try rewrite HT2 in HP1P2P5P7mtmp.\n\tassert(HT := rule_2 (P1 :: P2 :: P7 :: nil) (P2 :: P5 :: P7 :: nil) (P2 :: P7 :: nil) 3 2 2 HP1P2P5P7mtmp HP2P7mtmp HP2P5P7Mtmp Hincl);apply HT.\n}\ntry clear HP1P2P7m2. \n\nassert(HP1P2P7P8m2 : rk(P1 :: P2 :: P7 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P7 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P7 :: P8 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P8m1. \n\nassert(HP1P2P7P8m3 : rk(P1 :: P2 :: P7 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P2P7mtmp : rk(P1 :: P2 :: P7 :: nil) >= 3) by (solve_hyps_min HP1P2P7eq HP1P2P7m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P7 :: nil) (P1 :: P2 :: P7 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P7 :: nil) (P1 :: P2 :: P7 :: P8 :: nil) 3 3 HP1P2P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P8m2. \n\nassert(HP1P2P7P8m4 : rk(P1 :: P2 :: P7 :: P8 :: nil) >= 4).\n{\n\tassert(HP2P5P7P8Mtmp : rk(P2 :: P5 :: P7 :: P8 :: nil) <= 3) by (solve_hyps_max HP2P5P7P8eq HP2P5P7P8M3).\n\tassert(HP1P2P5P7P8mtmp : rk(P1 :: P2 :: P5 :: P7 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P5P7P8eq HP1P2P5P7P8m4).\n\tassert(HP2P7P8mtmp : rk(P2 :: P7 :: P8 :: nil) >= 3) by (solve_hyps_min HP2P7P8eq HP2P7P8m3).\n\tassert(Hincl : incl (P2 :: P7 :: P8 :: nil) (list_inter (P1 :: P2 :: P7 :: P8 :: nil) (P2 :: P5 :: P7 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P5 :: P7 :: P8 :: nil) (P1 :: P2 :: P7 :: P8 :: P2 :: P5 :: P7 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P7 :: P8 :: P2 :: P5 :: P7 :: P8 :: nil) ((P1 :: P2 :: P7 :: P8 :: nil) ++ (P2 :: P5 :: P7 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P5P7P8mtmp;try rewrite HT2 in HP1P2P5P7P8mtmp.\n\tassert(HT := rule_2 (P1 :: P2 :: P7 :: P8 :: nil) (P2 :: P5 :: P7 :: P8 :: nil) (P2 :: P7 :: P8 :: nil) 4 3 3 HP1P2P5P7P8mtmp HP2P7P8mtmp HP2P5P7P8Mtmp Hincl);apply HT.\n}\ntry clear HP1P2P7P8m3. try clear HP2P7P8M3. try clear HP2P7P8m3. \n\nassert(HP1P2P7P8P12P14m2 : rk(P1 :: P2 :: P7 :: P8 :: P12 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P7 :: P8 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P7 :: P8 :: P12 :: P14 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P8P12P14m1. \n\nassert(HP1P2P7P8P12P14m3 : rk(P1 :: P2 :: P7 :: P8 :: P12 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P2P7mtmp : rk(P1 :: P2 :: P7 :: nil) >= 3) by (solve_hyps_min HP1P2P7eq HP1P2P7m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P7 :: nil) (P1 :: P2 :: P7 :: P8 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P7 :: nil) (P1 :: P2 :: P7 :: P8 :: P12 :: P14 :: nil) 3 3 HP1P2P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P8P12P14m2. \n\nassert(HP1P2P7P8P12P14m4 : rk(P1 :: P2 :: P7 :: P8 :: P12 :: P14 :: nil) >= 4).\n{\n\tassert(HP1P2P7P8mtmp : rk(P1 :: P2 :: P7 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P7P8eq HP1P2P7P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P7 :: P8 :: nil) (P1 :: P2 :: P7 :: P8 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P7 :: P8 :: nil) (P1 :: P2 :: P7 :: P8 :: P12 :: P14 :: nil) 4 4 HP1P2P7P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P8P12P14m3. \n\nassert(HP7P8P12P14m2 : rk(P7 :: P8 :: P12 :: P14 :: nil) >= 2).\n{\n\tassert(HP7P8mtmp : rk(P7 :: P8 :: nil) >= 2) by (solve_hyps_min HP7P8eq HP7P8m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P7 :: P8 :: nil) (P7 :: P8 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P7 :: P8 :: nil) (P7 :: P8 :: P12 :: P14 :: nil) 2 2 HP7P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP7P8P12P14m1. \n\nassert(HP7P8P12P14m3 : rk(P7 :: P8 :: P12 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P2P12Mtmp : rk(P1 :: P2 :: P12 :: nil) <= 2) by (solve_hyps_max HP1P2P12eq HP1P2P12M2).\n\tassert(HP1P2P7P8P12P14mtmp : rk(P1 :: P2 :: P7 :: P8 :: P12 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P2P7P8P12P14eq HP1P2P7P8P12P14m4).\n\tassert(HP12mtmp : rk(P12 :: nil) >= 1) by (solve_hyps_min HP12eq HP12m1).\n\tassert(Hincl : incl (P12 :: nil) (list_inter (P1 :: P2 :: P12 :: nil) (P7 :: P8 :: P12 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P7 :: P8 :: P12 :: P14 :: nil) (P1 :: P2 :: P12 :: P7 :: P8 :: P12 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P12 :: P7 :: P8 :: P12 :: P14 :: nil) ((P1 :: P2 :: P12 :: nil) ++ (P7 :: P8 :: P12 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P7P8P12P14mtmp;try rewrite HT2 in HP1P2P7P8P12P14mtmp.\n\tassert(HT := rule_4 (P1 :: P2 :: P12 :: nil) (P7 :: P8 :: P12 :: P14 :: nil) (P12 :: nil) 4 1 2 HP1P2P7P8P12P14mtmp HP12mtmp HP1P2P12Mtmp Hincl); apply HT.\n}\ntry clear HP7P8P12P14m2. try clear HP1P2P7P8P12P14M4. try clear HP1P2P7P8P12P14m4. \n\nassert(HP7P8P12P14M3 : rk(P7 :: P8 :: P12 :: P14 :: nil) <= 3).\n{\n\tassert(HP4P7P8P12P14Mtmp : rk(P4 :: P7 :: P8 :: P12 :: P14 :: nil) <= 3) by (solve_hyps_max HP4P7P8P12P14eq HP4P7P8P12P14M3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P7 :: P8 :: P12 :: P14 :: nil) (P4 :: P7 :: P8 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (P7 :: P8 :: P12 :: P14 :: nil) (P4 :: P7 :: P8 :: P12 :: P14 :: nil) 3 3 HP4P7P8P12P14Mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP7P8P12P14M4. try clear HP4P7P8P12P14M3. try clear HP4P7P8P12P14m3. \n\nassert(HP1P2P5P8P9m2 : rk(P1 :: P2 :: P5 :: P8 :: P9 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P5 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P5 :: P8 :: P9 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P5P8P9m1. \n\nassert(HP1P2P5P8P9m3 : rk(P1 :: P2 :: P5 :: P8 :: P9 :: nil) >= 3).\n{\n\tassert(HP1P2P5mtmp : rk(P1 :: P2 :: P5 :: nil) >= 3) by (solve_hyps_min HP1P2P5eq HP1P2P5m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P5 :: nil) (P1 :: P2 :: P5 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P5 :: nil) (P1 :: P2 :: P5 :: P8 :: P9 :: nil) 3 3 HP1P2P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P5P8P9m2. \n\nassert(HP1P2P5P8P9m4 : rk(P1 :: P2 :: P5 :: P8 :: P9 :: nil) >= 4).\n{\n\tassert(HP1P2P5P8mtmp : rk(P1 :: P2 :: P5 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P5P8eq HP1P2P5P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P5 :: P8 :: nil) (P1 :: P2 :: P5 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P5 :: P8 :: nil) (P1 :: P2 :: P5 :: P8 :: P9 :: nil) 4 4 HP1P2P5P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P5P8P9m3. \n\nassert(HP2P5P9m2 : rk(P2 :: P5 :: P9 :: nil) >= 2).\n{\n\tassert(HP2P5mtmp : rk(P2 :: P5 :: nil) >= 2) by (solve_hyps_min HP2P5eq HP2P5m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P5 :: nil) (P2 :: P5 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P5 :: nil) (P2 :: P5 :: P9 :: nil) 2 2 HP2P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P5P9m1. \n\nassert(HP2P5P9m3 : rk(P2 :: P5 :: P9 :: nil) >= 3).\n{\n\tassert(HP1P8P9Mtmp : rk(P1 :: P8 :: P9 :: nil) <= 2) by (solve_hyps_max HP1P8P9eq HP1P8P9M2).\n\tassert(HP1P2P5P8P9mtmp : rk(P1 :: P2 :: P5 :: P8 :: P9 :: nil) >= 4) by (solve_hyps_min HP1P2P5P8P9eq HP1P2P5P8P9m4).\n\tassert(HP9mtmp : rk(P9 :: nil) >= 1) by (solve_hyps_min HP9eq HP9m1).\n\tassert(Hincl : incl (P9 :: nil) (list_inter (P2 :: P5 :: P9 :: nil) (P1 :: P8 :: P9 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P5 :: P8 :: P9 :: nil) (P2 :: P5 :: P9 :: P1 :: P8 :: P9 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P5 :: P9 :: P1 :: P8 :: P9 :: nil) ((P2 :: P5 :: P9 :: nil) ++ (P1 :: P8 :: P9 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P5P8P9mtmp;try rewrite HT2 in HP1P2P5P8P9mtmp.\n\tassert(HT := rule_2 (P2 :: P5 :: P9 :: nil) (P1 :: P8 :: P9 :: nil) (P9 :: nil) 4 1 2 HP1P2P5P8P9mtmp HP9mtmp HP1P8P9Mtmp Hincl);apply HT.\n}\ntry clear HP2P5P9m2. try clear HP1P2P5P8P9M4. try clear HP1P2P5P8P9m4. \n\nassert(HP2P5P7P9P14m2 : rk(P2 :: P5 :: P7 :: P9 :: P14 :: nil) >= 2).\n{\n\tassert(HP2P5mtmp : rk(P2 :: P5 :: nil) >= 2) by (solve_hyps_min HP2P5eq HP2P5m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P5 :: nil) (P2 :: P5 :: P7 :: P9 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P5 :: nil) (P2 :: P5 :: P7 :: P9 :: P14 :: nil) 2 2 HP2P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P5P7P9P14m1. \n\nassert(HP2P5P7P9P14M3 : rk(P2 :: P5 :: P7 :: P9 :: P14 :: nil) <= 3).\n{\n\tassert(HP2P5P7Mtmp : rk(P2 :: P5 :: P7 :: nil) <= 2) by (solve_hyps_max HP2P5P7eq HP2P5P7M2).\n\tassert(HP5P9P14Mtmp : rk(P5 :: P9 :: P14 :: nil) <= 2) by (solve_hyps_max HP5P9P14eq HP5P9P14M2).\n\tassert(HP5mtmp : rk(P5 :: nil) >= 1) by (solve_hyps_min HP5eq HP5m1).\n\tassert(Hincl : incl (P5 :: nil) (list_inter (P2 :: P5 :: P7 :: nil) (P5 :: P9 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P5 :: P7 :: P9 :: P14 :: nil) (P2 :: P5 :: P7 :: P5 :: P9 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P5 :: P7 :: P5 :: P9 :: P14 :: nil) ((P2 :: P5 :: P7 :: nil) ++ (P5 :: P9 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P2 :: P5 :: P7 :: nil) (P5 :: P9 :: P14 :: nil) (P5 :: nil) 2 2 1 HP2P5P7Mtmp HP5P9P14Mtmp HP5mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP2P5P7P9P14M4. \n\nassert(HP2P5P7P9P14m3 : rk(P2 :: P5 :: P7 :: P9 :: P14 :: nil) >= 3).\n{\n\tassert(HP2P5P9mtmp : rk(P2 :: P5 :: P9 :: nil) >= 3) by (solve_hyps_min HP2P5P9eq HP2P5P9m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P5 :: P9 :: nil) (P2 :: P5 :: P7 :: P9 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P5 :: P9 :: nil) (P2 :: P5 :: P7 :: P9 :: P14 :: nil) 3 3 HP2P5P9mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P5P7P9P14m2. \n\nassert(HP1P2P7P8P9m2 : rk(P1 :: P2 :: P7 :: P8 :: P9 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P7 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P7 :: P8 :: P9 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P8P9m1. \n\nassert(HP1P2P7P8P9m3 : rk(P1 :: P2 :: P7 :: P8 :: P9 :: nil) >= 3).\n{\n\tassert(HP1P2P7mtmp : rk(P1 :: P2 :: P7 :: nil) >= 3) by (solve_hyps_min HP1P2P7eq HP1P2P7m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P7 :: nil) (P1 :: P2 :: P7 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P7 :: nil) (P1 :: P2 :: P7 :: P8 :: P9 :: nil) 3 3 HP1P2P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P8P9m2. \n\nassert(HP1P2P7P8P9m4 : rk(P1 :: P2 :: P7 :: P8 :: P9 :: nil) >= 4).\n{\n\tassert(HP1P2P7P8mtmp : rk(P1 :: P2 :: P7 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P7P8eq HP1P2P7P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P7 :: P8 :: nil) (P1 :: P2 :: P7 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P7 :: P8 :: nil) (P1 :: P2 :: P7 :: P8 :: P9 :: nil) 4 4 HP1P2P7P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P8P9m3. \n\nassert(HP2P7P9m2 : rk(P2 :: P7 :: P9 :: nil) >= 2).\n{\n\tassert(HP2P7mtmp : rk(P2 :: P7 :: nil) >= 2) by (solve_hyps_min HP2P7eq HP2P7m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P7 :: nil) (P2 :: P7 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P7 :: nil) (P2 :: P7 :: P9 :: nil) 2 2 HP2P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P7P9m1. \n\nassert(HP2P7P9m3 : rk(P2 :: P7 :: P9 :: nil) >= 3).\n{\n\tassert(HP1P8P9Mtmp : rk(P1 :: P8 :: P9 :: nil) <= 2) by (solve_hyps_max HP1P8P9eq HP1P8P9M2).\n\tassert(HP1P2P7P8P9mtmp : rk(P1 :: P2 :: P7 :: P8 :: P9 :: nil) >= 4) by (solve_hyps_min HP1P2P7P8P9eq HP1P2P7P8P9m4).\n\tassert(HP9mtmp : rk(P9 :: nil) >= 1) by (solve_hyps_min HP9eq HP9m1).\n\tassert(Hincl : incl (P9 :: nil) (list_inter (P2 :: P7 :: P9 :: nil) (P1 :: P8 :: P9 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P7 :: P8 :: P9 :: nil) (P2 :: P7 :: P9 :: P1 :: P8 :: P9 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P7 :: P9 :: P1 :: P8 :: P9 :: nil) ((P2 :: P7 :: P9 :: nil) ++ (P1 :: P8 :: P9 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P7P8P9mtmp;try rewrite HT2 in HP1P2P7P8P9mtmp.\n\tassert(HT := rule_2 (P2 :: P7 :: P9 :: nil) (P1 :: P8 :: P9 :: nil) (P9 :: nil) 4 1 2 HP1P2P7P8P9mtmp HP9mtmp HP1P8P9Mtmp Hincl);apply HT.\n}\ntry clear HP2P7P9m2. \n\nassert(HP2P7P9P14m2 : rk(P2 :: P7 :: P9 :: P14 :: nil) >= 2).\n{\n\tassert(HP2P7mtmp : rk(P2 :: P7 :: nil) >= 2) by (solve_hyps_min HP2P7eq HP2P7m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P7 :: nil) (P2 :: P7 :: P9 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P7 :: nil) (P2 :: P7 :: P9 :: P14 :: nil) 2 2 HP2P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P7P9P14m1. \n\nassert(HP2P7P9P14m3 : rk(P2 :: P7 :: P9 :: P14 :: nil) >= 3).\n{\n\tassert(HP2P7P9mtmp : rk(P2 :: P7 :: P9 :: nil) >= 3) by (solve_hyps_min HP2P7P9eq HP2P7P9m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P7 :: P9 :: nil) (P2 :: P7 :: P9 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P7 :: P9 :: nil) (P2 :: P7 :: P9 :: P14 :: nil) 3 3 HP2P7P9mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P7P9P14m2. \n\nassert(HP2P7P9P14M3 : rk(P2 :: P7 :: P9 :: P14 :: nil) <= 3).\n{\n\tassert(HP2P5P7P9P14Mtmp : rk(P2 :: P5 :: P7 :: P9 :: P14 :: nil) <= 3) by (solve_hyps_max HP2P5P7P9P14eq HP2P5P7P9P14M3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P7 :: P9 :: P14 :: nil) (P2 :: P5 :: P7 :: P9 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (P2 :: P7 :: P9 :: P14 :: nil) (P2 :: P5 :: P7 :: P9 :: P14 :: nil) 3 3 HP2P5P7P9P14Mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P7P9P14M4. try clear HP2P5P7P9P14M3. try clear HP2P5P7P9P14m3. \n\nassert(HP1P2P4P8P9P11P14m2 : rk(P1 :: P2 :: P4 :: P8 :: P9 :: P11 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P8 :: P9 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P8 :: P9 :: P11 :: P14 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P8P9P11P14m1. \n\nassert(HP1P2P4P8P9P11P14m3 : rk(P1 :: P2 :: P4 :: P8 :: P9 :: P11 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P8 :: P9 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P8 :: P9 :: P11 :: P14 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P8P9P11P14m2. \n\nassert(HP1P2P4P8P9P11P14m4 : rk(P1 :: P2 :: P4 :: P8 :: P9 :: P11 :: P14 :: nil) >= 4).\n{\n\tassert(HP1P2P4P8mtmp : rk(P1 :: P2 :: P4 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8eq HP1P2P4P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P8 :: P9 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P8 :: P9 :: P11 :: P14 :: nil) 4 4 HP1P2P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P8P9P11P14m3. \n\nassert(HP8P9m2 : rk(P8 :: P9 :: nil) >= 2).\n{\n\tassert(HP10Mtmp : rk(P10 :: nil) <= 1) by (solve_hyps_max HP10eq HP10M1).\n\tassert(HP8P9P10mtmp : rk(P8 :: P9 :: P10 :: nil) >= 3) by (solve_hyps_min HP8P9P10eq HP8P9P10m3).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P8 :: P9 :: nil) (P10 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P8 :: P9 :: P10 :: nil) (P8 :: P9 :: P10 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P8 :: P9 :: P10 :: nil) ((P8 :: P9 :: nil) ++ (P10 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP8P9P10mtmp;try rewrite HT2 in HP8P9P10mtmp.\n\tassert(HT := rule_2 (P8 :: P9 :: nil) (P10 :: nil) (nil) 3 0 1 HP8P9P10mtmp Hmtmp HP10Mtmp Hincl);apply HT.\n}\ntry clear HP8P9m1. \n\nassert(HP2P4P8P9P11P14m2 : rk(P2 :: P4 :: P8 :: P9 :: P11 :: P14 :: nil) >= 2).\n{\n\tassert(HP2P4mtmp : rk(P2 :: P4 :: nil) >= 2) by (solve_hyps_min HP2P4eq HP2P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P4 :: nil) (P2 :: P4 :: P8 :: P9 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P4 :: nil) (P2 :: P4 :: P8 :: P9 :: P11 :: P14 :: nil) 2 2 HP2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P4P8P9P11P14m1. \n\nassert(HP2P4P8P9P11P14m3 : rk(P2 :: P4 :: P8 :: P9 :: P11 :: P14 :: nil) >= 3).\n{\n\tassert(HP2P4P8mtmp : rk(P2 :: P4 :: P8 :: nil) >= 3) by (solve_hyps_min HP2P4P8eq HP2P4P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P4 :: P8 :: nil) (P2 :: P4 :: P8 :: P9 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P4 :: P8 :: nil) (P2 :: P4 :: P8 :: P9 :: P11 :: P14 :: nil) 3 3 HP2P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P4P8P9P11P14m2. \n\nassert(HP2P4P8P9P11P14m4 : rk(P2 :: P4 :: P8 :: P9 :: P11 :: P14 :: nil) >= 4).\n{\n\tassert(HP1P8P9Mtmp : rk(P1 :: P8 :: P9 :: nil) <= 2) by (solve_hyps_max HP1P8P9eq HP1P8P9M2).\n\tassert(HP1P2P4P8P9P11P14mtmp : rk(P1 :: P2 :: P4 :: P8 :: P9 :: P11 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8P9P11P14eq HP1P2P4P8P9P11P14m4).\n\tassert(HP8P9mtmp : rk(P8 :: P9 :: nil) >= 2) by (solve_hyps_min HP8P9eq HP8P9m2).\n\tassert(Hincl : incl (P8 :: P9 :: nil) (list_inter (P1 :: P8 :: P9 :: nil) (P2 :: P4 :: P8 :: P9 :: P11 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P8 :: P9 :: P11 :: P14 :: nil) (P1 :: P8 :: P9 :: P2 :: P4 :: P8 :: P9 :: P11 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P8 :: P9 :: P2 :: P4 :: P8 :: P9 :: P11 :: P14 :: nil) ((P1 :: P8 :: P9 :: nil) ++ (P2 :: P4 :: P8 :: P9 :: P11 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P8P9P11P14mtmp;try rewrite HT2 in HP1P2P4P8P9P11P14mtmp.\n\tassert(HT := rule_4 (P1 :: P8 :: P9 :: nil) (P2 :: P4 :: P8 :: P9 :: P11 :: P14 :: nil) (P8 :: P9 :: nil) 4 2 2 HP1P2P4P8P9P11P14mtmp HP8P9mtmp HP1P8P9Mtmp Hincl); apply HT.\n}\ntry clear HP2P4P8P9P11P14m3. try clear HP1P2P4P8P9P11P14M4. try clear HP1P2P4P8P9P11P14m4. \n\nassert(HP2P5P9P14M3 : rk(P2 :: P5 :: P9 :: P14 :: nil) <= 3).\n{\n\tassert(HP2Mtmp : rk(P2 :: nil) <= 1) by (solve_hyps_max HP2eq HP2M1).\n\tassert(HP5P9P14Mtmp : rk(P5 :: P9 :: P14 :: nil) <= 2) by (solve_hyps_max HP5P9P14eq HP5P9P14M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P2 :: nil) (P5 :: P9 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P5 :: P9 :: P14 :: nil) (P2 :: P5 :: P9 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P5 :: P9 :: P14 :: nil) ((P2 :: nil) ++ (P5 :: P9 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P2 :: nil) (P5 :: P9 :: P14 :: nil) (nil) 1 2 0 HP2Mtmp HP5P9P14Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP2P5P9P14M4. \n\nassert(HP2P5P9P14m2 : rk(P2 :: P5 :: P9 :: P14 :: nil) >= 2).\n{\n\tassert(HP2P5mtmp : rk(P2 :: P5 :: nil) >= 2) by (solve_hyps_min HP2P5eq HP2P5m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P5 :: nil) (P2 :: P5 :: P9 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P5 :: nil) (P2 :: P5 :: P9 :: P14 :: nil) 2 2 HP2P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P5P9P14m1. \n\nassert(HP2P5P9P14m3 : rk(P2 :: P5 :: P9 :: P14 :: nil) >= 3).\n{\n\tassert(HP2P5P9mtmp : rk(P2 :: P5 :: P9 :: nil) >= 3) by (solve_hyps_min HP2P5P9eq HP2P5P9m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P5 :: P9 :: nil) (P2 :: P5 :: P9 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P5 :: P9 :: nil) (P2 :: P5 :: P9 :: P14 :: nil) 3 3 HP2P5P9mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P5P9M3. try clear HP2P5P9m3. try clear HP2P5P9P14m2. \n\nassert(HP2P14m2 : rk(P2 :: P14 :: nil) >= 2).\n{\n\tassert(HP5P9P14Mtmp : rk(P5 :: P9 :: P14 :: nil) <= 2) by (solve_hyps_max HP5P9P14eq HP5P9P14M2).\n\tassert(HP2P5P9P14mtmp : rk(P2 :: P5 :: P9 :: P14 :: nil) >= 3) by (solve_hyps_min HP2P5P9P14eq HP2P5P9P14m3).\n\tassert(HP14mtmp : rk(P14 :: nil) >= 1) by (solve_hyps_min HP14eq HP14m1).\n\tassert(Hincl : incl (P14 :: nil) (list_inter (P2 :: P14 :: nil) (P5 :: P9 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P5 :: P9 :: P14 :: nil) (P2 :: P14 :: P5 :: P9 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P14 :: P5 :: P9 :: P14 :: nil) ((P2 :: P14 :: nil) ++ (P5 :: P9 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP2P5P9P14mtmp;try rewrite HT2 in HP2P5P9P14mtmp.\n\tassert(HT := rule_2 (P2 :: P14 :: nil) (P5 :: P9 :: P14 :: nil) (P14 :: nil) 3 1 2 HP2P5P9P14mtmp HP14mtmp HP5P9P14Mtmp Hincl);apply HT.\n}\ntry clear HP2P14m1. \n\nassert(HP2P4P8P10M3 : rk(P2 :: P4 :: P8 :: P10 :: nil) <= 3).\n{\n\tassert(HP4Mtmp : rk(P4 :: nil) <= 1) by (solve_hyps_max HP4eq HP4M1).\n\tassert(HP2P8P10Mtmp : rk(P2 :: P8 :: P10 :: nil) <= 2) by (solve_hyps_max HP2P8P10eq HP2P8P10M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P4 :: nil) (P2 :: P8 :: P10 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P4 :: P8 :: P10 :: nil) (P4 :: P2 :: P8 :: P10 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P4 :: P2 :: P8 :: P10 :: nil) ((P4 :: nil) ++ (P2 :: P8 :: P10 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P4 :: nil) (P2 :: P8 :: P10 :: nil) (nil) 1 2 0 HP4Mtmp HP2P8P10Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP2P4P8P10M4. \n\nassert(HP2P4P8P10m2 : rk(P2 :: P4 :: P8 :: P10 :: nil) >= 2).\n{\n\tassert(HP2P4mtmp : rk(P2 :: P4 :: nil) >= 2) by (solve_hyps_min HP2P4eq HP2P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P4 :: nil) (P2 :: P4 :: P8 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P4 :: nil) (P2 :: P4 :: P8 :: P10 :: nil) 2 2 HP2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P4P8P10m1. \n\nassert(HP2P4P8P10m3 : rk(P2 :: P4 :: P8 :: P10 :: nil) >= 3).\n{\n\tassert(HP2P4P8mtmp : rk(P2 :: P4 :: P8 :: nil) >= 3) by (solve_hyps_min HP2P4P8eq HP2P4P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P4 :: P8 :: nil) (P2 :: P4 :: P8 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P4 :: P8 :: nil) (P2 :: P4 :: P8 :: P10 :: nil) 3 3 HP2P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P4P8P10m2. \n\nassert(HP1P2P3P9P10m2 : rk(P1 :: P2 :: P3 :: P9 :: P10 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P9 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P9 :: P10 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P9P10m1. \n\nassert(HP1P2P3P9P10M3 : rk(P1 :: P2 :: P3 :: P9 :: P10 :: nil) <= 3).\n{\n\tassert(HP1P2P3Mtmp : rk(P1 :: P2 :: P3 :: nil) <= 2) by (solve_hyps_max HP1P2P3eq HP1P2P3M2).\n\tassert(HP3P9P10Mtmp : rk(P3 :: P9 :: P10 :: nil) <= 2) by (solve_hyps_max HP3P9P10eq HP3P9P10M2).\n\tassert(HP3mtmp : rk(P3 :: nil) >= 1) by (solve_hyps_min HP3eq HP3m1).\n\tassert(Hincl : incl (P3 :: nil) (list_inter (P1 :: P2 :: P3 :: nil) (P3 :: P9 :: P10 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P9 :: P10 :: nil) (P1 :: P2 :: P3 :: P3 :: P9 :: P10 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P3 :: P3 :: P9 :: P10 :: nil) ((P1 :: P2 :: P3 :: nil) ++ (P3 :: P9 :: P10 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: P2 :: P3 :: nil) (P3 :: P9 :: P10 :: nil) (P3 :: nil) 2 2 1 HP1P2P3Mtmp HP3P9P10Mtmp HP3mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP3M1. try clear HP3m1. try clear HP1P2P3P9P10M4. \n\nassert(HP1P2P3P9P10m3 : rk(P1 :: P2 :: P3 :: P9 :: P10 :: nil) >= 3).\n{\n\tassert(HP1P2P9mtmp : rk(P1 :: P2 :: P9 :: nil) >= 3) by (solve_hyps_min HP1P2P9eq HP1P2P9m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P9 :: nil) (P1 :: P2 :: P3 :: P9 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P9 :: nil) (P1 :: P2 :: P3 :: P9 :: P10 :: nil) 3 3 HP1P2P9mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P9P10m2. \n\nassert(HP1P2P3P9P12P13m2 : rk(P1 :: P2 :: P3 :: P9 :: P12 :: P13 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P9 :: P12 :: P13 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P9 :: P12 :: P13 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P9P12P13m1. \n\nassert(HP1P2P3P9P12P13M3 : rk(P1 :: P2 :: P3 :: P9 :: P12 :: P13 :: nil) <= 3).\n{\n\tassert(HP9Mtmp : rk(P9 :: nil) <= 1) by (solve_hyps_max HP9eq HP9M1).\n\tassert(HP1P2P3P12P13Mtmp : rk(P1 :: P2 :: P3 :: P12 :: P13 :: nil) <= 2) by (solve_hyps_max HP1P2P3P12P13eq HP1P2P3P12P13M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P9 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P9 :: P12 :: P13 :: nil) (P9 :: P1 :: P2 :: P3 :: P12 :: P13 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P9 :: P1 :: P2 :: P3 :: P12 :: P13 :: nil) ((P9 :: nil) ++ (P1 :: P2 :: P3 :: P12 :: P13 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P9 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil) (nil) 1 2 0 HP9Mtmp HP1P2P3P12P13Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P2P3P9P12P13M4. \n\nassert(HP1P2P3P9P12P13m3 : rk(P1 :: P2 :: P3 :: P9 :: P12 :: P13 :: nil) >= 3).\n{\n\tassert(HP1P2P9mtmp : rk(P1 :: P2 :: P9 :: nil) >= 3) by (solve_hyps_min HP1P2P9eq HP1P2P9m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P9 :: nil) (P1 :: P2 :: P3 :: P9 :: P12 :: P13 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P9 :: nil) (P1 :: P2 :: P3 :: P9 :: P12 :: P13 :: nil) 3 3 HP1P2P9mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P9P12P13m2. \n\nassert(HP2P3P9m2 : rk(P2 :: P3 :: P9 :: nil) >= 2).\n{\n\tassert(HP2P3mtmp : rk(P2 :: P3 :: nil) >= 2) by (solve_hyps_min HP2P3eq HP2P3m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P3 :: nil) (P2 :: P3 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P3 :: nil) (P2 :: P3 :: P9 :: nil) 2 2 HP2P3mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P3P9m1. \n\nassert(HP2P3P9m3 : rk(P2 :: P3 :: P9 :: nil) >= 3).\n{\n\tassert(HP1P2P3P12P13Mtmp : rk(P1 :: P2 :: P3 :: P12 :: P13 :: nil) <= 2) by (solve_hyps_max HP1P2P3P12P13eq HP1P2P3P12P13M2).\n\tassert(HP1P2P3P9P12P13mtmp : rk(P1 :: P2 :: P3 :: P9 :: P12 :: P13 :: nil) >= 3) by (solve_hyps_min HP1P2P3P9P12P13eq HP1P2P3P9P12P13m3).\n\tassert(HP2P3mtmp : rk(P2 :: P3 :: nil) >= 2) by (solve_hyps_min HP2P3eq HP2P3m2).\n\tassert(Hincl : incl (P2 :: P3 :: nil) (list_inter (P2 :: P3 :: P9 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P9 :: P12 :: P13 :: nil) (P2 :: P3 :: P9 :: P1 :: P2 :: P3 :: P12 :: P13 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P3 :: P9 :: P1 :: P2 :: P3 :: P12 :: P13 :: nil) ((P2 :: P3 :: P9 :: nil) ++ (P1 :: P2 :: P3 :: P12 :: P13 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P3P9P12P13mtmp;try rewrite HT2 in HP1P2P3P9P12P13mtmp.\n\tassert(HT := rule_2 (P2 :: P3 :: P9 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil) (P2 :: P3 :: nil) 3 2 2 HP1P2P3P9P12P13mtmp HP2P3mtmp HP1P2P3P12P13Mtmp Hincl);apply HT.\n}\ntry clear HP2P3P9m2. try clear HP1P2P3P9P12P13M3. try clear HP1P2P3P9P12P13m3. \n\nassert(HP1P2P3P9m2 : rk(P1 :: P2 :: P3 :: P9 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P9 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P9m1. \n\nassert(HP1P2P3P9M3 : rk(P1 :: P2 :: P3 :: P9 :: nil) <= 3).\n{\n\tassert(HP1P2P3Mtmp : rk(P1 :: P2 :: P3 :: nil) <= 2) by (solve_hyps_max HP1P2P3eq HP1P2P3M2).\n\tassert(HP9Mtmp : rk(P9 :: nil) <= 1) by (solve_hyps_max HP9eq HP9M1).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P1 :: P2 :: P3 :: nil) (P9 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P9 :: nil) (P1 :: P2 :: P3 :: P9 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P3 :: P9 :: nil) ((P1 :: P2 :: P3 :: nil) ++ (P9 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: P2 :: P3 :: nil) (P9 :: nil) (nil) 2 1 0 HP1P2P3Mtmp HP9Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P2P3M2. try clear HP1P2P3m2. try clear HP1P2P3P9M4. \n\nassert(HP1P2P3P9m3 : rk(P1 :: P2 :: P3 :: P9 :: nil) >= 3).\n{\n\tassert(HP1P2P9mtmp : rk(P1 :: P2 :: P9 :: nil) >= 3) by (solve_hyps_min HP1P2P9eq HP1P2P9m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P9 :: nil) (P1 :: P2 :: P3 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P9 :: nil) (P1 :: P2 :: P3 :: P9 :: nil) 3 3 HP1P2P9mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P9m2. \n\nassert(HP2P3P9P10M3 : rk(P2 :: P3 :: P9 :: P10 :: nil) <= 3).\n{\n\tassert(HP2Mtmp : rk(P2 :: nil) <= 1) by (solve_hyps_max HP2eq HP2M1).\n\tassert(HP3P9P10Mtmp : rk(P3 :: P9 :: P10 :: nil) <= 2) by (solve_hyps_max HP3P9P10eq HP3P9P10M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P2 :: nil) (P3 :: P9 :: P10 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P3 :: P9 :: P10 :: nil) (P2 :: P3 :: P9 :: P10 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P3 :: P9 :: P10 :: nil) ((P2 :: nil) ++ (P3 :: P9 :: P10 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P2 :: nil) (P3 :: P9 :: P10 :: nil) (nil) 1 2 0 HP2Mtmp HP3P9P10Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP2P3P9P10M4. \n\nassert(HP2P3P9P10m2 : rk(P2 :: P3 :: P9 :: P10 :: nil) >= 2).\n{\n\tassert(HP2P3mtmp : rk(P2 :: P3 :: nil) >= 2) by (solve_hyps_min HP2P3eq HP2P3m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P3 :: nil) (P2 :: P3 :: P9 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P3 :: nil) (P2 :: P3 :: P9 :: P10 :: nil) 2 2 HP2P3mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P3M2. try clear HP2P3m2. try clear HP2P3P9P10m1. \n\nassert(HP2P3P9P10m3 : rk(P2 :: P3 :: P9 :: P10 :: nil) >= 3).\n{\n\tassert(HP1P2P3P9Mtmp : rk(P1 :: P2 :: P3 :: P9 :: nil) <= 3) by (solve_hyps_max HP1P2P3P9eq HP1P2P3P9M3).\n\tassert(HP1P2P3P9P10mtmp : rk(P1 :: P2 :: P3 :: P9 :: P10 :: nil) >= 3) by (solve_hyps_min HP1P2P3P9P10eq HP1P2P3P9P10m3).\n\tassert(HP2P3P9mtmp : rk(P2 :: P3 :: P9 :: nil) >= 3) by (solve_hyps_min HP2P3P9eq HP2P3P9m3).\n\tassert(Hincl : incl (P2 :: P3 :: P9 :: nil) (list_inter (P1 :: P2 :: P3 :: P9 :: nil) (P2 :: P3 :: P9 :: P10 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P9 :: P10 :: nil) (P1 :: P2 :: P3 :: P9 :: P2 :: P3 :: P9 :: P10 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P3 :: P9 :: P2 :: P3 :: P9 :: P10 :: nil) ((P1 :: P2 :: P3 :: P9 :: nil) ++ (P2 :: P3 :: P9 :: P10 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P3P9P10mtmp;try rewrite HT2 in HP1P2P3P9P10mtmp.\n\tassert(HT := rule_4 (P1 :: P2 :: P3 :: P9 :: nil) (P2 :: P3 :: P9 :: P10 :: nil) (P2 :: P3 :: P9 :: nil) 3 3 3 HP1P2P3P9P10mtmp HP2P3P9mtmp HP1P2P3P9Mtmp Hincl); apply HT.\n}\ntry clear HP1P2P3P9M3. try clear HP1P2P3P9m3. try clear HP2P3P9P10m2. try clear HP2P3P9M3. try clear HP2P3P9m3. try clear HP1P2P3P9P10M3. try clear HP1P2P3P9P10m3. \n\nassert(HP2P10m2 : rk(P2 :: P10 :: nil) >= 2).\n{\n\tassert(HP3P9P10Mtmp : rk(P3 :: P9 :: P10 :: nil) <= 2) by (solve_hyps_max HP3P9P10eq HP3P9P10M2).\n\tassert(HP2P3P9P10mtmp : rk(P2 :: P3 :: P9 :: P10 :: nil) >= 3) by (solve_hyps_min HP2P3P9P10eq HP2P3P9P10m3).\n\tassert(HP10mtmp : rk(P10 :: nil) >= 1) by (solve_hyps_min HP10eq HP10m1).\n\tassert(Hincl : incl (P10 :: nil) (list_inter (P2 :: P10 :: nil) (P3 :: P9 :: P10 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P3 :: P9 :: P10 :: nil) (P2 :: P10 :: P3 :: P9 :: P10 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P10 :: P3 :: P9 :: P10 :: nil) ((P2 :: P10 :: nil) ++ (P3 :: P9 :: P10 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP2P3P9P10mtmp;try rewrite HT2 in HP2P3P9P10mtmp.\n\tassert(HT := rule_2 (P2 :: P10 :: nil) (P3 :: P9 :: P10 :: nil) (P10 :: nil) 3 1 2 HP2P3P9P10mtmp HP10mtmp HP3P9P10Mtmp Hincl);apply HT.\n}\ntry clear HP2P10m1. try clear HP3P9P10M2. try clear HP3P9P10m2. try clear HP2P3P9P10M3. try clear HP2P3P9P10m3. \n\nassert(HP2P4P10m2 : rk(P2 :: P4 :: P10 :: nil) >= 2).\n{\n\tassert(HP2P4mtmp : rk(P2 :: P4 :: nil) >= 2) by (solve_hyps_min HP2P4eq HP2P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P4 :: nil) (P2 :: P4 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P4 :: nil) (P2 :: P4 :: P10 :: nil) 2 2 HP2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P4P10m1. \n\nassert(HP2P4P10m3 : rk(P2 :: P4 :: P10 :: nil) >= 3).\n{\n\tassert(HP2P8P10Mtmp : rk(P2 :: P8 :: P10 :: nil) <= 2) by (solve_hyps_max HP2P8P10eq HP2P8P10M2).\n\tassert(HP2P4P8P10mtmp : rk(P2 :: P4 :: P8 :: P10 :: nil) >= 3) by (solve_hyps_min HP2P4P8P10eq HP2P4P8P10m3).\n\tassert(HP2P10mtmp : rk(P2 :: P10 :: nil) >= 2) by (solve_hyps_min HP2P10eq HP2P10m2).\n\tassert(Hincl : incl (P2 :: P10 :: nil) (list_inter (P2 :: P4 :: P10 :: nil) (P2 :: P8 :: P10 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P4 :: P8 :: P10 :: nil) (P2 :: P4 :: P10 :: P2 :: P8 :: P10 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P4 :: P10 :: P2 :: P8 :: P10 :: nil) ((P2 :: P4 :: P10 :: nil) ++ (P2 :: P8 :: P10 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP2P4P8P10mtmp;try rewrite HT2 in HP2P4P8P10mtmp.\n\tassert(HT := rule_2 (P2 :: P4 :: P10 :: nil) (P2 :: P8 :: P10 :: nil) (P2 :: P10 :: nil) 3 2 2 HP2P4P8P10mtmp HP2P10mtmp HP2P8P10Mtmp Hincl);apply HT.\n}\ntry clear HP2P4P10m2. try clear HP2P4P8P10M3. try clear HP2P4P8P10m3. \n\nassert(HP2P4P6P10P14m2 : rk(P2 :: P4 :: P6 :: P10 :: P14 :: nil) >= 2).\n{\n\tassert(HP2P4mtmp : rk(P2 :: P4 :: nil) >= 2) by (solve_hyps_min HP2P4eq HP2P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P4 :: nil) (P2 :: P4 :: P6 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P4 :: nil) (P2 :: P4 :: P6 :: P10 :: P14 :: nil) 2 2 HP2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P4P6P10P14m1. \n\nassert(HP2P4P6P10P14M3 : rk(P2 :: P4 :: P6 :: P10 :: P14 :: nil) <= 3).\n{\n\tassert(HP2P4P6Mtmp : rk(P2 :: P4 :: P6 :: nil) <= 2) by (solve_hyps_max HP2P4P6eq HP2P4P6M2).\n\tassert(HP6P10P14Mtmp : rk(P6 :: P10 :: P14 :: nil) <= 2) by (solve_hyps_max HP6P10P14eq HP6P10P14M2).\n\tassert(HP6mtmp : rk(P6 :: nil) >= 1) by (solve_hyps_min HP6eq HP6m1).\n\tassert(Hincl : incl (P6 :: nil) (list_inter (P2 :: P4 :: P6 :: nil) (P6 :: P10 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P4 :: P6 :: P10 :: P14 :: nil) (P2 :: P4 :: P6 :: P6 :: P10 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P4 :: P6 :: P6 :: P10 :: P14 :: nil) ((P2 :: P4 :: P6 :: nil) ++ (P6 :: P10 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P2 :: P4 :: P6 :: nil) (P6 :: P10 :: P14 :: nil) (P6 :: nil) 2 2 1 HP2P4P6Mtmp HP6P10P14Mtmp HP6mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP2P4P6P10P14M4. \n\nassert(HP2P4P6P10P14m3 : rk(P2 :: P4 :: P6 :: P10 :: P14 :: nil) >= 3).\n{\n\tassert(HP2P4P10mtmp : rk(P2 :: P4 :: P10 :: nil) >= 3) by (solve_hyps_min HP2P4P10eq HP2P4P10m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P4 :: P10 :: nil) (P2 :: P4 :: P6 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P4 :: P10 :: nil) (P2 :: P4 :: P6 :: P10 :: P14 :: nil) 3 3 HP2P4P10mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P4P10M3. try clear HP2P4P10m3. try clear HP2P4P6P10P14m2. \n\nassert(HP2P4P6P8P10P14m2 : rk(P2 :: P4 :: P6 :: P8 :: P10 :: P14 :: nil) >= 2).\n{\n\tassert(HP2P4mtmp : rk(P2 :: P4 :: nil) >= 2) by (solve_hyps_min HP2P4eq HP2P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P4 :: nil) (P2 :: P4 :: P6 :: P8 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P4 :: nil) (P2 :: P4 :: P6 :: P8 :: P10 :: P14 :: nil) 2 2 HP2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P4P6P8P10P14m1. \n\nassert(HP2P4P6P8P10P14m3 : rk(P2 :: P4 :: P6 :: P8 :: P10 :: P14 :: nil) >= 3).\n{\n\tassert(HP2P4P8mtmp : rk(P2 :: P4 :: P8 :: nil) >= 3) by (solve_hyps_min HP2P4P8eq HP2P4P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P4 :: P8 :: nil) (P2 :: P4 :: P6 :: P8 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P4 :: P8 :: nil) (P2 :: P4 :: P6 :: P8 :: P10 :: P14 :: nil) 3 3 HP2P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P4P6P8P10P14m2. \n\nassert(HP2P4P6P8P10P14M3 : rk(P2 :: P4 :: P6 :: P8 :: P10 :: P14 :: nil) <= 3).\n{\n\tassert(HP2P8P10Mtmp : rk(P2 :: P8 :: P10 :: nil) <= 2) by (solve_hyps_max HP2P8P10eq HP2P8P10M2).\n\tassert(HP2P4P6P10P14Mtmp : rk(P2 :: P4 :: P6 :: P10 :: P14 :: nil) <= 3) by (solve_hyps_max HP2P4P6P10P14eq HP2P4P6P10P14M3).\n\tassert(HP2P10mtmp : rk(P2 :: P10 :: nil) >= 2) by (solve_hyps_min HP2P10eq HP2P10m2).\n\tassert(Hincl : incl (P2 :: P10 :: nil) (list_inter (P2 :: P8 :: P10 :: nil) (P2 :: P4 :: P6 :: P10 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P4 :: P6 :: P8 :: P10 :: P14 :: nil) (P2 :: P8 :: P10 :: P2 :: P4 :: P6 :: P10 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P8 :: P10 :: P2 :: P4 :: P6 :: P10 :: P14 :: nil) ((P2 :: P8 :: P10 :: nil) ++ (P2 :: P4 :: P6 :: P10 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P2 :: P8 :: P10 :: nil) (P2 :: P4 :: P6 :: P10 :: P14 :: nil) (P2 :: P10 :: nil) 2 3 2 HP2P8P10Mtmp HP2P4P6P10P14Mtmp HP2P10mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP2P4P6P10P14M3. try clear HP2P4P6P10P14m3. try clear HP2P4P6P8P10P14M4. \n\nassert(HP2P4P8P14m2 : rk(P2 :: P4 :: P8 :: P14 :: nil) >= 2).\n{\n\tassert(HP2P4mtmp : rk(P2 :: P4 :: nil) >= 2) by (solve_hyps_min HP2P4eq HP2P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P4 :: nil) (P2 :: P4 :: P8 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P4 :: nil) (P2 :: P4 :: P8 :: P14 :: nil) 2 2 HP2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P4P8P14m1. \n\nassert(HP2P4P8P14m3 : rk(P2 :: P4 :: P8 :: P14 :: nil) >= 3).\n{\n\tassert(HP2P4P8mtmp : rk(P2 :: P4 :: P8 :: nil) >= 3) by (solve_hyps_min HP2P4P8eq HP2P4P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P4 :: P8 :: nil) (P2 :: P4 :: P8 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P4 :: P8 :: nil) (P2 :: P4 :: P8 :: P14 :: nil) 3 3 HP2P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P4P8M3. try clear HP2P4P8m3. try clear HP2P4P8P14m2. \n\nassert(HP2P4P8P14M3 : rk(P2 :: P4 :: P8 :: P14 :: nil) <= 3).\n{\n\tassert(HP2P4P6P8P10P14Mtmp : rk(P2 :: P4 :: P6 :: P8 :: P10 :: P14 :: nil) <= 3) by (solve_hyps_max HP2P4P6P8P10P14eq HP2P4P6P8P10P14M3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P4 :: P8 :: P14 :: nil) (P2 :: P4 :: P6 :: P8 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (P2 :: P4 :: P8 :: P14 :: nil) (P2 :: P4 :: P6 :: P8 :: P10 :: P14 :: nil) 3 3 HP2P4P6P8P10P14Mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P4P8P14M4. try clear HP2P4P6P8P10P14M3. try clear HP2P4P6P8P10P14m3. \n\nassert(HP2P9m2 : rk(P2 :: P9 :: nil) >= 2).\n{\n\tassert(HP1Mtmp : rk(P1 :: nil) <= 1) by (solve_hyps_max HP1eq HP1M1).\n\tassert(HP1P2P9mtmp : rk(P1 :: P2 :: P9 :: nil) >= 3) by (solve_hyps_min HP1P2P9eq HP1P2P9m3).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P1 :: nil) (P2 :: P9 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P9 :: nil) (P1 :: P2 :: P9 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P9 :: nil) ((P1 :: nil) ++ (P2 :: P9 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P9mtmp;try rewrite HT2 in HP1P2P9mtmp.\n\tassert(HT := rule_4 (P1 :: nil) (P2 :: P9 :: nil) (nil) 3 0 1 HP1P2P9mtmp Hmtmp HP1Mtmp Hincl); apply HT.\n}\ntry clear HP2P9m1. \n\nassert(HP2P9P11P14m2 : rk(P2 :: P9 :: P11 :: P14 :: nil) >= 2).\n{\n\tassert(HP2P9mtmp : rk(P2 :: P9 :: nil) >= 2) by (solve_hyps_min HP2P9eq HP2P9m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P9 :: nil) (P2 :: P9 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P9 :: nil) (P2 :: P9 :: P11 :: P14 :: nil) 2 2 HP2P9mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P9P11P14m1. \n\nassert(HP2P9P11P14M3 : rk(P2 :: P9 :: P11 :: P14 :: nil) <= 3).\n{\n\tassert(HP2P9P11Mtmp : rk(P2 :: P9 :: P11 :: nil) <= 2) by (solve_hyps_max HP2P9P11eq HP2P9P11M2).\n\tassert(HP14Mtmp : rk(P14 :: nil) <= 1) by (solve_hyps_max HP14eq HP14M1).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P2 :: P9 :: P11 :: nil) (P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P9 :: P11 :: P14 :: nil) (P2 :: P9 :: P11 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P9 :: P11 :: P14 :: nil) ((P2 :: P9 :: P11 :: nil) ++ (P14 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P2 :: P9 :: P11 :: nil) (P14 :: nil) (nil) 2 1 0 HP2P9P11Mtmp HP14Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP2P9P11P14M4. \n\nassert(HP2P9P11P14m3 : rk(P2 :: P9 :: P11 :: P14 :: nil) >= 3).\n{\n\tassert(HP2P4P8P14Mtmp : rk(P2 :: P4 :: P8 :: P14 :: nil) <= 3) by (solve_hyps_max HP2P4P8P14eq HP2P4P8P14M3).\n\tassert(HP2P4P8P9P11P14mtmp : rk(P2 :: P4 :: P8 :: P9 :: P11 :: P14 :: nil) >= 4) by (solve_hyps_min HP2P4P8P9P11P14eq HP2P4P8P9P11P14m4).\n\tassert(HP2P14mtmp : rk(P2 :: P14 :: nil) >= 2) by (solve_hyps_min HP2P14eq HP2P14m2).\n\tassert(Hincl : incl (P2 :: P14 :: nil) (list_inter (P2 :: P4 :: P8 :: P14 :: nil) (P2 :: P9 :: P11 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P4 :: P8 :: P9 :: P11 :: P14 :: nil) (P2 :: P4 :: P8 :: P14 :: P2 :: P9 :: P11 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P4 :: P8 :: P14 :: P2 :: P9 :: P11 :: P14 :: nil) ((P2 :: P4 :: P8 :: P14 :: nil) ++ (P2 :: P9 :: P11 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP2P4P8P9P11P14mtmp;try rewrite HT2 in HP2P4P8P9P11P14mtmp.\n\tassert(HT := rule_4 (P2 :: P4 :: P8 :: P14 :: nil) (P2 :: P9 :: P11 :: P14 :: nil) (P2 :: P14 :: nil) 4 2 3 HP2P4P8P9P11P14mtmp HP2P14mtmp HP2P4P8P14Mtmp Hincl); apply HT.\n}\ntry clear HP2P4P8P14M3. try clear HP2P4P8P14m3. try clear HP2P9P11P14m2. try clear HP2P14M2. try clear HP2P14m2. try clear HP2P4P8P9P11P14M4. try clear HP2P4P8P9P11P14m4. \n\nassert(HP1P2P6P8P9P10P14m2 : rk(P1 :: P2 :: P6 :: P8 :: P9 :: P10 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P6 :: P8 :: P9 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P6 :: P8 :: P9 :: P10 :: P14 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P6P8P9P10P14m1. \n\nassert(HP1P2P6P8P9P10P14m3 : rk(P1 :: P2 :: P6 :: P8 :: P9 :: P10 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P2P6mtmp : rk(P1 :: P2 :: P6 :: nil) >= 3) by (solve_hyps_min HP1P2P6eq HP1P2P6m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P6 :: nil) (P1 :: P2 :: P6 :: P8 :: P9 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P6 :: nil) (P1 :: P2 :: P6 :: P8 :: P9 :: P10 :: P14 :: nil) 3 3 HP1P2P6mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P6P8P9P10P14m2. \n\nassert(HP1P2P6P8P9P10P14m4 : rk(P1 :: P2 :: P6 :: P8 :: P9 :: P10 :: P14 :: nil) >= 4).\n{\n\tassert(HP1P2P6P8mtmp : rk(P1 :: P2 :: P6 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P6P8eq HP1P2P6P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P6 :: P8 :: nil) (P1 :: P2 :: P6 :: P8 :: P9 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P6 :: P8 :: nil) (P1 :: P2 :: P6 :: P8 :: P9 :: P10 :: P14 :: nil) 4 4 HP1P2P6P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P6P8P9P10P14m3. \n\nassert(HP2P6P8P9P10P14m2 : rk(P2 :: P6 :: P8 :: P9 :: P10 :: P14 :: nil) >= 2).\n{\n\tassert(HP2P6mtmp : rk(P2 :: P6 :: nil) >= 2) by (solve_hyps_min HP2P6eq HP2P6m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P6 :: nil) (P2 :: P6 :: P8 :: P9 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P6 :: nil) (P2 :: P6 :: P8 :: P9 :: P10 :: P14 :: nil) 2 2 HP2P6mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P6M2. try clear HP2P6m2. try clear HP2P6P8P9P10P14m1. \n\nassert(HP2P6P8P9P10P14m3 : rk(P2 :: P6 :: P8 :: P9 :: P10 :: P14 :: nil) >= 3).\n{\n\tassert(HP2P6P8mtmp : rk(P2 :: P6 :: P8 :: nil) >= 3) by (solve_hyps_min HP2P6P8eq HP2P6P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P6 :: P8 :: nil) (P2 :: P6 :: P8 :: P9 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P6 :: P8 :: nil) (P2 :: P6 :: P8 :: P9 :: P10 :: P14 :: nil) 3 3 HP2P6P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P6P8M3. try clear HP2P6P8m3. try clear HP2P6P8P9P10P14m2. \n\nassert(HP2P6P8P9P10P14m4 : rk(P2 :: P6 :: P8 :: P9 :: P10 :: P14 :: nil) >= 4).\n{\n\tassert(HP1P8P9Mtmp : rk(P1 :: P8 :: P9 :: nil) <= 2) by (solve_hyps_max HP1P8P9eq HP1P8P9M2).\n\tassert(HP1P2P6P8P9P10P14mtmp : rk(P1 :: P2 :: P6 :: P8 :: P9 :: P10 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P2P6P8P9P10P14eq HP1P2P6P8P9P10P14m4).\n\tassert(HP8P9mtmp : rk(P8 :: P9 :: nil) >= 2) by (solve_hyps_min HP8P9eq HP8P9m2).\n\tassert(Hincl : incl (P8 :: P9 :: nil) (list_inter (P1 :: P8 :: P9 :: nil) (P2 :: P6 :: P8 :: P9 :: P10 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P6 :: P8 :: P9 :: P10 :: P14 :: nil) (P1 :: P8 :: P9 :: P2 :: P6 :: P8 :: P9 :: P10 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P8 :: P9 :: P2 :: P6 :: P8 :: P9 :: P10 :: P14 :: nil) ((P1 :: P8 :: P9 :: nil) ++ (P2 :: P6 :: P8 :: P9 :: P10 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P6P8P9P10P14mtmp;try rewrite HT2 in HP1P2P6P8P9P10P14mtmp.\n\tassert(HT := rule_4 (P1 :: P8 :: P9 :: nil) (P2 :: P6 :: P8 :: P9 :: P10 :: P14 :: nil) (P8 :: P9 :: nil) 4 2 2 HP1P2P6P8P9P10P14mtmp HP8P9mtmp HP1P8P9Mtmp Hincl); apply HT.\n}\ntry clear HP2P6P8P9P10P14m3. try clear HP1P2P6P8P9P10P14M4. try clear HP1P2P6P8P9P10P14m4. \n\nassert(HP1P6P8P9M3 : rk(P1 :: P6 :: P8 :: P9 :: nil) <= 3).\n{\n\tassert(HP6Mtmp : rk(P6 :: nil) <= 1) by (solve_hyps_max HP6eq HP6M1).\n\tassert(HP1P8P9Mtmp : rk(P1 :: P8 :: P9 :: nil) <= 2) by (solve_hyps_max HP1P8P9eq HP1P8P9M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P6 :: nil) (P1 :: P8 :: P9 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P6 :: P8 :: P9 :: nil) (P6 :: P1 :: P8 :: P9 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P6 :: P1 :: P8 :: P9 :: nil) ((P6 :: nil) ++ (P1 :: P8 :: P9 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P6 :: nil) (P1 :: P8 :: P9 :: nil) (nil) 1 2 0 HP6Mtmp HP1P8P9Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P6P8P9M4. \n\nassert(HP1P6P8P9m2 : rk(P1 :: P6 :: P8 :: P9 :: nil) >= 2).\n{\n\tassert(HP1P6mtmp : rk(P1 :: P6 :: nil) >= 2) by (solve_hyps_min HP1P6eq HP1P6m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P6 :: nil) (P1 :: P6 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P6 :: nil) (P1 :: P6 :: P8 :: P9 :: nil) 2 2 HP1P6mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P6P8P9m1. \n\nassert(HP1P6P8P9m3 : rk(P1 :: P6 :: P8 :: P9 :: nil) >= 3).\n{\n\tassert(HP1P6P8mtmp : rk(P1 :: P6 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P6P8eq HP1P6P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P6 :: P8 :: nil) (P1 :: P6 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P6 :: P8 :: nil) (P1 :: P6 :: P8 :: P9 :: nil) 3 3 HP1P6P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P6P8P9m2. \n\nassert(HP6P9m2 : rk(P6 :: P9 :: nil) >= 2).\n{\n\tassert(HP1P8P9Mtmp : rk(P1 :: P8 :: P9 :: nil) <= 2) by (solve_hyps_max HP1P8P9eq HP1P8P9M2).\n\tassert(HP1P6P8P9mtmp : rk(P1 :: P6 :: P8 :: P9 :: nil) >= 3) by (solve_hyps_min HP1P6P8P9eq HP1P6P8P9m3).\n\tassert(HP9mtmp : rk(P9 :: nil) >= 1) by (solve_hyps_min HP9eq HP9m1).\n\tassert(Hincl : incl (P9 :: nil) (list_inter (P6 :: P9 :: nil) (P1 :: P8 :: P9 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P6 :: P8 :: P9 :: nil) (P6 :: P9 :: P1 :: P8 :: P9 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P6 :: P9 :: P1 :: P8 :: P9 :: nil) ((P6 :: P9 :: nil) ++ (P1 :: P8 :: P9 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P6P8P9mtmp;try rewrite HT2 in HP1P6P8P9mtmp.\n\tassert(HT := rule_2 (P6 :: P9 :: nil) (P1 :: P8 :: P9 :: nil) (P9 :: nil) 3 1 2 HP1P6P8P9mtmp HP9mtmp HP1P8P9Mtmp Hincl);apply HT.\n}\ntry clear HP6P9m1. try clear HP1P6P8P9M3. try clear HP1P6P8P9m3. \n\nassert(HP6P9P10P14M3 : rk(P6 :: P9 :: P10 :: P14 :: nil) <= 3).\n{\n\tassert(HP9Mtmp : rk(P9 :: nil) <= 1) by (solve_hyps_max HP9eq HP9M1).\n\tassert(HP6P10P14Mtmp : rk(P6 :: P10 :: P14 :: nil) <= 2) by (solve_hyps_max HP6P10P14eq HP6P10P14M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P9 :: nil) (P6 :: P10 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P6 :: P9 :: P10 :: P14 :: nil) (P9 :: P6 :: P10 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P9 :: P6 :: P10 :: P14 :: nil) ((P9 :: nil) ++ (P6 :: P10 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P9 :: nil) (P6 :: P10 :: P14 :: nil) (nil) 1 2 0 HP9Mtmp HP6P10P14Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP6P9P10P14M4. \n\nassert(HP6P9P10P14m2 : rk(P6 :: P9 :: P10 :: P14 :: nil) >= 2).\n{\n\tassert(HP6P9mtmp : rk(P6 :: P9 :: nil) >= 2) by (solve_hyps_min HP6P9eq HP6P9m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P6 :: P9 :: nil) (P6 :: P9 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P6 :: P9 :: nil) (P6 :: P9 :: P10 :: P14 :: nil) 2 2 HP6P9mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP6P9M2. try clear HP6P9m2. try clear HP6P9P10P14m1. \n\nassert(HP6P9P10P14m3 : rk(P6 :: P9 :: P10 :: P14 :: nil) >= 3).\n{\n\tassert(HP2P8P10Mtmp : rk(P2 :: P8 :: P10 :: nil) <= 2) by (solve_hyps_max HP2P8P10eq HP2P8P10M2).\n\tassert(HP2P6P8P9P10P14mtmp : rk(P2 :: P6 :: P8 :: P9 :: P10 :: P14 :: nil) >= 4) by (solve_hyps_min HP2P6P8P9P10P14eq HP2P6P8P9P10P14m4).\n\tassert(HP10mtmp : rk(P10 :: nil) >= 1) by (solve_hyps_min HP10eq HP10m1).\n\tassert(Hincl : incl (P10 :: nil) (list_inter (P2 :: P8 :: P10 :: nil) (P6 :: P9 :: P10 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P6 :: P8 :: P9 :: P10 :: P14 :: nil) (P2 :: P8 :: P10 :: P6 :: P9 :: P10 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P8 :: P10 :: P6 :: P9 :: P10 :: P14 :: nil) ((P2 :: P8 :: P10 :: nil) ++ (P6 :: P9 :: P10 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP2P6P8P9P10P14mtmp;try rewrite HT2 in HP2P6P8P9P10P14mtmp.\n\tassert(HT := rule_4 (P2 :: P8 :: P10 :: nil) (P6 :: P9 :: P10 :: P14 :: nil) (P10 :: nil) 4 1 2 HP2P6P8P9P10P14mtmp HP10mtmp HP2P8P10Mtmp Hincl); apply HT.\n}\ntry clear HP6P9P10P14m2. try clear HP2P6P8P9P10P14M4. try clear HP2P6P8P9P10P14m4. \n\nassert(HP9P14m2 : rk(P9 :: P14 :: nil) >= 2).\n{\n\tassert(HP6P10P14Mtmp : rk(P6 :: P10 :: P14 :: nil) <= 2) by (solve_hyps_max HP6P10P14eq HP6P10P14M2).\n\tassert(HP6P9P10P14mtmp : rk(P6 :: P9 :: P10 :: P14 :: nil) >= 3) by (solve_hyps_min HP6P9P10P14eq HP6P9P10P14m3).\n\tassert(HP14mtmp : rk(P14 :: nil) >= 1) by (solve_hyps_min HP14eq HP14m1).\n\tassert(Hincl : incl (P14 :: nil) (list_inter (P9 :: P14 :: nil) (P6 :: P10 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P6 :: P9 :: P10 :: P14 :: nil) (P9 :: P14 :: P6 :: P10 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P9 :: P14 :: P6 :: P10 :: P14 :: nil) ((P9 :: P14 :: nil) ++ (P6 :: P10 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP6P9P10P14mtmp;try rewrite HT2 in HP6P9P10P14mtmp.\n\tassert(HT := rule_2 (P9 :: P14 :: nil) (P6 :: P10 :: P14 :: nil) (P14 :: nil) 3 1 2 HP6P9P10P14mtmp HP14mtmp HP6P10P14Mtmp Hincl);apply HT.\n}\ntry clear HP9P14m1. try clear HP6P9P10P14M3. try clear HP6P9P10P14m3. \n\nassert(HP2P9P14m2 : rk(P2 :: P9 :: P14 :: nil) >= 2).\n{\n\tassert(HP2P9mtmp : rk(P2 :: P9 :: nil) >= 2) by (solve_hyps_min HP2P9eq HP2P9m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P9 :: nil) (P2 :: P9 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P9 :: nil) (P2 :: P9 :: P14 :: nil) 2 2 HP2P9mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P9M2. try clear HP2P9m2. try clear HP2P9P14m1. \n\nassert(HP2P9P14m3 : rk(P2 :: P9 :: P14 :: nil) >= 3).\n{\n\tassert(HP5P9P14Mtmp : rk(P5 :: P9 :: P14 :: nil) <= 2) by (solve_hyps_max HP5P9P14eq HP5P9P14M2).\n\tassert(HP2P5P9P14mtmp : rk(P2 :: P5 :: P9 :: P14 :: nil) >= 3) by (solve_hyps_min HP2P5P9P14eq HP2P5P9P14m3).\n\tassert(HP9P14mtmp : rk(P9 :: P14 :: nil) >= 2) by (solve_hyps_min HP9P14eq HP9P14m2).\n\tassert(Hincl : incl (P9 :: P14 :: nil) (list_inter (P2 :: P9 :: P14 :: nil) (P5 :: P9 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P5 :: P9 :: P14 :: nil) (P2 :: P9 :: P14 :: P5 :: P9 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P9 :: P14 :: P5 :: P9 :: P14 :: nil) ((P2 :: P9 :: P14 :: nil) ++ (P5 :: P9 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP2P5P9P14mtmp;try rewrite HT2 in HP2P5P9P14mtmp.\n\tassert(HT := rule_2 (P2 :: P9 :: P14 :: nil) (P5 :: P9 :: P14 :: nil) (P9 :: P14 :: nil) 3 2 2 HP2P5P9P14mtmp HP9P14mtmp HP5P9P14Mtmp Hincl);apply HT.\n}\ntry clear HP2P9P14m2. try clear HP9P14M2. try clear HP9P14m2. try clear HP2P5P9P14M3. try clear HP2P5P9P14m3. \n\nassert(HP2P7P9P11P14m2 : rk(P2 :: P7 :: P9 :: P11 :: P14 :: nil) >= 2).\n{\n\tassert(HP2P7mtmp : rk(P2 :: P7 :: nil) >= 2) by (solve_hyps_min HP2P7eq HP2P7m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P7 :: nil) (P2 :: P7 :: P9 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P7 :: nil) (P2 :: P7 :: P9 :: P11 :: P14 :: nil) 2 2 HP2P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P7P9P11P14m1. \n\nassert(HP2P7P9P11P14m3 : rk(P2 :: P7 :: P9 :: P11 :: P14 :: nil) >= 3).\n{\n\tassert(HP2P7P9mtmp : rk(P2 :: P7 :: P9 :: nil) >= 3) by (solve_hyps_min HP2P7P9eq HP2P7P9m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P7 :: P9 :: nil) (P2 :: P7 :: P9 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P7 :: P9 :: nil) (P2 :: P7 :: P9 :: P11 :: P14 :: nil) 3 3 HP2P7P9mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P7P9P11P14m2. \n\nassert(HP2P7P9P11P14M3 : rk(P2 :: P7 :: P9 :: P11 :: P14 :: nil) <= 3).\n{\n\tassert(HP2P7P9P14Mtmp : rk(P2 :: P7 :: P9 :: P14 :: nil) <= 3) by (solve_hyps_max HP2P7P9P14eq HP2P7P9P14M3).\n\tassert(HP2P9P11P14Mtmp : rk(P2 :: P9 :: P11 :: P14 :: nil) <= 3) by (solve_hyps_max HP2P9P11P14eq HP2P9P11P14M3).\n\tassert(HP2P9P14mtmp : rk(P2 :: P9 :: P14 :: nil) >= 3) by (solve_hyps_min HP2P9P14eq HP2P9P14m3).\n\tassert(Hincl : incl (P2 :: P9 :: P14 :: nil) (list_inter (P2 :: P7 :: P9 :: P14 :: nil) (P2 :: P9 :: P11 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P7 :: P9 :: P11 :: P14 :: nil) (P2 :: P7 :: P9 :: P14 :: P2 :: P9 :: P11 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P7 :: P9 :: P14 :: P2 :: P9 :: P11 :: P14 :: nil) ((P2 :: P7 :: P9 :: P14 :: nil) ++ (P2 :: P9 :: P11 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P2 :: P7 :: P9 :: P14 :: nil) (P2 :: P9 :: P11 :: P14 :: nil) (P2 :: P9 :: P14 :: nil) 3 3 3 HP2P7P9P14Mtmp HP2P9P11P14Mtmp HP2P9P14mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP2P7P9P14M3. try clear HP2P7P9P14m3. try clear HP2P9P11P14M3. try clear HP2P9P11P14m3. try clear HP2P9P14M3. try clear HP2P9P14m3. try clear HP2P7P9P11P14M4. \n\nassert(HP2P7P9P11M3 : rk(P2 :: P7 :: P9 :: P11 :: nil) <= 3).\n{\n\tassert(HP7Mtmp : rk(P7 :: nil) <= 1) by (solve_hyps_max HP7eq HP7M1).\n\tassert(HP2P9P11Mtmp : rk(P2 :: P9 :: P11 :: nil) <= 2) by (solve_hyps_max HP2P9P11eq HP2P9P11M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P7 :: nil) (P2 :: P9 :: P11 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P7 :: P9 :: P11 :: nil) (P7 :: P2 :: P9 :: P11 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P7 :: P2 :: P9 :: P11 :: nil) ((P7 :: nil) ++ (P2 :: P9 :: P11 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P7 :: nil) (P2 :: P9 :: P11 :: nil) (nil) 1 2 0 HP7Mtmp HP2P9P11Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP2P7P9P11M4. \n\nassert(HP2P7P9P11m2 : rk(P2 :: P7 :: P9 :: P11 :: nil) >= 2).\n{\n\tassert(HP2P7mtmp : rk(P2 :: P7 :: nil) >= 2) by (solve_hyps_min HP2P7eq HP2P7m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P7 :: nil) (P2 :: P7 :: P9 :: P11 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P7 :: nil) (P2 :: P7 :: P9 :: P11 :: nil) 2 2 HP2P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P7P9P11m1. \n\nassert(HP2P7P9P11m3 : rk(P2 :: P7 :: P9 :: P11 :: nil) >= 3).\n{\n\tassert(HP2P7P9mtmp : rk(P2 :: P7 :: P9 :: nil) >= 3) by (solve_hyps_min HP2P7P9eq HP2P7P9m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P7 :: P9 :: nil) (P2 :: P7 :: P9 :: P11 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P7 :: P9 :: nil) (P2 :: P7 :: P9 :: P11 :: nil) 3 3 HP2P7P9mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P7P9M3. try clear HP2P7P9m3. try clear HP2P7P9P11m2. \n\nassert(HP1P2P8P10M3 : rk(P1 :: P2 :: P8 :: P10 :: nil) <= 3).\n{\n\tassert(HP1Mtmp : rk(P1 :: nil) <= 1) by (solve_hyps_max HP1eq HP1M1).\n\tassert(HP2P8P10Mtmp : rk(P2 :: P8 :: P10 :: nil) <= 2) by (solve_hyps_max HP2P8P10eq HP2P8P10M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P1 :: nil) (P2 :: P8 :: P10 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P8 :: P10 :: nil) (P1 :: P2 :: P8 :: P10 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P8 :: P10 :: nil) ((P1 :: nil) ++ (P2 :: P8 :: P10 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: nil) (P2 :: P8 :: P10 :: nil) (nil) 1 2 0 HP1Mtmp HP2P8P10Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P2P8P10M4. \n\nassert(HP1P2P8P10m2 : rk(P1 :: P2 :: P8 :: P10 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P8 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P8 :: P10 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P8P10m1. \n\nassert(HP1P2P8P10m3 : rk(P1 :: P2 :: P8 :: P10 :: nil) >= 3).\n{\n\tassert(HP1P2P8mtmp : rk(P1 :: P2 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P2P8eq HP1P2P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P8 :: nil) (P1 :: P2 :: P8 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P8 :: nil) (P1 :: P2 :: P8 :: P10 :: nil) 3 3 HP1P2P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P8P10m2. \n\nassert(HP1P2P10m2 : rk(P1 :: P2 :: P10 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P10 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P10m1. \n\nassert(HP1P2P10m3 : rk(P1 :: P2 :: P10 :: nil) >= 3).\n{\n\tassert(HP2P8P10Mtmp : rk(P2 :: P8 :: P10 :: nil) <= 2) by (solve_hyps_max HP2P8P10eq HP2P8P10M2).\n\tassert(HP1P2P8P10mtmp : rk(P1 :: P2 :: P8 :: P10 :: nil) >= 3) by (solve_hyps_min HP1P2P8P10eq HP1P2P8P10m3).\n\tassert(HP2P10mtmp : rk(P2 :: P10 :: nil) >= 2) by (solve_hyps_min HP2P10eq HP2P10m2).\n\tassert(Hincl : incl (P2 :: P10 :: nil) (list_inter (P1 :: P2 :: P10 :: nil) (P2 :: P8 :: P10 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P8 :: P10 :: nil) (P1 :: P2 :: P10 :: P2 :: P8 :: P10 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P10 :: P2 :: P8 :: P10 :: nil) ((P1 :: P2 :: P10 :: nil) ++ (P2 :: P8 :: P10 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P8P10mtmp;try rewrite HT2 in HP1P2P8P10mtmp.\n\tassert(HT := rule_2 (P1 :: P2 :: P10 :: nil) (P2 :: P8 :: P10 :: nil) (P2 :: P10 :: nil) 3 2 2 HP1P2P8P10mtmp HP2P10mtmp HP2P8P10Mtmp Hincl);apply HT.\n}\ntry clear HP1P2P10m2. \n\nassert(HP1P2P10P11M3 : rk(P1 :: P2 :: P10 :: P11 :: nil) <= 3).\n{\n\tassert(HP2Mtmp : rk(P2 :: nil) <= 1) by (solve_hyps_max HP2eq HP2M1).\n\tassert(HP1P10P11Mtmp : rk(P1 :: P10 :: P11 :: nil) <= 2) by (solve_hyps_max HP1P10P11eq HP1P10P11M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P2 :: nil) (P1 :: P10 :: P11 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P10 :: P11 :: nil) (P2 :: P1 :: P10 :: P11 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P1 :: P10 :: P11 :: nil) ((P2 :: nil) ++ (P1 :: P10 :: P11 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P2 :: nil) (P1 :: P10 :: P11 :: nil) (nil) 1 2 0 HP2Mtmp HP1P10P11Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P2P10P11M4. \n\nassert(HP1P2P10P11m2 : rk(P1 :: P2 :: P10 :: P11 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P10 :: P11 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P10 :: P11 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P10P11m1. \n\nassert(HP1P2P10P11m3 : rk(P1 :: P2 :: P10 :: P11 :: nil) >= 3).\n{\n\tassert(HP1P2P10mtmp : rk(P1 :: P2 :: P10 :: nil) >= 3) by (solve_hyps_min HP1P2P10eq HP1P2P10m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P10 :: nil) (P1 :: P2 :: P10 :: P11 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P10 :: nil) (P1 :: P2 :: P10 :: P11 :: nil) 3 3 HP1P2P10mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P10M3. try clear HP1P2P10m3. try clear HP1P2P10P11m2. \n\nassert(HP2P11m2 : rk(P2 :: P11 :: nil) >= 2).\n{\n\tassert(HP1P10P11Mtmp : rk(P1 :: P10 :: P11 :: nil) <= 2) by (solve_hyps_max HP1P10P11eq HP1P10P11M2).\n\tassert(HP1P2P10P11mtmp : rk(P1 :: P2 :: P10 :: P11 :: nil) >= 3) by (solve_hyps_min HP1P2P10P11eq HP1P2P10P11m3).\n\tassert(HP11mtmp : rk(P11 :: nil) >= 1) by (solve_hyps_min HP11eq HP11m1).\n\tassert(Hincl : incl (P11 :: nil) (list_inter (P2 :: P11 :: nil) (P1 :: P10 :: P11 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P10 :: P11 :: nil) (P2 :: P11 :: P1 :: P10 :: P11 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P11 :: P1 :: P10 :: P11 :: nil) ((P2 :: P11 :: nil) ++ (P1 :: P10 :: P11 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P10P11mtmp;try rewrite HT2 in HP1P2P10P11mtmp.\n\tassert(HT := rule_2 (P2 :: P11 :: nil) (P1 :: P10 :: P11 :: nil) (P11 :: nil) 3 1 2 HP1P2P10P11mtmp HP11mtmp HP1P10P11Mtmp Hincl);apply HT.\n}\ntry clear HP2P11m1. try clear HP1P2P10P11M3. try clear HP1P2P10P11m3. \n\nassert(HP2P7P11m2 : rk(P2 :: P7 :: P11 :: nil) >= 2).\n{\n\tassert(HP2P7mtmp : rk(P2 :: P7 :: nil) >= 2) by (solve_hyps_min HP2P7eq HP2P7m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P7 :: nil) (P2 :: P7 :: P11 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P7 :: nil) (P2 :: P7 :: P11 :: nil) 2 2 HP2P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P7P11m1. \n\nassert(HP2P7P11m3 : rk(P2 :: P7 :: P11 :: nil) >= 3).\n{\n\tassert(HP2P9P11Mtmp : rk(P2 :: P9 :: P11 :: nil) <= 2) by (solve_hyps_max HP2P9P11eq HP2P9P11M2).\n\tassert(HP2P7P9P11mtmp : rk(P2 :: P7 :: P9 :: P11 :: nil) >= 3) by (solve_hyps_min HP2P7P9P11eq HP2P7P9P11m3).\n\tassert(HP2P11mtmp : rk(P2 :: P11 :: nil) >= 2) by (solve_hyps_min HP2P11eq HP2P11m2).\n\tassert(Hincl : incl (P2 :: P11 :: nil) (list_inter (P2 :: P7 :: P11 :: nil) (P2 :: P9 :: P11 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P7 :: P9 :: P11 :: nil) (P2 :: P7 :: P11 :: P2 :: P9 :: P11 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P7 :: P11 :: P2 :: P9 :: P11 :: nil) ((P2 :: P7 :: P11 :: nil) ++ (P2 :: P9 :: P11 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP2P7P9P11mtmp;try rewrite HT2 in HP2P7P9P11mtmp.\n\tassert(HT := rule_2 (P2 :: P7 :: P11 :: nil) (P2 :: P9 :: P11 :: nil) (P2 :: P11 :: nil) 3 2 2 HP2P7P9P11mtmp HP2P11mtmp HP2P9P11Mtmp Hincl);apply HT.\n}\ntry clear HP2P7P11m2. \n\nassert(HP2P7P11P14m2 : rk(P2 :: P7 :: P11 :: P14 :: nil) >= 2).\n{\n\tassert(HP2P7mtmp : rk(P2 :: P7 :: nil) >= 2) by (solve_hyps_min HP2P7eq HP2P7m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P7 :: nil) (P2 :: P7 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P7 :: nil) (P2 :: P7 :: P11 :: P14 :: nil) 2 2 HP2P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P7M2. try clear HP2P7m2. try clear HP2P7P11P14m1. \n\nassert(HP2P7P11P14m3 : rk(P2 :: P7 :: P11 :: P14 :: nil) >= 3).\n{\n\tassert(HP2P7P11mtmp : rk(P2 :: P7 :: P11 :: nil) >= 3) by (solve_hyps_min HP2P7P11eq HP2P7P11m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P7 :: P11 :: nil) (P2 :: P7 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P7 :: P11 :: nil) (P2 :: P7 :: P11 :: P14 :: nil) 3 3 HP2P7P11mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P7P11M3. try clear HP2P7P11m3. try clear HP2P7P11P14m2. \n\nassert(HP2P7P11P14M3 : rk(P2 :: P7 :: P11 :: P14 :: nil) <= 3).\n{\n\tassert(HP2P7P9P11P14Mtmp : rk(P2 :: P7 :: P9 :: P11 :: P14 :: nil) <= 3) by (solve_hyps_max HP2P7P9P11P14eq HP2P7P9P11P14M3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P7 :: P11 :: P14 :: nil) (P2 :: P7 :: P9 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (P2 :: P7 :: P11 :: P14 :: nil) (P2 :: P7 :: P9 :: P11 :: P14 :: nil) 3 3 HP2P7P9P11P14Mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P7P11P14M4. try clear HP2P7P9P11P14M3. try clear HP2P7P9P11P14m3. \n\nassert(HP1P2P6P8P10m2 : rk(P1 :: P2 :: P6 :: P8 :: P10 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P6 :: P8 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P6 :: P8 :: P10 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P6P8P10m1. \n\nassert(HP1P2P6P8P10m3 : rk(P1 :: P2 :: P6 :: P8 :: P10 :: nil) >= 3).\n{\n\tassert(HP1P2P6mtmp : rk(P1 :: P2 :: P6 :: nil) >= 3) by (solve_hyps_min HP1P2P6eq HP1P2P6m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P6 :: nil) (P1 :: P2 :: P6 :: P8 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P6 :: nil) (P1 :: P2 :: P6 :: P8 :: P10 :: nil) 3 3 HP1P2P6mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P6P8P10m2. \n\nassert(HP1P2P6P8P10m4 : rk(P1 :: P2 :: P6 :: P8 :: P10 :: nil) >= 4).\n{\n\tassert(HP1P2P6P8mtmp : rk(P1 :: P2 :: P6 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P6P8eq HP1P2P6P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P6 :: P8 :: nil) (P1 :: P2 :: P6 :: P8 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P6 :: P8 :: nil) (P1 :: P2 :: P6 :: P8 :: P10 :: nil) 4 4 HP1P2P6P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P6P8P10m3. \n\nassert(HP1P6P10m2 : rk(P1 :: P6 :: P10 :: nil) >= 2).\n{\n\tassert(HP1P6mtmp : rk(P1 :: P6 :: nil) >= 2) by (solve_hyps_min HP1P6eq HP1P6m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P6 :: nil) (P1 :: P6 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P6 :: nil) (P1 :: P6 :: P10 :: nil) 2 2 HP1P6mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P6P10m1. \n\nassert(HP1P6P10m3 : rk(P1 :: P6 :: P10 :: nil) >= 3).\n{\n\tassert(HP2P8P10Mtmp : rk(P2 :: P8 :: P10 :: nil) <= 2) by (solve_hyps_max HP2P8P10eq HP2P8P10M2).\n\tassert(HP1P2P6P8P10mtmp : rk(P1 :: P2 :: P6 :: P8 :: P10 :: nil) >= 4) by (solve_hyps_min HP1P2P6P8P10eq HP1P2P6P8P10m4).\n\tassert(HP10mtmp : rk(P10 :: nil) >= 1) by (solve_hyps_min HP10eq HP10m1).\n\tassert(Hincl : incl (P10 :: nil) (list_inter (P1 :: P6 :: P10 :: nil) (P2 :: P8 :: P10 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P6 :: P8 :: P10 :: nil) (P1 :: P6 :: P10 :: P2 :: P8 :: P10 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P6 :: P10 :: P2 :: P8 :: P10 :: nil) ((P1 :: P6 :: P10 :: nil) ++ (P2 :: P8 :: P10 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P6P8P10mtmp;try rewrite HT2 in HP1P2P6P8P10mtmp.\n\tassert(HT := rule_2 (P1 :: P6 :: P10 :: nil) (P2 :: P8 :: P10 :: nil) (P10 :: nil) 4 1 2 HP1P2P6P8P10mtmp HP10mtmp HP2P8P10Mtmp Hincl);apply HT.\n}\ntry clear HP1P6P10m2. try clear HP1P2P6P8P10M4. try clear HP1P2P6P8P10m4. \n\nassert(HP1P6P7P10P14m2 : rk(P1 :: P6 :: P7 :: P10 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P6mtmp : rk(P1 :: P6 :: nil) >= 2) by (solve_hyps_min HP1P6eq HP1P6m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P6 :: nil) (P1 :: P6 :: P7 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P6 :: nil) (P1 :: P6 :: P7 :: P10 :: P14 :: nil) 2 2 HP1P6mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P6P7P10P14m1. \n\nassert(HP1P6P7P10P14M3 : rk(P1 :: P6 :: P7 :: P10 :: P14 :: nil) <= 3).\n{\n\tassert(HP1P6P7Mtmp : rk(P1 :: P6 :: P7 :: nil) <= 2) by (solve_hyps_max HP1P6P7eq HP1P6P7M2).\n\tassert(HP6P10P14Mtmp : rk(P6 :: P10 :: P14 :: nil) <= 2) by (solve_hyps_max HP6P10P14eq HP6P10P14M2).\n\tassert(HP6mtmp : rk(P6 :: nil) >= 1) by (solve_hyps_min HP6eq HP6m1).\n\tassert(Hincl : incl (P6 :: nil) (list_inter (P1 :: P6 :: P7 :: nil) (P6 :: P10 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P6 :: P7 :: P10 :: P14 :: nil) (P1 :: P6 :: P7 :: P6 :: P10 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P6 :: P7 :: P6 :: P10 :: P14 :: nil) ((P1 :: P6 :: P7 :: nil) ++ (P6 :: P10 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: P6 :: P7 :: nil) (P6 :: P10 :: P14 :: nil) (P6 :: nil) 2 2 1 HP1P6P7Mtmp HP6P10P14Mtmp HP6mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P6P7P10P14M4. \n\nassert(HP1P6P7P10P14m3 : rk(P1 :: P6 :: P7 :: P10 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P6P10mtmp : rk(P1 :: P6 :: P10 :: nil) >= 3) by (solve_hyps_min HP1P6P10eq HP1P6P10m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P6 :: P10 :: nil) (P1 :: P6 :: P7 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P6 :: P10 :: nil) (P1 :: P6 :: P7 :: P10 :: P14 :: nil) 3 3 HP1P6P10mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P6P10M3. try clear HP1P6P10m3. try clear HP1P6P7P10P14m2. \n\nassert(HP1P2P7P8P10m2 : rk(P1 :: P2 :: P7 :: P8 :: P10 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P7 :: P8 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P7 :: P8 :: P10 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P8P10m1. \n\nassert(HP1P2P7P8P10m3 : rk(P1 :: P2 :: P7 :: P8 :: P10 :: nil) >= 3).\n{\n\tassert(HP1P2P7mtmp : rk(P1 :: P2 :: P7 :: nil) >= 3) by (solve_hyps_min HP1P2P7eq HP1P2P7m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P7 :: nil) (P1 :: P2 :: P7 :: P8 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P7 :: nil) (P1 :: P2 :: P7 :: P8 :: P10 :: nil) 3 3 HP1P2P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P8P10m2. \n\nassert(HP1P2P7P8P10m4 : rk(P1 :: P2 :: P7 :: P8 :: P10 :: nil) >= 4).\n{\n\tassert(HP1P2P7P8mtmp : rk(P1 :: P2 :: P7 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P7P8eq HP1P2P7P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P7 :: P8 :: nil) (P1 :: P2 :: P7 :: P8 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P7 :: P8 :: nil) (P1 :: P2 :: P7 :: P8 :: P10 :: nil) 4 4 HP1P2P7P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P8P10m3. \n\nassert(HP1P7P10m2 : rk(P1 :: P7 :: P10 :: nil) >= 2).\n{\n\tassert(HP1P7mtmp : rk(P1 :: P7 :: nil) >= 2) by (solve_hyps_min HP1P7eq HP1P7m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P7 :: nil) (P1 :: P7 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P7 :: nil) (P1 :: P7 :: P10 :: nil) 2 2 HP1P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P7P10m1. \n\nassert(HP1P7P10m3 : rk(P1 :: P7 :: P10 :: nil) >= 3).\n{\n\tassert(HP2P8P10Mtmp : rk(P2 :: P8 :: P10 :: nil) <= 2) by (solve_hyps_max HP2P8P10eq HP2P8P10M2).\n\tassert(HP1P2P7P8P10mtmp : rk(P1 :: P2 :: P7 :: P8 :: P10 :: nil) >= 4) by (solve_hyps_min HP1P2P7P8P10eq HP1P2P7P8P10m4).\n\tassert(HP10mtmp : rk(P10 :: nil) >= 1) by (solve_hyps_min HP10eq HP10m1).\n\tassert(Hincl : incl (P10 :: nil) (list_inter (P1 :: P7 :: P10 :: nil) (P2 :: P8 :: P10 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P7 :: P8 :: P10 :: nil) (P1 :: P7 :: P10 :: P2 :: P8 :: P10 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P7 :: P10 :: P2 :: P8 :: P10 :: nil) ((P1 :: P7 :: P10 :: nil) ++ (P2 :: P8 :: P10 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P7P8P10mtmp;try rewrite HT2 in HP1P2P7P8P10mtmp.\n\tassert(HT := rule_2 (P1 :: P7 :: P10 :: nil) (P2 :: P8 :: P10 :: nil) (P10 :: nil) 4 1 2 HP1P2P7P8P10mtmp HP10mtmp HP2P8P10Mtmp Hincl);apply HT.\n}\ntry clear HP1P7P10m2. \n\nassert(HP1P7P10P14m2 : rk(P1 :: P7 :: P10 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P7mtmp : rk(P1 :: P7 :: nil) >= 2) by (solve_hyps_min HP1P7eq HP1P7m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P7 :: nil) (P1 :: P7 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P7 :: nil) (P1 :: P7 :: P10 :: P14 :: nil) 2 2 HP1P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P7P10P14m1. \n\nassert(HP1P7P10P14m3 : rk(P1 :: P7 :: P10 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P7P10mtmp : rk(P1 :: P7 :: P10 :: nil) >= 3) by (solve_hyps_min HP1P7P10eq HP1P7P10m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P7 :: P10 :: nil) (P1 :: P7 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P7 :: P10 :: nil) (P1 :: P7 :: P10 :: P14 :: nil) 3 3 HP1P7P10mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P7P10P14m2. \n\nassert(HP1P7P10P14M3 : rk(P1 :: P7 :: P10 :: P14 :: nil) <= 3).\n{\n\tassert(HP1P6P7P10P14Mtmp : rk(P1 :: P6 :: P7 :: P10 :: P14 :: nil) <= 3) by (solve_hyps_max HP1P6P7P10P14eq HP1P6P7P10P14M3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P7 :: P10 :: P14 :: nil) (P1 :: P6 :: P7 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (P1 :: P7 :: P10 :: P14 :: nil) (P1 :: P6 :: P7 :: P10 :: P14 :: nil) 3 3 HP1P6P7P10P14Mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P7P10P14M4. try clear HP1P6P7P10P14M3. try clear HP1P6P7P10P14m3. \n\nassert(HP1P2P4P8P10P11P14m2 : rk(P1 :: P2 :: P4 :: P8 :: P10 :: P11 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P8 :: P10 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P8 :: P10 :: P11 :: P14 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P8P10P11P14m1. \n\nassert(HP1P2P4P8P10P11P14m3 : rk(P1 :: P2 :: P4 :: P8 :: P10 :: P11 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P8 :: P10 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P8 :: P10 :: P11 :: P14 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P8P10P11P14m2. \n\nassert(HP1P2P4P8P10P11P14m4 : rk(P1 :: P2 :: P4 :: P8 :: P10 :: P11 :: P14 :: nil) >= 4).\n{\n\tassert(HP1P2P4P8mtmp : rk(P1 :: P2 :: P4 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8eq HP1P2P4P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P8 :: P10 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P8 :: P10 :: P11 :: P14 :: nil) 4 4 HP1P2P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P8P10P11P14m3. \n\nassert(HP8P10m2 : rk(P8 :: P10 :: nil) >= 2).\n{\n\tassert(HP9Mtmp : rk(P9 :: nil) <= 1) by (solve_hyps_max HP9eq HP9M1).\n\tassert(HP8P9P10mtmp : rk(P8 :: P9 :: P10 :: nil) >= 3) by (solve_hyps_min HP8P9P10eq HP8P9P10m3).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P9 :: nil) (P8 :: P10 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P8 :: P9 :: P10 :: nil) (P9 :: P8 :: P10 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P9 :: P8 :: P10 :: nil) ((P9 :: nil) ++ (P8 :: P10 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP8P9P10mtmp;try rewrite HT2 in HP8P9P10mtmp.\n\tassert(HT := rule_4 (P9 :: nil) (P8 :: P10 :: nil) (nil) 3 0 1 HP8P9P10mtmp Hmtmp HP9Mtmp Hincl); apply HT.\n}\ntry clear HP8P10m1. try clear HP8P9P10M3. try clear HP8P9P10m3. \n\nassert(HP1P4P8P10P11P14m2 : rk(P1 :: P4 :: P8 :: P10 :: P11 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P4mtmp : rk(P1 :: P4 :: nil) >= 2) by (solve_hyps_min HP1P4eq HP1P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: nil) (P1 :: P4 :: P8 :: P10 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: nil) (P1 :: P4 :: P8 :: P10 :: P11 :: P14 :: nil) 2 2 HP1P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P8P10P11P14m1. \n\nassert(HP1P4P8P10P11P14m3 : rk(P1 :: P4 :: P8 :: P10 :: P11 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P4P8mtmp : rk(P1 :: P4 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P4P8eq HP1P4P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: P8 :: nil) (P1 :: P4 :: P8 :: P10 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: P8 :: nil) (P1 :: P4 :: P8 :: P10 :: P11 :: P14 :: nil) 3 3 HP1P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P8P10P11P14m2. \n\nassert(HP1P4P8P10P11P14m4 : rk(P1 :: P4 :: P8 :: P10 :: P11 :: P14 :: nil) >= 4).\n{\n\tassert(HP2P8P10Mtmp : rk(P2 :: P8 :: P10 :: nil) <= 2) by (solve_hyps_max HP2P8P10eq HP2P8P10M2).\n\tassert(HP1P2P4P8P10P11P14mtmp : rk(P1 :: P2 :: P4 :: P8 :: P10 :: P11 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8P10P11P14eq HP1P2P4P8P10P11P14m4).\n\tassert(HP8P10mtmp : rk(P8 :: P10 :: nil) >= 2) by (solve_hyps_min HP8P10eq HP8P10m2).\n\tassert(Hincl : incl (P8 :: P10 :: nil) (list_inter (P2 :: P8 :: P10 :: nil) (P1 :: P4 :: P8 :: P10 :: P11 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P8 :: P10 :: P11 :: P14 :: nil) (P2 :: P8 :: P10 :: P1 :: P4 :: P8 :: P10 :: P11 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P8 :: P10 :: P1 :: P4 :: P8 :: P10 :: P11 :: P14 :: nil) ((P2 :: P8 :: P10 :: nil) ++ (P1 :: P4 :: P8 :: P10 :: P11 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P8P10P11P14mtmp;try rewrite HT2 in HP1P2P4P8P10P11P14mtmp.\n\tassert(HT := rule_4 (P2 :: P8 :: P10 :: nil) (P1 :: P4 :: P8 :: P10 :: P11 :: P14 :: nil) (P8 :: P10 :: nil) 4 2 2 HP1P2P4P8P10P11P14mtmp HP8P10mtmp HP2P8P10Mtmp Hincl); apply HT.\n}\ntry clear HP1P4P8P10P11P14m3. try clear HP1P2P4P8P10P11P14M4. try clear HP1P2P4P8P10P11P14m4. \n\nassert(HP1P10m2 : rk(P1 :: P10 :: nil) >= 2).\n{\n\tassert(HP2P8P10Mtmp : rk(P2 :: P8 :: P10 :: nil) <= 2) by (solve_hyps_max HP2P8P10eq HP2P8P10M2).\n\tassert(HP1P2P8P10mtmp : rk(P1 :: P2 :: P8 :: P10 :: nil) >= 3) by (solve_hyps_min HP1P2P8P10eq HP1P2P8P10m3).\n\tassert(HP10mtmp : rk(P10 :: nil) >= 1) by (solve_hyps_min HP10eq HP10m1).\n\tassert(Hincl : incl (P10 :: nil) (list_inter (P1 :: P10 :: nil) (P2 :: P8 :: P10 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P8 :: P10 :: nil) (P1 :: P10 :: P2 :: P8 :: P10 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P10 :: P2 :: P8 :: P10 :: nil) ((P1 :: P10 :: nil) ++ (P2 :: P8 :: P10 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P8P10mtmp;try rewrite HT2 in HP1P2P8P10mtmp.\n\tassert(HT := rule_2 (P1 :: P10 :: nil) (P2 :: P8 :: P10 :: nil) (P10 :: nil) 3 1 2 HP1P2P8P10mtmp HP10mtmp HP2P8P10Mtmp Hincl);apply HT.\n}\ntry clear HP1P10m1. try clear HP10M1. try clear HP10m1. \n\nassert(HP1P10P11P14m2 : rk(P1 :: P10 :: P11 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P10mtmp : rk(P1 :: P10 :: nil) >= 2) by (solve_hyps_min HP1P10eq HP1P10m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P10 :: nil) (P1 :: P10 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P10 :: nil) (P1 :: P10 :: P11 :: P14 :: nil) 2 2 HP1P10mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P10P11P14m1. \n\nassert(HP1P10P11P14M3 : rk(P1 :: P10 :: P11 :: P14 :: nil) <= 3).\n{\n\tassert(HP1P10P11Mtmp : rk(P1 :: P10 :: P11 :: nil) <= 2) by (solve_hyps_max HP1P10P11eq HP1P10P11M2).\n\tassert(HP14Mtmp : rk(P14 :: nil) <= 1) by (solve_hyps_max HP14eq HP14M1).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P1 :: P10 :: P11 :: nil) (P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P10 :: P11 :: P14 :: nil) (P1 :: P10 :: P11 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P10 :: P11 :: P14 :: nil) ((P1 :: P10 :: P11 :: nil) ++ (P14 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: P10 :: P11 :: nil) (P14 :: nil) (nil) 2 1 0 HP1P10P11Mtmp HP14Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P10P11P14M4. \n\nassert(HP1P10P11P14m3 : rk(P1 :: P10 :: P11 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P4P8P14Mtmp : rk(P1 :: P4 :: P8 :: P14 :: nil) <= 3) by (solve_hyps_max HP1P4P8P14eq HP1P4P8P14M3).\n\tassert(HP1P4P8P10P11P14mtmp : rk(P1 :: P4 :: P8 :: P10 :: P11 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P4P8P10P11P14eq HP1P4P8P10P11P14m4).\n\tassert(HP1P14mtmp : rk(P1 :: P14 :: nil) >= 2) by (solve_hyps_min HP1P14eq HP1P14m2).\n\tassert(Hincl : incl (P1 :: P14 :: nil) (list_inter (P1 :: P4 :: P8 :: P14 :: nil) (P1 :: P10 :: P11 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P4 :: P8 :: P10 :: P11 :: P14 :: nil) (P1 :: P4 :: P8 :: P14 :: P1 :: P10 :: P11 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P8 :: P14 :: P1 :: P10 :: P11 :: P14 :: nil) ((P1 :: P4 :: P8 :: P14 :: nil) ++ (P1 :: P10 :: P11 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P4P8P10P11P14mtmp;try rewrite HT2 in HP1P4P8P10P11P14mtmp.\n\tassert(HT := rule_4 (P1 :: P4 :: P8 :: P14 :: nil) (P1 :: P10 :: P11 :: P14 :: nil) (P1 :: P14 :: nil) 4 2 3 HP1P4P8P10P11P14mtmp HP1P14mtmp HP1P4P8P14Mtmp Hincl); apply HT.\n}\ntry clear HP1P10P11P14m2. try clear HP1P4P8P10P11P14M4. try clear HP1P4P8P10P11P14m4. \n\nassert(HP1P2P4P8P10P14m2 : rk(P1 :: P2 :: P4 :: P8 :: P10 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P8 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P8 :: P10 :: P14 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P8P10P14m1. \n\nassert(HP1P2P4P8P10P14m3 : rk(P1 :: P2 :: P4 :: P8 :: P10 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P8 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P8 :: P10 :: P14 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P8P10P14m2. \n\nassert(HP1P2P4P8P10P14m4 : rk(P1 :: P2 :: P4 :: P8 :: P10 :: P14 :: nil) >= 4).\n{\n\tassert(HP1P2P4P8mtmp : rk(P1 :: P2 :: P4 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8eq HP1P2P4P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P8 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P8 :: P10 :: P14 :: nil) 4 4 HP1P2P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P8P10P14m3. \n\nassert(HP1P4P8P10P14m2 : rk(P1 :: P4 :: P8 :: P10 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P4mtmp : rk(P1 :: P4 :: nil) >= 2) by (solve_hyps_min HP1P4eq HP1P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: nil) (P1 :: P4 :: P8 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: nil) (P1 :: P4 :: P8 :: P10 :: P14 :: nil) 2 2 HP1P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P8P10P14m1. \n\nassert(HP1P4P8P10P14m3 : rk(P1 :: P4 :: P8 :: P10 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P4P8mtmp : rk(P1 :: P4 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P4P8eq HP1P4P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: P8 :: nil) (P1 :: P4 :: P8 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: P8 :: nil) (P1 :: P4 :: P8 :: P10 :: P14 :: nil) 3 3 HP1P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P8P10P14m2. \n\nassert(HP1P4P8P10P14m4 : rk(P1 :: P4 :: P8 :: P10 :: P14 :: nil) >= 4).\n{\n\tassert(HP2P8P10Mtmp : rk(P2 :: P8 :: P10 :: nil) <= 2) by (solve_hyps_max HP2P8P10eq HP2P8P10M2).\n\tassert(HP1P2P4P8P10P14mtmp : rk(P1 :: P2 :: P4 :: P8 :: P10 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8P10P14eq HP1P2P4P8P10P14m4).\n\tassert(HP8P10mtmp : rk(P8 :: P10 :: nil) >= 2) by (solve_hyps_min HP8P10eq HP8P10m2).\n\tassert(Hincl : incl (P8 :: P10 :: nil) (list_inter (P2 :: P8 :: P10 :: nil) (P1 :: P4 :: P8 :: P10 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P8 :: P10 :: P14 :: nil) (P2 :: P8 :: P10 :: P1 :: P4 :: P8 :: P10 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P8 :: P10 :: P1 :: P4 :: P8 :: P10 :: P14 :: nil) ((P2 :: P8 :: P10 :: nil) ++ (P1 :: P4 :: P8 :: P10 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P8P10P14mtmp;try rewrite HT2 in HP1P2P4P8P10P14mtmp.\n\tassert(HT := rule_4 (P2 :: P8 :: P10 :: nil) (P1 :: P4 :: P8 :: P10 :: P14 :: nil) (P8 :: P10 :: nil) 4 2 2 HP1P2P4P8P10P14mtmp HP8P10mtmp HP2P8P10Mtmp Hincl); apply HT.\n}\ntry clear HP1P4P8P10P14m3. try clear HP1P2P4P8P10P14M4. try clear HP1P2P4P8P10P14m4. \n\nassert(HP1P10P14m2 : rk(P1 :: P10 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P10mtmp : rk(P1 :: P10 :: nil) >= 2) by (solve_hyps_min HP1P10eq HP1P10m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P10 :: nil) (P1 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P10 :: nil) (P1 :: P10 :: P14 :: nil) 2 2 HP1P10mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P10M2. try clear HP1P10m2. try clear HP1P10P14m1. \n\nassert(HP1P10P14m3 : rk(P1 :: P10 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P4P8P14Mtmp : rk(P1 :: P4 :: P8 :: P14 :: nil) <= 3) by (solve_hyps_max HP1P4P8P14eq HP1P4P8P14M3).\n\tassert(HP1P4P8P10P14mtmp : rk(P1 :: P4 :: P8 :: P10 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P4P8P10P14eq HP1P4P8P10P14m4).\n\tassert(HP1P14mtmp : rk(P1 :: P14 :: nil) >= 2) by (solve_hyps_min HP1P14eq HP1P14m2).\n\tassert(Hincl : incl (P1 :: P14 :: nil) (list_inter (P1 :: P4 :: P8 :: P14 :: nil) (P1 :: P10 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P4 :: P8 :: P10 :: P14 :: nil) (P1 :: P4 :: P8 :: P14 :: P1 :: P10 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P8 :: P14 :: P1 :: P10 :: P14 :: nil) ((P1 :: P4 :: P8 :: P14 :: nil) ++ (P1 :: P10 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P4P8P10P14mtmp;try rewrite HT2 in HP1P4P8P10P14mtmp.\n\tassert(HT := rule_4 (P1 :: P4 :: P8 :: P14 :: nil) (P1 :: P10 :: P14 :: nil) (P1 :: P14 :: nil) 4 2 3 HP1P4P8P10P14mtmp HP1P14mtmp HP1P4P8P14Mtmp Hincl); apply HT.\n}\ntry clear HP1P10P14m2. try clear HP1P14M2. try clear HP1P14m2. try clear HP1P4P8P10P14M4. try clear HP1P4P8P10P14m4. \n\nassert(HP1P7P10P11P14m2 : rk(P1 :: P7 :: P10 :: P11 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P7mtmp : rk(P1 :: P7 :: nil) >= 2) by (solve_hyps_min HP1P7eq HP1P7m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P7 :: nil) (P1 :: P7 :: P10 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P7 :: nil) (P1 :: P7 :: P10 :: P11 :: P14 :: nil) 2 2 HP1P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P7M2. try clear HP1P7m2. try clear HP1P7P10P11P14m1. \n\nassert(HP1P7P10P11P14m3 : rk(P1 :: P7 :: P10 :: P11 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P7P10mtmp : rk(P1 :: P7 :: P10 :: nil) >= 3) by (solve_hyps_min HP1P7P10eq HP1P7P10m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P7 :: P10 :: nil) (P1 :: P7 :: P10 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P7 :: P10 :: nil) (P1 :: P7 :: P10 :: P11 :: P14 :: nil) 3 3 HP1P7P10mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P7P10M3. try clear HP1P7P10m3. try clear HP1P7P10P11P14m2. \n\nassert(HP1P7P10P11P14M3 : rk(P1 :: P7 :: P10 :: P11 :: P14 :: nil) <= 3).\n{\n\tassert(HP1P7P10P14Mtmp : rk(P1 :: P7 :: P10 :: P14 :: nil) <= 3) by (solve_hyps_max HP1P7P10P14eq HP1P7P10P14M3).\n\tassert(HP1P10P11P14Mtmp : rk(P1 :: P10 :: P11 :: P14 :: nil) <= 3) by (solve_hyps_max HP1P10P11P14eq HP1P10P11P14M3).\n\tassert(HP1P10P14mtmp : rk(P1 :: P10 :: P14 :: nil) >= 3) by (solve_hyps_min HP1P10P14eq HP1P10P14m3).\n\tassert(Hincl : incl (P1 :: P10 :: P14 :: nil) (list_inter (P1 :: P7 :: P10 :: P14 :: nil) (P1 :: P10 :: P11 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P7 :: P10 :: P11 :: P14 :: nil) (P1 :: P7 :: P10 :: P14 :: P1 :: P10 :: P11 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P7 :: P10 :: P14 :: P1 :: P10 :: P11 :: P14 :: nil) ((P1 :: P7 :: P10 :: P14 :: nil) ++ (P1 :: P10 :: P11 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: P7 :: P10 :: P14 :: nil) (P1 :: P10 :: P11 :: P14 :: nil) (P1 :: P10 :: P14 :: nil) 3 3 3 HP1P7P10P14Mtmp HP1P10P11P14Mtmp HP1P10P14mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P7P10P14M3. try clear HP1P7P10P14m3. try clear HP1P10P11P14M3. try clear HP1P10P11P14m3. try clear HP1P10P14M3. try clear HP1P10P14m3. try clear HP1P7P10P11P14M4. \n\nassert(HP1P2P7P10m2 : rk(P1 :: P2 :: P7 :: P10 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P7 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P7 :: P10 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P10m1. \n\nassert(HP1P2P7P10m3 : rk(P1 :: P2 :: P7 :: P10 :: nil) >= 3).\n{\n\tassert(HP1P2P7mtmp : rk(P1 :: P2 :: P7 :: nil) >= 3) by (solve_hyps_min HP1P2P7eq HP1P2P7m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P7 :: nil) (P1 :: P2 :: P7 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P7 :: nil) (P1 :: P2 :: P7 :: P10 :: nil) 3 3 HP1P2P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P10m2. \n\nassert(HP1P2P7P10m4 : rk(P1 :: P2 :: P7 :: P10 :: nil) >= 4).\n{\n\tassert(HP2P8P10Mtmp : rk(P2 :: P8 :: P10 :: nil) <= 2) by (solve_hyps_max HP2P8P10eq HP2P8P10M2).\n\tassert(HP1P2P7P8P10mtmp : rk(P1 :: P2 :: P7 :: P8 :: P10 :: nil) >= 4) by (solve_hyps_min HP1P2P7P8P10eq HP1P2P7P8P10m4).\n\tassert(HP2P10mtmp : rk(P2 :: P10 :: nil) >= 2) by (solve_hyps_min HP2P10eq HP2P10m2).\n\tassert(Hincl : incl (P2 :: P10 :: nil) (list_inter (P1 :: P2 :: P7 :: P10 :: nil) (P2 :: P8 :: P10 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P7 :: P8 :: P10 :: nil) (P1 :: P2 :: P7 :: P10 :: P2 :: P8 :: P10 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P7 :: P10 :: P2 :: P8 :: P10 :: nil) ((P1 :: P2 :: P7 :: P10 :: nil) ++ (P2 :: P8 :: P10 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P7P8P10mtmp;try rewrite HT2 in HP1P2P7P8P10mtmp.\n\tassert(HT := rule_2 (P1 :: P2 :: P7 :: P10 :: nil) (P2 :: P8 :: P10 :: nil) (P2 :: P10 :: nil) 4 2 2 HP1P2P7P8P10mtmp HP2P10mtmp HP2P8P10Mtmp Hincl);apply HT.\n}\ntry clear HP1P2P7P10m3. try clear HP2P10M2. try clear HP2P10m2. try clear HP1P2P7P8P10M4. try clear HP1P2P7P8P10m4. \n\nassert(HP1P2P7P10P11P14m2 : rk(P1 :: P2 :: P7 :: P10 :: P11 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P7 :: P10 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P7 :: P10 :: P11 :: P14 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P10P11P14m1. \n\nassert(HP1P2P7P10P11P14m3 : rk(P1 :: P2 :: P7 :: P10 :: P11 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P2P7mtmp : rk(P1 :: P2 :: P7 :: nil) >= 3) by (solve_hyps_min HP1P2P7eq HP1P2P7m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P7 :: nil) (P1 :: P2 :: P7 :: P10 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P7 :: nil) (P1 :: P2 :: P7 :: P10 :: P11 :: P14 :: nil) 3 3 HP1P2P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P10P11P14m2. \n\nassert(HP1P2P7P10P11P14m4 : rk(P1 :: P2 :: P7 :: P10 :: P11 :: P14 :: nil) >= 4).\n{\n\tassert(HP1P2P7P10mtmp : rk(P1 :: P2 :: P7 :: P10 :: nil) >= 4) by (solve_hyps_min HP1P2P7P10eq HP1P2P7P10m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P7 :: P10 :: nil) (P1 :: P2 :: P7 :: P10 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P7 :: P10 :: nil) (P1 :: P2 :: P7 :: P10 :: P11 :: P14 :: nil) 4 4 HP1P2P7P10mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P10M4. try clear HP1P2P7P10m4. try clear HP1P2P7P10P11P14m3. \n\nassert(HP7P11m2 : rk(P7 :: P11 :: nil) >= 2).\n{\n\tassert(HP2P9P11Mtmp : rk(P2 :: P9 :: P11 :: nil) <= 2) by (solve_hyps_max HP2P9P11eq HP2P9P11M2).\n\tassert(HP2P7P9P11mtmp : rk(P2 :: P7 :: P9 :: P11 :: nil) >= 3) by (solve_hyps_min HP2P7P9P11eq HP2P7P9P11m3).\n\tassert(HP11mtmp : rk(P11 :: nil) >= 1) by (solve_hyps_min HP11eq HP11m1).\n\tassert(Hincl : incl (P11 :: nil) (list_inter (P7 :: P11 :: nil) (P2 :: P9 :: P11 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P7 :: P9 :: P11 :: nil) (P7 :: P11 :: P2 :: P9 :: P11 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P7 :: P11 :: P2 :: P9 :: P11 :: nil) ((P7 :: P11 :: nil) ++ (P2 :: P9 :: P11 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP2P7P9P11mtmp;try rewrite HT2 in HP2P7P9P11mtmp.\n\tassert(HT := rule_2 (P7 :: P11 :: nil) (P2 :: P9 :: P11 :: nil) (P11 :: nil) 3 1 2 HP2P7P9P11mtmp HP11mtmp HP2P9P11Mtmp Hincl);apply HT.\n}\ntry clear HP7P11m1. try clear HP2P7P9P11M3. try clear HP2P7P9P11m3. \n\nassert(HP7P11P14m2 : rk(P7 :: P11 :: P14 :: nil) >= 2).\n{\n\tassert(HP7P11mtmp : rk(P7 :: P11 :: nil) >= 2) by (solve_hyps_min HP7P11eq HP7P11m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P7 :: P11 :: nil) (P7 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P7 :: P11 :: nil) (P7 :: P11 :: P14 :: nil) 2 2 HP7P11mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP7P11P14m1. \n\nassert(HP7P11P14M2 : rk(P7 :: P11 :: P14 :: nil) <= 2).\n{\n\tassert(HP2P7P11P14Mtmp : rk(P2 :: P7 :: P11 :: P14 :: nil) <= 3) by (solve_hyps_max HP2P7P11P14eq HP2P7P11P14M3).\n\tassert(HP1P7P10P11P14Mtmp : rk(P1 :: P7 :: P10 :: P11 :: P14 :: nil) <= 3) by (solve_hyps_max HP1P7P10P11P14eq HP1P7P10P11P14M3).\n\tassert(HP1P2P7P10P11P14mtmp : rk(P1 :: P2 :: P7 :: P10 :: P11 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P2P7P10P11P14eq HP1P2P7P10P11P14m4).\n\tassert(Hincl : incl (P7 :: P11 :: P14 :: nil) (list_inter (P2 :: P7 :: P11 :: P14 :: nil) (P1 :: P7 :: P10 :: P11 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P7 :: P10 :: P11 :: P14 :: nil) (P2 :: P7 :: P11 :: P14 :: P1 :: P7 :: P10 :: P11 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P7 :: P11 :: P14 :: P1 :: P7 :: P10 :: P11 :: P14 :: nil) ((P2 :: P7 :: P11 :: P14 :: nil) ++ (P1 :: P7 :: P10 :: P11 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P7P10P11P14mtmp;try rewrite HT2 in HP1P2P7P10P11P14mtmp.\n\tassert(HT := rule_3 (P2 :: P7 :: P11 :: P14 :: nil) (P1 :: P7 :: P10 :: P11 :: P14 :: nil) (P7 :: P11 :: P14 :: nil) 3 3 4 HP2P7P11P14Mtmp HP1P7P10P11P14Mtmp HP1P2P7P10P11P14mtmp Hincl);apply HT.\n}\ntry clear HP2P7P11P14M3. try clear HP2P7P11P14m3. try clear HP1P7P10P11P14M3. try clear HP1P7P10P11P14m3. try clear HP7P11P14M3. try clear HP1P2P7P10P11P14M4. try clear HP1P2P7P10P11P14m4. \n\nassert(HP1P2P7P9m2 : rk(P1 :: P2 :: P7 :: P9 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P7 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P7 :: P9 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P9m1. \n\nassert(HP1P2P7P9m3 : rk(P1 :: P2 :: P7 :: P9 :: nil) >= 3).\n{\n\tassert(HP1P2P7mtmp : rk(P1 :: P2 :: P7 :: nil) >= 3) by (solve_hyps_min HP1P2P7eq HP1P2P7m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P7 :: nil) (P1 :: P2 :: P7 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P7 :: nil) (P1 :: P2 :: P7 :: P9 :: nil) 3 3 HP1P2P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P9m2. \n\nassert(HP1P2P7P9m4 : rk(P1 :: P2 :: P7 :: P9 :: nil) >= 4).\n{\n\tassert(HP1P8P9Mtmp : rk(P1 :: P8 :: P9 :: nil) <= 2) by (solve_hyps_max HP1P8P9eq HP1P8P9M2).\n\tassert(HP1P2P7P8P9mtmp : rk(P1 :: P2 :: P7 :: P8 :: P9 :: nil) >= 4) by (solve_hyps_min HP1P2P7P8P9eq HP1P2P7P8P9m4).\n\tassert(HP1P9mtmp : rk(P1 :: P9 :: nil) >= 2) by (solve_hyps_min HP1P9eq HP1P9m2).\n\tassert(Hincl : incl (P1 :: P9 :: nil) (list_inter (P1 :: P2 :: P7 :: P9 :: nil) (P1 :: P8 :: P9 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P7 :: P8 :: P9 :: nil) (P1 :: P2 :: P7 :: P9 :: P1 :: P8 :: P9 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P7 :: P9 :: P1 :: P8 :: P9 :: nil) ((P1 :: P2 :: P7 :: P9 :: nil) ++ (P1 :: P8 :: P9 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P7P8P9mtmp;try rewrite HT2 in HP1P2P7P8P9mtmp.\n\tassert(HT := rule_2 (P1 :: P2 :: P7 :: P9 :: nil) (P1 :: P8 :: P9 :: nil) (P1 :: P9 :: nil) 4 2 2 HP1P2P7P8P9mtmp HP1P9mtmp HP1P8P9Mtmp Hincl);apply HT.\n}\ntry clear HP1P2P7P9m3. try clear HP1P2P7P8P9M4. try clear HP1P2P7P8P9m4. \n\nassert(HP1P2P7P9P11m2 : rk(P1 :: P2 :: P7 :: P9 :: P11 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P7 :: P9 :: P11 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P7 :: P9 :: P11 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P9P11m1. \n\nassert(HP1P2P7P9P11m3 : rk(P1 :: P2 :: P7 :: P9 :: P11 :: nil) >= 3).\n{\n\tassert(HP1P2P7mtmp : rk(P1 :: P2 :: P7 :: nil) >= 3) by (solve_hyps_min HP1P2P7eq HP1P2P7m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P7 :: nil) (P1 :: P2 :: P7 :: P9 :: P11 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P7 :: nil) (P1 :: P2 :: P7 :: P9 :: P11 :: nil) 3 3 HP1P2P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P9P11m2. \n\nassert(HP1P2P7P9P11m4 : rk(P1 :: P2 :: P7 :: P9 :: P11 :: nil) >= 4).\n{\n\tassert(HP1P2P7P9mtmp : rk(P1 :: P2 :: P7 :: P9 :: nil) >= 4) by (solve_hyps_min HP1P2P7P9eq HP1P2P7P9m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P7 :: P9 :: nil) (P1 :: P2 :: P7 :: P9 :: P11 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P7 :: P9 :: nil) (P1 :: P2 :: P7 :: P9 :: P11 :: nil) 4 4 HP1P2P7P9mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P9M4. try clear HP1P2P7P9m4. try clear HP1P2P7P9P11m3. \n\nassert(HP1P2P7P11m2 : rk(P1 :: P2 :: P7 :: P11 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P7 :: P11 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P7 :: P11 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P11m1. \n\nassert(HP1P2P7P11m3 : rk(P1 :: P2 :: P7 :: P11 :: nil) >= 3).\n{\n\tassert(HP1P2P7mtmp : rk(P1 :: P2 :: P7 :: nil) >= 3) by (solve_hyps_min HP1P2P7eq HP1P2P7m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P7 :: nil) (P1 :: P2 :: P7 :: P11 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P7 :: nil) (P1 :: P2 :: P7 :: P11 :: nil) 3 3 HP1P2P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P11m2. \n\nassert(HP1P2P7P11m4 : rk(P1 :: P2 :: P7 :: P11 :: nil) >= 4).\n{\n\tassert(HP2P9P11Mtmp : rk(P2 :: P9 :: P11 :: nil) <= 2) by (solve_hyps_max HP2P9P11eq HP2P9P11M2).\n\tassert(HP1P2P7P9P11mtmp : rk(P1 :: P2 :: P7 :: P9 :: P11 :: nil) >= 4) by (solve_hyps_min HP1P2P7P9P11eq HP1P2P7P9P11m4).\n\tassert(HP2P11mtmp : rk(P2 :: P11 :: nil) >= 2) by (solve_hyps_min HP2P11eq HP2P11m2).\n\tassert(Hincl : incl (P2 :: P11 :: nil) (list_inter (P1 :: P2 :: P7 :: P11 :: nil) (P2 :: P9 :: P11 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P7 :: P9 :: P11 :: nil) (P1 :: P2 :: P7 :: P11 :: P2 :: P9 :: P11 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P7 :: P11 :: P2 :: P9 :: P11 :: nil) ((P1 :: P2 :: P7 :: P11 :: nil) ++ (P2 :: P9 :: P11 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P7P9P11mtmp;try rewrite HT2 in HP1P2P7P9P11mtmp.\n\tassert(HT := rule_2 (P1 :: P2 :: P7 :: P11 :: nil) (P2 :: P9 :: P11 :: nil) (P2 :: P11 :: nil) 4 2 2 HP1P2P7P9P11mtmp HP2P11mtmp HP2P9P11Mtmp Hincl);apply HT.\n}\ntry clear HP1P2P7P11m3. try clear HP2P11M2. try clear HP2P11m2. try clear HP1P2P7P9P11M4. try clear HP1P2P7P9P11m4. \n\nassert(HP1P2P7P11P12P14m2 : rk(P1 :: P2 :: P7 :: P11 :: P12 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P7 :: P11 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P7 :: P11 :: P12 :: P14 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P11P12P14m1. \n\nassert(HP1P2P7P11P12P14m3 : rk(P1 :: P2 :: P7 :: P11 :: P12 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P2P7mtmp : rk(P1 :: P2 :: P7 :: nil) >= 3) by (solve_hyps_min HP1P2P7eq HP1P2P7m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P7 :: nil) (P1 :: P2 :: P7 :: P11 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P7 :: nil) (P1 :: P2 :: P7 :: P11 :: P12 :: P14 :: nil) 3 3 HP1P2P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P11P12P14m2. \n\nassert(HP1P2P7P11P12P14m4 : rk(P1 :: P2 :: P7 :: P11 :: P12 :: P14 :: nil) >= 4).\n{\n\tassert(HP1P2P7P11mtmp : rk(P1 :: P2 :: P7 :: P11 :: nil) >= 4) by (solve_hyps_min HP1P2P7P11eq HP1P2P7P11m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P7 :: P11 :: nil) (P1 :: P2 :: P7 :: P11 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P7 :: P11 :: nil) (P1 :: P2 :: P7 :: P11 :: P12 :: P14 :: nil) 4 4 HP1P2P7P11mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P11M4. try clear HP1P2P7P11m4. try clear HP1P2P7P11P12P14m3. \n\nassert(HP7P11P12P14m2 : rk(P7 :: P11 :: P12 :: P14 :: nil) >= 2).\n{\n\tassert(HP7P11mtmp : rk(P7 :: P11 :: nil) >= 2) by (solve_hyps_min HP7P11eq HP7P11m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P7 :: P11 :: nil) (P7 :: P11 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P7 :: P11 :: nil) (P7 :: P11 :: P12 :: P14 :: nil) 2 2 HP7P11mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP7P11M2. try clear HP7P11m2. try clear HP7P11P12P14m1. \n\nassert(HP7P11P12P14m3 : rk(P7 :: P11 :: P12 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P2P12Mtmp : rk(P1 :: P2 :: P12 :: nil) <= 2) by (solve_hyps_max HP1P2P12eq HP1P2P12M2).\n\tassert(HP1P2P7P11P12P14mtmp : rk(P1 :: P2 :: P7 :: P11 :: P12 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P2P7P11P12P14eq HP1P2P7P11P12P14m4).\n\tassert(HP12mtmp : rk(P12 :: nil) >= 1) by (solve_hyps_min HP12eq HP12m1).\n\tassert(Hincl : incl (P12 :: nil) (list_inter (P1 :: P2 :: P12 :: nil) (P7 :: P11 :: P12 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P7 :: P11 :: P12 :: P14 :: nil) (P1 :: P2 :: P12 :: P7 :: P11 :: P12 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P12 :: P7 :: P11 :: P12 :: P14 :: nil) ((P1 :: P2 :: P12 :: nil) ++ (P7 :: P11 :: P12 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P7P11P12P14mtmp;try rewrite HT2 in HP1P2P7P11P12P14mtmp.\n\tassert(HT := rule_4 (P1 :: P2 :: P12 :: nil) (P7 :: P11 :: P12 :: P14 :: nil) (P12 :: nil) 4 1 2 HP1P2P7P11P12P14mtmp HP12mtmp HP1P2P12Mtmp Hincl); apply HT.\n}\ntry clear HP7P11P12P14m2. try clear HP1P2P7P11P12P14M4. try clear HP1P2P7P11P12P14m4. \n\nassert(HP7P11P12P14M3 : rk(P7 :: P11 :: P12 :: P14 :: nil) <= 3).\n{\n\tassert(HP12Mtmp : rk(P12 :: nil) <= 1) by (solve_hyps_max HP12eq HP12M1).\n\tassert(HP7P11P14Mtmp : rk(P7 :: P11 :: P14 :: nil) <= 2) by (solve_hyps_max HP7P11P14eq HP7P11P14M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P12 :: nil) (P7 :: P11 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P7 :: P11 :: P12 :: P14 :: nil) (P12 :: P7 :: P11 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P12 :: P7 :: P11 :: P14 :: nil) ((P12 :: nil) ++ (P7 :: P11 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P12 :: nil) (P7 :: P11 :: P14 :: nil) (nil) 1 2 0 HP12Mtmp HP7P11P14Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP7P11P14M2. try clear HP7P11P14m2. try clear HP7P11P12P14M4. \n\nassert(HP1P2P4P8P9m2 : rk(P1 :: P2 :: P4 :: P8 :: P9 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P8 :: P9 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P8P9m1. \n\nassert(HP1P2P4P8P9m3 : rk(P1 :: P2 :: P4 :: P8 :: P9 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P8 :: P9 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P8P9m2. \n\nassert(HP1P2P4P8P9m4 : rk(P1 :: P2 :: P4 :: P8 :: P9 :: nil) >= 4).\n{\n\tassert(HP1P2P4P8mtmp : rk(P1 :: P2 :: P4 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8eq HP1P2P4P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P8 :: P9 :: nil) 4 4 HP1P2P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P8P9m3. \n\nassert(HP1P2P4P9m2 : rk(P1 :: P2 :: P4 :: P9 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P9 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P9m1. \n\nassert(HP1P2P4P9m3 : rk(P1 :: P2 :: P4 :: P9 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P9 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P9m2. \n\nassert(HP1P2P4P9m4 : rk(P1 :: P2 :: P4 :: P9 :: nil) >= 4).\n{\n\tassert(HP1P8P9Mtmp : rk(P1 :: P8 :: P9 :: nil) <= 2) by (solve_hyps_max HP1P8P9eq HP1P8P9M2).\n\tassert(HP1P2P4P8P9mtmp : rk(P1 :: P2 :: P4 :: P8 :: P9 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8P9eq HP1P2P4P8P9m4).\n\tassert(HP1P9mtmp : rk(P1 :: P9 :: nil) >= 2) by (solve_hyps_min HP1P9eq HP1P9m2).\n\tassert(Hincl : incl (P1 :: P9 :: nil) (list_inter (P1 :: P2 :: P4 :: P9 :: nil) (P1 :: P8 :: P9 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P8 :: P9 :: nil) (P1 :: P2 :: P4 :: P9 :: P1 :: P8 :: P9 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P4 :: P9 :: P1 :: P8 :: P9 :: nil) ((P1 :: P2 :: P4 :: P9 :: nil) ++ (P1 :: P8 :: P9 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P8P9mtmp;try rewrite HT2 in HP1P2P4P8P9mtmp.\n\tassert(HT := rule_2 (P1 :: P2 :: P4 :: P9 :: nil) (P1 :: P8 :: P9 :: nil) (P1 :: P9 :: nil) 4 2 2 HP1P2P4P8P9mtmp HP1P9mtmp HP1P8P9Mtmp Hincl);apply HT.\n}\ntry clear HP1P2P4P9m3. try clear HP1P2P4P8P9M4. try clear HP1P2P4P8P9m4. \n\nassert(HP1P2P4P5P7P9P12P14m2 : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P5P7P9P12P14m1. \n\nassert(HP1P2P4P5P7P9P12P14m3 : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P5P7P9P12P14m2. \n\nassert(HP1P2P4P5P7P9P12P14m4 : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) >= 4).\n{\n\tassert(HP1P2P4P9mtmp : rk(P1 :: P2 :: P4 :: P9 :: nil) >= 4) by (solve_hyps_min HP1P2P4P9eq HP1P2P4P9m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: P9 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: P9 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) 4 4 HP1P2P4P9mtmp Hcomp Hincl);apply HT.\n}\n\n\nassert(HP1P2P4P5P7P9P12m2 : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P5P7P9P12m1. \n\nassert(HP1P2P4P5P7P9P12m3 : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P5P7P9P12m2. \n\nassert(HP1P2P4P5P7P9P12m4 : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: nil) >= 4).\n{\n\tassert(HP1P2P4P9mtmp : rk(P1 :: P2 :: P4 :: P9 :: nil) >= 4) by (solve_hyps_min HP1P2P4P9eq HP1P2P4P9m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: P9 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: P9 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: nil) 4 4 HP1P2P4P9mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P9M4. try clear HP1P2P4P9m4. try clear HP1P2P4P5P7P9P12m3. \n\nassert(HP4P5P9m2 : rk(P4 :: P5 :: P9 :: nil) >= 2).\n{\n\tassert(HP4P5mtmp : rk(P4 :: P5 :: nil) >= 2) by (solve_hyps_min HP4P5eq HP4P5m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P4 :: P5 :: nil) (P4 :: P5 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P4 :: P5 :: nil) (P4 :: P5 :: P9 :: nil) 2 2 HP4P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP4P5P9m1. \n\nassert(HP4P5P9m3 : rk(P4 :: P5 :: P9 :: nil) >= 3).\n{\n\tassert(HP1P2P4P5P7P12Mtmp : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil) <= 3) by (solve_hyps_max HP1P2P4P5P7P12eq HP1P2P4P5P7P12M3).\n\tassert(HP1P2P4P5P7P9P12mtmp : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: nil) >= 4) by (solve_hyps_min HP1P2P4P5P7P9P12eq HP1P2P4P5P7P9P12m4).\n\tassert(HP4P5mtmp : rk(P4 :: P5 :: nil) >= 2) by (solve_hyps_min HP4P5eq HP4P5m2).\n\tassert(Hincl : incl (P4 :: P5 :: nil) (list_inter (P4 :: P5 :: P9 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: nil) (P4 :: P5 :: P9 :: P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P4 :: P5 :: P9 :: P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil) ((P4 :: P5 :: P9 :: nil) ++ (P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P5P7P9P12mtmp;try rewrite HT2 in HP1P2P4P5P7P9P12mtmp.\n\tassert(HT := rule_2 (P4 :: P5 :: P9 :: nil) (P1 :: P2 :: P4 :: P5 :: P7 :: P12 :: nil) (P4 :: P5 :: nil) 4 2 3 HP1P2P4P5P7P9P12mtmp HP4P5mtmp HP1P2P4P5P7P12Mtmp Hincl);apply HT.\n}\ntry clear HP4P5P9m2. try clear HP1P2P4P5P7P12M3. try clear HP1P2P4P5P7P12m3. try clear HP1P2P4P5P7P9P12M4. try clear HP1P2P4P5P7P9P12m4. \n\nassert(HP1P4P5P8P9m2 : rk(P1 :: P4 :: P5 :: P8 :: P9 :: nil) >= 2).\n{\n\tassert(HP1P4mtmp : rk(P1 :: P4 :: nil) >= 2) by (solve_hyps_min HP1P4eq HP1P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: nil) (P1 :: P4 :: P5 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: nil) (P1 :: P4 :: P5 :: P8 :: P9 :: nil) 2 2 HP1P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P5P8P9m1. \n\nassert(HP1P4P5P8P9M3 : rk(P1 :: P4 :: P5 :: P8 :: P9 :: nil) <= 3).\n{\n\tassert(HP1P4P5Mtmp : rk(P1 :: P4 :: P5 :: nil) <= 2) by (solve_hyps_max HP1P4P5eq HP1P4P5M2).\n\tassert(HP1P8P9Mtmp : rk(P1 :: P8 :: P9 :: nil) <= 2) by (solve_hyps_max HP1P8P9eq HP1P8P9M2).\n\tassert(HP1mtmp : rk(P1 :: nil) >= 1) by (solve_hyps_min HP1eq HP1m1).\n\tassert(Hincl : incl (P1 :: nil) (list_inter (P1 :: P4 :: P5 :: nil) (P1 :: P8 :: P9 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P4 :: P5 :: P8 :: P9 :: nil) (P1 :: P4 :: P5 :: P1 :: P8 :: P9 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P5 :: P1 :: P8 :: P9 :: nil) ((P1 :: P4 :: P5 :: nil) ++ (P1 :: P8 :: P9 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: P4 :: P5 :: nil) (P1 :: P8 :: P9 :: nil) (P1 :: nil) 2 2 1 HP1P4P5Mtmp HP1P8P9Mtmp HP1mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P4P5P8P9M4. \n\nassert(HP1P4P5P8P9m3 : rk(P1 :: P4 :: P5 :: P8 :: P9 :: nil) >= 3).\n{\n\tassert(HP1P4P8mtmp : rk(P1 :: P4 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P4P8eq HP1P4P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: P8 :: nil) (P1 :: P4 :: P5 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: P8 :: nil) (P1 :: P4 :: P5 :: P8 :: P9 :: nil) 3 3 HP1P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P5P8P9m2. \n\nassert(HP1P4P5P9m2 : rk(P1 :: P4 :: P5 :: P9 :: nil) >= 2).\n{\n\tassert(HP1P4mtmp : rk(P1 :: P4 :: nil) >= 2) by (solve_hyps_min HP1P4eq HP1P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: nil) (P1 :: P4 :: P5 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: nil) (P1 :: P4 :: P5 :: P9 :: nil) 2 2 HP1P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P5P9m1. \n\nassert(HP1P4P5P9M3 : rk(P1 :: P4 :: P5 :: P9 :: nil) <= 3).\n{\n\tassert(HP1P4P5Mtmp : rk(P1 :: P4 :: P5 :: nil) <= 2) by (solve_hyps_max HP1P4P5eq HP1P4P5M2).\n\tassert(HP9Mtmp : rk(P9 :: nil) <= 1) by (solve_hyps_max HP9eq HP9M1).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P1 :: P4 :: P5 :: nil) (P9 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P4 :: P5 :: P9 :: nil) (P1 :: P4 :: P5 :: P9 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P5 :: P9 :: nil) ((P1 :: P4 :: P5 :: nil) ++ (P9 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: P4 :: P5 :: nil) (P9 :: nil) (nil) 2 1 0 HP1P4P5Mtmp HP9Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P4P5P9M4. \n\nassert(HP1P4P5P9m3 : rk(P1 :: P4 :: P5 :: P9 :: nil) >= 3).\n{\n\tassert(HP1P8P9Mtmp : rk(P1 :: P8 :: P9 :: nil) <= 2) by (solve_hyps_max HP1P8P9eq HP1P8P9M2).\n\tassert(HP1P4P5P8P9mtmp : rk(P1 :: P4 :: P5 :: P8 :: P9 :: nil) >= 3) by (solve_hyps_min HP1P4P5P8P9eq HP1P4P5P8P9m3).\n\tassert(HP1P9mtmp : rk(P1 :: P9 :: nil) >= 2) by (solve_hyps_min HP1P9eq HP1P9m2).\n\tassert(Hincl : incl (P1 :: P9 :: nil) (list_inter (P1 :: P4 :: P5 :: P9 :: nil) (P1 :: P8 :: P9 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P4 :: P5 :: P8 :: P9 :: nil) (P1 :: P4 :: P5 :: P9 :: P1 :: P8 :: P9 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P5 :: P9 :: P1 :: P8 :: P9 :: nil) ((P1 :: P4 :: P5 :: P9 :: nil) ++ (P1 :: P8 :: P9 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P4P5P8P9mtmp;try rewrite HT2 in HP1P4P5P8P9mtmp.\n\tassert(HT := rule_2 (P1 :: P4 :: P5 :: P9 :: nil) (P1 :: P8 :: P9 :: nil) (P1 :: P9 :: nil) 3 2 2 HP1P4P5P8P9mtmp HP1P9mtmp HP1P8P9Mtmp Hincl);apply HT.\n}\ntry clear HP1P4P5P9m2. try clear HP1P9M2. try clear HP1P9m2. try clear HP1P4P5P8P9M3. try clear HP1P4P5P8P9m3. \n\nassert(HP2P4P5P7P9P12P14m2 : rk(P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) >= 2).\n{\n\tassert(HP2P4mtmp : rk(P2 :: P4 :: nil) >= 2) by (solve_hyps_min HP2P4eq HP2P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P4 :: nil) (P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P4 :: nil) (P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) 2 2 HP2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P4P5P7P9P12P14m1. \n\nassert(HP2P4P5P7P9P12P14m3 : rk(P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P4P5Mtmp : rk(P1 :: P4 :: P5 :: nil) <= 2) by (solve_hyps_max HP1P4P5eq HP1P4P5M2).\n\tassert(HP1P2P4P5P7P9P12P14mtmp : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) >= 3) by (solve_hyps_min HP1P2P4P5P7P9P12P14eq HP1P2P4P5P7P9P12P14m3).\n\tassert(HP4P5mtmp : rk(P4 :: P5 :: nil) >= 2) by (solve_hyps_min HP4P5eq HP4P5m2).\n\tassert(Hincl : incl (P4 :: P5 :: nil) (list_inter (P1 :: P4 :: P5 :: nil) (P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) (P1 :: P4 :: P5 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P5 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) ((P1 :: P4 :: P5 :: nil) ++ (P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P5P7P9P12P14mtmp;try rewrite HT2 in HP1P2P4P5P7P9P12P14mtmp.\n\tassert(HT := rule_4 (P1 :: P4 :: P5 :: nil) (P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) (P4 :: P5 :: nil) 3 2 2 HP1P2P4P5P7P9P12P14mtmp HP4P5mtmp HP1P4P5Mtmp Hincl); apply HT.\n}\ntry clear HP2P4P5P7P9P12P14m2. try clear HP1P2P4P5P7P9P12P14M4. try clear HP1P2P4P5P7P9P12P14m3. \n\nassert(HP2P4P5P7P9P12P14m4 : rk(P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) >= 4).\n{\n\tassert(HP1P4P5P9Mtmp : rk(P1 :: P4 :: P5 :: P9 :: nil) <= 3) by (solve_hyps_max HP1P4P5P9eq HP1P4P5P9M3).\n\tassert(HP1P2P4P5P7P9P12P14mtmp : rk(P1 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P2P4P5P7P9P12P14eq HP1P2P4P5P7P9P12P14m4).\n\tassert(HP4P5P9mtmp : rk(P4 :: P5 :: P9 :: nil) >= 3) by (solve_hyps_min HP4P5P9eq HP4P5P9m3).\n\tassert(Hincl : incl (P4 :: P5 :: P9 :: nil) (list_inter (P1 :: P4 :: P5 :: P9 :: nil) (P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) (P1 :: P4 :: P5 :: P9 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P5 :: P9 :: P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) ((P1 :: P4 :: P5 :: P9 :: nil) ++ (P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P5P7P9P12P14mtmp;try rewrite HT2 in HP1P2P4P5P7P9P12P14mtmp.\n\tassert(HT := rule_4 (P1 :: P4 :: P5 :: P9 :: nil) (P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) (P4 :: P5 :: P9 :: nil) 4 3 3 HP1P2P4P5P7P9P12P14mtmp HP4P5P9mtmp HP1P4P5P9Mtmp Hincl); apply HT.\n}\ntry clear HP1P4P5P9M3. try clear HP1P4P5P9m3. try clear HP4P5P9M3. try clear HP4P5P9m3. try clear HP1P2P4P5P7P9P12P14M4. try clear HP1P2P4P5P7P9P12P14m4. \n\nassert(HP1P3P5m2 : rk(P1 :: P3 :: P5 :: nil) >= 2).\n{\n\tassert(HP1P3mtmp : rk(P1 :: P3 :: nil) >= 2) by (solve_hyps_min HP1P3eq HP1P3m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P3 :: nil) (P1 :: P3 :: P5 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P3 :: nil) (P1 :: P3 :: P5 :: nil) 2 2 HP1P3mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P3P5m1. \n\nassert(HP1P3P5m3 : rk(P1 :: P3 :: P5 :: nil) >= 3).\n{\n\tassert(HP1P4P5Mtmp : rk(P1 :: P4 :: P5 :: nil) <= 2) by (solve_hyps_max HP1P4P5eq HP1P4P5M2).\n\tassert(HP1P3P4P5mtmp : rk(P1 :: P3 :: P4 :: P5 :: nil) >= 3) by (solve_hyps_min HP1P3P4P5eq HP1P3P4P5m3).\n\tassert(HP1P5mtmp : rk(P1 :: P5 :: nil) >= 2) by (solve_hyps_min HP1P5eq HP1P5m2).\n\tassert(Hincl : incl (P1 :: P5 :: nil) (list_inter (P1 :: P3 :: P5 :: nil) (P1 :: P4 :: P5 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P3 :: P4 :: P5 :: nil) (P1 :: P3 :: P5 :: P1 :: P4 :: P5 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P3 :: P5 :: P1 :: P4 :: P5 :: nil) ((P1 :: P3 :: P5 :: nil) ++ (P1 :: P4 :: P5 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P3P4P5mtmp;try rewrite HT2 in HP1P3P4P5mtmp.\n\tassert(HT := rule_2 (P1 :: P3 :: P5 :: nil) (P1 :: P4 :: P5 :: nil) (P1 :: P5 :: nil) 3 2 2 HP1P3P4P5mtmp HP1P5mtmp HP1P4P5Mtmp Hincl);apply HT.\n}\ntry clear HP1P3P5m2. try clear HP1P3P4P5M3. try clear HP1P3P4P5m3. \n\nassert(HP1P3P5P8m2 : rk(P1 :: P3 :: P5 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P3mtmp : rk(P1 :: P3 :: nil) >= 2) by (solve_hyps_min HP1P3eq HP1P3m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P3 :: nil) (P1 :: P3 :: P5 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P3 :: nil) (P1 :: P3 :: P5 :: P8 :: nil) 2 2 HP1P3mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P3P5P8m1. \n\nassert(HP1P3P5P8m3 : rk(P1 :: P3 :: P5 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P3P5mtmp : rk(P1 :: P3 :: P5 :: nil) >= 3) by (solve_hyps_min HP1P3P5eq HP1P3P5m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P3 :: P5 :: nil) (P1 :: P3 :: P5 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P3 :: P5 :: nil) (P1 :: P3 :: P5 :: P8 :: nil) 3 3 HP1P3P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P3P5P8m2. \n\nassert(HP1P3P5P8m4 : rk(P1 :: P3 :: P5 :: P8 :: nil) >= 4).\n{\n\tassert(HP1P4P5P8Mtmp : rk(P1 :: P4 :: P5 :: P8 :: nil) <= 3) by (solve_hyps_max HP1P4P5P8eq HP1P4P5P8M3).\n\tassert(HP1P3P4P5P8mtmp : rk(P1 :: P3 :: P4 :: P5 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P3P4P5P8eq HP1P3P4P5P8m4).\n\tassert(HP1P5P8mtmp : rk(P1 :: P5 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P5P8eq HP1P5P8m3).\n\tassert(Hincl : incl (P1 :: P5 :: P8 :: nil) (list_inter (P1 :: P3 :: P5 :: P8 :: nil) (P1 :: P4 :: P5 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P3 :: P4 :: P5 :: P8 :: nil) (P1 :: P3 :: P5 :: P8 :: P1 :: P4 :: P5 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P3 :: P5 :: P8 :: P1 :: P4 :: P5 :: P8 :: nil) ((P1 :: P3 :: P5 :: P8 :: nil) ++ (P1 :: P4 :: P5 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P3P4P5P8mtmp;try rewrite HT2 in HP1P3P4P5P8mtmp.\n\tassert(HT := rule_2 (P1 :: P3 :: P5 :: P8 :: nil) (P1 :: P4 :: P5 :: P8 :: nil) (P1 :: P5 :: P8 :: nil) 4 3 3 HP1P3P4P5P8mtmp HP1P5P8mtmp HP1P4P5P8Mtmp Hincl);apply HT.\n}\ntry clear HP1P3P5P8m3. try clear HP1P3P4P5P8M4. try clear HP1P3P4P5P8m4. \n\nassert(HP1P3P5P6P8m2 : rk(P1 :: P3 :: P5 :: P6 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P3mtmp : rk(P1 :: P3 :: nil) >= 2) by (solve_hyps_min HP1P3eq HP1P3m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P3 :: nil) (P1 :: P3 :: P5 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P3 :: nil) (P1 :: P3 :: P5 :: P6 :: P8 :: nil) 2 2 HP1P3mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P3P5P6P8m1. \n\nassert(HP1P3P5P6P8m3 : rk(P1 :: P3 :: P5 :: P6 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P3P5mtmp : rk(P1 :: P3 :: P5 :: nil) >= 3) by (solve_hyps_min HP1P3P5eq HP1P3P5m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P3 :: P5 :: nil) (P1 :: P3 :: P5 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P3 :: P5 :: nil) (P1 :: P3 :: P5 :: P6 :: P8 :: nil) 3 3 HP1P3P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P3P5P6P8m2. \n\nassert(HP1P3P5P6P8m4 : rk(P1 :: P3 :: P5 :: P6 :: P8 :: nil) >= 4).\n{\n\tassert(HP1P3P5P8mtmp : rk(P1 :: P3 :: P5 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P3P5P8eq HP1P3P5P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P3 :: P5 :: P8 :: nil) (P1 :: P3 :: P5 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P3 :: P5 :: P8 :: nil) (P1 :: P3 :: P5 :: P6 :: P8 :: nil) 4 4 HP1P3P5P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P3P5P8M4. try clear HP1P3P5P8m4. try clear HP1P3P5P6P8m3. \n\nassert(HP1P2P4P5P6P8m2 : rk(P1 :: P2 :: P4 :: P5 :: P6 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P5 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P5 :: P6 :: P8 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P5P6P8m1. \n\nassert(HP1P2P4P5P6P8m3 : rk(P1 :: P2 :: P4 :: P5 :: P6 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P5 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P5 :: P6 :: P8 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P5P6P8m2. \n\nassert(HP1P2P4P5P6P8m4 : rk(P1 :: P2 :: P4 :: P5 :: P6 :: P8 :: nil) >= 4).\n{\n\tassert(HP1P2P4P8mtmp : rk(P1 :: P2 :: P4 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8eq HP1P2P4P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P5 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P5 :: P6 :: P8 :: nil) 4 4 HP1P2P4P8mtmp Hcomp Hincl);apply HT.\n}\n\n\nassert(HP2P4P5P6P8m2 : rk(P2 :: P4 :: P5 :: P6 :: P8 :: nil) >= 2).\n{\n\tassert(HP2P4mtmp : rk(P2 :: P4 :: nil) >= 2) by (solve_hyps_min HP2P4eq HP2P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P4 :: nil) (P2 :: P4 :: P5 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P4 :: nil) (P2 :: P4 :: P5 :: P6 :: P8 :: nil) 2 2 HP2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P4M2. try clear HP2P4m2. try clear HP2P4P5P6P8m1. \n\nassert(HP2P4P5P6P8m3 : rk(P2 :: P4 :: P5 :: P6 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P4P5Mtmp : rk(P1 :: P4 :: P5 :: nil) <= 2) by (solve_hyps_max HP1P4P5eq HP1P4P5M2).\n\tassert(HP1P2P4P5P6P8mtmp : rk(P1 :: P2 :: P4 :: P5 :: P6 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P2P4P5P6P8eq HP1P2P4P5P6P8m3).\n\tassert(HP4P5mtmp : rk(P4 :: P5 :: nil) >= 2) by (solve_hyps_min HP4P5eq HP4P5m2).\n\tassert(Hincl : incl (P4 :: P5 :: nil) (list_inter (P1 :: P4 :: P5 :: nil) (P2 :: P4 :: P5 :: P6 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P5 :: P6 :: P8 :: nil) (P1 :: P4 :: P5 :: P2 :: P4 :: P5 :: P6 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P5 :: P2 :: P4 :: P5 :: P6 :: P8 :: nil) ((P1 :: P4 :: P5 :: nil) ++ (P2 :: P4 :: P5 :: P6 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P5P6P8mtmp;try rewrite HT2 in HP1P2P4P5P6P8mtmp.\n\tassert(HT := rule_4 (P1 :: P4 :: P5 :: nil) (P2 :: P4 :: P5 :: P6 :: P8 :: nil) (P4 :: P5 :: nil) 3 2 2 HP1P2P4P5P6P8mtmp HP4P5mtmp HP1P4P5Mtmp Hincl); apply HT.\n}\ntry clear HP1P4P5M2. try clear HP1P4P5m2. try clear HP2P4P5P6P8m2. try clear HP1P2P4P5P6P8M4. try clear HP1P2P4P5P6P8m3. \n\nassert(HP2P4P5P6P8m4 : rk(P2 :: P4 :: P5 :: P6 :: P8 :: nil) >= 4).\n{\n\tassert(HP1P4P5P8Mtmp : rk(P1 :: P4 :: P5 :: P8 :: nil) <= 3) by (solve_hyps_max HP1P4P5P8eq HP1P4P5P8M3).\n\tassert(HP1P2P4P5P6P8mtmp : rk(P1 :: P2 :: P4 :: P5 :: P6 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P5P6P8eq HP1P2P4P5P6P8m4).\n\tassert(HP4P5P8mtmp : rk(P4 :: P5 :: P8 :: nil) >= 3) by (solve_hyps_min HP4P5P8eq HP4P5P8m3).\n\tassert(Hincl : incl (P4 :: P5 :: P8 :: nil) (list_inter (P1 :: P4 :: P5 :: P8 :: nil) (P2 :: P4 :: P5 :: P6 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P5 :: P6 :: P8 :: nil) (P1 :: P4 :: P5 :: P8 :: P2 :: P4 :: P5 :: P6 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P5 :: P8 :: P2 :: P4 :: P5 :: P6 :: P8 :: nil) ((P1 :: P4 :: P5 :: P8 :: nil) ++ (P2 :: P4 :: P5 :: P6 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P5P6P8mtmp;try rewrite HT2 in HP1P2P4P5P6P8mtmp.\n\tassert(HT := rule_4 (P1 :: P4 :: P5 :: P8 :: nil) (P2 :: P4 :: P5 :: P6 :: P8 :: nil) (P4 :: P5 :: P8 :: nil) 4 3 3 HP1P2P4P5P6P8mtmp HP4P5P8mtmp HP1P4P5P8Mtmp Hincl); apply HT.\n}\ntry clear HP1P4P5P8M3. try clear HP1P4P5P8m3. try clear HP4P5P8M3. try clear HP4P5P8m3. try clear HP1P2P4P5P6P8M4. try clear HP1P2P4P5P6P8m4. \n\nassert(HP5P6P8m2 : rk(P5 :: P6 :: P8 :: nil) >= 2).\n{\n\tassert(HP2P4P6Mtmp : rk(P2 :: P4 :: P6 :: nil) <= 2) by (solve_hyps_max HP2P4P6eq HP2P4P6M2).\n\tassert(HP2P4P5P6P8mtmp : rk(P2 :: P4 :: P5 :: P6 :: P8 :: nil) >= 3) by (solve_hyps_min HP2P4P5P6P8eq HP2P4P5P6P8m3).\n\tassert(HP6mtmp : rk(P6 :: nil) >= 1) by (solve_hyps_min HP6eq HP6m1).\n\tassert(Hincl : incl (P6 :: nil) (list_inter (P2 :: P4 :: P6 :: nil) (P5 :: P6 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P4 :: P5 :: P6 :: P8 :: nil) (P2 :: P4 :: P6 :: P5 :: P6 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P4 :: P6 :: P5 :: P6 :: P8 :: nil) ((P2 :: P4 :: P6 :: nil) ++ (P5 :: P6 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP2P4P5P6P8mtmp;try rewrite HT2 in HP2P4P5P6P8mtmp.\n\tassert(HT := rule_4 (P2 :: P4 :: P6 :: nil) (P5 :: P6 :: P8 :: nil) (P6 :: nil) 3 1 2 HP2P4P5P6P8mtmp HP6mtmp HP2P4P6Mtmp Hincl); apply HT.\n}\ntry clear HP2P4P6M2. try clear HP2P4P6m2. try clear HP5P6P8m1. try clear HP6M1. try clear HP6m1. try clear HP2P4P5P6P8M4. try clear HP2P4P5P6P8m3. \n\nassert(HP5P6P8m3 : rk(P5 :: P6 :: P8 :: nil) >= 3).\n{\n\tassert(HP2P4P6P8Mtmp : rk(P2 :: P4 :: P6 :: P8 :: nil) <= 3) by (solve_hyps_max HP2P4P6P8eq HP2P4P6P8M3).\n\tassert(HP2P4P5P6P8mtmp : rk(P2 :: P4 :: P5 :: P6 :: P8 :: nil) >= 4) by (solve_hyps_min HP2P4P5P6P8eq HP2P4P5P6P8m4).\n\tassert(HP6P8mtmp : rk(P6 :: P8 :: nil) >= 2) by (solve_hyps_min HP6P8eq HP6P8m2).\n\tassert(Hincl : incl (P6 :: P8 :: nil) (list_inter (P2 :: P4 :: P6 :: P8 :: nil) (P5 :: P6 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P4 :: P5 :: P6 :: P8 :: nil) (P2 :: P4 :: P6 :: P8 :: P5 :: P6 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P4 :: P6 :: P8 :: P5 :: P6 :: P8 :: nil) ((P2 :: P4 :: P6 :: P8 :: nil) ++ (P5 :: P6 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP2P4P5P6P8mtmp;try rewrite HT2 in HP2P4P5P6P8mtmp.\n\tassert(HT := rule_4 (P2 :: P4 :: P6 :: P8 :: nil) (P5 :: P6 :: P8 :: nil) (P6 :: P8 :: nil) 4 2 3 HP2P4P5P6P8mtmp HP6P8mtmp HP2P4P6P8Mtmp Hincl); apply HT.\n}\ntry clear HP2P4P6P8M3. try clear HP2P4P6P8m3. try clear HP5P6P8m2. try clear HP6P8M2. try clear HP6P8m2. try clear HP2P4P5P6P8M4. try clear HP2P4P5P6P8m4. \n\nassert(HP1P3P5P6M3 : rk(P1 :: P3 :: P5 :: P6 :: nil) <= 3).\n{\n\tassert(HP1Mtmp : rk(P1 :: nil) <= 1) by (solve_hyps_max HP1eq HP1M1).\n\tassert(HP3P5P6Mtmp : rk(P3 :: P5 :: P6 :: nil) <= 2) by (solve_hyps_max HP3P5P6eq HP3P5P6M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P1 :: nil) (P3 :: P5 :: P6 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P3 :: P5 :: P6 :: nil) (P1 :: P3 :: P5 :: P6 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P3 :: P5 :: P6 :: nil) ((P1 :: nil) ++ (P3 :: P5 :: P6 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: nil) (P3 :: P5 :: P6 :: nil) (nil) 1 2 0 HP1Mtmp HP3P5P6Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P3P5P6M4. \n\nassert(HP1P3P5P6m2 : rk(P1 :: P3 :: P5 :: P6 :: nil) >= 2).\n{\n\tassert(HP1P3mtmp : rk(P1 :: P3 :: nil) >= 2) by (solve_hyps_min HP1P3eq HP1P3m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P3 :: nil) (P1 :: P3 :: P5 :: P6 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P3 :: nil) (P1 :: P3 :: P5 :: P6 :: nil) 2 2 HP1P3mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P3M2. try clear HP1P3m2. try clear HP1P3P5P6m1. \n\nassert(HP1P3P5P6m3 : rk(P1 :: P3 :: P5 :: P6 :: nil) >= 3).\n{\n\tassert(HP1P3P5mtmp : rk(P1 :: P3 :: P5 :: nil) >= 3) by (solve_hyps_min HP1P3P5eq HP1P3P5m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P3 :: P5 :: nil) (P1 :: P3 :: P5 :: P6 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P3 :: P5 :: nil) (P1 :: P3 :: P5 :: P6 :: nil) 3 3 HP1P3P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P3P5M3. try clear HP1P3P5m3. try clear HP1P3P5P6m2. \n\nassert(HP5P6m2 : rk(P5 :: P6 :: nil) >= 2).\n{\n\tassert(HP4Mtmp : rk(P4 :: nil) <= 1) by (solve_hyps_max HP4eq HP4M1).\n\tassert(HP4P5P6mtmp : rk(P4 :: P5 :: P6 :: nil) >= 3) by (solve_hyps_min HP4P5P6eq HP4P5P6m3).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P4 :: nil) (P5 :: P6 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P4 :: P5 :: P6 :: nil) (P4 :: P5 :: P6 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P4 :: P5 :: P6 :: nil) ((P4 :: nil) ++ (P5 :: P6 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP4P5P6mtmp;try rewrite HT2 in HP4P5P6mtmp.\n\tassert(HT := rule_4 (P4 :: nil) (P5 :: P6 :: nil) (nil) 3 0 1 HP4P5P6mtmp Hmtmp HP4Mtmp Hincl); apply HT.\n}\ntry clear HP4M1. try clear HP4m1. try clear HP5P6m1. try clear HP4P5P6M3. try clear HP4P5P6m3. \n\nassert(HP1P5P6m2 : rk(P1 :: P5 :: P6 :: nil) >= 2).\n{\n\tassert(HP1P5mtmp : rk(P1 :: P5 :: nil) >= 2) by (solve_hyps_min HP1P5eq HP1P5m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P5 :: nil) (P1 :: P5 :: P6 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P5 :: nil) (P1 :: P5 :: P6 :: nil) 2 2 HP1P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P5P6m1. \n\nassert(HP1P5P6m3 : rk(P1 :: P5 :: P6 :: nil) >= 3).\n{\n\tassert(HP3P5P6Mtmp : rk(P3 :: P5 :: P6 :: nil) <= 2) by (solve_hyps_max HP3P5P6eq HP3P5P6M2).\n\tassert(HP1P3P5P6mtmp : rk(P1 :: P3 :: P5 :: P6 :: nil) >= 3) by (solve_hyps_min HP1P3P5P6eq HP1P3P5P6m3).\n\tassert(HP5P6mtmp : rk(P5 :: P6 :: nil) >= 2) by (solve_hyps_min HP5P6eq HP5P6m2).\n\tassert(Hincl : incl (P5 :: P6 :: nil) (list_inter (P1 :: P5 :: P6 :: nil) (P3 :: P5 :: P6 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P3 :: P5 :: P6 :: nil) (P1 :: P5 :: P6 :: P3 :: P5 :: P6 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P5 :: P6 :: P3 :: P5 :: P6 :: nil) ((P1 :: P5 :: P6 :: nil) ++ (P3 :: P5 :: P6 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P3P5P6mtmp;try rewrite HT2 in HP1P3P5P6mtmp.\n\tassert(HT := rule_2 (P1 :: P5 :: P6 :: nil) (P3 :: P5 :: P6 :: nil) (P5 :: P6 :: nil) 3 2 2 HP1P3P5P6mtmp HP5P6mtmp HP3P5P6Mtmp Hincl);apply HT.\n}\ntry clear HP1P5P6m2. try clear HP3P5P6M2. try clear HP3P5P6m2. try clear HP5P6M2. try clear HP5P6m2. try clear HP1P3P5P6M3. try clear HP1P3P5P6m3. \n\nassert(HP1P5P6P8m2 : rk(P1 :: P5 :: P6 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P5mtmp : rk(P1 :: P5 :: nil) >= 2) by (solve_hyps_min HP1P5eq HP1P5m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P5 :: nil) (P1 :: P5 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P5 :: nil) (P1 :: P5 :: P6 :: P8 :: nil) 2 2 HP1P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P5P6P8m1. \n\nassert(HP1P5P6P8m3 : rk(P1 :: P5 :: P6 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P5P6mtmp : rk(P1 :: P5 :: P6 :: nil) >= 3) by (solve_hyps_min HP1P5P6eq HP1P5P6m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P5 :: P6 :: nil) (P1 :: P5 :: P6 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P5 :: P6 :: nil) (P1 :: P5 :: P6 :: P8 :: nil) 3 3 HP1P5P6mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P5P6P8m2. \n\nassert(HP1P5P6P8m4 : rk(P1 :: P5 :: P6 :: P8 :: nil) >= 4).\n{\n\tassert(HP3P5P6P8Mtmp : rk(P3 :: P5 :: P6 :: P8 :: nil) <= 3) by (solve_hyps_max HP3P5P6P8eq HP3P5P6P8M3).\n\tassert(HP1P3P5P6P8mtmp : rk(P1 :: P3 :: P5 :: P6 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P3P5P6P8eq HP1P3P5P6P8m4).\n\tassert(HP5P6P8mtmp : rk(P5 :: P6 :: P8 :: nil) >= 3) by (solve_hyps_min HP5P6P8eq HP5P6P8m3).\n\tassert(Hincl : incl (P5 :: P6 :: P8 :: nil) (list_inter (P1 :: P5 :: P6 :: P8 :: nil) (P3 :: P5 :: P6 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P3 :: P5 :: P6 :: P8 :: nil) (P1 :: P5 :: P6 :: P8 :: P3 :: P5 :: P6 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P5 :: P6 :: P8 :: P3 :: P5 :: P6 :: P8 :: nil) ((P1 :: P5 :: P6 :: P8 :: nil) ++ (P3 :: P5 :: P6 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P3P5P6P8mtmp;try rewrite HT2 in HP1P3P5P6P8mtmp.\n\tassert(HT := rule_2 (P1 :: P5 :: P6 :: P8 :: nil) (P3 :: P5 :: P6 :: P8 :: nil) (P5 :: P6 :: P8 :: nil) 4 3 3 HP1P3P5P6P8mtmp HP5P6P8mtmp HP3P5P6P8Mtmp Hincl);apply HT.\n}\ntry clear HP1P5P6P8m3. try clear HP3P5P6P8M3. try clear HP3P5P6P8m3. try clear HP5P6P8M3. try clear HP5P6P8m3. try clear HP1P3P5P6P8M4. try clear HP1P3P5P6P8m4. \n\nassert(HP1P5P6P7P8m2 : rk(P1 :: P5 :: P6 :: P7 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P5mtmp : rk(P1 :: P5 :: nil) >= 2) by (solve_hyps_min HP1P5eq HP1P5m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P5 :: nil) (P1 :: P5 :: P6 :: P7 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P5 :: nil) (P1 :: P5 :: P6 :: P7 :: P8 :: nil) 2 2 HP1P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P5P6P7P8m1. \n\nassert(HP1P5P6P7P8m3 : rk(P1 :: P5 :: P6 :: P7 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P5P6mtmp : rk(P1 :: P5 :: P6 :: nil) >= 3) by (solve_hyps_min HP1P5P6eq HP1P5P6m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P5 :: P6 :: nil) (P1 :: P5 :: P6 :: P7 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P5 :: P6 :: nil) (P1 :: P5 :: P6 :: P7 :: P8 :: nil) 3 3 HP1P5P6mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P5P6P7P8m2. \n\nassert(HP1P5P6P7P8m4 : rk(P1 :: P5 :: P6 :: P7 :: P8 :: nil) >= 4).\n{\n\tassert(HP1P5P6P8mtmp : rk(P1 :: P5 :: P6 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P5P6P8eq HP1P5P6P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P5 :: P6 :: P8 :: nil) (P1 :: P5 :: P6 :: P7 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P5 :: P6 :: P8 :: nil) (P1 :: P5 :: P6 :: P7 :: P8 :: nil) 4 4 HP1P5P6P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P5P6P8M4. try clear HP1P5P6P8m4. try clear HP1P5P6P7P8m3. \n\nassert(HP1P5P6P7M3 : rk(P1 :: P5 :: P6 :: P7 :: nil) <= 3).\n{\n\tassert(HP5Mtmp : rk(P5 :: nil) <= 1) by (solve_hyps_max HP5eq HP5M1).\n\tassert(HP1P6P7Mtmp : rk(P1 :: P6 :: P7 :: nil) <= 2) by (solve_hyps_max HP1P6P7eq HP1P6P7M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P5 :: nil) (P1 :: P6 :: P7 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P5 :: P6 :: P7 :: nil) (P5 :: P1 :: P6 :: P7 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P5 :: P1 :: P6 :: P7 :: nil) ((P5 :: nil) ++ (P1 :: P6 :: P7 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P5 :: nil) (P1 :: P6 :: P7 :: nil) (nil) 1 2 0 HP5Mtmp HP1P6P7Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP5M1. try clear HP5m1. try clear HP1P5P6P7M4. \n\nassert(HP1P5P6P7m2 : rk(P1 :: P5 :: P6 :: P7 :: nil) >= 2).\n{\n\tassert(HP1P5mtmp : rk(P1 :: P5 :: nil) >= 2) by (solve_hyps_min HP1P5eq HP1P5m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P5 :: nil) (P1 :: P5 :: P6 :: P7 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P5 :: nil) (P1 :: P5 :: P6 :: P7 :: nil) 2 2 HP1P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P5P6P7m1. \n\nassert(HP1P5P6P7m3 : rk(P1 :: P5 :: P6 :: P7 :: nil) >= 3).\n{\n\tassert(HP1P5P6mtmp : rk(P1 :: P5 :: P6 :: nil) >= 3) by (solve_hyps_min HP1P5P6eq HP1P5P6m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P5 :: P6 :: nil) (P1 :: P5 :: P6 :: P7 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P5 :: P6 :: nil) (P1 :: P5 :: P6 :: P7 :: nil) 3 3 HP1P5P6mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P5P6M3. try clear HP1P5P6m3. try clear HP1P5P6P7m2. \n\nassert(HP5P7m2 : rk(P5 :: P7 :: nil) >= 2).\n{\n\tassert(HP1P6P7Mtmp : rk(P1 :: P6 :: P7 :: nil) <= 2) by (solve_hyps_max HP1P6P7eq HP1P6P7M2).\n\tassert(HP1P5P6P7mtmp : rk(P1 :: P5 :: P6 :: P7 :: nil) >= 3) by (solve_hyps_min HP1P5P6P7eq HP1P5P6P7m3).\n\tassert(HP7mtmp : rk(P7 :: nil) >= 1) by (solve_hyps_min HP7eq HP7m1).\n\tassert(Hincl : incl (P7 :: nil) (list_inter (P5 :: P7 :: nil) (P1 :: P6 :: P7 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P5 :: P6 :: P7 :: nil) (P5 :: P7 :: P1 :: P6 :: P7 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P5 :: P7 :: P1 :: P6 :: P7 :: nil) ((P5 :: P7 :: nil) ++ (P1 :: P6 :: P7 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P5P6P7mtmp;try rewrite HT2 in HP1P5P6P7mtmp.\n\tassert(HT := rule_2 (P5 :: P7 :: nil) (P1 :: P6 :: P7 :: nil) (P7 :: nil) 3 1 2 HP1P5P6P7mtmp HP7mtmp HP1P6P7Mtmp Hincl);apply HT.\n}\ntry clear HP5P7m1. try clear HP1P6P7M2. try clear HP1P6P7m2. try clear HP1P5P6P7M3. try clear HP1P5P6P7m3. \n\nassert(HP5P7P8m2 : rk(P5 :: P7 :: P8 :: nil) >= 2).\n{\n\tassert(HP5P7mtmp : rk(P5 :: P7 :: nil) >= 2) by (solve_hyps_min HP5P7eq HP5P7m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P5 :: P7 :: nil) (P5 :: P7 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P5 :: P7 :: nil) (P5 :: P7 :: P8 :: nil) 2 2 HP5P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP5P7P8m1. \n\nassert(HP5P7P8m3 : rk(P5 :: P7 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P6P7P8Mtmp : rk(P1 :: P6 :: P7 :: P8 :: nil) <= 3) by (solve_hyps_max HP1P6P7P8eq HP1P6P7P8M3).\n\tassert(HP1P5P6P7P8mtmp : rk(P1 :: P5 :: P6 :: P7 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P5P6P7P8eq HP1P5P6P7P8m4).\n\tassert(HP7P8mtmp : rk(P7 :: P8 :: nil) >= 2) by (solve_hyps_min HP7P8eq HP7P8m2).\n\tassert(Hincl : incl (P7 :: P8 :: nil) (list_inter (P5 :: P7 :: P8 :: nil) (P1 :: P6 :: P7 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P5 :: P6 :: P7 :: P8 :: nil) (P5 :: P7 :: P8 :: P1 :: P6 :: P7 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P5 :: P7 :: P8 :: P1 :: P6 :: P7 :: P8 :: nil) ((P5 :: P7 :: P8 :: nil) ++ (P1 :: P6 :: P7 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P5P6P7P8mtmp;try rewrite HT2 in HP1P5P6P7P8mtmp.\n\tassert(HT := rule_2 (P5 :: P7 :: P8 :: nil) (P1 :: P6 :: P7 :: P8 :: nil) (P7 :: P8 :: nil) 4 2 3 HP1P5P6P7P8mtmp HP7P8mtmp HP1P6P7P8Mtmp Hincl);apply HT.\n}\ntry clear HP5P7P8m2. try clear HP1P6P7P8M3. try clear HP1P6P7P8m3. try clear HP1P5P6P7P8M4. try clear HP1P5P6P7P8m4. \n\nassert(HP1P5P7m2 : rk(P1 :: P5 :: P7 :: nil) >= 2).\n{\n\tassert(HP1P5mtmp : rk(P1 :: P5 :: nil) >= 2) by (solve_hyps_min HP1P5eq HP1P5m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P5 :: nil) (P1 :: P5 :: P7 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P5 :: nil) (P1 :: P5 :: P7 :: nil) 2 2 HP1P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P5P7m1. \n\nassert(HP1P5P7m3 : rk(P1 :: P5 :: P7 :: nil) >= 3).\n{\n\tassert(HP2P5P7Mtmp : rk(P2 :: P5 :: P7 :: nil) <= 2) by (solve_hyps_max HP2P5P7eq HP2P5P7M2).\n\tassert(HP1P2P5P7mtmp : rk(P1 :: P2 :: P5 :: P7 :: nil) >= 3) by (solve_hyps_min HP1P2P5P7eq HP1P2P5P7m3).\n\tassert(HP5P7mtmp : rk(P5 :: P7 :: nil) >= 2) by (solve_hyps_min HP5P7eq HP5P7m2).\n\tassert(Hincl : incl (P5 :: P7 :: nil) (list_inter (P1 :: P5 :: P7 :: nil) (P2 :: P5 :: P7 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P5 :: P7 :: nil) (P1 :: P5 :: P7 :: P2 :: P5 :: P7 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P5 :: P7 :: P2 :: P5 :: P7 :: nil) ((P1 :: P5 :: P7 :: nil) ++ (P2 :: P5 :: P7 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P5P7mtmp;try rewrite HT2 in HP1P2P5P7mtmp.\n\tassert(HT := rule_2 (P1 :: P5 :: P7 :: nil) (P2 :: P5 :: P7 :: nil) (P5 :: P7 :: nil) 3 2 2 HP1P2P5P7mtmp HP5P7mtmp HP2P5P7Mtmp Hincl);apply HT.\n}\ntry clear HP1P5P7m2. try clear HP1P2P5P7M3. try clear HP1P2P5P7m3. \n\nassert(HP1P5P7P8m2 : rk(P1 :: P5 :: P7 :: P8 :: nil) >= 2).\n{\n\tassert(HP1P5mtmp : rk(P1 :: P5 :: nil) >= 2) by (solve_hyps_min HP1P5eq HP1P5m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P5 :: nil) (P1 :: P5 :: P7 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P5 :: nil) (P1 :: P5 :: P7 :: P8 :: nil) 2 2 HP1P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P5P7P8m1. \n\nassert(HP1P5P7P8m3 : rk(P1 :: P5 :: P7 :: P8 :: nil) >= 3).\n{\n\tassert(HP1P5P7mtmp : rk(P1 :: P5 :: P7 :: nil) >= 3) by (solve_hyps_min HP1P5P7eq HP1P5P7m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P5 :: P7 :: nil) (P1 :: P5 :: P7 :: P8 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P5 :: P7 :: nil) (P1 :: P5 :: P7 :: P8 :: nil) 3 3 HP1P5P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P5P7P8m2. \n\nassert(HP1P5P7P8m4 : rk(P1 :: P5 :: P7 :: P8 :: nil) >= 4).\n{\n\tassert(HP2P5P7P8Mtmp : rk(P2 :: P5 :: P7 :: P8 :: nil) <= 3) by (solve_hyps_max HP2P5P7P8eq HP2P5P7P8M3).\n\tassert(HP1P2P5P7P8mtmp : rk(P1 :: P2 :: P5 :: P7 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P5P7P8eq HP1P2P5P7P8m4).\n\tassert(HP5P7P8mtmp : rk(P5 :: P7 :: P8 :: nil) >= 3) by (solve_hyps_min HP5P7P8eq HP5P7P8m3).\n\tassert(Hincl : incl (P5 :: P7 :: P8 :: nil) (list_inter (P1 :: P5 :: P7 :: P8 :: nil) (P2 :: P5 :: P7 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P5 :: P7 :: P8 :: nil) (P1 :: P5 :: P7 :: P8 :: P2 :: P5 :: P7 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P5 :: P7 :: P8 :: P2 :: P5 :: P7 :: P8 :: nil) ((P1 :: P5 :: P7 :: P8 :: nil) ++ (P2 :: P5 :: P7 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P5P7P8mtmp;try rewrite HT2 in HP1P2P5P7P8mtmp.\n\tassert(HT := rule_2 (P1 :: P5 :: P7 :: P8 :: nil) (P2 :: P5 :: P7 :: P8 :: nil) (P5 :: P7 :: P8 :: nil) 4 3 3 HP1P2P5P7P8mtmp HP5P7P8mtmp HP2P5P7P8Mtmp Hincl);apply HT.\n}\ntry clear HP1P5P7P8m3. try clear HP2P5P7P8M3. try clear HP2P5P7P8m3. try clear HP5P7P8M3. try clear HP5P7P8m3. try clear HP1P2P5P7P8M4. try clear HP1P2P5P7P8m4. \n\nassert(HP1P5P7P8P9m2 : rk(P1 :: P5 :: P7 :: P8 :: P9 :: nil) >= 2).\n{\n\tassert(HP1P5mtmp : rk(P1 :: P5 :: nil) >= 2) by (solve_hyps_min HP1P5eq HP1P5m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P5 :: nil) (P1 :: P5 :: P7 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P5 :: nil) (P1 :: P5 :: P7 :: P8 :: P9 :: nil) 2 2 HP1P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P5P7P8P9m1. \n\nassert(HP1P5P7P8P9m3 : rk(P1 :: P5 :: P7 :: P8 :: P9 :: nil) >= 3).\n{\n\tassert(HP1P5P7mtmp : rk(P1 :: P5 :: P7 :: nil) >= 3) by (solve_hyps_min HP1P5P7eq HP1P5P7m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P5 :: P7 :: nil) (P1 :: P5 :: P7 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P5 :: P7 :: nil) (P1 :: P5 :: P7 :: P8 :: P9 :: nil) 3 3 HP1P5P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P5P7M3. try clear HP1P5P7m3. try clear HP1P5P7P8P9m2. \n\nassert(HP1P5P7P8P9m4 : rk(P1 :: P5 :: P7 :: P8 :: P9 :: nil) >= 4).\n{\n\tassert(HP1P5P7P8mtmp : rk(P1 :: P5 :: P7 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P5P7P8eq HP1P5P7P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P5 :: P7 :: P8 :: nil) (P1 :: P5 :: P7 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P5 :: P7 :: P8 :: nil) (P1 :: P5 :: P7 :: P8 :: P9 :: nil) 4 4 HP1P5P7P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P5P7P8M4. try clear HP1P5P7P8m4. try clear HP1P5P7P8P9m3. \n\nassert(HP5P7P9m2 : rk(P5 :: P7 :: P9 :: nil) >= 2).\n{\n\tassert(HP5P7mtmp : rk(P5 :: P7 :: nil) >= 2) by (solve_hyps_min HP5P7eq HP5P7m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P5 :: P7 :: nil) (P5 :: P7 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P5 :: P7 :: nil) (P5 :: P7 :: P9 :: nil) 2 2 HP5P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP5P7P9m1. \n\nassert(HP5P7P9m3 : rk(P5 :: P7 :: P9 :: nil) >= 3).\n{\n\tassert(HP1P8P9Mtmp : rk(P1 :: P8 :: P9 :: nil) <= 2) by (solve_hyps_max HP1P8P9eq HP1P8P9M2).\n\tassert(HP1P5P7P8P9mtmp : rk(P1 :: P5 :: P7 :: P8 :: P9 :: nil) >= 4) by (solve_hyps_min HP1P5P7P8P9eq HP1P5P7P8P9m4).\n\tassert(HP9mtmp : rk(P9 :: nil) >= 1) by (solve_hyps_min HP9eq HP9m1).\n\tassert(Hincl : incl (P9 :: nil) (list_inter (P5 :: P7 :: P9 :: nil) (P1 :: P8 :: P9 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P5 :: P7 :: P8 :: P9 :: nil) (P5 :: P7 :: P9 :: P1 :: P8 :: P9 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P5 :: P7 :: P9 :: P1 :: P8 :: P9 :: nil) ((P5 :: P7 :: P9 :: nil) ++ (P1 :: P8 :: P9 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P5P7P8P9mtmp;try rewrite HT2 in HP1P5P7P8P9mtmp.\n\tassert(HT := rule_2 (P5 :: P7 :: P9 :: nil) (P1 :: P8 :: P9 :: nil) (P9 :: nil) 4 1 2 HP1P5P7P8P9mtmp HP9mtmp HP1P8P9Mtmp Hincl);apply HT.\n}\ntry clear HP5P7P9m2. try clear HP1P5P7P8P9M4. try clear HP1P5P7P8P9m4. \n\nassert(HP1P2P5P7P8P9m2 : rk(P1 :: P2 :: P5 :: P7 :: P8 :: P9 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P5 :: P7 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P5 :: P7 :: P8 :: P9 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P5P7P8P9m1. \n\nassert(HP1P2P5P7P8P9m3 : rk(P1 :: P2 :: P5 :: P7 :: P8 :: P9 :: nil) >= 3).\n{\n\tassert(HP1P2P5mtmp : rk(P1 :: P2 :: P5 :: nil) >= 3) by (solve_hyps_min HP1P2P5eq HP1P2P5m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P5 :: nil) (P1 :: P2 :: P5 :: P7 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P5 :: nil) (P1 :: P2 :: P5 :: P7 :: P8 :: P9 :: nil) 3 3 HP1P2P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P5M3. try clear HP1P2P5m3. try clear HP1P2P5P7P8P9m2. \n\nassert(HP1P2P5P7P8P9m4 : rk(P1 :: P2 :: P5 :: P7 :: P8 :: P9 :: nil) >= 4).\n{\n\tassert(HP1P2P5P8mtmp : rk(P1 :: P2 :: P5 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P5P8eq HP1P2P5P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P5 :: P8 :: nil) (P1 :: P2 :: P5 :: P7 :: P8 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P5 :: P8 :: nil) (P1 :: P2 :: P5 :: P7 :: P8 :: P9 :: nil) 4 4 HP1P2P5P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P5P8M4. try clear HP1P2P5P8m4. try clear HP1P2P5P7P8P9m3. \n\nassert(HP2P5P7P9m2 : rk(P2 :: P5 :: P7 :: P9 :: nil) >= 2).\n{\n\tassert(HP2P5mtmp : rk(P2 :: P5 :: nil) >= 2) by (solve_hyps_min HP2P5eq HP2P5m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P5 :: nil) (P2 :: P5 :: P7 :: P9 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P5 :: nil) (P2 :: P5 :: P7 :: P9 :: nil) 2 2 HP2P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P5M2. try clear HP2P5m2. try clear HP2P5P7P9m1. \n\nassert(HP2P5P7P9M3 : rk(P2 :: P5 :: P7 :: P9 :: nil) <= 3).\n{\n\tassert(HP2P5P7Mtmp : rk(P2 :: P5 :: P7 :: nil) <= 2) by (solve_hyps_max HP2P5P7eq HP2P5P7M2).\n\tassert(HP9Mtmp : rk(P9 :: nil) <= 1) by (solve_hyps_max HP9eq HP9M1).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P2 :: P5 :: P7 :: nil) (P9 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P5 :: P7 :: P9 :: nil) (P2 :: P5 :: P7 :: P9 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P5 :: P7 :: P9 :: nil) ((P2 :: P5 :: P7 :: nil) ++ (P9 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P2 :: P5 :: P7 :: nil) (P9 :: nil) (nil) 2 1 0 HP2P5P7Mtmp HP9Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP2P5P7P9M4. \n\nassert(HP2P5P7P9m3 : rk(P2 :: P5 :: P7 :: P9 :: nil) >= 3).\n{\n\tassert(HP1P8P9Mtmp : rk(P1 :: P8 :: P9 :: nil) <= 2) by (solve_hyps_max HP1P8P9eq HP1P8P9M2).\n\tassert(HP1P2P5P7P8P9mtmp : rk(P1 :: P2 :: P5 :: P7 :: P8 :: P9 :: nil) >= 4) by (solve_hyps_min HP1P2P5P7P8P9eq HP1P2P5P7P8P9m4).\n\tassert(HP9mtmp : rk(P9 :: nil) >= 1) by (solve_hyps_min HP9eq HP9m1).\n\tassert(Hincl : incl (P9 :: nil) (list_inter (P2 :: P5 :: P7 :: P9 :: nil) (P1 :: P8 :: P9 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P5 :: P7 :: P8 :: P9 :: nil) (P2 :: P5 :: P7 :: P9 :: P1 :: P8 :: P9 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P5 :: P7 :: P9 :: P1 :: P8 :: P9 :: nil) ((P2 :: P5 :: P7 :: P9 :: nil) ++ (P1 :: P8 :: P9 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P5P7P8P9mtmp;try rewrite HT2 in HP1P2P5P7P8P9mtmp.\n\tassert(HT := rule_2 (P2 :: P5 :: P7 :: P9 :: nil) (P1 :: P8 :: P9 :: nil) (P9 :: nil) 4 1 2 HP1P2P5P7P8P9mtmp HP9mtmp HP1P8P9Mtmp Hincl);apply HT.\n}\ntry clear HP2P5P7P9m2. try clear HP1P2P5P7P8P9M4. try clear HP1P2P5P7P8P9m4. \n\nassert(HP4P5P7P9P12P14m2 : rk(P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) >= 2).\n{\n\tassert(HP4P5mtmp : rk(P4 :: P5 :: nil) >= 2) by (solve_hyps_min HP4P5eq HP4P5m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P4 :: P5 :: nil) (P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P4 :: P5 :: nil) (P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) 2 2 HP4P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP4P5M2. try clear HP4P5m2. try clear HP4P5P7P9P12P14m1. \n\nassert(HP4P5P7P9P12P14m3 : rk(P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) >= 3).\n{\n\tassert(HP2P5P7Mtmp : rk(P2 :: P5 :: P7 :: nil) <= 2) by (solve_hyps_max HP2P5P7eq HP2P5P7M2).\n\tassert(HP2P4P5P7P9P12P14mtmp : rk(P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) >= 3) by (solve_hyps_min HP2P4P5P7P9P12P14eq HP2P4P5P7P9P12P14m3).\n\tassert(HP5P7mtmp : rk(P5 :: P7 :: nil) >= 2) by (solve_hyps_min HP5P7eq HP5P7m2).\n\tassert(Hincl : incl (P5 :: P7 :: nil) (list_inter (P2 :: P5 :: P7 :: nil) (P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) (P2 :: P5 :: P7 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P5 :: P7 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) ((P2 :: P5 :: P7 :: nil) ++ (P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP2P4P5P7P9P12P14mtmp;try rewrite HT2 in HP2P4P5P7P9P12P14mtmp.\n\tassert(HT := rule_4 (P2 :: P5 :: P7 :: nil) (P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) (P5 :: P7 :: nil) 3 2 2 HP2P4P5P7P9P12P14mtmp HP5P7mtmp HP2P5P7Mtmp Hincl); apply HT.\n}\ntry clear HP2P5P7M2. try clear HP2P5P7m2. try clear HP4P5P7P9P12P14m2. try clear HP2P4P5P7P9P12P14M4. try clear HP2P4P5P7P9P12P14m3. \n\nassert(HP4P5P7P9P12P14m4 : rk(P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) >= 4).\n{\n\tassert(HP2P5P7P9Mtmp : rk(P2 :: P5 :: P7 :: P9 :: nil) <= 3) by (solve_hyps_max HP2P5P7P9eq HP2P5P7P9M3).\n\tassert(HP2P4P5P7P9P12P14mtmp : rk(P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) >= 4) by (solve_hyps_min HP2P4P5P7P9P12P14eq HP2P4P5P7P9P12P14m4).\n\tassert(HP5P7P9mtmp : rk(P5 :: P7 :: P9 :: nil) >= 3) by (solve_hyps_min HP5P7P9eq HP5P7P9m3).\n\tassert(Hincl : incl (P5 :: P7 :: P9 :: nil) (list_inter (P2 :: P5 :: P7 :: P9 :: nil) (P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) (P2 :: P5 :: P7 :: P9 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P5 :: P7 :: P9 :: P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) ((P2 :: P5 :: P7 :: P9 :: nil) ++ (P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP2P4P5P7P9P12P14mtmp;try rewrite HT2 in HP2P4P5P7P9P12P14mtmp.\n\tassert(HT := rule_4 (P2 :: P5 :: P7 :: P9 :: nil) (P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) (P5 :: P7 :: P9 :: nil) 4 3 3 HP2P4P5P7P9P12P14mtmp HP5P7P9mtmp HP2P5P7P9Mtmp Hincl); apply HT.\n}\ntry clear HP2P5P7P9M3. try clear HP2P5P7P9m3. try clear HP4P5P7P9P12P14m3. try clear HP2P4P5P7P9P12P14M4. try clear HP2P4P5P7P9P12P14m4. \n\nassert(HP1P2P3P7P12P13m2 : rk(P1 :: P2 :: P3 :: P7 :: P12 :: P13 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P7 :: P12 :: P13 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P3 :: P7 :: P12 :: P13 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P7P12P13m1. \n\nassert(HP1P2P3P7P12P13M3 : rk(P1 :: P2 :: P3 :: P7 :: P12 :: P13 :: nil) <= 3).\n{\n\tassert(HP7Mtmp : rk(P7 :: nil) <= 1) by (solve_hyps_max HP7eq HP7M1).\n\tassert(HP1P2P3P12P13Mtmp : rk(P1 :: P2 :: P3 :: P12 :: P13 :: nil) <= 2) by (solve_hyps_max HP1P2P3P12P13eq HP1P2P3P12P13M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P7 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P7 :: P12 :: P13 :: nil) (P7 :: P1 :: P2 :: P3 :: P12 :: P13 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P7 :: P1 :: P2 :: P3 :: P12 :: P13 :: nil) ((P7 :: nil) ++ (P1 :: P2 :: P3 :: P12 :: P13 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P7 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil) (nil) 1 2 0 HP7Mtmp HP1P2P3P12P13Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP7M1. try clear HP7m1. try clear HP1P2P3P7P12P13M4. \n\nassert(HP1P2P3P7P12P13m3 : rk(P1 :: P2 :: P3 :: P7 :: P12 :: P13 :: nil) >= 3).\n{\n\tassert(HP1P2P7mtmp : rk(P1 :: P2 :: P7 :: nil) >= 3) by (solve_hyps_min HP1P2P7eq HP1P2P7m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P7 :: nil) (P1 :: P2 :: P3 :: P7 :: P12 :: P13 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P7 :: nil) (P1 :: P2 :: P3 :: P7 :: P12 :: P13 :: nil) 3 3 HP1P2P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P3P7P12P13m2. \n\nassert(HP7P12m2 : rk(P7 :: P12 :: nil) >= 2).\n{\n\tassert(HP1P2P3P12P13Mtmp : rk(P1 :: P2 :: P3 :: P12 :: P13 :: nil) <= 2) by (solve_hyps_max HP1P2P3P12P13eq HP1P2P3P12P13M2).\n\tassert(HP1P2P3P7P12P13mtmp : rk(P1 :: P2 :: P3 :: P7 :: P12 :: P13 :: nil) >= 3) by (solve_hyps_min HP1P2P3P7P12P13eq HP1P2P3P7P12P13m3).\n\tassert(HP12mtmp : rk(P12 :: nil) >= 1) by (solve_hyps_min HP12eq HP12m1).\n\tassert(Hincl : incl (P12 :: nil) (list_inter (P7 :: P12 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P3 :: P7 :: P12 :: P13 :: nil) (P7 :: P12 :: P1 :: P2 :: P3 :: P12 :: P13 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P7 :: P12 :: P1 :: P2 :: P3 :: P12 :: P13 :: nil) ((P7 :: P12 :: nil) ++ (P1 :: P2 :: P3 :: P12 :: P13 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P3P7P12P13mtmp;try rewrite HT2 in HP1P2P3P7P12P13mtmp.\n\tassert(HT := rule_2 (P7 :: P12 :: nil) (P1 :: P2 :: P3 :: P12 :: P13 :: nil) (P12 :: nil) 3 1 2 HP1P2P3P7P12P13mtmp HP12mtmp HP1P2P3P12P13Mtmp Hincl);apply HT.\n}\ntry clear HP7P12m1. try clear HP1P2P3P12P13M2. try clear HP1P2P3P12P13m2. try clear HP1P2P3P7P12P13M3. try clear HP1P2P3P7P12P13m3. \n\nassert(HP5P7P9P12P14m2 : rk(P5 :: P7 :: P9 :: P12 :: P14 :: nil) >= 2).\n{\n\tassert(HP5P7mtmp : rk(P5 :: P7 :: nil) >= 2) by (solve_hyps_min HP5P7eq HP5P7m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P5 :: P7 :: nil) (P5 :: P7 :: P9 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P5 :: P7 :: nil) (P5 :: P7 :: P9 :: P12 :: P14 :: nil) 2 2 HP5P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP5P7M2. try clear HP5P7m2. try clear HP5P7P9P12P14m1. \n\nassert(HP5P7P9P12P14m3 : rk(P5 :: P7 :: P9 :: P12 :: P14 :: nil) >= 3).\n{\n\tassert(HP5P7P9mtmp : rk(P5 :: P7 :: P9 :: nil) >= 3) by (solve_hyps_min HP5P7P9eq HP5P7P9m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P5 :: P7 :: P9 :: nil) (P5 :: P7 :: P9 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P5 :: P7 :: P9 :: nil) (P5 :: P7 :: P9 :: P12 :: P14 :: nil) 3 3 HP5P7P9mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP5P7P9M3. try clear HP5P7P9m3. try clear HP5P7P9P12P14m2. \n\nassert(HP5P7P9P12P14m4 : rk(P5 :: P7 :: P9 :: P12 :: P14 :: nil) >= 4).\n{\n\tassert(HP4P7P12Mtmp : rk(P4 :: P7 :: P12 :: nil) <= 2) by (solve_hyps_max HP4P7P12eq HP4P7P12M2).\n\tassert(HP4P5P7P9P12P14mtmp : rk(P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) >= 4) by (solve_hyps_min HP4P5P7P9P12P14eq HP4P5P7P9P12P14m4).\n\tassert(HP7P12mtmp : rk(P7 :: P12 :: nil) >= 2) by (solve_hyps_min HP7P12eq HP7P12m2).\n\tassert(Hincl : incl (P7 :: P12 :: nil) (list_inter (P4 :: P7 :: P12 :: nil) (P5 :: P7 :: P9 :: P12 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P4 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) (P4 :: P7 :: P12 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P4 :: P7 :: P12 :: P5 :: P7 :: P9 :: P12 :: P14 :: nil) ((P4 :: P7 :: P12 :: nil) ++ (P5 :: P7 :: P9 :: P12 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP4P5P7P9P12P14mtmp;try rewrite HT2 in HP4P5P7P9P12P14mtmp.\n\tassert(HT := rule_4 (P4 :: P7 :: P12 :: nil) (P5 :: P7 :: P9 :: P12 :: P14 :: nil) (P7 :: P12 :: nil) 4 2 2 HP4P5P7P9P12P14mtmp HP7P12mtmp HP4P7P12Mtmp Hincl); apply HT.\n}\ntry clear HP4P7P12M2. try clear HP4P7P12m2. try clear HP5P7P9P12P14m3. try clear HP7P12M2. try clear HP7P12m2. try clear HP4P5P7P9P12P14M4. try clear HP4P5P7P9P12P14m4. \n\nassert(HP1P2P7P12P14m2 : rk(P1 :: P2 :: P7 :: P12 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P7 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P7 :: P12 :: P14 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P12P14m1. \n\nassert(HP1P2P7P12P14m3 : rk(P1 :: P2 :: P7 :: P12 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P2P7mtmp : rk(P1 :: P2 :: P7 :: nil) >= 3) by (solve_hyps_min HP1P2P7eq HP1P2P7m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P7 :: nil) (P1 :: P2 :: P7 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P7 :: nil) (P1 :: P2 :: P7 :: P12 :: P14 :: nil) 3 3 HP1P2P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P12P14m2. \n\nassert(HP7P12P14m2 : rk(P7 :: P12 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P2P12Mtmp : rk(P1 :: P2 :: P12 :: nil) <= 2) by (solve_hyps_max HP1P2P12eq HP1P2P12M2).\n\tassert(HP1P2P7P12P14mtmp : rk(P1 :: P2 :: P7 :: P12 :: P14 :: nil) >= 3) by (solve_hyps_min HP1P2P7P12P14eq HP1P2P7P12P14m3).\n\tassert(HP12mtmp : rk(P12 :: nil) >= 1) by (solve_hyps_min HP12eq HP12m1).\n\tassert(Hincl : incl (P12 :: nil) (list_inter (P1 :: P2 :: P12 :: nil) (P7 :: P12 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P7 :: P12 :: P14 :: nil) (P1 :: P2 :: P12 :: P7 :: P12 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P12 :: P7 :: P12 :: P14 :: nil) ((P1 :: P2 :: P12 :: nil) ++ (P7 :: P12 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P7P12P14mtmp;try rewrite HT2 in HP1P2P7P12P14mtmp.\n\tassert(HT := rule_4 (P1 :: P2 :: P12 :: nil) (P7 :: P12 :: P14 :: nil) (P12 :: nil) 3 1 2 HP1P2P7P12P14mtmp HP12mtmp HP1P2P12Mtmp Hincl); apply HT.\n}\ntry clear HP1P2P12M2. try clear HP1P2P12m2. try clear HP7P12P14m1. try clear HP12M1. try clear HP12m1. try clear HP1P2P7P12P14M4. try clear HP1P2P7P12P14m3. \n\nassert(HP7P12P14m3 : rk(P7 :: P12 :: P14 :: nil) >= 3).\n{\n\tassert(HP5P9P14Mtmp : rk(P5 :: P9 :: P14 :: nil) <= 2) by (solve_hyps_max HP5P9P14eq HP5P9P14M2).\n\tassert(HP5P7P9P12P14mtmp : rk(P5 :: P7 :: P9 :: P12 :: P14 :: nil) >= 4) by (solve_hyps_min HP5P7P9P12P14eq HP5P7P9P12P14m4).\n\tassert(HP14mtmp : rk(P14 :: nil) >= 1) by (solve_hyps_min HP14eq HP14m1).\n\tassert(Hincl : incl (P14 :: nil) (list_inter (P5 :: P9 :: P14 :: nil) (P7 :: P12 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P5 :: P7 :: P9 :: P12 :: P14 :: nil) (P5 :: P9 :: P14 :: P7 :: P12 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P5 :: P9 :: P14 :: P7 :: P12 :: P14 :: nil) ((P5 :: P9 :: P14 :: nil) ++ (P7 :: P12 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP5P7P9P12P14mtmp;try rewrite HT2 in HP5P7P9P12P14mtmp.\n\tassert(HT := rule_4 (P5 :: P9 :: P14 :: nil) (P7 :: P12 :: P14 :: nil) (P14 :: nil) 4 1 2 HP5P7P9P12P14mtmp HP14mtmp HP5P9P14Mtmp Hincl); apply HT.\n}\ntry clear HP7P12P14m2. try clear HP5P7P9P12P14M4. try clear HP5P7P9P12P14m4. \n\nassert(HP1P2P7P8P11P12P14m2 : rk(P1 :: P2 :: P7 :: P8 :: P11 :: P12 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P7 :: P8 :: P11 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P7 :: P8 :: P11 :: P12 :: P14 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P8P11P12P14m1. \n\nassert(HP1P2P7P8P11P12P14m3 : rk(P1 :: P2 :: P7 :: P8 :: P11 :: P12 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P2P7mtmp : rk(P1 :: P2 :: P7 :: nil) >= 3) by (solve_hyps_min HP1P2P7eq HP1P2P7m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P7 :: nil) (P1 :: P2 :: P7 :: P8 :: P11 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P7 :: nil) (P1 :: P2 :: P7 :: P8 :: P11 :: P12 :: P14 :: nil) 3 3 HP1P2P7mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7M3. try clear HP1P2P7m3. try clear HP1P2P7P8P11P12P14m2. \n\nassert(HP1P2P7P8P11P12P14m4 : rk(P1 :: P2 :: P7 :: P8 :: P11 :: P12 :: P14 :: nil) >= 4).\n{\n\tassert(HP1P2P7P8mtmp : rk(P1 :: P2 :: P7 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P7P8eq HP1P2P7P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P7 :: P8 :: nil) (P1 :: P2 :: P7 :: P8 :: P11 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P7 :: P8 :: nil) (P1 :: P2 :: P7 :: P8 :: P11 :: P12 :: P14 :: nil) 4 4 HP1P2P7P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P7P8M4. try clear HP1P2P7P8m4. try clear HP1P2P7P8P11P12P14m3. \n\nassert(HP1P2P8P9P11m2 : rk(P1 :: P2 :: P8 :: P9 :: P11 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P8 :: P9 :: P11 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P8 :: P9 :: P11 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P8P9P11m1. \n\nassert(HP1P2P8P9P11m3 : rk(P1 :: P2 :: P8 :: P9 :: P11 :: nil) >= 3).\n{\n\tassert(HP1P2P8mtmp : rk(P1 :: P2 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P2P8eq HP1P2P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P8 :: nil) (P1 :: P2 :: P8 :: P9 :: P11 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P8 :: nil) (P1 :: P2 :: P8 :: P9 :: P11 :: nil) 3 3 HP1P2P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P8P9P11m2. \n\nassert(HP1P2P8P9P11M3 : rk(P1 :: P2 :: P8 :: P9 :: P11 :: nil) <= 3).\n{\n\tassert(HP1P8P9Mtmp : rk(P1 :: P8 :: P9 :: nil) <= 2) by (solve_hyps_max HP1P8P9eq HP1P8P9M2).\n\tassert(HP2P9P11Mtmp : rk(P2 :: P9 :: P11 :: nil) <= 2) by (solve_hyps_max HP2P9P11eq HP2P9P11M2).\n\tassert(HP9mtmp : rk(P9 :: nil) >= 1) by (solve_hyps_min HP9eq HP9m1).\n\tassert(Hincl : incl (P9 :: nil) (list_inter (P1 :: P8 :: P9 :: nil) (P2 :: P9 :: P11 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P8 :: P9 :: P11 :: nil) (P1 :: P8 :: P9 :: P2 :: P9 :: P11 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P8 :: P9 :: P2 :: P9 :: P11 :: nil) ((P1 :: P8 :: P9 :: nil) ++ (P2 :: P9 :: P11 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: P8 :: P9 :: nil) (P2 :: P9 :: P11 :: nil) (P9 :: nil) 2 2 1 HP1P8P9Mtmp HP2P9P11Mtmp HP9mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P2P8P9P11M4. \n\nassert(HP2P8m2 : rk(P2 :: P8 :: nil) >= 2).\n{\n\tassert(HP1Mtmp : rk(P1 :: nil) <= 1) by (solve_hyps_max HP1eq HP1M1).\n\tassert(HP1P2P8mtmp : rk(P1 :: P2 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P2P8eq HP1P2P8m3).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P1 :: nil) (P2 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P8 :: nil) (P1 :: P2 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P8 :: nil) ((P1 :: nil) ++ (P2 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P8mtmp;try rewrite HT2 in HP1P2P8mtmp.\n\tassert(HT := rule_4 (P1 :: nil) (P2 :: P8 :: nil) (nil) 3 0 1 HP1P2P8mtmp Hmtmp HP1Mtmp Hincl); apply HT.\n}\ntry clear HP2P8m1. \n\nassert(HP2P8P9P11M3 : rk(P2 :: P8 :: P9 :: P11 :: nil) <= 3).\n{\n\tassert(HP8Mtmp : rk(P8 :: nil) <= 1) by (solve_hyps_max HP8eq HP8M1).\n\tassert(HP2P9P11Mtmp : rk(P2 :: P9 :: P11 :: nil) <= 2) by (solve_hyps_max HP2P9P11eq HP2P9P11M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P8 :: nil) (P2 :: P9 :: P11 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P8 :: P9 :: P11 :: nil) (P8 :: P2 :: P9 :: P11 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P8 :: P2 :: P9 :: P11 :: nil) ((P8 :: nil) ++ (P2 :: P9 :: P11 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P8 :: nil) (P2 :: P9 :: P11 :: nil) (nil) 1 2 0 HP8Mtmp HP2P9P11Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP2P8P9P11M4. \n\nassert(HP2P8P9P11m2 : rk(P2 :: P8 :: P9 :: P11 :: nil) >= 2).\n{\n\tassert(HP2P8mtmp : rk(P2 :: P8 :: nil) >= 2) by (solve_hyps_min HP2P8eq HP2P8m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P2 :: P8 :: nil) (P2 :: P8 :: P9 :: P11 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P2 :: P8 :: nil) (P2 :: P8 :: P9 :: P11 :: nil) 2 2 HP2P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP2P8M2. try clear HP2P8m2. try clear HP2P8P9P11m1. \n\nassert(HP2P8P9P11m3 : rk(P2 :: P8 :: P9 :: P11 :: nil) >= 3).\n{\n\tassert(HP1P8P9Mtmp : rk(P1 :: P8 :: P9 :: nil) <= 2) by (solve_hyps_max HP1P8P9eq HP1P8P9M2).\n\tassert(HP1P2P8P9P11mtmp : rk(P1 :: P2 :: P8 :: P9 :: P11 :: nil) >= 3) by (solve_hyps_min HP1P2P8P9P11eq HP1P2P8P9P11m3).\n\tassert(HP8P9mtmp : rk(P8 :: P9 :: nil) >= 2) by (solve_hyps_min HP8P9eq HP8P9m2).\n\tassert(Hincl : incl (P8 :: P9 :: nil) (list_inter (P1 :: P8 :: P9 :: nil) (P2 :: P8 :: P9 :: P11 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P8 :: P9 :: P11 :: nil) (P1 :: P8 :: P9 :: P2 :: P8 :: P9 :: P11 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P8 :: P9 :: P2 :: P8 :: P9 :: P11 :: nil) ((P1 :: P8 :: P9 :: nil) ++ (P2 :: P8 :: P9 :: P11 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P8P9P11mtmp;try rewrite HT2 in HP1P2P8P9P11mtmp.\n\tassert(HT := rule_4 (P1 :: P8 :: P9 :: nil) (P2 :: P8 :: P9 :: P11 :: nil) (P8 :: P9 :: nil) 3 2 2 HP1P2P8P9P11mtmp HP8P9mtmp HP1P8P9Mtmp Hincl); apply HT.\n}\ntry clear HP2P8P9P11m2. \n\nassert(HP8P11m2 : rk(P8 :: P11 :: nil) >= 2).\n{\n\tassert(HP2P9P11Mtmp : rk(P2 :: P9 :: P11 :: nil) <= 2) by (solve_hyps_max HP2P9P11eq HP2P9P11M2).\n\tassert(HP2P8P9P11mtmp : rk(P2 :: P8 :: P9 :: P11 :: nil) >= 3) by (solve_hyps_min HP2P8P9P11eq HP2P8P9P11m3).\n\tassert(HP11mtmp : rk(P11 :: nil) >= 1) by (solve_hyps_min HP11eq HP11m1).\n\tassert(Hincl : incl (P11 :: nil) (list_inter (P8 :: P11 :: nil) (P2 :: P9 :: P11 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P2 :: P8 :: P9 :: P11 :: nil) (P8 :: P11 :: P2 :: P9 :: P11 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P8 :: P11 :: P2 :: P9 :: P11 :: nil) ((P8 :: P11 :: nil) ++ (P2 :: P9 :: P11 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP2P8P9P11mtmp;try rewrite HT2 in HP2P8P9P11mtmp.\n\tassert(HT := rule_2 (P8 :: P11 :: nil) (P2 :: P9 :: P11 :: nil) (P11 :: nil) 3 1 2 HP2P8P9P11mtmp HP11mtmp HP2P9P11Mtmp Hincl);apply HT.\n}\ntry clear HP8P11m1. try clear HP2P8P9P11M3. try clear HP2P8P9P11m3. \n\nassert(HP1P2P8P11m2 : rk(P1 :: P2 :: P8 :: P11 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P8 :: P11 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P8 :: P11 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P8P11m1. \n\nassert(HP1P2P8P11m3 : rk(P1 :: P2 :: P8 :: P11 :: nil) >= 3).\n{\n\tassert(HP1P2P8mtmp : rk(P1 :: P2 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P2P8eq HP1P2P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P8 :: nil) (P1 :: P2 :: P8 :: P11 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P8 :: nil) (P1 :: P2 :: P8 :: P11 :: nil) 3 3 HP1P2P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P8P11m2. \n\nassert(HP1P2P8P11M3 : rk(P1 :: P2 :: P8 :: P11 :: nil) <= 3).\n{\n\tassert(HP1P2P8P9P11Mtmp : rk(P1 :: P2 :: P8 :: P9 :: P11 :: nil) <= 3) by (solve_hyps_max HP1P2P8P9P11eq HP1P2P8P9P11M3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P8 :: P11 :: nil) (P1 :: P2 :: P8 :: P9 :: P11 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (P1 :: P2 :: P8 :: P11 :: nil) (P1 :: P2 :: P8 :: P9 :: P11 :: nil) 3 3 HP1P2P8P9P11Mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P8P11M4. try clear HP1P2P8P9P11M3. try clear HP1P2P8P9P11m3. \n\nassert(HP7P8P11P12P14m2 : rk(P7 :: P8 :: P11 :: P12 :: P14 :: nil) >= 2).\n{\n\tassert(HP7P8mtmp : rk(P7 :: P8 :: nil) >= 2) by (solve_hyps_min HP7P8eq HP7P8m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P7 :: P8 :: nil) (P7 :: P8 :: P11 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P7 :: P8 :: nil) (P7 :: P8 :: P11 :: P12 :: P14 :: nil) 2 2 HP7P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP7P8M2. try clear HP7P8m2. try clear HP7P8P11P12P14m1. \n\nassert(HP7P8P11P12P14m3 : rk(P7 :: P8 :: P11 :: P12 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P2P8P11Mtmp : rk(P1 :: P2 :: P8 :: P11 :: nil) <= 3) by (solve_hyps_max HP1P2P8P11eq HP1P2P8P11M3).\n\tassert(HP1P2P7P8P11P12P14mtmp : rk(P1 :: P2 :: P7 :: P8 :: P11 :: P12 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P2P7P8P11P12P14eq HP1P2P7P8P11P12P14m4).\n\tassert(HP8P11mtmp : rk(P8 :: P11 :: nil) >= 2) by (solve_hyps_min HP8P11eq HP8P11m2).\n\tassert(Hincl : incl (P8 :: P11 :: nil) (list_inter (P1 :: P2 :: P8 :: P11 :: nil) (P7 :: P8 :: P11 :: P12 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P7 :: P8 :: P11 :: P12 :: P14 :: nil) (P1 :: P2 :: P8 :: P11 :: P7 :: P8 :: P11 :: P12 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P8 :: P11 :: P7 :: P8 :: P11 :: P12 :: P14 :: nil) ((P1 :: P2 :: P8 :: P11 :: nil) ++ (P7 :: P8 :: P11 :: P12 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P7P8P11P12P14mtmp;try rewrite HT2 in HP1P2P7P8P11P12P14mtmp.\n\tassert(HT := rule_4 (P1 :: P2 :: P8 :: P11 :: nil) (P7 :: P8 :: P11 :: P12 :: P14 :: nil) (P8 :: P11 :: nil) 4 2 3 HP1P2P7P8P11P12P14mtmp HP8P11mtmp HP1P2P8P11Mtmp Hincl); apply HT.\n}\ntry clear HP7P8P11P12P14m2. try clear HP1P2P7P8P11P12P14M4. try clear HP1P2P7P8P11P12P14m4. \n\nassert(HP7P8P11P12P14M3 : rk(P7 :: P8 :: P11 :: P12 :: P14 :: nil) <= 3).\n{\n\tassert(HP7P8P12P14Mtmp : rk(P7 :: P8 :: P12 :: P14 :: nil) <= 3) by (solve_hyps_max HP7P8P12P14eq HP7P8P12P14M3).\n\tassert(HP7P11P12P14Mtmp : rk(P7 :: P11 :: P12 :: P14 :: nil) <= 3) by (solve_hyps_max HP7P11P12P14eq HP7P11P12P14M3).\n\tassert(HP7P12P14mtmp : rk(P7 :: P12 :: P14 :: nil) >= 3) by (solve_hyps_min HP7P12P14eq HP7P12P14m3).\n\tassert(Hincl : incl (P7 :: P12 :: P14 :: nil) (list_inter (P7 :: P8 :: P12 :: P14 :: nil) (P7 :: P11 :: P12 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P7 :: P8 :: P11 :: P12 :: P14 :: nil) (P7 :: P8 :: P12 :: P14 :: P7 :: P11 :: P12 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P7 :: P8 :: P12 :: P14 :: P7 :: P11 :: P12 :: P14 :: nil) ((P7 :: P8 :: P12 :: P14 :: nil) ++ (P7 :: P11 :: P12 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P7 :: P8 :: P12 :: P14 :: nil) (P7 :: P11 :: P12 :: P14 :: nil) (P7 :: P12 :: P14 :: nil) 3 3 3 HP7P8P12P14Mtmp HP7P11P12P14Mtmp HP7P12P14mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP7P8P12P14M3. try clear HP7P8P12P14m3. try clear HP7P11P12P14M3. try clear HP7P11P12P14m3. try clear HP7P12P14M3. try clear HP7P12P14m3. try clear HP7P8P11P12P14M4. \n\nassert(HP1P2P4P8P11P12P14m2 : rk(P1 :: P2 :: P4 :: P8 :: P11 :: P12 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P8 :: P11 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P8 :: P11 :: P12 :: P14 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P8P11P12P14m1. \n\nassert(HP1P2P4P8P11P12P14m3 : rk(P1 :: P2 :: P4 :: P8 :: P11 :: P12 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P8 :: P11 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P8 :: P11 :: P12 :: P14 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P8P11P12P14m2. \n\nassert(HP1P2P4P8P11P12P14m4 : rk(P1 :: P2 :: P4 :: P8 :: P11 :: P12 :: P14 :: nil) >= 4).\n{\n\tassert(HP1P2P4P8mtmp : rk(P1 :: P2 :: P4 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8eq HP1P2P4P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P8 :: P11 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P8 :: P11 :: P12 :: P14 :: nil) 4 4 HP1P2P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P8P11P12P14m3. \n\nassert(HP1P8m2 : rk(P1 :: P8 :: nil) >= 2).\n{\n\tassert(HP2Mtmp : rk(P2 :: nil) <= 1) by (solve_hyps_max HP2eq HP2M1).\n\tassert(HP1P2P8mtmp : rk(P1 :: P2 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P2P8eq HP1P2P8m3).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P2 :: nil) (P1 :: P8 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P8 :: nil) (P2 :: P1 :: P8 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P1 :: P8 :: nil) ((P2 :: nil) ++ (P1 :: P8 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P8mtmp;try rewrite HT2 in HP1P2P8mtmp.\n\tassert(HT := rule_4 (P2 :: nil) (P1 :: P8 :: nil) (nil) 3 0 1 HP1P2P8mtmp Hmtmp HP2Mtmp Hincl); apply HT.\n}\ntry clear HP2M1. try clear HP2m1. try clear HP1P8m1. try clear HP1P2P8M3. try clear HP1P2P8m3. \n\nassert(HP1P8P10m2 : rk(P1 :: P8 :: P10 :: nil) >= 2).\n{\n\tassert(HP1P8mtmp : rk(P1 :: P8 :: nil) >= 2) by (solve_hyps_min HP1P8eq HP1P8m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P8 :: nil) (P1 :: P8 :: P10 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P8 :: nil) (P1 :: P8 :: P10 :: nil) 2 2 HP1P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P8P10m1. \n\nassert(HP1P8P10m3 : rk(P1 :: P8 :: P10 :: nil) >= 3).\n{\n\tassert(HP2P8P10Mtmp : rk(P2 :: P8 :: P10 :: nil) <= 2) by (solve_hyps_max HP2P8P10eq HP2P8P10M2).\n\tassert(HP1P2P8P10mtmp : rk(P1 :: P2 :: P8 :: P10 :: nil) >= 3) by (solve_hyps_min HP1P2P8P10eq HP1P2P8P10m3).\n\tassert(HP8P10mtmp : rk(P8 :: P10 :: nil) >= 2) by (solve_hyps_min HP8P10eq HP8P10m2).\n\tassert(Hincl : incl (P8 :: P10 :: nil) (list_inter (P1 :: P8 :: P10 :: nil) (P2 :: P8 :: P10 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P8 :: P10 :: nil) (P1 :: P8 :: P10 :: P2 :: P8 :: P10 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P8 :: P10 :: P2 :: P8 :: P10 :: nil) ((P1 :: P8 :: P10 :: nil) ++ (P2 :: P8 :: P10 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P8P10mtmp;try rewrite HT2 in HP1P2P8P10mtmp.\n\tassert(HT := rule_2 (P1 :: P8 :: P10 :: nil) (P2 :: P8 :: P10 :: nil) (P8 :: P10 :: nil) 3 2 2 HP1P2P8P10mtmp HP8P10mtmp HP2P8P10Mtmp Hincl);apply HT.\n}\ntry clear HP1P8P10m2. try clear HP1P2P8P10M3. try clear HP1P2P8P10m3. \n\nassert(HP1P8P10P11M3 : rk(P1 :: P8 :: P10 :: P11 :: nil) <= 3).\n{\n\tassert(HP8Mtmp : rk(P8 :: nil) <= 1) by (solve_hyps_max HP8eq HP8M1).\n\tassert(HP1P10P11Mtmp : rk(P1 :: P10 :: P11 :: nil) <= 2) by (solve_hyps_max HP1P10P11eq HP1P10P11M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P8 :: nil) (P1 :: P10 :: P11 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P8 :: P10 :: P11 :: nil) (P8 :: P1 :: P10 :: P11 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P8 :: P1 :: P10 :: P11 :: nil) ((P8 :: nil) ++ (P1 :: P10 :: P11 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P8 :: nil) (P1 :: P10 :: P11 :: nil) (nil) 1 2 0 HP8Mtmp HP1P10P11Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1P8P10P11M4. \n\nassert(HP1P8P10P11m2 : rk(P1 :: P8 :: P10 :: P11 :: nil) >= 2).\n{\n\tassert(HP1P8mtmp : rk(P1 :: P8 :: nil) >= 2) by (solve_hyps_min HP1P8eq HP1P8m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P8 :: nil) (P1 :: P8 :: P10 :: P11 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P8 :: nil) (P1 :: P8 :: P10 :: P11 :: nil) 2 2 HP1P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P8P10P11m1. \n\nassert(HP1P8P10P11m3 : rk(P1 :: P8 :: P10 :: P11 :: nil) >= 3).\n{\n\tassert(HP1P8P10mtmp : rk(P1 :: P8 :: P10 :: nil) >= 3) by (solve_hyps_min HP1P8P10eq HP1P8P10m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P8 :: P10 :: nil) (P1 :: P8 :: P10 :: P11 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P8 :: P10 :: nil) (P1 :: P8 :: P10 :: P11 :: nil) 3 3 HP1P8P10mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P8P10M3. try clear HP1P8P10m3. try clear HP1P8P10P11m2. \n\nassert(HP1P2P9P11M3 : rk(P1 :: P2 :: P9 :: P11 :: nil) <= 3).\n{\n\tassert(HP1Mtmp : rk(P1 :: nil) <= 1) by (solve_hyps_max HP1eq HP1M1).\n\tassert(HP2P9P11Mtmp : rk(P2 :: P9 :: P11 :: nil) <= 2) by (solve_hyps_max HP2P9P11eq HP2P9P11M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P1 :: nil) (P2 :: P9 :: P11 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P9 :: P11 :: nil) (P1 :: P2 :: P9 :: P11 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P9 :: P11 :: nil) ((P1 :: nil) ++ (P2 :: P9 :: P11 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: nil) (P2 :: P9 :: P11 :: nil) (nil) 1 2 0 HP1Mtmp HP2P9P11Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP1M1. try clear HP1m1. try clear HP1P2P9P11M4. \n\nassert(HP1P2P9P11m2 : rk(P1 :: P2 :: P9 :: P11 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P9 :: P11 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P9 :: P11 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P9P11m1. \n\nassert(HP1P2P9P11m3 : rk(P1 :: P2 :: P9 :: P11 :: nil) >= 3).\n{\n\tassert(HP1P2P9mtmp : rk(P1 :: P2 :: P9 :: nil) >= 3) by (solve_hyps_min HP1P2P9eq HP1P2P9m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P9 :: nil) (P1 :: P2 :: P9 :: P11 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P9 :: nil) (P1 :: P2 :: P9 :: P11 :: nil) 3 3 HP1P2P9mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P9M3. try clear HP1P2P9m3. try clear HP1P2P9P11m2. \n\nassert(HP1P11m2 : rk(P1 :: P11 :: nil) >= 2).\n{\n\tassert(HP2P9P11Mtmp : rk(P2 :: P9 :: P11 :: nil) <= 2) by (solve_hyps_max HP2P9P11eq HP2P9P11M2).\n\tassert(HP1P2P9P11mtmp : rk(P1 :: P2 :: P9 :: P11 :: nil) >= 3) by (solve_hyps_min HP1P2P9P11eq HP1P2P9P11m3).\n\tassert(HP11mtmp : rk(P11 :: nil) >= 1) by (solve_hyps_min HP11eq HP11m1).\n\tassert(Hincl : incl (P11 :: nil) (list_inter (P1 :: P11 :: nil) (P2 :: P9 :: P11 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P9 :: P11 :: nil) (P1 :: P11 :: P2 :: P9 :: P11 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P11 :: P2 :: P9 :: P11 :: nil) ((P1 :: P11 :: nil) ++ (P2 :: P9 :: P11 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P9P11mtmp;try rewrite HT2 in HP1P2P9P11mtmp.\n\tassert(HT := rule_2 (P1 :: P11 :: nil) (P2 :: P9 :: P11 :: nil) (P11 :: nil) 3 1 2 HP1P2P9P11mtmp HP11mtmp HP2P9P11Mtmp Hincl);apply HT.\n}\ntry clear HP1P11m1. try clear HP2P9P11M2. try clear HP2P9P11m2. try clear HP11M1. try clear HP11m1. try clear HP1P2P9P11M3. try clear HP1P2P9P11m3. \n\nassert(HP1P8P11m2 : rk(P1 :: P8 :: P11 :: nil) >= 2).\n{\n\tassert(HP1P8mtmp : rk(P1 :: P8 :: nil) >= 2) by (solve_hyps_min HP1P8eq HP1P8m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P8 :: nil) (P1 :: P8 :: P11 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P8 :: nil) (P1 :: P8 :: P11 :: nil) 2 2 HP1P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P8P11m1. \n\nassert(HP1P8P11m3 : rk(P1 :: P8 :: P11 :: nil) >= 3).\n{\n\tassert(HP1P10P11Mtmp : rk(P1 :: P10 :: P11 :: nil) <= 2) by (solve_hyps_max HP1P10P11eq HP1P10P11M2).\n\tassert(HP1P8P10P11mtmp : rk(P1 :: P8 :: P10 :: P11 :: nil) >= 3) by (solve_hyps_min HP1P8P10P11eq HP1P8P10P11m3).\n\tassert(HP1P11mtmp : rk(P1 :: P11 :: nil) >= 2) by (solve_hyps_min HP1P11eq HP1P11m2).\n\tassert(Hincl : incl (P1 :: P11 :: nil) (list_inter (P1 :: P8 :: P11 :: nil) (P1 :: P10 :: P11 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P8 :: P10 :: P11 :: nil) (P1 :: P8 :: P11 :: P1 :: P10 :: P11 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P8 :: P11 :: P1 :: P10 :: P11 :: nil) ((P1 :: P8 :: P11 :: nil) ++ (P1 :: P10 :: P11 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P8P10P11mtmp;try rewrite HT2 in HP1P8P10P11mtmp.\n\tassert(HT := rule_2 (P1 :: P8 :: P11 :: nil) (P1 :: P10 :: P11 :: nil) (P1 :: P11 :: nil) 3 2 2 HP1P8P10P11mtmp HP1P11mtmp HP1P10P11Mtmp Hincl);apply HT.\n}\ntry clear HP1P8P11m2. try clear HP1P10P11M2. try clear HP1P10P11m2. try clear HP1P11M2. try clear HP1P11m2. try clear HP1P8P10P11M3. try clear HP1P8P10P11m3. \n\nassert(HP1P4P8P11P12P14m2 : rk(P1 :: P4 :: P8 :: P11 :: P12 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P4mtmp : rk(P1 :: P4 :: nil) >= 2) by (solve_hyps_min HP1P4eq HP1P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: nil) (P1 :: P4 :: P8 :: P11 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: nil) (P1 :: P4 :: P8 :: P11 :: P12 :: P14 :: nil) 2 2 HP1P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P8P11P12P14m1. \n\nassert(HP1P4P8P11P12P14m3 : rk(P1 :: P4 :: P8 :: P11 :: P12 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P4P8mtmp : rk(P1 :: P4 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P4P8eq HP1P4P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: P8 :: nil) (P1 :: P4 :: P8 :: P11 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: P8 :: nil) (P1 :: P4 :: P8 :: P11 :: P12 :: P14 :: nil) 3 3 HP1P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P8P11P12P14m2. \n\nassert(HP1P4P8P11P12P14m4 : rk(P1 :: P4 :: P8 :: P11 :: P12 :: P14 :: nil) >= 4).\n{\n\tassert(HP1P2P8P11Mtmp : rk(P1 :: P2 :: P8 :: P11 :: nil) <= 3) by (solve_hyps_max HP1P2P8P11eq HP1P2P8P11M3).\n\tassert(HP1P2P4P8P11P12P14mtmp : rk(P1 :: P2 :: P4 :: P8 :: P11 :: P12 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8P11P12P14eq HP1P2P4P8P11P12P14m4).\n\tassert(HP1P8P11mtmp : rk(P1 :: P8 :: P11 :: nil) >= 3) by (solve_hyps_min HP1P8P11eq HP1P8P11m3).\n\tassert(Hincl : incl (P1 :: P8 :: P11 :: nil) (list_inter (P1 :: P2 :: P8 :: P11 :: nil) (P1 :: P4 :: P8 :: P11 :: P12 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P8 :: P11 :: P12 :: P14 :: nil) (P1 :: P2 :: P8 :: P11 :: P1 :: P4 :: P8 :: P11 :: P12 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P8 :: P11 :: P1 :: P4 :: P8 :: P11 :: P12 :: P14 :: nil) ((P1 :: P2 :: P8 :: P11 :: nil) ++ (P1 :: P4 :: P8 :: P11 :: P12 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P8P11P12P14mtmp;try rewrite HT2 in HP1P2P4P8P11P12P14mtmp.\n\tassert(HT := rule_4 (P1 :: P2 :: P8 :: P11 :: nil) (P1 :: P4 :: P8 :: P11 :: P12 :: P14 :: nil) (P1 :: P8 :: P11 :: nil) 4 3 3 HP1P2P4P8P11P12P14mtmp HP1P8P11mtmp HP1P2P8P11Mtmp Hincl); apply HT.\n}\ntry clear HP1P4P8P11P12P14m3. try clear HP1P2P4P8P11P12P14M4. try clear HP1P2P4P8P11P12P14m4. \n\nassert(HP1P5P8P9P14m2 : rk(P1 :: P5 :: P8 :: P9 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P5mtmp : rk(P1 :: P5 :: nil) >= 2) by (solve_hyps_min HP1P5eq HP1P5m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P5 :: nil) (P1 :: P5 :: P8 :: P9 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P5 :: nil) (P1 :: P5 :: P8 :: P9 :: P14 :: nil) 2 2 HP1P5mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P5M2. try clear HP1P5m2. try clear HP1P5P8P9P14m1. \n\nassert(HP1P5P8P9P14m3 : rk(P1 :: P5 :: P8 :: P9 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P5P8mtmp : rk(P1 :: P5 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P5P8eq HP1P5P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P5 :: P8 :: nil) (P1 :: P5 :: P8 :: P9 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P5 :: P8 :: nil) (P1 :: P5 :: P8 :: P9 :: P14 :: nil) 3 3 HP1P5P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P5P8M3. try clear HP1P5P8m3. try clear HP1P5P8P9P14m2. \n\nassert(HP1P5P8P9P14M3 : rk(P1 :: P5 :: P8 :: P9 :: P14 :: nil) <= 3).\n{\n\tassert(HP1P8P9Mtmp : rk(P1 :: P8 :: P9 :: nil) <= 2) by (solve_hyps_max HP1P8P9eq HP1P8P9M2).\n\tassert(HP5P9P14Mtmp : rk(P5 :: P9 :: P14 :: nil) <= 2) by (solve_hyps_max HP5P9P14eq HP5P9P14M2).\n\tassert(HP9mtmp : rk(P9 :: nil) >= 1) by (solve_hyps_min HP9eq HP9m1).\n\tassert(Hincl : incl (P9 :: nil) (list_inter (P1 :: P8 :: P9 :: nil) (P5 :: P9 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P5 :: P8 :: P9 :: P14 :: nil) (P1 :: P8 :: P9 :: P5 :: P9 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P8 :: P9 :: P5 :: P9 :: P14 :: nil) ((P1 :: P8 :: P9 :: nil) ++ (P5 :: P9 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P1 :: P8 :: P9 :: nil) (P5 :: P9 :: P14 :: nil) (P9 :: nil) 2 2 1 HP1P8P9Mtmp HP5P9P14Mtmp HP9mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP9M1. try clear HP9m1. try clear HP1P5P8P9P14M4. \n\nassert(HP5P8P9P14M3 : rk(P5 :: P8 :: P9 :: P14 :: nil) <= 3).\n{\n\tassert(HP8Mtmp : rk(P8 :: nil) <= 1) by (solve_hyps_max HP8eq HP8M1).\n\tassert(HP5P9P14Mtmp : rk(P5 :: P9 :: P14 :: nil) <= 2) by (solve_hyps_max HP5P9P14eq HP5P9P14M2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P8 :: nil) (P5 :: P9 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P5 :: P8 :: P9 :: P14 :: nil) (P8 :: P5 :: P9 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P8 :: P5 :: P9 :: P14 :: nil) ((P8 :: nil) ++ (P5 :: P9 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P8 :: nil) (P5 :: P9 :: P14 :: nil) (nil) 1 2 0 HP8Mtmp HP5P9P14Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP8M1. try clear HP8m1. try clear HP5P8P9P14M4. \n\nassert(HP5P8P9P14m2 : rk(P5 :: P8 :: P9 :: P14 :: nil) >= 2).\n{\n\tassert(HP5P8mtmp : rk(P5 :: P8 :: nil) >= 2) by (solve_hyps_min HP5P8eq HP5P8m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P5 :: P8 :: nil) (P5 :: P8 :: P9 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P5 :: P8 :: nil) (P5 :: P8 :: P9 :: P14 :: nil) 2 2 HP5P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP5P8M2. try clear HP5P8m2. try clear HP5P8P9P14m1. \n\nassert(HP5P8P9P14m3 : rk(P5 :: P8 :: P9 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P8P9Mtmp : rk(P1 :: P8 :: P9 :: nil) <= 2) by (solve_hyps_max HP1P8P9eq HP1P8P9M2).\n\tassert(HP1P5P8P9P14mtmp : rk(P1 :: P5 :: P8 :: P9 :: P14 :: nil) >= 3) by (solve_hyps_min HP1P5P8P9P14eq HP1P5P8P9P14m3).\n\tassert(HP8P9mtmp : rk(P8 :: P9 :: nil) >= 2) by (solve_hyps_min HP8P9eq HP8P9m2).\n\tassert(Hincl : incl (P8 :: P9 :: nil) (list_inter (P1 :: P8 :: P9 :: nil) (P5 :: P8 :: P9 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P5 :: P8 :: P9 :: P14 :: nil) (P1 :: P8 :: P9 :: P5 :: P8 :: P9 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P8 :: P9 :: P5 :: P8 :: P9 :: P14 :: nil) ((P1 :: P8 :: P9 :: nil) ++ (P5 :: P8 :: P9 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P5P8P9P14mtmp;try rewrite HT2 in HP1P5P8P9P14mtmp.\n\tassert(HT := rule_4 (P1 :: P8 :: P9 :: nil) (P5 :: P8 :: P9 :: P14 :: nil) (P8 :: P9 :: nil) 3 2 2 HP1P5P8P9P14mtmp HP8P9mtmp HP1P8P9Mtmp Hincl); apply HT.\n}\ntry clear HP1P8P9M2. try clear HP1P8P9m2. try clear HP5P8P9P14m2. try clear HP8P9M2. try clear HP8P9m2. try clear HP1P5P8P9P14M3. try clear HP1P5P8P9P14m3. \n\nassert(HP8P14m2 : rk(P8 :: P14 :: nil) >= 2).\n{\n\tassert(HP5P9P14Mtmp : rk(P5 :: P9 :: P14 :: nil) <= 2) by (solve_hyps_max HP5P9P14eq HP5P9P14M2).\n\tassert(HP5P8P9P14mtmp : rk(P5 :: P8 :: P9 :: P14 :: nil) >= 3) by (solve_hyps_min HP5P8P9P14eq HP5P8P9P14m3).\n\tassert(HP14mtmp : rk(P14 :: nil) >= 1) by (solve_hyps_min HP14eq HP14m1).\n\tassert(Hincl : incl (P14 :: nil) (list_inter (P8 :: P14 :: nil) (P5 :: P9 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P5 :: P8 :: P9 :: P14 :: nil) (P8 :: P14 :: P5 :: P9 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P8 :: P14 :: P5 :: P9 :: P14 :: nil) ((P8 :: P14 :: nil) ++ (P5 :: P9 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP5P8P9P14mtmp;try rewrite HT2 in HP5P8P9P14mtmp.\n\tassert(HT := rule_2 (P8 :: P14 :: nil) (P5 :: P9 :: P14 :: nil) (P14 :: nil) 3 1 2 HP5P8P9P14mtmp HP14mtmp HP5P9P14Mtmp Hincl);apply HT.\n}\ntry clear HP8P14m1. try clear HP5P9P14M2. try clear HP5P9P14m2. try clear HP5P8P9P14M3. try clear HP5P8P9P14m3. \n\nassert(HP8P11P12P14m2 : rk(P8 :: P11 :: P12 :: P14 :: nil) >= 2).\n{\n\tassert(HP8P11mtmp : rk(P8 :: P11 :: nil) >= 2) by (solve_hyps_min HP8P11eq HP8P11m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P8 :: P11 :: nil) (P8 :: P11 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P8 :: P11 :: nil) (P8 :: P11 :: P12 :: P14 :: nil) 2 2 HP8P11mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP8P11P12P14m1. \n\nassert(HP8P11P12P14m3 : rk(P8 :: P11 :: P12 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P4P8P14Mtmp : rk(P1 :: P4 :: P8 :: P14 :: nil) <= 3) by (solve_hyps_max HP1P4P8P14eq HP1P4P8P14M3).\n\tassert(HP1P4P8P11P12P14mtmp : rk(P1 :: P4 :: P8 :: P11 :: P12 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P4P8P11P12P14eq HP1P4P8P11P12P14m4).\n\tassert(HP8P14mtmp : rk(P8 :: P14 :: nil) >= 2) by (solve_hyps_min HP8P14eq HP8P14m2).\n\tassert(Hincl : incl (P8 :: P14 :: nil) (list_inter (P1 :: P4 :: P8 :: P14 :: nil) (P8 :: P11 :: P12 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P4 :: P8 :: P11 :: P12 :: P14 :: nil) (P1 :: P4 :: P8 :: P14 :: P8 :: P11 :: P12 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P8 :: P14 :: P8 :: P11 :: P12 :: P14 :: nil) ((P1 :: P4 :: P8 :: P14 :: nil) ++ (P8 :: P11 :: P12 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P4P8P11P12P14mtmp;try rewrite HT2 in HP1P4P8P11P12P14mtmp.\n\tassert(HT := rule_4 (P1 :: P4 :: P8 :: P14 :: nil) (P8 :: P11 :: P12 :: P14 :: nil) (P8 :: P14 :: nil) 4 2 3 HP1P4P8P11P12P14mtmp HP8P14mtmp HP1P4P8P14Mtmp Hincl); apply HT.\n}\ntry clear HP8P11P12P14m2. try clear HP1P4P8P11P12P14M4. try clear HP1P4P8P11P12P14m4. \n\nassert(HP8P11P12P14M3 : rk(P8 :: P11 :: P12 :: P14 :: nil) <= 3).\n{\n\tassert(HP7P8P11P12P14Mtmp : rk(P7 :: P8 :: P11 :: P12 :: P14 :: nil) <= 3) by (solve_hyps_max HP7P8P11P12P14eq HP7P8P11P12P14M3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P8 :: P11 :: P12 :: P14 :: nil) (P7 :: P8 :: P11 :: P12 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (P8 :: P11 :: P12 :: P14 :: nil) (P7 :: P8 :: P11 :: P12 :: P14 :: nil) 3 3 HP7P8P11P12P14Mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP8P11P12P14M4. try clear HP7P8P11P12P14M3. try clear HP7P8P11P12P14m3. \n\nassert(HP1P2P4P8P11P13P14m2 : rk(P1 :: P2 :: P4 :: P8 :: P11 :: P13 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P8 :: P11 :: P13 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P8 :: P11 :: P13 :: P14 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P8P11P13P14m1. \n\nassert(HP1P2P4P8P11P13P14m3 : rk(P1 :: P2 :: P4 :: P8 :: P11 :: P13 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P8 :: P11 :: P13 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P8 :: P11 :: P13 :: P14 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P8P11P13P14m2. \n\nassert(HP1P2P4P8P11P13P14m4 : rk(P1 :: P2 :: P4 :: P8 :: P11 :: P13 :: P14 :: nil) >= 4).\n{\n\tassert(HP1P2P4P8mtmp : rk(P1 :: P2 :: P4 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8eq HP1P2P4P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P8 :: P11 :: P13 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P8 :: P11 :: P13 :: P14 :: nil) 4 4 HP1P2P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P8P11P13P14m3. \n\nassert(HP1P4P8P11P13P14m2 : rk(P1 :: P4 :: P8 :: P11 :: P13 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P4mtmp : rk(P1 :: P4 :: nil) >= 2) by (solve_hyps_min HP1P4eq HP1P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: nil) (P1 :: P4 :: P8 :: P11 :: P13 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: nil) (P1 :: P4 :: P8 :: P11 :: P13 :: P14 :: nil) 2 2 HP1P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P8P11P13P14m1. \n\nassert(HP1P4P8P11P13P14m3 : rk(P1 :: P4 :: P8 :: P11 :: P13 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P4P8mtmp : rk(P1 :: P4 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P4P8eq HP1P4P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: P8 :: nil) (P1 :: P4 :: P8 :: P11 :: P13 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: P8 :: nil) (P1 :: P4 :: P8 :: P11 :: P13 :: P14 :: nil) 3 3 HP1P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P8P11P13P14m2. \n\nassert(HP1P4P8P11P13P14m4 : rk(P1 :: P4 :: P8 :: P11 :: P13 :: P14 :: nil) >= 4).\n{\n\tassert(HP1P2P8P11Mtmp : rk(P1 :: P2 :: P8 :: P11 :: nil) <= 3) by (solve_hyps_max HP1P2P8P11eq HP1P2P8P11M3).\n\tassert(HP1P2P4P8P11P13P14mtmp : rk(P1 :: P2 :: P4 :: P8 :: P11 :: P13 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8P11P13P14eq HP1P2P4P8P11P13P14m4).\n\tassert(HP1P8P11mtmp : rk(P1 :: P8 :: P11 :: nil) >= 3) by (solve_hyps_min HP1P8P11eq HP1P8P11m3).\n\tassert(Hincl : incl (P1 :: P8 :: P11 :: nil) (list_inter (P1 :: P2 :: P8 :: P11 :: nil) (P1 :: P4 :: P8 :: P11 :: P13 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P8 :: P11 :: P13 :: P14 :: nil) (P1 :: P2 :: P8 :: P11 :: P1 :: P4 :: P8 :: P11 :: P13 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P8 :: P11 :: P1 :: P4 :: P8 :: P11 :: P13 :: P14 :: nil) ((P1 :: P2 :: P8 :: P11 :: nil) ++ (P1 :: P4 :: P8 :: P11 :: P13 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P8P11P13P14mtmp;try rewrite HT2 in HP1P2P4P8P11P13P14mtmp.\n\tassert(HT := rule_4 (P1 :: P2 :: P8 :: P11 :: nil) (P1 :: P4 :: P8 :: P11 :: P13 :: P14 :: nil) (P1 :: P8 :: P11 :: nil) 4 3 3 HP1P2P4P8P11P13P14mtmp HP1P8P11mtmp HP1P2P8P11Mtmp Hincl); apply HT.\n}\ntry clear HP1P4P8P11P13P14m3. try clear HP1P2P4P8P11P13P14M4. try clear HP1P2P4P8P11P13P14m4. \n\nassert(HP8P11P13P14m2 : rk(P8 :: P11 :: P13 :: P14 :: nil) >= 2).\n{\n\tassert(HP8P11mtmp : rk(P8 :: P11 :: nil) >= 2) by (solve_hyps_min HP8P11eq HP8P11m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P8 :: P11 :: nil) (P8 :: P11 :: P13 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P8 :: P11 :: nil) (P8 :: P11 :: P13 :: P14 :: nil) 2 2 HP8P11mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP8P11P13P14m1. \n\nassert(HP8P11P13P14M3 : rk(P8 :: P11 :: P13 :: P14 :: nil) <= 3).\n{\n\tassert(HP8P11P13Mtmp : rk(P8 :: P11 :: P13 :: nil) <= 2) by (solve_hyps_max HP8P11P13eq HP8P11P13M2).\n\tassert(HP14Mtmp : rk(P14 :: nil) <= 1) by (solve_hyps_max HP14eq HP14M1).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P8 :: P11 :: P13 :: nil) (P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P8 :: P11 :: P13 :: P14 :: nil) (P8 :: P11 :: P13 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P8 :: P11 :: P13 :: P14 :: nil) ((P8 :: P11 :: P13 :: nil) ++ (P14 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P8 :: P11 :: P13 :: nil) (P14 :: nil) (nil) 2 1 0 HP8P11P13Mtmp HP14Mtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP8P11P13M2. try clear HP8P11P13m2. try clear HP8P11P13P14M4. \n\nassert(HP8P11P13P14m3 : rk(P8 :: P11 :: P13 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P4P8P14Mtmp : rk(P1 :: P4 :: P8 :: P14 :: nil) <= 3) by (solve_hyps_max HP1P4P8P14eq HP1P4P8P14M3).\n\tassert(HP1P4P8P11P13P14mtmp : rk(P1 :: P4 :: P8 :: P11 :: P13 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P4P8P11P13P14eq HP1P4P8P11P13P14m4).\n\tassert(HP8P14mtmp : rk(P8 :: P14 :: nil) >= 2) by (solve_hyps_min HP8P14eq HP8P14m2).\n\tassert(Hincl : incl (P8 :: P14 :: nil) (list_inter (P1 :: P4 :: P8 :: P14 :: nil) (P8 :: P11 :: P13 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P4 :: P8 :: P11 :: P13 :: P14 :: nil) (P1 :: P4 :: P8 :: P14 :: P8 :: P11 :: P13 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P8 :: P14 :: P8 :: P11 :: P13 :: P14 :: nil) ((P1 :: P4 :: P8 :: P14 :: nil) ++ (P8 :: P11 :: P13 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P4P8P11P13P14mtmp;try rewrite HT2 in HP1P4P8P11P13P14mtmp.\n\tassert(HT := rule_4 (P1 :: P4 :: P8 :: P14 :: nil) (P8 :: P11 :: P13 :: P14 :: nil) (P8 :: P14 :: nil) 4 2 3 HP1P4P8P11P13P14mtmp HP8P14mtmp HP1P4P8P14Mtmp Hincl); apply HT.\n}\ntry clear HP8P11P13P14m2. try clear HP1P4P8P11P13P14M4. try clear HP1P4P8P11P13P14m4. \n\nassert(HP1P2P4P8P11P14m2 : rk(P1 :: P2 :: P4 :: P8 :: P11 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P8 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P8 :: P11 :: P14 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P8P11P14m1. \n\nassert(HP1P2P4P8P11P14m3 : rk(P1 :: P2 :: P4 :: P8 :: P11 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P8 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P8 :: P11 :: P14 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P8P11P14m2. \n\nassert(HP1P2P4P8P11P14m4 : rk(P1 :: P2 :: P4 :: P8 :: P11 :: P14 :: nil) >= 4).\n{\n\tassert(HP1P2P4P8mtmp : rk(P1 :: P2 :: P4 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8eq HP1P2P4P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P8 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P8 :: P11 :: P14 :: nil) 4 4 HP1P2P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P8P11P14m3. \n\nassert(HP1P4P8P11P14m2 : rk(P1 :: P4 :: P8 :: P11 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P4mtmp : rk(P1 :: P4 :: nil) >= 2) by (solve_hyps_min HP1P4eq HP1P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: nil) (P1 :: P4 :: P8 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: nil) (P1 :: P4 :: P8 :: P11 :: P14 :: nil) 2 2 HP1P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P8P11P14m1. \n\nassert(HP1P4P8P11P14m3 : rk(P1 :: P4 :: P8 :: P11 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P4P8mtmp : rk(P1 :: P4 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P4P8eq HP1P4P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: P8 :: nil) (P1 :: P4 :: P8 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: P8 :: nil) (P1 :: P4 :: P8 :: P11 :: P14 :: nil) 3 3 HP1P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P8P11P14m2. \n\nassert(HP1P4P8P11P14m4 : rk(P1 :: P4 :: P8 :: P11 :: P14 :: nil) >= 4).\n{\n\tassert(HP1P2P8P11Mtmp : rk(P1 :: P2 :: P8 :: P11 :: nil) <= 3) by (solve_hyps_max HP1P2P8P11eq HP1P2P8P11M3).\n\tassert(HP1P2P4P8P11P14mtmp : rk(P1 :: P2 :: P4 :: P8 :: P11 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8P11P14eq HP1P2P4P8P11P14m4).\n\tassert(HP1P8P11mtmp : rk(P1 :: P8 :: P11 :: nil) >= 3) by (solve_hyps_min HP1P8P11eq HP1P8P11m3).\n\tassert(Hincl : incl (P1 :: P8 :: P11 :: nil) (list_inter (P1 :: P2 :: P8 :: P11 :: nil) (P1 :: P4 :: P8 :: P11 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P8 :: P11 :: P14 :: nil) (P1 :: P2 :: P8 :: P11 :: P1 :: P4 :: P8 :: P11 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P8 :: P11 :: P1 :: P4 :: P8 :: P11 :: P14 :: nil) ((P1 :: P2 :: P8 :: P11 :: nil) ++ (P1 :: P4 :: P8 :: P11 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P8P11P14mtmp;try rewrite HT2 in HP1P2P4P8P11P14mtmp.\n\tassert(HT := rule_4 (P1 :: P2 :: P8 :: P11 :: nil) (P1 :: P4 :: P8 :: P11 :: P14 :: nil) (P1 :: P8 :: P11 :: nil) 4 3 3 HP1P2P4P8P11P14mtmp HP1P8P11mtmp HP1P2P8P11Mtmp Hincl); apply HT.\n}\ntry clear HP1P4P8P11P14m3. try clear HP1P2P4P8P11P14M4. try clear HP1P2P4P8P11P14m4. \n\nassert(HP8P11P14m2 : rk(P8 :: P11 :: P14 :: nil) >= 2).\n{\n\tassert(HP8P11mtmp : rk(P8 :: P11 :: nil) >= 2) by (solve_hyps_min HP8P11eq HP8P11m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P8 :: P11 :: nil) (P8 :: P11 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P8 :: P11 :: nil) (P8 :: P11 :: P14 :: nil) 2 2 HP8P11mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP8P11P14m1. \n\nassert(HP8P11P14m3 : rk(P8 :: P11 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P4P8P14Mtmp : rk(P1 :: P4 :: P8 :: P14 :: nil) <= 3) by (solve_hyps_max HP1P4P8P14eq HP1P4P8P14M3).\n\tassert(HP1P4P8P11P14mtmp : rk(P1 :: P4 :: P8 :: P11 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P4P8P11P14eq HP1P4P8P11P14m4).\n\tassert(HP8P14mtmp : rk(P8 :: P14 :: nil) >= 2) by (solve_hyps_min HP8P14eq HP8P14m2).\n\tassert(Hincl : incl (P8 :: P14 :: nil) (list_inter (P1 :: P4 :: P8 :: P14 :: nil) (P8 :: P11 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P4 :: P8 :: P11 :: P14 :: nil) (P1 :: P4 :: P8 :: P14 :: P8 :: P11 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P8 :: P14 :: P8 :: P11 :: P14 :: nil) ((P1 :: P4 :: P8 :: P14 :: nil) ++ (P8 :: P11 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P4P8P11P14mtmp;try rewrite HT2 in HP1P4P8P11P14mtmp.\n\tassert(HT := rule_4 (P1 :: P4 :: P8 :: P14 :: nil) (P8 :: P11 :: P14 :: nil) (P8 :: P14 :: nil) 4 2 3 HP1P4P8P11P14mtmp HP8P14mtmp HP1P4P8P14Mtmp Hincl); apply HT.\n}\ntry clear HP8P11P14m2. try clear HP1P4P8P11P14M4. try clear HP1P4P8P11P14m4. \n\nassert(HP1P2P4P8P11P12P13P14m2 : rk(P1 :: P2 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P8P11P12P13P14m1. \n\nassert(HP1P2P4P8P11P12P13P14m3 : rk(P1 :: P2 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P2P4mtmp : rk(P1 :: P2 :: P4 :: nil) >= 3) by (solve_hyps_min HP1P2P4eq HP1P2P4m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: nil) (P1 :: P2 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) 3 3 HP1P2P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4M3. try clear HP1P2P4m3. try clear HP1P2P4P8P11P12P13P14m2. \n\nassert(HP1P2P4P8P11P12P13P14m4 : rk(P1 :: P2 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) >= 4).\n{\n\tassert(HP1P2P4P8mtmp : rk(P1 :: P2 :: P4 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8eq HP1P2P4P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P4 :: P8 :: nil) (P1 :: P2 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) 4 4 HP1P2P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P4P8M4. try clear HP1P2P4P8m4. try clear HP1P2P4P8P11P12P13P14m3. \n\nassert(HP1P4P8P11P12P13P14m2 : rk(P1 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P4mtmp : rk(P1 :: P4 :: nil) >= 2) by (solve_hyps_min HP1P4eq HP1P4m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: nil) (P1 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: nil) (P1 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) 2 2 HP1P4mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4M2. try clear HP1P4m2. try clear HP1P4P8P11P12P13P14m1. \n\nassert(HP1P4P8P11P12P13P14m3 : rk(P1 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P4P8mtmp : rk(P1 :: P4 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P4P8eq HP1P4P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P4 :: P8 :: nil) (P1 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P4 :: P8 :: nil) (P1 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) 3 3 HP1P4P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P4P8M3. try clear HP1P4P8m3. try clear HP1P4P8P11P12P13P14m2. \n\nassert(HP1P4P8P11P12P13P14m4 : rk(P1 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) >= 4).\n{\n\tassert(HP1P2P8P11Mtmp : rk(P1 :: P2 :: P8 :: P11 :: nil) <= 3) by (solve_hyps_max HP1P2P8P11eq HP1P2P8P11M3).\n\tassert(HP1P2P4P8P11P12P13P14mtmp : rk(P1 :: P2 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P2P4P8P11P12P13P14eq HP1P2P4P8P11P12P13P14m4).\n\tassert(HP1P8P11mtmp : rk(P1 :: P8 :: P11 :: nil) >= 3) by (solve_hyps_min HP1P8P11eq HP1P8P11m3).\n\tassert(Hincl : incl (P1 :: P8 :: P11 :: nil) (list_inter (P1 :: P2 :: P8 :: P11 :: nil) (P1 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) (P1 :: P2 :: P8 :: P11 :: P1 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P2 :: P8 :: P11 :: P1 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) ((P1 :: P2 :: P8 :: P11 :: nil) ++ (P1 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P4P8P11P12P13P14mtmp;try rewrite HT2 in HP1P2P4P8P11P12P13P14mtmp.\n\tassert(HT := rule_4 (P1 :: P2 :: P8 :: P11 :: nil) (P1 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) (P1 :: P8 :: P11 :: nil) 4 3 3 HP1P2P4P8P11P12P13P14mtmp HP1P8P11mtmp HP1P2P8P11Mtmp Hincl); apply HT.\n}\ntry clear HP1P2P8P11M3. try clear HP1P2P8P11m3. try clear HP1P4P8P11P12P13P14m3. try clear HP1P2P4P8P11P12P13P14M4. try clear HP1P2P4P8P11P12P13P14m4. \n\nassert(HP8P11P12P13P14m2 : rk(P8 :: P11 :: P12 :: P13 :: P14 :: nil) >= 2).\n{\n\tassert(HP8P11mtmp : rk(P8 :: P11 :: nil) >= 2) by (solve_hyps_min HP8P11eq HP8P11m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P8 :: P11 :: nil) (P8 :: P11 :: P12 :: P13 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P8 :: P11 :: nil) (P8 :: P11 :: P12 :: P13 :: P14 :: nil) 2 2 HP8P11mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP8P11M2. try clear HP8P11m2. try clear HP8P11P12P13P14m1. \n\nassert(HP8P11P12P13P14m3 : rk(P8 :: P11 :: P12 :: P13 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P4P8P14Mtmp : rk(P1 :: P4 :: P8 :: P14 :: nil) <= 3) by (solve_hyps_max HP1P4P8P14eq HP1P4P8P14M3).\n\tassert(HP1P4P8P11P12P13P14mtmp : rk(P1 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P4P8P11P12P13P14eq HP1P4P8P11P12P13P14m4).\n\tassert(HP8P14mtmp : rk(P8 :: P14 :: nil) >= 2) by (solve_hyps_min HP8P14eq HP8P14m2).\n\tassert(Hincl : incl (P8 :: P14 :: nil) (list_inter (P1 :: P4 :: P8 :: P14 :: nil) (P8 :: P11 :: P12 :: P13 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) (P1 :: P4 :: P8 :: P14 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P8 :: P14 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) ((P1 :: P4 :: P8 :: P14 :: nil) ++ (P8 :: P11 :: P12 :: P13 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P4P8P11P12P13P14mtmp;try rewrite HT2 in HP1P4P8P11P12P13P14mtmp.\n\tassert(HT := rule_4 (P1 :: P4 :: P8 :: P14 :: nil) (P8 :: P11 :: P12 :: P13 :: P14 :: nil) (P8 :: P14 :: nil) 4 2 3 HP1P4P8P11P12P13P14mtmp HP8P14mtmp HP1P4P8P14Mtmp Hincl); apply HT.\n}\ntry clear HP8P11P12P13P14m2. try clear HP8P14M2. try clear HP8P14m2. \n\nassert(HP8P11P12P13P14M3 : rk(P8 :: P11 :: P12 :: P13 :: P14 :: nil) <= 3).\n{\n\tassert(HP8P11P12P14Mtmp : rk(P8 :: P11 :: P12 :: P14 :: nil) <= 3) by (solve_hyps_max HP8P11P12P14eq HP8P11P12P14M3).\n\tassert(HP8P11P13P14Mtmp : rk(P8 :: P11 :: P13 :: P14 :: nil) <= 3) by (solve_hyps_max HP8P11P13P14eq HP8P11P13P14M3).\n\tassert(HP8P11P14mtmp : rk(P8 :: P11 :: P14 :: nil) >= 3) by (solve_hyps_min HP8P11P14eq HP8P11P14m3).\n\tassert(Hincl : incl (P8 :: P11 :: P14 :: nil) (list_inter (P8 :: P11 :: P12 :: P14 :: nil) (P8 :: P11 :: P13 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P8 :: P11 :: P12 :: P13 :: P14 :: nil) (P8 :: P11 :: P12 :: P14 :: P8 :: P11 :: P13 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P8 :: P11 :: P12 :: P14 :: P8 :: P11 :: P13 :: P14 :: nil) ((P8 :: P11 :: P12 :: P14 :: nil) ++ (P8 :: P11 :: P13 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P8 :: P11 :: P12 :: P14 :: nil) (P8 :: P11 :: P13 :: P14 :: nil) (P8 :: P11 :: P14 :: nil) 3 3 3 HP8P11P12P14Mtmp HP8P11P13P14Mtmp HP8P11P14mtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\ntry clear HP8P11P12P14M3. try clear HP8P11P12P14m3. try clear HP8P11P13P14M3. try clear HP8P11P13P14m3. try clear HP8P11P14M3. try clear HP8P11P14m3. try clear HP8P11P12P13P14M4. \n\nassert(HP1P2P6P8P10P14m2 : rk(P1 :: P2 :: P6 :: P8 :: P10 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P2mtmp : rk(P1 :: P2 :: nil) >= 2) by (solve_hyps_min HP1P2eq HP1P2m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: nil) (P1 :: P2 :: P6 :: P8 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: nil) (P1 :: P2 :: P6 :: P8 :: P10 :: P14 :: nil) 2 2 HP1P2mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2M2. try clear HP1P2m2. try clear HP1P2P6P8P10P14m1. \n\nassert(HP1P2P6P8P10P14m3 : rk(P1 :: P2 :: P6 :: P8 :: P10 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P2P6mtmp : rk(P1 :: P2 :: P6 :: nil) >= 3) by (solve_hyps_min HP1P2P6eq HP1P2P6m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P6 :: nil) (P1 :: P2 :: P6 :: P8 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P6 :: nil) (P1 :: P2 :: P6 :: P8 :: P10 :: P14 :: nil) 3 3 HP1P2P6mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P6M3. try clear HP1P2P6m3. try clear HP1P2P6P8P10P14m2. \n\nassert(HP1P2P6P8P10P14m4 : rk(P1 :: P2 :: P6 :: P8 :: P10 :: P14 :: nil) >= 4).\n{\n\tassert(HP1P2P6P8mtmp : rk(P1 :: P2 :: P6 :: P8 :: nil) >= 4) by (solve_hyps_min HP1P2P6P8eq HP1P2P6P8m4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P2 :: P6 :: P8 :: nil) (P1 :: P2 :: P6 :: P8 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P2 :: P6 :: P8 :: nil) (P1 :: P2 :: P6 :: P8 :: P10 :: P14 :: nil) 4 4 HP1P2P6P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P2P6P8M4. try clear HP1P2P6P8m4. try clear HP1P2P6P8P10P14m3. \n\nassert(HP1P6P8P10P14m2 : rk(P1 :: P6 :: P8 :: P10 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P6mtmp : rk(P1 :: P6 :: nil) >= 2) by (solve_hyps_min HP1P6eq HP1P6m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P6 :: nil) (P1 :: P6 :: P8 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P6 :: nil) (P1 :: P6 :: P8 :: P10 :: P14 :: nil) 2 2 HP1P6mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P6M2. try clear HP1P6m2. try clear HP1P6P8P10P14m1. \n\nassert(HP1P6P8P10P14m3 : rk(P1 :: P6 :: P8 :: P10 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P6P8mtmp : rk(P1 :: P6 :: P8 :: nil) >= 3) by (solve_hyps_min HP1P6P8eq HP1P6P8m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P6 :: P8 :: nil) (P1 :: P6 :: P8 :: P10 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P6 :: P8 :: nil) (P1 :: P6 :: P8 :: P10 :: P14 :: nil) 3 3 HP1P6P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P6P8M3. try clear HP1P6P8m3. try clear HP1P6P8P10P14m2. \n\nassert(HP1P6P8P10P14m4 : rk(P1 :: P6 :: P8 :: P10 :: P14 :: nil) >= 4).\n{\n\tassert(HP2P8P10Mtmp : rk(P2 :: P8 :: P10 :: nil) <= 2) by (solve_hyps_max HP2P8P10eq HP2P8P10M2).\n\tassert(HP1P2P6P8P10P14mtmp : rk(P1 :: P2 :: P6 :: P8 :: P10 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P2P6P8P10P14eq HP1P2P6P8P10P14m4).\n\tassert(HP8P10mtmp : rk(P8 :: P10 :: nil) >= 2) by (solve_hyps_min HP8P10eq HP8P10m2).\n\tassert(Hincl : incl (P8 :: P10 :: nil) (list_inter (P2 :: P8 :: P10 :: nil) (P1 :: P6 :: P8 :: P10 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P2 :: P6 :: P8 :: P10 :: P14 :: nil) (P2 :: P8 :: P10 :: P1 :: P6 :: P8 :: P10 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P2 :: P8 :: P10 :: P1 :: P6 :: P8 :: P10 :: P14 :: nil) ((P2 :: P8 :: P10 :: nil) ++ (P1 :: P6 :: P8 :: P10 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P2P6P8P10P14mtmp;try rewrite HT2 in HP1P2P6P8P10P14mtmp.\n\tassert(HT := rule_4 (P2 :: P8 :: P10 :: nil) (P1 :: P6 :: P8 :: P10 :: P14 :: nil) (P8 :: P10 :: nil) 4 2 2 HP1P2P6P8P10P14mtmp HP8P10mtmp HP2P8P10Mtmp Hincl); apply HT.\n}\ntry clear HP2P8P10M2. try clear HP2P8P10m2. try clear HP1P6P8P10P14m3. try clear HP8P10M2. try clear HP8P10m2. try clear HP1P2P6P8P10P14M4. try clear HP1P2P6P8P10P14m4. \n\nassert(HP1P8P14m2 : rk(P1 :: P8 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P8mtmp : rk(P1 :: P8 :: nil) >= 2) by (solve_hyps_min HP1P8eq HP1P8m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P8 :: nil) (P1 :: P8 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P8 :: nil) (P1 :: P8 :: P14 :: nil) 2 2 HP1P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P8P14m1. \n\nassert(HP1P8P14m3 : rk(P1 :: P8 :: P14 :: nil) >= 3).\n{\n\tassert(HP6P10P14Mtmp : rk(P6 :: P10 :: P14 :: nil) <= 2) by (solve_hyps_max HP6P10P14eq HP6P10P14M2).\n\tassert(HP1P6P8P10P14mtmp : rk(P1 :: P6 :: P8 :: P10 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P6P8P10P14eq HP1P6P8P10P14m4).\n\tassert(HP14mtmp : rk(P14 :: nil) >= 1) by (solve_hyps_min HP14eq HP14m1).\n\tassert(Hincl : incl (P14 :: nil) (list_inter (P1 :: P8 :: P14 :: nil) (P6 :: P10 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P6 :: P8 :: P10 :: P14 :: nil) (P1 :: P8 :: P14 :: P6 :: P10 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P8 :: P14 :: P6 :: P10 :: P14 :: nil) ((P1 :: P8 :: P14 :: nil) ++ (P6 :: P10 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P6P8P10P14mtmp;try rewrite HT2 in HP1P6P8P10P14mtmp.\n\tassert(HT := rule_2 (P1 :: P8 :: P14 :: nil) (P6 :: P10 :: P14 :: nil) (P14 :: nil) 4 1 2 HP1P6P8P10P14mtmp HP14mtmp HP6P10P14Mtmp Hincl);apply HT.\n}\ntry clear HP1P8P14m2. try clear HP6P10P14M2. try clear HP6P10P14m2. try clear HP1P6P8P10P14M4. try clear HP1P6P8P10P14m4. \n\nassert(HP1P8P11P12P13P14m2 : rk(P1 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P8mtmp : rk(P1 :: P8 :: nil) >= 2) by (solve_hyps_min HP1P8eq HP1P8m2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P8 :: nil) (P1 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P8 :: nil) (P1 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) 2 2 HP1P8mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P8M2. try clear HP1P8m2. try clear HP1P8P11P12P13P14m1. \n\nassert(HP1P8P11P12P13P14m3 : rk(P1 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) >= 3).\n{\n\tassert(HP1P8P11mtmp : rk(P1 :: P8 :: P11 :: nil) >= 3) by (solve_hyps_min HP1P8P11eq HP1P8P11m3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (P1 :: P8 :: P11 :: nil) (P1 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (P1 :: P8 :: P11 :: nil) (P1 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) 3 3 HP1P8P11mtmp Hcomp Hincl);apply HT.\n}\ntry clear HP1P8P11M3. try clear HP1P8P11m3. try clear HP1P8P11P12P13P14m2. \n\nassert(HP1P8P11P12P13P14m4 : rk(P1 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) >= 4).\n{\n\tassert(HP1P4P8P14Mtmp : rk(P1 :: P4 :: P8 :: P14 :: nil) <= 3) by (solve_hyps_max HP1P4P8P14eq HP1P4P8P14M3).\n\tassert(HP1P4P8P11P12P13P14mtmp : rk(P1 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P4P8P11P12P13P14eq HP1P4P8P11P12P13P14m4).\n\tassert(HP1P8P14mtmp : rk(P1 :: P8 :: P14 :: nil) >= 3) by (solve_hyps_min HP1P8P14eq HP1P8P14m3).\n\tassert(Hincl : incl (P1 :: P8 :: P14 :: nil) (list_inter (P1 :: P4 :: P8 :: P14 :: nil) (P1 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P4 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) (P1 :: P4 :: P8 :: P14 :: P1 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P8 :: P14 :: P1 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) ((P1 :: P4 :: P8 :: P14 :: nil) ++ (P1 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P4P8P11P12P13P14mtmp;try rewrite HT2 in HP1P4P8P11P12P13P14mtmp.\n\tassert(HT := rule_4 (P1 :: P4 :: P8 :: P14 :: nil) (P1 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) (P1 :: P8 :: P14 :: nil) 4 3 3 HP1P4P8P11P12P13P14mtmp HP1P8P14mtmp HP1P4P8P14Mtmp Hincl); apply HT.\n}\ntry clear HP1P8P11P12P13P14m3. try clear HP1P8P14M3. try clear HP1P8P14m3. try clear HP1P4P8P11P12P13P14M4. try clear HP1P4P8P11P12P13P14m4. \n\nassert(HP12P13P14m2 : rk(P12 :: P13 :: P14 :: nil) >= 2).\n{\n\tassert(HP1P4P8P14Mtmp : rk(P1 :: P4 :: P8 :: P14 :: nil) <= 3) by (solve_hyps_max HP1P4P8P14eq HP1P4P8P14M3).\n\tassert(HP1P4P8P12P13P14mtmp : rk(P1 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P4P8P12P13P14eq HP1P4P8P12P13P14m4).\n\tassert(HP14mtmp : rk(P14 :: nil) >= 1) by (solve_hyps_min HP14eq HP14m1).\n\tassert(Hincl : incl (P14 :: nil) (list_inter (P1 :: P4 :: P8 :: P14 :: nil) (P12 :: P13 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P4 :: P8 :: P12 :: P13 :: P14 :: nil) (P1 :: P4 :: P8 :: P14 :: P12 :: P13 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P4 :: P8 :: P14 :: P12 :: P13 :: P14 :: nil) ((P1 :: P4 :: P8 :: P14 :: nil) ++ (P12 :: P13 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P4P8P12P13P14mtmp;try rewrite HT2 in HP1P4P8P12P13P14mtmp.\n\tassert(HT := rule_4 (P1 :: P4 :: P8 :: P14 :: nil) (P12 :: P13 :: P14 :: nil) (P14 :: nil) 4 1 3 HP1P4P8P12P13P14mtmp HP14mtmp HP1P4P8P14Mtmp Hincl); apply HT.\n}\ntry clear HP1P4P8P14M3. try clear HP1P4P8P14m3. try clear HP12P13P14m1. try clear HP14M1. try clear HP14m1. try clear HP1P4P8P12P13P14M4. try clear HP1P4P8P12P13P14m4. \n\nassert(HP12P13P14M2 : rk(P12 :: P13 :: P14 :: nil) <= 2).\n{\n\tassert(HP1P12P13P14Mtmp : rk(P1 :: P12 :: P13 :: P14 :: nil) <= 3) by (solve_hyps_max HP1P12P13P14eq HP1P12P13P14M3).\n\tassert(HP8P11P12P13P14Mtmp : rk(P8 :: P11 :: P12 :: P13 :: P14 :: nil) <= 3) by (solve_hyps_max HP8P11P12P13P14eq HP8P11P12P13P14M3).\n\tassert(HP1P8P11P12P13P14mtmp : rk(P1 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) >= 4) by (solve_hyps_min HP1P8P11P12P13P14eq HP1P8P11P12P13P14m4).\n\tassert(Hincl : incl (P12 :: P13 :: P14 :: nil) (list_inter (P1 :: P12 :: P13 :: P14 :: nil) (P8 :: P11 :: P12 :: P13 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) (P1 :: P12 :: P13 :: P14 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P12 :: P13 :: P14 :: P8 :: P11 :: P12 :: P13 :: P14 :: nil) ((P1 :: P12 :: P13 :: P14 :: nil) ++ (P8 :: P11 :: P12 :: P13 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P8P11P12P13P14mtmp;try rewrite HT2 in HP1P8P11P12P13P14mtmp.\n\tassert(HT := rule_3 (P1 :: P12 :: P13 :: P14 :: nil) (P8 :: P11 :: P12 :: P13 :: P14 :: nil) (P12 :: P13 :: P14 :: nil) 3 3 4 HP1P12P13P14Mtmp HP8P11P12P13P14Mtmp HP1P8P11P12P13P14mtmp Hincl);apply HT.\n}\ntry clear HP8P11P12P13P14M3. try clear HP8P11P12P13P14m3. try clear HP12P13P14M3. try clear HP1P8P11P12P13P14M4. try clear HP1P8P11P12P13P14m4. \n\nassert(HP12P13M1 : rk(P12 :: P13 :: nil) <= 1).\n{\n\tassert(HP1P12P13Mtmp : rk(P1 :: P12 :: P13 :: nil) <= 2) by (solve_hyps_max HP1P12P13eq HP1P12P13M2).\n\tassert(HP12P13P14Mtmp : rk(P12 :: P13 :: P14 :: nil) <= 2) by (solve_hyps_max HP12P13P14eq HP12P13P14M2).\n\tassert(HP1P12P13P14mtmp : rk(P1 :: P12 :: P13 :: P14 :: nil) >= 3) by (solve_hyps_min HP1P12P13P14eq HP1P12P13P14m3).\n\tassert(Hincl : incl (P12 :: P13 :: nil) (list_inter (P1 :: P12 :: P13 :: nil) (P12 :: P13 :: P14 :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (P1 :: P12 :: P13 :: P14 :: nil) (P1 :: P12 :: P13 :: P12 :: P13 :: P14 :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P1 :: P12 :: P13 :: P12 :: P13 :: P14 :: nil) ((P1 :: P12 :: P13 :: nil) ++ (P12 :: P13 :: P14 :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HP1P12P13P14mtmp;try rewrite HT2 in HP1P12P13P14mtmp.\n\tassert(HT := rule_3 (P1 :: P12 :: P13 :: nil) (P12 :: P13 :: P14 :: nil) (P12 :: P13 :: nil) 2 2 3 HP1P12P13Mtmp HP12P13P14Mtmp HP1P12P13P14mtmp Hincl);apply HT.\n}\ntry clear HP1P12P13M2. try clear HP1P12P13m2. try clear HP12P13P14M2. try clear HP12P13P14m2. try clear HP12P13M2. try clear HP1P12P13P14M3. try clear HP1P12P13P14m3. \n\nassert(rk(P12 :: P13 ::  nil) <= 2) by (solve[apply matroid1_b_useful;simpl;repeat constructor|apply rk_upper_dim]).\nassert(rk(P12 :: P13 ::  nil) >= 1) by (solve[apply matroid1_b_useful2;simpl;repeat constructor|apply matroid1_a]).\nomega.\nQed.\n", "meta": {"author": "pascalschreck", "repo": "MatroidIncidenceProver", "sha": "e492d375a2264e6c908c9c47fe719c39e3f847f8", "save_path": "github-repos/coq/pascalschreck-MatroidIncidenceProver", "path": "github-repos/coq/pascalschreck-MatroidIncidenceProver/MatroidIncidenceProver-e492d375a2264e6c908c9c47fe719c39e3f847f8/matroidbasedIGprover/matroid_C_Coq/DevCoq/Dev/lemmas_automation_gV2_no_hyps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.2550170223995919}}
{"text": "Set Implicit Arguments.\nUnset Strict Implicit.\n\nRequire Import basics.\nRequire Import enat.\nRequire Import allen.\nRequire Import signal.\nRequire Import borders.\nRequire Import compare.\nRequire Import reactives.\n\n\nSection extend.\n\nLtac G x := generalize x.\n\nLtac BAD := intros BAD; inversion BAD.\n\nLtac INC_CMP CV1 CV2 :=\n  intros I J (LL,RR);\n  apply (inc_allen_by_comp2 (CV1 _ _ LL) (CV2 _ _ RR)).\n\nLtac RINC_CMP CV1 CV2 :=\n  intros I J (LL,RR);\n  apply (inc_allen_by_comp2 (CV1 _ _ LL) (CV2 _ _ RR)).\n\n\n\n(* eq_pred *)\n\nDefinition eq_pred (f g:(allen -> Prop)) := forall I, (f I)<->(g I).\n\n\n\n(*\n * filter\n *)\nDefinition filter (f:(allen -> Prop)) (p:sig) : sig :=\n fun t => (exists I, (tas t I p) /\\ (f I)).\n\nLemma eq_pred_eq_filter (f g:(allen -> Prop)) (p:sig) :\n (eq_pred f g) -> (eq_sig (filter f p) (filter g p)).\nintros EQ t.\nsplit;intros (I,(tIp,fI));exists I;split;auto.\n- rewrite <- (EQ I); auto.\n- rewrite (EQ I); auto.\nQed.\n\nLemma filter_follow_changes (F:allen->Prop) (p:sig) (t:nat) :\n (p t) ->\n (p (S t)) ->\n ((filter F p) t) ->\n ((filter F p) (S t)).\nintros Pt PSt (I,((tI,Ip),FI)).\nexists I.\nsplit;[split|];auto.\napply (in_allen_in_sig__on_succ (tas_def tI Ip) PSt).\nQed.\n\nLemma filter_unfollow_changes (F:allen->Prop) (p:sig) (t:nat) :\n (p t) ->\n (p (S t)) ->\n ((filter F p) (S t)) ->\n ((filter F p) t).\nintros Pt PSt (I,((StI,Ip),FI)).\nexists I.\nsplit;[split|];auto.\napply (in_allen_in_sig__on_prev (tas_def StI Ip) Pt).\nQed.\n\nLemma continuous___same_filter (F:allen->Prop) (p:sig) (t:nat) :\n (p t) ->\n (p (S t)) ->\n (((filter F p) t) <-> ((filter F p) (S t))).\nintros Pt PSt.\nsplit; [ apply (filter_follow_changes Pt PSt)\n       | apply (filter_unfollow_changes Pt PSt)].\nQed.\n\nLemma inc_sig_filter (F:allen->Prop) (p:sig) : (inc_sig (filter F p) p).\nintros t (I,(tIp,_)).\napply (tas_p tIp).\nQed.\n\nLemma filter_in_sig (p:sig) (f:allen->Prop) (I:allen) :\n (in_sig I p) ->\n (f I) ->\n (in_sig I (filter f p)).\nintros IInp FI.\nsplit;[|split].\n- case_eq (left I); auto; intros pli LI.\n  intros (II,((pliInII,IIInp),FII)).\n  G (previous_left_out IInp LI). apply not_not.\n  apply (tas_p (tas_def pliInII IIInp)).\n- case_eq (right I); auto; intros ri RI.\n  intros (II,((pliInII,IIInp),FII)).\n  apply (bounded_right_out IInp RI).\n  apply (tas_p (tas_def pliInII IIInp)).\n- intros t tInI; exists I; split; auto; split; auto.\nQed.\n\nLemma inc_sig_filters (f g:(allen -> Prop)) (p:sig) :\n (forall I, (f I) -> (g I)) ->\n (inc_sig (filter f p) (filter g p)).\nintros INC t (I,(tIp,FI)).\nexists I. split;[auto|].\napply (INC I FI).\nQed.\n\nLemma inc_sig_allen_filter (F:allen->Prop) (p:sig) :\n (inc_sig_allen (filter F p) p).\nintros I IInEx.\nG IInEx; intros (A,(B,C)).\nsplit;[|split].\n- case_eq (left I); auto.\n  intros l LI Pl.\n  rewrite LI in A.\n  apply A.\n  G (in_left IInEx); rewrite LI; intros AS.\n  rewrite continuous___same_filter;[ auto | auto | ].\n  apply (inc_sig_filter AS).\n- case_eq (right I); auto.\n  intros r RI Pr.\n  rewrite RI in B.\n  apply B.\n  G (previous_right RI); intros (pr,PRI).\n  rewrite PRI.\n  rewrite PRI in RI.\n  rewrite PRI in Pr.\n  G (previous_right_in IInEx RI); intros BP.\n  rewrite <- continuous___same_filter;[auto | | auto ].\n  apply (inc_sig_filter BP).\n- intros t tInI.\n  apply (inc_sig_filter (C _ tInI)).\nQed.\n\nLemma in_sig_filter (p:sig) (f:allen->Prop) (I:allen) :\n (in_sig I (filter f p)) ->\n (safe_allen_fun f) ->\n (f I).\nintros IInF SF.\nG (in_left IInF). intros (J,((lJ,Jp),FJ)).\nG (inc_sig_allen_filter IInF); intros IInp.\nG (tas_uniq (tas_def lJ Jp) (tas_def (in_allen_left I) IInp)); intros EQA.\napply (SF _ _ EQA FJ).\nQed.\n\nLemma tas_filter_tas_arg (F:allen->Prop) (p:sig) (I:allen) (t:nat) :\n (tas t I (filter F p)) ->\n (tas t I p).\nintros (tInI,IInF).\nsplit;[auto|].\napply (inc_sig_allen_filter IInF).\nQed.\n\nLemma filter_tas (p:sig) (f:allen->Prop) (I:allen) (t:nat):\n (tas t I p) ->\n (f I) ->\n (tas t I (filter f p)).\nintros tIp FI.\napply (tas_def (tas_allen tIp) (filter_in_sig (tas_sig tIp) FI)).\nQed.\n\n\nLemma not_filter (f g:(allen -> Prop)) (p:sig) :\n (safe_allen_fun f) ->\n (inc_sig (or_sig (filter (fun I => ~(f I)) p) (not_sig p))\n          (not_sig (filter f p)) ).\nintros SF t [(I,(tIp,NF))|Np].\n- apply all_not_not_ex.\n  intros II.\n  apply or_not_not_and.\n  G (pcheck (tas t II p)). intros [EQ|NEQ]; [right|left;auto].\n  G NF; apply ncontra.\n  apply (SF _ _ (eq_allen_sym (tas_uniq tIp EQ))).\n- G Np; apply ncontra.\n  apply inc_sig_filter.\nQed.\n\n\n(*\n * EXTEND\n *)\nDefinition extend (R:(allen -> allen -> Prop)) (p q:sig) : sig :=\n (filter (fun I => (exists J, (in_sig J q) /\\ (R I J))) p).\n\nLemma inc_sig_extend_left (R:allen->allen->Prop) (p q:sig) :\n (inc_sig (extend R p q) p).\napply inc_sig_filter.\nQed.\n\nLemma contra_extend (R1 R2:(allen -> allen -> Prop)) (p q:sig) (t:nat) :\n (safe_allen_relation R2) ->\n (inclusive_relation R1) ->\n (inclusive_relation R2) ->\n (forall I J, (R1 I J) -> (R2 I J) -> False) ->\n (extend R1 p q t) ->\n (extend R2 p q t) ->\n False.\nintros SF INC1 INC2 IMP (I,(tIp,(J,(Jq,R1IJ)))) (II,(tIIp,(JJ,(JJq,R2IJ)))).\nG (inc_allen_in_allen (INC1 _ _ R1IJ) (tas_allen tIp)). intros tJ.\nG (inc_allen_in_allen (INC2 _ _ R2IJ) (tas_allen tIIp)). intros tJJ.\nG (tas_uniq tIIp tIp). intros III.\nG (tas_uniq (tas_def tJJ JJq) (tas_def tJ Jq)). intros JJJ.\napply (IMP _ _ R1IJ (SF _ _ _ _ III JJJ R2IJ)).\nQed.\n\n(* should be used for all inclusive relation *)\nLemma ext_inc (R:(allen -> allen -> Prop)) (p q:sig) (t:nat) :\n (extend R p q t) ->\n (inclusive_relation R) ->\n (exists I, (tas t I p) /\\ (exists J, (tas t J q) /\\ (R I J))).\nintros (I,(tIp,(J,(JInq,RIJ)))) INC.\nexists I. split;[auto|].\nexists J. split;[|auto].\nsplit;[|auto].\napply (inc_allen_in_allen (INC _ _ RIJ) (tas_allen tIp)).\nQed.\n\nLemma inc_sig_not_extend (f:(allen -> allen -> Prop)) (p q:sig) :\n (inc_sig (not_sig p) (not_sig (extend f p q))).\napply inc_sig_not.\napply inc_sig_filter.\nQed.\n\n\n\n\nEnd extend.\n", "meta": {"author": "NicVolanschi", "repo": "Allen", "sha": "daf340d71f26f7fd589b46125853407b89280160", "save_path": "github-repos/coq/NicVolanschi-Allen", "path": "github-repos/coq/NicVolanschi-Allen/Allen-daf340d71f26f7fd589b46125853407b89280160/proof/extend.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.25501702239959184}}
{"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 seq_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_u_prg copy_s_u_triple copy_s_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.\n\nLemma copy_s_u_safe_termination a0 a1 a2 a3 rk ry y rx x d :\n  uniq(x, y) ->  uniq(rk, rx, ry, a0, a1, a2, a3, r0) ->\n  safe_termination\n  (fun st s h => state_mint (x |=> signed (Z.abs_nat (u2Z ([rk ]_ s))) rx \\U+\n      (y |=> unsign rk ry \\U+ d s)) st s h)\n  (copy_s_u rk rx ry a0 a1 a2 a3).\nProof.\nmove=> Hvars Hnodup.\nrewrite /safe_termination => st s h st_s_h.\ncase: (copy_s_u_termination s h _ _ _ _ _ _ _ Hnodup) => si Hsi.\nmove: (proj1 st_s_h x (signed (Z.abs_nat (u2Z ([rk ]_ s))) rx)).\nrewrite assoc.get_union_sing_eq.\nmove/(_ (refl_equal _)).\ncase=> len ptr U ru_fit encU ptr_fit HU.\ncase: encU => u1 u2 u3 u4.\nmove: (proj1 st_s_h y (unsign rk ry)).\nrewrite assoc.get_union_sing_neq; last by Uniq_neq.\nrewrite assoc.get_union_sing_eq.\ncase/(_ (refl_equal _)) => rx_fit Hx HX.\nmove: (copy_s_u_triple _ _ _ _ _ _ _ Hnodup U (Z2ints 32 (Z.abs_nat (u2Z ([rk ]_ s)))\n               ([ y ]_ st)%pseudo_expr) (Z.abs_nat (u2Z ([rk ]_ s))) u1).\nrewrite size_Z2ints.\nmove/(_ (refl_equal _) len ptr ptr_fit _ rx_fit) => hoare_triple.\napply constructive_indefinite_description'.\nmove: (triple_exec_precond _ _ _ hoare_triple _ _ _ Hsi\n  (heap.dom (heap_mint (signed (Z.abs_nat (u2Z ([rk ]_ s))) rx) s h \\U\n  heap_mint (unsign rk ry) s h))).\napply.\nsplit; first reflexivity.\nsplit; first by rewrite Z_of_nat_Zabs_nat //; exact: min_u2Z.\nsuff : h |P|\n        (heap.dom (heap_mint (signed (Z.abs_nat (u2Z ([rk ]_ s))) rx) s h \\U\n            heap_mint (unsign rk ry) s h)) =\n       heap_mint (signed (Z.abs_nat (u2Z ([rk ]_ s))) rx) s h \\U\n                 heap_mint (unsign rk ry) s h.\n  move=> ->.\n  apply assert_m.con_cons => //.\n  apply (proj2 st_s_h x y) => //; by [Uniq_neq | assoc_get_Some | assoc_get_Some].\nrewrite -heap.incluE.\napply heap_prop_m.inclu_union.\nexact: heap_inclu_heap_mint_signed.\nexact: 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_s_u_safe_termination.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.25493396656562956}}
{"text": "Require Import msl.seplog.\nRequire Import msl.base.\nRequire Import msl.ageable.\nRequire Import msl.sepalg.\nRequire Import msl.age_sepalg.\nRequire Import msl.predicates_hered.\nRequire Import msl.predicates_sl.\nRequire Import msl.subtypes.\nRequire Import msl.subtypes_sl.\nRequire Import msl.predicates_rec.\nRequire Import msl.contractive.\nRequire msl.normalize.\n\nLocal Open Scope logic.\n\nInstance algNatDed (T: Type){agT: ageable T} : NatDed (pred T).\n  apply (mkNatDed _\n                    predicates_hered.andp\n                    predicates_hered.orp\n                    (@predicates_hered.exp _ _)\n                    (@predicates_hered.allp _ _)\n                    predicates_hered.imp predicates_hered.prop\n                    (@predicates_hered.derives _ _)).\n apply pred_ext.\n apply derives_refl.\n apply derives_trans.\n apply andp_right.\n apply andp_left1.\n apply andp_left2.\n apply orp_left.\n apply orp_right1.\n apply orp_right2.\n intros ? ?; apply @exp_right.\n intros ? ?; apply @exp_left.\n intros ? ?; apply @allp_left.\n intros ? ?; apply @allp_right.\n apply imp_andp_adjoint.\n repeat intro. eapply H; eauto. hnf; auto.\n repeat intro. hnf; auto.\n repeat intro. specialize (H a (necR_refl _)). simpl in H. auto.\n repeat intro. specialize (H b). simpl in H. auto.\nDefined.\n\nInstance algSepLog (T: Type) {agT: ageable T}{JoinT: Join T}{PermT: Perm_alg T}{SepT: Sep_alg T}{AgeT: Age_alg T} :\n      @SepLog (pred T) (algNatDed T).\n apply (mkSepLog _ (algNatDed T) predicates_sl.emp predicates_sl.sepcon\n            predicates_sl.wand predicates_sl.ewand).\n apply sepcon_assoc.\n apply sepcon_comm.\n intros. pose proof (wand_sepcon_adjoint P Q R). simpl. rewrite H; split; auto.\n intros; simpl. apply predicates_hered.pred_ext; simpl.\n          intros ? [w1 [w2 [? [? [? ?]]]]];  split; auto. exists w1; exists w2; repeat split; auto.\n          intros ? [? [w1 [w2 [? [? ?]]]]];  exists w1; exists w2; repeat split; auto.\n intros; intro; apply sepcon_derives; auto.\n intros; simpl; apply ewand_sepcon; auto.\n intros; simpl. apply ewand_TT_sepcon; auto.\n intros; simpl. intros w [w1 [w2 [? [? ?]]]]. exists w1,w2; repeat split; auto. exists w2; exists w; repeat split; auto.\n  intros; simpl. apply ewand_conflict; auto.\nDefined.\n\nInstance algClassicalSep (T: Type) {agT: ageable T}{JoinT: Join T}{PermT: Perm_alg T}{SepT: Sep_alg T}{CancT: Canc_alg T}{AgeT: Age_alg T}:\n     @ClassicalSep (pred T) (algNatDed T)(algSepLog T).\n constructor; intros. simpl. apply predicates_sl.sepcon_emp.\nQed.\n\nDefinition Triv := predicates_hered.pred nat.\nInstance TrivNatDed: NatDed Triv := algNatDed nat.\nInstance TrivSeplog: SepLog Triv := @algSepLog nat _ _ _ _ (asa_nat).\nInstance TrivClassical: ClassicalSep Triv := @algClassicalSep _ _ _ _ _ _ asa_nat.\nInstance TrivIntuitionistic: IntuitionisticSep Triv.\n constructor. intros. hnf. intros. destruct H as [w1 [w2 [? [? _]]]].\n destruct H; subst; auto.\nQed.\n\nInstance algIndir (T: Type) {agT: ageable T}{JoinT: Join T}{PermT: Perm_alg T}{SepT: Sep_alg T}\n                {AgeT: Age_alg T}:\n         @Indir (pred T) (algNatDed T).\n apply (mkIndir _ _ (box laterM)); intros; simpl in *.\n apply @predicates_hered.now_later.\n apply @predicates_hered.axiomK.\n apply @predicates_hered.later_allp.\n simpl. intros; apply @box_ex.\n  simpl. intros; apply @later_ex; auto.\n apply @predicates_hered.later_imp.\n apply @predicates_hered.loeb; auto.\nDefined.\n\nInstance TrivIndir: Indir Triv := @algIndir nat _ _ _ _ asa_nat.\n\nSection SL2. Import msl.seplog.\n\nClass RecIndir (A: Type) {NA: NatDed A}{IA: Indir A} := mkRecIndir {\n  fash : A -> Triv;\n  unfash : Triv -> A;\n  HORec : forall {X} (f: (X -> A) -> (X -> A)), X -> A;\n  unfash_fash:  forall P: A, unfash (fash P) |-- P;\n  fash_K: forall P Q, fash (P --> Q) |-- fash P --> fash Q;\n  fash_derives: forall P Q, P |-- Q -> fash P |-- fash Q;\n  unfash_derives:  forall P Q,  P |-- Q -> unfash P |-- unfash Q;\n  later_fash:  forall P, later (fash P) = fash (later P);\n  later_unfash:  forall P, later (unfash P) = unfash (later P);\n  fash_andp: forall P Q, fash (P && Q) = fash P && fash Q;\n  unfash_allp:  forall {B} (P: B -> Triv), unfash (allp P) = ALL x:B, unfash (P x);  subp_allp: forall G B (X Y:B -> A),  (forall x:B, G |-- fash (imp (X x) (Y x))) ->  G |-- fash (imp (allp X) (allp Y));\n  subp_exp: forall G B (X Y:B -> A),  (forall x:B, G |-- fash (imp (X x) (Y x))) ->  G |-- fash (imp (exp X) (exp Y));\n  subp_e: forall (P Q : A), TT |-- fash (P --> Q) -> P |-- Q;\n  subp_i1: forall P (Q R: A), unfash P && Q |-- R -> P |-- fash (Q --> R);\n fash_TT: forall G, G |-- fash TT;\n  HOcontractive: forall {X: Type} (f: (X -> A) -> (X -> A)), Prop :=\n         fun {X} f => forall P Q,  (ALL x:X, later (fash (P x <--> Q x))) |-- (ALL x:X, fash (f P x <--> f Q x));\n  HORec_fold_unfold : forall X (f: (X -> A) -> (X -> A)) (H: HOcontractive f), HORec f = f (HORec f)\n}.\n\nDefinition HOnonexpansive {A}{NA: NatDed A}{IA: Indir A}{RA: RecIndir A}\n        {X: Type} (f: (X -> A) -> (X -> A)) :=\n         forall P Q: X -> A,  (ALL x:X, fash (P x <--> Q x)) |-- (ALL x:X, fash (f P x <--> f Q x)).\nEnd SL2.\n\n\nNotation \"'#' e\" := (fash e) (at level 30, right associativity): logic.\nNotation \"'!' e\" := (unfash e) (at level 30, right associativity): logic.\nNotation \"P '>=>' Q\" := (# (P --> Q)) (at level 55, right associativity) : logic.\nNotation \"P '<=>' Q\" := (# (P <--> Q)) (at level 57, no associativity) : logic.\n\nDefinition algRecIndir (T: Type) {agT: ageable T}{JoinT: Join T}{PermT: Perm_alg T}{SepT: Sep_alg T}{AgeT: Age_alg T} :\n         @RecIndir (pred T) (algNatDed T) (algIndir T).\n apply (mkRecIndir _ _ _ subtypes.fash subtypes.unfash HoRec.HORec); intros; simpl.\n repeat intro. do 3 red in H. apply H; auto.\n apply @subtypes.fash_K.\n apply @subtypes.fash_derives; auto.\n intros ? ?. do 3 red in H0. apply H in H0. apply H0.\n apply @subtypes.later_fash; auto.\n apply @subtypes.later_unfash.\n apply @subtypes.fash_and.\n apply pred_ext; repeat intro; do 3 red in H; apply (H b); auto.\n apply @subtypes.subp_allp; auto.\n eapply @subtypes.subp_exp; auto.\n eapply @subtypes.subp_e; eauto.\n eapply @subtypes.subp_i1; eauto.\n repeat intro; hnf; auto.\n intros. apply HoRec.HORec_fold_unfold; auto.\nDefined.\n\nInstance TrivRecIndir: RecIndir Triv := algRecIndir nat.\n\nSection SL3. Import msl.seplog.\n\nLemma fash_triv: forall P: Triv, fash P = P.\nProof.\n intros.\n apply pred_ext; intros ? ?.\n eapply H. unfold level; simpl.  unfold natLevel; auto.\n hnf; intros. eapply pred_nec_hereditary; try eapply H.\n apply nec_nat. auto.\nQed.\n\nClass SepRec  (A: Type) {NA: NatDed A}{SA: SepLog A}{IA: Indir A}{RA: RecIndir A} := mkSepRec {\n  unfash_sepcon_distrib: forall (P: Triv) (Q R: A),\n                 andp (unfash P) (sepcon Q R) = sepcon (andp (unfash P) Q) (andp (unfash P) R)\n}.\n\nEnd SL3.\n\nInstance algSepIndir (T: Type) {agT: ageable T}{JoinT: Join T}{PermT: Perm_alg T}{SepT: Sep_alg T}{AgeT: Age_alg T} :\n         @SepIndir (pred T) (algNatDed T) (algSepLog T) (algIndir T).\n apply mkSepIndir; simpl.\n apply @predicates_sl.later_sepcon; auto.\n apply @predicates_sl.later_wand; auto.\n apply @predicates_sl.later_ewand; auto.\nQed.\n\nInstance algSepRec (T: Type) {agT: ageable T}{JoinT: Join T}{PermT: Perm_alg T}{SepT: Sep_alg T}{AgeT: Age_alg T} :\n         @SepRec (pred T) (algNatDed T) (algSepLog T) (algIndir T)(algRecIndir T).\nconstructor.\n intros; simpl. apply subtypes_sl.unfash_sepcon_distrib.\nQed.\n\nInstance algCorableSepLog (T: Type) {agT: ageable T}{JoinT: Join T}{PermT: Perm_alg T}{SepT: Sep_alg T}{AgeT: Age_alg T} :\n         @CorableSepLog (pred T) (algNatDed T) (algSepLog T).\n  apply mkCorableSepLog with (corable := corable.corable).\n  + apply corable.corable_prop.\n  + apply corable.corable_andp.\n  + apply corable.corable_orp.\n  + apply corable.corable_imp.\n  + intros; apply corable.corable_allp; auto.\n  + intros; apply corable.corable_exp; auto.\n  + apply corable.corable_sepcon.\n  + apply corable.corable_wand.\n  + intros; simpl.\n    apply corable.corable_andp_sepcon1; auto.\nDefined.\n\nInstance algCorableIndir (T: Type) {agT: ageable T}{JoinT: Join T}{PermT: Perm_alg T}{SepT: Sep_alg T}{AgeT: Age_alg T} :\n         @CorableIndir (pred T) (algNatDed T) (algSepLog T) (algCorableSepLog T) (algIndir T).\n  unfold CorableIndir; simpl.\n  apply corable.corable_later.\nDefined.", "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/alg_seplog.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.25493396656562956}}
{"text": "From PetitC Require Import Ids Values TypedTree Memory Output InbuiltFunc InbuiltFuncSemantics.\nImport TypedTree.\n\nFrom Coq Require Import ZArith Lists.List.\nImport ListNotations.\nOpen Scope Z_scope.\n\nFixpoint assoc {X : Type} (id : func_id) (assoc_list : list (func_id * X)) : option X :=\n  match assoc_list with\n  | (id', x)::tail => if (id' =? id)%nat\n                      then Some x\n                      else assoc id tail\n  | []             => None\n  end.\n\nDefinition write_goes_wrong (mem : memory) (ptr : ptr_value) : Prop :=\n  ~exists val st', write mem ptr val st'.\n\nDefinition read_goes_wrong (mem : memory) (ptr : ptr_value) : Prop :=\n  ~exists val, read mem ptr val.\n\nDefinition allocate_var (mem : memory) (var_ptrs : VarIdMap.t ptr_value)\n    (id : var_id) : memory * VarIdMap.t ptr_value :=\n  let (ptr, mem') := allocate_stack mem in\n  (mem', VarIdMap.add id ptr var_ptrs).\n\nInductive allocate_vars : memory -> VarIdMap.t ptr_value -> list var_id ->\n                          memory -> VarIdMap.t ptr_value -> Prop :=\n\n  | AVNil : forall mem var_ptrs,\n      allocate_vars mem var_ptrs [] mem var_ptrs\n      \n  | AVCons : forall mem mem' mem'' var_ptrs var_ptrs' var_ptrs'' id ids_tail,\n        allocate_vars mem var_ptrs ids_tail mem' var_ptrs' ->\n        (mem'', var_ptrs'') = allocate_var mem' var_ptrs' id ->\n      allocate_vars mem var_ptrs (id::ids_tail)mem'' var_ptrs''.\n\nInductive assign_var (var_ptrs : VarIdMap.t ptr_value) :\n      memory -> var_id -> value -> memory -> Prop :=\n  | AssignVar : forall mem id ptr val mem',\n        VarIdMap.find id var_ptrs = Some ptr ->\n        write mem ptr val mem' ->\n      assign_var var_ptrs mem id val mem'.\n\nInductive assign_vars (var_ptrs : VarIdMap.t ptr_value) :\n      memory -> list var_id -> list value -> memory -> Prop :=\n\n  | AssignVarsNil : forall mem,\n      assign_vars var_ptrs mem [] [] mem\n    \n  | AssignVarsCons : forall mem mem' mem'' id val ids vals,\n        assign_vars var_ptrs mem ids vals mem' ->\n        assign_var var_ptrs mem' id val mem'' ->\n      assign_vars var_ptrs mem (id::ids) (val::vals) mem''.\n\nInductive call_var_ptrs_and_mem : VarIdMap.t ptr_value -> memory -> list var_id -> list value ->\n                                  VarIdMap.t ptr_value -> memory -> Prop :=\n  | CVITPAS : forall var_ptrs var_ptrs' mem mem' mem'' var_ids vals,\n        allocate_vars mem var_ptrs var_ids mem' var_ptrs' ->\n        assign_vars var_ptrs' mem' var_ids vals mem'' ->\n      call_var_ptrs_and_mem var_ptrs mem var_ids vals var_ptrs' mem''.\n\nInductive expr_context : (annotated_expr -> annotated_expr) -> Prop :=\n  | CHole :\n      expr_context (fun e => e)\n  | CCast ctx ty ty' ty'' :\n        expr_context ctx ->\n      expr_context (fun e => Cast ty ty' (ctx e) <: ty'')\n  | CLvalue ctx ty :\n        lvalue_context ctx ->\n      expr_context (fun e => LValue (ctx e) <: ty)\n  | CAddressOf ctx ty :\n        lvalue_context ctx ->\n      expr_context (fun e => AddressOf (ctx e) <: ty)\n  | CBinOpLeft binop ctx ty expr :\n        expr_context ctx ->\n      expr_context (fun e => BinOp binop (ctx e) expr <: ty)\n  | CBinOpRight binop ctx ty ty' value :\n        expr_context ctx ->\n      expr_context (fun e => BinOp binop (Const value <: ty) (ctx e) <: ty')\n  | CNot ctx ty :\n        expr_context ctx ->\n      expr_context (fun e => Not (ctx e) <: ty)\n  | CIncrOrDecr incr_or_decr pre_or_post ctx ty :\n        lvalue_context ctx ->\n      expr_context (fun e => IncrOrDecr ty incr_or_decr pre_or_post (ctx e) <: ty)\n  | CAssignLeft ctx expr ty :\n        lvalue_context ctx ->\n      expr_context (fun e => Assign (ctx e) expr <: ty)\n  | CAssignRight ctx ptr ty ty' complete_ty :\n        expr_context ctx ->\n      expr_context (fun e =>\n        Assign (Dereference (Const ptr <: ty) <l: complete_ty)\n               (ctx e)\n        <: ty'\n      )\n  | CCall ctx func_id ty :\n        list_expr_context ctx ->\n      expr_context (fun e => Call func_id (ctx e) <: ty)\n  | CCallInbuilt ctx inbuilt_func ty :\n        list_expr_context ctx ->\n      expr_context (fun e => CallInbuilt inbuilt_func (ctx e) <: ty)\n      \nwith lvalue_context : (annotated_expr -> annotated_lvalue) -> Prop :=\n  | CDereference ctx complete_ty :\n      expr_context ctx ->\n    lvalue_context (fun e => Dereference (ctx e) <l: complete_ty)\n    \nwith list_expr_context : (annotated_expr -> list_annotated_expr) -> Prop :=\n  | CHead ctx tail :\n        expr_context ctx ->\n      list_expr_context (fun e => LAECons (ctx e) tail)\n  | CTail ctx value ty :\n        list_expr_context ctx ->\n      list_expr_context (fun e => LAECons (Const value <: ty) (ctx e)).\n\nScheme expr_context_mutual_ind := Minimality for expr_context Sort Prop\nwith lvalue_context_mutual_ind := Minimality for lvalue_context Sort Prop\nwith list_expr_context_mutual_ind := Minimality for list_expr_context Sort Prop.\n\nDefinition bool_to_value (b : bool) : value :=\n  if b then IntValue one_int_value else IntValue zero_int_value.\n\nInductive cast_reduction : rich_type -> value -> rich_type -> value  -> Prop :=\n  | CRSame value rich_ty ty :\n        Some ty = of_rich rich_ty ->\n        can_have_type value ty ->\n      cast_reduction rich_ty     value\n                     rich_ty     value\n  | CRIntToBool int_value :\n      cast_reduction RInt       (IntValue int_value)\n                     RBool      (bool_to_value (negb (Z.eqb (int_value_to_Z int_value) 0)))\n  | CRBoolToInt int_value :\n      cast_reduction RBool      (IntValue int_value)\n                     RInt       (IntValue int_value)\n  | CRHeapPtrToBool ty ptr :\n      cast_reduction (RPtr ty)  (PtrValue ptr)\n                     RBool      (bool_to_value (negb (ptr_value_beq ptr NullPtr)))\n  | CRPtrToPtr ptr ty ty' :\n      cast_reduction (RPtr ty)  (PtrValue ptr)\n                     (RPtr ty') (PtrValue ptr).\n\nDefinition cast_reduction_goes_wrong\n    (ty_from : rich_type) (val_from : value) (ty_to : rich_type) : Prop :=\n  ~exists val_to, cast_reduction ty_from val_from ty_to val_to.\n\nInductive int_arith_binop_reduction : int_arith_binop -> Z -> Z -> Z -> Prop :=\n  | IABRPlusIntInt n m :\n      int_arith_binop_reduction PlusIntInt n m (n + m)\n  | IABRMinusIntInt n m :\n      int_arith_binop_reduction MinusIntInt n m (n - m)\n  | IABRTimes n m :\n      int_arith_binop_reduction Times n m (n * m)\n  | IABRDiv n m :\n      m <> 0%Z -> (* division and modulo by zero is undefined behavior *)\n      int_arith_binop_reduction Div n m (Z.abs n / Z.abs m * Z.sgn n * Z.sgn n)\n  | IABRMod n m :\n      m <> 0%Z ->\n      int_arith_binop_reduction Mod n m ((Z.abs n mod Z.abs m) * Z.sgn n * Z.sgn m).\n\nInductive comparison_reduction : comparison -> Z -> Z -> bool -> Prop :=\n  | CRBEq n m : comparison_reduction Eq n m (n =? m)%Z\n  | CRBLt n m : comparison_reduction Lt n m (n <? m)%Z.\n\nInductive binop_reduction : binop -> value -> value -> value -> Prop :=\n  | BRIntArithBinop (op : int_arith_binop) (lhs rhs result : int_value) :\n        int_arith_binop_reduction op (int_value_to_Z lhs)\n                                     (int_value_to_Z rhs)\n                                     (int_value_to_Z result) ->\n      binop_reduction (IntArithBinop op) (IntValue lhs) (IntValue rhs) (IntValue result)\n\n  | BRComparisonInt (comp : comparison) (lhs rhs : int_value) (result : bool) :\n        comparison_reduction comp (int_value_to_Z lhs) (int_value_to_Z rhs) result ->\n      binop_reduction (Comparison comp) (IntValue lhs) (IntValue rhs) (bool_to_value result)\n\n  | BRComparisonPtr (comp : comparison) (lhs rhs : ptr_value) (lhs_offset rhs_offset : offset)\n                    (result : bool) :\n        has_offset lhs lhs_offset ->\n        has_offset rhs rhs_offset ->\n        same_block lhs rhs ->\n        comparison_reduction comp lhs_offset rhs_offset result ->\n      binop_reduction (Comparison comp) (PtrValue lhs) (PtrValue rhs) (bool_to_value result)\n\n  | BRPlusPtrInt (lhs : ptr_value) (rhs : int_value) (result : ptr_value)\n                 (lhs_offset result_offset : offset) :\n        has_offset lhs lhs_offset ->\n        has_offset result result_offset ->\n        same_block lhs result ->\n        lhs_offset + Z.of_nat word_size * int_value_to_Z rhs = result_offset ->\n      binop_reduction PlusPtrInt (PtrValue lhs) (IntValue rhs) (PtrValue result)\n\n  | BRPlusIntPtr (lhs : int_value) (rhs result : ptr_value) (rhs_offset result_offset : offset) :\n        has_offset rhs rhs_offset ->\n        has_offset result result_offset ->\n        same_block rhs result ->\n        Z.of_nat word_size * int_value_to_Z lhs + rhs_offset = result_offset ->\n      binop_reduction PlusPtrInt (IntValue lhs) (PtrValue rhs) (PtrValue result)\n\n  | BRMinusPtrInt (lhs : ptr_value) (rhs : int_value) (result : ptr_value)\n                  (lhs_offset result_offset : offset) :\n        has_offset lhs lhs_offset ->\n        has_offset result result_offset ->\n        same_block lhs result ->\n        lhs_offset * Z.of_nat word_size * int_value_to_Z rhs = result_offset ->\n      binop_reduction MinusPtrInt (PtrValue lhs) (IntValue rhs) (PtrValue result)\n\n  | BRMinusPtrPtr (lhs rhs : ptr_value) (result : int_value) (lhs_offset rhs_offset : offset) :\n        has_offset lhs lhs_offset ->\n        has_offset rhs rhs_offset ->\n        lhs_offset - rhs_offset = Z.of_nat word_size * int_value_to_Z result ->\n      binop_reduction MinusPtrPtr (PtrValue lhs) (PtrValue rhs) (IntValue result).\n        \nDefinition binop_reduction_goes_wrong (op : binop) (lhs rhs : value) : Prop :=\n  ~exists result, binop_reduction op lhs rhs result.\n\nInductive short_circuit_reduction_first : short_circuit_op -> bool -> bool -> Prop :=\n  | SCRFFalseAnd : short_circuit_reduction_first And false false\n  | SCRFTrueOr   : short_circuit_reduction_first Or  true  true.\n\nInductive short_circuit_reduction_second : short_circuit_op -> bool -> bool -> bool -> Prop :=\n  | SCRSTrueAnd (b : bool) : short_circuit_reduction_second And true  b b\n  | SCRSFalseOr (b : bool) : short_circuit_reduction_second Or  false b b.\n\nDefinition to_plus_or_minus_one (iod : incr_or_decr) : Z :=\n  match iod with\n  | Incr => 1\n  | Decr => -1\n  end.\n\nInductive incr_or_decr_reduction : incr_or_decr -> rich_type -> value -> value -> Prop :=\n  | IRInt (incr_or_decr : incr_or_decr) (before after : int_value) :\n        (int_value_to_Z after = int_value_to_Z before + to_plus_or_minus_one incr_or_decr)%Z ->\n      incr_or_decr_reduction incr_or_decr RInt\n        (IntValue before)\n        (IntValue after)\n\n  | IRIncrPtr (incr_or_decr : incr_or_decr) (block_id : block_id) (offset : offset) (ty : rich_type) :\n      incr_or_decr_reduction incr_or_decr (RPtr ty)\n        (PtrValue (HeapPtr block_id offset))\n        (PtrValue (HeapPtr block_id\n                           (offset + Z.of_nat word_size * to_plus_or_minus_one incr_or_decr) % Z))\n\n  | IRIncrBool : forall (b : bool),\n      incr_or_decr_reduction Incr RBool\n        (bool_to_value b)\n        (bool_to_value true)\n\n  | IRDecrBool : forall (b : bool),\n      incr_or_decr_reduction Decr (RBool)\n        (bool_to_value b)\n        (bool_to_value (negb b)).\n\nSection ExprHeadReduction.\n\nVariable (var_ptrs : VarIdMap.t ptr_value).\n\nInductive expr_head_reduction : (memory * output) * annotated_expr ->\n                                (memory * output) * annotated_expr -> Prop :=\n                                \n  | HRCast (state : memory * output) (val val' : value) (ty ty' : rich_type) :\n        cast_reduction ty val ty' val' ->\n      expr_head_reduction\n        (state, Cast ty ty' (Const val <: ty) <: ty')\n        (state, Const val' <: ty')\n\n  | HRAddressOf (state : memory * output) (ptr : ptr_value) (ty : rich_type) :\n      expr_head_reduction\n        (state, AddressOf (Dereference (Const (PtrValue ptr) <: RPtr ty) <l: ty) <: RPtr ty)\n        (state, Const (PtrValue ptr) <: RPtr ty)\n\n  | HRBinOp (state : memory * output) (op : binop) (lhs rhs result : value)\n            (lhs_ty rhs_ty result_ty : rich_type) :\n        binop_reduction op lhs rhs result ->\n      expr_head_reduction\n        (state, BinOp op (Const lhs <: lhs_ty) (Const rhs <: rhs_ty) <: result_ty)\n        (state, Const result <: result_ty)\n\n  | HRShortCircuitFirst (state : memory * output) (op : short_circuit_op) (lhs : bool)\n                        (rhs : annotated_expr) (result : bool) :\n        short_circuit_reduction_first op lhs result ->\n      expr_head_reduction\n        (state, ShortCircuit op (Const (bool_to_value lhs) <: RBool) rhs <: RBool)\n        (state, Const (bool_to_value result) <: RBool)\n\n  | HRShortCircuitSecond (state : memory * output) (op : short_circuit_op) (lhs rhs result : bool) :\n        short_circuit_reduction_second op lhs rhs result ->\n      expr_head_reduction\n        (state, ShortCircuit op (Const (bool_to_value lhs) <: RBool)\n                                       (Const (bool_to_value rhs) <: RBool) <: RBool)\n        (state, Const (bool_to_value result) <: RBool)\n\n  | HRNot state (b : bool) :\n      expr_head_reduction\n        (state, Not (Const (bool_to_value b) <: RBool) <: RBool)\n        (state, Const (bool_to_value (negb b)) <: RBool)\n\n  | HRIncrOrDecr (mem mem' : memory) (out : output) (iod : incr_or_decr) (pop : pre_or_post)\n                 (ptr : ptr_value) (before after : value) (ty : rich_type) :\n        incr_or_decr_reduction iod ty before after ->\n        read mem ptr before ->\n        write mem ptr after mem' ->\n      expr_head_reduction\n        ((mem,  out), (IncrOrDecr ty iod pop\n                                  (Dereference (Const (PtrValue ptr) <: RPtr ty) <l: ty)) <: ty)\n        ((mem', out), Const (match pop with | Pre => after | Post => before end) <: ty)\n\n  | HRAssign (mem mem' : memory) (out : output) (ptr : ptr_value) (val : value) (ty : rich_type) :\n        write mem ptr val mem' ->\n      expr_head_reduction\n        ((mem,  out), (Assign (Dereference (Const (PtrValue ptr) <: RPtr ty) <l: ty)\n                         (Const val <: ty) <: ty))\n        ((mem', out), Const val <: ty)\n\n  (* calls are not reduced here, they are reduced by continuation_step *)\n\n  | HRInbuiltFunc (func : inbuilt_func) (mem mem' : memory) (out out' : output)\n                  (args : list value) (arg_tys : list rich_type)\n                  (returned : option value) (return_ty : rich_type) :\n        inbuilt_func_step func args returned mem out mem' out' ->\n        length args = length arg_tys ->\n      expr_head_reduction\n        ((mem,  out),  CallInbuilt func\n                          (list_to_list_annotated_expr\n                            (map (fun '(val, ty) => Const val <: ty)\n                                 (combine args arg_tys)))\n                          <: return_ty)\n        ((mem', out'), (match returned with\n                           | Some val => Const val\n                           | None     => Unit end)\n                          <: return_ty)\n\n  | HRVar (state : memory * output) (var_id : var_id) (ptr : ptr_value) (ty : rich_type) :\n        VarIdMap.find var_id var_ptrs = Some ptr ->\n      expr_head_reduction\n        (state, LValue (Var var_id <l: ty) <: ty)\n        (state, LValue (Dereference (Const (PtrValue ptr) <: RPtr ty) <l: ty) <: ty).\n\nEnd ExprHeadReduction.\n\n(* Inductive expr_head_reduction_goes_wrong : memory * output * annotated_expr -> Prop :=\n  | HRWBinop : forall state op lhs_val lhs_ty rhs_val rhs_ty result_ty,\n        binop_reduction_goes_wrong op lhs_ty lhs_val rhs_ty rhs_val ->\n      expr_head_reduction_goes_wrong\n        (state, BinOp op (Const lhs_val <: lhs_ty) (Const rhs_val <: rhs_ty) <: result_ty)\n        \n  | HRWAssign : forall state value value ty,\n        write_mem_goes_wrong state value ->\n      expr_head_reduction_goes_wrong\n        (state,  (Assign (Dereference (Const (PtrValue value) <: RPtr ty) <l: ty)\n                         (Const value <: ty) <: ty)). *)\n\n\nInductive continuation_after_cmd : Type :=\n  | KStop\n      (* do the command, then stop *)\n  | KSeq (c : cmd) (k : continuation_after_cmd)\n      (* do the command, then do [i], then do [k] *)\n  | KWhileAfterCmd (e : annotated_expr) (c : cmd) (k : continuation_after_cmd)\n      (* do the command as if in the body of the while, then do [while (e) { c }],\n         then do [k] *)\n  | KCall (ctx : annotated_expr -> annotated_expr)\n          (caller_var_ptrs : VarIdMap.t ptr_value)\n          (k : continuation_after_expr)\n      (* reduce the command until its [return const],\n         then do [ContinuedExpr (ctx const) k] *)\n  \nwith continuation_after_expr : Type :=\n  | KExpr (k : continuation_after_cmd)\n      (* evaluate the expression, discard its result, then do [k] *)\n  | KIf (c_then c_else : cmd) (k : continuation_after_cmd)\n      (* evaluate the expression,\n         do [c_then] if it evaluates to true or [c_else] if it evaluates to false,\n         then do [k] *)\n  | KWhileAfterExpr (e : annotated_expr) (c : cmd) (k : continuation_after_cmd)\n      (* evaluate the expression,\n         do [while (e) { c }] without evaluating the conditing for the first time\n                              using the result of the expression instead,\n         then do [k] *).\n\nInductive continued : Type :=\n  | ContinuedExpr : annotated_expr -> continuation_after_expr -> continued\n  | ContinuedCmd : cmd -> continuation_after_cmd -> continued.\n\nSection ContinuedStep.\n\nVariable (funcs : list (func_id * func)).\n\nInductive continued_step : VarIdMap.t ptr_value * (memory * output) * continued ->\n                           VarIdMap.t ptr_value * (memory * output) * continued -> Prop :=\n  \n  | CSSkipSeq var_ptrs state cmd cont :\n      continued_step\n        (var_ptrs, state,  ContinuedCmd Skip (KSeq cmd cont))\n        (var_ptrs, state,  ContinuedCmd cmd cont)\n      \n  | CSSkipWhileAfterCmd var_ptrs state expr cmd cont :\n      continued_step\n        (var_ptrs, state,  ContinuedCmd Skip (KWhileAfterCmd expr cmd cont))\n        (var_ptrs, state,  ContinuedCmd Skip (KSeq (While expr cmd) cont))\n    \n  | CSSeq var_ptrs state cmd1 cmd2 cont :\n      continued_step\n        (var_ptrs, state,  ContinuedCmd (Seq cmd1 cmd2) cont)\n        (var_ptrs, state,  ContinuedCmd cmd1 (KSeq cmd2 cont))\n        \n  | CSExpr var_ptrs state expr cont :\n      continued_step\n        (var_ptrs, state,  ContinuedCmd (Expr expr) cont)\n        (var_ptrs, state,  ContinuedExpr expr (KExpr cont))\n        \n  | CSIf var_ptrs state expr cmd_then cmd_else cont :\n      continued_step\n        (var_ptrs, state,  ContinuedCmd (If expr cmd_then cmd_else) cont)\n        (var_ptrs, state,  ContinuedExpr expr (KIf cmd_then cmd_else cont))\n\n  | CSWhile var_ptrs state expr cmd cont :\n      continued_step\n        (var_ptrs, state,  ContinuedCmd (While expr cmd) cont)\n        (var_ptrs, state,  ContinuedExpr expr (KWhileAfterExpr expr cmd cont))\n        \n  | CSBreakSeq var_ptrs state cmd cont :\n      continued_step\n        (var_ptrs, state,  ContinuedCmd Break (KSeq cmd cont))\n        (var_ptrs, state,  ContinuedCmd Break cont)\n\n  | CSBreakWhile var_ptrs state expr cmd cont :\n      continued_step\n        (var_ptrs, state,  ContinuedCmd Break (KWhileAfterCmd expr cmd cont))\n        (var_ptrs, state,  ContinuedCmd Skip cont)\n        \n  | CSContinueSeq var_ptrs state cmd cont :\n      continued_step\n        (var_ptrs, state,  ContinuedCmd Continue (KSeq cmd cont))\n        (var_ptrs, state,  ContinuedCmd Continue cont)\n        \n  | CSContinueWhile var_ptrs state expr cmd cont :\n      continued_step\n        (var_ptrs, state,  ContinuedCmd Continue (KWhileAfterCmd expr cmd cont))\n        (var_ptrs, state,  ContinuedCmd (While expr cmd) cont)\n        \n      (* we capitalize the E and R at the end of calle and caller so they are harder to confuse *)\n  | CSReturn var_ptrs_calleE var_ptrs_calleR state val ty ctx cont :\n      continued_step\n        (var_ptrs_calleE, state, ContinuedCmd (Return (Const val <: ty))\n                                                     (KCall ctx var_ptrs_calleR cont))\n        (var_ptrs_calleR, state, ContinuedExpr (ctx (Const val <: ty)) cont)\n        \n  | CSExprConst var_ptrs state val ty cont :\n      continued_step\n        (var_ptrs, state,  ContinuedExpr (Const val <: ty) (KExpr cont))\n        (var_ptrs, state,  ContinuedCmd Skip cont)\n\n  | CSExprIf var_ptrs state bool cmd_then cmd_else cont :\n      continued_step\n        (var_ptrs, state,  ContinuedExpr (Const (bool_to_value bool) <: RBool)\n                                              (KIf cmd_then cmd_else cont))\n        (var_ptrs, state,  ContinuedCmd (if bool then cmd_then else cmd_else) cont)\n  \n  | CSExprWhile var_ptrs state bool expr cmd cont :\n      continued_step\n        (var_ptrs, state,  ContinuedExpr  (Const (bool_to_value bool) <: RBool)\n                                               (KWhileAfterExpr expr cmd cont))\n        (var_ptrs, state,  if bool\n                                then ContinuedCmd cmd (KWhileAfterCmd expr cmd cont)\n                                else ContinuedCmd Skip cont)\n\n  | CSExprHeadReduction var_ptrs state state' ctx expr expr' cont :\n        expr_context ctx ->\n        expr_head_reduction var_ptrs (state, expr) (state', expr') ->\n      continued_step\n        (var_ptrs, state,  ContinuedExpr (ctx expr) cont)\n        (var_ptrs, state', ContinuedExpr (ctx expr') cont)\n\n      (* we capitalize the E and R at the end of calle and caller so they are harder to confuse *)\n  | CSExprCall var_ptrs_calleE var_ptrs_calleR mem mem' out func func_id arg_vals ctx cont :\n        assoc func_id funcs = Some func ->\n        expr_context ctx ->\n        let sig := f_signature func in\n        length arg_vals = length (fs_arg_rich_types sig) ->\n        let arg_exprs := list_to_list_annotated_expr\n          (map (fun '(val, ty) => Const val <: ty)\n               (combine arg_vals (fs_arg_rich_types sig))) in\n        let call_expr := (Call func_id arg_exprs <: fs_rich_return_type sig) in\n        call_var_ptrs_and_mem var_ptrs_calleR mem (f_arg_var_ids func) arg_vals\n                              var_ptrs_calleE mem' ->\n      continued_step\n        (var_ptrs_calleR, (mem,  out),  ContinuedExpr (ctx call_expr) cont)\n        (var_ptrs_calleE, (mem', out), ContinuedCmd (f_body func)\n                                                      (KCall ctx var_ptrs_calleR cont)).\n\nEnd ContinuedStep.\n\n(* Inductive continued_step_goes_wrong : IdMap.t value * state * continued -> Prop :=\n  | CSWExprHeadReduction : forall var_ptrs state ctx expr cont,\n        expr_context ctx ->\n        expr_head_reduction_goes_wrong (state, expr) ->\n      continued_step_goes_wrong\n        (var_ptrs, state,  ContinuedExpr (ctx expr) cont). *)\n", "meta": {"author": "astOwOlfo", "repo": "PetitC", "sha": "449bc594f698eaf476faac0943e65fb34e36a63f", "save_path": "github-repos/coq/astOwOlfo-PetitC", "path": "github-repos/coq/astOwOlfo-PetitC/PetitC-449bc594f698eaf476faac0943e65fb34e36a63f/Semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.25493396656562956}}
{"text": "Require Import Coq.omega.Omega.\nRequire Import Crypto.Util.FixCoqMistakes.\nRequire Import Crypto.Compilers.Syntax.\nRequire Import Crypto.Compilers.Wf.\nRequire Import Crypto.Compilers.Named.Context.\nRequire Import Crypto.Compilers.Named.ContextDefinitions.\nRequire Import Crypto.Compilers.Named.NameUtil.\nRequire Import Crypto.Compilers.Named.NameUtilProperties.\nRequire Import Crypto.Compilers.Named.ContextProperties.\nRequire Import Crypto.Compilers.Named.ContextProperties.Tactics.\nRequire Import Crypto.Util.Decidable.\nRequire Import Crypto.Util.ListUtil.\nRequire Import Crypto.Util.Prod.\nRequire Import Crypto.Util.Tactics.SplitInContext.\nRequire Import Crypto.Util.Tactics.DestructHead.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nRequire Import Crypto.Util.Tactics.SpecializeBy.\n\nSection with_context.\n  Context {base_type_code Name var} (Context : @Context base_type_code Name var)\n          (base_type_code_dec : DecidableRel (@eq base_type_code))\n          (Name_dec : DecidableRel (@eq Name))\n          (ContextOk : ContextOk Context).\n\n  Local Notation find_Name := (@find_Name base_type_code Name Name_dec).\n  Local Notation find_Name_and_val := (@find_Name_and_val base_type_code Name base_type_code_dec Name_dec).\n\n  Hint Rewrite (@find_Name_and_val_default_to_None _ base_type_code_dec _ Name_dec) using congruence : ctx_db.\n  Hint Rewrite (@find_Name_and_val_different _ base_type_code_dec _ Name_dec) using assumption : ctx_db.\n  Hint Rewrite (@find_Name_and_val_wrong_type _ base_type_code_dec _ Name_dec) using congruence : ctx_db.\n  Hint Rewrite (@snd_split_onames_skipn base_type_code Name) : ctx_db.\n\n  Local Ltac misc_oname_t_step :=\n    match goal with\n    | [ H : oname_list_unique (List.skipn _ _) -> _ |- _ ]\n      => specialize (fun pf => H (@oname_list_unique_skipn _ _ _ pf))\n    | [ H : ((_, _) = (_, _))%core -> _ |- _ ]\n      => specialize (fun a b => H (f_equal2 (@pair _ _) a b))\n    | [ H : ?x = (_,_)%core -> _ |- _ ]\n      => rewrite (surjective_pairing x) in H;\n           specialize (fun a b => H (f_equal2 (@pair _ _) a b))\n    end.\n\n  Lemma split_onames_find_Name\n        {n T N ls ls'}\n        (H : split_onames _ ls = (Some N, ls')%core)\n    : (exists t, @find_Name n T N = Some t)\n      <-> List.In (Some n) (List.firstn (CountLets.count_pairs T) ls).\n  Proof using Type.\n    revert dependent ls; intro ls; revert ls ls'; induction T; intros ls ls' H;\n      [ | | specialize (IHT1 (fst N) ls (snd (split_onames T1 ls)));\n            specialize (IHT2 (snd N) (snd (split_onames T1 ls)) (snd (split_onames (T1 * T2) ls))) ];\n      repeat first [ misc_oname_t_step\n                   | t_step\n                   | progress split_iff\n                   | progress specialize_by (eexists; eauto)\n                   | solve [ eauto using In_skipn, In_firstn ]\n                   | match goal with\n                     | [ H : List.In ?x (List.firstn ?n ?ls) |- List.In ?x (List.firstn (?n + ?m) ?ls) ]\n                       => apply (In_firstn n); rewrite firstn_firstn by omega\n                     | [ H : _ |- _ ] => first [ rewrite firstn_skipn_add in H\n                                               | rewrite firstn_firstn in H by omega ]\n                     | [ H : List.In ?x' (List.firstn (?n + ?m) ?ls) |- List.In ?x' (List.firstn ?m (List.skipn ?n ?ls)) ]\n                       => apply (In_firstn_skipn_split n) in H\n                     end ].\n  Qed.\n\n  Lemma split_onames_find_Name_Some_unique_iff\n        {n T N ls ls'}\n        (Hls : oname_list_unique ls)\n        (H : split_onames _ ls = (Some N, ls')%core)\n    : (exists t, @find_Name n T N = Some t)\n      <-> List.In (Some n) ls /\\ ~List.In (Some n) ls'.\n  Proof using Type.\n    rewrite (split_onames_find_Name (ls':=ls') (ls:=ls)) by assumption.\n    rewrite (surjective_pairing (split_onames _ _)) in H.\n    rewrite fst_split_onames_firstn, snd_split_onames_skipn in H.\n    inversion_prod; subst.\n    split; [ split | intros [? ?] ]; eauto using In_firstn, oname_list_unique_specialize.\n    match goal with\n    | [ H : List.In (Some _) ?ls |- _ ]\n      => is_var ls;\n           eapply In_firstn_skipn_split in H; destruct_head' or; eauto; exfalso; eauto\n    end.\n  Qed.\n\n  Lemma split_onames_find_Name_Some_unique\n        {t n T N ls ls'}\n        (Hls : oname_list_unique ls)\n        (H : split_onames _ ls = (Some N, ls')%core)\n        (Hfind : @find_Name n T N = Some t)\n    : List.In (Some n) ls /\\ ~List.In (Some n) ls'.\n  Proof using Type.\n    eapply split_onames_find_Name_Some_unique_iff; eauto.\n  Qed.\n\n  Lemma flatten_binding_list_find_Name_and_val_unique\n        {var' t n T N V v ls ls'}\n        (Hls : oname_list_unique ls)\n        (H : split_onames _ ls = (Some N, ls')%core)\n    : @find_Name_and_val var' t n T N V None = Some v\n      <-> List.In (existT (fun t => (Name * var' t)%type) t (n, v)) (Wf.flatten_binding_list N V).\n  Proof using Type.\n    revert dependent ls; intro ls; revert ls ls'; induction T; intros ls ls' Hls H;\n      [ | | specialize (IHT1 (fst N) (fst V) ls (snd (split_onames T1 ls)));\n            specialize (IHT2 (snd N) (snd V) (snd (split_onames T1 ls)) (snd (split_onames (T1 * T2) ls))) ];\n      repeat first [ find_Name_and_val_default_to_None_step\n                   | progress simpl in *\n                   | rewrite List.in_app_iff\n                   | misc_oname_t_step\n                   | t_step\n                   | progress split_iff\n                   | lazymatch goal with\n                     | [ H : find_Name ?n ?x = Some ?t, H' : find_Name_and_val ?t' ?n ?X ?V None = Some ?v |- _ ]\n                       => apply find_Name_and_val_find_Name_Some in H'\n                     | [ H : find_Name ?n ?x = Some ?t, H' : find_Name ?n ?x' = Some ?t' |- _ ]\n                       => let apply_in_tac H :=\n                              (eapply split_onames_find_Name_Some_unique in H;\n                               [ | | apply path_prod_uncurried; split; [ eassumption | simpl; reflexivity ] ];\n                               [ | solve [ eauto using oname_list_unique_firstn, oname_list_unique_skipn ] ]) in\n                          first [ constr_eq x x'; fail 1\n                                | apply_in_tac H; apply_in_tac H' ]\n                     end ].\n  Qed.\n\n  Lemma fst_split_mnames__flatten_binding_list__find_Name\n        (MName : Type) (force : MName -> option Name)\n        {var' t n T N V v} {ls : list MName}\n        (Hs : fst (split_mnames force T ls) = Some N)\n        (HN : List.In (existT _ t (n, v)%core) (Wf.flatten_binding_list (var2:=var') N V))\n    : find_Name n N = Some t.\n  Proof.\n    revert dependent ls; induction T;\n      [ | | specialize (IHT1 (fst N) (fst V));\n            specialize (IHT2 (snd N) (snd V)) ];\n      repeat first [ misc_oname_t_step\n                   | t_step\n                   | match goal with\n                     | [ H : _ |- _ ] => first [ rewrite snd_split_mnames_skipn in H\n                                               | rewrite List.in_app_iff in H ]\n                     | [ H : context[fst (split_mnames _ _ ?ls)] |- _ ]\n                       => is_var ls; rewrite (@fst_split_mnames_firstn _ _ _ _ _ ls) in H\n                     end ].\n  Abort.\n\n  Lemma fst_split_mnames__find_Name__flatten_binding_list\n        (MName : Type) (force : MName -> option Name)\n        {var' t n T N V v default} {ls : list MName}\n        (Hs : fst (split_mnames force T ls) = Some N)\n        (Hfind : find_Name n N = Some t)\n        (HN : List.In (existT _ t (n, v)%core) (Wf.flatten_binding_list N V))\n    : @find_Name_and_val var' t n T N V default = Some v.\n  Proof.\n    revert default; revert dependent ls; induction T;\n      [ | | specialize (IHT1 (fst N) (fst V));\n            specialize (IHT2 (snd N) (snd V)) ];\n      repeat first [ find_Name_and_val_default_to_None_step\n                   | rewrite List.in_app_iff in *\n                   | t_step ].\n  Abort.\nEnd with_context.\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/ContextProperties/NameUtil.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.25493396656562956}}
{"text": "Require Import IOA.\nRequire Import Network.\nRequire Import Simulation.\nRequire Import CounterSpec.\nRequire Import CounterRegister.\nRequire Import Automation.\nRequire Import Misc.\nRequire Import ListOps.\n\nRequire Import List.\nImport ListNotations.\n\nModule CounterNetworked.\n\n  Import CounterSpec.Api.\n  Import CounterRegister.CounterRegister.\n\n  (* counter built on top of register, but connected by\n     network. basically a copy of CounterRegister, but uses Network *)\n\n  Inductive Address := CounterAddr | RegisterAddr.\n\n  Lemma Address_eq_dec : forall (a a' : Address),\n      {a = a'} + {a <> a'}.\n  Proof.\n    decide equality.\n  Defined.\n\n  Definition Message := Register_API.\n\n  Lemma Message_eq_dec : forall (m m' : Message),\n      {m = m'} + {m <> m'}.\n  Proof.\n    repeat (decide equality).\n  Defined.\n\n  Definition CRNetwork : AutomatonDef (Network_API Address Message) :=\n    Network _ _ Address_eq_dec Message_eq_dec.\n\n  Definition Register_API_N : Type := Network_API Address Message.\n\n  Definition CRNetwork_actions : Type := Network_actions Address Message.\n\n  Definition Register_transition (st : Register_state) (act : Register_API_N) (st' : Register_state) : Prop :=\n    match act with\n    | Recv CounterAddr (Reg_Set n) RegisterAddr => (fst st = Reg_Ready /\\ st' = (Reg_Setting, n)) \\/\n                                                   (fst st <> Reg_Ready /\\ st' = st)\n    | Send RegisterAddr Reg_Set_Done CounterAddr => fst st = Reg_Setting /\\ st' = (Reg_Ready, snd st)\n    | Recv CounterAddr Reg_Get_Request RegisterAddr => (fst st = Reg_Ready /\\ st' = (Reg_Getting, snd st)) \\/\n                                                       (fst st <> Reg_Ready /\\ st' = st)\n    | Send RegisterAddr (Reg_Get_Response n) CounterAddr => st = (Reg_Getting, n) /\\ st' = (Reg_Ready, n)\n    | Send _ _ _ => False\n    | Recv _ _ _ => st' = st (* input-enabled *)\n    end.\n\n  Definition Register : AutomatonDef Register_API_N :=\n    mkAutomatonDef\n      _\n      Register_state\n      EmptySet\n      Register_init\n      (liftExternal Register_transition).\n\n  Goal in_traces Register\n       [\n         Recv CounterAddr Reg_Get_Request RegisterAddr;\n           Send RegisterAddr (Reg_Get_Response 0) CounterAddr;\n           Recv CounterAddr (Reg_Set 3) RegisterAddr;\n           Send RegisterAddr Reg_Set_Done CounterAddr\n       ].\n  Proof.\n    eexists ((_, _)); eexists ((_, _)); split; [hnf; eauto |].\n    repeat (eapply Step_External; simpl; eauto).\n  Qed.\n\n  Definition Counter_action_type : Type := Counter_API + Register_API_N.\n\n  Definition Counter_transition (st : Counter_state) (act : Counter_action_type) (st' : Counter_state) : Prop :=\n    match act with\n    | inl Reset => (fst st = DReady /\\ st' = (DResetting1, snd st)) \\/\n                   (fst st <> DReady /\\ st' = st)\n    | inr (Send CounterAddr (Reg_Set n) RegisterAddr) =>\n      match (fst st) with\n      | DResetting1 => n = 0 /\\ st' = (DResetting2, snd st)\n      | DIncrementing3 => n = snd st /\\ st' = (DIncrementing4, snd st)\n      | _ => False\n      end\n    | inr (Recv RegisterAddr Reg_Set_Done CounterAddr) =>\n      match (fst st) with\n      | DResetting2 => st' = (DResetting3, snd st)\n      | DIncrementing4 => st' = (DIncrementing5, snd st)\n      | _ => st' = st\n      end\n    | inl Reset_Done => fst st = DResetting3 /\\ st' = (DReady, snd st)\n    | inl Increment => (fst st = DReady /\\ st' = (DIncrementing1, snd st)) \\/\n                       (fst st <> DReady /\\ st' = st)\n    | inr (Send CounterAddr Reg_Get_Request RegisterAddr) =>\n      match (fst st) with\n      | DIncrementing1 => st' = (DIncrementing2, snd st)\n      | DReading1 => st' = (DReading2, snd st)\n      | _ => False\n      end\n    | inr (Recv RegisterAddr (Reg_Get_Response n) CounterAddr) =>\n      match (fst st) with\n      | DIncrementing2 => st' = (DIncrementing3, S n)\n      | DReading2 => st' = (DReading3, n)\n      | _ => st' = st\n      end\n    | inl Increment_Done => fst st = DIncrementing5 /\\ st' = (DReady, snd st)\n    | inl Read_Request => (fst st = DReady /\\ st' = (DReading1, snd st)) \\/\n                          (fst st <> DReady /\\ st' = st)\n    | inl (Read_Response n) => st = (DReading3, n) /\\ st' = (DReady, n)\n    | inr (Recv _ _ _) => st' = st\n    | inr (Send _ _ _) => False\n    end.\n\n  Definition Counter : AutomatonDef _ :=\n    mkAutomatonDef\n      _\n      Counter_state\n      EmptySet\n      Counter_init\n      (liftExternal Counter_transition).\n\n  Definition Counter_Register : AutomatonDef (Counter_API + Register_API_N) :=\n    compose\n      Counter\n      Register\n      _\n      (fun act => match act with\n                  | inl act_ctr => Some act\n                  | inr (Recv _ _ CounterAddr) => Some act\n                  | inr (Send CounterAddr _ _) => Some act\n                  | inr _ => None\n                  end)\n      (fun act => match act with\n                  | inr act_net => match act_net with\n                                   | Recv _ _ RegisterAddr => Some act_net\n                                   | Send RegisterAddr _ _ => Some act_net\n                                   | _ => None\n                                   end\n                  | _ => None\n                  end).\n\n  Definition Counter_Register_Networked : AutomatonDef (Counter_API + Register_API_N) :=\n    compose\n      Counter_Register\n      CRNetwork\n      (Counter_API + Network_API Address Message)\n      (fun act => Some act)\n      (fun act => match act with\n                  | inr act_net => Some act_net\n                  | _ => None\n                  end).\n\n  Definition Counter_Register_Networked_external : AutomatonDef Counter_API :=\n    rename\n      Counter_Register_Networked\n      Counter_API\n      (fun act_ctr => inl act_ctr)\n      Register_API_N\n      (fun act_reg => inr act_reg).\n\n  Goal in_traces Counter_Register_Networked_external\n       [\n         Increment;\n           Increment_Done\n       ].\n  Proof.\n    (* a horrible, messy proof that should be automated *)\n    unfold in_traces.\n    eexists ((_, _), nil).\n    eexists; split; [cbv; auto | ].\n    estep_ext_break; [cbv; auto |].\n    estep_int_break (inr (Send CounterAddr Reg_Get_Request RegisterAddr)); [cbv; eauto |].\n    estep_int_break (inr (Recv CounterAddr Reg_Get_Request RegisterAddr));\n      [simpl; intuition; destruct (Address_eq_dec _ _); destruct (Message_eq_dec); destruct (Address_eq_dec _ _); try congruence; intuition | ].\n    estep_int_break (inr (Send RegisterAddr (Reg_Get_Response 0) CounterAddr)); [cbv; eauto |].\n    estep_int_break (inr (Recv RegisterAddr (Reg_Get_Response 0) CounterAddr)); [cbv; eauto |].\n    estep_int_break (inr (Send CounterAddr (Reg_Set 1) RegisterAddr)); [cbv; eauto |].\n    estep_int_break (inr (Recv CounterAddr (Reg_Set 1) RegisterAddr));\n      [simpl; intuition; destruct (Address_eq_dec _ _); destruct (Message_eq_dec); destruct (Address_eq_dec _ _); try congruence; intuition | ].\n    estep_int_break (inr (Send RegisterAddr Reg_Set_Done CounterAddr)); [cbv; eauto |].\n    estep_int_break (inr (Recv RegisterAddr Reg_Set_Done CounterAddr)); [cbv; eauto |].\n    estep_ext_break; [cbv; auto |].\n    eauto.\n  Qed.\n\n  Ltac in_single :=\n    match goal with\n    | [ H : In _ [?x] |- _ ] => inversion H; clear H; shallow\n    end.\n\n  Ltac packet_eq :=\n    match goal with\n    | [ H : mkPacket _ _ _ = mkPacket _ _ _ |- _ ] => inversion H; clear H; subst\n    end.\n\n  Theorem counter_register_networked_correct :\n    refines Counter_Register_Networked_external CounterSpec.Blocking.Spec.\n  Proof.\n    apply refines_trans with (intermediate := Counter_Register_System_external); auto using counter_register_system_correct.\n    apply forward_simulation with\n    (f := fun\n           (st_net : StateType Counter_Register_Networked_external)\n           (st_dist : StateType Counter_Register_System_external) =>\n           let pkts := snd st_net in\n           let net_ctr := fst (fst st_net) in\n           let net_reg := snd (fst st_net) in\n           let net_ctr_pc := fst net_ctr in\n           let net_ctr_val := snd net_ctr in\n           let net_reg_pc := fst net_reg in\n           let net_reg_val := snd net_reg in\n           let dist_ctr := fst st_dist in\n           let dist_reg := snd st_dist in\n           let dist_ctr_pc := fst dist_ctr in\n           let dist_ctr_val := snd dist_ctr in\n           let dist_reg_pc := fst dist_reg in\n           let dist_reg_val := snd dist_reg in\n\n           (* this is probably too detailed reasoning about network state... *)\n           match dist_ctr_pc with\n           | DReady => net_ctr = dist_ctr /\\ net_reg = dist_reg /\\ dist_reg_pc = Reg_Ready /\\ pkts = nil\n           | DIncrementing1 => net_ctr = dist_ctr /\\ net_reg = dist_reg /\\ dist_reg_pc = Reg_Ready /\\ pkts = nil\n           | DIncrementing2 => net_ctr_pc = DIncrementing2 /\\\n                               dist_reg_pc = Reg_Getting /\\\n                               net_ctr_val = dist_ctr_val /\\\n                               net_reg_val = dist_reg_val /\\\n                               ((pkts = [mkPacket CounterAddr Reg_Get_Request RegisterAddr] /\\ net_reg_pc = Reg_Ready) \\/\n                                (pkts = nil /\\ net_reg_pc = Reg_Ready) \\/\n                                (pkts = nil /\\ net_reg_pc = Reg_Getting) \\/\n                                (pkts = [mkPacket RegisterAddr (Reg_Get_Response net_reg_val) CounterAddr] /\\ net_reg_pc = Reg_Ready))\n           | DIncrementing3 => net_ctr = dist_ctr /\\ net_reg = dist_reg /\\ dist_reg_pc = Reg_Ready /\\ pkts = nil\n           | DIncrementing4 => net_ctr_pc = DIncrementing4 /\\\n                               dist_reg_pc = Reg_Setting /\\\n                               net_ctr_val = dist_ctr_val /\\\n                               dist_reg_val = dist_ctr_val /\\\n                               ((pkts = [mkPacket CounterAddr (Reg_Set net_ctr_val) RegisterAddr] /\\ net_reg_pc = Reg_Ready) \\/\n                                (pkts = nil /\\ net_reg_pc = Reg_Ready) \\/\n                                (pkts = nil /\\ net_reg_pc = Reg_Setting /\\ net_reg_val = net_ctr_val) \\/\n                                (pkts = [mkPacket RegisterAddr Reg_Set_Done CounterAddr] /\\ net_reg_pc = Reg_Ready /\\ net_reg_val = net_ctr_val) \\/\n                                (pkts = nil /\\ net_reg_pc = Reg_Ready /\\ net_reg_val = net_ctr_val))\n           | DIncrementing5 => net_ctr = dist_ctr /\\ net_reg = dist_reg /\\ dist_reg_pc = Reg_Ready /\\ pkts = nil\n           | DResetting1 => net_ctr = dist_ctr /\\ net_reg = dist_reg /\\ dist_reg_pc = Reg_Ready /\\ pkts = nil\n           | DResetting2 => net_ctr_pc = DResetting2 /\\\n                            dist_reg_pc = Reg_Setting /\\\n                            net_ctr_val = dist_ctr_val /\\\n                            dist_reg_val = 0 /\\\n                            ((pkts = [mkPacket CounterAddr (Reg_Set 0) RegisterAddr] /\\ net_reg_pc = Reg_Ready) \\/\n                             (pkts = nil /\\ net_reg_pc = Reg_Ready) \\/\n                             (pkts = nil /\\ net_reg_pc = Reg_Setting /\\ net_reg_val = 0) \\/\n                             (pkts = [mkPacket RegisterAddr Reg_Set_Done CounterAddr] /\\ net_reg_pc = Reg_Ready /\\ net_reg_val = 0) \\/\n                             (pkts = nil /\\ net_reg_pc = Reg_Ready /\\ net_reg_val = 0))\n           | DResetting3 => net_ctr = dist_ctr /\\ net_reg = dist_reg /\\ dist_reg_pc = Reg_Ready /\\ pkts = nil\n           | DReading1 => net_ctr = dist_ctr /\\ net_reg = dist_reg /\\ dist_reg_pc = Reg_Ready /\\ pkts = nil\n           | DReading2 => net_ctr_pc = DReading2 /\\\n                          dist_reg_pc = Reg_Getting /\\\n                          net_ctr_val = dist_ctr_val /\\\n                          net_reg_val = dist_reg_val /\\\n                          ((pkts = [mkPacket CounterAddr Reg_Get_Request RegisterAddr] /\\ net_reg_pc = Reg_Ready) \\/\n                           (pkts = nil /\\ net_reg_pc = Reg_Ready) \\/\n                           (pkts = nil /\\ net_reg_pc = Reg_Getting) \\/\n                           (pkts = [mkPacket RegisterAddr (Reg_Get_Response net_reg_val) CounterAddr] /\\ net_reg_pc = Reg_Ready))\n           | DReading3 => net_ctr = dist_ctr /\\ net_reg = dist_reg /\\ dist_reg_pc = Reg_Ready /\\ pkts = nil\n           end\n    ).\n    split.\n    - intros s1 Hstart.\n      destruct s1 as [[[ic_pc ic_v] [ir_pc ir_v]] msgs].\n      inversion Hstart as [[Hc Hr] Hn].\n      inversion Hc; inversion Hr; inversion Hn; simpl in *.\n      eexists; ebreak_compstate; cbv; intuition.\n    - intros s1' s1 act1 s2' Hstep Hrel.\n      simpl in Hstep; unfold Rename_transition in Hstep.\n      destruct act1 as [[[[[] | []] | inact] | ract] | cact].\n      + (* drop *)\n        destruct inact.\n        simpl in Hrel.\n        destruct s1' as [[[s1'_cpc s1'_cv] [s1'_rpc s1'_rv]] s1'_msgs];\n          destruct s1 as [[[s1_cpc s1_cv] [s1_rpc s1_rv]] s1_msgs];\n          destruct s2' as [[s2'_cpc s2'_cv] [s2'_rpc s2'_rv]];\n          simpl in *.\n        destruct s2'_cpc eqn:H;\n          try solve [inversion Hstep as [[? [Hx ?]] ?]; intuition; subst; inversion Hx];\n          exists ((s2'_cpc, s2'_cv), (s2'_rpc, s2'_rv)).\n        all:\n          destruct Hrel;\n          explode;\n          subst;\n          simpl;\n          auto.\n        all:\n          split; [| solve [econstructor; eauto]];\n          explode;\n          subst;\n          intuition;\n          cleanup;\n          subst;\n          match goal with\n          | [ H : In _ [] |- _ ] => solve [inversion H]\n          | [ H : In _ _ |- _ ] => destruct H as [H | H]; [rewrite H | solve by inversion]\n          end;\n          eauto using remove_one_only.\n      + (* send/recv *)\n        destruct s1' as [[[s1'_cpc s1'_cv] [s1'_rpc s1'_rv]] s1'_msgs];\n          destruct s1 as [[[s1_cpc s1_cv] [s1_rpc s1_rv]] s1_msgs];\n          destruct s2' as [[s2'_cpc s2'_cv] [s2'_rpc s2'_rv]].\n        destruct ract as [src m dst | src m dst].\n        * (* send *)\n          destruct src; destruct dst; destruct m; simpl in *; try solve [intuition].\n          -- destruct s1'_cpc; destruct s1'_rpc; try tauto;\n               destruct s2'_cpc; cleanup; try congruence.\n             ++ eexists ((DResetting2, _), (_, _)).\n                simpl; split.\n                ** repeat split; subst; eauto.\n                ** eapply Step_Internal with (int := inr (Reg_Set _)); [| eapply Step_None];\n                     eauto; simpl; intuition.\n             ++ eexists ((DIncrementing4, _), (_, _)).\n                simpl; split.\n                ** repeat split; subst; eauto.\n                ** eapply Step_Internal with (int := inr (Reg_Set _)); [| eapply Step_None];\n                     eauto; simpl; intuition.\n          -- destruct s1'_cpc; destruct s1'_rpc; try tauto;\n               destruct s2'_cpc; cleanup; try congruence.\n             ++ eexists ((DIncrementing2, _), (_, _)).\n                simpl; split.\n                ** repeat split; subst; eauto.\n                ** eapply Step_Internal with (int := inr (Reg_Get_Request)); [| eapply Step_None];\n                     eauto; simpl; intuition.\n             ++ eexists ((DReading2, _), (_, _)).\n                simpl; split.\n                ** repeat split; subst; eauto.\n                ** eapply Step_Internal with (int := inr (Reg_Get_Request)); [| eapply Step_None];\n                     eauto; simpl; intuition.\n          -- destruct s1'_cpc; destruct s1'_rpc; try tauto;\n               destruct s2'_cpc;\n               cleanup;\n               try congruence;\n               repeat break_or;\n               try solve [intuition; congruence];\n               cleanup.\n             ++ eexists ((DResetting2, _), (_, _)).\n                simpl; split.\n                ** repeat split; subst; eauto 10.\n                ** subst; simpl; eauto.\n             ++ eexists ((DIncrementing4, _), (_, _)).\n                simpl; split.\n                ** repeat split; subst; eauto 10.\n                ** subst; simpl; eauto.\n          -- destruct s1'_cpc; destruct s1'_rpc; try tauto;\n               destruct s2'_cpc;\n               cleanup;\n               try congruence;\n               repeat break_or;\n               try solve [intuition; congruence];\n               cleanup.\n             ++ eexists ((DIncrementing2, _), (_, _)).\n                simpl; split.\n                ** repeat split; subst; eauto.\n                ** subst; simpl; eauto.\n             ++ eexists ((DReading2, _), (_, _)).\n                simpl; split.\n                ** repeat split; subst; eauto.\n                ** subst; simpl; eauto.\n        * (* recv *)\n          destruct src; destruct dst; destruct m; simpl in *;\n            try solve [exfalso; destruct s2'_cpc; cleanup; repeat break_or; cleanup; subst; shallow].\n          -- destruct s2'_cpc; cleanup; repeat break_or; cleanup; subst; shallow.\n             ++ in_single; packet_eq;\n                  eexists ((DResetting2, _), (_, _)); split.\n                ** repeat split; eauto 10.\n                ** simpl; eauto.\n             ++ in_single; packet_eq;\n                  eexists ((DIncrementing4, _), (_, _)); split.\n                ** repeat split; eauto 10 using remove_one_only.\n                ** simpl; eauto.\n          -- destruct s2'_cpc; cleanup; repeat break_or; cleanup; subst; shallow.\n             ++ in_single; packet_eq.\n                eexists ((DIncrementing2, _), (_, _)); split.\n                ** repeat split; eauto 10.\n                ** simpl; eauto.\n             ++ in_single; packet_eq.\n                eexists ((DReading2, _), (_, _)); split.\n                ** repeat split; eauto 10.\n                ** simpl; eauto.\n          -- destruct s2'_cpc; cleanup; repeat break_or; cleanup; subst; shallow.\n             ++ in_single; packet_eq.\n                eexists ((DResetting3, _), (_, _)); split.\n                ** repeat split; simpl; eauto 10.\n                ** eapply Step_Internal with (int := inr (Reg_Set_Done)); [| eapply Step_None];\n                     eauto; simpl; intuition.\n             ++ in_single; packet_eq.\n                eexists ((DIncrementing5, _), (_, _)); split.\n                ** repeat split; simpl; eauto 10.\n                ** eapply Step_Internal with (int := inr (Reg_Set_Done)); [| eapply Step_None];\n                     eauto; simpl; intuition.\n          -- destruct s2'_cpc; cleanup; repeat break_or; cleanup; subst; shallow.\n             ++ in_single; packet_eq.\n                eexists ((DIncrementing3, _), (_, _)); split.\n                ** repeat split; eauto using remove_one_only; simpl; eauto.\n                ** eapply Step_Internal with (int := inr (Reg_Get_Response _)); [| eapply Step_None];\n                     eauto; simpl; intuition.\n             ++ in_single; packet_eq.\n                eexists ((DReading3, _), (_, _)); split.\n                ** repeat split; eauto using remove_one_only; simpl; eauto.\n                ** eapply Step_Internal with (int := inr (Reg_Get_Response _)); [| eapply Step_None];\n                     eauto; simpl; intuition.\n      + (* counter API *)\n        destruct s1' as [[[s1'_cpc s1'_cv] [s1'_rpc s1'_rv]] s1'_msgs];\n          destruct s1 as [[[s1_cpc s1_cv] [s1_rpc s1_rv]] s1_msgs];\n          destruct s2' as [[s2'_cpc s2'_cv] [s2'_rpc s2'_rv]];\n          simpl in *.\n        eexists ((s1_cpc, s2'_cv), (s2'_rpc, s2'_rv)). (* identical, only thing that could change is counter pc *)\n        destruct s1'_cpc eqn:Hc1cpc; destruct s2'_cpc eqn:Hs2cpc; try solve [exfalso; cleanup; congruence];\n          destruct cact eqn:Hcact; cleanup; subst; cleanup; simpl in *; try congruence;\n            try break_or; shallow; cleanup; subst; intuition;\n              eapply Step_External; eauto; simpl; eauto.\n  Qed.\n\nEnd CounterNetworked.\n", "meta": {"author": "anishathalye", "repo": "coqioa", "sha": "6c8e741f8a2dfde32024849cd5a92da847e263b8", "save_path": "github-repos/coq/anishathalye-coqioa", "path": "github-repos/coq/anishathalye-coqioa/coqioa-6c8e741f8a2dfde32024849cd5a92da847e263b8/src/CounterNetworked.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2549339603760973}}
{"text": "(*\n * Coq code for \"Using XCAP to Certify Realistic System Code: Machine Context Management\"\n *\n * XCAP common definition and lemma library\n *\n * (for Coq version 8.0pl2)\n *)\n\nRequire Import ZArith.\nRequire Import axiom.\nRequire Import Map.\nRequire Import Mapt.\nRequire Import tm.\nRequire Import mathlib.\nRequire Import propx.\nRequire Import propxlib.\nRequire Import seplogic.\nRequire Import seplib.\nRequire Import List.\nRequire Import tylist.\nRequire Import xcap.\n\nDefinition reg4 L bx si di bp sp : RegFile -> PropX L := fun R =>\n  << R ebx = bx /\\ R esi = si /\\ R edi = di /\\ R ebp = bp /\\ R esp = sp >>.\n\nDefinition reg6 L bx cx dx si di bp sp : RegFile -> PropX L := fun R =>\n  << R ebx = bx /\\ R ecx = cx /\\ R edx = dx /\\ R esi = si /\\ R edi = di /\\ R ebp = bp /\\ R esp = sp >>.\n\nDefinition _Fn6p L args bx cx dx si di bp sp ss ret apre apost : State -> PropX L :=\n  fun S : State => let (HR, F) := S in let (H, R) := HR in\n    reg6 _ bx cx dx si di bp sp R\n      ./\\ star (stack _ sp ss (ret :: args))\n         (star apre\n               (fun H => (extv _ _ (eq_rect _ _\n                                   (Lift _ _ (var tO _ H)\n                                   ./\\ codeptr _ ret\n                                     (fun S' => let (HR', F') := S' in let (H', R') := HR' in\n                                     Ex retv. reg6 _ bx cx dx si di bp (sp+4) R' ./\\ << R' eax = retv>>\n                                          ./\\ star (stack _ (sp+4) (ss+4) args)\n                                             (star (fun H => Shift _ _ (eq_rect _ _ (apost retv H)\n                                                            _ (eq_tplus_tO_tail _)) _)\n                                                   (fun H => Lift _ _ (var tO _ H))) H'))\n                                  _ (tylist.eq_tplus_tO _))))) H.\n\nNotation \"'Fn6p' a1 , a2 '{Aux' : ; 'Pre' : apre ; 'Post' : apost }\" :=\n  (fun S : State => Ex a1, a2, bx, cx, dx, si, di, bp, sp, ss, ret.\n     extv _ _ (eq_rect _ _\n                          (_Fn6p _ (a1::a2::nil) bx cx dx si di bp sp ss ret apre (fun retv => apost) S)\n                          _ (tylist.eq_tplus_tO _))) (at level 110, only parsing).\n\nDefinition _Fn L args fs fvs bx si di bp sp ss ret apre apost : State -> PropX L :=\n  fun S : State => match S with ((H, R), F) =>\n    reg4 L bx si di bp sp R ./\\ << 0 <= ss-fs >>\n      ./\\ (extv _ _ (eq_rect _ _\n              ((star (stack _ sp ss (fvs ++ (ret :: args)))\n               (star (fun H => Shift _ _ (eq_rect _ _ (apre H) _ (eq_tplus_tO_tail _)) _)\n                     (fun H => Lift _ _ (var tO _ H))) H) ./\\\n                               codeptr _ ret\n                                     (fun S' => match S' with ((H',R'),F') =>\n                                     Ex retv. reg4 _ bx si di bp (sp+4+4*Z_of_nat (length fvs)) R' ./\\ << 0 <= ss - fs >> ./\\ << R' eax = retv>>\n                                          ./\\ star (stack _ (sp+4+4*Z_of_nat (length fvs)) (ss+4+4*Z_of_nat (length fvs)) args)\n                                             (star (fun H => Shift _ _ (eq_rect _ _ (apost retv H)\n                                                            _ (eq_tplus_tO_tail _)) _)\n                                                   (fun H => Lift _ _ (var tO _ H))) H'\n                                                end))\n                                  _ (tylist.eq_tplus_tO _)))\n                   end.\n\nDefinition _Fn6 L args fs fvs bx cx dx si di bp sp ss ret apre apost : State -> PropX L :=\n  fun S : State => match S with ((H, R), F) =>\n    reg6 L bx cx dx si di bp sp R ./\\ << 0 <= ss - fs >>\n      ./\\ (extv _ _ (eq_rect _ _\n              ((star (stack _ sp ss (fvs ++ (ret :: args)))\n               (star (fun H => Shift _ _ (eq_rect _ _ (apre H) _ (eq_tplus_tO_tail _)) _)\n                     (fun H => Lift _ _ (var tO _ H))) H) ./\\\n                               codeptr _ ret\n                                     (fun S' => match S' with ((H',R'),F') =>\n                                     Ex retv. reg6 _ bx cx dx si di bp (sp+4+4*Z_of_nat (length fvs)) R' ./\\ << 0 <= ss - fs >> ./\\ << R' eax = retv>>\n                                          ./\\ star (stack _ (sp+4+4*Z_of_nat (length fvs)) (ss+4+4*Z_of_nat (length fvs)) args)\n                                             (star (fun H => Shift _ _ (eq_rect _ _ (apost retv H)\n                                                            _ (eq_tplus_tO_tail _)) _)\n                                                   (fun H => Lift _ _ (var tO _ H))) H'\n                                                end))\n                                  _ (tylist.eq_tplus_tO _)))\n                   end.\n\nNotation \"'Fn' '{Aux' : ; 'Local' : [ fs ] ; 'Pre' : apre ; 'Post' : apost }\" :=\n  (fun S : State => Ex bx, si, di, bp, sp, ss, ret.\n     _Fn _ nil fs nil bx si di bp sp ss ret\n           (match S with ((_,r),f) => apre end)\n           (fun retv => apost) S) (at level 110, only parsing).\n\nNotation \"'Fn' a1 '{Aux' : ; 'Local' : [ fs ] ; 'Pre' : apre ; 'Post' : apost }\" :=\n  (fun S : State => Ex a1, bx, si, di, bp, sp, ss, ret.\n     _Fn _ (a1::nil) fs nil bx si di bp sp ss ret\n           (match S with ((_,r),f) => apre end)\n           (fun retv => apost) S) (at level 110, only parsing).\n\nNotation \"'Fn' a1 , a2 '{Aux' : ; 'Local' : [ fs ] ; 'Pre' : apre ; 'Post' : apost }\" :=\n  (fun S : State => Ex a1, a2, bx, si, di, bp, sp, ss, ret.\n     _Fn _ (a1::a2::nil) fs nil bx si di bp sp ss ret\n           (match S with ((_,r),f) => apre end)\n           (fun retv => apost) S) (at level 110, only parsing).\n\nNotation \"'Fnp' a1 '{Aux' : x1 ; 'Local' : [ fs ] ; 'Pre' : apre ; 'Post' : apost }\" :=\n  (fun S : State => Ex a1, x1, bx, si, di, bp, sp, ss, ret.\n     extv _ _ (eq_rect _ _\n    (_Fn _ (a1::nil) fs nil bx si di bp sp ss ret\n           (match S with ((_,r),f) => apre end)\n           (fun retv => apost) S)\n            _ (tylist.eq_tplus_tO _))) (at level 110, only parsing).\n\nNotation \"'Fnp' a1 , a2 '{Aux' : x1 ; 'Local' : [ fs ] ; 'Pre' : apre ; 'Post' : apost }\" :=\n  (fun S : State => Ex a1, a2, x1, bx, si, di, bp, sp, ss, ret.\n     extv _ _ (eq_rect _ _\n    (_Fn _ (a1::a2::nil) fs nil bx si di bp sp ss ret\n           (match S with ((_,r),f) => apre end)\n           (fun retv => apost) S)\n            _ (tylist.eq_tplus_tO _))) (at level 110, only parsing).\n\nNotation \"'Fnp' a1 , a2 '{Aux' : ; 'Local' : [ fs ] ; 'Pre' : apre ; 'Post' : apost }\" :=\n  (fun S : State => Ex a1, a2, bx, si, di, bp, sp, ss, ret.\n     extv _ _ (eq_rect _ _\n    (_Fn _ (a1::a2::nil) fs nil bx si di bp sp ss ret\n           (match S with ((_,r),f) => apre end)\n           (fun retv => apost) S)\n            _ (tylist.eq_tplus_tO _))) (at level 110, only parsing).\n\nNotation \"'Fnp' a1 , a2 , a3 , a4 , a5 '{Aux' : ; 'Local' : [ fs ] ; 'Pre' : apre ; 'Post' : apost }\" :=\n  (fun S : State => Ex a1, a2, a3, a4, a5, bx, si, di, bp, sp, ss, ret.\n     extv _ _ (eq_rect _ _\n    (_Fn _ (a1::a2::a3::a4::a5::nil) fs nil bx si di bp sp ss ret\n           (match S with ((_,r),f) => apre end)\n           (fun retv => apost) S)\n            _ (tylist.eq_tplus_tO _))) (at level 110, only parsing).\n\nNotation \"'Fn6' '{Aux' : ; 'Local' : [ fs ] ; 'Pre' : apre ; 'Post' : apost }\" :=\n  (fun S : State => Ex bx, cx, dx, si, di, bp, sp, ss, ret.\n     _Fn6 _ nil fs nil bx cx dx si di bp sp ss ret\n           (match S with ((_,r),f) => apre end)\n           (fun retv => apost) S) (at level 110, only parsing).\n\nNotation \"'Fn6' '{Aux' : ; 'Local' : [ fs ] , f1 ; 'Pre' : apre ; 'Post' : apost }\" :=\n  (fun S : State => Ex f1, bx, cx, dx, si, di, bp, sp, ss, ret.\n     _Fn6 _ nil fs (f1::nil) bx cx dx si di bp sp ss ret\n           (match S with ((_,r),f) => apre end)\n           (fun retv => apost) S) (at level 110, only parsing).\n\nNotation \"'Fn6' '{Aux' : ; 'Local' : [ fs ] , f1 , f2 ; 'Pre' : apre ; 'Post' : apost }\" :=\n  (fun S : State => Ex f1, f2, bx, cx, dx, si, di, bp, sp, ss, ret.\n     _Fn6 _ nil fs (f1::f2::nil) bx cx dx si di bp sp ss ret\n           (match S with ((_,r),f) => apre end)\n           (fun retv => apost) S) (at level 110, only parsing).\n\nNotation \"'Fn6p_' a1 , a2 '{Aux' : ; 'Local' : [ fs ] ; 'Pre' : apre ; 'Post' : apost }\" :=\n  (fun S : State => Ex a1, a2, bx, cx, dx, si, di, bp, sp, ss, ret.\n     extv _ _ (eq_rect _ _\n    (_Fn6 _ (a1::a2::nil) fs nil bx cx dx si di bp sp ss ret\n           (match S with ((_,r),f) => apre end)\n           (fun retv => apost) S)\n            _ (tylist.eq_tplus_tO _))) (at level 110, only parsing).\n\n\nLemma wfjmpr' : forall Si a r,\n                (a ==> fun S => extv _ _ (eq_rect _ _\n                                  (codeptr _ (_R S r) (var _ _) ./\\ var _ _ S)\n                                  _ (eq_tplus_tO _)))\n                                            -> WFiseq Si a (instr (jmp (reg r))).\nintros. apply wfjmpr. unfold Itp. intros. generalize (H _ _ H0). clear H. intro.\ndestv H a'. simpl in H. dest H. destv H a''. simpl in H. dest H. des H2.\napply ok_extv_i with a''. simpl. splitx. auto. generalize (H2 S). clear H2. intro.\ndes H2. rewrite <- shift_subst_eq in H2. auto.\nQed.\n\nLemma wfret'   : forall Si a,\n                (a ==> (fun S => Ex fret.\n                                   <<Map.lookup (_H S) (_R S esp) fret>> ./\\\n                                  extv _ _ (eq_rect _ _\n                                  (codeptr _ fret (var _ _) ./\\\n                                   Ex s'.\n                                     <<Next pop' S s'>> ./\\ var _ _ s')\n                                  _ (eq_tplus_tO _))))\n                                            -> WFiseq Si a (instr ret).\nintros. apply wfret. unfold Itp. intros. destruct S. destruct p.\ngeneralize (H _ _ H0). clear H. intro. destv H fret. dest H. simpl in H1.\ndestv H1 a'. simpl in H1. dest H1. destv H1 a''. simpl in H1. dest H1.\ndes H3.\nexistsx fret. splitx. auto. simpl. apply ok_extv_i with a''. simpl. splitx.\nauto. destv H2 S'. dest H2. existsx S'. splitx; auto.\ngeneralize (H3 S'). clear H3. intro H3. des H3.\nrewrite <- shift_subst_eq in H3. auto.\nQed.\n\nLemma wfweak : forall Si a a' I, (a ==> a') -> (Si |-{a'} I) -> (Si |-{a} I).\nintros. apply InstrSeqWeakening with Si a'; auto.\nunfold subseteq. intro. destruct (Si a0); auto.\nQed.\n\nLemma WFret : forall Si a fs, Si |-{ (Fn6 {Aux : ; Local : [fs] ;\n  Pre:  a;\n  Post: a}) } (instr ret).\nOpaque star codeptr ptoanyn.\nintros. apply wfret. unfold Itp. intros. destruct S; destruct p.\ndo 9 (dest H). dest H. dest H0. dest H1. simpl in H1.\ndest H1. generalize H1; clear H1; rwsubst; intros.\nrewrite <- shift_subst_eq_fun in H1.\nreplace (fun h:Heap => x8 h) with x8 in H1; try apply ext_eq; auto.\nTransparent codeptr.\nsimpl in H2.\nexistsx x7. splitx. dest H. destruct H3. destruct H4. destruct H5. destruct H6.\ndestruct H7. rewrite H8. propx.\ngeneralize H1; clear H1; apply lookup_star_lookup. apply stack_lookup_0.\ndest H2. simpl in H2. existsx x9. simpl. dest H2. splitx; auto.\nexistsx (h, updR r esp (x5 + 4), e). splitx.\npropx. dest H. destruct H4. destruct H5. destruct H6.\ndestruct H7. destruct H8.\napply stp_pop'; rewrite H9.\ngeneralize H1; clear H1; apply star_imp_prop. unfold stack. simpl.\nintros. generalize (star_sym _ _ _ _ H1); clear H1; apply star_imp_prop; intro.\napply star_imp_prop; intros. dest H1. unfold Dword. omega.\nunfold uR, updR. split; auto. intros. rewrite beq_rneq_false; auto.\ndes H3. generalize (H3 (h, updR r esp (x5+4), e)); clear H3; intros.\napply ok_imp_e with\n       (Subst tO State\n            (Subst (tS State tO) Heap\n               (Shift (tS Heap tO) tO\n                  (Ex retv\n                   . reg6 (tS Heap tO) x x0 x1 x2 x3 x4 (x5 + 4 + 0) (updR r esp (x5 + 4))\n                     ./\\ << 0 <= x6 - fs >>\n                         ./\\ << updR r esp (x5 + 4) eax = retv >>\n                             ./\\ star (stack (tS Heap tO) (x5 + 4 + 0) (x6 + 4 + 0) nil)\n                                   (star (fun H : Heap => Shift tO tO (a H) Heap) (fun H : Heap => var tO Heap H)) h) State)\n               (fun x : Heap => Shift tO tO (x8 x) State)) x9); auto.\nclear H3. simpl. existsx (r eax). splitx. propx. unfold updR. simpl.\ndest H. destruct H3. destruct H4. destruct H5. destruct H6. destruct H7.\nrepeat (split; auto). symmetry. apply Zplus_0_r.\nsplitx; auto. splitx. propx. tauto.\nrwshift (tS Heap tO) tO. do 2 rwsubst.\nrewrite <- shift_subst_eq_2_fun'. rewrite <- shift_subst_eq_fun.\ngeneralize H1; clear H1; apply star_imp; auto.\nintro. intro. replace (x5+4+0) with (x5+4); try (symmetry; apply Zplus_0_r).\nreplace (x6+4+0) with (x6+4); try (symmetry; apply Zplus_0_r).\napply stack_return.\nQed.\n\n(* add esp, 8\n   ret\n*)\nLemma WFret8 : forall Si a fs,\n  Si |-{ (Fn6 {Aux : ; Local : [fs], f1, f2 ;\n            Pre:  a;\n            Post: a}) } iseq (add esp (word 8))\n                             (instr ret).\nOpaque star codeptr ptoanyn.\nintros.\napply wfiseq with (Fn6 {Aux : ; Local : [fs+8] ;\n  Pre:  a;\n  Post: a}).\nunfold Itp. intros. destruct S; destruct p.\ndestv H f1. destv H f2.\ndestv H bx. destv H cx. destv H dx. destv H si. destv H di. destv H bp.\ndestv H sp. destv H ss. destv H retp. dest H.\ndest H0. destv H1 aprv. simpl in H1. dest H1.\ngeneralize H1; clear H1; rwsubst; intros. rewrite <- shift_subst_eq_fun in H1.\ndest H. destruct H3. destruct H4. destruct H5. destruct H6. destruct H7.\nexistsx (h, updR r esp (sp+8),\n  fun f => match f with cf => Zlt_bool (sp + 8) 0\n                      | zf => Zeq_bool (sp + 8) 0 end). splitx.\npropx. apply stp_add; simpl; rewrite H8.\nunfold stack in H1. simpl in H1.\ngeneralize (star_sym _ _ _ _ H1); clear H1; intros.\ngeneralize (star_assoc_R _ _ _ _ _ H1); clear H1; intros.\ngeneralize (star_assoc_R _ _ _ _ _ H1); clear H1; intros.\ngeneralize (star_assoc_R _ _ _ _ _ H1); clear H1; intros.\ngeneralize (star_sym _ _ _ _ H1); clear H1.\napply star_imp_prop. intro. replace (sp +4 +4) with (sp+8); try ring.\napply star_imp_prop. intros. dest H1. unfold Dword. omega.\nunfold uR, updR. split; auto. intros. rewrite beq_rneq_false; auto.\nunfold CalcF; auto.\nexistsx bx. existsx cx. existsx dx. existsx si. existsx di. existsx bp.\nexistsx (sp+8). existsx (ss+8). existsx retp. unfold _Fn6.\nsplitx; auto. unfold reg6, updR. simpl. propx. tauto.\nsplitx. replace (ss +8-(fs+8)) with (ss-fs); try ring; auto.\nexistsx aprv. simpl. splitx; auto. rwsubst. rewrite <- shift_subst_eq_fun.\ngeneralize H1; clear H1; apply star_imp; auto. intros.\nreplace (sp+8) with (sp+4+4); try ring.\nreplace (ss+8) with (ss+4+4); try ring.\napply stack_return with f2.\napply stack_return with f1; auto.\nreplace (sp+8+4+0) with (sp+4+8); try ring.\nreplace (ss+8+4+0) with (ss+4+8); try ring.\nreplace (ss+8-(fs+8)) with (ss-fs); try ring.\nauto.\napply WFret.\nQed.\n\n", "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/xcaplib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2549339603760972}}
{"text": "Require Import Charge.Logics.ILogic.\nRequire Import Charge.Logics.Later.\nRequire Import Charge.Logics.ILEmbed.\nRequire Import Charge.Open.OpenILogic.\nRequire Import Charge.Open.Subst.\n\nRequire Import Java.Language.Lang.\nRequire Import Java.Language.Program.\n\nRequire Import Java.Semantics.OperationalSemantics.\nRequire Import Java.Semantics.AxiomaticSemantics.\n\nRequire Import Java.Logic.SpecLogic.\nRequire Import Java.Logic.AssertionLogic.\n\nRequire Import ExtLib.Data.PreFun.\nRequire Import ExtLib.Structures.Applicative.\n\nRequire Import MirrorCharge.Java.Reify.\n\nSet Implicit Arguments.\nSet Strict Implicit.\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\nLemma pull_exists {A} {P : A -> sasn} c Q G\n\t(H : forall x, G |-- {[P x]} c {[Q]}) :\n\tG |-- {[lexists P]} c {[Q]}.\nProof.\n  rewrite <- exists_into_precond2.\n  apply lforallR. apply H.\nQed.\nPrint sasn.\nLemma eq_to_subst x (e : stack -> val) (P Q : sasn) \n    (H : apply_subst P (subst1 e x) |-- apply_subst Q (subst1 e x)) :\n\tembed (ap_eq [stack_get x, e]) //\\\\ P |-- Q.\nProof.\n  \n  admit.\nQed.\n\nLemma ent_left_exists {A} (P : sasn) (Q : A -> sasn)\n\t(H : exists x, P |-- Q x) :\n\tP |-- lexists Q.\nProof.\n  admit.\nQed.\n\nLemma rule_seq c1 c2 (P Q R : sasn) G\n      (Hc1 : G |-- {[P]} c1 {[Q]})\n      (Hc2 : G |-- {[Q]} c2 {[R]}) :\n  G |-- {[P]} cseq c1 c2 {[R]}.\nProof.\n  apply rule_seq with Q; assumption.\nQed.\n\nLemma rule_skip P Q G : P |-- Q -> G |-- {[P]} cskip {[Q]}.\nProof.\n  intros.\n  eapply roc_post; [eapply rule_skip | apply H].\nQed.\n\t\nLemma rule_skip2 P G :(* P |-- Q -> *)G |-- {[P]} cskip {[P]}.\nProof.\n  apply rule_skip. reflexivity.\nQed.\n\nLemma rule_if (e : dexpr) c1 c2 (P Q : sasn) G\n      (Hc1 : G |-- {[(@embed (@vlogic Lang.var val) sasn _ \n                      (ap_eq [eval e, pure (vbool true)])) //\\\\ P]} c1 {[Q]})\n      (Hc2 : G |-- {[(@embed (@vlogic Lang.var _) sasn _ \n                      (ap_eq [eval (E_not e), pure (vbool true)])) //\\\\ P]} c2 {[Q]}) : \n  G |-- {[P]} cif e c1 c2 {[Q]}. \nProof.\n  reify_imp (G |-- {[P]} cif e c1 c2 {[Q]}).\n  eapply rule_if; unfold vlogic_eval, Open.liftn, Open.lift; simpl in *;\n  \t[apply Hc1|apply Hc2].\nQed.\n\nRequire Import Charge.Logics.BILogic.\n\n  Lemma rule_read_fwd (x y : Lang.var) (f : field) (e : stack -> val) (P Q : sasn) (G : spec)\n    (HP : P |-- ap_pointsto [y, f, e])\n    (HQ : Exists v : val, (embed (ap_eq [stack_get x, apply_subst e (subst1 (pure (T := Fun stack) v) x)])) //\\\\\n    \t\t\t\t\t      (apply_subst P (subst1 (pure (T := Fun stack) v) x)) |-- Q) :\n    G |-- {[ P ]} cread x y f {[ Q ]}.\n  Proof.\n    pose proof @rule_read_fwd x y f e P. \n    unfold Open.liftn, Open.lift, open_eq, stack_get, Open.var_expr in *; simpl in *.\n    rewrite <- HQ , <- H; [apply ltrueR | apply HP].\n  Qed.\n\n\n  Lemma rule_write_fwd (x : Lang.var) (f : field) (e : dexpr) G (P Q F : sasn) (e' : stack -> val)\n        (HP : P |-- ap_pointsto [x, f, e'] ** F) \n        (HQ : ap_pointsto [x, f, eval e] ** F |-- Q) :\n    G |-- ({[ P ]} cwrite x f e {[ Q ]}).\n  Proof.\n     pose proof @rule_write_frame G P F x f e' e. unfold Open.liftn, Open.lift, open_eq, stack_get, Open.var_expr in *; simpl in *.\n\t rewrite <- HQ, H.\n\t unfold stack. unfold pointsto. unfold eval.\n\t \n\t setoid_rewrite <- sepSPC1 at 2.\n\t reflexivity. \n\t rewrite HP. \n\t setoid_rewrite <- sepSPC1 at 2.\n\t reflexivity.\n  Qed.\n\n  Lemma rule_assign_fwd (x : Lang.var) (e : dexpr) G P :\n    G |-- {[ P ]} cassign x e {[ Exists v : val,\n                                 embed (ap_eq [stack_get x, \n                                               apply_subst (eval e) (subst1 (pure (T := Fun stack) v) x)]) //\\\\ \n    \t\t\t\t\t\t\t   (apply_subst P (subst1 (pure (T := Fun stack) v) x)) ]}.\n  Proof.\n    pose proof @rule_assign_fwd G P.\n    apply H. reflexivity.\n  Qed.\n\n  Lemma rule_alloc_fwd (x : Lang.var) (C : class) (G : spec) (P Q : sasn) (fields : list field) (Pr : Program) \n\t(Heq : G |-- prog_eq Pr)\n\t(Hf : field_lookup Pr C fields) \n\t(Hent : Exists p : val, embed (ap_typeof [stack_get x, C]) //\\\\\n\t                                            embed (ap_eq [stack_get x, pure p]) //\\\\\n\t                                            fold_right (fun f P => ap_pointsto [x, f, pure null] ** P)\n\t                                                    (apply_subst P (subst1 (pure (T := Fun stack) p) x)) fields |-- Q) :\n\tG |-- {[ P ]} calloc x C {[ Q ]}.\n  Proof.\n  \tadmit.\n  Qed.\n\nCheck apply_subst.\n  Lemma rule_static_complete (x : Lang.var) C (m : String.string) (es : list dexpr) (ps : list String.string) (r : Lang.var) G\n    (P Q F Pm Qm : sasn)\n    (HSpec : G |-- |> method_spec C m ps r Pm Qm)\n    (HPre: P |-- apply_subst Pm (substl_trunc (zip ps (@map _ (stack -> val) eval es))) ** F)\n    (HLen: length ps = length es) :\n          G |-- {[ P ]} cscall x C m es {[ Exists v:val, apply_subst Qm (substl_trunc (zip (@cons String.string r ps) \n                                     (@cons (stack -> val) (stack_get x)\n                                      (@map (stack -> val) _ (fun e => apply_subst e (subst1 (pure (T := Fun stack) v) x)) \n                                          (@map dexpr (stack -> val) eval es))))) ** \n                           apply_subst F (subst1 (pure (T := Fun stack) v) x)]}.\nProof.\n\tadmit.\nQed.\n\nLemma rule_dynamic_complete (x y : Lang.var) (m : String.string) (es : list dexpr) (ps : list String.string) C (r : Lang.var) G\n    (P Q F Pm Qm : sasn)\n    (HSpec : G |-- |> method_spec C m ps r Pm Qm)\n    (HPre: P |-- (embed (ap_typeof [stack_get y, C]) //\\\\ \n                  apply_subst Pm (substl_trunc (zip ps (@map _ (stack -> val) eval (E_var y :: es))))) ** \n                 F)\n    (HPost : Exists v:val, embed (ap_typeof [apply_subst (stack_get y) (subst1 (pure (T := Fun stack) v) x), C]) //\\\\\n                    apply_subst Qm (substl_trunc (zip (@cons String.string r ps) \n                    (@cons (stack -> val) (stack_get x) (@cons (stack -> val) (apply_subst (stack_get y) (subst1 (pure (T := Fun stack) v) x))\n\t\t\t        (@map (stack -> val) _ (fun e => apply_subst e (subst1 (pure (T := Fun stack) v) x)) \n\t\t\t        (@map dexpr (stack -> val) eval es)))))) ** \n                    apply_subst F (subst1 (pure (T := Fun stack) v) x) |-- Q)\n    (HLen: length ps = length (E_var y :: es)) :\n           G |-- {[ P ]} cdcall x y m es {[ Q ]}.\nProof.\n    eapply rule_dcall_forward.\n    eassumption.\n    rewrite HPre. \n    reflexivity.\n    assumption.\n    rewrite <- HPost.\n    reflexivity.\nQed.\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/Semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2548131530526359}}
{"text": "Require Export Program.Basics. Open Scope program_scope.\nFrom Paco Require Import paco8 pacotac.\nSet Implicit Arguments.\n\nSection GeneralizedPaco8.\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\nLocal Notation rel := (rel8 T0 T1 T2 T3 T4 T5 T6 T7).\n\nSection RClo.\n\nInductive rclo8 (clo: rel->rel) (r: rel): rel :=\n| rclo8_base\n    x0 x1 x2 x3 x4 x5 x6 x7\n    (IN: r x0 x1 x2 x3 x4 x5 x6 x7):\n    @rclo8 clo r x0 x1 x2 x3 x4 x5 x6 x7\n| rclo8_clo'\n    r' x0 x1 x2 x3 x4 x5 x6 x7\n    (LE: r' <8= rclo8 clo r)\n    (IN: clo r' x0 x1 x2 x3 x4 x5 x6 x7):\n    @rclo8 clo r x0 x1 x2 x3 x4 x5 x6 x7\n.           \n\nLemma rclo8_mon_gen clo clo' r r' x0 x1 x2 x3 x4 x5 x6 x7\n      (IN: @rclo8 clo r x0 x1 x2 x3 x4 x5 x6 x7)\n      (LEclo: clo <9= clo')\n      (LEr: r <8= r') :\n  @rclo8 clo' r' x0 x1 x2 x3 x4 x5 x6 x7.\nProof.\n  induction IN; intros.\n  - econstructor 1. apply LEr, IN.\n  - econstructor 2; [intros; eapply H, PR|apply LEclo, IN].\nQed.\n\nLemma rclo8_mon clo:\n  monotone8 (rclo8 clo).\nProof.\n  repeat intro. eapply rclo8_mon_gen; [apply IN|intros; apply PR|apply LE].\nQed.\n\nLemma rclo8_clo clo r:\n  clo (rclo8 clo r) <8= rclo8 clo r.\nProof.\n  intros. econstructor 2; [|apply PR]. \n  intros. apply PR0.\nQed.\n\nLemma rclo8_rclo clo r:\n  rclo8 clo (rclo8 clo r) <8= rclo8 clo r.\nProof.\n  intros. induction PR.\n  - eapply IN.\n  - econstructor 2; [eapply H | eapply IN].\nQed.\n\nLemma rclo8_compose clo r:\n  rclo8 (rclo8 clo) r <8= rclo8 clo r.\nProof.\n  intros. induction PR.\n  - apply rclo8_base, IN.\n  - apply rclo8_rclo.\n    eapply rclo8_mon; [apply IN|apply H].\nQed.\n\nEnd RClo.  \n\nSection Main.\n\nVariable gf: rel -> rel.\nHypothesis gf_mon: monotone8 gf.\n\nVariant gpaco8 clo r rg x0 x1 x2 x3 x4 x5 x6 x7 : Prop :=\n| gpaco8_intro (IN: @rclo8 clo (paco8 (compose gf (rclo8 clo)) (rg \\8/ r) \\8/ r) x0 x1 x2 x3 x4 x5 x6 x7)\n.\n\nDefinition gupaco8 clo r := gpaco8 clo r r.\n\nLemma gpaco8_def_mon clo : monotone8 (compose gf (rclo8 clo)).\nProof.\n  eapply monotone8_compose. apply gf_mon. apply rclo8_mon.\nQed.\n\nHint Resolve gpaco8_def_mon : paco.\n\nLemma gpaco8_mon clo r r' rg rg' x0 x1 x2 x3 x4 x5 x6 x7\n      (IN: @gpaco8 clo r rg x0 x1 x2 x3 x4 x5 x6 x7)\n      (LEr: r <8= r')\n      (LErg: rg <8= rg'):\n  @gpaco8 clo r' rg' x0 x1 x2 x3 x4 x5 x6 x7.\nProof.\n  destruct IN. econstructor.\n  eapply rclo8_mon. apply IN.\n  intros. destruct PR; [|right; apply LEr, H].\n  left. eapply paco8_mon. apply H.\n  intros. destruct PR.\n  - left. apply LErg, H0.\n  - right. apply LEr, H0.\nQed.\n\nLemma gupaco8_mon clo r r' x0 x1 x2 x3 x4 x5 x6 x7\n      (IN: @gupaco8 clo r x0 x1 x2 x3 x4 x5 x6 x7)\n      (LEr: r <8= r'):\n  @gupaco8 clo r' x0 x1 x2 x3 x4 x5 x6 x7.\nProof.\n  eapply gpaco8_mon. apply IN. apply LEr. apply LEr.\nQed.\n\nLemma gpaco8_base clo r rg: r <8= gpaco8 clo r rg.\nProof.\n  econstructor. apply rclo8_base. right. apply PR.\nQed.\n\nLemma gpaco8_gen_guard  clo r rg:\n  gpaco8 clo r (rg \\8/ r) <8= gpaco8 clo r rg.\nProof.\n  intros. destruct PR. econstructor.\n  eapply rclo8_mon. apply IN. intros.\n  destruct PR; [|right; apply H].\n  left. eapply paco8_mon_gen; intros. apply H. apply PR.\n  destruct PR. apply H0. right. apply H0.\nQed.\n\nLemma gpaco8_rclo clo r rg:\n  rclo8 clo r <8= gpaco8 clo r rg.\nProof.\n  intros. econstructor.\n  eapply rclo8_mon. apply PR.\n  intros. right. apply PR0.\nQed.\n\nLemma gpaco8_clo clo r rg:\n  clo r <8= gpaco8 clo r rg.\nProof.\n  intros. apply gpaco8_rclo. eapply rclo8_clo', PR.\n  apply rclo8_base.\nQed.\n\nLemma gpaco8_gen_rclo clo r rg:\n  gpaco8 (rclo8 clo) r rg <8= gpaco8 clo r rg.\nProof.\n  intros. destruct PR. econstructor.\n  apply rclo8_compose.\n  eapply rclo8_mon. apply IN. intros.\n  destruct PR; [|right; apply H].\n  left. eapply paco8_mon_gen; intros; [apply H| |apply PR].\n  eapply gf_mon, rclo8_compose. apply PR.\nQed.\n\nLemma gpaco8_step_gen clo r rg:\n  gf (gpaco8 clo (rg \\8/ r) (rg \\8/ r)) <8= gpaco8 clo r rg.\nProof.\n  intros. econstructor. apply rclo8_base. left.\n  pstep. eapply gf_mon. apply PR.\n  intros. destruct PR0. eapply rclo8_mon. apply IN.\n  intros. destruct PR0.\n  - left. eapply paco8_mon. apply H. intros. destruct PR0; apply H0.\n  - right. apply H.\nQed.\n\nLemma gpaco8_step clo r rg:\n  gf (gpaco8 clo rg rg) <8= gpaco8 clo r rg.\nProof.\n  intros. apply gpaco8_step_gen.\n  eapply gf_mon. apply PR. intros.\n  eapply gpaco8_mon. apply PR0. left; apply PR1. left; apply PR1.\nQed.\n\nLemma gpaco8_final clo r rg:\n  (r \\8/ paco8 gf rg) <8= gpaco8 clo r rg.\nProof.\n  intros. destruct PR. apply gpaco8_base, H.\n  econstructor. apply rclo8_base.\n  left. eapply paco8_mon_gen. apply H.\n  - intros. eapply gf_mon. apply PR.\n    intros. apply rclo8_base. apply PR0.\n  - intros. left. apply PR.\nQed.\n\nLemma gpaco8_unfold clo r rg:\n  gpaco8 clo r rg <8= rclo8 clo (gf (gupaco8 clo (rg \\8/ r)) \\8/ r).\nProof.\n  intros. destruct PR.\n  eapply rclo8_mon. apply IN.\n  intros. destruct PR; cycle 1. right; apply H.\n  left. _punfold H; [|apply gpaco8_def_mon].\n  eapply gf_mon. apply H.\n  intros. econstructor.\n  eapply rclo8_mon. apply PR.\n  intros. destruct PR0; cycle 1. right. apply H0.\n  left. eapply paco8_mon. apply H0.\n  intros. left. apply PR0.\nQed.\n  \nLemma gpaco8_cofix clo r rg \n      l (OBG: forall rr (INC: rg <8= rr) (CIH: l <8= rr), l <8= gpaco8 clo r rr):\n  l <8= gpaco8 clo r rg.\nProof.\n  assert (IN: l <8= gpaco8 clo r (rg \\8/ l)).\n  { intros. apply OBG; [left; apply PR0 | right; apply PR0 | apply PR]. }\n  clear OBG. intros. apply IN in PR.\n  destruct PR. econstructor.\n  eapply rclo8_mon. apply IN0.\n  clear x0 x1 x2 x3 x4 x5 x6 x7 IN0.\n  intros. destruct PR; [|right; apply H].\n  left. revert x0 x1 x2 x3 x4 x5 x6 x7 H.\n  pcofix CIH. intros.\n  _punfold H0; [..|apply gpaco8_def_mon]. pstep.\n  eapply gf_mon. apply H0. intros.\n  apply rclo8_rclo. eapply rclo8_mon. apply PR.\n  intros. destruct PR0.\n  - apply rclo8_base. right. apply CIH. apply H.\n  - destruct H; [destruct H|].\n    + apply rclo8_base. right. apply CIH0. left. apply H.\n    + apply IN in H. destruct H.\n      eapply rclo8_mon. apply IN0.\n      intros. destruct PR0.\n      * right. apply CIH. apply H.      \n      * right. apply CIH0. right. apply H.\n    + apply rclo8_base. right. apply CIH0. right. apply H.\nQed.\n\nLemma gpaco8_gupaco clo r rg:\n  gupaco8 clo (gpaco8 clo r rg) <8= gpaco8 clo r rg.\nProof.\n  eapply gpaco8_cofix.\n  intros. destruct PR. econstructor.\n  apply rclo8_rclo. eapply rclo8_mon. apply IN.\n  intros. destruct PR.\n  - apply rclo8_base. left.\n    eapply paco8_mon. apply H.\n    intros. left; apply CIH.\n    econstructor. apply rclo8_base. right.\n    destruct PR; apply H0.\n  - destruct H. eapply rclo8_mon. apply IN0.\n    intros. destruct PR; [| right; apply H].\n    left. eapply paco8_mon. apply H.\n    intros. destruct PR.\n    + left. apply INC. apply H0.\n    + right. apply H0.\nQed.\n\nLemma gpaco8_gpaco clo r rg:\n  gpaco8 clo (gpaco8 clo r rg) (gupaco8 clo (rg \\8/ r)) <8= gpaco8 clo r rg.\nProof.\n  intros. apply gpaco8_unfold in PR.\n  econstructor. apply rclo8_rclo. eapply rclo8_mon. apply PR. clear x0 x1 x2 x3 x4 x5 x6 x7 PR. intros.\n  destruct PR; [|destruct H; apply IN].\n  apply rclo8_base. left. pstep.\n  eapply gf_mon. apply H. clear x0 x1 x2 x3 x4 x5 x6 x7 H. intros.\n  cut (@gupaco8 clo (rg \\8/ r) x0 x1 x2 x3 x4 x5 x6 x7).\n  { intros. destruct H. eapply rclo8_mon. apply IN. intros.\n    destruct PR0; [|right; apply H].\n    left. eapply paco8_mon. apply H. intros. destruct PR0; apply H0.\n  }\n  apply gpaco8_gupaco. eapply gupaco8_mon. apply PR. intros.\n  destruct PR0; [apply H|].\n  eapply gpaco8_mon; [apply H|right|left]; intros; apply PR0.\nQed.\n\nLemma gpaco8_uclo uclo clo r rg \n      (LEclo: uclo <9= gupaco8 clo) :\n  uclo (gpaco8 clo r rg) <8= gpaco8 clo r rg.\nProof.\n  intros. apply gpaco8_gupaco. apply LEclo, PR.\nQed.\n\nLemma gpaco8_weaken  clo r rg:\n  gpaco8 (gupaco8 clo) r rg <8= gpaco8 clo r rg.\nProof.\n  intros. apply gpaco8_unfold in PR.\n  induction PR.\n  - destruct IN; cycle 1. apply gpaco8_base, H.\n    apply gpaco8_step_gen. eapply gf_mon. apply H.\n    clear x0 x1 x2 x3 x4 x5 x6 x7 H.\n    eapply gpaco8_cofix. intros.\n    apply gpaco8_unfold in PR.\n    induction PR.\n    + destruct IN; cycle 1. apply gpaco8_base, H.\n      apply gpaco8_step. eapply gf_mon. apply H.\n      intros. apply gpaco8_base. apply CIH.\n      eapply gupaco8_mon. apply PR.\n      intros. destruct PR0; apply H0.\n    + apply gpaco8_gupaco.\n      eapply gupaco8_mon. apply IN. apply H.\n  - apply gpaco8_gupaco.\n    eapply gupaco8_mon. apply IN. apply H.\nQed.\n\nEnd Main.\n\nHint Resolve gpaco8_def_mon : paco.\n\nSection GeneralMonotonicity.\n\nVariable gf: rel -> rel.\n  \nLemma gpaco8_mon_gen (gf' clo clo': rel -> rel) x0 x1 x2 x3 x4 x5 x6 x7 r r' rg rg'\n      (IN: @gpaco8 gf clo r rg x0 x1 x2 x3 x4 x5 x6 x7)\n      (gf_mon: monotone8 gf)\n      (LEgf: gf <9= gf')\n      (LEclo: clo <9= clo')\n      (LEr: r <8= r')\n      (LErg: rg <8= rg') :\n  @gpaco8 gf' clo' r' rg' x0 x1 x2 x3 x4 x5 x6 x7.\nProof.\n  eapply gpaco8_mon; [|apply LEr|apply LErg].\n  destruct IN. econstructor.\n  eapply rclo8_mon_gen. apply IN. apply LEclo.\n  intros. destruct PR; [| right; apply H].\n  left. eapply paco8_mon_gen. apply H.\n  - intros. eapply LEgf.\n    eapply gf_mon. apply PR.\n    intros. eapply rclo8_mon_gen. apply PR0. apply LEclo. intros; apply PR1.\n  - intros. apply PR.\nQed.\n\nLemma gpaco8_mon_bot (gf' clo clo': rel -> rel) x0 x1 x2 x3 x4 x5 x6 x7 r' rg'\n      (IN: @gpaco8 gf clo bot8 bot8 x0 x1 x2 x3 x4 x5 x6 x7)\n      (gf_mon: monotone8 gf)\n      (LEgf: gf <9= gf')\n      (LEclo: clo <9= clo'):\n  @gpaco8 gf' clo' r' rg' x0 x1 x2 x3 x4 x5 x6 x7.\nProof.\n  eapply gpaco8_mon_gen. apply IN. apply gf_mon. apply LEgf. apply LEclo. contradiction. contradiction.\nQed.\n\nLemma gupaco8_mon_gen (gf' clo clo': rel -> rel) x0 x1 x2 x3 x4 x5 x6 x7 r r'\n      (IN: @gupaco8 gf clo r x0 x1 x2 x3 x4 x5 x6 x7)\n      (gf_mon: monotone8 gf)\n      (LEgf: gf <9= gf')\n      (LEclo: clo <9= clo')\n      (LEr: r <8= r'):\n  @gupaco8 gf' clo' r' x0 x1 x2 x3 x4 x5 x6 x7.\nProof.\n  eapply gpaco8_mon_gen. apply IN. apply gf_mon. apply LEgf. apply LEclo. apply LEr. apply LEr.\nQed.\n\nEnd GeneralMonotonicity.\n\nSection Compatibility.\n\nVariable gf: rel -> rel.\nHypothesis gf_mon: monotone8 gf.\n\nStructure compatible8 (clo: rel -> rel) : Prop :=\n  compat8_intro {\n      compat8_mon: monotone8 clo;\n      compat8_compat : forall r,\n          clo (gf r) <8= gf (clo r);\n    }.\n\nStructure wcompatible8 clo : Prop :=\n  wcompat8_intro {\n      wcompat8_mon: monotone8 clo;\n      wcompat8_wcompat : forall r,\n          clo (gf r) <8= gf (gupaco8 gf clo r);\n    }.\n\nLemma rclo8_dist clo\n      (MON: monotone8 clo)\n      (DIST: forall r1 r2, clo (r1 \\8/ r2) <8= (clo r1 \\8/ clo r2)):\n  forall r1 r2, rclo8 clo (r1 \\8/ r2) <8= (rclo8 clo r1 \\8/ rclo8 clo r2).\nProof.\n  intros. induction PR.\n  + destruct IN; [left|right]; apply rclo8_base, H.\n  + assert (REL: clo (rclo8 clo r1 \\8/ rclo8 clo r2) x0 x1 x2 x3 x4 x5 x6 x7).\n    { eapply MON. apply IN. apply H. }\n    apply DIST in REL. destruct REL; [left|right]; apply rclo8_clo, H0.\nQed.\n\nLemma rclo8_compat clo\n      (COM: compatible8 clo):\n  compatible8 (rclo8 clo).\nProof.\n  econstructor.\n  - apply rclo8_mon.\n  - intros. induction PR.\n    + eapply gf_mon. apply IN.\n      intros. eapply rclo8_base. apply PR.\n    + eapply gf_mon.\n      * eapply COM. eapply COM. apply IN. apply H.\n      * intros. eapply rclo8_clo. apply PR.\nQed.\n\nLemma rclo8_wcompat clo\n      (COM: wcompatible8 clo):\n  wcompatible8 (rclo8 clo).\nProof.\n  econstructor.\n  - apply rclo8_mon.\n  - intros. induction PR.\n    + eapply gf_mon. apply IN.\n      intros. apply gpaco8_base. apply PR.\n    + eapply gf_mon.\n      * eapply COM. eapply COM. apply IN. apply H.\n      * intros. eapply gpaco8_gupaco. apply gf_mon.\n        eapply gupaco8_mon_gen; intros; [apply PR|apply gf_mon|apply PR0| |apply PR0].\n        eapply rclo8_clo'. apply rclo8_base. apply PR0.\nQed.\n\nLemma compat8_wcompat clo\n      (CMP: compatible8 clo):\n  wcompatible8 clo.\nProof.\n  econstructor. apply CMP.\n  intros. apply CMP in PR.\n  eapply gf_mon. apply PR.\n  intros. apply gpaco8_clo, PR0. \nQed.\n\nLemma wcompat8_compat clo\n      (WCMP: wcompatible8 clo) :\n  compatible8 (gupaco8 gf clo).\nProof.\n  econstructor.\n  { red; intros. eapply gpaco8_mon. apply IN. apply LE. apply LE. }\n\n  intros. apply gpaco8_unfold in PR; [|apply gf_mon].\n  induction PR.\n  - destruct IN; cycle 1.\n    + eapply gf_mon. apply H.\n      intros. apply gpaco8_base, PR.\n    + eapply gf_mon. apply H.\n      intros. apply gpaco8_gupaco. apply gf_mon.\n      eapply gupaco8_mon. apply PR.\n      intros. apply gpaco8_step. apply gf_mon.\n      eapply gf_mon. destruct PR0 as [X|X]; apply X.\n      intros. apply gpaco8_base, PR1.\n  - eapply gf_mon, gpaco8_gupaco, gf_mon.\n    apply WCMP. eapply WCMP. apply IN.\n    intros. apply H, PR.\nQed.\n\nLemma wcompat8_union clo1 clo2\n      (WCMP1: wcompatible8 clo1)\n      (WCMP2: wcompatible8 clo2):\n  wcompatible8 (clo1 \\9/ clo2).\nProof.\n  econstructor.\n  - apply monotone8_union. apply WCMP1. apply WCMP2.\n  - intros. destruct PR.\n    + apply WCMP1 in H. eapply gf_mon. apply H.\n      intros. eapply gupaco8_mon_gen. apply PR. apply gf_mon. \n      intros; apply PR0. left; apply PR0. intros; apply PR0.\n    + apply WCMP2 in H. eapply gf_mon. apply H.\n      intros. eapply gupaco8_mon_gen. apply PR. apply gf_mon.\n      intros; apply PR0. right; apply PR0. intros; apply PR0.\nQed.\n\nEnd Compatibility.\n\nSection Soundness.\n\nVariable gf: rel -> rel.\nHypothesis gf_mon: monotone8 gf.\n\nLemma gpaco8_compat_init clo\n      (CMP: compatible8 gf clo):\n  gpaco8 gf clo bot8 bot8 <8= paco8 gf bot8.\nProof.\n  intros. destruct PR. revert x0 x1 x2 x3 x4 x5 x6 x7 IN.\n  pcofix CIH. intros.\n  pstep. eapply gf_mon; [| right; apply CIH, rclo8_rclo, PR]. \n  apply compat8_compat with (gf:=gf). apply rclo8_compat. apply gf_mon. apply CMP.\n  eapply rclo8_mon. apply IN.\n  intros. destruct PR; [|contradiction]. _punfold H; [..|apply gpaco8_def_mon, gf_mon].\n  eapply gpaco8_def_mon. apply gf_mon. apply H.\n  intros. destruct PR; [|destruct H0; contradiction]. left. apply H0.\nQed.\n\nLemma gpaco8_init clo\n      (WCMP: wcompatible8 gf clo):\n  gpaco8 gf clo bot8 bot8 <8= paco8 gf bot8.\nProof.\n  intros. eapply gpaco8_compat_init.\n  - apply wcompat8_compat, WCMP. apply gf_mon.\n  - eapply gpaco8_mon_bot. apply PR. apply gf_mon. intros; apply PR0.\n    intros. apply gpaco8_clo, PR0.\nQed.\n\nLemma gpaco8_unfold_bot clo\n      (WCMP: wcompatible8 gf clo):\n  gpaco8 gf clo bot8 bot8 <8= gf (gpaco8 gf clo bot8 bot8).\nProof.\n  intros. apply gpaco8_init in PR; [|apply WCMP].\n  _punfold PR; [..|apply gf_mon].\n  eapply gf_mon. apply PR.\n  intros. destruct PR0; [|contradiction]. apply gpaco8_final. apply gf_mon. right. apply H.\nQed.\n\nEnd Soundness.\n\nSection Distributivity.\n\nVariable gf: rel -> rel.\nHypothesis gf_mon: monotone8 gf.\n\nLemma gpaco8_dist clo r rg\n      (CMP: wcompatible8 gf clo)\n      (DIST: forall r1 r2, clo (r1 \\8/ r2) <8= (clo r1 \\8/ clo r2)):\n  gpaco8 gf clo r rg <8= (paco8 gf (rclo8 clo (rg \\8/ r)) \\8/ rclo8 clo r).\nProof.\n  intros. apply gpaco8_unfold in PR; [|apply gf_mon].\n  apply rclo8_dist in PR; [|apply CMP|apply DIST].\n  destruct PR; [|right; apply H].\n  left. revert x0 x1 x2 x3 x4 x5 x6 x7 H.\n  pcofix CIH; intros.\n  apply rclo8_wcompat in H0; [|apply gf_mon|apply CMP].\n  pstep. eapply gf_mon. apply H0. intros.\n  apply gpaco8_unfold in PR; [|apply gf_mon].\n  apply rclo8_compose in PR.\n  apply rclo8_dist in PR; [|apply CMP|apply DIST].\n  destruct PR.\n  - right. apply CIH.\n    eapply rclo8_mon. apply H. intros.\n    eapply gf_mon. apply PR. intros.\n    apply gpaco8_gupaco. apply gf_mon.\n    apply gpaco8_gen_rclo. apply gf_mon.\n    eapply gupaco8_mon. apply PR0. intros.\n    destruct PR1; apply H1.\n  - assert (REL: @rclo8 clo (rclo8 clo (gf (gupaco8 gf clo ((rg \\8/ r) \\8/ (rg \\8/ r))) \\8/ (rg \\8/ r))) x0 x1 x2 x3 x4 x5 x6 x7).\n    { eapply rclo8_mon. apply H. intros. apply gpaco8_unfold in PR. apply PR. apply gf_mon. }\n    apply rclo8_rclo in REL.\n    apply rclo8_dist in REL; [|apply CMP|apply DIST].\n    right. destruct REL; cycle 1.\n    + apply CIH0, H1.\n    + apply CIH.\n      eapply rclo8_mon. apply H1. intros.\n      eapply gf_mon. apply PR. intros.\n      eapply gupaco8_mon. apply PR0. intros.\n      destruct PR1; apply H2.\nQed.\n\nLemma gpaco8_dist_reverse clo r rg:\n  (paco8 gf (rclo8 clo (rg \\8/ r)) \\8/ rclo8 clo r) <8= gpaco8 gf clo r rg.\nProof.\n  intros. destruct PR; cycle 1.\n  - eapply gpaco8_rclo. apply H.\n  - econstructor. apply rclo8_base. left.\n    revert x0 x1 x2 x3 x4 x5 x6 x7 H. pcofix CIH; intros.\n    _punfold H0; [|apply gf_mon]. pstep.\n    eapply gf_mon. apply H0. intros.\n    destruct PR.\n    + apply rclo8_base. right. apply CIH, H.\n    + eapply rclo8_mon. apply H. intros.\n      right. apply CIH0. apply PR.\nQed.\n\nEnd Distributivity.\n\nSection Companion.\n\nVariable gf: rel -> rel.\nHypothesis gf_mon: monotone8 gf.\n\nInductive cpn8 (r: rel) x0 x1 x2 x3 x4 x5 x6 x7 : Prop :=\n| cpn8_intro\n    clo\n    (COM: compatible8 gf clo)\n    (CLO: clo r x0 x1 x2 x3 x4 x5 x6 x7)\n.\n\nLemma cpn8_mon: monotone8 cpn8.\nProof.\n  red. intros.\n  destruct IN. exists clo.\n  - apply COM.\n  - eapply compat8_mon; [apply COM|apply CLO|apply LE].\nQed.\n\nLemma cpn8_greatest: forall clo (COM: compatible8 gf clo), clo <9= cpn8.\nProof. intros. econstructor;[apply COM|apply PR]. Qed.\n\nLemma cpn8_compat: compatible8 gf cpn8.\nProof.\n  econstructor; [apply cpn8_mon|intros].\n  destruct PR; eapply gf_mon with (r:=clo r).\n  - eapply (compat8_compat COM); apply CLO.\n  - intros. econstructor; [apply COM|apply PR].\nQed.\n\nLemma cpn8_wcompat: wcompatible8 gf cpn8.\nProof. apply compat8_wcompat, cpn8_compat. apply gf_mon. Qed.\n\nLemma cpn8_gupaco:\n  gupaco8 gf cpn8 <9= cpn8.\nProof.\n  intros. eapply cpn8_greatest, PR. apply wcompat8_compat. apply gf_mon. apply cpn8_wcompat.\nQed.\n\nLemma cpn8_cpn r:\n  cpn8 (cpn8 r) <8= cpn8 r.\nProof.\n  intros. apply cpn8_gupaco, gpaco8_gupaco, gpaco8_clo. apply gf_mon.\n  eapply cpn8_mon, gpaco8_clo. apply PR.\nQed.\n\nLemma cpn8_base r:\n  r <8= cpn8 r.\nProof.\n  intros. apply cpn8_gupaco. apply gpaco8_base, PR.\nQed.\n\nLemma cpn8_clo\n      r clo (LE: clo <9= cpn8):\n  clo (cpn8 r) <8= cpn8 r.\nProof.\n  intros. apply cpn8_cpn, LE, PR.\nQed.\n\nLemma cpn8_step r:\n  gf (cpn8 r) <8= cpn8 r.\nProof.\n  intros. apply cpn8_gupaco. apply gpaco8_step. apply gf_mon.\n  eapply gf_mon, gpaco8_clo. apply PR.\nQed.\n\nLemma cpn8_uclo uclo\n      (MON: monotone8 uclo)\n      (WCOM: forall r, uclo (gf r) <8= gf (gupaco8 gf (uclo \\9/ cpn8) r)):\n  uclo <9= gupaco8 gf cpn8.\nProof.\n  intros. apply gpaco8_clo.\n  exists (gupaco8 gf (uclo \\9/ cpn8)).\n  - apply wcompat8_compat. apply gf_mon.\n    econstructor.\n    + apply monotone8_union. apply MON. apply cpn8_mon.\n    + intros. destruct PR0.\n      * apply WCOM, H.\n      * apply compat8_compat with (gf:=gf) in H; [| apply cpn8_compat].\n        eapply gf_mon. apply H. intros.\n        apply gpaco8_clo. right. apply PR0.\n  - apply gpaco8_clo. left. apply PR.\nQed.\n\nEnd Companion.\n\nEnd GeneralizedPaco8.\n\nHint Resolve gpaco8_def_mon : paco.\nHint Unfold gupaco8 : paco.\nHint Resolve gpaco8_base : paco.\nHint Resolve gpaco8_step : paco.\nHint Resolve gpaco8_final : paco.\nHint Resolve rclo8_base : paco.\nHint Constructors gpaco8 : paco.\n", "meta": {"author": "YaZko", "repo": "Coinduction_tutorial", "sha": "880648f436bea472816fc6b5d30cb48818b2e0a1", "save_path": "github-repos/coq/YaZko-Coinduction_tutorial", "path": "github-repos/coq/YaZko-Coinduction_tutorial/Coinduction_tutorial-880648f436bea472816fc6b5d30cb48818b2e0a1/src/paco/src/gpaco8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2547684625947325}}
{"text": "From oadt.lang_oadt Require Import\n     base syntax semantics typing infrastructure\n     equivalence admissible inversion values preservation.\nImport syntax.notations semantics.notations typing.notations equivalence.notations.\n\nImplicit Types (b : bool) (x X y Y : atom) (L : aset).\n\n#[local]\nCoercion EFVar : atom >-> expr.\n\nSection fix_gctx.\n\nContext (Σ : gctx).\nContext (Hwf : gctx_wf Σ).\n\n#[local]\nSet Default Proof Using \"Hwf\".\n\n(** * Lemmas about obliviousness *)\n\nLemma pared_obliv_preservation_inv Γ τ τ' κ :\n  τ ⇛ τ' ->\n  Γ ⊢ τ :: κ ->\n  Γ ⊢ τ' :: *@O ->\n  Γ ⊢ τ :: *@O.\nProof.\n  induction 1; intros; try case_label;\n    kind_inv;\n    simpl_cofin?;\n    simplify_eq;\n    try solve [ kinding_intro; eauto; set_shelve ];\n    try easy.\n\n  Unshelve.\n  all : fast_set_solver!!.\nQed.\n\nLemma pared_equiv_obliv_preservation Γ τ τ' κ :\n  τ ≡ τ' ->\n  Γ ⊢ τ :: *@O ->\n  Γ ⊢ τ' :: κ ->\n  Γ ⊢ τ' :: *@O.\nProof.\n  induction 1; intros;\n    eauto using pared_obliv_preservation_inv, pared_kinding_preservation.\nQed.\n\nLemma wval_woval Γ v l τ :\n  Γ ⊢ v :{l} τ ->\n  Γ ⊢ τ :: *@O ->\n  wval v ->\n  woval v.\nProof.\n  induction 1; intros; try wval_inv; try oval_inv;\n    kind_inv; simplify_eq;\n      try hauto lq: on ctrs: woval, oval; try easy.\n\n  (* TConv *)\n  apply_regularity.\n  auto_apply; eauto.\n  eapply pared_equiv_obliv_preservation; eauto.\n  equiv_naive_solver.\nQed.\n\nLemma val_oval Γ v l τ :\n  Γ ⊢ v :{l} τ ->\n  Γ ⊢ τ :: *@O ->\n  val v ->\n  oval v.\nProof.\n  intros Ht Hk Hv.\n  pose proof Hv.\n  apply val_wval in Hv.\n  eapply wval_woval in Hv; eauto.\n  sinvert Hv; eauto. val_inv. oval_inv.\nQed.\n\n(** * Canonical forms *)\nLtac canonical_form_solver :=\n  inversion 1; intros; subst;\n  try select (oval _) (fun H => sinvert H);\n  eauto;\n  type_inv;\n  kind_inv;\n  try simpl_whnf_equiv;\n  simplify_eq;\n  eauto 10.\n\nLemma canonical_form_unit Γ l e :\n  val e ->\n  Γ ⊢ e :{l} 𝟙 ->\n  e = <{ () }>.\nProof.\n  canonical_form_solver.\nQed.\n\nLemma canonical_form_abs Γ l1 l2 e τ2 τ1 :\n  val e ->\n  Γ ⊢ e :{l1} Π:{l2}τ2, τ1 ->\n  exists e' τ, e = <{ \\:{l2}τ => e' }>.\nProof.\n  canonical_form_solver.\nQed.\n\nLemma canonical_form_bool Γ l e :\n  val e ->\n  Γ ⊢ e :{l} 𝔹 ->\n  exists b, e = <{ b }>.\nProof.\n  canonical_form_solver.\nQed.\n\nLemma canonical_form_obool Γ l e :\n  val e ->\n  Γ ⊢ e :{l} ~𝔹 ->\n  exists b, e = <{ [b] }>.\nProof.\n  canonical_form_solver.\nQed.\n\nLemma canonical_form_prod Γ l e τ1 τ2 :\n  val e ->\n  Γ ⊢ e :{l} τ1 * τ2 ->\n  exists v1 v2, val v1 /\\ val v2 /\\ e = <{ (v1, v2) }>.\nProof.\n  canonical_form_solver.\nQed.\n\nLemma canonical_form_oprod Γ l e τ1 τ2 :\n  val e ->\n  Γ ⊢ e :{l} τ1 ~* τ2 ->\n  exists v1 v2, oval v1 /\\ oval v2 /\\ e = <{ ~(v1, v2) }>.\nProof.\n  canonical_form_solver.\nQed.\n\nLemma canonical_form_sum Γ l e τ1 τ2 :\n  val e ->\n  Γ ⊢ e :{l} τ1 + τ2 ->\n  exists b v τ, val v /\\ e = <{ inj@b<τ> v }>.\nProof.\n  canonical_form_solver.\nQed.\n\nLemma canonical_form_osum Γ l e τ1 τ2 :\n  val e ->\n  Γ ⊢ e :{l} τ1 ~+ τ2 ->\n  exists b v ω1 ω2, oval v /\\ otval ω1 /\\ otval ω2 /\\\n               e = <{ [inj@b<ω1 ~+ ω2> v] }>.\nProof.\n  canonical_form_solver.\n\n  (* The cases when [e] is boxed injection. *)\n  otval_inv.\n  repeat esplit; auto.\nQed.\n\n(** Though it seems we should have a condition of [X] being an (public) ADT, this\ncondition is not needed since it is implied by the typing judgment. *)\nLemma canonical_form_fold Γ l e X :\n  val e ->\n  Γ ⊢ e :{l} gvar X ->\n  exists v X', val v /\\ e = <{ fold<X'> v }>.\nProof.\n  inversion 1; canonical_form_solver.\nQed.\n\n(** * Canonical forms for weak values *)\n\nLemma canonical_form_weak_unit Γ l e :\n  wval e ->\n  Γ ⊢ e :{l} 𝟙 ->\n  e = <{ () }> \\/\n  (exists b v1 v2, wval v1 /\\ wval v2 /\\ e = <{ ~if [b] then v1 else v2 }>).\nProof.\n  canonical_form_solver.\nQed.\n\nLemma canonical_form_weak_abs Γ l1 l2 e τ2 τ1 :\n  wval e ->\n  Γ ⊢ e :{l1} Π:{l2}τ2, τ1 ->\n  (exists e' τ, e = <{ \\:{l2}τ => e' }>) \\/\n  (exists b v1 v2, wval v1 /\\ wval v2 /\\ e = <{ ~if [b] then v1 else v2 }>).\nProof.\n  canonical_form_solver.\nQed.\n\nLemma canonical_form_weak_bool Γ l e :\n  wval e ->\n  Γ ⊢ e :{l} 𝔹 ->\n  (exists b, e = <{ b }>) \\/\n  (exists b v1 v2, wval v1 /\\ wval v2 /\\ e = <{ ~if [b] then v1 else v2 }>).\nProof.\n  canonical_form_solver.\nQed.\n\nLemma canonical_form_weak_prod Γ l e τ1 τ2 :\n  wval e ->\n  Γ ⊢ e :{l} τ1 * τ2 ->\n  (exists v1 v2, wval v1 /\\ wval v2 /\\ e = <{ (v1, v2) }>) \\/\n  (exists b v1 v2, wval v1 /\\ wval v2 /\\ e = <{ ~if [b] then v1 else v2 }>).\nProof.\n  canonical_form_solver.\nQed.\n\nLemma canonical_form_weak_sum Γ l e τ1 τ2 :\n  wval e ->\n  Γ ⊢ e :{l} τ1 + τ2 ->\n  (exists b v τ, wval v /\\ e = <{ inj@b<τ> v }>) \\/\n  (exists b v1 v2, wval v1 /\\ wval v2 /\\ e = <{ ~if [b] then v1 else v2 }>).\nProof.\n  canonical_form_solver.\nQed.\n\nLemma canonical_form_weak_fold Γ l e X :\n  wval e ->\n  Γ ⊢ e :{l} gvar X ->\n  (exists v X', wval v /\\ e = <{ fold<X'> v }>) \\/\n  (exists b v1 v2, wval v1 /\\ wval v2 /\\ e = <{ ~if [b] then v1 else v2 }>).\nProof.\n  inversion 1; canonical_form_solver.\nQed.\n\nEnd fix_gctx.\n\nLtac apply_canonical_form_lem τ :=\n  lazymatch τ with\n  | <{ 𝟙 }> => canonical_form_unit\n  | <{ ~𝔹 }> => canonical_form_obool\n  | <{ _ ~* _ }> => canonical_form_oprod\n  | <{ _ ~+ _ }> => canonical_form_osum\n  end.\n\nLtac apply_canonical_form :=\n  match goal with\n  | H : val ?e, H' : _; _ ⊢ ?e :{_} ?τ |- _ =>\n    let lem := apply_canonical_form_lem τ in\n    eapply lem in H; [ | solve [ eauto ] | solve [ eauto ] ]; try simp_hyp H\n  end; subst.\n\nLtac apply_canonical_form_weak_lem τ :=\n  lazymatch τ with\n  | <{ Π:{_}_, _ }> => canonical_form_weak_abs\n  | <{ 𝔹 }> => canonical_form_weak_bool\n  | <{ _ + _ }> => canonical_form_weak_sum\n  | <{ _ * _ }> => canonical_form_weak_prod\n  | <{ gvar _ }> => canonical_form_weak_fold\n  end.\n\nLtac apply_canonical_form_weak :=\n  match goal with\n  | Hw : wval ?e, Ht : _; _ ⊢ ?e :{⊥} ?τ |- _ =>\n      eapply wval_val in Hw; [ | solve [ eauto ] ];\n      apply_canonical_form\n  | Hw : wval ?e, Ht : _; _ ⊢ ?e :{_} ?τ |- _ =>\n      let lem := apply_canonical_form_weak_lem τ in\n      eapply lem in Hw; [ | solve [ eauto ] | solve [ eauto ] ];\n      destruct Hw; try simp_hyp Hw; subst\n  end.\n\n\nSection fix_gctx.\n\nContext (Σ : gctx).\nContext (Hwf : gctx_wf Σ).\n\n#[local]\nSet Default Proof Using \"Hwf\".\n\n(** * Progress *)\n\nLtac ctx_solver :=\n  match goal with\n  | |- exists _, _ ⊨ _ -->! _ =>\n    eexists; solve_ctx\n  end.\n\n(** The combined progress theorems for expressions and types. *)\nTheorem progress_ :\n  (forall Γ e l τ,\n      Γ ⊢ e :{l} τ ->\n      Γ = ∅ ->\n      wval e \\/ exists e', e -->! e') /\\\n  (forall Γ τ κ,\n     Γ ⊢ τ :: κ ->\n     Γ = ∅ ->\n     κ = <{ *@O }> ->\n     otval τ \\/ exists τ', τ -->! τ').\nProof.\n  eapply typing_kinding_mutind; intros; subst;\n    (* If a type is not used in the conclusion, the mutual inductive hypothesis\n    for it is useless. Remove this hypothesis to avoid slowdown the\n    automation. *)\n    try match goal with\n        | H : context [otval ?τ \\/ _] |- val ?e \\/ _ =>\n          assert_fails contains e τ; clear H\n        end;\n    simp_hyps; try case_label; simplify_map_eq; eauto;\n    (* Solve the trivial evaluation context step. *)\n    repeat\n      match reverse goal with\n      | H : otval _ \\/ exists _, _ |- _ =>\n          destruct H as [| [] ]; [ | solve [ right; ctx_solver ] ]\n      end;\n    repeat\n      match reverse goal with\n      | H : wval _ \\/ exists _, _ |- _ =>\n          destruct H as [| [] ]; [ | solve [ right; ctx_solver ] ]\n      end;\n    try apply_canonical_form_weak;\n    try solve [ right; eauto using step, wval; ctx_solver\n              | left; eauto using wval, oval, otval ].\n\n  (* Oblivious injection. It steps to boxed injection. *)\n  right. otval_inv.\n  repeat econstructor; eauto.\n  case_split; eauto using otval_well_kinded, val_oval, wval_val.\n\n  (* Oblivious case. *)\n  right.\n  select! (otval _) (fun H => use (ovalty_inhabited _ H)).\n  eauto using step.\n\n  (* Oblivious pair. *)\n  left. eauto 10 using wval, oval, val_oval, wval_val.\n\n  (* Tape. *)\n  right.\n  hauto use: wval_woval ctrs: step inv: woval.\n\n  (* Boxed injection. *)\n  left. qauto use: ovalty_elim ctrs: wval.\n\n  (* Public product and sum. These case are impossible. *)\n  1-2:  enough (<{ *@P }> ⊑ <{ *@O }>) by easy; scongruence use: join_ub_r.\n\n  (* Kinding subsumption *)\n  select kind (fun κ => destruct κ); sintuition use: any_kind_otval.\nQed.\n\nTheorem progress_weak l τ e :\n  ∅ ⊢ e :{l} τ ->\n  wval e \\/ exists e', e -->! e'.\nProof.\n  hauto use: progress_.\nQed.\n\nTheorem progress τ e :\n  ∅ ⊢ e :{⊥} τ ->\n  val e \\/ exists e', e -->! e'.\nProof.\n  hauto use: progress_, wval_val.\nQed.\n\nTheorem kinding_progress τ :\n  ∅ ⊢ τ :: *@O ->\n  otval τ \\/ exists τ', τ -->! τ'.\nProof.\n  hauto use: progress_.\nQed.\n\nEnd fix_gctx.\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/progress.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771035, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2547684555940158}}
{"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 RmiAux.Spec.\n\nLocal Open Scope Z_scope.\n\nSection SpecLow.\n\n  Definition realm_create_ops_spec0  (adt: RData) : option RData :=\n    when'' _g_rd_base, _g_rd_ofst == get_locked_granule_spec 0 adt;\n    rely is_int _g_rd_ofst;\n    when'' _g_rtt_base, _g_rtt_ofst == get_locked_granule_spec 1 adt;\n    rely is_int _g_rtt_ofst;\n    when'' _g_rec_list_base, _g_rec_list_ofst == get_locked_granule_spec 2 adt;\n    rely is_int _g_rec_list_ofst;\n    when adt == set_g_rtt_rd_spec (_g_rtt_base, _g_rtt_ofst) (_g_rd_base, _g_rd_ofst) adt;\n    when adt == granule_set_state_spec (_g_rtt_base, _g_rtt_ofst) 5 adt;\n    when adt == granule_unlock_spec (_g_rtt_base, _g_rtt_ofst) adt;\n    when adt == granule_set_state_spec (_g_rec_list_base, _g_rec_list_ofst) 6 adt;\n    when adt == granule_unlock_spec (_g_rec_list_base, _g_rec_list_ofst) adt;\n    when'' _rd_base, _rd_ofst, adt == granule_map_spec (_g_rd_base, _g_rd_ofst) 2 adt;\n    rely is_int _rd_ofst;\n    when adt == granule_set_state_spec (_g_rd_base, _g_rd_ofst) 2 adt;\n    when adt == set_rd_state_spec (_rd_base, _rd_ofst) 0 adt;\n    when' _base == get_realm_params_par_base_spec  adt;\n    rely is_int64 _base;\n    when' _size == get_realm_params_par_size_spec  adt;\n    rely is_int64 _size;\n    when adt == set_rd_par_base_spec (_rd_base, _rd_ofst) (VZ64 _base) adt;\n    rely is_int64 (_base + _size);\n    when adt == set_rd_par_end_spec (_rd_base, _rd_ofst) (VZ64 (_base + _size)) adt;\n    when adt == set_rd_g_rtt_spec (_rd_base, _rd_ofst) (_g_rtt_base, _g_rtt_ofst) adt;\n    when adt == set_rd_g_rec_list_spec (_rd_base, _rd_ofst) (_g_rec_list_base, _g_rec_list_ofst) adt;\n    when' _algo == get_realm_params_measurement_algo_spec  adt;\n    rely is_int64 _algo;\n    if (_algo =? 1) then\n      when adt == set_rd_measurement_algo_spec (_rd_base, _rd_ofst) (VZ64 _algo) adt;\n      when adt == measurement_start_spec (_rd_base, _rd_ofst) adt;\n      when adt == buffer_unmap_spec (_rd_base, _rd_ofst) adt;\n      when adt == granule_unlock_spec (_g_rd_base, _g_rd_ofst) adt;\n      Some adt\n    else\n      when adt == set_rd_measurement_algo_spec (_rd_base, _rd_ofst) (VZ64 0) adt;\n      when adt == measurement_start_spec (_rd_base, _rd_ofst) adt;\n      when adt == buffer_unmap_spec (_rd_base, _rd_ofst) adt;\n      when adt == granule_unlock_spec (_g_rd_base, _g_rd_ofst) adt;\n      Some adt\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/RmiOps/LowSpecs/realm_create_ops.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2546923271429772}}
{"text": "From iris.algebra Require Export big_op.\nFrom iris.bi Require Export big_op.\nFrom iris.proofmode Require Export tactics.\nFrom iris.proofmode Require Import reduction coq_tactics intro_patterns.\nFrom iris.prelude Require Import options.\n\nSection list.\n  Context {PROP : bi}.\n  Implicit Types (P Q : PROP).\n  Implicit Types (A : Type).\n\n  Lemma big_sepL_mono_with_inv' {A} P Φ Ψ (m: list A) n :\n    (∀ k x, m !! k = Some x → P ∗ Φ (k + n) x ⊢ P ∗ Ψ (k + n) x) →\n    P ∗ ([∗ list] k ↦ x ∈ m, Φ (k + n) x) ⊢ P ∗ [∗ list] k ↦ x ∈ m, Ψ (k + n) x.\n  Proof.\n    revert n.\n    induction m as [|a m] => n Hwand //=.\n    - iIntros \"(HP&HΦ&Hl)\".\n      iDestruct (Hwand 0 a with \"[HP HΦ]\") as \"(HP&HΨ)\"; eauto.\n      { rewrite Nat.add_0_l. iFrame. }\n      rewrite ?Nat.add_0_l.\n      iFrame \"HΨ\".\n      setoid_rewrite <-Nat.add_succ_r.\n      iApply (IHm with \"[$ ]\"); eauto.\n      intros; eauto.\n      specialize (Hwand (S k)).\n      rewrite Nat.add_succ_r -Nat.add_succ_l. iApply Hwand; eauto.\n  Qed.\n\n  Lemma big_sepL_mono_with_fupd_inv' {A} `{!BiFUpd PROP} E P Φ Ψ (m: list A) n :\n    (∀ k x, m !! k = Some x → P ∗ Φ (k + n) x ={E}=∗ P ∗ Ψ (k + n) x) →\n    P ∗ ([∗ list] k ↦ x ∈ m, Φ (k + n) x) ={E}=∗ P ∗ [∗ list] k ↦ x ∈ m, Ψ (k + n) x.\n  Proof.\n    revert n.\n    induction m as [|a m] => n Hwand //=.\n    - by iIntros \"($&_)\". \n    - iIntros \"(HP&HΦ&Hl)\".\n      iMod (Hwand 0 a with \"[HP HΦ]\") as \"(HP&HΨ)\"; eauto.\n      { rewrite Nat.add_0_l. iFrame. }\n      rewrite ?Nat.add_0_l.\n      iFrame \"HΨ\".\n      setoid_rewrite <-Nat.add_succ_r.\n      iApply (IHm with \"[$ ]\"); eauto.\n      intros; eauto.\n      specialize (Hwand (S k)).\n      rewrite Nat.add_succ_r -Nat.add_succ_l. iApply Hwand; eauto.\n  Qed.\n\n  Lemma big_sepL_mono_with_fupd_inv {A} `{!BiFUpd PROP} E P Φ Ψ (m: list A) :\n    (∀ k x, m !! k = Some x → P ∗ Φ k x ={E}=∗ P ∗ Ψ k x) →\n    P -∗ ([∗ list] k ↦ x ∈ m, Φ k x) ={E}=∗ P ∗ [∗ list] k ↦ x ∈ m, Ψ k x.\n  Proof.\n    iIntros (?) \"HP H\".\n    iPoseProof (big_sepL_mono_with_fupd_inv' E P Φ Ψ _ O with \"[HP H]\") as \"H\";\n    setoid_rewrite Nat.add_0_r; eauto; iFrame.\n  Qed.\n\n  Lemma big_sepL_mono_with_inv {A} P Φ Ψ (m: list A) :\n    (∀ k x, m !! k = Some x → P ∗ Φ k x ⊢ P ∗ Ψ k x) →\n    P -∗ ([∗ list] k ↦ x ∈ m, Φ k x) -∗ P ∗ [∗ list] k ↦ x ∈ m, Ψ k x.\n  Proof.\n    iIntros (?) \"HP H\".\n    iPoseProof (big_sepL_mono_with_inv' P Φ Ψ _ O with \"[HP H]\") as \"H\";\n    setoid_rewrite Nat.add_0_r; eauto; iFrame.\n  Qed.\nEnd list.\n\nSection list2.\n  Context {A B : Type}.\n  Context {PROP : bi}.\n  Implicit Types Φ Ψ : nat → A → B → PROP.\n\n  Lemma big_sepL2_mono_with_fupd_inv E (P: PROP) `{!BiAffine PROP, !BiFUpd PROP} (Φ Ψ: nat → A → B → PROP) l1 l2:\n    (∀ k x y, l1 !! k = Some x → l2 !! k = Some y → P ∗ Φ k x y ={E}=∗ P ∗ Ψ k x y) →\n    P -∗ ([∗ list] k ↦ x;y ∈ l1;l2, Φ k x y) ={E}=∗ P ∗ [∗ list] k ↦ x;y ∈ l1;l2, Ψ k x y.\n  Proof.\n    iIntros (Himpl) \"HP\".\n    rewrite ?big_sepL2_alt.\n    iIntros \"(%&Hwand)\".\n    iPoseProof (big_sepL_mono_with_fupd_inv E P (λ k ab, Φ k (fst ab) (snd ab))\n                                      (λ k ab, Ψ k (fst ab) (snd ab)) with \"HP Hwand\") as \"H\".\n    { intros k x Hlookup. eapply Himpl; eauto.\n      - rewrite -(fst_zip l1 l2); last lia.\n        rewrite list_lookup_fmap Hlookup //=.\n      - rewrite -(snd_zip l1 l2); last lia.\n        rewrite list_lookup_fmap Hlookup //=.\n    }\n    iMod \"H\" as \"($&$)\". eauto.\n  Qed.\n\n  Lemma big_sepL2_mono_with_inv (P: PROP) `{!BiAffine PROP} (Φ Ψ: nat → A → B → PROP) l1 l2:\n    (∀ k x y, l1 !! k = Some x → l2 !! k = Some y → P ∗ Φ k x y ⊢ P ∗ Ψ k x y) →\n    P -∗ ([∗ list] k ↦ x;y ∈ l1;l2, Φ k x y) -∗ P ∗ [∗ list] k ↦ x;y ∈ l1;l2, Ψ k x y.\n  Proof.\n    iIntros (Himpl) \"HP\".\n    rewrite ?big_sepL2_alt.\n    iIntros \"(%&Hwand)\".\n    iPoseProof (big_sepL_mono_with_inv P (λ k ab, Φ k (fst ab) (snd ab))\n                                      (λ k ab, Ψ k (fst ab) (snd ab)) with \"HP Hwand\") as \"H\".\n    { intros k x Hlookup. eapply Himpl; eauto.\n      - rewrite -(fst_zip l1 l2); last lia.\n        rewrite list_lookup_fmap Hlookup //=.\n      - rewrite -(snd_zip l1 l2); last lia.\n        rewrite list_lookup_fmap Hlookup //=.\n    }\n    iDestruct \"H\" as \"($&$)\". eauto.\n  Qed.\nEnd list2.\n", "meta": {"author": "jtassarotti", "repo": "iris-inv-hierarchy", "sha": "b25fe890d72ecb5bafa9db422ece3939d99882ab", "save_path": "github-repos/coq/jtassarotti-iris-inv-hierarchy", "path": "github-repos/coq/jtassarotti-iris-inv-hierarchy/iris-inv-hierarchy-b25fe890d72ecb5bafa9db422ece3939d99882ab/iris/bi/big_op_extra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2546923216327976}}
{"text": "Require Import msl.msl_standard.\nRequire Import msl.cjoins.\nRequire Import msl.Coqlib2.\nRequire Import msl.sepalg_list.\nRequire Import veric.shares.\nRequire Import veric.rmaps.\n\nModule Rmaps_Lemmas (R: RMAPS).\nModule R := R.\nImport R.\n\nHint Resolve (@subp_sepcon _ Join_rmap Perm_rmap Sep_rmap): contractive.\n\n Lemma approx_p  : forall (p:pred rmap) n w, approx n p w -> p w.\n Proof. unfold approx; simpl; intuition. Qed.\n\n Lemma approx_lt : forall (p:pred rmap) n w, lt (level w) n -> p w -> approx n p w.\n Proof. unfold approx; simpl; intuition. Qed.\n\n Lemma approx_ge : forall p n w, ge (level w) n -> approx n p w -> False.\n Proof. unfold approx; intros. destruct H0; auto. omega. Qed.\n\n  Lemma ageN_level : forall n (phi1 phi2 : rmap),\n    ageN n phi1 = Some phi2 -> level phi1 = (n + (level phi2))%nat.\n  Proof.\n    unfold ageN; induction n; simpl; intros.\n    injection H; intros; subst; auto.\n    revert H.\n    repeat rewrite rmap_level_eq in *.\n    intros. invSome.\n    specialize (IHn _ _ H2).\n    apply  age_level in H.  rewrite rmap_level_eq in *. omega.\n  Qed.\n\nLemma NO_identity: forall nsh, identity (NO Share.bot nsh).\nProof.\n  unfold identity; intros.\n  inv H;\n  apply join_unit1_e in RJ; auto;   subst sh3; repeat proof_irr; auto.\nQed.\n\nLemma PURE_identity: forall k pds, identity (PURE k pds).\nProof.\n  unfold identity; intros.\n  inv H; auto.\nQed.\n\nLemma identity_NO:\n  forall r, identity  r -> r = NO Share.bot bot_unreadable \\/ exists k, exists pds, r = PURE k pds.\nProof.\n  destruct r; auto; intros.\n * left.\n  apply identity_unit_equiv in H. inv H.\n  apply identity_unit_equiv in RJ. apply identity_share_bot in RJ. subst.\n  f_equal. apply proof_irr.\n * apply identity_unit_equiv in H. inv H.\n   apply unit_identity in RJ. apply identity_share_bot in RJ. subst.\n   contradiction bot_unreadable.\n * right. exists k. exists p. trivial.\nQed.\n\nLemma age1_resource_at_identity:\n  forall phi phi' loc, age1 phi = Some phi' ->\n               (identity (phi@loc) <-> identity (phi'@loc)).\nProof.\n split; intro.\n (* FORWARD DIRECTION *)\n  generalize (identity_NO _ H0); clear H0; intro.\n  unfold resource_at in *.\n  rewrite rmap_age1_eq in *.\n  revert H H0; case_eq (unsquash phi); simpl; intros.\n  destruct n; inv H0.\n  rewrite unsquash_squash.\n  simpl.\n  destruct r. simpl in *.\n  unfold compose; simpl. destruct H1 as [H1 | [k [pds H1]]]; rewrite H1; simpl; auto.\n  apply NO_identity.\n  apply PURE_identity.\n (* BACKWARD DIRECTION *)\n  generalize (identity_NO _ H0); clear H0; intro.\n  unfold resource_at in *. simpl in H.\n  rewrite rmap_age1_eq in H.\n  revert H H0; case_eq (unsquash phi); simpl; intros.\n  destruct n; inv H0.\n  rewrite unsquash_squash in H1. destruct r. simpl in *.\n  unfold compose in H1; simpl in H1.\n  unfold resource_fmap in H1.\n  destruct (x loc).\n  destruct H1. inv H0;   apply NO_identity. destruct H0 as [? [? H0]]; inv H0.\n  destruct H1 as [H1 | [k' [pds' H1]]]; inv H1.\n  apply PURE_identity.\nQed.\n\nLemma necR_resource_at_identity:\n  forall phi phi' loc, necR phi phi' ->\n         identity (phi@loc) ->\n         identity (phi'@loc).\nProof.\n  induction 1; auto.\n  intro.\n apply -> (age1_resource_at_identity _ _ loc H); auto.\nQed.\n\nLemma make_rmap': forall f, AV.valid (fun l => res_option (f l)) ->\n          exists phi: rmap', proj1_sig phi = f.\nProof.\n  intros.\n  unfold rmap'.\n  exists (exist valid f H).\n  auto.\nQed.\n\n\nLemma make_rmap (f: AV.address -> resource) (V: AV.valid (res_option oo f))\n    (n: nat) (H: resource_fmap (approx n) (approx n) oo f = f) :\n  {phi: rmap | level phi = n /\\ resource_at phi = f}.\nProof.\nintros.\napply (exist _ (squash (n, @exist (AV.address -> resource) R.valid f V))).\nsimpl level; rewrite rmap_level_eq in *; unfold resource_at. rewrite unsquash_squash.\nsimpl; auto.\nQed.\n\nLemma make_rmap'':\n    forall n (f: AV.address -> resource) ,\n      AV.valid (fun l => res_option (f l)) ->\n      exists phi:rmap, level phi = n /\\ resource_at phi = resource_fmap (approx n) (approx n) oo f.\n  Proof.\n    intros.\n    exists (squash (n, exist valid f H)).\n    rewrite rmap_level_eq.\n      unfold resource_at; rewrite unsquash_squash; simpl; split; auto.\nQed.\n\nLemma approx_oo_approx':\n  forall n n', (n' >= n)%nat -> approx n oo approx n' = approx n.\nProof.\nunfold compose; intros.\nextensionality P.\n apply pred_ext; intros w ?; unfold approx; simpl in *; intuition.\nQed.\n\nLemma approx'_oo_approx:\n  forall n n', (n' >= n)%nat -> approx n' oo approx n = approx n.\nProof.\nunfold compose; intros.\nextensionality P.\n apply pred_ext; intros w ?; unfold approx; simpl in *; intuition.\nQed.\n\nLemma approx_oo_approx: forall n, approx n oo approx n = approx n.\nProof.\nintros; apply approx_oo_approx'; omega.\nQed.\n\nLemma resources_same_level:\n   forall f phi,\n     (forall l : AV.address, join_sub (f l) (phi @ l)) ->\n        resource_fmap (approx (level phi)) (approx (level phi)) oo f = f.\nProof.\n  intros.\n  rewrite rmap_level_eq.\n  unfold resource_fmap, resource_at in *.\n  unfold compose; extensionality l. spec H l.\n  destruct H as [g ?].\n  revert H; case_eq (unsquash phi); intros n ? ?.\n  generalize H; rewrite <- (squash_unsquash phi).\n  rewrite H. rewrite unsquash_squash.\n  simpl; intros.\n  injection H0. clear H0. intro.\n  clear phi H.\n  rewrite <- H0 in H1.\n  clear H0.\n  unfold rmap_fmap in *.\n  destruct r.\n  simpl in *.\n  revert H1.\n  unfold resource_fmap, compose.\n  destruct (f l); destruct g; destruct (x l); simpl; intro; auto; inv H1.\n  change (preds_fmap (approx n) (approx n) (preds_fmap (approx n) (approx n) p0))\n  with ((preds_fmap (approx n) (approx n) oo preds_fmap (approx n) (approx n)) p0).\n  rewrite preds_fmap_comp.\n  rewrite approx_oo_approx; auto.\n  change (preds_fmap (approx n) (approx n) (preds_fmap (approx n) (approx n) p1))\n  with ((preds_fmap (approx n) (approx n) oo preds_fmap (approx n) (approx n)) p1).\n  rewrite preds_fmap_comp.\n  rewrite approx_oo_approx; auto.\n  change (preds_fmap (approx n) (approx n) (preds_fmap (approx n) (approx n) p1))\n  with ((preds_fmap (approx n) (approx n) oo preds_fmap (approx n) (approx n)) p1).\n  rewrite preds_fmap_comp.\n  rewrite approx_oo_approx; auto.\nQed.\n\nLemma deallocate:\n  forall (phi: rmap) (f g : AV.address -> resource),\n  AV.valid (res_option oo f) -> AV.valid (res_option oo g) ->\n  (forall l, join  (f l) (g l) (phi@l)) ->\n   exists phi1, exists phi2,\n     join phi1 phi2 phi /\\ resource_at phi1 = f.\nProof.\n  intros until g. intros Hf Hg H0.\n  generalize (resources_same_level f phi); intro.\n  spec H. intro; econstructor; apply H0.\n  generalize (resources_same_level g phi); intro.\n  spec H1.\n  intro. econstructor; eapply join_comm; eauto.\n  generalize (make_rmap'' (level phi) f Hf); intros [phif [? Gf]].\n  generalize (make_rmap'' (level phi) g Hg); intros [phig [? Gg]].\n  exists phif; exists phig.\n  split.\n  rewrite rmap_level_eq in *.\n  unfold resource_at in *.\n  revert H0 H Gf H1 Gg H2 H3;\n  case_eq (unsquash phif); intros nf phif' ?.\n  case_eq (unsquash phig); intros ng phig' ?.\n  case_eq (unsquash phi); intros n phi' ?.\n  simpl.\n  intros; subst nf ng.\n  rewrite join_unsquash.\n  rewrite H; rewrite H0; rewrite H1.\n  rewrite <- H1.\n  revert H1; case_eq (unsquash phi); intros n' phi'' ?.\n  intros.\n  inversion H5.\n  simpl.\n  split.\n  simpl; constructor; auto.\n  subst n' phi''.\n  intro l; spec H2 l.\n  simpl.\n  rewrite Gf; rewrite Gg; clear Gf Gg.\n  rewrite H3; rewrite H4.\n  auto.\n  rewrite Gf.\n  auto.\nQed.\n\nLemma allocate:\n     forall (phi : rmap) (f : AV.address -> resource),\n     AV.valid (res_option oo f) ->\n        resource_fmap (approx (level phi)) (approx (level phi)) oo f = f ->\n       (forall l, {r' | join (phi@l) (f l) r'}) ->\n       exists phi1 : rmap,\n         exists phi2 : rmap,\n           join phi phi1 phi2 /\\ resource_at phi1 = f.\nProof.\n intros. rename X into H1.\n generalize (make_rmap'' (level phi) f H); intros [phif [? Gf]].\n pose (g loc := proj1_sig (H1 loc)).\n assert (H3: forall l, join (phi @ l) (f l) (g l))\n   by (unfold g; intro; destruct (H1 l); simpl in *; auto).\n clearbody g.\n generalize (make_rmap'' (level phi) g); intro.\n spec H4. {\n   assert (AV.valid (fun l => res_option (phi @ l))).\n     clear.\n     unfold resource_at.\n     case_eq (unsquash phi); intros.\n     simpl.\n     destruct r. simpl.\n     apply v.\n   eapply AV.valid_join. 2: apply H5. 2: apply H.\n   clear - H3.\n    unfold compose.\n   intro l; spec H3 l.\n   destruct (phi @ l); simpl in *.\n   *\n   inv H3; simpl. constructor; auto.\n   apply join_comm in RJ.\n   erewrite (join_readable_part_eq) by eassumption. constructor.\n   *\n    inv H3; simpl.\n   erewrite (join_readable_part_eq) by eassumption. constructor.\n   constructor.\n   constructor. simpl.\n   apply join_readable_part; auto. simpl. constructor; auto.\n   *    \n   inv H3; constructor; auto.\n  }\n destruct H4 as [phig [? ?]].\n exists phif; exists phig.\n split.\n 2: congruence.\n rewrite join_unsquash.\n unfold resource_at in *.\n rewrite rmap_level_eq in *.\n revert H0 H1 H2 H3 H4 H5 Gf.\n case_eq (unsquash phif); intros nf phif' ?.\n case_eq (unsquash phig); intros ng phig' ?.\n case_eq (unsquash phi); intros n phi' ?.\n simpl.\n intros; subst nf ng.\n split. split; trivial.\n simpl.\n intro l.\n spec H6 l.\n assert (proj1_sig phig' l = g l).\n   generalize (f_equal squash H2); intro.\n   rewrite squash_unsquash in H5.\n   subst phi.\n   rewrite unsquash_squash in H2.\n   injection H2; clear H2; intro.\n   rewrite <- H2 in H6.\n   rewrite <- H3 in H6.\n   rewrite H8.\n   clear - H6.\n   revert H6.\n   unfold rmap_fmap, compose, resource_fmap.\n   destruct phi'; simpl.\n   destruct (x l); destruct (f l); destruct (g l); simpl; intros; auto; try inv H6;\n              try change (preds_fmap (approx n) (approx n) (preds_fmap (approx n) (approx n) p0)) with\n                ((preds_fmap (approx n) (approx n) oo preds_fmap (approx n) (approx n)) p0);\n              try change (preds_fmap (approx n) (approx n) (preds_fmap (approx n) (approx n) p)) with\n                ((preds_fmap (approx n) (approx n) oo preds_fmap (approx n) (approx n)) p);\n                rewrite preds_fmap_comp; rewrite approx_oo_approx; auto.\n rewrite H5.\n rewrite Gf.\n rewrite H3.\n auto.\nQed.\n\n  Lemma unsquash_inj : forall x y,\n      unsquash x = unsquash y -> x = y.\n  Proof.\n    intros.\n    rewrite <- (squash_unsquash x).\n    rewrite <- (squash_unsquash y).\n    rewrite H; auto.\n  Qed.\n\n  Lemma rmap_ext: forall phi1 phi2,\n    level phi1 = level phi2 ->\n    (forall l, phi1@l = phi2@l) ->\n    phi1=phi2.\n  Proof.\n    intros.\n    apply unsquash_inj.\n    rewrite rmap_level_eq in *.\n    unfold resource_at in *.\n    rewrite <- (squash_unsquash phi1).\n    rewrite <- (squash_unsquash phi2).\n    destruct (unsquash phi1).\n    destruct (unsquash phi2).\n    simpl in H.\n    rewrite H.\n    rewrite unsquash_squash.\n    rewrite unsquash_squash.\n    simpl in H0.\n    replace (rmap_fmap (approx n0) (approx n0) r) with (rmap_fmap (approx n0) (approx n0) r0); auto.\n    destruct r; destruct r0.\n    simpl in *.\n    generalize (valid_res_map (approx n0) (approx n0) x0 v0).\n    generalize (valid_res_map (approx n0) (approx n0) x v).\n    replace (resource_fmap (approx n0) (approx n0) oo x0)\n      with (resource_fmap (approx n0) (approx n0) oo x).\n    intros v1 v2; replace v2 with v1 by apply proof_irr; auto.\n    extensionality l.\n    unfold compose.\n    spec H0 l.\n    subst n0.\n    rewrite H0; auto.\n  Qed.\n\n  Lemma resource_at_join:\n    forall phi1 phi2 phi3 loc,\n      join phi1 phi2 phi3 ->\n      join (phi1@loc) (phi2@loc) (phi3@loc).\n  Proof.\n    intros.\n    revert H; rewrite join_unsquash; unfold resource_at.\n    intros [? ?].\n    apply H0.\n  Qed.\n\n  Lemma resource_at_join2:\n    forall phi1 phi2 phi3,\n      level phi1 = level phi3 -> level phi2 = level phi3 ->\n      (forall loc, join (phi1@loc) (phi2@loc) (phi3@loc)) ->\n      join phi1 phi2 phi3.\n  Proof.\n    intros ? ? ?.\n    rewrite join_unsquash.\n    rewrite rmap_level_eq in *.\n    unfold resource_at.\n    case_eq (unsquash phi1); case_eq (unsquash phi2); case_eq (unsquash phi3); simpl; intros.\n    subst.\n    split; auto.\n  Qed.\n\nLemma all_resource_at_identity:\n  forall w, (forall l, identity (w@l)) ->\n         identity w.\nProof.\n  intros.\n  rewrite identity_unit_equiv.\n  apply join_unsquash.\n  split. split; auto.\n  revert H. unfold resource_at.\n  case_eq (unsquash w); simpl; intros.\n  intro a. spec H0 a.\n  rewrite identity_unit_equiv in H0.\n  trivial.\nQed.\n\n  Lemma ageN_squash : forall d n rm, le d n ->\n    ageN d (squash (n, rm)) = Some (squash ((n - d)%nat, rm)).\n  Proof.\n    induction d; simpl; intros.\n    unfold ageN; simpl.\n    replace (n-0)%nat with n by omega; auto.\n    unfold ageN; simpl.\n    rewrite rmap_age1_eq in *.\n    rewrite unsquash_squash.\n    destruct n.\n    inv H.\n    replace (S n - S d)%nat with (n - d)%nat by omega.\n    unfold ageN in IHd. rewrite rmap_age1_eq in IHd.\n    rewrite IHd.\n    2: omega.\n    f_equal.\n    apply unsquash_inj.\n    rewrite !unsquash_squash.\n    f_equal.\n    change (rmap_fmap (approx (n - d)) (approx (n - d))\n             (rmap_fmap (approx (S n)) (approx (S n)) rm)) with\n           ((rmap_fmap (approx (n - d)) (approx (n - d)) oo\n              rmap_fmap (approx (S n)) (approx (S n))) rm).\n    rewrite rmap_fmap_comp.\n    f_equal.\n    + clear.\n      assert (n-d <= (S n))%nat by omega.\n      revert H; generalize (n-d)%nat (S n).\n      clear.\n      intros.\n      extensionality p.\n      apply pred_ext'.  extensionality w.\n      unfold compose, approx.\n      apply prop_ext; simpl; intuition.\n    + clear.\n      assert (n-d <= (S n))%nat by omega.\n      revert H; generalize (n-d)%nat (S n).\n      clear.\n      intros.\n      extensionality p.\n      apply pred_ext'.  extensionality w.\n      unfold compose, approx.\n      apply prop_ext; simpl; intuition.\n  Qed.\n\n  Lemma unageN: forall n (phi': rmap),   exists phi, ageN n phi = Some phi'.\n  Proof.\n    intros n phi'.\n    rewrite <- (squash_unsquash phi').\n    destruct (unsquash phi'); clear phi'.\n    exists (squash ((n+n0)%nat,r)).\n    rewrite ageN_squash.\n    replace (n + n0 - n)%nat with n0 by omega; auto.\n    omega.\n  Qed.\n\nLemma YES_join_full: \n   forall sh rsh n P r2 r3,\n       join (R.YES sh rsh n P) r2 r3 ->\n       writable_share sh ->\n       exists sh2 rsh2, r2 = NO sh2 rsh2.\nProof.\n  intros.\n  inv H. eauto.\n  elimtype False; clear - RJ H0 rsh2.\n  destruct RJ.\n  destruct H0. destruct H0. destruct rsh2. subst sh sh3.\n  rewrite Share.glb_commute, Share.distrib1 in H.\n  rewrite Share.glb_commute.\n  apply lub_bot_e in H. destruct H. rewrite H. apply bot_identity.\nQed.\n\n\nLemma YES_not_identity:\n  forall sh rsh k Q, ~ identity (YES sh rsh k Q).\nProof.\nintros. intro.\nrewrite identity_unit_equiv in H.\nunfold unit_for in H.\ninv H.\napply share_self_join_bot in RJ; subst.\napply bot_unreadable in rsh. auto.\nQed.\n\nLemma YES_overlap:\nforall sh0 rsh0 sh1 rsh1 (phi0 phi1: rmap) loc k k' p p',\n  joins phi0 phi1 ->\n  phi1@loc = R.YES sh1 rsh1 k p -> \n  writable_share sh1 ->\n  phi0@loc = R.YES sh0 rsh0 k' p' ->\n  False.\nProof.\n  intros.\n  destruct H as [phi3 ?].\n  generalize (resource_at_join _ _ _ loc H); intro.\n  rewrite H2 in H3.\n  rewrite H0 in H3.\n  apply join_comm in H3.\n  apply YES_join_full in H3; auto.\n  destruct H3 as [? [? H3]]. inv H3.\nQed.\n\nLemma necR_NOx:\n   forall phi phi' l sh nsh, \n      necR phi phi' -> \n      phi@l = NO sh nsh -> \n      phi'@l = NO sh nsh.\nProof.\ninduction 1; eauto.\nunfold age in H; simpl in H.\nrevert H; rewrite rmap_age1_eq; unfold resource_at.\ndestruct (unsquash x).\nintros; destruct n; inv H.\nrewrite unsquash_squash; simpl in *; auto.\ndestruct r; simpl in *.\nunfold compose.\nrewrite H0.\nauto.\nQed.\n\nLtac do_map_arg :=\nmatch goal with |- ?a = ?b =>\n  match a with context [map ?x _] =>\n    match b with context [map ?y _] => replace y with x; auto end end end.\n\nLemma preds_fmap_fmap:\n  forall f1 f2 g1 g2 pp, preds_fmap f1 f2 (preds_fmap g1 g2 pp) = preds_fmap (f1 oo g1) (g2 oo f2) pp.\nProof.\ndestruct pp; simpl; auto.\nf_equal; extensionality i.\nrewrite <- fmap_comp; auto.\nQed.\n\nLemma resource_fmap_fmap:  forall f1 f2 g1 g2 r, resource_fmap f1 f2 (resource_fmap g1 g2 r) =\n                                                                      resource_fmap (f1 oo g1) (g2 oo f2) r.\nProof.\ndestruct r; simpl; auto.\nrewrite preds_fmap_fmap; auto.\nrewrite preds_fmap_fmap; auto.\nQed.\n\nLemma resource_at_approx:\n  forall phi l,\n      resource_fmap (approx (level phi)) (approx (level phi)) (phi @ l) = phi @ l.\nProof.\nintros. symmetry. rewrite rmap_level_eq. unfold resource_at.\ncase_eq (unsquash phi); intros.\nsimpl.\ndestruct r; simpl in *.\nassert (R.valid (resource_fmap (approx n) (approx n) oo x)).\napply valid_res_map; auto.\nset (phi' := (squash (n, exist (fun m : AV.address -> resource => R.valid m) _ H0))).\ngeneralize (unsquash_inj phi phi'); intro.\nspec H1.\nreplace (unsquash phi) with (unsquash (squash (unsquash phi))).\n2: rewrite squash_unsquash; auto.\nrewrite H.\nunfold phi'.\nrepeat rewrite unsquash_squash.\nsimpl.\nreplace (exist (fun m : AV.address -> resource => valid m)\n  (resource_fmap (approx n) (approx n) oo x) (valid_res_map (approx n) (approx n) x v)) with\n(exist (fun m : AV.address -> resource => valid m)\n  (resource_fmap (approx n) (approx n) oo resource_fmap (approx n) (approx n) oo x)\n  (valid_res_map (approx n) (approx n) (resource_fmap (approx n) (approx n) oo x) H0)); auto.\nassert (Hex: forall A (F: A -> Prop) (x x': A) y y', x=x' -> exist F x y = exist F x' y') by auto with extensionality.\napply Hex.\nunfold compose.\nextensionality y.\nrewrite resource_fmap_fmap.\nrewrite approx_oo_approx; auto.\nunfold phi' in *; clear phi'.\nsubst.\nrewrite unsquash_squash in H.\ninjection H; clear H; intro.\npattern x at 1; rewrite <- H.\nunfold compose.\nrewrite resource_fmap_fmap.\nrewrite approx_oo_approx; auto.\nQed.\n\nLemma necR_resource_at:\n  forall phi phi' loc r,\n        necR phi phi' ->\n         phi @ loc = resource_fmap (approx (level phi)) (approx (level phi)) r ->\n         phi' @ loc = resource_fmap (approx (level phi')) (approx (level phi')) r.\nProof.\nintros.\nrevert r loc H0; induction H; intros; auto.\nunfold age in H.\nsimpl in H.\nrevert H H0; rewrite rmap_level_eq, rmap_age1_eq; unfold resource_at.\n case_eq (unsquash x); intros.\ndestruct n; inv H0.\nsimpl in *.\nrewrite unsquash_squash; simpl.\ndestruct r0; simpl in *.\nunfold compose in *.\nrewrite H1; clear H1.\nrewrite resource_fmap_fmap.\nrewrite approx_oo_approx'; auto.\nrewrite approx'_oo_approx; auto.\nQed.\n\nLemma necR_YES:\n  forall phi phi' loc rsh sh k pp,\n        necR phi phi' ->\n         phi @ loc = YES rsh sh k pp ->\n         phi' @ loc = YES rsh sh k (preds_fmap (approx (level phi')) (approx (level phi')) pp).\nProof.\nintros.\ngeneralize (eq_sym (resource_at_approx phi loc));\npattern (phi @ loc) at 2; rewrite H0; intro.\napply (necR_resource_at _ _ _ _ H H1).\nQed.\n\nLemma necR_PURE:\n  forall phi phi' loc k pp,\n        necR phi phi' ->\n         phi @ loc = PURE k pp ->\n         phi' @ loc = PURE k (preds_fmap (approx (level phi')) (approx (level phi')) pp).\nProof.\n  intros.\n  generalize (eq_sym (resource_at_approx phi loc));\n  pattern (phi @ loc) at 2; rewrite H0; intro.\n  apply (necR_resource_at _ _ _ _ H H1).\nQed.\n\nLemma necR_NO:\n   forall phi phi' l sh nsh, necR phi phi' -> \n   (phi@l = NO sh nsh <-> phi'@l = NO sh nsh).\nProof.\n  intros; split.\n  apply necR_NOx; auto.\n  intros.\n  case_eq (phi @ l); intros; auto.\n   generalize (necR_NOx _ _ l _ _ H H1); intro. congruence.\n  generalize (necR_YES _ _ _ _ _ _ _ H H1); congruence.\n  generalize (necR_PURE _ _ _ _ _ H H1); congruence.\nQed.\n\nLemma resource_at_empty: forall phi, \n     identity phi -> \n     forall l, (phi @ l = NO Share.bot bot_unreadable \\/ exists k, exists pds, phi @ l = PURE k pds).\nProof.\n  intros.\n  rewrite identity_unit_equiv in H.\n  unfold unit_for in H.\n  generalize (resource_at_join _ _ _ l H); intro.\n  remember (phi @ l) as r.\n  destruct r; inv H0; eauto.\n  left. clear - RJ.\n  apply identity_unit_equiv in RJ; apply identity_share_bot in RJ; subst.\n  f_equal. apply proof_irr.\n  clear - r RJ.\n  apply share_self_join_bot in RJ. subst.\n  contradiction (bot_unreadable r).\nQed.\nArguments resource_at_empty [phi] _ _.\n\nLemma rmap_valid: forall r, AV.valid (res_option oo resource_at r).\nProof.\nunfold compose, resource_at; intros.\ndestruct (unsquash r).\ndestruct r0.\nsimpl.\napply v.\nQed.\n\nLtac inj_pair_tac :=\n match goal with H: (@existT ?U ?P ?p ?x = @existT _ _ _ ?y) |- _ =>\n   generalize (@inj_pair2 U P p x y H); clear H; intro; try (subst x || subst y)\n end.\n\nLemma preds_fmap_NoneP:\n  forall f1 f2, preds_fmap f1 f2 NoneP = NoneP.\nProof.\nintros.\nunfold NoneP.\nauto.\nQed.\n\nLemma necR_YES':\n   forall phi phi' loc rsh sh k,\n         necR phi phi' -> (phi@loc = YES rsh sh k NoneP <-> phi'@loc = YES rsh sh k NoneP).\nProof.\nintros.\ninduction H.\nrename x into phi; rename y into phi'.\nunfold age in H; simpl in H.\n(* revert H; case_eq (age1 phi); intros; try discriminate. *)\ninv H.\nsplit; intros.\nrewrite (necR_YES phi phi' loc rsh sh k NoneP); auto. constructor 1; auto.\nrewrite rmap_age1_eq in *.\nunfold resource_at in *.\nrevert H1; case_eq (unsquash phi); simpl; intros.\ndestruct n; inv H1.\nrewrite unsquash_squash in H. simpl in H. destruct r; simpl in *.\nunfold compose in H.\nrevert H; destruct (x loc); simpl; intros; auto.\ndestruct p; inv H.\ninj_pair_tac. f_equal. apply proof_irr.\nunfold NoneP; f_equal.\nauto.\ninv H.\nintuition.\nintuition.\nQed.\n\nLemma necR_YES'':\n   forall phi phi' loc rsh sh k,\n         necR phi phi' ->\n    ((exists pp, phi@loc = YES rsh sh k pp) <->\n    (exists pp, phi'@loc = YES rsh sh k pp)).\nProof.\nintros.\ninduction H; try solve [intuition].\nrename x into phi; rename y into phi'.\nrevert H; unfold age; case_eq (age1 phi); intros; try discriminate.\ninv H0.\nsimpl in *.\nsplit; intros [pp ?].\n+ econstructor;\n  apply (necR_YES phi phi' loc rsh sh k pp).\n  constructor 1; auto. auto.\n+ rename phi' into r.\n  rewrite rmap_age1_eq in *.\n  unfold resource_at in *.\n  revert H; case_eq (unsquash phi); simpl; intros.\n  destruct n; inv H1.\n  rewrite unsquash_squash in H0. simpl in H0. destruct r0; simpl in *.\n  unfold compose in H0.\n  revert H0; destruct (x loc); simpl; intros; auto.\n  inv H0.\n  inv H0.\n  econstructor; proof_irr; eauto.\n  inv H0.\nQed.\n\nLemma necR_PURE':\n   forall phi phi' loc k,\n         necR phi phi' ->\n    ((exists pp, phi@loc = PURE k pp) <->\n    (exists pp, phi'@loc = PURE k pp)).\nProof.\nintros.\ninduction H; try solve [intuition].\nrename x into phi; rename y into phi'.\nrevert H; unfold age; case_eq (age1 phi); intros; try discriminate.\ninv H0.\nsimpl in *.\nsplit; intros [pp ?].\n+ econstructor;\n  apply (necR_PURE phi phi' loc k pp).\n  constructor 1; auto. auto.\n+ rename phi' into r.\n  rewrite rmap_age1_eq in *.\n  unfold resource_at in *.\n  revert H; case_eq (unsquash phi); simpl; intros.\n  destruct n; inv H1.\n  rewrite unsquash_squash in H0. simpl in H0. destruct r0; simpl in *.\n  unfold compose in H0.\n  revert H0; destruct (x loc); simpl; intros; auto.\n  inv H0.\n  inv H0.\n  econstructor; eauto.\n  inv H0.\n  eauto.\nQed.\n\nLemma resource_at_join_sub:\n  forall phi1 phi2 l,\n       join_sub phi1 phi2 -> join_sub (phi1@l) (phi2@l).\nProof.\nintros.\ndestruct H as [phi ?].\ngeneralize (resource_at_join _ _ _ l H); intro.\neconstructor; eauto.\nQed.\n\nLemma age1_res_option: forall phi phi' loc,\n     age1 phi = Some phi' -> res_option (phi @ loc) = res_option (phi' @ loc).\n  Proof.\n    unfold res_option, resource_at; simpl.\n   rewrite rmap_age1_eq; intros phi1 phi2 l.\n case_eq (unsquash phi1); intros. destruct n; inv H0.\n rewrite unsquash_squash.\n   destruct r;\n    simpl.\n   unfold compose. destruct (x l); simpl; auto.\nQed.\n\nLemma necR_res_option:\n  forall (phi phi' : rmap) (loc : AV.address),\n  necR phi phi' -> res_option (phi @ loc) = res_option (phi' @ loc).\nProof.\n  intros.\n  case_eq (phi @ loc); intros.\n  rewrite (necR_NO _ _ _ _ n H) in H0. congruence.\n  destruct p.\n  rewrite (necR_YES phi phi' loc _ _ _ _ H H0); auto.\n  rewrite (necR_PURE phi phi' loc _ _ H H0); auto.\nQed.\n\n\nLemma age1_resource_at:\n     forall phi phi',\n          age1 phi = Some phi' ->\n         forall loc r,\n          phi @ loc = resource_fmap (approx (level phi)) (approx (level phi)) r ->\n          phi' @ loc = resource_fmap (approx (level phi')) (approx (level phi')) r.\nProof.\n   unfold resource_at; rewrite rmap_age1_eq, rmap_level_eq.\nintros until phi'; case_eq (unsquash phi); intros.\nsimpl in *.\ndestruct n; inv H0.\nrewrite unsquash_squash.\ndestruct r; simpl in *.\nunfold compose; rewrite H1.\nrewrite resource_fmap_fmap.\nrewrite approx_oo_approx'; auto.\nrewrite approx'_oo_approx; auto.\nQed.\n\n\nLemma age1_YES: forall phi phi' l rsh sh k ,\n  age1 phi = Some phi' -> (phi @ l = YES rsh sh k NoneP <-> phi' @ l = YES rsh sh k NoneP).\nProof.\nintros.\napply necR_YES'.\nconstructor 1; auto.\nQed.\n\nLemma age1_YES': forall phi phi' l rsh sh k ,\n  age1 phi = Some phi' -> ((exists P, phi @ l = YES rsh sh k P) <-> exists P, phi' @ l = YES rsh sh k P).\nProof.\nintros.\napply necR_YES''.\nconstructor 1; auto.\nQed.\n\nLemma age1_NO: forall phi phi' l sh nsh,\n  age1 phi = Some phi' -> (phi @ l = NO sh nsh <-> phi' @ l = NO sh nsh).\nProof.\nintros.\napply necR_NO.\nconstructor 1; auto.\nQed.\n\nLemma age1_PURE: forall phi phi' l k ,\n  age1 phi = Some phi' -> ((exists P, phi @ l = PURE k P) <-> exists P, phi' @ l = PURE k P).\nProof.\n  intros.\n  apply necR_PURE'.\n  constructor 1; auto.\nQed.\n\nLemma empty_NO: forall r, identity r -> r = NO Share.bot bot_unreadable \\/ exists k, exists pds, r = PURE k pds.\nProof.\nintros.\ndestruct r; auto.\nleft. f_equal. apply identity_unit_equiv in H. inv H.\n  apply identity_unit_equiv in RJ. apply identity_share_bot in RJ. subst.\n f_equal. apply proof_irr.\nunfold identity in H.\nspec H (NO Share.bot bot_unreadable) (YES sh r k p).\nspec H.\napply res_join_NO2.\nauto.\ninv H.\nright. exists k. exists p. trivial.\nQed.\n\nLemma level_age_fash:\n  forall m m': rmap, level m = S (level m') -> exists m1, age m m1.\nProof.\n  intros.\n  case_eq (age1 m); intros.\n  exists r. auto.\n  elimtype False.\n  eapply age1None_levelS_absurd in H0; eauto.\nQed.\n\nLemma level_later_fash:\n forall m m': rmap, (level m > level m')%nat  -> exists m1, laterR m m1 /\\ level m1 = level m'.\nProof.\n  intros.\n  assert (exists k, level m = S k + level m')%nat.\n    exists (level m - S (level m'))%nat.\n    omega.\n  clear H; destruct H0 as [k ?].\n  revert m H; induction k; intros.\n  simpl in H.\n  destruct (level_age_fash _ _ H) as [m1 ?].\n  exists m1; split; auto.\n  constructor 1; auto.\n  apply age_level in H0. rewrite H in H0. inv H0. trivial.\n  case_eq (age1 m); intros.\n  spec IHk r.\n  rewrite <- ageN1 in H0.\n  generalize (ageN_level _ _ _ H0); intro.\n  spec IHk; try omega.\n  destruct IHk as [m1 [? ?]].\n  exists m1; split; auto.\n  econstructor 2; eauto.\n  rewrite ageN1 in H0.\n  constructor 1.\n  auto.\n  elimtype False.\n  eapply age1None_levelS_absurd in H0; eauto.\nQed.\n\nLemma resource_at_constructive_joins2:\n  forall phi1 phi2,\n       level phi1 = level phi2 ->\n       (forall loc, constructive_joins (phi1 @ loc) (phi2 @ loc)) ->\n         constructive_joins phi1 phi2.\nProof.\nintros ? ? ? H0.\nassert (AV.valid (res_option oo (fun loc => proj1_sig (H0 loc)))). {\n apply AV.valid_join with (res_option oo (resource_at phi1)) (res_option oo (resource_at phi2));\n  try apply rmap_valid.\n intro l.\n unfold compose in *.\n destruct (H0 l); simpl in *.\n destruct (phi1 @ l).\n inv j; simpl; try constructor.\n apply join_comm in RJ.\n rewrite (join_readable_part_eq rsh2 n rsh3 RJ); constructor.\n inv j; simpl; try constructor.\n rewrite (join_readable_part_eq r nsh2 rsh3 RJ); constructor.\n constructor. apply join_readable_part; auto. split; reflexivity.\n inv j; constructor.\n}\ndestruct (make_rmap _ H1 (level phi1)) as [phi' [? ?]].\nclear H1.\nunfold compose; extensionality loc.\nspec H0 loc.\ndestruct H0 as [? H1].\nsimpl.\nsymmetry.\nrevert H1; case_eq (phi1 @ loc); intros.\ninv H1. reflexivity.\npose proof (resource_at_approx phi2 loc). rewrite <- H4 in H1. simpl in H1.\ninjection H1; intros.\nsimpl; f_equal; auto. rewrite H; auto.\ninv H1.\npose proof (resource_at_approx phi1 loc). rewrite H0 in H1. simpl in H1.\ninjection H1; intros.\nsimpl; f_equal; auto.\nsimpl; f_equal.\npose proof (resource_at_approx phi1 loc). rewrite H0 in H1. simpl in H1.\ninjection H1; intros; auto.\ninv H1.\nsimpl; f_equal.\npose proof (resource_at_approx phi1 loc). rewrite H0 in H1. simpl in H1.\ninjection H1; intros; auto.\n(*  End of make_rmap proof *)\nexists phi'.\napply resource_at_join2; auto.\ncongruence.\nintros.\nrewrite H3.\ndestruct (H0 loc).\nsimpl; auto.\nQed.\n\nLemma resource_at_joins2:\n  forall phi1 phi2,\n       level phi1 = level phi2 ->\n       (forall loc, constructive_joins (phi1 @ loc) (phi2 @ loc)) ->\n         joins phi1 phi2.\nProof.\n  intros.\n  apply cjoins_joins.\n  apply resource_at_constructive_joins2; trivial.\nQed.\n\nDefinition no_preds (r: resource) :=\n   match r with NO _ _ => True | YES _ _ _ pp => pp=NoneP | PURE _ pp => pp=NoneP end.\n\nLemma remake_rmap:\n  forall (f: AV.address -> resource),\n       AV.valid (res_option oo f) ->\n       forall n,\n       (forall l, (exists m, level m = n /\\ f l = m @ l) \\/ no_preds (f l)) ->\n       {phi: rmap | level phi = n /\\ resource_at phi = f}.\nProof.\n  intros.\n  apply make_rmap; auto.\n  extensionality l.\n  unfold compose.\n  destruct (H0 l); clear H0.\n  destruct H1 as [m [?  ?]].\n  rewrite H1.\n  subst.\n  apply resource_at_approx.\n  destruct (f l); simpl in *; auto.\n  subst p; reflexivity.\n  subst p; reflexivity.\nQed.\n\nLemma rmap_unage_age:\n  forall r, age (rmap_unage r) r.\nProof.\nintros; unfold age, rmap_unage; simpl.\ncase_eq (unsquash r); intros.\nrewrite rmap_age1_eq.\nrewrite unsquash_squash.\nf_equal.\napply unsquash_inj.\nrewrite H.\nrewrite unsquash_squash.\nf_equal.\ngeneralize (equal_f (rmap_fmap_comp (approx (S n)) (approx (S n)) (approx n) (approx n)) r0); intro.\nunfold compose at 1 in H0.\nrewrite H0.\nrewrite approx_oo_approx'; auto.\nrewrite approx'_oo_approx; auto.\nclear - H.\ngeneralize (unsquash_squash n r0); intros.\nrewrite <- H in H0.\nrewrite squash_unsquash in H0.\ncongruence.\nQed.\n\nLemma ageN_resource_at_eq:\n  forall phi1 phi2 loc n phi1' phi2',\n          level phi1 = level phi2 ->\n          phi1 @ loc = phi2 @ loc ->\n         ageN n phi1 = Some phi1' ->\n         ageN n phi2 = Some phi2' ->\n         phi1' @ loc = phi2' @ loc.\nProof.\nintros ? ? ? ? ? ? Hcomp ? ? ?; revert phi1 phi2 phi1' phi2' Hcomp H H0 H1; induction n; intros.\ninv H0; inv H1; auto.\nunfold ageN in H0, H1.\nsimpl in *.\nrevert H0 H1; case_eq (age1 phi1); case_eq (age1 phi2); intros; try discriminate.\nassert (level r = level r0) by (apply age_level in H0; apply age_level in H1; omega).\napply (IHn r0 r); auto.\nrewrite (age1_resource_at _ _ H0 loc _ (eq_sym (resource_at_approx _ _))).\nrewrite (age1_resource_at _ _ H1 loc _ (eq_sym (resource_at_approx _ _))).\nrewrite H. rewrite H4; auto.\nQed.\n\n  Definition empty_rmap' : rmap'.\n    set (f:= fun _: AV.address => NO Share.bot bot_unreadable).\n    assert (R.valid f).\n    red; unfold f; simpl.\n    apply AV.valid_empty.\n    exact (exist _ f H).\n  Defined.\n\n  Definition empty_rmap (n:nat) : rmap := R.squash (n, empty_rmap').\n\nLemma emp_empty_rmap: forall n, emp (empty_rmap n).\nProof.\nintros.\nintro; intros.\napply rmap_ext.\nComp.\nintros.\napply (resource_at_join _ _ _ l) in H.\nunfold empty_rmap, empty_rmap', resource_at in *.\ndestruct (unsquash a); destruct (unsquash b).\nsimpl in *.\ndestruct r; destruct r0; simpl in *.\nrewrite unsquash_squash in H.\nsimpl in *.\nunfold compose in H.\ninv H; auto; apply join_unit1_e in RJ; auto; subst; proof_irr; auto.\nQed.\n\nLemma empty_rmap_level:\n  forall lev, level (empty_rmap lev) = lev.\nProof.\nintros.\nsimpl.\nrewrite rmap_level_eq.\nunfold  empty_rmap.\nrewrite unsquash_squash; auto.\nQed.\n\nLemma approx_FF: forall n, approx n FF = FF.\nProof.\nintros.\napply pred_ext; auto.\nunfold approx; intros ? ?.\nhnf in H. destruct H; auto.\nQed.\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 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\nInstance Join_trace : Join (AV.address -> option (rshare * AV.kind)) :=\n     (Join_fun AV.address (option (rshare * AV.kind))\n                   (Join_lower (Join_prod rshare Join_rshare AV.kind (Join_equiv AV.kind)))).\n\n\n Lemma res_option_join:\n    forall x y z, \n     join x y z -> \n     @join _ (@Join_lower (rshare * AV.kind)\n     (Join_prod rshare Join_rshare AV.kind (Join_equiv AV.kind))) (res_option x) (res_option y) (res_option  z).\n Proof.\n   intros.\n   inv H; simpl; try constructor.\n   erewrite join_readable_part_eq by eassumption. constructor.\n   apply join_comm in  RJ.\n   erewrite join_readable_part_eq by eassumption. constructor.\n   constructor. apply join_readable_part; auto.\n   split; auto. \n Qed.\n\nLtac uniq_assert name P := \n lazymatch goal with H: P |- _ => fail \n    | _ => let H1 := fresh \"H\" name in assert (H1:P) end.\n\nLtac readable_unreadable_join_prover := \nrepeat match goal with\n| H: join ?A ?B ?C, H1: ~readable_share ?C |- _ =>\n   uniq_assert A (~readable_share A);\n    [ clear - H H1; contradict H1; eapply join_readable1; eauto; fail | ]\n| H: join ?A ?B ?C, H1: ~readable_share ?C |- _ =>\n   uniq_assert B (~readable_share B);\n    [ clear - H H1; contradict H1; eapply join_readable2; eauto; fail | ]\n| H: join ?A ?B ?C, H0: ~readable_share ?B, H1: readable_share ?C |- _ =>\n    (uniq_assert A (readable_share A);\n    [ clear - H H0 H1; destruct (readable_share_dec A); \n      [solve [auto]\n       |eapply join_unreadable_shares in H; eauto; solve [contradiction]] | ])\n| H: join ?A ?B ?C, H0: ~readable_share ?A, H1: readable_share ?C |- _ =>\n    (uniq_assert B (readable_share B);\n    [ clear - H H0 H1; destruct (readable_share_dec B); \n      [solve [auto]\n       | apply join_comm in H; \n         eapply join_unreadable_shares in H; eauto; solve [contradiction]] | ])\nend.\n\nLemma Cross_resource: Cross_alg resource.\nProof.\nintro; intros.\ndestruct a as [ra | ra sa ka pa | ka pa ].\ndestruct b as [rb | rb sb kb pb | kb pb ]; try solve [elimtype False; inv H].\ndestruct z as [rz | rz sz kz pz | kz pz ]; try solve [elimtype False; inv H].\ndestruct c as [rc | rc sc kc pc | kc pc ]; try solve [elimtype False; inv H0].\ndestruct d as [rd | rd sd kd pd | kd pd ]; try solve [elimtype False; inv H0].\nassert (J1: join ra rb rz) by (inv H; auto).\nassert (J2: join rc rd rz) by (inv H0; auto).\ndestruct (share_cross_split _ _ _ _ _ J1 J2) as [[[[ac ad] bc] bd] [Ha [Hb [Hc Hd]]]].\nreadable_unreadable_join_prover.\nexists (NO ac Hac,NO ad Had, NO bc Hbc, NO bd Hbd); \n  repeat split; simpl; auto; constructor; auto.\ndestruct z as [rz | rz sz kz pz | kz pz ]; try solve [elimtype False; inv H].\ndestruct c as [rc | rc sc kc pc | kc pc ]; try solve [elimtype False; inv H0].\ndestruct d as [rd | rd sd kd pd | kd pd ]; try solve [elimtype False; inv H0].\nassert (J1: join ra rb rz) by (inv H; auto).\nassert (J2: join rc rd rz) by (inv H0; auto).\ndestruct (share_cross_split _ _ _ _ _ J1 J2) as [[[[ac ad] bc] bd] [Ha [Hb [Hc Hd]]]].\nreadable_unreadable_join_prover.\nexists (NO ac Hac, NO ad Had, NO bc Hbc, YES bd Hbd kb pb); inv H; inv H0;\n  repeat split; simpl; auto; try constructor; auto.\nassert (J1: join ra rb rz) by (inv H; auto).\ndestruct d as [rd | rd sd kd pd | kd pd ]; try solve [elimtype False; inv H0].\nassert (J2: join rc rd rz) by (inv H0; auto).\ndestruct (share_cross_split _ _ _ _ _ J1 J2) as [[[[ac ad] bc] bd] [Ha [Hb [Hc Hd]]]].\nreadable_unreadable_join_prover.\nexists (NO ac Hac, NO ad Had, YES bc Hbc kb pb, NO bd Hbd); inv H; inv H0;\n  repeat split; simpl; auto; try constructor; auto.\nassert (J2: join rc rd rz) by (inv H0; auto).\ndestruct (share_cross_split _ _ _ _ _ J1 J2) as [[[[ac ad] bc] bd] [Ha [Hb [Hc Hd]]]].\nreadable_unreadable_join_prover.\nexists (NO ac Hac, NO ad Had, YES bc Hbc kb pb, YES bd Hbd kd pd); inv H; inv H0;\n  repeat split; simpl; auto; try constructor; auto.\ndestruct b as [rb | rb sb kb pb | kb pb ]; try solve [elimtype False; inv H].\ndestruct z as [rz | rz sz kz pz | kz pz ]; try solve [elimtype False; inv H].\nassert (J1: join ra rb rz) by (inv H; auto).\ndestruct c as [rc | rc sc kc pc | kc pc ]; try solve [elimtype False; inv H0].\ndestruct d as [rd | rd sd kd pd | kd pd ]; try solve [elimtype False; inv H0].\nassert (J2: join rc rd rz) by (inv H0; auto).\ndestruct (share_cross_split _ _ _ _ _ J1 J2) as [[[[ac ad] bc] bd] [Ha [Hb [Hc Hd]]]].\nreadable_unreadable_join_prover.\nexists (NO ac Hac, YES ad Had kd pd, NO bc Hbc, NO bd Hbd); inv H; inv H0;\n  repeat split; simpl; auto; try constructor; auto.\ndestruct d as [rd | rd sd kd pd | kd pd ]; try solve [elimtype False; inv H0].\nassert (J2: join rc rd rz) by (inv H0; auto).\ndestruct (share_cross_split _ _ _ _ _ J1 J2) as [[[[ac ad] bc] bd] [Ha [Hb [Hc Hd]]]].\nreadable_unreadable_join_prover.\nexists (YES ac Hac kc pc, NO ad Had, NO bc Hbc, NO bd Hbd); inv H; inv H0;\n  repeat split; simpl; auto; try constructor; auto.\nassert (J2: join rc rd rz) by (inv H0; auto).\ndestruct (share_cross_split _ _ _ _ _ J1 J2) as [[[[ac ad] bc] bd] [Ha [Hb [Hc Hd]]]].\nreadable_unreadable_join_prover.\nexists (YES ac Hac kc pc, YES ad Had kd pd, NO bc Hbc, NO bd Hbd); inv H; inv H0;\n  repeat split; simpl; auto; try constructor; auto.\ndestruct z as [rz | rz sz kz pz | kz pz ]; try solve [elimtype False; inv H].\nassert (J1: join ra rb rz) by (inv H; auto).\ndestruct c as [rc | rc sc kc pc | kc pc ]; try solve [elimtype False; inv H0].\ndestruct d as [rd | rd sd kd pd | kd pd ]; try solve [elimtype False; inv H0].\nassert (J2: join rc rd rz) by (inv H0; auto).\ndestruct (share_cross_split _ _ _ _ _ J1 J2) as [[[[ac ad] bc] bd] [Ha [Hb [Hc Hd]]]].\nreadable_unreadable_join_prover.\nexists (NO ac Hac, YES ad Had kd pd, NO bc Hbc, YES bd Hbd kd pd); inv H; inv H0;\n  repeat split; simpl; auto; try constructor; auto.\ndestruct d as [rd | rd sd kd pd | kd pd ]; try solve [elimtype False; inv H0].\nassert (J2: join rc rd rz) by (inv H0; auto).\ndestruct (share_cross_split _ _ _ _ _ J1 J2) as [[[[ac ad] bc] bd] [Ha [Hb [Hc Hd]]]].\nreadable_unreadable_join_prover.\nexists (YES ac Hac kc pc, NO ad Had, YES bc Hbc kb pb, NO bd Hbd); inv H; inv H0;\n  repeat split; simpl; auto; try constructor; auto.\nassert (J2: join rc rd rz) by (inv H0; auto).\ndestruct (share_cross_split _ _ _ _ _ J1 J2) as [[[[ac ad] bc] bd] [Ha [Hb [Hc Hd]]]].\ndestruct (Sumbool.sumbool_not _ _ (readable_share_dec ac)) as [Hac|Hac].\nreadable_unreadable_join_prover.\ndestruct (Sumbool.sumbool_not _ _ (readable_share_dec bd)) as [Hbd|Hbd].\nexists (NO ac Hac, YES ad Had ka pa, YES bc Hbc kc pc, NO bd Hbd); \n   inv H; inv H0; simpl; repeat split; auto;  constructor; auto.\nexists (NO ac Hac, YES ad Had ka pa, YES bc Hbc kc pc, YES bd Hbd kd pd); \n   inv H; inv H0; simpl; repeat split; auto;  constructor; auto.\ndestruct (Sumbool.sumbool_not _ _ (readable_share_dec ad)) as [Had|Had];\nreadable_unreadable_join_prover;\ndestruct (Sumbool.sumbool_not _ _ (readable_share_dec bc)) as [Hbc|Hbc];\nreadable_unreadable_join_prover.\nexists (YES ac Hac ka pa, NO ad Had, NO bc Hbc, YES bd Hbd kb pb); \n\n   inv H; inv H0; simpl; repeat split; auto;  constructor; auto.\nexists (YES ac Hac ka pa, NO ad Had, YES bc Hbc kc pc, YES bd Hbd kd pd);\n    inv H; inv H0; simpl; repeat split; auto;  constructor; auto.\nexists (YES ac Hac kc pc, YES ad Had kc pc, NO bc Hbc, YES bd Hbd kb pb);\n    inv H; inv H0; simpl; repeat split; auto;  constructor; auto.\ndestruct (Sumbool.sumbool_not _ _ (readable_share_dec bd)) as [Hbd|Hbd].\nexists (YES ac Hac ka pa,  YES ad Had kd pd, YES bc Hbc kb pb, NO bd Hbd);\n    inv H; inv H0; simpl; repeat split; auto;  constructor; auto.\nexists (YES ac Hac ka pa, YES ad Had ka pa, \n       YES bc Hbc ka pa,  YES bd Hbd ka pa);\n    inv H; inv H0; simpl; repeat split; auto;  constructor; auto.\nexists (PURE ka pa, PURE ka pa, PURE ka pa, PURE ka pa).\ninv H. inv H0.\nrepeat split; constructor; auto.\nQed.\n\nDefinition res_retain (r: resource) : Share.t :=\n match r with\n  | NO sh _ => retainer_part sh\n  | YES sh _ _ _ => retainer_part sh\n  | PURE _ _ => Share.bot\n end.\n\nLemma fixup_trace_readable:\n  forall a (b: rshare), readable_share (Share.lub (Share.glb Share.Lsh a) (Share.glb Share.Rsh (proj1_sig b))).\nProof.\nintros.\ndestruct b as [b H].\nforget (Share.glb Share.Lsh a) as a'. clear a.\nsimpl.\ndestruct H as [H' H].\ndo 3 red in H|-*.\nsimpl.\ncontradict H.\nrewrite Share.distrib1 in H.\nrewrite <- Share.glb_assoc in H.\nrewrite Share.glb_idem in H.\napply identity_share_bot in H.\napply lub_bot_e in H. destruct H.\nrewrite H0. apply bot_identity.\nQed.\n\nDefinition fixup_trace (retain: AV.address -> Share.t)\n                 (trace: AV.address -> option (rshare * AV.kind))\n                 (f: AV.address -> resource) : AV.address -> resource :=\n   fun x => match trace x, f x with\n            | None, PURE k pp => PURE k pp\n            | Some(sh,k), PURE _ pp =>\n               YES _ (fixup_trace_readable (retain x) sh) k pp\n            | Some (sh,k), YES _ _ _ pp => YES _ (fixup_trace_readable (retain x) sh) k pp\n            | Some (sh, k), NO _ _ => YES _ (fixup_trace_readable (retain x) sh) k NoneP\n            | None, _ => NO _ (@retainer_part_nonreadable (retain x))\n            end.\n\n\nDefinition fixup_trace_ok (tr: AV.address -> option (rshare * AV.kind)) :=\n forall x, match tr x with None => True | Some(sh,_)=> Share.glb Share.Rsh (proj1_sig sh) = (proj1_sig sh) end.\n\nLemma fixup_trace_valid: forall retain\n             tr \n             (trace_ok: fixup_trace_ok tr)\n              f,\n            AV.valid tr -> \n            AV.valid (res_option oo (fixup_trace retain tr f)).\n Proof. intros.\n  replace (res_option oo fixup_trace retain tr f) with tr. auto.\n  extensionality l. unfold compose. unfold fixup_trace.\n  specialize (trace_ok l).\n  destruct (tr l); simpl; auto.\n*\n  destruct p. rename r into s.\n  assert (s = readable_part (fixup_trace_readable (retain l) s)). {\n    destruct s; apply exist_ext'; simpl in *.\n    clear - trace_ok.\n    rewrite Share.lub_commute.\n    rewrite Share.distrib1.\n    rewrite <- !Share.glb_assoc. rewrite Share.glb_idem.\n    rewrite (Share.glb_commute _ Share.Lsh).\n    rewrite glb_Lsh_Rsh. rewrite (Share.glb_commute Share.bot). rewrite Share.glb_bot.\n    rewrite Share.lub_bot. auto.\n  }\n  destruct (f l); simpl; f_equal; f_equal; auto.\n*\n  destruct (f l); reflexivity.\nQed.\n\nLemma fixup_trace_rmap:\n    forall (retain: AV.address -> Share.t) \n             (tr: sig AV.valid) (trace_ok: fixup_trace_ok (proj1_sig tr)) (f: rmap),\n        {phi: rmap | \n             level phi = level f \n            /\\ resource_at phi = fixup_trace retain (proj1_sig tr) (resource_at f)}.\nProof.\n intros.\n apply make_rmap.\n apply fixup_trace_valid; auto. destruct tr; simpl; auto.\n extensionality l.\n unfold compose, fixup_trace.\n destruct tr. simpl.\n destruct (x l); simpl; auto. destruct p.\n case_eq (f @ l); intros.\n unfold resource_fmap. rewrite preds_fmap_NoneP; auto.\n generalize (resource_at_approx f l); intro.\n rewrite H in H0. symmetry in H0.\n  simpl in H0. simpl.\n   f_equal. injection H0; auto.\n generalize (resource_at_approx f l); intro.\n rewrite H in H0. symmetry in H0.\n  simpl in H0. simpl.\n   f_equal. injection H0; auto.\n case_eq (f @ l); intros; auto.\n generalize (resource_at_approx f l); intro.\n rewrite H in H0. symmetry in H0.\n  simpl in H0. simpl.\n   f_equal. injection H0; auto.\nQed.\n\nLemma join_res_retain:\n          forall a b c: rmap ,\n              join a b c ->\n              join (res_retain oo resource_at a) (res_retain oo resource_at b) (res_retain oo resource_at c).\nProof.\n intros.\n intro loc; apply (resource_at_join _ _ _ loc) in H.\n  unfold compose.\n inv H; simpl; auto; apply retainer_part_join; auto.\nQed.\n\nLemma join_fixup_trace_ok:\n  forall (v w: sig AV.valid) a,\n    join v w (exist AV.valid (res_option oo resource_at a) (rmap_valid a)) ->\n    fixup_trace_ok (proj1_sig v).\nProof.\n  intros.\n   hnf; intros.\n   destruct v, w. simpl in *.\n   red in H. red in H. simpl in H.\n   specialize (H x).\n   clear - H.\n   forget (x0 x) as u. forget (x1 x) as v.\n   unfold res_option, compose in H.\n   destruct (a @ x); inv H; auto.\n   unfold readable_part. simpl.\n   rewrite <- Share.glb_assoc. rewrite Share.glb_idem; auto.\n   destruct a1 as [[v ?] ?]. destruct a2 as [[w ?] ?].\n   destruct H3 as [H3 _]. do 2 red in H3. simpl in H3.\n   simpl. clear - H3.\n   assert (join_sub v (Share.glb Share.Rsh sh)) by (exists w; auto).\n   clear H3.\n   apply leq_join_sub in H.\n   assert (Share.Ord (Share.glb Share.Rsh sh) Share.Rsh).\n   apply Share.ord_spec1.\n   symmetry. rewrite Share.glb_commute. rewrite <- Share.glb_assoc.\n   rewrite Share.glb_idem. auto.\n   pose proof (Share.ord_trans _ _ _ H H0).\n   clear - H1.\n   apply Share.ord_spec1 in H1.\n   rewrite Share.glb_commute. auto.\nQed.\n\nInstance Perm_foo: Perm_alg\n               {x : AV.address -> option (rshare * AV.kind) |\n               AV.valid x}.\nProof.\napply Perm_prop.\napply Perm_fun.\napply Perm_lower.\napply Perm_prod.\napply Perm_rshare.\napply Perm_equiv.\nintros.\neapply AV.valid_join; eauto.\nQed.\n\nLtac crtac' :=\n repeat  (simpl in *; ((*solve [constructor; auto] ||*)\n   match goal with\n | H: None = res_option ?A |- _ => destruct A; inv H\n | H: Some _ = res_option ?A |- _ => destruct A; inv H\n | H: join (NO _ _) _ _ |- _ => inv H\n | H: join _ (NO _ _) _ |- _ => inv H\n | H: join (YES _ _ _ _) _ _ |- _ => inv H\n | H: join _ (YES _ _ _ _) _ |- _ => inv H\n | H: join (PURE _ _) _ _ |- _ => inv H\n | H: join _ (PURE _ _) _ |- _ => inv H\n | H: @join _ _ (Some _) _ _ |- _ => inv H\n | H: @join _ _ _ (Some _) _ |- _ => inv H\n | H: join None _ _ |- _ =>  inv H\n | H: join _ None _ |- _ => inv H\n end; auto)).\n\n\nLemma join_fixup_trace:\n forall (Rc Rd: AV.address -> Share.t)\n        (c d: AV.address -> option (rshare * AV.kind))\n        (z a: rmap) (l: AV.address), \n   join_sub (a @ l) (z @ l) ->\n   join (Rc l) (Rd l) (res_retain (a @ l)) ->\n   @join (option (rshare * AV.kind))\n       (@Join_lower (rshare * AV.kind)\n          (Join_prod rshare Join_rshare AV.kind\n             (Join_equiv AV.kind)))\n         (c l) (d l) (res_option (a @ l)) ->\n   join (fixup_trace Rc c (resource_at z) l) (fixup_trace Rd d (resource_at z) l) (a @ l).\nProof.\nintros.\nunfold fixup_trace.\nforget (a @ l) as al.\nforget (z @ l) as zl.\nforget (Rc l) as Rcl.\nforget (c l) as cl.\nforget (Rd l) as Rdl.\nforget (d l) as dl.\ndestruct H as [bl H].\nclear - H H0 H1.\ndestruct cl as [[? ?]|]; crtac'; try constructor.\n*\ndestruct (join_parts comp_Lsh_Rsh H0) as [J1 [J2 [J3 J4]]].\nunfold retainer_part.\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\napply left_right_join.\nrewrite Share.distrib1.\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\nassumption.\nrewrite Share.distrib1.\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\napply join_unit2; auto.\n*\ndestruct (join_parts comp_Lsh_Rsh H0) as [J1 [J2 [J3 J4]]].\nunfold retainer_part.\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\napply left_right_join.\nrewrite Share.distrib1.\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\nassumption.\nrewrite Share.distrib1.\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\napply join_unit2; auto.\n*\ndestruct a2.\ndestruct H5; simpl in *. destruct H1; subst.\ndestruct r,r1; simpl in *.\ndo 2 red in H. simpl in *.\nconstructor.\ndestruct (join_parts comp_Lsh_Rsh H0) as [J1 [J2 [J3 J4]]].\napply left_right_join.\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\nrewrite Share.distrib1.\nrewrite glb_Lsh_Rsh', Share.lub_bot.\nrewrite Share.distrib1.\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\nassumption.\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\nrewrite Share.distrib1.\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\nrewrite Share.distrib1.\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\ndestruct (join_parts comp_Rsh_Lsh H) as [K1 [K2 [K3 K4]]].\nrewrite ?K1, ?K2,?K3,?K4.\nassumption.\n*\ndestruct a2.\ndestruct H5; simpl in *. destruct H1; subst.\ndestruct r,r1; simpl in *.\ndo 2 red in H. simpl in *.\nconstructor.\ndestruct (join_parts comp_Lsh_Rsh H0) as [J1 [J2 [J3 J4]]].\napply left_right_join.\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\nrewrite Share.distrib1.\nrewrite glb_Lsh_Rsh', Share.lub_bot.\nrewrite Share.distrib1.\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\nassumption.\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\nrewrite Share.distrib1.\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\nrewrite Share.distrib1.\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\ndestruct (join_parts comp_Rsh_Lsh H) as [K1 [K2 [K3 K4]]].\nrewrite ?K1, ?K2,?K3,?K4.\nassumption.\n*\nunfold retainer_part in *.\ndestruct al; crtac'; try constructor;\nunfold retainer_part in *.\n +\ndestruct (join_parts comp_Lsh_Rsh H0) as [J1 [J2 [J3 J4]]].\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\nrewrite <- (Share.glb_top sh). rewrite Share.glb_commute.\nrewrite <- lub_Lsh_Rsh.\nrewrite Share.glb_commute.\nrewrite Share.distrib1.\napply not_readable_Rsh_part in nsh0.\nrewrite (Share.glb_commute _ Share.Rsh), nsh0.\nrewrite Share.lub_bot.\nrewrite Share.glb_commute; auto.\n +\nrewrite <- (Share.glb_top sh). rewrite Share.glb_commute.\nrewrite <- lub_Lsh_Rsh.\nrewrite Share.glb_commute.\nrewrite Share.distrib1.\napply not_readable_Rsh_part in nsh0.\nrewrite (Share.glb_commute _ Share.Rsh), nsh0.\nrewrite Share.lub_bot.\ndestruct (join_parts comp_Lsh_Rsh H0) as [J1 [J2 [J3 J4]]].\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\nrewrite Share.glb_commute; auto.\n +\ndestruct (join_parts comp_Lsh_Rsh H0) as [J1 [J2 [J3 J4]]].\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\napply left_right_join.\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\nrewrite Share.distrib1.\nrewrite glb_Lsh_Rsh', Share.lub_bot.\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\nauto.\nrewrite Share.distrib1.\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\napply join_unit1; auto.\n +\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\napply left_right_join.\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\ndestruct (join_parts comp_Lsh_Rsh H0) as [J1 [J2 [J3 J4]]].\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\nrewrite Share.distrib1.\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\nauto.\nrewrite <- Share.glb_assoc. rewrite glb_Rsh_Lsh.\nrewrite Share.glb_commute. rewrite Share.glb_bot. \nrewrite Share.distrib1.\nrewrite <- Share.glb_assoc. rewrite glb_Rsh_Lsh.\nrewrite Share.glb_commute. rewrite Share.glb_bot. \nrewrite Share.lub_commute, Share.lub_bot.\nrewrite <- Share.glb_assoc. rewrite Share.glb_idem.\napply join_unit1; auto.\n*\ndestruct (join_parts comp_Lsh_Rsh H0) as [J1 [J2 [J3 J4]]].\nunfold retainer_part in *.\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\nauto.\nrewrite <- (Share.glb_top sh). rewrite Share.glb_commute.\nrewrite <- lub_Lsh_Rsh.\nrewrite Share.glb_commute.\nrewrite Share.distrib1.\napply not_readable_Rsh_part in nsh0.\nrewrite (Share.glb_commute _ Share.Rsh), nsh0.\nrewrite Share.lub_bot.\nrewrite Share.glb_commute; auto.\n*\ndestruct (join_parts comp_Lsh_Rsh H0) as [J1 [J2 [J3 J4]]].\nunfold retainer_part in *.\nrewrite ?J1,?J2,?J3,?J4, ?glb_twice, ?glb_Lsh_Rsh', ?Share.lub_bot, ?lub_bot'.\nauto.\nrewrite <- (Share.glb_top sh). rewrite Share.glb_commute.\nrewrite <- lub_Lsh_Rsh.\nrewrite Share.glb_commute.\nrewrite Share.distrib1.\napply not_readable_Rsh_part in nsh0.\nrewrite (Share.glb_commute _ Share.Rsh), nsh0.\nrewrite Share.lub_bot.\nrewrite Share.glb_commute; auto.\nQed.\n\nInstance Cross_rmap:\n      @Cross_alg _ (Join_prop _ Join_trace AV.valid) ->\n      Cross_alg rmap.\nProof.\n  intro CAV.\n  repeat intro.\n  assert (Hz : valid (resource_at z)).\n  unfold resource_at.\n  case_eq (unsquash z); intros.\n  simpl.\n  destruct r; simpl; auto.\n  specialize (CAV\n          (exist AV.valid _ (rmap_valid a))\n          (exist AV.valid _ (rmap_valid b))\n          (exist AV.valid _ (rmap_valid c))\n          (exist AV.valid _ (rmap_valid d))\n          (exist AV.valid _ Hz)).\n  destruct CAV as [[[[Vac Vad] Vbc] Vbd] [Va [Vb [Vc Vd]]]].\n  intro l.  unfold compose. simpl.\n  apply res_option_join. apply resource_at_join. auto.\n  intro l.  simpl. unfold compose.\n  apply res_option_join. apply resource_at_join. auto.\n  assert (CAR: Cross_alg (AV.address -> Share.t)) by auto with typeclass_instances.\n  specialize (CAR _ _ _ _ _ (join_res_retain _ _ _ H) (join_res_retain _ _ _ H0)).\n  destruct CAR as [[[[Rac Rad] Rbc] Rbd] [Ra [Rb [Rc Rd]]]].\n  destruct (fixup_trace_rmap  Rac Vac (join_fixup_trace_ok _ _ _ Va) z) as [Mac [? ?]].\n  destruct (fixup_trace_rmap Rad Vad (join_fixup_trace_ok _ _ _ Vd) z) as [Mad [? ?]].\n  destruct (fixup_trace_rmap Rbc Vbc (join_fixup_trace_ok _ _ _ Vb) z) as [Mbc [? ?]].\n  destruct (fixup_trace_rmap Rbd Vbd (join_fixup_trace_ok _ _ _ (join_comm Vb)) z) as [Mbd [? ?]].\n  exists (Mac,Mad,Mbc,Mbd).\n  destruct Vac as [ac ?]; destruct Vad as [ad ?]; destruct Vbc as [bc ?];\n  destruct Vbd as [bd ?]; simpl in *.\n  assert (LEVa: level a = level z) by (apply join_level in H; destruct H; auto).\n  assert (LEVb: level b = level z) by (apply join_level in H; destruct H; auto).\n  assert (LEVc: level c = level z) by (apply join_level in H0; destruct H0; auto).\n  assert (LEVd: level d = level z) by (apply join_level in H0; destruct H0; auto).\n  do 2 red in Va,Vb,Vc,Vd; simpl in *.\n  unfold compose in *. clear Hz.\n  split; [|split3];   apply resource_at_join2; try congruence;\n  repeat match goal with\n  | H: AV.valid _ |- _ => clear H\n  | H: level _ = level _ |- _ => clear H\n  end;\n  intro l;\n  spec Va l; spec Vb l; spec Vc l; spec Vd l;\n  spec Ra l; spec Rb l; spec Rc l; spec Rd l; \n  apply (resource_at_join _ _ _ l) in H;\n  apply (resource_at_join _ _ _ l) in H0;\n  try rewrite H2; try rewrite H4; try rewrite H6; try rewrite H8;\n  simpl in *;\n eapply join_fixup_trace; eauto;\n (eapply join_join_sub; eassumption) || (eapply join_join_sub'; eassumption).\nQed.\n\nLemma identity_resource: forall r: resource, identity r <->\n    match r with YES _ _ _ _ => False | NO sh rsh => identity sh | PURE _ _ => True end.\nProof.\n intros. destruct r.\n split; intro; apply identity_unit_equiv in H;  apply identity_unit_equiv.\n inv H; auto. constructor; auto.\n intuition.\n specialize (H (NO Share.bot bot_unreadable) (YES sh r k p)).\n spec H. constructor. apply join_unit2; auto. inv H.\n intuition. intros  ? ? ?. inv H0. auto.\nQed.\n\nLemma resource_at_core_identity:  forall m i, identity (core m @ i).\nProof.\n  intros.\n  generalize (core_duplicable m); intro Hdup. apply (resource_at_join _ _ _ i) in Hdup.\n  apply identity_resource.\n  case_eq (core m @ i); intros; auto.\n  rewrite H in Hdup. inv Hdup. apply identity_unit_equiv; auto.\n  rewrite H in Hdup. inv Hdup.\n  clear - r RJ.\n  apply unit_identity in RJ. apply identity_share_bot in RJ.\n  subst. apply bot_unreadable in r. auto.\nQed.\n\nLemma YES_inj: forall sh rsh k pp sh' rsh' k' pp',\n           YES sh rsh k pp = YES sh' rsh' k' pp' ->\n            (sh,k,pp) = (sh',k',pp').\nProof. intros. inv H. auto. Qed.\n\nLemma SomeP_inj1: forall t t' a a', SomeP t a = SomeP t' a' -> t=t'.\n  Proof. intros. inv H; auto. Qed.\nLemma SomeP_inj2: forall t a a', SomeP t a = SomeP t a' -> a=a'.\n  Proof. intros. inv H. apply inj_pair2 in H1. auto. Qed.\nLemma SomeP_inj:\n   forall T a b, SomeP T a = SomeP T b -> a=b.\nProof. intros. inv H. apply inj_pair2 in H1. auto.\nQed.\n\nLemma PURE_inj: forall T x x' y y', PURE x (SomeP T y) = PURE x' (SomeP T y') -> x=x' /\\ y=y'.\n Proof. intros. inv H. apply inj_pair2 in H2. subst; auto.\n Qed.\n\nLemma core_resource_at: forall w i, core (w @ i) = core w @ i.\nProof.\n intros.\n generalize (core_unit w); intros.\n apply (resource_at_join _ _ _ i) in H.\n generalize (core_unit (w @ i)); unfold unit_for; intros.\n eapply join_canc; eauto.\nQed.\n\nLemma resource_at_identity: forall (m: rmap) (loc: AV.address),\n identity m -> identity (m @ loc).\nProof.\n  intros.\n  destruct (@resource_at_empty m H loc) as [?|[? [? ?]]].\n  rewrite H0. apply NO_identity.\n  rewrite H0. apply PURE_identity.\nQed.\n\nLemma core_YES: forall sh rsh k pp, core (YES sh rsh k pp) = NO Share.bot bot_unreadable.\nProof.\n intros. generalize (core_unit (YES sh rsh k pp)); unfold unit_for; intros. \n inv H; auto.\n apply unit_identity in RJ. apply identity_share_bot in RJ. subst; auto.\n f_equal. apply proof_irr.\n clear - H1.\n pose proof (core_unit (YES sh rsh k pp)).\n hnf in H. inv H.\n rewrite <- H2 in H1. inv H1.\n rewrite <- H2 in H1. inv H1.\n apply unit_identity in RJ. apply identity_share_bot in RJ. subst sh0.\n contradiction (bot_unreadable rsh0).\nQed.\n\nLemma core_NO: forall sh nsh, core (NO sh nsh) = NO Share.bot bot_unreadable.\nProof.\n intros.  generalize (core_unit (NO sh nsh)); unfold unit_for; intros.\n inv H; auto.\n pose proof (core_unit (NO sh nsh)).\n apply unit_identity in RJ. apply identity_share_bot in RJ. subst sh1.\n f_equal. apply proof_irr.\nQed.\n\nLemma core_PURE: forall k pp, core (PURE k pp) = PURE k pp.\nProof.\n intros. generalize (core_unit (PURE k pp)); unfold unit_for; intros.\n inv H; auto.\nQed.\n\n\nLemma core_not_YES: forall {w loc rsh sh k pp},\n   core w @ loc = YES rsh sh k pp -> False.\nProof.\nintros.\nrewrite <- core_resource_at in H.\ndestruct (w @ loc); [rewrite core_NO in H | rewrite core_YES in H | rewrite core_PURE in H]; inv H.\nQed.\n\nLemma resource_at_empty2:\n forall phi: rmap, (forall l, identity (phi @ l)) -> identity phi.\nProof.\nintros.\nassert (phi = core phi).\napply rmap_ext.\nrewrite level_core. auto.\nintro l; specialize (H l).\napply identity_unit_equiv in H; apply unit_core in H.\nrewrite core_resource_at in *; auto.\nrewrite H0.\napply core_identity.\nQed.\n\nLemma resource_fmap_core:\n  forall w loc, resource_fmap (approx (level w)) (approx (level w)) (core (w @ loc)) = core (w @ loc).\nProof.\nintros.\ncase_eq (w @ loc); intros;\n [rewrite core_NO | rewrite core_YES | rewrite core_PURE]; auto.\nrewrite <- H. apply resource_at_approx.\nQed.\n\nEnd Rmaps_Lemmas.\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/rmaps_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2545081595433702}}
{"text": "Set Implicit Arguments.\n\nRequire Import Coq.Lists.List.\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.ConvertLabel.\n\nDefinition to_bl_pair elt (p : glabel * elt) := (fst p : label, snd p).\n\nDefinition to_blm elt m := LabelMapFacts.of_list (List.map (@to_bl_pair _) (@elements elt m)).\n\nModule Notations.\n  Notation \"m1 === m2\" := (LabelMap.Equal m1 (to_blm m2)) (at level 70) : clm_scope.\nEnd Notations.\n\nSection TopSection.\n\n  Import Notations.\n  Open Scope clm_scope.\n  Import ListNotations.\n  Import FMapNotations.\n  Open Scope fmap.\n\n  Require Import Coq.Setoids.Setoid.\n  Require Import Coq.Lists.SetoidList.\n  Require Import Bedrock.Platform.Cito.GeneralTactics.\n  Require Import Bedrock.Platform.Cito.ListFacts1.\n\n  Set Printing Coercions.\n\n  Lemma NoDupKey_to_bl_pair_elements : forall elt m, LabelMapFacts.NoDupKey (List.map (@to_bl_pair _) (@elements elt m)).\n    intros.\n    eapply LabelMapFacts.NoDupKey_NoDup_fst.\n    rewrite map_map.\n    unfold to_bl_pair; simpl in *.\n    rewrite <- map_map.\n    eapply Injection_NoDup.\n    unfold to_bedrock_label.\n    unfold IsInjection; intuition.\n    destruct x; destruct y; simpl in *.\n    injection H0; intros; subst.\n    intuition.\n    eapply NoDupKey_NoDup_fst.\n    eapply elements_3w.\n  Qed.\n\n  Lemma to_blm_spec : forall elt (k : glabel) m, @LabelMap.find elt (k : label) (to_blm m) = find k m.\n    unfold to_blm, LabelMapFacts.to_map.\n    intros.\n    eapply option_univalence; split; intros.\n    eapply LabelMap.find_2 in H.\n    eapply LabelMapFacts.of_list_1 in H.\n    eapply LabelMapFacts.InA_eqke_In in H.\n    eapply in_map_iff in H.\n    openhyp.\n    destruct x; simpl in *.\n    unfold to_bl_pair, to_bedrock_label in *; simpl in *.\n    destruct g; simpl in *.\n    destruct k; simpl in *.\n    injection H; intros; subst.\n    eapply InA_eqke_In in H0.\n    eapply elements_mapsto_iff in H0.\n    eapply find_1; eauto.\n    eapply NoDupKey_to_bl_pair_elements.\n\n    eapply LabelMap.find_1.\n    eapply LabelMapFacts.of_list_1.\n    eapply NoDupKey_to_bl_pair_elements.\n    eapply LabelMapFacts.InA_eqke_In.\n    eapply in_map_iff.\n    exists (k, v); split; eauto.\n    eapply InA_eqke_In.\n    eapply elements_1.\n    eapply find_2.\n    eauto.\n  Qed.\n\n  Lemma to_blm_no_local : forall elt s1 s2 m, @LabelMap.find elt (s1, Local s2) (to_blm m) = None.\n    unfold to_blm, LabelMapFacts.to_map.\n    intros.\n    eapply LabelMapFacts.not_in_find.\n    intuition.\n    eapply LabelMapFacts.In_MapsTo in H.\n    openhyp.\n    eapply LabelMapFacts.of_list_1 in H.\n    eapply LabelMapFacts.InA_eqke_In in H.\n    eapply in_map_iff in H.\n    openhyp.\n    unfold to_bl_pair, to_bedrock_label in *; simpl in *.\n    discriminate.\n    eapply NoDupKey_to_bl_pair_elements.\n  Qed.\n\n  Lemma to_blm_local_not_in : forall elt s1 s2 m, ~ @LabelMap.In elt (s1, Labels.Local s2) (to_blm m).\n    intros.\n    eapply LabelMapFacts.not_find_in_iff.\n    rewrite to_blm_no_local; eauto.\n  Qed.\n\n  Lemma to_blm_mapsto_iff : forall elt k (v : elt) m, LabelMap.MapsTo k v (to_blm m) <-> exists k' : glabel, MapsTo k' v m /\\ k = (k' : label).\n    split; intros.\n    destruct k.\n    destruct l.\n    replace ((s, Labels.Global s0)) with (to_bedrock_label (s, s0)) in * by eauto.\n    eapply LabelMap.find_1 in H.\n    rewrite to_blm_spec in H.\n    eapply find_2 in H.\n    eexists; eauto.\n    eapply LabelMapFacts.MapsTo_In in H.\n    eapply to_blm_local_not_in in H; intuition.\n    openhyp.\n    subst.\n    eapply LabelMap.find_2.\n    rewrite to_blm_spec.\n    eapply find_1; eauto.\n  Qed.\n\n  Lemma to_blm_Equal : forall elt m1 m2, @LabelMap.Equal elt (to_blm m1) (to_blm m2) <-> m1 == m2.\n    unfold Equal, LabelMap.Equal.\n    intuition.\n    repeat erewrite <- to_blm_spec.\n    eauto.\n    destruct y.\n    destruct l.\n    replace ((s, Labels.Global s0)) with (to_bedrock_label (s, s0)) by eauto.\n    repeat erewrite to_blm_spec.\n    eauto.\n    repeat rewrite to_blm_no_local.\n    eauto.\n  Qed.\n\n  Global Add Parametric Morphism elt : (@to_blm elt)\n      with signature Equal ==> LabelMap.Equal as to_blm_Equal_m.\n    intros; eapply to_blm_Equal; eauto.\n  Qed.\n\n  Lemma to_blm_In : forall elt (k : glabel) m, @LabelMap.In elt (k : label) (to_blm m) <-> In k m.\n    split; intros.\n    eapply in_find_iff.\n    eapply LabelMapFacts.in_find_iff in H.\n    rewrite <- to_blm_spec.\n    eauto.\n    eapply in_find_iff in H.\n    eapply LabelMapFacts.in_find_iff.\n    rewrite to_blm_spec.\n    eauto.\n  Qed.\n\n  Lemma to_blm_Compat : forall elt m1 m2, @LabelMapFacts.Compat elt (to_blm m1) (to_blm m2) <-> Compat m1 m2.\n    unfold Compat, LabelMapFacts.Compat.\n    intuition.\n    repeat erewrite <- to_blm_spec.\n    eapply H.\n    eapply to_blm_In; eauto.\n    eapply to_blm_In; eauto.\n    destruct k.\n    destruct l.\n    replace ((s, Labels.Global s0)) with (to_bedrock_label (s, s0)) by eauto.\n    repeat erewrite to_blm_spec.\n    eapply H.\n    eapply to_blm_In; eauto.\n    eapply to_blm_In; eauto.\n    repeat rewrite to_blm_no_local.\n    eauto.\n  Qed.\n\n  Global Add Parametric Morphism elt : (@to_blm elt)\n      with signature (@Compat elt) ==> (@LabelMapFacts.Compat elt) as to_blm_Compat_m.\n    intros; eapply to_blm_Compat; eauto.\n  Qed.\n\n  Lemma to_blm_empty : forall elt, LabelMap.empty elt === {}.\n    unfold Equal, LabelMap.Equal.\n    intuition.\n  Qed.\n\n  Require Import Bedrock.Platform.Cito.GeneralTactics2.\n\n  Lemma to_blm_update : forall elt m1 m2, @LabelMap.Equal elt (to_blm (update m1 m2)) (LabelMapFacts.update (to_blm m1) (to_blm m2)).\n    unfold Equal, LabelMap.Equal.\n    intros.\n    destruct y.\n    destruct l; simpl.\n    replace ((s, Labels.Global s0)) with (to_bedrock_label (s, s0)) by eauto.\n    repeat erewrite to_blm_spec.\n    destruct (In_dec m2 (s, s0)).\n    rewrite update_o_2 by eauto.\n    rewrite LabelMapFacts.update_o_2.\n    repeat erewrite to_blm_spec.\n    eauto.\n    eapply to_blm_In; eauto.\n    rewrite update_o_1 by eauto.\n    rewrite LabelMapFacts.update_o_1.\n    repeat erewrite to_blm_spec.\n    eauto.\n    not_not.\n    eapply to_blm_In; eauto.\n    repeat rewrite to_blm_no_local.\n    symmetry.\n    eapply LabelMapFacts.not_in_find.\n    intuition.\n    eapply LabelMapFacts.update_in_iff in H.\n    openhyp.\n    eapply to_blm_local_not_in; eauto.\n    eapply to_blm_local_not_in; eauto.\n  Qed.\n\n  Lemma to_blm_diff : forall elt m1 m2, @LabelMap.Equal elt (to_blm (diff m1 m2)) (LabelMapFacts.diff (to_blm m1) (to_blm m2)).\n    unfold Equal, LabelMap.Equal.\n    intros.\n    destruct y.\n    destruct l; simpl.\n    replace ((s, Labels.Global s0)) with (to_bedrock_label (s, s0)) by eauto.\n    repeat erewrite to_blm_spec.\n    destruct (In_dec m2 (s, s0)).\n    rewrite diff_o_none by eauto.\n    rewrite LabelMapFacts.diff_o_none.\n    eauto.\n    eapply to_blm_In; eauto.\n    rewrite diff_o by eauto.\n    rewrite LabelMapFacts.diff_o.\n    repeat erewrite to_blm_spec.\n    eauto.\n    not_not.\n    eapply to_blm_In; eauto.\n    repeat rewrite to_blm_no_local.\n    symmetry.\n    eapply LabelMapFacts.not_in_find.\n    intuition.\n    eapply LabelMapFacts.diff_in_iff in H.\n    openhyp.\n    eapply to_blm_local_not_in; eauto.\n  Qed.\n\n  Lemma to_blm_add : forall elt (k : glabel) v m, @LabelMap.Equal elt (to_blm (add k v m)) (LabelMap.add (k : label) v (to_blm m)).\n    unfold Equal, LabelMap.Equal.\n    intros.\n    destruct y.\n    destruct l; simpl.\n    replace ((s, Labels.Global s0)) with (to_bedrock_label (s, s0)) by eauto.\n    repeat erewrite to_blm_spec.\n    rewrite add_o.\n    destruct (eq_dec k (s, s0)).\n    subst.\n    symmetry.\n    rewrite LabelMapFacts.add_eq_o; eauto.\n    rewrite LabelMapFacts.add_neq_o.\n    repeat erewrite to_blm_spec; eauto.\n    not_not.\n    unfold to_bedrock_label in *.\n    destruct k; simpl in *.\n    injection H; intros; subst.\n    eauto.\n    repeat rewrite to_blm_no_local.\n    symmetry.\n    eapply LabelMapFacts.not_in_find.\n    intuition.\n    eapply LabelMapFacts.add_in_iff in H.\n    unfold to_bedrock_label in *.\n    destruct k; simpl in *.\n    openhyp.\n    discriminate.\n    eapply to_blm_local_not_in; eauto.\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/ConvertLabelMap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.25450814684021644}}
{"text": "Require Import Rel.Definitions.\nRequire Import Lang.BindingsFacts.\nRequire Import Lang.Sig.\nRequire Import Lang.SigFacts.\nRequire Import Wf_natnat.\nRequire Import Compat_sub.\nRequire Import Compat_map_EV.\nRequire Import Compat_map_LV.\nSet Implicit Arguments.\n\nImplicit Types EV LV V L : Set.\n\nSection section_EV_bind_aux.\n\nHint 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\n| [ H : _ ⊨ (False)ᵢ |- _ ] => icontradict H\nend.\n\nFixpoint\n  EV_bind_𝓥_aux\n  n EV EV' LV\n  (Ξ : XEnv EV LV)\n  (f : EV → eff ∅ EV' LV ∅)\n  (δ₁ δ₂ : EV → eff0) (δ : EV → IRel 𝓤_Sig)\n  (δ₁' δ₂' : EV' → eff0) (δ' : EV' → IRel 𝓤_Sig)\n  (ρ₁ ρ₂ : LV → lbl0) (ρ : LV → IRel 𝓣_Sig)\n  (Hδ₁ : ∀ α, δ₁ α = subst_eff δ₁' ρ₁ (f α))\n  (Hδ₂ : ∀ α, δ₂ α = subst_eff δ₂' ρ₂ (f α))\n  (Hδ :\n    n ⊨ ∀ᵢ α ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂,\n        𝓾⟦ Ξ ⊢ ef_var α ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂ ⇔\n        𝓤⟦ (EV_bind_XEnv f Ξ) ⊢ f α ⟧ δ₁' δ₂' δ' ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂\n  )\n  (ξ₁ ξ₂ : list var)\n  (v₁ v₂ : val0) (T : ty ∅ EV LV ∅)\n  (W : Acc lt' (n, size_ty T))\n  {struct W} :\n  (n ⊨\n    𝓥⟦ Ξ ⊢ T ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ v₁ v₂ ⇔\n    𝓥⟦ (EV_bind_XEnv f Ξ) ⊢ EV_bind_ty f T ⟧ δ₁' δ₂' δ' ρ₁ ρ₂ ρ ξ₁ ξ₂ v₁ v₂)\nwith\n  EV_bind_𝓜_aux\n  n EV EV' LV\n  (Ξ : XEnv EV LV)\n  (f : EV → eff ∅ EV' LV ∅)\n  (δ₁ δ₂ : EV → eff0) (δ : EV → IRel 𝓤_Sig)\n  (δ₁' δ₂' : EV' → eff0) (δ' : EV' → IRel 𝓤_Sig)\n  (ρ₁ ρ₂ : LV → lbl0) (ρ : LV → IRel 𝓣_Sig)\n  (Hδ₁ : ∀ α, δ₁ α = subst_eff δ₁' ρ₁ (f α))\n  (Hδ₂ : ∀ α, δ₂ α = subst_eff δ₂' ρ₂ (f α))\n  (Hδ :\n    n ⊨ ∀ᵢ α ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂,\n        𝓾⟦ Ξ ⊢ ef_var α ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂ ⇔\n        𝓤⟦ (EV_bind_XEnv f Ξ) ⊢ f α ⟧ δ₁' δ₂' δ' ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂\n  )\n  (ξ₁ ξ₂ : list var)\n  (m₁ m₂ : md0) (σ : ms ∅ EV LV ∅) (ℓ : lbl LV ∅)\n  (W : Acc lt' (n, size_ms σ))\n  {struct W} :\n  (n ⊨\n    𝓜⟦ Ξ ⊢ σ ^ ℓ ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ m₁ m₂ ⇔\n    𝓜⟦ (EV_bind_XEnv f Ξ) ⊢ (EV_bind_ms f σ) ^ ℓ ⟧ δ₁' δ₂' δ' ρ₁ ρ₂ ρ ξ₁ ξ₂ m₁ m₂)\nwith\n  EV_bind_𝓾_aux\n  n EV EV' LV\n  (Ξ : XEnv EV LV)\n  (f : EV → eff ∅ EV' LV ∅)\n  (δ₁ δ₂ : EV → eff0) (δ : EV → IRel 𝓤_Sig)\n  (δ₁' δ₂' : EV' → eff0) (δ' : EV' → IRel 𝓤_Sig)\n  (ρ₁ ρ₂ : LV → lbl0) (ρ : LV → IRel 𝓣_Sig)\n  (Hδ₁ : ∀ α, δ₁ α = subst_eff δ₁' ρ₁ (f α))\n  (Hδ₂ : ∀ α, δ₂ α = subst_eff δ₂' ρ₂ (f α))\n  (Hδ :\n    n ⊨ ∀ᵢ α ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂,\n        𝓾⟦ Ξ ⊢ ef_var α ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂ ⇔\n        𝓤⟦ (EV_bind_XEnv f Ξ) ⊢ f α ⟧ δ₁' δ₂' δ' ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂\n  )\n  (ξ₁ ξ₂ : list var)\n  (t₁ t₂ : tm0) (ψ : IRel 𝓣_Sig) l₁ l₂ (ε : ef ∅ EV LV ∅)\n  (W : Acc lt' (n, 0))\n  {struct W} :\n  (n ⊨\n    𝓾⟦ Ξ ⊢ ε ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂ ⇔\n    𝓤⟦ (EV_bind_XEnv f Ξ) ⊢ EV_bind_ef f ε ⟧ δ₁' δ₂' δ' ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂)\nwith\n  EV_bind_𝓤_aux\n  n EV EV' LV\n  (Ξ : XEnv EV LV)\n  (f : EV → eff ∅ EV' LV ∅)\n  (δ₁ δ₂ : EV → eff0) (δ : EV → IRel 𝓤_Sig)\n  (δ₁' δ₂' : EV' → eff0) (δ' : EV' → IRel 𝓤_Sig)\n  (ρ₁ ρ₂ : LV → lbl0) (ρ : LV → IRel 𝓣_Sig)\n  (Hδ₁ : ∀ α, δ₁ α = subst_eff δ₁' ρ₁ (f α))\n  (Hδ₂ : ∀ α, δ₂ α = subst_eff δ₂' ρ₂ (f α))\n  (Hδ :\n    n ⊨ ∀ᵢ α ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂,\n        𝓾⟦ Ξ ⊢ ef_var α ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂ ⇔\n        𝓤⟦ (EV_bind_XEnv f Ξ) ⊢ f α ⟧ δ₁' δ₂' δ' ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂\n  )\n  (ξ₁ ξ₂ : list var)\n  (t₁ t₂ : tm0) (ψ : IRel 𝓣_Sig) l₁ l₂ (E : eff ∅ EV LV ∅)\n  (W : Acc lt' (n, size_eff E))\n  {struct W} :\n  (n ⊨\n    𝓤⟦ Ξ ⊢ E ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂ ⇔\n    𝓤⟦ (EV_bind_XEnv f Ξ) ⊢ EV_bind_eff f E ⟧ δ₁' δ₂' δ' ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂)\nwith\n  EV_bind_𝓣𝓵_aux\n  n EV EV' LV\n  (Ξ : XEnv EV LV)\n  (f : EV → eff ∅ EV' LV ∅)\n  (δ₁ δ₂ : EV → eff0) (δ : EV → IRel 𝓤_Sig)\n  (δ₁' δ₂' : EV' → eff0) (δ' : EV' → IRel 𝓤_Sig)\n  (ρ₁ ρ₂ : LV → lbl0) (ρ : LV → IRel 𝓣_Sig)\n  (Hδ₁ : ∀ α, δ₁ α = subst_eff δ₁' ρ₁ (f α))\n  (Hδ₂ : ∀ α, δ₂ α = subst_eff δ₂' ρ₂ (f α))\n  (Hδ :\n    n ⊨ ∀ᵢ α ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂,\n        𝓾⟦ Ξ ⊢ ef_var α ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂ ⇔\n        𝓤⟦ (EV_bind_XEnv f Ξ) ⊢ f α ⟧ δ₁' δ₂' δ' ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂\n  )\n  (ξ₁ ξ₂ : list var)\n  (t₁ t₂ : tm0) (ℓ : lbl LV ∅)\n  (W : Acc lt' (n, size_lbl Ξ ℓ))\n  {struct W} :\n  (n ⊨\n    𝓣𝓵⟦ Ξ ⊢ ℓ ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ⇔\n    𝓣𝓵⟦ (EV_bind_XEnv f Ξ) ⊢ ℓ ⟧ δ₁' δ₂' δ' ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂)\n.\n\nProof.\n{\ndestruct T as [ | Ta Ea Tb Eb | N ℓ | σ ℓ ] eqn:HT ; simpl 𝓥_Fun.\n+ auto.\n+ auto_contr.\n  apply 𝓚_Fun_nonexpansive ; repeat iintro ;\n  apply 𝓣_Fun_Fix'_nonexpansive ; repeat iintro ; auto.\n+ auto_contr.\n  apply 𝓥_roll_unroll_iff.\n  match goal with\n  | [ |- ?n ⊨ 𝓥⟦ _ ⊢ ?T ⟧ _ _ _ _ _ _ _ _ _ _ ⇔\n              𝓥⟦ _ ⊢ ?T' ⟧ _ _ _ _ _ _ _ _ _ _ ] =>\n    replace T' with (EV_bind_ty f T)\n    by (simpl ; erewrite EV_bind_it_msig ; crush)\n  end.\n  apply EV_bind_𝓥_aux ; auto.\n+ auto_contr.\n  apply EV_bind_𝓜_aux ; auto.\n}\n\n{\ndestruct σ as [ τ | τ | τ | Ta Ea ] eqn:Hσ ; simpl 𝓜_Fun.\n+ auto_contr.\n  erewrite <- EV_bind_map_XEnv ; [ | ].\n  apply EV_bind_𝓜_aux ; [ | | | auto ].\n  - intro α ; destruct α ; simpl ; [ rewrite app_nil_r ; reflexivity | ].\n    rewrite Hδ₁.\n    erewrite LV_bind_EV_map_eff, EV_bind_map_eff, EV_map_eff_id ; try reflexivity.\n    intro ; erewrite EV_map_eff_id ; reflexivity.\n  - intro α ; destruct α ; simpl ; [ rewrite app_nil_r ; reflexivity | ].\n    rewrite Hδ₂.\n    erewrite LV_bind_EV_map_eff, EV_bind_map_eff, EV_map_eff_id ; try reflexivity.\n    intro ; erewrite EV_map_eff_id ; reflexivity.\n  - iintro α ; repeat iintro ; destruct α ; simpl.\n    * isplit ; iintro' H ; [ ileft | idestruct H as H H ] ; auto.\n    * iespecialize Hδ.\n      eapply I_iff_transitive ; [ apply Hδ | ].\n      replace (EV_bind_XEnv (EV_lift_inc f) (EV_shift_XEnv Ξ))\n      with (EV_shift_XEnv (EV_bind_XEnv f Ξ))\n      by (erewrite EV_bind_map_XEnv ; reflexivity).\n      apply EV_map_𝓤 ; auto.\n      repeat iintro ; simpl ; apply auto_contr_id.\n  - reflexivity.\n+ auto_contr.\n  erewrite <- EV_bind_LV_map_XEnv ; [ | ].\n  apply EV_bind_𝓜_aux ; [ | | | auto ].\n  - intro ; rewrite Hδ₁.\n    unfold compose.\n    erewrite LV_bind_map_eff, EV_bind_LV_map_eff, LV_map_eff_id ; try reflexivity.\n    * intro ; erewrite LV_map_eff_id ; reflexivity.\n    * intro ; erewrite LV_map_lbl_id ; reflexivity.\n  - intro ; rewrite Hδ₂.\n    unfold compose.\n    erewrite LV_bind_map_eff, EV_bind_LV_map_eff, LV_map_eff_id ; try reflexivity.\n    * intro ; erewrite LV_map_eff_id ; reflexivity.\n    * intro ; erewrite LV_map_lbl_id ; reflexivity.\n  - iintro α ; repeat iintro.\n    iespecialize Hδ ; unfold compose.\n    eapply I_iff_transitive ; [ apply Hδ | ].\n    clear.\n    erewrite EV_bind_LV_map_XEnv ; [ | reflexivity ].\n    apply LV_map_𝓤 ;\n    try (simpl ; reflexivity) ;\n    try (repeat iintro ; simpl ; apply auto_contr_id).\n  - auto.\n+ auto_contr.\n  - apply EV_bind_𝓥_aux ; auto.\n  - apply EV_bind_𝓜_aux ; auto.\n+ rewrite EV_bind_XEnv_dom.\n  auto_contr.\n  apply 𝓗_Fun_nonexpansive ; repeat iintro.\n  - apply 𝓣_Fun_Fix'_nonexpansive ; repeat iintro ; [ auto | ].\n    auto_contr.\n    * apply 𝓗_Fun_nonexpansive ; repeat iintro ; [ auto_contr | ].\n      apply EV_bind_𝓣𝓵_aux ; auto.\n    * apply EV_bind_𝓤_aux ; auto.\n  - apply EV_bind_𝓣𝓵_aux ; auto. \n}\n\n{\ndestruct ε as [ | α | [ α | [ α | X ] ] ] ; simpl.\n+ auto.\n+ iespecialize Hδ ; apply Hδ.\n+ isplit ; iintro' H ; [ ileft ; apply H | ].\n  idestruct H as H H ; [ apply H | auto ].\n+ destruct α.\n+ match goal with\n  | [ |- n ⊨ ?P ⇔ ?Q ∨ᵢ (False)ᵢ ] =>\n    cut (n ⊨ P ⇔ Q)\n  end.\n  { clear ; intro H.\n    isplit ; iintro' H' ; [ ileft | idestruct H' as H' H' ; [ | auto ] ].\n    + erewrite <- I_iff_elim_M ; eassumption.\n    + erewrite I_iff_elim_M ; eassumption.\n  }\n  rewrite EV_bind_XEnv_dom.\n  auto_contr.\n  apply 𝓗_Fun_nonexpansive ; repeat iintro.\n  - auto_contr.\n  - destruct (get X Ξ) as [ [T E] | ] eqn:HX.\n    * eapply binds_EV_bind in HX ; rewrite HX.\n      apply 𝓣_Fun_Fix'_nonexpansive ; repeat iintro.\n      { apply 𝓥_roll_unroll_iff ; auto. }\n      { apply 𝓤_roll_unroll_iff ; auto. }\n    * apply get_none_inv in HX.\n      erewrite <- EV_bind_XEnv_dom in HX.\n      apply get_none in HX.\n      rewrite HX ; auto_contr.\n}\n\n{\ndestruct E as [ | ε E ] ; simpl ; [ auto | ].\nisplit ; iintro' H.\n+ idestruct H as H H.\n  - eapply ccompat_se with (E := EV_bind_ef f ε).\n    * crush.\n    * erewrite <- I_iff_elim_M ; [ apply H | ].\n      apply EV_bind_𝓾_aux ; auto.\n  - apply ccompat_se with (E := EV_bind_eff f E).\n    * crush.\n    * erewrite <- I_iff_elim_M ; [ apply H | ].\n      apply EV_bind_𝓤_aux ; auto.\n+ apply ccompat_eff_In_inverse in H.\n  destruct H as [ε' [Hε' H]].\n  apply in_app_or in Hε'.\n  destruct Hε' as [Hε' | Hε'] ; [ ileft | iright ].\n  - eapply ccompat_eff_In in Hε' ; [ clear H | apply H ].\n    erewrite I_iff_elim_M ; [ apply Hε' | ].\n    apply EV_bind_𝓾_aux ; auto.\n  - eapply ccompat_eff_In in Hε' ; [ clear H | apply H ].\n    erewrite I_iff_elim_M ; [ apply Hε' | ].\n    apply EV_bind_𝓤_aux ; auto.\n}\n\n{\ndestruct ℓ as [ α | [ | X ] ] ; simpl ; [ auto_contr | auto_contr | ].\ndestruct (get X Ξ) as [ [T E] | ] eqn:HX.\n* simpl in W ; rewrite HX in W.\n  eapply binds_EV_bind in HX as HX'; rewrite HX'.\n  apply 𝓣_Fun_Fix'_nonexpansive ; repeat iintro.\n  { apply 𝓥_roll_unroll_iff ; auto. }\n  { apply 𝓤_roll_unroll_iff ; auto. }\n* apply get_none_inv in HX.\n  erewrite <- EV_bind_XEnv_dom in HX.\n  apply get_none in HX.\n  rewrite HX ; auto_contr.\n}\n\nQed.\n\nEnd section_EV_bind_aux.\n\n\nSection section_EV_bind.\nContext (n : nat).\nContext (EV EV' LV : Set).\nContext (Ξ : XEnv EV LV).\nContext (f : EV → eff ∅ EV' LV ∅).\nContext (δ₁ δ₂ : EV → eff0) (δ : EV → IRel 𝓤_Sig).\nContext (δ₁' δ₂' : EV' → eff0) (δ' : EV' → IRel 𝓤_Sig).\nContext (ρ₁ ρ₂ : LV → lbl0) (ρ : LV → IRel 𝓣_Sig).\nContext (Hδ₁ : ∀ α, δ₁ α = subst_eff δ₁' ρ₁ (f α)).\nContext (Hδ₂ : ∀ α, δ₂ α = subst_eff δ₂' ρ₂ (f α)).\nContext (Hδ :\n  n ⊨ ∀ᵢ α ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂,\n      𝓾⟦ Ξ ⊢ ef_var α ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂ ⇔\n      𝓤⟦ (EV_bind_XEnv f Ξ) ⊢ f α ⟧ δ₁' δ₂' δ' ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂\n).\n\nHint Resolve lt'_wf.\n\nLemma EV_bind_𝓥 T ξ₁ ξ₂ v₁ v₂ :\nn ⊨\n  𝓥⟦ Ξ ⊢ T ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ v₁ v₂ ⇔\n  𝓥⟦ (EV_bind_XEnv f Ξ) ⊢ EV_bind_ty f T ⟧ δ₁' δ₂' δ' ρ₁ ρ₂ ρ ξ₁ ξ₂ v₁ v₂.\nProof.\napply EV_bind_𝓥_aux ; auto.\nQed.\n\nLemma EV_bind_𝓜 σ ℓ ξ₁ ξ₂ m₁ m₂ :\nn ⊨\n  𝓜⟦ Ξ ⊢ σ ^ ℓ ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ m₁ m₂ ⇔\n  𝓜⟦ (EV_bind_XEnv f Ξ) ⊢ (EV_bind_ms f σ) ^ ℓ ⟧ δ₁' δ₂' δ' ρ₁ ρ₂ ρ ξ₁ ξ₂ m₁ m₂.\nProof.\napply EV_bind_𝓜_aux ; auto.\nQed.\n\nLemma EV_bind_𝓤 E ξ₁ ξ₂ t₁ t₂ ψ L₁ L₂ :\nn ⊨\n  𝓤⟦ Ξ ⊢ E ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ψ L₁ L₂ ⇔\n  𝓤⟦ (EV_bind_XEnv f Ξ) ⊢ EV_bind_eff f E ⟧ δ₁' δ₂' δ' ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ψ L₁ L₂.\nProof.\napply EV_bind_𝓤_aux ; auto.\nQed.\n\nHint Resolve EV_bind_𝓥 EV_bind_𝓤.\n\nLemma EV_bind_𝓣 T E ξ₁ ξ₂ t₁ t₂ :\nn ⊨\n  𝓣⟦ Ξ ⊢ T # E ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ⇔\n  𝓣⟦ (EV_bind_XEnv f Ξ) ⊢ (EV_bind_ty f T) # (EV_bind_eff f E) ⟧\n  δ₁' δ₂' δ' ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂.\nProof.\napply 𝓣_Fun_Fix'_nonexpansive ; repeat iintro ; auto.\nQed.\n\nEnd section_EV_bind.\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_bind_EV.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.25450389730041323}}
{"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 Coq.Program.Equality String.\nRequire Import Definitions Subenvironments Weakening.\n\n(** * Narrowing Lemma *)\n(** The narrowing lemma states that typing is preserved under subenvironments.\n    The lemma corresponds to Lemma 3.11 in the paper.\n    The proof is by mutual induction on term typing, definition typing,\n    and subtyping. *)\n\n(** [G ⊢ t: T]                 #<br>#\n    [G' subG G]                #<br>#\n    [ok G']                    #<br>#\n    [―――――――――――――――――]        #<br>#\n    [G' ⊢ t: T]\n\n    and\n\n    [G ⊢ d: D]                 #<br>#\n    [G' subG G]                #<br>#\n    [ok G']                    #<br>#\n    [―――――――――――――――――]        #<br>#\n    [G' ⊢ d: D]\n\n    and\n\n    [G ⊢ ds :: T]              #<br>#\n    [G' subG G]                #<br>#\n    [ok G']                    #<br>#\n    [―――――――――――――――――]        #<br>#\n    [G' ⊢ ds :: T]\n\n    and\n\n    [G ⊢ S <: U]               #<br>#\n    [G' subG G]                #<br>#\n    [ok G']                    #<br>#\n    [―――――――――――――――――]        #<br>#\n    [G' ⊢ S <: U]              #<br>#\n\nNote: for simplicity, the definition typing judgements and [ok] conditions\n      are omitted from the paper formulation. *)\nLemma narrow_rules:\n  (forall G t T, G ⊢ t : T -> forall G',\n    G' ⪯ G ->\n    G' ⊢ t : T)\n/\\ (forall G d D, G /- d : D -> forall G',\n    G' ⪯ G ->\n    G' /- d : D)\n/\\ (forall G ds T, G /- ds :: T -> forall G',\n    G' ⪯ G ->\n    G' /- ds :: T)\n/\\ (forall G S U, G ⊢ S <: U -> forall G',\n    G' ⪯ G ->\n    G' ⊢ S <: U).\nProof.\n    apply rules_mutind; intros;\n    match goal with\n    | [ B: binds _ _ _, H : ?G' ⪯ _ |- _ ⊢ trm_var (avar_f _) : _ ] =>\n      induction H; [auto | apply binds_push_inv in B];\n        destruct_all; [ subst; eapply ty_sub | idtac];\n          eauto using ty_var, weaken_subtyp, weaken_ty_trm\n    | _ => try fresh_constructor; eauto\n    end.\nQed.\n\n(** The narrowing lemma, formulated only for term typing. *)\nLemma narrow_typing: forall G G' t T,\n  G ⊢ t : T ->\n  G' ⪯ G ->\n  G' ⊢ t : T.\nProof.\n  intros. apply* narrow_rules.\nQed.\n\n(** The narrowing lemma, formulated only for subtyping. *)\nLemma narrow_subtyping: forall G G' S U,\n  G ⊢ S <: U ->\n  G' ⪯ G ->\n  G' ⊢ S <: U.\nProof.\n  intros. apply* narrow_rules.\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/Narrowing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2544892186908187}}
{"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\nDefinition load8 id ofs :=\n (Sset id\n      (Ederef\n        (Ebinop Oadd\n          (Efield\n            (Ederef (Etempvar _ctx (tptr t_struct_SHA256state_st))\n              t_struct_SHA256state_st) _h (tarray tuint 8))\n          (Econst_int (Int.repr ofs) tint) (tptr tuint)) tuint)).\n\nLemma Znth_is_int:\n forall i r,\n  0 <=  i < Zlength r ->\n  is_int I32 Unsigned (Znth i (map Vint r)).\nProof.\nintros.\nunfold Znth.\nrewrite if_false by omega.\nrewrite (nth_map' Vint Vundef Int.zero).\napply I.\ndestruct H as [H0 H]; rewrite Zlength_correct in H.\nrewrite <- (Z2Nat.id i) in H; auto.\napply Nat2Z.inj_lt in H; auto.\nQed.\n\nLemma sha256_block_load8:\n  forall (Espec : OracleKind)\n     (data: val) (r_h: list int) (ctx: val) gv (wsh: share)\n   (Hwsh: writable_share wsh)\n   (H5 : length r_h = 8%nat),\n     semax\n         (func_tycontext f_sha256_block_data_order Vprog Gtot nil)\n  (PROP  ()\n   LOCAL  (temp _data data; temp _ctx ctx; temp _in data;\n                gvars gv)\n   SEP  (field_at wsh t_struct_SHA256state_st  [StructField _h] (map Vint r_h) ctx))\n   (Ssequence (load8 _a 0)\n     (Ssequence (load8 _b 1)\n     (Ssequence (load8 _c 2)\n     (Ssequence (load8 _d 3)\n     (Ssequence (load8 _e 4)\n     (Ssequence (load8 _f 5)\n     (Ssequence (load8 _g 6)\n     (Ssequence (load8 _h 7)\n         Sskip))))))))\n  (normal_ret_assert\n  (PROP  ()\n   LOCAL  (temp _a (Vint (nthi r_h 0));\n                temp _b (Vint (nthi r_h 1));\n                temp _c (Vint (nthi r_h 2));\n                temp _d (Vint (nthi r_h 3));\n                temp _e (Vint (nthi r_h 4));\n                temp _f (Vint (nthi r_h 5));\n                temp _g (Vint (nthi r_h 6));\n                temp _h (Vint (nthi r_h 7));\n                temp _data data; temp _ctx ctx; temp _in data;\n                gvars gv)\n   SEP  (field_at wsh t_struct_SHA256state_st  [StructField _h] (map Vint r_h) ctx))).\nProof.\nintros.\nunfold load8.\nabbreviate_semax.\nassert (H5': Zlength r_h = 8%Z)\n  by (rewrite Zlength_correct; rewrite H5; reflexivity).\ndo 8 forward.\nentailer!.\nQed.\n\nDefinition get_h (n: Z) :=\n    Sset _t\n        (Ederef\n           (Ebinop Oadd\n              (Efield\n                 (Ederef (Etempvar _ctx (tptr t_struct_SHA256state_st))\n                    t_struct_SHA256state_st) _h (tarray tuint 8))\n              (Econst_int (Int.repr n) tint) (tptr tuint)) tuint).\n\nDefinition add_h (n: Z) (i: ident) :=\n   Sassign\n       (Ederef\n          (Ebinop Oadd\n             (Efield\n                (Ederef (Etempvar _ctx (tptr t_struct_SHA256state_st))\n                   t_struct_SHA256state_st) _h (tarray tuint 8))\n             (Econst_int (Int.repr n) tint) (tptr tuint)) tuint)\n       (Ebinop Oadd (Etempvar _t tuint) (Etempvar i tuint) tuint).\n\nDefinition add_them_back :=\n [get_h 0; add_h 0 _a;\n  get_h 1; add_h 1 _b;\n  get_h 2; add_h 2 _c;\n  get_h 3; add_h 3 _d;\n  get_h 4; add_h 4 _e;\n  get_h 5; add_h 5 _f;\n  get_h 6; add_h 6 _g;\n  get_h 7; add_h 7 _h].\n\nFixpoint add_upto (k: nat) (u v: list int) {struct k} :=\n match k with\n | O => u\n | S k' => match u,v with\n                | u1::us, v1::vs => Int.add u1 v1 :: add_upto k' us vs\n                | _, _ => u\n                end\n end.\n\nLemma length_add_upto:\n  forall i r s,\n   length r = length s  ->\n   length (add_upto i r s) = length r.\nProof.\ninduction i; destruct r,s; intros;\n inv H; simpl; auto.\nQed.\n\n\nLemma force_lengthn_short:\n  forall {A} i (b: list A) v,\n     (i <= length b)%nat -> force_lengthn i b v = firstn i b.\nProof.\ninduction i; destruct b; intros.\nreflexivity.\nreflexivity.\ninv H.\nsimpl. f_equal. apply IHi. simpl in H. omega.\nQed.\n\nLemma add_upto_S:\n  forall (atoh regs : list int) (i : nat),\n  length atoh = 8%nat ->\n  length regs = 8%nat ->\n   (i < 8)%nat ->\n  map Vint (add_upto (S i) regs atoh) =\n  upd_Znth (Z.of_nat i) (map Vint (add_upto i regs atoh))\n   (Vint\n     (Int.add (nthi (add_upto i regs atoh) (Z.of_nat i))\n        (nthi atoh (Z.of_nat i)))).\nProof.\nintros. rename H1 into H4.\n assert ( i < length (add_upto i regs atoh))%nat\n    by (rewrite length_add_upto; omega).\n unfold upd_Znth.\n rewrite !sublist_map, <- map_cons, <- map_app.\n f_equal.\n\nassert (H18: length regs = length atoh) by congruence.\nassert (H19: (i < length regs)%nat) by omega.\nclear - H18 H19.\nrevert regs atoh H18 H19; induction i; destruct regs,atoh; intros;\ntry solve [inv H19]; inv H18.\nsimpl.\nf_equal.\nchange (i::regs) with ([i]++regs).\nautorewrite with sublist. auto.\nsimpl in H19.\nchange (add_upto (S (S i)) (i0 :: regs) (i1 :: atoh))\n  with (Int.add i0 i1 :: add_upto (S i) regs atoh).\nsimpl in H19.\nrewrite (IHi regs atoh); auto; [ | omega].\nclear IHi.\nsimpl add_upto.\nrewrite (sublist_split 0 1 (Z.of_nat (S i))); try omega.\nchange (@sublist int 0 1) with (@sublist int 0 (0+1)).\nrewrite sublist_len_1; try omega.\nrewrite inj_S.\nsimpl.\nautorewrite with sublist.\nf_equal.\nf_equal.\nchange (cons (Int.add i0 i1)) with (app [Int.add i0 i1]).\nrewrite sublist_app2 by (autorewrite with sublist; omega).\nf_equal.\nautorewrite with sublist; omega.\nf_equal.\nf_equal.\nunfold nthi.\nrewrite Z2Nat.inj_succ by omega.\nreflexivity.\nunfold nthi.\nrewrite Z2Nat.inj_succ by omega.\nreflexivity.\nchange (cons (Int.add i0 i1)) with (app [Int.add i0 i1]).\nrewrite sublist_app2 by (autorewrite with sublist; omega).\nf_equal.\nautorewrite with sublist; omega.\nautorewrite with sublist; omega.\nautorewrite with sublist. Omega1.\nrewrite inj_S.\nsplit; try omega.\nrewrite Zlength_cons.\nunfold Z.succ.\napply Zplus_le_compat_r.\nrewrite Zlength_correct.\nrewrite length_add_upto; auto.\napply Nat2Z.inj_le; auto.\nomega.\nQed.\n\nLemma upd_reptype_array_gso: (* perhaps move to floyd? *)\n forall t (a: list (reptype t)) v i j,\n    0 <= j <= Zlength a ->\n    0 <= i < Zlength a ->\n    i<>j ->\n    Znth i (upd_Znth j a v) = Znth i a.\nProof.\nintros.\nunfold upd_Znth.\nassert (i<j \\/ i>j) by omega.\nclear H1; destruct H2.\nautorewrite with sublist; auto.\nautorewrite with sublist; auto.\nchange (cons v) with (app [v]).\nautorewrite with sublist; auto.\nf_equal; omega.\nQed.\n\nLemma int_add_upto:\n  forall (regs atoh: list int),\n   Datatypes.length regs = 8%nat ->\n   Datatypes.length atoh = 8%nat ->\n   forall (j:nat)  (i:Z),\n     j = Z.to_nat i ->\n     0 <= i < 8 ->\n     is_int I32 Unsigned (Znth i (map Vint (add_upto j  regs atoh))).\nProof.\nintros until 2.\n  assert (ZR: Zlength regs = 8) by ( rewrite Zlength_correct, H; reflexivity).\n  induction j; intros.\n  simpl. apply Znth_is_int; omega.\n  unfold Znth.\n  rewrite if_false by omega.\n rewrite nth_map' with (d' := Int.zero).\n  apply I.\n  rewrite length_add_upto by omega.\n  rewrite H. apply Nat2Z.inj_lt.\n  rewrite Z2Nat.id by omega. apply H2.\nQed.\n\n\nLemma add_s:\n  forall (regs atoh: list int),\n   Datatypes.length regs = 8%nat ->\n   Datatypes.length atoh = 8%nat ->\n forall i i',\n    (i < 8)%nat ->\n    i' = Z.of_nat i ->\n    upd_Znth i' (map Vint (add_upto i regs atoh))\n             (Vint\n                (Int.add\n                   (Znth i' (add_upto i regs atoh))\n                   (nthi atoh i'))) =\n     map Vint (add_upto (S i) regs atoh).\nProof.\nintros.\nassert (is_int I32 Unsigned (Znth i' (map Vint (add_upto i regs atoh)))).\n apply  Znth_is_int.   rewrite Zlength_correct, length_add_upto, H.\n change (Z.of_nat 8) with 8; omega. rewrite H,H0;  auto.\nsubst i'.\nrewrite add_upto_S; try omega.\nf_equal.\ndestruct (Znth (Z.of_nat i) (map Vint (add_upto i regs atoh)));\n   try contradiction H3.\nsimpl.\nf_equal. f_equal.\nunfold Znth. rewrite if_false by omega.\nunfold nthi.\nrewrite Nat2Z.id. auto.\nQed.\n\nLemma add_upto_8:\n  forall (regs atoh: list int),\n   Datatypes.length regs = 8%nat ->\n   Datatypes.length atoh = 8%nat ->\n    add_upto 8 regs atoh = map2 Int.add regs atoh.\nProof.\nintros.\ndestruct atoh as [ | a [ | b [ | c [ | d [ | e [ | f [ | g [ | h [ | ]]]]]]]]]; inv H0.\ndestruct regs as [ | a' [ | b' [ | c' [ | d' [ | e' [ | f' [ | g' [ | h' [ | ]]]]]]]]]; inv H.\nsimpl; auto.\nQed.\n\nLemma add_them_back_proof:\n  forall (Espec : OracleKind)\n     (regs regs': list int) (ctx: val) gv (wsh: share) (Hwsh: writable_share wsh),\n     length regs = 8%nat ->\n     length regs' = 8%nat ->\n     semax  (func_tycontext f_sha256_block_data_order Vprog Gtot nil)\n   (PROP  ()\n   LOCAL  (temp _ctx ctx;\n                temp _a  (Vint (nthi regs' 0));\n                temp _b  (Vint (nthi regs' 1));\n                temp _c  (Vint (nthi regs' 2));\n                temp _d  (Vint (nthi regs' 3));\n                temp _e  (Vint (nthi regs' 4));\n                temp _f  (Vint (nthi regs' 5));\n                temp _g  (Vint (nthi regs' 6));\n                temp _h  (Vint (nthi regs' 7));\n                gvars gv)\n   SEP\n   (field_at wsh t_struct_SHA256state_st  [StructField _h] (map Vint regs) ctx))\n   (sequence add_them_back Sskip)\n  (normal_ret_assert\n   (PROP() LOCAL(temp _ctx ctx; gvars gv)\n    SEP (field_at wsh t_struct_SHA256state_st  [StructField _h]\n                (map Vint (map2 Int.add regs regs')) ctx))).\nProof.\nintros.\nrename regs' into atoh.\nunfold sequence, add_them_back.\nchange regs with  (add_upto 0 regs atoh) at 1.\nunfold get_h, add_h.\nabbreviate_semax.\nassert (ZR: Zlength regs = 8) by (rewrite Zlength_correct, H; reflexivity).\nassert (INT_ADD_UPTO := int_add_upto _ _ H H0).\nassert (ADD_S := add_s _ _ H H0).\n\nOpaque add_upto.\nassert (forall i i', i'=Z.of_nat i -> 0<= i' <8 -> 0 <= i' < Zlength (add_upto i regs atoh)). {\n intros;\n rewrite Zlength_correct; rewrite length_add_upto by omega;\n rewrite H; simpl; omega.\n}\nassert (0<=0) by computable.\nforward.\nforward.\nautorewrite with sublist.\nrewrite ADD_S by (try reflexivity; clear; omega).\nforward; forward.\nautorewrite with sublist.\nsimpl upd_Znth; rewrite ADD_S by (try reflexivity; clear; omega).\nforward; forward.\nautorewrite with sublist.\nsimpl upd_Znth; rewrite ADD_S by (try reflexivity; clear; omega).\nforward; forward.\nautorewrite with sublist.\nsimpl upd_Znth; rewrite ADD_S by (try reflexivity; clear; omega).\nforward; forward.\nautorewrite with sublist.\nsimpl upd_Znth; rewrite ADD_S by (try reflexivity; clear; omega).\nforward; forward.\nautorewrite with sublist.\nsimpl upd_Znth; rewrite ADD_S by (try reflexivity; clear; omega).\nforward; forward.\nautorewrite with sublist.\nsimpl upd_Znth; rewrite ADD_S by (try reflexivity; clear; omega).\nforward; forward.\nautorewrite with sublist.\nsimpl upd_Znth; rewrite ADD_S by (try reflexivity; clear; omega).\nrewrite (add_upto_8 _ _ H H0).\nentailer!.\nQed.\n\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/sha/verif_sha_bdo8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632683808532, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2544892117566309}}
{"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 projection_orthogonale.\nRequire Export angles_droites.\nSet Implicit Arguments.\nUnset Strict Implicit.\n \nLemma deux_hauteurs_trois :\n forall A B C H : PO,\n orthogonal (vec H A) (vec B C) ->\n orthogonal (vec H B) (vec A C) -> orthogonal (vec H C) (vec A B).\nintros.\napply def_orthogonal2.\nreplace (vec H C) with (add_PP (vec H A) (vec A C)) by Ringvec.\nlapply (def_orthogonal (A:=H) (B:=A) (C:=B) (D:=C)); auto; intros.\nlapply (def_orthogonal (A:=H) (B:=B) (C:=A) (D:=C)); auto; intros.\nSimplscal.\nreplace (scalaire (vec H A) (vec A B)) with (scalaire (vec H A) (vec A C)).\nreplace (scalaire (vec H A) (vec A C) + scalaire (vec A C) (vec A B))  with\n (scalaire (add_PP (vec H A) (vec A B)) (vec A C)).\nreplace (add_PP (vec H A) (vec A B)) with (vec H B); auto.\nRingvec.\nSimplscal.\nrewrite (scalaire_sym A B A C); auto.\nreplace (vec A B) with (add_PP (vec A C) (vec C B)).\nSimplscal.\nreplace (vec C B) with (mult_PP (-1) (vec B C)).\nSimplscal.\nrewrite H2; ring.\nRingvec.\nRingvec.\nQed.\n \nLemma triangle_rectangle_une_fois :\n forall A B C : PO,\n triangle A B C ->\n orthogonal (vec A B) (vec A C) ->\n ~ orthogonal (vec A B) (vec B C) /\\ ~ orthogonal (vec A C) (vec C B).\nintros.\ncut (triangle A C B); intros; auto with geo.\nderoule_triangle A C B.\nsplit; [ try assumption | idtac ].\nred in |- *; intros; apply H2.\nelim orthogonal_paralleles with (A := A) (B := B) (C := C) (E := B) (F := C);\n [ intros k H7; try exact H7\n | auto with geo\n | auto with geo\n | auto with geo\n | auto with geo ].\napply colineaire_alignes with (- k + 1); auto.\nreplace (vec A B) with (add_PP (mult_PP (-1) (vec B C)) (vec A C));\n [ idtac | Ringvec ].\nrewrite H7; Ringvec.\nderoule_triangle A B C.\nred in |- *; intros; apply H6.\nelim orthogonal_paralleles with (A := A) (B := C) (C := B) (E := C) (F := B);\n [ intros k H11; try exact H11\n | auto with geo\n | auto with geo\n | auto with geo\n | auto with geo ].\napply colineaire_alignes with (- k + 1); auto.\nreplace (vec A C) with (add_PP (mult_PP (-1) (vec C B)) (vec A B));\n [ idtac | Ringvec ].\nrewrite H11; Ringvec.\nQed.\n \nLemma triangle_distincts_pied_hauteur :\n forall A B C H : PO,\n triangle A B C -> H = projete_orthogonal A B C -> C <> H :>PO.\nintros.\nderoule_triangle A B C.\nelim (def_projete_orthogonal2 (A:=A) (B:=B) (C:=C) (H:=H)); auto; intros.\nred in |- *; intros; apply H2.\nrewrite H8; auto.\nQed.\nRequire Export Droite_espace.\n \nLemma triangle_hauteurs_secantes :\n forall A B C H K : PO,\n triangle A B C ->\n H = projete_orthogonal A B C ->\n K = projete_orthogonal A C B -> concours (droite C H) (droite B K).\nintros.\nderoule_triangle A B C.\nelim (def_projete_orthogonal2 (A:=A) (B:=B) (C:=C) (H:=H)); auto; intros.\nelim (def_projete_orthogonal2 (A:=A) (B:=C) (C:=B) (H:=K)); auto; intros.\ncut (C <> H); intros.\ncut (B <> K); intros.\nelim (position_relative_droites_coplanaires (A:=C) (B:=H) (C:=B) (D:=K));\n auto with geo; intros.\nabsurd (paralleles (droite C H) (droite B K)); auto.\napply angle_non_paralleles; auto.\nrewrite\n (angles_droites_orthogonales (A:=A) (B:=C) (C:=A) (D:=B) (E:=B) (F:=K)\n    (G:=C) (I:=H)); auto with geo.\napply (triangle_distincts_pied_hauteur (A:=A) (B:=C) (C:=B) (H:=K));\n auto with geo.\napply (triangle_distincts_pied_hauteur (A:=A) (B:=B) (C:=C) (H:=H));\n auto with geo.\nQed.\n \nLemma aux :\n forall A B C H K : PO,\n triangle A B C ->\n H = projete_orthogonal A B C :>PO ->\n K = projete_orthogonal A C B :>PO -> ~ alignes C H B \\/ ~ alignes C H K.\nintros.\nderoule_triangle A B C.\nelim (def_projete_orthogonal2 (A:=A) (B:=B) (C:=C) (H:=H)); auto; intros.\nelim (def_projete_orthogonal2 (A:=A) (B:=C) (C:=B) (H:=K)); auto; intros.\ncut (C <> H); intros.\ncut (B <> K); intros.\nelim (classic (orthogonal (vec B A) (vec B C))); intros.\ncut (H = B); intros.\nright; try assumption.\nrewrite H14.\ncut (~ orthogonal (vec A C) (vec B C)); intros.\nred in |- *; intros; apply H15.\nassert (alignes B K C); auto with geo.\nhalignes H17 k.\napply ortho_sym.\nrewrite H18.\nSimplortho.\nelim triangle_rectangle_une_fois with (A := B) (B := A) (C := C);\n [ try clear triangle_rectangle_une_fois; intros | auto with geo | auto ].\nred in |- *; intros; apply H16.\nauto with geo.\napply unicite_projete_orthogonal with (2 := H7) (3 := H8); auto with geo.\nleft.\nred in |- *; intros; apply H13.\nhalignes H14 k.\napply ortho_sym.\nreplace (vec B C) with (mult_PP (-1) (vec C B)); [ idtac | Ringvec ].\nrewrite H15.\nreplace (mult_PP (-1) (mult_PP k (vec C H))) with (mult_PP k (vec H C));\n [ idtac | Ringvec ].\nSimplortho.\napply (triangle_distincts_pied_hauteur (A:=A) (B:=C) (C:=B) (H:=K));\n auto with geo.\napply (triangle_distincts_pied_hauteur (A:=A) (B:=B) (C:=C) (H:=H)); auto.\nQed.\n \nLemma existence_intersection_deux_hauteurs_triangle :\n forall A B C H K : PO,\n triangle A B C ->\n H = projete_orthogonal A B C :>PO ->\n K = projete_orthogonal A C B :>PO ->\n ex (fun I : PO => I = pt_intersection (droite C H) (droite B K) :>PO).\nintros.\ncut (~ alignes C H B \\/ ~ alignes C H K); intros.\napply existence_pt_intersection; auto.\napply (triangle_distincts_pied_hauteur (A:=A) (B:=B) (C:=C) (H:=H)); auto.\napply (triangle_distincts_pied_hauteur (A:=A) (B:=C) (C:=B) (H:=K));\n auto with geo.\napply triangle_hauteurs_secantes with (A := A); auto.\napply aux with (A := A); auto.\nQed.\nParameter orthocentre : PO -> PO -> PO -> PO.\n \nAxiom\n  orthocentre_def :\n    forall A B C H : PO,\n    orthogonal (vec H A) (vec B C) ->\n    orthogonal (vec H B) (vec A C) ->\n    orthogonal (vec H C) (vec A B) -> H = orthocentre A B C :>PO.\n \nAxiom\n  orthocentre_def2 :\n    forall A B C H : PO,\n    H = orthocentre A B C :>PO ->\n    (orthogonal (vec H A) (vec B C) /\\ orthogonal (vec H B) (vec A C)) /\\\n    orthogonal (vec H C) (vec A B).\n \nLemma orthocentre_ordre :\n forall A B C H : PO,\n triangle A B C -> H = orthocentre A B C :>PO -> H = orthocentre C A B :>PO.\nintros.\nelim orthocentre_def2 with (A := A) (B := B) (C := C) (H := H);\n [ intros | auto ].\nelim H2; intros H4 H5; try clear H2; try exact H5.\napply orthocentre_def; auto with geo.\nQed.\n \nLemma orthocentre_permute :\n forall A B C H : PO,\n triangle A B C -> H = orthocentre A B C :>PO -> H = orthocentre B A C :>PO.\nintros.\nelim orthocentre_def2 with (A := A) (B := B) (C := C) (H := H);\n [ intros | auto ].\nelim H2; intros H4 H5; try clear H2; try exact H5.\napply orthocentre_def; auto with geo.\nQed.\n#[export] Hint Immediate orthocentre_ordre orthocentre_permute: geo.\n \nLemma orthocentre_triangle_rectangle :\n forall A B C : PO,\n triangle A B C ->\n orthogonal (vec A B) (vec B C) -> B = orthocentre A B C :>PO.\nintros.\napply orthocentre_def; auto with geo.\nreplace (vec B B) with zero; auto with geo.\nRingvec.\nQed.\n \nLemma intersection_deux_hauteurs_orthocentre_triangle :\n forall A B C H K I : PO,\n triangle A B C ->\n H = projete_orthogonal A B C :>PO ->\n K = projete_orthogonal A C B :>PO ->\n I = pt_intersection (droite C H) (droite B K) :>PO ->\n I = orthocentre A B C :>PO.\nintros A B C H K I H0 H2 H3 H4.\nderoule_triangle A B C.\nelim (def_projete_orthogonal2 (A:=A) (B:=B) (C:=C) (H:=H)); auto; intros.\nelim (def_projete_orthogonal2 (A:=A) (B:=C) (C:=B) (H:=K)); auto; intros.\ncut (C <> H); intros.\ncut (B <> K); intros.\ncut (~ alignes C H B \\/ ~ alignes C H K); intros.\nelim def_pt_intersection2 with (A := C) (B := H) (C := B) (D := K) (I := I);\n [ try clear def_pt_intersection2; intros | auto | auto | auto | auto ].\nhalignes H16 k.\nhalignes H15 k0.\ncut (orthogonal (vec I B) (vec A C) /\\ orthogonal (vec I C) (vec A B));\n intros.\nelim H19; intros H20 H21; try clear H19; try exact H21.\napply orthocentre_def; auto.\napply deux_hauteurs_trois.\nauto with geo.\nauto with geo.\nsplit; [ idtac | try assumption ].\nreplace (vec I B) with (mult_PP (-1) (vec B I)).\nrewrite H17.\nreplace (mult_PP (-1) (mult_PP k (vec B K))) with (mult_PP k (vec K B)).\nSimplortho.\nRingvec.\nRingvec.\nreplace (vec I C) with (mult_PP (-1) (vec C I)).\nrewrite H18.\nreplace (mult_PP (-1) (mult_PP k0 (vec C H))) with (mult_PP k0 (vec H C)).\nSimplortho.\nRingvec.\nRingvec.\napply aux with (A := A); auto.\napply (triangle_distincts_pied_hauteur (A:=A) (B:=C) (C:=B) (H:=K));\n auto with geo.\napply (triangle_distincts_pied_hauteur (A:=A) (B:=B) (C:=C) (H:=H)); auto.\nQed.\n \nLemma orthocentre_intersection_hauteurs :\n forall A B C H K I : PO,\n triangle A B C ->\n H = projete_orthogonal A B C :>PO ->\n K = projete_orthogonal A C B :>PO ->\n I = orthocentre A B C :>PO ->\n I = pt_intersection (droite C H) (droite B K) :>PO.\nintros.\nelim orthocentre_def2 with (A := A) (B := B) (C := C) (H := I);\n [ intros | auto ].\nelim H4; intros H6 H7; try clear H4; try exact H7.\ncut (~ alignes C H B \\/ ~ alignes C H K); intros.\nderoule_triangle A B C.\nelim (def_projete_orthogonal2 (A:=A) (B:=B) (C:=C) (H:=H)); auto; intros.\nelim (def_projete_orthogonal2 (A:=A) (B:=C) (C:=B) (H:=K)); auto; intros.\ncut (C <> H); intros.\ncut (B <> K); intros.\napply def_pt_intersection; auto.\nelim\n orthogonal_colineaires\n  with (A := A) (B := B) (C := H) (D := C) (E := C) (F := I);\n [ intros k H18; try exact H18\n | auto with geo\n | auto with geo\n | auto with geo\n | auto with geo ].\napply colineaire_alignes with (- k); auto.\nrewrite H18; Ringvec.\nelim\n orthogonal_colineaires\n  with (A := A) (B := C) (C := K) (D := B) (E := B) (F := I);\n [ intros k H18; try exact H18\n | auto with geo\n | auto with geo\n | auto with geo\n | auto with geo ].\napply colineaire_alignes with (- k); auto.\nrewrite H18; Ringvec.\napply (triangle_distincts_pied_hauteur (A:=A) (B:=C) (C:=B) (H:=K));\n auto with geo.\napply (triangle_distincts_pied_hauteur (A:=A) (B:=B) (C:=C) (H:=H)); auto.\napply aux with (A := A); auto.\nQed.\n", "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/orthocentre.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.25442669113831146}}
{"text": "Require Export MinBFT.\n(* Require Export CorrectKeys. *)\n\n\nSection MinBFT_at_most_f_byz.\n\n  (*  Context { pk  : @Key }.    if I add this one MinBFT_at_most_f_byz1 complains, but it still does not solve my problem *)\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { minbft_context      : MinBFT_context }.\n  Context { minbft_initial_keys : MinBFT_initial_keys }.\n(*  Context { dm                  : DataMessage }. *)\n  Context { minbft_auth         : MinBFT_auth }.\n  Context { usig_hash : USIG_hash }.\n\n\n  (* This says that all the events [e] _at all time_ that happen\n      at non-faulty locations (not in the [faulty] list are indeed non-faulty *)\n  Definition MinBFT_at_most_f_byz1 (eo : EventOrdering) :=\n    exists (faulty : list Rep),\n      length faulty <= F\n      /\\\n      forall (e : Event),\n        ~ In (loc e) (map MinBFT_replica faulty)\n        -> isCorrect e.\n\n  Lemma MinBFT_at_most_f_byz1_implies :\n    forall (eo : EventOrdering) L,\n      MinBFT_at_most_f_byz1 eo -> AXIOM_exists_at_most_f_faulty L F.\n  Proof.\n    introv atmost.\n    unfold MinBFT_at_most_f_byz1 in *.\n    exrepnd.\n    exists faulty.\n    repnd; dands; auto.\n    introv i j k eqn w.\n    apply atmost0.\n    introv xx; allrw in_map_iff; exrepnd; subst.\n    assert (loc e' = loc e1) as eqloc by eauto with eo.\n    rewrite k in eqloc; rewrite <- xx1 in eqloc; simpl in eqloc; ginv.\n  Qed.\n  Hint Resolve MinBFT_at_most_f_byz1_implies : pbft.\n\n(*  Check (fun i => @M_state_sm_before_event\n                    MinBFT_I_Node\n                    MinBFT_I_Key\n                    MinBFT_I_Msg\n                    baseFunIOusig\n                    2\n                    (MinBFT_replicaSM i)).\n*)\n\n  Definition AXIOM_MinBFT_correct_keys (eo : EventOrdering) :=\n    forall (e : Event) (i : Rep) st,\n      node_has_correct_trace_before e i\n      -> M_state_sm_before_event (MinBFT_replicaSM i) e = st\n      -> st >p>= (fun sop => match sop with\n                            | Some s => ret _ (keys e = local_keys s)\n                            | None => ret _ True\n                            end).\n\n  Definition default_local_key_map : local_key_map :=\n    MkLocalKeyMap [] [].\n\n  Definition MinBFT_get_keys0 (i : name) : MinBFT_nstate i -> local_key_map :=\n    match i with\n    | MinBFT_replica i => fun s => local_keys s\n    | MinBFT_client _  => fun _ => default_local_key_map\n    end.\n\n  Definition MinBFT_get_keys (i : name) : sm2S (MinBFTsys i) -> local_key_map :=\n    match i with\n    | MinBFT_replica i => fun s => local_keys s\n    | MinBFT_client _  => fun _ => default_local_key_map\n    end.\n\n\n Lemma correct_keys_implies_MinBFT_correct_keys :\n   forall {eo : EventOrdering} (e : Event),\n     AXIOM_M_correct_keys\n       (fun name => system2main_local e MinBFTsys)\n       (fun name => MinBFT_get_keys name)\n       eo\n     -> AXIOM_MinBFT_correct_keys eo.\n  Proof.\n    introv cor ctrace eqst.\n    apply (cor e (MinBFT_replica i) st); auto.\n  Qed.\n\n\n  Lemma correct_keys_implies_MinBFT_correct_keys_sys :\n  forall (eo : EventOrdering) (e : Event),\n    AXIOM_M_correct_keys_sys MinBFTsys  e (MinBFT_get_keys name) eo\n    -> AXIOM_MinBFT_correct_keys eo.\n  Proof.\n    introv cor ctrace eqst.\n    apply (cor e (MinBFT_replica i) st); auto.\n  Qed.\n\n\n\n\n  XXXXXXXXXXXXXXXXXXXx\n\n\nEnd MinBFT_at_most_f_byz.\n\n\nHint Resolve MinBFT_at_most_f_byz1_implies : pbft.\n\n\n(***************** old code to be checked ************************\n\n(*  CHECK this one\n Definition AXIOM_M_correct_keys_new\n             {eo   : EventOrdering}\n             (sys  : M_USystem)\n             (K    : forall (e : Event), sm2S (system2main_local e sys) -> local_key_map)\n              : Prop :=\n    forall (e : Event) (i : name) st,\n      has_correct_trace_before e i\n      -> M_state_sm_before_event (system2main_local e sys)  e = st\n      -> st >p>= (fun sop => match sop with\n                             | Some s => ret _ (keys e = K e s)\n                             | None => ret _ True\n                             end).\n *)\n\n  (*  CHECK this one\n  Definition AXIOM_M_correct_keys_new2\n             {eo   : EventOrdering}\n             (sys  : M_USystem)\n             (K  : forall (i : name), sm2S (sys i) -> local_key_map)\n              : Prop :=\n    forall (e : Event) (i : name) st,\n      has_correct_trace_before e i\n      -> M_state_sm_before_event (system2main_local e sys)  e = st\n      -> st >p>= (fun sop => match sop with\n                             | Some s => ret _ (keys e = K i  (sm2S (sys i)))\n                             | None => ret _ True\n                             end).\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/MinBFT_at_most_f_byz.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.25442669113831146}}
{"text": "From Coq Require Import String Arith.\n\nFrom Vyper Require Import Config Map.\nFrom Vyper.L10 Require Import Base.\nFrom Vyper.L50 Require Import Types AST Builtins DynError.\n\nLocal Open Scope list_scope.\n\n(** Lookup all the names in the variable map and check types. \n    The names need not be distinct.\n *)\nFixpoint get_vars_by_typenames {C: VyperConfig}\n                               (typenames: list typename)\n                               (vars: string_map dynamic_value)\n: dynamic_error + list dynamic_value\n:= match typenames with\n   | nil => inr nil\n   | (type, name) :: rest =>\n       match map_lookup vars name as z return (_ = z -> _) with\n       | None => fun _ => inl (DE_CannotResolveLocalVariable name)\n       | Some value => fun found =>\n           let t := projT1 value in \n           if yul_type_eq_dec type t\n             then match get_vars_by_typenames rest vars with\n                  | inl err => inl err\n                  | inr rest_results => inr (value :: rest_results)\n                  end\n             else inl (DE_TypeMismatch type t)\n       end eq_refl\n   end.\n\n(** Bind several variables. This happens to the function arguments right after a call\n    and also in a variable declaration with initializer.\n    The names must be distinct because shadowing is not allowed.\n *)\nFixpoint bind_vars_to_values {C: VyperConfig}\n                             (vars: list typename)\n                             (init: list dynamic_value)\n                             (loc: string_map dynamic_value)\n: dynamic_error + string_map dynamic_value\n:= match vars with\n   | nil =>\n      match init with\n      | nil => inr loc\n      | _ => inl DE_TooManyValues\n      end\n   | (vtype, vname) :: vtail =>\n      match init with\n      | nil => inl DE_TooFewValues\n      | (existT _ itype ivalue as ihead) :: itail =>\n          if yul_type_eq_dec vtype itype then\n            match map_lookup loc vname with\n            | Some _ => inl (DE_LocalNameShadowing vname)\n            | None => bind_vars_to_values vtail itail (map_insert loc vname ihead)\n            end\n          else inl (DE_TypeMismatch vtype itype)\n      end\n   end.\n\n(** Bind several variables to zeros. \n    This happens to the function outputs right after a call\n    and also in a variable declaration without initializer.\n    The names must be distinct because shadowing is not allowed.\n*)\nFixpoint bind_vars_to_zeros {C: VyperConfig}\n                            (vars: list typename)\n                            (loc: string_map dynamic_value)\n: dynamic_error + string_map dynamic_value\n:= match vars with\n   | nil => inr loc\n   | (vtype, vname) :: vtail =>\n        match map_lookup loc vname with\n        | Some _ => inl (DE_LocalNameShadowing vname)\n        | None => bind_vars_to_zeros vtail (map_insert loc vname (existT _ vtype (zero_value vtype)))\n        end\n   end.\n\n(** Rebind several variables. This happens in assignments. *)\nFixpoint rebind_vars_to_values {C: VyperConfig}\n                               (vars: list string)\n                               (rhs: list dynamic_value)\n                               (loc: string_map dynamic_value)\n: dynamic_error + string_map dynamic_value\n:= match vars with\n   | nil =>\n      match rhs with\n      | nil => inr loc\n      | _ => inl DE_TooManyValues\n      end\n   | vname :: vtail =>\n      match rhs with\n      | nil => inl DE_TooFewValues\n      | (existT _ rtype rvalue as rhead) :: rtail =>\n            match map_lookup loc vname with\n            | Some (existT _ vtype _) =>\n                if yul_type_eq_dec vtype rtype\n                  then rebind_vars_to_values vtail rtail (map_insert loc vname rhead)\n                  else inl (DE_TypeMismatch rtype vtype)\n            | None => inl (DE_CannotResolveLocalVariable vname)\n            end\n      end\n   end.\n\nFixpoint unbind_vars {C: VyperConfig}\n                     (vars: list typename)\n                     (loc: string_map dynamic_value)\n: string_map dynamic_value\n:= match vars with\n   | nil => loc\n   | h :: t => unbind_vars t (map_remove loc (snd h))\n   end.\n\nLemma unbind_vars_app {C: VyperConfig}\n                      (a b: list typename)\n                      (loc: string_map dynamic_value):\n  unbind_vars b (unbind_vars a loc) = unbind_vars (a ++ b) loc.\nProof.\nrevert loc. induction a as [|h]; intros. { easy. }\ncbn. apply IHa.\nQed.\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/LocalVars.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.25442669113831146}}
{"text": "\nFrom Coq Require Import ZArith List.\nFrom mathcomp Require Import ssreflect ssrbool ssrnat eqtype seq.\nFrom BitBlasting Require Import TypEnv State QFBV CNF BBCommon.\nFrom ssrlib Require Import Var ZAriths Tactics.\nFrom nbits Require Import NBits.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n\n\n(* ===== bit_blast_var ===== *)\n\nFixpoint bit_blast_var' (g : generator) (w : nat) : generator * word :=\n  match w with\n  | O => (g, [::])\n  | S n => let (g', hd) := gen g in\n           let (g'', tl) := bit_blast_var' g' n in\n           (g'', hd::tl)\n  end.\n\nFixpoint mk_env_var' E g bs : env * generator * word :=\n  match bs with\n  | [::] => (E, g, [::])\n  | bs_hd::bs_tl => let (g', hd) := gen g in\n                    let E' := env_upd E (var_of_lit hd) bs_hd in\n                    let '(E'', g'', tl) := mk_env_var' E' g' bs_tl in\n                    (E'', g'', hd::tl)\n  end.\n\nDefinition bit_blast_var (tenv : SSATE.env) g (v : ssavar) : generator * cnf * word :=\n  let (g', vs) := bit_blast_var' g (SSATE.vsize v tenv) in\n  (g', [::], vs).\n\nDefinition mk_env_var E g (bs : bits) (v : ssavar) : env * generator * cnf * word :=\n  let '(E', g', vs) := mk_env_var' E g bs in\n  (E', g', [::], vs).\n\nLemma bit_blast_var_cnf_empty tenv g v g' cs lrs :\n  bit_blast_var tenv g v = (g', cs, lrs) -> cs = [::].\nProof.\n  rewrite /bit_blast_var. dcase (bit_blast_var' g (SSATE.vsize v tenv)).\n  move=> [g_v lrs_v] Hbb. by case=> _ <- _.\nQed.\n\nLemma mk_env_var'_is_bit_blast_var' E g bs E' g' lrs :\n  mk_env_var' E g bs = (E', g', lrs) -> bit_blast_var' g (size bs) = (g', lrs).\nProof.\n  elim: bs g E E' g' lrs => [|bs_hd bs_tl IH] /=.\n  - by move=> ? ? ? ? ? [] _ <- <-.\n  - move=> ig iE oE og olrs.\n    dcase (mk_env_var' (env_upd iE ig bs_hd) (ig+1)%positive bs_tl).\n    move=> [[E g] lrs] Henv. case=> _ <- <-. by rewrite (IH _ _ _ _ _ Henv).\nQed.\n\nLemma mk_env_var_is_bit_blast_var tenv E g bs v E' g' cs lrs :\n  size bs = SSATE.vsize v tenv -> mk_env_var E g bs v = (E', g', cs, lrs) ->\n  bit_blast_var tenv g v = (g', cs, lrs).\nProof.\n  rewrite /mk_env_var /bit_blast_var. dcase (mk_env_var' E g bs).\n  move=> [[E_env g_env] ls_env] Henv <-. rewrite (mk_env_var'_is_bit_blast_var' Henv).\n  by case=> _ <- <- <-.\nQed.\n\nLemma mk_env_var_sat E g bs v E' g' cs lrs :\n  mk_env_var E g bs v = (E', g', cs, lrs) -> interp_cnf E' cs.\nProof.\n  rewrite /mk_env_var. dcase (mk_env_var' E g bs) => [[[oE og] olrs] Henv].\n  by case=> <- _ <- _.\nQed.\n\nLemma mk_env_var'_preserve E g bs E' g' lrs :\n  mk_env_var' E g bs = (E', g', lrs) -> env_preserve E E' g.\nProof.\n  elim: bs E g E' g' lrs => [| bs_hd bs_tl IH] /=.\n  - move=> ? ? ? ? ? [] <- _ _. exact: env_preserve_refl.\n  - move=> E g E' g' lrs.\n    dcase (mk_env_var' (env_upd E g bs_hd) (g + 1)%positive bs_tl).\n    move=> [[oE og] olrs] Henv. case=> <- _ _. move: (IH _ _ _ _ _ Henv).\n    exact: env_preserve_env_upd_succ.\nQed.\n\nLemma mk_env_var_preserve E g bs v E' g' cs lrs :\n  mk_env_var E g bs v = (E', g', cs, lrs) -> env_preserve E E' g.\nProof.\n  rewrite /mk_env_var. dcase (mk_env_var' E g bs) => [[[oE og] olrs] Henv].\n  case=> <- _ _ _. exact: (mk_env_var'_preserve Henv).\nQed.\n\nLemma mk_env_var'_newer_gen E g bs E' g' lrs :\n  mk_env_var' E g bs = (E', g', lrs) -> (g <=? g')%positive.\nProof.\n  elim: bs E g E' g' lrs => [| bs_hd bs_tl IH] /=.\n  - move=> ? ? ? ? ? [] _ <- _. exact: Pos.leb_refl.\n  - move=> E g E' g' lrs.\n    dcase (mk_env_var' (env_upd E g bs_hd) (g + 1)%positive bs_tl).\n    move=> [[oE og] olrs] Henv. case=> _ <- _. move: (IH _ _ _ _ _ Henv).\n    apply: pos_leb_trans. exact: pos_leb_add_diag_r.\nQed.\n\nLemma mk_env_var_newer_gen E g bs v E' g' cs lrs :\n  mk_env_var E g bs v = (E', g', cs, lrs) -> (g <=? g')%positive.\nProof.\n  rewrite /mk_env_var. dcase (mk_env_var' E g bs) => [[[oE og] olrs] Henv].\n  case=> _ <- _ _. exact: (mk_env_var'_newer_gen Henv).\nQed.\n\nLemma mk_env_var'_newer_res E g bs E' g' lrs :\n  mk_env_var' E g bs = (E', g', lrs) -> newer_than_lits g' lrs.\nProof.\n  elim: bs E g E' g' lrs => [| bs_hd bs_tl IH] /=.\n  - by move=> ? ? ? ? ? [] _ <- <-.\n  - move=> E g E' g' lrs.\n    dcase (mk_env_var' (env_upd E g bs_hd) (g + 1)%positive bs_tl).\n    move=> [[oE og] olrs] Henv. case=> _ <- <-. rewrite newer_than_lits_cons.\n    rewrite (IH _ _ _ _ _ Henv) andbT. rewrite /newer_than_lit /newer_than_var /=.\n    move: (mk_env_var'_newer_gen Henv) => H. apply: (pos_ltb_leb_trans _ H).\n    exact: pos_ltb_add_diag_r.\nQed.\n\nLemma mk_env_var_newer_res E g bs v E' g' cs lrs :\n  mk_env_var E g bs v = (E', g', cs, lrs) -> newer_than_lits g' lrs.\nProof.\n  rewrite /mk_env_var. dcase (mk_env_var' E g bs) => [[[oE og] olrs] Henv].\n  case=> _ <- _ <-. exact: (mk_env_var'_newer_res Henv).\nQed.\n\nLemma mk_env_var_newer_cnf E g bs v E' g' cs lrs :\n  mk_env_var E g bs v = (E', g', cs, lrs) -> newer_than_cnf g' cs.\nProof.\n  rewrite /mk_env_var. dcase (mk_env_var' E g bs) => [[[oE og] olrs] Henv].\n  by case=> _ <- <- _.\nQed.\n\nLemma mk_env_var'_enc E g bs E' g' lrs :\n  mk_env_var' E g bs = (E', g', lrs) -> enc_bits E' lrs bs.\nProof.\n  elim: bs E g E' g' lrs => [| bs_hd bs_tl IH] //=.\n  - by move=> ? ? ? ? ? [] <- _ <-.\n  - move=> E g E' g' lrs.\n    dcase (mk_env_var' (env_upd E g bs_hd) (g + 1)%positive bs_tl).\n    move=> [[oE og] olrs] Henv. case=> <- _ <-. rewrite enc_bits_cons.\n    rewrite (IH _ _ _ _ _ Henv) andbT. move: (mk_env_var'_preserve Henv) => Hpre.\n    apply: (env_preserve_enc_bit Hpre (newer_than_lit_add_diag_r (Pos g) 1)).\n    exact: enc_bit_env_upd_eq_pos.\nQed.\n\nLemma mk_env_var_enc E g bs v E' g' cs lrs :\n  mk_env_var E g bs v = (E', g', cs, lrs) -> enc_bits E' lrs bs.\nProof.\n  rewrite /mk_env_var. dcase (mk_env_var' E g bs) => [[[oE og] olrs] Henv].\n  case=> <- _ _ <-. exact: (mk_env_var'_enc Henv).\nQed.\n\nLemma mk_env_var'_env_equal E1 E2 g bs E1' E2' g1 g2 lrs1 lrs2 :\n  env_equal E1 E2 ->\n  mk_env_var' E1 g bs = (E1', g1, lrs1) ->\n  mk_env_var' E2 g bs = (E2', g2, lrs2) ->\n  env_equal E1' E2' /\\ g1 = g2 /\\ lrs1 = lrs2.\nProof.\n  elim: bs E1 E2 g g1 g2 lrs1 lrs2 => [| b bs IH] //= E1 E2 g g1 g2 lrs1 lrs2 Heq.\n  - case=> ? ? ?; subst. case=> ? ? ?; subst. done.\n  - dcase (mk_env_var' (env_upd E1 g b) (g + 1)%positive bs) => [[[E1'' g1''] tl1] Hv1].\n    dcase (mk_env_var' (env_upd E2 g b) (g + 1)%positive bs) => [[[E2'' g2''] tl2] Hv2].\n    case=> ? ? ?; case=> ? ? ?; subst.\n    move: (IH _ _ _ _ _ _ _ (env_equal_upd g b Heq) Hv1 Hv2) => [H1 [H2 H3]].\n    rewrite H2 H3. done.\nQed.\n\nLemma mk_env_var_env_equal E1 E2 g bs v E1' E2' g1 g2 cs1 cs2 lrs1 lrs2 :\n  env_equal E1 E2 ->\n  mk_env_var E1 g bs v = (E1', g1, cs1, lrs1) ->\n  mk_env_var E2 g bs v = (E2', g2, cs2, lrs2) ->\n  env_equal E1' E2' /\\ g1 = g2 /\\ cs1 = cs2 /\\ lrs1 = lrs2.\nProof.\n  rewrite /mk_env_var => Heq.\n  dcase (mk_env_var' E1 g bs) => [[[E1'' g1''] lrs1''] Hv1].\n  dcase (mk_env_var' E2 g bs) => [[[E2'' g2''] lrs2''] Hv2].\n  case=> ? ? ? ?; case=> ? ? ? ?; subst.\n  move: (mk_env_var'_env_equal Heq Hv1 Hv2) => [H1 [H2 H3]]. done.\nQed.\n\nLemma mk_env_var_consistent s iE im ig v oE og ocs olrs :\n  mk_env_var iE ig (SSAStore.acc v s) v = (oE, og, ocs, olrs) ->\n  newer_than_vm ig im ->\n  consistent im iE s ->\n  consistent (SSAVM.add v olrs im) oE s.\nProof.\n  move=> Henv Hnew Hcon. move=> x. rewrite /consistent1.\n  dcase (SSAVM.find x (SSAVM.add v olrs im)); case => //=.\n  move=> xls. case Hxv: (x == v).\n  - rewrite (SSAVM.Lemmas.find_add_eq Hxv). case=> ?; subst.\n    rewrite (eqP Hxv). exact: (mk_env_var_enc Henv).\n  - move/negP: Hxv => Hxv. rewrite (SSAVM.Lemmas.find_add_neq Hxv) => Hfx.\n    move: (Hcon x). rewrite /consistent1. rewrite Hfx => Henc.\n    move: (Hnew x _ Hfx) => Hnew_igxls.\n    exact: (env_preserve_enc_bits (mk_env_var_preserve Henv) Hnew_igxls Henc).\nQed.\n\n\n(* agree *)\n\nLemma agree_bit_blast_var E1 E2 g v :\n  QFBV.MA.agree (SSAVS.singleton v) E1 E2 ->\n  bit_blast_var E1 g v = bit_blast_var E2 g v.\nProof.\n  move=> Hag. rewrite /bit_blast_var. rewrite (QFBV.MA.agree_vsize_singleton Hag).\n  reflexivity.\nQed.\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/BBVar.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631556226292, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2544266851885185}}
{"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.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. 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/StateExecFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.25442668518851846}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Numbers.BinNums.\nRequire Import Crypto.Compilers.Syntax.\nRequire Import Crypto.Compilers.Named.PositiveContext.\nRequire Import Crypto.Compilers.CountLets.\nRequire Import Crypto.Compilers.Named.NameUtil.\nRequire Import Crypto.Compilers.Named.PositiveContext.Defaults.\nRequire Import Crypto.Util.ListUtil.\nRequire Import Crypto.Util.Option.\nRequire Import Crypto.Util.NatUtil.\nRequire Import Crypto.Util.Tactics.DestructHead.\n\nSection language.\n  Context {base_type_code : Type}\n          {op : flat_type base_type_code -> flat_type base_type_code -> Type}.\n\n  Lemma name_list_unique_map_pos_of_succ_nat_seq a b\n    : name_list_unique (map BinPos.Pos.of_succ_nat (seq a b)).\n  Proof using Type.\n    unfold name_list_unique, oname_list_unique, mname_list_unique.\n    intros k n.\n    rewrite !map_map, firstn_map, skipn_map, firstn_seq, skipn_seq.\n    rewrite !in_map_iff; intros; destruct_head' ex; destruct_head' and; inversion_option; subst.\n    match goal with H : _ |- _ => apply Pnat.SuccNat2Pos.inj in H end; subst.\n    rewrite in_seq in *.\n    omega *.\n  Qed.\n\n  Lemma name_list_unique_default_names_forf {var dummy t e}\n    : name_list_unique (@default_names_forf base_type_code op var dummy t e).\n  Proof using Type. apply name_list_unique_map_pos_of_succ_nat_seq. Qed.\n  Lemma name_list_unique_default_names_for {var dummy t e}\n    : name_list_unique (@default_names_for base_type_code op var dummy t e).\n  Proof using Type. apply name_list_unique_map_pos_of_succ_nat_seq. Qed.\n  Lemma name_list_unique_DefaultNamesFor {t e}\n    : name_list_unique (@DefaultNamesFor base_type_code op t e).\n  Proof using Type. apply name_list_unique_map_pos_of_succ_nat_seq. Qed.\nEnd language.\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/PositiveContext/DefaultsProperties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2544266851885184}}
{"text": "Require Import RefProofDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\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 RefineRel.\n\n  Inductive relate_share: option State -> option State -> Prop :=\n  | RELATE_NONE: relate_share None None\n  | RELATE_SHARE: forall st st'\n                    (id_gs: gs st = gs st')\n                    (id_gpt: gpt st = gpt st')\n                    (id_gpt_lk: gpt_lk st = gpt_lk st')\n                    (id_gpt_lk: tlbs st = tlbs st'),\n      relate_share (Some st) (Some st').\n\n  Record relate_RData (hadt: RData) (ladt: RData) :=\n      mkrelate_RData {\n          id_priv: priv ladt = priv hadt;\n          rel_share: relate_share (Some (share ladt)) (Some (share hadt));\n          hrepl: repl hadt = replay 4;\n          lrepl: repl ladt = replay 3;\n          valid_ho: ValidOracle 4 (oracle hadt);\n          valid_lo: ValidOracle 3 (oracle ladt);\n          rel_oracle: forall st st' l l',\n              let lh := oracle hadt l in\n              let lo := oracle ladt l' in\n              relate_share (Some st) (Some st') -> relate_share (repl ladt lo st) (repl hadt lh st')\n        }.\n\nEnd RefineRel.\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/RefRel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.25438736198029216}}
{"text": "Require Import VST.floyd.base2.\nRequire Import VST.floyd.client_lemmas.\n\nImport LiftNotation.\nLocal Open Scope logic.\n\nLemma typed_true_nullptr:\n forall v t0 t t',\n   typed_true t0 (force_val (sem_cmp Ceq (tptr t) (tptr t') v (Vint Int.zero))) ->\n   v=nullval.\nProof.\n intros.\n simpl in H. rewrite !andb_false_r in H. simpl in H.\n unfold typed_true, force_val, sem_cmp_pp, strict_bool_val, nullval in *.\n destruct Archi.ptr64  eqn:Hp;\n destruct t0, v; inv H;\n unfold sem_cmp_pp, strict_bool_val in H1;\n try (clear i; rename i0 into i);\n pose proof (Int.eq_spec i Int.zero);\n destruct (Int.eq i Int.zero); inv H1; auto.\nQed.\n\n\nLemma typed_true_nullptr':\n  forall  {cs: compspecs} t0  t t' v,\n    typed_true t0 (eval_binop Cop.Oeq (tptr t) (tptr t') v nullval) -> v=nullval.\nProof.\n intros.\n simpl in H. unfold sem_binary_operation' in H.\n unfold tptr, typed_true, force_val, sem_cmp, Cop.classify_cmp, sem_cmp_pp, \n   typeconv, remove_attributes, change_attributes, strict_bool_val, nullval, Val.of_bool in *.\n   rewrite (proj2 (eqb_type_false (Tpointer t noattr) int_or_ptr_type)) in H\n     by (intro Hx; inv Hx).\n   rewrite (proj2 (eqb_type_false (Tpointer t' noattr) int_or_ptr_type)) in H\n     by (intro Hx; inv Hx).\n   simpl in H.\n destruct Archi.ptr64  eqn:Hp;\n destruct t0, v; inv H;\n try solve [revert H1; simple_if_tac; intro H1; inv H1].\n pose proof (Int64.eq_spec i0 Int64.zero);\n destruct (Int64.eq i0 Int64.zero); inv H1; auto.\n pose proof (Int.eq_spec i0 Int.zero);\n destruct (Int.eq i0 Int.zero); inv H1; auto.\nQed.\n\nLemma typed_true_Oeq_nullval:\n forall  {cs: compspecs}  v t t',\n   local (`(typed_true tint) (`(eval_binop Cop.Oeq (tptr t) (tptr t')) v `(nullval))) |--\n   local (`(eq nullval) v).\nProof.\nintros.\n intro rho; unfold local, lift1; unfold_lift.\n apply prop_derives; intro.\n unfold tptr in H; simpl in H. unfold sem_binary_operation' in H.\n simpl in H. rewrite !andb_false_r in H.\n destruct (v rho); inv H.\n unfold sem_cmp_pp, strict_bool_val, nullval in *.\n destruct Archi.ptr64  eqn:Hp; simpl in H1;\n try solve [inv H1];\n try solve [pose proof (Int64.eq_spec i Int64.zero);\n                destruct (Int64.eq i Int64.zero); inv H1; auto];\n try solve [pose proof (Int.eq_spec i Int.zero);\n                destruct (Int.eq i Int.zero); inv H1; auto].\nQed.\n\nDefinition  binary_operation_to_comparison (op: Cop.binary_operation) :=\n match op with\n | Cop.Oeq => Some (@eq Z)\n | Cop.One => Some Zne\n | Cop.Olt => Some Z.lt\n | Cop.Ole => Some Z.le\n | Cop.Ogt => Some Z.gt\n | Cop.Oge => Some Z.ge\n | _ => None\n end.\n\n(*\nLemma typed_true_binop_int:\n  forall op op' e1 e2 Espec  {cs: compspecs} Delta P Q R c Post,\n   binary_operation_to_comparison op = Some op' ->\n   typeof e1 = tint ->\n   typeof e2 = tint ->\n   (PROPx P (LOCALx (tc_env Delta :: Q) (SEPx R))) |--  tc_expr Delta e1 ->\n   (PROPx P (LOCALx (tc_env Delta :: Q) (SEPx R))) |-- tc_expr Delta e2 ->\n  @semax cs Espec Delta (PROPx P (LOCALx\n      (`op' (`force_signed_int (eval_expr e1)) (`force_signed_int (eval_expr e2))\n          :: Q) (SEPx R))) c Post ->\n  @semax cs Espec Delta (PROPx P (LOCALx\n      (`(typed_true\n          (typeof (Ebinop op e1 e2 tint)))\n          (eval_expr (Ebinop op e1 e2 tint)) :: Q) (SEPx R))) c Post.\nProof.\nintros.\neapply semax_pre; [clear H4 | apply H4].\neapply derives_trans with\n (tc_expr Delta e1 && (tc_expr Delta e2\n   && PROPx P (LOCALx (tc_environ Delta :: `(typed_true (typeof (Ebinop op e1 e2 tint)))(eval_expr (Ebinop op e1 e2 tint)) :: Q) (SEPx R)))).\nrewrite <- andp_assoc.\napply andp_right; auto.\ndo 2 rewrite <- insert_local.\nrewrite <- andp_assoc.\nrewrite (andp_comm (local _)).\nrewrite andp_assoc.\napply andp_left2.\nrewrite insert_local.\napply andp_right; auto.\nclear H2 H3.\n(*do 2 rewrite insert_local.*)\nunfold PROPx, LOCALx; intro rho; simpl.\nnormalize.\nautorewrite with norm1 norm2; normalize.\nrewrite <- andp_assoc.\napply andp_derives; auto.\neapply derives_trans.\napply andp_derives; apply typecheck_expr_sound; auto.\nnormalize. split; auto.\nrewrite H1,H0 in *.\nclear H5 H2 H0 H1.\ndestruct (eval_expr e1 rho); inv H6.\ndestruct (eval_expr e2 rho); inv H7.\nunfold force_signed_int, force_int.\nunfold typed_true, eval_binop in H4.\ndestruct op; inv H; simpl in H4.\npose proof (Int.eq_spec i i0); destruct (Int.eq i i0); subst; auto.\n contradiction H4; auto.\nunfold Zne.\npose proof (Int.eq_spec i i0); destruct (Int.eq i i0); subst; auto.\ncontradict H.\nrewrite <- (Int.repr_signed i).\nrewrite <- (Int.repr_signed i0).\nf_equal; auto.\nunfold Int.lt in H4.\ndestruct (zlt (Int.signed i) (Int.signed i0)); auto; contradict H4; auto.\nunfold Int.lt in H4.\ndestruct (zlt (Int.signed i0) (Int.signed i)); auto; try omega; contradict H4; auto.\nunfold Int.lt in H4.\ndestruct (zlt (Int.signed i0) (Int.signed i)); auto; try omega; contradict H4; auto.\nunfold Int.lt in H4.\ndestruct (zlt (Int.signed i) (Int.signed i0)); auto; try omega; contradict H4; auto.\nQed.\n*)\n\nDefinition  binary_operation_to_opp_comparison (op: Cop.binary_operation) :=\n match op with\n | Cop.Oeq => Some Zne\n | Cop.One => Some (@eq Z)\n | Cop.Olt => Some Z.ge\n | Cop.Ole => Some Z.gt\n | Cop.Ogt => Some Z.le\n | Cop.Oge => Some Z.lt\n | _ => None\n end.\n\n(*\nLemma typed_false_binop_int:\n  forall op op' e1 e2 Espec  {cs: compspecs} Delta P Q R c Post,\n   binary_operation_to_opp_comparison op = Some op' ->\n   typeof e1 = tint ->\n   typeof e2 = tint ->\n   (PROPx P (LOCALx (tc_environ Delta :: Q) (SEPx R))) |-- (tc_expr Delta e1) ->\n   (PROPx P (LOCALx (tc_environ Delta :: Q) (SEPx R))) |-- (tc_expr Delta e2) ->\n  @semax cs Espec Delta (PROPx P (LOCALx\n      (`op' (`force_signed_int (eval_expr e1)) (`force_signed_int (eval_expr e2))\n          :: Q) (SEPx R))) c Post ->\n  @semax cs Espec Delta (PROPx P (LOCALx\n      (`(typed_false\n          (typeof (Ebinop op e1 e2 tint)))\n          (eval_expr (Ebinop op e1 e2 tint)) :: Q) (SEPx R))) c Post.\nProof.\nintros.\neapply semax_pre; [clear H4 | apply H4].\neapply derives_trans with\n ( local (tc_environ Delta) && ((tc_expr Delta e1) && ( (tc_expr Delta e2)\n   && PROPx P (LOCALx (tc_environ Delta :: `(typed_false (typeof (Ebinop op e1 e2 tint)))(eval_expr (Ebinop op e1 e2 tint)) :: Q) (SEPx R))))).\napply andp_right.\nrewrite <- insert_local. apply andp_left1; auto.\nrewrite <- andp_assoc.\napply andp_right; auto.\ndo 2 rewrite <- insert_local.\nrewrite <- andp_assoc.\nrewrite (andp_comm (local _)).\nrewrite andp_assoc.\napply andp_left2.\nrewrite insert_local.\napply andp_right; auto.\nclear H2 H3.\nunfold PROPx, LOCALx; intro rho; simpl.\nunfold local,lift1 at 1.\napply derives_extract_prop; intro TCE.\neapply derives_trans.\napply andp_derives; [ apply typecheck_expr_sound; auto | ].\napply andp_derives; [ apply typecheck_expr_sound; auto | ].\napply derives_refl.\nnormalize. autorewrite with norm1 norm2; normalize.\napply andp_right; auto. apply prop_right.\nsplit; auto.\nclear H6 TCE.\nrewrite H0 in *; rewrite H1 in *.\nclear H0 H1 H4.\ndestruct (eval_expr e1 rho); inv H2.\ndestruct (eval_expr e2 rho); inv H3.\nunfold force_signed_int, force_int.\nunfold typed_true, eval_binop in H5.\ndestruct op; inv H; simpl in H5.\npose proof (Int.eq_spec i i0); destruct (Int.eq i i0); inv H5; auto.\nintro; apply H.\nrewrite <- (Int.repr_signed i).\nrewrite <- (Int.repr_signed i0).\nf_equal; auto.\npose proof (Int.eq_spec i i0); destruct (Int.eq i i0); inv H5; auto.\nunfold Int.lt in H5.\ndestruct (zlt (Int.signed i) (Int.signed i0)); inv H5; auto.\nunfold Int.lt in H5.\ndestruct (zlt (Int.signed i0) (Int.signed i)); inv H5; omega.\nunfold Int.lt in H5.\ndestruct (zlt (Int.signed i0) (Int.signed i)); inv H5; omega.\nunfold Int.lt in H5.\ndestruct (zlt (Int.signed i) (Int.signed i0)); inv H5; omega.\nQed.\n*)\n\nLemma typed_false_One_nullval:\n forall  {cs: compspecs}  v t t',\n   local (`(typed_false tint) (`(eval_binop Cop.One (tptr t) (tptr t')) v `(nullval))) |--\n    local (`(eq nullval) v).\nProof.\nintros.\n intro rho; unfold local, lift1; unfold_lift.\n apply prop_derives; intro.\n simpl in H. unfold sem_binary_operation' in H.\n simpl in H. rewrite !andb_false_r in H.\n unfold sem_cmp_pp, nullval in *.\n destruct Archi.ptr64 eqn:Hp;\n destruct (v rho); inv H.\n pose proof (Int64.eq_spec i Int64.zero).\n destruct (Int64.eq i Int64.zero); inv H1.\n reflexivity.\n pose proof (Int.eq_spec i Int.zero).\n destruct (Int.eq i Int.zero); inv H1.\n reflexivity.\nQed.\n\nLemma typed_true_One_nullval:\n forall  {cs: compspecs}  v t t',\n   local (`(typed_true tint) (`(eval_binop Cop.One (tptr t) (tptr t')) v `(nullval))) |--\n   local (`(ptr_neq nullval) v).\nProof.\nintros.\n intro rho; unfold local, lift1; unfold_lift.\n apply prop_derives; intro.\n simpl in H. unfold sem_binary_operation' in H.\n simpl in H. rewrite !andb_false_r in H.\n unfold sem_cmp_pp, ptr_neq, ptr_eq, nullval in *; simpl; intro.\n destruct (v rho); try contradiction.\n simpl in *.\n unfold typed_true, force_val, strict_bool_val in *.\n destruct Archi.ptr64 eqn:?; auto.\n destruct H0 as [? [? ?]].\n first [ pose proof (Int64.eq_spec Int64.zero i)\n        | pose proof (Int.eq_spec Int.zero i)];\n rewrite H1 in H3; \n subst; inv H.\nQed.\n\n\nLemma typed_false_Oeq_nullval:\n forall  {cs: compspecs} v t t',\n   local (`(typed_false tint) (`(eval_binop Cop.Oeq (tptr t) (tptr t')) v `(nullval))) |--\n   local (`(ptr_neq nullval) v).\nProof.\nintros. subst.\n unfold_lift; intro rho.  unfold local, lift1; apply prop_derives; intro.\n simpl in H. unfold sem_binary_operation' in H.\n simpl in H. rewrite !andb_false_r in H.\n intro. apply ptr_eq_e in H0. rewrite <- H0 in H.\n inv H.\nQed.\n\nLemma local_entail_at:\n  forall n S T (H: local (locald_denote S) |-- local (locald_denote T))\n    P Q R,\n    nth_error Q n = Some S ->\n    PROPx P (LOCALx Q (SEPx R)) |--\n    PROPx P (LOCALx (replace_nth n Q T) (SEPx R)).\nProof.\n intros.\n unfold PROPx, LOCALx; simpl; intro rho;  apply andp_derives; auto.\n apply andp_derives; auto.\n unfold local, lift1.\n specialize (H rho). unfold local,lift1 in H.\n revert Q H0; induction n; destruct Q; simpl; intros; inv H0.\n unfold_lift; repeat rewrite prop_and.\n apply andp_derives; auto.\n  unfold_lift; repeat rewrite prop_and.\n apply andp_derives; auto.\nQed.\n\nLemma local_entail_at_semax_0:\n  forall Espec {cs: compspecs}Delta P Q1 Q1' Q R c Post,\n   local (locald_denote Q1) |-- local (locald_denote Q1') ->\n   @semax cs Espec Delta (PROPx P (LOCALx (Q1'::Q) (SEPx R))) c Post  ->\n   @semax cs Espec Delta (PROPx P (LOCALx (Q1::Q) (SEPx R))) c Post.\nProof.\nintros.\neapply semax_pre0.\neapply (local_entail_at 0).\napply H. reflexivity.\nauto.\nQed.\n\n(*\nLtac simplify_typed_comparison :=\nmatch goal with\n| |- semax _ (PROPx _ (LOCALx (`(typed_true _) ?A :: _) _)) _ _ =>\n (eapply typed_true_binop_int;\n   [reflexivity | reflexivity | reflexivity\n   | try solve [go_lowerx; apply prop_right; auto ]\n   | try solve [go_lowerx; apply prop_right; auto ]\n   | ])\n ||\n  (let a := fresh \"a\" in set (a:=A); simpl in a; unfold a; clear a;\n   eapply local_entail_at_semax_0; [\n    first [ apply typed_true_Oeq_nullval\n           | apply typed_true_One_nullval\n           ]\n    |  ])\n| |- semax _ (PROPx _ (LOCALx (`(typed_false _) ?A :: _) _)) _ _ =>\n (eapply typed_false_binop_int;\n   [reflexivity | reflexivity | reflexivity\n   | try solve [go_lowerx; apply prop_right; auto ]\n   | try solve [go_lowerx; apply prop_right; auto ]\n   | ])\n ||\n  let a := fresh \"a\" in set (a:=A); simpl in a; unfold a; clear a;\n   eapply local_entail_at_semax_0; [\n    first [ apply typed_false_Oeq_nullval\n           | apply typed_false_One_nullval\n           ]\n    |  ]\n| |- _ => idtac\nend.\n*)\n\nDefinition compare_pp op p q :=\n   match p with\n            | Vptr b z =>\n               match q with\n               | Vptr b' z' => if eq_block b b'\n                              then Vint (if Ptrofs.cmpu op z z' then Int.one else Int.zero)\n                              else Vundef\n               | _ => Vundef\n               end\n             | _ => Vundef\n   end.\n\nLemma force_sem_cmp_pp:\n  forall op p q,\n  isptr p -> isptr q ->\n  force_val (sem_cmp_pp op p q) =\n   match op with\n   | Ceq => Vint (if eq_dec p q then Int.one else Int.zero)\n   | Cne => Vint (if eq_dec p q then Int.zero else Int.one)\n   | _ => compare_pp op p q\n   end.\nProof.\nintros.\ndestruct p; try contradiction.\ndestruct q; try contradiction.\nclear.\nunfold sem_cmp_pp, compare_pp, Ptrofs.cmpu, Val.cmplu_bool.\ndestruct Archi.ptr64 eqn:Hp.\ndestruct op; simpl; auto.\nif_tac. if_tac. inv H0. rewrite Ptrofs.eq_true; reflexivity.\nrewrite Ptrofs.eq_false by congruence; reflexivity.\nif_tac. congruence. reflexivity.\nif_tac. if_tac. inv H0. rewrite Ptrofs.eq_true by auto. reflexivity.\nrewrite Ptrofs.eq_false by congruence; reflexivity.\nrewrite if_false by congruence. reflexivity.\nif_tac; [destruct (Ptrofs.ltu i i0); reflexivity | reflexivity].\nif_tac; [destruct (Ptrofs.ltu i0 i); reflexivity | reflexivity].\nif_tac; [destruct (Ptrofs.ltu i0 i); reflexivity | reflexivity].\nif_tac; [destruct (Ptrofs.ltu i i0); reflexivity | reflexivity].\ndestruct op; simpl; auto; rewrite Hp.\nif_tac. if_tac. inv H0. rewrite Ptrofs.eq_true; reflexivity.\nrewrite Ptrofs.eq_false by congruence; reflexivity.\nif_tac. congruence. reflexivity.\nif_tac. if_tac. inv H0. rewrite Ptrofs.eq_true by auto. reflexivity.\nrewrite Ptrofs.eq_false by congruence; reflexivity.\nrewrite if_false by congruence. reflexivity.\nif_tac; [destruct (Ptrofs.ltu i i0); reflexivity | reflexivity].\nif_tac; [destruct (Ptrofs.ltu i0 i); reflexivity | reflexivity].\nif_tac; [destruct (Ptrofs.ltu i0 i); reflexivity | reflexivity].\nif_tac; [destruct (Ptrofs.ltu i i0); reflexivity | reflexivity].\nQed.\n\nHint Rewrite force_sem_cmp_pp using (now auto) : norm.\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/compare_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.25438736198029216}}
{"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(** Construction and coloring of the interference graph. *)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Op.\nRequire Import Registers.\nRequire Import RTL.\nRequire Import RTLtyping.\nRequire Import Locations.\nRequire Import Conventions.\nRequire Import InterfGraph.\nRequire Import BuiltinFunctions.\n\n(** * Construction of the interference graph *)\n\n(** Two registers interfere if there exists a program point where\n    they are both simultaneously live, and it is possible that they\n    contain different values at this program point.  Consequently,\n    two registers that do not interfere can be merged into one register\n    while preserving the program behavior: there is no program point\n    where this merged register would have to hold two different values\n    (for the two original registers), so to speak.\n\n    The simplified algorithm for constructing the interference graph\n    from the results of the liveness analysis is as follows:\n<<\n     start with empty interference graph\n     for each parameter p and register r live at the function entry point:\n         add conflict edge p <-> r \n     for each instruction I in function:\n         let L be the live registers \"after\" I\n         if I is a \"move\" instruction  dst <- src, and dst is live:\n            add conflict edges dst <-> r for each r in L \\ {dst, src}\n         else if I is an instruction with result dst, and dst is live:\n            add conflict edges dst <-> r for each r in L \\ {dst};\n         if I is a \"call\" instruction dst <- f(args),\n            add conflict edges between all pseudo-registers in L \\ {dst}\n            and all caller-save machine registers\n     done\n>>\n    Notice that edges are added only when a register becomes live.\n    A register becomes live either if it is the result of an operation\n    (and is live afterwards), or if we are at the function entrance\n    and the register is a function parameter.  For two registers to\n    be simultaneously live at some program point, it must be the case\n    that one becomes live at a point where the other is already live.\n    Hence, it suffices to add interference edges between registers\n    that become live at some instruction and registers that are already\n    live at this instruction.  \n\n    Notice also the special treatment of ``move'' instructions:\n    since the destination register of the ``move'' is assigned the same value\n    as the source register, it is semantically correct to assign\n    the destination and the source registers to the same register,\n    even if the source register remains live afterwards.\n    (This is even desirable, since the ``move'' instruction can then\n    be eliminated.)  Thus, no interference is added between the\n    source and the destination of a ``move'' instruction.\n\n    Finally, for ``call'' instructions, we must make sure that\n    pseudo-registers live across the instruction are allocated to\n    callee-save machine register or to stack slots, but never to\n    caller-save machine registers (these lose their values across\n    the call).  We therefore add the corresponding conflict edges\n    between pseudo-registers live across and caller-save machine\n    registers (pairwise).  \n\n    The full algorithm is similar to the simplified algorithm above,\n    but records preference edges in addition to conflict edges.\n    Preference edges guide the graph coloring algorithm by telling it\n    that better code will be obtained eventually if it is possible\n    to allocate certain pseudo-registers to the same location or to\n    a given machine register.  Preference edges are added:\n-   between the destination and source pseudo-registers of a ``move''\n    instruction;\n-   between the arguments of a ``call'' instruction and the locations\n    of the arguments as dictated by the calling conventions;\n-   between the result of a ``call'' instruction and the location\n    of the result as dictated by the calling conventions.\n*)\n\nSection WITHEF.\nContext `{Hsc: SyntaxConfiguration}.\n\nDefinition add_interf_live\n    (filter: reg -> bool) (res: reg) (live: Regset.t) (g: graph): graph :=\n  Regset.fold \n    (fun r g => if filter r then add_interf r res g else g) live g.\n\nDefinition add_interf_op\n    (res: reg) (live: Regset.t) (g: graph): graph :=\n  add_interf_live\n    (fun r => if Reg.eq r res then false else true)\n    res live g.\n\nDefinition add_interf_move\n    (arg res: reg) (live: Regset.t) (g: graph): graph :=\n  add_interf_live\n    (fun r =>\n       if Reg.eq r res then false else\n       if Reg.eq r arg then false else true)\n    res live g.\n\nDefinition add_interf_destroyed\n    (live: Regset.t) (destroyed: list mreg) (g: graph): graph :=\n  List.fold_left\n    (fun g mr => Regset.fold (fun r g => add_interf_mreg r mr g) live g)\n    destroyed g.\n\nDefinition add_interfs_indirect_call\n    (rfun: reg) (locs: list loc) (g: graph): graph :=\n  List.fold_left\n    (fun g loc =>\n      match loc with R mr => add_interf_mreg rfun mr g | _ => g end)\n    locs g.\n\nDefinition add_interf_call\n    (ros: reg + ident) (locs: list loc) (g: graph): graph :=\n  match ros with\n  | inl rfun => add_interfs_indirect_call rfun locs g\n  | inr idfun => g\n  end.\n\nFixpoint add_prefs_call\n    (args: list reg) (locs: list loc) (g: graph) {struct args} : graph :=\n  match args, locs with\n  | a1 :: al, l1 :: ll =>\n      add_prefs_call al ll\n        (match l1 with R mr => add_pref_mreg a1 mr g | _ => g end)\n  | _, _ => g\n  end.\n\nDefinition add_prefs_builtin (ef: builtin_function)\n                            (args: list reg) (res: reg) (g: graph) : graph :=\n  match ef, args with\n  | EF_annot_val txt targ, arg1 :: _ => add_pref arg1 res g\n  | _, _ => g\n  end.\n\nDefinition add_interf_entry\n    (params: list reg) (live: Regset.t) (g: graph): graph :=\n  List.fold_left (fun g r => add_interf_op r live g) params g.\n\nFixpoint add_interf_params\n    (params: list reg) (g: graph) {struct params}: graph :=\n  match params with\n  | nil => g\n  | p1 :: pl =>\n      add_interf_params pl\n        (List.fold_left\n          (fun g r => if Reg.eq r p1 then g else add_interf r p1 g)\n          pl g)\n  end.\n\nDefinition add_edges_instr\n    (sig: signature) (i: instruction) (live: Regset.t) (g: graph) : graph :=\n  match i with\n  | Iop op args res s =>\n      if Regset.mem res live then\n        match is_move_operation op args with\n        | Some arg =>\n            add_pref arg res (add_interf_move arg res live g)\n        | None =>\n            add_interf_op res live g\n        end\n      else g\n  | Iload chunk addr args dst s =>\n      if Regset.mem dst live\n      then add_interf_op dst live g\n      else g\n  | Icall sig ros args res s =>\n      let largs := loc_arguments sig in\n      let lres := loc_result sig in\n      add_prefs_call args largs\n        (add_pref_mreg res lres\n          (add_interf_op res live\n            (add_interf_call ros largs\n              (add_interf_destroyed\n                (Regset.remove res live) destroyed_at_call_regs g))))\n  | Itailcall sig ros args =>\n      let largs := loc_arguments sig in\n      add_prefs_call args largs\n        (add_interf_call ros largs g)\n  | Ibuiltin ef args res s =>\n      add_prefs_builtin ef args res (add_interf_op res live g)\n  | Ireturn (Some r) =>\n      add_pref_mreg r (loc_result sig) g\n  | _ => g\n  end.\n\nDefinition add_edges_instrs (f: function) (live: PMap.t Regset.t) : graph :=\n  PTree.fold\n    (fun g pc i => add_edges_instr f.(fn_sig) i live!!pc g)\n    f.(fn_code)\n    empty_graph.\n\nDefinition interf_graph (f: function) (live: PMap.t Regset.t) (live0: Regset.t) :=\n  add_prefs_call f.(fn_params) (loc_parameters f.(fn_sig))\n    (add_interf_params f.(fn_params)\n      (add_interf_entry f.(fn_params) live0\n        (add_edges_instrs f live))).\n\n(** * Graph coloring *)\n\n(** The actual coloring of the graph is performed by a function written\n  directly in Caml, and not proved correct in any way.  This function\n  takes as argument the [RTL] function, the interference graph for\n  this function, an assignment of types to [RTL] pseudo-registers,\n  and the set of all [RTL] pseudo-registers mentioned in the\n  interference graph.  It returns the coloring as a function from\n  pseudo-registers to locations. *)\n\nParameter graph_coloring: \n  function -> graph -> regenv -> Regset.t -> (reg -> loc).\n\n(** To ensure that the result of [graph_coloring] is a correct coloring,\n  we check a posteriori its result using the following Coq functions.\n  Let [coloring] be the function [reg -> loc] returned by [graph_coloring].\n  The three properties checked are:\n- [coloring r1 <> coloring r2] if there is a conflict edge between\n  [r1] and [r2] in the interference graph.\n- [coloring r1 <> R m2] if there is a conflict edge between pseudo-register\n  [r1] and machine register [m2] in the interference graph.\n- For all [r] mentioned in the interference graph,\n  the location [coloring r] is acceptable and has the same type as [r].\n*)\n\nDefinition check_coloring_1 (g: graph) (coloring: reg -> loc) :=\n  SetRegReg.for_all \n    (fun r1r2 =>\n      if Loc.eq (coloring (fst r1r2)) (coloring (snd r1r2)) then false else true)\n    g.(interf_reg_reg).\n\nDefinition check_coloring_2 (g: graph) (coloring: reg -> loc) :=\n  SetRegMreg.for_all \n    (fun r1mr2 =>\n      if Loc.eq (coloring (fst r1mr2)) (R (snd r1mr2)) then false else true)\n    g.(interf_reg_mreg).\n\nDefinition same_typ (t1 t2: typ) :=\n  match t1, t2 with\n  | Tint, Tint => true\n  | Tfloat, Tfloat => true\n  | _, _ => false\n  end.\n\nDefinition loc_is_acceptable (l: loc) :=\n  match l with\n  | R r => \n     if In_dec Loc.eq l temporaries then false else true\n  | S (Local ofs ty) =>\n     if zlt ofs 0 then false else true\n  | _ =>\n     false\n  end.\n\nDefinition check_coloring_3 (rs: Regset.t) (env: regenv) (coloring: reg -> loc) :=\n  Regset.for_all\n    (fun r =>\n      let l := coloring r in\n      andb (loc_is_acceptable l) (same_typ (env r) (Loc.type l)))\n    rs.\n\nDefinition check_coloring\n       (g: graph) (env: regenv) (rs: Regset.t) (coloring: reg -> loc) :=\n  andb (check_coloring_1 g coloring)\n       (andb (check_coloring_2 g coloring)\n             (check_coloring_3 rs env coloring)).\n\n(** To preserve decidability of checking, the checks\n  (especially the third one) are performed for the pseudo-registers\n  mentioned in the interference graph.  To facilitate the proofs,\n  it is convenient to ensure that the properties hold for all\n  pseudo-registers.  To this end, we ``clip'' the candidate coloring\n  returned by [graph_coloring]: the final coloring behave identically\n  over pseudo-registers mentioned in the interference graph,\n  but returns a dummy machine register of the correct type otherwise. *)\n\nDefinition alloc_of_coloring (coloring: reg -> loc) (env: regenv) (rs: Regset.t) :=\n  fun r =>\n    if Regset.mem r rs\n    then coloring r\n    else match env r with Tint => R dummy_int_reg | Tfloat => R dummy_float_reg end.\n\n(** * Coloring of the interference graph *)\n\n(** The following function combines the phases described above:\n  construction of the interference graph, coloring by untrusted\n  Caml code, checking of the candidate coloring returned,\n  and adjustment of this coloring.  If the coloring candidate is\n  incorrect, [None] is returned, causing register allocation to fail. *)\n\nDefinition regalloc\n    (f: function) (live: PMap.t Regset.t) (live0: Regset.t) (env: regenv) :=\n  let g := interf_graph f live live0 in\n  let rs := all_interf_regs g in\n  let coloring := graph_coloring f g env rs in\n  if check_coloring g env rs coloring\n  then Some (alloc_of_coloring coloring env rs)\n  else None.\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/Coloring.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.25436456726738754}}
{"text": "From lrust.lifetime Require Export primitive.\nFrom lrust.lifetime Require Export faking.\nFrom iris.algebra Require Import csum auth frac gmap agree gset.\nFrom iris.base_logic.lib Require Import boxes.\nFrom iris.proofmode Require Import proofmode.\nFrom iris.prelude Require Import options.\n\nSection borrow.\nContext `{!invGS Σ, !lftGS Σ userE}.\nImplicit Types κ : lft.\n\nLemma raw_bor_create E κ P :\n  ↑lftN ⊆ E →\n  lft_ctx -∗ ▷ P ={E}=∗ raw_bor κ P ∗ ([†κ] ={E}=∗ ▷ P).\nProof.\n  iIntros (HE) \"#LFT HP\". iInv mgmtN as (A I) \"(>HA & >HI & Hinv)\" \"Hclose\".\n  iMod (ilft_create _ _ κ with \"HA HI Hinv\") as (A' I') \"(Hκ & HA & HI & Hinv)\".\n  iDestruct \"Hκ\" as %Hκ. iDestruct (@big_sepS_later with \"Hinv\") as \"Hinv\".\n  iDestruct (big_sepS_elem_of_acc _ _ κ with \"Hinv\") as \"[Hinv Hclose']\".\n  { by apply elem_of_dom. }\n  rewrite {1}/lft_inv. iDestruct \"Hinv\" as \"[[Hinv >%]|[Hinv >%]]\".\n  - rewrite {1}lft_inv_alive_unfold;\n      iDestruct \"Hinv\" as (Pb Pi) \"(Halive & Hvs & Hinh)\".\n    rewrite /lft_bor_alive; iDestruct \"Halive\" as (B) \"(HboxB & >HownB & HB)\".\n    iMod (lft_inh_extend _ _ P with \"Hinh\")\n      as \"(Hinh & HIlookup & Hinh_close)\"; first solve_ndisj.\n    iMod (slice_insert_full _ _ true with \"HP HboxB\")\n      as (γB) \"(HBlookup & HsliceB & HboxB)\"; first by solve_ndisj.\n    rewrite lookup_fmap. iDestruct \"HBlookup\" as %HBlookup.\n    rewrite -(fmap_insert bor_filled _ _ Bor_in).\n    iMod (own_bor_update with \"HownB\") as \"[HB● HB◯]\".\n    { eapply auth_update_alloc,\n        (alloc_singleton_local_update _ γB (1%Qp, to_agree Bor_in)); last done.\n      rewrite lookup_fmap. case:(B !! γB) HBlookup; done. }\n    rewrite -fmap_insert.\n    iSpecialize (\"Hclose'\" with \"[Hvs Hinh HboxB HB● HB]\").\n    { iNext. rewrite /lft_inv. iLeft. iFrame \"%\".\n      rewrite lft_inv_alive_unfold. iExists (P ∗ Pb)%I, (P ∗ Pi)%I.\n      iFrame \"Hinh\". iSplitL \"HboxB HB● HB\"; last by iApply lft_vs_frame.\n      rewrite /lft_bor_alive. iExists _. iFrame \"HboxB HB●\".\n      iApply @big_sepM_insert; first by destruct (B !! γB).\n      simpl. iFrame. }\n    iMod (\"Hclose\" with \"[HA HI Hclose']\") as \"_\"; [by iNext; iExists _, _; iFrame|].\n    iSplitL \"HB◯ HsliceB\".\n    + rewrite /bor /raw_bor /idx_bor_own. iModIntro. iExists γB. iFrame.\n      iExists P. rewrite -bi.iff_refl. auto.\n    + clear -HE. iIntros \"!> H†\".\n      iInv mgmtN as (A I) \"(>HA & >HI & Hinv)\" \"Hclose\".\n      iDestruct (\"HIlookup\" with \"HI\") as %Hκ.\n      iDestruct (big_sepS_elem_of_acc _ _ κ with \"Hinv\") as \"[Hinv Hclose']\".\n      { by apply elem_of_dom. }\n      rewrite /lft_dead; iDestruct \"H†\" as (Λ) \"[% #H†]\".\n      iDestruct (own_alft_auth_agree A Λ false with \"HA H†\") as %EQAΛ.\n      rewrite {1}/lft_inv; iDestruct \"Hinv\" as \"[[_ >%]|[Hinv >%]]\".\n      { unfold lft_alive_in in *. naive_solver. }\n      rewrite /lft_inv_dead; iDestruct \"Hinv\" as (Pinh) \"(Hdead & >Hcnt & Hinh)\".\n      iMod (\"Hinh_close\" $! Pinh with \"Hinh\") as (Pinh') \"(? & $ & ?)\".\n      iApply \"Hclose\". iExists A, I. iFrame. iNext. iApply \"Hclose'\".\n      rewrite /lft_inv. iRight. iFrame \"%\".\n      rewrite /lft_inv_dead. iExists Pinh'. iFrame.\n  - iFrame \"HP\". iApply fupd_frame_r. iSplitR \"\"; last by auto.\n    rewrite /lft_inv_dead. iDestruct \"Hinv\" as (Pinh) \"(Hdead & Hcnt & Hinh)\" .\n    iMod (raw_bor_fake with \"Hdead\") as \"[Hdead Hbor]\"; first solve_ndisj.\n    unfold bor. iFrame. iApply \"Hclose\". iExists _, _. iFrame. rewrite big_sepS_later.\n    iApply \"Hclose'\". iNext. rewrite /lft_inv. iRight.\n    rewrite /lft_inv_dead. iFrame. eauto.\nQed.\n\nLemma bor_create E κ P :\n  ↑lftN ⊆ E →\n  lft_ctx -∗ ▷ P ={E}=∗ &{κ}P ∗ ([†κ] ={E}=∗ ▷ P).\nProof.\n  iIntros (?) \"#LFT HP\". iMod (raw_bor_create with \"LFT HP\") as \"[HP $]\"; [done|].\n  rewrite /bor. iExists _. iFrame. iApply lft_incl_refl.\nQed.\nEnd borrow.\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/lifetime/model/borrow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331606115021, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.25427233488002865}}
{"text": "Require Import Arith.\nRequire Import Omega.\nRequire FunctionalExtensionality.\nRequire Import List.\nImport List.ListNotations.\n\nRequire Import mathcomp.ssreflect.ssreflect.\nRequire Import mathcomp.ssreflect.ssrbool.\nSet Bullet Behavior \"Strict Subproofs\".\n\nRequire Import StructTact.StructTactics.\nRequire Import StructTact.Util.\n\nRequire Import InfSeqExt.infseq.\n\nRequire Import Chord.Chord.\nRequire Import Chord.HandlerLemmas.\n\nDefinition live_node_bool (gst : global_state) (h : addr) : bool :=\n  if sigma gst h is Some st then\n    joined st && in_dec addr_eq_dec h (nodes gst) && ~~ in_dec addr_eq_dec h (failed_nodes gst)\n  else false.\n\nLtac break_live_node_name var :=\n  match goal with\n  | H : live_node _ _ |- _ =>\n    unfold live_node in H; repeat break_and; break_exists_name var; repeat break_and\n  end.\n\nLtac break_live_node_exists_exists :=\n  match goal with\n  | H : live_node _ _ |- _ =>\n    unfold live_node in H; repeat break_and; break_exists_exists; repeat break_and\n  end.\n\nLtac break_dead_node :=\n  match goal with\n  | H : dead_node _ _ |- _ =>\n    unfold dead_node in H; repeat break_and; break_exists; repeat break_and\n  end.\n\nLtac break_dead_node_name var :=\n  match goal with\n  | H : dead_node _ _ |- _ =>\n    unfold dead_node in H; repeat break_and; break_exists_name var; repeat break_and\n  end.\n\nLtac break_dead_node_exists_exists :=\n  match goal with\n  | H : dead_node _ _ |- _ =>\n    unfold dead_node in H; repeat break_and; break_exists_exists; repeat break_and\n  end.\n\nLtac break_live_node :=\n  match goal with\n  | H : live_node _ _ |- _ =>\n    unfold live_node in H; repeat break_and; break_exists; repeat break_and\n  end.\n\nTheorem live_node_characterization :\n  forall gst h st,\n    sigma gst h = Some st ->\n    joined st = true ->\n    In h (nodes gst) ->\n    ~ In h (failed_nodes gst) ->\n    live_node gst h.\nProof using.\n  unfold live_node.\n  intuition.\n  match goal with\n  | x : data |- exists _ : data, _ => exists x\n  end.\n  intuition.\nQed.\n\nDefinition live_node_dec :\n  forall gst h,\n    {live_node gst h} + {~ live_node gst h}.\nProof.\n  intros.\n  destruct (In_dec addr_eq_dec h (nodes gst));\n    destruct (In_dec addr_eq_dec h (failed_nodes gst));\n    destruct (sigma gst h) as [st|] eqn:?;\n    try destruct (joined st) eqn:?;\n        try solve [left; eapply live_node_characterization; eassumption\n                  |right; intro; inv_prop live_node; expand_def; congruence].\nDefined.\n\nDefinition live_addrs (gst : global_state) : list addr :=\n  filter (live_node_bool gst) (nodes gst).\n\nDefinition live_ptrs (gst : global_state) : list pointer :=\n  map make_pointer (live_addrs gst).\n\nDefinition live_ptrs_with_states (gst : global_state) : list (pointer * data) :=\n  FilterMap.filterMap (fun p =>\n                         match sigma gst (addr_of p) with\n                         | Some st => Some (p, st)\n                         | None => None\n                         end)\n                      (live_ptrs gst).\n\nTheorem live_node_equiv_live_node_bool :\n  forall gst h,\n    live_node gst h <-> live_node_bool gst h = true.\nProof using.\n  unfold live_node_bool.\n  intuition.\n  - repeat break_match; break_live_node; last by congruence.\n    find_rewrite.\n    find_injection.\n    apply/andP; split; first by apply/andP; split => //; case in_dec.\n    by case in_dec.\n  - repeat break_match; last by congruence.\n    move/andP: H => [H H_f]; move/andP: H => [H H_n].\n    apply: live_node_characterization; eauto.\n    * by move: H_n; case in_dec.\n    * by move: H_f; case in_dec.\nQed.\n\nLemma live_addr_In_live_addrs :\n  forall gst h,\n    live_node gst h ->\n    In h (live_addrs gst).\nProof.\n  unfold live_addrs.\n  intros.\n  apply filter_In; split.\n  - unfold live_node in *; break_and; auto.\n  - apply live_node_equiv_live_node_bool; auto.\nQed.\n\nLemma In_live_addrs_live :\n  forall gst h,\n    In h (live_addrs gst) ->\n    live_node gst h.\nProof.\n  unfold live_addrs.\n  intros.\n  find_apply_lem_hyp filter_In; break_and.\n  apply live_node_equiv_live_node_bool; auto.\nQed.\n\nLemma In_live_ptrs_live :\n  forall gst h,\n    In h (live_ptrs gst) ->\n    live_node gst (addr_of h).\nProof.\n  unfold live_ptrs.\n  intros.\n  apply In_live_addrs_live.\n  now find_apply_lem_hyp in_map_iff; expand_def.\nQed.\n\nLemma when_apply_handler_result_preserves_live_node :\n  forall h h0 st st' gst gst' e ms cts nts,\n    live_node gst h ->\n    sigma gst h = Some st ->\n    sigma gst' h = Some st' ->\n    joined st' = true ->\n    gst' = apply_handler_result h0 (st', ms, cts, nts) e gst ->\n    live_node gst' h.\nProof using.\n  intuition.\n  eapply live_node_characterization.\n  - eauto.\n  - break_live_node.\n    repeat find_rewrite.\n    find_inversion; eauto.\n  - find_apply_lem_hyp apply_handler_result_preserves_nodes.\n    find_inversion.\n    break_live_node; auto.\n  - find_apply_lem_hyp apply_handler_result_preserves_failed_nodes.\n    find_inversion.\n    break_live_node; auto.\nQed.\n\nTheorem live_node_preserved_by_recv_step :\n  forall gst h src st msg gst' e st' ms nts cts,\n    live_node gst h ->\n    Some st = sigma gst h ->\n    recv_handler src h st msg = (st', ms, nts, cts) ->\n    gst' = apply_handler_result h (st', ms, nts, cts) e gst ->\n    live_node gst' h.\nProof using.\n  intuition.\n  eapply when_apply_handler_result_preserves_live_node; eauto.\n  - eauto using apply_handler_result_updates_sigma.\n  - eapply joined_preserved_by_recv_handler.\n    * eauto.\n    * break_live_node.\n      find_rewrite.\n      find_injection.\n      auto.\nQed.\n\nTheorem live_node_preserved_by_timeout_step :\n  forall gst h st st' t ms nts cts e gst',\n    live_node gst h ->\n    sigma gst h = Some st ->\n    timeout_handler h st t = (st', ms, nts, cts) ->\n    gst' = apply_handler_result h (st', ms, nts, t :: cts) e gst ->\n    live_node gst' h.\nProof using.\n  intuition.\n  eapply when_apply_handler_result_preserves_live_node; eauto.\n  - eauto using apply_handler_result_updates_sigma.\n  - break_live_node.\n    unfold timeout_handler, fst in *; break_let.\n    repeat find_rewrite.\n    find_apply_lem_hyp joined_preserved_by_timeout_handler_eff.\n    repeat find_rewrite.\n    find_injection.\n    eauto.\nQed.\n\nDefinition best_succ_of (gst : global_state) (h : addr) : option addr :=\n  match (sigma gst) h with\n  | Some st => head (filter (live_node_bool gst) (map addr_of (succ_list st)))\n  | None => None\n  end.\n\nLemma live_node_specificity :\n  forall gst gst',\n    nodes gst = nodes gst' ->\n    failed_nodes gst = failed_nodes gst' ->\n    sigma gst = sigma gst' ->\n    live_node gst = live_node gst'.\nProof using.\n  intuition.\n  unfold live_node.\n  repeat find_rewrite.\n  auto.\nQed.\n\nLemma live_node_joined :\n  forall gst h,\n    live_node gst h ->\n    exists st,\n      sigma gst h = Some st /\\\n      joined st = true.\nProof using.\n  intuition.\n    by break_live_node_exists_exists.\nQed.\n\nLemma live_node_in_nodes :\n  forall gst h,\n    live_node gst h ->\n    In h (nodes gst).\nProof using.\n  intuition.\n    by break_live_node.\nQed.\nHint Resolve live_node_in_nodes.\n\nLemma live_node_not_in_failed_nodes :\n  forall gst h,\n    live_node gst h ->\n    ~ In h (failed_nodes gst).\nProof using.\n  intuition.\n    by break_live_node.\nQed.\nHint Resolve live_node_not_in_failed_nodes.\n\nLemma live_node_equivalence :\n  forall gst gst' h st st',\n    live_node gst h ->\n    nodes gst = nodes gst' ->\n    failed_nodes gst = failed_nodes gst' ->\n    sigma gst h = Some st ->\n    sigma gst' h = Some st' ->\n    joined st = joined st' ->\n    live_node gst' h.\nProof using.\n  intuition.\n  break_live_node.\n  eapply live_node_characterization.\n  * eauto.\n  * repeat find_rewrite.\n    find_injection.\n    eauto.\n  * repeat find_rewrite; auto.\n  * repeat find_rewrite; auto.\nQed.\n\nLemma live_node_means_state_exists :\n  forall gst h,\n    live_node gst h ->\n    exists st, sigma gst h = Some st.\nProof using.\n  intuition.\n  find_apply_lem_hyp live_node_joined.\n  break_exists_exists.\n    by break_and.\nQed.\nHint Resolve live_node_means_state_exists.\n\nLemma coarse_live_node_characterization :\n  forall gst gst' h,\n    live_node gst h ->\n    nodes gst = nodes gst' ->\n    failed_nodes gst = failed_nodes gst' ->\n    sigma gst = sigma gst' ->\n    live_node gst' h.\nProof using.\n  intuition.\n  find_copy_apply_lem_hyp live_node_means_state_exists.\n  break_exists.\n  eapply live_node_equivalence.\n  * repeat find_rewrite; eauto.\n  * repeat find_rewrite; eauto.\n  * repeat find_rewrite; eauto.\n  * repeat find_rewrite; eauto.\n  * repeat find_rewrite; eauto.\n  * repeat find_rewrite; eauto.\nQed.\n\nLemma adding_nodes_does_not_affect_live_node :\n  forall gst gst' h n st,\n    ~ In n (nodes gst) ->\n    sigma gst' = update addr_eq_dec (sigma gst) n (Some st) ->\n    nodes gst' = n :: nodes gst ->\n    failed_nodes gst' = failed_nodes gst ->\n    live_node gst h ->\n    live_node gst' h.\nProof using.\n  intuition.\n  break_live_node_name d.\n  repeat split.\n  * repeat find_rewrite.\n    now apply in_cons.\n  * by find_rewrite.\n  * exists d.\n    split => //.\n    repeat find_reverse_rewrite.\n    find_rewrite.\n    find_rewrite.\n    apply update_diff.\n    congruence.\nQed.\n\n(* reverse of the above, with additional hypothesis that h <> n. *)\nLemma adding_nodes_did_not_affect_live_node :\n  forall gst gst' h n st,\n    ~ In n (nodes gst) ->\n    sigma gst' = update addr_eq_dec (sigma gst) n st ->\n    nodes gst' = n :: nodes gst ->\n    failed_nodes gst' = failed_nodes gst ->\n    live_node gst' h ->\n    h <> n ->\n    live_node gst h.\nProof using.\n  intuition.\n  unfold live_node.\n  break_live_node_name d.\n  repeat split.\n  * repeat find_rewrite.\n    find_apply_lem_hyp in_inv.\n    break_or_hyp; congruence.\n  * repeat find_rewrite.\n    auto.\n  * exists d.\n    split => //.\n    repeat find_reverse_rewrite.\n    find_rewrite.\n    find_rewrite.\n    find_rewrite.\n    find_rewrite.\n    symmetry.\n    apply update_diff; auto.\nQed.\n\nLemma adding_nodes_does_not_affect_dead_node :\n  forall gst gst' h n st,\n    ~ In n (nodes gst) ->\n    sigma gst' = update addr_eq_dec (sigma gst) n st ->\n    nodes gst' = n :: nodes gst ->\n    failed_nodes gst' = failed_nodes gst ->\n    dead_node gst h ->\n    dead_node gst' h.\nProof using.\n  intuition.\n  break_dead_node_name d.\n  repeat split.\n  - find_rewrite.\n    eauto using in_cons.\n  - find_rewrite; auto.\n  - exists d.\n    repeat find_reverse_rewrite.\n    find_rewrite.\n    find_rewrite.\n    eapply update_diff.\n    congruence.\nQed.\n\n\n(* use lemma from Update.v instead *)\nLemma update_determined_by_f :\n  forall A (f : addr -> A) x d d' y,\n    y <> x ->\n    update addr_eq_dec f x d y = d' ->\n    f y = d'.\nProof using.\n  intuition.\n  symmetry.\n  repeat find_reverse_rewrite.\n  apply update_diff.\n  now apply not_eq_sym.\nQed.\n\nLemma adding_nodes_did_not_affect_dead_node :\n  forall gst gst' h n st,\n    ~ In n (nodes gst) ->\n    In h (nodes gst) ->\n    sigma gst' = update addr_eq_dec (sigma gst) n st ->\n    nodes gst' = n :: nodes gst ->\n    failed_nodes gst' = failed_nodes gst ->\n    dead_node gst' h ->\n    dead_node gst h.\nProof using.\n  intuition.\n  break_dead_node_name d.\n  unfold dead_node.\n  repeat split.\n  - find_rewrite.\n    eauto using in_cons.\n  - now repeat find_rewrite.\n  - eexists.\n    eapply update_determined_by_f.\n    * instantiate (1 := n).\n      eauto using In_notIn_implies_neq.\n    * repeat find_rewrite; eauto.\nQed.\n\nLemma coarse_dead_node_characterization :\n  forall gst gst' h,\n    dead_node gst h ->\n    sigma gst' = sigma gst ->\n    nodes gst' = nodes gst ->\n    failed_nodes gst' = failed_nodes gst ->\n    dead_node gst' h.\nProof using.\n  intuition.\n  break_dead_node_name d.\n  repeat split; try (find_rewrite; auto).\n  now exists d.\nQed.\n\nLemma coarse_best_succ_characterization :\n  forall gst gst' h s,\n    best_succ gst h s ->\n    sigma gst' = sigma gst ->\n    nodes gst' = nodes gst ->\n    failed_nodes gst' = failed_nodes gst ->\n    best_succ gst' h s.\nProof using.\n  unfold best_succ in *.\n  intuition.\n  break_exists_exists.\n  break_and.\n  repeat break_and_goal.\n  - eapply live_node_equivalence; eauto.\n    now repeat find_rewrite.\n  - now repeat find_rewrite.\n  - easy.\n  - move => o H_in.\n    find_apply_hyp_hyp.\n    eapply coarse_dead_node_characterization; eauto.\n  - eapply coarse_live_node_characterization; eauto.\nQed.\n\nLemma adding_nodes_does_not_affect_best_succ :\n  forall gst gst' h s n st,\n    best_succ gst h s ->\n    ~ In n (nodes gst) ->\n    sigma gst' = update addr_eq_dec (sigma gst) n (Some st) ->\n    nodes gst' = n :: nodes gst ->\n    failed_nodes gst' = failed_nodes gst ->\n    best_succ gst' h s.\nProof using.\n  unfold best_succ.\n  intuition.\n  break_exists_exists.\n  break_and.\n  repeat break_and_goal;\n    eauto using adding_nodes_does_not_affect_live_node.\n  - repeat break_live_node.\n    repeat find_rewrite.\n    match goal with\n    | H: sigma gst h = Some _ |- _ = Some _ => rewrite <- H\n    end.\n    eapply update_diff.\n    congruence.\n  - intuition.\n    find_copy_apply_hyp_hyp.\n    break_dead_node.\n    eauto using adding_nodes_does_not_affect_dead_node.\nQed.\n\nLemma global_state_eq_ext :\n  forall gst gst',\n    nodes gst = nodes gst' ->\n    failed_nodes gst = failed_nodes gst' ->\n    timeouts gst = timeouts gst' ->\n    sigma gst = sigma gst' ->\n    msgs gst = msgs gst' ->\n    trace gst = trace gst' ->\n    gst = gst'.\nProof using.\n  intros.\n  destruct gst, gst'.\n  simpl in *.\n  subst_max.\n  tauto.\nQed.\n\nDefinition channel (gst : global_state) (src dst : addr) : list payload :=\n  filterMap\n    (fun m =>\n       if (addr_eq_dec (fst m) src) && (addr_eq_dec (fst (snd m)) dst)\n       then Some (snd (snd m))\n       else None)\n    (msgs gst).\n\nLemma in_msgs_in_channel :\n  forall gst src dst p,\n    In (src, (dst, p)) (msgs gst) ->\n    In p (channel gst src dst).\nProof.\n  unfold channel.\n  intros.\n  eapply filterMap_In; eauto.\n  by case addr_eq_dec, addr_eq_dec.\nQed.\nHint Resolve in_msgs_in_channel.\n\nLemma in_channel_in_msgs :\n  forall gst src dst p,\n    In p (channel gst src dst) ->\n    In (src, (dst, p)) (msgs gst).\nProof.\n  unfold channel.\n  intros.\n  find_eapply_lem_hyp In_filterMap; eauto.\n  break_exists.\n  break_and.\n  assert (x = (src, (dst, p))).\n  { break_if; try discriminate.\n    find_apply_lem_hyp Bool.andb_true_iff; break_and.\n    repeat find_apply_lem_hyp addr_eqb_true.\n    find_injection.\n    move: H1 H2.\n    case addr_eq_dec, addr_eq_dec => H_a H_a' //=.\n    by destruct x, p; subst. }\n  now find_reverse_rewrite.\nQed.\nHint Resolve in_channel_in_msgs.\n\nLemma channel_contents :\n  forall gst src dst p,\n    In (src, (dst, p)) (msgs gst) <-> In p (channel gst src dst).\nProof using.\n  intuition.\nQed.\n\nLemma sigma_apply_handler_result_same :\n  forall h res es gst,\n    sigma (apply_handler_result h res es gst) h =\n    Some (fst (fst (fst res))).\nProof.\n  intros. unfold apply_handler_result.\n  repeat break_match. subst. simpl.\n  now rewrite_update.\nQed.\n\nLemma sigma_apply_handler_result_diff :\n  forall h h' res es gst,\n    h <> h' ->\n    sigma (apply_handler_result h res es gst) h' =\n    sigma gst h'.\nProof.\n  intros. unfold apply_handler_result.\n  repeat break_match. subst. simpl.\n  now rewrite_update.\nQed.\n\nLemma sigma_initial_st_start_handler :\n  forall gst h st,\n    initial_st gst ->\n    sigma gst h = Some st ->\n    st = fst (fst (start_handler h (nodes gst))).\nProof.\n  intros.\n  inv_prop initial_st.\n  break_and.\n  destruct (start_handler _ _) as [[d ?] ?] eqn:?.\n  simpl.\n  destruct (In_dec addr_eq_dec h (nodes gst)).\n  - apply_prop_hyp sigma start_handler;\n      intuition congruence.\n  - find_higher_order_rewrite; congruence.\nQed.\n\nLemma timeouts_apply_handler_result_diff :\n  forall h h' res es gst,\n    h <> h' ->\n    timeouts (apply_handler_result h res es gst) h' =\n    timeouts gst h'.\nProof.\n  intros. unfold apply_handler_result.\n  repeat break_match. subst. simpl.\n  now rewrite_update.\nQed.\n\nDefinition active_nodes (gst : global_state) :=\n  RemoveAll.remove_all addr_eq_dec (failed_nodes gst) (nodes gst).\n\nLemma labeled_step_dynamic_preserves_active_nodes :\n  forall gst l gst',\n    labeled_step_dynamic gst l gst' ->\n    active_nodes gst = active_nodes gst'.\nProof.\n  intros; unfold active_nodes.\n  erewrite labeled_step_dynamic_preserves_failed_nodes; eauto.\n  erewrite labeled_step_dynamic_preserves_nodes; eauto.\nQed.\n\nLemma active_nodes_always_identical :\n  forall l ex,\n    lb_execution ex ->\n    active_nodes (occ_gst (hd ex)) = l ->\n    always (fun ex' => l = active_nodes (occ_gst (hd ex'))) ex.\nProof.\n  cofix c. intros.\n  constructor; destruct ex.\n  - easy.\n  - apply c; eauto using lb_execution_invar.\n    inv_prop lb_execution.\n    find_apply_lem_hyp labeled_step_dynamic_preserves_active_nodes.\n    cbn; congruence.\nQed.\n\nDefinition has_succs (gst : global_state) (h : addr) (succs : list pointer) :=\n  exists st,\n    sigma gst h = Some st /\\\n    succ_list st = succs.\n\nLemma has_succs_intro :\n  forall gst h succs st,\n    sigma gst h = Some st ->\n    succ_list st = succs ->\n    has_succs gst h succs.\nProof.\n  eexists; eauto.\nQed.\n\nLemma initial_nodes_large :\n  forall gst,\n    initial_st gst ->\n    3 <= length (nodes gst).\nProof.\n  unfold initial_st.\n  intros.\n  break_and.\n  assert (2 <= Chord.SUCC_LIST_LEN)\n    by apply Chord.succ_list_len_lower_bound.\n  omega.\nQed.\n\n\nLemma Tick_in_initial_st :\n  forall gst h,\n    initial_st gst ->\n    In h (nodes gst) ->\n    timeouts gst h = [Tick].\nProof.\n  intros.\n  find_copy_eapply_lem_hyp initial_nodes_large.\n  unfold initial_st in *.\n  break_and.\n  destruct (start_handler h (nodes gst)) as [[? ?] nts] eqn:?.\n  assert ([Tick] = nts).\n  {\n    pose proof (sort_by_between_permutes h (map make_pointer (nodes gst)) _ eq_refl).\n    find_copy_apply_lem_hyp Permutation.Permutation_length.\n    find_rewrite_lem map_length.\n    destruct (sort_by_between h (map make_pointer (nodes gst))) as [| ? [|? ?]] eqn:? in *;\n      change ChordIDParams.name with addr in *;\n      simpl in *; try omega.\n    unfold start_handler in *.\n    change ChordIDParams.name with addr in *;\n      repeat find_rewrite.\n    now find_inversion.\n  }\n  find_rewrite.\n  eapply_prop_hyp start_handler start_handler; auto.\n  tauto.\nQed.\n\nLemma in_nodes_sigma_some :\n  forall gst h,\n    initial_st gst ->\n    In h (nodes gst) ->\n    exists st,\n      sigma gst h = Some st.\nProof.\n  intros. unfold initial_st in *. intuition.\n  match goal with\n  | H : context [start_handler] |- _ =>\n    remember H as Hsh; clear HeqHsh; clear H\n  end.\n  specialize (Hsh h). concludes.\n  destruct (start_handler h (nodes gst)) as [[st ms] nts].\n  specialize (Hsh st ms nts). intuition.\n  eauto.\nQed.\n\nLemma exists_node_in_initial_st :\n  forall gst,\n    initial_st gst ->\n    exists h,\n      In h (nodes gst) /\\ ~ In h (failed_nodes gst).\nProof.\n  intros. unfold initial_st in *. intuition.\n  destruct (nodes gst); simpl in *; [omega|].\n  repeat find_rewrite.\n  eexists; intuition; eauto.\nQed.\n\nLemma start_handler_init_state_preset :\n  forall h knowns,\n    length knowns > 1 ->\n    start_handler h knowns =\n    (init_state_preset h\n                       (find_pred h (sort_by_between h (map make_pointer knowns)))\n                       (chop_succs (List.tl (sort_by_between h (map make_pointer knowns)))),\n     nil,\n     Tick :: nil).\nProof.\n  intros.\n  unfold start_handler.\n  repeat break_match;\n    match goal with H : _ = _ |- _ => symmetry in H end;\n    find_copy_apply_lem_hyp sort_by_between_permutes;\n    [| | reflexivity];\n    find_apply_lem_hyp Permutation.Permutation_length;\n    rewrite map_length in H0; simpl in *; repeat find_reverse_rewrite;\n      exfalso; eapply gt_irrefl; eauto.\nQed.\n\nLemma live_node_in_initial_st :\n  forall gst,\n    initial_st gst ->\n    exists h,\n      live_node gst h.\nProof.\n  intros.\n  find_copy_apply_lem_hyp exists_node_in_initial_st.\n  break_exists_name h; exists h. intuition.\n  find_copy_eapply_lem_hyp in_nodes_sigma_some; eauto.\n  break_exists_name st. unfold live_node. intuition.\n  exists st. intuition.\n  find_apply_lem_hyp sigma_initial_st_start_handler; auto. subst.\n  pose proof succ_list_len_lower_bound.\n  rewrite start_handler_init_state_preset;\n    [|unfold initial_st in *; intuition].\n  reflexivity.\nQed.\n\nLemma sorted_knowns_same_length :\n  forall h ks,\n    length (sort_by_between h (map make_pointer ks)) = length ks.\nProof.\n  intros.\n  pose proof (sort_by_between_permutes h (map make_pointer ks) ltac:(eauto) ltac:(eauto)).\n  find_apply_lem_hyp Permutation.Permutation_length.\n  find_reverse_rewrite.\n  apply map_length.\nQed.\nHint Rewrite sorted_knowns_same_length.\n\n\nLemma initial_start_handler_st_joined :\n  forall h ks st ms nts,\n    start_handler h ks = (st, ms, nts) ->\n    length ks > 1 ->\n    joined st = true.\nProof.\n  intros.\n  unfold start_handler, empty_start_res, init_state_join, init_state_preset in *.\n  repeat break_match; try find_injection.\n  - rewrite <- (sorted_knowns_same_length h) in *.\n    find_rewrite.\n    simpl in *; omega.\n  - rewrite <- (sorted_knowns_same_length h) in *.\n    find_rewrite.\n    simpl in *; omega.\n  - reflexivity.\nQed.\n\nLemma initial_nodes_live :\n  forall gst h,\n    initial_st gst ->\n    In h (nodes gst) ->\n    live_node gst h.\nProof.\n  intros.\n  destruct (start_handler h (nodes gst)) as [[?st ?ms] ?nts] eqn:?.\n  inv_prop initial_st; break_and.\n  eapply live_node_characterization.\n  - apply_prop_hyp sigma start_handler; break_and; eauto.\n  - find_copy_apply_lem_hyp initial_nodes_large.\n    eapply initial_start_handler_st_joined; eauto; omega.\n  - auto.\n  - repeat find_rewrite; in_crush.\nQed.\nHint Resolve initial_nodes_live.\n\nTheorem initial_succ_list :\n  forall h gst st,\n    initial_st gst ->\n    In h (nodes gst) ->\n    sigma gst h = Some st ->\n    succ_list st = chop_succs (List.tl (sort_by_between h (map make_pointer (nodes gst)))).\nProof.\n  intros.\n  inv_prop initial_st; break_and.\n  find_copy_apply_lem_hyp initial_nodes_large.\n  destruct (start_handler h (nodes gst)) as [[?st ?ms] ?nts] eqn:?.\n  copy_eapply_prop_hyp start_handler start_handler; auto; break_and.\n  rewrite start_handler_init_state_preset in Heqp; eauto with arith.\n  repeat find_rewrite; repeat find_injection.\n  simpl in *; eauto.\nQed.\nHint Rewrite initial_succ_list.\n\nLemma NoDup_map_make_pointer :\n  forall l, NoDup l ->\n  NoDup (map make_pointer l).\nProof.\nelim => //=.\nmove => a l IH H_nd.\ninversion H_nd; subst.\nfind_apply_lem_hyp IH.\napply NoDup_cons => //.\nmove {H2 H_nd IH}.\nelim: l H1 => //=.\nmove => a' l IH H_in H_in'.\nhave H_neq: a' <> a by auto.\nhave H_nin: ~ In a l by auto.\nbreak_or_hyp.\n- unfold make_pointer in H.\n  by find_injection.\n- by apply IH.\nQed.\n\nLemma initial_successor_lists_full :\n  forall h gst,\n    initial_st gst ->\n    length (chop_succs (List.tl (sort_by_between h (map make_pointer (nodes gst))))) = SUCC_LIST_LEN.\nProof.\n  intros.\n  pose proof (sorted_knowns_same_length h (nodes gst)).\n  inv_prop initial_st; break_and.\n  rewrite -H0 in H1.\n  move: H1 H0.\n  set mm := map _ _.\n  move => H_le H_eq.\n  have H_pm := sort_by_between_permutes h mm (sort_by_between h mm) (eq_refl _).\n  have H_nd := NoDup_map_make_pointer _ H2.\n  rewrite -/mm in H_nd.\n  apply NoDup_Permutation_NoDup in H_pm => //.\n  move: H_pm H_le.\n  destruct (sort_by_between _ _) eqn:?.\n  - subst; move => H_nd' H_le.\n    simpl in *; omega.\n  - intros.\n    simpl in *.\n    rewrite /chop_succs.\n    rewrite firstn_length /=.\n    rewrite min_l; omega.\nQed.\n\nLemma best_succ_preserved :\n  forall gst gst' h h0 s st st',\n    In h (nodes gst) ->\n    ~ In h (failed_nodes gst) ->\n    sigma gst h = Some st ->\n    sigma gst' = update (addr_eq_dec) (sigma gst) h (Some st') ->\n    (joined st = true -> joined st' = true) ->\n    succ_list st = succ_list st' \\/ h <> h0 ->\n    nodes gst' = nodes gst ->\n    failed_nodes gst = failed_nodes gst' ->\n    best_succ gst h0 s ->\n    best_succ gst' h0 s.\nProof.\n  unfold best_succ.\n  intros.\n  destruct (addr_eq_dec h h0).\n  {\n    symmetry in e; subst.\n    expand_def.\n    repeat find_rewrite; rewrite_update.\n    find_inversion.\n    do 3 eexists.\n    repeat break_and_goal.\n    - repeat break_live_node.\n      eapply live_node_characterization; try congruence.\n      + repeat find_rewrite; rewrite_update; eauto.\n      + find_eapply_prop joined; congruence.\n    - reflexivity.\n    - find_rewrite; eauto.\n    - intros.\n      assert (dead_node gst o) by auto.\n      inv_prop dead_node; expand_def; unfold dead_node; repeat find_rewrite.\n      rewrite_update; eauto.\n    - inv_prop live_node; expand_def.\n      destruct (addr_eq_dec h s); subst.\n      + eapply live_node_characterization;\n          repeat find_rewrite; rewrite_update; eauto.\n        find_injection; auto.\n      + eapply live_node_equivalence; eauto.\n        repeat find_rewrite; rewrite_update; auto.\n  }\n  break_exists_exists.\n  repeat break_and_goal; break_and;\n    repeat find_rewrite; rewrite_update.\n  - repeat break_live_node.\n    eapply live_node_characterization; try congruence.\n    + repeat find_rewrite; rewrite_update; eauto.\n    + congruence.\n  - auto.\n  - auto.\n  - intros.\n    assert (dead_node gst o) by auto.\n    inv_prop dead_node; expand_def; unfold dead_node; repeat find_rewrite;\n      rewrite_update; eauto.\n  - repeat break_live_node.\n    destruct (addr_eq_dec s h);\n      eapply live_node_characterization; try congruence;\n        try solve [repeat find_rewrite; rewrite_update; eauto\n                  |congruence\n                  |find_eapply_prop joined; congruence].\nQed.\nHint Resolve best_succ_preserved.\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-util/SystemLemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2542723287636454}}
{"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.  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 sovar_alpha.\nRequire Export list_tacs.\n\nLemma get_utokens_swap {o} :\n  forall s (t : @NTerm o),\n    get_utokens (swap s t) = get_utokens t.\nProof.\n  nterm_ind t as [v|f ind|op bs ind] Case; simpl; 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.\nQed.\n\nLemma get_utokens_cswap {o} :\n  forall s (t : @NTerm o),\n    get_utokens (cswap s t) = get_utokens t.\nProof.\n  nterm_ind t as [v|f ind|op bs ind] Case; simpl; 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.\nQed.\n\nLemma swapbvars_remove_nvars :\n  forall vs1 vs2 l vs,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> swapbvars (mk_swapping vs1 vs2) (remove_nvars l vs)\n       = remove_nvars (swapbvars (mk_swapping vs1 vs2) l)\n                      (swapbvars (mk_swapping vs1 vs2) vs).\nProof.\n  induction vs; introv norep disj; simpl.\n  - allrw remove_nvars_nil_r; simpl; auto.\n  - allrw remove_nvars_cons_r; boolvar; tcsp; try (rw <- IHvs; auto); allsimpl; tcsp.\n    + provefalse.\n      allrw in_swapbvars.\n      destruct Heqb0.\n      exists a; sp.\n    + provefalse.\n      allrw in_swapbvars; exrepnd.\n      apply swapvars_eq in Heqb1; auto; subst; tcsp.\nQed.\n\nLemma free_vars_swap {o} :\n  forall (t : @NTerm o) vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> free_vars (swap (mk_swapping vs1 vs2) t)\n       = swapbvars (mk_swapping vs1 vs2) (free_vars t).\nProof.\n  nterm_ind t as [v|f ind|op bs ind] Case; introv norep disj; allsimpl; auto.\n\n  Case \"oterm\".\n  rw flat_map_map; unfold compose.\n  rw @swapbvars_flat_map.\n  apply eq_flat_maps; introv i.\n  destruct x as [l t]; simpl.\n  rw swapbvars_remove_nvars; auto.\n  erewrite ind; eauto.\nQed.\n\nLemma free_vars_cswap {o} :\n  forall (t : @NTerm o) vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> free_vars (cswap (mk_swapping vs1 vs2) t)\n       = swapbvars (mk_swapping vs1 vs2) (free_vars t).\nProof.\n  nterm_ind t as [v|f ind|op bs ind] Case; introv norep disj; allsimpl; auto.\n\n  Case \"oterm\".\n  rw flat_map_map; unfold compose.\n  rw @swapbvars_flat_map.\n  apply eq_flat_maps; introv i.\n  destruct x as [l t]; simpl.\n  rw swapbvars_remove_nvars; auto.\n  erewrite ind; eauto.\nQed.\n\nLemma subvars_d :\n  forall vs1 vs2, decidable (subvars vs1 vs2).\nProof.\n  introv.\n  unfold decidable, subvars, assert.\n  destruct (sub_vars vs1 vs2); sp.\n  right; sp.\nDefined.\n\nFixpoint bound_vars_ncl {p} (t : @NTerm p) : list NVar :=\n  match t with\n    | vterm v => []\n    | sterm f => []\n    | oterm op bts => flat_map bound_vars_bterm_ncl bts\n  end\n with bound_vars_bterm_ncl {p} (bt : BTerm) :=\n  match bt with\n  | bterm lv nt =>\n    if subvars_d (free_vars nt) lv\n    then []\n    else lv ++ bound_vars_ncl nt\n  end.\n\nLemma bound_vars_ncl_swap {o} :\n  forall (t : @NTerm o) (vs1 vs2 : list NVar),\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> bound_vars_ncl (swap (mk_swapping vs1 vs2) t)\n       = swapbvars (mk_swapping vs1 vs2) (bound_vars_ncl t).\nProof.\n  nterm_ind t as [v|f ind|op bs ind] Case; introv norep disj; allsimpl; auto.\n\n  Case \"oterm\".\n  rw @swapbvars_flat_map.\n  rw flat_map_map; unfold compose.\n  apply eq_flat_maps; introv i.\n  destruct x as [l t]; allsimpl.\n  rw @free_vars_swap; auto.\n  boolvar; allsimpl; tcsp.\n\n  - destruct n.\n    allrw subvars_prop; introv j.\n    pose proof (s (swapvar (mk_swapping vs1 vs2) x)) as h.\n    autodimp h hyp.\n    { allrw in_swapbvars.\n      exists x; dands; auto. }\n    allrw in_swapbvars; exrepnd.\n    apply swapvars_eq in h0; subst; auto.\n\n  - destruct n.\n    allrw subvars_prop; introv j.\n    allrw in_swapbvars; exrepnd; subst.\n    applydup s in j1.\n    eexists; dands; eauto.\n\n  - rw swapbvars_app; f_equal.\n    apply (ind t l); auto.\nQed.\n\nLemma bound_vars_ncl_cswap {o} :\n  forall (t : @NTerm o) (vs1 vs2 : list NVar),\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> bound_vars_ncl (cswap (mk_swapping vs1 vs2) t)\n       = swapbvars (mk_swapping vs1 vs2) (bound_vars_ncl t).\nProof.\n  nterm_ind t as [v|f ind|op bs ind] Case; introv norep disj; allsimpl; auto.\n\n  Case \"oterm\".\n  rw @swapbvars_flat_map.\n  rw flat_map_map; unfold compose.\n  apply eq_flat_maps; introv i.\n  destruct x as [l t]; allsimpl.\n  rw @free_vars_cswap; auto.\n  boolvar; allsimpl; tcsp.\n\n  - destruct n.\n    allrw subvars_prop; introv j.\n    pose proof (s (swapvar (mk_swapping vs1 vs2) x)) as h.\n    autodimp h hyp.\n    { allrw in_swapbvars.\n      exists x; dands; auto. }\n    allrw in_swapbvars; exrepnd.\n    apply swapvars_eq in h0; subst; auto.\n\n  - destruct n.\n    allrw subvars_prop; introv j.\n    allrw in_swapbvars; exrepnd; subst.\n    applydup s in j1.\n    eexists; dands; eauto.\n\n  - rw swapbvars_app; f_equal.\n    apply (ind t l); auto.\nQed.\n\nLemma sub_free_vars_swap_sub {o} :\n  forall vs1 vs2 (sub : @Sub o),\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> sub_free_vars (swap_sub (mk_swapping vs1 vs2) sub)\n       = swapbvars (mk_swapping vs1 vs2) (sub_free_vars sub).\nProof.\n  induction sub; introv norep disj; allsimpl; auto.\n  destruct a.\n  rw swapbvars_app; f_equal; tcsp.\n  rw @free_vars_swap; auto.\nQed.\n\nLemma sub_free_vars_cswap_sub {o} :\n  forall vs1 vs2 (sub : @Sub o),\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> sub_free_vars (cswap_sub (mk_swapping vs1 vs2) sub)\n       = swapbvars (mk_swapping vs1 vs2) (sub_free_vars sub).\nProof.\n  induction sub; introv norep disj; allsimpl; auto.\n  destruct a.\n  rw swapbvars_app; f_equal; tcsp.\n  rw @free_vars_cswap; auto.\nQed.\n\nLemma alphaeq_oterm_implies_combine {o} :\n  forall op bs (t : @NTerm o),\n    alphaeq (oterm op bs) t\n    -> {bs' : list BTerm\n        & t = oterm op bs'\n        # length bs = length bs'\n        # (forall b1 b2 : BTerm,\n             LIn (b1, b2) (combine bs bs')\n             -> alphaeqbt b1 b2)}.\nProof.\n  introv aeq.\n  apply alphaeq_eq in aeq.\n  apply alpha_eq_oterm_implies_combine in aeq; exrepnd.\n  exists bs'; dands; auto.\n  introv i.\n  apply aeq0 in i.\n  apply alphaeqbt_eq; auto.\nQed.\n\nLemma alphaeq_oterm_combine {o} :\n  forall op (bs1 bs2 : list (@BTerm o)),\n    alphaeq (oterm op bs1) (oterm op bs2)\n    <=>\n    (length bs1 = length bs2\n     # (forall b1 b2 : BTerm,\n          LIn (b1, b2) (combine bs1 bs2) -> alphaeqbt b1 b2)).\nProof.\n  introv.\n  rw @alphaeq_eq.\n  rw @alpha_eq_oterm_combine.\n  split; intro k; exrepnd; dands; auto; introv i; apply k in i;\n  apply alphaeqbt_eq; auto.\nQed.\n\nLemma disjoint_swapbvars3 :\n  forall bvs vs vs1 vs2 : list NVar,\n    disjoint vs1 vs2\n    -> no_repeats vs2\n    -> disjoint vs2 bvs\n    -> disjoint (remove_nvars vs1 bvs) vs\n    -> disjoint vs2 vs\n    -> length vs1 = length vs2\n    -> disjoint vs (swapbvars (mk_swapping vs1 vs2) bvs).\nProof.\n  introv d1 norep d2 d3 d4 len i j.\n  apply disjoint_sym in d3.\n  applydup d3 in i as k.\n  rw in_remove_nvars in k.\n  rw in_swapbvars in j; exrepnd; subst.\n  apply disjoint_sym in d2.\n  applydup d2 in j1 as q.\n  destruct (in_deq _ deq_nvar v' vs1) as [d|d].\n  - pose proof (swapvar_in vs1 vs2 v') as h.\n    repeat (autodimp h hyp).\n    apply d4 in h; sp.\n  - rw swapvar_not_in in i; auto.\n    rw swapvar_not_in in k; auto.\nQed.\n\nLemma map_combine_left :\n  forall (T1 T2 T3 : tuniv)\n         (f : T1 -> T3) (l1 : list T1) (l2 : list T2),\n    map (fun x => (f (fst x), snd x)) (combine l1 l2)\n    = combine (map f l1) l2.\nProof.\n  induction l1; introv; allsimpl; auto.\n  destruct l2; allsimpl; auto.\n  rw IHl1; auto.\nQed.\n\nLemma alphaeq_cswap_disj_free_vars {o} :\n  forall (t : @NTerm o) vs1 vs2,\n    length vs1 = length vs2\n    -> no_repeats vs2\n    -> disjoint (free_vars t) vs1\n    -> disjoint (allvars t) vs2\n    -> disjoint vs1 vs2\n    -> alphaeq (cswap (mk_swapping vs1 vs2) t) t.\nProof.\n  nterm_ind1s t as [v|f ind|op bs ind] Case;\n  introv len norep d1 d2 d3; allsimpl; eauto 3 with slow.\n\n  - Case \"vterm\".\n    allrw disjoint_singleton_l.\n    rw swapvar_not_in; eauto with slow.\n\n  - Case \"oterm\".\n    apply alphaeq_oterm_combine; allrw map_length; dands; auto.\n    introv i.\n    rw <- map_combine_left in i; rw in_map_iff in i; exrepnd; cpx.\n    rw in_combine_same in i1; repnd; subst; allsimpl.\n    destruct a as [l t]; allsimpl.\n    pose proof (fresh_vars (length l)\n                           ((swapbvars (mk_swapping vs1 vs2) l)\n                              ++ l\n                              ++ vs1\n                              ++ vs2\n                              ++ (free_vars t)\n                              ++ (allvars (cswap (mk_swapping vs1 vs2) t))\n                              ++ (allvars t))) as fv; exrepnd.\n    allrw disjoint_app_r; repnd.\n\n    apply (aeqbt _ lvn); allsimpl; allrw length_swapbvars; auto;\n    allrw disjoint_app_r; tcsp.\n    disj_flat_map; allsimpl; allrw disjoint_app_l; repnd.\n\n    rw @cswap_cswap.\n    rw mk_swapping_app; auto.\n    rw <- @cswap_app_cswap; eauto with slow.\n    rw <- mk_swapping_app; auto.\n    rw <- @cswap_cswap.\n    apply (ind t _ l); allrw @osize_cswap; eauto 3 with slow.\n\n    + rw @free_vars_cswap; eauto with slow.\n      apply disjoint_sym.\n      apply disjoint_swapbvars3; eauto with slow.\n\n    + apply disjoint_sym.\n      apply disjoint_allvars_cswap; eauto with slow.\nQed.\n\n\n(*\n*** Local Variables:\n*** coq-load-path: (\".\" \"../util/\")\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/terms/swap_props.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.25417941912038805}}
{"text": "From Coq Require Import List Vectors.Fin Arith.Compare_dec Lia Program.\nImport ListNotations.\n\nFrom CasperCBC Require Import Preamble ListExtras VLSM.Common VLSM.Equivocators.Common.\n\n(** * VLSM Projecting Equivocator Traces *)\n\nSection equivocator_vlsm_projections.\n\n(**\nGiven an [equivocator_vlsm] trace ending in a state <<s>>, we can obtain a\ntrace in the original vlsm leading to the <<si>>, the  <<i>>th internal\nstate in <<s>>, by extracting a path leading to si.\n\nThis section is devoting to formalizing this projects studying its\nproperties. In particular, we show that given a [protocol_trace] for\nthe [equivocator_vlsm], we can always extract such a trace for any valid\nindex, and, furthermore, that the trace extracted is protocol for the\noriginal machine.\n*)\n\nContext\n  {message : Type}\n  (X : VLSM message)\n  (equivocator_vlsm := equivocator_vlsm X)\n  (MachineDescriptor := MachineDescriptor X)\n  .\n\nLocal Ltac unfold_transition H :=\n  ( unfold transition in H; unfold equivocator_vlsm in H\n  ; unfold Common.equivocator_vlsm in H\n  ; unfold mk_vlsm in H; unfold machine in H\n  ; unfold projT2 in H; unfold equivocator_vlsm_machine in H\n  ; unfold equivocator_transition in H).\n\n(** Given a [transition_item] <<item>> for the [equivocator_vlsm] and a\n[MachineDescriptor] referring to a position in the [destination] of <<item>>,\nit returns a transition item for the original machine (if the descriptor\nmatches the copy affected by this transition) and a new machine descriptor\nreferring to a position in the state prior to the transition.\n*)\nDefinition equivocator_vlsm_transition_item_project\n  (item : vtransition_item equivocator_vlsm)\n  (descriptor : MachineDescriptor)\n  : option (option (vtransition_item X) * MachineDescriptor)\n  :=\n  match descriptor with\n  | NewMachine _ _ => Some (None, descriptor)\n  | Existing _ j _ =>\n    match item with {| l := (lx, descriptor); input := im; output := om; destination := s |} =>\n      let (n, bs) := s in\n      match (le_lt_dec (S n) j) with\n      | right lt_jn =>\n        let nj := of_nat_lt lt_jn in\n        let item' := {| l := lx; input := im; output := om; destination := bs nj|} in\n        match descriptor with\n        | NewMachine _ s =>\n          if nat_eq_dec (S j) (S n) then (* this is the first state *)\n            Some ( None, descriptor)\n          else Some (None, Existing _ j false)\n        | Existing _ i is_equiv =>\n          match is_equiv with\n          | false => (* no equivocation *)\n            if nat_eq_dec i j then\n              Some ( Some item', descriptor)\n            else Some (None, Existing _ j false)\n          | true => (* equivocation: transition happens on the copy *)\n            if nat_eq_dec (S j) (S n) then\n              Some (Some item', descriptor)\n            else Some (None, Existing _ j false)\n          end\n        end\n      | _ => None\n      end\n    end\n  end.\n\n(**\nSince equivocators always have machine 0, We can always project a 'valid'\nequivocator 'transition item' to component 0.\n*)\n\nLemma equivocators_vlsm_transition_item_project_zero_descriptor\n  (item : vtransition_item equivocator_vlsm)\n  s\n  (Ht : vtransition equivocator_vlsm (l item) (s, input item) = (destination item, output item))\n  (Hv : vvalid equivocator_vlsm (l item) (s, input item))\n  : exists oitem, equivocator_vlsm_transition_item_project item (Existing _ 0 false) = Some (oitem, Existing _ 0 false).\nProof.\n  unfold equivocator_vlsm_transition_item_project.\n  destruct item.\n  destruct l as (l, dl). destruct destination as (ndest, bdest).\n  destruct (le_lt_dec (S ndest) 0); [lia|].\n  destruct dl as [ndl | idl fdl]\n  ; [destruct (nat_eq_dec 1 (S ndest))| destruct fdl; [destruct (nat_eq_dec 1 (S ndest))| destruct (nat_eq_dec idl 0)]]\n  ; simpl in Ht; unfold vtransition in Ht; unfold_transition Ht; unfold snd in Ht\n  ; destruct Hv as [Hidl _].\n  - inversion Ht. subst. destruct s; inversion H0. lia.\n  - exists None. reflexivity.\n  - destruct (le_lt_dec (S (projT1 s)) idl); [lia|].\n    match type of Ht with\n    | (let (_, _) := ?t in _) = _ => destruct t\n    end.\n    inversion Ht. subst. destruct s; inversion H0. lia.\n  - exists None. reflexivity.\n  - subst idl. eexists _. reflexivity.\n  - exists None. reflexivity.\nQed.\n\n(**\nAn injectivity result for [equivocator_vlsm_transition_item_project].\n*)\nLemma equivocator_vlsm_transition_item_project_some_inj\n  {item : vtransition_item equivocator_vlsm}\n  {itemX itemX' : vtransition_item X}\n  {i i' : nat}\n  {fi fi' : bool}\n  (idescriptor := Existing _ i fi)\n  (idescriptor' := Existing _ i' fi')\n  {odescriptor odescriptor' : MachineDescriptor}\n  (HitemX : equivocator_vlsm_transition_item_project item idescriptor = Some (Some itemX, odescriptor))\n  (HitemX' : equivocator_vlsm_transition_item_project item idescriptor' = Some (Some itemX', odescriptor'))\n  : i = i' /\\ itemX = itemX' /\\ odescriptor = odescriptor'.\nProof.\n  unfold equivocator_vlsm_transition_item_project in *.\n  unfold idescriptor in *. clear idescriptor.\n  unfold idescriptor' in *. clear idescriptor'.\n  destruct item.\n  destruct l as (ls, descriptor).\n  destruct destination as (ndest, bdest).\n  destruct (le_lt_dec (S ndest) i); [congruence|].\n  destruct (le_lt_dec (S ndest) i'); [congruence|].\n  destruct descriptor as [sn | j fj].\n  - destruct (nat_eq_dec (S i) (S ndest)); congruence.\n  - destruct fj as [|] eqn:Hfj.\n    + destruct (nat_eq_dec (S i) (S ndest)); [|congruence].\n      inversion HitemX; subst. clear HitemX.\n      inversion e. subst i. clear e.\n      destruct (nat_eq_dec (S i') (S ndest)); [|congruence].\n      inversion HitemX'; subst. clear HitemX'.\n      inversion e; subst i'; clear e.\n      replace (of_nat_lt l0) with (of_nat_lt l) by apply of_nat_ext.\n      repeat split; reflexivity.\n    + destruct (nat_eq_dec j i); [|congruence].\n      destruct (nat_eq_dec j i'); [|congruence].\n      inversion HitemX. inversion HitemX'. subst.\n      replace (of_nat_lt l0) with (of_nat_lt l) by apply of_nat_ext.\n      repeat split; reflexivity.\nQed.\n\n(**\n[equivocator_vlsm_transition_item_project] only fails for an out-of-range\ndescriptor.\n*)\nLemma equivocator_transition_item_project_inv_none\n  (item : vtransition_item equivocator_vlsm)\n  (descriptor : MachineDescriptor)\n  (Hitem: equivocator_vlsm_transition_item_project item descriptor = None)\n  : exists\n    (i : nat)\n    (is_equiv : bool)\n    (Hdescriptor : descriptor = Existing _ i is_equiv),\n    projT1 (destination item) < i.\nProof.\n  unfold equivocator_vlsm_transition_item_project in Hitem.\n  destruct item.\n  destruct descriptor as [s|i is_equiv]; [congruence|].\n  exists i. exists is_equiv. exists eq_refl.\n  destruct destination as (n, bs).\n  destruct (le_lt_dec (S n) i); [assumption|].\n  destruct l as (ls, [is | ix [|]]).\n  - destruct (nat_eq_dec (S i) (S n)); congruence.\n  - destruct (nat_eq_dec (S i) (S n)); congruence.\n  - destruct (nat_eq_dec ix i); congruence.\nQed.\n\nLemma equivocator_transition_item_project_proper\n  (item : vtransition_item equivocator_vlsm)\n  (descriptor : MachineDescriptor)\n  (Hproper : proper_descriptor X descriptor (destination item))\n  : equivocator_vlsm_transition_item_project item descriptor <> None.\nProof.\n  intro contra.\n  apply equivocator_transition_item_project_inv_none in contra.\n  destruct contra as [id [fd [Heqd Hd]]].\n  subst. simpl in *. lia.\nQed.\n\n(**\nIf [equivocator_vlsm_transition_item_project] produces a transition item,\nthen that item has the same [input] and [output] as the argument item.\n*)\nLemma equivocator_transition_item_project_inv_messages\n  (item : vtransition_item equivocator_vlsm)\n  (itemX : vtransition_item X)\n  (idescriptor odescriptor : MachineDescriptor)\n  (Hitem : equivocator_vlsm_transition_item_project item idescriptor = Some (Some itemX, odescriptor))\n  : exists\n    (i : nat)\n    (is_equiv : bool),\n    idescriptor = Existing _ i is_equiv /\\\n    proper_descriptor X idescriptor (destination item) /\\\n    input item = input itemX /\\ output item = output itemX.\nProof.\n  unfold equivocator_vlsm_transition_item_project in Hitem.\n  destruct idescriptor as [s|j fj]; [congruence|].\n  exists j. exists fj. split; [reflexivity|].\n  destruct item.\n  destruct destination as (n, bs).\n  destruct l as (lx, descriptorx).\n  destruct (le_lt_dec (S n) j); [congruence|].\n  destruct descriptorx as [s | i' [|]] eqn:Hl; simpl.\n  - destruct (nat_eq_dec (S j) (S n)); congruence.\n  - destruct (nat_eq_dec (S j) (S n)); [|congruence].\n    split; [assumption|].\n    inversion Hitem. subst. repeat split; reflexivity.\n  - destruct (nat_eq_dec i' j); [|congruence].\n    split; [assumption|].\n    inversion Hitem. subst. repeat split; reflexivity.\nQed.\n\n(**\nIf the 'destination' of a 'valid' equivocator 'transition_item' is singleton,\nthen by projecting the item to component 0 we actually obtain a\n'transition_item' for the original machine.\n*)\nLemma no_equivocating_equivocator_transition_item_project\n  (item : vtransition_item equivocator_vlsm)\n  (Hno_equiv_item : is_singleton_state X (destination item))\n  (s : vstate equivocator_vlsm)\n  (Hv : vvalid equivocator_vlsm (l item) (s, input item))\n  (Ht : vtransition equivocator_vlsm (l item) (s, input item) = (destination item, output item))\n  : equivocator_vlsm_transition_item_project item (Existing _ 0 false) =\n      Some (Some\n        {| l := fst (l item); input := input item; output := output item; destination := equivocator_state_descriptor_project X (destination item) (Existing _ 0 false) |}\n        , Existing _ 0 false).\nProof.\n  destruct item.\n  unfold Common.l, Common.input, Common.output, Common.destination in *.\n  unfold equivocator_vlsm_transition_item_project.\n  destruct l as (li, eqvi).\n  destruct destination as (ni, bsi) eqn:Hdesti.\n  destruct (le_lt_dec (S ni) 0); [lia|].\n  specialize\n    (equivocator_transition_no_equivocation_zero_descriptor X _ _ _ _ _ Hv Ht Hno_equiv_item)\n    as Heq_eqvi.\n  simpl in Heq_eqvi. subst eqvi.\n  destruct (nat_eq_dec 0 0); [|congruence].\n  reflexivity.\nQed.\n\n\nLemma equivocator_transition_item_project_proper_characterization\n  (item : vtransition_item equivocator_vlsm)\n  (descriptor : MachineDescriptor)\n  (Hproper : proper_descriptor X descriptor (destination item))\n  : exists oitem descriptor',\n    equivocator_vlsm_transition_item_project item descriptor = Some (oitem, descriptor')\n    /\\ match oitem with\n      | Some itemx =>\n        l itemx = fst (l item) /\\  input item = input itemx /\\ output item = output itemx /\\\n        (equivocator_state_descriptor_project X (destination item) descriptor = destination itemx)\n      | None => True\n      end\n    /\\ forall\n      (s : vstate equivocator_vlsm)\n      (Hv : vvalid equivocator_vlsm (l item) (s, input item))\n      (Ht : vtransition equivocator_vlsm (l item) (s, input item) = (destination item, output item)),\n      proper_descriptor X descriptor' s /\\\n      match oitem with\n      | Some itemx =>\n        forall (sx : vstate X)\n          (Hsx : sx = equivocator_state_descriptor_project X s descriptor'),\n          vvalid X (l itemx) (sx, input itemx) /\\\n          vtransition X (l itemx) (sx, input itemx) = (destination itemx, output itemx)\n      | None =>\n        equivocator_state_descriptor_project X (destination item) descriptor = equivocator_state_descriptor_project X s descriptor'\n      end.\nProof.\n  destruct item. simpl. simpl in Hproper.\n  unfold equivocator_vlsm_transition_item_project.\n  destruct descriptor eqn:Heqvi.\n  - exists None. eexists _. split; [reflexivity|].\n    intros. split; [exact I|]. intros.\n    split; [|reflexivity].\n    assumption.\n  - destruct l as (li, eqvi).\n    simpl in Hproper.\n    destruct destination as (ni, bsi) eqn:Hdesti.\n    simpl in Hproper.\n    destruct (le_lt_dec (S ni) n); [lia|].\n    destruct eqvi as [nsi | ieqvi feqvi].\n    + destruct (nat_eq_dec (S n) (S ni)).\n      * exists None. eexists _. split; [reflexivity|]. split; [exact I|].\n        intros.\n        inversion e. subst. clear e.\n        split; [apply Hv|].\n        apply\n          (new_machine_label_equivocator_state_project_last X (li, NewMachine X nsi) s input _ output Ht nsi eq_refl b).\n      * exists None. eexists _. split; [reflexivity|]. split; [exact I|].\n        intros.\n        apply and_comm.\n        split.\n        { apply\n          (new_machine_label_equivocator_state_project_not_last X (li, NewMachine X nsi) s input _ output Ht nsi eq_refl).\n          simpl. lia.\n        }\n        simpl.\n        unfold vtransition in Ht. unfold_transition Ht. unfold snd in Ht.\n        inversion Ht. subst. clear Ht.\n        destruct s as (neqv, seqv). simpl in *. inversion H0.\n        subst ni. lia.\n    + destruct feqvi; [destruct (nat_eq_dec (S n) (S ni))|destruct (nat_eq_dec ieqvi n)].\n      * inversion e. subst ni. clear e.\n        eexists _. eexists _. split; [reflexivity|]. split; [repeat split|].\n        -- unfold equivocator_state_descriptor_project.\n          unfold equivocator_state_project.\n          destruct (le_lt_dec (S n) n); [lia|]. simpl. f_equal. apply of_nat_ext.\n        -- intros.\n          destruct Hv as [Heqv Hv].\n          split; [assumption|].\n          intros.\n          unfold equivocator_state_descriptor_project in Hsx.\n          unfold equivocator_state_project in Hsx.\n          simpl.\n          unfold fst in Hv.\n          unfold vvalid in Hv.\n          unfold vtransition in Ht.\n          unfold_transition Ht. unfold snd in Ht.\n          destruct (le_lt_dec (S (projT1 s)) ieqvi); [lia|].\n          replace (of_nat_lt l0) with (of_nat_lt Heqv) in * by apply of_nat_ext.\n          clear l0.\n          assert (Hsxi : sx = projT2 s (of_nat_lt Heqv)).\n          { subst.\n            destruct s as (nsi, si). unfold projT2.\n            simpl in Heqv.\n            destruct (le_lt_dec (S nsi) ieqvi); [lia|].\n            f_equal. apply of_nat_ext.\n          }\n          rewrite Hsxi. split; [assumption|].\n          unfold fst in Ht.\n          destruct (vtransition X li (projT2 s (of_nat_lt Heqv), input))\n            as (si'', om') eqn:Ht'.\n          inversion Ht.\n          f_equal.\n          destruct s as (ns, bs).\n          inversion H0. subst n. simpl_existT. subst bsi.\n          rewrite to_nat_of_nat.\n          destruct (nat_eq_dec (S ns) (S ns)); [|congruence].\n          reflexivity.\n      * eexists _. eexists _. split; [reflexivity|]. split; [exact I|].\n        intros.\n        apply and_comm.\n        split.\n        { apply\n            (existing_true_label_equivocator_state_project_not_last X (li, Existing X ieqvi true) s input _ output Ht _ eq_refl )\n          ; [|simpl; lia].\n          apply Hv.\n        }\n        destruct Hv as [Heqv Hv].\n        unfold vtransition in Ht. unfold_transition Ht. unfold snd in Ht.\n        destruct (le_lt_dec (S (projT1 s)) ieqvi); [lia|].\n        destruct (vtransition X (fst (li, Existing X ieqvi true))\n        (projT2 s (of_nat_lt l0), input))\n          as (si', om').\n        inversion Ht. subst.\n        destruct s as (neqv, seqv). simpl in *.\n        inversion H0. subst ni. lia.\n      * subst ieqvi.\n        eexists _. eexists _. split; [reflexivity|].\n        split; [repeat split|].\n        -- unfold equivocator_state_descriptor_project.\n          unfold equivocator_state_project.\n          destruct (le_lt_dec (S ni) n); [lia|]. simpl. f_equal. apply of_nat_ext.\n        -- intros.  destruct Hv as [Heqv Hv].\n          split; [assumption|].\n          intros. simpl.\n          unfold equivocator_state_descriptor_project in Hsx.\n          unfold equivocator_state_project in Hsx.\n          unfold fst in Hv.\n          unfold vvalid in Hv.\n          unfold vtransition in Ht. unfold_transition Ht. unfold snd in Ht.\n          destruct (le_lt_dec (S (projT1 s)) n); [lia|].\n          replace (of_nat_lt l0) with (of_nat_lt Heqv) in * by apply of_nat_ext.\n          clear l0.\n          assert (Hsxi : sx = projT2 s (of_nat_lt Heqv)).\n          { subst.\n            destruct s as (nsi, si). unfold projT2.\n            simpl in Heqv.\n            destruct (le_lt_dec (S nsi) n); [lia|].\n            f_equal. apply of_nat_ext.\n          }\n          rewrite Hsxi. split; [assumption|].\n          unfold fst in Ht.\n          destruct (vtransition X li (projT2 s (of_nat_lt Heqv), input))\n            as (si'', om') eqn:Ht'.\n          inversion Ht. clear Ht. subst ni.\n          simpl_existT. subst bsi.\n          f_equal.\n          rewrite eq_dec_if_true; [reflexivity|].\n          apply of_nat_ext.\n      * eexists _. eexists _. split; [reflexivity|]. split; [exact I|].\n        intros.\n        apply and_comm.\n        split.\n        { apply\n            (existing_false_label_equivocator_state_project_not_same X (li, Existing X ieqvi false) s input _ output Ht _ eq_refl)\n          ; [| simpl; lia|assumption].\n          destruct Hv as [Hieqvi Hv].\n          assumption.\n        }\n        destruct Hv as [Heqv Hv].\n        unfold vtransition in Ht. unfold_transition Ht. unfold snd in Ht.\n        destruct (le_lt_dec (S (projT1 s)) ieqvi); [lia|].\n        unfold fst in Ht.\n        destruct (vtransition X li (projT2 s (of_nat_lt l0), input))\n          as (si', om').\n        inversion Ht. subst. simpl. lia.\nQed.\n\nLemma equivocator_transition_item_project_inv_characterization\n  (item : vtransition_item equivocator_vlsm)\n  (itemx : vtransition_item X)\n  (descriptor descriptor' : MachineDescriptor)\n  (Hitem : equivocator_vlsm_transition_item_project item descriptor = Some (Some itemx, descriptor'))\n  : l itemx = fst (l item) /\\  input item = input itemx /\\ output item = output itemx /\\\n    (equivocator_state_descriptor_project X (destination item) descriptor = destination itemx)\n    .\nProof.\n  apply equivocator_transition_item_project_inv_messages in Hitem as Hitem'.\n  destruct Hitem' as [_ [_ [_ [Hproper _]]]].\n  apply equivocator_transition_item_project_proper_characterization in Hproper.\n  destruct Hproper as [oitem [odescriptor [Hpr' H]]].\n  rewrite Hpr' in Hitem.\n  inversion Hitem. subst. apply H.\nQed.\n\n(**\nThe projection of an [equivocator_vlsm] trace is obtained by traversing the\ntrace from right to left guided by the descriptors produced by\n[equivocator_vlsm_transition_item_project] and gathering all non-empty\n[transition_item]s it produces.\n*)\nDefinition equivocator_vlsm_trace_project\n  (tr : list (vtransition_item equivocator_vlsm))\n  (descriptor : MachineDescriptor)\n  : option (list (vtransition_item X) * MachineDescriptor)\n  :=\n  fold_right\n    (fun item result =>\n      match result with\n      | None => None\n      | Some (r, idescriptor) =>\n        match equivocator_vlsm_transition_item_project item idescriptor 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    )\n    (Some ([], descriptor))\n    tr.\n\n(**\nProjecting on a [NewMachine] descriptor yields an empty trace and the same\ndescriptor.\n*)\nLemma equivocator_vlsm_trace_project_on_new_machine\n  (tr : list (vtransition_item equivocator_vlsm))\n  (s : vstate X)\n  : equivocator_vlsm_trace_project tr (NewMachine _ s) = Some ([], NewMachine _ s).\nProof.\n  induction tr; [reflexivity|].\n  simpl. rewrite IHtr. reflexivity.\nQed.\n\n(** [equivocator_vlsm_trace_project] acts like a morphism w.r.t. concatenation\n(single element in left operand case).\n*)\nLemma equivocator_vlsm_trace_project_cons\n  (bprefix : vtransition_item equivocator_vlsm)\n  (bsuffix : list (vtransition_item equivocator_vlsm))\n  (dstart dlast : MachineDescriptor)\n  (tr : list (vtransition_item X))\n  (Hproject : equivocator_vlsm_trace_project ([bprefix] ++ bsuffix) dlast = Some (tr, dstart))\n  : exists\n    (dmiddle : MachineDescriptor)\n    (prefix suffix : list (vtransition_item X))\n    (Hprefix : equivocator_vlsm_trace_project [bprefix] dmiddle = Some (prefix, dstart))\n    (Hsuffix : equivocator_vlsm_trace_project bsuffix dlast = Some (suffix, dmiddle)),\n    tr = prefix ++ suffix.\nProof.\n  simpl in Hproject.\n  destruct (equivocator_vlsm_trace_project bsuffix dlast) as [(suffix, dmiddle)|]\n    eqn:Hsuffix\n  ; [|congruence].\n  exists dmiddle.\n  destruct (equivocator_vlsm_transition_item_project bprefix dmiddle) as [[[prefix|] i]|]\n    eqn:Hprefix\n  ; inversion Hproject; subst; clear Hproject.\n  - exists [prefix]. exists suffix.\n    repeat split.\n    simpl in *. rewrite Hprefix. reflexivity.\n  -  exists []. exists tr.\n    repeat split.\n    simpl in *. rewrite Hprefix. reflexivity.\nQed.\n\n(** [equivocator_vlsm_trace_project] acts like a morphism w.r.t. concatenation\n*)\nLemma equivocator_vlsm_trace_project_app\n  (bprefix bsuffix : list (vtransition_item equivocator_vlsm))\n  (dlast dstart : MachineDescriptor)\n  (tr : list (vtransition_item X))\n  (Hproject : equivocator_vlsm_trace_project (bprefix ++ bsuffix) dlast = Some (tr, dstart))\n  : exists\n    (dmiddle : MachineDescriptor)\n    (prefix suffix : list (vtransition_item X))\n    (Hprefix : equivocator_vlsm_trace_project bprefix dmiddle = Some (prefix, dstart))\n    (Hsuffix : equivocator_vlsm_trace_project bsuffix dlast = Some (suffix, dmiddle)),\n    tr = prefix ++ suffix.\nProof.\n  generalize dependent dstart. generalize dependent tr.\n  induction bprefix; intros.\n  - exists dstart. exists []. exists tr. exists eq_refl. exists Hproject. reflexivity.\n  - rewrite <- app_comm_cons in Hproject.\n    apply equivocator_vlsm_trace_project_cons in Hproject.\n    destruct Hproject as [da [prefixa [tr' [Ha [Hproject Heq]]]]].\n    spec IHbprefix tr' da Hproject.\n    destruct IHbprefix as [dmiddle [prefix' [suffix [Hprefix [Hsuffix Htr']]]]].\n    exists dmiddle.\n    exists (prefixa ++ prefix'). exists suffix.\n    repeat split; [|assumption|].\n    + simpl. rewrite Hprefix.\n      simpl in Ha.\n      destruct (equivocator_vlsm_transition_item_project a da)\n        as [(oitem', i)|]\n      ; [|congruence].\n      destruct oitem' as [item'|]; inversion Ha; subst; reflexivity.\n    + subst. rewrite app_assoc. reflexivity.\nQed.\n\n(** [equivocator_vlsm_trace_project] acts like a morphism w.r.t. concatenation\n(converse)\n*)\nLemma equivocator_vlsm_trace_project_app_inv\n  (bprefix bsuffix : list (vtransition_item equivocator_vlsm))\n  (dlast dstart dmiddle : MachineDescriptor)\n  (prefix suffix : list (vtransition_item X))\n  (Hprefix : equivocator_vlsm_trace_project bprefix dmiddle = Some (prefix, dstart))\n  (Hsuffix : equivocator_vlsm_trace_project bsuffix dlast = Some (suffix, dmiddle))\n  : equivocator_vlsm_trace_project (bprefix ++ bsuffix) dlast = Some (prefix ++ suffix, dstart).\nProof.\n  generalize dependent dstart. generalize dependent prefix.\n  induction bprefix; intros.\n  - inversion Hprefix. subst. assumption.\n  - simpl in Hprefix.\n    destruct (equivocator_vlsm_trace_project bprefix dmiddle) as [(prefix', dstart')|]\n      eqn:Hprefix'\n    ; [|congruence].\n    specialize (IHbprefix prefix' dstart' eq_refl).\n    simpl. rewrite IHbprefix.\n    destruct (equivocator_vlsm_transition_item_project a dstart')\n      as [[[item'|]i]|]\n    ; inversion Hprefix; subst; reflexivity.\nQed.\n\n(**\nNext we prove some inversion properties for [equivocator_vlsm_transition_item_project].\n*)\nLemma equivocator_protocol_transition_item_project_inv2\n  (l : vlabel equivocator_vlsm)\n  (s' s: vstate equivocator_vlsm)\n  (iom oom : option message)\n  (Hv: vvalid equivocator_vlsm l (s', iom))\n  (Ht: vtransition equivocator_vlsm l (s', iom) = (s, oom))\n  (item := {| l := l; input := iom; destination := s; output := oom |})\n  (di di' : MachineDescriptor)\n  (item' : vtransition_item X)\n  (Hitem: equivocator_vlsm_transition_item_project item di = Some (Some item', di'))\n  : exists\n    (i : nat)\n    (fi : bool)\n    (Hdi : di = Existing _ i fi)\n    (Hi : i < S (projT1 s))\n    (sx := projT2 s (of_nat_lt Hi))\n    (Hitem' : item' = {| l := fst l; input := iom; destination := sx; output := oom |})\n    (i' : nat)\n    (fi' : bool)\n    (Hdi' : di' = Existing _ i' fi')\n    (Hi' : i' < S (projT1 s'))\n    (s'x := projT2 s' (of_nat_lt Hi')),\n    vvalid X (fst l) (s'x, iom) /\\\n    vtransition X (fst l) (s'x, iom) = (sx, oom).\nProof.\n  unfold vvalid in Hv. unfold vtransition in Ht.\n  unfold_transition Ht.\n  simpl in Hv.\n  unfold equivocator_vlsm_transition_item_project in Hitem.\n  destruct di as [sn| i fi]; [congruence|].\n  exists i. exists fi. exists eq_refl. unfold item in Hitem.\n  destruct l as (lx, descriptor).\n  destruct s as (ns, bs).\n  destruct (le_lt_dec (S ns) i); [congruence|].\n  exists l. unfold snd in Ht. unfold snd in Hv.\n  destruct descriptor as [sn| j is_equiv].\n  - destruct (nat_eq_dec (S i) (S ns)); congruence.\n  - destruct Hv as [Hj Hv].\n    destruct (le_lt_dec (S (projT1 s')) j); [lia|].\n    replace (of_nat_lt l0) with (of_nat_lt Hj) in * by apply of_nat_ext. clear l0.\n    simpl in Ht.\n    destruct (vtransition X lx (projT2 s' (of_nat_lt Hj), iom))\n      as (si', om') eqn:Htx.\n    destruct s' as (n', bs').\n    destruct is_equiv as [|].\n    + destruct (nat_eq_dec (S i) (S ns)); [|congruence].\n      inversion Hitem. subst di' item'. clear Hitem.\n      exists eq_refl.\n      exists j. exists true. exists eq_refl.\n      exists Hj. split; [assumption|].\n      inversion Ht. subst. clear Ht. inversion e. subst i. clear e.\n      apply inj_pairT2 in H1. subst. simpl.\n      rewrite to_nat_of_nat.\n      destruct (nat_eq_dec (S n') (S n')); [assumption|].\n      elim n. reflexivity.\n    + destruct (nat_eq_dec j i); [|congruence]. subst.\n      inversion Hitem. subst di' item'. clear Hitem.\n      exists eq_refl. exists i. exists false. exists eq_refl.\n      exists Hj. split; [assumption|].\n      inversion Ht. subst. clear Ht.\n      apply inj_pairT2 in H1. subst. simpl.\n      rewrite eq_dec_if_true by apply of_nat_ext.\n      assumption.\nQed.\n\nLemma equivocator_protocol_transition_item_project_inv3\n  (l : vlabel equivocator_vlsm)\n  (s s' : vstate equivocator_vlsm)\n  (iom oom : option message)\n  (Hv: vvalid equivocator_vlsm l (s', iom))\n  (Ht: vtransition equivocator_vlsm l (s', iom) = (s, oom))\n  (item := {| l := l; input := iom; destination := s; output := oom |})\n  (di di' : MachineDescriptor)\n  (Hitem: equivocator_vlsm_transition_item_project item di = Some (None, di'))\n  : match di with\n    | NewMachine _ sn => di' = di\n    | Existing _ i fi =>\n      match di' with\n      | Existing _ i' fi' =>\n        exists\n          (Hi : i < S (projT1 s))\n          (Hi' : i' < S (projT1 s')),\n          projT2 s' (of_nat_lt Hi') = projT2 s (of_nat_lt Hi)\n      | NewMachine _ sn' =>\n        exists\n          (Hl : snd l = NewMachine _ sn')\n          (Hi : i = (projT1 s))\n          (Hiom : iom = None)\n          (Hoom : oom = None)\n          (Hsn : projT2 s (of_nat_lt (le_n (S (projT1 s)))) = sn')\n          ,\n          vinitial_state_prop X sn'\n      end\n    end.\nProof.\n  unfold vvalid in Hv. unfold vtransition in Ht.\n  destruct l as (lx, d).\n  simpl in Hv. unfold_transition Ht. unfold snd in Ht.\n  unfold equivocator_vlsm_transition_item_project in Hitem.\n  destruct di as [si | i fi]; [inversion Hitem; reflexivity|].\n  simpl in Hv. unfold item in Hitem.\n  destruct s as (ns, bs).\n  destruct (le_lt_dec (S ns) i); [congruence|].\n  destruct d as [sd | id fd].\n  - destruct (nat_eq_dec (S i) (S ns)); inversion Hitem; subst; clear Hitem.\n    + simpl. exists eq_refl. inversion e. exists eq_refl.\n      destruct s' as (ns', bs'). inversion Ht. subst.\n      simpl_existT.\n      destruct Hv. repeat split; [assumption| |assumption].\n      rewrite to_nat_of_nat.\n      destruct (nat_eq_dec (S ns') (S ns')); [|elim n]; reflexivity.\n    + simpl. exists l. inversion Ht. subst.\n      destruct s' as (ns', bs').\n      simpl in H0. inversion H0. subst.\n      simpl_existT. simpl.\n      assert (Hi : i < S ns') by lia.\n      exists Hi. subst.\n      rewrite to_nat_of_nat.\n      destruct (nat_eq_dec i (S ns')); [lia|].\n      f_equal. apply of_nat_ext.\n  - destruct Hv as [Hj Hv].\n    destruct (le_lt_dec (S (projT1 s')) id); [lia|].\n    replace (of_nat_lt l0) with (of_nat_lt Hj) in * by apply of_nat_ext. clear l0.\n    destruct s' as (n', bs'). simpl in Hv. unfold projT2 in Ht. simpl in Hj.\n    simpl in Ht.\n    destruct\n      (@vtransition message X lx\n      (@pair (@vstate message X) (option message)\n         (bs' (@of_nat_lt id (S n') Hj)) iom))\n      as (si', om') eqn:Htx.\n    destruct fd as [|].\n    + destruct (nat_eq_dec (S i) (S ns)); [congruence|].\n      inversion Hitem. subst di'. clear Hitem.\n      simpl. exists l. inversion Ht. subst.\n      assert (Hi' : i < S n') by lia.\n      exists Hi'.\n      simpl_existT. subst.\n      rewrite to_nat_of_nat in *.\n      destruct (nat_eq_dec i (S n')); [lia|].\n      f_equal.\n      apply of_nat_ext.\n    + destruct (nat_eq_dec id i); [congruence|].\n      inversion Hitem. subst di'. clear Hitem. simpl.\n      exists l. inversion Ht. subst. exists l.\n      simpl_existT. subst.\n      rewrite eq_dec_if_false; [reflexivity|].\n      intro contra. apply (f_equal to_nat) in contra.\n      repeat rewrite to_nat_of_nat in contra.\n      inversion contra. elim n. assumption.\nQed.\n\nLemma equivocator_protocol_transition_item_project_inv4\n  (l : vlabel equivocator_vlsm)\n  (s s' : vstate equivocator_vlsm)\n  (iom oom : option message)\n  (Hv: vvalid equivocator_vlsm l (s', iom))\n  (Ht: vtransition equivocator_vlsm l (s', iom) = (s, oom))\n  (i' : nat)\n  (fi' : bool)\n  (Hi' : i' < S (projT1 s'))\n  : exists\n    (Hi'' : i' < S (projT1 s))\n    (fi'' : bool)\n    (oitem : option (vtransition_item X))\n    (item := {| l := l; input := iom; destination := s; output := oom |}),\n    equivocator_vlsm_transition_item_project item (Existing _ i' fi') = Some (oitem, Existing _ i' fi'').\nProof.\n  unfold vvalid in Hv. unfold vtransition in Ht.\n  simpl in Hv. unfold_transition Ht. unfold equivocator_vlsm_transition_item_project.\n  destruct l as (lx, descriptor). simpl in Hv. unfold snd in Ht.\n  destruct s as (ns, bs).\n  destruct s' as (n', bs').\n  destruct descriptor as [sn | j is_equiv].\n  - simpl in Ht.\n    inversion Ht. subst. clear Ht. simpl_existT.\n    unfold projT1.\n    simpl in Hi'.\n    assert (Hi'' : i' < S (S n')) by lia.\n    exists Hi''.\n    destruct (le_lt_dec (S (S n')) i'). { lia. }\n    replace (of_nat_lt l) with (of_nat_lt Hi'') in * by apply of_nat_ext. clear l.\n    rewrite eq_dec_if_false.\n    + exists false. exists None. reflexivity.\n    + lia.\n  - destruct Hv as [Hj Hv]. unfold projT1 in Ht. simpl in Hj.\n    destruct (le_lt_dec (S n') j); [lia|].\n    replace (of_nat_lt l) with (of_nat_lt Hj) in * by apply of_nat_ext. clear l.\n    simpl in Ht.\n    destruct (vtransition X lx (bs' (of_nat_lt Hj), iom))\n      as (si', om') eqn:Htx.\n    simpl in Hi'.\n    assert (Hi'' : i' < S (S n')) by lia.\n    destruct is_equiv as [|] eqn:Hflag\n    ; inversion Ht; subst ns om'; clear Ht\n    ; apply inj_pairT2 in H1; subst bs.\n    + destruct (le_lt_dec (S (S n')) i'); [lia|].\n      destruct (nat_eq_dec (S i') (S (S n'))); [lia|].\n      exists Hi''. exists false.\n      exists None. reflexivity.\n    + destruct (le_lt_dec (S n') i'); [lia|].\n      destruct (nat_eq_dec j i').\n      * subst j.\n        rewrite eq_dec_if_true by apply of_nat_ext.\n        exists Hi'. exists false.\n        exists (Some {| l := lx; input := iom; destination := si'; output := oom |}).\n        reflexivity.\n      * exists Hi'. exists false. exists None. reflexivity.\nQed.\n\nLemma equivocator_protocol_transition_item_project_inv5_new_machine\n  (l : vlabel equivocator_vlsm)\n  (s s' : vstate equivocator_vlsm)\n  (iom oom : option message)\n  (Hv: vvalid equivocator_vlsm l (s', iom))\n  (Ht: vtransition equivocator_vlsm l (s', iom) = (s, oom))\n  (item := {| l := l; input := iom; destination := s; output := oom |})\n  (fi : bool)\n  (sn : state)\n  (Hnew : snd l = NewMachine _ sn)\n  : exists\n    (i : nat)\n    (Hi : i < S (projT1 s)),\n    equivocator_vlsm_transition_item_project item (Existing _ i fi) = Some (None, snd l).\nProof.\n  unfold equivocator_vlsm_transition_item_project.\n  destruct s as (ns, bs).\n  destruct s' as (ns', bs').\n  unfold vtransition in Ht. unfold_transition Ht.\n  unfold vvalid in Hv. simpl in Hv.\n  destruct l as (lx, d). unfold snd in Ht. simpl in Hv.\n  simpl in Hnew. subst d.\n  inversion Ht. subst; clear Ht.\n  simpl_existT.\n  exists (S ns').  split; [simpl; lia|].\n  unfold snd. unfold item.\n  destruct (le_lt_dec (S (S ns')) (S ns')); [lia|].\n  rewrite eq_dec_if_true; reflexivity.\nQed.\n\nLemma equivocator_protocol_transition_item_project_inv5\n  (l : vlabel equivocator_vlsm)\n  (s s' : vstate equivocator_vlsm)\n  (iom oom : option message)\n  (Hv: vvalid equivocator_vlsm l (s', iom))\n  (Ht: vtransition equivocator_vlsm l (s', iom) = (s, oom))\n  (item := {| l := l; input := iom; destination := s; output := oom |})\n  (fi : bool)\n  (i : nat)\n  (is_equiv : bool)\n  (Hsndl : snd l = Existing _ i is_equiv)\n  : exists\n    (i : nat)\n    (Hi : i < S (projT1 s))\n    (itemx : vtransition_item X),\n    equivocator_vlsm_transition_item_project item (Existing _ i fi) = Some (Some itemx, snd l).\nProof.\n  unfold equivocator_vlsm_transition_item_project.\n  destruct s as (ns, bs).\n  destruct s' as (ns', bs').\n  unfold vtransition in Ht. unfold_transition Ht.\n  unfold vvalid in Hv. simpl in Hv.\n  destruct l as (lx, d). unfold snd in Ht. simpl in Hv.\n  simpl in Hsndl. subst d.\n  unfold snd. unfold item. destruct Hv as [Hi Hv].\n  unfold projT1 in Ht.\n  destruct (le_lt_dec (S ns') i); [lia|].\n  replace (of_nat_lt l) with (of_nat_lt Hi) in * by apply of_nat_ext. clear l.\n  simpl in Ht.\n  destruct (vtransition X lx (bs' (of_nat_lt Hi), iom)) as (sn', om').\n  destruct is_equiv as [|]; inversion Ht; subst; clear Ht; apply inj_pairT2 in H1; subst.\n  + exists (S ns'). split; [simpl; lia|].\n    destruct (le_lt_dec (S (S ns')) (S ns')); [lia|].\n    rewrite eq_dec_if_true by  reflexivity.\n    eexists _. reflexivity.\n  + exists i. exists Hi.\n    destruct (le_lt_dec (S ns) i); [lia|].\n    rewrite eq_dec_if_true by reflexivity.\n    eexists _. reflexivity.\nQed.\n\n(**\nThe projection of a segment of an [equivocator_vlsm] protocol trace\nis defined and a protocol trace segment in the original vlsm.\n*)\nLemma equivocator_vlsm_trace_project_protocol\n  (bs : vstate equivocator_vlsm)\n  (btr : list (vtransition_item equivocator_vlsm))\n  (Hbtr : finite_protocol_trace_from equivocator_vlsm bs btr)\n  (j : nat)\n  (Hj : j < S (projT1 (finite_trace_last bs btr)))\n  (jf : bool)\n  : exists\n    (tr : list (vtransition_item X))\n    (di : MachineDescriptor)\n    (Htr : equivocator_vlsm_trace_project btr (Existing _ j jf) = Some (tr, di)),\n    match di with\n    | NewMachine _ sn =>\n      vinitial_state_prop X sn\n      /\\ projT2 (finite_trace_last bs btr) (of_nat_lt Hj) = finite_trace_last sn tr\n      /\\ finite_protocol_trace_from X sn tr\n    | Existing _ i fi =>\n      exists\n      (Hi : i < S (projT1 bs))\n      (s := projT2 bs (of_nat_lt Hi))\n      (Hlast : projT2 (finite_trace_last bs btr) (of_nat_lt Hj) = finite_trace_last s tr)\n      ,\n      finite_protocol_trace_from X s tr\n    end.\nProof.\n  induction Hbtr; intros.\n  - exists []. simpl. exists (Existing _ j jf). exists eq_refl. exists Hj. exists eq_refl.\n    constructor. apply equivocator_state_project_protocol_state in H.\n    destruct s. simpl. apply H.\n  - remember {| l := l; input := iom; destination := s; output := oom |} as item.\n    destruct H as [[Hs' [Hiom Hv]] Ht].\n    apply equivocator_state_project_protocol_state in Hs'.\n    apply equivocator_state_project_protocol_message in Hiom.\n    remember (finite_trace_last s' (item :: tl)) as lst.\n    rewrite finite_trace_last_cons in Heqlst.\n    rewrite Heqitem in Heqlst. simpl in Heqlst.\n    subst lst.\n    specialize (IHHbtr Hj).\n    destruct IHHbtr as [tr [di [Htl Hdi]]].\n    simpl. rewrite Htl.\n    destruct di as [sn| i fi].\n    + simpl. exists tr. exists (NewMachine _ sn). exists eq_refl. assumption.\n    + destruct (equivocator_vlsm_transition_item_project item (Existing _ i fi)) as [[[item'|]di']|]\n        eqn:Hitem.\n      * exists (item' :: tr). exists di'. exists eq_refl.\n        subst item.\n        apply (equivocator_protocol_transition_item_project_inv2 l s' s) in Hitem\n        ; [|assumption|assumption].\n        destruct Hitem as [_i [_fi [Heq [Hi [Heqitem' Hitem]]]]].\n        inversion Heq. subst _i _fi. clear Heq.\n        destruct Hdi as [_Hi Hlst].\n        replace (of_nat_lt _Hi) with (of_nat_lt Hi) in * by apply of_nat_ext. clear _Hi.\n        simpl in Hlst. destruct Hlst as [Hlst Htr].\n        repeat rewrite map_cons.\n        destruct Hitem as [i' [fi' [Hdi' [Hi' [Hv' Ht']]]]].\n        subst di'. exists Hi'.\n        rewrite finite_trace_last_cons. subst. simpl. exists Hlst.\n        constructor; [assumption|].\n        repeat split; [|assumption|assumption|assumption].\n        destruct s' as (ns', bs'). apply Hs'.\n      * subst item.\n        destruct Hdi as [Hi [Hlst Htr]].\n        apply (equivocator_protocol_transition_item_project_inv3 l s s') in Hitem\n        ; [|assumption|assumption].\n        eexists _. eexists _. exists eq_refl.\n        destruct di' as [sn' | i' fi'].\n        -- destruct Hitem as [Hl [Hi' [Hiom' [Hoom [Hsn'eq Hsn']]]]]. subst.\n          replace (of_nat_lt (le_n (S (projT1 s)))) with (of_nat_lt Hi) in * by apply of_nat_ext.\n          repeat split; assumption.\n        -- destruct Hitem as [_Hi [Hi' Heq]].\n          replace (of_nat_lt _Hi) with (of_nat_lt Hi) in Heq by apply of_nat_ext. clear _Hi.\n          exists Hi'. rewrite Heq. exists Hlst. assumption.\n      * apply equivocator_transition_item_project_inv_none in Hitem.\n        destruct Hitem as [_i [_fi [Heq Hitem]]].\n        destruct Hdi as [Hi Hdi].\n        inversion Heq. subst _i _fi item. simpl in Hitem. lia.\nQed.\n\n(**\nThe projection of a segment of a protocol trace from the [pre_loaded_with_all_messages_vlsm]\ncorresponding to the [equivocator_vlsm] is defined and it is a protocol\ntrace segment in the [pre_loaded_with_all_messages_vlsm] corresponding to the original vlsm.\n*)\nLemma preloaded_equivocator_vlsm_trace_project_protocol\n  (bs bf : vstate equivocator_vlsm)\n  (btr : list (vtransition_item equivocator_vlsm))\n  (Hbtr : finite_protocol_trace_from_to (pre_loaded_with_all_messages_vlsm equivocator_vlsm) bs bf btr)\n  (j : nat)\n  (Hj : j < S (projT1 bf))\n  (jf : bool)\n  : exists\n    (tr : list (vtransition_item X))\n    (di : MachineDescriptor)\n    (Htr : equivocator_vlsm_trace_project btr (Existing _ j jf) = Some (tr, di)),\n    match di with\n    | NewMachine _ sn =>\n      finite_protocol_trace_init_to (pre_loaded_with_all_messages_vlsm X)\n           sn (projT2 bf (of_nat_lt Hj)) tr\n    | Existing _ i fi =>\n      exists\n      (Hi : i < S (projT1 bs))\n      (s := projT2 bs (of_nat_lt Hi))\n      (f := projT2 bf (of_nat_lt Hj))\n      ,\n      finite_protocol_trace_from_to (pre_loaded_with_all_messages_vlsm X) s f tr\n    end.\nProof.\n  induction Hbtr; intros.\n  - exists []. simpl. exists (Existing _ j jf). exists eq_refl. exists Hj.\n    constructor.\n    apply (preloaded_equivocator_state_project_protocol_state _ s H (of_nat_lt Hj)).\n  - remember {| l := l; input := iom; destination := s; output := oom |} as item.\n    destruct H as [[Hs' [Hiom Hv]] Ht].\n    specialize (preloaded_equivocator_state_project_protocol_state _ _ Hs') as Hs'X.\n    remember\n      (@finite_trace_last message\n      (@type message equivocator_vlsm) s'\n      (item::tl))\n      as lst.\n    rewrite finite_trace_last_cons in Heqlst.\n    rewrite Heqitem in Heqlst. simpl in Heqlst.\n    subst lst.\n    specialize (IHHbtr Hj).\n    destruct IHHbtr as [tr [di [Htl Hdi]]].\n    simpl. rewrite Htl.\n    destruct di as [sn| i fi].\n    + simpl. exists tr. exists (NewMachine _ sn). exists eq_refl. assumption.\n    + destruct (equivocator_vlsm_transition_item_project item (Existing _ i fi)) as [[[item'|]di']|]\n        eqn:Hitem.\n      * exists (item' :: tr). exists di'. exists eq_refl.\n        subst item.\n        apply (equivocator_protocol_transition_item_project_inv2 l s' s) in Hitem\n        ; [|assumption|assumption].\n        destruct Hitem as [_i [_fi [Heq [Hi [Heqitem' Hitem]]]]].\n        inversion Heq. subst _i _fi. clear Heq.\n        destruct Hdi as [_Hi Htr].\n        replace (of_nat_lt _Hi) with (of_nat_lt Hi) in * by apply of_nat_ext. clear _Hi.\n        destruct di' as [sn'| i' fi']\n        ; [destruct Hitem as [i' [fi' [Hcontra _]]]; congruence|].\n        destruct Hitem as [_i' [_fi' [Heq [Hi' [Hv' Ht']]]]].\n        inversion Heq. subst _i' _fi'. clear Heq.\n        exists Hi'.\n        subst item'.\n        apply (finite_ptrace_from_to_extend (pre_loaded_with_all_messages_vlsm X)); [assumption|].\n        repeat split; [apply Hs'X| |assumption|assumption].\n        exists (proj1_sig (vs0 X)). apply (pre_loaded_with_all_messages_message_protocol_prop X).\n      * subst item.\n        apply (equivocator_protocol_transition_item_project_inv3 l s s') in Hitem\n        ; [|assumption|assumption].\n        destruct Hdi as [Hi Htr].\n        eexists _. eexists _. exists eq_refl.\n        destruct di' as [sn' | i' fi'].\n        -- destruct Hitem as [Hl [_Hi [_Hiom [_Hoom [_Hsn' Hsn']]]]]. subst.\n          split; [|assumption].\n          replace (of_nat_lt (le_n (S (projT1 s)))) with (of_nat_lt Hi) in * by apply of_nat_ext.\n          exact Htr.\n        -- destruct Hitem as [_Hi [Hi' Heq]].\n          replace (of_nat_lt _Hi) with (of_nat_lt Hi) in * by apply of_nat_ext. clear _Hi.\n          exists Hi'. rewrite Heq. assumption.\n      * apply equivocator_transition_item_project_inv_none in Hitem.\n        destruct Hitem as [_i [_fi [Heq Hitem]]].\n        destruct Hdi as [Hi Hdi].\n        inversion Heq. subst _i _fi item. simpl in Hitem. lia.\nQed.\n\n(**\nThe projection of a protocol trace from the [pre_loaded_with_all_messages_vlsm]\ncorresponding to the [equivocator_vlsm] is defined and it is a protocol\ntrace in the [pre_loaded_with_all_messages_vlsm] corresponding to the original vlsm.\n*)\nLemma preloaded_equivocator_vlsm_project_protocol_trace\n  (bs bf : vstate equivocator_vlsm)\n  (btr : list (vtransition_item equivocator_vlsm))\n  (Hbtr : finite_protocol_trace_from_to (pre_loaded_with_all_messages_vlsm equivocator_vlsm) bs bf btr)\n  (j : nat)\n  (Hj : j < S (projT1 bf))\n  (jf : bool)\n  : exists\n    (tr : list (vtransition_item X))\n    (di : MachineDescriptor)\n    (Htr : equivocator_vlsm_trace_project btr (Existing _ j jf) = Some (tr, di)),\n    match di with\n    | NewMachine _ sn =>\n      finite_protocol_trace_init_to (pre_loaded_with_all_messages_vlsm X)\n        sn (projT2 bf (of_nat_lt Hj)) tr\n    | Existing _ i fi =>\n      exists\n      (Hi : i < S (projT1 bs))\n      (s := projT2 bs (of_nat_lt Hi))\n      (f := projT2 bf (of_nat_lt Hj))\n      ,\n      finite_protocol_trace_from_to (pre_loaded_with_all_messages_vlsm X) s f tr\n      /\\ (vinitial_state_prop (pre_loaded_with_all_messages_vlsm equivocator_vlsm) bs\n          -> vinitial_state_prop (pre_loaded_with_all_messages_vlsm X) s)\n    end.\nProof.\n  destruct (preloaded_equivocator_vlsm_trace_project_protocol bs bf btr Hbtr j Hj jf)\n    as [tr [di [Hproject Hdi]]].\n  exists tr.\n  exists di.\n  exists Hproject.\n  destruct di as [sn | i fi].\n  - destruct Hdi as [Hsn Htr].\n    repeat split; assumption.\n  - destruct Hdi as [Hi Htr].\n    exists Hi. split; [assumption|].\n    intro Hinit.\n    destruct Hinit.\n    cut (projT2 bs (of_nat_lt (Hzero X bs)) = projT2 bs (of_nat_lt Hi)).\n    { intro R. rewrite <- R. assumption. }\n    f_equal. assert (Hi0 : i = 0) by lia. subst. apply of_nat_ext.\nQed.\n\n(**\nIf [equivocator_vlsm_trace_project] does not fail, then the index of the\nmachine descriptor is valid for the last state of the trace argument.\n*)\nSet Printing Implicit.\nLemma equivocator_vlsm_trace_project_inv\n  (tr: list transition_item)\n  (Hntr : tr <> [])\n  (j: nat)\n  (fj : bool)\n  (HtrX: equivocator_vlsm_trace_project tr (Existing _ j fj) <> None)\n  (is: state)\n  : j < S (projT1 (finite_trace_last is tr)).\nProof.\n  apply exists_last in Hntr.\n  destruct Hntr as [suffix [x Heq]]. subst tr.\n  destruct (equivocator_vlsm_trace_project (suffix ++ [x]) (Existing _ j fj)) eqn:Htr\n  ; [|elim HtrX; reflexivity].\n  clear HtrX. destruct p as (trX, d).\n  apply equivocator_vlsm_trace_project_app in Htr.\n  destruct Htr as [dmiddle [_ [lx [_ [Hx _]]]]].\n  rewrite finite_trace_last_is_last.\n  remember (Existing _ j fj) as dj.\n  simpl in *.\n  destruct (equivocator_vlsm_transition_item_project x dj)\n    as [(_x, _dmiddle)|]\n    eqn:Hx'\n  ; [|congruence].\n  destruct _x as [itemx|]; inversion Hx; subst lx _dmiddle; clear Hx.\n  - subst. destruct x. unfold equivocator_vlsm_transition_item_project in Hx'.\n    destruct l. destruct destination.\n    destruct (le_lt_dec (S x) j); [congruence|].\n    assumption.\n  - subst. unfold equivocator_vlsm_transition_item_project in Hx'. destruct x. destruct l. destruct destination.\n    destruct (le_lt_dec (S x) j); [congruence|].\n    assumption.\nQed.\n\n(**\nProjecting a protocol trace segment on an index which is valid for the\nfirst state of the trace does not fail and yields the same index.\n*)\nLemma preloaded_equivocator_vlsm_trace_project_protocol_inv\n  (bs : vstate equivocator_vlsm)\n  (btr : list (vtransition_item equivocator_vlsm))\n  (Hbtr : finite_protocol_trace_from (pre_loaded_with_all_messages_vlsm equivocator_vlsm) bs btr)\n  (i : nat)\n  (Hi : i < S (projT1 bs))\n  (fi : bool)\n  : exists\n    (fii : bool)\n    (tr : list (vtransition_item X)),\n    equivocator_vlsm_trace_project btr (Existing _ i fi) = Some (tr, Existing _ i fii).\nProof.\n  revert fi.\n  generalize dependent i.\n  induction Hbtr; intros.\n  - simpl. exists fi. exists []. reflexivity.\n  - remember {| l := l; input := iom; destination := s; output := oom |} as item.\n    simpl.\n    destruct H as [[_ [_ Hv]] Ht].\n    specialize\n      (equivocator_protocol_transition_item_project_inv4 l s s' iom oom Hv Ht i)\n      as Hitem.\n    replace\n      (@Build_transition_item message (@type message equivocator_vlsm) l iom s oom)\n      with item in Hitem.\n    destruct (Hitem false Hi) as [Hi' _].\n    spec IHHbtr i Hi' fi.\n    destruct IHHbtr as [fii' [tr Htr]].\n    rewrite Htr.\n    spec Hitem fii' Hi.\n    destruct Hitem as [_ [fi'' [oitem Hoitem]]].\n    rewrite Hoitem. exists fi''.\n    destruct oitem as [itemx|].\n    + exists (itemx :: tr). reflexivity.\n    + exists tr. reflexivity.\nQed.\n\n(**\nAn inversion lemma about projections of a protocol trace segment\n*)\nLemma preloaded_equivocator_vlsm_trace_project_protocol_inv2\n  (is fs: state)\n  (tr: list transition_item)\n  (Hntr : tr <> [])\n  (Htr: finite_protocol_trace_from_to (pre_loaded_with_all_messages_vlsm equivocator_vlsm) is fs tr)\n  (j : nat)\n  (fj : bool)\n  (di : MachineDescriptor)\n  (trX: list (vtransition_item X))\n  (HtrX: equivocator_vlsm_trace_project tr (Existing _ j fj) = Some (trX, di))\n  : exists (Hj : j < S (projT1 fs)),\n    match di with\n    | NewMachine _ sn =>\n      finite_protocol_trace_init_to (pre_loaded_with_all_messages_vlsm X)\n        sn (projT2 fs (of_nat_lt Hj)) trX\n    | Existing _ i fi =>\n      exists\n      (Hi : i < S (projT1 is)),\n      finite_protocol_trace_from_to (pre_loaded_with_all_messages_vlsm X)\n        (projT2 is (of_nat_lt Hi)) (projT2 fs (of_nat_lt Hj)) trX\n    end.\nProof.\n  specialize (equivocator_vlsm_trace_project_inv _ Hntr j fj) as Hj.\n  spec Hj. { rewrite HtrX. intro contra. congruence. }\n  spec Hj is.\n  replace (@finite_trace_last _ (@type _ equivocator_vlsm) is tr) with fs in Hj\n    by (rewrite <- (ptrace_get_last Htr);reflexivity).\n  exists Hj.\n  destruct\n    (preloaded_equivocator_vlsm_trace_project_protocol _ _ _ Htr _ Hj fj)\n    as [trX' [di' [HtrX' Hdi']]].\n  rewrite HtrX in HtrX'.\n  inversion HtrX'. subst di' trX'. clear HtrX'.\n  assumption.\nQed.\n\n(**\nAn inversion lemma about projections of a protocol trace\n*)\nLemma preloaded_equivocator_vlsm_protocol_trace_project_inv2\n  (is fs: state)\n  (tr: list transition_item)\n  (Hntr : tr <> [])\n  (Htr: finite_protocol_trace_from_to (pre_loaded_with_all_messages_vlsm equivocator_vlsm) is fs tr)\n  (j : nat)\n  (fj : bool)\n  (di : MachineDescriptor)\n  (trX: list (vtransition_item X))\n  (HtrX: equivocator_vlsm_trace_project tr (Existing _ j fj) = Some (trX, di))\n  : exists\n    (Hj : j < S (projT1 fs)),\n    match di with\n    | NewMachine _ sn =>\n      finite_protocol_trace_init_to (pre_loaded_with_all_messages_vlsm X)\n        sn (projT2 fs (of_nat_lt Hj)) trX\n    | Existing _ i fi =>\n      exists\n      (Hi : i < S (projT1 is))\n      (s := projT2 is (of_nat_lt Hi))\n      (f := projT2 fs (of_nat_lt Hj))\n      ,\n      finite_protocol_trace_from_to (pre_loaded_with_all_messages_vlsm X) s f trX\n      /\\ (vinitial_state_prop (pre_loaded_with_all_messages_vlsm equivocator_vlsm) is -> vinitial_state_prop (pre_loaded_with_all_messages_vlsm X) s)\n    end.\nProof.\n  specialize (equivocator_vlsm_trace_project_inv _ Hntr j fj) as Hj.\n  spec Hj. { rewrite HtrX. intro contra. congruence. }\n  spec Hj is.\n  replace (@finite_trace_last _ (@type _ equivocator_vlsm) is tr) with fs in Hj\n    by (symmetry;apply (ptrace_get_last Htr)).\n  exists Hj.\n  destruct\n    (preloaded_equivocator_vlsm_project_protocol_trace _ _ _ Htr _ Hj fj)\n    as [trX' [di' [HtrX' Hdi]]].\n  rewrite HtrX in HtrX'.\n  inversion HtrX'. subst di' trX'.  clear HtrX'.\n  assumption.\nQed.\n\nEnd equivocator_vlsm_projections.\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/Equivocators/Projections.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.25417941912038805}}
{"text": "Require Import List.\nRequire Import ZArith.\nRequire Import Psatz.\nRequire Import ITree.ITree.\nRequire Import ITree.Interp.Traces.\nRequire Import compcert.lib.Integers.\nRequire Import compcert.common.Memory.\nRequire Import VST.progs.io_specs.\nRequire Import VST.progs.io_dry.\nImport ExtLib.Structures.Monad.\n\nImport MonadNotation.\nLocal Open Scope monad_scope.\nLocal Open Scope Z.\n\n(* Weaker pre condition using trace_incl instead of eutt. *)\nDefinition getchar_pre' (m : mem) (witness : int -> IO_itree) (z : IO_itree) :=\n  let k := witness in trace_incl (r <- read;; k r) z.\n\n(* getchar_pre' really is weaker. *)\nGoal forall m w z,\n  getchar_pre m w z -> getchar_pre' m w z.\nProof.\n  unfold getchar_pre, getchar_pre', trace_incl; intros ? * Heq * Htrace.\n  apply eutt_trace_eq in Heq.\n  apply Heq; auto.\nQed.\n\n(* CertiKOS specs must terminate. Could get blocking version back by\n   wrapping getchar in a loop. *)\nDefinition getchar_post' (m0 m : mem) r (witness : (int -> IO_itree) * IO_itree) (z : IO_itree) :=\n  m0 = m /\\\n    (* Success *)\n    ((0 <= Int.signed r <= two_p 8 - 1 /\\ let (k, _) := witness in z = k r) \\/\n    (* No character to read *)\n    let (_, z0) := witness in z = z0 /\\ Int.signed r = -1).\n\n(** Traces *)\nInductive IO_trace_event :=\n| ETRead (r : Z)\n| ETWrite (c : Z).\nDefinition etrace := list IO_trace_event.\n\nDefinition trace_event_rtype (e : IO_trace_event) :=\n  match e with\n  | ETRead _ => int\n  | ETWrite _ => unit\n  end.\n\nDefinition io_event_of_io_tevent (e : IO_trace_event)\n  : IO_event (trace_event_rtype e) * (trace_event_rtype e) :=\n  match e with\n  | ETRead r => (ERead, Int.repr r)\n  | ETWrite c => (EWrite (Int.repr c), tt)\n  end.\n\nFixpoint trace_of_etrace (t : etrace) : @trace IO_event unit :=\n  match t with\n  | nil => TEnd\n  | e :: t' =>\n      let (e', r) := io_event_of_io_tevent e in\n      TEventResponse e' r (trace_of_etrace t')\n  end.\n\nSection SanityChecks.\n  Variable k : int -> itree IO_event unit.\n  Definition tree := (r <- read;; k r).\n\n  Goal is_trace tree (@TEnd _ unit).\n  Proof.\n    hnf; cbn.\n    constructor.\n  Qed.\n\n  Goal is_trace tree (@TEventEnd _ unit _ ERead).\n  Proof.\n    hnf; cbn.\n    constructor.\n  Qed.\n\n  Goal is_trace tree (@TEventResponse _ unit _ ERead Int.zero TEnd).\n  Proof.\n    hnf; cbn.\n    repeat constructor.\n  Qed.\n\n  Goal is_trace tree (trace_of_etrace nil).\n  Proof.\n    hnf; cbn.\n    constructor.\n  Qed.\n\n  Goal is_trace tree (trace_of_etrace (ETRead 0 :: nil)).\n  Proof.\n    hnf; cbn.\n    repeat constructor.\n  Qed.\nEnd SanityChecks.\n\n(** CertiKOS Specs *)\nSection Specs.\n\n  Class ConsoleLen := {\n    CONSOLE_MAX_LEN : Z;\n    console_len_pos : 0 < CONSOLE_MAX_LEN\n  }.\n  Context {Hclen : ConsoleLen}.\n\n  Class SerialOracle := {\n    serial_oracle : etrace -> Z;\n    serial_oracle_in_range : forall tr,\n      0 <= serial_oracle tr <= 255\n  }.\n  Context {Horacle : SerialOracle}.\n\n  Record state := mkSt {\n    st_mem : mem;\n    st_console : list Z;\n    st_trace : etrace;\n  }.\n\n  (* Read a character from the serial device and place it in the console buffer.\n     Triggered by an interrupt from the serial device. *)\n  Definition serial_getc (st : state) : state :=\n    let (mem, cons, tr) := st in\n    let c := serial_oracle tr in\n    let cons' := if Zlength cons <? CONSOLE_MAX_LEN then cons\n                 else skipn 1 cons in\n    mkSt mem (cons' ++ c :: nil) (tr ++ ETRead c :: nil).\n\n  (* Take the first element from the console buffer or -1 if it is empty. *)\n  Definition console_read (st : state) : state * Z :=\n    let (mem, cons, tr) := st in\n    match cons with\n    | nil => (st, -1)\n    | c :: rest =>\n      let st' := mkSt mem rest tr in\n      (st', c)\n    end.\n\n  (* Return the new state, the read character, and the section of the trace to\n     be consumed. *)\n  Definition getchar_spec (st : state) : state * Z * etrace :=\n    let (st', r) := console_read st in\n    (* Success *)\n    if 0 <=? r then (st', r, ETRead r :: nil)\n    (* Error *)\n    else (st', -1, nil).\n\n  (* Invariant that everything in the trace was put there by the serial\n     device. *)\n  Definition valid_trace st :=\n    forall c,\n      In (ETRead c) st.(st_trace) ->\n      exists tr, serial_oracle tr = c.\n\n  (* Invariant that everything in the console buffer is also in the trace. *)\n  Definition valid_console st :=\n    Zlength st.(st_console) <= CONSOLE_MAX_LEN /\\\n    forall c,\n      In c st.(st_console) ->\n      In (ETRead c) st.(st_trace).\n\n  Definition valid_state st :=\n    valid_trace st /\\ valid_console st.\n\n  Lemma serial_getc_preserve_valid_trace : forall st st',\n    valid_trace st ->\n    serial_getc st = st' ->\n    valid_trace st'.\n  Proof.\n    unfold valid_trace, serial_getc; intros * Hvalid Hspec c Hin.\n    destruct st as [? ? tr]; inv Hspec; cbn in *.\n    rewrite in_app_iff in Hin; cbn in Hin.\n    intuition.\n    inv H0; eauto.\n  Qed.\n\n  Lemma serial_getc_preserve_valid_console : forall st st',\n    valid_console st ->\n    serial_getc st = st' ->\n    valid_console st'.\n  Proof.\n    unfold valid_console, serial_getc; intros * (Hlen & Hvalid) Hspec.\n    destruct st as [? cons ?]; inv Hspec; cbn in *.\n    rewrite ?Zlength_correct in *.\n    destruct (_ <? _) eqn:Hlt; [rewrite Z.ltb_lt in Hlt | rewrite Z.ltb_nlt in Hlt].\n    + rewrite app_length; cbn.\n      split; try lia.\n      intros c; rewrite ?in_app_iff; cbn.\n      intuition (subst; auto).\n    + pose proof console_len_pos.\n      rewrite app_length; cbn.\n      split; [destruct cons; cbn in *; lia |].\n      intros c; rewrite ?in_app_iff; cbn.\n      destruct cons; intuition (subst; auto).\n      intuition.\n  Qed.\n\n  Lemma getchar_spec_preserve_valid_trace : forall st st' c tr,\n    valid_trace st ->\n    getchar_spec st = (st', c, tr) ->\n    valid_trace st'.\n  Proof.\n    unfold valid_trace, getchar_spec, console_read; intros * Hvalid Hspec c Hin.\n    destruct st as [? [| c' cons] ?].\n    - inv Hspec; eauto.\n    - destruct (0 <=? c'); inv Hspec; cbn in *; eauto.\n  Qed.\n\n  Lemma getchar_spec_preserve_valid_console : forall st st' c tr,\n    valid_console st ->\n    getchar_spec st = (st', c, tr) ->\n    valid_console st'.\n  Proof.\n    unfold valid_console, getchar_spec, console_read; intros * (Hlen & Hvalid) Hspec.\n    destruct st as [? [| c' cons] ?].\n    - inv Hspec; eauto.\n    - rewrite ?Zlength_correct in *.\n      destruct (0 <=? c'); inv Hspec; cbn in *; split; eauto; lia.\n  Qed.\n\nEnd Specs.\n\nSection SpecsCorrect.\n\n  Context `{SerialOracle} `{ConsoleLen}.\n\n  (* For any trace that the new itree (z) allows, the old itree (z0) allowed it\n     with the generated trace (t) as a prefix. *)\n  Definition consume_trace (z0 z : IO_itree) (et : etrace) :=\n    let t := trace_of_etrace et in\n    forall t',\n      is_trace z t' ->\n      is_trace z0 (app_trace t t').\n\n  Lemma getchar_correct k z m c t :\n    (* Initial state is valid *)\n    let st := mkSt m c t in\n    valid_state st ->\n    (* Pre condition holds *)\n    getchar_pre' m k z ->\n    exists st' r t',\n      (* Spec with same initial memory returns some state and result *)\n      getchar_spec st = (st', r, t') /\\\n      (* New itree is old k applied to result, or same as old itree if nothing\n         to read *)\n      let z' := if 0 <=? r then k (Int.repr r) else z in\n      (* Post condition holds on new state, itree, and result *)\n      getchar_post' m st'.(st_mem) (Int.repr r) (k, z) z' /\\\n      (* The new itree 'consumed' the generated trace *)\n      consume_trace z z' t'.\n  Proof.\n    unfold getchar_pre'; intros Hval Hpre; cbn.\n    unfold getchar_spec; cbn.\n    destruct c as [| r c]; cbn.\n    - (* Nothing to read *)\n      do 4 esplit; eauto.\n      split; hnf; cbn; auto.\n    - (* Read r *)\n      destruct Hval as (Hval_tr & (Hlen & Hval_cons)).\n      specialize (Hval_cons _ ltac:(cbn; auto)).\n      specialize (Hval_tr _ Hval_cons).\n      destruct Hval_tr as (? & Hr).\n      assert (0 <= r <= 255)\n        by (subst; apply serial_oracle_in_range; auto).\n      rewrite Zle_imp_le_bool by lia.\n      do 4 esplit; eauto.\n      rewrite Zle_imp_le_bool by lia.\n      split; hnf; cbn.\n      + rewrite Int.signed_repr; auto.\n        cbn; lia.\n      + intros * Htrace.\n        apply Hpre.\n        hnf; cbn.\n        repeat constructor.\n        apply Htrace.\n  Qed.\n\nEnd SpecsCorrect.\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/io_os_connection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2541561568726298}}
{"text": "From PlutusCert Require Import\n  PlutusIR\n  Analysis.FreeVars\n  Analysis.UniqueBinders\n  Analysis.WellScoped\n  Transform.Congruence\n  .\nImport NamedTerm.\nImport Term.\n\nFrom Coq Require Import\n  Strings.String\n  Lists.List\n  Lists.ListSet\n  .\nImport ListNotations.\n\n(* A binding group (Let without a body) *)\nDefinition binding_group := (Recursivity * list Binding)%type.\n\n(*\nAssuming globally unique variables, the new binding groups much satisfy:\n  - Well-scoped: each free variable in a binding RHS is bound\n  - All bindings equals those in the let-rec before transformaton\n\nNote that strictness of bindings does not matter: if one of the (strict)\nbindings diverges, the whole let-block diverges. This behaviour remains when\nregrouping/reordering all bindings.\n*)\n\nDefinition list_eq_elems {A} xs ys : Prop :=\n  forall (x : A), In x xs <-> In x ys.\n\n\nDefinition min_Rec (r1 r2 : Recursivity) : Recursivity :=\n  match r1, r2 with\n    | NonRec, NonRec => NonRec\n    | _ , _ => Rec\n  end.\n\n(* Collect subsequent binding groups, together with the \"inner\" term and\n   minimum recursivity *)\nInductive outer_binds : Term -> list Binding -> Term -> Recursivity -> Prop :=\n\n  | cv_Let : forall t_body lets t_inner r bs r_body,\n      outer_binds t_body lets t_inner r_body ->\n      outer_binds (Let r bs t_body) (bs ++ lets) t_inner (min_Rec r_body r)\n\n  | cv_Other : forall t_inner,\n      outer_binds t_inner [] t_inner NonRec\n\n  .\n\nInductive split_syn : Term -> Term -> Prop :=\n  | split_rec_let : forall bs t_body t bgs t_inner min_rec,\n\n      (* a decision-procedure would need to find the list bgs of binding groups that\n         satisfies the second premise (needs to do backtracking) *)\n      outer_binds t bgs t_inner min_rec ->\n      list_eq_elems bs bgs ->\n      split_syn t_body t_inner ->\n      split_syn (Let Rec bs t_body) t\n\n  | split_rec_cong : forall t t',\n      Cong split_syn t t' ->\n      split_syn t t'\n.\n\nDefinition split_rec t t' :=\n  split_syn t t' /\\\n  unique t /\\\n  closed t'\n.\n", "meta": {"author": "jaccokrijnen", "repo": "2022-scp-translation-relations", "sha": "59dce2e715d1f3f62fd552ec5debc7582e1126d5", "save_path": "github-repos/coq/jaccokrijnen-2022-scp-translation-relations", "path": "github-repos/coq/jaccokrijnen-2022-scp-translation-relations/2022-scp-translation-relations-59dce2e715d1f3f62fd552ec5debc7582e1126d5/src/Language/PlutusIR/Transform/SplitRec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2541561568726298}}
{"text": "Require Export Coq.Program.Tactics.\nRequire Export LibTactics.\n\nRequire Export CPS.\nRequire Export String.\n(* Require Export CoRN.ode.SimpleIntegration. *)\n\nVariable initialVel : Q.\nVariable initialPos : Q.\n\n\nRecord Train : Type := {\n  posX :> TContR;\n  velX : TContR;\n  deriv : isDerivativeOf velX posX;\n    (** this probably already implies continuity, which is now\n        explicitly put in TContR *)\n  initVel : {velX} (mkQTime 0 I)  = initialVel;\n  initPos : {posX} (mkQTime 0 I)  = initialPos\n}.\n\n\nInductive Topic :=  MOTOR | PSENSOR.\n\nScheme Equality for Topic.\n\nInstance ldskflskdalfkTopic_eq_dec : DecEq Topic.\nconstructor. exact Topic_eq_dec.\nDefined.\n\n\n\n(** When adding a nrew topic, add cases of this function *)\nDefinition topic2Type (t : Topic) : Type :=\nmatch t with\n| MOTOR => Q\n| PSENSOR => bool\nend.\n\n\nInstance  ttttt : @TopicClass Topic _.\n  constructor. exact topic2Type.\nDefined.\n\nDefinition left := false.\nDefinition right := true.\n\nInductive RosLoc := \n BASEMOTOR | PROXSENSOR (b:bool) | SWCONTROLLER.\n\nScheme Equality for RosLoc.\n\nInstance rldeqdsjfklsajlk : DecEq RosLoc.\nconstructor. exact RosLoc_eq_dec.\nDefined.\n\nClose Scope Q_scope.\n\n\nDefinition getVelM  : Message -> option Q :=\n  getPayload MOTOR.\n\nDefinition getSensorSide (m : Message ) : option bool :=\n  getPayload PSENSOR m.\n\nDefinition getProxSide (m : Message) : option bool :=\n  getPayload PSENSOR m.\n\nSection TrainProofs.\n\n(** To define IO devices, we already need\n    an Event type *)\nContext  \n  (minGap : Q)\n `{etype : @EventType _ _ _ Event RosLoc minGap tdeq}.\n\n\n(** In some cases, the equations might invove transcendental \n  functions like sine, cos which can output \n  irrationals even on rational *)\n\n\n\nDefinition getVelEv (e : Event) : option Q  :=\n  getRecdPayload MOTOR e.\n\nDefinition getVelOEv : (option Event) ->  option Q  :=\ngetRecdPayloadOp MOTOR.\n\n\nDefinition getVelAndTime (oev : option Event) \n    : option (Q * Event)  :=\ngetPayloadAndEv MOTOR oev.\n\n\nDefinition ProxPossibleTimeEvPair \n  (maxDelay: QTime) (side : bool)\n  (t: QTime) (ev: Event) \n  :=\n   (t < (eTime ev) < (t + maxDelay))%Q\n  /\\ (eMesg ev) = (mkImmMesg PSENSOR side).\n\n(** [side] is just an identifier *)\nDefinition ProximitySensor (alertDist : Q) (maxDelay: QTime) (side : bool)\n  : Device (Time -> ℝ) :=\nfun  (distanceAtTime : (Time -> ℝ))\n     (evs : nat -> option Event) \n  =>\n    (∀ t:QTime,\n       (distanceAtTime t  [<=] alertDist)\n       -> ∃ n, ∃ ev,\n          evs n = Some ev /\\ isSendEvt ev /\\\n            (ProxPossibleTimeEvPair maxDelay side t) ev)\n    /\\\n    (∀ (n: nat), \n        isSendEvtOp (evs n)\n        -> ∃ t : QTime, (distanceAtTime t  [<=]  alertDist)\n                /\\ opLiftF (ProxPossibleTimeEvPair maxDelay side t) (evs n)).\n\nDefinition inIntervalDuring\n  (interval: interval) (tStart tEnd : QTime)  (f : Time -> ℝ) : Prop :=\n  Squash (forall t : QTime, ( tStart <= t <= tEnd   -> (interval) (f t)))%Q.\n  \nDefinition isEqualDuring\n  (vel: Q) (tStart tEnd : QTime)  (f : Time -> ℝ) : Prop :=\n  (forall t : QTime, ( tStart <= t <= tEnd   -> (f t) [=] vel))%Q.\n\nVariable reactionTime : Q.\nVariable velAccuracy : Q.\nVariable transitionValues : interval.\n\n(*\nNotation \"a <== b <== c\" := ((a [<=] b) /\\ (b [<=] c)) \n  (at level 201,left associativity).\n*)\n\nDefinition simpleBetween (b a c eps : IR) \n  := ((Min a c  [<=] b) /\\ (b [<=] Max a c)).\n\n(** This can use [core.changsTo] *)\nDefinition correctVelDuring\n  (lastVel : Q) \n  (lastTime: QTime)\n  (uptoTime : QTime) \n  (velAtTime: Time -> ℝ) :=\n\n(exists  (qt : QTime), \n  lastTime <= qt <= (lastTime + reactionTime)\n  /\\ ((forall t : QTime, (qt <= t <= uptoTime -> (velAtTime t) [=] lastVel)))\n  /\\ (forall t : QTime, (lastTime <= t <= qt)  \n          -> (simpleBetween (velAtTime t) (velAtTime lastTime) lastVel 0)))%Q.\n  \nClose Scope Q_scope.\n\n\n(** all velocity messages whose index  < numPrevEvts .\n    the second item is the time that messsage was dequed.\n    last message, if any  is the outermost (head)\n    Even though just the last message is needed,\n    this list is handy for reasoning; it is a convenient\n    thing to do induction over\n *)\n\nDefinition velocityMessages (t : QTime) :=\n  (filterPayloadsUptoTime MOTOR (localEvts BASEMOTOR) t).\n\nDefinition lastVelAndTime\n  (t : QTime) : (Q * QTime) :=\n  lastPayloadAndTime MOTOR (localEvts BASEMOTOR) t initialVel.\n\n\n\nDefinition corrSinceLastVel\n  (evs : nat -> option Event)\n  (uptoTime : QTime) \n  (velAtTime: Time -> ℝ) :=\n  let (lastVel, lastTime) := lastVelAndTime uptoTime in\n  correctVelDuring lastVel lastTime uptoTime velAtTime.\n\n\nDefinition SlowMotorQ \n   : Device (Time -> ℝ) :=\nfun  (velAtTime: Time -> ℝ) (evs : nat -> option Event) \n  => forall t: QTime, corrSinceLastVel evs t velAtTime.\n\n(** it is a pure function that repeatedly\n   reads a message from the [PSENSOR] topic\n   and publish on the [MOTOR] *)\nDefinition SwControllerProgram (speed : Q):\n  SimplePureProcess PSENSOR MOTOR :=\nfun side  => match side with\n            | true => (-speed)%Q\n            | false => speed\n            end.\n\nLemma SPP : SimplePureProcess PSENSOR MOTOR\n            = (bool -> Q).\nProof.\nreflexivity.\nQed.\n\nDefinition SwProcess (speed : Q) \n      : Process Message (list Message):= \n  mkPureProcess (liftToMesg (SwControllerProgram speed)).\n\nDefinition digiControllerTiming  : \n  QTime :=  (mkQTime (1#2)%Q I).\n \nDefinition ControllerNode (speed : Q): RosSwNode :=\n  Build_RosSwNode (SwProcess speed) (digiControllerTiming, (QposMake 1 3)).\n\nRequire Import Psatz.\n\nLemma onlyNeededForOldProofsAux:\n  ∀ sp nd ns si,\n     possibleDeqSendOncePair2 (procOutMsgs (ControllerNode sp) \n        (localEvts SWCONTROLLER) nd) \n         (procTime (ControllerNode sp))\n        (timingAcc (ControllerNode sp)) (localEvts SWCONTROLLER) nd ns si\n  -> {es : Event | {ed : Event | isDeqEvt ed × isSendEvt es\n          × (nd < ns)\n              × (eTime es < eTime ed + 1)%Q\n        ×\n        localEvts SWCONTROLLER nd = Some ed \n        × localEvts SWCONTROLLER ns = Some es ×\n         {dmp : bool|  fst (eMesg ed) = ((mkMesg PSENSOR dmp))\n                  ∧ (mkImmMesg MOTOR ((SwControllerProgram sp) dmp)) = (eMesg es) }}}.\nProof.\n  intros ? ? ? ? Hp.\n  unfold possibleDeqSendOncePair2 in Hp.\n  unfold procOutMsgs in Hp.\n  simpl in Hp. unfold SwProcess in Hp. \n  rewrite getNewProcLPure in Hp.\n  destruct (localEvts SWCONTROLLER nd) as [evd|];[| tauto].\n  destruct (localEvts SWCONTROLLER ns) as [evs|];[| tauto].\n  unfold isDeqEvt, isSendEvt.\n  exists evs. exists evd.\n  destruct (eKind evd); try tauto.\n  destruct (eKind evs); try tauto.\n  split; auto.\n  split; auto.\n  repnd.\n  split;[omega|].\n  unfold getDeqOutput2, getOutput, liftToMesg in Hprrr, Hprrl.\n  simpl in Hprrr, Hprrl.\n  remember (getPayload PSENSOR (eMesg evd)) as evdp.\n  destruct evdp\n      as [dmp|];[| rewrite nth_error_nil in Hprrl; discriminate].\n  destruct si; simpl in Hprrl\n    ;[| rewrite nth_error_nil in Hprrl; discriminate].\n  rewrite <-Hprl in Hprrr.\n  unfold mkImmMesg, minDelayForIndex in Hprrr.\n  unfold compose, fold_right in Hprrr.\n  simpl in Hprrr.\n  apply proj1 in Hprrr.\n  simpl in Hprrr.\n  unfold inject_Z in Hprrr.\n  split; [lra|].\n  split; auto.\n  split; auto.\n  exists dmp.\n  unfold value in Hprrl.\n  inverts Hprrl.\n  split; auto.\n  apply MsgEta; auto.\nQed.\n\nLtac repnd2 :=\n  repeat match goal with\n           | [ H : _ /\\ _ |- _ ] =>\n            let lname := fresh H \"l\" in \n            let rname := fresh H \"r\" in \n              destruct H as [lname rname]\n           | [ H : _ × _ |- _ ] =>\n            let lname := fresh H \"l\" in \n            let rname := fresh H \"r\" in \n              destruct H as [lname rname]\n         end.\n\nLemma onlyNeededForOldProofs:\n  ∀ sp nd ns si,\n     possibleDeqSendOncePair2 (procOutMsgs (ControllerNode sp) \n        (localEvts SWCONTROLLER) nd) \n         (procTime (ControllerNode sp))\n        (timingAcc (ControllerNode sp)) (localEvts SWCONTROLLER) nd ns si\n  -> {es : Event | {ed : Event | isDeqEvt ed × isSendEvt es\n          × (nd < ns)\n              × (eTime ed < eTime es < eTime ed + 1)%Q\n        ×\n        localEvts SWCONTROLLER nd = Some ed \n        × localEvts SWCONTROLLER ns = Some es ×\n         {dmp : bool|  fst (eMesg ed) = ((mkMesg PSENSOR dmp))\n                  ∧ (mkImmMesg MOTOR ((SwControllerProgram sp) dmp)) = (eMesg es) }}}.\nProof.\n  intros ? ? ? ? Hp.\n  apply onlyNeededForOldProofsAux in Hp.\n  destruct Hp as [es Hp].\n  destruct Hp as [ed Hp].\n  exists es.\n  exists ed.\n  repnd2.\n  dands; try assumption;[].\n  apply timeIndexConsistent.\n  apply locEvtIndex in Hprrrrrl.\n  apply locEvtIndex in Hprrrrl.\n  repnd.\n  congruence.\nQed.\n\n\nLemma VelPosUB :forall (tst : Train)\n   (ta tb : Time) (Hab : ta[<]tb) (c : ℝ),\n   (forall (t:Time), (clcr ta tb) t -> ({velX tst} t) [<=] c)\n   -> ({posX tst} tb[-] {posX tst} ta)[<=]c[*](tb[-]ta).\nProof.\n  intros. apply TDerivativeUB2 with (F' := (velX tst)); auto.\n  apply deriv.\nQed.\n\nLemma VelPosLB :forall (tst : Train)\n   (ta tb : Time) (Hab : ta[<]tb) (c : ℝ),\n   (forall (t:Time), (clcr ta tb) t -> c [<=] ({velX tst} t))\n   -> c[*](tb[-]ta)[<=] ({posX tst} tb[-] {posX tst} ta).\nProof.\n  intros. apply TDerivativeLB2 with (F' := (velX tst)); auto.\n  apply deriv.\nQed.\n\nLemma QVelPosUB :forall (tst : Train)\n   (ta tb : QTime) (Hab : (ta<=tb)%Q) (c : Q),\n   (forall (t:QTime), (ta <= t <= tb)%Q -> ({velX tst} t) [<=] c)\n   -> (({posX tst} tb[-] {posX tst} ta)[<=] c*(tb-ta))%Q.\nProof.\n  intros. unfold Q2R.\n  rewrite inj_Q_mult.\n  apply TDerivativeUBQ with (F' := (velX tst)); auto.\n  apply deriv.\nQed.\n\nLemma QVelPosLB :forall (tst : Train)\n   (ta tb : QTime) (Hab : (ta<=tb)%Q) (c : Q),\n   (forall (t:QTime), (ta <= t <= tb)%Q -> Q2R c [<=] ({velX tst} t))\n   -> Q2R (c*(tb-ta))[<=] ({posX tst} tb[-] {posX tst} ta).\nProof.\n  intros. unfold Q2R.\n  rewrite inj_Q_mult.\n  apply TDerivativeLBQ with (F' := (velX tst)); auto.\n  apply deriv.\nQed.\n\nVariable boundary : ℝ.\n\nDefinition rboundary : ℝ := (boundary).\nDefinition lboundary : ℝ := ([0] [-] boundary).\n\nVariable alertDist : Q.\nVariable safeDist : ℝ.\nVariable maxDelay : QTime.\nVariable hwidth : ℝ. (* half of width *)\nDefinition speed : Q := 1.\n\n\nVariable reactionTimeGap : (reactionTime < minGap)%Q.\nDefinition lEndPos (ts : Train) (t : Time) : ℝ :=\n  (getF (posX ts) t [-]  hwidth).\n\nDefinition rEndPos (ts : Train) (t : Time) : ℝ :=\n  (getF (posX ts) t [+]  hwidth).\n\nDefinition velAtTime (ts : Train) (t : Time) : ℝ :=\n  (getF (velX ts) t).\n\nDefinition centerPosAtTime (ts : Train) (t : Time) : ℝ :=\n  (getF (posX ts) t).\n\nDefinition velBound : interval :=\n  (nbdAround [0] (speed [+] velAccuracy)).\n\nDefinition transitionInterval : interval :=\n  velBound.\n\n\nDefinition proxView (side :bool) :=\nmatch side with\n| true => (fun ts t => (rboundary [-] (rEndPos ts t)))\n| false => (fun ts t => ((lEndPos ts t) [-] lboundary))\nend.\n\n\nDefinition locNode (rl : RosLoc) : NodeSemantics :=\nmatch rl with\n| BASEMOTOR => DeviceSemantics (fun ts => getF (velX ts)) SlowMotorQ\n| PROXSENSOR  side=> DeviceSemantics\n                      (proxView side)\n                      (ProximitySensor alertDist maxDelay side)\n| SWCONTROLLER => SwSemantics (ControllerNode speed)\nend.\n\n\nDefinition locTopics (rl : RosLoc) : TopicInfo :=\nmatch rl with\n| BASEMOTOR => ((MOTOR::nil), nil)\n| PROXSENSOR _ => (nil, (PSENSOR::nil))\n| SWCONTROLLER => ((PSENSOR::nil), (MOTOR::nil))\nend.\n\nInstance rllllfjkfhsdakfsdakh : @CPS Train Topic Event  RosLoc _.\n  apply Build_CPS.\n  - exact locNode.\n  - exact locTopics.\n  - exact (fun srs dest del => (del <  1)%Q ).\nDefined.\n\n\n\nVariable tstate : Train.\nVariable eo : (@CPSExecution _  tstate minGap _ _ _ _ _ _ _ _ _).\n\nDefinition  TrainSpec (t:Time) : Prop :=\n    ((lEndPos tstate t) [-] safeDist [>=] lboundary )\n    /\\((rEndPos tstate t) [+] safeDist [<=] rboundary ).\n\nDefinition motorEvents : nat -> option Event \n   := localEvts BASEMOTOR.\n\nLemma QPositionLe :forall (tst : Train)\n   (ta tb : QTime) (Hab : (ta<=tb)%Q),\n   (forall (t:QTime), (ta <= t <= tb)%Q -> ({velX tst} t) [<=] 0)\n   -> ({posX tst} tb[<=] {posX tst} ta).\nProof.\n  intros ? ? ? ?  Hq.\n  apply QVelPosUB in Hq; auto.\n  unfold Q2R in Hq.\n  rewrite inj_Q_mult in Hq.\n  rewrite inj_Q_Zero in Hq.\n  rewrite cring_mult_zero_op in Hq.\n  apply shift_leEq_plus in Hq.\n  rewrite cm_lft_unit_unfolded in Hq.\n  trivial.\nQed.\n\nLemma QPositionGe :forall (tst : Train)\n   (ta tb : QTime) (Hab : (ta<=tb)%Q),\n   (forall (t:QTime), (ta <= t <= tb)%Q -> Q2R 0 [<=] ({velX tst} t))\n   -> ({posX tst} ta[<=] {posX tst} tb).\nProof.\n  intros ? ? ? ?  Hq.\n  apply QVelPosLB in Hq; auto.\n  unfold Q2R in Hq.\n  rewrite inj_Q_mult in Hq.\n  rewrite inj_Q_Zero in Hq.\n  rewrite cring_mult_zero_op in Hq.\n  apply shift_plus_leEq in Hq.\n  rewrite cm_lft_unit_unfolded in Hq.\n  trivial.\nQed.\n\nLemma QPositionGeIf :forall (tst : Train) (c : IR)\n   (ta tb : QTime) (Hab : (ta<=tb)%Q),\n   (forall (t:QTime), (ta <= t <= tb)%Q -> ({velX tst} t) [<=] 0)\n   -> c [<=] {posX tst} tb\n   -> c [<=] {posX tst} ta.\nProof.\n  intros ? ? ? ? ? Hq Hc.\n  apply QPositionLe in Hq; auto.\n  eauto using leEq_transitive.\nQed.\n\nLemma QPositionLeIf :forall (tst : Train) (c : IR)\n   (ta tb : QTime) (Hab : (ta<=tb)%Q),\n   (forall (t:QTime), (ta <= t <= tb)%Q -> 0 [<=] ({velX tst} t))\n   -> {posX tst} tb  [<=] c\n   -> {posX tst} ta  [<=] c.\nProof.\n  intros ? ? ? ? ? Hq Hc.\n  apply QPositionGe in Hq; auto.\n  eauto using leEq_transitive.\nQed.\n\n\n\n(** need to force deque events to happen\n    and also within acceptable time.\n    right now, the motor can disregard\n    all messages *)\n\nClose Scope Q_scope.\n\n\nLemma DeqSendOncePair : forall ns nd sp,\n  possibleDeqSendOncePair (ControllerNode sp) (localEvts SWCONTROLLER) nd ns\n  -> {es : Event | {ed : Event | isDeqEvt ed × isSendEvt es\n          × (nd < ns)\n              × (eTime ed < eTime es < eTime ed + digiControllerTiming)%Q\n        ×\n        localEvts SWCONTROLLER nd = Some ed \n        × localEvts SWCONTROLLER ns = Some es ×\n         {dmp : bool|  fst (eMesg ed) = ((mkMesg PSENSOR dmp))\n                  ∧ (mkImmMesg MOTOR ((SwControllerProgram sp) dmp)) = (eMesg es) }}}.\nProof.\n  intros ? ? ? Hnc.\n  apply PureProcDeqSendOncePair in Hnc.\n  simpl in Hnc.\n  destruct Hnc as [es Hnc].\n  destruct Hnc as [ed Hnc].\n  exists es. exists ed.  simpl.\n  exrepd. \n  pose proof (noSpamRecv eo _ a) as Hvr.\n  dands; trivial.\n  rewrite <- locEvtIndex in e.\n  TrimAndRHS e. rewrite e in Hvr.\n  simpl in Hvr. \n  specialize (s Hvr). clear Hvr. trivial.\nAbort.\n\n(*\nLemma DeqSendOncePair2 : forall ns nd sp,\n  possibleDeqSendOncePair2 (ControllerNode sp) \n    (localEvts SWCONTROLLER) nd ns\n\n  -> {es : Event | {ed : Event | isDeqEvt ed × isSendEvt es\n          × (nd < ns)\n              × (eTime ed < eTime es < eTime ed + 1)%Q\n        ×\n        localEvts SWCONTROLLER nd = Some ed \n        × localEvts SWCONTROLLER ns = Some es ×\n         {dmp : bool|  fst (eMesg ed) = ((mkMesg PSENSOR dmp))\n                  ∧ (mkImmMesg MOTOR ((SwControllerProgram sp) dmp)) = (eMesg es) }}}.\nProof.\n  intros ? ? ? Hnc.\n  apply PureProcDeqSendOncePair in Hnc.\n  simpl in Hnc.\n  destruct Hnc as [es Hnc].\n  destruct Hnc as [ed Hnc].\n  exists es. exists ed.  simpl.\n  exrepd. \n  pose proof (noSpamRecv eo _ a) as Hvr.\n  dands; trivial.\n  rewrite <- locEvtIndex in e.\n  TrimAndRHS e. rewrite e in Hvr.\n  simpl in Hvr. \n  specialize (s Hvr). clear Hvr. trivial.\nQed.\n*)\n\nLemma swControllerMessages : \n  forall es : Event,\n  SWCONTROLLER = eLoc es\n  -> isSendEvt es\n  -> {(eMesg es) = (mkImmMesg MOTOR speed)}\n      + {(eMesg es) = (mkImmMesg MOTOR (-speed))%Q}.\nProof.\n  intros es Hsw Hsend.\n  pose proof (locEvtIndex \n                SWCONTROLLER \n                (eLocIndex es) \n                es) as Hiff.\n  TrimAndRHS Hiff.\n  symmetry in Hsw.\n  specialize (Hiff (conj Hsw eq_refl)).\n  pose proof (corrNodes \n                  eo \n                  SWCONTROLLER \n                  (eLocIndex es)) as Hnc.\n  rewrite Hiff in Hnc.\n  TrimAndRHS Hnc. unfold isSendEvtOp in Hnc.\n  simpl in Hnc.\n  specialize (Hnc Hsend). destruct Hnc as [mDeq  Hnc].\n  destruct Hnc as [si Hnc].\n  unfold procTime, digiControllerTiming,\n  timingAcc, compose in Hnc. simpl in Hnc.\n  unfold digiControllerTiming in Hnc.\n  simpl in Hnc.\n  apply onlyNeededForOldProofs in Hnc.\n  simpl in Hnc. exrepd. \n  rewrite  e0 in Hiff. inversion Hiff as [Heq]. clear Hiff.\n  subst. unfold mkImmMesg. unfold mkMesg in H2.\n  destruct dmp;[right | left]; symmetry; apply H2.\nQed.\n\n\nLemma velMessages:\n  forall n : nat,\n     match getVelOEv (motorEvents n) with\n     | Some v => {v = speed} + {v = (-speed)%Q}\n     | None => True\n     end.\nProof.\n  intros n.\n  unfold motorEvents,getVelOEv, getRecdPayloadOp, getRecdPayload.\n  remember (localEvts BASEMOTOR n)  as oev.\n  destruct oev as [ ev| ]; simpl; [| auto; fail].\n  remember (deqMesg ev)  as om.\n  destruct om as [ sm| ]; simpl; [| auto; fail].\n  pose proof Heqom as Hem.\n  apply deqSingleMessage2  in Hem.\n  apply deqIsRecvEvt in Heqom.\n  \n  (** someone must have sent this message\n      which is contained in the receive (enque)\n      event evEnq. let the sent message\n      be [sm] and the corresponding event be [es] *)\n  pose proof (recvSend eo _ Heqom) as Hrecv.\n  repnd.\n  destruct Hrecv as [es Hrecv].\n  pose proof (proj2 (proj2 Hrecv)) as Hsend.\n  TrimAndRHS Hrecv.\n  unfold PossibleSendRecvPair in Hrecv.\n  simpl in Hrecv.\n  repnd. symmetry in Heqoev. \n  apply locEvtIndex in Heqoev.\n  repnd. rewrite Heqoevl in Hrecvrl.\n  (** since [BASEMOTOR] only receives on [MOTOR]\n      topic, the message [sm] must have that topic *)\n  unfold validRecvMesg in Hrecvrl.\n  simpl in Hrecvrl.\n  rewrite <- Hem in Hrecvrl.\n  rewrite RemoveOrFalse in Hrecvrl.\n  unfold validSendMesg in Hrecvrrl.\n  unfold mtopic in Hrecvrrl.\n  simpl. simpl. simpl. simpl in Hrecvrrl.\n  rewrite Hrecvl in Hrecvrrl.\n  remember (eLoc es) as sloc.\n  rewrite <- Hem in Hrecvrrl.\n  unfold mtopic in Hrecvrl.\n  simpl in Hrecvrl.\n  rewrite <- Hrecvrl in Hrecvrrl.\n  (** Only [SWCONTROLLER] sends on that topic *)\n  destruct sloc; simpl in Hrecvrrl;\n  try rewrite RemoveOrFalse in Hrecvrrl.\n    try contradiction;\n    try discriminate.\n\n  discriminate.\n  clear Hrecvrrl.\n  apply swControllerMessages in Hsend;\n    [| trivial].\n  destruct Hsend as [Hsend | Hsend];\n  apply (f_equal (fst)) in Hsend;\n  simpl in Hsend;\n  rewrite Hrecvl in Hsend;\n  rewrite <- Hem in Hsend;\n  unfold getPayload;\n  inverts Hsend as Hsend; simpl; rewrite Hsend; simpl; auto.\nQed.\n\nLemma  TrainVelBounded : forall (t:QTime),\n   velBound (velAtTime tstate t).\nProof.\n  intro t.\n  pose proof (corrNodes \n                  eo \n                  BASEMOTOR t) as Hnc.\n  unfold corrSinceLastVel in Hnc.\nAbort.\n\n\n\nLemma MotorOnlyReceivesFromSw :   forall Es Er,\n  isSendEvt Es\n  -> isRecvEvt Er\n  -> PossibleSendRecvPair Es Er\n  -> eLoc Er = BASEMOTOR\n  -> eLoc Es = SWCONTROLLER.\nProof.\n  intros ? ? Hs Hr Hsendl Hl.\n  unfold PossibleSendRecvPair in Hsendl.\n  repnd. clear Hsendlrrr.\n  unfold validRecvMesg in Hsendlrl.\n  pose proof (deqSingleMessage _ Hr) as XX.\n  destruct XX as [m XX].\n  repnd. rewrite <- XXl in Hsendlrl.\n  simpl in  XXl.\n  apply (f_equal ( fst)) in XXl.\n  rewrite <- Hsendll in XXl. simpl in Hsendlrrl.\n  rewrite Hl in Hsendlrl.\n  simpl in Hsendlrl.\n  rewrite RemoveOrFalse in Hsendlrl.\n  unfold validSendMesg in Hsendlrrl.\n  unfold mtopic in Hsendlrrl.\n  rewrite <- XXl in Hsendlrrl.\n  unfold mtopic in Hsendlrl.\n  simpl in Hsendlrrl,Hsendlrl. rewrite <- Hsendlrl in Hsendlrrl.\n  destruct (eLoc Es); simpl in Hsendlrrl;\n    try contradiction;\n    inversion Hsendlrrl; \n    try discriminate;\n    try contradiction.\n  reflexivity.\nQed.\n\n(** except the last 2 lines, the proof is same as the above *)\nLemma SwOnlyRecievesFromSensor :   forall Es Er,\n  isSendEvt Es\n  -> isRecvEvt Er\n  -> PossibleSendRecvPair Es Er\n  -> eLoc Er = SWCONTROLLER\n  -> {side: bool | eLoc Es = PROXSENSOR side}.\nProof.\n  intros ? ? Hs Hr Hsendl Hl.\n  unfold PossibleSendRecvPair in Hsendl.\n  repnd. clear Hsendlrrr.\n  unfold validRecvMesg in Hsendlrl.\n  pose proof (deqSingleMessage _ Hr) as XX.\n  destruct XX as [m XX].\n  repnd. rewrite <- XXl in Hsendlrl.\n  simpl in  XXl.\n  apply (f_equal ( fst)) in XXl.\n  rewrite <- Hsendll in XXl. simpl in Hsendlrrl.\n  rewrite Hl in Hsendlrl.\n  simpl in Hsendlrl.\n  rewrite RemoveOrFalse in Hsendlrl.\n  unfold validSendMesg in Hsendlrrl.\n  unfold mtopic in Hsendlrrl, Hsendlrl.\n  rewrite <- XXl in Hsendlrrl.\n  simpl in Hsendlrl, Hsendlrrl.\n  simpl in Hsendlrrl. rewrite <- Hsendlrl in Hsendlrrl.\n  destruct (eLoc Es); simpl in Hsendlrrl;\n    try contradiction;\n    try rewrite  RemoveOrFalse in Hsendlrrl; \n    try discriminate;\n    try contradiction.\n  exists b. reflexivity.\nQed.\n\n(** Ideally, device specs should imply a bound like this.\n    For a fine grained analysis, this might be less useful *)\nVariable velPos : forall (t : Time), \n  Q2R (-speed) [<=] ({velX tstate} t) /\\ ({velX tstate} t) [<=] speed.\n\n\nLemma centerPosChange : forall (ta tb : Time),\n  ta[<]tb\n  -> (centerPosAtTime tstate tb [-] centerPosAtTime tstate ta) [<=](tb[-]ta).\nProof.\n  intros. unfold centerPosAtTime. rewrite <- (one_mult _ (tb[-]ta)).\n  apply VelPosUB;[ trivial |].\n  intros. rewrite <- inj_Q_One.\n  apply velPos.\nQed.\n\nLemma centerPosChangeLB : forall (ta tb : Time),\n  ta[<]tb\n  -> (ta[-]tb) [<=] (centerPosAtTime tstate tb [-] centerPosAtTime tstate ta).\nProof.\n  intros. unfold centerPosAtTime.\n  rewrite <- minusInvR.\n  rewrite <- mult_minus1.\n  apply VelPosLB;[ trivial |].\n  intros. rewrite <- inj_Q_One.\n  rewrite <- inj_Q_inv.\n  apply velPos.\nQed.\n\nRequire Import Ring. \nRequire Import CoRN.tactics.CornTac.\nRequire Import CoRN.algebra.CRing_as_Ring.\n\nAdd Ring RisaRing: (CRing_Ring ℝ).\nRequire Import Setoid.\n\nOpen Scope Q_scope.\n\nLemma centerPosChangeQAux : forall (ta tb : QTime),\n  ((ta < tb)%Q)\n  -> (centerPosAtTime tstate tb [-] centerPosAtTime tstate ta) [<=] (tb - ta).\nProof.\n  intros ? ? Hlt.\n  pose proof (centerPosChange ta tb) as Hcc.\n  destruct ta as [qta  ap].\n  destruct tb as [qtb  bp].\n  lapply Hcc; [clear Hcc; intro Hcc |apply inj_Q_less;trivial].\n  eapply leEq_transitive; eauto.\n  trivial. unfold Q2R. rewrite inj_Q_minus. simpl. unfold Q2R. simpl.\n  apply leEq_reflexive.\nQed.\n\n\n(** this proof is not possible when [ta] and [tb] are\n    rationals *)\nLemma centerPosChangeQ : forall (ta tb : QTime),\n  (ta <= tb)%Q\n  -> (centerPosAtTime tstate tb [-] centerPosAtTime tstate ta) [<=] (tb - ta).\nProof.\n  intros ? ? Hlt.\n  apply Qle_lteq in Hlt.\n  destruct Hlt as [Hlt| Hlt].\n- apply centerPosChangeQAux; trivial.\n- apply (inj_Q_wd IR) in Hlt.\n  unfold centerPosAtTime.\n  unfold Q2R.\n  rewrite inj_Q_minus. rewrite Hlt.\n  apply TContRExtQ2 with (f:= posX tstate) in Hlt.\n  rewrite Hlt.\n  rewrite cg_minus_correct.\n  rewrite cg_minus_correct.\n  apply leEq_reflexive.\nQed.\n\nLemma centerPosChangeLBQ : forall (ta tb : QTime),\n  ta < tb\n  -> Q2R (ta - tb) [<=] (centerPosAtTime tstate tb [-] centerPosAtTime tstate ta).\nProof.\n  intros ? ? Hlt.\n  pose proof (centerPosChangeLB ta tb) as Hcc.\n  destruct ta as [qta  ap].\n  destruct tb as [qtb  bp].\n  lapply Hcc; [clear Hcc; intro Hcc |apply inj_Q_less;trivial].\n  eapply leEq_transitive; eauto.\n  trivial. unfold Q2R. rewrite inj_Q_minus. simpl. unfold Q2R. simpl.\n  apply leEq_reflexive.\nQed.\n\n\n\nLemma centerPosUB : forall (ts tf : QTime) (td : Q) (ps : ℝ),\n  ts < tf < ts + td\n  -> centerPosAtTime tstate ts[<=] ps\n  -> centerPosAtTime tstate tf[<=] (ps [+] td).\nProof.\n  intros ? ? ? ? Hint Hcs.\n  repnd.\n  apply qSubLt in Hintr.\n  rename Hintl into Htlt.\n  apply centerPosChangeQAux in Htlt.\n  remember (centerPosAtTime tstate tf) as cpvt. clear Heqcpvt.\n  remember (centerPosAtTime tstate ts) as cpst. clear Heqcpst.\n  rename Hintr into Hqlt.\n  apply inj_Q_less with (R1:=ℝ)  in Hqlt.\n  unfold Q2R in Htlt.\n  apply (leEq_less_trans _ _ _ _ Htlt) in Hqlt ; eauto.\n  clear Htlt ts tf.\n  apply less_leEq in Hqlt.\n  eapply (plus_resp_leEq_both _ _ _ _ _ Hcs) in Hqlt; eauto.\n  clear Hcs. rename Hqlt into hh.\n  rewrite realCancel in hh.\n  eapply leEq_transitive; eauto. clear hh.\n  unfold Q2R. apply leEq_reflexive.\nQed.\n\n\nLemma centerPosLB : forall (ts tf : QTime) (td : Q) (ps : ℝ),\n  ts < tf < ts + td\n  -> ps [<=] centerPosAtTime tstate ts\n  -> (ps [-] td) [<=] centerPosAtTime tstate tf.\nProof.\n  intros ? ? ? ? Hint Hcs.\n  repnd.\n  apply qSubLt in Hintr.\n  rename Hintl into Htlt.\n  apply centerPosChangeLBQ in Htlt.\n  remember (centerPosAtTime tstate tf) as cpvt. clear Heqcpvt.\n  remember (centerPosAtTime tstate ts) as cpst. clear Heqcpst.\n  rename Hintr into Hqlt.\n  apply inj_Q_less with (R1:=IR)  in Hqlt.\n  unfold Q2R in Htlt.\n  apply inv_resp_leEq in Htlt.\n  rewrite minusInvR in Htlt.\n  rewrite inj_Q_minus in Htlt.\n  rewrite minusInvR in Htlt.\n  rewrite <- inj_Q_minus in Htlt.\n  apply (leEq_less_trans _ _ _ _ Htlt) in Hqlt ; eauto.\n  clear Htlt ts tf.\n  apply less_leEq in Hqlt.\n  apply inv_resp_leEq in Hqlt.\n  rewrite minusInvR in Hqlt.\n  eapply (plus_resp_leEq_both _ _ _ _ _ Hcs) in Hqlt; eauto.\n  clear Hcs. rename Hqlt into hh.\n  rewrite realCancel in hh.\n  eapply leEq_transitive; eauto. clear hh.\n  unfold Q2R. apply leEq_reflexive.\nQed.\n\n\nLemma centerPosUB2 : forall (ts tf : QTime) (td : Q) (pf: Q),\n  (ts < tf < (ts + td))\n  -> centerPosAtTime tstate ts[<=] (pf-td)\n  -> centerPosAtTime tstate tf[<=] pf.\nProof.\n  intros ? ? ? ?  Hint Hcs.\n  apply centerPosUB with (td:= (td)) (tf:=tf) in Hcs; [| trivial; fail].\n  eapply leEq_transitive; eauto. clear Hcs Hint.\n  unfold Q2R. rewrite <- inj_Q_plus.\n  apply inj_Q_leEq.\n  simpl. lra.\nQed.\n\nLemma centerPosLB2 : forall (ts tf : QTime) (td : Q) (pf: Q),\n  (ts < tf < (ts + td))\n  -> Q2R (pf+td) [<=] centerPosAtTime tstate ts\n  -> Q2R pf [<=] centerPosAtTime tstate tf.\nProof.\n  intros ? ? ? ?  Hint Hcs.\n  apply centerPosLB with (td:= (td)) (tf:=tf) in Hcs; [| trivial; fail].\n  eapply leEq_transitive; eauto. clear Hcs Hint.\n  unfold Q2R. rewrite <- inj_Q_minus.\n  apply inj_Q_leEq.\n  unfold cg_minus. simpl. lra.\nQed.\n\n(*\nLemma centerPosUB3 : forall (ts tf td : QTime) (pf: R),\n  (ts < tf < (ts + td))\n  -> centerPosAtTime tstate ts[<=] (pf [-] td)\n  -> centerPosAtTime tstate tf[<=] pf.\nProof.\n  intros ? ? ? ?  Hint Hcs.\n  apply centerPosUB with (td:= (td)) (tf:=tf) in Hcs; [| trivial; fail].\n  eapply leEq_transitive; eauto. clear Hcs Hint.\n  unfold Q2R. rewrite <- inj_Q_plus.\n  apply inj_Q_leEq.\n  simpl. lra.\nQed.\n*)\n\nDefinition ConcreteValues : Prop :=\nhwidth =  2 \n                      /\\ boundary =  100 \n                      /\\ alertDist =   16\n                      /\\ (maxDelay = mkQTime 1 I)\n                      /\\ (reactionTime = 1)\n                      /\\ (initialVel = 0)\n                      /\\ (initialPos = 0).\n\n  \nVariable concreteValues : ConcreteValues.\n\nLemma reactionTime1 : reactionTime = 1.\nProof.\n  unfold ConcreteValues in concreteValues. tauto.\nQed.\n\nDefinition posVelMeg : Message :=\n  (mkImmMesg MOTOR speed).\n\nOpen Scope Z_scope.\n\nDefinition MotorRecievesPositivVelAtLHS (ev : Event)  :=\nmatch (eLoc  ev) with\n| BASEMOTOR => \n            isDeqEvt ev\n              -> fst (eMesg ev) = fst posVelMeg\n              -> (centerPosAtTime tstate (eTime ev)) [<=]  -78\n| SWCONTROLLER => \n            match eKind ev with\n            | sendEvt _ => \n                fst (eMesg ev) = fst posVelMeg\n                -> (centerPosAtTime tstate (eTime ev)) [<=] -79\n            | deqEvt => \n                fst (eMesg ev) = (mkMesg PSENSOR false)\n                -> (centerPosAtTime tstate (eTime ev)) [<=] -80\n            end\n| _ => True\nend.\n\nLemma QShiftMinus: ∀ a b c, (a - b < c -> a  <  b + c)%Q.\nProof.\n  intros. lra.\nQed.\n\n\nLtac SensorMsgInvert Hmd :=\n    (simpl in Hmd;\n    let T:= constr:(f_equal (getPayloadR PSENSOR)) in apply T in Hmd;\n    simpl in Hmd;\n    apply (f_equal (fun op => opExtract op false)) in Hmd;\n    simpl in Hmd).\n\nLemma  PosVelAtLHSAux : forall (ev : Event),\n          MotorRecievesPositivVelAtLHS ev.\nProof.\n  induction ev as [ev Hind] using \n    (@well_founded_induction_type Event (causedBy eo) (causalWf eo)) .\n  unfold MotorRecievesPositivVelAtLHS.\n  remember (eLoc ev) as evloc.\n  destruct evloc; auto.\n\n- intro Hdeqx. pose proof (recvSend eo _ Hdeqx) as Hsend.\n  destruct Hsend as [Es Hsend].\n  repnd. pose proof (globalCausal _ _ _ Hsendrl) as Htlt.\n  apply Hind in Hsendrl. clear Hind.\n  (** topic subscrions and topology say that [Es] must have\n      happened at [SWCONTROLLER] *)\n  symmetry in Heqevloc.\n  pose proof  (MotorOnlyReceivesFromSw _ _ \n      Hsendrr Hdeqx Hsendl Heqevloc) as Hsw.\n  unfold PossibleSendRecvPair in Hsendl.\n  repnd. clear Hsendlrrl Hsendlrl.\n  rewrite Heqevloc in Hsendlrrr.\n  rewrite Hsw in Hsendlrrr.\n  simpl in Hsendlrrr.\n  (** Now, lets unpack the induction hypothesis *)\n  unfold MotorRecievesPositivVelAtLHS in Hsendrl.\n  rewrite Hsw in Hsendrl.\n  unfold isSendEvt in Hsendrr.\n  destruct (eKind Es); (try inversion Hsendrr ).\n  rewrite Hsendll in Hsendrl.\n  parallelForall Hsendrl. clear x.\n  remember (eTime ev) as evt. clear Heqevt.\n  remember (eTime Es) as est. clear Heqest.\n  Local Opaque Q2R.\n  simpl in Hsendrl.\n  apply QShiftMinus in Hsendlrrr.\n  eapply centerPosUB2; try split; eauto.\n\n- rename ev into es. remember (eKind es) as eks.\n  destruct eks; [|auto].\n  + symmetry in Heqeks.\n    pose proof (corrNodes \n                eo \n                SWCONTROLLER \n                (eLocIndex es)) as Hnc.\n\n    pose proof (locEvtIndex SWCONTROLLER (eLocIndex es) es) as Hxx.\n    TrimAndRHS Hxx. rewrite Hxx in Hnc;[| split; auto; fail].\n    simpl  in Hnc. TrimAndRHS Hnc. clear Hxx.\n    specialize (Hnc (isSendEvtIf Heqeks)).\n    destruct Hnc as [m Hnc].\n    destruct Hnc as [si Hnc].\n    apply onlyNeededForOldProofs in Hnc.\n    simpl in Hnc. \n    destruct Hnc as [es0 Hnc].\n    destruct Hnc as [ed Hnc].\n    fold (inBetween (eTime ed) (eTime es0) (eTime ed + 1)) in Hnc.\n    exrepd. rename e into H4. rename e0 into H5.\n    pose proof (sameLocCausal eo _ H4 H5 l) as Hcaus.\n    clear l.\n    pose proof (locEvtIndex SWCONTROLLER (eLocIndex es) es) as Hiff.\n    TrimAndRHS Hiff.\n    rewrite Hiff in H5; auto;[].\n    inversion H5 as [Heqs].  clear H5.\n    symmetry in Heqs. subst es0. rename H0 into H7.\n    rewrite <- H7. intro Heq. clear H7.\n    simpl in Heq. \n    let T:= constr:(f_equal (getPayloadR MOTOR)) in \n    apply T in Heq. rename Heq into Heqq.\n    simpl in Heqq. inversion Heqq as [Heq]. clear Heqq.\n    unfold speed in Heq.\n    destruct dmp; simpl in Heq;[inversion Heq; fail| clear Heq].\n    specialize (Hind ed Hcaus). clear Hiff. clear Hcaus.\n    unfold MotorRecievesPositivVelAtLHS in Hind.\n    apply locEvtIndex in H4. repnd. subst m. \n    rewrite H4l in Hind. clear H4l. \n    unfold isDeqEvt in a.\n    destruct (eKind ed); inversion a.\n    rename H into H6.\n    specialize (Hind H6). clear H6.\n    unfold inBetween in i.\n    clear concreteValues Heqeks Heqevloc eo reactionTimeGap transitionValues velAccuracy boundary \n      alertDist safeDist maxDelay hwidth.\n    eapply centerPosUB2; eauto.\n\n  + clear Hind. symmetry in Heqeks. rename es into ed.\n    pose proof (recvSend eo ed (isDeqEvtIf Heqeks)) as Hsend.\n    destruct Hsend as [Es Hsend].\n    repnd. pose proof (globalCausal _ _ _ Hsendrl) as Htlt.\n    symmetry in Heqevloc.\n    pose proof  (SwOnlyRecievesFromSensor _ _ \n      Hsendrr (isDeqEvtIf Heqeks) Hsendl Heqevloc) as Hsw.\n    exrepd.\n    unfold PossibleSendRecvPair in Hsendl.\n    repnd. clear Hsendlrrl Hsendlrl.\n    rewrite Heqevloc in Hsendlrrr.\n    rewrite side0 in Hsendlrrr. simpl in Hsendlrrr.\n    rewrite <- Hsendll. intros Hmd.\n    apply QShiftMinus in Hsendlrrr.\n    eapply centerPosUB2; eauto.\n    clear Hsendlrrr.\n    pose proof (corrNodes \n                  eo \n                  (PROXSENSOR side)) as Hnc.\n    simpl in Hnc.\n    unfold DeviceSemantics, ProximitySensor in Hnc.\n    unfold ProxPossibleTimeEvPair in Hnc.\n    TrimAndLHS Hnc.\n    pose proof (locEvtIndex (PROXSENSOR side) (eLocIndex Es) Es) as Hx.\n    TrimAndRHS Hx.\n    specialize (Hnc (eLocIndex Es)).\n    rewrite Hx in Hnc; [| auto]. clear Hx.\n    simpl in Hnc.\n    specialize (Hnc Hsendrr).\n    destruct Hnc as [t Hnc].\n    rewrite inBetweenFold in Hnc.\n    repnd. unfold inBetween in Hncrl.\n    eapply centerPosUB2; eauto.\n    clear Hncrl.\n    rewrite Hncrr in Hmd.\n    SensorMsgInvert Hmd.\n    subst. unfold proxView in Hncl.\n    (* apply less_leEq in Hncl. *)\n    (* rewrite AbsIR_minus in Hncl. *)\n    (* apply AbsIR_bnd in Hncl. *)\n    unfold lEndPos, lboundary in Hncl.\n    pose proof concreteValues as Hcon.\n\n\nOpen Scope nat_scope.\n    AndProjN 0 Hcon as Hhw.\n    AndProjN 1 Hcon as Hbb.\n    AndProjN 2 Hcon as Hal.\n    AndProjN 3 Hcon as Hmd.\nClose Scope nat_scope.\n\n    unfold centerPosAtTime.\n    clear Hcon. subst. clear Hmd Hal Hbb Hhw.\n    remember ({posX tstate} t) as cpt.\n    clear dependent t.\n    clear dependent Event.\n    clear concreteValues velPos tstate reactionTimeGap \n        maxDelay transitionValues velAccuracy boundary safeDist \n        hwidth  reactionTime  alertDist minGap.\n    apply shift_leEq_plus in Hncl.\n    apply shift_leEq_plus in Hncl.\n    eapply leEq_transitive; eauto. clear dependent cpt.\n    rewrite <- inj_Q_Zero.\n    Local Transparent Q2R.\n    unfold Q2R, Z2R.\n    rewrite <- inj_Q_minus.\n    rewrite <- inj_Q_plus.\n    rewrite <- inj_Q_plus.\n    apply inj_Q_leEq.\n    simpl. unfold cg_minus. simpl.\n    simpl.  unfold QT2Q.\n    simpl. unfold inject_Z. simpl. lra.\nQed.\n\nClose Scope Z_scope.\n\nDefinition negVelMeg :  Message :=\n  (mkImmMesg MOTOR (-speed)).\n\nOpen Scope Z_scope.\n\nDefinition MotorRecievesNegVelAtRHS (ev : Event)  :=\nmatch (eLoc  ev) with\n| BASEMOTOR => \n            isDeqEvt ev\n              -> fst (eMesg ev) = fst negVelMeg\n              -> 78 [<=]  (centerPosAtTime tstate (eTime ev))\n| SWCONTROLLER => \n            match eKind ev with\n            | sendEvt _ => \n                fst  (eMesg ev) =  fst negVelMeg\n                -> 79 [<=] (centerPosAtTime tstate (eTime ev))\n            | deqEvt => \n                fst (eMesg ev) = (mkMesg PSENSOR true)\n                -> 80 [<=] (centerPosAtTime tstate (eTime ev))\n            end\n| _ => True\nend.\n\nLemma  NegVelAtRHSAux : forall (ev : Event),\n          MotorRecievesNegVelAtRHS ev.\nProof.\n  induction ev as [ev Hind] using \n    (@well_founded_induction_type Event (causedBy eo) (causalWf eo)).\n  unfold MotorRecievesNegVelAtRHS.\n  remember (eLoc ev) as evloc.\n  destruct evloc; auto.\n\n\n- intro Hdeqx. pose proof (recvSend eo _ Hdeqx) as Hsend.\n  destruct Hsend as [Es Hsend].\n  repnd. pose proof (globalCausal _ _ _ Hsendrl) as Htlt.\n  apply Hind in Hsendrl. clear Hind.\n  (** topic subscrions and topology say that [Es] must have\n      happened at [SWCONTROLLER] *)\n  symmetry in Heqevloc.\n  pose proof  (MotorOnlyReceivesFromSw _ _ \n      Hsendrr Hdeqx Hsendl Heqevloc) as Hsw.\n  unfold PossibleSendRecvPair in Hsendl.\n  repnd. clear Hsendlrrl Hsendlrl.\n  rewrite Heqevloc in Hsendlrrr.\n  rewrite Hsw in Hsendlrrr.\n  simpl in Hsendlrrr.\n  (** Now, lets unpack the induction hypothesis *)\n  unfold MotorRecievesNegVelAtRHS in Hsendrl.\n  rewrite Hsw in Hsendrl.\n  unfold isSendEvt in Hsendrr.\n  destruct (eKind Es); (try inversion Hsendrr ).\n  rewrite Hsendll in Hsendrl.\n  parallelForall Hsendrl. clear x.\n  remember (eTime ev) as evt. clear Heqevt.\n  remember (eTime Es) as est. clear Heqest.\n  Local Opaque Q2R.\n  simpl in Hsendrl.\n  apply QShiftMinus in Hsendlrrr.\n  eapply centerPosLB2; try split; eauto.\n\n- rename ev into es. remember (eKind es) as eks.\n  destruct eks; [|auto].\n  + symmetry in Heqeks.\n    pose proof (corrNodes \n                eo \n                SWCONTROLLER \n                (eLocIndex es)) as Hnc.\n\n    pose proof (locEvtIndex SWCONTROLLER (eLocIndex es) es) as Hxx.\n    TrimAndRHS Hxx. rewrite Hxx in Hnc;[| split; auto; fail].\n    simpl  in Hnc. TrimAndRHS Hnc. clear Hxx.\n    specialize (Hnc (isSendEvtIf Heqeks)).\n    destruct Hnc as [m Hnc].\n    destruct Hnc as [si Hnc].\n    apply onlyNeededForOldProofs in Hnc.\n    simpl in Hnc. \n    destruct Hnc as [es0 Hnc].\n    destruct Hnc as [ed Hnc].\n    fold (inBetween (eTime ed) (eTime es0) (eTime ed + 1)) in Hnc.\n    exrepd. rename e into H4. rename e0 into H5.\n    pose proof (sameLocCausal eo _ H4 H5 l) as Hcaus.\n    clear l.\n    pose proof (locEvtIndex SWCONTROLLER (eLocIndex es) es) as Hiff.\n    TrimAndRHS Hiff.\n    rewrite Hiff in H5; auto;[].\n    inversion H5 as [Heqs].  clear H5.\n    symmetry in Heqs. subst es0. rename H0 into H7.\n    rewrite <- H7. intro Heq. clear H7.\n        let T:= constr:(f_equal (getPayloadR MOTOR)) in \n    apply T in Heq. rename Heq into Heqq.\n    simpl in Heqq. inversion Heqq as [Heq]. clear Heqq.\n    unfold speed in Heq.\n    destruct dmp; simpl in Heq;[clear Heq| inversion Heq; fail].\n    specialize (Hind ed Hcaus). clear Hiff. clear Hcaus.\n    unfold MotorRecievesNegVelAtRHS in Hind.\n    apply locEvtIndex in H4. repnd. subst m. \n    rewrite H4l in Hind. clear H4l.\n    unfold isDeqEvt in a.\n    destruct (eKind ed); inversion a.\n    rename H into H6.\n    specialize (Hind H6). clear H6.\n    unfold inBetween in i.\n    clear concreteValues Heqeks Heqevloc eo reactionTimeGap transitionValues velAccuracy boundary \n      alertDist safeDist maxDelay hwidth.\n    eapply centerPosLB2; eauto.\n\n  + clear Hind. symmetry in Heqeks. rename es into ed.\n    pose proof (recvSend eo _ (isDeqEvtIf Heqeks)) as Hsend.\n    destruct Hsend as [Es Hsend].\n    repnd. pose proof (globalCausal _ _ _ Hsendrl) as Htlt.\n    symmetry in Heqevloc.\n    pose proof  (SwOnlyRecievesFromSensor _ _ \n      Hsendrr (isDeqEvtIf Heqeks) Hsendl Heqevloc) as Hsw.\n    exrepd.\n    unfold PossibleSendRecvPair in Hsendl.\n    repnd. clear Hsendlrrl Hsendlrl.\n    rewrite Heqevloc in Hsendlrrr.\n    rewrite side0 in Hsendlrrr. simpl in Hsendlrrr.\n    rewrite <- Hsendll. intros Hmd.\n    apply QShiftMinus in Hsendlrrr.\n    eapply centerPosLB2; eauto.\n    clear Hsendlrrr.\n    pose proof (corrNodes \n                  eo \n                  (PROXSENSOR side)) as Hnc.\n    simpl in Hnc.\n    unfold DeviceSemantics, ProximitySensor in Hnc.\n    unfold ProxPossibleTimeEvPair in Hnc.\n    TrimAndLHS Hnc.\n    pose proof (locEvtIndex (PROXSENSOR side) (eLocIndex Es) Es) as Hx.\n    TrimAndRHS Hx.\n    specialize (Hnc (eLocIndex Es)).\n    rewrite Hx in Hnc; [| auto]. clear Hx.\n    simpl in Hnc.\n    specialize (Hnc Hsendrr).\n    destruct Hnc as [t Hnc].\n    rewrite inBetweenFold in Hnc.\n    repnd. unfold inBetween in Hncrl.\n    eapply centerPosLB2; eauto.\n    clear Hncrl.\n    rewrite Hncrr in Hmd.\n    SensorMsgInvert Hmd.\n    subst. unfold proxView in Hncl.\n    (* apply less_leEq in Hncl. *)\n    (* apply AbsIR_bnd in Hncl. *)\n    unfold rEndPos, rboundary in Hncl.\n    pose proof concreteValues as Hcon.\n\nOpen Scope nat_scope.\n    AndProjN 0 Hcon as Hhw.\n    AndProjN 1 Hcon as Hbb.\n    AndProjN 2 Hcon as Hal.\n    AndProjN 3 Hcon as Hmd.\nClose Scope nat_scope.\n\n    unfold centerPosAtTime.\n    clear Hcon. subst. clear Hmd Hal Hbb Hhw.\n    remember ({posX tstate} t) as cpt.\n    clear dependent t.\n    clear dependent Event.\n    clear concreteValues velPos tstate reactionTimeGap \n        maxDelay transitionValues velAccuracy boundary safeDist \n        hwidth  reactionTime  alertDist minGap.\n    rewrite CAbGroups.minus_plus in Hncl.\n    apply shift_leEq_plus in Hncl.\n    apply minusSwapLe in Hncl.\n    eapply leEq_transitive; eauto. clear dependent cpt.\n    unfold Z2R. unfold inject_Z.\n    Local Transparent Q2R.\n    unfold Q2R, Z2R.\n    rewrite <- inj_Q_plus.\n    rewrite <- inj_Q_minus.\n    apply inj_Q_leEq.\n    simpl. unfold cg_minus. simpl.\n     lra.\nQed.\n\n\n\nClose Scope Z_scope.\n\nLemma velocityMessagesAuxMsg: forall upto mt,\n  member mt (filterPayloadsUptoIndex MOTOR (localEvts BASEMOTOR) upto)\n  -> {fst mt  = speed} + {fst mt = (-speed)}.\nProof.\n  induction upto as [ | upt Hind]; simpl; intros mt Hmem;[contradiction|].\n  pose proof (velMessages upt) as Hvm.\n  unfold getPayloadAndEv, getRecdPayload in Hmem.\n  unfold getVelOEv, getRecdPayloadOp, \n    getRecdPayload, motorEvents in Hvm. simpl in Hvm.\n  simpl in Hmem.\n  destruct (localEvts BASEMOTOR upt) as [ev|]; simpl in Hvm, Hmem;\n    [| auto; fail].\n  fold (getVelM) in Hvm, Hmem.\n  destruct (opBind getVelM (deqMesg ev)) as [vel|];\n    [| auto; fail].\n  simpl in Hmem.\n  destruct Hmem as [Hmem| Hmem];[auto;fail| subst].\n  simpl. destruct Hvm; auto.\nQed.\n\nLemma velocityMessagesMsg: forall m t,\n  member m (velocityMessages t)\n  -> {fst m  = speed} + {fst m = (-speed)}.\nProof.\n  intros ? ? Hmem.\n  apply velocityMessagesAuxMsg in Hmem.\n  trivial.\nQed.\n\nOpen Scope Z_scope.\n\nLemma posVelAtLHS : forall evp,\n  getRecdPayload MOTOR evp = Some speed\n  -> eLoc evp = BASEMOTOR\n  -> (centerPosAtTime tstate (eTime evp)) [<=]  -78.\nProof.\n  intros ? Hp Hl.\n  pose proof (PosVelAtLHSAux evp) as Hev.\n  unfold MotorRecievesPositivVelAtLHS in Hev.\n  rewrite Hl in Hev.\n  pose proof (getRecdPayloadSpecMesg MOTOR) as Hd.\n  simpl in Hd.\n  specialize (Hd _ _ Hp). repnd.\n  specialize (Hev Hdl Hdr).\n  trivial.\nQed.\n  \nLemma negVelAtRHS : forall evp,\n  getRecdPayload MOTOR evp = Some (-speed)%Q\n  -> eLoc evp = BASEMOTOR\n  -> 78 [<=] (centerPosAtTime tstate (eTime evp)) .\nProof.\n  intros ? Hp Hl.\n  pose proof (NegVelAtRHSAux evp) as Hev.\n  unfold MotorRecievesNegVelAtRHS in Hev.\n  rewrite Hl in Hev.\n  pose proof (getRecdPayloadSpecMesg MOTOR) as Hd.\n  simpl in Hd.\n  specialize (Hd _ _ Hp). repnd.\n  specialize (Hev Hdl Hdr).\n  trivial.\nQed.\n\nClose Scope Z_scope.\n\nDefinition priorMotorMesg (vel: Q) (t : QTime):=\n(λ ev : Event,\n         eTime ev < t\n         ∧ getRecdPayload MOTOR ev = Some vel \n          ∧ eLoc ev = BASEMOTOR).\n\nOpen Scope Z_scope.\nLemma motorLastPosVelAux : forall (lm : list (Q * Event)) (t : QTime),\n  1 [<=] (centerPosAtTime tstate t)\n  -> lm = velocityMessages t\n  -> sig (latestEvt  (priorMotorMesg speed t)).\nProof.\n  intro. unfold priorMotorMesg.\n  induction lm as [|hlm tlm Hind]; intros ? Hcent Heq.\n- simpl. assert False;[| contradiction].\n  pose proof (corrNodes \n                eo \n                BASEMOTOR t) as Hm.\n  simpl in Hm.\n  unfold corrSinceLastVel, lastVelAndTime, correctVelDuring in Hm.\n  unfold lastPayloadAndTime in Hm. unfold velocityMessages in Heq.\n  rewrite <- Heq in Hm. unfold last in Hm.\n  pose proof concreteValues as Hinit.\nOpen Scope nat_scope.\n  AndProjN 4 Hinit as Hrt.\n  AndProjN 5 Hinit as Hv.\n  AndProjN 6 Hinit as Hp.\nClose Scope nat_scope.\n  clear Hinit. \n  subst. clear Hrt Heq. unfold hd in Hm.\n  rewrite mapNil in Hm.\n  rewrite (initVel tstate) in Hm.\n  destruct Hm as [qtrans Hm]. repnd.\n  \n  eapply QPositionGeIf with (ta:=(mkQTime 0 I)) in Hcent; auto;\n    [|apply qtimePos|].\n  + rewrite initPos in Hcent.\n    rewrite Hp in Hcent.\n    unfold Q2R in Hcent.\n    apply leEq_inj_Q in Hcent.\n    simpl in Hcent.\n    unfold inject_Z in Hcent. lra.\n  + intros qt H0t. \n    pose proof (Qlt_le_dec qt qtrans) as Hd.\n    destruct Hd as [Hd|Hd];[clear Hmrl | clear Hmrr].\n    apply Qlt_le_weak in Hd.\n    * rewrite Hv in Hmrr. specialize (Hmrr qt (conj (proj1 H0t) Hd)).\n      unfold core.between in Hmrr.\n      apply proj2 in Hmrr.\n      eapply leEq_transitive; eauto.\n      rewrite Max_id. apply inj_Q_leEq.\n      simpl. unfold inject_Z. simpl. lra.\n\n    * rewrite Hv in Hmrl. specialize (Hmrl qt (conj Hd (proj2 H0t))).\n      rewrite Hmrl.\n      apply inj_Q_leEq.\n      simpl. unfold inject_Z. simpl. lra.\n- (** check if nth event is +1 Deq . if so, exists n. else\n      it is a -1. if not, by a lemma similar to PosVelAtNegPos,\n      we can prove that centerpos at (eTime (nth event)) >=50\n      . hence it is >0, hence, apply induction nyp with \n      t:=(eTime (nth event)) \n    *)\n  pose proof (corrNodes \n                eo \n                BASEMOTOR t) as Hm.\n  simpl in Hm.\n  unfold corrSinceLastVel, lastVelAndTime, correctVelDuring in Hm.\n  unfold lastPayloadAndTime in Hm. unfold velocityMessages in Heq.\n  rewrite <- Heq in Hm.\n  match type of Heq with\n  | ?h::_ = ?r => assert (member h r) as Hvm;\n      [rewrite <- Heq; simpl; right; reflexivity|]\n  end.\n  apply velocityMessagesMsg in Hvm.\n  pose proof Heq as Hcorr.\n  unfold velocityMessages in Hcorr.\n  pose proof (filterPayloadsTimeCorr MOTOR BASEMOTOR) as Hs.\n  simpl in Hs.\n  apply Hs in Hcorr. clear Hs.\n  destruct Hvm as [Hvm | Hvm].\n  + clear Hm Hind. (** last message was of positive vel *)\n    exists (snd hlm). simpl in Hvm.\n    simpl. rewrite Hvm in Hcorr.\n    fold (posVelMeg) in Hcorr. repnd.\n    pose proof (filterPayloadsTimeLatest MOTOR BASEMOTOR) as Hlat.\n    simpl in Hlat. \n    apply Hlat in Heq.\n    eapply latestEvtStr; eauto.\n    intros ? Hp. simpl. repnd.\n    rewrite Hprl. dands; auto.\n\n  + unfold hd in Hm. (** last message was of negative vel *)\n    destruct hlm as [hq ht].\n    simpl in Hvm. simpl in Hcorr.\n    simpl in Hcorr. repnd. simpl in Hm. \n    specialize (fun gt => Hind (eTime ht) gt Hcorrrrr).\n    clear Hm Hcent. subst hq.\n    lapply Hind;[clear Hind; intros Hind|].\n    * destruct Hind as [evInd Hind]. exists evInd.\n      unfold latestEvt in Hind. repnd.\n      split; [dands; auto; eauto using Qlt_trans|].\n      intros ? Hpp.\n      repnd. \n      let slem:= eval simpl in (filterPayloadsTimeComp MOTOR) in\n        eapply slem in Hpprl; eauto.\n      unfold velocityMessages in Heq.\n      rewrite <- Heq in Hpprl.\n      simpl in Hpprl.\n      destruct Hpprl as [Hh| Ht];\n        [|subst; apply (f_equal fst) in Ht; inverts Ht; fail].\n      subst tlm. \n      let slem:= eval simpl in (filterPayloadsTimeCorr2 MOTOR) in\n        apply slem in Hh.\n      simpl in Hh. repnd.\n      apply Hindr; dands; auto.\n    * clear Hind Heq Hcorrrrr.\n      eapply negVelAtRHS in Hcorrl; eauto.\n      eapply leEq_transitive;[ | apply Hcorrl].\n      UnfoldLRA.\nQed.\n\nLemma motorLastNegVelAux : forall (lm : list (Q * Event)) (t : QTime),\n  (centerPosAtTime tstate t) [<=] -1\n  -> lm = velocityMessages t\n  -> sig (latestEvt  (priorMotorMesg (-speed) t)).\nProof.\n  intro. unfold priorMotorMesg.\n  induction lm as [|hlm tlm Hind]; intros ? Hcent Heq.\n- simpl. assert False;[| contradiction].\n  pose proof (corrNodes \n                eo \n                BASEMOTOR t) as Hm.\n  simpl in Hm.\n  unfold corrSinceLastVel, lastVelAndTime, correctVelDuring in Hm.\n  unfold lastPayloadAndTime in Hm. unfold velocityMessages in Heq.\n  rewrite <- Heq in Hm. unfold last in Hm.\n  pose proof concreteValues as Hinit.\nOpen Scope nat_scope.\n  AndProjN 4 Hinit as Hrt.\n  AndProjN 5 Hinit as Hv.\n  AndProjN 6 Hinit as Hp.\nClose Scope nat_scope.\n  clear Hinit. \n  subst. clear Hrt Heq. unfold hd in Hm.\n  rewrite mapNil in Hm.\n  rewrite (initVel tstate) in Hm.\n  destruct Hm as [qtrans Hm]. repnd.\n  \n  eapply QPositionLeIf with (ta:=(mkQTime 0 I)) in Hcent; auto;\n    [|apply qtimePos|].\n  + rewrite initPos in Hcent.\n    rewrite Hp in Hcent.\n    unfold Q2R in Hcent.\n    apply leEq_inj_Q in Hcent.\n    unfold inject_Z in Hcent. simpl in Hcent.\n    lra.\n  + intros qt H0t.\n    pose proof (Qlt_le_dec qt qtrans) as Hd.\n    destruct Hd as [Hd|Hd];[clear Hmrl | clear Hmrr].\n    apply Qlt_le_weak in Hd.\n    * rewrite Hv in Hmrr. specialize (Hmrr qt (conj (proj1 H0t) Hd)).\n      unfold core.between in Hmrr.\n      apply proj1 in Hmrr.\n      eapply leEq_transitive; eauto.\n      rewrite Min_id. UnfoldLRA.\n\n    * rewrite Hv in Hmrl. specialize (Hmrl qt (conj Hd (proj2 H0t))).\n      rewrite Hmrl.\n      apply inj_Q_leEq.\n      simpl. unfold inject_Z. simpl. lra.\n- (** check if nth event is +1 Deq . if so, exists n. else\n      it is a -1. if not, by a lemma similar to PosVelAtNegPos,\n      we can prove that centerpos at (eTime (nth event)) >=50\n      . hence it is >0, hence, apply induction nyp with \n      t:=(eTime (nth event)) \n    *)\n  pose proof (corrNodes \n                eo \n                BASEMOTOR t) as Hm.\n  simpl in Hm.\n  unfold corrSinceLastVel, lastVelAndTime, correctVelDuring in Hm.\n  unfold lastPayloadAndTime in Hm. unfold velocityMessages in Heq.\n  rewrite <- Heq in Hm.\n  match type of Heq with\n  | ?h::_ = ?r => assert (member h r) as Hvm;\n      [rewrite <- Heq; simpl; right; reflexivity|]\n  end.\n  apply velocityMessagesMsg in Hvm.\n  pose proof Heq as Hcorr.\n  unfold velocityMessages in Hcorr.\n  pose proof (filterPayloadsTimeCorr MOTOR BASEMOTOR) as Hs.\n  simpl in Hs.\n  apply Hs in Hcorr. clear Hs.\n  apply Sumbool.sumbool_not in Hvm.\n  destruct Hvm as [Hvm | Hvm].\n  + clear Hm Hind. (** last message was of positive vel *)\n    exists (snd hlm). simpl in Hvm.\n    simpl. rewrite Hvm in Hcorr.\n    fold (posVelMeg) in Hcorr. repnd.\n    pose proof (filterPayloadsTimeLatest MOTOR BASEMOTOR) as Hlat.\n    simpl in Hlat. \n    apply Hlat in Heq.\n    eapply latestEvtStr; eauto.\n    intros ? Hp. simpl. repnd.\n    rewrite Hprl. dands; auto.\n\n  + unfold hd in Hm. (** last message was of negative vel *)\n    destruct hlm as [hq ht].\n    simpl in Hvm. simpl in Hcorr.\n    simpl in Hcorr. repnd. simpl in Hm. \n    specialize (fun gt => Hind (eTime ht) gt Hcorrrrr).\n    clear Hm Hcent. subst hq.\n    lapply Hind;[clear Hind; intros Hind|].\n    * destruct Hind as [evInd Hind]. exists evInd.\n      unfold latestEvt in Hind. repnd.\n      split; [dands; auto; eauto using Qlt_trans|].\n      intros ? Hpp.\n      repnd. \n      let slem:= eval simpl in (filterPayloadsTimeComp MOTOR) in\n        eapply slem in Hpprl; eauto.\n      unfold velocityMessages in Heq.\n      rewrite <- Heq in Hpprl.\n      simpl in Hpprl.\n      destruct Hpprl as [Hh| Ht];\n        [|subst; apply (f_equal fst) in Ht; inverts Ht; fail].\n      subst tlm. \n      let slem:= eval simpl in (filterPayloadsTimeCorr2 MOTOR) in\n        apply slem in Hh.\n      simpl in Hh. repnd.\n      apply Hindr; dands; auto.\n    * clear Hind Heq Hcorrrrr.\n      eapply posVelAtLHS in Hcorrl; eauto.\n      eapply leEq_transitive;[apply Hcorrl|].\n      UnfoldLRA.\nQed.\n\n(** in the aux version, lm was there only for induction.\n    lets get rid of it*)\nLemma motorLastPosVel: forall (t : QTime),\n  1 [<=] (centerPosAtTime tstate t)\n  -> sig (latestEvt (priorMotorMesg speed t)).\nProof.\n  intros. eapply motorLastPosVelAux; eauto.\nQed.\n\n(** in the aux version, lm was there only for induction.\n    lets get rid of it*)\nLemma motorLastNegVel: forall (t : QTime),\n  (centerPosAtTime tstate t) [<=] (Z2R (-1))\n  -> sig (latestEvt (priorMotorMesg (-speed) t)).\nProof.\n  intros. eapply motorLastNegVelAux; eauto.\nQed.\n\n\nLemma SensorOnlySendsToSw :   forall Es Er side,\n  isSendEvt Es\n  -> isRecvEvt Er\n  -> PossibleSendRecvPair Es Er\n  -> eLoc Es = PROXSENSOR side\n  -> eLoc Er = SWCONTROLLER.\nProof.\n  intros ? ? ? Hs Hr Hsendl Hl.\n  unfold PossibleSendRecvPair in Hsendl.\n  repnd. clear Hsendlrrr.\n  unfold validSendMesg in Hsendlrrl.\n  pose proof (deqSingleMessage _ Hr) as XX.\n  destruct XX as [m XX].\n  repnd. rewrite <- XXl in Hsendlrl.\n  apply (f_equal ( fst)) in XXl.\n  rewrite <- Hsendll in XXl. simpl in Hsendlrrl.\n  simpl in Hsendlrrl, XXl. \n  unfold mtopic in Hsendlrrl. simpl in Hsendlrrl.\n  rewrite <- XXl in Hsendlrrl.\n  rewrite Hl in Hsendlrrl.\n  simpl in Hsendlrrl.\n  rewrite RemoveOrFalse in Hsendlrrl.\n  unfold validSendMesg in Hsendlrrl.\n  simpl in Hsendlrrl. unfold validRecvMesg, mtopic in Hsendlrl.\n  simpl in Hsendlrl. rewrite <- Hsendlrrl in Hsendlrl.\n  destruct (eLoc Er); simpl in Hsendlrl;\n    try rewrite RemoveOrFalse in Hsendlrl;\n    try contradiction;\n    inversion Hsendlrrl; \n    try discriminate;\n    try contradiction.\n  reflexivity.\nQed.\n\nLemma SwOnlySendsToMotor :   forall Es Er,\n  isSendEvt Es\n  -> isRecvEvt Er\n  -> PossibleSendRecvPair Es Er\n  -> eLoc Es = SWCONTROLLER\n  -> eLoc Er = BASEMOTOR.\nProof.\n  intros ? ?  Hs Hr Hsendl Hl.\n  unfold PossibleSendRecvPair in Hsendl.\n  repnd. clear Hsendlrrr.\n  unfold validSendMesg in Hsendlrrl.\n  pose proof (deqSingleMessage _ Hr) as XX.\n  destruct XX as [m XX].\n  repnd. rewrite <- XXl in Hsendlrl.\n  apply (f_equal ( fst)) in XXl.\n  rewrite <- Hsendll in XXl. simpl in Hsendlrrl.\n  simpl in Hsendlrrl, XXl. \n  unfold mtopic in Hsendlrrl. simpl in Hsendlrrl.\n  rewrite <- XXl in Hsendlrrl.\n  rewrite Hl in Hsendlrrl.\n  simpl in Hsendlrrl.\n  rewrite RemoveOrFalse in Hsendlrrl.\n  unfold validSendMesg in Hsendlrrl.\n  simpl in Hsendlrrl. unfold validRecvMesg, mtopic in Hsendlrl.\n  simpl in Hsendlrl. rewrite <- Hsendlrrl in Hsendlrl.\n  destruct (eLoc Er); simpl in Hsendlrl;\n    try rewrite RemoveOrFalse in Hsendlrl;\n    try contradiction;\n    inversion Hsendlrrl; \n    try discriminate;\n    try contradiction.\n  reflexivity.\nQed.\n  \nLemma timeDiffLBPosVel : forall (ts te : Time) (ps pe : ℝ),\n  {tstate} ts [<=] ps\n  -> pe [<=] {tstate} te\n  -> ts [<=] te\n  -> ps [<] pe\n  -> (pe[-]ps) [<=] te [-] ts.\nProof.\n  intros ? ? ? ? Htl Htr Hte Hplt.\n  assert ({tstate} ts [<] {tstate} te) as Hlt by eauto 4 with CoRN.\n  apply TContRlt in Hlt; trivial;[].\n  pose proof (minus_resp_leEq_both _ _ _ _ _ Htr Htl).\n  eapply leEq_transitive; eauto.\n  apply centerPosChange.\n  trivial.\nQed.\n\nLemma timeDiffLBNegVel : forall (ts te : Time) (ps pe : ℝ),\n  {tstate} te [<=] pe\n  -> ps [<=] {tstate} ts\n  -> ts [<=] te\n  -> pe [<] ps\n  ->  (ps[-]pe) [<=] te [-] ts .\nProof.\n  intros ? ? ? ? Htl Htr Hte Hplt.\n  assert ({tstate} te [<] {tstate} ts) as Hlt by eauto 4 with CoRN.\n  apply TContRgt in Hlt; trivial;[].\n  pose proof (minus_resp_leEq_both _ _ _ _ _ Htl Htr) as HH.\n  apply inv_cancel_leEq.\n  rewrite minusInvR.\n  rewrite minusInvR.\n  eapply leEq_transitive; eauto.\n  apply centerPosChangeLB.\n  trivial.\nQed.\n\nClose Scope Q_scope.\nOpen Scope nat_scope.\n\nLemma NegAfterLatestPos : forall evMp evMn t (n:nat),\n  priorMotorMesg (-speed) t evMn\n  -> (latestEvt (priorMotorMesg speed t)) evMp\n  -> (eTime evMp < eTime evMn)%Q\n  -> (S (eLocIndex evMn) <= n)%nat\n  -> let lm := filterPayloadsUptoIndex MOTOR (localEvts BASEMOTOR) n in\n     match lm with\n     | hdp::tlp =>\n          (eTime (snd hdp) < t)%Q -> (fst hdp) = (-speed)%Q\n     | nil => True\n     end.\nProof.\n  intros  ? ? ? ? Hp Hl Het Hle.\n  induction Hle as [| np Hnp Hind].\n- simpl. unfold priorMotorMesg in Hp.\n  repnd.\n  pose proof (locEvtIndex BASEMOTOR (eLocIndex evMn) evMn) as Hxx.\n  rewrite ((proj1 Hxx) (conj Hprr eq_refl)).\n  simpl. rewrite Hprl. simpl. reflexivity.\n- simpl. simpl in Hind.\n  pose proof (velocityMessagesAuxMsg (S np)) as Hxy.\n  pose proof (filterPayloadsIndexCorr2 MOTOR BASEMOTOR (S np)) as Hxz.\n  simpl in Hxy, Hxz.\n  remember ((getPayloadAndEv MOTOR (localEvts BASEMOTOR np)))\n    as oplev.\n  destruct oplev as [plev|];[clear Hind| exact Hind].\n  simpl. simpl in Hxz, Hxy. \n  specialize (Hxz _ (inr eq_refl)).\n  specialize (Hxy _ (inr eq_refl)).\n  intros Hplt.\n  destruct Hxy as [hxy | Hxy];trivial;[].\n  provefalse. \n  unfold latestEvt in Hl.\n  repnd. rewrite hxy in Hxzl. clear Hxzrr.\n  unfold priorMotorMesg in Hlr.\n  specialize (Hlr _ (conj Hplt (conj Hxzl Hxzrl))).\n  clear Hxzl Hxzrl.\n  revert Hlr.\n  remember (localEvts BASEMOTOR np) as oev.\n  destruct oev as [ev|];\n  simpl in Heqoplev;[|inverts Heqoplev; fail].\n  destruct (getRecdPayload MOTOR ev); inverts Heqoplev.\n  simpl in Hplt. simpl.\n  intro Hcc. assert (eTime evMp < eTime ev)%Q;[| lra].\n  clear Hcc.\n  symmetry in Heqoev. apply locEvtIndex in Heqoev.\n  repnd.\n  fold (lt (eLocIndex evMn) np) in Hnp.\n  rewrite <- Heqoevr  in Hnp.\n  apply timeIndexConsistent in Hnp.\n  remember (eTime ev).\n  remember (eTime evMp).\n  lra.\nQed.\n\nLemma PosAfterLatestNeg : forall evMp evMn t (n:nat),\n  priorMotorMesg (speed) t evMn\n  -> (latestEvt (priorMotorMesg (-speed) t)) evMp\n  -> (eTime evMp < eTime evMn)%Q\n  -> (S (eLocIndex evMn) <= n)%nat\n  -> let lm := filterPayloadsUptoIndex \n                  MOTOR (localEvts BASEMOTOR) n in\n     match lm with\n     | hdp::tlp =>\n          (eTime (snd hdp) < t)%Q -> (fst hdp) = (speed)\n     | nil => True\n     end.\nProof.\n  intros  ? ? ? ? Hp Hl Het Hle.\n  induction Hle as [| np Hnp Hind].\n- simpl. unfold priorMotorMesg in Hp.\n  repnd.\n  pose proof (locEvtIndex BASEMOTOR (eLocIndex evMn) evMn) as Hxx.\n  rewrite ((proj1 Hxx) (conj Hprr eq_refl)).\n  simpl. rewrite Hprl. simpl. reflexivity.\n- simpl. simpl in Hind.\n  pose proof (velocityMessagesAuxMsg (S np)) as Hxy.\n  pose proof (filterPayloadsIndexCorr2 MOTOR BASEMOTOR (S np)) as Hxz.\n  simpl in Hxy, Hxz.\n  remember ((getPayloadAndEv MOTOR (localEvts BASEMOTOR np)))\n    as oplev.\n  destruct oplev as [plev|];[clear Hind| exact Hind].\n  simpl. simpl in Hxz, Hxy. \n  specialize (Hxz _ (inr eq_refl)).\n  specialize (Hxy _ (inr eq_refl)).\n  intros Hplt.\n  destruct Hxy as [Hxy | Hxy];trivial;[].\n  provefalse. \n  unfold latestEvt in Hl.\n  repnd. rewrite Hxy in Hxzl. clear Hxzrr.\n  unfold priorMotorMesg in Hlr.\n  specialize (Hlr _ (conj Hplt (conj Hxzl Hxzrl))).\n  clear Hxzl Hxzrl.\n  revert Hlr.\n  remember (localEvts BASEMOTOR np) as oev.\n  destruct oev as [ev|];\n  simpl in Heqoplev;[|inverts Heqoplev; fail].\n  destruct (getRecdPayload MOTOR ev); inverts Heqoplev.\n  simpl in Hplt. simpl.\n  intro Hcc. assert (eTime evMp < eTime ev)%Q;[| lra].\n  clear Hcc.\n  symmetry in Heqoev. apply locEvtIndex in Heqoev.\n  repnd.\n  fold (lt (eLocIndex evMn) np) in Hnp.\n  rewrite <- Heqoevr  in Hnp.\n  apply timeIndexConsistent in Hnp.\n  remember (eTime ev).\n  remember (eTime evMp).\n  lra.\nQed.\n\nOpen Scope Z_scope.\n\nLemma VelNegAfterLatestPosAux : forall evMp evMn t ev,\n  priorMotorMesg (-speed) t evMn\n  -> (latestEvt (priorMotorMesg speed t)) evMp\n  -> (eTime evMp < eTime evMn)%Q\n  -> ((eLocIndex evMn) < eLocIndex ev)%nat\n  -> (eLoc ev = BASEMOTOR)\n  -> (eTime ev < t)%Q\n  -> ({velX tstate}  (eTime ev) [<=] -1).\nProof.\n  intros  ? ? ? ? Hp Hl Het Hle Hloc Hevt.\n  pose proof (NegAfterLatestPos _ _ _ _ Hp Hl Het Hle) as Hnn.\n  simpl in Hnn.\n  pose proof (corrNodes \n              eo \n              BASEMOTOR  (eTime ev)) as Hm.\n  simpl in Hm.\n  unfold corrSinceLastVel, lastVelAndTime, \n      lastPayloadAndTime, filterPayloadsUptoTime in Hm.\n  rewrite numPrevEvtsEtime in Hm; [| trivial];[].\n    (* we know that \n      the default case of [hd] wont get invoked in Hm\n      Luckily, [initialVel] is correct,\n      but let's not depend on that because\n      we already have a message/event that must be\n      in that list *)\n  pose proof (fun pl => filterPayloadsIndexComp  \n        MOTOR BASEMOTOR (eLocIndex ev) pl evMn) as Hcomp.\n  unfold priorMotorMesg in Hp.\n  repnd. rewrite Hprl in Hcomp. rewrite Hprr in Hcomp.\n  specialize (Hcomp _ eq_refl eq_refl).\n  lapply Hcomp;[clear Hcomp; intro Hcomp| omega].\n  remember ((filterPayloadsUptoIndex MOTOR \n        (localEvts BASEMOTOR) (eLocIndex ev))) as lf.\n  destruct lf as [ | plev lft ];[inverts Hcomp; fail|].\n  clear Hcomp. simpl in Hm.\n  apply filterPayloadsIndexCorr in Heqlf.\n  repnd.\n  clear Heqlfrrr.\n  assert (eLocIndex (snd plev) <  eLocIndex ev)%nat as Hev by omega.\n  apply timeIndexConsistent in Heqlfrrl.\n  DestImp Hnn;[| eauto using Qlt_trans].\n  unfold correctVelDuring, corrSinceLastVel, lastVelAndTime, \n    velocityMessages, filterPayloadsUptoTime in Hm.\n  destruct Hm as [qt Hm].\n  repnd. clear Hmrr.\n  specialize (Hmrl (eTime ev)). rewrite Hnn in Hmrl.\n  apply evSpacIndex in Hev;[| congruence].\n  assert (eTime (snd plev) + reactionTime <= eTime ev)%Q\n    by (  remember (eTime ev);  remember (eTime evMp); remember (eTime (snd plev)); lra).\n  assert (qt <= eTime ev)%Q as Hqt by \n    eauto using Qle_trans.\n  rewrite Hmrl;\n    [|split; trivial]; apply leEq_reflexive; fail.\nQed.\n\nLemma VelPosAfterLatestNegAux : forall evMp evMn t ev,\n  priorMotorMesg (speed) t evMn\n  -> (latestEvt (priorMotorMesg (-speed) t)) evMp\n  -> (eTime evMp < eTime evMn)%Q\n  -> ((eLocIndex evMn) < eLocIndex ev)%nat\n  -> (eLoc ev = BASEMOTOR)\n  -> (eTime ev < t)%Q\n  -> 1 [<=] {velX tstate}  (eTime ev).\nProof.\n  intros  ? ? ? ? Hp Hl Het Hle Hloc Hevt.\n  pose proof (PosAfterLatestNeg _ _ _ _ Hp Hl Het Hle) as Hnn.\n  simpl. simpl in Hnn.\n  pose proof (corrNodes \n              eo \n              BASEMOTOR  (eTime ev)) as Hm.\n  simpl in Hm.\n  unfold corrSinceLastVel, lastVelAndTime, \n      lastPayloadAndTime, filterPayloadsUptoTime in Hm.\n  rewrite numPrevEvtsEtime in Hm; [| trivial];[].\n    (* we know that \n      the default case of [hd] wont get invoked in Hm\n      Luckily, [initialVel] is correct,\n      but let's not depend on that because\n      we already have a message/event that must be\n      in that list *)\n  pose proof (fun pl => filterPayloadsIndexComp  \n        MOTOR BASEMOTOR (eLocIndex ev) pl evMn) as Hcomp.\n  unfold priorMotorMesg in Hp.\n  repnd. rewrite Hprl in Hcomp. rewrite Hprr in Hcomp.\n  specialize (Hcomp _ eq_refl eq_refl).\n  lapply Hcomp;[clear Hcomp; intro Hcomp| omega].\n  remember ((filterPayloadsUptoIndex MOTOR \n        (localEvts BASEMOTOR) (eLocIndex ev))) as lf.\n  destruct lf as [ | plev lft ];[inverts Hcomp; fail|].\n  clear Hcomp. simpl in Hm.\n  apply filterPayloadsIndexCorr in Heqlf.\n  repnd.\n  clear Heqlfrrr.\n  assert (eLocIndex (snd plev) <  eLocIndex ev)%nat as Hev by omega.\n  apply timeIndexConsistent in Heqlfrrl.\n  DestImp Hnn;[| eauto using Qlt_trans].\n  unfold correctVelDuring, corrSinceLastVel, lastVelAndTime, \n    velocityMessages, filterPayloadsUptoTime in Hm.\n  destruct Hm as [qt Hm].\n  repnd. clear Hmrr.\n  specialize (Hmrl (eTime ev)). rewrite Hnn in Hmrl.\n  apply evSpacIndex in Hev;[| congruence].\n  assert (eTime (snd plev) + reactionTime <= eTime ev)%Q\n    by (  remember (eTime ev);  remember (eTime evMp); remember (eTime (snd plev)); lra).\n  assert (qt <= eTime ev)%Q as Hqt by \n    eauto using Qle_trans.\n  rewrite Hmrl;\n    [|split; trivial]; apply leEq_reflexive; fail.\nQed.\n\nOpen Scope Q_scope.\n\nLemma VelNegAfterLatestPos : forall evMp evMn tunsafe\n    (t : QTime),\n  priorMotorMesg (-speed) tunsafe evMn\n  -> (latestEvt (priorMotorMesg speed tunsafe)) evMp\n  -> (eTime evMp < eTime evMn)%Q\n  -> ((eTime evMn) + reactionTime) <= t <= tunsafe\n  -> ({velX tstate} t [<=] -1).\nClose Scope Q_scope.\nProof.\n  intros  ? ? ? ? Hp Hl Het Hbet.\n  pose proof (corrNodes \n              eo \n              BASEMOTOR t) as Hm.\n  simpl in Hm.\n  unfold corrSinceLastVel, lastVelAndTime, \n      lastPayloadAndTime, filterPayloadsUptoTime in Hm.\n    (* we know that \n      the default case of [hd] wont get invoked in Hm\n      Luckily, [initialVel] is corrent,\n      but let's not depend on that because\n      we already have a message/event that must be\n      in that list *)\n  pose proof (fun pl => filterPayloadsIndexComp  \n        MOTOR BASEMOTOR (numPrevEvts (localEvts BASEMOTOR) t) pl evMn) as Hcomp.\n  pose proof Hp as Hpb.\n  unfold priorMotorMesg in Hp.\n  repnd. rewrite Hprl in Hcomp. rewrite Hprr in Hcomp.\n  specialize (Hcomp _ eq_refl eq_refl).\n  rewrite reactionTime1 in Hbetl. \n  DestImp Hcomp;[|apply numPrevEvtsSpec; trivial; remember (eTime evMn);  remember (eTime evMp); lra].\n\n  remember(filterPayloadsUptoIndex MOTOR (localEvts BASEMOTOR)\n             (numPrevEvts (localEvts BASEMOTOR) t)) as lf.\n  destruct lf as [ | plev lft ];[inverts Hcomp; fail|].\n  inverts Hcomp as; simpl in Hm.\n- intros Hcomp.\n  pose proof (NegAfterLatestPos _ _ _ \n      (numPrevEvts (localEvts BASEMOTOR) t) Hpb Hl Het) as Hnn.\n  rewrite <- Heqlf in Hnn. simpl in Hnn.\n  DestImp Hnn;[|apply numPrevEvtsSpec; trivial;  remember (eTime evMn);  remember (eTime evMp); lra].\n  eapply filterPayloadsIndexSorted in Hcomp; eauto.\n  apply filterPayloadsTimeCorr in Heqlf.\n  rename Heqlf into Hf. repnd. \n  assert (eTime (snd plev) < tunsafe)%Q by  ( remember (eTime evMn);  remember (eTime evMp); \n     remember (eTime (snd plev)); lra).\n  DestImp Hnn;[|trivial;fail].\n  eapply VelNegAfterLatestPosAux in Hcomp; eauto.\n  rewrite Hnn in Hm.\n  revert Hfrrl.\n  revert Hm.\n  revert Hcomp.\n  clear. intros Hv Hm Hlt.\n  unfold correctVelDuring, corrSinceLastVel, lastVelAndTime, \n    velocityMessages, filterPayloadsUptoTime in Hm.\n  destruct Hm as [qt Hm].\n  repnd.\n  pose proof (Qlt_le_dec qt t) as Hdec.\n  apply Qlt_le_weak in Hlt.\n  destruct Hdec as [Hdec | Hdec]; [clear Hmrr|clear Hmrl].\n  + apply Qlt_le_weak in Hdec.\n    rewrite Hmrl; [| split]; auto;[|]; apply leEq_reflexive.\n  + unfold core.between in Hmrr.\n    specialize (Hmrr _ (conj Hlt Hdec)).\n    unfold simpleBetween in Hmrr.\n    repnd.\n    trivial. unfold speed in Hmrrr.\n    unfold Q2R, Z2R , inject_Z in Hmrrr, Hv.\n    revert Hmrrl. simplInjQ.\n    intro Hmrrl.\n    eapply leEq_transitive; eauto.\n    apply Max_leEq; auto.\n    unfold inject_Z.\n    simplInjQ.\n    apply leEq_reflexive.\n- unfold correctVelDuring, corrSinceLastVel, lastVelAndTime, \n    velocityMessages, filterPayloadsUptoTime in Hm.\n  destruct Hm as [qt Hm].\n  repnd. clear Hmrr.\n  specialize (Hmrl t). rewrite reactionTime1 in Hmlr.\n  assert (qt <= t)%Q by lra.\n  rewrite Hmrl;\n    [|split; trivial]; apply leEq_reflexive; fail.\nQed.\n\nOpen Scope Q_scope.\n\nLemma VelPosAfterLatestNeg : forall evMp evMn tunsafe\n    (t : QTime),\n  priorMotorMesg (speed) tunsafe evMn\n  -> (latestEvt (priorMotorMesg (-speed) tunsafe)) evMp\n  -> (eTime evMp < eTime evMn)\n  -> ((eTime evMn) + reactionTime) <= t <= tunsafe\n  -> (Z2R 1 [<=] {velX tstate} t).\nClose Scope Q_scope.\nProof.\n  intros  ? ? ? ? Hp Hl Het Hbet.\n  pose proof (corrNodes \n              eo \n              BASEMOTOR t) as Hm.\n  simpl in Hm.\n  unfold corrSinceLastVel, lastVelAndTime, \n      lastPayloadAndTime, filterPayloadsUptoTime in Hm.\n    (* we know that \n      the default case of [hd] wont get invoked in Hm\n      Luckily, [initialVel] is corrent,\n      but let's not depend on that because\n      we already have a message/event that must be\n      in that list *)\n  pose proof (fun pl => filterPayloadsIndexComp  \n        MOTOR BASEMOTOR (numPrevEvts (localEvts BASEMOTOR) t) pl evMn) as Hcomp.\n  pose proof Hp as Hpb.\n  unfold priorMotorMesg in Hp.\n  repnd. rewrite Hprl in Hcomp. rewrite Hprr in Hcomp.\n  specialize (Hcomp _ eq_refl eq_refl).\n  rewrite reactionTime1 in Hbetl. \n  DestImp Hcomp;[|apply numPrevEvtsSpec; trivial; remember (eTime evMn);  remember (eTime evMp); lra].\n  remember(filterPayloadsUptoIndex MOTOR (localEvts BASEMOTOR)\n             (numPrevEvts (localEvts BASEMOTOR) t)) as lf.\n  destruct lf as [ | plev lft ];[inverts Hcomp; fail|].\n  inverts Hcomp as; simpl in Hm.\n- intros Hcomp.\n  pose proof (PosAfterLatestNeg _ _ _ \n      (numPrevEvts (localEvts BASEMOTOR) t) Hpb Hl Het) as Hnn.\n  rewrite <- Heqlf in Hnn. simpl in Hnn.\n  DestImp Hnn;[|apply numPrevEvtsSpec; trivial; remember (eTime evMn);  remember (eTime evMp); lra].\n  eapply filterPayloadsIndexSorted in Hcomp; eauto.\n  apply filterPayloadsTimeCorr in Heqlf.\n  rename Heqlf into Hf. repnd. \n  assert (eTime (snd plev) < tunsafe)%Q by   ( remember (eTime evMn);  remember (eTime evMp); \n     remember (eTime (snd plev)); lra).\n  DestImp Hnn;[|trivial;fail].\n  eapply VelPosAfterLatestNegAux in Hcomp; eauto.\n  rewrite Hnn in Hm.\n  revert Hfrrl.\n  revert Hm.\n  revert Hcomp.\n  clear. intros Hv Hm Hlt.\n  unfold correctVelDuring, corrSinceLastVel, lastVelAndTime, \n    velocityMessages, filterPayloadsUptoTime in Hm.\n  destruct Hm as [qt Hm].\n  repnd.\n  pose proof (Qlt_le_dec qt t) as Hdec.\n  apply Qlt_le_weak in Hlt.\n  destruct Hdec as [Hdec | Hdec]; [clear Hmrr|clear Hmrl].\n  + apply Qlt_le_weak in Hdec.\n    rewrite Hmrl; [| split]; auto;[|];\n     apply leEq_reflexive.\n  + unfold core.between in Hmrr.\n    specialize (Hmrr _ (conj Hlt Hdec)).\n    unfold simpleBetween in Hmrr.\n    repnd.\n    trivial. unfold speed in Hmrrr.\n    unfold Q2R, Z2R , inject_Z in Hmrrr, Hv.\n    revert Hmrrl. simplInjQ.\n    intro Hmrrl.\n    eapply leEq_transitive;[| apply Hmrrl].\n    apply leEq_Min; auto.\n    unfold inject_Z.\n    apply leEq_reflexive.\n- unfold correctVelDuring, corrSinceLastVel, lastVelAndTime, \n    velocityMessages, filterPayloadsUptoTime in Hm.\n  destruct Hm as [qt Hm].\n  repnd. clear Hmrr.\n  specialize (Hmrl t). rewrite reactionTime1 in Hmlr.\n  assert (qt <= t)%Q by lra.\n  rewrite Hmrl;\n    [|split; trivial]; apply leEq_reflexive; fail.\nQed.\n\n\nLemma RHSSafe : forall t: QTime,  (centerPosAtTime tstate t) [<=]  95.\nProof.\n  intros. apply leEq_def. intros Hc.\n  apply less_leEq in Hc.\n  assert (Z2R 1[<=]centerPosAtTime tstate t) as Hle1 by\n  (eapply leEq_transitive; eauto; unfold Z2R, inject_Z\n    ;apply inj_Q_leEq; simpl;  lra).\n  apply motorLastPosVel in Hle1.\n  destruct Hle1 as [evMp Hlat].\n  pose proof (Hlat) as Hlatb.\n  unfold latestEvt, priorMotorMesg in Hlat. apply proj1 in Hlat.\n  repnd. eapply posVelAtLHS in Hlatrl ; eauto.\n\n  (** Applying IVT *)\n  assert (Z2R (-78) [<] Z2R 95) as H99 by UnfoldLRA.\n  assert (centerPosAtTime tstate (eTime evMp) [<] centerPosAtTime tstate t)\n    as Hlt by eauto 4 with CoRN.\n  clear H99. unfold centerPosAtTime in Hlatrl, Hc.\n  assert (Z2R (-78) [<=] Z2R 86) as H91 by UnfoldLRA.\n  assert (Z2R (86) [<=] Z2R 95) as H92 by UnfoldLRA.\n  apply IVTTimeMinMax with (e:=[1]) (y:=Z2R 86)  in Hlt; simpl; \n    try split; eauto 3 with CoRN;[].\n  clear H91 H92.\n  destruct Hlt as [tivt H99].\n  destruct H99 as [Hclr Habs].\n  simpl in Hclr.\n  destruct Hclr as [Httpp Htppt].\n  rewrite leEq_imp_Min_is_lft in Httpp by\n      (repeat (rewrite <- QT2T_Q2R);\n       apply less_leEq;\n       apply inj_Q_less; simpl; trivial).\n\n  rewrite leEq_imp_Max_is_rht in Htppt by\n      (repeat (rewrite <- QT2T_Q2R);\n       apply less_leEq;\n       apply inj_Q_less; simpl; trivial).\n  \n  pose proof Habs as HUB.\n  rewrite AbsIR_minus in HUB.\n  apply AbsIR_bnd in HUB.\n  apply AbsIR_bnd in Habs.\n  apply shift_minus_leEq in Habs.\n  rename Habs into HLB.\n  unfold Z2R in HLB, HUB.\n  autorewrite with QSimpl in HLB, HUB.\n  revert HLB. simplInjQ. intro HLB.\n  revert HUB. simplInjQ. intro HUB.\n\n  (** Applying IVT finished, we need to know that\n     ([tpp] - [t]) > 8, because 9 sec is enough\n     for corrective action to kick in in the motor.\n    if 8 is not enough, change 95 to sth bigger *)\n\n  rewrite  QT2T_Q2R in Htppt.\n  pose proof (timeDiffLBPosVel _ _ _ _ HUB Hc Htppt) as Htlt.\n  lapply Htlt;[clear Htlt; intros Htlt| UnfoldLRA].\n  revert Htlt. unfold Z2R. simplInjQ.\n  intros Htlt. simpl. \n  repeat (rewrite <- QT2T_Q2R in Htlt).\n  autorewrite with QSimpl in Htlt.\n  apply leEq_inj_Q in Htlt.\n  unfold cg_minus in Htlt.\n  simpl in Htlt.\n\n\n    (* now invoking sensor's spec\n      to get the event that it fired soon after [tivt] *)\n\n  \n  pose proof (corrNodes \n                eo \n                (PROXSENSOR right)) as Hnc.\n\n  simpl in Hnc.\n  apply proj1 in Hnc.\n  specialize (Hnc tivt).\n  unfold rEndPos, rboundary in Hnc.\n  pose proof concreteValues as Hcon.\n\nOpen Scope nat_scope.\n    AndProjN 0 Hcon as Hhw.\n    AndProjN 1 Hcon as Hbb.\n    AndProjN 2 Hcon as Hal.\n    AndProjN 3 Hcon as Hmd.\n    AndProjN 4 Hcon as Hrrrrr.\nClose Scope nat_scope.\n\nCheck VelNegAfterLatestPos.\npose proof VelNegAfterLatestPos as Hvnalpb.\n  subst.\n\n  clear Hcon Hhw Hbb Hal Hmd. \n  unfold Z2R, inject_Z in Hnc.\n  rewrite cag_commutes in Hnc.\n  rewrite CAbGroups.minus_plus in Hnc.\n  lapply Hnc;[clear Hnc;intro Hnc|\n    apply minusSwapLe;\n    eapply leEq_transitive; eauto;\n    unfold Q2R;\n    repeat (rewrite <- inj_Q_minus);\n    apply inj_Q_leEq; unfold cg_minus; simpl;\n        remember (eTime evMp); lra].\n  destruct Hnc as [n Hnc].\n  destruct Hnc as [ev Hnc].\n  repnd.\n  rename ev into Esens.\n  (** got the event generated by the prox sensor.\n      let's count the time towards the deadline *)\n  unfold ProxPossibleTimeEvPair in Hncrr.\n  repnd. simpl in Hncrrlr.\n  rename Hncrrlr  into Htub.\n  (** lets deliver the message to the s/w node *)\n\n\n  pose proof (eventualDelivery eo _ Hncrl) as Hrec.\n  destruct Hrec as [Er  Hrec].\n  repnd.\n  apply locEvtIndex in Hncl.\n  pose proof (SensorOnlySendsToSw _ _ _ \n      Hncrl Hrecrr Hrecl (proj1 Hncl)) as Hsw.\n  unfold PossibleSendRecvPair in Hrecl.\n  pose proof (proj1 Hrecl) as Hmeq.\n  repeat (apply proj2 in Hrecl).\n  rewrite Hsw in Hrecl.\n  rewrite (proj1 Hncl) in Hrecl.\n  simpl in Hrecl.\n  rename Er into Eswr.\n  repnd. rewrite Hncrrr in Hmeq.\n\n  (** got the msg received by sw. lets update the time bounds *)\n\n  assert ((eTime Eswr) < tivt + (2 # 1))%Q  as Htubb by \n    (remember (eTime Eswr);  remember (eTime evMp); lra).\n\n  clear Htub. rename Htubb into Htub.\n  pose proof (globalCausal _ _ _ Hrecrl) as Hubb.\n  assert (tivt < (eTime Eswr))%Q  as Htlb \n    by (remember (eTime Eswr); remember (eTime Esens);  \n        remember (eTime evMp);lra).\n  clear Hubb Hrecl Hncrrr Hncrl Hrecrl Hnclr Hncll Htppt\n      Hncrrll Esens.\n\n  (** lets process the message on the s/w node *)\n   pose proof (corrNodes \n                eo \n                SWCONTROLLER \n                (eLocIndex Eswr)) as Hnc.\n  apply snd in Hnc.\n  pose proof (locEvtIndex SWCONTROLLER (eLocIndex Eswr) Eswr) as Hxx.\n  rewrite (proj1 Hxx) in Hnc;[| split; auto; fail].\n  simpl  in Hnc.\n  specialize (Hnc Hrecrr (0%nat)).\n  destruct Hnc as [m Hnc ]. \n    unfold procOutMsgs.\n    apply proj1 in Hxx.\n    rewrite Hxx; auto.\n    simpl. unfold SwProcess. rewrite getNewProcLPure. simpl.\n    unfold getDeqOutput2, getOutput. simpl.\n    unfold liftToMesg, getPayload.\n    rewrite <- Hmeq.\n    simpl. omega.\n  apply onlyNeededForOldProofs in Hnc.\n  simpl in Hnc. \n  destruct Hnc as [es0 Hnc].\n  destruct Hnc as [ed Hnc].\n  exrepd. rewrite ((proj1 Hxx) (conj Hsw eq_refl)) in e.\n  symmetry in e. inverts e.\n  rename es0 into Esws.\n  simpl in H1, Hmeq. rewrite <- Hmeq in H1.\n  SensorMsgInvert H1. subst dmp.\n  clear Hmeq.\n  rename H2 into Hmot.\n  simpl in Hmot.\n  \n  (** got the msg sent received by sw. \n      lets update the time bounds *)\n\n  assert ((eTime Esws) < tivt + (3 # 1))%Q  as Htubb by \n    (remember (eTime Eswr); remember (eTime Esws);  \n        remember (eTime evMp);lra).\n  clear Htub. rename Htubb into Htub.\n  assert (tivt < (eTime Esws))%Q  as Htlbb by \n    (remember (eTime Eswr); remember (eTime Esws);  \n        remember (eTime evMp);lra).\n  clear Htlb. rename Htlbb into Htlb.\n  rename e0 into Hss.\n  apply locEvtIndex in Hss.\n  clear H0 H l Hrecrr Hxx Hsw a Eswr.\n\n  rename a0 into HmotSend.\n\n  (** let's receive the -speed message on the motor *)\n  \n  pose proof (eventualDelivery eo _ HmotSend) as Hmrec.\n  destruct Hmrec as [Er  Hmrec].\n  repnd. rename Er into Emr.\n  pose proof (SwOnlySendsToMotor _ _ \n      HmotSend Hmrecrr Hmrecl Hssl) as HmotR.\n  unfold PossibleSendRecvPair in Hmrecl.\n  pose proof (proj1 Hmrecl) as Hmeq.\n  repeat (apply proj2 in Hmrecl).\n  rewrite HmotR in Hmrecl.\n  rewrite Hssl in Hmrecl.\n  simpl in Hmrecl.\n  repnd. rewrite <- Hmot in Hmeq.\n  \n    (** got the msg received by sw. lets update the time bounds *)\n\n  rewrite <- QT2T_Q2R in Httpp.\n  apply leEq_inj_Q in Httpp.\n  simpl in Httpp.\n  pose proof (globalCausal _ _ _ Hmrecrl) as Hubb.\n  assert (eTime evMp < eTime Emr)%Q as Hql by \n        (remember (eTime Emr); remember (eTime Esws);  \n        remember (eTime evMp);lra).\n\n  assert ((eTime Emr) < t)%Q as Hlt by \n    (remember (eTime Emr); remember (eTime Esws);  \n        remember (eTime evMp);lra).\n  assert (Qtadd (eTime Emr) (mkQTime 1 I)< tivt + (5 # 1))%Q  \n    as Htubb by (unfold Qtadd; simpl; (remember (eTime Emr); remember (eTime Esws);  \n        remember (eTime evMp);lra)).\n  assert (tivt < Qtadd (eTime Emr) (mkQTime 1 I))%Q  \n    as Htlbb by (unfold Qtadd; simpl; (remember (eTime Emr); remember (eTime Esws);  \n        remember (eTime evMp);lra)).\n  assert (Qtadd (eTime Emr) (mkQTime 1 I) < t)%Q  \n    as Hltt by (unfold Qtadd; simpl; (remember (eTime Emr); remember (eTime Esws);  \n        remember (eTime evMp);lra)).\n  apply (centerPosUB _ _ _ _ (conj Htlbb Htubb)) in HUB.\n  revert HUB. simplInjQ. intro HUB.\n  pose proof (fun tl pm\n      => Hvnalpb evMp Emr t tl pm Hlatb) as Hv.\n  specialize (fun tl pm => Hv tl pm Hql).\n  unfold priorMotorMesg, getRecdPayload, deqMesg in Hv.\n  unfold isRecvEvt, isDeqEvt in Hmrecrr.\n  destruct (eKind Emr); inversion Hmrecrr; [].\n  Local Opaque Q2R.\n  simpl in Hv, Hmeq. \n  simpl in Hv. unfold getPayload in Hv.\n  simpl in Hv. rewrite <- Hmeq in Hv.\n  clear Hql.\n  specialize (fun tl => Hv tl (conj Hlt (conj eq_refl HmotR))).\n  pose proof (QVelPosUB tstate _ _ (Qlt_le_weak _ _ Hltt) (inject_Z (-1))) \n      as Hvb.\n  specialize ( Hvb Hv).\n  clear Hv. unfold centerPosAtTime in HUB.\n  remember ({tstate} (Qtadd (eTime Emr) (mkQTime 1 I))) as qta.\n  unfold Qtadd in Hltt.\n  simpl in Hltt.\n  assert ({tstate} t[-]qta [<=] [0]) as HH0 by\n     (eapply  leEq_transitive; eauto;\n      rewrite <- inj_Q_Zero;\n      apply inj_Q_leEq;\n      simpl; unfold inject_Z; simpl; \n       remember (eTime Emr); remember (eTime Esws); remember (eTime evMp);\n      lra).\n  pose proof (plus_resp_leEq_both _ _ _ _ _ HH0 HUB) as Hf.\n  rewrite <- cg_cancel_mixed in Hf.\n  pose proof (leEq_transitive _ _ _ _ Hc Hf) as XX.\n  rewrite <- inj_Q_Zero in XX.\n  rewrite <- inj_Q_plus in XX.\n  apply leEq_inj_Q in XX.\n  simpl in XX. unfold inject_Z in XX.\n  remember (eTime Emr); remember (eTime Esws); remember (eTime evMp).\n  lra.\nQed.\n\nLemma LHSSafe : forall t: QTime, \n  -95 [<=] (centerPosAtTime tstate t).\nProof.\n  intros. apply leEq_def. intros Hc.\n  apply less_leEq in Hc.\n  assert (centerPosAtTime tstate t[<=]Z2R (-1)) as Hle1 by\n  (eapply leEq_transitive; eauto; unfold Z2R, inject_Z\n    ;apply inj_Q_leEq; simpl;  lra).\n  apply motorLastNegVel in Hle1.\n  destruct Hle1 as [evMp Hlat].\n  pose proof (Hlat) as Hlatb.\n  unfold latestEvt, priorMotorMesg in Hlat. apply proj1 in Hlat.\n  repnd. eapply negVelAtRHS in Hlatrl ; eauto.\n\n  (** Applying IVT *)\n  assert (Z2R (-95) [<] Z2R 78) as H99 by UnfoldLRA.\n  assert (centerPosAtTime tstate t \n        [<] centerPosAtTime tstate (eTime evMp))\n    as Hlt by eauto 4 with CoRN.\n  clear H99. unfold centerPosAtTime in Hlatrl, Hc.\n  assert (Z2R (-86) [<=] Z2R (78)) as H91 by UnfoldLRA.\n  assert (Z2R (-95) [<=] Z2R (-86)) as H92 by UnfoldLRA.\n  apply IVTTimeMinMax with (e:=[1]) (y:=Z2R (-86))  in Hlt; simpl; \n    try split; eauto 3 with CoRN;[].\n  clear H91 H92.\n  destruct Hlt as [tivt H99].\n  destruct H99 as [Hclr Habs].\n  simpl in Hclr.\n  destruct Hclr as [Httpp Htppt].\n  rewrite Min_comm in Httpp.\n  rewrite leEq_imp_Min_is_lft in Httpp by\n      (repeat (rewrite <- QT2T_Q2R);\n       apply less_leEq;\n       apply inj_Q_less; simpl; trivial).\n\n  rewrite Max_comm in Htppt.\n  rewrite leEq_imp_Max_is_rht in Htppt by\n      (repeat (rewrite <- QT2T_Q2R);\n       apply less_leEq;\n       apply inj_Q_less; simpl; trivial).\n  \n  pose proof Habs as HUB.\n  rewrite AbsIR_minus in HUB.\n  apply AbsIR_bnd in HUB.\n  apply AbsIR_bnd in Habs.\n  apply shift_minus_leEq in Habs.\n  rename Habs into HLB.\n  unfold Z2R in HLB, HUB.\n  autorewrite with QSimpl in HLB, HUB.\n  revert HLB. simplInjQ. intro HLB.\n  revert HUB. simplInjQ. intro HUB.\n\n  (** Applying IVT finished, we need to know that\n     ([tpp] - [t]) > 8, because 9 sec is enough\n     for corrective action to kick in in the motor.\n    if 8 is not enough, change 95 to sth bigger *)\n\n  rewrite  QT2T_Q2R in Htppt.\n\n\n  pose proof (timeDiffLBNegVel _ _ _ _ Hc HLB  Htppt) as Htlt.\n  lapply Htlt;[clear Htlt; intros Htlt| UnfoldLRA].\n  revert Htlt. unfold Z2R. simplInjQ.\n  intros Htlt. simpl. \n  repeat (rewrite <- QT2T_Q2R in Htlt).\n  autorewrite with QSimpl in Htlt.\n  apply leEq_inj_Q in Htlt.\n  unfold cg_minus in Htlt.\n  simpl in Htlt.\n\n    (* now invoking sensor's spec\n      to get the event that it fired soon after [tivt] *)\n  \n  pose proof (corrNodes \n                eo \n                (PROXSENSOR left)) as Hnc.\n  simpl in Hnc.\n  apply proj1 in Hnc.\n  specialize (Hnc tivt).\n  unfold lEndPos, lboundary in Hnc.\n  pose proof concreteValues as Hcon.\nOpen Scope nat_scope.\n    AndProjN 0 Hcon as Hhw.\n    AndProjN 1 Hcon as Hbb.\n    AndProjN 2 Hcon as Hal.\n    AndProjN 3 Hcon as Hmd.\n    AndProjN 4 Hcon as Hrrrrr.\nClose Scope nat_scope.\n  subst.\n  clear Hcon Hhw Hbb Hal Hmd. \n  unfold Z2R, inject_Z in Hnc.\n  remember ({tstate} tivt) as tttt.\n  (* wierd error: Error: build_signature: \n      no constraint can apply on a dependent argument*)\n\n  rewrite <- inj_Q_Zero in Hnc.\n  rewrite <- CAbGroups.minus_plus in Hnc.\n  autorewrite with QSimpl in Hnc.\n  revert Hnc. simplInjQ. intros Hnc.\n  DestImp Hnc;[|\n    apply shift_minus_leEq;\n    eapply leEq_transitive; eauto;\n    autorewrite with QSimpl;\n    UnfoldLRA].\n  destruct Hnc as [n Hnc].\n  destruct Hnc as [ev Hnc].\n  repnd.\n  rename ev into Esens.\n  (** got the event generated by the prox sensor.\n      let's count the time towards the deadline *)\n  unfold ProxPossibleTimeEvPair in Hncrr.\n  repnd. simpl in Hncrrlr.\n  rename Hncrrlr  into Htub.\n  (** lets deliver the message to the s/w node *)\n\n  pose proof (eventualDelivery eo  _ Hncrl) as Hrec.\n  destruct Hrec as [Er  Hrec].\n  repnd.\n  apply locEvtIndex in Hncl.\n  pose proof (SensorOnlySendsToSw _ _ _ \n      Hncrl Hrecrr Hrecl (proj1 Hncl)) as Hsw.\n  unfold PossibleSendRecvPair in Hrecl.\n  pose proof (proj1 Hrecl) as Hmeq.\n  repeat (apply proj2 in Hrecl).\n  rewrite Hsw in Hrecl.\n  rewrite (proj1 Hncl) in Hrecl.\n  simpl in Hrecl.\n  rename Er into Eswr.\n  repnd. rewrite Hncrrr in Hmeq.\n\n  (** got the msg received by sw. lets update the time bounds *)\n\n  assert ((eTime Eswr) < tivt + (2 # 1))%Q  as Htubb by lra.\n  clear Htub. rename Htubb into Htub.\n  pose proof (globalCausal _ _ _ Hrecrl) as Hubb.\n  assert (tivt < (eTime Eswr))%Q  as Htlb by lra.\n  clear Hubb Hrecl Hncrrr Hncrl Hrecrl Hnclr Hncll Htppt\n      Hncrrll Esens.\n\n  (** lets process the message on the s/w node *)\n   pose proof (corrNodes \n                eo \n                SWCONTROLLER \n                (eLocIndex Eswr)) as Hnc.\n  apply snd in Hnc.\n  pose proof (locEvtIndex SWCONTROLLER (eLocIndex Eswr) Eswr) as Hxx.\n  rewrite (proj1 Hxx) in Hnc;[| split; auto; fail].\n  simpl  in Hnc.\n  specialize (Hnc Hrecrr (0%nat)).\n  destruct Hnc as [m Hnc ]. \n    unfold procOutMsgs.\n    apply proj1 in Hxx.\n    rewrite Hxx; auto.\n    simpl. unfold SwProcess. rewrite getNewProcLPure. simpl.\n    unfold getDeqOutput2, getOutput. simpl.\n    unfold liftToMesg, getPayload.\n    rewrite <- Hmeq.\n    simpl. omega.\n  apply onlyNeededForOldProofs in Hnc.\n  simpl in Hnc. \n  destruct Hnc as [es0 Hnc].\n  destruct Hnc as [ed Hnc].\n  exrepd. rewrite ((proj1 Hxx) (conj Hsw eq_refl)) in e.\n  symmetry in e. inverts e.\n  rename es0 into Esws.\n  simpl in Hmeq, H1. rewrite <- Hmeq in H1.\n  SensorMsgInvert H1. subst dmp.\n  clear Hmeq.\n  rename H2 into Hmot.\n  simpl in Hmot.\n  \n  (** got the msg sent received by sw. \n      lets update the time bounds *)\n\n  assert ((eTime Esws) < tivt + (3 # 1))%Q  as Htubb by lra.\n  clear Htub. rename Htubb into Htub.\n  assert (tivt < (eTime Esws))%Q  as Htlbb by lra.\n  clear Htlb. rename Htlbb into Htlb.\n  rename e0 into Hss.\n  apply locEvtIndex in Hss.\n  clear H0 H a l Hrecrr Hxx Hsw Eswr.\n\n  rename a0 into HmotSend.\n\n  (** let's receive the -speed message on the motor *)\n  \n  pose proof (eventualDelivery eo  _ HmotSend) as Hmrec.\n  destruct Hmrec as [Er  Hmrec].\n  repnd. rename Er into Emr.\n  pose proof (SwOnlySendsToMotor _ _ \n      HmotSend Hmrecrr Hmrecl Hssl) as HmotR.\n  unfold PossibleSendRecvPair in Hmrecl.\n  pose proof (proj1 Hmrecl) as Hmeq.\n  repeat (apply proj2 in Hmrecl).\n  rewrite HmotR in Hmrecl.\n  rewrite Hssl in Hmrecl.\n  simpl in Hmrecl.\n  repnd. rewrite <- Hmot in Hmeq.\n  \n    (** got the msg received by sw. lets update the time bounds *)\n\n  rewrite <- QT2T_Q2R in Httpp.\n  apply leEq_inj_Q in Httpp.\n  simpl in Httpp.\n  pose proof (globalCausal _ _ _ Hmrecrl) as Hubb.\n  assert (eTime evMp < eTime Emr)%Q as Hql by lra.\n  assert ((eTime Emr) < t)%Q as Hlt by lra.\n  assert (Qtadd (eTime Emr) (mkQTime 1 I)< tivt + (5 # 1))%Q  \n    as Htubb by (unfold Qtadd; simpl; lra).\n  assert (tivt < Qtadd (eTime Emr) (mkQTime 1 I))%Q  \n    as Htlbb by (unfold Qtadd; simpl; lra).\n  assert (Qtadd (eTime Emr) (mkQTime 1 I) < t)%Q  \n    as Hltt by (unfold Qtadd; simpl; lra).\n  clear dependent Esws.\n  subst tttt.\n  apply (centerPosLB _ _ _ _ (conj Htlbb Htubb)) in HLB.\n  revert HLB. simplInjQ. intro HLB.\n  pose proof (fun tl pm\n      => VelPosAfterLatestNeg evMp Emr t tl pm Hlatb) as Hv.\n  specialize (fun tl pm => Hv tl pm Hql).\n  unfold priorMotorMesg, getRecdPayload, deqMesg in Hv.\n  unfold isRecvEvt, isDeqEvt in Hmrecrr.\n  destruct (eKind Emr); inversion Hmrecrr; [].\n  simpl in Hv, Hmeq. unfold getPayload in Hv.\n  simpl in Hv. simpl in Hmeq. \n  rewrite <- Hmeq in Hv.\n  simpl in Hv.\n  clear Hql.\n  specialize (fun tl => Hv tl (conj Hlt (conj eq_refl HmotR))).\n  pose proof (QVelPosLB tstate _ _ (Qlt_le_weak _ _ Hltt) \n                                (inject_Z (1))) \n      as Hvb.\n  rewrite reactionTime1 in Hv.\n  specialize ( Hvb Hv).\n  clear Hv. unfold centerPosAtTime in HLB.\n  remember ({tstate} (Qtadd (eTime Emr) (mkQTime 1 I))) as qta.\n  unfold Qtadd in Hltt.\n  simpl in Hltt.\n  assert ( [0] [<=] {tstate} t[-]qta) as HH0 by\n     (eapply  leEq_transitive; eauto;\n      rewrite <- inj_Q_Zero;\n      apply inj_Q_leEq;\n      simpl; unfold inject_Z; simpl; lra).\n  pose proof (plus_resp_leEq_both _ _ _ _ _ HH0 HLB) as Hf.\n  rewrite <- cg_cancel_mixed in Hf.\n  pose proof (leEq_transitive _ _ _ _ Hf Hc) as XX.\n  rewrite <- inj_Q_Zero in XX.\n  rewrite <- inj_Q_plus in XX.\n  apply leEq_inj_Q in XX.\n  simpl in XX. unfold inject_Z in XX.\n  lra.\nQed.\n\n\nCoercion Z2R : Z >-> st_car.\n\nLemma TrainSafe : \n    forall t: Time,  |(centerPosAtTime tstate t)| [<=] 95.\nProof.\n  intros.\n  apply AbsSmall_imp_AbsIR.\n  split.\n- apply TContRR2QLB. intro qt. unfold Z2R. rewrite <- inj_Q_inv.\n  apply LHSSafe.\n- apply TContRR2QUB.\n  exact RHSSafe.\nQed.\n\n\n\n\nEnd TrainProofs.", "meta": {"author": "aa755", "repo": "ROSCoq", "sha": "bb71cdf642fce1ab2f129c833db7a6c358965313", "save_path": "github-repos/coq/aa755-ROSCoq", "path": "github-repos/coq/aa755-ROSCoq/ROSCoq-bb71cdf642fce1ab2f129c833db7a6c358965313/examples/train.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2541561568726298}}
{"text": "(* En este archivo se demuestra la corrección de la acción read *)\nRequire Export Exec.\nRequire Export Implementacion.\nRequire Export AuxFunsCorrect.\nRequire Import Classical.\nRequire Import Estado.\nRequire Import DefBasicas.\nRequire Import Semantica.\nRequire Import Operaciones.\nRequire Import ErrorManagement.\nRequire Import Maps.\nRequire Import Tacticas.\nRequire Import ValidStateLemmas.\n\nSection Read.\n\n\nLemma readCorrect : forall (s:System) (i:iCmp) (c:CProvider) (u:uri), (pre (read i c u) s) -> validstate s -> post_read i c u s (read_post i c u s).\nProof.\n    intros.\n    unfold post_read.\n    unfold read_post.\n    auto.\nQed.\n\nLemma notPreReadThenError : forall (s:System) (i:iCmp) (c:CProvider) (u:uri), ~(pre (read i c u) s) -> validstate s -> exists ec : ErrorCode, response (step s (read i c u)) = error ec /\\ ErrorMsg s (read i c u) ec /\\ s = system (step s (read i c u)).\nProof.\n    intros.\n    simpl.\n    simpl in H.\n    unfold pre_read in H.\n    unfold read_safe.\n    unfold read_pre.\n    case_eq (negb (existsResBool c u s));intros.\n    exists no_such_res.\n    split;auto.\n    split;auto.\n    rewrite negb_true_iff in H1.\n    invertBool H1.\n    intro;apply H1.\n    apply existsRes_iff;auto. \n    case_eq (map_apply iCmp_eq (running (state s)) i);intros.\n    case_eq ((canReadBool c0 c s || delPermsBool c0 c u Read s));intros.\n    destruct H.\n    split.\n    rewrite negb_false_iff in H1.\n    apply existsRes_iff;auto. \n    exists c0.\n    split;auto.\n    rewrite orb_true_iff in H3.\n    destruct H3.\n    left.\n    unfold canReadBool in H.\n    unfold canRead.\n    apply canDoThisBoolCorrect;auto.\n    right.\n    apply delPermsBoolCorrect;auto.\n\n    exists not_enough_permissions.\n    split;auto.\n    split;auto.\n    exists c0.\n    split;auto.\n    invertBool H3.\n    intro;apply H3.\n    rewrite orb_true_iff.\n    destruct H4.\n    left.\n    unfold canReadBool.\n    unfold canRead in H4.\n    apply canDoThisBoolCorrect;auto.\n    right.\n    apply delPermsBoolCorrect;auto.\n    \n    exists instance_not_running.\n    split;auto.\n\nQed.\n\nLemma readIsSound : forall (s:System) (i:iCmp) (c:CProvider) (u:uri),\n        validstate s -> exec s (read i c u) (system (step s (read i c u))) (response (step s (read i c u))).\nProof.\n    \n    intros.\n    unfold exec.\n    split.\n    auto.\n    elim (classic (pre (read i c u) s));intro.\n    left.\n    assert(read_pre i c u s = None).\n    unfold read_pre.\n    destruct H0.\n    destruct H1.\n    destruct_conj H1.\n    assert (negb (existsResBool c u s)=false).\n    rewrite negb_false_iff.\n    apply existsRes_iff;auto.\n    rewrite H1.\n    \n    assert (canReadBool x c s || delPermsBool x c u Read s = true).\n    rewrite orb_true_iff.\n    destruct H3.\n    left.\n    unfold canRead in H3.\n    unfold canReadBool.\n    apply canDoThisBoolCorrect; auto.\n    right.\n    apply delPermsBoolCorrect; auto.\n    \n    rewrite H2.\n    rewrite H4.\n    auto.\n    \n    \n    \n    unfold step;simpl.\n    unfold read_safe;simpl.\n    rewrite H1;simpl.\n    split;auto.\n    split;auto.\n    apply readCorrect;auto.\n    right.\n    apply notPreReadThenError;auto.\n    \nQed.\nEnd Read.\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/ReadIsSound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.2539230496800786}}
{"text": "From Coq Require Import RelationClasses Morphisms Utf8.\n\nFrom Mon Require Import SPropMonadicStructures SpecificationMonads MonadExamples\n  SPropBase FiniteProbabilities.\n\nFrom Relational Require Import OrderEnrichedCategory\n  OrderEnrichedRelativeMonadExamples Commutativity GenericRulesSimple.\n\nSet Warnings \"-notation-overridden,-ambiguous-paths\".\nFrom mathcomp Require Import all_ssreflect all_algebra reals distr realsum\n  finmap.set finmap.finmap xfinmap.\nSet Warnings \"notation-overridden,ambiguous-paths\".\n\nFrom Crypt Require Import Axioms ChoiceAsOrd SubDistr Couplings Theta_dens\n  Theta_exCP LaxComp FreeProbProg RelativeMonadMorph_prod\n  StateTransformingLaxMorph chUniverse.\n\nImport SPropNotations.\nImport Num.Theory.\n\n\n#[local] Open Scope ring_scope.\n\n#[local] Definition ops_StP (S : choiceType) :=\n  @ops_StP S.\n\n#[local] Definition ar_StP (S : choiceType) :=\n  @ar_StP S.\n\n(* free monad *)\nDefinition FrStP (S : choiceType) :=\n  @FrStP S.\n\n#[local] Definition pure {S : choiceType} {A : ord_choiceType} (a : A) :=\n  ord_relmon_unit (FrStP S) A a.\n\n#[local] Definition bindF {S : choiceType} {A B : ord_choiceType}\n  (f : TypeCat ⦅ choice_incl A; FrStP S B ⦆ ) (m : FrStP S A) :=\n  ord_relmon_bind (FrStP S) f m.\n\nDefinition retF {S : choiceType} {A : choiceType} (a : A) :=\n  retrFree (ops_StP S) (ar_StP S) A a.\n\n\n(* morphism *)\nDefinition θ {S1 S2 : choiceType} :=\n  @thetaFstdex S1 S2.\n\nDefinition θ0 {S : choiceType} {A : ord_choiceType} (c : FrStP S A) :=\n  @unaryIntState S A c.\n\n\n(* spec monad *)\n#[local] Definition WrelSt {S1 S2 : choiceType} :=\n  rlmm_codomain (@θ S1 S2).\n\n\n(* Rem.: this spec monad is a ordered relative monad, while previously we were using an ordered monad *)\n\nDefinition retW {A1 A2 : ord_choiceType} {S1 S2 : choiceType} (a : A1 * A2) :\n  Base.dfst (@WrelSt S1 S2 ⟨ A1, A2 ⟩).\nProof.\n  apply (ord_relmon_unit WrelSt).\n  simpl.\n  exact: a.\nDefined.\n\n\nDefinition bindW {A1 A2 B1 B2 : ord_choiceType} {S1 S2 : choiceType}\n  (w : Base.dfst (@WrelSt S1 S2 ⟨ A1, A2 ⟩))\n  (f : A1 * A2 → Base.dfst (@WrelSt S1 S2 ⟨ B1, B2 ⟩)) :\n  Base.dfst (@WrelSt S1 S2 ⟨ B1, B2 ⟩).\nProof.\n  unshelve eapply (ord_relmon_bind WrelSt).\n  - simpl. exact: npair A1 A2.\n  - simpl.\n    exists f.\n    move => [a1 a2] [b1 b2] Hleq.\n    inversion Hleq.\n    by move => [s1 s2] π H.\n  - exact: w.\nDefined.\n\nImport OrderEnrichedRelativeMonadExamplesNotation.\n\nDefinition semantic_judgement (A1 A2 : ord_choiceType) {S1 S2 : choiceType}\n  (c1 : FrStP S1 A1) (c2 : FrStP S2 A2)\n  (w  : Base.dfst (WrelSt ⟨ A1, A2 ⟩)) : Prop :=\n   (θ ⟨A1,A2⟩)∙1 ⟨c1,c2⟩ ≤ w.\n\nDefinition fromPrePost {A1 A2 : ord_choiceType} {S1 S2: choiceType}\n  (pre : (S1 * S2) → Prop)\n  (post : (A1 * S1) → (A2 * S2) → Prop) :\n  Base.dfst (@WrelSt S1 S2 ⟨ A1, A2 ⟩).\nProof.\n  simpl.\n  unshelve econstructor.\n  move=> [is1 is2]. unshelve econstructor.\n  move=> myPost.\n  exact (\n    pre (is1,is2) ∧\n    ∀ as1 as2, (post as1 as2) → myPost (as1, as2)\n  ).\n  move => x y Hxy [H1 H2].\n  split.\n  - assumption.\n  - move => as1 as2 post12. apply: Hxy. by apply: H2.\n  move => x y Heq π.\n  by rewrite Heq.\nDefined.\n\nDeclare Scope rsemantic_scope.\nDelimit Scope rsemantic_scope with rsem.\n\nModule RSemanticNotation.\n\n  Notation \"⊨ c1 ≈ c2 [{ w }]\" :=\n    (semantic_judgement _ _ c1 c2 w) : rsemantic_scope.\n\n  Notation \"⊨ ⦃ pre ⦄ c1 ≈ c2 ⦃ post ⦄\" :=\n    (semantic_judgement _ _ c1 c2 (fromPrePost pre post))\n    : rsemantic_scope.\n\nEnd RSemanticNotation.\n\nImport RSemanticNotation.\n#[local] Open Scope rsemantic_scope.\n\nImport finmap.set finmap.finmap xfinmap.\n\nOpen Scope fset_scope.\n\nDefinition d_inv {A1 A2 : choiceType} (d : SDistr  (F_choice_prod ⟨ A1, A2 ⟩)) :\n  SDistr  (F_choice_prod ⟨ A2, A1 ⟩) :=\n  dswap d.\n\nLemma d_inv_coupling {A1 A2} {c1 : SDistr A1} {c2 : SDistr A2}\n  (d : SDistr (F_choice_prod ⟨ A1, A2 ⟩ )) (d_coupling : coupling d c1 c2) :\n  coupling (d_inv d) c2 c1.\nProof.\n  unfold coupling. split.\n  - unfold lmg. unfold d_inv.\n    apply distr_ext. move=> x. erewrite (dfst_dswap d).\n    destruct d_coupling as [lH rH]. rewrite -rH. unfold rmg. reflexivity.\n  - unfold rmg. unfold d_inv.\n    apply distr_ext. move=> x. erewrite (dsnd_dswap d).\n    destruct d_coupling as [lH rH]. rewrite -lH. unfold lmg. reflexivity.\nQed.\n\nTheorem inv_rule {A1 A2 : ord_choiceType} {S1 S2 : choiceType} {P Q}\n  (c1 : FrStP S1 A1) (c2 : FrStP S2 A2)\n  (H : ⊨ ⦃ P ⦄ c1 ≈ c2 ⦃ Q ⦄ ) :\n  ⊨ ⦃ λ '(st1,st2), P (st2, st1) ⦄ c2 ≈ c1 ⦃ λ as1 as2, Q as2 as1 ⦄.\nProof.\n  move => [st1 st2] /=. move => π [H1 H2] /=.\n  specialize (H (st2, st1) (fun '(as1, as2) => π (as2, as1))).\n  simpl in H.\n  destruct H as [d [d_coupling Hd]].\n  split; auto.\n  exists  (@d_inv _ _ d).\n  split.\n  by apply: d_inv_coupling.\n  move => as2 as1 H'.\n  apply: Hd.\n  rewrite /d_inv /= in H'. destruct d. simpl in *.\n  rewrite dswapE in H'. cbn in H'. assumption.\nQed.\n\n(* GENERIC MONADIC RULES *)\nTheorem ret_rule  {A1 A2 : ord_choiceType} {S1 S2 : choiceType}\n  (a1 : A1) (a2 : A2):\n  ⊨ @pure S1 A1 a1 ≈ @pure S2 A2 a2  [{ retW (a1, a2) }].\nProof.\n  rewrite /semantic_judgement /θ.\n  unfold \"≤\". simpl.\n  rewrite /MonoCont_order //=. move => [ss1 ss2] πa1a2 /=.\n  exists (SDistr_unit (F_choice_prod (npair (prod_choiceType A1 S1) (prod_choiceType A2 S2)))\n                 ((a1, ss1), (a2, ss2))).\n  split.\n  - rewrite /SubDistr.SDistr_obligation_1 /=.\n    by apply SDistr_unit_F_choice_prod_coupling.\n  - move => b1 b2 Hb1b2 /=.\n    by rewrite -(distr_get _ _ Hb1b2).\nQed.\n\nTheorem weaken_rule  {A1 A2 : ord_choiceType} {S1 S2 : choiceType}\n  {d1 : FrStP S1 A1}\n  {d2 : FrStP S2 A2} :\n  ∀ w w', (⊨ d1 ≈ d2 [{ w }]) → w ≤ w' → (⊨ d1 ≈ d2 [{ w' }] ).\nProof.\n  rewrite /semantic_judgement.\n  by etransitivity.\nQed.\n\nTheorem bind_rule {A1 A2 B1 B2 : ord_choiceType} {S1 S2 : choiceType}\n  {f1 : A1 → FrStP S1 B1}\n  {f2 : A2 → FrStP S2 B2}\n  (m1 : FrStP S1 A1)\n  (m2 : FrStP S2 A2)\n  (wm : Base.dfst (WrelSt ⟨ A1, A2 ⟩))\n  (judge_wm : ⊨ m1 ≈ m2 [{ wm }])\n  (wf : (A1 * A2) → Base.dfst (WrelSt ⟨ B1, B2 ⟩))\n  (judge_wf : ∀ a1 a2, ⊨ (f1 a1) ≈ (f2 a2) [{ (wf (a1, a2)) }]) :\n  ⊨ (bindF f1 m1 ) ≈ (bindF f2 m2) [{ bindW wm wf }].\nProof.\n  move => [st1 st2].\n  etransitivity.\n  rewrite /bindF /=.\n    by apply (rlmm_law2 _ _ _ _ θ ⟨ A1, A2 ⟩ ⟨ B1, B2 ⟩ ⟨ f1 , f2 ⟩ ⟨ m1 , m2 ⟩ (st1, st2)).\n    rewrite /semantic_judgement in judge_wm, judge_wf.\n  destruct A1 as [A1 chA1]. destruct A2 as [A2 chA2].\n  destruct B1 as [B1 chB1]. destruct B2 as [B2 chB2].\n  simpl in *.\n  apply (@omon_bind WProp (A1 * S1 * (A2 * S2)) (B1 * S1 * (B2 * S2)) _ _ (judge_wm (st1, st2))).\n  move => [[a1 st1'] [a2 st2']].\n  by apply: (judge_wf a1 a2).\nQed.\n\nTheorem bind_rule_pp {A1 A2 B1 B2 : ord_choiceType}  {S1 S2 : choiceType}\n  {f1 : A1 → FrStP S1 B1}\n  {f2 : A2 → FrStP S2 B2}\n  (m1 : FrStP S1 A1)\n  (m2 : FrStP S2 A2)\n  (pre : S1 * S2 → Prop)\n  (middle : (A1 * S1) → (A2 * S2) → Prop)\n  (post : (B1 * S1) → (B2 * S2) → Prop)\n  (judge_wm : ⊨ ⦃ pre ⦄ m1 ≈ m2 ⦃ middle ⦄)\n  (judge_wf : ∀ a1 a2,\n      ⊨ ⦃ λ '(s1, s2), middle (a1, s1) (a2, s2) ⦄\n        f1 a1 ≈ f2 a2\n        ⦃ post ⦄ ) :\n  ⊨ ⦃ pre ⦄ (bindrFree _ _ m1 f1 ) ≈ (bindrFree _ _ m2 f2) ⦃ post ⦄.\nProof.\n  destruct S1, S2, A1, A2, B1, B2.\n  eapply weaken_rule.\n  - apply bind_rule with (wf := (fun '(a1, a2) => fromPrePost (fun '(s1, s2) => middle (a1, s1) (a2, s2)) post)).\n    + exact judge_wm.\n    + exact judge_wf.\n  - cbv. intuition.\nQed.\n\n(* Pre-condition manipulating rules *)\nTheorem pre_weaken_rule {A1 A2 : ord_choiceType} {S1 S2 : choiceType}\n  {d1 : FrStP S1 A1}\n  {d2 : FrStP S2 A2} :\n  ∀ (pre pre' : S1 * S2 → Prop) post,\n    (⊨ ⦃ pre ⦄ d1 ≈ d2 ⦃ post ⦄) →\n    (∀ st1 st2, pre' (st1, st2) → pre (st1, st2) ) →\n    (⊨ ⦃ pre' ⦄ d1 ≈ d2 ⦃ post ⦄).\nProof.\n  move => w w' post Hjudg Hleq. move => [st1 st2].\n  move => π [H1 H2]. simpl in π.\n  apply: Hjudg.\n  rewrite /fromPrePost /=.\n  split.\n  - by apply: Hleq.\n  - assumption.\nQed.\n\nTheorem pre_hypothesis_rule  {A1 A2 : ord_choiceType} {S1 S2 : choiceType}\n  {d1 : FrStP S1 A1}\n  {d2 : FrStP S2 A2} :\n  ∀ (pre : S1 * S2 → Prop) post,\n    (∀ st1 st2,\n      pre (st1, st2) →\n      ⊨ ⦃ (λ st, st.1 = st1 ∧ st.2 = st2 ) ⦄ d1 ≈ d2 ⦃ post ⦄\n    ) →\n    (⊨ ⦃ pre ⦄ d1 ≈ d2 ⦃ post ⦄).\nProof.\n  move => pre post Hjudg. move => [st1 st2].\n  move => π [H1 H2] /=. simpl in π.\n  apply: (Hjudg st1 st2 H1 (st1, st2)).\n  by rewrite /fromPrePost /=.\nQed.\n\nTheorem pre_strong_hypothesis_rule  {A1 A2 : ord_choiceType} {S1 S2 : choiceType}\n                             {d1 : FrStP S1 A1}\n                             {d2 : FrStP S2 A2} :\n  forall (pre : S1 * S2 -> Prop) post, (forall st1 st2, pre (st1, st2)) -> (⊨ ⦃ (fun st => True ) ⦄ d1 ≈ d2 ⦃ post ⦄) ->\n                              (⊨ ⦃ pre ⦄ d1 ≈ d2 ⦃ post ⦄).\nProof.\n  move => pre post Hpre Hjudg.\n  by apply (pre_weaken_rule (fun st => True) _).\nQed.\n\n(* Rem.: took around 40s to Qed. *)\n(* post-condition manipulating rules *)\n(* Rem.: simplified the proof resorting to weaken_rule, should be quickier *)\nTheorem post_weaken_rule  {A1 A2 : ord_choiceType} {S1 S2 : choiceType}\n                          {d1 : FrStP S1 A1}\n                          {d2 : FrStP S2 A2} :\n    forall (pre : S1 * S2 -> Prop) (post1 post2 : A1 * S1 -> A2 * S2 -> Prop),\n    (⊨ ⦃ pre ⦄ d1 ≈ d2 ⦃ post1 ⦄) ->\n    (forall as1 as2, post1 as1 as2 -> post2 as1 as2) -> (⊨ ⦃ pre ⦄ d1 ≈ d2 ⦃ post2 ⦄).\nProof.\n  move => pre post1 post2 Hjudg Hleq.\n  eapply weaken_rule.\n  - exact Hjudg.\n  - cbv. intuition.\nQed.\n\nDeclare Scope RulesStateProb_scope.\nDelimit Scope RulesStateProb_scope with RSP.\n\nModule RSPNotation.\n\n  Notation \"x <- c1 ;; c2\" :=\n    (bindF (fun x => c2) c1)\n    (right associativity, at level 84, c1 at next level)\n    : RulesStateProb_scope.\n\n  Notation \" x ∈ T <<- c1 ;; c2 \" :=\n    (bindF (fun x : T => c2) c1)\n    (right associativity, at level 90, c1 at next level)\n    : RulesStateProb_scope.\n\n  Notation \"c1 ;; c2\" :=\n    (bindF (fun _ => c2) c1)\n    (at level 100, right associativity)\n    : RulesStateProb_scope.\n\nEnd RSPNotation.\n\nImport RSPNotation.\nOpen Scope RulesStateProb_scope.\n\nTheorem seq_rule  { A1 A2 : ord_choiceType }\n                  { B1 B2 : ord_choiceType }\n                  {S1 S2 : choiceType}\n                  {f1 : A1 -> FrStP S1 B1}\n                  {f2 : A2 -> FrStP S2 B2}\n                  (m1 : FrStP S1 A1) (m2 : FrStP S2 A2)\n                  (P : S1 * S2 -> Prop) (R : A1 * S1 -> A2 * S2 -> Prop)\n                  (Q : B1 * S1 -> B2 * S2 -> Prop)\n                  (judge1 : ⊨ ⦃ P ⦄ m1 ≈ m2 ⦃ R ⦄ )\n                  (judge2 : forall a1 a2, ⊨ ⦃ (fun st => R (a1, st.1) (a2, st.2)) ⦄ (f1 a1) ≈ (f2 a2) ⦃ Q ⦄ ) :\n ⊨ ⦃ P ⦄  x ∈ A1 <<- m1 ;; f1 x ≈  x ∈ A2 <<- m2 ;; f2 x  ⦃ Q ⦄.\nProof.\n  have H :  ⊨ x ∈ A1 <<- m1;; f1 x ≈ x ∈ A2 <<- m2;; f2 x\n      [{bindW (fromPrePost P R) (fun a : A1 * A2 => fromPrePost (fun st : S1 * S2 => R (a.1, st.1) (a.2, st.2)) Q)}]\n    := (bind_rule m1 m2 (fromPrePost P R) judge1\n                      (fun a => fromPrePost (fun st => R (a.1, st.1) (a.2, st.2)) Q) judge2).\n  rewrite /fromPrePost.\n  move => [st1 st2] /=.\n  move => β [Hbeta1 Hbeta2].\n  specialize (H (st1, st2) β). simpl in H. destruct H as [HH1 [HH2 HH2']].\n  split; auto. rewrite /fromPrePost in judge2.\n  move => [a1 sst1] [a2 sst2] HR.\n  specialize (judge2 a1 a2).\n  split; assumption.\n  exists HH1.\n  split; assumption.\nQed.\n\n\n(* Rem.: can we do \\sum_ ( c \\in C ) ... where C : choiceType? *)\nDefinition prod_comp { L R } { M : finType } { d1 : SDistr L } {d2 : SDistr M } { d3 : SDistr R } d12 d23\n           ( H12 : coupling d12 d1 d2 ) ( H23 : coupling d23 d2 d3 ): SDistr (F_choice_prod ⟨ L,  R ⟩).\nProof.\n  exists (fun '(l, r) => \\sum_ ( m <- (index_enum M) | m \\in (dinsupp d2) ) (d12 (l,m) * d23 (m,r)) / (d2 m)).\n  - admit.\n  - admit.\n  - admit.\nAdmitted.\n\n\nDefinition prod_comp_coupling { L R } { M : finType} { d1 : SDistr L } {d2 : SDistr M } { d3 : SDistr R }\n           { d12 d23 } (H12 : coupling d12 d1 d2) (H23 : coupling d23 d2 d3):\n coupling (@prod_comp L R M d1 d2 d3 d12 d23 H12 H23) d1 d3.\nProof. Admitted.\n\n(* useful to introduce intermediate games [Formal Certification of Code-Based Cryptographic Proofs, page 24] *)\nTheorem comp_rule { A1 A3 : ord_choiceType } { A2 S2 : finType } { S1 S3 : choiceType }\n                  { P P' } { Q Q'}\n                  (c1 : FrStP S1 A1) (c2 : FrStP S2 A2) (c3 : FrStP S3 A3)\n                  (H12 : ⊨ ⦃ P ⦄ c1 ≈ c2 ⦃ Q ⦄)\n                  (H23 : ⊨ ⦃ P' ⦄ c2 ≈ c3 ⦃ Q' ⦄) :\n  ⊨ ⦃ fun '(s1, s3) => exists s2, P(s1,s2) /\\ P'(s2,s3) ⦄\n    c1 ≈ c3\n    ⦃ fun as1 as3 => exists as2, Q as1 as2 /\\ Q' as2 as3⦄.\nProof.\n  move => [s1 s3].\n  move => π. simpl in π.\n  rewrite /fromPrePost /=. move => [[s2 [HP HP']] H].\n  specialize (H12 (s1, s2) (fun '(as1, as2) => forall as3, Q' as2 as3 -> π (as1, as3)) ). simpl in H12.\n  destruct H12 as [d12 [coupling12 H12]].\n  { split.\n    assumption.\n    move => as1 as2 HQ as3 HQ'.\n    apply: (H as1 as3).\n    exists as2. split; assumption. }\n  specialize (H23 (s2, s3) (fun '(as2, as3) => forall as1, Q as1 as2 ->  π (as1, as3)) ). simpl in H23.\n  destruct H23 as [d23 [coupling23 H23]].\n  { split.\n    assumption.\n    move => as2 as3 HQ as1 HQ'.\n    apply: (H as1 as3).\n    exists as2. split; assumption. }\n  pose d13 := prod_comp d12 d23 coupling12 coupling23.\n  exists d13.\n  split.\n    by apply: prod_comp_coupling.\n    move => as1 as3 d13_gt0.\n    apply: (H as1 as3).\n    (* by definition of d13*) admit.\nAdmitted.\n\n\n(* Lemma bij_pres_summable { A B: choiceType } { d : A -> R } { f : A -> B }  {finv : B -> A } *)\n(*       (kinvf  : cancel finv f) (kfinv : cancel f finv) ( H: summable (T:= A) (R:=R) d): *)\n(*   summable (T:=B) (R:=R) (fun b : B => d (finv b)). *)\n(* Admitted.  *)\n\n(*CA: not used  *)\nDefinition d__f { A B : ord_choiceType} { d : SDistr A } { f : A -> B } : SDistr  B. Admitted.\n(*CA's proof sketch\n  d__f : B -> [0,1]\n\n         b ↦ ∑_{a ∈ A: f(a) = b} d(a)  // d-measure of the pre-image of b -- in particular if b is not in image(f) then d__f(b) = 0 //\n\n\n  - 0 ≤ d__f (b) because sum of non-negative quantities\n  - for J ⊆ B, d__f (J) = d (f^-1 (J)) that is finite\n  - ∑_{b ∈ B} d__f(b) = ∑_{a ∈ A} d(a)\n\n *)\n\n\n(* CA: old proof for a bijective f *)\n(* Proof. *)\n(*   destruct d as [d Hd1 Hd2 Hd3]. *)\n(*   unshelve eexists.  *)\n(*   { move => b. exact: d (finv b). }  *)\n(*   - move => b /=.  by apply: Hd1.  *)\n(*   - by apply: bij_pres_summable.  *)\n(*   - unshelve erewrite <- reindex_psum. *)\n(*     { apply: predT. }  *)\n(*     assumption. *)\n(*       by []. *)\n(*       exists f. *)\n(*    -- move => x H. apply: kinvf. *)\n(*    -- move => x H. apply: kfinv. *)\n(* Defined.  *)\n\n(*CA: not used *)\nTheorem post_conclusion_rule {A0 A1 B : ord_choiceType} { S : choiceType } { pre : S * S -> Prop }\n        {c0 : FrStP S A0 } { c1 : FrStP S A1 }\n        { f0 : A0 -> B } { f1 : A1 -> B } (* (Hbij0 : bijective f0) (Hbij1 : bijective f1) *)\n        (H : ⊨ ⦃ pre ⦄\n               (x0 <- c0 ;; retF x0) ≈\n               (x1 <- c1 ;; retF x1)\n               ⦃ fun '(a0, s0) '(a1, s1) => s0 = s1 /\\ f0 a0 = f1 a1 ⦄) :\n  ⊨ ⦃ pre ⦄ x0 <- c0 ;; retF (f0 x0) ≈ x1 <- c1 ;; retF (f1 x1) ⦃ eq ⦄.\nProof.\n  move => [s0 s1].\n  specialize (H (s0, s1)).\n  unfold \"≤\" in *. simpl. simpl in H.\n  rewrite /MonoCont_order //=. rewrite /MonoCont_order //= in H.\n  move => β [hs0 h].\n  specialize (H (fun '(a0, s0, (a1, s1)) => (β (f0 a0 ,s0, (f1 a1, s1))))).\n  destruct H as [d [H H']].\n  split.\n  - assumption.\n  - move => [a1 st1] [a2 st2] [Heqa Heqst]. subst.\n    apply: h. by rewrite Heqst.\n  - unshelve eexists.\n    { unshelve eapply d__f.\n      exact: F_choice_prod ⟨ F_choice_prod ⟨ A0, S ⟩, F_choice_prod ⟨ A1, S ⟩ ⟩.\n      exact: d.\n      move => [[a0 st0] [a1 st1]]. exact: (f0 a0, st0, (f1 a1, st1)). }\n    split.\n    { (*CA:  let fs0 : A0 * S -> B * S = fun (a0, st) => (f a0, st)\n\n             to prove the lmg it suffices to show that\n\n             \"θ (x <- c0 ;; ret (f0 x)) : SDistr B * S\"  =\n\n             \" d__fs0 (θ (x <- c0 ;; ret x) \"\n\n             // it will map (b,s) ↦ ∑_{a0 ∈ A0: f(a0) = b} θ (x <- c0; ret x)  //\n\n             indeed for (b1,st1),\n\n             Σ_{(b0, st0)} d' (b0,st0) (b1,st1) =\n\n             Σ_{(a0,st0) a1 : f0(a0) = b0 /\\ f1(a1) = b1} d (a0,st0) (a1,st1) = [coupling d _ _ ]\n\n             Σ_{a1 : f1(a1) = } θ (x <- c1 ;; ret x) (a1, st1) = θ (x <- c1 ;; ret (f1 x)\n\n        *) admit. }\n      move => [b0 st0] [b1 st1] Hgt0.\n      (* by definition of d' fi^-1(bi) are both non empty\n         -> exits ai s.t. fi(ai) = bi,  i = 1,2\n         -> specialize H with (a0,st0) (a1,st1) and get the thesis\n       *)\n    admit.\nAdmitted.\n\n(*CA: depends on post_conclusion_rule but is not used *)\nLemma f_preserves_eq { A B : ord_choiceType } { S : choiceType }\n                     { x  y: FrStP S A }\n                     (f : A -> B ) (* (Hbij : bijective f)    *)\n                     ( H: ⊨ ⦃ fun '(s1, s2) => s1 = s2 ⦄\n                             ( X <- x ;; retF X ) ≈\n                             ( Y <- y ;; retF Y)\n\n                            ⦃ eq ⦄ ) :\n    ⊨ ⦃ fun '(s1, s2) => s1 = s2 ⦄\n       (X <- x ;; retF (f X) ) ≈\n       (Y <- y ;; retF (f Y) )\n\n       ⦃ eq ⦄.\nProof.\n  apply: post_conclusion_rule; auto.\n  unshelve eapply post_weaken_rule. { exact: eq. }\n  - assumption.\n  - move => /= [a1 s1] [a2 s2] [H1 H2]. split; by subst.\nQed.\n\n\n\nTheorem if_rule  {A1 A2 : ord_choiceType} {S1 S2 : choiceType}\n                 (c1 c2 : FrStP S1 A1)\n                 (c1' c2' : FrStP S2 A2)\n                 {b1 b2 : bool}\n                 {pre : S1 * S2 -> Prop} {post : A1 * S1 -> A2 * S2 -> Prop}\n                 {pre_b1b2 : forall st, pre st -> b1 = b2}\n                 { H1 : ⊨ ⦃ fun st => pre st /\\ b1 = true ⦄ c1 ≈ c1' ⦃ post ⦄ }\n                 { H2 : ⊨ ⦃ fun st => pre st /\\ b1 = false ⦄ c2 ≈ c2' ⦃ post ⦄ } :\n  ⊨ ⦃ pre ⦄\n      (if b1 then c1 else c2) ≈\n      (if b2 then c1' else c2')\n     ⦃ post ⦄.\nProof.\n  apply pre_hypothesis_rule. move=> st1 st2 pre_holds.\n  specialize (pre_b1b2 (st1, st2) pre_holds). subst.\n  destruct b2 eqn:Hb.\n  - apply (pre_weaken_rule (fun st => pre st /\\ true = true)).\n    assumption.\n    rewrite /= => st1' st2' [Heq1 Heq2]. subst.\n    split; auto.\n  - apply (pre_weaken_rule (fun st => pre st /\\ false = false)).\n    assumption.\n    rewrite /= => st1' st2' [Heq1 Heq2]. subst.\n    split; auto.\nQed.\n\n(* TODO: asymmetric variants of if_rule: if_ruleL and if_ruleR *)\n\n\nFixpoint bounded_do_while {S : choiceType}  (n : nat) (c : FrStP S bool_choiceType) :\n  FrStP S bool_choiceType :=\n  (* false means fuel emptied, true means execution finished *)\n  match n with\n  | 0 => retF false\n  | S n => bindF (fun b => match b with\n                         | false => retF true\n                         | true => bounded_do_while n c\n                         end\n                ) c\n  end.\n\nTheorem bounded_do_while_rule  {A1 A2 : ord_choiceType} {S1 S2 : choiceType}\n                               {n : nat}\n                               (c1 : FrStP S1 bool_choiceType)\n                               (c2 : FrStP S2 bool_choiceType)\n                               {inv : bool -> bool -> (S1 * S2) -> Prop}\n                               {H : ⊨ ⦃ inv true true ⦄ c1 ≈ c2 ⦃ fun bs1 bs2 => (inv bs1.1 bs2.1) (bs1.2,  bs2.2) /\\ bs1.1 = bs2.1 ⦄ } :\n  ⊨ ⦃ inv true true ⦄\n    bounded_do_while n c1 ≈ bounded_do_while n c2\n    ⦃ fun ls rs => (ls.1 = false /\\ rs.1 = false) \\/ (inv false false) (ls.2, rs.2) ⦄.\nProof.\n  induction n.\n  - simpl. eapply weaken_rule.\n    apply ret_rule. simpl. intros [? ?] ?. simpl. cbv. intuition eauto.\n  - simpl. eapply weaken_rule.\n    apply bind_rule. apply H.\n    move => b1 b2. eapply weaken_rule. apply if_rule.\n    move => st.\n    instantiate (1 := fun s => inv b1 b2 s /\\ b1 = b2).\n    rewrite /=. move => [hfoo heq]. assumption.\n    instantiate (1 := fun ls rs => ls.1 = false /\\ rs.1 = false \\/ (inv false false) (ls.2, rs.2)).\n    eapply weaken_rule. apply IHn. simpl. intros [? ?] ?. cbv. intuition eauto.\n    rewrite -H3. rewrite {2}H4. assumption.\n    eapply weaken_rule. apply ret_rule.\n    simpl. intros [? ?] ?. cbv. intuition eauto.\n    apply H2. right. rewrite -H3. rewrite {2}H4. assumption.\n    instantiate (1 := fun '(b1, b2) => fromPrePost (fun st => (inv b1 b2 st) /\\ b1 = b2)\n                                                 (fun ls rs => ls.1 = false /\\ rs.1 = false \\/ (inv false false (ls.2, rs.2)))).\n    move => [st1 st2] /=.\n    cbv; intuition.\n    move => [st1 st2] /=. move => β /=.\n    move => [h1 h2].\n    split; auto.\n    move => [b1 s1] [b2 s2] /= [hh1 hh2]. subst.\n    split; auto.\nQed.\n\n(*TODO: asymmetric variants of bounded_do_while -- Rem.: low priority as not useful for our examples *)\n\nDefinition θ_dens { S : choiceType } { X : ord_choiceType } :=\n  @Theta_dens.unary_theta_dens (F_choice_prod_obj ⟨ X, S ⟩).\n\n\nLemma Pr_eq {X Y : ord_choiceType} { S1 S2 : choiceType } {A : pred (X * S1)} {B : pred (Y * S2)}\n            Ψ ϕ\n            (c1 : FrStP S1 X) (c2 : FrStP S2 Y)\n            (H : ⊨ ⦃ Ψ ⦄ c1 ≈ c2 ⦃ ϕ ⦄)\n            { s1 s2 } (HPsi : Ψ (s1, s2) )\n            (Hpost : forall x y,  ϕ x y -> (A x) <-> (B y)) :\n  \\P_[ θ_dens (θ0 c1 s1) ] A =\n  \\P_[ θ_dens (θ0 c2 s2) ] B.\nProof.\n  rewrite /pr /=.\n  specialize (H (s1,s2) (fun '(a, b) => A a <-> B b)). simpl in H.\n  destruct H as [d [[H11 H12] H2]].\n  split; assumption.\n  rewrite /θ0 /θ_dens /unary_theta_dens /=.\n  rewrite -H11 -H12.\n  rewrite /lmg /rmg.\n  assert ((fun x : X * S1 => (A x)%:R * dfst d x) = (fun x : X *S1 => (A x)%:R * psum (fun w => d (x, w)))) as HeqH11.\n  { extensionality k. rewrite dfstE. reflexivity. }\n  rewrite HeqH11. simpl in HeqH11.\n  assert ((fun x : X * S1 => (A x)%:R * psum (fun w => d (x, w))) = (fun x : X * S1 => psum (fun w => (A x)%:R * d (x, w)))) as H4.\n  { extensionality k. rewrite -psumZ. reflexivity.\n    case (A k); intuition. by rewrite ler01. }\n  rewrite H4.\n  assert ((fun x : Y * S2 => (B x)%:R * dsnd d x) = (fun y : Y * S2 => (B y)%:R * psum (fun w => d (w, y)))) as HeqH12.\n  { extensionality K. rewrite dsndE. reflexivity. }\n  rewrite HeqH12.\n  unfold F_choice_prod_obj in d.\n  assert ((fun y : Y * S2 => (B y)%:R * psum (fun w => d (w, y))) = (fun y : Y * S2 => psum (fun w => (B y)%:R * d (w, y)))) as H5.\n  { extensionality k. rewrite -psumZ. reflexivity.\n    case (B k); intuition; by rewrite ler01. }\n  rewrite H5.\n  clear H5 H4 HeqH12 HeqH11.\n  rewrite -(@psum_pair _ _ _ (fun '(x, y) => (A x)%:R * d (x, y))).\n  rewrite -(@psum_pair_swap _ _ _ (fun '(x, y) => (B y)%:R * d (x, y))).\n  f_equal.\n  extensionality k.\n  destruct k as [x y].\n  case (0 < d (x, y)) eqn:Hd.\n  move: Hd. move/idP => Hd.\n  specialize (H2 _ _ Hd).\n  case (A x) eqn:Ha.\n  + case (B y) eqn: Hb.\n    reflexivity.\n    move: H2. intuition. rewrite H. reflexivity. auto.\n    case (B y) eqn:Hb.\n    intuition. rewrite H0. reflexivity. auto.\n    reflexivity.\n    assert (d (x, y) = 0).\n    rewrite Order.POrderTheory.lt_def in Hd.\n    apply Bool.andb_false_iff in Hd.\n    destruct Hd.\n    ++ move: H. move/eqP. auto.\n    ++ assert (0 <= d (x, y)) as Hn.\n       { apply ge0_mu. }\n       move: H. move/idP. intuition.\n         by rewrite H !GRing.mulr0.\n    (* summable B*)\n    assert ((fun x =>\n               (nat_of_bool (let '(_, y) := x in B y))%:R * d x) =\n            (fun '(x, y)  => (B y)%:R * d (x, y))) as Heq1.\n    { extensionality k. destruct k as [k1 k2].\n      case (B k2). reflexivity. reflexivity. }\n    rewrite -Heq1.\n    pose (@summable_pr R (prod_choiceType (prod_choiceType X S1)\n                                          (prod_choiceType Y S2))\n                                          (fun '(x, y) => B y) d).\n    simpl in *. unfold nat_of_bool in s. rewrite /nat_of_bool. exact s.\n    (* summable A *)\n    assert ((fun x =>\n               (nat_of_bool (let '(x, _) := x in A x))%:R * d x) =\n            (fun '(x, y)  => (A x)%:R * d (x, y))) as Heq2.\n    { extensionality k. destruct k as [k1 k2].\n      case (B k2). reflexivity. reflexivity. }\n    rewrite -Heq2.\n    pose (@summable_pr R (prod_choiceType (prod_choiceType X S1)\n                                          (prod_choiceType Y S2))\n                                          (fun '(x, y) => A x) d).\n    simpl in *. unfold nat_of_bool in s. rewrite /nat_of_bool. exact s.\nQed.\n\nCorollary coupling_eq { A : ord_choiceType } { S : choiceType }\n                      (K1 K2 : FrStP S A )\n                      (ψ : S * S -> Prop)\n                      (H : ⊨ ⦃ ψ ⦄ K1 ≈ K2 ⦃ eq ⦄):\n  forall s1 s2, ψ (s1, s2) -> θ_dens (θ0 K1 s1) = θ_dens (θ0 K2 s2).\nProof.\n  move => s1 s2 psi_s1_s2.\n  apply distr_ext => /= w.\n  assert (\\P_[ θ_dens (θ0 K1 s1) ] (pred1 w) = \\P_[ θ_dens (θ0 K2 s2) ] (pred1 w)).\n  { apply: (Pr_eq ψ eq); rewrite //= => x y Heq. by subst.  }\n  by repeat rewrite -pr_pred1 in H0.\nQed.\n\n\nLemma rewrite_eqDistrL { A1 A2 : ord_choiceType } {S1 S2 : choiceType } { P } { Q }\n                       (c1 c1' : FrStP S1 A1) (c2 : FrStP S2 A2)\n                       (H : ⊨ ⦃ P ⦄ c1 ≈ c2 ⦃ Q ⦄)\n                       (θeq : forall s : S1, θ_dens (θ0 c1 s) = θ_dens (θ0 c1' s) ) :\n\n  ⊨ ⦃ P ⦄ c1'  ≈ c2 ⦃ Q ⦄.\nProof.\n  move => [s1 s2].\n  specialize (H (s1, s2)).\n  specialize (θeq s1).\n  rewrite /θ0 /θ_dens /= in θeq.\n  rewrite /θ /= /MonoCont_order /=.\n  rewrite -θeq.\n  by apply H.\nQed.\n\nLemma rewrite_eqDistrR { A1 A2 : ord_choiceType } {S1 S2 : choiceType} { P } { Q }\n                       (c1  : FrStP S1 A1) (c2 c2': FrStP S2 A2)\n                       (H : ⊨ ⦃ P ⦄ c1 ≈ c2 ⦃ Q ⦄)\n                       (θeq : forall s : S2, θ_dens (θ0 c2 s) = θ_dens (θ0 c2' s) ) :\n\n  ⊨ ⦃ P ⦄ c1  ≈ c2' ⦃ Q ⦄.\nProof.\n  move => [s1 s2].\n  specialize (H (s1, s2)).\n  specialize (θeq s2).\n  rewrite /θ0 /θ_dens /= in θeq.\n  rewrite /θ /= /MonoCont_order /=.\n  rewrite -θeq.\n  by apply H.\nQed.\n\n\nDefinition coupling_self_SDistr { A } ( d: SDistr A) : SDistr (F_choice_prod ⟨ A, A ⟩) :=\n  dmargin (fun a => (a,a)) d.\n\n\nLemma coupling_self { A } (d : SDistr A) :\n  coupling (coupling_self_SDistr d) d d.\nProof.\n  unfold coupling. unfold coupling_self_SDistr. split.\n  - unfold lmg. unfold dmargin.\n    apply distr_ext. move=> a.\n    rewrite dlet_dlet.\n    have coucou:  d a = (\\dlet_(y <- d) dunit y) a . rewrite dlet_dunit_id. reflexivity.\n    rewrite coucou. f_equal. f_equal.\n    apply boolp.funext. move=> y. apply distr_ext. move=> b. rewrite dlet_unit.\n    reflexivity.\n  - unfold rmg. unfold dmargin.\n    apply distr_ext. move=> a.\n    rewrite dlet_dlet.\n    have coucou:  d a = (\\dlet_(y <- d) dunit y) a . rewrite dlet_dunit_id. reflexivity.\n    rewrite coucou. f_equal. f_equal.\n    apply boolp.funext. move=> y. apply distr_ext. move=> b. rewrite dlet_unit.\n    reflexivity.\nQed.\n\nLemma aux_lemma0 {A} (c : SDistr A) (a1 a2 : A) :\ncoupling_self_SDistr c (a1,a2) = (if a1 == a2 then c a1 else 0).\nProof.\n  destruct (eqType_lem A a1 a2).\n  - rewrite H. unfold coupling_self_SDistr. rewrite refl_true.\n    unfold dmargin.\n    have coucou : c a2 = (\\dlet_(x <- c) dunit x) a2.\n      symmetry. rewrite dlet_dunit_id. reflexivity.\n    rewrite coucou. f_equal.\nAbort.\n\nLemma aux_domain : forall u v : R, u * v <> 0 -> u <> 0.\nProof.\n  move=> u v. apply contra_not. move=> H0. rewrite H0.\n  apply GRing.Theory.mul0r.\nQed.\n\n\n\nLemma aux_lemma { A } {d : SDistr A} :\n  forall a1 a2, 0 < (coupling_self_SDistr d) (a1,a2) -> a1 = a2.\nProof.\n  move=> a1 a2. unfold coupling_self_SDistr. rewrite dmargin_psumE.\n  move=> Hpsum.\n  have Hpsum' : psum (fun x : A => ((x, x) == (a1, a2))%:R * d x) <> 0.\n    move=> abs. rewrite -abs in Hpsum. rewrite Order.POrderTheory.ltxx in Hpsum.\n    discriminate.\n  clear Hpsum.\n  eapply neq0_psum in Hpsum'. destruct Hpsum'.\n  apply aux_domain in H.\n  destruct (eqType_lem  bool_eqType ((x,x) == (a1,a2)) true) as [Houi | Hnon].\n  move: Houi => /eqP Houi. move: Houi => [H1 H2]. rewrite -H1 -H2. reflexivity.\n  have Hnon' : (x,x) == (a1,a2) = false.\n    destruct ((x,x) == (a1,a2)). contradiction. reflexivity.\n  rewrite Hnon' in H. cbn in H. contradiction.\nQed.\n\n\n\nLemma reflexivity_rule { A : ord_choiceType } { S : choiceType }\n                       (c : FrStP S A):\n  ⊨ ⦃ fun '(s1, s2) => s1 = s2 ⦄ c ≈ c ⦃ eq ⦄.\nProof.\n  move => [st1 st] /=. move =>  α [H1 H2] /=. subst.\n  exists (coupling_self_SDistr (θ_dens (θ0 c st))).\n  split.\n  - exact: coupling_self.\n  - move => [a1 s1] [a2 s2] H.\n    apply: H2. apply: aux_lemma H.\nQed.\n\nDefinition dsym { A B : ord_choiceType } { S1 S2 : choiceType } (d : SDistr_carrier\n          (F_choice_prod_obj\n             ⟨ Choice.Pack {| Choice.base := prod_eqMixin B S2; Choice.mixin := prod_choiceMixin B S2 |},\n               Choice.Pack {| Choice.base := prod_eqMixin A S1; Choice.mixin := prod_choiceMixin A S1 |} ⟩)) :\nSDistr_carrier\n          (F_choice_prod_obj\n             ⟨ Choice.Pack {| Choice.base := prod_eqMixin A S1; Choice.mixin := prod_choiceMixin A S1 |},\n               Choice.Pack {| Choice.base := prod_eqMixin B S2; Choice.mixin := prod_choiceMixin B S2 |} ⟩) :=\ndswap d.\n\n\nLemma dsym_coupling { A B : ord_choiceType } { S1 S2 : choiceType } { d : SDistr_carrier\n          (F_choice_prod_obj\n             ⟨ Choice.Pack {| Choice.base := prod_eqMixin B S2; Choice.mixin := prod_choiceMixin B S2 |},\n               Choice.Pack {| Choice.base := prod_eqMixin A S1; Choice.mixin := prod_choiceMixin A S1 |} ⟩) }\n      {d1 d2 }\n      (Hcoupling : coupling d d1 d2) : coupling (dsym d) d2 d1.\nProof.\n  rewrite /dsym. destruct Hcoupling as [dfst_d dsnd_d]. unfold coupling, lmg, rmg in *.\n  subst. split.\n  - apply: distr_ext. exact: dfst_dswap d.\n  - apply: distr_ext. exact: dsnd_dswap d.\nQed.\n\nLemma symmetry_rule { A B : ord_choiceType } { S1 S2 : choiceType } { pre post }\n      (c1  : FrStP S1 A) (c2  : FrStP S2 B)\n      (H: ⊨ ⦃ fun '(s2, s1) => pre (s1, s2) ⦄ c2 ≈ c1 ⦃ fun '(b,s2) '(a,s1) => post (a,s1) (b,s2) ⦄ ):\n      ⊨ ⦃ pre  ⦄ c1 ≈ c2 ⦃ post ⦄.\nProof.\n  move => [s1 s2]. move => /= π.\n  move => [Hpre H'].\n  specialize (H (s2,s1) (fun '(a,s1,(b,s2)) => π ((b,s2,(a,s1))))).\n  cbn in H.\n  destruct H as [d' [H1 H2]].\n  - rewrite /=. split.\n    -- assumption.\n    -- move => [a h1] [b h2] Hpost /=. apply: (H' (b, h2) (a, h1) Hpost).\n  simpl in d', H1, H2. exists (dswap d'). split.\n    - exact: dsym_coupling.\n    -- move => [b h2] [a h1] Hdsym. apply: (H2 (a, h1) (b, h2)).\n       apply msupp.\n       have Heq: dswap (dswap d') = d'. { apply: distr_ext. exact: (dswapK d'). }\n       rewrite -Heq.\n       apply dinsupp_swap.\n       apply /dinsuppP.\n       rewrite lt0r in Hdsym.\n       move /andP: Hdsym. move => [Hd1  Hd2].\n       apply /eqP. assumption.\nQed.\n\nTheorem swap_rule { A1 A2 : ord_choiceType } { S : choiceType } { I : S * S -> Prop } {post : A1 * S -> A2 * S -> Prop }\n                  (c1 : FrStP S A1) (c2 : FrStP S A2)\n                  (Hinv1 : ⊨ ⦃ I ⦄ c1 ≈ c2 ⦃ fun '(a1, s1) '(a2, s2) => I (s1, s2) /\\ post (a1,s1) (a2,s2) ⦄ )\n                  (Hinv2 : ⊨ ⦃ I ⦄ c2 ≈ c1 ⦃ fun '(a2, s2) '(a1, s1) => I (s1, s2) /\\ post (a1,s1) (a2,s2) ⦄ ):\n  ⊨ ⦃ I ⦄ (c1 ;; c2) ≈ (c2 ;; c1) ⦃ fun '(a2, s2) '(a1, s1) => I (s1, s2) /\\ post (a1,s1) (a2,s2) ⦄ .\nProof.\n  apply: seq_rule.\n  - exact: Hinv1.\n  - move => a1 a2.\n    apply: pre_weaken_rule.\n    { apply: post_weaken_rule.\n      exact: Hinv2.\n      move => [a1' s1] [a2' s2] [HI HQ].\n      split; assumption. }\n    move => st1 st2 /= [HI HQ].\n    assumption.\nQed.\n\n(*Rem.: don't worry too much about indexes and order, in most cases predicates will be symmetric *)\nTheorem swap_ruleL { A1 A2 B : ord_choiceType } { S : choiceType }\n                   { pre I : S * S -> Prop }\n                   { post :  A2 * S -> A1 * S -> Prop }\n                   (l : FrStP S B) (c1 : FrStP S A1) (c2 : FrStP S A2)\n                   (HL    : ⊨ ⦃ pre ⦄ l ≈ l ⦃ fun '(b1, s1) '(b2, s2) => I (s1, s2) ⦄)\n                   (Hinv1 : ⊨ ⦃ I ⦄ c1 ≈ c2 ⦃ fun '(a1, s1) '(a2, s2) => I (s1, s2) /\\ post (a2, s2) (a1, s1)  ⦄ )\n                   (Hinv2 : ⊨ ⦃ I ⦄ c2 ≈ c1 ⦃ fun '(a2, s2) '(a1, s1) => I (s1, s2) /\\ post (a2, s2) (a1, s1) ⦄ ):\n  ⊨ ⦃ pre ⦄ (l ;; c1 ;; c2) ≈ (l ;; c2 ;; c1) ⦃ post ⦄ .\nProof.\n  apply: seq_rule.\n  exact: HL.\n  move => a1 a2 /=.\n  unshelve apply: post_weaken_rule.\n  { exact: (fun '(x2, s2) '(x1, s1) => I(s1,s2) /\\ (post (x2,s2) (x1,s1))). }\n  by apply: (@swap_rule A1 A2 S I (fun '(x1,h1) '(x2, h2) => post (x2,h2) (x1,h1)) c1 c2 Hinv1 Hinv2).\n  move => [a1' s1] [a2' s2] [HI HHL] /=. assumption.\nQed.\n\n\nSection AuxLemmasSwapRuleR.\n\nLemma  smMonEqu1\n{A1 A2 B : ord_choiceType} {S : choiceType}\n(r : A1 -> A2 -> FrStP S B) (c1 : FrStP S A1) (c2 : FrStP S A2) :\n(a2 ∈ choice_incl A2 <<- c2;; a1 ∈ choice_incl A1 <<- c1;; (r a1 a2))\n=\n(a ∈ choice_incl (prod_choiceType A1 A2) <<-\n        (a2 ∈ choice_incl A2 <<- c2;; a1 ∈ choice_incl A1 <<- c1;; retF (a1, a2));;\n        r a.1 a.2).\nProof.\n   symmetry.\n   cbn. unfold FreeProbProg.rFree_obligation_2.\n   unshelve epose (assoc := (@ord_relmon_law3 _ _ _ (FrStP S) _ _ _ _ _)).\n     shelve. shelve. shelve.\n     exact (fun a : A1 * A2 => r a.1 a.2).\n     exact (fun a2 : A2 =>\n        bindrFree (@StateTransformingLaxMorph.ops_StP S) (@StateTransformingLaxMorph.ar_StP S) c1\n          (fun a1 : A1 => retF (a1, a2))).\n   cbn in assoc. unfold FreeProbProg.rFree_obligation_2 in assoc.\n   symmetry in assoc. unshelve eapply equal_f in assoc. exact c2. rewrite assoc.\n   clear assoc.\n   f_equal. apply boolp.funext. move=> a2.\n   unshelve epose (assoc := (@ord_relmon_law3 _ _ _ (FrStP S) _ _ _ _ _)).\n     shelve. shelve. shelve.\n     exact (fun a : A1 * A2 => r a.1 a.2).\n     exact (fun a1 : A1 => retF (a1, a2)).\n   cbn in assoc. unfold FreeProbProg.rFree_obligation_2 in assoc.\n   symmetry in assoc. unshelve eapply equal_f in assoc. exact c1. rewrite assoc.\n   reflexivity.\nQed.\n\nLemma  smMonEqu2\n{A1 A2 B : ord_choiceType} {S : choiceType}\n(r : A1 -> A2 -> FrStP S B) (c1 : FrStP S A1) (c2 : FrStP S A2) :\n(a1 ∈ choice_incl A1 <<- c1;; a2 ∈ choice_incl A2 <<- c2;; (r a1 a2))\n=\n(a ∈ choice_incl (prod_choiceType A1 A2) <<-\n        (a1 ∈ choice_incl A1 <<- c1;; a2 ∈ choice_incl A2 <<- c2;; retF (a1, a2));;\n        r a.1 a.2).\nProof.\n   symmetry.\n   cbn. unfold FreeProbProg.rFree_obligation_2.\n   unshelve epose (assoc := (@ord_relmon_law3 _ _ _ (FrStP S) _ _ _ _ _)).\n     shelve. shelve. shelve.\n     exact (fun a : A1 * A2 => r a.1 a.2).\n     exact (fun a1 : A1 =>\n      bindrFree (@StateTransformingLaxMorph.ops_StP S) (@StateTransformingLaxMorph.ar_StP S) c2\n        (fun a2 : A2 => retF (a1, a2))).\n   cbn in assoc. unfold FreeProbProg.rFree_obligation_2 in assoc.\n   symmetry in assoc. unshelve eapply equal_f in assoc. exact c1. rewrite assoc.\n   clear assoc.\n   f_equal. apply boolp.funext. move=> a1.\n   unshelve epose (assoc := (@ord_relmon_law3 _ _ _ (FrStP S) _ _ _ _ _)).\n     shelve. shelve. shelve.\n     exact (fun a : A1 * A2 => r a.1 a.2).\n     exact (fun a2 : A2 => retF (a1, a2)).\n   cbn in assoc. unfold FreeProbProg.rFree_obligation_2 in assoc.\n   symmetry in assoc. unshelve eapply equal_f in assoc. exact c2. rewrite assoc.\n   reflexivity.\nQed.\n\nContext (S : choiceType).\n\nLet Frp_fld :=  @Frp.\n\nLemma theta0_vsbind {P Q : ord_choiceType} (p : FrStP S P) (q : FrStP S Q)\n  (s : S) :\nθ0 (x ∈ P <<- p ;; q) s\n=\n(ord_relmon_bind Frp_fld)\n  (fun ps : P * S => let (p,s) := ps in θ0 q s)\n  (θ0 p s).\nProof.\n  unfold θ0.\n  epose (assoc := rlmm_law2 _ _ _ _ (unaryIntState) P Q (fun _ => q) ).\n  cbn in assoc. specialize (assoc p).\n  cbn. unshelve eapply equal_f in assoc. exact s.\n  rewrite [LHS]assoc.\n  unfold OrderEnrichedRelativeAdjunctionsExamples.ToTheS_obligation_1.\n  unfold FreeProbProg.rFree_obligation_2.\n  reflexivity.\nQed.\n\nLemma some_commutativity\n  {A1 A2 B : ord_choiceType}\n  (post : B * S -> B * S -> Prop)\n  (r : A1 -> A2 -> FrStP S B)\n  (c1 : FrStP S A1)\n  (c2 : FrStP S A2)\n  (HR : forall (a1 : A1) (a2 : A2), ⊨ ⦃ fun '(s2, s1) => s1 = s2 ⦄ r a1 a2 ≈ r a1 a2 ⦃ post ⦄ )\n  (post_eq : forall bs bs' : B * S, bs = bs' -> post bs bs')\n  (Hcomm : forall s : S,\n          θ_dens (θ0 (a1 ∈ choice_incl A1 <<- c1;; a2 ∈ choice_incl A2 <<- c2;; retF (a1, a2)) s) =\n          θ_dens (θ0 (a2 ∈ choice_incl A2 <<- c2;; a1 ∈ choice_incl A1 <<- c1;; retF (a1, a2)) s) )\n  (s : S) :\nθ_dens\n  (θ0\n     (a ∈ choice_incl (prod_choiceType A1 A2) <<-\n      (a1 ∈ choice_incl A1 <<- c1;; a2 ∈ choice_incl A2 <<- c2;; retF (a1, a2));;\n      r a.1 a.2) s) =\nθ_dens\n  (θ0\n     (a ∈ choice_incl (prod_choiceType A1 A2) <<-\n      (a2 ∈ choice_incl A2 <<- c2;; a1 ∈ choice_incl A1 <<- c1;; retF (a1, a2));;\n      r a.1 a.2) s).\nProof.\n  (*we begin by using bind preservation of θ0 on both sides*)\n  pose ( p12 :=\n(a1 ∈ choice_incl A1 <<- c1;; a2 ∈ choice_incl A2 <<- c2;; retF (a1, a2)) ).\n  assert (θ0_comm :\n(θ0 (a ∈ choice_incl (prod_choiceType A1 A2) <<- p12 ;; r a.1 a.2) s)\n=\n(ord_relmon_bind Frp_fld)^~(θ0 p12 s)\n  (fun xs' => let (x,s'):= xs' in θ0 (r x.1 x.2) s') ).\n{\n  unfold θ0.\n  unshelve epose (assoc := rlmm_law2 _ _ _ _ (unaryIntState) _ _ _ ).\n    shelve. shelve. shelve.\n    exact (fun (a : A1 * A2) => r a.1 a.2).\n  cbn in assoc. specialize (assoc p12).\n  cbn. unshelve eapply equal_f in assoc. exact s.\n  rewrite [LHS]assoc.\n  unfold OrderEnrichedRelativeAdjunctionsExamples.ToTheS_obligation_1.\n  unfold FreeProbProg.rFree_obligation_2.\n  reflexivity.\n}\n  rewrite θ0_comm. clear θ0_comm.\n\n  pose ( p21 :=\n(a2 ∈ choice_incl A2 <<- c2;; a1 ∈ choice_incl A1 <<- c1;; retF (a1, a2)) ).\n  assert (θ0_comm :\n(θ0 (a ∈ choice_incl (prod_choiceType A1 A2) <<- p21 ;; r a.1 a.2) s)\n=\n(ord_relmon_bind Frp_fld)^~(θ0 p21 s)\n  (fun xs' => let (x,s'):= xs' in θ0 (r x.1 x.2) s') ).\n{\n  unfold θ0.\n  unshelve epose (assoc := rlmm_law2 _ _ _ _ (unaryIntState) _ _ _ ).\n    shelve. shelve. shelve.\n    exact (fun (a : A1 * A2) => r a.1 a.2).\n  cbn in assoc. specialize (assoc p21).\n  cbn. unshelve eapply equal_f in assoc. exact s.\n  rewrite [LHS]assoc.\n  unfold OrderEnrichedRelativeAdjunctionsExamples.ToTheS_obligation_1.\n  unfold FreeProbProg.rFree_obligation_2.\n  reflexivity.\n}\n  rewrite θ0_comm. clear θ0_comm.\n\n  (*next we apply bind preservation of θ_dens*)\n  unshelve etransitivity.\n    cbn. unshelve eapply (ord_relmon_bind SDistr).\n    - exact ( prod_choiceType (prod_choiceType A1 A2 ) S ).\n    - move=> [x s'].  exact ( θ_dens (θ0 (r x.1 x.2) s' ) ).\n    - exact (θ_dens (θ0 p12 s)).\n  unfold θ_dens at 1.\n  pose utheta_dens_fld :=\n@unary_theta_dens.\n  unshelve epose (θ_dens_bind :=\n@rmm_law2 _ _ _ _ _ _ _ _ _ utheta_dens_fld _ _ _).\n  shelve. shelve.\n  exact (fun xs' : A1 * A2 * S => let (x, s') := xs' in θ0 (r x.1 x.2) s').\n  rewrite /=.\n  move: θ_dens_bind => /= θ_dens_bind.\n  unshelve eapply equal_f in θ_dens_bind. exact (θ0 p12 s).\n  rewrite θ_dens_bind.\n  unfold SubDistr.SDistr_obligation_2.\n  rewrite  /θ_dens /=.\n  assert (contEqu :\n( fun x : A1 * A2 * S =>\n     Theta_dens.unary_theta_dens_obligation_1 (F_choice_prod_obj ⟨ B, S ⟩)\n       (let (x0, s') := x in θ0 (r x0.1 x0.2) s') )\n=\n( fun trucc : A1 * A2 * S =>\n     let (x, s') := trucc in\n     Theta_dens.unary_theta_dens_obligation_1 (F_choice_prod_obj ⟨ B, S ⟩)\n       (θ0 (r x.1 x.2) s') ) ).\n  apply boolp.funext. move=> [[a1 a2] ss]. reflexivity.\n  rewrite contEqu. apply f_equal. reflexivity.\n\n  (*p12 is p21 under θ_dens ∘ θ0 *)\n  unfold θ_dens at 3.\n  pose utheta_dens_fld :=\n@unary_theta_dens.\n  unshelve epose (θ_dens_bind :=\n@rmm_law2 _ _ _ _ _ _ _ _ _ utheta_dens_fld _ _ _).\n  shelve. shelve.\n  exact (fun xs' : A1 * A2 * S => let (x, s') := xs' in θ0 (r x.1 x.2) s').\n  rewrite /=.\n  move: θ_dens_bind => /= θ_dens_bind.\n  unshelve eapply equal_f in θ_dens_bind. exact (θ0 p21 s).\n  rewrite θ_dens_bind.\n  assert ( contEqu :\n(fun trucc : A1 * A2 * S =>\n     let (x, s') := trucc in θ_dens (θ0 (r x.1 x.2) s'))\n=\n(fun x : A1 * A2 * S =>\n     Theta_dens.unary_theta_dens_obligation_1 (F_choice_prod_obj ⟨ B, S ⟩)\n       (let (x0, s') := x in θ0 (r x0.1 x0.2) s')) ).\n  apply boolp.funext. move=> [[a1 a2] ss]. rewrite /=. reflexivity.\n  rewrite contEqu. apply f_equal.\n  apply Hcomm.\nQed.\n\n\nEnd AuxLemmasSwapRuleR.\n\nTheorem swap_ruleR { A1 A2 B : ord_choiceType } { S : choiceType }\n                   { post : B * S -> B * S -> Prop }\n                   (r : A1 -> A2 -> FrStP S B) (c1 : FrStP S A1) (c2 : FrStP S A2)\n                   (HR    : forall a1  a2, ⊨ ⦃ fun '(s2, s1) => s1 = s2 ⦄ (r a1 a2) ≈ (r a1 a2) ⦃ post ⦄)\n                   (post_eq : forall bs bs', bs = bs' -> post bs bs')\n\n                   (*Rem.: \"commutativity condition\" always satisfied for example by sample o ;; sample o' *)\n                   (Hcomm: forall s,  θ_dens (θ0 ((a1 <- c1 ;; a2 <- c2 ;; retF (a1,a2) )) s) =\n                                 θ_dens (θ0 ((a2 <- c2 ;; a1 <- c1 ;; retF (a1,a2) )) s) ):\n\n  ⊨ ⦃ fun '(s1, s2) => s1 = s2 ⦄  ( a1 <- c1 ;; a2 <- c2 ;; (r a1 a2) ) ≈ ( a2 <- c2 ;;  a1 <- c1 ;; (r a1 a2)) ⦃ post ⦄ .\nProof.\n  unshelve apply: rewrite_eqDistrL.\n    exact: ( a <- (a2 <- c2 ;;  a1 <- c1 ;; retF (a1, a2)) ;; r a.1 a.2 ).\n  unshelve apply: rewrite_eqDistrR.\n    exact: ( a <- (a1 <- c1 ;;  a2 <- c2 ;; retF (a1, a2)) ;; r a.1 a.2 ).\n  eapply (seq_rule _ _ _ (fun aa1 aa2 => aa1 = aa2)).\n  apply: rewrite_eqDistrL. exact: reflexivity_rule. assumption.\n  -  move => [a1 a2] [a1' a2']. apply: pre_hypothesis_rule.\n     move => s1 s2 /= [H1 H2 H3]. subst.\n     specialize (HR a1' a2' (s2, s2)).\n     move => [s s'] /=. move => β [[Heq Heq'] H]. subst. apply: HR.\n     simpl. split; auto.\n  -  rewrite (@smMonEqu1 A1 A2 B S r c1 c2).\n     move=> s.\n     unshelve eapply some_commutativity. exact post.\n       apply HR.\n       apply post_eq.\n       apply Hcomm.\n  -  rewrite (@smMonEqu2 A1 A2 B S r c1 c2).\n     move=> s.\n     unshelve erewrite <- some_commutativity. exact post.\n     reflexivity.\n       apply HR.\n       apply post_eq.\n       apply Hcomm.\nQed.\n\n\n(*Rem.: a proved variant of the above -- less useful though *)\nLemma swap_ruleR' { A1 A2 B : ord_choiceType } { S : choiceType }\n                  { I : S * S -> Prop}\n                  { post : B * S -> B * S -> Prop } { Q : A1 * S -> A2 * S -> Prop }\n                  (r : FrStP S B) (c1 : FrStP S A1) (c2 : FrStP S A2)\n                  (HR    : forall a1  a2, ⊨ ⦃ fun '(s2, s1) => Q (a1, s1) (a2, s2) ⦄ r ≈ r ⦃ post ⦄)\n                   (Hinv1 : ⊨ ⦃ I ⦄ c1 ≈ c2 ⦃ fun '(a1, s1) '(a2, s2) => I (s1, s2) /\\ Q (a1, s1) (a2, s2) ⦄ )\n                   (Hinv2 : ⊨ ⦃ I ⦄ c2 ≈ c1 ⦃ fun '(a2, s2) '(a1, s1) => I (s1, s2) /\\ Q (a1, s1) (a2, s2) ⦄ ) :\n  ⊨ ⦃ I ⦄  ( c1 ;; c2 ;; r ) ≈ ( c2 ;; c1 ;; r ) ⦃ post ⦄ .\nProof.\n  have Hfoo : (c1;; c2 ;; r ) = ( (c1 ;; c2) ;; r ).\n  { unfold \";;\". by rewrite ord_relmon_law3. } rewrite Hfoo; clear Hfoo.\n  have Hfoo : (c2;; c1;; r ) = ((c2 ;; c1) ;; r).\n  { unfold \";;\". by rewrite ord_relmon_law3. } rewrite Hfoo; clear Hfoo.\n  unshelve apply: seq_rule.\n  { exact: (fun '(a2, s2) '(a1, s1) => Q (a1, s1) (a2, s2)). }\n  apply: post_weaken_rule.\n  eapply (swap_rule c1 c2).\n  exact: Hinv1.\n  exact: Hinv2.\n  { move => [a1 s1] [a2 s2] [HI HQ]. auto. }\n  move => a2 a1 /=.\n  exact: HR a1 a2.\nQed.\n\n(*Rem.: TODO possibly generalize as above *)\nTheorem swap_rule_ctx { A1 A2 Bl Br : ord_choiceType } { S : choiceType }\n                      { I pre : S * S -> Prop }\n                      { post: Br * S -> Br * S -> Prop } { Q : A1 * S -> A2 * S -> Prop }\n                      (l : FrStP S Bl) (r : FrStP S Br) (c1 : FrStP S A1) (c2 : FrStP S A2)\n                      (HL    : ⊨ ⦃ pre ⦄ l ≈ l ⦃ fun '(a1, s1) '(a2, s2) => I (s1, s2) ⦄)\n                      (HR    : forall a1 a2, ⊨ ⦃ fun '(s2, s1) => Q (a1,s1) (a2,s2) ⦄ r ≈ r ⦃ post ⦄)\n                      (Hinv1 : ⊨ ⦃ I ⦄ c1 ≈ c2 ⦃ fun '(a1, s1) '(a2, s2) => I (s1, s2) /\\ Q (a1, s1) (a2, s2) ⦄ )\n                      (Hinv2 : ⊨ ⦃ I ⦄ c2 ≈ c1 ⦃ fun '(a2, s2) '(a1, s1) => I (s1, s2) /\\ Q (a1, s1) (a2, s2) ⦄ ):\n  ⊨ ⦃ pre ⦄  l ;; c1 ;; c2 ;; r ≈ l ;; c2 ;; c1 ;; r ⦃ post ⦄ .\nProof.\n  apply: seq_rule.\n   - exact: HL.\n   - move => a1 a2 /=.\n     apply: swap_ruleR'.\n     -- exact: HR.\n     -- exact: Hinv1.\n     -- exact: Hinv2.\nQed.\n\n\n\nSection samplerC_rule.\nNotation η M := (ord_relmon_unit M).\nNotation dnib M := (ord_relmon_bind M).\n(* In this section we prove a rule called samplerC, which tells that *)\n(* sampling operations in the monad free monad Fr[St,P] *)\n(* (on a  stateful probabilistic signature) commute with other *)\n(* operations (for instance 'get' ...) *)\n\n(* More precisely we prove that the semantics of programs *)\n(* Fr[St,P] --> StT(Fr[P]) --> StT(SD) *)\n(* assigns the same value to *)\n(* r <- sample o ;; a <- c ;; ret (a,r) and *)\n(* a <- c ;; r <- sample o ;; ret (a,r). *)\n(* And this condition is sufficient to prove a rule like the one described *)\n(* above *)\n\n(*operations and arities for probabilities*)\nLet Op := P_OP.\nLet Ar := P_AR.\n\nContext { A : ord_choiceType }  {S : choiceType}.\n\n(*for state + prob*)\nLet Opst := (ops_StP S).\nLet Arst := (ar_StP S).\n\nContext (o : Op) (c : FrStP S A).\n\nArguments bindrFree { _ _ _ _ } _ _.\nArguments ropr {_ _ _ } _ _.\nArguments callrFree {_ _} _.\nArguments retrFree {_ _ _} _.\n\n(*the two programs of interest...*)\n(*sample_c and c_sample*)\nLet splo :=  @callrFree Opst Arst (op_iota o).\nDefinition sample_c :=\nbindrFree splo (fun r =>\nbindrFree c (fun a =>\nretrFree (a,r))).\n\nDefinition c_sample :=\nbindrFree c (fun a =>\nbindrFree splo (fun r =>\nretrFree (a,r))).\n\n\nLemma θ0_vs_bind {X Y : choiceType} (m : FrStP S X) (k : X -> FrStP S Y):\nθ0 (bindrFree m k) =\n(dnib stT_Frp) (fun x:X => θ0 (k x)) (θ0  m).\nProof.\n  assert ( to_dnib : bindrFree m k = (dnib (FrStP S)  k) m ).\n    reflexivity.\n  rewrite to_dnib.\n  rewrite /θ0.\n  pose bla :=\nrmm_law2 _ _ _ _ (@unaryIntState S)\n         X Y k.\n  rewrite /= in bla.\n  unshelve eapply equal_f in bla. exact m.\n  rewrite /=. assumption.\nQed.\n\nLemma θ0_vs_sample_c :\n  θ0 sample_c\n  =\n  dnib stT_Frp\n    (fun r : Arst (op_iota o) => dnib stT_Frp (fun a : A => θ0 (retrFree (a, r))) (θ0 c))\n    (θ0 splo).\nProof.\n  unfold sample_c.\n  rewrite θ0_vs_bind.\n  eassert (eqCont :\n(fun r : Arst (op_iota o) => θ0 (bindrFree c (fun a : choice_incl A => retrFree (a, r))))\n=\n(fun r => _) ).\n  apply boolp.funext. move=> x. rewrite θ0_vs_bind. reflexivity.\n  rewrite eqCont. reflexivity.\nQed.\n\nLemma θ0_vs_c_sample :\n  θ0 c_sample\n  =\n  dnib stT_Frp\n    (fun a : A => dnib stT_Frp (fun r : Arst (op_iota o) => θ0 (retrFree (a, r))) (θ0 splo))\n    (θ0 c).\nProof.\n  unfold c_sample.\n  rewrite θ0_vs_bind.\n  eapply (f_equal (λ x, dnib stT_Frp x (θ0 c))).\n  apply boolp.funext. move=> a.\n  rewrite θ0_vs_bind. reflexivity.\nQed.\n\nLemma θ0_c_sample_vs_s0 (s0 : S) :\nθ0 c_sample s0 =\nbindrFree (θ0 c s0) (fun asc => let (a, sc) := asc in\nbindrFree (θ0 splo sc) (fun rsr => let (r,sr) := rsr in\nretrFree (a,r,sr))).\nProof.\n  rewrite θ0_vs_c_sample.\n  rewrite /=.\n  rewrite /OrderEnrichedRelativeAdjunctionsExamples.ToTheS_obligation_1.\n  rewrite /FreeProbProg.rFree_obligation_2.\n  reflexivity.\nQed.\n\nLemma θ0_sample_c_vs_s0 (s0 : S) :\nθ0 sample_c s0 =\nbindrFree (θ0 splo s0) (fun rsr => let (r,sr) := rsr in\nbindrFree (θ0 c sr) (fun asc => let (a, sc) := asc in\nretrFree (a,r,sc))).\nProof.\n  rewrite θ0_vs_sample_c.\n  rewrite /=.\n  rewrite /OrderEnrichedRelativeAdjunctionsExamples.ToTheS_obligation_1.\n  rewrite /FreeProbProg.rFree_obligation_2.\n  reflexivity.\nQed.\n\nLet Frp_fld :=  @Frp.\n\nLemma bindrFree_and_ret {U:choiceType} (mu : Frp_fld U) :\nbindrFree mu (fun u =>\nretrFree u)\n=\nmu.\nProof.\n  unfold bindrFree. induction mu.\n  reflexivity.\n  f_equal. apply boolp.funext. move=> p.\n  specialize (H p). rewrite H. reflexivity.\nQed.\n\n\nLemma op_outoffree (s0 : S):\nUniversalFreeMap.outOfFree sigMap (Arst (op_iota o)) splo\n=\n@sigMap S (op_iota o).\nProof.\n    cbn.\n    rewrite /OrderEnrichedRelativeAdjunctionsExamples.ToTheS_obligation_1.\n    apply boolp.funext. move=> s0'.\n    rewrite /FreeProbProg.rFree_obligation_2.\n    rewrite /FreeProbProg.rFree_obligation_1.\n    cbn. rewrite /probopStP. reflexivity.\nQed.\n\nLet sploP := @callrFree Op Ar o.\n\n(* Lemma quick_slice : *)\n(* Ar o = Arst (op_iota o). *)\n(*   destruct o. cbn. reflexivity. *)\n(* Qed. *)\n\n(* Let sploP' :=  @callrFree Op Ar o. *)\n(* Program Definition sploP : rFreeF Op Ar (Arst (op_iota o)) := sploP'. *)\n(* Next Obligation. *)\n(*   apply quick_slice. *)\n(* Qed. *)\n\n\n(* Context (s0 : S). *)\n(* Goal True. *)\n(*   pose bla := θ0 splo s0. cbn in bla. *)\n(*   pose bla' := bindrFree sploP (fun r => *)\n(* retrFree (r, s0) ). *)\n(*   cbn in bla'. *)\n(* rFreeF P_OP P_AR (F_choice_prod_obj ⟨ Arst (op_iota o), S ⟩) *)\n(* rFreeF Op   Ar   (prod_choiceType (Ar o) S) *)\n\nLemma θ0_of_sample (s0 : S) :\nθ0 splo s0\n=\nbindrFree sploP (fun r =>\nretrFree (r, s0) ).\nProof.\n  unfold θ0. unfold unaryIntState.\n  rewrite (op_outoffree s0). rewrite /=.\n  rewrite /probopStP.\n  destruct o as [X op].\n  reflexivity.\nQed.\n\nLemma θ0_OF_sample_c_s0 (s0 : S) :\nθ0 sample_c s0 =\nbindrFree sploP (fun r =>\nbindrFree (θ0 c s0) (fun asc => let (a, sc) := asc in\nretrFree (a,r,sc))).\nProof.\n  rewrite θ0_sample_c_vs_s0.\n  rewrite θ0_of_sample.\n  epose (bind_assoc := ord_relmon_law3 Frp_fld _ _ _ _ _).\n  eapply equal_f in bind_assoc.\n  cbn in bind_assoc.\n  rewrite /FreeProbProg.rFree_obligation_2 in bind_assoc.\n  erewrite <- bind_assoc.\n  f_equal.\nQed.\n\nLemma θ0_OF_c_sample_s0 (s0 : S) :\nθ0 c_sample s0 =\nbindrFree (θ0 c s0) (fun asc => let (a, sc) := asc in\nbindrFree sploP (fun r =>\nretrFree (a,r,sc))).\nProof.\n  rewrite θ0_c_sample_vs_s0.\n  f_equal. apply boolp.funext. move=> [a sc].\n  rewrite θ0_of_sample.\n  epose (bind_assoc := ord_relmon_law3 Frp_fld _ _ _ _ _).\n  eapply equal_f in bind_assoc.\n  cbn in bind_assoc.\n  rewrite /FreeProbProg.rFree_obligation_2 in bind_assoc.\n  erewrite <- bind_assoc.\n  f_equal.\nQed.\n\nLet utheta_dens_fld :=\n(@Theta_dens.unary_theta_dens).\n\nLemma utheta_dens_vs_bind {X Y : choiceType}\n(m : Frp X)\n(k : X -> Frp Y) :\nutheta_dens_fld _ (bindrFree m k)\n=\n(dnib SDistr) (fun x => utheta_dens_fld _ (k x))\n              (utheta_dens_fld _ m).\nProof.\n  assert ( to_dnib : bindrFree m k = (dnib Frp  k) m ).\n    reflexivity.\n  rewrite to_dnib.\n  pose bla :=\nrmm_law2 _ _ _ _\n(@Theta_dens.unary_theta_dens)\nX Y k.\n  rewrite /= in bla.\n  unshelve eapply equal_f in bla. exact m.\n  rewrite /=. assumption.\nQed.\n\nLemma θ_dens_vs_bind' {X Y : choiceType}\n(m : Frp  X )\n(k : X -> Frp (prod_choiceType Y S)) :\nθ_dens (bindrFree m k) =\n(dnib SDistr) (fun xs => θ_dens (k xs)) (utheta_dens_fld _ m).\nProof.\n  assert ( to_dnib : bindrFree m k = (dnib Frp  k) m ).\n    reflexivity.\n  rewrite to_dnib.\n  rewrite /θ_dens.\n  pose bla :=\nrmm_law2 _ _ _ _\n(@Theta_dens.unary_theta_dens)\nX (prod_choiceType Y S) k.\n  rewrite /= in bla.\n  unshelve eapply equal_f in bla. exact m.\n  rewrite /=. assumption.\nQed.\n\n\nLet SD_bind\n{A B : choiceType}\n(m : SDistr_carrier A)\n(k : A -> SDistr_carrier B) :=\nSDistr_bind A B k m.\nLet SD_ret {A : choiceType}\n(a : A) :=\nSDistr_unit A a.\n\nLemma θ_dens_OF_θ0_sample_c_s0 (s0:S) :\nθ_dens (θ0 sample_c s0)\n=\nSD_bind (utheta_dens_fld _ sploP) (fun r =>\nSD_bind (utheta_dens_fld _ (θ0 c s0)) (fun asc => let (a,sc) := asc in\nSDistr_unit _ (a,r,sc))).\nProof.\n  rewrite θ0_OF_sample_c_s0.\n  rewrite !/θ_dens.\n  rewrite utheta_dens_vs_bind.\n  rewrite !/SD_bind.\n  rewrite /=.\n  rewrite /SubDistr.SDistr_obligation_2.\n  f_equal.\n  apply boolp.funext. move=> r.\n  rewrite /Theta_dens.unary_theta_dens_obligation_1.\n  epose (hlp := utheta_dens_vs_bind _ _).\n  rewrite /= in hlp.\n  unfold Theta_dens.unary_theta_dens_obligation_1 in hlp.\n  unfold SubDistr.SDistr_obligation_2 in hlp.\n  erewrite hlp.\n  f_equal.\n  apply boolp.funext. move=> [aa ss].\n  clear hlp.\n  cbn. f_equal.\nQed.\n\n\n\nLemma θ_dens_OF_θ0_c_sample_s0 (s0:S) :\nθ_dens (θ0 c_sample s0)\n=\nSD_bind (utheta_dens_fld _ (θ0 c s0)) (fun asc => let (a,sc) := asc in\nSD_bind (utheta_dens_fld _ sploP) (fun r =>\nSDistr_unit _ (a,r,sc))).\nProof.\n  rewrite θ0_OF_c_sample_s0.\n  rewrite !/θ_dens.\n  rewrite utheta_dens_vs_bind.\nunshelve eassert (eq_cont :\n(λ x : choice_incl\n             (ord_functor_comp (OrderEnrichedRelativeAdjunctionsExamples.unaryTimesS1 S)\n                (OrderEnrichedRelativeAdjunctions.KleisliLeftAdjoint Frp) A),\n       utheta_dens_fld\n         (F_choice_prod_obj\n            ⟨ ord_functor_id ord_choiceType (prod_choiceType A (Arst (op_iota o))),\n            OrderEnrichedRelativeAdjunctionsExamples.mkConstFunc ord_choiceType ord_choiceType S\n              (prod_choiceType A (Arst (op_iota o))) ⟩)\n         (let (a, sc) := x in bindrFree sploP (λ r : choice_incl (Ar o), retrFree (a, r, sc))))\n=\nfun x => let (a,sc) := x in\nSD_bind (utheta_dens_fld _ sploP) (fun r =>\nSDistr_unit _ (a,r,sc))).\n    apply boolp.funext. move=> [aa ss]. rewrite utheta_dens_vs_bind. reflexivity.\n  rewrite eq_cont. rewrite /=.\n  rewrite !/SD_bind.\n  rewrite /SubDistr.SDistr_obligation_2.\n  rewrite /Theta_dens.unary_theta_dens_obligation_1.\n  reflexivity.\nQed.\n\n\nLemma SD_commutativity {X Y : choiceType}\n(p : SDistr X) (q : SDistr Y) :\nSD_bind p (fun x =>\nSD_bind q (fun y =>\nSD_ret (x,y)))\n=\nSD_bind q (fun y =>\nSD_bind p (fun x =>\nSD_ret (x,y))).\nProof.\n  rewrite !/SD_bind. rewrite !/SDistr_bind.\n  rewrite !/SD_ret. rewrite !/SDistr_unit.\n  rewrite !/dlet.\n  unlock. apply distr_ext. move=> [x y].\n  rewrite /mlet /=.\n  transitivity\n(psum\n  (fun x0 : X => psum (fun x1 : Y => p x0 * q x1 * dunit (T:=prod_choiceType X Y) (x0, x1) (x, y)))).\n{\n  apply eq_psum. move=> x0. rewrite -psumZ /=.\n  apply eq_psum. move=> y0 /=.\n  rewrite GRing.mulrA. reflexivity.\n  destruct p as [pmap p0 p_sum p1]. apply p0.\n}\n  symmetry.\n  transitivity\n(psum\n  (fun x0 : Y => psum (fun x1 : X => p x1 * q x0 * dunit (T:=prod_choiceType X Y) (x1, x0) (x, y)))).\n{\n    apply eq_psum. move=> y0. rewrite -psumZ /=.\n    apply eq_psum. move=> x0 /=.\n    rewrite GRing.mulrA. rewrite[q y0 * _] GRing.mulrC.\n    reflexivity.\n    destruct q as [qmap q0 q_sum q1]. apply q0.\n}\n  symmetry.\n(*   epose (hlp := psum_pair_swap *)\n(* (S:=fun (yx0 : Y * X) => let (y0,x0) := yx0 in *)\n(* p x0 * q y0 * dunit (T:=prod_choiceType X Y) (x0,y0) (x,y)) _). *)\n(*   rewrite -hlp. *)\n(*   rewrite psum_pair. reflexivity. *)\n(*   Unshelve<. *)\n  apply interchange_psum.\n{\n  move=> x0.\n  unshelve eapply eq_summable.\n    move=> y0. exact (q y0 * (p x0 * dunit (T:=_) (x0,y0)(x,y))).\n    move=> y0. rewrite GRing.mulrA. rewrite [q y0 * _] GRing.mulrC.\n    reflexivity.\n  apply (\n  summable_mu_wgtd (T:=Y)\n  (f:=fun y0 => p x0 * dunit (T:=_) (x0,y0) (x,y)) q ).\n  move=> y0. unshelve edestruct mulr_cp1.\n    exact R.\n  clear p1. destruct p0 as [le1 _].\n  apply /andP. split.\n  apply mulr_ge0.\n  destruct p as [pmap p_0 p_sum p_1]. apply p_0.\n  destruct (dunit (T:=_) (x0,y0)) as [umap u_0 u_sum u_1]. apply u_0.\n  apply le1. destruct p as [pmap p_0 p_sum p_1]. apply p_0.\n  destruct (dunit (T:=_) (x0,y0)) as [umap u_0 u_sum u_1]. apply u_0.\n  apply le1_mu1. apply le1_mu1.\n}\n  unshelve eapply eq_summable.\n    move=> x0. exact ( p x0 * psum (fun y0 => q y0 * dunit (T:=_) (x0,y0)(x,y))).\n  move=> x0. rewrite -psumZ. apply eq_psum. move=> y0 /=. rewrite GRing.mulrA. reflexivity.\n  destruct p as [pmap p_0 p_sum p_1]. apply p_0.\n  apply (\n  summable_mu_wgtd (T:=X)\n  (f:=fun x0 => psum (fun y0 : Y => q y0 * dunit (T:=prod_choiceType X Y) (x0, y0) (x, y))) p).\n  move=> x0. apply /andP. split.\n  apply ge0_psum.\n  unshelve eapply Order.POrderTheory.le_trans.\n    exact (psum q).\n  eapply le_psum.\n  move=> y0. apply/andP. split.\n  apply mulr_ge0.\n  destruct q as [qmap q_0 q_sum q_1]. apply q_0.\n  easy.\n(* ler_pimulr: forall [R : numDomainType] [x y : R], 0 <= y -> x <= 1 -> y * x <= y *)\n  apply ler_pimulr. destruct q as [qmap q_0 q_sum q_1]. apply q_0.\n  apply le1_mu1. easy. destruct q as [qmap q_0 q_sum q_1]. apply q_1.\nQed.\n\nLemma SD_commutativity' {X Y Z : choiceType}\n(p : SDistr X) (q : SDistr Y)\n(g : X -> Y -> SDistr Z) :\nSD_bind p (fun x =>\nSD_bind q (fun y =>\ng x y))\n=\nSD_bind q (fun y =>\nSD_bind p (fun x =>\ng x y)).\nProof.\n  transitivity\n(SD_bind (\n  SD_bind p (fun x =>\n  SD_bind q (fun y =>\n  SD_ret (x,y)))\n        ) (fun xy => let (x,y) := xy in\ng x y)).\n{\n  epose (bind_bind := (ord_relmon_law3 SDistr) _ _ _ _ _).\n  eapply equal_f in bind_bind.\n  rewrite /= in bind_bind.\n  unfold SubDistr.SDistr_obligation_2 in bind_bind.\n  rewrite !/SD_bind.\n  erewrite <- bind_bind.\n  f_equal. apply boolp.funext. move=> x.\n  clear bind_bind.\n  epose (bind_bind := (ord_relmon_law3 SDistr) _ _ _ _ _).\n  eapply equal_f in bind_bind.\n  rewrite /= in bind_bind.\n  unfold SubDistr.SDistr_obligation_2 in bind_bind.\n  erewrite <- bind_bind. f_equal.\n  apply boolp.funext ; move=> y.\n  clear bind_bind.\n  epose (bind_ret := (ord_relmon_law2 SDistr) _ _ _).\n  eapply equal_f in bind_ret. rewrite /= in bind_ret.\n  unfold SubDistr.SDistr_obligation_2 in bind_ret.\n  unfold SubDistr.SDistr_obligation_1 in bind_ret.\n  rewrite /SD_ret. erewrite bind_ret. reflexivity.\n}\n  rewrite SD_commutativity.\n  epose (bind_bind := (ord_relmon_law3 SDistr) _ _ _ _ _).\n  eapply equal_f in bind_bind.\n  rewrite /= in bind_bind.\n  unfold SubDistr.SDistr_obligation_2 in bind_bind.\n  rewrite !/SD_bind.\n  erewrite <- bind_bind.\n  f_equal. apply boolp.funext. move=> y.\n  clear bind_bind.\n  epose (bind_bind := (ord_relmon_law3 SDistr) _ _ _ _ _).\n  eapply equal_f in bind_bind.\n  rewrite /= in bind_bind.\n  unfold SubDistr.SDistr_obligation_2 in bind_bind.\n  erewrite <- bind_bind. f_equal.\n  apply boolp.funext ; move=> x.\n  clear bind_bind.\n  epose (bind_ret := (ord_relmon_law2 SDistr) _ _ _).\n  eapply equal_f in bind_ret. rewrite /= in bind_ret.\n  unfold SubDistr.SDistr_obligation_2 in bind_ret.\n  unfold SubDistr.SDistr_obligation_1 in bind_ret.\n  rewrite /SD_ret. erewrite bind_ret. reflexivity.\nQed.\n\n\nLemma sample_c_is_c_sample (s0 : S):\nθ_dens (θ0 sample_c s0)\n=\nθ_dens (θ0 c_sample s0).\nProof.\n  rewrite (θ_dens_OF_θ0_sample_c_s0 s0).\n  rewrite (θ_dens_OF_θ0_c_sample_s0 s0).\n  unshelve epose (hlp :=\nSD_commutativity'\n(utheta_dens_fld (Ar o) sploP)\n(utheta_dens_fld _ (θ0 c s0)) _).\n    shelve.\n    move=> rr /= [aa ss]. exact (SDistr_unit _ (aa,rr,ss)).\n  rewrite hlp. f_equal.\n  apply boolp.funext. move=> [a sc]. f_equal.\nQed.\n\n\nEnd samplerC_rule.\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/rules/RulesStateProb.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.25392304968007856}}
{"text": "From Undecidability.L Require Export Util.L_facts.\nFrom Undecidability.L.Tactics Require Import Lproc Lbeta Lrewrite Reflection.\nRequire Import ListTactics.\nImport L_Notations.\n\nLocal Ltac wLsimpl' _n := intros;try reflexivity';try standardizeGoal _n ; try reflexivity'.\nLocal Ltac wLsimpl := wLsimpl' 100.\n\n(* Lsimpl' uses correctnes lemmas and wLsimpl*)\nLtac Lsimpl' :=\n  match goal with\n  | |- eval ?s _ => assert (lambda s) by Lproc;split;[ (exact (starR _ _);fail 1)|Lproc]\n  | |- eval ?s _ => (progress (eapply eval_helper;[Lsimpl';reflexivity|]))\n\n  | _ => try Lrewrite;try wLsimpl' 100\n  end.\n\nLtac Lreduce :=\n  repeat progress ( (Lrewrite;try Lbeta) || Lbeta).\n\nLtac Lsimpl :=\n  lazymatch goal with\n  | |- _ >( _ ) _ => repeat progress Lbeta;try Lreflexivity\n  | |- _ => LrewriteSimpl\n  end.\n\nLtac LsimplHypo := standardizeHypo 100.\n\n\n\nTactic Notation \"closedRewrite\" :=\n  match goal with\n    | [ |- context[subst ?s _ _] ] =>\n      let cl := fresh \"cl\" in assert (cl:closed s);[Lproc|rewrite !cl;clear cl]\n                                                     \n  end.\n\nTactic Notation \"closedRewrite\" \"in\" hyp(h):=\n  match type of h with\n    | context[subst ?s _ _] =>\n      let cl := fresh \"cl\" in assert (cl:closed s);[Lproc|rewrite !cl in h;clear cl]\n  end.\n\nTactic Notation \"redStep\" \"at\" integer(pos) := rewrite step_Lproc at pos;[simpl;try closedRewrite|Lproc].\n\nTactic Notation \"redStep\" \"in\" hyp(h) \"at\" integer(pos) := rewrite step_Lproc in h at pos;[simpl in h;try closedRewrite in h|Lproc].\n(*\nTactic Notation \"redStep\" := redStep at 1.\n*)\nTactic Notation \"redStep\" \"in\" hyp(h) := redStep in h at 1.\n\n(* register needed lemmas:*)\n\n\nLemma rho_correct s t : proc s -> lambda t -> rho s t >* s (rho s) t.\nProof.\n  intros. unfold rho,r. redStep at 1. apply star_trans_l. now Lsimpl. \nQed.\n\n(* Hint Resolve rho_correct : Lrewrite. *)\n\n\nLemma rho_inj s t: rho s = rho t -> s = t.\nProof.\n  unfold rho,r. congruence.\nQed.\n\n\n#[export] Hint Resolve rho_lambda rho_cls : LProc.\n\nTactic Notation \"recStep\" constr(P) \"at\" integer(i):=\n  match eval lazy [P] in P with\n      | rho ?rP => unfold P;rewrite rho_correct at i;[|Lproc..];fold P;try unfold rP\n  end.\n\nTactic Notation \"recStep\" constr(P) :=\n  intros;recStep P at 1.\n\n(*\nLemma rClosed_closed s: recProc s -> proc s.\nProof.\n  intros [? [? ?]]. subst. split; auto with LProc.\nQed.\n\n#[export] Hint Resolve rClosed_closed : LProc cbv.\n *)\n\nLemma I_proc : proc I.\nProof.\n  fLproc.\nQed.\n\nLemma K_proc : proc K.\nProof.\n  fLproc.\nQed.\n\nLemma omega_proc : proc omega.\nProof.\n  fLproc.\nQed.\n\nLemma Omega_closed : closed Omega.\nProof.\n  fLproc. \nQed.\n\n#[export] Hint Resolve I_proc K_proc omega_proc Omega_closed: LProc.\n\n#[export] Hint Extern 0 (I >(_) _)=> unfold I;reflexivity : Lrewrite.\n#[export] Hint Extern 0 (K >(_) _)=> unfold K;reflexivity : Lrewrite.\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/L/Tactics/Lsimpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.25392142869728274}}
{"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\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. condtac; ss; i.\n      * des. subst. exploit Memory.remove_get0; eauto. i. des. congr.\n      * congr.\n  - exploit Memory.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: 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. 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: @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.\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 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  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/prop/PromiseConsistent.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.25391544689767137}}
{"text": "(*\nAn artificially slow tactic, to test asynchronicity and delays between server and client\n*)\n\nLtac ackerman m n :=\n  match m with\n    | O => constr:(S n)\n    | S ?m' =>\n      match n with\n        | O =>\n          let res := ackerman m' 1 in\n          constr:(res)\n        | S ?n' =>\n          let tmp1 := ackerman m n' in\n          let tmp2 := ackerman m' tmp1 in\n          constr:(tmp2)\n      end\n  end.\n\n(* notree *)\nTheorem t : False.\nProof.\n  let res := ackerman 3 5 in pose res.\n  idtac \"to be processed\".\n  idtac \"does idtac print this?\".\nQed.\n", "meta": {"author": "Ptival", "repo": "PeaCoq", "sha": "4d186879910a327455e7b7b239d58a9502145680", "save_path": "github-repos/coq/Ptival-PeaCoq", "path": "github-repos/coq/Ptival-PeaCoq/PeaCoq-4d186879910a327455e7b7b239d58a9502145680/web/coq/tests/slow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2539059321396022}}
{"text": "Require Import GateCancellation.\nRequire Import HadamardReduction.\nRequire Import NotPropagation.\nRequire Import Optimize1qGates.\nRequire Import RotationMerging.\nRequire Import RzQGateSet.\nRequire Import SwapRoute.\nRequire Import MappingValidation.\nRequire Import GreedyLayout.\nRequire Import FullGateSet.\nImport FullList.\n\nLocal Close Scope Q_scope.\nLocal Close Scope C_scope.\nLocal Close Scope R_scope.\n\n(** This file contains the VOQC transformations that are extracted to OCaml, \n   along with their correctness properties. The definitions and proofs in this \n   file are largely wrappers around definitions and proofs in other files. **)\n\nDefinition circ := full_ucom_l.\n\nDefinition layout := Layouts.layout.\n\nDefinition c_graph : Type := nat * (nat -> nat -> bool).\nDefinition graph_dim (cg : c_graph) := fst cg.\nDefinition is_in_graph (cg : c_graph) := snd cg.\n\nDefinition path_finding_fun : Type := nat -> nat -> list nat.\nDefinition qubit_ordering_fun : Type := option nat -> list nat.\n\n(* Cast function changes the dependent type; it will be extracted to a no-op *)\nFixpoint cast {dim} (c : circ dim) dim' : @circ dim' := \n  match c with \n  | [] => []\n  | App1 g m :: t => App1 g m :: cast t dim'\n  | App2 g m n :: t => App2 g m n :: cast t dim'\n  | App3 g m n p :: t => App3 g m n p :: cast t dim'\n  end.\n\n(** * Utility functions **)\n\nDefinition check_well_typed {dim} (c : circ dim) (n : nat) :=\n  uc_well_typed_l_b n (cast c n).\nDefinition convert_to_ibm {dim} (c : circ dim) :=\n  FullGateSet.convert_to_ibm c.\nDefinition convert_to_rzq {dim} (c : circ dim) :=\n  FullGateSet.convert_to_rzq c.\nDefinition replace_rzq {dim} (c : circ dim) :=\n  FullGateSet.replace_rzq c.\nDefinition decompose_to_cnot {dim} (c : circ dim) :=\n  FullGateSet.decompose_to_cnot c.\n\nLemma check_well_typed_correct : forall {dim} (c : circ dim) n,\n  check_well_typed c n = true <-> uc_well_typed_l (cast c n).\nProof. intros. apply uc_well_typed_l_b_equiv. Qed.\n\nLemma convert_to_ibm_preserves_semantics : forall {dim} (c : circ dim),\n  (convert_to_ibm c =l= c)%ucom.\nProof. intros. apply FullGateSet.convert_to_ibm_sound. Qed.\n\nLtac show_preserves_WT H :=\n  eapply uc_equiv_l_implies_WT;\n  [ symmetry; apply H | assumption ].\n\nLtac show_preserves_WT_cong H :=\n  eapply uc_cong_l_implies_WT;\n  [ symmetry; apply H | assumption ].\n\nLemma convert_to_ibm_preserves_WT : forall {dim} (c : circ dim),\n  uc_well_typed_l c -> uc_well_typed_l (convert_to_ibm c).\nProof. intros dim c H. show_preserves_WT (convert_to_ibm_preserves_semantics c). Qed.\n\nLemma convert_to_ibm_preserves_mapping : forall {dim} (l : full_ucom_l dim) (cg : c_graph),\n  respects_constraints_directed (is_in_graph cg) U_CX l ->\n  respects_constraints_directed (is_in_graph cg) U_CX (convert_to_ibm l).\nProof. \n  intros. \n  apply FullGateSet.convert_to_ibm_preserves_mapping.\n  assumption.\nQed.\n\nLemma convert_to_ibm_uses_ibm_gates : forall {dim} (c : circ dim),\n  forall_gates only_ibm (convert_to_ibm c).\nProof. intros. apply FullGateSet.convert_to_ibm_gates. Qed.\n\nLemma convert_to_rzq_preserves_semantics : forall {dim} (c : circ dim),\n  (convert_to_rzq c ≅l≅ c)%ucom.\nProof. intros. apply FullGateSet.convert_to_rzq_sound. Qed.\n\nLemma convert_to_rzq_preserves_WT : forall {dim} (c : circ dim),\n  uc_well_typed_l c -> uc_well_typed_l (convert_to_rzq c).\nProof. \n  intros dim c H. \n  show_preserves_WT_cong (convert_to_rzq_preserves_semantics c). \nQed.\n\nLemma convert_to_rzq_preserves_mapping : forall {dim} (l : full_ucom_l dim) (cg : c_graph),\n  respects_constraints_directed (is_in_graph cg) U_CX l ->\n  respects_constraints_directed (is_in_graph cg) U_CX (convert_to_rzq l).\nProof. \n  intros. \n  apply FullGateSet.convert_to_rzq_preserves_mapping.\n  assumption.\nQed.\n\nLemma convert_to_rzq_uses_rzq_gates : forall {dim} (c : circ dim),\n  forall_gates only_rzq (convert_to_rzq c).\nProof. intros. apply FullGateSet.convert_to_rzq_gates. Qed.\n\nLemma replace_rzq_preserves_semantics : forall {dim} (c : circ dim),\n  (replace_rzq c =l= c)%ucom.\nProof. intros. apply FullGateSet.replace_rzq_sound. Qed.\n\nLemma replace_rzq_preserves_WT : forall {dim} (c : circ dim),\n  uc_well_typed_l c -> uc_well_typed_l (replace_rzq c).\nProof. intros dim c H. show_preserves_WT (replace_rzq_preserves_semantics c). Qed.\n\nLemma replace_rzq_preserves_mapping : forall {dim} (l : full_ucom_l dim) (cg : c_graph),\n  respects_constraints_directed (is_in_graph cg) U_CX l ->\n  respects_constraints_directed (is_in_graph cg) U_CX (replace_rzq l).\nProof. \n  intros. \n  apply FullGateSet.replace_rzq_preserves_mapping.\n  assumption.\nQed.\n\nLemma replace_rzq_does_not_use_rzq_gates : forall {dim} (c : circ dim),\n  forall_gates no_rzq (replace_rzq c).\nProof. intros. apply FullGateSet.replace_rzq_gates. Qed.\n\nLemma decompose_to_cnot_preserves_semantics : forall {dim} (c : circ dim),\n  (decompose_to_cnot c =l= c)%ucom.\nProof. intros. apply FullGateSet.decompose_to_cnot_sound. Qed.\n\nLemma decompose_to_cnot_preserves_WT : forall {dim} (c : circ dim),\n  uc_well_typed_l c -> uc_well_typed_l (decompose_to_cnot c).\nProof.\n  intros dim c H.\n  show_preserves_WT (decompose_to_cnot_preserves_semantics c).\nQed.\n\nLemma decompose_to_cnot_uses_cnot_gates : forall {dim} (c : circ dim),\n  forall_gates only_cnots (decompose_to_cnot c).\nProof. intros. apply FullGateSet.decompose_to_cnot_gates. Qed.\n\nDefinition count_I {dim} (l : circ dim) :=\n  length (filter (fun g => match g with | App1 U_I _ => true | _ => false end) l).\nDefinition count_X {dim} (l : circ dim) :=\n  length (filter (fun g => match g with | App1 U_X _ => true | _ => false end) l).\nDefinition count_Y {dim} (l : circ dim) :=\n  length (filter (fun g => match g with | App1 U_Y _ => true | _ => false end) l).\nDefinition count_Z {dim} (l : circ dim) :=\n  length (filter (fun g => match g with | App1 U_Z _ => true | _ => false end) l).\nDefinition count_H {dim} (l : circ dim) :=\n  length (filter (fun g => match g with | App1 U_H _ => true | _ => false end) l).\nDefinition count_S {dim} (l : circ dim) :=\n  length (filter (fun g => match g with | App1 U_S _ => true | _ => false end) l).\nDefinition count_T {dim} (l : circ dim) :=\n  length (filter (fun g => match g with | App1 U_T _ => true | _ => false end) l).\nDefinition count_Sdg {dim} (l : circ dim) :=\n  length (filter (fun g => match g with | App1 U_Sdg _ => true | _ => false end) l).\nDefinition count_Tdg {dim} (l : circ dim) :=\n  length (filter (fun g => match g with | App1 U_Tdg _ => true | _ => false end) l).\nDefinition count_Rx {dim} (l : circ dim) :=\n  length (filter (fun g => match g with | App1 (U_Rx _) _ => true | _ => false end) l).\nDefinition count_Ry {dim} (l : circ dim) :=\n  length (filter (fun g => match g with | App1 (U_Ry _) _ => true | _ => false end) l).\nDefinition count_Rz {dim} (l : circ dim) :=\n  length (filter (fun g => match g with | App1 (U_Rz _) _ => true | _ => false end) l).\nDefinition count_Rzq {dim} (l : circ dim) :=\n  length (filter (fun g => match g with | App1 (U_Rzq _) _ => true | _ => false end) l).\nDefinition count_U1 {dim} (l : circ dim) :=\n  length (filter (fun g => match g with | App1 (U_U1 _) _ => true | _ => false end) l).\nDefinition count_U2 {dim} (l : circ dim) :=\n  length (filter (fun g => match g with | App1 (U_U2 _ _) _ => true | _ => false end) l).\nDefinition count_U3 {dim} (l : circ dim) :=\n  length (filter (fun g => match g with | App1 (U_U3 _ _ _) _ => true | _ => false end) l).\nDefinition count_CX {dim} (l : circ dim) :=\n  length (filter (fun g => match g with | App2 U_CX _ _ => true | _ => false end) l).\nDefinition count_CZ {dim} (l : circ dim) :=\n  length (filter (fun g => match g with | App2 U_CZ _ _ => true | _ => false end) l).\nDefinition count_SWAP {dim} (l : circ dim) :=\n  length (filter (fun g => match g with | App2 U_SWAP _ _ => true | _ => false end) l).\nDefinition count_CCX {dim} (l : circ dim) :=\n  length (filter (fun g => match g with | App3 U_CCX _ _ _ => true | _ => false end) l).\nDefinition count_CCZ {dim} (l : circ dim) :=\n  length (filter (fun g => match g with | App3 U_CCZ _ _ _ => true | _ => false end) l).\n\nDefinition count_1q {dim} (l : circ dim) :=\n  length (filter (fun g => match g with | App1 _ _ => true | _ => false end) l).\nDefinition count_2q {dim} (l : circ dim) :=\n  length (filter (fun g => match g with | App2 _ _ _ => true | _ => false end) l).\nDefinition count_3q {dim} (l : circ dim) :=\n  length (filter (fun g => match g with | App3 _ _ _ _ => true | _ => false end) l).\nDefinition count_total {dim} (l : circ dim) := length l.\n\nDefinition count_rzq_clifford {dim} (l : circ dim) :=\n  let f g := match g with\n             | App1 (U_Rzq q) _ =>\n                 let q' := RzQGateSet.bound q in\n                 Qeq_bool q' zero_Q || Qeq_bool q' half_Q || \n                   Qeq_bool q' three_halves_Q || Qeq_bool q' one_Q\n             | _ => false end in\n  length (filter f l).\n\nLtac rewrite_count :=\n  symmetry; rewrite cons_to_app; rewrite filter_app, app_length; reflexivity. \n\nLemma count_1q_correct : forall {dim} (l : circ dim),\n  count_1q l \n    = (count_I l + count_X l + count_Y l + count_Z l +\n       count_H l + count_S l + count_T l + count_Sdg l + count_Tdg l +\n       count_Rx l + count_Ry l + count_Rz l + count_Rzq l + \n       count_U1 l + count_U2 l + count_U3 l)%nat.\nProof.\n  intros dim l.\n  induction l; simpl.\n  reflexivity.\n  replace (count_1q (a :: l)) with (count_1q [a] + count_1q l) \n    by (unfold count_1q; rewrite_count).\n  replace (count_I (a :: l)) with (count_I [a] + count_I l) \n    by (unfold count_I; rewrite_count).\n  replace (count_X (a :: l)) with (count_X [a] + count_X l) \n    by (unfold count_X; rewrite_count).\n  replace (count_Y (a :: l)) with (count_Y [a] + count_Y l) \n    by (unfold count_Y; rewrite_count).\n  replace (count_Z (a :: l)) with (count_Z [a] + count_Z l) \n    by (unfold count_Z; rewrite_count).\n  replace (count_H (a :: l)) with (count_H [a] + count_H l) \n    by (unfold count_H; rewrite_count).\n  replace (count_S (a :: l)) with (count_S [a] + count_S l) \n    by (unfold count_S; rewrite_count).\n  replace (count_T (a :: l)) with (count_T [a] + count_T l) \n    by (unfold count_T; rewrite_count).\n  replace (count_Sdg (a :: l)) with (count_Sdg [a] + count_Sdg l) \n    by (unfold count_Sdg; rewrite_count).\n  replace (count_Tdg (a :: l)) with (count_Tdg [a] + count_Tdg l) \n    by (unfold count_Tdg; rewrite_count).\n  replace (count_Rx (a :: l)) with (count_Rx [a] + count_Rx l) \n    by (unfold count_Rx; rewrite_count).\n  replace (count_Ry (a :: l)) with (count_Ry [a] + count_Ry l) \n    by (unfold count_Ry; rewrite_count).\n  replace (count_Rz (a :: l)) with (count_Rz [a] + count_Rz l) \n    by (unfold count_Rz; rewrite_count).\n  replace (count_Rzq (a :: l)) with (count_Rzq [a] + count_Rzq l) \n    by (unfold count_Rzq; rewrite_count).\n  replace (count_U1 (a :: l)) with (count_U1 [a] + count_U1 l) \n    by (unfold count_U1; rewrite_count).\n  replace (count_U2 (a :: l)) with (count_U2 [a] + count_U2 l) \n    by (unfold count_U2; rewrite_count).\n  replace (count_U3 (a :: l)) with (count_U3 [a] + count_U3 l) \n    by (unfold count_U3; rewrite_count).\n  rewrite IHl. clear.\n  repeat rewrite Nat.add_assoc.\n  repeat rewrite (Nat.add_comm _ (_ [a])).\n  repeat rewrite Nat.add_assoc.\n  do 16 (apply f_equal2; auto).\n  destruct a; dependent destruction f; reflexivity.\nQed.\n\nLemma count_2q_correct : forall {dim} (l : circ dim),\n  count_2q l \n    = (count_CX l + count_CZ l + count_SWAP l)%nat.\nProof.\n  intros dim l.\n  induction l; simpl.\n  reflexivity.\n  replace (count_2q (a :: l)) with (count_2q [a] + count_2q l) \n    by (unfold count_2q; rewrite_count).\n  replace (count_CX (a :: l)) with (count_CX [a] + count_CX l) \n    by (unfold count_CX; rewrite_count).\n  replace (count_CZ (a :: l)) with (count_CZ [a] + count_CZ l) \n    by (unfold count_CZ; rewrite_count).\n  replace (count_SWAP (a :: l)) with (count_SWAP [a] + count_SWAP l) \n    by (unfold count_SWAP; rewrite_count).\n  rewrite IHl. clear.\n  repeat rewrite Nat.add_assoc.\n  repeat rewrite (Nat.add_comm _ (_ [a])).\n  repeat rewrite Nat.add_assoc.\n  do 3 (apply f_equal2; auto).\n  destruct a; dependent destruction f; reflexivity.\nQed.\n\nLemma count_3q_correct : forall {dim} (l : circ dim),\n  count_3q l \n    = (count_CCX l + count_CCZ l)%nat.\nProof.\n  intros dim l.\n  induction l; simpl.\n  reflexivity.\n  replace (count_3q (a :: l)) with (count_3q [a] + count_3q l) \n    by (unfold count_3q; rewrite_count).\n  replace (count_CCX (a :: l)) with (count_CCX [a] + count_CCX l) \n    by (unfold count_CCX; rewrite_count).\n  replace (count_CCZ (a :: l)) with (count_CCZ [a] + count_CCZ l) \n    by (unfold count_CCZ; rewrite_count).\n  rewrite IHl. clear.\n  repeat rewrite Nat.add_assoc.\n  repeat rewrite (Nat.add_comm _ (_ [a])).\n  repeat rewrite Nat.add_assoc.\n  do 2 (apply f_equal2; auto).\n  destruct a; dependent destruction f; reflexivity.\nQed.\n\nLemma count_total_correct : forall {dim} (l : circ dim),\n  count_total l = (count_1q l + count_2q l + count_3q l)%nat.\nProof.\n  intros dim l.\n  induction l; simpl.\n  reflexivity.\n  replace (count_1q (a :: l)) with (count_1q [a] + count_1q l) \n    by (unfold count_1q; rewrite_count).\n  replace (count_2q (a :: l)) with (count_2q [a] + count_2q l) \n    by (unfold count_2q; rewrite_count).\n  replace (count_3q (a :: l)) with (count_3q [a] + count_3q l) \n    by (unfold count_3q; rewrite_count).\n  rewrite IHl. clear.\n  destruct a; dependent destruction f; simpl; lia.\nQed.\n\n(** * IBM gate set optimizations **)\n\nDefinition optimize_ibm {dim} (c : circ dim) : circ dim :=\n  IBM_to_full (Optimize1qGates.optimize_1q_gates (full_to_IBM c)).\n\nLemma optimize_ibm_preserves_semantics : forall {dim} (c : circ dim),\n  uc_well_typed_l c -> (optimize_ibm c ≅l≅ c)%ucom.\nProof. \n  intros dim c H.\n  unfold optimize_ibm.\n  erewrite IBM_to_full_cong.\n  apply uc_equiv_cong_l.\n  apply IBM_to_full_inv.\n  apply Optimize1qGates.optimize_1q_gates_sound.\n  apply FullGateSet.full_to_IBM_WT.\n  assumption.\nQed.\n\nLemma optimize_ibm_preserves_WT : forall {dim} (c : circ dim),\n  uc_well_typed_l c -> uc_well_typed_l (optimize_ibm c).\nProof.\n  intros dim c H.\n  show_preserves_WT_cong (optimize_ibm_preserves_semantics c H).\nQed.\n\nLemma optimize_ibm_preserves_mapping : forall {dim} (c : circ dim) (cg : c_graph),\n  respects_constraints_directed (is_in_graph cg) U_CX c -> \n  respects_constraints_directed (is_in_graph cg) U_CX (optimize_ibm c).\nProof. \n  intros. \n  apply IBM_to_full_preserves_mapping.\n  apply Optimize1qGates.optimize_1q_gates_respects_constraints.\n  apply full_to_IBM_preserves_mapping.\n  assumption.\nQed.\n\n(** * RzQ gate set optimizations **)\n\nDefinition not_propagation {dim} (c : circ dim) : circ dim :=\n  RzQ_to_full (NotPropagation.not_propagation (full_to_RzQ c)).\n\nDefinition hadamard_reduction {dim} (c : circ dim) : circ dim :=\n  RzQ_to_full (HadamardReduction.hadamard_reduction (full_to_RzQ c)).\n\nDefinition cancel_single_qubit_gates {dim} (c : circ dim) : circ dim :=\n  RzQ_to_full (GateCancellation.cancel_single_qubit_gates (full_to_RzQ c)).\n\nDefinition cancel_two_qubit_gates {dim} (c : circ dim) : circ dim :=\n  RzQ_to_full (GateCancellation.cancel_two_qubit_gates (full_to_RzQ c)).\n\nDefinition merge_rotations {dim} (c : circ dim) : circ dim :=\n  RzQ_to_full (RotationMerging.merge_rotations (full_to_RzQ c)).\n\n(* optimize_nam function applies our optimizations in the following order,\n   as designed by Nam et al. :\n   0, 1, 3, 2, 3, 1, 2, 4, 3, 2 \n   \n   0 - not propagation\n   1 - hadamard reduction\n   2 - single qubit gate cancellation\n   3 - two qubit gate cancellation\n   4 - rotation merging *) \n\nDefinition optimize_nam {dim} (c : circ dim) : circ dim :=\n  RzQ_to_full\n    (GateCancellation.cancel_single_qubit_gates \n      (GateCancellation.cancel_two_qubit_gates \n        (RotationMerging.merge_rotations\n          (GateCancellation.cancel_single_qubit_gates \n            (HadamardReduction.hadamard_reduction \n              (GateCancellation.cancel_two_qubit_gates \n                (GateCancellation.cancel_single_qubit_gates \n                  (GateCancellation.cancel_two_qubit_gates \n                    (HadamardReduction.hadamard_reduction \n                      (NotPropagation.not_propagation \n                        (full_to_RzQ c))))))))))). \n\n(* Light version of the optimizer that excludes rotation merging\n   (used for evaluating on QFT & adder programs). *)\nDefinition optimize_nam_light {dim} (c : circ dim) : circ dim :=\n  RzQ_to_full\n    (GateCancellation.cancel_single_qubit_gates \n      (HadamardReduction.hadamard_reduction \n        (GateCancellation.cancel_two_qubit_gates \n          (GateCancellation.cancel_single_qubit_gates \n            (GateCancellation.cancel_two_qubit_gates \n              (HadamardReduction.hadamard_reduction \n                (NotPropagation.not_propagation \n                  (full_to_RzQ c)))))))).\n\n(* LCR optimizer for multiple iterations. *)\nDefinition optimize_nam_lcr {dim} (c : circ dim) : option (circ dim * circ dim * circ dim) :=\n  LCR c optimize_nam (fun n => @match_gate n).\n\nLemma cancel_single_qubit_gates_sound' : forall {dim} (l : RzQ_ucom_l dim),\n  uc_well_typed_l l -> RzQList.uc_cong_l (GateCancellation.cancel_single_qubit_gates l) l.\nProof. \n  intros. apply RzQList.uc_equiv_cong_l. \n  apply GateCancellation.cancel_single_qubit_gates_sound. assumption. \nQed.\n\nLemma cancel_two_qubit_gates_sound' : forall {dim} (l : RzQ_ucom_l dim),\n  uc_well_typed_l l -> RzQList.uc_cong_l (GateCancellation.cancel_two_qubit_gates l) l.\nProof. \n  intros. apply RzQList.uc_equiv_cong_l. \n  apply GateCancellation.cancel_two_qubit_gates_sound. assumption. \nQed.\n\nLemma merge_rotations_sound' : forall {dim} (l : RzQ_ucom_l dim),\n  uc_well_typed_l l -> RzQList.uc_cong_l (RotationMerging.merge_rotations l) l.\nProof. \n  intros. apply RzQList.uc_equiv_cong_l. \n  apply RotationMerging.merge_rotations_sound. assumption.\nQed.\n\nLtac show_preserves_semantics_nam :=\n  unfold not_propagation, hadamard_reduction, cancel_single_qubit_gates, cancel_two_qubit_gates, merge_rotations, optimize_nam, optimize_nam_light;\n  erewrite RzQ_to_full_cong;\n  [ apply RzQ_to_full_inv \n  | repeat (try rewrite NotPropagation.not_propagation_sound;\n            try rewrite HadamardReduction.hadamard_reduction_sound;\n            try rewrite cancel_single_qubit_gates_sound';\n            try rewrite cancel_two_qubit_gates_sound';\n            try rewrite merge_rotations_sound';\n            try apply FullGateSet.full_to_RzQ_WT;\n            try apply NotPropagation.not_propagation_WT;\n            try apply HadamardReduction.hadamard_reduction_WT;\n            try apply GateCancellation.cancel_single_qubit_gates_WT;\n            try apply GateCancellation.cancel_two_qubit_gates_WT;\n            try apply RotationMerging.merge_rotations_WT;\n            try assumption; try reflexivity) ].\n\nLemma not_propagation_preserves_semantics : forall {dim} (c : circ dim),\n  uc_well_typed_l c -> (not_propagation c ≅l≅ c)%ucom.\nProof. intros. show_preserves_semantics_nam. Qed.\n\nLemma not_propagation_preserves_WT : forall {dim} (c : circ dim),\n  uc_well_typed_l c -> uc_well_typed_l (not_propagation c).\nProof.\n  intros dim c H.\n  show_preserves_WT_cong (not_propagation_preserves_semantics c H).\nQed.\n\nLtac show_preserves_mapping_nam :=\n  unfold not_propagation, hadamard_reduction, cancel_single_qubit_gates, cancel_two_qubit_gates, merge_rotations, optimize_nam, optimize_nam_light;\n  repeat (try apply RzQ_to_full_preserves_mapping;\n          try apply NotPropagation.not_propagation_respects_constraints;\n          try apply HadamardReduction.hadamard_reduction_respects_constraints;\n          try apply GateCancellation.cancel_single_qubit_gates_respects_constraints;\n          try apply GateCancellation.cancel_two_qubit_gates_respects_constraints;\n          try apply RotationMerging.merge_rotations_respects_constraints;\n          try apply full_to_RzQ_preserves_mapping;\n          try assumption).\n\nLemma not_propagation_preserves_mapping : forall {dim} (c : circ dim) (cg : c_graph),\n  respects_constraints_directed (is_in_graph cg) U_CX c -> \n  respects_constraints_directed (is_in_graph cg) U_CX (not_propagation c).\nProof. intros. show_preserves_mapping_nam. Qed.\n\nLemma hadamard_reduction_preserves_semantics : forall {dim} (c : circ dim),\n  (hadamard_reduction c ≅l≅ c)%ucom.\nProof. intros. show_preserves_semantics_nam. Qed.\n\nLemma hadamard_reduction_preserves_WT : forall {dim} (c : circ dim),\n  uc_well_typed_l c -> uc_well_typed_l (hadamard_reduction c).\nProof.\n  intros dim c H.\n  show_preserves_WT_cong (hadamard_reduction_preserves_semantics c).\nQed.\n\nLemma hadamard_reduction_preserves_mapping : forall {dim} (c : circ dim) (cg : c_graph),\n  respects_constraints_directed (is_in_graph cg) U_CX c -> \n  respects_constraints_directed (is_in_graph cg) U_CX (hadamard_reduction c).\nProof. intros. show_preserves_mapping_nam. Qed.\n\nLemma cancel_single_qubit_gates_preserves_semantics : forall {dim} (c : circ dim),\n  uc_well_typed_l c -> (cancel_single_qubit_gates c ≅l≅ c)%ucom.\nProof. intros. show_preserves_semantics_nam. Qed.\n\nLemma cancel_single_qubit_gates_preserves_WT : forall {dim} (c : circ dim),\n  uc_well_typed_l c -> uc_well_typed_l (cancel_single_qubit_gates c).\nProof.\n  intros dim c H.\n  show_preserves_WT_cong (cancel_single_qubit_gates_preserves_semantics c H).\nQed.\n\nLemma cancel_single_qubit_gates_preserves_mapping : forall {dim} (c : circ dim) (cg : c_graph),\n  respects_constraints_directed (is_in_graph cg) U_CX c -> \n  respects_constraints_directed (is_in_graph cg) U_CX (cancel_single_qubit_gates c).\nProof. intros. show_preserves_mapping_nam. Qed.\n\nLemma cancel_two_qubit_gates_preserves_semantics : forall {dim} (c : circ dim),\n  uc_well_typed_l c -> (cancel_two_qubit_gates c ≅l≅ c)%ucom.\nProof. intros. show_preserves_semantics_nam. Qed.\n\nLemma cancel_two_qubit_gates_preserves_WT : forall {dim} (c : circ dim),\n  uc_well_typed_l c -> uc_well_typed_l (cancel_two_qubit_gates c).\nProof.\n  intros dim c H.\n  show_preserves_WT_cong (cancel_two_qubit_gates_preserves_semantics c H).\nQed.\n\nLemma cancel_two_qubit_gates_preserves_mapping : forall {dim} (c : circ dim) (cg : c_graph),\n  respects_constraints_directed (is_in_graph cg) U_CX c -> \n  respects_constraints_directed (is_in_graph cg) U_CX (cancel_two_qubit_gates c).\nProof. intros. show_preserves_mapping_nam. Qed.\n\nLemma merge_rotations_preserves_semantics : forall {dim} (c : circ dim),\n  uc_well_typed_l c -> (merge_rotations c ≅l≅ c)%ucom.\nProof. intros. show_preserves_semantics_nam. Qed.\n\nLemma merge_rotations_preserves_WT : forall {dim} (c : circ dim),\n  uc_well_typed_l c -> uc_well_typed_l (merge_rotations c).\nProof.\n  intros dim c H.\n  show_preserves_WT_cong (merge_rotations_preserves_semantics c H).\nQed.\n\nLemma merge_rotations_preserves_mapping : forall {dim} (c : circ dim) (cg : c_graph),\n  respects_constraints_directed (is_in_graph cg) U_CX c -> \n  respects_constraints_directed (is_in_graph cg) U_CX (merge_rotations c).\nProof. intros. show_preserves_mapping_nam. Qed.\n\nLemma optimize_nam_preserves_semantics : forall {dim} (c : circ dim),\n  uc_well_typed_l c -> (optimize_nam c ≅l≅ c)%ucom.\nProof. intros. show_preserves_semantics_nam. Qed.\n\nLemma optimize_nam_preserves_WT : forall {dim} (c : circ dim),\n  uc_well_typed_l c -> uc_well_typed_l (optimize_nam c).\nProof.\n  intros dim c H.\n  show_preserves_WT_cong (optimize_nam_preserves_semantics c H).\nQed.\n\nLemma optimize_nam_preserves_mapping : forall {dim} (c : circ dim) (cg : c_graph),\n  respects_constraints_directed (is_in_graph cg) U_CX c -> \n  respects_constraints_directed (is_in_graph cg) U_CX (optimize_nam c).\nProof. intros. show_preserves_mapping_nam. Qed.\n\nLemma optimize_nam_light_preserves_semantics : forall {dim} (c : circ dim),\n  uc_well_typed_l c -> (optimize_nam_light c ≅l≅ c)%ucom.\nProof. intros. show_preserves_semantics_nam. Qed.\n\nLemma optimize_nam_light_preserves_WT : forall {dim} (c : circ dim),\n  uc_well_typed_l c -> uc_well_typed_l (optimize_nam_light c).\nProof.\n  intros dim c H.\n  show_preserves_WT_cong (optimize_nam_light_preserves_semantics c H).\nQed.\n\nLemma optimize_nam_light_preserves_mapping : forall {dim} (c : circ dim) (cg : c_graph),\n  respects_constraints_directed (is_in_graph cg) U_CX c -> \n  respects_constraints_directed (is_in_graph cg) U_CX (optimize_nam_light c).\nProof. intros. show_preserves_mapping_nam. Qed.\n\nLemma optimize_nam_lcr_preserves_semantics : forall {dim} (c0 l c r : circ dim) n,\n  n > 2 -> uc_well_typed_l c0 -> \n  optimize_nam_lcr c0 = Some (l, c, r) ->\n  (niter c0 n ≅l≅ (l ++ (niter c (n - 2)) ++ r))%ucom.\nProof. \n  intros dim c0 l c r n Hn WT H.\n  eapply LCR_correct in H.\n  apply H.\n  all: try assumption.\n  apply optimize_nam_preserves_semantics.\n  apply optimize_nam_preserves_WT.\nQed.\n\nLemma niter_WT : forall {dim} (c : circ dim) n,\n  uc_well_typed_l c -> uc_well_typed_l (niter c n).\nProof.\n  intros dim c n WT.\n  induction n.\n  constructor.\n  eapply uc_well_typed_l_implies_dim_nonzero.\n  apply WT.\n  simpl.\n  apply uc_well_typed_l_app; split; assumption.\nQed.\n\nLemma niter_WT_inv : forall {dim} (c : circ dim) n,\n  n > 0 -> uc_well_typed_l (niter c n) -> uc_well_typed_l c.\nProof.\n  intros dim c n Hn WT.\n  destruct n; try lia.\n  induction n; simpl in WT.\n  rewrite app_nil_r in WT.\n  assumption.\n  apply IHn; try lia.\n  simpl.\n  apply uc_well_typed_l_app in WT as [_ WT].\n  assumption.\nQed.\n\nLemma optimize_nam_lcr_preserves_WT : forall {dim} (c0 l c r : circ dim) n,\n  n > 2 -> uc_well_typed_l c0 -> \n  optimize_nam_lcr c0 = Some (l, c, r) ->\n  uc_well_typed_l l /\\ uc_well_typed_l c /\\ uc_well_typed_l r.\nProof.\n  intros dim c0 l c r n Hn WT H.\n  eapply optimize_nam_lcr_preserves_semantics in H; try apply Hn; auto.\n  apply uc_cong_l_implies_WT in H.\n  apply uc_well_typed_l_app in H as [H1 H23].\n  apply uc_well_typed_l_app in H23 as [H2 H3].\n  repeat split; try assumption.\n  eapply niter_WT_inv; try apply H2. lia.\n  apply niter_WT.\n  assumption.\nQed.\n\nLemma optimize_nam_lcr_preserves_mapping : forall {dim} (c0 l c r : circ dim) (cg : c_graph),\n  respects_constraints_directed (is_in_graph cg) U_CX c0 -> \n  optimize_nam_lcr c0 = Some (l, c, r) ->\n  respects_constraints_directed (is_in_graph cg) U_CX l\n    /\\ respects_constraints_directed (is_in_graph cg) U_CX c\n    /\\ respects_constraints_directed (is_in_graph cg) U_CX r.\nProof. \n  intros dim c0 l c r cg Hcg H.\n  eapply MappingConstraints.LCR_respects_constraints in H as [H0 [H1 H2]].\n  repeat split. \n  apply H0. apply H2. apply H1.\n  intros.\n  apply optimize_nam_preserves_mapping.\n  assumption.\n  assumption.\nQed.\n\n(** * Full 'optimize' function *)\n\nDefinition optimize {dim} (c : circ dim) : circ dim :=\n  optimize_ibm (optimize_nam c).\n\nLemma optimize_preserves_semantics : forall {dim} (c : circ dim),\n  uc_well_typed_l c -> (optimize c ≅l≅ c)%ucom.\nProof. \n  intros dim c H.\n  unfold optimize.\n  rewrite optimize_ibm_preserves_semantics.\n  apply optimize_nam_preserves_semantics.\n  assumption.\n  apply optimize_nam_preserves_WT.\n  assumption.\nQed.\n\nLemma optimize_preserves_WT : forall {dim} (c : circ dim),\n  uc_well_typed_l c -> uc_well_typed_l (optimize c).\nProof.\n  intros dim c H.\n  show_preserves_WT_cong (optimize_preserves_semantics c H).\nQed.\n\nLemma optimize_preserves_mapping : forall {dim} (c : circ dim) (cg : c_graph),\n  respects_constraints_directed (is_in_graph cg) U_CX c -> \n  respects_constraints_directed (is_in_graph cg) U_CX (optimize c).\nProof. \n  intros. \n  apply optimize_ibm_preserves_mapping.\n  apply optimize_nam_preserves_mapping.\n  assumption.\nQed.\n\n(** * Circuit mapping **)\n\nDefinition swap_route {dim} (c : circ dim) (lay : layout) (cg : c_graph) (get_path : path_finding_fun) :=\n  let n := graph_dim cg in\n  let (c,_) := SwapRoute.swap_route (full_to_map (cast c n)) lay get_path in\n  map_to_full c.\n  \nDefinition decompose_swaps {dim} (c : circ dim) (cg : c_graph) :=\n  map_to_full (SwapRoute.decompose_swaps_and_cnots (full_to_map c) (is_in_graph cg)).\n\nDefinition trivial_layout n : layout := Layouts.trivial_layout n.\nDefinition check_list l : bool := Layouts.check_list l.\nDefinition list_to_layout l : layout := Layouts.list_to_layout l.\nDefinition layout_to_list (lay : layout) n : list nat := \n  map (fun ox => match ox with Some x => x | _ => O end) (Layouts.layout_to_list n lay).\nDefinition greedy_layout {dim} (c : circ dim) (cg : c_graph) (q_ordering : option nat -> list nat) : layout :=\n  let n := graph_dim cg in\n  GreedyLayout.greedy_layout (full_to_map (cast c n)) n q_ordering.\n\nDefinition beq_tup t t' := \n  match t, t' with\n  | (n1, n2), (n1', n2') => (n1 =? n1') && (n2 =? n2')\n  end.\n\nDefinition make_lnn n : c_graph := (n, LNN.is_in_graph n).\nDefinition make_lnn_ring n : c_graph := (n, LNNRing.is_in_graph n).\nDefinition make_grid m n : c_graph := (m * n, Grid.is_in_graph m n).\n\nDefinition c_graph_from_coupling_map (n : nat) (cmap : list (nat * nat)) : c_graph :=\n  (n, fun n1 n2 => existsb (beq_tup (n1, n2)) cmap).\n\nDefinition lnn_path_finding_fun (n : nat) : path_finding_fun := LNN.get_path.\nDefinition lnn_ring_path_finding_fun n : path_finding_fun := LNNRing.get_path n.\nDefinition grid_path_finding_fun (m n : nat) : path_finding_fun := Grid.get_path n.\n\nDefinition lnn_qubit_ordering_fun n : qubit_ordering_fun := LNN.q_ordering n.\nDefinition lnn_ring_qubit_ordering_fun n : qubit_ordering_fun := LNNRing.q_ordering n.\n\nDefinition get_path_valid (cg : c_graph) (get_path : path_finding_fun) :=\n  ConnectivityGraph.get_path_valid (fst cg) get_path (snd cg).\n\nLemma lnn_path_finding_fun_valid : forall n,\n  get_path_valid (make_lnn n) (lnn_path_finding_fun n).\nProof. intros. apply LNN.lnn_get_path_valid. Qed.\n\nLemma lnn_ring_path_finding_fun_valid : forall n,\n  get_path_valid (make_lnn_ring n) (lnn_ring_path_finding_fun n).\nProof. intros. apply LNNRing.lnn_ring_get_path_valid. Qed.\n\nLemma grid_path_finding_fun_valid : forall m n,\n  get_path_valid (make_grid m n) (grid_path_finding_fun m n).\nProof. \n  intros. \n  intros ? ? ? ? ?. \n  apply Grid.get_path_valid; auto. \nQed.\n\nLemma lnn_qubit_ordering_fun_valid : forall n, \n  valid_q_ordering (lnn_qubit_ordering_fun n) n.\nProof. intros. apply LNN.lnn_q_ordering_valid. Qed.\n\nLemma lnn_ring_qubit_ordering_fun_valid : forall n, \n  valid_q_ordering (lnn_ring_qubit_ordering_fun n) n.\nProof. intros. apply LNNRing.lnn_ring_q_ordering_valid. Qed.\n\nModule MVP := MappingValidationProofs FullGateSet.\n\nLemma list_to_ucom_map_to_full : forall {dim} (l : gate_list _ dim),\n  uc_equiv (MVP.SRP.MapList.list_to_ucom l) (FullList.list_to_ucom (map_to_full l)).\nProof.\n  intros.\n  induction l.\n  reflexivity.\n  simpl.\n  unfold map_to_full. \n  rewrite change_gate_set_cons.\n  rewrite FullList.list_to_ucom_append.\n  destruct a; rewrite IHl; apply useq_mor; try reflexivity.\n  all: dependent destruction u; simpl; rewrite SKIP_id_r; reflexivity.\nQed.\n\nLemma list_to_ucom_full_to_map : forall {dim} (l : circ dim),\n  uc_equiv (FullList.list_to_ucom l) (MVP.SRP.MapList.list_to_ucom (full_to_map l)).\nProof.\n  intros.\n  induction l.\n  reflexivity.\n  simpl.\n  unfold full_to_map. \n  rewrite change_gate_set_cons.\n  rewrite MapList.list_to_ucom_append.\n  destruct a; rewrite IHl; apply useq_mor; try reflexivity.\n  all: dependent destruction f; simpl; rewrite SKIP_id_r; try reflexivity.\n  all: repeat rewrite <- useq_assoc; reflexivity.\nQed.\n\nLemma swap_route_preserves_semantics : forall {dim} (c : circ dim) (lay : layout) (cg : c_graph) (get_path : path_finding_fun),\n  let n := graph_dim cg in\n  uc_well_typed_l (cast c n) ->\n  layout_bijective n lay ->\n  get_path_valid cg get_path ->\n  cast c n ≡x swap_route c lay cg get_path.\nProof.\n  intros dim c lay cg get_path n WT WF Hpath.\n  subst n.\n  unfold swap_route.\n  destruct (SwapRoute.swap_route (full_to_map (cast c (graph_dim cg))) lay get_path) eqn:sr.\n  assert (srWF:=sr).\n  apply MVP.SRP.swap_route_WF in srWF; auto.\n  apply MVP.SRP.swap_route_sound in sr; auto.\n  unfold MVP.SRP.uc_equiv_perm_ex in sr.\n  unfold uc_equiv_perm.\n  exists (get_log lay). exists (get_phys l).\n  repeat split.\n  apply get_log_perm. assumption.\n  apply get_phys_perm. assumption.\n  unfold eval, MVP.SRP.MapList.eval in *.\n  rewrite <- list_to_ucom_map_to_full, <- sr.\n  rewrite list_to_ucom_full_to_map.\n  reflexivity.\n  apply full_to_map_WT. assumption.\n  intros n1 n2 Hn1 Hn2 Hneq.\n  destruct (Hpath n1 n2 Hn1 Hn2 Hneq) as [_ [_ [_ [H _]]]].\n  apply H.\n  apply full_to_map_WT. assumption.\n  intros n1 n2 Hn1 Hn2 Hneq.\n  destruct (Hpath n1 n2 Hn1 Hn2 Hneq) as [_ [_ [_ [H _]]]].\n  apply H.\nQed.\n\nLemma swap_route_preserves_WT : forall {dim} (c : circ dim) (lay : layout) (cg : c_graph) (get_path : path_finding_fun),\n  let n := graph_dim cg in\n  uc_well_typed_l (cast c n) ->\n  layout_bijective n lay ->\n  get_path_valid cg get_path ->\n  uc_well_typed_l (swap_route c lay cg get_path).\nProof. \n  intros dim c lay cg get_path n WT WF Hpath. \n  specialize (swap_route_preserves_semantics _ _ _ get_path WT WF Hpath) as H.\n  destruct H as [p1 [p2 [Hp1 [Hp2 H]]]].\n  apply list_to_ucom_WT. \n  apply uc_eval_nonzero_iff.\n  apply list_to_ucom_WT in WT.\n  apply uc_eval_nonzero_iff in WT.\n  intro contra.\n  unfold eval in H.\n  rewrite contra in H.\n  rewrite Mmult_0_r, Mmult_0_l in H.\n  contradiction.\nQed.\n\nLemma swap_route_respects_constraints_undirected : forall {dim} (c : circ dim) (lay : layout) (cg : c_graph) (get_path : path_finding_fun),\n  let n := graph_dim cg in\n  uc_well_typed_l (cast c n) ->\n  layout_bijective n lay ->\n  get_path_valid cg get_path ->\n  respects_constraints_undirected (is_in_graph cg) (swap_route c lay cg get_path).\nProof.\n  intros dim c lay cg get_path n WT WF Hpath.\n  subst n.\n  unfold swap_route.\n  destruct (SwapRoute.swap_route (full_to_map (cast c (graph_dim cg))) lay get_path) eqn:sr.\n  apply MVP.SRP.swap_route_respects_undirected with (is_in_graph:=is_in_graph cg) in sr; auto.\n  apply map_to_full_preserves_mapping_undirected. assumption.\n  apply full_to_map_WT. assumption.\nQed.\n\nLemma map_to_full_equiv : forall {dim} (l l' : gate_list _ dim),\n  MVP.SRP.MapList.uc_equiv_l l l' ->\n  uc_equiv_l (map_to_full l) (map_to_full l').\nProof.\n  intros dim l l' H.\n  unfold uc_equiv_l.\n  unfold MVP.SRP.MapList.uc_equiv_l in H.\n  rewrite <- 2 list_to_ucom_map_to_full.\n  assumption.\nQed.\n\nLemma decompose_swaps_preserves_semantics : forall {dim} (c : circ dim) (cg : c_graph),\n  uc_equiv_l (decompose_swaps c cg) c.\nProof. \n  intros. \n  unfold decompose_swaps.\n  erewrite map_to_full_equiv.\n  apply map_to_full_inv.\n  apply decompose_swaps_and_cnots_sound.\nQed.\n\nLemma decompose_swaps_preserves_WT : forall {dim} (c : circ dim) (cg : c_graph),\n  uc_well_typed_l c ->\n  uc_well_typed_l (decompose_swaps c cg).\nProof.\n  intros dim c cg WT.\n  specialize (decompose_swaps_preserves_semantics c cg) as H.\n  apply list_to_ucom_WT. \n  apply uc_eval_nonzero_iff.\n  apply list_to_ucom_WT in WT.\n  apply uc_eval_nonzero_iff in WT.\n  intro contra.\n  unfold uc_equiv_l, uc_equiv in H.\n  rewrite contra in H.\n  rewrite H in WT.\n  contradiction.\nQed.\n\nLemma decompose_swaps_respects_constraints : forall {dim} (c : circ dim) (cg : c_graph),\n  respects_constraints_undirected (is_in_graph cg) c ->\n  respects_constraints_directed (is_in_graph cg) U_CX (decompose_swaps c cg).\nProof.\n  intros.\n  unfold decompose_swaps.\n  apply map_to_full_preserves_mapping_directed.\n  apply decompose_swaps_and_cnots_respects_directed.\n  apply full_to_map_preserves_mapping_undirected.\n  assumption.\nQed.\n\nLemma trivial_layout_well_formed : forall n, layout_bijective n (trivial_layout n).\nProof. intros. apply Layouts.trivial_layout_bijective. Qed.\n\nLemma list_to_layout_well_formed : forall l, \n  check_list l = true -> layout_bijective (length l) (list_to_layout l).\nProof. intros l H. apply Layouts.check_list_layout_bijective. auto. Qed.\n\nLemma greedy_layout_well_formed : forall {dim} (c : circ dim) (cg : c_graph) (q_ordering : qubit_ordering_fun), \n  let n := graph_dim cg in\n  uc_well_typed_l (cast c n) ->\n  valid_q_ordering q_ordering (graph_dim cg) ->\n  layout_bijective n (greedy_layout c cg q_ordering).\nProof. \n  intros. \n  apply GreedyLayout.greedy_layout_bijective.\n  apply full_to_map_WT. \n  assumption.\n  assumption.\nQed.\n\n(** * Mapping validation **)\n\nDefinition remove_swaps {dim} (c : circ dim) (lay : layout) :=\n  let (c,_) := MappingValidation.remove_swaps (full_to_map c) lay in\n  map_to_full c.\n\nDefinition check_swap_equivalence {dim} (c1 c2 : circ dim) (lay1 lay2 : layout) :=\n  MappingValidation.is_swap_equivalent (full_to_map c1) (full_to_map c2) lay1 lay2\n    (fun n => @MappingGateSet.match_gate (FullGateSet.U 1) n FullGateSet.match_gate).\n\nDefinition check_constraints {dim} (c : circ dim) (cg : c_graph) :=\n  MappingValidation.check_constraints (full_to_map c) (is_in_graph cg).\n\nLemma full_to_map_inv : forall {dim} (l : _ dim),\n  MVP.SRP.MapList.uc_equiv_l (full_to_map (map_to_full l)) l.\nProof.\n  intros dim l.\n  induction l.\n  reflexivity.\n  unfold full_to_map, map_to_full.\n  rewrite change_gate_set_cons.\n  rewrite change_gate_set_app.\n  rewrite IHl.\n  rewrite cons_to_app.\n  MVP.SRP.MapList.apply_app_congruence.\n  destruct a; dependent destruction m; \n  unfold change_gate_set; simpl; reflexivity.\nQed.\n\nLemma remove_swaps_preserves_semantics : forall {dim} (c : circ dim) (lay : layout),\n  uc_well_typed_l c -> \n  layout_bijective dim lay ->\n  remove_swaps c lay ≡x c.\nProof. \n  intros dim c lay WT WF.\n  unfold remove_swaps.\n  destruct (MappingValidation.remove_swaps (full_to_map c) lay) eqn:rs.\n  assert (rsWF:=rs).\n  apply MVP.remove_swaps_WF in rsWF; auto.\n  apply MVP.remove_swaps_sound in rs; auto.\n  unfold MVP.SRP.uc_equiv_perm_ex in rs.\n  symmetry.\n  unfold uc_equiv_perm.\n  exists (get_phys lay). exists (get_log l).\n  repeat split.\n  apply get_phys_perm. assumption.\n  apply get_log_perm. assumption.\n  unfold eval, MVP.SRP.MapList.eval in *.\n  rewrite <- list_to_ucom_full_to_map in rs.\n  rewrite rs.\n  apply f_equal2; try reflexivity.\n  apply f_equal2; try reflexivity.\n  rewrite list_to_ucom_full_to_map.\n  rewrite full_to_map_inv.\n  reflexivity.\n  apply full_to_map_WT. assumption.\n  apply full_to_map_WT. assumption.\nQed.\n\nLemma remove_swaps_preserves_WT : forall {dim} (c : circ dim) (lay : layout),\n  uc_well_typed_l c -> \n  layout_bijective dim lay ->\n  uc_well_typed_l (remove_swaps c lay).\nProof.\n  intros dim c lay WT WF.\n  specialize (remove_swaps_preserves_semantics c lay WT WF) as H.\n  symmetry in H.\n  destruct H as [p1 [p2 [Hp1 [Hp2 H]]]].\n  apply list_to_ucom_WT. \n  apply uc_eval_nonzero_iff.\n  apply list_to_ucom_WT in WT.\n  apply uc_eval_nonzero_iff in WT.\n  intro contra.\n  unfold eval in H.\n  rewrite contra in H.\n  rewrite Mmult_0_r, Mmult_0_l in H.\n  contradiction.\nQed.\n\nLemma check_swap_equivalence_correct : forall dim (c1 c2 : circ dim) (lay1 lay2 : layout),\n  uc_well_typed_l c1 ->\n  uc_well_typed_l c2 ->\n  layout_bijective dim lay1 ->\n  layout_bijective dim lay2 ->\n  check_swap_equivalence c1 c2 lay1 lay2 = true ->\n  c1 ≡x c2.\nProof.\n  intros dim c1 c2 lay1 lay2 WT1 WT2 WF1 WF2 H.\n  unfold check_swap_equivalence in H.\n  unfold is_swap_equivalent in H.\n  destruct (MappingValidation.check_swap_equivalence (full_to_map c1)\n                                                     (full_to_map c2) lay1 lay2\n                                                     (fun n : nat => MappingGateSet.match_gate match_gate)) eqn:mv.\n  assert (mvWF:=mv).\n  destruct p.\n  2: inversion H.\n  apply MVP.check_swap_equivalence_implies_equivalence in mv; auto.\n  apply MVP.check_swap_equivalence_layouts_WF in mvWF as [? ?]; auto.\n  unfold MVP.SRP.uc_equiv_perm_ex in mv.\n  exists (get_phys lay1 ∘ get_log lay2)%prg.\n  exists (get_phys l0 ∘ get_log l)%prg.\n  repeat split.\n  apply Permutations.permutation_compose.\n  apply get_phys_perm; auto.\n  apply get_log_perm; auto.\n  apply Permutations.permutation_compose.\n  apply get_phys_perm; auto.\n  apply get_log_perm; auto.\n  unfold eval.\n  unfold MVP.SRP.MapList.eval in mv.\n  rewrite <- 2 list_to_ucom_full_to_map in mv.\n  apply mv.\n  all: apply full_to_map_WT; assumption.\nQed.\n\nLemma check_constraints_correct : forall dim (c : circ dim) (cg : c_graph),\n  check_constraints c cg = true ->\n  respects_constraints_directed (is_in_graph cg) MappingGateSet.UMap_CNOT (full_to_map c).\nProof. intros. apply MVP.check_constraints_implies_respect_constraints. auto. Qed.\n\n(** * Example verified composition of transformations **)\n\nDefinition optimize_and_map_to_lnn_ring_16 {dim} (c : circ dim) :=\n  let cg := make_lnn_ring 16 in\n  let get_path := lnn_ring_path_finding_fun 16 in\n  let q_ordering := lnn_ring_qubit_ordering_fun 16 in\n  if check_well_typed c 16\n  then\n    let c1 := optimize_nam c in                 (* optimization #1 *)\n    let lay := greedy_layout c cg q_ordering in\n    let c2 := swap_route c1 lay cg get_path in  (* mapping *)\n    let c3 := decompose_swaps c2 cg in          (* optimized SWAP decomposition *)\n    Some (optimize c3)                          (* optimization #2 *)\n  else None.\n\nLemma cast_same : forall {dim} (c : circ dim), cast c dim = c.\nProof. \n  intros dim c. \n  induction c. \n  reflexivity. \n  simpl. \n  destruct a; rewrite IHc; reflexivity.\nQed.\n\nLemma optimize_and_map_to_lnn_ring_16_preserves_semantics : forall (c : circ _) c',\n  optimize_and_map_to_lnn_ring_16 c = Some c' -> \n  c ≅x c'.\nProof.\n  intros c c' H.\n  unfold optimize_and_map_to_lnn_ring_16 in H.\n  remember (make_lnn_ring 16) as cg.\n  remember (lnn_ring_path_finding_fun 16) as get_path.\n  remember (greedy_layout c cg (lnn_ring_qubit_ordering_fun 16)) as lay.\n  assert (Hpath : get_path_valid cg get_path).\n  { subst. apply lnn_ring_path_finding_fun_valid. }\n  clear Heqget_path.\n  destruct (check_well_typed c 16) eqn:WT; inversion H.\n  apply check_well_typed_correct in WT.\n  replace 16 with (graph_dim cg) in *.\n  rewrite cast_same in WT.\n  assert (WF : layout_bijective (graph_dim cg) lay).\n  { subst. apply greedy_layout_well_formed. \n    rewrite cast_same. assumption.\n    apply lnn_ring_qubit_ordering_fun_valid. }\n  clear - WT Hpath WF.\n  specialize (swap_route_preserves_semantics (optimize_nam c) lay cg get_path) as Hmap.\n  destruct Hmap as [p1 [p2 [Hp1 [Hp2 Hmap]]]]; auto.\n  rewrite cast_same.\n  apply optimize_nam_preserves_WT. auto.\n  exists p1. exists p2.\n  repeat split; auto.\n  rewrite cast_same in Hmap.\n  specialize (optimize_nam_preserves_semantics c WT) as Hnam.\n  destruct Hnam as [x Hnam].\n  assert (Haux: eval c = Cexp (- x) .* eval (optimize_nam c)).\n  { unfold eval. rewrite Hnam.\n    rewrite Mscale_assoc.\n    rewrite Cexp_mul_neg_l.\n    rewrite Mscale_1_l. auto. }\n  rewrite Haux, Hmap.\n  remember (swap_route (optimize_nam c) lay cg get_path) as c0.\n  clear Hmap Hnam Haux.\n  specialize (optimize_preserves_semantics (decompose_swaps c0 cg)) as Hopt.\n  destruct Hopt as [y Hopt].\n  apply decompose_swaps_preserves_WT.\n  subst c0. apply swap_route_preserves_WT; auto.\n  rewrite cast_same.\n  apply optimize_nam_preserves_WT; auto.\n  assert (Haux: eval (optimize (decompose_swaps c0 cg)) = Cexp y .* eval (decompose_swaps c0 cg)).\n  { unfold eval. rewrite Hopt. reflexivity. }\n  rewrite Haux.\n  clear Hopt Haux.\n  exists (- x - y)%R.\n  distribute_scale.\n  apply f_equal2.\n  rewrite <- Cexp_add.\n  field_simplify (- x - y + y)%R.\n  reflexivity.\n  apply f_equal2; try reflexivity.\n  apply f_equal2; try reflexivity.\n  symmetry.\n  apply decompose_swaps_preserves_semantics.\n  subst cg.\n  reflexivity.\nQed.\n\nLemma optimize_and_map_to_lnn_ring_16_respects_constraints : forall (c : circ 16) c',\n  optimize_and_map_to_lnn_ring_16 c = Some c' -> \n  respects_constraints_directed (is_in_graph (make_lnn_ring 16)) U_CX c'.\nProof.\n  intros c c' H.\n  unfold optimize_and_map_to_lnn_ring_16 in H.\n  remember (make_lnn_ring 16) as cg.\n  remember (lnn_ring_path_finding_fun 16) as get_path.\n  remember (greedy_layout c cg (lnn_ring_qubit_ordering_fun 16)) as lay.\n  assert (Hpath : get_path_valid cg get_path).\n  { subst. apply lnn_ring_path_finding_fun_valid. }\n  clear Heqget_path.\n  destruct (check_well_typed c 16) eqn:WT; inversion H.\n  apply check_well_typed_correct in WT.\n  replace (graph_dim cg) with 16 in *.\n  rewrite cast_same in WT.\n  assert (WF : layout_bijective 16 lay).\n  { subst. apply greedy_layout_well_formed. \n    rewrite cast_same. assumption.\n    apply lnn_ring_qubit_ordering_fun_valid. }\n  clear - WT Hpath WF Heqcg.\n  apply optimize_preserves_mapping.\n  apply decompose_swaps_respects_constraints.\n  apply swap_route_respects_constraints_undirected; auto.\n  replace (graph_dim cg) with 16.\n  rewrite cast_same.\n  apply optimize_nam_preserves_WT. auto.\n  subst. reflexivity.\n  replace (graph_dim cg) with 16. auto.\n  subst. reflexivity.\n  subst. reflexivity.\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/Main.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2539059321396022}}
{"text": "Require Import VST.msl.base.\nRequire Import VST.msl.ageable.\nRequire Import VST.msl.functors.\nRequire Import VST.msl.predicates_hered.\nImport VST.msl.functors.MixVariantFunctor.\nImport VST.msl.functors.MixVariantFunctorLemmas.\nRequire Import Arith.\n\nModule Type KNOT_INPUT__MIXVARIANT_HERED_T_OTH_REL.\n  Parameter F : functor.\n\n  Parameter other : Type.\n\n  Parameter Rel : forall A, F A -> F A -> Prop.\n\n  Parameter Rel_fmap : forall A B (f1: A->B) (f2:B->A) x y,\n    Rel A x y ->\n    Rel B (fmap F f1 f2 x) (fmap F f1 f2 y).\n  Axiom Rel_refl : forall A x, Rel A x x.\n  Axiom Rel_trans : forall A x y z,\n    Rel A x y -> Rel A y z -> Rel A x z.\n\n  Parameter ORel : other -> other -> Prop.\n  Axiom ORel_refl : reflexive other ORel.\n  Axiom ORel_trans : transitive other ORel.\n\n  Parameter T:Type.\n  Parameter T_bot:T.\n\n  Parameter T_rel : T -> T -> Prop.\n  Parameter T_rel_bot : forall x, T_rel T_bot x.\n  Parameter T_rel_refl : forall x, T_rel x x.\n  Parameter T_rel_trans : transitive T T_rel.\n\nEnd KNOT_INPUT__MIXVARIANT_HERED_T_OTH_REL.\n\nModule Type KNOT__MIXVARIANT_HERED_T_OTH_REL.\n  Declare Module KI: KNOT_INPUT__MIXVARIANT_HERED_T_OTH_REL.\n  Import KI.\n\n  Parameter knot:Type.\n  Parameter ageable_knot : ageable knot.\n  #[global] Existing Instance ageable_knot.\n\n  Parameter hered : (knot * other -> T) -> Prop.\n  Definition predicate := { p:knot * other -> T | hered p }.\n\n  Parameter squash : (nat * F predicate) -> knot.\n  Parameter unsquash : knot -> (nat * F predicate).\n\n  Parameter approx : nat -> predicate -> predicate.\n\n  Axiom squash_unsquash : forall k:knot, squash (unsquash k) = k.\n  Axiom unsquash_squash : forall (n:nat) (f:F predicate),\n    unsquash (squash (n,f)) = (n, fmap F (approx n) (approx n) f).\n\n  Axiom approx_spec : forall n p ko,\n    proj1_sig (approx n p) ko =\n     if (Compare_dec.le_gt_dec n (level (fst ko))) then T_bot else proj1_sig p ko.\n\n  Definition knot_rel (k1 k2:knot) :=\n    let (n,f) := unsquash k1 in\n    let (n',f') := unsquash k2 in\n    n = n' /\\ Rel predicate f f'.\n\n  Axiom knot_age1 : forall k:knot,\n    age1 k =\n    match unsquash k with\n    | (O,_) => None\n    | (S n,x) => Some (squash (n,x))\n    end.\n\n  Axiom knot_level : forall k:knot,\n    level k = fst (unsquash k).\n\n  Axiom hered_spec : forall p,\n    hered p =\n    (forall k k' k'' o o',\n      clos_refl_trans _ age k k' ->\n      knot_rel  k' k'' ->\n      ORel o o' ->\n      T_rel (p (k,o)) (p (k'',o'))).\n\n  #[export] Program Instance ext_knot : Ext_ord knot := { ext_order := knot_rel }.\n  Next Obligation.\n  Proof.\n    unfold knot_rel. split.\n    - intros k.\n      destruct (unsquash k); split; auto.\n      apply Rel_refl.\n    - intros k1 k2 k3.\n      destruct (unsquash k1), (unsquash k2), (unsquash k3).\n      intros [] []; subst; split; auto.\n      eapply Rel_trans; eauto.\n  Qed.\n  Next Obligation.\n  Proof.\n    intros ?????.\n    unfold age, knot_rel in *. rewrite knot_age1 in H.\n    destruct (unsquash y) eqn: Hy.\n    destruct n; inv H; simpl.\n    destruct (unsquash z) eqn: Hz.\n    destruct H0 as [? H0]; subst.\n    exists (squash (n, _f0)).\n    - rewrite !unsquash_squash.\n      split; auto.\n      apply Rel_fmap; auto.\n    - rewrite knot_age1, Hz; auto.\n  Qed.\n  Next Obligation.\n  Proof.\n    unfold age, knot_rel in *. rewrite knot_age1 in H0.\n    destruct (unsquash a) eqn: Ha.\n    destruct n; inv H0.\n    destruct (unsquash b) eqn: Hb.\n    destruct H as [? H]; subst.\n    exists (squash (n, _f0)).\n    split.\n    - rewrite knot_age1, Hb; auto.\n    - rewrite !unsquash_squash; split; auto.\n      apply Rel_fmap; auto.\n  Qed.\n  Next Obligation.\n  Proof.\n    rewrite !knot_level. unfold knot_rel in H.\n    destruct (unsquash a), (unsquash b), H; auto.\n  Qed.\n\n  Lemma knot_order : ext_order = knot_rel.\n  Proof. reflexivity. Qed.\n\nEnd KNOT__MIXVARIANT_HERED_T_OTH_REL.\n\nModule Knot_MixVariantHeredTOthRel (KI':KNOT_INPUT__MIXVARIANT_HERED_T_OTH_REL) :\n  KNOT__MIXVARIANT_HERED_T_OTH_REL with Module KI:=KI'.\n  Module KI := KI'.\n  Import KI.\n\n  Definition sinv_prod X := prod X (F X * other -> T).\n\n  Definition guppy_sig := (fun X:Type => X * (F X * other -> T) -> Prop).\n  Definition guppy_ty := sigT guppy_sig.\n\n  Definition guppy_step_ty (Z:guppy_ty) : Type :=\n    (sig (fun (x:sinv_prod (projT1 Z)) => projT2 Z x)).\n\n  Definition guppy_age (Z:guppy_ty) (x:guppy_step_ty Z) : projT1 Z := fst (proj1_sig x).\n  Definition guppy_unage (Z:guppy_ty)\n    (H:forall t, projT2 Z (t,fun _ => T_bot))\n    (x:projT1 Z) : guppy_step_ty Z :=\n    exist (fun z => projT2 Z z) (x, fun _ => T_bot) (H x).\n\n  Definition guppy_step_prop (Z:guppy_ty) (xf:sinv_prod (guppy_step_ty Z)) :=\n    (forall (k:F (guppy_step_ty Z)) (o:other) H,\n         T_rel (snd xf (k,o))\n               (snd (proj1_sig (fst xf)) (fmap F (guppy_age Z) (guppy_unage Z H) k,o))) /\\\n    (forall (k k':F (guppy_step_ty Z)) (o o':other),\n         Rel (guppy_step_ty Z) k k' ->\n         ORel o o' ->\n         T_rel (snd xf (k,o)) (snd xf (k',o'))).\n\n  Definition guppy_step (Z:guppy_ty) : guppy_ty :=\n    existT guppy_sig (guppy_step_ty Z) (guppy_step_prop Z).\n\n  Definition guppy_base : guppy_ty :=\n    existT guppy_sig unit\n      (fun xf =>\n        (forall (k k':F unit) (o o':other),\n          Rel unit k k' ->\n          ORel o o' ->\n          T_rel (snd xf (k,o)) (snd xf (k',o')))).\n\n  Fixpoint guppy (n:nat) : guppy_ty :=\n    match n with\n    | 0    => guppy_base\n    | S n' => guppy_step (guppy n')\n    end.\n\n  Definition sinv (n:nat) : Type := projT1 (guppy n).\n  Definition sinv_prop (n:nat) : prod (sinv n) (F (sinv n) * other -> T) -> Prop := projT2 (guppy n).\n\n  Fixpoint floor (m:nat) (n:nat) (p:sinv (m+n)) : sinv n :=\n    match m as m' return forall (p : sinv (m'+n)), sinv n with\n    | O => fun p => p\n    | S m' => fun p => floor m' n (fst (proj1_sig p))\n    end p.\n\n  Definition knot := { n:nat & F (sinv n) }.\n\n  Definition sinv_age n : sinv (S n) -> sinv n := guppy_age (guppy n).\n  Program Definition sinv_unage n : sinv n -> sinv (S n) := guppy_unage (guppy n) _.\n  Next Obligation.\n    revert t; induction n; simpl; auto.\n    repeat intro.\n    apply T_rel_bot.\n    split; simpl in *; repeat intro.\n    apply T_rel_bot.\n    apply T_rel_bot.\n  Qed.\n\n  Definition F_sinv n := F (sinv n).\n\n  Definition age1_def (k:knot) : option knot :=\n    match k with\n      | existT _ 0 f => None\n      | existT _ (S m) f => Some\n          (existT F_sinv m (fmap F (sinv_age m) (sinv_unage m) f))\n    end.\n\n  Definition age_def x y := age1_def x = Some y.\n\n  Inductive knot_rel_inner : knot -> knot -> Prop :=\n    | intro_krel : forall n (f f':F_sinv n),\n         Rel _ f f' ->\n         knot_rel_inner (existT (F_sinv) n f) (existT (F_sinv) n f').\n\n  Definition hered (p:knot * other -> T) : Prop :=\n    forall k k' k'' o o',\n      clos_refl_trans _ age_def k k' ->\n      knot_rel_inner k' k'' -> ORel o o' ->\n      T_rel (p (k,o)) (p (k'',o')).\n\n  Definition predicate := { p:knot * other -> T | hered p }.\n\n  Definition app_sinv (n:nat) (p:sinv (S n)) (x:F_sinv n * other) :=\n    snd (proj1_sig p) x.\n\n  Section stratifies.\n    Variable Q:knot * other -> T.\n    Variable HQ:hered Q.\n\n    Fixpoint stratifies (n:nat) : sinv n -> Prop :=\n    match n as n' return sinv n' -> Prop with\n    | 0 => fun _ => True\n    | S n' => fun (p:sinv (S n')) =>\n          stratifies n' (fst (proj1_sig p)) /\\\n          forall (k:F_sinv n') (o:other), snd (proj1_sig p) (k,o) = Q (existT F_sinv n' k,o)\n    end.\n\n    Lemma stratifies_unique : forall n p1 p2,\n      stratifies n p1 ->\n      stratifies n p2 ->\n      p1 = p2.\n    Proof.\n      induction n; simpl; intuition.\n      destruct p1; destruct p2; auto.\n      destruct p1; destruct p2.\n      simpl in *; fold guppy in *.\n      cut (x = x0).\n      intros.\n      revert p p0 H2 H3.\n      rewrite <- H0.\n      intros.\n      replace p0 with p by (apply proof_irr); auto.\n      destruct x; destruct x0; simpl in *.\n      apply injective_projections; simpl.\n      apply IHn; auto.\n      extensionality; intros.\n      simpl in *.\n      destruct x as [x o].\n      destruct (H2 x o); destruct (H3 x o).\n      rewrite H2.\n      rewrite H3.\n      auto.\n    Qed.\n\n    Definition stratify (n:nat) : { x:sinv n | stratifies n x }.\n    Proof.\n      induction n.\n      exists tt; simpl; exact I.\n      assert (HX:\n        projT2 (guppy n)\n        (proj1_sig IHn, fun v : F_sinv n * other => Q (existT F_sinv n (fst v),snd v))).\n      destruct n.\n      simpl; intros.\n      eapply HQ.\n      apply rt_refl.\n      constructor; auto.\n      auto.\n      simpl; intros.\n      destruct IHn; simpl.\n      simpl in s; destruct s.\n      destruct x; simpl in *; fold guppy in *.\n      destruct x; simpl in *.\n      split; hnf; simpl; intros.\n      rewrite H0.\n      eapply HQ.\n      apply rt_step.\n      hnf; simpl.\n      reflexivity.\n      constructor; auto.\n      unfold sinv_unage.\n      replace (sinv_unage_obligation_1 n) with H1.\n      unfold sinv_age.\n      apply Rel_refl.\n      apply proof_irr.\n      apply ORel_refl.\n      eapply HQ.\n      apply rt_refl.\n      constructor; auto.\n      auto.\n\n      exists ((exist (fun x => projT2 (guppy n) x) ( proj1_sig IHn, fun v:F_sinv n * other => Q (existT (F_sinv) n (fst v),snd v) ) HX)).\n      simpl; split; auto.\n      destruct IHn; auto.\n    Qed.\n  End stratifies.\n\n  Lemma decompose_nat : forall (x y:nat), { m:nat & y = (m + S x) } + { ge x y }.\n  Proof.\n    intros x y; revert x; induction y; simpl; intros.\n    right; auto with arith.\n    destruct (IHy x) as [[m H]|H].\n    left; exists (S m); lia.\n    destruct (Peano_dec.eq_nat_dec x y).\n    left; exists O; lia.\n    right; lia.\n  Qed.\n\n  Definition unstratify (n:nat) (p:sinv n) : knot * other -> T := fun w =>\n    match w with (existT _ nw w',o) =>\n      match decompose_nat nw n with\n        | inleft (existT _ m Hm) => snd (proj1_sig (floor m (S nw) (eq_rect  n _ p (m + S nw) Hm))) (w',o)\n        | inright H => T_bot\n      end\n    end.\n\n  Lemma floor_shuffle:\n    forall (m1 n : nat)\n      (p1 : sinv (m1 + S n)) (H1 : (m1 + S n) = (S m1 + n)),\n      floor (S m1) n (eq_rect (m1 + S n) sinv p1 (S m1 + n) H1) = fst (proj1_sig (floor m1 (S n) p1)).\n  Proof.\n    intros.\n    remember (fst (proj1_sig (floor m1 (S n) p1))) as p.\n    fold guppy in *.\n    revert n p1 H1 p Heqp.\n    induction m1; simpl; intros.\n    replace H1 with (refl_equal (S n)) by (apply proof_irr); simpl; auto.\n    assert (m1 + S n = S m1 + n) by lia.\n    destruct p1 as [[p1 f'] Hp1]; simpl in *; fold guppy in *.\n    generalize (IHm1 n p1 H p Heqp).\n    clear.\n    revert Hp1 H1; generalize H.\n    revert p1 f'.\n    rewrite H.\n    simpl; intros.\n    replace H1 with (refl_equal (S (S (m1 + n)))) by (apply proof_irr).\n    simpl.\n    replace H0 with (refl_equal (S (m1+n))) in H2 by (apply proof_irr).\n    simpl in H2.\n    trivial.\n  Qed.\n\n  Lemma unstratify_hered : forall n p,\n    hered (unstratify n p).\n  Proof.\n    intros.\n    hnf; intros.\n    apply T_rel_trans with (unstratify n p (k',o)).\n    clear o' H0 H1.\n    induction H.\n    hnf in H; simpl in H.\n    destruct x as [x f]; simpl in H.\n    destruct x; try discriminate.\n    assert (y =\n      (existT (F_sinv) x (fmap F (sinv_age x) (sinv_unage x) f))).\n    inversion H; auto.\n    subst y.\n    unfold unstratify.\n    case_eq (decompose_nat (S x) n); intros.\n    destruct s.\n    case_eq (decompose_nat x n); intros.\n    destruct s.\n    destruct n.\n    exfalso; lia.\n    assert (S x0 = x1) by lia; subst x1.\n    revert H1.\n    generalize e e0; revert p; rewrite e; intros.\n    rewrite floor_shuffle.\n    replace e1 with (refl_equal (x0 + S (S x)));\n      simpl eq_rect.\n    2: apply proof_irr.\n    revert H1.\n    generalize (floor x0 (S (S x)) p).\n    intros [[s' fs] Hs] H1; simpl in *; fold guppy in *.\n    destruct Hs.\n    simpl in H2.\n    eapply H2; auto.\n    exfalso.\n    lia.\n    apply T_rel_bot.\n    apply T_rel_refl.\n    eapply T_rel_trans; eauto.\n\n    clear H.\n    inv H0.\n    simpl.\n    destruct (decompose_nat n0 n); [ | apply T_rel_bot ].\n    destruct s; simpl.\n    destruct (floor x (S n0) (eq_rect n sinv p (x +S n0) e)); simpl.\n    destruct n0; simpl in x0; destruct x0; simpl.\n    apply p0; auto.\n    apply p0; auto.\n  Qed.\n\n  Lemma unstratify_Q : forall n (p:sinv n) Q,\n    stratifies Q n p ->\n    forall (k:knot) (o:other),\n      projT1 k < n ->\n      (unstratify n p (k,o) = Q (k,o)).\n  Proof.\n    intros.\n    unfold unstratify.\n    destruct k.\n    destruct (decompose_nat x n).\n    destruct s.\n    simpl in H0.\n    2: simpl in *; exfalso; lia.\n    clear H0.\n    revert p H.\n    generalize e.\n    rewrite e.\n    intros.\n    replace e0 with (refl_equal (x0 + S x)) by apply proof_irr.\n    simpl.\n    clear e e0.\n    revert p H.\n    induction x0; simpl; intros.\n    destruct H.\n    auto.\n    destruct H.\n    apply IHx0.\n    auto.\n  Qed.\n\n  Lemma stratifies_unstratify_more :\n    forall (n m1 m2:nat) (p1:sinv (m1+n)) (p2:sinv (m2+n)),\n      floor m1 n p1 = floor m2 n p2 ->\n      (stratifies (unstratify (m1+n) p1) n (floor m1 n p1) ->\n       stratifies (unstratify (m2+n) p2) n (floor m2 n p2)).\n  Proof.\n    induction n; intuition.\n    split.\n    assert (m2 + S n = S m2 + n) by lia.\n    erewrite <- floor_shuffle.\n    instantiate (1:=H1).\n    replace (unstratify (m2 + S n) p2)\n      with (unstratify (S m2 + n) (eq_rect (m2 + S n) sinv p2 (S m2 + n) H1)).\n    assert (m1 + S n = S m1 + n) by lia.\n    eapply (IHn (S m1) (S m2)\n      (eq_rect (m1 + S n) sinv p1 (S m1 + n) H2)).\n    rewrite floor_shuffle.\n    rewrite floor_shuffle.\n    rewrite H; auto.\n    clear - H0.\n    rewrite floor_shuffle.\n    simpl in H0.\n    destruct H0.\n    clear H0.\n    revert p1 H.\n    generalize H2.\n    rewrite <- H2.\n    intros.\n    replace H0 with (refl_equal (m1 + S n)) by apply proof_irr; auto.\n    clear.\n    revert p2.\n    generalize H1.\n    rewrite H1.\n    intros.\n    replace H0 with (refl_equal (S m2 + n)) by apply proof_irr; auto.\n\n    intros.\n    simpl.\n    destruct (decompose_nat n (m2 + S n)).\n    destruct s.\n    assert (m2 = x).\n    lia.\n    subst x.\n    replace e with (refl_equal (m2 + S n)).\n    simpl; tauto.\n    apply proof_irr.\n    exfalso; lia.\n  Qed.\n\n  Lemma stratify_unstratify : forall n p H,\n    proj1_sig (stratify (unstratify n p) H n) = p.\n  Proof.\n    intros.\n    apply stratifies_unique with (unstratify n p).\n    destruct (stratify _ H n).\n    simpl; auto.\n    clear H.\n    revert p; induction n.\n    simpl; intros; auto.\n    intros.\n    simpl; split.\n\n    assert (stratifies (unstratify n (fst (proj1_sig p))) n (fst (proj1_sig p))).\n    apply IHn.\n    apply (stratifies_unstratify_more n 0 1 (fst (proj1_sig p)) p).\n    simpl; auto.\n    auto.\n\n    intros.\n    destruct (decompose_nat n (S n)).\n    destruct s.\n    assert (x = 0) by lia.\n    subst x.\n    simpl.\n    simpl in e.\n    replace e with (refl_equal (S n)) by apply proof_irr.\n    simpl.\n    split; auto.\n    exfalso; lia.\n  Qed.\n\n  Definition strat (n:nat) (p:predicate) : sinv n :=\n    proj1_sig (stratify (proj1_sig p) (proj2_sig p) n).\n\n  Definition unstrat (n:nat) (p:sinv n) : predicate :=\n    exist hered (unstratify n p) (unstratify_hered n p).\n\n  Definition squash (x:nat * F predicate) : knot :=\n    match x with (n,f) => existT (F_sinv) n (fmap F (strat n) (unstrat n) f) end.\n\n  Definition unsquash (k:knot) : nat * F predicate :=\n    match k with existT _ n f => (n, fmap F (unstrat n) (strat n) f) end.\n\n  Definition knot_level_def (k:knot) : nat :=\n    fst (unsquash k).\n\n  Definition knot_age1_def (k:knot) : option knot :=\n    match unsquash k with\n    | (O,_) => None\n    | (S n,x) => Some (squash (n,x))\n    end.\n\n  Definition knot_unage_def (k:knot) :=\n    let (n,k) := unsquash k in squash (S n,k).\n\n  Program Definition approx (n:nat) (p:predicate) : predicate :=\n    fun w => if (Compare_dec.le_gt_dec n (knot_level_def (fst w))) then T_bot else proj1_sig p w.\n  Next Obligation.\n    hnf; simpl; intros.\n    destruct (Compare_dec.le_gt_dec n (knot_level_def k)).\n    apply T_rel_bot.\n    destruct (Compare_dec.le_gt_dec n (knot_level_def k'')).\n    exfalso.\n    cut (knot_level_def k'' <= knot_level_def k).\n    lia.\n    replace (knot_level_def k'') with (knot_level_def k').\n    clear -H; induction H.\n    hnf in H.\n    unfold age1_def in H.\n    destruct x; destruct y; simpl.\n    destruct x; try discriminate.\n    inv H.\n    simpl.\n    unfold knot_level_def; simpl; auto.\n    auto.\n    eapply Nat.le_trans; eauto.\n    inv H0.\n    unfold knot_level_def; simpl; auto.\n\n    destruct p as [p Hp]; simpl.\n    eapply Hp; eauto.\n  Qed.\n\n  Lemma strat_unstrat : forall n,\n    strat n oo unstrat n = id (sinv n).\n  Proof.\n    intros; extensionality p.\n    unfold compose, id.\n    unfold strat, unstrat.\n    simpl.\n    rewrite stratify_unstratify.\n    auto.\n  Qed.\n\n  Lemma predicate_eq : forall (p1 p2:predicate),\n    proj1_sig p1 = proj1_sig p2 ->\n    p1 = p2.\n  Proof.\n    intros; destruct p1; destruct p2; simpl in H.\n    subst x0.\n    replace h0 with h by apply proof_irr.\n    auto.\n  Qed.\n\n  Lemma unstrat_strat : forall n,\n    unstrat n oo strat n = approx n.\n  Proof.\n    intros.\n    extensionality.\n    unfold compose.\n    unfold unstrat, strat.\n    unfold approx.\n    apply predicate_eq.\n    simpl.\n    extensionality k.\n    destruct (Compare_dec.le_gt_dec n (knot_level_def (fst k))).\n    unfold unstratify.\n    destruct k.\n    destruct k.\n    unfold knot_level_def in l.\n    simpl in *.\n    destruct (decompose_nat x0 n); simpl.\n    destruct s; simpl; exfalso; lia.\n    auto.\n    destruct x as [x Hx]; simpl.\n    destruct (stratify x Hx n); simpl.\n    destruct k.\n    rewrite unstratify_Q with (Q:=x); auto.\n    unfold level in *.\n    destruct k; simpl in *; auto.\n  Qed.\n\n  Lemma squash_unsquash : forall k, squash (unsquash k) = k.\n  Proof.\n    intros.\n    destruct k as [n f]; simpl.\n    f_equal.\n    change ((fmap F (strat n) (unstrat n) oo (fmap F (unstrat n) (strat n))) f = f).\n    rewrite fmap_comp.\n    rewrite strat_unstrat.\n    rewrite fmap_id.\n    auto.\n  Qed.\n\n  Lemma unsquash_squash : forall n f,\n    unsquash (squash (n,f)) = (n, fmap F (approx n) (approx n) f).\n  Proof.\n    intros.\n    unfold unsquash, squash.\n    f_equal.\n    change ((fmap F (unstrat n) (strat n) oo (fmap F (strat n) (unstrat n))) f = fmap F (approx n) (approx n) f).\n    rewrite fmap_comp.\n    rewrite unstrat_strat.\n    auto.\n  Qed.\n\n  Lemma strat_Sx_unstrat : forall x,\n    sinv_unage x = strat (S x) oo unstrat x.\n  Proof.\n    intros.\n    extensionality k.\n    unfold sinv_unage.\n    generalize (sinv_unage_obligation_1); intro P.\n    unfold guppy_unage.\n    unfold compose, strat, unstrat.\n    simpl.\n    apply stratifies_unique with (unstratify x k).\n    revert k.\n    induction x; simpl; intuition.\n    destruct (decompose_nat 0 0); auto.\n    destruct s; exfalso; lia.\n    eapply (stratifies_unstratify_more x 0 1).\n    simpl; reflexivity.\n    simpl.\n    simpl in *.\n    destruct (IHx (fst (proj1_sig k))); auto.\n    destruct (decompose_nat x (S x)).\n    destruct s.\n    assert (x0 = 0) by lia; subst x0.\n    simpl in *.\n    replace e with (refl_equal (S x)) by apply proof_irr; auto.\n    exfalso; lia.\n    destruct (decompose_nat x (S x)).\n    destruct s.\n    assert (x0 = 0) by lia; subst x0.\n    simpl in *.\n    destruct (decompose_nat (S x) (S x)).\n    destruct s; exfalso; lia.\n    auto.\n    destruct (decompose_nat (S x) (S x)).\n    destruct s; exfalso; lia.\n    auto.\n\n    destruct (stratify (unstratify x k) (unstratify_hered x k) (S x)).\n    simpl stratifies in s; case s; intros.\n    simpl stratifies; split; auto.\n  Qed.\n\n  Lemma strat_unstrat_Sx : forall x,\n    sinv_age x = strat x oo unstrat (S x).\n  Proof.\n    intros.\n    extensionality k.\n    unfold sinv_age, guppy_age.\n    unfold compose.\n    unfold strat, unstrat.\n    simpl.\n    apply stratifies_unique with (unstratify x (fst (proj1_sig k))).\n    revert k; induction x; simpl; auto.\n    intros.\n    split.\n    eapply (stratifies_unstratify_more x 0 1 ).\n    simpl; reflexivity.\n    simpl.\n    apply IHx.\n    intros.\n    destruct (decompose_nat x (S x)).\n    destruct s.\n    assert (x0 = 0) by lia; subst x0.\n    simpl in *.\n    replace e with (refl_equal (S x)) by apply proof_irr; simpl.\n    tauto.\n    exfalso; lia.\n    destruct (stratify (unstratify (S x) k)\n      (unstratify_hered (S x) k) x).\n    simpl; auto.\n    cut (x0 = (fst (proj1_sig k))); intros.\n    subst x0.\n    eapply (stratifies_unstratify_more x 1 0).\n    simpl; reflexivity.\n    simpl; auto.\n    eapply stratifies_unique.\n    apply s.\n    eapply (stratifies_unstratify_more x 0 1).\n    simpl; reflexivity.\n    simpl.\n    generalize (fst (proj1_sig k) : sinv x).\n    clear.\n    induction x; simpl; intuition.\n    eapply (stratifies_unstratify_more x 0 1).\n    simpl; reflexivity.\n    simpl.\n    apply IHx.\n    destruct (decompose_nat x (S x)).\n    destruct s0.\n    assert (x0 = 0) by lia; subst.\n    simpl in *.\n    replace e with (refl_equal (S x)); simpl; auto.\n    apply proof_irr.\n    exfalso; lia.\n  Qed.\n\n  Lemma age1_eq : forall k,\n    age1_def k = knot_age1_def k.\n  Proof.\n    intros.\n    unfold knot_age1_def.\n    case_eq (unsquash k); intros.\n    case_eq k; intros.\n    simpl.\n    assert (n = x).\n    subst k.\n    inv H; auto.\n    subst x.\n    destruct n; auto.\n    f_equal.\n    f_equal.\n\n    rewrite strat_Sx_unstrat.\n    rewrite strat_unstrat_Sx.\n    rewrite <- fmap_comp.\n    unfold compose.\n    f_equal.\n    subst k.\n    inv H; auto.\n  Qed.\n\n  Lemma unsquash_inj : forall k1 k2,\n    unsquash k1 = unsquash k2 ->\n    k1 = k2.\n  Proof.\n    intros.\n    rewrite <- (squash_unsquash k1).\n    rewrite <- (squash_unsquash k2).\n    rewrite H.\n    trivial.\n  Qed.\n  Arguments unsquash_inj [k1 k2] _.\n\n\n  Lemma pred_ext : forall (p1 p2:predicate),\n    (forall x, proj1_sig p1 x = proj1_sig p2 x) ->\n    p1 = p2.\n  Proof.\n    intros.\n    destruct p1 as [p1 Hp1]; destruct p2 as [p2 Hp2].\n    simpl in *.\n    assert (p1 = p2).\n    extensionality x; auto.\n    subst p2.\n    replace Hp2 with Hp1; auto.\n    apply proof_irr.\n  Qed.\n\n  Lemma approx_spec : forall n p ko,\n    proj1_sig (approx n p) ko =\n     if (Compare_dec.le_gt_dec n (knot_level_def (fst ko))) then T_bot else proj1_sig p ko.\n  Proof.\n    intros; simpl; auto.\n  Qed.\n\n  Lemma ag_knot_facts : ageable_facts knot knot_level_def knot_age1_def.\n  Proof.\n    constructor.\n\n    unfold knot_age1_def; unfold knot_level_def; simpl; intros x'.\n    destruct (unsquash x') as [n f] eqn:?H; intros.\n    destruct x' as [x f0].\n    exists (squash (S x, fmap F (unstrat x) (strat x) f0)).\n    rewrite unsquash_squash.\n    f_equal. f_equal.\n    clear.\n    transitivity ((fmap F (strat x) (unstrat x) oo fmap F (approx (S x)) (approx (S x)) oo fmap F (unstrat x) (strat x)) f0); auto.\n    do 2 rewrite fmap_comp.\n    rewrite compose_assoc.\n    replace (strat x oo approx (S x) oo unstrat x) with (@id (sinv x)).\n    rewrite fmap_id. auto.\n    rewrite <- (strat_unstrat x).\n    f_equal.\n    extensionality a.\n    unfold compose, approx.\n    case_eq (unstrat x a); intros.\n    match goal with\n      [ |- _ = exist _ ?X _ ] =>\n      assert (x0 = X)\n    end.\n   2:{\n    generalize (approx_obligation_1 (S x)\n      (exist (fun p => hered p) x0 h)).\n    rewrite <- H0.\n    intros. f_equal.\n    }\n    extensionality.\n    destruct x1.\n    unfold unstrat in H.\n    inv H.\n    destruct k.\n    unfold unstratify.\n    unfold knot_level_def.\n    simpl fst.\n    destruct (decompose_nat x0 x).\n    destruct s.\n    destruct (Compare_dec.le_gt_dec (S x) x0).\n    exfalso; lia.\n    simpl.\n    destruct (decompose_nat x0 x).\n    destruct s.\n    assert (x1 = x2) by lia.\n    subst x2.\n    replace e0 with e by apply proof_irr.\n    auto.\n    exfalso; lia.\n    destruct (Compare_dec.le_gt_dec (S x) x0); auto.\n    simpl.\n    destruct (decompose_nat x0 x); auto.\n    destruct s. exfalso. lia.\n\n    intro.\n    unfold knot_age1_def, knot_level_def.\n    case_eq (unsquash x); intros.\n    destruct n; simpl; intuition;\n      discriminate.\n\n    intros.\n    unfold knot_age1_def, knot_level_def in *.\n    case_eq (unsquash x); intros; rewrite H0 in H.\n    destruct n; try discriminate; simpl.\n    inv H; simpl; auto.\n  Qed.\n\n  Definition ageable_knot : ageable knot :=\n    mkAgeable knot knot_level_def knot_age1_def ag_knot_facts.\n  #[global] Existing Instance ageable_knot.\n\n  Definition knot_rel (k1 k2:knot) :=\n    let (n,f) := unsquash k1 in\n    let (n',f') := unsquash k2 in\n    n = n' /\\ Rel predicate f f'.\n\n  Lemma hered_spec : forall p,\n    hered p =\n    (forall k k' k'' o o',\n      clos_refl_trans _ age k k' ->\n      knot_rel  k' k'' ->\n      ORel o o' ->\n      T_rel (p (k,o)) (p (k'',o'))).\n  Proof.\n    intros.\n    apply prop_ext.\n    intuition.\n    eapply H.\n    instantiate (1:=k').\n    clear -H0; induction H0; auto.\n    apply rt_step.\n    unfold age_def.\n    rewrite age1_eq.\n    auto.\n    eapply rt_trans; eauto.\n    destruct k' as [x f], k'' as [x0 f0].\n    unfold knot_rel, unsquash in H1.\n    destruct H1; subst.\n    constructor.\n    apply (Rel_fmap _ _ (strat x0) (unstrat x0)) in H3.\n    change f with (id _ f).\n    change f0 with (id _ f0).\n    rewrite <- fmap_id.\n    rewrite <- (strat_unstrat x0).\n    rewrite <- fmap_comp.\n    auto.\n    assumption.\n\n    hnf; intros.\n    apply (H k k' k''); auto.\n    clear -H0; induction H0; auto.\n    apply rt_step.\n    hnf.\n    rewrite <- age1_eq; auto.\n    eapply rt_trans; eauto.\n\n    destruct k'; destruct k''.\n    inv H1.\n    simpl.\n    hnf; split; auto.\n    apply Eqdep_dec.inj_pair2_eq_dec in H5; auto.\n    apply Eqdep_dec.inj_pair2_eq_dec in H7; auto.\n    subst.\n    apply Rel_fmap; auto.\n    exact Peano_dec.eq_nat_dec.\n    exact Peano_dec.eq_nat_dec.\n  Qed.\n\n  Lemma knot_age1 : forall k:knot,\n    age1 k =\n    match unsquash k with\n    | (O,_) => None\n    | (S n,x) => Some (squash (n,x))\n    end.\n  Proof.\n    intros; reflexivity.\n  Qed.\n\n  Lemma knot_level : forall k:knot,\n    level k = fst (unsquash k).\n  Proof.\n    intros; reflexivity.\n  Qed.\n\n  #[export] Program Instance ext_knot : Ext_ord knot := { ext_order := knot_rel }.\n  Next Obligation.\n  Proof.\n    unfold knot_rel. split.\n    - intros k.\n      destruct (unsquash k); split; auto.\n      apply Rel_refl.\n    - intros k1 k2 k3.\n      destruct (unsquash k1), (unsquash k2), (unsquash k3).\n      intros [] []; subst; split; auto.\n      eapply Rel_trans; eauto.\n  Qed.\n(*  Next Obligation.\n  Proof.\n    intros ?????.\n    unfold age, knot_rel in *. rewrite knot_age1 in H0.\n    destruct (unsquash z) eqn: Hz.\n    destruct n; inv H0.\n    rewrite unsquash_squash in H.\n    destruct (unsquash x) eqn: Hx.\n    destruct H as [? H]; subst.\n    exists (squash (S n0, _f0)); simpl.\n    - rewrite knot_age1, unsquash_squash.\n      f_equal; apply unsquash_inj.\n      rewrite unsquash_squash, Hx.\n      rewrite fmap_app, <- (approx_approx1 1), <- (approx_approx2 1), <- (unsquash_approx Hx).\n      reflexivity.\n    - rewrite unsquash_squash; split; auto.\n      rewrite (unsquash_approx Hz); rewrite (unsquash_approx Hx) in *.\n      rewrite fmap_app, <- (approx_approx1 1), <- (approx_approx2 1).\n      (* may not be true: the unaged pred may not be in Rel even if the aged one is *)\n      admit.\n  Admitted.*)\n  Next Obligation.\n  Proof.\n    intros ?????.\n    unfold age, knot_rel in *. rewrite knot_age1 in H.\n    destruct (unsquash y) eqn: Hy.\n    destruct n; inv H; simpl.\n    destruct (unsquash z) eqn: Hz.\n    destruct H0 as [? H0]; subst.\n    exists (squash (n, _f0)); simpl.\n    - split; auto.\n      do 2 apply Rel_fmap; auto.\n    - rewrite knot_age1, Hz; auto.\n  Qed.\n  Next Obligation.\n  Proof.\n    unfold age, knot_rel in *. rewrite knot_age1 in H0.\n    destruct (unsquash a) eqn: Ha.\n    destruct n; inv H0.\n    destruct (unsquash b) eqn: Hb.\n    destruct H as [? H]; subst.\n    exists (squash (n, _f0)).\n    split.\n    - rewrite knot_age1, Hb; auto.\n    - rewrite !unsquash_squash; split; auto.\n      rewrite fmap_app, unstrat_strat.\n      apply Rel_fmap; auto.\n  Qed.\n  Next Obligation.\n  Proof.\n    rewrite !knot_level. unfold knot_rel in H.\n    destruct (unsquash a), (unsquash b), H; auto.\n  Qed.\n\n  Lemma knot_order : ext_order = knot_rel.\n  Proof. reflexivity. Qed.\n\nEnd Knot_MixVariantHeredTOthRel.\n\nModule KnotLemmas1.\n\nClass Input: Type := {\n  knot: Type;\n  Fpred: Type;\n  squash: nat * Fpred -> knot;\n  unsquash: knot -> nat * Fpred;\n  approxF: nat -> Fpred -> Fpred;\n  squash_unsquash : forall k:knot, squash (unsquash k) = k;\n  unsquash_squash : forall (n:nat) (f:Fpred),\n    unsquash (squash (n,f)) = (n, approxF n f)\n}.\n\nClass Output (input: Input): Prop := {\n  unsquash_inj : forall k1 k2,\n    unsquash k1 = unsquash k2 ->\n    k1 = k2;\n  squash_surj : forall k, exists n, exists Fp,\n    squash (n, Fp) = k;\n  unsquash_approx : forall k n Fp,\n    unsquash k = (n, Fp) ->\n    Fp = approxF n Fp\n}.\n\nLemma Proof (kli: Input): Output kli.\nProof.\n  constructor.\n  + intros.\n    rewrite <- (squash_unsquash k1).\n    rewrite <- (squash_unsquash k2).\n    rewrite H.\n    trivial.\n  + intros.\n    remember (unsquash k).\n    destruct p as [n f].\n    exists n.\n    exists f.\n    rewrite Heqp.\n    rewrite squash_unsquash.\n    trivial.\n  + intros.\n    generalize H; intro.\n    rewrite <- (squash_unsquash k) in H.\n    rewrite H0 in H.\n    rewrite unsquash_squash in H.\n    inversion H.\n    rewrite H2.\n    symmetry.\n    trivial.\nQed.\n\nEnd KnotLemmas1.\n\nModule KnotLemmas2.\n\nClass Input: Type := {\n  knot: Type;\n  other: Type;\n  T: Type;\n  t0: T;\n  ageable_knot : ageable knot;\n  predicate: Type;\n  p2p: predicate -> (knot * other -> T);\n  approx : nat -> predicate -> predicate;\n  pred_ext : forall (p1 p2:predicate),\n    (forall x, p2p p1 x = p2p p2 x) ->\n    p1 = p2;\n  approx_spec : forall n p ko,\n    p2p (approx n p) ko =\n     if (Compare_dec.le_gt_dec n (level (fst ko))) then t0 else p2p p ko\n}.\n\nClass Output (input: Input): Prop := {\n  approx_approx1 : forall m n,\n    approx n = approx n oo approx (m+n);\n  approx_approx2 : forall m n,\n    approx n = approx (m+n) oo approx n\n}.\n\nLemma Proof (kli: Input): Output kli.\nProof.\n  constructor.\n  + intros.\n    extensionality p.\n    apply pred_ext.\n    intros [k o].\n    unfold compose.\n    repeat rewrite approx_spec.\n    simpl.\n    destruct (Compare_dec.le_gt_dec n (level k)); auto.\n    destruct (Compare_dec.le_gt_dec (m+n) (level k)); auto.\n    exfalso; lia.\n  + intros.\n    extensionality p.\n    apply pred_ext.\n    intros [k o].\n    unfold compose.\n    repeat rewrite approx_spec.\n    simpl.\n    destruct (Compare_dec.le_gt_dec (m+n) (level k)); auto.\n    destruct (Compare_dec.le_gt_dec n (level k)); auto.\n    exfalso; lia.\nQed.\n\nEnd KnotLemmas2.\n\nModule KnotLemmas_MixVariantHeredTOthRel (K : KNOT__MIXVARIANT_HERED_T_OTH_REL).\n  Import K.KI.\n  Import K.\n\n  Lemma unsquash_inj : forall k1 k2,\n    unsquash k1 = unsquash k2 ->\n    k1 = k2.\n  Proof.\n    apply\n     (@KnotLemmas1.unsquash_inj\n       (KnotLemmas1.Build_Input _ _ _ _ _ squash_unsquash unsquash_squash)),\n     (KnotLemmas1.Proof).\n  Qed.\n  Arguments unsquash_inj [k1 k2] _.\n\n  Lemma squash_surj : forall k, exists n, exists Fp,\n    squash (n, Fp) = k.\n  Proof.\n    apply\n     (@KnotLemmas1.squash_surj\n       (KnotLemmas1.Build_Input _ _ _ _ _ squash_unsquash unsquash_squash)),\n     (KnotLemmas1.Proof).\n  Qed.\n\n  Lemma unsquash_approx : forall k n Fp,\n    unsquash k = (n, Fp) ->\n    Fp = fmap F (approx n) (approx n) Fp.\n  Proof.\n    apply\n     (@KnotLemmas1.unsquash_approx\n       (KnotLemmas1.Build_Input _ _ _ _ _ squash_unsquash unsquash_squash)),\n     (KnotLemmas1.Proof).\n  Qed.\n  Arguments unsquash_approx [k n Fp] _.\n\n  Lemma pred_ext : forall (p1 p2:predicate),\n    (forall x, proj1_sig p1 x = proj1_sig p2 x) ->\n    p1 = p2.\n  Proof.\n    intros.\n    destruct p1 as [p1 Hp1]; destruct p2 as [p2 Hp2].\n    simpl in *.\n    assert (p1 = p2).\n    extensionality x; auto.\n    subst p2.\n    replace Hp2 with Hp1; auto.\n    apply proof_irr.\n  Qed.\n\n  Lemma approx_approx1 : forall m n,\n    approx n = approx n oo approx (m+n).\n  Proof.\n    apply\n     (@KnotLemmas2.approx_approx1\n       (KnotLemmas2.Build_Input _ _ _ _ _ _ _ _ pred_ext approx_spec)),\n     (KnotLemmas2.Proof).\n  Qed.\n\n  Lemma approx_approx2 : forall m n,\n    approx n = approx (m+n) oo approx n.\n  Proof.\n    apply\n     (@KnotLemmas2.approx_approx2\n       (KnotLemmas2.Build_Input _ _ _ _ _ _ _ _ pred_ext approx_spec)),\n     (KnotLemmas2.Proof).\n  Qed.\n\nEnd KnotLemmas_MixVariantHeredTOthRel.\n\nModule Type KNOT_FULL_OUTPUT.\n  Declare Module KI: KNOT_INPUT__MIXVARIANT_HERED_T_OTH_REL.\n  Declare Module K0: KNOT__MIXVARIANT_HERED_T_OTH_REL with Module KI := KI.\n  Import K0.\n  Parameter predicate: Type.\n  Parameter pkp: bijection predicate K0.predicate.\nEnd KNOT_FULL_OUTPUT.\n\nModule Type KNOT_FULL.\n  Declare Module KI: KNOT_INPUT__MIXVARIANT_HERED_T_OTH_REL.\n  Declare Module KO: KNOT_FULL_OUTPUT with Module KI := KI.\n  Import KI.\n  Import KO.\n\n  Definition knot : Type := KO.K0.knot.\n  Definition ageable_knot : ageable knot := KO.K0.ageable_knot.\n  #[global] Existing Instance ageable_knot.\n  Definition ext_knot : Ext_ord knot := KO.K0.ext_knot.\n  #[global] Existing Instance ext_knot.\n  Definition predicate: Type := KO.predicate.\n\n  Definition squash : (nat * KI.F predicate) -> knot :=\n    fun k => KO.K0.squash\n     (fst k, fmap KI.F (bij_f _ _ KO.pkp) (bij_g _ _ KO.pkp) (snd k)).\n\n  Definition unsquash : knot -> (nat * KI.F predicate) :=\n    fun k => let (n, f) := KO.K0.unsquash k in\n      (n, fmap KI.F (bij_g _ _ KO.pkp) (bij_f _ _ KO.pkp) f).\n\n  Parameter approx : nat -> predicate -> predicate.\n\n  Axiom squash_unsquash : forall k:knot, squash (unsquash k) = k.\n  Axiom unsquash_squash : forall (n:nat) (f:F predicate),\n    unsquash (squash (n,f)) = (n, fmap F (approx n) (approx n) f).\n\n  Axiom approx_spec : forall n p ko,\n    proj1_sig (bij_f _ _ KO.pkp (approx n p)) ko =\n     if (Compare_dec.le_gt_dec n (level (fst ko)))\n     then KI.T_bot\n     else proj1_sig (bij_f _ _ KO.pkp p) ko.\n\n  Axiom knot_age1 : forall k:knot,\n    age1 k =\n    match unsquash k with\n    | (O,_) => None\n    | (S n,x) => Some (squash (n,x))\n    end.\n\n  Axiom knot_level : forall k:knot,\n    level k = fst (unsquash k).\n\n  Definition knot_rel (k1 k2:knot) :=\n    let (n,f) := unsquash k1 in\n    let (n',f') := unsquash k2 in\n    n = n' /\\ KI.Rel predicate f f'.\n\n  Axiom knot_rel_spec: forall k1 k2: knot,\n    knot_rel k1 k2 = KO.K0.knot_rel k1 k2.\n\nEnd KNOT_FULL.\n\nModule Type KNOT_FULL_LEMMAS.\n  Declare Module K: KNOT_FULL.\n  Import K.\n\n  Axiom unsquash_inj : forall k1 k2,\n    unsquash k1 = unsquash k2 ->\n    k1 = k2.\n  Arguments unsquash_inj [k1 k2] _.\n\n  Axiom squash_surj : forall k, exists n, exists Fp,\n    squash (n, Fp) = k.\n\n  Axiom unsquash_approx : forall k n Fp,\n    unsquash k = (n, Fp) ->\n    Fp = fmap KI.F (approx n) (approx n) Fp.\n  Arguments unsquash_approx [k n Fp] _.\n\n  Axiom approx_approx1 : forall m n,\n    approx n = approx n oo approx (m+n).\n\n  Axiom approx_approx2 : forall m n,\n    approx n = approx (m+n) oo approx n.\n\nEnd KNOT_FULL_LEMMAS.\n\nModule KnotFull\n  (KI': KNOT_INPUT__MIXVARIANT_HERED_T_OTH_REL)\n  (KO': KNOT_FULL_OUTPUT with Module KI := KI'):\n  KNOT_FULL with Module KI := KI' with Module KO:=KO'.\n\n  Import MixVariantFunctor.\n  Module KI:=KI'.\n  Module KO:=KO'.\n\n  Definition knot: Type := KO.K0.knot.\n  Definition ageable_knot : ageable knot := KO.K0.ageable_knot.\n  #[global] Existing Instance ageable_knot.\n  Definition ext_knot : Ext_ord knot := KO.K0.ext_knot.\n  #[global] Existing Instance ext_knot.\n  Definition predicate: Type := KO.predicate.\n\n  Definition squash : (nat * KI.F predicate) -> knot :=\n    fun k => KO.K0.squash\n     (fst k, fmap KI.F (bij_f _ _ KO.pkp) (bij_g _ _ KO.pkp) (snd k)).\n\n  Definition unsquash : knot -> (nat * KI.F predicate) :=\n    fun k => let (n, f) := KO.K0.unsquash k in\n      (n, fmap KI.F (bij_g _ _ KO.pkp) (bij_f _ _ KO.pkp) f).\n\n  Definition approx : nat -> predicate -> predicate :=\n    fun n => (bij_g _ _ KO.pkp) oo KO.K0.approx n oo (bij_f _ _ KO.pkp).\n\n  Lemma squash_unsquash : forall k:knot, squash (unsquash k) = k.\n  Proof.\n    intros; unfold squash, unsquash.\n    destruct (KO.K0.unsquash k) as [n f] eqn:?H; simpl.\n    rewrite fmap_app, bij_fg_id, fmap_id.\n    unfold id.\n    rewrite <- H; apply KO.K0.squash_unsquash.\n  Qed.\n\n  Lemma unsquash_squash : forall (n:nat) (f:KI.F predicate),\n    unsquash (squash (n,f)) = (n, fmap KI.F (approx n) (approx n) f).\n  Proof.\n    intros; unfold squash, unsquash, approx; simpl.\n    rewrite KO.K0.unsquash_squash, !fmap_app, compose_assoc.\n    auto.\n  Qed.\n\n  Lemma approx_spec : forall n p ko,\n    proj1_sig (bij_f _ _ KO.pkp (approx n p)) ko =\n     if (Compare_dec.le_gt_dec n (level (fst ko)))\n     then KI.T_bot\n     else proj1_sig (bij_f _ _ KO.pkp p) ko.\n  Proof.\n    intros.\n    rewrite <- KO.K0.approx_spec.\n    unfold approx.\n    pattern (KO.K0.approx n) at 2.\n    rewrite <- (id_unit2 _ _ (KO.K0.approx n)), <- (bij_fg_id KO.pkp).\n    reflexivity.\n  Qed.\n\n  Lemma knot_age1 : forall k:knot,\n    age1 k =\n    match unsquash k with\n    | (O,_) => None\n    | (S n,x) => Some (squash (n,x))\n    end.\n  Proof.\n    intros.\n    unfold squash, unsquash.\n    rewrite KO.K0.knot_age1.\n    destruct (KO.K0.unsquash k) as [n f] eqn:?H.\n    destruct n; auto.\n    f_equal; simpl.\n    rewrite fmap_app, bij_fg_id, fmap_id.\n    auto.\n  Qed.\n\n  Lemma knot_level: forall k:knot, level k = fst (unsquash k).\n  Proof.\n    intros.\n    unfold unsquash.\n    rewrite KO.K0.knot_level.\n    destruct (KO.K0.unsquash k) as [n f]; auto.\n  Qed.\n\n  Definition knot_rel (k1 k2:knot) :=\n    let (n,f) := unsquash k1 in\n    let (n',f') := unsquash k2 in\n    n = n' /\\ KI.Rel predicate f f'.\n\n  Lemma knot_rel_spec: forall k1 k2: knot,\n    knot_rel k1 k2 = KO.K0.knot_rel k1 k2.\n  Proof.\n    intros.\n    unfold knot_rel, KO.K0.knot_rel, unsquash.\n    destruct (KO.K0.unsquash k1) as [n1 f1].\n    destruct (KO.K0.unsquash k2) as [n2 f2].\n    f_equal.\n    apply prop_ext.\n    split; intros.\n    + pose proof KI.Rel_fmap _ _ (bij_f _ _ KO.pkp) (bij_g _ _ KO.pkp) _ _ H.\n      rewrite !fmap_app, bij_fg_id, fmap_id in H0.\n      auto.\n    + pose proof KI.Rel_fmap _ _ (bij_g _ _ KO.pkp) (bij_f _ _ KO.pkp) _ _ H.\n      auto.\n  Qed.\n\nEnd KnotFull.\n\nModule KnotFullLemmas (K: KNOT_FULL).\n  Import K.KI.\n  Import K.\n\n  Lemma unsquash_inj : forall k1 k2,\n    unsquash k1 = unsquash k2 ->\n    k1 = k2.\n  Proof.\n    apply\n     (@KnotLemmas1.unsquash_inj\n       (KnotLemmas1.Build_Input _ _ _ _ _ squash_unsquash unsquash_squash)),\n     (KnotLemmas1.Proof).\n  Qed.\n  Arguments unsquash_inj [k1 k2] _.\n\n  Lemma squash_surj : forall k, exists n, exists Fp,\n    squash (n, Fp) = k.\n  Proof.\n    apply\n     (@KnotLemmas1.squash_surj\n       (KnotLemmas1.Build_Input _ _ _ _ _ squash_unsquash unsquash_squash)),\n     (KnotLemmas1.Proof).\n  Qed.\n\n  Lemma unsquash_approx : forall k n Fp,\n    unsquash k = (n, Fp) ->\n    Fp = fmap F (approx n) (approx n) Fp.\n  Proof.\n    apply\n     (@KnotLemmas1.unsquash_approx\n       (KnotLemmas1.Build_Input _ _ _ _ _ squash_unsquash unsquash_squash)),\n     (KnotLemmas1.Proof).\n  Qed.\n  Arguments unsquash_approx [k n Fp] _.\n\n  Lemma pred_ext : forall (p1 p2:predicate),\n    (forall x, proj1_sig (bij_f _ _ KO.pkp p1) x =\n               proj1_sig (bij_f _ _ KO.pkp p2) x) ->\n    p1 = p2.\n  Proof.\n    intros.\n    change (p1 = p2) with (id K.KO.predicate p1 = id K.KO.predicate p2).\n    rewrite <- (bij_gf_id KO.pkp); unfold compose.\n    destruct (bij_f _ _ KO.pkp p1) as [pp1 Hp1];\n    destruct (bij_f _ _ KO.pkp p2) as [pp2 Hp2].\n    simpl in *.\n    assert (pp1 = pp2).\n    extensionality x; auto.\n    subst pp2.\n    replace Hp2 with Hp1; auto.\n    apply proof_irr.\n  Qed.\n\n  Lemma approx_approx1 : forall m n,\n    approx n = approx n oo approx (m+n).\n  Proof.\n    apply\n     (@KnotLemmas2.approx_approx1\n       (KnotLemmas2.Build_Input _ _ _ _ _ _\n         (@proj1_sig _ _ oo bij_f _ _ K.KO.pkp) _ pred_ext approx_spec)),\n     (KnotLemmas2.Proof).\n  Qed.\n\n  Lemma approx_approx2 : forall m n,\n    approx n = approx (m+n) oo approx n.\n  Proof.\n    apply\n     (@KnotLemmas2.approx_approx2\n       (KnotLemmas2.Build_Input _ _ _ _ _ _\n         (@proj1_sig _ _ oo bij_f _ _ K.KO.pkp) _ pred_ext approx_spec)),\n     (KnotLemmas2.Proof).\n  Qed.\n\nEnd KnotFullLemmas.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n(*\nModule Type KNOT_FULL_INPUT.\n  Parameter F : functor.\n\n  Parameter other : Type.\n\n  Parameter Rel : forall A, F A -> F A -> Prop.\n\n  Parameter Rel_fmap : forall A B (f1: A->B) (f2:B->A) x y,\n    Rel A x y ->\n    Rel B (fmap F f1 f2 x) (fmap F f1 f2 y).\n  Axiom Rel_refl : forall A x, Rel A x x.\n  Axiom Rel_trans : forall A x y z,\n    Rel A x y -> Rel A y z -> Rel A x z.\n\n  Parameter ORel : other -> other -> Prop.\n  Axiom ORel_refl : reflexive other ORel.\n  Axiom ORel_trans : transitive other ORel.\n\n  Parameter T:Type.\n  Parameter T_bot:T.\n\n  Parameter T_rel : T -> T -> Prop.\n  Parameter T_rel_bot : forall x, T_rel T_bot x.\n  Parameter T_rel_refl : forall x, T_rel x x.\n  Parameter T_rel_trans : transitive T T_rel.\n\n  Parameter Pred: forall K: Type, ageable K -> (K -> K -> Prop) -> Type.\n\n  Parameter Pred2predicate: forall {K agK KRel},\n    Pred K agK KRel ->\n    { p: K * other -> T |\n      (forall k k' k'' o o',\n      clos_refl_trans _ age k k' ->\n      KRel k' k'' ->\n      ORel o o' ->\n      T_rel (p (k,o)) (p (k'',o'))) }.\n\n  Parameter predicate2Pred: forall {K agK} {KRel: K -> K -> Prop},\n    { p: K * other -> T |\n      (forall (k k' k'': K) o o',\n      clos_refl_trans _ age k k' ->\n      KRel k' k'' ->\n      ORel o o' ->\n      T_rel (p (k,o)) (p (k'',o'))) } ->\n    Pred K agK KRel.\n\n  Axiom P2p2P: forall K agK KRel (P: Pred K agK KRel),\n    predicate2Pred (Pred2predicate P) = P.\n\n  Axiom p2P2p: forall K agK KRel p,\n    Pred2predicate (@predicate2Pred K agK KRel p) = p.\n\nEnd KNOT_FULL_INPUT.\n\nModule Type KNOT_FULL.\n  Declare Module KI: KNOT_FULL_INPUT.\n  Import KI.\n\n  Parameter knot:Type.\n  Parameter ageable_knot : ageable knot.\n  #[global] Existing Instance ageable_knot.\n  Parameter knot_rel: knot -> knot -> Prop.\n\n  Definition predicate: Type := Pred knot ageable_knot knot_rel.\n\n  Parameter squash : (nat * F predicate) -> knot.\n  Parameter unsquash : knot -> (nat * F predicate).\n\n  Parameter approx : nat -> predicate -> predicate.\n\n  Axiom squash_unsquash : forall k:knot, squash (unsquash k) = k.\n  Axiom unsquash_squash : forall (n:nat) (f:F predicate),\n    unsquash (squash (n,f)) = (n, fmap F (approx n) (approx n) f).\n\n  Axiom approx_spec : forall n p ko,\n    proj1_sig (Pred2predicate (approx n (predicate2Pred p))) ko =\n     if (le_gt_dec n (level (fst ko))) then T_bot else proj1_sig p ko.\n\n  Axiom knot_rel_spec: forall (k1 k2:knot),\n     knot_rel k1 k2 =\n    let (n,f) := unsquash k1 in\n    let (n',f') := unsquash k2 in\n    n = n' /\\ Rel predicate f f'.\n\n  Axiom knot_age1 : forall k:knot,\n    age1 k =\n    match unsquash k with\n    | (O,_) => None\n    | (S n,x) => Some (squash (n,x))\n    end.\n\n  Axiom knot_level : forall k:knot,\n    level k = fst (unsquash k).\n\nEnd KNOT_FULL.\n\nModule KnotFull (KI': KNOT_FULL_INPUT): KNOT_FULL with Module KI:=KI'.\n\n  Import MixVariantFunctor.\n  Module KI:=KI'.\n\n  Module Input.\n    Definition F: functor := KI.F.\n    Definition other: Type := KI.other.\n    Definition Rel: forall (A:Type), KI.F A -> KI.F A -> Prop := KI.Rel.\n\n    Definition Rel_fmap : forall A B (f1: A->B) (f2:B->A) x y,\n      Rel A x y ->\n      Rel B (fmap F f1 f2 x) (fmap F f1 f2 y)\n      := KI.Rel_fmap.\n\n    Definition Rel_refl : forall A x, Rel A x x := KI.Rel_refl.\n\n    Definition Rel_trans : forall A x y z,\n      Rel A x y -> Rel A y z -> Rel A x z\n      := KI.Rel_trans.\n\n    Definition ORel := KI.ORel.\n    Definition ORel_refl := KI.ORel_refl.\n    Definition ORel_trans := KI.ORel_trans.\n\n    Definition T := KI.T.\n    Definition T_bot: T := KI.T_bot.\n    Definition T_rel : T -> T -> Prop := KI.T_rel.\n    Definition T_rel_bot : forall x, T_rel T_bot x := KI.T_rel_bot.\n    Definition T_rel_refl : forall x, T_rel x x := KI.T_rel_refl.\n    Definition T_rel_trans : transitive T T_rel := KI.T_rel_trans.\n  End Input.\n\n  Module K := Knot_MixVariantHeredTOthRel(Input).\n  Module KL := KnotLemmas_MixVariantHeredTOthRel(K).\n\n  Definition knot: Type := K.knot.\n  Definition ageable_knot : ageable knot := K.ageable_knot.\n  #[global] Existing Instance ageable_knot.\n  Definition knot_rel: knot -> knot -> Prop := K.knot_rel.\n  Definition predicate: Type := KI.Pred knot ageable_knot knot_rel.\n\n  Definition squash : (nat * KI.F predicate) -> knot :=\n    fun k => K.squash (fst k, fmap KI.F KI.Pred2predicate KI.predicate2Pred (snd k)).\n\n  Parameter unsquash : knot -> (nat * F predicate).\n\n  Parameter approx : nat -> predicate -> predicate.\n\n  Axiom squash_unsquash : forall k:knot, squash (unsquash k) = k.\n  Axiom unsquash_squash : forall (n:nat) (f:F predicate),\n    unsquash (squash (n,f)) = (n, fmap F (approx n) (approx n) f).\n\n  Axiom approx_spec : forall n p ko,\n    proj1_sig (Pred2predicate (approx n (predicate2Pred p))) ko =\n     if (le_gt_dec n (level (fst ko))) then T_bot else proj1_sig p ko.\n\n  Axiom knot_rel_spec: forall (k1 k2:knot),\n     knot_rel k1 k2 =\n    let (n,f) := unsquash k1 in\n    let (n',f') := unsquash k2 in\n    n = n' /\\ Rel predicate f f'.\n\n  Axiom knot_age1 : forall k:knot,\n    age1 k =\n    match unsquash k with\n    | (O,_) => None\n    | (S n,x) => Some (squash (n,x))\n    end.\n\n  Axiom knot_level : forall k:knot,\n    level k = fst (unsquash k).\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/msl/knot_full_variant.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.2538861933349492}}
{"text": "(* begin hide *)\nFrom Coq Require Import\n     List\n     String\n     Logic.FunctionalExtensionality.\n\nFrom Vellvm Require Import\n     Utils.Util\n     Utils.ListUtil\n     Utils.Tactics\n     Syntax.LLVMAst\n     Syntax.AstLib\n     Syntax.CFG\n     Syntax.Traversal\n     Syntax.DynamicTypes.\n\nRequire Import Coqlib.\n\nImport CFGNotations.\nImport ListNotations.\nOpen Scope list_scope.\n(* end hide *)\n\n(** * Conversion from static to dynamic types\n    LLVM admits static types than can be recursive in the case of function types.\n    At run-time, this information is unnecessary, we therefore pre-process them by\n    converting them into a notion of dynamic types whose pointer type contains no\n    further information.\n    The conversion also inlines globally declared types (field [m_type_defs] of a [modul] (i.e. a [mcfg]).\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#[export] Hint Constructors typ_order : core.\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\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\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\nLtac destruct_prod :=\n  match goal with\n  | [ |- context[let (_, _) := ?p in _]] => destruct p\n  | [ p: ?A * ?B |- _ ] => destruct p\n  end.\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\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#[export] Hint Resolve wf_lt_typ_order : core.\n#[export] Hint Constructors lex_ord : core.\n\nProgram Fixpoint typ_to_dtyp (env : list (ident * typ)) (t : typ) {measure (List.length env, t) (lex_ord lt typ_order)} : dtyp :=\n  match t with\n  | TYPE_Array sz t =>\n    let nt := typ_to_dtyp env t in\n    DTYPE_Array sz nt\n\n  | TYPE_Function ret args =>\n    DTYPE_Pointer \n\n  | TYPE_Struct fields =>\n    let nfields := map_In fields (fun t _ => typ_to_dtyp env t) in\n    DTYPE_Struct nfields\n\n  | TYPE_Packed_struct fields =>\n    let nfields := map_In fields (fun t _ => typ_to_dtyp env t) in\n    DTYPE_Packed_struct nfields\n\n  | TYPE_Vector sz t =>\n    let nt := typ_to_dtyp env t in\n    DTYPE_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 => DTYPE_Void   (* TODO: should this be None? *)\n    | Some (_, t) => typ_to_dtyp (remove_key Ident.eq_dec id env) t\n    end\n\n  | TYPE_I sz => DTYPE_I sz\n  | TYPE_Pointer t' => DTYPE_Pointer\n  | TYPE_Void => DTYPE_Void\n  | TYPE_Half => DTYPE_Half\n  | TYPE_Float => DTYPE_Float\n  | TYPE_Double => DTYPE_Double\n  | TYPE_X86_fp80 => DTYPE_X86_fp80\n  | TYPE_Fp128 => DTYPE_Fp128\n  | TYPE_Ppc_fp128 => DTYPE_Ppc_fp128\n  | TYPE_Metadata => DTYPE_Metadata\n  | TYPE_X86_mmx => DTYPE_X86_mmx\n  | TYPE_Opaque => DTYPE_Opaque\n  end.\nNext Obligation.\n  left.\n  symmetry in Heq_opt. apply find_some in Heq_opt. destruct Heq_opt 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\nLemma typ_to_dtyp_equation  : forall env t,\n    typ_to_dtyp env t =\n    match t with\n    | TYPE_Array sz t =>\n      let nt := typ_to_dtyp env t in\n      DTYPE_Array sz nt\n\n    | TYPE_Function ret args =>\n      DTYPE_Pointer (* Function nret nargs *)\n\n    | TYPE_Struct fields =>\n      let nfields := map_In fields (fun t _ => typ_to_dtyp env t) in\n      DTYPE_Struct nfields\n\n    | TYPE_Packed_struct fields =>\n      let nfields := map_In fields (fun t _ => typ_to_dtyp env t) in\n      DTYPE_Packed_struct nfields\n\n    | TYPE_Vector sz t =>\n      let nt := typ_to_dtyp env t in\n      DTYPE_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 => DTYPE_Void   (* TODO: should this be None? *)\n      | Some (_, t) => typ_to_dtyp (remove_key Ident.eq_dec id env) t\n      end\n\n    | TYPE_I sz => DTYPE_I sz\n    | TYPE_Pointer t' => DTYPE_Pointer\n    | TYPE_Void => DTYPE_Void\n    | TYPE_Half => DTYPE_Half\n    | TYPE_Float => DTYPE_Float\n    | TYPE_Double => DTYPE_Double\n    | TYPE_X86_fp80 => DTYPE_X86_fp80\n    | TYPE_Fp128 => DTYPE_Fp128\n    | TYPE_Ppc_fp128 => DTYPE_Ppc_fp128\n    | TYPE_Metadata => DTYPE_Metadata\n    | TYPE_X86_mmx => DTYPE_X86_mmx\n    | TYPE_Opaque => DTYPE_Opaque\n    end.\nProof.\n  intros env t.\n  unfold typ_to_dtyp.\n  unfold typ_to_dtyp_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(* Specialized version of the characteristic equation for contexts where we don't want to compute *)\nLemma typ_to_dtyp_I : forall s i, typ_to_dtyp s (TYPE_I i) = DTYPE_I i.\nProof.\n  intros; rewrite typ_to_dtyp_equation; reflexivity.\nQed.\n\nLemma typ_to_dtyp_D : forall s, typ_to_dtyp s TYPE_Double = DTYPE_Double.\nProof.\n  intros; rewrite typ_to_dtyp_equation; reflexivity.\nQed.\n\nLemma typ_to_dtyp_P :\n  forall t s,\n    typ_to_dtyp s (TYPE_Pointer t) = DTYPE_Pointer.\nProof.\n  intros t s.\n  apply typ_to_dtyp_equation.\nQed.\n\nLemma typ_to_dtyp_D_array : forall n s, typ_to_dtyp s (TYPE_Array n TYPE_Double) = DTYPE_Array n DTYPE_Double.\nProof.\n  intros.\n  rewrite typ_to_dtyp_equation.\n  rewrite typ_to_dtyp_D.\n  reflexivity.\nQed.\n\n(** ** Conversion of syntactic components\n\n    Front-ends and optimizations generate code containing static types.\n    Since the semantics always acts upon dynamic types, in order to reason\n    about the sub-components of code produce, we need to be able to convert\n    types of any syntactic substructure of Vellvm.\n\n    We leverage the parameterized [Tfmap] typeclass to do this in a fairly lightway.\n *)\nSection ConvertTyp.\n\n  Class ConvertTyp (F: Set -> Set) : Type :=\n    convert_typ : list (ident * typ) -> F typ -> F dtyp.\n\n  #[global] Instance ConvertTyp_exp : ConvertTyp exp :=\n    fun env => tfmap (typ_to_dtyp env).\n\n  #[global] Instance ConvertTyp_instr : ConvertTyp instr :=\n    fun env => tfmap (typ_to_dtyp env).\n\n  #[global] Instance ConvertTyp_term : ConvertTyp terminator :=\n    fun env => tfmap (typ_to_dtyp env).\n\n  #[global] Instance ConvertTyp_code : ConvertTyp code :=\n    fun env => tfmap (typ_to_dtyp env).\n\n  #[global] Instance ConvertTyp_phi : ConvertTyp phi :=\n    fun env => tfmap (typ_to_dtyp env).\n\n  #[global] Instance ConvertTyp_block : ConvertTyp block :=\n    fun env => tfmap (typ_to_dtyp env).\n\n  #[global] Instance ConvertTyp_cfg : ConvertTyp cfg :=\n    fun env => tfmap (typ_to_dtyp env).\n\n  #[global] Instance ConvertTyp_mcfg : ConvertTyp mcfg :=\n    fun env => tfmap (typ_to_dtyp env).\n\n  #[global] Instance ConvertTyp_list {A} `{TFunctor A}: ConvertTyp (fun T => list (A T)) :=\n    fun env => tfmap (typ_to_dtyp env).\n\nEnd ConvertTyp.\n\nLemma convert_typ_list_app :\n  forall {F} `{TFunctor F} (a b : list (F typ)) (env : list (ident * typ)),\n    convert_typ env (a ++ b)%list = (convert_typ env a ++ convert_typ env b)%list.\nProof.\n  intros F H a.\n  induction a; cbn; intros; auto.\n  rewrite IHa; reflexivity.\nQed.\n\n(**\n     Conversion to dynamic types\n *)\n\nDefinition convert_types (CFG:(CFG.mcfg typ)) : (CFG.mcfg dtyp) :=\n  convert_typ (m_type_defs CFG) CFG.\n\nLemma convert_typ_ocfg_app : forall (a b : ocfg typ) env, (convert_typ env (a ++ b) = convert_typ env a ++ convert_typ env b)%list.\nProof.\n  intros; rewrite convert_typ_list_app; reflexivity.\nQed.\n\nLemma convert_typ_code_app : forall (a b : code typ) env, (convert_typ env (a ++ b) = convert_typ env a ++ convert_typ env b)%list.\nProof.\n  induction a as [| [] a IH]; cbn; intros; auto.\n  rewrite IH; reflexivity.\nQed.\n\nLemma convert_typ_mcfg_app:\n  forall mcfg1 mcfg2 : modul (cfg typ),\n    convert_typ [] (mcfg1 @@ mcfg2) =\n    convert_typ [] mcfg1 @@ convert_typ [] mcfg2.\nProof.\n  intros [] []; cbn.\n  unfold convert_typ,ConvertTyp_mcfg,tfmap,TFunctor_mcfg; cbn.\n  f_equal; try (unfold endo, Endo_option; cbn; repeat flatten_goal; now intuition).\n  unfold tfmap, TFunctor_list; rewrite map_app; reflexivity.\n  unfold tfmap, TFunctor_list'; rewrite map_app; reflexivity.\n  unfold tfmap, TFunctor_list'; rewrite map_app; reflexivity.\n  unfold tfmap, TFunctor_list'; rewrite map_app; reflexivity.\nQed.\n\nLemma convert_types_app_mcfg : forall mcfg1 mcfg2,\n    m_type_defs mcfg1 = [] ->\n    m_type_defs mcfg2 = [] ->\n    convert_types (modul_app mcfg1 mcfg2) =\n    modul_app (convert_types mcfg1) (convert_types mcfg2).\nProof.\n  unfold convert_types.\n  intros * EQ1 EQ2.\n  rewrite m_type_defs_app, EQ1,EQ2.\n  cbn; rewrite convert_typ_mcfg_app.\n  reflexivity.\nQed.\n\nLemma mcfg_of_tle_app : forall x y,\n    m_type_defs (mcfg_of_modul (modul_of_toplevel_entities x)) = nil ->\n    m_type_defs (mcfg_of_modul (modul_of_toplevel_entities y)) = nil ->\n    convert_types (mcfg_of_tle (x ++ y)) =\n    modul_app (convert_types (mcfg_of_tle x)) (convert_types (mcfg_of_tle y)).\nProof.\n  intros. \n  unfold mcfg_of_tle.\n  rewrite modul_of_toplevel_entities_app.\n  rewrite mcfg_of_app_modul.\n  rewrite convert_types_app_mcfg; auto.\nQed.\n\nLemma mcfg_of_tle_cons : forall x y,\n    m_type_defs (mcfg_of_modul (modul_of_toplevel_entities [x])) = nil ->\n    m_type_defs (mcfg_of_modul (modul_of_toplevel_entities y)) = nil ->\n    convert_types (mcfg_of_tle (x :: y)) =\n    modul_app (convert_types  (mcfg_of_tle [x])) (convert_types  (mcfg_of_tle y)).\nProof.\n  intros; rewrite list_cons_app; apply mcfg_of_tle_app; auto.\nQed.\n\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/TypToDtyp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.25388619333494916}}
{"text": "Require Export Db.Inst.\nRequire Export Db.Lemmas.\nRequire Export Db.WellScoping.\nRequire Export StlcIso.SpecSyntax.\nRequire Export RecTypes.InstTy.\n\n#[export]\n#[refine] Instance vrTm : Vr Tm := {| vr := var |}.\nProof. inversion 1; auto. Defined.\n\nLocal Ltac crush :=\n  intros; cbn in * |-;\n  repeat\n    (cbn;\n     repeat crushStlcSyntaxMatchH;\n     repeat crushDbSyntaxMatchH;\n     repeat crushDbLemmasMatchH;\n     rewrite ?comp_up, ?up_liftSub, ?up_comp_lift\n    );\n  auto.\n\nModule TmKit <: Kit.\n\n  Definition TM := Tm.\n  Definition inst_vr := vrTm.\n\n  Section Application.\n\n    Context {Y: Type}.\n    Context {vrY : Vr Y}.\n    Context {wkY: Wk Y}.\n    Context {liftY: Lift Y Tm}.\n\n    #[export]\n    #[refine] Instance inst_ap : Ap Tm Y := {| ap := apTm |}.\n    Proof.\n      induction x; crush.\n    Defined.\n\n    #[export]\n    #[refine] Instance inst_ap_vr : LemApVr Tm Y := {}.\n    Proof. reflexivity. Qed.\n\n  End Application.\n\n  #[export]\n  #[refine] Instance inst_ap_inj: LemApInj Tm Ix := {}.\n  Proof.\n    intros m Inj_m x. revert m Inj_m.\n    induction x; destruct y; simpl; try discriminate;\n    inversion 1; subst; f_equal; eauto using InjSubIxUp.\n  Qed.\n\n  #[export]\n  #[refine] Instance inst_ap_comp (Y Z: Type)\n    {vrY: Vr Y} {wkY: Wk Y} {liftY: Lift Y Tm}\n    {vrZ: Vr Z} {wkZ: Wk Z} {liftZ: Lift Z Tm}\n    {apYZ: Ap Y Z} {compUpYZ: LemCompUp Y Z}\n    {apLiftYTmZ: LemApLift Y Z Tm} :\n    LemApComp Tm Y Z := {}.\n  Proof. induction x; crush. Qed.\n\n  #[export]\n  #[refine] Instance inst_ap_liftSub (Y: Type)\n    {vrY: Vr Y} {wkY: Wk Y} {liftY: Lift Y Tm} :\n    LemApLiftSub Tm Y := {}.\n  Proof. induction t; crush. Qed.\n\n  Lemma inst_ap_ixComp (t: Tm) :\n    ∀ (ξ: Sub Ix) (ζ: Sub Tm), t[ξ][ζ] = t[⌈ξ⌉ >=> ζ].\n  Proof. pose proof up_comp_lift. induction t; crush. Qed.\n\nEnd TmKit.\nModule InstTm := Inst TmKit.\nExport InstTm. (* Export for shorter names. *)\n\n#[export]\nInstance wsVrTm: WsVr Tm.\nProof.\n  constructor.\n  - now constructor.\n  - now inversion 1.\nQed.\n\nSection Application.\n\n  Context {Y: Type}.\n  Context {vrY : Vr Y}.\n  Context {wkY: Wk Y}.\n  Context {liftY: Lift Y Tm}.\n  Context {wsY: Ws Y}.\n  Context {wsVrY: WsVr Y}.\n  Context {wsWkY: WsWk Y}.\n  Context {wsLiftY: WsLift Y Tm}.\n\n  Hint Resolve wsLift : ws.\n  Hint Resolve wsSub_up : ws.\n\n\n  Global Instance wsApTm : WsAp Tm Y.\n  Proof.\n    constructor.\n    - intros ξ γ δ t wξ wt; revert ξ δ wξ.\n      induction wt; intros ξ δ wξ; crush;\n      try econstructor;\n      try match goal with\n            | |- wsTm ?δ ?t =>\n              change (wsTm δ t) with ⟨ δ ⊢ t ⟩\n          end; eauto with ws.\n    - intros γ t wt.\n      induction wt; crush.\n      + apply IHwt; inversion 1; crush.\n      + apply IHwt2; inversion 1; crush.\n      + apply IHwt3; inversion 1; crush.\n  Qed.\nEnd Application.\n\n#[export]\nInstance wsWkTm: WsWk Tm.\nProof.\n  constructor; crush.\n  - refine (wsAp _ H); eauto.\n    constructor; eauto.\nQed.\n(*   - admit. *)\n(*     (* induction x; cbn in H; inversion H. *) *)\n(*     (* + change (wk i) with (S i) in *. *) *)\n(*     (*   inversion H1; subst. eapply WsVar; eassumption. *) *)\n(*     (* +  *) *)\n(* Admitted. *)\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/StlcIso/Inst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526660244837, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.2538861933349491}}
{"text": "(* this file contains basic definitions and lemmas about registers and addresses *)\nFrom Coq Require Import ssreflect Eqdep_dec ZArith.\nFrom HypVeri Require Import machine monad stdpp_extra.\nFrom stdpp Require Import fin_maps list countable fin vector gmap.\n\n(* these definitions are frequently used *)\n\nSection VMID0.\n  Context `{hypconst:HypervisorConstants}.\n\n  Program Definition V0 : VMID := (@nat_to_fin 0 _ _).\n  Next Obligation.\n  destruct hypconst. simpl. lia.\n  Defined.\n\n  Lemma V0eq : (fin_to_nat V0) = 0.\n  Proof.\n    rewrite /V0.\n    apply fin_to_nat_to_fin.\n  Qed.\n\nEnd VMID0.\n\nProgram Definition W0 : Word := (finz.FinZ 0 _ _).\nSolve Obligations with lia.\n\nProgram Definition W1 : Word := (finz.FinZ 1 _ _).\nSolve Obligations with lia.\n\nProgram Definition W2 : Word := (finz.FinZ 2 _ _).\nSolve Obligations with lia.\n\nProgram Definition W6 : Word := (finz.FinZ 6 _ _).\nSolve Obligations with lia.\n\nProgram Definition I0 : Imm := (I W0 _).\nSolve Obligations with try lia;solve_finz.\n\nProgram Definition I1 : Imm := (I W1 _).\nSolve Obligations with try lia; solve_finz.\n\nProgram Definition I2 : Imm := (I W2 _).\nSolve Obligations with try lia; solve_finz.\n\nProgram Definition I6 : Imm := (I W6 _).\nSolve Obligations with try lia; solve_finz.\n\nProgram Definition R0 :reg_name := (R 0 _).\nSolve Obligations with lia.\n\nProgram Definition R1 :reg_name := (R 1 _).\nSolve Obligations with lia.\n\nProgram Definition R2 :reg_name := (R 2 _).\nSolve Obligations with lia.\n\nProgram Definition R3 :reg_name := (R 3 _).\nSolve Obligations with lia.\n\nProgram Definition R4 :reg_name := (R 4 _).\nSolve Obligations with lia.\n\nProgram Definition R5 :reg_name := (R 5 _).\nSolve Obligations with lia.\n\nProgram Definition R6 :reg_name := (R 6 _).\nSolve Obligations with lia.\n\nProgram Definition R7 :reg_name := (R 7 _).\nSolve Obligations with lia.\n\nProgram Definition R8 :reg_name := (R 8 _).\nSolve Obligations with lia.\n\nProgram Definition R9 :reg_name := (R 9 _).\nSolve Obligations with lia.\n\nProgram Definition R10 :reg_name := (R 10 _).\nSolve Obligations with lia.\n\nDefinition page_of_W0: list Word:=\n  map (λ _, W0) (seq 0 (Z.to_nat page_size)).\n\nDefinition pages_of_W0 (n:nat): list (list Word):=\n  map (λ _, page_of_W0) (seq 0 n).\n\nLemma length_page_of_W0 : length (page_of_W0) = (Z.to_nat page_size).\nProof.\n  rewrite /page_of_W0 map_length seq_length //.\nQed.\n\nLemma length_pages_of_W0 n : length (pages_of_W0 n) = n.\nProof.\n  rewrite /pages_of_W0 map_length seq_length //.\nQed.\n\nLemma length_pages_of_W0_forall n : forall ws, ws ∈  (pages_of_W0 n) -> length ws = (Z.to_nat page_size).\nProof.\n  intros.\n  apply elem_of_list_In in H.\n  rewrite /pages_of_W0 in H.\n  apply in_map_iff in H.\n  destruct H.\n  destruct H.\n  rewrite -H length_page_of_W0 //.\nQed.\n\nDefinition hvcf_to_tt hvcf:=\n  match hvcf with\n    | Donate => Some Donation\n    | Lend => Some Lending\n    | Share => Some Sharing\n    | _ => None\n  end.\n\n\nSection list_of_vmids.\nContext `{HypervisorConstants}.\n\n(* list of all valid vmids, heavily used in state_interp *)\nDefinition list_of_vmids  := vec_to_list (fun_to_vec (λ v: fin vm_count, v)).\n\nLemma length_list_of_vmids : length list_of_vmids = vm_count.\nProof.\n  rewrite /list_of_vmids.\n  apply vec_to_list_length.\nQed.\n\nLemma in_list_of_vmids v: In v list_of_vmids.\nProof.\n  apply elem_of_list_In.\n  apply elem_of_vlookup.\n  exists v.\n  apply lookup_fun_to_vec.\nQed.\n\nLemma NoDup_list_of_vmids : NoDup list_of_vmids.\nProof.\n  apply NoDup_alt.\n  rewrite /list_of_vmids.\n  intros ??? Hlk1 Hlk2.\n  rewrite <-vlookup_lookup' in Hlk1.\n  rewrite <-vlookup_lookup' in Hlk2.\n  destruct Hlk1 as [Hlt1 Hlk1], Hlk2 as [Hlt2 Hlk2].\n  rewrite lookup_fun_to_vec in Hlk1.\n  rewrite lookup_fun_to_vec in Hlk2.\n  rewrite -Hlk2 in Hlk1.\n  rewrite <-(fin_to_nat_to_fin i vm_count Hlt1).\n  rewrite <-(fin_to_nat_to_fin j vm_count Hlt2).\n  rewrite Hlk1 //.\nQed.\n\nLemma lookup_list_of_vmids i (Hlt: i < vm_count):\n  list_of_vmids !! i = Some (nat_to_fin Hlt).\nProof.\n  unfold list_of_vmids.\n  set (f := (nat_to_fin Hlt)).\n  assert ( i = fin_to_nat f ).\n  subst f.\n  rewrite fin_to_nat_to_fin //.\n  rewrite H0.\n  apply -> (@vlookup_lookup VMID).\n  apply lookup_fun_to_vec.\nQed.\n\nEnd list_of_vmids.\n\n(* an address is in the range of the page with PID p *)\nDefinition addr_in_page (a: Addr ) (p:PID):=\n  ((of_pid p) <=? a)%f ∧ (a <=? ((of_pid p) ^+ (page_size -1 )))%f.\n\n(* a sequence of addresses is in the range of the page with PID p *)\nDefinition seq_in_page (b :Addr) (l: nat) (p:PID) :=\n  l > 0 ∧\n  (* the starting address b is greater than the base addr of the page *)\n  ((of_pid p) <=? b)%Z\n  (* the ending address doesn't excess the boundary of address space *)\n  ∧ is_Some (b + (Z.of_nat l - 1))%f\n  (* the ending address is less than or equal to the last address of the page *)\n  ∧ ((b ^+ (Z.of_nat l -1))%f <=? ((of_pid p) ^+ (page_size-1))%f)%Z.\n\n(* we can always get the last address of a page *)\nLemma last_addr_in_bound (p:PID):\n  is_Some ((of_pid p) + (page_size -1)%Z)%f.\nProof.\n  destruct p.\n  destruct z.\n  simplify_eq /=.\n  assert (Hy : exists y, (y * page_size = word_size)%Z).\n  exists 2000%Z.\n  lia.\n  destruct Hy.\n  assert (Hlt: (z + page_size -1 < word_size)%Z).\n  {\n    apply Z.ltb_lt in finz_lt.\n    apply Z.leb_le in finz_nonneg.\n    assert (Hlt': (z  < word_size - page_size + 1 )%Z).\n    {\n      destruct (decide (z  < word_size - page_size + 1)%Z).\n      lia.\n      assert(H': ( (x -1 ) * page_size < z )%Z).\n      lia.\n      apply Z.eqb_eq in align.\n      apply Z.rem_divide in align;[|lia].\n      destruct align.\n      subst z.\n      rewrite -H in finz_lt.\n      apply Zmult_gt_0_lt_reg_r in finz_lt;[|lia].\n      apply Zmult_gt_0_lt_reg_r in H';[|lia].\n      lia.\n    }\n    lia.\n  }\n  unfold finz.incr.\n  simpl.\n  destruct (Z_lt_dec (z + (page_size - 1))%Z word_size).\n  destruct (Z_le_dec 0%Z (z + (page_size - 1))%Z).\n  eauto.\n  exfalso.\n  apply n.\n  lia.\n  exfalso.\n  apply n.\n  lia.\nQed.\n\n(* complementing lemmas for finz *)\nLemma finz_of_z_is_Some {fb} (z : Z):\n  (z >= 0)%Z ->\n  (z < fb)%Z ->\n  is_Some (finz.of_z (finz_bound := fb) z).\nProof.\n  intros.\n  unfold finz.of_z.\n  destruct (Z_lt_dec z fb).\n  2: lia.\n  destruct (Z_le_dec 0%Z z).\n  2: lia.\n  exists (finz.FinZ z (match Z.ltb_lt z fb with\n                              | conj _ H2 => H2\n                              end l) (match Z.leb_le 0 z with\n                                      | conj _ H2 => H2\n                                      end l0)).\n  done.\nQed.\n\nLemma incr_default_incr{fb} (f1 f2: finz.finz fb) z :\n  (f1 + z)%f = Some f2 -> (f1 ^+ z)%f = f2.\nProof.\n  intro.\n  solve_finz.\nQed.\n\nLemma finz_incr_z_plus{b} (f1 f2 : (finz.finz b)) z :\n  (f1 + z)%f = Some f2 <-> (f1 + z)%Z = (finz.to_z f2).\nProof.\n  split;solve_finz.\nQed.\n\nLemma finz_incr_z_plus'{b} (f1 : (finz.finz b)) z :\n  (f1 + z)%f = None <-> (b <= (f1 + z))%Z ∨ ((f1 +z) < 0)%Z .\nProof.\n  split; solve_finz.\nQed.\n\nLemma finz_plus_Z_lt{b} (f: (finz.finz b)) z1 z2:\n  (is_Some (f + z1)%f) -> (is_Some (f + z2)%f) ->\n  ((f ^+ z1)%f < (f ^+ z2)%f)%Z -> (z1 < z2)%Z.\nProof.\n  intros H1 H2 Hlt.\n  destruct H1 as [f1 H1].\n  destruct H2 as [f2 H2].\n  rewrite (incr_default_incr f f1 z1) in Hlt;eauto.\n  rewrite (incr_default_incr f f2 z2) in Hlt;eauto.\n  solve_finz.\nQed.\n\nLemma finz_plus_Z_le{b} (f: (finz.finz b)) z1 z2:\n  (is_Some (f + z1)%f) ->\n  (is_Some (f + z2)%f) ->\n  ((f ^+ z1)%f <= (f ^+ z2)%f)%Z ->\n  (z1 <= z2)%Z.\nProof.\n  intros H1 H2 Hlt.\n  destruct H1 as [f1 H1].\n  destruct H2 as [f2 H2].\n  rewrite (incr_default_incr f f1 z1) in Hlt;eauto.\n  rewrite (incr_default_incr f f2 z2) in Hlt;eauto.\n  solve_finz.\nQed.\n\n(*  relation between to_pid_aligned and addr_in_page *)\nLemma to_pid_aligned_in_page (a:Addr) (p:PID) :\n  addr_in_page a p -> (to_pid_aligned a ) = p.\nProof.\n  intro.\n  unfold to_pid_aligned.\n  unfold addr_in_page in H.\n  destruct H.\n  pose proof (last_addr_in_bound p).\n  destruct H1.\n  rewrite (incr_default_incr (of_pid p) x (page_size -1)%Z) in H0;eauto.\n  destruct p.\n  destruct z.\n  assert (Heq : z = (page_size * (a / page_size))%Z).\n  {\n    destruct a.\n    simplify_eq /=.\n    unfold finz.leb in H.\n    simpl in H.\n    unfold finz.ltb in H0.\n    simpl in H0.\n    apply Is_true_eq_true in H, H0.\n    apply Z.leb_le in H.\n    apply Z.leb_le in H0.\n    apply finz_incr_z_plus in H1.\n    simpl in H1.\n    rewrite -H1 in H0.\n    simpl in H0.\n    apply Z.eqb_eq in align.\n    apply Z.rem_divide in align;[|lia].\n    destruct align.\n    subst z.\n    apply (fast_Zmult_comm page_size x0) in H.\n    apply Z.quot_le_lower_bound in H;[|lia].\n    assert (H0': (z0 < page_size* (x0+1) )%Z).\n    lia.\n    apply Z.quot_lt_upper_bound in H0';[|lia|lia].\n    assert (Heq: (z0 `quot` page_size = x0)%Z).\n    lia.\n    rewrite Z.quot_div_nonneg in Heq;[lia|lia| ].\n    solve_finz.\n  }\n  subst z.\n  remember (machine.to_pid_aligned_obligation_3 a) as Ha'.\n  simpl in Ha'.\n  assert (Heqiv : Ha' = align).\n  apply eq_proofs_unicity; decide equality; decide equality.\n  rewrite Heqiv.\n  remember (machine.to_pid_aligned_obligation_1 a) as Ha''.\n  simpl in  Ha''.\n  remember (machine.to_pid_aligned_obligation_2 a) as Ha'''.\n  simpl in  Ha'''.\n  assert (Heqiv' : Ha'' = finz_lt).\n  apply eq_proofs_unicity; decide equality; decide equality.\n  rewrite Heqiv'.\n  assert (Heqiv'' : Ha''' = finz_nonneg).\n  apply eq_proofs_unicity; decide equality; decide equality.\n  rewrite Heqiv'' // .\nQed.\n\nLemma in_page_to_pid_aligned a: addr_in_page a (to_pid_aligned a).\nProof.\n  unfold addr_in_page, to_pid_aligned.\n  split.\n  - simpl.\n    unfold finz.leb.\n    simpl.\n    unfold Is_true.\n    case_match;[done|].\n    apply Z.leb_nle in Heqb.\n    apply Heqb.\n    apply Z.mul_div_le.\n    lia.\n  - unfold finz.leb.\n    simpl.\n    pose proof (last_addr_in_bound (to_pid_aligned a)) as Hplus.\n    destruct Hplus as [? Hplus].\n    unfold finz.incr_default.\n    unfold to_pid_aligned in Hplus.\n    rewrite Hplus.\n    simpl in Hplus.\n    destruct x.\n    simpl.\n    assert (1000 * a `div` 1000 + (1000 - 1) = z)%Z as <-.\n    { solve_finz. }\n    pose proof (Z.div_mod a 1000).\n    rewrite ->H at 1.\n    2: {lia. }\n    unfold Is_true.\n    case_match;[done|].\n    apply Z.leb_nle in Heqb.\n    apply Heqb.\n    apply Zplus_le_compat_l.\n    rewrite -Z.rem_mod_nonneg;[lia|lia|].\n    assert (a `rem` 1000 < 1000)%Z.\n    {\n      pose proof (Z.rem_bound_pos_pos a 1000).\n      apply H0;lia.\n    }\n    lia.\nQed.\n\nLemma to_pid_aligned_eq (p:PID) : to_pid_aligned p = p.\nProof.\n  unfold to_pid_aligned.\n  destruct p.\n  apply of_pid_eq.\n  simpl.\n  destruct z.\n  apply finz_to_z_eq.\n  simplify_eq /=.\n  unfold finz.leb in finz_lt.\n  unfold finz.ltb in finz_nonneg.\n  apply Z.ltb_lt in finz_lt.\n  apply Z.leb_le in finz_nonneg.\n  apply Z.eqb_eq in align.\n  apply Z.rem_divide in align;[|lia].\n  destruct align.\n  subst z.\n  rewrite Z_div_mult;[lia|].\n  apply (fast_Zmult_comm page_size x).\n  lia.\nQed.\n\nLemma finz_plus_assoc {fb} (a : finz fb) (n m : Z):\n  (0 <= n)%Z ->\n  (0 <= m)%Z ->\n  ((a ^+ n) ^+ m)%f = (a ^+ (n + m)%Z)%f.\nProof. solve_finz. Qed.\n\n(* complementing lemmas for finz.seq *)\nLemma finz_seq_notin2{b} (f f' : finz.finz b) n :\n  (f' ^+ ((Z.of_nat n)-1) < f)%f -> f ∉ finz.seq f' n.\nProof.\n  revert f f'. induction n; cbn.\n  { intros. inversion 1. }\n  { intros. apply not_elem_of_cons. split. solve_finz. eapply IHn. solve_finz. }\nQed.\n\nLemma finz_seq_in1{b} (f f' : finz.finz b) n :\n  f ∈ finz.seq f' n ->  (f' <= f )%f.\nProof.\n  revert f f'. induction n; cbn.\n  { intros. inversion H. }\n  { intros. apply  elem_of_cons in H.\n    destruct H.\n    solve_finz.\n    eapply IHn in H. solve_finz. }\nQed.\n\nLemma finz_seq_in2{b} (f f' : finz.finz b) n :\n  f ∈ finz.seq f' n ->  (f <= f' ^+ ((Z.of_nat n)-1))%f.\nProof.\n  revert f f'. induction n; cbn.\n  { intros. inversion H. }\n  { intros. apply  elem_of_cons in H.\n    destruct H.\n    solve_finz.\n    eapply IHn in H. solve_finz. }\nQed.\n\n(* if the sequcence is included in a page,\nthen every address in the sequcence is in the page *)\nDefinition seq_in_page_forall1 (b: Addr) (l:nat) (p:PID) :\n  seq_in_page b l p -> (∀ a, a ∈ (finz.seq b l) -> addr_in_page a p).\nProof.\n  intros.\n  (* apply Forall_forall. *)\n  unfold addr_in_page.\n  destruct H.\n  split.\n  - unfold finz.leb.\n    unfold Is_true.\n    destruct (decide (b <= a)%f).\n    unfold Is_true in H.\n    assert (Hap: ((of_pid p) <= a)%Z).\n    destruct ((((of_pid p) <=? b))%Z) eqn:Heqn.\n    apply Z.leb_le in Heqn.\n    solve_finz.\n    destruct H1.\n    inversion H1.\n    apply Z.leb_le in Hap.\n    rewrite Hap //=.\n    exfalso.\n    assert (Hlt: (a < b )%f).\n    solve_finz.\n    apply (finz_seq_notin _ _ l)in Hlt.\n    contradiction.\n  - destruct l.\n    inversion H.\n    destruct H1.\n    destruct H2.\n    destruct H2.\n    rewrite (incr_default_incr b x _ ) in H3;eauto.\n    pose proof (last_addr_in_bound p).\n    destruct H4.\n    rewrite (incr_default_incr (of_pid p) x0 _ ) in H3;eauto.\n    rewrite (incr_default_incr (of_pid p) x0 _ );eauto.\n    apply  finz_incr_z_plus in H4.\n    apply finz_seq_in2 in H0.\n    apply  finz_incr_z_plus in H2.\n    assert (H1': (b + (Z.of_nat l -1))%Z = (x-1)%Z ). by lia.\n    assert(Hl : ((Z.of_nat (S l) - 1)%Z = (Z.of_nat l))%Z).  by lia.\n    rewrite Hl  in H0 H1.\n    rewrite -H4 in H3.\n    rewrite -H2 in H3.\n    unfold finz.leb.\n    rewrite -H4.\n    assert (H0': (a <= b + (Z.of_nat l))%Z).\n    solve_finz.\n    rewrite -H2 in H1'.\n    destruct (decide (a <= (of_pid p) + (page_size - 1)))%Z.\n    apply Z.leb_le in l0.\n    solve_finz.\n    exfalso.\n    destruct ((b + Z.of_nat l <=? (of_pid p) + (page_size - 1))%Z) eqn:Heqn.\n    apply Z.leb_le in Heqn.\n    lia.\n    rewrite Hl in H3.\n    rewrite Heqn in H3.\n    contradiction.\nQed.\n\n\nLemma finz_seq_lookup'{b} (f0 fi:(finz.finz b)) (i n : nat) :\n  is_Some(f0 + (Z.of_nat n - 1))%f ->\n  finz.seq f0 n !! i = Some fi ->\n  i < n ∧ (f0 + (Z.of_nat i))%f = Some fi.\nProof using.\n  revert i fi f0. induction n.\n  { intros. done. }\n  { intros i fi f0 Hsafe HSome.\n    destruct i as [|i].\n    { split. solve_finz. simpl in HSome. inversion HSome. solve_finz. }\n    { simpl in HSome.\n      apply IHn in HSome.\n      destruct HSome.\n      split.\n      lia. rewrite -H0. solve_finz.\n      assert (Hlt: i < n).\n      {\n        apply lookup_lt_Some in HSome.\n        rewrite finz_seq_length in HSome.\n        done.\n      }\n      solve_finz.\n    }\n    }\nQed.\n\nLemma finz_seq_cons {b} (f: finz.finz b) (l:nat) :\n  (l > 0) ->\n  (finz.seq f l) = f :: (finz.seq (f ^+ 1)%f (l-1)).\nProof.\n  intro.\n  destruct l eqn:Hl;[lia|].\n  simpl.\n  repeat f_equal.\n  lia.\nQed.\n\nDefinition seq_in_page_forall2 (b: Addr) (l:nat) (p:PID) :\n  seq_in_page b l p -> (∀ a, a ∈ (finz.seq b l) -> to_pid_aligned a = p).\nProof.\n  intros.\n  apply to_pid_aligned_in_page.\n  by apply (seq_in_page_forall1 b l p H a).\nQed.\n\n\n(* Definition seq_in_page_forall2 (b: Addr) (l:nat) (p:PID) : *)\n(*    l > 0 -> (∀ a, a ∈ (finz.seq b l) -> addr_in_page a p) -> seq_in_page b l p. *)\n(* Proof. *)\n(*   intros Hl Hforall. *)\n(*   rewrite /seq_in_page. *)\n(*   assert (b ∈ finz.seq b l) as Hb. *)\n(*   rewrite finz_seq_cons;auto. *)\n(*   set_solver. *)\n(*   apply (Hforall b) in Hb. *)\n(*   rewrite /addr_in_page in Hb. *)\n(*   destruct Hb as [Hbge Hble]. *)\n(*   split. *)\n(*   solve_finz. *)\n(*   assert ((b ^+ (Z.of_nat l -1 ))%f ∈ finz.seq b l) as Hbl. *)\n(*   admit. *)\n(*   pose proof Hbl as Hbl'. *)\n(*   apply (Hforall (b ^+ (Z.of_nat l -1 ))%f) in Hbl. *)\n(*   rewrite /addr_in_page in Hbl. *)\n(*   destruct Hbl. *)\n(*   split;[|solve_finz]. *)\n(*   pose proof (last_addr_in_bound p). *)\n(*   (* don't know how to prove it ... seems the def of addr_in_page need to be changed. *) *)\n(*   Admitted. *)\n\n(* fin_to_nat vec_to_list of_imm of_pid finz.to_z NonPropType.frame Is_true NonPropType.callee *)\nLemma seq_in_page_append1 (b:Word) (l l' : nat) p:\n  (0 < l) -> (l < l') -> seq_in_page b l' p -> seq_in_page b l p.\nProof.\n  intros Hlpos Hlt Hseq.\n  rewrite /seq_in_page.\n  split;[done|].\n  rewrite /seq_in_page in Hseq.\n  destruct Hseq as (Hl'pos & Hple & Hbl'isSome & Hbl'le).\n  split; auto.\n  split.\n  solve_finz.\n  assert (Hllt: ((Z.of_nat l - 1) < (Z.of_nat l' -1))%Z).\n  solve_finz.\n  assert (((b ^+ (Z.of_nat l - 1))%f < (b ^+ (Z.of_nat l' - 1)))%f).\n  solve_finz.\n  rewrite /Is_true in Hbl'le.\n  case_match.\n  apply Z.leb_le in Heqb0.\n  rewrite /Is_true.\n  case_match.\n  done.\n  solve_finz.\n  done.\nQed.\n\n\nLemma seq_in_page_append2 (b :Word) (l o : nat) p:\n  o<l ->\n  is_Some (b + (Z.of_nat o))%f->\n  seq_in_page b l p ->\n  seq_in_page (b ^+ (Z.of_nat o))%f (l - o) p.\nProof.\n  intros Holt Hb'in Hseq.\n  rewrite /seq_in_page.\n  rewrite /seq_in_page in Hseq.\n  destruct Hseq as (Hlpos & Hple & HblisSome & Hblle).\n  split.\n  lia.\n  split.\n  rewrite /Is_true in Hple.\n  case_match;[|done].\n  apply Z.leb_le in Heqb0.\n  rewrite /Is_true.\n  case_match;[done|].\n  solve_finz.\n  split.\n  solve_finz.\n  rewrite /Is_true in Hblle.\n  case_match;[|done].\n  apply Z.leb_le in Heqb0.\n  rewrite /Is_true.\n  case_match;[done|].\n  solve_finz.\nQed.\n\n(* an alternative definition, not sure which is better *)\n(* Definition addr_of_page' (p: PID) := map (λ off, ((of_pid p) + off)%f) (seqZ 0%Z page_size). *)\n\nLemma finz_seq_lookup0{b} n (f : finz.finz b) x :\n   is_Some(f + 1)%f ->\n   finz.seq f n !! x = Some f -> x=0.\nProof.\n  revert f. destruct n; cbn.\n  { intros. inversion H0. }\n  { intros.\n    destruct (decide (x=0)).\n    done.\n    rewrite lookup_cons_ne_0 in H0;eauto.\n    apply elem_of_list_lookup_2 in H0.\n    pose proof (finz_seq_notin f (f ^+ 1)%f n).\n    assert ( (f < f ^+ 1)%f) as Hlt.\n    solve_finz.\n    apply H1 in Hlt.\n    done.\n  }\nQed.\n\n\nLemma finz_seq_NoDup'{b} (f : finz.finz b) (n : nat) :\n  is_Some (f + (Z.of_nat (n-1)))%f →\n  NoDup (finz.seq f n).\nProof using.\n  revert f. induction n; intros f Hfn.\n  { apply NoDup_nil_2. }\n  { cbn.\n    destruct n; intros;simpl.\n    { apply NoDup_singleton. }\n    { apply NoDup_cons_2.\n      apply not_elem_of_cons.\n      split.\n      solve_finz.\n      apply finz_seq_notin.\n      solve_finz.\n      eapply IHn.\n      solve_finz. } }\nQed.\n\nLemma finz_seq_in_inv{b} (f f' : finz.finz b) n:\n    (f' <= f )%f -> (f <= f' ^+ (Z.of_nat n))%f ->\n    f ∈ finz.seq f' (n+1).\n Proof.\n   revert f f'. induction n; cbn.\n   { intros.\n     assert (f = f')%f as ->.\n     {\n       solve_finz.\n     }\n     set_solver +.\n   }\n   {\n     intros.\n     destruct (decide (f = f')).\n     {\n       rewrite e.\n       apply elem_of_list_here.\n     }\n     apply elem_of_list_further.\n     apply IHn.\n     solve_finz.\n     solve_finz.\n   }\n Qed.\n\n\n Definition addr_of_page (p: PID) := (finz.seq (of_pid p) (Z.to_nat page_size)).\n\n Lemma elem_of_addr_of_page_tpa (a:Addr) : a ∈ (addr_of_page (tpa a)).\n Proof.\n   rewrite /addr_of_page.\n   pose proof (in_page_to_pid_aligned a) as [H1 H2].\n   assert ((Z.to_nat 1000) = (Z.to_nat 999) + 1) as ->.\n   { done. }\n   apply finz_seq_in_inv.\n   {\n     rewrite /Is_true in H1.\n     case_match;last done.\n     solve_finz.\n   }\n   {\n     rewrite /Is_true in H2.\n     case_match;last done.\n     solve_finz.\n   }\n Qed.\n\nLemma elem_of_addr_of_page_of_pid (a : Addr) : of_pid (tpa a) ∈ addr_of_page (tpa a).\nProof.\n  unfold addr_of_page.\n  unfold tpa.\n  rewrite finz_seq_cons; first lia.\n  apply elem_of_list_here.            \nQed.\n\nLemma elem_of_addr_of_page_iff (a:Addr) (p : PID) : a ∈ (addr_of_page p) <-> p = (tpa a).\nProof.\n  split.\n  {\n     rewrite /addr_of_page.\n     intro Hin.\n     symmetry.\n     apply to_pid_aligned_in_page.\n     rewrite /addr_in_page.\n     split.\n     apply finz_seq_in1 in Hin.\n     rewrite Is_true_true.\n     solve_finz.\n     apply finz_seq_in2 in Hin.\n     rewrite Is_true_true.\n     solve_finz.\n  }\n  intros ->.\n  apply elem_of_addr_of_page_tpa.\nQed.\n\nLemma addr_of_page_not_empty_exists (p : PID) : ∃a, a ∈ addr_of_page p.\nProof.\n  exists (of_pid p).\n  apply elem_of_addr_of_page_iff.\n  rewrite to_pid_aligned_eq //.\nQed.\n\nLemma addr_of_page_not_empty_set (p : PID) : list_to_set (addr_of_page p) ≠ (∅: gset _) .\nProof.\n  pose proof (addr_of_page_not_empty_exists p) as H.\n  destruct H as [a H].\n  intro Heq.\n  rewrite -(elem_of_list_to_set (C:= gset Addr) a (addr_of_page p)) in H.\n  rewrite Heq in H.\n  set_solver + H.\nQed.\n\nLemma addr_of_page_NoDup (p:PID) : NoDup (addr_of_page p).\nProof.\n  rewrite /addr_of_page.\n  apply finz_seq_NoDup'.\n  apply last_addr_in_bound.\nQed.\n\nLemma addr_of_page_disj (p1 p2 :PID) :\n  p1 ≠ p2 ->\n  ((list_to_set (addr_of_page p1)) : gset Addr) ## list_to_set (addr_of_page p2).\nProof.\n  intro Hneq.\n  apply elem_of_disjoint.\n  intros a.\n  rewrite !elem_of_list_to_set.\n  rewrite !elem_of_addr_of_page_iff.\n  intros -> Hin2.\n  done.\nQed.\n\nLemma addr_of_page_subseteq (p : PID) (n:nat) :\n  ((Z.of_nat n) <= page_size)%Z ->\n  list_to_set (C:=gset _) (finz.seq p n) ⊆ list_to_set (addr_of_page p).\nProof.\n  destruct n eqn:Heqn.\n  done.\n  intro Hle.\n  intros a Hin.\n  rewrite elem_of_list_to_set.\n  rewrite elem_of_list_to_set in Hin.\n  pose proof Hin.\n  apply finz_seq_in1 in Hin.\n  apply finz_seq_in2 in H.\n  apply elem_of_addr_of_page_iff.\n  symmetry.\n  apply to_pid_aligned_in_page.\n  rewrite /addr_in_page.\n  split.\n  apply Is_true_eq_left.\n  solve_finz.\n  apply Is_true_eq_left.\n  pose proof (last_addr_in_bound p).\n  solve_finz.\nQed.\n\nLemma pid_lt_lt (p1 p2:PID):\n  ((of_pid p1) < (of_pid p2))%f -> (p1 ^+ (page_size - 1) < p2)%f.\nProof.\n  intro.\n  pose proof (last_addr_in_bound p1).\n  destruct H0.\n  rewrite (incr_default_incr (of_pid p1) x);eauto.\n  destruct p1,p2.\n  destruct z,z0.\n  simpl in *.\n  apply Z.eqb_eq in align, align0.\n  apply Z.rem_divide in align,align0;try lia.\n  destruct align, align0.\n  assert ( z < z0 )%Z.\n  solve_finz.\n  subst z.\n  subst z0.\n  destruct x.\n  simpl in H0.\n  assert (z = x0 * 1000 + 1000 -1)%Z.\n  solve_finz.\n  subst z.\n  solve_finz.\nQed.\n\nLemma finz_seq_nonempty_length {b} (x f :finz.finz b) (l:nat):\n  x ∈ finz.seq f l-> l >0.\nProof.\n  intros.\n  destruct l.\n  inversion H.\n  lia.\nQed.\n\nLemma addr_in_notin (p1 p2 : PID) (x: Addr) (l1 : nat) :\n  ((Z.of_nat l1) < page_size)%Z ->\n  p1 ≠ p2 ->\n  x ∈ finz.seq (of_pid p1) l1 ->\n  ∀ l2 , ((Z.of_nat l2) < page_size)%Z -> x ∉ finz.seq (of_pid p2) l2.\nProof.\n  intros.\n  pose proof H1.\n  apply finz_seq_nonempty_length in H3.\n  destruct (decide ((of_pid p1) <= (of_pid p2))%f).\n  - assert ( (of_pid p1) ≠ (of_pid p2))%f.\n    { intro. apply H0. by apply of_pid_eq. }\n    assert ( (of_pid p1) < (of_pid p2))%f. solve_finz.\n    apply  finz_seq_notin.\n    apply pid_lt_lt in H5.\n    apply finz_seq_in2 in H1.\n    solve_finz.\n  - destruct l2.\n    apply not_elem_of_nil.\n    assert ( (of_pid p2) < (of_pid p1))%f. solve_finz.\n    apply  finz_seq_notin2.\n    apply finz_seq_in1 in H1.\n    apply pid_lt_lt in H4.\n    solve_finz.\nQed.\n\nLemma finz_seq_zip_page (p: PID) (ws: list Word):\n  (length ws) <= (Z.to_nat page_size) ->\n  ((zip (finz.seq (of_pid p) (length ws)) ws) = (zip (finz.seq (of_pid p) (Z.to_nat page_size)) ws)).\nProof.\n  intro Hlen.\n  rewrite <-(zip_fst_snd (zip (finz.seq _ (Z.to_nat page_size)) ws)).\n  rewrite !snd_zip; auto.\n  f_equal.\n  generalize dependent (of_pid p).\n  induction ws; first done.\n  cbn.\n  destruct (Z.to_nat page_size) eqn:Heqn; first done.\n  cbn.\n  intros f.\n  f_equal.\n  assert (Hn : n = ((Z.to_nat page_size) - 1)).\n  lia.\n  subst n.\n  rewrite (@zip_length_le _ _ ws\n                          (finz.seq (f ^+ 1)%f ((Z.to_nat page_size) -1))\n                          (finz.seq (f ^+ 1)%f (Z.to_nat page_size))\n                          [(f ^+ page_size)%f]).\n  simpl in Hlen.\n  rewrite finz_seq_length.\n  lia.\n  rewrite (finz_seq_decomposition (Z.to_nat page_size) _ ((Z.to_nat page_size) -1)).\n  lia.\n  f_equal.\n  simpl.\n  f_equal.\n  rewrite Unnamed_thm12.\n  lia.\n  lia.\n  rewrite Z.add_comm.\n  assert (H999_1 : Z.add (page_size - 1)%Z 1%Z = 1000%Z).\n  reflexivity.\n  rewrite H999_1.\n  reflexivity.\n  rewrite IHws.\n  simpl in Hlen.\n  lia.\n  rewrite -Heqn.\n  reflexivity.\nQed.\n\n", "meta": {"author": "logsem", "repo": "VMSL", "sha": "0a9b005b599a770e40c07abc9aa10a4ee9759315", "save_path": "github-repos/coq/logsem-VMSL", "path": "github-repos/coq/logsem-VMSL/VMSL-0a9b005b599a770e40c07abc9aa10a4ee9759315/theories/machine_extra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.25388618682561714}}
{"text": "Set Warnings \"-notation-overridden\".\n\nRequire Import LinearScan.Lib.\nRequire Import LinearScan.UsePos.\nRequire Import LinearScan.Range.\nRequire Import LinearScan.Interval.\nRequire Import LinearScan.Blocks.\nRequire Import LinearScan.LiveSets.\nRequire Import LinearScan.Morph.\nRequire Import LinearScan.ScanState.\nRequire Import LinearScan.Loops.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nGeneralizable All Variables.\n\nSection Build.\n\nVariable maxReg : nat.          (* max number of registers *)\nDefinition PhysReg := 'I_maxReg.\n\nVariables blockType1 blockType2 opType1 opType2 : Set.\nVariables mType : Type -> Type.\nContext `{mDict : Monad mType}.\n\nVariable binfo : BlockInfo blockType1 blockType2 opType1 opType2.\nVariable oinfo : OpInfo maxReg opType1 opType2.\n\nDefinition BuildState (b : nat) := IntMap (SortedRanges b.*2.+1).\n\nDefinition newBuildState {n} : BuildState n := emptyIntMap.\n\nDefinition PendingRanges b e := NonEmpty (BoundedRange b.*2.+1 e.*2.+1).\n\nDefinition emptyPendingRanges (b e : nat) (H : b < e) (liveOuts : IntSet) :\n  IntMap (PendingRanges b e).\nProof.\n  have Hsz : b.*2.+1 < e.*2.+1 by undoubled.\n  have empty  := emptyBoundedRange Hsz.\n  have f xs vid := IntMap_insert (vid + maxReg) [::: empty] xs.\n  exact (IntSet_foldl f emptyIntMap liveOuts).\nDefined.\n\n(* We sort ascending in order of range end, with smaller ranges occurring\n   after larger ones. *)\nDefinition BoundedRange_leq {b e} (x y : BoundedRange b.*2.+1 e.*2.+1) : bool.\nProof.\n  move: x => [[x _] _].\n  move: y => [[y _] _].\n  case: (rend x == rend y).\n    exact: (rbeg x <= rbeg y).\n  exact: (rend x <= rend y).\nDefined.\n\nProgram Instance BoundedRange_leq_trans {b e} :\n  Transitive (@BoundedRange_leq b e).\nObligation 1.\n  rewrite /BoundedRange_leq /= in H H0 *.\n  destruct x; destruct y; destruct z.\n  destruct x; destruct x1; destruct i.\n  destruct x0; destruct i0.\n  case E1: (rend x == rend x0) in H H0 *;\n  case E2: (rend x0 == rend x1) in H H0 *;\n  case E3: (rend x1 == rend x) in H H0 *;\n  case E4: (rend x == rend x1) in H H0 *;\n  move/eqP in E1;\n  move/eqP in E2;\n  move/eqP in E3;\n  move/eqP in E4;\n  by ordered.\nQed.\n\nLemma BoundedRange_leq_antisym {b e} : forall x y,\n  ~~ (@BoundedRange_leq b e) y x -> (@BoundedRange_leq b e) x y.\nProof.\n  move=> x y Hneg.\n  rewrite /BoundedRange_leq /= in Hneg *.\n  destruct x; destruct y.\n  destruct x; destruct x0.\n  case E1: (rend x == rend x0) in Hneg *;\n  case E2: (rend x0 == rend x) in Hneg *;\n  move/eqP in E1;\n  move/eqP in E2;\n  by ordered.\nQed.\n\nDefinition compilePendingRanges {b e} (Hlt : b < e)\n  (ranges : seq (BoundedRange b.*2.+1 e.*2.+1))\n  (H : StronglySorted BoundedRange_leq ranges) :\n  { rs : SortedRanges b.*2.+1\n  | last b.*2.+1 [seq rend r.1 | r <- rs.1] <= e.*2.+1\n  & if ranges is _ :: _\n    then if rs.1 is r' :: _\n         then { H : 0 < size ranges\n              | rend (safe_hd ranges H).1.1 <= rend r'.1 }\n         else False\n    else True}.\nProof.\n  elim: ranges => [|r1 rs IHrs] in H *.\n    apply: exist2 _ _ (exist2 _ _ [::] _ _) _ _.\n    - by constructor.\n    - by [].\n    - by undoubled.\n    - intros; exact: I.\n\n  destruct rs as [|r2 rs2] eqn:R2.\n    apply: exist2 _ _ (exist2 _ _ [:: r1.1] _ _) _ _.\n    - by constructor; constructor.\n    - clear -r1.\n      case: r1 => [H1 H2] /=.\n      by ordered.\n    - clear -r1.\n      case: r1 => [H1 H2] /=.\n      by ordered.\n    - by exists (ltn0Sn _).\n\n  have Hconn : rend r1.1.1 <= rend r2.1.1.\n    inv H; inv H2; inv H3.\n    rewrite /BoundedRange_leq /= in H2.\n    destruct r1; destruct x;\n    destruct r2; destruct x0; simpl.\n    case E: (rend x == rend x0) => // in H2 *.\n    by move/eqP in E; rewrite {}E.\n\n  apply StronglySorted_inv in H.\n  move: H => [Hs Hf].\n  specialize (IHrs Hs).\n  case: IHrs => [[[|r2' rs2'] H2a H2b] /= H3 H4] in Hs *;\n    first by [].\n\n  (* Owing to the way the list is sorted, this is the only check we need for\n     intersection and adjacency. *)\n  case E: (range_ltn r1.1 r2').\n    rewrite /=.\n    apply: exist2 _ _ (exist2 _ _ [:: r1.1, r2' & rs2'] _ _) _ _.\n    - constructor.\n        exact: H2a.\n      constructor.\n        exact: E.\n      inv H2a.\n      exact/(Forall_ordered E).\n    - clear -r1.\n      case: r1 => [H1 H2] /=.\n      by ordered.\n    - by [].\n    - by exists (ltn0Sn _).\n\n  move: r1 => [[rd1 r1] Hr1] /= in Hs Hf Hconn E *.\n  move: r2' => [rd2' r2'] /= in Hs Hf E R2 H2a H2b H3 H4 *.\n\n  (* Otherwise, if the ranges are directly adjacent, or intersect, coalesce\n     them into a single range. *)\n  apply: exist2 _ _\n    (exist2 _ _ [:: packRange (Range_merge r1 r2') & rs2'] _ _) _ _.\n\n  (* Prove that sorting over range_ltn has been established. *)\n  rewrite /range_ltn /= in E *.\n  constructor.\n    by inv H2a.\n  induction rs2' as [|r3 rs3 IHrs3].\n    by constructor.\n  rewrite /=.\n  have Hmax: maxn (rend rd1) (rend rd2') < rbeg r3.1.\n    inv Hf.\n    clear -Hs H2a H4 Hconn.\n    inv H2a; inv H4; inv H1; inv H2.\n    rewrite gtn_max.\n    rewrite /range_ltn /= in H3.\n    by ordered.\n  constructor=> //.\n  apply IHrs3.\n  constructor=> //.\n    by inv H2a; inv H1.\n  by inv H2a; inv H2.\n\n  rewrite /= in H3 *.\n  apply: (last_leq H3).\n  rewrite gtn_max in Hmax.\n  apply/ltnW.\n  move: (Range_bounded r3.2).\n  by ordered.\n\n  (* Return a witness to an ordering property [rend rd1 <= maxn (rend rd1)\n     (rend rd2')], which makes induction much easier. *)\n  rewrite /=.\n  rewrite leq_min.\n  by ordered.\n\n  rewrite /=.\n  intros.\n  apply: (last_leq H3).\n  rewrite geq_max.\n  inv H4.\n  by ordered.\n\n  rewrite /=.\n  exists (ltn0Sn _).\n  rewrite leq_max.\n  by apply/orP; left.\nDefined.\n\nProgram Fixpoint rangesToBoundedRanges {b e} (y : RangeSig) (ys : seq RangeSig)\n  (H1 : StronglySorted range_ltn (y :: ys)) (H2 : b.*2.+1 <= rbeg y.1)\n  (Hbound : last (rend y.1) [seq rend r.1 | r <- ys] <= e.*2.+1) :\n  NonEmpty (BoundedRange b.*2.+1 e.*2.+1) :=\n  match ys with\n  | nil => NE_Sing y\n  | cons z zs =>\n      NE_Cons y (@rangesToBoundedRanges b e z zs _ _ _)\n  end.\nNext Obligation.\n  rewrite /= in Hbound.\n  by ordered.\nQed.\nNext Obligation.\n  apply/andP; split=> //.\n  apply StronglySorted_impl_cons in H1;\n    last exact: range_ltn_trans.\n  move: H1 Hbound.\n  rewrite [(z; H)]lock.\n  rewrite /range_ltn map_comp (last_map rend) /= last_map -lock /=.\n  move: (Range_bounded (last (z; H) zs).2).\n  case: zs => //= [|w ws].\n  by ordered.\n  move=> H3 H4 H5.\n  apply/(leq_trans _ H5).\n  apply/(leq_trans _ H3).\n  apply/ltnW.\n  by ordered.\nQed.\nNext Obligation.\n  by inv H1.\nQed.\nNext Obligation.\n  inv H1; inv H6.\n  rewrite /range_ltn /= in H4.\n  move: (Range_bounded H0).\n  by ordered.\nQed.\n\nDefinition compressPendingRanges `(ranges : PendingRanges b e) (H : b < e) :\n  PendingRanges b e.\nProof.\n  case: ranges => [r|r rs].\n    exact: [::: r].\n  pose Hsort := sortBy_sorted [::: r & rs] BoundedRange_leq_antisym.\n  specialize (Hsort BoundedRange_leq_trans).\n  rewrite NE_to_list_from_list /= in Hsort.\n  move: (compilePendingRanges H Hsort) => [[srs1 H1 H2] Hbound /= H3].\n  clear -srs1 H1 H2 H3 Hbound.\n  case E: (insert BoundedRange_leq r (sortBy BoundedRange_leq rs))\n    => [|x xs] in H3 *.\n    move: E.\n    set xs := insert _ _ _.\n    move=> E.\n    have E1 : size xs = size [::] by rewrite E.\n    by rewrite insert_size /= in E1.\n  destruct srs1 as [|y ys]; simpl in *.\n    contradiction H3.\n  exact: (rangesToBoundedRanges H1 H2 Hbound).\nDefined.\n\nDefinition mergeIntoSortedRanges `(H : b < e)\n  (pmap : IntMap (PendingRanges b e)) (rmap : IntMap (SortedRanges e.*2.+1)) :\n  IntMap (SortedRanges b.*2.+1).\nProof.\n  apply: (IntMap_mergeWithKey _ _ _ pmap rmap).\n  - (* The combining function, when entries are present in both maps. *)\n    move=> _ brs srs2.\n    pose Hsort := sortBy_sorted brs BoundedRange_leq_antisym.\n    specialize (Hsort BoundedRange_leq_trans).\n    move: (compilePendingRanges H Hsort) => [[srs1 ? ?] Hbound _].\n    exact: Some (SortedRanges_cat srs2 Hbound).\n\n  - (* When no rmap entry are present. *)\n    apply: IntMap_map _.\n    move=> brs.\n    pose Hsort := sortBy_sorted brs BoundedRange_leq_antisym.\n    specialize (Hsort BoundedRange_leq_trans).\n    move: (compilePendingRanges H Hsort) => [srs1 _ _].\n    exact: srs1.\n\n  - (* When no pmap entry is present. *)\n    move=> sr.\n    have H': b.*2.+1 <= e.*2.+1 by undoubled.\n    exact: IntMap_map (transportSortedRanges H') sr.\nDefined.\n\nDefinition upos_before_rend `(r : Range rd) (upos : UsePos) :=\n  if ups rd is u :: _\n  then upos <= u\n  else upos <  rend rd.\nArguments upos_before_rend [rd] r upos /.\n\nLemma validUsePosition `(r : Range rd) (upos : UsePos)\n  (Hbeg : rbeg rd <= upos) (Hend : upos_before_rend r upos) :\n  [/\\ validRangeBounds (rbeg rd) (rend rd) (upos :: ups rd)\n  &   StronglySorted upos_le (upos :: ups rd)].\nProof.\n  rewrite /= in Hend.\n  split.\n    move: (Range_proper r).\n    move/andP=> [H1 H2] /=.\n    do 3 (apply/andP; split => //).\n    case: (ups rd) => //= [u us] in Hend H2 *.\n    case: (uvar upos) => // in Hend *;\n    case: (uvar u) => //= in Hend H2 *;\n    case E: (uloc u == rend rd) => // in Hend *;\n    try move/leq_eqF in E;\n    by ordered.\n  move: (Range_sorted r) => Hsorted.\n  constructor=> // {Hbeg}.\n  case: (ups rd) => /= [|u us] in Hend Hsorted *.\n    by constructor.\n  case: (uvar upos) => // in Hend *;\n  try case: (uvar u) => //= in Hend *;\n  constructor=> //;\n  inv Hsorted;\n  case: (uloc u == rend rd) => // in Hend;\n  try exact/ltnW;\n  try exact: Forall_ordered;\n  try move/ltnW in Hend;\n  apply: Forall_ordered; rewrite /upos_le;\n  try exact Hend; auto.\nDefined.\n\nDefinition makeNewRange {b pos e} (H : b <= pos < e) (upos : UsePos)\n  (Heqe : uloc upos == if uvar upos is Input\n                       then pos.*2.+1\n                       else pos.*2.+2) :\n  BoundedRange b.*2.+1 e.*2.+1.\nProof.\n  (* If the variable is only [Input], assume it starts from the beginning; and\n     if [Output], that it persists until the end.  Only [Temp] variables are\n     handled using a single-instruction range. *)\n  pose rd :=\n    {| rbeg := if (uvar upos == Input) || (uvar upos == InputOutput)\n               then b.*2.+1\n               else pos.*2.+2\n     ; rend := match uvar upos with\n               | Input       => pos.*2.+2\n               | Temp        => pos.*2.+3\n               | InputOutput => e.*2.+1\n               | Output      => e.*2.+1\n               end\n     ; ups  := [:: upos ] |}.\n\n  apply: ((rd; _); _).\n    constructor=> /=.\n    + case E: (uvar upos) in Heqe rd *;\n      move/eqP in Heqe; rewrite {}Heqe;\n      try undoubled;\n      breakup; try undoubled;\n      simpl in *;\n      try apply/ltn_addn1;\n      rewrite -?doubleS ?ltn_Sdouble;\n      try undoubled.\n      rewrite doubleS.\n      apply ltnW.\n      apply ltn_addn1.\n      by undoubled.\n    + by constructor; constructor.\n\n  rewrite /= => r.\n  case: (uvar upos).\n  + case U: (pos.*2.+1 == pos.*2.+2).\n      move/eqP in U.\n      by ordered.\n    by undoubled.\n  (* jww (2015-08-29): Remove this repetition. *)\n  + clear r rd Heqe.\n    apply/andP; split;\n    rewrite -?doubleS ?ltn_Sdouble;\n    by undoubled.\n  + clear r rd Heqe.\n    apply/andP; split;\n    rewrite -?doubleS ?ltn_Sdouble;\n    simpl in *;\n    try undoubled.\n    rewrite doubleS.\n    apply ltnW.\n    apply ltn_addn1.\n    by undoubled.\n  + clear r rd Heqe.\n    simpl in *.\n    apply/andP; split;\n    rewrite -?doubleS ?ltn_Sdouble;\n    try undoubled.\n    rewrite doubleS.\n    apply ltnW.\n    apply ltn_addn1.\n    by undoubled.\nDefined.\n\nDefinition makeUsePos (pos : nat) (var : VarInfo maxReg) :\n  { u : UsePos | uloc u == if uvar u is Input\n                           then pos.*2.+1\n                           else pos.*2.+2 }.\nProof.\n  set upos := {| uloc   := if varKind var is Input\n                           then pos.*2.+1\n                           else pos.*2.+2\n               ; regReq := regRequired var\n               ; uvar   := varKind var |}.\n  exists upos;\n  rewrite /upos;\n  case: (varKind var) => //=;\n  by rewrite /= odd_double.\nDefined.\n\n(* This is the most complex of the variable handling functions, because under\n   certain circumstances we need to insert the variable into an existing range\n   rather than just create a new range each time, as we do for inputs and\n   temporaries. *)\nDefinition handleOutputVar {b pos e} (H : b <= pos < e)\n  (range : option (PendingRanges b e)) (var : VarInfo maxReg) :\n  option (PendingRanges b e).\nProof.\n  move: (makeUsePos pos var) => [upos Heqe].\n\n  (* If no range exists yet, make a new one that extends from [pos] to [e]. *)\n  case: range => [range|]; last first.\n    exact (Some [::: makeNewRange H Heqe]).\n\n  (* If [pos] fits within the current range, use it; otherwise, shift the\n     beginning of the current range down to [pos] so that our use position may\n     fit within it. The boolean value is true if we are to replace the\n     beginning of the range list with the new range, and false if we are to\n     prepend it only. *)\n  have res : (bool * { r1 : RangeSig | (b.*2.+1 <= rbeg r1.1 <= upos) &&\n                                       (rend r1.1 <= e.*2.+1) })%type.\n    move: (NE_head range) => [r /andP [Hbeg Hend]].\n    case E: (upos < head_or_end r.1).\n      case: (ups r.1) => /= [|[loc req kind] us].\n        split. exact true.\n        pose r1 := Range_shift r.2 E.\n        have Hr1: r1 = Range_shift r.2 E by [].\n        exists r1.\n        move: (Range_shift_spec Hr1) => [-> -> _].\n        move/eqP: Heqe => ->.\n        case: (uvar upos);\n        rewrite -?doubleS;\n        try undoubled.\n          move/andP in H.\n          destruct H.\n          apply/andP; split.\n            apply/andP; split.\n              rewrite doubleS.\n              apply ltnW.\n              apply ltn_addn1.\n              by undoubled.\n            by undoubled.\n          by undoubled.\n          apply/andP; split.\n            apply/andP; split.\n              rewrite doubleS.\n              apply ltnW.\n              apply ltn_addn1.\n              by undoubled.\n            by undoubled.\n          by undoubled.\n          apply/andP; split.\n            apply/andP; split.\n              rewrite doubleS.\n              apply ltnW.\n              apply ltn_addn1.\n              by undoubled.\n            by undoubled.\n          by undoubled.\n      (* Is the use position at the beginning of the range output only? If so,\n         then we can allow a lifetime hole between the current position and\n         the beginning of that range. *)\n      case: (kind == Output).\n        split. exact false.\n        have H0 : b <= pos < pos.+1 by ordered.\n        pose NR := makeNewRange H0 Heqe.\n        exists NR.1.\n        rewrite /= {NR}.\n        move/eqP: Heqe => ->.\n        case: (uvar upos) => /=;\n        rewrite -?doubleS;\n        try undoubled.\n          move/andP in H0.\n          destruct H0.\n          apply/andP; split.\n            apply/andP; split.\n              by undoubled.\n            rewrite doubleS.\n            apply ltnW.\n            apply ltn_addn1.\n            by undoubled.\n          by undoubled.\n          apply/andP; split.\n            apply/andP; split.\n              rewrite doubleS.\n              apply ltnW.\n              apply ltn_addn1.\n              by undoubled.\n            by undoubled.\n          by undoubled.\n          apply/andP; split.\n            apply/andP; split.\n              rewrite doubleS.\n              apply ltnW.\n              apply ltn_addn1.\n              by undoubled.\n            by undoubled.\n          by undoubled.\n      split. exact true.\n      pose r1 := Range_shift r.2 E.\n      have Hr1: r1 = Range_shift r.2 E by [].\n      exists r1.\n      move: (Range_shift_spec Hr1) => [-> -> _].\n      move/eqP: Heqe => ->.\n      case: (uvar upos);\n      rewrite -?doubleS;\n      try undoubled.\n        move/andP in H.\n        destruct H.\n        apply/andP; split.\n          apply/andP; split.\n            rewrite doubleS.\n            apply ltnW.\n            apply ltn_addn1.\n            by undoubled.\n          by undoubled.\n        by undoubled.\n        apply/andP; split.\n          apply/andP; split.\n            rewrite doubleS.\n            apply ltnW.\n            apply ltn_addn1.\n            by undoubled.\n          by undoubled.\n        by undoubled.\n        apply/andP; split.\n          apply/andP; split.\n            rewrite doubleS.\n            apply ltnW.\n            apply ltn_addn1.\n            by undoubled.\n          by undoubled.\n        by undoubled.\n    split. exact true.\n    move/negbT in E; rewrite -ltnNge /= in E.\n    exists r.\n    move: (Range_proper r.2) => /=.\n    by case: (ups r.1) => [|? ?] /= in E *; ordered.\n  move: res => [replaceFirst [r1 /andP [/andP [? Hbeg2] ?]]].\n\n  (* Check whether our use position actually fits within the end of the\n     current range, after shifting.  If not, ignore the current range and just\n     create a new one.  At the step where we combine the pending ranges, any\n     intersecting ranges will be coalesced. *)\n  case Hupos : (upos_before_rend r1.2 upos); last first.\n    exact: Some [::: makeNewRange H Heqe & range].\n\n  (* We have a valid range to put the use position in; derive this fact from\n     what we know so far, and then cons our use position onto the front of the\n     existing range. *)\n  move: (validUsePosition Hbeg2 Hupos) => [Hloc Hsorted].\n\n  case: replaceFirst.\n    have br : BoundedRange b.*2.+1 e.*2.+1.\n      exists (Range_cons r1.2 Hloc Hsorted).\n      by rewrite /=; ordered.\n    case: range => [_|_ rs].\n      exact: Some [::: br].\n    exact: Some [::: br & rs].\n  have br : BoundedRange b.*2.+1 e.*2.+1.\n    exists r1.\n    by ordered.\n  exact: Some [::: br & range].\nDefined.\n\nDefinition handleVar {b pos e} (H : b <= pos < e)\n  (range : option (PendingRanges b e)) (var : VarInfo maxReg) :\n  option (PendingRanges b e).\nProof.\n  move: (makeUsePos pos var) => [? Heqe].\n  case: range => [range|].\n    exact: Some [::: makeNewRange H Heqe & range].\n  exact: Some [::: makeNewRange H Heqe].\nDefined.\n\nDefinition handleVars_combine {b pos e} (H : b <= pos < e) (vid : nat)\n  (vars : seq (VarInfo maxReg)) (c1 : PendingRanges b e) :\n  option (PendingRanges b e).\nProof.\n  have Hlt : b < e by ordered.\n  have c2 := compressPendingRanges c1 Hlt.\n  have c3 := foldl (handleOutputVar H) (Some c2)\n                   (filter (fun k => varKind k == Output) vars).\n  have c4 := foldl (handleVar H) c3\n                   (filter (fun k => varKind k != Output) vars).\n  exact: c4.\nDefined.\n\n(* If there is no variable reference at this position, do nothing. *)\nDefinition handleVars_onlyRanges {b pos e} (H : b <= pos < e) :\n  IntMap (PendingRanges b e) -> IntMap (PendingRanges b e).\nProof. exact. Defined.\n\n(* If a variable referenced for which no reservation was made (for example, an\n   input variable that is not used as an output later in the block), we simply\n   add it. *)\nDefinition handleVars_onlyVars {b pos e} (H : b <= pos < e) :\n  IntMap (seq (VarInfo maxReg)) -> IntMap (PendingRanges b e).\nProof.\n  apply: IntMap_foldlWithKey _ emptyIntMap => m vid vars.\n  have c2 := foldl (handleOutputVar H) None\n                   (filter (fun k => varKind k == Output) vars).\n  have c3 := foldl (handleVar H) c2\n                   (filter (fun k => varKind k != Output) vars).\n  case: c3 => [c3|].\n    exact: IntMap_insert vid c3 m.\n  exact: m.\nDefined.\n\nDefinition handleVars\n  (varRefs : seq (VarInfo maxReg)) `(Hlt : b <= pos < e)\n  `(ranges : IntMap (PendingRanges b e)) : IntMap (PendingRanges b e) :=\n  let vars := IntMap_map NE_to_list $\n              IntMap_groupOn (@nat_of_varId maxReg) varRefs in\n  IntMap_mergeWithKey (handleVars_combine Hlt) (handleVars_onlyVars Hlt)\n                      (handleVars_onlyRanges Hlt) vars ranges.\n\nDefinition reduceOp {b pos e} (block : blockType1) (op : opType1)\n  (ranges : IntMap (PendingRanges b e)) (Hlt : b <= pos < e) :\n  IntMap (PendingRanges b e) :=\n  (* If the operation is a function call, force a flush of every register.\n\n     jww (2015-01-30): This needs to be improved to consider the calling\n     convention of the operation. *)\n  let refs  := opRefs oinfo op in\n  let refs' :=\n    if opKind oinfo op is IsCall\n    then\n      (* Although every register should be dropped, some architectures\n         actually pass the address they wish to call to in a variable.  Since\n         this is only an input variable, it's OK to allocate it up to the\n         call, since we needn't assume it will contain a value after the\n         call.  *)\n      let regsNeeded :=\n          count (fun r => match varId r with\n                          | inl _ => false\n                          | inr _ => true\n                          end) refs in\n      drop regsNeeded\n           (filter (fun x => varId x \\notin map (@varId maxReg) refs)\n                   [seq {| varId       := inl n\n                           ; varKind     := Temp\n                           ; regRequired := true\n                        |} | n in ord_enum maxReg]) ++ refs\n    else refs in\n\n  handleVars refs' Hlt ranges.\n\nLemma leq_plus : forall m n, m <= m + n.\nProof. elim=> [|m IHm] //=. Qed.\n\nLemma ltn_plus : forall m n, 0 < n -> m < m + n.\nProof. elim=> [|m IHm] //=. Qed.\n\nDefinition reduceBlock {pos} (bid : BlockId) (block : blockType1)\n  (Hsz : 0 < blockSize binfo block)\n  (loops : LoopState) (varUses : IntMap IntSet) :\n  let sz := blockSize binfo block in\n  let b := pos in\n  let e := pos + sz in\n  IntMap (PendingRanges b e) -> IntMap (PendingRanges b e).\nProof.\n  move=> sz b e.\n  rewrite /sz /blockSize.\n  set ops := allBlockOps binfo block.\n\n  have Hlt : pos <= (pos + sz).-1 < pos + sz.\n    apply/andP; split.\n      by rewrite -subn1 -addnBA // leq_plus //.\n    rewrite prednK.\n      by ordered.\n    rewrite addn_gt0.\n    by apply/orP; right.\n\n  (* If the current block is a loop end block, insert an [Input] pseudo-use\n     position at the very end of the block for every variable which was\n     referenced within that loop.  This causes the allocation algorithm to\n     split other intervals first before those used by the loop. *)\n  move=> ranges.\n  have :=\n    if ~~ IntSet_member bid (loopEndBlocks loops) then ranges else\n    let f acc loopIndex blks :=\n      if ~~ IntSet_member bid blks then acc else\n      if IntMap_lookup loopIndex varUses isn't Some uses then acc else\n      IntSet_union acc uses in\n    let uses := IntMap_foldlWithKey f emptyIntSet (loopIndices loops) in\n    handleVars [seq {| varId       := inr u\n                     ; varKind     := Input\n                     ; regRequired := false |}\n               | u <- IntSet_toList uses] Hlt ranges.\n  clear ranges.\n\n  have H : 0 < size ops -> b < pos + (size ops) <= e.\n    rewrite /b /e /sz /blockSize.\n    replace (allBlockOps binfo block) with ops; last by [].\n    move=> ?.\n    apply/andP; split=> //.\n    exact: ltn_plus.\n  elim/last_ind E: ops => [|os o IHos] /= in H *.\n    by [].\n  move=> ranges.\n\n  have H1 : b <= pos + (size os) < e.\n    rewrite size_rcons in H.\n    have: 0 < (size os).+1 by [].\n    move/H=> /andP [H2 H3].\n    apply/andP; split.\n      exact: leq_plus.\n    by rewrite addnS in H3.\n  move: (reduceOp block o ranges H1).\n\n  have: 0 < size os -> b < pos + size os <= e.\n    move=> ?.\n    apply/andP; split.\n      exact: ltn_plus.\n    move/andP: H1 => [_ ?].\n    exact/ltnW.\n  exact: IHos.\nDefined.\n\nDefinition reduceBlocks (blocks : seq blockType1) (loops : LoopState)\n  (varUses : IntMap IntSet) (liveSets : IntMap BlockLiveSets) {pos} :\n  BuildState pos.\nProof.\n  elim: blocks => [|b blocks IHbs] in pos *.\n    exact: newBuildState.\n\n  pose sz := blockSize binfo b.\n  case E: (0 < sz);\n    last exact: IHbs pos.\n\n  have Hsz : pos < pos + sz by exact: ltn_plus.\n\n  have bid := blockId binfo b.\n  have outs := if IntMap_lookup bid liveSets is Some ls\n               then blockLiveOut ls\n               else emptyIntSet.\n  have ranges := emptyPendingRanges Hsz outs.\n  have pending := reduceBlock bid E loops varUses ranges.\n  exact: mergeIntoSortedRanges Hsz pending (IHbs (pos + sz)).\nDefined.\n\nDefinition compileIntervals `(bs : BuildState pos) :\n  (* Return the set of fixed intervals, and the set of variable intervals,\n     respectively. *)\n  FixedIntervalsType maxReg * IntMap IntervalSig.\nProof.\n  apply: IntMap_foldlWithKey _ (vconst None, emptyIntMap) bs.\n  move=> [regs vars] vid rs.\n  case E: rs.1 => [|? ?];\n    first by exact: (regs, vars).\n  case V: (vid < maxReg).\n    simpl in E.\n    move: (Interval_fromRanges vid E) => /= i.\n    exact: (vreplace regs (Ordinal V) (Some (packInterval i)), vars).\n  have vid' := vid - maxReg.\n  move: (Interval_fromRanges vid' E) => /= i.\n  exact: (regs, IntMap_insert vid' (packInterval i) vars).\nDefined.\n\nDefinition buildIntervals (blocks : seq blockType1) (loops : LoopState)\n  (liveSets : IntMap BlockLiveSets) : ScanStateSig maxReg InUse :=\n  let add_unhandled_interval (ss  : ScanStateSig maxReg Pending) i :=\n        packScanState (ScanState_newUnhandled ss.2 i.2 I) in\n  let s0 := ScanState_nil maxReg in\n  if blocks isn't b :: bs\n  then packScanState (ScanState_finalize s0)\n  else\n    let varUses := computeVarReferences binfo oinfo (b :: bs) loops in\n    let reduced := reduceBlocks (pos:=0) (b :: bs) loops varUses liveSets in\n    let: (regs, vars) := compileIntervals reduced in\n    let s1 := ScanState_setFixedIntervals s0 regs in\n    let s2 := packScanState s1 in\n    let s3 := IntMap_foldl add_unhandled_interval s2 vars in\n    let s4 := ScanState_finalize s3.2 in\n    packScanState s4.\n\nEnd Build.\n", "meta": {"author": "jwiegley", "repo": "linearscan", "sha": "1f8c74134d7634061d3cce4b2817708e9e82037d", "save_path": "github-repos/coq/jwiegley-linearscan", "path": "github-repos/coq/jwiegley-linearscan/linearscan-1f8c74134d7634061d3cce4b2817708e9e82037d/src/Build.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.25388618682561714}}
{"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.Znat.\nFrom Coq Require Import ZArith Psatz.\nFrom Coq Require Import PeanoNat.\nImport ListNotations.\n\n\nInductive move :=\n  | R : nat -> move\n  | L : nat -> move\n  | U : nat -> move\n  | D : nat -> move\n.\n\nDefinition test_in := [\nR 4;\nU 4;\nL 3;\nD 1;\nR 4;\nD 1;\nL 5;\nR 2\n].\n\nDefinition input := [\nR 2;\nL 2;\nD 2;\nU 2;\nR 2;\nD 2;\nL 2;\nD 2;\nU 2;\nL 2;\nD 1;\nR 1;\nD 2;\nR 2;\nU 1;\nR 1;\nU 2;\nR 1;\nL 2;\nD 2;\nL 1;\nU 1;\nL 1;\nD 1;\nR 1;\nL 2;\nU 2;\nR 2;\nU 1;\nR 2;\nL 2;\nD 1;\nU 1;\nD 2;\nL 1;\nU 1;\nL 1;\nD 1;\nU 1;\nD 1;\nL 2;\nD 2;\nU 2;\nL 2;\nU 1;\nR 2;\nD 2;\nL 1;\nR 1;\nU 1;\nR 1;\nL 1;\nU 2;\nD 1;\nU 2;\nR 1;\nU 1;\nR 2;\nD 2;\nR 2;\nU 2;\nD 2;\nU 2;\nL 1;\nD 2;\nR 1;\nL 2;\nD 2;\nR 2;\nL 2;\nU 2;\nL 2;\nR 1;\nD 1;\nR 1;\nL 2;\nD 1;\nL 2;\nR 1;\nU 1;\nR 1;\nU 1;\nL 2;\nU 1;\nD 2;\nR 1;\nL 1;\nD 1;\nR 1;\nL 2;\nR 2;\nL 2;\nR 1;\nL 1;\nD 1;\nL 1;\nR 1;\nD 2;\nU 1;\nD 2;\nR 1;\nD 1;\nU 1;\nL 1;\nR 1;\nD 2;\nR 2;\nL 2;\nR 1;\nL 1;\nR 1;\nU 3;\nL 2;\nR 3;\nL 1;\nR 1;\nL 2;\nD 1;\nU 3;\nL 1;\nR 3;\nU 1;\nL 2;\nU 2;\nD 2;\nR 2;\nD 1;\nL 2;\nU 1;\nR 1;\nL 3;\nR 2;\nL 3;\nR 2;\nL 2;\nD 2;\nU 3;\nR 2;\nL 1;\nR 2;\nU 1;\nD 2;\nU 3;\nD 1;\nU 3;\nL 1;\nR 3;\nD 2;\nR 1;\nL 2;\nD 1;\nL 1;\nD 3;\nU 2;\nL 3;\nR 1;\nU 3;\nL 1;\nR 2;\nU 3;\nD 2;\nU 3;\nL 3;\nR 1;\nL 2;\nR 2;\nD 3;\nL 1;\nD 3;\nR 3;\nL 1;\nU 1;\nD 1;\nL 3;\nD 1;\nU 2;\nD 3;\nU 3;\nL 1;\nU 2;\nD 1;\nR 3;\nD 1;\nR 1;\nL 2;\nU 1;\nR 1;\nL 1;\nU 3;\nD 3;\nU 3;\nR 1;\nD 3;\nU 1;\nL 2;\nR 2;\nU 2;\nR 1;\nD 3;\nL 1;\nD 2;\nU 2;\nR 2;\nD 2;\nR 3;\nL 2;\nR 1;\nL 3;\nD 3;\nR 1;\nL 1;\nU 3;\nR 1;\nD 3;\nR 3;\nD 2;\nU 2;\nR 2;\nD 2;\nU 3;\nD 2;\nR 1;\nU 2;\nL 3;\nD 1;\nL 2;\nU 1;\nD 1;\nU 4;\nR 4;\nU 4;\nD 4;\nU 3;\nD 1;\nR 4;\nL 1;\nD 2;\nR 3;\nU 1;\nR 2;\nD 2;\nU 4;\nR 3;\nD 2;\nL 1;\nU 4;\nD 3;\nU 1;\nD 4;\nL 2;\nU 3;\nD 4;\nR 3;\nL 2;\nD 4;\nL 2;\nR 3;\nU 2;\nR 2;\nU 1;\nL 3;\nR 3;\nL 3;\nU 4;\nR 4;\nU 2;\nR 3;\nU 1;\nL 3;\nD 4;\nL 4;\nR 4;\nD 3;\nL 4;\nR 1;\nU 4;\nD 3;\nR 3;\nU 1;\nL 4;\nU 2;\nL 2;\nD 4;\nU 3;\nR 1;\nU 2;\nD 4;\nU 4;\nD 4;\nU 1;\nL 4;\nR 3;\nU 2;\nR 1;\nL 4;\nD 4;\nU 3;\nR 2;\nL 2;\nU 3;\nL 1;\nR 1;\nL 1;\nU 4;\nL 1;\nR 3;\nU 1;\nR 1;\nD 2;\nR 2;\nL 4;\nD 1;\nL 2;\nR 1;\nD 1;\nL 3;\nD 3;\nU 4;\nR 2;\nL 4;\nU 2;\nL 1;\nR 3;\nU 3;\nL 2;\nR 2;\nD 2;\nR 3;\nU 4;\nL 1;\nU 3;\nL 3;\nU 1;\nR 1;\nL 2;\nD 3;\nL 5;\nD 2;\nU 2;\nD 4;\nR 2;\nL 3;\nU 3;\nR 1;\nU 4;\nD 1;\nR 2;\nU 1;\nL 5;\nR 4;\nD 5;\nR 5;\nD 2;\nU 2;\nL 5;\nD 2;\nU 3;\nR 2;\nL 4;\nD 5;\nL 4;\nR 4;\nU 5;\nR 2;\nU 5;\nL 1;\nD 2;\nL 3;\nU 4;\nD 2;\nU 2;\nL 3;\nR 4;\nU 4;\nR 5;\nL 1;\nD 2;\nU 4;\nD 5;\nL 5;\nR 4;\nU 3;\nR 2;\nU 5;\nL 3;\nU 5;\nR 3;\nU 2;\nR 2;\nD 3;\nR 2;\nL 2;\nD 4;\nR 4;\nU 3;\nR 3;\nD 5;\nR 2;\nU 3;\nL 5;\nR 1;\nU 5;\nD 4;\nR 3;\nD 5;\nU 1;\nR 4;\nL 5;\nD 1;\nU 3;\nL 4;\nU 3;\nR 3;\nD 5;\nU 5;\nD 5;\nL 5;\nU 4;\nD 5;\nL 3;\nR 3;\nD 4;\nU 2;\nL 5;\nR 1;\nU 5;\nL 4;\nU 4;\nD 5;\nR 4;\nL 1;\nU 2;\nD 2;\nL 1;\nR 2;\nD 4;\nR 5;\nL 3;\nR 4;\nD 4;\nL 4;\nR 2;\nL 1;\nD 3;\nL 3;\nR 2;\nD 3;\nR 5;\nD 2;\nU 4;\nD 5;\nL 1;\nU 3;\nD 3;\nU 6;\nL 1;\nR 1;\nL 4;\nR 6;\nL 1;\nR 1;\nD 2;\nU 6;\nR 1;\nU 3;\nR 6;\nU 1;\nR 1;\nL 3;\nD 5;\nR 6;\nL 6;\nR 1;\nU 2;\nR 1;\nL 5;\nR 5;\nD 6;\nR 4;\nD 4;\nR 1;\nU 6;\nR 4;\nU 1;\nR 5;\nU 3;\nL 5;\nU 1;\nR 5;\nL 5;\nD 5;\nR 3;\nL 5;\nD 3;\nL 2;\nU 3;\nR 1;\nU 1;\nD 4;\nR 4;\nL 2;\nU 3;\nL 1;\nU 5;\nL 5;\nD 4;\nR 6;\nU 6;\nL 5;\nU 3;\nR 3;\nD 1;\nU 6;\nR 2;\nL 4;\nR 2;\nL 5;\nU 3;\nD 1;\nU 3;\nR 1;\nD 1;\nL 3;\nU 6;\nL 5;\nU 2;\nL 3;\nD 1;\nL 3;\nU 6;\nL 4;\nD 3;\nR 4;\nD 1;\nL 4;\nU 1;\nR 6;\nD 6;\nR 5;\nD 4;\nR 4;\nD 4;\nU 6;\nD 4;\nL 3;\nR 4;\nL 5;\nR 1;\nD 6;\nU 6;\nD 2;\nR 1;\nL 6;\nU 6;\nL 5;\nD 6;\nU 4;\nR 4;\nD 3;\nU 5;\nD 6;\nU 7;\nL 5;\nU 7;\nR 6;\nU 1;\nL 6;\nU 1;\nR 2;\nD 7;\nR 4;\nU 1;\nR 6;\nL 6;\nD 4;\nL 4;\nU 4;\nR 1;\nD 7;\nL 7;\nD 7;\nL 5;\nD 1;\nL 1;\nU 2;\nR 5;\nD 5;\nL 3;\nU 5;\nD 6;\nL 4;\nR 1;\nU 6;\nL 3;\nD 6;\nL 7;\nD 6;\nR 3;\nU 7;\nR 1;\nD 6;\nR 3;\nU 7;\nD 5;\nU 1;\nL 4;\nU 3;\nD 3;\nU 3;\nR 1;\nL 2;\nR 2;\nL 1;\nU 3;\nD 5;\nU 7;\nD 1;\nU 7;\nL 4;\nD 3;\nU 4;\nR 6;\nD 2;\nL 5;\nR 7;\nL 5;\nR 1;\nU 6;\nR 7;\nU 4;\nD 3;\nU 1;\nL 1;\nD 1;\nU 6;\nL 1;\nU 1;\nR 7;\nL 4;\nD 1;\nU 2;\nR 7;\nL 7;\nR 5;\nU 4;\nR 2;\nL 7;\nU 6;\nR 5;\nL 1;\nR 3;\nU 7;\nD 7;\nL 4;\nR 1;\nU 4;\nR 1;\nL 7;\nD 4;\nL 5;\nD 7;\nU 4;\nL 5;\nR 6;\nU 1;\nL 4;\nR 6;\nD 2;\nL 1;\nD 2;\nU 4;\nL 5;\nU 5;\nD 4;\nU 7;\nL 2;\nD 3;\nU 5;\nR 7;\nD 1;\nR 7;\nD 6;\nU 4;\nR 3;\nD 5;\nU 5;\nD 8;\nR 7;\nL 7;\nR 1;\nD 5;\nL 3;\nR 1;\nU 3;\nR 6;\nD 5;\nR 6;\nL 5;\nD 7;\nL 5;\nR 2;\nD 1;\nR 7;\nL 1;\nD 3;\nR 8;\nL 5;\nU 8;\nR 6;\nU 4;\nD 2;\nU 4;\nD 5;\nU 7;\nD 5;\nU 2;\nD 3;\nU 1;\nR 4;\nL 2;\nR 4;\nU 7;\nR 8;\nD 2;\nU 3;\nR 7;\nD 2;\nU 1;\nD 6;\nR 4;\nL 4;\nR 3;\nD 8;\nR 8;\nU 7;\nL 3;\nU 7;\nD 1;\nU 6;\nR 8;\nL 1;\nR 1;\nD 8;\nU 7;\nL 3;\nD 4;\nL 4;\nR 2;\nL 6;\nD 6;\nL 4;\nR 7;\nD 8;\nL 8;\nU 8;\nR 2;\nL 6;\nU 5;\nD 2;\nL 5;\nU 1;\nL 6;\nD 6;\nU 7;\nL 2;\nU 5;\nR 6;\nD 5;\nL 8;\nU 8;\nR 1;\nU 2;\nL 3;\nD 1;\nL 3;\nU 4;\nD 3;\nL 6;\nR 9;\nL 9;\nU 9;\nR 1;\nD 4;\nU 1;\nL 3;\nR 7;\nU 7;\nR 1;\nU 1;\nR 2;\nD 4;\nU 8;\nL 7;\nR 3;\nU 8;\nL 1;\nR 1;\nD 7;\nU 3;\nL 3;\nU 8;\nD 3;\nL 1;\nD 6;\nL 3;\nU 4;\nD 3;\nU 3;\nL 3;\nD 5;\nL 6;\nU 9;\nL 1;\nU 2;\nL 3;\nR 1;\nL 9;\nD 2;\nU 1;\nL 3;\nR 9;\nL 8;\nR 2;\nL 7;\nD 4;\nL 4;\nR 2;\nL 4;\nR 8;\nD 4;\nL 2;\nD 5;\nR 8;\nU 6;\nL 9;\nD 1;\nL 6;\nR 9;\nD 4;\nL 5;\nU 5;\nD 1;\nU 3;\nL 4;\nU 2;\nL 2;\nR 2;\nL 1;\nR 7;\nL 4;\nD 4;\nU 4;\nL 1;\nR 2;\nD 6;\nL 1;\nU 8;\nD 7;\nR 5;\nD 7;\nR 7;\nL 8;\nU 8;\nL 5;\nD 7;\nU 2;\nD 2;\nR 1;\nU 2;\nL 1;\nR 1;\nL 2;\nD 1;\nU 9;\nL 9;\nU 9;\nR 1;\nU 3;\nR 7;\nU 8;\nR 1;\nL 7;\nD 1;\nU 7;\nR 9;\nD 8;\nR 2;\nD 5;\nL 5;\nD 2;\nL 6;\nU 6;\nR 1;\nL 1;\nD 2;\nR 4;\nL 3;\nU 2;\nR 5;\nL 3;\nR 6;\nU 8;\nR 1;\nU 1;\nR 7;\nD 10;\nR 2;\nD 4;\nR 3;\nL 5;\nD 1;\nU 8;\nR 1;\nU 4;\nD 6;\nL 5;\nU 8;\nD 6;\nL 6;\nR 4;\nL 9;\nR 5;\nU 6;\nL 8;\nU 6;\nL 10;\nD 4;\nU 6;\nL 8;\nU 3;\nR 3;\nL 6;\nU 1;\nR 9;\nD 8;\nU 9;\nR 5;\nU 10;\nR 8;\nU 9;\nL 7;\nR 4;\nD 7;\nU 3;\nL 5;\nR 3;\nD 9;\nL 9;\nU 6;\nR 10;\nL 2;\nD 7;\nU 8;\nD 4;\nL 3;\nU 4;\nR 2;\nL 10;\nD 4;\nU 10;\nR 7;\nD 5;\nR 7;\nU 3;\nL 10;\nR 8;\nL 7;\nD 3;\nL 6;\nR 1;\nL 2;\nU 1;\nR 1;\nU 8;\nR 5;\nL 9;\nR 9;\nL 1;\nD 4;\nR 6;\nU 7;\nL 7;\nR 3;\nU 4;\nD 2;\nU 8;\nL 5;\nD 3;\nL 6;\nD 7;\nL 2;\nU 1;\nR 6;\nL 8;\nD 9;\nR 3;\nU 4;\nD 8;\nL 5;\nR 9;\nL 1;\nU 7;\nL 5;\nD 4;\nU 5;\nL 4;\nR 4;\nL 3;\nU 11;\nD 1;\nL 10;\nU 6;\nL 5;\nD 3;\nU 8;\nD 11;\nL 8;\nR 2;\nU 5;\nL 9;\nD 3;\nL 11;\nR 2;\nU 5;\nL 7;\nD 11;\nR 8;\nU 1;\nL 10;\nR 10;\nL 9;\nR 9;\nL 8;\nR 7;\nD 3;\nU 6;\nR 11;\nU 8;\nD 4;\nL 9;\nU 3;\nD 5;\nL 4;\nR 5;\nD 7;\nL 5;\nU 10;\nD 8;\nL 3;\nD 2;\nU 9;\nD 6;\nL 3;\nU 3;\nD 8;\nU 4;\nR 1;\nL 9;\nU 4;\nL 5;\nD 10;\nL 11;\nU 6;\nD 8;\nL 5;\nR 9;\nL 2;\nU 2;\nL 10;\nR 5;\nU 6;\nL 7;\nR 7;\nU 9;\nD 6;\nR 7;\nD 8;\nU 7;\nR 6;\nL 2;\nD 6;\nR 8;\nL 5;\nR 1;\nL 10;\nR 8;\nU 11;\nR 10;\nL 10;\nR 10;\nL 4;\nU 4;\nD 9;\nU 8;\nR 5;\nD 7;\nU 7;\nL 6;\nD 4;\nL 9;\nR 2;\nU 8;\nD 2;\nL 2;\nD 2;\nU 6;\nL 2;\nR 9;\nU 10;\nD 11;\nU 3;\nR 9;\nU 1;\nL 11;\nR 7;\nL 4;\nR 5;\nU 10;\nL 3;\nR 10;\nL 10;\nD 2;\nL 9;\nD 9;\nL 6;\nD 11;\nR 10;\nL 2;\nR 4;\nD 2;\nR 4;\nD 8;\nL 3;\nU 10;\nR 4;\nL 2;\nU 1;\nL 3;\nR 1;\nL 2;\nR 3;\nD 2;\nL 2;\nD 3;\nR 5;\nU 10;\nL 12;\nR 5;\nD 5;\nU 9;\nL 9;\nD 2;\nL 8;\nU 2;\nL 11;\nU 5;\nL 8;\nU 7;\nR 4;\nU 10;\nD 4;\nL 5;\nR 3;\nD 8;\nR 12;\nL 5;\nU 9;\nL 10;\nR 5;\nU 10;\nR 1;\nL 5;\nU 6;\nD 7;\nL 12;\nD 2;\nR 12;\nL 1;\nU 11;\nD 8;\nR 12;\nL 8;\nU 3;\nR 9;\nL 8;\nD 2;\nL 10;\nD 10;\nR 4;\nD 2;\nR 11;\nU 4;\nR 10;\nU 7;\nL 7;\nD 5;\nU 5;\nR 9;\nD 10;\nL 10;\nU 1;\nD 11;\nU 4;\nD 5;\nU 5;\nD 8;\nU 2;\nD 4;\nR 4;\nL 5;\nU 10;\nD 12;\nR 9;\nL 11;\nR 9;\nL 1;\nD 9;\nL 11;\nD 12;\nU 4;\nR 7;\nD 1;\nU 3;\nL 4;\nU 9;\nR 12;\nD 1;\nL 7;\nU 7;\nD 6;\nU 1;\nR 3;\nL 7;\nU 5;\nL 2;\nD 10;\nR 12;\nL 3;\nU 7;\nD 10;\nL 5;\nR 1;\nU 9;\nL 1;\nD 11;\nR 5;\nL 2;\nD 1;\nU 3;\nR 2;\nL 3;\nU 5;\nL 3;\nD 5;\nR 10;\nL 7;\nR 12;\nU 4;\nD 3;\nR 3;\nL 2;\nR 7;\nU 4;\nD 9;\nU 7;\nD 1;\nR 9;\nL 2;\nU 6;\nR 5;\nD 3;\nU 7;\nR 12;\nL 10;\nD 11;\nL 8;\nU 12;\nD 13;\nU 9;\nD 5;\nU 4;\nR 2;\nL 3;\nU 13;\nR 4;\nL 9;\nU 4;\nL 3;\nU 9;\nR 1;\nD 6;\nU 4;\nD 3;\nU 5;\nR 5;\nL 11;\nR 8;\nD 1;\nU 4;\nD 10;\nR 5;\nD 10;\nU 3;\nD 4;\nR 1;\nU 3;\nR 13;\nL 6;\nD 8;\nR 12;\nL 4;\nU 2;\nL 13;\nD 11;\nL 4;\nU 8;\nL 10;\nR 2;\nD 8;\nR 11;\nL 2;\nD 8;\nR 8;\nL 10;\nU 10;\nL 4;\nD 9;\nL 7;\nD 11;\nL 10;\nU 13;\nL 6;\nU 7;\nD 8;\nL 3;\nR 10;\nL 14;\nU 13;\nL 11;\nD 5;\nR 8;\nU 2;\nD 9;\nL 14;\nU 7;\nR 4;\nU 1;\nD 8;\nU 8;\nD 9;\nL 2;\nD 7;\nR 1;\nD 9;\nR 2;\nU 4;\nD 8;\nL 9;\nR 6;\nL 2;\nR 11;\nD 6;\nL 5;\nU 8;\nL 4;\nR 3;\nD 5;\nL 3;\nU 9;\nR 3;\nU 1;\nD 7;\nR 1;\nL 10;\nU 1;\nL 8;\nU 11;\nD 8;\nU 12;\nR 9;\nL 5;\nD 10;\nL 2;\nR 8;\nD 10;\nR 6;\nD 1;\nL 11;\nD 8;\nR 7;\nL 14;\nD 12;\nL 11;\nR 11;\nU 9;\nR 12;\nD 10;\nL 12;\nR 4;\nL 8;\nD 2;\nR 3;\nL 14;\nR 7;\nU 10;\nR 1;\nL 6;\nR 4;\nD 11;\nL 13;\nR 12;\nU 4;\nL 12;\nU 10;\nD 8;\nR 10;\nD 9;\nR 13;\nL 2;\nU 2;\nD 7;\nU 7;\nR 3;\nD 3;\nR 13;\nU 8;\nR 10;\nU 13;\nD 14;\nR 11;\nD 7;\nR 2;\nU 5;\nD 2;\nL 6;\nU 14;\nL 10;\nR 9;\nU 11;\nR 12;\nD 5;\nL 11;\nR 12;\nU 11;\nR 8;\nL 2;\nD 14;\nU 3;\nD 9;\nU 5;\nL 4;\nU 5;\nL 6;\nD 3;\nL 1;\nR 10;\nL 4;\nD 12;\nU 15;\nL 5;\nD 11;\nL 15;\nD 10;\nL 14;\nU 1;\nL 14;\nD 6;\nR 6;\nU 9;\nR 1;\nL 7;\nD 11;\nU 12;\nD 2;\nR 7;\nL 2;\nD 13;\nU 13;\nR 6;\nL 3;\nD 3;\nR 11;\nU 3;\nD 3;\nU 11;\nL 10;\nU 7;\nR 7;\nD 9;\nU 10;\nR 11;\nU 12;\nD 11;\nR 11;\nU 2;\nR 2;\nD 9;\nR 12;\nD 1;\nL 11;\nR 1;\nU 2;\nR 14;\nL 4;\nR 1;\nD 12;\nR 7;\nU 12;\nL 2;\nU 5;\nD 7;\nR 15;\nD 5;\nL 9;\nD 7;\nR 10;\nU 12;\nD 10;\nR 11;\nD 5;\nU 10;\nR 2;\nU 11;\nR 3;\nU 6;\nD 14;\nU 11;\nD 5;\nL 8;\nD 6;\nL 2;\nU 2;\nL 14;\nR 8;\nU 15;\nL 10;\nD 1;\nR 4;\nL 8;\nD 7;\nL 15;\nU 10;\nD 14;\nU 9;\nL 7;\nR 13;\nU 11;\nR 15;\nL 11;\nR 2;\nL 11;\nR 14;\nL 1;\nD 10;\nL 2;\nU 7;\nL 9;\nD 12;\nR 2;\nL 4;\nU 4;\nR 9;\nL 6;\nR 13;\nD 1;\nU 13;\nR 7;\nD 3;\nR 14;\nL 12;\nD 15;\nR 16;\nL 7;\nR 2;\nU 3;\nR 9;\nU 10;\nD 6;\nU 7;\nL 11;\nD 12;\nL 16;\nR 12;\nD 10;\nU 16;\nD 9;\nU 14;\nL 14;\nU 11;\nD 14;\nL 14;\nD 10;\nL 3;\nD 10;\nU 6;\nD 11;\nL 8;\nU 4;\nD 1;\nU 5;\nD 5;\nL 4;\nU 8;\nR 3;\nD 12;\nU 4;\nR 8;\nD 6;\nU 8;\nD 2;\nU 12;\nL 6;\nD 12;\nR 7;\nD 6;\nU 7;\nD 12;\nL 3;\nR 2;\nL 12;\nR 13;\nU 16;\nL 6;\nD 8;\nU 13;\nR 14;\nD 4;\nU 7;\nD 1;\nR 4;\nD 13;\nR 10;\nD 7;\nR 11;\nL 6;\nU 6;\nR 7;\nL 8;\nD 2;\nL 11;\nU 3;\nL 12;\nU 4;\nD 11;\nU 8;\nD 10;\nU 1;\nR 12;\nU 1;\nL 15;\nR 15;\nD 2;\nL 8;\nD 13;\nL 3;\nR 8;\nU 14;\nR 5;\nU 3;\nD 15;\nU 7;\nD 1;\nL 6;\nD 8;\nU 13;\nR 6;\nL 6;\nD 3;\nL 9;\nD 17;\nU 8;\nR 16;\nL 6;\nD 9;\nU 3;\nL 10;\nR 13;\nL 14;\nU 8;\nR 7;\nU 12;\nD 14;\nR 1;\nD 3;\nL 11;\nR 8;\nD 9;\nR 17;\nD 5;\nR 17;\nU 8;\nL 10;\nD 7;\nU 4;\nD 16;\nL 9;\nD 1;\nL 16;\nR 7;\nL 1;\nR 11;\nU 10;\nR 2;\nU 10;\nL 15;\nU 10;\nR 2;\nD 11;\nU 12;\nL 15;\nU 4;\nD 2;\nR 4;\nU 2;\nL 11;\nR 16;\nU 10;\nR 4;\nD 9;\nU 7;\nD 2;\nR 10;\nD 14;\nL 10;\nU 9;\nR 7;\nD 3;\nR 7;\nL 3;\nU 15;\nD 13;\nL 17;\nR 12;\nU 13;\nD 16;\nU 13;\nR 13;\nU 14;\nL 16;\nU 7;\nD 2;\nR 11;\nU 17;\nD 9;\nR 12;\nU 16;\nL 11;\nR 3;\nU 9;\nL 6;\nD 2;\nU 1;\nD 7;\nL 1;\nU 7;\nD 8;\nU 11;\nL 4;\nR 6;\nL 2;\nU 12;\nL 13;\nU 5;\nL 17;\nR 16;\nD 10;\nU 12;\nL 7;\nR 4;\nU 8;\nD 17;\nR 13;\nL 2;\nD 5;\nL 1;\nR 2;\nD 16;\nU 9;\nD 15;\nL 8;\nU 14;\nR 9;\nD 18;\nU 16;\nL 17;\nU 9;\nD 11;\nU 17;\nR 8;\nD 17;\nU 14;\nD 8;\nU 8;\nR 8;\nU 14;\nR 5;\nL 1;\nR 3;\nD 5;\nU 10;\nR 16;\nU 18;\nD 16;\nU 11;\nD 18;\nU 13;\nL 11;\nD 2;\nR 16;\nD 15;\nL 9;\nD 12;\nR 11;\nL 8;\nU 8;\nR 10;\nL 2;\nD 6;\nL 5;\nD 9;\nL 3;\nD 1;\nU 18;\nD 12;\nU 13;\nL 6;\nR 17;\nD 10;\nR 9;\nL 6;\nR 3;\nU 1;\nR 1;\nU 6;\nL 15;\nU 8;\nD 15;\nU 14;\nR 10;\nL 6;\nU 1;\nL 12;\nR 9;\nD 13;\nU 1;\nL 16;\nU 16;\nL 13;\nR 4;\nU 3;\nD 11;\nL 12;\nR 11;\nU 17;\nR 18;\nL 4;\nR 6;\nL 18;\nD 10;\nL 16;\nR 2;\nD 4;\nR 14;\nD 11;\nL 12;\nR 7;\nL 9;\nU 12;\nD 12;\nR 4;\nL 1;\nD 14;\nR 14;\nL 3;\nU 2;\nL 6;\nR 7;\nD 6;\nU 18;\nL 17;\nU 12;\nR 12;\nL 5;\nD 13;\nR 7;\nD 8;\nL 16;\nD 13;\nU 4;\nD 3;\nR 16;\nL 9;\nU 8;\nD 15;\nR 8;\nL 12;\nR 5;\nL 1;\nU 11;\nD 11;\nL 10;\nU 7;\nD 6;\nL 15;\nD 9;\nR 10;\nD 6;\nU 14;\nL 7;\nU 19;\nR 17;\nL 12;\nU 1;\nL 9;\nR 17;\nD 12;\nU 3;\nL 15;\nR 16;\nD 15;\nR 15;\nL 1;\nU 16;\nR 19;\nD 9;\nL 16;\nD 12;\nR 8;\nL 2;\nD 16;\nL 17;\nU 16;\nD 9;\nL 9;\nU 8;\nL 9;\nR 16;\nL 3;\nD 8;\nU 7;\nD 10;\nU 17;\nR 2;\nD 16;\nR 6;\nU 9;\nR 4;\nL 17;\nD 10;\nU 10;\nL 14;\nD 9;\nR 8;\nL 9;\nR 18;\nU 13;\nL 16;\nR 2;\nU 16;\nL 11;\nU 4;\nL 13;\nR 8;\nL 19;\nU 4;\nD 10;\nR 10;\nU 14;\nR 13;\nL 17;\nU 17;\nR 12;\nD 18;\nR 2;\nD 5;\nL 12;\nU 6;\nD 7;\nR 9;\nL 13;\nD 15;\nR 9;\nU 16;\nD 14;\nR 8;\nL 8;\nU 10;\nL 8;\nD 18;\nU 8;\nD 9;\nL 6;\nR 8;\nU 4;\nD 14;\nL 13;\nD 4;\nR 3;\nU 13;\nL 2].\n\nOpen Scope Z_scope.\nFixpoint set_add (pos : (Z*Z)) (l : list (Z*Z)) :=\n  let (x,y) := pos in\n  match l with\n  | nil => [pos]\n  | (x',y') :: r => if x <? x' then (x',y') :: set_add pos r else if y <? y' then (x',y') :: set_add pos r else if andb (x =? x') (y =? y') then l else pos :: l\n  end.\n\nDefinition state : Type := ((Z*Z)*list (Z*Z)*list (Z*Z)).\n\nDefinition move_close (h : Z*Z) (t : Z*Z) : Z*Z :=\n  let (hx,hy) := h in\n  let (tx,ty) := t in\n  if Z.max (Z.abs (hx-tx)) (Z.abs (hy-ty)) >? 1 then\n    (tx+Z.sgn (hx-tx),ty+Z.sgn (hy-ty))\n  else\n    t\n.\n\nFixpoint update_rope (prev : Z*Z) (l : list (Z*Z)) :=\n  match l with\n  | nil => nil\n  | h :: r => let h' := (move_close prev h) in h' :: update_rope h' r\n  end.\n\nFixpoint plast (l : list (Z*Z)) :=\n  match l with\n  | nil => (0,0)\n  | [x] => x\n  | h :: t => plast t\n  end.\n\nDefinition step_right (curState : state) : state :=\n  let (p,seen)  := curState in\n  let (h,t)  := p in\n  let (hx,hy) := h in\n  let h' := (hx+1,hy) in\n  let t' := update_rope h' t in\n  (h',t',set_add (plast t') seen)\n.\n\nDefinition step_left (curState : state) : state :=\n  let (p,seen)  := curState in\n  let (h,t)  := p in\n  let (hx,hy) := h in\n  let h' := (hx-1,hy) in\n  let t' := update_rope h' t in\n  (h',t',set_add (plast t') seen)\n.\nDefinition step_up (curState : state) : state :=\n  let (p,seen)  := curState in\n  let (h,t)  := p in\n  let (hx,hy) := h in\n  let h' := (hx,hy+1) in\n  let t' := update_rope h' t in\n  (h',t',set_add (plast t') seen)\n.\nDefinition step_down (curState : state) : state :=\n  let (p,seen)  := curState in\n  let (h,t)  := p in\n  let (hx,hy) := h in\n  let h' := (hx,hy-1) in\n  let t' := update_rope h' t in\n  (h',t',set_add (plast t') seen)\n.\n\nFixpoint n_times {A} (t : nat) (f : A -> A) (a : A):=\n  match t with\n  | O => a\n  | S n => n_times n f (f a)\n  end.\n\nDefinition step (m : move) (curState : state) : state :=\n  match m with\n  | R n => n_times n step_right curState\n  | L n => n_times n step_left curState\n  | U n => n_times n step_up curState\n  | D n => n_times n step_down curState\n  end.\n\nDefinition flip {A B C} (f : A -> B -> C) (b : B) (a : A) :=\n  f a b.\n\nDefinition impl_1 (i : list move) :=\n  let (p,seen) := (fold_left (flip step) i ((0,0),[(0,0)],[(0,0)])) in\n  length seen.\n\nExample test1 : impl_1 test_in = 13%nat. Proof. vm_compute. reflexivity. Qed.\n\nCompute (impl_1 input).\n\nDefinition impl_2 (i : list move) :=\n  let (p,seen) := (fold_left (flip step) i ((0,0),[(0,0);(0,0);(0,0);(0,0);(0,0);(0,0);(0,0);(0,0);(0,0)],[(0,0)])) in\n  length seen.\n\nExample test2 : impl_2 test_in = 1%nat. Proof. vm_compute. reflexivity. Qed.\n\nCompute (impl_2 input).", "meta": {"author": "MarcusVoelker", "repo": "AoC2022", "sha": "33f67bc9a0df5354bf111c3247f87375ee6399e3", "save_path": "github-repos/coq/MarcusVoelker-AoC2022", "path": "github-repos/coq/MarcusVoelker-AoC2022/AoC2022-33f67bc9a0df5354bf111c3247f87375ee6399e3/Day9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2538861868256171}}
{"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_UnSeal.\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  (* Proving the meaning of unsealing in the LR sane. Note the use of the later in the result. *)\n  Lemma unsealing_preserves_interp sb p0 b0 e0 a0:\n        permit_unseal p0 = true →\n        withinBounds b0 e0 a0 = true →\n        fixpoint interp1 (WSealed a0 sb) -∗\n        fixpoint interp1 (WSealRange p0 b0 e0 a0) -∗\n        ▷ fixpoint interp1 (WSealable sb).\n  Proof.\n    iIntros (Hpseal Hwb) \"#HVsd #HVsr\".\n    rewrite (fixpoint_interp1_eq (WSealRange _ _ _ _)) (fixpoint_interp1_eq (WSealed _ _)) /= Hpseal /interp_sb.\n    iDestruct \"HVsr\" as \"[_ Hss]\".\n    apply seq_between_dist_Some in Hwb.\n    iDestruct (big_sepL_delete with \"Hss\") as \"[HSa0 _]\"; eauto.\n    iDestruct \"HSa0\" as (P) \"[HsealP HWcond]\".\n    iDestruct \"HVsd\" as (P') \"[% [HsealP' HP']]\".\n    iDestruct (seal_pred_agree with \"HsealP HsealP'\") as \"Hequiv\". iSpecialize (\"Hequiv\" $! (WSealable sb)).\n    iAssert (▷ P (WSealable sb))%I as \"HP\". { iNext. by iRewrite \"Hequiv\". }\n    by iApply \"HWcond\".\n  Qed.\n\n  Lemma unseal_case (r : leibnizO Reg) (p : Perm)\n        (b e a : Addr) (w : Word) (dst r1 r2 : RegName) (P:D):\n    ftlr_instr r p b e a w (UnSeal 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_UnSeal 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 [ * Hr1 Hr2 Hunseal Hwb HincrPC | ].\n    { apply incrementPC_Some_inv in HincrPC as (p''&b''&e''&a''& ? & HPC & Z & Hregs') .\n\n      assert (r1 ≠ PC) as Hne1.\n      { destruct (decide (PC = r1)); last auto. simplify_map_eq; auto. }\n      rewrite lookup_insert_ne in Hr1; auto.\n      assert (r2 ≠ PC) as Hne2.\n      { destruct (decide (PC = r2)); last auto. simplify_map_eq; auto. }\n      rewrite lookup_insert_ne in Hr2; auto.\n\n      unshelve iDestruct (\"Hreg\" $! r1 _ _ Hr1) as \"HVsr\"; eauto.\n      unshelve iDestruct (\"Hreg\" $! r2 _ _ Hr2) as \"HVsd\"; eauto.\n      (* Generate interp instance before step, so we get rid of the later *)\n      iDestruct (unsealing_preserves_interp with \"HVsd HVsr\") as \"HVsb\"; auto.\n\n      iApply wp_pure_step_later; auto.\n      iMod (\"Hcls\" with \"[HP Ha]\");[iExists w;iFrame|iModIntro].\n      iNext; iIntros \"_\".\n\n      (* If PC=dst and perm of unsealed cap = E -> error! *)\n      destruct (decide (PC = dst ∧ p'' = E)) as [ [Herr1 Herr2] | HNoError].\n      { (* Error case *)\n        simplify_map_eq.\n        iDestruct ((big_sepM_delete _ _ PC) with \"Hmap\") as \"[HPC Hmap]\".\n        { subst. by rewrite lookup_insert. }\n        iApply (wp_bind (fill [SeqCtx])).\n        iApply (wp_notCorrectPC_perm with \"[HPC]\"); eauto. split; auto.\n        iIntros \"!> _\".\n        iApply wp_pure_step_later; auto.\n        iNext; iIntros \"_\".\n        iApply wp_value.\n        iIntros (a1); inversion a1.\n      }\n      (* Otherwise, we will be able to derive validity of the PC below*)\n\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 in Hvs; inversion Hvs. auto. }\n        { repeat (rewrite lookup_insert_ne in Hvs); auto.\n          iApply \"Hreg\"; auto. } }\n        { subst regs'. rewrite insert_insert. iApply \"Hmap\". }\n      iModIntro.\n      destruct (reg_eq_dec PC dst) as [Heq | Hne]; simplify_map_eq.\n      - iApply (interp_weakening with \"IH HVsb\"); auto; try solve_addr. (* HNoError used here *)\n        { by rewrite PermFlowsToReflexive. }\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/UnSeal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.2538861868256171}}
{"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 Simple C11 *)\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 I := unknown_set \"I\".\nDefinition REL := unknown_set \"REL\".\nDefinition SC := unknown_set \"SC\".\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 CACQ := ACQ ⊔ (SC ⊓ R ⊔ ACQ_REL).\nDefinition CREL := REL ⊔ (SC ⊓ W ⊔ ACQ_REL).\nDefinition Access := R ⊔ W.\nDefinition a_id := toid A.\nDefinition rmw_id := toid RMW.\nDefinition crel_id := toid CREL.\nDefinition cacq_id := toid CACQ.\nDefinition sc_id := toid SC.\nDefinition asw := [I] ⋅ top ⋅ [(M ⊓ !I)].\nDefinition A_0 := ((*failed: try X with emptyset_0*) emptyset_0) ⊔ ((*successful: try A with emptyset_0*) A).\nDefinition P := M ⊓ !A_0.\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_0] ⋅ top ⋅ [A_0].\nDefinition AP r := r ⊓ [A_0] ⋅ top ⋅ [P].\nDefinition PA r := r ⊓ [P] ⋅ top ⋅ [A_0].\nDefinition PP r := r ⊓ [P] ⋅ top ⋅ [P].\nDefinition AM r := r ⊓ [A_0] ⋅ top ⋅ [M].\nDefinition MA r := r ⊓ [M] ⋅ top ⋅ [A_0].\nDefinition noid r : relation events := r ⊓ !id.\nDefinition atom := [A_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 rsElem := coi ⊔ co ⋅ rmw_id.\nDefinition breakRseq := co ⊓ !rsElem.\nDefinition rseq := id ⊔ rsElem ⊓ !(breakRseq ⋅ co).\nDefinition fence_id := toid F.\nDefinition fid := fence_id ⋅ po ⊔ 1.\nDefinition idf := po ⋅ fence_id ⊔ 1.\nDefinition sw := ext ⊓ crel_id ⋅ (fid ⋅ (rseq ⋅ (rf ⋅ (a_id ⋅ (idf ⋅ cacq_id))))).\nDefinition Y := po.\nDefinition hb := (po ⊔ (asw ⊔ sw))^+.\nDefinition hb_loc := hb ⊓ loc.\nDefinition scp := hb ⊔ co.\nDefinition ConsSC := acyclic scp.\nVariable S : relation events.\nDefinition rfNA := rf ⊓ !AA rf.\nDefinition ConsRFna := is_empty (rfNA ⊓ !hb_loc).\nDefinition S_loc := MM S ⊓ loc.\nDefinition minWRSC := let aux := WR S_loc in aux ⊓ !(WW S_loc ⋅ aux).\nDefinition rfSCSC := sc_id ⋅ (rf ⋅ sc_id).\nDefinition rfXSC := rf ⋅ sc_id ⊓ !rfSCSC.\nDefinition X := hb ⋅ minWRSC.\nDefinition badRFSC := rfSCSC ⊓ !minWRSC ⊔ rfXSC ⊓ hb ⋅ minWRSC.\nDefinition SCReads := is_empty badRFSC.\nDefinition IrrHB := irreflexive hb.\nDefinition chapo := rf ⊔ (fr ⊔ (co ⊔ (co ⋅ rf ⊔ fr ⋅ rf))).\nDefinition Coh := acyclic (hb_loc ⊔ chapo).\nDefinition cosucc := co ⊓ !(co ⋅ co).\nDefinition AtRMW := is_empty (rf ⋅ rmw_id ⊓ !cosucc).\nDefinition locSomeW := loc ⊓ !RR loc.\nDefinition dr := let r1 := locSomeW ⊓ ext in let r2 := r1 ⊓ !AA r1 in r2 ⊓ !(hb ⊔ hb°).\nDefinition dataRace := is_empty dr.\nDefinition ur := let r1 := locSomeW ⊓ int in let r2 := noid r1 in r2 ⊓ !(po ⊔ po°).\nDefinition unsequencedRace := not (is_empty ur).\nDefinition witness_conditions := generate_cos cobase co /\\ linearisations SC scp S.\nDefinition model_conditions := ConsSC /\\ (ConsRFna /\\ (SCReads /\\ (IrrHB /\\ (Coh /\\ (AtRMW /\\ (dataRace /\\ unsequencedRace)))))).\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 I REL SC tag2events emptyset_0 partition tag2instrs po_loc rfe rfi co0 toid fencerel ctrlcfence imply nodetour singlestep LKW CACQ CREL Access a_id rmw_id crel_id cacq_id sc_id asw A_0 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 rsElem breakRseq rseq fence_id fid idf sw Y hb hb_loc scp ConsSC rfNA ConsRFna S_loc minWRSC rfSCSC rfXSC X badRFSC SCReads IrrHB chapo Coh cosucc AtRMW locSomeW dr dataRace ur unsequencedRace witness_conditions model_conditions : cat.\n\nDefinition valid (c : candidate) :=\n  exists co S : relation (events c),\n    witness_conditions c co S /\\\n    model_conditions c co S.\n\n(* End of translation of model Simple C11 *)\n", "meta": {"author": "jmadiot", "repo": "cats", "sha": "d3d6cae610dbd41c8a00d8cbdc0374cb02d6de95", "save_path": "github-repos/coq/jmadiot-cats", "path": "github-repos/coq/jmadiot-cats/cats-d3d6cae610dbd41c8a00d8cbdc0374cb02d6de95/models/simple_c11.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.253886180316285}}
{"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\nFrom QArithSternBrocot Require Export quadratic_correctness.\nFrom Coq Require Import Eqdep_dec.\nImport Field_Theory_Q.\n\n\nLemma Qopp_lazy_Qopp : forall x : Q, Qopp_lazy x = Qopp x.\nProof.\n intros x.\n unfold Qopp_lazy in |- *.\n rewrite homography.\n unfold spec_h in |- *.\n replace (Z_to_Q 1) with Qone; trivial.\n replace (Z_to_Q (-1)) with (Qopp Qone); trivial.\n unfold Z_to_Q in |- *.\n rewrite Qmult_Qopp_left.\n rewrite Qmult_zero.\n rewrite Qplus_zero_right.\n rewrite Qplus_zero_left.\n rewrite Qmult_one_right.\n rewrite Qmult_one_left.\n reflexivity.\nDefined.\n\n\nLemma Qinv_lazy_Qinv :\n forall (x : Q) (Hx : x <> Zero), Qinv_lazy x Hx = Qinv x.\nProof.\n intros x Hx.\n unfold Qinv_lazy in |- *.\n rewrite homography.\n unfold spec_h in |- *.\n replace (Z_to_Q 1) with Qone; trivial.\n unfold Z_to_Q in |- *.\n repeat rewrite Qmult_one_left.\n rewrite Qplus_zero_right.\n reflexivity.\nDefined.\n\n\nLemma Qplus_lazy_Qplus : forall x y : Q, Qplus_lazy x y = Qplus x y.\nProof.\n intros x y.\n unfold Qplus_lazy in |- *.\n rewrite quadratic.\n unfold spec_q in |- *.\n replace (Z_to_Q 1) with Qone; trivial.\n unfold Z_to_Q in |- *.\n repeat rewrite Qmult_one_left.\n rewrite Qmult_one_right.\n repeat rewrite Qmult_zero.\n rewrite Qplus_zero_left.\n rewrite Qplus_zero_right.\n reflexivity.\nDefined.\n\nLemma Qminus_lazy_Qminus : forall x y : Q, Qminus_lazy x y = Qminus x y.\nintros x y.\nunfold Qminus_lazy in |- *.\nrewrite quadratic in |- *.\nunfold spec_q in |- *.\nchange (Z_to_Q 1) with Qone in |- *.\nunfold Z_to_Q in |- *.\nsimpl Qpositive_c in |- *.\nfield.\ndiscriminate.\nDefined.\n\nLemma Qmult_lazy_Qmult : forall x y : Q, Qmult_lazy x y = Qmult x y.\nProof.\n intros x y.\n unfold Qmult_lazy in |- *.\n rewrite quadratic.\n unfold spec_q in |- *.\n change (Z_to_Q 1) with Qone.\n unfold Z_to_Q in |- *.\n rewrite Qmult_one_left.\n rewrite Qmult_one_right.\n repeat rewrite Qmult_zero.\n repeat rewrite Qplus_zero_right.\n repeat rewrite Qplus_zero_left.\n reflexivity.\nDefined.\n\nLemma Qdiv_lazy_Qdiv :\n  forall (x y : Q) (Hy : y <> Zero), Qdiv_lazy x y Hy = Qdiv x y.\nintros x y Hy.\nunfold Qdiv_lazy in |- *.\nrewrite quadratic in |- *.\nunfold spec_q in |- *.\nchange (Z_to_Q 1) with Qone in |- *.\nunfold Z_to_Q in |- *.\nfield.\ntrivial.\nDefined.\n\nLemma second_Q_Ring_Theory :\n ring_theory Zero Qone Qplus_lazy Qmult_lazy Qminus_lazy Qopp_lazy (eq(A:=Q)).\n  split; intros n m p || intros n m || intros n;\n  repeat rewrite Qplus_lazy_Qplus;\n  repeat rewrite Qmult_lazy_Qmult;\n  repeat rewrite Qminus_lazy_Qminus;\n  repeat rewrite Qdiv_lazy_Qdiv;\n  repeat rewrite Qopp_lazy_Qopp;\n  repeat rewrite Qinv_lazy_Qinv;\n try first\n      [ apply Qplus_sym\n      | apply Qplus_assoc\n      | apply Qmult_sym\n      | apply Qmult_assoc\n      | apply Qplus_zero_left\n      | apply Qmult_one_left\n      | apply Q_opp_def\n      | apply Q_distr_left\n      | reflexivity ].\nDefined.\n\n(** If we want to use the Field tactic , the multiplicative inverse\nshould be total. We make our [Qinv_lazy] a total function by\noutputting a dummy variable (Zero) whenever the denominator is\nzero. Note that we can not do this in the case of real numbers (being\nZero is undecidable) but for rational numbers there is no problem *)\nDefinition total_Qinv_lazy (x : Q) :=\n  match Q_zerop x with\n  | left _ => Zero\n  | right h => Qinv_lazy x h\n  end.\n\nLemma Qinv_lazy_defT :\n forall (n : Q) (Hn : n <> Zero), Qmult_lazy (Qinv_lazy n Hn) n = Qone.\nProof.\n intros n Hn; rewrite Qinv_lazy_Qinv; rewrite Qmult_lazy_Qmult; \n  rewrite Qmult_sym; apply Qinv_def; intro; apply Hn; \n  assumption.\nDefined.\n\nLemma total_Qinv_lazy_defT :\n forall n : Q, n <> Zero -> Qmult_lazy (total_Qinv_lazy n) n = Qone.\nProof.\n intros n Hn.\n unfold total_Qinv_lazy in |- *; case (Q_zerop n); intros Hn';\n  [ Falsum\n  | apply Qinv_lazy_defT ].\nDefined.\n\nDefinition total_Qdiv_lazy (x y : Q) :=\n  match Q_zerop y with\n  | left _ => Zero\n  | right h => Qdiv_lazy x y h\n  end.\n\n\nLemma second_QField :\n  field_theory Zero Qone Qplus_lazy Qmult_lazy Qminus_lazy\n    Qopp_lazy total_Qdiv_lazy total_Qinv_lazy (eq(A:=Q)).\nconstructor.\n apply second_Q_Ring_Theory.\n discriminate.\n intros; unfold total_Qdiv_lazy, total_Qinv_lazy in |- *.\n  destruct (Q_zerop q).\n   rewrite Qmult_lazy_Qmult in |- *.\n   ring.\n   rewrite Qdiv_lazy_Qdiv in |- *; rewrite Qmult_lazy_Qmult in |- *;\n     rewrite Qinv_lazy_Qinv in |- *; reflexivity.\n exact total_Qinv_lazy_defT.\nDefined.\n\nAdd Field second_Qfield : second_QField\n  (decidable Q_eq_prop, constants [Qcst]).\n\nDefinition not_eq2eqT (A : Type) (x y : A) (H1 : x <> y) : \n  x <> y := fun H2 : x = y => H1 H2.\n", "meta": {"author": "coq-community", "repo": "qarith-stern-brocot", "sha": "a36a01526e76f4ef92bc87445da33dfb025e2db4", "save_path": "github-repos/coq/coq-community-qarith-stern-brocot", "path": "github-repos/coq/coq-community-qarith-stern-brocot/qarith-stern-brocot-a36a01526e76f4ef92bc87445da33dfb025e2db4/theories/second_Field_Theory_Q.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.25385945003154614}}
{"text": "Require Import ExtLib.Tactics.\nRequire Import MirrorCore.RTac.Core.\nRequire Import MirrorCore.RTac.IsSolved.\n\nRequire Import MirrorCore.Util.Forwardy.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nSection parameterized.\n  Context {typ : Set}.\n  Context {expr : Set}.\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  Definition SOLVE (tac : rtac typ expr) : rtac typ expr :=\n    fun ctx s g =>\n      match is_solved (tac ctx s g) with\n      | Some s => Solved s\n      | _ => Fail\n      end.\n\n  Theorem SOLVE_sound\n  : forall tac, rtac_sound tac -> rtac_sound (SOLVE tac).\n  Proof.\n    unfold SOLVE, rtac_sound.\n    intros.\n    specialize (H ctx s g).\n    destruct (is_solved (tac ctx s g)) eqn:?; subst; try apply rtac_spec_Fail.\n    eapply is_solved_sound in Heqo.\n    eapply Proper_rtac_spec_impl.\n    { reflexivity. }\n    { eapply Heqo. }\n    { eapply H. reflexivity. }\n  Qed.\n\n  Fixpoint SOLVES (tacs : list (rtac typ expr)) : rtac typ expr :=\n    match tacs with\n    | nil => fun ctx s g => Fail\n    | tac :: tacs =>\n      let rec := SOLVES tacs in\n      fun ctx s g =>\n        match is_solved (tac ctx s g) with\n        | Some s => Solved s\n        | _ => rec ctx s g\n        end\n    end.\n\n  Theorem SOLVES_sound\n  : forall tacs, Forall rtac_sound tacs -> rtac_sound (SOLVES tacs).\n  Proof.\n    induction 1; simpl.\n    { red. intros; subst. eapply rtac_spec_Fail. }\n    { red.\n      intros.\n      destruct (is_solved (x ctx s g)) eqn:?; subst; eauto.\n      eapply is_solved_sound in Heqo.\n      eapply Proper_rtac_spec_impl.\n      { reflexivity. }\n      { eapply Heqo. }\n      { eapply H. reflexivity. } }\n  Qed.\n\nEnd parameterized.\n\nArguments SOLVE {_ _} _%rtac _ _ _.\nArguments SOLVES {_ _} _%or_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/Solve.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.25385945003154614}}
{"text": "Require Import FloydSeq.base2.\nRequire Import FloydSeq.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": "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/proj_reptype_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2538392343246956}}
{"text": "(* Distributed under the terms of the MIT license. *)\nFrom MetaCoq.Utils Require Import utils MCUtils.\nFrom MetaCoq.Common Require Import config.\nFrom MetaCoq.PCUIC Require Import PCUICAst PCUICAstUtils\n  PCUICEquality PCUICContextSubst PCUICUnivSubst PCUICCases\n  PCUICReduction PCUICCumulativity PCUICTyping PCUICGuardCondition\n  PCUICWeakeningConfig PCUICWeakeningConfigConv.\nFrom Equations Require Import Equations.\n\nRequire Import ssreflect.\n\nSet Default Goal Selector \"!\".\nImplicit Types (cf : checker_flags).\n\nLocal Ltac constructor_per_goal' _ :=\n  let n := numgoals in\n  [ > .. | econstructor n; shelve ];\n  gtry (constructor_per_goal' ()).\nLocal Ltac constructor_per_goal _ :=\n  unshelve constructor_per_goal' (); shelve_unifiable.\n\nLemma weakening_config_wf_local_sized {cf1 cf2 : checker_flags} Σ Γ\n  (Hwf : match cf1 with _ => wf_local Σ Γ end)\n  (IH : forall Γ0 t0 T0 (H0 : @typing cf1 Σ Γ0 t0 T0),\n      typing_size H0 < S (All_local_env_size (fun _ _ _ _ H => typing_size H) Σ Γ Hwf)\n      -> @typing cf2 Σ Γ0 t0 T0)\n  : match cf2 with _ => wf_local Σ Γ end.\nProof.\n  simpl in *.\n  induction Hwf; [ constructor 1 | constructor 2 | constructor 3 ].\n  all: try assumption.\n  all: unfold lift_typing, lift_judgment, infer_sort in *.\n  all: rdest.\n  all: simpl in *.\n  all: try (unshelve eapply IH; [ eassumption | ];\n            try solve [ constructor; simpl in *; cbn in *; lia ]).\n  all: repeat (exactly_once (idtac; multimatch goal with H : _ |- _ => unshelve eapply H; [ try eassumption .. | intros; simpl in * ]; clear H end)).\n  all: try (cbn; lia).\nQed.\n\nLemma weakening_config {cf1 cf2} Σ Γ t T :\n  config.impl cf1 cf2 ->\n  @typing cf1 Σ Γ t T ->\n  @typing cf2 Σ Γ t T.\nProof.\n  intros Hcf H.\n  pose proof (@Fix_F { Σ & { Γ & { t & { T & @typing cf1 Σ Γ t T }}}}) as p0.\n  specialize (p0 (PCUICUtils.dlexprod (precompose lt (fun Σ => globenv_size (fst Σ)))\n                    (fun Σ => precompose lt (fun x => typing_size x.π2.π2.π2)))) as p.\n  try clear p0.\n  set (foo := (Σ; Γ; t; _; H) : { Σ & { Γ & { t & { T & Σ ;;; Γ |- t : T }}}}).\n  change Σ with foo.π1.\n  change Γ with foo.π2.π1.\n  change t with foo.π2.π2.π1.\n  change T with foo.π2.π2.π2.π1.\n  change H with foo.π2.π2.π2.π2.\n  revert foo.\n  match goal with\n    |- let foo := _ in @?P foo => specialize (p (fun x => P x))\n  end.\n  forward p; [ | apply p; apply PCUICUtils.wf_dlexprod; intros; apply wf_precompose; apply lt_wf].\n  clear p.\n  clear Σ Γ t T H.\n  intros (Σ & Γ & t & T & H). simpl.\n  intros IH. specialize (fun Σ Γ t T H => IH (Σ; Γ; t; T; H)). simpl in IH.\n  destruct H; constructor_per_goal (); try eassumption.\n  all: try (unshelve eapply IH; [ eassumption .. | ];\n            try solve [ constructor; simpl; lia ]).\n  all: try (eapply (@weakening_config_cumulSpec cf1 cf2); eassumption).\n  all: try now constructor; simpl; repeat destruct ?; simpl; lia.\n  all: specialize (fun Γ t T H H' => IH _ Γ t T H ltac:(right; exact H')).\n  all: simpl in IH.\n  all: try (set (k := fix_context _) in *; clearbody k).\n  all: match goal with\n       | [ H : All (fun d => ∑ s : ?S, _) ?l |- All (fun d => ∑ s' : ?S, _) ?l ]\n         => is_var l; clear -H IH; induction H as [|???? IH']; constructor\n       | [ H : All (fun d => _ ;;; _ |- _ : _) ?l |- All (fun d => _ ;;; _ |- _ : _) ?l ]\n         => is_var l; clear -H IH; induction H as [|???? IH']; constructor\n       | [ H : case_side_conditions _ _ _ _ _ _ _ _ _ _ _ |- case_side_conditions _ _ _ _ _ _ _ _ _ _ _ ] => destruct H; constructor\n       | [ H : case_branch_typing _ _ _ _ _ _ _ _ _ _ _ |- case_branch_typing _ _ _ _ _ _ _ _ _ _ _ ] => destruct H; constructor\n       | _ => idtac\n       end.\n  all: unfold wf_branches in *.\n  all: repeat match goal with H : All _ (_ :: _) |- _ => depelim H end.\n  all: rdest.\n  all: try (unshelve eapply IH'; clear IH'; auto; [];\n            intros;\n            unshelve eapply IH; [ eassumption .. | simpl; lia ]).\n  all: try (unshelve eapply IH; [ eassumption .. | simpl; lia ]).\n  all: try now eapply (@weakening_config_consistent_instance cf1 cf2); eassumption.\n  all: try now eapply (@weakening_config_is_allowed_elimination cf1 cf2); eassumption.\n  all: try now repeat destruct ?; subst; simpl in *; assumption.\n  all: repeat destruct ?; subst.\n  all: lazymatch goal with\n       | [ H : ctx_inst _ _ _ _ _ |- ctx_inst _ _ _ _ _ ]\n         => revert dependent H;\n            repeat match goal with\n              | [ |- context[typing_size ?x] ]\n                => generalize (typing_size x); clear x; intro\n              end;\n            intro H; intros;\n            induction H; constructor_per_goal ()\n       | [ H : All2i _ _ ?x ?y |- All2i _ _ ?x ?y ]\n         => induction H; constructor_per_goal (); cbv zeta in *\n       | _ => idtac\n       end.\n  all: repeat rdest; try assumption.\n  all: repeat (exactly_once (idtac; multimatch goal with H : _ |- _ => unshelve eapply H; [ try eassumption .. | intros; simpl ctx_inst_size in *; simpl branches_size in * ]; clear H end)).\n  all: lazymatch goal with\n       | [ |- _ < _ ] => lia || (simpl; lia)\n       | _ => idtac\n       end.\n  all: repeat match goal with H : Forall2 _ (_ :: _) (_ :: _) |- _ => depelim H end.\n  all: try assumption.\n  all: [ > unshelve eapply (@weakening_config_wf_local_sized cf1 cf2); [ eassumption | ] .. ].\n  all: intros; unshelve eapply IH; [ eassumption | ].\n  all: simpl in *; try lia.\n  all: cbn in *; try lia.\n  all: try assumption.\n  all: repeat match goal with\n         | [ |- context[All_local_env_size ?x ?y ?z ?w] ]\n           => let v := fresh in\n              set (v := All_local_env_size _ y z w) in *\n         end.\n  all: try lia.\nQed.\n\nLemma weakening_config_wf_local {cf1 cf2 : checker_flags} Σ Γ :\n  config.impl cf1 cf2\n  -> match cf1 with _ => wf_local Σ Γ end\n  -> match cf2 with _ => wf_local Σ Γ end.\nProof.\n  intros Hcf H; eapply All_local_env_impl; [ eassumption | ].\n  intros * H'; eapply lift_typing_impl; [ eassumption | ].\n  intros *; eapply (@weakening_config cf1 cf2); assumption.\nQed.\n\nLemma weakening_config_wf {cf1 cf2 : checker_flags} Σ :\n  config.impl cf1 cf2\n  -> @wf cf1 Σ\n  -> @wf cf2 Σ.\nProof.\n  rewrite /wf/Forall_decls_typing.\n  intros; eapply (@on_global_env_impl_config cf1 cf2); try eassumption.\n  { intros; eapply @lift_typing_impl; [ eassumption | ].\n    intros; eapply (@weakening_config cf1 cf2); eassumption. }\n  { intros; eapply (@weakening_config_cumulSpec0 cf1 cf2); eassumption. }\nQed.\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/Typing/PCUICWeakeningConfigTyp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2537820050602248}}
{"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_granule_undelegate_spec (addr: Z64) (adt: RData) : option (RData * Z64) :=\n    match addr with\n    | VZ64 addr =>\n      rely Z.land (r_scr_el3 (cpu_regs (priv adt))) SCR_WORLD_MASK =? SCR_REALM_WORLD;\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        rely prop_dec ((gpt_lk (share adt)) @ gidx = None);\n        rely prop_dec ((gpt (share adt)) @ gidx = true);\n        if g_tag (ginfo gn) =? GRANULE_STATE_DELEGATED then\n          rely prop_dec (gtype gn = GRANULE_STATE_DELEGATED);\n          let e := EVT CPU_ID (ACQ gidx) in\n          let e1 := EVT CPU_ID (ACQ_GPT gidx) in\n          let e2 := EVT CPU_ID (REL_GPT gidx false) in\n          let g' := gn {ginfo: (ginfo gn) {g_tag: GRANULE_STATE_NS}} 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' {glock: Some CPU_ID})) in\n          Some (adt {log: e' :: e2 :: e1 :: e :: (log adt)}\n                    {share: (share adt) {gs: (gs (share adt)) # gidx == (g' {gtype: GRANULE_STATE_NS})}\n                                        {gpt: (gpt (share adt)) # gidx == false}}\n                    {priv: (priv adt) {cpu_regs: regs'}},\n                VZ64 0)\n        else\n          let e := EVT CPU_ID (ACQ gidx) in\n          let e' := EVT CPU_ID (REL gidx (gn {glock: Some CPU_ID})) in\n          Some (adt {log: e' :: e :: (log adt)}, VZ64 1)\n      else Some (adt, VZ64 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/RmiSMC/Specs/smc_granule_undelegate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2537354682758416}}
{"text": "Require Import BenB.\nRequire Import BenB2.\n\n(* ====================================================================== *)\n\n(* \n   Title: \n   ======\n   Authors:\n   Mart Brennenraedts, s1078038\n   Daan Weessies, s1063758\n   Wessel van der Lans, s1084461\n   Mees Ephraim, s1085936\n*)\n\n(* ====================================================================== *)\n\n(*\n   [\n     This file has to be a valid script, meaning that it\n     can be executed by Coq.\n     Therefore, explanations in natural language have to be between\n     comment markers.\n\n     In this project template, text within square brackets (within\n     comment markers) is intended to clarify what needs to be \n     written where.\n\n     In the final version, we expect that all these blocks have been\n     replaced by (your) proper content.\n   ]\n   \n*)\n\n(*\n   Abstract:\n   =========\n   [\n     Explain whether you managed to prove the correctness theorem.\n     And how did that go: did you have to change a lot compared to\n     the original model as it was before you started with the proof,\n     or could you use your formalization without many modifications?\n   ]\n\n*)\n\n(*\n   Focus:\n\n   Modeling Goal:\n   ==============\n   Verification model \n\n\n   Fragment of reality:\n   ====================\n\n\n ____ ___ ____   _____ ____  _____ ____  _   _   ________  _   _ _____ \n| __ )_ _/ ___| |  ___|  _ \\| ____/ ___|| | | | |__  / _ \\| \\ | | ____|\n|  _ \\| | |  _  | |_  | |_) |  _| \\___ \\| |_| |   / / | | |  \\| |  _|  \n| |_) | | |_| | |  _| |  _ <| |___ ___) |  _  |  / /| |_| | |\\  | |___ \n|____/___\\____| |_|   |_| \\_\\_____|____/|_| |_| /____\\___/|_| \\_|_____|\n\n/%%&&&&&&&&&%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%###############((((/////****\n(&&&&&&&&&&%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&&&&&&&&&\n(&&&&&&&&&&&%%%%%%%%%%%%%%%%%%%%%%%%%%%%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/%%((&&&\n(&&&&&&&&&&&%%%%%%%%%%%%%%%%%%%%%%%%%%%%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&&&&&&&&&\n(&&&&&&&&&&&%&&%%%%%%%%%%%%%%%%%%%%%%%%%@%%%%%%%%%%%%%%&&&&&&&&&&&&&&&@@@@@@&&&&\n(&&&/**/(%&&&&&%%%%%%%%%%%%%%%%%%%%%%%%%@%%%%%%%#((((((((((####(########@@@@&&&&\n(&&&%*/.@%&&&&%%%%%%%%%%%%%%%%%%%%%%%%%%@%%%%%%%(..... . ...............@@@@&&&&\n(&&&*,*(.%&&&&%%%%%%%%%%%%%%%%%%%%%%%%%%@%%%%%%%(...,*****,,,,,,*****,*.&@@@&&&&\n(&&&&&&&&&&&&&%%%%%%%%%%%%%%%%%%%%%%%%%%@%%%%%%%/....................,,.&@@@&&&&\n(&&&&&&&&&&&&&&%%%%%%%%%%%%%%%%%%%%%%%%%@%%%%%%%/.,,      . ....      ..&@@@&&&&\n(&&&&&&&&&&&&&&%%%%%%%%%%%%%%%%%%%%%%%%%@%%%%%%%(,.........,...,.,,,,,,,@@@@&&&&\n(&&&&&&&&&&&&&&%%%%%%%%%%%%%%%%%%%%%%%%%@%%%%%%%%*,,,,,***,,,,,,*****,,,@@@@&&&&\n(&&&&&&&&&&&&&&&%&%%%%%%%%%%%%%%%%%%%%%%@%%%%%%%/      .................@@@@&&&&\n(&&&&&&&&&&&&&&&%&&%%%%%%%%%%%%%%%%%%%%%@%%%%%%%/    ...................&@@@&&&&\n(&&&&&&&&&&&&&&&%%%%%%%%%%%%%%%%%%%%%%%%@%%%%%%%/   ...  ...,......,,,..&@@@&&&&\n(&&&&&&&&&&&&&&&%%%%%%%%%%%%%%%%%%%%%%%%@%%%%%%%/ .**,**,.*/,,**.,/*,*/,@@@@&&&&\n(&&&&&&&&&&&&&&%%%%%%%%%%%%%%%%%%%%%%%%%@%%%%%%%/,,**,//*/**,,//.,/**//*&@@@&&&&\n(&&&&&&&&&&&&&&&%%%%%%%%%%%%%%%%%%%%%%%%@%%%%%%%/............... .,....,@@@@&&&&\n(&&&&&&&&&&&&&&&%%%%%%%%%%%%%%%%%%%%%%%%@%%%%%%%/.............., .,....,@@@@&&&&\n(&&&&&&&&&&&&&&&%%%%%%%%%%%%%%%%%%%%%%%%@%%%%%%%/ ......,......, .,....,@@@@&&&&\n(&&&&&&&&&%%%%%%%%(##%########%%%%%%%%%%@%%%%%%%(,,..,,,,,,,,,,,,,,,,*,,@@@@&&&&\n(&&&&&&&@@%%%%%%%%%%%%%#######%@@%%%%%%%@%%%%%%%(... .  .,.............,&@@@&&&&\n(&&&&&&&@@%#%%%%%%%%%%########%@@%%%%%%%@%%%%%%%#,..    .,.....,..,,,..,&@@@&&&&\n(&&&&&&&@@%%%%%%%%%%%%#####((#&@@%%%%%%%@%%%%%%%#/  .....,,. ..,..,,  ..@@@@&&&&\n(&&&&&&&@@@@@@&&%%%%%%%%%&%%&&&@@%%%%%%%@%%%%%%%(........ ,....,..,,,...@@@@&&&&\n(&&&&&&&@@@@@&&&&%%%%%%%&&%%&&&@@%%%%%%%@%%%%%%%#**,,////(,[*[***//[**[*&@@@&&&&\n(&&&&&&&@@@@@&&&&#(/////&&&%%@@@@%%%%%%%@%%%%%%%((/,**/(###///(//*//(/#(@@@@&&&\n(&&&&&&&@@@@@&&%%%&&&&&&%&%%%@@@@%%%%%%%@%%%%%%%#*, .****/[*,**[*/*[*.*/@@@@&&&&\n(&&&&&&&@@@@@&&%%%%%%%%%%&%%%&&&&%%%%%%%@%%%%%%%[*. ,,/,/**,..,**/*/,..*@@@@&&&&\n(&&&&&&&@@@@@&&%%%%%%%%%%%%%#&&&&%%%%%%%@%%%%%%%#*. ,,*.//*,..,/.*//,..*@@@@&&&&\n(&&&&&&&@@@@@%%%%%&&%%%%&%%%#&&&&%%%%%%%@%%%%%%%#*. ,,*,//,. .,/.*//,..*@@@@&&&&\n(&&&&&&&@@@@@&%%%%%%%%%%%%%%#&&&&%%%%%%%@%%%%%%%(                       @@@@&&&&\n(&&&&&&&@@@@@&%%%%%%%%%%%%%%#&&&&%%%%%%%@%%%%%%%%%%%%&&&&&&&&&&&&&@@@@@@@@@@&&&&\n(&&&&&&&@@@@@&%%%%%%%%%%%%%%#&&&&%%%%%%%@%%%%%%%%%%%%&&&&&&&&&&&&&&@@@@@@@@@&&&&\n(&&&&&&&@@&&@&&&&&&&&&&&&&&&%&&&&%%%%%%%@%%%%%%%#%%%%%%%%%%%%%%%%%%%%&&&&&&&&&&&\n(&&&&&&&&&&&&&&&&&&&&&%%%%%%%%%%%%%%%%%%@%%%%%%%%%%%%%%%%&&&&&&&&&&&&&&&&&%&&&&&\n &%@@#&&@&%&&@@@@@@@@@@@@@@@@@@@@@@@@@@@@%##&@@@@@@@@@@@@@@@@@@@@@@&@&%&&@@@&&#%\n(@&&#&&&&&&&&&&&&&&&&%%%&%&%%%%%%%%%%%%%@%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&&&&@#&&&\n(&&&###((((////****,,,,,,,..............@.............,,,,,,,*****///(((((##%&&&\n(&&&&&&&&&&&&&&&&&&&&&%%%%%%%%%%%%%%%%%%@%%%%%%%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&&&\n(&&&&&&&&&&&&&&&&&&&&&%%%%%%%%%%%%%%%%%%@%%%%%%%%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&&\n(&&&&&&&&&&&&&&&&&&&&&&&&%%%%%%%%%%%%%%%@%%%%%%%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&&&\n(&&&&&&&&&&&&&&&&&&&&&&%%%%%%%%%%%%%%%%%@%%%%%%%%%%%%%%%%%%%&&&%%%&&&&&&&&&&&&&&\n(&&&&&&&&&&&&&&&&&&&&&&&&%%%%%%%%%%%%%%%@%%%%%%%%%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&\n(&&&&&&&&&&&&&&&&&&&&&&&%%%%%%%%%%%%%%%%@%%%%%%%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&&&\n(&&&&&&&&&&&&&&&&&&&&&&&&%%%%%%%%%%%%%%%@%%%%%%%%%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&\n(&&&&&&&&&&&&&&&&&&&&&&&%%%%%%%%%%%%%%%%@%%%%%%%%%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&\n(&&&&&&&&&&&&&&&&&&&&&&&&&%%%%%%%%%%%%%%@%%%%%%%%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&&\n(&&&&&&&&&&&&&&&&&&&&&&%%%%%%%%%%%%%%%%%@%%%%%%%%%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&\n(&&&&&&&&&&&&&&&&&&&&&&&&&%%%%%%%%%%%%%%@%%%%%%%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&&&\n(&&&&&&&&&&&&&&&&&&&&&&&%&%%%%%%%%%%%%%%@%%%%%%%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&&&\n(&&&&&&&&&&&&&&&&&&&&&&&&&%%%%%%%%%%%%%%@%%%%%%%%%%%%%%%%%%%%%%&%&&%&&&&&&&&&&&&\n(@&&&&&&&&&&&&&&&&&&&&&&&&%%%%%%%%%%%%%%@%%%%%%%%%%%%%%%%%%%%%%&%&&&&&&&&&&&&&&&\n(&&&&&&&&&&&&&&&&&&&&&&&&&&&&&%%%%%%%%%&@%%%%%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&&&&&\n(&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&%%%%%%%%%@%%%%%%%%%%%%%%%%%%%%%&%%&&&&&&&&&&&&&&&\n(&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&%%%%%%%%@%%%%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&&&&&&\n(&&&&&&&&&&&&&&&&&&&&&&&&&&&&&%&%%%%%%%%@%%%%%%%%%%%%%%%%%%&%&%&&&&&&&&&&&&&&&&&\n(&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&%&&%%%%%@%%%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&&&&&&&\n(&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&@%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&&&&&&&&&\n(@&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&@%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&&&&&&&&&&\n(@&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&@%%%%%%%%%&&%&%%%&&&&&&&&&&&&&&&&&&&&&&&\n(@&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&@%%%%%%%%&%%&&%%&&&&&&&&&&&&&&&&&&&&&&&&\n(&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&@&&&&&&&%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n(&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&@&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n(&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&@&&&&%%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n(&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&@&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n(&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&@&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n(@&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n  @@@@                                                                    /@@@#\n\n\n\n\n\n                                                                                                                        \n\n\n  As accurately pictured above, the fragment of reality is an LG smart fridge. Even more accurate pictures can be found in \n  the pdf file.\n\n   \n\n   Perspective:\n   ============\n   We focus on the cooling of the food, the light in the fridge and the creation of ice.\n*)\n\n\n(*\n   Abstractions or simplifications:\n   ================================\n   [\n     Depending on the chosen focus, you may simplify certain aspects of\n     your artifact.\n     If you are modeling some kind of home automation system, it is not\n     unreasonable to assume that the net power is constant, although this\n     is not exactly the case in reality. However, if you are modeling an\n     artifact that protects against high peaks of power, these fluctuations\n     should be part of the model.\n\n     Write down explicitly which assumptions you have made to simplify\n     the artifact.\n   ]\n\n*)\n\n(* ====================================================================== *)\n\n(* Domain model *)\n\nDefinition Time := R.\n(* Time in seconds in reals*)\nDefinition Temp := R.\n(*meaning: temperature in degrees celcius in reals*)\nDefinition Food := Set.\n(* Set of all food *)\n\n\n(* Constants (including their meaning) *)\n\nDefinition MaximumFridgeTemp := 4.  \n(* The minimum temperature at which the FridgeTempSensor gives off the FridgeTempTooHigh signal *)\nDefinition MaximumFreezerTemp := -5.\n(* The minimum temperature at which the FreezerTempSensor gives off the FreezerTempTooHigh signal *)\n\n\n\n(* Functions *)\nVariable TimeToTemp: Time -> Temp. \n\n\n\n\n(* Predicates (including their meaning and measurements) *)\n\nVariable FoodPutInFreezer: Food -> Time -> Prop.\n(* meaning: food x is put in the freezer at time y *)\n(* measurement: look in the freezer *)\nVariable FoodPutInFridge: Food -> Time -> Prop.\n(* meaning: food x is put in the fridge at time y *)\n(* measurement : look in the fridge *)\nVariable FoodIsCool: Food -> Time -> Prop.\n(* meaning: the temperature of food x is within a margin of error of the MaximumFridgeTemp *)\n(* measurement: measure the food's temperature with a thermometer *)\nVariable FoodIsFrozen: Food -> Time -> Prop.\n(* meaning: the temperature of food x is within a margin of error of the MaximumFreezerTemp *)\n(* measurement: measure the food's temperature with a thermometer *)\n\n\n(* Inputs and outputs of the SmartFridge *)\n\nVariable PowerIn: Time -> Prop.\n(* power is supplied to the smartfridge's powersupply *)\nVariable FridgeDoorROpen: Time -> Prop.\n(* the right fridge door is opened *)\nVariable FridgeDoorLOpen: Time -> Prop.\n(* the left fridge door is opened *)\nVariable FreezerDoorROpen: Time -> Prop.\n(* the right freezer door is opened *)\nVariable FreezerDoorLOpen: Time -> Prop.\n(* the left freezer door is opened *)\nVariable ColdWater: Time -> Prop.\n(* cold water is dispensed by the dispenser *)\nVariable CubedIce: Time -> Prop.\n(* ice cubes are dispensed by the dispenser *)\nVariable CrushedIce: Time -> Prop.\n(* crushed ice is dispensed by the dispenser *)\nVariable WaterIn: Time -> Prop.\n(* water is supplied to the IceMakerTray and to the WaterCooler *)\nVariable FridgeLightOn: Time -> Prop.\n(* the light inside the fridge is emitting *)\nVariable WaterButtonIn: Time -> Prop.\n(* The option to receive cold water is selected on the ControlPanel *)\nVariable CrushedIceButtonIn: Time -> Prop.\n(* The option to receive crushed ice is selected on the ControlPanel *)\nVariable CubedIceButtonIn: Time -> Prop.\n(* The option to receive cubed ice is selected on the ControlPanel *)\n\n\n(* Internal components for the SmartFridge *)\n\nVariable Pow1: Time -> Prop.\n(* Power flows between the Powersupply and the FridgePowerHub *)\nVariable Pow2: Time -> Prop.\n(* Power flows between the Powersupply and the FreezerPowerHub *)\n\n\n(* Internal IceMaker variables *)\n\nVariable PowIceMakerTray: Time -> Prop.\n(* Power flows between the icemaker and the icemaker powerhub *)\nVariable ReservoirFull: Time -> Prop.\n(* The ice reservoir is full *)\nVariable PowIceReservoir: Time -> Prop.\n(* Power is flowing between the ice reservoir and the icemaker powerhub *)\nVariable CrushIce: Time -> Prop.\n(* There is ice that needs to be crushed *)\nVariable FillReservoir: Time -> Prop.\n(* There is room in the IceReservoir*)\nVariable DispenceIce: Time -> Prop.\n(* The dispenser requires ice *)\nVariable PowDispenser: Time -> Prop.\n(* Power is flowing between the IceMakerPowerHub and the Dispenser *)\nVariable PowIceCrusher: Time -> Prop.\n(* Power flows between the IceCrusher and the IceMakerPowerHub *)\nVariable DispenseWater: Time -> Prop.\n(* The dispenser requires ice from the WaterCooler *)\nVariable PowWaterCooler: Time -> Prop.\n(* Power flows between the WaterCooler and the IceMakerPowerHub *)\nVariable DispenseCrushedIce: Time -> Prop.\n(* The dispenser requires crushed ice *)\n\n\n(* FridgeDoorL variables *)\n\nVariable PowIceMaker: Time -> Prop.\n(* Power flows between the FridgeDoorLPowerHub and IceMaker *)\nVariable PowControlPanel: Time -> Prop.\n(* power is supplied to the ControlPanelPowerHub if and only if power is supplied to the FridgeDoorLPowerHub *)\nVariable ColdWaterSignal: Time -> Prop.\n(* WaterButton is being pressed *)\nVariable CrushedIceSignal: Time -> Prop.\n(* CrushedIceButton is being pressed *)\nVariable CubedIceSignal: Time -> Prop.\n(* CubedIceButton is being pressed *)\nVariable PowFridgeDoorSensorL: Time -> Prop.\n(* The Sensor in FridgeDoorL is supplied with power *)\n\n\n\n(* Internal components of ControlPanel *)\n\nVariable PowWaterButton: Time -> Prop. \n(* power is supplied to the button for selecting water if and only if power is supplied to the ControlPanelPowerHub *)\nVariable PowCrushedIceButton: Time -> Prop. \n(* power is supplied to the button for selecting crushed ice if and only if power is supplied to the ControlPanelPowerHub *)\nVariable PowCubedIceButton: Time -> Prop. \n(* power is supplied to the button for selecting cubed ice if and only if power is supplied to the ControlPanelPowerHub *)\n\n\n(* Internal components of the freezer *)\n\nVariable FreezerDoorSignalL: Time -> Prop.\n(* The sensor in the freezerdoor senses that the left door is open *)\nVariable FreezerDoorSignalR: Time -> Prop.\n(* The sensor in the freezerdoor senses that the right door is open *)\nVariable FreezerTempTooHigh: Time -> Prop.\n(* The temperature near the freezer sensor is higher than MaximumFreezerTemp *)\nVariable PowF: Time -> Prop.\n(* Power is flowing between the FreezerPowerHub and FreezerDoorL *)\nVariable PowG: Time -> Prop.\n(* Power is flowing between the FreezerPowerHub and FreezerCooler *)\nVariable PowH: Time -> Prop.\n(* Power is flowing between the FreezerPowerHub and FreezerLight *)\nVariable PowI: Time -> Prop.\n(* Power is flowing between the FreezerPowerHub and FreezerTempSensor *)\nVariable PowJ: Time -> Prop.\n(* Power is flowing between the FreezerPowerHub and FreezerDoorR *)\nVariable FreezerRightTemp: Time -> Prop.\n(* The freezer is actively cooling *)\nVariable FreezerLightOn: Time -> Prop.\n(* The freezer light is turned on *)\n\n\n(* Internal components of the fridge *)\n\nVariable FridgeDoorSignalL: Time -> Prop.\n(* The sensor in the Fridgedoor senses that the left door is open *)\nVariable FridgeDoorSignalR: Time -> Prop.\n(* The sensor in the Fridgedoor senses that the right door is open *)\nVariable FridgeTempTooHigh: Time -> Prop.\n(* The temperature near the Fridge sensor is higher than MaximumFridgeTemp *)\nVariable PowA: Time -> Prop.\n(* Power is flowing between the FridgePowerHub and FridgeDoorL *)\nVariable PowB: Time -> Prop.\n(* Power is flowing between the FridgePowerHub and FridgeCooler *)\nVariable PowC: Time -> Prop.\n(* Power is flowing between the FridgePowerHub and FridgeLight *)\nVariable PowD: Time -> Prop.\n(* Power is flowing between the FridgePowerHub and FridgeTempSensor *)\nVariable PowE: Time -> Prop.\n(* Power is flowing between the FridgePowerHub and FridgeDoorR *)\nVariable FridgeRightTemp: Time -> Prop.\n(* The fridge is actively cooling *)\n\n\n(* Internal components of FreezerDoorL *)\n\nVariable PowFreezerDoorSensorL: Time -> Prop.\n(* power is supplied to FreezerDoorSensorL if and only if power is supplied to FreezerDoorLPowerhub *)\n\n\n(* Internal components of FreezerDoorR*)\n\nVariable PowFreezerDoorSensorR: Time -> Prop.\n(* power is supplied to FreezerDoorSensorR if and only if power is supplied to FreezerDoorRPowerHub *)\n\n(* Internal components of FridgeDoorR *)\n\nVariable PowFridgeDoorSensorR: Time -> Prop.\n(* power is supplied to FridgeDoorSensorR if and only if power is supplied to FridgeDoorRPowerhub *)\n\n\n\n\n(* ====================================================================== *)\n\n(* Auxiliary predicates (including their meaning) *)\n\n(*\n   [\n     At this place within this template you may define as many\n     auxiliary predicates as you want, but do not forget to include\n     their meaning.\n   ]\n*)\n\n(* ====================================================================== *)\n\n(* Components *)\n\n(*\n   [\n     For each component you have to specify the following information:\n    \n     OUTSIDE comment markers:\n     - The 'Definition' to be read by Coq, in a readable layout that\n       matches the mathematical structure of the formula.\n\n     WITHIN comment markers:\n     - The specification of the component in natural language. Obviously,\n       this specification should be consistent with the formula used\n       by Coq.\n     - If appropriate, a short explanation in natural language about\n       the choices that have been made.\n   ]\n*)\n\n(* Specifications of devices in ControlPanel *)\n\nDefinition WaterButton :=\n  forall t:Time,\n        WaterButtonIn t\n      /\\\n        PowWaterButton t\n    <->\n      ColdWaterSignal t\n.\n(* meaning: if and only if the button to select cold water is pressed and power is supplied to the button to select cold water then the signal for cold water is sent *)\n\nDefinition CrushedIceButton :=\n  forall t:Time,\n        CrushedIceButtonIn t\n      /\\\n        PowCrushedIceButton t\n    <->\n      CrushedIceSignal t\n.\n(* meaning: if and only if the button to select crushed ice is pressed and power is supplied to the button to select crushed ice then the signal for crushed ice is sent *)\n\nDefinition CubedIceButton :=\n  forall t:Time,\n        CubedIceButtonIn t\n      /\\\n        PowCubedIceButton t\n    <->\n        CubedIceSignal t\n.\n(* meaning: if and only if the button to select cubed ice is pressed and power is supplied to the button to select cubed ice then the signal for cubed ice is sent *)\n\nDefinition ControlPanelPowerHub :=\n  forall t:Time,\n      PowControlPanel t\n    <->\n        PowWaterButton t\n      /\\\n        PowCrushedIceButton t\n      /\\\n        PowCubedIceButton t\n      \n.\n(* meaning: if and only if power is supplied to the control panel then power is supplied to the water button, crushed ice button, and cubed ice button *)\n\n\n\n\n(* specification of devices in FridgeDoorL *)\n\nDefinition FridgeDoorLPowerHub :=\n  forall t:Time,\n        PowIceMaker t\n      /\\\n        PowControlPanel t\n      /\\\n        PowFridgeDoorSensorL t\n    <->\n      PowA t\n.\n(* meaning: power is supplied to PowIceMaker, PowControlPanel and PowFridgeDoorSensorL if and only if power is supplied to PowA *)\n\n\nDefinition FridgeDoorSensorL :=\n  forall t:Time,\n      FridgeDoorLOpen t\n    /\\\n      PowFridgeDoorSensorL t\n  <->\n    FridgeDoorSignalL t\n.\n(* meaning: The signal FridgeDoorSignalL is sent if and only if FridgeDoorLOpen and PowFridgeDoorSensorL are received *)\n\n\n    \n    \n\n(* Specifications of devices in IceMaker *)\n\nDefinition IceMakerTray :=\n  forall t:Time,\n        WaterIn t\n      /\\\n        PowIceMakerTray t\n      /\\\n        ~ReservoirFull t\n    <->\n      FillReservoir t    \n.\n(* meaning: iff there's water pressure on the water line, and power is being supplied to the IceMakerTray, and the IceReservoir  is not full, then the IceReservoir is being filled *)\n\n\nDefinition WaterCooler :=\n  forall t:Time,\n        PowWaterCooler t\n      /\\\n        WaterIn t\n      /\\\n        ColdWaterSignal t\n    <->\n      DispenseWater t\n.\n(* meaning: iff power is being supplied to the WaterCooler, and there is water pressure on the water line, and WaterCooler is receiving a cold water signal from WaterButton, then water flows from the WaterCooler to the Dispenser*)\n\nDefinition IceReservoir :=\n  forall t:Time,\n          PowIceReservoir t\n        /\\\n          CrushedIceSignal t\n      <->\n        CrushIce t\n    /\\\n          PowIceReservoir t\n        /\\\n          CubedIceSignal t\n      <->\n        CubedIce t   \n.\n(* meaning: *)\n\nDefinition IceMakerPowerHub :=\n  forall t:Time,\n      PowIceMaker t\n    <->\n        PowIceMakerTray t\n      /\\\n        PowIceCrusher t\n      /\\\n        PowWaterCooler t\n      /\\\n        PowIceReservoir t\n      /\\\n        PowDispenser t\n.\n(* iff power is supplied to the IceMakerPowerHub, then power is supplied to the IceMakerTray, \nIceCrusher, WaterCooler, IceReservoir and Dispenser *)\n\nDefinition IceCrusher :=\n  forall t:Time,\n        PowIceCrusher t\n      /\\\n        CrushedIce t\n    <->\n      DispenseCrushedIce t\n.\n(* iff power is supplied to the IceCrusher and ice is received, then it will send crushed ice to the dispenser  *)\n\n\nDefinition Dispenser :=\n  forall t:Time,\n      (\n            PowDispenser t\n          /\\\n            DispenseWater t\n        <->\n          ColdWater t\n      )  \n    /\\\n      (\n            PowDispenser t\n          /\\\n            DispenceIce t\n        <->\n          CubedIce t\n      )\n    /\\\n      (\n            PowDispenser t\n          /\\\n            DispenseCrushedIce t\n        <->\n          CrushedIce t\n      )\n.\n(*  iff power is supplied to the Dispenser and water is received from the WaterCooler, then ColdWater is dispensed\nand iff power is supplied to the Dispenser and cubed ice is received from the IceReservoir, then CubedIce is dispensed \nand iff power is supplied to the Dispenser and crushed ice is received from the IceCrusher, then CrushedIce is dispensed*)\n\n\n\n\n(* Specifications of devices in FridgeDoorR *)\n\nDefinition FridgeDoorSensorR :=\n  forall t:Time,\n        FridgeDoorROpen t\n      /\\\n        PowFridgeDoorSensorR t\n    <->\n      FridgeDoorSignalR t\n.\n(* meaning: if and only if power is supplied to the sensor in the right-side fridge door and the right-side fridge door is opened, then a signal is sent from the right-side fridge door *)\n\n\n\nDefinition FridgeDoorRPowerHub :=\n  forall t:Time,\n        PowE t\n      <->\n        PowFridgeDoorSensorR t\n.\n(* meaning: iff power is being supplied to FridgeDoorRPowerHub, then it is supplying power to FridgeDoorSensorR *)\n\n    \n\n\n\n(* Specifications of devices in FreezerDoorR *)\n\nDefinition FreezerDoorSensorR :=\n  forall t:Time,\n        FreezerDoorROpen t\n      /\\\n        PowFreezerDoorSensorR t\n    <->\n      FreezerDoorSignalR t\n.\n(* meaning: if and only if power is supplied to the sensor in the right-side freezer door and the right-side freezer door is opened, then a signal is sent from the right-side freezer door *)\n\n\nDefinition FreezerDoorRPowerHub :=\n  forall t:Time,\n      PowJ t\n    <->\n      PowFreezerDoorSensorR t\n.\n(* meaning: iff power is supplied to PowJ, then power is supplied to the right-side freezer door sensor *)\n\n\n\n\n(* Specifications of devices in FreezerDoorL *)\n\nDefinition FreezerDoorSensorL :=\n  forall t:Time,\n        FreezerDoorLOpen t\n      /\\\n        PowFreezerDoorSensorL t\n    <->\n      FreezerDoorSignalL t\n.\n(* meaning: iff power is supplied to the sensor in the left-side freezer door and the left-side freezer door is opened, then a signal is sent from the left-side freezer door *)\n\nDefinition FreezerDoorLPowerhub :=\n  forall t:Time,\n      PowF t\n    <->\n      PowFreezerDoorSensorL t\n.\n(* meaning: iff power is supplied to PowF, then power is supplied to the left-side freezer door sensor *)\n\n\n\n\n(* Specifications of devices in SmartFridge *)\n\nDefinition Powersupply :=\n  forall t:Time,\n        PowerIn t\n    <->\n        Pow1 t\n      /\\\n        Pow2 t\n.\n(* Meaning: DC Power is supplied to FridgePowerhub and FreezerPowerhub iff AC Power is supplied to the Powersupply *)\n\n\n\n\n\n(* Specifications of devices in Fridge *)\n\nDefinition FridgeLight :=\n  forall t:Time,\n          FridgeDoorSignalL t\n        \\/\n          FridgeDoorSignalR t\n      /\\\n        PowC t\n    <->\n      FridgeLightOn t\n.\n(* Meaning: The light of the fridge is turned on if and only if it receives power through PowC and one or more of its doors is open *)\n\nDefinition FridgeCooler :=\n  forall t:Time,\n        FridgeTempTooHigh t\n      /\\\n        PowB t\n    <->\n      (\n        exists d:Time,\n          FridgeRightTemp (t + d) \n      )   \n.\n(* Meaning: When both power is delivered through PowB and the FridgeTempTooHigh signal is received, then the cooler will turn on *)\n\nDefinition FridgeTempSensor :=\n    forall t:Time,\n          TimeToTemp( t ) > MaximumFridgeTemp\n        /\\\n          PowD t\n      <->\n        FridgeTempTooHigh t\n.\n(* Meaning: For any moment in time if and only if the temperature is greater than the MaximumFridgeTemp and PowD supplies power then the signal FridgeTempTooHigh is send *)\n\nDefinition FridgePowerHub :=\n  forall t:Time,\n      Pow1 t\n    <->\n        PowA t\n      /\\\n        PowB t\n      /\\\n        PowC t\n      /\\\n        PowD t\n      /\\\n        PowE t\n.\n(* Meaning: if and only if power is supplied to Pow1, then power is supplied to PowA, PowB, PowC, PowD and PowE *)\n\nDefinition FridgeStorage :=\n  forall t:Time,\n    forall f:Food,\n          FoodPutInFridge f t\n        /\\\n          FridgeRightTemp t\n      <->\n        (\n          exists d:Time,\n            FoodIsCool f (t+d)\n        )\n          \n.\n(* Iff a certain food f is in the fridge and the fridge cooler has been turned on at time t, then the food wil be cool at time t+d *)\n\n\n\n\n(* Specifications of devices in Freezer *)\n\nDefinition FreezerPowerHub :=\n  forall t:Time,\n      Pow2 t\n    <->\n        PowF t\n      /\\\n        PowG t\n      /\\\n        PowH t\n      /\\\n        PowI t\n      /\\\n        PowJ t\n.\n(* meaning: iff power is supplied to Pow2, then power is supplied to PowF, PowG, PowH, PowI, and PowJ *)\n\nDefinition FreezerCooler := \n  forall t:Time,\n          PowG t\n        /\\\n          FreezerTempTooHigh t\n      <->\n        (\n          exists d:Time, \n            FreezerRightTemp ( t + d )\n        )\n.\n(* Iff power is supplied to PowG and the temperature inside the freezer is too high, then the cooler inside the freezer will turn on *)\n\nDefinition FreezerTempSensor :=\n  forall t:Time,\n        TimeToTemp t > MaximumFreezerTemp\n      /\\\n        PowI t\n    <->\n      FreezerTempTooHigh t\n.\n(* Iff the temperature at time t is higher than the maximum allowed freezer temperature and power is supplied to PowI, then a signal is sent that the freezer temperature is too high *)\n\nDefinition FreezerLight :=\n  forall t:Time,\n        PowH t\n      /\\\n        FreezerDoorSignalL t\n    <->\n      FreezerLightOn t \n.\n(* Iff power is supplied to PowH at time t and there is a signal coming from the left-side freezer door at time t, then the freezer light will be turned on at time t *)\n\nDefinition FreezerStorage :=\n  forall t:Time,\n      forall f:Food,\n          FoodPutInFreezer f t\n        /\\\n          FreezerRightTemp t\n      <->\n        (\n          exists d:Time,\n            FoodIsFrozen f ( t + d )\n        )\n.\n(* For any moment in time if and only if food is in the freezer and the freezer is at the right temp, then the food is frozen at some later moment of time *)\n\n\nDefinition FridgeDoorR :=\n    forall t: Time,\n            PowE t\n          /\\\n            FridgeDoorROpen t\n      <->\n          FridgeDoorSignalR t\n.\n(* For any moment in time iff power is supplied to PowE and the right-side fridge door is opened at time t, then a signal is sent from the right-side\nfridge door *)\n\nDefinition FreezerDoorR :=\n  forall t:Time,\n        PowJ t\n      /\\\n        FreezerDoorROpen t\n    <->\n      FreezerDoorSignalR t\n.\n(* For any moment in time iff power is supplied to PowJ and the right-side freezer door is opened at time t, then a signal is sent from the right-side\nfreezer door *)\n\nDefinition FreezerDoorL :=\n  forall t:Time,\n          FreezerDoorLOpen t\n        /\\\n          PowF t\n      <->\n        FreezerDoorSignalL t\n.\n(* For any moment in time iff power is supplied to PowF and the left-side freezer door is opened at time t, then a signal is sent from the left-side\nfreezer door *)\n\nDefinition ControlPanel :=\n  forall t:Time,\n      (    \n            PowControlPanel t\n          /\\\n            WaterButtonIn t\n        <-> \n          ColdWaterSignal t\n      )\n    /\\\n      (\n            PowControlPanel t\n          /\\\n            CrushedIceButtonIn t\n        <-> \n          CrushedIceSignal t\n      )\n    /\\\n      (\n            PowControlPanel t\n          /\\\n            CubedIceButtonIn t\n        <-> \n          CubedIceSignal t\n      )\n.\n(* For any moment in time, iff power is supplied to PowControlPanel and the button to select water is pressed, then a cold-water signal is sent, and\niff power is supplied to PowControlPanel and the button to select crushed ice is pressed, then a crushed-ice signal is sent, and\niff power is supplied to PowControlPanel and the button to select cubed ice is pressed, then a cubed-ice signal is sent *)\n\nDefinition FridgeDoorL :=\n  forall t:Time,\n        (\n            FridgeDoorLOpen t\n          /\\\n            PowA t\n        <->\n          FridgeDoorSignalL t\n        )\n    /\\\n      (\n            PowA t\n          /\\\n            WaterIn t\n          /\\\n            WaterButtonIn t\n        <->\n          ColdWater t\n      )\n    /\\\n      (\n            PowA t\n          /\\\n            WaterIn t\n          /\\\n            CrushedIceButtonIn t\n        <->\n          CrushedIce t\n      )\n    /\\\n      (\n            PowA t\n          /\\\n            WaterIn t\n          /\\\n            CubedIceButtonIn t\n        <->\n          CubedIce t\n      )   \n.\n(* For any moment in time, if and only if power is supplied to PowA and the fridgedoor is open then, FridgeDoorSignalL is send.\nAnd for any moment in time, if and only if power is supplied to PowA and waterpressure is supplied to WaterIn and the WaterButton is pressed then, ColdWater is delivered to the dispenser.\nAnd for any moment in time, if and only if power is supplied to PowA and waterpressure is supplied to WaterIn and the CrushedIceButton is pressed then, crushed ice is dispensed.\nAnd for any moment in time, if and only if power is supplied to PowA and waterpressure is supplied to WaterIn and the CubedIceButton is pressed then, cubed ice is dispensed. *)\n\n\nDefinition IceMaker :=\n  forall t:Time,\n      (\n            PowIceMaker t\n          /\\\n            WaterIn t\n          /\\\n            ColdWaterSignal t\n        <->\n          ColdWater t\n      )\n    /\\\n      (\n            PowIceMaker t\n          /\\\n            WaterIn t\n          /\\\n            CrushedIceSignal t\n        <->\n          CrushedIce t\n      )\n    /\\\n      (\n            PowIceMaker t\n          /\\\n            WaterIn t\n          /\\\n            CubedIceSignal t\n        <->\n          CubedIce t\n      )\n.\n\n(* \n   iff power is being supplied to the IceMaker and there's water pressure and there's a signal coming from the WaterButton\n   then cold water is flowing out of the dispenser.\n   \n   iff power is being supplied to the IceMaker and there's water pressure and there's a signal coming frm the CrushedIceButton,\n   then crushed ice is being dispensed.\n   \n   iff power is being supplied to the IceMaker and there's water pressure and there's a signal coming from the CubedIceButton,\n   then CubedIce is being dispensed.\n*)\n\nDefinition Freezer :=\n  forall t: Time,\n    forall f:Food,\n        (\n              Pow2 t\n            /\\\n              FoodPutInFreezer f t\n          <->\n              (\n                exists d: Time,\n                  FoodIsFrozen f (d+t)\n              )\n        )\n      /\\\n        (\n              Pow2 t\n            /\\\n              (\n                  FreezerDoorLOpen t\n                \\/\n                  FreezerDoorROpen t\n              )\n          <->\n            FreezerLightOn t\n        )\n.\n(* For any moment in time, it holds that iff power is supplied to the freezer \n   and food is put in the freezer, then at a later moment in time, that food wil be frozen. \n   And iff power is supplied to the freezer and either the right or the left door is open,\n   then the freezer light will be on.*)\n\nDefinition Fridge :=\n  forall t:Time,\n    forall f:Food,\n        (\n              Pow1 t\n            /\\\n                FridgeDoorROpen t\n              \\/\n                FridgeDoorLOpen t\n          <->\n            FridgeLightOn t\n        )\n      /\\\n        (\n              Pow1 t\n            /\\\n              FoodPutInFreezer f t\n          <->\n            (\n              exists d:Time,\n                FoodIsCool f (t+d)\n            )\n        )\n      /\\\n        (\n              Pow1 t\n            /\\\n              WaterButtonIn t\n            /\\\n              WaterIn t \n          <->\n            ColdWater t\n        )\n      /\\  \n        (\n              Pow1 t\n            /\\\n              CrushedIceButtonIn t\n            /\\\n              WaterIn t\n          <->\n            CrushedIce t\n        )\n      /\\\n        (\n              Pow1 t\n            /\\\n              CubedIceButtonIn t\n            /\\\n              WaterIn t\n          <->\n            CubedIce t\n        )\n.\n(* for any moment in time, \niff power is supplied to Pow1 at time t and either the right-side or the left-side fridge door is opened at time t, then the fridge light is on at time t, and \niff power is supplied to Pow1 at time t and food has been put in the freezer at time t, then the food will be cool at time (t+d), and \niff power is supplied to Pow1 at time t, and the button to select water is pressed at time t, and the waterline is connected at time t, then cold water is dispensed at time t, and \niff power is supplied to Pow1 at time t, and the button to select crushed ice is pressed at time t, and the waterline is connected at time t, then crushed ice is dispensed at time t, and \niff power is supplied to Pow1 at time t, and the button to select cubed ice is pressed at time t, and the waterline is connected at time t, then cubed ice is dispensed at time t\n *)\n\n\n    \n      \n\n    \n\n(* ====================================================================== *)\n\n(* Specification of the overall system *)\n\n(*\n   [\n     Here you have to specify:\n\n     OUTSIDE comment markers:\n     - The 'Definition' to be read by Coq, in a readable layout that\n       matches the mathematical structure of the formula.\n\n     WITHIN comment markers:\n     - The specification of the overall system in natural language.\n       Obviously, this specification should be consistent with the\n       formula used by Coq.\n     - If appropriate, a short explanation in natural language about\n       the choices that have been made.\n   ]\n*)\n\n(*\nOutputs:\n    ColdWater\n      WaterIn\n      PowerIn\n      WaterButtonIn\n    CubedIce\n      WaterIn\n      PowerIn\n      CubedIceButtonIn\n    CrushedIce\n      WaterIn\n      PowerIn\n      CrushedIceButtonIn\n    FoodIsFrozen\n      PowerIn\n      FoodPutInFreezer\n    FoodIsCool\n      PowerIn\n      FoodPutInFridge\n    FreezerLightOn\n      PowerIn\n      FreezerDoorROpen \\/ FreezerDoorLOpen\n    FridgeLightOn\n      PowerIn\n      FridgeDoorROpen \\/ FridgeDoorLOpen\n\n\nInputs:\n    WaterIn\n    PowerIn\n    FreezerDoorROpen\n    FreezerDoorLOpen\n    WaterButtonIn\n    CrushedIceButtonIn\n    CubedIceButtonIn\n    FridgeDoorLOpen\n    FridgeDoorROpen \n    FoodPutInFridge\n    FoodPutInFreezer\n*)\n\nDefinition SmartFridge :=\n  forall t:Time,\n      (\n            WaterIn t\n          /\\\n            PowerIn t\n          /\\\n            WaterButtonIn t\n        ->\n          ColdWater t\n      ) \n    /\\\n      (\n            WaterIn t\n          /\\\n            PowerIn t\n          /\\\n            CubedIceButtonIn t\n        ->\n          CubedIce t\n      )\n    /\\\n      (\n            WaterIn t\n          /\\\n            PowerIn t\n          /\\\n            CrushedIceButtonIn t\n        ->\n          CrushedIce t\n      )\n    /\\\n      (\n        forall f:Food,\n          exists d:Time,\n                PowerIn t\n              /\\\n                FoodPutInFreezer f t\n            ->\n              FoodIsFrozen f ( t + d )\n      )\n    /\\\n      (\n        forall f:Food,\n          exists d:Time,\n                PowerIn t\n              /\\\n                FoodPutInFridge f t\n            ->\n              FoodIsCool f ( t + d )\n      )\n    /\\\n      (\n            (\n                FreezerDoorROpen t\n              \\/\n                FreezerDoorLOpen t\n            )\n          /\\\n            PowerIn t\n        ->\n          FreezerLightOn t\n      )\n    /\\\n      (\n            (\n                FridgeDoorROpen t\n              \\/\n                FridgeDoorLOpen t\n            )\n          /\\\n            PowerIn t\n        ->\n          FridgeLightOn t\n      )\n.\n\n(* ====================================================================== *)\n\n(* Extras *)\n\n(*\n   [\n     It is very likely that you do not need any extras!\n\n     However, if it turns out during your proof that you have to prove\n     several times (almost) the same, then you may define a 'Lemma' at\n     this place, followed by its proof. And in the proof of the correctness\n     theorem, you may apply this lemma several times.\n     Note that it is always allowed to add lemmas to this script!\n\n     Sometimes it happens that Coq has troubles with 'trivial' properties\n     of numbers, that cannot be solve easily using 'lin_solve'.\n     In such situations, you may contact your supervisor and discuss \n     whether this may be solved by adding an 'Axiom', which can also be\n     applied later on within the proof of the correctness theorem.\n   ]\n*)\n\n(*\n\nTheorem CorFreezerDoorR :\n      FreezerDoorSensorR\n    /\\\n      FreezerDoorRPowerHub\n  ->\n    FreezerDoorR\n.\n\nTheorem CorFreezerDoorL :\n      FreezerDoorLPowerhub\n    /\\\n      FreezerDoorSensorL\n  ->\n    FreezerDoorL\n.\n\nTheorem CorFridgeDoorR :\n      FridgeDoorSensorR\n    /\\\n      FridgeDoorRPowerHub\n  ->\n    FridgeDoorR\n.\n\nTheorem CorFridgeDoorL :\n      FridgeDoorLPowerHub\n    /\\\n      FridgeDoorSensorL\n    /\\\n      ControlPanel\n    /\\\n      IceMaker\n  ->\n    FridgeDoorL\n.\n\nTheorem CorControlpanel :\n      WaterButton\n    /\\\n      CrushedIceButton\n    /\\\n      CubedIceButton\n    /\\\n      ControlPanelPowerHub\n  ->\n    ControlPanel    \n.\n\nTheorem CorFridge :\n      FridgeStorage\n    /\\\n      FridgeLight\n    /\\\n      FridgeDoorL\n    /\\\n      FridgeCooler\n    /\\\n      FridgeTempSensor\n    /\\\n      FridgeDoorR\n    /\\\n      FridgePowerHub\n  ->\n    Fridge\n.\n\nTheorem CorFreezer :\n      FreezerTempSensor\n    /\\\n      FreezerPowerHub\n    /\\\n      FreezerCooler\n    /\\\n      FreezerDoorL\n    /\\\n      FreezerDoorR\n    /\\\n      FreezerLight\n    /\\\n      FreezerStorage\n  ->\n    Freezer\n.\n\n*)\n\n(* Correctness theorem *) \n\n(* ====================================================================== *)\n\n(*\n   [\n     Write down your correctness theorem in the usual notation:\n     Theorem CorTheorem:\n     Component1 /\\ Component2 /\\ ... /\\ ComponentN -> SpecOfTheOverallSystem.\n\n     Note that as long as you don't know what natural deduction is\n     and you cannot start with the proof yet, you should keep this\n     theorem within comment markers, otherwise you will get a red cross\n     for stating a theorem without a proof.\n   \n     For the final version you obviously have to remove these comment\n     markers and provide a real proof!\n\n     Note that even if your proof is correct, you won't be able to\n     get a green check mark, but only an orange flag, for technical\n     reasons. But that is no problem.\n   ]\n\n\n\n\n\nTheorem CorTheorem :\n        Freezer \n      /\\ \n        Powersupply\n      /\\\n         Fridge\n    ->\n      SmartFridge\n.\n\n\nProof.\nunfold WaterButton. \nunfold CrushedIceButton. \nunfold CubedIceButton.\nunfold ControlPanelPowerHub.\nunfold FridgeDoorLPowerHub. \nunfold FridgeDoorSensorL.\nunfold IceMakerTray.\nunfold WaterCooler.\nunfold IceReservoir.\nunfold IceMakerPowerHub.\nunfold IceCrusher. \nunfold Dispenser.\nunfold FridgeDoorSenso rR.\nunfold FridgeDoorRPowerHub.\nunfold FreezerDoorSensorR. \nunfold FreezerDoorRPowerHub.\nunfold FreezerDoorSensorL.\nunfold FreezerDoorLPowerhub.\nunfold Powersupply.\nunfold FridgeLight.\nunfold FridgeCooler.\nunfold FridgeTempSensor.\nunfold FridgePowerHub.\nunfold FridgeStorage.\nunfold FreezerPowerHub.\nunfold FreezerCooler.\nunfold FreezerTempSensor.\nunfold FreezerLight.\nunfold FreezerStorage.\ntauto.\nQed.\n*)\n\n\n(*\n  \n*)", "meta": {"author": "mraedts", "repo": "coq-project", "sha": "90241b7c82326697cdc934874277c98b1de7a3d5", "save_path": "github-repos/coq/mraedts-coq-project", "path": "github-repos/coq/mraedts-coq-project/coq-project-90241b7c82326697cdc934874277c98b1de7a3d5/a.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.2536736350113484}}
{"text": "Require Import compcert.common.Memory.\nRequire Import VST.msl.Coqlib2.\nRequire Import VST.msl.eq_dec.\nRequire Import VST.msl.seplog.\nRequire Import VST.msl.ageable.\nRequire Import VST.msl.age_to.\nRequire Import VST.veric.coqlib4.\nRequire Import VST.veric.compcert_rmaps.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nLemma pred_hered {A} {_ : ageable A} (P : pred A) : hereditary age (app_pred P).\nProof.\n  destruct P; auto.\nQed.\n\nLemma hereditary_necR {phi phi' : rmap} {P} :\n  necR phi phi' ->\n  hereditary age P ->\n  P phi -> P phi'.\nProof.\n  intros N H; induction N; auto.\n  apply H; auto.\nQed.\n\nLemma anti_hereditary_necR {phi phi' : rmap} {P} :\n  necR phi phi' ->\n  hereditary (fun x y => age y x) P ->\n  P phi' -> P phi.\nProof.\n  intros N H; induction N; auto.\n  apply H; auto.\nQed.\n\nLemma app_pred_age {R} {phi phi' : rmap} :\n  age phi phi' ->\n  app_pred R phi ->\n  app_pred R phi'.\nProof.\n  destruct R as [R HR]; simpl.\n  apply HR.\nQed.\n\nLemma age_yes_sat {Phi Phi' phi phi' l z sh sh'} (R : pred rmap) :\n  level Phi = level phi ->\n  age Phi Phi' ->\n  age phi phi' ->\n  app_pred R phi ->\n  Phi  @ l = YES sh sh' (LK z) (SomeP rmaps.Mpred (fun _ => R)) ->\n  app_pred (approx (S (level phi')) R) phi' /\\\n  Phi' @ l = YES sh sh' (LK z) (SomeP rmaps.Mpred (fun _ => approx (level Phi') R)).\nProof.\n  intros L A Au SAT AT.\n  pose proof (app_pred_age Au SAT) as SAT'.\n  split.\n  - split.\n    + apply age_level in A; apply age_level in Au. omega.\n    + apply SAT'.\n  - apply (necR_YES _ Phi') in AT.\n    + rewrite AT.\n      reflexivity.\n    + constructor. assumption.\nQed.\n\nLemma age_resource_at {phi phi' loc} :\n  age phi phi' ->\n  phi' @ loc = resource_fmap (approx (level phi')) (approx (level phi')) (phi @ loc).\nProof.\n  intros A.\n  rewrite <- (age1_resource_at _ _ A loc (phi @ loc)).\n  - reflexivity.\n  - rewrite resource_at_approx. reflexivity.\nQed.\n\nLemma age_to_resource_at phi n loc : age_to n phi @ loc = resource_fmap (approx n) (approx n) (phi @ loc).\nProof.\n  assert (D : (n <= level phi \\/ n >= level phi)%nat) by omega.\n  destruct D as [D | D]; swap 1 2.\n  - rewrite age_to_ge; auto.\n    rewrite <-resource_at_approx.\n    match goal with\n      |- _ = ?map ?f1 ?f2 (?map ?g1 ?g2 ?r) => transitivity (map (f1 oo g1) (g2 oo f2) r)\n    end; swap 1 2.\n    + destruct (phi @ loc); unfold \"oo\"; simpl; auto.\n      * destruct p; auto.\n        rewrite preds_fmap_fmap; auto.\n      * destruct p; auto.\n        rewrite preds_fmap_fmap; auto.\n    + f_equal. rewrite approx'_oo_approx; auto.\n      rewrite approx_oo_approx'; auto.\n  - generalize (age_to_ageN n phi).\n    generalize (age_to n phi); intros phi'.\n    replace n with (level phi - (level phi - n))%nat at 2 3 by omega.\n    generalize (level phi - n)%nat; intros k. clear n D.\n    revert phi phi'; induction k; intros phi phi'.\n    + unfold ageN in *; simpl.\n      injection 1 as <-.\n      simpl; replace (level phi - 0)%nat with (level phi) by omega.\n      symmetry.\n      apply resource_at_approx.\n    + change (ageN (S k) phi) with\n      (match age1 phi with Some w' => ageN k w' | None => None end).\n      destruct (age1 phi) as [o|] eqn:Eo. 2:congruence.\n      intros A; specialize (IHk _ _ A).\n      rewrite IHk.\n      pose proof age_resource_at Eo (loc := loc) as R.\n      rewrite R.\n      clear A R.\n      rewrite (age_level _ _ Eo).\n      simpl.\n      match goal with\n        |- ?map ?f1 ?f2 (?map ?g1 ?g2 ?r) = _ => transitivity (map (f1 oo g1) (g2 oo f2) r)\n      end.\n      * destruct (phi @ loc); unfold \"oo\"; simpl; auto.\n        -- destruct p; auto.\n           rewrite preds_fmap_fmap; auto.\n        -- destruct p; auto.\n           rewrite preds_fmap_fmap; auto.\n      * f_equal. rewrite approx_oo_approx'; auto.\n        omega.\n        rewrite approx'_oo_approx; auto.\n        omega.\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/age_to_resource_at.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.4148988457967689, "lm_q1q2_score": 0.25366168093637104}}
{"text": "Require Import VST.floyd.proofauto.\nLocal Open Scope logic.\nRequire Import List. Import ListNotations.\nRequire Import ZArith.\nLocal Open Scope Z.\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: lia.\nrewrite Zmod_eq in T1. 2: lia.\nrewrite Zmod_eq in T2. 2: lia.\nrewrite Zmod_eq in T3. 2: lia. 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: lia.\nrewrite Zmod_eq in T5. 2: lia.\nrewrite Zmod_eq in T6. 2: lia.\nrewrite Zmod_eq in T7. 2: lia. 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: lia.\nrewrite Z.mod_small in T9. 2: lia.\nrewrite Zmod_eq in T10. 2: lia.\nrewrite Zmod_eq in T11. 2: lia. 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: lia.\nrewrite Z.mod_small in T13. 2: lia.\nrewrite Z.mod_small in T14. 2: lia.\nrewrite Z.mod_small in T15. 2: lia.\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: lia.\nrewrite Z.mod_small in W4. 2: lia.\nrewrite Z.mod_small in W4. 2: lia.\nrewrite Z.mod_small in W4. 2: lia.*)\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 _out out; temp _in nonce; temp _k k; temp _c c;\n   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 _out out; temp _in nonce; temp _k k; temp _c c;\n      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 _out out; temp _in nonce; temp _k k; temp _c c;\n   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*) }\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. lia.\n     + rewrite <- HM. 2: lia.\n       apply upd_Znth_diff; trivial; lia. }\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. lia.\n  intros kk K. apply H2. lia. }\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 _out out; temp _in nonce; temp _k k; temp _c c;\n   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 _out out; temp _in nonce;\n       temp _k k; temp _c c; 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 _out out; temp _in nonce; temp _k k; temp _c c;\n   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). lia. 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 _out out; temp _in nonce; temp _k k; temp _c c;\n   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 (repeat Vundef 16). 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; lia.\n    destruct (Znth_mapVint r ((5 * j + 4 * 1) mod 16)) as [t1 T1].\n      rewrite RZL; apply Z_mod_lt; lia.\n    destruct (Znth_mapVint r ((5 * j + 4 * 2) mod 16)) as [t2 T2].\n      rewrite RZL; apply Z_mod_lt; lia.\n    destruct (Znth_mapVint r ((5 * j + 4 * 3) mod 16)) as [t3 T3].\n      rewrite RZL; apply Z_mod_lt; lia. \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*)\n    rewrite Z.add_comm, Z2Nat.inj_add; try lia.\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. lia. }\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; lia.\n  Exists wints. rewrite Z.add_comm, Z2Nat.inj_add; try lia.\n  Time entailer!. (*4.3*)\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": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/tweetnacl20140427/verif_fcore_loop3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.4225046348141883, "lm_q1q2_score": 0.25358236354895974}}
{"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.\nRequire Import Progress.\n\nRequire Import SimMemory.\nRequire Import SimPromises.\nRequire Import SimLocal.\nRequire Import Compatibility.\nRequire Import SimThread.\n\nRequire Import Syntax.\nRequire Import Semantics.\n\nSet Implicit Arguments.\n\n\nLemma intro_load_sim_stmts\n      r loc ord:\n  sim_stmts (RegFile.eq_except (RegSet.singleton r))\n            []\n            [Stmt.instr (Instr.load r loc ord)]\n            (RegFile.eq_except (RegSet.singleton r)).\nProof.\n  pcofix CIH. ii. subst. pfold. ii. splits; try done; i.\n  { exploit SimPromises.cap; try apply LOCAL; eauto. }\n  { right. esplits; eauto.\n    eapply sim_local_memory_bot; eauto.\n  }\n  ii. right.\n  inv STEP_TGT; inv STEP; try (inv STATE; inv INSTR); 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    destruct e_tgt; ss. esplits; eauto; ss.\n    + econs 1.\n    + ss.\n    + by inv LOCAL0.\n    + by inv LOCAL0.\n    + left. eapply paco9_mon; [apply sim_stmts_nil|]; ss.\n      * etrans; [eauto|].\n        symmetry. apply RegFile.eq_except_singleton.\n      * inv LOCAL. inv LOCAL0. inv LOCAL. econs; ss.\n        etrans; eauto. apply TViewFacts.read_tview_incr.\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/IntroLoad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883449573377, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.25358235750593205}}
{"text": "Unset Automatic Introduction.\n\nRequire Import RezkCompletion.pathnotations.\nRequire Import Foundations.hlevel2.hSet.\n        Import RezkCompletion.pathnotations.PathNotations.\n\nFixpoint c (m n:nat) : UU.\n  intros [|m] [|n].\n  * exact unit.\n  * exact empty.\n  * exact empty.\n  * exact (c m n).\nDefined.\n\nFixpoint encode (m n:nat) : m == n -> c m n.\n  intros [|m] [|n] p.\n  * exact tt.\n  * destruct p. exact tt.\n  * destruct p.", "meta": {"author": "DanGrayson", "repo": "Ktheory", "sha": "d4122535ee4a287a2a0c2b39bd6ffcba439d66ab", "save_path": "github-repos/coq/DanGrayson-Ktheory", "path": "github-repos/coq/DanGrayson-Ktheory/Ktheory-d4122535ee4a287a2a0c2b39bd6ffcba439d66ab/misc/nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.253582357505932}}
{"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_sleep {p} : extensional_op (@NCan p NSleep).\nProof.\n  introv Hpra Hprt Hprt' Hcv Has Hi.\n\n  applydup @isprogram_sleep_implies in Hprt; exrepnd; subst; cpx.\n  applydup @isprogram_sleep_implies in Hprt'; exrepnd; subst; cpx.\n  allrw @fold_sleep.\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 computes_to_val_like_in_max_k_steps_sleep_implies in Hcv; exrepnd; cpx.\n  unfold extensional_op_ind in Hi.\n  applydup @computes_to_val_like_in_max_k_steps_preserves_program in Hcv2; auto.\n  apply Hi with (v := t0) in Hcv2; auto; clear Hi.\n\n  dorn Hcv1; exrepnd; subst.\n\n  - apply howe_lemma2 in Hcv2; auto; prove_isprogram; exrepnd.\n    unfold approx_starbts, lblift_sub in Hcv2; simpl in Hcv2; repnd; cpx.\n    allrw @fold_integer.\n    apply approx_open_implies_approx_star.\n    apply approx_implies_approx_open.\n    apply reduces_to_implies_approx_eauto; prove_isprogram.\n    apply reduces_to_trans with (b := mk_sleep (mk_integer z)).\n    { apply reduces_to_prinarg; auto.\n      destruct Hcv1; auto. }\n    { apply reduces_to_if_step; reflexivity. }\n\n  - apply isexc_implies in Hcv3; auto; exrepnd; subst; GC.\n    apply howe_lemma2_exc in Hcv2; auto; exrepnd.\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 reduces_to_implies_approx_eauto; prove_isprogram.\n    apply reduces_to_trans with (b := mk_sleep (mk_exception a' e')).\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_sleep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.253582357505932}}
{"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 develops the memory model that is used in the dynamic\n  semantics of all the languages used in the compiler.\n  It defines a type [mem] of memory states, the following 4 basic\n  operations over memory states, and their properties:\n- [load]: read a memory chunk at a given address;\n- [store]: store a memory chunk at a given address;\n- [alloc]: allocate a fresh memory block;\n- [free]: invalidate a memory block.\n*)\n\nRequire Import Zwf.\nRequire Import Axioms.\nRequire Import Coqlib.\nRequire Intv.\nRequire Import Maps.\nRequire Archi.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Export Memdata.\nRequire Export Memtype.\nRequire Intv.\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\" := (PMap.get b a) (at level 1).\n\nModule Mem <: MEM.\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: PMap.t (ZMap.t memval);  (**r [block -> offset -> memval] *)\n  mem_access: PMap.t (Z -> perm_kind -> option permission);\n                                         (**r [block -> offset -> kind -> option permission] *)\n  nextblock: block;\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, ~(Plt b nextblock) -> mem_access#b ofs k = None;\n  contents_default:\n    forall b, fst mem_contents#b = Undef\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) := Plt 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\nLocal Hint 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\nLocal Hint 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\nLocal Hint 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 (plt 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\nLocal Hint 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\nLocal Hint 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\nLocal Hint 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\nLocal Hint 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 (PMap.init (ZMap.init Undef))\n        (PMap.init (fun ofs k => None))\n        1%positive _ _ _.\nNext Obligation.\n  repeat rewrite PMap.gi. red; auto.\nQed.\nNext Obligation.\n  rewrite PMap.gi. auto.\nQed.\nNext Obligation.\n  rewrite PMap.gi. auto.\nQed.\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 (PMap.set m.(nextblock)\n                   (ZMap.init Undef)\n                   m.(mem_contents))\n         (PMap.set m.(nextblock)\n                   (fun ofs k => if zle lo ofs && zlt ofs hi then Some Freeable else None)\n                   m.(mem_access))\n         (Psucc m.(nextblock))\n         _ _ _,\n   m.(nextblock)).\nNext Obligation.\n  repeat rewrite PMap.gsspec. destruct (peq 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 PMap.gsspec. destruct (peq b (nextblock m)).\n  subst b. elim H. apply Plt_succ.\n  apply nextblock_noaccess. red; intros; elim H.\n  apply Plt_trans_succ; auto.\nQed.\nNext Obligation.\n  rewrite PMap.gsspec. destruct (peq b (nextblock m)). auto. apply contents_default.\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        (PMap.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  repeat rewrite PMap.gsspec. destruct (peq 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 PMap.gsspec. destruct (peq b0 b). subst.\n  destruct (zle lo ofs && zlt ofs hi). auto. apply nextblock_noaccess; auto.\n  apply nextblock_noaccess; auto.\nQed.\nNext Obligation.\n  apply contents_default.\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' => ZMap.get p c :: 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  ZMap.get q (setN vl p c) = ZMap.get q c.\nProof.\n  induction vl; intros; simpl.\n  auto.\n  simpl length in H. rewrite inj_S in H.\n  transitivity (ZMap.get q (ZMap.set p a c)).\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  ZMap.get q (setN vl p c) = ZMap.get q c.\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 -> ZMap.get i c1 = ZMap.get i c2) ->\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_disjoint:\n  forall vl q c n p,\n  Intv.disjoint (p, p + Z_of_nat n) (q, q + Z_of_nat (length vl)) ->\n  getN n p (setN vl q c) = getN n p c.\nProof.\n  intros. apply getN_exten. intros. apply setN_other.\n  intros; red; intros; subst r. eelim H; eauto.\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_setN_disjoint. apply Intv.disjoint_range. auto.\nQed.\n\nRemark setN_default:\n  forall vl q c, fst (setN vl q c) = fst c.\nProof.\n  induction vl; simpl; intros. auto. rewrite IHvl. auto.\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\nProgram Definition 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 (PMap.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                _ _ _)\n  else\n    None.\nNext Obligation. apply access_max. Qed.\nNext Obligation. apply nextblock_noaccess; auto. Qed.\nNext Obligation.\n  rewrite PMap.gsspec. destruct (peq b0 b).\n  rewrite setN_default. apply contents_default.\n  apply contents_default.\nQed.\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\nProgram Definition 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             (PMap.set b (setN bytes ofs (m.(mem_contents)#b)) m.(mem_contents))\n             m.(mem_access)\n             m.(nextblock)\n             _ _ _)\n  else\n    None.\nNext Obligation. apply access_max. Qed.\nNext Obligation. apply nextblock_noaccess; auto. Qed.\nNext Obligation.\n  rewrite PMap.gsspec. destruct (peq b0 b).\n  rewrite setN_default. apply contents_default.\n  apply contents_default.\nQed.\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                (PMap.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  repeat rewrite PMap.gsspec. destruct (peq 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 PMap.gsspec. destruct (peq 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.\nNext Obligation.\n  apply contents_default.\nQed.\n\n(** * Properties of the memory operations *)\n\n(** Properties of the empty store. *)\n\nTheorem nextblock_empty: nextblock empty = 1%positive.\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 PMap.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\nLocal Hint 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  | _ => 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\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 -> ZMap.get (ofs + z) m1.(mem_contents)#b = ZMap.get (ofs + z) m2.(mem_contents)#b) ->\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\nTheorem load_int64_split:\n  forall m b ofs v,\n  load Mint64 m b ofs = Some v ->\n  exists v1 v2,\n     load Mint32 m b ofs = Some (if Archi.big_endian then v1 else v2)\n  /\\ load Mint32 m b (ofs + 4) = Some (if Archi.big_endian then v2 else v1)\n  /\\ Val.lessdef v (Val.longofwords v1 v2).\nProof.\n  intros.\n  exploit load_valid_access; eauto. intros [A B]. simpl in *.\n  exploit load_loadbytes. eexact H. simpl. intros [bytes [LB EQ]].\n  change 8 with (4 + 4) in LB.\n  exploit loadbytes_split. eexact LB. omega. omega.\n  intros (bytes1 & bytes2 & LB1 & LB2 & APP).\n  change 4 with (size_chunk Mint32) in LB1.\n  exploit loadbytes_load. eexact LB1.\n  simpl. apply Zdivides_trans with 8; auto. exists 2; auto.\n  intros L1.\n  change 4 with (size_chunk Mint32) in LB2.\n  exploit loadbytes_load. eexact LB2.\n  simpl. apply Zdivide_plus_r. apply Zdivides_trans with 8; auto. exists 2; auto. exists 1; auto.\n  intros L2.\n  exists (decode_val Mint32 (if Archi.big_endian then bytes1 else bytes2));\n  exists (decode_val Mint32 (if Archi.big_endian then bytes2 else bytes1)).\n  split. destruct Archi.big_endian; auto.\n  split. destruct Archi.big_endian; auto.\n  rewrite EQ. rewrite APP. apply decode_val_int64.\n  erewrite loadbytes_length; eauto. reflexivity.\n  erewrite loadbytes_length; eauto. reflexivity.\nQed.\n\nTheorem loadv_int64_split:\n  forall m a v,\n  loadv Mint64 m a = Some v ->\n  exists v1 v2,\n     loadv Mint32 m a = Some (if Archi.big_endian then v1 else v2)\n  /\\ loadv  Mint32 m (Val.add a (Vint (Int.repr 4))) = Some (if Archi.big_endian then v2 else v1)\n  /\\ Val.lessdef v (Val.longofwords v1 v2).\nProof.\n  intros. destruct a; simpl in H; try discriminate.\n  exploit load_int64_split; eauto. intros (v1 & v2 & L1 & L2 & EQ).\n  assert (NV: Int.unsigned (Int.add i (Int.repr 4)) = Int.unsigned i + 4).\n    rewrite Int.add_unsigned. apply Int.unsigned_repr.\n    exploit load_valid_access. eexact H. intros [P Q]. simpl in Q.\n    exploit (Zdivide_interval (Int.unsigned i) Int.modulus 8).\n    omega. apply Int.unsigned_range. auto. exists (two_p (32-3)); reflexivity.\n    unfold Int.max_unsigned. omega.\n  exists v1; exists v2.\nOpaque Int.repr.\n  split. auto.\n  split. simpl. rewrite NV. auto.\n  auto.\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\nLocal Hint 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 = PMap.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 PMap.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 PMap.gsspec. destruct (peq 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 PMap.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 PMap.gsspec. destruct (peq 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_in:\n  forall vl p q c,\n  p <= q < p + Z_of_nat (length vl) ->\n  In (ZMap.get q (setN vl p c)) vl.\nProof.\n  induction vl; intros.\n  simpl in H. omegaContradiction.\n  simpl length in H. rewrite inj_S in H. simpl.\n  destruct (zeq p q). subst q. rewrite setN_outside. rewrite ZMap.gss.\n  auto with coqlib. omega.\n  right. apply IHvl. omega.\nQed.\n\nLemma getN_in:\n  forall c q n p,\n  p <= q < p + Z_of_nat n ->\n  In (ZMap.get q c) (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\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\nLemma load_store_overlap:\n  forall chunk m1 b ofs v m2 chunk' ofs' v',\n  store chunk m1 b ofs v = Some m2 ->\n  load chunk' m2 b ofs' = Some v' ->\n  ofs' + size_chunk chunk' > ofs ->\n  ofs + size_chunk chunk > ofs' ->\n  exists mv1 mvl mv1' mvl',\n      shape_encoding chunk v (mv1 :: mvl)\n  /\\  shape_decoding chunk' (mv1' :: mvl') v'\n  /\\  (   (ofs' = ofs /\\ mv1' = mv1)\n       \\/ (ofs' > ofs /\\ In mv1' mvl)\n       \\/ (ofs' < ofs /\\ In mv1 mvl')).\nProof.\n  intros.\n  exploit load_result; eauto. erewrite store_mem_contents by eauto; simpl.\n  rewrite PMap.gss.\n  set (c := (mem_contents m1)#b). intros V'.\n  destruct (size_chunk_nat_pos chunk) as [sz SIZE].\n  destruct (size_chunk_nat_pos chunk') as [sz' SIZE'].\n  destruct (encode_val chunk v) as [ | mv1 mvl] eqn:ENC.\n  generalize (encode_val_length chunk v); rewrite ENC; simpl; congruence.\n  set (c' := setN (mv1::mvl) ofs c) in *.\n  exists mv1, mvl, (ZMap.get ofs' c'), (getN sz' (ofs' + 1) c').\n  split. rewrite <- ENC. apply encode_val_shape.\n  split. rewrite V', SIZE'. apply decode_val_shape.\n  destruct (zeq ofs' ofs).\n- subst ofs'. left; split. auto. unfold c'. simpl.\n  rewrite setN_outside by omega. apply ZMap.gss.\n- right. destruct (zlt ofs ofs').\n(* If ofs < ofs':  the load reads (at ofs') a continuation byte from the write.\n       ofs   ofs'   ofs+|chunk|\n        [-------------------]       write\n             [-------------------]  read\n*)\n+ left; split. omega. unfold c'. simpl. apply setN_in.\n  assert (Z.of_nat (length (mv1 :: mvl)) = size_chunk chunk).\n  { rewrite <- ENC; rewrite encode_val_length. rewrite size_chunk_conv; auto. }\n  simpl length in H3. rewrite inj_S in H3. omega.\n(* If ofs > ofs':  the load reads (at ofs) the first byte from the write.\n       ofs'   ofs   ofs'+|chunk'|\n               [-------------------]  write\n         [----------------]           read\n*)\n+ right; split. omega. replace mv1 with (ZMap.get ofs c').\n  apply getN_in.\n  assert (size_chunk chunk' = Zsucc (Z.of_nat sz')).\n  { rewrite size_chunk_conv. rewrite SIZE'. rewrite inj_S; auto. }\n  omega.\n  unfold c'. simpl. rewrite setN_outside by omega. apply ZMap.gss.\nQed.\n\nDefinition compat_pointer_chunks (chunk1 chunk2: memory_chunk) : Prop :=\n  match chunk1, chunk2 with\n  | (Mint32 | Many32), (Mint32 | Many32) => True\n  | Many64, Many64 => True\n  | _, _ => False\n  end.\n\nLemma compat_pointer_chunks_true:\n  forall chunk1 chunk2,\n  (chunk1 = Mint32 \\/ chunk1 = Many32 \\/ chunk1 = Many64) ->\n  (chunk2 = Mint32 \\/ chunk2 = Many32 \\/ chunk2 = Many64) ->\n  quantity_chunk chunk1 = quantity_chunk chunk2 ->\n  compat_pointer_chunks chunk1 chunk2.\nProof.\n  intros. destruct H as [P|[P|P]]; destruct H0 as [Q|[Q|Q]];\n  subst; red; auto; discriminate.\nQed.\n\nTheorem load_pointer_store:\n  forall chunk m1 b ofs v m2 chunk' b' ofs' v_b v_o,\n  store chunk m1 b ofs v = Some m2 ->\n  load chunk' m2 b' ofs' = Some(Vptr v_b v_o) ->\n  (v = Vptr v_b v_o /\\ compat_pointer_chunks chunk chunk' /\\ b' = b /\\ ofs' = ofs)\n  \\/ (b' <> b \\/ ofs' + size_chunk chunk' <= ofs \\/ ofs + size_chunk chunk <= ofs').\nProof.\n  intros.\n  destruct (peq b' b); auto. subst b'.\n  destruct (zle (ofs' + size_chunk chunk') ofs); auto.\n  destruct (zle (ofs + size_chunk chunk) ofs'); auto.\n  exploit load_store_overlap; eauto.\n  intros (mv1 & mvl & mv1' & mvl' & ENC & DEC & CASES).\n  inv DEC; try contradiction.\n  destruct CASES as [(A & B) | [(A & B) | (A & B)]].\n- (* Same offset *)\n  subst. inv ENC.\n  assert (chunk = Mint32 \\/ chunk = Many32 \\/ chunk = Many64)\n  by (destruct chunk; auto || contradiction).\n  left; split. rewrite H3.\n  destruct H4 as [P|[P|P]]; subst chunk'; destruct v0; simpl in H3; congruence.\n  split. apply compat_pointer_chunks_true; auto.\n  auto.\n- (* ofs' > ofs *)\n  inv ENC.\n  + exploit H10; eauto. intros (j & P & Q). inv P. congruence.\n  + exploit H8; eauto. intros (n & P); congruence.\n  + exploit H2; eauto. congruence.\n- (* ofs' < ofs *)\n  exploit H7; eauto. intros (j & P & Q). subst mv1. inv ENC. congruence.\nQed.\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 load_store_overlap; eauto.\n  intros (mv1 & mvl & mv1' & mvl' & ENC & DEC & CASES).\n  destruct CASES as [(A & B) | [(A & B) | (A & B)]].\n- congruence.\n- inv ENC.\n  + exploit H9; eauto. intros (j & P & Q). subst mv1'. inv DEC. congruence. auto.\n  + contradiction.\n  + exploit H5; eauto. intros; subst. inv DEC; auto.\n- inv DEC.\n  + exploit H10; eauto. intros (j & P & Q). subst mv1. inv ENC. congruence.\n  + exploit H8; eauto. intros (n & P). subst mv1. inv ENC. contradiction.\n  + auto.\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  ~compat_pointer_chunks chunk chunk' ->\n  v = Vundef.\nProof.\n  intros.\n  exploit load_store_overlap; eauto.\n  generalize (size_chunk_pos chunk'); omega.\n  generalize (size_chunk_pos chunk); omega.\n  intros (mv1 & mvl & mv1' & mvl' & ENC & DEC & CASES).\n  destruct CASES as [(A & B) | [(A & B) | (A & B)]]; try omegaContradiction.\n  inv ENC; inv DEC; auto.\n- elim H1. apply compat_pointer_chunks_true; auto.\n- contradiction.\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  destruct (valid_access_dec m chunk2 b ofs Writable); auto.\n  f_equal. apply mkmem_ext; auto. congruence.\n  elim n. apply valid_access_compat with chunk1; auto. omega.\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\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  destruct (valid_access_dec m Mfloat64al32 b ofs Writable).\n  rewrite <- H. f_equal. apply mkmem_ext; auto.\n  elim 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\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. unfold storebytes.\n  destruct (range_perm_dec m1 b ofs (ofs + Z_of_nat (length bytes)) Cur Writable).\n  econstructor; 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  f_equal. apply mkmem_ext; 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  f_equal. apply mkmem_ext; 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 = PMap.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. assert (STORE2:=STORE). unfold storebytes in STORE2. 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 STORE2; simpl. rewrite PMap.gss. rewrite nat_of_Z_of_nat.\n  apply getN_setN_same.\n  red; eauto with mem.\nQed.\n\nTheorem loadbytes_storebytes_disjoint:\n  forall b' ofs' len,\n  len >= 0 ->\n  b' <> b \\/ Intv.disjoint (ofs', ofs' + len) (ofs, ofs + Z_of_nat (length bytes)) ->\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 PMap.gsspec. destruct (peq b' b). subst b'.\n  apply getN_setN_disjoint. 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 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. apply loadbytes_storebytes_disjoint; auto.\n  destruct H0; auto. right. apply Intv.disjoint_range; auto.\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 PMap.gsspec. destruct (peq 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 PMap.gss.  rewrite setN_concat. symmetry. apply PMap.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\nTheorem store_int64_split:\n  forall m b ofs v m',\n  store Mint64 m b ofs v = Some m' ->\n  exists m1,\n     store Mint32 m b ofs (if Archi.big_endian then Val.hiword v else Val.loword v) = Some m1\n  /\\ store Mint32 m1 b (ofs + 4) (if Archi.big_endian then Val.loword v else Val.hiword v) = Some m'.\nProof.\n  intros.\n  exploit store_valid_access_3; eauto. intros [A B]. simpl in *.\n  exploit store_storebytes. eexact H. intros SB.\n  rewrite encode_val_int64 in SB.\n  exploit storebytes_split. eexact SB. intros [m1 [SB1 SB2]].\n  rewrite encode_val_length in SB2. simpl in SB2.\n  exists m1; split.\n  apply storebytes_store. exact SB1.\n  simpl. apply Zdivides_trans with 8; auto. exists 2; auto.\n  apply storebytes_store. exact SB2.\n  simpl. apply Zdivide_plus_r. apply Zdivides_trans with 8; auto. exists 2; auto. exists 1; auto.\nQed.\n\nTheorem storev_int64_split:\n  forall m a v m',\n  storev Mint64 m a v = Some m' ->\n  exists m1,\n     storev Mint32 m a (if Archi.big_endian then Val.hiword v else Val.loword v) = Some m1\n  /\\ storev Mint32 m1 (Val.add a (Vint (Int.repr 4))) (if Archi.big_endian then Val.loword v else Val.hiword v) = Some m'.\nProof.\n  intros. destruct a; simpl in H; try discriminate.\n  exploit store_int64_split; eauto. intros [m1 [A B]].\n  exists m1; split.\n  exact A.\n  unfold storev, Val.add. rewrite Int.add_unsigned. rewrite Int.unsigned_repr. exact B.\n  exploit store_valid_access_3. eexact H. intros [P Q]. simpl in Q.\n  exploit (Zdivide_interval (Int.unsigned i) Int.modulus 8).\n    omega. apply Int.unsigned_range. auto. exists (two_p (32-3)); reflexivity.\n  change (Int.unsigned (Int.repr 4)) with 4. unfold Int.max_unsigned. omega.\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 = Psucc (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.\n  apply Plt_trans_succ; auto.\nQed.\n\nTheorem fresh_block_alloc:\n  ~(valid_block m1 b).\nProof.\n  unfold valid_block. rewrite alloc_result. apply Plt_strict.\nQed.\n\nTheorem valid_new_block:\n  valid_block m2 b.\nProof.\n  unfold valid_block. rewrite alloc_result. rewrite nextblock_alloc. apply Plt_succ.\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  exploit Plt_succ_inv; eauto. tauto.\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 PMap.gsspec. destruct (peq b' (nextblock m1)); auto.\n  rewrite nextblock_noaccess in H. contradiction. subst b'. apply Plt_strict.\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 PMap.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 eq_block 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 PMap.gsspec. unfold eq_block. destruct (peq 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 dec_eq_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 dec_eq_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  destruct (eq_block 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 dec_eq_true. intro.\n  exploit perm_alloc_inv. eexact H3. rewrite dec_eq_true. intro.\n  intuition omega.\n  split; auto. red; intros.\n  exploit perm_alloc_inv. apply H0. eauto. rewrite dec_eq_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 PMap.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 PMap.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\nTheorem loadbytes_alloc_unchanged:\n  forall b' ofs n,\n  valid_block m1 b' ->\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  injection ALLOC; intros A B. rewrite <- B; simpl.\n  rewrite PMap.gso. auto. rewrite A. eauto with mem.\n  red; intros. eapply perm_alloc_1; eauto.\n  rewrite pred_dec_false; auto.\n  red; intros; elim n0. red; intros. eapply perm_alloc_4; eauto. eauto with mem.\nQed.\n\nTheorem loadbytes_alloc_same:\n  forall n ofs bytes byte,\n  loadbytes m2 b ofs n = Some bytes ->\n  In byte bytes -> byte = Undef.\nProof.\n  unfold loadbytes; intros. destruct (range_perm_dec m2 b ofs (ofs + n) Cur Readable); inv H.\n  revert H0.\n  injection ALLOC; intros A B. rewrite <- A; rewrite <- B; simpl. rewrite PMap.gss.\n  generalize (nat_of_Z n) ofs. induction n0; simpl; intros.\n  contradiction.\n  rewrite ZMap.gi in H0. destruct H0; 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 PMap.gsspec. destruct (peq 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 PMap.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 PMap.gsspec. destruct (peq 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 PMap.gsspec. destruct (peq 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 PMap.gsspec. destruct (peq 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\nTheorem load_free_2:\n  forall chunk b ofs v,\n  load chunk m2 b ofs = Some v -> load chunk m1 b ofs = Some v.\nProof.\n  intros. unfold load. rewrite pred_dec_true.\n  rewrite (load_result _ _ _ _ _ H). rewrite free_result; auto.\n  apply valid_access_free_inv_1. eauto with mem.\nQed.\n\nTheorem loadbytes_free:\n  forall b ofs n,\n  b <> bf \\/ lo >= hi \\/ ofs + n <= lo \\/ hi <= ofs ->\n  loadbytes m2 b ofs n = loadbytes m1 b ofs n.\nProof.\n  intros. unfold loadbytes.\n  destruct (range_perm_dec m2 b ofs (ofs + n) Cur Readable).\n  rewrite pred_dec_true.\n  rewrite free_result; auto.\n  red; intros. eapply perm_free_3; eauto.\n  rewrite pred_dec_false; auto.\n  red; intros. elim n0; red; intros.\n  eapply perm_free_1; eauto. destruct H; auto. right; omega.\nQed.\n\nTheorem loadbytes_free_2:\n  forall b ofs n bytes,\n  loadbytes m2 b ofs n = Some bytes -> loadbytes m1 b ofs n = Some bytes.\nProof.\n  intros. unfold loadbytes in *.\n  destruct (range_perm_dec m2 b ofs (ofs + n) Cur Readable); inv H.\n  rewrite pred_dec_true. rewrite free_result; auto.\n  red; intros. apply perm_free_3; auto.\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 PMap.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 PMap.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 PMap.gsspec. destruct (peq 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 PMap.gsspec. destruct (peq 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 (eq_block 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\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\nTheorem loadbytes_drop:\n  forall b' ofs n,\n  b' <> b \\/ ofs + n <= lo \\/ hi <= ofs \\/ perm_order p Readable ->\n  loadbytes m' b' ofs n = loadbytes m b' ofs n.\nProof.\n  intros.\n  unfold loadbytes.\n  destruct (range_perm_dec m b' ofs (ofs + n) Cur 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  red; intros.\n  destruct (eq_block 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. intuition.\n  eapply perm_drop_3; eauto.\n  rewrite pred_dec_false; eauto.\n  red; intros; elim n0; red; intros.\n  eapply perm_drop_4; 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_align:\n      forall b1 b2 delta chunk ofs p,\n      f b1 = Some(b2, delta) ->\n      range_perm m1 b1 ofs (ofs + size_chunk chunk) Max p ->\n      (align_chunk chunk | delta);\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 (ZMap.get ofs m1.(mem_contents)#b1) (ZMap.get (ofs+delta) m2.(mem_contents)#b2)\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\nLemma valid_access_inj:\n  forall f m1 m2 b1 b2 delta chunk ofs p,\n  mem_inj f m1 m2 ->\n  f b1 = Some(b2, delta) ->\n  valid_access m1 chunk b1 ofs p ->\n  valid_access m2 chunk b2 (ofs + delta) p.\nProof.\n  intros. destruct H1 as [A B]. constructor.\n  replace (ofs + delta + size_chunk chunk)\n     with ((ofs + size_chunk chunk) + delta) by omega.\n  eapply range_perm_inj; eauto.\n  apply Z.divide_add_r; auto. eapply mi_align; eauto with mem.\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 valid_access_inj; 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 (ZMap.get q c1) (ZMap.get (q + delta) c2)) ->\n  (forall q, access q -> memval_inject f (ZMap.get q (setN vl1 p c1))\n                                         (ZMap.get (q + delta) (setN vl2 (p + delta) c2))).\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 valid_access_inj; 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(* align *)\n  intros. eapply mi_align with (ofs := ofs0) (p := p); eauto.\n  red; intros; eauto with mem.\n(* mem_contents *)\n  intros.\n  rewrite (store_mem_contents _ _ _ _ _ _ H0).\n  rewrite (store_mem_contents _ _ _ _ _ _ STORE).\n  rewrite ! PMap.gsspec.\n  destruct (peq 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 peq_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 (peq 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(* align *)\n  intros. eapply mi_align with (ofs := ofs0) (p := p); eauto.\n  red; intros; eauto with mem.\n(* mem_contents *)\n  intros.\n  rewrite (store_mem_contents _ _ _ _ _ _ H0).\n  rewrite PMap.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  intros; eapply mi_align0; eauto.\n(* mem_contents *)\n  intros.\n  rewrite (store_mem_contents _ _ _ _ _ _ H1).\n  rewrite PMap.gsspec. destruct (peq 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(* align *)\n  intros. eapply mi_align with (ofs := ofs0) (p := p); eauto.\n  red; intros. eapply perm_storebytes_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  rewrite ! PMap.gsspec. destruct (peq 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 peq_true.\n  apply setN_inj with (access := fun ofs => perm m1 b1 ofs Cur Readable); auto.\n  destruct (peq 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(* align *)\n  intros. eapply mi_align with (ofs := ofs0) (p := p); eauto.\n  red; intros. eapply perm_storebytes_2; eauto.\n(* mem_contents *)\n  intros.\n  rewrite (storebytes_mem_contents _ _ _ _ _ H0).\n  rewrite PMap.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(* align *)\n  eauto.\n(* mem_contents *)\n  intros.\n  rewrite (storebytes_mem_contents _ _ _ _ _ H1).\n  rewrite PMap.gsspec. destruct (peq 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\nLemma storebytes_empty_inj:\n  forall f m1 b1 ofs1 m1' m2 b2 ofs2 m2',\n  mem_inj f m1 m2 ->\n  storebytes m1 b1 ofs1 nil = Some m1' ->\n  storebytes m2 b2 ofs2 nil = Some m2' ->\n  mem_inj f m1' m2'.\nProof.\n  intros. destruct H. constructor.\n(* perm *)\n  intros.\n  eapply perm_storebytes_1; eauto.\n  eapply mi_perm0; eauto.\n  eapply perm_storebytes_2; eauto.\n(* align *)\n  intros. eapply mi_align0 with (ofs := ofs) (p := p); eauto.\n  red; intros. eapply perm_storebytes_2; eauto.\n(* mem_contents *)\n  intros.\n  assert (perm m1 b0 ofs Cur Readable). eapply perm_storebytes_2; eauto.\n  rewrite (storebytes_mem_contents _ _ _ _ _ H0).\n  rewrite (storebytes_mem_contents _ _ _ _ _ H1).\n  simpl. rewrite ! PMap.gsspec.\n  destruct (peq b0 b1); destruct (peq b3 b2); subst; eapply mi_memval0; eauto.\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(* align *)\n  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 PMap.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 (eq_block b0 b1). congruence. eauto.\n(* align *)\n  intros. eapply mi_align0 with (ofs := ofs) (p := p); eauto.\n  red; intros. exploit perm_alloc_inv; eauto.\n  destruct (eq_block b0 b1); auto. congruence.\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 PMap.gsspec. unfold eq_block in H4. destruct (peq 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 (eq_block b0 b1). subst b0.\n  rewrite H4 in H5; inv H5. eauto. eauto.\n(* align *)\n  intros. destruct (eq_block b0 b1).\n  subst b0. assert (delta0 = delta) by congruence. subst delta0.\n  assert (lo <= ofs < hi).\n  { eapply perm_alloc_3; eauto. apply H6. generalize (size_chunk_pos chunk); omega. }\n  assert (lo <= ofs + size_chunk chunk - 1 < hi).\n  { eapply perm_alloc_3; eauto. apply H6. generalize (size_chunk_pos chunk); omega. }\n  apply H2. omega.\n  eapply mi_align0 with (ofs := ofs) (p := p); eauto.\n  red; intros. eapply perm_alloc_4; 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 PMap.gsspec. unfold eq_block in H7.\n  destruct (peq 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(* align *)\n  intros. eapply mi_align0 with (ofs := ofs) (p := p); eauto.\n  red; intros; eapply perm_free_3; eauto.\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 (eq_block 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(* align *)\n  eapply mi_align0; eauto.\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(* align *)\n  intros. eapply mi_align0 with (ofs := ofs) (p := p0); eauto.\n  red; intros; eapply perm_drop_4; eauto.\n(* contents *)\n  intros.\n  replace (ZMap.get ofs m1'.(mem_contents)#b1) with (ZMap.get ofs m1.(mem_contents)#b1).\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  constructor.\n(* perm *)\n  intros.\n  assert (perm m2 b3 (ofs + delta0) k p0).\n    eapply mi_perm0; eauto. eapply perm_drop_4; eauto.\n  destruct (eq_block 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 (eq_block 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  intuition.\n(* align *)\n  intros. eapply mi_align0 with (ofs := ofs) (p := p0); eauto.\n  red; intros; eapply perm_drop_4; eauto.\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. constructor.\n  (* perm *)\n  intros. eapply perm_drop_3; eauto.\n  destruct (eq_block b2 b); auto. subst b2. right.\n  destruct (zlt (ofs + delta) lo); auto.\n  destruct (zle hi (ofs + delta)); auto.\n  byContradiction. exploit H1; eauto. omega.\n  (* align *)\n  eapply mi_align0; eauto.\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    mext_perm_inv: forall b ofs k p,\n      perm m2 b ofs k p ->\n      perm m1 b ofs k p \\/ ~perm m1 b ofs Max Nonempty\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. apply Z.divide_0_r.\n  intros. unfold inject_id in H; inv H. replace (ofs + 0) with ofs by omega.\n  apply memval_lessdef_refl.\n  tauto.\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  constructor; auto.\n  rewrite (nextblock_store _ _ _ _ _ _ H0).\n  rewrite (nextblock_store _ _ _ _ _ _ A).\n  auto.\n  intros. exploit mext_perm_inv0; intuition eauto using perm_store_1, perm_store_2.\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.\n  intros. eauto using perm_store_2.\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  constructor; auto.\n  rewrite (nextblock_storebytes _ _ _ _ _ H0).\n  rewrite (nextblock_storebytes _ _ _ _ _ A).\n  auto.\n  intros. exploit mext_perm_inv0; intuition eauto using perm_storebytes_1, perm_storebytes_2.\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.\n  intros. eauto using perm_storebytes_2.\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.\n  intros. eapply perm_alloc_inv in H; eauto.\n  generalize (perm_alloc_inv _ _ _ _ _ H0 b0 ofs Max Nonempty); intros PERM.\n  destruct (eq_block b0 b).\n  subst b0.\n  assert (EITHER: lo1 <= ofs < hi1 \\/ ~(lo1 <= ofs < hi1)) by omega.\n  destruct EITHER.\n  left. apply perm_implies with Freeable; auto with mem. eapply perm_alloc_2; eauto.\n  right; tauto.\n  exploit mext_perm_inv0; intuition eauto using perm_alloc_1, perm_alloc_4.\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.\n  intros. exploit mext_perm_inv0; eauto. intros [A|A].\n  eapply perm_free_inv in A; eauto. destruct A as [[A B]|A]; auto.\n  subst b0. right; eapply perm_free_2; eauto.\n  intuition eauto using perm_free_3.\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.\n  intros. eauto using perm_free_3.\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  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 H1.\n  eapply perm_free_2. eexact H0. instantiate (1 := ofs); omega. eauto.\n  intros. exploit mext_perm_inv0; eauto using perm_free_3. intros [A|A].\n  eapply perm_free_inv in A; eauto. destruct A as [[A B]|A]; auto.\n  subst b0. right; eapply perm_free_2; eauto.\n  right; intuition eauto using perm_free_3.\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. tauto.\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 perm_extends_inv:\n  forall m1 m2 b ofs k p,\n  extends m1 m2 -> perm m2 b ofs k p -> perm m1 b ofs k p \\/ ~perm m1 b ofs Max Nonempty.\nProof.\n  intros. inv H; 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 valid_access_inj; 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      perm m1 b (Int.unsigned ofs) Max Nonempty \\/ perm m1 b (Int.unsigned ofs - 1) Max Nonempty ->\n      delta >= 0 /\\ 0 <= Int.unsigned ofs + delta <= Int.max_unsigned;\n    mi_perm_inv:\n      forall b1 ofs b2 delta k p,\n      f b1 = Some(b2, delta) ->\n      perm m2 b2 (ofs + delta) k p ->\n      perm m1 b1 ofs k p \\/ ~perm m1 b1 ofs Max Nonempty\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 (plt 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 perm_inject_inv:\n  forall f m1 m2 b1 ofs b2 delta k p,\n  inject f m1 m2 ->\n  f b1 = Some(b2, delta) ->\n  perm m2 b2 (ofs + delta) k p ->\n  perm m1 b1 ofs k p \\/ ~perm m1 b1 ofs Max Nonempty.\nProof.\n  intros. eapply mi_perm_inv; 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 valid_access_inj; 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\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.\n  assert (perm m1 b1 (Int.unsigned ofs1) Max Nonempty) by eauto with mem.\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. rewrite weak_valid_pointer_spec in H0.\n  rewrite ! valid_pointer_nonempty_perm in H0.\n  exploit mi_representable; eauto. destruct H0; eauto with mem.\n  intros [A B].\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.\n  exploit weak_valid_pointer_inject; eauto. intros W.\n  rewrite weak_valid_pointer_spec in H0.\n  rewrite ! valid_pointer_nonempty_perm in H0.\n  exploit mi_representable; eauto. destruct H0; eauto with mem.\n  intros [A B].\n  pose proof (Int.unsigned_range ofs).\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\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  intuition.\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 Mint64; 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  destruct H4; eauto with mem.\n(* perm inv *)\n  intros. exploit mi_perm_inv0; eauto using perm_store_2.\n  intuition eauto using perm_store_1, perm_store_2.\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  destruct H3; eauto with mem.\n(* perm inv *)\n  intros. exploit mi_perm_inv0; eauto using perm_store_2.\n  intuition eauto using perm_store_1, perm_store_2.\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.\n(* perm inv *)\n  intros. eauto using perm_store_2.\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  destruct H4; eauto using perm_storebytes_2.\n(* perm inv *)\n  intros. exploit mi_perm_inv0; eauto using perm_storebytes_2.\n  intuition eauto using perm_storebytes_1, 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  destruct H3; eauto using perm_storebytes_2.\n(* perm inv *)\n  intros. exploit mi_perm_inv0; eauto.\n  intuition eauto using perm_storebytes_1, 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.\n(* perm inv *)\n  intros. eapply mi_perm_inv0; eauto using perm_storebytes_2.\nQed.\n\nTheorem storebytes_empty_inject:\n  forall f m1 b1 ofs1 m1' m2 b2 ofs2 m2',\n  inject f m1 m2 ->\n  storebytes m1 b1 ofs1 nil = Some m1' ->\n  storebytes m2 b2 ofs2 nil = Some m2' ->\n  inject f m1' m2'.\nProof.\n  intros. inversion H. constructor; intros.\n(* inj *)\n  eapply storebytes_empty_inj; eauto.\n(* freeblocks *)\n  intros. apply mi_freeblocks0. red; intros; elim H2; 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  destruct H3; eauto using perm_storebytes_2.\n(* perm inv *)\n  intros. exploit mi_perm_inv0; eauto using perm_storebytes_2.\n  intuition eauto using perm_storebytes_1, perm_storebytes_2.\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.\n(* perm inv *)\n  intros. eapply perm_alloc_inv in H2; eauto. destruct (eq_block b0 b2).\n  subst b0. eelim fresh_block_alloc; eauto.\n  eapply mi_perm_inv0; eauto.\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 eq_block b b1 then None else f b).\n  assert (inject_incr f f').\n    red; unfold f'; intros. destruct (eq_block 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 (eq_block b0 b1). congruence. eauto.\n    unfold f'; intros. destruct (eq_block b0 b1). congruence. eauto.\n    unfold f'; intros. destruct (eq_block 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 dec_eq_true.\n(* freeblocks *)\n  intros. unfold f'. destruct (eq_block b b1). auto.\n  apply mi_freeblocks0. red; intro; elim H3. eauto with mem.\n(* mappedblocks *)\n  unfold f'; intros. destruct (eq_block b b1). congruence. eauto.\n(* no overlap *)\n  unfold f'; red; intros.\n  destruct (eq_block b0 b1); destruct (eq_block b2 b1); try congruence.\n  eapply mi_no_overlap0. eexact H3. eauto. eauto.\n  exploit perm_alloc_inv. eauto. eexact H6. rewrite dec_eq_false; auto.\n  exploit perm_alloc_inv. eauto. eexact H7. rewrite dec_eq_false; auto.\n(* representable *)\n  unfold f'; intros.\n  destruct (eq_block b b1); try discriminate.\n  eapply mi_representable0; try eassumption.\n  destruct H4; eauto using perm_alloc_4.\n(* perm inv *)\n  intros. unfold f' in H3; destruct (eq_block b0 b1); try discriminate.\n  exploit mi_perm_inv0; eauto.\n  intuition eauto using perm_alloc_1, perm_alloc_4.\n(* incr *)\n  split. auto.\n(* image *)\n  split. unfold f'; apply dec_eq_true.\n(* incr *)\n  intros; unfold f'; apply dec_eq_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 eq_block b b1 then Some(b2, delta) else f b).\n  assert (inject_incr f f').\n    red; unfold f'; intros. destruct (eq_block 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 (eq_block 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 (eq_block b0 b1).\n      inversion H8. subst b0 b3 delta0.\n      elim (fresh_block_alloc _ _ _ _ _ H0).\n      eapply perm_valid_block with (ofs := ofs). apply H9. generalize (size_chunk_pos chunk); omega.\n      eauto.\n    unfold f'; intros. destruct (eq_block 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 dec_eq_true.\n(* freeblocks *)\n  unfold f'; intros. destruct (eq_block b b1). subst b.\n  elim H9. eauto with mem.\n  eauto with mem.\n(* mappedblocks *)\n  unfold f'; intros. destruct (eq_block 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 (eq_block b0 b1); destruct (eq_block b3 b1).\n  congruence.\n  inversion H10; subst b0 b1' delta1.\n    destruct (eq_block b2 b2'); auto. subst b2'. right; red; intros.\n    eapply H6; eauto. omega.\n  inversion H11; subst b3 b2' delta2.\n    destruct (eq_block b1' b2); auto. subst b1'. right; red; intros.\n    eapply H6; eauto. omega.\n  eauto.\n(* representable *)\n  unfold f'; intros.\n  destruct (eq_block b b1).\n   subst. injection H9; intros; subst b' delta0. destruct H10.\n    exploit 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 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  eapply mi_representable0; try eassumption.\n  destruct H10; eauto using perm_alloc_4.\n(* perm inv *)\n  intros. unfold f' in H9; destruct (eq_block b0 b1).\n  inversion H9; clear H9; subst b0 b3 delta0.\n  assert (EITHER: lo <= ofs < hi \\/ ~(lo <= ofs < hi)) by omega.\n  destruct EITHER.\n  left. apply perm_implies with Freeable; auto with mem. eapply perm_alloc_2; eauto.\n  right; intros A. eapply perm_alloc_inv in A; eauto. rewrite dec_eq_true in A. tauto.\n  exploit mi_perm_inv0; eauto. intuition eauto using perm_alloc_1, perm_alloc_4.\n(* incr *)\n  split. auto.\n(* image of b1 *)\n  split. unfold f'; apply dec_eq_true.\n(* image of others *)\n  intros. unfold f'; apply dec_eq_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  destruct H2; eauto with mem.\n(* perm inv *)\n  intros. exploit mi_perm_inv0; eauto. intuition eauto using perm_free_3.\n  eapply perm_free_inv in H4; eauto. destruct H4 as [[A B] | A]; auto.\n  subst b1. right; eapply perm_free_2; eauto.\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].\n  destruct (free m1 b lo hi) as [m11|] eqn:E; try discriminate.\n  apply IHl with m11; auto. eapply free_left_inject; eauto.\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.\n(* perm inv *)\n  intros. eauto using perm_free_3.\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; simpl; intros.\n  inv H. auto.\n  destruct a as [[b1 lo1] hi1].\n  destruct (free m b1 lo1 hi1) as [m1|] eqn:E; try discriminate.\n  exploit IHl; eauto. intros [A B].\n  split. eauto with mem.\n  intros. destruct H1. inv H1.\n  elim (perm_free_2 _ _ _ _ _ E 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\nTheorem free_parallel_inject:\n  forall f m1 m2 b lo hi m1' b' delta,\n  inject f m1 m2 ->\n  free m1 b lo hi = Some m1' ->\n  f b = Some(b', delta) ->\n  exists m2',\n     free m2 b' (lo + delta) (hi + delta) = Some m2'\n  /\\ inject f m1' m2'.\nProof.\n  intros.\n  destruct (range_perm_free m2 b' (lo + delta) (hi + delta)) as [m2' FREE].\n  eapply range_perm_inject; eauto. eapply free_range_perm; eauto.\n  exists m2'; split; auto.\n  eapply free_inject with (m1 := m1) (l := (b,lo,hi)::nil); eauto.\n  simpl; rewrite H0; auto.\n  intros. destruct (eq_block b1 b).\n  subst b1. rewrite H1 in H2; inv H2.\n  exists lo, hi; split; auto with coqlib. omega.\n  exploit mi_no_overlap. eexact H. eexact n. eauto. eauto.\n  eapply perm_max. eapply perm_implies. eauto. auto with mem.\n  instantiate (1 := ofs + delta0 - delta).\n  apply perm_cur_max. apply perm_implies with Freeable; auto with mem.\n  eapply free_range_perm; eauto. omega.\n  intros [A|A]. congruence. omega.\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.\n  intros. eapply mi_perm_inv0; eauto using perm_drop_4.\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  (* align *)\n  destruct (f b1) as [[b' delta'] |] eqn:?; try discriminate.\n  destruct (f' b') as [[b'' delta''] |] eqn:?; inv H.\n  apply Z.divide_add_r.\n  eapply mi_align0; eauto.\n  eapply mi_align1 with (ofs := ofs + delta') (p := p); eauto.\n  red; intros. replace ofs0 with ((ofs0 - delta') + delta') by omega.\n  eapply mi_perm0; eauto. apply H0. omega.\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  intuition 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  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.\n(* perm inv *)\n  intros.\n  destruct (f b1) as [[b' delta'] |] eqn:?; try discriminate.\n  destruct (f' b') as [[b'' delta''] |] eqn:?; try discriminate.\n  inversion H; clear H; subst b'' delta.\n  replace (ofs + (delta' + delta'')) with ((ofs + delta') + delta'') in H0 by omega.\n  exploit mi_perm_inv1; eauto. intros [A|A].\n  eapply mi_perm_inv0; eauto.\n  right; red; intros. elim A. eapply perm_inj; eauto.\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  destruct H1; eauto using perm_extends.\n(* perm inv *)\n  exploit mi_perm_inv0; eauto. intros [A|A].\n  eapply mext_perm_inv0; eauto.\n  right; red; intros; elim A. eapply perm_extends; eauto.\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.\n(* perm inv *)\n  exploit mext_perm_inv0; eauto. intros [A|A].\n  eapply mi_perm_inv0; eauto.\n  right; red; intros; elim A. eapply perm_inj; 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. inversion H; subst; 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.\n  (* perm inv *)\n  exploit mext_perm_inv1; eauto. intros [A|A].\n  eapply mext_perm_inv0; eauto.\n  right; red; intros; elim A. eapply perm_extends; eauto.\nQed.\n\n(** Injecting a memory into itself. *)\n\nDefinition flat_inj (thr: block) : meminj :=\n  fun (b: block) => if plt 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 (plt b1 thr); inversion H0; subst.\n  destruct (plt 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 pred_dec_false. auto.\n(* mappedblocks *)\n  unfold flat_inj, valid_block; intros.\n  destruct (plt 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 (plt b (nextblock m)); inv H0. generalize (Int.unsigned_range_2 ofs); omega.\n(* perm inv *)\n  unfold flat_inj; intros.\n  destruct (plt b1 (nextblock m)); inv H0.\n  rewrite Zplus_0_r in H1; auto.\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 (plt b1 thr); inv H.\n  replace (ofs + 0) with ofs by omega; auto.\n(* align *)\n  unfold flat_inj; intros. destruct (plt b1 thr); inv H. apply Z.divide_0_r.\n(* mem_contents *)\n  intros; simpl. rewrite ! PMap.gi. 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  Plt (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 pred_dec_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  Plt 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 pred_dec_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  Plt 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 pred_dec_true; eauto.\n  repeat rewrite Zplus_0_r. intros [m'' [A B]]. congruence.\nQed.\n\n(** * Invariance properties between two memory states *)\n\nSection UNCHANGED_ON.\n\nVariable P: block -> Z -> Prop.\n\nRecord unchanged_on (m_before m_after: mem) : Prop := mk_unchanged_on {\n  unchanged_on_nextblock:\n    Ple (nextblock m_before) (nextblock m_after);\n  unchanged_on_perm:\n    forall b ofs k p,\n    P b ofs -> valid_block m_before b ->\n    (perm m_before b ofs k p <-> perm m_after b ofs k p);\n  unchanged_on_contents:\n    forall b ofs,\n    P b ofs -> perm m_before b ofs Cur Readable ->\n    ZMap.get ofs (PMap.get b m_after.(mem_contents)) =\n    ZMap.get ofs (PMap.get b m_before.(mem_contents))\n}.\n\nLemma unchanged_on_refl:\n  forall m, unchanged_on m m.\nProof.\n  intros; constructor. apply Ple_refl. tauto. tauto.\nQed.\n\nLemma valid_block_unchanged_on:\n  forall m m' b,\n  unchanged_on m m' -> valid_block m b -> valid_block m' b.\nProof.\n  unfold valid_block; intros. apply unchanged_on_nextblock in H. xomega.\nQed.\n\nLemma perm_unchanged_on:\n  forall m m' b ofs k p,\n  unchanged_on m m' -> P b ofs ->\n  perm m b ofs k p -> perm m' b ofs k p.\nProof.\n  intros. destruct H. apply unchanged_on_perm0; auto. eapply perm_valid_block; eauto.\nQed.\n\nLemma perm_unchanged_on_2:\n  forall m m' b ofs k p,\n  unchanged_on m m' -> P b ofs -> valid_block m b ->\n  perm m' b ofs k p -> perm m b ofs k p.\nProof.\n  intros. destruct H. apply unchanged_on_perm0; auto.\nQed.\n\nLemma unchanged_on_trans:\n  forall m1 m2 m3, unchanged_on m1 m2 -> unchanged_on m2 m3 -> unchanged_on m1 m3.\nProof.\n  intros; constructor.\n- apply Ple_trans with (nextblock m2); apply unchanged_on_nextblock; auto.\n- intros. transitivity (perm m2 b ofs k p); apply unchanged_on_perm; auto.\n  eapply valid_block_unchanged_on; eauto.\n- intros. transitivity (ZMap.get ofs (mem_contents m2)#b); apply unchanged_on_contents; auto.\n  eapply perm_unchanged_on; eauto.\nQed.\n\nLemma loadbytes_unchanged_on_1:\n  forall m m' b ofs n,\n  unchanged_on m m' ->\n  valid_block m b ->\n  (forall i, ofs <= i < ofs + n -> P b i) ->\n  loadbytes m' b ofs n = loadbytes m b ofs n.\nProof.\n  intros.\n  destruct (zle n 0).\n+ erewrite ! loadbytes_empty by assumption. auto.\n+ unfold loadbytes. destruct H.\n  destruct (range_perm_dec m b ofs (ofs + n) Cur Readable).\n  rewrite pred_dec_true. f_equal.\n  apply getN_exten. intros. rewrite nat_of_Z_eq in H by omega.\n  apply unchanged_on_contents0; auto.\n  red; intros. apply unchanged_on_perm0; auto.\n  rewrite pred_dec_false. auto.\n  red; intros; elim n0; red; intros. apply <- unchanged_on_perm0; auto.\nQed.\n\nLemma loadbytes_unchanged_on:\n  forall m m' b ofs n bytes,\n  unchanged_on m m' ->\n  (forall i, ofs <= i < ofs + n -> P b i) ->\n  loadbytes m b ofs n = Some bytes ->\n  loadbytes m' b ofs n = Some bytes.\nProof.\n  intros.\n  destruct (zle n 0).\n+ erewrite loadbytes_empty in * by assumption. auto.\n+ rewrite <- H1. apply loadbytes_unchanged_on_1; auto.\n  exploit loadbytes_range_perm; eauto. instantiate (1 := ofs). omega.\n  intros. eauto with mem.\nQed.\n\nLemma load_unchanged_on_1:\n  forall m m' chunk b ofs,\n  unchanged_on m m' ->\n  valid_block m b ->\n  (forall i, ofs <= i < ofs + size_chunk chunk -> P b i) ->\n  load chunk m' b ofs = load chunk m b ofs.\nProof.\n  intros. unfold load. destruct (valid_access_dec m chunk b ofs Readable).\n  destruct v. rewrite pred_dec_true. f_equal. f_equal. apply getN_exten. intros.\n  rewrite <- size_chunk_conv in H4. eapply unchanged_on_contents; eauto.\n  split; auto. red; intros. eapply perm_unchanged_on; eauto.\n  rewrite pred_dec_false. auto.\n  red; intros [A B]; elim n; split; auto. red; intros; eapply perm_unchanged_on_2; eauto.\nQed.\n\nLemma load_unchanged_on:\n  forall m m' chunk b ofs v,\n  unchanged_on m m' ->\n  (forall i, ofs <= i < ofs + size_chunk chunk -> P b i) ->\n  load chunk m b ofs = Some v ->\n  load chunk m' b ofs = Some v.\nProof.\n  intros. rewrite <- H1. eapply load_unchanged_on_1; eauto with mem.\nQed.\n\nLemma store_unchanged_on:\n  forall chunk m b ofs v m',\n  store chunk m b ofs v = Some m' ->\n  (forall i, ofs <= i < ofs + size_chunk chunk -> ~ P b i) ->\n  unchanged_on m m'.\nProof.\n  intros; constructor; intros.\n- rewrite (nextblock_store _ _ _ _ _ _ H). apply Ple_refl.\n- split; intros; eauto with mem.\n- erewrite store_mem_contents; eauto. rewrite PMap.gsspec.\n  destruct (peq b0 b); auto. subst b0. apply setN_outside.\n  rewrite encode_val_length. rewrite <- size_chunk_conv.\n  destruct (zlt ofs0 ofs); auto.\n  destruct (zlt ofs0 (ofs + size_chunk chunk)); auto.\n  elim (H0 ofs0). omega. auto.\nQed.\n\nLemma storebytes_unchanged_on:\n  forall m b ofs bytes m',\n  storebytes m b ofs bytes = Some m' ->\n  (forall i, ofs <= i < ofs + Z_of_nat (length bytes) -> ~ P b i) ->\n  unchanged_on m m'.\nProof.\n  intros; constructor; intros.\n- rewrite (nextblock_storebytes _ _ _ _ _ H). apply Ple_refl.\n- split; intros. eapply perm_storebytes_1; eauto. eapply perm_storebytes_2; eauto.\n- erewrite storebytes_mem_contents; eauto. rewrite PMap.gsspec.\n  destruct (peq b0 b); auto. subst b0. apply setN_outside.\n  destruct (zlt ofs0 ofs); auto.\n  destruct (zlt ofs0 (ofs + Z_of_nat (length bytes))); auto.\n  elim (H0 ofs0). omega. auto.\nQed.\n\nLemma alloc_unchanged_on:\n  forall m lo hi m' b,\n  alloc m lo hi = (m', b) ->\n  unchanged_on m m'.\nProof.\n  intros; constructor; intros.\n- rewrite (nextblock_alloc _ _ _ _ _ H). apply Ple_succ.\n- split; intros.\n  eapply perm_alloc_1; eauto.\n  eapply perm_alloc_4; eauto.\n  eapply valid_not_valid_diff; eauto with mem.\n- injection H; intros A B. rewrite <- B; simpl.\n  rewrite PMap.gso; auto. rewrite A.  eapply valid_not_valid_diff; eauto with mem.\nQed.\n\nLemma free_unchanged_on:\n  forall m b lo hi m',\n  free m b lo hi = Some m' ->\n  (forall i, lo <= i < hi -> ~ P b i) ->\n  unchanged_on m m'.\nProof.\n  intros; constructor; intros.\n- rewrite (nextblock_free _ _ _ _ _ H). apply Ple_refl.\n- split; intros.\n  eapply perm_free_1; eauto.\n  destruct (eq_block b0 b); auto. destruct (zlt ofs lo); auto. destruct (zle hi ofs); auto.\n  subst b0. elim (H0 ofs). omega. auto.\n  eapply perm_free_3; eauto.\n- unfold free in H. destruct (range_perm_dec m b lo hi Cur Freeable); inv H.\n  simpl. auto.\nQed.\n\nLemma drop_perm_unchanged_on:\n  forall m b lo hi p m',\n  drop_perm m b lo hi p = Some m' ->\n  (forall i, lo <= i < hi -> ~ P b i) ->\n  unchanged_on m m'.\nProof.\n  intros; constructor; intros.\n- rewrite (nextblock_drop _ _ _ _ _ _ H). apply Ple_refl.\n- split; intros. eapply perm_drop_3; eauto.\n  destruct (eq_block b0 b); auto.\n  subst b0.\n  assert (~ (lo <= ofs < hi)). { red; intros; eelim H0; eauto. }\n  right; omega.\n  eapply perm_drop_4; eauto.\n- unfold drop_perm in H.\n  destruct (range_perm_dec m b lo hi Cur Freeable); inv H; simpl. auto.\nQed.\n\nEnd UNCHANGED_ON.\n\nLemma unchanged_on_implies:\n  forall (P Q: block -> Z -> Prop) m m',\n  unchanged_on P m m' ->\n  (forall b ofs, Q b ofs -> valid_block m b -> P b ofs) ->\n  unchanged_on Q m m'.\nProof.\n  intros. destruct H. constructor; intros.\n- auto.\n- apply unchanged_on_perm0; auto.\n- apply unchanged_on_contents0; auto.\n  apply H0; auto. eapply perm_valid_block; eauto.\nQed.\n\nEnd Mem.\n\nNotation mem := Mem.mem.\n\nGlobal Opaque Mem.alloc Mem.free Mem.store Mem.load Mem.storebytes Mem.loadbytes.\n\nHint Resolve\n  Mem.valid_not_valid_diff\n  Mem.perm_implies\n  Mem.perm_cur\n  Mem.perm_max\n  Mem.perm_valid_block\n  Mem.range_perm_implies\n  Mem.range_perm_cur\n  Mem.range_perm_max\n  Mem.valid_access_implies\n  Mem.valid_access_valid_block\n  Mem.valid_access_perm\n  Mem.valid_access_load\n  Mem.load_valid_access\n  Mem.loadbytes_range_perm\n  Mem.valid_access_store\n  Mem.perm_store_1\n  Mem.perm_store_2\n  Mem.nextblock_store\n  Mem.store_valid_block_1\n  Mem.store_valid_block_2\n  Mem.store_valid_access_1\n  Mem.store_valid_access_2\n  Mem.store_valid_access_3\n  Mem.storebytes_range_perm\n  Mem.perm_storebytes_1\n  Mem.perm_storebytes_2\n  Mem.storebytes_valid_access_1\n  Mem.storebytes_valid_access_2\n  Mem.nextblock_storebytes\n  Mem.storebytes_valid_block_1\n  Mem.storebytes_valid_block_2\n  Mem.nextblock_alloc\n  Mem.alloc_result\n  Mem.valid_block_alloc\n  Mem.fresh_block_alloc\n  Mem.valid_new_block\n  Mem.perm_alloc_1\n  Mem.perm_alloc_2\n  Mem.perm_alloc_3\n  Mem.perm_alloc_4\n  Mem.perm_alloc_inv\n  Mem.valid_access_alloc_other\n  Mem.valid_access_alloc_same\n  Mem.valid_access_alloc_inv\n  Mem.range_perm_free\n  Mem.free_range_perm\n  Mem.nextblock_free\n  Mem.valid_block_free_1\n  Mem.valid_block_free_2\n  Mem.perm_free_1\n  Mem.perm_free_2\n  Mem.perm_free_3\n  Mem.valid_access_free_1\n  Mem.valid_access_free_2\n  Mem.valid_access_free_inv_1\n  Mem.valid_access_free_inv_2\n  Mem.unchanged_on_refl\n: mem.\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/compcert/common/Memory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.25354847576876716}}
{"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\n  Extracts the unguessable tokens from canonical operators, opids, and\n  terms.\n\n*)\n\nRequire Export terms2.\nRequire Export sovar.\n\nDefinition oatom o := @OList (get_patom_set o).\nDefinition oatomv {o} a : oatom o := OLO a.\nDefinition oatoml {o} l : oatom o := OLL l.\nDefinition oatoms {o} f : oatom o := OLS f.\n\nDefinition oatomvs {o} (l : list (get_patom_set o)) : list (oatom o) :=\n  map oatomv l.\n\nFixpoint get_cutokens {p} (t : @NTerm p) : oatom p :=\n  match t with\n    | vterm _ => oatoml []\n    | sterm f => oatoms (fun n => get_cutokens (f n))\n    | oterm o bterms =>\n      oappl ((oatomvs (get_utokens_o o))\n               ++ (map get_cutokens_b bterms))\n  end\nwith get_cutokens_b {p} (bt : @BTerm p) : oatom p :=\n       match bt with\n         | bterm _ t => get_cutokens t\n       end.\n\nFixpoint get_utokens_so {p} (t : @SOTerm p) : list (get_patom_set p) :=\n  match t with\n  | sovar _ ts => flat_map get_utokens_so ts\n  | soseq s => []\n  | soterm op bs => (get_utokens_o op) ++ (flat_map get_utokens_b_so bs)\n  end\nwith get_utokens_b_so {p} (bt : @SOBTerm p) : list (get_patom_set p) :=\n       match bt with\n       | sobterm _ t => get_utokens_so t\n       end.\n\nFixpoint get_cutokens_so {p} (t : @SOTerm p) : oatom p :=\n  match t with\n  | sovar _ ts => oappl (map get_cutokens_so ts)\n  | soseq s => oatoms (fun n => get_cutokens (s n))\n  | soterm op bs => oappl ((oatomvs (get_utokens_o op))\n                             ++ (map get_cutokens_b_so bs))\n  end\nwith get_cutokens_b_so {p} (bt : @SOBTerm p) : oatom p :=\n       match bt with\n       | sobterm _ t => get_cutokens_so t\n       end.\n\nDefinition get_utokens_bs {p} (bts : list (@BTerm p)) : list (get_patom_set p) :=\n  flat_map get_utokens_b bts.\n\nDefinition get_cutokens_bs {p} (bts : list (@BTerm p)) : oatom p :=\n  oatoml (map get_cutokens_b bts).\n\nDefinition getc_utokens {p} (t : @CTerm p) : list (get_patom_set p) :=\n  get_utokens (get_cterm t).\n\nDefinition getc_cutokens {p} (t : @CTerm p) : oatom p :=\n  get_cutokens (get_cterm t).\n\nDefinition is_free_from_atom {o} (a : get_patom_set o) (t : @NTerm o) :=\n  !LIn a (get_utokens t).\n\nDefinition is_free_from_oatom {o} (a : get_patom_set o) (t : @NTerm o) :=\n  !in_olist a (get_cutokens t).\n\nLemma nt_wf_utoken {o} : forall a : @get_patom_set o, nt_wf (mk_utoken a).\nProof.\n  sp; repeat constructor; simpl; 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/terms/atoms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.25353439273006523}}
{"text": "Require Import Coq.omega.Omega.\nRequire Import Bedrock.DepList Bedrock.Platform.AutoSep Bedrock.Platform.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\nFixpoint 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\nFixpoint 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\nLemma 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.\nQed.\n\nLemma 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.\nQed.\n\nLemma 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.\nQed.\n\nLemma 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.\nQed.\n\nLemma allWords_universal : forall sz w,\n  In w (allWords sz).\n  rewrite allWords_eq; intros; apply allWordsUpto_universal.\n  apply wordToNat_bound.\n  auto.\nQed.\n\nLemma 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.\nQed.\n\nLemma 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.\nQed.\n\nLemma 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.\nQed.\n\nLemma 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.\nQed.\n\nLemma get_clear_eq : forall a sm,\n  smem_get a (smem_clear sm a) = None.\n  intros; apply get_clear_eq'.\nQed.\n\nHint Rewrite get_clear_eq get_clear_ne\n  using solve [ assumption | W_neq ] : get.\n\nLemma 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.\nQed.\n\nLemma 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.\nQed.\n\nLemma 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.\nQed.\n\nLemma 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.\nQed.\n\nHint Rewrite get_emp get_put_eq get_put_ne\n  using solve [ assumption | W_neq ] : get.\n\nLemma 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.\nQed.\n\nLemma 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.\nQed.\n\nLemma 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.\nQed.\n\nLemma 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.\nQed.\n\nLemma 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.\nQed.\n\nLemma 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.\nQed.\n\nLemma wordToNat_ninj' : forall sz (u v : word sz),\n  wordToNat u <> wordToNat v\n  -> u <> v.\n  congruence.\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  propxFo.\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  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  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  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.\nRequire Import Coq.Arith.Arith.\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  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  Require Import Coq.Arith.Arith.\n\n  Lemma wiggle : forall P Q R,\n    P * (Q * R) ===> Q * P * R.\n    sepLemma.\n  Qed.\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    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    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 Bedrock.Platform.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": "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/Bootstrap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.25353439273006523}}
{"text": "(** Beginning of the file for CP mechanisation as described in\n\n    Philip Wadler. 2012. Propositions as sessions. In Proceedings of the 17th\n    ACM SIGPLAN international conference on Functional programming (ICFP '12).\n    ACM, New York, NY, USA, 273-286. DOI=10.1145/2364527.2364568\n    http://doi.acm.org/10.1145/2364527.2364568\n\n*)\nRequire Import Metatheory.Metatheory.\nRequire Import Coq.Sorting.Permutation.\n\nSet Implicit Arguments.\n\n(** Propositional variables are represented as natural numbers (bound) or\n    atoms (free).\n*)\nInductive pvar :=\n  | pvar_bvar : nat -> pvar\n  | pvar_fvar : atom -> pvar.\n\nCoercion pvar_bvar : nat >-> pvar.\nCoercion pvar_fvar : atom >-> pvar.\n\n(** Propositions ranged over by A, B and C.\n\n    Note binding is de Bruijn indices with forall/exists being binders.\n*)\nInductive prop : Type :=\n  | pp_var : pvar -> prop\n  | pp_dvar : pvar -> prop (* dual of a pvar *)\n  | pp_times : prop -> prop -> prop\n  | pp_par : prop -> prop -> prop\n  | pp_plus : prop -> prop -> prop\n  | pp_with : prop -> prop -> prop\n  | pp_accept : prop -> prop (* !A *)\n  | pp_request : prop -> prop (* ?A *)\n  | pp_one : prop (* unit for times *)\n  | pp_bot : prop (* unit for par *)\n  | pp_zero : prop (* unit for plus *)\n  | pp_top : prop (* unit for with *).\n\nHint Constructors prop.\n\n(** Define some friendly notation. Level 48 to have higher precedence than\n    the ~ notation for environments; prevents need for parens. *)\nNotation \"A ⨂ B\" := (pp_times A B) (at level 48, left associativity)\n                                         : cp_scope.\nNotation \"A ⅋ B\" := (pp_par A B) (at level 48, left associativity)\n                                     : cp_scope.\nNotation \"A ⨁ B\" := (pp_plus A B) (at level 48, left associativity)\n                                       : cp_scope.\nNotation \"A & B\" := (pp_with A B) (at level 48, left associativity)\n                                       : cp_scope.\nNotation \"'!' A\" := (pp_accept A) (at level 48, left associativity)\n                                  : cp_scope.\nNotation \"'?' A\" := (pp_request A) (at level 48, left associativity)\n                                   : cp_scope.\nReserved Notation \"'¬' A\" (at level 47, left associativity).\n\nDelimit Scope cp_scope with cp.\nOpen Scope cp_scope.\n\n(** Return the dual of the proposition [pp]. *)\nFixpoint prop_dual (pp : prop) : prop :=\n  match pp with\n  | pp_var X => pp_dvar X\n  | pp_dvar X => pp_var X\n  | A ⨂ B => ¬A ⅋ ¬B\n  | A ⅋ B => ¬A ⨂ ¬B\n  | A ⨁ B => ¬A & ¬B\n  | A & B => ¬A ⨁ ¬B\n  | ! A => ? ¬A\n  | ? A => ! ¬A\n  | pp_one => pp_bot\n  | pp_bot => pp_one\n  | pp_zero => pp_top\n  | pp_top => pp_zero\n  end\nwhere \"'¬' A\" := (prop_dual A) : cp_scope.\n\nInductive dual_props : prop -> prop -> Prop :=\n  | dual_var : forall X, dual_props (pp_var X) (pp_dvar X)\n  | dual_mul : forall A B dA dB (DUA: dual_props A dA) (DUB: dual_props B dB),\n                 dual_props (A ⨂ B) (dA ⅋ dB)\n  | dual_add : forall A B dA dB (DUA: dual_props A dA) (DUB: dual_props B dB),\n                  dual_props (A ⨁ B) (dA & dB)\n  | dual_exp : forall A dA (DUA: dual_props A dA), dual_props (! A) (? dA)\n  | dual_umul : dual_props pp_one pp_bot\n  | dual_uadd : dual_props pp_zero pp_top\n  | dual_sym : forall P dP (DP: dual_props P dP),\n                 dual_props dP P.\n\nHint Constructors dual_props.\n\n(** Substitution of proposition [A] for [X] in [B] is denoted by\n    {{ A // X }} B -- double syntax used to get Coq to accept it. *)\nReserved Notation \"'{{' A '//' X '}}' B\" (at level 46, left associativity).\n\n(** The following definition of substitution for a free propositional variable\n    assumes the term to be substituted is locally closed.\n*)\nFixpoint prop_subst (x: atom) (u: prop) (pp: prop) : prop :=\n  match pp with\n  | pp_var v\n    => match v with\n       | pvar_fvar y => if x == y then u else pp\n       | _ => pp\n       end\n  | pp_dvar v\n    => match v with\n       | pvar_fvar y => if x == y then ¬u else pp\n       | _ => pp\n       end\n  | A ⨂ B => {{ u // x }} A ⨂ {{ u // x }} B\n  | A ⅋ B => {{ u // x }} A ⅋ {{ u // x }} B\n  | A ⨁ B => {{ u // x }} A ⨁ {{ u // x }} B\n  | A & B => {{ u // x }} A & {{ u // x }} B\n  | ! A => ! {{ u // x }} A\n  | ? A => ? {{ u // x }} A\n  | _ => pp\n  end\nwhere \"'{{' A '//' X '}}' B\" := (prop_subst X A B) : cp_scope.\n\n(** Opening a prop pp is replacing an unbound prop variable with index k with\n    free propositional variable u.\n*)\nFixpoint prop_open_rec (k: nat) (u: atom) (pp: prop) :=\n  match pp with\n  | pp_var v\n    => match v with\n       | pvar_bvar n => if k == n then pp_var u else pp\n       | _ => pp\n       end\n  | pp_dvar v\n    => match v with\n       | pvar_bvar n => if k == n then pp_dvar u else pp\n       | _ => pp\n       end\n  | A ⨂ B => (prop_open_rec k u A) ⨂ (prop_open_rec k u B)\n  | A ⅋ B => (prop_open_rec k u A) ⅋ (prop_open_rec k u B)\n  | A ⨁ B => (prop_open_rec k u A) ⨁ (prop_open_rec k u B)\n  | A & B => (prop_open_rec k u A) & (prop_open_rec k u B)\n  | ! A => ! (prop_open_rec k u A)\n  | ? A => ? (prop_open_rec k u A)\n  | _ => pp\n  end.\n\nDefinition open_prop t u := prop_open_rec 0 u t.\n\nFixpoint fv_prop (pp:prop) : atoms :=\n  match pp with\n  | pp_var v\n    => match v with\n       | pvar_fvar y => singleton y\n       | _ => empty\n       end\n  | pp_dvar v\n    => match v with\n       | pvar_fvar y => singleton y\n       | _ => empty\n       end\n  | A ⨂ B => fv_prop A `union` fv_prop B\n  | A ⅋ B => fv_prop A `union` fv_prop B\n  | A ⨁ B => fv_prop A `union` fv_prop B\n  | A & B => fv_prop A `union` fv_prop B\n  | ! A => fv_prop A\n  | ? A => fv_prop A\n  | _ => empty\n  end.\n\n(** Names within processes; represent channel identifiers. *)\nInductive pname : Set :=\n  | p_bn : nat -> pname\n  | p_fn : atom -> pname.\n\nCoercion p_bn : nat >-> pname.\nCoercion p_fn : atom >-> pname.\n\n(** Definition of a processes ranged over by P, Q and R. *)\nInductive proc : Set :=\n  | p_link : pname -> pname -> proc\n  | p_par : prop -> proc -> proc -> proc\n  | p_output : pname -> prop -> proc -> proc -> proc\n  | p_input : pname -> prop -> proc -> proc\n  | p_left : pname -> proc -> proc\n  | p_right : pname -> proc -> proc\n  | p_choice : pname -> proc -> proc -> proc\n  | p_accept : pname -> prop -> proc -> proc\n  | p_request : pname -> prop -> proc -> proc\n  | p_weak: pname -> proc -> proc\n  | p_empout : pname -> proc\n  | p_empin : pname -> proc -> proc\n  | p_empcho : pname -> proc.\n\nHint Constructors proc.\n\n(** Some helpful notations. *)\nNotation \"x ⟷ y\" := (p_link x y) (at level 68) : cp_scope.\nNotation \"'ν' A '→' P '‖' Q\" := (p_par A P Q) (at level 68, x ident,\n                                               right associativity)\n                                              : cp_scope.\n\n(** Change of notation from the paper; Coq doesn't seem to like the x coming\n    first. *)\nNotation \"'[' A ']' x '→' P '‖' Q\" := (p_output x A P Q) (at level 68,\n                                                          right associativity)\n                                                         : cp_scope.\n(** We use ⟨⟩ instead of () in the input cases. *)\nNotation \"'⟨' A '⟩' x '→' P\" := (p_input x A P) (at level 68,\n                                                right associativity)\n                                                : cp_scope.\n\nNotation \"x '[inl]' → P\" := (p_left x P) (at level 68,\n                                          right associativity) : cp_scope.\nNotation \"x '[inr]' → P\" := (p_right x P) (at level 68,\n                                          right associativity) : cp_scope.\nNotation \"x 'CASE' P 'OR' Q\" := (p_choice x P Q) (at level 68,\n                                                  right associativity)\n                                                 : cp_scope.\nNotation \"'!' '⟨' A '⟩' x → P\" := (p_accept x A P) (at level 68,\n                                                    right associativity)\n                                                   : cp_scope.\nNotation \"'?' '[' A ']' x → P\" := (p_request x A P) (at level 68,\n                                                     right associativity)\n                                                    : cp_scope.\nNotation \"'?' '[' ']' x → P\" := (p_weak x P) (at level 68,\n                                              right associativity)\n                                             : cp_scope.\nNotation \"x '→' 0\" := (p_empout x) (at level 68) : cp_scope.\nNotation \"⟨⟩ x → P\" := (p_empin x P) (at level 68,\n                                      right associativity) : cp_scope.\nNotation \"x 'CASE' 0\" := (p_empcho x) (at level 68) : cp_scope.\n\n(** The following definition of substitution for a free name\n    assumes the term to be substituted is locally closed.\n*)\nFixpoint proc_subst (x y: atom) (p: proc) : proc :=\n  let\n    sub := fun u => match u with\n                    | p_fn z => if z == x then y else u\n                    | _ => u\n                    end\n  in\n    match p with\n    | w ⟷ z => sub w ⟷ sub z\n    | ν A → P ‖ Q => ν A → (proc_subst x y P) ‖ (proc_subst x y Q)\n    | [A] z → P ‖ Q => [A] (sub z) → (proc_subst x y P) ‖ (proc_subst x y Q)\n    | ⟨A⟩ z → P => ⟨A⟩ (sub z) → (proc_subst x y P)\n    | z [inl] → P => (sub z) [inl] → (proc_subst x y P)\n    | z [inr] → P => (sub z) [inr] → (proc_subst x y P)\n    | z CASE P OR Q => (sub z) CASE (proc_subst x y P) OR (proc_subst x y Q)\n    | ! ⟨A⟩ z → P => ! ⟨A⟩ (sub z) → (proc_subst x y P)\n    | ? [A] z → P => ? [A] (sub z) → (proc_subst x y P)\n    | ? [] z → P => ? [] (sub z) → (proc_subst x y P)\n    | z → 0 => (sub z) → 0\n    | ⟨⟩ z → P => ⟨⟩ (sub z) → (proc_subst x y P)\n    | z CASE 0 => (sub z) CASE 0\n    end.\n\nNotation \"[ x ~> y ] P\" := (proc_subst x y P) (at level 68) : cp_scope.\n\n(** Opening a proc p is replacing an unbound name with index k with\n    free name x.\n*)\nFixpoint proc_open_rec (k: nat) (x: atom) (p: proc) :=\n  let\n    sub := fun u => match u with\n                    | p_bn n => if n == k then p_fn x else u\n                    | _ => u\n                    end\n  in\n    match p with\n    | w ⟷ z => sub w ⟷ sub z\n    | ν A → P ‖ Q\n      => ν A → (proc_open_rec (S k) x P) ‖ (proc_open_rec (S k) x Q)\n    | [A] z → P ‖ Q\n      => [A] (sub z) → (proc_open_rec (S k) x P) ‖ (proc_open_rec k x Q)\n    | ⟨A⟩ z → P => ⟨A⟩ (sub z) → (proc_open_rec (S k) x P)\n    | z [inl] → P => (sub z) [inl] → (proc_open_rec k x P)\n    | z [inr] → P => (sub z) [inr] → (proc_open_rec k x P)\n    | z CASE P OR Q\n      => (sub z) CASE (proc_open_rec k x P) OR (proc_open_rec k x Q)\n    | ! ⟨A⟩ z → P => ! ⟨A⟩ (sub z) → (proc_open_rec (S k) x P)\n    | ? [A] z → P => ? [A] (sub z) → (proc_open_rec (S k) x P)\n    | ? [] z → P => ? [] (sub z) → (proc_open_rec k x P)\n    | z → 0 => sub z → 0\n    | ⟨⟩ z → P => ⟨⟩ (sub z) → (proc_open_rec k x P)\n    | z CASE 0 => (sub z) CASE 0\n    end.\n\nNotation \"{ k ~> u } t\" := (proc_open_rec k u t) (at level 68,\n                                                  right associativity).\n\nDefinition open_proc P x := proc_open_rec 0 x P.\nNotation \"P ^^ x\" := (open_proc P x) (at level 68) : cp_scope.\n\nHint Unfold open_proc.\n\nFixpoint fv_proc (p : proc) : atoms :=\n  let\n    fv := fun u => match u with\n                   | p_fn z => singleton z\n                   | _ => empty\n                   end\n  in\n    match p with\n    | w ⟷ z => fv w `union` fv z\n    | ν A → P ‖ Q => fv_proc P `union` fv_proc Q\n    | [A] z → P ‖ Q => fv z `union` fv_proc P `union` fv_proc Q\n    | ⟨A⟩ z → P => fv z `union` fv_proc P\n    | z [inl] → P => fv z `union` fv_proc P\n    | z [inr] → P => fv z `union` fv_proc P\n    | z CASE P OR Q => fv z `union` fv_proc P `union` fv_proc Q\n    | ! ⟨A⟩ z → P => fv z `union` fv_proc P\n    | ? [A] z → P => fv z `union` fv_proc P\n    | ? [] z → P => fv z `union` fv_proc P\n    | z → 0 => fv z\n    | ⟨⟩ z → P => fv z `union` fv_proc P\n    | z CASE 0 => fv z\n    end.\n\n(* Permute binders inside process. *)\nReserved Notation \"{ a <~> b } Q\" (at level 68, right associativity).\n\nFixpoint swap_binders (a b:nat) (Q:proc) : proc :=\n  let\n    swap := fun x => match x with\n                     | p_bn n =>\n                       p_bn (if n == a then b else if n == b then a else n)\n                     | _ => x\n                     end\n  in\n    match Q with\n    | w ⟷ z => swap w ⟷ swap z\n    | ν A → P ‖ R\n      => ν A → ({S a <~> S b} P) ‖ ({S a <~> S b} R)\n    | [A] z → P ‖ R\n      => [A] (swap z) → ({S a <~> S b} P) ‖ ({a <~> b}R)\n    | ⟨A⟩ z → P => ⟨A⟩ (swap z) → ({S a <~> S b} P)\n    | z [inl] → P => (swap z) [inl] → ({a <~> b} P)\n    | z [inr] → P => (swap z) [inr] → ({a <~> b} P)\n    | z CASE P OR R\n      => (swap z) CASE ({a <~> b} P) OR ({a <~> b} R)\n    | ! ⟨A⟩ z → P => ! ⟨A⟩ (swap z) → ({S a <~> S b} P)\n    | ? [A] z → P => ? [A] (swap z) → ({S a <~> S b} P)\n    | ? [] z → P => ? [] (swap z) → ({a <~> b} P)\n    | z → 0 => swap z → 0\n    | ⟨⟩ z → P => ⟨⟩ (swap z) → ({a <~> b} P)\n    | z CASE 0 => (swap z) CASE 0\n    end\nwhere \"{ a <~> b } P\" := (swap_binders a b P) : cp_scope.\n\n(** Environments for the process calculus are mappings of atoms to\n    propositions. *)\nDefinition penv := list (atom * prop).\n\n(** Encoding an environment as all requests; for the server accept process\n    rule. *)\nInductive all_requests : penv -> Prop :=\n  | all_reqs_nil : all_requests nil\n  | all_reqs_cons : forall x A Γ (REQS: all_requests Γ),\n                          all_requests ((x ~ ? A) ++ Γ).\n\nHint Constructors all_requests.\n\n(** Locally closed processes. *)\nInductive lc_proc : proc -> Prop :=\n  | lc_p_fwd : forall (w x:atom), lc_proc (w ⟷ x)\n  | lc_p_cut : forall (L:atoms) P Q A\n                    (COP: forall (x:atom) (NL: x `notin` L),\n                            lc_proc (open_proc P x))\n                    (COQ: forall (x:atom) (NL: x `notin` L),\n                            lc_proc (open_proc Q x)),\n               lc_proc (ν A → P ‖ Q)\n  | lc_p_output : forall (L:atoms) P Q (x:atom) A\n                         (COP: forall (y:atom) (NL: y `notin` L),\n                                 lc_proc (open_proc P y))\n                         (COQ: lc_proc Q),\n                    lc_proc ([A]x → P ‖ Q)\n  | lc_p_input : forall (L:atoms) P (x:atom) A\n                        (COP: forall (y:atom) (NL: y `notin` L),\n                                lc_proc (open_proc P y)),\n                   lc_proc (⟨A⟩x → P)\n  | lc_p_left : forall P (x:atom) (COP: lc_proc P),\n                  lc_proc (x[inl] → P)\n  | lc_p_right : forall P (x:atom) (COP: lc_proc P),\n                   lc_proc (x[inr] → P)\n  | lc_p_choice : forall P Q (x:atom) (COP: lc_proc P) (COQ: lc_proc Q),\n                    lc_proc (x CASE P OR Q)\n  | lc_p_accept : forall (L:atoms) P (x:atom) A\n                         (COP: forall (y:atom) (NL: y `notin` L),\n                                 lc_proc (open_proc P y)),\n                    lc_proc (! ⟨A⟩ x → P)\n  | lc_p_request : forall (L:atoms) P (x:atom) A\n                          (COP: forall (y:atom) (NL: y `notin` L),\n                                  lc_proc (open_proc P y)),\n                     lc_proc (? [A] x → P)\n  | lc_p_weak : forall P (x:atom) (COP: lc_proc P), lc_proc (? [] x → P)\n  | lc_p_empout : forall (x:atom), lc_proc (x → 0)\n  | lc_p_empin : forall P (x:atom) (COP: lc_proc P), lc_proc (⟨⟩ x → P)\n  | lc_p_empcho : forall (x:atom), lc_proc (x CASE 0).\n\nHint Constructors lc_proc.\n\nReserved Notation \"P '⊢cp' Γ\" (at level 69).\n\n(** The uniqueness assumption is necessary to ensure environments are only\n    combined if they contain distinct names.\n    Note in some cases we utilise cofinite quantification to provide a\n    suitably fresh name for some channels. Some cases could be written as\n    x `notin` Γ for some x, Γ but I elected to maintain uniq assumptions\n    wherever possible to keep the development symmetrical (in theory, this\n    could help proofs since all rules follow a similar structure).\n\n    The proof scripts use the location of the forall quantifiers to simplify\n    application of the constructors. For example, the position of L as the\n    first quantified variable is essential for the \"pick fresh\" tactics. In\n    principle, one could change this by utilising the SFLibTactics.v applys\n    et al. tactics.\n*)\nInductive cp_rule : proc -> penv -> Prop :=\n  | cp_fwd : forall Γ (x w:atom) A\n                    (PER: Permutation Γ (w ~ ¬A ++ x ~ A))\n                    (UN: uniq Γ),\n               w ⟷ x ⊢cp Γ\n  | cp_cut : forall (L:atoms) P Q A Γ ΔP ΔQ\n                    (PER: Permutation Γ (ΔP ++ ΔQ))\n                    (UN: uniq Γ)\n                    (CPP: forall (x:atom) (NL: x `notin` L),\n                            (open_proc P x) ⊢cp (x ~ A) ++ ΔP)\n                    (CPQ: forall (x:atom) (NL: x `notin` L),\n                            (open_proc Q x) ⊢cp (x ~ ¬A) ++ ΔQ),\n               ν A → P ‖ Q ⊢cp Γ\n  | cp_output : forall (L:atoms) P Q Γ ΔP ΔQ x A B\n                       (PER: Permutation Γ ((x ~ A ⨂ B) ++ ΔP ++ ΔQ))\n                       (UN: uniq Γ)\n                       (CPP: forall (y:atom) (NL: y `notin` L),\n                               (open_proc P y) ⊢cp (y ~ A) ++ ΔP)\n                       (CPQ: Q ⊢cp (x ~ B) ++ ΔQ),\n                  [A]x → P ‖ Q ⊢cp Γ\n  | cp_input : forall (L:atoms) P Γ ΔP x A B\n                      (PER: Permutation Γ ((x ~ A ⅋ B) ++ ΔP))\n                      (UN: uniq Γ)\n                      (CPP: forall (y:atom) (NL: y `notin` L),\n                           (open_proc P y) ⊢cp (y ~ A) ++ (x ~ B) ++ ΔP),\n                 ⟨A⟩x → P ⊢cp Γ\n  | cp_left : forall P Γ Δ x A B\n                     (PER: Permutation Γ ((x ~ A ⨁ B) ++ Δ))\n                     (CPP: P ⊢cp (x ~ A) ++ Δ),\n                x[inl] → P ⊢cp Γ\n  | cp_right : forall P Γ Δ x A B\n                      (PER: Permutation Γ ((x ~ A ⨁ B) ++ Δ))\n                      (CPP: P ⊢cp (x ~ B) ++ Δ),\n                 x[inr] → P ⊢cp Γ\n  | cp_choice : forall P Q Γ Δ x A B\n                       (PER: Permutation Γ ((x ~ A & B) ++ Δ))\n                       (CPP: P ⊢cp (x ~ A) ++ Δ)\n                       (CPQ: Q ⊢cp (x ~ B) ++ Δ),\n                  x CASE P OR Q ⊢cp Γ\n  | cp_accept : forall (L:atoms) P Γ Δ (x:atom) A\n                       (PER: Permutation Γ (x ~ ! A ++ Δ))\n                       (REQSΓ: all_requests Δ)\n                       (UN: uniq Γ)\n                       (CPP: forall (y:atom) (NL: y `notin` L),\n                               (open_proc P y) ⊢cp (y ~ A) ++ Δ),\n                  ! ⟨A⟩ x → P ⊢cp Γ\n  | cp_request : forall (L:atoms) P Γ Δ (x:atom) A\n                        (PER: Permutation Γ (x ~ ? A ++ Δ))\n                        (UN: uniq Γ)\n                        (CPP: forall (y:atom) (NL: y `notin` L),\n                                (open_proc P y) ⊢cp (y ~ A) ++ Δ),\n                   ? [A] x → P ⊢cp Γ\n  | cp_weaken : forall P Γ Δ (x:atom) A\n                       (PER: Permutation Γ (x ~ ? A ++ Δ))\n                       (UN: uniq Γ)\n                       (CPP: P ⊢cp Δ),\n                  ? [] x → P ⊢cp Γ\n  | cp_empout : forall (x: atom), x → 0 ⊢cp x ~ pp_one\n  | cp_empin : forall P Γ Δ (x:atom)\n                      (PER: Permutation Γ (x ~ pp_bot ++ Δ))\n                      (UN: uniq Γ)\n                      (CPP: P ⊢cp Δ),\n                 ⟨⟩ x → P ⊢cp Γ\n  | cp_empcho : forall (x:atom), x CASE 0 ⊢cp x ~ pp_top\nwhere \"P '⊢cp' Γ\" := (cp_rule P Γ) : cp_scope.\n\nHint Constructors cp_rule.\n\nFixpoint weakenv (xs:list atom) (P:proc) : proc :=\n  match xs with\n  | nil => P\n  | x :: xs' => ? [] x → (weakenv xs' P)\n  end.\n\n(* Structural equivalences *)\n\nDefinition proc_equiv (P Q:proc) := forall Γ, P ⊢cp Γ <-> Q ⊢cp Γ.\nNotation \"P =p= Q\" := (proc_equiv P Q) (at level 69) : cp_scope.\n\nReserved Notation \"P '==>cp' Q\" (at level 69, right associativity).\n\n(** Principal cut reductions and commuting conversions. *)\nInductive proc_red : proc -> proc -> Prop :=\n  (** Principal cut reductions *)\n  | red_axcut :\n      forall P A (w x:atom) (NF: w `notin` fv_proc P),\n        ν A → w ⟷ 0 ‖ P\n      ==>cp\n        (open_proc P w)\n  | red_multi :\n      forall P Q R A dA B (DUA: dual_props A dA),\n        ν A ⨂ B → ([A]0 → P ‖ Q) ‖ ⟨dA⟩ 0 → R\n      ==>cp\n        ν A → P ‖ (ν B → Q ‖ {0 <~> 1}R)\n  | red_add_inl :\n      forall P Q R A B,\n        ν A ⨁ B → (0[inl] → P) ‖ 0 CASE Q OR R\n      ==>cp\n        ν A → P ‖ Q\n  | red_add_inr :\n      forall P Q R A B,\n        ν A ⨁ B → (0[inr] → P) ‖ 0 CASE Q OR R\n      ==>cp\n        ν B → P ‖ R\n  | red_spawn :\n      forall P Q A dA (DUA: dual_props A dA),\n        ν ! A → ! ⟨A⟩ 0 → P ‖ ? [dA]0 → Q\n      ==>cp\n        ν A → P ‖ Q\n  | red_gc :\n      forall P Q (y:atom) A\n             (NF: y `notin` fv_proc P),\n        ν ! A → ! ⟨A⟩0 → P ‖ ? [] 0 → Q\n      ==>cp\n        weakenv (elements (remove y (fv_proc (P ^^ y)))) Q\n  | red_unit :\n      forall P,\n        ν pp_one → (0 → 0) ‖ ⟨⟩0 → P\n      ==>cp\n        P\n  (** Commuting conversions *)\n  | red_cc_multi_one:\n      forall P Q R (x:atom) A B\n             (LCQ: lc_proc Q),\n        ν A → ([B] x → P ‖ Q) ‖ R\n      ==>cp\n        [B] x → (ν A → {0 <~> 1}P ‖ R) ‖ Q\n  | red_cc_multi_two:\n      forall P Q R (x:atom) A B\n             (LCP: forall x, lc_proc (P ^^ x)),\n        ν A → ([B] x → P ‖ Q) ‖ R\n      ==>cp\n        [B] x → P ‖ (ν A → Q ‖ R)\n  | red_cc_input:\n      forall P Q (x:atom) A B,\n        ν A → (⟨B⟩ x → P) ‖ Q\n      ==>cp\n        ⟨B⟩x → ν A → ({0 <~> 1}P) ‖ Q\n  | red_cc_add_inl:\n      forall P Q (x:atom) A,\n        ν A → (x[inl] → P) ‖ Q\n      ==>cp\n        x[inl] → (ν A → P ‖ Q)\n  | red_cc_add_inr:\n      forall P Q (x:atom) A,\n        ν A → (x[inr] → P) ‖ Q\n      ==>cp\n        x[inr] → (ν A → P ‖ Q)\n  | red_cc_choice:\n      forall P Q R (x:atom) A,\n        ν A → (x CASE P OR Q) ‖ R\n      ==>cp\n        x CASE (ν A → P ‖ R) OR (ν A → Q ‖ R)\n  | red_cc_accept:\n      forall P Q (x:atom) A B\n             (REQS: forall Γ Δ\n                           (PER: Permutation Γ (x~! B++Δ))\n                           (WT: ν A → (! ⟨B⟩x → P) ‖ Q ⊢cp Γ),\n                      all_requests Δ),\n        ν A → (! ⟨B⟩x → P) ‖ Q\n      ==>cp\n        ! ⟨B⟩x → (ν A → {0 <~> 1}P ‖ Q)\n  | red_cc_request:\n      forall P Q (x:atom) A B,\n        ν A → (? [B]x → P) ‖ Q\n      ==>cp\n        ? [B]x → (ν A → {0 <~> 1}P ‖ Q)\n  | red_cc_weaken:\n      forall P Q (x:atom) A,\n        ν A → (? []x → P) ‖ Q\n      ==>cp\n        ? []x → (ν A → P ‖ Q)\n  | red_cc_empin:\n      forall P Q (x:atom) A,\n        ν A → (⟨⟩x → P) ‖ Q\n      ==>cp\n        ⟨⟩x → (ν A → P ‖ Q)\n  | red_cc_empcho:\n      forall Q (x y:atom) A\n           (REQS: forall Γ Δ\n                         (PER: Permutation Γ (x~pp_top ++ Δ))\n                         (WT: ν A → (? []0 → x CASE 0) ‖ Q ⊢cp Γ),\n                    all_requests Δ)\n             (NF: y `notin` fv_proc Q),\n        ν A → (? []0 → x CASE 0) ‖ Q\n      ==>cp\n        weakenv (elements (remove y (fv_proc (Q ^^ y)))) (x CASE 0)\n  | red_equiv:\n      forall P Q R S\n             (EQPQ: P =p= Q)\n             (RED: Q ==>cp R)\n             (EQRS: R =p= S),\n        P\n      ==>cp\n        S\n  | red_congr_cut_l:\n      forall P Q R A\n             (REDL: forall x (NFV: x `notin` fv_proc P `union` fv_proc R),\n                      P ^^ x ==>cp R ^^ x),\n        ν A → P ‖ Q\n      ==>cp\n        ν A → R ‖ Q\n  | red_congr_cut_r:\n      forall P Q R A\n             (REDR: forall x (NFV: x `notin` fv_proc Q `union` fv_proc R),\n                      Q ^^ x ==>cp R ^^ x),\n        ν A → P ‖ Q\n      ==>cp\n        ν A → P ‖ R\nwhere \"P '==>cp' Q\" := (proc_red P Q) : cp_scope.\n\nDefinition is_cut (P:proc) : Prop :=\n  match P with\n  | ν _ → _ ‖ _ => True\n  | _ => False\n  end.", "meta": {"author": "cmcl", "repo": "msci", "sha": "06b1607ee1f4dde3c7c984ce6e1bbc86a8fd36f9", "save_path": "github-repos/coq/cmcl-msci", "path": "github-repos/coq/cmcl-msci/msci-06b1607ee1f4dde3c7c984ce6e1bbc86a8fd36f9/Coq Developments/msci/CP_Definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.25353439273006523}}
{"text": "Require Import Ring.\n\nRequire Export himp_steps.\nRequire Export himp_syntax_sugar.\n\nRequire Export fun_domains_props.\n\nRequire Export proof.\nRequire Export proof_automation.\nRequire Import patterns.\nRequire Import equate_map_reflection.\nRequire Export himp_claims.\n\nOpen Scope string_scope.\nOpen Scope list_scope.\n\nSet Implicit Arguments.\n\n(* Some lemmas used in proof automation *)\n\nLemma use_value_heap : forall ret krest store stack frame funs mark\n           (Q : Spec kcfg) (P : kcfg -> Prop),\n  (forall r' store' heap' funs' mark',\n    heap' |= ret r' :* litP frame ->\n    store' ~= store ->\n    funs' ~= funs ->\n    (mark' >= mark)%Z ->\n    Q (KCfg (kra r' krest) store' stack heap' funs' mark') P\n   ) ->\n  (forall k', value_heap ret krest store stack frame funs mark k' -> Q k' P).\nProof. destruct k'. destruct 1. intuition. subst. auto. Qed.\n\nLemma use_return_heap : forall ret stack frame funs mark\n           (Q : Spec kcfg) (P : kcfg -> Prop),\n  (forall r' krest store' heap' funs' mark',\n    heap' |= ret r' :* litP frame ->\n    funs' ~= funs ->\n    (mark' >= mark)%Z ->\n    Q (KCfg (kra (SReturn r') krest) store' stack heap' funs' mark') P\n   ) ->\n  (forall k', return_heap ret stack frame funs mark k' -> Q k' P).\nProof. destruct k'. simpl.\nlet H := fresh in intro H;decompose record H;clear H.\nsubst. auto.\nQed.\n\nArguments stk_equiv s1 s2 : simpl nomatch.\n\n(** Register it as an equivalence relations,\n    mostly just so we can say \"reflexivity\" *)\nLemma stk_equiv_refl : forall s, stk_equiv s s.\nProof.\ninduction s;simpl;auto.\ndestruct a. simpl. auto using equivRefl.\nQed.\n\nLemma stk_equiv_sym : forall s1 s2, stk_equiv s1 s2 -> stk_equiv s2 s1.\nProof.\ninduction s1;destruct s2;simpl;firstorder.\ndestruct a;trivial.\ndestruct a,f;firstorder.\nQed.\n\nLemma stk_equiv_trans : forall s1 s2 s3,\n  stk_equiv s1 s2 -> stk_equiv s2 s3 -> stk_equiv s1 s3.\nProof.\ninduction s1.\ndestruct s2;intros. assumption. destruct H.\n\ndestruct s2.\nintros. destruct a. simpl in H. destruct H.\nintros. destruct s3. destruct f. simpl in H0. destruct H0.\ndestruct a.\ndestruct f.\ndestruct f0.\nsimpl in * |- *.\nintuition.\ncongruence.\nequate_maps.\neauto.\nQed.\n\nAdd Relation (list Frame) stk_equiv\n  reflexivity proved by stk_equiv_refl\n  symmetry proved by stk_equiv_sym\n  transitivity proved by stk_equiv_trans\n  as stk_equiv_rel.\n\n(** Now proof automation *)\n\n\n\nCreate HintDb step_hints discriminated.\nCreate HintDb done_hints discriminated.\n(* f_equal ? *)\nHint Resolve stk_equiv_refl : step_hints done_hints.\nHint Extern 2 (_ ~= _) => equate_maps : step_hints done_hints.\nHint Extern 1 (@eq Z ?l ?r) =>\n  (has_evar l;fail 1) || (has_evar r;fail 1) || solve[ring] : step_hints done_hints.\nLtac step_solver := econstructor (solve[simpl;try reflexivity;eauto with step_hints]);idtac.\n\n(* The tactic trans_applies succeed if there is any claim in the set of\n   claims being proved whose expectation for the kcell matches the current code\n *)\nLtac trans_applies := econstructor(\n  match goal with [|- kcell _ = _] => reflexivity || fail 1 | _ => idtac end).\n\n(* The transitivity tactic tries to apply any claim whose preconditions\n   can be met as a transitivity.\n   If one applies, it uses the supplied \"trans_use_result\" tactic to extract hypothesis\n   from the conclusion, and get the goal back into the form of a simple\n   \"dtrans\" claim for further proof search.\n   (if trans_use result tactic succeeds but doesn't get things into the right form,\n   execution will be paused at that point (with the transitivity already taken)\n   for the user to do it, because trying to automatically take another step will fail.\n\n   If no claim applies, it then checks for a claim that matches the current\n   code but couldn't be used automatically, and pauses for the user\n   (assuming that the claim should work, and the prover just failed).\n\n   Otherwise, it returns to the main proof search tactic.   \n *)\nLtac trans_solver := econstructor(simpl;\n  solve [reflexivity\n  |auto with zarith\n  |equate_maps]).\n\nLtac trans_use_result := idtac.\n\nLtac trans_tac :=\n  eapply dtrans;[solve[trans_solver] || (trans_applies;idtac \"pausing for trans\";fail 1)|]\n  ;try trans_use_result. (* if trans_solver succeeded, we commit to the transitivity *)\n\n(*\n  We evaluation becomes stuck on a symbolic boolean constant, we need to make\n  a case distinction on whether the constant is true or false so evaluation can\n  proceed, but we also need to add some new hypothesis(es) recording the fact\n  that the symbolic conclusion was true or false, in case the condition tested\n  will be important for finishing the proof later.\n\n  This handling might need to be refined a bit to work nicely with the predicates\n  needed in a particular specification, but some basic cases corresponding to\n  the boolean expressions in the language seems to work pretty well for now.\n *)\nLtac split_bool B :=\n  match B with\n    | (?x <? ?y)%Z => pose proof Zlt_cases x y;destruct B\n    | (?x <=? ?y)%Z => pose proof Zle_cases x y;destruct B\n    | (?x =? ?y)%Z =>\n        first[replace B with true\n          by (symmetry;apply Z.eqb_eq; (auto with zarith || ring || omega))\n             |replace B with false\n          by (symmetry;apply Z.eqb_neq; (auto with zarith || ring || omega))\n             |destruct (Z.eqb_spec x y)]\n    | (negb ?B') => split_bool B'\n  end.\n\n(*\n  The positions where evaluation may be stuck on a symbolic constant\n  are purely a function of the language. These could perhaps be computed\n  automatically by comparing evaluation rules.\n *)\nLtac split_tac :=\n  simpl;\n  match goal with\n  | [|- trans _ _ {| kcell := kra (KStmt (SIf (BCon ?B) _ _)) _ |} _ ] =>\n    split_bool B\n  | [|- trans _ _ {| kcell := kra (KExp (BAnd (BCon ?B) _)) _ |} _ ] =>\n    split_bool B\n  end;idtac.\n\nLtac done_solver := simpl;repeat split;try reflexivity;auto with done_hints zarith.\n\nLtac use_cfg_assumptions :=\n  match goal with\n    | [H : kcell ?v = _ |- _] =>\n      is_var v; destruct v; simpl in * |- ;\n      rewrite H in * |- *;clear H\n    | [H : _ /\\ _  |- _ ] => destruct H\n    | [H : ?l ~= _ |- ?G] =>\n         match G with\n         | context [?l] => fail 1\n         | _ => is_var l;rewrite H in * |- *;clear H l\n         end\n   end.\n\nLtac start_proving :=\n  let get_cfg_assumptions := (intros;repeat use_cfg_assumptions) in\n  get_cfg_assumptions;apply proved_sound;destruct 1;\n  simpl in * |-;get_cfg_assumptions.\n\n(* Pause execution if we ever end up with\n   a map equation between two variables,\n   or a non-decomposed pattern hypothesis *)\nLtac hyp_check :=\n  match goal with\n(*\n | [H : ?l ~= ?r |- _] => is_var l; is_var r\n   We can end up with irreducible equations between map variables,\n   if both are used in the goal, in places where we don't (yet)\n   know how to do setoid rewriting by ~=.\n\n   Especially happens with transitivity.   \n\n   Maybe just being able to rewrite in the current\n   configuration of \"trans\" would allow eliminating most of these?\n *)\n  | [H : (_ :* _) |= _ |- _] => idtac\n  | [H : _ |= _ :* _ |- _] => idtac\n  | [H : _ |= _ |-> _ |- _] => idtac\n  | [H : _ |= emptyP |- _] => idtac\n  end;fail 1.\n\nLtac generic_solver trans_tac step_solver done_solver split_stuck :=\n  start_proving;(eapply sstep;[solve [step_solver]|]);\n  generic_run trans_tac step_solver done_solver split_stuck.\n", "meta": {"author": "Formal-Systems-Laboratory", "repo": "coinduction", "sha": "1031da11c4a4523ea9b7347036b6bdabc7620e1d", "save_path": "github-repos/coq/Formal-Systems-Laboratory-coinduction", "path": "github-repos/coq/Formal-Systems-Laboratory-coinduction/coinduction-1031da11c4a4523ea9b7347036b6bdabc7620e1d/coinduction-proofs/himp/himp_tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4843800842769843, "lm_q1q2_score": 0.2535343927300652}}
{"text": "From Tealeaves.Classes Require Export\n  DT.Functor\n  Kleisli.DT.Functor.\n\nImport Kleisli.Decorated.Functor.\nImport Product.Notations.\nImport Comonad.Notations.\nImport DT.Functor.Notations.\n\n#[local] Generalizable Variables A B C.\n\nModule Operations.\n  Section with_kleisli.\n\n    Context\n      (E : Type)\n      (T : Type -> Type)\n      `{Fmapdt E T}.\n\n    #[export] Instance Dist_Fmapdt: Dist T := fun G _ _ _ A => fmapdt T G (extract (E ×)).\n    #[export] Instance Decorate_Fmapdt: Decorate E T := fun A => fmapdt T (fun A => A) (@id ((E ×) A)).\n\n  End with_kleisli.\nEnd Operations.\n\nImport Operations.\n\nModule Instances.\n\n  Section with_functor.\n\n    Context\n      (E : Type)\n      (T : Type -> Type)\n      `{Kleisli.DT.Functor.DecoratedTraversableFunctor E T}.\n\n    Import Kleisli.DT.Functor.Derived.\n\n    Lemma dec_dec : forall (A : Type),\n        dec T ∘ dec T = fmap T (cojoin (E ×)) ∘ dec T (A := A).\n    Proof.\n      intros.\n      unfold_ops @Decorate_Fmapdt.\n      change_left (fmapd T (@id (E * (E * A))) ∘ fmapd T id).\n      rewrite (dfun_fmapd2 E T).\n      change_right (fmap T (coμ (prod E)) ∘ fmapd T (@id (E * A))).\n      rewrite (fmap_fmapd T).\n      fequal. now ext [e a].\n    Qed.\n\n    Lemma dec_extract : forall (A : Type),\n        fmap T (extract (E ×)) ∘ dec T = @id (T A).\n    Proof.\n      intros.\n      unfold_ops @Decorate_Fmapdt.\n      unfold_ops @Fmap_Fmapdt.\n      change_left (fmapd T (extract (prod E) ∘ extract (prod E)) ∘ fmapd T (@id (E * A))).\n      rewrite (dfun_fmapd2 E T).\n      reassociate ->. rewrite (extract_cobind (E ×)).\n      apply (dfun_fmapd1 E T).\n    Qed.\n\n    Lemma dec_natural : Natural (@dec E T _).\n    Proof.\n      constructor.\n      - typeclasses eauto.\n      - typeclasses eauto.\n      - intros. unfold_ops @Fmap_compose.\n        unfold_ops @Fmap_Fmapdt.\n        unfold_ops @Decorate_Fmapdt.\n        change\n          (fmapd T (fmap (prod E) f ∘ extract (prod E)) ∘ fmapd T id =\n             fmapd T id ∘ fmapd T (f ∘ extract (prod E))).\n        rewrite (dfun_fmapd2 E T).\n        rewrite (dfun_fmapd2 E T).\n        reassociate ->. rewrite (extract_cobind (E ×)).\n        now rewrite <- (fmap_to_cobind (E ×)).\n    Qed.\n\n    #[export] Instance: Classes.Decorated.Functor.DecoratedFunctor E T :=\n      {| dfun_dec_natural := dec_natural;\n         dfun_dec_dec := dec_dec;\n         dfun_dec_extract := dec_extract;\n      |}.\n\n  (** *** Traversable functor instance *)\n  (******************************************************************************)\n  Lemma dist_natural_T : forall (G : Type -> Type) (H2 : Fmap G) (H3 : Pure G) (H4 : Mult G),\n      Applicative G -> Natural (@dist T _ G H2 H3 H4).\n  Proof.\n    intros. constructor.\n    - typeclasses eauto.\n    - typeclasses eauto.\n    - intros.\n      unfold_ops @Fmap_compose @Dist_Fmapdt @Fmap_Fmapdt.\n      change (@fmapdt E T _ (fun A0 : Type => A0) _ _ _)\n        with (@fmapd E T _).\n      rewrite (fmapd_fmapdt T G).\n      rewrite (fmapdt_fmapd T G).\n      rewrite (cokleisli_id_l).\n      rewrite (cobind_id (E ×)).\n      unfold id. fequal.\n      ext [e a]. unfold compose. cbn.\n      compose near a on left.\n      rewrite (fun_fmap_fmap G).\n      reflexivity.\n  Qed.\n\n  Lemma dist_morph_T : forall (G1 G2 : Type -> Type) (H2 : Fmap G1) (H3 : Pure G1) (H4 : Mult G1) (H5 : Fmap G2)\n                         (H6 : Pure G2) (H7 : Mult G2) (ϕ : forall A : Type, G1 A -> G2 A),\n      ApplicativeMorphism G1 G2 ϕ -> forall A : Type, dist T G2 ∘ fmap T (ϕ A) = ϕ (T A) ∘ dist T G1.\n  Proof.\n    intros. unfold_ops @Dist_Fmapdt @Fmap_Fmapdt.\n      change (@fmapdt E T _ (fun A0 : Type => A0) _ _ _)\n        with (@fmapd E T _).\n      inversion H1.\n      rewrite (fmapdt_fmapd T G2).\n      rewrite <- (kdtfun_morph E T).\n      rewrite (cokleisli_id_l).\n      reflexivity.\n  Qed.\n\n  Lemma dist_unit_T : forall A : Type,\n      dist T (fun A0 : Type => A0) = @id (T A).\n  Proof.\n    intros. unfold_ops @Dist_Fmapdt.\n    now rewrite (kdtfun_fmapdt1 E T).\n  Qed.\n\n  Lemma dist_linear_T : forall (G1 : Type -> Type) (H2 : Fmap G1) (H3 : Pure G1) (H4 : Mult G1),\n      Applicative G1 ->\n      forall (G2 : Type -> Type) (H6 : Fmap G2) (H7 : Pure G2) (H8 : Mult G2),\n        Applicative G2 -> forall A : Type, dist T (G1 ∘ G2) (A := A) = fmap G1 (dist T G2) ∘ dist T G1.\n  Proof.\n    intros. unfold_ops @Dist_Fmapdt.\n    rewrite (kdtfun_fmapdt2 E T).\n    fequal.\n    change (extract (E ×) (A := G1 (G2 A))) with (id (A := G1 (G2 A)) ∘ extract (E ×)).\n    rewrite kcompose_dt_32.\n    rewrite (fun_fmap_id (E ×)).\n    ext [e a]. unfold compose; cbn.\n    compose near a.\n    rewrite (fun_fmap_fmap G1).\n    rewrite (fun_fmap_id G1).\n    reflexivity.\n  Qed.\n\n  #[export] Instance: Classes.Traversable.Functor.TraversableFunctor T :=\n    {| dist_natural := dist_natural_T;\n       dist_morph := dist_morph_T;\n       dist_unit := dist_unit_T;\n       dist_linear := dist_linear_T;\n    |}.\n\n  Lemma dtfun_compat_T : forall (G : Type -> Type) (H2 : Fmap G) (H3 : Pure G) (H4 : Mult G),\n      Applicative G -> forall A : Type,\n        dist T G ∘ fmap T (strength G) ∘ dec (A := G A) T = fmap G (dec T) ∘ dist T G.\n  Proof.\n    intros. unfold_ops @Dist_Fmapdt @Fmap_Fmapdt @Decorate_Fmapdt.\n      change (@fmapdt E T _ (fun A0 : Type => A0) _ _ _)\n        with (@fmapd E T _).\n      rewrite (fmapd_fmapdt T G).\n      rewrite (fmapdt_fmapd T G).\n      rewrite (fmapdt_fmapd T G).\n      rewrite (cobind_id (E ×)).\n      rewrite (fun_fmap_id G).\n      fequal. ext [e a].\n      reflexivity.\n  Qed.\n\n  #[export] Instance: Classes.DT.Functor.DecoratedTraversableFunctor E T :=\n    {| dtfun_compat := dtfun_compat_T;\n    |}.\n\n  End with_functor.\n\nEnd Instances.\n\n#[local] Generalizable Variables E T.\n\nModule AlgebraicToKleisli.\n\n  Context\n    `{fmapT : Fmap T}\n    `{distT : Dist T}\n    `{decorateT : Decorate E T}\n    `{! DT.Functor.DecoratedTraversableFunctor E T}.\n\n  #[local] Instance fmapdt' : Fmapdt E T := ToKleisli.Fmapdt_distdec E T.\n\n  Definition fmap' : Fmap T := Derived.Fmap_Fmapdt T.\n  Definition decorate' : Decorate E T := Operations.Decorate_Fmapdt E T.\n  Definition dist' : Dist T := Operations.Dist_Fmapdt E T.\n\n  Goal fmapT = fmap'.\n  Proof.\n    unfold fmap'. unfold_ops @Derived.Fmap_Fmapdt.\n    unfold fmapdt, fmapdt'.\n    unfold_ops @ToKleisli.Fmapdt_distdec.\n    ext A B f.\n    rewrite (dist_unit T).\n    rewrite <- (fun_fmap_fmap T).\n    reassociate -> on right.\n    reassociate -> on right.\n    rewrite (dfun_dec_extract E T).\n    reflexivity.\n  Qed.\n\n  Goal distT = dist'.\n  Proof.\n    unfold dist'. unfold_ops @Operations.Dist_Fmapdt.\n    unfold fmapdt, fmapdt'.\n    unfold_ops @ToKleisli.Fmapdt_distdec.\n    ext G Hmap Hpure Hmult. ext A.\n    reassociate -> on right.\n    rewrite (dfun_dec_extract E T).\n    reflexivity.\n  Qed.\n\n  Goal decorateT = decorate'.\n  Proof.\n    unfold decorate'. unfold_ops @Operations.Decorate_Fmapdt.\n    unfold fmapdt, fmapdt'.\n    unfold_ops @ToKleisli.Fmapdt_distdec.\n    ext A.\n    rewrite (dist_unit T).\n    now rewrite (fun_fmap_id T).\n  Qed.\n\nEnd AlgebraicToKleisli.\n\nModule KleisliToAlgebraic.\n\n  Context\n    `{fmapdtT : Fmapdt E T}\n    `{@Classes.Kleisli.DT.Functor.DecoratedTraversableFunctor E T _}.\n\n  #[local] Instance fmap' : Fmap T := Derived.Fmap_Fmapdt T.\n  #[local] Instance dist' : Dist T := Operations.Dist_Fmapdt E T.\n  #[local] Instance decorate' : Decorate E T := Operations.Decorate_Fmapdt E T.\n\n  Definition fmapdt' : Fmapdt E T := ToKleisli.Fmapdt_distdec E T.\n\n  Import Derived.\n\n  Goal forall G `{Applicative G}, @fmapdtT G _ _ _ = @fmapdt' G _ _ _.\n  Proof.\n    intros.\n    unfold fmapdt'. unfold_ops @ToKleisli.Fmapdt_distdec.\n    unfold fmap, fmap', dist, dist', dec, decorate'.\n    ext A B f.\n    unfold_ops @Operations.Dist_Fmapdt.\n    unfold_ops @Derived.Fmap_Fmapdt.\n    unfold_ops @Operations.Decorate_Fmapdt.\n    change_right (fmapdt T G (extract (prod E)) ∘\n                    fmap T f ∘\n                    fmapd T id).\n    unfold fmap'.\n    change (@Derived.Fmap_Fmapdt T) with (@Derived.Fmap_Fmapdt T).\n    rewrite (fmapdt_fmap T G).\n    rewrite (fmapdt_fmapd T G).\n    fequal. ext [e a]. reflexivity.\n  Qed.\n\nEnd KleisliToAlgebraic.\n", "meta": {"author": "dunnl", "repo": "tealeaves", "sha": "8dd6ba8acdd097f6e474ae2a1a9b10f5cc9ca65b", "save_path": "github-repos/coq/dunnl-tealeaves", "path": "github-repos/coq/dunnl-tealeaves/tealeaves-8dd6ba8acdd097f6e474ae2a1a9b10f5cc9ca65b/Tealeaves/Classes/Equivalences/DT/Functor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.25346880792982424}}
{"text": "Require Export MMLL.SL.Syntax.\n\nSection SubExpSets.\n  Context `{SI : Signature}.\n  Context `{OLS : OLSig}.\n \n Definition SetX  (x:  subexp -> bool) (b:bool) (K : list TypedFormula):= Forall (fun k => x (fst k) = b) K.\n \n Definition LtX  i (K : list TypedFormula) := Forall (fun k => lt i (fst k)) K.\n  \n Global Instance perm_SetX A b :\n      Proper (@Permutation TypedFormula ==>  Basics.impl)\n             (SetX A b).\n    Proof.\n      unfold Proper; unfold respectful; unfold Basics.impl .\n      intros.\n      unfold SetX.\n      rewrite <- H;auto.\n    Qed.\n\nGlobal Instance perm_LtX a :\n      Proper (@Permutation TypedFormula ==>  Basics.impl)\n             (LtX a).\n    Proof.\n      unfold Proper; unfold respectful; unfold Basics.impl .\n      intros.\n      unfold LtX.\n      rewrite <- H;auto.\n    Qed.\n\n\n  Definition Loc (L:list TypedFormula):= \n        map (fun x => (loc,(snd x))) L.\n  Global Instance perm_Loc :\n      Proper (@Permutation TypedFormula ==> @Permutation TypedFormula)\n             (Loc ).\n    Proof.\n      unfold Proper; unfold respectful.\n      intros.\n      unfold Loc.\n      rewrite <- H;auto.\n    Qed.\n    \n  Definition PlusT (L:list TypedFormula):=   \n        map (fun x => (plust (fst x),snd x) ) L.\n  Global Instance perm_PlusT :\n      Proper (@Permutation TypedFormula ==> @Permutation TypedFormula)\n             (PlusT ).\n    Proof.\n      unfold Proper; unfold respectful.\n      intros.\n      unfold PlusT.\n      rewrite <- H;auto.\n    Qed.\n  \n   Fixpoint getU  (l : list TypedFormula) :=\n  match l with\n  | [] => []\n  | (x,F) :: l0 => if u x then (x,F) :: (getU l0) else getU l0\n  end.\n  \n Fixpoint getL (l : list TypedFormula) :=\n  match l with\n  | [] => []\n  | (x,F) :: l0 => if u x then getL l0 else (x,F) :: (getL l0) \n  end.\n   \nEnd SubExpSets.\n\n Global Hint Unfold SetX LtX PlusT Loc first second: core.  \n\n(* Ltac sfold := \nrepeat\nmatch goal with\n | [  |- context[map (fun x => (loc,_)) ?K]] => change (map (fun x => (loc,_)) K) with (Loc K) \n | [  |- context[map (fun x => (plust _,_)) ?K]] => change (map (fun x => (plust _,_)) K) with (PlusT K)\n  | [  |- context[map snd ?L] ] => change (map snd L) with (second L)\n | [ H : context[map snd ?L] |- _ ] => fold (second L) in H\n  \n | [ H : context[map (fun x => (loc,_)) ?K] |- _ ] => fold (Loc K) in H  \n | [ H : context[map (fun x => (plust _,_)) ?K] |- _ ] => fold (PlusT K) in H \n(*  | [ H : context[Forall isFormula ?L] |- _ ] => fold (isFormulaL L) in H     *)            \nend. *)\n \n \n \nTactic Notation \"srewrite\" constr(H) := autounfold;\n let Hs := type of H in \n match Hs with\n| Permutation _ _ => try rewrite H\n                     \nend.\n\nTactic Notation \"srewrite_reverse\" constr(H) := autounfold;\n let Hs := type of H in \n match Hs with\n| Permutation _ _ => symmetry in H;try rewrite H\n                     \nend.\n\n\nTactic Notation \"srewrite\" constr(H1) \"in\" constr(H2) := \nautounfold in H2;\n let Hs := type of H1 in \n match Hs with\n| Permutation _ _ => try rewrite H1 in H2\n                     \nend.\n\nTactic Notation \"srewrite_reverse\" constr(H1) \"in\" constr(H2) := \nautounfold in H2;\n let Hs := type of H1 in \n match Hs with\n| Permutation _ _ => symmetry in H1; try rewrite H1 in H2\n                     \nend.\n\n Ltac simplSignature1 := \n  repeat \n    multimatch goal with\n  (* Basic simplifcation *)\n  | [  |- context[_ []] ] => simpl\n  | [ H: context[_ []]  |- _ ] => simpl in H\n \n | [ H: context[if u loc then _ else _] |- _ ] => rewrite locu in H\n | [ H: context[if mt loc then _ else _] |- _ ] => rewrite locT in H\n | [ H: context[if md loc then _ else _] |- _ ] => rewrite locD in H\n | [ H: context[if m4 loc then _ else _] |- _ ] => rewrite loc4 in H\n | [ H: context[if mk loc then _ else _] |- _ ] => rewrite locK in H\n | [ |- context[if u loc then _ else _]  ] => rewrite locu \n | [ |- context[if mt loc then _ else _] ] => rewrite locT \n | [ |- context[if md loc then _ else _] ] => rewrite locD \n | [ |- context[if m4 loc then _ else _] ] => rewrite loc4 \n | [ |- context[if mk loc then _ else _] ] => rewrite locK \n\n  | [ H1: u (fst ?F) = _, H2: context[_(?F :: _)] |- _ ] => \n     destruct F;simpl in H1;simpl in H2; try rewrite H1 in H2 \n  | [ H: u (fst ?F) = _ |- context[_ (?F :: _)] ] => \n     destruct F;simpl;simpl in H; try rewrite H \n | [ H1: ?s ?a = _, H2: context[if ?s ?a then _ else _] |- _ ] => rewrite H1 in H2 \n | [ H: ?s ?a = _|- context[if ?s ?a then _ else _] ] => rewrite H \n\n(* About second *)\n | [ H: context[second(_++_)] |- _ ] => rewrite secondApp in H \n | [ |- context[second(_++_)] ] => rewrite secondApp\n \n | [  |- context[_ (_::_)] ] => simpl\n  | [ H: context[_ (_::_)] |- _ ] => simpl in H \n\n  end.\n\n \n Ltac solveSignature1 := try\n  match goal with\n  | [ H1: UnbNoDSignature, H2: md _ = true |- _ ] => rewrite allNoD in H2;discriminate H2 \n  | [ H: UnbSignature |- u ?i = true ] => apply allU \n  | [ H: md ?i = true |- ?i <> loc ] => apply locNoD;auto \n  | [ H: m4 ?i = true |- ?i <> loc ] => apply locNo4;auto \n  | [ H: mt ?i = false |- ?i <> loc ] => apply locTDiff;auto \n  | [ H: u ?i = false |- ?i <> loc ] => apply locUDiff;auto \n\n  | [ |- lt ?i ?i] => apply @PreOrder_Reflexive; exact lt_pre\n  | [ |- u loc = true ] => apply locu \n  | [ |- mt loc = true ] => apply locT \n  | [ |- m4 loc = false ] => apply loc4 \n  | [ |- mk loc = true ] => apply locK \n  | [ |- md loc = false ] => apply locD\n  \n  | [ |- mt (plust _) = true ] => apply T_in_plust\n  | [ |- subexp ] => exact loc\n    \n  | [H: u loc = false |- _] => rewrite locu in H; discriminate H   \n  | [H: mk loc = false |- _] => rewrite locK in H; discriminate H  \n  | [H: mt loc = false |- _] => rewrite locT in H; discriminate H  \n  | [H: m4 loc = true |- _] => rewrite loc4 in H; discriminate H  \n  | [H: md loc = true |- _] => rewrite locD in H; discriminate H  \n\n  | [H1: ?a <> loc, H2: lt ?a loc |- _] => apply locAlone in H1;assert(False); [apply H1;left;auto|];contradiction\n  | [H1: ?a <> loc, H2: lt loc ?a |- _] => apply locAlone in H1;assert(False); [apply H1;right;auto|];contradiction\n    \n   | [H: SetX ?a ?b (?F::?K) |- ?a (fst ?F) = ?b] => inversion H;subst;auto\n   | [H: SetX ?a ?b ((?s, _)::?K) |- ?a ?s = ?b] => inversion H;subst;auto\n  \n   | [H: _ ?i (?F::?K) |- lt ?i (fst ?F) ] => inversion H;subst;intuition\n   | [H: _ ?i ((?s, _)::?K) |- lt ?i ?s ] => inversion H;subst;intuition\n   \n  end.\n  \n Ltac solveLocation :=simplSignature1; try solve [solveSignature1]; autounfold in *;solveForall.\n \n\nSection Properties.\n  Context `{SI : Signature}.\n  Context `{OLS : OLSig}.\n       \n  Lemma locSetK1 sub a b F: sub a = b -> SetX sub b [(a, F)].\n  Proof with solveLocation.\n  constructor... \n  Qed.\n\n   \n(*   Lemma locSetK2 i F: i <> loc -> ~ SetK i [(loc, F)]. *)\n  \n  Lemma locSetK4 F:  ~ SetX m4 true [(loc, F)].\n  Proof with sauto.\n  intro.\n  inversion H...\n  solveLocation.\n  Qed.\n \n  Lemma locSetD F:  ~ SetX md true [(loc, F)].\n  Proof with sauto.\n  intro.\n  inversion H...\n  solveLocation.\n  Qed.\n  \n  Lemma locSetU F : SetX u true [(loc, F)].\n  Proof.\n  solveLocation.\n  simpl. solveSubExp. \n  Qed.\n \n (* Local Hint Resolve locSetX:core.\n *)\n  \n  Lemma locSetT F : SetX mt true [(loc, F)].\n  Proof.\n  unfold SetX.\n  constructor;auto. \n  simpl. solveSubExp. \n  Qed.\n  \n  Lemma locApp K1 K2: Loc (K1 ++ K2) = Loc K1 ++ Loc K2.\n  Proof.\n  apply map_app.\n   Qed.\n \n  Lemma PlusTApp K1 K2: PlusT (K1 ++ K2) = PlusT K1 ++ PlusT K2.\n  Proof.\n  apply map_app.\n   Qed.\n \n Lemma locApp' K1 K2 : Permutation (Loc (K1 ++ K2)) (Loc K1 ++ Loc K2).\n  Proof.\n  solveLocation.\n  rewrite map_app;auto.\n  Qed.\n \n Lemma PlusTApp' K1 K2: Permutation (PlusT (K1 ++ K2)) (PlusT K1 ++ PlusT K2).\n  Proof.\n  unfold PlusT.\n  rewrite map_app;auto.\n   Qed.\n   \n   Lemma SetU_then_empty K : SetX u true K -> getL K =[].\n   Proof with sauto.\n  induction K;intros...\n  destruct a as [p F].\n  inversion H...\n  simpl. rewrite H2...\n  Qed. \n  \n    \n   Lemma SetL_then_empty K : SetX u false K -> getU K =[].\n   Proof with sauto.\n  induction K;intros...\n  destruct a as [p F].\n  inversion H...\n  simpl. rewrite H2...\n  Qed. \n\n  \n  Lemma MapPlusT_fixpoint : forall C , PlusT (PlusT C) = (PlusT C).\n  Proof with subst;auto.\n  induction C;simpl;intros;auto.\n  rewrite plust_plust_fixpoint...\n  rewrite IHC...\n  Qed.\n \n     \n  Lemma SetTPlusT K: SetX mt true K -> PlusT K = K.\n   Proof with sauto.\n   induction K;intros...\n   destruct a;simpl.\n   inversion H...\n   apply plustpropT in H2.\n   rewrite H2.\n   rewrite IHK;auto.\n Qed.\n\n   Lemma SetKRef a F: LtX a [(a, F)].\n  Proof with sauto.\n  apply Forall_cons... \n  apply @PreOrder_Reflexive.\n  exact lt_pre.\n  Qed.\n\n   Lemma SetKTrans i a K : LtX i K -> lt a i -> LtX a K.\n  Proof with sauto.\n  induction K;simpl;intros...\n  inversion H...\n  apply Forall_cons... \n  apply @PreOrder_Transitive with (R:=lt) (y:=i);auto.\n  exact lt_pre.\n  apply IHK...\n  Qed.\n\n  Global Instance trans_SetK :\n       Proper (lt ==> @Permutation TypedFormula ==> Basics.flip Basics.impl)\n             (LtX ).\n    Proof.\n      unfold Proper; unfold respectful; unfold Basics.flip; unfold Basics.impl .\n      intros;subst.\n      rewrite H0.\n      eapply (SetKTrans _ _ _ H1);auto. \n    Qed.\n  \n  Lemma SetKK4_then_empty' i K : SetX m4 false K -> LtX i K -> m4 i = true -> K=[].\n  Proof with sauto.\n  destruct K;intros...\n  destruct t as [p F].\n  inversion H...\n  assert(m4 p = true).\n  {\n  eapply m4Closure.\n  exact H1. inversion H0...  }\n  sauto.\n  Qed.\n  \n  Lemma SetUL_then_empty' i K : SetX u false K -> LtX i K -> u i = true -> K=[].\n  Proof with sauto.\n  destruct K;intros...\n  destruct t as [p F].\n  inversion H...\n  assert(u p = true).\n  {\n  eapply uClosure.\n  exact H1. inversion H0...  }\n  sauto.\n  Qed.\n  \n  \n    Lemma SetTKClosure i sub K  : (forall x y : subexp,\n       sub x = true -> lt x y -> sub y = true) -> sub i = true -> LtX i K -> SetX sub true K. \n  Proof with sauto.\n  intros.\n  induction K;intros... \n  inversion H1...\n  apply Forall_cons...\n  eapply H. \n  exact H0. exact H4.\n  apply IHK...\n  Qed.\n  \n(*   Check SetTKClosure _ u _ uClosure . *)\n  Lemma SetUKClosure i K  : u i = true -> LtX i K -> SetX u true K. \n  Proof with sauto.\n  intros.\n  apply SetTKClosure with (i:=i)...\n  exact uClosure.\n  Qed.\n\n Lemma SetK4Closure i K  : m4 i = true -> LtX i K -> SetX m4 true K. \n  Proof with sauto.\n  induction K;intros... \n  inversion H0...\n  apply Forall_cons...\n  eapply m4Closure. \n  exact H. exact H3.\n  apply IHK...\n  Qed.\n\nLemma SetDClosure i K  : md i = true -> LtX i K -> SetX md true K. \n  Proof with sauto.\n  induction K;intros... \n  inversion H0...\n  apply Forall_cons...\n  eapply mdClosure. \n  exact H. exact H3.\n  apply IHK...\n  Qed.\n\n Lemma SetK4In sub a K: SetX sub true K -> In a K -> sub (fst a) = true.\n  Proof with sauto.\n  intros.\n  eapply @ForallIn with (F:=a) in H...\n  Qed.\n \n \n  Lemma SetKK4_then_empty sub K : SetX sub true K -> SetX sub false K -> K=[].\n   Proof with sauto.\n  destruct K;intros...\n  destruct t as [p F].\n  inversion H...\n  inversion H0...\n  Qed. \n  \n  Theorem cxtDestruct K: Permutation K (getU K++getL K).\n Proof with subst;auto.\n induction K;auto.\n destruct a as [a F].\n destruct (uDec a); simpl; rewrite e.\n constructor;auto.\n apply Permutation_cons_app;auto.\n Qed.\n \n  Theorem cxtDestructSecond K: Permutation (second K) (second (getU K++getL K)).\n Proof with subst;auto.\n induction K;auto.\n destruct a as [a F].\n destruct (uDec a); simpl; rewrite e.\n constructor;auto.\n rewrite secondApp.\n simpl.\n apply Permutation_cons_app;auto.\n rewrite <- secondApp;auto.\n Qed.\n\n Theorem cxtDestruct' K: exists K1 K2, Permutation K (getU K++getL K1 ++ getL K2) /\\ Permutation (getL K) (getL K1 ++ getL K2).\n Proof with sauto.\n induction K...\n exists [].\n exists [].\n simpl;auto.\n destruct a as [a F].\n destruct (uDec a); simpl;\n rewrite e;simpl.\n exists x. exists x0.\n constructor;auto.\n exists ((a,F)::x).\n  exists x0.\n  simpl; rewrite e;simpl.\n  constructor;auto.\n apply Permutation_cons_app;auto.\n Qed.\n \n Lemma getUPerm K1 K2 : Permutation K1 K2 -> Permutation (getU K1) (getU K2).\nProof with subst;auto.\n revert dependent K2.\n revert dependent K1.\n induction 1;intros. \n * simpl...\n * destruct x as [x F];\n   destruct (uDec x);\n   simpl;rewrite e...\n * destruct x as [x F];\n   destruct y as [y G];\n   destruct (uDec x);\n   destruct (uDec y);\n   simpl;rewrite e;rewrite e0...  \n   apply perm_swap.\n * eapply (Permutation_trans IHPermutation1 IHPermutation2). Qed.\n \n  Lemma getLPerm K1 K2 : Permutation K1 K2 -> Permutation (getL K1) (getL K2).\nProof with subst;auto.\n revert dependent K2.\n revert dependent K1.\n induction 1;intros. \n * simpl...\n * destruct x as [x F];\n   destruct (uDec x);\n   simpl;rewrite e...\n * destruct x as [x F];\n   destruct y as [y G];\n   destruct (uDec x);\n   destruct (uDec y);\n   simpl;rewrite e;rewrite e0...  \n   apply perm_swap.\n * eapply (Permutation_trans IHPermutation1 IHPermutation2). Qed.\n\n  Global Instance getU_morph :\n      Proper ((@Permutation TypedFormula) ==> (@Permutation TypedFormula))\n             (getU ).\n    Proof.\n    unfold Proper; unfold respectful.\n    intros. \n    apply getUPerm;auto.\n    Qed. \n  \n    Global Instance getL_morph :\n      Proper ((@Permutation TypedFormula) ==> (@Permutation TypedFormula))\n             (getL ).\n    Proof.\n    unfold Proper; unfold respectful.\n    intros. \n    apply getLPerm;auto.\n    Qed. \n    \n     \n  Lemma getU_fixpoint K : getU(getU K) =  getU K.\n  Proof.\n  induction K;auto.\n  destruct a;simpl;auto.\n  destruct (uDec s);rewrite e;auto;\n  simpl; rewrite e.\n  rewrite IHK; auto.\n Qed.\n  \n    Lemma getL_fixpoint K : getL(getL K) =  getL K.\n  Proof.\n  induction K;auto.\n  destruct a;simpl;auto.\n  destruct (uDec s);rewrite e;auto;\n  simpl; rewrite e.\n  rewrite IHK; auto.\n Qed.  \n \n  Lemma getUgetL K : getU(getL K) =  [].\n  Proof.\n  induction K;auto.\n  destruct a;simpl;auto.\n  destruct (uDec s);rewrite e;auto;\n  simpl; rewrite e.\n  rewrite IHK; auto.\n Qed.\n  \n  Lemma getLgetU K : getL(getU K) =  [].\n  Proof.\n   induction K;auto.\n  destruct a;simpl;auto.\n  destruct (uDec s);rewrite e;auto;\n  simpl; rewrite e.\n  rewrite IHK; auto.\n  Qed.\n\n \n  Lemma getUApp K1 K2 : getU (K1 ++ K2) =  getU K1 ++ getU K2.\n  Proof.\n    induction K1;auto.\n  destruct a;simpl;auto.\n  destruct (uDec s);rewrite e;auto;\n  simpl.\n  rewrite IHK1; auto.\n   Qed.\n \n \n Lemma getUApp' K1 K2 : Permutation (getU (K1 ++ K2)) (getU K1 ++ getU K2).\n  Proof.\n  rewrite getUApp;auto.\n  Qed. \n \n Lemma uIngetU i F B :  u i = true -> In (i, F) B -> In (i, F) (getU B).\n Proof with sauto.\n  intros.\n  rewrite cxtDestruct in H0.\n  apply in_app_or in H0.\n  destruct H0;auto.\n  induction B...\n  destruct a.\n  destruct(uDec s); simpl in *.\n  rewrite e in *...  firstorder. \n  rewrite e in *...\n  inversion H0...\n Qed.\n \n  Lemma getLApp K1 K2 : getL (K1 ++ K2) =  getL K1 ++ getL K2.\n  Proof.\n  induction K1;auto.\n  destruct a;simpl;auto.\n  destruct (uDec s);rewrite e;auto.\n  simpl. \n  rewrite IHK1. auto.\n Qed.\n  \n Lemma getLApp' K1 K2 : Permutation (getL (K1 ++ K2)) (getL K1 ++ getL K2).\n  Proof.\n  rewrite getLApp;auto.\n  Qed. \n\nLemma lIngetL i F B :  u i = false -> In (i, F) B -> In (i, F) (getL B).\n Proof with sauto.\n  intros.\n  rewrite cxtDestruct in H0.\n  apply in_app_or in H0.\n  destruct H0;auto.\n  induction B...\n  destruct a.\n  destruct(uDec s); simpl in *;\n  rewrite e in *...\n  simpl in H0...\n  firstorder.\n Qed.\n\nLemma lIngetU i F B :  u i = true -> In (i, F) B -> In (i, F) (getU B).\n Proof with sauto.\n  intros.\n  rewrite cxtDestruct in H0.\n  apply in_app_or in H0.\n  destruct H0;auto.\n  induction B...\n  destruct a.\n  destruct(uDec s); simpl in *;\n  rewrite e in *...\n  simpl in H0...\n  firstorder.\n  inversion H0...\n Qed.\n\n\n  Theorem getUtoSetU K: SetX u true (getU K).\n Proof with subst;auto.\n induction K...  \n apply Forall_nil.\n destruct a as [a F].\n simpl.\n destruct (uDec a); simpl;\n rewrite e...\n Qed.\n \n   Theorem getLtoSetU K: SetX u true (getL K) -> getL K =[].\n Proof with sauto.\n induction K;intros. \n * auto.\n * destruct a as [a F].\n   destruct (uDec a); simpl in *;\n  rewrite e in *...\n  inversion H...\n Qed.\n \n \n Lemma getUPerm_SetU K X : Permutation (getU K) X -> SetX u true X.\n  Proof.\n  intros.\n  symmetry in H.\n  srewrite  H.\n  apply getUtoSetU.\n Qed. \n \n\n \n  Theorem getLtoSetL K: SetX u false (getL K).\n Proof with subst;auto.\n induction K...\n apply Forall_nil.\n \n destruct a as [a F].\n simpl.\n destruct (uDec a); simpl;\n rewrite e...\n Qed.\n \n  Lemma getLPerm_SetL K X : Permutation (getL K) X -> SetX u false X.\n  Proof.\n  intros.\n  symmetry in H.\n  srewrite H.\n  apply getLtoSetL.\n Qed. \n \n  Theorem setUtoGetU K: SetX u true K -> getU K = K.\n Proof with subst;auto.\n induction K; intros...\n destruct a as [a F].\n inversion H...\n apply IHK in H3.\n simpl in *. rewrite H2...\n rewrite H3...\n Qed.\n\n  Theorem setLtoGetL K: SetX u false K -> getL K = K.\n Proof with subst;auto.\n\n induction K; intros...\n destruct a as [a F].\n inversion H...\n apply IHK in H3.\n simpl in *. rewrite H2...\n rewrite H3...\n Qed.\n \n   Lemma getUPermU K1 K2 : Permutation (getU K1) K2 -> Permutation (getU K1) (getU K2).\nProof with sauto.\n intros.\n rewrite H.\n apply getUPerm_SetU in H.\n rewrite cxtDestruct...\n rewrite (SetU_then_empty _ H)...\n rewrite setUtoGetU...\n rewrite setUtoGetU...\n Qed.\n \n Theorem Unb_Lin_Disj' K: exists K1 K2, SetX u true K1 /\\ SetX u false K2 /\\ Permutation K (K1++K2).\n Proof with subst;solveLocation;auto .\n induction K;auto.\n do 2 eexists [];simpl...\n destruct IHK.\n destruct H.\n decompose [and] H ;clear H.\n destruct a as [a F].\n destruct (uDec a).\n eexists ((a,F)::x).\n eexists x0.\n split... \n eexists x.\n eexists ((a,F)::x0).\n split... \n split...  \n rewrite H3... apply Permutation_middle.\n Qed.\n \n(* Lemmata about SetK *) \n  \n  (*  Lemma SetKPlusT' a K: SetK (plust a)  K -> SetX mk true K.\n  Proof with sauto.\n  induction K;intros;auto.\n\n  destruct a0 as [p F].\n  inversion H...\n \n  apply IHK in H3;auto.\n  apply Forall_cons...\n  apply @PreOrder_Transitive with (R:=lt) (y:=(plust a));auto.\n  exact lt_pre.\n  apply plust_incL. \n  apply @PreOrder_Reflexive.\n  exact lt_pre.\n  Qed.\n   *)\n   \n  Lemma SetKPlusT b K: SetX mk b K ->  SetX mk b (PlusT K).\n  Proof with sauto.\n  induction K;simpl;intros;auto.\n\n  destruct a as [p F].\n  inversion H...\n  apply Forall_cons;simpl;auto.\n  do 2 rewrite allK...\n apply IHK...\n  Qed.\n  \n  \n    Lemma SetK4PlusT b K: SetX m4 b K ->  SetX m4 b (PlusT K).\n  Proof with sauto.\n  induction K;simpl;intros;auto.\n\n  destruct a as [p F].\n  inversion H...\n  apply Forall_cons;simpl;auto. \n  apply plust_keeping4;auto.\n apply IHK...\n  Qed.\n\n   Lemma SetK4PlusT' b K: SetX m4 b (PlusT K)  -> SetX m4 b K.\n  Proof with sauto.\n  induction K;simpl;intros;auto.\n   apply Forall_cons...\n    apply  Forall_inv in H...\n    apply plust_keeping4';auto.\n    apply  Forall_inv_tail in H...\n  Qed.\n\n\n  Lemma SetUPlusT b K: SetX u b K ->  SetX u b (PlusT K).\n  Proof with sauto.\n  induction K;simpl;intros;auto.\n    destruct a as [p F].\n    inversion H...\n    apply Forall_cons...  \n    apply plust_keepingu... \n  Qed.\n\n Lemma PlusTSetU b K: SetX u b (PlusT K) -> SetX u b K.\n  Proof with sauto.\n  induction K;simpl;intros;auto.\n    apply Forall_cons...\n    apply  Forall_inv in H...\n    apply plust_keepingu';auto.\n    apply  Forall_inv_tail in H...\n  Qed.\n  \n  Lemma SetUDec sub K :  {SetX sub true K} + {~ SetX sub true K}.\n  Proof with sauto.\n    induction K;simpl;auto.\n    destruct IHK.\n    - destruct a as [p F]... \n      destruct (subDec sub p). \n      left.  apply Forall_cons...\n      right. intro.\n      inversion H...\n    - destruct a as [p F]. \n      destruct (subDec sub p).\n      right. intro. inversion H... \n      right. intro.\n      inversion H... \n Qed.\n \n \n  Lemma SetULoc K: SetX u true (Loc K).\n  Proof with sauto.\n  induction K;simpl;intros;auto.\n    destruct a as [p F].\n    simpl.\n    apply Forall_cons...\n    apply locu.  \n Qed.\n \n   Lemma SetTLoc K: SetX mt true (Loc K).\n  Proof with sauto.\n  induction K;simpl;intros;auto.\n    destruct a as [p F].\n    simpl.\n    apply Forall_cons...\n    apply locT.  \n Qed.\n \n  \n  Lemma getLPlusT K: SetX mt true K -> getL K = getL (PlusT K).\n  Proof with sauto.\n  induction K. \n  * simpl;auto.\n  * destruct a as [p F].\n    destruct (uDec p);intros.\n    - simpl. rewrite e.\n      apply plust_keepingu in e.\n      rewrite e.\n      apply IHK.\n      inversion H...\n    - simpl. rewrite e.\n      apply plust_keepingu in e.\n      rewrite e.\n      rewrite IHK.\n      apply  Forall_inv in H...\n      rewrite plustpropT;auto.\n      apply  Forall_inv_tail in H...\n  Qed.\n \n   Lemma getUPlusT K: SetX mt true K -> getU K = getU (PlusT K).\n  Proof with sauto.\n  induction K. \n  * simpl;auto.\n  * destruct a as [p F].\n    destruct (uDec p);intros.\n    - simpl. rewrite e.\n      apply plust_keepingu in e.\n      rewrite e.\n      rewrite IHK.\n      apply  Forall_inv in H...\n      rewrite plustpropT;auto.\n      apply  Forall_inv_tail in H...\n - simpl. rewrite e.\n      apply plust_keepingu in e.\n      rewrite e.\n      apply IHK.\n      inversion H...      \n  Qed.\n \n Lemma getLEPlusT K: getL K = [] <-> getL (PlusT K) = [].\n  Proof with sauto.\n  split;intros.\n  * induction K...\n    destruct a as [p F].\n    destruct (uDec p);intros.\n    - simpl in H. rewrite e in H.\n      apply plust_keepingu in e.\n      simpl.\n      rewrite e...\n    - simpl in H. rewrite e in H...\n  * induction K...\n    destruct a as [p F].\n    destruct (uDec p);intros.\n    - simpl. rewrite e.\n      simpl in H.\n      apply plust_keepingu in e.\n      rewrite e in H...\n    -  simpl in H.\n      apply plust_keepingu in e.\n      rewrite e in H... \nQed.\n\n Lemma getUEPlusT K: getU K = [] <-> getU (PlusT K) = [].\n  Proof with sauto.\n  split;intros.\n  * induction K...\n    destruct a as [p F].\n    destruct (uDec p);intros.\n    - simpl in H. rewrite e in H.\n      apply plust_keepingu in e.\n      simpl.\n      rewrite e...\n    - simpl in H. rewrite e in H...\n      apply plust_keepingu in e.\n      simpl.\n      rewrite e...\n  * induction K...\n    destruct a as [p F].\n    destruct (uDec p);intros.\n    - simpl. rewrite e.\n      simpl in H.\n      apply plust_keepingu in e.\n      rewrite e in H...\n    - simpl. rewrite e.\n      simpl in H.\n      apply plust_keepingu in e.\n      rewrite e in H...\nQed.\n    \n Lemma getUELoc K: K = [] <-> getU (Loc K) = [].\n  Proof with sauto.\n  split;intros.\n  rewrite H. simpl;auto.\n  * induction K...\n    simpl in H. rewrite locu in H...\nQed.\n   \n  Lemma getULoc K: getU (Loc K) = Loc K.\n  Proof with sauto.\n  induction K;intros...\n  simpl. rewrite locu...\n  rewrite IHK...\nQed.\n\nLemma  PlusTgetU K : (PlusT (getU K)) = getU (PlusT K).\nProof with sauto.\n  induction K;intros...\n  destruct a as [b F].\n  destruct (uDec b)...\n  * simpl...\n    simpl.\n    rewrite (plust_keepingu _ _ e).\n    rewrite IHK...\n  * simpl...\n    rewrite (plust_keepingu _ _ e)... \nQed.\n\nLemma  PlusTgetL K : (PlusT (getL K)) = getL (PlusT K).\nProof with sauto.\n  induction K;intros...\n  destruct a as [b F].\n  destruct (uDec b)...\n  * simpl...\n    simpl.\n    rewrite (plust_keepingu _ _ e)...\n  * simpl...\n    rewrite (plust_keepingu _ _ e)...\n    simpl.\n    rewrite IHK...\nQed.\n\nLemma  getUPlusTgetU' K : getU (PlusT (getU K)) = PlusT (getU K).\nProof with sauto.\n  induction K;intros...\n  destruct a as [b F].\n  destruct (uDec b)...\n  * simpl...\n    simpl.\n    rewrite (plust_keepingu _ _ e).\n    rewrite IHK...\n  * simpl...\nQed.\n\nLemma  getUPlusTgetL' K : getL (PlusT (getL K)) = PlusT (getL K).\nProof with sauto.\n  induction K;intros...\n  destruct a as [b F].\n  destruct (uDec b)...\n  * simpl...\n  * simpl...\n    simpl.\n    rewrite (plust_keepingu _ _ e).\n    rewrite IHK...    \nQed.\n\n Lemma getLELoc K: getL (Loc K) = [].\n  Proof with sauto.\n  induction K...\n  destruct a as [p F].\n  simpl.\n  rewrite locu;auto.\n Qed. \n \n  Lemma getLgetUPlusT K: getL (PlusT (getU K)) = [].\n  Proof with sauto.\n  induction K... \n  destruct a as [p F].\n  destruct (uDec p).\n  - assert(u (plust p) = true).\n    apply plust_keepingu;auto.\n    simpl... \n    simpl. rewrite H;auto.\n  - simpl. rewrite e;auto. \n Qed. \n \n Lemma getLgetUPlusT' K: SetX u true K -> getL (PlusT K) = [].\n  Proof with sauto.\n  induction K;intros... \n  destruct a as [p F].\n  destruct (uDec p).\n  - assert(u (plust p) = true).\n    apply plust_keepingu;auto.\n    simpl. rewrite H0.\n    apply IHK.\n    inversion H... \n  - inversion H... \n Qed. \n \n  Lemma getUgetLPlusT K: getU (PlusT (getL K)) = [].\n  Proof with sauto.\n  \n  induction K... \n  destruct a as [p F].\n  destruct (uDec p).\n  - simpl. rewrite e;auto. \n  - assert(u (plust p) = false).\n    apply plust_keepingu;auto. \n    simpl. rewrite e;auto.\n    simpl. rewrite H;auto.\n Qed. \n \n \n  Lemma isFormulaL_getU B :  \n      isFormulaL (second B) -> isFormulaL  (second (getU B)). \n  Proof.\n    induction B;intros;sauto. \n    destruct a as [a F]. \n    destruct(uDec a);simpl;sauto.\n    - \n      simpl in *.\n      inversion H;sauto.\n      apply Forall_cons;sauto.\n    -\n      simpl in *.\n      inversion H;sauto.\n  Qed.    \n    \n    Lemma isFormulaL_getL  B :  \n      isFormulaL  (second B) -> isFormulaL  (second (getL B)). \n  Proof.\n    induction B;intros;sauto. \n    destruct a as [a F]. \n    destruct(uDec a);simpl;sauto.\n    - simpl in *.\n      inversion H;sauto.\n   -  simpl in *.\n      inversion H;sauto.\n      apply Forall_cons;sauto.\n  Qed.\n  \n  Lemma isFormulaLSplitUL  B :  \n      isFormulaL  (second (getU B)) ->  isFormulaL  (second (getL B)) -> isFormulaL  (second B). \n  Proof.\n    intros.\n    rewrite cxtDestructSecond.\n    rewrite secondApp.\n    apply Forall_app;auto.\n  Qed.   \n  \n      \n Lemma isFormulaL_PlusT  B :  \n      isFormulaL  (second B) -> isFormulaL  (second (PlusT B)). \n  Proof.\n    induction B;simpl;unfold isFormulaL;intros;auto.\n    apply Forall_cons.\n    apply Forall_inv in H;auto.\n    apply Forall_inv_tail in H.\n    apply IHB;auto.\n    Qed.\n \n Lemma isFormulaL_Loc   B :  \n      isFormulaL  (second B) -> isFormulaL  (second (Loc B)). \n  Proof.\n    induction B;simpl;unfold isFormulaL;intros;auto.\n    constructor...\n    apply Forall_inv in H;auto.\n    apply Forall_inv_tail in H.\n    apply IHB;auto.\n    Qed.\n    \n     Lemma isFormulaLSecond  B D X Y:  \n     Permutation (getL B) (getL D ++ X) -> \n     Permutation (getU B) (getU D ++ Y) ->\n     isFormulaL  (second B) -> isFormulaL  (second D). \n  Proof.\n    autounfold;unfold second;intros.\n    rewrite cxtDestruct in H1.\n    rewrite H in H1.\n    rewrite H0 in H1.\n    fold (second ((getU D ++ Y) ++ getL D ++ X)) in H1.\n    repeat rewrite secondApp in H1.\n    apply Forall_app in H1.\n    destruct H1.\n    apply Forall_app in H1.\n    apply Forall_app in H2.\n    sauto.\n    rewrite cxtDestruct.\n    fold (second (getU D ++ getL D)). \n    repeat rewrite secondApp.\n    apply Forall_app;auto.\n    Qed.\n    \n   Lemma subexpInLoc  C: forall (i:subexp) (F:oo), In (i, F) (Loc C) -> i = loc.\n  Proof with subst;auto.\n  induction C;intros...\n  * simpl in H. contradiction.\n  * simpl in H.\n    destruct H.\n    inversion H...\n    apply IHC in H...\n  Qed.\n   \n    Lemma subexpInMap  C: forall (i:subexp) (F:oo), In (i, F) (PlusT C) -> i = plust i.\n  Proof with subst;auto.\n  induction C;intros...\n  * simpl in H. contradiction.\n  * simpl in H.\n    destruct H.\n    inversion H...\n    rewrite plust_plust_fixpoint;auto.\n    apply IHC in H...\n  Qed.\n  \n    Lemma SetKLoc i K  : i <> loc -> LtX i K -> In loc (first K) -> False. \n  Proof with sauto.\n  induction K;simpl;intros.\n  contradiction.\n  destruct H1.\n  * destruct a;simpl in *;subst.\n    inversion H0...\n    apply locAlone in H.\n    apply H. left;auto.\n  * apply IHK;auto.\n    inversion H0...\n Qed. \n\n  Lemma SetK4Loc i K  : i <> loc -> SetX m4 true K -> In loc (first K) -> False. \n  Proof with sauto.\n  induction K;simpl;intros.\n  contradiction.\n  destruct H1.\n  * destruct a;simpl in *;subst.\n    inversion H0... solveSubExp. \n  * apply IHK;auto.\n    inversion H0...\n  Qed.\n\n  \n  Lemma PlusT_fixpoint : forall C , PlusT (PlusT C) = (PlusT C).\n  Proof with subst;auto.\n  induction C;simpl;intros;auto.\n  rewrite plust_plust_fixpoint...\n  rewrite IHC...\n  Qed.\n  \n  Lemma PlusT_fixpoint' : forall C , SetX mt true C -> (PlusT C) = C.\n  Proof with sauto.\n  induction C;simpl;intros;auto.\n  inversion H...\n  apply IHC in H3.\n  rewrite H3...\n  destruct a as [p F].\n  simpl in *.\n  rewrite plustpropT...\n  Qed.\n  \n\n Lemma getUS F t D L: getU D = (t, F)::L -> u t = true.\n Proof with sauto.\n induction D;intros...\n destruct a.\n destruct (uDec s).\n inversion H... \n inversion H1...\n inversion H... \n Qed.\n \n\n  Lemma linearEmpty K : getL K = [] -> getL K = [] /\\ Permutation (getU K) K /\\ SetX u true K.\n  Proof with auto.\n  intros. split;auto.\n  revert dependent K. \n  induction K;intros...\n  destruct a as [p F].\n  destruct (uDec p).\n  - simpl. rewrite e.\n    simpl in H.\n    rewrite e in H.\n    apply IHK in H. \n    split;sauto. \n  - simpl. rewrite e.\n    simpl in H.\n    rewrite e in H.\n    inversion H...\nQed.\n\nLemma unboundedEmpty K : getU K = [] -> getU K = [] /\\ Permutation (getL K) K /\\ SetX u false K.\n  Proof with auto.\n  intros. split;auto.\n  revert dependent K. \n  induction K;intros...\n  destruct a as [p F].\n  destruct (uDec p).\n  - simpl. rewrite e.\n    simpl in H.\n    rewrite e in H.\n    inversion H...\n  - simpl. rewrite e.\n    simpl in H.\n    rewrite e in H.\n     apply IHK in H. \n    split;sauto. \n Qed.\n \n  Lemma SetK4Destruct sub b K : SetX sub b K -> SetX sub b (getU K) /\\ SetX sub b (getL K).\n  Proof with sauto.\n  intros.\n  rewrite cxtDestruct in H;split;\n  apply Forall_app in H...\n  Qed.\n  \n   Lemma linearInUnb a A K : u a = false -> SetX u true K -> In (a, A) K -> False.\n  Proof with sauto.\n  induction K;intros...\n  destruct a0.\n  inversion H1...\n  inversion H0...\n  apply IHK...\n  inversion H0... \n  Qed. \n  \n  \nLemma  setUPlusTgetU K : SetX u true K -> PlusT (getU K) = PlusT K.\nProof with sauto.\n  induction K;intros...\n  destruct a as [b F].\n  inversion H...\n  simpl. rewrite H2...\n  simpl...\n  rewrite IHK;auto.\n Qed.\n\nLemma  setULocgetU K : SetX u true K -> Loc (getU K) = Loc K.\nProof with sauto.\n  induction K;intros...\n  destruct a as [b F].\n  inversion H...\n  simpl. rewrite H2...\n  simpl...\n  rewrite IHK;auto.\n Qed.\n  \n  \n Lemma SetK4LocEmpty C : LtX loc C -> SetX m4 true C -> C = []. \n Proof with sauto.\n induction C;intros...\n inversion H...\n inversion H0...\n assert(False).\n eapply @locAlone with (a:=(fst a))...\n intro... \n rewrite H1 in H5.\n solveSubExp.\n contradiction.\n Qed. \n \n  Lemma LtXPlusT  a K : LtX a K -> LtX (plust a) (PlusT K).\n  Proof with sauto.\n  induction K;simpl;intros...\n  destruct a0 as [b F].\n  inversion H...\n  apply IHK in H3...\n  apply Forall_cons...\n   apply plust_mono ...\n  Qed.\n\n Lemma InContext1 F BD B D:\n  Permutation (getU BD) (getU B) ->\n  Permutation (getU BD) (getU D) ->\n  Permutation (getL BD) (getL B ++ getL D) ->\n  In F B ->  In F BD.\n  Proof with sauto.\n  intros.\n  rewrite cxtDestruct.\n  rewrite H.\n  rewrite H1.\n  rewrite app_assoc.\n  rewrite <- cxtDestruct.\n  apply in_or_app;auto.\n  Qed.\n\n Lemma InSecond1 F BD B D:\n  Permutation (getU BD) (getU B) ->\n  Permutation (getU BD) (getU D) ->\n  Permutation (getL BD) (getL B ++ getL D) ->\n  In F (second B) ->  In F (second BD).\n  Proof with sauto.\n  intros.\n  unfold second.\n  rewrite cxtDestruct.\n  rewrite H.\n  rewrite H1.\n  rewrite app_assoc.\n  rewrite <- cxtDestruct.\n  rewrite map_app.\n  apply in_or_app;auto.\n  Qed.\n  \n  \n  \n Lemma InContext2 F BD B D:\n  Permutation (getU BD) (getU B) ->\n  Permutation (getU BD) (getU D) ->\n  Permutation (getL BD) (getL B ++ getL D) ->\n  In F D ->  In F BD.\n  Proof with sauto.\n  intros.\n  rewrite cxtDestruct.\n  rewrite H0.\n  rewrite H1.\n  rewrite Permutation_midle_app.\n  rewrite <- cxtDestruct.\n  apply in_or_app;auto.\n  Qed.\n  \n  Lemma InSecond2 F BD B D:\n  Permutation (getU BD) (getU B) ->\n  Permutation (getU BD) (getU D) ->\n  Permutation (getL BD) (getL B ++ getL D) ->\n  In F (second D) ->  In F (second BD).\n  Proof with sauto.\n  intros.\n  unfold second.\n  rewrite cxtDestruct.\n  rewrite H0.\n  rewrite H1.\n  rewrite Permutation_midle_app.\n  rewrite <- cxtDestruct.\n  rewrite map_app.\n  apply in_or_app;auto.\n  Qed.  \n \n\n  Lemma isFormulaSecond1  BD X Y B Z U:\n  isFormulaL  (second (X++getU BD++Y)) -> \n  Permutation (X++getU BD++Y) (Z++B++U) ->\n  isFormulaL  (second B).\n   Proof with sauto.\n   intros.\n   assert(isFormulaL  (second (Z ++ B ++ U))).\n   symmetry in H0.\n   srewrite H0...\n   rewrite !secondApp in H1.\n   apply Forall_app in H1...\n   apply Forall_app in H3...\n Qed.  \n\n Lemma isFormulaSecond2  BD X Y B Z U:\n  isFormulaL  (second (X++getL BD++Y)) -> \n  Permutation (X++getL BD++Y) (Z++B++U) ->\n  isFormulaL  (second B).\n   Proof with sauto.\n   intros.\n   assert(isFormulaL  (second (Z ++ B ++ U))).\n   symmetry in H0.\n   srewrite H0...\n   rewrite !secondApp in H1.\n   apply Forall_app in H1...\n   apply Forall_app in H3...\n Qed.\n \n\n\n  Lemma isFormulaSecondSplit1  BD X Y B D:\n  isFormulaL  (second (BD++X++Y)) -> \n  Permutation (getU BD++X) (getU B) ->\n  Permutation (getL BD++Y) (getL B ++ getL D) -> isFormulaL  (second B).\n   Proof with sauto.\n  intros.\n   rewrite !secondApp in H.\n  assert(isFormulaL  (second BD)).\n  apply Forall_app in H...\n  assert(isFormulaL  (second X)).\n  apply Forall_app in H...\n  apply Forall_app in H4...\n  assert(isFormulaL  (second Y)).\n  apply Forall_app in H...\n  apply Forall_app in H5...\n  assert(Permutation ([] ++ getU BD ++ X) ([] ++getU B ++ [])).\n  sauto.\n  eapply isFormulaSecond1  in H5...\n  assert(Permutation ([] ++ getL BD ++ Y) ([] ++getL B ++ getL D)).\n  sauto.\n  eapply isFormulaSecond2  in H6...\n  apply isFormulaLSplitUL...\n  \n  rewrite !secondApp...\n  apply Forall_app...\n  apply isFormulaL_getL...\n  rewrite !secondApp...\n  apply Forall_app...\n  apply isFormulaL_getU...\n Qed. \n \n  Lemma isFormulaSecondSplit2  BD X Y B D:\n  isFormulaL  (second (BD++X++Y)) -> \n  Permutation (getU BD++X) (getU D) ->\n  Permutation (getL BD++Y) (getL B ++ getL D) -> isFormulaL  (second D).\n   Proof with sauto.\n  intros.\n  eapply isFormulaSecondSplit1 with (X:=X) (Y:=Y) (BD:=BD) (D:=B);auto.\n  rewrite H1...\n  Qed.\n \n \n     Theorem destructClassicSetK4 C4 C4' CN CN': \n    SetX m4 true C4 -> SetX m4 true C4' ->\n    Permutation (C4 ++ CN) (C4' ++ CN') -> \n    exists K4_1 K4_2 K4_3 N, Permutation C4 (K4_1 ++ K4_2) /\\ Permutation C4' (K4_1 ++ K4_3) /\\ \n                    Permutation CN (K4_3 ++ N) /\\ Permutation CN' (K4_2 ++ N). \n  Proof with subst;auto.\n    intros.\n    revert dependent C4'.\n    revert dependent CN.\n    revert dependent CN'.\n    induction C4;intros.\n    * \n      eexists []. \n      eexists []. \n      eexists C4'.\n      eexists CN'. \n      simpl.\n      split;auto.\n    *\n      simpl in H1.\n      symmetry in H1.\n      \n      checkPermutationCases H1.\n      - eapply IHC4 with (CN:=a::CN) (CN':=CN') in H0;\n        [sauto | solveLocation | \n         rewrite H2;symmetry;rewrite <- app_comm_cons;\n         apply Permutation_cons_app;auto].\n         checkPermutationCases H4.\n         + \n           eexists (a::x0).\n           eexists x1.\n           eexists x4.\n           eexists x3.\n           split;auto.\n           rewrite <- app_comm_cons.\n           apply Permutation_cons...\n           split;auto.\n           rewrite H5.\n           rewrite H4. perm. \n         + eexists x0.\n           eexists (a::x1).\n           eexists x2.\n           eexists x4.\n           split;auto.\n           apply Permutation_cons_app...\n           split;auto.\n           split;auto.\n           rewrite H7. \n           rewrite H4. perm.\n      - \n        eapply IHC4 with (CN:=CN) (CN':=x) in H0;\n        [sauto | solveLocation | symmetry;auto].\n        eexists x0.\n        eexists (a::x1).\n        eexists x2.\n        eexists x3.\n        split;auto.\n        apply Permutation_cons_app...\n        split;auto.\n        split;auto.\n        rewrite H2. rewrite H7.\n        perm.\n Qed.       \n \n  Theorem destructClassicSetK CK CK' CN CN': \n    SetX m4 false CK -> SetX m4 false CK' ->\n    Permutation (CK ++ CN) (CK' ++ CN') -> \n    exists K_1 K_2 K_3 N, Permutation CK (K_1 ++ K_2) /\\ Permutation CK' (K_1 ++ K_3) /\\ \n                    Permutation CN (K_3 ++ N) /\\ Permutation CN' (K_2 ++ N). \n  Proof with subst;auto.\n    intros.\n    revert dependent CK'.\n    revert dependent CN.\n    revert dependent CN'.\n    induction CK;intros.\n    * \n      eexists []. \n      eexists []. \n      eexists CK'.\n      eexists CN'. \n      simpl.\n      split;auto.\n    *\n      checkPermutationCases H1.\n      - eapply IHCK with (CN:=a::CN) (CN':=CN') in H0;\n        [sauto | solveLocation | \n         rewrite H2;symmetry;rewrite <- app_comm_cons;\n         apply Permutation_cons_app;auto].\n         checkPermutationCases H4.\n         + \n           eexists (a::x0).\n           eexists x1.\n           eexists x4.\n           eexists x3.\n           split;auto.\n           rewrite <- app_comm_cons.\n           apply Permutation_cons...\n           split;auto.\n           rewrite H5.\n           rewrite H4. perm. \n         + eexists x0.\n           eexists (a::x1).\n           eexists x2.\n           eexists x4.\n           split;auto.\n           apply Permutation_cons_app...\n           split;auto.\n           split;auto.\n           rewrite H7. \n           rewrite H4. perm.\n      - \n        eapply IHCK with (CN:=CN) (CN':=x) in H0;\n        [sauto | solveLocation | symmetry;auto].\n        eexists x0.\n        eexists (a::x1).\n        eexists x2.\n        eexists x3.\n        split;auto.\n        apply Permutation_cons_app...\n        split;auto.\n        split;auto.\n        rewrite H2. rewrite H7.\n        perm.  \n Qed.       \n\n Theorem destructClassicSet C4 C4' CK CK' CN CN': \n SetX m4 true C4 -> SetX m4 true C4' -> SetX m4 false CK -> SetX m4 false CK' -> \n Permutation (C4 ++ CK ++ CN) (C4' ++ CK' ++ CN') -> \n (exists K_1 K_2 K_3 N, \n          Permutation CK (K_1 ++ K_2) /\\ Permutation CK' (K_1 ++ K_3) /\\ \n          Permutation (C4 ++ CN) (K_3 ++ N) /\\ Permutation (C4' ++ CN') (K_2 ++ N)) /\\\n (exists K4_1 K4_2 K4_3 N, \n          Permutation C4 (K4_1 ++ K4_2) /\\ Permutation C4' (K4_1 ++ K4_3) /\\ \n          Permutation (CK ++ CN) (K4_3 ++ N) /\\ Permutation (CK' ++ CN') (K4_2 ++ N)). \n  Proof with subst;auto.\n  split;intros.\n  * assert(Permutation (CK ++ (C4 ++ CN)) (CK' ++ (C4' ++ CN'))).\n    rewrite Permutation_app_swap_app.\n    rewrite H3. perm.\n    clear H3.\n    apply destructClassicSetK in H4...\n  * apply destructClassicSetK4  in H3...\n  Qed.\n \n\n  Theorem destructClassicSet' C4 C4' CK CK' CN CN': \n SetX m4 true C4 -> SetX m4 true C4' -> SetX m4 false CK -> SetX m4 false CK' -> \n Permutation (C4 ++ CK ++ CN) (C4' ++ CK' ++ CN') -> \n exists K_1 K_2 K_3 K4_1 K4_2 K4_3 N, \n          Permutation CK (K_1 ++ K_2) /\\ Permutation CK' (K_1 ++ K_3) /\\ \n          Permutation C4 (K4_1 ++ K4_2) /\\ Permutation C4' (K4_1 ++ K4_3) /\\ \n          Permutation CN (K_3 ++ K4_3 ++ N) /\\ Permutation CN' (K_2 ++ K4_2 ++ N) . \n  Proof with sauto.\n  intros.\n    \n    revert dependent CK.\n    revert dependent C4'.\n    revert dependent CK'.\n    revert dependent CN.\n    revert dependent CN'.\n    induction C4;intros...\n    * \n    revert dependent C4'.\n    revert dependent CK'.\n    revert dependent CN.\n    revert dependent CN'.\n    induction CK;intros...\n      eexists []. \n      eexists []. \n      eexists CK'.\n      eexists []. \n      eexists []. \n      eexists C4'.\n      eexists CN'...\n      rewrite H3...  \n      simpl in H3.\n      checkPermutationCases H3.\n      - rewrite H4 in H0.\n        inversion H0...\n        inversion H1...\n      -  checkPermutationCases H4.\n         rewrite <- H6 in H5.\n         symmetry in H5.\n         apply IHCK in H5...\n         sauto...\n         eexists (a :: x1).\n         eexists x2.\n         eexists x3.\n         eexists [].\n         eexists [].\n         eexists x6.\n         eexists x7...\n         rewrite H5...\n         rewrite H4.\n         rewrite H8...\n         inversion H1...\n         rewrite H4 in H2.\n         inversion H2...\n         rewrite <- H6 in H5.\n         symmetry in H5.\n         apply IHCK in H5...\n         sauto...\n         eexists x1.\n         eexists (a::x2).\n         eexists x3.\n         eexists [].\n         eexists [].\n         eexists x6.\n         eexists x7...\n         rewrite H5... \n         rewrite H4.\n         rewrite H12...\n         inversion H1...\n    *\n      simpl in H3.\n      revert dependent C4'.\n      revert dependent CK'.\n      revert dependent CN.\n      revert dependent CN'.\n      induction CK;intros...\n      - checkPermutationCases H3.\n         symmetry in H5.\n         change (C4++CN) with (C4++[]++CN) in H5.\n         apply IHC4 in H5...\n         sauto...\n         eexists [].\n         eexists [].\n         eexists x2.\n         eexists (a::x3).\n         eexists x4.\n         eexists x5.\n         eexists x6...\n         rewrite H6...\n         rewrite H4.\n         rewrite H8...\n         inversion H...\n         rewrite H4 in H0.\n         inversion H0...\n         \n         checkPermutationCases H4.\n         rewrite H4 in H2.\n         inversion H2...\n         inversion H...\n         \n         rewrite <- H6 in H5.\n         symmetry in H5.\n         change (C4++CN) with (C4++[]++CN) in H5.\n         apply IHC4 in H5...\n         sauto...\n         eexists [].\n         eexists [].\n         eexists x3.\n         eexists x4.\n         exists (a::x5).\n         eexists x6.\n         eexists x7...\n         rewrite H7... \n         rewrite H4.\n         rewrite H12...\n         inversion H...\n      -  assert(Permutation  (a :: C4 ++ (a0 :: CK) ++ CN)  (a0 :: C4 ++ (a :: CK) ++ CN)) by perm.\n         rewrite H4 in H3. clear H4. \n          checkPermutationCases H3.\n          symmetry in H5.\n            assert(Permutation (C4 ++ a :: CK ++ CN) (a ::  C4 ++ CK ++ CN)) by perm.\n            rewrite H3 in H5.\n         clear H3.\n         apply IHCK in H5... \n         rewrite H4 in H0.\n         inversion H0...\n         inversion H1...\n         inversion H1...\n         rewrite H4 in H0.\n         inversion H0...\n         checkPermutationCases H4.\n        \n         \n         symmetry in H5.\n         assert(Permutation (C4 ++ a :: CK ++ CN) (a ::  C4 ++ CK ++ CN)) by perm.\n            rewrite H3 in H5.\n         clear H3.\n         rewrite <- H6 in H5.\n         apply IHCK in H5... \n         eexists (a0::x1).\n         exists x2.\n         exists x3.\n         exists x4.\n         exists x5.\n         exists x6.\n         exists x7...\n         rewrite H5...\n         rewrite H4.\n         rewrite H8...\n         inversion H1...\n         rewrite H4 in H2.\n         inversion H2...\n         symmetry in H5.\n         assert(Permutation (C4 ++ a :: CK ++ CN) (a ::  C4 ++ CK ++ CN)) by perm.\n            rewrite H3 in H5.\n         clear H3.\n         rewrite <- H6 in H5.\n         apply IHCK in H5... \n         eexists x1.\n         exists (a0::x2).\n         exists x3.\n         exists x4.\n         exists x5.\n         exists x6.\n         exists x7...\n         rewrite H5...\n         rewrite H4.\n         rewrite H12... inversion H1...\n  Qed.\n  \n   Theorem destructClassicSetU' C4 C4' CK CK' CN CN': \n SetX m4 true C4 -> SetX m4 true C4' -> SetX m4 false CK -> SetX m4 false CK' -> \n Permutation (getU C4 ++ getU CK ++ getU CN) (getU C4' ++ getU CK' ++ getU CN') -> \n exists K_1 K_2 K_3 K4_1 K4_2 K4_3 N, \n          Permutation (getU CK) (getU K_1 ++ getU K_2) /\\ Permutation (getU CK') (getU K_1 ++ getU K_3) /\\ \n          Permutation (getU C4) (getU K4_1 ++ getU K4_2) /\\ Permutation (getU C4') (getU K4_1 ++ getU K4_3) /\\ \n          Permutation (getU CN) (getU K_3 ++ getU K4_3 ++ getU N) /\\ Permutation (getU CN') (getU K_2 ++ getU K4_2 ++ getU N) . \n  Proof with sauto.\n     intros.\n     apply destructClassicSet' in H3...\n     eexists x.\n     eexists x0.\n     eexists x1.\n     eexists x2.\n     eexists x3.\n     eexists x4.\n     eexists x5.\n       2:{ rewrite cxtDestruct in H. apply Forall_app in H...  }\n      2:{ rewrite cxtDestruct in H0. apply Forall_app in H0... }\n     2:{ rewrite cxtDestruct in H1. apply Forall_app in H1... }\n    2:{ rewrite cxtDestruct in H2. apply Forall_app in H2... }\n    repeat rewrite <- getUApp.\n    rewrite (@setUtoGetU (x++x0)).\n     rewrite (@setUtoGetU (x++x1)).\n      rewrite (@setUtoGetU (x2++x3)).\n       rewrite (@setUtoGetU (x2++x4)).\n        rewrite (@setUtoGetU (x1++x4++x5)).\n        rewrite (@setUtoGetU (x0++x3++x5))...\n    \n    apply getUPerm_SetU in H10...\n    apply getUPerm_SetU in H8...\n    apply getUPerm_SetU in H7...\n    apply getUPerm_SetU in H5...\n    apply getUPerm_SetU in H6...\n    apply getUPerm_SetU in H4...\n   Qed. \n   \n     \n  Theorem destructClassicSetU C4 C4' CK CK' CN CN': \n SetX m4 true C4 -> SetX m4 true C4' -> SetX m4 false CK -> SetX m4 false CK' -> \n Permutation (getU C4 ++ getU CK ++ getU CN) (getU C4' ++ getU CK' ++ getU CN') -> \n (exists K_1 K_2 K_3 N, \n          Permutation (getU CK) (getU K_1 ++ getU K_2) /\\ Permutation (getU CK') (getU K_1 ++ getU K_3) /\\ \n          Permutation (getU C4 ++ getU CN) (getU K_3 ++ getU N) /\\ Permutation (getU C4' ++ getU CN') (getU K_2 ++ getU N)) /\\\n (exists K4_1 K4_2 K4_3 N, \n          Permutation (getU C4) (getU K4_1 ++ getU K4_2) /\\ Permutation (getU C4') (getU K4_1 ++ getU K4_3) /\\ \n          Permutation (getU CK ++ getU CN) (getU K4_3 ++ getU N) /\\ Permutation (getU CK' ++ getU CN') (getU K4_2 ++ getU N)). \n  Proof with sauto.\n  intros. apply destructClassicSet in H3...\n  \n  \n  3:{ rewrite cxtDestruct in H. apply Forall_app in H... }\n  3:{ rewrite cxtDestruct in H0. apply Forall_app in H0... }\n  3:{ rewrite cxtDestruct in H1. apply Forall_app in H1... }\n  3:{ rewrite cxtDestruct in H2. apply Forall_app in H2... }\n \n  apply getUPermU  in H3.\n  apply getUPermU in H10.\n  setoid_rewrite <- getUApp in H8.\n  apply getUPermU in H8.\n  setoid_rewrite <- getUApp in H12.\n  apply getUPermU in H12...\n\n  setoid_rewrite getUApp in H3.\n  setoid_rewrite getUApp in H10.\n  setoid_rewrite getUApp in H8.\n  setoid_rewrite getUApp in H12.\n  \n  exists x3. exists x4.\n  exists x5. exists x6...\n  \n    apply getUPermU  in H5.\n  apply getUPermU  in H7.\n  setoid_rewrite <- getUApp in H6.\n  apply getUPermU  in H6.\n  setoid_rewrite <- getUApp in H9.\n  apply getUPermU  in H9.\n  \n  setoid_rewrite getUApp in H5.\n  setoid_rewrite getUApp in H6.\n  setoid_rewrite getUApp in H7.\n  setoid_rewrite getUApp in H9.\n  \n  exists x. exists x0.\n  exists x1. exists x2...\n  Qed.\n \n  Lemma simplUnb BD B D:          \n  Permutation (getU BD) (getU D) ->\n  Permutation (getL BD) (getL B ++ getL D) ->\n  SetX u true B -> Permutation BD D.\n  Proof.   \n  intros.\n  rewrite (SetU_then_empty _ H1) in H0.\n  rewrite (cxtDestruct BD).\n  rewrite H0.\n  rewrite H.\n  simpl. \n  rewrite <- cxtDestruct;auto.\n  Qed.\n  \n  Lemma simplUnb' BD B D:          \n  Permutation (getU BD) (getU B) ->\n  Permutation (getL BD) (getL B ++ getL D) ->\n  SetX u true D -> Permutation BD B.\n  Proof.   \n  intros.\n  rewrite (SetU_then_empty _ H1) in H0.\n  rewrite (cxtDestruct BD).\n  rewrite H.\n  rewrite H0;sauto.\n  rewrite <- cxtDestruct;auto.\n  Qed.\n  \n Definition SetU K := SetX  u true K. \n Definition SetL K := SetX  u false K.\n Definition SetT K := SetX  mt true K. \n Definition SetK K := SetX  m4 false K.\n Definition SetK4 K := SetX m4 true K.\n\nEnd Properties.\n\n Global Hint Unfold SetU SetL SetT SetK SetK4:core. \n\nGlobal Hint Resolve SetUPlusT locSetU locSetT SetUKClosure SetK4Closure SetDClosure getUtoSetU getLtoSetL: ExBase.\n\n\nGlobal Hint Resolve SetKPlusT SetK4PlusT SetK4PlusT' SetUPlusT PlusTSetU SetULoc SetTLoc: ExBase.\n\nGlobal Hint Extern 1 (LtX ?a ?K) =>\n  match goal with\n  | H: LtX ?i ?K,  H1: lt ?a ?i |- _ =>  apply (SetKTrans _ _ _ H H1)\n  end : core.\n\nGlobal Hint Resolve SetKLoc SetK4Loc linearInUnb: ExBase.\n\nLtac solveLT :=  \ntry\n match goal with\n   | [H1: ?a <> loc, H2: lt ?a loc |- _] => apply locAlone in H1;assert(False); [apply H1;left;auto|];contradiction\n  | [H1: ?a <> loc, H2: lt loc ?a |- _] => apply locAlone in H1;assert(False); [apply H1;right;auto|];contradiction\n   | [H: _ ?i (?F::?K) |- lt ?i (fst ?F) ] => inversion H;subst;intuition\n   | [H: _ ?i ((?s, _)::?K) |- lt ?i ?s ] => inversion H;subst;intuition\n   | [H: _ ?i (_::?K) |- LtX ?i ?K ] => inversion H;subst;intuition\n   \n   \n   | [H: lt ?x ?y, H2: LtX ?y ?K |- LtX ?x ?K ] => rewrite H;auto\n   | [H: Permutation ?K ?K', H2: LtX ?x ?K' |- LtX ?x ?K ] => rewrite H;auto\n    | [H: Permutation ?K ?K', H2: LtX ?x ?K |- LtX ?x ?K' ] => rewrite <- H;auto  \n \n  end;auto.\n\nLtac solveSE :=  \ntry\n match goal with\n | [H: SetK ((?s, _)::_) |- m4 ?s = false] => inversion H;subst;auto\n    | [H: SetK4 ((?s, _)::_) |- m4 ?s = true] => inversion H;subst;auto\n      | [H: SetT ((?s, _)::_) |- mt ?s = true] => inversion H;subst;auto\n  | [H: SetU ((?s, _)::_) |- u ?s = true] => inversion H;subst;auto      \n    | [H: SetL ((?s, _)::_) |- u ?s = false] => inversion H;subst;auto\n\n | [H: SetK (?s::_) |- m4 (fst ?s) = false] => inversion H;subst;intuition\n    | [H: SetK4 (?s::_) |- m4 (fst ?s) = true] => inversion H;subst;intuition\n      | [H: SetT (?s::_) |- mt (fst ?s) = true] => inversion H;subst;intuition\n  | [H: SetU (?s::_) |- u (fst ?s) = true] => inversion H;subst;intuition\n    | [H: SetL (?s::_) |- u (fst ?s) = false] => inversion H;subst;intuition\n\n     \n    | [H: SetU (_::?K) |- SetU ?K] => inversion H;subst;auto\n   | [H: SetL (_::?K) |- SetL ?K] => inversion H;subst;auto\n   | [H: SetK (_::?K) |- SetK ?K] => inversion H;subst;auto\n   | [H: SetK4 (_::?K) |- SetK4 ?K] => inversion H;subst;auto\n   | [H: SetT (_::?K) |- SetT ?K] => inversion H;subst;auto \n  end;auto.\n \n(*  Ltac solveSignature := solveSignature1; \n try\n  match goal with\n  | [H: SetK ((?s, _)::?K) |- m4 ?s = false] => inversion H;subst;auto\n    | [H: SetK4 ((?s, _)::?K) |- m4 ?s = true] => inversion H;subst;auto\n      | [H: SetT ((?s, _)::?K) |- mt ?s = true] => inversion H;subst;auto\n  | [H: SetU ((?s, _)::?K) |- u ?s = true] => inversion H;subst;auto      \n    | [H: SetL ((?s, _)::?K) |- u ?s = false] => inversion H;subst;auto\n     \n  end. *)\n \n \n Ltac simplEmpty := \n repeat    \n  multimatch goal with\n\n  | [H: LtX loc ?K, H1: SetK4 ?K |- _  ] =>  assert(K=[]) by apply (SetK4LocEmpty _ H H1);clear H H1 \n \n  | [H: SetU ?K, H1: SetL ?K |- _  ] =>  assert(K=[]) by apply (SetKK4_then_empty _ _ H H1);clear H H1 \n  | [H: SetK4 ?K, H1: SetK ?K |- _  ] =>  assert(K=[]) by apply (SetKK4_then_empty _ _ H H1);clear H H1 \n\n  | [H: SetK ?K, H0: LtX ?i ?K, H1:  m4 ?i = true |- _  ] =>  assert(K=[]) by apply (SetKK4_then_empty' _ _ H H0 H1);clear H \n\n  | [H: SetL ?K, H0: LtX ?i ?K, H1:  u ?i = true |- _  ] =>  assert(K=[]) by apply (SetUL_then_empty' _ _ H H0 H1);clear H \n\n  | [  |- context[getL(getU _)] ] => rewrite getLgetU \n  | [ H: context[getL(getU _)] |- _  ] => rewrite getLgetU in H\n  | [  |- context[getU(getL _)] ] => rewrite getUgetL \n  | [ H: context[getU(getL _)] |- _  ] => rewrite getUgetL in H\n  | [  |- context[getL (Loc _)] ] => rewrite getLELoc\n  | [ H: context[getL (Loc _)] |- _  ] => rewrite getLELoc in H\n\n  | [ H: SetU ?K |- context[getL ?K] ] => rewrite (SetU_then_empty _ H)\n  | [ H1: SetU ?K, H2: context[getL ?K] |- _ ] => rewrite (SetU_then_empty _ H1) in H2\n\n  | [ H: SetL ?K |- context[getU ?K] ] => rewrite (SetL_then_empty _ H)\n  | [ H1: SetL ?K, H2: context[getU ?K] |- _ ] => rewrite (SetL_then_empty _ H1) in H2\n  \n   \n | [ H: SetU (getL ?K)  |- context[getL ?K] ] => rewrite (getLtoSetU _ H)\n  | [H0: SetU (getL ?K), H: context[getL ?K] |- _  ] => rewrite (getLtoSetU _ H0) in H\n\n | [ H: SetU ?K  |- context[getL (PlusT ?K)] ] => rewrite (getLgetUPlusT' _ H)\n  | [H0: SetU ?K, H: context[getL (PlusT ?K)] |- _  ] => rewrite (getLgetUPlusT' _ H0) in H\n\n | [  |- context[getL (PlusT (getU _))] ] => rewrite getLgetUPlusT\n  | [H: context[getL (PlusT (getU _))] |- _  ] => rewrite getLgetUPlusT in H\n| [  |- context[getU (PlusT (getL _))] ] => rewrite getUgetLPlusT\n  | [H: context[getU (PlusT (getL _))] |- _  ] => rewrite getUgetLPlusT in H\n\n | [H: SetU (getL ?K) |- context[getL ?K]  ] => rewrite (getLtoSetU _ H)\n \n  | [H: SetU (getL ?K), H1: context[getL ?K] |- _  ] => rewrite (getLtoSetU _ H) in H1\nend.\n\n\nLtac simplFix := \n repeat    \n  multimatch goal with\n  | [  |- context[PlusT (PlusT _)] ] => rewrite MapPlusT_fixpoint\n | [H:  context[PlusT (PlusT _)]  |- _ ]  => rewrite MapPlusT_fixpoint in H\n\n | [  |- context[getU (getU _)] ] => rewrite getU_fixpoint\n | [H:  context[getU (getU _)]  |- _ ]  => rewrite getU_fixpoint in H\n\n | [  |- context[getL (getL _)] ] => rewrite getL_fixpoint\n | [H:  context[getL (getL _)]  |- _ ]  => rewrite getL_fixpoint in H\n\n | [  |- context[getU (Loc _)] ] => rewrite getULoc\n | [H:  context[getU (Loc _)]  |- _ ]  => rewrite getULoc in H\n\n | [H: SetT ?K  |- context[PlusT ?K] ] => rewrite (SetTPlusT _ H)\n | [H: SetT ?K, H1: context[PlusT ?K]  |- _ ]  => rewrite (SetTPlusT _ H) in H1\n\n | [H: SetU ?K  |- context[getU ?K] ] => rewrite (setUtoGetU _ H)\n | [H: SetU ?K, H1: context[getU ?K]  |- _ ]  => rewrite (setUtoGetU _ H) in H1\n\n | [H: SetL ?K  |- context[getL ?K] ] => rewrite (setLtoGetL _ H)\n | [H: SetL ?K, H1: context[getL ?K]  |- _ ]  => rewrite (setLtoGetL _ H) in H1\n\n\n| [  |- context[getU (PlusT (getU _))] ] => rewrite getUPlusTgetU'\n | [H: context[getU (PlusT (getU _))]  |- _ ]  => rewrite getUPlusTgetU' in H\n\n| [  |- context[getL (PlusT (getL _))] ] => rewrite getUPlusTgetL'\n | [H: context[getL (PlusT (getL _))]  |- _ ]  => rewrite getUPlusTgetL' in H\n\n| [  |- context[PlusT (getU _)] ] => rewrite  PlusTgetU\n | [H: context[PlusT (getU _)]  |- _ ]  => rewrite  PlusTgetU in H\n\n| [  |- context[PlusT (getL _)] ] => rewrite  PlusTgetL\n | [H: context[PlusT (getL _)]  |- _ ]  => rewrite  PlusTgetL  in H\nend.\n\n\n\n\nLtac simplCtx :=\n multimatch goal with\n \n | [  |- context[PlusT(_++_)] ] => setoid_rewrite PlusTApp\n | [ H: context[PlusT(_++_)] |- _ ] => setoid_rewrite PlusTApp in H \n | [  |- context[getU(_++_)] ] => setoid_rewrite getUApp\n | [  |- context[getL(_++_)] ] => setoid_rewrite getLApp\n | [ H: context[getU(_++_)] |- _ ] => setoid_rewrite getUApp in H\n | [ H: context[getL(_++_)] |- _ ] => setoid_rewrite getLApp in H\n  | [  |- context[(second (getU ?K++getL ?K))] ] => rewrite <- cxtDestructSecond\n | [ H:context[(second (getU ?K++getL ?K))] |- _ ] => rewrite <- cxtDestructSecond in H \nend. \n\n \nLtac solveSignature2 :=\n match goal with\n  | [ H: SetX ?s ?b ?K |- SetX ?s ?b (getU ?K)] => apply SetK4Destruct in H;sauto\n  | [ H: SetX ?s ?b ?K |- SetX ?s ?b (getL ?K)] => apply SetK4Destruct in H;sauto\n\n| [ H: SetX ?s ?b ?K, H2: Permutation (getU ?K) (?K2 ++ _) |- SetX ?s ?b ?K2] => \n   let H' := fresh \"H\" in\n          apply SetK4Destruct in H; destruct H as [H H'];rewrite H2 in H;solveSignature2\n | [ H: SetX ?s ?b ?K, H2: Permutation (getU ?K) (_ ++ ?K2) |- SetX ?s ?b ?K2] => \n   let H' := fresh \"H\" in\n          apply SetK4Destruct in H; destruct H as [H H'];rewrite H2 in H;solveSignature2\n\n  | [H: Permutation (getU ?CN) (_ ++ ?M) |- SetU ?N] =>  apply getUPerm_SetU in H;solveSignature2\n  | [H: Permutation (getU ?CN) (?M ++ _) |- SetU ?M] =>  apply getUPerm_SetU in H;solveSignature2\n\n | [ H: SetT ?K |- SetT (getU ?K)] => rewrite cxtDestruct in H;solveSignature2\n | [ H: SetT ?K |- SetT (getL ?K)] => rewrite cxtDestruct in H;solveSignature2\n \n | [ H1: u ?i = false, H2: In (?i, ?F) ?B  |- In (?i, ?F) (getL ?B) ] => apply lIngetL;auto\n\nend.\n ", "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/SL/Locations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.2534688079298242}}
{"text": "From Undecidability.L Require Import L_facts Tactics.LTactics.\nFrom Undecidability.L.Datatypes Require Import LSum LBool LNat Lists LProd.\n\nFrom Complexity.L.AbstractMachines Require Import FunctionalDefinitions AbstractHeapMachineDef UnfoldTailRec UnfoldHeap.\n\nRequire Import Undecidability.L.AbstractMachines.LargestVar.\n\nFrom Undecidability.L Require Import Prelim.LoopSum Functions.LoopSum Functions.UnboundIteration Functions.LoopSum Functions.Equality.\n\nFrom Complexity.L.AbstractMachines.Computable Require Import Shared Lookup.\nImport Nat.\nImport UnfoldTailRec.task.\n\nImport GenEncode.\nMetaCoq Run (tmGenEncode \"task_enc\" task).\n#[export]\nHint Resolve task_enc_correct : Lrewrite.\n\n#[export]\nInstance termT_S : computableTime' closT (fun _ _ => (1,fun _ _ => (1,tt))).\nProof.\n  extract constructor.\n  solverec.\nQed.\n\nDefinition time_unfoldTailRecStep : (list task * list heapEntry * list term ) -> _ :=\n  fun '(stack,H,res) => match stack with\n                     | closT (var n,a) k::_ => lookupTime (length H) (n-k) + min n k * 28\n                     | _ => 0\n                     end + 96.\n\n#[export]\nInstance term_unfoldTailRecStep : computableTime' unfoldTailRecStep (fun x _ => (time_unfoldTailRecStep x,tt)).\nProof.\nextract. unfold time_unfoldTailRecStep. solverec.\nall: unfold c__leb2, leb_time, c__leb, c__sub1, sub_time, c__sub. all: solverec. \nQed.\n\n\n\nDefinition unfoldBool_time lengthH largestVar :=\n  lookupTime lengthH largestVar * 7 + largestVar *196+ EqBool.c__eqbComp term * (size (enc (lam (lam # 0))) + size (enc (lam (lam # 1)))) + 1245.\n\n#[export]\nInstance term_unfoldBool : computableTime' unfoldBoolean\n                                          (fun H _ => (1,fun q _ => (unfoldBool_time (length H) (max (largestVarH H) (largestVarC q)),tt))).\nProof.\n  unfold unfoldBoolean.\n  unfold enc; cbn [encodable_bool_enc].\n  extract.\n  recRel_prettify.\n  intros H _. split. reflexivity.\n  intros [s a] _. split. 2:now solverec.\n  unshelve eassert (H':= time_loopSum_bound_onlyByN _ _\n      (f:=unfoldTailRecStep)\n      (fT:=(fun (x0 : list task * list heapEntry * list term) (_ : unit) => (time_unfoldTailRecStep x0, tt)))\n      (P:= fun n '(stack,H',res) =>\n             H' = H\n             /\\ largestVarState (stack,H',res) <= max (largestVarH H) (largestVar s)\n             /\\ (length res <= n))\n      (boundL := 96 + lookupTime (length H) (max (largestVarH H) (largestVar s)) + max (largestVarH H) (largestVar s) * 28)\n      (boundR := fun n => 28*n) _).\n\n  -intros n x. assert (H':=unfoldTailRecStep_largestVar_inv x).\n   unfold unfoldTailRecStep in *.\n   repeat (let eq := fresh \"eq\" in destruct _ eqn:eq). all:try congruence. all:subst. all:inv eq2. \n   all:unfold time_unfoldTailRecStep.\n   \n   all:intros (->&H'1&?).\n   all:try rewrite H',H'1.\n   all:cbn [fst].\n   \n\n   all:repeat match goal with\n                H : _ <=? _ = true |- _ => apply Nat.leb_le in H\n              | H : _ <=? _ = false |- _ => apply Nat.leb_gt in H\n              | H : lookup _ _ _ = Some _ |- _ => apply lookup_size in H;cbn in H\n              end.\n   all:intuition (try eassumption;cbn [length];try Lia.nia;try eauto).\n\n   3:now cbn in *;Lia.nia.\n   1-3:assert (H'3 : n1 <= (Init.Nat.max (largestVarH H) (largestVar s))) by (cbn in *; Lia.nia).\n   1-3:rewrite lookupTime_mono with (n' := Init.Nat.max (largestVarH H) (largestVar s));[|reflexivity|try lia].\n   1-3:cbn - [plus mult]in *.\n   1-3:Lia.lia.\n  -rewrite H'. clear H'.\n   2:{ cbn. intuition idtac. all:Lia.lia. } \n   ring_simplify.\n   (*\n   specialize @list_eqbTime_bound_r with (f:=fun x => 17 * sizeT x + 11) as H'1.\n*)\n   destruct loopSum as [[]|].\n   cbn [size].\n\n   repeat destruct _.\n   all:unfold unfoldBool_time, largestVarC, EqBool.eqbTime. all:cbn [fst snd].\n   all:try rewrite -> !Nat.le_min_r. all:lia.\nQed.\n\n\nLemma unfoldBool_time_mono l l' n n':\n  l <= l' -> n <= n' -> unfoldBool_time l n <= unfoldBool_time l' n'.\nProof.\n  unfold unfoldBool_time. intros H1 H2.\n  rewrite lookupTime_mono. 2,3:eassumption. rewrite H2. reflexivity.\nQed.\n\nLemma unfoldBool_time_leq lengthH largestVar :\n  unfoldBool_time lengthH largestVar <= (largestVar + 1) * (lengthH * 15 + 41 + 28) * 7 + EqBool.c__eqbComp term * 46 + 1245.\nProof.\n  unfold unfoldBool_time. unfold lookupTime.\n  unfold enc,encodable_term_enc. all:unfold enc;cbn.\n  Lia.nia.\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/AbstractMachines/Computable/Unfolding.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.25337826650444567}}
{"text": "Require Import floyd.proofauto.\nRequire Import data_at_test.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs.  mk_varspecs prog. Defined.\n\nDefinition value := tuint.\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  (Z.div tag 1024 = n)\n          LOCAL (temp _p p)\n          SEP (data_at Ews (tarray value (1+n)) \n                      (map Vint (map Int.repr (tag::contents)))\n                      (offset_val (-sizeof value) p))\n  POST [ tint ]\n        PROP () LOCAL()\n           SEP (TT).\n\nDefinition Gprog : funspecs := \n        ltac:(with_library prog [fiddle_spec]).\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 (tag/1024) 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 (N0: 0 <= n)\n  by (pose proof (Zlength_nonneg contents); omega).\n(* STOP HERE. *)\nassert_PROP (p = field_address0 (tarray value (1+n)) [ArraySubsc 1] (offset_val (-sizeof value) p)). {\n  entailer!.\n  unfold field_address0.\n  rewrite if_true. simpl. rewrite offset_offset_val.\n  destruct H as [H _].\n  destruct p; try contradiction H. simpl. f_equal. rewrite Int.add_zero. auto.\n  destruct H as [? [? [? [? [? [? [? ?]]]]]]].\n  hnf. repeat simple apply conj; auto.\n  split; hnf.\n  auto. omega.\n}\nreplace field_address0 with field_address in H by admit.\nforward.\n(*\nLtac call to \"forward\" failed.\nError:\nTactic failure: sc_new_instantiate should really not have failed (level 10).\n*)\n\n(** SPLITTING APPROACH **)\n\nerewrite (split2_data_at_Tarray Ews value (1+n) 1 _ \n      (map Vint (map Int.repr (tag :: contents)))\n      (map Vint (map Int.repr (tag :: nil)))\n      (map Vint (map Int.repr (contents))));\n  try omega; \n  try (autorewrite with sublist; apply JMeq_refl).\n2: rewrite !sublist_map, sublist_1_cons;\n   autorewrite with sublist; apply JMeq_refl.\n\nassert_PROP (p = field_address (tarray value 1) [ArraySubsc 1] (offset_val (-sizeof value) p)). {\n  entailer!.\n  unfold field_address.\n  rewrite if_true. simpl. rewrite offset_offset_val.\n  destruct H as [H _].\n  destruct p; try contradiction H. simpl. f_equal. rewrite Int.add_zero. auto.\n  destruct H as [? [? [? [? [? [? [? ?]]]]]]].\n  hnf. repeat simple apply conj; auto.\n  split; hnf.\n  auto. omega.\n}\n\nforward.\n \n 2: omega.\n\n  try reflexivity.\n\n\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_data_at_test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.25337826006591463}}
{"text": "(* ssreflect *)\n\nFrom mathcomp.ssreflect Require Import ssreflect ssrbool ssrnat ssrfun eqtype seq fintype finfun.\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nRequire Import Bool.\nRequire Import Zbool.\nRequire Import BinPos.\n\nRequire Import VST.concurrency.compcert_imports. Import CompcertCommon.\n\nRequire Import VST.msl.Axioms.\n\nRequire Import VST.concurrency.sepcomp. Import SepComp.\n\nRequire Import VST.concurrency.pred_lemmas.\nRequire Import VST.concurrency.seq_lemmas.\nRequire Import VST.concurrency.inj_lemmas.\n\n(* The following variation of [join] is appropriate for shared resources  *)\n(* like extern injections: each core must have a consistent mapping on    *)\n(* extern blocks but the domains of the mappings are not necessarily      *)\n(* disjoint.                                                              *)\n\nDefinition join2 (j  k : Values.meminj) b :=\n  match j b with\n    | Some (b1,d1) =>\n      match k b with\n        | Some (b2,d2) =>\n            if [&& Pos.eqb b1 b2 & Zeq_bool d1 d2]\n            then Some (b1,d1) else None\n        | None => None\n      end\n    | None => None\n  end.\n\nLemma join2P j k b1 b2 d2 :\n  join2 j k b1 = Some (b2,d2) <->\n  [/\\ j b1 = Some (b2,d2) & k b1 = Some (b2,d2)].\nProof.\nrewrite/join2; split.\ncase A: (j b1)=> // [[x y]]; case B: (k b1)=> // [[x' y']].\ncase H: (_ && _)=> //; move: H; move/andP=> [].\nby move/Peqb_true_eq=> <-; move/Zeq_bool_eq=> <-; case=> -> ->.\nmove=> []-> ->; case H: (_ && _)=> //; move: H; move/andP=> []; split.\nby rewrite/is_true Pos.eqb_eq.\nby rewrite/is_true -Zeq_is_eq_bool.\nQed.\n\n(* Why is this lemma not in ZArith?!? *)\n\nLemma Zeq_bool_refl x : Zeq_bool x x.\nProof. by case: (Zeq_is_eq_bool x x)=> A _; apply: A. Qed.\n\nLemma Zeq_bool_sym x y : Zeq_bool x y = Zeq_bool y x.\nProof.\ncase e: (Zeq_bool x y).\nrewrite (Zeq_bool_eq _ _ e).\nby rewrite Zeq_bool_refl.\nmove: (Zeq_bool_neq _ _ e)=> neq.\ncase f: (Zeq_bool y x)=> //.\nmove: (Zeq_bool_eq _ _ f)=> eq.\nby subst x; elimtype False; apply: neq.\nQed.\n\nLemma join2_inject_incr j k :\n  inject_incr j k ->\n  join2 j k = j.\nProof.\nmove=> incr; rewrite /join2; extensionality b.\ncase jj: (j b)=> //[[x y]].\nmove: (incr _ _ _ jj).\ncase kk: (k b)=> [[x' y']|//].\ncase=> -> ->.\nby rewrite Pos.eqb_refl Zeq_bool_refl.\nQed.\n\nLemma join2C j k : join2 j k = join2 k j.\nProof.\nrewrite /join2; extensionality b.\ncase: (j b)=> [[x y]|].\ncase: (k b)=> [[x' y']|].\nrewrite Pos.eqb_sym.\nrewrite Zeq_bool_sym.\ncase e: (_ && _)=> //.\ncase: (andP e).\nmove/Peqb_true_eq=> ->.\nby move/Zeq_bool_eq=> ->.\nby [].\nby case: (k b)=> [[? ?]|].\nQed.\n\nLemma join2A j k l : join2 j (join2 k l) = join2 (join2 j k) l.\nProof.\nrewrite /join2; extensionality b.\ncase: (j b)=> [[x y]|] //.\ncase: (k b)=> [[x' y']|] //.\ncase: (l b)=> [[x'' y'']|] //.\nrewrite Pos.eqb_sym.\nrewrite Zeq_bool_sym.\ncase e: (_ && _)=> //.\ncase: (andP e).\nmove/Peqb_true_eq=> ->.\nmove/Zeq_bool_eq=> ->.\nrewrite Pos.eqb_sym.\nrewrite Zeq_bool_sym.\ncase f: (_ && _)=> //.\ncase: (andP f).\nmove/Peqb_true_eq=> ->.\nmove/Zeq_bool_eq=> ->.\nby rewrite Pos.eqb_refl Zeq_bool_refl.\ncase f: (_ && _)=> //.\ncase: (andP f).\nmove/Peqb_true_eq=> ->.\nmove/Zeq_bool_eq=> ->.\ncase g: (_ && _)=> //.\ncase: (andP g).\nmove/Peqb_true_eq=> A.\nmove/Zeq_bool_eq=> B.\nmove: e; rewrite andb_false_iff; case.\nby rewrite A Pos.eqb_refl.\nby rewrite B Zeq_bool_refl.\nby case e: (_ && _).\nQed.\n\n(* [join_sm mu1 mu2] is a union operator on structured injections. If     *)\n(* we have struct. injections                                             *)\n(*                                                                        *)\n(*   mu1 = LOC1, locof1, EXT1, extof1                                     *)\n(*   mu2 = LOC2, locof2, EXT2, extof2                                     *)\n(*                                                                        *)\n(* then [join_sm mu1 mu2 = mu12] is equal to                              *)\n(*                                                                        *)\n(*   LOC1 \\cup LOC2, join locof1 locof2,                                  *)\n(*   EXT1 \\cap EXT2, join2 extof1 extof2                                  *)\n(*                                                                        *)\n(* w/ PUB12 = \\emptyset, FRGN12 = FRGN1 \\cap FRGN2.                       *)\n(*                                                                        *)\n(* While conceptually, LOC1 \\cup LOC2 is disjoint union, in practice we   *)\n(* make [join_sm] a total operation.  However, [mu12] is only             *)\n(* well-defined if                                                        *)\n(*                                                                        *)\n(*   1) LOC1 \\cap \\LOC2 = \\emptyset; and                                  *)\n(*   2) extof1 and extof2 are \"consistent\"                                *)\n(*                                                                        *)\n(* We say that two injections [j],[k] are consistent when the following   *)\n(* condition holds:                                                       *)\n\nDefinition consistent (j k : Values.meminj) :=\n  forall b1 b2 b2' d2 d2',\n  j b1 = Some (b2,d2) -> k b1 = Some (b2',d2') -> [/\\ b2=b2' & d2=d2'].\n\nDefinition DisjointLS :=\n  [fun mu mu' => Disjoint (locBlocksSrc mu) (locBlocksSrc mu')].\n\nDefinition DisjointLT :=\n  [fun mu mu' => Disjoint (locBlocksTgt mu) (locBlocksTgt mu')].\n\nDefinition Consistent :=\n  [fun mu mu' => consistent (as_inj mu) (as_inj mu')].\n\nDefinition join_sm mu1 mu2 : SM_Injection :=\n  Build_SM_Injection\n    [predU (locBlocksSrc mu1) & locBlocksSrc mu2]\n    [predU (locBlocksTgt mu1) & locBlocksTgt mu2]\n    pred0\n    pred0\n    (join (local_of mu1) (local_of mu2))\n    [predI (extBlocksSrc mu1) & extBlocksSrc mu2]\n    [predI (extBlocksTgt mu1) & extBlocksTgt mu2]\n    [predI (frgnBlocksSrc mu1) & frgnBlocksSrc mu2]\n    [predI (frgnBlocksTgt mu1) & frgnBlocksTgt mu2]\n    (join2 (extern_of mu1) (extern_of mu2)).\n\nLemma consistent_incr: forall mu0 mu mu',\n                         inject_incr (as_inj mu0) (as_inj mu) ->\n                         inject_incr (as_inj mu) (as_inj mu') ->\n                         Consistent mu0 mu'.\nProof.\n  clear.\n  move => mu0 mu mu'.\n  rewrite /Consistent /consistent => //=.\n  move => incr incr' b1 b2 b2' d2 d2'.\n  move/incr /incr' => map1.\n  rewrite map1.\n  case => //=.\nQed.\n\nLemma join_sm_wd (mu1 : Inj.t) (mu2 : Inj.t) :\n  DisjointLS mu1 mu2 ->\n  DisjointLT mu1 mu2 ->\n  Consistent mu1 mu2 ->\n  SM_wd (join_sm mu1 mu2).\nProof.\nmove=> D1 D2 C12; apply: Build_SM_wd; rewrite/join_sm/=/in_mem/=/in_mem/=.\nmove=> b; move: (Inj_DisjointLES mu1); move/DisjointP/(_ b).\nmove: (Inj_DisjointLES mu2); move/DisjointP/(_ b).\nby case: (locBlocksSrc mu1 b); case: (locBlocksSrc mu2 b);\n   case: (extBlocksSrc mu1 b); case: (extBlocksSrc mu2 b)=>//=;\n   solve[by left|by right|by case|by move=> _; case].\nmove=> b; move: (Inj_DisjointLET mu1); move/DisjointP/(_ b).\nmove: (Inj_DisjointLET mu2); move/DisjointP/(_ b).\nrewrite/join_sm/=/in_mem/=/in_mem/=.\nby case: (locBlocksTgt mu1 b); case: (locBlocksTgt mu2 b);\n   case: (extBlocksTgt mu1 b); case: (extBlocksTgt mu2 b)=>//=;\n   solve[by left|by right|by case|by move=> _; case].\nrewrite/join=> b1 b2 z.\ncase H: (local_of _ _)=> [[? ?]|]=> A; move: A H. case=> -> ->.\nby move/local_DomRng; move/(_ (Inj_wd mu1))=> []-> ->.\nmove/local_DomRng; move/(_ (Inj_wd mu2))=> []-> -> _.\nby split; apply/orP; right.\nmove=> b1 b2 z; move/join2P=> [].\nmove/(extern_DomRng _ (Inj_wd mu1))=> []-> -> /=.\nby move/(extern_DomRng _ (Inj_wd mu2))=> []-> -> /=.\nby [].\nmove=> b1; move/andP=> []; rewrite/join2.\nmove=> A B.\nmove: (frgnSrcAx _ (Inj_wd _) _ A)=> []b2 []d2 []A0 A'.\nmove: (frgnSrcAx _ (Inj_wd _) _ B)=> []b2' []d2' []B0 B'.\nexists b2,d2; move: A' B'; rewrite A0 B0; case H: (_ && _).\nby move: H; move/andP=> []; move/Peqb_true_eq=> <- _ -> ->.\nhave A0': as_inj mu1 b1 = Some (b2,d2).\n  by rewrite /as_inj /join A0.\nhave B0': as_inj mu2 b1 = Some (b2',d2').\n  by rewrite /as_inj /join B0.\nmove: (C12 _ _ _ _ _ A0' B0') H; case=> <- <-; move/andP=> []; split.\nby rewrite/is_true Pos.eqb_eq.\nby rewrite/is_true -Zeq_is_eq_bool.\nby [].\nmove=> b; move/andP=> [].\nmove/frgntgt_sub_exttgt; rewrite/in_mem/= => ->.\nby move/frgntgt_sub_exttgt; rewrite/in_mem/= => ->.\nQed.\n\n(* The following definitions/lemmas extend [join2] to nonempty sequences  *)\n(* of struct. injections.                                                 *)\n\nDefinition AllDisjoint (proj : SM_Injection -> Values.block -> bool) :=\n  All2 (fun mu mu' => Disjoint (proj mu) (proj mu')).\n\nDefinition AllConsistent :=\n  All2 (fun mu mu' => consistent (as_inj mu) (as_inj mu')).\n\nFixpoint join_all (mu0 : Inj.t) (mus : seq Inj.t) : SM_Injection :=\n  if mus is [:: mu & mus] then join_sm mu (join_all mu0 mus)\n  else mu0.\n\nLemma join_all_cons mu0 mu mus :\n  join_all mu0 (mu :: mus) = join_sm mu (join_all mu0 mus).\nProof. by []. Qed.\n\nLemma join_all_frgnS_cons mu0 mu mus :\n  frgnBlocksSrc (join_all mu0 (mu :: mus))\n  = [predI (frgnBlocksSrc mu) & frgnBlocksSrc (join_all mu0 mus)].\nProof. by rewrite join_all_cons. Qed.\n\nLemma join_all_frgnT_cons mu0 mu mus :\n  frgnBlocksTgt (join_all mu0 (mu :: mus))\n  = [predI (frgnBlocksTgt mu) & frgnBlocksTgt (join_all mu0 mus)].\nProof. by rewrite join_all_cons. Qed.\n\nLemma join_all_extS_cons mu0 mu mus :\n  extBlocksSrc (join_all mu0 (mu :: mus))\n  = [predI (extBlocksSrc mu) & extBlocksSrc (join_all mu0 mus)].\nProof. by rewrite join_all_cons. Qed.\n\nLemma join_all_extT_cons mu0 mu mus :\n  extBlocksTgt (join_all mu0 (mu :: mus))\n  = [predI (extBlocksTgt mu) & extBlocksTgt (join_all mu0 mus)].\nProof. by rewrite join_all_cons. Qed.\n\nLemma join_all_disjoint_src mu0 (mu : Inj.t) mus :\n  All (fun mu' => Disjoint (locBlocksSrc mu0) (locBlocksSrc mu'))\n    (map Inj.mu (mu :: mus)) ->\n  Disjoint (locBlocksSrc mu0) (locBlocksSrc (join_all mu mus)).\nProof.\nelim: mus=> //=; first by move=> [].\nby move=> mu' mus' IH []A []B C; move: (IH (conj A C))=> D; apply: DisjointInU.\nQed.\n\nLemma join_all_disjoint_tgt mu0 (mu : Inj.t) mus :\n  All (fun mu' => Disjoint (locBlocksTgt mu0) (locBlocksTgt mu'))\n    (map Inj.mu (mu :: mus)) ->\n  Disjoint (locBlocksTgt mu0) (locBlocksTgt (join_all mu mus)).\nProof.\nelim: mus=> //=; first by move=> [].\nby move=> mu' mus' IH []A []B C; move: (IH (conj A C))=> D; apply: DisjointInU.\nQed.\n\nLemma join2_consistent j k k' :\n  consistent j k ->\n  consistent j k' ->\n  consistent j (join2 k k').\nProof.\nrewrite/consistent=> A B b1 b2 b2' d2 d2' C.\nby move/join2P=> []D E; case: (A _ _ _ _ _ C D).\nQed.\n\nLemma local_some_extern_none (mu : Inj.t) b1 b2 d2 :\n  local_of mu b1 = Some (b2,d2) ->\n  extern_of mu b1 = None.\nProof.\ncase/local_DomRng; first by apply Inj_wd.\nmove/locBlocksSrc_externNone=> -> //.\nby apply: Inj_wd.\nQed.\n\nLemma locof_extof_False (mu : Inj.t) (mus : seq Inj.t) b1 b2 d2 b2' d2' :\n  local_of (join_all mu mus) b1 = Some (b2, d2) ->\n  extern_of (join_all mu mus) b1 = Some (b2', d2') ->\n  False.\nProof.\nelim: mus=> //; first by move/local_some_extern_none=> ->.\nmove=> mu0 mus' IH /=; rewrite /join.\ncase e: (local_of mu0 b1)=> [[b' ofs']|].\ncase=> e1 e2; rewrite e1 e2 in e.\nby move/join2P=> []; move: (local_some_extern_none e)=> ->.\nmove=> A; move/join2P=> []B C.\napply: (IH A C).\nQed.\n\nLemma join_sm_consistent mu0 (mu1 mu2 : Inj.t) :\n  Consistent mu0 mu1 ->\n  Consistent mu0 mu2 ->\n  Consistent mu0 (join_sm mu1 mu2).\nProof.\nmove=> A B b1 b2 b2' d2 d2' E /=; rewrite /join_sm /as_inj /join /=.\ncase e: (join2 _ _ _)=> // [[b' ofs']|].\ncase=> e1 e2; rewrite e1 e2 in e.\nmove: e; move/join2P=> []E1 E2.\nhave E1': as_inj mu1 b1 = Some (b2',d2').\n  by rewrite /as_inj /join E1.\nby apply: (A _ _ _ _ _ E E1').\ncase f: (local_of _ _)=> // [[b' ofs']|].\ncase=> e1 e2.\nrewrite e1 e2 in f.\nhave F: extern_of mu1 b1 = None.\n  by apply: (local_some_extern_none f).\nhave G: as_inj mu1 b1 = Some (b2',d2').\n  by rewrite /as_inj /join F f.\nby apply: (A _ _ _ _ _ E G).\nmove=> F.\nhave G: as_inj mu2 b1 = Some (b2',d2').\n  rewrite /as_inj /join F.\n  case G: (extern_of _ _)=> //[[b' ofs']].\n  by rewrite (local_some_extern_none F) in G.\nby apply: (B _ _ _ _ _ E G).\nQed.\n\nLemma join_sm_consistent' mu0 (mu1 mu2 : Inj.t) (mus : seq Inj.t) :\n  Consistent mu0 mu1 ->\n  Consistent mu0 (join_all mu2 mus) ->\n  Consistent mu0 (join_sm mu1 (join_all mu2 mus)).\nProof.\nmove=> A B b1 b2 b2' d2 d2' E /=; rewrite /join_sm /as_inj /join /=.\ncase e: (join2 _ _ _)=> // [[b' ofs']|].\ncase=> e1 e2; rewrite e1 e2 in e.\nmove: e; move/join2P=> []E1 E2.\nhave E1': as_inj mu1 b1 = Some (b2',d2').\n  by rewrite /as_inj /join E1.\nby apply: (A _ _ _ _ _ E E1').\ncase f: (local_of _ _)=> // [[b' ofs']|].\ncase=> e1 e2.\nrewrite e1 e2 in f.\nhave F: extern_of mu1 b1 = None.\n  by apply: (local_some_extern_none f).\nhave G: as_inj mu1 b1 = Some (b2',d2').\n  by rewrite /as_inj /join F f.\nby apply: (A _ _ _ _ _ E G).\nmove=> F.\nhave G: as_inj (join_all mu2 mus) b1 = Some (b2',d2').\n  rewrite /as_inj /join F.\n  case G: (extern_of _ _)=> //[[b' ofs']].\n  by elimtype False; apply: (locof_extof_False F G).\nby apply: (B _ _ _ _ _ E G).\nQed.\n\nLemma join_all_consistent mu0 (mu : Inj.t) mus :\n  All (fun mu' => consistent (as_inj mu0) (as_inj mu'))\n    (map Inj.mu (mu :: mus)) ->\n  consistent (as_inj mu0) (as_inj (join_all mu mus)).\nProof.\nelim: mus=> //=; first by move=> [].\nmove=> mu' mus' IH []A []B C; move: (IH (conj A C))=> D.\nby apply: join_sm_consistent'.\nQed.\n\nLemma join2P' (j k : SM_Injection) b1 :\n  Consistent j k ->\n  (join2 (extern_of j) (extern_of k) b1 = None <->\n   [\\/ extern_of j b1 = None | extern_of k b1 = None]).\nProof.\nrewrite /=/consistent=> C.\nrewrite/join2; split.\ncase A: (extern_of j b1)=> // [[x y]|].\ncase B: (extern_of k b1)=> // [[x' y']|].\nhave A': as_inj j b1 = Some (x,y) by rewrite /as_inj /join A.\nhave B': as_inj k b1 = Some (x',y') by rewrite /as_inj /join B.\ncase: (C _ _ _ _ _ A' B')=> -> ->.\nby rewrite Pos.eqb_refl Zeq_bool_refl /=.\nby right.\nby left.\ncase=> ->; first by [].\nby case: (extern_of j b1)=> // [[? ?]].\nQed.\n\nLemma Disjoint_locSrcC mu mu' : DisjointLS mu mu' -> DisjointLS mu' mu.\nProof. by rewrite /= DisjointC. Qed.\n\nLemma Disjoint_locTgtC mu mu' : DisjointLT mu mu' -> DisjointLT mu' mu.\nProof. by rewrite /= DisjointC. Qed.\n\nLemma consistentC mu mu' : Consistent mu mu' -> Consistent mu' mu.\nProof.\nrewrite /= /consistent=> A b1 b2 b2' d2 d2' B C.\nby case: (A _ _ _ _ _ C B)=> -> ->.\nQed.\n\nLemma join_all_wd mu (mus : seq Inj.t) :\n  AllDisjoint locBlocksSrc $ map Inj.mu (mu :: mus) ->\n  AllDisjoint locBlocksTgt $ map Inj.mu (mu :: mus) ->\n  AllConsistent $ map Inj.mu (mu :: mus) ->\n  SM_wd (join_all mu mus).\nProof.\nelim: mus=> /=; first by move=> _ _ _; apply: (Inj_wd mu).\nmove=> mu0 mus IH A B C.\nmove: {A B C}\n  (All2C A Disjoint_locSrcC) (All2C B Disjoint_locTgtC)\n  (All2C C consistentC).\nmove/All2_cons=> []A B.\nmove/All2_cons=> []C D.\nmove/All2_cons=> []E F.\nhave wd: SM_wd (join_all mu mus) by apply IH.\nchange (SM_wd (join_sm mu0 (Inj.mk wd))).\napply: join_sm_wd=> /=.\nby apply: join_all_disjoint_src.\nby apply: join_all_disjoint_tgt.\nby apply join_all_consistent.\nQed.\n\nLemma join_sm_frgn (mu1 mu2 : Inj.t) b :\n  frgnBlocksSrc mu1 b ->\n  frgnBlocksSrc mu2 b ->\n  frgnBlocksSrc (join_sm mu1 mu2) b.\nProof. by rewrite/join_sm/= => A B; apply/andP; split. Qed.\n\nDefinition assimilated mu0 mu := join_sm mu0 mu = mu.\n\nLemma assimilated_sub_locSrc mu0 mu :\n  assimilated mu0 mu -> {subset (locBlocksSrc mu0) <= locBlocksSrc mu}.\nProof. by rewrite/assimilated/join_sm=> <- b /= => A; apply/orP; left. Qed.\n\nLemma assimilated_sub_locTgt mu0 mu :\n  assimilated mu0 mu -> {subset (locBlocksTgt mu0) <= locBlocksTgt mu}.\nProof. by rewrite/assimilated/join_sm=> <- b /= => A; apply/orP; left. Qed.\n\nLemma assimilated_sub_extSrc mu0 mu :\n  assimilated mu0 mu -> {subset (locBlocksSrc mu0) <= locBlocksSrc mu}.\nProof. by rewrite/assimilated/join_sm=> <- b /= => A; apply/orP; left. Qed.\n\nLemma join_sm_extSrc mu1 mu2 :\n  extBlocksSrc (join_sm mu1 mu2)\n  = [predI (extBlocksSrc mu1) & extBlocksSrc mu2].\nProof. by []. Qed.\n\nLemma join_sm_extTgt mu1 mu2 :\n  extBlocksTgt (join_sm mu1 mu2)\n  = [predI (extBlocksTgt mu1) & extBlocksTgt mu2].\nProof. by []. Qed.\n\nLemma join_sm_frgnSrc mu1 mu2 :\n  frgnBlocksSrc (join_sm mu1 mu2)\n  = [predI (frgnBlocksSrc mu1) & frgnBlocksSrc mu2].\nProof. by []. Qed.\n\nLemma join_sm_frgnTgt mu1 mu2 :\n  frgnBlocksTgt (join_sm mu1 mu2)\n  = [predI (frgnBlocksTgt mu1) & frgnBlocksTgt mu2].\nProof. by []. Qed.\n\nLemma join_sm_preserves_globals F V (ge : Genv.t F V) (mu1 mu2 : Inj.t) :\n  Events.meminj_preserves_globals ge (extern_of mu1) ->\n  Events.meminj_preserves_globals ge (extern_of mu2) ->\n  Events.meminj_preserves_globals ge (extern_of (join_sm mu1 mu2)).\nProof.\nmove=> []A []B C []D []E G; rewrite /join_sm /= /join2; split.\n+ move=> id b H.\n  rewrite (A _ _ H) (D _ _ H).\n  by case: (@andP _ _)=> // [][]; rewrite /is_true Pos.eqb_eq -Zeq_is_eq_bool.\nsplit.\n+ move=> b gv H; rewrite (B _ _ H) (E _ _ H).\n  by case: (@andP _ _)=> // [][]; rewrite /is_true Pos.eqb_eq -Zeq_is_eq_bool.\n+ move=> b1 b2 d gv H.\n  case H1: (extern_of _ _)=> // [[? ?]]; case H2: (extern_of _ _)=> // [[? ?]].\n  case: (@andP _ _)=> //; case.\n  rewrite /is_true Pos.eqb_eq -Zeq_is_eq_bool=> X Y; case=> Z W.\n  by move: X Y Z W H1 H2=> -> -> -> -> //; move/(C _ _ _ _ H)=> <-.\nQed.\n\nLemma join_sm_isGlob F V (ge : Genv.t F V) (mu1 mu2 : Inj.t) :\n (forall b, isGlobalBlock ge b -> frgnBlocksSrc mu1 b) ->\n (forall b, isGlobalBlock ge b -> frgnBlocksSrc mu2 b) ->\n forall b, isGlobalBlock ge b -> frgnBlocksSrc (join_sm mu1 mu2) b.\nProof.\nrewrite/join_sm /= => A B b C; move: (A _ C) (B _ C)=> ? ?.\nby apply/andP; split.\nQed.\n\nLemma join_all_id mu : join_all mu [::] = mu.\nProof. by []. Qed.\n\nLemma join_all_preserves_globals\n      F V (ge : Genv.t F V) (mu : Inj.t) (mus : seq Inj.t) :\n  Events.meminj_preserves_globals ge (extern_of mu) ->\n  (AllDisjoint locBlocksSrc \\o map Inj.mu) (mu :: mus) ->\n  (AllDisjoint locBlocksTgt \\o map Inj.mu) (mu :: mus) ->\n  (AllConsistent \\o map Inj.mu) (mu :: mus) ->\n  All (Events.meminj_preserves_globals ge \\o extern_of \\o Inj.mu) mus ->\n  Events.meminj_preserves_globals ge (extern_of (join_all mu mus)).\nProof.\nelim: mus=> //= mu' mus' IH PRES A B C.\nmove: {A B C}\n  (All2C A Disjoint_locSrcC) (All2C B Disjoint_locTgtC)\n  (All2C C consistentC).\nmove/All2_cons=> []B C.\nmove/All2_cons=> []D E.\nmove/All2_cons=> []G H.\nhave wd: SM_wd (join_all mu mus') by apply: join_all_wd.\nmove=> []I J.\nchange (Events.meminj_preserves_globals ge\n  (extern_of (join_sm mu' (Inj.mk wd)))).\napply: join_sm_preserves_globals=> //.\nby apply: IH.\nQed.\n\nLemma join_all_isGlob F V (ge : Genv.t F V) (mu : Inj.t) (mus : seq Inj.t) :\n (forall b, isGlobalBlock ge b -> frgnBlocksSrc mu b) ->\n All (fun mu => forall b, isGlobalBlock ge b -> frgnBlocksSrc mu b)\n     (map Inj.mu mus) ->\n forall b, isGlobalBlock ge b -> frgnBlocksSrc (join_all mu mus) b.\nProof.\nelim: mus mu=> // mu' mus' IH mu A /= []B C b D; apply/andP; split=> //.\nby apply: (B _ D).\nby apply: IH.\nQed.\n\nLemma join_sm_valid mu1 mu2 m1 m2 :\n  sm_valid mu1 m1 m2 ->\n  sm_valid mu2 m1 m2 ->\n  sm_valid (join_sm mu1 mu2) m1 m2.\nProof.\nrewrite/join_sm/sm_valid/DOM/RNG/DomSrc/DomTgt /= => [][]A B []C D; split.\nmove=> b1; move/orP; case.\nmove/orP; case=> E.\nby apply: A; apply/orP; left.\nby apply: C; apply/orP; left.\nmove/andP=> []E F.\nby apply: A; apply/orP; right.\nmove=> b2; move/orP; case.\nmove/orP; case=> E.\nby apply: B; apply/orP; left.\nby apply: D; apply/orP; left.\nmove/andP=> []E F.\nby apply: D; apply/orP; right.\nQed.\n\nLemma join_smvalid_src mu1 mu2 m1 :\n  smvalid_src mu1 m1 ->\n  smvalid_src mu2 m1 ->\n  smvalid_src (join_sm mu1 mu2) m1.\nProof.\nrewrite/join_sm/smvalid_src/DOM/RNG/DomSrc/DomTgt /= => []A B.\nmove=> b1; move/orP; case.\nmove/orP; case=> E.\nby apply: A; apply/orP; left.\nby apply: B; apply/orP; left.\nmove/andP=> []E F.\nby apply: A; apply/orP; right.\nQed.\n\nLemma join_all_valid (mu : Inj.t) mus m1 m2 :\n  sm_valid mu m1 m2 ->\n  All (fun mu0 => sm_valid (Inj.mu mu0) m1 m2) mus ->\n  sm_valid (join_all mu mus) m1 m2.\nProof.\nmove: mu m1 m2; elim: mus=> // mu' mus' IH mu m1 m2 A /= []B C.\nby apply: join_sm_valid=> //; apply: IH.\nQed.\n\nLemma join_all_valid_src (mu : Inj.t) mus m1 :\n  smvalid_src mu m1 ->\n  All (fun mu0 => smvalid_src (Inj.mu mu0) m1) mus ->\n  smvalid_src (join_all mu mus) m1.\nProof.\nmove: mu m1; elim: mus=> // mu' mus' IH mu m1 A /= []B C.\nby apply: join_smvalid_src=> //; apply: IH.\nQed.\n\nLemma DisjointLS_restrict mu1 mu2 X Y :\n  DisjointLS mu1 mu2 ->\n  DisjointLS (restrict_sm mu1 X) (restrict_sm mu2 Y).\nProof. by case: mu1; case: mu2. Qed.\n\nLemma DisjointLT_restrict mu1 mu2 X Y :\n  DisjointLT mu1 mu2 ->\n  DisjointLT (restrict_sm mu1 X) (restrict_sm mu2 Y).\nProof. by case: mu1; case: mu2. Qed.\n\nLemma DisjointLS_E1 mu1 mu2 b :\n  DisjointLS mu1 mu2 ->\n  locBlocksSrc mu1 b ->\n  locBlocksSrc mu2 b=false.\nProof.\nmove/DisjointP; move/(_ b); case; first by contradiction.\nby case: (locBlocksSrc mu2 b).\nQed.\n\nLemma DisjointLS_E2 mu1 mu2 b :\n  DisjointLS mu1 mu2 ->\n  locBlocksSrc mu2 b ->\n  locBlocksSrc mu1 b=false.\nProof.\nmove/DisjointP; move/(_ b); case; first by case: (locBlocksSrc mu1 b).\nby contradiction.\nQed.\n\nLemma DisjointLT_E1 mu1 mu2 b :\n  DisjointLT mu1 mu2 ->\n  locBlocksTgt mu1 b ->\n  locBlocksTgt mu2 b=false.\nProof.\nmove/DisjointP; move/(_ b); case; first by contradiction.\nby case: (locBlocksTgt mu2 b).\nQed.\n\nLemma DisjointLT_E2 mu1 mu2 b :\n  DisjointLT mu1 mu2 ->\n  locBlocksTgt mu2 b ->\n  locBlocksTgt mu1 b=false.\nProof.\nmove/DisjointP; move/(_ b); case; first by case: (locBlocksTgt mu1 b).\nby contradiction.\nQed.\n\nLemma DisjointLS_incr mu1 mu1' mu2 m1 m2 m1' m2' :\n  DisjointLS mu1 mu2 ->\n  intern_incr mu1 mu1' ->\n  sm_inject_separated mu1 mu1' m1 m2 ->\n  sm_locally_allocated mu1 mu1' m1 m2 m1' m2' ->\n  sm_valid mu2 m1 m2 ->\n  DisjointLS mu1' mu2.\nProof.\nmove/DisjointP=> A B C D E /=; rewrite DisjointP=> b; move: (A b).\ncase=> // F.\ncase G: (locBlocksSrc mu2 b); last by right. left=> H.\nhave F': locBlocksSrc mu1 b = false by move: F; case: (locBlocksSrc mu1 b).\ncase: (sm_inject_separated_intern_MYB _ _ _ _ _ _ C D); move/(_ b F' H)=> I _.\nby case: E; move/(_ b); rewrite/DOM/DomSrc G=> J _; apply: I; apply: J.\nby right.\nQed.\n\nLemma DisjointLT_incr mu1 mu1' mu2 m1 m2 m1' m2' :\n  DisjointLT mu1 mu2 ->\n  intern_incr mu1 mu1' ->\n  sm_inject_separated mu1 mu1' m1 m2 ->\n  sm_locally_allocated mu1 mu1' m1 m2 m1' m2' ->\n  sm_valid mu2 m1 m2 ->\n  DisjointLT mu1' mu2.\nProof.\nmove/DisjointP=> A B C D E /=; rewrite DisjointP=> b; move: (A b).\ncase=> // F.\ncase G: (locBlocksTgt mu2 b); last by right. left=> H.\nhave F': locBlocksTgt mu1 b = false by move: F; case: (locBlocksTgt mu1 b).\ncase: (sm_inject_separated_intern_MYB _ _ _ _ _ _ C D)=> _; move/(_ b F' H)=> I.\nby case: E=> _; move/(_ b); rewrite/RNG/DomTgt G => J; apply: I; apply: J.\nby right.\nQed.\n\nLemma AllDisjointLS_incr mu1 mu1' mus m1 m2 m1' m2' :\n  All (fun mu0 => DisjointLS mu1 mu0) mus ->\n  intern_incr mu1 mu1' ->\n  sm_inject_separated mu1 mu1' m1 m2 ->\n  sm_locally_allocated mu1 mu1' m1 m2 m1' m2' ->\n  All (fun mu0 => sm_valid mu0 m1 m2) mus ->\n  All (fun mu0 => DisjointLS mu1' mu0) mus.\nProof.\nelim: mus=> // mu0 mus' IH /= []A B C D E []F G.\nsplit; first by apply: (DisjointLS_incr A C D E F).\nby apply: IH.\nQed.\n\nLemma AllDisjointLT_incr mu1 mu1' mus m1 m2 m1' m2' :\n  All (fun mu0 => DisjointLT mu1 mu0) mus ->\n  intern_incr mu1 mu1' ->\n  sm_inject_separated mu1 mu1' m1 m2 ->\n  sm_locally_allocated mu1 mu1' m1 m2 m1' m2' ->\n  All (fun mu0 => sm_valid mu0 m1 m2) mus ->\n  All (fun mu0 => DisjointLT mu1' mu0) mus.\nProof.\nelim: mus=> // mu0 mus' IH /= []A B C D E []F G.\nsplit; first by apply: (DisjointLT_incr A C D E F).\nby apply: IH.\nQed.\n\nLemma vis_join_sm mu1 mu2 :\n  vis (join_sm mu1 mu2)\n  = [predU [predU (locBlocksSrc mu1) & locBlocksSrc mu2]\n         & [predI (frgnBlocksSrc mu1) & frgnBlocksSrc mu2]].\nProof.\nby rewrite/vis/join_sm/=; extensionality b=> /=; rewrite/predU.\nQed.\n\nLemma locBlocksSrc_vis mu : {subset (locBlocksSrc mu) <= vis mu}.\nProof. by rewrite/vis=> b; rewrite/in_mem/= => A; apply/orP; left. Qed.\n\nLemma frgnBlocksSrc_vis mu : {subset (frgnBlocksSrc mu) <= vis mu}.\nProof. by rewrite/vis=> b; rewrite/in_mem/= => A; apply/orP; right. Qed.\n\nLemma join_sm_incr mu1 mu1' mu2 mu2' :\n  disjoint (local_of mu1') (local_of mu2') ->\n  intern_incr mu1 mu1' ->\n  intern_incr mu2 mu2' ->\n  intern_incr (join_sm mu1 mu2) (join_sm mu1' mu2').\nProof.\nrewrite/intern_incr/join_sm/= => disj.\nmove=> []incr1 []<- []A []B []? []? []<- []<- []<- <-.\nmove=> []incr2 []<- []C []D []? []? []<- []<- []<- <-.\nsplit=> //.\napply: inject_incr_join=> //.\nsplit=> //.\nsplit=> //.\nmove=> b; move/orP; case=> H.\nby rewrite/in_mem/= (A _ H).\nby rewrite/in_mem/= (C _ H); apply/orP; right.\nsplit=> //.\nmove=> b; move/orP; case=> H.\nby rewrite/in_mem/= (B _ H).\nby rewrite/in_mem/= (D _ H); apply/orP; right.\nQed.\n\nLemma join_all_incr (mu_trash mu mu' : Inj.t) (mus : seq Inj.t) :\n  disjoint (local_of mu') (local_of (join_all mu_trash mus)) ->\n  intern_incr mu mu' ->\n  intern_incr (join_all mu_trash (mu :: mus))\n              (join_all mu_trash (mu':: mus)).\nProof. by move=> /= A B; apply: join_sm_incr. Qed.\n\nLemma joinP j k b1 b2 d :\n  join j k b1 = Some (b2,d) <->\n  j b1 = Some (b2,d) \\/ (j b1 = None /\\ k b1 = Some (b2,d)).\nProof.\nrewrite/join; split.\ncase: (j b1)=> // [[? ?]|->]; first by case=> -> ->; left.\nby right. case=> A; first by rewrite A.\nby case: A=> ->.\nQed.\n\nLemma joinP' j k b1 :\n  join j k b1 = None <-> j b1 = None /\\ k b1 = None.\nProof.\nrewrite/join; split; first by case: (j b1)=> //; first by case.\nby move=> []-> ->.\nQed.\n\nLemma as_injE mu b1 b2 d :\n  as_inj mu b1 = Some (b2,d) ->\n  [\\/ local_of mu b1 = Some (b2,d) | extern_of mu b1 = Some (b2,d)].\nProof.\nrewrite/as_inj/join; case: (extern_of mu b1)=> // [[? ?]|].\nby case=> -> ->; right.\nby left.\nQed.\n\nLemma as_injE' mu b1 :\n  as_inj mu b1 = None ->\n  [/\\ local_of mu b1 = None & extern_of mu b1 = None].\nProof.\nrewrite/as_inj/join; case: (extern_of mu b1)=> // [[? ?]].\nby discriminate.\nQed.\n\nLemma local_of_join_smE mu1 mu2 b1 b2 d :\n  local_of (join_sm mu1 mu2) b1 = Some (b2,d) ->\n  [\\/ local_of mu1 b1 = Some (b2,d)\n    | [/\\ local_of mu1 b1 = None & local_of mu2 b1 = Some (b2,d)]].\nProof. by rewrite/join_sm/=; move/joinP. Qed.\n\nLemma local_of_join_smE' mu1 mu2 b1 :\n  local_of (join_sm mu1 mu2) b1 = None ->\n  [/\\ local_of mu1 b1 = None & local_of mu2 b1 = None].\nProof. by rewrite/join_sm/=; move/joinP'. Qed.\n\nLemma extern_of_join_smE mu1 mu2 b1 b2 d :\n  extern_of (join_sm mu1 mu2) b1 = Some (b2,d) ->\n  [/\\ extern_of mu1 b1 = Some (b2,d)\n    & extern_of mu2 b1 = Some (b2,d)].\nProof. by rewrite/join_sm/=; move/join2P. Qed.\n\nLemma extern_of_join_smE' mu1 mu2 b1 :\n  Consistent mu1 mu2 ->\n  extern_of (join_sm mu1 mu2) b1 = None ->\n  [\\/ extern_of mu1 b1 = None\n    | extern_of mu2 b1 = None].\nProof. by rewrite/join_sm/=; move/(join2P' b1)=> ->. Qed.\n\nLemma join2_restrict j k X :\n  join2 (restrict j X) (restrict k X) = restrict (join2 j k) X.\nProof.\nextensionality b.\ncase A: (join2 _ _ b)=> [[b' ofs]|].\nmove: A; move/join2P=> [].\nmove/restrictD_Some=> []A B; move/restrictD_Some=> []C _.\nby rewrite/join2/restrict B A C Pos.eqb_refl Zeq_bool_refl.\nmove: A; rewrite/join2.\ncase A: (restrict j X b)=> [[b' ofs]|].\ncase B: (restrict k X b)=> [[b'' ofs']|].\ncase C: (Pos.eqb b' b'') A B.\ncase D: (Zeq_bool ofs ofs')=> //=.\nby rewrite/restrict; case E: (X b)=> //; move=> -> ->; rewrite C D.\nby rewrite/restrict; case E: (X b)=> //; move=> -> ->; rewrite C.\nmove: A; move/restrictD_Some=> []C D; rewrite/restrict D C.\nmove: B; move/restrictD_None; case: (k b)=> // [[b'' ofs']].\nby move/(_ b'' ofs' erefl); move: D=> ->.\nrewrite/restrict; case B: (j b)=> // [[b' ofs]|].\nby move: A; move/restrictD_None; move/(_ b' ofs B)=> ->.\nby case: (X b).\nQed.\n\nLemma join_sm_restrict mu1 mu2 X :\n  restrict_sm (join_sm mu1 mu2) X\n  = join_sm (restrict_sm mu1 X) (restrict_sm mu2 X).\nProof.\nrewrite/join_sm/=; f_equal.\nby rewrite !restrict_sm_locBlocksSrc.\nby rewrite !restrict_sm_locBlocksTgt.\nby rewrite -!join_restrict !restrict_sm_local.\nby rewrite !restrict_sm_extBlocksSrc.\nby rewrite !restrict_sm_extBlocksTgt.\nby rewrite !restrict_sm_frgnBlocksSrc.\nby rewrite !restrict_sm_frgnBlocksTgt.\nby rewrite -!join2_restrict !restrict_sm_extern.\nQed.\n\nLemma disjoint_restrict j k X :\n  disjoint j k ->\n  disjoint (restrict j X) (restrict k X).\nProof. by rewrite/disjoint/restrict=> A b; case: (X b)=> //; left. Qed.\n\nLemma restrict_incr' j j' X X' :\n  {subset X <= X'} ->\n  Values.inject_incr j j' ->\n  Values.inject_incr (restrict j X) (restrict j' X').\nProof.\nmove=> A; rewrite/Values.inject_incr=> B b b' ofs.\nmove/restrictD_Some=> []C; move/A; rewrite/in_mem/= => D.\nby rewrite/restrict D; apply: (B _ _ _ C).\nQed.\n\nLemma restrict_disj j X X' :\n  {subset X <= X'} ->\n  (forall b b' ofs, j b = Some (b',ofs) -> ~~ [predD X' & X] b) ->\n  restrict j X = restrict j X'.\nProof.\nmove=> A B; rewrite/restrict; extensionality b.\ncase C: (X b); first by move: (A b C); rewrite/in_mem/= => ->.\ncase D: (X' b)=> //.\ncase E: (j b)=> // [[b' ofs]].\nmove: (B _ _ _ E).\nrewrite notin_predD; move/orP; case.\nby rewrite/in_mem/= D.\nby rewrite/in_mem/= C.\nQed.\n\nLemma intern_incr_restrict mu mu' X X' :\n  intern_incr mu mu' ->\n  {subset X <= X'} ->\n  (forall b b' ofs, extern_of mu' b = Some (b',ofs) -> ~~ [predD X' & X] b) ->\n  intern_incr (restrict_sm mu X) (restrict_sm mu' X').\nProof.\ncase=> A []B []C []D []E []F []G []H []I J K; split=> //.\nby rewrite 2!restrict_sm_local; apply: restrict_incr'.\nsplit; first by rewrite 2!restrict_sm_extern; rewrite B; apply: restrict_disj.\nsplit; first by rewrite 2!restrict_sm_locBlocksSrc; apply: C.\nsplit; first by rewrite 2!restrict_sm_locBlocksTgt; apply: D.\nsplit; first by rewrite 2!restrict_sm_pubBlocksSrc E.\nsplit; first by rewrite 2!restrict_sm_pubBlocksTgt F.\nsplit; first by rewrite 2!restrict_sm_frgnBlocksSrc G.\nsplit; first by rewrite 2!restrict_sm_frgnBlocksTgt H.\nsplit; first by rewrite 2!restrict_sm_extBlocksSrc I.\nby rewrite 2!restrict_sm_extBlocksTgt J.\nQed.\n\nLemma join_sm_vis_loc mu1 (mu1' : Inj.t) mu2 b :\n  intern_incr mu1 mu1' ->\n  vis (join_sm mu1 mu2) b=false ->\n  vis (join_sm mu1' mu2) b ->\n  locBlocksSrc mu1 b=false /\\ locBlocksSrc mu1' b.\nProof.\nrewrite 2!vis_join_sm /=/in_mem/=/in_mem/=.\nmove=> incr D E.\nhave F: locBlocksSrc mu1 b=false by move: D; case: (locBlocksSrc mu1 b).\nrewrite F in D; move: D=> /= => D.\nhave G: locBlocksSrc mu2 b=false by move: D; case: (locBlocksSrc mu2 b).\nrewrite G in D; move: D=> /= => D.\nhave H: (frgnBlocksSrc mu1 b=false \\/ frgnBlocksSrc mu2 b=false).\n  move: D; case: (frgnBlocksSrc mu1 b); case: (frgnBlocksSrc mu2 b)=> //=.\n  by right. by left. by right.\nhave I: (frgnBlocksSrc mu1' b && frgnBlocksSrc mu2 b = false).\n  move: H; case: incr=> _ []_ []_ []_ []_ []_ []<- []_ _.\n  case: (frgnBlocksSrc mu1 b)=> //.\n  case: (frgnBlocksSrc mu2 b)=> //.\n  by case.\nhave J: locBlocksSrc mu1' b.\n  by move: E; rewrite G I=> /=; move/orP; case=> //; move/orP; case.\nby split.\nQed.\n\nLemma join_sm_vis_dom mu1 (mu1' : Inj.t) mu2 b :\n  intern_incr mu1 mu1' ->\n  vis (join_sm mu1 mu2) b=false ->\n  vis (join_sm mu1' mu2) b ->\n  DOM mu1 b=false /\\ DOM mu1' b.\nProof.\nrewrite 2!vis_join_sm /=/in_mem/=/in_mem/=.\nmove=> incr D E.\nhave F: locBlocksSrc mu1 b=false by move: D; case: (locBlocksSrc mu1 b).\nrewrite F in D; move: D=> /= => D.\nhave G: locBlocksSrc mu2 b=false by move: D; case: (locBlocksSrc mu2 b).\nrewrite G in D; move: D=> /= => D.\nhave H: (frgnBlocksSrc mu1 b=false \\/ frgnBlocksSrc mu2 b=false).\n  move: D; case: (frgnBlocksSrc mu1 b); case: (frgnBlocksSrc mu2 b)=> //=.\n  by right. by left. by right.\nhave I: (frgnBlocksSrc mu1' b && frgnBlocksSrc mu2 b = false).\n  move: H; case: incr=> _ []_ []_ []_ []_ []_ []<- []_ _.\n  case: (frgnBlocksSrc mu1 b)=> //.\n  case: (frgnBlocksSrc mu2 b)=> //.\n  by case.\nhave J: locBlocksSrc mu1' b.\n  by move: E; rewrite G I=> /=; move/orP; case=> //; move/orP; case.\nhave K: extBlocksSrc mu1' b=false.\n  by apply: (locBlocksSrc_extBlocksSrc _ (Inj_wd mu1') _ J).\nhave L: extBlocksSrc mu1 b=false.\n  by move: H; case: incr=> _ []_ []_ []_ []_ []_ []_ []_ []->.\nby rewrite/DOM/DomSrc F J K L.\nQed.\n\nLemma join_sm_vis_extBlocksSrc mu1 mu1' mu2 :\n  intern_incr mu1 mu1' ->\n  extBlocksSrc (join_sm mu1 mu2) = extBlocksSrc (join_sm mu1' mu2).\nProof.\nrewrite 2!join_sm_extSrc.\nby case=> _ []_ []_ []_ []_ []_ []_ []_ []->.\nQed.\n\nLemma join_sm_restrict_incr mu1 (mu1' mu2 : Inj.t) m1 m2 :\n  disjoint (local_of mu1') (local_of mu2) ->\n  intern_incr mu1 mu1' ->\n  sm_inject_separated mu1 mu1' m1 m2 ->\n  sm_valid mu2 m1 m2 ->\n  let mu12  := join_sm mu1 mu2 in\n  let mu12' := join_sm mu1' mu2 in\n  intern_incr (restrict_sm mu12 (vis mu12)) (restrict_sm mu12' (vis mu12')).\nProof.\nmove=> A B sep val mu12 mu12'; rewrite 2!join_sm_restrict.\nhave S: {subset vis mu12 <= vis mu12'}.\n  { move=> b; rewrite 2!vis_join_sm /in_mem/=/in_mem/=/in_mem/=.\n    move/orP; case=> D; apply/orP.\n    left; case: (orP D)=> E; apply/orP; last by right.\n    by case: B=> _ []_ []F _; left; apply: (F _ E).\n    move: (andP D)=> []E F; right; apply/andP; split=> //.\n    by case: B=> _ []_ []_ []_ []_ []_ []<-. }\napply: join_sm_incr=> //.\nby rewrite 2!restrict_sm_local; apply: (disjoint_restrict _ A).\nhave C: forall b b' ofs,\n  extern_of mu1' b = Some (b',ofs) -> ~~[predD (vis mu12') & (vis mu12)] b.\n  { move=> b b' ofs; rewrite/mu12'/= => C; apply/negP; move/andP=> []E F.\n    cut (locBlocksSrc mu1' b = true).\n    by move/(locBlocksSrc_externNone _ (Inj_wd _)); rewrite C.\n    move: E F; rewrite/mu12/vis/in_mem/=; move/negP; rewrite/in_mem/=.\n    case: B=> _ []_ []_ []_ []_ []_ []<- []_ []_ _.\n    case: (locBlocksSrc mu1 b)=> //; case: (locBlocksSrc mu2 b)=> //.\n    by case: (locBlocksSrc mu1' b). }\nby apply: (intern_incr_restrict B).\nhave C: forall b b' ofs,\n  extern_of mu2 b = Some (b',ofs) -> ~~[predD (vis mu12') & (vis mu12)] b.\n  { move=> b b' ofs; rewrite/mu12'/= => C; apply/negP; move/andP=> []E F.\n    have G: DOM mu1 b=false /\\ DOM mu1' b.\n      have E': vis mu12 b = false.\n        by move: E; rewrite/in_mem/=; case: (vis mu12 b).\n      have F': vis mu12' b by apply: F.\n      by apply (join_sm_vis_dom B E' F').\n    rewrite/DOM in G; case: G=> G H; case: sep=> []_ [].\n    have G': DomSrc mu1 b=false.\n      move: G; case: (DomSrc mu1 b)=> //.\n    have H': (is_true false) <-> False by split.\n    by move=> I; elimtype False; rewrite -H' -I.\n    move/(_ b G' H).\n    case: val; rewrite/DOM/DomSrc; move/(_ b).\n    case: (extern_DomRng _ (Inj_wd mu2) _ _ _ C)=> -> _ I _ J _.\n    by apply: J; apply: I; apply/orP; right. }\nby apply: intern_incr_restrict.\nQed.\n\nLemma join_sm_inject_separated (mu1 mu1' mu2 : Inj.t) m1 m2 m1' m2' :\n  Consistent mu1 mu2 ->\n  intern_incr mu1 mu1' ->\n  sm_inject_separated mu1 mu1' m1 m2 ->\n  sm_locally_allocated mu1 mu1' m1 m2 m1' m2' ->\n  sm_valid mu1 m1 m2 ->\n  sm_valid mu2 m1 m2 ->\n  sm_inject_separated (join_sm mu1 mu2) (join_sm mu1' mu2) m1 m2.\nProof.\nmove=> consistent A []B []C D E val F.\nrewrite ->sm_locally_allocatedChar in E.\ncase: E=> E1 []E2 []E3 []E4 []E5 E6.\nsplit.\nmove=> b1 b2 d.\nrewrite/join_sm/DomSrc/DomTgt/as_inj/in_mem/=/in_mem/=.\nmove/joinP'=> []G. move/joinP'=> []H I.\nmove/joinP=> J.\nrewrite ->join2P' in G=> //.\ncase: J.\nmove/join2P=> []J K.\ncase: G=> L.\ncase: (B b1 b2 d).\nby rewrite/as_inj/join L H.\nby rewrite/as_inj/join J.\nmove=> M N.\nsplit.\nmove: M N; rewrite/DomSrc/DomTgt.\ncase: (locBlocksSrc mu1 b1)=> //.\ncase: (extBlocksSrc mu1 b1)=> //.\ncase: (locBlocksTgt mu1 b2)=> //=.\ncase: (extern_DomRng _ (Inj_wd _) _ _ _ K)=> _ M.\nhave ->: locBlocksSrc mu2 b1 = false.\n  case: (extern_DomRng _ (Inj_wd _) _ _ _ K).\n  by move/(extBlocksSrc_locBlocksSrc _ (Inj_wd _))=> ->.\nby [].\nmove: M N; rewrite/DomSrc/DomTgt.\ncase: (locBlocksSrc mu1 b1)=> //.\ncase: (extBlocksSrc mu1 b1)=> //.\ncase: (locBlocksTgt mu1 b2)=> //=.\ncase: (extBlocksTgt mu1 b2)=> //=.\ncase: (extern_DomRng _ (Inj_wd _) _ _ _ K)=> M N.\nhave ->: locBlocksTgt mu2 b2 = false.\n  case: (extern_DomRng _ (Inj_wd _) _ _ _ K)=> _.\n  by move/(extBlocksTgt_locBlocksTgt _ (Inj_wd _))=> ->.\nby [].\nrewrite K in L; congruence.\nmove=> []. move/join2P'=> J.\nmove/joinP=> K.\ncase: K. move=> K.\ncase: G=> G.\ncase: (B b1 b2 d).\nby rewrite/as_inj/join G H.\nrewrite/as_inj/join.\nhave ->: extern_of mu1' b1=None.\n  case X: (extern_of mu1' b1)=> // [[? ?]].\n  case: (extern_DomRng _ (Inj_wd _) _ _ _ X)=> Y _.\n  case: (local_DomRng _ (Inj_wd _) _ _ _ K)=> Z _.\n  by move: Y Z; move/(extBlocksSrc_locBlocksSrc _ (Inj_wd _))=> ->.\nby [].\nmove=> M N.\nsplit.\nmove: M N; rewrite/DomSrc/DomTgt.\ncase X: (locBlocksSrc mu1 b1)=> //.\ncase Y: (extBlocksSrc mu1 b1)=> //.\ncase: (locBlocksTgt mu1 b2)=> //.\ncase: (extBlocksTgt mu1 b2)=> //.\nsimpl.\nhave L: ~Memory.Mem.valid_block m1 b1.\n  apply: C.\n  by rewrite/DomSrc X Y.\n  case: (local_DomRng _ (Inj_wd _) _ _ _ K).\n  rewrite/DomSrc.\n  by move=> ->.\ncase M: (locBlocksSrc mu2 b1)=> //.\ncase: F; move/(_ b1)=> N.\nelimtype False.\napply: L; apply: N.\nby rewrite/DOM/DomSrc M.\nmove: M N; rewrite/DomSrc/DomTgt.\ncase: (locBlocksSrc mu1 b1)=> //.\ncase: (extBlocksSrc mu1 b1)=> //.\ncase X: (locBlocksTgt mu1 b2)=> //.\ncase Y: (extBlocksTgt mu1 b2)=> //.\nsimpl.\nhave L: ~Memory.Mem.valid_block m2 b2.\n  apply: D.\n  by rewrite/DomTgt X Y.\n  case: (local_DomRng _ (Inj_wd _) _ _ _ K).\n  rewrite/DomTgt.\n  by move=> _ ->.\ncase M: (locBlocksTgt mu2 b2)=> //.\ncase: F=> _; move/(_ b2)=> N.\nelimtype False.\napply: L; apply: N.\nby rewrite/RNG/DomTgt M.\ncase: (local_DomRng _ (Inj_wd _) _ _ _ K)=> M N.\nrewrite E3 in M.\nrewrite E4 in N.\nhave O: extern_of mu1 b1=None.\n  case X: (extern_of mu1 b1)=> // [[? ?]].\n  case: (extern_DomRng _ (Inj_wd _) _ _ _ X)=> O P.\n  case: val; move/(_ b1)=> Q.\n  move: M; case Y: (locBlocksSrc mu1 b1)=> //=.\n  rewrite extBlocksSrc_locBlocksSrc in Y=> //.\n  by apply: Inj_wd.\n  rewrite freshloc_charT=> [][]Z W _.\n  elimtype False.\n  apply: W.\n  apply: Q.\n  by rewrite/DOM/DomSrc O; apply/orP; right.\ncase: (B b1 b2 d).\nby rewrite/as_inj/join O H.\nrewrite/as_inj/join.\nhave ->: extern_of mu1' b1=None.\n  case P: (extern_of mu1' b1)=> // [[? ?]].\n  case: (extern_DomRng _ (Inj_wd _) _ _ _ P)=> Q R.\n  case: (local_DomRng _ (Inj_wd _) _ _ _ K)=> S T.\n  rewrite extBlocksSrc_locBlocksSrc in S=> //.\n  by apply: Inj_wd.\nby [].\nmove=> P Q.\nsplit.\nmove: P; rewrite/DomSrc.\ncase X: (locBlocksSrc mu1 b1)=> //.\ncase Y: (extBlocksSrc mu1 b1)=> //.\nsimpl.\ncase Z: (locBlocksSrc mu2 b1)=> //.\nhave L: ~Memory.Mem.valid_block m1 b1.\n  apply: C.\n  by rewrite/DomSrc X Y.\n  case: (local_DomRng _ (Inj_wd _) _ _ _ K).\n  rewrite/DomSrc.\n  by move=> ->.\ncase R: (locBlocksSrc mu2 b1)=> //.\ncase: F; move/(_ b1)=> S.\nelimtype False.\napply: L; apply: S.\nby rewrite/DOM/DomSrc Z.\nrewrite Z in R.\ncongruence.\nmove: Q; rewrite/DomTgt.\ncase X: (locBlocksTgt mu1 b2)=> //.\ncase Y: (extBlocksTgt mu1 b2)=> //.\nsimpl.\ncase Z: (locBlocksTgt mu2 b2)=> //.\nhave L: ~Memory.Mem.valid_block m2 b2.\n  apply: D.\n  by rewrite/DomTgt X Y.\n  case: (local_DomRng _ (Inj_wd _) _ _ _ K).\n  rewrite/DomTgt.\n  by move=> _ ->.\ncase R: (locBlocksTgt mu2 b2)=> //.\ncase: F=> _; move/(_ b2)=> S.\nelimtype False.\napply: L; apply: S.\nby rewrite/RNG/DomTgt Z.\nrewrite Z in R.\ncongruence.\nby rewrite I=> [][].\nsplit.\n{ move=> b1.\nrewrite/DomSrc/join_sm/=/in_mem/=.\nmove=> G H.\nhave G1: locBlocksSrc mu1 b1=false.\n  move: G.\n  by case: (locBlocksSrc mu1 b1).\nhave G2: locBlocksSrc mu2 b1=false.\n  move: G.\n  rewrite G1.\n  by case: (locBlocksSrc mu2 b1).\nhave G3: (extBlocksSrc mu1 b1 && extBlocksSrc mu2 b1)=false.\n  move: G.\n  case: (extBlocksSrc mu1 b1 && extBlocksSrc mu2 b1)=> //.\n  case/orP.\n  by right.\nhave H1: locBlocksSrc mu1' b1=true.\n  move: H.\n  rewrite G2.\n  rewrite E5.\n  rewrite G3=> /=.\n  by case: (locBlocksSrc mu1' b1).\nhave G4: extBlocksSrc mu1 b1=false.\n  rewrite -E5.\n  apply locBlocksSrc_extBlocksSrc in H1=> //.\n  by apply: Inj_wd.\napply: C.\nby rewrite/DomSrc G1 G4.\nby rewrite/DomSrc H1. }\n{ move=> b1.\nrewrite/DomTgt/join_sm/=/in_mem/=.\nmove=> G H.\nhave G1: locBlocksTgt mu1 b1=false.\n  move: G.\n  by case: (locBlocksTgt mu1 b1).\nhave G2: locBlocksTgt mu2 b1=false.\n  move: G.\n  rewrite G1.\n  by case: (locBlocksTgt mu2 b1).\nhave G3: (extBlocksTgt mu1 b1 && extBlocksTgt mu2 b1)=false.\n  move: G.\n  case: (extBlocksTgt mu1 b1 && extBlocksTgt mu2 b1)=> //.\n  case/orP.\n  by right.\nhave H1: locBlocksTgt mu1' b1=true.\n  move: H.\n  rewrite G2.\n  rewrite E6.\n  rewrite G3=> /=.\n  by case: (locBlocksTgt mu1' b1).\nhave G4: extBlocksTgt mu1 b1=false.\n  rewrite -E6.\n  apply locBlocksTgt_extBlocksTgt in H1=> //.\n  by apply: Inj_wd.\napply: D.\nby rewrite/DomTgt G1 G4.\nby rewrite/DomTgt H1. }\nQed.\n\nLemma join_all_sm_inject_separated\n    (mu_trash : Inj.t) (mu1 mu1' : Inj.t) (mus : seq Inj.t) m1 m2 m1' m2' :\n  All (fun mu0 => Consistent mu1 mu0) [seq Inj.mu x | x <- mus] ->\n  All (fun mu0 => sm_valid mu0 m1 m2) [seq Inj.mu x | x <- mus] ->\n  SM_wd (join_all mu_trash $ mus) ->\n  Consistent mu1 mu_trash ->\n  intern_incr mu1 mu1' ->\n  sm_inject_separated mu1 mu1' m1 m2 ->\n  sm_locally_allocated mu1 mu1' m1 m2 m1' m2' ->\n  sm_valid mu1 m1 m2 ->\n  sm_valid mu_trash m1 m2 ->\n  sm_inject_separated\n    (join_all mu_trash $ mu1 :: mus) (join_all mu_trash $ mu1' :: mus) m1 m2.\nProof.\nelim: mus; first by move=> _ _ _; apply: join_sm_inject_separated.\nmove=> mu0 mus' IH cons1 /=.\nmove=> []val1 allval wd cons2 incr sep localloc val2 valtr.\nhave B': All [eta Consistent mu1] [seq Inj.mu x | x <- mu_trash :: mus'].\n  by move=> /=; split=> //; move: cons1=> /= [].\nmove: (join_all_consistent B')=> G.\nchange (sm_inject_separated (join_sm mu1 (Inj.mk wd))\n                            (join_sm mu1' (Inj.mk wd)) m1 m2).\napply join_sm_inject_separated with (m1':=m1') (m2':=m2')=> //.\nmove: cons1=> /= []H I.\nhave J: Consistent mu1 (join_all mu_trash mus').\n  by apply: join_all_consistent.\nby apply: (join_sm_consistent' H J).\napply: join_sm_valid=> //; apply: join_all_valid=> //; move: allval.\nby rewrite -All_comp.\nQed.\n\nLemma join_sm_DomSrc mu1 mu2 :\n  DomSrc (join_sm mu1 mu2)\n  = (fun b => locBlocksSrc mu1 b || locBlocksSrc mu2 b\n           || extBlocksSrc mu1 b && extBlocksSrc mu2 b).\nProof. by []. Qed.\n\nLemma join_sm_DomTgt mu1 mu2 :\n  DomTgt (join_sm mu1 mu2)\n  = (fun b => locBlocksTgt mu1 b || locBlocksTgt mu2 b\n           || extBlocksTgt mu1 b && extBlocksTgt mu2 b).\nProof. by []. Qed.\n\nLemma join_sm_locBlocksSrc mu1 mu2 :\n  locBlocksSrc (join_sm mu1 mu2)\n  = (fun b => locBlocksSrc mu1 b || locBlocksSrc mu2 b).\nProof. by []. Qed.\n\nLemma join_sm_locBlocksTgt mu1 mu2 :\n  locBlocksTgt (join_sm mu1 mu2)\n  = (fun b => locBlocksTgt mu1 b || locBlocksTgt mu2 b).\nProof. by []. Qed.\n\nLemma join_sm_extBlocksSrc mu1 mu2 :\n  extBlocksSrc (join_sm mu1 mu2)\n  = (fun b => extBlocksSrc mu1 b && extBlocksSrc mu2 b).\nProof. by []. Qed.\n\nLemma join_sm_extBlocksTgt mu1 mu2 :\n  extBlocksTgt (join_sm mu1 mu2)\n  = (fun b => extBlocksTgt mu1 b && extBlocksTgt mu2 b).\nProof. by []. Qed.\n\nLemma join_sm_locally_allocated mu1 mu1' mu2 m1 m2 m1' m2' :\n  sm_locally_allocated mu1 mu1' m1 m2 m1' m2' ->\n  sm_locally_allocated (join_sm mu1 mu2) (join_sm mu1' mu2) m1 m2 m1' m2'.\nProof.\nrewrite 2!sm_locally_allocatedChar.\nmove=> []A []B []C []D []E F.\nrewrite !join_sm_DomSrc !join_sm_DomTgt.\nrewrite !join_sm_locBlocksSrc !join_sm_locBlocksTgt.\nrewrite !join_sm_extBlocksSrc !join_sm_extBlocksTgt.\nsplit.\nextensionality b; rewrite C E -(orb_comm (freshloc _ _ _)) -!orb_assoc.\nby rewrite (orb_comm (freshloc _ _ _)) !orb_assoc.\nsplit.\nextensionality b; rewrite D F -(orb_comm (freshloc _ _ _)) -!orb_assoc.\nby rewrite (orb_comm (freshloc _ _ _)) !orb_assoc.\nsplit.\nby extensionality b; rewrite C -orb_assoc (orb_comm (freshloc _ _ _)) orb_assoc.\nsplit.\nextensionality b; rewrite D.\nby rewrite -orb_assoc (orb_comm (freshloc _ _ _)) orb_assoc.\nsplit; extensionality b; first by rewrite E.\nby rewrite F.\nQed.\n\nLemma join_all_locally_allocated mu_trash (mu mu' : Inj.t) mus m1 m2 m1' m2' :\n  sm_locally_allocated mu mu' m1 m2 m1' m2' ->\n  sm_locally_allocated\n    (join_all mu_trash (mu :: mus))\n    (join_all mu_trash (mu' :: mus)) m1 m2 m1' m2'.\nProof.\nelim: mus; first by rewrite !join_all_cons; apply: join_sm_locally_allocated.\nmove=> mu0 mus' IH A; rewrite 2!join_all_cons.\nby apply: join_sm_locally_allocated.\nQed.\n\nLemma All_disjoint (mu_trash : Inj.t) (mu : Inj.t) mus :\n  disjoint (local_of mu) (local_of mu_trash) ->\n  All (fun mu2 : Inj.t => disjoint (local_of mu) (local_of mu2)) mus ->\n  disjoint (local_of mu) (local_of (join_all mu_trash mus)).\nProof.\nelim: mus=> // mu0 mus' IH A /= []B C.\nrewrite disjoint_com; apply: join_disjoint; first by rewrite disjoint_com.\nby rewrite disjoint_com; apply: IH.\nQed.\n\nLemma DisjointLS_disjoint (mu mu' : Inj.t) :\n  DisjointLS mu mu' -> disjoint (local_of mu) (local_of mu').\nProof.\nmove=> A b.\ncase B: (local_of mu b)=> [[? ?]|].\ncase: (local_DomRng _ (Inj_wd _) _ _ _ B)=> C _.\ncase E: (local_of mu' b)=> [[? ?]|].\ncase: (local_DomRng _ (Inj_wd _) _ _ _ E)=> D _.\nby move: D; move: (DisjointLS_E1 A C)=> ->.\nby right.\nby left.\nQed.\n\nLemma join_all_restrict_incr (mu_trash mu mu' : Inj.t) (mus : seq Inj.t) m1 m2 :\n  All (fun mu2 : Inj.t => disjoint (local_of mu') (local_of mu2)) mus ->\n  All (DisjointLS mu_trash) $ map Inj.mu mus ->\n  All (DisjointLT mu_trash) $ map Inj.mu mus ->\n  All (fun mu2 => Consistent mu_trash mu2) $ map Inj.mu mus ->\n  disjoint (local_of mu') (local_of mu_trash) ->\n  AllDisjoint locBlocksSrc \\o map Inj.mu $ mus ->\n  AllDisjoint locBlocksTgt \\o map Inj.mu $ mus ->\n  AllConsistent \\o map Inj.mu $ mus ->\n  All (fun mu2 => sm_valid (Inj.mu mu2) m1 m2) mus ->\n  intern_incr mu mu' ->\n  sm_inject_separated mu mu' m1 m2 ->\n  sm_valid (Inj.mu mu_trash) m1 m2 ->\n  let mu_tot  := join_all mu_trash (mu :: mus) in\n  let mu_tot' := join_all mu_trash (mu' :: mus) in\n  intern_incr (restrict_sm mu_tot (vis mu_tot)) (restrict_sm mu_tot' (vis mu_tot')).\nProof.\nmove=> A disj_S disj_T consist disj_trash allS allT allC B C D E top top'.\nrewrite/top/top' 2!join_all_cons.\nhave G: SM_wd (join_all mu_trash mus) by apply: join_all_wd.\nhave H: sm_valid (Inj.mk G) m1 m2 by apply: join_all_valid.\nhave I: disjoint (local_of mu') (local_of (Inj.mk G)).\n  by apply: All_disjoint.\nby apply: (join_sm_restrict_incr I C D H).\nQed.\n\nLemma join_all_restrict_sep\n    (mu_trash : Inj.t) (mu1 mu1' : Inj.t) (mus : seq Inj.t) m1 m2 m1' m2' :\n  All (fun mu0 => Consistent mu1 mu0) [seq Inj.mu x | x <- mus] ->\n  All (fun mu0 => sm_valid mu0 m1 m2) [seq Inj.mu x | x <- mus] ->\n  Consistent mu1 mu_trash ->\n  sm_valid mu_trash m1 m2 ->\n  sm_valid mu1 m1 m2 ->\n  intern_incr mu1 mu1' ->\n  sm_inject_separated mu1 mu1' m1 m2 ->\n  sm_locally_allocated mu1 mu1' m1 m2 m1' m2' ->\n  let mu_tot  := join_all mu_trash (mu1 :: mus) in\n  let mu_tot' := join_all mu_trash (mu1' :: mus) in\n  sm_valid mu_tot m1 m2 ->\n  SM_wd (join_all mu_trash mus) ->\n  SM_wd mu_tot ->\n  sm_inject_separated\n    (restrict_sm mu_tot (vis mu_tot))\n    (restrict_sm mu_tot' (vis mu_tot')) m1 m2.\nProof.\nmove=> A B C D val incr E loc_alloc mu_tot mu_tot' F tot'_wd tot_wd.\nhave Cut: sm_inject_separated mu_tot mu_tot' m1 m2.\n  by eapply (join_all_sm_inject_separated (m1':=m1')); eauto.\nset mu_tot2 := Inj.mk tot_wd.\nchange (sm_inject_separated\n         (restrict_sm mu_tot2 (vis mu_tot2))\n         (restrict_sm mu_tot' (vis mu_tot')) m1 m2).\n  apply: sm_sep_restrict2=> //.\nmove=> b Y Z.\nhave [G H]: [/\\ locBlocksSrc mu1 b=false & locBlocksSrc mu1' b=true].\n  by apply (join_sm_vis_loc incr Y Z).\napply sm_locally_allocatedChar in loc_alloc.\ncase loc_alloc=> A1 []A2 []A3 []A4 []A5 A6.\nrewrite A3 G /= in H.\nrewrite ->freshloc_charT in H.\nby case: H.\nQed.\n\nLemma join_absorb f g : join f (join f g) = join f g.\nProof.\nby rewrite /join; extensionality a; case: (f a).\nQed.\n\nLemma join_absorb' f' f g :\n  inject_incr f' f ->\n  join f' (join f g) = join f g.\nProof.\nmove=> A; rewrite /join; extensionality a.\nby case e: (f' a)=> // [[b ofs]]; rewrite (A _ _ _ e).\nQed.\n\nLemma join_sm_absorb mu1 mu2 :\n  join_sm mu1 (join_sm mu1 mu2) = join_sm mu1 mu2.\nProof.\ncase: mu1=> ? ? ? ? ? ? ? ? ? ?; rewrite /join_sm /join2 /=; f_equal.\nby rewrite predU_absorb.\nby rewrite predU_absorb.\nby rewrite join_absorb.\nby rewrite predI_absorb.\nby rewrite predI_absorb.\nby rewrite predI_absorb.\nby rewrite predI_absorb.\nextensionality a.\ncase: (_ a)=> //.\nmove=> [b ofs].\ncase: (extern_of _ _)=> //.\nmove=> [b' ofs'].\ncase: (_ && _)=> //.\nby rewrite Pos.eqb_refl Zeq_bool_refl.\nQed.\n\nLemma join_sm_absorb' mu0 mu1 mu2 :\n  inject_incr (local_of mu0) (local_of mu1) ->\n  inject_incr (extern_of mu1) (extern_of mu0) ->\n  {subset (locBlocksSrc mu0) <= locBlocksSrc mu1} ->\n  {subset (locBlocksTgt mu0) <= locBlocksTgt mu1} ->\n  {subset (extBlocksSrc mu1) <= extBlocksSrc mu0} ->\n  {subset (extBlocksTgt mu1) <= extBlocksTgt mu0} ->\n  {subset (frgnBlocksSrc mu1) <= frgnBlocksSrc mu0} ->\n  {subset (frgnBlocksTgt mu1) <= frgnBlocksTgt mu0} ->\n  join_sm mu0 (join_sm mu1 mu2) = join_sm mu1 mu2.\nProof.\ncase: mu0=> ? ? ? ? ? ex0s ex0t fr0s fr0t ef0.\ncase: mu1=> ? ? ? ? ? ex1s ex1t fr1s fr1t ef1; rewrite /join_sm /join2 /=.\nmove=> A B C D E F G H; f_equal.\nby rewrite predU_absorb'.\nby rewrite predU_absorb'.\nby rewrite join_absorb'.\nby rewrite -predI_absorb_sub.\nby rewrite -predI_absorb_sub.\nby rewrite -predI_absorb_sub.\nby rewrite -predI_absorb_sub.\nextensionality a.\ncase e0: (ef0 a)=> // [[b ofs]|].\ncase e1: (ef1 a)=> // [[b' ofs']].\ncase e2: (extern_of _ _)=> // [[b'' ofs'']].\ncase f: (_ && _)=> //.\ncase: (andP f).\nmove/Peqb_true_eq=> ->.\nmove/Zeq_bool_eq=> ->.\ncase g: (_ && _)=> //.\ncase: (andP g).\nmove/Peqb_true_eq=> ->.\nby move/Zeq_bool_eq=> ->.\nmove: (B _ _ _ e1); rewrite e0; case.\ncase: (andP f).\nmove/Peqb_true_eq=> ->.\nmove/Zeq_bool_eq=> ->.\nmove=> eq1 eq2.\nrewrite eq1 eq2 Pos.eqb_refl Zeq_bool_refl /= in g.\ncongruence.\ncase e1: (ef1 a)=> // [[b ofs]].\nmove: (B _ _ _ e1); rewrite e0; congruence.\nQed.\n\nLemma join_all_absorb' mu_trash (mu0 mu1 : Inj.t) (mus : seq Inj.t) :\n  inject_incr (local_of mu0) (local_of mu1) ->\n  inject_incr (extern_of mu1) (extern_of mu0) ->\n  {subset (locBlocksSrc mu0) <= locBlocksSrc mu1} ->\n  {subset (locBlocksTgt mu0) <= locBlocksTgt mu1} ->\n  {subset (extBlocksSrc mu1) <= extBlocksSrc mu0} ->\n  {subset (extBlocksTgt mu1) <= extBlocksTgt mu0} ->\n  {subset (frgnBlocksSrc mu1) <= frgnBlocksSrc mu0} ->\n  {subset (frgnBlocksTgt mu1) <= frgnBlocksTgt mu0} ->\n  join_all mu_trash [:: mu0, mu1 & mus] = join_all mu_trash [:: mu1 & mus].\nProof.\nby move=> A B C D E F G H /=; rewrite join_sm_absorb'.\nQed.\n\nLemma join_all_locBlocksSrc mu mus b :\n  locBlocksSrc (join_all mu mus) b\n  <-> locBlocksSrc mu b\n      \\/ (exists mu0, List.In mu0 mus /\\ locBlocksSrc mu0 b).\nProof.\nelim: mus mu=> //=; split=> H1; first by left.\nby case: H1=> //; move=> []? [].\ncase: (orP H1); rewrite /in_mem /= => H2.\nby right; exists a; split; first by left.\nmove: H2; rewrite H; case; first by left.\nby case=> x []H2 H3; right; exists x; split=> //; right.\ncase: H1=> [H1|[x [H2 H3]]]; apply/orP; rewrite /in_mem /=.\nby rewrite H; right; left.\ncase: H2; first by move=> ->; left.\nby move=> H4; right; rewrite H; right; exists x; split.\nQed.\n\nLemma join_all_locBlocksTgt mu mus b :\n  locBlocksTgt (join_all mu mus) b\n  <-> locBlocksTgt mu b\n      \\/ (exists mu0, List.In mu0 mus /\\ locBlocksTgt mu0 b).\nProof.\nelim: mus mu=> //=; split=> H1; first by left.\nby case: H1=> //; move=> []? [].\ncase: (orP H1); rewrite /in_mem /= => H2.\nby right; exists a; split; first by left.\nmove: H2; rewrite H; case; first by left.\nby case=> x []H2 H3; right; exists x; split=> //; right.\ncase: H1=> [H1|[x [H2 H3]]]; apply/orP; rewrite /in_mem /=.\nby rewrite H; right; left.\ncase: H2; first by move=> ->; left.\nby move=> H4; right; rewrite H; right; exists x; split.\nQed.\n\nLemma join_all_extBlocksSrc mu mus b :\n  extBlocksSrc (join_all mu mus) b\n  <-> extBlocksSrc mu b\n      /\\ (forall mu0, List.In mu0 mus -> extBlocksSrc mu0 b).\nProof.\nelim: mus mu=> //=; split=> H1; first by split.\nby case: H1=> //; move=> []? [].\ncase: (andP H1); rewrite /in_mem /= => H2; rewrite H; case=> H3 H4.\nsplit=> //; move=> mu0; case; first by move=> <-.\nby move=> H5; apply: (H4 _ H5).\ncase: H1=> H1 H2.\napply/andP; rewrite /in_mem /=; split.\nby apply: H2; left.\nby rewrite H; split=> //; move=> mu0 H3; apply: H2; right.\nQed.\n\nLemma join_all_frgnBlocksSrc mu mus b :\n  frgnBlocksSrc (join_all mu mus) b\n  <-> frgnBlocksSrc mu b\n      /\\ (forall mu0, List.In mu0 mus -> frgnBlocksSrc mu0 b).\nProof.\nelim: mus mu=> //=; split=> H1; first by split.\nby case: H1=> //; move=> []? [].\ncase: (andP H1); rewrite /in_mem /= => H2; rewrite H; case=> H3 H4.\nsplit=> //; move=> mu0; case; first by move=> <-.\nby move=> H5; apply: (H4 _ H5).\ncase: H1=> H1 H2.\napply/andP; rewrite /in_mem /=; split.\nby apply: H2; left.\nby rewrite H; split=> //; move=> mu0 H3; apply: H2; right.\nQed.\n\nLemma join_all_extBlocksTgt mu mus b :\n  extBlocksTgt (join_all mu mus) b\n  <-> extBlocksTgt mu b\n      /\\ (forall mu0, List.In mu0 mus -> extBlocksTgt mu0 b).\nProof.\nelim: mus mu=> //=; split=> H1; first by split.\nby case: H1=> //; move=> []? [].\ncase: (andP H1); rewrite /in_mem /= => H2; rewrite H; case=> H3 H4.\nsplit=> //; move=> mu0; case; first by move=> <-.\nby move=> H5; apply: (H4 _ H5).\ncase: H1=> H1 H2.\napply/andP; rewrite /in_mem /=; split.\nby apply: H2; left.\nby rewrite H; split=> //; move=> mu0 H3; apply: H2; right.\nQed.\n\nLemma join_all_frgnBlocksTgt mu mus b :\n  frgnBlocksTgt (join_all mu mus) b\n  <-> frgnBlocksTgt mu b\n      /\\ (forall mu0, List.In mu0 mus -> frgnBlocksTgt mu0 b).\nProof.\nelim: mus mu=> //=; split=> H1; first by split.\nby case: H1=> //; move=> []? [].\ncase: (andP H1); rewrite /in_mem /= => H2; rewrite H; case=> H3 H4.\nsplit=> //; move=> mu0; case; first by move=> <-.\nby move=> H5; apply: (H4 _ H5).\ncase: H1=> H1 H2.\napply/andP; rewrite /in_mem /=; split.\nby apply: H2; left.\nby rewrite H; split=> //; move=> mu0 H3; apply: H2; right.\nQed.\n\nLemma join_all_local_of (mu mu0 : Inj.t) mus :\n  AllDisjoint locBlocksSrc [seq Inj.mu x | x <- [:: mu, mu0 & mus]] ->\n  local_of (join_all mu [:: mu0 & mus])\n  = join (local_of mu) (local_of (join_all mu0 mus)).\nProof.\nelim: mus mu0 mu=> //=.\nmove=> mu0 mu /= D; rewrite join_com=> //.\nmove: D=> /=; case=> /=; case.\nby move/DisjointLS_disjoint; rewrite disjoint_com.\nmove=> a mus' IH mu0 mu /= D.\nsymmetry.\nrewrite join_assoc.\nrewrite (join_com (local_of mu)).\nrewrite -join_assoc.\nrewrite -(IH mu0 mu).\nrewrite join_assoc.\nrewrite (join_com (local_of a)).\nby rewrite -join_assoc.\ncase: D=> /= [][]_ []_ H [][]; move/DisjointLS_disjoint.\nby rewrite disjoint_com.\ncase: D=> /= [][]H1 []H2 H3 [][]H4 H5 []H6 H7.\nby split=> //.\ncase: D=> /= [][]H1 []H2 H3 [][]H4 H5 []H6 H7.\nby apply: (DisjointLS_disjoint H2).\nQed.\n\nLemma DisjointLS_local_of_contra (mu mu' : Inj.t) b b' d' b'' d'' :\n  local_of mu b = Some (b',d') ->\n  local_of mu' b = Some (b'',d'') ->\n  DisjointLS mu mu' ->\n  False.\nProof.\nby move=> L1 L2; move/DisjointLS_disjoint; move/(_ b); rewrite L1 L2; case.\nQed.\n\nSection join_all_shift.\n\nVariables mu0 mu1 mu_trash : Inj.t.\n\nVariable mus : seq Inj.t.\n\nLet mu_trash'' := join_sm mu0 mu_trash.\n\nVariable mu_trash''_wd : SM_wd mu_trash''.\n\nLet mu_trash' := Inj.mk mu_trash''_wd.\n\nLemma join_all_shift_locBlocksSrcE :\n  locBlocksSrc (join_all mu_trash' mus)\n  = [predU (locBlocksSrc mu0)\n    & locBlocksSrc (join_all mu_trash mus)].\nProof.\nrewrite /= /predU; f_equal; extensionality b; rewrite /in_mem /= /in_mem /=.\ncase lOf0: (locBlocksSrc mu0)=> /=.\nhave H: locBlocksSrc (join_all mu_trash' mus) b.\n{ rewrite join_all_locBlocksSrc; left; rewrite /mu_trash' /=.\n  by apply/orP; rewrite /in_mem /=; left. }\nby [].\nhave H:\n      is_true (locBlocksSrc (join_all mu_trash mus) b)\n  <-> is_true (locBlocksSrc (join_all mu_trash' mus) b).\n{ by rewrite 2!join_all_locBlocksSrc /mu_trash' /= /in_mem /= lOf0. }\nhave H2:\n    locBlocksSrc (join_all mu_trash mus) b\n  = locBlocksSrc (join_all mu_trash' mus) b.\n{ move: H; case: (locBlocksSrc (join_all mu_trash mus) b).\n  by case=> H1 H2; rewrite H1.\n  case: (locBlocksSrc (join_all mu_trash' mus) b)=> //.\n  by case=> //_; move/(_ erefl). }\nby rewrite H2.\nQed.\n\nLemma join_all_shift_locBlocksSrc :\n    [predU (locBlocksSrc mu0)\n    & locBlocksSrc (join_all mu_trash [:: mu1 & mus])]\n  = [predU (locBlocksSrc mu1)\n    & locBlocksSrc (join_all mu_trash' mus)].\nProof.\nrewrite join_all_shift_locBlocksSrcE /=.\nby rewrite predUA predUC -predUA.\nQed.\n\nLemma join_all_shift_locBlocksTgtE :\n  locBlocksTgt (join_all mu_trash' mus)\n  = [predU (locBlocksTgt mu0)\n    & locBlocksTgt (join_all mu_trash mus)].\nProof.\nrewrite /= /predU; f_equal; extensionality b; rewrite /in_mem /= /in_mem /=.\ncase lOf0: (locBlocksTgt mu0)=> /=.\nhave H: locBlocksTgt (join_all mu_trash' mus) b.\n{ rewrite join_all_locBlocksTgt; left; rewrite /mu_trash' /=.\n  by apply/orP; rewrite /in_mem /=; left. }\nby [].\nhave H:\n      is_true (locBlocksTgt (join_all mu_trash mus) b)\n  <-> is_true (locBlocksTgt (join_all mu_trash' mus) b).\n{ by rewrite 2!join_all_locBlocksTgt /mu_trash' /= /in_mem /= lOf0. }\nhave H2:\n    locBlocksTgt (join_all mu_trash mus) b\n  = locBlocksTgt (join_all mu_trash' mus) b.\n{ move: H; case: (locBlocksTgt (join_all mu_trash mus) b).\n  by case=> H1 H2; rewrite H1.\n  case: (locBlocksTgt (join_all mu_trash' mus) b)=> //.\n  by case=> //_; move/(_ erefl). }\nby rewrite H2.\nQed.\n\nLemma join_all_shift_locBlocksTgt :\n    [predU (locBlocksTgt mu0)\n    & locBlocksTgt (join_all mu_trash [:: mu1 & mus])]\n  = [predU (locBlocksTgt mu1)\n    & locBlocksTgt (join_all mu_trash' mus)].\nProof.\nrewrite join_all_shift_locBlocksTgtE /=.\nby rewrite predUA predUC -predUA.\nQed.\n\nLemma join_all_shift_extBlocksSrcE :\n  extBlocksSrc (join_all mu_trash' mus)\n  = [predI (extBlocksSrc mu0)\n    & extBlocksSrc (join_all mu_trash mus)].\nProof.\nrewrite /= /predI; f_equal; extensionality b; rewrite /in_mem /= /in_mem /=.\ncase eOf0: (extBlocksSrc mu0)=> /=.\ncut (extBlocksSrc (join_all mu_trash mus) b\n <-> extBlocksSrc (join_all mu_trash' mus) b).\ncase: (extBlocksSrc mu1 b)=> //.\ncase: (extBlocksSrc _ _)=> //.\ncase: (extBlocksSrc _ _)=> //.\ncase. by move/(_ erefl). case.\ncase: (extBlocksSrc _ _)=> //.\ncase: (extBlocksSrc _ _)=> //.\nby move=> _; move/(_ erefl).\nby move=> _; move/(_ erefl).\ncase.\ncase: (extBlocksSrc _ _)=> //.\ncase: (extBlocksSrc _ _)=> //.\nby move/(_ erefl).\ncase: (extBlocksSrc _ _)=> //.\ncase: (extBlocksSrc _ _)=> //.\nby move=> _; move/(_ erefl).\nby move=> _; move/(_ erefl).\nrewrite 2!join_all_extBlocksSrc.\nhave H: (extBlocksSrc mu_trash b = extBlocksSrc mu_trash' b).\n{ by rewrite /mu_trash' /= /in_mem /= eOf0. }\nby rewrite -H.\ncut (false\n <-> extBlocksSrc (join_all mu_trash' mus) b).\ncase: (extBlocksSrc _ _)=> //.\nby case=> _; move/(_ erefl).\nrewrite join_all_extBlocksSrc /mu_trash' /= /in_mem /= eOf0 /=.\nby split=> //; last by case.\nQed.\n\nLemma join_all_shift_extBlocksSrc :\n    [predI (extBlocksSrc mu0)\n    & extBlocksSrc (join_all mu_trash [:: mu1 & mus])]\n  = [predI (extBlocksSrc mu1)\n    & extBlocksSrc (join_all mu_trash' mus)].\nProof.\nrewrite join_all_shift_extBlocksSrcE /=.\nby rewrite predIA predIC -predIA.\nQed.\n\nLemma join_all_shift_frgnBlocksSrcE :\n  frgnBlocksSrc (join_all mu_trash' mus)\n  = [predI (frgnBlocksSrc mu0)\n    & frgnBlocksSrc (join_all mu_trash mus)].\nProof.\nrewrite /= /predI; f_equal; extensionality b; rewrite /in_mem /= /in_mem /=.\ncase eOf0: (frgnBlocksSrc mu0)=> /=.\ncut (frgnBlocksSrc (join_all mu_trash mus) b\n <-> frgnBlocksSrc (join_all mu_trash' mus) b).\ncase: (frgnBlocksSrc mu1 b)=> //.\ncase: (frgnBlocksSrc _ _)=> //.\ncase: (frgnBlocksSrc _ _)=> //.\ncase. by move/(_ erefl). case.\ncase: (frgnBlocksSrc _ _)=> //.\ncase: (frgnBlocksSrc _ _)=> //.\nby move=> _; move/(_ erefl).\nby move=> _; move/(_ erefl).\ncase.\ncase: (frgnBlocksSrc _ _)=> //.\ncase: (frgnBlocksSrc _ _)=> //.\nby move/(_ erefl).\ncase: (frgnBlocksSrc _ _)=> //.\ncase: (frgnBlocksSrc _ _)=> //.\nby move=> _; move/(_ erefl).\nby move=> _; move/(_ erefl).\nrewrite 2!join_all_frgnBlocksSrc.\nhave H: (frgnBlocksSrc mu_trash b = frgnBlocksSrc mu_trash' b).\n{ by rewrite /mu_trash' /= /in_mem /= eOf0. }\nby rewrite -H.\ncut (false\n <-> frgnBlocksSrc (join_all mu_trash' mus) b).\ncase: (frgnBlocksSrc _ _)=> //.\nby case=> _; move/(_ erefl).\nrewrite join_all_frgnBlocksSrc /mu_trash' /= /in_mem /= eOf0 /=.\nby split=> //; last by case.\nQed.\n\nLemma join_all_shift_extBlocksTgtE :\n  extBlocksTgt (join_all mu_trash' mus)\n  = [predI (extBlocksTgt mu0)\n    & extBlocksTgt (join_all mu_trash mus)].\nProof.\nrewrite /= /predI; f_equal; extensionality b; rewrite /in_mem /= /in_mem /=.\ncase eOf0: (extBlocksTgt mu0)=> /=.\ncut (extBlocksTgt (join_all mu_trash mus) b\n <-> extBlocksTgt (join_all mu_trash' mus) b).\ncase: (extBlocksTgt mu1 b)=> //.\ncase: (extBlocksTgt _ _)=> //.\ncase: (extBlocksTgt _ _)=> //.\ncase. by move/(_ erefl). case.\ncase: (extBlocksTgt _ _)=> //.\ncase: (extBlocksTgt _ _)=> //.\nby move=> _; move/(_ erefl).\nby move=> _; move/(_ erefl).\ncase.\ncase: (extBlocksTgt _ _)=> //.\ncase: (extBlocksTgt _ _)=> //.\nby move/(_ erefl).\ncase: (extBlocksTgt _ _)=> //.\ncase: (extBlocksTgt _ _)=> //.\nby move=> _; move/(_ erefl).\nby move=> _; move/(_ erefl).\nrewrite 2!join_all_extBlocksTgt.\nhave H: (extBlocksTgt mu_trash b = extBlocksTgt mu_trash' b).\n{ by rewrite /mu_trash' /= /in_mem /= eOf0. }\nby rewrite -H.\ncut (false\n <-> extBlocksTgt (join_all mu_trash' mus) b).\ncase: (extBlocksTgt _ _)=> //.\nby case=> _; move/(_ erefl).\nrewrite join_all_extBlocksTgt /mu_trash' /= /in_mem /= eOf0 /=.\nby split=> //; last by case.\nQed.\n\nLemma join_all_shift_extBlocksTgt :\n    [predI (extBlocksTgt mu0)\n    & extBlocksTgt (join_all mu_trash [:: mu1 & mus])]\n  = [predI (extBlocksTgt mu1)\n    & extBlocksTgt (join_all mu_trash' mus)].\nProof.\nrewrite join_all_shift_extBlocksTgtE /=.\nby rewrite predIA predIC -predIA.\nQed.\n\nLemma join_all_shift_frgnBlocksTgtE :\n  frgnBlocksTgt (join_all mu_trash' mus)\n  = [predI (frgnBlocksTgt mu0)\n    & frgnBlocksTgt (join_all mu_trash mus)].\nProof.\nrewrite /= /predI; f_equal; extensionality b; rewrite /in_mem /= /in_mem /=.\ncase eOf0: (frgnBlocksTgt mu0)=> /=.\ncut (frgnBlocksTgt (join_all mu_trash mus) b\n <-> frgnBlocksTgt (join_all mu_trash' mus) b).\ncase: (frgnBlocksTgt mu1 b)=> //.\ncase: (frgnBlocksTgt _ _)=> //.\ncase: (frgnBlocksTgt _ _)=> //.\ncase. by move/(_ erefl). case.\ncase: (frgnBlocksTgt _ _)=> //.\ncase: (frgnBlocksTgt _ _)=> //.\nby move=> _; move/(_ erefl).\nby move=> _; move/(_ erefl).\ncase.\ncase: (frgnBlocksTgt _ _)=> //.\ncase: (frgnBlocksTgt _ _)=> //.\nby move/(_ erefl).\ncase: (frgnBlocksTgt _ _)=> //.\ncase: (frgnBlocksTgt _ _)=> //.\nby move=> _; move/(_ erefl).\nby move=> _; move/(_ erefl).\nrewrite 2!join_all_frgnBlocksTgt.\nhave H: (frgnBlocksTgt mu_trash b = frgnBlocksTgt mu_trash' b).\n{ by rewrite /mu_trash' /= /in_mem /= eOf0. }\nby rewrite -H.\ncut (false\n <-> frgnBlocksTgt (join_all mu_trash' mus) b).\ncase: (frgnBlocksTgt _ _)=> //.\nby case=> _; move/(_ erefl).\nrewrite join_all_frgnBlocksTgt /mu_trash' /= /in_mem /= eOf0 /=.\nby split=> //; last by case.\nQed.\n\nLemma join_all_shift_local_ofE :\n  All (fun mu1 => DisjointLS mu0 mu1) [seq Inj.mu x | x <- mus] ->\n  local_of (join_all mu_trash' mus)\n  = join (local_of mu0) (local_of (join_all mu_trash mus)).\nProof.\nmove=> D; elim: mus D=> // a mus' IH /= []D E.\nrewrite IH // join_assoc (join_com (local_of a)).\nby rewrite -join_assoc.\nby rewrite disjoint_com; apply: DisjointLS_disjoint D.\nQed.\n\nLemma join_all_shift_local_of :\n  AllDisjoint locBlocksSrc [seq Inj.mu x | x <- [:: mu_trash, mu0, mu1 & mus]] ->\n    join (local_of mu0) (local_of (join_all mu_trash [:: mu1 & mus]))\n  = join (local_of mu1) (local_of (join_all mu_trash' mus)).\nProof.\nmove=> D; rewrite /join join_all_local_of=> //.\nextensionality b.\ncase lOf0: (local_of mu0 b)=> [[x y]|].\ncase lOf1: (local_of mu1 b)=> [[x' y']|].\nelimtype False; apply: (DisjointLS_local_of_contra lOf0 lOf1).\nby case: D=> /= [][]H1 []H2 H3 [][]H4 H5 []H6 H7.\nelim: mus D=> //=.\nby rewrite /join lOf0.\nmove=> a mus' IH D; rewrite /join.\ncase lOfa: (local_of a b)=> [[x' y']|].\nelimtype False; apply: (DisjointLS_local_of_contra lOf0 lOfa).\nby case: D=> /= [][]H1 []H2 H3 [][]H4 []H5.\napply: IH.\ncase: D=> /= [][]H1 []H2 []H3 H4 [][]H5 []H6 H7 [][]H8 H9 []H10 H11.\nby split.\nrewrite /join.\ncase lOf1: (local_of mu1 b)=> [[x y]|].\ncase lOftr: (local_of mu_trash b)=> [[x' y']|].\nelimtype False; apply: (DisjointLS_local_of_contra lOf1 lOftr).\nby case: D=> /= [][]H1 []H2 H3 [][]H4 H5 []H6 H7; rewrite DisjointC.\nelim: mus D=> //a mus' IH D /=; rewrite /join.\ncase lOfa: (local_of a b)=> [[x' y']|].\nelimtype False; apply: (DisjointLS_local_of_contra lOf1 lOfa).\nby case: D=> /= [][]H1 []H2 []H3 H4 [][]H5 []H6 H7 [][]H8 H9 []H10 H11.\napply: IH.\nby case: D=> /= [][]H1 []H2 []H3 H4 [][]H5 []H6 H7 [][]H8 H9 []H10 H11.\ncase lOftr: (local_of mu_trash b)=> [[x y]|].\nelim: mus D; first by move=> D /=; rewrite /join lOf0 lOftr.\nmove=> a mus' IH D /=; rewrite /join.\ncase lOfa: (local_of a b)=> [[x' y']|].\nelimtype False; apply: (DisjointLS_local_of_contra lOftr lOfa).\nby case: D=> /= [][]H1 []H2 []H3 H4 [][]H5 []H6 H7 [][]H8 H9 []H10 H11.\napply: IH.\nby case: D=> /= [][]H1 []H2 []H3 H4 [][]H5 []H6 H7 [][]H8 H9 []H10 H11; split.\nelim: mus D; first by rewrite /= /join lOf0 lOf1 lOftr.\nmove=> a mus' IH D /=; rewrite /join.\ncase: (local_of a b)=> //.\napply: IH.\nby case: D=> /= [][]H1 []H2 []H3 H4 [][]H5 []H6 H7 [][]H8 H9 []H10 H11; split.\nby case: D=> /= [][]H1 []H2 H3 [][]H4 H5 []H6 H7; split.\nQed.\n\nLemma join_all_shift_extern_ofE :\n  extern_of (join_all mu_trash' mus)\n  = join2 (extern_of mu0) (extern_of (join_all mu_trash mus)).\nProof.\nelim: mus=> // a mus' IH /=.\nrewrite IH //.\nby rewrite join2A (join2C (extern_of a)) -join2A.\nQed.\n\nEnd join_all_shift.\n\nDefinition replace_externs' (mu : SM_Injection) (eSrc' eTgt' : block -> bool) :=\n  match mu with\n    | {| locBlocksSrc := locBSrc; locBlocksTgt := locBTgt; pubBlocksSrc := pSrc;\n      pubBlocksTgt := pTgt; local_of := local; frgnBlocksSrc := frgnBSrc;\n      frgnBlocksTgt := frgnBTgt; extern_of := extern |} =>\n      {| locBlocksSrc := locBSrc;\n         locBlocksTgt := locBTgt;\n         pubBlocksSrc := pSrc;\n         pubBlocksTgt := pTgt;\n         local_of := local;\n         extBlocksSrc := eSrc';\n         extBlocksTgt := eTgt';\n         frgnBlocksSrc := frgnBSrc;\n         frgnBlocksTgt := frgnBTgt;\n         extern_of := restrict extern eSrc' |}\n  end.\n\nLemma replace_externs'_locBlocksSrc mu eSrc' eTgt' :\n  locBlocksSrc (replace_externs' mu eSrc' eTgt')\n  = locBlocksSrc mu.\nProof. by case: mu. Qed.\n\nLemma replace_externs'_locBlocksTgt mu eSrc' eTgt' :\n  locBlocksTgt (replace_externs' mu eSrc' eTgt')\n  = locBlocksTgt mu.\nProof. by case: mu. Qed.\n\nLemma replace_externs'_extBlocksSrc mu eSrc' eTgt' :\n  extBlocksSrc (replace_externs' mu eSrc' eTgt')\n  = eSrc'.\nProof. by case: mu. Qed.\n\nLemma replace_externs'_extBlocksTgt mu eSrc' eTgt' :\n  extBlocksTgt (replace_externs' mu eSrc' eTgt')\n  = eTgt'.\nProof. by case: mu. Qed.\n\nLemma replace_externs'_local_of mu eSrc' eTgt' :\n  local_of (replace_externs' mu eSrc' eTgt')\n  = local_of mu.\nProof. by case: mu. Qed.\n\nLemma replace_externs'_extern_of mu eSrc' eTgt' :\n  extern_of (replace_externs' mu eSrc' eTgt')\n  = restrict (extern_of mu) eSrc'.\nProof. by case: mu. Qed.\n\nLemma replace_externs'_wd (mu : Inj.t) eSrc' eTgt' :\n  (forall b, locBlocksSrc mu b = false \\/ eSrc' b = false) ->\n  (forall b, locBlocksTgt mu b = false \\/ eTgt' b = false) ->\n  (forall b, frgnBlocksSrc mu b -> eSrc' b) ->\n  (forall b, frgnBlocksTgt mu b -> eTgt' b) ->\n  SM_wd (replace_externs' mu eSrc' eTgt').\nProof.\nmove=> H1 H2 S1 S2; apply: Build_SM_wd.\nrewrite replace_externs'_locBlocksSrc.\nby rewrite replace_externs'_extBlocksSrc.\nrewrite replace_externs'_locBlocksTgt.\nby rewrite replace_externs'_extBlocksTgt.\nrewrite replace_externs'_local_of.\nmove=> b1 b2 z lOf.\ncase: (Inj_wd mu)=> _ _ H3 _ _ _ _ _.\ncase: (H3 _ _ _ lOf).\nrewrite replace_externs'_locBlocksSrc.\nrewrite replace_externs'_locBlocksTgt.\nby move=> ? ?; split.\nrewrite replace_externs'_extern_of.\nrewrite replace_externs'_extBlocksSrc.\nrewrite replace_externs'_extBlocksTgt.\nAbort. (*FIXME*)\n\nLemma vis_restrict_sm mu X : vis (restrict_sm mu X) = vis mu.\nProof.\nby extensionality b; case: mu.\nQed.\n\nLemma sm_locally_allocated_refl mu m1 m2 :\n  sm_locally_allocated mu mu m1 m2 m1 m2.\nProof.\ncase: mu=> // ? ? ? ? ? ? ? ? ? ? /=; split=> //.\nby extensionality b; rewrite freshloc_irrefl orb_false_r.\nsplit; first by extensionality b; rewrite freshloc_irrefl orb_false_r.\nby split.\nQed.\n\nLemma inject_incr_empty j : inject_incr (fun _ => None) j.\nProof.\nby move=> b b' ofs; discriminate.\nQed.\n\nImport structured_injections.\n\nLemma sharedTgt_DomTgt (mu : Inj.t) :\n  forall b, sharedTgt mu b -> DomTgt mu b.\nProof.\nrewrite /sharedTgt /DomTgt=> b; move/orP; case.\nby move/(frgnBlocksExternTgt _ (Inj_wd _) _)=> ->; apply/orP; right.\nby move/(pubBlocksLocalTgt _ (Inj_wd _) _)=> ->; apply/orP; left.\nQed.\n\nSection getBlocks_lems.\n\nContext args1 args2 j (vinj : Val.inject_list j args1 args2).\n\nLemma getBlocks_tail v vs b :\n  getBlocks vs b ->\n  getBlocks (v :: vs) b.\nProof.\nby case: v=> //? ? ?; rewrite getBlocksD; apply/orP; right.\nQed.\n\nLemma vals_def_getBlocksTS b' :\n  vals_def args1 ->\n  getBlocks args2 b' ->\n  exists b d', [/\\ getBlocks args1 b & j b = Some (b',d')].\nProof.\nmove=> H1 H2.\nelim: args2 args1 vinj H1 H2=> //.\nmove=> a2 args2' IH args1' vinj' H1 H2.\nmove: H2 vinj' H1; rewrite getBlocksD.\ncase: args1'; first by move=> ?; inversion 1.\nmove=> a1 args1' /=; case: a2=> //.\nmove=> A; inversion 1; subst; move/andP=> []C D.\ncase: (IH _ H4 D A)=> x []y []? ?; exists x,y; split=> //.\nby apply: getBlocks_tail.\nmove=> i A; inversion 1; subst; move/andP=> []C D.\ncase: (IH _ H4 D A)=> x []y []? ?; exists x,y; split=> //.\nby apply: getBlocks_tail.\nmove=> i A; inversion 1; subst; move/andP=> []C D.\ncase: (IH _ H4 D A)=> x []y []? ?; exists x,y; split=> //.\nby apply: getBlocks_tail.\nmove=> i A; inversion 1; subst; move/andP=> []C D.\ncase: (IH _ H4 D A)=> x []y []? ?; exists x,y; split=> //.\nby apply: getBlocks_tail.\nmove=> i A; inversion 1; subst; move/andP=> []C D.\ncase: (IH _ H4 D A)=> x []y []? ?; exists x,y; split=> //.\nby apply: getBlocks_tail.\nmove=> b i; case/orP.\nmove/Coqlib.proj_sumbool_true=> eq; subst b'.\ninversion 1; subst; move/andP=> []H5 H6.\ninversion H2; subst=> //.\nexists b1,delta; split=> //.\nrewrite getBlocksD; apply/orP; left.\nby apply: Coqlib.proj_sumbool_is_true.\nmove=> A; inversion 1; subst; case/andP=> B C.\ncase: (IH _ H4 C A)=> x []y []? ?; exists x,y; split=> //.\nby apply: getBlocks_tail.\nQed.\n\nEnd getBlocks_lems.\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/join_sm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.4804786780479071, "lm_q1q2_score": 0.2533643532045529}}
{"text": "(** * Projection functors from comma categories *)\nRequire Import Category.Core Functor.Core.\nRequire Import Category.Prod Functor.Prod.Core.\nRequire Import Functor.Composition.Core Functor.Identity.\nRequire Import InitialTerminalCategory.Core InitialTerminalCategory.Functors.\nRequire Comma.Core.\nRequire Import Types.Prod.\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\". (* work around bug #5567, https://coq.inria.fr/bugs/show_bug.cgi?id=5567, notation-overridden,parsing should not trigger for only printing notations *)\n\nSet Universe Polymorphism.\nSet Implicit Arguments.\nGeneralizable All Variables.\nSet Asymmetric Patterns.\n\nLocal Open Scope functor_scope.\nLocal Open Scope category_scope.\n\n(** ** First projection [(S / T) → A × B] (for [S : A → C ← B : T]) *)\nSection comma_category.\n  Variables A B C : PreCategory.\n  Variable S : Functor A C.\n  Variable T : Functor B C.\n\n  Definition comma_category_projection : Functor (S / T) (A * B)\n    := Build_Functor\n         (S / T) (A * B)\n         (fun abf => (CommaCategory.a abf, CommaCategory.b abf)%core)\n         (fun _ _ m => (CommaCategory.g m, CommaCategory.h m)%core)\n         (fun _ _ _ _ _ => idpath)\n         (fun _ => idpath).\nEnd comma_category.\n\n(** ** First projections [(S / a) → A] and [(a / S) → A] *)\nSection slice_category.\n  Variable A : PreCategory.\n\n  Local Arguments Functor.Composition.Core.compose / .\n  Local Arguments Functor.Composition.Core.compose_composition_of / .\n  Local Arguments Functor.Composition.Core.compose_identity_of / .\n  Local Arguments path_prod / .\n  Local Arguments path_prod' / .\n  Local Arguments path_prod_uncurried / .\n\n  Definition arrow_category_projection : Functor (arrow_category A) A\n    := Eval simpl in fst o comma_category_projection _ 1.\n\n  Definition slice_category_over_projection (a : A) : Functor (A / a) A\n    := Eval simpl in fst o comma_category_projection 1 _.\n\n  Definition coslice_category_over_projection (a : A) : Functor (a \\ A) A\n    := Eval simpl in snd o comma_category_projection _ 1.\n\n  Section slice_coslice.\n    Variable C : PreCategory.\n    Variable a : C.\n    Variable S : Functor A C.\n\n    Definition slice_category_projection : Functor (S / a) A\n      := Eval simpl in fst o comma_category_projection S !a.\n\n    Definition coslice_category_projection : Functor (a / S) A\n      := Eval simpl in snd o comma_category_projection !a S.\n  End slice_coslice.\nEnd slice_category.\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/Comma/Projection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.25336434606623276}}
{"text": "Require Import Tweetnacl.Libs.Export.\n\nSection get.\n\nContext {T:Type}.\n\nDefinition get_a (t:(T * T * T * T * T * T)) : T := match t with\n  (a,b,c,d,e,f) => a\nend.\nDefinition get_b (t:(T * T * T * T * T * T)) : T := match t with\n  (a,b,c,d,e,f) => b\nend.\nDefinition get_c (t:(T * T * T * T * T * T)) : T := match t with\n  (a,b,c,d,e,f) => c\nend.\nDefinition get_d (t:(T * T * T * T * T * T)) : T := match t with\n  (a,b,c,d,e,f) => d\nend.\nDefinition get_e (t:(T * T * T * T * T * T)) : T := match t with\n  (a,b,c,d,e,f) => e\nend.\nDefinition get_f (t:(T * T * T * T * T * T)) : T := match t with\n  (a,b,c,d,e,f) => f\nend.\n\nEnd get.\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/proofs/spec/Gen/Get_abcdef.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4804786780479071, "lm_q1q2_score": 0.2533643460662327}}
{"text": "(*\nCopyright © 2009 Valentin Blot and Bas Spitters\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis proof and associated documentation files (the \"Proof\"), to deal in\nthe Proof without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Proof, and to permit persons to whom the Proof is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Proof.\n\nTHE PROOF IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE PROOF OR THE USE OR OTHER DEALINGS IN THE PROOF.\n*)\nRequire Export CRings RingClass.\n\nSection cring_is_ring.\nGlobal Instance CRing_is_Ring (CR : CRing) : Ring (@cm_unit CR) (@cr_one CR) (@csg_op CR) (@cr_mult CR) (fun x y => x [-] y) (@cg_inv CR).\nProof with auto.\n split;split;algebra.\nQed.\nEnd cring_is_ring.\n\nSection SubCRings.\n\nVariable CR : CRing.\nVariable P : CR -> Type.\nVariable Punit : P [0].\nVariable op_pres_P : bin_op_pres_pred _ P csg_op.\nVariable inv_pres_P : un_op_pres_pred _ P cg_inv.\nVariable Pone : P [1].\nVariable mul_pres_P : bin_op_pres_pred _ P cr_mult.\n\nLet subcrr : CAbGroup := Build_SubCAbGroup _ _ Punit op_pres_P inv_pres_P.\nLet submult : CSetoid_bin_op subcrr := Build_SubCSetoid_bin_op _ _ _ mul_pres_P.\n\nLemma isring_scrr : is_CRing subcrr (Build_subcsetoid_crr _ _ _ Pone) submult.\nProof.\n assert (associative submult).\n  intros x y z; destruct x as [x xpf]; destruct y as [y ypf]; destruct z as [z zpf]; simpl; apply mult_assoc.\n apply (Build_is_CRing _ _ _ H).\n    split; intro x; destruct x as [x xpf]; simpl; algebra.\n   intros x y; destruct x as [x xpf]; destruct y as [y ypf]; simpl; apply mult_commutes.\n  intros x y z; destruct x as [x xpf]; destruct y as [y ypf]; destruct z as [z zpf]; simpl; apply dist.\n simpl; apply ring_non_triv.\nQed.\n\nDefinition Build_SubCRing : CRing := Build_CRing _ _ _ isring_scrr.\n\nGlobal Instance SubCRing_is_SubRing : SubRing P.\nProof.\n constructor; auto.\n intros x y Px Py; apply op_pres_P; [ | apply inv_pres_P ]; assumption.\nQed.\n\nEnd SubCRings.\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/liouville/CRingClass.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2533643460662327}}
{"text": "From RecoveryRefinement Require Import Lib.\nRequire Export Maybe Disk.\n\nModule TxnD.\n\n  Definition State: Type := disk * disk.\n\n  Inductive WriteStatus := WriteOK | WriteErr.\n\n  Inductive Op : Type -> Type :=\n  | op_commit : Op unit\n  | op_read (a : addr) : Op block\n  | op_write (a : addr) (b : block) : Op WriteStatus\n  | op_size : Op nat.\n\n  Inductive op_step : OpSemantics Op State :=\n  | step_commit : forall d_old d,\n      op_step (op_commit) (d_old, d) (d, d) tt\n  | step_read : forall a r d_old d,\n      (* note that we read from the old disk - this allows the log to serve\n      reads directly from the data region rather than from the log (which in\n      practice is done with an in-memory cache of the log) *)\n      match index d_old a with\n      | Some b0 => r = b0\n      | None => exists b, r = b\n      end ->\n      op_step (op_read a) (d_old, d) (d_old, d) r\n  | step_write_success : forall a b d_old d d',\n      d' = (assign d a b) ->\n      op_step (op_write a b) (d_old, d) (d_old, d') WriteOK\n  | step_write_fail : forall a b d_old d,\n      op_step (op_write a b) (d_old, d) (d_old, d) WriteErr\n  | step_size : forall d_old d,\n      (* it's an invariant of the log that the disks have the same size *)\n      op_step (op_size) (d_old, d) (d_old, d) (length d).\n\n  Definition txn_crash : State -> State -> unit -> Prop :=\n    fun '(d_old, d) '(d_old', d') r =>\n      d_old' = d_old /\\\n      d' = d_old.\n\n  Definition dyn : Dynamics Op State :=\n    {| step := op_step; crash_step := txn_crash |}.\n\n  Definition l : Layer Op :=\n    {| Layer.State := State; sem := dyn; initP := fun '(d_old, d) => d_old = d |}.\n\nEnd TxnD.\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/TxnDiskAPI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.25336434606623265}}
{"text": "(* Copyright (c) 2012-2015, Robbert Krebbers. *)\n(* This file is distributed under the terms of the BSD license. *)\nRequire Export axiomatic_statements axiomatic_expressions.\nLocal Open Scope ctype_scope.\n\nDefinition const_assert `{EnvSpec K}\n  (ν : lrval K) (P : assert K) : vassert K := λ ν', (⌜ ν' = ν ⌝ ★ P)%A.\nNotation \"ν '|' P\" := (const_assert ν P) (at level 100) : assert_scope.\nArguments const_assert _ _ _ _ _ _/.\n\nSection axiomatic_expressions_simple.\nContext `{EnvSpec K}.\nImplicit Types e : expr K.\nImplicit Types p : ptr K.\nImplicit Types v : val K.\nImplicit Types ν : lrval K.\n\n#[global] Instance:\n  `{Proper ((≡{Γ,δ}) ==> pointwise_relation _ (≡{Γ,δ})) (const_assert ν)}.\nProof. by intros Γ δ ν P Q HPQ ν'; simpl; rewrite HPQ. Qed.\n\nLemma ax_expr_weaken_post' Γ δ A P Q Q' e ν :\n  Q' ⊆{Γ,δ} Q →\n  Γ\\ δ\\ A ⊨ₑ {{ P }} e {{ ν | Q' }} → Γ\\ δ\\ A ⊨ₑ {{ P }} e {{ ν | Q }}.\nProof. intros HQ. by apply ax_expr_weaken; simpl; intros; rewrite ?HQ. Qed.\nLemma ax_expr_frame_l' Γ δ A B P Q e ν :\n  Γ\\ δ\\ B ⊨ₑ {{ P }} e {{ ν | Q }} →\n  Γ\\ δ\\ B ⊨ₑ {{ A ★ P }} e {{ ν | A ★ Q }}.\nProof.\n  intros; unfold const_assert.\n  setoid_rewrite (assoc (R:=(≡{Γ,δ})) (★)%A).\n  setoid_rewrite (comm (R:=(≡{Γ,δ})) (★)%A _ A).\n  setoid_rewrite <-(assoc (R:=(≡{Γ,δ})) (★)%A).\n  by apply ax_expr_frame_l.\nQed.\nLemma ax_expr_frame_r' Γ δ A B P Q e ν :\n  Γ\\ δ\\ B ⊨ₑ {{ P }} e {{ ν | Q }} →\n  Γ\\ δ\\ B ⊨ₑ {{ P ★ A }} e {{ ν | Q ★ A }}.\nProof. rewrite !(comm (★)%A _ A). apply ax_expr_frame_l'. Qed.\nLemma ax_expr_invariant_l' Γ δ A B P Q e ν :\n  Γ\\ δ\\ A ★ B ⊨ₑ {{ P }} e {{ ν | Q }} →\n  Γ\\ δ\\ B ⊨ₑ {{ A ★ P }} e {{ ν | A ★ Q }}.\nProof.\n  intros; unfold const_assert.\n  setoid_rewrite (assoc (R:=(≡{Γ,δ})) (★)%A).\n  setoid_rewrite (comm (R:=(≡{Γ,δ})) (★)%A _ A).\n  setoid_rewrite <-(assoc (R:=(≡{Γ,δ})) (★)%A).\n  by apply ax_expr_invariant_l.\nQed.\nLemma ax_expr_invariant_r' Γ δ A B P Q e ν :\n  Γ\\ δ\\ A ★ B ⊨ₑ {{ P }} e {{ ν | Q }} →\n  Γ\\ δ\\ B ⊨ₑ {{ P ★ A }} e {{ ν | Q ★ A }}.\nProof. rewrite !(comm (★)%A _ A). apply ax_expr_invariant_l'. Qed.\nLemma ax_expr_invariant_emp' Γ δ A B e ν :\n  Γ\\ δ\\ A ★ B ⊨ₑ {{ emp }} e {{ ν | emp }} →\n  Γ\\ δ\\ B ⊨ₑ {{ A }} e {{ ν | A }}.\nProof.\n  intros; rewrite <-(left_id _ (★)%A A); by apply ax_expr_invariant_r'.\nQed.\nLemma ax_var' Γ δ A P x p :\n  (A ★ P)%A ⊆{Γ,δ} (var x ⇓ inl p)%A →\n  Γ\\ δ\\ A ⊨ₑ {{ P }} var x {{ inl p | P }}.\nProof.\n  rewrite (comm (★)%A); intros; eapply ax_var; eauto.\n  simpl; apply assert_and_intro, assert_wand_intro; eauto.\n  by rewrite assert_Prop_l by done.\nQed.\nLemma ax_rtol' Γ δ A P Q e v p :\n  (A ★ Q)%A ⊆{Γ,δ} (.*(#v) ⇓ inl p)%A →\n  Γ\\ δ\\ A ⊨ₑ {{ P }} e {{ inr v | Q }} →\n  Γ\\ δ\\ A ⊨ₑ {{ P }} .* e {{ inl p | Q }}.\nProof.\n  rewrite (comm (★)%A); intros; eapply ax_rtol; eauto.\n  intros; apply assert_Prop_intro_l; intros; simplify_equality'.\n  apply assert_exist_intro with p, assert_and_intro, assert_wand_intro; auto.\n  by rewrite assert_Prop_l by done.\nQed.\nLemma ax_rofl' Γ δ A P Q e p :\n  Γ\\ δ\\ A ⊨ₑ {{ P }} e {{ inl p | Q }} →\n  Γ\\ δ\\ A ⊨ₑ {{ P }} & e {{ inr (ptrV p) | Q }}.\nProof.\n  intros; eapply ax_rofl; eauto.\n  intros; apply assert_Prop_intro_l; intros; simplify_equality'.\n  by rewrite assert_Prop_l by done.\nQed.\nLemma ax_load' Γ δ A P Q e p v :\n  Γ\\ δ\\ A ⊨ₑ {{ P }} e {{ inl p | Q }} →\n  (A ★ Q)%A ⊆{Γ,δ} (load (%p) ⇓ inr v)%A →\n  Γ\\ δ\\ A ⊨ₑ {{ P }} load e {{ inr v | Q }}.\nProof.\n  rewrite (comm (★)%A); intros; eapply ax_load; eauto. intros; simpl.\n  apply assert_Prop_intro_l; intros; simplify_equality'.\n  apply assert_exist_intro with v, assert_and_intro, assert_wand_intro; eauto.\n  by rewrite assert_Prop_l by done.\nQed.\nLemma ax_assign' Γ δ A P1 P2 Q1 Q2 Q ass e1 e2 μ γ τ p v va v' :\n  Γ\\ δ\\ A ⊨ₑ {{ P1 }} e1 {{ inl p | Q1 }} →\n  Γ\\ δ\\ A ⊨ₑ {{ P2 }} e2 {{ inr v | Q2 }} →\n  (A ★ Q1 ★ Q2)%A ⊆{Γ,δ} (assert_assign p v ass τ va v')%A →\n  (Q1 ★ Q2)%A ⊆{Γ,δ} (%p ↦{μ,γ} - : τ ★\n    (%p ↦{μ,perm_lock γ} # (freeze true va) : τ -★ Q))%A →\n  Some Writable ⊆ perm_kind γ →\n  Γ\\ δ\\ A ⊨ₑ {{ P1 ★ P2 }} e1 ::={ass} e2 {{ inr v' | Q }}.\nProof.\n  rewrite (comm (★)%A A); intros; eapply ax_assign; eauto.\n  intros; simpl; rewrite <-!(assoc (★)%A).\n  apply assert_Prop_intro_l; intros; simplify_equality'.\n  rewrite (comm (★)%A _ Q2), (assoc (★)%A Q1).\n  apply assert_Prop_intro_r; intros; simplify_equality'.\n  apply assert_exist_intro with va, assert_exist_intro with v',\n    assert_and_intro, assert_wand_intro; eauto.\n  rewrite assert_Prop_l by done; eauto.\nQed.\nLemma ax_assign_r' Γ δ A P Q Q' ass e1 e2 μ γ τ p v va v' :\n  Γ\\ δ\\ A ⊨ₑ {{ emp }} e1 {{ inl p | emp }} →\n  Γ\\ δ\\ A ⊨ₑ {{ P }} e2 {{ inr v | Q }} →\n  (A ★ Q)%A ⊆{Γ,δ} (assert_assign p v ass τ va v')%A →\n  Q ⊆{Γ,δ} (%p ↦{μ,γ} - : τ ★\n    (%p ↦{μ,perm_lock γ} # (freeze true va) : τ -★ Q'))%A →\n  Some Writable ⊆ perm_kind γ →\n  Γ\\ δ\\ A ⊨ₑ {{ P }} e1 ::={ass} e2 {{ inr v' | Q' }}.\nProof.\n  intros. rewrite <-(left_id _ (★)%A P).\n  eapply ax_assign'; rewrite ?(left_id _ (★)%A); eauto.\nQed.\nLemma ax_eltl' Γ δ A P Q e rs p p' :\n  Γ\\ δ\\ A ⊨ₑ {{ P }} e {{ inl p | Q }} →\n  (A ★ Q)%A ⊆{Γ,δ} (%p %> rs ⇓ inl p')%A →\n  Γ\\ δ\\ A ⊨ₑ {{ P }} e %> rs {{ inl p' | Q }}.\nProof.\n  rewrite (comm (★)%A); intros; eapply ax_eltl; eauto.\n  intros; apply assert_Prop_intro_l; intros; simplify_equality'.\n  apply assert_exist_intro with p', assert_and_intro, assert_wand_intro; auto.\n  by rewrite assert_Prop_l by done.\nQed.\nLemma ax_eltr' Γ δ A P Q e rs v v' :\n  Γ\\ δ\\ A ⊨ₑ {{ P }} e {{ inr v | Q }} →\n  (A ★ Q)%A ⊆{Γ,δ} (#v #> rs ⇓ inr v')%A →\n  Γ\\ δ\\ A ⊨ₑ {{ P }} e #> rs {{ inr v' | Q }}.\nProof.\n  rewrite (comm (★)%A); intros; eapply ax_eltr; eauto.\n  intros; apply assert_Prop_intro_l; intros; simplify_equality'.\n  apply assert_exist_intro with v', assert_and_intro, assert_wand_intro; auto.\n  by rewrite assert_Prop_l by done.\nQed.\nLemma ax_insert' Γ δ A P1 P2 Q1 Q2 e1 e2 r v1 v2 v :\n  Γ\\ δ\\ A ⊨ₑ {{ P1 }} e1 {{ inr v1 | Q1 }} →\n  Γ\\ δ\\ A ⊨ₑ {{ P2 }} e2 {{ inr v2 | Q2 }} →\n  (A ★ Q1 ★ Q2)%A ⊆{Γ,δ} (#[r:=#v1] (#v2) ⇓ inr v)%A →\n  Γ\\ δ\\ A ⊨ₑ {{ P1 ★ P2 }} #[r:=e1] e2 {{ inr v | Q1 ★ Q2 }}.\nProof.\n  rewrite (comm (★)%A); intros; eapply ax_insert; eauto.\n  intros; simpl; rewrite <-!(assoc (★)%A).\n  apply assert_Prop_intro_l; intros; simplify_equality'.\n  rewrite (comm (★)%A _ Q2), (assoc (★)%A Q1).\n  apply assert_Prop_intro_r; intros; simplify_equality'.\n  apply assert_exist_intro with v, assert_and_intro, assert_wand_intro; auto.\n  by rewrite assert_Prop_l by done.\nQed.\nLemma ax_free' Γ δ A P Q e o τ n τp :\n  Γ\\ δ\\ A ⊨ₑ {{ P }} e {{ inl (Ptr (Addr o [RArray 0 τ n] 0 (τ.[n]) τ τp)) |\n    % Ptr (addr_top o (τ.[n])) ↦{true,perm_full} - : (τ.[n]) ★ Q }} →\n  Γ\\ δ\\ A ⊨ₑ {{ P }} free e {{ inr voidV | Q }}.\nProof.\n  intros; eapply ax_free with _ τ; eauto.\n  intros; apply assert_Prop_intro_l; intros; simplify_equality'.\n  apply assert_exist_intro with o, assert_exist_intro with n,\n    assert_exist_intro with τp.\n  by rewrite !(assert_Prop_l _ _ (_ = _)) by done.\nQed.\nLemma ax_unop' Γ δ A P Q op e v v' :\n  Γ\\ δ\\ A ⊨ₑ {{ P }} e {{ inr v | Q }} →\n  (A ★ Q)%A ⊆{Γ,δ} (.{op} #v ⇓ inr v')%A →\n  Γ\\ δ\\ A ⊨ₑ {{ P }} .{op} e {{ inr v' | Q }}.\nProof.\n  rewrite (comm (★)%A); intros; eapply ax_unop; eauto.\n  intros; apply assert_Prop_intro_l; intros; simplify_equality'.\n  apply assert_exist_intro with v', assert_and_intro, assert_wand_intro; auto.\n  by rewrite assert_Prop_l by done.\nQed.\nLemma ax_binop' Γ δ A P1 P2 Q1 Q2 op e1 e2 v1 v2 v :\n  Γ\\ δ\\ A ⊨ₑ {{ P1 }} e1 {{ inr v1 | Q1 }} →\n  Γ\\ δ\\ A ⊨ₑ {{ P2 }} e2 {{ inr v2 | Q2 }} →\n  (A ★ Q1 ★ Q2)%A ⊆{Γ,δ} (# v1 .{op} # v2 ⇓ inr v)%A →\n  Γ\\ δ\\ A ⊨ₑ {{ P1 ★ P2 }} e1 .{op} e2 {{ inr v | Q1 ★ Q2 }}.\nProof.\n  rewrite (comm (★)%A); intros; eapply ax_binop; eauto.\n  intros; simpl; rewrite <-!(assoc (★)%A).\n  apply assert_Prop_intro_l; intros; simplify_equality'.\n  rewrite (comm (★)%A _ Q2), (assoc (★)%A Q1).\n  apply assert_Prop_intro_r; intros; simplify_equality'.\n  apply assert_exist_intro with v, assert_and_intro, assert_wand_intro; auto.\n  by rewrite assert_Prop_l by done.\nQed.\nLemma ax_binop_r' Γ δ A P Q op e1 e2 v1 v2 v :\n  Γ\\ δ\\ A ⊨ₑ {{ emp }} e1 {{ inr v1 | emp }} →\n  Γ\\ δ\\ A ⊨ₑ {{ P }} e2 {{ inr v2 | Q }} →\n  (A ★ Q)%A ⊆{Γ,δ} (# v1 .{op} # v2 ⇓ inr v)%A →\n  Γ\\ δ\\ A ⊨ₑ {{ P }} e1 .{op} e2 {{ inr v | Q }}.\nProof.\n  intros. rewrite <-(left_id _ (★)%A P), <-(left_id _ (★)%A Q).\n  eapply ax_binop'; rewrite ?(left_id _ (★)%A); eauto.\nQed.\nLemma ax_cast' Γ δ A P Q σ e v v' :\n  Γ\\ δ\\ A ⊨ₑ {{ P }} e {{ inr v | Q }} →\n  (A ★ Q)%A ⊆{Γ,δ} (cast{σ} (#v) ⇓ inr v')%A →\n  Γ\\ δ\\ A ⊨ₑ {{ P }} cast{σ} e {{ inr v' | Q }}.\nProof.\n  rewrite (comm (★)%A); intros; eapply ax_cast; eauto.\n  intros; apply assert_Prop_intro_l; intros; simplify_equality'.\n  apply assert_exist_intro with v', assert_and_intro, assert_wand_intro; auto.\n  by rewrite assert_Prop_l by done.\nQed.\nLemma ax_expr_if' Γ δ A P P' P'' Q e e1 e2 vb :\n  Γ\\ δ\\ A ⊨ₑ {{ P }} e {{ inr (VBase vb) | P' }} →\n  (A ★ P')%A ⊆{Γ,δ} (.{NotOp} #VBase vb ⇓ -)%A →\n  P' ⊆{Γ,δ} (P''◊)%A →\n  Γ\\ δ\\ A ⊨ₑ {{ ⌜ ¬base_val_is_0 vb ⌝ ★ P'' }} e1 {{ Q }} →\n  Γ\\ δ\\ A ⊨ₑ {{ ⌜ base_val_is_0 vb ⌝ ★ P'' }} e2 {{ Q }} →\n  Γ\\ δ\\ A ⊨ₑ {{ P }} if{e} e1 else e2 {{ Q }}.\nProof.\n  rewrite (comm (★)%A); intros; eapply ax_expr_if; eauto.\n  * intros; simpl. rewrite (comm (★)%A), <-(assoc (★)%A).\n    by apply assert_Prop_intro_l; intros; simplify_equality'.\n  * intros; apply assert_Prop_intro_l; intros; simplify_equality'.\n    by rewrite assert_Prop_l by done.\n  * intros; apply assert_Prop_intro_l; intros; simplify_equality'.\n    by rewrite assert_Prop_l by done.\nQed.\nLemma ax_expr_comma' Γ δ A P P' Q e1 e2 ν :\n  Γ\\ δ\\ A ⊨ₑ {{ P }} e1 {{ ν | P' ◊ }} →\n  Γ\\ δ\\ A ⊨ₑ {{ P' }} e2 {{ Q }} →\n  Γ\\ δ\\ A ⊨ₑ {{ P }} e1 ,, e2 {{ Q }}.\nProof.\n  intros; eapply ax_expr_comma; eauto; eapply ax_expr_weaken_post; eauto.\n  by intros; apply assert_Prop_intro_l.\nQed.\nLemma ax_do' Γ δ R J T C P Q Q' e ν :\n  Γ\\ δ\\ emp ⊨ₑ {{ P }} e {{ ν | Q }} →\n  Q ⊆{Γ,δ} (Q'◊)%A →\n  Γ\\ δ\\ R\\ J\\ T\\ C ⊨ₛ {{ P }} !e {{ Q' }}.\nProof.\n  intros. eapply ax_do, ax_expr_weaken_post; eauto.\n  by intros; apply assert_Prop_intro_l; intros; simplify_equality'.\nQed.\nLemma ax_if' Γ δ R J T C P P' P'' Q e s1 s2 vb :\n  Γ\\ δ\\ emp ⊨ₑ {{ P }} e {{ inr (VBase vb) | P' }} →\n  P' ⊆{Γ,δ} (.{NotOp} #VBase vb ⇓ -)%A →\n  P' ⊆{Γ,δ} (P''◊)%A →\n  Γ\\ δ\\ R\\ J\\ T\\ C ⊨ₛ {{ ⌜ ¬base_val_is_0 vb ⌝ ★ P'' }} s1 {{ Q }} →\n  Γ\\ δ\\ R\\ J\\ T\\ C ⊨ₛ {{ ⌜ base_val_is_0 vb ⌝ ★ P'' }} s2 {{ Q }} →\n  Γ\\ δ\\ R\\ J\\ T\\ C ⊨ₛ {{ P }} if{e} s1 else s2 {{ Q }}.\nProof.\n  intros; eapply ax_if; eauto.\n  * by intros; apply assert_Prop_intro_l; intros; simplify_equality'.\n  * intros; apply assert_Prop_intro_l; intros; simplify_equality'.\n    by rewrite assert_Prop_l by done.\n  * intros; apply assert_Prop_intro_l; intros; simplify_equality'.\n    by rewrite assert_Prop_l by done.\nQed.\nLemma ax_if'' Γ δ R J T C P Q e s1 s2 vb :\n  UnlockIndep P →\n  Γ\\ δ\\ emp ⊨ₑ {{ P }} e {{ inr (VBase vb) | P }} →\n  P ⊆{Γ,δ} (.{NotOp} #VBase vb ⇓ -)%A →\n  Γ\\ δ\\ R\\ J\\ T\\ C ⊨ₛ {{ ⌜ ¬base_val_is_0 vb ⌝ ★ P }} s1 {{ Q }} →\n  Γ\\ δ\\ R\\ J\\ T\\ C ⊨ₛ {{ ⌜ base_val_is_0 vb ⌝ ★ P }} s2 {{ Q }} →\n  Γ\\ δ\\ R\\ J\\ T\\ C ⊨ₛ {{ P }} if{e} s1 else s2 {{ Q }}.\nProof. intros ???; eapply ax_if'; eauto. Qed.\nEnd axiomatic_expressions_simple.\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_simple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.63341027751814, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.2532448023159765}}
{"text": "From mathcomp Require Import\n  ssreflect ssrfun ssrbool eqtype ssrnat seq bigop choice fintype finset.\nFrom extructures Require Import fmap.\nFrom CoqUtils Require Import word.\nRequire Import lib.utils common.types.\nRequire Import lib.ssr_list_utils lib.ssr_set_utils.\nRequire Import compartmentalization.isolate_sets compartmentalization.common.\n\nSet Bullet Behavior \"Strict Subproofs\".\nImport DoNotation.\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)\n        {ops          : machine_ops mt}\n        {spec         : machine_ops_spec ops}\n        {scr          : syscall_regs mt}\n        {cmp_syscalls : compartmentalization_syscall_addrs mt}.\n\nOpen Scope word_scope.\nLocal Notation word  := (mword mt).\nLocal Notation value := word.\nLocal Notation memory := {fmap word -> word}.\nLocal Notation registers := {fmap reg mt -> word}.\n\nImplicit Type pc : value.\nImplicit Type M : memory.\nImplicit Type R : registers.\nImplicit Type r rsrc rdest rpsrc rpdest rtgt : reg mt.\n\n(* BCP: Can we change `store_targets' to `writable_memory', and disallow writes\n   to `address_space'?  [TODO] *)\nRecord compartment := Compartment { address_space : {set value}\n                                  ; jump_targets  : {set value}\n                                  ; store_targets : {set value} }.\nNotation \"<< A , J , S >>\" := (Compartment A J S) (format \"<< A , J , S >>\").\nImplicit Type c     : compartment.\nImplicit Type A J S : {set value}.\nImplicit Type C     : seq compartment.\n\nDefinition compartment_eq c1 c2 :=\n  [&& address_space c1 == address_space c2,\n      jump_targets c1 == jump_targets c2 &\n      store_targets c1 == store_targets c2].\n\nLemma compartment_eqP : Equality.axiom compartment_eq.\nProof.\nmove=> [? ? ?] [? ? ?]; apply: (iffP and3P) => [[]|[<- <- <-]]; try by [].\nby simpl; repeat move/eqP->.\nQed.\n\nDefinition compartment_eqMixin := EqMixin compartment_eqP.\nCanonical compartment_eqType :=\n  Eval hnf in EqType compartment compartment_eqMixin.\n\nDefinition prod_of_compartment (c : compartment) : {set value} * {set value} * {set value} :=\n  (address_space c, jump_targets c, store_targets c).\n\nDefinition compartment_of_prod (c : {set value} * {set value} * {set value}) : compartment :=\n  let: (aS, jT, sT) := c in Compartment aS jT sT.\n\nLemma prod_of_compartmentK : cancel prod_of_compartment compartment_of_prod.\nProof. by case. Qed.\n\nDefinition compartment_choiceMixin := CanChoiceMixin prod_of_compartmentK.\nCanonical compartment_choiceType := Eval hnf in ChoiceType compartment compartment_choiceMixin.\nDefinition compartment_countMixin := CanCountMixin prod_of_compartmentK.\nCanonical compartment_countType := Eval hnf in CountType compartment compartment_countMixin.\nDefinition compartment_finMixin := CanFinMixin prod_of_compartmentK.\nCanonical compartment_finType := Eval hnf in FinType compartment compartment_finMixin.\n\nDefinition non_overlapping (C : seq compartment) : bool :=\n  [forall c1 in C,\n     [forall c2 in C,\n        ~~ [disjoint address_space c1 & address_space c2] ==>\n           (c1 == c2)]].\n\nLemma non_overlappingP C :\n  reflect (forall c1 c2,\n             c1 \\in C -> c2 \\in C ->\n             ~~ [disjoint address_space c1 & address_space c2] ->\n             c1 = c2)\n          (non_overlapping C).\nProof.\n  apply/(iffP idP)=> H.\n  - move=> c1 c2 Hc1 Hc2 Hdis.\n    by move/forall_inP/(_ c1 Hc1)/forall_inP/(_ c2 Hc2)/implyP/(_ Hdis)/eqP: H.\n  - apply/forall_inP=> c1 /H {H} H.\n    apply/forall_inP=> c2 /H {H} H.\n    apply/implyP=> Hdis.\n    by apply/eqP; auto.\nQed.\n\n(* BCP: Do we need this?  Can we get away with just having all user memory\n   inside a compartment at all times?  [TODO] *)\nDefinition contained_compartments (C : seq compartment) : bool :=\n  \\bigcup_(i <- C) jump_targets i :|: \\bigcup_(i <- C) store_targets i\n  \\subset \\bigcup_(i <- C) address_space i.\n\nDefinition good_compartments (C : seq compartment) : bool :=\n  non_overlapping          C &&\n  contained_compartments   C.\n\nReserved Notation \"C ⊢ p ∈ c\" (at level 70).\n\nDefinition in_compartment (p : value) (cs : seq compartment) (c : compartment) :=\n  [&& c \\in cs & p \\in address_space c].\n\nNotation \"C ⊢ p ∈ c\" := (in_compartment p C c).\nNotation \"C ⊢ p1 , p2 , .. , pk ∈ c\" :=\n  (and .. (and (C ⊢ p1 ∈ c) (C ⊢ p2 ∈ c)) .. (C ⊢ pk ∈ c))\n  (at level 70).\n\nFixpoint in_compartment_opt (C : seq compartment)\n                            (p : value) : option compartment :=\n  match C with\n    | [::]     => None\n    | c :: C => if p \\in address_space c\n                then Some c\n                else in_compartment_opt C p\n  end.\n\nRecord state := State { pc           : value\n                      ; regs         : registers\n                      ; mem          : memory\n                      ; compartments : seq compartment\n                      ; step_kind    : where_from\n                      ; previous     : compartment }.\n                        (* Initially, step_kind should be INTERNAL and previous\n                           should just be the initial main compartment *)\n\nDefinition tuple_of_state s :=\n  (pc s, regs s, mem s, compartments s, step_kind s, previous s).\n\nDefinition state_of_tuple s : state :=\n  let: (pc, regs, mem, compartments, step_kind, previous) := s in\n  State pc regs mem compartments step_kind previous.\n\nLemma tuple_of_stateK : cancel tuple_of_state state_of_tuple.\nProof. by case. Qed.\n\nDefinition state_eqMixin := CanEqMixin tuple_of_stateK.\nCanonical state_eqType := Eval hnf in EqType state state_eqMixin.\n\nDefinition permitted_now_in (C : seq compartment)\n                            (sk : where_from)\n                            (prev : compartment)\n                            (pc : word) : option compartment :=\n  do! c <- in_compartment_opt C pc;\n  do! guard (c == prev) || ((sk == JUMPED) && (pc \\in jump_targets prev));\n  Some c.\nArguments permitted_now_in C !sk prev pc /.\n\nRecord syscall := Syscall { semantics : state -> option state }.\n\nDefinition isolate_fn (MM : state) : option state :=\n  let '(State pc R M C sk c) := MM in\n  do! c_sys <- permitted_now_in C sk c pc;\n  do! pA <- R syscall_arg1;\n  do! pJ <- R syscall_arg2;\n  do! pS <- R syscall_arg3;\n  let A := address_space c in\n  let J := jump_targets c in\n  let S := store_targets c in\n  do! A' : {set value} <- isolate_create_set id M pA;\n  do! guard A' \\subset A;\n  do! guard A' != set0;\n  do! J' : {set value} <- isolate_create_set id M pJ;\n  do! guard J' \\subset (A :|: J);\n  do! S' : {set value} <- isolate_create_set id M pS;\n  do! guard S' \\subset (A :|: S);\n  let c_upd := <<A :\\: A', J, S>> in\n  let c'    := <<A',J',S'>> in\n  let C'    := c_upd :: c' :: rem_all c C in\n  do! pc'    <- R ra;\n  do! c_next <- in_compartment_opt C' pc';\n  do! guard c_upd == c_next;\n  do! guard pc' \\in jump_targets c_sys;\n  Some (State pc' R M C' JUMPED c_sys).\n\nDefinition isolate :=\n  {| semantics := isolate_fn |}.\n\n(* There are two possible design choices for this function: either it takes a\n   single address to add to the jump table, or it takes a pointer to memory with\n   a jump table layout as for isolate.  The former seems nicer, but the latter's\n   pretty easy too. *)\n\nDefinition add_to_compartment_component\n             (rd : compartment -> {set value})\n             (wr : {set value} -> compartment -> compartment)\n             (MM : state) : option state :=\n  let '(State pc R M C sk c) := MM in\n  do! c_sys <- permitted_now_in C sk c pc;\n  (* Is this necessary?  We don't need it for `isolate' because we can prove it\n     there (due to non-emptiness constraints), but we can't prove it here.  It\n     should always be true, since syscalls live in one-address compartments, so\n     if they're entered via a JAL from elsewhere, we're fine. *)\n  do! guard c != c_sys;\n  do! p <- R syscall_arg1;\n  do! guard p \\in (address_space c :|: rd c);\n  let c' := wr (p |: rd c) c in\n  let C' := c' :: rem_all c C in\n  do! pc'    <- R ra;\n  do! c_next <- in_compartment_opt C' pc';\n  do! guard c' == c_next;\n  do! guard pc' \\in jump_targets c_sys;\n  Some (State pc' R M C' JUMPED c_sys).\n\nDefinition add_to_jump_targets :=\n  {| semantics := add_to_compartment_component\n                    jump_targets\n                    (fun J' c => let '<<Aprev,_,Sprev>> := c in <<Aprev,J',Sprev>>) |}.\n\nDefinition add_to_store_targets :=\n  {| semantics := add_to_compartment_component\n                    store_targets\n                    (fun S' c => let '<<A,J,_>> := c in <<A,J,S'>>) |}.\n\nDefinition syscall_table :=\n  [fmap (isolate_addr, isolate);\n        (add_to_jump_targets_addr, add_to_jump_targets);\n        (add_to_store_targets_addr, add_to_store_targets)].\n\nDefinition user_address_space (M : memory) (c : compartment) : bool :=\n  [forall x in address_space c, M x].\nArguments user_address_space M !c /.\n\nDefinition syscall_address_space (M : memory) (c : compartment) : bool :=\n  [exists sc, [&& ~~ M sc, sc \\in syscall_addrs &\n                  address_space c == set1 sc] ].\n\nArguments syscall_address_space : simpl never.\n\nDefinition syscalls_separated (M : memory) : seq compartment -> bool :=\n  all (predU (user_address_space M) (syscall_address_space M)).\nArguments syscalls_separated M C /.\n\nDefinition syscalls_present (C : seq compartment) : bool :=\n  all (isSome ∘ in_compartment_opt C) syscall_addrs.\n\nDefinition good_state (MM : state) : bool :=\n  [&& previous MM \\in compartments MM,\n      good_compartments (compartments MM),\n      syscalls_separated (mem MM) (compartments MM) &\n      syscalls_present (compartments MM) ].\n\nDefinition good_syscall (sc : syscall) (MM : state) : bool :=\n  if good_state MM\n  then match in_compartment_opt (compartments MM) (pc MM) with\n         | Some c => if syscall_address_space (mem MM) c\n                     then match semantics sc MM with\n                            | Some MM' => good_state MM'\n                            | None     => true\n                          end\n                     else true\n         | None => true\n       end\n  else true.\n\nDefinition decode M pc :=\n  do! pc_val <- M pc;\n  decode_instr pc_val.\n\nInductive step (MM MM' : state) : Prop :=\n| step_nop :     forall pc R M C sk prev c\n                        (ST : MM = State pc R M C sk prev)\n                   (INST  : decode M pc ?= Nop _)\n                   (STEP  : permitted_now_in C sk prev pc ?= c)\n                   (NEXT  : MM' = State (pc + 1) R M C INTERNAL c),\n                        step MM MM'\n\n| step_const :   forall pc R M C sk prev c x rdest R'\n                        (ST : MM = State pc R M C sk prev)\n                   (INST  : decode M pc ?= Const x rdest)\n                   (STEP  : permitted_now_in C sk prev pc ?= c)\n                   (UPD   : updm R rdest (swcast x) ?= R')\n                   (NEXT  : MM' = State (pc + 1) R' M C INTERNAL c),\n                        step MM MM'\n\n| step_mov   :   forall pc R M C sk prev c rsrc rdest x R'\n                        (ST : MM = State pc R M C sk prev)\n                   (INST  : decode M pc ?= Mov rsrc rdest)\n                   (STEP  : permitted_now_in C sk prev pc ?= c)\n                   (GET   : R rsrc ?= x)\n                   (UPD   : updm R rdest x ?= R')\n                   (NEXT  : MM' = State (pc + 1) R' M C INTERNAL c),\n                        step MM MM'\n\n| step_binop :   forall pc R M C sk prev c op rsrc1 rsrc2 rdest x1 x2 R'\n                        (ST : MM = State pc R M C sk prev)\n                   (INST  : decode M pc ?= Binop op rsrc1 rsrc2 rdest)\n                   (STEP  : permitted_now_in C sk prev pc ?= c)\n                   (GETR1 : R rsrc1 ?= x1)\n                   (GETR2 : R rsrc2 ?= x2)\n                   (UPDR  : updm R rdest (binop_denote op x1 x2) ?= R')\n                   (NEXT  : MM' = State (pc + 1) R' M C INTERNAL c),\n                        step MM MM'\n\n| step_load  :   forall pc R M C sk prev c rpsrc rdest p x R'\n                        (ST : MM = State pc R M C sk prev)\n                   (INST  : decode M pc ?= Load rpsrc rdest)\n                   (STEP  : permitted_now_in C sk prev pc ?= c)\n                   (GETR  : R rpsrc ?= p)\n                   (GETM  : M p     ?= x)\n                   (UPDR  : updm R rdest x ?= R')\n                   (NEXT  : MM' = State (pc + 1) R' M C INTERNAL c),\n                        step MM MM'\n\n| step_store :   forall pc R M C sk prev c rsrc rpdest x p M'\n                        (ST : MM = State pc R M C sk prev)\n                   (INST  : decode M pc ?= Store rpdest rsrc)\n                   (STEP  : permitted_now_in C sk prev pc ?= c)\n                   (GETRS : R rpdest ?= p)\n                   (GETRD : R rsrc   ?= x)\n                   (VALID : p \\in address_space c :|: store_targets c)\n                   (UPDR  : updm M p x ?= M')\n                   (NEXT  : MM' = State (pc + 1) R M' C INTERNAL c),\n                        step MM MM'\n\n| step_jump  :   forall pc R M C sk prev c rtgt pc'\n                        (ST : MM = State pc R M C sk prev)\n                   (INST  : decode M pc ?= Jump rtgt)\n                   (STEP  : permitted_now_in C sk prev pc ?= c)\n                   (GETR  : R rtgt ?= pc')\n                   (NEXT  : MM' = State pc' R M C JUMPED c),\n                        step MM MM'\n\n| step_bnz   :   forall pc R M C sk prev c rsrc x b\n                        (ST : MM = State pc R M C sk prev)\n                   (INST  : decode M pc ?= Bnz rsrc x)\n                   (GETR  : R rsrc ?= b)\n                   (STEP  : permitted_now_in C sk prev pc ?= c)\n                   (NEXT  : MM' = State (pc + (if b == 0\n                                               then 1\n                                               else swcast x))\n                                        R M C INTERNAL c),\n                        step MM MM'\n\n(* We make JAL inter-compartmental, like JUMP, but things must be set up so that\n * the return address is callable by the destination compartment.  However, see\n * [Note Fancy JAL] below. *)\n| step_jal   :   forall pc R M C c sk prev rtgt pc' R'\n                        (ST : MM = State pc R M C sk prev)\n                   (INST  : decode M pc ?= Jal rtgt)\n                   (STEP  : permitted_now_in C sk prev pc ?= c)\n                   (GETR  : R rtgt ?= pc')\n                   (UPDR  : updm R ra (pc + 1) ?= R')\n                   (NEXT  : MM' = State pc' R' M C JUMPED c),\n                        step MM MM'\n\n| step_syscall : forall pc R M C sk prev sc\n                        (ST : MM = State pc R M C sk prev)\n                   (INST  : M pc = None)\n                   (GETSC : syscall_table pc ?= sc)\n                   (CALL  : semantics sc MM ?= MM'),\n                        step MM MM'.\n\n(* [Note Fancy JAL]\n * ~~~~~~~~~~~~~~~~\n * OK, you *could* do something fancy with JAL, but it would depart from the\n * original SFI paper.  In this model, JAL is inter-compartmental (like JUMP),\n * and the value stored into ra by JAL is special (either because ra is special,\n * or because JAL applies a special tag) in that it is ALWAYS a valid argument\n * to JUMP.  The ra-is-special version is nice because then we don't need to\n * introduce tags to the abstract machine, but then we can't stash it.  We can't\n * easily make JAL have the behavior that only the called compartment can return\n * via the produced address, because on the concrete machine, we won't know the\n * target compartment.  This recovers some of the ability to have proper\n * function calls, although not perfectly -- unless we introduce abstract tags,\n * we don't get nesting. *)\n\n(***** PROOFS *****)\n\n(*** Proofs for `user_address_space' and `syscall_address_space' ***)\n\nTheorem user_address_space_same : forall M c c',\n  address_space c = address_space c' ->\n  user_address_space M c = user_address_space M c'.\nProof. move=> M [A J S] [A' J' S'] /= -> //. Qed.\n\nTheorem syscall_address_space_same : forall M c c',\n  address_space c = address_space c' ->\n  syscall_address_space M c = syscall_address_space M c'.\nProof. move=> M [A J S] [A' J' S'] /= -> //. Qed.\n\nTheorem user__not_syscall : forall M c,\n  user_address_space M c -> ~~ syscall_address_space M c.\nProof.\n  move=> M c /forallP USER.\n  rewrite negb_exists.\n  apply/forallP => p.\n  apply/negP => /and3P [Hget _ /eqP Heq].\n  move: USER => /(_ p).\n  by rewrite Heq /= in_set1 eqxx /= (negbTE Hget).\nQed.\n\nTheorem syscall___not_user : forall M c,\n  syscall_address_space M c -> ~~ user_address_space M c.\nProof.\n  move=> M c.\n  apply contraTN.\n  by apply user__not_syscall.\nQed.\n\nCorollary not_user_and_syscall : forall M c,\n  ~~ (user_address_space M c && syscall_address_space M c).\nProof.\n  intros; destruct (user_address_space M c) eqn:UAS; simpl.\n  - apply user__not_syscall; assumption.\n  - auto.\nQed.\n\n(*** Proofs for `good_compartments' ***)\n\n(* For `auto' *)\nLemma good_compartments__non_overlapping C :\n  good_compartments C = true -> non_overlapping C = true.\nProof. by case/andP. Qed.\n(*Global*) Hint Resolve good_compartments__non_overlapping.\n\n(* For `auto' *)\nLemma good_compartments__contained_compartments C :\n  good_compartments C = true -> contained_compartments C = true.\nProof. by case/andP. Qed.\n(*Global*) Hint Resolve good_compartments__contained_compartments.\n\n(*** Proofs for `non_overlapping' ***)\n\nTheorem non_overlapping_subset (C1 C2 : seq compartment) :\n  {subset C1 <= C2} ->\n  non_overlapping C2 ->\n  non_overlapping C1.\nProof.\n  move=> Hsubset /non_overlappingP Hno.\n  by apply/non_overlappingP=> c1 c2 /Hsubset Hc1 /Hsubset Hc2; eauto.\nQed.\n(*Global*) Hint Resolve non_overlapping_subset.\n\nTheorem non_overlapping_tail c C :\n  non_overlapping (c :: C) -> non_overlapping C.\nProof.\n  apply non_overlapping_subset => c' Hc'.\n  by rewrite in_cons Hc' orbT.\nQed.\n(*Global*) Hint Resolve non_overlapping_tail.\n\nTheorem non_overlapping_rem c C :\n  non_overlapping C ->\n  non_overlapping (rem_all c C).\nProof.\n  apply non_overlapping_subset => c'.\n  by rewrite in_rem_all => /andP [].\nQed.\n(*Global*) Hint Resolve non_overlapping_rem.\n\nCorollary non_overlapping_rem' : forall c C,\n  good_compartments C ->\n  non_overlapping (rem_all c C).\nProof. auto. Qed.\n(*Global*) Hint Resolve non_overlapping_rem'.\n\nTheorem non_overlapping_cons c C :\n  non_overlapping (c :: C) =\n  all [pred c' | ~~ [disjoint address_space c & address_space c'] ==>\n                    (c == c')] C &&\n  non_overlapping C.\nProof.\n  apply/(sameP idP)/(iffP idP).\n  - move/andP=> [/allP Hc /non_overlappingP Hnol].\n    apply/non_overlappingP=> c1 c2.\n    rewrite !in_cons => /orP [/eqP ?|c1_in_C] /orP [/eqP ?|c2_in_C] Hdis;\n    try subst c1; try subst c2; try done; try auto.\n    + move: (Hc _ c2_in_C) => /=.\n      by rewrite Hdis /= => /eqP.\n    + move: (Hc _ c1_in_C) => /=.\n      by rewrite disjoint_sym Hdis /= => /eqP.\n  - move=> Hnol.\n    apply/andP.\n    split; last by eauto.\n    apply/allP=> c' c'_in_C.\n    apply/implyP=> Hdis.\n    by move/non_overlappingP: Hnol => /(_ c c') -> //=;\n    rewrite in_cons ?eqxx ?c'_in_C ?orbT.\nQed.\n\nLemma non_overlapping_replace c c' C :\n  c \\in C ->\n  non_overlapping C ->\n  address_space c' \\subset address_space c ->\n  all [pred c'' | ~~ [disjoint address_space c' & address_space c''] ==> (c' == c'')]\n      (rem_all c C).\nProof.\n  move=> c_in_C Hnol /subsetP Hsub.\n  apply/allP=> c''.\n  rewrite in_rem_all /= -setI_eq0 => /andP [Hneq c''_in_C].\n  apply/implyP.\n  case/set0Pn=> [p].\n  rewrite in_setI=> /andP [/Hsub p_in_c p_in_c''].\n  move/non_overlappingP: Hnol => /(_ _ _ c''_in_C c_in_C) H_c''_c.\n  suff: c'' == c by rewrite (negbTE Hneq).\n  apply/eqP/H_c''_c.\n  rewrite -setI_eq0.\n  apply/set0Pn. exists p. by rewrite in_setI p_in_c'' p_in_c.\nQed.\n\n(*** Proofs for `in_compartment' and `in_compartment_opt' ***)\n\nTheorem in_compartment_here : forall p C A J S,\n  p \\in A -> <<A,J,S>> :: C ⊢ p ∈ <<A,J,S>>.\nProof.\n  move=> p C A J S IN.\n  rewrite /in_compartment inE /=.\n  apply/andP; split.\n  - by apply/orP; left.\n  - by [].\nQed.\n(*Global*) Hint Resolve in_compartment_here.\n\nTheorem in_compartment_there : forall p C c c',\n  C ⊢ p ∈ c' -> c :: C ⊢ p ∈ c'.\nProof.\n  move=> p C c c' /andP [IN_C IN_A].\n  rewrite /in_compartment inE /=.\n  apply/andP; split.\n  - by apply/orP; right.\n  - by [].\nQed.\n(*Global*) Hint Resolve in_compartment_there.\n\nTheorem in_compartment_element C p c :\n  C ⊢ p ∈ c ->\n  c \\in C.\nProof. by move=> /andP []. Qed.\n(*Global*) Hint Resolve in_compartment_element.\n\nTheorem in_compartment__in_address_space C p c :\n  C ⊢ p ∈ c -> p \\in address_space c.\nProof. by move=> /andP []. Qed.\n(*Global*) Hint Resolve in_compartment__in_address_space.\n\nTheorem in_same_compartment C p p' c :\n  C ⊢ p ∈ c ->\n  p' \\in address_space c ->\n  C ⊢ p' ∈ c.\nProof. by move=> /andP [] *; apply/andP. Qed.\n(*Global*) Hint Resolve in_same_compartment.\n\nTheorem unique_here_not_there C p c :\n  c \\notin C     ->\n  c :: C ⊢ p ∈ c ->\n  ~~ (C ⊢ p ∈ c).\nProof.\n  move=> /negP OUT HERE; apply/negP; move=> /in_compartment_element THERE.\n  by contradict OUT.\nQed.\n(*Global*) Hint Resolve unique_here_not_there.\n\nTheorem unique_must_be_here C p c c' :\n  c' \\notin C     ->\n  c :: C ⊢ p ∈ c' ->\n  c = c'.\nProof.\n  move=> OUT /andP [IN_C _].\n  rewrite inE in IN_C; move/orP in IN_C.\n  case: IN_C.\n  - by move=> /eqP.\n  - by move/negP in OUT.\nQed.\n(*Global*) Hint Resolve unique_must_be_here.\n\nTheorem in_compartment_opt_correct : forall C p c,\n  in_compartment_opt C p ?= c -> C ⊢ p ∈ c.\nProof.\n  elim=> [// | /= c' C IH p c].\n  case I: (p \\in address_space c'); move: I; [move=> IN | move=> NIN].\n  - case=> ?; subst; apply/andP; split.\n    + by rewrite inE; apply/orP; left.\n    + by [].\n  - move=> ICO; apply IH in ICO.\n    by apply in_compartment_there.\nQed.\n(*Global*) Hint Resolve in_compartment_opt_correct.\n\nTheorem in_compartment_opt_missing_correct : forall C p,\n  in_compartment_opt C p = None -> forall c, ~~ (C ⊢ p ∈ c).\nProof.\n  elim=> [// | /= c' C IH p].\n  case I: (p \\in address_space c'); move: I; [by [] | move=> NIN NICO].\n  move/IH in NICO; move=> c; apply/negP; move=> /andP [IN_C IN_A].\n  move: (NICO c) => /negP NICO'; apply NICO'; apply/andP.\n  split; last by [].\n  rewrite inE in IN_C; move/orP in IN_C.\n  case: IN_C => [/eqP ? | //]; subst.\n  by rewrite NIN in IN_A.\nQed.\n(*Global*) Hint Resolve in_compartment_opt_missing_correct.\n\nTheorem in_compartment_opt_present : forall C p c,\n  C ⊢ p ∈ c -> exists c', in_compartment_opt C p ?= c'.\nProof.\n  elim=> [// | /= c' C IH p c /andP [IN_C IN_A]].\n  rewrite inE in IN_C.\n  case/orP: IN_C => [/eqP<- | IN_C].\n  - by rewrite IN_A; exists c.\n  - specialize IH with p c; rewrite /in_compartment IN_C IN_A /= in IH;\n      case: (IH erefl) => [c'' ICO].\n    rewrite ICO.\n    by case: (p \\in address_space c') => /=; [exists c' | exists c''].\nQed.\n(*Global*) Hint Resolve in_compartment_opt_present.\n\nCorollary in_compartment_opt_is_some C p c :\n  C ⊢ p ∈ c -> in_compartment_opt C p.\nProof.\n  move=> IC; apply in_compartment_opt_present in IC.\n  by case: IC => c' ICO; rewrite ICO.\nQed.\n(*Global*) Hint Resolve in_compartment_opt_is_some.\n\nTheorem in_compartment_opt_sound C p c :\n  non_overlapping C ->\n  C ⊢ p ∈ c ->\n  in_compartment_opt C p ?= c.\nProof.\n  elim: C => [| c' C IH Hnol /andP] //=.\n  rewrite in_cons; move=> [/orP [/eqP <- -> //|c_in_C] p_in_c].\n  have [p_in_c'|p_nin_c'] := boolP (p \\in address_space c').\n  { apply f_equal.\n    move/non_overlappingP: Hnol.\n    apply; try rewrite in_cons ?eqxx ?c_in_C ?orbT //.\n    rewrite -setI_eq0.\n    apply/set0Pn.\n    exists p. by rewrite in_setI p_in_c p_in_c'. }\n  apply IH; first by eapply non_overlapping_tail; eauto.\n  by rewrite /in_compartment c_in_C p_in_c.\nQed.\n(*Global*) Hint Resolve in_compartment_opt_sound.\n\nCorollary in_compartment_opt_sound' : forall C p c,\n  good_compartments C ->\n  C ⊢ p ∈ c ->\n  in_compartment_opt C p ?= c.\nProof. auto. Qed.\n(*Global*) Hint Resolve in_compartment_opt_sound'.\n\nCorollary in_compartment_opt_sound_is_some C p c :\n  non_overlapping C ->\n  C ⊢ p ∈ c -> in_compartment_opt C p.\nProof. by move=> NOL IC; apply in_compartment_opt_sound in IC; rewrite ?IC. Qed.\n(*Global*) Hint Resolve in_compartment_opt_sound_is_some.\n\nCorollary in_compartment_opt_sound_is_some' : forall C p c,\n  good_compartments C ->\n  C ⊢ p ∈ c -> in_compartment_opt C p.\nProof. eauto. Qed.\n(*Global*) Hint Resolve in_compartment_opt_sound_is_some'.\n\n(*** Proofs for `contained_compartments' ***)\n\nTheorem contained_compartments_spec C :\n  contained_compartments C = true <->\n  (forall c a, c \\in C -> (a \\in jump_targets c \\/ a \\in store_targets c) ->\n               exists c', c' \\in C /\\ a \\in address_space c').\nProof.\n  rewrite /contained_compartments; split.\n  - rewrite subUset; move=> /andP [IN_a_J IN_a_S] c a IN_c IN_a.\n    by case: IN_a => IN_a; [move: IN_a_J => IN | move: IN_a_S => IN];\n       move/subsetP/(_ a) in IN;\n       rewrite (bigcup_seq_in c) // in IN;\n       move/(_ erefl)/bigcup_seqP in IN.\n  - move=> SPEC; apply/subsetP; move=> a IN_a; rewrite inE in IN_a.\n    apply/bigcup_seqP.\n    by case/orP: IN_a => IN_a; move: IN_a => /bigcup_seqP [c [IN_c IN_a]];\n       apply (SPEC c) => //;\n       [left | right].\nQed.\n\n(*** Proofs for/requiring `good_compartments' ***)\n\nTheorem in_unique_compartment C p c1 c2 :\n  good_compartments C ->\n  C ⊢ p ∈ c1 ->\n  C ⊢ p ∈ c2 ->\n  c1 = c2.\nProof.\n  move=> /andP [/non_overlappingP NOL CC]\n         /andP [c1_in_C p_in_c1]\n         /andP [c2_in_C p_in_c2].\n  suff: ~~ [disjoint address_space c1 & address_space c2] by eauto.\n  rewrite -setI_eq0. apply/set0Pn. exists p.\n  by rewrite in_setI p_in_c1 p_in_c2.\nQed.\n(*Global*) Hint Resolve in_unique_compartment.\n\n(*** Proofs about `good_state' ***)\n\n(* For `auto' *)\nLemma good_state__previous_is_compartment MM :\n  good_state MM ->\n  previous MM \\in compartments MM.\nProof. by move=> /and4P [] *. Qed.\n(*Global*) Hint Resolve good_state__previous_is_compartment.\n\n(* For `auto' *)\nLemma good_state_decomposed__previous_is_compartment : forall pc R M C sk prev,\n  good_state (State pc R M C sk prev) ->\n  prev \\in C.\nProof.\n  intros pc R M C sk prev;\n    apply (@good_state__previous_is_compartment (State pc R M C sk prev)).\nQed.\n(*Global*) Hint Resolve good_state_decomposed__previous_is_compartment.\n\n(* For `auto' *)\nLemma good_state__good_compartments MM :\n  good_state MM -> good_compartments (compartments MM).\nProof. by move=> /and4P [] *. Qed.\n(*Global*) Hint Resolve good_state__good_compartments.\n\n(* For `auto' *)\nLemma good_state_decomposed__good_compartments : forall pc R M C sk prev,\n  good_state (State pc R M C sk prev) -> good_compartments C.\nProof.\n  intros pc R M C sk prev;\n    apply (@good_state__good_compartments (State pc R M C sk prev)).\nQed.\n(*Global*) Hint Resolve good_state_decomposed__good_compartments.\n\n(* For `auto' *)\nLemma good_state__syscalls_separated MM :\n  good_state MM -> syscalls_separated (mem MM) (compartments MM).\nProof. by move=> /and4P [] *. Qed.\n(*Global*) Hint Resolve good_state__syscalls_separated.\n\n(* For `auto' *)\nLemma good_state_decomposed__syscalls_separated : forall pc R M C sk prev,\n  good_state (State pc R M C sk prev) -> syscalls_separated M C.\nProof.\n  intros pc R M C sk prev;\n    apply (@good_state__syscalls_separated (State pc R M C sk prev)).\nQed.\n(*Global*) Hint Resolve good_state_decomposed__syscalls_separated.\n\n(* For `auto' *)\nLemma good_state__syscalls_present MM :\n  good_state MM -> syscalls_present (compartments MM).\nProof. by move=> /and4P [] *. Qed.\n(*Global*) Hint Resolve good_state__syscalls_present.\n\n(* For `auto' *)\nLemma good_state_decomposed__syscalls_present : forall pc R M C sk prev,\n  good_state (State pc R M C sk prev) -> syscalls_present C.\nProof.\n  intros pc R M C sk prev;\n    apply (@good_state__syscalls_present (State pc R M C sk prev)).\nQed.\n(*Global*) Hint Resolve good_state_decomposed__syscalls_present.\n\n(*** Proofs for `permitted_now_in' ***)\n\nTheorem permitted_now_in_spec : forall C sk prev pc c,\n  good_compartments C ->\n  (permitted_now_in C sk prev pc ?= c <->\n   C ⊢ pc ∈ c /\\ (c = prev \\/ (sk = JUMPED /\\ pc \\in jump_targets prev))).\nProof.\n  intros C sk prev pc c GOODS; unfold permitted_now_in; simpl; split.\n  - intros PNI.\n    destruct (in_compartment_opt C pc) as [c'|] eqn:ICO; simpl in PNI;\n      [|discriminate].\n    destruct (_ || _) eqn:COND; simpl in PNI; [|discriminate].\n    inversion PNI; subst c'.\n    apply in_compartment_opt_correct in ICO; auto.\n    split; [assumption|].\n    by move: COND => /orP [/eqP EQ | /andP [/eqP EQ IN]]; auto.\n  - intros [IC COND].\n    apply in_compartment_opt_sound in IC; auto.\n    rewrite IC; simpl.\n    move: COND => [/eqP -> | [/eqP -> ELEM]]; simpl.\n    + reflexivity.\n    + rewrite ELEM /=; auto. by rewrite orbT.\nQed.\n\nCorollary permitted_now_in__in_compartment_opt : forall C sk prev pc c,\n  good_compartments C ->\n  permitted_now_in C sk prev pc ?= c ->\n  in_compartment_opt C pc ?= c.\nProof.\n  intros C sk prev pc c GOODS PNI.\n  apply permitted_now_in_spec in PNI; try assumption.\n  move: PNI => [IC _]; apply in_compartment_opt_sound in IC; auto.\nQed.\n\n(*** Proofs about `good_syscall' and `get_syscall'. ***)\n\nTheorem isolate_good : forall MM, good_syscall isolate MM.\nProof.\n  unfold isolate, good_syscall; intros MM; simpl.\n  destruct (good_state MM) eqn:GOOD; [simpl|reflexivity].\n  destruct (in_compartment_opt _ _) as [c_sys0|] eqn:ICO_sys;\n    [simpl|reflexivity].\n  destruct (syscall_address_space _ _) eqn:SAS; [simpl|reflexivity].\n  destruct MM as [pc R M C sk c];\n    unfold good_state, isolate, isolate_fn;\n    rewrite (lock in_compartment_opt);\n    simpl in *.\n  (* Now, compute in `isolate_fn'. *)\n  let (* Can't get the binder name, so we provide it *)\n      DO var := match goal with\n                  | |- is_true match (do! _ <- ?GET;   _) with _ => _ end =>\n                    let def_var := fresh \"def_\" var in\n                    destruct GET as [var|] eqn:def_var\n                  | |- is_true match (match ?COND with true => _ | false => None end)\n                       with _ => _ end =>\n                    destruct COND eqn:var\n                end; simpl; [|reflexivity]\n  in DO c_sys;\n     DO pA; DO pJ; DO pS;\n     destruct c as [A J S] eqn:def_AJS; simpl;\n     DO A'; DO SUBSET_A'; DO NONEMPTY_A';\n     DO J'; DO SUBSET_J';\n     DO S'; DO SUBSET_S';\n     DO pc'; DO c_next; DO SAME; DO RETURN_OK;\n     set (c_upd := <<A :\\: A',J,S>>) in *;\n     set (c'    := <<A',J',S'>>) in *;\n     repeat rewrite <-def_AJS in *.\n  assert (c_sys0 = c_sys) by\n    (apply permitted_now_in__in_compartment_opt in def_c_sys;\n     solve [eauto 3 | congruence]);\n    subst c_sys0.\n  unfold good_compartments in *; simpl;\n    assert (TEMP : good_compartments C = true) by\n      (rewrite /good_state /good_compartments /= in GOOD *;\n       case/and4P: GOOD; tauto);\n    case/andP: TEMP=> NOL CC.\n  have IN : c \\in C by case/and4P: GOOD.\n  assert (NONEMPTY_A_A' : (A :\\: A') != set0). {\n    move/eqP in SAME; subst c_next.\n    rewrite <-(lock in_compartment_opt) in *; simpl in *.\n    have [EQ|] := altP (A :\\: A' =P set0); last by [].\n    subst c' c_upd; rewrite EQ in_set0 in def_c_next.\n    have [IN_pc' | NIN_pc'] := boolP (pc' \\in A').\n    - rewrite IN_pc' in def_c_next; inversion def_c_next; subst.\n      by move/eqP in NONEMPTY_A'.\n    - rewrite (negbTE NIN_pc') in def_c_next.\n      apply in_compartment_opt_correct in def_c_next.\n      move: def_c_next => /andP /= [] _.\n      by rewrite in_set0.\n  }\n  assert (NONEMPTY_A : A != set0) by\n    by apply/negP => /eqP EQ; rewrite EQ set0D in NONEMPTY_A_A';\n       move/eqP in NONEMPTY_A_A'.\n  assert (NOT_SYSCALL_c : ~~ syscall_address_space M c). {\n    apply/negP; intro SAS'; subst c.\n    move: SAS'; rewrite /syscall_address_space /=\n      => /existsP [sc /andP [NGET /andP [IN_sc /eqP EQ_sc]]];\n      rewrite !inE in IN_sc.\n    rewrite EQ_sc in c_upd SAME def_c_next; subst A.\n    apply permitted_now_in_spec in def_c_sys; eauto 3.\n    move/id in def_c_sys; move/id in NONEMPTY_A_A'; move/id in SUBSET_A'.\n    assert (NIN_pc : sc \\notin A'). {\n      move: NONEMPTY_A_A' => /set0Pn [a IN_diff].\n      rewrite in_setD in IN_diff.\n      move: IN_diff => /andP [NIN IN_a] //.\n      by rewrite in_set1 in IN_a; move: IN_a => /eqP<-.\n    }\n    move/subsetP in SUBSET_A'.\n    move: NONEMPTY_A' => /set0Pn [a' IN_a'].\n    move: (SUBSET_A' a' IN_a'); rewrite in_set1 => /eqP ?; subst a'.\n    by move/negP in NIN_pc.\n  }\n  assert (USER_c : user_address_space M c). {\n    assert (SS : syscalls_separated M C = true) by\n      (eapply good_state_decomposed__syscalls_separated; eassumption).\n    rewrite /syscalls_separated in SS. move/allP in SS.\n    specialize (SS c IN).\n    move: SS => /orP [UAS | SAS'] //.\n    by rewrite SAS' in NOT_SYSCALL_c.\n  }\n  assert (DIFF : c <> c_sys). {\n    intro; subst c_sys.\n    by rewrite SAS in NOT_SYSCALL_c.\n  }\n  rewrite -!andbA.\n  apply/and5P. split; last (apply/and3P; split).\n  - (* c_sys \\in [:: c_upd, c' & rem_all c C] *)\n    case/in_compartment_opt_correct/andP: ICO_sys => c_in _.\n    by rewrite !in_cons in_rem_all c_in (eq_sym _ c) (introF eqP DIFF) !orbT.\n  - (* non_overlapping c_upd c' *)\n    by rewrite !non_overlapping_cons (@non_overlapping_rem _ _ NOL) andbT /=\n               -setI_eq0 {1}setDE -setIA [_ :&: A']setIC setICr setI0 eqxx /=\n               (@non_overlapping_replace c c_upd C IN) ?(@non_overlapping_replace c c' C IN)\n               // def_AJS /c' /c_upd //= subsetDl.\n  - unfold contained_compartments; subst c_upd c'; simpl.\n    have As_same :\n              (A :\\: A' :|: A' :|: \\bigcup_(d <- rem_all c C) address_space d) =\n              \\bigcup_(d <- C) address_space d. {\n      rewrite big_filter /= (bigID (pred1 c) predT) /= -subsetDU //.\n      apply f_equal2=> //.\n      have Heq : [seq i <- C | i == c] =i [:: <<A,J,S>>].\n        rewrite def_AJS=> c'.\n        rewrite in_cons mem_filter orbF.\n        have [{c'} ->/=|//] := c' =P <<A,J,S>>.\n        by rewrite -def_AJS.\n      rewrite -big_filter (eq_big_idem _ _ _ Heq) /= ?big_seq1 // => x.\n      by apply setUid.\n    }\n    apply/subsetP => a /=.\n    rewrite !big_cons /= !setUA As_same !inE.\n    let fix_sub SS := move/subsetP/(_ a) in SS; rewrite ?inE in SS\n    in fix_sub SUBSET_A'; fix_sub SUBSET_J'; fix_sub SUBSET_S'.\n    move/contained_compartments_spec in CC;\n      move: (CC) => /(_ c a IN) CC_c; subst c; simpl in *.\n    (* a \\in J/S *)\n    let solve_in_orig  := apply/CC_c; by [left | right] in\n    (* a \\in J'/S' *)\n    let solve_in_prime := idtac; match goal with\n                            | SS  : is_true (a \\in pred_of_set ?JS) -> _\n                            , IN' : is_true (a \\in pred_of_set ?JS) |- _ =>\n                                move: (SS IN') => /orP [] *;\n                                [exists <<A,J,S>> | solve_in_orig]\n                          end in\n    (* a \\in \\bigcup_(d <- rem_all c C) jump_targets/store_targets d *)\n    let solve_in_rest  := idtac; match goal with\n                           | INs : is_true\n                                     (a \\in pred_of_set\n                                            (\\bigcup_(_ <- _) _ _)) |- _ =>\n                               move: INs\n                                     => /bigcup_seqP [c'' [IN_c'' IN_a'']];\n                               rewrite in_rem_all in IN_c'';\n                               move: IN_c'' => /andP [/eqP NEQ_c'' IN_c''];\n                               apply/(CC c'' a IN_c''); by [left | right]\n                         end\n    in by rewrite -!orbA; move=> /or4P [         IN_a_J | IN_a_J' | IN_a_JTs\n                                       | /or3P [ IN_a_S | IN_a_S' | IN_a_STs ]];\n          apply/bigcup_seqP;\n          by [solve_in_orig | solve_in_prime | solve_in_rest].\n  - (* user_address_space M c_upd || syscall_address_space M c_upd *)\n    subst c c_upd; simpl in *.\n    apply/orP; left.\n    by apply: forall_subset USER_c; rewrite subsetDl.\n  - (* user_address_space M c' || syscall_address_space M c' *)\n    subst c c_upd; simpl in *.\n    apply/orP; left.\n    by eapply forall_subset; [|exact USER_c].\n  - (* syscalls_separated (delete c C) *)\n    assert (SS : syscalls_separated M C = true) by\n      (eapply good_state_decomposed__syscalls_separated; eassumption).\n    apply/allP=> c''. rewrite in_rem_all=> /andP [_].\n    move/allP: SS. by apply.\n  - (* syscalls_present *)\n    assert (SP : syscalls_present C) by\n      (eapply good_state_decomposed__syscalls_present; eassumption).\n    rewrite /syscalls_present /syscall_table in SP *.\n    move/allP in SP. apply/allP.\n    move=> sc /SP IN_sc.\n    cbv [funcomp] in *.\n    case ICO: (in_compartment_opt C sc) IN_sc => [c_sc|//] _.\n    move: (ICO) => /in_compartment_opt_correct /andP [IN_c_sc IN_sc].\n    destruct (c_sc == c) eqn:EQ.\n    + move/eqP in EQ; subst; simpl in *.\n      have [->|->] // : sc \\in A :\\: A' \\/ sc \\in A'\n        by apply/setUP; rewrite -subsetDU.\n      by case: (sc \\in A :\\: A').\n    + simpl.\n      case: (sc \\in A :\\: A') => //; case: (sc \\in A') => //.\n      have /in_compartment_opt_sound -> // : rem_all c C ⊢ sc ∈ c_sc by\n        apply/andP; rewrite in_rem_all EQ /=.\n      by apply non_overlapping_rem.\nQed.\n(*Global*) Hint Resolve isolate_good.\n\nLemma good_compartments_preserved_for_add_to_compartment_component :\n  forall c c' C,\n    good_compartments C ->\n    c \\in C ->\n    address_space c = address_space c' ->\n    jump_targets c' \\subset address_space c :|: jump_targets c ->\n    store_targets c' \\subset address_space c :|: store_targets c ->\n    good_compartments (c' :: rem_all c C).\nProof.\n  move=> c c' C GOOD IN ADDR SUBSET_J SUBSET_S.\n  unfold good_compartments; repeat (andb_true_split; simpl); auto.\n  - case/andP: GOOD => Hnol _.\n    rewrite non_overlapping_cons non_overlapping_replace ?ADDR ?subxx //=.\n    by apply non_overlapping_rem.\n  - apply/contained_compartments_spec => /= d a IN_d IN_a.\n    have /contained_compartments_spec CC : contained_compartments C by auto.\n    let sub SS := move/subsetP/(_ a) in SS; rewrite inE in SS\n    in sub SUBSET_J; sub SUBSET_S.\n    have [EQ | /eqP NEQ] := altP (c' =P d); subst.\n    + specialize (CC c a IN); simpl in CC.\n      case: IN_a => IN_a;\n        [apply SUBSET_J in IN_a | apply SUBSET_S in IN_a];\n        case/orP: IN_a => IN_a.\n      (* The first two... *)\n      * by rewrite ADDR in IN_a; exists d.\n      * case: CC => [ | d' [IN_d' IN'_a]]; first by left.\n        { have [EQ | NEQ] := altP (d' =P c).\n          - by subst; exists d; rewrite -ADDR.\n          - by exists d'; rewrite inE in_rem_all NEQ /= IN_d' orbT. }\n      (* ...are the same as the second two (except for a left/right swap). *)\n      * by rewrite ADDR in IN_a; exists d.\n      * case: CC => [ | d' [IN_d' IN'_a]]; first by right.\n        { have [EQ | NEQ] := altP (d' =P c).\n          - by subst; exists d; rewrite -ADDR.\n          - by exists d'; rewrite inE in_rem_all NEQ /= IN_d' orbT. }\n    + move: IN_d; rewrite inE => /orP [/eqP ? | IN_d]; [congruence|].\n      move: CC => /(_ d a) [| // | d' [IN_d' IN'_a]].\n      * by rewrite in_rem_all in IN_d; move: IN_d => /andP [].\n      * { have [? | NEQ'] := altP (d' =P c).\n          - by subst; exists c'; rewrite inE -ADDR eq_refl /=.\n          - by exists d'; rewrite inE in_rem_all NEQ' IN_d' orbT. }\nQed.\n\nLemma add_to_compartment_component_good : forall rd wr MM,\n  (forall X c, address_space c = address_space (wr X c)) ->\n  (forall X c, jump_targets (wr X c) = jump_targets c \\/\n               jump_targets (wr X c) = X /\\ rd c = jump_targets c) ->\n  (forall X c, store_targets (wr X c) = store_targets c \\/\n               store_targets (wr X c) = X /\\ rd c = store_targets c) ->\n  good_syscall (Syscall (add_to_compartment_component rd wr)) MM.\nProof.\n  rewrite /good_syscall /= => rd wr MM ADDR eqJ eqS.\n  destruct (good_state MM) eqn:GOOD; [simpl|reflexivity].\n  destruct (in_compartment_opt _ _) as [c_sys0|] eqn:ICO_pc;\n    [simpl|reflexivity].\n  destruct (syscall_address_space _ _) eqn:SAS; [simpl|reflexivity].\n  destruct MM as [pc R M C sk c];\n    unfold good_state, add_to_compartment_component;\n    rewrite (lock in_compartment_opt);\n    simpl in *.\n  generalize GOOD; rewrite /good_state /= => /and4P [PREV GOODS SS SP].\n  destruct (permitted_now_in _ _ _ _) as [c_sys|] eqn:PNI; [simpl|reflexivity].\n  destruct (c != c_sys)               eqn:NEQ;             [simpl|reflexivity].\n  destruct (R syscall_arg1)       as [p|];             [simpl|reflexivity].\n  case ELEM: (p \\in _)                    ;            [simpl|reflexivity].\n  destruct (R ra)                 as [pc'|];           [simpl|reflexivity].\n  rewrite <-(lock in_compartment_opt);\n    destruct (in_compartment_opt _ pc') as [c_next|] eqn:ICO_pc';\n    simpl; [|reflexivity].\n  destruct (_ == c_next) eqn:EQ; move/eqP in EQ; simpl;\n    [subst c_next | reflexivity].\n  case ELEM_pc': (pc' \\in _); simpl; [|reflexivity].\n  assert (c_sys0 = c_sys) by\n    (apply permitted_now_in__in_compartment_opt in PNI; congruence);\n    subst c_sys0.\n  apply in_compartment_opt_correct in ICO_pc; auto.\n  andb_true_split.\n  - rewrite inE.\n    have -> : c_sys \\in rem_all c C. {\n      rewrite in_rem_all eq_sym; apply/andP; split; first by [].\n      eapply in_compartment_element; eassumption.\n    }\n    by rewrite orbT.\n  - destruct c as [A J S]; simpl in *.\n    rewrite inE in ELEM.\n    by apply good_compartments_preserved_for_add_to_compartment_component=> //;\n       apply/subsetP => a; rewrite inE /=;\n       [move: (eqJ) => eqX | move: (eqS) => eqX];\n       case: (eqX (p |: rd <<A,J,S>>) <<A,J,S>>) => /= [-> | [-> eqRd]];\n       first [ move=> ->; rewrite orbT\n             | move: ELEM;\n               rewrite inE in_set1 eqRd => ELEM /orP [/eqP -> // | ->];\n               rewrite orbT ].\n  - rewrite (@user_address_space_same M _ c); auto.\n    rewrite (@syscall_address_space_same M _ c); auto.\n    by move/allP/(_ _ PREV): SS.\n  - apply/allP=> c''. rewrite in_rem_all=> /andP [_].\n    move/allP: SS. by apply.\n  - move/id in SP.\n    rewrite /syscalls_present /syscall_table /is_true in SP *.\n    move/allP in SP.\n    apply/allP => sc /SP.\n    cbv [funcomp] in *.\n    simpl; rewrite <-ADDR.\n    case ICO: (in_compartment_opt C sc) => [c_sc|//] _.\n    move: (ICO) => /in_compartment_opt_correct/andP [IN_c_sc IN_sc].\n    have [<- | NEQ_sc] := altP (c_sc =P c).\n    + by rewrite IN_sc.\n    + case: (sc \\in address_space c) => //.\n      have IC' : rem_all c C ⊢ sc ∈ c_sc\n        by apply/andP; rewrite in_rem_all; split; first apply/andP.\n      apply in_compartment_opt_sound in IC'; auto.\n      by rewrite IC'.\nQed.\n\nTheorem add_to_jump_targets_good : forall MM,\n  good_syscall add_to_jump_targets MM.\nProof.\n  clear - mt ops spec.\n  intros; apply add_to_compartment_component_good;\n    intros; destruct c as [A J S]; auto.\nQed.\n(*Global*) Hint Resolve add_to_jump_targets_good.\n\nTheorem add_to_store_targets_good : forall MM,\n  good_syscall add_to_store_targets MM.\nProof.\n  clear - mt ops spec.\n  intros; apply add_to_compartment_component_good;\n    intros; destruct c as [A J S]; auto.\nQed.\n(*Global*) Hint Resolve add_to_store_targets_good.\n\nLemma get_syscall_good addr sc :\n  syscall_table addr ?= sc -> forall MM, good_syscall sc MM.\nProof.\n  rewrite /syscall_table /= !setmE.\n  have [_ /= {addr sc} [<-] MM|_] := addr =P isolate_addr; first by auto.\n  have [_ /= {addr sc} [<-] MM|_] := addr =P add_to_jump_targets_addr; first by auto.\n  by have [_ /= {addr sc} [<-] MM|//] := addr =P add_to_store_targets_addr; auto.\nQed.\n(*Global*) Hint Resolve get_syscall_good.\n\n(*** Proofs about the machine. ***)\n\nGeneralizable Variables MM.\n\nTheorem step_deterministic : forall MM0 MM1 MM2\n                                    (STEP1 : step MM0 MM1)\n                                    (STEP2 : step MM0 MM2),\n  good_state MM0 ->\n  MM1 = MM2.\nProof.\n  intros; destruct STEP1, STEP2; subst; try congruence;\n    repeat match goal with pc' := _ |- _ => subst pc' end;\n    match goal with ST : State _ _ _ _ _ _ = State _ _ _ _ _ _ |- _ =>\n      inversion ST; subst\n    end;\n    try match goal with\n      | INST  : decode ?M ?pc ?= _,\n        INST' : getm ?M ?pc = None |- _\n        => unfold decode in INST; rewrite INST' in INST; discriminate\n    end;\n    repeat f_equal; try congruence.\n  match goal with\n    |- (match ?b1 == 0 with true => 1 | false => swcast ?x1 end) =\n       (match ?b2 == 0 with true => 1 | false => swcast ?x2 end) =>\n    replace b2 with b1 by congruence; replace x2 with x1 by congruence\n  end; reflexivity.\nQed.\n\nLemma stepping_syscall_preserves_good : forall MM MM' sc,\n  mem MM (pc MM)                                          = None       ->\n  syscall_table (pc MM)                                  ?= sc         ->\n  in_compartment_opt (compartments MM) (pc MM)                         ->\n  good_syscall sc MM                                                   ->\n  semantics sc MM                                        ?= MM'        ->\n  good_state MM                                                        ->\n  good_state MM'                                         .\nProof.\n  intros MM MM' sc INST PC ICO GOODSC CALL GOOD.\n  unfold good_syscall in GOODSC; rewrite GOOD CALL in GOODSC.\n  destruct MM as [pc R M C sk prev]; simpl in *; subst.\n  destruct (in_compartment_opt C _) as [c|] eqn:ICO';\n    [clear ICO; rename ICO' into ICO | discriminate].\n  destruct (syscall_address_space M c) eqn:SAS; [assumption | clear GOODSC].\n  apply in_compartment_opt_correct in ICO; eauto 3;\n    move: ICO => /andP [IN IN'].\n  assert (SS : syscalls_separated M C) by eauto; simpl in *.\n  move: SS => /allP/(_ c IN) /= SS.\n  rewrite SAS orbF /user_address_space /= in SS.\n  move/forallP/(_ pc)/implyP/(_ IN') in SS.\n  by rewrite INST in SS.\nQed.\n\nLemma syscall_step_preserves_good : forall MM MM' sc,\n  mem MM (pc MM)         = None ->\n  syscall_table (pc MM) ?= sc   ->\n  semantics sc MM       ?= MM'  ->\n  good_state MM                 ->\n  good_state MM'       .\nProof.\n  intros MM MM' sc INST GETSC CALL GOOD; generalize GETSC => GETSC'.\n  rewrite /syscall_table mkfmapE in GETSC; simpl in *.\n  assert (SP : syscalls_present (compartments MM)) by eauto.\n  unfold syscalls_present,is_true in SP; move/allP in SP.\n  move: SP GETSC GETSC' CALL => /(_ (pc MM))/=.\n  rewrite !in_cons.\n  have [E /(_ erefl) ? [<-] ? ?|NE1] //= := pc MM =P _.\n    eapply stepping_syscall_preserves_good; try eassumption; eauto 3.\n  have [E /(_ erefl) ? [<-] ? ?|NE2] //= := pc MM =P _.\n    eapply stepping_syscall_preserves_good; try eassumption; eauto 3.\n  have [E /(_ erefl) ? [<-] ? ?|NE3] //= := pc MM =P _.\n  by eapply stepping_syscall_preserves_good; try eassumption; eauto 3.\nQed.\n\nLemma previous_compartment : forall `(STEP : step MM MM'),\n  good_state MM -> (* This hypothesis only needed for syscalls *)\n  previous MM' \\in compartments MM'.\nProof.\n  intros MM MM' STEP GOOD; destruct STEP; try solve [\n    subst; simpl in *;\n    match goal with\n      | STEP : permitted_now_in ?C ?sk ?prev ?pc ?= ?c |- context[?c \\in ?C] =>\n        apply permitted_now_in_spec in STEP; last (by eauto 2);\n        by case: STEP => [/andP []] *\n    end\n  ].\n  (* Syscalls *)\n  assert (GOOD' : good_state MM') by\n   (apply syscall_step_preserves_good with MM sc; subst; assumption);\n   auto.\nQed.\n(*Global*) Hint Resolve previous_compartment.\n\nLemma good_compartments_preserved : forall `(STEP : step MM MM'),\n  good_state MM -> (* Full strength only needed for syscalls *)\n  good_compartments (compartments MM').\nProof.\n  intros MM MM' STEP GOOD;\n    assert (GOODC : good_compartments (compartments MM)) by auto;\n    destruct STEP; try (subst; simpl in *; exact GOODC).\n  (* Syscalls *)\n  assert (GOOD' : good_state MM') by\n   (apply syscall_step_preserves_good with MM sc; subst; assumption);\n   auto.\nQed.\n(*Global*) Hint Resolve good_compartments_preserved.\n\nLemma syscalls_separated_preserved : forall `(STEP : step MM MM'),\n  good_state MM ->\n  syscalls_separated (mem MM') (compartments MM').\nProof.\n  intros MM MM' STEP GOOD; destruct STEP;\n    try solve [subst; cbv [mem compartments]; eauto 2].\n  - (* Store *)\n    subst; assert (SS : syscalls_separated M C) by eauto; simpl in *.\n    apply/allP => c' IN; move/allP/(_ c' IN)/orP in SS; apply/orP.\n    destruct c' as [A J S]; simpl in *.\n    case: SS => [UAS | SAS]; [left | right].\n    + eapply forall_impl; [| exact UAS].\n      move=> /= a GET.\n      destruct (M a) eqn:GET';\n        [clear GET; rename GET' into GET | discriminate].\n      move: GET UPDR; rewrite /updm.\n      case: (M p) => [m'|] //= GET [<-].\n      rewrite setmE GET.\n      by case: (_ == _).\n    + unfold syscall_address_space in *; cbv [address_space] in *.\n      move: SAS => /existsP [sc /and3P [NGET TABLED /eqP ->]].\n      apply/existsP; exists sc; rewrite TABLED eq_refl !andbT.\n      move: (UPDR); rewrite /updm /=.\n      case GET: (M p)=> [old|] //= SET.\n      have NEQ : sc <> p by intro; subst; rewrite GET in NGET.\n      by move: SET => /= [<-]; rewrite setmE (introF eqP NEQ).\n  - (* Syscall *)\n    assert (GOOD' : good_state MM') by\n      (apply syscall_step_preserves_good with MM sc; subst; assumption);\n      auto.\nQed.\n\nLemma syscalls_present_preserved : forall `(STEP : step MM MM'),\n  good_state MM ->\n  syscalls_present (compartments MM').\nProof.\n  intros MM MM' STEP GOOD; destruct STEP;\n    try solve [subst; simpl in *; eauto 2].\n  (* Syscall *)\n  assert (GOOD' : good_state MM') by\n    (apply syscall_step_preserves_good with MM sc; subst; assumption);\n    auto.\nQed.\n\nTheorem good_state_preserved : forall `(STEP : step MM MM'),\n  good_state MM  ->\n  good_state MM'.\nProof.\n  intros MM MM' STEP GOOD; unfold good_state; andb_true_split.\n  - eapply previous_compartment; eassumption.\n  - eapply good_compartments_preserved; eassumption.\n  - eapply syscalls_separated_preserved; eassumption.\n  - eapply syscalls_present_preserved; eassumption.\nQed.\n(*Global*) Hint Resolve good_state_preserved.\n\nLemma step__permitted_now_in : forall `(STEP : step MM MM'),\n  good_state MM ->\n  exists c, permitted_now_in (compartments MM)\n                             (step_kind MM)\n                             (previous MM)\n                             (pc MM)\n              ?= c.\nProof.\n  intros MM MM' STEP GOOD; destruct STEP; subst; simpl in *;\n    try (eexists; eassumption).\n  (* Syscalls *)\n  rewrite /syscall_table mkfmapE /= in GETSC.\n  repeat match type of GETSC with\n    | context[if ?EQ then _ else _] => destruct EQ\n    | None ?= _ => discriminate\n    | Some _ ?= _ => inversion GETSC; subst; clear GETSC;\n                     simpl in CALL;\n                     destruct (permitted_now_in C sk prev pc0);\n                     [eauto | discriminate]\n  end.\nQed.\n\nTheorem was_in_compartment : forall `(STEP : step MM MM'),\n  good_state MM ->\n  in_compartment_opt (compartments MM) (pc MM).\nProof.\n  intros MM MM' STEP GOOD; apply step__permitted_now_in in STEP; auto.\n  move: STEP => [c /permitted_now_in_spec PNI].\n  repeat (lapply PNI; clear PNI; [intros PNI | auto]).\n  destruct PNI as [IC _].\n  apply in_compartment_opt_sound in IC; auto.\n  - by rewrite IC.\n  - by apply good_compartments__non_overlapping, good_state__good_compartments.\nQed.\n\nTheorem permitted_pcs : forall MM MM' MM''\n                               (STEP : step MM MM') (STEP' : step MM' MM''),\n  good_state MM ->\n  exists c, compartments MM ⊢ pc MM ∈ c /\\\n            (pc MM' \\in address_space c \\/ pc MM' \\in jump_targets c).\nProof.\n  intros MM MM' MM'' STEP STEP' GOOD; generalize STEP => STEPPED;\n    destruct STEP;\n    subst; simpl in *;\n    try solve\n      [ apply permitted_now_in_spec in STEP; eauto 3;\n        apply step__permitted_now_in in STEP'; eauto 3;\n        destruct STEP' as [c' PNI];\n        destruct STEP as [IC STEP]; exists c; split; [exact IC|];\n        apply permitted_now_in_spec in PNI; simpl in *; eauto 3;\n\n        destruct PNI as [IC' [-> | [EQ IN_J]]];\n          [|solve [discriminate | right; auto]];\n        left; move/andP in IC'; tauto ].\n  (* Syscalls *)\n  move: (GOOD) => /and4P /= [ELEM /andP [NOL CC] SS SP].\n  rewrite /syscall_table mkfmapE /= in GETSC.\n  repeat match type of GETSC with\n    | context[if ?EQ then _ else _] => destruct EQ\n    | None ?= _ => discriminate\n    | Some _ ?= _ => inversion GETSC; subst; clear GETSC\n  end.\n  - (* isolate *)\n    unfold semantics,isolate,isolate_fn in CALL;\n      rewrite (lock in_compartment_opt) in CALL;\n      simpl in *.\n    let (* Can't get the binder name, so we provide it *)\n        DO var := match type of CALL with\n                    | (do! _ <- ?GET;   _) ?= _ =>\n                      let def_var := fresh \"def_\" var in\n                      destruct GET as [var|] eqn:def_var\n                    | (match ?COND with true => _ | false => None end) ?= _ =>\n                      destruct COND eqn:var\n                  end; simpl in CALL; [|discriminate]\n    in DO c_sys; DO pA; DO pJ; DO pS;\n       destruct prev as [A J S] eqn:def_AJS; simpl in CALL;\n       DO A'; DO SUBSET_A'; DO NONEMPTY_A';\n       DO J'; DO SUBSET_J';\n       DO S'; DO SUBSET_S';\n       DO pc'; DO c_next; DO SAME; DO RETURN_OK;\n       set (c_upd := <<A :\\: A',J,S>>) in *;\n       set (c'    := <<A',J',S'>>) in *;\n       repeat rewrite <-def_AJS in *;\n       inversion CALL; subst; clear CALL; simpl.\n    apply permitted_now_in__in_compartment_opt in def_c_sys; eauto 3.\n    exists c_sys; split.\n    + apply in_compartment_opt_correct; eauto.\n    + by right.\n  - (* add_to_jump_targets *)\n    unfold semantics,add_to_jump_targets,add_to_compartment_component in CALL;\n      rewrite (lock in_compartment_opt) in CALL;\n      simpl in CALL.\n    let (* Can't get the binder name, so we provide it *)\n        DO var := match type of CALL with\n                    | (do! _ <- ?GET;   _) ?= _ =>\n                      let def_var := fresh \"def_\" var in\n                      destruct GET as [var|] eqn:def_var\n                    | (match ?COND with true => _ | false => None end) ?= _ =>\n                      destruct COND eqn:var\n                  end; simpl in CALL; [|discriminate]\n    in DO c_sys; DO NEQ;\n       DO p; DO ELEM_p;\n       DO pc'; DO c_next;\n       destruct (_ == c_next) eqn:EQ; simpl in CALL; [|discriminate];\n       DO RETURN_OK;\n       move/eqP in EQ; rewrite EQ in def_c_next CALL;\n       inversion CALL; subst; simpl in *; clear CALL.\n    apply permitted_now_in__in_compartment_opt in def_c_sys; eauto 3.\n    exists c_sys; split.\n    + apply in_compartment_opt_correct; eauto.\n    + by right.\n  - (* add_to_store_targets *)\n    unfold semantics,add_to_store_targets,add_to_compartment_component in CALL;\n      rewrite (lock in_compartment_opt) in CALL;\n      simpl in CALL.\n    let (* Can't get the binder name, so we provide it *)\n        DO var := match type of CALL with\n                    | (do! _ <- ?GET;   _) ?= _ =>\n                      let def_var := fresh \"def_\" var in\n                      destruct GET as [var|] eqn:def_var\n                    | (match ?COND with true => _ | false => None end) ?= _ =>\n                      destruct COND eqn:var\n                  end; simpl in CALL; [|discriminate]\n    in DO c_sys; DO NEQ;\n       DO p; DO ELEM_p;\n       DO pc'; DO c_next;\n       destruct (_ == c_next) eqn:EQ; simpl in CALL; [|discriminate];\n       DO RETURN_OK;\n       move/eqP in EQ; rewrite EQ in def_c_next CALL;\n       inversion CALL; subst; simpl in *; clear CALL.\n    apply permitted_now_in__in_compartment_opt in def_c_sys; eauto 3.\n    exists c_sys; split.\n    + apply in_compartment_opt_correct; eauto.\n    + by right.\nQed.\n\nTheorem permitted_modifications : forall `(STEP : step MM MM') c,\n  good_state MM        ->\n  compartments MM ⊢ pc MM ∈ c ->\n  forall a,\n    mem MM a <> mem MM' a ->\n    a \\in address_space c \\/ a \\in store_targets c.\nProof.\n  intros MM MM' STEP c GOOD_STATE IC a DIFF; destruct STEP;\n    try (subst; simpl in *; congruence).\n  - (* Store *)\n    subst; simpl in *.\n    have [EQ|NE] := altP (a =P p); [subst|].\n    + apply permitted_now_in__in_compartment_opt,\n            in_compartment_opt_correct\n        in STEP; eauto 3.\n      by rewrite inE in VALID; replace c0 with c in * by eauto 3; apply/orP.\n    + move: UPDR DIFF; rewrite /updm; case: (M p) => [?|] //= [<-].\n      by rewrite setmE (negbTE NE).\n  - (* Syscall *)\n    rewrite /syscall_table mkfmapE /= in GETSC.\n    repeat match type of GETSC with\n      | (if ?COND then Some _ else _) ?= _ =>\n        destruct COND\n      | Some _ ?= _ =>\n        inversion GETSC; subst; clear GETSC\n      | None ?= _ =>\n        discriminate\n    end; simpl in *;\n      repeat match type of CALL with\n        | (do! _ <- ?GET; _) ?= _ =>\n          destruct GET; simpl in CALL; [|discriminate]\n        | (if ?COND then _ else _) ?= _ =>\n          destruct COND; simpl in CALL; [|discriminate]\n        | match ?c with <<_,_,_>> => _ end ?= _ =>\n          destruct c; simpl in CALL\n      end;\n      inversion CALL; subst; simpl in *; clear CALL;\n      elim DIFF; reflexivity.\nQed.\n\nEnd WithClasses.\n\nModule Notations.\n(* Repeated notations *)\nNotation memory mt := {fmap mword mt -> mword mt}.\nNotation registers mt := {fmap reg mt -> mword mt}.\nNotation \"<< A , J , S >>\" := (@Compartment _ A J S) (format \"<< A , J , S >>\").\nNotation \"C ⊢ p ∈ c\" := (in_compartment p C c) (at level 70).\nNotation \"C ⊢ p1 , p2 , .. , pk ∈ c\" :=\n  (and .. (and (C ⊢ p1 ∈ c) (C ⊢ p2 ∈ c)) .. (C ⊢ pk ∈ c))\n  (at level 70).\nEnd Notations.\n\nModule Hints.\n(* Can be updated automatically by an Emacs script; see `global-hint.el' *)\n(* Start globalized hint section *)\n  Hint Resolve good_compartments__non_overlapping.\n  Hint Resolve good_compartments__contained_compartments.\n  Hint Resolve non_overlapping_subset.\n  Hint Resolve non_overlapping_tail.\n  Hint Resolve non_overlapping_rem.\n  Hint Resolve non_overlapping_rem'.\n  Hint Resolve non_overlapping_replace.\n  Hint Resolve in_compartment_element.\n  Hint Resolve in_compartment__in_address_space.\n  Hint Resolve in_same_compartment.\n  Hint Resolve unique_here_not_there.\n  Hint Resolve unique_must_be_here.\n  Hint Resolve in_compartment_opt_correct.\n  Hint Resolve in_compartment_opt_missing_correct.\n  Hint Resolve in_compartment_opt_present.\n  Hint Resolve in_compartment_opt_is_some.\n  Hint Resolve in_compartment_opt_sound.\n  Hint Resolve in_compartment_opt_sound'.\n  Hint Resolve in_compartment_opt_sound_is_some.\n  Hint Resolve in_compartment_opt_sound_is_some'.\n  Hint Resolve in_unique_compartment.\n  Hint Resolve good_state__previous_is_compartment.\n  Hint Resolve good_state_decomposed__previous_is_compartment.\n  Hint Resolve good_state__good_compartments.\n  Hint Resolve good_state_decomposed__good_compartments.\n  Hint Resolve good_state__syscalls_separated.\n  Hint Resolve good_state_decomposed__syscalls_separated.\n  Hint Resolve good_state__syscalls_present.\n  Hint Resolve good_state_decomposed__syscalls_present.\n  Hint Resolve isolate_good.\n  Hint Resolve add_to_jump_targets_good.\n  Hint Resolve add_to_store_targets_good.\n  Hint Resolve get_syscall_good.\n  Hint Resolve previous_compartment.\n  Hint Resolve good_compartments_preserved.\n  Hint Resolve good_state_preserved.\n(* End globalized hint section *)\nEnd Hints.\n\nEnd Abs.\n\nCanonical 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/compartmentalization/abstract.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.25324480231597646}}
{"text": "(** This file is exprerimental, currently not in use.\nHere, the ⊑ relation has computation baked in, which is useful if we\never add cofixpoints, where arguments of constructors of coinductive types\nmay compute further.\nFor a variant that supports separate compilation/linking, see certiClassesLinkable\n*)\n\nRequire Import Common.exceptionMonad.\nRequire Import Common.AstCommon.\nRequire Import Common.certiClasses.\nRequire Import Common.certiClasses2.\nRequire Import Coq.Unicode.Utf8.\n\n\nClass BigStepOpSem (Term:Type) := bigStepEval:> @certiClasses.BigStepOpSem Term Term.\n\n\nClass CerticoqLanguage (Term:Type)\n  `{BigStepOpSem Term} `{GoodTerm Term} \n   `{QuestionHead Term} `{ObserveNthSubterm Term} \n:= \n{\n}.\n\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\n(* Because we may need to compute in subterms before obseving them, this definition\nbakes in computations. *)\nCoInductive compObsLe : Src -> Dst -> Prop :=\n| sameObs : forall (s : Src) (d : Dst),\n    (forall (sv:Src),\n        s ⇓ sv\n        -> (exists dv:Dst,\n              d ⇓ dv /\\\n              yesPreserved sv dv\n              /\\ (forall n:nat, liftLe compObsLe (observeNthSubterm n sv) (observeNthSubterm n dv))))\n    -> compObsLe s d.\n\n\nRequire Import SquiggleEq.tactics.\nRequire Import SquiggleEq.LibTactics.\n\nContext `{CerticoqTranslation Src Dst}.\nDefinition compObsPreserving :=\n   ∀ (o:Opt) (s:Src),\n    goodTerm s\n    -> liftLe compObsLe (Some s) (exception_option (translate Src Dst o s)).\n\nEnd CompObsPreserving.\n\nClass CerticoqTranslationCorrect {Src Dst : Type}\n  `{CerticoqLanguage Src} \n  `{CerticoqLanguage Dst}\n  `{CerticoqTranslation Src Dst}\n  := \n{\n  certiGoodPres : goodPreserving Src Dst;\n  obsePres : compObsPreserving Src Dst;\n}.\n\n\nGlobal Arguments CerticoqTranslationCorrect\n  {Src} {Dst} {H} {H0} {H1} {H2} H3  {H4} {H5} {H6} {H7} H8 {H9}.\n\nNotation \"s ⊑ t\" := (compObsLe _ _ s t) (at level 65).\n\nSection Compose.\nContext (Src Inter Dst : Type)\n   `{Ls: CerticoqLanguage Src} `{Li: CerticoqLanguage Inter}  `{Ld: CerticoqLanguage Dst}.\n\nLemma compObsLeTransitive  :\n   forall   (s : Src) (i : Inter) (d : Dst),\n  s ⊑ i\n  -> i ⊑ d \n  -> s ⊑ d.\nProof.\n  cofix compObsLeTransitive.\n  intros ? ? ? Ha Hb.\n  inversion Ha as [ss is Hah Has]. subst. clear Ha.\n  inversion Hb as [is ds Hbh Hbs]. subst. clear Hb.\n  constructor; auto.\n  intros ? Hevs.\n  destruct (Hah _ Hevs) as [iv  Hci]. clear Hah.\n  destruct Hci as [Hevi Hci].\n  destruct Hci as [Hyesi Hsubi].\n  destruct (Hbh _ Hevi) as [dv  Hcd]. clear Hbh.\n  destruct Hcd as [Hevd Hcd].\n  destruct Hcd as [Hyesd Hsubd].\n  exists dv. split;[ assumption| split];\n    [eauto using (@yesPreservedTransitive Src Inter Dst) | ]; [].\n  clear Hyesi Hyesd.\n  intros n.\n  specialize (Hsubi n).\n  specialize (Hsubd n).\n  destruct Hsubi;[| constructor ].\n  inversion Hsubd. subst. clear Hsubd.\n  constructor. eauto.\nQed.\n\nRequire Import SquiggleEq.LibTactics.\nContext   {t1 : CerticoqTranslation Src Inter}\n  {t2 : CerticoqTranslation Inter Dst}.\nGlobal Instance composeCerticoqTranslationCorrect\n(* we don't need a translation for the value type, although typically Src=SrcValue*)\n  {Ht1: CerticoqTranslationCorrect Ls Li}\n  {Ht2: CerticoqTranslationCorrect Li Ld}\n    : CerticoqTranslationCorrect Ls Ld.\nProof.\n  destruct Ht1, Ht2.\n  constructor; [eapply composePreservesGood; eauto; fail |].\n  intros ? ? Hgoods.\n  specialize (obsePres0 o _ Hgoods).\n  inverts obsePres0 as Hle Heq.\n  unfold goodPreserving in *. \n  eapply certiGoodPres0 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 (obsePres1 o _ Hgoods).\n  inverts obsePres1 as Hlei Heqi.\n  eapply certiGoodPres1 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 compObsLeTransitive; eauto.\nQed.\n\nEnd Compose.\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/common/CertiClasses/certiClasses3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778403, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.25324479678246353}}
{"text": "From Coq Require Import Reals Psatz.\nFrom Coquelicot Require Import Rcomplements Rbar Series Lim_seq Hierarchy.\nFrom stdpp Require Import relations fin_maps functions.\nFrom self.prelude Require Import classical.\nFrom self.program_logic Require Export language.\nFrom self.prob Require Export distribution couplings.\n\n(** Distribution for [n]-step partial evaluation *)\nSection exec.\n  Context {Λ : language}.\n  Implicit Types ρ : cfg Λ.\n  Implicit Types e : expr Λ.\n  Implicit Types σ : state Λ.\n\n  Definition prim_step_or_val (ρ : cfg Λ) : distr (cfg Λ) :=\n    match to_val ρ.1 with\n    | Some v => dret ρ\n    | None => prim_step ρ.1 ρ.2\n    end.\n\n  Lemma prim_step_or_val_no_val e σ :\n    to_val e = None → prim_step_or_val (e, σ) = prim_step e σ.\n  Proof. rewrite /prim_step_or_val /=. by intros ->. Qed.\n\n  Lemma prim_step_or_val_is_val e σ :\n    is_Some (to_val e) → prim_step_or_val (e, σ) = dret (e, σ).\n  Proof. rewrite /prim_step_or_val /=. by intros [? ->]. Qed.\n\n  Definition exec (n : nat) ρ : distr (cfg Λ) := iterM n prim_step_or_val ρ.\n\n  Lemma exec_O ρ :\n    exec 0 ρ = dret ρ.\n  Proof. done. Qed.\n\n  Lemma exec_Sn ρ n :\n    exec (S n) ρ = prim_step_or_val ρ ≫= exec n.\n  Proof. done. Qed.\n\n  Lemma exec_plus ρ n m :\n    exec (n + m) ρ = exec n ρ ≫= exec m.\n  Proof. rewrite /exec iterM_plus //.  Qed.\n\n  Lemma exec_1 :\n    exec 1 = prim_step_or_val.\n  Proof.\n    extensionality ρ; destruct ρ as [e σ].\n    rewrite exec_Sn /exec /= dret_id_right //.\n  Qed.\n\n  Lemma exec_Sn_r e σ n :\n    exec (S n) (e, σ) = exec n (e, σ) ≫= prim_step_or_val.\n  Proof.\n    assert (S n = n + 1)%nat as -> by lia.\n    rewrite exec_plus exec_1 //.\n  Qed.\n\n  Lemma exec_det_step n ρ e1 e2 σ1 σ2 :\n    prim_step e1 σ1 (e2, σ2) = 1 →\n    exec n ρ (e1, σ1) = 1 →\n    exec (S n) ρ (e2, σ2) = 1.\n  Proof.\n    destruct ρ as [e0 σ0].\n    rewrite exec_Sn_r.\n    intros H ->%pmf_1_eq_dret.\n    rewrite dret_id_left /=.\n    case_match; [|done].\n    assert (to_val e1 = None); [|simplify_eq].\n    eapply val_stuck. erewrite H. lra.\n  Qed.\n\n  Lemma exec_det_step_ctx K `{!LanguageCtx K} n ρ e1 e2 σ1 σ2 :\n    prim_step e1 σ1 (e2, σ2) = 1 →\n    exec n ρ (K e1, σ1) = 1 →\n    exec (S n) ρ (K e2, σ2) = 1.\n  Proof.\n    intros. eapply exec_det_step; [|done].\n    rewrite -fill_step_prob //.\n    eapply (val_stuck _ σ1 (e2, σ2)). lra.\n  Qed.\n\n  Lemma exec_PureExec_ctx K `{!LanguageCtx K} (P : Prop) m n ρ e e' σ :\n    P →\n    PureExec P n e e' →\n    exec m ρ (K e, σ) = 1 →\n    exec (m + n) ρ (K e', σ) = 1.\n  Proof.\n    move=> HP /(_ HP).\n    destruct ρ as [e0 σ0].\n    revert e e' m. induction n=> e e' m.\n    { rewrite -plus_n_O. by inversion 1. }\n    intros (e'' & Hsteps & Hpstep)%nsteps_inv_r Hdet.\n    specialize (IHn _ _ m Hsteps Hdet).\n    rewrite -plus_n_Sm.\n    eapply exec_det_step_ctx; [done| |done].\n    apply Hpstep.\n  Qed.\n\nEnd exec.\n\nGlobal Arguments exec {_} _ _ : simpl never.\n\n(** Distribution for evaluation ending in a value in less than [n]-step *)\nSection exec_val.\n  Context {Λ : language}.\n  Implicit Types ρ : cfg Λ.\n  Implicit Types e : expr Λ.\n  Implicit Types v : val Λ.\n  Implicit Types σ : state Λ.\n\n  Fixpoint exec_val (n : nat) (ρ : cfg Λ) {struct n} : distr (val Λ) :=\n    match to_val ρ.1, n with\n      | Some v, _ => dret v\n      | None, 0 => dzero\n      | None, S n => prim_step ρ.1 ρ.2 ≫= exec_val n\n    end.\n\n  Lemma exec_val_unfold (n : nat) :\n    exec_val n = λ ρ,\n      match to_val ρ.1, n with\n      | Some v, _ => dret v\n      | None, 0 => dzero\n      | None, S n => prim_step ρ.1 ρ.2 ≫= exec_val n\n      end.\n  Proof. by destruct n. Qed.\n\n  Lemma exec_val_is_val v e σ n :\n    to_val e = Some v → exec_val n (e, σ) = dret v.\n  Proof. destruct n; simpl; by intros ->. Qed.\n\n  Lemma exec_val_Sn (ρ : cfg Λ) (n: nat) :\n    exec_val (S n) ρ = prim_step_or_val ρ ≫= exec_val n.\n  Proof.\n    destruct ρ as [e σ].\n    rewrite /prim_step_or_val /=.\n    destruct (to_val e) eqn:Hv=>/=; [|done].\n    rewrite dret_id_left -/exec_val.\n    fold exec_val.\n    erewrite exec_val_is_val; eauto.\n  Qed.\n\n  Lemma exec_val_mon ρ n v :\n    exec_val n ρ v <= exec_val (S n) ρ v.\n  Proof.\n    apply refRcoupl_eq_elim.\n    move : ρ.\n    induction n.\n    - intros.\n      apply refRcoupl_from_leq.\n      intros w. rewrite /distr_le /=.\n      by case_match.\n    - intros; do 2 rewrite exec_val_Sn.\n      eapply refRcoupl_dbind; [|apply refRcoupl_eq_refl].\n      by intros ? ? ->.\n  Qed.\n\n  Lemma exec_val_mon' ρ n m v :\n    n ≤ m → exec_val n ρ v <= exec_val m ρ v.\n  Proof.\n    eapply (mon_succ_to_mon (λ x, exec_val x ρ v)); intro; apply exec_val_mon.\n  Qed.\n\n  Lemma exec_val_Sn_not_val e σ n :\n    to_val e = None →\n    exec_val (S n) (e, σ) = prim_step e σ ≫= exec_val n.\n  Proof. intros ?. rewrite exec_val_Sn prim_step_or_val_no_val //. Qed.\n\n  Lemma exec_exec_val_le n ρ v σ :\n    exec n ρ (of_val v, σ) <= exec_val n ρ v.\n  Proof.\n    revert ρ. induction n; intros [e σ'].\n    - rewrite exec_O.\n      destruct (decide ((e, σ') = (of_val v, σ))) as [[= -> ->]|].\n      + rewrite (exec_val_is_val v); [|auto using to_of_val].\n        rewrite !dret_1_1 //.\n      + rewrite dret_0 //.\n    - rewrite exec_Sn exec_val_Sn.\n      destruct (to_val e) as [w|] eqn:Heq.\n      + rewrite prim_step_or_val_is_val //.\n        rewrite 2!dret_id_left -/exec_val.\n        apply IHn.\n      + rewrite prim_step_or_val_no_val //.\n        rewrite /pmf /= /dbind_pmf.\n        eapply SeriesC_le.\n        * intros ρ. split.\n          { by apply Rmult_le_pos. }\n          apply Rmult_le_compat; by auto.\n        * eapply pmf_ex_seriesC_mult_fn.\n          exists 1. by intros ρ.\n  Qed.\n\n  Lemma exec_exec_val_det n ρ v σ :\n    exec n ρ (of_val v, σ) = 1 → exec_val n ρ v = 1.\n  Proof.\n    intros ?.\n    pose proof (exec_exec_val_le n ρ v σ).\n    pose proof (pmf_le_1 (exec_val n ρ) v).\n    lra.\n  Qed.\n\n  Lemma exec_exec_val_neq_le n m ρ v v' σ :\n    v ≠ v' → exec_val m ρ v' + exec n ρ (of_val v, σ) <= 1.\n  Proof.\n    intros Hneq.\n    eapply Rle_trans; [apply Rplus_le_compat_l, exec_exec_val_le | ].\n    eapply Rle_trans; [apply Rplus_le_compat_l,\n        (exec_val_mon' _ n (n `max` m)), Nat.le_max_l | ].\n    eapply Rle_trans; [apply Rplus_le_compat_r,\n        (exec_val_mon' _ m (n `max` m)), Nat.le_max_r | ].\n    eapply Rle_trans; [ | apply (pmf_SeriesC (exec_val (n `max` m) ρ)) ].\n    apply pmf_plus_neq_SeriesC; auto.\n  Qed.\n\n  Lemma exec_exec_val_det_neg n m ρ v v' σ :\n    exec n ρ (of_val v, σ) = 1 →\n    v ≠ v' →\n    exec_val m ρ v' = 0.\n  Proof.\n    intros Hexec Hv.\n    pose proof (exec_exec_val_neq_le n m ρ v v' σ Hv) as H.\n    rewrite Hexec in H.\n    pose proof (pmf_pos (exec_val m ρ) v').\n    lra.\n  Qed.\n\nEnd exec_val.\n\n(** Limit of [prim_exec]  *)\nSection prim_exec_lim.\n  Context {Λ : language}.\n  Implicit Types ρ : cfg Λ.\n  Implicit Types e : expr Λ.\n  Implicit Types v : val Λ.\n  Implicit Types σ : state Λ.\n\n  Definition lim_exec_val (ρ : cfg Λ) : distr (val Λ):=\n    lim_distr (λ n, exec_val n ρ) (exec_val_mon ρ).\n\n  Lemma lim_exec_val_rw (ρ : cfg Λ) v :\n    lim_exec_val ρ v = Sup_seq (λ n, (exec_val n ρ) v).\n  Proof.\n    rewrite lim_distr_pmf; auto.\n  Qed.\n\n  Lemma lim_exec_val_prim_step (ρ : cfg Λ) :\n    lim_exec_val ρ = prim_step_or_val ρ ≫= lim_exec_val.\n  Proof.\n   apply distr_ext.\n   intro v.\n   rewrite lim_exec_val_rw/=.\n   rewrite {2}/pmf/=/dbind_pmf.\n   setoid_rewrite lim_exec_val_rw.\n   assert\n     (SeriesC (λ a : cfg Λ, prim_step_or_val ρ a * Sup_seq (λ n : nat, exec_val n a v)) =\n     SeriesC (λ a : cfg Λ, Sup_seq (λ n : nat, prim_step_or_val ρ a * exec_val n a v))) as ->.\n   { apply SeriesC_ext; intro v'.\n     apply eq_rbar_finite.\n     rewrite rmult_finite.\n     rewrite (rbar_finite_real_eq (Sup_seq (λ n : nat, exec_val n v' v))); auto.\n     - rewrite <- (Sup_seq_scal_l (prim_step_or_val ρ v') (λ n : nat, exec_val n v' v)); auto.\n     - apply (Rbar_le_sandwich 0 1).\n       + apply (Sup_seq_minor_le _ _ 0%nat); simpl; auto.\n       + apply upper_bound_ge_sup; intro; simpl; auto.\n   }\n   rewrite (MCT_seriesC _ (λ n, exec_val (S n) ρ v) (lim_exec_val ρ v)); auto.\n   - intros; apply Rmult_le_pos; auto.\n   - intros.\n     apply Rmult_le_compat; auto; [apply Rle_refl | apply exec_val_mon]; auto.\n   - intro.\n     exists (prim_step_or_val ρ a); intro.\n     rewrite <- Rmult_1_r.\n     apply Rmult_le_compat_l; auto.\n   - intro n.\n     rewrite exec_val_Sn.\n     rewrite {3}/pmf/=/dbind_pmf.\n     apply SeriesC_correct; auto.\n     apply (ex_seriesC_le _ (prim_step_or_val ρ)); auto.\n     intro; split; auto.\n     + apply Rmult_le_pos; auto.\n     + rewrite <- Rmult_1_r.\n       apply Rmult_le_compat_l; auto.\n   - rewrite lim_exec_val_rw.\n     rewrite mon_sup_succ.\n     + rewrite (Rbar_le_sandwich 0 1); auto.\n       * apply (Sup_seq_correct (λ n : nat, exec_val (S n) ρ v)).\n       * apply (Sup_seq_minor_le _ _ 0%nat); simpl; auto.\n       * apply upper_bound_ge_sup; intro; simpl; auto.\n     + intro; apply exec_val_mon.\n  Qed.\n\n  Lemma lim_exec_val_exec n (ρ : cfg Λ) :\n    lim_exec_val ρ = exec n ρ ≫= lim_exec_val.\n  Proof.\n    move : ρ.\n    induction n; intro ρ.\n    - rewrite exec_O.\n      rewrite dret_id_left; auto.\n    - rewrite exec_Sn -dbind_assoc/=.\n      rewrite lim_exec_val_prim_step.\n      apply dbind_eq; [|done].\n      intros ??. apply IHn.\n  Qed.\n\n  Lemma lim_exec_val_exec_det n ρ (v : val Λ) σ :\n    exec n ρ (of_val v, σ) = 1 →\n    lim_exec_val ρ = dret v.\n  Proof.\n    intro Hv.\n    apply distr_ext.\n    intro v'.\n    rewrite lim_exec_val_rw.\n    rewrite {2}/pmf/=/dret_pmf.\n    assert (is_finite (Sup_seq (λ n, exec_val n ρ v'))) as Haux.\n    {\n      apply (Rbar_le_sandwich 0 1).\n      + apply (Sup_seq_minor_le _ _ 0%nat); simpl; auto.\n      + apply upper_bound_ge_sup; intro; simpl; auto.\n    }\n    case_bool_decide; simplify_eq.\n    - apply Rle_antisym.\n      + apply finite_rbar_le; auto.\n        apply upper_bound_ge_sup.\n        intro; simpl; auto.\n      + apply rbar_le_finite; auto.\n        apply (Sup_seq_minor_le _ _ n); simpl; auto.\n        destruct ρ as (e2 & σ2).\n        eapply exec_exec_val_det in Hv.\n        rewrite Hv //.\n    - rewrite -(sup_seq_const 0).\n      f_equal. apply Sup_seq_ext=> m.\n      f_equal. by eapply exec_exec_val_det_neg.\n  Qed.\n\n  Lemma lim_exec_val_continous ρ1 v r :\n    (∀ n, exec_val n ρ1 v <= r) → lim_exec_val ρ1 v <= r.\n  Proof.\n    intro Hexec.\n    rewrite lim_exec_val_rw.\n    assert (is_finite (Sup_seq (λ n : nat, exec_val n ρ1 v))) as Haux.\n    {\n      apply (Rbar_le_sandwich 0 1); auto.\n      + apply (Sup_seq_minor_le _ _ 0%nat); simpl; auto.\n      + apply upper_bound_ge_sup; intro; simpl; auto.\n    }\n    apply finite_rbar_le; auto.\n    apply upper_bound_ge_sup.\n    intro; simpl; auto.\n  Qed.\n\n\nEnd prim_exec_lim.\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/exec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2531635848781404}}
{"text": "Add LoadPath \"C:\\Users\\Polina\\Documents\\Coq\\amintimany-categories-bd56bc28cc67\\amintimany-categories-bd56bc28cc67\\Category\".\nAdd LoadPath \"C:\\Users\\Polina\\Documents\\Coq\\amintimany-categories-bd56bc28cc67\\amintimany-categories-bd56bc28cc67\\Essentials\".\nAdd LoadPath \"C:\\Users\\Polina\\Documents\\Coq\\amintimany-categories-bd56bc28cc67\\amintimany-categories-bd56bc28cc67\\Functor\".\nAdd LoadPath \"C:\\Users\\Polina\\Documents\\Coq\\amintimany-categories-bd56bc28cc67\\amintimany-categories-bd56bc28cc67\\Cat\".\nAdd LoadPath \"C:\\Users\\Polina\\Documents\\Coq\\amintimany-categories-bd56bc28cc67\\amintimany-categories-bd56bc28cc67\\NatTrans\".\nAdd LoadPath \"C:\\Users\\Polina\\Documents\\Coq\\amintimany-categories-bd56bc28cc67\\amintimany-categories-bd56bc28cc67\\Limits\".\nAdd LoadPath \"C:\\Users\\Polina\\Documents\\Coq\\amintimany-categories-bd56bc28cc67\\amintimany-categories-bd56bc28cc67\\Archetypal\".\nAdd LoadPath \"C:\\Users\\Polina\\Documents\\Coq\\amintimany-categories-bd56bc28cc67\\amintimany-categories-bd56bc28cc67\\Coq_Cats\\Type_Cat\".\nAdd LoadPath \"C:\\Users\\Polina\\Documents\\Coq\\amintimany-categories-bd56bc28cc67\\amintimany-categories-bd56bc28cc67\\Ext_Cons\".\nAdd LoadPath \"C:\\Users\\Polina\\Documents\\Coq\\amintimany-categories-bd56bc28cc67\\amintimany-categories-bd56bc28cc67\\Ext_Cons\\Prod_Cat\".\nAdd LoadPath \"C:\\Users\\Polina\\Documents\\Coq\\amintimany-categories-bd56bc28cc67\\amintimany-categories-bd56bc28cc67\\Basic_Cons\".\nAdd LoadPath \"C:\\Users\\Polina\\Documents\\Coq\\amintimany-categories-bd56bc28cc67\\amintimany-categories-bd56bc28cc67\\Coq_Cats\".\nAdd LoadPath \"C:\\Users\\Polina\\Documents\\Coq\\amintimany-categories-bd56bc28cc67\\amintimany-categories-bd56bc28cc67\\Basic_Cons\".\nAdd LoadPath \"C:\\Users\\Polina\\Documents\\Coq\\amintimany-categories-bd56bc28cc67\\amintimany-categories-bd56bc28cc67\\Abst_Comp\".\nAdd LoadPath \"C:\\Users\\Polina\\Documents\\Coq\\amintimany-categories-bd56bc28cc67\\amintimany-categories-bd56bc28cc67\\Functor\".\n\nRequire Import Main_Func.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Main_Category.\nRequire Import CCC.\nRequire Import Restriction.\nRequire Import Range.\nRequire Import Set_Cat.\nRequire Import Cat.\nRequire Import NatTrans Func_Cat Operations.\n\nRequire Import Coq.Logic.EqdepFacts.\nImport EqNotations.\nRequire Import Coq.Program.Equality.\nRequire Export ProofIrrelevance.\nRequire Export JMeq.\nRequire Import Eqdep.\n\nGeneralizable All Variables.\n\n(*AXIOM proof irrelevance*)\nAxiom pf_ir : forall A: Prop , forall p q:A, p=q.\n\n\n(* objects and morphisms in the category Par *)\nDefinition hom := fun (A B : Set) => {P:A -> Prop & ( forall x:A, P x -> B )}.\n\nDefinition obj := Set.\n\n(* Equality in Par *)\nLemma HomParEqv: forall  a b: obj,   (hom a b) -> (hom a b) -> Prop  .\nProof.\n  unfold hom. intros.\n  destruct X; destruct X0.\n  exact ((forall (z:a), (x z <-> x0 z)) /\\ ( forall z:a,forall pf:x z,forall pf1:x0 z, x z -> (b0 z pf = b1 z pf1))). \nDefined.\n\n\n(* AXIOM equality in Par *)\nAxiom par_eqv_def : forall a b: obj, forall f g : hom a b, HomParEqv a b f g <-> f = g.\n\n\nLemma rel_equiv : forall a b: obj, forall f g : hom a b , f = g ->\n  forall (n1 : a) , forall (pf : projT1 f n1), forall (pf1 : projT1 g n1),\n   (projT2 f) n1 pf = (projT2 g) n1 pf1.\nProof.\n intros a b f g h. rewrite h. intros.\n replace pf with pf1. auto. apply pf_ir.\nDefined.\n\nLemma same_app : forall a b: obj, forall P : a -> Prop, forall f g : forall x : a, P x -> b, \n  forall (n1 n2 : a) , f = g -> n1 = n2 -> (forall (pf : P n1), forall (pf1 : P n2),\n   f n1 pf = g n2 pf1).\nProof.\n  intros a b P f g n1 n2 e e1.\n  rewrite e. rewrite e1. intros. rewrite (pf_ir _ pf pf1). auto.\nDefined.\n\n(* composition in Par *)\nDefinition Compose : forall A B C : Set, hom A B -> hom B C -> hom A C.\n  unfold hom.\n  intros.\n  destruct X.\n  destruct X0.\n  exists (fun (z:A) => (x z /\\ (forall (p:x z), (x0 (b z p))))).\n  intros.\n  destruct H.\n  exact (c (b x1 H) (H0 H) ).\nDefined.\n\n(* identity in Par *)\nDefinition Id : forall A : Set, hom A A.\n  unfold hom.\n  intros.\n  exists (fun (a:A) => True).\n  intros.\n  auto.\nDefined.\n\nInstance Par_Cat : Category :=\n{\n  Obj := obj;\n\n  Hom := hom;\n\n  compose := Compose;\n\n  id := Id\n}.\nProof.\n(* associativity *)\n  unfold hom. intros.\n  apply (par_eqv_def a d (Compose a b d f (Compose b c d g h)) (Compose a c d (Compose a b c f g) h)).\n  destruct f; destruct g; destruct h.\n  compute. split. intros. split; split.\n  split. destruct H. auto.\n  intros. destruct H.\n  elim (H0 p). intros; auto.\n\n  intros. \n  destruct p; destruct H. destruct (H0 x2).\n  exact (H2 (x3 x2)).\n   \n  destruct H; destruct H; auto.\n  split; destruct H. destruct H. exact (H1 p).\n\n  intro. generalize (H0 H). compute. destruct H.\n  rewrite (pf_ir  (x z)  x2 p).\n  rewrite (pf_ir (x0 (b0 z p)) (x3 p) p0).\n  auto.\n\n  intros. destruct pf. destruct a0.  destruct H. destruct (H0 H). destruct pf1. destruct a1.\n  rewrite <- (pf_ir (x z) x2 x6).\n  rewrite <- (pf_ir (x0 (b0 z x2)) (x7 x2) x3).\n  rewrite (pf_ir  (x1 (c0 (b0 z x2) (x7 x2))) (x4 (x7 x2)) (x5 (conj x2 x7))).\n  auto.\n\n\n(* symmetric associativity *)\n  unfold hom. intros.\n  apply (par_eqv_def a d (Compose a c d (Compose a b c f g) h)  (Compose a b d f (Compose b c d g h))).\n  destruct f; destruct g; destruct h.\n  compute. split. intros. split; split.\n  destruct H. destruct H. auto.\n  split. destruct H. destruct H.\n  exact (H1 p).\n \n  intro. destruct H. generalize (H0 H). intro. destruct H.\n  rewrite <- (pf_ir (x z) p x2) in H1.\n  rewrite <- (pf_ir (x0 (b0 z p)) (x3 p) p0).\n  auto.\n\n  split; destruct H.\n  auto.\n  intro.\n  destruct (H0 p). auto.\n  intro. destruct p.\n  destruct H. destruct (H0 x2). exact (H2 (x3 x2)).\n\n  intros. destruct pf; destruct pf1.\n  destruct a0.  destruct (a1 x3).\n  rewrite <- (pf_ir (x z) x3 x4).\n  rewrite <- (pf_ir (x0 (b0 z x3)) (x5 x3) x6).\n  rewrite (pf_ir (x1 (c0 (b0 z x3) (x5 x3))) (x2 (conj x3 x5)) (x7 (x5 x3))).\n  auto.\n\n(* id left unit *)\n  intros.\n  apply (par_eqv_def a b (Compose a b b h (Id b)) h ).\n  destruct h. compute.\n  split. intros. split. intro.\n  destruct H; auto.\n  intro; split. auto. intro; auto.\n\n  intros; destruct pf.\n  rewrite (pf_ir (x z) x0 pf1). auto.\n\n(* id right unit *)\n  intros.\n  apply (par_eqv_def a b (Compose a a b (Id a) h) h ).\n  destruct h. compute.\n  split. intros. split. intro.\n  destruct H; auto.\n  intro; split. auto. intro; auto.\n\n  intros; destruct pf.\n  rewrite (pf_ir (x z) (x0 t) pf1). auto.\nDefined.\n\n\n(* define restriction combinator map that makes Par a restriction category *)\nDefinition rc_ParMap : forall a b : Par_Cat, Hom a b -> Hom a a.\n  intros a b. compute. intro. destruct X.\n  exists x. intros. exact x0.\nDefined.\n\n\n(* Instantiate the restriction combinator for Par *)\nDefinition rc_Par :  RestrictionComb Par_Cat.\nProof.\n  exists rc_ParMap; intros.\n\n(* rc1 *)\n  apply (par_eqv_def a b (f ∘ rc_ParMap a b f) f).\n  destruct f. compute. split. intros. split.\n  intros. destruct H; auto.\n  split; intros; auto.\n  intros. destruct pf.\n  rewrite (pf_ir (x z) (x1 x0) pf1).\n  auto.\n  \n(* rc2 *)\n  apply (par_eqv_def a a (rc_ParMap a c g ∘ rc_ParMap a b f) (rc_ParMap a b f ∘ rc_ParMap a c g)).\n  destruct f. destruct g. compute. split. intros. split.\n  intros. destruct H; auto.\n  split; intros; auto.\n  destruct H. exact (H0 H). \n  destruct H; auto.\n\n  intros. destruct pf. destruct pf1. auto.\n\n(* rc3 *)\n  apply (par_eqv_def a a (rc_ParMap a c (g ∘ rc_ParMap a b f)) (rc_ParMap a c g ∘ rc_ParMap a b f)).\n  destruct f. destruct g. compute. split. intros. split.\n  intros. destruct H; auto.\n  split; intros; auto.\n  destruct H. auto. destruct H. exact (H0 H). \n\n  intros. destruct pf. destruct pf1. auto.\n\n(* rc4 *)\n  apply (par_eqv_def a b (rc_ParMap b c g ∘ f) (f ∘ rc_ParMap a c (g ∘ f))).\n  destruct f. destruct g. compute. split. intros. split.\n  intros. destruct H. auto.\n  split. destruct H. destruct H. auto.\n  destruct H. intros. destruct H. exact (H1 p). \n\n  intros. destruct pf. destruct pf1. \n  rewrite (pf_ir (x z) x1 (x3 a0)).\n  auto.\nDefined.\n\n(* define Par as an instance of a restruction category *)\nInstance Par_isRC : RestrictionCat Par_Cat rc_Par .\nexists. Defined.\n\nInductive empty_set : Set := .\n\nInductive unit : Set :=\n    tt : unit.\n\n(* define the terms and proofs needed to instantiate the terminal object in Par *)\nDefinition  par_p_term : Par_isRC := unit.\nDefinition  par_pt_morph : ∀ (a : Par_isRC), Hom a par_p_term.\n  intros. compute. destruct Par_isRC. \n  exists (fun (x : a) => True). intros; tauto.\nDefined.\n\nDefinition  par_id_is_ptm : id par_p_term = par_pt_morph par_p_term .\n  apply par_eqv_def. compute; split; try intros; try split; try intros; try tauto.\n  destruct z. auto. \nDefined.\n\nDefinition p_m_t_prop : Prop. \n  destruct Par_isRC. destruct rc_Par. exact (∀ (a : Par_isRC), rc a par_p_term (par_pt_morph a) = id a).\nDefined.\n\nDefinition  par_morph_total : p_m_t_prop.\n  compute. intros. try tauto.\nDefined.\n\nDefinition pmug_prop : Prop. \n  destruct Par_isRC. destruct rc_Par. \n  exact (∀ (a b : Par_isRC) (f : Hom a b), \n  ((par_pt_morph b) ∘f) = (par_pt_morph a) ∘ (rc a b f)).\nDefined.\n\nDefinition  par_pt_morph_unique_greatest : pmug_prop.\n  compute. intros. destruct f. apply par_eqv_def. \n  compute; split; try intros; try split; try intros; try split; try intros; try auto;\n  try destruct H; auto.\n  destruct pf. destruct pf1. auto.\nDefined.\n\n(* define the terms and proofs needed to instantiate the partial products in Par *)\nDefinition  par_p_prod (a b : Par_isRC) : Par_isRC .\n  compute. compute in a. compute in b. exact (a * b).\nDefined.\n\nDefinition  par_Pi_1p (a b : Par_isRC) : Hom (par_p_prod a b) a.\n  compute. exists (fun (t : a * b) => True). intros.\n  exact (fst x).\nDefined.\n\nDefinition  par_Pi_2p (a b : Par_isRC) : Hom (par_p_prod a b) b.\n  compute. exists (fun (t : a * b) => True). intros.\n  exact (snd x).\nDefined.\n\nDefinition  par_Pi_1Tot_prop (a b : Par_isRC) : Prop.\n  destruct Par_isRC. destruct RCat_RC. exact (rc (par_p_prod a b) a (par_Pi_1p a b) = id (par_p_prod a b)).\nDefined.\n\nDefinition  par_Pi_1Tot (a b : Par_isRC) : par_Pi_1Tot_prop a b.\n  compute. apply par_eqv_def. compute. split; try split; try intros; try intros; try auto.\nDefined. \n\nDefinition  par_Pi_2Tot_prop (a b : Par_isRC) : Prop.\n  destruct Par_isRC. destruct RCat_RC. exact (rc (par_p_prod a b) b (par_Pi_2p a b) = id (par_p_prod a b)).\nDefined.\n\nDefinition  par_Pi_2Tot (a b : Par_isRC) : par_Pi_2Tot_prop a b.\n  compute. apply par_eqv_def. compute. split; try split; try intros; try intros; try auto.\nDefined. \n\nDefinition  par_pProd_morph_ex (a b : Par_isRC) : ∀ (p' : Par_isRC) (r1 : Hom p' a) (r2 : Hom p' b), Hom p' (par_p_prod a b) .\n  compute. intros. destruct r1 as [r1]; destruct r2 as [r2].\n  exists (fun (t : p') => (r1 t) /\\ (r2 t)).\n  intros. destruct H. exact ((a0 x H, b0 x H0)).\nDefined.\n\nDefinition  par_pProd_morph_rest_prop (a b : Par_isRC) : Prop.\n  destruct Par_isRC. destruct RCat_RC. exact (∀ (p' : Par_isRC) (r1 : Hom p' a) (r2 : Hom p' b), \n    (rc p' a r1)∘(rc p' b r2) = rc p' (par_p_prod a b) (par_pProd_morph_ex a b p' r1 r2)).\nDefined. \n\nDefinition  par_pProd_morph_rest (a b : Par_isRC) : par_pProd_morph_rest_prop a b.\n  compute. intros. apply par_eqv_def. compute. destruct r1 as [r1]; destruct r2 as [r2].\n  split; intros; try split; try intros; try split; try destruct H; try auto.\n  destruct pf. auto.\nDefined.\n\nDefinition  par_pProd_morph_com_1 (a b : Par_isRC) : ∀ (p' : Par_isRC) (r1 : Hom p' a) (r2 : Hom p' b), lt_eq p' a ((par_Pi_1p a b) ∘ (par_pProd_morph_ex a b p' r1 r2))  r1.\n  compute. intros. apply par_eqv_def. compute. destruct r1 as [r1]; destruct r2 as [r2].\n  intros; try intros; try split; try intros ; try split; try intros; \n  try destruct H as [h1 h2];  try split; try intros; try split; try split; try (exact (h2 h1));\n  try destruct h1 as [h11 h12]; try destruct h11 as [h111 h112]; try destruct h12 as [h112 h122]; try auto.\n  destruct pf. destruct pf1. destruct a2. destruct a1. rewrite (pf_ir (r1 z) (r (conj a1 t0)) r0). auto.\nDefined.\n\nDefinition  par_pProd_morph_com_2 (a b : Par_isRC) : ∀ (p' : Par_isRC) (r1 : Hom p' a) (r2 : Hom p' b), lt_eq p' b ((par_Pi_2p a b) ∘ (par_pProd_morph_ex a b p' r1 r2))  r2.\n  compute. intros. apply par_eqv_def. compute. destruct r1 as [r1]; destruct r2 as [r2].\n  intros; try intros; try split; try intros ; try split; try intros; \n  try destruct H as [h1 h2];  try split; try intros; try split; try split; try (exact (h2 h1));\n  try destruct h1 as [h11 h12]; try destruct h11 as [h111 h112]; try destruct h12 as [h112 h122]; try auto.\n  destruct pf. destruct pf1. destruct a2. destruct a1. rewrite (pf_ir (r2 z) (r (conj a1 t0)) r3). auto.\nDefined.\n\nDefinition  par_pProd_morph_unique_prop (a b : Par_isRC) : Prop.\n    destruct Par_isRC. destruct RCat_RC. \n    exact (∀ (p' : Par_isRC) (r1 : Hom p' a) (r2 : Hom p' b) (pm : Hom p' (par_p_prod a b)),\n     (lt_eq p' a ((par_Pi_1p a b) ∘ pm)  r1) -> (lt_eq p' b ((par_Pi_2p a b) ∘ pm)  r2)\n       -> ((rc p' a r1)∘(rc p' b r2) = rc p' (par_p_prod a b) pm) -> pm = par_pProd_morph_ex a b p' r1 r2).\nDefined.\n\nDefinition  par_pProd_morph_unique (a b : Par_isRC) : par_pProd_morph_unique_prop a b.\n  unfold par_pProd_morph_unique_prop. simpl. \n  intros. apply par_eqv_def. compute.\n  destruct r1 as [r1]; destruct r2 as [r2]. destruct pm.\n  split; try intros; try split; try intros; try split;\n\n  simpl in H1; simpl in H0; simpl in H;\n  inversion H1. rewrite <- H4 in H2;\n  destruct H2; exact (H3 H2).\n  rewrite <- H4 in H2; destruct H2; try auto.\n  destruct H2. split. auto. intro; auto.\n  destruct pf1. compute in p.\n  assert (H_f1 : (x z ∧ (x z → True)) ∧ (x z ∧ (x z → True) → r1 z)).\n  split; try intros; try split; try intros; try split; try auto.\n  assert (H_f2 : x z ∧ (x z → True)).\n  split; try intros; try auto.\n  generalize (rel_equiv _ _ _ _ H z H_f1 H_f2).\n  assert (H_s1 : (x z ∧ (x z → True)) ∧ (x z ∧ (x z → True) → r2 z)).\n  split; try intros; try split; try intros; try split; try auto.\n  assert (H_s2 : x z ∧ (x z → True)).\n  split; try intros; try auto.\n  generalize (rel_equiv _ _ _ _ H0 z H_s1 H_s2).\n  compute. destruct H_f1; destruct H_f2; destruct H_s1; destruct H_s2.\n  replace (r4 a2) with r0; try (apply pf_ir). replace (r3 a1) with r; try (apply pf_ir). \n  replace x1 with pf; try (apply pf_ir). replace x0 with pf; try (apply pf_ir).\n  destruct (p z pf). intros. rewrite H3. rewrite H6. auto.\nDefined.\n\n(* instantiate terminal object in Par *)\nDefinition PPTerm : @ParTerm Par_isRC rc_Par Par_isRC.\n  exists par_p_term par_pt_morph.\n  exact par_morph_total. exact par_id_is_ptm. exact par_pt_morph_unique_greatest.\nDefined.\n\n(* instantiate partial products in Par *)\nDefinition PPProds : @Has_pProducts Par_isRC rc_Par Par_isRC.\n  compute. intros. exists (par_p_prod a b) (par_Pi_1p a b)  (par_Pi_2p a b) (par_pProd_morph_ex a b).\n  exact (par_Pi_1Tot a b). exact (par_Pi_2Tot a b).\n  exact (par_pProd_morph_rest a b).\n  exact (par_pProd_morph_com_1 a b). exact (par_pProd_morph_com_2 a b).\n  exact (par_pProd_morph_unique a b).\nDefined.\n\nInstance Par_isCRC : CartRestrictionCat rc_Par .\n  exists. exact PPTerm. exact PPProds. \nDefined.\n\n\n(* map from objects in Set to objects in Tot(Par) *)\nDefinition Fo : Set_Cat -> Tot rc_Par Par_isRC.\n  compute. intros. exists X. auto.\nDefined. \n\n(* map from arrows in Set to arrows in Tot(Par) *)\nDefinition Fm : ∀ (a b : Set_Cat), Hom Set_Cat a b → Hom (Tot rc_Par Par_isRC) (Fo a) (Fo b).\n  intros. compute.\n  exists (existT (λ P : a → Prop, ∀ x : a, P x → b) \n  (λ _ : a, True) (λ (x : a) (_ : True), H x)). tauto.\nDefined.\n\n(* map from objects in Tot(Par) to objects in Set *)\nDefinition Fo' : Tot rc_Par Par_isRC -> Set_Cat.\n  compute. intros. destruct X. exact x.\nDefined. \n\n(* map from arrows in Tot(Par) to arrows in Set *)\nDefinition Fm' : ∀ (a b : (Tot rc_Par Par_isRC)), Hom (Tot rc_Par Par_isRC) a b -> Hom Set_Cat (Fo' a) (Fo' b).\n  intros a b f. compute. destruct f as [fp f]. destruct a as [a]; destruct b as [b].\n  destruct fp. compute in p. compute in f. intro x0. compute in x. \n  assert (pf : x x0). \n  inversion f. auto.\n  exact (p x0 pf).\nDefined.\n\n(* auxiliary results about equality between existential and sigma types *)\nLemma sig_eq : forall (a b : (Tot rc_Par Par_isRC)), forall (f g : Hom (Tot rc_Par Par_isRC) a b),\n  (proj1_sig f = proj1_sig g)  -> f = g.\nProof.\n  intros; destruct f; destruct g. compute in H. replace x with x0.\n  compute in x. destruct x. compute in x0; destruct x0. compute. inversion H.\n  destruct a; destruct b.\n  compute in t; compute in t0. eauto. \nDefined.\n\n(* lemma for rewriting of terms of type exist P p x *)\nLemma exist_eq : forall (U:Type) (P:U -> Prop) (p q:U) (x:P p) (y:P q), p = q ->\n    exist P p x = exist P q y.\nProof.\n  intros. apply eq_dep_eq_sig . generalize x. \n  replace (∀ x0 : P p, eq_dep U P p x0 q y) with (∀ x0 : P q, eq_dep U P q x0 q y).\n  intros. rewrite (pf_ir (P q) x0 y). auto. rewrite H. auto.\nDefined.\n\n(* define functor from Set to Tot(Par) *)\nDefinition TotPar_Set_Cat_Eqv_f : Functor Set_Cat (Tot rc_Par Par_isRC). \nProof.\n  unfold Set_Cat. unfold Par_isRC. unfold rc_Par.\n  exists Fo Fm. intros. unfold id. compute. \n  apply (sig_eq (Fo c) (Fo c) _ _ ).\n  compute. auto.\n  intros. compute.\n  apply (sig_eq (Fo a) (Fo c) _ _ ). \n  compute. apply par_eqv_def. compute.\n  split; try intros;  try auto. destruct pf1. auto.\nDefined.\n\n(* define functor from Tot(Par) to Set *)\nDefinition TotPar_Set_Cat_Eqv_b : Functor (Tot rc_Par Par_isRC) Set_Cat .\n  exists Fo' Fm'. intros. unfold id. \n  destruct c. compute. auto.\n  intros. \n  destruct a; destruct b; destruct c. \n  destruct f; destruct g. compute in x.\n  destruct x3; destruct x2. \n  compute in p. compute in x2. compute in t2.\n  compute in x3. compute in p0.\n  compute in t3.\n  inversion t2. inversion t3. \n  unfold compose. \n  apply functional_extensionality. intro. \n  simpl. compute in x4. assert (x2 x4). rewrite H0. auto.\n  rewrite (pf_ir (x2 x4) _ H). \n  assert (x3 (p0 x4 H)). rewrite H2. auto.\n  rewrite (pf_ir (x3 (p0 x4 H)) _ H4).\n  unfold rc_ParMap. compute. \n  assert (H5' : existT (λ P : x → Prop, ∀ x5 : x, P x5 → x) \n             (λ z : x, x2 z ∧ (∀ p1 : x2 z, x3 (p0 z p1)))\n             (λ (x5 : x) (_ : x2 x5 ∧ (∀ p1 : x2 x5, x3 (p0 x5 p1))), x5) =\n           existT (λ P : x → Prop, ∀ x5 : x, P x5 → x) (λ _ : x, True) (λ (x5 : x) (_ : True), x5)).\n  rewrite H2. rewrite H0. apply par_eqv_def. compute. tauto. \n  assert (H6' : existT \n                 (λ x5 : x → Prop, ∀ x6 : x, x5 x6 → x) \n                 (λ _ : x, True) \n                 (λ (x5 : x) (_ : True), x5) =\n               existT \n                 (λ x5 : x → Prop, ∀ x6 : x, x5 x6 → x) \n                 (λ _ : x, True) \n                 (λ (x5 : x) (_ : True), x5)). auto.\n  rewrite (pf_ir (existT (λ P : x → Prop, ∀ x5 : x, P x5 → x) \n             (λ z : x, x2 z ∧ (∀ p1 : x2 z, x3 (p0 z p1)))\n             (λ (x5 : x) (_ : x2 x5 ∧ (∀ p1 : x2 x5, x3 (p0 x5 p1))), x5) =\n           existT (λ P : x → Prop, ∀ x5 : x, P x5 → x) (λ _ : x, True) (λ (x5 : x) (_ : True), x5)) _ H5').\n  inversion H5'.\n\n  assert (existT (λ P : x → Prop, ∀ x5 : x, P x5 → x) (λ _ : x, True) (λ (x5 : x) (_ : True), x5) =\n       existT (λ P : x → Prop, ∀ x5 : x, P x5 → x) (λ _ : x, True) (λ (x5 : x) (_ : True), x5)\n       → x2 x4 ∧ (∀ p1 : x2 x4, x3 (p0 x4 p1))) . \n  intro. split. auto. intro. replace p1 with H. auto. apply pf_ir.\n  assert (existT (λ x5 : x → Prop, ∀ x6 : x, x5 x6 → x)\n                 (λ _ : x, True) \n                 (λ (x5 : x) (_ : True), x5) =\n               existT (λ x5 : x → Prop, ∀ x6 : x, x5 x6 → x)\n                 (λ _ : x, True) \n                 (λ (x5 : x) (_ : True), x5)). auto.\n  replace _ with (H5 H8). destruct (H5 H8). replace x5 with H. replace (x6 H) with H4.\n  auto. apply pf_ir. apply pf_ir. apply pf_ir.\nDefined.\n\n\n(* show that composing the above functors Tot(Par) -> Set -> Tot(Par) gives the identity functor on Tot(Par)\n  by showing it's equal to the identity func on objects *)\nLemma TotPar_Set_Cat_Eqv_o : forall a ,\n @FO (Tot rc_Par Par_isRC) (Tot rc_Par Par_isRC)\n  (Functor_compose  TotPar_Set_Cat_Eqv_b TotPar_Set_Cat_Eqv_f) a = @FO (Tot rc_Par Par_isRC) (Tot rc_Par Par_isRC) (Functor_id _) a.\ncompute. intros. destruct a.  auto.\nDefined.\n\n(* show that composing the above functors Tot(Par) -> Set -> Tot(Par) gives the identity functor on Tot(Par)\n  by showing it's equal to the identity func on maps *)\nDefinition TotPar_Set_Cat_Eqv_m (a b : (Tot rc_Par Par_isRC)) (f : @Hom  (Tot rc_Par Par_isRC) a b) (x : (proj1_sig a)) :\n (@FA (Tot rc_Par Par_isRC) (Tot rc_Par Par_isRC) (Functor_id _) _ _ f = \n    (@FA (Tot rc_Par Par_isRC) (Tot rc_Par Par_isRC) (Functor_compose  TotPar_Set_Cat_Eqv_b TotPar_Set_Cat_Eqv_f) _ _ f)).\ndestruct f as [f]. destruct a as [a]. destruct b as [b]. compute.\napply exist_eq. compute in f. destruct f as [pf f].\napply par_eqv_def. simpl. split. compute in t. inversion t. \nintros. split; auto. intros. compute.\nassert (forall (pff : (pf z)), f z pf0 = f z pff).\nintros. rewrite (pf_ir (pf z) pf0 pff). auto. apply H0.\nDefined.\n\n(* show that composing the above functors Set -> Tot(Par) -> Set gives the identity functor on Set \n    by showing it's equal to the identity func on objects *)\nLemma Set_TotPar_Cat_Eqv_o : forall a ,\n @FO Set_Cat Set_Cat\n  (Functor_compose  TotPar_Set_Cat_Eqv_f TotPar_Set_Cat_Eqv_b) a = @FO Set_Cat Set_Cat (Functor_id _) a.\ncompute.  auto.\nDefined.\n\n(* show that composing the above functors Set -> Tot(Par) -> Set gives the identity functor on Set \n    by showing it's equal to the identity func on maps *)\nDefinition Set_TotPar_Cat_Eqv_m (a b : Set_Cat) (f : @Hom Set_Cat a b) (x : a) :\n (@FA Set_Cat Set_Cat (Functor_id _) _ _ f = \n    (@FA Set_Cat Set_Cat (Functor_compose  TotPar_Set_Cat_Eqv_f TotPar_Set_Cat_Eqv_b ) _ _ f)).\ncompute. apply functional_extensionality. intro. auto.\nDefined.\n\n\n(* define the range combinator mapping in a cartesian restriction category *)\nDefinition rrc : rrcType Par_isRC.\n  unfold rrcType. intros. destruct X as [fp f]. compute.\n  exists (fun (y : b) => (exists x : a, exists p : (fp x), f x p = y)).\n  intros. exact x.\nDefined.\n\n(* define an instance of the RangeComp type class for Par_isCRC *)\nDefinition rrc_Par :  @RangeComb Par_isCRC rc_Par Par_isCRC.\n  exists rrc; intros; destruct f; apply par_eqv_def; try destruct g;  compute  ;\n  try split; try intros; try split; \n  try split; try intros; try split; try auto; try destruct H; try auto.\n  exists z. exists p. auto. destruct pf.\n  rewrite (pf_ir _ x0 pf1); auto.\n  exists x1. destruct H. destruct x2. exists x2. auto.\n  destruct H. destruct x2. generalize (x3 x2). intro.\n  rewrite H in H0. auto. \n  destruct H as [x' p]. destruct p as [p e].\n  exists x'. assert (x x' ∧ (∀ p0 : x x', x0 (b0 x' p0))).\n  split. exact p. intro. rewrite (pf_ir _ p p0) in e.\n  rewrite e.\n  assert ((∃ (x0 : a) (p : x x0), b0 x0 p = z)).\n  exists x'. exists p. rewrite (pf_ir _ p p0). auto.\n  exact (H0 H). exists H. destruct H. \n  rewrite (pf_ir _ x1 p); auto.\n  destruct pf1. auto.\n  destruct H. destruct x2. destruct e. \n  exists x3.  assert (x x3 ∧ (∀ p : x x3, x0 (b0 x3 p))).\n  split. destruct e. exact x4. intros.\n  destruct e. rewrite (pf_ir _ p x4). rewrite e.\n  apply x2. exists x3. exists x4. auto.\n  exists H0. destruct H0. \n  destruct e. rewrite (pf_ir _ x4 x6).\n  elim H. rewrite (same_app _ _ _ c0 c0 (b0 x3 x6) x1 eq_refl e (x5 x6) (x2\n     (ex_intro (λ x7 : a, ∃ p : x x7, b0 x7 p = x1) x3\n        (ex_intro (λ p : x x3, b0 x3 p = x1) x6 e)))). auto.\n  destruct H. destruct x2.\n  exists (b0 x1 x2).\n  assert ((∃ (x4 : a) (p : x x4), b0 x4 p = b0 x1 x2) ∧ ((∃ (x4 : a) (p : x x4), b0 x4 p = b0 x1 x2) → x0 (b0 x1 x2))).\n  split.  exists x1. exists x2. auto.\n  intro. exact (x3 x2). exists H0.\n  destruct H0. rewrite <- H.\n  rewrite (pf_ir _ (x4 e) (x3 x2)). auto. \nDefined.\n\n(* define an instance of Par as a range category *)\nDefinition Par_isRangeC : RangeCat Par_isCRC rc_Par Par_isCRC rrc_Par.\nexists. Defined.\n\n(* prove the Beck Chevalley condition in Par *)\nDefinition Par_BCC : @sat_Beck_Chevalley Par_isCRC rc_Par Par_isCRC Par_isCRC rrc_Par Par_isRangeC .\nunfold sat_Beck_Chevalley. \nunfold Beck_Chevalley. intros.\napply par_eqv_def. unfold HomParEqv. simpl.\nunfold rrc. destruct f as [pf f]. destruct g as [pg g].\nsimpl. split; try intros; try split; try intros; try split; try split; try auto; try intros;\ntry (destruct H). destruct z as [y1 y1']. destruct x0 as  [x1 x1']; destruct H; compute.\ncompute in H; destruct x0. destruct a;  destruct a0; compute in H.\nexists x1. exists (p0 t).\nassert (fst (f x1 (p0 t), g x1' (p1 t0)) = fst (y1, y1')).\nrewrite H. auto. compute in H0. auto.\ndestruct z as [y1 y1']. destruct x0 as  [x1 x1']; destruct H; compute.\ncompute in H; destruct x0. destruct a;  destruct a0; compute in H.\nassert (snd (f x1 (p0 t), g x1' (p1 t0)) = snd (y1, y1')).\nrewrite H. auto. compute in H0. exists x1'. exists (p1 t0). auto.\ndestruct z as [y1 y1']. unfold par_p_prod.  destruct H; compute.\ndestruct H0. destruct (H1 I). destruct (H2 I).\ndestruct H3; destruct H4. exists ( x0 , x1).\nassert (p : (True ∧ (True → pf (let (fst, _) := (x0, x1) in fst)))\n    ∧ True ∧ (True → pg (let (_, snd) := (x0, x1) in snd))).\nsplit; try split; try auto. exists p. destruct p. destruct a. destruct a0.\ncompute in H3. compute in H4. \nrewrite <- H3. rewrite <- H4. assert (p t= x2). apply pf_ir; auto.\nassert (p0 t0 = x3). apply pf_ir; auto. rewrite H5; rewrite H6; auto.\ndestruct z as [z1 z2]. destruct H. destruct pf1.\ndestruct a. destruct a0. compute. auto. \nDefined.\n\n(* define an instance of Par as a cartesian range category *)\nInstance Par_isCRRC : CartRangeCat Par_isCRC rc_Par Par_isCRC Par_isCRC rrc_Par Par_isRangeC.\nexists.\nexact Par_BCC.\nDefined.\n", "meta": {"author": "polinavino", "repo": "Turing-Category-Formalization", "sha": "61020a96ec4f40199b2ddfb18e4f117fe8410703", "save_path": "github-repos/coq/polinavino-Turing-Category-Formalization", "path": "github-repos/coq/polinavino-Turing-Category-Formalization/Turing-Category-Formalization-61020a96ec4f40199b2ddfb18e4f117fe8410703/Par_Cat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4765796510636759, "lm_q1q2_score": 0.2531635778042187}}
{"text": "(* Computational definition and declarative spec for closure conversion. Part of the CertiCoq project.\n * Author: Zoe Paraskevopoulou, 2016\n *)\n\nFrom SFS Require Import cps cps_util set_util identifiers ctx\n     Ensembles_util List_util functions.\n\nFrom Coq Require Import ZArith.Znumtheory\n     Lists.List MSets.MSets MSets.MSetRBT Numbers.BinNums\n     NArith.BinNat PArith.BinPos Sets.Ensembles Strings.String.\n\nFrom ExtLib Require Import Structures.Monads Data.Monads.StateMonad.\nFrom Template Require Import BasicAst. (* For identifier names *)\n\nImport ListNotations Nnat MonadNotation.\n\nFrom SFS Require Import Coqlib Maps. \n\nOpen Scope monad_scope.\nOpen Scope ctx_scope.\nOpen Scope fun_scope.\nOpen Scope string.\n\n(** * Closure conversion as a relation  *)\n\nSection CC.\n\n  Variable (clo_tag : cTag). (* Tag for closure records *)\n\n\n  (* The free-variable set of a source program *)\n  Definition FV (Scope : Ensemble var) (Funs : Ensemble var) (FVs : list var) :=\n    Scope :|: (Funs \\\\ Scope) :|: (FromList FVs \\\\ (Scope :|: Funs)).\n  \n  (* The free-variable set of a closure converted *)\n  Definition FV_cc (Scope : Ensemble var) (Funs : Ensemble var) (γ : var  -> var) (Γ : var) :=\n    Scope :|: (Funs \\\\ Scope) :|: image γ (Funs \\\\ Scope) :|: [set Γ].\n\n  (* Closure application *)\n  Definition AppClo f t xs f' Γ :=\n    Eproj f' clo_tag 0%N f\n          (Eproj Γ clo_tag 1%N f\n                 (Eapp f' t (Γ :: xs))).\n  \n  Inductive project_var :\n    Ensemble var -> (* Variables in the current scope *)\n    Ensemble var -> (* Functions not yet constructed *)\n    (var -> var) -> (* function mapping functions to environments *)\n    cTag -> (* tag of the current environment constructor *)\n    var -> (* Current environment *)\n    list var -> (* The environment *)\n    var -> (* Before projection *)\n    exp_ctx -> (* Context that will perform the projection *)\n    Ensemble var -> (* New current scope *)\n    Ensemble var -> (* New funs *)\n    Prop :=\n  | Var_in_Scope :\n      forall Scope Funs fenv c FVs x Γ,\n        x \\in Scope ->\n        project_var Scope Funs fenv c Γ FVs x Hole_c Scope Funs\n  | Var_in_Funs :\n      forall Scope Funs fenv c FVs f Γ,\n        ~ f \\in Scope ->\n        f \\in Funs ->\n        (* adds the function in scope so that it's not constructed again *)\n        project_var Scope Funs fenv c Γ FVs f\n                    (Econstr_c f clo_tag [f ; (fenv f)] Hole_c) (f |: Scope) (Funs \\\\ [set f])\n  | Var_in_FVs :\n      forall Scope Funs fenv c FVs x N Γ,\n        ~ x \\in Scope ->\n        ~ x \\in Funs ->\n        nthN FVs N = Some x ->\n        (* adds the var in scope so that it's not projected again *)\n        project_var Scope Funs fenv c Γ FVs x\n                    (Eproj_c x c N Γ Hole_c) (x |: Scope) Funs.\n  \n  Inductive project_vars :\n    Ensemble var -> (* Variables in the current scope *)\n    Ensemble var -> (* Functions not yet constructed *)\n    (var -> var) -> (* function mapping functions to environments *)\n    cTag -> (* tag of the current environment constructor *)\n    var -> (* The environment argument *)\n    list var -> (* The free variables *)\n    list var -> (* Before projection *)\n    exp_ctx -> (* Context that will perform the projection *)\n    Ensemble var -> (* New current scope *)\n    Ensemble var -> (* Funs *)\n    Prop :=\n  | VarsNil :\n      forall Scope Funs fenv c Γ FVs,\n        project_vars Scope Funs fenv c Γ FVs [] Hole_c Scope Funs\n  | VarsCons :\n      forall Scope1 Scope2 Scope3 Funs1 Funs2 Funs3 fenv c Γ FVs y ys C1 C2,\n        project_var Scope1 Funs1 fenv c Γ FVs y C1 Scope2 Funs2 ->\n        project_vars Scope2 Funs2 fenv c Γ FVs ys C2 Scope3 Funs3  ->\n        project_vars Scope1 Funs1 fenv c Γ FVs (y :: ys) (comp_ctx_f C1 C2) Scope3 Funs3.\n\n  Definition extend_fundefs' (f : var -> var) (B : fundefs) (x : var) : var -> var :=\n    fun y => if (@Dec _ (name_in_fundefs B) _) y then x else f y.\n\n\n  Inductive Closure_conversion :\n    Ensemble var -> (* Variables in the current scope *)\n    Ensemble var -> (* Functions that are not yet constructed *)\n    (var -> var) -> (* function mapping functions to environments *)\n    cTag -> (* tag of the current environment constructor *)\n    var -> (* The environment argument *)\n    list var -> (* The free variables - need to be ordered *)\n    exp -> (* Before cc *)\n    exp -> (* After cc *)\n    exp_ctx -> (* The context that the output expression should be put in *)\n    Prop :=\n  | CC_Econstr :\n      forall Scope Scope' Funs Funs' fenv c Γ FVs x ys C C' t e e',\n        project_vars Scope Funs fenv c Γ FVs ys C Scope' Funs' ->\n        Closure_conversion (x |: Scope') Funs' fenv c Γ FVs e e' C' ->\n        Closure_conversion Scope Funs fenv c Γ FVs (Econstr x t ys e) \n                           (Econstr x t ys (C' |[ e' ]|)) C\n  | CC_Ecase :\n      forall Scope Scope' Funs Funs' fenv c Γ FVs x C pats pats',\n        project_var Scope Funs fenv c Γ FVs x C Scope' Funs' ->\n        Forall2 (fun (pat pat' : cTag * exp) =>\n                   (fst pat) = (fst pat') /\\\n                   exists C' e',\n                     snd pat' = C' |[ e' ]| /\\\n                     Closure_conversion Scope' Funs' fenv c Γ FVs (snd pat) e' C')\n                pats pats' ->\n        Closure_conversion Scope Funs fenv c Γ FVs (Ecase x pats) (Ecase x pats') C\n  | CC_Eproj :\n      forall Scope Scope' Funs Funs' fenv c Γ FVs x y C C' t N e e',\n        project_var Scope Funs fenv c Γ FVs y C Scope' Funs' ->\n        Closure_conversion (x |: Scope') Funs' fenv c Γ FVs e e' C' ->\n        Closure_conversion Scope Funs fenv c Γ FVs (Eproj x t N y e)\n                           (Eproj x t N y (C' |[ e' ]|)) C\n  | CC_Efun :\n      forall Scope Scope' Funs Funs' fenv c Γ c' Γ' FVs FVs' B B' e e' C Ce,\n        (* The environment contains all the variables that are free in B *)\n        (occurs_free_fundefs B) <--> (FromList FVs') ->\n        (* needed for cost preservation *)\n        NoDup FVs' ->\n        project_vars Scope Funs fenv c Γ FVs FVs' C Scope' Funs' ->\n        (* Γ' is the variable that will hold the record of the environment *)\n        ~ Γ' \\in (bound_var (Efun B e) :|: FromList FVs' :|: FV Scope Funs FVs :|:\n                  FV_cc Scope Funs fenv Γ) ->\n        (* closure convert function blocks *)\n        Closure_conversion_fundefs B c' FVs' B B' ->\n        (* closure convert the rest of the program *)\n        Closure_conversion (Scope' \\\\ name_in_fundefs B)\n                           ((name_in_fundefs B) :|: Funs') (extend_fundefs' fenv B Γ') c Γ FVs e e' Ce  ->\n        Closure_conversion Scope Funs fenv c Γ FVs (Efun B e)\n                           (Efun B' (Ce |[ e' ]|)) (comp_ctx_f C (Econstr_c Γ' c' FVs' Hole_c))\n  | CC_Eapp :\n      forall Scope Scope' Funs Funs' fenv c Γ FVs f f' ft env' ys C S,\n        Disjoint _ S (FV_cc Scope' Funs' fenv Γ) ->\n        (* Project the function name and the actual parameter *)\n        project_vars Scope Funs fenv c Γ FVs (f :: ys) C Scope' Funs' ->\n        (* The name of the function pointer and the name of the environment\n         should not shadow the variables in the current scope and the\n         variables that where used in the projections *)\n        f' \\in S -> env' \\in S -> f' <> env' ->\n        Closure_conversion Scope Funs fenv c Γ FVs (Eapp f ft ys) (AppClo f ft ys f' env') C\n  | CC_Eprim :\n      forall Scope Scope' Funs Funs' fenv c Γ FVs x ys C C' f e e',\n        project_vars Scope Funs fenv c Γ FVs ys C Scope' Funs' ->\n        Closure_conversion (x |: Scope') Funs' fenv c Γ FVs e e' C' ->\n        Closure_conversion Scope Funs fenv c Γ FVs (Eprim x f ys e)\n                           (Eprim x f ys (C' |[ e' ]|)) C\n  | CC_Ehalt :\n      forall Scope Scope' Funs Funs' fenv c Γ FVs x C,\n        (* Project the function name and the actual parameter *)\n        project_var Scope Funs fenv c Γ FVs x C Scope' Funs' ->\n        Closure_conversion Scope Funs fenv c Γ FVs (Ehalt x) (Ehalt x) C\n  with Closure_conversion_fundefs :\n         fundefs -> (* The current block. Needed to make closures upon entry. *)\n         cTag -> (* tag of the current environment constructor *)\n         list var -> (* The environment *)\n         fundefs -> (* Before cc *)\n         fundefs -> (* After cc *)\n         Prop :=\n       | CC_Fccons :\n           forall B c Γ' FVs S f t ys e e' C defs defs',\n             (* The environment binding should not shadow the current scope\n               (i.e. the names of the mut. rec. functions and the other arguments) *)\n             Disjoint _ S ((name_in_fundefs B) :|: (FromList ys) :|: (bound_var e) :|: FromList FVs) ->\n             (* new argument *)\n             In _ S  Γ' ->\n             Closure_conversion_fundefs B c FVs defs defs' ->\n             Closure_conversion (FromList ys) (name_in_fundefs B) (extend_fundefs' id B Γ')\n                                c Γ' FVs e e' C ->\n             Closure_conversion_fundefs B c FVs (Fcons f t ys e defs )\n                                        (Fcons f t (Γ' :: ys) (C |[ e' ]|) defs')\n       | CC_Fnil :\n           forall B c FVs,\n             Closure_conversion_fundefs B c FVs Fnil Fnil.\n  \n\n  (** * Computational definition of closure conversion *)\n  \n  Inductive VarInfo : Type :=\n  (* A free variable, i.e. a variable outside the scope of the current function.\n   The argument is position of a free variable in the env record *)\n  | FVar : N -> VarInfo\n  (* A function defined in the current block of function definitions. The first\n   argument is the closure environment  *)\n  | MRFun : var -> VarInfo\n  (* A variable declared in the scope of the current function *)\n  | BoundVar : VarInfo.\n  \n  (* Maps variables to [VarInfo] *)\n  Definition VarInfoMap := M.t VarInfo.\n\n  Record state_contents :=\n    mkSt { var_map : VarInfoMap ; \n           next_var : var ; (* next fresh name *)\n           nect_cTag : cTag ; (* next unique tag for closures *)\n           next_iTag : iTag; cenv : cEnv;\n           name_env : M.t BasicAst.name }.\n  \n  (** The state is the next available free variable, cTag and iTag and the tag environment *)\n  Definition ccstate :=\n    state state_contents.\n\n  Definition get_var_entry (x : var) : ccstate (option VarInfo)  :=\n    p <- get ;;\n    let '(mkSt vm n c i e names) := p in\n    match vm ! x with\n      | Some info => ret (Some info)\n      | None => ret None\n    end.\n\n  Definition set_var_entry (x : var) (info : VarInfo) : ccstate unit :=\n    p <- get ;;\n    let '(mkSt vm n c i e names) := p in\n    put (mkSt (M.set x info vm) n c i e names) ;;\n    ret tt.\n\n  (** Get a the name entry of a variable *)\n  Definition get_name_entry (x : var) : ccstate BasicAst.name :=\n    p <- get ;;\n    let '(mkSt vm n c i e names) := p in\n    match names ! x with\n      | Some name => ret name\n      | None => ret nAnon\n    end.\n\n  (** Set a the name entry of a variable *)\n  Definition set_name_entry (x : var) (name : BasicAst.name) : ccstate unit :=\n    p <- get ;;\n    let '(mkSt vm n c i e names) := p in\n    put (mkSt vm n c i e (M.set x name names)) ;;\n    ret tt.\n\n  Definition pop_var_map (t : unit) : ccstate VarInfoMap :=\n    p <- get ;;\n    let '(mkSt vm n c i e names) := p in\n    put (mkSt (M.empty VarInfo) n c i e names) ;;\n    ret vm.\n\n  Definition peak_var_map (t : unit) : ccstate VarInfoMap :=\n    p <- get ;;\n    let '(mkSt vm n c i e names) := p in\n    ret vm.\n\n  Definition push_var_map (map : VarInfoMap) : ccstate unit :=\n    p <- get ;;\n    let '(mkSt vm n c i e names) := p in\n    put (mkSt map n c i e names) ;;\n    ret tt.\n  \n\n  (* (** Add name *) *)\n  Definition add_name (fresh : var) (name : string): ccstate unit :=\n    set_name_entry fresh (nNamed name).\n\n  (** Add_name as suffix *)\n  Definition add_name_suff (fresh old : var) (suff : string) :=\n    oldn <- get_name_entry old ;;\n    match oldn with\n      | nNamed s =>\n        set_name_entry fresh (nNamed (append s suff))\n      | nAnon =>\n        set_name_entry fresh (nNamed (append \"anon\" suff))\n    end.\n\n  (** Commonly used suffixes *)\n  Definition clo_env_suffix := \"_env\".\n  Definition clo_suffix := \"_clo\".\n  Definition code_suffix := \"_code\".\n  Definition proj_suffix := \"_proj\".\n\n\n  (** Get a fresh name, and create a pretty name *)\n  Definition get_name (old_var : var) (suff : string) : ccstate var :=\n    p <- get ;;\n    let '(mkSt vm n c i e names) := p in\n    put (mkSt vm ((n+1)%positive) c i e names) ;;\n    add_name_suff n old_var suff ;;\n    ret n.\n\n  (** Get a fresh name, and create a pretty name *)\n  Definition get_name_no_suff (name : string) : ccstate var :=\n    p <- get ;;\n    let '(mkSt vm n c i e names) := p in\n    put (mkSt vm ((n+1)%positive) c i e names) ;;\n    add_name n name ;;\n    ret n.\n\n  \n  Definition make_record_cTag (n : N) : ccstate cTag :=\n    p <- get ;;\n    let '(mkSt vm x c i e names) := p  in\n    let inf := (nAnon, nAnon, i, n, 0%N) : cTyInfo in\n    let e' := ((M.set c inf e) : cEnv) in\n    put (mkSt vm x (c+1)%positive (i+1)%positive e' names) ;;\n    ret c.\n\n  (** Looks up a variable in the map and handles it appropriately *) \n  Definition get_var (x : var) (c : cTag) (Γ : var): ccstate exp_ctx :=\n    info <- get_var_entry x ;;\n    match info with\n      | Some entry =>\n        match entry with\n        | FVar pos =>\n          set_var_entry x BoundVar ;; \n          ret (Eproj_c x c pos Γ Hole_c) \n        | MRFun env_ptr  =>\n          set_var_entry x BoundVar ;; \n          ret (Econstr_c x clo_tag [x; env_ptr] Hole_c)\n        | BoundVar => ret Hole_c\n        end\n      | None => ret Hole_c (* should never reach here *)\n    end.\n   \n  Fixpoint get_vars (xs : list var) (c : cTag) (Γ : var) : ccstate exp_ctx :=\n    match xs with\n      | [] => ret Hole_c\n      | x :: xs =>\n        C1 <- get_var x c Γ ;;\n        C2 <- get_vars xs c Γ ;; \n        ret (comp_ctx_f C1 C2)\n    end.\n\n  (** Add some bound variables in the map *)\n  Fixpoint add_params args : ccstate unit :=\n    match args with\n      | [] => ret tt\n      | x :: xs =>\n        set_var_entry x BoundVar ;;\n        add_params xs\n    end.\n  \n  (** Add the free variables in the map *)\n  Fixpoint add_fvs xs n : ccstate unit :=\n    match xs with\n      | [] => ret tt\n      | x :: xs =>\n        set_var_entry x (FVar n) ;;\n        add_fvs xs (n + 1)%N\n    end.\n\n  Fixpoint add_funs B Γ : ccstate unit :=\n    match B with\n    | Fcons f typ xs e B' =>\n      set_var_entry f (MRFun Γ) ;;\n      add_funs B' Γ \n    | Fnil => ret tt\n    end.\n\n\n  (** Construct the closure environment  *)\n  Definition make_env (fvs : list var) (c_old : cTag) (Γ_new Γ_old : var)\n  : ccstate (cTag * exp_ctx) :=\n    C <- get_vars fvs c_old Γ_old  ;;\n    c_new <- make_record_cTag (N_as_OT.of_nat (List.length fvs)) ;; (* TODO fix *)\n    ret (c_new, comp_ctx_f C (Econstr_c Γ_new c_new fvs Hole_c)).\n\n\n  Fixpoint exp_closure_conv (e : exp)\n           (c : cTag) (Γ : var) : ccstate (exp * exp_ctx) := \n    match e with\n    | Econstr x tag ys e' =>\n      C1 <- get_vars ys c Γ ;;\n      set_var_entry x BoundVar ;;\n      ef <- exp_closure_conv e' c Γ ;;\n      let (e_cc, C) := ef in \n      ret (Econstr x tag ys (C |[ e_cc ]|), C1)\n    | Ecase x pats =>\n      C1 <- get_var x c Γ ;;\n      pats' <-\n      (fix mapM_cc l :=\n         match l with\n         | [] => ret []\n         | (y, e) :: xs =>\n           var_map <- peak_var_map tt ;;\n           ef <- exp_closure_conv e c Γ ;;\n           push_var_map var_map ;;\n           xs' <- mapM_cc xs ;;\n           ret ((y, ((snd ef) |[ fst ef ]|)) :: xs')\n         end) pats;;\n        ret (Ecase x pats', C1)\n      | Eproj x tag n y e' =>\n        C1 <- get_var y c Γ ;;\n        set_var_entry x BoundVar ;;\n        ef <- exp_closure_conv e' c Γ ;;\n        let (e_cc, C) := ef in \n        ret (Eproj x tag n y (C |[ e_cc ]|), C1)\n      | Efun defs e =>\n        (* precompute free vars so this computation does not mess up the complexity *)\n        let fv_set := fundefs_fv defs in\n        let fvs := PS.elements fv_set in \n        Γ' <- get_name_no_suff \"env\";;\n        t1 <- make_env fvs c Γ' Γ ;;\n        let '(c', Cenv) := t1 in\n        (* fundefs *)\n        var_map <- pop_var_map tt ;;\n        add_fvs fvs 0%N ;;\n        defs' <- fundefs_closure_conv defs defs c' ;;\n        push_var_map var_map ;;\n        (* end fundefs *)\n        add_funs defs Γ' ;;\n        ef <- exp_closure_conv e c Γ ;;\n        let (e_cc, C) := ef in \n        ret (Efun defs' (C |[ e_cc ]|), Cenv)\n      | Eapp f ft xs =>\n        C1 <- get_vars (f :: xs) c Γ ;;\n        ptr <- get_name f code_suffix ;;\n        Γ <- get_name f clo_env_suffix ;;\n        ret (Eproj ptr clo_tag 0 f\n                   (Eproj Γ clo_tag 1 f\n                          (Eapp ptr ft (Γ :: xs))), C1)\n    | Eprim x prim ys e' =>\n      C1 <- get_vars ys c Γ ;;\n      set_var_entry x BoundVar ;;\n      ef <- exp_closure_conv e' c Γ ;;\n      let (e_cc, C) := ef in \n      ret (Eprim x prim ys (C |[ e_cc ]|), C1)\n    | Ehalt x =>\n      C1 <- get_var x c Γ ;;\n      ret (Ehalt x, C1)\n    end\n  with fundefs_closure_conv B (defs : fundefs) (c : cTag)\n       : ccstate fundefs  :=\n         match defs with\n           | Fcons f tag ys e defs' =>\n             var_map <- peak_var_map tt ;;\n             (* formal parameter for the environment pointer *)\n             Γ <- get_name f clo_env_suffix ;;\n             add_funs B Γ ;;\n             (* Add arguments to the map *)\n             add_params ys ;;\n             ef <- exp_closure_conv e c Γ ;;\n             let (e_cc, C) := ef in \n             push_var_map var_map ;;\n             defs'' <- fundefs_closure_conv B defs' c ;;\n             ret (Fcons f tag (Γ :: ys) (C |[ e_cc ]|) defs'')\n           | Fnil => ret Fnil\n         end.\n\n\n  (* Toplevel closure conversion program *)\n  Definition closure_conversion_top\n             (e : exp) (c : cTag) (Γ : var) (i : iTag) (cenv : cEnv) (nmap:M.t BasicAst.name) : exp * exp_ctx :=\n    let next := ((Pos.max (max_var e 1%positive) Γ) + 1)%positive in\n    let state := mkSt (Maps.PTree.empty VarInfo) next c i cenv nmap in\n    let '(e, C, s) := runState\n                        (exp_closure_conv e 1%positive Γ)\n                        state in\n    \n    (e, C).\n\nEnd CC.\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/closure_conversion.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2530683252493279}}
{"text": "(* DEC1 language development.\n   Paolo Torrini, \n   Universite' Lille-1 - CRIStAL-CNRS\n*)\n(* inversion lemmas for the step rules *)\nRequire Export Basics.\nRequire Export EnvLibA.\nRequire Export RelLibA.\n\nRequire Export Coq.Program.Equality.\nRequire Import Coq.Init.Specif.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Omega.\nRequire Import Coq.Lists.List.\n\nRequire Import IdModTypeA.\nRequire Import StaticSemA.\nRequire Import TRInductA.\nRequire Import WeakenA.\nRequire Import TSoundnessA.\nRequire Import IdModTypeA.\nRequire Import DetermA.\nRequire Import WeakenA.\nRequire Import AbbrevA.\n\nImport ListNotations.\n\nModule Invert (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 AbbrevI := Abbrev IdT.\nExport AbbrevI.\n\n\n(** inverse big-step lemmas (using modules up to Weaken) *)\n\n\nLemma BindN_BStep1 (fenv: funEnv) (env: valEnv)\n      (e1 e2: Exp) (v: Value) (s s': W) : \n  (forall (e:Exp) (s: W), sigT (fun v: Value =>\n                 sigT (fun s': W => \n      EClosure fenv env (Conf Exp s e) (Conf Exp s' (Val v))))) ->\n  (forall (e:Exp) (s s1 s2: W) (v1 v2: Value), \n      EClosure fenv env (Conf Exp s e) (Conf Exp s1 (Val v1)) ->\n      EClosure fenv env (Conf Exp s e) (Conf Exp s2 (Val v2)) -> \n        (s1 = s2) /\\ (v1 = v2)) ->\n  EClosure fenv env (Conf Exp s (BindN e1 e2)) (Conf Exp s' (Val v)) ->\n  (sigT2 (fun s1 : W =>\n            (sigT (fun v1: Value =>\n                     EClosure fenv env (Conf Exp s e1) (Conf Exp s1 (Val v1)))))\n         (fun s1 : W =>\n            EClosure fenv env (Conf Exp s1 e2) (Conf Exp s' (Val v)))).\n  intros X K.\n  intros.\n  generalize X.\n  intro X1.\n  specialize (X e1 s).\n  destruct X as [v1 X].\n  destruct X as [s1 X].\n  specialize (X1 e2 s1).  \n  destruct X1 as [v2 X1].\n  destruct X1 as [s2 X1].\n\n  generalize X.\n  intro K1.\n  eapply BindN_extended_congruence in X.\n  instantiate (1:=e2) in X.\n  \n  assert (EStep fenv env (Conf Exp s1 (BindN (Val v1) e2)) (Conf Exp s1 e2)).\n  constructor.\n  eapply StepIsEClos in X2.\n  \n  assert (EClosure fenv env (Conf Exp s (BindN e1 e2)) (Conf Exp s1 e2)).\n  eapply EClosConcat.\n  exact X.\n  assumption.  \n\n  assert (EClosure fenv env (Conf Exp s (BindN e1 e2)) (Conf Exp s2 (Val v2))).\n  eapply EClosConcat.\n  exact X3.\n  assumption.\n\n  assert (s' = s2 /\\ v = v2).\n  eapply K.\n  eauto.\n  assumption.\n  destruct H.\n  subst.\n\n  econstructor.\n  econstructor.  \n  eauto. \n  auto.\nDefined.\n  \n\nLemma BindN_BStep2 (fenv: funEnv) (env: valEnv)\n      (e1 e2: Exp) (v: Value) (s s': W) : \n  (forall (e:Exp) (s: W), sigT (fun v: Value =>\n                 sigT (fun s': W => \n      EClosure fenv env (Conf Exp s e) (Conf Exp s' (Val v))))) ->\n  (forall (e:Exp) (s s1 s2: W) (v1 v2: Value), \n      EClosure fenv env (Conf Exp s e) (Conf Exp s1 (Val v1)) ->\n      EClosure fenv env (Conf Exp s e) (Conf Exp s2 (Val v2)) -> \n        (s1 = s2) /\\ (v1 = v2)) ->\n  EClosure fenv env (Conf Exp s (BindN e1 e2)) (Conf Exp s' (Val v)) ->\n  forall (s1 : W) (v1: Value),\n    EClosure fenv env (Conf Exp s e1) (Conf Exp s1 (Val v1)) ->\n    EClosure fenv env (Conf Exp s1 e2) (Conf Exp s' (Val v)).\n  intros.\n  generalize X1.\n  intro X2.\n  eapply BindN_extended_congruence in X1.\n  instantiate (1:= e2) in X1.\n\n  assert (EStep fenv env (Conf Exp s1 (BindN (Val v1) e2)) (Conf Exp s1 e2)).\n  constructor.\n  eapply StepIsEClos in X3.\n  assert (EClosure fenv env (Conf Exp s (BindN e1 e2)) (Conf Exp s1 e2)).\n  eapply EClosConcat.\n  exact X1.\n  auto.\n  specialize (X e2 s1).\n  destruct X as [v2 X].\n  destruct X as [s2 X].\n  assert (EClosure fenv env (Conf Exp s (BindN e1 e2)) (Conf Exp s2 (Val v2))).\n  eapply EClosConcat.\n  exact X4.\n  auto.\n  assert (s' = s2 /\\ v = v2).\n  eapply H.\n  exact X0.\n  auto.\n  destruct H0.\n  subst.\n  auto.\nDefined.\n\n\n\nLemma BindS_BStep1 (fenv: funEnv) (env: valEnv)\n      (e1 e2: Exp) (x: Id) (v: Value) (s s': W) : \n  (forall (fenv: funEnv) (env: valEnv) (e:Exp) (s: W), sigT (fun v: Value =>\n                 sigT (fun s': W => \n      EClosure fenv env (Conf Exp s e) (Conf Exp s' (Val v))))) ->\n  (forall (e:Exp) (s s1 s2: W) (v1 v2: Value), \n      EClosure fenv env (Conf Exp s e) (Conf Exp s1 (Val v1)) ->\n      EClosure fenv env (Conf Exp s e) (Conf Exp s2 (Val v2)) -> \n        (s1 = s2) /\\ (v1 = v2)) ->\n  EClosure fenv env (Conf Exp s (BindS x e1 e2)) (Conf Exp s' (Val v)) ->\n  sigT (fun s1 : W =>\n     (sigT2 (fun v1: Value =>\n        EClosure fenv env (Conf Exp s e1) (Conf Exp s1 (Val v1)))\n              (fun v1 : Value =>\n        EClosure fenv ((x,v1)::env) (Conf Exp s1 e2) (Conf Exp s' (Val v))))).\n  intros X K.\n  intros.\n  generalize X.\n  intro X1.\n  specialize (X fenv env e1 s).\n  destruct X as [v1 X].\n  destruct X as [s1 X].\n  generalize X.\n  intro K1.\n  eapply BindS_extended_congruence in X.\n  instantiate (1:=e2) in X.\n  instantiate (1:=x) in X.\n  \n  assert (EStep fenv env (Conf Exp s1 (BindS x (Val v1) e2))\n                         (Conf Exp s1 (BindMS emptyE [(x,v1)] e2))).\n  constructor.\n  eapply StepIsEClos in X2.\n  \n  assert (EClosure fenv env (Conf Exp s (BindS x e1 e2))\n                            (Conf Exp s1 (BindMS emptyE [(x,v1)] e2))).\n  eapply EClosConcat.\n  exact X.\n  assumption.  \n\n  specialize (X1 fenv ((x,v1)::env) e2 s1).  \n  destruct X1 as [v2 X1].\n  destruct X1 as [s2 X1].\n\n  assert (EClosure fenv env (Conf Exp s (BindS x e1 e2))\n                            (Conf Exp s2 (Val v2))).\n  eapply EClosConcat.\n  exact X3.\n\n  assert (EClosure fenv env (Conf Exp s1 (BindMS emptyE [(x, v1)] e2))\n                            (Conf Exp s2 (BindMS emptyE [(x, v1)] (Val v2)))).\n  eapply BindMS_extended_congruence.\n  reflexivity.\n  reflexivity.\n  assumption.\n  \n  eapply EClosConcat.\n  exact X4.\n  eapply StepIsEClos.\n  constructor.\n  \n  assert (s' = s2 /\\ v = v2).\n  eapply K.\n  eauto.\n  assumption.\n  destruct H.\n  subst.\n\n  econstructor.\n  econstructor.  \n  eauto. \n  auto.\nDefined.\n\n\n\nLemma Apply_BStep1 (fenv: funEnv) (env: valEnv)\n      (f: Fun) (es: list Exp) (v: Value) (s s': W) : \n  (forall (fenv: funEnv) (env: valEnv) (e:Exp) (s: W), sigT (fun v: Value =>\n                 sigT (fun s': W => \n      EClosure fenv env (Conf Exp s e) (Conf Exp s' (Val v))))) ->\n  (forall (fenv: funEnv) (env: valEnv) (es:list Exp) (s: W),\n      sigT (fun vs: list Value =>\n                 sigT (fun s': W => \n      PrmsClosure fenv env (Conf Prms s (PS es))\n                           (Conf Prms s' (PS (map Val vs)))))) ->\n   (forall (e:Exp) (s s1 s2: W) (v1 v2: Value), \n      EClosure fenv env (Conf Exp s e) (Conf Exp s1 (Val v1)) ->\n      EClosure fenv env (Conf Exp s e) (Conf Exp s2 (Val v2)) -> \n        (s1 = s2) /\\ (v1 = v2)) ->\n\n   match f as f with\n    | FC fenv' tenv' e0 e1 x n =>\n  length tenv' = length es ->     \n  EClosure fenv env (Conf Exp s (Apply (QF f) (PS es)))\n                                (Conf Exp s' (Val v)) ->\n  sigT (fun s1 : W =>\n     (sigT2 (fun vs: list Value =>\n               PrmsClosure fenv env (Conf Prms s (PS es))\n                                    (Conf Prms s1 (PS (map Val vs))))\n            (fun vs : list Value =>\n    match n with\n    | 0 =>   \n      EClosure fenv' (mkVEnv tenv' vs) (Conf Exp s1 e0)\n                                       (Conf Exp s' (Val v))\n    | S n' =>\n      EClosure ((x, FC fenv' tenv' e0 e1 x n') :: fenv')\n         (mkVEnv tenv' vs) (Conf Exp s1 e1) (Conf Exp s' (Val v))\n    end)))\n   end.\n\nProof.  \n  intros P1 P2 P3.\n  destruct f.\n  intros.\n\n  generalize P2.\n  intro P0.\n  specialize (P0 fenv env es s).\n  destruct P0 as [vs P0].\n  destruct P0 as [s1 P0].\n  generalize P0. \n  intro X0.\n  eapply Apply1_extended_congruence with (f:=(FC fenv0 tenv e0 e1 x n)) in X0.\n  \n  econstructor.\n  instantiate (1:=s1). \n\n  generalize P0.\n  intro P6.\n  eapply PrmsClos_aux0 in P6.\n  rewrite map_length with (f:=Val) in P6.\n  rewrite P6 in H.\n  clear P6.\n\n  econstructor.\n  instantiate (1:=vs).\n  exact P0.\n  \n  destruct n.\n(**)\n  generalize P1.\n  intro P5.\n  specialize (P5 fenv0 (mkVEnv tenv vs) e0 s1).\n  destruct P5 as [v2 P5].\n  destruct P5 as [s2 P5].\n  \n  assert (EClosure fenv env (Conf Exp s1\n            (Apply (QF (FC fenv0 tenv e0 e1 x 0)) (PS (map Val vs))))\n                   (Conf Exp s1 (BindMS fenv0 (mkVEnv tenv vs) e0))).             eapply StepIsEClos.\n  econstructor.\n  econstructor.\n  reflexivity.\n  exact H.\n  reflexivity.\n\n  assert (EClosure fenv env (Conf Exp s1 (BindMS fenv0 (mkVEnv tenv vs) e0))\n                       (Conf Exp s2 (BindMS fenv0 (mkVEnv tenv vs) (Val v2)))).\n  eapply BindMS_extended_congruence.\n  reflexivity.\n  reflexivity.\n  eapply weaken.\n  exact P5.\n\n  assert (EClosure fenv env\n                   (Conf Exp s2 (BindMS fenv0 (mkVEnv tenv vs) (Val v2)))\n                   (Conf Exp s2 (Val v2))).\n  eapply StepIsEClos.\n  econstructor.\n\n  assert (EClosure fenv env\n        (Conf Exp s (Apply (QF (FC fenv0 tenv e0 e1 x 0)) (PS es)))\n        (Conf Exp s2 (Val v2))).\n  eapply EClosConcat.\n  exact X0.\n  eapply EClosConcat.\n  exact X1.  \n  eapply EClosConcat.\n  exact X2.\n  exact X3.\n\n  assert (s' = s2 /\\ v = v2).\n  eapply P3.\n  exact X.\n  exact X4.\n\n  destruct H0. \n  subst.\n  exact P5.\n(**)\n \n  generalize P1.\n  intro P5.\n  set ((x, FC fenv0 tenv e0 e1 x n) :: fenv0) as fenv'.\n  \n  specialize (P5 fenv' (mkVEnv tenv vs) e1 s1).\n  destruct P5 as [v2 P5].\n  destruct P5 as [s2 P5].\n  \n  assert (EClosure fenv env (Conf Exp s1\n            (Apply (QF (FC fenv0 tenv e0 e1 x (S n))) (PS (map Val vs))))\n                   (Conf Exp s1\n                         (BindMS fenv' (mkVEnv tenv vs) e1))).\n  eapply StepIsEClos.\n  econstructor.\n  econstructor.\n  reflexivity.\n  exact H.\n  reflexivity.\n\n  assert (EClosure fenv env (Conf Exp s1 (BindMS fenv' (mkVEnv tenv vs) e1))\n                       (Conf Exp s2 (BindMS fenv' (mkVEnv tenv vs) (Val v2)))).\n  eapply BindMS_extended_congruence.\n  reflexivity.\n  reflexivity.\n  eapply weaken.\n  exact P5.\n\n  assert (EClosure fenv env\n                   (Conf Exp s2 (BindMS fenv' (mkVEnv tenv vs) (Val v2)))\n                   (Conf Exp s2 (Val v2))).\n  eapply StepIsEClos.\n  econstructor.\n\n  assert (EClosure fenv env\n        (Conf Exp s (Apply (QF (FC fenv0 tenv e0 e1 x (S n))) (PS es)))\n        (Conf Exp s2 (Val v2))).\n  eapply EClosConcat.\n  exact X0.\n  eapply EClosConcat.\n  exact X1.  \n  eapply EClosConcat.\n  exact X2.\n  exact X3.\n\n  assert (s' = s2 /\\ v = v2).\n  eapply P3.\n  exact X.\n  exact X4.\n\n  destruct H0. \n  subst.\n  exact P5.\nDefined.\n\n(*********************************************************************)\n\n(** further inverse big-step lemmas *)\n\n\nLemma BindN_BStepT1 (ftenv: funTC) (tenv: valTC)\n      (fenv: funEnv) (env: valEnv) \n      (e1 e2: Exp) (v: Value) (s s': W)\n      (k1: FEnvTyping fenv ftenv)\n      (k2: EnvTyping env tenv) (t: VTyp)\n      (k3: ExpTyping ftenv tenv fenv (BindN e1 e2) t) :\n  EClosure fenv env (Conf Exp s (BindN e1 e2)) (Conf Exp s' (Val v)) ->\n  (sigT2 (fun s1 : W =>\n            (sigT (fun v1: Value =>\n                     EClosure fenv env (Conf Exp s e1) (Conf Exp s1 (Val v1)))))\n         (fun s1 : W =>\n            EClosure fenv env (Conf Exp s1 e2) (Conf Exp s' (Val v)))).\n  intros.\n  inversion k3; subst.\n  rename X0 into Y1.\n  rename X1 into Y2.\n  rename t into t2.\n  \n  assert (ExpSoundness ftenv tenv fenv e1 t1 Y1) as X1.\n  eapply (ExpEval ftenv tenv fenv e1 t1 Y1).\n  unfold ExpSoundness in X1.\n  unfold SoundExp in X1.\n  specialize (X1 k1 env k2 s).\n  destruct X1 as [v1 k4 X1].\n  destruct X1 as [s1 X1].\n\n  generalize X1.\n  intro.\n\n  assert (ExpSoundness ftenv tenv fenv e2 t2 Y2) as X2.\n  eapply (ExpEval ftenv tenv fenv e2 t2 Y2).\n  unfold ExpSoundness in X2.\n  unfold SoundExp in X2.\n  specialize (X2 k1 env k2 s1).\n  destruct X2 as [v2 k5 X2].\n  destruct X2 as [s2 X2].\n  \n  eapply BindN_extended_congruence in X1.\n  instantiate (1:=e2) in X1.\n  \n  assert (EStep fenv env (Conf Exp s1 (BindN (Val v1) e2)) (Conf Exp s1 e2)).\n  constructor.\n  eapply StepIsEClos in X3.\n  \n  assert (EClosure fenv env (Conf Exp s (BindN e1 e2)) (Conf Exp s1 e2)).\n  eapply EClosConcat.\n  exact X1.\n  assumption.  \n\n  assert (EClosure fenv env (Conf Exp s (BindN e1 e2)) (Conf Exp s2 (Val v2))).\n  eapply EClosConcat.\n  exact X4.\n  assumption.\n\n  assert (s' = s2 /\\ v = v2).\n  eapply ExpConfluence. \n  exact k3.\n  auto.\n  eauto.\n  eauto.\n  auto.\n\n  destruct H.\n  subst.\n\n  econstructor.\n  econstructor.  \n  eauto. \n  auto.\nDefined.\n\n\nLemma BindS_BStepT1 (ftenv: funTC) (tenv: valTC)\n      (fenv: funEnv) (env: valEnv) \n      (e1 e2: Exp) (x: Id) (v: Value) (s s': W)\n      (k1: FEnvTyping fenv ftenv)\n      (k2: EnvTyping env tenv) (t: VTyp)\n      (k3: ExpTyping ftenv tenv fenv (BindS x e1 e2) t) :\n  EClosure fenv env (Conf Exp s (BindS x e1 e2)) (Conf Exp s' (Val v)) ->\n  sigT (fun s1 : W =>\n     (sigT2 (fun v1: Value =>\n        EClosure fenv env (Conf Exp s e1) (Conf Exp s1 (Val v1)))\n              (fun v1 : Value =>\n        EClosure fenv ((x,v1)::env) (Conf Exp s1 e2) (Conf Exp s' (Val v))))).\n  intros.\n  inversion k3; subst.\n  rename X0 into Y1.\n  rename X1 into Y2.\n  rename t into t2.\n  \n  assert (ExpSoundness ftenv tenv fenv e1 t1 Y1) as X1.\n  eapply (ExpEval ftenv tenv fenv e1 t1 Y1).\n  unfold ExpSoundness in X1.\n  unfold SoundExp in X1.\n  specialize (X1 k1 env k2 s).\n  destruct X1 as [v1 k4 X1].\n  destruct X1 as [s1 X1].\n\n  generalize X1.\n  intro.\n\n  eapply BindS_extended_congruence in X1.\n  instantiate (1:=e2) in X1.\n  instantiate (1:=x) in X1.\n  \n  assert (EStep fenv env (Conf Exp s1 (BindS x (Val v1) e2))\n                         (Conf Exp s1 (BindMS emptyE [(x,v1)] e2))).\n  constructor.\n  eapply StepIsEClos in X2.\n  \n  assert (EClosure fenv env (Conf Exp s (BindS x e1 e2))\n                            (Conf Exp s1 (BindMS emptyE [(x,v1)] e2))).\n  eapply EClosConcat.\n  exact X1.\n  assumption.  \n\n  assert (ExpSoundness ftenv tenv' fenv e2 t2 Y2) as X4.\n  eapply (ExpEval ftenv tenv' fenv e2 t2 Y2).\n  unfold ExpSoundness in X4.\n  unfold SoundExp in X4.\n\n  assert (MatchEnvsT ValueTyping ((x, v1) :: env) tenv').\n  econstructor.\n  auto.\n  auto.\n  specialize (X4 k1 ((x,v1)::env) X5 s1).\n  destruct X4 as [v2 k5 X4].\n  destruct X4 as [s2 X4].\n\n  assert (EClosure fenv env (Conf Exp s (BindS x e1 e2))\n                            (Conf Exp s2 (Val v2))).\n  eapply EClosConcat.\n  exact X3.\n\n  assert (EClosure fenv env (Conf Exp s1 (BindMS emptyE [(x, v1)] e2))\n                            (Conf Exp s2 (BindMS emptyE [(x, v1)] (Val v2)))).\n  eapply BindMS_extended_congruence.\n  reflexivity.\n  reflexivity.\n  assumption.\n  \n  eapply EClosConcat.\n  exact X6.\n  eapply StepIsEClos.\n  constructor.\n  \n  assert (s' = s2 /\\ v = v2).\n  eapply ExpConfluence. \n  exact k3.\n  auto.\n  eauto.\n  eauto.\n  auto.\n  \n  destruct H.\n  subst.\n\n  econstructor.\n  econstructor.  \n  eauto. \n  auto.\nDefined.\n\n\nLemma Apply_BStepT1 (ftenv: funTC) (tenv: valTC)\n      (fenv: funEnv) (env: valEnv)\n      (f: Fun) (es: list Exp) (v: Value) (s s': W) \n      (k1: FEnvTyping fenv ftenv)\n      (k2: EnvTyping env tenv) (t: VTyp)\n      (k3: ExpTyping ftenv tenv fenv (Apply (QF f) (PS es)) t) :\n   match f as f with\n    | FC fenv' tenv' e0 e1 x n =>\n  length tenv' = length es ->     \n  EClosure fenv env (Conf Exp s (Apply (QF f) (PS es)))\n                                (Conf Exp s' (Val v)) ->\n  sigT (fun s1 : W =>\n     (sigT2 (fun vs: list Value =>\n               PrmsClosure fenv env (Conf Prms s (PS es))\n                                    (Conf Prms s1 (PS (map Val vs))))\n            (fun vs : list Value =>\n    match n with\n    | 0 =>   \n      EClosure fenv' (mkVEnv tenv' vs) (Conf Exp s1 e0)\n                                       (Conf Exp s' (Val v))\n    | S n' =>\n      EClosure ((x, FC fenv' tenv' e0 e1 x n') :: fenv')\n         (mkVEnv tenv' vs) (Conf Exp s1 e1) (Conf Exp s' (Val v))\n    end)))\n   end.\n\nProof.\n  destruct f.\n  intros.\n  inversion k3; subst.\n  rename X1 into Y2.\n  rename X2 into Y1.\n  \n  assert (PrmsSoundness ftenv tenv fenv (PS es) (PT (map snd fps)) Y1) as X1.\n  eapply (PrmsEval ftenv tenv fenv (PS es) (PT (map snd fps)) Y1).\n  unfold PrmsSoundness in X1.\n  unfold SoundPrms in X1.\n  specialize (X1 k1 env k2 s).\n  destruct X1 as [es1 X1].\n  destruct X1 as [vs k4 X1].\n  destruct X1 as [k5 X1].\n  destruct X1 as [s1 X1].\n  \n  generalize X1.\n  intro.\n\n  eapply Apply1_extended_congruence with (f:=(FC fenv0 tenv0 e0 e1 x n)) in X1.\n  \n  econstructor.\n  instantiate (1:=s1). \n\n  generalize X2.\n  intro P6.\n  eapply PrmsClos_aux0 in P6.\n  inversion k4; subst.\n  \n  rewrite map_length with (f:=Val) in P6.\n  rewrite P6 in H.\n  clear P6.\n\n  econstructor.\n  instantiate (1:=vs).\n  auto.\n  \n  destruct n.\n  (**)\n  inversion Y2; subst.\n  inversion X3; subst.\n  \n  assert (ExpSoundness ftenv0 fps fenv0 e0 t X5) as X6.\n  eapply (ExpEval ftenv0 fps fenv0 e0 t X5).\n  unfold ExpSoundness in X6.\n  unfold SoundExp in X6.\n\n  assert (MatchEnvsT ValueTyping (mkVEnv fps vs) fps).\n  eapply prmsTypingAux_T.\n  auto.\n  eapply matchListsAux02_T.\n  eauto.\n  eauto.\n  \n  specialize (X6 X4 (mkVEnv fps vs) X7 s1).\n  destruct X6 as [v2 k7 P5].\n  destruct P5 as [s2 P5].\n  \n  assert (EClosure fenv env (Conf Exp s1\n            (Apply (QF (FC fenv0 fps e0 e1 x 0)) (PS (map Val vs))))\n                   (Conf Exp s1 (BindMS fenv0 (mkVEnv fps vs) e0))) as A1.        eapply StepIsEClos.\n  econstructor.\n  econstructor.\n  reflexivity.\n  exact H.\n  reflexivity.\n\n  assert (EClosure fenv env (Conf Exp s1 (BindMS fenv0 (mkVEnv fps vs) e0))\n                 (Conf Exp s2 (BindMS fenv0 (mkVEnv fps vs) (Val v2)))) as A2.\n  eapply BindMS_extended_congruence.\n  reflexivity.\n  reflexivity.\n  eapply weaken.\n  exact P5.\n\n  assert (EClosure fenv env\n                   (Conf Exp s2 (BindMS fenv0 (mkVEnv fps vs) (Val v2)))\n                   (Conf Exp s2 (Val v2))) as A3.\n  eapply StepIsEClos.\n  econstructor.\n\n  assert (EClosure fenv env\n        (Conf Exp s (Apply (QF (FC fenv0 fps e0 e1 x 0)) (PS es)))\n        (Conf Exp s2 (Val v2))) as A4.\n  eapply EClosConcat.\n  exact X1.\n  eapply EClosConcat.\n  exact A1.  \n  eapply EClosConcat.\n  exact A2.\n  exact A3.\n\n  assert (s' = s2 /\\ v = v2).\n  eapply ExpConfluence.\n  exact k3.\n  auto.\n  eauto.\n  eauto.\n  auto.\n\n  destruct H0. \n  subst.\n  exact P5.\n(**)\n  \n  inversion Y2; subst.\n  inversion X3; subst.\n  \n  assert (ExpSoundness ftenv' fps fenv' e1 t X5) as X06.\n  eapply (ExpEval ftenv' fps fenv' e1 t X5).\n  unfold ExpSoundness in X06.\n  unfold SoundExp in X06.\n\n  assert (MatchEnvsT ValueTyping (mkVEnv fps vs) fps).\n  eapply prmsTypingAux_T.\n  auto.\n  eapply matchListsAux02_T.\n  eauto.\n  eauto.\n\n  assert (MatchEnvsT FunTyping fenv' ftenv').\n  econstructor.\n  auto.\n  auto.\n  \n  specialize (X06 X8 (mkVEnv fps vs) X7 s1).\n  destruct X06 as [v2 k7 P5].\n  destruct P5 as [s2 P5].\n  \n  assert (EClosure fenv env (Conf Exp s1\n            (Apply (QF (FC fenv0 fps e0 e1 x (S n))) (PS (map Val vs))))\n                   (Conf Exp s1 (BindMS fenv' (mkVEnv fps vs) e1))) as A1.        eapply StepIsEClos.\n  econstructor.\n  econstructor.\n  reflexivity.\n  exact H.\n  reflexivity.\n\n  assert (EClosure fenv env (Conf Exp s1 (BindMS fenv' (mkVEnv fps vs) e1))\n                 (Conf Exp s2 (BindMS fenv' (mkVEnv fps vs) (Val v2)))) as A2.\n  eapply BindMS_extended_congruence.\n  reflexivity.\n  reflexivity.\n  eapply weaken.\n  exact P5.\n\n  assert (EClosure fenv env\n                   (Conf Exp s2 (BindMS fenv' (mkVEnv fps vs) (Val v2)))\n                   (Conf Exp s2 (Val v2))) as A3.\n  eapply StepIsEClos.\n  econstructor.\n\n  assert (EClosure fenv env\n        (Conf Exp s (Apply (QF (FC fenv0 fps e0 e1 x (S n))) (PS es)))\n        (Conf Exp s2 (Val v2))) as A4.\n  eapply EClosConcat.\n  exact X1.\n  eapply EClosConcat.\n  exact A1.  \n  eapply EClosConcat.\n  exact A2.\n  exact A3.\n\n  assert (s' = s2 /\\ v = v2).\n  eapply ExpConfluence.\n  exact k3.\n  auto.\n  eauto.\n  eauto.\n  auto.\n\n  destruct H0. \n  subst.\n  exact P5.\nDefined.\n\n\n\nLemma Prms_BStepT1 (ftenv: funTC) (tenv: valTC)\n      (fenv: funEnv) (env: valEnv) \n      (e: Exp) (es: list Exp) (v: Value) (vs: list Value) (s s': W)\n      (k1: FEnvTyping fenv ftenv)\n      (k2: EnvTyping env tenv) (pt: PTyp)\n      (k3: PrmsTyping ftenv tenv fenv (PS (e::es)) pt) :\n  PrmsClosure fenv env (Conf Prms s (PS (e::es)))\n                       (Conf Prms s' (PS (map Val (v::vs)))) ->\n  (sigT2 (fun s1 : W =>\n            (sigT (fun v1: Value =>\n                     EClosure fenv env (Conf Exp s e) (Conf Exp s1 (Val v1)))))\n         (fun s1 : W =>\n            PrmsClosure fenv env (Conf Prms s1 (PS es))\n                                 (Conf Prms s' (PS (map Val vs))))).\n  intros.\n  inversion k3; subst.\n  inversion X0; subst.\n  rename X1 into Y1.\n  rename X2 into Y3.\n  rename y into t.\n  rename l' into ts.\n  \n  assert (ExpSoundness ftenv tenv fenv e t Y1) as X1.\n  eapply (ExpEval ftenv tenv fenv e t Y1).\n  unfold ExpSoundness in X1.\n  unfold SoundExp in X1.\n  specialize (X1 k1 env k2 s).\n  destruct X1 as [v1 k4 X1].\n  destruct X1 as [s1 X1].\n\n  generalize X1.\n  intro Y4.\n\n  assert (PrmsTyping ftenv tenv fenv (PS es) (PT ts)) as Y2.\n  constructor.\n  auto.\n  \n  assert (PrmsSoundness ftenv tenv fenv (PS es) (PT ts) Y2) as X2.\n  eapply (PrmsEval ftenv tenv fenv (PS es) (PT ts) Y2).\n  unfold PrmsSoundness in X2.\n  unfold SoundPrms in X2.\n  specialize (X2 k1 env k2 s1).\n  destruct X2 as [es1 X2].\n  destruct X2 as [vs1 Y5 X2].\n  destruct X2 as [Y6 X2].\n  destruct X2 as [s2 X2].\n\n  inversion Y5; subst.\n\n(**)\n  assert (PrmsClosure fenv env (Conf Prms s (PS (e :: es)))\n        (Conf Prms s2 (PS (map Val (v1 :: vs1))))).\n  eapply Pars_extended_congruence4.\n  eauto.\n  exact X2.\n  \n  constructor 1 with (x:=s1).\n  constructor 1 with (x:=v1).\n  exact X1.\n\n  assert (s' = s2 /\\ vs = vs1).\n  eapply PrmsConfluence in X.\n  specialize (X X3).\n  destruct X.\n  split.\n  exact H.\n  inversion H0; subst.\n  auto.\n  eauto.\n  auto.\n  auto.\n  destruct H.\n  rewrite H.\n  rewrite H0.\n  auto.\nDefined.  \n\n\n\nLemma Prms_BStepT2 (ftenv: funTC) (tenv: valTC)\n      (fenv: funEnv) (env: valEnv) \n      (e: Exp) (es: list Exp) (v: Value) (vs: list Value) (s s': W)\n      (k1: FEnvTyping fenv ftenv)\n      (k2: EnvTyping env tenv) (pt: PTyp)\n      (k3: PrmsTyping ftenv tenv fenv (PS (e::es)) pt) :\n  PrmsClosure fenv env (Conf Prms s (PS (e::es)))\n                       (Conf Prms s' (PS (map Val (v::vs)))) ->\n  (sigT2 (fun s1 : W =>\n            (EClosure fenv env (Conf Exp s e) (Conf Exp s1 (Val v))))\n         (fun s1 : W =>\n            PrmsClosure fenv env (Conf Prms s1 (PS es))\n                                 (Conf Prms s' (PS (map Val vs))))).\n  intros.\n  inversion k3; subst.\n  inversion X0; subst.\n  rename X1 into Y1.\n  rename X2 into Y3.\n  rename y into t.\n  rename l' into ts.\n  \n  assert (ExpSoundness ftenv tenv fenv e t Y1) as X1.\n  eapply (ExpEval ftenv tenv fenv e t Y1).\n  unfold ExpSoundness in X1.\n  unfold SoundExp in X1.\n  specialize (X1 k1 env k2 s).\n  destruct X1 as [v1 k4 X1].\n  destruct X1 as [s1 X1].\n \n(*\n  generalize X1.\n  intro Y4.\n*)\n  assert (PrmsTyping ftenv tenv fenv (PS es) (PT ts)) as Y2.\n  constructor.\n  auto.\n  \n  assert (PrmsSoundness ftenv tenv fenv (PS es) (PT ts) Y2) as X2.\n  eapply (PrmsEval ftenv tenv fenv (PS es) (PT ts) Y2).\n  unfold PrmsSoundness in X2.\n  unfold SoundPrms in X2.\n  specialize (X2 k1 env k2 s1).\n  \n  destruct X2 as [es1 X2].\n  destruct X2 as [vs1 Y5 X2].\n  destruct X2 as [Y6 X2].\n  destruct X2 as [s2 X2].\n  inversion Y5; subst.\n\n  assert (PrmsClosure fenv env (Conf Prms s (PS (e :: es)))\n        (Conf Prms s2 (PS (map Val (v1 :: vs1))))).\n  eapply Pars_extended_congruence4.\n  eauto.\n  exact X2.\n  \n  \n  (**)\n  assert (s' = s2 /\\ (v::vs) = (v1::vs1)).\n  eapply PrmsConfluence in X.\n  specialize (X X3).\n  exact X.\n\n  eauto.\n  auto.\n  auto.\n  destruct H.\n  injection H0.\n  intros.\n  \n  constructor 1 with (x:=s1).\n  rewrite H2.\n  auto.\n  rewrite H.\n  rewrite H1.\n  auto.\nDefined.  \n\n\nLemma IfThenElse_BStepT1 (ftenv: funTC) (tenv: valTC)\n      (fenv: funEnv) (env: valEnv) \n      (e1 e2 e3: Exp) (v: Value) (s s': W)\n      (k1: FEnvTyping fenv ftenv)\n      (k2: EnvTyping env tenv) (t: VTyp)\n      (k3: ExpTyping ftenv tenv fenv (IfThenElse e1 e2 e3) t) :\n  EClosure fenv env (Conf Exp s (IfThenElse e1 e2 e3)) (Conf Exp s' (Val v)) ->\n  sum (sigT2 (fun s1 : W =>\n        EClosure fenv env (Conf Exp s e1) (Conf Exp s1 (Val (cst bool true))))           (fun s1 : W =>\n             (EClosure fenv env (Conf Exp s1 e2) (Conf Exp s' (Val v)))))\n      (sigT2 (fun s1 : W =>\n      EClosure fenv env (Conf Exp s e1) (Conf Exp s1 (Val (cst bool false))))           (fun s1 : W => \n             (EClosure fenv env (Conf Exp s1 e3) (Conf Exp s' (Val v))))).\nProof.\n  intros.\n  inversion k3; subst.\n  \n  assert (ExpSoundness ftenv tenv fenv e1 Bool X0) as Y1.\n  eapply (ExpEval ftenv tenv fenv e1 Bool X0).\n  unfold ExpSoundness in Y1.\n  unfold SoundExp in Y1.\n  specialize (Y1 k1 env k2 s).\n\n  assert (ExpSoundness ftenv tenv fenv e2 t X1) as Y2.\n  eapply (ExpEval ftenv tenv fenv e2 t X1).\n  unfold ExpSoundness in Y2.\n  unfold SoundExp in Y2.\n  specialize (Y2 k1 env k2).\n\n  assert (ExpSoundness ftenv tenv fenv e3 t X2) as Y3.\n  eapply (ExpEval ftenv tenv fenv e3 t X2).\n  unfold ExpSoundness in Y3.\n  unfold SoundExp in Y3.\n  specialize (Y3 k1 env k2).\n\n  destruct Y1 as [v1 H1 Y1].\n  destruct Y1 as [s1 Y1].\n  specialize (Y2 s1).\n  specialize (Y3 s1).\n  destruct v1.\n  destruct v0. \n  inversion H1; subst.\n  simpl in *.\n  subst T.\n  inversion H; subst.\n  clear H2.\n\n  destruct v0.\n\n(**)\n  destruct Y2 as [v2 H2 Y2].\n  destruct Y2 as [s2 Y2].\n  \n  assert (EClosure fenv env (Conf Exp s (IfThenElse e1 e2 e3))\n                   (Conf Exp s2 (Val v2))).  \n  eapply EClosConcat.\n  eapply IfThenElse_extended_congruence.\n  exact Y1.\n  econstructor.\n  econstructor.\n  exact Y2.\n\n  assert (s' = s2 /\\ v = v2).\n  eapply (ExpConfluence ftenv tenv fenv (IfThenElse e1 e2 e3) t k3).\n  auto.\n  eauto.\n  exact X.\n  auto.\n  destruct H.\n\n  constructor.\n  econstructor 1 with (x:=s1).\n  auto.\n  rewrite H.\n  rewrite H3.\n  exact Y2.\n\n(**)\n  clear Y2.\n  rename Y3 into Y2.\n  destruct Y2 as [v2 H2 Y2].\n  destruct Y2 as [s2 Y2].\n  \n  assert (EClosure fenv env (Conf Exp s (IfThenElse e1 e2 e3))\n                   (Conf Exp s2 (Val v2))).  \n  eapply EClosConcat.\n  eapply IfThenElse_extended_congruence.\n  exact Y1.\n  econstructor.\n  econstructor.\n  exact Y2.\n\n  assert (s' = s2 /\\ v = v2).\n  eapply (ExpConfluence ftenv tenv fenv (IfThenElse e1 e2 e3) t k3).\n  auto.\n  eauto.\n  exact X.\n  auto.\n  destruct H.\n\n  constructor 2.\n  econstructor 1 with (x:=s1).\n  auto.\n  rewrite H.\n  rewrite H3.\n  exact Y2.\nQed.\n  \n\n\nLemma Apply_BStepT2\n      (ftenv: funTC) (tenv: valTC)\n      (fenv: funEnv) (env: valEnv)\n      (f: Fun) (es: list Exp) (v: Value) (s s': W) \n      (k1: FEnvTyping fenv ftenv)\n      (k2: EnvTyping env tenv) (t: VTyp)\n      (k3: ExpTyping ftenv tenv fenv (Apply (QF f) (PS es)) t) :\n  EClosure fenv env (Conf Exp s (Apply (QF f) (PS es)))\n                                (Conf Exp s' (Val v)) ->\n  sigT (fun s1 : W =>\n          (sigT2 (fun vs: list Value =>   \n               PrmsClosure fenv env (Conf Prms s (PS es))\n                                    (Conf Prms s1 (PS (map Val vs))))\n            (fun vs : list Value =>\n               EClosure fenv env (Conf Exp s1 (Apply (QF f)\n                                                  (PS (map Val vs))))\n                                 (Conf Exp s' (Val v))))).\nProof.\n  intros.\n  inversion k3; subst.\n  rename X1 into Y2.\n  rename X2 into Y1.\n  \n  assert (PrmsSoundness ftenv tenv fenv (PS es) (PT (map snd fps)) Y1) as X1.\n  eapply (PrmsEval ftenv tenv fenv (PS es) (PT (map snd fps)) Y1).\n  unfold PrmsSoundness in X1.\n  unfold SoundPrms in X1.\n  specialize (X1 k1 env k2 s).\n  destruct X1 as [es1 X1].\n  destruct X1 as [vs k4 X1].\n  destruct X1 as [k5 X1].\n  destruct X1 as [s1 X1].\n   \n  generalize X1.\n  intro.\n\n  eapply Apply1_extended_congruence with (f:=f) in X1.\n  \n  econstructor 1 with (x:=s1).\n  \n  inversion k4; subst.\n\n  econstructor 1 with (x:=vs).\n  auto.\n\n  assert (ExpTyping ftenv tenv fenv (Apply (QF f) (PS (map Val vs))) t).\n  econstructor.\n  reflexivity.\n  auto.\n  eauto.\n  eapply weakenPrmsTyping in k5.\n  instantiate (1:=fenv) in k5.\n  instantiate (1:=tenv) in k5.\n  instantiate (1:=ftenv) in k5.\n  simpl in k5.\n  auto.\n  constructor.\n  auto.\n\n  set (Apply (QF f) (PS (map Val vs))) as e.\n\n  assert (ExpSoundness ftenv tenv fenv e t X3) as X6.\n  eapply (ExpEval ftenv tenv fenv e t X3).\n  unfold ExpSoundness in X6.\n  unfold SoundExp in X6.\n  specialize (X6 X0 env k2 s1).\n  destruct X6 as [v2 H0 X6].\n  destruct X6 as [s2 X6].\n\n  assert (EClosure fenv env (Conf Exp s (Apply (QF f) (PS es)))\n                   (Conf Exp s2 (Val v2))).\n  eapply EClosConcat.\n  exact X1.\n  auto.\n\n  assert (s' = s2 /\\ v = v2).\n  eapply ExpConfluence.\n  exact k3.\n  auto.\n  eauto.\n  eauto.\n  auto.\n  destruct H.\n  rewrite H.\n  rewrite H1.\n  auto.\nDefined.\n  \n\nLemma Apply_BStepT2t\n      (ftenv: funTC) (tenv: valTC)\n      (fenv: funEnv) (env: valEnv)\n      (f: Fun) (es: list Exp) (v: Value) (s s': W) \n      (k1: FEnvTyping fenv ftenv)\n      (k2: EnvTyping env tenv) (t: VTyp) (pt: PTyp)\n      (k3: ExpTyping ftenv tenv fenv (Apply (QF f) (PS es)) t)\n      (k0: PrmsTyping ftenv tenv fenv (PS es) pt) :\n  EClosure fenv env (Conf Exp s (Apply (QF f) (PS es)))\n                                (Conf Exp s' (Val v)) ->\n  sigT (fun s1 : W =>\n          (sigT2 (fun vs: list Value =>\n               (PrmsTyping ftenv tenv fenv (PS (map Val vs)) pt *       \n               PrmsClosure fenv env (Conf Prms s (PS es))\n                                    (Conf Prms s1 (PS (map Val vs))))%type)\n            (fun vs : list Value =>\n               EClosure fenv env (Conf Exp s1 (Apply (QF f)\n                                                  (PS (map Val vs))))\n                                 (Conf Exp s' (Val v))))).\nProof.\n  intros.\n  inversion k3; subst.\n  rename X1 into Y2.\n  rename X2 into Y1.\n  \n  assert (PrmsSoundness ftenv tenv fenv (PS es) (PT (map snd fps)) Y1) as X1.\n  eapply (PrmsEval ftenv tenv fenv (PS es) (PT (map snd fps)) Y1).\n  unfold PrmsSoundness in X1.\n  unfold SoundPrms in X1.\n  specialize (X1 k1 env k2 s).\n  destruct X1 as [es1 X1].\n  destruct X1 as [vs k4 X1].\n  destruct X1 as [k5 X1].\n  destruct X1 as [s1 X1].\n   \n  generalize X1.\n  intro.\n\n  eapply Apply1_extended_congruence with (f:=f) in X1.\n  \n  econstructor 1 with (x:=s1).\n  \n  inversion k4; subst.\n\n  econstructor 1 with (x:=vs).\n  split.\n  \n  assert (pt = PT (map snd fps)).\n  eapply PrmsStrongTyping.\n  exact k0.\n  auto.\n  eauto.\n  auto.\n  rewrite H.\n  auto.\n\n  eapply weakenPrmsTyping in k5.\n  instantiate (1:=fenv) in k5.\n  instantiate (1:=tenv) in k5.\n  instantiate (1:=ftenv) in k5.\n  simpl in k5.\n  auto.\n  constructor.\n  auto.\n\n  exact X2.\n    \n  assert (ExpTyping ftenv tenv fenv (Apply (QF f) (PS (map Val vs))) t).\n  econstructor.\n  reflexivity.\n  auto.\n  eauto.\n  eapply weakenPrmsTyping in k5.\n  instantiate (1:=fenv) in k5.\n  instantiate (1:=tenv) in k5.\n  instantiate (1:=ftenv) in k5.\n  simpl in k5.\n  auto.\n  constructor.\n  auto.\n\n  set (Apply (QF f) (PS (map Val vs))) as e.\n\n  assert (ExpSoundness ftenv tenv fenv e t X3) as X6.\n  eapply (ExpEval ftenv tenv fenv e t X3).\n  unfold ExpSoundness in X6.\n  unfold SoundExp in X6.\n  specialize (X6 X0 env k2 s1).\n  destruct X6 as [v2 H0 X6].\n  destruct X6 as [s2 X6].\n\n  assert (EClosure fenv env (Conf Exp s (Apply (QF f) (PS es)))\n                   (Conf Exp s2 (Val v2))).\n  eapply EClosConcat.\n  exact X1.\n  auto.\n\n  assert (s' = s2 /\\ v = v2).\n  eapply ExpConfluence.\n  exact k3.\n  auto.\n  eauto.\n  eauto.\n  auto.\n  destruct H.\n  rewrite H.\n  rewrite H1.\n  auto.\nDefined.\n  \n\nEnd Invert.\n\n\n(*\nLemma BStep_convert \n      (fenv: funEnv) (env: valEnv)\n      (e1 e2: Exp) (v: Value) (s s': W) :\n  forall P, \n    (forall \n        (w1: forall (fenv: funEnv) (env: valEnv) (e:Exp) (s: W),\n             sigT (fun v: Value =>\n                 sigT (fun s': W => \n          EClosure fenv env (Conf Exp s e) (Conf Exp s' (Val v))))) \n        (w2: forall (e:Exp) (s s1 s2: W) (v1 v2: Value), \n           EClosure fenv env (Conf Exp s e) (Conf Exp s1 (Val v1)) ->\n           EClosure fenv env (Conf Exp s e) (Conf Exp s2 (Val v2)) -> \n           (s1 = s2) /\\ (v1 = v2)),\n      P fenv env e1 e2 v s s') ->\n    (forall \n        (ftenv: funTC) (tenv: valTC) \n        (k1: FEnvTyping fenv ftenv)\n        (k2: EnvTyping env tenv) (t: VTyp)\n        (k3: ExpTyping ftenv tenv fenv e1 t),\n      P fenv env e1 e2 v s s').\n  intros.\n  eapply X.\n  intros.\n  econstructor.\n  instantiate (1:= extractRunValue ftenv tenv fenv e1 t k3 k1 env k2 s).\n  econstructor.\n  instantiate (1:= extractRunState ftenv tenv fenv e1 t k3 k1 env k2 s).\n  eapply EvalIntro.\n*)  \n\n\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/DEC1/InvertA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543457, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2529321925861822}}
{"text": "(** In this file, the shape domain of Cosa is defined *)\n\nRequire Import Cosa.Lib.Header.\nRequire Import Cosa.Abstract.NumericalDomain.\nRequire Import Cosa.Abstract.Lang.\nRequire Import Cosa.Shape.Summary.\nRequire Import Cosa.Shape.Graph.\nRequire Import Cosa.Interaction.Interaction.\nRequire Import Cosa.Interaction.Rule.\nRequire Import Cosa.Shape.ShapeDomainSig.\n\n(* WORK IN PROGRESS *)\n\nSection Domain.\n\n  Variable num_dom : NumericalDomain.t Graph.node.\n  Variable ind_env : Summary.env.\n\n  (** Domain signature *)\n  Record t := {\n     carrier :> Type ;\n     γ : carrier -> ℘ (cenv*ConcreteFragment.fragment) ;\n\n     inclusion : Rule.rule_set (carrier*carrier) (carrier*carrier) ;\n     inclusion_correct : forall g₁ g₂, Proof_of (deductive inclusion) (g₁,g₂) -> γ g₁ ⊆ γ g₂\n     (** More operations here. *)\n  }.\n\n  (** inclusion is not fully implemented yet. We replace it by a dummy [Rule_set]\n      in which there are no proofs. *)\n  Definition inclusion_rules {S} : Rule.rule_set S S := {|\n    Rule := Empty_set ;\n    action := fun magic => match magic with end\n  |}.\n\n  Program Definition make : t := {|\n     carrier := ShapeDomainSig.t num_dom ind_env ;\n     γ := ShapeDomainSig.γ ;\n\n     inclusion := inclusion_rules\n  |}.\n  Next Obligation. (** inclusion_correct *)\n    destruct X.\n    simpl in c.\n    destruct c as [ [] ? ].\n  Qed. (** it is true, though as inclusion is a dummy, irrelevant. *)\n\nEnd Domain.", "meta": {"author": "aspiwack", "repo": "cosa", "sha": "2d808236e71f2289033dff6b74a3f57311df9a14", "save_path": "github-repos/coq/aspiwack-cosa", "path": "github-repos/coq/aspiwack-cosa/cosa-2d808236e71f2289033dff6b74a3f57311df9a14/Shape/ShapeDomain.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.25286930293536025}}
{"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_signextend ===== *)\n\nDefinition bit_blast_signextend n (g: generator) (ls: word) : generator * cnf * word :=\n  (g, [::], cat ls (nseq n (msl ls))) .\n\nDefinition mk_env_signextend n (E: env) (g: generator) (ls: word) : env * generator * cnf * word :=\n  (E, g, [::], cat ls (nseq n (msl ls))) .\n\nLemma bit_blast_signextend_correct n g bs E ls g' cs lrs :\n  bit_blast_signextend n g ls = (g', cs, lrs) ->\n  enc_bits E ls bs ->\n  interp_cnf E (add_prelude cs) ->\n  enc_bits E lrs (sext n bs).\nProof.\n  rewrite /bit_blast_signextend.\n  case=> _ <- <- /= => Henc Hicnf.\n  rewrite /sext.\n  rewrite /msl /msb /=.\n  move: (add_prelude_enc_bit_ff Hicnf) => Hff.\n  move: (enc_bit_lastd Hff Henc) => Hlastd.\n  move: Henc (enc_bits_copy n Hlastd).\n  exact: enc_bits_cat.\nQed.\n\nLemma mk_env_signextend_is_bit_blast_signextend n E g ls E' g' cs lrs :\n    mk_env_signextend n E g ls = (E', g', cs, lrs) ->\n    bit_blast_signextend n g ls = (g', cs, lrs).\nProof.\n  rewrite /mk_env_signextend /bit_blast_signextend.\n  intros; dcase_hyps.\n    by rewrite H0 H1 H2.\nQed.\n\nLemma mk_env_signextend_newer_gen n E g ls E' g' cs lrs :\n    mk_env_signextend n E g ls = (E', g', cs, lrs) ->\n    (g <=? g')%positive.\nProof.\n  rewrite /mk_env_signextend.\n  intros. dcase_hyps; subst.\n  exact /Pos.leb_refl.\nQed.\n\n\nLemma mk_env_signextend_newer_res n E g ls E' g' cs lrs :\n    mk_env_signextend n E g ls = (E', g', cs, lrs) ->\n    newer_than_lit g lit_tt ->\n    newer_than_lits g ls ->\n    newer_than_lits g' lrs.\nProof.\n  case=> _ <- _ <- .\n  rewrite -newer_than_lit_neg => Hg'ff .\n  move=> Hgls.\n  rewrite newer_than_lits_cat.\n  rewrite -[neg_lit lit_tt]/lit_ff in Hg'ff .\n  rewrite /msl /=.\n  rewrite (newer_than_lits_copy n (newer_than_lit_lastd Hg'ff Hgls)) .\n  by rewrite Hgls.\nQed.\n\nLemma mk_env_signextend_newer_cnf n E g ls E' g' cs lrs :\n    mk_env_signextend n E g ls = (E', g', cs, lrs) ->\n    newer_than_lit g lit_tt ->\n    newer_than_lits g ls ->\n    newer_than_cnf g' cs.\nProof.\n    by case=> _ <- <- _ .\nQed.\n\nLemma mk_env_signextend_preserve n E g ls E' g' cs lrs :\n    mk_env_signextend n E g ls = (E', g', cs, lrs) ->\n    env_preserve E E' g.\nProof.\n    by case=> <- _ _ _ .\nQed.\n\nLemma mk_env_signextend_sat n E g ls E' g' cs lrs :\n    mk_env_signextend n E g ls = (E', g', cs, lrs) ->\n    newer_than_lit g lit_tt ->\n    newer_than_lits g ls ->\n    interp_cnf E' cs.\nProof.\n    by case=> <- _ <- _ .\nQed.\n\nLemma mk_env_signextend_env_equal E1 E2 g n ls E1' E2' g1 g2 cs1 cs2 lrs1 lrs2 :\n  env_equal E1 E2 ->\n  mk_env_signextend n E1 g ls = (E1', g1, cs1, lrs1) ->\n  mk_env_signextend n E2 g ls = (E2', g2, cs2, lrs2) ->\n  env_equal E1' E2' /\\ g1 = g2 /\\ cs1 = cs2 /\\ lrs1 = lrs2.\nProof.\n  rewrite /mk_env_signextend => 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/BBSignExtend.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.25286930293536025}}
{"text": "Set Implicit Arguments.\n\nSection ADTValue.\n\n  Variable ADTValue : Type.\n\n  Require Import Bedrock.Platform.Cito.Transit.\n  Require Import Bedrock.Platform.Cito.Semantics.\n\n  Require Import Bedrock.Platform.Cito.Syntax.\n  Require Import Bedrock.Platform.Cito.GLabel.\n  Require Import Bedrock.Platform.Cito.GLabelMap.\n  Import GLabelMap.\n  Require Import Bedrock.Platform.Cito.SemanticsExpr.\n  Require Import Bedrock.Platform.Cito.GeneralTactics Bedrock.Platform.Cito.GeneralTactics2 Bedrock.Platform.Cito.GeneralTactics3.\n\n  Notation Callee := (@Callee ADTValue).\n\n  Definition Specs := GLabelMap.t Callee.\n\n  Definition f_var := \"_f\".\n\n  Notation State := (@State ADTValue).\n\n  Definition RunsToDCall specs retvar f args (v v' : State) :=\n    match find f specs with\n      | Some (Semantics.Foreign spec) =>\n        exists inputs outputs ret_w ret_a f_w,\n          let vs := upd (fst v) f_var f_w in\n          TransitTo spec (List.map (eval vs) args) inputs outputs ret_w ret_a (snd v) (snd v') /\\\n          fst v' = upd_option vs retvar ret_w\n      | _ => True\n    end.\n\n  Definition SafeDCall specs f args (v : State) :=\n    match find f specs with\n      | Some (Semantics.Foreign spec) =>\n        forall f_w,\n          let vs := upd (fst v) f_var f_w in\n          exists inputs, TransitSafe spec (List.map (eval vs) args) inputs (snd v)\n      | _ => False\n    end.\n\n  (* shallow embedding *)\n  Definition assert := Specs -> State -> State -> Prop.\n  Definition entailment := Specs -> Prop.\n\n  Inductive StmtEx :=\n  | SkipEx : StmtEx\n  | SeqEx : StmtEx -> StmtEx -> StmtEx\n  | IfEx : Expr -> StmtEx -> StmtEx -> StmtEx\n  | WhileEx : assert -> Expr -> StmtEx -> StmtEx\n  | AssignEx : string -> Expr -> StmtEx\n  | AssertEx : assert -> StmtEx\n  | DCallEx : option string -> glabel -> list Expr -> StmtEx.\n\n  Definition and_lift (a b : assert) : assert := fun specs v v' => a specs v v' /\\ b specs v v'.\n  Definition or_lift (a b : assert) : assert := fun specs v v' => a specs v v' \\/ b specs v v'.\n  Definition imply_close (a b : assert) : entailment := fun specs => forall v v', a specs v v' -> b specs v v'.\n\n  Infix \"/\\\" := and_lift : assert_scope.\n  Infix \"\\/\" := or_lift : assert_scope.\n  Infix \"-->\" := imply_close (at level 90) : assert_scope.\n\n  Close Scope equiv_scope.\n\n  Definition is_true e : assert := fun _ _ v => eval (fst v) e <> $0.\n  Definition is_false e : assert := fun _ _ v => eval (fst v) e = $0.\n\n  Open Scope assert_scope.\n\n  Fixpoint to_stmt s :=\n    match s with\n      | SkipEx => Syntax.Skip\n      | SeqEx a b => Syntax.Seq (to_stmt a) (to_stmt b)\n      | IfEx e t f => Syntax.If e (to_stmt t) (to_stmt f)\n      | WhileEx _ e b => Syntax.While e (to_stmt b)\n      | AssignEx x e => Syntax.Assign x e\n      | AssertEx _ => Syntax.Skip\n      | DCallEx x f args => Syntax.Seq (Syntax.Label f_var f) (Syntax.Call x (Var f_var) args)\n    end.\n\n  Coercion to_stmt : StmtEx >-> Stmt.\n\n  Fixpoint sp (stmt : StmtEx) (p : assert) : assert :=\n    match stmt with\n      | SeqEx a b => sp b (sp a p)\n      | IfEx e t f => sp t (p /\\ is_true e) \\/ sp f (p /\\ is_false e)\n      | WhileEx inv e _ => inv /\\ is_false e\n      | AssertEx a => a\n      | SkipEx => p\n      | AssignEx x e =>\n        (fun specs v0 v' =>\n           exists v,\n             p specs v0 v /\\\n             v' = (upd (fst v) x (eval (fst v) e), snd v))%type\n      | DCallEx x f args =>\n        (fun specs v0 v' =>\n           exists v,\n             p specs v0 v /\\\n             RunsToDCall specs x f args v v')%type\n    end.\n\n  Fixpoint vc stmt (p : assert) : list entailment :=\n    match stmt with\n      | SeqEx a b => vc a p ++ vc b (sp a p)\n      | IfEx e t f => vc t (p /\\ is_true e) ++ vc f (p /\\ is_false e)\n      | WhileEx inv e body =>\n        (p --> inv) :: (sp body (inv /\\ is_true e) --> inv) :: vc body (inv /\\ is_true e)\n      | AssertEx a => (p --> a) :: nil\n      | SkipEx => nil\n      | AssignEx _ _ => nil\n      | DCallEx x f args => (p --> (fun specs _ v => SafeDCall specs f args v)) :: nil\n    end.\n\n  Definition and_all : list entailment -> entailment := fold_right (fun a b specs => a specs /\\ b specs)%type (fun _ => True).\n\n  Lemma and_all_app : forall ls1 ls2 specs, and_all (ls1 ++ ls2) specs -> and_all ls1 specs /\\ and_all ls2 specs.\n    induction ls1; simpl; intuition.\n    eapply IHls1 in H1; openhyp; eauto.\n    eapply IHls1 in H1; openhyp; eauto.\n  Qed.\n\n  Lemma is_true_intro : forall e specs v v', wneb (eval (fst v') e) $0 = true -> (is_true e) specs v v'.\n    intros.\n    unfold is_true.\n    unfold wneb in *.\n    destruct (weq _ _) in *; intuition.\n  Qed.\n\n  Hint Resolve is_true_intro.\n\n  Lemma is_false_intro : forall e specs v v', wneb (eval (fst v') e) $0 = false -> (is_false e) specs v v'.\n    intros.\n    unfold is_false.\n    unfold wneb in *.\n    destruct (weq _ _) in *; intuition.\n  Qed.\n\n  Hint Resolve is_false_intro.\n\n  Hint Constructors Semantics.RunsTo.\n  Hint Constructors Semantics.Safe.\n\n  Ltac inject :=\n    match goal with\n      | H : _ = _ |- _ => unfold_all; injection H; intros; subst\n    end.\n\n  Definition Env := ((glabel -> option W) * (W -> option Callee))%type.\n\n  Open Scope type.\n\n  Definition specs_fs_agree (specs : Specs) (env : Env) :=\n    let labels := fst env in\n    let fs := snd env in\n    forall p spec,\n      fs p = Some spec <->\n      exists (lbl : glabel),\n        labels lbl = Some p /\\\n        find lbl specs = Some spec.\n\n  Definition labels_in_scope (specs : Specs) (labels : glabel -> option W) :=\n    forall lbl, In lbl specs -> labels lbl <> None.\n\n  Definition specs_stn_injective (specs : Specs) stn := forall lbl1 lbl2 (w : W), In lbl1 specs -> In lbl2 specs -> stn lbl1 = Some w -> stn lbl2 = Some w -> lbl1 = lbl2.\n\n  Definition specs_env_agree (specs : Specs) (env : Env) :=\n    labels_in_scope specs (fst env) /\\\n    specs_stn_injective specs (fst env) /\\\n    specs_fs_agree specs env.\n\n  Require Import Bedrock.Platform.Cito.GLabelMapFacts.\n  Require Import Bedrock.Platform.Cito.Option.\n\n  Require Import Bedrock.Platform.Cito.BedrockTactics.\n\n  Lemma RunsTo_RunsToDCall :\n    forall specs env r f args v v',\n      specs_env_agree specs env ->\n      RunsTo env (DCallEx r f args) v v' ->\n      RunsToDCall specs r f args v v'.\n  Proof.\n    intros.\n    simpl in *.\n    unfold RunsToDCall.\n    inv_clear H0.\n    inv_clear H3.\n    destruct (option_dec(find f specs)).\n    destruct s; rewrite e; simpl in *.\n    destruct x; simpl in *.\n    destruct H; simpl in *.\n    destruct env; simpl in *.\n    rename a into f0.\n    assert (o0 w = Some (Foreign f0)).\n    eapply H0.\n    descend; eauto.\n    generalize H6; intro HH.\n    inv_clear H6; simpl in *.\n    sel_upd_simpl; rewrite H7 in H1; discriminate.\n    sel_upd_simpl; rewrite H7 in H1; injection H1; intros; subst.\n    eapply RunsTo_TransitTo in HH.\n    Focus 2.\n    simpl; sel_upd_simpl; eauto.\n    openhyp.\n    destruct r; simpl in *.\n    subst; simpl in *.\n    descend.\n    eauto.\n    sel_upd_simpl; eauto.\n    descend.\n    eauto.\n    eauto.\n    eauto.\n    rewrite e; eauto.\n  Qed.\n\n  Lemma SafeDCall_Safe :\n    forall specs env r f args v,\n      specs_env_agree specs env ->\n      SafeDCall specs f args v ->\n      Safe env (DCallEx r f args) v.\n  Proof.\n    intros.\n    destruct H.\n    destruct env; simpl in *.\n    unfold SafeDCall in *.\n    destruct (option_dec(find f specs)).\n    destruct s; rewrite e in *; simpl in *.\n    destruct x.\n    econstructor.\n    econstructor.\n    eapply H.\n    eapply MapsTo_In; eapply find_mapsto_iff; eauto.\n    intros.\n    inv_clear H2.\n    specialize (H0 w); clear H.\n    destruct H0 as [inputs Htsf].\n    eapply TransitSafe_Safe; eauto.\n    sel_upd_simpl.\n    eapply H1.\n    descend; eauto.\n    intuition.\n    rewrite e in *; eauto.\n    intuition.\n  Qed.\n\n  Lemma sound_runsto' : forall env (s : Stmt) v v', RunsTo env s v v' -> forall s' : StmtEx, s = s' -> forall specs, specs_env_agree specs env -> forall p, and_all (vc s' p) specs -> forall v0, p specs v0 v -> (sp s' p) specs v0 v'.\n    induction 1; simpl; intros; destruct s'; try discriminate; simpl in *; try inject.\n\n    (* skip *)\n    eauto.\n\n    openhyp.\n    eauto.\n\n    (* seq *)\n    eapply_in_any and_all_app; openhyp.\n    eauto.\n\n    (* call *)\n    openhyp.\n    descend.\n    eauto.\n    eapply RunsTo_RunsToDCall; simpl; eauto.\n\n    (* if *)\n    eapply_in_any and_all_app; openhyp.\n    left.\n    eapply IHRunsTo; eauto.\n    split; eauto.\n\n    eapply_in_any and_all_app; openhyp.\n    right.\n    eapply IHRunsTo; eauto.\n    split; eauto.\n\n    (* while *)\n    openhyp.\n    eapply (IHRunsTo2 (WhileEx _ e s')); simpl in *; eauto.\n    eapply IHRunsTo1; simpl in *; eauto.\n    split; eauto.\n\n    openhyp.\n    split; eauto.\n\n    (* assign *)\n    descend; eauto.\n  Qed.\n\n  Theorem sound_runsto : forall env (s : StmtEx) v v' specs p, RunsTo env s v v' -> specs_env_agree specs env -> and_all (vc s p) specs -> p specs v v -> (sp s p) specs v v'.\n    intros.\n    eapply sound_runsto'; eauto.\n  Qed.\n\n  Close Scope assert_scope.\n\n  Theorem sound_safe : forall specs env (s : Stmt) (s' : StmtEx) v p v0, s = s' -> specs_env_agree specs env -> and_all (vc s' p) specs -> p specs v0 v -> Safe env s v.\n    intros.\n    eapply (Safe_coind (fun s v => Safe env s v \\/ exists (s' : StmtEx) p v0, s = s' /\\ and_all (vc s' p) specs /\\ p specs v0 v)); [ .. | right; descend; eauto]; generalize H0; clear; intros; openhyp.\n\n    (* seq *)\n    inversion H; subst.\n    descend; left; eauto.\n\n    destruct x; try discriminate; simpl in *; try inject.\n    eapply_in_any and_all_app; openhyp.\n    descend.\n    right; descend; eauto.\n    intros.\n    eapply sound_runsto' with (p := x0) in H4; eauto.\n    right; descend; eauto.\n\n    (* dcall *)\n\n    openhyp.\n    eapply H1 in H2.\n    eapply SafeDCall_Safe in H2; eauto.\n    simpl in *.\n    inv_clear H2.\n    split.\n    eauto.\n    intros.\n    eauto.\n\n    (* if *)\n    inversion H; subst.\n    openhyp; subst.\n    left; descend.\n    eauto.\n    left; eauto.\n    right; descend.\n    eauto.\n    left; eauto.\n\n    destruct x; try discriminate; simpl in *; try inject.\n    eapply_in_any and_all_app; openhyp.\n    unfold wneb.\n    destruct (weq (eval (fst v) e) $0) in *.\n    right.\n    descend; eauto.\n    right; descend; eauto.\n    split; eauto.\n    left.\n    descend; eauto.\n    right; descend; eauto.\n    split; eauto.\n\n    (* while *)\n    inversion H; unfold_all; subst.\n    left; descend.\n    eauto.\n    left; eauto.\n    left; eauto.\n    right; eauto.\n\n    destruct x; try discriminate; simpl in *; try inject.\n    openhyp.\n    unfold wneb.\n    destruct (weq (eval (fst v) e) $0) in *.\n    right.\n    eauto.\n    left.\n    descend; eauto.\n    right.\n    descend; eauto.\n    split; eauto.\n    right.\n    eapply sound_runsto' with (p := and_lift a (is_true e)) in H5; eauto.\n    descend.\n    instantiate (1 := WhileEx _ e x).\n    eauto.\n    2 : eauto.\n    simpl.\n    descend; eauto.\n    split; eauto.\n\n    (* call *)\n    inversion H; unfold_all; subst.\n    left; descend; eauto.\n    right; descend; eauto.\n\n    destruct x; try discriminate; simpl in *; try inject.\n\n    (* label *)\n    inversion H; unfold_all; subst.\n    eauto.\n\n    destruct x0; try discriminate; simpl in *; try inject.\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/ProgramLogic2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160664, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2528693029353602}}
{"text": "Require Import OrderedTypeEx.\nRequire Import StoreIface.\nRequire Import BasicMachineTypes.\nRequire Import AnnotationIface.\nRequire Import List.\nRequire Import ZArith.\n\nModule Type CLASSDATATYPES\n  (C_B : BASICS)\n  (C_A : ANNOTATION C_B).\n\n(***************************\n * Various notions of type\n ***************************)\nInductive array_type : Set :=\n aty_boolean | aty_char | aty_float | aty_double | aty_byte | aty_short | aty_int | aty_long : array_type.\n\nInductive stack_type : Set :=\n sty_int | sty_long | sty_double | sty_float | sty_addr.\n\nInductive java_type : Set :=\n| ty_byte\n| ty_char\n| ty_double\n| ty_float\n| ty_int\n| ty_long\n| ty_boolean\n| ty_short : java_type\n| ty_ref : java_ref_type -> java_type\nwith java_ref_type : Set :=\n| ty_obj : C_B.Classname.t -> java_ref_type\n| ty_arr : java_type -> java_ref_type.\n\nDeclare Module JavaType_as_UOT : UsualOrderedType with Definition t := java_type.\n\nInductive value_category : Set := category1 | category2.\n\nDefinition java_type_category : java_type -> value_category :=\n  fun ty => match ty with\n  | ty_byte => category1\n  | ty_char => category1\n  | ty_short => category1\n  | ty_boolean => category1\n  | ty_int => category1\n  | ty_float => category1\n  | ty_ref _ => category1\n  | ty_double => category2\n  | ty_long => category2\n  end.\n\nDefinition stack_type_category : stack_type -> value_category :=\n  fun ty => match ty with\n  | sty_int => category1\n  | sty_float => category1\n  | sty_double => category2\n  | sty_addr => category1\n  | sty_long => category2\n  end.\n\n(**********************\n * The instructions\n **********************)\n\n(* Constants *)\nInductive double_constant : Set := d0 | d1 : double_constant.\nInductive float_constant : Set := f0 | f1 | f2 : float_constant.\nInductive long_constant : Set := l0 | l1 : long_constant.\n\n(* Comparison operations *)\nInductive acmp : Set := acmp_eq | acmp_ne : acmp.\nInductive cmp : Set := cmp_eq | cmp_ne | cmp_lt | cmp_ge | cmp_gt | cmp_le : cmp.\nInductive float_cmp_opt : Set := fcmp_l | fcmp_g : float_cmp_opt.\n\n(* Arithmetic operations *)\nInductive integer_bop : Set :=\n iadd | idiv | iand | imul | ior | irem | ishl | ishr | isub | iushr | ixor : integer_bop.\n\nInductive integer_uop : Set :=\n ineg : integer_uop.\n\nInductive float_bop : Set :=\n fadd | fdiv | fmul | frem | fsub : float_bop.\n\nInductive float_uop : Set :=\n fneg : float_uop.\n\nInductive opcode : Set :=\n(* Arithmetic *)\n| op_iarithb : integer_bop -> opcode\n| op_iarithu : integer_uop -> opcode\n| op_larithb : integer_bop -> opcode\n| op_larithu : integer_uop -> opcode\n| op_iinc    : nat -> C_B.Int32.t -> opcode\n| op_darithb : float_bop -> opcode\n| op_darithu : float_uop -> opcode\n| op_farithb : float_bop -> opcode\n| op_farithu : float_uop -> opcode\n\n(* Stack Operations *)\n| op_dup     : opcode\n| op_dup_x1  : opcode\n| op_dup_x2  : opcode\n| op_dup2    : opcode\n| op_dup2_x1 : opcode\n| op_dup2_x2 : opcode\n| op_nop     : opcode\n| op_pop     : opcode\n| op_pop2    : opcode\n| op_swap    : opcode\n\n(* Local Variables *)\n| op_load   : stack_type -> nat -> opcode\n| op_store  : stack_type -> nat -> opcode\n\n(* OO *)\n| op_instanceof      : C_B.ConstantPoolRef.t -> opcode\n| op_invokeinterface : C_B.ConstantPoolRef.t -> opcode\n| op_invokespecial   : C_B.ConstantPoolRef.t -> opcode\n| op_invokestatic    : C_B.ConstantPoolRef.t -> opcode\n| op_invokevirtual   : C_B.ConstantPoolRef.t -> opcode\n| op_aconst_null     : opcode\n| op_checkcast       : C_B.ConstantPoolRef.t -> opcode\n| op_getfield        : C_B.ConstantPoolRef.t -> opcode\n| op_getstatic       : C_B.ConstantPoolRef.t -> opcode\n| op_new             : C_B.ConstantPoolRef.t -> opcode\n| op_putfield        : C_B.ConstantPoolRef.t -> opcode\n| op_putstatic       : C_B.ConstantPoolRef.t -> opcode\n\n(* Comparisons and flow control *)\n| op_if_acmp : acmp -> Z -> opcode\n| op_if_icmp : cmp -> Z -> opcode\n| op_if      : cmp -> Z -> opcode\n| op_ifnonnull : Z -> opcode\n| op_ifnull  : Z -> opcode\n| op_goto    : Z -> opcode\n| op_valreturn : stack_type -> opcode\n| op_return  : opcode\n| op_athrow  : opcode\n| op_dcmp    : float_cmp_opt -> opcode\n| op_fcmp    : float_cmp_opt -> opcode\n| op_lcmp    : opcode\n| op_lookupswitch : Z -> Z -> list (Z * Z) -> opcode\n| op_tableswitch : Z -> Z -> Z -> list Z -> opcode\n\n(* Arrays *)\n| op_iaload  : opcode\n| op_iastore : opcode\n| op_aaload  : opcode\n| op_aastore : opcode\n| op_anewarray : C_B.ConstantPoolRef.t -> opcode\n| op_arraylength : opcode\n| op_baload  : opcode\n| op_bastore : opcode\n| op_caload  : opcode\n| op_castore : opcode\n| op_daload  : opcode\n| op_dastore : opcode\n| op_faload  : opcode\n| op_fastore : opcode\n| op_laload  : opcode\n| op_lastore : opcode\n| op_multianewarray : C_B.ConstantPoolRef.t -> nat -> opcode\n| op_newarray : array_type -> opcode\n| op_saload  : opcode\n| op_sastore : opcode\n\n(* Constants *)\n| op_iconst : C_B.Int32.t -> opcode\n| op_dconst : double_constant -> opcode\n| op_fconst : float_constant -> opcode\n| op_lconst : long_constant -> opcode\n| op_ldc    : C_B.ConstantPoolRef.t -> opcode\n| op_ldc2   : C_B.ConstantPoolRef.t -> opcode\n\n(* Concurrency *)\n| op_monitorenter : opcode\n| op_monitorexit  : opcode\n\n(* Conversions *)\n| op_i2b    : opcode\n| op_i2c    : opcode\n| op_i2d    : opcode\n| op_i2f    : opcode\n| op_i2l    : opcode\n| op_i2s    : opcode\n| op_d2f    : opcode\n| op_d2i    : opcode\n| op_d2l    : opcode\n| op_f2d    : opcode\n| op_f2i    : opcode\n| op_f2l    : opcode\n| op_l2d    : opcode\n| op_l2f    : opcode\n| op_l2i    : opcode.\n\n(*************************\n * Some functions for dealing with the program counter\n *************************)\nParameter pc_plus_offset : nat -> Z -> option nat.\n(* for checking if the current program counter is in the range of an exception handler *)\nParameter is_within : forall s e p, ({p >= s /\\ p < e} + {p < s \\/ p >= e})%nat.\n\n(*************************\n * The structure of classes\n *************************)\nRecord descriptor : Set := mkDescriptor\n { descriptor_ret_type : option java_type\n ; descriptor_arg_types : list java_type\n }.\n\nDeclare Module Descriptor_as_UOT : UsualOrderedType with Definition t := descriptor.\n\nRecord exception_handler : Set := mkExcHandler\n  { exc_start_pc : nat\n  ; exc_end_pc   : nat\n  ; exc_handler_pc : nat\n  ; exc_catch_type : option C_B.ConstantPoolRef.t\n  }.\n\nRecord precode : Type := mkPreCode\n  { precode_max_stack       : nat\n  ; precode_max_lvars       : nat\n  ; precode_code            : list opcode            (* FIXME: need a better representation than lists *)\n  ; precode_exception_table : list exception_handler\n  ; precode_annot           : C_A.code_annotation\n  }. (* + certificate *)\n\nRecord code : Set := mkCode\n  { code_max_stack       : nat\n  ; code_max_lvars       : nat\n  ; code_code            : list opcode            (* FIXME: need a better representation than lists *)\n  ; code_exception_table : list exception_handler\n  }. (* + certificate *)\n\nRecord premethod : Type := mkPreMethod\n  { premethod_name         : C_B.Methodname.t\n  ; premethod_descriptor   : descriptor\n  ; premethod_public       : bool\n  ; premethod_protected    : bool\n  ; premethod_private      : bool\n  ; premethod_abstract     : bool (* if this is false, and the code does not exist, then the method is native *)\n  ; premethod_static       : bool\n  ; premethod_final        : bool\n  ; premethod_synchronized : bool\n  ; premethod_strict       : bool\n  ; premethod_code         : option precode\n  ; premethod_annot        : C_A.method_annotation\n  }. (* + attributes *)\n\nRecord method : Type := mkMethod\n  { method_name         : C_B.Methodname.t\n  ; method_descriptor   : descriptor\n  ; method_public       : bool\n  ; method_protected    : bool\n  ; method_private      : bool\n  ; method_abstract     : bool (* if this is false, and the code does not exist, then the method is native *)\n  ; method_static       : bool\n  ; method_final        : bool\n  ; method_synchronized : bool\n  ; method_strict       : bool\n  ; method_code         : option code\n  ; method_annot        : C_A.method_annotation\n  }. (* + attributes *)\n\nDeclare Module MethodList : STORE with Definition key := (C_B.Methodname.t * descriptor)%type\n                                  with Definition object := method\n                                  with Definition Key.eq := (@eq (C_B.Methodname.t * descriptor)).\n\nRecord field : Set := mkField\n  { field_name      : C_B.Fieldname.t\n  ; field_type      : java_type\n  ; field_public    : bool\n  ; field_private   : bool\n  ; field_protected : bool\n  ; field_static    : bool\n  ; field_final     : bool\n  ; field_volatile  : bool\n  ; field_transient : bool\n  }. (* + attributes (ConstantValue) *)\n\nDeclare Module FieldList : STORE with Definition key := (C_B.Fieldname.t * java_type)%type\n                                 with Definition object := field.\n\nInductive constantpool_entry : Set :=\n| cpe_methodref : C_B.Classname.t -> C_B.Methodname.t -> descriptor -> constantpool_entry\n| cpe_interfacemethodref : C_B.Classname.t -> C_B.Methodname.t -> descriptor -> constantpool_entry\n| cpe_fieldref  : C_B.Classname.t -> C_B.Fieldname.t -> java_type -> constantpool_entry\n| cpe_int       : C_B.Int32.t -> constantpool_entry\n| cpe_classref  : C_B.Classname.t -> constantpool_entry\n| cpe_other     : constantpool_entry.\n\nDeclare Module ConstantPool : STORE with Definition key := C_B.ConstantPoolRef.t\n                                    with Definition object := constantpool_entry.\n\nRecord preclass : Type := mkPreClass\n  { preclass_name         : C_B.Classname.t\n  ; preclass_super_name   : option C_B.Classname.t\n  ; preclass_super_interfaces : list C_B.Classname.t\n  ; preclass_public       : bool\n  ; preclass_final        : bool\n  ; preclass_super        : bool\n  ; preclass_interface    : bool\n  ; preclass_abstract     : bool\n  ; preclass_methods      : list premethod\n  ; preclass_fields       : FieldList.t\n  ; preclass_constantpool : ConstantPool.t\n  ; preclass_annotation   : C_A.class_annotation\n  }. (* + attributes *)\n\nRecord class : Type := mkClass\n  { class_name         : C_B.Classname.t\n  ; class_super_class  : option C_B.Classname.t\n  ; class_interfaces   : list C_B.Classname.t\n  ; class_public       : bool\n  ; class_final        : bool\n  ; class_super        : bool\n  ; class_interface    : bool\n  ; class_abstract     : bool\n  ; class_methods      : MethodList.t\n  ; class_fields       : FieldList.t\n  ; class_constantpool : ConstantPool.t\n  }. (* + attributes *)\n\nInductive has_premethod : list premethod -> C_B.Methodname.t * descriptor -> premethod -> Prop :=\n| has_premethod_cons_1 : forall nm d public protected private abstract static final synchronized strict code annot meths,\n   has_premethod (mkPreMethod nm d public protected private abstract static final synchronized strict code annot::meths)\n                 (nm,d)\n                 (mkPreMethod nm d public protected private abstract static final synchronized strict code annot)\n| has_premethod_cons_2 : forall nm d public protected private abstract static final synchronized strict code annot meths nm' d' m,\n   has_premethod meths (nm',d') m ->\n   (nm <> nm' \\/ d <> d') ->\n   has_premethod (mkPreMethod nm d public protected private abstract static final synchronized strict code annot::meths)\n                 (nm',d')\n                 m.\n\nHypothesis has_premethod_dec : forall ms mdesc,\n (exists m, has_premethod ms mdesc m)\\/(forall m, ~has_premethod ms mdesc m).\n\nHypothesis has_premethod_functional : forall ms mdesc mA mB,\n has_premethod ms mdesc mA ->\n has_premethod ms mdesc mB ->\n mA = mB.\n\nHypothesis has_premethod_in : forall ms m,\n  has_premethod ms (premethod_name m, premethod_descriptor m) m ->\n  In m ms.\n\nHypothesis has_premethod_name : forall ms md m,\n  has_premethod ms md m -> md = (premethod_name m, premethod_descriptor m).\nImplicit Arguments has_premethod_name [ms md m].\n\nEnd CLASSDATATYPES.\n\n\n\n\n\n\n\n\n\n\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/ClassDatatypesIface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.2528693029353602}}
{"text": "(** * Induced functors between comma categories *)\nRequire Import Category.Core Functor.Core NaturalTransformation.Core.\nRequire Import Category.Dual.\nRequire Import Category.Prod.\nRequire Import NaturalTransformation.Identity.\nRequire Import FunctorCategory.Core Cat.Core.\nRequire Import InitialTerminalCategory.Core InitialTerminalCategory.Functors.\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\".\nRequire Import Comma.Projection.\nRequire Import Types.Prod HoTT.Tactics Types.Unit.\n\nSet Universe Polymorphism.\nSet Implicit Arguments.\nGeneralizable All Variables.\nSet Asymmetric Patterns.\n\nLocal Open Scope functor_scope.\nLocal Open Scope category_scope.\n\n(** ** Morphisms in [(A → C)ᵒᵖ × (B → C)] from [(s₀, s₁)] to [(d₀, d₁)] induce functors [(s₀ / s₁) → (d₀ / d₁)] *)\nSection comma_category_induced_functor.\n  Context `{Funext}.\n  Variables A B C : PreCategory.\n\n  Definition comma_category_induced_functor_object_of s d\n             (m : morphism ((A -> C)^op * (B -> C)) s d)\n             (x : fst s / snd s)\n  : (fst d / snd d)\n    := CommaCategory.Build_object\n         (fst d) (snd d)\n         (CommaCategory.a x)\n         (CommaCategory.b x)\n         ((snd m) (CommaCategory.b x) o CommaCategory.f x o (fst m) (CommaCategory.a x)).\n\n  Lemma comma_category_induced_functor_object_of_identity s x\n  : comma_category_induced_functor_object_of (Category.Core.identity s) x\n    = x.\n  Proof.\n    let x1 := match goal with |- ?x1 = ?x2 => constr:(x1) end in\n    let x2 := match goal with |- ?x1 = ?x2 => constr:(x2) end in\n    apply (CommaCategory.path_object' x1 x2 idpath idpath).\n    simpl.\n    abstract (rewrite ?left_identity, ?right_identity; reflexivity).\n  Defined.\n\n  Definition comma_category_induced_functor_object_of_compose s d d'\n             (m : morphism ((A -> C)^op * (B -> C)) d d')\n             (m' : morphism ((A -> C)^op * (B -> C)) s d)\n             x\n  : comma_category_induced_functor_object_of (m o m') x\n    = comma_category_induced_functor_object_of\n        m\n        (comma_category_induced_functor_object_of m' x).\n  Proof.\n    let x1 := match goal with |- ?x1 = ?x2 => constr:(x1) end in\n    let x2 := match goal with |- ?x1 = ?x2 => constr:(x2) end in\n    apply (CommaCategory.path_object' x1 x2 idpath idpath).\n    abstract (\n        destruct m', m, x;\n        simpl in *;\n          rewrite !associativity;\n        reflexivity\n      ).\n  Defined.\n\n  Definition comma_category_induced_functor_morphism_of s d m s0 d0\n             (m0 : morphism (fst s / snd s) s0 d0)\n  : morphism (fst d / snd d)\n             (@comma_category_induced_functor_object_of s d m s0)\n             (@comma_category_induced_functor_object_of s d m d0).\n  Proof.\n    simpl.\n    let s := match goal with |- CommaCategory.morphism ?s ?d => constr:(s) end in\n    let d := match goal with |- CommaCategory.morphism ?s ?d => constr:(d) end in\n    refine (CommaCategory.Build_morphism s d (CommaCategory.g m0) (CommaCategory.h m0) _);\n      simpl in *; clear.\n    abstract (\n        destruct_head prod;\n        destruct_head CommaCategory.morphism;\n        destruct_head CommaCategory.object;\n        simpl in *;\n          repeat (try_associativity_quick (rewrite <- !commutes || (progress f_ap)));\n        repeat (try_associativity_quick (rewrite !commutes || (progress f_ap)));\n        assumption\n      ). (* 3.495 s *)\n  Defined.\n\n  Definition comma_category_induced_functor s d\n             (m : morphism ((A -> C)^op * (B -> C)) s d)\n  : Functor (fst s / snd s) (fst d / snd d).\n  Proof.\n    refine (Build_Functor (fst s / snd s) (fst d / snd d)\n                          (@comma_category_induced_functor_object_of s d m)\n                          (@comma_category_induced_functor_morphism_of s d m)\n                          _\n                          _\n           );\n    abstract (\n        intros; apply CommaCategory.path_morphism; reflexivity\n      ).\n  Defined.\nEnd comma_category_induced_functor.\n\n(** ** Morphisms in [C] from [a] to [a'] induce functors [(C / a) → (C / a')] *)\nSection slice_category_induced_functor.\n  Context `{Funext}.\n  Variable C : PreCategory.\n\n  Section slice_coslice.\n    Variable D : PreCategory.\n\n    (** TODO(JasonGross): See if this can be recast as an exponential law functor about how [1 → Cat] is isomorphic to [Cat], or something *)\n    Definition slice_category_induced_functor_nt s d (m : morphism D s d)\n    : NaturalTransformation !s !d.\n    Proof.\n      exists (fun _ : Unit => m);\n      simpl; intros; clear;\n      abstract (autorewrite with category; reflexivity).\n    Defined.\n\n    Variable F : Functor C D.\n    Variable a : D.\n\n    Section slice.\n      Definition slice_category_induced_functor F' a'\n                 (m : morphism D a a')\n                 (T : NaturalTransformation F' F)\n      : Functor (F / a) (F' / a')\n        := comma_category_induced_functor\n             (s := (F, !a))\n             (d := (F', !a'))\n             (T, @slice_category_induced_functor_nt a a' m).\n\n      Definition slice_category_nt_induced_functor F' T\n        := @slice_category_induced_functor F' a 1 T.\n      Definition slice_category_morphism_induced_functor a' m\n        := @slice_category_induced_functor F a' m 1.\n    End slice.\n\n    Section coslice.\n      Definition coslice_category_induced_functor F' a'\n                 (m : morphism D a' a)\n                 (T : NaturalTransformation F F')\n      : Functor (a / F) (a' / F')\n        := comma_category_induced_functor\n             (s := (!a, F))\n             (d := (!a', F'))\n             (@slice_category_induced_functor_nt a' a m, T).\n\n      Definition coslice_category_nt_induced_functor F' T\n        := @coslice_category_induced_functor F' a 1 T.\n      Definition coslice_category_morphism_induced_functor a' m\n        := @coslice_category_induced_functor F a' m 1.\n    End coslice.\n  End slice_coslice.\n\n  Definition slice_category_over_induced_functor a a' (m : morphism C a a')\n  : Functor (C / a) (C / a')\n    := Eval hnf in slice_category_morphism_induced_functor _ _ _ m.\n  Definition coslice_category_over_induced_functor a a' (m : morphism C a' a)\n  : Functor (a \\ C) (a' \\ C)\n    := Eval hnf in coslice_category_morphism_induced_functor _ _ _ m.\nEnd slice_category_induced_functor.\n\n(** ** Functors [A → A'] functors [(cat / A) → (cat / A')] *)\nSection cat_over_induced_functor.\n  Context `{Funext}.\n  Variable P : PreCategory -> Type.\n  Context `{H0 : forall C D, P C -> P D -> IsHSet (Functor C D)}.\n\n  Local Notation cat := (@sub_pre_cat _ P H0).\n\n  Definition cat_over_induced_functor a a' (m : morphism cat a a')\n  : Functor (cat / a) (cat / a')\n    := slice_category_over_induced_functor cat a a' m.\n\n  Definition over_cat_induced_functor a a' (m : morphism cat a' a)\n  : Functor (a \\ cat) (a' \\ cat)\n    := coslice_category_over_induced_functor cat a a' m.\nEnd cat_over_induced_functor.\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/Comma/InducedFunctors.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2528643982120679}}
{"text": "From iris.algebra Require Import gset coPset.\nFrom iris.proofmode Require Import tactics.\nFrom iris.base_logic.lib Require Export invariants.\nFrom iris.prelude 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))) ].\nGlobal Instance 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\nGlobal Instance: 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'.\n      - 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": "jtassarotti", "repo": "iris-inv-hierarchy", "sha": "b25fe890d72ecb5bafa9db422ece3939d99882ab", "save_path": "github-repos/coq/jtassarotti-iris-inv-hierarchy", "path": "github-repos/coq/jtassarotti-iris-inv-hierarchy/iris-inv-hierarchy-b25fe890d72ecb5bafa9db422ece3939d99882ab/iris/base_logic/lib/na_invariants.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2528643922425712}}
{"text": "Require Import GHC.Base.\nRequire Import Proofs.GHC.Base.\nRequire Import Data.Ord.\n\nFrom Coq Require Import ssreflect ssrbool ssrfun.\nSet Bullet Behavior \"Strict Subproofs\".\n\nInstance EqLaws_Down {a} `{EqLaws a} : EqLaws (Down a).\nProof.\n  split;\n  unfold op_zeze__, op_zsze__;\n  unfold Ord.Eq___Down;\n  unfold op_zeze____, op_zsze____;\n  unfold Ord.Eq___Down_op_zsze__;\n  unfold Ord.Eq___Down_op_zeze__;\n  unfold coerce, Coercible_Unpeel, unpeel, repeel, Unpeel_refl;\n  unfold \"_==_\";\n  unfold \"_/=_\".\n\n  - case=> * /=; apply Eq_refl.\n  - do 2 case=> ? //=; apply Eq_sym.\n  - do 3 case=> ? //=; apply Eq_trans.\n  - do 2 case=> ? //=; apply Eq_inv.\nQed.\n\nInstance EqExact_Down {a} `{EqExact a} : EqExact (Down a).\nProof.\n  split;\n  unfold op_zeze__, op_zsze__;\n  unfold Ord.Eq___Down;\n  unfold op_zeze____, op_zsze____;\n  unfold Ord.Eq___Down_op_zsze__;\n  unfold Ord.Eq___Down_op_zeze__;\n  unfold coerce, Coercible_Unpeel, unpeel, repeel, Unpeel_refl;\n  unfold Unpeel_arrow, Unpeel_Down, unpeel, repeel.\n  unfold Eq___Down\n     => - [x] [y] /=.\n  case E: (x == y); constructor; move/Eq_eq in E.\n  + by rewrite E.\n  + by contradict E; case: E.\nQed.\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/base-thy/Data/Ord.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.252841041507886}}
{"text": "Add LoadPath \"C:\\td202\\GitHub\\coq\\views\".\n\nRequire Import Heaps.\nRequire Import String.\nRequire Import FractionalPermissions.\nRequire Import MSets.\nRequire Import SetoidClass.\nRequire Import Tactics.\nRequire Import CountableFiniteMaps.\nRequire Import SeparationAlgebras.\nRequire Import Setof.\nRequire Import HeapSeparationAlgebra.\nRequire Import SeparationAlgebraProduct.\n\nModule CAPModel (ht : HeapTypes) .\n Module Export TheHeap := MHeaps ht.\n Module HSA := (HeapSA ht TheHeap).\n\n (* Action identifiers are pairs of string and lists of values *)\n Definition AID := (string * (list Val))%type.\n\n (* Region identifiers are natural numbers. *)\n Definition RID := nat.\n Program Instance RID_Setoid : Setoid RID.\n Program Instance RID_Countable : Countable RID.\n Solve Obligations using firstorder.\n \n\n\n (* Tokens are pairs of region idenitifer and\n    action identifier. *)\n Record Token := { tok_rid : RID; tok_aid : AID }.\n\n Module CapPSAP <: PermissionSeparationAlgebraParams.\n   Definition A := Token.\n   Definition PA := FracPerm.T.\n   Instance PA_Setoid : Setoid PA := FracPerm.FPsetoid.\n   Definition op : partial_dec_op PA := FracPerm.plus.\n   Instance PA_PermAlg : PermAlgMixin op := FracPerm.FP_pa.\n End CapPSAP.\n\n Module CapSA := PermissionSeparationAlgebra CapPSAP.\n\n Definition Cap := CapSA.S.\n\n Definition LState := (store * Cap)%type.\n\n Existing Instance prod_setoid.\n Existing Instance prod_SA.\n Definition ls_sepop := prod_sepop _ HSA.sepop _ CapSA.sepop.\n Instance ls_SA : SepAlg ls_sepop := prod_SA _ _ _ _.\n\n Definition SState := CFMap RID LState.\n \n Definition lcol (l : LState) (s : SState) : partial_val (T:=LState)\n  :=\n   cfm_dom_fold\n  (fun (X : partial_val) (a : RID) (H : cfm_def_at s a) =>\n   lift_op ls_sepop X (lift_val (cfm_def_get H))) (lift_val l).\n\n\n Definition Act := SState -> LState -> Prop.\n Definition AMod := Token -> option Act.\n\n Record wellformed (l : LState) (s : SState) (a : AMod) : Prop :=\n   {\n     wf_col_def : defined (lcol l s);\n     wf_caps_acts : forall t, None = a t -> (snd (val (lcol l s))) t == FracPerm.zero;\n     wf_act_regs : forall t, None = cfm s (tok_rid t) -> None = a t\n   }.\n\n Record world :=\n   {\n     wrld_local : LState;\n     wrld_shared : SState;\n     wrld_amod : AMod;\n     wrld_wf :> wellformed wrld_local wrld_shared wrld_amod\n   }.\n\n\n Existing Instance cfm_setoid.\n Definition world_sepop : partial_op world.\n  intros w1 w2.\n  destruct w1.\n  destruct w2.\n  set (ls_sepop wrld_local0 wrld_local1).\n  set (defined p /\\ wrld_shared0 == wrld_shared1 /\\ wrld_amod0 == wrld_amod1).\n  split.\n  exact (defined p /\\ wrld_shared0 == wrld_shared1 /\\ wrld_amod0 == wrld_amod1).\n  \n  remember (ls_sepop wrld_local0 wrld_local1).\n  destruct p.\n  \n  split.\n  \n\n HSA.sepop\n\nEnd CAPModel.", "meta": {"author": "resource-reasoning", "repo": "coq", "sha": "6561111ab25f5e956a1fe726d5e244a92f893850", "save_path": "github-repos/coq/resource-reasoning-coq", "path": "github-repos/coq/resource-reasoning-coq/coq-6561111ab25f5e956a1fe726d5e244a92f893850/CAPModel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2528410351405296}}
{"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 core_c_trivial_bigstep.\nRequire Export three_locals.\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\nGoal forall S, rtc (cstep Γ δ) S0 S -> ~ is_undef_state S.\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 [m H1].\n  inv_rcsteps H1. elim (is_Some_None HS).\n  inv_rcstep.\n  inv_rcsteps H1. elim (is_Some_None HS).\n  inv_rcstep.\n}\napply Γ_valid.\nFocus 2. {\n  destruct S as [k [] m]; try (elim (is_Some_None HS)); exact I.\n} Unfocus.\nclear HS H1 S.\n\neconstructor.\neconstructor.\n- econstructor.\n  + simpl; lia.\n  + econstructor.\n  + split.\n    * unfold int_lower.\n      simpl.\n      lia.\n    * unfold int_upper.\n      simpl.\n      lia.\n- econstructor.\n  econstructor.\n  + econstructor.\n    * simpl; lia.\n    * econstructor.\n    * split; try unfold int_lower; try unfold int_upper; simpl; lia.\n  + econstructor.\n    econstructor.\n    * econstructor.\n      -- simpl; lia.\n      -- econstructor.\n         reflexivity.\n      -- split; try unfold int_lower; try unfold int_upper; simpl; lia.\n    * econstructor.\n      -- econstructor.\n         reflexivity.\n      -- split; try unfold int_lower; try unfold int_upper; simpl; lia.\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/three_locals_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.25275323619293016}}
{"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 MemoryFacts.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\n\nSet Implicit Arguments.\n\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; try refl.\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; try refl.\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 lc1.(Local.promises))\n      (RESERVE: msg <> Message.reserve):\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. intros x.\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; ss.\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-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/lang/Progress.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2527532308330863}}
{"text": "Require Import Framework TotalMem FSParameters CachedDiskLayer.\nRequire Import Log Log.RepImplications Specs LogCache LoggedDiskLayer LogCacheToLoggedDisk.Definitions.\nRequire Import ClassicalFacts FunctionalExtensionality Lia Eqdep.\n\nSet Nested Proofs Allowed.\n\nLocal Notation \"'imp'\" := CachedDiskLang.\nLocal Notation \"'abs'\" := (LoggedDiskLang log_length data_length).\nLocal Notation \"'refinement'\" := LoggedDiskRefinement.\n\n\n  Definition cached_disk_reboot_list l_selector : list (imp.(state) -> imp.(state)) :=\n    (map (fun selector (s: imp.(state)) =>\n            (empty_mem, (fst (snd s), select_total_mem selector (snd (snd s)))))\n         l_selector).\n\n  Definition logged_disk_reboot_list n := repeat (fun s : abs.(state) => s) n.\n\n  Ltac unify_execs :=\n    match goal with\n    |[H : exec_with_recovery ?u ?x ?y ?z ?a ?b ?c _,\n      H0 : exec_with_recovery ?u ?x ?y ?z ?a ?b ?c _ |- _ ] =>\n     eapply exec_with_recovery_deterministic_wrt_reboot_state in H; [| apply H0]\n    | [ H: exec ?u ?x ?y ?z ?a _,\n        H0: exec ?u ?x ?y ?z ?a _ |- _ ] =>\n      eapply exec_deterministic_wrt_oracle in H; [| apply H0]\n    | [ H: exec' ?u ?x ?y ?z _,\n        H0: exec' ?u ?x ?y ?z _ |- _ ] =>\n      eapply exec_deterministic_wrt_oracle in H; [| apply H0]\n    | [ H: exec _ ?u ?x ?y ?z _,\n        H0: LayerImplementation.exec' ?u ?x ?y ?z _ |- _ ] =>\n      eapply exec_deterministic_wrt_oracle in H; [| apply H0]\n    end.\n  \n  Lemma recovery_oracles_refine_length:\n    forall O_imp O_abs (L_imp: Layer O_imp) (L_abs: Layer O_abs) (ref: Refinement L_imp L_abs)\n      l_o_imp l_o_abs T (u: user) s (p1: L_abs.(prog) T) rec l_rf u, \n      recovery_oracles_refine ref u s p1 rec l_rf l_o_imp l_o_abs ->\n      length l_o_imp = length l_o_abs.\n  Proof.\n    induction l_o_imp; simpl; intros; eauto.\n    tauto.\n    destruct l_o_abs; try tauto; eauto.\n  Qed.\n\n  Lemma select_mem_synced:\n    forall A AEQ V (m: @mem A AEQ (V * list V)) selector (a: A) vs,\n      select_mem selector m a = Some vs ->\n      snd vs = nil.\n  Proof.\n    unfold select_mem; intros.\n    destruct (m a); try congruence.\n    inversion H; simpl; eauto.\n  Qed.\n\n  Lemma map_addr_list_eq_map_map:\n    forall txns s hdr_state log_state valid_part hdr hdr_blockset log_blocksets,\n      log_rep_explicit hdr_state log_state valid_part hdr txns hdr_blockset log_blocksets s ->\n      map addr_list txns =\n      map (map (Init.Nat.add data_start))\n          (map (map (fun a => a - data_start)) (map addr_list txns)).\n  Proof.\n    intros.\n    repeat rewrite map_map.\n    apply map_ext_in.\n    intros.\n    rewrite map_map.\n    rewrite map_noop; eauto.\n    intros.\n    unfold log_rep_explicit, log_rep_inner, txns_valid in *;\n    simpl in *; cleanup_no_match.\n    eapply Forall_forall in H9; eauto.\n    unfold txn_well_formed in H9; simpl in *; cleanup_no_match.\n    eapply Forall_forall in H13; eauto; lia.\n  Qed.\n\n  \n\n  Lemma sumbool_agree_addr_dec:\n    forall n x y,\n      sumbool_agree (addr_dec x y) (addr_dec (n + x) (n + y)).\n  Proof.\n    unfold sumbool_agree; intros; intuition eauto.\n    destruct (addr_dec x y);\n    destruct (addr_dec (n + x) (n + y)); eauto;\n    try congruence; try lia.\n  Qed.\n  \n  Theorem abstract_oracles_exist_wrt_recover:\n    forall l_selector u, \n      abstract_oracles_exist_wrt refinement refines_reboot u (|Recover|) (|Recover|) (cached_disk_reboot_list l_selector).\n  Proof.\n    unfold abstract_oracles_exist_wrt, refines_reboot; induction l_selector;\n    simpl; intros; cleanup; invert_exec.\n    {\n      exists  [ [OpToken (LoggedDiskOperation log_length data_length) Cont] ]; simpl.\n      intuition eauto.\n      left.\n      eexists; intuition eauto.\n      destruct t.\n      eexists; intuition eauto.\n      eexists; intuition eauto.\n      left.\n      eexists; intuition eauto.\n      eapply_fresh recover_finished in H8; eauto.\n    }\n    { \n      eapply IHl_selector in H12; eauto; cleanup.\n      exists ([OpToken (LoggedDiskOperation log_length data_length) CrashBefore]::x0); simpl.\n      repeat split; eauto; try (unify_execs; cleanup).\n      eapply recovery_oracles_refine_length in H0; eauto.\n      right.\n      eexists; repeat split; eauto.\n      eexists; repeat split; eauto.\n      right.\n      eexists; repeat split; eauto.\n      intros.\n      eapply_fresh recover_crashed in H11; eauto.\n      logic_clean; eauto.\n      eauto.\n      \n      eapply_fresh recover_crashed in H11; eauto.\n      cleanup; repeat split_ors;\n      simpl in *; unfold cached_log_reboot_rep in H0;\n      cleanup;\n      try eapply reboot_rep_to_reboot_rep in H0;\n      try eapply crash_rep_recover_to_reboot_rep in H0;\n      try eapply log_rep_to_reboot_rep in H0;\n      eexists; unfold cached_log_reboot_rep; simpl;\n      eexists; intuition eauto;\n      match goal with\n      |[H: select_total_mem _ _ _ = _ |- _ ]=>\n       eapply select_total_mem_synced in H\n      end; eauto.\n    }\n  Qed.\n\n  Theorem abstract_oracles_exist_wrt_recover':\n    forall l_selector u, \n      abstract_oracles_exist_wrt refinement refines u (|Recover|) (|Recover|) (cached_disk_reboot_list l_selector).\n  Proof.\n    unfold abstract_oracles_exist_wrt, refines_reboot; induction l_selector;\n    simpl; intros; cleanup; invert_exec.\n    {\n      exists  [ [OpToken (LoggedDiskOperation log_length data_length) Cont] ]; simpl.\n      intuition eauto.\n      destruct t.\n      left.\n      eexists; intuition eauto.\n      eexists; intuition eauto.\n      eexists; intuition eauto.\n      unfold refines, cached_log_reboot_rep in *; cleanup.\n      left.\n      eexists; intuition eauto.\n      eapply recover_finished in H7; eauto.\n    }\n    {\n      unfold refines, cached_log_rep in *.\n      cleanup.\n      eapply log_rep_to_reboot_rep_same in H0.\n              \n      eapply abstract_oracles_exist_wrt_recover in H11; eauto; cleanup.\n      exists ([OpToken (LoggedDiskOperation log_length data_length) CrashBefore]::x); simpl.\n      repeat split; eauto;\n      intros; simpl in *; try unify_execs; cleanup.\n      eapply recovery_oracles_refine_length in H1; eauto.\n      right.\n      eexists; repeat split; eauto.\n      eexists; repeat split; eauto.\n      right.\n      eexists; repeat split; eauto.\n      intros.\n      \n      eapply_fresh recover_crashed in H10; eauto.\n      logic_clean; eauto.\n      eauto.\n      \n      eapply_fresh recover_crashed in H10; eauto;\n      [|\n        unfold cached_log_reboot_rep;\n        eexists; intuition eauto\n      ].\n      cleanup; repeat split_ors;\n      simpl in *; unfold cached_log_reboot_rep in H1;\n      cleanup;\n      try eapply reboot_rep_to_reboot_rep in H1;\n      try eapply crash_rep_recover_to_reboot_rep in H1;\n      try eapply log_rep_to_reboot_rep in H1;\n      eexists; unfold refines_reboot, cached_log_reboot_rep; simpl;\n      eexists; intuition eauto;\n      match goal with\n      |[H: select_total_mem _ _ _ = _ |- _ ]=>\n       eapply select_total_mem_synced in H\n      end; eauto.\n    }\n  Qed.\n\n  Theorem abstract_oracles_exist_wrt_read:\n    forall l_selector a u, \n      abstract_oracles_exist_wrt refinement refines u (|Read a|) (|Recover|) (cached_disk_reboot_list l_selector).\n  Proof.\n    unfold abstract_oracles_exist_wrt, refines_reboot; induction l_selector;\n    simpl; intros; cleanup; invert_exec.\n    {\n      exists  [ [OpToken (LoggedDiskOperation log_length data_length) Cont] ]; simpl.\n      intuition eauto; simpl in *; try unify_execs; cleanup.\n      left.\n      eexists; intuition eauto.\n      eexists; intuition eauto.\n      eexists; intuition eauto.\n\n      left.\n      eexists; intuition eauto.\n      eexists; intuition eauto.\n      eapply_fresh read_finished in H7; eauto; cleanup.\n      cleanup; eauto.\n    }\n    {\n      unfold refines, cached_log_rep in *.\n      cleanup.\n      eapply_fresh log_rep_to_reboot_rep_same in H0.\n              \n      eapply abstract_oracles_exist_wrt_recover in H11; eauto; cleanup.\n      exists ([OpToken (LoggedDiskOperation log_length data_length) CrashBefore]::x); simpl.\n      repeat split; eauto; intros; simpl in *; try (unify_execs; cleanup).\n      eapply recovery_oracles_refine_length in H1; eauto.\n\n      right; eexists; intuition eauto.      \n      eexists; intuition eauto.  \n      eapply_fresh read_crashed in H10; cleanup; eauto.\n      eauto.\n      {        \n        eapply_fresh read_crashed in H10; cleanup; eauto.\n        eapply reboot_rep_to_reboot_rep in Hx.\n        eexists; unfold cached_log_reboot_rep; simpl.\n        eexists; simpl; intuition eauto.\n        unfold cached_log_reboot_rep; simpl.\n        eexists; intuition eauto.\n        simpl in *.\n        eapply select_total_mem_synced in H1; eauto.\n      }\n    }\n  Qed.\n\n  Arguments cached_log_rep: simpl never.\n  Arguments cached_log_crash_rep: simpl never.\n  \n  Fixpoint non_colliding_selector_rec {T}\nu (R: state CachedDiskLang -> T -> Prop) \nl_selector (rec: prog CachedDiskLang 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 CachedDiskLang u o s1 rec (Crashed s1') ->\n    non_colliding_selector selector (snd s1') /\\\n    non_colliding_selector_rec u R ls rec lo \n    (empty_mem, (fst (snd s1'), \n    select_total_mem selector (snd (snd s1'))))\n    end\n  end.\n\nDefinition non_colliding_selector_list {T T'}\nu (R: state CachedDiskLang -> T -> Prop) \n(Rc: state CachedDiskLang -> T -> Prop) \nl_selector \n(p: prog CachedDiskLang T') \n(rec: prog CachedDiskLang 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 CachedDiskLang u o s1 p (Crashed s1') ->\n    non_colliding_selector selector (snd s1') /\\\n    non_colliding_selector_rec u Rc ls rec lo \n    (empty_mem, (fst (snd s1'), \n    select_total_mem selector (snd (snd s1'))))\n    end\n  end.\n\n\n  Theorem abstract_oracles_exist_wrt_write:\n    forall l_selector l_a l_v u l_o s1 s1',\n      \n    non_colliding_selector_list\n    u refines refines_reboot l_selector\n    (refinement.(Simulation.Definitions.compile) (|Write l_a l_v|)) \n    (refinement.(Simulation.Definitions.compile) (|Recover|))  \n      l_o s1 ->\n\n      abstract_oracles_exist_wrt_explicit refinement refines u \n      (|Write l_a l_v|) (|Recover|) (cached_disk_reboot_list l_selector)\n      l_o s1 s1'.\n  Proof. \n    unfold abstract_oracles_exist_wrt_explicit, refines_reboot; induction l_selector;\n    simpl; intros; cleanup; invert_exec.\n    {\n      exists  [ [OpToken (LoggedDiskOperation log_length data_length) Cont] ]; simpl.\n      intuition eauto; try unify_execs; cleanup.\n      left.\n      eexists; intuition eauto.\n      eexists; intuition eauto.\n      eexists; intuition eauto.\n      left.\n      eexists; intuition eauto.\n      eexists; intuition eauto.\n      eapply_fresh write_finished in H8; eauto.\n      unfold refines, cached_log_rep in *;\n      cleanup; eauto.\n      split_ors; cleanup.\n      {\n        clear H5.\n        left; eexists; intuition eauto.\n        rewrite <- H9.\n        setoid_rewrite H0 in H2.\n        repeat rewrite total_mem_map_shift_comm.\n        repeat rewrite total_mem_map_fst_list_upd_batch_set.\n        erewrite empty_mem_list_upd_batch_eq_list_upd_batch_total; eauto.\n        eapply log_rep_forall2_txns_length_match; eauto.\n        eexists; eauto.\n        eapply log_rep_forall2_txns_length_match; eauto.\n      }\n      {\n        right; eexists; intuition eauto.\n        rewrite <- H12.\n        setoid_rewrite H0 in H2.\n        repeat rewrite total_mem_map_shift_comm.\n        repeat rewrite total_mem_map_fst_list_upd_batch_set.\n        erewrite empty_mem_list_upd_batch_eq_list_upd_batch_total; eauto.\n        eapply log_rep_forall2_txns_length_match; eauto.\n        eexists; eauto.\n        eapply log_rep_forall2_txns_length_match; eauto.\n      }\n    }\n    {\n      unfold refines, cached_log_rep in *.\n      cleanup.\n      unfold log_rep in *; cleanup.\n      eapply_fresh write_crashed_oracle in H11; eauto.\n              \n      eapply abstract_oracles_exist_wrt_recover in H13; eauto; cleanup.\n      repeat split_ors.\n      cleanup.\n      {\n        exists ([OpToken (LoggedDiskOperation log_length data_length) CrashBefore]::x1); simpl.\n        repeat split; eauto; intros; try unify_execs; cleanup.\n        eapply recovery_oracles_refine_length in H2; eauto.\n        right.\n        eexists; repeat split; eauto.\n        eexists; repeat split; eauto.\n        right.\n        eexists; left.\n        repeat split; eauto.\n        unfold cached_log_rep in H4; cleanup.\n        left.\n        unfold cached_log_rep in *; simpl in *; cleanup.\n        repeat split; eauto.\n        eexists; repeat split; eauto.\n        rewrite <- H12.\n        repeat rewrite total_mem_map_shift_comm.\n        repeat rewrite total_mem_map_fst_list_upd_batch_set.\n        erewrite empty_mem_list_upd_batch_eq_list_upd_batch_total; eauto.\n        eapply log_rep_forall2_txns_length_match; eauto.\n        eexists; eauto.\n        eapply log_rep_forall2_txns_length_match; eauto.\n        eexists; eauto.\n        {\n          unfold log_header_rep, log_rep_general, \n          log_rep_explicit, log_header_block_rep in *; cleanup.\n          eauto.\n        }\n      }\n      unfold cached_log_crash_rep in *; cleanup.\n      split_ors; cleanup.\n      split_ors; cleanup.\n      {\n        exists ([OpToken (LoggedDiskOperation log_length data_length) CrashBefore]::x1); simpl.\n        repeat split; eauto; intros; try unify_execs; cleanup.\n        eapply recovery_oracles_refine_length in H2; eauto.\n        right.\n        eexists; repeat split; eauto; try unify_execs; cleanup.\n        eexists; repeat split; eauto; try unify_execs; cleanup.\n        right.\n        eexists; right; repeat split; eauto.\n        right.\n        unfold cached_log_crash_rep; simpl.\n        repeat split; eauto.\n        unfold cached_log_rep in *; cleanup.\n        left; eexists; repeat split; eauto.\n        eexists; repeat split; eauto.\n        setoid_rewrite H0 in H13.\n        setoid_rewrite <- H9.\n        repeat rewrite total_mem_map_shift_comm.\n        repeat rewrite total_mem_map_fst_list_upd_batch_set.\n        erewrite empty_mem_list_upd_batch_eq_list_upd_batch_total; eauto.\n        eapply log_rep_forall2_txns_length_match; eauto.\n        unfold log_rep; eauto.\n        eapply log_rep_forall2_txns_length_match; eauto.\n        unfold log_rep; eauto.\n\n        {\n          unfold log_header_rep, log_rep_general, \n          log_rep_explicit, log_header_block_rep in *; cleanup.\n          eauto.\n        }\n        (*\n        unfold cached_log_rep in *; cleanup.\n        left; intuition eauto.\n        eapply crash_rep_log_write_to_reboot_rep in H3.\n        unfold cached_log_reboot_rep.\n        eexists; intuition eauto.\n        simpl.\n\n        unfold log_rep, log_reboot_rep, log_rep_general in *.\n        logic_clean.\n        erewrite map_addr_list_eq_map_map; eauto.\n        rewrite shift_list_upd_batch_set_comm; eauto.\n        setoid_rewrite map_addr_list_eq_map_map at 2; eauto.\n        rewrite shift_list_upd_batch_set_comm; eauto.\n        rewrite shift_select_total_mem_synced.\n        eapply empty_mem_list_upd_batch_eq_list_upd_batch_total in H11; eauto.       \n        repeat rewrite <- shift_list_upd_batch_set_comm.        \n        repeat erewrite <- map_addr_list_eq_map_map; eauto.\n        repeat rewrite total_mem_map_shift_comm in *.\n        repeat rewrite total_mem_map_fst_list_upd_batch_set in *.\n        setoid_rewrite <- H11; eauto.\n\n        all: try apply sumbool_agree_addr_dec.\n        all: try eapply log_rep_forall2_txns_length_match; eauto.\n        all: unfold log_rep, log_rep_general; eauto.\n        intros; apply H9; lia.\n        *)\n      }\n      {\n        eapply_fresh crash_rep_header_write_to_reboot_rep' in H4.\n        split_ors.\n        {\n          exists ([OpToken (LoggedDiskOperation log_length data_length) CrashBefore]::x1); simpl.\n          repeat split; eauto; intros; try unify_execs; cleanup.\n          eapply recovery_oracles_refine_length in H2; eauto.\n          right.\n          eexists; repeat split; eauto; try unify_execs; cleanup.\n          eexists; repeat split; eauto; try unify_execs; cleanup.\n          right.\n          eexists; right; repeat split; eauto.\n          right.\n          unfold cached_log_crash_rep; simpl.\n          repeat split; eauto.\n          unfold cached_log_rep in *; cleanup.\n          right; do 2 eexists; repeat split; eauto;\n          repeat rewrite <- sync_list_upd_batch_set in *.\n          setoid_rewrite <- H12.\n          setoid_rewrite <- H13.\n          setoid_rewrite H0 in H19.\n          repeat rewrite total_mem_map_shift_comm.\n          repeat rewrite total_mem_map_fst_list_upd_batch_set.\n          erewrite empty_mem_list_upd_batch_eq_list_upd_batch_total; eauto.\n          eapply log_rep_forall2_txns_length_match; eauto.\n          unfold log_rep; eauto.\n          eapply log_rep_forall2_txns_length_match; eauto.\n          unfold log_rep; eauto.\n\n          setoid_rewrite <- H13.\n          setoid_rewrite H0 in H19.\n          repeat rewrite total_mem_map_shift_comm.\n          repeat rewrite total_mem_map_fst_list_upd_batch_set.\n          erewrite empty_mem_list_upd_batch_eq_list_upd_batch_total; eauto.\n          eapply log_rep_forall2_txns_length_match; eauto.\n          unfold log_rep; eauto.\n          eapply log_rep_forall2_txns_length_match; eauto.\n          unfold log_rep; eauto.\n\n          {\n            unfold log_header_rep, log_rep_general, \n            log_rep_explicit, log_header_block_rep in *; cleanup.\n            intuition eauto.\n          }\n\n          unfold cached_log_rep in *; cleanup.\n          left; repeat split; eauto.\n          unfold cached_log_reboot_rep_explicit_part.\n          do 2 eexists; repeat split; eauto.\n          simpl; eexists; repeat split; eauto.\n\n          unfold log_rep, log_header_rep,\n          log_reboot_rep_explicit_part, log_rep_general in *.\n          logic_clean.\n          erewrite map_addr_list_eq_map_map; eauto.\n          rewrite shift_list_upd_batch_set_comm; eauto.\n          setoid_rewrite map_addr_list_eq_map_map at 2; eauto.\n          rewrite shift_list_upd_batch_set_comm; eauto.\n          rewrite shift_select_total_mem_synced.\n          \n          repeat rewrite <- shift_list_upd_batch_set_comm.        \n          repeat erewrite <- map_addr_list_eq_map_map; eauto.\n          repeat rewrite total_mem_map_shift_comm in *.\n          repeat rewrite total_mem_map_fst_list_upd_batch_set in *.\n          setoid_rewrite <- H13; eauto.\n          setoid_rewrite H0 in H19.\n          repeat rewrite total_mem_map_shift_comm.\n          repeat rewrite total_mem_map_fst_list_upd_batch_set.\n          erewrite empty_mem_list_upd_batch_eq_list_upd_batch_total; eauto.\n\n          all: try apply sumbool_agree_addr_dec.\n          all: try solve [eapply log_rep_forall2_txns_length_match; unfold log_rep, log_rep_general; eauto].\n          intros; apply H14; lia.\n          unfold select_total_mem.\n          setoid_rewrite H9; simpl.\n          unfold select_for_addr; cleanup; eauto.\n          erewrite addr_list_to_blocks_length_eq; eauto.\n          rewrite map_length; eauto.\n        }\n        split_ors; cleanup.\n        {\n          exists ([OpToken (LoggedDiskOperation log_length data_length) CrashBefore]::x1); simpl.\n          repeat split; eauto; intros; try unify_execs; cleanup.\n          eapply recovery_oracles_refine_length in H2; eauto.\n          right.\n          eexists; repeat split; eauto; try unify_execs; cleanup.\n          eexists; repeat split; eauto; try unify_execs; cleanup.\n          right.\n          eexists; right; repeat split; eauto.\n          right.\n          unfold cached_log_crash_rep; simpl.\n          repeat split; eauto.\n          unfold cached_log_rep in *; cleanup.\n          right; do 2 eexists; repeat split; eauto;\n          repeat rewrite <- sync_list_upd_batch_set in *.\n          setoid_rewrite <- H12.\n          setoid_rewrite <- H13.\n          setoid_rewrite H0 in H22.\n          repeat rewrite total_mem_map_shift_comm.\n          repeat rewrite total_mem_map_fst_list_upd_batch_set.\n          erewrite empty_mem_list_upd_batch_eq_list_upd_batch_total; eauto.\n          eapply log_rep_forall2_txns_length_match; eauto.\n          unfold log_rep; eauto.\n          eapply log_rep_forall2_txns_length_match; eauto.\n          unfold log_rep; eauto.\n\n          setoid_rewrite <- H13.\n          setoid_rewrite H0 in H22.\n          repeat rewrite total_mem_map_shift_comm.\n          repeat rewrite total_mem_map_fst_list_upd_batch_set.\n          erewrite empty_mem_list_upd_batch_eq_list_upd_batch_total; eauto.\n          eapply log_rep_forall2_txns_length_match; eauto.\n          unfold log_rep; eauto.\n          eapply log_rep_forall2_txns_length_match; eauto.\n          unfold log_rep; eauto.\n\n          {\n            unfold log_header_rep, log_rep_general, \n            log_rep_explicit, log_header_block_rep in *; cleanup.\n            intuition eauto.\n          }\n\n          unfold cached_log_rep in *; cleanup.\n          right; left; repeat split; eauto.\n          unfold cached_log_reboot_rep_explicit_part.\n          do 2 eexists; repeat split; eauto.\n          simpl; eexists; repeat split; eauto.\n\n          unfold log_rep, log_header_rep,\n          log_reboot_rep_explicit_part, log_rep_general in *.\n          logic_clean.\n          erewrite map_addr_list_eq_map_map; eauto.\n          rewrite shift_list_upd_batch_set_comm; eauto.\n          setoid_rewrite map_addr_list_eq_map_map at 2; eauto.\n          rewrite shift_list_upd_batch_set_comm; eauto.\n          rewrite shift_select_total_mem_synced.\n          \n          repeat rewrite <- shift_list_upd_batch_set_comm.        \n          repeat erewrite <- map_addr_list_eq_map_map; eauto.\n          repeat rewrite total_mem_map_shift_comm in *.\n          repeat rewrite total_mem_map_fst_list_upd_batch_set in *.\n          setoid_rewrite <- H13; eauto.\n          setoid_rewrite H0 in H22.\n          repeat rewrite total_mem_map_shift_comm.\n          repeat rewrite total_mem_map_fst_list_upd_batch_set.\n          erewrite empty_mem_list_upd_batch_eq_list_upd_batch_total; eauto.\n\n          all: try apply sumbool_agree_addr_dec.\n          all: try solve [eapply log_rep_forall2_txns_length_match; unfold log_rep, log_rep_general; eauto].\n          intros; apply H14; lia.\n          {\n            split_ors; cleanup.\n            {\n              unfold log_header_rep, log_rep_general, \n              log_rep_explicit, log_header_block_rep in *; cleanup.\n              left; intuition eauto.\n              exists (x6 - count (current_part (decode_header (fst (snd (snd s1) hdr_block_num))))).\n\n              unfold log_crash_rep, \n              log_reboot_rep_explicit_part, \n              log_rep_explicit, log_header_block_rep in *; logic_clean.\n              simpl in *; rewrite H41 in H9; inversion H9.\n              subst.\n              repeat rewrite encode_decode_header in *.\n              rewrite H4 in *.\n\n              unfold log_reboot_rep_explicit_part,\n              log_rep_explicit, log_rep_inner,\n              header_part_is_valid, txns_valid in *; \n              simpl in *; logic_clean.\n\n              repeat match goal with \n              |[H: count (_ _) = _|- _] =>\n                rewrite H in *\n              end.\n\n              repeat match goal with \n              |[H: map _ _ = records (_ _)|- _] =>\n                rewrite <- H in *\n              end.\n              repeat rewrite map_map in *. \n              repeat rewrite map_app in *; simpl in *.\n              rewrite fold_left_app in H19; simpl in *.\n\n              match goal with \n              |[H: Forall _ (_ ++ [_]) |- _] =>\n                eapply forall_app_l in H;\n                inversion H; subst\n              end.\n              unfold txn_well_formed in *; logic_clean.\n              match goal with \n              |[H: addr_count _ = _,\n                H0: data_count _ = _,\n                H1: addr_blocks _ = _ |- _] =>\n                rewrite H, H0, H1 in *\n              end.\n              erewrite addr_list_to_blocks_length_eq in H19.\n              2: apply map_length.\n\n              repeat rewrite <- PeanoNat.Nat.add_assoc.\n              repeat rewrite Minus.le_plus_minus_r by lia.\n              unfold select_total_mem in *; simpl in *.\n              repeat split; eauto.\n              lia.\n              intros Hx.\n              apply H21.\n              rewrite Hx.\n              edestruct H25; eauto.\n              instantiate (1:= x6 -\n              fold_left PeanoNat.Nat.add\n          (map (fun x : txn => addr_count (record x) + data_count (record x))\n             x2) 0).\n              lia.\n              repeat rewrite <- PeanoNat.Nat.add_assoc in *.\n              repeat rewrite Minus.le_plus_minus_r in * by lia.\n              eauto.\n            }\n            {\n              unfold log_header_rep, log_rep_general, \n              log_rep_explicit, log_header_block_rep in *; cleanup.\n              right; intuition eauto.\n              exists x6.\n\n              unfold log_crash_rep, \n              log_reboot_rep_explicit_part, \n              log_rep_explicit, log_header_block_rep in *; logic_clean.\n              simpl in *; rewrite H41 in H9; inversion H9.\n              subst.\n              repeat rewrite encode_decode_header in *.\n              rewrite H4 in *.\n\n              unfold log_reboot_rep_explicit_part,\n              log_rep_explicit, log_rep_inner,\n              header_part_is_valid, txns_valid in *; \n              simpl in *; logic_clean.\n\n              repeat match goal with \n              |[H: count (_ _) = _|- _] =>\n                rewrite H in *\n              end.\n\n              rewrite <- H64, <- H70 in *; simpl in *.\n\n              match goal with \n              |[H: Forall _ [_] |- _] =>\n                inversion H; subst\n              end.\n              unfold txn_well_formed in *; logic_clean.\n              match goal with \n              |[H: addr_count _ = _,\n                H0: data_count _ = _,\n                H1: addr_blocks _ = _ |- _] =>\n                rewrite H, H0, H1 in *\n              end.\n              erewrite addr_list_to_blocks_length_eq in H19.\n              2: apply map_length.\n\n              repeat rewrite <- PeanoNat.Nat.add_assoc.\n              repeat rewrite Minus.le_plus_minus_r by lia.\n              unfold select_total_mem in *; simpl in *.\n              repeat split; eauto.\n              intros Hx.\n              apply H21.\n              rewrite Hx.\n              edestruct H25; eauto.\n            }\n          }\n          erewrite addr_list_to_blocks_length_eq; eauto.\n          rewrite map_length; eauto.\n        }\n        {\n          exists ([OpToken (LoggedDiskOperation log_length data_length) CrashAfter]::x1); simpl.\n          repeat split; eauto; intros; try unify_execs; cleanup.\n          eapply recovery_oracles_refine_length in H2; eauto.\n          right.\n          eexists; repeat split; eauto; try unify_execs; cleanup.\n          eexists; repeat split; eauto; try unify_execs; cleanup.\n          right.\n          eexists; right; repeat split; eauto.\n          right.\n          unfold cached_log_crash_rep; simpl.\n          repeat split; eauto.\n          unfold cached_log_rep in *; cleanup.\n          right; do 2 eexists; repeat split; eauto;\n          \n          repeat rewrite <- sync_list_upd_batch_set in *.\n          setoid_rewrite <- H12.\n          setoid_rewrite <- H13.\n          setoid_rewrite H0 in H20.\n          repeat rewrite total_mem_map_shift_comm.\n          repeat rewrite total_mem_map_fst_list_upd_batch_set.\n          erewrite empty_mem_list_upd_batch_eq_list_upd_batch_total; eauto.\n          eapply log_rep_forall2_txns_length_match; eauto.\n          unfold log_rep; eauto.\n          eapply log_rep_forall2_txns_length_match; eauto.\n          unfold log_rep; eauto.\n\n          setoid_rewrite <- H13.\n          setoid_rewrite H0 in H20.\n          repeat rewrite total_mem_map_shift_comm.\n          repeat rewrite total_mem_map_fst_list_upd_batch_set.\n          erewrite empty_mem_list_upd_batch_eq_list_upd_batch_total; eauto.\n          eapply log_rep_forall2_txns_length_match; eauto.\n          unfold log_rep; eauto.\n          eapply log_rep_forall2_txns_length_match; eauto.\n          unfold log_rep; eauto.\n          {\n            unfold log_header_rep, log_rep_general, \n            log_rep_explicit, log_header_block_rep in *; cleanup.\n            intuition eauto.\n          }\n\n          unfold cached_log_rep in *; cleanup.\n          right; right; repeat split; eauto.\n          unfold cached_log_reboot_rep_explicit_part.\n          do 2 eexists; repeat split; eauto.\n          simpl; eexists; repeat split; eauto.\n\n          unfold log_rep, log_header_rep,\n          log_reboot_rep_explicit_part, log_rep_general in *.\n          logic_clean.\n          erewrite map_addr_list_eq_map_map; eauto.\n          rewrite shift_list_upd_batch_set_comm; eauto.\n          setoid_rewrite map_addr_list_eq_map_map at 2; eauto.\n          rewrite shift_list_upd_batch_set_comm; eauto.\n          rewrite shift_select_total_mem_synced.\n          \n          repeat rewrite <- shift_list_upd_batch_set_comm.        \n          repeat erewrite <- map_addr_list_eq_map_map; eauto.\n          repeat rewrite total_mem_map_shift_comm in *.\n          repeat rewrite total_mem_map_fst_list_upd_batch_set in *.\n          setoid_rewrite <- H12; eauto.\n          setoid_rewrite <- H13; eauto.\n          setoid_rewrite H0 in H20.\n          repeat rewrite total_mem_map_shift_comm.\n          repeat rewrite total_mem_map_fst_list_upd_batch_set.\n          erewrite empty_mem_list_upd_batch_eq_list_upd_batch_total; eauto.\n\n          all: try apply sumbool_agree_addr_dec.\n          all: try solve [eapply log_rep_forall2_txns_length_match; unfold log_rep, log_rep_general; eauto].\n          intros; apply H14; lia.\n          {\n            unfold select_total_mem in *.\n            setoid_rewrite H9.\n            rewrite select_for_addr_not_1_latest; simpl; eauto.\n          }\n          {\n            split_ors; cleanup.\n            {\n              unfold log_header_rep, log_rep_general, \n            log_rep_explicit, log_header_block_rep in *; cleanup.\n              left; intuition eauto.\n              edestruct H23; eauto.\n              erewrite <- H21.\n              setoid_rewrite <- H19; fold Nat.add; try lia.\n              unfold select_total_mem; simpl; eauto.\n\n              unfold log_crash_rep, \n              log_reboot_rep_explicit_part, \n              log_rep_explicit, log_header_block_rep in *; logic_clean.\n              simpl in *; rewrite H42 in H9; inversion H9.\n              subst.\n              repeat rewrite encode_decode_header in *.\n              rewrite H4.\n\n              unfold log_reboot_rep_explicit_part,\n              log_rep_explicit, log_rep_inner,\n              header_part_is_valid, txns_valid in *; \n              simpl in *; logic_clean.\n\n              repeat match goal with \n              |[H: count (_ _) = _|- _] =>\n                setoid_rewrite H\n              end.\n\n              repeat match goal with \n              |[H: map _ _ = records (_ _)|- _] =>\n                setoid_rewrite <- H\n              end.\n              repeat rewrite map_map in *. \n              repeat rewrite map_app in *; simpl.\n              setoid_rewrite fold_left_app; simpl.\n\n              match goal with \n              |[H: Forall _ (_ ++ [_]) |- _] =>\n                eapply forall_app_l in H;\n                inversion H; subst\n              end.\n              unfold txn_well_formed in *; logic_clean.\n              match goal with \n              |[H: addr_count _ = _,\n                H0: data_count _ = _,\n                H1: addr_blocks _ = _ |- _] =>\n                rewrite H, H0, H1\n              end.\n              erewrite addr_list_to_blocks_length_eq.\n              2: apply map_length.\n              lia.\n            }\n            {\n              unfold log_header_rep, log_rep_general, \n            log_rep_explicit, log_header_block_rep in *; cleanup.\n              right; intuition eauto.\n              edestruct H23; eauto.\n              erewrite <- H21.\n              setoid_rewrite <- H19; fold Nat.add; try lia.\n              unfold select_total_mem; simpl; eauto.\n\n              unfold log_crash_rep, \n              log_reboot_rep_explicit_part, \n              log_rep_explicit, log_header_block_rep in *; logic_clean.\n              simpl in *; rewrite H42 in H9; inversion H9.\n              subst.\n              repeat rewrite encode_decode_header in *.\n\n              unfold log_reboot_rep_explicit_part,\n              log_rep_explicit, log_rep_inner,\n              header_part_is_valid, txns_valid in *; \n              simpl in *; logic_clean.\n\n              repeat match goal with \n              |[H: count (_ _) = _|- _] =>\n                setoid_rewrite H\n              end.\n\n              rewrite <- H59.\n              simpl.\n\n              match goal with \n              |[H: Forall _ [_] |- _] =>\n                inversion H; subst\n              end.\n              unfold txn_well_formed in *; logic_clean.\n              match goal with \n              |[H: addr_count _ = _,\n                H0: data_count _ = _,\n                H1: addr_blocks _ = _ |- _] =>\n                rewrite H, H0, H1\n              end.\n              erewrite addr_list_to_blocks_length_eq.\n              2: apply map_length.\n              lia.\n\n\n              unfold log_crash_rep, \n              log_reboot_rep_explicit_part, \n              log_rep_explicit, log_header_block_rep in *; logic_clean.\n              simpl in *; rewrite H42 in H9; inversion H9.\n              subst.\n              repeat rewrite encode_decode_header in *.\n              rewrite H4.\n\n              unfold log_reboot_rep_explicit_part,\n              log_rep_explicit, log_rep_inner,\n              header_part_is_valid, txns_valid in *; \n              simpl in *; logic_clean.\n\n              repeat match goal with \n              |[H: count (_ _) = _|- _] =>\n                setoid_rewrite H\n              end.\n\n              rewrite <- H71.\n              simpl; lia.\n            }\n          }\n          erewrite addr_list_to_blocks_length_eq; eauto.\n          rewrite map_length; eauto.\n        }\n        {\n          edestruct H; eauto.\n          do 2 eexists; intuition eauto.\n        }\n        all: eauto.\n      }\n      split_ors; cleanup.\n      {\n        exists ([OpToken (LoggedDiskOperation log_length data_length) CrashAfter]::x1); simpl.\n        repeat split; eauto; intros; try unify_execs; cleanup.\n        eapply recovery_oracles_refine_length in H2; eauto.\n        right.\n        eexists; repeat split; eauto; try unify_execs; cleanup.\n        eexists; repeat split; eauto; try unify_execs; cleanup.        \n        right.\n        eexists; right; repeat split; eauto.\n        left.\n        unfold cached_log_crash_rep in *; simpl; cleanup.\n        repeat split; eauto.\n        unfold cached_log_rep in *; cleanup.\n        eexists; repeat split; eauto.\n        repeat rewrite <- sync_list_upd_batch_set in *.\n        setoid_rewrite <- H10.\n        setoid_rewrite H0 in e.\n        repeat rewrite total_mem_map_shift_comm.\n        repeat rewrite total_mem_map_fst_list_upd_batch_set.\n        erewrite empty_mem_list_upd_batch_eq_list_upd_batch_total; eauto.\n        eapply log_rep_forall2_txns_length_match; eauto.\n        unfold log_rep; eauto.\n        eapply log_rep_forall2_txns_length_match; eauto.\n        unfold log_rep; eauto.\n        erewrite addr_list_to_blocks_length_eq; eauto.\n        rewrite map_length; eauto.\n        {\n            unfold log_header_rep, log_rep_general, \n            log_rep_explicit, log_header_block_rep in *; cleanup.\n            setoid_rewrite H7.\n            intuition eauto.\n        }\n      }\n      split_ors; cleanup.\n      {\n        exists ([OpToken (LoggedDiskOperation log_length data_length) CrashBefore]::x1); simpl.\n        repeat split; eauto; intros; try unify_execs; cleanup.\n        eapply recovery_oracles_refine_length in H2; eauto.\n        right.\n        eexists; repeat split; eauto; try unify_execs; cleanup.\n        eexists; repeat split; eauto.\n        right.\n        eexists; left; repeat split; eauto.\n        {\n          \n          unfold cached_log_rep in *; cleanup.\n          right; left; eauto.\n          unfold cached_log_crash_rep in *;\n          simpl in *; cleanup.\n          repeat split; eauto.\n          eexists; repeat split; eauto.\n          cleanup.\n          setoid_rewrite <- H13.\n          repeat rewrite total_mem_map_shift_comm.\n          repeat rewrite total_mem_map_fst_list_upd_batch_set.\n          erewrite empty_mem_list_upd_batch_eq_list_upd_batch_total; eauto.\n          eapply log_rep_forall2_txns_length_match; eauto.\n          unfold log_rep; eauto.\n          eapply log_rep_forall2_txns_length_match; eauto.\n          unfold log_rep; eauto.\n          {\n              unfold log_header_rep, log_rep_general, \n              log_rep_explicit, log_header_block_rep in *; cleanup.\n              eauto.\n          }\n\n          {\n              unfold log_header_rep, log_rep_general, \n              log_rep_explicit, log_header_block_rep in *; cleanup.\n              eauto.\n          }\n          unfold log_header_rep, log_rep_general, \n              log_rep_explicit, log_header_block_rep in *; cleanup.\n          erewrite addr_list_to_blocks_length_eq; eauto.\n        }\n      }\n      {\n        exists ([OpToken (LoggedDiskOperation log_length data_length) CrashBefore]::x1); simpl.\n        repeat split; eauto; intros; try unify_execs; cleanup.\n        eapply recovery_oracles_refine_length in H2; eauto.\n        right.\n        eexists; repeat split; eauto; try unify_execs; cleanup.\n        eexists; repeat split; eauto.\n        right.\n        eexists; left; intuition eauto.\n        unfold cached_log_rep in H12; cleanup.\n        right; right; eauto.\n        unfold cached_log_crash_rep in *;\n        simpl in *; cleanup.\n        eexists; intuition eauto.\n        setoid_rewrite <- H13.\n        repeat rewrite total_mem_map_shift_comm.\n        repeat rewrite total_mem_map_fst_list_upd_batch_set.\n        erewrite empty_mem_list_upd_batch_eq_list_upd_batch_total; eauto.\n        eapply log_rep_forall2_txns_length_match; eauto.\n        unfold log_rep; eauto.\n        eapply log_rep_forall2_txns_length_match; eauto.\n        unfold log_rep; eauto.\n        {\n          unfold log_header_rep, log_rep_general, \n          log_rep_explicit, log_header_block_rep in *; cleanup.\n          lia.\n        }\n        unfold log_header_rep, log_rep_general, \n            log_rep_explicit, log_header_block_rep in *; cleanup.\n        erewrite addr_list_to_blocks_length_eq; eauto.\n      }\n      {\n        repeat split_ors.\n        {\n          unfold cached_log_rep in *; cleanup; eauto;\n          try eapply log_rep_to_reboot_rep in H5;\n          eexists; unfold refines_reboot, cached_log_reboot_rep; simpl;\n          eexists; repeat split; eauto;\n            eapply select_total_mem_synced; eauto.\n        }\n        {\n          unfold cached_log_crash_rep in *; cleanup; eauto.\n          split_ors; cleanup.\n          split_ors; cleanup.\n          {\n            eapply crash_rep_log_write_to_reboot_rep in H2.\n            eexists; unfold refines_reboot, cached_log_reboot_rep; simpl;\n            eexists; repeat split; eauto;\n            eapply select_total_mem_synced; eauto.\n          }\n          {\n            eapply crash_rep_header_write_to_reboot_rep in H2.\n            split_ors;\n            eexists; unfold refines_reboot, cached_log_reboot_rep; simpl;\n            eexists; repeat split; eauto;\n            eapply select_total_mem_synced; eauto.\n            edestruct H; eauto.\n            do 2 eexists; intuition eauto.\n          }\n          split_ors; cleanup.\n          {\n            eapply log_rep_to_reboot_rep in H2.\n            eexists; unfold refines_reboot, cached_log_reboot_rep; simpl;\n            eexists; repeat split; eauto;\n            eapply select_total_mem_synced; eauto.\n          }\n          split_ors; cleanup.\n          {\n            split_ors.\n            {\n              cleanup.\n            eapply crash_rep_apply_to_reboot_rep in H2.\n            split_ors;\n            eexists; unfold refines_reboot, cached_log_reboot_rep; simpl;\n            eexists; repeat split; eauto;\n            eapply select_total_mem_synced; eauto.\n            }\n                {\n              eapply log_rep_to_reboot_rep in H2.\n            eexists; unfold refines_reboot, cached_log_reboot_rep; simpl;\n                eexists; repeat split; eauto;\n            eapply select_total_mem_synced; eauto.\n            }\n          }\n          {\n            eapply log_rep_to_reboot_rep in H2.\n            eexists; unfold refines_reboot, cached_log_reboot_rep; simpl;\n            eexists; repeat split; eauto;\n            eapply select_total_mem_synced; eauto.\n          }\n        }\n      }\n    }\nQed.\n\n  Fixpoint not_init {T} (p_abs: abs.(prog) T) :=\n    match p_abs with\n    |Op _ o =>\n     match o with\n     | Init _ => False\n     | _ => True\n     end\n    |Ret _ => True\n    |Bind p1 p2 =>\n     not_init p1 /\\ (forall r, not_init (p2 r))\n    end.\n    \n    (*\n  Theorem abstract_oracles_exists_logged_disk:\n    forall T (p_abs: abs.(prog) T) l_selector u l_o s1 s1',\n      not_init p_abs ->\n      (forall T p, \n      eq_dep _ _ T p _ (|Write l_a l_v|) ->\n        non_colliding_selector_list\n    u refines refines_reboot l_selector\n    (refinement.(Simulation.Definitions.compile) p) \n    (refinement.(Simulation.Definitions.compile) (|Recover|))  \n      l_o s1) ->\n      abstract_oracles_exist_wrt_explicit refinement \n      refines u p_abs (|Recover|) \n      (cached_disk_reboot_list l_selector) l_o s1 s1'.\n  Proof.\n    unfold abstract_oracles_exist_wrt_explicit; induction p_abs;\n    simpl; intros; cleanup_no_match.\n    {(** OPS **)\n      destruct o; intuition.\n      eapply abstract_oracles_exist_wrt_read; eauto.\n      eapply abstract_oracles_exist_wrt_write; eauto.\n      eapply H0; eauto.\n      eapply abstract_oracles_exist_wrt_recover'; eauto.\n    }\n    {\n      repeat invert_exec; cleanup.\n      {\n        rewrite <- H3; simpl.\n        exists [[Layer.Cont (LoggedDiskOperation log_length data_length)]]; simpl; intuition.\n        left.\n        eexists; repeat split; eauto; try unify_execs; cleanup.\n        eexists; repeat split; eauto; try unify_execs; cleanup.\n      }\n      {\n        destruct l_selector; simpl in *; try congruence; cleanup.\n        repeat invert_exec.\n        invert_exec'' H10.\n        eapply abstract_oracles_exist_wrt_recover in H12; eauto.\n        cleanup.\n        exists ([Layer.Crash (LoggedDiskOperation log_length data_length)]::x0);\n        simpl; intuition eauto.\n        apply recovery_oracles_refine_length in H2; eauto.\n        right.\n        eexists; repeat split; eauto; try unify_execs; cleanup.\n        econstructor.\n        left; eexists; intuition eauto.\n        econstructor.\n        unfold refines, cached_log_rep in *.\n        cleanup.\n        eapply log_rep_to_reboot_rep in H2.\n        unfold refines_reboot, cached_log_reboot_rep.\n        do 2 eexists; intuition eauto.\n        eapply select_total_mem_synced in H3; eauto.\n      }\n    }\n    {\n      repeat invert_exec.\n      {\n        invert_exec'' H13.\n        edestruct IHp_abs; eauto.\n        instantiate (2:= []); simpl.\n        eauto.\n        eapply ExecFinished; eauto.\n        edestruct H.\n        eauto.\n        {\n          simpl in *.\n          edestruct H1; eauto.\n        }\n        2: {\n          instantiate (3:= []); simpl.\n          eapply ExecFinished; eauto.\n        }\n        eapply exec_compiled_preserves_refinement_finished in H10; eauto.\n        simpl in *; cleanup; try tauto.\n        simpl in *.\n        exists ([o0 ++ o]); split; eauto.\n        repeat split_ors; cleanup;\n        repeat unify_execs; cleanup.\n        left.\n        cleanup.\n        do 2 eexists; repeat split; eauto.\n        econstructor; eauto.\n        right; simpl; repeat eexists; intuition eauto.\n      }\n      {\n        destruct l_selector; simpl in *; try congruence; cleanup.\n        invert_exec'' H11.\n        {\n          edestruct IHp_abs; eauto.\n          instantiate (2:= []); simpl.\n          instantiate (1:= RFinished d1' r).\n          eapply ExecFinished; eauto.\n          edestruct H.\n          eauto.\n          2: {\n            instantiate (3:= t::l_selector); simpl.\n            instantiate (1:= Recovered (extract_state_r ret)).\n            econstructor; eauto.\n          }\n          eapply exec_compiled_preserves_refinement_finished in H9; eauto.\n          simpl in *; cleanup; try tauto.\n          simpl in *.\n          exists ((o0 ++ o)::l); split; eauto.\n          repeat split_ors; cleanup;\n          repeat unify_execs; cleanup.  \n          right.\n          eexists; intuition eauto.\n          econstructor; eauto.\n          right; simpl; repeat eexists; intuition eauto.\n        }\n        {\n          edestruct IHp_abs; eauto.\n          instantiate (2:= t::l_selector); simpl.\n          instantiate (1:= Recovered (extract_state_r ret)).\n          econstructor; eauto.\n          simpl in *; cleanup; try tauto.\n          simpl in *.\n          eexists (_::l); split; eauto.\n          repeat split_ors;\n            cleanup; repeat (unify_execs; cleanup).\n            right.            \n            eexists; intuition eauto.\n            solve [econstructor; eauto].\n        }\n      }\n    }\n  Qed.\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/Refinements/LogCacheToLoggedDisk/AbstractOracles.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.25268296425167647}}
{"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": "robbertkrebbers", "repo": "compcert", "sha": "524c26591e884a3676a5fbef77d8c79193955b82", "save_path": "github-repos/coq/robbertkrebbers-compcert", "path": "github-repos/coq/robbertkrebbers-compcert/compcert-524c26591e884a3676a5fbef77d8c79193955b82/ia32/CombineOp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2526829642516764}}
{"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 stdpp_extra iris_extra cap_lang\n     region rules_base rules rules_binary rules_binary_base.\nFrom cap_machine.examples Require Import disjoint_regions_tactics.\n\nDefinition mkregion (r_start r_end: Addr) (contents: list Word): gmap Addr Word :=\n  list_to_map (zip (finz.seq_between r_start r_end) contents).\n\nDefinition mbkregion (r_start r_end: Addr) (contents: list Word) (contents_spec: list Word): gmap Addr (Word * Word) :=\n  list_to_map (zip (finz.seq_between r_start r_end) (zip contents contents_spec)).\n\nLemma zip_seq_between_lookup {A} (b e a : Addr) (l : list A) x :\n  (b + length l = Some e)%a →\n  (a, x) ∈ zip (finz.seq_between b e) l ↔ ∃ (i:nat), a = (b ^+ i)%a ∧ l !! i = Some x.\nProof.\n  revert b e a x. induction l as [| x l].\n  { intros * Hl. cbn.\n    rewrite (_: b = e). 2: solve_addr.\n    rewrite finz_seq_between_empty //. 2: solve_addr. cbn.\n    split. by inversion 1. intros [? [? ?] ].  rewrite lookup_nil in H0. congruence. }\n  { intros * Hl. cbn in *.\n    rewrite finz_seq_between_cons. 2: solve_addr. cbn.\n    split.\n    { intros [HH|HH]%elem_of_cons.\n      { simplify_eq. exists 0. split. solve_addr. constructor. }\n      { eapply IHl in HH as [i [? ?] ].\n        { exists (S i). split; solve_addr. }\n        { solve_addr. } } }\n    { intros [i [? H2] ]. destruct i.\n      { cbn in H2. simplify_eq. rewrite (_: b ^+ 0%nat = b)%a. constructor. solve_addr. }\n      { constructor. cbn in H2. apply IHl. solve_addr. exists i.\n        split; solve_addr. } } }\nQed.\n\nLemma list_to_map_app {A} `{EqDecision A, Countable A} {B} (l1 l2: list (A * B)) :\n  (list_to_map (l1 ++ l2) : gmap A B) = list_to_map l1 ∪ list_to_map l2.\nProof.\n  revert l2. induction l1.\n  { intros l2. rewrite /= left_id_L //. }\n  { intros l2. rewrite /= IHl1 insert_union_l //. }\nQed.\n\nLemma mkregion_app l1 l2 b e :\n  (b + length (l1 ++ l2))%a = Some e →\n  mkregion b e (l1 ++ l2) =\n  mkregion b (b ^+ length l1)%a l1 ∪ mkregion (b ^+ length l1)%a e l2.\nProof.\n  rewrite /mkregion. rewrite app_length. intros HH.\n  rewrite (finz_seq_between_split _ (b ^+ length l1)%a). 2: split; solve_addr.\n  rewrite zip_app. 2: rewrite finz_seq_between_length /finz.dist; solve_addr.\n  rewrite list_to_map_app //.\nQed.\n\nLemma mkregion_lookup (b e a : Addr) l x :\n  (b + length l = Some e)%a →\n  mkregion b e l !! a = Some x ↔ ∃ (i:nat), a = (b ^+ i)%a ∧ l !! i = Some x.\nProof.\n  intros Hl. rewrite /mkregion.\n  rewrite -elem_of_list_to_map. apply zip_seq_between_lookup; auto.\n  rewrite fst_zip. apply finz_seq_between_NoDup.\n  rewrite finz_seq_between_length /finz.dist. solve_addr.\nQed.\n\nLemma dom_mkregion_incl a e l:\n  dom (mkregion a e l) ⊆ list_to_set (finz.seq_between a e).\nProof.\n  rewrite /mkregion. generalize (finz.seq_between a e). induction l.\n  { intros. rewrite zip_with_nil_r /=. rewrite dom_empty_L. apply empty_subseteq. }\n  { intros ll. destruct ll as [| x ll].\n    - cbn. rewrite dom_empty_L. done.\n    - cbn [list_to_set zip zip_with list_to_map foldr fst snd]. rewrite dom_insert_L.\n      set_solver. }\nQed.\n\nLemma dom_mkregion_incl_rev a e l:\n  (a + length l = Some e)%a →\n  list_to_set (finz.seq_between a e) ⊆ dom (mkregion a e l).\nProof.\n  rewrite /mkregion. intros Hl.\n  assert (length (finz.seq_between a e) = length l) as Hl'.\n  { rewrite finz_seq_between_length /finz.dist. solve_addr. }\n  clear Hl. revert Hl'. generalize (finz.seq_between a e). induction l.\n  { intros. rewrite zip_with_nil_r /=. rewrite dom_empty_L.\n    destruct l; [| inversion Hl']. cbn. apply empty_subseteq. }\n  { intros ll Hll. destruct ll as [| x ll]; [by inversion Hll|].\n    cbn [list_to_set zip zip_with list_to_map foldr fst snd].\n    rewrite dom_insert_L. cbn in Hll. apply Nat.succ_inj in Hll.\n    specialize (IHl ll Hll). set_solver. }\nQed.\n\nLemma dom_mkregion_eq a e l:\n  (a + length l = Some e)%a →\n  dom (mkregion a e l) = list_to_set (finz.seq_between a e).\nProof.\n  intros Hlen. apply (anti_symm subseteq).\n  - apply dom_mkregion_incl.\n  - by apply dom_mkregion_incl_rev.\nQed.\n\nLemma in_dom_mkregion a e l k:\n  k ∈ dom (mkregion a e l) →\n  k ∈ finz.seq_between a e.\nProof.\n  intros H.\n  pose proof (dom_mkregion_incl a e l) as HH.\n  rewrite elem_of_subseteq in HH.\n  specialize (HH _ H). eapply @elem_of_list_to_set; eauto.\n  typeclasses eauto.\nQed.\n\nLemma in_dom_mkregion' a e l k:\n  (a + length l = Some e)%a →\n  k ∈ finz.seq_between a e →\n  k ∈ dom (mkregion a e l).\nProof.\n  intros. rewrite dom_mkregion_eq // elem_of_list_to_set //.\nQed.\n\nLtac disjoint_map_to_list :=\n  rewrite (@map_disjoint_dom _ _ (gset Addr)) ?dom_union_L;\n  eapply disjoint_mono_l;\n  rewrite ?dom_list_to_map_singleton;\n  repeat (\n    try lazymatch goal with\n        | |- _ ∪ _ ⊆ _ =>\n          etransitivity; [ eapply union_mono_l | eapply union_mono_r ]\n        end;\n    [ first [ apply dom_mkregion_incl | reflexivity ] |..]\n  );\n  try match goal with |- _ ## dom (mkregion _ _ _) =>\n    eapply disjoint_mono_r; [ apply dom_mkregion_incl |] end;\n  rewrite -?list_to_set_app_L ?dom_list_to_map_singleton;\n  apply stdpp_extra.list_to_set_disj.\n\nLemma mkregion_sepM_to_sepL2 `{Σ: gFunctors} (a e: Addr) l (φ: Addr → Word → iProp Σ) :\n  (a + length l)%a = Some e →\n  ⊢ ([∗ map] k↦v ∈ mkregion a e l, φ k v) -∗ ([∗ list] k;v ∈ (finz.seq_between a e); l, φ k v).\nProof.\n  rewrite /mkregion. revert a e. induction l as [| x l].\n  { cbn. intros. rewrite zip_with_nil_r /=. assert (a = e) as -> by solve_addr.\n    rewrite /finz.seq_between finz_dist_0. 2: solve_addr. cbn. eauto. }\n  { cbn. intros a e Hlen. rewrite finz_seq_between_cons. 2: solve_addr.\n    cbn. iIntros \"H\". iDestruct (big_sepM_insert with \"H\") as \"[? H]\".\n    { rewrite -not_elem_of_list_to_map /=.\n      intros [ [? ?] [-> [? ?]%elem_of_zip_l%elem_of_finz_seq_between] ]%elem_of_list_fmap.\n      solve_addr. }\n    iFrame. iApply (IHl with \"H\"). solve_addr. }\nQed.\n\nLemma mkregion_prepare `{memG Σ} (a e: Addr) l :\n  (a + length l)%a = Some e →\n  ⊢ ([∗ map] k↦v ∈ mkregion a e l, k ↦ₐ v) ==∗ ([∗ list] k;v ∈ (finz.seq_between a e); l, k ↦ₐ v).\nProof.\n  iIntros (?) \"H\". iDestruct (mkregion_sepM_to_sepL2 with \"H\") as \"H\"; auto.\nQed.\n\nLemma mkregion_prepare_spec `{cfgSG Σ} (a e: Addr) l :\n  (a + length l)%a = Some e →\n  ⊢ ([∗ map] k↦v ∈ mkregion a e l, k ↣ₐ v) ==∗ ([∗ list] k;v ∈ (finz.seq_between a e); l, k ↣ₐ v).\nProof.\n  iIntros (?) \"H\". iDestruct (mkregion_sepM_to_sepL2 with \"H\") as \"H\"; auto.\nQed.\n\n\nLemma mkregion_sepM_to_sepL2_zip `{Σ: gFunctors} (a e: Addr) l l' (φ φ': Addr → Word → iProp Σ) :\n  (a + length l)%a = Some e →\n  (a + length l')%a = Some e →\n  ([∗ map] k↦v ∈ mkregion a e l, φ k v) -∗\n    ([∗ map] k↦v ∈ mkregion a e l', φ' k v) -∗\n    ([∗ map] k↦v ∈ mbkregion a e l l', φ k v.1 ∗ φ' k v.2).\nProof.\n  rewrite /mkregion. revert a e l'. induction l as [| x l].\n  { cbn. intros. rewrite zip_with_nil_r /=. assert (a = e) as -> by solve_addr.\n    rewrite /finz.seq_between /finz.dist /=. assert ((Z.to_nat (e - e)) = 0) as ->. lia. simpl. \n    rewrite /mbkregion. rewrite finz_seq_between_empty;[|solve_addr]. eauto. }\n  { cbn. intros a e l' Hlen Hlen'.\n    assert (length l' = S (length l)) as Hleneq.\n    { solve_addr. }\n    destruct l';[inversion Hleneq|]. simpl in *.\n    rewrite finz_seq_between_cons. 2: solve_addr.\n    rewrite /mbkregion /=.\n    cbn. iIntros \"H H'\". iDestruct (big_sepM_insert with \"H\") as \"[? H]\".\n    { rewrite -not_elem_of_list_to_map /=.\n      intros [ [? ?] [-> [? ?]%elem_of_zip_l%elem_of_finz_seq_between] ]%elem_of_list_fmap.\n      solve_addr. }\n    iDestruct (big_sepM_insert with \"H'\") as \"[? H']\".\n    { rewrite -not_elem_of_list_to_map /=.\n      intros [ [? ?] [-> [? ?]%elem_of_zip_l%elem_of_finz_seq_between] ]%elem_of_list_fmap.\n      solve_addr. }\n    rewrite (finz_seq_between_cons a). 2: solve_addr. simpl.\n    iApply big_sepM_insert.\n    { rewrite -not_elem_of_list_to_map /=.\n      intros [ [? ?] [-> [? ?]%elem_of_zip_l%elem_of_finz_seq_between] ]%elem_of_list_fmap.\n      solve_addr. }\n    iFrame. iApply (IHl with \"H H'\"). solve_addr. solve_addr. }\nQed.\n\nLemma mbkregion_prepare `{memG Σ, cfgSG Σ} (a e : Addr) l l' :\n  (a + length l)%a = Some e →\n  (a + length l')%a = Some e →\n  ([∗ map] k↦v ∈ mkregion a e l, k ↦ₐ v) -∗\n  ([∗ map] k↦v ∈ mkregion a e l', k ↣ₐ v) ==∗\n  ([∗ map] k↦v ∈ mbkregion a e l l', k ↦ₐ v.1 ∗ k ↣ₐ v.2).\nProof.\n  iIntros (? ?) \"H H'\". iDestruct (mkregion_sepM_to_sepL2_zip with \"H H'\") as \"H\"; auto.\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/mkregion_helpers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.25267028871027175}}
{"text": "(** * LogRel.TypeConstructorsInj: injectivity and no-confusion of type constructors, and many consequences, including subject reduction. *)\nFrom Coq Require Import CRelationClasses.\nFrom LogRel.AutoSubst Require Import core unscoped Ast Extra.\nFrom LogRel Require Import Utils BasicAst Notations Context NormalForms Weakening UntypedReduction\n  GenericTyping DeclarativeTyping DeclarativeInstance AlgorithmicTyping.\nFrom LogRel Require Import LogicalRelation Validity Fundamental DeclarativeSubst.\nFrom LogRel.LogicalRelation Require Import Escape Neutral Induction.\nFrom LogRel.Substitution Require Import Escape.\n\nSet Printing Primitive Projection Parameters.\n\nImport DeclarativeTypingProperties.\n\n\nSection TypeConstructors.\n\n  Definition type_hd_view (Γ : context) {T T' : term} (nfT : isType T) (nfT' : isType T') : Type :=\n    match nfT, nfT' with\n      | @UnivType s, @UnivType s' => s = s'\n      | @ProdType A B, @ProdType A' B' => [Γ |- A' ≅ A] × [Γ,, A' |- B ≅ B']\n      | NatType, NatType => True\n      | EmptyType, EmptyType => True\n      | NeType _, NeType _ => [Γ |- T ≅ T' : U]\n      | _, _ => False\n    end.\n\n  Lemma red_ty_complete : forall (Γ : context) (T T' : term),\n    isType T ->\n    [Γ |- T ≅ T'] ->\n    ∑ T'', [Γ |- T' ⇒* T''] × isType T''.\n  Proof.\n    intros * tyT Hconv.\n    eapply Fundamental in Hconv as [HΓ HT HT' Hconv].\n    eapply reducibleTyEq in Hconv.\n    set (HTred := reducibleTy _ HT) in *.\n    clearbody HTred.\n    clear HT.\n    destruct HTred as [[] lr] ; cbn in *.\n    destruct lr.\n    - destruct Hconv as [[]].\n      eexists ; split; tea.\n      constructor.\n    - destruct Hconv as [? red].\n      eexists ; split.\n      1: apply red.\n      apply ty_ne_whne in ne.\n      now constructor.\n    - destruct Hconv as [?? red].\n      eexists ; split.\n      1: apply red.\n      now constructor.\n    - destruct Hconv as [red].\n      eexists ; split.\n      1: apply red.\n      now constructor.\n    - destruct Hconv as [red].\n      eexists ; split.\n      1: apply red.\n      now constructor.\n  Qed.\n\n  Lemma ty_conv_inj : forall (Γ : context) (T T' : term) (nfT : isType T) (nfT' : isType T'),\n    [Γ |- T ≅ T'] ->\n    type_hd_view Γ nfT nfT'.\n  Proof.\n    intros * Hconv.\n    eapply Fundamental in Hconv as [HΓ HT HT' Hconv].\n    eapply reducibleTyEq in Hconv.\n    set (HTred := reducibleTy _ HT) in *.\n    clearbody HTred.\n    clear HT.\n    eapply reducibleTy in HT'.\n    destruct HTred as [[] lrT].\n    cbn in *.\n    inversion lrT ; subst ; clear lrT.\n    - subst.\n      destruct Hconv as [].\n      assert (T' = U) as HeqT' by (eapply redtywf_whnf ; gen_typing); subst.\n      destruct H.\n      assert (T = U) as HeqU by (eapply redtywf_whnf ; gen_typing). \n      destruct nfT ; inversion HeqU ; subst.\n      2: now exfalso ; gen_typing.\n      clear HeqU.\n      remember U as T eqn:HeqU in nfT' |- * at 2.\n      destruct nfT' ; inversion HeqU ; subst.\n      2: now exfalso ; gen_typing.\n      now reflexivity.\n    - destruct neA as [nT ? ne], Hconv as [nT' ? ne'] ; cbn in *.\n      assert (T = nT) as <- by\n        (apply red_whnf ; gen_typing).\n      assert (T' = nT') as <- by\n        (apply red_whnf ; gen_typing).\n      destruct nfT.\n      + apply ty_ne_whne in ne, ne'; exfalso ; gen_typing.\n      + apply ty_ne_whne in ne, ne'; exfalso ; gen_typing.\n      + apply ty_ne_whne in ne, ne'; inversion ne.\n      + destruct nfT'.\n        * apply ty_ne_whne in ne, ne'; exfalso ; gen_typing.\n        * apply ty_ne_whne in ne, ne'; exfalso ; gen_typing.\n        * apply ty_ne_whne in ne, ne'; inversion ne'.\n        * apply ty_ne_whne in ne, ne'; inversion ne'; gen_typing.\n        * apply ty_ne_whne in ne, ne'. inversion ne.\n      + destruct nfT'.\n        * apply ty_ne_whne in ne, ne'; exfalso ; gen_typing.\n        * apply ty_ne_whne in ne, ne'; exfalso ; gen_typing.\n        * apply ty_ne_whne in ne, ne'; inversion ne'.\n        * apply ty_ne_whne in ne, ne'; inversion ne'; gen_typing.\n        * apply ty_ne_whne in ne, ne'. cbn. gen_typing.\n    - assert [|- Γ] by (apply escape in HT' ; boundary).\n      rewrite <- (PiRedTyPack.pack_beta ΠA ΠAad) in *.\n      remember (PiRedTyPack.pack ΠA ΠAad) as ΠA' eqn:Heq in *.\n      clear ΠA ΠAad Heq.\n      destruct ΠA' as [dom cod red], Hconv as [dom' cod' red'] ; cbn in *.\n      assert (T = tProd dom cod) as HeqT by (apply red_whnf ; gen_typing). \n      assert (T' = tProd dom' cod') as HeqT' by (apply red_whnf ; gen_typing).\n      destruct nfT.\n      1,3,4: congruence.\n      2: subst ; exfalso ; gen_typing.\n      destruct nfT'.\n      1,3,4: congruence.\n      2: subst ; exfalso ; gen_typing.\n      inversion HeqT ; inversion HeqT' ; subst ; clear HeqT HeqT'.\n      cbn.\n      assert [Γ |-[ de ] dom' ≅ dom].\n      {\n        symmetry.\n        replace dom with (dom⟨wk_id (Γ := Γ)⟩) by now bsimpl.\n        replace dom' with (dom'⟨wk_id (Γ := Γ)⟩) by now bsimpl.\n        now unshelve now eapply LogicalRelation.Escape.escapeEq.\n      }\n      split ; tea.\n      replace cod with (cod[tRel 0 .: (wk1 (Γ := Γ) dom') >> tRel ])\n        by (bsimpl ; rewrite scons_eta' ; now bsimpl).\n      replace cod' with (cod'[tRel 0 .: (wk1 (Γ := Γ) dom') >> tRel ])\n        by (bsimpl ; rewrite scons_eta' ; now bsimpl).\n      assert [ |-[ de ] Γ,, dom'].\n      {\n        econstructor ; tea.\n        eapply prod_ty_inv.\n        now gen_typing.\n      }\n      (unshelve now eapply LogicalRelation.Escape.escapeEq) ; tea.\n      apply neuTerm.\n      1: econstructor; reflexivity.\n      2: econstructor.\n      1,2: eapply wfTermConv.\n      2,4: eapply typing_wk; tea.\n      1,2: rewrite wk1_ren_on; constructor; tea; constructor.\n    - destruct Hconv.\n      assert (T' = tNat) as HeqT' by (eapply redtywf_whnf ; gen_typing).\n      assert (T = tNat) as HeqT by (destruct NA; eapply redtywf_whnf ; gen_typing).\n      destruct nfT; inversion HeqT.\n      + destruct nfT'; inversion HeqT'.\n        * constructor.\n        * exfalso; subst; inversion w.\n      + exfalso; subst; inversion w.\n    - destruct Hconv.\n      assert (T' = tEmpty) as HeqT' by (eapply redtywf_whnf ; gen_typing).\n      assert (T = tEmpty) as HeqT by (destruct NA; eapply redtywf_whnf ; gen_typing).\n      destruct nfT; inversion HeqT.\n      + destruct nfT'; inversion HeqT'.\n        * econstructor.\n        * exfalso; subst; inversion w.\n      + exfalso; subst; inversion w.\n  Qed.\n\n  Corollary red_ty_compl_univ_l Γ T :\n    [Γ |- U ≅ T] ->\n    [Γ |- T ⇒* U].\n  Proof.\n    intros HT.\n    pose proof HT as HT'.\n    unshelve eapply red_ty_complete in HT' as (T''&[? nfT]).\n    2: econstructor.\n    enough (T'' = U) as -> by easy.\n    assert [Γ |- U ≅ T''] as Hconv by\n      (etransitivity ; [eassumption|now eapply RedConvTyC]).\n    unshelve eapply ty_conv_inj in Hconv.\n    1: econstructor.\n    1: eassumption.\n    now destruct nfT, Hconv.\n  Qed.\n\n  Corollary red_ty_compl_univ_r Γ T :\n    [Γ |- T ≅ U] ->\n    [Γ |- T ⇒* U].\n  Proof.\n    intros.\n    eapply red_ty_compl_univ_l.\n    now symmetry.\n  Qed.\n\n  Corollary red_ty_compl_nat_l Γ T :\n    [Γ |- tNat ≅ T] ->\n    [Γ |- T ⇒* tNat].\n  Proof.\n    intros HT.\n    pose proof HT as HT'.\n    unshelve eapply red_ty_complete in HT' as (T''&[? nfT]).\n    2: econstructor.\n    enough (T'' = tNat) as -> by easy.\n    assert [Γ |- tNat ≅ T''] as Hconv by\n      (etransitivity ; [eassumption|now eapply RedConvTyC]).\n    unshelve eapply ty_conv_inj in Hconv.\n    1: econstructor.\n    1: eassumption.\n    now destruct nfT, Hconv.\n  Qed.\n\n  Corollary red_ty_compl_nat_r Γ T :\n    [Γ |- T ≅ tNat] ->\n    [Γ |- T ⇒* tNat].\n  Proof.\n    intros.\n    eapply red_ty_compl_nat_l.\n    now symmetry.\n  Qed.\n\n  Corollary red_ty_compl_empty_l Γ T :\n    [Γ |- tEmpty ≅ T] ->\n    [Γ |- T ⇒* tEmpty].\n  Proof.\n    intros HT.\n    pose proof HT as HT'.\n    unshelve eapply red_ty_complete in HT' as (T''&[? nfT]).\n    2: econstructor.\n    enough (T'' = tEmpty) as -> by easy.\n    assert [Γ |- tEmpty ≅ T''] as Hconv by\n      (etransitivity ; [eassumption|now eapply RedConvTyC]).\n    unshelve eapply ty_conv_inj in Hconv.\n    1: econstructor.\n    1: eassumption.\n    now destruct nfT, Hconv.\n  Qed.\n\n  Corollary red_ty_compl_empty_r Γ T :\n    [Γ |- T ≅ tEmpty] ->\n    [Γ |- T ⇒* tEmpty].\n  Proof.\n    intros.\n    eapply red_ty_compl_empty_l.\n    now symmetry.\n  Qed.\n\n  Corollary red_ty_compl_prod_l Γ A B T :\n    [Γ |- tProd A B ≅ T] ->\n    ∑ A' B', [× [Γ |- T ⇒* tProd A' B'], [Γ |- A' ≅ A] & [Γ,, A' |- B ≅ B']].\n  Proof.\n    intros HT.\n    pose proof HT as HT'.\n    unshelve eapply red_ty_complete in HT as (T''&[? nfT]).\n    2: econstructor.\n    assert [Γ |- tProd A B ≅ T''] as Hconv by \n      (etransitivity ; [eassumption|now eapply RedConvTyC]).\n    unshelve eapply ty_conv_inj in Hconv.\n    1: constructor.\n    1: assumption.\n    destruct nfT, Hconv.\n    do 2 eexists ; split.\n    all: eassumption.\n  Qed.\n\n  Corollary prod_ty_inj Γ A B  A' B' :\n    [Γ |- tProd A B ≅ tProd A' B'] ->\n    [Γ |- A' ≅ A] × [Γ,, A' |- B ≅ B'].\n  Proof.\n    intros Hty.\n    unshelve eapply ty_conv_inj in Hty.\n    1-2: constructor.\n    now eassumption.\n  Qed.\n\nEnd TypeConstructors.\n\nSection Boundary.\n\n  Lemma in_ctx_wf Γ n decl :\n    [|- Γ] ->\n    in_ctx Γ n decl ->\n    [Γ |- decl].\n  Proof.\n    intros HΓ Hin.\n    induction Hin.\n    - inversion HΓ ; subst ; cbn in * ; refold.\n      renToWk.\n      now apply typing_wk.\n    - inversion HΓ ; subst ; cbn in * ; refold.\n      renToWk.\n      now eapply typing_wk.\n  Qed.\n\n  Let PCon (Γ : context) := True.\n  Let PTy (Γ : context) (A : term) := True.\n  Let PTm (Γ : context) (A t : term) := [Γ |- A].\n  Let PTyEq (Γ : context) (A B : term) := [Γ |- A] × [Γ |- B].\n  Let PTmEq (Γ : context) (A t u : term) := [× [Γ |- A], [Γ |- t : A] & [Γ |- u : A]].\n\n  Lemma boundary : WfDeclInductionConcl PCon PTy PTm PTyEq PTmEq.\n  Proof.\n    subst PCon PTy PTm PTyEq PTmEq.\n    apply WfDeclInduction.\n    all: try easy.\n    - intros.\n      now eapply in_ctx_wf.\n    - intros.\n      now econstructor.\n    - intros.\n      now eapply typing_subst1, prod_ty_inv.\n    - intros; gen_typing.\n    - intros; gen_typing.\n    - intros.\n      now eapply typing_subst1.\n    - intros; gen_typing.\n    - intros.\n      now eapply typing_subst1.\n    - intros * ? _ ? [] ? [].\n      split.\n      all: constructor ; tea.\n      eapply stability1.\n      3: now symmetry.\n      all: eassumption.\n    - intros * ? [].\n      split.\n      all: now econstructor.\n    - intros.\n      split.\n      + now eapply typing_subst1.\n      + econstructor ; tea.\n        now econstructor.\n      + now eapply typing_subst1.\n    - intros * ? _ ? [] ? [].\n      split.\n      + easy.\n      + now econstructor.\n      + econstructor ; tea.\n        eapply stability1.\n        4: eassumption.\n        all: econstructor ; tea.\n        now symmetry.\n    - intros * ? [] ? [].\n      split.\n      + eapply typing_subst1.\n        1: eassumption.\n        now eapply prod_ty_inv.\n      + now econstructor.\n      + econstructor.\n        1: now econstructor.\n        eapply typing_subst1.\n        1: now symmetry.\n        econstructor.\n        now eapply prod_ty_inv.\n    - intros * ? []; split; gen_typing.\n    - intros * ? [] ? [] ? [] ? []; split.\n      + now eapply typing_subst1.\n      + gen_typing.\n      + eapply ty_conv.\n        assert [Γ |-[de] tNat ≅ tNat] by now constructor.\n        1: eapply ty_natElim; tea; eapply ty_conv; tea. \n        * eapply typing_subst1; tea; do 2 constructor; boundary.\n        * eapply elimSuccHypTy_conv ; tea.\n          now boundary.\n        * symmetry; now eapply typing_subst1.\n    - intros **; split; tea.\n      eapply ty_natElim; tea; constructor; boundary.   \n    - intros **.\n      assert [Γ |- tSucc n : tNat] by now constructor.\n      assert [Γ |- P[(tSucc n)..]] by now eapply typing_subst1.\n      split; tea.\n      2: eapply ty_simple_app.\n      1,5: now eapply ty_natElim.\n      2: tea.\n      1: now eapply typing_subst1.\n      replace (arr _ _) with (arr P P[tSucc (tRel 0)]⇑)[n..] by now bsimpl.\n      eapply ty_app; tea.\n    - intros * ? [] ? []; split.\n      + now eapply typing_subst1.\n      + gen_typing.\n      + eapply ty_conv.\n        assert [Γ |-[de] tEmpty ≅ tEmpty] by now constructor.\n        1: eapply ty_emptyElim; tea; eapply ty_conv; tea. \n        * symmetry; now eapply typing_subst1.\n    - intros * ? [] ? [].\n      split ; gen_typing.\n    - intros * ? [].\n      split ; gen_typing.\n    - intros * ? [] ? [].\n      split ; gen_typing.\n  Qed.\n\nEnd Boundary.\n\nCorollary boundary_tm Γ A t : [Γ |- t : A] -> [Γ |- A].\nProof.\n  now intros ?%boundary.\nQed.\n\nCorollary boundary_ty_conv_l Γ A B : [Γ |- A ≅ B] -> [Γ |- A].\nProof.\n  now intros ?%boundary.\nQed.\n\nCorollary boundary_ty_conv_r Γ A B : [Γ |- A ≅ B] -> [Γ |- B].\nProof.\n  now intros ?%boundary.\nQed.\n\nCorollary boundary_ored_ty_r Γ A B : [Γ |- A ⇒ B] -> [Γ |- B].\nProof.\n  now intros ?%RedConvTy%boundary.\nQed.\n\nCorollary boundary_red_ty_r Γ A B : [Γ |- A ⇒* B] -> [Γ |- B].\nProof.\n  now intros ?%RedConvTyC%boundary.\nQed.\n\nCorollary boundary_tm_conv_l Γ A t u : [Γ |- t ≅ u : A] -> [Γ |- t : A].\nProof.\n  now intros []%boundary.\nQed.\n\nCorollary boundary_tm_conv_r Γ A t u : [Γ |- t ≅ u : A] -> [Γ |- u : A].\nProof.\n  now intros []%boundary.\nQed.\n\nCorollary boundary_tm_conv_ty Γ A t u : [Γ |- t ≅ u : A] -> [Γ |- A].\nProof.\n  now intros []%boundary.\nQed.\n\nCorollary boundary_ored_tm_l Γ A t u : [Γ |- t ⇒ u : A] -> [Γ |- t : A].\nProof.\n  now intros []%RedConvTe%boundary.\nQed.\n\nCorollary boundary_ored_tm_r Γ A t u : [Γ |- t ⇒ u : A] -> [Γ |- u : A].\nProof.\n  now intros []%RedConvTe%boundary.\nQed.\n\nCorollary boundary_ored_tm_ty Γ A t u : [Γ |- t ⇒ u : A] -> [Γ |- A].\nProof.\n  now intros []%RedConvTe%boundary.\nQed.\n\nCorollary boundary_red_tm_r Γ A t u : [Γ |- t ⇒* u : A] -> [Γ |- u : A].\nProof.\n  now intros []%RedConvTeC%boundary.\nQed.\n\nCorollary boundary_red_tm_ty Γ A t u : [Γ |- t ⇒* u : A] -> [Γ |- A].\nProof.\n  now intros []%RedConvTeC%boundary.\nQed.\n\n#[export] Hint Resolve\n  boundary_tm boundary_ty_conv_l boundary_ty_conv_r\n  boundary_tm_conv_l boundary_tm_conv_r boundary_tm_conv_ty\n  boundary_ored_tm_l boundary_ored_tm_r boundary_ored_tm_ty\n  boundary_red_tm_l boundary_red_tm_r boundary_red_tm_ty\n  boundary_ored_ty_r boundary_red_ty_r : boundary.\n\nLemma boundary_ctx_conv_l (Γ Δ : context) :\n  [ |- Γ ≅ Δ] ->\n  [|- Γ].\nProof.\n  destruct 1.\n  all: econstructor ; boundary.\nQed.\n\n#[export] Hint Resolve boundary_ctx_conv_l : boundary.\n\nCorollary conv_ctx_refl_l (Γ Δ : context) :\n[ |- Γ ≅ Δ] ->\n[|- Γ ≅ Γ].\nProof.\n  intros.\n  eapply ctx_refl ; boundary.\nQed.\n\nLemma typing_eta' (Γ : context) A B f :\n  [Γ |- f : tProd A B] ->\n  [Γ,, A |- eta_expand f : B].\nProof.\n  intros Hf.\n  eapply typing_eta ; tea.\n  - eapply prod_ty_inv.\n    boundary.\n  - eapply prod_ty_inv.\n    boundary.\nQed.\n\nCorollary red_ty_compl_prod_r Γ A B T :\n  [Γ |- T ≅ tProd A B] ->\n  ∑ A' B', [× [Γ |- T ⇒* tProd A' B'], [Γ |- A ≅ A'] & [Γ,, A |- B' ≅ B]].\nProof.\n  intros HT.\n  symmetry in HT.\n  eapply red_ty_compl_prod_l in HT as (?&?&[HA ? HB]).\n  do 2 eexists ; split ; tea.\n  1: now symmetry.\n  symmetry.\n  eapply stability1 ; tea.\n  1-2: now boundary.\n  now symmetry.\nQed.\n\nSection Stability.\n\n  Lemma conv_well_subst (Γ Δ : context) :\n    [ |- Γ ≅ Δ] ->\n    [Γ |-s tRel : Δ].\n  Proof.\n    induction 1 as [| * ? HA].\n    - now econstructor.\n    - assert [Γ |- A] by boundary.\n      assert [|- Γ,, A] by\n        (econstructor ; boundary).\n      econstructor ; tea.\n      + eapply well_subst_ext, well_subst_up ; tea.\n        reflexivity.\n      + eapply wfTermConv.\n        1: econstructor; [gen_typing| now econstructor].\n        rewrite <- rinstInst'_term; do 2 erewrite <- wk1_ren_on.\n        now eapply typing_wk.\n  Qed.\n\n  Let PCon (Γ : context) := True.\n  Let PTy (Γ : context) (A : term) := forall Δ,\n    [|- Δ ≅ Γ] -> [Δ |- A].\n  Let PTm (Γ : context) (A t : term) := forall Δ,\n    [|- Δ ≅ Γ] -> [Δ |- t : A].\n  Let PTyEq (Γ : context) (A B : term) := forall Δ,\n    [|- Δ ≅ Γ] -> [Δ |- A ≅ B].\n  Let PTmEq (Γ : context) (A t u : term) := forall Δ,\n    [|- Δ ≅ Γ] -> [Δ |- t ≅ u : A].\n\n  Theorem stability : WfDeclInductionConcl PCon PTy PTm PTyEq PTmEq.\n  Proof.\n    red.\n    repeat match goal with |- _ × _ => split end.\n    1: now unfold PCon.\n    all: intros * Hty Δ HΔ.\n    all: pose proof (boundary_ctx_conv_l _ _ HΔ).\n    all: eapply conv_well_subst in HΔ.\n    all: pose proof (subst_refl _ _ _ HΔ).\n    all: eapply typing_subst in Hty ; tea.\n    all: asimpl ; repeat (rewrite idSubst_term in Hty ; [..|reflexivity]).\n    all: try eassumption.\n  Qed.\n\n\n  #[global] Instance ConvCtxSym : Symmetric ConvCtx.\n  Proof.\n    intros Γ Δ.\n    induction 1.\n    all: constructor ; tea.\n    eapply stability ; tea.\n    now symmetry.\n  Qed.\n\n  Corollary conv_ctx_refl_r (Γ Δ : context) :\n    [ |- Γ ≅ Δ] ->\n    [|- Δ ≅ Δ].\n  Proof.\n    intros H.\n    symmetry in H.\n    now eapply ctx_refl ; boundary.\n  Qed.\n\n  #[global] Instance ConvCtxTrans : Transitive ConvCtx.\n  Proof.\n    intros Γ1 Γ2 Γ3 H1 H2.\n    induction H1 in Γ3, H2 |- *.\n    all: inversion H2 ; subst ; clear H2.\n    all: constructor.\n    1: eauto.\n    etransitivity ; tea.\n    now eapply stability.\n  Qed.\n\nEnd Stability.\n\nLemma termGen' Γ t A :\n[Γ |- t : A] ->\n∑ A', (termGenData Γ t A') × [Γ |- A' ≅ A].\nProof.\nintros * H.\ndestruct (termGen _ _ _ H) as [? [? [->|]]].\n2: now eexists.\neexists ; split ; tea.\neconstructor.\nboundary.\nQed.\n\nTheorem subject_reduction_one Γ t t' A :\n    [Γ |- t : A] ->\n    [t ⇒ t'] ->\n    [Γ |- t ⇒ t' : A].\nProof.\n  intros Hty Hred.\n  induction Hred in Hty, A |- *.\n  - apply termGen' in Hty as (?&((?&?&[-> Hty])&Heq)).\n    apply termGen' in Hty as (?&((?&[->])&Heq')).\n    eapply prod_ty_inj in Heq' as [? HeqB].\n    econstructor.\n    1: econstructor ; gen_typing.\n    etransitivity ; tea.\n    eapply typing_subst1 ; tea.\n    now econstructor.\n  - apply termGen' in Hty as (?&((?&?&[->])&Heq)).\n    econstructor ; tea.\n    econstructor.\n    1: now eapply IHHred.\n    refold ; gen_typing.\n  - apply termGen' in Hty as [?[[->]?]].\n    econstructor; tea.\n    econstructor; tea.\n    now eapply IHHred.\n  - apply termGen' in Hty as [?[[->]?]].\n    econstructor; tea; econstructor; tea.\n  - apply termGen' in Hty as [?[[-> ??? hsn] Heq]].\n    econstructor; tea; econstructor; tea.\n    now apply termGen' in hsn as [? [[]?]].\n  - apply termGen' in Hty as [?[[->]?]].\n    econstructor; tea.\n    econstructor; tea.\n    now eapply IHHred.\nQed.\n\nTheorem subject_reduction Γ t t' A :\n  [Γ |- t : A] ->\n  [t ⇒* t'] ->\n  [Γ |- t ⇒* t' : A].\nProof.\n  intros Hty.\n  induction 1 as [| ? ? ? o red] in A, Hty |- *.\n  1: now econstructor.\n  eapply subject_reduction_one in o ; tea.\n  etransitivity.\n  2: eapply IHred.\n  1: now constructor.\n  boundary.\nQed.\n\nLemma subject_reduction_one_type Γ A A' :\n  [Γ |- A] ->\n  [A ⇒ A'] ->\n  [Γ |- A ⇒ A'].\nProof.\n  intros Hty.\n  inversion 1 ; subst.\n  all: inversion Hty ; subst ; clear Hty.\n  all: econstructor.\n  all: now eapply subject_reduction_one.\nQed.\n\nTheorem subject_reduction_type Γ A A' :\n[Γ |- A] ->\n[A ⇒* A'] ->\n[Γ |- A ⇒* A'].\nProof.\n  intros Hty.\n  induction 1 as [| ? ? ? o red] in Hty |- *.\n  1: now econstructor.\n  eapply subject_reduction_one_type in o ; tea.\n  etransitivity.\n  2: eapply IHred.\n  1: now constructor.\n  boundary.\nQed.\n\nCorollary conv_red_l Γ A A' A'' : [Γ |-[de] A' ≅ A''] -> [A' ⇒* A] -> [Γ |-[de] A ≅ A''].\nProof.\n  intros Hconv **.\n  etransitivity ; tea.\n  symmetry.\n  eapply RedConvTyC, subject_reduction_type ; tea.\n  boundary.\nQed.", "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/TypeConstructorsInj.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.25267028176721046}}
{"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 AST.\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  | _ => 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_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\n  destruct (propagate_float_constants tt); simpl; auto.\n\n  rewrite shift_symbol_address; auto.\n\n  rewrite Int.add_commut. rewrite shift_symbol_address. rewrite Val.add_commut. auto.\n\n  rewrite Int.add_commut; auto.\n\n  rewrite Val.add_assoc. rewrite Int.add_commut. auto.\n\n  change (Val.add (Vint n1) (Val.add sp (Vint n2)) = Val.add sp (Vint (Int.add n1 n2))).\n  rewrite Val.add_permut. auto.\n\n  rewrite shift_symbol_address; auto.\n\n  rewrite Val.add_assoc; auto.\n\n  unfold symbol_address. destruct (Genv.find_symbol ge s1); auto.\n\n  rewrite Val.sub_add_opp. rewrite Val.add_assoc. simpl. rewrite Int.sub_add_opp. auto.\n\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\n  destruct (Int.ltu n2 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\n  unfold eval_static_intoffloat. destruct (Float.intoffloat n1); simpl in H0; inv H0.\n  simpl; auto.\n\n  destruct (propagate_float_constants tt); simpl; auto.\n\n  unfold eval_static_condition_val, Val.of_optbool.\n  destruct (eval_static_condition c vl0) eqn:?.\n  rewrite (eval_static_condition_correct _ _ _ m _ H Heqo).\n  destruct b; simpl; auto.\n  simpl; 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. apply Val.add_commut.\n  repeat rewrite Val.add_assoc. auto.\n  fold (Val.add (Vint n1) (Val.add sp (Vint ofs))).\n  rewrite Val.add_permut. decEq. rewrite Val.add_commut. auto.\n  rewrite shift_symbol_address. 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 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 r2,\n  rs#r2 = Vint n ->\n  let (op, args) := make_shlimm n r1 r2 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  destruct (Int.ltu n Int.iwordsize) eqn:?; intros.\n  rewrite Val.shl_rolm; auto. econstructor; split; eauto. auto.\n  econstructor; split; eauto. simpl. congruence.\nQed.\n\nLemma make_shrimm_correct:\n  forall n r1 r2,\n  rs#r2 = Vint n ->\n  let (op, args) := make_shrimm n r1 r2 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  destruct (Int.ltu n Int.iwordsize) eqn:?.\n  econstructor; split; eauto. simpl. auto.\n  econstructor; split; eauto. simpl. congruence.\nQed.\n\nLemma make_shruimm_correct:\n  forall n r1 r2,\n  rs#r2 = Vint n ->\n  let (op, args) := make_shruimm n r1 r2 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  destruct (Int.ltu n Int.iwordsize) eqn:?; intros.\n  rewrite Val.shru_rolm; auto. econstructor; split; eauto. auto.\n  econstructor; split; eauto. simpl. congruence.\nQed.\n\nLemma make_mulimm_correct:\n  forall n r1 r2,\n  rs#r2 = Vint n ->\n  let (op, args) := make_mulimm n r1 r2 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). rewrite Val.shl_rolm.\n  econstructor; split; eauto. auto.\n  eapply Int.is_power2_range; eauto.\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  econstructor; split. simpl; eauto.\n  exploit Int.is_power2_range; eauto. intros RANGE.\n  rewrite <- Val.shru_rolm; auto. rewrite H0 in H.\n  destruct (rs#r1); simpl in *; inv H.\n  destruct (Int.eq n Int.zero); inv H2.\n  rewrite RANGE. rewrite (Int.divu_pow2 i0 _ _ Heqo). auto.\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 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(* add *)\n  InvApproxRegs. SimplVMA. inv H0. rewrite H1. rewrite Val.add_commut. apply make_addimm_correct.\n  InvApproxRegs. SimplVMA. inv H0. rewrite H. apply make_addimm_correct.\n(* sub *)\n  InvApproxRegs; SimplVMA. inv H0. rewrite H1. econstructor; split; eauto.\n  InvApproxRegs; SimplVMA. inv H0. rewrite H. rewrite Val.sub_add_opp. apply make_addimm_correct.\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(* and *)\n  InvApproxRegs. SimplVMA. inv H0. rewrite H1. rewrite Val.and_commut. apply make_andimm_correct.\n  InvApproxRegs. SimplVMA. inv H0. rewrite H. apply make_andimm_correct.\n(* or *)\n  InvApproxRegs. SimplVMA. inv H0. rewrite H1. rewrite Val.or_commut. apply make_orimm_correct.\n  InvApproxRegs. SimplVMA. inv H0. rewrite H. apply make_orimm_correct.\n(* xor *)\n  InvApproxRegs. SimplVMA. inv H0. rewrite H1. rewrite Val.xor_commut. apply make_xorimm_correct.\n  InvApproxRegs. SimplVMA. inv H0. rewrite H. apply make_xorimm_correct.\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(* cmp *)\n  generalize (cond_strength_reduction_correct c args0 vl0).\n  destruct (cond_strength_reduction c args0 vl0) as [c' args']; intros.\n  rewrite <- H1 in H0; auto. econstructor; split; eauto.\n(* default *)\n  exists v; 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 H; rewrite H0. rewrite shift_symbol_address. auto.\n  rewrite H; rewrite H0. rewrite Int.add_commut. rewrite shift_symbol_address. rewrite Val.add_commut; auto.\n  rewrite H; rewrite H0. rewrite Val.add_assoc; auto.\n  rewrite H; rewrite H0. rewrite Val.add_permut; auto.\n  rewrite H0. auto.\n  rewrite H. rewrite Val.add_commut. auto.\n  rewrite H0. rewrite Val.add_commut; auto.\n  rewrite H; auto.\n  rewrite H. rewrite shift_symbol_address. auto.\n  rewrite H. rewrite shift_symbol_address. auto.\n  rewrite H. rewrite Val.add_assoc. auto.\n  auto.\nQed.\n\nEnd STRENGTH_REDUCTION.\n\nEnd ANALYSIS.\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/powerpc/ConstpropOpproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.25267028176721046}}
{"text": "Require Import Algebra.Monad.Utils Algebra.SetoidCat SetoidUtils Algebra.Functor Algebra.Applicative Tactics Algebra.SetoidCat.PairUtils Algebra.Monad.\n\nRequire Import RelationClasses Relation_Definitions Morphisms SetoidClass.\n\nOpen Scope type_scope.\n\n\n\nSection Instances.\nInstance monadFunctor  {m mS} {mnd : @Monad m mS} : @Functor m mS.\nProof.\n  exists (@monad_fmap m mS mnd).\n  intros. simpl. arrequiv. normalize_monad. bindproper. simpl. arrequiv. unfold comp. rewrite left_unit. simpl. reflexivity.\n  intros. simpl. arrequiv. rewrite right_unit_equiv. reflexivity. simpl. arrequiv.\nDefined.\n\nEnd Instances.\n", "meta": {"author": "xu-hao", "repo": "CertifiedQueryArrow", "sha": "8db512e0ebea8011b0468d83c9066e4a94d8d1c4", "save_path": "github-repos/coq/xu-hao-CertifiedQueryArrow", "path": "github-repos/coq/xu-hao-CertifiedQueryArrow/CertifiedQueryArrow-8db512e0ebea8011b0468d83c9066e4a94d8d1c4/Algebra/Functor/Monad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2526665748766075}}
{"text": "(** Commutation of groupoid quotient with sums *)\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\n\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.Groupoids.\n\nRequire Import UniMath.Bicategories.Core.Bicat.\nImport Bicat.Notations.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.Base.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.Map1Cells.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.Map2Cells.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.Identitor.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.Compositor.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.PseudoFunctorBicat.\nRequire Import UniMath.Bicategories.PseudoFunctors.PseudoFunctor.\nImport UniMath.Bicategories.PseudoFunctors.PseudoFunctor.Notations.\nRequire Import UniMath.Bicategories.PseudoFunctors.Examples.Identity.\nRequire Import UniMath.Bicategories.PseudoFunctors.Examples.Composition.\nRequire Import UniMath.Bicategories.Transformations.PseudoTransformation.\nRequire Import UniMath.Bicategories.Core.Examples.OneTypes.\n\nRequire Import signature.hit_signature.\nRequire Import prelude.all.\nRequire Import algebra.one_types_polynomials.\nRequire Import algebra.groupoid_polynomials.\n\nLocal Open Scope cat.\n\nOpaque comp_psfunctor.\n\nDefinition gquot_inl_grpd\n           {P₁ P₂ : poly_code}\n           {G : groupoid}\n  : gquot (poly_act_groupoid P₁ G) → gquot (poly_act_groupoid (P₁ + P₂) G).\nProof.\n  use gquot_rec.\n  - exact (λ z, gcl (poly_act_groupoid (P₁ + P₂) G) (inl z)).\n  - exact (λ a₁ a₂ g, @gcleq (poly_act_groupoid (P₁ + P₂) G) (inl a₁) (inl a₂) g).\n  - exact (λ _, ge _ _).\n  - exact (λ a₁ a₂ a₃ g₁ g₂,\n           @gconcat\n             (poly_act_groupoid (P₁ + P₂) G)\n             (inl a₁) (inl a₂) (inl a₃) g₁ g₂).\n  - apply gtrunc.\nDefined.\n\nDefinition gquot_inr_grpd\n           {P₁ P₂ : poly_code}\n           {G : groupoid}\n  : gquot (poly_act_groupoid P₂ G) → gquot (poly_act_groupoid (P₁ + P₂) G).\nProof.\n  use gquot_rec.\n  - exact (λ z, gcl (poly_act_groupoid (P₁ + P₂) G) (inr z)).\n  - exact (λ a₁ a₂ g, @gcleq (poly_act_groupoid (P₁ + P₂) G) (inr a₁) (inr a₂) g).\n  - exact (λ _, ge _ _).\n  - exact (λ a₁ a₂ a₃ g₁ g₂,\n           @gconcat\n             (poly_act_groupoid (P₁ + P₂) G)\n             (inr a₁) (inr a₂) (inr a₃) g₁ g₂).\n  - apply gtrunc.\nDefined.\n\nSection GQuotSum.\n  Context {P₁ P₂ : poly_code}\n          (IHP₁ : pstrans\n                    (comp_psfunctor (⟦ P₁ ⟧) gquot_psfunctor)\n                    (comp_psfunctor gquot_psfunctor ⦃ P₁ ⦄))\n          (IHP₂ : pstrans\n                    (comp_psfunctor (⟦ P₂ ⟧) gquot_psfunctor)\n                    (comp_psfunctor gquot_psfunctor ⦃ P₂ ⦄)).\n\n  Definition sum_gquot_data_comp\n             (X : grpd_bicat)\n    : (comp_psfunctor (⟦ P₁ + P₂ ⟧) gquot_psfunctor) X\n      -->\n      (comp_psfunctor gquot_psfunctor ⦃ P₁ + P₂ ⦄) X.\n  Proof.\n    intro z.\n    induction z as [z | z].\n    - exact (gquot_inl_grpd (IHP₁ X z)).\n    - exact (gquot_inr_grpd (IHP₂ X z)).\n  Defined.\n  \n  Definition gquot_inl_grpd_gquot_functor\n             {X Y : grpd_bicat}\n             (f : X --> Y)\n    : ∏ (z : gquot (⦃ P₁ ⦄ X)),\n      # (comp_psfunctor gquot_psfunctor ⦃ P₁ + P₂ ⦄) f (gquot_inl_grpd z)\n      =\n      gquot_inl_grpd (gquot_functor_map (# ⦃ P₁ ⦄ f) z).\n  Proof.\n    use gquot_ind_set.\n    - exact (λ _, idpath _).\n    - abstract\n        (intros a₁ a₂ g ;\n         use map_PathOver ;\n         refine (whisker_square\n                   (idpath _)\n                   _\n                   _\n                   (idpath _)\n                   _) ;\n           [ refine (!(!(maponpathscomp _ _ _) @ _)) ;\n             refine (maponpaths\n                       (maponpaths (gquot_functor_map (poly_act_functor (P₁ + P₂) f)))\n                       (gquot_rec_beta_gcleq _ _ _ _ _ _ _ _ _ _) @ _) ;\n             apply gquot_rec_beta_gcleq\n           | refine (!(!(maponpathscomp _ _ _) @ _)) ;\n             refine (maponpaths\n                       (maponpaths gquot_inl_grpd)\n                       (gquot_rec_beta_gcleq _ _ _ _ _ _ _ _ _ _) @ _) ;\n             apply gquot_rec_beta_gcleq\n           | apply vrefl]).\n    - intro.\n      exact (gtrunc _ _ _).\n  Defined.\n\n  Definition sum_gquot_data_nat_inl\n             {X Y : grpd_bicat}\n             (f : X --> Y)\n             (z : ⟦ P₁ ⟧ (gquot_psfunctor X) : one_type)\n    : # (comp_psfunctor gquot_psfunctor ⦃ P₁ + P₂ ⦄) f (gquot_inl_grpd (IHP₁ X z))\n      =\n      sum_gquot_data_comp Y (inl (# (⟦ P₁ ⟧) (gquot_functor_map f) z)).\n  Proof.\n    refine (_ @ maponpaths gquot_inl_grpd (pr1 (psnaturality_of IHP₁ f) z)).\n    exact (gquot_inl_grpd_gquot_functor f (IHP₁ X z)).\n  Defined.\n\n  Definition gquot_inr_grpd_gquot_functor\n             {X Y : grpd_bicat}\n             (f : X --> Y)\n    : ∏ (z : gquot (⦃ P₂ ⦄ X)),\n      # (comp_psfunctor gquot_psfunctor ⦃ P₁ + P₂ ⦄) f (gquot_inr_grpd z)\n      =\n      gquot_inr_grpd (gquot_functor_map (# ⦃ P₂ ⦄ f) z).\n  Proof.\n    use gquot_ind_set.\n    - exact (λ _, idpath _).\n    - abstract\n        (intros a₁ a₂ g ;\n         use map_PathOver ;\n         refine (whisker_square\n                   (idpath _)\n                   _\n                   _\n                   (idpath _)\n                   _) ;\n           [ refine (!(!(maponpathscomp _ _ _) @ _)) ;\n             refine (maponpaths\n                       (maponpaths (gquot_functor_map (poly_act_functor (P₁ + P₂) f)))\n                       (gquot_rec_beta_gcleq _ _ _ _ _ _ _ _ _ _) @ _) ;\n             apply gquot_rec_beta_gcleq\n           | refine (!(!(maponpathscomp _ _ _) @ _)) ;\n             refine (maponpaths\n                       (maponpaths gquot_inr_grpd)\n                       (gquot_rec_beta_gcleq _ _ _ _ _ _ _ _ _ _) @ _) ;\n             apply gquot_rec_beta_gcleq\n           | apply vrefl]).\n    - intro.\n      exact (gtrunc _ _ _).\n  Defined.\n\n  Definition sum_gquot_data_nat_inr\n             {X Y : grpd_bicat}\n             (f : X --> Y)\n             (z : ⟦ P₂ ⟧ (gquot_psfunctor X) : one_type)\n    : # (comp_psfunctor gquot_psfunctor ⦃ P₁ + P₂ ⦄) f (gquot_inr_grpd (IHP₂ X z))\n      =\n      sum_gquot_data_comp Y (inr (# (⟦ P₂ ⟧) (gquot_functor_map f) z)).\n  Proof.\n    refine (_ @ maponpaths gquot_inr_grpd (pr1 (psnaturality_of IHP₂ f) z)).\n    exact (gquot_inr_grpd_gquot_functor f (IHP₂ X z)).\n  Defined.\n\n  Definition sum_gquot_data\n    : pstrans_data\n        (comp_psfunctor (⟦ P₁ + P₂ ⟧) gquot_psfunctor)\n        (comp_psfunctor gquot_psfunctor ⦃ P₁ + P₂ ⦄).\n  Proof.\n    use make_pstrans_data.\n    - exact sum_gquot_data_comp.\n    - intros X Y f.\n      use make_invertible_2cell.\n      + intro z.\n        induction z as [z | z].\n        * exact (sum_gquot_data_nat_inl f z).\n        * exact (sum_gquot_data_nat_inr f z).\n      + apply one_type_2cell_iso.\n  Defined.\n  \n  Definition sum_gquot_naturality_help_inl\n             {X Y : grpd_bicat}\n             {f g : grpd_bicat ⟦ X, Y ⟧}\n             (p : f ==> g)\n    : ∏ (z : gquot (⦃ P₁ ⦄ X)),\n      (gquot_inl_grpd_gquot_functor f z)\n        @ maponpaths\n            gquot_inl_grpd\n            (gquot_functor_cell\n               (poly_act_nat_trans P₁ p) z)\n      =\n      (gquot_functor_cell\n        (poly_act_nat_trans (P₁ + P₂) p) (gquot_inl_grpd z))\n      @ gquot_inl_grpd_gquot_functor g z.\n  Proof.\n    use gquot_ind_prop.\n    - intro a.\n      refine (!_).\n      refine (pathscomp0rid _ @ _).\n      refine (!_).\n      exact (gquot_rec_beta_gcleq _ _ _ _ _ _ _ _ _ (pr1 (## ⦃ P₁ ⦄ p) a)).\n    - intro.\n      exact (gtrunc _ _ _ _ _).\n  Qed.\n  \n  Definition sum_gquot_naturality_help_inr\n             {X Y : grpd_bicat}\n             {f g : grpd_bicat ⟦ X, Y ⟧}\n             (p : f ==> g)\n    : ∏ (z : gquot (⦃ P₂ ⦄ X)),\n      (gquot_inr_grpd_gquot_functor f z)\n        @ maponpaths gquot_inr_grpd\n            (gquot_functor_cell\n               (poly_act_nat_trans P₂ p) z)\n      =\n      gquot_functor_cell\n        (poly_act_nat_trans (P₁ + P₂) p) (gquot_inr_grpd z)\n      @ gquot_inr_grpd_gquot_functor g z.\n    Proof.\n    use gquot_ind_prop.\n    - intro a.\n      refine (!_).\n      refine (pathscomp0rid _ @ _).\n      refine (!_).\n      exact (gquot_rec_beta_gcleq _ _ _ _ _ _ _ _ _ (pr1 (## ⦃ P₂ ⦄ p) a)).\n    - intro.\n      exact (gtrunc _ _ _ _ _).\n  Qed.\n\n  Definition sum_gquot_id_help_inl\n             {X : grpd_bicat}\n    : ∏ z,\n      maponpaths\n        gquot_inl_grpd\n        ((pr122 (pr1 (comp_psfunctor gquot_psfunctor ⦃ P₁ ⦄))) X z)\n      =\n      (pr122 (pr1 (comp_psfunctor gquot_psfunctor ⦃ P₁ + P₂ ⦄)))\n        X (gquot_inl_grpd z)\n        @ gquot_inl_grpd_gquot_functor (id₁ X) z.\n  Proof.\n    use gquot_ind_prop.\n    - intro a.\n      refine (!_).\n      refine (pathscomp0rid _ @ _).\n      refine (!_).\n      exact (gquot_rec_beta_gcleq _ _ _ _ _ _ _ _ _ (pr1 (pr122 (pr1 ⦃ P₁⦄) X) a)).\n    - intro.\n      exact (gtrunc _ _ _ _ _).\n  Qed.\n\n  Definition sum_gquot_id_help_inr\n             {X : grpd_bicat}\n    : ∏ z,\n      maponpaths\n        gquot_inr_grpd\n        ((pr122 (pr1 (comp_psfunctor gquot_psfunctor ⦃ P₂ ⦄))) X z)\n      =\n      (pr122 (pr1 (comp_psfunctor gquot_psfunctor ⦃ P₁ + P₂ ⦄)))\n        X (gquot_inr_grpd z)\n        @ gquot_inr_grpd_gquot_functor (id₁ X) z.\n  Proof.\n    use gquot_ind_prop.\n    - intro a.\n      refine (!_).\n      refine (pathscomp0rid _ @ _).\n      refine (!_).\n      exact (gquot_rec_beta_gcleq _ _ _ _ _ _ _ _ _ (pr1 (pr122 (pr1 ⦃ P₂ ⦄) X) a)).\n    - intro.\n      exact (gtrunc _ _ _ _ _).\n  Qed.\n  \n  Definition sum_gquot_pstrans_comp_inl_help\n             {X Y Z : grpd_bicat}\n             (f : X --> Y) (g : Y --> Z)\n             {x y : gquot (⦃ P₁ ⦄ Y)}\n             (p : x = y)             \n    : maponpaths\n        (gquot_functor_map (# ⦃ P₁ + P₂ ⦄ g))\n        (maponpaths gquot_inl_grpd p)\n        @ gquot_inl_grpd_gquot_functor\n            g y\n      =\n      (gquot_inl_grpd_gquot_functor _ _)\n        @ maponpaths\n        gquot_inl_grpd\n        (maponpaths\n           (gquot_functor_map (# ⦃ P₁ ⦄ g))\n           p).\n  Proof.\n    induction p.\n    refine (!_).\n    apply pathscomp0rid.\n  Qed.\n  \n  Definition sum_gquot_pstrans_comp_inl_help_two\n             {X Y Z : grpd_bicat}\n             (f : X --> Y) (g : Y --> Z)\n    : ∏ (z : gquot (⦃ P₁ ⦄ X)),\n      maponpaths\n        (gquot_functor_map (poly_act_functor (P₁ + P₂) g))\n        (gquot_inl_grpd_gquot_functor f z)\n    @ gquot_inl_grpd_gquot_functor\n        g\n        (gquot_functor_map (poly_act_functor P₁ f) z)\n    @ maponpaths\n        gquot_inl_grpd\n        (gquot_functor_composition\n           (poly_act_functor P₁ f)\n           (poly_act_functor P₁ g)\n           z\n    @ gquot_functor_cell\n           (poly_act_functor_composition P₁ f g) \n           z)\n    =\n      (gquot_functor_composition\n         (poly_act_functor (P₁ + P₂) f)\n         (poly_act_functor (P₁ + P₂) g)\n         (gquot_inl_grpd z)\n    @ gquot_functor_cell\n        (poly_act_functor_composition (P₁ + P₂) f g)\n        (gquot_inl_grpd z))\n    @ gquot_inl_grpd_gquot_functor (f ∙ g) z.\n  Proof.\n    use gquot_ind_prop.\n    - intro a.\n      refine (!_).\n      refine (pathscomp0rid _ @ _).\n      refine (!_).\n      exact (gquot_rec_beta_gcleq\n                _ _ _ _ _ _ _ _ _\n                (pr1 ((pr222 (pr1 ⦃ P₁ ⦄)) X Y Z f g) a)).\n    - intro.\n      exact (gtrunc _ _ _ _ _).\n  Qed.\n\n  Definition sum_gquot_pstrans_comp_inr_help\n             {X Y Z : grpd_bicat}\n             (f : X --> Y) (g : Y --> Z)\n             {x y : gquot (⦃ P₂ ⦄ Y)}\n             (p : x = y)             \n    : maponpaths\n        (gquot_functor_map (# ⦃ P₁ + P₂ ⦄ g))\n        (maponpaths gquot_inr_grpd p)\n      @ gquot_inr_grpd_gquot_functor\n          g y\n      =\n      (gquot_inr_grpd_gquot_functor _ _)\n      @ maponpaths\n          gquot_inr_grpd\n          (maponpaths\n             (gquot_functor_map (# ⦃ P₂ ⦄ g))\n             p).\n  Proof.\n    induction p.\n    refine (!_).\n    apply pathscomp0rid.\n  Qed.\n\n  Definition sum_gquot_pstrans_comp_inr_help_two\n             {X Y Z : grpd_bicat}\n             (f : X --> Y) (g : Y --> Z)\n    : ∏ (z : gquot (⦃ P₂ ⦄ X)),\n      maponpaths\n        (gquot_functor_map (poly_act_functor (P₁ + P₂) g))\n        (gquot_inr_grpd_gquot_functor f z)\n    @ gquot_inr_grpd_gquot_functor\n        g\n        (gquot_functor_map (poly_act_functor P₂ f) z)\n    @ maponpaths\n        gquot_inr_grpd\n        (gquot_functor_composition\n           (poly_act_functor P₂ f)\n           (poly_act_functor P₂ g)\n           z\n    @ gquot_functor_cell\n           (poly_act_functor_composition P₂ f g) \n           z)\n    =\n      (gquot_functor_composition\n         (poly_act_functor (P₁ + P₂) f)\n         (poly_act_functor (P₁ + P₂) g)\n         (gquot_inr_grpd z)\n    @ gquot_functor_cell\n        (poly_act_functor_composition (P₁ + P₂) f g)\n        (gquot_inr_grpd z))\n    @ gquot_inr_grpd_gquot_functor (f ∙ g) z.\n  Proof.\n    use gquot_ind_prop.\n    - intro a.\n      refine (!_).\n      refine (pathscomp0rid _ @ _).\n      refine (!_).\n      exact (gquot_rec_beta_gcleq\n                _ _ _ _ _ _ _ _ _\n                (pr1 ((pr222 (pr1 ⦃ P₂ ⦄)) X Y Z f g) a)).\n    - intro.\n      exact (gtrunc _ _ _ _ _).\n  Qed.\n\n  Definition sum_gquot_is_pstrans\n    : is_pstrans sum_gquot_data.\n  Proof.\n    repeat split.\n    - intros X Y f g p.\n      use funextsec.\n      intro z.\n      induction z as [z | z].\n      + refine (!_).\n        etrans.\n        {\n          etrans.\n          {\n            refine (maponpaths (λ z, _ @ z) _).\n            refine (maponpathscomp inl (sum_gquot_data_comp Y) _  @ _).\n            exact (!(maponpathscomp (IHP₁ Y) gquot_inl_grpd _)).\n          }\n          refine (!(path_assoc _ _ _) @ _).\n          refine (maponpaths (λ z, _ @ z) _).\n          refine (!(maponpathscomp0 _ _ _) @ _).\n          refine (maponpaths\n                   (maponpaths gquot_inl_grpd)\n                   (!(eqtohomot (psnaturality_natural IHP₁ X Y f g p) z)) @ _).\n          exact (maponpathscomp0 _ _ _).\n        }\n        refine (path_assoc _ _ _ @ _ @ !(path_assoc _ _ _)).\n        refine (maponpaths (λ z, z @ _) _).\n        exact (sum_gquot_naturality_help_inl p (IHP₁ X z)).\n      + refine (!_).\n        etrans.\n        {\n          etrans.\n          {\n            refine (maponpaths (λ z, _ @ z) _).\n            refine (maponpathscomp inr (sum_gquot_data_comp Y) _  @ _).\n            exact (!(maponpathscomp (IHP₂ Y) gquot_inr_grpd _)).\n          }\n          refine (!(path_assoc _ _ _) @ _).\n          refine (maponpaths (λ z, _ @ z) _).\n          refine (!(maponpathscomp0 _ _ _) @ _).\n          refine (maponpaths\n                    (maponpaths gquot_inr_grpd)\n                    (!(eqtohomot (psnaturality_natural IHP₂ X Y f g p) z)) @ _).\n          exact (maponpathscomp0 _ _ _).\n        }\n        refine (path_assoc _ _ _ @ _ @ !(path_assoc _ _ _)).\n        refine (maponpaths (λ z, z @ _) _).\n        exact (sum_gquot_naturality_help_inr p (IHP₂ X z)).\n    - intros X.\n      use funextsec.\n      intro z.\n      induction z as [z | z].\n      + refine (!_).\n        etrans.\n        {\n          refine (maponpathscomp0 (sum_gquot_data_comp X) _ _ @ _).\n          etrans.\n          {\n            refine (maponpaths (λ z, z @ _) _).\n            refine (maponpathscomp inl (sum_gquot_data_comp X) _  @ _).\n            exact (!(maponpathscomp (IHP₁ X) gquot_inl_grpd _)).\n          }\n          etrans.\n          {\n            refine (maponpaths (λ z, _ @ z) _).\n            refine (maponpathscomp inl (sum_gquot_data_comp X) _  @ _).\n            exact (!(maponpathscomp (IHP₁ X) gquot_inl_grpd _)).\n          }\n          refine (!(maponpathscomp0 gquot_inl_grpd _ _) @ _).\n          refine (maponpaths (maponpaths gquot_inl_grpd) _).\n          refine (!(maponpathscomp0 (IHP₁ X) _ _) @ _).\n          exact (!(eqtohomot (pstrans_id IHP₁ X) z)).\n        }\n        refine (maponpathscomp0 gquot_inl_grpd _ _ @ _).\n        refine (_ @ !(path_assoc _ _ _)).\n        apply maponpaths_2.\n        apply sum_gquot_id_help_inl.\n      + refine (!_).\n        etrans.\n        {\n          refine (maponpathscomp0 (sum_gquot_data_comp X) _ _ @ _).\n          etrans.\n          {\n            refine (maponpaths (λ z, z @ _) _).\n            refine (maponpathscomp inr (sum_gquot_data_comp X) _  @ _).\n            exact (!(maponpathscomp (IHP₂ X) gquot_inr_grpd _)).\n          }\n          etrans.\n          {\n            refine (maponpaths (λ z, _ @ z) _).\n            refine (maponpathscomp inr (sum_gquot_data_comp X) _  @ _).\n            exact (!(maponpathscomp (IHP₂ X) gquot_inr_grpd _)).\n          }\n          refine (!(maponpathscomp0 gquot_inr_grpd _ _) @ _).\n          refine (maponpaths (maponpaths gquot_inr_grpd) _).\n          refine (!(maponpathscomp0 (IHP₂ X) _ _) @ _).\n          exact (!(eqtohomot (pstrans_id IHP₂ X) z)).\n        }\n        refine (maponpathscomp0 gquot_inr_grpd _ _ @ _).\n        refine (_ @ !(path_assoc _ _ _)).\n        apply maponpaths_2.\n        apply sum_gquot_id_help_inr.\n    - intros X Y Z f g.\n      use funextsec.\n      intro z.\n      induction z as [z | z].\n      + refine (!_).\n        etrans.\n        {\n          refine (maponpaths (λ z, z @ _) (_ @ _)).\n          { apply pathscomp0rid. }\n          refine (maponpaths (λ z, z @ _) _).\n          apply pathscomp0rid.\n        }\n        etrans.\n        {\n          refine (maponpaths (λ z, _ @ z) _).\n          refine (maponpathscomp0 (sum_gquot_data_comp Z) _ _ @ _).\n          etrans.\n          {\n            refine (maponpaths (λ z, z @ _) _).\n            refine (maponpathscomp inl (sum_gquot_data_comp Z) _  @ _).\n            exact (!(maponpathscomp (IHP₁ Z) gquot_inl_grpd _)).\n          }\n          etrans.\n          {\n            refine (maponpaths (λ z,\n                                maponpaths\n                                  gquot_inl_grpd\n                                  (maponpaths\n                                     (IHP₁ Z)\n                                     _\n                                  )\n                                  @ z) _).\n            refine (maponpathscomp inl (sum_gquot_data_comp Z) _  @ _).\n            exact (!(maponpathscomp (IHP₁ Z) gquot_inl_grpd _)).\n          }\n          refine (!(maponpathscomp0 gquot_inl_grpd _ _) @ _).\n          refine (maponpaths (maponpaths gquot_inl_grpd) _).\n          exact (!(maponpathscomp0 (IHP₁ Z) _ _)).\n        }\n        etrans.\n        {\n          refine (maponpaths (λ z, (z @ _) @ _) _).\n          exact ((maponpathscomp0 (gquot_functor_map _) _ _)).\n        }\n        do 2 (refine (!(path_assoc _ _ _) @ _)).\n        etrans.\n        {\n          refine (maponpaths (λ z, _ @ z) _).\n          etrans.\n          {\n            refine (maponpaths (λ z, _ @ z) _).\n            refine (!(path_assoc _ _ _) @ _).\n            refine (maponpaths (λ z, _ @ z) _).\n            exact (!(maponpathscomp0 gquot_inl_grpd _ _)).\n          }\n          refine (path_assoc _ _ _ @ _).\n          refine (maponpaths (λ z, z @ _) _).\n          exact (sum_gquot_pstrans_comp_inl_help f g ((pr1 (psnaturality_of IHP₁ f)) z)).\n        }\n        etrans.\n        {\n          refine (maponpaths (λ z, _ @ z) _).\n          refine (!(path_assoc _ _ _) @ _).\n          refine (maponpaths (λ z, _ @ z) _).\n          refine (!(maponpathscomp0 gquot_inl_grpd _ _) @ _).\n          refine (maponpaths (maponpaths gquot_inl_grpd) _).\n          refine (path_assoc _ _ _ @ _).\n          etrans.\n          {\n            refine (maponpaths (λ z, z @ _) _).\n            refine (!(pathscomp0rid _) @ _).\n            refine (maponpaths (λ z, (z @ _) @ _) _).\n            exact (!(pathscomp0rid _)).\n          }\n          exact (!(eqtohomot (pstrans_comp IHP₁ f g) z)).\n        }\n        etrans.\n        {\n          refine (maponpaths (λ z, _ @ (_ @ z)) _).\n          exact (maponpathscomp0 gquot_inl_grpd _ _).\n        }\n        do 2 (refine (path_assoc _ _ _ @ _)).\n        refine (_ @ !(path_assoc _ _ _)).\n        apply maponpaths_2.\n        refine (!(path_assoc _ _ _) @ _).\n        exact (sum_gquot_pstrans_comp_inl_help_two f g (IHP₁ X z)).\n      + refine (!_).\n        etrans.\n        {\n          refine (maponpaths (λ z, z @ _) (_ @ _)).\n          { apply pathscomp0rid. }\n          refine (maponpaths (λ z, z @ _) _).\n          apply pathscomp0rid.\n        }\n        etrans.\n        {\n          refine (maponpaths (λ z, _ @ z) _).\n          refine (maponpathscomp0 (sum_gquot_data_comp Z) _ _ @ _).\n          etrans.\n          {\n            refine (maponpaths (λ z, z @ _) _).\n            refine (maponpathscomp inr (sum_gquot_data_comp Z) _  @ _).\n            exact (!(maponpathscomp (IHP₂ Z) gquot_inr_grpd _)).\n          }\n          etrans.\n          {\n            refine (maponpaths (λ z,\n                                maponpaths\n                                  gquot_inr_grpd\n                                  (maponpaths\n                                     (IHP₂ Z)\n                                     _\n                                  )\n                                  @ z) _).\n            refine (maponpathscomp inr (sum_gquot_data_comp Z) _  @ _).\n            exact (!(maponpathscomp (IHP₂ Z) gquot_inr_grpd _)).\n          }\n          refine (!(maponpathscomp0 gquot_inr_grpd _ _) @ _).\n          refine (maponpaths (maponpaths gquot_inr_grpd) _).\n          exact (!(maponpathscomp0 (IHP₂ Z) _ _)).\n        }\n        etrans.\n        {\n          refine (maponpaths (λ z, (z @ _) @ _) _).\n          exact ((maponpathscomp0 (gquot_functor_map _) _ _)).\n        }\n        do 2 (refine (!(path_assoc _ _ _) @ _)).\n        etrans.\n        {\n          refine (maponpaths (λ z, _ @ z) _).\n          etrans.\n          {\n            refine (maponpaths (λ z, _ @ z) _).\n            refine (!(path_assoc _ _ _) @ _).\n            refine (maponpaths (λ z, _ @ z) _).\n            exact (!(maponpathscomp0 gquot_inr_grpd _ _)).\n          }\n          refine (path_assoc _ _ _ @ _).\n          refine (maponpaths (λ z, z @ _) _).\n          exact (sum_gquot_pstrans_comp_inr_help f g ((pr1 (psnaturality_of IHP₂ f)) z)).\n        }\n        etrans.\n        {\n          refine (maponpaths (λ z, _ @ z) _).\n          refine (!(path_assoc _ _ _) @ _).\n          refine (maponpaths (λ z, _ @ z) _).\n          refine (!(maponpathscomp0 gquot_inr_grpd _ _) @ _).\n          refine (maponpaths (maponpaths gquot_inr_grpd) _).\n          refine (path_assoc _ _ _ @ _).\n          etrans.\n          {\n            refine (maponpaths (λ z, z @ _) _).\n            refine (!(pathscomp0rid _) @ _).\n            refine (maponpaths (λ z, (z @ _) @ _) _).\n            exact (!(pathscomp0rid _)).\n          }\n          exact (!(eqtohomot (pstrans_comp IHP₂ f g) z)).\n        }\n        etrans.\n        {\n          refine (maponpaths (λ z, _ @ (_ @ z)) _).\n          exact (maponpathscomp0 gquot_inr_grpd _ _).\n        }\n        do 2 (refine (path_assoc _ _ _ @ _)).\n        refine (_ @ !(path_assoc _ _ _)).\n        apply maponpaths_2.\n        refine (!(path_assoc _ _ _) @ _).\n        exact (sum_gquot_pstrans_comp_inr_help_two f g (IHP₂ X z)).\n  Qed.\n\n  Definition sum_gquot\n    : pstrans\n        (comp_psfunctor (⟦ P₁ + P₂ ⟧) gquot_psfunctor)\n        (comp_psfunctor gquot_psfunctor ⦃ P₁ + P₂ ⦄).\n  Proof.\n    use make_pstrans.\n    - exact sum_gquot_data.\n    - exact sum_gquot_is_pstrans.\n  Defined.\nEnd GQuotSum.\n", "meta": {"author": "UniMath", "repo": "GrpdHITs", "sha": "cb5a9af84400eb770392632eb74860d4ebad9306", "save_path": "github-repos/coq/UniMath-GrpdHITs", "path": "github-repos/coq/UniMath-GrpdHITs/GrpdHITs-cb5a9af84400eb770392632eb74860d4ebad9306/code/hit_biadjunction/gquot_commute/gquot_commute_sum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.2526520462059837}}
{"text": "(* Copyright (c) 2008, Harvard University\n * All rights reserved.\n *\n * Author: Ryan Wisnesky\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\nModule Type NONDEP_ASSOCIATION.\n  (* This is weaker than the real ynot finite map because the\n     type of a value does not depend on its key.\n     However, it corresponds to Jahob when V := ptr. *) \n  Variables K V : Set.\n  Variable  eqK : forall (k1 k2: K), {k1 = k2} + {k1 <> k2}.\nEnd NONDEP_ASSOCIATION.\n\nModule NondepAssocListModel(A : NONDEP_ASSOCIATION).\n Export A.\n Require Export List.\n Set Implicit Arguments.\n\n (* This model is slightly different from Jahob's model\n    using sets.  We expose lists, but with the with unique \n    keys invariant, these operations can implement\n    the same list mutations that Jahob gets using set deletion \n    and union. *)  \n\n Fixpoint delete (l: list (prod K V)) (k: K) :=  \n   match l with  \n     | nil => nil\n     | (k', v')::b => if eqK k k'  then delete b k  else (k',v') :: (delete b k)  \n   end.\n\n Fixpoint lookup l (k: K) : option V         :=  \n   match l with  \n     | nil => None\n     | (k', v)::b   => if eqK k k'  then Some v      else lookup b k               \n   end.\n\n Definition head (ls : list (prod K V)) := \n   match ls with \n     | nil => None \n     | x :: _ => Some x \n   end.\n\n Definition tail (ls : list (prod K V)) := \n   match ls with \n     | nil => nil  \n     | _ :: ls' => ls'  \n   end.\n\nEnd NondepAssocListModel.\n\n(* This is the interface for the Jahob AssocList example,\n   as expressed in Y0. *)\nModule Type JAHOB_ASSOC_LIST.\n Require Export List.\n Declare Module A  : NONDEP_ASSOCIATION.\n Module AL := NondepAssocListModel(A).\n Import AL.\n\n Require Export Ynot.\n Open Scope hprop_scope.\n\n Parameter t   : Set.\n Parameter rep : t -> list (prod K V) -> hprop.\n\n Parameter new : STsep __ (fun r => rep r nil).\n Parameter free: forall (p: t),\n   STsep (rep p nil) (fun _: unit => __).\n\n Parameter add: forall k v (p: t) (m: [list (prod K V)]),\n   STsep (m ~~ rep p m * [lookup m k = None])\n         (fun _:unit => m ~~ rep p ((k,v)::m)).\n\n Parameter put: forall k v (p: t) (m: [list (prod K V)]), \n   STsep (m ~~ rep p m)\n         (fun r => m ~~ [lookup m k = r] * rep p ((k,v)::(delete m k))).\n\n Parameter get: forall k   (p: t) (m: [list (prod K V)]),\n   STsep (m ~~ rep p m)\n         (fun r:option V => m ~~ rep p m * [lookup m k = r] ).\n\n Parameter isEmpty: forall (p: t) (m: [list (prod K V)]),\n   STsep (m ~~ rep p m) (fun r:bool => m ~~ rep p m * if r then [m = nil] else [m <> nil]).\n\n Parameter remove : forall k (p: t) (m: [list (prod K V)]),\n                     STsep (m ~~ rep p m * Exists v :@ V, [lookup m k = Some v]) \n                (fun r:V => m ~~ rep p (delete m k) *     [lookup m k = Some r]).\n\n Parameter replace: forall k v (p: t) (m: [list (prod K V)]),\n  STsep (m ~~             rep p m * Exists v0 :@ V,     [lookup m k = Some v0] )\n        (fun r:V => m ~~  rep p ((k,v)::(delete m k)) * [lookup m k = Some r ] ).\n\n(* technically want rep -> uniq lemma *)\n\n(* drop contains key *)\n\nEnd JAHOB_ASSOC_LIST.\n\n(* This uses the same algorithms as Jahob *)\nModule JahobAssocList(A : NONDEP_ASSOCIATION) : JAHOB_ASSOC_LIST with Module A := A.\n Module A := A.\n Module AL := NondepAssocListModel(A).\n Require Import Ynot.\n Import AL.\n\n Open Scope hprop_scope.\n\n(* Representation ***********************************************)\n\n  Definition t : Set := ptr.\n \n  Record Node : Set := node {\n    key  : K;\n    value: V;\n    next : option ptr\n  }.\n\n  Fixpoint rep' (op: option ptr) m {struct m} :=\n    match op with\n      | None => [m = nil] \n      | Some h => match m with\n                    | (k,v) :: b =>  Exists nxt :@ option ptr,\n                          h --> node k v nxt * rep' nxt b * [lookup b k = None]\n                    | nil => [False]\n                   end\n    end.\n\n  Definition rep p m : hprop :=\n    Exists n :@ option ptr, p --> n * rep' n m.\n\n(* Reasoning **************************************************)\n\nLtac simplr := repeat (try discriminate;\n  match goal with\n    | [ H : head ?x = Some _ |- _ ] =>\n      destruct x; simpl in *; [\n        discriminate\n        | injection H; clear H; intros; subst\n      ]\n    | [ |- match ?v with\n             | Some _ => _\n             | None   => _\n           end ==> _] => destruct v\n    | [ |- _ ==> match ?v with\n             | Some _ => _\n                   | None   => _\n                 end ] =>\n      match type of v with\n        | option ?T => equate v (@None T)\n      end\n    | [ H : _ :: _ = _ :: _ |- _ ] => injection H; clear H; intros; subst\n    | [ H : next _ = _ |- _ ] => rewrite -> H\n    | [ H : Some _ = Some _ |- _ ] => inversion H; clear H\n    | [  H : ?a = ?b -> False , HH : (if (eqK ?a ?b) then Some _ else None) = Some _  |- _ ] => \n            destruct (eqK a b) ; [ contradiction | discriminate ] \n    | [  HH : (if (eqK ?a ?b) then Some _ else _) = None  |- _ ] => \n            destruct (eqK a b) ; [ discriminate | idtac ]\n    | [  H : ?a = ?b -> False , HH : (if (eqK ?a ?b) then Some _ else Some ?v1) =\n             Some ?v  |- context[Some ?v1 = Some ?v] ] => \n           destruct (eqK a b) ; [ try congruence | try contradiction ] \n    | [ _ : ?a = ?b -> False ,  HH : (if (eqK ?a ?b) then _ else ?c) = ?d  |- _ ] => \n           destruct (eqK a b) ; [ contradiction | idtac ]\n    | [ |- context[ if eqK ?a ?a then _ else _ ] ] => destruct (eqK a a) \n    | [ H : ?a = ?b -> False |- context[ if eqK ?a ?b then _ else _ ] ] =>\n             destruct (eqK a b); [ contradiction | idtac ] \n    | [  H : next ?nn = ?a |- ?n = node (key ?nn) (value ?nn) ?a ] =>\n              rewrite <- H; destruct n; reflexivity\n    | [ _ : (if eqK ?a ?b then Some _ else None) = Some _ |- _ ] => \n           destruct (eqK a b); [ idtac | discriminate ] \n    | [ _ : (if eqK ?a ?a then _ else _) = _ |- _ ] => destruct (eqK a a); [ idtac | intuition ] \n  end).\n\nLtac t := unfold rep; unfold rep'; sep fail simplr.\nLtac f := fold rep'; fold rep.\n\nLemma eta_node : forall fn, fn = node (key fn) (value fn) (next fn).\n  destruct fn; reflexivity.\nQed.\n\nHint Resolve eta_node.\n\nLemma ll_concat : forall nde a b c hd, Some (key nde, value nde) = head a ->\n  rep' (next nde) (tail a ++ b :: c) * hd --> nde *\n   [lookup (tail a ++ b :: c) (key nde) = None] ==> rep' (Some hd) (a ++ b :: c)  .\n  induction a; t.\nQed.\n\nHint Resolve ll_concat.\nLemma cons_nil : forall l2 x0 x, rep' l2 x0 * rep' None x ==> rep' l2 (x ++ x0).\n  destruct x; t.\nQed.\nLemma node_next : forall nde p,  next nde = p -> nde = node (key nde) (value nde) p.\n  destruct nde; simpl; congruence.\nQed.\n\nHint Resolve cons_nil.\nHint Resolve node_next.\n\nLemma lkup: forall m k x, \n lookup m x = None -> lookup (delete m k) x = None. \nintros. induction m. t. trivial. simpl in *. destruct a. t.\n destruct (eqK x k0). t. destruct (eqK k k0). t. t. Qed.\n\n(* Hint Resolve lkup. *)\n\nTheorem rep'_None : forall ls,\n  rep' None ls ==> [ls = nil].\n  destruct ls; sep fail idtac.\nQed.\n\nTheorem rep'_Some : forall ls hd,\n  rep' (Some hd) ls ==> Exists k :@ K, Exists v :@ V, \n    Exists t :@ list (prod K V), Exists p :@ option ptr,\n  [ls = (k,v) :: t] * hd --> node k v p * [lookup t k = None] * rep' p t.\n  destruct ls; sep fail ltac:(try discriminate).\nQed.\n\nLemma node_eta : forall fn k v x,\n  [fn = node k v x] ==> [key fn = k] * [value fn = v] * [next fn = x].\n  destruct fn; sep fail ltac:(try congruence).\nQed.\n\nLemma cons_eta : forall x h t,\n  [x = h :: t] ==> [head x = Some h] * [tail x = t].\n  destruct x; sep fail ltac:(try congruence).\nQed.\n\nLemma rep'_eq : forall m x v0 v1 x0 fn,\n  m = [x]%inhabited\n  -> (m ~~~ tail m) = [x0]%inhabited\n  -> tail x = v0\n  -> next fn = v1\n  -> rep' v1 v0 ==> rep' (next fn) x0.\n  t.\nQed.\n\nHint Resolve rep'_eq.\n\nTheorem rep_rep' : forall m p, rep p m ==>\n  Exists n :@ option ptr, p --> n * rep' n m. t. Qed.\n\nHint Resolve rep_rep'.\n\nLemma repl : forall m p k, (rep p m * Exists v :@ V, [lookup m k = Some v]) ==>\n Exists x :@ option ptr, p --> x * (Exists cur :@ ptr, [x = Some cur] * rep' (Some cur) m * Exists v :@ V, [lookup m k = Some v]).\nProof.\n  induction m. intros. sep fail auto. instantiate (1 := v). instantiate (1 := p). inversion H0.\n  intros. destruct a. unfold rep; case_eq (eqK k k0); intros; subst; inhabiter.\n  unfold lookup. rewrite H. simpl. destruct v0. sep fail auto. sep fail auto.\n  instantiate (1 := None). instantiate (1:= p). inversion H3.\n  simpl. rewrite H in *. destruct v0. inhabiter. sep fail auto. instantiate (1 := v1).\n  sep fail auto.\n  intro_pure. inversion H3.\nQed.\n\nHint Resolve repl.\n\nLtac simp_prem :=\n  simpl_IfNull;\n  repeat simpl_prem ltac:(apply rep'_None || apply rep'_Some || apply repl ||\n                          apply node_eta || apply cons_eta || apply rep_rep');\n    unpack_conc.\n\nLtac destr := match goal with [ x : list (prod K V) |- context[rep' None ?x] ] => destruct x; try t end.\n\nLtac t'' := unfold rep; fold rep'; sep simp_prem simplr.\n\nLtac t' := match goal with\n             | [ |- _ ==> ?P ] =>\n               match P with\n                 | context[rep' (next _) _] =>\n                   inhabiter; simp_prem;\n                   intro_pure; simpl_prem ltac:(solve [ eauto ]); unintro_pure; canceler; t''\n               end\n             | _ => t''\n           end.\n\nTheorem lkup0 : forall ls k,\n  lookup ls k = None -> ls = delete ls k.\n intros. induction ls. t. t. destruct a. destruct (eqK k k0). t. pose (IHls H). rewrite <- e. trivial. Qed.\n\nLemma lkpdel : forall m k, lookup (delete m k) k = None.\n intros. induction m. trivial. simpl. destruct a. destruct (eqK k k0). assumption. simpl. \n destruct (eqK k k0). contradiction. assumption. Qed.\n\nLtac tx := match goal with | [ H : lookup ?ls ?n = None |- rep' ?x ?ls ==> rep' ?x (delete ?ls ?n) ] =>  rewrite <- (lkup0 ls n H) ; t end. \n\n(* Implementation ***************************************************)\n\n  Open Scope stsepi_scope.\n\n  Definition new : STsep __ (fun r => rep r nil).\n    refine {{ New (@None ptr) }}; t. Qed.\n\n  Definition free  p: STsep (rep p nil) (fun _:unit => __).\n  intros; refine {{ Free p }}; t. Qed.\n\n  Definition add: forall k v (p: t) (m: [list (prod K V)]),\n   STsep (m ~~ rep p m * [lookup m k = None])\n         (fun _:unit => m ~~ rep p ((k,v)::m)).\n   intros. refine ( op <- ! p ;\n                    n  <- New (node k v op) ;\n                    {{ p ::= (Some n) }} ); t. Qed.\n\n (* Get           **********)\n\n Definition get' : forall (k: K) (hd: option ptr) (m: [list (prod K V)]), \n    STsep (m ~~ rep' hd m) (fun r => m ~~ [lookup m k = r] * rep' hd m).\n  intro k.\n  refine (Fix2\n    (fun hd m => m ~~ rep' hd m)\n    (fun hd m r => m ~~ [lookup m k = r] * rep' hd m)\n    (fun self hd m =>  \n      IfNull hd\n      Then  {{ Return None }}\n      Else  fn <- ! hd ;\n            if eqK k (key fn) \n            then {{ Return (Some (value fn)) }} \n            else {{ self (next fn) (m ~~~ tail m)  <@> _  }})); pose lkup.\n  (** TODO **)\n  t'. t'. t'. t'. t'. t'. t'.\n  Admitted.\n\n  Definition get (k: K) (p: ptr) (m: [list (prod K V)]) :\n    STsep (m ~~ rep p m)\n          (fun r:option V => m ~~ rep p m * [lookup m k = r] ).\n  intros; refine (hd <- !p;\n                  {{ get' k hd m  <@> (p --> hd) }}); t. Qed.\n\n (* isEmpty         ********)\n\n Definition isEmpty: forall (p: t) (m: [list (prod K V)]),\n   STsep (m ~~ rep p m) (fun r:bool => m ~~ rep p m * if r then [m = nil] else [m <> nil]).\n   intros; refine ( ohd <- (p !! (fun ohd => m ~~ rep' ohd m))%stsep  ;\n                    IfNull ohd \n                    Then  {{ Return true  }}\n                    Else  {{ Return false }} ); t'. \n Qed.\n\n (* Remove         *********)\n\nDefinition remove_pre' k ls prev pn cur n := \n Exists t :@ list (K*V), prev --> pn * rep' (next n) t * \n(Exists v :@ V, [lookup ((key n, value n)::t) k = Some v] * [key n <> key pn] * \n   [ls = (key pn, value pn)::(key n, value n)::t] * [key pn <> k] *\n   [next pn = Some cur] * [lookup ((key n, value n)::t) (key pn) = None] *\n   [lookup t (key n) = None]).\n\nDefinition remove_pre k ls prev pn cur := (ls ~~ Exists n :@ Node, cur --> n * remove_pre' k ls prev pn cur n).\n\nDefinition remove_post k ls prev (pn:Node) (_:ptr) :=\n(fun r:V => ls ~~ Exists pk :@ K, Exists pv :@ V, Exists x :@ list (prod K V), \n          [ls = (pk,pv) :: x] * rep' (Some prev) ((pk,pv)::(delete x k)) * [lookup x k = Some r]).\n\nDefinition remove_frame ls pn n k prev cur := Exists t :@ list (prod K V), [lookup t (key pn) = None] * \n  [ls = (key pn, value pn) :: (key n, value n) :: t]  * [k <> key n] * \n  [key pn <> key n] * prev --> node (key pn) (value pn) (Some cur).\n\nDefinition remove'' : forall k ls prev pn cur, STsep (remove_pre k ls prev pn cur) (remove_post k ls prev pn cur).             \nintro k. refine (Fix4 (remove_pre k) (remove_post k)  \n (fun self ls prev pn cur =>        \n  n <- (cur !! (fun n => ls ~~ remove_pre' k ls prev pn cur n))%stsep;\n  if eqK k (key n)  \n  then Free cur ;;\n        prev ::= node (key pn) (value pn) (next n) ;;  \n        {{ Return (value n) }}\n  else IfNull (next n) As nt \n       Then  {{ !!! }} \n       Else {{ self (ls ~~~ tail ls) cur n nt <@> (ls ~~ remove_frame ls pn n k prev cur)  }})); \nunfold remove_pre; unfold remove_pre'; unfold remove_post; unfold remove_frame; pose lkup; pose lkup.\nt. instantiate (1:=v1). t. t. t. t. t. t. t. t. fold rep'. erewrite <- lkup0; eauto.\nt.\n(** TODO **)\nAdmitted.\n\n\n Definition remove : forall k (p: t) (m: [list (prod K V)]),\n                     STsep (m ~~ rep p m * Exists v :@ V, [lookup m k = Some v]) \n                (fun r:V => m ~~ rep p (delete m k) *     [lookup m k = Some r]).\n intros. refine ( \n  hdptr <- ! p ;\n  IfNull hdptr \n  Then {{ !!! }} \n  Else hd <- (hdptr !! (fun hd => m ~~ Exists tl :@ list (prod K V), p --> Some hdptr * Exists v :@ V, [lookup m k = Some v] *\n                                       [m = (key hd, value hd)::tl] * rep' (next hd) tl * [lookup tl (key hd) = None]))%stsep   ;\n          if eqK k (key hd)\n          then Free hdptr ;;\n               p ::= next hd ;; \n               {{ Return (value hd) }}\n          else IfNull (next hd) As nt \n               Then {{ !!! }}\n               Else {{ remove'' k m hdptr hd nt <@> (m ~~ p --> Some hdptr * [head m = Some (key hd, value hd)] ) }}\n  ); unfold remove_pre; unfold remove_pre'; unfold remove_post; pose lkup; pose lkup0; pose lkpdel.\n(** TODO **)\nAdmitted.\n(*\nt. instantiate (1:=v0). t. t. instantiate (1:= v1). t. t'. t. t'. instantiate (1:=v0). t. t. instantiate (1:= v1). t.\nt. t. t. t. t. t'. tx. sep fail auto. t'. t. t'. instantiate (1:=v0). t. t. Qed.\n*)\n\n (* Replace        **********)\n\n Definition replace: forall k v (p: t) (m: [list (prod K V)]),\n  STsep (m ~~             rep p m * Exists v0 :@ V,    [lookup m k = Some v0] )\n        (fun r:V => m ~~  rep p ((k,v)::(delete m k)) * [lookup m k = Some r ]).\n intros. refine ( x <- remove k p m ;\n                  add k v p (m ~~~ delete m k)  <@> (m ~~ [lookup m k = Some x]) ;;\n                  {{ Return x }} ); pose lkup; pose lkup0; pose lkpdel. \n sep fail auto. instantiate (1:=v0). t. t. t. t. t. t. Qed.\n\n (* Put           *********)\n\nDefinition put k v (p: t) (m: [list (prod K V)]):\n   STsep (m ~~ rep p m)\n         (fun r => m ~~ [lookup m k = r] * rep p ((k,v)::(delete m k))).\nintros.\nrefine ( x <- get k p m ;\n          (match x as x0 return STsep (m ~~ rep p m * [x =lookup m k] * [x = x0])\n                                    (fun _:unit => m ~~ rep p (delete m k) * [x = lookup m k])  with\n             | Some xx =>  z <- remove k p m <@> (m ~~ [Some xx =lookup m k] * [x = Some xx]) ;\n                             {{ Return  tt  }}\n            | None => {{  Return tt }} \n          end)  ;;\n          add k v p (m ~~~ delete m k) <@> (m ~~ [x = lookup m k]) ;;\n         {{ Return x }}\n         ); pose lkup; pose lkpdel; pose lkup0; try solve [ t | t' | sep fail auto; symmetry in H; t'; tx ].\n sep fail auto. f. instantiate (1:=xx). t. t'. tx. Qed.\n\nEnd JahobAssocList.\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/Data/JahobAssocList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.25263797876724914}}
{"text": "Require Import Coq.Bool.Bool.\nRequire Import ExtLib.Core.RelDec.\nRequire Import ExtLib.Structures.Applicative.\nRequire Import ExtLib.Tactics.Consider.\nRequire Import ExtLib.Tactics.\n\nRequire Import MirrorCore.TypesI.\nRequire Import MirrorCore.Lambda.Expr.\nRequire Import MirrorCore.Lambda.ExprVariables.\nRequire Import MirrorCore.Lambda.ExprTac.\nRequire Import MirrorCore.Lambda.Ptrns.\nRequire Import MirrorCore.SymI.\nRequire Import MirrorCore.Views.FuncView.\nRequire Import MirrorCore.Views.Ptrns.\nRequire Import MirrorCore.Reify.ReifyClass.\n\nSet Implicit Arguments.\nSet Strict Implicit.\nSet Maximal Implicit Insertion.\n\nInductive ap_func (typ : Set) : Set :=\n| pPure (_ : typ)\n| pAp (_ _ : typ).\n\nArguments ap_func _ : clear implicits.\n\nSection ApplicativeFuncInst.\n  Context {typ func : Set} {RType_typ : RType typ}.\n  Context {Heq : RelDec (@eq typ)} {HC : RelDec_Correct Heq}.\n  Context {T : Type -> Type} {Applicative_T : Applicative T}.\n\n  Context {Typ2_tyArr : Typ2 _ RFun}.\n  Context {Typ1_T : Typ1 _ T}.\n\n  Let tyArr : typ -> typ -> typ := @typ2 _ _ _ _.\n  Let tyT : typ -> typ := @typ1 _ _ _ _.\n\n  Definition typeof_ap_func (f : ap_func typ) : option typ :=\n    match f with\n    | pPure t => Some (tyArr t (tyT t))\n    | pAp t u => Some (tyArr (tyT (tyArr t u)) (tyArr (tyT t) (tyT u)))\n    end.\n\n  Global Instance RelDec_ap_func : RelDec (@eq (ap_func typ)) :=\n  { rel_dec := fun a b =>\n\t         match a, b with\n\t  \t       | pPure t, pPure t' => t ?[eq] t'\n\t  \t       | pAp t u, pAp t' u' => t ?[eq] t' && u ?[eq] u'\n\t  \t       | _, _ => false\n\t         end\n  }.\n\n  Global Instance RelDec_Correct_ap_func : RelDec_Correct RelDec_ap_func.\n  Proof.\n    constructor.\n    destruct x; destruct y; simpl; try rewrite andb_true_iff;\n    repeat rewrite rel_dec_correct; try intuition congruence.\n  Qed.\n\n  Definition pureR t : typD (tyArr t (tyT t)) :=\n    castR id (RFun (typD t) (T (typD t))) (@pure T Applicative_T (typD t)).\n\n  Definition apR t u : typD (tyArr (tyT (tyArr t u)) (tyArr (tyT t) (tyT u))) :=\n    castR id (RFun (T (RFun (typD t) (typD u))) (RFun (T (typD t)) (T (typD u))))\n          (@ap T Applicative_T (typD t) (typD u)).\n\n  Definition ap_func_symD f : match typeof_ap_func f return Type with\n\t                      | Some t => typD t\n\t                      | None => unit\n\t                      end :=\n    match f as f return match typeof_ap_func f return Type with\n\t\t\t| Some t => typD t\n\t\t\t| None => unit\n\t\t\tend with\n    | pPure t => pureR t\n    | pAp t u => apR t u\n    end.\n\n    Global Instance RSym_ApFunc : SymI.RSym (ap_func typ) := {\n      typeof_sym := typeof_ap_func;\n      symD := ap_func_symD;\n      sym_eqb := (fun a b => Some (rel_dec a b))\n    }.\n\n  Global Instance RSymOk_lopen_func : SymI.RSymOk RSym_ApFunc.\n  Proof.\n    constructor.\n    intros. unfold sym_eqb; simpl.\n    consider (a ?[ eq ] b); auto.\n  Qed.\n\nEnd ApplicativeFuncInst.\n\nSection MakeApplicative.\n  Context {typ func : Set} {RType_typ : RType typ}.\n  Context {FV : PartialView func (ap_func typ)}.\n  Context {Typ2_tyArr : Typ2 _ RFun}.\n\n  Let tyArr : typ -> typ -> typ := @typ2 _ _ _ _.\n\n  Definition fPure t := f_insert (pPure t).\n  Definition fAp t u := f_insert (pAp t u).\n\n  Definition mkPure (t : typ) (f : expr typ func) : expr typ func := App (Inj (fPure t)) f.\n  Definition mkAp (t u : typ) (f a : expr typ func) := App (App (Inj (fAp t u)) f) a.\n\n  Fixpoint mkAps f es t :=\n    match es with\n    | nil => mkPure t f\n    | (e, t')::es => mkAp t' t (mkAps f es (tyArr t' t)) e\n    end.\n\n  Definition fptrnPure {T : Type} (p : Ptrns.ptrn typ T) : ptrn (ap_func typ) T :=\n    fun f U good bad =>\n      match f with\n      | pPure t => p t U good (fun _ => bad (pPure t))\n      | pAp t u => bad (pAp t u)\n      end.\n\n  Definition fptrnAp {T : Type} (p : Ptrns.ptrn (typ * typ) T) : ptrn (ap_func typ) T :=\n    fun f U good bad =>\n      match f with\n      | pPure t => bad (pPure t)\n      | pAp t u => p (t, u) U good (fun _ => bad (pAp t u))\n      end.\n\n  Global Instance fptrnPure_ok {T : Type} {p : ptrn typ T} {Hok : ptrn_ok p} :\n    ptrn_ok (fptrnPure p).\n  Proof.\n    red; intros.\n    destruct x; simpl; [destruct (Hok t) |].\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    { right; unfold Fails; reflexivity. }\n  Qed.\n\n  Global Instance fptrnAp_ok {T : Type} {p : ptrn (typ * typ) T} {Hok : ptrn_ok p} :\n    ptrn_ok (fptrnAp p).\n  Proof.\n    red; intros.\n    destruct x; simpl; [|destruct (Hok (t, t0))].\n    { right; unfold Fails; reflexivity. }\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  Lemma Succeeds_fptrnPure {T : Type} (f : ap_func typ) (p : ptrn typ T) (res : T)\n        {pok : ptrn_ok p} (H : Succeeds f (fptrnPure p) res) :\n    exists t, Succeeds t p res /\\ f = pPure t.\n  Proof.\n    unfold Succeeds, fptrnPure in H.\n    unfold ptrn_ok in pok.\n    specialize (H (option T) Some (fun _ => None)).\n    destruct f; try congruence.\n    specialize (pok t).\n    destruct pok; [|rewrite H0 in H; congruence].\n    destruct H0.\n    rewrite H0 in H; inv_all; subst.\n    exists t; split; [assumption | reflexivity].\n  Qed.\n\n  Lemma Succeeds_fptrnAp {T : Type} (f : ap_func typ) (p : ptrn (typ * typ) T) (res : T)\n        {pok : ptrn_ok p} (H : Succeeds f (fptrnAp p) res) :\n    exists t u, Succeeds (t, u) p res /\\ f = pAp t u.\n  Proof.\n    unfold Succeeds, fptrnAp in H.\n    unfold ptrn_ok in pok.\n    specialize (H (option T) Some (fun _ => None)).\n    destruct f; try congruence.\n    specialize (pok (t, t0)).\n    destruct pok; [|rewrite H0 in H; congruence].\n    destruct H0.\n    rewrite H0 in H; inv_all; subst.\n    exists t, t0; split; [assumption | reflexivity].\n  Qed.\n\n  Global Instance fptrnPure_SucceedsE {T : Type} {f : ap_func typ}\n         {p : ptrn typ T} {res : T} {pok : ptrn_ok p} :\n    SucceedsE f (fptrnPure p) res := {\n      s_result := exists t, Succeeds t p res /\\ f = pPure t;\n      s_elim := @Succeeds_fptrnPure T f p res pok\n    }.\n\n  Global Instance fptrnAp_SucceedsE {T : Type} {f : ap_func typ}\n         {p : ptrn (typ * typ) T} {res : T} {pok : ptrn_ok p} :\n    SucceedsE f (fptrnAp p) res :=\n  { s_result := exists t u, Succeeds (t, u) p res /\\ f = pAp t u\n  ; s_elim := @Succeeds_fptrnAp T f p res pok\n  }.\n\n  Definition applicative_ptrn_cases {T : Type}\n             (do_pure : typ  -> expr typ func -> T)\n             (do_ap : typ -> typ -> expr typ func -> expr typ func -> T) :=\n    por (appr (inj (ptrn_view _ (fptrnPure (pmap do_pure Ptrns.get)))) Ptrns.get)\n        (appr (appr (inj (ptrn_view _ (fptrnAp (pmap (fun x a b => do_ap (fst x) (snd x) a b)\n                                                     Ptrns.get))))\n                    Ptrns.get)\n              Ptrns.get).\n\nDefinition applicative_cases {T : Type}\n           (do_pure : typ  -> expr typ func -> T)\n           (do_ap : typ -> typ -> expr typ func -> expr typ func -> T)\n  : Ptrns.ptrn (expr typ func) T :=\n  applicative_ptrn_cases do_pure do_ap.\n\nEnd MakeApplicative.\n\nSection PtrnApplicative.\n  Context {typ func : Set} {RType_typ : RType typ}.\n  Context {FV : PartialView func (ap_func typ)}.\n\n(* Putting this in the previous sectioun caused universe inconsistencies\n  when calling '@mkAp typ func' in JavaFunc (with typ and func instantiated) *)\n\n  Definition ptrnPure {T A : Type}\n             (p : ptrn typ T)  (a : ptrn (expr typ func) A)\n  : ptrn (expr typ func) (T * A):=\n    app (inj (ptrn_view _ (fptrnPure p))) a.\n\n  Definition ptrnAp {A B T : Type}\n             (p : ptrn (typ * typ) T)\n             (a : ptrn (expr typ func) A)\n             (b : ptrn (expr typ func) B) : ptrn (expr typ func) (T * A * B) :=\n    app (app (inj (ptrn_view _ (fptrnAp p))) a) b.\n\nEnd PtrnApplicative.\n\nSection ReifyApplicative.\n  Context {typ func : Set} {FV : PartialView func (ap_func typ)}.\n  Context {T : Type -> Type} {IH : Applicative T}.\n  Context {t : Reify typ}.\n\n  Definition reify_pure : Command (expr typ func) :=\n    CPattern (ls := (typ:Type)::nil)\n             (RApp (RApp (RExact (@pure T)) RIgnore) (RGet 0 RIgnore))\n             (fun (x : function (CCall (reify_scheme typ))) => Inj (fPure x)).\n\n  Definition reify_ap : Command (expr typ func) :=\n    CPattern (ls := (typ:Type)::(typ:Type)::nil)\n             (RApp (RApp (RApp (RExact (@pure T)) RIgnore) (RGet 0 RIgnore)) (RGet 1 RIgnore))\n             (fun (x y : function (CCall (reify_scheme typ))) => Inj (fAp x y)).\n\n  Definition reify_applicative : Command (expr typ func) :=\n    CFirst (reify_pure :: reify_ap :: nil).\n\nEnd ReifyApplicative.\n\nArguments reify_applicative _ _ {_} _ {_}.", "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/ApplicativeView.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.25263797217432904}}
{"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     AvgSalary.\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 AvgSalaryProtocolSecure <: AutomatedSafeProtocolSS.\n\n  Import AvgSalaryProtocol.\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  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      (* (fun st => safety st /\\ alignment st /\\ returns_align st). *)\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 *; rwuf; simpl in H0.\n\n    time (\n        repeat transition_system_step\n      ).\n\n    Unshelve.\n    all: exact 0 || contradiction || 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 AvgSalaryProtocolSecure.\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/AvgSalarySecure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.36296919862864757, "lm_q1q2_score": 0.2526114355163281}}
{"text": "Require Import AutoSep.\nRequire Import List.\n\nSet Implicit Arguments.\n\n\n(** The king of the abstract predicates *)\n\nModule Type SINGLY_LINKED_LIST.\n  Parameter sll : list W -> W -> HProp.\n\n  Axiom sll_extensional : forall ls p, HProp_extensional (sll ls p).\n\n  Axiom nil_fwd : forall ls (p : W), p = 0\n    -> sll ls p ===> [| ls = nil |].\n\n  Axiom nil_bwd : forall ls (p : W), p = 0\n    -> [| ls = nil |] ===> sll ls p.\n\n  Axiom cons_fwd : forall ls (p : W), p <> 0\n    -> sll ls p ===> Ex x, Ex ls', [| ls = x :: ls' |] * Ex p', (p ==*> x, p') * sll ls' p'.\n\n  Axiom cons_bwd : forall ls (p : W), p <> 0\n    -> (Ex x, Ex ls', [| ls = x :: ls' |] * Ex p', (p ==*> x, p') * sll ls' p') ===> sll ls p.\nEnd SINGLY_LINKED_LIST.\n\nModule SinglyLinkedList : SINGLY_LINKED_LIST.\n  Open Scope Sep_scope.\n\n  Fixpoint sll (ls : list W) (p : W) : HProp :=\n    match ls with\n      | nil => [| p = 0 |]\n      | x :: ls' => [| p <> 0 |] * Ex p', (p ==*> x, p') * sll ls' p'\n    end.\n\n  Theorem sll_extensional : forall ls (p : W), HProp_extensional (sll ls p).\n    destruct ls; reflexivity.\n  Qed.\n\n  Theorem nil_fwd : forall ls (p : W), p = 0\n    -> sll ls p ===> [| ls = nil |].\n    destruct ls; sepLemma.\n  Qed.\n\n  Theorem nil_bwd : forall ls (p : W), p = 0\n    -> [| ls = nil |] ===> sll ls p.\n    destruct ls; sepLemma.\n  Qed.\n\n  Theorem cons_fwd : forall ls (p : W), p <> 0\n    -> sll ls p ===> Ex x, Ex ls', [| ls = x :: ls' |] * Ex p', (p ==*> x, p') * sll ls' p'.\n    destruct ls; sepLemma.\n  Qed.\n\n  Theorem cons_bwd : forall ls (p : W), p <> 0\n    -> (Ex x, Ex ls', [| ls = x :: ls' |] * Ex p', (p ==*> x, p') * sll ls' p') ===> sll ls p.\n    destruct ls; sepLemma;\n      match goal with\n        | [ H : _ :: _ = _ :: _ |- _ ] => injection H; sepLemma\n      end.\n  Qed.\nEnd SinglyLinkedList.\n\nImport SinglyLinkedList.\nHint Immediate sll_extensional.\n\n(*TIME Clear Timing Profile. *)\n\nDefinition hints : TacPackage.\n(*TIME idtac \"sll:prepare\". Time *)\n  prepare (nil_fwd, cons_fwd) (nil_bwd, cons_bwd).\n(*TIME Time *)\nDefined.\n\nDefinition null A (ls : list A) : bool :=\n  match ls with\n    | nil => true\n    | _ => false\n  end.\n\nDefinition nullS : spec := SPEC(\"x\") reserving 0\n  Al ls,\n  PRE[V] sll ls (V \"x\")\n  POST[R] [| R = null ls |] * sll ls (V \"x\").\n\nDefinition lengthS : spec := SPEC(\"x\") reserving 1\n  Al ls,\n  PRE[V] sll ls (V \"x\")\n  POST[R] [| R = length ls |] * sll ls (V \"x\").\n\nDefinition revS : spec := SPEC(\"x\") reserving 3\n  Al ls,\n  PRE[V] sll ls (V \"x\")\n  POST[R] sll (rev ls) R.\n\nDefinition appendS : spec := SPEC(\"x\", \"y\") reserving 2\n  Al ls1, Al ls2,\n  PRE[V] sll ls1 (V \"x\") * sll ls2 (V \"y\")\n  POST[R] sll (ls1 ++ ls2) R.\n\nDefinition sllM := bmodule \"sll\" {{\n  bfunction \"null\"(\"x\") [nullS]\n    If (\"x\" = 0) {\n      Return 1\n    } else {\n      Return 0\n    }\n  end with bfunction \"length\"(\"x\", \"n\") [lengthS]\n    \"n\" <- 0;;\n    [Al ls,\n      PRE[V] sll ls (V \"x\")\n      POST[R] [| R = V \"n\" ^+ (length ls : W) |] * sll ls (V \"x\")]\n    While (\"x\" <> 0) {\n      \"n\" <- \"n\" + 1;;\n      \"x\" <- \"x\" + 4;;\n      \"x\" <-* \"x\"\n    };;\n    Return \"n\"\n  end with bfunction \"rev\"(\"x\", \"acc\", \"tmp1\", \"tmp2\") [revS]\n    \"acc\" <- 0;;\n    [Al ls, Al accLs,\n      PRE[V] sll ls (V \"x\") * sll accLs (V \"acc\")\n      POST[R] Ex ls', [| ls' = rev_append ls accLs |] * sll ls' R ]\n    While (\"x\" <> 0) {\n      \"tmp2\" <- \"x\";;\n      \"tmp1\" <- \"x\" + 4;;\n      \"x\" <-* \"tmp1\";;\n      \"tmp1\" *<- \"acc\";;\n      \"acc\" <- \"tmp2\"\n    };;\n    Return \"acc\"\n  end with bfunction \"append\"(\"x\", \"y\", \"r\", \"tmp\") [appendS]\n    If (\"x\" = 0) {\n      Return \"y\"\n    } else {\n      \"r\" <- \"x\";;\n      \"tmp\" <- \"x\" + 4;;\n      \"tmp\" <-* \"tmp\";;\n      [Al p1, Al x, Al ls1, Al ls2,\n        PRE[V] [| V \"x\" <> $0 |] * [| V \"tmp\" = p1 |]\n          * V \"x\" =*> x * (V \"x\" ^+ $4) =*> p1 * sll ls1 p1 * sll ls2 (V \"y\")\n        POST[R] [| R = V \"r\" |] * sll (x :: ls1 ++ ls2) (V \"x\") ]\n      While (\"tmp\" <> 0) {\n        \"x\" <- \"tmp\";;\n        \"tmp\" <- \"x\" + 4;;\n        \"tmp\" <-* \"tmp\"\n      };;\n\n      \"tmp\" <- \"x\" + 4;;\n      \"tmp\" *<- \"y\";;\n      Return \"r\"\n    }\n  end\n}}.\n\nLtac notConst x :=\n  match x with\n    | O => fail 1\n    | S ?x' => notConst x'\n    | _ => idtac\n  end.\n\nLtac finish := repeat match goal with\n                        | [ H : _ = _ |- _ ] => rewrite H\n                      end; simpl;\n               repeat match goal with\n                        | [ |- context[natToW (S ?x)] ] =>\n                          notConst x; rewrite (natToW_S x)\n                      end; try rewrite <- rev_alt;\n               congruence || W_eq || reflexivity || tauto || eauto.\n\nTheorem sllMOk : moduleOk sllM.\n(*TIME idtac \"sll:verify\". Time *)\n  vcgen; abstract (sep hints; finish).\n(*TIME Time *)\nQed.\n\n(*TIME Print Timing Profile. *)\n", "meta": {"author": "csgordon", "repo": "bedrock", "sha": "debab1b6e491b7c5e83bd3b1fe5d0e4c4e728d12", "save_path": "github-repos/coq/csgordon-bedrock", "path": "github-repos/coq/csgordon-bedrock/bedrock-debab1b6e491b7c5e83bd3b1fe5d0e4c4e728d12/examples/SinglyLinkedList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.25237800026447665}}
{"text": "(** ** Trakhtenbrot's Theorem *)\n\nFrom Undecidability.PCP Require Import PCP_undec.\nFrom Undecidability.Synthetic Require Import Undecidability ReducibilityFacts DecidabilityFacts.\nFrom Undecidability.FOL.Semantics.FiniteTarski Require Fragment Full DoubleNegation.\nFrom Undecidability.FOL Require Import FSAT Reductions.FSATd_to_FSATdc Reductions.PCPb_to_FSAT.\n\nSection Full.\n  Import Full.\n  Theorem FSAT_undec :\n    undecidable FSAT.\n  Proof.\n    apply (undecidability_from_reducibility dPCPb_undec).\n    exists (finsat_formula). intros x. apply FSAT_reduction.\n  Qed.\n\n  Theorem FSATd_undec :\n    undecidable FSATd.\n  Proof. \n    apply (undecidability_from_reducibility dPCPb_undec).\n    exists (finsat_formula). intros x. apply FSATd_reduction.\n  Qed.\n\n  Theorem FSATdc_undec :\n    undecidable FSATdc.\n  Proof.\n   apply (undecidability_from_reducibility FSATd_undec).\n   apply FSATd_to_FSATdc.reduction.\n  Qed.\nEnd Full.\n\n\nSection Fragment.\n  Import Fragment DoubleNegation.\n\n  Theorem FSAT_undec_frag :\n    undecidable FSAT.\n  Proof.\n    apply (undecidability_from_reducibility (FSAT_undec)).\n    exists translate_form.\n    intros k. split; intros (D & I & rho & (l & Hlist) & Hdec & H).\n    - exists D, (full_tarski_tarski_interp I), rho; repeat split.\n      + now exists l.\n      + destruct I; apply Hdec.\n      + rewrite <- (full_interp_inverse_1 I) in H.\n        destruct (Hdec FSAT.P) as [fP HfP].\n        destruct (Hdec FSAT.less) as [fL HfL].\n        destruct (Hdec FSAT.equiv) as [fE HfE].\n        unshelve now eapply translate_form_correct in H.\n        intros ff phi rho'. apply Full.general_decider. 1: now exists l.\n        rewrite full_interp_inverse_1. intros ff' [] v ee; cbn;\n        apply DecidabilityFacts.decidable_iff'.\n        1: now exists fP. 1: now exists fL. now exists fE.\n    - exists D, (tarski_full_tarski_interp I), rho; repeat split.\n      + now exists l.\n      + destruct I; apply Hdec.\n      + destruct (Hdec FSAT.P) as [fP HfP].\n        destruct (Hdec FSAT.less) as [fL HfL].\n        destruct (Hdec FSAT.equiv) as [fE HfE].\n        unshelve now eapply translate_form_correct.\n        intros ff phi rho'. apply Full.general_decider. 1: now exists l.\n        intros ff' [] v ee; cbn;\n        apply DecidabilityFacts.decidable_iff'; destruct I.\n        1: now exists fP. 1: now exists fL. now exists fE.\n  Qed.\n\n  Theorem FSATd_undec_frag :\n    undecidable FSATd.\n  Proof.\n    apply (undecidability_from_reducibility (FSATd_undec)).\n    exists translate_form.\n    intros k. split; intros (D & I & rho & (l & Hlist) & Hdisc & Hdec & H).\n    - exists D, (full_tarski_tarski_interp I), rho; repeat split.\n      + now exists l.\n      + easy.\n      + destruct I; apply Hdec.\n      + rewrite <- (full_interp_inverse_1 I) in H.\n        destruct (Hdec FSAT.P) as [fP HfP].\n        destruct (Hdec FSAT.less) as [fL HfL].\n        destruct (Hdec FSAT.equiv) as [fE HfE].\n        unshelve now eapply translate_form_correct in H.\n        intros ff phi rho'. apply Full.general_decider. 1: now exists l.\n        rewrite full_interp_inverse_1. intros ff' [] v ee; cbn;\n        apply DecidabilityFacts.decidable_iff'.\n        1: now exists fP. 1: now exists fL. now exists fE.\n    - exists D, (tarski_full_tarski_interp I), rho; repeat split.\n      + now exists l.\n      + easy.\n      + destruct I; apply Hdec.\n      + destruct (Hdec FSAT.P) as [fP HfP].\n        destruct (Hdec FSAT.less) as [fL HfL].\n        destruct (Hdec FSAT.equiv) as [fE HfE].\n        unshelve now eapply translate_form_correct.\n        intros ff phi rho'. apply Full.general_decider. 1: now exists l.\n        intros ff' [] v ee; cbn;\n        apply DecidabilityFacts.decidable_iff'; destruct I.\n        1: now exists fP. 1: now exists fL. now exists fE.\n  Qed.\n\n  Theorem FSATdc_undec_frag :\n    undecidable FSATdc.\n  Proof.\n    apply (undecidability_from_reducibility FSATdc_undec).\n    unshelve eexists translate_form_closed. 1-2: unfold Dec.dec; repeat decide equality.\n    intros [k Hclosed]. split; intros (D & I & rho & (l & Hlist) & Hdisc & Hdec & H).\n    - exists D, (full_tarski_tarski_interp I), rho; repeat split.\n      + now exists l.\n      + easy.\n      + destruct I; apply Hdec.\n      + rewrite <- (full_interp_inverse_1 I) in H.\n        destruct (Hdec FSAT.P) as [fP HfP].\n        destruct (Hdec FSAT.less) as [fL HfL].\n        destruct (Hdec FSAT.equiv) as [fE HfE].\n        unshelve now eapply translate_form_correct in H.\n        intros ff phi rho'. apply Full.general_decider. 1: now exists l.\n        rewrite full_interp_inverse_1. intros ff' [] v ee; cbn;\n        apply DecidabilityFacts.decidable_iff'.\n        1: now exists fP. 1: now exists fL. now exists fE.\n    - exists D, (tarski_full_tarski_interp I), rho; repeat split.\n      + now exists l.\n      + easy.\n      + destruct I; apply Hdec.\n      + destruct (Hdec FSAT.P) as [fP HfP].\n        destruct (Hdec FSAT.less) as [fL HfL].\n        destruct (Hdec FSAT.equiv) as [fE HfE].\n        unshelve now eapply translate_form_correct.\n        intros ff phi rho'. apply Full.general_decider. 1: now exists l.\n        intros ff' [] v ee; cbn;\n        apply DecidabilityFacts.decidable_iff'; destruct I.\n        1: now exists fP. 1: now exists fL. now exists fE.\n  Qed.\nEnd Fragment.\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/FSAT_direct_undec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2523779933878144}}
{"text": "(** a generalization of Σ-monoids to monoidal categories in place of functor categories\n\nauthor: Kobe Wullaert 2023\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.\n\nRequire Import UniMath.CategoryTheory.DisplayedCats.Core.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Constructions.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Total.\nRequire Import UniMath.CategoryTheory.Monoidal.WhiskeredBifunctors.\nRequire Import UniMath.CategoryTheory.Monoidal.Categories.\nRequire Import UniMath.CategoryTheory.Actegories.MorphismsOfActegories.\nRequire Import UniMath.CategoryTheory.Monoidal.CategoriesOfMonoids.\nRequire Import UniMath.CategoryTheory.FunctorAlgebras.\nRequire Import UniMath.SubstitutionSystems.GeneralizedSubstitutionSystems.\n\nLocal Open Scope cat.\n\nImport BifunctorNotations.\n\nDefinition SigmaMonoid_characteristic_equation {V : category} {Mon_V : monoidal V} {H : V ⟶ V}\n    (x : V) (η : V ⟦ monoidal_unit Mon_V, x ⟧)\n    (μ : V ⟦ x ⊗_{ Mon_V} x, x ⟧) (τ :  V ⟦ H x, x ⟧)\n    (st : V ⟦ x ⊗_{ Mon_V} H x, H (x ⊗_{ Mon_V} x) ⟧) : UU\n    := st · #H μ · τ = x ⊗^{Mon_V}_{l} τ · μ.\n\nSection SigmaMonoid.\n\n  Context {V : category}\n          {Mon_V : monoidal V}\n          {H : V ⟶ V}\n          (θ : pointedtensorialstrength Mon_V H).\n\n  Definition SigmaMonoid_disp_cat_no_compatibility : disp_cat V\n    := dirprod_disp_cat (algebra_disp_cat H) (monoid_disp_cat Mon_V).\n\n  Definition SigmaMonoid_compatibility\n             (X : total_category SigmaMonoid_disp_cat_no_compatibility) : UU.\n  Proof.\n    set (x := pr1 X).\n    set (η := monoid_data_unit _ (pr22 X : monoid _ _)).\n    set (μ := monoid_data_multiplication _ (pr22 X : monoid _ _)).\n    set (τ := pr12 X : H x --> x).\n    set (st := pr1 θ (x ,, η) x).\n    exact (SigmaMonoid_characteristic_equation x η μ τ st).\n  Defined.\n\n  Definition SigmaMonoid_disp_cat_without_sigma_constr\n    : disp_cat (total_category SigmaMonoid_disp_cat_no_compatibility)\n    := disp_full_sub\n         (total_category SigmaMonoid_disp_cat_no_compatibility)\n         SigmaMonoid_compatibility.\n\n  Definition SigmaMonoid_disp_cat\n    : disp_cat V\n    := sigma_disp_cat SigmaMonoid_disp_cat_without_sigma_constr.\n\n  Definition SigmaMonoid : category\n    := total_category SigmaMonoid_disp_cat.\n\n  Definition SigmaMonoid_carrier (σ : SigmaMonoid) : V := pr1 σ.\n  Definition SigmaMonoid_η (σ : SigmaMonoid) : V ⟦ monoidal_unit Mon_V, SigmaMonoid_carrier σ ⟧\n    := monoid_data_unit _ (pr212 σ : monoid _ _).\n  Definition SigmaMonoid_μ (σ : SigmaMonoid) :\n    V ⟦ SigmaMonoid_carrier σ ⊗_{ Mon_V} SigmaMonoid_carrier σ, SigmaMonoid_carrier σ ⟧\n    := monoid_data_multiplication _ (pr212 σ : monoid _ _).\n  Definition SigmaMonoid_τ (σ : SigmaMonoid) : V ⟦ H (SigmaMonoid_carrier σ), SigmaMonoid_carrier σ⟧\n    := pr112 σ.\n\n  Lemma SigmaMonoid_is_compatible (σ : SigmaMonoid) :\n    SigmaMonoid_characteristic_equation (SigmaMonoid_carrier σ)\n      (SigmaMonoid_η σ) (SigmaMonoid_μ σ) (SigmaMonoid_τ σ)\n      (pr1 θ (SigmaMonoid_carrier σ ,, SigmaMonoid_η σ) (SigmaMonoid_carrier σ)).\n  Proof.\n    exact (pr22 σ).\n  Qed.\n\n  Let MON := category_of_monoids_in_monoidal_cat Mon_V.\n\n  (** the following should be an instance of general results on projection into constituents *)\n  Definition SigmaMonoid_to_monoid_data : functor_data SigmaMonoid MON.\n  Proof.\n    use make_functor_data.\n    - intro σ. exact (pr1 σ,, pr212 σ).\n    - intros σ1 σ2 m. exact (pr1 m,, pr212 m).\n  Defined.\n\n  Lemma SigmaMonoid_to_monoid_laws : is_functor SigmaMonoid_to_monoid_data.\n  Proof.\n    split.\n    - intro. apply idpath.\n    - intro; intros. apply idpath.\n  Qed.\n\n  Definition SigmaMonoid_to_monoid : functor SigmaMonoid MON :=\n    SigmaMonoid_to_monoid_data,,SigmaMonoid_to_monoid_laws.\n\nEnd SigmaMonoid.\n\nSection GHSS_to_SigmaMonoid.\n\n  Context {V : category}\n          {Mon_V : monoidal V}\n          {H : V ⟶ V}\n          (θ : pointedtensorialstrength Mon_V H).\n\n  Definition ghhs_to_sigma_monoid (t : ghss Mon_V H θ)\n    : SigmaMonoid θ.\n  Proof.\n    exists (pr1 t).\n    exists (tau_from_alg Mon_V H θ t ,, ghss_monoid Mon_V H θ t).\n    exact (gfbracket_τ Mon_V H θ t (Z :=  (pr1 t,, μ_0 Mon_V H θ t)) (identity _)).\n  Defined.\n\nEnd GHSS_to_SigmaMonoid.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/SubstitutionSystems/SigmaMonoids.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2523076131713541}}
{"text": "(* From Coq Require Import Program.Wf. *)\nFrom Coq Require Import Relation_Definitions.\nFrom Relational Require Import OrderEnrichedCategory OrderEnrichedRelativeMonadExamples.\nFrom Mon Require Import SPropBase.\nSet Warnings \"-notation-overridden,-ambiguous-paths\".\nFrom mathcomp Require Import all_ssreflect (*boolp*).\nSet Warnings \"notation-overridden,ambiguous-paths\".\nFrom Crypt Require Import Axioms OrderEnrichedRelativeAdjunctions LaxFunctorsAndTransf LaxMorphismOfRelAdjunctions TransformingLaxMorph OrderEnrichedRelativeAdjunctionsExamples ThetaDex SubDistr Theta_exCP ChoiceAsOrd FreeProbProg UniversalFreeMap RelativeMonadMorph_prod LaxComp chUniverse.\n(* From Crypt Require Import only_prob.Rules. *)\n\nImport SPropNotations.\n\n(*In this file we transform the lax relative monad morphism thetaDex : FreeProb² → Wrelprop\ninto a stateful effect observation stT_thetaDex : StT(FreeProb²) → StT(Wrelprop)*)\n\n(*\nWe also subsequently make the domain of stT_thetaDex free by precomposing with a morphism\nwith type FreeStateProb² → StT(FreeProb²)\n*)\n\nSection StT_thetaDex_definition.\n\n  Let myThetaDex :=  thetaDex.\n\n  Context {S1 S2 : choiceType}.\n  Let TingAdj1_0 := Chi_DomainStateAdj S1 S2.\n  Let TingAdj2_0 :=  Chi_CodomainStateAdj S1 S2.\n\n  Let myJMWprod :=\n    @RelativeMonadMorph_prod.JMWprod _ _ (ord_functor_id TypeCat) _ _ (ord_functor_id TypeCat).\n\n  Program Definition state_beta' :  lnatTrans\n    (lord_functor_comp (strict2laxFunc (binaryToTheS S1 S2))\n       (strict2laxFunc (ord_functor_comp myJMWprod Jprod)))\n    (lord_functor_comp (strict2laxFunc (ord_functor_comp myJMWprod Jprod))\n       (strict2laxFunc (ToTheS_OrdCat S1 S2))) :=\n    mkLnatTrans _ _.\n  Next Obligation.\n    move=> [A1 A2]. simpl.\n    unshelve econstructor.\n    move=> [g1 g2]. unshelve econstructor.\n    move=> [s1 s2]. exact ⟨ g1 s1 , g2 s2 ⟩.\n    cbv. move=> x y. move=> Hxy. destruct Hxy. reflexivity.\n    cbv. move=> x y. move=> Hxy. move=> [s1 s2]. destruct Hxy. reflexivity.\n  Defined.\n\n  (*this is a morphism between the transformed adjunctions. see rlmm_from_lmla below\n   to conclude the def of stT_thetaDex*)\n  Program Definition stT_thetaDex_adj :=\n    Transformed_lmla myThetaDex TingAdj1_0 TingAdj2_0 state_beta' _ _.\n  Next Obligation.\n    move=> [A1 A2 [a1 a2] [s1 s2]].\n    (*Unfortunately we have to manually destruct A1 and A2 because functions were defined like this in\n     Theta_exCP.v*)\n    move: A1 a1. move=> [A1 chA1] a1.\n    move: A2 a2. move=> [A2 chA2] a2.\n    cbv. reflexivity.\n  Qed.\n  Next Obligation.\n    move=> [[A1 chA1] [A2 chA2]] [Y1 Y2] [g1 g2]. simpl.\n    apply sig_eq. simpl. apply boolp.funext. move=> [[a1 s1] [a2 s2]].\n    simpl. reflexivity.\n  Qed.\n\n  Definition stT_thetaDex := rlmm_from_lmla stT_thetaDex_adj.\n\n\nEnd StT_thetaDex_definition.\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\n(*\nHere we build a unary choiceType relative monad, free, with a stateful-probabilistic\nsignature.\n*)\nSection FreeStateProbMonad.\n\n\n  Context {S : choiceType}. (*the set of states is itself a choiceType*)\n\n(*old formulation*)\n  (* Inductive stateE : Type -> Type := *)\n  (* |gett : stateE S *)\n  (* |putt : S -> stateE unit. *)\n\n\n  Inductive S_OP :=\n    |sgett : S_OP\n    |sputt : S -> S_OP.\n\n  Definition S_AR : S_OP -> choiceType := fun sop =>\n    match sop with\n    |sgett => S\n    |sputt _ => chUnit\n    end.\n\n\n\n  (*Now how can we combine state and probabilities?*)\n  (*operations are either stateful or probabilistic...*)\n  Inductive SP_OP :=\n    |gett : SP_OP\n    |putt : S -> SP_OP\n    |samplee : P_OP -> SP_OP.\n\n  Definition SP_AR : SP_OP -> choiceType := fun stpOp =>\n    match stpOp with\n    |gett => S\n    |putt _ => chUnit\n    |samplee p_op => chElement (projT1 p_op)\n    end.\n\n  Definition op_iota : P_OP -> SP_OP := samplee.\n\n  Lemma computational_sliceMorph (o : P_OP) :\n    P_AR o = SP_AR ( samplee o ).\n  Proof.\n    reflexivity.\n  Qed.\n\n  (*retro comp*)\n  Definition ops_StP := SP_OP.\n  Definition ar_StP := SP_AR.\n\n  (*Here is our free choiceType relative monad with a stateful probabilistic signature*)\n  Definition FrStP := rFree ops_StP ar_StP.\n\nEnd FreeStateProbMonad.\n\n(*Now we build a relative monad morphism from FrStP to StT(Frp). In other words\nwe interpret the stateful part of the signature of FrStP, but not the probabilistic\none*)\nSection UnaryInterpretState.\n\n  Context {S : choiceType}.\n\n\n  (*The domain of the intended morphism is FrStP ...*)\n  Let FrStP_filled := @FrStP S.\n\n\n  (*The codomain is StT(Frp)*)\n\n  Let prob_ops :=  P_OP.\n  Let prob_ar :=  P_AR.\n\n  Definition Frp :=  rFree prob_ops prob_ar.\n  Let myLflat :=  unaryTimesS1 S.\n  Let myR := ToTheS S.\n  Notation FrpF := (rFreeF prob_ops prob_ar).\n\n\n  Program Definition unaryStTransfromingAdj :\n  leftAdjunctionSituation choice_incl (ord_functor_comp myLflat choice_incl) myR :=\n    mkNatIso _ _ _ _ _ _ _.\n  Next Obligation. (*ni_map*)\n    move=> [A T]. simpl. unshelve econstructor.\n      move=> g a s. exact (g (a,s)).\n      cbv. move=> g1 g2. move=> Hg12. move=> a.\n      apply boolp.funext. move=> s.\n      move: Hg12 => /(_ (a,s)) Hg12.\n      assumption.\n  Defined.\n  Next Obligation. (*ni_inv*)\n    move=> [A T]. simpl. unshelve econstructor.\n    move=> g [a s]. exact (g a s).\n    cbv. move=> g1 g2. move=> Hg12. move=> [a s].\n    move: Hg12 => /(_ a) Hg12.\n    destruct Hg12. reflexivity.\n  Defined.\n  Next Obligation.\n    move=> [A T]. move=> [A' T'].\n    move=> [p q]. simpl in *.\n    apply sig_eq. simpl. apply boolp.funext. move=> g.\n    apply boolp.funext. move=> a'. apply boolp.funext.\n    move=> s. simpl.\n    unfold OrderEnrichedRelativeAdjunctionsExamples.ToTheS_obligation_1.\n    reflexivity.\n  Qed.\n  Next Obligation.\n    move=> [A T].\n    apply sig_eq. simpl.\n    apply boolp.funext. move=> g. cbv.\n    apply boolp.funext. move=> a. reflexivity.\n  Qed.\n  Next Obligation.\n    move=> [A T].\n    apply sig_eq. simpl.\n    apply boolp.funext. move=> g. cbv.\n    apply boolp.funext. move=> [a s].\n    reflexivity.\n  Qed.\n\n\n  (*This is StT(Frp)*)\n  Definition stT_Frp := AdjTransform Frp myLflat myR unaryStTransfromingAdj.\n\n  (*Let us define get and put in this monad ...*)\n  Let retrFree_filled (X:choiceType) := retrFree prob_ops prob_ar X.\n\n  Definition getStP : stT_Frp S :=\n    fun s : S => retrFree_filled (F_choice_prod_obj ⟨ S, S ⟩) (s, s).\n\n  Definition putStP : S -> stT_Frp unit_choiceType := fun new_s old_s =>\n    retrFree_filled (F_choice_prod ⟨ unit_choiceType, S ⟩) (tt, new_s).\n\n\n  Definition probopStP {T : chUniverse} (sd: SDistr T) : stT_Frp (chElement T).\n    move=> s. simpl.\n    unshelve eapply ropr.\n      unshelve econstructor. exact T. exact sd.\n    cbn. move=> t. eapply retrFree_filled. simpl. exact ( (t,s) ).\n  Defined.\n\n\n  Let ops_StP_filled :=  @ops_StP S.\n  Let ar_StP_filled := @ar_StP S.\n\n\n  Definition sigMap : forall op : ops_StP_filled, stT_Frp( ar_StP_filled op ).\n  move=> op. cbv in op. destruct op.\n  - exact getStP.\n  - cbn. exact (putStP s).\n  - cbn. apply probopStP. destruct p. cbn.  assumption.\n  Defined.\n\n  Definition unaryIntState\n  : relativeMonadMorphism _ _ (FrStP_filled) stT_Frp\n  := @outOfFree (ops_StP_filled) (ar_StP_filled) stT_Frp sigMap.\n\n\nEnd UnaryInterpretState.\n\n\n\n(*now we square this morphism to get a relative monad morphism FrStP² → stT(Frp)²*)\nSection SquareUnaryIntState.\n\n  Context {S1 S2 : choiceType}.\n\n  Let unaryIntState_filled_left := @unaryIntState S1.\n  Let unaryIntState_filled_right := @unaryIntState S2.\n  Definition preInterpretState :=\n  prod_relativeMonadMorphism\n    unaryIntState_filled_left unaryIntState_filled_right.\n\nEnd SquareUnaryIntState.\n\n\n(*We also need an additional bit stT(Frp)² → stT(Frp²), the latter being the domain\nof stT_thetaDex *)\nSection StT_vs_squaredMonads.\n\n  Context {S1 S2 : choiceType}.\n\n  Let preInterpretState_filled := @preInterpretState S1 S2.\n  Let stT_thetaDex_filled := @stT_thetaDex S1 S2.\n\n  (*domain of the additional morphism*)\n  Let squOf_stT_Frp := rlmm_codomain preInterpretState_filled.\n  (*and codomain*)\n  Let stT_squOf_Frp := rlmm_domain stT_thetaDex_filled.\n\n  (*base square*)\n  Definition BinaryTrivialChi :\n  natIso ( prod_functor choice_incl choice_incl )\n         (ord_functor_comp (prod_functor choice_incl choice_incl)\n                           (ord_functor_id (prod_cat TypeCat TypeCat))).\n  apply natIso_sym. apply ord_functor_unit_right.\n  Defined.\n\n  Notation Frpp := (rFreeF P_OP P_AR).\n\n  Program Definition additionalIntState :\n  relativeMonadMorphism (ord_functor_id _) BinaryTrivialChi squOf_stT_Frp stT_squOf_Frp :=\n    mkRelMonMorph (ord_functor_id _) BinaryTrivialChi squOf_stT_Frp stT_squOf_Frp _ _ _.\n  Next Obligation.\n    move=> [A1 A2]. unshelve econstructor.\n      easy.\n      easy.\n  Defined.\n\nEnd StT_vs_squaredMonads.\n\n\n(*And now we are finally ready to define the intended theta *)\nSection MakeTheDomainFree.\n\n  Context {S1 S2 : choiceType}.\n\n  Let preInterpretState_filled := @preInterpretState S1 S2.\n  Let addIntState_filled := @additionalIntState S1 S2.\n  Let stT_thetaDex_filled := @stT_thetaDex S1 S2.\n\n  (*FrStP² → stT(Frp²) part*)\n  Definition justInterpState :=\n  rlmm_comp _ _ _ _ _ _ _ preInterpretState_filled addIntState_filled.\n\n  (*the other part is stT_thetaDex : stT(Frp²) → Wstrelprop*)\n\n  (*we now combine those two morphisms *)\n  Definition thetaFstdex := rlmm_comp _ _ _ _ _ _ _ justInterpState stT_thetaDex_filled.\n\n  (*\n    Fstdex because:\n       start with theta dex = θex ∘ θdens : Frp² → Wrelprop\n       then state transform ; stT( θdex ) : StT( Frp² ) → WStRelprop\n       then make the domain free ; θFstdex : FrStP ² → WStRelprop\n\n  *)\n\n  (*thetaFdex : FrStP² → Wrelprop *)\n(*\n  Eval hnf in rlmm_domain thetaFstdex.\n  Eval hnf in rlmm_codomain thetaFstdex.\n*)\n\nEnd MakeTheDomainFree.\n\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/StateTransformingLaxMorph.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.25227477306869234}}
{"text": "Require Import sflib.\n\nRequire Import Axioms.\nRequire Import Basic.\nRequire Import DataStructure.\nRequire Import DenseOrder.\nRequire Import Loc.\n\nRequire Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import MemoryFacts.\nRequire Import MemoryProps.\n\nSet Implicit Arguments.\n\nInductive split_reserve\n          (promises1 mem1:Memory.t)\n          (loc:Loc.t) (from to:Time.t) (msg:Message.t)\n          (promises2 mem2:Memory.t): forall (kind:Memory.op_kind), Prop :=\n| split_reserve_intro\n    ts3\n    (PROMISES: Memory.split promises1 loc from to ts3 msg Message.reserve promises2)\n    (MEM: Memory.split mem1 loc from to ts3 msg Message.reserve mem2)\n    (TS: Memory.message_to msg loc to)\n    (RESERVE: exists val' released', msg = Message.concrete val' released'):\n    split_reserve promises1 mem1 loc from to msg promises2 mem2 (Memory.op_kind_split ts3 Message.reserve)\n.\nHint Constructors split_reserve.\n\nLemma split_reserve_write prom0 mem0 loc from to val released prom1 mem1 ts3 prom2\n      (SEMI: split_reserve prom0 mem0 loc from to (Message.concrete val released) prom1 mem1 (Memory.op_kind_split ts3 Message.reserve))\n      (REMOVE: Memory.remove prom1 loc from to (Message.concrete val released) prom2)\n      (MLE: Memory.le prom0 mem0)\n  :\n    exists prom_mid0 mem_mid0 mem_mid1,\n      (<<REMOVE: Memory.promise prom0 mem0 loc from ts3 Message.reserve prom_mid0 mem_mid0 Memory.op_kind_cancel>>) /\\\n      (<<ADDMESSAGE: Memory.write prom_mid0 mem_mid0 loc from to val released prom_mid0 mem_mid1 Memory.op_kind_add>>) /\\\n      (<<ADDRESERVE: Memory.promise prom_mid0 mem_mid1 loc to ts3 Message.reserve prom2 mem1 Memory.op_kind_add>>).\nProof.\nAdmitted.\n  (* inv SEMI. des. clarify.\n  hexploit split_succeed_wf; try apply PROMISES. i. des.\n  exploit Memory.split_get0; [eapply PROMISES|]. intros. des.\n  exploit (@Memory.remove_exists prom0 loc from ts3 Message.reserve); eauto.\n  intros [prom_mid0 PROMREMOVE].\n  exploit (@Memory.remove_exists_le prom0 mem0 loc from ts3 Message.reserve); eauto.\n  intros [mem_mid0 MEMREMOVE].\n  assert (PROMISE0: Memory.promise prom0 mem0 loc from ts3 Message.reserve prom_mid0 mem_mid0 Memory.op_kind_cancel).\n  { econs; eauto. }\n  hexploit promise_memory_le; try apply PROMISE0; eauto. intros MLEMID0.\n  exploit (@Memory.add_exists mem_mid0 loc from to (Message.concrete val' released')); eauto.\n  { ii. erewrite Memory.remove_o in GET4; eauto. des_ifs. guardH o.\n    exploit Memory.get_disjoint.\n    { eapply GET4. }\n    { eapply Memory.split_get0 in MEM. des. apply GET6. }\n    i. des.\n    { unguard. ss. des; clarify. }\n    { eapply x1; eauto. inv LHS. econs; eauto.\n      ss. etrans; eauto. left. auto. }\n  }\n  intros [mem_mid1 MEMADDMESSAGE].\n  exploit (@Memory.add_exists_le prom_mid0 mem_mid0 loc from to (Message.concrete val' released')); eauto.\n  intros [prom_mid1 PROMADDMESSAGE].\n  exploit (@Memory.remove_exists prom_mid1 loc from to (Message.concrete val' released')).\n  { eapply Memory.add_get0; eauto. }\n  intros [prom_mid2 PROMFULFILL].\n  assert (prom_mid2 = prom_mid0).\n  { eapply MemoryFacts.add_remove_eq; eauto. } subst.\n  assert (WRTIE0: Memory.write prom_mid0 mem_mid0 loc from to val' released' prom_mid0 mem_mid1 Memory.op_kind_add).\n  { econs; eauto. econs; eauto. i.\n    erewrite Memory.remove_o in GET4; eauto. des_ifs. guardH o.\n    exploit Memory.get_disjoint.\n    { eapply GET4. }\n    { eapply Memory.split_get0 in MEM. des. apply GET6. }\n    i. des.\n    { unguard. ss. des; clarify. }\n    { eapply memory_get_ts_strong in GET4. des.\n      { subst. exfalso. eapply Time.lt_strorder.\n        eapply TimeFacts.lt_le_lt; try apply TS12. eapply Time.bot_spec. }\n      eapply x0.\n      { instantiate (1:=Time.meet to' ts3). unfold Time.meet. des_ifs.\n        { econs; ss. refl. }\n        { econs; ss. left. auto. }\n      }\n      { unfold Time.meet. des_ifs.\n        { econs; ss. transitivity to; eauto. }\n        { econs; ss.\n          { transitivity to; eauto. }\n          { refl. }\n        }\n      }\n    }\n  }\n  hexploit write_memory_le; try apply WRITE0; eauto. intros MLEMID1.\n  exploit (@Memory.add_exists mem_mid1 loc to ts3 Message.reserve); eauto.\n  { ii. erewrite Memory.add_o in GET4; eauto. des_ifs.\n    { ss. des; clarify. inv LHS. inv RHS. ss. timetac. }\n    guardH o. erewrite Memory.remove_o in GET4; eauto. des_ifs. guardH o0.\n    exploit Memory.get_disjoint.\n    { eapply GET4. }\n    { eapply Memory.split_get0 in MEM. des. apply GET6. }\n    i. des.\n    { unguard. ss. des; clarify. }\n    { eapply x1; eauto. inv LHS. econs; eauto. }\n  }\n  { econs. }\n  intros [mem_mid2 MEMADDRESERVE].\n  exploit (@Memory.add_exists_le prom_mid0 mem_mid1 loc to ts3 Message.reserve); eauto.\n  intros [prom_mid2 PROMADDRESERVE].\n  assert (PROMEQ: prom_mid2 = prom2).\n  { eapply Memory.ext. intros.\n    erewrite (@Memory.add_o prom_mid2 prom_mid0); eauto.\n    erewrite (@Memory.remove_o prom_mid0 prom0); eauto.\n    erewrite (@Memory.remove_o prom2 prom1); eauto.\n    erewrite (@Memory.split_o prom1 prom0); eauto. des_ifs.\n    { ss. des; clarify. }\n    { ss. des; clarify. }\n  }\n  assert (MEMEQ: mem_mid2 = mem1).\n  { eapply Memory.ext. intros.\n    erewrite (@Memory.add_o mem_mid2 mem_mid1); eauto.\n    erewrite (@Memory.add_o mem_mid1 mem_mid0); eauto.\n    erewrite (@Memory.remove_o mem_mid0 mem0); eauto.\n    erewrite (@Memory.split_o mem1 mem0); eauto. des_ifs.\n    ss. des; clarify.\n  }\n  subst. esplits; eauto. econs; eauto. ss.\nQed. *)\n\nLemma split_reserve_promise prom0 mem0 loc from to msg prom1 mem1 ts3\n      (SEMI: split_reserve prom0 mem0 loc from to msg prom1 mem1 (Memory.op_kind_split ts3 Message.reserve))\n      (MLE: Memory.le prom0 mem0)\n  :\n    exists prom_mid0 mem_mid0 prom_mid1 mem_mid1,\n      (<<REMOVE: Memory.promise prom0 mem0 loc from ts3 Message.reserve prom_mid0 mem_mid0 Memory.op_kind_cancel>>) /\\\n      (<<ADDMESSAGE: Memory.promise prom_mid0 mem_mid0 loc from to msg prom_mid1 mem_mid1 Memory.op_kind_add>>) /\\\n      (<<ADDRESERVE: Memory.promise prom_mid1 mem_mid1 loc to ts3 Message.reserve prom1 mem1 Memory.op_kind_add>>) /\\\n      (<<CLOSEDMSG: Memory.closed_message msg mem1 -> Memory.closed_message msg mem_mid1>>).\nProof.\nAdmitted.\n  (* inv SEMI. des. clarify.\n  hexploit split_succeed_wf; try apply PROMISES. i. des.\n  exploit Memory.split_get0; [eapply PROMISES|]. intros. des.\n  exploit (@Memory.remove_exists prom0 loc from ts3 Message.reserve); eauto.\n  intros [prom_mid0 PROMREMOVE].\n  exploit (@Memory.remove_exists_le prom0 mem0 loc from ts3 Message.reserve); eauto.\n  intros [mem_mid0 MEMREMOVE].\n  assert (PROMISE0: Memory.promise prom0 mem0 loc from ts3 Message.reserve prom_mid0 mem_mid0 Memory.op_kind_cancel).\n  { econs; eauto. }\n  hexploit promise_memory_le; try apply PROMISE0; eauto. intros MLEMID0.\n  exploit (@Memory.add_exists mem_mid0 loc from to (Message.concrete val' released')); eauto.\n  { ii. erewrite Memory.remove_o in GET4; eauto. des_ifs. guardH o.\n    exploit Memory.get_disjoint.\n    { eapply GET4. }\n    { eapply Memory.split_get0 in MEM. des. apply GET6. }\n    i. des.\n    { unguard. ss. des; clarify. }\n    { eapply x1; eauto. inv LHS. econs; eauto.\n      ss. etrans; eauto. left. auto. }\n  }\n  intros [mem_mid1 MEMADDMESSAGE].\n  exploit (@Memory.add_exists_le prom_mid0 mem_mid0 loc from to (Message.concrete val' released')); eauto.\n  intros [prom_mid1 PROMADDMESSAGE].\n  assert (PROMISE1: Memory.promise prom_mid0 mem_mid0 loc from to (Message.concrete val' released') prom_mid1 mem_mid1 Memory.op_kind_add).\n  { econs; eauto. i.\n    erewrite Memory.remove_o in GET4; eauto. des_ifs. guardH o.\n    exploit Memory.get_disjoint.\n    { eapply GET4. }\n    { eapply Memory.split_get0 in MEM. des. apply GET6. }\n    i. des.\n    { unguard. ss. des; clarify. }\n    { eapply memory_get_ts_strong in GET4. des.\n      { subst. exfalso. eapply Time.lt_strorder.\n        eapply TimeFacts.lt_le_lt; try apply TS12. eapply Time.bot_spec. }\n      eapply x0.\n      { instantiate (1:=Time.meet to' ts3). unfold Time.meet. des_ifs.\n        { econs; ss. refl. }\n        { econs; ss. left. auto. }\n      }\n      { unfold Time.meet. des_ifs.\n        { econs; ss. transitivity to; eauto. }\n        { econs; ss.\n          { transitivity to; eauto. }\n          { refl. }\n        }\n      }\n    }\n  }\n  hexploit promise_memory_le; try apply PROMISE1; eauto. intros MLEMID1.\n  exploit (@Memory.add_exists mem_mid1 loc to ts3 Message.reserve); eauto.\n  { ii. erewrite Memory.add_o in GET4; eauto. des_ifs.\n    { ss. des; clarify. inv LHS. inv RHS. ss. timetac. }\n    guardH o. erewrite Memory.remove_o in GET4; eauto. des_ifs. guardH o0.\n    exploit Memory.get_disjoint.\n    { eapply GET4. }\n    { eapply Memory.split_get0 in MEM. des. apply GET6. }\n    i. des.\n    { unguard. ss. des; clarify. }\n    { eapply x1; eauto. inv LHS. econs; eauto. }\n  }\n  { econs. }\n  intros [mem_mid2 MEMADDRESERVE].\n  exploit (@Memory.add_exists_le prom_mid1 mem_mid1 loc to ts3 Message.reserve); eauto.\n  intros [prom_mid2 PROMADDRESERVE].\n  assert (PROMEQ: prom_mid2 = prom1).\n  { eapply Memory.ext. intros.\n    erewrite (@Memory.add_o prom_mid2 prom_mid1); eauto.\n    erewrite (@Memory.add_o prom_mid1 prom_mid0); eauto.\n    erewrite (@Memory.remove_o prom_mid0 prom0); eauto.\n    erewrite (@Memory.split_o prom1 prom0); eauto. des_ifs.\n    ss. des; clarify.\n  }\n  assert (MEMEQ: mem_mid2 = mem1).\n  { eapply Memory.ext. intros.\n    erewrite (@Memory.add_o mem_mid2 mem_mid1); eauto.\n    erewrite (@Memory.add_o mem_mid1 mem_mid0); eauto.\n    erewrite (@Memory.remove_o mem_mid0 mem0); eauto.\n    erewrite (@Memory.split_o mem1 mem0); eauto. des_ifs.\n    ss. des; clarify.\n  }\n  subst. esplits; eauto.\n  { econs; eauto. ss. }\n  { i. eapply memory_concrete_le_closed_msg; try apply H. ii.\n    erewrite (@Memory.split_o mem1 mem0) in GET4; eauto.\n    erewrite (@Memory.add_o mem_mid1 mem_mid0); eauto.\n    erewrite (@Memory.remove_o mem_mid0 mem0); eauto. des_ifs.\n  }\nQed. *)", "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/SplitReserve.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2522747667728525}}
{"text": "Require Import Platform.AutoSep.\n\nRequire Import Platform.Malloc Platform.Cito.examples.Cell.\n\n\nModule Type ADT.\n  Parameter cell : W -> W -> HProp.\n\n  Axiom cell_fwd : forall n c, cell n c ===> [| c <> 0 |] * [| freeable c 2 |]\n    * Ex junk, c ==*> n, junk.\n  Axiom cell_bwd : forall n (c : W), [| c <> 0 |] * [| freeable c 2 |]\n    * (Ex junk, c ==*> n, junk) ===> cell n c.\nEnd ADT.\n\nModule Adt : ADT.\n  Open Scope Sep_scope.\n\n  Definition cell (n c : W) : HProp :=\n    [| c <> 0 |] * [| freeable c 2 |]\n    * Ex junk, c ==*> n, junk.\n\n  Theorem cell_fwd : forall n c, cell n c ===> [| c <> 0 |] * [| freeable c 2 |]\n    * Ex junk, c ==*> n, junk.\n    unfold cell; sepLemma.\n  Qed.\n\n  Theorem cell_bwd : forall n (c : W), [| c <> 0 |] * [| freeable c 2 |]\n    * (Ex junk, c ==*> n, junk) ===> cell n c.\n    unfold cell; sepLemma.\n  Qed.\nEnd Adt.\n\nImport Adt.\nExport Adt.\n\nDefinition hints : TacPackage.\n  prepare cell_fwd cell_bwd.\nDefined.\n\nDefinition newS := newS cell 8.\nDefinition deleteS := deleteS cell 6.\nDefinition readS := readS cell 0.\nDefinition writeS := writeS cell 0.\n\nDefinition m := bimport [[ \"malloc\"!\"malloc\" @ [mallocS], \"malloc\"!\"free\" @ [freeS] ]]\n  bmodule \"SimpleCell\" {{\n    bfunction \"new\"(\"extra_stack\", \"x\") [newS]\n      \"x\" <-- Call \"malloc\"!\"malloc\"(0, 2)\n      [PRE[_, R] R =?> 2 * [| R <> 0 |] * [| freeable R 2 |] * mallocHeap 0\n       POST[R'] cell 0 R' * mallocHeap 0];;\n\n      \"x\" *<- 0;;\n      Return \"x\"\n    end\n\n    with bfunction \"delete\"(\"extra_stack\", \"self\") [deleteS]\n      Call \"malloc\"!\"free\"(0, \"self\", 2)\n      [PRE[_] Emp\n       POST[_] Emp];;\n\n      Return 0\n    end\n\n    with bfunction \"read\"(\"extra_stack\", \"self\") [readS]\n      \"self\" <-* \"self\";;\n      Return \"self\"\n    end\n\n    with bfunction \"write\"(\"extra_stack\", \"self\", \"n\") [writeS]\n      \"self\" *<- \"n\";;\n      Return 0\n    end\n  }}.\n\nLocal Hint Extern 1 (@eq W _ _) => words.\n\nTheorem ok : moduleOk m.\n  vcgen; abstract (sep hints; eauto).\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/Cito/examples/SimpleCell.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2521779748096991}}
{"text": "Require Import Coq.Strings.String Coq.Strings.Ascii Coq.Lists.List.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Common.List.Operations.\nRequire Import Fiat.Common.Equality.\nRequire Import Fiat.Common.Gensym.\n\nGlobal Arguments nat_of_ascii !_ / .\nGlobal Arguments Compare_dec.leb !_ !_ / .\nGlobal Arguments BinPos.Pos.to_nat !_ / .\n\nDelimit Scope item_scope with item.\nBind Scope item_scope with item.\nDelimit Scope production_scope with production.\nDelimit Scope production_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 : 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\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 {_} _ _.\nGlobal Arguments nat_of_ascii !_ / .\nGlobal Arguments Compare_dec.leb !_ !_ / .\nGlobal Arguments BinPos.Pos.to_nat !_ / .\n\n(** Variant of [nat_of_ascii] that will extract more cleanly, because\n    it doesn't depend on various other constants (only inductives) *)\n(** Keep this outside the module so it doesn't get extracted. *)\nDefinition nat_of_ascii_sig ch : { n : nat | n = nat_of_ascii ch }.\nProof.\n  unfold nat_of_ascii.\n  unfold N_of_ascii, N_of_digits.\n  eexists.\n  refine (_ : (let (a0, a1, a2, a3, a4, a5, a6, a7) := ch in _) = _).\n  destruct ch as [a0 a1 a2 a3 a4 a5 a6 a7].\n  repeat rewrite ?Nnat.N2Nat.inj_add, ?Nnat.N2Nat.inj_mul.\n  repeat match goal with\n           | [ |- context[BinNat.N.to_nat (if ?b then ?x else ?y)] ]\n             => replace (BinNat.N.to_nat (if b then x else y))\n                with (if b then BinNat.N.to_nat x else BinNat.N.to_nat y)\n               by (destruct b; reflexivity)\n         end.\n  simpl @BinNat.N.to_nat.\n  rewrite Mult.mult_0_r, Plus.plus_0_r.\n  reflexivity.\nDefined.\n\nModule opt.\n  Definition nat_of_ascii ch\n    := Eval cbv beta iota zeta delta [proj1_sig nat_of_ascii_sig] in\n        proj1_sig (nat_of_ascii_sig ch).\nEnd opt.\n\nGlobal Arguments opt.nat_of_ascii !_ / .\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/PreNotations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2521779748096991}}
{"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 multicopy_lsm multicopy_lsm_util.\n\nSection multicopy_lsm_upsert.\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  Lemma upsert_spec N γ_te γ_he γ_s Prot γ_I γ_J γ_f γ_gh r (k: K) (v: V) :\n    ⊢ ⌜k ∈ KS⌝ -∗ \n        (ghost_update_protocol N γ_te γ_he Prot k) -∗ \n        mcs_inv N γ_te γ_he γ_s Prot \n          (Inv_LSM γ_s γ_I γ_J γ_f γ_gh r) -∗\n            <<< ∀ t H, MCS γ_te γ_he t H >>> \n                   upsert r #k #v @ ⊤ ∖ (↑(mcsN N))\n            <<< MCS γ_te γ_he (t + 1) (H ∪ {[(k, (v, t))]}), RET #() >>>.\n  Proof.\n    iIntros \"%\". iLöb as \"IH\".\n    rename H into k_in_KS.    \n    iIntros \"Ghost_updP #HInv\" (Φ) \"AU\". wp_lam. wp_pures.\n    iApply fupd_wp. \n    (** Open invariant to establish root node in footprint **)\n    iInv \"HInv\" as (t0 H0)\"(mcs_high & >Inv_LSM)\".\n    iDestruct \"Inv_LSM\" as (hγ0 I0 J0)\"(Hglob & Hstar)\".\n    iDestruct \"Hglob\" as \"(HI & Out_I & HR \n            & Out_J & Inf_J & Hf & Hγ & #FP_r & domm_IR & domm_Iγ)\".\n    iModIntro. iSplitR \"AU Ghost_updP\". iNext. \n    iExists t0, H0. iFrame \"mcs_high\". \n    iExists hγ0, I0, J0. iFrame \"∗ #\". iModIntro.\n    (** Lock the node r **)\n    awp_apply lockNode_spec_high without \"Ghost_updP\"; try done.\n    iAaccIntro with \"\"; try eauto with iFrame. \n    iIntros (Cr Qr)\"HnP_n\". iModIntro. \n    iIntros \"Ghost_updP\". wp_pures.\n    iDestruct \"HnP_n\" as (γ_er γ_cr γ_qr γ_cirr es Vr Tr)\n                      \"(node_r & #HnP_gh & HnP_frac & HnP_C & HnP_cts)\".\n    wp_apply (addContents_spec with \"[$node_r]\"); try done.\n    iIntros (b Vr')\"(node_r & Hif)\".\n    (** Case analysis on whether addContents is successful **)\n    destruct b; last first.\n    - (** Case : addContents fails. Unlock root node and apply \n                 inductive hypothesis IH **) \n      iDestruct \"Hif\" as %HVr. replace Vr'. wp_pures.\n      awp_apply (unlockNode_spec_high \n          with \"[] [] [HnP_gh HnP_frac HnP_C HnP_cts node_r]\") \n            without \"Ghost_updP\" ; try done.\n      { iExists γ_er, γ_cr, γ_qr, γ_cirr, es, Vr, Tr.\n        iFrame \"∗#\". }\n      iAaccIntro with \"\"; try eauto with iFrame.\n      iIntros \"_\". iModIntro.\n      iIntros \"Ghost_updP\". wp_pures.\n      iApply (\"IH\" with \"Ghost_updP\"); try done.\n    - (** Case : addContent successful **)\n      (** Linearization Point: open invariant and update the resources **)\n      wp_pures. \n      \n      (* Need to unfold unlockNode here in order to apply \n         ghost_udpate_protocol, which requires stripping off\n         a later modality. This requires a physical step in heapLang,\n         which is available by unfolding the unlockNode *)\n\n      unfold unlockNode.\n      wp_pures. wp_bind(getLockLoc _)%E.\n      wp_apply getLockLoc_spec; first done.\n      iIntros (l) \"%\"; subst l; wp_pures.\n\n      iInv \"HInv\" as (t1 H1)\"(mcs_high & >Inv_LSM)\".\n      iDestruct \"Inv_LSM\" as (hγ1 I1 J1)\"(Hglob & Hstar)\".\n      iDestruct \"mcs_high\" as \"(>MCS_auth & >HH & >HInit & >HClock & >HUniq & Prot)\".\n      iDestruct \"Hglob\" as \"(HI & Out_I & HR \n            & Out_J & Inf_J & Hf & Hγ & _ & domm_IR & domm_Iγ)\".\n      iDestruct \"Hif\" as %HVr'.\n      \n      set (Tr' := <[k := t1]> Tr).\n      set (Cr' := <[k := (v, t1)]> Cr).\n      set (H1' := H1 ∪ {[(k, (v, t1))]}).\n      \n      iPoseProof ((auth_own_incl γ_s H1 _) with \"[$HH $HnP_C]\") as \"%\".\n      rename H into Cr_sub_H1. apply gset_included in Cr_sub_H1.\n      iDestruct \"HClock\" as %HClock_H1.\n      (** Re-establish maxTS for updated T and H **)\n      assert (HClock (t1 + 1) H1') as HClock_H1'.\n      { subst H1'. intros k' v' t' H'.\n        assert (((k', (v', t')) ∈ H1) ∨ (k' = k ∧ v' = v ∧ t' = t1)) \n              as Hor by set_solver.\n        destruct Hor as [Hor | Hor]. \n        pose proof HClock_H1 k' v' t' Hor as Hres. lia.\n        destruct Hor as [_ [_ Hor]]. replace t'. lia. }       \n      iAssert (⌜set_of_map Cr' ⊆ H1'⌝)%I as %Cr'_sub_H1'.\n      { subst H1'. iPureIntro. subst Cr'.\n        pose proof (set_of_map_insert_subseteq Cr k v t1) as H'.\n        assert (set_of_map Cr = set_of_map Cr) as H'' by done. \n        set_solver. }\n      (** Update the (● H) resource **)  \n      iMod (own_update γ_s (● H1) (● H1') \n          with \"[$HH]\") as \"HH\".\n      { apply (auth_update_auth _ _ H1').\n        apply gset_local_update. set_solver. }\n      iMod (own_update γ_s (● H1') \n             (● H1' ⋅ ◯ (set_of_map Cr')) \n              with \"[$HH]\") as \"HH\".\n      { subst H1'.\n        apply (auth_update_alloc _ (H1 ∪ {[(k, (v, t1))]}) (set_of_map Cr')).\n        apply local_update_discrete. intros m Valid_H1 H1_eq.\n        split; try done. rewrite /(ε ⋅? m) in H1_eq.\n        destruct m. rewrite gset_op in H1_eq. \n        rewrite left_id in H1_eq *; intros H1_eq.\n        rewrite <-H1_eq. \n        rewrite /(set_of_map Cr' ⋅? Some (H1 ∪ {[k, (v, t1)]})).\n        rewrite gset_op.\n        rewrite /(ε) in H1_eq. unfold ucmra_unit in H1_eq.\n        simpl in H1_eq.\n        assert ((k, (v, t1)) ∈ set_of_map Cr') as H'.\n        { subst Cr'. apply set_of_map_member.\n          apply lookup_insert. } \n        clear - H' Cr_sub_H1 Cr'_sub_H1'. set_solver.\n        exfalso. clear -H1_eq. set_solver. }\n      (** Re-establish HInit **)   \n      iAssert (⌜HInit H1'⌝)%I with \"[HInit]\" as \"HInit\".\n      { subst H1'. iDestruct \"HInit\" as %HInit.\n        unfold multicopy.HInit. iPureIntro.\n        clear -HInit k_in_KS. intros k' Hk'.\n        pose proof HInit k' Hk' as H'. set_solver. }  \n      iDestruct \"HnP_C\" as \"_\".  \n      iDestruct \"HH\" as \"(HH & HnP_C)\".   \n      iAssert (⌜r ∈ domm I1⌝)%I as %r_in_I.\n      { by iPoseProof (inFP_domm _ _ _ with \"[$FP_r] [$Hf]\") as \"H'\". }\n      rewrite (big_sepS_delete _ (domm I1) r); last by eauto.\n      iDestruct \"Hstar\" as \"(H_r & Hstar')\".\n      iDestruct \"H_r\" as (br Cr'' Qr'')\"(Hl_r & HnS_r)\".\n      iPoseProof (nodePred_lockR_true with \"[$node_r] [$Hl_r]\")\n         as \"%\". subst br.\n      iDestruct \"HnS_r\" as (γ_er' γ_cr' γ_qr' γ_cirr' es' Tr'' Br Ir Jr) \"HnS_r'\".\n      iPoseProof (nodePred_nodeShared_eq with \"[$HnP_gh] [$HnP_frac] [$HnS_r']\")\n           as \"(HnP_frac & HnS_r' &%&%&%)\". subst es' Tr'' Qr''.   \n      iDestruct \"HnS_r'\" as \"(HnS_gh & HnS_frac & HnS_si & HnS_FP \n                            & HnS_cl & HnS_oc & HnS_Bn & HnS_H & HnS_star & Hφ)\".\n\n\n      (** Update contents-in-reach of r **)\n      set (Br' := <[k := t1]>Br).\n      assert (Br' = <[k := t1]>Br) as HBr'. try done.\n      iEval (rewrite decide_True) in \"HnS_H\".\n      iDestruct \"HnS_H\" as \"(% & %)\". \n      rename H into Br_eq_H1. rename H2 into Infz_Ir.\n\n      iAssert (⌜contents_in_reach Br' Tr' Qr⌝)%I with \"[HnS_Bn]\" as \"HnS_Bn\".\n      { iDestruct \"HnS_Bn\" as %H'. iPureIntro. \n        intros k' t' HKS. destruct (decide (k' = k)).\n        - subst k'. subst Tr' Br'.\n          rewrite !lookup_insert.\n          split; try done.\n        - subst Tr' Br'. \n          rewrite !lookup_insert_ne; try done.\n          pose proof H' k' t' HKS; try done. }\n\n      \n      iAssert (⌜∀ k : K, Br' !!! k = (map_of_set H1' !!! k).2⌝)%I as %Br'_eq_H1'.\n      { iDestruct \"HUniq\" as %HUniq. \n        iPureIntro. subst Br' H1'. intros k'.\n        rewrite <-map_of_set_insert_eq; try done.\n        destruct (decide (k' = k)).\n        - subst k'. rewrite !lookup_total_insert; by simpl.\n        - rewrite !lookup_total_insert_ne; try done. }\n      iEval (rewrite (big_sepS_delete (_) (KS) k); last by eauto) in \"HnS_star\".\n      iDestruct \"HnS_star\" as \"(Hk & HnS_star')\".\n      iAssert (⌜Br !!! k ≤ t1⌝)%I as %Br_le_t1. \n      { iPureIntro. rewrite lookup_total_alt.\n        destruct (Br !! k) eqn: Hbrk; last first.\n        - rewrite Hbrk. simpl; clear; lia.\n        - rewrite Hbrk. simpl.\n          pose proof Br_eq_H1 k as Br_eq_H1. \n          (* rewrite Br_eq_H1 in Hbrk. *)\n          pose proof map_of_set_lookup_cases H1 k as H'.\n          destruct H' as [H' | [_ H']]; last first.\n          + rewrite !lookup_total_alt in Br_eq_H1.\n            rewrite H' Hbrk in Br_eq_H1. simpl in Br_eq_H1. \n            subst t; clear; lia.\n          + destruct H' as [v' [t' [H' [H'' H''']]]].\n            rewrite !lookup_total_alt in Br_eq_H1.\n            rewrite H''' Hbrk in Br_eq_H1. simpl in Br_eq_H1.\n            subst t'. \n            pose proof HClock_H1 k v' t H' as H''''.\n            clear -H''''; lia. }  \n      iMod (own_update (γ_cirr !!! k) (● (MaxNat (Br !!! k))) \n                (● (MaxNat (Br' !!! k))) with \"Hk\") as \"Hk\".\n      { apply (auth_update_auth _ _ (MaxNat (Br' !!! k))).\n        apply max_nat_local_update.\n        simpl. rewrite HBr'.\n        by rewrite lookup_total_insert. }        \n      iAssert ([∗ set] k0 ∈ KS, own (γ_cirr !!! k0) \n                  (● {| max_nat_car := Br' !!! k0 |}))%I \n          with \"[HnS_star' Hk]\" as \"HnS_star\".\n      { iEval (rewrite (big_sepS_delete (_) (KS) k); last by eauto).\n        iFrame \"Hk\".        \n        iApply (big_opS_proper \n             (λ y, own (γ_cirr !!! y) (● {| max_nat_car := Br' !!! y |}))\n             (λ y, own (γ_cirr !!! y) (● {| max_nat_car := Br !!! y |})) \n             (KS ∖ {[k]})).\n        intros x Hx. assert (x ≠ k) as H' by set_solver.\n        iFrame. iSplit. \n        iIntros \"H\". iEval (rewrite HBr') in \"H\".\n        assert (<[k := t1]> Br !!! x = Br !!! x) as H''. \n        { apply lookup_total_insert_ne; try done. } \n        by iEval (rewrite H'') in \"H\".       \n        iIntros \"H\". iEval (rewrite HBr').\n        assert (<[k:= t1]> Br !!! x = Br !!! x) as H''. \n        { apply lookup_total_insert_ne; try done. } \n        by iEval (rewrite H'').\n        done. }\n      iMod ((frac_update γ_er γ_cr γ_qr es Tr Qr es Tr' Qr) \n                  with \"[$HnP_frac $HnS_frac]\") as \"(HnP_frac & HnS_frac)\".\n      iDestruct \"Inf_J\" as %Inf_J.\n      iPoseProof ((auth_own_incl γ_J J1 Jr) with \"[HR HnS_si]\")\n                                    as (Ro) \"%\". \n      { unfold singleton_interfaces_ghost_state.\n        iDestruct \"HnS_si\" as \"(_ & H' & _)\". \n        iFrame. } rename H into Incl_J1.\n      iPoseProof (own_valid with \"HR\") as \"%\".\n      rename H into Valid_J1.\n      iAssert (⌜domm Jr = {[r]}⌝)%I as \"%\".\n      { by iDestruct \"HnS_si\" as \"(_&_&_&H')\". }\n      rename H into Domm_Jr.\n      iAssert (⌜φ1 es Qr⌝ ∗ ⌜φ2 r Br' Ir⌝ ∗ ⌜φ3 Br' Qr⌝ \n                ∗ ⌜φ4 r Br' Jr⌝ ∗ ⌜φ5 r Jr⌝ \n                ∗ ⌜φ6 r es Jr Qr⌝ ∗ ⌜φ7 r Ir⌝)%I\n            with \"[Hφ]\" as \"Hφ\".\n      { iDestruct \"Hφ\" as %Hφ. \n        destruct Hφ as [Hφ1 [Hφ2 [Hφ3 [Hφ4 [Hφ5 [Hφ6 Hφ7]]]]]].\n        iPureIntro. repeat split; try done.\n        - intros k' t' HKS Hins.\n          pose proof Infz_Ir r as Infz_Ir.\n          rewrite Infz_Ir in Hins.\n          exfalso. clear -Hins. set_solver.\n        - intros k' HKS. subst Br'. destruct (decide (k' = k)).\n          + subst k'. rewrite lookup_total_insert.\n            apply (Nat.le_trans _ (Br !!! k) _); try done.\n            apply Hφ3; try done.\n          + rewrite lookup_total_insert_ne; try done.\n            apply Hφ3; try done.\n        - intros k' HKS. right.\n          apply (inset_monotone J1 Jr Ro); try done.\n          by rewrite <-auth_auth_valid.\n          pose proof Inf_J r k' HKS as Inf_J.\n          by rewrite decide_True in Inf_J.\n          rewrite Domm_Jr. clear. set_solver. }\n            \n      iAssert (⌜HUnique H1'⌝)%I with \"[HUniq]\" as %HUniq.\n      { iDestruct \"HUniq\" as %HUniq.\n        iPureIntro. subst H1'.\n        intros k' t' v' v'' H' H''.\n        assert (((k', (v', t')) ∈ H1) ∨ (k' = k ∧ v' = v ∧ t' = t1)) \n              as Hor by set_solver.\n        assert (((k', (v'', t')) ∈ H1) ∨ (k' = k ∧ v'' = v ∧ t' = t1)) \n              as Hor' by set_solver.\n        destruct Hor as [Hor | Hor]. \n        - destruct Hor' as [Hor' | Hor'].\n          + apply (HUniq k' t' v' v'' Hor Hor'); try done.\n          + destruct Hor' as [? [? ?]]. subst k' v'' t'.\n            apply (HClock_H1 k v' t1) in Hor.\n            clear -Hor; lia.\n        - destruct Hor as [? [? ?]]. subst k' v' t'.\n          destruct Hor' as [Hor' | Hor'].\n          + apply (HClock_H1 k v'' t1) in Hor'.\n            clear -Hor'; lia.\n          + destruct Hor' as [? [? ?]]. by subst v''. }  \n          \n      iAssert (contents_proj Cr' Vr' Tr')%I with \"[HnP_cts]\" as \"HnP_cts\".\n      { iDestruct \"HnP_cts\" as \"(% & % & %)\".\n        rename H into dom_Cr_Vr; rename H2 into dom_Cr_Tr;\n        rename H3 into Cr_eq_Vr_Tr. \n        iPureIntro. subst Cr' Vr' Tr'. split; last split.\n        - apply leibniz_equiv. rewrite !dom_insert.\n          rewrite dom_Cr_Vr. clear; set_solver.\n        - apply leibniz_equiv. rewrite !dom_insert.\n          rewrite dom_Cr_Tr. clear; set_solver.\n        - intros k' v' t'. destruct (decide (k' = k)).\n          + subst k'. rewrite !lookup_insert. split.\n            * intros H'; by inversion H'.\n            * intros [H' H'']; inversion H'; by inversion H''.\n          + rewrite !lookup_insert_ne; try done. }\n\n      iDestruct \"Hl_r\" as \"(Hlockr & _)\". wp_store.\n        \n          \n            \n      (** Linearization **)    \n      iMod \"AU\" as (t' H1'')\"[MCS [_ Hclose]]\".\n      iAssert (⌜t' = t1 ∧ H1'' = H1⌝)%I as \"(% & %)\". \n      { iPoseProof (MCS_agree with \"[$MCS_auth] [$MCS]\") as \"(% & %)\".\n        by iPureIntro. } subst t' H1''. \n      iDestruct \"MCS\" as \"(MCS◯t & MCS◯h & _)\".\n      iDestruct \"MCS_auth\" as \"(MCS●t & MCS●h)\".\n      iMod ((auth_excl_update γ_te (t1+1) t1 t1) with \"MCS●t MCS◯t\") \n                                          as \"(MCS●t & MCS◯t)\".\n      iMod ((auth_excl_update γ_he (H1 ∪ {[(k, (v, t1))]}) H1 H1) with \"MCS●h MCS◯h\") \n                                          as \"(MCS●h & MCS◯h)\".\n      iCombine \"MCS◯t MCS◯h\" as \"(MCS_t & MCS_h)\".\n      iCombine \"MCS●t MCS●h\" as \"MCS_auth\".\n      iMod (\"Hclose\" with \"[MCS_t MCS_h]\") as \"HΦ\".\n      iFrame. by iPureIntro.\n      \n      (** Use ghost_update_protocol to update Prot(H) **)\n      iSpecialize (\"Ghost_updP\" $! v t1 H1).\n      \n\n      iMod (\"Ghost_updP\" with \"[] [$MCS_auth] [$Prot]\") \n                        as \"(Prot & MCS_auth)\". \n      { assert ((k, (v, t1)) ∈ H1') as H' by set_solver.\n        assert ((∀ (v' : V) (t' : nat), (k, (v', t')) ∈ H1' → t' ≤ t1))\n          as H''.\n        { intros v' t' Hvt'. subst H1'. \n          rewrite elem_of_union in Hvt'*; intros Hvt'.\n          destruct Hvt' as [Hvt' | Hvt'].\n          - apply HClock_H1 in Hvt'. clear -Hvt'; lia.\n          - assert (t' = t1) by (clear -Hvt'; set_solver).\n            subst t'; clear; lia. }  \n        pose proof map_of_set_lookup H1' k v t1 HUniq H' H'' as H'''.\n        iPureIntro. rewrite lookup_total_alt.\n        rewrite H'''. by simpl. }          \n      \n      \n      iModIntro. iFrame \"HΦ\". iNext.\n      iExists (t1+1), (H1 ∪ {[(k, (v, t1))]}).\n      \n      iSplitL \"MCS_auth Prot HInit HH\".\n      { iFrame \"∗\". iPureIntro. done. }\n      iExists hγ1, I1, J1. iFrame \"∗ %\".   \n      rewrite (big_sepS_delete _ (domm I1) r); last by eauto.\n      iSplitR \"Hstar'\"; last first.\n      { iApply (big_sepS_mono \n                (λ y, ∃ (bn : bool) (Cn : gmap K (V * T)) (Qn : gmap K T),\n                        lockR bn y (nodePred γ_gh γ_s r y Cn Qn)\n                      ∗ nodeShared γ_I γ_J γ_f γ_gh r y Qn H1)%I\n                (λ y, ∃ (bn : bool) (Cn : gmap K (V * T)) (Qn : gmap K T),\n                        lockR bn y (nodePred γ_gh γ_s r y Cn Qn)\n                      ∗ nodeShared γ_I γ_J γ_f γ_gh r y Qn (H1 ∪ {[k, (v, t1)]}))%I\n                (domm I1 ∖ {[r]})); try done.\n      intros y y_dom. assert (y ≠ r) as Hy by set_solver. iFrame.\n      iIntros \"Hstar\". iDestruct \"Hstar\" as (b C Q)\"(Hl & HnS)\".\n      iExists b, C, Q. iFrame. \n      iDestruct \"HnS\" as (γ_e γ_c γ_q γ_cir esy Ty By Iy Jy)\n                  \"(HnS_gh & domm_γcir & HnS_frac & HnS_si & HnS_FP \n                            & HnS_cl & HnS_oc & HnS_Bn & HnS_H & HnS_star \n                            & Hφ0 & Hφ2 & Hφ3 & Hφ4 & Hφ5 & Hφ7)\".\n      iExists γ_e, γ_c, γ_q, γ_cir, esy, Ty, By, Iy. iExists Jy. iFrame.\n      destruct (decide (y = r)); try done. } \n      { iExists false, Cr', Qr. \n        iSplitL \"node_r Hlockr HnP_C HnP_frac HnP_cts\".\n        iFrame. iExists γ_er, γ_cr, γ_qr, γ_cirr, es, Vr', Tr'. iFrame \"∗#\". \n        iExists γ_er, γ_cr, γ_qr, γ_cirr, es, Tr', Br', Ir. iExists Jr.\n        iFrame \"∗#\". iEval (rewrite decide_True). \n        iFrame \"%∗\". }\n  Qed.                  \n\n\nEnd multicopy_lsm_upsert.\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/multicopy/multicopy_lsm_upsert.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.25211874779687266}}
{"text": "(** * Implementation of Section 4.8 *)\nRequire Import Rpos.\nRequire Import FOL_R.\nRequire Import RL.Utilities.riesz_logic_Nat_more.\nRequire Import riesz_logic_List_more.\nRequire Import RL.hmr.hmr.\nRequire Import RL.hmr.term.\nRequire Import RL.hmr.semantic.\nRequire Import RL.hmr.hseq.\nRequire Import RL.hmr.p_hseq.\nRequire Import RL.hmr.lambda_prop_tools.\nRequire Import RL.hmr.invertibility.\nRequire Import RL.hmr.can_elim.\nRequire Import RL.hmr.M_elim.\nRequire Import RL.hmr.tech_lemmas.\n\nRequire Import CMorphisms.\nRequire Import Lra.\nRequire Import Lia.\nRequire Import FunctionalExtensionality.\nRequire Import Program.\n\nRequire Import RL.OLlibs.List_more.\nRequire Import RL.OLlibs.List_Type.\nRequire Import RL.OLlibs.Permutation_Type.\nRequire Import RL.OLlibs.Permutation_Type_more.\nRequire Import RL.OLlibs.Permutation_Type_solve.\n\nImport EqNotations.\n\nLocal Open Scope R_scope.\n\n(** ** Lambda property *)\nLemma hmrr_fuse :\n  forall G T A r1 r2,\n    HMR_T_M (((r1, A) :: (r2 , A) :: T) :: G) ->\n    HMR_T_M (((plus_pos r1 r2, A) :: T) :: G).\nProof.\n  intros G T A r1 r2 pi.\n  apply hmrr_can_elim.\n  unfold HMR_full.\n  change hmr_frag_full with (hmr_frag_add_CAN hmr_frag_full).\n  apply hmrr_can_fuse.\n  apply HMR_le_frag with hmr_frag_T_M; try assumption.\n  repeat split.\nQed.\n\nLemma hmrr_unfuse :\n  forall G T A r1 r2,\n    HMR_T_M (((plus_pos r1 r2, A) :: T) :: G) ->\n    HMR_T_M (((r1, A) :: (r2 , A) :: T) :: G).\nProof.\n  intros G T A r1 r2 pi.\n  apply hmrr_can_elim.\n  unfold HMR_full.\n  change hmr_frag_full with (hmr_frag_add_CAN hmr_frag_full).\n  apply hmrr_can_unfuse.\n  apply HMR_le_frag with hmr_frag_T_M; try assumption.\n  repeat split.\nQed.\n\nLemma hmrr_unfuse_gen :\n  forall G T D r1 r2,\n    HMR_T_M ((hseq.seq_mul (plus_pos r1 r2) D ++ T) :: G) ->\n    HMR_T_M ((hseq.seq_mul r1 D ++ hseq.seq_mul r2 D ++ T) :: G).\nProof.\n  intros G T D r1 r2.\n  revert T; induction D; intros T pi; try assumption.\n  - destruct a as [a A]; simpl in *.\n    apply hmrr_ex_seq with ((time_pos r1 a, A) :: (time_pos r2 a, A) :: hseq.seq_mul r1 D ++ hseq.seq_mul r2 D ++ T); [ Permutation_Type_solve | ].\n    apply hmrr_unfuse.\n    replace (plus_pos (time_pos r1 a) (time_pos r2 a)) with (time_pos (plus_pos r1 r2) a) by (destruct r1; destruct r2; destruct a; apply Rpos_eq; simpl; nra).\n    apply hmrr_ex_seq with (hseq.seq_mul r1 D ++ hseq.seq_mul r2 D ++ (time_pos (plus_pos r1 r2) a, A) :: T) ; [ Permutation_Type_solve | ].\n    apply IHD.\n    eapply hmrr_ex_seq ; [ | apply pi].\n    Permutation_Type_solve.\nQed.\n\nLemma hmrr_fuse_gen :\n  forall G T D r1 r2,\n    HMR_T_M ((hseq.seq_mul r1 D ++ hseq.seq_mul r2 D ++ T) :: G) ->\n    HMR_T_M ((hseq.seq_mul (plus_pos r1 r2) D ++ T) :: G).\nProof.\n  intros G T D r1 r2.\n  revert T; induction D; intros T pi; try assumption.\n  - destruct a as [a A]; simpl in *.\n    replace (time_pos (plus_pos r1 r2) a) with (plus_pos (time_pos r1 a) (time_pos r2 a)) by (destruct r1; destruct r2; destruct a; apply Rpos_eq; simpl; nra).\n    apply hmrr_fuse.\n    apply hmrr_ex_seq with (hseq.seq_mul (plus_pos r1 r2) D ++ (time_pos r1 a, A) :: (time_pos r2 a, A) :: T) ; [ Permutation_Type_solve | ].\n    apply IHD.\n    eapply hmrr_ex_seq ; [ | apply pi].\n    Permutation_Type_solve.\nQed.\n\n(* begin hide *)\nLemma concat_with_coeff_mul_oadd_Rpos_list_fuse : forall G T H L1 L2,\n    length L1 = length L2 ->\n    HMR_T_M ((concat_with_coeff_mul G L1 ++ concat_with_coeff_mul G L2 ++ T) :: H) ->\n    HMR_T_M ((concat_with_coeff_mul G (oadd_Rpos_list L1 L2) ++ T) :: H).\nProof.\n  intros G T H L1; revert G T H; induction L1; intros G T H L2 Hlen pi; [ destruct L2; inversion Hlen; destruct G; apply pi | ].\n  destruct L2; inversion Hlen.\n  destruct G; [ apply pi | ].\n  destruct a; destruct o; simpl in *.\n  - rewrite<- app_assoc; apply hmrr_fuse_gen.\n    apply hmrr_ex_seq with (concat_with_coeff_mul G (oadd_Rpos_list L1 L2) ++ (hseq.seq_mul r s ++ hseq.seq_mul r0 s ++ T)) ; [ Permutation_Type_solve | ].\n    apply IHL1; try assumption.\n    eapply hmrr_ex_seq ; [ | apply pi].\n    Permutation_Type_solve.\n  - apply hmrr_ex_seq with (concat_with_coeff_mul G (oadd_Rpos_list L1 L2) ++ (hseq.seq_mul r s ++ T)) ; [ Permutation_Type_solve | ].\n    apply IHL1; try assumption.\n    eapply hmrr_ex_seq ; [ | apply pi].\n    Permutation_Type_solve.\n  - apply hmrr_ex_seq with (concat_with_coeff_mul G (oadd_Rpos_list L1 L2) ++ (hseq.seq_mul r s ++ T)) ; [ Permutation_Type_solve | ].\n    apply IHL1; try assumption.\n    eapply hmrr_ex_seq ; [ | apply pi].\n    Permutation_Type_solve.\n  - apply IHL1; try assumption.\nQed.\n(* end hide *)\n\nLemma lambda_prop :\n  forall G,\n    hseq_is_basic G ->\n    HMR_T_M G ->\n    { L &\n      prod (length L = length G)\n           ((Exists_inf (fun x => x <> None) L) *\n            (forall n, sum_weight_with_coeff n G L = 0) *\n            (0 <= sum_weight_with_coeff_one G L) *\n            (HMR_T_M ((concat_with_coeff_mul (only_diamond_hseq G) L) :: nil)))}.\nProof.\n  intros G Ha pi.\n  induction pi.\n  - split with ((Some One) :: 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 (None :: 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 ((oadd_Rpos o o0) :: L).\n    repeat split; auto.\n    + inversion Hex; subst.\n      * apply Exists_inf_cons_hd.\n        destruct o; [ | exfalso; apply H0; reflexivity].\n        destruct o0; intros H; inversion H.\n      * inversion X1; subst; auto.\n        apply Exists_inf_cons_hd.\n        destruct o; destruct o0; try (exfalso; apply H0; reflexivity); intro H; inversion H.\n    + intros n.\n      specialize (Hsum n).\n      destruct o; destruct o0; try destruct r; try destruct r0; simpl; simpl in Hsum; nra.\n    + destruct o; destruct o0; try destruct r; try destruct r0; simpl; simpl in Hone; nra.\n    + destruct o; destruct o0; simpl; simpl in Hind; try assumption.\n      apply hmrr_fuse_gen.\n      apply Hind.\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 (o :: o :: L).\n    repeat split; auto.\n    + simpl in *; rewrite Hlen; reflexivity.\n    + intro n.\n      specialize (Hsum n).\n      destruct o; auto.\n      simpl in *.\n      rewrite sum_weight_seq_var_app in Hsum.\n      rewrite sum_weight_seq_covar_app in Hsum.\n      nra.\n    + destruct o; auto.\n      simpl in *.\n      rewrite sum_weight_seq_one_app in Hone.\n      rewrite sum_weight_seq_coone_app in Hone.\n      nra.\n    + destruct o; try assumption.\n      simpl in *.\n      rewrite only_diamond_seq_app in Hind.\n      rewrite hseq.seq_mul_app in Hind.\n      rewrite app_assoc; apply Hind.\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 o.\n    2:{ split with (None :: 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 o.\n    2:{ split with (None :: L2).\n        repeat split; auto. }\n    split with ((Some (time_pos r r0)) :: oadd_Rpos_list (map (mul_Rpos_oRpos r0) L1) (map (mul_Rpos_oRpos r) L2)).\n    repeat split; auto.\n    + simpl in Hlen1, Hlen2; simpl.\n      rewrite oadd_Rpos_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      simpl.\n      rewrite sum_weight_seq_var_app; rewrite sum_weight_seq_covar_app.\n      rewrite sum_weight_with_coeff_oadd_Rpos_list ; [ | simpl in Hlen1, Hlen2; simpl; rewrite 2 map_length; lia].\n      rewrite 2 sum_weight_with_coeff_omul_Rpos_list.\n      destruct r; destruct r0; simpl in *; nra.\n    + simpl; simpl in Hone1, Hone2.\n      rewrite sum_weight_seq_one_app; rewrite sum_weight_seq_coone_app.\n      rewrite sum_weight_with_coeff_one_oadd_Rpos_list ; [ | simpl in Hlen1, Hlen2; simpl; rewrite 2 map_length; lia].\n      rewrite 2 sum_weight_with_coeff_one_omul_Rpos_list.\n      destruct r as [r Hr]; destruct r0 as [r0 Hr0]; simpl in *.\n      clear - Hr Hr0 Hone1 Hone2.\n      apply R_blt_lt in Hr; apply R_blt_lt in Hr0.\n      nra.\n    + simpl in Hind1, Hind2 |- *.\n      rewrite only_diamond_seq_app; rewrite hseq.seq_mul_app.\n      rewrite <- (seq_mul_twice (only_diamond_seq T2)).\n      replace (time_pos r r0) with (time_pos r0 r) by (destruct r0; destruct r; apply Rpos_eq; simpl; nra).\n      rewrite <- seq_mul_twice.\n      apply hmrr_ex_seq with ((concat_with_coeff_mul (only_diamond_hseq G) (oadd_Rpos_list (map (mul_Rpos_oRpos r0) L1) (map (mul_Rpos_oRpos r) L2))) ++ (hseq.seq_mul r0 (hseq.seq_mul r (only_diamond_seq T1)) ++ hseq.seq_mul r (hseq.seq_mul r0 (only_diamond_seq T2)))) ; [ Permutation_Type_solve | ].\n      apply concat_with_coeff_mul_oadd_Rpos_list_fuse ; [ simpl in Hlen1, Hlen2; simpl; rewrite 2 map_length; lia | ].\n      rewrite 2 concat_with_coeff_mul_omul_Rpos_list.\n      apply hmrr_ex_seq with (hseq.seq_mul r (hseq.seq_mul r0 (only_diamond_seq T2) ++ (concat_with_coeff_mul (only_diamond_hseq G) L2)) ++ hseq.seq_mul r0 (hseq.seq_mul r (only_diamond_seq T1) ++ (concat_with_coeff_mul (only_diamond_hseq G) L1))) ; [ rewrite ? hseq.seq_mul_app; Permutation_Type_solve | ].\n      apply hmrr_M; [ reflexivity | | ];\n        eapply hmrr_T; try reflexivity;\n          rewrite hseq.seq_mul_twice; rewrite inv_pos_l; rewrite hseq.seq_mul_One; assumption.      \n  - inversion Ha; subst.\n    destruct IHpi as [L [Hlen [[[Hex Hsum] Hone] Hind]]].\n    { apply Forall_inf_cons; try assumption.\n      apply seq_basic_mul; apply X. }\n    destruct L; try now inversion Hlen.\n    destruct o.\n    2:{ split with (None :: L).\n        repeat split; auto. }\n    split with (Some (time_pos r0 r) :: L).\n    repeat split; auto.\n    + apply Exists_inf_cons_hd; intros H; inversion H.\n    + destruct r; destruct r0; simpl in *; intros n; specialize (Hsum n);rewrite sum_weight_seq_var_mul in Hsum; rewrite sum_weight_seq_covar_mul in Hsum; simpl in *.\n      nra.\n    + destruct r; destruct r0; simpl in *; rewrite sum_weight_seq_one_mul in Hone; rewrite sum_weight_seq_coone_mul in Hone.\n      simpl in *; nra.\n    + simpl in *.\n      rewrite<- hseq.seq_mul_twice; rewrite only_diamond_seq_mul.\n      apply Hind.\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        simpl in Hsum.\n        destruct o; 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 o; simpl in Hsum; auto.\n        nra.\n    + destruct L; try now inversion Hlen.\n      simpl in *; rewrite ? sum_weight_seq_app.\n      simpl in *; rewrite ? sum_weight_seq_one_app; rewrite ? sum_weight_seq_coone_app.\n      destruct o; auto.\n      rewrite ? sum_weight_seq_coone_vec_neq; try now (intros H; inversion H).\n      rewrite ? sum_weight_seq_one_vec_neq; try now (intros H; inversion H).\n      nra.\n    + unfold only_diamond_hseq; fold only_diamond_hseq.\n      rewrite 2 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 (oadd_Rpos o o0 :: L).\n    repeat split; auto.\n    + inversion Hex; subst.\n      * apply Exists_inf_cons_hd.\n        destruct o; destruct o0; try (exfalso; apply H0; reflexivity); intros H; inversion H.\n      * inversion X; subst; auto.\n        apply Exists_inf_cons_hd; \n          destruct o; destruct o0; try (exfalso; apply H0; reflexivity); intros H; inversion H.\n    + intros n.\n      simpl.\n      specialize (Hsum n).\n      destruct o; destruct o0; try destruct r; try destruct r0; simpl in *; nra.\n    + destruct o; destruct o0; try destruct r; try destruct r0; simpl in *; nra.\n    + destruct o; destruct o0; try apply Hind.\n      simpl in *.\n      apply hmrr_fuse_gen; 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  - destruct IHpi as [L [Hlen [[[Hex Hsum] Hone] Hind]]].\n    { inversion Ha; subst.\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 n; specialize (Hsum n).\n      destruct L; try now inversion Hlen.\n      destruct o; simpl in *; auto.\n      rewrite ? sum_weight_seq_var_app; rewrite ? sum_weight_seq_covar_app.\n      rewrite ? sum_weight_seq_var_vec_neq; try (intros H; now inversion H).\n      rewrite ? sum_weight_seq_covar_vec_neq; try (intros H; now inversion H).\n      nra.\n    + destruct L; try now inversion Hlen.\n      destruct o; simpl in *; auto.\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 (intros H; now inversion H).\n      rewrite ? sum_weight_seq_coone_vec_neq; try (intros H; now inversion H).\n      apply (Rmult_le_compat_l (projT1 r1)) in r0.\n      2:{ destruct r1 as [r1 Hr1]; simpl.\n          clear - Hr1; apply R_blt_lt in Hr1.\n          nra. }\n      nra.\n    + destruct L; try now inversion Hlen.\n      destruct o; simpl in *; auto.\n      rewrite 2 only_diamond_seq_app; rewrite 2 hseq.seq_mul_app.\n      rewrite only_diamond_seq_vec_one; rewrite only_diamond_seq_vec_coone.\n      rewrite 2 hseq.seq_mul_vec_mul_vec.\n      rewrite<- ? app_assoc.\n      apply hmrr_one; try assumption.\n      rewrite 2 hseq.mul_vec_sum_vec.\n      clear - r0.\n      destruct r1 as [r1 Hr1]; simpl; apply R_blt_lt in Hr1; nra.\n  - split with (Some One :: nil).\n    repeat split; auto.\n    + apply Exists_inf_cons_hd; intros H; inversion H.\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 (intros H; now inversion H).\n      rewrite ? sum_weight_seq_covar_vec_neq; try (intros H; now inversion H).\n      rewrite sum_weight_seq_var_seq_diamond; rewrite sum_weight_seq_covar_seq_diamond; 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 (intros H; now inversion H).\n      rewrite ? sum_weight_seq_coone_vec_neq; try (intros H; now inversion H).\n      rewrite sum_weight_seq_one_seq_diamond; rewrite sum_weight_seq_coone_seq_diamond; nra.\n    + simpl.\n      rewrite hseq.seq_mul_One.\n      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      rewrite app_nil_r; 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 n; specialize (Hsum n).\n      destruct o; simpl in *; auto.\n      rewrite <- (sum_weight_seq_var_perm _ _ _ p); rewrite <- (sum_weight_seq_covar_perm _ _ _ p); apply Hsum.\n    + destruct o; simpl in *; auto.\n      rewrite <- (sum_weight_seq_one_perm _ _ p); rewrite <- (sum_weight_seq_coone_perm _ _ p); apply Hone.\n    + destruct o; simpl in *; auto.\n      eapply hmrr_ex_seq; [ | apply Hind].\n      apply Permutation_Type_app; try reflexivity.\n      apply hseq.seq_mul_perm.\n      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 G H L p Hlen) as [L' [Hperm' [[Hsum' Hone'] Hperm'']]].\n    split with L'.\n    repeat split.\n    + apply Permutation_Type_length in p.\n      apply Permutation_Type_length in Hperm'.\n      etransitivity ; [ | apply p].\n      etransitivity ; [ | apply Hlen].\n      symmetry; apply Hperm'.\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 Hind].\n      apply Hperm''.\n  - inversion f.\nQed.\n\nLemma 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 <> None) L) *\n            (forall n, sum_weight_with_coeff n G L = 0) *\n            (0 <= sum_weight_with_coeff_one G L) *\n            (HMR_T_M ((concat_with_coeff_mul (only_diamond_hseq G) L) :: nil)))} ->\n    HMR_T_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 <> None) L) *\n                     (forall n, (sum_weight_var n H - sum_weight_covar n H) + sum_weight_with_coeff n G L = 0) *\n                     (0 <= (sum_weight_one H - sum_weight_coone H) + sum_weight_with_coeff_one G L) *\n                     (HMR_T_M ((flat_map only_diamond_seq H ++ concat_with_coeff_mul (only_diamond_hseq G) L) :: nil)))} + HMR_T_M H ->\n             HMR_T_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; simpl; specialize (Hsum n); nra.\n      + simpl; 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 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    destruct r ; [ | exfalso; apply Hp; reflexivity].\n    apply hmrr_T with r; try reflexivity.\n    change (hseq.seq_mul r T :: H ++ G')\n      with\n        ((hseq.seq_mul r T :: H) ++ G').\n    assert (hseq_is_basic (T :: G')) as HatG'.\n    { apply Forall_inf_Permutation_Type with G; try assumption. }\n    apply IHn.\n    + apply Permutation_Type_length in HpermG.\n      rewrite HpermG in Heqn; simpl in Heqn; inversion Heqn; auto.\n    + inversion HatG'; auto.\n    + apply Forall_inf_cons; auto.\n      apply seq_basic_mul; now inversion HatG'.\n    + destruct (Forall_inf_Exists_inf_dec (fun x : option Rpos => x = None)) with (La ++ Lb).\n      { intros x.\n        destruct x ; [ right; intros H'; inversion H' | left; reflexivity]. }\n      * right.\n        apply basic_proof_all_eq.\n        -- apply seq_basic_mul.\n           apply hseq_basic_perm with _ (T :: G') in HatG; try assumption.\n           inversion HatG; assumption.\n        -- apply HatH.\n        -- intros n0.\n           specialize (Hsum' n0); specialize (Hsum n0).\n           simpl in *.\n           rewrite (sum_weight_with_coeff_all_0 _ (La ++ Lb)) in Hsum'; try assumption.\n           rewrite sum_weight_seq_var_mul; rewrite sum_weight_seq_covar_mul; simpl.\n           nra.\n        -- simpl in *.\n           rewrite (sum_weight_with_coeff_one_all_0 _ (La ++ Lb)) in Hone'; try assumption.\n           rewrite sum_weight_seq_one_mul; rewrite sum_weight_seq_coone_mul; simpl.\n           nra.\n        -- eapply hmrr_ex_seq ; [ | apply Hind].\n           rewrite HeqL.\n           simpl.\n           etransitivity ; [ apply Permutation_Type_app_swap | ].\n           apply Permutation_Type_app; [ | reflexivity].\n           rewrite concat_with_coeff_mul_only_diamond.\n           apply only_diamond_seq_perm.\n           rewrite HeqL in Hpc; etransitivity ; [ apply Hpc | ].\n           simpl.\n           rewrite concat_with_coeff_mul_all_0; try assumption.\n           rewrite app_nil_r; reflexivity.\n      * left; split with (La ++ Lb).\n        repeat split.\n        -- rewrite HeqL in Hlen.\n           rewrite ? app_length.\n           rewrite ? app_length in Hlen; simpl in Hlen.\n           lia.\n        -- apply e.\n        -- intros n0.\n           specialize (Hsum' n0); specialize (Hsum n0).\n           simpl in *.\n           rewrite sum_weight_seq_var_mul; rewrite sum_weight_seq_covar_mul; simpl.\n           nra.\n        -- simpl in *.\n           rewrite sum_weight_seq_one_mul; rewrite sum_weight_seq_coone_mul; simpl.\n           nra.\n        -- eapply hmrr_ex_seq ; [ | apply Hind].\n           rewrite HeqL.\n           simpl.\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 2 concat_with_coeff_mul_only_diamond.\n           rewrite <- only_diamond_seq_app.\n           apply only_diamond_seq_perm.\n           rewrite HeqL in Hpc; etransitivity ; [ apply Hpc | ].\n           simpl.\n           apply Permutation_Type_app_swap.\n  - eapply hmrr_ex_hseq; [ apply Permutation_Type_app_comm | ].\n    apply hmrr_W_gen.\n    apply pi.\nQed.\n\n(** ** Decidablity *)\n(* begin hide *)\n(* Preliminary work necessary for the decidability result *)\nFixpoint pos_indexes (L : list (option Rpos)) :=\n  match L with\n  | nil => nil\n  | (Some r :: L) => 0%nat :: map S (pos_indexes L)\n  | (None :: L) => map S (pos_indexes L)\n  end.\n\nLemma In_inf_pos_indexes:\n  forall i L,\n    In_inf i (pos_indexes L) ->\n    (i < length L)%nat.\nProof.\n  intros i L; revert i; induction L; intros i Hin; try now inversion Hin.\n  destruct a; simpl in Hin; try (inversion Hin; subst).\n  - simpl; lia.\n  - simpl; destruct i.\n    + exfalso; apply not_0_In_inf_map_S in X; apply X.\n    + apply In_inf_map_S_inv in X.\n      specialize (IHL i X).\n      lia.\n  - simpl; destruct i.\n    + exfalso; apply not_0_In_inf_map_S in Hin; apply Hin.\n    + apply In_inf_map_S_inv in Hin.\n      specialize (IHL i Hin).\n      lia.\nQed.\n\nLemma pos_indexes_nth : forall L i,\n    In_inf i (pos_indexes L) ->\n    {r & nth i L None = Some r}.\nProof.\n  induction L; intros i Hin; try now exfalso.\n  destruct a.\n  - destruct i.\n    + split with r; auto.\n    + simpl; apply IHL.\n      apply In_inf_map_S_inv.\n      inversion Hin; [ exfalso; inversion H | ].\n      apply X.\n  - destruct i.\n    + exfalso.\n      apply not_0_In_inf_map_S with (pos_indexes L).\n      apply Hin.\n    + apply IHL; apply In_inf_map_S_inv; apply Hin.\nQed.\n\nLemma pos_indexes_Forall_inf : forall L,\n    Forall_inf (fun n : nat => (n < length L)%nat) (pos_indexes L).\nProof.\n  induction L; [ apply Forall_inf_nil | ].\n  simpl.\n  destruct a.\n  - apply Forall_inf_cons.\n    + lia.\n    + apply Forall_inf_lt_map_S.\n      apply IHL.\n  - apply Forall_inf_lt_map_S; apply IHL.\nQed.\n\nLemma pos_indexes_not_In_inf : forall L i,\n    (i < length L)%nat ->\n    (In_inf i (pos_indexes L) -> False) ->\n    (nth i L None = None).\nProof.\n  induction L; intros i Hlen H; try now inversion Hlen.\n  simpl in H.\n  destruct a.\n  - destruct i; [ exfalso; apply H; left; lia | ].\n    simpl.\n    apply IHL; [ simpl in Hlen; lia | ].\n    intros Hin.\n    apply H.\n    right.\n    apply in_inf_map.\n    apply Hin.\n  - destruct i; [ auto | ].\n    simpl.\n    apply IHL; [simpl in Hlen; lia | ].\n    intros Hin.\n    apply H.\n    apply in_inf_map; apply Hin.\nQed.\n\nLemma pos_indexes_order : forall L,\n    forall i j : nat,\n      (j < length (pos_indexes L))%nat ->\n      (i < j)%nat -> (nth i (pos_indexes L) 0 < nth j (pos_indexes L) 0)%nat.\nProof.\n  induction L; intros i j Hlen Hlt ; [ now inversion Hlen | ].\n  simpl.\n  destruct a.\n  - simpl in Hlen.\n    destruct j; [inversion Hlt | ].\n    destruct i; simpl.\n    + rewrite nth_indep with _ _ j _ 1%nat ; [ | lia].\n      rewrite map_nth.\n      lia.\n    + rewrite nth_indep with _ _ _ _ 1%nat ; [ | lia].\n      rewrite nth_indep with _ _ j _ 1%nat ; [ | lia].\n      rewrite ? map_nth.\n      apply lt_n_S.\n      rewrite map_length in Hlen.\n      apply IHL; lia.\n  - simpl in Hlen.\n    rewrite nth_indep with _ _ _ _ 1%nat ; [ | lia].\n    rewrite nth_indep with _ _ j _ 1%nat ; [ | lia].\n    rewrite ? map_nth.\n    apply lt_n_S.\n    rewrite map_length in Hlen.\n    apply IHL; lia.\nQed.\n\nLemma pos_indexes_cond : forall L v,\n    (forall i j : nat,\n      (j < length v)%nat ->\n      (i < j)%nat -> (nth i v 0 < nth j v 0)%nat) ->\n    (forall i,\n        (i < length v)%nat ->\n        (nth i v 0 < length L)%nat) ->\n    (forall i,\n        In_inf i v ->\n        nth i L None <> None) ->\n    (forall i,\n        (i < length L)% nat ->\n        nth i L None <> None ->\n        In_inf i v) ->\n    v = pos_indexes L.\nProof.\n  induction L; intros v H1 H2 H3 H4.\n  - destruct v; auto.\n    exfalso.\n    apply (H3 n); [ left; auto |] .\n    destruct n; auto.\n  - destruct a.\n    + simpl.\n      destruct v.\n      { exfalso.\n        apply in_inf_nil with _ 0%nat.\n        apply H4; simpl; try lia.\n        intros H; inversion H. }\n      destruct n.\n      2:{ exfalso.\n          apply (all_neq_not_In_inf (S n :: v) 0%nat).\n          - apply forall_Forall_inf.\n            intros x Hin.\n            apply not_eq_sym.\n            apply Nat.lt_neq.\n            apply In_inf_nth with _ _ _ 0%nat in Hin as [j Hlenj Heqj].\n            rewrite <- Heqj.\n            destruct j; try (simpl; lia).\n            apply Nat.lt_trans with (S n); try lia.\n            change (S n) with (nth 0%nat (S n :: v) 0%nat) at 1.\n            apply H1; simpl in *; try lia.\n          - apply H4; simpl in *; try lia.\n            intros H; inversion H. }\n      destruct all_neq_0_map_S with v.\n      * apply forall_Forall_inf.\n        intros x Hin.\n        apply not_eq_sym.\n        apply Nat.lt_neq.\n        apply In_inf_nth with _ _ _ 0%nat in Hin as [j Hlenj Heqj].\n        rewrite <- Heqj.\n        change (nth j v 0)%nat with (nth (S j) (0 :: v) 0)%nat.\n        change 0%nat with (nth 0 (0 :: v) 0)%nat.\n        apply H1; simpl in *; lia.\n      * rewrite e.\n        rewrite (IHL x); auto.\n        -- intros i j Hltj Hltij.\n           apply lt_S_n.\n           rewrite <- map_nth.\n           rewrite <- (map_nth _ _ _ j).\n           rewrite nth_indep with _ _ _ _ 0%nat ; [ | rewrite map_length; lia].\n           rewrite nth_indep with _ _ j _ 0%nat ; [ | rewrite map_length; lia].\n           rewrite <- e.\n           change (nth i v 0)%nat with (nth (S i) (0 :: v) 0)%nat.\n           change (nth j v 0)%nat with (nth (S j) (0 :: v) 0)%nat.\n           rewrite <- (map_length S) in Hltj.\n           rewrite <- e in Hltj.\n           apply H1; simpl in *; try lia.\n        -- intros i Hlti.\n           apply lt_S_n.\n           rewrite <- map_nth.\n           rewrite nth_indep with _ _ _ _ 0%nat ; [ | rewrite map_length; lia].\n           rewrite <- e.\n           change (nth i v 0)%nat with (nth (S i) (0 :: v) 0)%nat.\n           rewrite <- (map_length S) in Hlti.\n           rewrite <- e in Hlti.\n           apply H2; simpl in *; try lia.\n        -- intros i Hin.\n           apply In_inf_map_S in Hin.\n           rewrite <- e in Hin.\n           change (nth i L None) with (nth (S i) (Some r :: L) None).\n           apply H3.\n           right; auto.\n        -- intros i Hlti Hneq.\n           change (nth i L None) with (nth (S i) (Some r :: L) None) in Hneq.\n           apply lt_n_S in Hlti.\n           specialize (H4 (S i) Hlti Hneq).\n           rewrite e in H4.\n           inversion H4; [ inversion H |].\n           apply In_inf_map_S_inv in X.\n           apply X.\n    + destruct all_neq_0_map_S with v.\n      * apply forall_Forall_inf.\n        intros x Hin.\n        apply not_eq_sym.\n        intros H.\n        subst.\n        specialize (H3 _ Hin); simpl in H3.\n        contradiction.\n      * simpl.\n        rewrite e.\n        rewrite (IHL x); auto.\n        -- intros i j Hltj Hltij.\n           apply lt_S_n.\n           rewrite <- map_nth.\n           rewrite <- (map_nth _ _ _ j).\n           rewrite nth_indep with _ _ _ _ 0%nat ; [ | rewrite map_length; lia].\n           rewrite nth_indep with _ _ j _ 0%nat ; [ | rewrite map_length; lia].\n           rewrite <- e.\n           change (nth i v 0)%nat with (nth (S i) (0 :: v) 0)%nat.\n           change (nth j v 0)%nat with (nth (S j) (0 :: v) 0)%nat.\n           rewrite <- (map_length S) in Hltj.\n           rewrite <- e in Hltj.\n           apply H1; simpl in *; try lia.\n        -- intros i Hlti.\n           apply lt_S_n.\n           rewrite <- map_nth.\n           rewrite nth_indep with _ _ _ _ 0%nat ; [ | rewrite map_length; lia].\n           rewrite <- e.\n           change (nth i v 0)%nat with (nth (S i) (0 :: v) 0)%nat.\n           rewrite <- (map_length S) in Hlti.\n           rewrite <- e in Hlti.\n           apply H2; simpl in *; try lia.\n        -- intros i Hin.\n           apply In_inf_map_S in Hin.\n           rewrite <- e in Hin.\n           change (nth i L None) with (nth (S i) (None :: L) None).\n           apply H3.\n           auto.\n        -- intros i Hlti Hneq.\n           change (nth i L None) with (nth (S i) (None :: L) None) in Hneq.\n           apply lt_n_S in Hlti.\n           specialize (H4 (S i) Hlti Hneq).\n           rewrite e in H4.\n           apply In_inf_map_S_inv in H4.\n           apply H4.\nQed.    \n\n(* get a real number x and convert |x| to oRpos *)\nDefinition R_to_oRpos x :=\n  match R_order_dec x with\n              | R_is_gt _ H => Some (existT (fun x => 0 <? x = true) x H)\n              | R_is_lt _ H => Some (existT (fun x => 0 <? x = true) (- x) H)\n              | R_is_null _ _ => None\n  end.\n\nDefinition eval_to_oRpos val f := R_to_oRpos (FOL_R_term_sem val f).\n\nDefinition oRpos_to_R (o : option Rpos) :=\n  match o with\n  | None => 0\n  | Some r => projT1 r\n  end.\n\nLemma R_to_oRpos_oRpos_to_R :\n  forall o,\n    R_to_oRpos (oRpos_to_R o) = o.\nProof.\n  destruct o; unfold R_to_oRpos; simpl;\n    [ | case (R_order_dec 0); intros e; simpl; try reflexivity; exfalso; apply R_blt_lt in e; lra].\n  destruct r as [r Hr]; simpl.\n  case (R_order_dec r); intros e;\n    try (replace e with Hr by (apply Eqdep_dec.UIP_dec; apply Bool.bool_dec); reflexivity);\n    exfalso; apply R_blt_lt in Hr; try apply R_blt_lt in e; lra.\nQed.\n\nLemma oRpos_to_R_to_Rpos : forall r (Hr : 0 <? projT1 r = true),\n    existT _ (oRpos_to_R (Some r)) Hr = r.\nProof.\n  intros [r Hr] H.\n  apply Rpos_eq; reflexivity.\nQed.\n\nLemma map_oRpos_to_R_all_pos:\n  forall L val i, Forall_inf (fun x => 0 <= FOL_R_term_sem (upd_val_vec val (seq i (length L)) (map oRpos_to_R L)) x) (map FOL_R_var (seq i (length L))).\nProof.\n  induction L; intros val i; [ apply Forall_inf_nil | ].\n  simpl.\n  apply Forall_inf_cons; [ | apply IHL].\n  rewrite FOL_R_term_sem_upd_val_vec_not_in.\n  2:{ apply not_In_inf_seq; lia. }\n  rewrite upd_val_eq.\n  clear.\n  destruct a; simpl; try (destruct r as [r Hr]; simpl; apply R_blt_lt in Hr); lra.\nQed.\n\nLemma eval_to_oRpos_eq :\n  forall val vr k,\n    map (eval_to_oRpos (upd_val_vec val (seq k (length vr)) vr)) (map FOL_R_var (seq k (length vr))) = map R_to_oRpos vr.\nProof.\n  intros val vr; revert val; induction vr; intros val k; auto.\n  simpl.\n  rewrite (IHvr _ (S k)).\n  unfold eval_to_oRpos.\n  rewrite FOL_R_term_sem_upd_val_vec_not_in.\n  2:{ apply not_In_inf_seq; lia. }\n  unfold upd_val.\n  rewrite Nat.eqb_refl.\n  reflexivity.\nQed.\n\nLemma eval_p_seq_upd_val_vec_nth :\n  forall val G L k,\n    length G = length L ->\n    (max_var_weight_p_hseq G < k)%nat ->\n    eval_p_sequent (upd_val_vec val (seq k (length L)) (map oRpos_to_R L)) (flat_map (fun i => seq_mul (FOL_R_var (k + i)) (nth i G nil)) (pos_indexes L)) = concat_with_coeff_mul (map (eval_p_sequent val) G) L.\nProof.\n  intros val G; revert val; induction G; intros val [ | o L] k Hlen Hlt; auto; try now inversion Hlen.\n  destruct o.\n  - simpl pos_indexes; simpl map.\n    rewrite (cons_is_app 0%nat); rewrite flat_map_app.\n    rewrite eval_p_sequent_app.\n    simpl (flat_map _ (0%nat :: nil)).\n    rewrite app_nil_r.\n    simpl upd_val_vec.\n    rewrite flat_map_concat_map.\n    rewrite map_map.\n    rewrite <- flat_map_concat_map.\n    replace (flat_map (fun x : nat => seq_mul (FOL_R_var (k + S x)) (nth (S x) (a :: G) nil)) (pos_indexes L)) with (flat_map (fun x : nat => seq_mul (FOL_R_var ((S k) + x)) (nth x G nil)) (pos_indexes L)).\n    2:{ apply flat_map_ext.\n        intros a'.\n        simpl.\n        replace (S (k + a')) with (k + S a')%nat by lia.\n        reflexivity. }\n    simpl in Hlt.\n    rewrite IHG; [ | simpl in Hlen; lia | lia].\n    simpl.\n    rewrite eval_p_sequent_upd_val_vec_lt.\n    2:{ apply forall_Forall_inf.\n        intros x Hin.\n        replace (k + 0)%nat with k by lia.\n        assert (k < x)%nat.\n        { apply In_inf_seq_le_start in Hin.\n          lia. }\n        destruct a; [ simpl; lia | ].\n        rewrite max_var_weight_p_seq_seq_mul; simpl max_var_FOL_R_term; try lia.\n        intros H'; inversion H'. }\n    rewrite eval_p_hseq_upd_val_lt; try lia.\n    replace (eval_p_sequent (upd_val val k (projT1 r)) (seq_mul (FOL_R_var (k + 0)) a))\n      with (hseq.seq_mul r (eval_p_sequent val a)); auto.\n    apply Nat.max_lub_lt_iff in Hlt as [Hlt _].\n    clear - Hlt.\n    revert Hlt; induction a; intros Hlt; auto.\n    destruct a as [a A].\n    simpl in *.\n    replace (k + 0)%nat with k by lia.\n    rewrite upd_val_eq.\n    rewrite upd_val_term_lt; try lia.\n    sem_is_pos_decomp val a;\n      assert {H & R_order_dec (projT1 r * FOL_R_term_sem val a) = H} as [H HeqH] by (split with (R_order_dec (projT1 r * FOL_R_term_sem val a)); reflexivity); destruct H as [H | H | H];\n        rewrite ? HeqH; revert H HeqH; intros era Hera ea Hea; auto;\n          try (exfalso;\n               clear - era ea;\n               destruct r as [r Hr]; simpl in *; apply R_blt_lt in Hr;\n               try (apply R_blt_lt in era);\n               try (apply R_blt_lt in ea);\n               nra);\n          simpl; try rewrite IHa; try lia;\n            try (replace (k + 0)%nat with k by lia); auto.\n    + replace (time_pos r (existT (fun x : R => (0 <? x) = true) (FOL_R_term_sem val a) ea))\n        with (existT (fun x : R => (0 <? x) = true) (projT1 r * FOL_R_term_sem val a) era); auto.\n      apply Rpos_eq; destruct r; simpl; lra.\n    + replace (time_pos r (existT (fun x : R => (0 <? x) = true) (- FOL_R_term_sem val a) ea))\n        with (existT (fun x : R => (0 <? x) = true) (- (projT1 r * FOL_R_term_sem val a)) era); auto.\n      apply Rpos_eq; destruct r; simpl; lra.\n  - simpl pos_indexes.\n    simpl concat_with_coeff_mul.\n    simpl upd_val_vec.\n    rewrite flat_map_concat_map.\n    rewrite map_map.\n    rewrite <- flat_map_concat_map.\n    replace (flat_map (fun x : nat => seq_mul (FOL_R_var (k + S x)) (nth (S x) (a :: G) nil)) (pos_indexes L)) with (flat_map (fun x : nat => seq_mul (FOL_R_var ((S k) + x)) (nth x G nil)) (pos_indexes L)).\n    2:{ apply flat_map_ext.\n        intros a'.\n        simpl.\n        replace (S (k + a')) with (k + S a')%nat by lia.\n        reflexivity. }\n    rewrite IHG; simpl in*; try lia.\n    rewrite eval_p_hseq_upd_val_lt; try lia.\n    reflexivity.    \nQed.\n\nFixpoint p_sum_weight_var_with_coeff n G L :=\n  match G, L with\n  | _, nil => FOL_R_cst 0\n  | nil, _ => FOL_R_cst 0\n  | T :: G , r :: L => (r *R sum_weight_p_seq_var n T) +R p_sum_weight_var_with_coeff n G L\n  end.\n\nLemma p_sum_weight_var_with_coeff_lt_max_var : forall n G L val,\n    (max_var_p_hseq G < n)%nat ->\n    FOL_R_term_sem val (p_sum_weight_var_with_coeff n G L) = 0.\nProof.\n  intros n; induction G; intros L val Hlt; destruct L; auto.\n  simpl in *.\n  simpl; try rewrite sum_weight_p_seq_var_lt_max_var; try lia;\n    rewrite IHG; try lia;\n      lra.\nQed.\n\nLemma p_sum_weight_var_with_coeff_app1 : forall n G1 G2 L,\n    (length L <= length G1)%nat ->\n    p_sum_weight_var_with_coeff n (G1 ++ G2) L = p_sum_weight_var_with_coeff n G1 L.\nProof.\n  intros n; induction G1; intros G2 L Hlen; destruct L; try (now inversion Hlen); [destruct G2 | ]; auto.\n  simpl; rewrite IHG1; auto.\n  simpl in Hlen; lia.\nQed.\n\nLemma p_sum_weight_var_with_coeff_app2 : forall val n G1 G2 L1 L2,\n    (length L1 = length G1) ->\n    FOL_R_pred_sem val (p_sum_weight_var_with_coeff n (G1 ++ G2) (L1 ++ L2) =R p_sum_weight_var_with_coeff n G1 L1 +R p_sum_weight_var_with_coeff n G2 L2).\nProof.\n  intros n; induction G1; intros G2 L1 L2 Hlen; destruct L1; try (now inversion Hlen); [destruct L2 ; destruct G2 | ]; simpl; try lra.\n  simpl in *; rewrite IHG1; auto.\n  lra.\nQed.\n\nLemma p_sum_weight_var_with_coeff_app3 : forall n G L1 L2,\n    (length G <= length L1)%nat ->\n    p_sum_weight_var_with_coeff n G (L1 ++ L2) = p_sum_weight_var_with_coeff n G L1.\nProof.\n  intros n; induction G; intros L1 L2 Hlen; destruct L1; try (now inversion Hlen); [now destruct L2 | ].\n  simpl; rewrite IHG; auto.\n  simpl in Hlen; lia.\nQed.\n\nFixpoint p_sum_weight_covar_with_coeff n G L :=\n  match G, L with\n  | _, nil => FOL_R_cst 0\n  | nil, _ => FOL_R_cst 0\n  | T :: G , r :: L => (r *R sum_weight_p_seq_covar n T) +R p_sum_weight_covar_with_coeff n G L\n  end.\n\nLemma p_sum_weight_covar_with_coeff_lt_max_covar : forall n G L val,\n    (max_var_p_hseq G < n)%nat ->\n    FOL_R_term_sem val (p_sum_weight_covar_with_coeff n G L) = 0.\nProof.\n  intros n; induction G; intros L val Hlt; destruct L; auto.\n  simpl in *.\n  simpl; try rewrite sum_weight_p_seq_covar_lt_max_var; try lia;\n    rewrite IHG; try lia;\n      lra.\nQed.\n\nLemma p_sum_weight_covar_with_coeff_app1 : forall n G1 G2 L,\n    (length L <= length G1)%nat ->\n    p_sum_weight_covar_with_coeff n (G1 ++ G2) L = p_sum_weight_covar_with_coeff n G1 L.\nProof.\n  intros n; induction G1; intros G2 L Hlen; destruct L; try (now inversion Hlen); [destruct G2 | ]; auto.\n  simpl; rewrite IHG1; auto.\n  simpl in Hlen; lia.\nQed.\n\nLemma p_sum_weight_covar_with_coeff_app2 : forall val n G1 G2 L1 L2,\n    (length L1 = length G1) ->\n    FOL_R_pred_sem val (p_sum_weight_covar_with_coeff n (G1 ++ G2) (L1 ++ L2) =R p_sum_weight_covar_with_coeff n G1 L1 +R p_sum_weight_covar_with_coeff n G2 L2).\nProof.\n  intros n; induction G1; intros G2 L1 L2 Hlen; destruct L1; try (now inversion Hlen); [destruct L2 ; destruct G2 | ]; simpl; try lra.\n  simpl in *; rewrite IHG1; auto.\n  lra.\nQed.\n\nLemma p_sum_weight_covar_with_coeff_app3 : forall n G L1 L2,\n    (length G <= length L1)%nat ->\n    p_sum_weight_covar_with_coeff n G (L1 ++ L2) = p_sum_weight_covar_with_coeff n G L1.\nProof.\n  intros n; induction G; intros L1 L2 Hlen; destruct L1; try (now inversion Hlen); [now destruct L2 | ].\n  simpl; rewrite IHG; auto.\n  simpl in Hlen; lia.\nQed.\n\nFixpoint p_sum_weight_one_with_coeff G L :=\n  match G, L with\n  | _, nil => FOL_R_cst 0\n  | nil, _ => FOL_R_cst 0\n  | T :: G , r :: L => (r *R sum_weight_p_seq_one T) +R p_sum_weight_one_with_coeff G L\n  end.\n\nLemma p_sum_weight_one_with_coeff_app1 : forall G1 G2 L,\n    (length L <= length G1)%nat ->\n    p_sum_weight_one_with_coeff (G1 ++ G2) L = p_sum_weight_one_with_coeff G1 L.\nProof.\n  induction G1; intros G2 L Hlen; destruct L; try (now inversion Hlen); [destruct G2 | ]; auto.\n  simpl; rewrite IHG1; auto.\n  simpl in Hlen; lia.\nQed.\n\nLemma p_sum_weight_one_with_coeff_app2 : forall val G1 G2 L1 L2,\n    (length L1 = length G1) ->\n    FOL_R_pred_sem val (p_sum_weight_one_with_coeff (G1 ++ G2) (L1 ++ L2) =R p_sum_weight_one_with_coeff G1 L1 +R p_sum_weight_one_with_coeff G2 L2).\nProof.\n  induction G1; intros G2 L1 L2 Hlen; destruct L1; try (now inversion Hlen); [destruct L2 ; destruct G2 | ]; simpl; try lra.\n  simpl in *; rewrite IHG1; auto.\n  lra.\nQed.\n\nLemma p_sum_weight_one_with_coeff_app3 : forall G L1 L2,\n    (length G <= length L1)%nat ->\n    p_sum_weight_one_with_coeff G (L1 ++ L2) = p_sum_weight_one_with_coeff G L1.\nProof.\n  induction G; intros L1 L2 Hlen; destruct L1; try (now inversion Hlen); [now destruct L2 | ].\n  simpl; rewrite IHG; auto.\n  simpl in Hlen; lia.\nQed.\n\nFixpoint p_sum_weight_coone_with_coeff G L :=\n  match G, L with\n  | _, nil => FOL_R_cst 0\n  | nil, _ => FOL_R_cst 0\n  | T :: G , r :: L => (r *R sum_weight_p_seq_coone T) +R p_sum_weight_coone_with_coeff G L\n  end.\n\nLemma p_sum_weight_coone_with_coeff_app1 : forall G1 G2 L,\n    (length L <= length G1)%nat ->\n    p_sum_weight_coone_with_coeff (G1 ++ G2) L = p_sum_weight_coone_with_coeff G1 L.\nProof.\n  induction G1; intros G2 L Hlen; destruct L; try (now inversion Hlen); [destruct G2 | ]; auto.\n  simpl; rewrite IHG1; auto.\n  simpl in Hlen; lia.\nQed.\n\nLemma p_sum_weight_coone_with_coeff_app2 : forall val G1 G2 L1 L2,\n    (length L1 = length G1) ->\n    FOL_R_pred_sem val (p_sum_weight_coone_with_coeff (G1 ++ G2) (L1 ++ L2) =R p_sum_weight_coone_with_coeff G1 L1 +R p_sum_weight_coone_with_coeff G2 L2).\nProof.\n  induction G1; intros G2 L1 L2 Hlen; destruct L1; try (now inversion Hlen); [destruct L2 ; destruct G2 | ]; simpl; try lra.\n  simpl in *; rewrite IHG1; auto.\n  lra.\nQed.\n\nLemma p_sum_weight_coone_with_coeff_app3 : forall G L1 L2,\n    (length G <= length L1)%nat ->\n    p_sum_weight_coone_with_coeff G (L1 ++ L2) = p_sum_weight_coone_with_coeff G L1.\nProof.\n  induction G; intros L1 L2 Hlen; destruct L1; try (now inversion Hlen); [now destruct L2 | ].\n  simpl; rewrite IHG; auto.\n  simpl in Hlen; lia.\nQed.\n\nLemma eval_to_oRpos_to_R_eq : forall L val i,\n    Forall_inf (fun x => 0 <= FOL_R_term_sem (upd_val_vec val (seq i (length L)) (map oRpos_to_R L)) x) (map FOL_R_var (seq i (length L))) ->\n    map (eval_to_oRpos (upd_val_vec val (seq i (length L)) (map oRpos_to_R L))) (map FOL_R_var (seq i (length L))) = L.\nProof.\n  induction L; intros val i Hall.\n  - reflexivity.\n  - inversion Hall; subst.\n    simpl.\n    rewrite IHL; auto.\n    unfold eval_to_oRpos.\n    rewrite FOL_R_term_sem_upd_val_vec_not_in.\n    2:{ apply not_In_inf_seq; lia. }\n    clear - H0.\n    simpl in H0.\n    rewrite upd_val_vec_not_in in H0.\n    2:{ apply not_In_inf_seq; lia. }\n    rewrite upd_val_eq in H0 |-*.\n    case_eq (R_order_dec (oRpos_to_R a));\n      intros e He;\n      [ | exfalso; clear - H0 e; apply R_blt_lt in e | ]; try lra.\n    + destruct a;\n        simpl in H0;\n        [ | exfalso; clear - e; apply R_blt_lt in e; simpl in e; lra].\n      rewrite R_to_oRpos_oRpos_to_R; reflexivity.\n    + rewrite R_to_oRpos_oRpos_to_R; reflexivity.\nQed.\n\nFixpoint p_concat_with_coeff_mul G L :=\n  match G, L with\n  | _, nil => nil\n  | nil, _ => nil\n  | T :: G , r :: L => seq_mul r T ++ p_concat_with_coeff_mul G L\n  end.\n\nLemma p_concat_with_coeff_mul_only_diamond : forall G L,\n    p_concat_with_coeff_mul (only_diamond_p_hseq G) L = only_diamond_p_seq (p_concat_with_coeff_mul G L).\nProof.\n  induction G; intros L; destruct L; auto.\n  simpl; rewrite IHG; auto.\n  rewrite only_diamond_p_seq_app.\n  rewrite only_diamond_p_seq_mul; reflexivity.\nQed.\n\nLemma FOL_R_term_sem_eval_p_sequent : forall val n T,\n    FOL_R_term_sem val (sum_weight_p_seq_var n T) - FOL_R_term_sem val (sum_weight_p_seq_covar n T) = sum_weight_seq_var n (eval_p_sequent val T) - sum_weight_seq_covar n (eval_p_sequent val T) .\nProof.\n  intros val n; induction T; simpl; try reflexivity.\n  destruct a as [a A].\n  sem_is_pos_decomp val a; intros e He; simpl;\n    destruct A; simpl; try case (n =? n0); simpl; try rewrite IHT; try lra.\nQed.\n\nLemma FOL_R_term_sem_eval_p_hseq : forall val n G L,\n    Forall_inf (fun x => 0 <= FOL_R_term_sem val x) L ->\n    FOL_R_term_sem val (p_sum_weight_var_with_coeff n G L) - FOL_R_term_sem val (p_sum_weight_covar_with_coeff n G L) = sum_weight_var_with_coeff n (map (eval_p_sequent val) G) (map (eval_to_oRpos val) L) - sum_weight_covar_with_coeff n (map (eval_p_sequent val) G) (map (eval_to_oRpos val) L).\nProof.\n  intros val n; induction G; intros L Hall; destruct Hall; simpl; try reflexivity.\n  specialize (IHG l Hall).\n  unfold eval_to_oRpos; unfold R_to_oRpos.\n  sem_is_pos_decomp val x; intros e' He'; simpl ; [ | exfalso; clear - r e'; apply R_blt_lt in e' |  ]; try lra.\n  - transitivity\n      (FOL_R_term_sem val x * (FOL_R_term_sem val (sum_weight_p_seq_var n a) - FOL_R_term_sem val (sum_weight_p_seq_covar n a)) +\n       (FOL_R_term_sem val (p_sum_weight_var_with_coeff n G l) - FOL_R_term_sem val (p_sum_weight_covar_with_coeff n G l))); try lra.\n    rewrite IHG; rewrite FOL_R_term_sem_eval_p_sequent.\n    unfold eval_to_oRpos; unfold R_to_oRpos.\n    lra.\n  - rewrite e'.\n    unfold eval_to_oRpos in IHG; unfold R_to_oRpos in IHG.\n    lra.\nQed.\n\nLemma FOL_R_term_sem_eval_p_sequent_one : forall val T,\n    FOL_R_term_sem val (sum_weight_p_seq_one T) - FOL_R_term_sem val (sum_weight_p_seq_coone T) = sum_weight_seq_one (eval_p_sequent val T) - sum_weight_seq_coone (eval_p_sequent val T) .\nProof.\n  intros val; induction T; simpl; try reflexivity.\n  destruct a as [a A].\n  sem_is_pos_decomp val a; intros e He; simpl;\n    destruct A;  simpl; try rewrite IHT; try lra.\nQed.\n\nLemma FOL_R_term_sem_eval_p_hseq_one : forall val G L,\n    Forall_inf (fun x => 0 <= FOL_R_term_sem val x) L ->\n    FOL_R_term_sem val (p_sum_weight_one_with_coeff G L) - FOL_R_term_sem val (p_sum_weight_coone_with_coeff G L) = sum_weight_one_with_coeff (map (eval_p_sequent val) G) (map (eval_to_oRpos val) L) - sum_weight_coone_with_coeff (map (eval_p_sequent val) G) (map (eval_to_oRpos val) L).\nProof.\n  intros val; induction G; intros L Hall; destruct Hall; simpl; try reflexivity.\n  specialize (IHG l Hall).\n  unfold eval_to_oRpos; unfold R_to_oRpos.\n  sem_is_pos_decomp val x; intros e' He'; simpl ; [ | exfalso; clear - r e'; apply R_blt_lt in e' |  ]; try lra.\n  - transitivity\n      (FOL_R_term_sem val x * (FOL_R_term_sem val (sum_weight_p_seq_one a) - FOL_R_term_sem val (sum_weight_p_seq_coone a)) +\n       (FOL_R_term_sem val (p_sum_weight_one_with_coeff G l) - FOL_R_term_sem val (p_sum_weight_coone_with_coeff G l))); try lra.\n    rewrite IHG; rewrite FOL_R_term_sem_eval_p_sequent_one.\n    unfold eval_to_oRpos; unfold R_to_oRpos.\n    lra.\n  - rewrite e'.\n    unfold eval_to_oRpos in IHG; unfold R_to_oRpos in IHG.\n    lra.\nQed.\n\nLemma FOL_R_term_sem_upd_val_vec_lt : forall val a vx vr,\n    Forall_inf (fun x => max_var_FOL_R_term a < x)%nat vx ->\n    FOL_R_term_sem (upd_val_vec val vx vr) a = FOL_R_term_sem val a.\nProof.\n  intros val; induction a; intros vx vr Hall.\n  - simpl.\n    apply upd_val_vec_not_in.\n    intros Hin.\n    apply (Forall_inf_forall Hall) in Hin.\n    simpl in Hin; lia.\n  - reflexivity.\n  - simpl; rewrite IHa1; [ rewrite IHa2 | ]; try reflexivity; refine (Forall_inf_arrow _ _ Hall);\n      intros a Hlt; simpl in Hlt; lia.\n  - simpl; rewrite IHa1; [ rewrite IHa2 | ]; try reflexivity; refine (Forall_inf_arrow _ _ Hall);\n      intros a Hlt; simpl in Hlt; lia.\nQed.\n\nLemma eval_p_hseq_upd_val_vec_lt : forall val G vx vr,\n    Forall_inf (fun x => max_var_weight_p_hseq G < x)%nat vx ->\n    map (eval_p_sequent (upd_val_vec val vx vr)) G = map (eval_p_sequent val) G.\nProof.\n  intros val; induction G; intros vx vr Hall; simpl; try reflexivity.\n  rewrite eval_p_sequent_upd_val_vec_lt ; [ | refine (Forall_inf_arrow _ _ Hall); intros a' Hlt'; simpl in Hlt'; lia].\n  rewrite IHG ; [ | refine (Forall_inf_arrow _ _ Hall); intros a' Hlt'; simpl in Hlt'; lia].\n  reflexivity.\nQed.\n\nLemma sum_weight_with_coeff_eval_eq : forall val n G L,\n    sum_weight_var_with_coeff n (map (eval_p_sequent val) G) L - sum_weight_covar_with_coeff n (map (eval_p_sequent val) G) L = FOL_R_term_sem (upd_val_vec val (seq (S (max_var_weight_p_hseq G)) (length L)) (map oRpos_to_R L)) (p_sum_weight_var_with_coeff n G (map FOL_R_var (seq (S (max_var_weight_p_hseq G)) (length L)))) - FOL_R_term_sem (upd_val_vec val (seq (S (max_var_weight_p_hseq G)) (length L)) (map oRpos_to_R L)) (p_sum_weight_covar_with_coeff n G (map FOL_R_var (seq (S (max_var_weight_p_hseq G)) (length L)))).\nProof.\n  intros val n G L.\n  rewrite FOL_R_term_sem_eval_p_hseq; auto.\n  2:{ apply map_oRpos_to_R_all_pos. }\n  rewrite eval_to_oRpos_to_R_eq.\n  2:{ apply map_oRpos_to_R_all_pos. }\n  rewrite eval_p_hseq_upd_val_vec_lt; try reflexivity.\n  apply forall_Forall_inf.\n  intros x Hin.\n  case_eq (max_var_weight_p_hseq G <? x)%nat; intros H; [ apply Nat.ltb_lt in H | apply Nat.ltb_nlt in H]; auto.\n  exfalso.\n  apply not_In_inf_seq with (S (max_var_weight_p_hseq G)) (length L) x; try lia.\n  apply Hin.\nQed.\n\nLemma sum_weight_with_coeff_one_eval_eq : forall val G L,\n    sum_weight_one_with_coeff (map (eval_p_sequent val) G) L - sum_weight_coone_with_coeff (map (eval_p_sequent val) G) L = FOL_R_term_sem (upd_val_vec val (seq (S (max_var_weight_p_hseq G)) (length L)) (map oRpos_to_R L)) (p_sum_weight_one_with_coeff G (map FOL_R_var (seq (S (max_var_weight_p_hseq G)) (length L)))) - FOL_R_term_sem (upd_val_vec val (seq (S (max_var_weight_p_hseq G)) (length L)) (map oRpos_to_R L)) (p_sum_weight_coone_with_coeff G (map FOL_R_var (seq (S (max_var_weight_p_hseq G)) (length L)))).\nProof.\n  intros val G L.\n  rewrite FOL_R_term_sem_eval_p_hseq_one; auto.\n  2:{ apply map_oRpos_to_R_all_pos. }\n  rewrite eval_to_oRpos_to_R_eq.\n  2:{ apply map_oRpos_to_R_all_pos. }\n  rewrite eval_p_hseq_upd_val_vec_lt; try reflexivity.\n  apply forall_Forall_inf.\n  intros x Hin.\n  case_eq (max_var_weight_p_hseq G <? x)%nat; intros H; [ apply Nat.ltb_lt in H | apply Nat.ltb_nlt in H]; auto.\n  exfalso.\n  apply not_In_inf_seq with (S (max_var_weight_p_hseq G)) (length L) x; try lia.\n  apply Hin.\nQed.\n\n(* Put non basic formula first, i.e., G in the form H | |- T, r.A with A non basic. *)\n\nFixpoint p_seq_fst_non_basic_term (T : p_sequent) : (FOL_R_term * term) :=\n  match T with\n  | nil => (FOL_R_cst 0, HMR_var 0)\n  | (a, A) :: T => if (0 <? HMR_complexity_term A)%nat\n                   then (a , A)\n                   else (p_seq_fst_non_basic_term T)\n  end.\n\nLemma p_seq_fst_non_basic_term_correct :\n  forall T,\n    (p_seq_is_basic T -> False) ->\n    (is_basic (snd (p_seq_fst_non_basic_term T)) -> False).\nProof.\n  induction T; intros Hnbs Hbt; [ apply Hnbs; apply Forall_inf_nil | ].\n  destruct a as [a A]; simpl in *.\n  case_eq (0 <? HMR_complexity_term A)%nat; intros H1; rewrite H1 in Hbt;\n    (apply Nat.ltb_lt in H1 + apply Nat.ltb_nlt in H1).\n  - apply is_basic_complexity_0 in Hbt.\n    simpl in Hbt.\n    lia.\n  - apply IHT; auto.\n    intros H2.\n    apply Hnbs.\n    apply Forall_inf_cons; auto.\n    apply is_basic_complexity_0_inv.\n    lia.\nQed.\n\nLemma p_seq_fst_non_basic_term_well_defined :\n  forall val T,\n    (0 < HMR_complexity_p_seq T)%nat ->\n    p_seq_well_defined val T ->\n    (0 <? FOL_R_term_sem val (fst (p_seq_fst_non_basic_term T))) = true.\nProof.\n  intros val; induction T; intros Hlt; [ simpl in Hlt; exfalso; try lia | ].\n  intros Hwd.\n  destruct a as [a A].\n  simpl.\n  case_eq (0 <? HMR_complexity_term A)%nat; intros H; auto; inversion Hwd; subst; auto.\n  apply IHT; auto.\n  apply Nat.ltb_nlt in H.\n  simpl in *.\n  lia.\nQed.  \n\nFixpoint p_seq_without_fst_non_basic_term (T : p_sequent) : p_sequent :=\n  match T with\n  | nil => nil\n  | (a, A) :: T => if (0 <? HMR_complexity_term A)%nat\n                   then T\n                   else (a , A) :: (p_seq_without_fst_non_basic_term T)\n  end.\n\nLemma p_seq_put_non_basic_fst : forall T,\n    (p_seq_is_basic T -> False) ->\n    Permutation_Type T (p_seq_fst_non_basic_term T :: p_seq_without_fst_non_basic_term T).\nProof.\n  induction T; intros Hnb; [ exfalso; apply Hnb; apply Forall_inf_nil | ].\n  destruct a as [a A]; simpl.\n  case_eq (0 <? HMR_complexity_term A)%nat; intros H1;\n    apply Nat.ltb_lt in H1 + apply Nat.ltb_nlt in H1; auto.\n  assert (p_seq_is_basic T -> False).\n  { intros H; apply Hnb; apply Forall_inf_cons; auto.\n    apply is_basic_complexity_0_inv.\n    lia. }\n  specialize (IHT H).\n  transitivity ((a , A) :: p_seq_fst_non_basic_term T :: p_seq_without_fst_non_basic_term T);\n    Permutation_Type_solve.\nQed.\n\nLemma p_seq_without_fst_non_basic_term_well_defined :\n  forall val T,\n    p_seq_well_defined val T ->\n    p_seq_well_defined val (p_seq_without_fst_non_basic_term T).\nProof.\n  intros val; induction T; intros Hwd; [apply Forall_inf_nil |].\n  destruct a as [a A]; inversion Hwd; subst.\n  simpl.\n  case_eq (0 <? HMR_complexity_term A)%nat; intros H; try apply Forall_inf_cons; try apply IHT; auto.\nQed.\n\nFixpoint p_hseq_p_seq_max_complexity (G : p_hypersequent) : p_sequent :=\n  match G with\n  | nil => nil\n  | T :: G => if (fst (HMR_complexity_p_hseq G) <=? HMR_complexity_p_seq T)\n              then T\n              else p_hseq_p_seq_max_complexity G\n  end.\n\nLemma p_hseq_p_seq_max_complexity_well_defined :\n  forall val G,\n    p_hseq_well_defined val G ->\n    p_seq_well_defined val (p_hseq_p_seq_max_complexity G).\nProof.\n  intros val; induction G; intros Hwd; [ apply Forall_inf_nil | ].\n  inversion Hwd; specialize (IHG X0); subst.\n  simpl; case (fst (HMR_complexity_p_hseq G) <=? HMR_complexity_p_seq a); auto.\nQed.\n\nLemma p_hseq_p_seq_max_complexity_correct :\n  forall G,\n    HMR_complexity_p_seq (p_hseq_p_seq_max_complexity G) = fst (HMR_complexity_p_hseq G).\nProof.\n  induction G; auto.\n  simpl.\n  case_eq (fst (HMR_complexity_p_hseq G) <=? HMR_complexity_p_seq a); intros H1;\n    case_eq (HMR_complexity_p_seq a =? fst (HMR_complexity_p_hseq G)); intros H2;\n      case_eq (HMR_complexity_p_seq a <? fst (HMR_complexity_p_hseq G))%nat; intros H3;\n        simpl;\n        apply Nat.leb_le in H1 + apply Nat.leb_nle in H1;\n        apply Nat.eqb_eq in H2 + apply Nat.eqb_neq in H2;\n        apply Nat.ltb_lt in H3 + apply Nat.ltb_nlt in H3;\n        try lia.\nQed.\n\nFixpoint p_hseq_without_max_complexity (G : p_hypersequent) : p_hypersequent :=\n  match G with\n  | nil => nil\n  | T :: G => if (fst (HMR_complexity_p_hseq G) <=? HMR_complexity_p_seq T)\n              then G\n              else T :: p_hseq_without_max_complexity G\n  end.\n\nLemma p_hseq_without_max_complexity_well_defined :\n  forall val G,\n    p_hseq_well_defined val G ->\n    p_hseq_well_defined val (p_hseq_without_max_complexity G).\nProof.\n  intros val; induction G; intros Hwd; [apply Forall_inf_nil | ].\n  inversion Hwd; subst; specialize (IHG X0).\n  simpl; case (fst (HMR_complexity_p_hseq G) <=? HMR_complexity_p_seq a); try apply Forall_inf_cons; auto.\nQed.\n\nLemma p_hseq_put_max_complexity_fst : forall G,\n    G <> nil ->\n    Permutation_Type G (p_hseq_p_seq_max_complexity G :: p_hseq_without_max_complexity G).\nProof.\n  induction G; intros Hnnil; [ exfalso; auto | ].\n  simpl.\n  case_eq (fst (HMR_complexity_p_hseq G) <=? HMR_complexity_p_seq a); intros H1;\n    apply Nat.leb_le in H1 + apply Nat.leb_nle in H1; auto.\n  destruct G.\n  { exfalso; simpl in H1; lia. }\n  assert (p :: G <> nil) as Hnnil'.\n  { intros H; inversion H. }\n  specialize (IHG Hnnil').\n  transitivity (a :: p_hseq_p_seq_max_complexity (p :: G) :: p_hseq_without_max_complexity (p :: G)); Permutation_Type_solve.\nQed.\n\nDefinition p_hseq_put_non_basic_fst G :=\n  ((p_seq_fst_non_basic_term (p_hseq_p_seq_max_complexity G) :: p_seq_without_fst_non_basic_term (p_hseq_p_seq_max_complexity G)) :: p_hseq_without_max_complexity G).\n\nLemma p_hseq_put_non_basic_fst_modal_complexity :\n  forall G,\n    (p_hseq_is_basic G -> False) ->\n    modal_complexity_p_hseq (p_hseq_put_non_basic_fst G) = modal_complexity_p_hseq G.\nProof.\n  intros G Hnb.\n  unfold p_hseq_put_non_basic_fst.\n  rewrite modal_complexity_perm_fst_seq with _ _ (p_hseq_p_seq_max_complexity G).\n  2:{ symmetry; apply p_seq_put_non_basic_fst.\n      intros H.\n      apply Hnb.\n      apply p_hseq_is_basic_complexity_0_inv.\n      rewrite <- p_hseq_p_seq_max_complexity_correct.\n      apply p_seq_is_basic_complexity_0.\n      apply H. }\n  rewrite modal_complexity_perm with _ G; auto.\n  symmetry; apply p_hseq_put_max_complexity_fst.\n  intros H; apply Hnb; rewrite H.\n  apply Forall_inf_nil.\nQed.\n\nLemma p_hseq_put_non_basic_fst_HMR_complexity :\n  forall G,\n    (p_hseq_is_basic G -> False) ->\n    HMR_complexity_p_hseq (p_hseq_put_non_basic_fst G) = HMR_complexity_p_hseq G.\nProof.\n  intros G Hnb.\n  apply same_modal_complexity_HMR_complexity.\n  apply p_hseq_put_non_basic_fst_modal_complexity; auto.\nQed.\n\nLemma p_hseq_put_non_basic_fst_correct :\n  forall G a A T H,\n    (p_hseq_is_basic G -> False) ->\n    p_hseq_put_non_basic_fst G = ((a, A) :: T) :: H ->\n    is_basic A -> False.\nProof.\n  intros G a A T H Hnb Heq Hb.\n  unfold p_hseq_put_non_basic_fst in Heq.\n  inversion Heq; subst.\n  apply p_seq_fst_non_basic_term_correct with (p_hseq_p_seq_max_complexity G).\n  - intros Hb'.\n    apply Hnb.\n    apply p_hseq_is_basic_complexity_0_inv.\n    apply p_seq_is_basic_complexity_0 in Hb'.\n    rewrite p_hseq_p_seq_max_complexity_correct in Hb'.\n    apply Hb'.\n  - rewrite H1.\n    apply Hb.\nQed.\n\nLemma p_hseq_put_non_basic_fst_well_defined :\n  forall val G,\n    (0 < fst (HMR_complexity_p_hseq G))%nat ->\n    p_hseq_well_defined val G ->\n    p_hseq_well_defined val (p_hseq_put_non_basic_fst G).\nProof.\n  intros val G Hn0 Hwd.\n  apply Forall_inf_cons; (destruct G; [ exfalso; simpl in *; lia | ]).\n  - apply Forall_inf_cons.\n    + apply p_seq_fst_non_basic_term_well_defined; [ | apply p_hseq_p_seq_max_complexity_well_defined; auto].\n      rewrite p_hseq_p_seq_max_complexity_correct.\n      apply Hn0.\n    + apply p_seq_without_fst_non_basic_term_well_defined.\n      apply p_hseq_p_seq_max_complexity_well_defined.\n      apply Hwd.\n  - apply p_hseq_without_max_complexity_well_defined; apply Hwd.\nQed.\n  \nDefinition apply_logical_rule_on_p_hypersequent G : (p_hypersequent + (p_hypersequent * p_hypersequent)) :=\n  match G with\n  | nil => inl nil\n  | T :: G => match T with\n              | nil => inl (nil :: G)\n              | (a, A) :: T => match A with\n                               | A1 +S A2 => inl (((a, A1) :: (a, A2) :: T) :: G)\n                               | A1 /\\S A2 => inr ((((a, A1) :: T) :: G) , (((a, A2) :: T) :: G))\n                               | A1 \\/S A2 => inl (((a, A2) :: T) :: ( (a, A1) :: T) :: G)\n                               | r0 *S A => inl (((FOL_R_cst (projT1 r0) *R a, A) :: T) :: G)\n                               | HMR_zero => inl (T :: G)\n                               | _ => inl (((a, A) :: T) :: G)\n                               end\n              end\n  end.\n\nLemma apply_logical_rule_on_p_hypersequent_inl_well_defined :\n  forall val G G1,\n    apply_logical_rule_on_p_hypersequent G = inl G1 ->\n    p_hseq_well_defined val G ->\n    p_hseq_well_defined val G1.\nProof.\n  intros val G G1 Heq Hwd.\n  destruct G ; [inversion Heq; apply Forall_inf_nil | ].\n  destruct l; [inversion Heq; apply Hwd | ].\n  destruct p as [a A].\n  destruct A; inversion Heq; subst; auto;\n    inversion Hwd; subst;\n      inversion X; subst; simpl in *;\n        (apply Forall_inf_cons; [ | try apply Forall_inf_cons]); auto;\n          apply Forall_inf_cons; auto.\n  apply R_blt_lt; apply R_blt_lt in H0.\n  destruct r as [r Hr].\n  clear - H0 Hr.\n  simpl; apply R_blt_lt in Hr.\n  nra.\nQed.\n\nLemma apply_logical_rule_on_p_hypersequent_inr_l_well_defined :\n  forall val G G1 G2,\n    apply_logical_rule_on_p_hypersequent G = inr (G1, G2) ->\n    p_hseq_well_defined val G ->\n    p_hseq_well_defined val G1.\nProof.\n  intros val G G1 G2 Heq Hwd.\n  destruct G ; [inversion Heq | ].\n  destruct l; [inversion Heq | ].\n  destruct p as [a A].\n  destruct A; inversion Heq; subst; auto.\n  inversion Hwd; subst.\n  inversion X; subst.\n  apply Forall_inf_cons ; [ apply Forall_inf_cons | ]; auto.\nQed.\n\nLemma apply_logical_rule_on_p_hypersequent_inr_r_well_defined :\n  forall val G G1 G2,\n    apply_logical_rule_on_p_hypersequent G = inr (G1, G2) ->\n    p_hseq_well_defined val G ->\n    p_hseq_well_defined val G2.\nProof.\n  intros val G G1 G2 Heq Hwd.\n  destruct G ; [inversion Heq | ].\n  destruct l; [inversion Heq | ].\n  destruct p as [a A].\n  destruct A; inversion Heq; subst; auto.\n  inversion Hwd; subst.\n  inversion X; subst.\n  apply Forall_inf_cons ; [ apply Forall_inf_cons | ]; auto.\nQed.\n\nLemma apply_logical_rule_on_p_hypersequent_inl_HMR :\n  forall val G G1,\n    apply_logical_rule_on_p_hypersequent G = inl G1 ->\n    p_hseq_well_defined val G ->\n    HMR_T_M (map (eval_p_sequent val) G) ->\n    HMR_T_M (map (eval_p_sequent val) G1).\nProof.\n  intros val G G1 Heq Hwd pi.\n  destruct G; [ exfalso; apply (HMR_not_empty _ nil pi); auto | ].\n  destruct l; [ inversion Heq; apply pi | ].\n  destruct p as [a A].\n  destruct A; inversion Heq; subst; auto.\n  - inversion Hwd; inversion X; subst.\n    simpl in pi.\n    sem_is_pos_decomp val a; intros e He;\n      try (exfalso; clear - e H2;\n           try (apply R_blt_lt in e); apply R_blt_lt in H2; simpl in *; lra).\n    rewrite He in pi.\n    simpl.\n    apply hmrr_Z_inv with ((existT _ (FOL_R_term_sem val a) e) :: nil).\n    apply pi.\n  - inversion Hwd; inversion X; subst.\n    simpl in pi |- *.\n    sem_is_pos_decomp val a; intros e He;\n      try (exfalso; clear - e H2;\n           try (apply R_blt_lt in e); apply R_blt_lt in H2; simpl in *; lra).\n    rewrite He in pi.\n    revert pi;set (r := (existT (fun x : R => (0 <? x) = true) (FOL_R_term_sem val a) e)); intros pi.\n    change ((r, A1) :: (r, A2) :: eval_p_sequent val l) with\n        (hseq.vec (r :: nil) A1 ++ hseq.vec (r :: nil) A2 ++ eval_p_sequent val l).\n    apply hmrr_plus_inv.\n    apply pi.\n  - inversion Hwd; inversion X; subst.\n    simpl in *.\n    sem_is_pos_decomp val a; intros e He;\n      try (exfalso; clear - e H2;\n           try (apply R_blt_lt in e); apply R_blt_lt in H2; simpl in *; lra).\n    case (R_order_dec (projT1 r * FOL_R_term_sem val a)); intros e';\n      try (exfalso; destruct r as [r Hr]; clear - e e' H2;\n           simpl in *;\n           apply R_blt_lt in Hr; apply R_blt_lt in e; try (apply R_blt_lt in e');\n           nra).\n    rewrite He in pi.\n    replace ((existT (fun x : R => (0 <? x) = true) (projT1 r * FOL_R_term_sem val a) e', A)\n              :: eval_p_sequent val l) with\n        (hseq.vec (hseq.mul_vec r ((existT (fun x => (0 <? x) = true) (FOL_R_term_sem val a) e) :: nil)) A ++ eval_p_sequent val l).\n    2:{ simpl.\n        replace (time_pos r (existT (fun x : R => (0 <? x) = true) (FOL_R_term_sem val a) e))\n          with (existT (fun x : R => (0 <? x) = true) (projT1 r * FOL_R_term_sem val a) e') by (destruct r; apply Rpos_eq; clear; simpl; nra); auto. }\n    apply hmrr_mul_inv.\n    apply pi.\n  - inversion Hwd; inversion X; subst.\n    simpl in pi |- *.\n    sem_is_pos_decomp val a; intros e He;\n      try (exfalso; clear - e H2;\n           try (apply R_blt_lt in e); apply R_blt_lt in H2; simpl in *; lra).\n    rewrite He in pi.\n    revert pi;set (r := (existT (fun x : R => (0 <? x) = true) (FOL_R_term_sem val a) e)); intros pi.\n    change ((r, A1) :: eval_p_sequent val l) with\n        (hseq.vec (r :: nil) A1 ++ eval_p_sequent val l).\n    change ((r, A2) :: eval_p_sequent val l) with\n        (hseq.vec (r :: nil) A2 ++ eval_p_sequent val l).\n    apply hmrr_max_inv.\n    apply pi.\nQed.\n\nLemma apply_logical_rule_on_p_hypersequent_inl_HMR_inv :\n  forall val G G1,\n    apply_logical_rule_on_p_hypersequent G = inl G1 ->\n    p_hseq_well_defined val G ->\n    HMR_T_M (map (eval_p_sequent val) G1) ->\n    HMR_T_M (map (eval_p_sequent val) G).\nProof.\n  intros val G G1 Heq Hwd pi.\n  destruct G; [ exfalso; apply (HMR_not_empty _ _ pi); inversion Heq; auto | ].\n  destruct l; [ inversion Heq; subst; apply pi | ].\n  destruct p as [a A].\n  destruct A; inversion Heq; subst; auto.\n  - inversion Hwd; inversion X; subst.\n    simpl in *.\n    sem_is_pos_decomp val a; intros e He;\n      try (exfalso; clear - e H2;\n           try (apply R_blt_lt in e); apply R_blt_lt in H2; simpl in *; lra).\n    revert pi;set (r := (existT (fun x : R => (0 <? x) = true) (FOL_R_term_sem val a) e)); intros pi.\n    change ((r, HMR_zero) :: eval_p_sequent val l) with\n        (hseq.vec (r :: nil) HMR_zero ++ eval_p_sequent val l).\n    apply hmrr_Z.\n    apply pi.\n  - inversion Hwd; inversion X; subst.\n    simpl in pi |- *.\n    sem_is_pos_decomp val a; intros e He;\n      try (exfalso; clear - e H2;\n           try (apply R_blt_lt in e); apply R_blt_lt in H2; simpl in *; lra).\n    rewrite He in pi.\n    revert pi;set (r := (existT (fun x : R => (0 <? x) = true) (FOL_R_term_sem val a) e)); intros pi.\n    change ((r, A1 +S A2) :: eval_p_sequent val l) with\n        (hseq.vec (r :: nil) (A1 +S A2) ++ eval_p_sequent val l).\n    apply hmrr_plus.\n    apply pi.\n  - inversion Hwd; inversion X; subst.\n    simpl in *.\n    sem_is_pos_decomp val a; intros e He;\n      try (exfalso; clear - e H2;\n           try (apply R_blt_lt in e); apply R_blt_lt in H2; simpl in *; lra).\n    case_eq (R_order_dec (projT1 r * FOL_R_term_sem val a)); intros e' He';\n      try (exfalso; destruct r as [r Hr]; clear - e e' H2;\n           simpl in *;\n           apply R_blt_lt in Hr; apply R_blt_lt in e; try (apply R_blt_lt in e');\n           nra).\n    rewrite He' in pi.\n    replace ((existT (fun x : R => (0 <? x) = true) (projT1 r * FOL_R_term_sem val a) e', A)\n              :: eval_p_sequent val l) with\n        (hseq.vec (hseq.mul_vec r ((existT (fun x => (0 <? x) = true) (FOL_R_term_sem val a) e) :: nil)) A ++ eval_p_sequent val l) in pi.\n    2:{ simpl.\n        replace (time_pos r (existT (fun x : R => (0 <? x) = true) (FOL_R_term_sem val a) e))\n          with (existT (fun x : R => (0 <? x) = true) (projT1 r * FOL_R_term_sem val a) e') by (destruct r; apply Rpos_eq; clear; simpl; nra); auto. }\n    revert pi;set (r' := (existT (fun x : R => (0 <? x) = true) (FOL_R_term_sem val a) e)); intros pi.\n    change ((r', r *S A) :: eval_p_sequent val l)\n      with (hseq.vec (r' :: nil) (r *S A) ++ eval_p_sequent val l).    \n    apply hmrr_mul.\n    apply pi.\n  - inversion Hwd; inversion X; subst.\n    simpl in pi |- *.\n    sem_is_pos_decomp val a; intros e He;\n      try (exfalso; clear - e H2;\n           try (apply R_blt_lt in e); apply R_blt_lt in H2; simpl in *; lra).\n    rewrite He in pi.\n    revert pi;set (r := (existT (fun x : R => (0 <? x) = true) (FOL_R_term_sem val a) e)); intros pi.\n    change ((r, A1 \\/S A2) :: eval_p_sequent val l) with\n        (hseq.vec (r :: nil) (A1 \\/S A2) ++ eval_p_sequent val l).\n    apply hmrr_max.\n    apply pi.\nQed.\n\nLemma apply_logical_rule_on_p_hypersequent_inr_l_HMR :\n  forall val G G1 G2,\n    apply_logical_rule_on_p_hypersequent G = inr (G1 , G2) ->\n    p_hseq_well_defined val G ->\n    HMR_T_M (map (eval_p_sequent val) G) ->\n    HMR_T_M (map (eval_p_sequent val) G1).\nProof.\n  intros val G G1 G2 Heq Hwd pi.\n  destruct G; [ exfalso; apply (HMR_not_empty _ nil pi); auto | ].\n  destruct l; [ inversion Heq; apply pi | ].\n  destruct p as [a A].\n  destruct A; inversion Heq; subst; auto.\n  inversion Hwd; inversion X; subst.\n  simpl in pi |- *.\n  sem_is_pos_decomp val a; intros e He;\n    try (exfalso; clear - e H2;\n         try (apply R_blt_lt in e); apply R_blt_lt in H2; simpl in *; lra).\n  rewrite He in pi.\n  revert pi;set (r := (existT (fun x : R => (0 <? x) = true) (FOL_R_term_sem val a) e)); intros pi.\n  change ((r, A1) :: eval_p_sequent val l) with\n      (hseq.vec (r :: nil) A1 ++ eval_p_sequent val l).\n  apply hmrr_min_inv_l with A2.\n  apply pi.\nQed.\n\nLemma apply_logical_rule_on_p_hypersequent_inr_r_HMR :\n  forall val G G1 G2,\n    apply_logical_rule_on_p_hypersequent G = inr (G1 , G2) ->\n    p_hseq_well_defined val G ->\n    HMR_T_M (map (eval_p_sequent val) G) ->\n    HMR_T_M (map (eval_p_sequent val) G2).\nProof.\n  intros val G G1 G2 Heq Hwd pi.\n  destruct G; [ exfalso; apply (HMR_not_empty _ nil pi); auto | ].\n  destruct l; [ inversion Heq; apply pi | ].\n  destruct p as [a A].\n  destruct A; inversion Heq; subst; auto.\n  inversion Hwd; inversion X; subst.\n  simpl in pi |- *.\n  sem_is_pos_decomp val a; intros e He;\n    try (exfalso; clear - e H2;\n         try (apply R_blt_lt in e); apply R_blt_lt in H2; simpl in *; lra).\n  rewrite He in pi.\n  revert pi;set (r := (existT (fun x : R => (0 <? x) = true) (FOL_R_term_sem val a) e)); intros pi.\n  change ((r, A2) :: eval_p_sequent val l) with\n      (hseq.vec (r :: nil) A2 ++ eval_p_sequent val l).\n  apply hmrr_min_inv_r with A1.\n  apply pi.\nQed.\n\nLemma apply_logical_rule_on_p_hypersequent_inr_HMR_inv :\n  forall val G G1 G2,\n    apply_logical_rule_on_p_hypersequent G = inr (G1 , G2) ->\n    p_hseq_well_defined val G ->\n    HMR_T_M (map (eval_p_sequent val) G1) ->\n    HMR_T_M (map (eval_p_sequent val) G2) ->\n    HMR_T_M (map (eval_p_sequent val) G).\nProof.\n  intros val G G1 G2 Heq Hwd pi1 pi2.\n  destruct G; [ exfalso; inversion Heq | ].\n  destruct l; [ inversion Heq | ].\n  destruct p as [a A].\n  destruct A; inversion Heq; subst; auto.\n  inversion Hwd; inversion X; subst.\n  simpl in pi1,pi2 |- *.\n  sem_is_pos_decomp val a; intros e He;\n    try (exfalso; clear - e H2;\n         try (apply R_blt_lt in e); apply R_blt_lt in H2; simpl in *; lra).\n  rewrite He in pi1; rewrite He in pi2.\n  revert pi1 pi2;set (r := (existT (fun x : R => (0 <? x) = true) (FOL_R_term_sem val a) e)); intros pi1 pi2.\n  change ((r, A1 /\\S A2) :: eval_p_sequent val l) with\n      (hseq.vec (r :: nil) (A1 /\\S A2) ++ eval_p_sequent val l).\n  apply hmrr_min; auto.\nQed.\n    \nLemma apply_logical_rule_on_p_hypersequent_correct_inl :\n  forall G G1 n,\n    snd (fst (modal_complexity_p_hseq G)) = S n ->\n    apply_logical_rule_on_p_hypersequent (p_hseq_put_non_basic_fst G) = inl G1 ->\n    modal_complexity_p_hseq G1 <3 modal_complexity_p_hseq G.\nProof.\n  intros G G1 n H1 H2.\n  unfold modal_complexity_p_hseq in H1.\n  simpl in H1.\n  remember (p_hseq_put_non_basic_fst G) as H.\n  destruct H.\n  { exfalso.\n    rewrite <- p_hseq_put_non_basic_fst_HMR_complexity in H1 ; [ rewrite <- HeqH in H1; inversion H1 |].\n    intros Hnb.\n    apply p_hseq_is_basic_complexity_0 in Hnb; lia. }\n  destruct l.\n  { unfold p_hseq_put_non_basic_fst in HeqH.\n    inversion HeqH. }\n  destruct p as [a A].\n  assert (is_basic A -> False).\n  { apply p_hseq_put_non_basic_fst_correct with G a l H; auto.\n    intros Hb.\n    apply p_hseq_is_basic_complexity_0 in Hb.\n    lia. }\n  destruct A; simpl in H2; inversion H2; subst; try (exfalso; now apply H0).\n  - rewrite <- (p_hseq_put_non_basic_fst_modal_complexity G).\n    2:{ intros Hnb.\n        apply p_hseq_is_basic_complexity_0 in Hnb; lia. }\n    rewrite <- HeqH.\n    change ((a, HMR_zero) :: l) with (vec (a :: nil) HMR_zero ++ l).\n    apply hmrr_Z_decrease_modal_complexity ; [ intros H'; inversion H' | ].\n    simpl vec; simpl app.\n    rewrite HeqH.\n    unfold p_hseq_put_non_basic_fst in *.\n    rewrite HMR_complexity_perm_fst_seq with _ _ (p_hseq_p_seq_max_complexity G).\n    2:{ symmetry; apply p_seq_put_non_basic_fst.\n        intros Hb.\n        apply p_seq_is_basic_complexity_0 in Hb.\n        rewrite p_hseq_p_seq_max_complexity_correct in Hb; lia. }\n    rewrite complexity_p_hseq_perm with _ G.\n    2:{ symmetry; apply p_hseq_put_max_complexity_fst.\n        intros Heq; rewrite Heq in H1; inversion H1. }\n    rewrite <-p_hseq_p_seq_max_complexity_correct.\n    rewrite complexity_p_seq_perm with (p_hseq_p_seq_max_complexity G) (p_seq_fst_non_basic_term (p_hseq_p_seq_max_complexity G) :: p_seq_without_fst_non_basic_term (p_hseq_p_seq_max_complexity G)).\n    2:{ apply p_seq_put_non_basic_fst.\n        intros Hb.\n        apply p_seq_is_basic_complexity_0 in Hb.\n        rewrite p_hseq_p_seq_max_complexity_correct in Hb; lia. }\n    inversion HeqH; subst; reflexivity.\n  - rewrite <- (p_hseq_put_non_basic_fst_modal_complexity G).\n    2:{ intros Hnb.\n        apply p_hseq_is_basic_complexity_0 in Hnb; lia. }\n    rewrite <- HeqH.\n    change ((a, A1 +S A2) :: l) with (vec (a :: nil) (A1 +S A2) ++ l).\n    change ((a, A1) :: (a, A2) :: l) with (vec (a :: nil) A1 ++ vec (a :: nil) A2 ++ l).\n    apply hmrr_plus_decrease_modal_complexity ; [ intros H'; inversion H' | ].\n    simpl vec; simpl app.\n    rewrite HeqH.\n    unfold p_hseq_put_non_basic_fst in *.\n    rewrite HMR_complexity_perm_fst_seq with _ _ (p_hseq_p_seq_max_complexity G).\n    2:{ symmetry; apply p_seq_put_non_basic_fst.\n        intros Hb.\n        apply p_seq_is_basic_complexity_0 in Hb.\n        rewrite p_hseq_p_seq_max_complexity_correct in Hb; lia. }\n    rewrite complexity_p_hseq_perm with _ G.\n    2:{ symmetry; apply p_hseq_put_max_complexity_fst.\n        intros Heq; rewrite Heq in H1; inversion H1. }\n    rewrite <-p_hseq_p_seq_max_complexity_correct.\n    rewrite complexity_p_seq_perm with (p_hseq_p_seq_max_complexity G) (p_seq_fst_non_basic_term (p_hseq_p_seq_max_complexity G) :: p_seq_without_fst_non_basic_term (p_hseq_p_seq_max_complexity G)).\n    2:{ apply p_seq_put_non_basic_fst.\n        intros Hb.\n        apply p_seq_is_basic_complexity_0 in Hb.\n        rewrite p_hseq_p_seq_max_complexity_correct in Hb; lia. }\n    inversion HeqH; subst; reflexivity.\n  - rewrite <- (p_hseq_put_non_basic_fst_modal_complexity G).\n    2:{ intros Hnb.\n        apply p_hseq_is_basic_complexity_0 in Hnb; lia. }\n    rewrite <- HeqH.\n    change ((a, r *S A) :: l) with (vec (a :: nil) (r *S A) ++ l).\n    change ((FOL_R_cst (projT1 r) *R a, A) :: l) with (vec (mul_vec (FOL_R_cst (projT1 r)) (a :: nil)) A ++ l).\n    apply hmrr_mul_decrease_modal_complexity ; [ intros H'; inversion H' | ].\n    simpl vec; simpl app.\n    rewrite HeqH.\n    unfold p_hseq_put_non_basic_fst in *.\n    rewrite HMR_complexity_perm_fst_seq with _ _ (p_hseq_p_seq_max_complexity G).\n    2:{ symmetry; apply p_seq_put_non_basic_fst.\n        intros Hb.\n        apply p_seq_is_basic_complexity_0 in Hb.\n        rewrite p_hseq_p_seq_max_complexity_correct in Hb; lia. }\n    rewrite complexity_p_hseq_perm with _ G.\n    2:{ symmetry; apply p_hseq_put_max_complexity_fst.\n        intros Heq; rewrite Heq in H1; inversion H1. }\n    rewrite <-p_hseq_p_seq_max_complexity_correct.\n    rewrite complexity_p_seq_perm with (p_hseq_p_seq_max_complexity G) (p_seq_fst_non_basic_term (p_hseq_p_seq_max_complexity G) :: p_seq_without_fst_non_basic_term (p_hseq_p_seq_max_complexity G)).\n    2:{ apply p_seq_put_non_basic_fst.\n        intros Hb.\n        apply p_seq_is_basic_complexity_0 in Hb.\n        rewrite p_hseq_p_seq_max_complexity_correct in Hb; lia. }\n    inversion HeqH; subst; reflexivity.\n  - rewrite <- (p_hseq_put_non_basic_fst_modal_complexity G).\n    2:{ intros Hnb.\n        apply p_hseq_is_basic_complexity_0 in Hnb; lia. }\n    rewrite <- HeqH.\n    change ((a, A1 \\/S A2) :: l) with (vec (a :: nil) (A1 \\/S A2) ++ l).\n    change ((a, A1) :: l) with (vec (a :: nil) A1 ++ l).\n    change ((a, A2) :: l) with (vec (a :: nil) A2 ++ l).\n    apply hmrr_max_decrease_modal_complexity ; [ intros H'; inversion H' | ].\n    simpl vec; simpl app.\n    rewrite HeqH.\n    unfold p_hseq_put_non_basic_fst in *.\n    rewrite HMR_complexity_perm_fst_seq with _ _ (p_hseq_p_seq_max_complexity G).\n    2:{ symmetry; apply p_seq_put_non_basic_fst.\n        intros Hb.\n        apply p_seq_is_basic_complexity_0 in Hb.\n        rewrite p_hseq_p_seq_max_complexity_correct in Hb; lia. }\n    rewrite complexity_p_hseq_perm with _ G.\n    2:{ symmetry; apply p_hseq_put_max_complexity_fst.\n        intros Heq; rewrite Heq in H1; inversion H1. }\n    rewrite <-p_hseq_p_seq_max_complexity_correct.\n    rewrite complexity_p_seq_perm with (p_hseq_p_seq_max_complexity G) (p_seq_fst_non_basic_term (p_hseq_p_seq_max_complexity G) :: p_seq_without_fst_non_basic_term (p_hseq_p_seq_max_complexity G)).\n    2:{ apply p_seq_put_non_basic_fst.\n        intros Hb.\n        apply p_seq_is_basic_complexity_0 in Hb.\n        rewrite p_hseq_p_seq_max_complexity_correct in Hb; lia. }\n    inversion HeqH; subst; reflexivity.\nQed.\n\nLemma apply_logical_rule_on_p_hypersequent_correct_inr_l :\n  forall G G1 G2 n,\n    snd (fst (modal_complexity_p_hseq G)) = S n ->\n    apply_logical_rule_on_p_hypersequent (p_hseq_put_non_basic_fst G) = inr (G1 , G2) ->\n    modal_complexity_p_hseq G1 <3 modal_complexity_p_hseq G.\nProof.\n  intros G G1 G2 n H1 H2.\n  unfold modal_complexity_p_hseq in H1.\n  simpl in H1.\n  remember (p_hseq_put_non_basic_fst G) as H.\n  destruct H.\n  { exfalso.\n    rewrite <- p_hseq_put_non_basic_fst_HMR_complexity in H1 ; [ rewrite <- HeqH in H1; inversion H1 |].\n    intros Hnb.\n    apply p_hseq_is_basic_complexity_0 in Hnb; lia. }\n  destruct l.\n  { unfold p_hseq_put_non_basic_fst in HeqH.\n    inversion HeqH. }\n  destruct p as [a A].\n  assert (is_basic A -> False).\n  { apply p_hseq_put_non_basic_fst_correct with G a l H; auto.\n    intros Hb.\n    apply p_hseq_is_basic_complexity_0 in Hb.\n    lia. }\n  destruct A; simpl in H2; inversion H2; subst; try (exfalso; now apply H0).\n  rewrite <- (p_hseq_put_non_basic_fst_modal_complexity G).\n  2:{ intros Hnb.\n      apply p_hseq_is_basic_complexity_0 in Hnb; lia. }\n  rewrite <- HeqH.\n  change ((a, A1 /\\S A2) :: l) with (vec (a :: nil) (A1 /\\S A2) ++ l).\n  change ((a, A1) :: l) with (vec (a :: nil) A1 ++ l).\n  apply hmrr_min_r_decrease_modal_complexity ; [ intros H'; inversion H' | ].\n  simpl vec; simpl app.\n  rewrite HeqH.\n  unfold p_hseq_put_non_basic_fst in *.\n  rewrite HMR_complexity_perm_fst_seq with _ _ (p_hseq_p_seq_max_complexity G).\n  2:{ symmetry; apply p_seq_put_non_basic_fst.\n      intros Hb.\n      apply p_seq_is_basic_complexity_0 in Hb.\n      rewrite p_hseq_p_seq_max_complexity_correct in Hb; lia. }\n  rewrite complexity_p_hseq_perm with _ G.\n  2:{ symmetry; apply p_hseq_put_max_complexity_fst.\n      intros Heq; rewrite Heq in H1; inversion H1. }\n  rewrite <-p_hseq_p_seq_max_complexity_correct.\n  rewrite complexity_p_seq_perm with (p_hseq_p_seq_max_complexity G) (p_seq_fst_non_basic_term (p_hseq_p_seq_max_complexity G) :: p_seq_without_fst_non_basic_term (p_hseq_p_seq_max_complexity G)).\n  2:{ apply p_seq_put_non_basic_fst.\n      intros Hb.\n      apply p_seq_is_basic_complexity_0 in Hb.\n      rewrite p_hseq_p_seq_max_complexity_correct in Hb; lia. }\n  inversion HeqH; subst; reflexivity.\nQed.\n\nLemma apply_logical_rule_on_p_hypersequent_correct_inr_r :\n  forall G G1 G2 n,\n    snd (fst (modal_complexity_p_hseq G)) = S n ->\n    apply_logical_rule_on_p_hypersequent (p_hseq_put_non_basic_fst G) = inr (G1 , G2) ->\n    modal_complexity_p_hseq G2 <3 modal_complexity_p_hseq G.\nProof.\n  intros G G1 G2 n H1 H2.\n  unfold modal_complexity_p_hseq in H1.\n  simpl in H1.\n  remember (p_hseq_put_non_basic_fst G) as H.\n  destruct H.\n  { exfalso.\n    rewrite <- p_hseq_put_non_basic_fst_HMR_complexity in H1 ; [ rewrite <- HeqH in H1; inversion H1 |].\n    intros Hnb.\n    apply p_hseq_is_basic_complexity_0 in Hnb; lia. }\n  destruct l.\n  { unfold p_hseq_put_non_basic_fst in HeqH.\n    inversion HeqH. }\n  destruct p as [a A].\n  assert (is_basic A -> False).\n  { apply p_hseq_put_non_basic_fst_correct with G a l H; auto.\n    intros Hb.\n    apply p_hseq_is_basic_complexity_0 in Hb.\n    lia. }\n  destruct A; simpl in H2; inversion H2; subst; try (exfalso; now apply H0).\n  rewrite <- (p_hseq_put_non_basic_fst_modal_complexity G).\n  2:{ intros Hnb.\n      apply p_hseq_is_basic_complexity_0 in Hnb; lia. }\n  rewrite <- HeqH.\n  change ((a, A1 /\\S A2) :: l) with (vec (a :: nil) (A1 /\\S A2) ++ l).\n  change ((a, A2) :: l) with (vec (a :: nil) A2 ++ l).\n  apply hmrr_min_l_decrease_modal_complexity ; [ intros H'; inversion H' | ].\n  simpl vec; simpl app.\n  rewrite HeqH.\n  unfold p_hseq_put_non_basic_fst in *.\n  rewrite HMR_complexity_perm_fst_seq with _ _ (p_hseq_p_seq_max_complexity G).\n  2:{ symmetry; apply p_seq_put_non_basic_fst.\n      intros Hb.\n      apply p_seq_is_basic_complexity_0 in Hb.\n      rewrite p_hseq_p_seq_max_complexity_correct in Hb; lia. }\n  rewrite complexity_p_hseq_perm with _ G.\n  2:{ symmetry; apply p_hseq_put_max_complexity_fst.\n      intros Heq; rewrite Heq in H1; inversion H1. }\n  rewrite <-p_hseq_p_seq_max_complexity_correct.\n  rewrite complexity_p_seq_perm with (p_hseq_p_seq_max_complexity G) (p_seq_fst_non_basic_term (p_hseq_p_seq_max_complexity G) :: p_seq_without_fst_non_basic_term (p_hseq_p_seq_max_complexity G)).\n  2:{ apply p_seq_put_non_basic_fst.\n      intros Hb.\n      apply p_seq_is_basic_complexity_0 in Hb.\n      rewrite p_hseq_p_seq_max_complexity_correct in Hb; lia. }\n  inversion HeqH; subst; reflexivity.\nQed.\n\n(* end hide *)\n\n(** return the conjunction /\\(beta_{k + i} = 0) for all i \\in v *)\nFixpoint FOL_R_all_zero k (v : list nat) :=\n  match v with\n  | nil => FOL_R_true\n  | n :: v => FOL_R_and\n                (FOL_R_atoms ((FOL_R_var (k + n)) =R (FOL_R_cst 0)))\n                (FOL_R_all_zero k v)\n  end.\n\nLemma cond_FOL_R_all_zero_formula_sem : forall k v val,\n    (forall n, In_inf n v -> val (k + n)%nat = 0) ->\n    FOL_R_formula_sem val (FOL_R_all_zero k v).\nProof.\n  intros k; induction v; intros val H; [apply I | ].\n  split.\n  - apply H.\n    apply in_inf_eq.\n  - apply IHv.\n    intros n Hin.\n    apply H.\n    apply in_inf_cons; apply Hin.\nQed.\n    \nLemma cond_FOL_R_all_zero_formula_sem_inv : forall k v val,\n    FOL_R_formula_sem val (FOL_R_all_zero k v) ->\n    forall n, In_inf n v -> val (k + n)%nat = 0.\nProof.\n  intros k; induction v; intros val Hf n Hin; inversion Hin; subst.\n  - destruct Hf as [Heq _]; apply Heq.\n  - destruct Hf as [_ Hf].\n    apply IHv; assumption.\nQed.\n\n(** return the conjunction /\\(0\\leq\\beta_{k + i} /\\ \\beta_{k + i} = 0) for all in \\in v *)\nFixpoint FOL_R_all_gtz k (v : list nat ) :=\n  match v with\n  | nil => FOL_R_true\n  | n :: v => FOL_R_and (FOL_R_and\n                           (FOL_R_atoms ((FOL_R_var (k + n)) <>R (FOL_R_cst 0)))\n                           (FOL_R_atoms ((FOL_R_cst 0) <=R(FOL_R_var (k + n)))))\n                        (FOL_R_all_gtz k v)\n  end.\n\nLemma cond_FOL_R_all_gtz_formula_sem : forall k v val,\n    (forall n, In_inf n v -> 0 < val (k + n)%nat) ->\n    FOL_R_formula_sem val (FOL_R_all_gtz k v).\nProof.\n  intros k; induction v; intros val H; [apply I | ].\n  split.\n  - specialize (H a (in_inf_eq a v)).\n    split; simpl; lra.\n  - apply IHv.\n    intros n Hin.\n    apply H.\n    apply in_inf_cons; apply Hin.\nQed.\n    \nLemma cond_FOL_R_all_gtz_formula_sem_inv : forall k v val,\n    FOL_R_formula_sem val (FOL_R_all_gtz k v) ->\n    forall n, In_inf n v -> 0 < val (k + n)%nat.\nProof.\n  intros k; induction v; intros val Hf n Hin; inversion Hin; subst.\n  - destruct Hf as [[Hneq Hle] _].\n    simpl in *; lra.\n  - destruct Hf as [_ Hf].\n    apply IHv; assumption.\nQed.\n\n(** return the conjunction /\\(\\sum_i^m \\beta_{(max_var_weight G) + i} \\sum\\vec R_{i,j} = \\sum_i^m \\beta_{(max_var_weight G) + i} \\sum\\vec S_{i,j} *)\nFixpoint FOL_R_all_atoms_eq G k :=\n  match k with\n  | 0%nat => FOL_R_atoms ((p_sum_weight_var_with_coeff 0%nat G (map FOL_R_var (seq (S (max_var_weight_p_hseq G)) (length G)))) =R(p_sum_weight_covar_with_coeff 0%nat G (map FOL_R_var (seq (S (max_var_weight_p_hseq G)) (length G)))))\n  | S k => FOL_R_and\n             (FOL_R_atoms ((p_sum_weight_var_with_coeff (S k) G (map FOL_R_var (seq (S (max_var_weight_p_hseq G)) (length G)))) =R (p_sum_weight_covar_with_coeff (S k) G (map FOL_R_var (seq (S (max_var_weight_p_hseq G)) (length G))))))\n             (FOL_R_all_atoms_eq G k)\n  end.\n\n\nLemma cond_FOL_R_all_atoms_eq_formula_sem : forall G k val,\n    (forall n, (n <= k)%nat -> FOL_R_pred_sem val (p_sum_weight_var_with_coeff n G (map FOL_R_var (seq (S (max_var_weight_p_hseq G)) (length G))) =R p_sum_weight_covar_with_coeff n G (map FOL_R_var (seq (S (max_var_weight_p_hseq G)) (length G))))) ->\n    FOL_R_formula_sem val (FOL_R_all_atoms_eq G k).\nProof.\n  intros G; induction k; intros val H.\n  - simpl.\n    specialize (H 0%nat (Nat.le_refl 0%nat)).\n    apply H.\n  - simpl.\n    split.\n    + specialize (H (S k) (Nat.le_refl (S k))).\n      apply H.\n    + apply IHk.\n      intros n Hle.\n      apply H.\n      lia.\nQed.\n    \nLemma cond_FOL_R_all_atoms_eq_formula_sem_inv : forall G k val,\n    FOL_R_formula_sem val (FOL_R_all_atoms_eq G k) ->\n    forall n, (n <= k)%nat -> FOL_R_pred_sem val (p_sum_weight_var_with_coeff n G (map FOL_R_var (seq (S (max_var_weight_p_hseq G)) (length G))) =R p_sum_weight_covar_with_coeff n G (map FOL_R_var (seq (S (max_var_weight_p_hseq G)) (length G)))).\nProof.\n  intros G; induction k; intros val Hf n Hle.\n  - simpl in Hf.\n    destruct n; inversion Hle.\n    apply Hf.\n  - destruct Hf as [Hf1 Hf2].\n    case_eq (n =? S k)%nat; intros Heq.\n    + simpl in Hf1 |- *.\n      apply Nat.eqb_eq in Heq; rewrite Heq.\n      apply Hf1.\n    + apply IHk ; try assumption.\n      apply Nat.eqb_neq in Heq.\n      lia.\nQed.\n\n(** return the formula (\\sum_i^m \\beta_{(max_var_weight G) + i} \\sum\\vec R_{i,j} = \\sum_i^m \\beta_{(max_var_weight G) + i} \\sum\\vec S_{i,j} *)\nDefinition FOL_R_coone_le_one G := FOL_R_atoms ((p_sum_weight_coone_with_coeff G (map FOL_R_var (seq (S (max_var_weight_p_hseq G)) (length G)))) <=R (p_sum_weight_one_with_coeff G (map FOL_R_var (seq (S (max_var_weight_p_hseq G)) (length G))))).\n\n(** return the formula corresponding to \\phi_{G,v} *)\nDefinition FOL_R_phi G v :=\n  FOL_R_and (FOL_R_all_zero (S (max_var_weight_p_hseq G)) (complementary v (length G)))\n            (FOL_R_and (FOL_R_all_gtz (S (max_var_weight_p_hseq G)) v)\n                       (FOL_R_and (FOL_R_all_atoms_eq G (max_var_p_hseq G))\n                                  (FOL_R_coone_le_one G))).\n    \n(** return the whole formula *)\n\n(* begin hide *)\n(* auxiliary functions used to help Coq understands they terminate *)\nFixpoint FOL_R_basic_case_aux (G : p_hypersequent) (V : list (list nat)) n (Heqn : max_diamond_p_hseq G = n) (acc : Acc lt_nat4 (modal_complexity_p_hseq G , length V)) : FOL_R_formula\nwith HMR_dec_formula_aux (G : p_hypersequent) (x: nat) (Heqx : snd (fst (modal_complexity_p_hseq G)) = x) p (Heqp : apply_logical_rule_on_p_hypersequent (p_hseq_put_non_basic_fst G) = p) (acc : Acc lt_nat4 (modal_complexity_p_hseq G, S (length (make_subsets (length G))))) : FOL_R_formula.\n  - destruct acc as [acc].\n    destruct V as [ | v V].\n    + apply FOL_R_false.\n    +  destruct n.\n       * refine (FOL_R_or\n                   (exists_vec (seq (S (max_var_weight_p_hseq G)) (length G)) (FOL_R_phi G v))\n                   (FOL_R_basic_case_aux G V\n                                         0%nat\n                                         Heqn\n                                         (acc _\n                                              (lt_nat4_last\n                                                 _\n                                                 _\n                                                 _\n                                                 (Nat.lt_succ_diag_r _))))).\n       * refine (FOL_R_or\n                   (exists_vec (seq (S (max_var_weight_p_hseq G)) (length G))\n                               (FOL_R_and (FOL_R_phi G v)\n                                          (HMR_dec_formula_aux (flat_map (fun i : nat => seq_mul (FOL_R_var (S (max_var_weight_p_hseq G) + i)) (only_diamond_p_seq (nth i G nil))) v :: nil)\n                                                               _\n                                                               (eq_refl _)\n                                                               _\n                                                               (eq_refl _)\n                                                               (acc _ (lt_nat3_to_lt_nat4\n                                                                         _\n                                                                         _\n                                                                         _\n                                                                         _\n                                                                         (modal_complexity_only_diamond_p_seq _ _ _ _ Heqn))))))\n                   (FOL_R_basic_case_aux G V\n                                         (S n)\n                                         Heqn\n                                         (acc _\n                                              (lt_nat4_last\n                                                 _\n                                                 _\n                                                 _\n                                                 (Nat.lt_succ_diag_r _))))).\n  - destruct acc as [acc].\n    destruct x.\n    + refine (FOL_R_basic_case_aux G (map (@rev nat) (make_subsets (length G)))\n                                   _\n                                   (eq_refl _)\n                                   (acc _\n                                        (lt_nat4_last\n                                           _\n                                           _\n                                           _\n                                           (eq_rect _ (fun x => (x < S (length (make_subsets (length G))))%nat) (Nat.lt_succ_diag_r _) _ (eq_sym (map_length _ _)))))).\n    + destruct p.\n      * refine (HMR_dec_formula_aux p\n                                _\n                                eq_refl\n                                _\n                                eq_refl\n                                (acc _\n                                     (lt_nat3_to_lt_nat4 _ _ _ _\n                                                         (apply_logical_rule_on_p_hypersequent_correct_inl G p x Heqx Heqp)))).\n      * destruct p.\n        refine (FOL_R_and\n                  (HMR_dec_formula_aux p\n                                   _\n                                   (eq_refl _)\n                                   _\n                                   (eq_refl _)\n                                   (acc _\n                                        (lt_nat3_to_lt_nat4 _ _ _ _\n                                                            (apply_logical_rule_on_p_hypersequent_correct_inr_l G p p0 x Heqx Heqp))))\n                  (HMR_dec_formula_aux p0\n                                    _\n                                   eq_refl\n                                   _\n                                   eq_refl\n                                   (acc _\n                                        (lt_nat3_to_lt_nat4 _ _ _ _\n                                                            (apply_logical_rule_on_p_hypersequent_correct_inr_r G p p0 x Heqx Heqp))))).\nDefined.    \n\nLemma FOL_R_basic_case_aux_sem_indep_acc val (G : p_hypersequent) (V : list (list nat)) n (Heqn : max_diamond_p_hseq G = n) (acc1 acc2 : Acc lt_nat4 (modal_complexity_p_hseq G , length V)) :\n    FOL_R_formula_sem val (FOL_R_basic_case_aux G V n Heqn acc1) ->\n    FOL_R_formula_sem val (FOL_R_basic_case_aux G V n Heqn acc2)\nwith HMR_dec_formula_aux_sem_indep_acc val (G : p_hypersequent) (x: nat) (Heqx : snd (fst (modal_complexity_p_hseq G)) = x) p (Heqp : apply_logical_rule_on_p_hypersequent (p_hseq_put_non_basic_fst G) = p) (acc1 acc2 : Acc lt_nat4 (modal_complexity_p_hseq G, S (length (make_subsets (length G))))) :\n         FOL_R_formula_sem val (HMR_dec_formula_aux G x Heqx p Heqp acc1) ->\n         FOL_R_formula_sem val (HMR_dec_formula_aux G x Heqx p Heqp acc2).\nProof.\n  - destruct acc1 as [acc1]; destruct acc2 as [acc2].\n    destruct V; destruct n; intros Hf; try destruct Hf as [Hf | Hf].\n    + inversion Hf.\n    + inversion Hf.\n    + simpl.\n      left.\n      apply Hf.\n    + simpl.\n      right.\n      refine (FOL_R_basic_case_aux_sem_indep_acc _ _ _ _ _ (acc1 _ _) (acc2 _ _) Hf).\n    + left.\n      apply cond_FOL_R_exists_vec_formula_sem.\n      apply cond_FOL_R_exists_vec_formula_sem_inv in Hf as [v [Hlen [Hf1 Hf2]]].\n      split with v.\n      split; [ |  split]; auto.\n      refine (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ (acc1 _ _) (acc2 _ _) Hf2).\n    + simpl.\n      right.\n      refine (FOL_R_basic_case_aux_sem_indep_acc _ _ _ _ _ (acc1 _ _) (acc2 _ _) Hf).\n  - destruct acc1 as [acc1]; destruct acc2 as [acc2]; intros Hf.\n    destruct x.\n    + simpl.\n      refine (FOL_R_basic_case_aux_sem_indep_acc _ _ _ _ _ (acc1 _ _) (acc2 _ _) Hf).\n    + destruct p.\n      * refine (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ (acc1 _ _) (acc2 _ _) Hf).\n      * destruct p.\n        destruct Hf as [Hf1 Hf2].\n        split.\n        -- refine (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ (acc1 _ _) (acc2 _ _) Hf1).\n        -- refine (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ (acc1 _ _) (acc2 _ _) Hf2).\nQed.\n\nLemma FOL_R_basic_case_aux_sem_indep_n :\n  forall val (G : p_hypersequent) (V : list (list nat)) n (Heqn : max_diamond_p_hseq G = n) m (Heqm : max_diamond_p_hseq G = m) (acc : Acc lt_nat4 (modal_complexity_p_hseq G , length V)),\n  FOL_R_formula_sem val (FOL_R_basic_case_aux G V n Heqn acc) ->\n  FOL_R_formula_sem val (FOL_R_basic_case_aux G V m Heqm acc).\nProof.\n  intros val G V.\n  induction V; intros n Heqn m Heqm acc;\n    destruct acc as [acc]; auto.\n  destruct n; destruct m; try (exfalso; lia); intros [Hf | Hf].\n  + left.\n    apply Hf.\n  + right.\n    apply (IHV _ Heqn _ Heqm); apply Hf.\n  + left.\n    apply cond_FOL_R_exists_vec_formula_sem.\n    apply cond_FOL_R_exists_vec_formula_sem_inv in Hf as [v [Hlen [Hf1 Hf2]]].\n    split with v.\n    split; [ |  split]; auto.\n    apply (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ _ _ Hf2).\n  + right.\n    apply (IHV _ Heqn _ Heqm); apply Hf.\nQed.\n\nLemma HMR_dec_formula_aux_sem_indep_n : forall val G (n: nat) (Heqn : snd (fst (modal_complexity_p_hseq G)) = n) m (Heqm : snd (fst (modal_complexity_p_hseq G)) = m) p (Heqp : apply_logical_rule_on_p_hypersequent (p_hseq_put_non_basic_fst G) = p) acc,\n    FOL_R_formula_sem val (HMR_dec_formula_aux G n Heqn p Heqp acc) ->\n    FOL_R_formula_sem val (HMR_dec_formula_aux G m Heqm p Heqp acc).\nProof.\n  intros val G.\n  assert ({x & x = modal_complexity_p_hseq G}) as [x Heqx] by (split with (modal_complexity_p_hseq G); reflexivity).\n  revert G Heqx.\n  apply (lt_nat3_wf_rect x); clear x.\n  intros x H G Heqx [ | n] Heqn [ | m] Heqm [G1 | [G1 G2]] Heqp [acc] Hf;\n    try destruct Hf as [Hf1 Hf2]; try (exfalso; lia).\n  - apply Hf.\n  - apply Hf.\n  - unfold HMR_dec_formula_aux in *; fold HMR_dec_formula_aux in *.\n    refine (H (modal_complexity_p_hseq G1) _ G1 eq_refl _ eq_refl _ eq_refl _ eq_refl _ _).\n    { rewrite Heqx.\n      apply apply_logical_rule_on_p_hypersequent_correct_inl with n; auto. }\n    refine (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ _ _ Hf).\n  - split.\n    + unfold HMR_dec_formula_aux in *; fold HMR_dec_formula_aux in *.\n      refine (H (modal_complexity_p_hseq G1) _ G1 eq_refl _ eq_refl _ eq_refl _ eq_refl _ _).\n      { rewrite Heqx.\n        apply apply_logical_rule_on_p_hypersequent_correct_inr_l with G2 n; auto. }\n      refine (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ _ _ Hf1).\n    + unfold HMR_dec_formula_aux in *; fold HMR_dec_formula_aux in *.\n      refine (H (modal_complexity_p_hseq G2) _ G2 eq_refl _ eq_refl _ eq_refl _ eq_refl _ _).\n      { rewrite Heqx.\n        apply apply_logical_rule_on_p_hypersequent_correct_inr_r with G1 n; auto. }\n      refine (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ _ _ Hf2).\nQed.\n\nLemma HMR_dec_formula_aux_sem_indep_Heqp : forall val G (n: nat) (Heqn : snd (fst (modal_complexity_p_hseq G)) = n) p (Heqp1 Heqp2 : apply_logical_rule_on_p_hypersequent (p_hseq_put_non_basic_fst G) = p) acc,\n    FOL_R_formula_sem val (HMR_dec_formula_aux G n Heqn p Heqp1 acc) ->\n    FOL_R_formula_sem val (HMR_dec_formula_aux G n Heqn p Heqp2 acc).\nProof.\n  intros val G [ | n] Heqn [G1 | [G1 G2]] Heqp1 Heqp2 [acc] Hf;\n    try destruct Hf as [Hf1 Hf2]; try (exfalso; lia).\n  - apply Hf.\n  - apply Hf.\n  - unfold HMR_dec_formula_aux in *; fold HMR_dec_formula_aux in *.\n    apply (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ _ _ Hf).\n  - split.\n    + unfold HMR_dec_formula_aux in *; fold HMR_dec_formula_aux in *.\n      apply (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ _ _ Hf1).\n    + unfold HMR_dec_formula_aux in *; fold HMR_dec_formula_aux in *.\n      apply (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ _ _ Hf2).\nQed.\n\nLemma HMR_dec_formula_aux_sem_indep_p : forall val G (n: nat) (Heqn : snd (fst (modal_complexity_p_hseq G)) = n) p1 (Heqp1 : apply_logical_rule_on_p_hypersequent (p_hseq_put_non_basic_fst G) = p1) p2 (Heqp2 : apply_logical_rule_on_p_hypersequent (p_hseq_put_non_basic_fst G) = p2) acc,\n    FOL_R_formula_sem val (HMR_dec_formula_aux G n Heqn p1 Heqp1 acc) ->\n    FOL_R_formula_sem val (HMR_dec_formula_aux G n Heqn p2 Heqp2 acc).\nProof.\n  intros val G [ | n] Heqn [G1 | [G1 G2]] Heqp1 [G'1 | [G'1 G'2]] Heqp2 [acc] Hf;\n    try destruct Hf as [Hf1 Hf2]; try (exfalso; rewrite Heqp1 in Heqp2; now inversion Heqp2).\n  - apply Hf.\n  - apply Hf.\n  - assert (G1 = G'1) as H.\n    { clear - Heqp1 Heqp2; rewrite Heqp1 in Heqp2; now inversion Heqp2. }\n    subst.\n    apply (HMR_dec_formula_aux_sem_indep_Heqp _ _ _ _ _ _ _ _ Hf).\n  - assert (G1 = G'1) as H1.\n    { clear - Heqp1 Heqp2; rewrite Heqp1 in Heqp2; now inversion Heqp2. }\n    assert (G2 = G'2) as H2.\n    { clear - Heqp1 Heqp2; rewrite Heqp1 in Heqp2; now inversion Heqp2. }\n    subst.\n    split.\n    + apply (HMR_dec_formula_aux_sem_indep_Heqp _ _ _ _ _ _ _ _ (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ _ _ Hf1)).\n    + apply (HMR_dec_formula_aux_sem_indep_Heqp _ _ _ _ _ _ _ _ (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ _ _ Hf2)).\nQed.\n\nLemma cond_FOL_R_basic_case_aux_no_diamond :\n  forall val (G : p_hypersequent) (V : list (list nat)) (Heqn : max_diamond_p_hseq G = 0%nat) (acc : Acc lt_nat4 (modal_complexity_p_hseq G , length V)),\n    {v & prod (In_inf v V) (FOL_R_formula_sem val (exists_vec (seq (S (max_var_weight_p_hseq G)) (length G)) (FOL_R_phi G v)))} ->\n    FOL_R_formula_sem val (FOL_R_basic_case_aux G V 0%nat Heqn acc).\nProof.\n  intros val G V.\n  induction V as [ | v V]; intros Heqn acc [v0 [Hin Hf]];\n    destruct acc as [acc].\n  - inversion Hin.\n  - inversion Hin; subst.\n    + simpl.\n      left.\n      apply Hf.\n    + simpl; right.\n      apply IHV.\n      split with v0.\n      split; auto.\nQed.\n\nLemma cond_FOL_R_basic_case_aux_diamond :\n  forall val (G : p_hypersequent) (V : list (list nat)) n (Heqn : max_diamond_p_hseq G = S n) (acc : Acc lt_nat4 (modal_complexity_p_hseq G, length V)),\n    { v & { acc' &  prod (In_inf v V)\n                         (FOL_R_formula_sem val (exists_vec (seq (S (max_var_weight_p_hseq G)) (length G))\n                                                             (FOL_R_and\n                                                                (FOL_R_phi G v)\n                                                                (HMR_dec_formula_aux (flat_map (fun i : nat => seq_mul (FOL_R_var (S (max_var_weight_p_hseq G) + i)) (only_diamond_p_seq (nth i G nil))) v :: nil) _ eq_refl _ eq_refl acc'))))} } ->\n    FOL_R_formula_sem val (FOL_R_basic_case_aux G V (S n) Heqn acc).\nProof.\n  intros val G V.\n  induction V; intros n Heqn [acc] [v [acc' [Hin Hf]]].\n  - inversion Hin.\n  - inversion Hin; subst.\n    + left.\n      apply cond_FOL_R_exists_vec_formula_sem.\n      apply cond_FOL_R_exists_vec_formula_sem_inv in Hf as [v' [Hlen [Hf1 Hf2]]].\n      split with v'.\n      split; [ |  split]; auto.\n      apply (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ _ _ Hf2).\n    + right.\n      apply IHV.\n      split with v.\n      split with acc'.\n      repeat split; auto.\nQed.\n\nLemma cond_FOL_R_basic_case_aux_no_diamond_inv :\n  forall val (G : p_hypersequent) (V : list (list nat)) (Heqn : max_diamond_p_hseq G = 0%nat) (acc : Acc lt_nat4 (modal_complexity_p_hseq G , length V)),\n    FOL_R_formula_sem val (FOL_R_basic_case_aux G V 0%nat Heqn acc) ->\n    {v & prod (In_inf v V) (FOL_R_formula_sem val (exists_vec (seq (S (max_var_weight_p_hseq G)) (length G)) (FOL_R_phi G v)))}.\nProof.\n  intros val G V.\n  induction V as [ | v V]; intros Heqn acc Hf;\n    destruct acc as [acc].\n  - inversion Hf.\n  - inversion Hf.\n    + split with v.\n      repeat split; auto.\n      left.\n      reflexivity.\n    + destruct (IHV _ _ X) as [v0 [Hin Hf']].\n      split with v0.\n      repeat split; auto.\n      now right.\nQed.\n\nLemma cond_FOL_R_basic_case_aux_diamond_inv :\n  forall val (G : p_hypersequent) (V : list (list nat)) n (Heqn : max_diamond_p_hseq G = S n) (acc : Acc lt_nat4 (modal_complexity_p_hseq G, length V)),\n    FOL_R_formula_sem val (FOL_R_basic_case_aux G V (S n) Heqn acc) ->\n    { v & { acc' &  prod (In_inf v V)\n                         (FOL_R_formula_sem val (exists_vec (seq (S (max_var_weight_p_hseq G)) (length G))\n                                                             (FOL_R_and\n                                                                (FOL_R_phi G v)\n                                                                (HMR_dec_formula_aux (flat_map (fun i : nat => seq_mul (FOL_R_var (S (max_var_weight_p_hseq G) + i)) (only_diamond_p_seq (nth i G nil))) v :: nil) _ eq_refl _ eq_refl acc'))))} }.\nProof.\n  intros val G V.\n  induction V; intros n Heqn [acc] Hf.\n  - inversion Hf.\n  - inversion Hf.\n    + split with a.\n      split with (wf_lt_nat4 _).\n      apply cond_FOL_R_exists_vec_formula_sem_inv in X as [v [Hin [Hf1 Hf2]]].\n      repeat split.\n      * left; reflexivity.\n      * apply cond_FOL_R_exists_vec_formula_sem.\n        split with v; split; [ | split]; auto.\n        apply (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ _ _ Hf2).\n    + destruct (IHV _ _ _ X) as [v0 [acc' [Hin Hf']]].\n      split with v0.\n      split with acc'.\n      repeat split; auto.\n      now right.\nQed.\n\nLemma cond_HMR_dec_formula_aux_basic :\n  forall val G (Heqx : snd (fst (modal_complexity_p_hseq G)) = 0%nat) p (Heqp : apply_logical_rule_on_p_hypersequent (p_hseq_put_non_basic_fst G) = p) acc1 acc2,\n    FOL_R_formula_sem val (FOL_R_basic_case_aux G (map (@rev nat) (make_subsets (length G))) _ eq_refl acc2) ->\n    FOL_R_formula_sem val (HMR_dec_formula_aux G 0%nat Heqx p Heqp acc1).\nProof.\n  intros val G Heqx p Heqp acc1 acc2 Hf.\n  destruct acc1 as [acc1].\n  simpl.\n  apply (FOL_R_basic_case_aux_sem_indep_acc _ _ _ _ _ _ _ Hf).\nQed.\n\nLemma cond_HMR_dec_formula_aux_inl :\n  forall val G n (Heqx : snd (fst (modal_complexity_p_hseq G)) = S n) G1 (Heqp : apply_logical_rule_on_p_hypersequent (p_hseq_put_non_basic_fst G) = inl G1) acc1 acc2,\n    FOL_R_formula_sem val (HMR_dec_formula_aux G1 _ eq_refl _ eq_refl acc2) ->\n    FOL_R_formula_sem val (HMR_dec_formula_aux G _ Heqx _ Heqp acc1).\nProof.\n  intros val G n heqx G1 Heqp acc1 acc2 Hf.\n  destruct acc1 as [acc1].\n  apply (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ _ _ Hf).\nQed.\n\nLemma cond_HMR_dec_formula_aux_inr :\n  forall val G n (Heqx : snd (fst (modal_complexity_p_hseq G)) = S n) G1 G2 (Heqp : apply_logical_rule_on_p_hypersequent (p_hseq_put_non_basic_fst G) = inr (G1, G2)) acc1 acc2 acc3,\n    FOL_R_formula_sem val (HMR_dec_formula_aux G1 _ eq_refl _ eq_refl acc2) ->\n    FOL_R_formula_sem val (HMR_dec_formula_aux G2 _ eq_refl _ eq_refl acc3) ->\n    FOL_R_formula_sem val (HMR_dec_formula_aux G _ Heqx _ Heqp acc1).\nProof.\n  intros val G n heqx G1 G2 Heqp acc1 acc2 acc3 Hf1 Hf2.\n  destruct acc1 as [acc1].\n  split;\n    [ apply (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ _ _ Hf1)\n    | apply (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ _ _ Hf2) ].\nQed.\n\nLemma cond_HMR_dec_formula_aux_basic_inv :\n  forall val G (Heqx : snd (fst (modal_complexity_p_hseq G)) = 0%nat) p (Heqp : apply_logical_rule_on_p_hypersequent (p_hseq_put_non_basic_fst G) = p) acc1 acc2,\n    FOL_R_formula_sem val (HMR_dec_formula_aux G 0%nat Heqx p Heqp acc1) ->\n    FOL_R_formula_sem val (FOL_R_basic_case_aux G (map (@rev nat) (make_subsets (length G))) _ eq_refl acc2).\nProof.\n  intros val G Heqx p Heqp acc1 acc2 Hf.\n  destruct acc1 as [acc1].\n  simpl.\n  apply (FOL_R_basic_case_aux_sem_indep_acc _ _ _ _ _ _ _ Hf).\nQed.\n\nLemma cond_HMR_dec_formula_aux_inl_inv :\n  forall val G n (Heqx : snd (fst (modal_complexity_p_hseq G)) = S n) G1 (Heqp : apply_logical_rule_on_p_hypersequent (p_hseq_put_non_basic_fst G) = inl G1) acc1 acc2,\n    FOL_R_formula_sem val (HMR_dec_formula_aux G _ Heqx _ Heqp acc1) ->\n    FOL_R_formula_sem val (HMR_dec_formula_aux G1 _ eq_refl _ eq_refl acc2).\nProof.\n  intros val G n heqx G1 Heqp acc1 acc2 Hf.\n  destruct acc1 as [acc1].\n  simpl in Hf.\n  refine (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ _ _ Hf).\nQed.\n\nLemma cond_HMR_dec_formula_aux_inr_inv :\n  forall val G n (Heqx : snd (fst (modal_complexity_p_hseq G)) = S n) G1 G2 (Heqp : apply_logical_rule_on_p_hypersequent (p_hseq_put_non_basic_fst G) = inr (G1, G2)) acc1 acc2 acc3,\n    FOL_R_formula_sem val (HMR_dec_formula_aux G _ Heqx _ Heqp acc1) ->\n    (FOL_R_formula_sem val (HMR_dec_formula_aux G1 _ eq_refl _ eq_refl acc2) *\n     FOL_R_formula_sem val (HMR_dec_formula_aux G2 _ eq_refl _ eq_refl acc3)).\nProof.\n  intros val G n heqx G1 G2 Heqp acc1 acc2 acc3 Hf.\n  destruct acc1 as [acc1].\n  destruct Hf as [Hf1 Hf2].\n  split;\n    [ apply (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ _ _ Hf1)\n    | apply (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ _ _ Hf2) ].\nQed.\n\n(* end hide *)\n\nDefinition FOL_R_basic_case G V := FOL_R_basic_case_aux G V _ eq_refl (wf_lt_nat4 _).\n\nDefinition HMR_dec_formula G := HMR_dec_formula_aux G _ eq_refl _ eq_refl (wf_lt_nat4 _).\n\nLemma cond_FOL_R_basic_case_no_diamond :\n  forall val (G : p_hypersequent) (V : list (list nat)) (Heqn : max_diamond_p_hseq G = 0%nat),\n    {v & prod (In_inf v V) (FOL_R_formula_sem val (exists_vec (seq (S (max_var_weight_p_hseq G)) (length G)) (FOL_R_phi G v)))} ->\n    FOL_R_formula_sem val (FOL_R_basic_case G V).\nProof.\n  intros val G V Heqn H.\n  apply (FOL_R_basic_case_aux_sem_indep_acc _ _ _ _ _ _ _ (FOL_R_basic_case_aux_sem_indep_n _ _ _ _ Heqn _ _ _ (cond_FOL_R_basic_case_aux_no_diamond _ _ _ Heqn (wf_lt_nat4 _) H))).\nQed.\n\nLemma cond_FOL_R_basic_case_diamond :\n  forall val (G : p_hypersequent) (V : list (list nat)) n (Heqn : max_diamond_p_hseq G = S n),\n    { v & prod (In_inf v V)\n               (FOL_R_formula_sem val (exists_vec (seq (S (max_var_weight_p_hseq G)) (length G))\n                                                  (FOL_R_and\n                                                     (FOL_R_phi G v)\n                                                     (HMR_dec_formula (flat_map (fun i : nat => seq_mul (FOL_R_var (S (max_var_weight_p_hseq G) + i)) (only_diamond_p_seq (nth i G nil))) v :: nil))))) }->\n    FOL_R_formula_sem val (FOL_R_basic_case G V).\nProof.\n  intros val G V n Heqn [v [Hin Hf]].\n  refine (FOL_R_basic_case_aux_sem_indep_acc _ _ _ _ _ _ _ (FOL_R_basic_case_aux_sem_indep_n _ _ _ _ Heqn _ _ _ (cond_FOL_R_basic_case_aux_diamond _ _ _ _ Heqn (wf_lt_nat4 _) _))).\n  split with v.\n  split with (wf_lt_nat4 _).\n  split; auto.\nQed.\n\nLemma cond_FOL_R_basic_case_no_diamond_inv :\n  forall val (G : p_hypersequent) (V : list (list nat)) (Heqn : max_diamond_p_hseq G = 0%nat),\n    FOL_R_formula_sem val (FOL_R_basic_case G V) ->\n    {v & prod (In_inf v V) (FOL_R_formula_sem val (exists_vec (seq (S (max_var_weight_p_hseq G)) (length G)) (FOL_R_phi G v)))}.\nProof.\n  intros val G V Heqn Hf.\n  apply (cond_FOL_R_basic_case_aux_no_diamond_inv _ _ _ Heqn (wf_lt_nat4 _)).\n  apply (FOL_R_basic_case_aux_sem_indep_n _ _ _ _ _ _ _ _ Hf).\nQed.\n\nLemma cond_FOL_R_basic_case_diamond_inv :\n  forall val (G : p_hypersequent) (V : list (list nat)) n (Heqn : max_diamond_p_hseq G = S n),\n    FOL_R_formula_sem val (FOL_R_basic_case G V) ->\n    { v & prod (In_inf v V)\n               (FOL_R_formula_sem val (exists_vec (seq (S (max_var_weight_p_hseq G)) (length G))\n                                                  (FOL_R_and\n                                                     (FOL_R_phi G v)\n                                                     (HMR_dec_formula (flat_map (fun i : nat => seq_mul (FOL_R_var (S (max_var_weight_p_hseq G) + i)) (only_diamond_p_seq (nth i G nil))) v :: nil))))) }.\nProof.\n  intros val G V n Heqn Hf.\n  destruct (cond_FOL_R_basic_case_aux_diamond_inv val _ V _ Heqn (wf_lt_nat4 _)) as [v [acc [Hin Hf']]].\n  { apply (FOL_R_basic_case_aux_sem_indep_n _ _ _ _ _ _ _ _ Hf). }\n  split with v.\n  repeat split; auto.\n  apply cond_FOL_R_exists_vec_formula_sem_inv in Hf' as [v' [Hin' [Hf1 Hf2]]].\n  apply cond_FOL_R_exists_vec_formula_sem.\n  split with v'; split ; [ | split]; auto.\n  apply (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ _ _ Hf2).\nQed.\n\nLemma cond_HMR_dec_formula_basic :\n  forall val G (Heqx : snd (fst (modal_complexity_p_hseq G)) = 0%nat),\n    FOL_R_formula_sem val (FOL_R_basic_case G (map (@rev nat) (make_subsets (length G)))) ->\n    FOL_R_formula_sem val (HMR_dec_formula G).\nProof.\n  intros val G Heqn Hf.\n  unfold HMR_dec_formula.\n  refine (HMR_dec_formula_aux_sem_indep_n _ _ _ _ _ _ _ _ _ (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ _ _ (cond_HMR_dec_formula_aux_basic val G Heqn _ eq_refl _ _ Hf))).\n  apply wf_lt_nat4.\nQed.\n\nLemma cond_HMR_dec_formula_inl :\n  forall val G n (Heqx : snd (fst (modal_complexity_p_hseq G)) = S n) G1 (Heqp : apply_logical_rule_on_p_hypersequent (p_hseq_put_non_basic_fst G) = inl G1),\n    FOL_R_formula_sem val (HMR_dec_formula G1) ->\n    FOL_R_formula_sem val (HMR_dec_formula G).\nProof.\n  intros val G n Heqx G1 Heqp Hf.\n  unfold HMR_dec_formula in *.\n  apply HMR_dec_formula_aux_sem_indep_n with (S n) Heqx.\n  refine (HMR_dec_formula_aux_sem_indep_p _ _ _ _ _ _ _ _ _ (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ _ _ (cond_HMR_dec_formula_aux_inl _ _ _ _ _ _ _ _ Hf))); auto.\n  apply wf_lt_nat4.\nQed.\n\nLemma cond_HMR_dec_formula_inr :\n  forall val G n (Heqx : snd (fst (modal_complexity_p_hseq G)) = S n) G1 G2 (Heqp : apply_logical_rule_on_p_hypersequent (p_hseq_put_non_basic_fst G) = inr (G1, G2)),\n    FOL_R_formula_sem val (HMR_dec_formula G1) ->\n    FOL_R_formula_sem val (HMR_dec_formula G2) ->\n    FOL_R_formula_sem val (HMR_dec_formula G).\nProof.\n  intros val G n Heqx G1 G2 Heqp Hf1 Hf2.\n  unfold HMR_dec_formula in *.\n  apply HMR_dec_formula_aux_sem_indep_n with (S n) Heqx.\n  refine (HMR_dec_formula_aux_sem_indep_p _ _ _ _ _ _ _ _ _ (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ _ _ (cond_HMR_dec_formula_aux_inr _ _ _ _ _ _ _ _ _ _ Hf1 Hf2))); auto.\n  apply wf_lt_nat4.\nQed.\n\nLemma cond_HMR_dec_formula_basic_inv :\n  forall val G (Heqx : snd (fst (modal_complexity_p_hseq G)) = 0%nat),\n    FOL_R_formula_sem val (HMR_dec_formula G) ->\n    FOL_R_formula_sem val (FOL_R_basic_case G (map (@rev nat) (make_subsets (length G)))).\nProof.\n  intros val G Heqx Hf.\n  unfold HMR_dec_formula in Hf.\n  apply HMR_dec_formula_aux_sem_indep_n with _ _ _ _ _ Heqx _ _ _ in Hf.\n  remember (wf_lt_nat4 (modal_complexity_p_hseq G, S (length (make_subsets (length G))))).\n  destruct a.\n  refine (FOL_R_basic_case_aux_sem_indep_acc _ _ _ _ _ _ _ Hf).\nQed.\n\nLemma cond_HMR_dec_formula_inl_inv :\n  forall val G n (Heqx : snd (fst (modal_complexity_p_hseq G)) = S n) G1 (Heqp : apply_logical_rule_on_p_hypersequent (p_hseq_put_non_basic_fst G) = inl G1),\n    FOL_R_formula_sem val (HMR_dec_formula G) ->\n    FOL_R_formula_sem val (HMR_dec_formula G1).\nProof.\n  intros val G n Heqx G1 Heqp Hf.\n  unfold HMR_dec_formula in *.\n  apply HMR_dec_formula_aux_sem_indep_n with _ _ _ _ (S n) Heqx _ _ _ in Hf.\n  apply HMR_dec_formula_aux_sem_indep_p with _ _ _ _ _ _ _ Heqp _ in Hf.\n  refine (cond_HMR_dec_formula_aux_inl_inv _ _ _ _ _ _ _ _ (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ _ _ Hf)); auto.\n  apply wf_lt_nat4.\nQed.\n\nLemma cond_HMR_dec_formula_inr_inv :\n  forall val G n (Heqx : snd (fst (modal_complexity_p_hseq G)) = S n) G1 G2 (Heqp : apply_logical_rule_on_p_hypersequent (p_hseq_put_non_basic_fst G) = inr (G1, G2)),\n    FOL_R_formula_sem val (HMR_dec_formula G) ->\n    (FOL_R_formula_sem val (HMR_dec_formula G1) *\n     FOL_R_formula_sem val (HMR_dec_formula G2)).\nProof.\n  intros val G n Heqx G1 G2 Heqp Hf.\n  unfold HMR_dec_formula in *.\n  apply HMR_dec_formula_aux_sem_indep_n with _ _ _ _ (S n) Heqx _ _ _ in Hf.\n  apply HMR_dec_formula_aux_sem_indep_p with _ _ _ _ _ _ _ Heqp _ in Hf.\n  refine (cond_HMR_dec_formula_aux_inr_inv _ _ _ _ _ _ _ _ _ _ (HMR_dec_formula_aux_sem_indep_acc _ _ _ _ _ _ _ _ Hf)).\n  apply wf_lt_nat4.\nQed.\n\nLemma FOL_R_basic_case_1\n      val\n      (G : p_hypersequent)\n      (Hwd : p_hseq_well_defined val G)\n      (Hb : p_hseq_is_basic G)\n      (pi : HMR_T (map (eval_p_sequent val) G))\n      (acc : Acc lt_nat4 (modal_complexity_p_hseq G, 0%nat)) :\n  FOL_R_formula_sem val (FOL_R_basic_case G (map (@rev nat) (make_subsets (length G))))\nwith HMR_dec_formula_1\n       val\n       (G : p_hypersequent)\n       (Hwd : p_hseq_well_defined val G)\n       (pi : HMR_T (map (eval_p_sequent val) G))\n       (acc : Acc lt_nat4 (modal_complexity_p_hseq G, 1%nat)) :\n       FOL_R_formula_sem val (HMR_dec_formula G).\nProof.\n  - destruct acc as [acc].\n    remember (max_diamond_p_hseq G); symmetry in Heqn.\n    destruct n;\n      (apply HMR_le_frag with _ hmr_frag_T_M _ in pi; \n       [ | repeat split; auto]);\n      destruct (lambda_prop _ (p_hseq_basic_hseq_basic _ _ Hb) pi) as [L [Hlen [[[Hex Hsum] Hone] Hstep]]].\n    + apply cond_FOL_R_basic_case_no_diamond; auto.\n      split with (pos_indexes L).\n      split.\n      { rewrite <- (rev_involutive (pos_indexes L)).\n        apply in_inf_map.\n        apply cond_is_in_make_subsets.\n        - clear - Hex.\n          apply rev_not_nil.\n          induction L; [inversion Hex | ].\n          inversion Hex; subst.\n          + destruct a ; [ | exfalso; now apply H0 ].\n            intros H; inversion H.\n          + destruct a; [ intros H; inversion H | ].\n            simpl.\n            intros H'; apply map_eq_nil in H'.\n            apply IHL; assumption.\n        - intros i.\n          case_eq (i <? length (rev (pos_indexes L)))%nat.\n          + intros Hlt; apply Nat.ltb_lt in Hlt.\n            apply Forall_inf_nth; try assumption.\n            rewrite map_length in Hlen.\n            rewrite <- Hlen.\n            apply Forall_inf_rev.\n            apply pos_indexes_Forall_inf.\n          + intros Hlt; apply Nat.ltb_nlt in Hlt; rewrite nth_overflow; destruct G; simpl; try lia.\n            apply HMR_not_empty in pi.\n            exfalso; auto.            \n        - intros i j Hlen' Hlt'.\n          apply rev_reverse_order_lt; try lia.\n          apply pos_indexes_order. }\n      apply cond_FOL_R_exists_vec_formula_sem.\n      split with (map oRpos_to_R L).\n      split; [ rewrite map_length in Hlen; rewrite map_length; rewrite seq_length; symmetry; apply Hlen | ].\n      repeat split.\n      * apply cond_FOL_R_all_zero_formula_sem.\n        intros n Hin.\n        rewrite map_length in Hlen; rewrite <- Hlen.\n        rewrite <- (map_length oRpos_to_R L).\n        rewrite upd_val_vec_eq.\n        rewrite nth_indep with _ _ _ _ (oRpos_to_R None).\n        2:{ rewrite map_length; rewrite Hlen; apply (In_inf_complementary_lt _ _ _ Hin). }\n        rewrite map_nth.\n        rewrite pos_indexes_not_In_inf; auto.\n        { rewrite Hlen; apply (In_inf_complementary_lt _ _ _ Hin). }\n        intros Hin'.\n        apply In_inf_complementary2 with (pos_indexes L) (length G) n; auto.\n      * apply cond_FOL_R_all_gtz_formula_sem.\n        intros n Hin.\n        change (list (prod Rpos term)) with sequent.\n        rewrite map_length in Hlen; rewrite <- Hlen.\n        rewrite <- (map_length oRpos_to_R L).\n        rewrite upd_val_vec_eq.\n        assert (n < length L)%nat as Hlt.\n        { apply (@Forall_inf_forall _ (fun x => x < length L)%nat) with (pos_indexes L); [ apply pos_indexes_Forall_inf | ].\n          apply Hin. }\n        rewrite nth_indep with _ _ _ _ (oRpos_to_R None); auto.\n        2:{ rewrite map_length; apply Hlt. }\n        rewrite map_nth.\n        destruct (pos_indexes_nth L n) as [[r Hr] Heq].\n        { apply Hin. }\n        rewrite Heq; simpl.\n        clear - Hr; apply R_blt_lt in Hr; apply Hr.\n      * apply cond_FOL_R_all_atoms_eq_formula_sem.\n        intros n Hlen'.\n        rewrite map_length in Hlen; rewrite <- Hlen.\n        simpl.\n        specialize (Hsum n).\n        rewrite sum_weight_with_coeff_eq_var_covar in Hsum.\n        rewrite (sum_weight_with_coeff_eval_eq val n G L) in Hsum.\n        lra.\n      * rewrite map_length in Hlen.\n        simpl.\n        rewrite sum_weight_with_coeff_eq_one_coone in Hone.\n        rewrite (sum_weight_with_coeff_one_eval_eq val G L) in Hone.\n        rewrite <- Hlen.\n        lra.\n    + apply cond_FOL_R_basic_case_diamond with n; auto.\n      split with (pos_indexes L).\n      split.\n      { rewrite <- (rev_involutive (pos_indexes L)).\n        apply in_inf_map.\n        apply cond_is_in_make_subsets.\n        - apply rev_not_nil.\n          clear - Hex.\n          induction L; [inversion Hex | ].\n          inversion Hex; subst.\n          + destruct a ; [ | exfalso; now apply H0 ].\n            intros H; inversion H.\n          + destruct a; [ intros H; inversion H | ].\n            simpl.\n            intros H'; apply map_eq_nil in H'.\n            apply IHL; assumption.\n        - intros i.\n          apply rev_nth_all_lt.\n          clear i.\n          intros i.\n          case_eq (i <? length (pos_indexes L))%nat.\n          + intros Hlt; apply Nat.ltb_lt in Hlt.\n            apply Forall_inf_nth; try assumption.\n            rewrite map_length in Hlen.\n            rewrite <- Hlen.\n            apply pos_indexes_Forall_inf.\n          + intros Hlt; apply Nat.ltb_nlt in Hlt; rewrite nth_overflow; destruct G; simpl; try lia.\n            apply HMR_not_empty in pi.\n            exfalso; auto.            \n        - intros i j Hlen' Hlt'.\n          apply rev_reverse_order_lt; try lia.\n          apply pos_indexes_order. }\n      apply cond_FOL_R_exists_vec_formula_sem.\n      split with (map oRpos_to_R L).\n      split; [ rewrite map_length in Hlen; rewrite map_length; rewrite seq_length; symmetry; apply Hlen | ].\n      split.\n      * repeat split.\n        -- apply cond_FOL_R_all_zero_formula_sem.\n           intros m Hin.\n           rewrite map_length in Hlen; rewrite <- Hlen.\n           rewrite <- (map_length oRpos_to_R L).\n           rewrite upd_val_vec_eq.\n           rewrite nth_indep with _ _ _ _ (oRpos_to_R None).\n           2:{ rewrite map_length; rewrite Hlen; apply (In_inf_complementary_lt _ _ _ Hin). }\n           rewrite map_nth.\n           rewrite pos_indexes_not_In_inf; auto.\n           { rewrite Hlen; apply (In_inf_complementary_lt _ _ _ Hin). }\n           intros Hin'.\n           apply In_inf_complementary2 with (pos_indexes L) (length G) m; auto.\n        -- apply cond_FOL_R_all_gtz_formula_sem.\n           intros m Hin.\n           change (list (prod Rpos term)) with sequent.\n           rewrite map_length in Hlen; rewrite <- Hlen.\n           rewrite <- (map_length oRpos_to_R L).\n           rewrite upd_val_vec_eq.\n           assert (m < length L)%nat as Hlt.\n           { apply (@Forall_inf_forall _ (fun x => x < length L)%nat) with (pos_indexes L); [ apply pos_indexes_Forall_inf | ].\n             apply Hin. }\n           rewrite nth_indep with _ _ _ _ (oRpos_to_R None); auto.\n           2:{ rewrite map_length; apply Hlt. }\n           rewrite map_nth.\n           destruct (pos_indexes_nth L m) as [[r Hr] Heq].\n           { apply Hin. }\n           rewrite Heq; simpl.\n           clear - Hr; apply R_blt_lt in Hr; apply Hr.\n        -- apply cond_FOL_R_all_atoms_eq_formula_sem.\n           intros m Hlen'.\n           rewrite map_length in Hlen; rewrite <- Hlen.\n           simpl.\n           specialize (Hsum m).\n           rewrite sum_weight_with_coeff_eq_var_covar in Hsum.\n           rewrite (sum_weight_with_coeff_eval_eq val m G L) in Hsum.\n           lra.\n        -- simpl.\n           rewrite map_length in Hlen; rewrite <- Hlen.\n           rewrite sum_weight_with_coeff_eq_one_coone in Hone.\n           rewrite (sum_weight_with_coeff_one_eval_eq val G L) in Hone.\n           lra.\n      * refine (HMR_dec_formula_1 (upd_val_vec val (seq  _ _) _) _ _ _ _).\n        -- rewrite flat_map_concat_map.\n           apply Forall_inf_cons ; [ | apply Forall_inf_nil].\n           apply forall_Forall_inf.\n           intros A HinA.\n           apply In_inf_concat in HinA as [l [Hin1 Hin2]].\n           apply in_inf_map_inv in Hin1 as [i Heq Hin3].\n           rewrite <- Heq in Hin2.\n           apply In_inf_seq_mul in Hin2 as [[b B] [HeqB HinB]].\n           rewrite HeqB.\n           simpl.\n           rewrite map_length in Hlen.\n           rewrite <- Hlen.\n           rewrite <- map_length with _ _ oRpos_to_R _.\n           change (S (max_var_weight_p_hseq G + i)) with ((S (max_var_weight_p_hseq G)) + i)%nat.\n           rewrite upd_val_vec_eq.\n           rewrite FOL_R_term_sem_upd_val_vec_lt.\n           2:{ apply forall_Forall_inf.\n               intros x Hinx.\n               apply Nat.lt_le_trans with (S (max_var_weight_p_hseq G)).\n               - apply Nat.le_lt_trans with (max_var_weight_p_seq (only_diamond_p_seq (nth i G nil))).\n                 + apply max_var_FOL_R_term_In_inf_p_seq with B; auto.\n                 + apply Nat.le_lt_trans with (max_var_weight_p_seq (nth i G nil)) ; [ apply max_var_weight_p_seq_only_diamond | ].\n                   apply Nat.le_lt_trans with (max_var_weight_p_hseq G) ; [ | lia ].\n                   apply max_var_weight_p_seq_In_inf_p_hseq.\n                   apply nth_In_inf.\n                   rewrite <- Hlen.\n                   apply In_inf_pos_indexes; auto.\n               - apply (In_inf_seq_le_start _ _ _ Hinx). }\n           apply R_blt_lt.\n           apply Rmult_lt_0_compat.\n           ++ rewrite nth_indep with _ _ _ _ (oRpos_to_R None).\n              2:{ rewrite map_length.\n                  apply In_inf_pos_indexes; auto. }\n              rewrite map_nth.\n              destruct (pos_indexes_nth _ _ Hin3) as [[r Hr] Heqr].\n              rewrite Heqr; simpl.\n              clear - Hr; apply R_blt_lt in Hr; apply Hr.\n           ++ change b with (fst (b , B)).\n              apply R_blt_lt.\n              refine (@Forall_inf_forall _ (fun x => (0 <? FOL_R_term_sem val (fst x)) = true) (only_diamond_p_seq (nth i G nil)) _ (b, B) _); auto.\n              apply p_seq_well_defined_only_diamond.\n              refine (@Forall_inf_forall _ (p_seq_well_defined val) G _ (nth i G nil) _); auto.\n              apply nth_In_inf.\n              rewrite <- Hlen.\n              apply In_inf_pos_indexes; auto. \n        -- replace (fun i : nat => seq_mul (FOL_R_var i) (only_diamond_p_seq (nth i G nil)))\n             with (fun i : nat => seq_mul (FOL_R_var i) (nth i (only_diamond_p_hseq G) nil)).\n           2:{ apply functional_extensionality.\n               intros x.\n               rewrite <- (map_nth only_diamond_p_seq); reflexivity. }\n           simpl; rewrite map_length in Hlen; rewrite <- Hlen.\n           replace (flat_map\n                      (fun i : nat =>\n                         seq_mul (FOL_R_var (S (max_var_weight_p_hseq G + i)))\n                                 (only_diamond_p_seq (nth i G nil))) (pos_indexes L))\n             with (flat_map\n                     (fun i : nat =>\n                        seq_mul (FOL_R_var ((S (max_var_weight_p_hseq G)) + i))\n                                ((nth i (only_diamond_p_hseq G) nil))) (pos_indexes L)).\n           2:{ apply flat_map_ext.\n               intros a.\n               rewrite <- (map_nth _ G nil).\n               reflexivity. }\n           rewrite eval_p_seq_upd_val_vec_nth.\n           ++ apply hmrr_M_elim; rewrite  <- only_diamond_eval_p_hseq; apply Hstep.\n           ++ change (only_diamond_p_hseq G) with (map only_diamond_p_seq G).\n              rewrite map_length.\n              symmetry; apply Hlen.\n           ++ apply Nat.le_lt_trans with (max_var_weight_p_hseq G); try lia.\n              rewrite max_var_weight_p_hseq_only_diamond.\n              apply Nat.le_refl.\n        -- apply acc.\n           apply fst_lt4.\n           rewrite Heqn.\n           rewrite flat_map_concat_map.\n           simpl.\n           rewrite Nat.max_0_r.\n           apply max_diamond_p_seq_concat.\n           apply forall_Forall_inf.\n           intros x Hinx.\n           apply in_inf_map_inv in Hinx as [i Heq Hini].\n           rewrite <- Heq.\n           rewrite max_diamond_seq_mul.\n           rewrite <- Heqn.\n           rewrite <- map_nth.\n           apply Nat.le_lt_trans with (max_diamond_p_hseq (map only_diamond_p_seq G)).\n           ++ apply max_diamond_nth.\n           ++ apply max_diamond_only_diamond_p_hseq_lt.\n              lia.\n  - destruct acc as [acc].\n    remember (snd (fst (modal_complexity_p_hseq G))).\n    destruct n;\n      [ |\n        remember (apply_logical_rule_on_p_hypersequent (p_hseq_put_non_basic_fst G)) ].\n    + apply cond_HMR_dec_formula_basic; auto.\n      refine (FOL_R_basic_case_1 val G Hwd _ pi _).\n      { apply p_hseq_is_basic_complexity_0_inv; auto. }\n      apply acc.\n      apply fth_lt4.\n      lia.\n    + destruct s as [G1 | [G1 G2] ].\n      * apply (cond_HMR_dec_formula_inl val G n (eq_sym Heqn) G1 (eq_sym Heqs)).\n        refine (HMR_dec_formula_1 val G1 _ _ _).\n        -- eapply apply_logical_rule_on_p_hypersequent_inl_well_defined; [ symmetry; apply Heqs | ].\n           apply p_hseq_put_non_basic_fst_well_defined; auto.\n           simpl in Heqn; rewrite <- Heqn; lia.\n        -- apply hmrr_M_elim.\n           eapply apply_logical_rule_on_p_hypersequent_inl_HMR; [ symmetry; apply Heqs | | ].\n           ++ apply p_hseq_put_non_basic_fst_well_defined; auto.\n              simpl in Heqn; rewrite <- Heqn; lia.\n           ++ unfold p_hseq_put_non_basic_fst.\n              rewrite map_cons.\n              apply hmrr_ex_seq with (eval_p_sequent val (p_hseq_p_seq_max_complexity G)).\n              { apply Permutation_Type_eval_p_sequent.\n                apply p_seq_put_non_basic_fst.\n                intros H.\n                apply p_seq_is_basic_complexity_0 in H.\n                rewrite p_hseq_p_seq_max_complexity_correct in H.\n                simpl in *; lia. }\n              apply hmrr_ex_hseq with (map (eval_p_sequent val) G); auto ; [ | eapply HMR_le_frag ; [ | apply pi]; repeat split; auto ].\n              rewrite <- map_cons.\n              apply Permutation_Type_map.\n              apply p_hseq_put_max_complexity_fst.\n              intros H; rewrite H in Heqn; inversion Heqn.\n        -- apply acc.\n           apply lt_nat3_to_lt_nat4.\n           apply (apply_logical_rule_on_p_hypersequent_correct_inl G G1 n (eq_sym Heqn) (eq_sym Heqs)).\n      * apply (cond_HMR_dec_formula_inr val G n (eq_sym Heqn) G1 G2 (eq_sym Heqs)).\n        -- refine (HMR_dec_formula_1 val G1 _ _ _).\n           ++ eapply apply_logical_rule_on_p_hypersequent_inr_l_well_defined; [ symmetry; apply Heqs | ].\n              apply p_hseq_put_non_basic_fst_well_defined; auto.\n              simpl in Heqn; rewrite <- Heqn; lia.\n           ++ apply hmrr_M_elim.\n              eapply apply_logical_rule_on_p_hypersequent_inr_l_HMR; [ symmetry; apply Heqs | | ].\n              ** apply p_hseq_put_non_basic_fst_well_defined; auto.\n                 simpl in Heqn; rewrite <- Heqn; lia.\n              ** unfold p_hseq_put_non_basic_fst.\n                 rewrite map_cons.\n                 apply hmrr_ex_seq with (eval_p_sequent val (p_hseq_p_seq_max_complexity G)).\n                 { apply Permutation_Type_eval_p_sequent.\n                   apply p_seq_put_non_basic_fst.\n                   intros H.\n                   apply p_seq_is_basic_complexity_0 in H.\n                   rewrite p_hseq_p_seq_max_complexity_correct in H.\n                   simpl in *; lia. }\n                 apply hmrr_ex_hseq with (map (eval_p_sequent val) G); auto ; [ | eapply HMR_le_frag ; [ | apply pi]; repeat split; auto ].\n                 rewrite <- map_cons.\n                 apply Permutation_Type_map.\n                 apply p_hseq_put_max_complexity_fst.\n                 intros H; rewrite H in Heqn; inversion Heqn.\n           ++ apply acc.\n              apply lt_nat3_to_lt_nat4.\n              apply (apply_logical_rule_on_p_hypersequent_correct_inr_l G G1 G2 n (eq_sym Heqn) (eq_sym Heqs)).\n        -- refine (HMR_dec_formula_1 val G2 _ _ _).\n           ++ eapply apply_logical_rule_on_p_hypersequent_inr_r_well_defined; [ symmetry; apply Heqs | ].\n              apply p_hseq_put_non_basic_fst_well_defined; auto.\n              simpl in Heqn; rewrite <- Heqn; lia.\n           ++ apply hmrr_M_elim.\n              eapply apply_logical_rule_on_p_hypersequent_inr_r_HMR; [ symmetry; apply Heqs | | ].\n              ** apply p_hseq_put_non_basic_fst_well_defined; auto.\n                 simpl in Heqn; rewrite <- Heqn; lia.\n              ** unfold p_hseq_put_non_basic_fst.\n                 rewrite map_cons.\n                 apply hmrr_ex_seq with (eval_p_sequent val (p_hseq_p_seq_max_complexity G)).\n                 { apply Permutation_Type_eval_p_sequent.\n                   apply p_seq_put_non_basic_fst.\n                   intros H.\n                   apply p_seq_is_basic_complexity_0 in H.\n                   rewrite p_hseq_p_seq_max_complexity_correct in H.\n                   simpl in *; lia. }\n                 apply hmrr_ex_hseq with (map (eval_p_sequent val) G); auto ; [ | eapply HMR_le_frag ; [ | apply pi]; repeat split; auto ].\n                 rewrite <- map_cons.\n                 apply Permutation_Type_map.\n                 apply p_hseq_put_max_complexity_fst.\n                 intros H; rewrite H in Heqn; inversion Heqn.\n           ++ apply acc.\n              apply lt_nat3_to_lt_nat4.\n              apply (apply_logical_rule_on_p_hypersequent_correct_inr_r G G1 G2 n (eq_sym Heqn) (eq_sym Heqs)).\nQed.\n\nLemma FOL_R_basic_case_2\n      val\n      (G : p_hypersequent)\n      (Hwd : p_hseq_well_defined val G)\n      (Hb : p_hseq_is_basic G)\n      (Hf : FOL_R_formula_sem val (FOL_R_basic_case G (map (@rev nat) (make_subsets (length G)))))\n      (acc : Acc lt_nat4 (modal_complexity_p_hseq G, 0%nat)) :\n  HMR_T (map (eval_p_sequent val) G)\nwith HMR_dec_formula_2\n       val\n       (G : p_hypersequent)\n       (Hwd : p_hseq_well_defined val G)\n       (Hf : FOL_R_formula_sem val (HMR_dec_formula G))\n       (acc : Acc lt_nat4 (modal_complexity_p_hseq G, 1%nat)) :\n       HMR_T (map (eval_p_sequent val) G).\nProof.\n  - destruct acc as [acc].\n    remember (max_diamond_p_hseq G).\n    destruct n.\n    + apply cond_FOL_R_basic_case_no_diamond_inv in Hf; auto.\n      destruct Hf as [vx [Hinvx Hf]].\n      apply cond_FOL_R_exists_vec_formula_sem_inv in Hf as [vr [Hlen [Hf1 [Hf2 [Hf3 Hf4]]]]].\n      apply hmrr_M_elim.\n      apply lambda_prop_inv ; [apply p_hseq_basic_hseq_basic; auto | ].\n      split with (map (fun x => eval_to_oRpos (upd_val_vec val (seq (S (max_var_weight_p_hseq G)) (length G)) vr) (FOL_R_var x)) (seq (S (max_var_weight_p_hseq G)) (length G))).\n      repeat split.\n      * rewrite ? map_length.\n        rewrite seq_length; auto.\n      * apply in_inf_map_inv in Hinvx as [vxr Heq Hin].\n        apply cond_is_in_make_subsets_inv in Hin as [[Hnnil Hle] Hlt].\n        destruct vxr ; [ exfalso; apply Hnnil; auto | ].\n        apply nth_Exists_inf with n None.\n        -- rewrite map_length.\n           rewrite seq_length.\n           apply (Hle 0)%nat.\n        -- rewrite nth_indep with _ _ _ _ ((fun x => eval_to_oRpos (upd_val_vec val (seq (S (max_var_weight_p_hseq G)) (length G)) vr) (FOL_R_var x)) 0%nat).\n           2:{ rewrite map_length.\n               rewrite seq_length.\n               apply (Hle 0)%nat. }\n           rewrite (map_nth (fun x => eval_to_oRpos (upd_val_vec val (seq (S (max_var_weight_p_hseq G)) (length G)) vr) (FOL_R_var x))).\n           apply cond_FOL_R_all_gtz_formula_sem_inv with _ _ _ n in Hf2.\n           2:{ rewrite <- Heq.\n               apply in_inf_rev.\n               left; auto. }\n           unfold eval_to_oRpos.\n           simpl.\n           rewrite seq_nth.\n           2:{ apply (Hle 0)%nat. }\n           unfold R_to_oRpos.\n           case (R_order_dec\n                      (upd_val_vec val (seq (S (max_var_weight_p_hseq G)) (length G)) vr\n                                   (S (max_var_weight_p_hseq G) + n)));\n             intros e; try (exfalso; try apply R_blt_lt in e; lra).\n           intros H; inversion H.\n      * intros n.\n        case_eq (n <=? max_var_p_hseq G)%nat; intros Hle.\n        -- apply cond_FOL_R_all_atoms_eq_formula_sem_inv with _ _ _ n in Hf3 ; [ | apply Nat.leb_le in Hle; auto].\n           replace (map\n                     (fun x : nat =>\n                        eval_to_oRpos (upd_val_vec val (seq (S (max_var_weight_p_hseq G)) (length G)) vr)\n                                      (FOL_R_var x)) (seq (S (max_var_weight_p_hseq G)) (length G))) with\n               (map (eval_to_oRpos (upd_val_vec val (seq (S (max_var_weight_p_hseq G)) (length G)) vr)) (map FOL_R_var (seq (S (max_var_weight_p_hseq G)) (length G)))) by (now rewrite map_map).\n           simpl in Hf3.\n           apply Rminus_diag_eq in Hf3.\n           rewrite FOL_R_term_sem_eval_p_hseq in Hf3.\n           2:{ apply forall_Forall_inf.\n               intros x Hinx.\n               apply in_inf_map_inv in Hinx as [i Heqi Hini].\n               apply In_inf_nth with _ _ _ 0%nat in Hini as [k Hltk Heqk].\n               rewrite <- Heqi; rewrite <- Heqk.\n               rewrite seq_length in Hlen.\n               rewrite Hlen.\n               rewrite seq_nth.\n               2:{ rewrite <- Hlen.\n                   rewrite seq_length in Hltk.\n                   apply Hltk. }\n               simpl.\n               rewrite <- Nat.add_succ_l.\n               rewrite (upd_val_vec_eq vr val k (S (max_var_weight_p_hseq G))).\n               destruct (in_inf_dec Nat.eq_dec k vx); auto.\n               - apply cond_FOL_R_all_gtz_formula_sem_inv with _ _ _ k in Hf2; auto.\n                 rewrite Hlen in Hf2.\n                 rewrite upd_val_vec_eq in Hf2.\n                 lra.\n               - apply cond_FOL_R_all_zero_formula_sem_inv with _ _ _ k in Hf1.\n                 2:{ apply In_inf_complementary2_inv; auto.\n                     rewrite seq_length in Hltk.\n                     apply Hltk. }\n                 rewrite Hlen in Hf1.\n                 rewrite upd_val_vec_eq in Hf1.\n                 lra. }\n           rewrite sum_weight_with_coeff_eq_var_covar.\n           replace (map (eval_p_sequent (upd_val_vec val (seq (S (max_var_weight_p_hseq G)) (length G)) vr)) G) with (map (eval_p_sequent val) G) in Hf3; auto.\n           symmetry; apply eval_p_hseq_upd_val_vec_lt.\n           apply forall_Forall_inf.\n           intros x Hinx.\n           apply In_inf_seq_le_start in Hinx.\n           lia.\n        -- apply Nat.leb_nle in Hle.\n           clear - Hle.\n           rewrite sum_weight_with_coeff_eq_var_covar.\n           assert (H := max_var_hseq_le_p_hseq val G).\n           rewrite sum_weight_var_with_coeff_lt_max_var; [ | lia ].\n           rewrite sum_weight_covar_with_coeff_lt_max_var; [ | lia ].\n           lra.\n      * replace (map\n                   (fun x : nat =>\n                      eval_to_oRpos (upd_val_vec val (seq (S (max_var_weight_p_hseq G)) (length G)) vr)\n                                    (FOL_R_var x)) (seq (S (max_var_weight_p_hseq G)) (length G))) with\n            (map (eval_to_oRpos (upd_val_vec val (seq (S (max_var_weight_p_hseq G)) (length G)) vr)) (map FOL_R_var (seq (S (max_var_weight_p_hseq G)) (length G)))) by (now rewrite map_map).\n        simpl in Hf4.\n        apply Rminus_diag_le in Hf4.\n        rewrite FOL_R_term_sem_eval_p_hseq_one in Hf4.\n        2:{ apply forall_Forall_inf.\n            intros x Hinx.\n            apply in_inf_map_inv in Hinx as [i Heqi Hini].\n            apply In_inf_nth with _ _ _ 0%nat in Hini as [k Hltk Heqk].\n            rewrite <- Heqi; rewrite <- Heqk.\n            rewrite seq_length in Hlen.\n            rewrite Hlen.\n            rewrite seq_nth.\n            2:{ rewrite <- Hlen.\n                rewrite seq_length in Hltk.\n                apply Hltk. }\n            simpl.\n            rewrite <- Nat.add_succ_l.\n            rewrite (upd_val_vec_eq vr val k (S (max_var_weight_p_hseq G))).\n            destruct (in_inf_dec Nat.eq_dec k vx); auto.\n            - apply cond_FOL_R_all_gtz_formula_sem_inv with _ _ _ k in Hf2; auto.\n              rewrite Hlen in Hf2.\n              rewrite upd_val_vec_eq in Hf2.\n              lra.\n            - apply cond_FOL_R_all_zero_formula_sem_inv with _ _ _ k in Hf1.\n              2:{ apply In_inf_complementary2_inv; auto.\n                  rewrite seq_length in Hltk.\n                  apply Hltk. }\n              rewrite Hlen in Hf1.\n              rewrite upd_val_vec_eq in Hf1.\n              lra. }\n        rewrite sum_weight_with_coeff_eq_one_coone.\n        replace (map (eval_p_sequent (upd_val_vec val (seq (S (max_var_weight_p_hseq G)) (length G)) vr)) G) with (map (eval_p_sequent val) G) in Hf4; auto.\n        symmetry; apply eval_p_hseq_upd_val_vec_lt.\n        apply forall_Forall_inf.\n        intros x Hinx.\n        apply In_inf_seq_le_start in Hinx.\n        lia.\n      * set (val' := (upd_val_vec val (seq (S (max_var_weight_p_hseq G)) (length G)) vr)).\n        set (L := (map (fun x : nat => eval_to_oRpos val' (FOL_R_var x))\n                       (seq (S (max_var_weight_p_hseq G)) (length G)))).\n        set (T := flat_map (fun i : nat =>\n                              seq_mul (FOL_R_var (S (max_var_weight_p_hseq G) + i))\n                                      (only_diamond_p_seq (nth i G nil))) (pos_indexes L)).\n        remember T; clear - Heqn Hf1 Hf2 Hf3 Hf4 Hlen.\n        destruct (concat_with_coeff_mul_only_diamond_decomp_no_diamond (map (eval_p_sequent val) G) L) as [[r s] [Hperm Heq]].\n        { assert (H := max_diamond_eval_p_hseq val G).\n          lia. }\n        rewrite concat_with_coeff_mul_only_diamond.\n        apply hmrr_ex_seq with (hseq.vec s HMR_coone ++ hseq.vec r HMR_one ++ nil); [ Permutation_Type_solve | ].\n        apply hmrr_one ; [ | apply hmrr_INIT].\n        replace (map\n                     (fun x : nat =>\n                        eval_to_oRpos (upd_val_vec val (seq (S (max_var_weight_p_hseq G)) (length G)) vr)\n                                      (FOL_R_var x)) (seq (S (max_var_weight_p_hseq G)) (length G))) with\n               (map (eval_to_oRpos (upd_val_vec val (seq (S (max_var_weight_p_hseq G)) (length G)) vr)) (map FOL_R_var (seq (S (max_var_weight_p_hseq G)) (length G)))) by (now rewrite map_map).\n        simpl in Hf4.\n        apply Rminus_diag_le in Hf4.\n        rewrite FOL_R_term_sem_eval_p_hseq_one in Hf4.\n        2:{ apply forall_Forall_inf.\n            intros x Hinx.\n            apply in_inf_map_inv in Hinx as [i Heqi Hini].\n            apply In_inf_nth with _ _ _ 0%nat in Hini as [k Hltk Heqk].\n            rewrite <- Heqi; rewrite <- Heqk.\n            rewrite seq_length in Hlen.\n            rewrite Hlen.\n            rewrite seq_nth.\n            2:{ rewrite <- Hlen.\n                rewrite seq_length in Hltk.\n                apply Hltk. }\n            simpl.\n            rewrite <- Nat.add_succ_l.\n            rewrite (upd_val_vec_eq vr val k (S (max_var_weight_p_hseq G))).\n            destruct (in_inf_dec Nat.eq_dec k vx); auto.\n            - apply cond_FOL_R_all_gtz_formula_sem_inv with _ _ _ k in Hf2; auto.\n              rewrite Hlen in Hf2.\n              rewrite upd_val_vec_eq in Hf2.\n              lra.\n            - apply cond_FOL_R_all_zero_formula_sem_inv with _ _ _ k in Hf1.\n              2:{ apply In_inf_complementary2_inv; auto.\n                  rewrite seq_length in Hltk.\n                  apply Hltk. }\n              rewrite Hlen in Hf1.\n              rewrite upd_val_vec_eq in Hf1.\n              lra. }\n        rewrite sum_weight_with_coeff_eq_one_coone in Heq.\n        replace (map (eval_p_sequent (upd_val_vec val (seq (S (max_var_weight_p_hseq G)) (length G)) vr)) G) with (map (eval_p_sequent val) G) in Hf4.\n        2:{ symmetry; apply eval_p_hseq_upd_val_vec_lt.\n            apply forall_Forall_inf.\n            intros x Hinx.\n            apply In_inf_seq_le_start in Hinx.\n            lia. }\n        unfold L in Heq; unfold val' in Heq.\n        rewrite map_map in Hf4.\n        lra.\n    + apply cond_FOL_R_basic_case_diamond_inv with _ _ _ n in Hf; auto.\n      destruct Hf as [vx [Hinvx Hf]].\n      apply cond_FOL_R_exists_vec_formula_sem_inv in Hf as [vr [Hlen [[Hf1 [Hf2 [Hf3 Hf4]]] Hf5]]].\n      apply hmrr_M_elim.\n      apply lambda_prop_inv ; [apply p_hseq_basic_hseq_basic; auto | ].\n      split with (map R_to_oRpos vr).\n      repeat split.\n      * rewrite ? map_length.\n        rewrite seq_length in Hlen; auto.\n      * apply in_inf_map_inv in Hinvx as [vxr Heq Hin].\n        apply cond_is_in_make_subsets_inv in Hin as [[Hnnil Hle] Hlt].\n        destruct vxr ; [ exfalso; apply Hnnil; auto | ].\n        apply nth_Exists_inf with n0 None.\n        -- rewrite map_length.\n           rewrite seq_length in Hlen.\n           rewrite <- Hlen.\n           apply (Hle 0)%nat.\n        -- rewrite nth_indep with _ _ _ _ (R_to_oRpos 0).\n           2:{ rewrite map_length.\n               rewrite seq_length in Hlen.\n               rewrite <- Hlen.\n               apply (Hle 0)%nat. }\n           rewrite map_nth.\n           apply cond_FOL_R_all_gtz_formula_sem_inv with _ _ _ n0 in Hf2.\n           2:{ rewrite <- Heq.\n               apply in_inf_rev.\n               left; auto. }\n           unfold R_to_oRpos.\n           rewrite seq_length in Hlen; rewrite Hlen in Hf2.\n           rewrite upd_val_vec_eq in Hf2.\n           rewrite nth_indep with _ _ _ _ 0 in Hf2.\n           2:{ rewrite <- Hlen.\n               apply (Hle 0)%nat. }\n           case (R_order_dec (nth n0 vr 0));\n             intros e; try (exfalso; try apply R_blt_lt in e; lra).\n           intros H; inversion H.\n      * intros n0.\n        case_eq (n0 <=? max_var_p_hseq G)%nat; intros Hle.\n        -- apply cond_FOL_R_all_atoms_eq_formula_sem_inv with _ _ _ n0 in Hf3 ; [ | apply Nat.leb_le in Hle; auto].\n           simpl in Hf3.\n           apply Rminus_diag_eq in Hf3.\n           rewrite FOL_R_term_sem_eval_p_hseq in Hf3.\n           2:{ apply forall_Forall_inf.\n               intros x Hinx.\n               apply in_inf_map_inv in Hinx as [i Heqi Hini].\n               apply In_inf_nth with _ _ _ 0%nat in Hini as [k Hltk Heqk].\n               rewrite <- Heqi; rewrite <- Heqk.\n               rewrite seq_length in Hlen.\n               rewrite Hlen.\n               rewrite seq_nth.\n               2:{ rewrite <- Hlen.\n                   rewrite seq_length in Hltk.\n                   apply Hltk. }\n               simpl.\n               rewrite <- Nat.add_succ_l.\n               rewrite (upd_val_vec_eq vr val k (S (max_var_weight_p_hseq G))).\n               destruct (in_inf_dec Nat.eq_dec k vx); auto.\n               - apply cond_FOL_R_all_gtz_formula_sem_inv with _ _ _ k in Hf2; auto.\n                 rewrite Hlen in Hf2.\n                 rewrite upd_val_vec_eq in Hf2.\n                 lra.\n               - apply cond_FOL_R_all_zero_formula_sem_inv with _ _ _ k in Hf1.\n                 2:{ apply In_inf_complementary2_inv; auto.\n                     rewrite seq_length in Hltk.\n                     apply Hltk. }\n                 rewrite Hlen in Hf1.\n                 rewrite upd_val_vec_eq in Hf1.\n                 lra. }\n           rewrite sum_weight_with_coeff_eq_var_covar.\n           replace (map (eval_p_sequent (upd_val_vec val (seq (S (max_var_weight_p_hseq G)) (length G)) vr)) G) with (map (eval_p_sequent val) G) in Hf3; auto.\n           2:{ symmetry; apply eval_p_hseq_upd_val_vec_lt.\n               apply forall_Forall_inf.\n               intros x Hin.\n               apply In_inf_seq_le_start in Hin.\n               lia. }\n           rewrite seq_length in Hlen.\n           rewrite Hlen in Hf3.\n           rewrite eval_to_oRpos_eq in Hf3.\n           apply Hf3.\n        -- apply Nat.leb_nle in Hle.\n           clear - Hle.\n           rewrite sum_weight_with_coeff_eq_var_covar.\n           assert (H := max_var_hseq_le_p_hseq val G).\n           rewrite sum_weight_var_with_coeff_lt_max_var; [ | lia ].\n           rewrite sum_weight_covar_with_coeff_lt_max_var; [ | lia ].\n           lra.\n      * simpl in Hf4.\n        apply Rminus_diag_le in Hf4.\n        rewrite FOL_R_term_sem_eval_p_hseq_one in Hf4.\n        2:{ apply forall_Forall_inf.\n            intros x Hinx.\n            apply in_inf_map_inv in Hinx as [i Heqi Hini].\n            apply In_inf_nth with _ _ _ 0%nat in Hini as [k Hltk Heqk].\n            rewrite <- Heqi; rewrite <- Heqk.\n            rewrite seq_length in Hlen.\n            rewrite Hlen.\n            rewrite seq_nth.\n            2:{ rewrite <- Hlen.\n                rewrite seq_length in Hltk.\n                apply Hltk. }\n            simpl.\n            rewrite <- Nat.add_succ_l.\n            rewrite (upd_val_vec_eq vr val k (S (max_var_weight_p_hseq G))).\n            destruct (in_inf_dec Nat.eq_dec k vx); auto.\n            - apply cond_FOL_R_all_gtz_formula_sem_inv with _ _ _ k in Hf2; auto.\n              rewrite Hlen in Hf2.\n              rewrite upd_val_vec_eq in Hf2.\n              lra.\n            - apply cond_FOL_R_all_zero_formula_sem_inv with _ _ _ k in Hf1.\n              2:{ apply In_inf_complementary2_inv; auto.\n                  rewrite seq_length in Hltk.\n                  apply Hltk. }\n              rewrite Hlen in Hf1.\n              rewrite upd_val_vec_eq in Hf1.\n              lra. }\n        rewrite sum_weight_with_coeff_eq_one_coone.\n        replace (map (eval_p_sequent (upd_val_vec val (seq (S (max_var_weight_p_hseq G)) (length G)) vr)) G) with (map (eval_p_sequent val) G) in Hf4; auto.\n        2:{ symmetry; apply eval_p_hseq_upd_val_vec_lt.\n            apply forall_Forall_inf.\n            intros x Hin.\n            apply In_inf_seq_le_start in Hin.\n            lia. }\n        rewrite seq_length in Hlen.\n        rewrite Hlen in Hf4.\n        rewrite eval_to_oRpos_eq in Hf4.\n        apply Hf4.\n      * set (val' := (upd_val_vec val (seq (S (max_var_weight_p_hseq G)) (length G)) vr)).\n        revert Hf4;\n          set (T := flat_map (fun i : nat =>\n                              seq_mul (FOL_R_var (S (max_var_weight_p_hseq G) + i))\n                                      (only_diamond_p_seq (nth i G nil))) vx); intros Hf4.\n        specialize (HMR_dec_formula_2 val' (T :: nil)).\n        assert (p_hseq_well_defined val' (T :: nil)) as Hwd'.\n        { unfold val'; unfold T.\n          rewrite flat_map_concat_map.\n          apply Forall_inf_cons ; [ | apply Forall_inf_nil].\n          apply forall_Forall_inf.\n          intros A HinA.\n          apply In_inf_concat in HinA as [l [Hin1 Hin2]].\n          apply in_inf_map_inv in Hin1 as [i Heq Hin3].\n          assert (i < length G)%nat as Hlti.\n          { apply in_inf_map_inv in Hinvx as [vx' Heq' Hinvx'].\n            apply cond_is_in_make_subsets_inv in Hinvx' as [[_ H1] _].\n            rewrite <- Heq' in Hin3.\n            apply in_inf_rev_inv in Hin3.\n            apply In_inf_nth with _ _ _ 0%nat in Hin3 as [i' Hleni Heqi].\n            rewrite <- Heqi.\n            apply H1. }\n          rewrite <- Heq in Hin2.\n          apply In_inf_seq_mul in Hin2 as [[b B] [HeqB HinB]].\n          rewrite HeqB.\n          simpl.\n          rewrite seq_length in Hlen.\n          rewrite Hlen.\n          change (S (max_var_weight_p_hseq G + i)) with ((S (max_var_weight_p_hseq G)) + i)%nat.\n          rewrite upd_val_vec_eq.\n          rewrite FOL_R_term_sem_upd_val_vec_lt.\n          2:{ apply forall_Forall_inf.\n              intros x Hinx.\n              apply Nat.lt_le_trans with (S (max_var_weight_p_hseq G)).\n              - apply Nat.le_lt_trans with (max_var_weight_p_seq (only_diamond_p_seq (nth i G nil))).\n                + apply max_var_FOL_R_term_In_inf_p_seq with B; auto.\n                + apply Nat.le_lt_trans with (max_var_weight_p_seq (nth i G nil)) ; [ apply max_var_weight_p_seq_only_diamond | ].\n                  apply Nat.le_lt_trans with (max_var_weight_p_hseq G) ; [ | lia ].\n                  apply max_var_weight_p_seq_In_inf_p_hseq.\n                  apply nth_In_inf.\n                  apply Hlti.\n              - apply (In_inf_seq_le_start _ _ _ Hinx). }\n          apply R_blt_lt.\n          apply Rmult_lt_0_compat.\n          ++ apply cond_FOL_R_all_gtz_formula_sem_inv with _ _ _ i in Hf2; auto.\n             rewrite Hlen in Hf2; rewrite (upd_val_vec_eq vr val i) in Hf2.\n             apply Hf2.\n          ++ change b with (fst (b , B)).\n             apply R_blt_lt.\n             refine (@Forall_inf_forall _ (fun x => (0 <? FOL_R_term_sem val (fst x)) = true) (only_diamond_p_seq (nth i G nil)) _ (b, B) _); auto.\n             apply p_seq_well_defined_only_diamond.\n             refine (@Forall_inf_forall _ (p_seq_well_defined val) G _ (nth i G nil) _); auto.\n             apply nth_In_inf.\n             apply Hlti. }\n        specialize (HMR_dec_formula_2 Hwd' Hf5).\n        unfold val' in HMR_dec_formula_2; unfold T in HMR_dec_formula_2.\n        replace (fun i : nat => seq_mul (FOL_R_var (S (max_var_weight_p_hseq G) + i)) (only_diamond_p_seq (nth i G nil)))\n             with (fun i : nat => seq_mul (FOL_R_var (S (max_var_weight_p_hseq G) + i)) (nth i (only_diamond_p_hseq G) nil)) in HMR_dec_formula_2.\n        2:{ apply functional_extensionality.\n            intros x.\n            rewrite <- (map_nth only_diamond_p_seq); reflexivity. }\n        simpl in HMR_dec_formula_2.\n        replace vx with (pos_indexes (map R_to_oRpos vr)) in HMR_dec_formula_2.\n        2:{ symmetry; apply pos_indexes_cond.\n            - intros i j Hltj Hltij.\n              apply in_inf_map_inv in Hinvx as [vxr Heqvxr Hinvxr].\n              apply cond_is_in_make_subsets_inv in Hinvxr as [Hnil H].\n              rewrite <- Heqvxr.\n              apply rev_reverse_order; try rewrite Heqvxr; try lia.\n              intros i' j' Hltj' Hltij'.\n              apply H; auto.\n            - intros i Hlti.\n              rewrite map_length.\n              rewrite <- Hlen.\n              rewrite seq_length.\n              apply in_inf_map_inv in Hinvx as [vxr Heqvxr Hinvxr].\n              apply cond_is_in_make_subsets_inv in Hinvxr as [[Hnil H] H'].\n              rewrite <- Heqvxr.\n              rewrite rev_nth; try (rewrite <- Heqvxr in Hlti; rewrite rev_length in Hlti; lia).\n              apply H.\n            - intros i Hin.\n              apply cond_FOL_R_all_gtz_formula_sem_inv with _ _ _ i in Hf2; auto.\n              apply in_inf_map_inv in Hinvx as [vxr Heqvxr Hinvxr].\n              apply cond_is_in_make_subsets_inv in Hinvxr as [[Hnil H'] H].\n              rewrite seq_length in Hlen; rewrite Hlen in Hf2.\n              rewrite upd_val_vec_eq in Hf2.\n              replace (@None Rpos) with (R_to_oRpos 0) at 1.\n              2:{ unfold R_to_oRpos.\n                  case R_order_dec; intro e; try (exfalso; simpl in *; apply R_blt_lt in e; lra); auto. }\n              rewrite map_nth.\n              unfold R_to_oRpos.\n              rewrite nth_indep with _ _ _ _ 0 in Hf2.\n              2:{ rewrite <- Heqvxr in Hin.\n                  apply in_inf_rev_inv in Hin.\n                  apply In_inf_nth with _ _ _ 0%nat in Hin as [k Hltk Heqk].\n                  rewrite <- Heqk.\n                  rewrite <- Hlen.\n                  apply H'. }\n              case (R_order_dec (nth i vr 0)); intros e; try (intro Heq; now inversion Heq).\n              exfalso.\n              lra.\n            - intros i Hlti Hneq.\n              destruct (in_inf_dec Nat.eq_dec i vx); auto.\n              exfalso.\n              rewrite seq_length in Hlen.\n              apply cond_FOL_R_all_zero_formula_sem_inv with _ _ _ i in Hf1.\n              2:{ apply In_inf_complementary2_inv.\n                  rewrite Hlen.\n                  rewrite map_length in Hlti; apply Hlti.\n                  apply f. }\n              rewrite Hlen in Hf1.\n              rewrite upd_val_vec_eq in Hf1.\n              replace (@None Rpos) with (R_to_oRpos 0) in Hneq at 1.\n              2:{ unfold R_to_oRpos.\n                  case R_order_dec; intro e; try (exfalso; simpl in *; apply R_blt_lt in e; lra); auto. }\n              rewrite map_nth in Hneq.\n              rewrite nth_indep with _ _ _ _ 0 in Hf1.\n              2:{ rewrite map_length in Hlti.\n                  apply Hlti. }\n              rewrite Hf1 in Hneq.\n              apply Hneq.\n              unfold R_to_oRpos.\n              case (R_order_dec 0); intros e; try (exfalso; simpl in *; apply R_blt_lt in e; lra).\n              reflexivity. }\n        rewrite seq_length in Hlen.\n        rewrite Hlen in HMR_dec_formula_2.\n        pattern vr in HMR_dec_formula_2 at 3.\n        replace vr with (map oRpos_to_R (map R_to_oRpos vr)) in HMR_dec_formula_2 .\n        2:{ rewrite map_map.\n            apply nth_ext with 0 0.\n            { rewrite map_length; auto. }\n            intros n0.\n            case_eq (n0 <? length vr)%nat; intros Hltn0.\n            2:{ apply Nat.ltb_nlt in Hltn0.\n                rewrite nth_overflow; [|rewrite map_length; lia ].\n                rewrite nth_overflow; try lia.\n                reflexivity. }\n            apply Nat.ltb_lt in Hltn0.\n            rewrite nth_indep with _ _ _ _ (oRpos_to_R (R_to_oRpos 0)).\n            2:{ rewrite map_length; lia. }\n            rewrite (map_nth (fun x => oRpos_to_R (R_to_oRpos x))).\n            destruct (in_inf_dec Nat.eq_dec n0 vx); auto.\n            - apply cond_FOL_R_all_gtz_formula_sem_inv with _ _ _ n0 in Hf2; auto.\n              rewrite Hlen in Hf2.\n              rewrite upd_val_vec_eq in Hf2.\n              rewrite nth_indep with _ _ _ _ 0 in Hf2; auto.\n              unfold R_to_oRpos.\n              case (R_order_dec (nth n0 vr 0)); intros e;\n                try (exfalso; simpl in *; try apply R_blt_lt in e; lra).\n              reflexivity.\n            - apply cond_FOL_R_all_zero_formula_sem_inv with _ _ _ n0 in Hf1.\n              2:{ apply In_inf_complementary2_inv; auto.\n                  rewrite Hlen.\n                  apply Hltn0. }\n              rewrite Hlen in Hf1.\n              rewrite upd_val_vec_eq in Hf1.\n              rewrite nth_indep with _ _ _ _ 0 in Hf1; auto.\n              unfold R_to_oRpos.\n              case (R_order_dec (nth n0 vr 0)); intros e;\n                try (exfalso; simpl in *; try apply R_blt_lt in e; lra).\n              rewrite e;\n                reflexivity. }\n        rewrite <- (map_length R_to_oRpos vr) in HMR_dec_formula_2.\n        rewrite eval_p_seq_upd_val_vec_nth in HMR_dec_formula_2.\n        2:{ change (only_diamond_p_hseq G) with (map only_diamond_p_seq G).\n            rewrite 2 map_length; auto. }\n        2:{ eapply Nat.le_lt_trans; [ apply max_var_weight_p_hseq_only_diamond | ].\n            lia. }\n        apply (HMR_le_frag (hmr_frag_T)) ; [ repeat split; auto | ].\n        rewrite only_diamond_eval_p_hseq.\n        apply HMR_dec_formula_2.\n        apply acc.\n        apply fst_lt4.\n        simpl.\n        rewrite (max_diamond_seq_mul_nth _ _ (S (max_var_weight_p_hseq G))).\n        rewrite flat_map_concat_map.\n        simpl.\n        rewrite Nat.max_0_r.\n        rewrite <- Heqn.\n        apply max_diamond_p_seq_concat.\n        apply forall_Forall_inf.\n        intros x Hinx.\n        apply in_inf_map_inv in Hinx as [i Heq Hini].\n        rewrite <- Heq.\n        apply Nat.le_lt_trans with (max_diamond_p_hseq (map only_diamond_p_seq G)).\n        ++ apply max_diamond_nth.\n        ++ rewrite Heqn.\n           apply max_diamond_only_diamond_p_hseq_lt.\n           lia.           \n  - destruct acc as [acc].\n    remember (snd (fst (modal_complexity_p_hseq G))).\n    destruct n.\n    { refine (FOL_R_basic_case_2 val G Hwd _ _ _).\n      - apply p_hseq_is_basic_complexity_0_inv.\n        simpl in Heqn; auto.\n      - apply cond_HMR_dec_formula_basic_inv in Hf; auto.\n      - apply acc.\n        apply fth_lt4; lia. }\n    apply hmrr_ex_hseq with (eval_p_sequent val (p_hseq_p_seq_max_complexity G) :: map (eval_p_sequent val) (p_hseq_without_max_complexity G)).\n    { rewrite <- map_cons.\n      apply Permutation_Type_map.\n      symmetry; apply p_hseq_put_max_complexity_fst.\n      destruct G; [ inversion Heqn | intros H; inversion H]. }\n    apply hmrr_ex_seq with (eval_p_sequent val (p_seq_fst_non_basic_term (p_hseq_p_seq_max_complexity G) :: p_seq_without_fst_non_basic_term (p_hseq_p_seq_max_complexity G))).\n    { apply Permutation_Type_eval_p_sequent.\n      symmetry; apply p_seq_put_non_basic_fst.\n      intros Hb; apply p_seq_is_basic_complexity_0 in Hb.\n      rewrite p_hseq_p_seq_max_complexity_correct in Hb.\n      simpl in *; lia. }\n    remember (apply_logical_rule_on_p_hypersequent (p_hseq_put_non_basic_fst G)).\n    destruct s as [G1 | [G1 G2]].\n    + rewrite <- map_cons.\n      apply hmrr_M_elim.\n      refine (apply_logical_rule_on_p_hypersequent_inl_HMR_inv val _ G1 (eq_sym Heqs) _ _).\n      * apply p_hseq_put_non_basic_fst_well_defined; auto.\n        simpl in Heqn; lia.\n      * apply (HMR_le_frag hmr_frag_T _); [ repeat split; auto | ].\n        refine (HMR_dec_formula_2 val G1 _ _ _).\n        -- apply apply_logical_rule_on_p_hypersequent_inl_well_defined with (p_hseq_put_non_basic_fst G); auto.\n           apply p_hseq_put_non_basic_fst_well_defined; auto.\n           simpl in Heqn; lia.\n        -- apply (cond_HMR_dec_formula_inl_inv val G n (eq_sym Heqn) G1) in Hf; auto.\n        -- apply acc.\n           apply lt_nat3_to_lt_nat4.\n           apply apply_logical_rule_on_p_hypersequent_correct_inl with n; auto.\n    + rewrite <- map_cons.\n      apply hmrr_M_elim.\n      refine (apply_logical_rule_on_p_hypersequent_inr_HMR_inv val _ G1 G2 (eq_sym Heqs) _ _ _).\n      * apply p_hseq_put_non_basic_fst_well_defined; auto.\n        simpl in Heqn; lia.\n      * apply (HMR_le_frag hmr_frag_T _); [ repeat split; auto | ].\n        refine (HMR_dec_formula_2 val G1 _ _ _).\n        -- apply apply_logical_rule_on_p_hypersequent_inr_l_well_defined with (p_hseq_put_non_basic_fst G) G2; auto.\n           apply p_hseq_put_non_basic_fst_well_defined; auto.\n           simpl in Heqn; lia.\n        -- apply (cond_HMR_dec_formula_inr_inv val G n (eq_sym Heqn) G1 G2) in Hf as [Hf1 _ ]; auto.\n        -- apply acc.\n           apply lt_nat3_to_lt_nat4.\n           apply apply_logical_rule_on_p_hypersequent_correct_inr_l with G2 n; auto.\n      * apply (HMR_le_frag hmr_frag_T _); [ repeat split; auto | ].\n        refine (HMR_dec_formula_2 val G2 _ _ _).\n        -- apply apply_logical_rule_on_p_hypersequent_inr_r_well_defined with (p_hseq_put_non_basic_fst G) G1; auto.\n           apply p_hseq_put_non_basic_fst_well_defined; auto.\n           simpl in Heqn; lia.\n        -- apply (cond_HMR_dec_formula_inr_inv val G n (eq_sym Heqn) G1 G2) in Hf as [_ Hf2]; auto.\n        -- apply acc.\n           apply lt_nat3_to_lt_nat4.\n           apply apply_logical_rule_on_p_hypersequent_correct_inr_r with G1 n; auto.\nQed.\n\n(** there exists a formula \\phi_G such that \\phi_G(\\vec r) has a proof if and only if G[\\vec r /\\vec x] has a proof *) \nLemma HMR_FOL_R_equiv : forall G,\n    { f & forall val, p_hseq_well_defined val G ->\n                      prod\n                        (HMR_full (map (eval_p_sequent val) G) -> FOL_R_formula_sem val f)\n                        (FOL_R_formula_sem val f -> HMR_full (map (eval_p_sequent val) G)) }.\nProof.\n  enough (forall G,\n             { f & forall val, p_hseq_well_defined val G ->\n                               prod\n                                (HMR_T (map (eval_p_sequent val) G) -> FOL_R_formula_sem val f)\n                                (FOL_R_formula_sem val f -> HMR_T (map (eval_p_sequent val) G)) }).\n  { intros G.\n    specialize (X G) as [f H].\n    split with f.\n    intros val H'.\n    destruct (H val) as [H1 H2]; try assumption.\n    split.\n    - intros pi.\n      apply H1.\n      apply hmrr_M_elim.\n      apply hmrr_can_elim.\n      apply pi.\n    - intros Hf.\n      refine (HMR_le_frag _ _ _ _ (H2 Hf)).\n      repeat split; auto. }\n  intros G.\n  split with (HMR_dec_formula G).\n  intros val Hwd.\n  split.\n  - intros pi.\n    apply HMR_dec_formula_1; auto.\n    apply wf_lt_nat4.\n  - intros Hf.\n    apply HMR_dec_formula_2; auto.\n    apply wf_lt_nat4.\nQed.\n\nLemma p_HMR_decidable : forall val G,\n    p_hseq_well_defined val G ->\n    (HMR_full (map (eval_p_sequent val) G)) + (HMR_full (map (eval_p_sequent val) G) -> False).\nProof.\n  intros val G Hwd.\n  destruct (HMR_FOL_R_equiv G) as [f [H1 H2]]; [ apply Hwd | ].\n  destruct (FOL_R_decidable f) with val.\n  - left.\n    apply H2; apply f0.\n  - right.\n    intros pi; apply f0; apply H1; apply pi.\nQed.\n\n(** Theorem 4.11 *)\nLemma HMR_decidable : forall G,\n    (HMR_full G) + (HMR_full G -> False).\nProof.\n  intros G.\n  rewrite <- (eval_p_hypersequent_to_p_hypersequent) with (fun x => 0) _.\n  apply p_HMR_decidable.\n  apply to_p_hypersequent_well_defined.\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/decidability.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.4148988457967689, "lm_q1q2_score": 0.25211874190105116}}
{"text": "Require Import List.\nImport ListNotations.\n\nRequire oeuf.SourceValues.\nRequire oeuf.HighestValues.\nRequire oeuf.HigherValue.\nRequire oeuf.HighValues.\n\nRequire oeuf.MatchValues.\n\nRequire Import StructTact.StructTactics.\nRequire Import oeuf.StuartTact.\n\n\nInductive value_level : Set :=\n| VlSource\n        (G : list (SourceValues.type * list SourceValues.type * SourceValues.type))\n        (ty : SourceValues.type)\n| VlHighest\n| VlHigher\n| VlHighFname (* HighValues, using sequential indexes for function names *)\n| VlHigh\n.\n\n\nDefinition value_type vl : Type :=\n    match vl with\n    | VlSource G ty => SourceValues.value G ty\n    | VlHighest => HighestValues.value\n    | VlHigher => HigherValue.value\n    | VlHighFname => HighValues.value\n    | VlHigh => HighValues.value\n    end.\n\nDefinition value_match_indexed M vl1 vl2 : value_type vl1 -> value_type vl2 -> Prop :=\n    match vl1, vl2 with\n\n    (* zero steps *)\n    | VlSource G1 ty1, VlSource G2 ty2 =>\n            fun v1 v2 => existT _ G1 (existT _ ty1 v1) = existT _ G2 (existT _ ty2 v2)\n                    :> { G : _ & { ty : _ & SourceValues.value G ty } }\n    | VlHighest, VlHighest => eq\n    | VlHigher, VlHigher => eq\n    | VlHighFname, VlHighFname => eq\n    | VlHigh, VlHigh => eq\n\n    (* one step *)\n    | VlSource G ty, VlHighest => fun v1 v2 => MatchValues.compile_highest v1 = v2\n    | VlHighest, VlHigher => MatchValues.mv_higher\n    | VlHigher, VlHighFname => MatchValues.mv_high\n    | VlHighFname, VlHigh => MatchValues.mv_fmajor M\n\n    (* two steps *)\n    | VlSource G ty, VlHigher => fun v1 v3 => exists v2,\n            MatchValues.compile_highest v1 = v2 /\\\n            MatchValues.mv_higher v2 v3\n    | VlHighest, VlHighFname => fun v1 v3 => exists v2,\n            MatchValues.mv_higher v1 v2 /\\\n            MatchValues.mv_high v2 v3\n    | VlHigher, VlHigh => fun v1 v3 => exists v2,\n            MatchValues.mv_high v1 v2 /\\\n            MatchValues.mv_fmajor M v2 v3\n\n    (* three steps *)\n    | VlSource G ty, VlHighFname => fun v1 v4 => exists v2 v3,\n            MatchValues.compile_highest v1 = v2 /\\\n            MatchValues.mv_higher v2 v3 /\\\n            MatchValues.mv_high v3 v4\n    | VlHighest, VlHigh => fun v1 v4 => exists v2 v3,\n            MatchValues.mv_higher v1 v2 /\\\n            MatchValues.mv_high v2 v3 /\\\n            MatchValues.mv_fmajor M v3 v4\n\n    (* four steps *)\n    | VlSource G ty, VlHigh => fun v1 v5 => exists v2 v3 v4,\n            MatchValues.compile_highest v1 = v2 /\\\n            MatchValues.mv_higher v2 v3 /\\\n            MatchValues.mv_high v3 v4 /\\\n            MatchValues.mv_fmajor M v4 v5\n\n    (* anything else *)\n    | _, _ => fun _ _ => False\n    end.\n\n(* Like value_match_indexed, but all cases usind indices are deleted. *)\nDefinition value_match vl1 vl2 : value_type vl1 -> value_type vl2 -> Prop :=\n    match vl1, vl2 with\n\n    (* zero steps *)\n    | VlSource G1 ty1, VlSource G2 ty2 =>\n            fun v1 v2 => existT _ G1 (existT _ ty1 v1) = existT _ G2 (existT _ ty2 v2)\n                    :> { G : _ & { ty : _ & SourceValues.value G ty } }\n    | VlHighest, VlHighest => eq\n    | VlHigher, VlHigher => eq\n    | VlHighFname, VlHighFname => eq\n    | VlHigh, VlHigh => eq\n\n    (* one step *)\n    | VlSource G ty, VlHighest => fun v1 v2 => MatchValues.compile_highest v1 = v2\n    | VlHighest, VlHigher => MatchValues.mv_higher\n    | VlHigher, VlHighFname => MatchValues.mv_high\n\n    (* two steps *)\n    | VlSource G ty, VlHigher => fun v1 v3 => exists v2,\n            MatchValues.compile_highest v1 = v2 /\\\n            MatchValues.mv_higher v2 v3\n    | VlHighest, VlHighFname => fun v1 v3 => exists v2,\n            MatchValues.mv_higher v1 v2 /\\\n            MatchValues.mv_high v2 v3\n\n    (* three steps *)\n    | VlSource G ty, VlHighFname => fun v1 v4 => exists v2 v3,\n            MatchValues.compile_highest v1 = v2 /\\\n            MatchValues.mv_higher v2 v3 /\\\n            MatchValues.mv_high v3 v4\n\n    (* four steps *)\n\n    (* anything else *)\n    | _, _ => fun _ _ => False\n    end.\n\nDefinition value_level_le_indexed vl1 vl2 : Prop :=\n    match vl1, vl2 with\n\n    (* zero steps *)\n    | VlSource G1 ty1, VlSource G2 ty2 => G1 = G2 /\\ ty1 = ty2\n    | VlHighest, VlHighest => True\n    | VlHigher, VlHigher => True\n    | VlHighFname, VlHighFname => True\n    | VlHigh, VlHigh => True\n\n    (* one step *)\n    | VlSource _ _, VlHighest => True\n    | VlHighest, VlHigher => True\n    | VlHigher, VlHighFname => True\n    | VlHighFname, VlHigh => True\n\n    (* two steps *)\n    | VlSource _ _, VlHigher => True\n    | VlHighest, VlHighFname => True\n    | VlHigher, VlHigh => True\n\n    (* three steps *)\n    | VlSource _ _, VlHighFname => True\n    | VlHighest, VlHigh => True\n\n    (* four steps *)\n    | VlSource _ _, VlHigh => True\n\n    (* anything else *)\n    | _, _ => False\n    end.\n\nDefinition value_level_le vl1 vl2 : Prop :=\n    match vl1, vl2 with\n\n    (* zero steps *)\n    | VlSource G1 ty1, VlSource G2 ty2 => G1 = G2 /\\ ty1 = ty2\n    | VlHighest, VlHighest => True\n    | VlHigher, VlHigher => True\n    | VlHighFname, VlHighFname => True\n    | VlHigh, VlHigh => True\n\n    (* one step *)\n    | VlSource _ _, VlHighest => True\n    | VlHighest, VlHigher => True\n    | VlHigher, VlHighFname => True\n\n    (* two steps *)\n    | VlSource _ _, VlHigher => True\n    | VlHighest, VlHighFname => True\n\n    (* three steps *)\n    | VlSource _ _, VlHighFname => True\n\n    (* four steps *)\n\n    (* anything else *)\n    | _, _ => False\n    end.\n\nLemma value_match_indexed_compose : forall M vl1 vl2 vl3 v1 v2 v3,\n    value_match_indexed M vl1 vl2 v1 v2 ->\n    value_match_indexed M vl2 vl3 v2 v3 ->\n    value_match_indexed M vl1 vl3 v1 v3.\ndestruct vl1, vl2, vl3; intros ? ? ? Hm1 Hm2; simpl in *; subst;\ntry fix_existT; repeat (break_exists || break_and);\ntry solve [eauto | exfalso; eauto | firstorder congruence].\nQed.\n\nLemma value_match_indexed_decompose : forall M vl1 vl2 vl3 v1 v3,\n    value_match_indexed M vl1 vl3 v1 v3 ->\n    value_level_le_indexed vl1 vl2 ->\n    value_level_le_indexed vl2 vl3 ->\n    exists v2, value_match_indexed M vl1 vl2 v1 v2 /\\ value_match_indexed M vl2 vl3 v2 v3.\ndestruct vl1, vl2, vl3; intros ? ? ? Hle1 Hle2;\ntry solve [inversion Hle1 | inversion Hle2];\nsimpl in *; repeat (break_exists || break_and); subst; eauto 9.\nQed.\n\nLemma value_match_compose : forall vl1 vl2 vl3 v1 v2 v3,\n    value_match vl1 vl2 v1 v2 ->\n    value_match vl2 vl3 v2 v3 ->\n    value_match vl1 vl3 v1 v3.\ndestruct vl1, vl2, vl3; intros ? ? ? Hm1 Hm2; simpl in *; subst;\ntry fix_existT; repeat (break_exists || break_and);\ntry solve [eauto | exfalso; eauto | firstorder congruence].\nQed.\n\nLemma value_match_decompose : forall vl1 vl2 vl3 v1 v3,\n    value_match vl1 vl3 v1 v3 ->\n    value_level_le_indexed vl1 vl2 ->\n    value_level_le_indexed vl2 vl3 ->\n    exists v2, value_match vl1 vl2 v1 v2 /\\ value_match vl2 vl3 v2 v3.\ndestruct vl1, vl2, vl3; intros ? ? Hm Hle1 Hle2;\ntry solve [inversion Hle1 | inversion Hle2 | inversion Hm];\nsimpl in *; repeat (break_exists || break_and); subst; eauto 9.\nQed.\n\nLemma value_level_le_indexed_refl : forall vl,\n    value_level_le_indexed vl vl.\ndestruct vl; simpl; eauto.\nQed.\n\nLemma value_level_le_indexed_trans : forall vl1 vl2 vl3,\n    value_level_le_indexed vl1 vl2 ->\n    value_level_le_indexed vl2 vl3 ->\n    value_level_le_indexed vl1 vl3.\ndestruct vl1, vl2; simpl; try solve [intros ? ?; exfalso; eassumption].\nall: destruct vl3; simpl; try solve [intros ? ?; exfalso; eassumption].\nall: intros; eauto.\n\nfirstorder congruence.\nQed.\n\nLemma value_level_le_refl : forall vl,\n    value_level_le vl vl.\ndestruct vl; simpl; eauto.\nQed.\n\nLemma value_level_le_trans : forall vl1 vl2 vl3,\n    value_level_le vl1 vl2 ->\n    value_level_le vl2 vl3 ->\n    value_level_le vl1 vl3.\ndestruct vl1, vl2; simpl; try solve [intros ? ?; exfalso; eassumption].\nall: destruct vl3; simpl; try solve [intros ? ?; exfalso; eassumption].\nall: intros; eauto.\n\nfirstorder congruence.\nQed.\n\nLemma value_level_le_add_index : forall vl1 vl2,\n    value_level_le vl1 vl2 ->\n    value_level_le_indexed vl1 vl2.\ndestruct vl1, vl2; simpl; intro; eauto.\nQed.\n\nLemma value_match_remove_index : forall M vl1 vl2 v1 v2,\n    value_level_le vl1 vl2 ->\n    value_match_indexed M vl1 vl2 v1 v2 ->\n    value_match vl1 vl2 v1 v2.\nintros0 Hvm.\ndestruct vl1, vl2; simpl in *; eauto.\nQed.\n\nLemma value_match_add_index : forall M vl1 vl2 v1 v2,\n    value_match vl1 vl2 v1 v2 ->\n    value_match_indexed M vl1 vl2 v1 v2.\nintros0 Hvm. intros.\ndestruct vl1, vl2; simpl in *; eauto; try solve [exfalso; eauto].\nQed.\n\nLemma value_match_add_index_iff : forall M vl1 vl2 v1 v2,\n    value_level_le vl1 vl2 ->\n    value_match vl1 vl2 v1 v2 <->\n    value_match_indexed M vl1 vl2 v1 v2.\nintros; split; eauto using value_match_add_index, value_match_remove_index.\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/AllValues.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.2520769397520214}}
{"text": "Require Import Coqlib.\nRequire Import Asm.\nRequire Import PeekTactics.\nRequire Import PeepsLib.\nRequire Import Integers.\nRequire Import PregTactics.\nRequire Import StepIn.\nRequire Import AsmBits.\nRequire Import Values.\nRequire Import ValEq.\nRequire Import Integers.\nRequire Import PeepsTactics.\n\nModule Imp.\n\n(* dummy addrmode *)\nDefinition da : addrmode := Addrmode None None (inl Int.zero).\n\nDefinition peep_vec_mull_example :=\n            Pmovsd_fm XMM0 da ::\n            Pmovsd_fm XMM0 da ::\n            Pmuld_ff XMM0 XMM0 ::\n            Pmovsd_fm XMM0 da ::\n            Pmovsd_fm XMM0 da ::\n            Pmuld_ff XMM0 XMM0 ::\n            Pmovsd_fm XMM0 da ::\n            Pmovsd_fm XMM0 da ::\n            Pmuld_ff XMM0 XMM0 ::\n            Pmovsd_fm XMM0 da ::\n            Pmovsd_fm XMM0 da ::\n            Pmuld_ff XMM0 XMM0 ::\n            Pmovsd_mf da XMM0 ::\n            Pmovsd_mf da XMM0 ::\n            Pmovsd_mf da XMM0 ::\n            Pmovsd_mf da XMM0 ::\n            nil.\n\n\nSection VEC_MULL.\n\n  Variable concrete : code.\n  Variable r1 r2 r3 r4 r5 r6 r7 r8 : freg.\n  Variable a b c : addrmode.\n\n  \n  Definition a8 := addr_add a 8.\n  Definition a16 := addr_add a 16.\n  Definition a24 := addr_add a 24.\n\n  Definition b8 := addr_add b 8.\n  Definition b16 := addr_add b 16.\n  Definition b24 := addr_add b 24.\n  \n  Definition c8 := addr_add c 8.\n  Definition c16 := addr_add c 16.\n  Definition c24 := addr_add c 24.\n  \n  Definition make_bfreg (f : freg) : bfreg :=\n    match f with\n      | XMM0 => xmm0\n      | XMM1 => xmm1\n      | XMM2 => xmm2\n      | XMM3 => xmm3\n      | XMM4 => xmm4\n      | XMM5 => xmm5\n      | XMM6 => xmm6\n      | XMM7 => xmm7\n    end.\n\n  Definition get_high_reg (b : bfreg) : hfreg :=\n    let (_,h) := split_big_freg b in h.\n\n  Definition br1 := make_bfreg r1.\n  Definition br2 := make_bfreg r2.\n  Definition br3 := make_bfreg r3.\n  Definition br4 := make_bfreg r4.\n  Definition br5 := make_bfreg r5.\n  Definition br6 := make_bfreg r6.\n  Definition br7 := make_bfreg r7.\n  Definition br8 := make_bfreg r8.\n  Definition hr1 := get_high_reg br1.\n  Definition hr2 := get_high_reg br2.\n  Definition hr3 := get_high_reg br3.\n  Definition hr4 := get_high_reg br4.\n  Definition hr5 := get_high_reg br5.\n  Definition hr6 := get_high_reg br6.\n  Definition hr7 := get_high_reg br7.\n  Definition hr8 := get_high_reg br8.\n\n  \n  Definition peep_vec_mull_defs : rewrite_defs :=\n    {|\n      fnd :=\n            Pmovsd_fm r1 a ::\n            Pmovsd_fm r2 b ::\n            Pmuld_ff r1 r2 ::\n            Pmovsd_fm r3 a8 ::\n            Pmovsd_fm r4 b8 ::\n            Pmuld_ff r3 r4 ::\n            Pmovsd_fm r5 a16 ::\n            Pmovsd_fm r6 b16 ::\n            Pmuld_ff r5 r6 ::\n            Pmovsd_fm r7 a24 ::\n            Pmovsd_fm r8 b24 ::\n            Pmuld_ff r7 r8 ::\n            Pmovsd_mf c r1 ::\n            Pmovsd_mf c8 r3 ::\n            Pmovsd_mf c16 r5 ::\n            Pmovsd_mf c24 r7 ::\n            nil\n      ; rpl :=\n          Pmovups_rm br1 a ::\n          Pmovups_rm br2 b ::\n          Pmulpd_ff br1 br2 ::\n          Pmovups_rm br3 a16 ::\n          Pmovups_rm br4 b16 ::\n          Pmulpd_ff br3 br4 ::\n          Pmovups_mr c br1 ::\n          Pmovups_mr c16 br3 ::\n          Pnop :: Pnop :: Pnop :: Pnop ::\n          Pnop :: Pnop :: Pnop :: Pnop :: nil\n      ; lv_in :=\n          PC :: nil\n      ; lv_out :=\n          PC :: nil\n      ; clobbered :=\n          nil\n    |}.\n  \n  Lemma peep_vec_mull_selr :\n    StepEquiv.step_through_equiv_live (fnd peep_vec_mull_defs) (rpl peep_vec_mull_defs) (lv_in peep_vec_mull_defs) (lv_out peep_vec_mull_defs).\n  Proof.    \n    prep_l.    \n    step_l.\n    step_l.\n    step_l.\n    step_l.\n    step_l.\n    step_l.\n    step_l.\n    step_l.\n    step_l.\n    step_l.\n    step_l.\n    step_l.\n    step_l.\n    step_l.\n    step_l.\n    step_l.\n    prep_r.    \n    (* step_r. *)\n    prep_exec_instr.\n    {\n      clear -H.\n      assert False by admit.\n      exfalso.\n      assumption.\n    }\n    repeat break_exists.\n    specialize (H4 x3).\n\n    step_r.\n\n    prep_exec_instr.\n    {\n      clear -H.\n      assert False by admit.\n      exfalso.\n      assumption.\n    }\n    repeat break_exists.\n    specialize (H20 x3).\n    step_r.\n\n    prep_exec_instr.\n    {\n      clear -H.\n      assert False by admit.\n      exfalso.\n      assumption.\n    }\n    repeat break_exists.\n    specialize (H35 x3).\n    step_r.\n\n    prep_exec_instr.\n    {\n      clear -H.\n      assert False by admit.\n      exfalso.\n      assumption.\n    }\n    repeat break_exists.\n    specialize (H50 x3).\n    step_r.\n\n    prep_exec_instr.\n    {\n      clear -H.\n      assert False by admit.\n      exfalso.\n      assumption.\n    }\n    repeat break_exists.\n    specialize (H64 x3).\n    step_r.\n\n    prep_exec_instr.\n    {\n      clear -H.\n      assert False by admit.\n      exfalso.\n      assumption.\n    }\n    repeat break_exists.\n    specialize (H77 x3).\n    step_r.\n\n    prep_exec_instr.\n    {\n      clear -H.\n      assert False by admit.\n      exfalso.\n      assumption.\n    }\n    repeat break_exists.\n    specialize (H92 x3).\n    step_r.\n\n    prep_exec_instr.\n    {\n      clear -H.\n      assert False by admit.\n      exfalso.\n      assumption.\n    }\n    repeat break_exists.\n    specialize (H106 x3).\n    step_r.\n\n    prep_exec_instr.\n    {\n      clear -H.\n      assert False by admit.\n      exfalso.\n      assumption.\n    }\n    repeat break_exists.\n    specialize (H134 x3).\n    step_r.\n\n    step_r.\n    step_r.\n    step_r.\n    step_r.\n    step_r.\n    step_r.\n    step_r.\n\n    assert (x43 = md').\n    exploit step_through_md; eauto.\n    unfold peep_code.\n    simpl.\n    intros.\n    repeat break_or; simpl; tauto.\n    subst x43.\n    \n    finish_r.\n    admit.\n  Qed.\n\n  Definition peep_vec_mull_proofs : rewrite_proofs :=\n    {|\n      defs := peep_vec_mull_defs\n      ; selr := peep_vec_mull_selr\n    |}.\n\n  Definition peep_vec_mull :\n    concrete = fnd peep_vec_mull_defs ->\n    StepEquiv.rewrite.\n  Proof.\n    intros.\n    peep_tac_mk_rewrite' peep_vec_mull_defs peep_vec_mull_proofs; admit.\n  Qed.\n\nEnd VEC_MULL.\n\nDefinition peep_vec_mull_rewrite (c : code) : option StepEquiv.rewrite.\n  name peep_vec_mull p.\n  unfold peep_vec_mull_defs in p.\n  simpl in p. \n  specialize (p c).\n  set_code_cons c.\n  set_code_cons c.\n  set_code_cons c.\n  set_code_cons c.\n  set_code_cons c.\n  set_code_cons c.\n  set_code_cons c.\n  set_code_cons c.\n  set_code_cons c.\n  set_code_cons c.\n  set_code_cons c.\n  set_code_cons c.\n  set_code_cons c.\n  set_code_cons c.\n  set_code_cons c.\n  set_code_cons c.\n  set_code_nil c.\n  set_instr_eq i 0%nat peep_vec_mull_example.\n  set_instr_eq i0 1%nat peep_vec_mull_example.\n  set_instr_eq i1 2%nat peep_vec_mull_example.\n  set_instr_eq i2 3%nat peep_vec_mull_example.\n  set_instr_eq i3 4%nat peep_vec_mull_example.\n  set_instr_eq i4 5%nat peep_vec_mull_example.\n  set_instr_eq i5 6%nat peep_vec_mull_example.\n  set_instr_eq i6 7%nat peep_vec_mull_example.\n  set_instr_eq i7 8%nat peep_vec_mull_example.\n  set_instr_eq i8 9%nat peep_vec_mull_example.\n  set_instr_eq i9 10%nat peep_vec_mull_example.\n  set_instr_eq i10 11%nat peep_vec_mull_example.\n  set_instr_eq i11 12%nat peep_vec_mull_example.\n  set_instr_eq i12 13%nat peep_vec_mull_example.\n  set_instr_eq i13 14%nat peep_vec_mull_example.\n  set_instr_eq i14 15%nat peep_vec_mull_example.\n\n  Require Import AddrmodeEq.\n  destruct (addrmode_eq a1 (addr_add a 8)); [|exact None].\n  destruct (addrmode_eq a3 (addr_add a 16)); [|exact None].\n  destruct (addrmode_eq a5 (addr_add a 24)); [|exact None].\n  destruct (addrmode_eq a2 (addr_add a0 8)); [|exact None].\n  destruct (addrmode_eq a4 (addr_add a0 16)); [|exact None].\n  destruct (addrmode_eq a6 (addr_add a0 24)); [|exact None].\n  destruct (addrmode_eq a9 (addr_add a7 8)); [|exact None].\n  destruct (addrmode_eq a10 (addr_add a7 16)); [|exact None].\n  destruct (addrmode_eq a11 (addr_add a7 24)); [|exact None].\n\n  subst.\n  unfold a8 in *.\n  unfold b8 in *.\n  unfold c8 in *.\n  unfold a16 in *.\n  unfold b16 in *.\n  unfold c16 in *.\n  unfold a24 in *.\n  unfold b24 in *.\n  unfold c24 in *.\n  destruct (preg_eq rd rd1); [|exact None]. \n  destruct (preg_eq rd0 r1); [|exact None].\n  destruct (preg_eq rd2 rd4); [|exact None]. \n  destruct (preg_eq rd3 r0); [|exact None].\n  destruct (preg_eq rd5 rd7); [|exact None]. \n  destruct (preg_eq rd6 r2); [|exact None].\n  destruct (preg_eq rd8 rd10); [|exact None]. \n  destruct (preg_eq rd9 r3); [|exact None].\n  destruct (preg_eq r4 rd1); [|exact None].\n  destruct (preg_eq r5 rd4); [|exact None].\n  destruct (preg_eq r6 rd7); [|exact None].\n  destruct (preg_eq r7 rd10); [|exact None].\n  inv e. inv e0.\n  inv e1. inv e2.\n  inv e3. inv e4.\n  inv e5. inv e6.\n  inv e7. inv e8.\n  inv e9. inv e10.\n  specialize (p rd1 r1).\n  specialize (p rd4 r0).\n  specialize (p rd7 r2).\n  specialize (p rd10 r3).\n  specialize (p a a0 a7).\n  specialize (p eq_refl).\n  exact (Some p).\nQed.\n\nEnd Imp.\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_VecMul.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2520554619551142}}
{"text": "Require Import Process Refinement ModelCheck.\n\n\nModule Done.\n  Definition chs : channels := fun _ => nat.\n\n  Definition pr : process chs := Done.\n\n  Theorem pr_pr : refines pr pr.\n  Proof.\n    mc.\n  Qed.\nEnd Done.\n\nModule DoneSend.\n  Definition chs : channels := fun _ => nat.\n\n  Definition pr1 : process chs := Done.\n\n  Definition pr2 : process chs := #!chs[\"X\", 0], Done.\n\n  Theorem pr1_pr2 : refines pr1 pr2.\n  Proof.\n    mc.\n  Qed.\nEnd DoneSend.\n\nModule Send.\n  Definition chs : channels := fun _ => nat.\n\n  Definition pr : process chs := #!chs[\"X\", 0], Done.\n\n  Theorem pr_pr : refines pr pr.\n  Proof.\n    mc.\n  Qed.\nEnd Send.\n\nModule Recv.\n  Definition chs : channels := fun _ => nat.\n\n  Definition pr : process chs := #?chs[\"X\", x], Done.\n\n  Theorem pr_pr : refines pr pr.\n  Proof.\n    mc.\n  Qed.\nEnd Recv.\n\nModule RecvSend.\n  Definition chs : channels := fun _ => nat.\n\n  Definition pr : process chs := #?chs[\"X\", x], #!chs[\"Y\", x], Done.\n\n  Theorem pr_pr : refines pr pr.\n  Proof.\n    mc.\n  Qed.\nEnd RecvSend.\n\nModule ComputeRhs.\n  Definition chs : channels := fun _ => nat.\n\n  Definition pr1 : process chs := #!chs[\"X\", 0], Done.\n\n  Definition pr2 : process chs := (#?chs[\"Y\", v], #!chs[\"X\", v], Done) || (#!chs[\"Y\", 0], Done).\n\n  Theorem pr1_pr2 : refines pr1 pr2.\n  Proof.\n    mc.\n  Qed.\nEnd ComputeRhs.\n\nModule SwapSend.\n  Definition chs : channels := fun _ => nat.\n\n  Definition pr1 : process chs := (#!chs[\"X\", 0], Done) || (#!chs[\"Y\", 1], Done).\n\n  Definition pr2 : process chs := (#!chs[\"Y\", 1], Done) || (#!chs[\"X\", 0], Done).\n\n  Theorem pr1_pr2 : refines pr1 pr2.\n  Proof.\n    mc.\n  Qed.\nEnd SwapSend.\n\nModule SwapSendRecv.\n  Definition chs : channels := fun _ => nat.\n\n  Definition pr1 : process chs := (#!chs[\"X\", 0], Done) || (#?chs[\"Y\", x], #!chs[\"Z\", x], Done).\n\n  Definition pr2 : process chs := (#?chs[\"Y\", x], #!chs[\"Z\", x], Done) || (#!chs[\"X\", 0], Done).\n\n  Theorem pr1_pr2 : refines pr1 pr2.\n  Proof.\n    mc.\n  Qed.\nEnd SwapSendRecv.\n\nModule WithSelf.\n  Definition chs : channels := fun _ => nat.\n\n  Definition pr1 : process chs := ##[(Send, \"X\")],\n    (#?chs[\"Y\", x], #!chs[\"X\", S x], Done)\n    || (#!chs[\"Y\", 0], Done).\n\n  Definition pr2 : process chs := #!chs[\"X\", 1], Done.\n\n  Theorem pr1_pr2 : refines pr1 pr2.\n  Proof.\n    mc.\n  Qed.\nEnd WithSelf.\n\nModule WithMoreSelf.\n  Definition chs : channels := fun _ => nat.\n\n  Definition pr1 : process chs := ##[(Send, \"X\")],\n    (#?chs[\"Y\", x], #!chs[\"X\", S x], Done)\n    || (#!chs[\"Y\", 0], Done)\n    || (#!chs[\"Y\", 1], Done).\n\n  Definition pr2 : process chs :=\n    (#!chs[\"X\", 2], Done)\n    || (#!chs[\"X\", 1], Done).\n\n  Theorem pr1_pr2 : refines pr1 pr2.\n  Proof.\n    mc.\n  Qed.\nEnd WithMoreSelf.\n\nModule DependentTypingAhoy.\n  Definition chs : channels := fun s => if string_dec s \"B\" then bool else nat.\n\n  Definition pr1 : process chs := ##[(Recv, \"B\"), (Send, \"X\")],\n    (#?chs[\"B\", b], #?chs[\"N\", n], if b then #!chs[\"X\", 42], Done else #!chs[\"X\", n], Done)\n    || (#!chs[\"N\", 13], Done).\n\n  Definition pr2 : process chs :=\n    #?chs[\"B\", b], if b then #!chs[\"X\", 42], Done else #!chs[\"X\", 13], Done.\n\n  Theorem pr1_pr2 : refines pr1 pr2.\n  Proof.\n    mc.\n  Qed.\nEnd DependentTypingAhoy.\n\nModule RecvSendRestr.\n  Definition chs : channels := fun _ => nat.\n\n  Definition pr : process chs := ##[(Recv, \"X\"), (Send, \"Y\")], #?chs[\"X\", x], #!chs[\"Y\", x], Done.\n\n  Theorem pr_pr : refines pr pr.\n  Proof.\n    mc.\n  Qed.\nEnd RecvSendRestr.\n", "meta": {"author": "JasonGross", "repo": "apps", "sha": "906b9ca6f3f53e3a37a9a487a9289959f5167ba2", "save_path": "github-repos/coq/JasonGross-apps", "path": "github-repos/coq/JasonGross-apps/apps-906b9ca6f3f53e3a37a9a487a9289959f5167ba2/old-code/Examples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.25205546195511414}}
{"text": "(* THIS FILE CONTAINS\n   Lemmas that DO NOT depend on CompCert or Verifiable C,\n   and that are used in the proof of the C program but are not\n   used in the proof of functional_prog.v.\n*)\n\nRequire Recdef.\nRequire Import Integers.\nRequire Coq.Strings.String.\nRequire Coq.Strings.Ascii.\n(* Add LoadPath \"~/Desktop/Code/research/vst/compcert/lib\". *)\nRequire Import Coqlib.\n(* Add LoadPath \"~/Desktop/Code/research/compcert-2.4/lib\". *)\n(* Require Import compcert.lib.Coqlib. *)\nRequire Import List.\n(* Pwd. *)\n(* Add LoadPath \"~/Desktop/Code/research/vst/sha\". *)\n(* Require Import sha.SHA256. *)\nRequire Import SHA256.\n(* Add LoadPath \"~/Desktop/Code/research/vst/msl\". *)\nRequire Import Coqlib2.         (* formerly msl.Coqlib2 *)\nRequire Export common_lemmas.\n(* TODO fix *)\nRequire Psatz.\n\nGlobal Opaque CBLOCKz LBLOCKz.\n\nLemma int_min_signed_eq: Int.min_signed = -2147483648.\nProof. reflexivity. Qed.\n\nLemma int_max_signed_eq: Int.max_signed = 2147483647.\nProof. reflexivity. Qed.\n\nLemma int_max_unsigned_eq: Int.max_unsigned = 4294967295.\nProof. reflexivity. Qed.\n\nLtac repable_signed := \n   pose proof int_min_signed_eq; \n   pose proof int_max_signed_eq; \n   pose proof int_max_unsigned_eq; \n(*   unfold repable_signed in *; *)\n   omega.\n\nHint Rewrite Int.bits_or using omega : testbit.\nHint Rewrite Int.bits_shl using omega : testbit.\nHint Rewrite Int.bits_and using omega : testbit.\nHint Rewrite Int.bits_shru using omega : testbit.\nHint Rewrite Int.unsigned_repr using omega : testbit.\nHint Rewrite Int.testbit_repr using omega : testbit.\nHint Rewrite if_false using omega : testbit.\nHint Rewrite if_true using omega : testbit.\nHint Rewrite Z.ones_spec_low using omega : testbit.\nHint Rewrite Z.ones_spec_high using omega : testbit.\nHint Rewrite orb_false_r orb_true_r andb_false_r andb_true_r : testbit.\nHint Rewrite orb_false_l orb_true_l andb_false_l andb_true_l : testbit.\nHint Rewrite Z.add_simpl_r : testbit.\nHint Rewrite Int.unsigned_repr using repable_signed : testbit.\n\nLemma Ztest_Inttest:\n forall a, Z.testbit (Int.unsigned a) = Int.testbit a.\nProof. reflexivity. Qed.\nHint Rewrite Ztest_Inttest : testbit.\n\nDefinition swap (i: int) : int :=\n Int.or (Int.shl (Int.and i (Int.repr 255)) (Int.repr 24))\n   (Int.or (Int.shl (Int.and (Shr 8 i) (Int.repr 255)) (Int.repr 16))\n      (Int.or (Int.shl (Int.and (Shr 16 i) (Int.repr 255)) (Int.repr 8))\n         (Shr 24 i))).\n\nLemma swap_swap: forall w, swap (swap w) = w.\nProof.\nunfold swap, Shr; intros.\napply Int.same_bits_eq; intros.\nassert (Int.zwordsize=32) by reflexivity.\nchange 255 with (Z.ones 8).\nassert (32 < Int.max_unsigned) by (compute; auto).\nautorewrite with testbit.\nif_tac; [if_tac; [if_tac | ] | ]; autorewrite with testbit; f_equal; omega.\nQed.\n\nLemma map_swap_involutive:\n forall l, map swap (map swap l)  = l.\nProof. intros.\n rewrite map_map. \n replace (fun x => swap (swap x)) with (@Datatypes.id int).\n apply map_id. extensionality x. symmetry; apply swap_swap.\nQed.\n\nLemma isbyteZ_testbit:\n  forall i j, 0 <= i < 256 -> j >= 8 -> Z.testbit i j = false.\nProof.\nintros; erewrite Byte.Ztestbit_above with (n:=8%nat); auto.\nQed.\n\nLemma length_intlist_to_Zlist:\n  forall l, length (intlist_to_Zlist l) = (4 * length l)%nat.\nProof.\ninduction l.\nsimpl. reflexivity. simpl. omega.\nQed.\n\nLemma Zlength_intlist_to_Zlist: forall l,\n  Zlength (intlist_to_Zlist l) = WORD*Zlength l.\nProof.\nintros. repeat rewrite Zlength_correct. rewrite length_intlist_to_Zlist.\nrewrite Nat2Z.inj_mul. reflexivity.\nQed.\n\nLemma intlist_to_Zlist_Z_to_int_cons:\n  forall a b c d l, \n      isbyteZ a -> isbyteZ b -> isbyteZ c -> isbyteZ d ->\n     intlist_to_Zlist (Z_to_Int a b c d :: l) = \n     a::b::c::d:: intlist_to_Zlist l.\nProof.\nintros. simpl.\nunfold isbyteZ in *.\nassert (Int.zwordsize=32)%Z by reflexivity.\nunfold Z_to_Int, Shr; simpl.\nchange 255%Z with (Z.ones 8).\nrepeat f_equal; auto;\nmatch goal with |- _ = ?A => transitivity (Int.unsigned (Int.repr A));\n   [f_equal | apply Int.unsigned_repr; repable_signed]\nend;\napply Int.same_bits_eq; intros;\nautorewrite with testbit.\n*\nif_tac; autorewrite with testbit; [ | symmetry; apply isbyteZ_testbit; omega].\nrewrite (isbyteZ_testbit b) by omega.\nrewrite (isbyteZ_testbit c) by omega.\nrewrite (isbyteZ_testbit d) by omega.\nautorewrite with testbit; auto.\n*\nif_tac; autorewrite with testbit; [ | symmetry; apply isbyteZ_testbit; omega].\nif_tac; autorewrite with testbit; [ | symmetry; apply isbyteZ_testbit; omega].\nrewrite (isbyteZ_testbit c) by omega.\nrewrite (isbyteZ_testbit d) by omega.\nautorewrite with testbit; auto.\n*\nif_tac; autorewrite with testbit; [ | symmetry; apply isbyteZ_testbit; omega].\nif_tac; autorewrite with testbit; [ | symmetry; apply isbyteZ_testbit; omega].\nif_tac; autorewrite with testbit; [ | symmetry; apply isbyteZ_testbit; omega].\nrewrite (isbyteZ_testbit d) by omega.\nautorewrite with testbit; auto.\n*\ndestruct (zlt i 8); autorewrite with testbit;  [ | symmetry; apply isbyteZ_testbit; omega].\nauto.\nQed.\n\nLemma Zlist_to_intlist_to_Zlist:\n  forall nl: list Z, \n  NPeano.divide (Z.to_nat WORD) (length nl) ->\n  Forall isbyteZ nl ->\n  intlist_to_Zlist (Zlist_to_intlist nl) = nl.\nProof.\nintros nl [k H].\nrevert nl H; induction k; intros.\ndestruct nl; inv H; reflexivity.\nsimpl in H.\ndestruct nl as [ | a [ | b [ | c [ | d ?]]]]; inv H.\ninv H0. inv H4. inv H5. inv H6.\nunfold Zlist_to_intlist; fold Zlist_to_intlist.\nrewrite intlist_to_Zlist_Z_to_int_cons by auto.\nrepeat f_equal; auto.\nQed.\n\nLemma intlist_to_Zlist_to_intlist:\n  forall il: list int,\n   Zlist_to_intlist (intlist_to_Zlist il) = il.\nProof.\ninduction il.\nreflexivity.\nsimpl.\nf_equal; auto. clear.\nassert (Int.zwordsize=32)%Z by reflexivity.\nunfold Z_to_Int, Shr; simpl.\nchange 255%Z with (Z.ones 8).\napply Int.same_bits_eq; intros.\nrewrite Int.repr_unsigned.\nautorewrite with testbit.\nif_tac; autorewrite with testbit; [ | f_equal; omega].\nif_tac; autorewrite with testbit; [ | f_equal; omega].\nif_tac; autorewrite with testbit; [ | f_equal; omega].\nauto.\nQed.\n\nLemma length_Zlist_to_intlist: forall n l, \n       length l = (Z.to_nat WORD * n)%nat -> \n       length (Zlist_to_intlist l) = n.\nProof.\ninduction n; intros.\ndestruct l; inv H; reflexivity.\nreplace (S n) with (1 + n)%nat in H by omega.\nrewrite mult_plus_distr_l in H.\ndestruct l as [|i0 l]; [ inv H |].\ndestruct l as [|i1 l]; [ inv H |].\ndestruct l as [|i2 l]; [ inv H |].\ndestruct l as [|i3 l]; [ inv H |].\nsimpl. f_equal. apply IHn. forget (Z.to_nat WORD * n)%nat as A. inv H; auto.\nQed.\n\nLemma big_endian_integer_ext:\n forall f f', (forall z, (0 <= z < WORD)%Z -> f z = f' z) ->\n    big_endian_integer f = big_endian_integer f'.\nProof.\nunfold big_endian_integer;\nintros.\nrepeat f_equal; intros; apply H; repeat split; compute; auto; congruence.\nQed.\n\n\nLocal Open Scope nat.\n\nDefinition LBLOCK : nat := Z.to_nat LBLOCKz.   \nDefinition CBLOCK : nat := Z.to_nat CBLOCKz.\nOpaque LBLOCK CBLOCK.\n\nLemma LBLOCK_zeq: Z.of_nat LBLOCK = 16%Z.\nProof. reflexivity. Qed.\n\nLemma CBLOCK_zeq: (Z.of_nat CBLOCK = 64%Z).\nProof. reflexivity. Qed.\n\nLemma LBLOCKz_nonneg: (0 <= LBLOCKz)%Z.\nProof. change LBLOCKz with 16%Z; omega. Qed.\nHint Resolve LBLOCKz_nonneg.\n\nLemma LBLOCKz_pos: (0 < LBLOCKz)%Z.\nProof. change LBLOCKz with 16%Z; omega. Qed.\nHint Resolve LBLOCKz_pos.\n\nLemma CBLOCKz_nonneg: (0 <= CBLOCKz)%Z.\nProof. change CBLOCKz with 64%Z; omega. Qed.\nHint Resolve CBLOCKz_nonneg.\n\nLemma CBLOCKz_pos: (0 < CBLOCKz)%Z.\nProof. change CBLOCKz with 64%Z; omega. Qed.\nHint Resolve CBLOCKz_pos.\n\nLemma intlist_to_Zlist_app:\n forall al bl, intlist_to_Zlist (al++bl) = intlist_to_Zlist al ++ intlist_to_Zlist bl.\nProof. intros; induction al; simpl; auto. repeat f_equal; auto. Qed.\n\nLemma firstn_app:\n forall {A} n m (al: list A), firstn n al ++ firstn m (skipn n al) =\n  firstn (n+m) al.\nProof. induction n; destruct al; intros; simpl; auto.\ndestruct m; reflexivity.\nf_equal; auto.\nQed.\n\nLemma nth_skipn:\n  forall A i n data (d:A),\n       nth i (skipn n data) d = nth (i+n) data d.\nProof.\nintros.\nrevert i data; induction n; simpl; intros.\nf_equal; omega.\ndestruct data; auto.\ndestruct i; simpl; auto.\nrewrite IHn.\nreplace (i + S n) with (S (i + n)) by omega; auto.\nQed.\n\nLemma Forall_app :\nforall {A} P (l1 l2 :list A),\nForall P (l1 ++ l2) <->\nForall P l1 /\\ Forall P l2.\nintros.\nsplit; induction l1; intros.\ninv H. destruct l2; inv H0. auto.\nsplit. auto. simpl in H2. inv H2.\nconstructor; auto.\nsplit. inv H. constructor; auto. apply IHl1 in H3.\nintuition.\ninv H. apply IHl1 in H3. intuition.\nsimpl. intuition.\nsimpl. constructor.\ndestruct H. inv H. auto.\napply IHl1. intuition.\ninv H0; auto.\nQed.\n\nLemma firstn_firstn: forall {A} lo n (data: list A), firstn lo (firstn (lo + n) data) = firstn lo data.\nProof.\n  intros.\n  revert data; induction lo; intros.\n  + reflexivity.\n  + destruct data; simpl; [reflexivity |].\n    rewrite IHlo.\n    reflexivity.\nQed.\n\nLemma skipn_firstn: forall {A} lo n (data: list A), skipn lo (firstn (lo + n) data) = firstn n (skipn lo data).\nProof.\n  intros.\n  revert data; induction lo; intros.\n  + reflexivity.\n  + destruct data; simpl.\n    - destruct n; reflexivity.\n    - apply IHlo.\nQed.\n\nLemma Zlength_app: forall T (al bl: list T),\n    Zlength (al++bl) = (Zlength al + Zlength bl)%Z.\nProof. induction al; intros. simpl app; rewrite Zlength_nil; omega.\n simpl app; repeat rewrite Zlength_cons; rewrite IHal; omega.\nQed.\nLemma Zlength_rev: forall T (vl: list T), Zlength (rev vl) = Zlength vl.\nProof. induction vl; simpl; auto. rewrite Zlength_cons. rewrite <- IHvl.\nrewrite Zlength_app. rewrite Zlength_cons. rewrite Zlength_nil; omega.\nQed.\n\nLemma Zlength_map: forall A B (f: A -> B) l, Zlength (map f l) = Zlength l.\nProof. induction l; simpl; auto. repeat rewrite Zlength_cons. f_equal; auto.\nQed.\n\nLocal Open Scope Z.\n\nLemma divide_length_app:\n forall {A} n (al bl: list A), \n      (n | Zlength al) -> \n      (n | Zlength bl) ->\n      (n | Zlength (al++bl)).\nProof.\n intros. destruct H,H0. exists (x+x0)%Z.\n rewrite Zlength_app,H,H0;  \n rewrite Z.mul_add_distr_r; omega.\nQed.\n\nLemma isbyte_intlist_to_Zlist : forall l, Forall isbyteZ (intlist_to_Zlist l).\nProof.\ninduction l; simpl; intros.\nconstructor.\nassert (forall i, Int.unsigned (Int.and i (Int.repr 255)) < 256).\nclear; intro.\neapply Z.lt_le_trans.\napply (Int.and_interval i (Int.repr (Z.ones 8))).\nchange (Int.size  (Int.repr (Z.ones 8))) with 8.\nrewrite Zmin_spec.\nif_tac.\neapply Z.le_trans with (two_p 8).\napply two_p_monotone. \nsplit; [ | omega].\napply Int.size_range.\ncompute; congruence.\ncompute; congruence.\nunfold Shr, isbyteZ; repeat constructor; try apply Int.unsigned_range; auto; clear IHl.\nrewrite <- (Int.divu_pow2 a (Int.repr (2 ^ 24)) (Int.repr 24) (eq_refl _)).\nunfold Int.divu.\nrewrite Int.unsigned_repr.\nrewrite Int.unsigned_repr by (compute; split; congruence).\napply Z.div_lt_upper_bound.\ncompute; congruence.\nchange (2 ^ 24 * 256)%Z with (Int.modulus).\napply Int.unsigned_range.\nassert (0 < 2 ^ 24)\n by (apply Z.pow_pos_nonneg; clear; omega).\nrewrite Int.unsigned_repr by (compute; split; congruence).\nsplit.\napply Z.div_pos; auto.\napply Int.unsigned_range.\napply Z.div_le_upper_bound; auto.\napply Z.le_trans with (Int.modulus+1).\ndestruct (Int.unsigned_range a).\nomega.\ncompute; congruence.\nQed.\n\nLemma isbyte_intlist_to_Zlist' : forall l,\n   Forall isbyteZ (map Int.unsigned (map Int.repr (intlist_to_Zlist l))).\nProof.\nintro.\nreplace (map Int.unsigned (map Int.repr (intlist_to_Zlist l))) with (intlist_to_Zlist l).\napply isbyte_intlist_to_Zlist.\ninduction l; simpl; auto.\nrepeat f_equal; auto; symmetry; apply Int.repr_unsigned.\nQed.\n\nLemma Forall_isbyte_repr_unsigned:\n forall l: list int, map Int.repr (map Int.unsigned l) = l.\nProof.\ninduction l; intros.\nreflexivity.\nsimpl.\nf_equal; auto.\napply Int.repr_unsigned.\nQed.\n\nLemma map_unsigned_repr_isbyte:\n  forall l : list Z , Forall isbyteZ l -> map Int.unsigned (map Int.repr l) = l.\nProof. induction l; simpl; intros; auto.\n  inv H. f_equal; auto. unfold isbyteZ in H2; apply Int.unsigned_repr. \n assert (Int.max_unsigned > 256)%Z by (compute; congruence).\n omega.\nQed.\n\nLemma int_unsigned_inj: forall a b, Int.unsigned a = Int.unsigned b -> a=b.\nProof.\nintros.\nrewrite <- (Int.repr_unsigned a); rewrite <- (Int.repr_unsigned b).\ncongruence.\nQed.\n\nLemma intlist_to_Zlist_inj: forall al bl, intlist_to_Zlist al = intlist_to_Zlist bl -> al=bl.\nProof.\ninduction al; destruct bl; intros; auto.\ninv H.\ninv H.\nsimpl in H.\ninjection H; intros.\nf_equal; auto.\nclear - H1 H2 H3 H4.\nrename i into b.\napply int_unsigned_inj in H1.\napply int_unsigned_inj in H2.\napply int_unsigned_inj in H3.\napply int_unsigned_inj in H4.\nunfold Shr in *.\napply Int.same_bits_eq; intros.\nassert (Int.zwordsize=32)%Z by reflexivity.\nchange 255%Z with (Z.ones 8) in *.\ndestruct (zlt i 8).\ntransitivity (Int.testbit (Int.and a (Int.repr (Z.ones 8))) i).\nautorewrite with testbit; auto.\nrewrite H1. autorewrite with testbit; auto.\ndestruct (zlt i 16).\ntransitivity (Int.testbit (Int.and (Int.shru a (Int.repr 8)) (Int.repr (Z.ones 8))) (i-8)).\nautorewrite with testbit.\nchange (Int.unsigned (Int.repr 8)) with 8%Z.\nrewrite Z.sub_add; auto.\nrewrite H2.\nautorewrite with testbit.\nrewrite Z.sub_add. auto.\ndestruct (zlt i 24).\ntransitivity (Int.testbit (Int.and (Int.shru a (Int.repr 16)) (Int.repr (Z.ones 8))) (i-16)).\nautorewrite with testbit.\nchange (Int.unsigned (Int.repr 16)) with 16%Z.\nrewrite Z.sub_add. auto.\nrewrite H3.\nautorewrite with testbit.\nchange (Int.unsigned (Int.repr 16)) with 16%Z.\nrewrite Z.sub_add. auto.\ntransitivity (Int.testbit (Int.shru a (Int.repr 24)) (i-24)).\nautorewrite with testbit.\nchange (Int.unsigned (Int.repr 24)) with 24%Z.\nrewrite Z.sub_add. auto.\nrewrite H4.\nautorewrite with testbit.\nchange (Int.unsigned (Int.repr 24)) with 24%Z.\nrewrite Z.sub_add. auto.\nQed.\n\nLemma Zlength_intlist_to_Zlist_app:\n forall al bl,  Zlength (intlist_to_Zlist (al++bl)) =\n    (Zlength (intlist_to_Zlist al) + Zlength (intlist_to_Zlist bl))%Z.\nProof.\ninduction al; simpl; intros; auto.\nrepeat rewrite Zlength_cons.\nrewrite IHal.\nomega.\nQed.\n\nLemma Forall_firstn:\n  forall A (f: A -> Prop) n l, Forall f l -> Forall f (firstn n l).\nProof.\ninduction n; destruct l; intros.\nconstructor. constructor. constructor.\ninv H. simpl. constructor; auto.\nQed.\n\nLemma Forall_skipn:\n  forall A (f: A -> Prop) n l, Forall f l -> Forall f (skipn n l).\nProof.\ninduction n; destruct l; intros.\nconstructor. inv H; constructor; auto. constructor.\ninv H. simpl.  auto.\nQed.\n\nLocal Open Scope Z.\n\nLemma add_repr: forall i j, Int.add (Int.repr i) (Int.repr j) = Int.repr (i+j).\nProof. intros.\n  rewrite Int.add_unsigned.\n apply Int.eqm_samerepr.\n unfold Int.eqm.\n apply Int.eqm_add; apply Int.eqm_sym; apply Int.eqm_unsigned_repr.\nQed.\n\nLemma mul_repr:\n forall x y, Int.mul (Int.repr x) (Int.repr y) = Int.repr (x * y).\nProof.\nintros. unfold Int.mul.\napply Int.eqm_samerepr.\nrepeat rewrite Int.unsigned_repr_eq.\napply Int.eqm_mult; unfold Int.eqm; apply Int.eqmod_sym;\napply Int.eqmod_mod; compute; congruence.\nQed.\n\nLemma hilo_lemma:\n  forall hi lo, [Int.repr (hilo hi lo / Int.modulus), Int.repr (hilo hi lo)] = [hi, lo].\nProof.\nunfold hilo; intros.\nrewrite Z.div_add_l by (compute; congruence).\nrewrite Zdiv_small by apply Int.unsigned_range.\nrewrite Z.add_0_r.\nrewrite Int.repr_unsigned.\nf_equal.\nf_equal.\nrewrite <- add_repr.\nrewrite <- mul_repr.\nreplace (Int.repr Int.modulus) with (Int.repr 0).\nrewrite Int.mul_zero. rewrite Int.add_zero_l. apply Int.repr_unsigned.\napply Int.eqm_samerepr.\nunfold Int.eqm.\nchange 0 with (Int.modulus mod Int.modulus).\napply Int.eqmod_sym.\napply Int.eqmod_mod.\ncompute; congruence.\nQed.\n\nLemma Forall_isbyteZ_unsigned_repr:\n forall l, Forall isbyteZ l -> Forall isbyteZ (map Int.unsigned (map Int.repr l)).\nProof. induction 1. constructor.\nconstructor. rewrite Int.unsigned_repr; auto.\nunfold isbyteZ in H; repable_signed.\napply IHForall.\nQed.\n\nLemma divide_hashed:\n forall (bb: list int), \n    NPeano.divide LBLOCK (length bb) <->\n    (LBLOCKz | Zlength bb).\nProof.\nintros; split; intros [n ?].\nexists (Z.of_nat n). rewrite Zlength_correct, H.\nrewrite Nat2Z.inj_mul; auto.\nexists (Z.to_nat n).\nrewrite Zlength_correct in H.\nassert (0 <= n).\nassert (0 <= n * LBLOCKz) by omega.\napply Z.mul_nonneg_cancel_r in H0; auto.\nrewrite <- (Z2Nat.id (n*LBLOCKz)%Z) in H by omega.\napply Nat2Z.inj in H. rewrite H.\nchange LBLOCK with (Z.to_nat LBLOCKz).\nrewrite Z2Nat.inj_mul; auto.\nQed.\n\nLemma hash_blocks_equation' : forall (r : registers) (msg : list int),\n       hash_blocks r msg =\n       match msg with\n       | [] => r\n       | _ :: _ => hash_blocks (hash_block r (firstn LBLOCK msg)) (skipn LBLOCK msg)\n       end.\nProof. exact hash_blocks_equation. Qed.\n\nLemma CBLOCK_eq: CBLOCK=64%nat.\nProof. reflexivity. Qed.\nLemma LBLOCK_eq: LBLOCK=16%nat.\nProof. reflexivity. Qed.\n\nLemma hash_blocks_last:\n forall a bl c, \n              Zlength a = 8 ->\n              (LBLOCKz | Zlength bl) -> \n              Zlength c = LBLOCKz ->\n   hash_block (hash_blocks a bl) c = hash_blocks a (bl++ c).\nProof.\nintros.\nassert (POS: (0 < LBLOCK)%nat) by (rewrite LBLOCK_eq; omega).\napply divide_hashed in H0.\ndestruct H0 as [n ?].\nrewrite Zlength_correct in H,H1.\nchange 8 with (Z.of_nat 8) in H.\n(*change LBLOCK with 16%nat in H0.*)\nchange LBLOCKz with (Z.of_nat LBLOCK) in H1.\napply Nat2Z.inj in H. \napply Nat2Z.inj in H1.\nrevert a bl H H0; induction n; intros.\ndestruct bl; inv H0.\nrewrite hash_blocks_equation'. \nsimpl. rewrite hash_blocks_equation'.\ndestruct c eqn:?. inv H1.\nrewrite <- Heql in *; clear i l Heql.\nrewrite firstn_same by omega.\nreplace (skipn LBLOCK c) with (@nil int).\nrewrite hash_blocks_equation'; reflexivity.\npose proof (skipn_length LBLOCK c).\nspec H0; [omega |]. rewrite H1 in H0.\ndestruct (skipn LBLOCK c); try reflexivity; inv H0.\nreplace (S n * LBLOCK)%nat with (n * LBLOCK + LBLOCK)%nat  in H0 by\n  (simpl; omega).\nrewrite hash_blocks_equation'.\ndestruct bl.\nsimpl in H0.\nPsatz.lia.\nforget (i::bl) as bl'; clear i bl. rename bl' into bl.\nrewrite IHn.\nsymmetry.\nrewrite hash_blocks_equation.\ndestruct bl.\nsimpl in H0; Psatz.lia.\nunfold app at 1; fold app.\nforget (i::bl) as bl'; clear i bl. rename bl' into bl.\nf_equal.\nf_equal.\napply firstn_app1.\nPsatz.nia.\napply skipn_app1.\nPsatz.nia.\napply length_hash_block; auto. (* fixme *) change 16%nat with LBLOCK.\nrewrite firstn_length. apply min_l.\nPsatz.nia.\nrewrite skipn_length.\napply plus_reg_l with LBLOCK.\nrewrite plus_comm. \nrewrite NPeano.Nat.sub_add by Psatz.lia.\nomega.\n(*Psatz.lia.*)\nrewrite H0. assert (Hn: (n*LBLOCK >= 0)%nat).\n  remember ((n * LBLOCK)%nat). clear. omega.\n  omega. \nQed.\n\nLemma length_hash_blocks: forall regs blocks,\n  length regs = 8%nat ->\n  (LBLOCKz | Zlength blocks) ->\n  length (hash_blocks regs blocks) = 8%nat.\nProof.\nintros.\ndestruct H0 as [n ?].\nrewrite Zlength_correct in H0.\nassert (POS := LBLOCKz_pos).\nchange LBLOCKz with (Z.of_nat LBLOCK) in *.\nrewrite <- (Z2Nat.id n) in H0 \n by (apply -> Z.mul_nonneg_cancel_r ; [ | apply POS]; omega).\nrewrite <- Nat2Z.inj_mul in H0.\napply Nat2Z.inj in H0.\nrevert regs blocks H H0; induction (Z.to_nat n); intros.\n  destruct blocks; inv H0.\nrewrite hash_blocks_equation'; auto.\ndestruct blocks.\ndestruct LBLOCK; inv POS; inv H0.\nrewrite hash_blocks_equation'; auto.\nforget (i::blocks) as bb.\napply IHn0; auto.\napply length_hash_block; auto. (* fixme *) change 16%nat with LBLOCK.\nrewrite firstn_length. apply min_l. simpl in H0. Psatz.nia.\nrewrite skipn_length. rewrite H0; clear - POS.  simpl.\nrewrite plus_comm. rewrite NPeano.Nat.add_sub. auto.\nsimpl in H0. rewrite H0; clear - POS. Psatz.lia.\nQed.\n\nLemma nth_list_repeat: forall A i n (x :A),\n    nth i (list_repeat n x) x = x.\nProof.\n induction i; destruct n; simpl; auto.\nQed.\n\nLemma map_list_repeat:\n  forall A B (f: A -> B) n x,\n     map f (list_repeat n x) = list_repeat n (f x).\nProof. induction n; simpl; intros; f_equal; auto.\nQed.\n\nLemma Forall_list_repeat:\n  forall A (f: A -> Prop) n (x: A),\n     f x -> Forall f (list_repeat n x).\nProof.\n intros; induction n; simpl; auto.\nQed.\n\nLemma ZtoNat_Zlength: \n forall {A} (l: list A), Z.to_nat (Zlength l) = length l.\nProof.\nintros. rewrite Zlength_correct. apply Nat2Z.id.\nQed.\nHint Rewrite @ZtoNat_Zlength : norm.\n\nLemma Zlength_nonneg:\n forall {A} (l: list A), 0 <= Zlength l.\nProof.\nintros. rewrite Zlength_correct. omega.\nQed.\n\n\n\n\n", "meta": {"author": "k-qy", "repo": "vst-hmac", "sha": "324239050b2a0a29cb771ef93e8c7583f6731741", "save_path": "github-repos/coq/k-qy-vst-hmac", "path": "github-repos/coq/k-qy-vst-hmac/vst-hmac-324239050b2a0a29cb771ef93e8c7583f6731741/pure_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.25205546195511414}}
{"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 Psatz.\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(* Check hmapIsMember. *)\n\n\n(* Lemma foo: forall (l: Ledger) addr, isSome\n(eval_state\n (callEmbeddedStateAdj (H0 :=  FullState_T1xT2xT3xT4xT5xT6xT7xT8xT9xT10xT11xT12xT13xT14xT15xT16_T17)\n (DePoolFuncs.ParticipantBase_Ф_fetchParticipant\n addr)\n DePoolFuncs.DePoolSpec.LedgerClass.local0)\n l) =\nisSome\n(eval_state\n (callEmbeddedStateAdj (H0 :=  FullState_T1xT2xT3xT4xT5xT6xT7xT8xT9xT10xT11xT12xT13xT14xT15xT16_T17)\n (DePoolFuncs.ParticipantBase_Ф_fetchParticipant\n addr)\n DePoolFuncs.DePoolSpec.LedgerClass.local0)\n l).\n Proof.\n    intros.\n    reflexivity.\n Qed.    *)\n\n(* Existing Instance embeddedLocalState.\n \nExisting Instance monadStateT.\nExisting Instance monadStateStateT. *)\n\n(* Existing Instance embeddedLocalState.\nExisting Instance embeddedMultisig. *)\n\n \n \n \n (* function ConfigParamsBase.getCurValidatorData (  )  virtual internal returns  ( uint256 hash ,  uint32 utime_since ,  uint32 utime_until )   { \n         ( TvmCell cell ,  bool ok )  = tvm_rawConfigParam ( 34 )  ; \n        require ( ok ,  InternalErrors . ERROR508 )  ; \n        hash = tvm_hash ( cell )  ; \n        TvmSlice s = cell . toSlice (  )  ; \n         (  ,  utime_since ,  utime_until )  = s . decode ( uint8 ,  uint32 ,  uint32 )  ; \n     } \n\nDefinition ConfigParamsBase_Ф_getCurValidatorData :  LedgerT ( XErrorValue ( XInteger256 # XInteger32 # XInteger32 ) XInteger ) :=  \n\tU0! {( Л_cell , Л_ok )} := tvm_rawConfigParam (! $ xInt34 !) ;\n \tRequire {{ $ Л_ok , ↑ε8 InternalErrors_ι_ERROR508 }} ; \n \tU0! Л_hash := tvm_hash (! $ Л_cell !) ; \n \tU0! Л_s := ($ Л_cell) ->toSlice() ; \n\tU0! {( _ , Л_utime_since , Л_utime_until )} := ($ Л_s) ->decode(uint8,uint32,uint32) ;  (* (uint8 , uint32 , uint32) *)\n\treturn# ( $Л_hash, $Л_utime_since , $Л_utime_until ). \n*) \n\n\n\n Lemma ConfigParamsBase_Ф_getCurValidatorData_exec : forall (l: Ledger), \n    exec_state (  ConfigParamsBase_Ф_getCurValidatorData ) l =  l. \n Proof. \n   intros. destruct l. compute. auto.\n Qed. \n \n Lemma ConfigParamsBase_Ф_getCurValidatorData_eval : forall (l: Ledger) ,\n eval_state ( ConfigParamsBase_Ф_getCurValidatorData ) l =\n\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  if Л_ok then Value (hash , snd (fst (fst res)) , snd (fst res))\n          else Error (eval_state ( ↑8 ε InternalErrors_ι_ERROR508) l).\n Proof. \n   intros. destruct l. compute.  auto. \n Qed. \n \n (* function ConfigParamsBase.getPrevValidatorHash (  )  virtual internal returns  ( uint )   { \n         ( TvmCell cell ,  bool ok )  = tvm_rawConfigParam ( 32 )  ; \n        require ( ok ,  InternalErrors . ERROR507 )  ; \n        return tvm_hash ( cell )  ; \n     } \n\nDefinition ConfigParamsBase_Ф_getPrevValidatorHash : LedgerT ( XErrorValue XInteger XInteger ) := \n\tU0! {( Л_cell , Л_ok )} := tvm_rawConfigParam (! $ xInt32 !) ;\n \tRequire {{ $ Л_ok , ↑ε8 InternalErrors_ι_ERROR507 }} ; \n \t tvm_hash (! $ Л_cell !).*) \n\n Lemma ConfigParamsBase_Ф_getPrevValidatorHash_exec : forall (l: Ledger) , \n \t exec_state (  ConfigParamsBase_Ф_getPrevValidatorHash ) l = l .  \n Proof. \n   intros. destruct l. auto. \n Qed. \n \n Lemma ConfigParamsBase_Ф_getPrevValidatorHash_eval : forall (l: Ledger)  ,\n eval_state (  ConfigParamsBase_Ф_getPrevValidatorHash ) l = \n \n let (Л_cell, Л_ok) := eval_state (tvm_rawConfigParam 32) l in\n let hash := tvm_hash Л_cell in\n\n if Л_ok then Value hash\n else Error (eval_state ( ↑8 ε InternalErrors_ι_ERROR507) l).\n Proof. \n   intros. compute. auto.\n Qed. \n \n (* function ConfigParamsBase.roundTimeParams (  )  virtual internal returns  ( \n        uint32 validatorsElectedFor , \n        uint32 electionsStartBefore , \n        uint32 electionsEndBefore , \n        uint32 stakeHeldFor\n     )   { \n        bool ok ; \n         ( validatorsElectedFor ,  electionsStartBefore ,  electionsEndBefore ,  stakeHeldFor ,  ok )  = tvm_configParam ( 15 )  ; \n        require ( ok ,  InternalErrors . ERROR509 )  ; \n     } \n\nDefinition ConfigParamsBase_Ф_roundTimeParams  : LedgerT ( XErrorValue ( XInteger32 # XInteger32 # XInteger32 # XInteger32 ) XInteger )  := \n U0! {( Л_validatorsElectedFor , Л_electionsStartBefore , Л_electionsEndBefore , Л_stakeHeldFor , Л_ok )} := tvm_configParam (! $ xInt15 !) ; \n Require {{ $ Л_ok , ↑ε8 InternalErrors_ι_ERROR509 }} ; \n return# ($Л_validatorsElectedFor, $Л_electionsStartBefore, $Л_electionsEndBefore, $Л_stakeHeldFor ). \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 \n Lemma ConfigParamsBase_Ф_roundTimeParams_eval : forall (l: Ledger) ,\n  eval_state ConfigParamsBase_Ф_roundTimeParams l = \n  let (Л_params, Л_ок) := eval_state (tvm_configParam 15) l in\n  let stakeHeldFor := snd Л_params in\n  let electionsEndBefore := snd (fst Л_params) in\n  let electionsStartBefore := snd (fst (fst Л_params)) in\n  let validatorsElectedFor := fst (fst (fst Л_params)) in\n   if Л_ок\n    then\n      Value (validatorsElectedFor,\n            electionsStartBefore,\n            electionsEndBefore,\n            stakeHeldFor)\n    else Error (eval_state ( ↑8 ε InternalErrors_ι_ERROR509) l). \n Proof. \n   intros. destruct l.  compute. auto.\n Qed. \n \n (* function ConfigParamsBase.getMaxStakeFactor (  )  virtual pure internal returns  ( uint32 )   { \n         ( TvmCell cell ,  bool ok )  = tvm_rawConfigParam ( 17 )  ; \n        require ( ok ,  InternalErrors . ERROR516 )  ; \n        TvmSlice s = cell . toSlice (  )  ; \n        s . loadTons (  )  ; \n        s . loadTons (  )  ; \n        s . loadTons (  )  ; \n        return s . decode ( uint32 )  ; \n     } \n\nDefinition ConfigParamsBase_Ф_getMaxStakeFactor : LedgerT ( XErrorValue XInteger32 XInteger ) := \n\tU0! {( Л_cell , Л_ok )} := tvm_rawConfigParam (! $ xInt17 !) ; \n \tRequire {{ $ Л_ok , ↑ε8 InternalErrors_ι_ERROR516 }} ; \n \tU0! Л_s := ($ Л_cell) ->toSlice() ; \n \tЛ_s ->loadTons() ;\n \tЛ_s ->loadTons() ; \n \tЛ_s ->loadTons() ;\n\t($ Л_s) ->decode(uint32) . (*uint32*)\n*) \n\n Lemma ConfigParamsBase_Ф_getMaxStakeFactor_exec : forall (l: Ledger) , \n \t exec_state ConfigParamsBase_Ф_getMaxStakeFactor l = l .  \n Proof. \n   intros. destruct l. auto. \n Qed. \n \n Lemma ConfigParamsBase_Ф_getMaxStakeFactor_eval : forall (l: Ledger)  ,\n eval_state (  ConfigParamsBase_Ф_getMaxStakeFactor ) l = \n\n let (Л_cell, Л_ok) := eval_state (tvm_rawConfigParam 17) l in \n let sliceRaw := toSlice Л_cell in\n let t1 := tvm_loadTons (tvm_loadTons (tvm_loadTons sliceRaw)) in\n let res := fst (decode_uint32 t1) in \n if Л_ok\n then Value res\n else  Error (eval_state ( ↑8 ε InternalErrors_ι_ERROR516) l). \n Proof. \n   intros. destruct l. \n   compute. auto.\n Qed. \n \n (* function ConfigParamsBase.getElector (  )  virtual pure internal returns  ( address )   { \n         ( TvmCell cell ,  bool ok )  = tvm_rawConfigParam ( 1 )  ; \n        require ( ok ,  InternalErrors . ERROR517 )  ; \n        TvmSlice s = cell . toSlice (  )  ; \n        uint256 value = s . decode ( uint256 )  ; \n        return address . makeAddrStd (  - 1 ,  value )  ; \n     } \n\nDefinition ConfigParamsBase_Ф_getElector : LedgerT ( XErrorValue XAddress XInteger ) := \n U0! {( Л_cell , Л_ok )} := tvm_rawConfigParam (! $ xInt1 !) ; \n Require {{ $ Л_ok , ↑ε8 InternalErrors_ι_ERROR517 }} ; \n U0! Л_s := ($ Л_cell) ->toSlice() ; \n U0! Л_value := ($ Л_s) ->decode(uint256) ; \n  address->makeAddrStd (! $xInt0 !- $ xInt1 , $ Л_value !) .\n*) \n\n Lemma ConfigParamsBase_Ф_getElector_exec : forall (l: Ledger) , \n \t exec_state ConfigParamsBase_Ф_getElector l = l .  \n Proof. \n   intros. destruct l. auto. \n Qed. \n \n Lemma ConfigParamsBase_Ф_getElector_eval : forall (l: Ledger) ,\n eval_state  ConfigParamsBase_Ф_getElector l =\n\n let (Л_cell, Л_ok) := eval_state (tvm_rawConfigParam 1) l in\n\n let sliceRaw := toSlice Л_cell in      \n let v := fst (decode_uint256 sliceRaw) in\n let res := address_makeAddrStd (-1)%Z v in\n\n  if Л_ok then Value res\n    else Error (eval_state ( ↑8 ε InternalErrors_ι_ERROR517) l).\n Proof. \n  intros. destruct l.\n  compute. 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/ConfigParamsBaseProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.25205546195511414}}
{"text": "(*\n * Module: Instructions\n *\n * Description:\n *  This module defines the various instructions that exist within the language.\n *)\n\nRequire Import TLB.\nRequire Import Arith.\n\n(*\n * Inductive Type: tm\n *\n * Description:\n *   This data type represents all of the instructions that can occur in\n *   the language.  It also contains a \"val\" instruction which encapsulates\n *   data that can be stored in the store.\n *\n *   It's called \"tm\" because tm is short for \"term\" which is what the basic\n *   element of most small-step semantics are called.\n *\n *   This machine has a single register and has memory addressing modes.\n *\n *   val : Represents a value in memory\n *   sec : Represents a secret value in memory\n *   ldi : Load immediate value into register\n *   lda : Load value from specified address into register\n *   sta : Store value in register into specified address\n *   add : Add a constant value to the value in the register.  The result stays\n *         within the register.\n *   map : Add a TLB entry to the MMU.\n *   invalidate : Reset a TLB entry back to a default value.\n *   jmp : Jump to the address located in the register.\n *   jeq : Jump to the specified address if the register is zero.\n *   jne : Jump to the specified address if the register is negative.\n *   trap: Generate a machine trap (syscall, exception, or interrupt).\n *   iret: Return from a trap.\n *   svaDeclareStack : Declare a range of memory to be a stack.\n *   svaLoadPGTable : Load the ASID value\n *   svaInitStack   : Create and initialize a new thread\n *   svaSwap        : Switch to a new thread identified in the register\n *   svaRegisterTrap: Register a trap handler\n *   svaSaveIcontext: Save a copy of the interrupt context\n *   svaLoadIcontext: Save a copy of the interrupt context\n *   svaPushFunction: Push a function frame on to the interrupted stack\n *   jsr : Jump to the subroutine located in the register.\n *   ret : Return to the previously executed jsr instruction.\n *)\nInductive tm : Type :=\n  | val  : nat -> tm\n  | sec  : tm\n  | ldi  : nat -> tm\n  | lda  : nat -> tm\n  | sta  : nat -> tm\n  | add  : nat -> tm\n  | sub  : nat -> tm\n  | map  : nat -> TLBTy -> tm\n  | jmp  : tm\n  | jeq  : nat -> tm\n  | jne  : nat -> tm\n  | trap : tm\n  | iret : tm\n  | svaDeclareStack : nat -> nat -> tm\n  | svaLoadPGTable : tm\n  | svaInitStack : nat -> tm\n  | svaSwap : tm\n  | svaRegisterTrap : tm\n  | svaSaveIcontext : tm\n  | svaLoadIcontext : tm\n  | svaPushFunction : nat -> tm\n  | jsr : tm\n  | ret : tm.\n\n", "meta": {"author": "jtcriswell", "repo": "Pudding", "sha": "1ea9885e213771bf923f9791b9bdf41a19a0be1e", "save_path": "github-repos/coq/jtcriswell-Pudding", "path": "github-repos/coq/jtcriswell-Pudding/Pudding-1ea9885e213771bf923f9791b9bdf41a19a0be1e/Instructions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.61878043374385, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2520499379587779}}
{"text": "Require Import SetoidList ZArith Lia.\nRequire Import Flocq.Core.Zaux.\nFrom compcert Require Import common.Errors backend.Cminor lib.Integers.\nFrom sparkfrontend Require Import LibTac LibHypsNaming compcert_utils more_stdlib.\nImport compcert.common.Memory.\nRequire compcert.cfrontend.Ctypes.\n\n(*Require Import sparkfrontend.LibTac sparkfrontend.LibHypsNaming  compcert.common.Errors\n        compcert.common.Cminor compcert.lib.Integers sparkfrontend.compcert_utils sparkfrontend.more_stdlib.*)\n\nOpen Scope nat_scope.\n(** The Chaining structure of the stacks.\n\nIn this section we describe the way the first element of each local\nstack points to another local stack up to a given depth. This give a\nstack of stacks that is isomrphic to Spark's stack of stacks. *)\n\n(* We need this structural invariant at least to prove that execution\n   never modifies the chaining pointers. *) \nInductive chained_stack_structure m : nat -> Values.val -> Prop :=\n| chained_0: forall b, chained_stack_structure m 0 (Values.Vptr b Ptrofs.zero) (* Should b null? *)\n| chained_S: forall n b' b,\n    chained_stack_structure m n (Values.Vptr b' Ptrofs.zero) ->\n    Mem.loadv AST.Mint32 m (Values.Vptr b Ptrofs.zero) = Some (Values.Vptr b' Ptrofs.zero) ->\n    chained_stack_structure m (S n) (Values.Vptr b Ptrofs.zero).\n\n\nInductive repeat_Mem_loadv (chk:AST.memory_chunk) (m : mem): forall (lvl:nat) (sp sp' : Values.val), Prop :=\n| Repeat_loadv1: forall sp, repeat_Mem_loadv chk m O sp sp\n| Repeat_loadv2: forall lvl sp sp' sp'',\n    repeat_Mem_loadv chk m lvl sp' sp'' ->\n    Mem.loadv AST.Mint32 m sp = Some sp' ->\n    repeat_Mem_loadv chk m (S lvl) sp sp''.\n\n\n(* CE gives the maximum number of loads. *)\nDefinition stack_localstack_aligned lvl locenv g m sp :=\n  forall δ_lvl,\n    (δ_lvl <= lvl)%nat ->\n    exists b_δ,\n      Cminor.eval_expr g sp locenv m (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) δ_lvl) (Values.Vptr b_δ Ptrofs.zero).\n\nLtac rename_chained t th :=\n  match th with\n| chained_stack_structure ?m ?lvl ?sp => fresh \"chain_\" m \"_\" lvl \"_\" sp\n| chained_stack_structure ?m ?lvl _ => fresh \"chain_\" m \"_\" lvl\n| chained_stack_structure ?m _ _ => fresh \"chain_\" m\n| chained_stack_structure _ ?lvl _ => fresh \"chain_\" lvl\n| chained_stack_structure _ _ _ => fresh \"chain\"\n| repeat_Mem_loadv _ ?m ?lvl ?v ?sp => fresh \"repeat_loadv_\" lvl \"_\" v\n| repeat_Mem_loadv _ ?m ?lvl ?v ?sp => fresh \"repeat_loadv_\" lvl\n| repeat_Mem_loadv _ ?m ?lvl ?v ?sp => fresh \"repeat_loadv\"\n| stack_localstack_aligned _ _ ?g ?m ?sp => fresh \"aligned_\" g \"_\" m\n| stack_localstack_aligned _ _ _ ?m ?sp => fresh \"aligned_\" m\n| stack_localstack_aligned _ _ ?g _ ?sp => fresh \"aligned_\" g\nend.\n\nLtac prefixable h th ::=\n  match th with\n  | _ => prefixable_compcert h th\n  | _ => prefixable_eq_neq h th\n  end.\n\n\nLtac rename_hyp h th ::=\n  match th with\n  | _ => (compcert_utils.rename_hyp1 h th)\n  | _ => (LibHypsNaming.rename_hyp_neg h th)\n  | _ => (rename_chained h th)\n  end.\n\nLemma chained_stack_structure_le m sp : forall n,\n    chained_stack_structure m n sp ->\n    forall n', (n' <= n)%nat -> \n               chained_stack_structure m n' sp.\nProof.\n  !!intros ? ?.\n  !induction h_chain_m_n_sp;!intros.\n  - assert (n'=0)%nat by lia;subst.\n    constructor.\n  - destruct n'.\n    * constructor.\n    * econstructor;eauto.\n      apply h_forall_n';eauto;lia.\nQed.\n\nLemma chained_stack_struct_inv_sp_zero: forall m n sp,\n    chained_stack_structure m n sp -> exists b',  sp = (Values.Vptr b' Ptrofs.zero).\nProof.\n  !intros.\n  inversion h_chain_m_n_sp;subst;eauto.\nQed.\n\nLemma chained_stack_struct_sp_add: forall m n sp,\n    chained_stack_structure m n sp -> (Values.Val.add sp (Values.Vint Int.zero)) = sp.\nProof.\n  !intros.\n  destruct (chained_stack_struct_inv_sp_zero m n sp);subst;auto.\nQed.\n\nLemma cm_eval_addrstack_zero:\n  forall b ofs m g e,\n      Cminor.eval_expr g (Values.Vptr b ofs) e m (Econst (Oaddrstack Ptrofs.zero)) (Values.Vptr b ofs).\nProof.\n  !intros.\n  constructor;cbn.\n  rewrite Ptrofs.add_zero.\n  reflexivity.\nQed.\n\nLemma cm_eval_addrstack_zero_chain:\n  forall n sp m,\n    chained_stack_structure m n sp ->\n    forall g e,\n      Cminor.eval_expr g sp e m (Econst (Oaddrstack Ptrofs.zero)) sp.\nProof.\n  !intros.\n  destruct (chained_stack_struct_inv_sp_zero _ _ _ h_chain_m_n_sp).\n  subst.\n  apply cm_eval_addrstack_zero.\nQed.\n\n(* a useful formulation of the two previous lemmas. *)\nLemma det_cm_eval_addrstack_zero_chain : forall m lvl sp e g vaddr,\n    chained_stack_structure m lvl sp ->\n    Cminor.eval_expr g sp e m (Econst (Oaddrstack Ptrofs.zero)) vaddr ->\n    vaddr = sp.\nProof.\n  !intros.\n  pose proof cm_eval_addrstack_zero_chain lvl sp m h_chain_m_lvl_sp g e.\n  eapply det_eval_expr;eauto.\nQed.\n\nLemma det_cm_eval_addrstack_zero : forall b i m e g vaddr,\n    Cminor.eval_expr g (Values.Vptr b i) e m (Econst (Oaddrstack Ptrofs.zero)) vaddr ->\n    vaddr = (Values.Vptr b i).\nProof.\n  !intros.\n  pose proof cm_eval_addrstack_zero b i m g e.\n  eapply det_eval_expr;eauto.\nQed.\n\nLtac subst_det_addrstack_zero :=\n\n  match goal with\n  | H:Cminor.eval_expr ?g ?sp ?e ?m ?exp ?vaddr,\n      H':Cminor.eval_expr ?g ?sp ?e ?m ?exp ?vaddr' |- _ =>\n    assert (vaddr=vaddr') by (eapply det_eval_expr;eauto);\n    try (subst vaddr + subst vaddr');\n    clear H\n    (* to avoid useless applications *)\n  | H:Cminor.eval_expr ?g ?sp ?e ?m ?exp ?sp |- _ =>\n    fail 1\n  | H:Cminor.eval_expr ?g (Values.Vptr ?b ?i) ?e ?m (Econst (Oaddrstack Ptrofs.zero)) ?vaddr |- _ =>\n    assert (vaddr=(Values.Vptr b i)) by (eapply det_cm_eval_addrstack_zero;eauto);\n    try subst vaddr\n  | H:Cminor.eval_expr ?g ?sp ?e ?m (Econst (Oaddrstack Ptrofs.zero)) ?vaddr,\n      H':chained_stack_structure ?m ?n ?sp |- _ =>\n    assert (vaddr=sp) by (eapply det_cm_eval_addrstack_zero_chain;eauto);\n    try subst vaddr\n\n  end.\n\nLemma chained_stack_structure_aux m sp : forall n,\n    chained_stack_structure m (S n) sp ->\n    forall g e, exists b',\n      chained_stack_structure m n (Values.Vptr b' Ptrofs.zero)\n      /\\ Mem.loadv AST.Mint32 m sp = Some (Values.Vptr b' Ptrofs.zero)\n      /\\ Cminor.eval_expr g sp e m (Eload AST.Mint32 (Econst (Oaddrstack Ptrofs.zero))) (Values.Vptr b' Ptrofs.zero).\nProof.\n  !!intros until 1.\n  inversion h_chain_m;subst;!intros.\n  exists b';split;[|split];eauto.\n  econstructor;eauto.\n  constructor.\n  cbn.\n  reflexivity.\nQed.\n\nLemma build_loads__decomp_S: forall m b0 g e b, \n    Cminor.eval_expr g (Values.Vptr b0 Ptrofs.zero) e m \n                     (Eload AST.Mint32 (Econst (Oaddrstack Ptrofs.zero)))\n                     (Values.Vptr b Ptrofs.zero) ->\n    forall n v,\n      Cminor.eval_expr g (Values.Vptr b0 Ptrofs.zero) e m\n                       (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) (S n)) v ->\n      exists sp',\n        Cminor.eval_expr g (Values.Vptr b0 Ptrofs.zero) e m\n                         (Eload AST.Mint32 (Econst (Oaddrstack Ptrofs.zero))) sp'\n        /\\ Cminor.eval_expr g sp' e m (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n) v.\nProof.\n  !intros.\n  revert v b h_CM_eval_expr h_CM_eval_expr_v.\n  !induction n.\n  - !intros.\n    cbn in *.\n    exists v;split;auto.\n    constructor;cbn.\n    subst_det_addrstack_zero.\n    cbn.\n    rewrite Ptrofs.add_zero.\n    reflexivity.\n  - !intros.\n    cbn in h_CM_eval_expr_v.\n    !invclear h_CM_eval_expr_v;subst.\n    change (Eload AST.Mint32 (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n)) with (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) (S n)) in h_CM_eval_expr_vaddr.\n    specialize (h_forall_v _ _ h_CM_eval_expr h_CM_eval_expr_vaddr).\n    decomp h_forall_v.\n    exists sp';split;auto.\n    cbn.\n    econstructor;eauto.\nQed.\n\nLemma chained_stack_structure_decomp_S: forall m max sp g e, \n    forall n v, chained_stack_structure m max sp ->\n      n < max ->\n      Cminor.eval_expr g sp e m\n                       (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) (S n))\n                       v ->\n         exists sp',\n           Cminor.eval_expr g sp e m (Eload AST.Mint32 (Econst (Oaddrstack Ptrofs.zero))) sp' /\\\n           Cminor.eval_expr g sp' e m (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n) v.\nProof.\n  !!intros until n.\n  !induction n.\n  - !intros.\n    cbn in *.\n    exists v;split;auto.\n    eapply cm_eval_addrstack_zero_chain with (n:=Nat.pred max);eauto.\n    rewrite <- (PeanoNat.Nat.succ_pred_pos _ h_lt_O_max) in h_chain_m_max_sp.\n    !inversion h_chain_m_max_sp.\n    !inversion h_CM_eval_expr_v.\n    subst_det_addrstack_zero.\n    rewrite h_loadv in h_loadv_vaddr_v.\n    inversion h_loadv_vaddr_v.\n    assumption.\n  - !intros.\n    cbn in h_CM_eval_expr_v.\n    !invclear h_CM_eval_expr_v;subst.\n    change (Eload AST.Mint32 (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n)) with (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) (S n)) in h_CM_eval_expr_vaddr.\n    !!assert (n<max) by lia.\n    specialize h_forall_v with (1:=h_chain_m_max_sp)(2:=h_lt_n_max)(3:=h_CM_eval_expr_vaddr).\n    decomp h_forall_v.\n    exists sp';split;auto.\n    cbn.\n    econstructor;eauto.\nQed.\n\n\n\nLemma chained_stack_structure_spec :\n  forall  g e m n b,\n    (forall lvl,\n        (lvl <= n)%nat\n        -> exists b',\n          Cminor.eval_expr g (Values.Vptr b Ptrofs.zero) e m\n                           (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) lvl)\n                           (Values.Vptr b' Ptrofs.zero))\n    -> chained_stack_structure m n (Values.Vptr b Ptrofs.zero).\nProof.\n  !!induction n;!intros.\n  - constructor.\n  - !!assert (1 <= S n) by lia.\n    !!pose proof  (h_forall_lvl 1%nat h_le).\n    decomp h_ex.\n    !!assert (S n <= S n) by lia.\n    !!pose proof  (h_forall_lvl _ h_le0).\n    decomp h_ex.\n    cbn in *.\n    !!specialize build_loads__decomp_S with (1:=h_CM_eval_expr)(2:=h_CM_eval_expr0) as ?.\n    decomp h_ex.\n    subst_det_addrstack_zero.\n    eapply chained_S with (b':=b');eauto.\n    + eapply h_forall_b.\n      !intros.\n      !!assert (S lvl <= S n) by lia.\n      !!pose proof  (h_forall_lvl _ h_le1).\n      decomp h_ex.\n      cbn in *.\n      !!specialize build_loads__decomp_S with (1:=h_CM_eval_expr_sp') (2:=h_CM_eval_expr) as ?.\n      decomp h_ex.\n      subst_det_addrstack_zero.\n      eauto.\n    + !inversion h_CM_eval_expr_sp'.\n      subst_det_addrstack_zero.\n      assumption.\nQed.\n\n\nLemma assignment_preserve_chained_stack_structure_aux:\n  forall stkptr m chk e_t_v addr_blck addr_ofs m' n,\n    chained_stack_structure m n stkptr ->\n    (4 <= (Ptrofs.unsigned addr_ofs))%Z ->\n    Mem.storev chk m (Values.Vptr addr_blck addr_ofs) e_t_v = Some m' ->\n    chained_stack_structure m' n stkptr.\nProof.\n  !intros.\n  induction h_chain_m_n_stkptr.\n  - constructor.\n  - econstructor.\n    all:swap 1 2.\n    + unfold Mem.loadv.\n      unfold Mem.storev in heq_storev_e_t_v_m'.\n      erewrite Mem.load_store_other with (m1:=m);eauto.\n    + assumption.\nQed.\n\n\n(*\nLemma add_Vint_zero: forall m vaddr x,\n    Mem.loadv AST.Mint32 m vaddr = Some x ->\n    Values.Val.add x (Values.Vint Int.zero) = x.\nProof.\n  !intros. \n  destruct vaddr;cbn in *; try discriminate.\n  cbn.\nQed.\n *)\n\nLemma chained_stack_structure_decomp_S_2': forall n m sp,\n    chained_stack_structure m (S n) sp ->\n    forall g e v sp',\n      Cminor.eval_expr g sp e m (Eload AST.Mint32 (Econst (Oaddrstack Ptrofs.zero))) sp' ->\n      Cminor.eval_expr g sp' e m (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n) v ->\n      Cminor.eval_expr g sp e m (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) (S n)) v.\nProof.\n  intro n.\n  !induction n.\n  - !intros.\n    cbn in *.\n    !inversion h_CM_eval_expr_sp'.\n    !inversion h_CM_eval_expr_vaddr.\n    !inversion h_CM_eval_expr_v.\n    cbn in *.\n    !invclear h_eval_constant.\n    !invclear h_eval_constant0;subst.\n    assert (exists b, sp' = Values.Vptr b Ptrofs.zero).\n    { !inversion h_chain_m.\n      cbn in *.\n      rewrite Ptrofs.add_zero in h_loadv_vaddr_sp'.\n      rewrite h_loadv_vaddr_sp' in h_loadv.\n      inversion h_loadv.\n      eauto. }\n    decomp H;subst.\n    econstructor;cbn;eauto.\n  - !intros.\n    cbn in h_CM_eval_expr_v.\n    cbn.\n    inversion h_CM_eval_expr_v;subst.\n    econstructor;eauto.\n    eapply h_forall_m;eauto.\n    eapply chained_stack_structure_le;eauto.\nQed.\n\n\n\n\nLemma chain_structure_spec:\n  forall n m sp ,\n    chained_stack_structure m n sp ->\n    forall g e,\n      exists b, Cminor.eval_expr g sp e m (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n) (Values.Vptr b Ptrofs.zero).\nProof.\n  !!intros until 1.\n  !induction h_chain_m_n_sp;!intros.\n  - exists b.\n    eapply cm_eval_addrstack_zero;eauto.\n  - specialize (h_forall_g g e).\n    decomp h_forall_g.\n    exists b0.\n    eapply chained_stack_structure_decomp_S_2';eauto.\n    + econstructor;eauto.\n    + econstructor;eauto.\n      constructor.\n      reflexivity.\nQed.\n\nLemma chain_repeat_loadv_1 : forall m n sp,\n    chained_stack_structure m n sp ->\n    forall v g e, repeat_Mem_loadv AST.Mint32 m n sp v ->\n                  Cminor.eval_expr g sp e m (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n) v.\nProof.\n  !!intros until 1.\n  !induction h_chain_m_n_sp;cbn;!intros.\n  - !inversion h_repeat_loadv_O.\n    apply cm_eval_addrstack_zero.\n  - eapply chained_stack_structure_decomp_S_2'.\n    + econstructor;eauto.\n    + econstructor;eauto.\n      econstructor;eauto.\n    + eapply h_forall_v;eauto.\n      !inversion h_repeat_loadv.\n      rewrite h_loadv in h_loadv_sp'.\n      !invclear h_loadv_sp'.\n      assumption.\nQed.\n\nLemma chained_stack_structure_decomp_S_2: forall n m sp,\n    chained_stack_structure m (S n) sp ->\n    forall g e v,\n      Cminor.eval_expr g sp e m (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) (S n)) v ->\n      exists sp',\n        Cminor.eval_expr g sp e m (Eload AST.Mint32 (Econst (Oaddrstack Ptrofs.zero))) sp' /\\\n        Cminor.eval_expr g sp' e m (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n) v.\nProof.\n  intro n.\n  !induction n.\n  - !intros.\n    cbn in *.\n    exists v;split;auto.\n    constructor;cbn.\n    !!pose proof chained_stack_structure_aux _ _ _ h_chain_m g e.\n    decomp h_ex.\n    subst_det_addrstack_zero.\n    cbn.\n    rewrite Ptrofs.add_zero.  \n    reflexivity.\n  - !intros.\n    cbn in h_CM_eval_expr_v.\n    !inversion h_CM_eval_expr_v;subst.\n    change (Eload AST.Mint32 (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n)) with (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) (S n)) in h_CM_eval_expr_vaddr.\n    !assert (chained_stack_structure m (S n) sp).\n    { eapply chained_stack_structure_le;eauto. }\n    specialize h_forall_m with (1:=h_chain_m0) (2:=h_CM_eval_expr_vaddr).\n    decomp h_forall_m.\n    exists sp';split;auto.\n    cbn.\n    econstructor;eauto.\nQed.\n\n\n\n(* We can cut a chain into a smaller chain. *)\nLemma chain_structure_cut:\n  forall n'' n' m sp ,\n    chained_stack_structure m (n'+n'') sp ->\n    forall g e,\n      exists v sp' : Values.val, \n        Cminor.eval_expr g sp e m (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) (n'+n'')%nat) v\n        /\\ Cminor.eval_expr g sp e m (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n'') sp'\n        /\\ Cminor.eval_expr g sp' e m (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n') v\n        /\\ chained_stack_structure m n' sp'.\nProof.\n  !!intros * ? *.\n  !!pose proof chain_structure_spec _ _ _ h_chain_m g e.\n  decomp h_ex.\n  exists (Values.Vptr b Ptrofs.zero).\n  revert dependent h_CM_eval_expr.\n  revert dependent h_chain_m.\n  revert n' m sp g e b.\n  !induction n'';!intros;up_type.\n  - replace (n'+0)%nat with n' in * by lia.\n    exists sp;split;[eauto| split;eauto].\n    cbn.\n    eapply cm_eval_addrstack_zero_chain;eauto.\n  - specialize (h_forall_n' (S n') m sp g e b).\n    !assert (chained_stack_structure m (S n' + n'') sp).\n    { replace (n' + S n'')%nat with (S n' + n'')%nat in h_chain_m; try lia.\n      assumption. }\n    specialize (h_forall_n' h_chain_m0).\n    replace (n' + S n'')%nat with (S n' + n'')%nat in h_CM_eval_expr; try lia.\n    specialize (h_forall_n' h_CM_eval_expr).\n    decomp h_forall_n'.\n    !specialize chained_stack_structure_decomp_S_2 with (1:=h_chain_m1)(2:=h_CM_eval_expr1) as ?. \n    decomp h_ex.\n    exists sp'0;split;[|split;[|split]];eauto.\n    + replace (n' + S n'')%nat with (S n' + n'')%nat; try lia.\n      assumption.\n    + cbn.\n      econstructor.\n      * eassumption.\n      * !inversion h_CM_eval_expr_sp'0.\n        repeat subst_det_addrstack_zero.\n        assumption.\n    + !inversion h_CM_eval_expr_sp'0;subst.\n      repeat subst_det_addrstack_zero.\n      clear h_chain_m h_chain_m0.\n      !inversion h_chain_m1;subst;up_type.\n      cbn in *.\n      rewrite h_loadv in h_loadv_vaddr_sp'0.\n      inversion h_loadv_vaddr_sp'0.\n      subst.\n      assumption.\nQed.\n\n\n\n\nLemma chained_stack_structure_decomp_S_3: forall n m sp n_base,\n    chained_stack_structure m (S n + n_base) sp ->\n    let base := (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n_base) in\n    forall g e v,\n      Cminor.eval_expr g sp e m (build_loads_ base (S n)) v ->\n      exists sp',\n        Cminor.eval_expr g sp e m (Eload AST.Mint32 (Econst (Oaddrstack Ptrofs.zero))) sp' /\\\n        Cminor.eval_expr g sp' e m (build_loads_ base n) v.\nProof.\n  !intros.\n  unfold base in h_CM_eval_expr_v.\n  rewrite <- build_loads_compos in h_CM_eval_expr_v.\n  cbn [plus] in h_CM_eval_expr_v.\n  !!pose proof chained_stack_structure_decomp_S_2 _ _ _ h_chain_m g e v h_CM_eval_expr_v.\n  decomp h_ex.\n  exists sp';split;eauto.\n  unfold base.\n  rewrite <- build_loads_compos_comm.\n  rewrite Nat.add_comm.\n  assumption.\nQed.\n\nLemma chained_stack_structure_decomp_add: forall n1 n2 m sp,\n    chained_stack_structure m (n1 + n2) sp ->\n    forall g e v,\n      Cminor.eval_expr g sp e m (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) (n1 + n2)) v ->\n      exists sp',\n        Cminor.eval_expr g sp e m (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n2) sp' /\\\n        Cminor.eval_expr g sp' e m (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n1) v.\nProof.\n  !!intros until e.\n  specialize chain_structure_cut with (1:=h_chain_m)(g:=g)(e:=e) as h.\n  decomp h.\n  !intros.\n  subst_det_addrstack_zero.\n  exists sp'.\n  split;auto.\nQed.\n\nLemma chained_stack_structure_decomp_add': forall n1 n2 m sp sp' g e v,\n    chained_stack_structure m (n1 + n2) sp ->\n    Cminor.eval_expr g sp e m (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n2) sp' ->\n    Cminor.eval_expr g sp' e m (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n1) v -> \n    Cminor.eval_expr g sp e m (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) (n1 + n2)) v.\nProof.\n  !!intros until 1.\n  specialize chain_structure_cut with (1:=h_chain_m)(g:=g)(e:=e) as h.\n  decomp h.\n  !intros.\n  repeat subst_det_addrstack_zero.\n  assumption.\nQed.\n\n\n\n\nLemma chain_repeat_loadv_2: forall (m : mem) (n : nat) (sp : Values.val),\n    chained_stack_structure m n sp\n    -> forall (v : Values.val) (g : genv) (e : env),\n      eval_expr g sp e m (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n) v\n      -> repeat_Mem_loadv AST.Mint32 m n sp v.\nProof.\n  !!intros until 1.\n  !induction h_chain_m_n_sp;!intros.\n  - !inversion h_CM_eval_expr_v.\n    inversion h_eval_constant.\n    rewrite Ptrofs.add_zero_l.\n    constructor.\n  - assert (chained_stack_structure m (S n) (Values.Vptr b Ptrofs.zero)) by (econstructor;eauto).    \n    econstructor 2.\n    all:swap 1 2.\n    + eassumption.\n    + eapply h_forall_v with (g:=g)(e:=e).\n      cbn in h_CM_eval_expr_v.\n      specialize chained_stack_structure_decomp_S_2 with (1:=H)(2:=h_CM_eval_expr_v) as h.\n      decomp h.\n      !assert ((Values.Vptr b' Ptrofs.zero) = sp').\n      { clear h_CM_eval_expr_v0.\n        !inversion h_CM_eval_expr_sp';subst.\n        !inversion h_CM_eval_expr_vaddr.\n        cbn in h_eval_constant.\n        rewrite Ptrofs.add_zero_l in h_eval_constant.\n        inversion h_eval_constant.\n        subst.\n        rewrite h_loadv in h_loadv_vaddr_sp'.\n        inversion h_loadv_vaddr_sp'.\n        auto. }\n      rewrite heq_vptr_b'_zero.\n      assumption.\nQed.\n\nLemma chain_repeat_loadv: forall (m : mem) (n : nat) (sp : Values.val),\n    chained_stack_structure m n sp\n    -> forall (v : Values.val) (g : genv) (e : env),\n      repeat_Mem_loadv AST.Mint32 m n sp v\n      <-> eval_expr g sp e m (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n) v.\nProof.\n  split.\n  - apply chain_repeat_loadv_1;auto.\n  - apply chain_repeat_loadv_2;auto.\nQed.\n\nLemma chain_struct_build_loads_ofs : forall  m n sp_init,\n    chained_stack_structure m n sp_init ->\n    forall δ_var g e b ofs,\n      (δ_var mod Ptrofs.modulus)%Z = δ_var ->\n      Cminor.eval_expr g sp_init e m (build_loads n δ_var) (Values.Vptr b ofs) ->\n      ofs = Ptrofs.repr δ_var.\nProof.\n  !intros.\n  !!pose proof chained_stack_struct_inv_sp_zero _ _ _ h_chain_m_n_sp_init.\n  decomp h_ex;subst.\n  unfold build_loads in h_CM_eval_expr;cbn.\n  !invclear h_CM_eval_expr.\n  !inversion h_CM_eval_expr_v2;subst;cbn in *.\n  !invclear h_eval_binop_Oadd_v1_v2.\n  !invclear h_eval_constant.  \n  replace n with (0+n)%nat in h_CM_eval_expr_v1,h_chain_m_n_sp_init by auto with arith.\n  !!pose proof chain_structure_cut _ _ _ _ h_chain_m_n_sp_init g e.\n  decomp h_ex.\n  replace (0+n)%nat with n in h_CM_eval_expr_v1,h_chain_m_n_sp_init by auto with arith.  \n  subst_det_addrstack_zero.\n  !!pose proof chained_stack_struct_inv_sp_zero _ _ _ h_chain_m_O_sp'.\n  decomp h_ex.\n  subst.\n  cbn in h_val_add_v1_v2.\n  rewrite Ptrofs.add_zero_l in h_val_add_v1_v2.\n  destruct Archi.ptr64.\n  - inversion h_val_add_v1_v2.\n  - !inversion h_val_add_v1_v2.\n    unfold Ptrofs.of_int.\n    rewrite Int.unsigned_repr_eq.\n    apply f_equal;auto.\nQed.\n\n\nLemma malloc_preserves_chained_structure : \n  forall lvl m sp b ofs  m' new_sp,\n    Mem.alloc m b ofs = (m', new_sp) ->\n    chained_stack_structure m lvl sp ->\n    chained_stack_structure m' lvl sp.\nProof.\n  intro lvl.\n  !induction lvl;!intros.\n  - !inversion h_chain_m_O_sp.\n    constructor.\n  - !inversion h_chain_m.\n    cbn in *.\n    econstructor.\n    + eapply h_forall_m;eauto.\n    + cbn.\n      eapply Mem.load_alloc_other;eauto.\nQed.\n\n\nLemma malloc_preserves_chaining_loads : \n  forall m lvl sp sz m' new_sp,\n    Mem.alloc m 0 sz = (m', new_sp) ->\n    forall n, (n <= lvl)%nat ->\n         chained_stack_structure m lvl sp ->\n         forall e g sp',\n           Cminor.eval_expr g sp e m (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n) sp'\n           -> Cminor.eval_expr g sp e m' (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n) sp'.\nProof.\n  !!intros until n.\n  induction n;!intros.\n  - cbn in *.\n    !!pose proof chained_stack_struct_inv_sp_zero _ _ _ h_chain_m_lvl_sp.\n    decomp h_ex.\n    subst.\n    subst_det_addrstack_zero.\n    apply cm_eval_addrstack_zero.\n  - !!assert (n <= lvl)%nat by lia.\n    specialize (IHn h_le_n_lvl h_chain_m_lvl_sp).\n    cbn -[Mem.storev] in *.\n    !inversion h_CM_eval_expr_sp'.\n    specialize (IHn _ _ _ h_CM_eval_expr_vaddr).\n    econstructor.\n    + eassumption.\n    + cbn in *.\n      rewrite <- h_loadv_vaddr_sp'.\n      destruct vaddr; try discriminate.\n      cbn in *.\n      eapply Mem.load_alloc_unchanged;eauto.\n      eapply Mem.valid_access_valid_block.\n      apply Mem.load_valid_access in h_loadv_vaddr_sp'.\n      eapply Mem.valid_access_implies with (1:=h_loadv_vaddr_sp').\n      constructor.\nQed.\n\n\nLemma malloc_preserves_chaining_loads_2 : \n  forall m lvl sp sz m' new_sp,\n    Mem.alloc m 0 sz = (m', new_sp) ->\n    forall n, (n <= lvl)%nat ->\n         chained_stack_structure m lvl sp ->\n         forall e g sp',\n           Cminor.eval_expr g sp e m' (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n) sp'\n           -> Cminor.eval_expr g sp e m (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n) sp'.\nProof.\n  !!intros until n.\n  induction n;!intros.\n  - cbn in *.\n    !!pose proof chained_stack_struct_inv_sp_zero _ _ _ h_chain_m_lvl_sp.\n    decomp h_ex.\n    subst.\n    subst_det_addrstack_zero.\n    apply cm_eval_addrstack_zero.\n  - !!assert (n <= lvl)%nat by lia.\n    specialize (IHn h_le_n_lvl h_chain_m_lvl_sp).\n    cbn -[Mem.storev] in *.\n    !inversion h_CM_eval_expr_sp'.\n    specialize (IHn _ _ _ h_CM_eval_expr_vaddr).\n    econstructor.\n    + eassumption.\n    + cbn in *.\n      rewrite <- h_loadv_vaddr_sp'.\n      destruct vaddr; try discriminate.\n      cbn in *.\n      symmetry.\n      eapply Mem.load_alloc_unchanged;eauto.\n      destruct (Mem.valid_block_alloc_inv _ _ _ _ _ h_malloc_m_m' b).\n      * eapply Mem.valid_access_valid_block.\n        apply Mem.load_valid_access in h_loadv_vaddr_sp'.\n        eapply Mem.valid_access_implies with (1:=h_loadv_vaddr_sp').\n        constructor.\n      * exfalso.\n        subst.\n        !!assert ((lvl-n) + n = lvl)%nat by lia.\n        rewrite <- heq_add in h_chain_m_lvl_sp.\n        !!pose proof (chain_structure_cut _ _ _ _ h_chain_m_lvl_sp) g e.\n        decomp h_ex.\n        rewrite heq_add in h_CM_eval_expr_v.\n        subst_det_addrstack_zero.\n        destruct (lvl - n)%nat eqn:heq'.\n        -- exfalso; lia.\n        -- cbn in h_CM_eval_expr_v0.\n           eapply chained_stack_structure_decomp_S_2 in h_CM_eval_expr_v0.\n           ++ decomp h_CM_eval_expr_v0.\n              !inversion h_CM_eval_expr_sp'0.\n              subst_det_addrstack_zero.\n              absurd (Mem.valid_block m new_sp).\n              ** eapply Mem.fresh_block_alloc;eauto.\n              ** unfold Mem.loadv in h_loadv_vaddr_sp'0.\n                 eapply  Mem.load_valid_access in h_loadv_vaddr_sp'0.\n                 eapply Mem.valid_access_valid_block.\n                 eapply Mem.valid_access_implies;eauto.\n                 constructor.\n           ++ assumption.\n      * assumption.\nQed.\n\n\n\n\nLemma malloc_distinct_from_chaining_loads : \n  forall lvl m sp, \n    chained_stack_structure m lvl sp ->\n    forall n sz m' new_sp,\n      Mem.alloc m 0 sz = (m', new_sp) ->\n      forall e g, (n < lvl)%nat -> forall b' ,\n          Cminor.eval_expr g sp e m \n                           ((build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n)) (Values.Vptr b' Ptrofs.zero)\n          -> b' <> new_sp.\nProof.\n  !!intros * ?.\n  !induction h_chain_m_lvl_sp;cbn;!intros.\n  - exfalso;lia.\n  - destruct n0.\n    + cbn in *.\n      !!subst_det_addrstack_zero.\n      !invclear H.\n      intro abs;subst b.\n      !!pose proof Mem.load_valid_access _ _ _ _ _ h_loadv.\n      !!pose proof Mem.fresh_block_alloc _ _ _ _ _ h_malloc_m_m'.\n      apply h_neg_valid_blck_m_new_sp.\n      eapply Mem.valid_access_valid_block.\n      eapply Mem.valid_access_implies with (1:=h_valid_access_new_sp).\n      constructor.\n    + eapply h_forall_n with (n0:=n0);eauto.\n      * lia.\n      * !assert(chained_stack_structure m (S n) (Values.Vptr b Ptrofs.zero)).\n        { econstructor;eauto. }\n        !assert(chained_stack_structure m (S n0) (Values.Vptr b Ptrofs.zero)).\n        { eapply chained_stack_structure_le with (n:=S n).\n          - assumption.\n          - lia. }\n        !!pose proof chained_stack_structure_decomp_S_2 _ _ _ h_chain_m0 g e _ h_CM_eval_expr.\n        decomp h_ex.\n        !inversion h_CM_eval_expr_sp'.\n        subst_det_addrstack_zero.\n        subst.\n        rewrite h_loadv in h_loadv_vaddr_sp'.\n        inversion h_loadv_vaddr_sp'.\n        subst.\n        eassumption.\nQed.\n\n\n(* if we store in a block [sp0] not invovlved in the chaining from [sp], then\n   all chainging addresses reachable from sp from sp'' are unchanged. *)\nLemma chain_aligned: forall m n stkptr,\n  chained_stack_structure m n stkptr ->\n  forall lgth_CE,\n    (lgth_CE <= n)%nat ->\n    forall locenv g,\n      stack_localstack_aligned lgth_CE locenv g m stkptr.\nProof.\n  !!intros until 1.\n  unfold stack_localstack_aligned.\n  !induction h_chain_m_n_stkptr;!intros.\n  - exists b.\n    assert (δ_lvl = 0%nat) by lia;subst.\n    cbn.\n    apply cm_eval_addrstack_zero.\n  - destruct δ_lvl.\n    + cbn.\n      exists b.\n      apply cm_eval_addrstack_zero.\n    + cbn.\n      !!destruct lgth_CE;[cbn in h_le_δ_lvl_lgth_CE;exfalso;lia|].\n      subst;up_type.\n      specialize (h_forall_lgth_CE lgth_CE).\n      !!assert (lgth_CE <= n) by lia.\n      !!assert (δ_lvl <= lgth_CE)%nat by lia.\n      specialize (fun locenv g => h_forall_lgth_CE h_le_lgth_CE_n locenv g δ_lvl h_le_δ_lvl_lgth_CE0).\n      specialize (h_forall_lgth_CE locenv g).\n      decomp h_forall_lgth_CE.\n      exists b_δ.\n      assert (chained_stack_structure m (S δ_lvl) (Values.Vptr b Ptrofs.zero)).\n      { econstructor; eauto.\n        eapply chained_stack_structure_le;eauto.\n        lia. }\n      eapply chained_stack_structure_decomp_S_2';eauto.\n      econstructor;eauto.\n      eapply cm_eval_addrstack_zero_chain;eauto.\nQed.\n\nLemma storev_outside_struct_chain_preserves_chaining:\n  forall sp0 e sp g m lvl,\n      (* chainging addresses are unchanged. *)\n      (forall n, (n < lvl)%nat -> forall b' ,\n            Cminor.eval_expr g sp e m \n                             ((build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n)) (Values.Vptr b' Ptrofs.zero)\n            -> b' <> sp0) ->\n      forall n, chained_stack_structure m lvl sp ->\n           forall x _v _chk m', Mem.storev _chk m (Values.Vptr sp0 _v) x = Some m' ->\n                   (n <= lvl)%nat -> forall v,\n                       Cminor.eval_expr g sp e m ((build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n)) v\n                       -> Cminor.eval_expr g sp e m' ((build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n)) v.\nProof.\n  !!intros until lvl.\n  intros h_eval_sp_lds n.\n  !induction n;!intros.\n  - cbn in *.\n    !!pose proof chained_stack_struct_inv_sp_zero _ _ _ h_chain_m_lvl_sp.\n    decomp h_ex.\n    subst.\n    subst_det_addrstack_zero.\n    apply cm_eval_addrstack_zero.\n  - !!assert (n <= lvl)%nat by lia.\n    specialize (h_impl_forall_x h_chain_m_lvl_sp _ _ _ _ heq_storev_x_m' h_le_n_lvl).\n    cbn -[Mem.storev] in *.\n    !inversion h_CM_eval_expr_v.\n    specialize (h_impl_forall_x _ h_CM_eval_expr_vaddr).\n    econstructor.\n    + eassumption.\n    + cbn in *.\n      destruct vaddr; try discriminate.\n      cbn in *.\n      pose proof Mem.load_store_other _ _ _ _ _ _ heq_storev_x_m' AST.Mint32 b (Ptrofs.unsigned i) as h.\n      rewrite h.\n      * assumption.\n      * left.\n        eapply h_eval_sp_lds with (n:=n).\n        -- lia.\n        -- assert (i = Ptrofs.zero). \n           { !!pose proof chain_aligned _ _ _ h_chain_m_lvl_sp lvl (le_n _) e g.\n             red in h_aligned_g_m.\n             !!assert (n <= lvl) by lia.\n             specialize (h_aligned_g_m _ h_le_n_lvl0).\n             decomp h_aligned_g_m.\n             !! (subst_det_addrstack_zero;idtac).\n             inversion heq_vptr_b_i.\n             reflexivity. }\n           subst.\n           eassumption.\nQed.\n\n(* more general result: we can change something in the chained\nstructure but not the structure itself (chainging pointers. *)\nLemma gen_storev_outside_struct_chain_preserves_chaining:\n  forall sp0 e sp g m lvl ofs0,\n    (* chainging addresses are unchanged. *)\n    ((4 <= (Ptrofs.unsigned ofs0))%Z \\/\n    (forall n, (n < lvl)%nat -> forall b' ,\n          Cminor.eval_expr\n            g sp e m (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n)\n            (Values.Vptr b' Ptrofs.zero)\n          -> b' <> sp0)) ->\n    forall n, chained_stack_structure m lvl sp ->\n              forall x _chk m', Mem.storev _chk m (Values.Vptr sp0 ofs0) x = Some m' ->\n                                (n <= lvl)%nat -> forall v,\n                                    Cminor.eval_expr g sp e m ((build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n)) v\n                                    -> Cminor.eval_expr g sp e m' ((build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n)) v.\nProof.\n  !!intros until ofs0.\n  intros h_eval_sp_lds n.\n  !induction n;!intros.\n  - cbn in *.\n    !!pose proof chained_stack_struct_inv_sp_zero _ _ _ h_chain_m_lvl_sp.\n    decomp h_ex.\n    subst.\n    subst_det_addrstack_zero.\n    apply cm_eval_addrstack_zero.\n  - !!assert (n <= lvl)%nat by lia.\n    specialize h_impl_forall_x with (1:=h_chain_m_lvl_sp)(2:=heq_storev_x_m') (3:=h_le_n_lvl).\n    cbn -[Mem.storev] in *.\n    !inversion h_CM_eval_expr_v.\n    specialize (h_impl_forall_x _ h_CM_eval_expr_vaddr).\n    econstructor.\n    + eassumption.\n    + cbn in *.\n      destruct vaddr; try discriminate.\n      cbn in *.\n      pose proof Mem.load_store_other _ _ _ _ _ _ heq_storev_x_m' AST.Mint32 b (Ptrofs.unsigned i) as h.\n      rewrite h.\n      * assumption.\n      * !destruct h_eval_sp_lds.\n        -- right.\n           assert (i = Ptrofs.zero).\n           { !!specialize chained_stack_structure_le with (1:=h_chain_m_lvl_sp) (2:=h_le_n_lvl) as ?.\n             !!specialize chain_structure_spec with (1:=h_chain_m_n_sp) (g:=g)(e:=e) as ?.\n             decomp h_ex.\n             !!specialize det_eval_expr with (1:=h_CM_eval_expr) (2:=h_CM_eval_expr_vaddr) as ?.\n             !inversion heq_vptr_b0_zero.\n             reflexivity. }\n           subst.\n           left.\n           cbn.\n           rewrite Ptrofs.unsigned_zero.\n           lia.\n        -- left.\n           eapply h_forall_n with (n:=n).\n           ++ lia.\n           ++ assert (i = Ptrofs.zero). \n              { !!pose proof chain_aligned _ _ _ h_chain_m_lvl_sp lvl (le_n _) e g.\n                red in h_aligned_g_m.\n                !!assert (n <= lvl) by lia.\n                specialize (h_aligned_g_m _ h_le_n_lvl0).\n                decomp h_aligned_g_m.\n                !! (subst_det_addrstack_zero;idtac).\n                inversion heq_vptr_b_i.\n                reflexivity. }\n              subst.\n              eassumption.\nQed.\n\n\nLemma storev_outside_struct_chain_preserves_chaining2:\n  forall sp0 e sp g m lvl,\n      (* chainging addresses are unchanged. *)\n      (forall n, (n < lvl)%nat -> forall b' ,\n            Cminor.eval_expr g sp e m \n                             ((build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n)) (Values.Vptr b' Ptrofs.zero)\n            -> b' <> sp0) ->\n      forall n, chained_stack_structure m lvl sp ->\n           forall x _v _chk m', Mem.storev _chk m (Values.Vptr sp0 _v) x = Some m' ->\n                   (n <= lvl)%nat -> forall v,\n                       Cminor.eval_expr g sp e m' ((build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n)) v\n                       -> Cminor.eval_expr g sp e m ((build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n)) v.\nProof.\n  !!intros until lvl.\n  intros h_eval_sp_lds n.\n  !induction n;!intros.\n  - cbn in *.\n    !!pose proof chained_stack_struct_inv_sp_zero _ _ _ h_chain_m_lvl_sp.\n    decomp h_ex.\n    subst.\n    subst_det_addrstack_zero.\n    apply cm_eval_addrstack_zero.\n  - !!assert (n <= lvl)%nat by lia.\n    specialize (h_impl_forall_x h_chain_m_lvl_sp _ _ _ _ heq_storev_x_m' h_le_n_lvl).\n    cbn -[Mem.storev] in *.\n    !inversion h_CM_eval_expr_v.\n    specialize (h_impl_forall_x _ h_CM_eval_expr_vaddr).\n    econstructor.\n    + eassumption.\n    + cbn in *.\n      destruct vaddr; try discriminate.\n      cbn in *.\n      pose proof Mem.load_store_other _ _ _ _ _ _ heq_storev_x_m' AST.Mint32 b (Ptrofs.unsigned i) as h.\n      rewrite <- h.\n      * assumption.\n      * left.\n        eapply h_eval_sp_lds with (n:=n).\n        -- lia.\n        -- assert (i = Ptrofs.zero). \n           { !!pose proof chain_aligned _ _ _ h_chain_m_lvl_sp lvl (le_n _) e g.\n             red in h_aligned_g_m.\n             !!assert (n <= lvl) by lia.\n             specialize (h_aligned_g_m _ h_le_n_lvl0).\n             decomp h_aligned_g_m.\n             !! (subst_det_addrstack_zero;idtac).\n             inversion heq_vptr_b_δ_zero.\n             reflexivity. }\n           subst.\n           eassumption.\nQed.\n\n(* More general result *)\nLemma gen_storev_outside_struct_chain_preserves_chaining2:\n  forall sp0 e sp g m lvl ofs0,\n    (* chainging addresses are unchanged. *)\n    ((4 <= (Ptrofs.unsigned ofs0))%Z \\/\n     forall n, (n < lvl)%nat -> forall b' ,\n         Cminor.eval_expr g sp e m \n                          ((build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n)) (Values.Vptr b' Ptrofs.zero)\n         -> b' <> sp0) ->\n    forall n, chained_stack_structure m lvl sp ->\n              forall x _chk m', Mem.storev _chk m (Values.Vptr sp0 ofs0) x = Some m' ->\n                                   (n <= lvl)%nat -> forall v,\n                                       Cminor.eval_expr g sp e m' ((build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n)) v\n                                       -> Cminor.eval_expr g sp e m ((build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n)) v.\nProof.\n  !!intros until ofs0.\n  intros h_eval_sp_lds n.\n  !induction n;!intros.\n  - cbn in *.\n    !!specialize chained_stack_struct_inv_sp_zero with (1:=h_chain_m_lvl_sp) as ?.\n    decomp h_ex.\n    subst.\n    subst_det_addrstack_zero.\n    apply cm_eval_addrstack_zero.\n  - !!assert (n <= lvl)%nat by lia.\n    specialize h_impl_forall_x with (1:=h_chain_m_lvl_sp) (2:=heq_storev_x_m') (3:=h_le_n_lvl).\n    cbn -[Mem.storev] in *.\n    !inversion h_CM_eval_expr_v.\n    specialize (h_impl_forall_x _ h_CM_eval_expr_vaddr).\n    econstructor.\n    + eassumption.\n    + cbn in *.\n      destruct vaddr; try discriminate.\n      cbn in *.\n      pose proof Mem.load_store_other _ _ _ _ _ _ heq_storev_x_m' AST.Mint32 b (Ptrofs.unsigned i) as h.\n      rewrite <- h.\n      * assumption.\n      * !destruct h_eval_sp_lds.\n        -- right.\n           assert (i = Ptrofs.zero).\n           { !!specialize chained_stack_structure_le with (1:=h_chain_m_lvl_sp) (2:=h_le_n_lvl) as ?.\n             !!specialize chain_structure_spec with (1:=h_chain_m_n_sp) (g:=g)(e:=e) as ?.\n             decomp h_ex.\n             !!specialize det_eval_expr with (1:=h_CM_eval_expr) (2:=h_impl_forall_x) as ?.\n             !inversion heq_vptr_b0_zero.\n             reflexivity. }\n           subst.\n           left.\n           cbn.\n           rewrite Ptrofs.unsigned_zero.\n           lia.\n        -- left.\n           eapply h_forall_n with (n:=n).\n           ++ lia.\n           ++ assert (i = Ptrofs.zero). \n              { !!pose proof chain_aligned _ _ _ h_chain_m_lvl_sp lvl (le_n _) e g.\n                red in h_aligned_g_m.\n                !!assert (n <= lvl) by lia.\n                specialize (h_aligned_g_m _ h_le_n_lvl0).\n                decomp h_aligned_g_m.\n                !! (subst_det_addrstack_zero;idtac).\n                inversion heq_vptr_b_δ_zero.\n                reflexivity. }\n              subst.\n              eassumption.\nQed.\n\nLemma storev_outside_struct_chain_preserves_var_addresses:\n  forall sp0 e sp g m lvl,\n      (* chainging addresses are unchanged. *)\n      (forall n, (n < lvl)%nat -> forall b' ,\n            Cminor.eval_expr g sp e m \n                             ((build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n)) (Values.Vptr b' Ptrofs.zero)\n            -> b' <> sp0) ->\n      forall n, chained_stack_structure m lvl sp ->\n           forall x _v _chk m' δ, Mem.storev _chk m (Values.Vptr sp0 _v) x = Some m' ->\n                   (n <= lvl)%nat -> forall v,\n                       Cminor.eval_expr g sp e m ((build_loads n δ)) v\n                       -> Cminor.eval_expr g sp e m' ((build_loads n δ)) v.\nProof.\n  !!intros until lvl.\n  intros h_eval_sp_lds n.\n  !intros.\n  unfold build_loads in *.\n  !invclear h_CM_eval_expr_v.\n  econstructor;[ | |eassumption].\n  - eapply storev_outside_struct_chain_preserves_chaining;eauto.\n  - !inversion h_CM_eval_expr_v2.\n    constructor.\n    assumption.\nQed.\n\nLemma storev_outside_struct_chain_preserves_var_addresses2:\n  forall sp0 e sp g m lvl,\n      (* chainging addresses are unchanged. *)\n      (forall n, (n < lvl)%nat -> forall b' ,\n            Cminor.eval_expr g sp e m \n                             ((build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n)) (Values.Vptr b' Ptrofs.zero)\n            -> b' <> sp0) ->\n      forall n, chained_stack_structure m lvl sp ->\n           forall x _v _chk m' δ, Mem.storev _chk m (Values.Vptr sp0 _v) x = Some m' ->\n                   (n <= lvl)%nat -> forall v,\n                       Cminor.eval_expr g sp e m' ((build_loads n δ)) v\n                       -> Cminor.eval_expr g sp e m ((build_loads n δ)) v.\nProof.\n  !!intros until lvl.\n  intros h_eval_sp_lds n.\n  !intros.\n  unfold build_loads in *.\n  !invclear h_CM_eval_expr_v.\n  econstructor;[ | |eassumption].\n  - eapply storev_outside_struct_chain_preserves_chaining2;eauto.\n  - !inversion h_CM_eval_expr_v2.\n    constructor.\n    assumption.\nQed.\n\n(* The content of variable do not change either (we go one lvl less deep, since we add one ELoad.  *)\nLemma storev_outside_struct_chain_preserves_var_value:\n  forall sp0 e sp g m lvl,\n      (* chainging addresses are unchanged. *)\n      (forall n, (n <= lvl)%nat -> forall b' ,\n            Cminor.eval_expr g sp e m \n                             ((build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n)) (Values.Vptr b' Ptrofs.zero)\n            -> b' <> sp0) ->\n      forall n, chained_stack_structure m lvl sp ->\n           forall x _v _chk _chk' m' δ, Mem.storev _chk m (Values.Vptr sp0 _v) x = Some m' ->\n                   (n <= lvl)%nat -> forall v,\n                       Cminor.eval_expr g sp e m (Eload _chk' (build_loads n δ)) v\n                       -> Cminor.eval_expr g sp e m' (Eload _chk' (build_loads n δ)) v.\nProof.\n  !!intros.\n  rename h_forall_n into h_unch.\n  !inversion h_CM_eval_expr_v.\n  assert (h_unch':forall n : nat,\n             (n < lvl)%nat\n             -> forall b' : Values.block,\n               Cminor.eval_expr g sp e m (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n) (Values.Vptr b' Ptrofs.zero) -> b' <> sp0).\n  { intros.\n    eapply h_unch with (n:=n0).\n    - lia.\n    - assumption. }\n  !!pose proof storev_outside_struct_chain_preserves_var_addresses _ _ _ _ _ _ h_unch' _ h_chain_m_lvl_sp _ _ _ _ _ heq_storev_x_m' h_le_n_lvl _ h_CM_eval_expr_vaddr.\n  econstructor;eauto.\n  unfold build_loads in h_CM_eval_expr_vaddr, h_CM_eval_expr_vaddr0.\n  !invclear h_CM_eval_expr_vaddr.\n  !invclear h_CM_eval_expr_vaddr0.\n  destruct vaddr;try discriminate.\n  pose proof Mem.load_store_other _ _ _ _ _ _ heq_storev_x_m' _chk' b (Ptrofs.unsigned i) as h.\n  unfold Mem.loadv in *.\n  rewrite h.\n  - assumption.\n  - left.\n    !assert (v1=(Values.Vptr b Ptrofs.zero)).\n    { clear h. \n      !!pose proof chain_aligned _ _ _ h_chain_m_lvl_sp lvl (le_n _) e g.\n      red in h_aligned_g_m.\n      !!assert (n <= lvl) by lia.\n      specialize (h_aligned_g_m _ h_le_n_lvl0).\n      decomp h_aligned_g_m.\n      subst_det_addrstack_zero.\n      f_equal.\n      cbn in *.\n      destruct v2;try discriminate.\n      inversion h_eval_binop_Oadd_v1_v2.\n      destruct Archi.ptr64;auto. }\n    subst.\n    eapply h_unch;eauto.\nQed.\n\n\nProposition storev_outside_struct_chain_preserves_chained_structure:\n  forall (sp0 : Values.block) (e : env) (sp : Values.val) (g : genv) (m : mem) (lvl : nat),\n    (forall n : nat,\n        (n < lvl)%nat\n        -> forall b' : Values.block,\n          Cminor.eval_expr g sp e m (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n) (Values.Vptr b' Ptrofs.zero) -> b' <> sp0)\n    -> chained_stack_structure m lvl sp\n    -> forall (x : Values.val) (_v : ptrofs) (_chk : AST.memory_chunk) (m' : mem),\n        Mem.storev _chk m (Values.Vptr sp0 _v) x = Some m' ->\n        chained_stack_structure m' lvl sp.\nProof.\n  !intros.\n  assert\n    ( forall n, (n <= lvl)%nat -> forall v : Values.val,\n          Cminor.eval_expr g sp e m (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n) v\n          -> Cminor.eval_expr g sp e m' (build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n) v).\n  { !intro.\n    eapply storev_outside_struct_chain_preserves_chaining;eauto. }\n  destruct (chained_stack_struct_inv_sp_zero _ _ _ h_chain_m_lvl_sp).\n  subst.\n  eapply chained_stack_structure_spec.\n  !intros.\n  !!pose proof chain_structure_spec lvl0 m (Values.Vptr x0 Ptrofs.zero).\n  !!edestruct h_impl_forall_g with (g:=g) (e:=e).\n  eapply chained_stack_structure_le;eauto;try lia.\n  eauto.\nQed.\n\n\nLemma malloc_distinct_from_chaining_loads_2 : \n  forall lvl m sp, \n    chained_stack_structure m lvl sp ->\n    forall n sz m' new_sp,\n      Mem.alloc m 0 sz = (m', new_sp) ->\n      forall e g, (n < lvl)%nat -> forall b' ,\n          Cminor.eval_expr g sp e m'\n                           ((build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n)) (Values.Vptr b' Ptrofs.zero)\n          -> b' <> new_sp.\nProof.\n  !intros.\n  assert (Cminor.eval_expr g sp e m\n                           ((build_loads_ (Econst (Oaddrstack Ptrofs.zero)) n)) (Values.Vptr b' Ptrofs.zero)).\n  { eapply malloc_preserves_chaining_loads_2;eauto.\n    eapply chained_stack_structure_le;eauto;try lia. }\n  eapply malloc_distinct_from_chaining_loads; eauto.\nQed.\n\n", "meta": {"author": "Matafou", "repo": "sparkCompCert", "sha": "bdcaf805617022189eb3d40d37323f339f1b02a9", "save_path": "github-repos/coq/Matafou-sparkCompCert", "path": "github-repos/coq/Matafou-sparkCompCert/sparkCompCert-bdcaf805617022189eb3d40d37323f339f1b02a9/chained_structure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2520499379587779}}
{"text": "From Perennial.goose_lang Require Import notation typing.\nFrom Perennial.goose_lang Require Import proofmode lifting lib.into_val.\nFrom Perennial.goose_lang.lib Require Export proph.impl.\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\n(** list-based prophecy variables (the most general underlying primitive) *)\n\nTheorem wp_NewProph_list :\n  {{{ True }}}\n    NewProph #()\n  {{{ (p : proph_id) pvs, RET #p; proph p pvs }}}.\nProof.\n  iIntros (Φ) \"_ HΦ\". wp_lam.\n  wp_apply wp_new_proph. iIntros (pvs v). by iApply \"HΦ\".\nQed.\n\nTheorem wp_ResolveProph_list E (p : proph_id) pvs v :\n  {{{ proph p pvs }}}\n    ResolveProph (#p) (Val v) @ E\n  {{{ pvs', RET (LitV LitUnit); ⌜pvs = v::pvs'⌝ ∗ proph p pvs' }}}.\nProof.\n  iIntros (Φ) \"Hp HΦ\". wp_lam.\n  wp_apply (wp_resolve_proph with \"Hp\"). auto.\nQed.\n\n(** typed assign-once prophecy variables *)\nSection once.\n  Context `{!IntoVal T}.\n\n  Definition proph_once (p : proph_id) (x : T) : iProp Σ :=\n    ∃ pvs : list val, proph p pvs ∗\n               ⌜match v ← head pvs; from_val v with\n                | Some x' => x=x'\n                | None => True\n                end⌝.\n\n  Theorem wp_NewProph_once :\n    {{{ True }}}\n      NewProph #()\n    {{{ (p : proph_id) (x : T), RET #p; proph_once p x }}}.\n  Proof.\n    iIntros (Φ) \"_ HΦ\". iApply wp_NewProph_list; first done.\n    iIntros \"!> %p %pvs Hp\".\n    iApply (\"HΦ\" $! p (default (IntoVal_def T) (v ← head pvs; from_val v))).\n    iExists pvs. iFrame. iPureIntro.\n    destruct (head pvs); simpl; last done.\n    destruct (from_val v); done.\n  Qed.\n\n  Theorem wp_ResolveProph_once (p : proph_id) (x y : T) v :\n    from_val v = Some y →\n    {{{ proph_once p x }}}\n      ResolveProph (#p) (Val v)\n    {{{ RET (LitV LitUnit); ⌜x = y⌝ }}}.\n  Proof.\n    iIntros (Hv Φ) \"(%pvs & Hp & %Hpvs) HΦ\".\n    iApply (wp_ResolveProph_list with \"Hp\").\n    iIntros \"!> %pvs' [%Hpvs' _]\". iApply \"HΦ\". iPureIntro.\n    subst pvs. simpl in Hpvs.\n    rewrite Hv in Hpvs. done.\n  Qed.\n\nEnd once.\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/proph/proph.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331606115021, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.25199577471523477}}
{"text": "Require Import List.\nRequire Import SepTheoryX PropX.\nRequire Import PropXTac.\nRequire Import RelationClasses EqdepClass.\nRequire Import Expr ExprUnify.\nRequire Import SepExpr SepHeap.\nRequire Import Setoid.\nRequire Import Prover.\nRequire Import SepExpr.\nRequire Import Folds.\nRequire Import Reflection.\nRequire SepUnify.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nModule Make (U : SynUnifier) (SH : SepHeap).\n  Module Import SE := SH.SE.\n  Module HEAP_FACTS := SepHeapFacts SH.\n  Module Import SEP_FACTS := HEAP_FACTS.SEP_FACTS.\n  Import HEAP_FACTS.\n  Module Import SEP_UFACTS := SepUnify.Make U SH.\n\n  Section env.\n    Variable types : list type.\n    Variable pcType : tvar.\n    Variable stateType : tvar.\n\n    Variable funcs : functions types.\n    Variable preds : SE.predicates types pcType stateType.\n\n    (** The actual tactic code **)\n    Variable Prover : ProverT types.\n    Variable Prover_correct : ProverT_correct Prover funcs.\n\n\n    Definition unifyArgs (bound : nat) (summ : Facts Prover) (l r : list (expr types)) (ts : list tvar) (sub : U.Subst types)\n      : option (U.Subst types) :=\n      Folds.fold_left_3_opt \n        (fun l r t (acc : U.Subst _) =>\n          if Prove Prover summ (Expr.Equal t (U.exprInstantiate acc l) (U.exprInstantiate acc r))\n            then Some acc\n            else U.exprUnify bound l r acc)\n        l r ts sub.\n\n    Fixpoint unify_remove (bound : nat) (summ : Facts Prover) (l : exprs types) (ts : list tvar) (r : list (exprs types))\n      (sub : U.Subst types)\n      : option (list (list (expr types)) * U.Subst types) :=\n        match r with \n          | nil => None\n          | a :: b => \n            match unifyArgs bound summ l a ts sub with\n              | None => \n                match unify_remove bound summ l ts b sub with\n                  | None => None\n                  | Some (x,sub) => Some (a :: x, sub)\n                end\n              | Some sub => Some (b, sub)\n            end\n        end.\n    \n    Section with_typing.\n      Variable tfuncs : tfunctions.\n      Variables tU tG : tenv.\n      Variables U G : env types.\n\n      Hypothesis WT_funcs : WellTyped_funcs tfuncs funcs.\n      Hypothesis WT_env_U : WellTyped_env tU U.\n      Hypothesis WT_env_G : WellTyped_env tG G.\n\n      Lemma unifyArgs_Extends_WellTyped : forall bound summ l r ts S S',\n        U.Subst_WellTyped tfuncs tU tG S ->\n        all2 (@is_well_typed _ tfuncs tU tG) l ts = true ->\n        all2 (@is_well_typed _ tfuncs tU tG) r ts = true ->\n        unifyArgs bound summ l r ts S = Some S' ->\n        U.Subst_Extends S' S /\\\n        U.Subst_WellTyped tfuncs tU tG S'.\n      Proof.\n        unfold unifyArgs; induction l; destruct r; destruct ts; simpl; intros; try congruence.\n        { inversion H2. subst; intuition; auto. }\n        { repeat match goal with\n          | [ H : (if ?X then _ else _) = true |- _ ] =>\n            revert H; case_eq X; intros; [ | congruence ]\n                   | [ |- context [ exprD ?A ?B ?C ?D ?E ] ] =>\n                     case_eq (exprD A B C D E); intros\n                 end; simpl in *;\n        try solve [ \n          match goal with\n            | [ H : is_well_typed _ _ _ ?e _ = true , H' : exprD _ _ _ (U.exprInstantiate ?S' ?e) _ = None |- _ ] =>\n              exfalso; revert H; revert H'; clear; intros H' H;\n                eapply WellTyped_exprInstantiate with (S := S') in H;\n                  eapply is_well_typed_correct in H;\n                    rewrite H' in H ; destruct H; congruence\n          end ].\n          consider (Prove Prover summ (Equal t (U.exprInstantiate S a) (U.exprInstantiate S e))); simpl; eauto.\n          consider (U.exprUnify bound a e S); intros; try congruence.\n          eapply IHl in H6; eauto using U.exprUnify_WellTyped.\n          intuition. etransitivity; eauto using U.exprUnify_Extends. }\n      Qed.          \n\n      Lemma unifyArgs_bad_cases : forall summ bound S S' ts t e a l r,\n        U.Subst_WellTyped tfuncs tU tG S ->\n(*        Valid Prover_correct U G summ -> *)\n        all2 (@is_well_typed _ tfuncs tU tG) l ts = true ->\n        all2 (@is_well_typed _ tfuncs tU tG) r ts = true ->\n        @is_well_typed _ tfuncs tU tG a t = true ->\n        @is_well_typed _ tfuncs tU tG e t = true ->\n        match\n          (if Prove Prover summ\n            (Equal t (U.exprInstantiate S a) (U.exprInstantiate S e))\n            then Some S\n            else U.exprUnify bound a e S)\n          with\n          | Some acc =>\n            fold_left_3_opt\n            (fun (l r : expr types) (t : tvar) (acc0 : U.Subst types) =>\n              if Prove Prover summ\n                (Equal t (U.exprInstantiate acc0 l)\n                  (U.exprInstantiate acc0 r))\n                then Some acc0\n                else U.exprUnify bound l r acc0) l r ts acc\n          | None => None\n        end = Some S' ->\n        U.Subst_Extends S' S /\\ U.Subst_WellTyped tfuncs tU tG S'.\n      Proof.\n        intros. destruct (Prove Prover summ (Equal t (U.exprInstantiate S a) (U.exprInstantiate S e))).\n        apply unifyArgs_Extends_WellTyped in H4; eauto; intuition.\n        revert H4. case_eq (U.exprUnify bound a e S); intros; eauto.\n        generalize H4. eapply U.exprUnify_Extends in H4.\n        intro. eapply U.exprUnify_WellTyped in H6; eauto.\n        eapply unifyArgs_Extends_WellTyped in H5; eauto; intuition.\n        etransitivity; eauto. \n        congruence.\n      Qed.\n\n      Lemma unifyArgsOk : forall bound summ R l r ts f S S',\n        U.Subst_WellTyped tfuncs tU tG S ->\n        Valid Prover_correct U G summ ->\n        all2 (@is_well_typed _ tfuncs tU tG) l ts = true ->\n        all2 (@is_well_typed _ tfuncs tU tG) r ts = true ->\n        unifyArgs bound summ l r ts S = Some S' ->\n        U.Subst_equations funcs U G S' ->\n        @applyD types (exprD funcs U G) ts (map (U.exprInstantiate S') l) R f =\n        @applyD types (exprD funcs U G) ts (map (U.exprInstantiate S') r) R f /\\\n        U.Subst_Extends S' S /\\\n        U.Subst_WellTyped tfuncs tU tG S'.\n      Proof.\n        unfold unifyArgs; induction l; destruct r; destruct ts; simpl; intros; try congruence.\n        { inversion H2. inversion H3; subst; intuition; auto. }\n        { repeat match goal with\n          | [ H : (if ?X then _ else _) = true |- _ ] =>\n            revert H; case_eq X; intros; [ | congruence ]\n                   | [ |- context [ exprD ?A ?B ?C ?D ?E ] ] =>\n                     case_eq (exprD A B C D E); intros\n                 end; simpl in *;\n        try solve [ \n          match goal with\n            | [ H : is_well_typed _ _ _ ?e _ = true , H' : exprD _ _ _ (U.exprInstantiate ?S' ?e) _ = None |- _ ] =>\n              exfalso; revert H; revert H'; clear; intros H' H;\n                eapply WellTyped_exprInstantiate with (S := S') in H;\n                  eapply is_well_typed_correct in H;\n                    rewrite H' in H ; destruct H; congruence\n          end ].\n          revert H3. case_eq (Prove Prover summ (Equal t (U.exprInstantiate S a) (U.exprInstantiate S e))); intros.\n          { eapply Prove_correct in H3; eauto.\n            erewrite U.exprInstantiate_WellTyped in H2 by eauto.\n            erewrite U.exprInstantiate_WellTyped in H1 by eauto.\n            eapply is_well_typed_correct in H2; eauto.\n            eapply is_well_typed_correct in H1; eauto.\n            destruct H2; destruct H1.\n            unfold ValidProp, Provable in *. simpl in *.\n            repeat match goal with \n                     | [ H : _ = _ |- _ ] => rewrite H in *\n                     | [ H : ?X -> ?Y |- _ ] => \n                       let H' := fresh in assert (H':X) by eauto; specialize (H H')\n                   end.\n            subst.\n            eapply IHl with (f := f t0) in H9; eauto.\n            intuition. rewrite H3. f_equal. f_equal.\n            erewrite <- U.Subst_equations_exprInstantiate in H2 by eauto.\n            erewrite <- U.Subst_equations_exprInstantiate in H1 by eauto.\n            rewrite U.exprInstantiate_Extends in H2 by eauto.\n            rewrite U.exprInstantiate_Extends in H1 by eauto.\n            rewrite H2 in H8. rewrite H1 in H7. inversion H7; inversion H8; subst; auto. }\n          { clear H3. revert H9. case_eq (U.exprUnify bound a e S); intros; try congruence.\n            eapply IHl with (f := f t0) in H9; eauto using U.exprUnify_WellTyped.\n            intuition. rewrite H10. f_equal. f_equal.\n            eapply U.exprUnify_sound in H3. \n            assert (U.exprInstantiate S' (U.exprInstantiate s a) = U.exprInstantiate S' (U.exprInstantiate s e)).\n            rewrite H3; auto.\n            repeat rewrite U.exprInstantiate_Extends in H11 by eauto. rewrite H11 in H7. rewrite H7 in H8. inversion H8; auto.\n\n            etransitivity; eauto using U.exprUnify_Extends. }\n          { exfalso.\n            eapply unifyArgs_bad_cases in H3; eauto; intuition.\n            do 2 match goal with\n              | [ H : is_well_typed _ _ _ ?E _ = true ,\n                  H' : exprD _ _ _ ?E _ = None |- _ ] =>\n              (eapply is_well_typed_correct in H ; eauto) ; destruct H; congruence\n              | [ H : exprD _ _ _ ?E _ = None |- _ ] =>\n                assert (@is_well_typed _ tfuncs tU tG E t = true) by \n                  (rewrite <- U.exprInstantiate_WellTyped; eauto)\n            end. }\n          { exfalso.\n            eapply unifyArgs_bad_cases in H3; eauto; intuition.\n            do 2 match goal with\n              | [ H : is_well_typed _ _ _ ?E _ = true ,\n                  H' : exprD _ _ _ ?E _ = None |- _ ] =>\n              (eapply is_well_typed_correct in H ; eauto) ; destruct H; congruence\n              | [ H : exprD _ _ _ ?E _ = None |- _ ] =>\n                assert (@is_well_typed _ tfuncs tU tG E t = true) by \n                  (rewrite <- U.exprInstantiate_WellTyped; eauto)\n            end. }\n          { exfalso.\n            eapply unifyArgs_bad_cases in H3; eauto; intuition.\n            do 2 match goal with\n              | [ H : is_well_typed _ _ _ ?E _ = true ,\n                  H' : exprD _ _ _ ?E _ = None |- _ ] =>\n              (eapply is_well_typed_correct in H ; eauto) ; destruct H; congruence\n              | [ H : exprD _ _ _ ?E _ = None |- _ ] =>\n                assert (@is_well_typed _ tfuncs tU tG E t = true) by \n                  (rewrite <- U.exprInstantiate_WellTyped; eauto)\n            end. } }\n      Qed.\n      \n      Lemma unify_removeOk : forall cs bound summ f p l S,\n        U.Subst_WellTyped tfuncs tU tG S ->\n        Valid Prover_correct U G summ ->\n        nth_error preds f = Some p ->\n        all2 (@is_well_typed _ tfuncs tU tG) l (SDomain p) = true ->\n        forall r r' S' P,\n          List.Forall (fun r => all2 (@is_well_typed _ tfuncs tU tG) r (SDomain p) = true) r ->\n          unify_remove bound summ l (SDomain p) r S = Some (r', S') ->\n          U.Subst_equations funcs U G S' ->\n          forall Q,\n          SE.himp funcs preds U G cs (SH.starred (SE.Func f) r' Q) P ->\n          SE.himp funcs preds U G cs\n            (SH.starred (SE.Func f) r Q) (SE.Star (SE.Func f l) P) /\\\n          U.Subst_Extends S' S.\n      Proof.\n        induction r; simpl; intros; try congruence.\n        revert H4. case_eq (unifyArgs bound summ l a (SDomain p) S); intros; try congruence.\n        { inversion H7; clear H7; subst.\n          inversion H3; clear H3; subst.\n          rewrite SH.starred_def. simpl. rewrite <- SH.starred_def.\n          eapply unifyArgsOk with (R := ST.hprop (tvarD types pcType) (tvarD types stateType) nil) (f := SDenotation p) in H4;\n            eauto. \n          intuition.\n          apply himp_star_frame; auto. unfold himp; simpl. rewrite H1.\n          match goal with\n            | [ |- ST.himp _ match ?X with _ => _ end match ?Y with _ => _ end ] =>\n              cutrewrite (X = Y)\n          end. reflexivity.\n          revert H3. repeat rewrite applyD_forget_exprInstantiate by eauto; eauto. }\n        { revert H7. case_eq (unify_remove bound summ l (SDomain p) r S); intros; try congruence.\n          destruct p0. inversion H8; clear H8; subst. clear H4.\n          inversion H3; clear H3; subst.\n          rewrite SH.starred_def in H6. simpl in H6. rewrite <- SH.starred_def in H6.\n          eapply IHr in H7; eauto.\n          Focus 2. instantiate (2 := (SH.SE.Star (Func f a) Q)). instantiate (1 := P).\n          etransitivity; [ | eapply H6 ].\n          rewrite SH.starred_base. rewrite heq_star_assoc. \n          rewrite SH.starred_base with (base := Q). reflexivity.\n          intuition. rewrite starred_cons. rewrite <- H3. \n          rewrite SH.starred_base. rewrite SH.starred_base with (base := SH.SE.Star (Func f a) Q). \n          rewrite heq_star_assoc. reflexivity. }\n      Qed.\n\n      Require Import Reflection Tactics.\n\n      Lemma unify_remove_PureFacts : forall bound summ f p l S,\n        U.Subst_WellTyped tfuncs tU tG S ->\n        nth_error preds f = Some p ->\n        all2 (@is_well_typed _ tfuncs tU tG) l (SDomain p) = true ->\n        forall r r' S',\n          List.Forall (fun r => all2 (@is_well_typed _ tfuncs tU tG) r (SDomain p) = true) r ->\n          unify_remove bound summ l (SDomain p) r S = Some (r', S') ->\n             U.Subst_Extends S' S\n          /\\ U.Subst_WellTyped tfuncs tU tG S'\n          /\\ List.Forall (fun r => all2 (@is_well_typed _ tfuncs tU tG) r (SDomain p) = true) r'.\n      Proof.\n        induction r; simpl; intros; try congruence.\n        consider (unifyArgs bound summ l a (SDomain p) S); intros.\n        { inversion H4; clear H4; subst. inversion H2; clear H2; subst.\n          eapply unifyArgs_Extends_WellTyped in H3; eauto. intuition eauto. }\n        { consider (unify_remove bound summ l (SDomain p) r S); intros.\n          { destruct p0. inversion H5; clear H5; subst. inversion H2; clear H2; subst.\n            eapply IHr in H8; intuition. eauto. eauto. eauto. }\n          { congruence. } }\n      Qed.\n\n    End with_typing.\n\n    Require Ordering.\n\n    Definition cancel_list : Type := \n      list (exprs types * nat).\n\n    (** This function determines whether an expression [l] is more \"defined\"\n     ** than an expression [r]. An expression is more defined if it \"uses UVars later\".\n     ** NOTE: This is a \"fuzzy property\" but correctness doesn't depend on it.\n     **)\n    Fixpoint expr_count_meta (e : expr types) : nat :=\n      match e with\n        | Expr.Const _ _\n        | Var _ => 0\n        | UVar _ => 1\n        | Not l => expr_count_meta l\n        | Equal _ l r => expr_count_meta l + expr_count_meta r\n        | Expr.Func _ args =>\n          fold_left plus (map expr_count_meta args) 0\n      end.\n\n    Fixpoint exprs_count_meta (es : exprs types) : nat :=\n      match es with\n        | nil => O\n        | e :: es' => expr_count_meta e + exprs_count_meta es'\n      end.\n\n    (** When expressions have the same number of uvars, we want to favor the larger\n     ** expressions first, since they are less likely to match spuriously. *)\n    Fixpoint expr_size (e : expr types) : nat :=\n      match e with\n        | Expr.Const _ _\n        | Var _\n        | UVar _ => 0\n        | Not l => S (expr_size l)\n        | Equal _ l r => S (expr_size l + expr_size r)\n        | Expr.Func _ args => fold_left plus (map expr_size args) 1\n      end.\n\n    Definition meta_order_args (l r : exprs types) : Datatypes.comparison :=\n      match Compare_dec.nat_compare (exprs_count_meta l) (exprs_count_meta r) with\n        | Datatypes.Eq =>\n          Ordering.list_lex_cmp _ (fun l r => Compare_dec.nat_compare (expr_size l) (expr_size r)) l r\n        | v => v\n      end.\n\n    Definition meta_order_funcs (l r : exprs types * func) : Datatypes.comparison :=\n      match snd l, snd r with\n        | 2, 0 => Datatypes.Lt\n        | 2, 1 => Datatypes.Lt\n        | 2, S (S (S _)) => Datatypes.Lt\n        | 0, 2 => Datatypes.Gt\n        | 1, 2 => Datatypes.Gt\n        | S (S (S _)), 2 => Datatypes.Gt\n        | _, _ =>\n          match meta_order_args (fst l) (fst r) with\n            | Datatypes.Eq => Compare_dec.nat_compare (snd l) (snd r)\n            | x => x\n          end\n      end.\n\n    Definition order_impures (imps : MM.mmap (exprs types)) : cancel_list :=\n      FM.fold (fun k => fold_left (fun (acc : cancel_list) (args : exprs types) => \n        Ordering.insert_in_order _ meta_order_funcs (args, k) acc)) imps nil.\n\n    Lemma impuresD'_flatten : forall U G cs imps,\n      SE.heq funcs preds U G cs\n        (SH.impuresD _ _ imps)\n        (SH.starred (fun v => SE.Func (snd v) (fst v)) \n          (FM.fold (fun f argss acc => \n            map (fun args => (args, f)) argss ++ acc) imps nil) SE.Emp).\n    Proof.\n      clear. intros. eapply MM.PROPS.fold_rec; intros.\n        rewrite (SH.impuresD_Empty funcs preds U G cs H).\n        rewrite SH.starred_def. simpl. reflexivity.\n\n        rewrite SH.impuresD_Add; eauto. rewrite SH.starred_app. \n        rewrite H2. symmetry. rewrite SH.starred_base. heq_canceler.\n        repeat rewrite SH.starred_def.\n        clear; induction e; simpl; intros; try reflexivity.\n        rewrite IHe. reflexivity.\n    Qed.\n\n    Lemma fold_Permutation : forall imps L R,\n      Permutation.Permutation L R ->\n      Permutation.Permutation\n      (FM.fold (fun (f : FM.key) (argss : list (exprs types)) (acc : list (exprs types * FM.key)) =>\n        map (fun args : exprs types => (args, f)) argss ++ acc) imps L)\n      (FM.fold\n        (fun k : FM.key =>\n         fold_left\n           (fun (acc : cancel_list) (args : exprs types) =>\n            Ordering.insert_in_order (exprs types * nat) meta_order_funcs\n              (args, k) acc)) imps R).\n    Proof.\n      clear. intros.\n      eapply @MM.PROPS.fold_rel; simpl; intros; auto.\n        revert H1; clear. revert a; revert b; induction e; simpl; intros; auto.\n        rewrite <- IHe; eauto.\n        \n        destruct (@Ordering.insert_in_order_inserts (exprs types * nat) meta_order_funcs (a,k) b) as [ ? [ ? [ ? ? ] ] ].\n        subst. rewrite H.\n        rewrite <- app_ass.\n        eapply Permutation.Permutation_cons_app.\n        rewrite app_ass. eapply Permutation.Permutation_app; eauto.\n    Qed.\n\n    Lemma order_impures_D : forall U G cs imps,\n      heq funcs preds U G cs \n        (SH.impuresD _ _ imps)\n        (SH.starred (fun v => (Func (snd v) (fst v))) (order_impures imps) Emp).\n    Proof.\n      clear. intros. rewrite impuresD'_flatten. unfold order_impures.\n      eapply starred_perm. eapply fold_Permutation. reflexivity.\n    Qed.\n    \n    (** NOTE : l and r are reversed here **)\n    (** cancel_in_order ls acc rem = (l,r,sub) ->\n     ** r ===> l ->\n     ** rem ===> ls * acc\n     **)\n    Fixpoint cancel_in_order (bound : nat) (summ : Facts Prover) \n      (ls : cancel_list) (acc rem : MM.mmap (exprs types)) (sub : U.Subst types)\n      (progress : bool)\n      : option (MM.mmap (exprs types) * MM.mmap (exprs types) * U.Subst types) :=\n      match ls with\n        | nil => \n          if progress then Some (acc, rem, sub) else None\n        | (args,f) :: ls => \n          match FM.find f rem with\n            | None => cancel_in_order bound summ ls (MM.mmap_add f args acc) rem sub progress\n            | Some argss =>\n              match nth_error preds f with\n                | None => cancel_in_order bound summ ls (MM.mmap_add f args acc) rem sub progress (** Unused! **)\n                | Some ts => \n                  match unify_remove bound summ args (SDomain ts) argss sub with\n                    | None => cancel_in_order bound summ ls (MM.mmap_add f args acc) rem sub progress\n                    | Some (rem', sub) =>\n                      cancel_in_order bound summ ls acc (FM.add f rem' rem) sub true\n                  end\n              end                      \n          end\n      end.\n\n    Lemma cancel_in_order_equiv : forall bound summ ls acc rem sub L R S acc' progress,\n      MM.mmap_Equiv acc acc' ->\n      cancel_in_order bound summ ls acc rem sub progress = Some (L, R, S) ->\n      exists L' R' S',\n        cancel_in_order bound summ ls acc' rem sub progress = Some (L', R', S') /\\\n        MM.mmap_Equiv L L' /\\\n        MM.mmap_Equiv R R' /\\\n        U.Subst_Equal S S'.\n    Proof.\n      clear. induction ls; simpl; intros.\n      { inversion H0; subst; auto. \n        destruct progress; try congruence. inversion H0; clear H0; subst.\n        do 3 eexists. split; [ reflexivity | intuition ]. }\n      { repeat match goal with\n                 | [ H : match ?X with \n                           | (_,_) => _\n                         end = _ |- _ ] => destruct X\n                 | [ H : match ?X with\n                           | Some _ => _ | None => _ \n                         end = _ |- _ ] =>\n                 revert H; case_eq X; intros\n               end;\n        (eapply IHls; [ eauto using MM.mmap_add_mor | eassumption ]). }\n    Qed.\n\n    Lemma cancel_in_order_mmap_add_acc : forall bound summ ls n e acc rem sub L R S progress,\n      cancel_in_order bound summ ls (MM.mmap_add n e acc) rem sub progress = Some (L, R, S) ->\n      exists L' R' S',\n        cancel_in_order bound summ ls acc rem sub progress = Some (L', R', S') /\\\n        MM.mmap_Equiv (MM.mmap_add n e L') L /\\\n        MM.mmap_Equiv R R' /\\\n        U.Subst_Equal S S'.\n    Proof.\n      clear. induction ls; simpl; intros.\n      { inversion H; subst.\n        destruct progress; try congruence. inversion H; clear H; subst.\n        do 3 eexists; split. \n        reflexivity. split; try reflexivity. split; try reflexivity. }\n      { repeat match goal with\n                 | [ H : match ?X with \n                           | (_,_) => _\n                         end = _ |- _ ] => destruct X\n                 | [ H : match ?X with\n                           | Some _ => _ | None => _ \n                         end = _ |- _ ] =>\n                 revert H; case_eq X; intros\n               end;\n        try solve [ eapply IHls; eauto ];\n        match goal with\n          | [ H : cancel_in_order _ _ _ _ _ _ _ = _ |- _ ] =>\n            eapply cancel_in_order_equiv in H; [ | eapply MM.mmap_add_comm ]\n        end;\n        repeat match goal with\n                 | [ H : exists x, _ |- _ ] => destruct H\n                 | [ H : _ /\\ _ |- _ ] => destruct H\n               end;\n        match goal with\n          | [ H : cancel_in_order _ _ _ _ _ _ _ = _ |- _ ] =>\n            eapply IHls in H\n        end;\n        repeat match goal with\n                 | [ H : exists x, _ |- _ ] => destruct H\n                 | [ H : _ /\\ _ |- _ ] => destruct H\n                 | [ |- exists x, _ /\\ _ ] => eexists; split; [ eassumption | ]\n                 | [ |- exists x, _ ] => eexists\n                 | [ H : MM.mmap_Equiv _ _ |- _ ] => rewrite H\n                 | [ H : U.Subst_Equal _ _ |- _ ] => rewrite H\n               end; try intuition reflexivity. }\n    Qed.\n\n    Lemma nth_error_typeof_preds : forall p n,\n      nth_error (typeof_preds p) n = option_map (@typeof_pred types pcType stateType) (nth_error p n).\n    Proof.\n      clear. unfold typeof_preds. intros. rewrite Tactics.map_nth_error_full. reflexivity.\n    Qed.\n    \n    Require Import Tactics.\n\n    Lemma WellTyped_impures_add : forall tf tp tU tG f l m,\n      SH.WellTyped_impures (types := types) tf tp tU tG m = true ->\n      match nth_error tp f with\n        | None => false\n        | Some p => allb (fun l => all2 (is_well_typed tf tU tG) l p) l\n      end = true ->\n      SH.WellTyped_impures tf tp tU tG (FM.add f l m) = true.\n    Proof. clear.\n      intros. eapply SH.WellTyped_impures_eq. intros.\n      consider (nth_error tp f); try congruence; intros.\n      rewrite MF.FACTS.add_o in H1. destruct (MF.FACTS.eq_dec f k); think.\n      destruct v; auto.\n      eapply SH.WellTyped_impures_eq in H; eauto.\n    Qed.\n\n    Lemma WellTyped_impures_mmap_add : forall tf tp tU tG f l m,\n      SH.WellTyped_impures (types := types) tf tp tU tG m = true ->\n      match nth_error tp f with\n        | None => false\n        | Some p => all2 (is_well_typed tf tU tG) l p\n      end = true ->\n      SH.WellTyped_impures tf tp tU tG (MM.mmap_add f l m) = true.\n    Proof. clear.\n      intros. eapply SH.WellTyped_impures_eq. intros.\n      consider (nth_error tp f); try congruence; intros.\n      unfold MM.mmap_add in *. consider (FM.find (elt:=list (list (expr types))) f m); intros.\n      rewrite MF.FACTS.add_o in H3. destruct (MF.FACTS.eq_dec f k).\n      { inversion H3; clear H3; subst. rewrite H0. simpl. rewrite H2.\n        eapply SH.WellTyped_impures_eq in H. 2: eauto. destruct l0; auto. rewrite H0 in *. assumption. }\n      { eapply SH.WellTyped_impures_eq; eauto. }\n      { rewrite MF.FACTS.add_o in H3. destruct (MF.FACTS.eq_dec f k).\n        inversion H3; clear H3; subst. rewrite H0. simpl; rewrite H2; auto.\n        eapply SH.WellTyped_impures_eq; eauto. }\n    Qed.\n\n    Lemma cancel_in_order_PureFacts_weak : forall tU tG bound summ,\n      let tf := typeof_funcs funcs in\n      let tp := SE.typeof_preds preds in\n(*\n      let tU := typeof_env U in\n      let tG := typeof_env G in *)\n      forall ls acc rem sub L R S progress,\n      U.Subst_WellTyped tf tU tG sub ->\n      allb (fun v => SE.WellTyped_sexpr tf tp tU tG \n        (Func (pcType := pcType) (stateType := stateType) (snd v) (fst v))) ls = true ->\n      SH.WellTyped_impures tf tp tU tG acc = true ->\n      SH.WellTyped_impures tf tp tU tG rem = true ->\n(*      Valid Prover_correct U G summ ->  *)\n      cancel_in_order bound summ ls acc rem sub progress = Some (L, R, S) ->\n         U.Subst_Extends S sub \n      /\\ U.Subst_WellTyped tf tU tG S\n      /\\ SH.WellTyped_impures tf tp tU tG L = true \n      /\\ SH.WellTyped_impures tf tp tU tG R = true.\n    Proof.\n      induction ls; simpl; intros.\n      { destruct progress; try congruence. inversion H3; clear H3; subst; intuition. }\n      { subst tp. rewrite nth_error_typeof_preds in H0. destruct a; simpl in *. \n        repeat match goal with\n                 | H : context [ option_map _ ?X ] |- _ =>\n                   (consider X; simpl in *; try congruence); [ intros ]\n                 | [ H : match ?X with _ => _ end = _ |- _ ] =>\n                   (consider X; intros; try congruence); [ intros ]\n                 | [ H : match ?X with\n                           | Some _ => _ | None => _ \n                         end = _ |- _ ] =>\n                 consider X; intros\n               end; simpl in *; subst.\n{ assert (List.Forall\n          (fun r : list (expr types) =>\n            all2 (is_well_typed tf tU tG) r (SDomain p) = true) l0).\n          { eapply SH.WellTyped_impures_eq in H2; try eassumption.\n            destruct l0. constructor. rewrite nth_error_typeof_preds in H2.\n            rewrite H0 in H2. generalize dependent (e :: l0); simpl; intros.\n            unfold typeof_pred in H2. clear - H2.\n            induction l2; simpl in *; constructor; think; auto. }\n          eapply unify_remove_PureFacts in H7.\n          2: eauto. 2: eauto. 2: eauto. 2: eauto. \n          { eapply IHls in H8; eauto. intuition.\n            etransitivity; eassumption.\n            intuition. intuition.\n            eapply SH.WellTyped_impures_eq. intros. rewrite MF.FACTS.add_o in H10.\n            destruct (MF.FACTS.eq_dec f k); auto. inversion H10; clear H10; subst. \n            rewrite nth_error_typeof_preds in *. rewrite H0 in *. simpl. destruct v; intuition.\n            generalize dependent (e :: v); intros.\n            clear - H11. unfold typeof_pred. induction H11; simpl; auto. rewrite H. auto.\n            eapply SH.WellTyped_impures_eq; eauto. } }\n        { clear H6. eapply IHls in H7; eauto.\n          eapply WellTyped_impures_mmap_add; auto. rewrite nth_error_typeof_preds.\n          rewrite H0. simpl. auto. }\n        { clear H4. eapply IHls in H6; eauto.\n          eapply WellTyped_impures_mmap_add; auto. rewrite nth_error_typeof_preds.\n          rewrite H0. simpl. auto. } }\n    Qed.\n\n    Lemma cancel_in_order_PureFacts : forall U G bound summ,\n      let tf := typeof_funcs funcs in\n      let tp := SE.typeof_preds preds in\n      let tU := typeof_env U in\n      let tG := typeof_env G in\n      forall ls acc rem sub L R S progress,\n      U.Subst_WellTyped tf tU tG sub ->\n      U.Subst_equations funcs U G S ->\n      allb (fun v => SE.WellTyped_sexpr tf tp tU tG \n        (Func (pcType := pcType) (stateType := stateType) (snd v) (fst v))) ls = true ->\n      SH.WellTyped_impures tf tp tU tG acc = true ->\n      SH.WellTyped_impures tf tp tU tG rem = true ->\n      cancel_in_order bound summ ls acc rem sub progress = Some (L, R, S) ->\n         U.Subst_equations funcs U G sub \n      /\\ U.Subst_WellTyped (typeof_funcs funcs) (typeof_env U) (typeof_env G) S\n      /\\ SH.WellTyped_impures tf tp tU tG L = true \n      /\\ SH.WellTyped_impures tf tp tU tG R = true.\n    Proof.\n      intros.\n      eapply cancel_in_order_PureFacts_weak in H4; try eassumption. intuition.\n      eapply U.Subst_equations_Extends. 2: eassumption. eauto. \n    Qed.\n\n    Lemma impuresD_mmap_add : forall cs U G f args m,\n      heq funcs preds U G cs \n      (SH.impuresD pcType stateType (MM.mmap_add f args m))\n      (Star (Func f args) (SH.impuresD pcType stateType m)).\n    Proof. clear.\n      intros. unfold MM.mmap_add. consider (FM.find (elt:=list (exprs types)) f m); intros.\n      { rewrite SH.impuresD_Add with (f := f) (argss := args :: l) (i := FM.remove f m).\n        rewrite starred_cons. \n        rewrite SH.impuresD_Add with (f := f) (argss := l) (i := FM.remove f m) (i' := m).\n        heq_canceler.\n        intro. repeat (rewrite MF.FACTS.add_o || rewrite MF.FACTS.remove_o). destruct (MF.FACTS.eq_dec f y); subst; auto.\n        rewrite MF.FACTS.remove_in_iff. intro. intuition; congruence.\n        intro. repeat (rewrite MF.FACTS.add_o || rewrite MF.FACTS.remove_o). destruct (MF.FACTS.eq_dec f y); subst; auto.\n        rewrite MF.FACTS.remove_in_iff. intro. intuition; congruence. }\n      { rewrite SH.impuresD_Add with (f := f) (argss := args :: nil) (i := m).\n        rewrite starred_cons. \n        heq_canceler.\n        intro. repeat (rewrite MF.FACTS.add_o || rewrite MF.FACTS.remove_o). destruct (MF.FACTS.eq_dec f y); subst; auto.\n        intro. destruct H0. apply MF.FACTS.find_mapsto_iff in H0; congruence. }\n    Qed.\n\n    Lemma cancel_in_order_common : forall \n      (U G : env types)\n      (cs : codeSpec (tvarD types pcType) (tvarD types stateType))\n      (bound : nat) (summ : Facts Prover) (e : exprs types) \n      (n : nat) (ls : list (exprs types * nat)),\n      (forall (acc rem : MM.mmap (exprs types)) (sub : U.Subst types)\n        (L R : MM.mmap (exprs types)) (S : U.Subst types) progress,\n        U.Subst_WellTyped (typeof_funcs funcs) (typeof_env U) (typeof_env G) sub ->\n        U.Subst_WellTyped (typeof_funcs funcs) (typeof_env U) (typeof_env G) S ->\n        U.Subst_equations funcs U G S ->\n        Valid Prover_correct U G summ ->\n        cancel_in_order bound summ ls acc rem sub progress = Some (L, R, S) ->\n        allb\n        (fun v : list (expr types) * func =>\n          match nth_error (typeof_preds preds) (snd v) with\n            | Some ts =>\n              all2\n              (is_well_typed (typeof_funcs funcs) (typeof_env U)\n                (typeof_env G)) (map (U.exprInstantiate S) (fst v)) ts\n            | None => false\n          end) ls = true ->\n        SH.WellTyped_impures (typeof_funcs funcs) (typeof_preds preds)\n        (typeof_env U) (typeof_env G) acc = true ->\n        SH.WellTyped_impures (typeof_funcs funcs) (typeof_preds preds)\n        (typeof_env U) (typeof_env G) rem = true ->\n        forall P Q,\n          himp funcs preds U G cs\n          (Star (SH.impuresD pcType stateType (impuresInstantiate S R)) P)\n          (Star (SH.impuresD pcType stateType (impuresInstantiate S L)) Q) ->\n          himp funcs preds U G cs\n          (Star (SH.impuresD pcType stateType (impuresInstantiate S rem)) P)\n          (Star\n            (Star\n              (SH.starred\n                (fun v : list (expr types) * func =>\n                  Func (snd v) (map (U.exprInstantiate S) (fst v))) ls Emp)\n              (SH.impuresD pcType stateType (impuresInstantiate S acc))) Q)) ->\n      forall (acc rem : MM.mmap (exprs types)) (sub : U.Subst types)\n        (L R : MM.mmap (exprs types)) (S : U.Subst types) progress,\n        U.Subst_WellTyped (typeof_funcs funcs) (typeof_env U) (typeof_env G) sub ->\n        U.Subst_WellTyped (typeof_funcs funcs) (typeof_env U) (typeof_env G) S ->\n        U.Subst_equations funcs U G S ->\n        Valid Prover_correct U G summ ->\n        SH.WellTyped_impures (typeof_funcs funcs) (typeof_preds preds)\n        (typeof_env U) (typeof_env G) acc = true ->\n        SH.WellTyped_impures (typeof_funcs funcs) (typeof_preds preds)\n        (typeof_env U) (typeof_env G) rem = true ->\n        forall P Q,\n          himp funcs preds U G cs\n          (Star (SH.impuresD pcType stateType (impuresInstantiate S R)) P)\n          (Star (SH.impuresD pcType stateType (impuresInstantiate S L)) Q) ->\n          forall p : predicate types pcType stateType,\n            nth_error preds n = Some p ->\n            all2 (is_well_typed (typeof_funcs funcs) (typeof_env U) (typeof_env G))\n            (map (U.exprInstantiate S) e) (typeof_pred p) = true ->\n            allb\n            (fun v : list (expr types) * func =>\n              match nth_error (typeof_preds preds) (snd v) with\n                | Some ts =>\n                  all2\n                  (is_well_typed (typeof_funcs funcs) (typeof_env U) (typeof_env G))\n                  (map (U.exprInstantiate S) (fst v)) ts\n                | None => false\n              end) ls = true ->\n            cancel_in_order bound summ ls (MM.mmap_add n e acc) rem sub progress = Some (L, R, S) ->\n            himp funcs preds U G cs\n            (Star (SH.impuresD pcType stateType (impuresInstantiate S rem)) P)\n            (Star (Star\n              (SH.SE.Star (Func n (map (U.exprInstantiate S) e))\n                (SH.starred\n                  (fun v : list (expr types) * func =>\n                    Func (snd v) (map (U.exprInstantiate S) (fst v))) ls Emp))\n              (SH.impuresD pcType stateType (impuresInstantiate S acc))) Q).\n    Proof.\n      intros. \n      assert (allb (fun v : list (expr types) * func => WellTyped_sexpr (typeof_funcs funcs) (typeof_preds preds) \n        (typeof_env U) (typeof_env G) (Func (pcType := pcType) (stateType := stateType) (snd v) (fst v))) ls = true).\n      { eapply allb_impl. eauto. simpl. intros. destruct (nth_error (typeof_preds preds) (snd x)); auto.\n        rewrite all2_map_1 in H11. eapply all2_impl; try eassumption. intros.\n        simpl in *. rewrite <- U.exprInstantiate_WellTyped in H12; eauto. }\n      assert (SH.WellTyped_impures (typeof_funcs funcs) (typeof_preds preds)\n        (typeof_env U) (typeof_env G) (MM.mmap_add n e acc) = true).\n      { eapply WellTyped_impures_mmap_add. eauto. rewrite nth_error_typeof_preds. rewrite H7. simpl.\n        unfold typeof_pred. rewrite all2_map_1 in H8. eapply all2_impl. eauto. simpl.\n        intros. rewrite <- U.exprInstantiate_WellTyped in H12; eauto. }\n      generalize H10. eapply cancel_in_order_PureFacts in H10; eauto. intro.\n      eapply H in H13; eauto. intuition.\n      rewrite H13.\n      do 2 rewrite SEP_UFACTS.impuresD_forget_impuresInstantiate by eassumption.\n      rewrite impuresD_mmap_add. rewrite Func_forget_exprInstantiate by eassumption.\n      rewrite heq_star_comm with (Q := SH.starred\n        (fun v : list (expr types) * func =>\n          Func (snd v) (map (U.exprInstantiate S) (fst v))) ls Emp).\n      repeat rewrite heq_star_assoc. reflexivity.\n    Qed.\n\n    (** cancel_in_order ls acc rem = (l,r,sub) ->\n     ** r ===> l ->\n     ** rem ===> ls * acc\n     **)\n    Lemma cancel_in_orderOk : forall U G cs bound summ ls acc rem sub L R S progress,\n      let tf := typeof_funcs funcs in\n      let tp := SE.typeof_preds preds in\n      let tU := typeof_env U in\n      let tG := typeof_env G in\n      U.Subst_WellTyped tf tU tG sub ->\n      U.Subst_WellTyped tf tU tG S ->\n      U.Subst_equations funcs U G S ->\n      Valid Prover_correct U G summ ->\n      cancel_in_order bound summ ls acc rem sub progress = Some (L, R, S) ->\n      allb (fun v => SE.WellTyped_sexpr tf tp tU tG \n        (Func (pcType := pcType) (stateType := stateType) (snd v) (map (@U.exprInstantiate _ S) (fst v)))) ls = true ->\n      SH.WellTyped_impures tf tp tU tG acc = true ->\n      SH.WellTyped_impures tf tp tU tG rem = true ->\n      forall P Q,\n      himp funcs preds U G cs \n        (Star (SH.impuresD _ _ (impuresInstantiate S R)) P)\n        (Star (SH.impuresD _ _ (impuresInstantiate S L)) Q) ->\n      himp funcs preds U G cs \n        (Star (SH.impuresD _ _ (impuresInstantiate S rem)) P)\n        (Star (Star (SH.starred (fun v => (Func (snd v) (map (@U.exprInstantiate _ S) (fst v)))) ls Emp)\n                    (SH.impuresD _ _ (impuresInstantiate S acc))) Q).\n    Proof.\n      induction ls; simpl; intros.\n      { destruct progress; try congruence. inversion H3; clear H3; subst. \n        repeat rewrite starred_nil. rewrite heq_star_emp_l. auto. }\n      { rewrite starred_cons. rewrite nth_error_typeof_preds in H4. destruct a; simpl in *.\n        repeat match goal with\n                 | H : context [ option_map _ ?X ] |- _ =>\n                   (consider X; simpl in *; try congruence); [ intros ]\n                 | [ H : match ?X with _ => _ end = _ |- _ ] =>\n                   (consider X; intros; try congruence); [ intros ]\n                 | [ H : match ?X with\n                           | Some _ => _ | None => _ \n                         end = _ |- _ ] =>\n                 consider X; intros\n               end; simpl in *; subst.\n        { assert (all2 (is_well_typed (typeof_funcs funcs) (typeof_env U) (typeof_env G)) e (SDomain p) = true).\n          { rewrite all2_map_1 in H8. eapply all2_impl. eapply H8. intros. simpl in *.\n            rewrite <- U.exprInstantiate_WellTyped in H10; eauto. }\n          assert (List.Forall (fun r : list (expr types) =>\n            all2 (is_well_typed (typeof_funcs funcs) (typeof_env U) (typeof_env G)) r (SDomain p) = true) l).\n          { eapply SH.WellTyped_impures_eq in H6; eauto. destruct l. constructor.\n            rewrite nth_error_typeof_preds in *. rewrite H3 in H6. revert H6.\n            generalize (e0 :: l). simpl. clear. induction l; simpl; intros; auto.\n            consider (all2 (is_well_typed (typeof_funcs funcs) (typeof_env U) (typeof_env G)) a (typeof_pred p)); intros.\n            constructor; auto. }\n          generalize H11. eapply unify_remove_PureFacts in H11; eauto using typeof_env_WellTyped_env, typeof_funcs_WellTyped_funcs.\n          intuition.\n          assert (allb (fun v : list (expr types) * func =>\n            WellTyped_sexpr (typeof_funcs funcs) (typeof_preds preds)\n            (typeof_env U) (typeof_env G) (Func (pcType := pcType) (stateType := stateType) (snd v) (fst v))) ls = true).\n          { eapply allb_impl. eassumption. simpl. intros.\n            destruct (nth_error (typeof_preds preds) (snd x)); auto.\n            rewrite all2_map_1 in H16. eapply all2_impl. eauto. simpl. intros.\n            rewrite <- U.exprInstantiate_WellTyped in H18; eauto. }\n          assert (SH.WellTyped_impures (typeof_funcs funcs) (typeof_preds preds)\n            (typeof_env U) (typeof_env G) (FM.add n l0 rem) = true).\n          { eapply WellTyped_impures_add; eauto. \n            rewrite nth_error_typeof_preds in *. rewrite H3. simpl. clear - H17.\n            unfold typeof_pred in *. induction H17; simpl; think; auto. }\n          generalize H12. eapply cancel_in_order_PureFacts in H12; eauto. intuition.\n          do 2 rewrite SEP_UFACTS.impuresD_forget_impuresInstantiate by eassumption.\n          assert (MM.PROPS.Add n l (FM.remove (elt:=list (exprs types)) n rem) rem).\n          { red. intro. rewrite MF.FACTS.add_o. rewrite MF.FACTS.remove_o.\n            destruct (MF.FACTS.eq_dec n y); subst; auto. }\n          assert (~FM.In (elt:=list (exprs types)) n (FM.remove (elt:=list (exprs types)) n rem)).\n          { rewrite MF.FACTS.remove_in_iff. intro. intuition; congruence. }\n          rewrite SH.impuresD_Add with (i := FM.remove n rem) (i' := rem) (f := n) (argss := l) by eassumption.\n          rewrite heq_star_assoc.          \n          rewrite Func_forget_exprInstantiate by eassumption.\n          eapply unify_removeOk with (cs := cs) in H14; [ | | | | eassumption | | | | | | ];\n            eauto using typeof_env_WellTyped_env, typeof_funcs_WellTyped_funcs.\n          destruct H14. repeat rewrite heq_star_assoc. rewrite <- H14. rewrite heq_star_comm. rewrite <- SH.starred_base. \n          reflexivity.\n          eapply IHls in H19; eauto.\n          do 2 rewrite SEP_UFACTS.impuresD_forget_impuresInstantiate in H19 by eassumption.\n          rewrite heq_star_assoc in H19. rewrite <- H19.\n          rewrite SH.impuresD_Add with (i := FM.remove n rem) (i' := FM.add n l0 rem) (f := n) (argss := l0).\n          rewrite SH.starred_base. rewrite heq_star_comm. rewrite heq_star_assoc. reflexivity.\n          { intro. repeat (rewrite MF.FACTS.add_o || rewrite MF.FACTS.remove_o). destruct (MF.FACTS.eq_dec n y); auto. }\n          { rewrite MF.FACTS.remove_in_iff. intro. intuition; congruence. } }\n        { eapply cancel_in_order_common in H11; eauto. }\n        { eapply cancel_in_order_common in H10; eauto. } }\n    Qed.\n\n    Lemma fold_left_insert_perm : forall e a k,\n      Permutation.Permutation (map (fun x => (x,k)) e ++ a)\n      (fold_left\n        (fun (acc : cancel_list) (args : exprs types) =>\n          Ordering.insert_in_order (exprs types * func) meta_order_funcs\n          (args, k) acc) e a).\n    Proof.\n      clear. induction e; simpl.\n      eauto.\n      intros. rewrite <- IHe; clear IHe.\n      destruct (@Ordering.insert_in_order_inserts _ meta_order_funcs (a,k) a0). destruct H.\n      intuition subst. rewrite H0.\n      rewrite <- app_ass. rewrite <- app_ass.\n      eapply Permutation.Permutation_middle.\n    Qed.\n\n    (** TODO: it would be good to keep this somewhat general with respect to the order so that we can play around with it\n     ** NOTE: return None if we don't make progress\n     **)\n    Definition sepCancel (bound : nat) (summ : Facts Prover) (l r : SH.SHeap types pcType stateType) (s : U.Subst types) \n      (prog : bool) : option (SH.SHeap _ _ _ * SH.SHeap _ _ _ * U.Subst types) :=\n      let ordered_r := order_impures (SH.impures r) in\n      let sorted_l := FM.map (fun v => Ordering.sort _ meta_order_args v) (SH.impures l) in \n      match \n        cancel_in_order bound summ ordered_r (MM.empty _) sorted_l s prog\n        with\n        | None => None \n        | Some (rf, lf, sub) =>\n          Some ({| SH.impures := lf ; SH.pures := SH.pures l ; SH.other := SH.other l |},\n                {| SH.impures := rf ; SH.pures := SH.pures r ; SH.other := SH.other r |},\n                sub)\n      end.\n\n    Theorem sepCancel_PuresPrem : forall funcs U G bound summ l r l' r' s s' b,\n      sepCancel bound summ l r s b = Some (l', r', s') ->\n      AllProvable funcs U G (SH.pures l) ->\n      AllProvable funcs U G (SH.pures l').\n    Proof.\n      unfold sepCancel. intros.\n      destruct (cancel_in_order bound summ (order_impures (SH.impures r))\n              (MM.empty (exprs types))\n              (FM.map\n                 (fun v : list (exprs types) =>\n                  Ordering.sort (exprs types) meta_order_args v)\n                 (SH.impures l)) s). destruct p. destruct p. inversion H.\n      auto. congruence.\n    Qed.\n\n    Lemma starred_ext : forall T U G cs F F' (ls : list T) B,\n      (forall x, heq funcs preds U G cs (F x) (F' x)) -> \n      heq funcs preds U G cs (SH.starred F ls B) (SH.starred F' ls B).\n    Proof. clear.\n      induction ls; intros; repeat (rewrite starred_nil || rewrite starred_cons).\n      reflexivity. rewrite H. rewrite IHls; auto. reflexivity.\n    Qed.\n\n    Lemma Equiv_map : forall T (E : T -> T -> Prop) (F : T -> T) a,\n      (forall x, E (F x) x) ->\n      FM.Equiv E (FM.map F a) a.\n    Proof. clear.\n      red; intros. split; intros.\n      rewrite MF.PROPS.F.map_in_iff. tauto.\n      apply MF.FACTS.map_mapsto_iff in H0. destruct H0. intuition; subst.\n      apply MF.FACTS.find_mapsto_iff in H1. apply MF.FACTS.find_mapsto_iff in H3. \n      rewrite H1 in H3; inversion H3; auto.\n    Qed.\n\n    Lemma allb_permutation : forall T F (a b : list T),\n      Permutation.Permutation a b ->\n      allb F a = allb F b.\n    Proof. clear.\n      induction 1; simpl; auto.\n      destruct (F x); auto.\n      destruct (F x); destruct (F y); auto.\n      rewrite IHPermutation1; auto.\n    Qed.\n\n    Lemma fold_left_fold_left_insert_perm : forall l (B : cancel_list),\n      Permutation.Permutation \n      (B ++ fold_left (fun (a : cancel_list) (p : FM.key * list (list (expr types))) =>\n        fold_left (fun (acc : cancel_list) (args : list (expr types)) =>\n          Ordering.insert_in_order (list (expr types) * func) meta_order_funcs (args, fst p) acc) (snd p) a) l nil)\n      (fold_left (fun (a : cancel_list) (p : FM.key * list (list (expr types))) =>\n        fold_left (fun (acc : cancel_list) (args : list (expr types)) =>\n          Ordering.insert_in_order (list (expr types) * func) meta_order_funcs (args, fst p) acc) (snd p) a) l B).\n    Proof.\n      induction l; simpl; intros. \n      rewrite app_nil_r; reflexivity.\n      etransitivity. 2: eapply IHl. destruct a; simpl. \n      symmetry. \n      rewrite Permutation.Permutation_app_tail.\n      2: symmetry; apply (@fold_left_insert_perm l0 B k).\n      rewrite Permutation.Permutation_app_tail.\n      2: apply Permutation.Permutation_app_comm with (l' := B). rewrite app_ass.\n      apply Permutation.Permutation_app_head.\n      etransitivity. 2: eapply IHl. apply Permutation.Permutation_app_tail.\n      etransitivity. 2: apply fold_left_insert_perm. rewrite app_nil_r; auto.\n    Qed.\n\n    Lemma WellTyped_empty : forall tf tp tU tG,\n      SH.WellTyped_impures tf tp tU tG (MM.empty (exprs types)) = true.\n    Proof. clear.\n      intros. rewrite SH.WellTyped_impures_spec_eq. rewrite MF.PROPS.fold_Empty; auto with typeclass_instances.\n      apply FM.empty_1.\n    Qed.\n\n    Lemma order_impures_WellTyped : forall tf tp tU tG imp,\n      SH.WellTyped_impures tf tp tU tG imp = true ->\n      allb (fun v : list (expr types) * func => WellTyped_sexpr tf tp tU tG\n        (Func (pcType := pcType) (stateType := stateType) (snd v) (fst v))) (order_impures imp) = true.\n    Proof. clear.\n      intros. unfold order_impures.\n      rewrite SH.WellTyped_impures_spec_eq in H.\n      rewrite FM.fold_1 in *. revert H. unfold exprs in *. generalize true at 2 4.\n      induction (FM.elements (elt:=list (list (expr types))) imp); auto; intros.\n      simpl in *. \n      assert (fold_left\n        (fun (a : bool) (p : FM.key * list (list (expr types))) =>\n          (a &&\n            match snd p with\n              | nil => true\n              | _ :: _ =>\n                match nth_error tp (fst p) with\n                  | Some ts =>\n                    allb\n                    (fun args : list (expr types) =>\n                      all2\n                      (is_well_typed tf\n                        tU tG) args ts) \n                    (snd p)\n                  | None => false\n                end\n            end)%bool) l false = false).\n      { clear. induction l; simpl; auto. } \n      destruct b; simpl in H; try congruence.\n      destruct a. destruct l0; simpl in *. eauto.\n      consider (nth_error tp k); intros; try congruence.\n      consider (all2 (is_well_typed tf tU tG) l0 t); intros; try congruence.\n      consider (allb\n        (fun args : list (expr types) =>\n          all2\n          (is_well_typed tf tU tG) args t) l1); intros; try congruence.\n      rewrite <- IHl by assumption.\n      erewrite allb_permutation. \n      2: symmetry; apply fold_left_fold_left_insert_perm.\n      rewrite allb_app. erewrite <- allb_permutation.\n      2: eapply fold_left_insert_perm.\n      rewrite allb_app. rewrite allb_map. simpl. unfold exprs in *.\n      think. simpl. auto. \n    Qed.\n\n    Lemma map_sort_WellTyped : forall C tf tp tU tG imp,\n      SH.WellTyped_impures tf tp tU tG imp = true ->\n      SH.WellTyped_impures tf tp tU tG\n      (FM.map (fun v : list (exprs types) => Ordering.sort (exprs types) C v) imp) = true.\n    Proof. clear.\n      intros. eapply SH.WellTyped_impures_eq; intros. rewrite MF.FACTS.map_o in H0.\n      consider (FM.find (elt:=list (exprs types)) k imp); simpl in *; try congruence; intros.\n      inversion H1; clear H1; subst.\n      eapply SH.WellTyped_impures_eq in H0. 2: eassumption.\n      destruct l; auto. destruct (nth_error tp k); try contradiction.\n      erewrite allb_permutation in H0. 2: symmetry; eapply Ordering.sort_permutation.\n      rewrite H0. destruct (Ordering.sort (exprs types) C (e :: l)); auto. \n    Qed.\n\n    Theorem sepCancel_PureFacts : forall tU tG bound summ l r l' r' s s' b,\n      let tf := typeof_funcs funcs in\n      let tp := typeof_preds preds in\n      sepCancel bound summ l r s b = Some (l', r', s') ->\n      U.Subst_WellTyped tf tU tG s ->\n      SH.WellTyped_sheap tf tp tU tG l = true ->\n      SH.WellTyped_sheap tf tp tU tG r = true ->\n         U.Subst_WellTyped tf tU tG s' \n      /\\ SH.WellTyped_sheap tf tp tU tG l' = true\n      /\\ SH.WellTyped_sheap tf tp tU tG r' = true.\n    Proof. \n      unfold sepCancel. intros.\n      consider (cancel_in_order bound summ (order_impures (SH.impures r))\n              (MM.empty (exprs types))\n              (FM.map\n                 (fun v : list (exprs types) =>\n                  Ordering.sort (exprs types) meta_order_args v)\n                 (SH.impures l)) s b); intros.\n      destruct p. destruct p. inversion H3; clear H3; subst.\n      rewrite SH.WellTyped_sheap_eq in H1.\n      rewrite SH.WellTyped_sheap_eq in H2. think.\n      eapply cancel_in_order_PureFacts_weak in H; try eassumption; \n        eauto using order_impures_WellTyped, WellTyped_empty, map_sort_WellTyped.\n      intuition.\n      rewrite SH.WellTyped_sheap_eq; simpl; think; auto.\n      rewrite SH.WellTyped_sheap_eq; simpl; think; auto.\n      congruence.\n    Qed.\n\n    Theorem sepCancel_correct : forall U G cs bound summ l r l' r' sub sub' b,\n      U.Subst_WellTyped (typeof_funcs funcs) (typeof_env U) (typeof_env G) sub' ->\n      SH.WellTyped_sheap (typeof_funcs funcs) (typeof_preds preds) (typeof_env U) (typeof_env G) l = true ->\n      SH.WellTyped_sheap (typeof_funcs funcs) (typeof_preds preds) (typeof_env U) (typeof_env G) r = true ->\n      Valid Prover_correct U G summ ->\n      sepCancel bound summ l r sub' b = Some (l', r', sub) ->\n      himp funcs preds U G cs (SH.sheapD l') (SH.sheapD r') ->\n      U.Subst_equations funcs U G sub ->\n      himp funcs preds U G cs (SH.sheapD l) (SH.sheapD r).\n    Proof.\n      destruct l; destruct r. unfold sepCancel. simpl. intros.\n      repeat match goal with \n               | [ H : match ?X with _ => _ end = _ |- _ ] => \n                 revert H; case_eq X; intros; try congruence\n               | [ H : prod _ _ |- _ ] => destruct H\n               | [ H : (_,_) = (_,_) |- _ ] => inversion H; clear H; subst\n               | [ H : Some _ = Some _ |- _ ] => inversion H; clear H; subst\n             end.\n      do 2 rewrite SH.sheapD_def. simpl. \n      eapply cancel_in_orderOk with (cs := cs) (U := U) (G := G) \n        (P := Star (SH.starred (SH.SE.Inj (stateType:=stateType)) pures SH.SE.Emp)\n                   (SH.starred (SH.SE.Const (stateType:=stateType)) other SH.SE.Emp)) \n        (Q := Star (SH.starred (SH.SE.Inj (stateType:=stateType)) pures0 SH.SE.Emp)\n                   (SH.starred (SH.SE.Const (stateType:=stateType)) other0 SH.SE.Emp)) in H3;\n        eauto using typeof_env_WellTyped_env, typeof_funcs_WellTyped_funcs, U.Subst_empty_WellTyped.\n      { clear H4.\n        do 2 rewrite impuresD_forget_impuresInstantiate in H3 by eassumption. \n        rewrite SH.impuresD_Empty with (i := MM.empty _) in H3.\n        rewrite starred_ext with (ls := order_impures impures0) in H3. 2: intro; apply Func_forget_exprInstantiate; auto.\n        rewrite SH.impuresD_Equiv with (b := impures) in H3.\n        rewrite H3. repeat rewrite heq_star_assoc. apply himp_star_frame.\n        rewrite <- order_impures_D. reflexivity.\n        rewrite heq_star_emp_l. reflexivity.\n\n        red.\n        symmetry. erewrite Equiv_map. reflexivity. intros. eapply Ordering.sort_permutation.\n        apply FM.empty_1. }\n      { eapply U.Subst_equations_WellTyped; auto. }\n      { rewrite SH.WellTyped_sheap_eq in H1. think. simpl in *.\n        eapply order_impures_WellTyped in H1.\n        eapply allb_impl; try eassumption. simpl; intros.\n        destruct (nth_error (typeof_preds preds) (snd x)); auto.\n        rewrite all2_map_1. erewrite all2_impl. 2: eauto. auto.        \n        simpl; intros.\n        rewrite <- U.exprInstantiate_WellTyped; auto using U.Subst_equations_WellTyped. }\n      { apply WellTyped_empty. }\n      { apply map_sort_WellTyped. rewrite SH.WellTyped_sheap_eq in H0. think. simpl in *. auto. }\n      { do 2 (rewrite SH.sheapD_def in H4; simpl in H4). \n        do 2 rewrite impuresD_forget_impuresInstantiate by eassumption. eapply H4. }\n    Qed.\n\n  End env.\n\nEnd Make.\n", "meta": {"author": "csgordon", "repo": "bedrock", "sha": "debab1b6e491b7c5e83bd3b1fe5d0e4c4e728d12", "save_path": "github-repos/coq/csgordon-bedrock", "path": "github-repos/coq/csgordon-bedrock/bedrock-debab1b6e491b7c5e83bd3b1fe5d0e4c4e728d12/src/SepCancel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2519957686536129}}
{"text": "(* Distributed under the terms of the MIT license. *)\nFrom Coq Require Import ssreflect CRelationClasses.\nFrom MetaCoq.Utils Require Import utils.\nFrom MetaCoq.Common Require Import config Universes uGraph.\nFrom MetaCoq.PCUIC Require Import PCUICAst PCUICAstUtils PCUICInduction PCUICOnFreeVars\n     PCUICLiftSubst PCUICEquality PCUICUnivSubst\n     PCUICCases PCUICCumulativity PCUICTyping PCUICReduction PCUICWeakeningEnv PCUICWeakeningEnvTyp\n     PCUICClosed PCUICPosition PCUICGuardCondition PCUICUnivSubstitutionConv.\n\nRequire Import Equations.Prop.DepElim.\nFrom Equations Require Import Equations.\n\n(** * Universe Substitution lemmas for typing derivations. *)\n\nLocal Set Keyed Unification.\n\nSet Default Goal Selector \"!\".\n\nLocal Ltac aa := rdest; eauto with univ_subst.\n\nSection SubstIdentity.\n  Context `{cf:checker_flags}.\n\nLemma compare_universe_subst_instance pb {Σ : global_env_ext} univs u :\n  valid_constraints (global_ext_constraints (Σ.1, univs)) (subst_instance_cstrs u Σ) ->\n  RelationClasses.subrelation (compare_universe pb Σ)\n    (fun x y : Universe.t =>\n    compare_universe pb (global_ext_constraints (Σ.1, univs)) (subst_instance_univ u x)\n      (subst_instance_univ u y)).\nProof using Type.\n  intros v.\n  destruct pb; cbn.\n  - now apply eq_universe_subst_instance.\n  - now apply leq_universe_subst_instance.\nQed.\n\nLemma cumulSpec_subst_instance (Σ : global_env_ext) Γ u A B pb univs :\n  valid_constraints (global_ext_constraints (Σ.1, univs))\n                    (subst_instance_cstrs u Σ) ->\n  Σ ;;; Γ ⊢ A ≤s[pb] B ->\n  (Σ.1,univs) ;;; subst_instance u Γ ⊢ subst_instance u A ≤s[pb] subst_instance u B.\nProof.\n  intros e H. unfold cumulSpec.\n  revert pb Γ A B H e.\n  apply: cumulSpec0_ind_all; intros; cbn; try solve [econstructor; intuition eauto].\n  - rewrite subst_instance_subst. solve [econstructor].\n  - rewrite subst_instance_subst. solve [econstructor].\n  - rewrite subst_instance_lift. eapply cumul_rel.\n    unfold subst_instance.\n    unfold option_map in *. destruct (nth_error Γ) eqn:E; inversion H.\n    unfold map_context. rewrite nth_error_map E. cbn.\n    rewrite map_decl_body. destruct c. cbn in *. subst.\n    reflexivity.\n  - rewrite subst_instance_mkApps. cbn.\n    rewrite iota_red_subst_instance.\n    change (bcontext br) with (bcotext (map_branch (subst_instance u) br)).\n    eapply cumul_iota; eauto with pcuic.\n    * rewrite nth_error_map H //.\n    * simpl. now len.\n  - rewrite !subst_instance_mkApps. cbn.\n    eapply cumul_fix.\n    + unfold unfold_fix in *. destruct (nth_error mfix idx) eqn:E.\n      * inversion H.\n        rewrite nth_error_map E. cbn.\n        destruct d. cbn in *. cbn in *; try congruence.\n        f_equal. f_equal.\n        now rewrite subst_instance_subst fix_subst_instance_subst.\n      * inversion H.\n    + unfold is_constructor in *.\n      destruct (nth_error args narg) eqn:E; inversion H0; clear H0.\n      rewrite nth_error_map E. cbn.\n     eapply isConstruct_app_subst_instance.\n  - rewrite !subst_instance_mkApps.\n    unfold unfold_cofix in *. destruct (nth_error mfix idx) eqn:E.\n    + inversion H.\n    eapply cumul_cofix_case.  fold subst_instance_constr.\n    unfold unfold_cofix.\n    rewrite nth_error_map E. cbn.\n    rewrite subst_instance_subst.\n    now rewrite cofix_subst_instance_subst.\n    + cbn.\n    inversion H.\n  - unfold unfold_cofix in *.\n    destruct nth_error eqn:E; inversion H.\n    rewrite !subst_instance_mkApps.\n    eapply cumul_cofix_proj. fold subst_instance.\n    unfold unfold_cofix.\n    rewrite nth_error_map. destruct nth_error; cbn.\n     1: rewrite subst_instance_subst cofix_subst_instance_subst.\n    all: now inversion E.\n  - rewrite subst_instance_two. solve [econstructor; eauto].\n  - rewrite !subst_instance_mkApps.\n    eapply cumul_proj. now rewrite nth_error_map H.\n  - eapply cumul_Trans; intuition.\n    * rewrite on_free_vars_ctx_subst_instance; eauto.\n    * rewrite on_free_vars_subst_instance. unfold is_open_term.\n      replace #|Γ@[u]| with #|Γ|; eauto. rewrite map_length; eauto.\n  - eapply cumul_Evar. eapply All2_map.\n    eapply All2_impl. 1: tea. cbn; intros. eapply X0.2; eauto.\n  - eapply cumul_Case; try solve [intuition; eauto].\n    * destruct X as [X [Xuni [Xcont [_ Xret]]]]. repeat split; eauto; cbn.\n      + apply All2_map. eapply All2_impl. 1: tea. cbn; intros. eapply X3.2; eauto.\n      + apply precompose_subst_instance. eapply R_universe_instance_impl; eauto.\n        now apply eq_universe_subst_instance.\n      + rewrite subst_instance_app inst_case_predicate_context_subst_instance in Xret.\n        eapply Xret; eauto.\n    * eapply All2_map. eapply All2_impl. 1: tea. cbn; intros.\n      repeat split; eauto; intuition.\n      rewrite subst_instance_app inst_case_branch_context_subst_instance in X1; eauto.\n  - eapply cumul_Fix. apply All2_map. eapply All2_impl. 1: tea.\n    cbn; intros; intuition.\n    rewrite subst_instance_app fix_context_subst_instance in X0; eauto.\n  - eapply cumul_CoFix. apply All2_map. eapply All2_impl. 1: tea.\n    cbn; intros; intuition.\n    rewrite subst_instance_app fix_context_subst_instance in X0; eauto.\n - repeat rewrite subst_instance_mkApps. eapply cumul_Ind.\n    * apply precompose_subst_instance_global.\n      rewrite map_length. eapply R_global_instance_impl_same_napp; try eapply H; eauto.\n      { now apply eq_universe_subst_instance. }\n      { now apply compare_universe_subst_instance. }\n    * eapply All2_map. eapply All2_impl. 1: tea. cbn; intros.\n      eapply X0.2; eauto.\n - repeat rewrite subst_instance_mkApps. eapply cumul_Construct.\n    * apply precompose_subst_instance_global. cbn.\n      rewrite map_length. eapply R_global_instance_impl_same_napp; try eapply H; eauto.\n      { now apply eq_universe_subst_instance. }\n      { now apply compare_universe_subst_instance. }\n    * eapply All2_map. eapply All2_impl. 1: tea. cbn; intros.\n      eapply X0.2; eauto.\n  - eapply cumul_Sort. now apply compare_universe_subst_instance.\n  - eapply cumul_Const. apply precompose_subst_instance.\n    eapply R_universe_instance_impl; eauto.\n    now apply compare_universe_subst_instance.\nDefined.\n\nLemma convSpec_subst_instance (Σ : global_env_ext) Γ u A B univs :\nvalid_constraints (global_ext_constraints (Σ.1, univs))\n                  (subst_instance_cstrs u Σ) ->\n  Σ ;;; Γ |- A =s B ->\n  (Σ.1,univs) ;;; subst_instance u Γ |- subst_instance u A =s subst_instance u B.\nProof using Type.\n  apply cumulSpec_subst_instance.\nQed.\n\nLemma conv_decls_subst_instance (Σ : global_env_ext) {Γ Γ'} u univs d d' :\n  valid_constraints (global_ext_constraints (Σ.1, univs))\n    (subst_instance_cstrs u Σ) ->\n  conv_decls cumulSpec0 Σ Γ Γ' d d' ->\n  conv_decls cumulSpec0 (Σ.1, univs) (subst_instance u Γ) (subst_instance u Γ')\n    (subst_instance u d) (subst_instance u d').\nProof using Type.\n  intros valid Hd; depelim Hd; constructor; tas;\n    eapply convSpec_subst_instance; tea.\nQed.\n\nLemma cumul_decls_subst_instance (Σ : global_env_ext) {Γ Γ'} u univs d d' :\n  valid_constraints (global_ext_constraints (Σ.1, univs))\n    (subst_instance_cstrs u Σ) ->\n  cumul_decls cumulSpec0 Σ Γ Γ' d d' ->\n  cumul_decls cumulSpec0 (Σ.1, univs) (subst_instance u Γ) (subst_instance u Γ')\n    (subst_instance u d) (subst_instance u d').\nProof using Type.\n  intros valid Hd; depelim Hd; constructor; tas;\n    (eapply convSpec_subst_instance || eapply cumulSpec_subst_instance); tea.\nQed.\n\nLemma conv_ctx_subst_instance (Σ : global_env_ext) {Γ Γ'} u univs :\n  valid_constraints (global_ext_constraints (Σ.1, univs)) (subst_instance_cstrs u Σ) ->\n  conv_context cumulSpec0 Σ Γ Γ' ->\n  conv_context cumulSpec0 (Σ.1, univs) (subst_instance u Γ) (subst_instance u Γ').\nProof using Type.\n  intros valid.\n  intros; eapply All2_fold_map, All2_fold_impl; tea => ? ? d d'.\n  now eapply conv_decls_subst_instance.\nQed.\n\nLemma subst_instance_ws_cumul_ctx_pb_rel (Σ : global_env_ext) {Γ Γ'} u univs :\n  valid_constraints (global_ext_constraints (Σ.1, univs)) (subst_instance_cstrs u Σ) ->\n  cumul_context cumulSpec0 Σ Γ Γ' ->\n  cumul_context cumulSpec0 (Σ.1, univs) (subst_instance u Γ) (subst_instance u Γ').\nProof using Type.\n  intros valid.\n  intros; eapply All2_fold_map, All2_fold_impl; tea => ? ? d d'.\n  now eapply cumul_decls_subst_instance.\nQed.\n\nHint Resolve subst_instance_cstrs_two\n     satisfies_equal_sets satisfies_subsets : univ_subst.\nHint Resolve monomorphic_global_constraint monomorphic_global_constraint_ext : univ_subst.\nHint Unfold CS.For_all : univ_subst.\nHint Resolve consistent_ext_trans : univ_subst.\nHint Resolve consistent_instance_valid_constraints : univ_subst.\nHint Rewrite subst_instance_extended_subst : substu.\nHint Rewrite expand_lets_subst_instance : substu.\nHint Rewrite subst_instance_subst_context subst_instance_lift_context\n  subst_instance_lift subst_instance_mkApps\n  subst_instance_subst\n  subst_instance_it_mkProd_or_LetIn\n  subst_instance_it_mkLambda_or_LetIn\n  subst_instance_inds\n  : substu.\nLtac substu := autorewrite with substu.\nHint Rewrite subst_instance_expand_lets_ctx : substu.\nHint Resolve subst_instance_wf_predicate\n  subst_instance_wf_branch subst_instance_wf_branches : pcuic.\nHint Resolve All_local_env_over_subst_instance : univ_subst.\nHint Resolve declared_inductive_wf_ext_wk declared_inductive_wf_global_ext : pcuic.\n\n\nLemma typing_subst_instance :\n  env_prop (fun Σ Γ t T => forall u univs,\n                wf_ext_wk Σ ->\n                consistent_instance_ext (Σ.1, univs) Σ.2 u ->\n                (Σ.1,univs) ;;; subst_instance u Γ\n                |- subst_instance u t : subst_instance u T)\n          (fun Σ Γ => forall u univs,\n          wf_ext_wk Σ ->\n          consistent_instance_ext (Σ.1, univs) Σ.2 u ->\n          wf_local(Σ.1,univs) (subst_instance u Γ)).\nProof using Type.\n  apply typing_ind_env; intros Σ wfΣ Γ wfΓ; cbn  -[Universe.make] in *.\n  - rewrite /subst_instance /=.\n    induction 1.\n    + constructor.\n    + simpl. constructor; auto.\n      eapply infer_typing_sort_impl; tea.\n      intros Hty. eapply Hs; auto.\n    + simpl. constructor; auto.\n      ++ eapply infer_typing_sort_impl; tea.\n         intros Hty. eapply Hs; auto.\n      ++ apply Hc; auto.\n\n  - intros n decl eq X u univs wfΣ' H. rewrite subst_instance_lift.\n    rewrite map_decl_type. econstructor; aa.\n    unfold subst_instance, map_context.\n    now rewrite nth_error_map eq.\n  - intros l X Hl u univs wfΣ' H.\n    rewrite subst_instance_univ_super.\n    + econstructor.\n      * aa.\n      * now apply wf_universe_subst_instance.\n  - intros n t0 b s1 s2 X X0 X1 X2 X3 u univs wfΣ' H.\n    rewrite product_subst_instance; aa. econstructor.\n    + eapply X1; eauto.\n    + eapply X3; eauto.\n  - intros n t0 b s1 bty X X0 X1 X2 X3 u univs wfΣ' H.\n    econstructor.\n    + eapply X1; aa.\n    + eapply X3; aa.\n  - intros n b b_ty b' s1 b'_ty X X0 X1 X2 X3 X4 X5 u univs wfΣ' H.\n    econstructor; eauto. eapply X5; aa.\n  - intros t0 na A B s u X X0 X1 X2 X3 X4 X5 u0 univs wfΣ' H.\n    rewrite subst_instance_subst. cbn. econstructor.\n    + eapply X1; eauto.\n    + eapply X3; eauto.\n    + eapply X5; eauto.\n  - intros. rewrite subst_instance_two. econstructor; [aa|aa|].\n    clear X X0; cbn in *.\n    eapply consistent_ext_trans; eauto.\n  - intros. rewrite subst_instance_two. econstructor; [aa|aa|].\n    clear X X0; cbn in *.\n    eapply consistent_ext_trans; eauto.\n  - intros. eapply meta_conv. 1: econstructor; aa.\n    clear.\n    unfold type_of_constructor; cbn.\n    rewrite subst_instance_subst. f_equal.\n    + unfold inds. induction #|ind_bodies mdecl|. 1: reflexivity.\n      cbn. now rewrite IHn.\n    + symmetry; apply subst_instance_two.\n\n  - intros ci p c brs args u mdecl idecl isdecl hΣ hΓ indnp eqpctx wfp cup\n      wfpctx pty Hpty Hcpc kelim\n      IHctxi Hc IHc notCoFinite wfbrs hbrs i univs wfext cu.\n    rewrite subst_instance_mkApps subst_instance_it_mkLambda_or_LetIn map_app.\n    cbn.\n    change (subst_instance i (preturn p)) with (preturn (subst_instance i p)).\n    change (subst_instance i (pcontext p)) with (pcontext (subst_instance i p)).\n    change (map_predicate _ _ _ _ _) with (subst_instance i p).\n    rewrite subst_instance_case_predicate_context.\n    eapply type_Case with (p:=subst_instance i p)\n                          (ps:=subst_instance_univ i u); eauto with pcuic.\n    3,4: constructor; eauto with pcuic.\n    + rewrite -subst_instance_case_predicate_context - !subst_instance_app_ctx.\n      eapply Hpty; eauto.\n    + eapply IHc in cu => //.\n      now rewrite subst_instance_mkApps map_app in cu.\n    + simpl. eapply consistent_ext_trans; tea.\n    + now rewrite -subst_instance_case_predicate_context -subst_instance_app_ctx.\n    + cbn in *.\n      eapply is_allowed_elimination_subst_instance; aa.\n    + move: IHctxi. simpl.\n      rewrite -subst_instance_app.\n      rewrite -subst_instance_two_context.\n      rewrite -[List.rev (subst_instance i _)]map_rev.\n      clear -wfext cu. induction 1; try destruct t0; cbn; constructor; simpl; eauto.\n      all:now rewrite -(subst_instance_subst_telescope i [_]).\n    + rewrite -{1}(map_id (ind_ctors idecl)).\n      eapply All2i_map. eapply All2i_impl; eauto.\n      cbn -[case_branch_type case_branch_context subst_instance].\n      intros k cdecl br (hctx & hcbctx & (hbod & ihbod) & hbty & ihbty).\n      rewrite case_branch_type_fst.\n      rewrite - !subst_instance_case_branch_context - !subst_instance_app_ctx.\n      rewrite -subst_instance_case_predicate_context subst_instance_case_branch_type.\n      repeat split; auto.\n      * specialize (ihbod i univs wfext cu).\n        cbn. eapply ihbod.\n      * specialize (ihbty i univs wfext cu).\n        cbn. eapply ihbty.\n  - intros p c u mdecl idecl cdecl pdecl isdecl args X X0 X1 X2 H u0 univs wfΣ' H0.\n    rewrite subst_instance_subst. cbn.\n    rewrite !subst_instance_two.\n    rewrite {4}/subst_instance /subst_instance_list /=.\n    rewrite map_rev.\n    econstructor; eauto. 2:now rewrite map_length.\n    eapply X2 in H0; tas. rewrite subst_instance_mkApps in H0.\n    eassumption.\n\n  - intros mfix n decl H H0 H1 X X0 wffix u univs wfΣ'.\n    rewrite (map_dtype _ (subst_instance u)). econstructor.\n    + specialize (H1 u univs wfΣ' H2).\n      rewrite subst_instance_app in H1.\n      now eapply wf_local_app_inv in H1 as [].\n    + now eapply fix_guard_subst_instance.\n    + rewrite nth_error_map H0. reflexivity.\n    + apply All_map, (All_impl X); simpl; intuition auto.\n      eapply infer_typing_sort_impl with (tu := X1).\n      intros [_ Hs]; now apply Hs.\n    + eapply All_map, All_impl; tea.\n      intros x [X1 X3].\n      specialize (X3 u univs wfΣ' H2).\n      rewrite (map_dbody (subst_instance u)) in X3.\n      rewrite subst_instance_lift in X3.\n      rewrite fix_context_length ?map_length in X0, X1, X3.\n      rewrite (map_dtype _ (subst_instance u) x) in X3.\n      rewrite subst_instance_app in X3.\n      rewrite <- (fix_context_subst_instance u mfix).\n      now len.\n    + red; rewrite <- wffix.\n      unfold wf_fixpoint, wf_fixpoint_gen.\n      f_equal.\n      { rewrite forallb_map. solve_all. cbn.\n        destruct (dbody x) => //. }\n      rewrite map_map_compose.\n      now rewrite subst_instance_check_one_fix.\n\n      - intros mfix n decl H H0 H1 X X0 wffix u univs wfΣ'.\n      rewrite (map_dtype _ (subst_instance u)). econstructor.\n      + specialize (H1 u univs wfΣ' H2).\n        rewrite subst_instance_app in H1.\n        now eapply wf_local_app_inv in H1 as [].\n      + now eapply cofix_guard_subst_instance.\n      + rewrite nth_error_map H0. reflexivity.\n      + apply All_map, (All_impl X); simpl; intuition auto.\n        eapply infer_typing_sort_impl with (tu := X1).\n        intros [_ Hs]; now apply Hs.\n      + eapply All_map, All_impl; tea.\n        intros x [X1 X3].\n        specialize (X3 u univs wfΣ' H2).\n        rewrite (map_dbody (subst_instance u)) in X3.\n        rewrite subst_instance_lift in X3.\n        rewrite fix_context_length ?map_length in X0, X1, X3.\n        rewrite (map_dtype _ (subst_instance u) x) in X3.\n        rewrite subst_instance_app in X3.\n        rewrite <- (fix_context_subst_instance u mfix).\n        now len.\n      + red; rewrite <- wffix.\n        unfold wf_cofixpoint, wf_cofixpoint_gen.\n        rewrite map_map_compose.\n        now rewrite subst_instance_check_one_cofix.\n\n  - econstructor; eauto.\n\n  - intros t0 A B X X0 X1 X2 X3 X4 cum u univs wfΣ' H.\n    econstructor.\n    + eapply X2; aa.\n    + eapply X4; aa.\n    + eapply cumulSpec_subst_instance; aa.\nQed.\n\nLemma typing_subst_instance' Σ φ Γ t T u univs :\n  wf_ext_wk (Σ, univs) ->\n  (Σ, univs) ;;; Γ |- t : T ->\n  consistent_instance_ext (Σ, φ) univs u ->\n  (Σ, φ) ;;; subst_instance u Γ\n            |- subst_instance u t : subst_instance u T.\nProof using Type.\n  intros X X0 X1.\n  eapply (typing_subst_instance (Σ, univs)); tas. apply X.\nQed.\n\nLemma typing_subst_instance_wf_local Σ φ Γ u univs :\n  wf_ext_wk (Σ, univs) ->\n  wf_local (Σ, univs) Γ ->\n  consistent_instance_ext (Σ, φ) univs u ->\n  wf_local (Σ, φ) (subst_instance u Γ).\nProof using Type.\n  intros X X0 X1.\n  eapply (env_prop_wf_local typing_subst_instance (Σ, univs)); tas. 1: apply X.\nQed.\n\nLemma typing_subst_instance'' Σ φ Γ t T u univs :\n  wf_ext_wk (Σ, univs) ->\n  (Σ, univs) ;;; Γ |- t : T ->\n  consistent_instance_ext (Σ, φ) univs u ->\n  (Σ, φ) ;;; subst_instance u Γ\n            |- subst_instance u t : subst_instance u T.\nProof using Type.\n  intros X X0 X1.\n  eapply (typing_subst_instance (Σ, univs)); tas. 1: apply X.\nQed.\n\nLemma typing_subst_instance_ctx (Σ : global_env_ext) Γ t T ctx u :\n  wf Σ.1 ->\n  on_udecl_prop Σ (Polymorphic_ctx ctx) ->\n  (Σ.1, Polymorphic_ctx ctx) ;;; Γ |- t : T ->\n  consistent_instance_ext Σ (Polymorphic_ctx ctx) u ->\n  Σ ;;; subst_instance u Γ\n            |- subst_instance u t : subst_instance u T.\nProof using Type.\n  destruct Σ as [Σ φ]. intros X X0 X1.\n  eapply typing_subst_instance''; tea.\n  split; tas.\nQed.\n\nLemma typing_subst_instance_decl Σ Γ t T c decl u :\n  wf Σ.1 ->\n  lookup_env Σ.1 c = Some decl ->\n  (Σ.1, universes_decl_of_decl decl) ;;; Γ |- t : T ->\n  consistent_instance_ext Σ (universes_decl_of_decl decl) u ->\n  Σ ;;; subst_instance u Γ\n            |- subst_instance u t : subst_instance u T.\nProof using Type.\n  destruct Σ as [Σ φ]. intros X X0 X1 X2.\n  eapply typing_subst_instance''; tea.\n  split; tas.\n  eapply weaken_lookup_on_global_env'; tea.\nQed.\n\n\n\n\nLemma wf_local_instantiate_poly {Σ ctx Γ u} :\n  wf_ext (Σ.1, Polymorphic_ctx ctx) ->\n  consistent_instance_ext Σ (Polymorphic_ctx ctx) u ->\n  wf_local (Σ.1, Polymorphic_ctx ctx) Γ ->\n  wf_local Σ (subst_instance u Γ).\nProof using Type.\n  intros wfΣ Huniv wf.\n  epose proof (type_Sort _ _ Universes.Universe.lProp wf) as ty. forward ty.\n  - now simpl.\n  - eapply typing_subst_instance_ctx in ty;\n    cbn; eauto using typing_wf_local.\n    * apply wfΣ.\n    * destruct wfΣ. now eapply on_udecl_on_udecl_prop.\nQed.\n\nLemma wf_local_instantiate {Σ} {decl : global_decl} {Γ u c} :\n  wf Σ.1 ->\n  lookup_env Σ.1 c = Some decl ->\n  consistent_instance_ext Σ (universes_decl_of_decl decl) u ->\n  wf_local (Σ.1, universes_decl_of_decl decl) Γ ->\n  wf_local Σ (subst_instance u Γ).\nProof using Type.\n  intros wfΣ Hdecl Huniv wf.\n  epose proof (type_Sort _ _ Universes.Universe.lProp wf) as ty. forward ty.\n  - now simpl.\n  - eapply typing_subst_instance_decl in ty;\n    cbn; eauto using typing_wf_local.\nQed.\n\nLemma isType_subst_instance_decl Σ Γ T c decl u :\n  wf Σ.1 ->\n  lookup_env Σ.1 c = Some decl ->\n  isType (Σ.1, universes_decl_of_decl decl) Γ T ->\n  consistent_instance_ext Σ (universes_decl_of_decl decl) u ->\n  isType Σ (subst_instance u Γ) (subst_instance u T).\nProof using Type.\n  intros wfΣ look isty cu.\n  eapply infer_typing_sort_impl with (tu := isty).\n  intros Hs; now eapply (typing_subst_instance_decl _ _ _ (tSort _)).\nQed.\n\nLemma isArity_subst_instance u T :\n  isArity T ->\n  isArity (subst_instance u T).\nProof using Type.\n  induction T; cbn; intros; tauto.\nQed.\n\nLemma wf_local_subst_instance Σ Γ ext u :\n  wf_global_ext Σ.1 ext ->\n  consistent_instance_ext Σ ext u ->\n  wf_local (Σ.1, ext) Γ ->\n  wf_local Σ (subst_instance u Γ).\nProof using Type.\n  destruct Σ as [Σ φ]. intros X X0 X1. simpl in *.\n  induction X1; cbn; constructor; auto.\n  1,2: eapply infer_typing_sort_impl with (tu := t0); intros Hs.\n  3: rename t1 into Hs.\n  all: eapply typing_subst_instance'' in Hs; eauto; apply X.\nQed.\n\nLemma wf_local_subst_instance_decl Σ Γ c decl u :\n  wf Σ.1 ->\n  lookup_env Σ.1 c = Some decl ->\n  wf_local (Σ.1, universes_decl_of_decl decl) Γ ->\n  consistent_instance_ext Σ (universes_decl_of_decl decl) u ->\n  wf_local Σ (subst_instance u Γ).\nProof using Type.\n  destruct Σ as [Σ φ]. intros X X0 X1 X2.\n  induction X1; cbn; constructor; auto.\n  1,2: eapply infer_typing_sort_impl with (tu := t0); intros Hs.\n  3: rename t1 into Hs.\n  all: eapply typing_subst_instance_decl in Hs; eauto; apply X.\nQed.\n\n  Lemma subst_instance_ind_sort_id Σ mdecl ind idecl :\n    wf Σ ->\n    declared_inductive Σ ind mdecl idecl ->\n    let u := abstract_instance (ind_universes mdecl) in\n    subst_instance_univ u (ind_sort idecl) = ind_sort idecl.\n  Proof using Type.\n    intros wfΣ decli u.\n    pose proof (on_declared_inductive decli) as [onmind oib].\n    pose proof (onArity oib) as ona.\n    rewrite (oib.(ind_arity_eq)) in ona.\n    red in ona. destruct ona.\n    eapply typed_subst_abstract_instance in t.\n    2:split; simpl; auto.\n    - rewrite !subst_instance_it_mkProd_or_LetIn in t.\n      eapply (f_equal (destArity [])) in t.\n      rewrite !destArity_it_mkProd_or_LetIn in t. simpl in t. noconf t.\n      simpl in H; noconf H. apply H0.\n    - destruct decli as [declm _].\n      eapply declared_inductive_wf_global_ext in declm; auto.\n      destruct declm. apply o.\n  Qed.\n\n  Lemma subst_instance_ind_type_id Σ mdecl ind idecl :\n    wf Σ ->\n    declared_inductive Σ ind mdecl idecl ->\n    let u := abstract_instance (ind_universes mdecl) in\n    subst_instance u (ind_type idecl) = ind_type idecl.\n  Proof using Type.\n    intros wfΣ decli u.\n    pose proof (on_declared_inductive decli) as [_ oib].\n    pose proof (onArity oib) as ona.\n    rewrite (oib.(ind_arity_eq)) in ona |- *.\n    red in ona. destruct ona.\n    eapply typed_subst_abstract_instance in t; eauto.\n    destruct decli as [declm _].\n    eapply declared_inductive_wf_global_ext in declm; auto.\n  Qed.\n\n  Lemma isType_subst_instance_id Σ Γ T :\n    wf_ext_wk Σ ->\n    let u := abstract_instance Σ.2 in\n    isType Σ Γ T -> subst_instance u T = T.\n  Proof using Type.\n    intros wf_ext u isT.\n    destruct isT. eapply typed_subst_abstract_instance in t; auto.\n  Qed.\n\nEnd SubstIdentity.\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/Typing/PCUICUnivSubstitutionTyp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.25199576259199097}}
{"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 ssrnat eqtype seq.\nRequire Import ZArith_ext machine_int.\nImport MachineInt.\nRequire Import mips_seplog.\n\nLocal Close Scope positive_scope.\n\nLocal Open Scope heap_scope.\nImport expr_m.\nLocal Open Scope mips_expr_scope.\nLocal Open Scope mips_cmd_scope.\nImport assert_m.\nLocal Open Scope mips_assert_scope.\nLocal Open Scope mips_hoare_scope.\n\n(** * Frame rule *)\n\nDefinition modified_regs0 (c : cmd0) : seq store.var :=\n  match c with\n    | nop => nil\n    | add rd _ _ => rd :: nil\n    | addi rt _ _ => rt :: nil\n    | addiu rt _ _ => rt :: nil\n    | addu rd _ _ => rd :: nil\n    | cmd_and rd _ _ => rd :: nil\n    | andi rt _ _ => rt :: nil\n    | lw rt _ _  => rt :: nil\n    | lwxs rt _ _ => rt :: nil\n    | maddu _ _ => nil\n    | mflo rd => rd :: nil\n    | movn rd _ _ => rd :: nil\n    | movz rd _ _ => rd :: nil\n    | mfhi rd => rd :: nil\n    | mflhxu rd => rd :: nil\n    | msubu _ _  => nil\n    | mthi _ => nil\n    | mtlo _ => nil\n    | multu _ _  => nil\n    | nor rd _ _ => rd :: nil\n    | cmd_or rd _ _ => rd :: nil\n    | sll rx _ _ => rx :: nil\n    | sllv rd _ _ => rd :: nil\n    | sra rd _ _ => rd :: nil\n    | srl rd _ _ => rd :: nil\n    | srlv rd _ _ => rd :: nil\n    | sltu rd _ _ => rd :: nil\n    | sw _ _ _ => nil\n    | subu rd _ _ => rd :: nil\n    | xor rd _ _ => rd :: nil\n    | xori rt _ _ => rt :: nil\n  end.\n\nFixpoint modified_regs (c : @while.cmd cmd0 expr_b) : seq store.var :=\n  match c with\n    | while.cmd_cmd0 c0 => modified_regs0 c0\n    | while.while _ c => modified_regs c\n    | c1 ; c2 => modified_regs c1 ++ modified_regs c2\n    | while.ifte t c1 c2 => modified_regs c1 ++ modified_regs c2\n  end.\n\nLemma inde_seq R c d : inde (modified_regs (c ; d)) R ->\n  inde (modified_regs c) R /\\ inde (modified_regs d) R.\nProof.\nmove=> H; split => s h x v H'; split => H''.\n- rewrite -H //=; apply List.in_or_app; by left.\n- rewrite (H _ _ x v) //=; apply List.in_or_app; by left.\n- rewrite -H //=; apply List.in_or_app; by right.\n- rewrite (H _ _ x v) //=; apply List.in_or_app; by right.\nQed.\n\nLemma inde_ifte R t c d : inde (modified_regs (while.ifte t c d)) R ->\n  inde (modified_regs c) R /\\ inde (modified_regs d) R.\nProof.\nmove=> H; split => s h x v H'; split => H''.\n- rewrite -H //=; apply: List.in_or_app; by left.\n- rewrite (H _ _ x v) //=; apply: List.in_or_app; by left.\n- rewrite -H //=; apply List.in_or_app; by right.\n- rewrite (H _ _ x v) //=; apply List.in_or_app; by right.\nQed.\n\nDefinition modifies_mult0 (c : cmd0) :=\n  match c with\n    | nop => false\n    | add _ _ _ => false\n    | addi _ _ _ => false\n    | addiu _ _ _ => false\n    | addu _ _ _ => false\n    | cmd_and _ _ _ => false\n    | andi _ _ _ => false\n    | lw _ _ _ => false\n    | lwxs _ _ _ => false\n    | maddu _ _ => true\n    | mfhi _ => false\n    | mflhxu _ => true\n    | mflo _ => false\n    | movn _ _ _ => false\n    | movz _ _ _ => false\n    | msubu _ _ => true\n    | mtlo _ => true\n    | mthi _ => true\n    | multu _ _ => true\n    | nor _ _ _ => false\n    | cmd_or _ _ _ => false\n    | sll _ _ _ => false\n    | sllv _ _ _ => false\n    | sltu _ _ _ => false\n    | sra _ _ _ => false\n    | srl _ _ _ => false\n    | srlv _ _ _ => false\n    | subu _ _ _ => false\n    | sw _ _ _ => false\n    | xor _ _ _ => false\n    | xori _ _ _ => false\n  end.\n\nFixpoint modifies_mult (c : @while.cmd cmd0 expr_b) : bool :=\n  match c with\n    | while.cmd_cmd0 c => modifies_mult0 c\n    | while.while _ c' => modifies_mult c'\n    | c1 ; c2 => modifies_mult c1 || modifies_mult c2\n    | while.ifte t c1 c2 => modifies_mult c1 || modifies_mult c2\n  end.\n\n(** an assert that is independent of the execution of a command modifying the multiplier *)\nDefinition inde_cmd_mult c (P : assert) := modifies_mult c -> inde_mult P.\n\nLemma inde_cmd_mult_TT : forall l, inde_cmd_mult l TT. Proof. by []. Qed.\n\nLemma inde_cmd_mult_seq R c d : inde_cmd_mult (c; d) R ->\n  inde_cmd_mult c R /\\ inde_cmd_mult d R.\nProof.\nmove=> H; split => H' s h m m'; split => H''.\n- by rewrite -(H _ _ _ m) //= H'.\n- by rewrite -(H _ _ _ m') //= H'.\n- by rewrite -(H _ _ _ m) //= H' orbC.\n- by rewrite -(H _ _ _ m') //= H' orbC.\nQed.\n\nLemma inde_cmd_mult_ifte R t c d : inde_cmd_mult (while.ifte t c d) R ->\n  inde_cmd_mult c R /\\ inde_cmd_mult d R.\nProof.\nmove=> H; split => H' s h m m'; split => H''.\n- by rewrite -(H _ _ _ m) //= H'.\n- by rewrite -(H _ _ _ m') //= H'.\n- by rewrite -(H _ _ _ m) //= H' orbC.\n- by rewrite -(H _ _ _ m') //= H' orbC.\nQed.\n\nLemma frame_rule0 (P Q : assert) (c : cmd0) : {{[ P ]}} c {{[ Q ]}} ->\n  forall (R : assert), inde (modified_regs c) R ->\n    inde_cmd_mult c R -> {{ P ** R }} c {{ Q ** R }}.\nProof.\nelim; clear P Q c.\n- (* nop *) move=> P R H1 H2; by do 2 constructor.\n- (* add *) move=> Q rs rt rd R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_add rd rs rt (Q ** R))); last by do 2 constructor.\n  move=> s h [h1 [h2 [H3 [H4 [ [H5 H7] H6] ] ] ] ].\n  split => //.\n  exists h1, h2; repeat (split => //).\n  by apply inde_upd_store.\n- (* addi *)\n  move=> Q rt rs imm R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_addi rt rs imm (Q ** R))); last by do 2 constructor.\n  move=> s h [h1 [h2 [ H3 [H4 [ [H5 H7] H6] ] ] ] ].\n  split => //.\n  exists h1, h2; repeat (split => //).\n  by apply inde_upd_store.\n- (* addiu *) move=> Q rt rs imm R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_addiu rt rs imm (Q ** R))); last by do 2 constructor.\n  move=> s h [h1 [h2 [ H3 [H4 [ H5 H6] ] ] ] ].\n  exists h1, h2; repeat (split => //).\n  by apply inde_upd_store.\n- (* addu *) move=> Q rs rt rd R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_addu rd rs rt (Q ** R))); last by do 2 constructor.\n  move=> s h [h1 [h2 [ H3 [H4 [H5 H6] ] ] ] ].\n  exists h1, h2; repeat (split => //).\n  by apply inde_upd_store.\n- (* cmd_and *) move=> P rd rs rt R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_and rd rs rt (P ** R))); last by do 2 constructor.\n  move=> s h [h1 [h2 [ H3 [H4 [H5 H6] ] ] ] ].\n  exists h1, h2; repeat (split => //).\n  by apply inde_upd_store.\n- (* andi *) move=> P rt rs imm R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_andi rt rs imm (P ** R))); last by do 2 constructor.\n  move=> s h [h1 [h2 [ H3 [H4 [H5 H6] ] ] ] ].\n  exists h1, h2; repeat (split => //).\n  by apply inde_upd_store.\n- (* lw *) move=> Q rt offset base R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_lw rt offset base (Q ** R))); last by do 2 constructor.\n  move=> s h [h1 [h2 [H3 [H4 [ [p [H7 [z [H8 H9] ] ] ] H6] ] ] ] ].\n  exists p; split => //.\n  exists z; split => //.\n  rewrite H4.\n  by apply heap.get_union_L.\n  exists h1, h2; repeat (split => //).\n  by apply inde_upd_store.\n- (* lwxs *) move=> rt index base P0 R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_lwxs rt index base (P0 ** R))); last by do 2 constructor.\n  move=> s h [h1 [h2 [H3 [H4 [ [p [H7 [z [H8 H9] ] ] ] H6] ] ] ] ].\n  exists p; split => //.\n  exists z; split => //.\n  rewrite H4.\n  by apply heap.get_union_L.\n  exists h1, h2; repeat (split => //).\n  by apply inde_upd_store.\n- (* maddu *) move=> Q rs rt R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_maddu rs rt (Q ** R))); last by do 2 constructor.\n  move=> [s m] h [h1 [h2 [ H3 [H4 [H5 H6] ] ] ] ].\n  exists h1, h2; repeat (split => //).\n  by rewrite -(H2 _ s h2 m).\n- (* mfhi *) move=> Q rd R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_mfhi rd (Q ** R))); last by do 2 constructor.\n  move=> s h [h1 [h2 [ H3 [H4 [H5 H6] ] ] ] ].\n  exists h1, h2; repeat (split => //).\n  by apply inde_upd_store.\n- (* mflhxu *) move=> rd Q R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_mflhxu rd (Q ** R))); last by do 2 constructor.\n  move=> [s [a [hi lo]]] h [h1 [h2 [ H3 [H4 [H5 H6] ] ] ] ].\n  exists h1, h2; repeat (split => //).\n  rewrite /=.\n  case: ifP => [/eqP ? | X].\n  + rewrite -(H2 _ _ _) //; by apply H6.\n  + have : List.In rd (modified_regs (mflhxu rd)) by rewrite /=; auto.\n    move/(H1 (s, (a, (hi, lo))) h2 rd lo).\n    rewrite /store.upd X => {}H1.\n    rewrite -(H2 _ _ _ (a, (hi, lo))) //; tauto.\n- (* mflo *) move=> Q rd R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_mflo rd (Q ** R))); last by do 2 constructor.\n  move=> s h [h1 [h2 [ H3 [H4 [H5 H6] ] ] ] ].\n  exists h1, h2; repeat (split => //).\n  by apply inde_upd_store.\n- (* movn *) move=> Q rd rs rt R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_movn rd rs rt (Q ** R))); last by do 2 constructor.\n  move=> s h [h1 [h2 [ H3 [H4 [H5 H6] ] ] ] ].\n  split => H7.\n  exists h1, h2; repeat (split => //).\n  by apply (proj1 H5).\n  by apply inde_upd_store.\n  exists h1, h2; repeat (split => //).\n  by apply (proj2 H5).\n- (* movz *) move=> Q rd rs rt R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_movz rd rs rt (Q ** R))); last by do 2 constructor.\n  move=> s h [h1 [h2 [ H3 [H4 [H5 H6] ] ] ] ].\n  split => H7.\n  exists h1, h2; repeat (split => //).\n  by apply (proj1 H5).\n  by apply inde_upd_store.\n  exists h1, h2; repeat (split => //).\n  by apply (proj2 H5).\n- (* msubu *) move=> Q rs rt R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_msubu rs rt (Q ** R))); last by do 2 constructor.\n  move=> [s m] h [h1 [h2 [ H3 [H4 [H5 H6] ] ] ] ].\n  exists h1, h2; repeat (split => //).\n  by rewrite -(H2 _ s h2 m).\n- (* mthi *) move=> Q rs R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_mthi rs (Q ** R))); last by do 2 constructor.\n  move=> [s [a [hi lo]]] h [h1 [h2 [ H3 [H4 [H5 H6] ] ] ] ].\n  exists h1, h2; repeat (split => //).\n  rewrite /= -(H2 _ _ _) //.\n  by apply H6.\n- (* mtlo *) move=> Q rs R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_mtlo rs (Q ** R))); last by do 2 constructor.\n  move=> [s [a [hi lo]]] h [h1 [h2 [ H3 [H4 [H5 H6] ] ] ] ].\n  exists h1, h2; repeat (split => //).\n  rewrite /= -(H2 _ s h2) //.\n  by apply H6.\n- (* multu *) move=> Q rs rt R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_multu rs rt (Q ** R))); last by do 2 constructor.\n  move=> [s m] h [h1 [h2 [ H3 [H4 [H5 H6] ] ] ] ].\n  exists h1, h2; repeat (split => //).\n  by rewrite /= -(H2 _ s h2 m).\n- (* nor *) move=> Q rd rs rt R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_nor rd rs rt (Q ** R))); last by do 2 constructor.\n  move=> [s m] h [h1 [h2 [ H3 [H4 [H5 H6] ] ] ] ].\n  exists h1, h2; repeat (split => //).\n  by apply inde_upd_store.\n- (* or *) move=> Q rd rs rt R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_or rd rs rt (Q ** R))); last by do 2 constructor.\n  move=> [s m] h [h1 [h2 [ H3 [H4 [H5 H6] ] ] ] ].\n  exists h1, h2; repeat (split => //).\n  by apply inde_upd_store.\n- (* sll *) move=> Q rx ry sa R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_sll rx ry sa (Q ** R))); last by do 2 constructor.\n  move=> [s m] h [h1 [h2 [ H3 [H4 [H5 H6] ] ] ] ].\n  exists h1, h2; repeat (split => //).\n  by apply inde_upd_store.\n- (* sllv *) move=> Q rd rs rt R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_sllv rd rs rt (Q ** R))); last by do 2 constructor.\n  move=> [s m] h [h1 [h2 [ H3 [H4 [H5 H6] ] ] ] ].\n  exists h1, h2; repeat (split => //).\n  by apply inde_upd_store.\n- (* sltu *) move=> Q rd rs rt R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_sltu rd rs rt (Q ** R))); last by do 2 constructor.\n  move=> [s m] h [h1 [h2 [ H3 [H4 [H5 H6] ] ] ] ].\n  exists h1, h2; repeat (split => //).\n  by apply inde_upd_store.\n- (* sra *) move=> Q rd rt sa R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_sra rd rt sa (Q ** R))); last by do 2 constructor.\n  move=> [s m] h [h1 [h2 [ H3 [H4 [H5 H6] ] ] ] ].\n  exists h1, h2; repeat (split => //).\n  by apply inde_upd_store.\n- (* srl *) move=> Q rd rt sa R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_srl rd rt sa (Q ** R))); last by do 2 constructor.\n  move=> [s m] h [h1 [h2 [ H3 [H4 [H5 H6] ] ] ] ].\n  exists h1, h2; repeat (split => //).\n  by apply inde_upd_store.\n- (* srlv *) move=> Q rd rt rs R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_srlv rd rt rs (Q ** R))); last by do 2 constructor.\n  move=> [s m] h [h1 [h2 [H3 [H4 [H5 H6] ] ] ] ].\n  exists h1, h2; repeat (split => //).\n  by apply inde_upd_store.\n- (* subu *) move=> Q rs rt rd R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_subu rd rs rt (Q ** R))); last by do 2 constructor.\n  move=> s h [h1 [h2 [H3 [H4 [H5 H6] ] ] ] ].\n  exists h1, h2; repeat (split => //).\n  by apply inde_upd_store.\n- (* sw *) move=> rt off b Q R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_sw rt off b (Q ** R))); last by do 2 constructor.\n  move=> s h [h1 [h2 [ H3 [H4 [ [p [H7 [ [z H8] H9]]] H6]]]]].\n  exists p; split => //.\n  split.\n  exists z.\n  rewrite H4.\n  by apply heap.get_union_L.\n  exists (heap.upd p [rt]_s h1), h2; split.\n  by apply heap.disj_upd.\n  split => //.\n  rewrite H4.\n  by apply heap.upd_union_L with z.\n- (* xor *) move=> Q rd rs rt R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_xor rd rs rt (Q ** R))); last by do 2 constructor.\n  move=> s h [h1 [h2 [ H3 [H4 [H5 H6]]]]].\n  exists h1, h2; repeat (split => //).\n  by apply inde_upd_store.\n- (* xori *) move=> Q rt rs imm R H1 H2.\n  apply (hoare_prop_m.hoare_stren (wp_xori rt rs imm (Q ** R))); last by do 2 constructor.\n  move=> s h [h1 [h2 [ H3 [H4 [H5 H6]]]]].\n  exists h1, h2; repeat (split=> //).\n  by apply inde_upd_store.\nQed.\n\nLemma frame_rule_R (P : assert) c (Q : assert) : {{ P }} c {{ Q }} -> \n  forall (R : assert), inde (modified_regs c) R -> inde_cmd_mult c R ->\n    {{ P ** R }} c {{ Q ** R }}.\nProof.\nelim; clear P c Q.\n- exact frame_rule0.\n- (* seq *) move=> Q P R c d H IHhoare1 H0 IHhoare2 U.\n  case/inde_seq => H11 H12.\n  case/inde_cmd_mult_seq => H21 H22.\n  apply (while.hoare_seq _ _ _ _ _ _ (Q ** U)); by [apply IHhoare1 | apply IHhoare2].\n- (* conseq *) move=> P P' Q Q' c H H0 H1 IHhoare R H2 H3.\n  move: (IHhoare _ H2 H3) => H4.\n  apply (hoare_prop_m.hoare_stren (P' ** R)).\n  move=> s h [h1 [h2 [H5 [H6 [H7 H8]]]]]; by exists h1, h2; auto.\n  apply (hoare_prop_m.hoare_weak (Q' ** R)) => //.\n  move=> s h [h1 [h2 [ H5 [H6 [H7 H8]]]]]; by exists h1, h2; auto.\n- (* while *) move=> P t c H IHhoare R H1 H2.\n  apply (hoare_prop_m.hoare_weak (fun s h => (P ** R) s h /\\ ~~ eval_b t s)).\n  move=> s h [[h1 [h2 [H3 [H4 [H5 H6]]]]] H7]; by exists h1, h2.\n  apply (hoare_prop_m.hoare_stren (P ** R)) => //.\n  apply while.hoare_while with (P := P ** R).\n  move: (IHhoare _ H1 H2) => H3.\n  apply (hoare_prop_m.hoare_stren (fun s h => ((fun s0 h0 => P s0 h0 /\\ eval_b t s) ** R) s h)) => //.\n  move=> s h [ [h1 [h2 [ H4 [H5 [H6 H7] ] ] ] ] H8 ]; by exists h1, h2.\n- (* ifte *) move=> P Q t c d H1 IHhoare1 H3 IHhoare2 R.\n  case/inde_ifte => H51 H52.\n  case/inde_cmd_mult_ifte => H61 H62.\n  apply while.hoare_ifte.\n  + apply (hoare_prop_m.hoare_stren ((fun s h => P s h /\\ eval_b t s) ** R)).\n    move=> s h [ [h1 [h2 [H8 [H9 [H10 H11] ] ] ] ] H12 ]; by exists h1, h2.\n    by apply IHhoare1.\n  + apply (hoare_prop_m.hoare_stren ((fun s h => P s h /\\ ~~ eval_b t s) ** R)).\n    move=> s h [ [h1 [h2 [H8 [H9 [H10 H11] ] ] ] ] H12 ]; by exists h1, h2.\n    by apply IHhoare2.\nQed.\n\nLemma frame_rule_L (P : assert) (c : while.cmd) (Q : _assert) : {{P}}c {{Q}} ->\n  forall R : assert, inde (modified_regs c) R ->\n    inde_cmd_mult c R -> {{R ** P}}c {{R ** Q}}.\nProof.\nmove=> P_c_Q R H1 H2.\napply (while.hoare_conseq _ _ _ _ _ _ _ (P ** R) _ (Q ** R)).\nby rewrite assert_m.conCE.\nby rewrite assert_m.conCE.\nby apply frame_rule_R.\nQed.\n\nLemma before_frame R P' Q' P c Q : {{ P' ** R }} c {{ Q' ** R }} ->\n  P ===> P' ** R -> Q' ** R ===> Q -> {{ P }} c {{ Q }}.\nProof. move=> H1 H2 H3; by eapply while.hoare_conseq; eauto. Qed.\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/cryptoasm/mips_frame.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061854293323, "lm_q2_score": 0.5, "lm_q1q2_score": 0.25195309271466615}}
{"text": "Require Import OptionExt.\n\n(* option monad *)\nDefinition ret := fun (A:Type) (a:A) => Some a.\nDefinition bind : forall (A B:Type), option A -> (A -> option B) -> option B :=\n  fun A B a f =>\n  match a with\n  | None => None\n  | Some a => f a\n  end.\nDefinition fail := fun (A:Type) => None (A:=A).\n\nImplicit Arguments bind [A B].\nImplicit Arguments ret [A].\nImplicit Arguments fail [A].\n\nDefinition lift_bool : bool -> option unit := fun b => if b then ret tt else fail.\n\nNotation \"c1 ;; c2\" := (bind c1 (fun _ => c2)) (at level 20, right associativity).\nNotation \"x <- c1 ;: c2\" := (bind c1 (fun x => c2)) (at level 20, right associativity).\n\n(* Tactics for option monad handling *)\nLtac destruct_opt t t' result resulteq :=\n  destruct (option_dec t) as [[result resulteq] | resulteq];\n  rewrite resulteq in t';\n  [simpl in t' | discriminate].\n\nLtac ret_inject t :=\n  unfold ret in t; injection t; clear t; intro t.\n", "meta": {"author": "bacam", "repo": "coqjvm", "sha": "cabb813e3ad8263685b4198eea68f1505ff92947", "save_path": "github-repos/coq/bacam-coqjvm", "path": "github-repos/coq/bacam-coqjvm/coqjvm-cabb813e3ad8263685b4198eea68f1505ff92947/coqjvm/ill/OptionMonad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.5, "lm_q1q2_score": 0.25195308526454024}}
{"text": "Require Export MMLL.Misc.Hybrid.\nRequire Export MMLL.OL.CutCoherence.LNSg.LKBipoles.\nImport MMLL.Misc.Permutations.\nRequire Import MMLL.SL.FLLReasoning.\nRequire Import MMLL.SL.InvPositivePhase.\n         \nExport ListNotations.\nExport LLNotations.\n\nSet Implicit Arguments.\n\nSection LKCut.\n\nContext {SI: Signature}.\n\n Definition CutC (h: nat) (a:subexp):= forall m n n' i j FC M N L,\n    m <= h ->\n    m = i + j ->\n    n' <= n ->\n    isOLFormula FC ->\n    lengthUexp FC n' ->\n    IsPositiveAtomFormulaL N ->\n   IsPositiveAtomFormulaL M ->\n   IsPositiveAtomFormulaL (second L) ->\n    mt a = true ->\n    (seqN (LK a) i ((a,u|FC|)::L) M (UP []) ->\n     seqN (LK a) j ((a,d|FC|)::L) N (UP []) -> \n     seq (LKC a (pred n)) L (M ++ N) (UP [])).\n \nLtac CutTacPOSNEG := sauto;\n  try\n    match goal with\n    | [ |- isFormula _] => constructor;auto\n    | [ |- IsPositiveAtomFormula _] =>  constructor;auto\n    | [ |- LKC _ _] => autounfold; solve[constructor;constructor;auto]\n    | [ H: ~ IsPositiveAtom ?F, H': In ?F (atom _ :: _) |-_] => \n      solve [apply PositiveAtomIn in H';auto;contradiction]\n    | [ H: seqN _ _ _ _ (DW zero) |- _] => invTri H\n    | [ H: seq  _ _ _ (DW zero) |- _] => invTri' H\n    | [ |- LKC _ _ ]=> autounfold;solve [repeat (constructor;auto)]\n    | [ |- LK _ ]=> autounfold;solve [repeat (constructor;auto)]\n    | [|- IsPositiveAtomFormulaL (d| _ | :: _)] => solve[repeat (constructor;auto)]\n    end; OLSolve.\n\n Ltac solveBipole :=\n match goal with\n| [H: context[CteBipole] |- _] => inversion H \n| [H: context[BinBipole] |- _] => inversion H\n| [H: context[QuBipole] |- _] => inversion H  end.\n\nTactic Notation \"Bipole\"  constr(B) constr(S):=\n        match B with \n        | TT => TFocus (CteBipole TT_BODY S)\n        | FF => TFocus (CteBipole FF_BODY S)\nend.\n\n(* ; [do 2 constructor;OLSolve | solveBipole | ].\n *)\nTactic Notation \"Bipole\"  constr(B) constr(S) constr(F) constr(G):= \n     match B with\n     | AND => TFocus (BinBipole AND_BODY S F G)\n     | OR => TFocus (BinBipole OR_BODY S F G)\n     | IMP => TFocus (BinBipole IMP_BODY S F G) \n  end.\n  \n  \nTactic Notation \"Bipole\"  constr(B) constr(S) constr(FX) :=\n    match B with\n     | ALL => TFocus (QuBipole ALL_BODY S FX)\n     | SOME => TFocus (QuBipole SOME_BODY S FX)\n  end.\n  \n\nLemma exchangeSwap n th L F A B C: Permutation A (B ::C)\n -> seqN th n L (F :: A) (UP []) -> seqN th n L (B :: F :: C) (UP []).\n Proof with sauto.\n intros.\n eapply exchangeLCN.\n 2: exact H0.\n rewrite H...\n Qed.\n        \nLtac PermSwap Hs Hp:=\n    eapply exchangeSwap in Hs;[| exact Hp].\n\nLemma exchangeSwap2 n th L F G A B C: Permutation A (B ::C)\n -> seqN th n L (F :: G :: A) (UP []) -> seqN th n L (B :: F :: G :: C) (UP []).\n Proof with sauto.\n intros.\n eapply exchangeLCN.\n 2: exact H0.\n rewrite H...\n Qed.\n        \nLtac PermSwap2 Hs Hp:=\n    eapply exchangeSwap2 in Hs;[| exact Hp].\n\n \nLtac applyCutC Hl Hr :=\n match goal with\n  [ C: CutC _ _, \n    Hc: lengthUexp ?P ?n |- seq _ ?L (?M++?N) _  ] =>\n    match type of Hl with\n      | seqN _ ?l ((?i, u| ?P|)::?L) ?M _  =>\n         match type of Hr with\n         | seqN _ ?r ((?i, d| ?P|)::?L) ?N _ =>\n           let H' := fresh \"H\" in assert(H' : l + r = l + r) by auto;\n           refine(C _ _ _ _ _ _ _ _ _ _  H'  _ _ Hc _ _ _ _ Hl Hr);\n           CutTacPOSNEG\n          | _ => idtac\n          end\n     | _ => idtac      \n   end\nend.   \n\n \n\nLtac permuteANDR :=              \n  match goal with \n  | [ H1 : seqN _ _ _ _ (DW (AND_BODY.(rb_rightBody) _ _)),\n       H2 : Permutation ?N (u| t_bin AND ?F ?G | :: ?x) |- \n       seq _ _ (?M ++ ?N) (UP []) ] => \n       \n      apply FocusingWith in H1;sauto;\n      TFocus (BinBipole AND_BODY Right F G); \n      simpl;\n      LLTensor [u| t_bin AND F G | ] (M++x);[\n      rewrite H2;sauto  |  \n      solveLL;LLStore ; rewrite <- Permutation_midle ]\n \n  | [ H1 : seqN _ _ _ _ (DW (AND_BODY.(rb_rightBody) _ _)),\n       H2 : Permutation ?M (u| t_bin AND ?F ?G | :: ?x) |- \n       seq _ _ (?M ++ ?N) (UP []) ] => \n       \n      apply FocusingWith in H1;sauto;\n      TFocus (BinBipole AND_BODY Right F G); \n      simpl;\n      LLTensor [u| t_bin AND F G | ] (x++N);[\n      rewrite H2;sauto  |  \n      solveLL;LLStore  ]   \n  end.\n  \n   \nLtac permuteANDRight :=              \n    match goal with \n    | [ H : seqN _ _ _ _ (DW (rb_rightBody _ _)) ,\n        Hpp: Permutation ?N (u| t_bin AND ?F ?G | :: ?x)\n         |- \n        seq _ _ (?M ++ ?N) (UP []) ] => \n        \n        apply FocusingWith in H;sauto;\n        TFocus (BinBipole AND_BODY Right F G); \n        simpl;\n        LLTensor [u| t_bin AND F G | ] (M++x);[\n        rewrite Hpp;sauto  |  solveLL;LLStore ; rewrite <- Permutation_midle ]\n    | [ H : seqN _ _ _ _ (DW (rb_rightBody _ _)) ,\n        Hpp: Permutation ((?i, u| t_bin AND ?F ?G |) :: ?x) ?Cx\n         |- \n        seq _ ?Cx (?M ++ ?N) (UP []) ] => \n        \n        apply FocusingWith in H;sauto;\n        TFocus (BinBipole AND_BODY Right F G); \n        simpl;\n        LLTensor (@nil oo) (M++N);[\n        solveLL  |  solveLL;LLStore ; rewrite <- Permutation_midle ]\n  end. \n\n\n\nLtac permuteANDLeft :=              \n               match goal with \n    | [ H : seqN _ _ _ _ (DW (rb_leftBody _ _)) ,\n        Hpp: Permutation ?N (d| t_bin AND ?F ?G | :: ?x)\n         |- \n        seq _ _ (?M ++ ?N) (UP []) ] => \n        \n        apply FocusingPlus in H;sauto;[\n        TFocus (BinBipole AND_BODY Left F G); \n        simpl;\n        LLTensor [d| t_bin AND F G | ] (M++x);\n        [rewrite Hpp;sauto  |  LLPlusL;solveLL;rewrite <- Permutation_midle ]\n        | \n         TFocus (BinBipole AND_BODY Left F G); \n        simpl;\n        LLTensor [d| t_bin AND F G | ] (M++x);\n        [rewrite Hpp;sauto  |  LLPlusR;solveLL;rewrite <- Permutation_midle ]] \n        \n    | [ H : seqN _ _ _ _ (DW (rb_leftBody _ _)) ,\n        Hpp: Permutation ((?i, d| t_bin AND ?F ?G |) :: ?x) ?Cx\n         |- \n        seq _ ?Cx (?M ++ ?N) (UP []) ] => \n        \n        apply FocusingPlus in H;sauto;[\n        TFocus (BinBipole AND_BODY Left F G); \n        simpl;\n        LLTensor (@nil oo) (M++N);[\n        solveLL  |  LLPlusL;solveLL; rewrite <- Permutation_midle ]\n        |\n        TFocus (BinBipole AND_BODY Left F G); \n        simpl;\n        LLTensor (@nil oo) (M++N);[\n        solveLL  |  LLPlusR;solveLL; rewrite <- Permutation_midle ]\n        ]     \n     end. \n        \n   Ltac permuteORRight :=              \n   match goal with \n    | [ H : seqN _ _ _ _ (DW (rb_rightBody _ _)) ,\n        Hpp: Permutation ?N (u| t_bin OR ?F ?G | :: ?x)\n         |- \n        seq _ _ (?M ++ ?N) (UP []) ] => \n        \n        apply FocusingPlus in H;sauto;[\n        TFocus (BinBipole OR_BODY Right F G); \n        simpl;\n        LLTensor [u| t_bin OR F G | ] (M++x);\n        [rewrite Hpp;sauto  |  LLPlusL;solveLL;rewrite <- Permutation_midle ]\n        | TFocus (BinBipole OR_BODY Right F G); \n        simpl;\n        LLTensor [u| t_bin OR F G | ] (M++x);\n        [rewrite Hpp;sauto  | LLPlusR;solveLL;rewrite <- Permutation_midle ]\n        ]  \n   | [ H : seqN _ _ _ _ (DW (rb_rightBody _ _)) ,\n        Hpp: Permutation ((?i, u| t_bin OR ?F ?G |) :: ?x) ?Cx\n         |- \n        seq _ ?Cx (?M ++ ?N) (UP []) ] => \n        \n        apply FocusingPlus in H;sauto;[\n        TFocus (BinBipole OR_BODY Right F G); \n        simpl;\n        LLTensor (@nil oo) (M++N);[\n        solveLL  |  LLPlusL;solveLL; rewrite <- Permutation_midle ]\n        |\n        TFocus (BinBipole OR_BODY Right F G); \n        simpl;\n        LLTensor (@nil oo) (M++N);[\n        solveLL  |  LLPlusR;solveLL; rewrite <- Permutation_midle ]\n        ]     \n     end. \n \n  \n Ltac permuteORLeft :=              \n              \n                match goal with \n    | [ H : seqN _ _ _ _ (DW (rb_leftBody _ _)) ,\n        Hpp: Permutation ?N (d| t_bin OR ?F ?G | :: ?x)\n         |- \n        seq _ _ (?M ++ ?N) (UP []) ] => \n        \n        apply FocusingWith in H;sauto;\n        TFocus (BinBipole OR_BODY Left F G); \n        simpl;\n        LLTensor [d| t_bin OR F G | ] (M++x);[\n        rewrite Hpp;sauto  |  solveLL;LLStore ; rewrite <- Permutation_midle ]\n         | [ H : seqN _ _ _ _ (DW (rb_leftBody _ _)) ,\n        Hpp: Permutation ((?i, d| t_bin OR ?F ?G |) :: ?x) ?Cx\n         |- \n        seq _ ?Cx (?M ++ ?N) (UP []) ] => \n        \n        apply FocusingWith in H;sauto;\n        TFocus (BinBipole OR_BODY Left F G); \n        simpl;\n        LLTensor (@nil oo) (M++N);[\n        solveLL  |  solveLL;LLStore ; rewrite <- Permutation_midle ]\n      \n            end.\n   \n               \n Ltac permuteIMPRight :=              \n match goal with \n    | [ H : seqN _ _ _ _ (DW (rb_rightBody _ _)) ,\n        Hpp: Permutation ?N (u| t_bin IMP ?F ?G | :: ?x)\n         |- \n        seq _ _ (?M ++ ?N) (UP []) ] => \n        \n        apply FocusingPar in H;sauto;\n        TFocus (BinBipole IMP_BODY Right F G); \n        simpl;\n        LLTensor [u| t_bin IMP F G | ] (M++x);[\n        rewrite Hpp;sauto  |  solveLL;do 2 LLStore;\n        rewrite <- PermutConsApp;\n            rewrite <-  Permutation_midle;\n            rewrite perm_swap\n             ]\n           \n            end.\n          \n  Theorem FocusingForallUP :\n    forall n th (y: expr con) FX D G, proper y ->\n    seqN th n G D (DW (∀{ fun x : expr con => u| FX x |})) ->\n      exists m , n =  S (S (S m))  /\\ seqN th m G (u| FX y |::D) (UP [ ]).\n  Proof with sauto.\n    intros.\n    inversion H0... \n    inversion H6...\n    solveF.\n    specialize (H9 _ H).\n    inversion H9...\n    eexists n0.\n    split;eauto.\n  Qed.\n         \n   Theorem FocusingForallDW :\n    forall n th (y: expr Syntax.con) FX D G, proper y ->\n    seqN th n G D (DW (∀{ fun x : expr Syntax.con => d| FX x |})) ->\n      exists m , n =  S (S (S m))  /\\ seqN th m G (d| FX y |::D) (UP [ ]).\n  Proof with sauto.\n    intros.\n    inversion H0... \n    inversion H6...\n    solveF.\n    specialize (H9 _ H).\n    inversion H9...\n    eexists n0.\n    split;eauto.\n  Qed.\n\n   Theorem FocusingExistsUP :\n    forall n th FX D G, \n    seqN th n G D (DW (∃{ fun x : expr Syntax.con => u| FX x |})) ->\n      exists m t, n =  S (S (S m))  /\\ proper t /\\ seqN th m G (u| FX t |::D) (UP [ ]).\n  Proof with sauto.\n    intros.\n    inversion H... solveF. \n    inversion H6...\n    inversion H8...\n    eexists n0, t.\n    split;eauto.\n  Qed.\n\n   Theorem FocusingExistsDW :\n    forall n th FX D G, \n    seqN th n G D (DW (∃{ fun x : expr Syntax.con => d| FX x |})) ->\n      exists m t, n =  S (S (S m))  /\\ proper t /\\ seqN th m G (d| FX t |::D) (UP [ ]).\n  Proof with sauto.\n    intros.\n    inversion H... solveF. \n    inversion H6...\n    inversion H8...\n    eexists n0, t.\n    split;eauto.\n  Qed.\n\n               \n Ltac permuteALLRight :=              \n   match goal with \n    | [ H : seqN _ _ _ _ (DW (rq_rightBody _)) ,\n        Hpp: Permutation ?N (u| t_quant ALL ?FX | :: ?x)\n         |- \n        seq _ _ (?M ++ ?N) (UP []) ] => \n      \n      TFocus (QuBipole ALL_BODY Right FX);\n      simpl;\n      LLTensor [u| t_quant ALL FX | ] (M++x);\n       [  rewrite Hpp;sauto |  \n       LLRelease; LLForall; try solveUniform;LLStore \n       ]; match goal with\n       [Hpro: proper ?x |- context[?x]] =>          specialize(FocusingForallUP _ Hpro H) as Hj';sauto\n       end\n       \n    | [ H : seqN _ _ _ _ (DW (rq_rightBody _)) ,\n        Hpp: Permutation ((?i, u| t_quant ALL ?FX |) :: ?x) ?Cx\n         |- \n        seq _ ?Cx (?M ++ ?N) (UP []) ] => \n      \n      TFocus (QuBipole ALL_BODY Right FX);\n      simpl;\n      LLTensor (@nil oo) (M++N);\n       [  solveLL |  \n       LLRelease; LLForall; try solveUniform;LLStore \n       ]; match goal with\n       [Hpro: proper ?x |- context[?x]] =>          specialize(FocusingForallUP _ Hpro H) as Hj';sauto\n       end\n      end.\n    \n Ltac permuteALLLeft :=              \n   match goal with \n    | [ H : seqN _ _ _ _ (DW (rq_leftBody _)) ,\n        Hpp: Permutation ?N (d| t_quant ALL ?FX | :: ?x)\n         |- \n        seq _ _ (?M ++ ?N) (UP []) ] => \n      \n     apply FocusingExistsDW in H;sauto; \n        TFocus (QuBipole ALL_BODY Left FX); \n        simpl;\n        LLTensor [d| t_quant ALL FX | ] (M++x);[\n        rewrite Hpp;sauto |  ] ; match goal with\n      [Hpro: proper ?x |- _] => \n            LLExists x; LLRelease; LLStore\n       end\n       \n    | [ H : seqN _ _ _ _ (DW (rq_leftBody _)) ,\n        Hpp: Permutation ((?i, d| t_quant ALL ?FX |) :: ?x) ?Cx\n         |- \n        seq _ ?Cx (?M ++ ?N) (UP []) ] => \n      \n     apply FocusingExistsDW in H;sauto; \n        TFocus (QuBipole ALL_BODY Left FX); \n        simpl;\n        LLTensor (@nil oo) (M++N);[\n        solveLL |  ]; match goal with\n       [Hpro: proper ?x |- _] => \n            LLExists x; LLRelease; LLStore\n       end\n  end.\n\n Ltac permuteSOMERight :=              \n   match goal with \n    | [ H : seqN _ _ _ _ (DW (rq_rightBody _)) ,\n        Hpp: Permutation ?N (u| t_quant SOME ?FX | :: ?x)\n         |- \n        seq _ _ (?M ++ ?N) (UP []) ] => \n      \n     apply FocusingExistsUP in H;sauto; \n        TFocus (QuBipole SOME_BODY Right FX); \n        simpl;\n        LLTensor [u| t_quant SOME FX | ] (M++x);[\n        rewrite Hpp;sauto |  ] ; match goal with\n      [Hpro: proper ?x |- _] => \n            LLExists x; LLRelease; LLStore\n       end\n       \n    | [ H : seqN _ _ _ _ (DW (rq_rightBody _)) ,\n        Hpp: Permutation ((?i, u| t_quant SOME ?FX |) :: ?x) ?Cx\n         |- \n        seq _ ?Cx (?M ++ ?N) (UP []) ] => \n      \n     apply FocusingExistsUP in H;sauto; \n        TFocus (QuBipole SOME_BODY Right FX); \n        simpl;\n        LLTensor (@nil oo) (M++N);[\n        solveLL |  ]; match goal with\n       [Hpro: proper ?x |- _] => \n            LLExists x; LLRelease; LLStore\n       end\n  end.\n        \n   Ltac permuteSOMELeft :=              \n   match goal with \n    | [ H : seqN _ _ _ _ (DW (rq_leftBody _)) ,\n        Hpp: Permutation ?N (d| t_quant SOME ?FX | :: ?x)\n         |- \n        seq _ _ (?M ++ ?N) (UP []) ] => \n      \n      TFocus (QuBipole SOME_BODY Left FX);\n      simpl;\n      LLTensor [d| t_quant SOME FX | ] (M++x);\n       [  rewrite Hpp;sauto |  \n       LLRelease; LLForall; try solveUniform;LLStore \n       ]; match goal with\n       [Hpro: proper ?x |- context[?x]] =>          specialize(FocusingForallDW _ Hpro H) as Hj';sauto\n       end\n       \n    | [ H : seqN _ _ _ _ (DW (rq_leftBody _)) ,\n        Hpp: Permutation ((?i, d| t_quant SOME ?FX |) :: ?x) ?Cx\n         |- \n        seq _ ?Cx (?M ++ ?N) (UP []) ] => \n      \n      TFocus (QuBipole SOME_BODY Left FX);\n      simpl;\n      LLTensor (@nil oo) (M++N);\n       [  solveLL |  \n       LLRelease; LLForall; try solveUniform;LLStore \n       ]; match goal with\n       [Hpro: proper ?x |- context[?x]] =>          specialize(FocusingForallDW _ Hpro H) as Hj';sauto\n       end\n      end.\n      \n  Context  {USI:UnbSignature}.\n  Context  {UND:UnbNoDSignature}.\n  \nLtac FocusClause C L A B:=\n     match C with\n     | AND => match L with\n                      | up => TFocus (BinBipole AND_BODY Right A B)\n                      | down => TFocus (BinBipole AND_BODY Left A B)\n                      end\n     | OR => match L with\n                      | up => TFocus (BinBipole OR_BODY Right A B)\n                      | down => TFocus (BinBipole OR_BODY Left A B)\n                      end\n     | IMP => match L with\n                      | up => TFocus (BinBipole IMP_BODY Right A B)\n                      | down => TFocus (BinBipole IMP_BODY Left A B)\n                      end\n    end.\n    \nLtac permute := \nmatch goal with\n | [ H : Permutation ?M (atom (?a (t_bin ?C ?A ?B)) :: ?x) |- \n       seq _ _ (?M ++ ?N) _] => FocusClause C a A B\n | [ H : Permutation ?N (atom (?a (t_bin ?C ?A ?B)) :: ?x) |- \n       seq _ _ (?M ++ ?N) _] => FocusClause C a A B\n end.\n \n Ltac solveQF :=\n  match goal with\n   [ H1 : isOLFormula (t_quant qt ?FX), \n     H2 : proper ?x |- isOLFormula (?FX ?x)] =>\n                inversion H1;subst;OLSolve;\n                match goal with\n       [ H : lbind 0%nat _ = lbind 0%nat ?FX |-\n          isOLFormula (?FX ?x)] =>\n                apply lbindEq in H;sauto;\n               try rewrite <- H;sauto\n              end  \n                \n   end.  \n  \n  Lemma LKCutC F F0 FC L M N a h n0 n1 n' n:\n     mt a = true -> S h = S n0 + S n1 -> isOLFormula FC ->\n     lengthUexp FC n' -> \n     n' <= n ->\n     IsPositiveAtomFormulaL M ->\n     IsPositiveAtomFormulaL N ->\n     IsPositiveAtomFormulaL (second L) ->\n     CutC h a ->\n     seqN (LK a) (S n0) ((a,u| FC |) :: L) M (UP []) ->\n     seqN (LK a) (S n1) ((a,d| FC |) :: L) N (UP []) ->\n     LK a F ->\n     ~ IsPositiveAtom F ->\n     seqN (LK a) n0 ((a,u| FC |) :: L) M (DW F) ->\n     LK a F0 ->\n     ~ IsPositiveAtom F0 ->\n     seqN (LK a) n1 ((a,d| FC |) :: L) N (DW F0) ->\n     seq (LKC a (pred n)) L (M ++ N) (UP []).\nProof with CutTacPOSNEG.     \n    intros H4 Heqh isFFC lngF HRel isFM isFN isFL. \n    intro CutHC.\n    intros Hi Hj.\n    intros H H0 H1 H2 H3 H5.\n\n   inversion H;sauto. \n   (* Analizing the derivation on the left *)     \n   * (* 1/6 - Constants *)\n      inversion H6;sauto.\n      (* Four Cases *)     \n     3:{ \n      apply BipoleReasoning in H1...\n      inversion H10...\n      solveF.\n      inversion H10...\n      solveF. }\n    3:{\n      apply BipoleReasoning in H1...\n      Bipole FF Left.\n      LLTensor [d| t_cons FF | ] (N++x0).\n      rewrite H11...\n      simpl. solveLL.\n      checkPermutationCases H12.\n      Bipole FF Left.\n      LLTensor (@nil oo) (M++N). \n      solveLL... \n      simpl. solveLL. }\n     2:{ \n      apply BipoleReasoning in H1...\n      inversion H10...\n      solveF.\n      inversion H10...\n      solveF. }\n      apply BipoleReasoning in H1...\n      simpl in H11.\n      Bipole TT Right.\n      LLTensor [u| t_cons TT |] (x0++N).\n      rewrite H11...\n      simpl...\n      checkPermutationCases H12.\n      clear H11.\n      {   (** FF Right is pal *)\n          inversion H2...\n          (* Analizing the derivation on the right *)     \n          - (* Constants Case *) \n             inversion H1...\n     3:{ \n      apply BipoleReasoning in H5...\n      inversion H12...\n      solveF.\n      inversion H12...\n      solveF. }\n    3:{\n      apply BipoleReasoning in H5...\n      Bipole FF Left.\n      LLTensor [d| t_cons FF | ] (M++x1).\n      rewrite H13...\n      simpl. solveLL.\n      checkPermutationCases H14.\n      Bipole FF Left.\n      LLTensor (@nil oo) (M++N). \n      solveLL... \n      simpl. solveLL. }\n     2:{ \n      apply BipoleReasoning in H5...\n      inversion H11...\n      solveF.\n      inversion H11...\n      solveF. }\n      \n      apply BipoleReasoning in H5...\n      Bipole TT Right.\n      LLTensor [u| t_cons TT |] (M++x1).\n      rewrite H7...\n      simpl...       \n                 checkPermutationCases H8.  \n                Bipole TT Right.\n                LLTensor (@nil oo) (M++N).\n                solveLL... \n                simpl...\n          - inversion H1...\n            (* Connectives Case *) \n            -- apply BipoleReasoning in H5...\n                simpl in H13.\n                permuteANDRight.\n                applyCutC Hi H12.\n                applyCutC Hi H14.\n                checkPermutationCases H14.\n                apply FocusingWith in H12...\n                TFocus (BinBipole AND_BODY Right F G).\n                LLTensor (@nil oo) (M++N).\n                solveLL...\n                simpl.\n                LLRelease. LLWith. 1-2: LLStore.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H16.\n            -- apply BipoleReasoning in H5...\n                simpl in H13.\n                permuteANDLeft.\n                applyCutC Hi H11.\n                applyCutC Hi H11.\n                 checkPermutationCases H14.\n                apply FocusingPlus in H12...\n                all:TFocus (BinBipole AND_BODY Left F G).\n                all:LLTensor (@nil oo) (M++N).\n                all:solveLL...\n                all: simpl.\n                1: LLPlusL; LLRelease; LLStore.\n                2: LLPlusR; LLRelease; LLStore.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H14.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H14.\n            -- apply BipoleReasoning in H5...\n                simpl in H13.\n                permuteORRight.\n                applyCutC Hi H11.\n                applyCutC Hi H11.\n                 checkPermutationCases H14.\n                apply FocusingPlus in H12...\n                all:TFocus (BinBipole OR_BODY Right F G).\n                all:LLTensor (@nil oo) (M++N).\n                all:solveLL...\n                all: simpl.\n                1: LLPlusL; LLRelease; LLStore.\n                2: LLPlusR; LLRelease; LLStore.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H14.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H14.           \n            -- apply BipoleReasoning in H5...\n                simpl in H13.\n                permuteORLeft.\n                applyCutC Hi H12.\n                applyCutC Hi H14.\n                checkPermutationCases H14.\n                apply FocusingWith in H12...\n                TFocus (BinBipole OR_BODY Left F G).\n                LLTensor (@nil oo) (M++N).\n                solveLL...\n                simpl.\n                LLRelease. LLWith. 1-2: LLStore.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H16.\n            -- apply BipoleReasoning in H5...\n                simpl in H13.\n                \n      match goal with \n    | [ H1 : seqN _ _ _ _ (DW (rb_rightBody _ _)) ,\n        H2 : Permutation ?N (u| t_bin IMP ?F ?G | :: ?x)\n        |- seq _ _ (?M ++ ?N) (UP []) ] => \n        \n        apply FocusingPar in H1;sauto;\n        TFocus (BinBipole IMP_BODY Right F G); \n        simpl;\n        LLTensor [u| t_bin IMP F G |] (M++x);[\n        rewrite H2;sauto |  solveLL;do 2 LLStore;\n        rewrite <- PermutConsApp;\n            rewrite <-  Permutation_midle;\n            rewrite perm_swap\n             ]\n   end.\n    applyCutC Hi H11.\n    OLSolve.\n   checkPermutationCases H14. \n\n   match goal with \n    | [ H1 : seqN _ _ _ _ (DW (rb_rightBody _ _)) ,\n        H2 : Permutation ?Cx ((?i, u| t_bin IMP ?F ?G |) :: ?x) \n         |- seq _ ?Cx (?M ++ ?N) (UP []) ] => \n        \n        apply FocusingPar in H1;sauto;\n        TFocus (BinBipole IMP_BODY Right F G); \n        simpl;\n        LLTensor (@nil oo) (M++N);[\n        solveLL;sauto |  solveLL;do 2 LLStore;\n        rewrite <- PermutConsApp;\n            rewrite <-  Permutation_midle;\n            rewrite perm_swap\n             ]\n           \n            end.\n        applyCutC Hi H14.\n            \n            -- apply BipoleReasoning in H5...\n                apply FocusingTensor in H12...\n                simpl in H13.\n                PosNegAll a...\n                1-2: intro; intros...\n                rewrite CEncodeApp.\n                LLPerm (CEncode a N ++ (CEncode a M ++ L)).      \n               apply  AbsorptionLSet'...\n               apply setTCEncode...\n               rewrite secCEncode.\n               assert(IsPositiveAtomFormulaL x1) by OLSolve.\n                TFocus (BinBipole IMP_BODY Left F G). \n                simpl.\n                LLTensor [d| t_bin IMP F G | ] x1.\n                LLTensor x3 x4. \n                1-2: LLRelease; LLStore.\n                1-2: apply  AbsorptionLSet'...\n                1,3: apply setTCEncode...\n                1-2: rewrite secCEncode.\n                1-2: rewrite Permutation_app_comm.\n                applyCutC Hi H11.\n                applyCutC Hi H15.\n                \n                checkPermutationCases H14.\n                apply FocusingTensor in H12...\n                PosNegAll a...\n                1-2: intro; intros...\n                rewrite CEncodeApp.\n                LLPerm (CEncode a N ++ (CEncode a M ++ L)).      \n               apply  AbsorptionLSet'...\n               apply setTCEncode...\n               rewrite secCEncode.\n               \n                TFocus (BinBipole IMP_BODY Left F G). \n                simpl.\n                LLTensor (@nil oo) N.\n                apply weakeningGen. \n                apply allSeTU... \n                solveLL.\n                LLTensor x5 x6. \n                1-2: LLRelease; LLStore.\n                1-2: apply  AbsorptionLSet'...\n                1,3: apply setTCEncode...\n                1-2: rewrite secCEncode.\n                1-2: rewrite Permutation_app_comm.\n                applyCutC Hi H14.\n                applyCutC Hi H17.\n          - (* INIT Case *)        \n             apply FocusingInitRuleU in H5...\n             PosNegAll a...\n             1-2: intro; intros...\n             rewrite CEncodeApp.\n             LLPerm (CEncode a N ++ (CEncode a M ++ L)).      \n                 \n              apply  AbsorptionLSet'...\n               apply setTCEncode...\n               rewrite secCEncode.\n               TFocus (RINIT OO).\n                LLTensor [u| OO |] [d| OO |].\n                checkPermutationCases H11.\n                clear H8.\n                rewrite Permutation_app_comm...\n                simpl.\n                PosNeg a.\n                intro; intros...\n                simpl.\n                apply seqNtoSeq in Hi.\n               refine (WeakTheory _ _ Hi)...\n               apply TheoryEmb1.\n               rewrite Permutation_app_comm.\n               apply WeakPosNeg with (a:=a)...\n               1-2: intro; intros...\n               TFocus (RINIT OO).\n                LLTensor [u| OO |] (@nil oo).\n                solveLL.\n                \n                checkPermutationCases H11.\n                rewrite Permutation_app_comm.\n                apply WeakPosNeg with (a:=a)...\n               1-2: intro; intros...\n               TFocus (RINIT OO).\n                LLTensor (@nil oo) [d| OO |] .\n                solveLL.\n                \n                checkPermutationCases H11.\n                checkPermutationCases H5.\n                rewrite H11.\n                TFocus (NEG (t_cons TT) a).\n                inversion H4...\n                LLTensor (@nil oo) M;[solveLL | ].\n                LLRelease. LLStoreC.\n                rewrite <- H11.\n               apply seqNtoSeq in Hi.\n               refine (WeakTheory _ _ Hi)...\n               apply TheoryEmb1.\n               rewrite <- (app_nil_l M).\n               apply WeakPosNeg with (a:=a)...\n               1-2: intro; intros...\n               TFocus (RINIT OO).\n                LLTensor (@nil oo) (@nil oo).\n                solveLL. solveLL.\n         - (* Quantifiers Case *)        \n            inversion H1...\n            -- apply BipoleReasoning in H5...\n                simpl in H14.\n                permuteALLRight.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                solveQF.\n                checkPermutationCases H15.\n                symmetry in H11.\n                permuteALLRight.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H17.\n                solveQF.\n            -- apply BipoleReasoning in H5...\n                simpl in H14.\n                permuteALLLeft.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                solveQF.\n                checkPermutationCases H15.\n                symmetry in H11.\n                permuteALLLeft.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H17.\n                solveQF.\n            -- apply BipoleReasoning in H5...\n                simpl in H14.\n                permuteSOMERight.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                solveQF.\n                checkPermutationCases H15.\n                symmetry in H11.\n                permuteSOMERight.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H17.\n                solveQF.\n            -- apply BipoleReasoning in H5...\n                simpl in H14.\n                permuteSOMELeft.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                solveQF.\n                checkPermutationCases H15.\n                symmetry in H11.\n                permuteSOMELeft.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H17.\n                solveQF.\n         - (* POS Case *)                    \n            apply BipoleReasoning in H5...\n            apply FocusingQuest in H11...\n            TFocus (POS OO a).\n            LLTensor [d| OO |] (M++x1).\n            rewrite H12...\n            LLRelease. LLStoreC.\n            eapply weakeningN with (F:=(a, d| OO |)) in Hi...\n            LLSwapC H8.\n            LLSwapC Hi.\n            applyCutC Hi H8.\n            apply allU.\n            checkPermutationCases H13.\n            apply FocusingQuest in H11...\n            eapply contractionN in H7...\n            applyCutC Hi H7.\n            apply allU.\n            \n            apply FocusingQuest in H11...\n            TFocus (POS OO a).\n            LLTensor (@nil oo) (M++N).\n            solveLL.\n            LLRelease. LLStoreC.\n            eapply weakeningN with (F:=(a, d| OO |)) in Hi...\n            LLSwapC H13.\n            LLSwapC Hi.\n            applyCutC Hi H13.\n            apply allU.\n         - (* NEG Case *)     \n            apply BipoleReasoning in H5...\n            apply FocusingQuest in H11...\n            TFocus (NEG OO a).\n            LLTensor [u| OO |] (M++x1).\n            rewrite H12...\n            LLRelease. LLStoreC.\n            eapply weakeningN with (F:=(a, u| OO |)) in Hi...\n            LLSwapC H8.\n            LLSwapC Hi.\n            applyCutC Hi H8.\n            apply allU.\n            checkPermutationCases H13.\n            apply FocusingQuest in H11...\n            TFocus (NEG OO a).\n            LLTensor (@nil oo) (M++N).\n            solveLL.\n            LLRelease. LLStoreC.\n            eapply weakeningN with (F:=(a, u| OO |)) in Hi...\n            LLSwapC H13.\n            LLSwapC Hi.\n            applyCutC Hi H13.\n            apply allU.  }\n   \n    (* Continuing the case 3/4 - FF Right *) \n    \n    Bipole TT Right. \n    LLTensor (@nil oo) (M++N).\n    solveLL...\n    simpl...\n      \n   \n     * (* 2/6 - Connectives *)\n        inversion H6;sauto. \n      ** (* 1/6 - AND RIGHT *)\n      apply BipoleReasoning in H1...\n      apply FocusingWith in H10...\n      PosNegAll a...\n      1-2: intro; intros...\n      rewrite CEncodeApp.\n      rewrite app_assoc_reverse.\n      apply AbsorptionLSet'...\n               apply setTCEncode...\n               rewrite secCEncode.\n      TFocus (BinBipole AND_BODY Right F1 G). \n      LLTensor [u| t_bin AND F1 G|] x0.\n      simpl. LLRelease. LLWith.\n      1-2: LLStore.\n      1-2: apply AbsorptionLSet'...\n      1,3 : apply setTCEncode...\n      1-2 : rewrite secCEncode.\n      applyCutC H10 Hj.\n      applyCutC H12 Hj.\n      \n      checkPermutationCases H12.\n      { (** AND Right is principal *)\n          clear H11.\n          inversion H2...\n          (* Analizing the derivation on the right *)     \n          - (* Constants Case *) \n             inversion H1...\n      3:{ \n      apply BipoleReasoning in H5...\n      inversion H12...\n      solveF.\n      inversion H12...\n      solveF. }\n    3:{\n      apply BipoleReasoning in H5...\n      Bipole FF Left.\n      LLTensor [d| t_cons FF | ] (M++x1).\n      rewrite H13...\n      simpl. solveLL.\n      checkPermutationCases H14.\n      Bipole FF Left.\n      LLTensor (@nil oo) (M++N). \n      solveLL... \n      simpl. solveLL. }\n     2:{ \n      apply BipoleReasoning in H5...\n      inversion H12...\n      solveF.\n      inversion H12...\n      solveF. }\n      \n      apply BipoleReasoning in H5...\n      Bipole TT Right.\n      LLTensor [u| t_cons TT |] (M++x1).\n      rewrite H13...\n      simpl...       \n                 checkPermutationCases H14.  \n                Bipole TT Right.\n                LLTensor (@nil oo) (M++N).\n                solveLL... \n                simpl...\n          - inversion H1...\n            (* Connectives Case *) \n            -- apply BipoleReasoning in H5...\n                simpl in H13.\n                permuteANDRight.\n                applyCutC Hi H12.\n                applyCutC Hi H14.\n                checkPermutationCases H14.\n                apply FocusingWith in H12...\n                TFocus (BinBipole AND_BODY Right F G0).\n                LLTensor (@nil oo) (M++N).\n                solveLL...\n                simpl.\n                LLRelease. LLWith. 1-2: LLStore.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H16.\n            -- apply BipoleReasoning in H5...\n                simpl in H13.\n                permuteANDLeft.\n                applyCutC Hi H11.\n                applyCutC Hi H11.\n                checkPermutationCases H14.\n                 \n           { clear H13.\n                    \n           apply @PosNegSetT' with (a:=a)...\n           1-2: intro;intros...\n           rewrite <- (app_nil_r []).\n           \n           Import SL.CutElimination.\n           \n           eapply GeneralCut' with (C:=dual ((AND_BODY.(rb_leftBody) F1 G)))...\n           rewrite <- (app_nil_r []).\n           eapply GeneralCut' with (C:=dual ((AND_BODY.(rb_rightBody) F1 G)))...\n             \n           inversion lngF...\n           eapply WeakTheory with (th:=(CUTLN (max n1 n2))).\n           intros.\n           apply TheoryEmb2.\n           refine(CuteRuleN H5 _)...\n           apply weakeningAll...\n                    \n           apply AND_CUTCOHERENT... \n\n           simpl.\n           apply FocusingWith in H10...\n           LLRelease. \n           LLWith. \n           1-2: LLStore.\n           1-2: apply AbsorptionLSet'...\n           1,3: apply setTCEncode...\n           1-2: apply AbsorptionLSet'...\n           1,3: apply setTCEncode...\n           1-2: rewrite !secCEncode.\n           1-2: simpl; rewrite app_comm_cons. \n           applyCutC H9 Hj.\n           applyCutC H10 Hj. \n           \n           simpl.\n           apply FocusingWith in H10...\n           apply FocusingPlus in H12...\n           1: LLPlusL; LLRelease; LLStore. \n           2: LLPlusR; LLRelease; LLStore.  \n           1-2: apply AbsorptionLSet'...\n           1,3: apply setTCEncode...\n           1-2: apply AbsorptionLSet'...\n           1,3: apply setTCEncode...\n           1-2: rewrite !secCEncode.\n           1-2: simpl; rewrite <- Permutation_midle.\n           1-2: applyCutC Hi H8. }\n\n                apply FocusingPlus in H12...\n                all:TFocus (BinBipole AND_BODY Left F G0).\n                all:LLTensor (@nil oo) (M++N).\n                all:solveLL...\n                1-2: simpl.\n                1: LLPlusL; LLRelease; LLStore.\n                2: LLPlusR; LLRelease; LLStore.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H14.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H14.\n            -- apply BipoleReasoning in H5...\n                simpl in H13.\n                permuteORRight.\n                applyCutC Hi H11.\n                applyCutC Hi H11.\n                 checkPermutationCases H14.\n                apply FocusingPlus in H12...\n                all:TFocus (BinBipole OR_BODY Right F G0).\n                all:LLTensor (@nil oo) (M++N).\n                all:solveLL...\n                all: simpl.\n                1: LLPlusL; LLRelease; LLStore.\n                2: LLPlusR; LLRelease; LLStore.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H14.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H14.           \n            -- apply BipoleReasoning in H5...\n                simpl in H13.\n                permuteORLeft.\n                applyCutC Hi H12.\n                applyCutC Hi H14.\n                checkPermutationCases H14.\n                apply FocusingWith in H12...\n                TFocus (BinBipole OR_BODY Left F G0).\n                LLTensor (@nil oo) (M++N).\n                solveLL...\n                simpl.\n                LLRelease. LLWith. 1-2: LLStore.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H16.\n            -- apply BipoleReasoning in H5...\n                simpl in H13.\n                \n      match goal with \n    | [ H1 : seqN _ _ _ _ (DW (rb_rightBody _ _)) ,\n        H2 : Permutation ?N (u| t_bin IMP ?F ?G | :: ?x)\n        |- seq _ _ (?M ++ ?N) (UP []) ] => \n        \n        apply FocusingPar in H1;sauto;\n        TFocus (BinBipole IMP_BODY Right F G); \n        simpl;\n        LLTensor [u| t_bin IMP F G |] (M++x);[\n        rewrite H2;sauto |  solveLL;do 2 LLStore;\n        rewrite <- PermutConsApp;\n            rewrite <-  Permutation_midle;\n            rewrite perm_swap\n             ]\n   end.\n    applyCutC Hi H11.\n    OLSolve.\n   checkPermutationCases H14. \n\n   match goal with \n    | [ H1 : seqN _ _ _ _ (DW (rb_rightBody _ _)) ,\n        H2 : Permutation ?Cx ((?i, u| t_bin IMP ?F ?G |) :: ?x) \n         |- seq _ ?Cx (?M ++ ?N) (UP []) ] => \n        \n        apply FocusingPar in H1;sauto;\n        TFocus (BinBipole IMP_BODY Right F G); \n        simpl;\n        LLTensor (@nil oo) (M++N);[\n        solveLL;sauto |  solveLL;do 2 LLStore;\n        rewrite <- PermutConsApp;\n            rewrite <-  Permutation_midle;\n            rewrite perm_swap\n             ]\n           \n            end.\n        applyCutC Hi H14.\n            \n            -- apply BipoleReasoning in H5...\n                apply FocusingTensor in H12...\n                simpl in H13.\n                PosNegAll a...\n                1-2: intro; intros...\n                rewrite CEncodeApp.\n                LLPerm (CEncode a N ++ (CEncode a M ++ L)).      \n               apply  AbsorptionLSet'...\n               apply setTCEncode...\n               rewrite secCEncode.\n               assert(IsPositiveAtomFormulaL x1) by OLSolve.\n                TFocus (BinBipole IMP_BODY Left F G0). \n                simpl.\n                LLTensor [d| t_bin IMP F G0 | ] x1.\n                LLTensor x3 x4. \n                1-2: LLRelease; LLStore.\n                1-2: apply  AbsorptionLSet'...\n                1,3: apply setTCEncode...\n                1-2: rewrite secCEncode.\n                1-2: rewrite Permutation_app_comm.\n                applyCutC Hi H11.\n                applyCutC Hi H15.\n                \n                checkPermutationCases H14.\n                apply FocusingTensor in H12...\n                PosNegAll a...\n                1-2: intro; intros...\n                rewrite CEncodeApp.\n                LLPerm (CEncode a N ++ (CEncode a M ++ L)).      \n               apply  AbsorptionLSet'...\n               apply setTCEncode...\n               rewrite secCEncode.\n               \n                TFocus (BinBipole IMP_BODY Left F G0). \n                simpl.\n                LLTensor (@nil oo) N.\n                apply weakeningGen. \n                apply allSeTU... \n                solveLL.\n                LLTensor x5 x6. \n                1-2: LLRelease; LLStore.\n                1-2: apply  AbsorptionLSet'...\n                1,3: apply setTCEncode...\n                1-2: rewrite secCEncode.\n                1-2: rewrite Permutation_app_comm.\n                applyCutC Hi H14.\n                applyCutC Hi H17.\n          - (* INIT Case *)        \n             apply FocusingInitRuleU in H5...\n             PosNegAll a...\n             1-2: intro; intros...\n             rewrite CEncodeApp.\n             LLPerm (CEncode a N ++ (CEncode a M ++ L)).      \n                 \n              apply  AbsorptionLSet'...\n               apply setTCEncode...\n               rewrite secCEncode.\n               TFocus (RINIT OO).\n                LLTensor [u| OO |] [d| OO |].\n                checkPermutationCases H11.\n                clear H8.\n                rewrite Permutation_app_comm...\n                simpl.\n                PosNeg a.\n                intro; intros...\n                simpl.\n                apply seqNtoSeq in Hi.\n               refine (WeakTheory _ _ Hi)...\n               apply TheoryEmb1.\n               rewrite Permutation_app_comm.\n               apply WeakPosNeg with (a:=a)...\n               1-2: intro; intros...\n               TFocus (RINIT OO).\n                LLTensor [u| OO |] (@nil oo).\n                solveLL.\n                \n                checkPermutationCases H11.\n                rewrite Permutation_app_comm.\n                apply WeakPosNeg with (a:=a)...\n               1-2: intro; intros...\n               TFocus (RINIT OO).\n                LLTensor (@nil oo) [d| OO |] .\n                solveLL.\n                \n                checkPermutationCases H11.\n                checkPermutationCases H5.\n                rewrite H11.\n                TFocus (NEG (t_bin AND F1 G) a).\n                inversion H4...\n                LLTensor (@nil oo) M;[solveLL | ].\n                LLRelease. LLStoreC.\n                rewrite <- H11.\n               apply seqNtoSeq in Hi.\n               refine (WeakTheory _ _ Hi)...\n               apply TheoryEmb1.\n               rewrite <- (app_nil_l M).\n               apply WeakPosNeg with (a:=a)...\n               1-2: intro; intros...\n               TFocus (RINIT OO).\n                LLTensor (@nil oo) (@nil oo).\n                solveLL. solveLL.\n         - (* Quantifiers Case *)        \n            inversion H1...\n            -- apply BipoleReasoning in H5...\n                simpl in H14.\n                permuteALLRight.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                solveQF.\n                checkPermutationCases H15.\n                symmetry in H11.\n                permuteALLRight.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H17.\n                solveQF.\n            -- apply BipoleReasoning in H5...\n                simpl in H14.\n                permuteALLLeft.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                solveQF.\n                checkPermutationCases H15.\n                symmetry in H11.\n                permuteALLLeft.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H17.\n                solveQF.\n            -- apply BipoleReasoning in H5...\n                simpl in H14.\n                permuteSOMERight.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                solveQF.\n                checkPermutationCases H15.\n                symmetry in H11.\n                permuteSOMERight.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H17.\n                solveQF.\n            -- apply BipoleReasoning in H5...\n                simpl in H14.\n                permuteSOMELeft.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                solveQF.\n                checkPermutationCases H15.\n                symmetry in H11.\n                permuteSOMELeft.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H17.\n                solveQF.\n         - (* POS Case *)                    \n            apply BipoleReasoning in H5...\n            apply FocusingQuest in H11...\n            TFocus (POS OO a).\n            LLTensor [d| OO |] (M++x1).\n            rewrite H12...\n            LLRelease. LLStoreC.\n            eapply weakeningN with (F:=(a, d| OO |)) in Hi...\n            LLSwapC H8.\n            LLSwapC Hi.\n            applyCutC Hi H8.\n            apply allU.\n            checkPermutationCases H13.\n            apply FocusingQuest in H11...\n            eapply contractionN in H7...\n            applyCutC Hi H7.\n            apply allU.\n            \n            apply FocusingQuest in H11...\n            TFocus (POS OO a).\n            LLTensor (@nil oo) (M++N).\n            solveLL.\n            LLRelease. LLStoreC.\n            eapply weakeningN with (F:=(a, d| OO |)) in Hi...\n            LLSwapC H13.\n            LLSwapC Hi.\n            applyCutC Hi H13.\n            apply allU.\n         - (* NEG Case *)     \n            apply BipoleReasoning in H5...\n            apply FocusingQuest in H11...\n            TFocus (NEG OO a).\n            LLTensor [u| OO |] (M++x1).\n            rewrite H12...\n            LLRelease. LLStoreC.\n            eapply weakeningN with (F:=(a, u| OO |)) in Hi...\n            LLSwapC H8.\n            LLSwapC Hi.\n            applyCutC Hi H8.\n            apply allU.\n            checkPermutationCases H13.\n            apply FocusingQuest in H11...\n            TFocus (NEG OO a).\n            LLTensor (@nil oo) (M++N).\n            solveLL.\n            LLRelease. LLStoreC.\n            eapply weakeningN with (F:=(a, u| OO |)) in Hi...\n            LLSwapC H13.\n            LLSwapC Hi.\n            applyCutC Hi H13.\n            apply allU.  }\n            \n      apply FocusingWith in H10...\n      TFocus (BinBipole AND_BODY Right F1 G). \n      simpl.\n      LLTensor (@nil oo) (M++N).\n      solveLL...\n      LLRelease.\n      LLWith. 1-2: LLStore.\n      rewrite app_comm_cons.\n      applyCutC H13 Hj.\n      rewrite app_comm_cons.\n      applyCutC H14 Hj.\n      \n      ** (* 2/6 - AND LEFT *)\n      apply BipoleReasoning in H1...\n      PosNegAll a...\n      1-2: intro; intros...\n      rewrite CEncodeApp.\n      rewrite app_assoc_reverse.\n      apply AbsorptionLSet'...\n               apply setTCEncode...\n               rewrite secCEncode.\n      apply FocusingPlus in H10...\n      1-2: TFocus (BinBipole AND_BODY Left F1 G). \n      1-2: LLTensor [d| t_bin AND F1 G|] x0.\n      1: simpl; LLPlusL; LLRelease; LLStore.\n      2: simpl; LLPlusR; LLRelease; LLStore.\n      1-2: apply AbsorptionLSet'...\n      1,3 : apply setTCEncode...\n      1-2 : rewrite secCEncode.\n      applyCutC H9 Hj.\n      applyCutC H9 Hj.\n      \n      checkPermutationCases H12.\n      \n      apply FocusingPlus in H10...\n      1-2: TFocus (BinBipole AND_BODY Left F1 G). \n      1-2: LLTensor (@nil oo) (M++N).\n      1,3: solveLL...\n      1: simpl; LLPlusL; LLRelease; LLStore.\n      2: simpl; LLPlusR; LLRelease; LLStore.\n      rewrite app_comm_cons.\n      applyCutC H12 Hj.\n      rewrite app_comm_cons.\n      applyCutC H12 Hj.\n      ** (* 3/6 - OR RIGHT *)\n      apply BipoleReasoning in H1...\n      PosNegAll a...\n      1-2: intro; intros...\n      rewrite CEncodeApp.\n      rewrite app_assoc_reverse.\n      apply AbsorptionLSet'...\n               apply setTCEncode...\n               rewrite secCEncode.\n      apply FocusingPlus in H10...\n      1-2: TFocus (BinBipole OR_BODY Right F1 G). \n      1-2: LLTensor [u| t_bin OR F1 G|] x0.\n      1: simpl; LLPlusL; LLRelease; LLStore.\n      2: simpl; LLPlusR; LLRelease; LLStore.\n      1-2: apply AbsorptionLSet'...\n      1,3 : apply setTCEncode...\n      1-2 : rewrite secCEncode.\n      applyCutC H9 Hj.\n      applyCutC H9 Hj.\n      \n      checkPermutationCases H12.\n      { (** OR Right is principal *)\n          clear H11.\n          inversion H2...\n          (* Analizing the derivation on the right *)     \n          - (* Constants Case *) \n             inversion H1...\n3:{ \n      apply BipoleReasoning in H5...\n      inversion H12...\n      solveF.\n      inversion H12...\n      solveF. }\n    3:{\n      apply BipoleReasoning in H5...\n      Bipole FF Left.\n      LLTensor [d| t_cons FF | ] (M++x1).\n      rewrite H13...\n      simpl. solveLL.\n      checkPermutationCases H14.\n      Bipole FF Left.\n      LLTensor (@nil oo) (M++N). \n      solveLL... \n      simpl. solveLL. }\n     2:{ \n      apply BipoleReasoning in H5...\n      inversion H12...\n      solveF.\n      inversion H12...\n      solveF. }\n      \n      apply BipoleReasoning in H5...\n      Bipole TT Right.\n      LLTensor [u| t_cons TT |] (M++x1).\n      rewrite H13...\n      simpl...       \n                 checkPermutationCases H14.  \n                Bipole TT Right.\n                LLTensor (@nil oo) (M++N).\n                solveLL... \n                simpl...\n          - inversion H1...\n            (* Connectives Case *) \n            -- apply BipoleReasoning in H5...\n                simpl in H13.\n                permuteANDRight.\n                applyCutC Hi H12.\n                applyCutC Hi H14.\n                checkPermutationCases H14.\n                apply FocusingWith in H12...\n                TFocus (BinBipole AND_BODY Right F G0).\n                LLTensor (@nil oo) (M++N).\n                solveLL...\n                simpl.\n                LLRelease. LLWith. 1-2: LLStore.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H16.\n            -- apply BipoleReasoning in H5...\n                simpl in H13.\n                permuteANDLeft.\n                applyCutC Hi H11.\n                applyCutC Hi H11.\n                 checkPermutationCases H14.\n                apply FocusingPlus in H12...\n                all:TFocus (BinBipole AND_BODY Left F G0).\n                all:LLTensor (@nil oo) (M++N).\n                all:solveLL...\n                1-2: simpl.\n                1: LLPlusL; LLRelease; LLStore.\n                2: LLPlusR; LLRelease; LLStore.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H14.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H14.\n            -- apply BipoleReasoning in H5...\n                simpl in H13.\n                permuteORRight.\n                applyCutC Hi H11.\n                applyCutC Hi H11.\n                 checkPermutationCases H14.\n                apply FocusingPlus in H12...\n                all:TFocus (BinBipole OR_BODY Right F G0).\n                all:LLTensor (@nil oo) (M++N).\n                all:solveLL...\n                all: simpl.\n                1: LLPlusL; LLRelease; LLStore.\n                2: LLPlusR; LLRelease; LLStore.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H14.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H14.           \n            -- apply BipoleReasoning in H5...\n                simpl in H13.\n                permuteORLeft.\n                applyCutC Hi H12.\n                applyCutC Hi H14.\n                checkPermutationCases H14.\n\n           { clear H13.\n                    \n           apply @PosNegSetT' with (a:=a)...\n           1-2: intro;intros...\n           rewrite <- (app_nil_r []).\n           \n           eapply GeneralCut' with (C:=dual ((OR_BODY.(rb_leftBody) F1 G)))...\n           rewrite <- (app_nil_r []).\n           eapply GeneralCut' with (C:=dual ((OR_BODY.(rb_rightBody) F1 G)))...\n             \n           inversion lngF...\n           eapply WeakTheory with (th:=(CUTLN (max n1 n2))).\n           intros.\n           apply TheoryEmb2.\n           refine(CuteRuleN H5 _)...\n           apply weakeningAll...\n                    \n           apply OR_CUTCOHERENT... \n           \n           simpl.\n           apply FocusingWith in H12...\n           apply FocusingPlus in H10...\n           1: LLPlusL; LLRelease; LLStore. \n           2: LLPlusR; LLRelease; LLStore.  \n           1-2: apply AbsorptionLSet'...\n           1,3: apply setTCEncode...\n           1-2: apply AbsorptionLSet'...\n           1,3: apply setTCEncode...\n           1-2: rewrite !secCEncode.\n           1-2: simpl; rewrite app_comm_cons. \n           1-2: applyCutC H8 Hj.\n           \n           simpl.\n           apply FocusingWith in H12...\n           LLRelease. \n           LLWith. \n           1-2: LLStore.\n           1-2: apply AbsorptionLSet'...\n           1,3: apply setTCEncode...\n           1-2: apply AbsorptionLSet'...\n           1,3: apply setTCEncode...\n           1-2: rewrite !secCEncode.\n           1-2: simpl; rewrite <- Permutation_midle. \n           applyCutC Hi H9.\n           applyCutC Hi H12.        }                \n                \n                apply FocusingWith in H12...\n                TFocus (BinBipole OR_BODY Left F G0).\n                LLTensor (@nil oo) (M++N).\n                solveLL...\n                simpl.\n                LLRelease. LLWith. 1-2: LLStore.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H16.\n            -- apply BipoleReasoning in H5...\n                simpl in H13.\n                \n      match goal with \n    | [ H1 : seqN _ _ _ _ (DW (rb_rightBody _ _)) ,\n        H2 : Permutation ?N (u| t_bin IMP ?F ?G | :: ?x)\n        |- seq _ _ (?M ++ ?N) (UP []) ] => \n        \n        apply FocusingPar in H1;sauto;\n        TFocus (BinBipole IMP_BODY Right F G); \n        simpl;\n        LLTensor [u| t_bin IMP F G |] (M++x);[\n        rewrite H2;sauto |  solveLL;do 2 LLStore;\n        rewrite <- PermutConsApp;\n            rewrite <-  Permutation_midle;\n            rewrite perm_swap\n             ]\n   end.\n    applyCutC Hi H11.\n    OLSolve.\n   checkPermutationCases H14. \n\n   match goal with \n    | [ H1 : seqN _ _ _ _ (DW (rb_rightBody _ _)) ,\n        H2 : Permutation ?Cx ((?i, u| t_bin IMP ?F ?G |) :: ?x) \n         |- seq _ ?Cx (?M ++ ?N) (UP []) ] => \n        \n        apply FocusingPar in H1;sauto;\n        TFocus (BinBipole IMP_BODY Right F G); \n        simpl;\n        LLTensor (@nil oo) (M++N);[\n        solveLL;sauto |  solveLL;do 2 LLStore;\n        rewrite <- PermutConsApp;\n            rewrite <-  Permutation_midle;\n            rewrite perm_swap\n             ]\n           \n            end.\n        applyCutC Hi H14.\n            \n            -- apply BipoleReasoning in H5...\n                apply FocusingTensor in H12...\n                simpl in H13.\n                PosNegAll a...\n                1-2: intro; intros...\n                rewrite CEncodeApp.\n                LLPerm (CEncode a N ++ (CEncode a M ++ L)).      \n               apply  AbsorptionLSet'...\n               apply setTCEncode...\n               rewrite secCEncode.\n               assert(IsPositiveAtomFormulaL x1) by OLSolve.\n                TFocus (BinBipole IMP_BODY Left F G0). \n                simpl.\n                LLTensor [d| t_bin IMP F G0 | ] x1.\n                LLTensor x3 x4. \n                1-2: LLRelease; LLStore.\n                1-2: apply  AbsorptionLSet'...\n                1,3: apply setTCEncode...\n                1-2: rewrite secCEncode.\n                1-2: rewrite Permutation_app_comm.\n                applyCutC Hi H11.\n                applyCutC Hi H15.\n                \n                checkPermutationCases H14.\n                apply FocusingTensor in H12...\n                PosNegAll a...\n                1-2: intro; intros...\n                rewrite CEncodeApp.\n                LLPerm (CEncode a N ++ (CEncode a M ++ L)).      \n               apply  AbsorptionLSet'...\n               apply setTCEncode...\n               rewrite secCEncode.\n               \n                TFocus (BinBipole IMP_BODY Left F G0). \n                simpl.\n                LLTensor (@nil oo) N.\n                apply weakeningGen. \n                apply allSeTU... \n                solveLL.\n                LLTensor x5 x6. \n                1-2: LLRelease; LLStore.\n                1-2: apply  AbsorptionLSet'...\n                1,3: apply setTCEncode...\n                1-2: rewrite secCEncode.\n                1-2: rewrite Permutation_app_comm.\n                applyCutC Hi H14.\n                applyCutC Hi H17.\n          - (* INIT Case *)        \n             apply FocusingInitRuleU in H5...\n             PosNegAll a...\n             1-2: intro; intros...\n             rewrite CEncodeApp.\n             LLPerm (CEncode a N ++ (CEncode a M ++ L)).      \n                 \n              apply  AbsorptionLSet'...\n               apply setTCEncode...\n               rewrite secCEncode.\n               TFocus (RINIT OO).\n                LLTensor [u| OO |] [d| OO |].\n                checkPermutationCases H11.\n                clear H8.\n                rewrite Permutation_app_comm...\n                simpl.\n                PosNeg a.\n                intro; intros...\n                simpl.\n                apply seqNtoSeq in Hi.\n               refine (WeakTheory _ _ Hi)...\n               apply TheoryEmb1.\n               rewrite Permutation_app_comm.\n               apply WeakPosNeg with (a:=a)...\n               1-2: intro; intros...\n               TFocus (RINIT OO).\n                LLTensor [u| OO |] (@nil oo).\n                solveLL.\n                \n                checkPermutationCases H11.\n                rewrite Permutation_app_comm.\n                apply WeakPosNeg with (a:=a)...\n               1-2: intro; intros...\n               TFocus (RINIT OO).\n                LLTensor (@nil oo) [d| OO |] .\n                solveLL.\n                \n                checkPermutationCases H11.\n                checkPermutationCases H5.\n                rewrite H11.\n                TFocus (NEG (t_bin OR F1 G) a).\n                inversion H4...\n                LLTensor (@nil oo) M;[solveLL | ].\n                LLRelease. LLStoreC.\n                rewrite <- H11.\n               apply seqNtoSeq in Hi.\n               refine (WeakTheory _ _ Hi)...\n               apply TheoryEmb1.\n               rewrite <- (app_nil_l M).\n               apply WeakPosNeg with (a:=a)...\n               1-2: intro; intros...\n               TFocus (RINIT OO).\n                LLTensor (@nil oo) (@nil oo).\n                solveLL. solveLL.\n         - (* Quantifiers Case *)        \n            inversion H1...\n            -- apply BipoleReasoning in H5...\n                simpl in H14.\n                permuteALLRight.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                solveQF.\n                checkPermutationCases H15.\n                symmetry in H11.\n                permuteALLRight.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H17.\n                solveQF.\n            -- apply BipoleReasoning in H5...\n                simpl in H14.\n                permuteALLLeft.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                solveQF.\n                checkPermutationCases H15.\n                symmetry in H11.\n                permuteALLLeft.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H17.\n                solveQF.\n            -- apply BipoleReasoning in H5...\n                simpl in H14.\n                permuteSOMERight.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                solveQF.\n                checkPermutationCases H15.\n                symmetry in H11.\n                permuteSOMERight.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H17.\n                solveQF.\n            -- apply BipoleReasoning in H5...\n                simpl in H14.\n                permuteSOMELeft.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                solveQF.\n                checkPermutationCases H15.\n                symmetry in H11.\n                permuteSOMELeft.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H17.\n                solveQF.\n         - (* POS Case *)                    \n            apply BipoleReasoning in H5...\n            apply FocusingQuest in H11...\n            TFocus (POS OO a).\n            LLTensor [d| OO |] (M++x1).\n            rewrite H12...\n            LLRelease. LLStoreC.\n            eapply weakeningN with (F:=(a, d| OO |)) in Hi...\n            LLSwapC H8.\n            LLSwapC Hi.\n            applyCutC Hi H8.\n            apply allU.\n            checkPermutationCases H13.\n            apply FocusingQuest in H11...\n            eapply contractionN in H7...\n            applyCutC Hi H7.\n            apply allU.\n            \n            apply FocusingQuest in H11...\n            TFocus (POS OO a).\n            LLTensor (@nil oo) (M++N).\n            solveLL.\n            LLRelease. LLStoreC.\n            eapply weakeningN with (F:=(a, d| OO |)) in Hi...\n            LLSwapC H13.\n            LLSwapC Hi.\n            applyCutC Hi H13.\n            apply allU.\n         - (* NEG Case *)     \n            apply BipoleReasoning in H5...\n            apply FocusingQuest in H11...\n            TFocus (NEG OO a).\n            LLTensor [u| OO |] (M++x1).\n            rewrite H12...\n            LLRelease. LLStoreC.\n            eapply weakeningN with (F:=(a, u| OO |)) in Hi...\n            LLSwapC H8.\n            LLSwapC Hi.\n            applyCutC Hi H8.\n            apply allU.\n            checkPermutationCases H13.\n            apply FocusingQuest in H11...\n            TFocus (NEG OO a).\n            LLTensor (@nil oo) (M++N).\n            solveLL.\n            LLRelease. LLStoreC.\n            eapply weakeningN with (F:=(a, u| OO |)) in Hi...\n            LLSwapC H13.\n            LLSwapC Hi.\n            applyCutC Hi H13.\n            apply allU.  }\n      \n      apply FocusingPlus in H10...\n      1-2: TFocus (BinBipole OR_BODY Right F1 G). \n      1-2: LLTensor (@nil oo) (M++N).\n      1,3: solveLL...\n      1: simpl; LLPlusL; LLRelease; LLStore.\n      2: simpl; LLPlusR; LLRelease; LLStore.\n      rewrite app_comm_cons.\n      applyCutC H12 Hj.\n      rewrite app_comm_cons.\n      applyCutC H12 Hj.      \n     ** \n      apply BipoleReasoning in H1...\n      apply FocusingWith in H10...\n      PosNegAll a...\n      1-2: intro; intros...\n      rewrite CEncodeApp.\n      rewrite app_assoc_reverse.\n      apply AbsorptionLSet'...\n               apply setTCEncode...\n               rewrite secCEncode.\n      TFocus (BinBipole OR_BODY Left F1 G). \n      LLTensor [d| t_bin OR F1 G|] x0.\n      simpl. LLRelease. LLWith.\n      1-2: LLStore.\n      1-2: apply AbsorptionLSet'...\n      1,3 : apply setTCEncode...\n      1-2 : rewrite secCEncode.\n      applyCutC H10 Hj.\n      applyCutC H12 Hj.\n     \n      checkPermutationCases H12.\n      apply FocusingWith in H10...\n      TFocus (BinBipole OR_BODY Left F1 G). \n      simpl.\n      LLTensor (@nil oo) (M++N).\n      solveLL...\n      LLRelease.\n      LLWith. 1-2: LLStore.\n      rewrite app_comm_cons.\n      applyCutC H13 Hj.\n      rewrite app_comm_cons.\n      applyCutC H14 Hj.\n      ** (* 5/6 - IMP Right *)\n      apply BipoleReasoning in H1...\n      apply FocusingPar in H10...\n      TFocus (BinBipole IMP_BODY Right F1 G).\n      LLTensor [u| t_bin IMP F1 G |] (x0++N).\n      rewrite H11...\n      simpl. LLRelease. LLPar. do 2 LLStore.\n      do 2 rewrite app_comm_cons.\n      applyCutC H9 Hj.\n      OLSolve.\n      \n      checkPermutationCases H12.\n      { (** IMP Right is principal *)\n          clear H11.\n          inversion H2...\n          (* Analizing the derivation on the right *)     \n          - (* Constants Case *) \n             inversion H1...\n3:{ \n      apply BipoleReasoning in H5...\n      inversion H12...\n      solveF.\n      inversion H12...\n      solveF. }\n    3:{\n      apply BipoleReasoning in H5...\n      Bipole FF Left.\n      LLTensor [d| t_cons FF | ] (M++x1).\n      rewrite H13...\n      simpl. solveLL.\n      checkPermutationCases H14.\n      Bipole FF Left.\n      LLTensor (@nil oo) (M++N). \n      solveLL... \n      simpl. solveLL. }\n     2:{ \n      apply BipoleReasoning in H5...\n      inversion H12...\n      solveF.\n      inversion H12...\n      solveF. }\n      \n      apply BipoleReasoning in H5...\n      Bipole TT Right.\n      LLTensor [u| t_cons TT |] (M++x1).\n      rewrite H13...\n      simpl...       \n                 checkPermutationCases H14.  \n                Bipole TT Right.\n                LLTensor (@nil oo) (M++N).\n                solveLL... \n                simpl...\n              \n          - inversion H1...\n            (* Connectives Case *) \n            -- apply BipoleReasoning in H5...\n                simpl in H13.\n                permuteANDRight.\n                applyCutC Hi H12.\n                applyCutC Hi H14.\n                checkPermutationCases H14.\n                apply FocusingWith in H12...\n                TFocus (BinBipole AND_BODY Right F G0).\n                LLTensor (@nil oo) (M++N).\n                solveLL...\n                simpl.\n                LLRelease. LLWith. 1-2: LLStore.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H16.\n            -- apply BipoleReasoning in H5...\n                simpl in H13.\n                permuteANDLeft.\n                applyCutC Hi H11.\n                applyCutC Hi H11.\n                 checkPermutationCases H14.\n                apply FocusingPlus in H12...\n                all:TFocus (BinBipole AND_BODY Left F G0).\n                all:LLTensor (@nil oo) (M++N).\n                all:solveLL...\n                1-2: simpl.\n                1: LLPlusL; LLRelease; LLStore.\n                2: LLPlusR; LLRelease; LLStore.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H14.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H14.\n            -- apply BipoleReasoning in H5...\n                simpl in H13.\n                permuteORRight.\n                applyCutC Hi H11.\n                applyCutC Hi H11.\n                 checkPermutationCases H14.\n                apply FocusingPlus in H12...\n                all:TFocus (BinBipole OR_BODY Right F G0).\n                all:LLTensor (@nil oo) (M++N).\n                all:solveLL...\n                all: simpl.\n                1: LLPlusL; LLRelease; LLStore.\n                2: LLPlusR; LLRelease; LLStore.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H14.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H14.           \n            -- apply BipoleReasoning in H5...\n                simpl in H13.\n                permuteORLeft.\n                applyCutC Hi H12.\n                applyCutC Hi H14.\n                checkPermutationCases H14.\n                apply FocusingWith in H12...\n                TFocus (BinBipole OR_BODY Left F G0).\n                LLTensor (@nil oo) (M++N).\n                solveLL...\n                simpl.\n                LLRelease. LLWith. 1-2: LLStore.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H16.\n            -- apply BipoleReasoning in H5...\n                simpl in H13.\n                \n      match goal with \n    | [ H1 : seqN _ _ _ _ (DW (rb_rightBody _ _)) ,\n        H2 : Permutation ?N (u| t_bin IMP ?F ?G | :: ?x)\n        |- seq _ _ (?M ++ ?N) (UP []) ] => \n        \n        apply FocusingPar in H1;sauto;\n        TFocus (BinBipole IMP_BODY Right F G); \n        simpl;\n        LLTensor [u| t_bin IMP F G |] (M++x);[\n        rewrite H2;sauto |  solveLL;do 2 LLStore;\n        rewrite <- PermutConsApp;\n            rewrite <-  Permutation_midle;\n            rewrite perm_swap\n             ]\n   end.\n    applyCutC Hi H11.\n    OLSolve.\n   checkPermutationCases H14. \n\n   match goal with \n    | [ H1 : seqN _ _ _ _ (DW (rb_rightBody _ _)) ,\n        H2 : Permutation ?Cx ((?i, u| t_bin IMP ?F ?G |) :: ?x) \n         |- seq _ ?Cx (?M ++ ?N) (UP []) ] => \n        \n        apply FocusingPar in H1;sauto;\n        TFocus (BinBipole IMP_BODY Right F G); \n        simpl;\n        LLTensor (@nil oo) (M++N);[\n        solveLL;sauto |  solveLL;do 2 LLStore;\n        rewrite <- PermutConsApp;\n            rewrite <-  Permutation_midle;\n            rewrite perm_swap\n             ]\n           \n            end.\n        applyCutC Hi H14.\n            \n            -- apply BipoleReasoning in H5...\n                apply FocusingTensor in H12...\n                simpl in H13.\n                PosNegAll a...\n                1-2: intro; intros...\n                rewrite CEncodeApp.\n                LLPerm (CEncode a N ++ (CEncode a M ++ L)).      \n               apply  AbsorptionLSet'...\n               apply setTCEncode...\n               rewrite secCEncode.\n               assert(IsPositiveAtomFormulaL x1) by OLSolve.\n                TFocus (BinBipole IMP_BODY Left F G0). \n                simpl.\n                LLTensor [d| t_bin IMP F G0 | ] x1.\n                LLTensor x3 x4. \n                1-2: LLRelease; LLStore.\n                1-2: apply  AbsorptionLSet'...\n                1,3: apply setTCEncode...\n                1-2: rewrite secCEncode.\n                1-2: rewrite Permutation_app_comm.\n                applyCutC Hi H11.\n                applyCutC Hi H15.\n                \n                checkPermutationCases H14.\n \n           { clear H13.\n                    \n           apply @PosNegSetT' with (a:=a)...\n           1-2: intro;intros...\n           rewrite <- (app_nil_r []).\n           \n           eapply GeneralCut' with (C:=dual ((IMP_BODY.(rb_leftBody) F1 G)))...\n           rewrite <- (app_nil_r []).\n           eapply GeneralCut' with (C:=dual ((IMP_BODY.(rb_rightBody) F1 G)))...\n             \n           inversion lngF...\n           eapply WeakTheory with (th:=(CUTLN (max n1 n2))).\n           intros.\n           apply TheoryEmb2.\n           refine(CuteRuleN H5 _)...\n           apply weakeningAll...\n                    \n           apply IMP_CUTCOHERENT... \n           \n           simpl.\n           apply FocusingPar in H10...\n           LLRelease; LLPar.\n           do 2 LLStore. \n           apply AbsorptionLSet'...\n           apply setTCEncode...\n           apply AbsorptionLSet'...\n           apply setTCEncode...\n           rewrite !secCEncode.\n           simpl; do 2 rewrite app_comm_cons. \n           applyCutC H8 Hj.\n           \n           simpl.\n           apply FocusingTensor in H12...\n           LLTensor; LLRelease;LLStore. \n           1-2: apply AbsorptionLSet'...\n           1,3: apply setTCEncode...\n           1-2: rewrite !secCEncode.\n           1-2: srewrite H9; rewrite map_app.\n           1-2: rewrite app_assoc_reverse.\n          \n           1: rewrite Permutation_app_swap_app.\n           1-2: apply weakeningGen...\n           \n           1-2: apply AbsorptionLSet'...\n           1,3: apply setTCEncode...\n           1-2: rewrite !secCEncode.\n           1-2: simpl; rewrite <- Permutation_midle. \n           applyCutC Hi H8.\n           applyCutC Hi H13.        }                  \n              \n                apply FocusingTensor in H12...\n                PosNegAll a...\n                1-2: intro; intros...\n                rewrite CEncodeApp.\n                LLPerm (CEncode a N ++ (CEncode a M ++ L)).      \n               apply  AbsorptionLSet'...\n               apply setTCEncode...\n               rewrite secCEncode.\n               \n                TFocus (BinBipole IMP_BODY Left F G0). \n                simpl.\n                LLTensor (@nil oo) N.\n                apply weakeningGen. \n                apply allSeTU... \n                solveLL.\n                LLTensor x5 x6. \n                1-2: LLRelease; LLStore.\n                1-2: apply  AbsorptionLSet'...\n                1,3: apply setTCEncode...\n                1-2: rewrite secCEncode.\n                1-2: rewrite Permutation_app_comm.\n                applyCutC Hi H14.\n                applyCutC Hi H17.\n          - (* INIT Case *)        \n             apply FocusingInitRuleU in H5...\n             PosNegAll a...\n             1-2: intro; intros...\n             rewrite CEncodeApp.\n             LLPerm (CEncode a N ++ (CEncode a M ++ L)).      \n                 \n              apply  AbsorptionLSet'...\n               apply setTCEncode...\n               rewrite secCEncode.\n               TFocus (RINIT OO).\n                LLTensor [u| OO |] [d| OO |].\n                checkPermutationCases H11.\n                clear H8.\n                rewrite Permutation_app_comm...\n                simpl.\n                PosNeg a.\n                intro; intros...\n                simpl.\n                apply seqNtoSeq in Hi.\n               refine (WeakTheory _ _ Hi)...\n               apply TheoryEmb1.\n               rewrite Permutation_app_comm.\n               apply WeakPosNeg with (a:=a)...\n               1-2: intro; intros...\n               TFocus (RINIT OO).\n                LLTensor [u| OO |] (@nil oo).\n                solveLL.\n                \n                checkPermutationCases H11.\n                rewrite Permutation_app_comm.\n                apply WeakPosNeg with (a:=a)...\n               1-2: intro; intros...\n               TFocus (RINIT OO).\n                LLTensor (@nil oo) [d| OO |] .\n                solveLL.\n                \n                checkPermutationCases H11.\n                checkPermutationCases H5.\n                rewrite H11.\n                TFocus (NEG (t_bin IMP F1 G) a).\n                inversion H4...\n                LLTensor (@nil oo) M;[solveLL | ].\n                LLRelease. LLStoreC.\n                rewrite <- H11.\n               apply seqNtoSeq in Hi.\n               refine (WeakTheory _ _ Hi)...\n               apply TheoryEmb1.\n               rewrite <- (app_nil_l M).\n               apply WeakPosNeg with (a:=a)...\n               1-2: intro; intros...\n               TFocus (RINIT OO).\n                LLTensor (@nil oo) (@nil oo).\n                solveLL. solveLL.\n         - (* Quantifiers Case *)        \n            inversion H1...\n            -- apply BipoleReasoning in H5...\n                simpl in H14.\n                permuteALLRight.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                solveQF.\n                checkPermutationCases H15.\n                symmetry in H11.\n                permuteALLRight.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H17.\n                solveQF.\n            -- apply BipoleReasoning in H5...\n                simpl in H14.\n                permuteALLLeft.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                solveQF.\n                checkPermutationCases H15.\n                symmetry in H11.\n                permuteALLLeft.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H17.\n                solveQF.\n            -- apply BipoleReasoning in H5...\n                simpl in H14.\n                permuteSOMERight.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                solveQF.\n                checkPermutationCases H15.\n                symmetry in H11.\n                permuteSOMERight.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H17.\n                solveQF.\n            -- apply BipoleReasoning in H5...\n                simpl in H14.\n                permuteSOMELeft.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                solveQF.\n                checkPermutationCases H15.\n                symmetry in H11.\n                permuteSOMELeft.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H17.\n                solveQF.\n         - (* POS Case *)                    \n            apply BipoleReasoning in H5...\n            apply FocusingQuest in H11...\n            TFocus (POS OO a).\n            LLTensor [d| OO |] (M++x1).\n            rewrite H12...\n            LLRelease. LLStoreC.\n            eapply weakeningN with (F:=(a, d| OO |)) in Hi...\n            LLSwapC H8.\n            LLSwapC Hi.\n            applyCutC Hi H8.\n            apply allU.\n            checkPermutationCases H13.\n            apply FocusingQuest in H11...\n            eapply contractionN in H7...\n            applyCutC Hi H7.\n            apply allU.\n            \n            apply FocusingQuest in H11...\n            TFocus (POS OO a).\n            LLTensor (@nil oo) (M++N).\n            solveLL.\n            LLRelease. LLStoreC.\n            eapply weakeningN with (F:=(a, d| OO |)) in Hi...\n            LLSwapC H13.\n            LLSwapC Hi.\n            applyCutC Hi H13.\n            apply allU.\n         - (* NEG Case *)     \n            apply BipoleReasoning in H5...\n            apply FocusingQuest in H11...\n            TFocus (NEG OO a).\n            LLTensor [u| OO |] (M++x1).\n            rewrite H12...\n            LLRelease. LLStoreC.\n            eapply weakeningN with (F:=(a, u| OO |)) in Hi...\n            LLSwapC H8.\n            LLSwapC Hi.\n            applyCutC Hi H8.\n            apply allU.\n            checkPermutationCases H13.\n            apply FocusingQuest in H11...\n            TFocus (NEG OO a).\n            LLTensor (@nil oo) (M++N).\n            solveLL.\n            LLRelease. LLStoreC.\n            eapply weakeningN with (F:=(a, u| OO |)) in Hi...\n            LLSwapC H13.\n            LLSwapC Hi.\n            applyCutC Hi H13.\n            apply allU.  }\n            \n            \n      apply FocusingPar in H10...\n      TFocus (BinBipole IMP_BODY Right F1 G). \n      simpl.\n      LLTensor (@nil oo) (M++N).\n      solveLL...\n      LLRelease.\n      LLPar. do 2 LLStore.\n      do 2 rewrite app_comm_cons.\n      applyCutC H12 Hj.\n      \n      ** (* 2/6 - IMP LEFT *)\n      apply BipoleReasoning in H1...\n      PosNegAll a...\n      1-2: intro; intros...\n      rewrite CEncodeApp.\n      rewrite app_assoc_reverse.\n      apply AbsorptionLSet'...\n               apply setTCEncode...\n               rewrite secCEncode.\n      apply FocusingTensor in H10...\n      \n      assert(IsPositiveAtomFormulaL x0) by OLSolve.\n      TFocus (BinBipole IMP_BODY Left F1 G). \n      LLTensor [d| t_bin IMP F1 G|] x0.\n      simpl; LLTensor x2 x3; LLRelease; LLStore.\n      1-2: apply AbsorptionLSet'...\n      1,3 : apply setTCEncode...\n      1-2 : rewrite secCEncode.\n      applyCutC H9 Hj.\n      applyCutC H13 Hj.\n      \n      checkPermutationCases H12.\n\n      PosNegAll a...\n      1-2: intro; intros...\n      rewrite CEncodeApp.\n      rewrite app_assoc_reverse.\n      apply AbsorptionLSet'...\n               apply setTCEncode...\n               rewrite secCEncode.\n      apply FocusingTensor in H10...\n      \n      TFocus (BinBipole IMP_BODY Left F1 G). \n      LLTensor (@nil oo) M. \n      apply weakeningGen... solveLL...\n      LLTensor x4 x5; LLRelease; LLStore.\n      1-2: apply AbsorptionLSet'...\n      1,3 : apply setTCEncode...\n      1-2 : rewrite secCEncode.\n      applyCutC H12 Hj.\n      applyCutC H15 Hj.\n    \n   * (* 3/6 - INIT *) \n   apply FocusingInitRuleU in H1...\n             PosNegAll a...\n             1-2: intro; intros...\n             rewrite CEncodeApp.\n             LLPerm (CEncode a M ++ (CEncode a N ++ L)).      \n                 \n             apply  AbsorptionLSet'...\n             apply setTCEncode...\n             rewrite secCEncode.\n             TFocus (RINIT OO).\n             LLTensor [u| OO |] [d| OO |].\n             \n                checkPermutationCases H9.\n                \n               apply WeakPosNeg with (a:=a)...\n               1-2: intro; intros...\n               TFocus (RINIT OO).\n                LLTensor [u| OO |] (@nil oo).\n                solveLL.\n               \n                checkPermutationCases H9.\n           \n                { clear H8.\n                   simpl. \n                   PosNeg a.\n                   intro; intros...\n                   simpl...\n                   apply seqNtoSeq in Hj.\n               refine (WeakTheory _ _ Hj)...\n               apply TheoryEmb1. }\n               \n                \n                apply WeakPosNeg with (a:=a)...\n               1-2: intro; intros...\n               TFocus (RINIT OO).\n                LLTensor (@nil oo) [d| OO |] .\n                solveLL.\n                \n                checkPermutationCases H7.\n                checkPermutationCases H9.\n                rewrite H7.\n                apply contraction with (F:=(x, d| FC |))...\n                apply allU.\n                rewrite <- H7.\n                eapply PosFS with (a:=a)...\n                intro;intros...\n               apply seqNtoSeq in Hj.\n               refine (WeakTheory _ _ Hj)...\n               apply TheoryEmb1.\n               \n               \n               rewrite <- (app_nil_l N).\n               apply WeakPosNeg with (a:=a)...\n               1-2: intro; intros...\n               TFocus (RINIT OO).\n                LLTensor (@nil oo) (@nil oo).\n                solveLL. solveLL.\n  \n   * (* 4/6 - QUANTIFIERS *)  \n      inversion H6...\n      ** (* 1/4 - ALL Right *)\n      apply BipoleReasoning in H1...\n      TFocus (QuBipole ALL_BODY Right FX). \n      LLTensor [u| t_quant ALL FX|] (x0++N).\n      rewrite H12...\n      simpl; LLRelease; LLForall. \n      solveUniform. LLStore.\n      apply FocusingForallUP with (y:=x1) in H11...\n      rewrite app_comm_cons.\n      applyCutC H11 Hj.\n      solveQF.\n      \n      checkPermutationCases H13.\n      { (** ALL Right is principal *)\n          clear H12.\n          inversion H2...\n          (* Analizing the derivation on the right *)     \n          - (* Constants Case *) \n             inversion H1...\n3:{ \n      apply BipoleReasoning in H5...\n      inversion H13...\n      solveF.\n      inversion H13...\n      solveF. }\n    3:{\n      apply BipoleReasoning in H5...\n      Bipole FF Left.\n      LLTensor [d| t_cons FF | ] (M++x1).\n      rewrite H14...\n      simpl. solveLL.\n      checkPermutationCases H15.\n      Bipole FF Left.\n      LLTensor (@nil oo) (M++N). \n      solveLL... \n      simpl. solveLL. }\n     2:{ \n      apply BipoleReasoning in H5...\n      inversion H13...\n      solveF.\n      inversion H13...\n      solveF. }\n      \n      apply BipoleReasoning in H5...\n      Bipole TT Right.\n      LLTensor [u| t_cons TT |] (M++x1).\n      rewrite H14...\n      simpl...       \n      \n                 checkPermutationCases H15.  \n                Bipole TT Right.\n                LLTensor (@nil oo) (M++N).\n                solveLL... \n                simpl...\n          - inversion H1...\n            (* Connectives Case *) \n            -- apply BipoleReasoning in H5...\n                simpl in H14.\n                permuteANDRight.\n                applyCutC Hi H13.\n                applyCutC Hi H15.\n                checkPermutationCases H15.\n                apply FocusingWith in H13...\n                TFocus (BinBipole AND_BODY Right F G).\n                LLTensor (@nil oo) (M++N).\n                solveLL...\n                simpl.\n                LLRelease. LLWith. 1-2: LLStore.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H16.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H17.\n            -- apply BipoleReasoning in H5...\n                simpl in H14.\n                permuteANDLeft.\n                applyCutC Hi H12.\n                applyCutC Hi H12.\n                 checkPermutationCases H15.\n                apply FocusingPlus in H13...\n                all:TFocus (BinBipole AND_BODY Left F G).\n                all:LLTensor (@nil oo) (M++N).\n                all:solveLL...\n                1-2: simpl.\n                1: LLPlusL; LLRelease; LLStore.\n                2: LLPlusR; LLRelease; LLStore.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n            -- apply BipoleReasoning in H5...\n                simpl in H14.\n                permuteORRight.\n                applyCutC Hi H12.\n                applyCutC Hi H12.\n                 checkPermutationCases H15.\n                apply FocusingPlus in H13...\n                all:TFocus (BinBipole OR_BODY Right F G).\n                all:LLTensor (@nil oo) (M++N).\n                all:solveLL...\n                all: simpl.\n                1: LLPlusL; LLRelease; LLStore.\n                2: LLPlusR; LLRelease; LLStore.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.           \n            -- apply BipoleReasoning in H5...\n                simpl in H14.\n                permuteORLeft.\n                applyCutC Hi H13.\n                applyCutC Hi H15.\n                checkPermutationCases H15.\n        \n                apply FocusingWith in H13...\n                TFocus (BinBipole OR_BODY Left F G).\n                LLTensor (@nil oo) (M++N).\n                solveLL...\n                simpl.\n                LLRelease. LLWith. 1-2: LLStore.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H16.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H17.\n            -- apply BipoleReasoning in H5...\n                simpl in H14.\n                \n      match goal with \n    | [ H1 : seqN _ _ _ _ (DW (rb_rightBody _ _)) ,\n        H2 : Permutation ?N (u| t_bin IMP ?F ?G | :: ?x)\n        |- seq _ _ (?M ++ ?N) (UP []) ] => \n        \n        apply FocusingPar in H1;sauto;\n        TFocus (BinBipole IMP_BODY Right F G); \n        simpl;\n        LLTensor [u| t_bin IMP F G |] (M++x);[\n        rewrite H2;sauto |  solveLL;do 2 LLStore;\n        rewrite <- PermutConsApp;\n            rewrite <-  Permutation_midle;\n            rewrite perm_swap\n             ]\n   end.\n    applyCutC Hi H12.\n    OLSolve.\n   checkPermutationCases H15. \n\n   match goal with \n    | [ H1 : seqN _ _ _ _ (DW (rb_rightBody _ _)) ,\n        H2 : Permutation ?Cx ((?i, u| t_bin IMP ?F ?G |) :: ?x) \n         |- seq _ ?Cx (?M ++ ?N) (UP []) ] => \n        \n        apply FocusingPar in H1;sauto;\n        TFocus (BinBipole IMP_BODY Right F G); \n        simpl;\n        LLTensor (@nil oo) (M++N);[\n        solveLL;sauto |  solveLL;do 2 LLStore;\n        rewrite <- PermutConsApp;\n            rewrite <-  Permutation_midle;\n            rewrite perm_swap\n             ]\n           \n            end.\n        applyCutC Hi H15.\n            \n            -- apply BipoleReasoning in H5...\n                apply FocusingTensor in H13...\n                simpl in H14.\n                PosNegAll a...\n                1-2: intro; intros...\n                rewrite CEncodeApp.\n                LLPerm (CEncode a N ++ (CEncode a M ++ L)).      \n               apply  AbsorptionLSet'...\n               apply setTCEncode...\n               rewrite secCEncode.\n               assert(IsPositiveAtomFormulaL x1) by OLSolve.\n                TFocus (BinBipole IMP_BODY Left F G). \n                simpl.\n                LLTensor [d| t_bin IMP F G | ] x1.\n                LLTensor x3 x4. \n                1-2: LLRelease; LLStore.\n                1-2: apply  AbsorptionLSet'...\n                1,3: apply setTCEncode...\n                1-2: rewrite secCEncode.\n                1-2: rewrite Permutation_app_comm.\n                applyCutC Hi H12.\n                applyCutC Hi H16.\n                \n                checkPermutationCases H15.\n                apply FocusingTensor in H13...\n                PosNegAll a...\n                1-2: intro; intros...\n                rewrite CEncodeApp.\n                LLPerm (CEncode a N ++ (CEncode a M ++ L)).      \n               apply  AbsorptionLSet'...\n               apply setTCEncode...\n               rewrite secCEncode.\n               \n                TFocus (BinBipole IMP_BODY Left F G). \n                simpl.\n                LLTensor (@nil oo) N.\n                apply weakeningGen. \n                apply allSeTU... \n                solveLL.\n                LLTensor x5 x6. \n                1-2: LLRelease; LLStore.\n                1-2: apply  AbsorptionLSet'...\n                1,3: apply setTCEncode...\n                1-2: rewrite secCEncode.\n                1-2: rewrite Permutation_app_comm.\n                applyCutC Hi H15.\n                applyCutC Hi H18.\n          - (* INIT Case *)        \n             apply FocusingInitRuleU in H5...\n             PosNegAll a...\n             1-2: intro; intros...\n             rewrite CEncodeApp.\n             LLPerm (CEncode a N ++ (CEncode a M ++ L)).      \n                 \n              apply  AbsorptionLSet'...\n               apply setTCEncode...\n               rewrite secCEncode.\n               TFocus (RINIT OO).\n                LLTensor [u| OO |] [d| OO |].\n                checkPermutationCases H12.\n                clear H9.\n                rewrite Permutation_app_comm...\n                simpl.\n                PosNeg a.\n                intro; intros...\n                simpl.\n                apply seqNtoSeq in Hi.\n               refine (WeakTheory _ _ Hi)...\n               apply TheoryEmb1.\n               rewrite Permutation_app_comm.\n               apply WeakPosNeg with (a:=a)...\n               1-2: intro; intros...\n               TFocus (RINIT OO).\n                LLTensor [u| OO |] (@nil oo).\n                solveLL.\n                \n                checkPermutationCases H12.\n                rewrite Permutation_app_comm.\n                apply WeakPosNeg with (a:=a)...\n               1-2: intro; intros...\n               TFocus (RINIT OO).\n                LLTensor (@nil oo) [d| OO |] .\n                solveLL.\n                \n                checkPermutationCases H12.\n                checkPermutationCases H5.\n      \n      rewrite H12.\n      rewrite Permutation_cons_append.\n      rewrite Permutation_app_comm.\n      eapply contractionSet' with (C2:=x4).\n      1-2:eauto.\n      simpl... \n      rewrite <- H12.\n      apply NwgFS with (a:=a)...\n      intro;intros...\n       apply seqNtoSeq in Hi.\n               refine (WeakTheory _ _ Hi)...\n               apply TheoryEmb1.\n               \n               rewrite <- (app_nil_l M).\n               apply WeakPosNeg with (a:=a)...\n               1-2: intro; intros...\n               TFocus (RINIT (OO)).\n                LLTensor (@nil oo) (@nil oo).\n                solveLL. solveLL...\n        \n         - (* Quantifiers Case *)        \n            inversion H1...\n            -- apply BipoleReasoning in H5...\n                simpl in H15.\n                permuteALLRight.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H16.\n                solveQF.\n                checkPermutationCases H16.\n                symmetry in H12.\n                permuteALLRight.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H18.\n                solveQF.\n            -- apply BipoleReasoning in H5...\n                simpl in H15.\n                permuteALLLeft.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H16.\n                solveQF.\n                checkPermutationCases H16.\n       { clear H15.\n       inversion H8...\n                    inversion lngF...\n                     apply lbindEq in H10...\n                     apply lbindEq in H16...\n                     apply lbindEq in H17...\n                  \n           apply @PosNegSetT' with (a:=a)...\n           1-2: intro;intros...\n           rewrite <- (app_nil_r []).\n           \n           eapply GeneralCut' with (C:=dual (ALL_BODY.(rq_leftBody) FX0)). \n          rewrite <- (app_nil_r []).\n          eapply GeneralCut' with (C:=dual (ALL_BODY.(rq_rightBody) FX)). \n          \n           eapply WeakTheory with (th:=(CUTLN n0)).\n                 intros.\n                 apply TheoryEmb2.\n                 refine(CuteRuleN H5 _)...\n                 apply weakeningAll...  \n                 apply ALL_CUTCOHERENT...\n                 symmetry... \n                 rewrite <- H16...\n                 solveUniform. \n                 intros... \n                 solveQF. \n     \n           \n           simpl.\n           solveLL. LLStore.\n(*            apply FocusingExistsDW in H14. *)\n           eapply FocusingForallUP with (y:=x1) in H11...\n          \n           apply AbsorptionLSet'...\n           apply setTCEncode...\n           apply AbsorptionLSet'...\n           apply setTCEncode...\n           rewrite !secCEncode.\n           simpl; rewrite app_comm_cons.\n           \n    assert(H' : x2 + S (S x0) = x2 + S (S x0)) by auto. \n           refine(CutHC _ _ _ _ _ _ _ _ _ _  H'  _ _ lngF _ _ _ _ H19 Hj);\n           CutTacPOSNEG.\n        solveQF.   \n        \n         simpl.\n         eapply FocusingExistsDW  in H14...\n         LLExists x2.  LLRelease. LLStore.\n         \n           apply AbsorptionLSet'...\n           apply setTCEncode...\n           apply AbsorptionLSet'...\n           apply setTCEncode...\n           rewrite !secCEncode.\n           simpl; rewrite <- Permutation_midle.\n           \n    assert(H' : S (S x) + x1 = S (S x) + x1) by auto. \n           refine(CutHC _ _ _ _ _ _ _ _ _ _  H'  _ _ lngF _ _ _ _ Hi H22);\n           CutTacPOSNEG.\n        solveQF.   \n   }                \n                \n                symmetry in H12.\n                permuteALLLeft.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H18.\n                solveQF.\n            -- apply BipoleReasoning in H5...\n                simpl in H15.\n                permuteSOMERight.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H16.\n                solveQF.\n                checkPermutationCases H16.\n                symmetry in H12.\n                permuteSOMERight.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H18.\n                solveQF.\n            -- apply BipoleReasoning in H5...\n                simpl in H15.\n                permuteSOMELeft.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H16.\n                solveQF.\n                checkPermutationCases H16.\n                symmetry in H12.\n                permuteSOMELeft.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H18.\n                solveQF.\n         - (* POS Case *)                    \n            apply BipoleReasoning in H5...\n            apply FocusingQuest in H12...\n            TFocus (POS OO a).\n            LLTensor [d| OO |] (M++x1).\n            rewrite H13...\n            LLRelease. LLStoreC.\n            eapply weakeningN with (F:=(a, d| OO |)) in Hi...\n            LLSwapC H9.\n            LLSwapC Hi.\n            applyCutC Hi H9.\n            apply allU.\n            checkPermutationCases H14.\n            apply FocusingQuest in H12...\n            eapply contractionN in H8...\n            applyCutC Hi H8.\n            apply allU.\n            \n            apply FocusingQuest in H12...\n            TFocus (POS OO a).\n            LLTensor (@nil oo) (M++N).\n            solveLL.\n            LLRelease. LLStoreC.\n            eapply weakeningN with (F:=(a, d| OO |)) in Hi...\n            LLSwapC H14.\n            LLSwapC Hi.\n            applyCutC Hi H14.\n            apply allU.\n         - (* NEG Case *)     \n            apply BipoleReasoning in H5...\n            apply FocusingQuest in H12...\n            TFocus (NEG OO a).\n            LLTensor [u| OO |] (M++x1).\n            rewrite H13...\n            LLRelease. LLStoreC.\n            eapply weakeningN with (F:=(a, u| OO |)) in Hi...\n            LLSwapC H9.\n            LLSwapC Hi.\n            applyCutC Hi H9.\n            apply allU.\n            checkPermutationCases H14.\n            apply FocusingQuest in H12...\n            TFocus (NEG OO a).\n            LLTensor (@nil oo) (M++N).\n            solveLL.\n            LLRelease. LLStoreC.\n            eapply weakeningN with (F:=(a, u| OO |)) in Hi...\n            LLSwapC H14.\n            LLSwapC Hi.\n            applyCutC Hi H14.\n            apply allU.  }\n             \n      TFocus (QuBipole ALL_BODY Right FX). \n      LLTensor (@nil oo) (M++N).\n      solveLL...\n      simpl; LLRelease; LLForall. \n      solveUniform. LLStore.\n      apply FocusingForallUP with (y:=x3) in H11...\n      rewrite app_comm_cons.\n      applyCutC H14 Hj.\n      solveQF.\n      ** (* 2/4 - ALL Left *)\n      apply BipoleReasoning in H1...\n      TFocus (QuBipole ALL_BODY Left FX). \n      LLTensor [d| t_quant ALL FX|] (x0++N).\n      rewrite H12...\n      apply FocusingExistsDW in H11...\n      \n      simpl; LLExists x2; LLRelease;LLStore. \n      rewrite app_comm_cons.\n      applyCutC H13 Hj.\n      solveQF.\n      \n      checkPermutationCases H13.\n     \n      TFocus (QuBipole ALL_BODY Left FX). \n      LLTensor (@nil oo) (M++N).\n      solveLL...\n      apply FocusingExistsDW in H11...\n      simpl; LLExists x4; LLRelease;LLStore. \n      rewrite app_comm_cons.\n      applyCutC H15 Hj.\n      solveQF.\n** (* 3/4 - SOME Right *)\n      apply BipoleReasoning in H1...\n      TFocus (QuBipole SOME_BODY Right FX). \n      LLTensor [u| t_quant SOME FX|] (x0++N).\n      rewrite H12...\n      apply FocusingExistsUP in H11...\n      \n      simpl; LLExists x2; LLRelease;LLStore. \n      rewrite app_comm_cons.\n      applyCutC H13 Hj.\n      solveQF.\n      \n      checkPermutationCases H13.\n      { (** SOME Right is principal *)\n          clear H12.\n          inversion H2...\n          (* Analizing the derivation on the right *)     \n          - (* Constants Case *) \n             inversion H1...\n3:{ \n      apply BipoleReasoning in H5...\n      inversion H13...\n      solveF.\n      inversion H13...\n      solveF. }\n    3:{\n      apply BipoleReasoning in H5...\n      Bipole FF Left.\n      LLTensor [d| t_cons FF | ] (M++x1).\n      rewrite H14...\n      simpl. solveLL.\n      checkPermutationCases H15.\n      Bipole FF Left.\n      LLTensor (@nil oo) (M++N). \n      solveLL... \n      simpl. solveLL. }\n     2:{ \n      apply BipoleReasoning in H5...\n      inversion H13...\n      solveF.\n      inversion H13...\n      solveF. }\n      \n      apply BipoleReasoning in H5...\n      Bipole TT Right.\n      LLTensor [u| t_cons TT |] (M++x1).\n      rewrite H14...\n      simpl...       \n                 checkPermutationCases H15.  \n                Bipole TT Right.\n                LLTensor (@nil oo) (M++N).\n                solveLL... \n                simpl...\n          - inversion H1...\n            (* Connectives Case *) \n            -- apply BipoleReasoning in H5...\n                simpl in H14.\n                permuteANDRight.\n                applyCutC Hi H13.\n                applyCutC Hi H15.\n                checkPermutationCases H15.\n                apply FocusingWith in H13...\n                TFocus (BinBipole AND_BODY Right F G).\n                LLTensor (@nil oo) (M++N).\n                solveLL...\n                simpl.\n                LLRelease. LLWith. 1-2: LLStore.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H16.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H17.\n            -- apply BipoleReasoning in H5...\n                simpl in H14.\n                permuteANDLeft.\n                applyCutC Hi H12.\n                applyCutC Hi H12.\n                 checkPermutationCases H15.\n                apply FocusingPlus in H13...\n                all:TFocus (BinBipole AND_BODY Left F G).\n                all:LLTensor (@nil oo) (M++N).\n                all:solveLL...\n                1-2: simpl.\n                1: LLPlusL; LLRelease; LLStore.\n                2: LLPlusR; LLRelease; LLStore.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n            -- apply BipoleReasoning in H5...\n                simpl in H14.\n                permuteORRight.\n                applyCutC Hi H12.\n                applyCutC Hi H12.\n                 checkPermutationCases H15.\n                apply FocusingPlus in H13...\n                all:TFocus (BinBipole OR_BODY Right F G).\n                all:LLTensor (@nil oo) (M++N).\n                all:solveLL...\n                all: simpl.\n                1: LLPlusL; LLRelease; LLStore.\n                2: LLPlusR; LLRelease; LLStore.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H15.           \n            -- apply BipoleReasoning in H5...\n                simpl in H14.\n                permuteORLeft.\n                applyCutC Hi H13.\n                applyCutC Hi H15.\n                checkPermutationCases H15.\n        \n                apply FocusingWith in H13...\n                TFocus (BinBipole OR_BODY Left F G).\n                LLTensor (@nil oo) (M++N).\n                solveLL...\n                simpl.\n                LLRelease. LLWith. 1-2: LLStore.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H16.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H17.\n            -- apply BipoleReasoning in H5...\n                simpl in H14.\n                \n      match goal with \n    | [ H1 : seqN _ _ _ _ (DW (rb_rightBody _ _)) ,\n        H2 : Permutation ?N (u| t_bin IMP ?F ?G | :: ?x)\n        |- seq _ _ (?M ++ ?N) (UP []) ] => \n        \n        apply FocusingPar in H1;sauto;\n        TFocus (BinBipole IMP_BODY Right F G); \n        simpl;\n        LLTensor [u| t_bin IMP F G |] (M++x);[\n        rewrite H2;sauto |  solveLL;do 2 LLStore;\n        rewrite <- PermutConsApp;\n            rewrite <-  Permutation_midle;\n            rewrite perm_swap\n             ]\n   end.\n    applyCutC Hi H12.\n    OLSolve.\n   checkPermutationCases H15. \n\n   match goal with \n    | [ H1 : seqN _ _ _ _ (DW (rb_rightBody _ _)) ,\n        H2 : Permutation ?Cx ((?i, u| t_bin IMP ?F ?G |) :: ?x) \n         |- seq _ ?Cx (?M ++ ?N) (UP []) ] => \n        \n        apply FocusingPar in H1;sauto;\n        TFocus (BinBipole IMP_BODY Right F G); \n        simpl;\n        LLTensor (@nil oo) (M++N);[\n        solveLL;sauto |  solveLL;do 2 LLStore;\n        rewrite <- PermutConsApp;\n            rewrite <-  Permutation_midle;\n            rewrite perm_swap\n             ]\n           \n            end.\n        applyCutC Hi H15.\n            \n            -- apply BipoleReasoning in H5...\n                apply FocusingTensor in H13...\n                simpl in H14.\n                PosNegAll a...\n                1-2: intro; intros...\n                rewrite CEncodeApp.\n                LLPerm (CEncode a N ++ (CEncode a M ++ L)).      \n               apply  AbsorptionLSet'...\n               apply setTCEncode...\n               rewrite secCEncode.\n               assert(IsPositiveAtomFormulaL x1) by OLSolve.\n                TFocus (BinBipole IMP_BODY Left F G). \n                simpl.\n                LLTensor [d| t_bin IMP F G | ] x1.\n                LLTensor x3 x4. \n                1-2: LLRelease; LLStore.\n                1-2: apply  AbsorptionLSet'...\n                1,3: apply setTCEncode...\n                1-2: rewrite secCEncode.\n                1-2: rewrite Permutation_app_comm.\n                applyCutC Hi H12.\n                applyCutC Hi H16.\n                \n                checkPermutationCases H15.\n                apply FocusingTensor in H13...\n                PosNegAll a...\n                1-2: intro; intros...\n                rewrite CEncodeApp.\n                LLPerm (CEncode a N ++ (CEncode a M ++ L)).      \n               apply  AbsorptionLSet'...\n               apply setTCEncode...\n               rewrite secCEncode.\n               \n                TFocus (BinBipole IMP_BODY Left F G). \n                simpl.\n                LLTensor (@nil oo) N.\n                apply weakeningGen. \n                apply allSeTU... \n                solveLL.\n                LLTensor x5 x6. \n                1-2: LLRelease; LLStore.\n                1-2: apply  AbsorptionLSet'...\n                1,3: apply setTCEncode...\n                1-2: rewrite secCEncode.\n                1-2: rewrite Permutation_app_comm.\n                applyCutC Hi H15.\n                applyCutC Hi H18.\n          - (* INIT Case *)        \n             apply FocusingInitRuleU in H5...\n             PosNegAll a...\n             1-2: intro; intros...\n             rewrite CEncodeApp.\n             LLPerm (CEncode a N ++ (CEncode a M ++ L)).      \n                 \n              apply  AbsorptionLSet'...\n               apply setTCEncode...\n               rewrite secCEncode.\n               TFocus (RINIT OO).\n                LLTensor [u| OO |] [d| OO |].\n                checkPermutationCases H12.\n                clear H9.\n                rewrite Permutation_app_comm...\n                simpl.\n                PosNeg a.\n                intro; intros...\n                simpl.\n                apply seqNtoSeq in Hi.\n               refine (WeakTheory _ _ Hi)...\n               apply TheoryEmb1.\n               rewrite Permutation_app_comm.\n               apply WeakPosNeg with (a:=a)...\n               1-2: intro; intros...\n               TFocus (RINIT OO).\n                LLTensor [u| OO |] (@nil oo).\n                solveLL.\n                \n                checkPermutationCases H12.\n                rewrite Permutation_app_comm.\n                apply WeakPosNeg with (a:=a)...\n               1-2: intro; intros...\n               TFocus (RINIT OO).\n                LLTensor (@nil oo) [d| OO |] .\n                solveLL.\n                \n                checkPermutationCases H12.\n                checkPermutationCases H5.\n      \n      rewrite H12.\n      rewrite Permutation_cons_append.\n      rewrite Permutation_app_comm.\n      eapply contractionSet' with (C2:=x4).\n      1-2:eauto.\n      simpl... \n      rewrite <- H12.\n      apply NwgFS with (a:=a)...\n      intro;intros...\n       apply seqNtoSeq in Hi.\n               refine (WeakTheory _ _ Hi)...\n               apply TheoryEmb1.\n               \n               rewrite <- (app_nil_l M).\n               apply WeakPosNeg with (a:=a)...\n               1-2: intro; intros...\n               TFocus (RINIT (OO)).\n                LLTensor (@nil oo) (@nil oo).\n                solveLL. solveLL...\n        \n         - (* Quantifiers Case *)        \n            inversion H1...\n            -- apply BipoleReasoning in H5...\n                simpl in H15.\n                permuteALLRight.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H16.\n                solveQF.\n                checkPermutationCases H16.\n                symmetry in H12.\n                permuteALLRight.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H18.\n                solveQF.\n            -- apply BipoleReasoning in H5...\n                simpl in H15.\n                permuteALLLeft.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H16.\n                solveQF.\n                checkPermutationCases H16.\n                symmetry in H12.\n                permuteALLLeft.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H18.\n                solveQF.\n            -- apply BipoleReasoning in H5...\n                simpl in H15.\n                permuteSOMERight.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H16.\n                solveQF.\n                checkPermutationCases H16.\n                symmetry in H12.\n                permuteSOMERight.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H18.\n                solveQF.\n            -- apply BipoleReasoning in H5...\n                simpl in H15.\n                permuteSOMELeft.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H16.\n                solveQF.\n                checkPermutationCases H16.\n       { clear H15.\n       inversion H8...\n                    inversion lngF...\n                     apply lbindEq in H10...\n                     apply lbindEq in H16...\n                     apply lbindEq in H17...\n                  \n           apply @PosNegSetT' with (a:=a)...\n           1-2: intro;intros...\n           rewrite <- (app_nil_r []).\n           \n           eapply GeneralCut' with (C:=dual (SOME_BODY.(rq_leftBody) FX0)). \n          rewrite <- (app_nil_r []).\n          eapply GeneralCut' with (C:=dual (SOME_BODY.(rq_rightBody) FX)). \n          \n           eapply WeakTheory with (th:=(CUTLN n0)).\n                 intros.\n                 apply TheoryEmb2.\n                 refine(CuteRuleN H5 _)...\n                 apply weakeningAll...  \n                 apply SOME_CUTCOHERENT...\n                 symmetry... \n                 rewrite <- H16...\n                 solveUniform. \n                 intros... \n                 solveQF. \n\n         simpl.\n         eapply FocusingExistsUP  in H11...\n         LLExists x2.  LLRelease. LLStore.\n         \n           apply AbsorptionLSet'...\n           apply setTCEncode...\n           apply AbsorptionLSet'...\n           apply setTCEncode...\n           rewrite !secCEncode.\n           simpl; rewrite app_comm_cons.\n           \n    assert(H' : x1 + S (S x0) = x1 + S (S x0)) by auto. \n           refine(CutHC _ _ _ _ _ _ _ _ _ _  H'  _ _ lngF _ _ _ _ H22 Hj);\n           CutTacPOSNEG.\n        solveQF.   \n\n           simpl.\n           solveLL. LLStore.\n           eapply FocusingForallDW with (y:=x1) in H14...\n          \n           apply AbsorptionLSet'...\n           apply setTCEncode...\n           apply AbsorptionLSet'...\n           apply setTCEncode...\n           rewrite !secCEncode.\n           simpl; rewrite <- Permutation_midle.\n           \n    assert(H' : S (S x) + x2 = S (S x) + x2) by auto. \n           refine(CutHC _ _ _ _ _ _ _ _ _ _  H'  _ _ lngF _ _ _ _ Hi H19);\n           CutTacPOSNEG.\n        solveQF.   \n        \n   }                \n                symmetry in H12.\n                permuteSOMELeft.\n                rewrite <- Permutation_midle.\n                applyCutC Hi H18.\n                solveQF.\n         - (* POS Case *)                    \n            apply BipoleReasoning in H5...\n            apply FocusingQuest in H12...\n            TFocus (POS OO a).\n            LLTensor [d| OO |] (M++x1).\n            rewrite H13...\n            LLRelease. LLStoreC.\n            eapply weakeningN with (F:=(a, d| OO |)) in Hi...\n            LLSwapC H9.\n            LLSwapC Hi.\n            applyCutC Hi H9.\n            apply allU.\n            checkPermutationCases H14.\n            apply FocusingQuest in H12...\n            eapply contractionN in H8...\n            applyCutC Hi H8.\n            apply allU.\n            \n            apply FocusingQuest in H12...\n            TFocus (POS OO a).\n            LLTensor (@nil oo) (M++N).\n            solveLL.\n            LLRelease. LLStoreC.\n            eapply weakeningN with (F:=(a, d| OO |)) in Hi...\n            LLSwapC H14.\n            LLSwapC Hi.\n            applyCutC Hi H14.\n            apply allU.\n         - (* NEG Case *)     \n            apply BipoleReasoning in H5...\n            apply FocusingQuest in H12...\n            TFocus (NEG OO a).\n            LLTensor [u| OO |] (M++x1).\n            rewrite H13...\n            LLRelease. LLStoreC.\n            eapply weakeningN with (F:=(a, u| OO |)) in Hi...\n            LLSwapC H9.\n            LLSwapC Hi.\n            applyCutC Hi H9.\n            apply allU.\n            checkPermutationCases H14.\n            apply FocusingQuest in H12...\n            TFocus (NEG OO a).\n            LLTensor (@nil oo) (M++N).\n            solveLL.\n            LLRelease. LLStoreC.\n            eapply weakeningN with (F:=(a, u| OO |)) in Hi...\n            LLSwapC H14.\n            LLSwapC Hi.\n            applyCutC Hi H14.\n            apply allU.  }\n            \n      TFocus (QuBipole SOME_BODY Right FX). \n      LLTensor (@nil oo) (M++N).\n      solveLL...\n      apply FocusingExistsUP in H11...\n      simpl; LLExists x4; LLRelease;LLStore. \n      rewrite app_comm_cons.\n      applyCutC H15 Hj.\n      solveQF.\n      ** (* 4/4 - SOME Left *)\n      apply BipoleReasoning in H1...\n      TFocus (QuBipole SOME_BODY Left FX). \n      LLTensor [d| t_quant SOME FX|] (x0++N).\n      rewrite H12...\n      simpl; LLRelease; LLForall. \n      solveUniform. LLStore.\n      apply FocusingForallDW with (y:=x1) in H11...\n      rewrite app_comm_cons.\n      applyCutC H11 Hj.\n      solveQF.\n      \n      checkPermutationCases H13.\n    \n      TFocus (QuBipole SOME_BODY Left FX). \n      LLTensor (@nil oo) (M++N).\n      solveLL...\n      simpl; LLRelease; LLForall. \n      solveUniform. LLStore.\n      apply FocusingForallDW with (y:=x3) in H11...\n      rewrite app_comm_cons.\n      applyCutC H14 Hj.\n      solveQF.\n   * (* 5/6 - POS *)\n      apply BipoleReasoning in H1...\n      apply FocusingQuest in H9...\n      rewrite H10.\n      rewrite <- app_comm_cons.\n      PosNeg a.\n      intro; intros...\n      simpl.\n      eapply weakeningN with (F:=(a, d| OO |)) in Hj...\n      LLSwapC H8.\n      LLSwapC Hj.\n      applyCutC H8 Hj.\n      apply allU.\n      \n      checkPermutationCases H11.\n      apply FocusingQuest in H9...\n      rewrite H6.\n      apply contraction with (F:=(x0, d| OO |))...\n      apply allU.\n      rewrite <- H6.\n      apply PosFS with (a:=a)...\n      intro;intros...\n      \n      eapply weakeningN with (F:=(a, d| OO |)) in Hj...\n      LLSwapC H11.\n      LLSwapC Hj.\n      applyCutC H11 Hj.\n      apply allU.\n   * (* 6/6 - NEG *)\n      apply BipoleReasoning in H1...\n      apply FocusingQuest in H9...\n      rewrite H10.\n      rewrite <- app_comm_cons.\n      PosNeg a.\n      intro; intros...\n      simpl.\n      eapply weakeningN with (F:=(a, u| OO |)) in Hj...\n      LLSwapC H8.\n      LLSwapC Hj.\n      applyCutC H8 Hj.\n      apply allU.\n      \n      checkPermutationCases H11.\n      { \n       apply FocusingQuest in H9...\n        eapply contractionN in H6...\n            applyCutC H6 Hj.\n            apply allU. \n     }\n      \n      apply FocusingQuest in H9...\n      rewrite H6.\n      apply contraction with (F:=(x0, u| OO |))...\n      apply allU.\n      rewrite <- H6.\n      apply NwgFS with (a:=a)...\n      intro;intros...\n      \n      eapply weakeningN with (F:=(a, u| OO |)) in Hj...\n      LLSwapC H11.\n      LLSwapC Hj.\n      applyCutC H11 Hj.\n      apply allU.\n  Qed.    \n  \n  \n       Lemma LKCutL F F0 FC L M N a h n0 n1 n' n:\n     mt a = true -> S h = S n0 + S n1 -> isOLFormula FC ->\n     lengthUexp FC n' -> \n     n' <= n ->\n     IsPositiveAtomFormulaL M ->\n     IsPositiveAtomFormulaL N ->\n     IsPositiveAtomFormulaL (second L) ->\n     CutC h a -> \n     seqN (LK a) (S n0) L (u| FC | :: M) (UP []) ->\n     seqN (LK a) (S n1) L (d| FC | :: N) (UP []) ->\n     LK a F ->\n     ~ IsPositiveAtom F ->\n     seqN (LK a) n0 L (u| FC | :: M) (DW F) ->\n     LK a F0 ->\n     ~ IsPositiveAtom F0 ->\n     seqN (LK a) n1 L (d| FC | :: N) (DW F0) ->\n     seq (LKC a (pred n)) L (M ++ N) (UP []).\nProof with CutTacPOSNEG.     \n    intros H4 Heqh isFFC lngF HRel isFM isFN isFL. \n    intro CutHC.\n    intros Hi Hj.\n    intros H H0 H1 H2 H3 H5.\n\n   eapply AbsorptionL with (i:=a) in Hi...\n   eapply AbsorptionL with (i:=a) in Hj...\n   eapply AbsorptionL with (i:=a) in H1...\n   eapply AbsorptionL with (i:=a) in H5...\n   \n   eapply LKCutC with\n       (F:=F) (F0:=F0)\n       (FC:=FC) (h:=h) (a:=a) (n':=n') (n0:=n0) (n1:=n1)...\n   Qed.    \n   \nTheorem LKCutStepC:\n    forall n n' a i j FC L M N,\n    isOLFormula FC ->\n    lengthUexp FC n' ->\n    IsPositiveAtomFormulaL M -> \n    IsPositiveAtomFormulaL N -> \n    IsPositiveAtomFormulaL (second L) -> \n    mt a = true -> \n    n' <= n ->\n   ( seqN  (LK a) i ((a,u|FC|)::L) M  (UP []) -> \n    seqN  (LK a) j ((a,d|FC|)::L) N  (UP []) ->\n    seq   (LKC a (pred n)) L (M++N)  (UP [])).\n  Proof with CutTacPOSNEG;solveSignature1.\n   intros.\n   remember (plus i j) as h.\n    \n   revert dependent L.\n   revert dependent M.\n   revert dependent N.\n   revert dependent FC.\n   revert dependent i.\n   revert dependent n.\n   revert j n'.\n    \n   induction h using strongind;intros *.\n   - intros... \n      -- intros;sauto.\n         symmetry in Heqh.\n         apply plus_is_O in Heqh.\n         destruct Heqh;subst.\n         inversion H6.\n    - intros HRel i Heqh FC isFFC lngF N isFN M isFM L isFL.\n       intros Hi Hj.\n       \n        assert(CutC h a).\n        { unfold CutC;intros.\n            revert H11.\n            revert H10.\n            eapply H with (m:=m) (n':=n'0)... }\n       \n        clear H.\n        rename H0 into CutHC.\n        \n        inversion Hi...\n        + apply RemoveNotPos1 in H0;sauto...\n            intro HF.\n            inversion HF;subst;inversion H...\n        + apply InUNotPos in H2;sauto...\n        + apply RemoveNotPos2 in H2;sauto...\n        + inversion Hj...\n            ++ apply RemoveNotPos1 in H3;sauto...\n                   intro HF.\n                   inversion HF;subst;inversion H2...\n            ++ apply InUNotPos in H6;sauto...\n            ++ apply RemoveNotPos2 in H6;sauto...\n            ++\n            \n        eapply LKCutC with\n       (F:=F) (F0:=F0)\n       (FC:=FC) (h:=h) (a:=a) (n':=n') (n0:=n0) (n1:=n1)...\n  Qed. \n \nTheorem LKCutStep:\n    forall n n' a FC L M N,\n    isOLFormula FC ->\n    lengthUexp FC n' ->\n    IsPositiveAtomFormulaL M -> \n    IsPositiveAtomFormulaL N -> \n    IsPositiveAtomFormulaL (second L) -> \n    mt a = true -> \n    n' <= n ->\n   ( seq  (LK a) L (u|FC|::M)  (UP []) -> \n    seq  (LK a) L (d|FC|::N)  (UP []) ->\n    seq   (LKC a (pred n)) L (M++N)  (UP [])).\n  Proof with CutTacPOSNEG.\n   intros *.\n   intros isFF lngF isFM isFN isFL Ha Hn'. \n   intros Hi Hj.\n   \n   apply seqtoSeqN in Hi, Hj...\n   eapply AbsorptionL with (i:=a) in H0...\n   eapply AbsorptionL with (i:=a) in H...\n   \n   eapply LKCutStepC  with\n       (FC:=FC) (a:=a) (n':=n') (i:=x0) (j:=x)...\n  \n  Qed.     \n \n Theorem LKCutAdmissibility:\n    forall n h a L M,\n    IsPositiveAtomFormulaL M -> \n    IsPositiveAtomFormulaL (second L) -> \n    mt a = true -> \n    seqN (LKC a n) h L M (UP []) -> seq (LK a) L M (UP []) .\n    Proof with CutTacPOSNEG.\n    \n    induction n;induction h using strongind ; intros *; \n    intros isFM isFL mtA HC; try solve[inversion HC].\n    *\n    apply seqNtoSeq in HC.\n    refine(WeakTheory _ _ HC).\n    apply OOTheryCut0.\n    *\n    inversion HC;sauto;try solve [solveSignature1]. \n    apply RemoveNotPos1 in H2;sauto...\n    intro HF.\n    inversion HF;subst;inversion H1...\n        \n    apply InUNotPos in H4;sauto...\n    apply RemoveNotPos2 in H4;sauto...\n       \n    inversion H1;sauto.\n    + (* A formula from the theory was used *)\n      (* Constants *)\n      inversion H0...\n      3:{ \n       apply BipoleReasoning in H3... \n       inversion H7... \n       solveF.\n       inversion H7... \n       solveF. }\n    3:{    \n       apply BipoleReasoning in H3...\n       Bipole FF Left.\n       simpl in H8.\n       LLTensor [d| t_cons FF |] x0.\n       simpl...\n       Bipole FF Left.\n       simpl in H9.\n       LLTensor (@nil oo) M.\n       solveLL.\n       simpl... }\n   2:{\n         apply BipoleReasoning in H3... \n       inversion H7... \n       solveF.\n       inversion H7... \n       solveF.\n  }    \n       apply BipoleReasoning in H3...\n       Bipole TT Right.\n       simpl in H8.\n       LLTensor [u| t_cons TT |] x0.\n       simpl...\n       Bipole TT Right.\n       simpl in H9.\n       LLTensor (@nil oo) M.\n       solveLL.\n       simpl...\n    + (* A formula from the theory was used *)\n      (* Connectives *)\n      inversion H0...\n      ++ \n       apply BipoleReasoning in H3...\n       simpl in H7.\n       apply FocusingWith in H7...\n       TFocus (BinBipole AND_BODY Right F0 G).\n       LLTensor [u| t_bin AND F0 G |] x0.\n       simpl. LLRelease. LLWith. 1-2: LLStore.\n       eapply H in H7...\n       eapply H in H9...\n       simpl in H7.\n       apply FocusingWith in H7...\n       TFocus (BinBipole AND_BODY Right F0 G).\n       LLTensor (@nil oo) M.\n       solveLL.\n       simpl. LLRelease. LLWith. 1-2: LLStore.\n       eapply H in H8...\n       eapply H in H10...\n      ++ \n       apply BipoleReasoning in H3...\n       simpl in H7.\n       apply FocusingPlus in H7...\n       TFocus (BinBipole AND_BODY Left F0 G).\n       LLTensor [d| t_bin AND F0 G |] x0.\n       simpl. LLPlusL. LLRelease. LLStore.\n       eapply H in H6...\n       TFocus (BinBipole AND_BODY Left F0 G).\n       LLTensor [d| t_bin AND F0 G |] x0.\n       simpl. LLPlusR. LLRelease. LLStore.\n       eapply H in H6...\n       \n       simpl in H7.\n       apply FocusingPlus in H7...\n       TFocus (BinBipole AND_BODY Left F0 G).\n       LLTensor (@nil oo) M.\n       solveLL.\n       simpl. LLPlusL. LLRelease. LLStore.\n       eapply H in H7...\n       \n       TFocus (BinBipole AND_BODY Left F0 G).\n       LLTensor (@nil oo) M.\n       solveLL.\n       simpl. LLPlusR. LLRelease. LLStore.\n       eapply H in H7...\n      ++ \n       apply BipoleReasoning in H3...\n       simpl in H7.\n       apply FocusingPlus in H7...\n       TFocus (BinBipole OR_BODY Right F0 G).\n       LLTensor [u| t_bin OR F0 G |] x0.\n       simpl. LLPlusL. LLRelease. LLStore.\n       eapply H in H6...\n       TFocus (BinBipole OR_BODY Right F0 G).\n       LLTensor [u| t_bin OR F0 G |] x0.\n       simpl. LLPlusR. LLRelease. LLStore.\n       eapply H in H6...\n       \n       simpl in H7.\n       apply FocusingPlus in H7...\n       TFocus (BinBipole OR_BODY Right F0 G).\n       LLTensor (@nil oo) M.\n       solveLL.\n       simpl. LLPlusL. LLRelease. LLStore.\n       eapply H in H7...\n       \n       TFocus (BinBipole OR_BODY Right F0 G).\n       LLTensor (@nil oo) M.\n       solveLL.\n       simpl. LLPlusR. LLRelease. LLStore.\n       eapply H in H7...\n      ++ \n       apply BipoleReasoning in H3...\n       simpl in H7.\n       apply FocusingWith in H7...\n       TFocus (BinBipole OR_BODY Left F0 G).\n       LLTensor [d| t_bin OR F0 G |] x0.\n       simpl. LLRelease. LLWith. 1-2: LLStore.\n       eapply H in H7...\n       eapply H in H9...\n       simpl in H7.\n       apply FocusingWith in H7...\n       TFocus (BinBipole OR_BODY Left F0 G).\n       LLTensor (@nil oo) M.\n       solveLL.\n       simpl. LLRelease. LLWith. 1-2: LLStore.\n       eapply H in H8...\n       eapply H in H10...\n      ++ \n       apply BipoleReasoning in H3...\n       simpl in H7.\n       apply FocusingPar in H7...\n       TFocus (BinBipole IMP_BODY Right F0 G).\n       LLTensor [u| t_bin IMP F0 G |] x0.\n       simpl. LLRelease. LLPar. do 2 LLStore.\n       eapply H in H6...\n       OLSolve.\n       \n       simpl in H7.\n       apply FocusingPar in H7...\n       TFocus (BinBipole IMP_BODY Right F0 G).\n       LLTensor (@nil oo) M.\n       solveLL.\n       simpl. LLRelease. LLPar. do 2 LLStore.\n       eapply H in H7...\n      ++ \n       apply BipoleReasoning in H3...\n       simpl in H7.\n       apply FocusingTensor in H7...\n       assert(isx0L: IsPositiveAtomFormulaL x0).\n       OLSolve.\n       TFocus (BinBipole IMP_BODY Left F0 G).\n       LLTensor [d| t_bin IMP F0 G |] x0.\n       simpl. LLTensor x2 x3.\n       1-2: LLRelease. \n       1-2: LLStore.\n       eapply H in H6...\n       eapply H in H10...\n       \n       simpl in H7.\n       apply FocusingTensor in H7...\n       TFocus (BinBipole IMP_BODY Left F0 G).\n       LLTensor (@nil oo) M.\n       simpl. solveLL. \n       simpl. LLTensor x3 x4.\n       1-2: LLRelease. \n       1-2: LLStore.\n       eapply H in H7...\n       eapply H in H11...\n    + (* A formula from the theory was used *)\n      (* Init Rule *)\n      apply FocusingInitRuleU in H3...\n      ++ \n       TFocus (RINIT OO).\n       LLTensor  [u| OO |] [d| OO |].\n       ++ \n       TFocus (RINIT OO).\n       LLTensor  [u| OO |] (@nil oo).\n       solveLL.\n       ++ \n       TFocus (RINIT OO).\n       LLTensor (@nil oo)  [d| OO |].\n       solveLL.\n       ++ \n       TFocus (RINIT OO).\n       LLTensor.\n       init2 x0 x2.\n       init2 x x1.\n    + (* A formula from the theory was used *)\n      (* Quantifiers *)\n      inversion H0...\n      ++ \n       apply BipoleReasoning in H3...\n       simpl in H8.\n       inversion H8...\n       inversion H12...\n       solveF.\n       Bipole ALL Right FX.\n      \n       LLTensor [u| t_quant ALL FX |] x0.\n       simpl. LLRelease. LLForall. \n       specialize (H15 _ H3).\n       inversion H15...\n       LLStore.\n       apply H in H18...\n       inversion H5...\n       apply lbindEq in H10...\n       rewrite <- H10...\n       \n        simpl in H8.\n       inversion H8...\n       inversion H13...\n       solveF.\n      \n       Bipole ALL Right FX.\n      simpl.\n       LLTensor (@nil oo) M. \n       solveLL.\n       simpl. LLRelease. LLForall. \n       specialize (H16 _ H3).\n       inversion H16...\n       LLStore.\n       apply H in H19...\n       inversion H5...\n       apply lbindEq in H11...\n       rewrite <- H11...\n      ++ \n       apply BipoleReasoning in H3...\n       simpl in H8.\n       inversion H8...\n       solveF.\n       inversion H13...\n       inversion H15...\n       \n       Bipole ALL Left FX.\n      \n       LLTensor [d| t_quant ALL FX |] x0.\n       simpl. LLExists t. \n       LLRelease. LLStore.\n       apply H in H18...\n       inversion H5...\n       apply lbindEq in H11...\n       rewrite <- H11...\n       \n        simpl in H8.\n       inversion H8...\n       solveF.\n       inversion H14...\n       inversion H16...\n      \n       Bipole ALL Left FX.\n      simpl.\n       LLTensor (@nil oo) M. \n       solveLL.\n       LLExists t. LLRelease. LLStore.\n       apply H in H19...\n       inversion H5...\n       apply lbindEq in H12...\n       rewrite <- H12...\n      ++ \n       apply BipoleReasoning in H3...\n       simpl in H8.\n       inversion H8...\n       solveF.\n       inversion H13...\n       inversion H15...\n       \n       Bipole SOME Right FX.\n      \n       LLTensor [u| t_quant SOME FX |] x0.\n       simpl. LLExists t. \n       LLRelease. LLStore.\n       apply H in H18...\n       inversion H5...\n       apply lbindEq in H11...\n       rewrite <- H11...\n       \n        simpl in H8.\n       inversion H8...\n       solveF.\n       inversion H14...\n       inversion H16...\n      \n       Bipole SOME Right FX.\n      simpl.\n       LLTensor (@nil oo) M. \n       solveLL.\n       LLExists t. LLRelease. LLStore.\n       apply H in H19...\n       inversion H5...\n       apply lbindEq in H12...\n       rewrite <- H12...\n      ++ \n       apply BipoleReasoning in H3...\n       simpl in H8.\n       inversion H8...\n       inversion H12...\n       solveF.\n       Bipole SOME Left FX.\n      \n       LLTensor [d| t_quant SOME FX |] x0.\n       simpl. LLRelease. LLForall. \n       specialize (H15 _ H3).\n       inversion H15...\n       LLStore.\n       apply H in H18...\n       inversion H5...\n       apply lbindEq in H10...\n       rewrite <- H10...\n       \n        simpl in H8.\n       inversion H8...\n       inversion H13...\n       solveF.\n      \n       Bipole SOME Left FX.\n      simpl.\n       LLTensor (@nil oo) M. \n       solveLL.\n       simpl. LLRelease. LLForall. \n       specialize (H16 _ H3).\n       inversion H16...\n       LLStore.\n       apply H in H19...\n       inversion H5...\n       apply lbindEq in H11...\n       rewrite <- H11...\n    + (* A formula from the theory was used *)\n      (* POS *)\n       apply BipoleReasoning in H3...\n       inversion H6...\n       inversion H10...\n       2: solveF.\n       TFocus (POS OO a). \n       LLTensor [d| OO|] x0.\n       LLRelease. LLStoreC.\n       eapply H in H11...\n       \n       inversion H6...\n       inversion H11...\n       2: solveF.\n       TFocus (POS OO a). \n       LLTensor (@nil oo) M.\n       solveLL.\n       LLRelease. LLStoreC.\n       eapply H in H12...\n    + (* A formula from the theory was used *)\n      (* NEG *)\n       apply BipoleReasoning in H3...\n       inversion H6...\n       inversion H10...\n       2: solveF.\n       TFocus (NEG OO a). \n       LLTensor [u| OO|] x0.\n       LLRelease. LLStoreC.\n       eapply H in H11...\n       \n       inversion H6...\n       inversion H11...\n       2: solveF.\n       TFocus (NEG OO a). \n       LLTensor (@nil oo) M.\n       solveLL.\n       LLRelease. LLStoreC.\n       eapply H in H12...\n    + (* A formula from the theory was used *)\n      (* Linear Cut *)\n       inversion H0...\n       apply FocusingTensor in H3...\n       rewrite H9.\n       apply H in H5...\n       apply H in H11...\n       2-3: OLSolve.\n       \n       assert(seq (LKC a (pred ((S n)))) L (x1 ++ x0) (UP [])).\n       refine (LKCutStep _ H7 _ _ _ _ _ H11 H5)...\n       simpl in H3.\n       apply seqtoSeqN in H3...\n       eapply IHn in H3...\n       2-3: OLSolve.\n       LLExact H3.\n Qed.\n \nEnd LKCut.", "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/LNSg/LKCut.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.5, "lm_q1q2_score": 0.25195308526454024}}
{"text": "(* This file is generated by Why3's Coq-realize driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire BuiltIn.\nRequire int.Int.\nRequire int.Abs.\n\n(* This file is generated by Why3's Coq-realize driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire BuiltIn.\nRequire int.Int.\nRequire int.Abs.\n\n(* Why3 goal *)\nDefinition div: Z -> Z -> Z.\nintros x y.\ncase (Z_le_dec 0 (Zmod x y)) ; intros H.\nexact (Zdiv x y).\nexact (Zdiv x y + 1)%Z.\nDefined.\n\n(* Why3 goal *)\nDefinition mod1: Z -> Z -> Z.\nintros x y.\nexact (x - y * div x y)%Z.\nDefined.\n\n(* Why3 goal *)\nLemma Div_mod : forall (x:Z) (y:Z), (~ (y = 0%Z)) -> (x = ((y * (div x\n  y))%Z + (mod1 x y))%Z).\nintros x y Zy.\nunfold mod1, div.\ncase Z_le_dec ; intros H ; ring.\nQed.\n\n(* Why3 goal *)\nLemma Mod_bound : forall (x:Z) (y:Z), (~ (y = 0%Z)) -> ((0%Z <= (mod1 x\n  y))%Z /\\ ((mod1 x y) < (ZArith.BinInt.Z.abs y))%Z).\nintros x y Zy.\nzify.\nassert (H1 := Z_mod_neg x y).\nassert (H2 := Z_mod_lt x y).\nunfold mod1, div.\ncase Z_le_dec ; intros H0.\nrewrite Zmult_comm, <- Zmod_eq_full with (1 := Zy).\nomega.\nreplace (x - y * (x / y + 1))%Z with (x - x / y * y - y)%Z by ring.\nrewrite <- Zmod_eq_full with (1 := Zy).\nomega.\nQed.\n\n(* Why3 goal *)\nLemma Div_unique : forall (x:Z) (y:Z) (q:Z), (0%Z < y)%Z ->\n  ((((q * y)%Z <= x)%Z /\\ (x < ((q * y)%Z + y)%Z)%Z) -> ((div x y) = q)).\nintros x y q h1 (h2,h3).\nassert (h:(~(y=0))%Z) by omega.\ngeneralize (Mod_bound x y h); intro h0.\nrewrite Z.abs_eq in h0; auto with zarith.\ngeneralize (Div_mod x y h); clear h; intro h.\nassert (cases:(div x y = q \\/ (div x y <= q - 1 \\/ div x y >= q+1))%Z) by omega.\ndestruct cases as [h4 | [h5 | h6]]; auto.\nassert (y * div x y <= y * (q - 1))%Z.\n apply  Zmult_le_compat_l; auto with zarith.\nreplace (y*(q-1))%Z with (q*y - y)%Z in H by ring.\nelimtype False.\nomega.\nassert (y * div x y >= y * (q + 1))%Z.\n apply  Zmult_ge_compat_l; auto with zarith.\nreplace (y*(q+1))%Z with (q*y + y)%Z in H by ring.\nelimtype False.\nomega.\nQed.\n\n(* Why3 goal *)\nLemma Div_bound : forall (x:Z) (y:Z), ((0%Z <= x)%Z /\\ (0%Z < y)%Z) ->\n  ((0%Z <= (div x y))%Z /\\ ((div x y) <= x)%Z).\nintros x y (Hx,Hy).\nunfold div.\ncase Z_le_dec ; intros H.\nsplit.\napply Z_div_pos with (2 := Hx).\nnow apply Zlt_gt.\ndestruct (Z_eq_dec y 1) as [H'|H'].\nrewrite H', Zdiv_1_r.\napply Zle_refl.\nrewrite <- (Zdiv_1_r x) at 2.\napply Zdiv_le_compat_l with (1 := Hx).\nomega.\nelim H.\napply Z_mod_lt.\nnow apply Zlt_gt.\nQed.\n\n(* Why3 goal *)\nLemma Mod_1 : forall (x:Z), ((mod1 x 1%Z) = 0%Z).\nintros x.\nunfold mod1, div.\nrewrite Zmod_1_r, Zdiv_1_r, Zmult_1_l.\napply Zminus_diag.\nQed.\n\n(* Why3 goal *)\nLemma Div_1 : forall (x:Z), ((div x 1%Z) = x).\nintros x.\nunfold div.\nnow rewrite Zmod_1_r, Zdiv_1_r.\nQed.\n\n(* Why3 goal *)\nLemma Div_inf : forall (x:Z) (y:Z), ((0%Z <= x)%Z /\\ (x < y)%Z) -> ((div x\n  y) = 0%Z).\nintros x y Hxy.\nunfold div.\ncase Z_le_dec ; intros H.\nnow apply Zdiv_small.\nelim H.\nnow rewrite Zmod_small.\nQed.\n\n(* Why3 goal *)\nLemma Div_inf_neg : forall (x:Z) (y:Z), ((0%Z < x)%Z /\\ (x <= y)%Z) ->\n  ((div (-x)%Z y) = (-1%Z)%Z).\nintros x y Hxy.\nassert (h: (x < y \\/ x = y)%Z) by omega.\ndestruct h.\n(* case 0 < x < y *)\nassert (h1: (x mod y = x)%Z).\n  rewrite Zmod_small; auto with zarith.\nassert (h2: ((-x) mod y = y - x)%Z).\n  rewrite Z_mod_nz_opp_full.\n  rewrite h1; auto.\nrewrite h1; auto with zarith.\nunfold div.\ncase Z_le_dec; auto with zarith.\nintros h3.\nrewrite Z_div_nz_opp_full; auto with zarith.\nrewrite Zdiv_small; auto with zarith.\n\n(* case x = y *)\nsubst.\nassert (h1: (y mod y = 0)%Z).\n  rewrite Z_mod_same_full; auto with zarith.\nassert (h2: ((-y) mod y = 0)%Z).\n  rewrite Z_mod_zero_opp_full; auto with zarith.\nunfold div.\ncase Z_le_dec; rewrite h2; auto with zarith.\nintro.\nrewrite Z_div_zero_opp_full; auto with zarith.\nrewrite Z_div_same_full; auto with zarith.\nQed.\n\n(* Why3 goal *)\nLemma Mod_0 : forall (y:Z), (~ (y = 0%Z)) -> ((mod1 0%Z y) = 0%Z).\nintros y Hy.\nunfold mod1, div.\nrewrite Zmod_0_l.\nsimpl.\nnow rewrite Zdiv_0_l, Zmult_0_r.\nQed.\n\n(* Why3 goal *)\nLemma Div_1_left : forall (y:Z), (1%Z < y)%Z -> ((div 1%Z y) = 0%Z).\nintros y Hy.\nrewrite Div_inf; auto with zarith.\nQed.\n\n(* Why3 goal *)\nLemma Div_minus1_left : forall (y:Z), (1%Z < y)%Z -> ((div (-1%Z)%Z\n  y) = (-1%Z)%Z).\nintros y Hy.\nunfold div.\nassert (h1: (1 mod y = 1)%Z).\napply Zmod_1_l; auto.\nassert (h2: ((-(1)) mod y = y-1)%Z).\n  rewrite Z_mod_nz_opp_full; auto with zarith.\ncase Z_le_dec; auto with zarith.\nintro.\nrewrite Z_div_nz_opp_full; auto with zarith.\nrewrite Zdiv_small; auto with zarith.\nQed.\n\n(* Why3 goal *)\nLemma Mod_1_left : forall (y:Z), (1%Z < y)%Z -> ((mod1 1%Z y) = 1%Z).\nintros y Hy.\nunfold mod1.\nrewrite Div_1_left; auto with zarith.\nQed.\n\n(* Why3 goal *)\nLemma Mod_minus1_left : forall (y:Z), (1%Z < y)%Z -> ((mod1 (-1%Z)%Z\n  y) = (y - 1%Z)%Z).\nintros y Hy.\nunfold mod1.\nrewrite Div_minus1_left; auto with zarith.\nQed.\n\nOpen Scope Z_scope.\n\n(* Why3 goal *)\nLemma Div_mult : forall (x:Z) (y:Z) (z:Z), (0%Z < x)%Z ->\n  ((div ((x * y)%Z + z)%Z x) = (y + (div z x))%Z).\nintros x y z h.\nunfold div.\ndestruct (Z_le_dec 0 (z mod x)).\ndestruct (Z_le_dec 0 ((x*y+z) mod x)).\nrewrite Zmult_comm.\nrewrite Z_div_plus_full_l; auto with zarith.\ngeneralize (Z_mod_lt (x * y + z) x); auto with zarith.\ngeneralize (Z_mod_lt z x); auto with zarith.\nQed.\n\n(* Why3 goal *)\nLemma Mod_mult : forall (x:Z) (y:Z) (z:Z), (0%Z < x)%Z ->\n  ((mod1 ((x * y)%Z + z)%Z x) = (mod1 z x)).\nintros x y z h.\nunfold mod1.\nrewrite Div_mult.\nring.\nauto with zarith.\nQed.\n\n", "meta": {"author": "schrodibear", "repo": "why3", "sha": "9f8eb767380987a28e43b81729ae1d682363bb49", "save_path": "github-repos/coq/schrodibear-why3", "path": "github-repos/coq/schrodibear-why3/why3-9f8eb767380987a28e43b81729ae1d682363bb49/lib/coq/int/EuclideanDivision.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.5, "lm_q1q2_score": 0.25195308526454024}}
{"text": "From iris_simp_lang Require Import notation tactics.\nFrom iris.prelude Require Import options.\n\n(*|\nThese instances prove that various expressions are atomic or pure.\n\n`Atomic e` is defined generically for languages by saying `e` reduces to a value\n(recall: this is defined by `to_val e = Some _`) in a single step.\n\n`PureExec φ n e1 e2` shows that if φ holds (a pure Coq proposition), `e1`\nexecutes to `e2` in `n` steps. This is eventually needed to define a tactic\n`wp_pure _` that finds and reasons about pure reductions (this subsumes\n`wp_let`, `wp_seq`, `wp_app` and the like, which are just restrictions of\n`wp_pure`).\n|*)\n\n\nGlobal Instance into_val_val v : IntoVal (Val v) v.\nProof. done. Qed.\nGlobal Instance as_val_val v : AsVal (Val v).\nProof. by eexists. Qed.\n\n(** * Instances of the [Atomic] class *)\nSection atomic.\n  Local Ltac solve_atomic :=\n    apply strongly_atomic_atomic, ectx_language_atomic;\n      [inversion 1; naive_solver\n      |apply ectxi_language_sub_redexes_are_values; intros [] **; naive_solver].\n\n  Global Instance rec_atomic s f x e : Atomic s (Rec f x e).\n  Proof. solve_atomic. Qed.\n  (** The instance below is a more general version of [Skip] *)\n  Global Instance beta_atomic s f x v1 v2 : Atomic s (App (RecV f x (Val v1)) (Val v2)).\n  Proof. destruct f, x; solve_atomic. Qed.\n  Global Instance unop_atomic s op v : Atomic s (UnOp op (Val v)).\n  Proof. solve_atomic. Qed.\n  Global Instance binop_atomic s op v1 v2 : Atomic s (BinOp op (Val v1) (Val v2)).\n  Proof. solve_atomic. Qed.\n  Global Instance if_true_atomic s v1 e2 :\n    Atomic s (If (Val $ LitV $ LitBool true) (Val v1) e2).\n  Proof. solve_atomic. Qed.\n  Global Instance if_false_atomic s e1 v2 :\n    Atomic s (If (Val $ LitV $ LitBool false) e1 (Val v2)).\n  Proof. solve_atomic. Qed.\n\n  Global Instance fork_atomic s e : Atomic s (Fork e).\n  Proof. solve_atomic. Qed.\n\n  Global Instance heap_op_atomic op s v1 v2 : Atomic s (HeapOp op (Val v1) (Val v2)).\n  Proof. solve_atomic. Qed.\nEnd atomic.\n\n(** * Instances of the [PureExec] class *)\n(** The behavior of the various [wp_] tactics with regard to lambda differs in\nthe following way:\n\n- [wp_pures] does *not* reduce lambdas/recs that are hidden behind a definition.\n- [wp_rec] and [wp_lam] reduce lambdas/recs that are hidden behind a definition.\n\nTo realize this behavior, we define the class [AsRecV v f x erec], which takes a\nvalue [v] as its input, and turns it into a [RecV f x erec] via the instance\n[AsRecV_recv : AsRecV (RecV f x e) f x e]. We register this instance via\n[Hint Extern] so that it is only used if [v] is syntactically a lambda/rec, and\nnot if [v] contains a lambda/rec that is hidden behind a definition.\n\nTo make sure that [wp_rec] and [wp_lam] do reduce lambdas/recs that are hidden\nbehind a definition, we activate [AsRecV_recv] by hand in these tactics. *)\nClass AsRecV (v : val) (f x : binder) (erec : expr) :=\n  as_recv : v = RecV f x erec.\nGlobal Hint Mode AsRecV ! - - - : typeclass_instances.\nDefinition AsRecV_recv f x e : AsRecV (RecV f x e) f x e := eq_refl.\nGlobal Hint Extern 0 (AsRecV (RecV _ _ _) _ _ _) =>\n  apply AsRecV_recv : typeclass_instances.\n\nSection pure_exec.\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    subst; intros ?; apply nsteps_once, pure_head_step_pure_step;\n      constructor; [solve_exec_safe | solve_exec_puredet].\n\n  Global Instance pure_recc f x (erec : expr) :\n    PureExec True 1 (Rec f x erec) (Val $ RecV f x erec).\n  Proof. solve_pure_exec. Qed.\n  Global Instance pure_beta f x (erec : expr) (v1 v2 : val) `{!AsRecV v1 f x erec} :\n    PureExec True 1 (App (Val v1) (Val v2)) (subst' x v2 (subst' f v1 erec)).\n  Proof. unfold AsRecV in *. solve_pure_exec. Qed.\n\n  Global Instance pure_unop op v v' :\n    PureExec (un_op_eval op v = Some v') 1 (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 (BinOp op (Val v1) (Val v2)) (Val v') | 10.\n  Proof. solve_pure_exec. Qed.\n  (* Higher-priority instance for [EqOp]. *)\n  Global Instance pure_eqop v1 v2 :\n    PureExec True 1\n      (BinOp EqOp (Val v1) (Val v2))\n      (Val $ LitV $ LitBool $ bool_decide (v1 = v2)) | 1.\n  Proof. solve_pure_exec. Qed.\n\n  Global Instance pure_if_true e1 e2 :\n    PureExec True 1 (If (Val $ LitV $ LitBool true) e1 e2) e1.\n  Proof. solve_pure_exec. Qed.\n  Global Instance pure_if_false e1 e2 :\n    PureExec True 1 (If (Val $ LitV $ LitBool false) e1 e2) e2.\n  Proof. solve_pure_exec. Qed.\nEnd pure_exec.\n", "meta": {"author": "tchajed", "repo": "iris-simp-lang", "sha": "652edebbc59759fcaf5ea059ed7378aff2945c7f", "save_path": "github-repos/coq/tchajed-iris-simp-lang", "path": "github-repos/coq/tchajed-iris-simp-lang/iris-simp-lang-652edebbc59759fcaf5ea059ed7378aff2945c7f/src/class_instances.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.5, "lm_q1q2_score": 0.25195308526454024}}
{"text": "\n\nLocal Set Primitive Projections.\nRecord sigT {A} (P : A -> Type) : Type := existT\n  { projT1 : A ; projT2 : P projT1 }.\n\nRecord unit : Type := tt { }.\n\n\nGeneralizable All Variables.\n\nDefinition paths : forall A, A -> A -> Type := @eq.\nDefinition idpath : forall A a, paths A a a := @eq_refl.\nDefinition paths_ind : forall A a (P : forall y, paths A a y -> Type),\n    P a (idpath A a) -> forall y p, P y p.\n  intros A a P X y p. destruct p; assumption.\nDefined.\nDefinition paths_ind_beta : forall A a P u, paths _ (paths_ind A a P u a (idpath A a)) u.\n  reflexivity.\nDefined.\n\nArguments sigT {A}%type P%type.\nArguments existT {A}%type P%type _ _.\nArguments projT1 {A P} _ / .\nArguments projT2 {A P} _ / .\nNotation \"'exists' x .. y , p\" := (sigT (fun x => .. (sigT (fun y => p)) ..))\n  (at level 200, x binder, right associativity,\n   format \"'[' 'exists'  '/  ' x  ..  y ,  '/  ' p ']'\")\n  : type_scope.\nNotation \"{ x : A  & P }\" := (sigT (fun x:A => P)) : type_scope.\n\n\nDefinition relation (A : Type) := A -> A -> Type.\n\nClass Reflexive {A} (R : relation A) :=\n  reflexivity : forall x : A, R x x.\n\nClass Symmetric {A} (R : relation A) :=\n  symmetry : forall x y, R x y -> R y x.\n\nClass Transitive {A} (R : relation A) :=\n  transitivity : forall x y z, R x y -> R y z -> R x z.\n\nClass PreOrder {A} (R : relation A) :=\n  { PreOrder_Reflexive : Reflexive R | 2 ;\n    PreOrder_Transitive : Transitive R | 2 }.\n\nGlobal Existing Instance PreOrder_Reflexive.\nGlobal Existing Instance PreOrder_Transitive.\n\nArguments reflexivity {A R _} / _.\nArguments symmetry {A R _} / _ _ _.\nArguments transitivity {A R _} / {_ _ _} _ _.\n\nLtac reflexivity :=\n  Coq.Init.Notations.reflexivity\n  || (intros;\n      let R := match goal with |- ?R ?x ?y => constr:(R) end in\n      let pre_proof_term_head := constr:(@reflexivity _ R _) in\n      let proof_term_head := (eval cbn in pre_proof_term_head) in\n      apply (pre_proof_term_head : forall x, R x x)).\n\nLtac symmetry :=\n  let R := match goal with |- ?R ?x ?y => constr:(R) end in\n  let x := match goal with |- ?R ?x ?y => constr:(x) end in\n  let y := match goal with |- ?R ?x ?y => constr:(y) end in\n  let pre_proof_term_head := constr:(@symmetry _ R _) in\n  let proof_term_head := (eval cbn in pre_proof_term_head) in\n  refine (proof_term_head y x _); change (R y x).\n\nTactic Notation \"etransitivity\" open_constr(y) :=\n  let R := match goal with |- ?R ?x ?z => constr:(R) end in\n  let x := match goal with |- ?R ?x ?z => constr:(x) end in\n  let z := match goal with |- ?R ?x ?z => constr:(z) end in\n  let pre_proof_term_head := constr:(@transitivity _ R _) in\n  let proof_term_head := (eval cbn in pre_proof_term_head) in\n  refine (proof_term_head x y z _ _); [ change (R x y) | change (R y z) ].\n\nTactic Notation \"etransitivity\" := etransitivity _.\n\nLtac transitivity x := etransitivity x.\n\nNotation idmap := (fun x => x).\n\nDelimit Scope equiv_scope with equiv.\nDelimit Scope function_scope with function.\nDelimit Scope path_scope with path.\nDelimit Scope fibration_scope with fibration.\nDelimit Scope trunc_scope with trunc.\n\nOpen Scope trunc_scope.\nOpen Scope equiv_scope.\nOpen Scope path_scope.\nOpen Scope fibration_scope.\nOpen Scope nat_scope.\nOpen Scope function_scope.\nOpen Scope type_scope.\nOpen Scope core_scope.\n\nDefinition const {A B} (b : B) := fun x : A => b.\n\nNotation \"( x ; y )\" := (existT _ x y) : fibration_scope.\nBind Scope fibration_scope with sigT.\nNotation pr1 := projT1.\nNotation pr2 := projT2.\nNotation \"x .1\" := (pr1 x) (at level 3, format \"x '.1'\") : fibration_scope.\nNotation \"x .2\" := (pr2 x) (at level 3, format \"x '.2'\") : fibration_scope.\n\nNotation compose := (fun g f x => g (f x)).\nNotation \"g 'o' f\" := (compose g%function f%function) (at level 40, left associativity) : function_scope.\n\n(* Instance iff_compose : Transitive iff | 1 *)\n(*   := fun A B C f g => (fst g o fst f , snd f o snd g). *)\n(* Arguments iff_compose {A B C} f g : rename. *)\n\n(* Instance iff_inverse : Symmetric iff | 1 *)\n(*   := fun A B f => (snd f , fst f). *)\n(* Arguments iff_inverse {A B} f : rename. *)\n\n(* Instance iff_reflexive : Reflexive iff | 1 *)\n(*   := fun A => (idmap , idmap). *)\n\nDefinition composeD {A B C} (g : forall b, C b) (f : A -> B) := fun x : A => g (f x).\nGlobal Arguments composeD {A B C}%type_scope (g f)%function_scope x.\nHint Unfold composeD.\nNotation \"g 'oD' f\" := (composeD g f) (at level 40, left associativity) : function_scope.\n\nNotation \"x = y :> A\" := (paths A x y) : type_scope.\nNotation \"x = y\" := (x = y :>_) : type_scope.\n\nBind Scope path_scope with paths.\nOpen Scope path_scope.\n\nArguments paths {A} _ _.\nArguments idpath {A a} , [A] a.\nArguments paths_ind [A] a P f y p.\n\nGlobal Instance reflexive_paths {A} : Reflexive (@paths A) | 0 := @idpath A.\nArguments reflexive_paths / .\nNotation \"1\" := (idpath _) : path_scope.\n\nDefinition transport {A : Type} (P : A -> Type) {x y : A} (p : x = y) (u : P x) : P y := paths_ind x (fun y _ => P y) u y p.\n\nArguments transport {A}%type_scope P%function_scope {x y} p%path_scope u : simpl nomatch.\n\nDefinition transport_beta {A} (P : A -> Type) {x : A} (u : P x)\n  : transport P 1 u = u\n  := paths_ind_beta A x (fun y _ => P y) u.\n\nNotation \"p # x\" := (transport _ p x) (right associativity, at level 65, only parsing) : path_scope.\n\nDefinition inverse {A : Type} {x y : A} (p : x = y) : y = x\n  := transport (fun x' => x' = x) p 1.\n\nGlobal Instance symmetric_paths {A} : Symmetric (@paths A) | 0 := @inverse A.\nArguments symmetric_paths / .\n\nDefinition concat {A : Type} {x y z : A} (p : x = y) (q : y = z) : x = z.\n  (* := transport (paths _ x) q (transport (fun y => x = y) p 1). *)\n  now destruct p, q.\nDefined.\n\nArguments concat {A x y z} p q : simpl nomatch.\n\nGlobal Instance transitive_paths {A} : Transitive (@paths A) | 0 := @concat A.\nArguments transitive_paths / .\n\nNotation \"p @ q\" := (concat p%path q%path) (at level 20) : path_scope.\nNotation \"p ^\" := (inverse p%path) (at level 3, format \"p '^'\") : path_scope.\n\nDefinition ap {A B:Type} (f:A -> B) {x y:A} (p:x = y) : f x = f y\n  := transport (fun y => f x = f y) p 1.\n\nGlobal Arguments ap {A B}%type_scope f%function_scope {x y} p%path_scope.\n\nDefinition pointwise_paths {A} {P:A->Type} (f g:forall x:A, P x)\n  := forall x:A, f x = g x.\n\nGlobal Arguments pointwise_paths {A}%type_scope {P} (f g)%function_scope.\n\nHint Unfold pointwise_paths : typeclass_instances.\n\nNotation \"f == g\" := (pointwise_paths f g) (at level 70, no associativity) : type_scope.\n\nDefinition apD10 {A} {B:A->Type} {f g : forall x, B x} (h:f=g)\n  : f == g\n  := fun x => transport (fun g => f x = g x) h 1.\n\nGlobal Arguments apD10 {A%type_scope B} {f g}%function_scope h%path_scope _.\n\nDefinition ap10 {A B} {f g:A->B} (h:f=g) : f == g\n  := apD10 h.\n\nGlobal Arguments ap10 {A B}%type_scope {f g}%function_scope h%path_scope _.\n\nDefinition ap11 {A B} {f g:A->B} (h:f=g) {x y:A} (p:x=y) : f x = g y\n  := ap10 h x @ ap g p.\n\nGlobal Arguments ap11 {A B}%type_scope {f g}%function_scope h%path_scope {x y} p%path_scope.\n\nArguments ap {A B} f {x y} p : simpl nomatch.\n\nDefinition apD {A:Type} {B:A->Type} (f:forall a:A, B a) {x y:A} (p:x=y):\n  p # (f x) = f y\n  := paths_ind x (fun y p => p # (f x) = f y) (transport_beta _ _) y p.\n\nArguments apD {A%type_scope B} f%function_scope {x y} p%path_scope : simpl nomatch.\n\nDefinition Sect {A B : Type} (s : A -> B) (r : B -> A) :=\n  forall x : A, r (s x) = x.\n\nGlobal Arguments Sect {A B}%type_scope (s r)%function_scope.\n\nClass IsEquiv {A B : Type} (f : A -> B) := BuildIsEquiv {\n                                               equiv_inv : B -> A ;\n                                               eisretr : Sect equiv_inv f;\n                                               eissect : Sect f equiv_inv;\n                                               eisadj : forall x : A, eisretr (f x) = ap f (eissect x)\n                                             }.\n\nArguments eisretr {A B}%type_scope f%function_scope {_} _.\nArguments eissect {A B}%type_scope f%function_scope {_} _.\nArguments eisadj {A B}%type_scope f%function_scope {_} _.\nArguments IsEquiv {A B}%type_scope f%function_scope.\n\nRecord Equiv A B := BuildEquiv {\n                        equiv_fun : A -> B ;\n                        equiv_isequiv : IsEquiv equiv_fun\n                      }.\n\nCoercion equiv_fun : Equiv >-> Funclass.\n\nGlobal Existing Instance equiv_isequiv.\n\nArguments equiv_fun {A B} _ _.\nArguments equiv_isequiv {A B} _.\n\nBind Scope equiv_scope with Equiv.\n\nNotation \"A <~> B\" := (Equiv A B) (at level 85) : type_scope.\n\nNotation \"f ^-1\" := (@equiv_inv _ _ f _) (at level 3, format \"f '^-1'\") : function_scope.\n\nDefinition ap10_equiv {A B : Type} {f g : A <~> B} (h : f = g) : f == g\n  := ap10 (ap equiv_fun h).\n\nClass Contr (A : Type) :=\n  BuildContr { center : A ;\n               contr : (forall y : A, center = y) }.\n\nArguments center A {_}.\n\n\nClass Funext := { isequiv_apD10 : forall (A : Type) (P : A -> Type) f g, IsEquiv (@apD10 A P f g) }.\n\nExisting Instance isequiv_apD10.\n\nDefinition path_forall `{Funext} {A : Type} {P : A -> Type} (f g : forall x : A, P x) : f == g -> f = g\n  := (@apD10 A P f g)^-1.\n\nGlobal Arguments path_forall {_ A%type_scope P} (f g)%function_scope _.\n\nDefinition path_forall2 `{Funext} {A B : Type} {P : A -> B -> Type} (f g : forall x y, P x y) :\n  (forall x y, f x y = g x y) -> f = g\n  :=\n    (fun E => path_forall f g (fun x => path_forall (f x) (g x) (E x))).\n\nGlobal Arguments path_forall2 {_} {A B}%type_scope {P} (f g)%function_scope _.\n\n\n\n(* PathGroupoid.v *)\n\nDefinition concat_p1 {A : Type} {x y : A} (p : x = y) :\n  p @ 1 = p.\n  now destruct p.\nDefined.\n\nDefinition concat_1p {A : Type} {x y : A} (p : x = y) :\n  1 @ p = p.\n  now destruct p.\nDefined.\n\n\nDefinition concat_p_pp {A : Type} {x y z t : A} (p : x = y) (q : y = z) (r : z = t) :\n  p @ (q @ r) = (p @ q) @ r.\n  now destruct p, q, r.\nDefined.\n\nDefinition concat_pp_p {A : Type} {x y z t : A} (p : x = y) (q : y = z) (r : z = t) :\n  (p @ q) @ r = p @ (q @ r).\n  now destruct p, q, r.\nDefined.\n\nDefinition concat_pV {A : Type} {x y : A} (p : x = y) :\n  p @ p^ = 1.\n  now destruct p.\nDefined.\n\nDefinition concat_Vp {A : Type} {x y : A} (p : x = y) :\n  p^ @ p = 1.\n  now destruct p.\nDefined.\n\nDefinition concat_V_pp {A : Type} {x y z : A} (p : x = y) (q : y = z) :\n  p^ @ (p @ q) = q.\n  now destruct p, q.\nDefined.\n\nDefinition concat_p_Vp {A : Type} {x y z : A} (p : x = y) (q : x = z) :\n  p @ (p^ @ q) = q.\n  now destruct p, q.\nDefined.\n\nDefinition concat_pp_V {A : Type} {x y z : A} (p : x = y) (q : y = z) :\n  (p @ q) @ q^ = p.\n  now destruct p, q.\nDefined.\n\nDefinition concat_pV_p {A : Type} {x y z : A} (p : x = z) (q : y = z) :\n  (p @ q^) @ q = p.\n  now destruct p, q.\nDefined.\n\nDefinition inv_pp {A : Type} {x y z : A} (p : x = y) (q : y = z) :\n  (p @ q)^ = q^ @ p^.\n  now destruct p, q.\nDefined.\n\nDefinition inv_Vp {A : Type} {x y z : A} (p : y = x) (q : y = z) :\n  (p^ @ q)^ = q^ @ p.\n  now destruct p, q.\nDefined.\n\nDefinition inv_pV {A : Type} {x y z : A} (p : x = y) (q : z = y) :\n  (p @ q^)^ = q @ p^.\n  now destruct p, q.\nDefined.\n\nDefinition inv_VV {A : Type} {x y z : A} (p : y = x) (q : z = y) :\n  (p^ @ q^)^ = q @ p.\n  now destruct p, q.\nDefined.\n\nDefinition inv_V {A : Type} {x y : A} (p : x = y) :\n  p^^ = p.\n  now destruct p.\nDefined.\n\nDefinition moveR_Mp {A : Type} {x y z : A} (p : x = z) (q : y = z) (r : y = x) :\n  p = r^ @ q -> r @ p = q.\nProof.\n  destruct r.\n  intro h. exact (concat_1p _ @ h @ concat_1p _).\nDefined.\n\nDefinition moveR_pM {A : Type} {x y z : A} (p : x = z) (q : y = z) (r : y = x) :\n  r = q @ p^ -> r @ p = q.\nProof.\n  destruct p.\n  intro h. exact (concat_p1 _ @ h @ concat_p1 _).\nDefined.\n\nDefinition moveR_Vp {A : Type} {x y z : A} (p : x = z) (q : y = z) (r : x = y) :\n  p = r @ q -> r^ @ p = q.\nProof.\n  destruct r.\n  intro h. exact (concat_1p _ @ h @ concat_1p _).\nDefined.\n\nDefinition moveR_pV {A : Type} {x y z : A} (p : z = x) (q : y = z) (r : y = x) :\n  r = q @ p -> r @ p^ = q.\nProof.\n  destruct p.\n  intro h. exact (concat_p1 _ @ h @ concat_p1 _).\nDefined.\n\nDefinition moveL_Mp {A : Type} {x y z : A} (p : x = z) (q : y = z) (r : y = x) :\n  r^ @ q = p -> q = r @ p.\nProof.\n  destruct r.\n  intro h. exact ((concat_1p _)^ @ h @ (concat_1p _)^).\nDefined.\n\nDefinition moveL_pM {A : Type} {x y z : A} (p : x = z) (q : y = z) (r : y = x) :\n  q @ p^ = r -> q = r @ p.\nProof.\n  destruct p.\n  intro h. exact ((concat_p1 _)^ @ h @ (concat_p1 _)^).\nDefined.\n\nDefinition moveL_Vp {A : Type} {x y z : A} (p : x = z) (q : y = z) (r : x = y) :\n  r @ q = p -> q = r^ @ p.\nProof.\n  destruct r.\n  intro h. exact ((concat_1p _)^ @ h @ (concat_1p _)^).\nDefined.\n\nDefinition moveL_pV {A : Type} {x y z : A} (p : z = x) (q : y = z) (r : y = x) :\n  q @ p = r -> q = r @ p^.\nProof.\n  destruct p.\n  intro h. exact ((concat_p1 _)^ @ h @ (concat_p1 _)^).\nDefined.\n\nDefinition moveL_1M {A : Type} {x y : A} (p q : x = y) :\n  p @ q^ = 1 -> p = q.\nProof.\n  destruct q.\n  intro h. exact ((concat_p1 _)^ @ h).\nDefined.\n\nDefinition moveL_M1 {A : Type} {x y : A} (p q : x = y) :\n  q^ @ p = 1 -> p = q.\nProof.\n  destruct q.\n  intro h. exact ((concat_1p _)^ @ h).\nDefined.\n\nDefinition moveL_1V {A : Type} {x y : A} (p : x = y) (q : y = x) :\n  p @ q = 1 -> p = q^.\nProof.\n  destruct q.\n  intro h. exact ((concat_p1 _)^ @ h).\nDefined.\n\nDefinition moveL_V1 {A : Type} {x y : A} (p : x = y) (q : y = x) :\n  q @ p = 1 -> p = q^.\nProof.\n  destruct q.\n  intro h. exact ((concat_1p _)^ @ h).\nDefined.\n\nDefinition moveR_M1 {A : Type} {x y : A} (p q : x = y) :\n  1 = p^ @ q -> p = q.\nProof.\n  destruct p.\n  intro h. exact (h @ (concat_1p _)).\nDefined.\n\nDefinition moveR_1M {A : Type} {x y : A} (p q : x = y) :\n  1 = q @ p^ -> p = q.\nProof.\n  destruct p.\n  intro h. exact (h @ (concat_p1 _)).\nDefined.\n\nDefinition moveR_1V {A : Type} {x y : A} (p : x = y) (q : y = x) :\n  1 = q @ p -> p^ = q.\nProof.\n  destruct p.\n  intro h. exact (h @ (concat_p1 _)).\nDefined.\n\nDefinition moveR_V1 {A : Type} {x y : A} (p : x = y) (q : y = x) :\n  1 = p @ q -> p^ = q.\nProof.\n  destruct p.\n  intro h. exact (h @ (concat_1p _)).\nDefined.\n\nDefinition moveR_transport_p {A : Type} (P : A -> Type) {x y : A}\n  (p : x = y) (u : P x) (v : P y)\n  : u = p^ # v -> p # u = v.\nProof.\n  destruct p.\n  exact idmap.\nDefined.\n\nDefinition moveR_transport_V {A : Type} (P : A -> Type) {x y : A}\n  (p : y = x) (u : P x) (v : P y)\n  : u = p # v -> p^ # u = v.\nProof.\n  destruct p.\n  exact idmap.\nDefined.\n\nDefinition moveL_transport_V {A : Type} (P : A -> Type) {x y : A}\n  (p : x = y) (u : P x) (v : P y)\n  : p # u = v -> u = p^ # v.\nProof.\n  destruct p.\n  exact idmap.\nDefined.\n\nDefinition moveL_transport_p {A : Type} (P : A -> Type) {x y : A}\n  (p : y = x) (u : P x) (v : P y)\n  : p^ # u = v -> u = p # v.\nProof.\n  destruct p.\n  exact idmap.\nDefined.\n\nDefinition moveR_transport_p_V {A : Type} (P : A -> Type) {x y : A}\n           (p : x = y) (u : P x) (v : P y) (q : u = p^ # v)\n  : (moveR_transport_p P p u v q)^ = moveL_transport_p P p v u q^.\nProof.\n  destruct p; reflexivity.\nDefined.\n\nDefinition moveR_transport_V_V {A : Type} (P : A -> Type) {x y : A}\n           (p : y = x) (u : P x) (v : P y) (q : u = p # v)\n  : (moveR_transport_V P p u v q)^ = moveL_transport_V P p v u q^.\nProof.\n  destruct p; reflexivity.\nDefined.\n\nDefinition moveL_transport_V_V {A : Type} (P : A -> Type) {x y : A}\n           (p : x = y) (u : P x) (v : P y) (q : p # u = v)\n  : (moveL_transport_V P p u v q)^ = moveR_transport_V P p v u q^.\nProof.\n  destruct p; reflexivity.\nDefined.\n\nDefinition moveL_transport_p_V {A : Type} (P : A -> Type) {x y : A}\n           (p : y = x) (u : P x) (v : P y) (q : p^ # u = v)\n  : (moveL_transport_p P p u v q)^ = moveR_transport_p P p v u q^.\nProof.\n  destruct p; reflexivity.\nDefined.\n\n\nDefinition ap_1 {A B : Type} (x : A) (f : A -> B) :\n  ap f 1 = 1 :> (f x = f x)\n  := 1.\n\nDefinition apD_1 {A B} (x : A) (f : forall x : A, B x) :\n  apD f 1 = 1 :> (f x = f x)\n  := 1.\n\nDefinition ap_pp {A B : Type} (f : A -> B) {x y z : A} (p : x = y) (q : y = z) :\n  ap f (p @ q) = (ap f p) @ (ap f q).\n  now destruct p, q.\nDefined.\n\nDefinition ap_p_pp {A B : Type} (f : A -> B) {w : B} {x y z : A}\n  (r : w = f x) (p : x = y) (q : y = z) :\n  r @ (ap f (p @ q)) = (r @ ap f p) @ (ap f q).\nProof.\n  destruct p, q. simpl. exact (concat_p_pp r 1 1).\nDefined.\n\nDefinition ap_pp_p {A B : Type} (f : A -> B) {x y z : A} {w : B}\n  (p : x = y) (q : y = z) (r : f z = w) :\n  (ap f (p @ q)) @ r = (ap f p) @ (ap f q @ r).\nProof.\n  destruct p, q. simpl. exact (concat_pp_p 1 1 r).\nDefined.\n\nDefinition inverse_ap {A B : Type} (f : A -> B) {x y : A} (p : x = y) :\n  (ap f p)^ = ap f (p^).\n  now destruct p.\nDefined.\n\nDefinition ap_V {A B : Type} (f : A -> B) {x y : A} (p : x = y) :\n  ap f (p^) = (ap f p)^.\n  now destruct p.\nDefined.\n\nDefinition ap_idmap {A : Type} {x y : A} (p : x = y) :\n  ap idmap p = p.\n  now destruct p.\nDefined.\n\nDefinition ap_compose {A B C : Type} (f : A -> B) (g : B -> C) {x y : A} (p : x = y) :\n  ap (g o f) p = ap g (ap f p).\n  now destruct p.\nDefined.\n\nDefinition ap_compose' {A B C : Type} (f : A -> B) (g : B -> C) {x y : A} (p : x = y) :\n  ap (fun a => g (f a)) p = ap g (ap f p).\n  now destruct p.\nDefined.\n\nDefinition ap_const {A B : Type} {x y : A} (p : x = y) (z : B) :\n  ap (fun _ => z) p = 1.\n  now destruct p.\nDefined.\n\nDefinition concat_Ap {A B : Type} {f g : A -> B} (p : forall x, f x = g x) {x y : A} (q : x = y) :\n  (ap f q) @ (p y) = (p x) @ (ap g q).\n  destruct q. cbn. now rewrite concat_p1, concat_1p.\nDefined.\n\nDefinition concat_A1p {A : Type} {f : A -> A} (p : forall x, f x = x) {x y : A} (q : x = y) :\n  (ap f q) @ (p y) = (p x) @ q.\n  destruct q. cbn. now rewrite concat_p1, concat_1p.\nDefined.\n\nDefinition concat_pA1 {A : Type} {f : A -> A} (p : forall x, x = f x) {x y : A} (q : x = y) :\n  (p x) @ (ap f q) =  q @ (p y).\n  destruct q. cbn. now rewrite concat_p1, concat_1p.\nDefined.\n\nDefinition concat_pA_pp {A B : Type} {f g : A -> B} (p : forall x, f x = g x)\n  {x y : A} (q : x = y)\n  {w z : B} (r : w = f x) (s : g y = z)\n  :\n  (r @ ap f q) @ (p y @ s) = (r @ p x) @ (ap g q @ s).\nProof.\n  destruct q, s; simpl.\n  repeat rewrite concat_p1.\n  reflexivity.\nDefined.\n\nDefinition concat_pA_p {A B : Type} {f g : A -> B} (p : forall x, f x = g x)\n  {x y : A} (q : x = y)\n  {w : B} (r : w = f x)\n  :\n  (r @ ap f q) @ p y = (r @ p x) @ ap g q.\nProof.\n  destruct q; simpl.\n  repeat rewrite concat_p1.\n  reflexivity.\nDefined.\n\nDefinition concat_A_pp {A B : Type} {f g : A -> B} (p : forall x, f x = g x)\n  {x y : A} (q : x = y)\n  {z : B} (s : g y = z)\n  :\n  (ap f q) @ (p y @ s) = (p x) @ (ap g q @ s).\nProof.\n  destruct q, s; cbn.\n  repeat rewrite concat_p1, concat_1p.\n  reflexivity.\nDefined.\n\nDefinition concat_pA1_pp {A : Type} {f : A -> A} (p : forall x, f x = x)\n  {x y : A} (q : x = y)\n  {w z : A} (r : w = f x) (s : y = z)\n  :\n  (r @ ap f q) @ (p y @ s) = (r @ p x) @ (q @ s).\nProof.\n  destruct q, s; simpl.\n  repeat rewrite concat_p1.\n  reflexivity.\nDefined.\n\nDefinition concat_pp_A1p {A : Type} {g : A -> A} (p : forall x, x = g x)\n  {x y : A} (q : x = y)\n  {w z : A} (r : w = x) (s : g y = z)\n  :\n  (r @ p x) @ (ap g q @ s) = (r @ q) @ (p y @ s).\nProof.\n  destruct q, s; simpl.\n  repeat rewrite concat_p1.\n  reflexivity.\nDefined.\n\nDefinition concat_pA1_p {A : Type} {f : A -> A} (p : forall x, f x = x)\n  {x y : A} (q : x = y)\n  {w : A} (r : w = f x)\n  :\n  (r @ ap f q) @ p y = (r @ p x) @ q.\nProof.\n  destruct q; simpl.\n  repeat rewrite concat_p1.\n  reflexivity.\nDefined.\n\nDefinition concat_A1_pp {A : Type} {f : A -> A} (p : forall x, f x = x)\n  {x y : A} (q : x = y)\n  {z : A} (s : y = z)\n  :\n  (ap f q) @ (p y @ s) = (p x) @ (q @ s).\nProof.\n  destruct q, s; cbn.\n  repeat rewrite concat_p1, concat_1p.\n  reflexivity.\nDefined.\n\nDefinition concat_pp_A1 {A : Type} {g : A -> A} (p : forall x, x = g x)\n  {x y : A} (q : x = y)\n  {w : A} (r : w = x)\n  :\n  (r @ p x) @ ap g q = (r @ q) @ p y.\nProof.\n  destruct q; simpl.\n  repeat rewrite concat_p1.\n  reflexivity.\nDefined.\n\nDefinition concat_p_A1p {A : Type} {g : A -> A} (p : forall x, x = g x)\n  {x y : A} (q : x = y)\n  {z : A} (s : g y = z)\n  :\n  p x @ (ap g q @ s) = q @ (p y @ s).\nProof.\n  destruct q, s; simpl.\n  repeat rewrite concat_p1, concat_1p.\n  reflexivity.\nDefined.\n\nLemma concat_1p_1 {A} {x : A} (p : x = x) (q : p = 1)\n: concat_1p p @ q = ap (fun p' => 1 @ p') q.\nProof.\n  rewrite <- (inv_V q).\n  set (r := q^). clearbody r; clear q; destruct r.\n  reflexivity.\nDefined.\n\nLemma concat_p1_1 {A} {x : A} (p : x = x) (q : p = 1)\n: concat_p1 p @ q = ap (fun p' => p' @ 1) q.\nProof.\n  rewrite <- (inv_V q).\n  set (r := q^). clearbody r; clear q; destruct r.\n  reflexivity.\nDefined.\n\nDefinition apD10_1 {A} {B:A->Type} (f : forall x, B x) (x:A)\n  : apD10 (idpath f) x = 1\n:= 1.\n\nDefinition apD10_pp {A} {B:A->Type} {f f' f'' : forall x, B x}\n  (h:f=f') (h':f'=f'') (x:A)\n: apD10 (h @ h') x = apD10 h x @ apD10 h' x.\nProof.\n  case h, h'; reflexivity.\nDefined.\n\nDefinition apD10_V {A} {B:A->Type} {f g : forall x, B x} (h:f=g) (x:A)\n  : apD10 (h^) x = (apD10 h x)^.\n  now destruct h.\nDefined.\n\nDefinition ap10_1 {A B} {f:A->B} (x:A) : ap10 (idpath f) x = 1\n  := 1.\n\nDefinition ap10_pp {A B} {f f' f'':A->B} (h:f=f') (h':f'=f'') (x:A)\n  : ap10 (h @ h') x = ap10 h x @ ap10 h' x\n:= apD10_pp h h' x.\n\nDefinition ap10_V {A B} {f g : A->B} (h : f = g) (x:A)\n  : ap10 (h^) x = (ap10 h x)^\n:= apD10_V h x.\n\nDefinition apD10_ap_precompose {A B C} (f : A -> B) {g g' : forall x:B, C x} (p : g = g') a\n: apD10 (ap (fun h : forall x:B, C x => h oD f) p) a = apD10 p (f a).\nProof.\n  destruct p; reflexivity.\nDefined.\n\nDefinition ap10_ap_precompose {A B C} (f : A -> B) {g g' : B -> C} (p : g = g') a\n: ap10 (ap (fun h : B -> C => h o f) p) a = ap10 p (f a)\n  := apD10_ap_precompose f p a.\n\nDefinition apD10_ap_postcompose {A B C} (f : forall x, B x -> C) {g g' : forall x:A, B x} (p : g = g') a\n: apD10 (ap (fun h : forall x:A, B x => fun x => f x (h x)) p) a = ap (f a) (apD10 p a).\nProof.\n  destruct p; reflexivity.\nDefined.\n\nDefinition ap10_ap_postcompose {A B C} (f : B -> C) {g g' : A -> B} (p : g = g') a\n: ap10 (ap (fun h : A -> B => f o h) p) a = ap f (ap10 p a)\n:= apD10_ap_postcompose (fun a => f) p a.\n\n\nDefinition transport_1 {A : Type} (P : A -> Type) {x : A} (u : P x)\n  : 1 # u = u\n:= 1.\n\nDefinition transport_pp {A : Type} (P : A -> Type) {x y z : A} (p : x = y) (q : y = z) (u : P x) :\n  p @ q # u = q # p # u.\n  now destruct p, q.\nDefined.\n\nDefinition transport_pV {A : Type} (P : A -> Type) {x y : A} (p : x = y) (z : P y)\n  : p # p^ # z = z\n  := (transport_pp P p^ p z)^\n  @ ap (fun r => transport P r z) (concat_Vp p).\n\nDefinition transport_Vp {A : Type} (P : A -> Type) {x y : A} (p : x = y) (z : P x)\n  : p^ # p # z = z\n  := (transport_pp P p p^ z)^\n  @ ap (fun r => transport P r z) (concat_pV p).\n\nDefinition transport_p_pp {A : Type} (P : A -> Type)\n  {x y z w : A} (p : x = y) (q : y = z) (r : z = w)\n  (u : P x)\n  : ap (fun e => e # u) (concat_p_pp p q r)\n    @ (transport_pp P (p@q) r u) @ ap (transport P r) (transport_pp P p q u)\n  = (transport_pp P p (q@r) u) @ (transport_pp P q r (p#u))\n  :> ((p @ (q @ r)) # u = r # q # p # u) .\nProof.\n  destruct p, q, r.  simpl.  exact 1.\nDefined.\n\nDefinition transport_pVp {A} (P : A -> Type) {x y:A} (p:x=y) (z:P x)\n  : transport_pV P p (transport P p z)\n  = ap (transport P p) (transport_Vp P p z).\nProof.\n  destruct p; reflexivity.\nDefined.\n\nDefinition transport_VpV {A} (P : A -> Type) {x y : A} (p : x = y) (z : P y)\n  : transport_Vp P p (transport P p^ z)\n    = ap (transport P p^) (transport_pV P p z).\nProof.\n  destruct p; reflexivity.\nDefined.\n\nDefinition ap_transport_transport_pV {A} (P : A -> Type) {x y : A}\n           (p : x = y) (u : P x) (v : P y) (e : transport P p u = v)\n  : ap (transport P p) (moveL_transport_V P p u v e)\n       @ transport_pV P p v = e.\nProof.\n    now destruct e, p.\nDefined.\n\nDefinition moveL_transport_V_1 {A} (P : A -> Type) {x y : A}\n           (p : x = y) (u : P x)\n  : moveL_transport_V P p u (p # u) 1 = (transport_Vp P p u)^.\nProof.\n  destruct p; reflexivity.\nDefined.\n\n\n\nDefinition ap11_is_ap10_ap01 {A B} {f g:A->B} (h:f=g) {x y:A} (p:x=y)\n: ap11 h p = ap10 h x @ ap g p.\n  now destruct h, p.\nDefined.\n\nDefinition transportD {A : Type} (B : A -> Type) (C : forall a:A, B a -> Type)\n  {x1 x2 : A} (p : x1 = x2) (y : B x1) (z : C x1 y)\n  : C x2 (p # y).\n  now destruct p.\nDefined.\n\nDefinition transportD2 {A : Type} (B C : A -> Type) (D : forall a:A, B a -> C a -> Type)\n  {x1 x2 : A} (p : x1 = x2) (y : B x1) (z : C x1) (w : D x1 y z)\n  : D x2 (p # y) (p # z).\n  now destruct p.\nDefined.\n\nDefinition ap011 {A B C} (f : A -> B -> C) {x x' y y'} (p : x = x') (q : y = y')\n: f x y = f x' y'\n:= ap11 (ap f p) q.\n\nDefinition ap011D {A B C} (f : forall (a:A), B a -> C)\n           {x x'} (p : x = x') {y y'} (q : p # y = y')\n: f x y = f x' y'.\nProof.\n  destruct p, q; reflexivity.\nDefined.\n\nDefinition ap01D1 {A B C} (f : forall (a:A), B a -> C a)\n           {x x'} (p : x = x') {y y'} (q : p # y = y')\n: transport C p (f x y) = f x' y'.\nProof.\n  destruct p, q; reflexivity.\nDefined.\n\nDefinition apD011 {A B C} (f : forall (a:A) (b:B a), C a b)\n           {x x'} (p : x = x') {y y'} (q : p # y = y')\n: transport (C x') q (transportD B C p y (f x y)) = f x' y'.\nProof.\n  destruct p, q; reflexivity.\nDefined.\n\nDefinition transport2 {A : Type} (P : A -> Type) {x y : A} {p q : x = y}\n  (r : p = q) (z : P x)\n  : p # z = q # z\n  := ap (fun p' => p' # z) r.\n\nDefinition transport2_is_ap10 {A : Type} (Q : A -> Type) {x y : A} {p q : x = y}\n  (r : p = q) (z : Q x)\n  : transport2 Q r z = ap10 (ap (transport Q) r) z.\n  now destruct r.\nDefined.\n\nDefinition transport2_p2p {A : Type} (P : A -> Type) {x y : A} {p1 p2 p3 : x = y}\n  (r1 : p1 = p2) (r2 : p2 = p3) (z : P x)\n  : transport2 P (r1 @ r2) z = transport2 P r1 z @ transport2 P r2 z.\nProof.\n  destruct r1, r2; reflexivity.\nDefined.\n\nDefinition transport2_V {A : Type} (Q : A -> Type) {x y : A} {p q : x = y}\n  (r : p = q) (z : Q x)\n  : transport2 Q (r^) z = (transport2 Q r z)^.\n  now destruct r.\nDefined.\n\nDefinition concat_AT {A : Type} (P : A -> Type) {x y : A} {p q : x = y}\n  {z w : P x} (r : p = q) (s : z = w)\n  : ap (transport P p) s  @  transport2 P r w\n    = transport2 P r z  @  ap (transport P q) s.\n  now destruct r, s.\nDefined.\n\nLemma ap_transport {A} {P Q : A -> Type} {x y : A} (p : x = y) (f : forall x, P x -> Q x) (z : P x) :\n  f y (p # z) = (p # (f x z)).\n  now destruct p.\nDefined.\n\nLemma ap_transportD {A : Type}\n      (B : A -> Type) (C1 C2 : forall a : A, B a -> Type)\n      (f : forall a b, C1 a b -> C2 a b)\n      {x1 x2 : A} (p : x1 = x2) (y : B x1) (z : C1 x1 y)\n: f x2 (p # y) (transportD B C1 p y z)\n  = transportD B C2 p y (f x1 y z).\nProof.\n  now destruct p.\nDefined.\n\nLemma ap_transportD2 {A : Type}\n      (B C : A -> Type) (D1 D2 : forall a, B a -> C a -> Type)\n      (f : forall a b c, D1 a b c -> D2 a b c)\n      {x1 x2 : A} (p : x1 = x2) (y : B x1) (z : C x1) (w : D1 x1 y z)\n: f x2 (p # y) (p # z) (transportD2 B C D1 p y z w)\n  = transportD2 B C D2 p y z (f x1 y z w).\nProof.\n  now destruct p.\nDefined.\n\nLemma ap_transport_pV {X} (Y : X -> Type) {x1 x2 : X} (p : x1 = x2)\n      {y1 y2 : Y x2} (q : y1 = y2)\n: ap (transport Y p) (ap (transport Y p^) q) =\n  transport_pV Y p y1 @ q @ (transport_pV Y p y2)^.\nProof.\n  destruct p, q; reflexivity.\nDefined.\n\nDefinition transport_pV_ap {X} (P : X -> Type) (f : forall x, P x)\n      {x1 x2 : X} (p : x1 = x2)\n: ap (transport P p) (apD f p^) @ apD f p = transport_pV P p (f x2).\nProof.\n  destruct p; reflexivity.\nDefined.\n\nDefinition apD_pp {A} {P : A -> Type} (f : forall x, P x)\n           {x y z : A} (p : x = y) (q : y = z)\n  : apD f (p @ q)\n    = transport_pp P p q (f x) @ ap (transport P q) (apD f p) @ apD f q.\nProof.\n  destruct p, q; reflexivity.\nDefined.\n\nDefinition apD_V {A} {P : A -> Type} (f : forall x, P x)\n           {x y : A} (p : x = y)\n  : apD f p^ = moveR_transport_V _ _ _ _ (apD f p)^.\nProof.\n  destruct p; reflexivity.\nDefined.\nDefinition transport_const {A B : Type} {x1 x2 : A} (p : x1 = x2) (y : B)\n  : transport (fun x => B) p y = y.\nProof.\n  destruct p.  exact 1.\nDefined.\n\nDefinition transport2_const {A B : Type} {x1 x2 : A} {p q : x1 = x2}\n  (r : p = q) (y : B)\n  : transport_const p y = transport2 (fun _ => B) r y @ transport_const q y.\n  destruct r. symmetry; apply concat_1p.\nDefined.\n\nLemma transport_compose {A B} {x y : A} (P : B -> Type) (f : A -> B)\n  (p : x = y) (z : P (f x))\n  : transport (fun x => P (f x)) p z  =  transport P (ap f p) z.\nProof.\n  destruct p; reflexivity.\nDefined.\n\nLemma transportD_compose {A A'} B {x x' : A} (C : forall x : A', B x -> Type) (f : A -> A')\n      (p : x = x') y (z : C (f x) y)\n: transportD (B o f) (C oD f) p y z\n  = transport (C (f x')) (transport_compose B f p y)^ (transportD B C (ap f p) y z).\nProof.\n  destruct p; reflexivity.\nDefined.\n\nLemma transport_apD_transportD {A} B (f : forall x : A, B x) (C : forall x, B x -> Type)\n      {x1 x2 : A} (p : x1 = x2) (z : C x1 (f x1))\n: apD f p # transportD B C p _ z\n  = transport (fun x => C x (f x)) p z.\nProof.\n  destruct p; reflexivity.\nDefined.\n\nLemma transport_precompose {A B C} (f : A -> B) (g g' : B -> C) (p : g = g')\n: transport (fun h : B -> C => g o f = h o f) p 1 =\n  ap (fun h => h o f) p.\nProof.\n  destruct p; reflexivity.\nDefined.\n\nDefinition transport_idmap_ap A (P : A -> Type) x y (p : x = y) (u : P x)\n: transport P p u = transport idmap (ap P p) u.\n  now destruct p.\nDefined.\n\n(** Sometimes, it's useful to have the goal be in terms of [ap], so we can use lemmas about [ap].  However, we can't just [rewrite !transport_idmap_ap], as that's likely to loop.  So, instead, we provide a tactic [transport_to_ap], that replaces all [transport P p u] with [transport idmap (ap P p) u] for non-[idmap] [P]. *)\nLtac transport_to_ap :=\n  repeat match goal with\n           | [ |- context[transport ?P ?p ?u] ]\n             => match P with\n                  | idmap => fail 1 (* we don't want to turn [transport idmap (ap _ _)] into [transport idmap (ap idmap (ap _ _))] *)\n                  | _ => idtac\n                end;\n               progress rewrite (transport_idmap_ap _ P _ _ p u)\n         end.\n\nDefinition transport_transport {A B} (C : A -> B -> Type)\n           {x1 x2 : A} (p : x1 = x2) {y1 y2 : B} (q : y1 = y2)\n           (c : C x1 y1)\n: transport (C x2) q (transport (fun x => C x y1) p c)\n  = transport (fun x => C x y2) p (transport (C x1) q c).\nProof.\n  destruct p, q; reflexivity.\nDefined.\n\nLemma apD_const {A B} {x y : A} (f : A -> B) (p: x = y) :\n  apD f p = transport_const p (f x) @ ap f p.\nProof.\n  destruct p; reflexivity.\nDefined.\n\nDefinition concat2 {A} {x y z : A} {p p' : x = y} {q q' : y = z} (h : p = p') (h' : q = q')\n  : p @ q = p' @ q'.\n  now destruct h, h'.\nDefined.\n\nNotation \"p @@ q\" := (concat2 p q)%path (at level 20) : path_scope.\n\nArguments concat2 : simpl nomatch.\n\nLemma concat2_ap_ap {A B : Type} {x' y' z' : B}\n           (f : A -> (x' = y')) (g : A -> (y' = z'))\n           {x y : A} (p : x = y)\n: (ap f p) @@ (ap g p) = ap (fun u => f u @ g u) p.\nProof.\n    now destruct p.\nDefined.\n\nDefinition inverse2 {A : Type} {x y : A} {p q : x = y} (h : p = q)\n  : p^ = q^\n:= ap inverse h.\n\nLemma ap_pp_concat_pV {A B} (f : A -> B) {x y : A} (p : x = y)\n: ap_pp f p p^ @ ((1 @@ ap_V f p) @ concat_pV (ap f p))\n  = ap (ap f) (concat_pV p).\nProof.\n  destruct p; reflexivity.\nDefined.\n\nLemma ap_pp_concat_Vp {A B} (f : A -> B) {x y : A} (p : x = y)\n: ap_pp f p^ p @ ((ap_V f p @@ 1) @ concat_Vp (ap f p))\n  = ap (ap f) (concat_Vp p).\nProof.\n  destruct p; reflexivity.\nDefined.\n\nLemma concat_pV_inverse2 {A} {x y : A} (p q : x = y) (r : p = q)\n: (r @@ inverse2 r) @ concat_pV q = concat_pV p.\nProof.\n  destruct r, p; reflexivity.\nDefined.\n\nLemma concat_Vp_inverse2 {A} {x y : A} (p q : x = y) (r : p = q)\n: (inverse2 r @@ r) @ concat_Vp q = concat_Vp p.\nProof.\n  destruct r, p; reflexivity.\nDefined.\n\nDefinition whiskerL {A : Type} {x y z : A} (p : x = y)\n  {q r : y = z} (h : q = r) : p @ q = p @ r\n:= 1 @@ h.\n\nDefinition whiskerR {A : Type} {x y z : A} {p q : x = y}\n  (h : p = q) (r : y = z) : p @ r = q @ r\n:= h @@ 1.\n\nDefinition cancelL {A} {x y z : A} (p : x = y) (q r : y = z)\n: (p @ q = p @ r) -> (q = r)\n:= fun h => (concat_V_pp p q)^ @ whiskerL p^ h @ (concat_V_pp p r).\n\nDefinition cancelR {A} {x y z : A} (p q : x = y) (r : y = z)\n: (p @ r = q @ r) -> (p = q)\n:= fun h => (concat_pp_V p r)^ @ whiskerR h r^ @ (concat_pp_V q r).\n\nDefinition whiskerR_p1 {A : Type} {x y : A} {p q : x = y} (h : p = q) :\n  (concat_p1 p) ^ @ whiskerR h 1 @ concat_p1 q = h.\n  now destruct h, p.\nDefined.\n\nDefinition whiskerR_1p {A : Type} {x y z : A} (p : x = y) (q : y = z) :\n  whiskerR 1 q = 1 :> (p @ q = p @ q).\n  reflexivity.\nDefined.\n\nDefinition whiskerL_p1 {A : Type} {x y z : A} (p : x = y) (q : y = z) :\n  whiskerL p 1 = 1 :> (p @ q = p @ q).\n  reflexivity.\nDefined.\n\nDefinition whiskerL_1p {A : Type} {x y : A} {p q : x = y} (h : p = q) :\n  (concat_1p p) ^ @ whiskerL 1 h @ concat_1p q = h.\n  now destruct h, p.\nDefined.\n\nDefinition whiskerR_p1_1 {A} {x : A} (h : idpath x = idpath x)\n: whiskerR h 1 = h.\nProof.\n  refine (_ @ whiskerR_p1 h); simpl.\n  symmetry; refine (concat_p1 _ @ concat_1p _).\nDefined.\n\nDefinition whiskerL_1p_1 {A} {x : A} (h : idpath x = idpath x)\n: whiskerL 1 h = h.\nProof.\n  refine (_ @ whiskerL_1p h); simpl.\n  symmetry; refine (concat_p1 _ @ concat_1p _).\nDefined.\n\nDefinition concat2_p1 {A : Type} {x y : A} {p q : x = y} (h : p = q) :\n  h @@ 1 = whiskerR h 1 :> (p @ 1 = q @ 1).\n  now destruct h.\nDefined.\n\nDefinition concat2_1p {A : Type} {x y : A} {p q : x = y} (h : p = q) :\n  1 @@ h = whiskerL 1 h :> (1 @ p = 1 @ q).\n  now destruct h.\nDefined.\n\nDefinition cancel2L {A : Type} {x y z : A} {p p' : x = y} {q q' : y = z}\n           (g : p = p') (h k : q = q')\n: (g @@ h = g @@ k) -> (h = k).\nProof.\n  intro r. destruct g, p, q.\n  refine ((whiskerL_1p h)^ @ _). refine (_ @ (whiskerL_1p k)).\n  refine (whiskerR _ _). refine (whiskerL _ _).\n  apply r.\nDefined.\n\nDefinition cancel2R {A : Type} {x y z : A} {p p' : x = y} {q q' : y = z}\n           (g h : p = p') (k : q = q')\n: (g @@ k = h @@ k) -> (g = h).\nProof.\n  intro r. destruct k, p, q.\n  refine ((whiskerR_p1 g)^ @ _). refine (_ @ (whiskerR_p1 h)).\n  refine (whiskerR _ _). refine (whiskerL _ _).\n  apply r.\nDefined.\n\nDefinition whiskerL_pp {A} {x y z : A} (p : x = y) {q q' q'' : y = z}\n           (r : q = q') (s : q' = q'')\n: whiskerL p (r @ s) = whiskerL p r @ whiskerL p s.\nProof.\n  destruct p, r, s; reflexivity.\nDefined.\n\nDefinition whiskerR_pp {A} {x y z : A} {p p' p'' : x = y} (q : y = z)\n           (r : p = p') (s : p' = p'')\n: whiskerR (r @ s) q = whiskerR r q @ whiskerR s q.\nProof.\n  destruct q, r, s; reflexivity.\nDefined.\n\nDefinition whiskerL_VpL {A} {x y z : A} (p : x = y)\n           {q q' : y = z} (r : q = q')\n: (concat_V_pp p q)^ @ whiskerL p^ (whiskerL p r) @ concat_V_pp p q'\n  = r.\nProof.\n  destruct p, r, q. reflexivity.\nDefined.\n\nDefinition whiskerL_pVL {A} {x y z : A} (p : y = x)\n           {q q' : y = z} (r : q = q')\n: (concat_p_Vp p q)^ @ whiskerL p (whiskerL p^ r) @ concat_p_Vp p q'\n  = r.\nProof.\n  destruct p, r, q. reflexivity.\nDefined.\n\nDefinition whiskerR_pVR {A} {x y z : A} {p p' : x = y}\n           (r : p = p') (q : y = z)\n: (concat_pp_V p q)^ @ whiskerR (whiskerR r q) q^ @ concat_pp_V p' q\n  = r.\nProof.\n  destruct p, r, q. reflexivity.\nDefined.\n\nDefinition whiskerR_VpR {A} {x y z : A} {p p' : x = y}\n           (r : p = p') (q : z = y)\n: (concat_pV_p p q)^ @ whiskerR (whiskerR r q^) q @ concat_pV_p p' q\n  = r.\nProof.\n  destruct p, r, q. reflexivity.\nDefined.\n\nDefinition concat_concat2 {A : Type} {x y z : A} {p p' p'' : x = y} {q q' q'' : y = z}\n  (a : p = p') (b : p' = p'') (c : q = q') (d : q' = q'') :\n  (a @@ c) @ (b @@ d) = (a @ b) @@ (c @ d).\nProof.\n  case d.\n  case c.\n  case b.\n  case a.\n  reflexivity.\nDefined.\n\nDefinition concat_whisker {A} {x y z : A} (p p' : x = y) (q q' : y = z) (a : p = p') (b : q = q') :\n  (whiskerR a q) @ (whiskerL p' b) = (whiskerL p b) @ (whiskerR a q').\n  destruct b, a; symmetry; eapply concat_1p.\nDefined.\n\nDefinition pentagon {A : Type} {v w x y z : A} (p : v = w) (q : w = x) (r : x = y) (s : y = z)\n  : whiskerL p (concat_p_pp q r s)\n      @ concat_p_pp p (q@r) s\n      @ whiskerR (concat_p_pp p q r) s\n  = concat_p_pp p q (r@s) @ concat_p_pp (p@q) r s.\nProof.\n  case p, q, r, s.  reflexivity.\nDefined.\n\nDefinition triangulator {A : Type} {x y z : A} (p : x = y) (q : y = z)\n  : concat_p_pp p 1 q @ whiskerR (concat_p1 p) q\n  = whiskerL p (concat_1p q).\nProof.\n  case p, q.  reflexivity.\nDefined.\n\nDefinition eckmann_hilton {A : Type} {x:A} (p q : 1 = 1 :> (x = x)) : p @ q = q @ p :=\n  (whiskerR_p1 p @@ whiskerL_1p q)^\n  @ (concat_p1 _ @@ concat_p1 _)\n  @ (concat_1p _ @@ concat_1p _)\n  @ (concat_whisker _ _ _ _ p q)\n  @ (concat_1p _ @@ concat_1p _)^\n  @ (concat_p1 _ @@ concat_p1 _)^\n  @ (whiskerL_1p q @@ whiskerR_p1 p).\n\nDefinition ap02 {A B : Type} (f:A->B) {x y:A} {p q:x=y} (r:p=q) : ap f p = ap f q.\n  now destruct r.\nDefined.\n\nDefinition ap02_pp {A B} (f:A->B) {x y:A} {p p' p'':x=y} (r:p=p') (r':p'=p'')\n  : ap02 f (r @ r') = ap02 f r @ ap02 f r'.\nProof.\n  case r, r'; reflexivity.\nDefined.\n\nDefinition ap02_p2p {A B} (f:A->B) {x y z:A} {p p':x=y} {q q':y=z} (r:p=p') (s:q=q')\n  : ap02 f (r @@ s) =   ap_pp f p q\n                      @ (ap02 f r  @@  ap02 f s)\n                      @ (ap_pp f p' q')^.\nProof.\n  case r, s, p, q. reflexivity.\nDefined.\n\nDefinition apD02 {A : Type} {B : A -> Type} {x y : A} {p q : x = y}\n  (f : forall x, B x) (r : p = q)\n  : apD f p = transport2 B r (f x) @ apD f q.\n  destruct r; symmetry; eapply concat_1p.\nDefined.\n\nDefinition apD02_const {A B : Type} (f : A -> B) {x y : A} {p q : x = y} (r : p = q)\n: apD02 f r = (apD_const f p)\n              @ (transport2_const r (f x) @@ ap02 f r)\n              @ (concat_p_pp _ _ _)^\n              @ (whiskerL (transport2 _ r (f x)) (apD_const f q)^).\n  now destruct r, p.\nDefined.\n\nDefinition apD02_pp {A} (B : A -> Type) (f : forall x:A, B x) {x y : A}\n  {p1 p2 p3 : x = y} (r1 : p1 = p2) (r2 : p2 = p3)\n  : apD02 f (r1 @ r2)\n  = apD02 f r1\n  @ whiskerL (transport2 B r1 (f x)) (apD02 f r2)\n  @ concat_p_pp _ _ _\n  @ (whiskerR (transport2_p2p B r1 r2 (f x))^ (apD f p3)).\nProof.\n  destruct r1, r2. destruct p1. reflexivity.\nDefined.\n\nDefinition ap_transport_Vp_idmap {A B} (p q : A = B) (r : q = p) (z : A)\n: ap (transport idmap q^) (ap (fun s => transport idmap s z) r)\n  @ ap (fun s => transport idmap s (p # z)) (inverse2 r)\n  @ transport_Vp idmap p z\n  = transport_Vp idmap q z.\nProof.\n  now destruct r, q.\nDefined.\n\nDefinition ap_transport_pV_idmap {A B} (p q : A = B) (r : q = p) (z : B)\n: ap (transport idmap q) (ap (fun s => transport idmap s^ z) r)\n  @ ap (fun s => transport idmap s (p^ # z)) r\n  @ transport_pV idmap p z\n  = transport_pV idmap q z.\nProof.\n  now destruct r, q.\nDefined.\n\nNotation concatR := (fun p q => concat q p).\n\nHint Resolve\n  concat_1p concat_p1 concat_p_pp\n  inv_pp inv_V\n : path_hints.\n\nHint Rewrite\n@concat_p1\n@concat_1p\n@concat_p_pp (* there is a choice here !*)\n@concat_pV\n@concat_Vp\n@concat_V_pp\n@concat_p_Vp\n@concat_pp_V\n@concat_pV_p\n(*@inv_pp*) (* I am not sure about this one *)\n@inv_V\n@moveR_Mp\n@moveR_pM\n@moveL_Mp\n@moveL_pM\n@moveL_1M\n@moveL_M1\n@moveR_M1\n@moveR_1M\n@ap_1\n(* @ap_pp\n@ap_p_pp ?*)\n@inverse_ap\n@ap_idmap\n(* @ap_compose\n@ap_compose'*)\n@ap_const\n(* Unsure about naturality of [ap], was absent in the old implementation*)\n@apD10_1\n:paths.\n\nLtac hott_simpl :=\n  autorewrite with paths in * |- * ; auto with path_hints.\n\n(* Contractible.v *)\n\n\n(** If a space is contractible, then any two points in it are connected by a path in a canonical way. *)\nDefinition path_contr `{Contr A} (x y : A) : x = y\n  := (contr x)^ @ (contr y).\n\n(** Similarly, any two parallel paths in a contractible space are homotopic, which is just the principle UIP. *)\nDefinition path2_contr `{Contr A} {x y : A} (p q : x = y) : p = q.\nProof.\n  assert (K : forall (r : x = y), r = path_contr x y).\n    intro r; destruct r; symmetry; now apply concat_Vp.\n  transitivity (path_contr x y). apply K. symmetry; apply K.\nDefined.\n\n(** It follows that any space of paths in a contractible space is contractible. *)\n(** Because [Contr] is a notation, and [Contr_internal] is the record, we need to iota expand to fool Coq's typeclass machinery into accepting supposedly \"mismatched\" contexts. *)\n\nGlobal Instance contr_paths_contr `{Contr A} (x y : A) : Contr (x = y) | 10000 := let c := {|\n  center := (contr x)^ @ contr y;\n  contr := path2_contr ((contr x)^ @ contr y)\n|} in c.\n\n(** Also, the total space of any based path space is contractible.  We define the [contr] fields as separate definitions, so that we can give them [simpl nomatch] annotations. *)\n\nDefinition path_basedpaths {X : Type} {x y : X} (p : x = y)\n: (x;1) = (y;p) :> {z:X & x=z}.\nProof.\n  destruct p; reflexivity.\nDefined.\n\nArguments path_basedpaths {X x y} p : simpl nomatch.\n\nGlobal Instance contr_basedpaths {X : Type} (x : X) : Contr {y : X & x = y} | 100.\nProof.\n  exists (x ; 1).\n  intros [y p]; apply path_basedpaths.\nDefined.\n\n(* ??? *)\nDefinition path_basedpaths' {X : Type} {x y : X} (p : y = x)\n: @existT _ (fun z => @paths X z x) x 1 = (y; p).\nProof.\n  destruct p; reflexivity.\nDefined.\n\nGlobal Instance contr_basedpaths' {X : Type} (x : X) : Contr {y : X & y = x} | 100.\nProof.\n  refine (BuildContr _ (@existT _ (fun z => @paths X z x) x 1) _).\n  intros [y p]; apply path_basedpaths'.\nDefined.\n\nArguments path_basedpaths' {X x y} p : simpl nomatch.\n\nDefinition ap_pr1_path_contr_basedpaths {X : Type}\n           {x y z : X} (p : x = y) (q : x = z)\n: ap pr1 (path_contr ((y;p):{y':X & x = y'}) (z;q)) = p^ @ q.\nProof.\n  destruct p,q; reflexivity.\nDefined.\n\nDefinition ap_pr1_path_contr_basedpaths' {X : Type}\n           {x y z : X} (p : y = x) (q : z = x)\n: ap pr1 (path_contr ((y;p):{y':X & y' = x}) (z;q)) = p @ q^.\nProof.\n  destruct p,q; reflexivity.\nDefined.\n\nDefinition ap_pr1_path_basedpaths {X : Type}\n           {x y : X} (p : x = y)\n: ap pr1 (path_basedpaths p) = p.\nProof.\n  destruct p; reflexivity.\nDefined.\n\nDefinition ap_pr1_path_basedpaths' {X : Type}\n           {x y : X} (p : y = x)\n: ap pr1 (path_basedpaths' p) = p^.\nProof.\n  destruct p; reflexivity.\nDefined.\n\n(** If the domain is contractible, the function is propositionally constant. *)\nDefinition contr_dom_equiv {A B} (f : A -> B) `{Contr A} : forall x y : A, f x = f y\n  := fun x y => ap f ((contr x)^ @ contr y).\n\n\n(* Equivalences.v *)\n\nGlobal Instance isequiv_idmap (A : Type) : IsEquiv idmap | 0 :=\n  BuildIsEquiv A A idmap idmap (fun _ => 1) (fun _ => 1) (fun _ => 1).\n\nDefinition equiv_idmap (A : Type) : A <~> A := BuildEquiv A A idmap _.\n\nArguments equiv_idmap {A} , A.\n\nNotation \"1\" := equiv_idmap : equiv_scope.\n\nGlobal Instance reflexive_equiv : Reflexive Equiv | 0 := @equiv_idmap.\n\n(** The composition of equivalences is an equivalence. *)\nGlobal Instance isequiv_compose `{IsEquiv A B f} `{IsEquiv B C g}\n  : IsEquiv (compose g f) | 1000\n  := BuildIsEquiv A C (compose g f)\n    (compose f^-1 g^-1)\n    (fun c => ap g (eisretr f (g^-1 c)) @ eisretr g c)\n    (fun a => ap (f^-1) (eissect g (f a)) @ eissect f a)\n    (fun a =>\n      (whiskerL _ (eisadj g (f a))) @\n      (ap_pp g _ _)^ @\n      ap02 g\n      ( (concat_A1p (eisretr f) (eissect g (f a)))^ @\n        (ap_compose f^-1 f _ @@ eisadj f a) @\n        (ap_pp f _ _)^\n      ) @\n      (ap_compose f g _)^\n    ).\n\n(* An alias of [isequiv_compose], with some arguments explicit; often convenient when type class search fails. *)\nDefinition isequiv_compose'\n  {A B : Type} (f : A -> B) (_ : IsEquiv f)\n  {C : Type} (g : B -> C) (_ : IsEquiv g)\n  : IsEquiv (g o f)\n  := isequiv_compose.\n\nDefinition equiv_compose {A B C : Type} (g : B -> C) (f : A -> B)\n  `{IsEquiv B C g} `{IsEquiv A B f}\n  : A <~> C\n  := BuildEquiv A C (compose g f) _.\n\nDefinition equiv_compose' {A B C : Type} (g : B <~> C) (f : A <~> B)\n  : A <~> C\n  := equiv_compose g f.\n\n(** We put [g] and [f] in [equiv_scope] explcitly.  This is a partial work-around for https://coq.inria.fr/bugs/show_bug.cgi?id=3990, which is that implicitly bound scopes don't nest well. *)\nNotation \"g 'oE' f\" := (equiv_compose' g%equiv f%equiv) (at level 40, left associativity) : equiv_scope.\n\n(* The TypeClass [Transitive] has a different order of parameters than [equiv_compose].  Thus in declaring the instance we have to switch the order of arguments. *)\nGlobal Instance transitive_equiv : Transitive Equiv | 0 :=\n  fun _ _ _ f g => equiv_compose g f.\n\n\n(** Anything homotopic to an equivalence is an equivalence. *)\nSection IsEquivHomotopic.\n\n  Context {A B : Type} (f : A -> B) {g : A -> B}.\n  Context `{IsEquiv A B f}.\n  Hypothesis h : f == g.\n\n  Let sect := (fun b:B => (h (f^-1 b))^ @ eisretr f b).\n  Let retr := (fun a:A => (ap f^-1 (h a))^ @ eissect f a).\n\n  (* We prove the triangle identity with rewrite tactics.  Since we lose control over the proof term that way, we make the result opaque with \"Qed\". *)\n  Let adj (a : A) : sect (g a) = ap g (retr a).\n  Proof.\n    unfold sect, retr.\n    rewrite ap_pp. apply moveR_Vp.\n    rewrite concat_p_pp, <- concat_Ap, concat_pp_p, <- concat_Ap.\n    rewrite ap_V; apply moveL_Vp.\n    rewrite <- ap_compose; rewrite (concat_A1p (eisretr f) (h a)).\n    apply whiskerR, eisadj.\n  Qed.\n\n  (* This should not be an instance; it can cause the unifier to spin forever searching for functions to be hoomotpic to. *)\n  Definition isequiv_homotopic : IsEquiv g\n    := BuildIsEquiv _ _ g (f ^-1) sect retr adj.\n\n  Definition equiv_homotopic : A <~> B\n    := BuildEquiv _ _ g isequiv_homotopic.\n\nEnd IsEquivHomotopic.\n\n\n(** The inverse of an equivalence is an equivalence. *)\nSection EquivInverse.\n\n  Context {A B : Type} (f : A -> B) {feq : IsEquiv f}.\n\n  Theorem other_adj (b : B) : eissect f (f^-1 b) = ap f^-1 (eisretr f b).\n  Proof.\n    (* First we set up the mess. *)\n    rewrite <- (concat_1p (eissect _ _)).\n    rewrite <- (concat_Vp (ap f^-1 (eisretr f (f (f^-1 b))))).\n    rewrite (whiskerR (inverse2 (ap02 f^-1 (eisadj f (f^-1 b)))) _).\n    refine (whiskerL _ (concat_1p (eissect _ _))^ @ _).\n    rewrite <- (concat_Vp (eissect f (f^-1 (f (f^-1 b))))).\n    rewrite <- (whiskerL _ (concat_1p (eissect f (f^-1 (f (f^-1 b)))))).\n    rewrite <- (concat_pV (ap f^-1 (eisretr f (f (f^-1 b))))).\n    apply moveL_M1.\n    repeat rewrite concat_p_pp.\n    (* Now we apply lots of naturality and cancel things. *)\n    rewrite <- (concat_pp_A1 (fun a => (eissect f a)^) _ _).\n    rewrite (ap_compose' f f^-1).\n    rewrite <- (ap_p_pp _ _ (ap f (ap f^-1 (eisretr f (f (f^-1 b))))) _).\n    rewrite <- (ap_compose f^-1 f).\n    rewrite (concat_A1p (eisretr f) _).\n    rewrite ap_pp, concat_p_pp.\n    rewrite (concat_pp_V _ (ap f^-1 (eisretr f (f (f^-1 b))))).\n    repeat rewrite <- ap_V; rewrite <- ap_pp.\n    rewrite <- (concat_pA1 (fun y => (eissect f y)^) _).\n    rewrite ap_compose', <- (ap_compose f^-1 f).\n    rewrite <- ap_p_pp.\n    rewrite (concat_A1p (eisretr f) _).\n    rewrite concat_p_Vp.\n    rewrite <- ap_compose.\n    rewrite (concat_pA1_p (eissect f) _).\n    rewrite concat_pV_p; apply concat_Vp.\n  Qed.\n\n  Global Instance isequiv_inverse : IsEquiv f^-1 | 10000\n    := BuildIsEquiv B A f^-1 f (eissect f) (eisretr f) other_adj.\nEnd EquivInverse.\n\n(** If the goal is [IsEquiv _^-1], then use [isequiv_inverse]; otherwise, don't pretend worry about if the goal is an evar and we want to add a [^-1]. *)\nHint Extern 0 (IsEquiv _^-1) => apply @isequiv_inverse : typeclass_instances.\n\n(** [Equiv A B] is a symmetric relation. *)\nTheorem equiv_inverse {A B : Type} : (A <~> B) -> (B <~> A).\nProof.\n  intro e.\n  exists (e^-1).\n  apply isequiv_inverse.\nDefined.\n\nNotation \"e ^-1\" := (@equiv_inverse _ _ e) : equiv_scope.\n\nGlobal Instance symmetric_equiv : Symmetric Equiv | 0 := @equiv_inverse.\n\n(** If [g \\o f] and [f] are equivalences, so is [g].  This is not an Instance because it would require Coq to guess [f]. *)\nDefinition cancelR_isequiv {A B C} (f : A -> B) {g : B -> C}\n  `{IsEquiv A B f} `{IsEquiv A C (g o f)}\n  : IsEquiv g\n  := isequiv_homotopic (compose (compose g f) f^-1)\n       (fun b => ap g (eisretr f b)).\n\nDefinition cancelR_equiv {A B C} (f : A -> B) {g : B -> C}\n  `{IsEquiv A B f} `{IsEquiv A C (g o f)}\n  : B <~> C\n  := BuildEquiv B C g (cancelR_isequiv f).\n\n(** If [g \\o f] and [g] are equivalences, so is [f]. *)\nDefinition cancelL_isequiv {A B C} (g : B -> C) {f : A -> B}\n  `{IsEquiv B C g} `{IsEquiv A C (g o f)}\n  : IsEquiv f\n  := isequiv_homotopic (compose g^-1 (compose g f))\n       (fun a => eissect g (f a)).\n\nDefinition cancelL_equiv {A B C} (g : B -> C) {f : A -> B}\n  `{IsEquiv B C g} `{IsEquiv A C (g o f)}\n  : A <~> B\n  := BuildEquiv _ _ f (cancelL_isequiv g).\n\n(** Combining these with [isequiv_compose], we see that equivalences can be transported across commutative squares. *)\nDefinition isequiv_commsq {A B C D}\n           (f : A -> B) (g : C -> D) (h : A -> C) (k : B -> D)\n           (p : k o f == g o h)\n           `{IsEquiv _ _ f} `{IsEquiv _ _ h} `{IsEquiv _ _ k}\n: IsEquiv g.\nProof.\n  refine (@cancelR_isequiv _ _ _ h g _ _).\n  refine (isequiv_homotopic _ p).\nDefined.\n\nDefinition isequiv_commsq' {A B C D}\n           (f : A -> B) (g : C -> D) (h : A -> C) (k : B -> D)\n           (p : g o h == k o f)\n           `{IsEquiv _ _ g} `{IsEquiv _ _ h} `{IsEquiv _ _ k}\n: IsEquiv f.\nProof.\n  refine (@cancelL_isequiv _ _ _ k f _ _).\n  refine (isequiv_homotopic _ p).\nDefined.\n\n(** Transporting is an equivalence. *)\nSection EquivTransport.\n\n  Context {A : Type} (P : A -> Type) (x y : A) (p : x = y).\n\n  Global Instance isequiv_transport : IsEquiv (transport P p) | 0\n    := BuildIsEquiv (P x) (P y) (transport P p) (transport P p^)\n    (transport_pV P p) (transport_Vp P p) (transport_pVp P p).\n\n  Definition equiv_transport : P x <~> P y\n    := BuildEquiv _ _ (transport P p) _.\n\nEnd EquivTransport.\n\n(** In all the above cases, we were able to directly construct all the structure of an equivalence.  However, as is evident, sometimes it is quite difficult to prove the adjoint law.\n\n   The following adjointification theorem allows us to be lazy about this if we wish.  It says that if we have all the data of an (adjoint) equivalence except the triangle identity, then we can always obtain the triangle identity by modifying the datum [equiv_is_section] (or [equiv_is_retraction]).  The proof is the same as the standard categorical argument that any equivalence can be improved to an adjoint equivalence.\n\n   As a stylistic matter, we try to avoid using adjointification in the library whenever possible, to preserve the homotopies specified by the user.  *)\n\nSection Adjointify.\n\n  Context {A B : Type} (f : A -> B) (g : B -> A).\n  Context (isretr : Sect g f) (issect : Sect f g).\n\n  (* This is the modified [eissect]. *)\n  Let issect' := fun x =>\n    ap g (ap f (issect x)^)  @  ap g (isretr (f x))  @  issect x.\n\n  Let is_adjoint' (a : A) : isretr (f a) = ap f (issect' a).\n  Proof.\n    unfold issect'.\n    apply moveR_M1.\n    repeat rewrite ap_pp, concat_p_pp; rewrite <- ap_compose.\n    rewrite (concat_pA1 (fun b => (isretr b)^) (ap f (issect a)^)).\n    repeat rewrite concat_pp_p; rewrite ap_V; apply moveL_Vp; rewrite concat_p1.\n    rewrite concat_p_pp, <- ap_compose.\n    rewrite (concat_pA1 (fun b => (isretr b)^) (isretr (f a))).\n    rewrite concat_pV, concat_1p; reflexivity.\n  Qed.\n\n  (** We don't make this a typeclass instance, because we want to control when we are applying it. *)\n  Definition isequiv_adjointify : IsEquiv f\n    := BuildIsEquiv A B f g isretr issect' is_adjoint'.\n\n  Definition equiv_adjointify : A <~> B\n    := BuildEquiv A B f isequiv_adjointify.\n\nEnd Adjointify.\n\nArguments isequiv_adjointify {A B}%type_scope (f g)%function_scope isretr issect.\nArguments equiv_adjointify {A B}%type_scope (f g)%function_scope isretr issect.\n\n(** An involution is an endomap that is its own inverse. *)\nDefinition isequiv_involution {X : Type} (f : X -> X) (isinvol : Sect f f)\n: IsEquiv f\n  := isequiv_adjointify f f isinvol isinvol.\n\nDefinition equiv_involution {X : Type} (f : X -> X) (isinvol : Sect f f)\n: X <~> X\n  := equiv_adjointify f f isinvol isinvol.\n\n(** Several lemmas useful for rewriting. *)\nDefinition moveR_equiv_M `{IsEquiv A B f} (x : A) (y : B) (p : x = f^-1 y)\n  : (f x = y)\n  := ap f p @ eisretr f y.\n\nDefinition moveL_equiv_M `{IsEquiv A B f} (x : A) (y : B) (p : f^-1 y = x)\n  : (y = f x)\n  := (eisretr f y)^ @ ap f p.\n\nDefinition moveR_equiv_V `{IsEquiv A B f} (x : B) (y : A) (p : x = f y)\n  : (f^-1 x = y)\n  := ap (f^-1) p @ eissect f y.\n\nDefinition moveL_equiv_V `{IsEquiv A B f} (x : B) (y : A) (p : f y = x)\n  : (y = f^-1 x)\n  := (eissect f y)^ @ ap (f^-1) p.\n\n(** Equivalence preserves contractibility (which of course is trivial under univalence). *)\nLemma contr_equiv A {B} (f : A -> B) `{IsEquiv A B f} `{Contr A}\n  : Contr B.\nProof.\n  exists (f (center A)).\n  intro y.\n  apply moveR_equiv_M.\n  apply contr.\nQed.\n\nDefinition contr_equiv' A {B} `(f : A <~> B) `{Contr A}\n  : Contr B\n  := contr_equiv A f.\n\n(** Any two contractible types are equivalent. *)\nGlobal Instance isequiv_contr_contr {A B : Type}\n       `{Contr A} `{Contr B} (f : A -> B)\n  : IsEquiv f\n  := BuildIsEquiv _ _ f (fun _ => (center A))\n                  (fun x => path_contr _ _)\n                  (fun x => path_contr _ _)\n                  (fun x => path_contr _ _).\n\nLemma equiv_contr_contr {A B : Type} `{Contr A} `{Contr B}\n  : (A <~> B).\nProof.\n  apply equiv_adjointify with (fun _ => center B) (fun _ => center A);\n  intros ?; apply contr.\nDefined.\n\n(** Assuming function extensionality, composing with an equivalence is itself an equivalence *)\n\nGlobal Instance isequiv_precompose `{Funext} {A B C : Type}\n  (f : A -> B) `{IsEquiv A B f}\n  : IsEquiv (fun (g:B->C) => g o f) | 1000\n  := isequiv_adjointify (fun (g:B->C) => g o f)\n    (fun h => h o f^-1)\n    (fun h => path_forall _ _ (fun x => ap h (eissect f x)))\n    (fun g => path_forall _ _ (fun y => ap g (eisretr f y))).\n\nDefinition equiv_precompose `{Funext} {A B C : Type}\n  (f : A -> B) `{IsEquiv A B f}\n  : (B -> C) <~> (A -> C)\n  := BuildEquiv _ _ (fun (g:B->C) => g o f) _.\n\nDefinition equiv_precompose' `{Funext} {A B C : Type} (f : A <~> B)\n  : (B -> C) <~> (A -> C)\n  := BuildEquiv _ _ (fun (g:B->C) => g o f) _.\n\nGlobal Instance isequiv_postcompose `{Funext} {A B C : Type}\n  (f : B -> C) `{IsEquiv B C f}\n  : IsEquiv (fun (g:A->B) => f o g) | 1000\n  := isequiv_adjointify (fun (g:A->B) => f o g)\n    (fun h => f^-1 o h)\n    (fun h => path_forall _ _ (fun x => eisretr f (h x)))\n    (fun g => path_forall _ _ (fun y => eissect f (g y))).\n\nDefinition equiv_postcompose `{Funext} {A B C : Type}\n  (f : B -> C) `{IsEquiv B C f}\n  : (A -> B) <~> (A -> C)\n  := BuildEquiv _ _ (fun (g:A->B) => f o g) _.\n\nDefinition equiv_postcompose' `{Funext} {A B C : Type} (f : B <~> C)\n  : (A -> B) <~> (A -> C)\n  := BuildEquiv _ _ (fun (g:A->B) => f o g) _.\n\n(** Conversely, if pre- or post-composing with a function is always an equivalence, then that function is also an equivalence.  It's convenient to know that we only need to assume the equivalence when the other type is the domain or the codomain. *)\n\nDefinition isequiv_isequiv_precompose {A B : Type} (f : A -> B)\n  (precomp := (fun (C : Type) (h : B -> C) => h o f))\n  (Aeq : IsEquiv (precomp A)) (Beq : IsEquiv (precomp B))\n  : IsEquiv f.\nProof.\n  assert (H : forall (C D : Type)\n                     (Ceq : IsEquiv (precomp C)) (Deq : IsEquiv (precomp D))\n                     (k : C -> D) (h : A -> C),\n                k o (precomp C)^-1 h = (precomp D)^-1 (k o h)).\n  { intros C D ? ? k h.\n    transitivity ((precomp D)^-1 (k o (precomp C ((precomp C)^-1 h)))).\n    - transitivity ((precomp D)^-1 (precomp D (k o ((precomp C)^-1 h)))).\n      + rewrite (eissect (precomp D) _); reflexivity.\n      + reflexivity.\n    - rewrite (eisretr (precomp C) h); reflexivity. }\n  refine (isequiv_adjointify f ((precomp A)^-1 idmap) _ _).\n  - intros x.\n    change ((f o (precomp A)^-1 idmap) x = idmap x).\n    apply ap10.\n    rewrite (H A B Aeq Beq).\n    change ((precomp B)^-1 (precomp B idmap) = idmap).\n    apply eissect.\n  - intros x.\n    change ((precomp A ((precomp A)^-1 idmap)) x = idmap x).\n    apply ap10, eisretr.\nQed.\n\n(*\nDefinition isequiv_isequiv_postcompose {A B : Type} (f : A -> B)\n  (postcomp := (fun (C : Type) (h : C -> A) => f o h))\n  (feq : forall C:Type, IsEquiv (postcomp C))\n  : IsEquiv f.\n(* TODO *)\n*)\n\n(** If [f] is an equivalence, then so is [ap f].  We are lazy and use [adjointify]. *)\nGlobal Instance isequiv_ap `{IsEquiv A B f} (x y : A)\n  : IsEquiv (@ap A B f x y) | 1000\n  := isequiv_adjointify (ap f)\n  (fun q => (eissect f x)^  @  ap f^-1 q  @  eissect f y)\n  (fun q =>\n    ap_pp f _ _\n    @ whiskerR (ap_pp f _ _) _\n    @ ((ap_V f _ @ inverse2 (eisadj f _)^)\n      @@ (ap_compose f^-1 f _)^\n      @@ (eisadj f _)^)\n    @ concat_pA1_p (eisretr f) _ _\n    @ whiskerR (concat_Vp _) _\n    @ concat_1p _)\n  (fun p =>\n    whiskerR (whiskerL _ (ap_compose f f^-1 _)^) _\n    @ concat_pA1_p (eissect f) _ _\n    @ whiskerR (concat_Vp _) _\n    @ concat_1p _).\n\n(** The function [equiv_ind] says that given an equivalence [f : A <~> B], and a hypothesis from [B], one may always assume that the hypothesis is in the image of [e].\n\nIn fibrational terms, if we have a fibration over [B] which has a section once pulled back along an equivalence [f : A <~> B], then it has a section over all of [B].  *)\n\nDefinition equiv_ind `{IsEquiv A B f} (P : B -> Type)\n  : (forall x:A, P (f x)) -> forall y:B, P y\n  := fun g y => transport P (eisretr f y) (g (f^-1 y)).\n\nArguments equiv_ind {A B} f {_} P _ _.\n\nDefinition equiv_ind_comp `{IsEquiv A B f} (P : B -> Type)\n  (df : forall x:A, P (f x)) (x : A)\n  : equiv_ind f P df (f x) = df x.\nProof.\n  unfold equiv_ind.\n  rewrite eisadj.\n  rewrite <- transport_compose.\n  exact (apD df (eissect f x)).\nDefined.\n\n(** Using [equiv_ind], we define a handy little tactic which introduces a variable and simultaneously substitutes it along an equivalence. *)\n\nLtac equiv_intro E x :=\n  match goal with\n    | |- forall y, @?Q y =>\n      refine (equiv_ind E Q _); intros x\n  end.\n\n(** [equiv_composeR'], a flipped version of [equiv_compose'], is (like [concatR]) most often useful partially applied, to give the “first half” of an equivalence one is constructing and leave the rest as a subgoal. One could similarly define [equiv_composeR] as a flip of [equiv_compose], but it doesn’t seem so useful since it doesn’t leave the remaining equivalence as a subgoal. *)\nDefinition equiv_composeR' {A B C} (f : A <~> B) (g : B <~> C)\n  := equiv_compose' g f.\n\n(* Shouldn't this become transitivity mid ? *)\nLtac equiv_via mid :=\n  apply @equiv_composeR' with (B := mid).\n\n(** It's often convenient when constructing a chain of equivalences to use [equiv_compose'], etc.  But when we treat an [Equiv] object constructed in that way as a function, via the coercion [equiv_fun], Coq sometimes needs a little help to realize that the result is the same as ordinary composition.  This tactic provides that help. *)\nLtac ev_equiv :=\n  repeat match goal with\n           | [ |- context[equiv_fun (equiv_compose' ?g ?f) ?a] ] =>\n             change ((equiv_compose' g f) a) with (g (f a))\n           | [ |- context[equiv_fun (equiv_compose ?g ?f) ?a] ] =>\n             change ((equiv_compose g f) a) with (g (f a))\n           | [ |- context[equiv_fun (equiv_inverse ?f) ?a] ] =>\n             change ((equiv_inverse f) a) with (f^-1 a)\n         end.\n\n\n(* Types/Paths.v *)\n\nDefinition transport_paths_l {A : Type} {x1 x2 y : A} (p : x1 = x2) (q : x1 = y)\n  : transport (fun x => x = y) p q = p^ @ q.\nProof.\n  destruct p, q; reflexivity.\nDefined.\n\nDefinition transport_paths_r {A : Type} {x y1 y2 : A} (p : y1 = y2) (q : x = y1)\n  : transport (fun y => x = y) p q = q @ p.\nProof.\n  destruct p, q; reflexivity.\nDefined.\n\nDefinition transport_paths_lr {A : Type} {x1 x2 : A} (p : x1 = x2) (q : x1 = x1)\n  : transport (fun x => x = x) p q = p^ @ q @ p.\nProof.\n  destruct p; simpl.\n  exact ((concat_1p q)^ @ (concat_p1 (1 @ q))^).\nDefined.\n\nDefinition transport_paths_Fl {A B : Type} {f : A -> B} {x1 x2 : A} {y : B}\n  (p : x1 = x2) (q : f x1 = y)\n  : transport (fun x => f x = y) p q = (ap f p)^ @ q.\nProof.\n  destruct p, q; reflexivity.\nDefined.\n\nDefinition transport_paths_Fr {A B : Type} {g : A -> B} {y1 y2 : A} {x : B}\n  (p : y1 = y2) (q : x = g y1)\n  : transport (fun y => x = g y) p q = q @ (ap g p).\nProof.\n  destruct p. symmetry; apply concat_p1.\nDefined.\n\nDefinition transport_paths_FlFr {A B : Type} {f g : A -> B} {x1 x2 : A}\n  (p : x1 = x2) (q : f x1 = g x1)\n  : transport (fun x => f x = g x) p q = (ap f p)^ @ q @ (ap g p).\nProof.\n  destruct p; simpl.\n  exact ((concat_1p q)^ @ (concat_p1 (1 @ q))^).\nDefined.\n\nDefinition transport_paths_FlFr_D {A : Type} {B : A -> Type}\n  {f g : forall a, B a} {x1 x2 : A} (p : x1 = x2) (q : f x1 = g x1)\n: transport (fun x => f x = g x) p q\n  = (apD f p)^ @ ap (transport B p) q @ (apD g p).\nProof.\n  destruct p; simpl.\n  exact ((ap_idmap _)^ @ (concat_1p _)^ @ (concat_p1 _)^).\nDefined.\n\nDefinition transport_paths_FFlr {A B : Type} {f : A -> B} {g : B -> A} {x1 x2 : A}\n  (p : x1 = x2) (q : g (f x1) = x1)\n  : transport (fun x => g (f x) = x) p q = (ap g (ap f p))^ @ q @ p.\nProof.\n  destruct p; simpl.\n  exact ((concat_1p q)^ @ (concat_p1 (1 @ q))^).\nDefined.\n\nDefinition transport_paths_lFFr {A B : Type} {f : A -> B} {g : B -> A} {x1 x2 : A}\n  (p : x1 = x2) (q : x1 = g (f x1))\n  : transport (fun x => x = g (f x)) p q = p^ @ q @ (ap g (ap f p)).\nProof.\n  destruct p; simpl.\n  exact ((concat_1p q)^ @ (concat_p1 (1 @ q))^).\nDefined.\n\nDefinition transport_paths2 {A : Type} {x y : A}\n           (p : x = y) (q : idpath x = idpath x)\n: transport (fun a => idpath a = idpath a) p q\n  =  (concat_Vp p)^\n    @ whiskerL p^ ((concat_1p p)^ @ whiskerR q p @ concat_1p p)\n    @ concat_Vp p.\nProof.\n  destruct p. simpl.\n  refine (_ @ (concat_p1 _)^).\n  refine (_ @ (concat_1p _)^).\n  assert (H : forall (p : x = x) (q : 1 = p),\n                (q @ (concat_p1 p)^) @ (concat_1p (p @ 1))^\n                = whiskerL (idpath x) (idpath 1 @ whiskerR q 1 @ idpath (p @ 1))).\n  { intros p' q'. destruct q'. reflexivity. }\n  transitivity (q @ (concat_p1 1)^ @ (concat_1p 1)^).\n  { simpl; exact ((concat_p1 _)^ @ (concat_p1 _)^). }\n  refine (H 1 q).\nDefined.\n\nDefinition equiv_ap `(f : A -> B) `{IsEquiv A B f} (x y : A)\n  : (x = y) <~> (f x = f y)\n  := BuildEquiv _ _ (ap f) _.\n\nGlobal Arguments equiv_ap (A B)%type_scope f%function_scope _ _ _.\n\nDefinition equiv_ap' `(f : A <~> B) (x y : A)\n  : (x = y) <~> (f x = f y)\n  := equiv_ap f x y.\n\n(* TODO: Is this really necessary? *)\nDefinition equiv_inj `(f : A -> B) `{IsEquiv A B f} {x y : A}\n  : (f x = f y) -> (x = y)\n  := (ap f)^-1.\n\n(** ** Path operations are equivalences *)\n\nGlobal Instance isequiv_path_inverse {A : Type} (x y : A)\n  : IsEquiv (@inverse A x y) | 0.\nProof.\n  refine (BuildIsEquiv _ _ _ (@inverse A y x)\n                       (@inv_V A y x) (@inv_V A x y) _).\n  intros p; destruct p; reflexivity.\nDefined.\n\nDefinition equiv_path_inverse {A : Type} (x y : A)\n  : (x = y) <~> (y = x)\n  := BuildEquiv _ _ (@inverse A x y) _.\n\nGlobal Instance isequiv_concat_l {A : Type} `(p : x = y:>A) (z : A)\n  : IsEquiv (@transitivity A _ _ x y z p) | 0.\nProof.\n  refine (BuildIsEquiv _ _ _ (concat p^)\n                       (concat_p_Vp p) (concat_V_pp p) _).\n  intros q; destruct p; destruct q; reflexivity.\nDefined.\n\nDefinition equiv_concat_l {A : Type} `(p : x = y) (z : A)\n  : (y = z) <~> (x = z)\n  := BuildEquiv _ _ (concat p) _.\n\nGlobal Instance isequiv_concat_r {A : Type} `(p : y = z) (x : A)\n  : IsEquiv (fun q:x=y => q @ p) | 0.\nProof.\n  refine (BuildIsEquiv _ _ (fun q => q @ p) (fun q => q @ p^)\n           (fun q => concat_pV_p q p) (fun q => concat_pp_V q p) _).\n  intros q; destruct p; destruct q; reflexivity.\nDefined.\n\nDefinition equiv_concat_r {A : Type} `(p : y = z) (x : A)\n  : (x = y) <~> (x = z)\n  := BuildEquiv _ _ (fun q => q @ p) _.\n\nGlobal Instance isequiv_concat_lr {A : Type} {x x' y y' : A} (p : x' = x) (q : y = y')\n  : IsEquiv (fun r:x=y => p @ r @ q) | 0\n  := @isequiv_compose _ _ (fun r => p @ r) _ _ (fun r => r @ q) _.\n\nDefinition equiv_concat_lr {A : Type} {x x' y y' : A} (p : x' = x) (q : y = y')\n  : (x = y) <~> (x' = y')\n  := BuildEquiv _ _ (fun r:x=y => p @ r @ q) _.\n\nGlobal Instance isequiv_whiskerL {A} {x y z : A} (p : x = y) {q r : y = z}\n: IsEquiv (@whiskerL A x y z p q r).\nProof.\n  simple refine (isequiv_adjointify _ _ _ _).\n  - apply cancelL.\n  - intros k. unfold cancelL.\n    rewrite !whiskerL_pp.\n    refine ((_ @@ 1 @@ _) @ whiskerL_pVL p k).\n    + destruct p, q; reflexivity.\n    + destruct p, r; reflexivity.\n  - intros k. unfold cancelL.\n    refine ((_ @@ 1 @@ _) @ whiskerL_VpL p k).\n    + destruct p, q; reflexivity.\n    + destruct p, r; reflexivity.\nDefined.\n\nDefinition equiv_whiskerL {A} {x y z : A} (p : x = y) (q r : y = z)\n: (q = r) <~> (p @ q = p @ r)\n  := BuildEquiv _ _ (whiskerL p) _.\n\nDefinition equiv_cancelL {A} {x y z : A} (p : x = y) (q r : y = z)\n: (p @ q = p @ r) <~> (q = r)\n  := equiv_inverse (equiv_whiskerL p q r).\n\nDefinition isequiv_cancelL {A} {x y z : A} (p : x = y) (q r : y = z)\n  : IsEquiv (cancelL p q r).\nProof.\n  change (IsEquiv (equiv_cancelL p q r)); exact _.\nDefined.\n\nGlobal Instance isequiv_whiskerR {A} {x y z : A} {p q : x = y} (r : y = z)\n: IsEquiv (fun h => @whiskerR A x y z p q h r).\nProof.\n  simple refine (isequiv_adjointify _ _ _ _).\n  - apply cancelR.\n  - intros k. unfold cancelR.\n    rewrite !whiskerR_pp.\n    refine ((_ @@ 1 @@ _) @ whiskerR_VpR k r).\n    + destruct p, r; reflexivity.\n    + destruct q, r; reflexivity.\n  - intros k. unfold cancelR.\n    refine ((_ @@ 1 @@ _) @ whiskerR_pVR k r).\n    + destruct p, r; reflexivity.\n    + destruct q, r; reflexivity.\nDefined.\n\nDefinition equiv_whiskerR {A} {x y z : A} (p q : x = y) (r : y = z)\n: (p = q) <~> (p @ r = q @ r)\n  := BuildEquiv _ _ (fun h => whiskerR h r) _.\n\nDefinition equiv_cancelR {A} {x y z : A} (p q : x = y) (r : y = z)\n: (p @ r = q @ r) <~> (p = q)\n  := equiv_inverse (equiv_whiskerR p q r).\n\nDefinition isequiv_cancelR {A} {x y z : A} (p q : x = y) (r : y = z)\n  : IsEquiv (cancelR p q r).\nProof.\n  change (IsEquiv (equiv_cancelR p q r)); exact _.\nDefined.\n\n(** We can use these to build up more complicated equivalences.\n\nIn particular, all of the [move] family are equivalences.\n\n(Note: currently, some but not all of these [isequiv_] lemmas have corresponding [equiv_] lemmas.  Also, they do *not* currently contain the computational content that e.g. the inverse of [moveR_Mp] is [moveL_Vp]; perhaps it would be useful if they did? *)\n\nGlobal Instance isequiv_moveR_Mp\n {A : Type} {x y z : A} (p : x = z) (q : y = z) (r : y = x)\n: IsEquiv (moveR_Mp p q r).\nProof.\n  destruct r.\n  apply (isequiv_compose' _ (isequiv_concat_l _ _) _ (isequiv_concat_r _ _)).\nDefined.\n\nDefinition equiv_moveR_Mp\n  {A : Type} {x y z : A} (p : x = z) (q : y = z) (r : y = x)\n: (p = r^ @ q) <~> (r @ p = q)\n:= BuildEquiv _ _ (moveR_Mp p q r) _.\n\nGlobal Instance isequiv_moveR_pM\n  {A : Type} {x y z : A} (p : x = z) (q : y = z) (r : y = x)\n: IsEquiv (moveR_pM p q r).\nProof.\n  destruct p.\n  apply (isequiv_compose' _ (isequiv_concat_l _ _) _ (isequiv_concat_r _ _)).\nDefined.\n\nDefinition equiv_moveR_pM\n  {A : Type} {x y z : A} (p : x = z) (q : y = z) (r : y = x)\n: (r = q @ p^) <~> (r @ p = q)\n:= BuildEquiv _ _ (moveR_pM p q r) _.\n\nGlobal Instance isequiv_moveR_Vp\n  {A : Type} {x y z : A} (p : x = z) (q : y = z) (r : x = y)\n: IsEquiv (moveR_Vp p q r).\nProof.\n  destruct r.\n  apply (isequiv_compose' _ (isequiv_concat_l _ _) _ (isequiv_concat_r _ _)).\nDefined.\n\nDefinition equiv_moveR_Vp\n  {A : Type} {x y z : A} (p : x = z) (q : y = z) (r : x = y)\n: (p = r @ q) <~> (r^ @ p = q)\n:= BuildEquiv _ _ (moveR_Vp p q r) _.\n\nGlobal Instance isequiv_moveR_pV\n  {A : Type} {x y z : A} (p : z = x) (q : y = z) (r : y = x)\n: IsEquiv (moveR_pV p q r).\nProof.\n  destruct p.\n  apply (isequiv_compose' _ (isequiv_concat_l _ _) _ (isequiv_concat_r _ _)).\nDefined.\n\nDefinition equiv_moveR_pV\n  {A : Type} {x y z : A} (p : z = x) (q : y = z) (r : y = x)\n: (r = q @ p) <~> (r @ p^ = q)\n:= BuildEquiv _ _ (moveR_pV p q r) _.\n\nGlobal Instance isequiv_moveL_Mp\n  {A : Type} {x y z : A} (p : x = z) (q : y = z) (r : y = x)\n: IsEquiv (moveL_Mp p q r).\nProof.\n  destruct r.\n  apply (isequiv_compose' _ (isequiv_concat_l _ _) _ (isequiv_concat_r _ _)).\nDefined.\n\nDefinition equiv_moveL_Mp\n  {A : Type} {x y z : A} (p : x = z) (q : y = z) (r : y = x)\n: (r^ @ q = p) <~> (q = r @ p)\n:= BuildEquiv _ _ (moveL_Mp p q r) _.\n\nDefinition isequiv_moveL_pM\n  {A : Type} {x y z : A} (p : x = z) (q : y = z) (r : y = x)\n: IsEquiv (moveL_pM p q r).\nProof.\n  destruct p.\n  apply (isequiv_compose' _ (isequiv_concat_l _ _) _ (isequiv_concat_r _ _)).\nDefined.\n\nDefinition equiv_moveL_pM\n  {A : Type} {x y z : A} (p : x = z) (q : y = z) (r : y = x) :\n  q @ p^ = r <~> q = r @ p\n  := BuildEquiv _ _ _ (isequiv_moveL_pM p q r).\n\nGlobal Instance isequiv_moveL_Vp\n  {A : Type} {x y z : A} (p : x = z) (q : y = z) (r : x = y)\n: IsEquiv (moveL_Vp p q r).\nProof.\n  destruct r.\n  apply (isequiv_compose' _ (isequiv_concat_l _ _) _ (isequiv_concat_r _ _)).\nDefined.\n\nDefinition equiv_moveL_Vp\n  {A : Type} {x y z : A} (p : x = z) (q : y = z) (r : x = y)\n: r @ q = p <~> q = r^ @ p\n:= BuildEquiv _ _ (moveL_Vp p q r) _.\n\nGlobal Instance isequiv_moveL_pV\n  {A : Type} {x y z : A} (p : z = x) (q : y = z) (r : y = x)\n: IsEquiv (moveL_pV p q r).\nProof.\n  destruct p.\n  apply (isequiv_compose' _ (isequiv_concat_l _ _) _ (isequiv_concat_r _ _)).\nDefined.\n\nDefinition equiv_moveL_pV\n  {A : Type} {x y z : A} (p : z = x) (q : y = z) (r : y = x)\n: q @ p = r <~> q = r @ p^\n:= BuildEquiv _ _ (moveL_pV p q r) _.\n\nDefinition isequiv_moveL_1M {A : Type} {x y : A} (p q : x = y)\n: IsEquiv (moveL_1M p q).\nProof.\n  destruct q. apply isequiv_concat_l.\nDefined.\n\nDefinition isequiv_moveL_M1 {A : Type} {x y : A} (p q : x = y)\n: IsEquiv (moveL_M1 p q).\nProof.\n  destruct q. apply isequiv_concat_l.\nDefined.\n\nDefinition isequiv_moveL_1V {A : Type} {x y : A} (p : x = y) (q : y = x)\n: IsEquiv (moveL_1V p q).\nProof.\n  destruct q. apply isequiv_concat_l.\nDefined.\n\nDefinition isequiv_moveL_V1 {A : Type} {x y : A} (p : x = y) (q : y = x)\n: IsEquiv (moveL_V1 p q).\nProof.\n  destruct q. apply isequiv_concat_l.\nDefined.\n\nDefinition isequiv_moveR_M1 {A : Type} {x y : A} (p q : x = y)\n: IsEquiv (moveR_M1 p q).\nProof.\n  destruct p. apply isequiv_concat_r.\nDefined.\n\nDefinition isequiv_moveR_1M {A : Type} {x y : A} (p q : x = y)\n: IsEquiv (moveR_1M p q).\nProof.\n  destruct p. apply isequiv_concat_r.\nDefined.\n\nDefinition isequiv_moveR_1V {A : Type} {x y : A} (p : x = y) (q : y = x)\n: IsEquiv (moveR_1V p q).\nProof.\n  destruct p. apply isequiv_concat_r.\nDefined.\n\nDefinition isequiv_moveR_V1 {A : Type} {x y : A} (p : x = y) (q : y = x)\n: IsEquiv (moveR_V1 p q).\nProof.\n  destruct p. apply isequiv_concat_r.\nDefined.\n\n\nDefinition moveR_moveL_transport_V {A : Type} (P : A -> Type) {x y : A}\n           (p : x = y) (u : P x) (v : P y) (q : transport P p u = v)\n  : moveR_transport_p P p u v (moveL_transport_V P p u v q) = q.\nProof.\n  destruct p; reflexivity.\nDefined.\n\nDefinition moveL_moveR_transport_p {A : Type} (P : A -> Type) {x y : A}\n           (p : x = y) (u : P x) (v : P y) (q : u = transport P p^ v)\n  : moveL_transport_V P p u v (moveR_transport_p P p u v q) = q.\nProof.\n  destruct p; reflexivity.\nDefined.\n\nGlobal Instance isequiv_moveR_transport_p {A : Type} (P : A -> Type) {x y : A}\n  (p : x = y) (u : P x) (v : P y)\n: IsEquiv (moveR_transport_p P p u v).\nProof.\n  unshelve eapply isequiv_adjointify.\n  apply moveL_transport_V.\n  intro q; apply moveR_moveL_transport_V.\n  intro q; apply moveL_moveR_transport_p.\nDefined.\n\nDefinition equiv_moveR_transport_p {A : Type} (P : A -> Type) {x y : A}\n  (p : x = y) (u : P x) (v : P y)\n: u = transport P p^ v <~> transport P p u = v\n:= BuildEquiv _ _ (moveR_transport_p P p u v) _.\n\n\nDefinition moveR_moveL_transport_p {A : Type} (P : A -> Type) {x y : A}\n           (p : y = x) (u : P x) (v : P y) (q : transport P p^ u = v)\n  : moveR_transport_V P p u v (moveL_transport_p P p u v q) = q.\nProof.\n  destruct p; reflexivity.\nDefined.\n\nDefinition moveL_moveR_transport_V {A : Type} (P : A -> Type) {x y : A}\n           (p : y = x) (u : P x) (v : P y) (q : u = transport P p v)\n  : moveL_transport_p P p u v (moveR_transport_V P p u v q) = q.\nProof.\n  destruct p; reflexivity.\nDefined.\n\nGlobal Instance isequiv_moveR_transport_V {A : Type} (P : A -> Type) {x y : A}\n  (p : y = x) (u : P x) (v : P y)\n: IsEquiv (moveR_transport_V P p u v).\nProof.\n  unshelve eapply isequiv_adjointify.\n  apply moveL_transport_p.\n  intro q; apply moveR_moveL_transport_p.\n  intro q; apply moveL_moveR_transport_V.\nDefined.\n\nDefinition equiv_moveR_transport_V {A : Type} (P : A -> Type) {x y : A}\n  (p : y = x) (u : P x) (v : P y)\n: u = transport P p v <~> transport P p^ u = v\n:= BuildEquiv _ _ (moveR_transport_V P p u v) _.\n\nGlobal Instance isequiv_moveL_transport_V {A : Type} (P : A -> Type) {x y : A}\n  (p : x = y) (u : P x) (v : P y)\n: IsEquiv (moveL_transport_V P p u v).\nProof.\n  unshelve eapply isequiv_adjointify.\n  apply moveR_transport_p.\n  intro q; apply moveL_moveR_transport_p.\n  intro q; apply moveR_moveL_transport_V.\nDefined.\n\nDefinition equiv_moveL_transport_V {A : Type} (P : A -> Type) {x y : A}\n  (p : x = y) (u : P x) (v : P y)\n: transport P p u = v <~> u = transport P p^ v\n:= BuildEquiv _ _ (moveL_transport_V P p u v) _.\n\nGlobal Instance isequiv_moveL_transport_p {A : Type} (P : A -> Type) {x y : A}\n  (p : y = x) (u : P x) (v : P y)\n: IsEquiv (moveL_transport_p P p u v).\nProof.\n  unshelve eapply isequiv_adjointify.\n  apply moveR_transport_V.\n  intro q; apply moveL_moveR_transport_V.\n  intro q; apply moveR_moveL_transport_p.\nDefined.\n\nDefinition equiv_moveL_transport_p {A : Type} (P : A -> Type) {x y : A}\n  (p : y = x) (u : P x) (v : P y)\n: transport P p^ u = v <~> u = transport P p v\n:= BuildEquiv _ _ (moveL_transport_p P p u v) _.\n\nGlobal Instance isequiv_moveR_equiv_M `{IsEquiv A B f} (x : A) (y : B)\n: IsEquiv (@moveR_equiv_M A B f _ x y).\nProof.\n  unfold moveR_equiv_M.\n  refine (@isequiv_compose _ _ (ap f) _ _ (fun q => q @ eisretr f y) _).\nDefined.\n\nDefinition equiv_moveR_equiv_M `{IsEquiv A B f} (x : A) (y : B)\n  : (x = f^-1 y) <~> (f x = y)\n  := BuildEquiv _ _ (@moveR_equiv_M A B f _ x y) _.\n\nGlobal Instance isequiv_moveR_equiv_V `{IsEquiv A B f} (x : B) (y : A)\n: IsEquiv (@moveR_equiv_V A B f _ x y).\nProof.\n  unfold moveR_equiv_V.\n  refine (@isequiv_compose _ _ (ap f^-1) _ _ (fun q => q @ eissect f y) _).\nDefined.\n\nDefinition equiv_moveR_equiv_V `{IsEquiv A B f} (x : B) (y : A)\n  : (x = f y) <~> (f^-1 x = y)\n  := BuildEquiv _ _ (@moveR_equiv_V A B f _ x y) _.\n\nGlobal Instance isequiv_moveL_equiv_M `{IsEquiv A B f} (x : A) (y : B)\n: IsEquiv (@moveL_equiv_M A B f _ x y).\nProof.\n  unfold moveL_equiv_M.\n  refine (@isequiv_compose _ _ (ap f) _ _ (fun q => (eisretr f y)^ @ q) _).\nDefined.\n\nDefinition equiv_moveL_equiv_M `{IsEquiv A B f} (x : A) (y : B)\n  : (f^-1 y = x) <~> (y = f x)\n  := BuildEquiv _ _ (@moveL_equiv_M A B f _ x y) _.\n\nGlobal Instance isequiv_moveL_equiv_V `{IsEquiv A B f} (x : B) (y : A)\n: IsEquiv (@moveL_equiv_V A B f _ x y).\nProof.\n  unfold moveL_equiv_V.\n  refine (@isequiv_compose _ _ (ap f^-1) _ _ (fun q => (eissect f y)^ @ q) _).\nDefined.\n\nDefinition equiv_moveL_equiv_V `{IsEquiv A B f} (x : B) (y : A)\n  : (f y = x) <~> (y = f^-1 x)\n  := BuildEquiv _ _ (@moveL_equiv_V A B f _ x y) _.\n\n(** *** Dependent paths *)\n\n(** Usually, a dependent path over [p:x1=x2] in [P:A->Type] between [y1:P x1] and [y2:P x2] is a path [transport P p y1 = y2] in [P x2].  However, when [P] is a path space, these dependent paths have a more convenient description: rather than transporting the left side both forwards and backwards, we transport both sides of the equation forwards, forming a sort of \"naturality square\".\n\n   We use the same naming scheme as for the transport lemmas. *)\n\nDefinition dpath_path_l {A : Type} {x1 x2 y : A}\n  (p : x1 = x2) (q : x1 = y) (r : x2 = y)\n  : q = p @ r\n  <~>\n  transport (fun x => x = y) p q = r.\nProof.\n  destruct p; simpl.\n  exact (equiv_concat_r (concat_1p r) q).\nDefined.\n\nDefinition dpath_path_r {A : Type} {x y1 y2 : A}\n  (p : y1 = y2) (q : x = y1) (r : x = y2)\n  : q @ p = r\n  <~>\n  transport (fun y => x = y) p q = r.\nProof.\n  destruct p; simpl.\n  exact (equiv_concat_l (concat_p1 q)^ r).\nDefined.\n\nDefinition dpath_path_lr {A : Type} {x1 x2 : A}\n  (p : x1 = x2) (q : x1 = x1) (r : x2 = x2)\n  : q @ p = p @ r\n  <~>\n  transport (fun x => x = x) p q = r.\nProof.\n  destruct p; simpl.\n  transitivity (q @ 1 = r).\n  exact (equiv_concat_r (concat_1p r) (q @ 1)).\n  exact (equiv_concat_l (concat_p1 q)^ r).\nDefined.\n\nDefinition dpath_path_Fl {A B : Type} {f : A -> B} {x1 x2 : A} {y : B}\n  (p : x1 = x2) (q : f x1 = y) (r : f x2 = y)\n  : q = ap f p @ r\n  <~>\n  transport (fun x => f x = y) p q = r.\nProof.\n  destruct p; simpl.\n  exact (equiv_concat_r (concat_1p r) q).\nDefined.\n\nDefinition dpath_path_Fr {A B : Type} {g : A -> B} {x : B} {y1 y2 : A}\n  (p : y1 = y2) (q : x = g y1) (r : x = g y2)\n  : q @ ap g p = r\n  <~>\n  transport (fun y => x = g y) p q = r.\nProof.\n  destruct p; simpl.\n  exact (equiv_concat_l (concat_p1 q)^ r).\nDefined.\n\nDefinition dpath_path_FlFr {A B : Type} {f g : A -> B} {x1 x2 : A}\n  (p : x1 = x2) (q : f x1 = g x1) (r : f x2 = g x2)\n  : q @ ap g p = ap f p @ r\n  <~>\n  transport (fun x => f x = g x) p q = r.\nProof.\n  destruct p; simpl.\n  transitivity (q @ 1 = r).\n  exact (equiv_concat_r (concat_1p r) (q @ 1)).\n  exact (equiv_concat_l (concat_p1 q)^ r).\nDefined.\n\nDefinition dpath_path_FFlr {A B : Type} {f : A -> B} {g : B -> A}\n  {x1 x2 : A} (p : x1 = x2) (q : g (f x1) = x1) (r : g (f x2) = x2)\n  : q @ p = ap g (ap f p) @ r\n  <~>\n  transport (fun x => g (f x) = x) p q = r.\nProof.\n  destruct p; simpl.\n  transitivity (q @ 1 = r).\n  exact (equiv_concat_r (concat_1p r) (q @ 1)).\n  exact (equiv_concat_l (concat_p1 q)^ r).\nDefined.\n\nDefinition dpath_path_lFFr {A B : Type} {f : A -> B} {g : B -> A}\n  {x1 x2 : A} (p : x1 = x2) (q : x1 = g (f x1)) (r : x2 = g (f x2))\n  : q @ ap g (ap f p) = p @ r\n  <~>\n  transport (fun x => x = g (f x)) p q = r.\nProof.\n  destruct p; simpl.\n  transitivity (q @ 1 = r).\n  exact (equiv_concat_r (concat_1p r) (q @ 1)).\n  exact (equiv_concat_l (concat_p1 q)^ r).\nDefined.\n\nDefinition dpath_paths2 {A : Type} {x y : A}\n           (p : x = y) (q : idpath x = idpath x)\n           (r : idpath y = idpath y)\n: (concat_1p p)^ @ whiskerR q p @ concat_1p p\n  = (concat_p1 p)^ @ whiskerL p r @ concat_p1 p\n  <~>\n  transport (fun a => idpath a = idpath a) p q = r.\nProof.\n  destruct p. simpl.\n  refine (_ oE (equiv_whiskerR _ _ 1)^-1).\n  refine (_ oE (equiv_whiskerL 1 _ _)^-1).\n  refine (equiv_concat_lr _ _).\n  - symmetry; apply whiskerR_p1_1.\n  - apply whiskerL_1p_1.\nDefined.\n\n(** ** Universal mapping property *)\n\nGlobal Instance isequiv_paths_ind `{Funext} {A : Type} (a : A)\n  (P : forall x, (a = x) -> Type)\n  : IsEquiv (paths_ind a P) | 0.\nProof.\n  refine (isequiv_adjointify (paths_ind a P) (fun f => f a 1) _ _).\n  - intros f.\n    apply path_forall; intros x.\n    apply path_forall; intros p.\n    destruct p; reflexivity.\n  - intros u. reflexivity.\nDefined.\n\nDefinition equiv_paths_ind `{Funext} {A : Type} (a : A)\n  (P : forall x, (a = x) -> Type)\n  : P a 1 <~> forall x p, P x p\n  := BuildEquiv _ _ (paths_ind a P) _.\n\n\n(* Types/Forall.v *)\n\nSection AssumeFunext.\nContext `{Funext}.\n\n(** ** Paths *)\n\n(** Paths [p : f = g] in a function type [forall x:X, P x] are equivalent to functions taking values in path types, [H : forall x:X, f x = g x], or concisely, [H : f == g].\n\nThis equivalence, however, is just the combination of [apD10] and function extensionality [funext], and as such, [path_forall], et seq. are given in the [Overture]:  *)\n\n(** Now we show how these things compute. *)\n\nDefinition apD10_path_forall `{P : A -> Type}\n  (f g : forall x, P x) (h : f == g)\n  : apD10 (path_forall _ _ h) == h\n  := apD10 (eisretr apD10 h).\n\nDefinition eta_path_forall `{P : A -> Type}\n  (f g : forall x, P x) (p : f = g)\n  : path_forall _ _ (apD10 p) = p\n  := eissect apD10 p.\n\nDefinition path_forall_1 `{P : A -> Type} (f : forall x, P x)\n  : (path_forall f f (fun x => 1)) = 1\n  := eta_path_forall f f 1.\n\n(** The identification of the path space of a dependent function space, up to equivalence, is of course just funext. *)\n\nDefinition equiv_apD10 `{Funext} {A : Type} (P : A -> Type) f g\n: (f = g) <~> (f == g)\n  := BuildEquiv _ _ (@apD10 A P f g) _.\n\nGlobal Instance isequiv_path_forall `{P : A -> Type} (f g : forall x, P x)\n  : IsEquiv (path_forall f g) | 0\n  := @isequiv_inverse _ _ (@apD10 A P f g) _.\n\nDefinition equiv_path_forall `{P : A -> Type} (f g : forall x, P x)\n  : (f == g)  <~>  (f = g)\n  := BuildEquiv _ _ (path_forall f g) _.\n\nGlobal Arguments equiv_path_forall {A%type_scope P} (f g)%function_scope.\n\n(** ** Path algebra *)\n\nDefinition path_forall_pp `{P : A -> Type} (f g h : forall x, P x)\n           (p : f == g) (q : g == h)\n: path_forall f h (fun x => p x @ q x) = path_forall f g p @ path_forall g h q.\nProof.\n  revert p q.\n  equiv_intro (@apD10 A P f g) p.\n  equiv_intro (@apD10 A P g h) q.\n  transitivity (path_forall f h (apD10 (p @ q))).\n  - apply ap, path_forall; intros x.\n    symmetry; apply apD10_pp.\n  - refine (eta_path_forall _ _ _ @ _).\n    apply concat2; symmetry; apply eta_path_forall.\nDefined.\n\n\nDefinition path_forall_V `{P : A -> Type} (f g : forall x, P x)\n           (p : f == g)\n  : path_forall _ _ (fun x => (p x)^) = (path_forall _ _ p)^.\nProof.\n  transitivity (path_forall _ _ (fun x => (apD10 (path_forall _ _ p) x)^)).\n  eapply ap. symmetry. apply (@ap _ _ (fun h x => (h x)^)). apply eisretr.\n transitivity (path_forall _ _ (apD10 (path_forall _ _ p)^)).\n  apply ap, inverse. apply path_forall; intros x. apply apD10_V.\n  apply eissect.\nDefined.\n\n(** ** Transport *)\n\n(** The concrete description of transport in sigmas and pis is rather trickier than in the other types. In particular, these cannot be described just in terms of transport in simpler types; they require the full Id-elim rule by way of \"dependent transport\" [transportD].\n\n  In particular this indicates why \"transport\" alone cannot be fully defined by induction on the structure of types, although Id-elim/transportD can be (cf. Observational Type Theory). A more thorough set of lemmas, along the lines of the present ones but dealing with Id-elim rather than just transport, might be nice to have eventually? *)\nDefinition transport_forall\n  {A : Type} {P : A -> Type} {C : forall x, P x -> Type}\n  {x1 x2 : A} (p : x1 = x2) (f : forall y : P x1, C x1 y)\n  : (transport (fun x => forall y : P x, C x y) p f)\n    == (fun y =>\n       transport (C x2) (transport_pV _ _ _) (transportD _ _ p _ (f (p^ # y)))).\n  now destruct p.\nDefined.\n\n(** A special case of [transport_forall] where the type [P] does not depend on [A],\n    and so it is just a fixed type [B]. *)\nDefinition transport_forall_constant\n  {A B : Type} {C : A -> B -> Type}\n  {x1 x2 : A} (p : x1 = x2) (f : forall y : B, C x1 y)\n  : (transport (fun x => forall y : B, C x y) p f)\n    == (fun y => transport (fun x => C x y) p (f y)).\n  now destruct p.\nDefined.\n\nDefinition apD_transport_forall_constant\n  {A B : Type} (C : A -> B -> Type)\n  {x1 x2 : A} (p : x1 = x2) (f : forall y : B, C x1 y)\n  {y1 y2 : B} (q : y1 = y2)\n: apD (transport (fun x => forall y : B, C x y) p f) q\n  = ap (transport (C x2) q) (transport_forall_constant p f y1)\n    @ transport_transport C p q (f y1)\n    @ ap (transport (fun x : A => C x y2) p) (apD f q)\n    @ (transport_forall_constant p f y2)^.\nProof.\n  destruct p, q; reflexivity.\nDefined.\n\n(** ** Maps on paths *)\n\n(** The action of maps given by application. *)\nDefinition ap_apply_lD {A} {B : A -> Type} {f g : forall x, B x} (p : f = g) (z : A)\n  : ap (fun f => f z) p = apD10 p z\n:= 1.\n\nDefinition ap_apply_lD2 {A} {B : A -> Type} { C : forall x, B x -> Type}\n           {f g : forall x y, C x y} (p : f = g) (z1 : A) (z2 : B z1)\n  : ap (fun f => f z1 z2) p = apD10 (apD10 p z1) z2.\nProof.\n  now destruct p.\nDefined.\n\n\n(** The action of maps given by lambda. *)\nDefinition ap_lambdaD {A B : Type} {C : B -> Type} {x y : A} (p : x = y) (M : forall a b, C b) :\n  ap (fun a b => M a b) p =\n  path_forall _ _ (fun b => ap (fun a => M a b) p).\nProof.\n  destruct p;\n  symmetry;\n  simpl; apply path_forall_1.\nDefined.\n\n(** ** Dependent paths *)\n\n(** Usually, a dependent path over [p:x1=x2] in [P:A->Type] between [y1:P x1] and [y2:P x2] is a path [transport P p y1 = y2] in [P x2].  However, when [P] is a function space, these dependent paths have a more convenient description: rather than transporting the argument of [y1] forwards and backwards, we transport only forwards but on both sides of the equation, yielding a \"naturality square\". *)\n\nDefinition dpath_forall\n  {A:Type} (B:A -> Type) (C:forall a, B a -> Type) (x1 x2:A) (p:x1=x2)\n  (f:forall y1:B x1, C x1 y1) (g:forall (y2:B x2), C x2 y2)\n  : (forall (y1:B x1), transportD B C p y1 (f y1) = g (transport B p y1))\n  <~>\n  (transport (fun x => forall y:B x, C x y) p f = g).\nProof.\n  destruct p.\n  apply equiv_path_forall.\nDefined.\n\nDefinition dpath_forall_constant\n  {A B:Type} (C : A -> B -> Type) (x1 x2:A) (p:x1=x2)\n  (f:forall (y1:B), C x1 y1) (g:forall (y2:B), C x2 y2)\n  : (forall (y1:B), transport (fun x => C x y1) p (f y1) = g y1)\n  <~>\n  (transport (fun x => forall y:B, C x y) p f = g).\nProof.\n  destruct p.\n  apply equiv_path_forall.\nDefined.\n\n(** ** Functorial action *)\n\n(** The functoriality of [forall] is slightly subtle: it is contravariant in the domain type and covariant in the codomain, but the codomain is dependent on the domain. *)\nDefinition functor_forall `{P : A -> Type} `{Q : B -> Type}\n    (f0 : B -> A) (f1 : forall b:B, P (f0 b) -> Q b)\n  : (forall a:A, P a) -> (forall b:B, Q b)\n  := (fun g b => f1 _ (g (f0 b))).\n\nDefinition ap_functor_forall `{P : A -> Type} `{Q : B -> Type}\n    (f0 : B -> A) (f1 : forall b:B, P (f0 b) -> Q b)\n    (g g' : forall a:A, P a) (h : g == g')\n  : ap (functor_forall f0 f1) (path_forall _ _ h)\n    = path_forall _ _ (fun b:B => (ap (f1 b) (h (f0 b)))).\nProof.\n  revert h.  equiv_intro (@apD10 A P g g') h.\n  destruct h.  simpl.\n  transitivity (idpath (functor_forall f0 f1 g)).\n  - exact (ap (ap (functor_forall f0 f1)) (path_forall_1 g)).\n  - symmetry.  apply path_forall_1.\nDefined.\n\nDefinition functor_forall_compose\n           `{P : A -> Type} `{Q : B -> Type} `{R : C -> Type}\n           (f0 : B -> A) (f1 : forall b:B, P (f0 b) -> Q b)\n           (g0 : C -> B) (g1 : forall c:C, Q (g0 c) -> R c)\n           (k : forall a, P a)\n  : functor_forall g0 g1 (functor_forall f0 f1 k) == functor_forall (f0 o g0) (fun c => g1 c o f1 (g0 c)) k\n  := fun a => 1.\n\n(** ** Equivalences *)\n\nGlobal Instance isequiv_functor_forall `{P : A -> Type} `{Q : B -> Type}\n  `{IsEquiv B A f} `{forall b, @IsEquiv (P (f b)) (Q b) (g b)}\n  : IsEquiv (functor_forall f g) | 1000.\nProof.\n  simple refine (isequiv_adjointify (functor_forall f g)\n    (functor_forall (f^-1)\n      (fun (x:A) (y:Q (f^-1 x)) => eisretr f x # (g (f^-1 x))^-1 y\n      )) _ _);\n  try assumption; (* https://coq.inria.fr/bugs/show_bug.cgi?id=3848 *)\n  intros h.\n  - abstract (\n        apply path_forall; intros b; unfold functor_forall;\n        rewrite eisadj;\n        rewrite <- transport_compose;\n        rewrite ap_transport;\n        rewrite eisretr;\n        apply apD\n      ).\n  - abstract (\n        apply path_forall; intros a; unfold functor_forall;\n        rewrite eissect;\n        apply apD\n      ).\nDefined.\n\nDefinition equiv_functor_forall `{P : A -> Type} `{Q : B -> Type}\n  (f : B -> A) `{IsEquiv B A f}\n  (g : forall b, P (f b) -> Q b)\n  `{forall b, @IsEquiv (P (f b)) (Q b) (g b)}\n  : (forall a, P a) <~> (forall b, Q b)\n  := BuildEquiv _ _ (functor_forall f g) _.\n\nDefinition equiv_functor_forall' `{P : A -> Type} `{Q : B -> Type}\n  (f : B <~> A) (g : forall b, P (f b) <~> Q b)\n  : (forall a, P a) <~> (forall b, Q b)\n  := equiv_functor_forall f g.\n\nDefinition equiv_functor_forall_id `{P : A -> Type} `{Q : A -> Type}\n  (g : forall a, P a <~> Q a)\n  : (forall a, P a) <~> (forall a, Q a)\n  := equiv_functor_forall (equiv_idmap A) g.\n\nDefinition equiv_functor_forall_pb {A B : Type} {P : A -> Type}\n  (f : B <~> A)\n  : (forall a, P a) <~> (forall b, P (f b))\n  := equiv_functor_forall' (Q := P o f) f (fun b => equiv_idmap).\n\nDefinition equiv_functor_forall_pf {A B : Type} {Q : B -> Type}\n  (f : B <~> A)\n  : (forall a, (Q (f^-1 a))) <~> (forall b, Q b).\nProof.\n  simple refine (equiv_functor_forall' (P := Q o f^-1) f _).\n  intros b; exact (equiv_transport Q _ _ (eissect f b)).\nDefined.\n\n(** There is another way to make forall functorial that acts on on equivalences only. *)\n\nDefinition equiv_functor_forall_covariant\n           `{P : A -> Type} `{Q : B -> Type}\n           (f : A <~> B) (g : forall a, P a <~> Q (f a))\n  : (forall a, P a) <~> (forall b, Q b).\nProof.\n  refine (equiv_adjointify\n           (fun (k:forall a, P a) b => eisretr f b # (g (f^-1 b) (k (f^-1 b))))\n           (fun h a => (g a)^-1 (h (f a)))\n           _ _).\n  - intros h; apply path_forall; intros b.\n    refine (_ @ apD h (eisretr f b)).\n    apply ap, eisretr.\n  - intros k; apply path_forall; intros a.\n    refine (_ @ apD k (eissect f a)).\n    apply moveR_equiv_V.\n    refine (_ @ (ap_transport (eissect f a) g (k (f^-1 (f a))))^).\n    refine (_ @ (transport_compose Q f (eissect f a) _)^).\n    refine (ap (fun p => transport Q p _) (eisadj f a)).\nDefined.\n\nDefinition equiv_functor_forall_covariant_compose\n           `{P : A -> Type} `{Q : B -> Type} `{R : C -> Type}\n           (f0 : A <~> B) (f1 : forall a, P a <~> Q (f0 a))\n           (g0 : B <~> C) (g1 : forall b, Q b <~> R (g0 b))\n           (h : forall a, P a) (c : C)\n  : equiv_functor_forall_covariant g0 g1 (equiv_functor_forall_covariant f0 f1 h) c\n    = equiv_functor_forall_covariant (g0 oE f0) (fun a => g1 (f0 a) oE f1 a) h c.\nProof.\n  cbn.\n  rewrite (ap_transport _ g1 _).\n  rewrite (transport_compose R g0 _ _).\n  symmetry; apply transport_pp.\nQed.\n\n(** ** Truncatedness: any dependent product of n-types is an n-type *)\n\nGlobal Instance contr_forall `{P : A -> Type} `{forall a, Contr (P a)}\n  : Contr (forall a, P a) | 100.\nProof.\n  exists (fun a => center (P a)).\n  intro f.  apply path_forall.  intro a.  apply contr.\nDefined.\n\n(* Global Instance trunc_forall `{P : A -> Type} `{forall a, IsTrunc n (P a)} *)\n(*   : IsTrunc n (forall a, P a) | 100. *)\n(* Proof. *)\n(*   generalize dependent P. *)\n(*   simple_induction n n IH; simpl; intros P ?. *)\n(*   (* case [n = -2], i.e. contractibility *) *)\n(*   - exact _. *)\n(*   (* case n = n'.+1 *) *)\n(*   - intros f g; apply (trunc_equiv _ (apD10 ^-1)). *)\n(* Defined. *)\n\n(** ** Contractibility: A product over a contractible type is equivalent to the fiber over the center. *)\n\nDefinition equiv_contr_forall `{Contr A} `(P : A -> Type)\n: (forall a, P a) <~> P (center A).\nProof.\n  simple refine (equiv_adjointify (fun (f:forall a, P a) => f (center A)) _ _ _).\n  - intros p a; exact (transport P (path_contr _ _) p).\n  - intros p.\n    refine (transport2 P (q := 1) _ p).\n    apply path_contr.\n  - intros f; apply path_forall; intros a.\n    apply apD.\nDefined.\n\n(** ** Symmetry of curried arguments *)\n\n(** Using the standard Haskell name for this, as it’s a handy utility function.\n\nNote: not sure if [P] will usually be deducible, or whether it would be better explicit. *)\nDefinition flip `{P : A -> B -> Type}\n  : (forall a b, P a b) -> (forall b a, P a b)\n  := fun f b a => f a b.\n\nGlobal Instance isequiv_flip `{P : A -> B -> Type}\n  : IsEquiv (@flip _ _ P) | 0.\nProof.\n  set (flip_P := @flip _ _ P).\n  set (flip_P_inv := @flip _ _ (flip P)).\n  set (flip_P_is_sect := (fun f => 1) : Sect flip_P flip_P_inv).\n  set (flip_P_is_retr := (fun g => 1) : Sect flip_P_inv flip_P).\n  exists flip_P_inv flip_P_is_retr flip_P_is_sect.\n  intro g.  exact 1.\nDefined.\n\nDefinition equiv_flip `(P : A -> B -> Type)\n  : (forall a b, P a b) <~> (forall b a, P a b)\n  := BuildEquiv _ _ (@flip _ _ P) _.\n\nEnd AssumeFunext.\n\n\n\n(* Types/Sigma.v *)\n\n\n(** In homotopy type theory, We think of elements of [Type] as spaces, homotopy types, or weak omega-groupoids. A type family [P : A -> Type] corresponds to a fibration whose base is [A] and whose fiber over [x] is [P x].\n\nFrom such a [P] we can build a total space over the base space [A] so that the fiber over [x : A] is [P x]. This is just Coq's dependent sum construction, written as [sigT P] or [{x : A & P x}]. The elements of [{x : A & P x}] are pairs, written [existT P x y] in Coq, where [x : A] and [y : P x].  In [Common.v] we defined the notation [(x;y)] to mean [existT _ x y].\n\nThe base and fiber components of a point in the total space are extracted with the two projections [pr1] and [pr2]. *)\n\n(** ** Unpacking *)\n\n(** Sometimes we would like to prove [Q u] where [u : {x : A & P x}] by writing [u] as a pair [(pr1 u ; pr2 u)]. This is accomplished by [sigT_unpack]. We want tight control over the proof, so we just write it down even though is looks a bit scary. *)\n\nDefinition unpack_sigma `{P : A -> Type} (Q : sigT P -> Type) (u : sigT P)\n: Q (u.1; u.2) -> Q u\n  := idmap.\n\nArguments unpack_sigma / .\n\n(** ** Eta conversion *)\n\nDefinition eta_sigma `{P : A -> Type} (u : sigT P)\n  : (u.1; u.2) = u\n  := 1.\n\nArguments eta_sigma / .\n\nDefinition eta2_sigma `{P : forall (a : A) (b : B a), Type}\n           (u : sigT (fun a => sigT (P a)))\n  : (u.1; (u.2.1; u.2.2)) = u\n  := 1.\n\nArguments eta2_sigma / .\n\nDefinition eta3_sigma `{P : forall (a : A) (b : B a) (c : C a b), Type}\n           (u : sigT (fun a => sigT (fun b => sigT (P a b))))\n  : (u.1; (u.2.1; (u.2.2.1; u.2.2.2))) = u\n  := 1.\n\nArguments eta3_sigma / .\n\n(** ** Paths *)\n\n(** A path in a total space is commonly shown component wise. Because we use this over and over, we write down the proofs by hand to make sure they are what we think they should be. *)\n\n(** With this version of the function, we often have to give [u] and [v] explicitly, so we make them explicit arguments. *)\nDefinition path_sigma_uncurried {A : Type} (P : A -> Type) (u v : sigT P)\n           (pq : {p : u.1 = v.1 & p # u.2 = v.2})\n: u = v.\n  destruct u, v, pq; cbn in *.\n  now destruct projT7, projT8.\nDefined.\n\n(** This is the curried one you usually want to use in practice.  We define it in terms of the uncurried one, since it's the uncurried one that is proven below to be an equivalence. *)\nDefinition path_sigma {A : Type} (P : A -> Type) (u v : sigT P)\n           (p : u.1 = v.1) (q : p # u.2 = v.2)\n: u = v\n  := path_sigma_uncurried P u v (p;q).\n\n(** A contravariant instance of [path_sigma_uncurried] *)\nDefinition path_sigma_uncurried_contra {A : Type} (P : A -> Type) (u v : sigT P)\n           (pq : {p : u.1 = v.1 & u.2 = p^ # v.2})\n: u = v\n  := (path_sigma_uncurried P v u (pq.1^;pq.2^))^.\n\n(** A variant of [Forall.dpath_forall] from which uses dependent sums to package things. It cannot go into [Forall] because [Sigma] depends on [Forall]. *)\n\nDefinition dpath_forall'\n           {A : Type } (P : A -> Type) (Q: sigT P -> Type) {x y : A} (h : x = y)\n           (f : forall p, Q (x ; p)) (g : forall p, Q (y ; p))\n:\n  (forall p, transport Q (path_sigma P (x ; p) (y; _) h 1) (f p) = g (h # p))\n    <~>\n    (forall p, transportD P (fun x => fun p => Q ( x ; p)) h p (f p) = g (transport P h p)).\nProof.\n  destruct h.\n  apply 1%equiv.\nDefined.\n\n\n(** This version produces only paths between pairs, as opposed to paths between arbitrary inhabitants of dependent sum types.  But it has the advantage that the components of those pairs can more often be inferred, so we make them implicit arguments. *)\nDefinition path_sigma' {A : Type} (P : A -> Type) {x x' : A} {y : P x} {y' : P x'}\n           (p : x = x') (q : p # y = y')\n: (x;y) = (x';y')\n  := path_sigma P (x;y) (x';y') p q.\n\n\n(** Projections of paths from a total space. *)\n\nDefinition pr1_path `{P : A -> Type} {u v : sigT P} (p : u = v)\n: u.1 = v.1\n  :=\n    ap pr1 p.\n(* match p with idpath => 1 end. *)\n\nNotation \"p ..1\" := (pr1_path p) (at level 3) : fibration_scope.\n\nDefinition pr2_path `{P : A -> Type} {u v : sigT P} (p : u = v)\n: p..1 # u.2 = v.2\n  := (transport_compose P pr1 p u.2)^\n     @ (@apD {x:A & P x} _ pr2 _ _ p).\n\nNotation \"p ..2\" := (pr2_path p) (at level 3) : fibration_scope.\n\n(** Now we show how these things compute. *)\n\nDefinition pr1_path_sigma_uncurried `{P : A -> Type} {u v : sigT P}\n           (pq : { p : u.1 = v.1 & p # u.2 = v.2 })\n: (path_sigma_uncurried _ _ _ pq)..1 = pq.1.\nProof.\n  destruct u as [u1 u2]; destruct v as [v1 v2]; simpl in *.\n  destruct pq as [p q].\n  destruct p; simpl in q; destruct q; reflexivity.\nDefined.\n\nDefinition pr2_path_sigma_uncurried `{P : A -> Type} {u v : sigT P}\n           (pq : { p : u.1 = v.1 & p # u.2 = v.2 })\n: (path_sigma_uncurried _ _ _ pq)..2\n  = ap (fun s => transport P s u.2) (pr1_path_sigma_uncurried pq) @ pq.2.\nProof.\n  destruct u as [u1 u2]; destruct v as [v1 v2]; simpl in *.\n  destruct pq as [p q].\n  destruct p; simpl in q; destruct q; reflexivity.\nDefined.\n\nDefinition eta_path_sigma_uncurried `{P : A -> Type} {u v : sigT P}\n           (p : u = v)\n: path_sigma_uncurried _ _ _ (p..1; p..2) = p.\nProof.\n  destruct p. reflexivity.\nDefined.\n\nLemma transport_pr1_path_sigma_uncurried\n      `{P : A -> Type} {u v : sigT P}\n      (pq : { p : u.1 = v.1 & transport P p u.2 = v.2 })\n      Q\n: transport (fun x => Q x.1) (@path_sigma_uncurried A P u v pq)\n  = transport _ pq.1.\nProof.\n  destruct pq as [p q], u, v; simpl in *.\n  destruct p, q; simpl in *.\n  reflexivity.\nDefined.\n\nDefinition pr1_path_sigma `{P : A -> Type} {u v : sigT P}\n           (p : u.1 = v.1) (q : p # u.2 = v.2)\n: (path_sigma _ _ _ p q)..1 = p\n  := pr1_path_sigma_uncurried (p; q).\n\n(* Writing it the other way can help [rewrite]. *)\nDefinition ap_pr1_path_sigma {A:Type} {P : A -> Type} {u v : sigT P}\n           (p : u.1 = v.1) (q : p # u.2 = v.2)\n  : ap pr1 (path_sigma _ _ _ p q) = p\n  := pr1_path_sigma p q.\n\nDefinition pr2_path_sigma `{P : A -> Type} {u v : sigT P}\n           (p : u.1 = v.1) (q : p # u.2 = v.2)\n: (path_sigma _ _ _ p q)..2\n  = ap (fun s => transport P s u.2) (pr1_path_sigma p q) @ q\n  := pr2_path_sigma_uncurried (p; q).\n\nDefinition eta_path_sigma `{P : A -> Type} {u v : sigT P} (p : u = v)\n: path_sigma _ _ _ (p..1) (p..2) = p\n  := eta_path_sigma_uncurried p.\n\nDefinition transport_pr1_path_sigma\n           `{P : A -> Type} {u v : sigT P}\n           (p : u.1 = v.1) (q : p # u.2 = v.2)\n           Q\n: transport (fun x => Q x.1) (@path_sigma A P u v p q)\n  = transport _ p\n  := transport_pr1_path_sigma_uncurried (p; q) Q.\n\n(** This lets us identify the path space of a sigma-type, up to equivalence. *)\n\nGlobal Instance isequiv_path_sigma `{P : A -> Type} {u v : sigT P}\n: IsEquiv (path_sigma_uncurried P u v) | 0.\nProof.\n  simple refine (BuildIsEquiv\n            _ _\n            _ (fun r => (r..1; r..2))\n            eta_path_sigma\n            _ _).\n  all: destruct u, v; intros [p q].\n  all: simpl in *.\n  all: destruct q, p; simpl in *.\n  all: reflexivity.\nDefined.\n\nDefinition equiv_path_sigma `(P : A -> Type) (u v : sigT P)\n: {p : u.1 = v.1 &  p # u.2 = v.2} <~> (u = v)\n  := BuildEquiv _ _ (path_sigma_uncurried P u v) _.\n\n(* A contravariant version of [isequiv_path_sigma'] *)\nInstance isequiv_path_sigma_contra `{P : A -> Type} {u v : sigT P}\n  : IsEquiv (path_sigma_uncurried_contra P u v) | 0.\n  unshelve eapply (isequiv_adjointify (path_sigma_uncurried_contra P u v)).\n  - intros []. exists 1. reflexivity.\n  - intro r; destruct r; destruct u as [u1 u2]; reflexivity.\n  - destruct u, v; intros [p q].\n    simpl in *.\n    destruct p; simpl in q.\n    destruct q; reflexivity.\nDefined.\n\n(* A contravariant version of [equiv_path_sigma] *)\nDefinition equiv_path_sigma_contra {A : Type} `(P : A -> Type) (u v : sigT P)\n  : {p : u.1 = v.1 & u.2 = p^ # v.2} <~> (u = v)\n  := BuildEquiv _ _ (path_sigma_uncurried_contra P u v) _.\n\n(** This identification respects path concatenation. *)\n\nDefinition path_sigma_pp_pp {A : Type} (P : A -> Type) {u v w : sigT P}\n           (p1 : u.1 = v.1) (q1 : p1 # u.2 = v.2)\n           (p2 : v.1 = w.1) (q2 : p2 # v.2 = w.2)\n: path_sigma P u w (p1 @ p2)\n             (transport_pp P p1 p2 u.2 @ ap (transport P p2) q1 @ q2)\n  = path_sigma P u v p1 q1 @ path_sigma P v w p2 q2.\nProof.\n  destruct u, v, w. simpl in *.\n  destruct p1, p2, q1, q2.\n  reflexivity.\nDefined.\n\nDefinition path_sigma_pp_pp' {A : Type} (P : A -> Type)\n           {u1 v1 w1 : A} {u2 : P u1} {v2 : P v1} {w2 : P w1}\n           (p1 : u1 = v1) (q1 : p1 # u2 = v2)\n           (p2 : v1 = w1) (q2 : p2 # v2 = w2)\n: path_sigma' P (p1 @ p2)\n              (transport_pp P p1 p2 u2 @ ap (transport P p2) q1 @ q2)\n  = path_sigma' P p1 q1 @ path_sigma' P p2 q2\n  := @path_sigma_pp_pp A P (u1;u2) (v1;v2) (w1;w2) p1 q1 p2 q2.\n\nDefinition path_sigma_p1_1p' {A : Type} (P : A -> Type)\n           {u1 v1 : A} {u2 : P u1} {v2 : P v1}\n           (p : u1 = v1) (q : p # u2 = v2)\n: path_sigma' P p q\n  = path_sigma' P p 1 @ path_sigma' P 1 q.\nProof.\n  destruct p, q.\n  reflexivity.\nDefined.\n\n(** [pr1_path] also commutes with the groupoid structure. *)\n\nDefinition pr1_path_1 {A : Type} {P : A -> Type} (u : sigT P)\n: (idpath u) ..1 = idpath (u .1)\n  := 1.\n\nDefinition pr1_path_pp {A : Type} {P : A -> Type} {u v w : sigT P}\n           (p : u = v) (q : v = w)\n: (p @ q) ..1 = (p ..1) @ (q ..1)\n  := ap_pp _ _ _.\n\nDefinition pr1_path_V {A : Type} {P : A -> Type} {u v : sigT P} (p : u = v)\n: p^ ..1 = (p ..1)^\n  := ap_V _ _.\n\n(** Applying [existT] to one argument is the same as [path_sigma] with reflexivity in the first place. *)\n\nDefinition ap_existT {A : Type} (P : A -> Type) (x : A) (y1 y2 : P x)\n           (q : y1 = y2)\n: ap (existT P x) q = path_sigma' P 1 q.\nProof.\n  destruct q; reflexivity.\nDefined.\n\n(** Dependent transport is the same as transport along a [path_sigma]. *)\n\nDefinition transportD_is_transport\n           {A:Type} (B:A->Type) (C:sigT B -> Type)\n           (x1 x2:A) (p:x1=x2) (y:B x1) (z:C (x1;y))\n: transportD B (fun a b => C (a;b)) p y z\n  = transport C (path_sigma' B p 1) z.\nProof.\n  destruct p. reflexivity.\nDefined.\n\n\n(** And we can simplify when the first equality is [1]. *)\nLemma ap_path_sigma_1p {A B : Type} {P : A -> Type} (F : forall a, P a -> B)\n      (a : A) {x y : P a} (p : x = y)\n  : ap (fun w => F w.1 w.2) (path_sigma' P 1 p) = ap (fun z => F a z) p.\nProof.\n  destruct p; reflexivity.\nDefined.\n\n\n\n(** A path between paths in a total space is commonly shown component wise. *)\n\n(** With this version of the function, we often have to give [u] and [v] explicitly, so we make them explicit arguments. *)\nDefinition path_path_sigma_uncurried {A : Type} (P : A -> Type) (u v : sigT P)\n           (p q : u = v)\n           (rs : {r : p..1 = q..1 & transport (fun x => transport P x u.2 = v.2) r p..2 = q..2})\n: p = q.\nProof.\n  destruct rs, p, u.\n  etransitivity; [ | apply eta_path_sigma ].\n  destruct projT4, projT3. reflexivity.\nDefined.\n\n(** This is the curried one you usually want to use in practice.  We define it in terms of the uncurried one, since it's the uncurried one that is proven below to be an equivalence. *)\nDefinition path_path_sigma {A : Type} (P : A -> Type) (u v : sigT P)\n           (p q : u = v)\n           (r : p..1 = q..1)\n           (s : transport (fun x => transport P x u.2 = v.2) r p..2 = q..2)\n: p = q\n  := path_path_sigma_uncurried P u v p q (r; s).\n\n(** ** Transport *)\n\n(** The concrete description of transport in sigmas (and also pis) is rather trickier than in the other types.  In particular, these cannot be described just in terms of transport in simpler types; they require also the dependent transport [transportD].\n\n  In particular, this indicates why \"transport\" alone cannot be fully defined by induction on the structure of types, although Id-elim/transportD can be (cf. Observational Type Theory).  A more thorough set of lemmas, along the lines of the present ones but dealing with Id-elim rather than just transport, might be nice to have eventually? *)\n\nDefinition transport_sigma {A : Type} {B : A -> Type} {C : forall a:A, B a -> Type}\n           {x1 x2 : A} (p : x1 = x2) (yz : { y : B x1 & C x1 y })\n: transport (fun x => { y : B x & C x y }) p yz\n  = (p # yz.1 ; transportD _ _ p yz.1 yz.2).\nProof.\n  destruct p.  destruct yz as [y z]. reflexivity.\nDefined.\n\n(** The special case when the second variable doesn't depend on the first is simpler. *)\nDefinition transport_sigma' {A B : Type} {C : A -> B -> Type}\n           {x1 x2 : A} (p : x1 = x2) (yz : { y : B & C x1 y })\n: transport (fun x => { y : B & C x y }) p yz =\n  (yz.1 ; transport (fun x => C x yz.1) p yz.2).\nProof.\n  destruct p. destruct yz. reflexivity.\nDefined.\n\n(** Or if the second variable contains a first component that doesn't depend on the first.  Need to think about the naming of these. *)\n\nDefinition transport_sigma_' {A : Type} {B C : A -> Type}\n           {D : forall a:A, B a -> C a -> Type}\n           {x1 x2 : A} (p : x1 = x2)\n           (yzw : { y : B x1 & { z : C x1 & D x1 y z } })\n: transport (fun x => { y : B x & { z : C x & D x y z } }) p yzw\n  = (p # yzw.1 ; (p # yzw.2.1 ; transportD2 _ _ _ p yzw.1 yzw.2.1 yzw.2.2)).\nProof.\n  destruct p. reflexivity.\nDefined.\n\n(** ** Functorial action *)\n\nDefinition functor_sigma `{P : A -> Type} `{Q : B -> Type}\n           (f : A -> B) (g : forall a, P a -> Q (f a))\n: sigT P -> sigT Q\n  := fun u => (f u.1 ; g u.1 u.2).\n\nDefinition ap_functor_sigma `{P : A -> Type} `{Q : B -> Type}\n           (f : A -> B) (g : forall a, P a -> Q (f a))\n           (u v : sigT P) (p : u.1 = v.1) (q : p # u.2 = v.2)\n: ap (functor_sigma f g) (path_sigma P u v p q)\n  = path_sigma Q (functor_sigma f g u) (functor_sigma f g v)\n               (ap f p)\n               ((transport_compose Q f p (g u.1 u.2))^\n                @ (@ap_transport _ P (fun x => Q (f x)) _ _ p g u.2)^\n                @ ap (g v.1) q).\nProof.\n  destruct u as [u1 u2]; destruct v as [v1 v2]; simpl in p, q.\n  destruct p; simpl in q.\n  destruct q.\n  reflexivity.\nDefined.\n\n(** ** Equivalences *)\n\nGlobal Instance isequiv_functor_sigma `{P : A -> Type} `{Q : B -> Type}\n         `{IsEquiv A B f} `{forall a, @IsEquiv (P a) (Q (f a)) (g a)}\n: IsEquiv (functor_sigma f g) | 1000.\nProof.\n  refine (isequiv_adjointify (functor_sigma f g)\n                             (functor_sigma (f^-1)\n                                            (fun x y => ((g (f^-1 x))^-1 ((eisretr f x)^ # y)))) _ _);\n  intros [x y].\n  - refine (path_sigma' _ (eisretr f x) _); simpl.\n    abstract (\n        rewrite (eisretr (g (f^-1 x)));\n        apply transport_pV\n      ).\n  - refine (path_sigma' _ (eissect f x) _); simpl.\n    refine ((ap_transport (eissect f x) (fun x' => (g x') ^-1)\n                          (transport Q (eisretr f (f x)) ^ (g x y)))^ @ _).\n    abstract (\n        rewrite transport_compose, eisadj, transport_pV;\n        apply eissect\n      ).\nDefined.\n\nDefinition equiv_functor_sigma `{P : A -> Type} `{Q : B -> Type}\n           (f : A -> B) `{IsEquiv A B f}\n           (g : forall a, P a -> Q (f a))\n           `{forall a, @IsEquiv (P a) (Q (f a)) (g a)}\n: sigT P <~> sigT Q\n  := BuildEquiv _ _ (functor_sigma f g) _.\n\nDefinition equiv_functor_sigma' `{P : A -> Type} `{Q : B -> Type}\n           (f : A <~> B)\n           (g : forall a, P a <~> Q (f a))\n: sigT P <~> sigT Q\n  := equiv_functor_sigma f g.\n\nDefinition equiv_functor_sigma_id `{P : A -> Type} `{Q : A -> Type}\n           (g : forall a, P a <~> Q a)\n: sigT P <~> sigT Q\n  := equiv_functor_sigma' 1 g.\n\n(** Lemma 3.11.9(i): Summing up a contractible family of types does nothing. *)\n\nGlobal Instance isequiv_pr1_contr {A} {P : A -> Type}\n         `{forall a, Contr (P a)}\n: IsEquiv (@pr1 A P) | 100.\nProof.\n  refine (isequiv_adjointify (@pr1 A P)\n                             (fun a => (a ; center (P a))) _ _).\n  - intros a; reflexivity.\n  - intros [a p].\n    refine (path_sigma' P 1 (contr _)).\nDefined.\n\nDefinition equiv_sigma_contr {A : Type} (P : A -> Type)\n           `{forall a, Contr (P a)}\n: sigT P <~> A\n  := BuildEquiv _ _ pr1 _.\n\n(** Lemma 3.11.9(ii): Dually, summing up over a contractible type does nothing. *)\n\nDefinition equiv_contr_sigma {A : Type} (P : A -> Type) `{Contr A}\n: { x : A & P x } <~> P (center A).\nProof.\n  refine (equiv_adjointify (fun xp => (contr xp.1)^ # xp.2)\n                           (fun p => (center A ; p)) _ _).\n  - intros p; simpl.\n    exact (ap (fun q => q # p) (path_contr _ 1)).\n  - intros [a p].\n    refine (path_sigma' _ (contr a) _).\n    apply transport_pV.\nDefined.\n\n(** ** Associativity *)\n\nDefinition equiv_sigma_assoc `(P : A -> Type) (Q : {a : A & P a} -> Type)\n: {a : A & {p : P a & Q (a;p)}} <~> sigT Q\n  := @BuildEquiv\n       _ _ _\n       (@BuildIsEquiv\n          {a : A & {p : P a & Q (a;p)}} (sigT Q)\n          (fun apq => ((apq.1; apq.2.1); apq.2.2))\n          (fun apq => (apq.1.1; (apq.1.2; apq.2)))\n          (fun _ => 1)\n          (fun _ => 1)\n          (fun _ => 1)).\n", "meta": {"author": "CoqHott", "repo": "sProp", "sha": "2c58441e8188bf9d22d7865081c86710ffb62826", "save_path": "github-repos/coq/CoqHott-sProp", "path": "github-repos/coq/CoqHott-sProp/sProp-2c58441e8188bf9d22d7865081c86710ffb62826/MiniHoTT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.25192233240103734}}
{"text": "Require Import FP.Classes.\nRequire Import FP.CoreData.\nRequire Import FP.CoreClasses.\nRequire Import FP.Data.Identity.\nRequire Import FP.Data.Cont.\nRequire Import FP.Data.Susp.\nRequire Import FP.Data.Option.\nRequire Import FP.Data.Peano.\nRequire Import FP.Data.N.\nRequire Import FP.Data.State.\n\nImport CoreDataNotation.\nImport CoreClassesNotation.\nImport ClassesNotation.\nImport SuspNotation.\n\nSection Foldable.\n  Context {X T} `{! Foldable X T }.\n\n  Definition fold {A} (f:X -> A -> A) (a:A) : T -> A :=\n    cofold (fun (x:X) (aM:identity A) => f x $ run_identity aM) (Identity a).\n  Definition mfold {m A} `{! Monad m } (f:X -> A -> m A) (a:A) : T -> m A :=\n    fold (fun (x:X) (aM:m A) => a <- aM ;; f x a) (mret a).\n  Definition revfold {A} (f:X -> A -> A) : A -> T -> A :=\n    run_cont '.:' \n      mfold begin fun (x:X) (a:A) =>\n        callcc $ fun (k:A -> cont A A) =>\n          a <- k a ;;\n          mret $ f x a\n      end.\n  Definition lazyfold {A} (f:forall {C}, X -> (C -> A) -> C -> A) (a:A) : T -> A :=\n    cofold (fun (x:X) (aW:susp A) => f x force aW) (delay | a).\nEnd Foldable.\n\nSection Fix.\n  Context {T} {F:Foldable T T}.\n\n  Definition fold_fix {A B}\n      (ff:(T -> A -> option B) -> T -> A -> option B) (t:T) (a:A) : option B :=\n    lazyfold begin fun (C:Type) (t:T) (k:C->T->A->option B) (l:C) =>\n      ff $ fun _ (a:A) => k l t a\n    end (const2 None) t t a.\n\n  Definition fold_mfix {m A B} `{! Monad m }\n      (ff:(T -> A -> m (option B)) -> T -> A -> m (option B)) (t:T) (a:A) : m (option B) :=\n    lazyfold begin fun (C:Type) (t:T) (k:C->T->A->m (option B)) (l:C) =>\n      ff $ fun _ (a:A) => k l t a\n    end (const2 $ mret None) t t a.\nEnd Fix.\n\nSection Iterable.\n  Context {X T} `{! Iterable X T }.\n\n  Definition iter {A} (f:A -> X -> A) (a:A) : T -> A :=\n    coiter (fun (aM:identity A) (x:X) => f (run_identity aM) x) (Identity a).\n  Definition miter {m A} `{! Monad m } (f:A -> X -> m A) (a:A) : T -> m A :=\n    iter (fun (aM:m A) (x:X) => a <- aM ;; f a x) (mret a).\n  Definition reviter {A} (f:A -> X -> A) : A -> T -> A :=\n    run_cont '.:'\n      miter begin fun (a:A) (x:X) =>\n        callcc $ fun (k:A -> cont A A) =>\n          a <- k a ;;\n          mret $ f a x\n      end.\n  Definition lazyiter {A} (f:forall {C}, (C -> A) -> X -> C -> A) (a:A) : T -> A :=\n    coiter (fun (aW:susp A) (x:X) => f force x aW) (delay | a).\nEnd Iterable.\n\nSection Buildable.\n  Context {X T} `{! Buildable X T }.\n\n  Definition build (f:forall A, (X -> A -> A) -> A -> A) : T :=\n    run_identity $ mbuild $\n      fun A (f':X -> A -> A) (a:A) =>\n        mret $ f A begin fun (x:X) (a:A) =>\n          f' x a\n        end a.\nEnd Buildable.\n\nSection GeneralizedList.\n  Definition map {T A U B} `{! Foldable A T ,! Buildable B U }\n      (f:A -> B) (t:T) : U :=\n    build $ fun C (cons:B -> C -> C) (nil:C) =>\n      fold (fun (a:A) (c:C) => cons (f a) c) nil t.\n\n  Definition foreach {T A U B} `{! Foldable A T ,! Buildable B U }\n      : T -> (A -> B) -> U := flip map.\n\n  Definition filter {T A U} `{! Foldable A T ,! Buildable A U }\n      (f:A -> bool) (t:T) : U :=\n    build $ fun C (cons:A -> C -> C) (nil:C) =>\n      fold (fun (a:A) (c:C) => if f a then cons a c else c) nil t.\n\n  Definition select {T A} `{! Foldable A T } (p:A -> bool) : T -> option A :=\n    lazyfold begin fun C (a:A) (k:C -> option A) (l:C) =>\n      if p a then Some a else k l\n    end None.\n\n  Definition lookup {T A B} `{! EqvDec A ,! Foldable (A*B) T } (a:A)\n      : T -> option B :=\n    mbind_fmap snd '.' select (fun (p:A*B) => fst p ~=! a).\n  \n  Definition cat_options {T A U} `{! Foldable (option A) T ,! Buildable A U }\n      (t:T) : U :=\n    build $ fun C (cons:A -> C -> C) (nil:C) =>\n      fold (fun (aM:option A) (c:C) => option_elim aM id cons c) nil t.\n\n  Definition numbered {T A U} `{! Foldable A T ,! Buildable (N*A) U }\n      (t:T) : U :=\n    eval_state 0 $ mbuild $ fun C (cons:N*A -> C -> C) (nil:C) =>\n      mfold begin fun (a:A) (c:C) =>\n        n <- pinc ;;\n        mret $ cons (n,a) c\n      end nil t.\n\n  Definition intersperse {T A U} `{! Foldable A T ,! Buildable A U }\n      (i:A) (t:T) : U :=\n    eval_state false $ mbuild $ fun C (cons:A -> C -> C) (nil:C) =>\n      mfold begin fun (a:A) (c:C) =>\n        b <- mget ;;\n        mput true ;;\n        mret $ if b:bool then\n          cons a (cons i c)\n        else\n          cons a c \n      end nil t.\n\n  Definition replicate {T A} `{! Buildable A T } (n:N) (a:A) : T :=\n    build $ fun C (cons:A -> C -> C) (nil:C) =>\n      loopr (cons a) nil n.\n\n  Definition length {T A P} `{! Foldable A T ,! Peano P } (t:T) : P :=\n    exec_state pzero $\n      mfold begin fun (_:A) (_:unit) =>\n        pinc ;; mret tt\n      end tt t.\nEnd GeneralizedList.", "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/Foldable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.25186084168671835}}
{"text": "From iris.algebra Require Export cmra.\nFrom iris.algebra Require Import updates local_updates.\nFrom stdpp Require Export collections coPset.\nSet Default Proof Using \"Type\".\n(** This is pretty much the same as algebra/gset, but I was not able to\ngeneralize the construction without breaking canonical structures. *)\n\n(* The union CMRA *)\nSection coPset.\n  Implicit Types X Y : coPset.\n\n  Canonical Structure coPsetC := discreteC coPset.\n\n  Instance coPset_valid : Valid coPset := λ _, True.\n  Instance coPset_unit : Unit coPset := (∅ : coPset).\n  Instance coPset_op : Op coPset := union.\n  Instance coPset_pcore : PCore coPset := Some.\n\n  Lemma coPset_op_union X Y : X ⋅ Y = X ∪ Y.\n  Proof. done. Qed.\n  Lemma coPset_core_self X : core X = X.\n  Proof. done. Qed.\n  Lemma coPset_included X Y : X ≼ Y ↔ X ⊆ Y.\n  Proof.\n    split.\n    - intros [Z ->]. rewrite coPset_op_union. set_solver.\n    - intros (Z&->&?)%subseteq_disjoint_union_L. by exists Z.\n  Qed.\n\n  Lemma coPset_ra_mixin : RAMixin coPset.\n  Proof.\n    apply ra_total_mixin; eauto.\n    - solve_proper.\n    - solve_proper.\n    - solve_proper.\n    - intros X1 X2 X3. by rewrite !coPset_op_union assoc_L.\n    - intros X1 X2. by rewrite !coPset_op_union comm_L.\n    - intros X. by rewrite coPset_core_self idemp_L.\n  Qed.\n  Canonical Structure coPsetR := discreteR coPset coPset_ra_mixin.\n\n  Global Instance coPset_cmra_discrete : CmraDiscrete coPsetR.\n  Proof. apply discrete_cmra_discrete. Qed.\n\n  Lemma coPset_ucmra_mixin : UcmraMixin coPset.\n  Proof. split. done. intros X. by rewrite coPset_op_union left_id_L. done. Qed.\n  Canonical Structure coPsetUR := UcmraT coPset coPset_ucmra_mixin.\n\n  Lemma coPset_opM X mY : X ⋅? mY = X ∪ from_option id ∅ mY.\n  Proof. destruct mY; by rewrite /= ?right_id_L. Qed.\n\n  Lemma coPset_update X Y : X ~~> Y.\n  Proof. done. Qed.\n\n  Lemma coPset_local_update X Y X' : X ⊆ X' → (X,Y) ~l~> (X',X').\n  Proof.\n    intros (Z&->&?)%subseteq_disjoint_union_L.\n    rewrite local_update_unital_discrete=> Z' _ /leibniz_equiv_iff->.\n    split. done. rewrite coPset_op_union. set_solver.\n  Qed.\nEnd coPset.\n\n(* The disjoiny union CMRA *)\nInductive coPset_disj :=\n  | CoPset : coPset → coPset_disj\n  | CoPsetBot : coPset_disj.\n\nSection coPset_disj.\n  Arguments op _ _ !_ !_ /.\n  Canonical Structure coPset_disjC := leibnizC coPset_disj.\n\n  Instance coPset_disj_valid : Valid coPset_disj := λ X,\n    match X with CoPset _ => True | CoPsetBot => False end.\n  Instance coPset_disj_unit : Unit coPset_disj := CoPset ∅.\n  Instance coPset_disj_op : Op coPset_disj := λ X Y,\n    match X, Y with\n    | CoPset X, CoPset Y => if decide (X ## Y) then CoPset (X ∪ Y) else CoPsetBot\n    | _, _ => CoPsetBot\n    end.\n  Instance coPset_disj_pcore : PCore coPset_disj := λ _, Some ε.\n\n  Ltac coPset_disj_solve :=\n    repeat (simpl || case_decide);\n    first [apply (f_equal CoPset)|done|exfalso]; set_solver by eauto.\n\n  Lemma coPset_disj_included X Y : CoPset X ≼ CoPset Y ↔ X ⊆ Y.\n  Proof.\n    split.\n    - move=> [[Z|]]; simpl; try case_decide; set_solver.\n    - intros (Z&->&?)%subseteq_disjoint_union_L.\n      exists (CoPset Z). coPset_disj_solve.\n  Qed.\n  Lemma coPset_disj_valid_inv_l X Y :\n    ✓ (CoPset X ⋅ Y) → ∃ Y', Y = CoPset Y' ∧ X ## Y'.\n  Proof. destruct Y; repeat (simpl || case_decide); by eauto. Qed.\n  Lemma coPset_disj_union X Y : X ## Y → CoPset X ⋅ CoPset Y = CoPset (X ∪ Y).\n  Proof. intros. by rewrite /= decide_True. Qed.\n  Lemma coPset_disj_valid_op X Y : ✓ (CoPset X ⋅ CoPset Y) ↔ X ## Y.\n  Proof. simpl. case_decide; by split. Qed.\n\n  Lemma coPset_disj_ra_mixin : RAMixin coPset_disj.\n  Proof.\n    apply ra_total_mixin; eauto.\n    - intros [?|]; destruct 1; coPset_disj_solve.\n    - by constructor.\n    - by destruct 1.\n    - intros [X1|] [X2|] [X3|]; coPset_disj_solve.\n    - intros [X1|] [X2|]; coPset_disj_solve.\n    - intros [X|]; coPset_disj_solve.\n    - exists (CoPset ∅); coPset_disj_solve.\n    - intros [X1|] [X2|]; coPset_disj_solve.\n  Qed.\n  Canonical Structure coPset_disjR := discreteR coPset_disj coPset_disj_ra_mixin.\n\n  Global Instance coPset_disj_cmra_discrete : CmraDiscrete coPset_disjR.\n  Proof. apply discrete_cmra_discrete. Qed.\n\n  Lemma coPset_disj_ucmra_mixin : UcmraMixin coPset_disj.\n  Proof. split; try apply _ || done. intros [X|]; coPset_disj_solve. Qed.\n  Canonical Structure coPset_disjUR := UcmraT coPset_disj coPset_disj_ucmra_mixin.\nEnd coPset_disj.\n", "meta": {"author": "jtassarotti", "repo": "polaris", "sha": "c7873f05214351d54cacf3d8482625ee33ad3288", "save_path": "github-repos/coq/jtassarotti-polaris", "path": "github-repos/coq/jtassarotti-polaris/polaris-c7873f05214351d54cacf3d8482625ee33ad3288/theories/algebra/coPset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2517686431313862}}
{"text": "From Coq Require Import Extraction.\nFrom Coq Require Import ZArith.\n\nExtract Inductive nat => \"u64\" [\"0\" \"__nat_succ\"] \"__nat_elim!\".\nExtract Inductive positive => \"u64\" [\"__pos_onebit\" \"__pos_zerobit\" \"1\"] \"__pos_elim!\".\nExtract Inductive N => \"u64\" [\"0\" \"__N_frompos\"] \"__N_elim!\".\nExtract Inductive Z => \"i64\" [\"0\" \"__Z_frompos\" \"__Z_fromneg\"] \"__Z_elim!\".\nExtract Inductive comparison =>\n  \"std::cmp::Ordering\"\n    [\"std::cmp::Ordering::Equal\"\n     \"std::cmp::Ordering::Less\"\n     \"std::cmp::Ordering::Greater\"].\n\nExtract Constant BinPosDef.Pos.add => \"fn ##name##(&'a self, a: u64, b: u64) -> u64 { a + b }\".\nExtract Constant BinPosDef.Pos.succ => \"fn ##name##(&'a self, a: u64) -> u64 { a + 1 }\".\nExtract Constant BinPosDef.Pos.pred => \"fn ##name##(&'a self, a: u64) -> u64 { a - 1 }\".\nExtract Constant BinPosDef.Pos.sub => \"fn ##name##(&'a self, a: u64, b: u64) -> u64 { a - b }\".\nExtract Constant BinPosDef.Pos.mul => \"fn ##name##(&'a self, a: u64, b: u64) -> u64 { a * b }\".\nExtract Constant BinPosDef.Pos.min => \"fn ##name##(&'a self, a: u64, b: u64) -> u64 { std::cmp::min(a, b) }\".\nExtract Constant BinPosDef.Pos.max => \"fn ##name##(&'a self, a: u64, b: u64) -> u64 { std::cmp::max(a, b) }\".\nExtract Constant BinPosDef.Pos.eqb => \"fn ##name##(&'a self, a: u64, b: u64) -> bool { a == b }\".\nExtract Constant BinPosDef.Pos.compare =>\n\"fn ##name##(&'a self, a: u64, b: u64) -> std::cmp::Ordering {\n  a.cmp(&b)\n}\".\nExtract Constant BinPosDef.Pos.compare_cont =>\n\"fn ##name##(&'a self, cont: std::cmp::Ordering, a: u64, b: u64) -> std::cmp::Ordering {\n  if a < b then\n    std::cmp::Ordering::Less\n  else if a == b then\n    cont\n  else\n    std::cmp::Ordering::Greater\".\n\nExtract Constant BinNatDef.N.add => \"fn ##name##(&'a self, a: u64, b: u64) -> u64 { a + b }\".\nExtract Constant BinNatDef.N.succ => \"fn ##name##(&'a self, a: u64) -> u64 { a + 1 }\".\nExtract Constant BinNatDef.N.pred => \"fn ##name##(&'a self, a: u64) -> u64 { a - 1 }\".\nExtract Constant BinNatDef.N.sub => \"fn ##name##(&'a self, a: u64, b: u64) -> u64 { a - b }\".\nExtract Constant BinNatDef.N.mul => \"fn ##name##(&'a self, a: u64, b: u64) -> u64 { a * b }\".\nExtract Constant BinNatDef.N.div => \"fn ##name##(&'a self, a: u64, b: u64) -> u64 { a / b }\".\nExtract Constant BinNatDef.N.modulo => \"fn ##name##(&'a self, a: u64, b: u64) -> u64 { a % b }\".\nExtract Constant BinNatDef.N.min => \"fn ##name##(&'a self, a: u64, b: u64) -> u64 { std::cmp::min(a, b) }\".\nExtract Constant BinNatDef.N.max => \"fn ##name##(&'a self, a: u64, b: u64) -> u64 { std::cmp::max(a, b) }\".\nExtract Constant BinNatDef.N.eqb => \"fn ##name##(&'a self, a: u64, b: u64) -> bool { a == b }\".\nExtract Constant BinNatDef.N.compare =>\n\"fn ##name##(&'a self, a: u64, b: u64) -> std::cmp::Ordering { a.cmp(&b) }\".\n\nExtract Constant BinIntDef.Z.add => \"fn ##name##(&'a self, a: i64, b: i64) -> i64 { a + b }\".\nExtract Constant BinIntDef.Z.succ => \"fn ##name##(&'a self, a: i64) -> i64 { a + 1 }\".\nExtract Constant BinIntDef.Z.pred => \"fn ##name##(&'a self, a: i64) -> i64 { a - 1 }\".\nExtract Constant BinIntDef.Z.sub => \"fn ##name##(&'a self, a: i64, b: i64) -> i64 { a - b }\".\nExtract Constant BinIntDef.Z.mul => \"fn ##name##(&'a self, a: i64, b: i64) -> i64 { a * b }\".\nExtract Constant BinIntDef.Z.opp => \"fn ##name##(&'a self, a: i64) -> i64 { -a }\".\nExtract Constant BinIntDef.Z.min => \"fn ##name##(&'a self, a: i64, b: i64) -> i64 { std::cmp::min(a, b) }\".\nExtract Constant BinIntDef.Z.max => \"fn ##name##(&'a self, a: i64, b: i64) -> i64 { std::cmp::max(a, b) }\".\nExtract Constant BinIntDef.Z.eqb => \"fn ##name##(&'a self, a: i64, b: i64) -> bool { a == b }\".\n(* TODO: div and modulo are nontrivial since Coq rounds towards negative infinity *)\n(*Extract ConstanBinIntDef.t Z.div => \"fn ##name##(a: i64, b: i64) -> i64 { a.checked_div(b).unwrap_or(0) }\".\nExtract Constant BinIntDef.Z.modulo => \"fn ##name##(a: i64, b: i64) -> i64 { a.checked_rem(b).unwrap_or(a) }\".*)\nExtract Constant BinIntDef.Z.compare =>\n\"fn ##name##(&'a self, a: i64, b: i64) -> std::cmp::Ordering { a.cmp(&b) }\".\nExtract Constant BinIntDef.Z.of_N =>\n\"fn ##name##(&'a self, a: u64) -> i64 {\n  use std::convert::TryFrom;\n  i64::try_from(a).unwrap()\n}\".\nExtract Constant BinIntDef.Z.abs_N => \"fn ##name#(&'a self, a: i64) -> u64 { a.unsigned_abs() }\".\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/extraction/plugin/theories/ExtrRustUncheckedArith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.25176864313138614}}
{"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 csubst.\n\n\nDefinition bot_exc {o} : @NTerm o := mk_exception mk_bot mk_bot.\nDefinition bot_excc {o} : @CTerm o := mkc_exception mkc_bot mkc_bot.\n\nDefinition mk_isexc {o} (t : @NTerm o) : @NTerm o := mk_approx bot_exc t.\n\nLemma fold_isexc {p} :\n  forall (t : @NTerm p),\n    mk_approx bot_exc t = mk_isexc t.\nProof. sp. Qed.\n\nLemma wf_bot_exc {o} : @wf_term o bot_exc.\nProof.\n  unfold bot_exc.\n  apply wf_exception; eauto 3 with slow.\nQed.\nHint Resolve wf_bot_exc : slow.\n\nLemma wf_isexc {p} :\n  forall a : @NTerm p, wf_term a -> wf_term (mk_isexc a).\nProof.\n  sp; unfold mk_isexc.\n  allrw @wf_term_eq.\n  constructor; repeat (allsimpl; sp; subst; repeat constructor).\nQed.\n\nLemma wf_isexc_iff {p} :\n  forall a : @NTerm p, wf_term a <=> wf_term (mk_isexc a).\nProof.\n  sp; split; intro i.\n  apply wf_isexc; sp.\n  allrw @wf_term_eq.\n  allrw @nt_wf_eq.\n  apply wf_approx_iff in i; sp.\nQed.\n\nLemma isprogram_bot_exc {o} : @isprogram o bot_exc.\nProof.\n  introv.\n  apply isprogram_exception; eauto 3 with slow.\nQed.\nHint Resolve isprogram_bot_exc : slow.\n\nLemma isprogram_isexc {p} :\n  forall t : @NTerm p,\n    isprogram t\n    -> isprogram (mk_isexc t).\nProof.\n  unfold mk_isexc; introv isp.\n  apply isprogram_approx; eauto 3 with slow.\nQed.\n\nLemma isprog_isexc {p} :\n  forall t : @NTerm p,\n    isprog t\n    -> isprog (mk_isexc t).\nProof.\n  sp; allrw @isprog_eq.\n  apply isprogram_isexc; sp.\nQed.\n\nDefinition mkc_isexc {p} (t : @CTerm p) : CTerm :=\n  let (a,x) := t in\n    exist isprog (mk_isexc a) (isprog_isexc a x).\n\nLemma isprog_vars_isexc {p} :\n  forall vs (a : @NTerm p), isprog_vars vs (mk_isexc a) <=> isprog_vars vs a.\nProof.\n  introv.\n  allrw @isprog_vars_eq; simpl.\n  allrw remove_nvars_nil_l; allrw app_nil_r.\n  allrw @nt_wf_eq.\n  allrw <- @wf_isexc_iff; sp.\nQed.\n\nLemma cover_vars_isexc {p} :\n  forall a sub,\n    @cover_vars p (mk_isexc a) sub\n    <=> cover_vars a sub.\nProof.\n  sp; unfold mk_isexc; split; sp; allrw @cover_vars_eq; allsimpl;\n  allrw remove_nvars_nil_l; allrw app_nil_r;\n  allrw subvars_app_l; sp.\nQed.\n\nLemma csubst_bot_exc {o} :\n  forall (sub : @CSub o), csubst bot_exc sub = bot_exc.\nProof.\n  introv.\n  apply csubst_trivial.\n  simpl; auto.\nQed.\n\nLemma lsubstc_bot_exc {o} :\n  forall (sub : @CSub o)\n         (w  : wf_term bot_exc)\n         (c  : cover_vars bot_exc sub),\n    lsubstc bot_exc w sub c = bot_excc.\nProof.\n  introv.\n  pose proof (lsubstc_mk_exception_ex mk_bot mk_bot sub w c) as h; exrepnd.\n  unfold bot_exc.\n  rw h1; clear h1.\n  allrw @lsubstc_mk_bot; auto.\nQed.\n\nLemma lsubstc_vars_bot_exc {o} :\n  forall (sub : @CSub o)\n         (w  : wf_term bot_exc)\n         (vs : list NVar)\n         (c  : cover_vars_upto bot_exc sub vs),\n    lsubstc_vars bot_exc w sub vs c = mk_cv vs bot_excc.\nProof.\n  introv.\n  apply cvterm_eq; simpl.\n  rw @csubst_bot_exc; auto.\nQed.\n\nLemma lsubstc_mk_isexc {p} :\n  forall t sub,\n  forall wt : @wf_term p t,\n  forall w  : wf_term (mk_isexc t),\n  forall ct : cover_vars t sub,\n  forall c  : cover_vars (mk_isexc t) sub,\n    lsubstc (mk_isexc t) w sub c\n    = mkc_isexc (lsubstc t wt sub ct).\nProof.\n  unfold mk_isexc; sp.\n  pose proof (lsubstc_mk_approx_ex bot_exc t sub w c) as h.\n  exrepnd.\n  rw h1; clear h1.\n  rw @lsubstc_bot_exc.\n  apply cterm_eq; simpl; auto.\nQed.\n\nLemma lsubstc_mk_isexc_ex {p} :\n  forall t sub,\n  forall w  : wf_term (@mk_isexc p t),\n  forall c  : cover_vars (mk_isexc t) sub,\n    {wt : wf_term t\n     & {ct : cover_vars t sub\n        & lsubstc (mk_isexc t) w sub c\n             = mkc_isexc (lsubstc t wt sub ct)}}.\nProof.\n  sp.\n  duplicate w; duplicate c.\n  rw <- @wf_isexc_iff in w.\n  rw @cover_vars_isexc in c.\n  exists w c.\n  apply lsubstc_mk_isexc.\nQed.\n\nLemma mkc_isexc_eq {o} :\n  forall (t : @CTerm o), mkc_isexc t = mkc_approx bot_excc t.\nProof.\n  introv.\n  destruct_cterms.\n  apply cterm_eq; simpl; auto.\nQed.\n\n\nDefinition mk_halts_like {o} (t : @NTerm o) : @NTerm o :=\n  mk_approx bot_exc (mk_cbv t nvarx bot_exc).\n\nLemma fold_halts_like {p} :\n  forall (t : @NTerm p),\n    mk_approx bot_exc (mk_cbv t nvarx bot_exc) = mk_halts_like t.\nProof. sp. Qed.\n\nLemma wf_halts_like {p} :\n  forall a : @NTerm p, wf_term a -> wf_term (mk_halts_like a).\nProof.\n  introv wf; unfold mk_halts_like.\n  apply wf_approx; eauto 3 with slow.\n  apply wf_cbv; eauto 3 with slow.\nQed.\n\nLemma wf_halts_like_iff {p} :\n  forall a : @NTerm p, wf_term a <=> wf_term (mk_halts_like a).\nProof.\n  sp; split; intro i.\n  apply wf_halts_like; sp.\n  unfold mk_halts_like in i.\n  apply wf_approx_iff in i; repnd.\n  apply wf_cbv_iff in i; sp.\nQed.\n\nLemma isprogram_halts_like {p} :\n  forall t : @NTerm p,\n    isprogram t\n    -> isprogram (mk_halts_like t).\nProof.\n  unfold mk_halts_like; introv isp.\n  apply isprogram_approx; eauto 3 with slow.\n  apply isprogram_cbv; eauto 3 with slow.\nQed.\n\nLemma isprog_halts_like {p} :\n  forall t : @NTerm p,\n    isprog t\n    -> isprog (mk_halts_like t).\nProof.\n  sp; allrw @isprog_eq.\n  apply isprogram_halts_like; sp.\nQed.\n\nDefinition mkc_halts_like {p} (t : @CTerm p) : CTerm :=\n  let (a,x) := t in\n    exist isprog (mk_halts_like a) (isprog_halts_like a x).\n\nLemma isprog_vars_halts_like {p} :\n  forall vs (a : @NTerm p), isprog_vars vs (mk_halts_like a) <=> isprog_vars vs a.\nProof.\n  introv.\n  allrw @isprog_vars_eq; simpl.\n  allrw remove_nvars_nil_l; allrw app_nil_r.\n  allrw @nt_wf_eq.\n  allrw <- @wf_halts_like_iff; sp.\nQed.\n\nLemma cover_vars_halts_like {p} :\n  forall a sub,\n    @cover_vars p (mk_halts_like a) sub\n    <=> cover_vars a sub.\nProof.\n  sp; unfold mk_halts_like; split; sp; allrw @cover_vars_eq; allsimpl;\n  allrw remove_nvars_nil_l; allrw app_nil_r;\n  allrw subvars_app_l; sp.\nQed.\n\nLemma lsubstc_mk_halts_like {p} :\n  forall t sub,\n  forall wt : @wf_term p t,\n  forall w  : wf_term (mk_halts_like t),\n  forall ct : cover_vars t sub,\n  forall c  : cover_vars (mk_halts_like t) sub,\n    lsubstc (mk_halts_like t) w sub c\n    = mkc_halts_like (lsubstc t wt sub ct).\nProof.\n  unfold mk_isexc; sp.\n  pose proof (lsubstc_mk_approx_ex bot_exc (mk_cbv t nvarx bot_exc) sub w c) as h.\n  exrepnd.\n  unfold mk_halts_like.\n  rw h1; clear h1.\n  pose proof (lsubstc_mk_cbv_ex t nvarx bot_exc sub w2 c2) as h; exrepnd.\n  rw h1; clear h1.\n  rw @lsubstc_bot_exc.\n  rw @lsubstc_vars_bot_exc.\n  apply cterm_eq; simpl; auto.\nQed.\n\nLemma lsubstc_mk_halts_like_ex {p} :\n  forall t sub,\n  forall w  : wf_term (@mk_halts_like p t),\n  forall c  : cover_vars (mk_halts_like t) sub,\n    {wt : wf_term t\n     & {ct : cover_vars t sub\n     & lsubstc (mk_halts_like t) w sub c\n       = mkc_halts_like (lsubstc t wt sub ct)}}.\nProof.\n  sp.\n  duplicate w; duplicate c.\n  rw <- @wf_halts_like_iff in w.\n  rw @cover_vars_halts_like in c.\n  exists w c.\n  apply lsubstc_mk_halts_like.\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/csubst5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.25176864313138614}}
{"text": "Require Import Bool.\nRequire Import List.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\n\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 Thread.\nRequire Import Configuration.\n\nRequire Import FulfillStep.\nRequire Import SimMemory.\nRequire Import SimPromises.\nRequire Import SimLocal.\nRequire Import Compatibility.\nRequire Import SimThread.\n\nRequire Import Syntax.\nRequire Import Semantics.\nRequire Import SplitAcq.\n\nSet Implicit Arguments.\n\n\nDefinition local_acqrel (lc:Local.t) :=\n  (Local.mk (TView.write_fence_tview\n               (TView.read_fence_tview lc.(Local.tview) Ordering.acqrel)\n               TimeMap.bot\n               Ordering.acqrel)\n            lc.(Local.promises)).\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 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_local 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 val released lc2_src mem2_src kind>> /\\\n    <<LOCAL2: sim_local 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 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  i. des.\n  esplits; eauto.\n  - econs; 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 lc1_src (local_acquired lc1_tgt))\n      (ACQUIRED1: View.le lc1_src.(Local.tview).(TView.cur)\n                          (View.join lc1_tgt.(Local.tview).(TView.cur) releasedm_tgt.(View.unwrap)))\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 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 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  { 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 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_bot; 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    + etrans; 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 lc1_src (local_acquired lc1_tgt))\n      (ACQUIRED1: View.le lc1_src.(Local.tview).(TView.cur)\n                          (View.join lc1_tgt.(Local.tview).(TView.cur) releasedm_tgt.(View.unwrap)))\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 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; try exact STEP_SRC; try exact STEP_SRC0; eauto.\n  { i. exploit ORD0; eauto.\n    - etrans; 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:lang.(Language.state)) (lc_src:Local.t) (sc1_src:TimeMap.t) (mem1_src:Memory.t)\n                        (st_tgt:lang.(Language.state)) (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 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 mem1_src mem2_src)\n      (MEM_FUTURE_TGT: Memory.future 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_future\n      st_src lc_src sc1_src mem1_src\n      st_tgt lc_tgt sc1_tgt mem1_tgt\n      sc2_src mem2_src\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_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      (MEM_FUTURE_SRC: Memory.future mem1_src mem2_src)\n      (WF_SRC: Local.wf lc_src mem2_src)\n      (SC_SRC: Memory.closed_timemap sc2_src mem2_src)\n      (MEM_SRC: Memory.closed mem2_src):\n  exists lc'_src sc2_tgt mem2_tgt,\n    <<SC2: TimeMap.le sc2_src sc2_tgt>> /\\\n    <<MEM2: 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 lc_tgt mem2_tgt>> /\\\n    <<SC_TGT: Memory.closed_timemap sc2_tgt mem2_tgt>> /\\\n    <<MEM_TGT: Memory.closed mem2_tgt>> /\\\n    <<SIM2: sim_acqrel st_src lc'_src sc2_src mem2_src\n                         st_tgt lc_tgt sc2_tgt mem2_tgt>>.\nProof.\n  inv SIM1.\n  exploit SimPromises.future; try apply MEM1; eauto.\n  { inv LOCAL. ss. eauto. }\n  i. des. esplits; eauto.\n  - etrans.\n    + apply Memory.max_timemap_spec; eauto. viewtac.\n    + apply sim_memory_max_timemap; eauto.\n  - etrans.\n    + apply Memory.max_timemap_spec; eauto. viewtac.\n    + apply Memory.future_max_timemap; eauto.\n  - apply Memory.max_timemap_closed. viewtac.\n  - econs; eauto.\n    + etrans.\n      * apply Memory.max_timemap_spec; eauto. viewtac.\n      * apply sim_memory_max_timemap; eauto.\n    + apply Memory.max_timemap_closed. viewtac.\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    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.\n    + econs 2. econs. econs; eauto.\n    + eauto.\n    + right. econs; eauto.\n  - (* fence *)\n    exploit Local.fence_step_future; eauto. i. des.\n    inv STATE. inv INSTR. inv LOCAL1. ss.\n    esplits; (try by econs 1); eauto.\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  - exploit sim_acqrel_mon; eauto. i.\n    exploit sim_acqrel_future; try apply x0; eauto. i. des.\n    esplits; eauto.\n  - 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.\n    + esplits; eauto.\n      left. eapply paco9_mon; eauto. ss.\n    + 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  { exploit SimPromises.future; try apply LOCAL; eauto. i. des.\n    esplits; eauto.\n    - etrans.\n      + apply Memory.max_timemap_spec; eauto. viewtac.\n      + apply sim_memory_max_timemap; eauto.\n    - etrans.\n      + apply Memory.max_timemap_spec; eauto. viewtac.\n      + apply Memory.future_max_timemap; eauto.\n    - apply Memory.max_timemap_closed. viewtac.\n  }\n  { esplits; eauto.\n    inv LOCAL. apply SimPromises.sem_bot_inv in PROMISES; auto. rewrite PROMISES. auto.\n  }\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.\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.\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.\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. eapply MEM_TGT. eauto. }\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.\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-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/SplitAcqRel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2517460651641146}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\nRequire Import Coq.micromega.Lia.\nRequire Import bedrock2.Syntax.\nRequire Import bedrock2.ProgramLogic.\nRequire Import bedrock2.Map.Separation.\nRequire Import bedrock2.Map.SeparationLogic.\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.Datatypes.List.\nRequire Import coqutil.Datatypes.PropSet.\nRequire Import Crypto.Bedrock.Field.Common.Types.\nRequire Import Crypto.Bedrock.Field.Common.Tactics.\nRequire Import Crypto.Bedrock.Field.Common.Util.\nRequire Import Crypto.Bedrock.Field.Translation.Proofs.Cmd.\nRequire Import Crypto.Bedrock.Field.Translation.Proofs.Equivalence.\nRequire Import Crypto.Bedrock.Field.Translation.Proofs.EquivalenceProperties.\nRequire Import Crypto.Bedrock.Field.Translation.Proofs.Flatten.\nRequire Import Crypto.Bedrock.Field.Translation.Proofs.UsedVarnames.\nRequire Import Crypto.Bedrock.Field.Translation.Proofs.VarnameSet.\nRequire Import Crypto.Bedrock.Field.Translation.Proofs.LoadStoreList.\nRequire Import Crypto.Bedrock.Field.Translation.Func.\nRequire Import Crypto.Bedrock.Field.Translation.Flatten.\nRequire Import Crypto.Bedrock.Field.Translation.LoadStoreList.\nRequire Import Crypto.Language.API.\nRequire Import Crypto.Util.ListUtil.\nRequire Import Crypto.Util.Option.\nImport ListNotations. Local Open Scope Z_scope.\n\nImport API.Compilers.\nImport Wf.Compilers.expr.\nImport Types.Notations.\n\nSection Func.\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\n  Local Existing Instance rep.Z.\n\n  Inductive valid_func : forall {t}, @API.expr (fun _ => unit) t -> Prop :=\n  | validf_Abs :\n      forall {s d} f, valid_func (f tt) ->\n                      valid_func (expr.Abs (s:=type.base s) (d:=d) f)\n  | validf_base :\n      forall {b} e, valid_cmd e -> valid_func (t:=type.base b) e\n  .\n\n  Lemma translate_func'_correct {t}\n        (* three exprs, representing the same Expr with different vars *)\n        (e0 : @API.expr (fun _ => unit) t)\n        (e1 : @API.expr API.interp_type t)\n        (e2 : @API.expr ltype t)\n        (* expressions are valid input to translate_func' *)\n        (e0_valid : valid_func e0)\n        (* context list (consists only of arguments) *)\n        (G : list _) :\n    (* exprs are all related *)\n    wf3 G e0 e1 e2 ->\n    forall (argnames : type.for_each_lhs_of_arrow ltype t)\n           (args : type.for_each_lhs_of_arrow API.interp_type t)\n           (nextn : nat),\n      (* ret1 := fiat-crypto interpretation of e1 applied to args1 *)\n      let ret1 : base.interp (type.final_codomain t) :=\n          type.app_curried (API.interp e1) args in\n      (* out := translation output for e2; triple of\n         (# varnames used, return values, cmd) *)\n      let out := translate_func' e2 nextn argnames in\n      let nvars := fst (fst out) in\n      let ret2 := base_rtype_of_ltype (snd (fst out)) in\n      let body := snd out in\n      (* look up variables in argnames *)\n      let argvalues :=\n          type.map_for_each_lhs_of_arrow rtype_of_ltype argnames in\n      (* argnames don't contain variables we could later overwrite *)\n      (forall n,\n        (nextn <= n)%nat ->\n        ~ varname_set_args argnames (varname_gen n)) ->\n      (* G doesn't contain variables we could overwrite *)\n      (forall n,\n        (nextn <= n)%nat ->\n        ~ context_varname_set G (varname_gen n)) ->\n      forall (tr : Semantics.trace)\n             (locals : locals)\n             (mem : mem)\n             (functions : list (string*func)),\n        (* locals doesn't contain variables we could overwrite *)\n        (forall n nvars,\n            (nextn <= n)%nat ->\n            map.undef_on locals (used_varnames (varname_gen:=varname_gen) n nvars)) ->\n        (* argument values are equivalent *)\n        locally_equivalent_args args argvalues locals ->\n        (* contexts are equivalent; for every variable in the context list G,\n           the fiat-crypto and bedrock2 results match *)\n        context_equiv G locals ->\n        (* executing translation output is equivalent to interpreting e *)\n        WeakestPrecondition.cmd\n          (WeakestPrecondition.call functions)\n          body tr mem locals\n          (fun tr' mem' locals' =>\n             tr = tr' /\\\n             mem = mem' /\\\n             subset (varname_set_base (snd (fst out)))\n                            (used_varnames (varname_gen:=varname_gen) nextn nvars) /\\\n             Interface.map.only_differ\n               locals (used_varnames (varname_gen:=varname_gen) nextn nvars) locals' /\\\n             locally_equivalent_base\n               (listZ:=rep.listZ_local) ret1 ret2 locals').\n  Proof.\n    revert G. cbv zeta.\n    induction e0_valid; intros *.\n    { (* Abs *)\n      inversion 1; cleanup_wf.\n      cbn [translate_func']; intros.\n      match goal with\n      | H : context [varname_set_args] |- _ =>\n        cbn [varname_set_args] in H;\n          setoid_rewrite not_union_iff in H;\n          match type of H with\n            forall x y, ?P /\\ ?Q =>\n            assert (forall x y, P) by (apply H);\n            assert (forall x y, Q) by (apply H);\n            clear H\n          end\n      end.\n      destruct argnames.\n      cbv [locally_equivalent_args] in *.\n      cbn [fst snd equivalent_args\n               type.map_for_each_lhs_of_arrow] in *.\n      cleanup. sepsimpl.\n      eapply IHe0_valid; eauto; [ | ].\n      { destruct args; cbn [fst snd].\n        cbn [context_varname_set]; intros.\n        apply not_union_iff; eauto with lia. }\n      { eapply Forall_cons; eauto. } }\n    { (* base case *)\n      inversion 1; cleanup_wf;\n      cbv [translate_func']; intros.\n      all:eapply Proper_cmd;\n        [solve [apply Proper_call] | repeat intro\n         | eapply (translate_cmd_correct (t:=type.base _));\n           solve [eauto] ];\n        cbv beta in *; cleanup; subst; tauto. }\n  Qed.\n\n  Lemma look_up_return_values {t} :\n    forall (ret : base.interp t)\n           (retnames : listexcl_base_ltype (listZ:=rep.listZ_mem) t)\n           (retsizes : base_access_sizes t)\n           (locals : locals)\n           (mem : mem)\n           (R : _ -> Prop),\n      sep (equivalent_listexcl\n             ret (map_listexcl (fun t => base_rtype_of_ltype (t:=t)) retnames)\n             retsizes locals) R mem ->\n      WeakestPrecondition.list_map\n        (WeakestPrecondition.get locals)\n        (flatten_listexcl_base_ltype retnames)\n        (fun flat_rets =>\n           sep (equivalent_listexcl_flat_base ret flat_rets retsizes)\n               R mem).\n  Proof.\n    cbv [flatten_retnames].\n    induction t;\n      cbn [flatten_base_ltype\n             flatten_listexcl_base_ltype\n             equivalent_listexcl_flat_base\n             equivalent_listexcl\n             flatten_rets base_rtype_of_ltype rep.rtype_of_ltype\n             flatten_base_rtype equivalent_flat_base\n             rep.listZ_mem rep.Z equivalent]; break_match;\n        repeat match goal with\n               | _ => progress (intros; cleanup)\n               | _ => progress subst\n               | _ => progress sepsimpl\n               | _ => progress cbn [rep.equiv rep.listZ_mem rep.Z] in *\n               | _ => progress cbn [List.hd\n                                      WeakestPrecondition.list_map\n                                      WeakestPrecondition.list_map_body\n                                      WeakestPrecondition.literal\n                                      WeakestPrecondition.dexpr\n                                      WeakestPrecondition.dexprs\n                                      WeakestPrecondition.expr\n                                      WeakestPrecondition.expr_body]\n               | _ => rewrite word.of_Z_unsigned\n               | H : WeakestPrecondition.dexpr _ _ _ _ |- _ => destruct H\n               | |- WeakestPrecondition.get _ _ _ => eexists; split; [ eassumption | ]\n               | |- WeakestPrecondition.literal _ _ =>\n                 cbv [WeakestPrecondition.literal dlet.dlet]\n               | |- Lift1Prop.ex1 _ _ => eexists; sepsimpl; eauto; [ ]\n               | H : False |- _ => tauto\n               | _ => reflexivity\n               | _ => solve [eauto]\n               end.\n    { apply list_map_app_iff;\n        [ split; intros;\n          (eapply Proper_get; [|eassumption]); repeat intro;\n          match goal with H : _ |- _ => apply H; solve [eauto] end |  ].\n      fold (@Language.Compilers.base.interp) in *.\n      eapply Proper_list_map; [ solve [apply Proper_get] | repeat intro | ].\n      2:{ eapply IHt1;\n          (* TODO: why does ecancel_assumption not work here? *)\n          use_sep_assumption; rewrite sep_assoc; reflexivity. }\n      cbv beta in *.\n      eapply Proper_list_map; [ solve [apply Proper_get] | repeat intro | ].\n      2:{ eapply IHt2.\n          (* TODO: why does ecancel_assumption not work here? *)\n          use_sep_assumption; rewrite sep_comm,sep_assoc; reflexivity. }\n      cbv beta in *.\n      apply sep_ex1_l.\n      match goal with |- context[List.firstn _ (?x ++ ?y)] =>\n                      exists (length x) end.\n      rewrite firstn_app_sharp, skipn_app_sharp by reflexivity.\n      ecancel_assumption. }\n  Qed.\n\n  Lemma equivalent_flat_base_iff1 {t} :\n    forall (names : base_ltype t)\n           (values : base.interp t)\n           (sizes : base_access_sizes t)\n           (flat_values : list word)\n           (locals locals' : locals),\n      NoDup (flatten_base_ltype names) ->\n      map.putmany_of_list_zip\n        (flatten_base_ltype names) flat_values locals = Some locals' ->\n      Lift1Prop.iff1\n        (equivalent_flat_base values flat_values sizes)\n        (equivalent_base values (base_rtype_of_ltype names) sizes locals').\n  Proof.\n    induction t;\n      cbn [rep.Z rep.equiv base_rtype_of_ltype\n                 equivalent_base equivalent_flat_base\n                 flatten_base_ltype];\n      break_match; cbn [fst snd]; intros; try reflexivity; [ | | ].\n    all:match goal with\n          H : _ |- _ =>\n          pose proof H;\n            eapply map.putmany_of_list_zip_sameLength in H;\n            cbn [length] in H\n        end.\n    { repeat intro. rewrite sep_emp_l.\n      destruct flat_values as [| ? [|? ?] ]; cbn [length] in *; try lia.\n      cbv [emp List.hd\n               WeakestPrecondition.literal dlet.dlet\n               WeakestPrecondition.get WeakestPrecondition.dexpr\n               WeakestPrecondition.expr WeakestPrecondition.expr_body].\n      repeat match goal with\n             | _ => progress sepsimpl\n             | _ => progress subst\n             | _ => progress cbn [map.putmany_of_list_zip] in *\n             | H : Some _ = Some _ |- _ => inversion H; clear H; subst\n             | _ => rewrite map.get_put_same, word.of_Z_unsigned\n             | _ => split; intros; cleanup; subst\n             | _ => eexists; sepsimpl; [ reflexivity .. | ]\n             | _ => solve [eauto]\n             end. }\n    { match goal with\n      | H : _ |- _ =>\n        rewrite putmany_of_list_zip_app_l in H;\n          pose proof H;\n          rewrite putmany_of_list_zip_bind_comm in H by auto\n      end.\n      match goal with\n        H : NoDup (_ ++ _) |- _ =>\n        pose proof H;\n        apply NoDup_app_iff in H; cleanup\n      end.\n      cbv [Option.bind] in *.\n      break_match_hyps; try congruence.\n      repeat intro; split; intros.\n      { match goal with\n        | H : Lift1Prop.ex1 _ _ |- _ => destruct H end.\n        eapply Proper_sep_iff1;\n          [ symmetry; eapply IHt1; eassumption\n          | symmetry; eapply IHt2; eassumption | ].\n        erewrite <-flatten_base_samelength by ecancel_assumption.\n        rewrite firstn_length_firstn, skipn_length_firstn.\n        assumption. }\n      { eexists.\n        eapply Proper_sep_iff1;\n          [ eapply IHt1; eassumption\n          | eapply IHt2; eassumption | ].\n        eapply Proper_sep_iff1; [ | reflexivity | ].\n        { eapply (equivalent_only_differ_iff1\n                    ltac:(eapply equiv_listZ_only_differ_mem)\n                 _ locals');\n            eauto using @only_differ_sym, @map.only_differ_putmany with typeclass_instances.\n          symmetry.\n          eapply disjoint_sameset; eauto using varname_set_flatten.\n          apply NoDup_disjoint; eauto using string_dec. }\n        { eauto. } } }\n    { repeat intro. rewrite sep_emp_l.\n      destruct flat_values as [| ? [|? ?] ]; cbn [length] in *; try lia.\n      cbv [List.hd\n             rep.equiv rep.rtype_of_ltype rep.listZ_mem rep.Z\n             WeakestPrecondition.literal dlet.dlet\n             WeakestPrecondition.get WeakestPrecondition.dexpr\n             WeakestPrecondition.expr WeakestPrecondition.expr_body].\n      match goal with\n        H : map.putmany_of_list_zip _ _ _ = _ |- _ =>\n        cbn [map.putmany_of_list_zip] in H; inversion H; clear H; subst\n      end.\n      split; intros;\n        repeat match goal with\n               | _ => progress sepsimpl\n               | _ => progress subst\n               | H : Some _ = Some _ |- _ =>\n                 inversion H; clear H; subst\n               | H : _ |- _ => rewrite word.of_Z_unsigned in H\n               | H : _ |- _ => rewrite map.get_put_same in H\n               | _ => rewrite map.get_put_same\n               | _ => rewrite word.of_Z_unsigned\n               | |- Lift1Prop.ex1 _ _ => eexists\n               | |- exists _, _ => eexists\n               | |- _ /\\ _ => split\n               | _ => solve [eauto]\n               | _ => congruence\n               end. }\n  Qed.\n\n  (* When arguments are loaded into initial locals, the new argument names map\n     to the correct values *)\n  Lemma equivalent_flat_args_iff1 {t} :\n    forall (argnames : type.for_each_lhs_of_arrow ltype t)\n           (args : type.for_each_lhs_of_arrow API.interp_type t)\n           (argsizes : type.for_each_lhs_of_arrow access_sizes t)\n           (flat_args : list word)\n           (locals locals' : locals),\n      NoDup (flatten_argnames argnames) ->\n      map.putmany_of_list_zip\n        (flatten_argnames argnames) flat_args locals = Some locals' ->\n      let argvalues :=\n          type.map_for_each_lhs_of_arrow rtype_of_ltype argnames in\n      Lift1Prop.iff1\n        (equivalent_flat_args args flat_args argsizes)\n        (equivalent_args args argvalues argsizes locals').\n  Proof.\n    induction t;\n      cbn [equivalent_args\n             equivalent_flat_args\n             flatten_argnames type.map_for_each_lhs_of_arrow];\n      break_match; intros; try reflexivity; [ | ].\n    all:match goal with\n          H : _ |- _ =>\n          pose proof H;\n            eapply map.putmany_of_list_zip_sameLength in H\n        end.\n    { destruct flat_args; cbn [length] in *; try lia; [ ].\n      repeat intro; cbv [emp]; tauto. }\n    { destruct argnames. cbn [fst snd rtype_of_ltype] in *.\n      match goal with\n      | H : _ |- _ =>\n        pose proof H; rewrite putmany_of_list_zip_app_l in H\n      end.\n      match goal with\n      | H : NoDup (_ ++ _) |- _ =>\n        pose proof H; apply NoDup_app_iff in H; cleanup\n      end.\n      cbv [Option.bind] in *. break_match_hyps; try congruence.\n      repeat intro; split; intros.\n      { repeat match goal with\n               | _ => progress cleanup\n               | H : Lift1Prop.ex1 _ _ |- _ => destruct H\n               | H: _ |- _ =>\n                 erewrite <-flatten_base_samelength in H by eauto;\n                   rewrite ?firstn_length_firstn, ?skipn_length_firstn in H\n               end.\n        split; eauto.\n        { eexists.\n          eapply Proper_sep_iff1;\n            [ | reflexivity | eassumption ].\n          rewrite equivalent_flat_base_iff1 by eauto.\n          eapply equivalent_only_differ_iff1;\n            eauto using @only_differ_sym, @map.only_differ_putmany\n              with typeclass_instances equiv; [ ].\n          rewrite varname_set_flatten; symmetry;\n            apply NoDup_disjoint; eauto using string_dec. }\n        { eapply IHt2; eassumption. } }\n      { cleanup; subst.\n        eexists; split; eauto.\n        { eexists.\n          eapply Proper_sep_iff1;\n            [ | reflexivity | eassumption ].\n          rewrite equivalent_flat_base_iff1 by eauto.\n          eapply equivalent_only_differ_iff1;\n            eauto using @only_differ_sym, @map.only_differ_putmany\n              with typeclass_instances equiv; [ ].\n          rewrite varname_set_flatten; symmetry;\n            apply NoDup_disjoint; eauto using string_dec. }\n        { eapply IHt2; eassumption. } } }\n  Qed.\n\n  Lemma equivalent_listonly_flat_iff1 {t} :\n    forall (names : listonly_base_ltype t) (values : list word)\n           (sizes : base_access_sizes t)\n           (l locals init_locals : locals)\n           (vset : set string) (x : base.interp t),\n      NoDup (flatten_listonly_base_ltype names) ->\n      map.putmany_of_list_zip (flatten_listonly_base_ltype names) values l = Some init_locals ->\n      map.only_differ init_locals vset locals ->\n      disjoint vset (of_list (flatten_listonly_base_ltype names)) ->\n      Lift1Prop.iff1\n        (equivalent_listonly\n           x (map_listonly base_rtype_of_ltype names) sizes locals)\n        (equivalent_listonly_flat_base x values sizes).\n  Proof.\n    induction t;\n      cbn [fst snd equivalent_listonly equivalent_listonly_flat_base\n               flatten_listonly_base_ltype\n               equivalent_flat_base map_listonly];\n      intros; break_match; try reflexivity; [ | | ].\n    { cbn [map.putmany_of_list_zip] in *.\n      break_match_hyps; try congruence; [ ].\n      split; intros; sepsimpl; tauto. }\n    { destruct names. cbn [fst snd] in *.\n      match goal with\n      | H : _ |- _ =>\n        pose proof H; rewrite putmany_of_list_zip_app_l in H\n      end.\n      match goal with\n      | H : NoDup (_ ++ _) |- _ =>\n        pose proof H; apply NoDup_app_iff in H; cleanup\n      end.\n      cbv [Option.bind] in *. break_match_hyps; try congruence; [ ].\n      match goal with\n      | H : _ |- _ => rewrite of_list_app in H;\n                        rewrite disjoint_union_r_iff in H\n      end.\n      cleanup.\n\n      match goal with\n      | H : map.putmany_of_list_zip _ (List.firstn _ _) _ = Some _ |- _ =>\n        pose proof H; apply map.only_differ_putmany in H\n      end.\n      match goal with\n      | H : map.putmany_of_list_zip _ (List.skipn _ _) _ = Some _ |- _ =>\n        pose proof H; apply map.only_differ_putmany in H\n      end.\n\n      erewrite IHt1; eauto using only_differ_trans; [ |\n        apply disjoint_union_l_iff; intuition trivial;\n        symmetry; eapply NoDup_disjoint; eauto ].\n      erewrite IHt2 by eauto using only_differ_trans.\n      split; intros; [ eexists; eassumption | ].\n      sepsimpl.\n      erewrite <-flatten_listonly_samelength by ecancel_assumption.\n      rewrite firstn_length_firstn, skipn_length_firstn.\n      fold (@Language.Compilers.base.interp) in *.\n      ecancel_assumption. }\n    { cbn [map.putmany_of_list_zip] in *.\n      break_match_hyps; try congruence; [ ].\n      match goal with H : Some _ = Some _ |- _ =>\n                      inversion H; subst; clear H end.\n      cbn [rep.Z rep.listZ_mem base_rtype_of_ltype rep.rtype_of_ltype\n                 rep.equiv length List.hd].\n      cbn [WeakestPrecondition.dexpr\n             WeakestPrecondition.expr WeakestPrecondition.expr_body].\n      cbv [WeakestPrecondition.literal dlet.dlet].\n      repeat match goal with\n             | H : _ |- _ => rewrite map.get_put_same in H\n             | H : context [of_list [_] ] |- _ =>\n               rewrite of_list_singleton in H\n             | H : map.only_differ (map.put _ ?k ?v) _ ?m' |- _ =>\n               eapply only_differ_notin in H;\n                 [ | eapply disjoint_singleton_r_iff; eassumption ]\n             end.\n      cbv [WeakestPrecondition.get].\n      split; intros; sepsimpl; subst; try reflexivity.\n      { eexists. sepsimpl; eauto; [ ].\n        rewrite !word.of_Z_unsigned in *.\n        eexists; sepsimpl; eauto; [ ].\n        eexists; sepsimpl; eauto; [ ].\n        congruence. }\n      { eexists; sepsimpl; eauto; [ ].\n        eexists; sepsimpl; eauto; [ ].\n        eexists; sepsimpl; eauto; [ ].\n        eexists; split; eauto; [ ].\n        apply word.of_Z_unsigned. } }\n  Qed.\n\n  Lemma translate_func_correct {t}\n        (e : API.Expr t)\n        (* expressions are valid input to translate_func *)\n        (e_valid : valid_func (e _)) :\n    Wf e ->\n    forall (fname : string)\n           (retnames : base_ltype (type.final_codomain t))\n           (retsizes : base_access_sizes (type.final_codomain t))\n           (argnames : type.for_each_lhs_of_arrow ltype t)\n           (arglengths : type.for_each_lhs_of_arrow list_lengths t)\n           (argsizes : type.for_each_lhs_of_arrow access_sizes t)\n           (args : type.for_each_lhs_of_arrow API.interp_type t),\n      (* rets := fiat-crypto interpretation of e1 applied to args *)\n      let rets : base.interp (type.final_codomain t) :=\n          type.app_curried (API.interp (e _)) args in\n      (* extract list lengths from fiat-crypto arguments/return values *)\n      arglengths = list_lengths_from_args args ->\n      let retlengths := list_lengths_from_value rets in\n      (* out := translation output for e2; triple of\n         (function arguments, function return variable names, body) *)\n      let out := translate_func\n                   e argnames arglengths argsizes retnames retsizes in\n      let f : string*func := (fname, fst out) in\n      let lengths := snd out in\n      forall tr\n             (mem : mem)\n             (flat_args : list word)\n             (out_ptrs : list word)\n             (argvalues : list word)\n             (functions : list (string*func))\n             (R : _ -> Prop),\n        (* argument values are the concatenation of true argument values\n           and output pointer values *)\n        argvalues = out_ptrs ++ flat_args ->\n        length out_ptrs =\n        length (flatten_listonly_base_ltype\n                  (fst (extract_listnames retnames))) ->\n        (* argnames don't contain variables we could later overwrite *)\n        (forall n, ~ varname_set_args argnames (varname_gen n)) ->\n        (* argument values are equivalent *)\n        equivalent_flat_args args flat_args argsizes mem ->\n        (* argnames don't have duplicates *)\n        NoDup (flatten_argnames argnames) ->\n        (* argument bounds are within allowed integer size *)\n        access_sizes_good_args argsizes ->\n        (* argument bounds are obeyed *)\n        within_access_sizes_args args argsizes ->\n        (* retnames don't contain variables we could later overwrite *)\n        (forall n, ~ varname_set_base retnames (varname_gen n)) ->\n        (* retnames don't have duplicates *)\n        NoDup (flatten_base_ltype retnames) ->\n        (* return value bounds are within allowed integer size *)\n        base_access_sizes_good retsizes ->\n        (* return value bounds are obeyed *)\n        within_base_access_sizes rets retsizes ->\n        (* argnames and retnames are disjoint *)\n        disjoint (varname_set_args argnames)\n                         (varname_set_base retnames) ->\n        (* seplogic frame for return values *)\n        sep (lists_reserved_with_initial_context\n               retlengths argnames retnames retsizes argvalues) R mem ->\n        (* translated function produces equivalent results *)\n        WeakestPrecondition.call\n          (f :: functions) fname tr mem argvalues\n          (fun tr' mem' flat_rets =>\n             tr = tr' /\\\n             (* lengths of output lists match *)\n             retlengths = snd out /\\\n             (* return values are equivalent *)\n             sep (sep (equivalent_listexcl_flat_base\n                         rets flat_rets retsizes)\n                      (equivalent_listonly_flat_base\n                         rets out_ptrs retsizes))\n                 R mem').\n  Proof.\n    cbv [translate_func]; intros. subst.\n    cbn [fst snd\n             WeakestPrecondition.call\n             WeakestPrecondition.call_body WeakestPrecondition.func].\n    rewrite eqb_refl.\n    match goal with\n      |- exists l, map.of_list_zip ?ks ?vs = Some l /\\ _ =>\n      assert (NoDup ks);\n        [ | assert (exists m, map.of_list_zip ks vs = Some m);\n            [ | cleanup; eexists; split; [ eassumption | ] ] ]\n    end.\n    { apply disjoint_NoDup; eauto using flatten_listonly_NoDup.\n      eapply subset_disjoint_l;\n        [ | symmetry; rewrite <-varname_set_args_flatten; solve [eauto] ].\n      eapply flatten_listonly_subset. }\n    { eapply of_list_zip_app; try lia; [ ].\n      erewrite flatten_args_samelength; eauto. }\n    match goal with H : _ |- _ =>\n                    pose proof H;\n                      eapply (of_list_zip_flatten_argnames argnames) in H;\n                      cleanup\n    end.\n    match goal with\n    | H : map.of_list_zip _ _ = Some _ |- _ =>\n      pose proof H;\n      cbv [map.of_list_zip] in H;\n        rewrite putmany_of_list_zip_app_l in H;\n        rewrite firstn_app_sharp, skipn_app_sharp in H\n          by eauto using flatten_args_samelength;\n        pose proof H; (* preserve original ordering *)\n        erewrite putmany_of_list_zip_bind_comm in H by eauto;\n        cbv [Option.bind] in *; repeat break_match_hyps; try congruence; [ ]\n    end.\n    cbn [WeakestPrecondition.cmd WeakestPrecondition.cmd_body].\n    eapply Proper_cmd; [ solve [apply Proper_call] | repeat intro | ].\n    2 : { eapply load_arguments_correct; try eassumption; eauto.\n          eapply equivalent_flat_args_iff1; eauto. }\n    cbv beta in *. cleanup; subst.\n    eapply Proper_cmd; [ solve [apply Proper_call] | repeat intro | ].\n    2 : { eapply @translate_func'_correct with (args:=args);\n          cbv [context_equiv]; intros; try apply Wf3_of_Wf; eauto; [ ].\n          eapply only_differ_disjoint_undef_on; eauto;\n            [ eapply used_varnames_disjoint; lia | ].\n          eapply putmany_of_list_zip_undef_on\n            with (ks:=flatten_argnames _); eauto;\n            [ rewrite <-varname_set_args_flatten;\n              symmetry; eapply disjoint_used_varnames_lt;\n              eauto with lia | ].\n          eapply putmany_of_list_zip_undef_on;\n            eauto using @undef_on_empty with typeclass_instances.\n          eapply subset_disjoint_l;\n            eauto using flatten_listonly_subset; [ ].\n          eapply disjoint_sym.\n          eapply disjoint_used_varnames_lt; eauto with lia. }\n    cbv beta in *. cleanup; subst.\n    eapply Proper_cmd; [ solve [apply Proper_call] | repeat intro | ].\n    2 : {\n      cbv [lists_reserved_with_initial_context] in *.\n      break_match_hyps; try congruence; [ ].\n      match goal with H : Some _ = Some _ |- _ =>\n                      inversion H; clear H; subst end.\n      eapply store_return_values_correct;\n        eauto using @only_differ_trans with typeclass_instances.\n      { eapply of_list_zip_undef_on; eauto.\n        rewrite of_list_app.\n        rewrite <-varname_set_args_flatten.\n        repeat match goal with\n               | |- disjoint (union _ _) _ =>\n                 apply disjoint_union_l_iff; split; auto\n               | |- disjoint _ (union _ _) =>\n                 apply disjoint_union_r_iff; split; auto\n               | |- disjoint\n                      (of_list\n                         (flatten_listonly_base_ltype _))\n                      (used_varnames _ _) =>\n                 symmetry;\n                 eapply subset_disjoint_r;\n                   [ solve [apply flatten_listonly_subset] | ]\n               end;\n          (* solvers *)\n          try match goal with\n              | |- disjoint _ (varname_set_listexcl _) =>\n                eapply subset_disjoint_r;\n                  solve [eauto using varname_set_listexcl_subset]\n              | |- disjoint (used_varnames _ _) _ =>\n                apply disjoint_used_varnames_lt; intros;\n                  solve [eauto with lia]\n              | |- disjoint _ (used_varnames _ _) =>\n                symmetry; apply disjoint_used_varnames_lt; intros;\n                  solve [eauto with lia]\n              | _ => solve [eauto using flatten_listonly_disjoint]\n              | _ => solve [symmetry; eauto using flatten_listonly_disjoint]\n              end. }\n      { eapply subset_disjoint_l; try eassumption.\n        eauto using disjoint_used_varnames_lt. } }\n\n    cbv beta in *. cleanup; subst.\n    match goal with H : list_lengths_from_value _ = _ |- _ =>\n                    rewrite H end.\n    eapply Proper_list_map;\n      [ solve [apply Proper_get]\n      | | eapply look_up_return_values; eauto;\n          apply equivalent_extract_listnames; eauto ].\n    repeat intro; cleanup; subst; eauto.\n    split; eauto.\n    split; eauto.\n\n    use_sep_assumption.\n    cancel.\n\n    repeat match goal with H : NoDup (_ ++ _) |- _ =>\n                           apply NoDup_app_iff in H end.\n    cleanup.\n\n    eapply equivalent_listonly_flat_iff1;\n      eauto 10 using @only_differ_sym, @map.only_differ_putmany,\n      @only_differ_trans with typeclass_instances; [ ].\n    repeat match goal with\n             |- disjoint (union _ _) _ =>\n             eapply disjoint_union_l_iff; split\n           | _ => rewrite <-varname_set_args_flatten\n           | _ =>\n             solve[eauto using flatten_listonly_disjoint,\n                   subset_disjoint_r, flatten_listonly_subset,\n                   disjoint_used_varnames_lt]\n           | _ =>\n             symmetry;\n               solve[eauto using flatten_listonly_disjoint,\n                     subset_disjoint_r, flatten_listonly_subset,\n                     disjoint_used_varnames_lt]\n           end.\n  Qed.\nEnd Func.\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/Func.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.2517460651641145}}
{"text": "(************************************************************************)\n(* Copyright (c) 2017-2018, Ajay Kumar Eeralla <ae266@mail.missouri.edu>*)     \n(************************************************************************)\n Require Export voting.\n (** proofs **)\n\nTheorem frame4_ind: (phi5 0 1) ~ (phi5 1 0).\nProof. repeat unfold phi5, phi4, phi3, phi2, phi1, t1, t2, t3, t4. repeat unfold t4.\n       simpl.\napply IFBRANCH_M5 with (ml1:= phi0) (ml2:=phi0).\nsimpl.       repeat unfold Avote.\napply IFBRANCH_M4 with (ml1:= phi0 ++ [bol (theta x1 A), msg (tr 0 0 3 5 7 9)]) (ml2:= phi0 ++ [ bol (theta x1 A), msg (tr 0 1 3 5 7 9)]).\nsimpl.  \napply IFBRANCH_M3 with (ml1:= phi0 ++[ bol (theta x1 A), msg (tr 0 0 3 5 7 9), bol (theta (x2t 0) B), msg (tr 1 1 4 6 8 10)])(ml2:= phi0 ++[\n  bol (theta x1 A), msg (tr 0 1 3 5 7 9), bol (theta (x2t 1) B), msg (tr 1 0 4 6 8 10)]).\napply IFBRANCH_M3 with (ml1:= phi0 ++[bol (theta x1 A), msg (tr 0 0 3 5 7 9), bol (theta (x2t 0) B), msg (tr 1 1 4 6 8 10), bol (to (x3tt 0 1)) #? A ])(ml2:= phi0 ++[bol (theta x1 A), msg (tr 0 1 3 5 7 9), bol (theta (x2t 1) B), msg (tr 1 0 4 6 8 10), bol (to (x3tt 1 0)) #? A]).\n \napply IFBRANCH_M2 with (ml1:= phi0 ++[bol (theta x1 A), msg (tr 0 0 3 5 7 9), bol (theta (x2t 0) B), msg (tr 1 1 4 6 8 10), bol (to (x3tt 0 1)) #? A, bol (acc 0 3 5 (x3tt 0 1)), msg (e 0 3 5 (x3tt 0 1) TWO 11 2) ])(ml2:= phi0 ++[bol (theta x1 A), msg (tr 0 1 3 5 7 9), bol (theta (x2t 1) B), msg (tr 1 0 4 6 8 10), bol (to (x3tt 1 0)) #? A, bol (acc 1 3 5 (x3tt 1 0)), msg (e 1 3 5 (x3tt 1 0) TWO 11 2)]).\nsimpl.\n \napply IFBRANCH_M2 with (ml1:= phi0 ++[bol (theta x1 A), msg (tr 0 0 3 5 7 9), bol (theta (x2t 0) B), msg (tr 1 1 4 6 8 10), bol (to (x3tt 0 1)) #? A, bol (acc 0 3 5 (x3tt 0 1)), msg (e 0 3 5 (x3tt 0 1) TWO 11 2), bol (to (x4ttt 0 1)) #? B ])(ml2:= phi0 ++[bol (theta x1 A), msg (tr 0 1 3 5 7 9), bol (theta (x2t 1) B), msg (tr 1 0 4 6 8 10), bol (to (x3tt 1 0)) #? A, bol (acc 1 3 5 (x3tt 1 0)), msg (e 1 3 5 (x3tt 1 0) TWO 11 2), bol (to (x4ttt 1 0)) #? B]).\nsimpl.\n\nrepeat unfold t5.\nsimpl.\nrepeat unfold mchecks, strm.\napply IFBRANCH_M1 with (ml1:= [msg A, msg B, msg M, msg C1, msg C2, msg C3, msg ONE, msg TWO, msg THREE, msg (vk 0), msg (vk 1), \n   msg (pke 2), bol (theta x1 A), msg (tr 0 0 3 5 7 9), bol (theta (x2t 0) B), msg (tr 1 1 4 6 8 10), \n   bol (to (x3tt 0 1)) #? A, bol (acc 0 3 5 (x3tt 0 1)), msg (e 0 3 5 (x3tt 0 1) TWO 11 2), bol (to (x4ttt 0 1)) #? B,\n   bol (acc 1 4 6 (x4ttt 0 1)), msg (e 1 4 6 (x4ttt 0 1) TWO 12 2)])(ml2:= [msg A, msg B, msg M, msg C1, msg C2, msg C3, msg ONE, msg TWO, msg THREE, msg (vk 0), msg (vk 1), msg (pke 2),\n  bol (theta x1 A), msg (tr 0 1 3 5 7 9), bol (theta (x2t 1) B), msg (tr 1 0 4 6 8 10), bol (to (x3tt 1 0)) #? A,\n  bol (acc 1 3 5 (x3tt 1 0)), msg (e 1 3 5 (x3tt 1 0) TWO 11 2), bol (to (x4ttt 1 0)) #? B, bol (acc 0 4 6 (x4ttt 1 0)),\n  msg (e 0 4 6 (x4ttt 1 0) TWO 12 2)]).\nsimpl.\nunfold p, d. repeat unfold e.\n\n\n\n\n\nTheorem frame8_ind: (phi8 0 1) ~ (phi8 1 0).\n Proof. unfold phi8. simpl. repeat unfold t1, t2, t3, t4, t4s, t4ss, t47, t48. repeat unfold tr. repeat unfold Avote, Bvote.\n        repeat unfold t5. repeat unfold strm. repeat unfold t61, t62, t61s, t62s, t61ss, t62ss, t71, t72, t71s, t72s. repeat unfold fintrm. repeat unfold strm.\n        apply IFBRANCH_M8 with (ml1:= phi0) (ml2:= phi0); simpl.\n        apply IFBRANCH_M7 with (ml1:= phi0 ++ [bol (theta x1 A), msg (vk 0, (b 0 3 5, s 0 3 5 7 9))]) (ml2:= (phi0++[ bol (theta x1 A), msg (vk 0, (b 1 3 5, s 1 3 5 7 9))])); simpl.  \n        apply IFBRANCH_M6 with (ml1:= phi0 ++ [ bol (theta x1 A), msg (vk 0, (b 0 3 5, s 0 3 5 7 9)), bol (theta (x2t 0) B), msg (vk 1, (b 1 4 6, s 1 4 6 8 10))]) (ml2:= phi0++ [  bol (theta x1 A), msg (vk 0, (b 1 3 5, s 1 3 5 7 9)), bol (theta (x2t 1) B), msg (vk 1, (b 0 4 6, s 0 4 6 8 10))]); simpl.\n\n    \n\n        apply IFBRANCH_M6 with (ml1:= phi0 ++ [ bol (theta x1 A), msg (vk 0, (b 0 3 5, s 0 3 5 7 9)), bol (theta (x2t 0) B), msg (vk 1, (b 1 4 6, s 1 4 6 8 10)),  bol (to (x3tt 0 1)) #? A]) (ml2:= phi0++ [  bol (theta x1 A), msg (vk 0, (b 1 3 5, s 1 3 5 7 9)), bol (theta (x2t 1) B), msg (vk 1, (b 0 4 6, s 0 4 6 8 10)), bol (to (x3tt 1 0)) #? A]); simpl. \n        apply IFBRANCH_M5 with (ml1:= phi0 ++ [ bol (theta x1 A), msg (vk 0, (b 0 3 5, s 0 3 5 7 9)), bol (theta (x2t 0) B), msg (vk 1, (b 1 4 6, s 1 4 6 8 10)),  bol (to (x3tt 0 1)) #? A,  bol (acc 0 3 5 (x3tt 0 1)), msg (e 0 3 5 (x3tt 0 1) TWO 11 2)]) (ml2:= phi0++ [  bol (theta x1 A), msg (vk 0, (b 1 3 5, s 1 3 5 7 9)), bol (theta (x2t 1) B), msg (vk 1, (b 0 4 6, s 0 4 6 8 10)), bol (to (x3tt 1 0)) #? A, bol (acc 1 3 5 (x3tt 1 0)), msg (e 1 3 5 (x3tt 1 0) TWO 11 2)]); simpl.\n \n\n        apply IFBRANCH_M5 with (ml1:= phi0 ++ [ bol (theta x1 A), msg (vk 0, (b 0 3 5, s 0 3 5 7 9)), bol (theta (x2t 0) B), msg (vk 1, (b 1 4 6, s 1 4 6 8 10)),  bol (to (x3tt 0 1)) #? A,  bol (acc 0 3 5 (x3tt 0 1)), msg (e 0 3 5 (x3tt 0 1) TWO 11 2), bol (to (x4ttt 0 1)) #? B]) (ml2:= phi0++ [  bol (theta x1 A), msg (vk 0, (b 1 3 5, s 1 3 5 7 9)), bol (theta (x2t 1) B), msg (vk 1, (b 0 4 6, s 0 4 6 8 10)), bol (to (x3tt 1 0)) #? A, bol (acc 1 3 5 (x3tt 1 0)), msg (e 1 3 5 (x3tt 1 0) TWO 11 2), bol (to (x4ttt 1 0)) #? B]); simpl.\n \n        apply IFBRANCH_M4 with (ml1:= phi0 ++ [ bol (theta x1 A), msg (vk 0, (b 0 3 5, s 0 3 5 7 9)), bol (theta (x2t 0) B), msg (vk 1, (b 1 4 6, s 1 4 6 8 10)),  bol (to (x3tt 0 1)) #? A,  bol (acc 0 3 5 (x3tt 0 1)), msg (e 0 3 5 (x3tt 0 1) TWO 11 2), bol (to (x4ttt 0 1)) #? B,  bol (acc 1 4 6 (x4ttt 0 1)), msg (e 1 4 6 (x4ttt 0 1) TWO 12 2)]) (ml2:= phi0++ [  bol (theta x1 A), msg (vk 0, (b 1 3 5, s 1 3 5 7 9)), bol (theta (x2t 1) B), msg (vk 1, (b 0 4 6, s 0 4 6 8 10)), bol (to (x3tt 1 0)) #? A, bol (acc 1 3 5 (x3tt 1 0)), msg (e 1 3 5 (x3tt 1 0) TWO 11 2), bol (to (x4ttt 1 0)) #? B,  bol (acc 0 4 6 (x4ttt 1 0)), msg (e 0 4 6 (x4ttt 1 0) TWO 12 2)]); simpl.\n\n        \n        apply IFBRANCH_M3 with (ml1:= phi0 ++ [ bol (theta x1 A), msg (vk 0, (b 0 3 5, s 0 3 5 7 9)), bol (theta (x2t 0) B), msg (vk 1, (b 1 4 6, s 1 4 6 8 10)),  bol (to (x3tt 0 1)) #? A,  bol (acc 0 3 5 (x3tt 0 1)), msg (e 0 3 5 (x3tt 0 1) TWO 11 2), bol (to (x4ttt 0 1)) #? B,  bol (acc 1 4 6 (x4ttt 0 1)), msg (e 1 4 6 (x4ttt 0 1) TWO 12 2),  bol (mchecks x5t 0 1 TWO),\n   msg (shufl (p 1 (x5t 0 1)) (p 2 (x5t 0 1)) (p 3 (x5t 0 1)))]) (ml2:= phi0++ [  bol (theta x1 A), msg (vk 0, (b 1 3 5, s 1 3 5 7 9)), bol (theta (x2t 1) B), msg (vk 1, (b 0 4 6, s 0 4 6 8 10)), bol (to (x3tt 1 0)) #? A, bol (acc 1 3 5 (x3tt 1 0)), msg (e 1 3 5 (x3tt 1 0) TWO 11 2), bol (to (x4ttt 1 0)) #? B,  bol (acc 0 4 6 (x4ttt 1 0)), msg (e 0 4 6 (x4ttt 1 0) TWO 12 2), bol (mchecks x5t 1 0 TWO),\n                                                                                  msg (shufl (p 1 (x5t 1 0)) (p 2 (x5t 1 0)) (p 3 (x5t 1 0)))]); simpl. \n\n           apply IFBRANCH_M3 with (ml1:= phi0 ++ [ bol (theta x1 A), msg (vk 0, (b 0 3 5, s 0 3 5 7 9)), bol (theta (x2t 0) B), msg (vk 1, (b 1 4 6, s 1 4 6 8 10)),  bol (to (x3tt 0 1)) #? A,  bol (acc 0 3 5 (x3tt 0 1)), msg (e 0 3 5 (x3tt 0 1) TWO 11 2), bol (to (x4ttt 0 1)) #? B,  bol (acc 1 4 6 (x4ttt 0 1)), msg (e 1 4 6 (x4ttt 0 1) TWO 12 2),  bol (mchecks x5t 0 1 TWO),\n   msg (shufl (p 1 (x5t 0 1)) (p 2 (x5t 0 1)) (p 3 (x5t 0 1))),  bol (theta21 x6t A 0 1)]) (ml2:= phi0++ [  bol (theta x1 A), msg (vk 0, (b 1 3 5, s 1 3 5 7 9)), bol (theta (x2t 1) B), msg (vk 1, (b 0 4 6, s 0 4 6 8 10)), bol (to (x3tt 1 0)) #? A, bol (acc 1 3 5 (x3tt 1 0)), msg (e 1 3 5 (x3tt 1 0) TWO 11 2), bol (to (x4ttt 1 0)) #? B,  bol (acc 0 4 6 (x4ttt 1 0)), msg (e 0 4 6 (x4ttt 1 0) TWO 12 2), bol (mchecks x5t 1 0 TWO),\n                                                                                                            msg (shufl (p 1 (x5t 1 0)) (p 2 (x5t 1 0)) (p 3 (x5t 1 0))), bol (theta21 x6t A 1 0)]); simpl.\n           \n \n            apply IFBRANCH_M2 with (ml1:= phi0 ++ [bol (theta x1 A), msg (vk 0, (b 0 3 5, s 0 3 5 7 9)), bol (theta (x2t 0) B), msg (vk 1, (b 1 4 6, s 1 4 6 8 10)),  bol (to (x3tt 0 1)) #? A,  bol (acc 0 3 5 (x3tt 0 1)), msg (e 0 3 5 (x3tt 0 1) TWO 11 2), bol (to (x4ttt 0 1)) #? B,  bol (acc 1 4 6 (x4ttt 0 1)), msg (e 1 4 6 (x4ttt 0 1) TWO 12 2),  bol (mchecks x5t 0 1 TWO),\n   msg (shufl (p 1 (x5t 0 1)) (p 2 (x5t 0 1)) (p 3 (x5t 0 1))),  bol (theta21 x6t A 0 1),  bol (acc1 0 1 3 5) & (bcheck (c 0 3) (x6t 0 1)), msg (e1 0 3 x6t 1 13)]) (ml2:= phi0++ [bol (theta x1 A), msg (vk 0, (b 1 3 5, s 1 3 5 7 9)), bol (theta (x2t 1) B), msg (vk 1, (b 0 4 6, s 0 4 6 8 10)), bol (to (x3tt 1 0)) #? A, bol (acc 1 3 5 (x3tt 1 0)), msg (e 1 3 5 (x3tt 1 0) TWO 11 2), bol (to (x4ttt 1 0)) #? B,  bol (acc 0 4 6 (x4ttt 1 0)), msg (e 0 4 6 (x4ttt 1 0) TWO 12 2), bol (mchecks x5t 1 0 TWO),\n                                                                                  msg (shufl (p 1 (x5t 1 0)) (p 2 (x5t 1 0)) (p 3 (x5t 1 0))), bol (theta21 x6t A 1 0), bol (acc1 1 0 3 5) & (bcheck (c 1 3) (x6t 1 0)), msg (e1 1 3 x6t 0 13)]); simpl.\n \n\n                 apply IFBRANCH_M2 with (ml1:= phi0 ++ [bol (theta x1 A), msg (vk 0, (b 0 3 5, s 0 3 5 7 9)), bol (theta (x2t 0) B), msg (vk 1, (b 1 4 6, s 1 4 6 8 10)),  bol (to (x3tt 0 1)) #? A,  bol (acc 0 3 5 (x3tt 0 1)), msg (e 0 3 5 (x3tt 0 1) TWO 11 2), bol (to (x4ttt 0 1)) #? B,  bol (acc 1 4 6 (x4ttt 0 1)), msg (e 1 4 6 (x4ttt 0 1) TWO 12 2),  bol (mchecks x5t 0 1 TWO),\n   msg (shufl (p 1 (x5t 0 1)) (p 2 (x5t 0 1)) (p 3 (x5t 0 1))),  bol (theta21 x6t A 0 1),  bol (acc1 0 1 3 5) & (bcheck (c 0 3) (x6t 0 1)), msg (e1 0 3 x6t 1 13),  bol (theta21 x7t B 0 1)]) (ml2:= phi0++ [bol (theta x1 A), msg (vk 0, (b 1 3 5, s 1 3 5 7 9)), bol (theta (x2t 1) B), msg (vk 1, (b 0 4 6, s 0 4 6 8 10)), bol (to (x3tt 1 0)) #? A, bol (acc 1 3 5 (x3tt 1 0)), msg (e 1 3 5 (x3tt 1 0) TWO 11 2), bol (to (x4ttt 1 0)) #? B,  bol (acc 0 4 6 (x4ttt 1 0)), msg (e 0 4 6 (x4ttt 1 0) TWO 12 2), bol (mchecks x5t 1 0 TWO),\n                                                                                  msg (shufl (p 1 (x5t 1 0)) (p 2 (x5t 1 0)) (p 3 (x5t 1 0))), bol (theta21 x6t A 1 0), bol (acc1 1 0 3 5) & (bcheck (c 1 3) (x6t 1 0)), msg (e1 1 3 x6t 0 13), bol (theta21 x7t B 1 0)]); simpl.\n\n           apply IFBRANCH_M1 with (ml1:= phi0 ++ [bol (theta x1 A), msg (vk 0, (b 0 3 5, s 0 3 5 7 9)), bol (theta (x2t 0) B), msg (vk 1, (b 1 4 6, s 1 4 6 8 10)),  bol (to (x3tt 0 1)) #? A,  bol (acc 0 3 5 (x3tt 0 1)), msg (e 0 3 5 (x3tt 0 1) TWO 11 2), bol (to (x4ttt 0 1)) #? B,  bol (acc 1 4 6 (x4ttt 0 1)), msg (e 1 4 6 (x4ttt 0 1) TWO 12 2),  bol (mchecks x5t 0 1 TWO),\n   msg (shufl (p 1 (x5t 0 1)) (p 2 (x5t 0 1)) (p 3 (x5t 0 1))),  bol (theta21 x6t A 0 1),  bol (acc1 0 1 3 5) & (bcheck (c 0 3) (x6t 0 1)), msg (e1 0 3 x6t 1 13),  bol (theta21 x7t B 0 1), bol (acc1 0 1 4 6) & (bcheck (c 1 4) (x7t 0 1)), msg (e1 0 4 x7t 1 14)]) (ml2:= phi0++ [bol (theta x1 A), msg (vk 0, (b 1 3 5, s 1 3 5 7 9)), bol (theta (x2t 1) B), msg (vk 1, (b 0 4 6, s 0 4 6 8 10)), bol (to (x3tt 1 0)) #? A, bol (acc 1 3 5 (x3tt 1 0)), msg (e 1 3 5 (x3tt 1 0) TWO 11 2), bol (to (x4ttt 1 0)) #? B,  bol (acc 0 4 6 (x4ttt 1 0)), msg (e 0 4 6 (x4ttt 1 0) TWO 12 2), bol (mchecks x5t 1 0 TWO),\n                                                                                                                                                                                                                                                                                     msg (shufl (p 1 (x5t 1 0)) (p 2 (x5t 1 0)) (p 3 (x5t 1 0))), bol (theta21 x6t A 1 0), bol (acc1 1 0 3 5) & (bcheck (c 1 3) (x6t 1 0)), msg (e1 1 3 x6t 0 13), bol (theta21 x7t B 1 0), bol (acc1 1 0 4 6) & (bcheck (c 0 4) (x7t 1 0)), msg (e1 1 4 x7t 0 14)]); simpl.\n\n\n       unfold mchecks, theta21. unfold d.", "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/votingProofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2517460598792441}}
{"text": "(*\ndate: 04/09/2018\nauthor: Teng Zhang\n*)\n\n(*definition of semantic rules*)\n\nRequire Import\n  Coq.Strings.String\n  Coq.Lists.List\n  Coq.Bool.Bool\n  Coq.Vectors.Vector\n  Coq.ZArith.ZArith\n  Coq.ZArith.Zdigits\n  Coq.QArith.QArith_base\n  Coq.QArith.Qabs\n  Coq.FSets.FMapList\n  Coq.FSets.FMapFacts\n  Coq.Init.Notations\n  Coq.omega.Omega.\n\nRequire Import Coq.Sorting.Permutation.\nRequire Export SmedlAST_submission.\nRequire Export SMEDL_helper.\n\nSet Implicit Arguments.\nSet Boolean Equality Schemes.\n\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nGeneralizable All Variables.\n\nRequire Import Coq.Strings.Ascii.\n\nSection semantic_rule.\n\n(*from state of the state machine and the event instance, get the current step*)\n  Definition stepStateMap := (scenario_state*event_instance)->option step.\n  \n  Definition stepStateMap' := (scenario_state*event_instance*scenario)->option (step).\n  \n(*construct stepStateMap*)\nDefinition update_stepStateMap (map: stepStateMap) (key: scenario_state*event_instance) (value: option step): stepStateMap :=\nfun (key':scenario_state*event_instance) => if string_dec (fst key') (fst key) \n                                                                          then if event_instance_dec (snd key') (snd key) \n                                                                                     then value \n                                                                                  else map key' \n                                                                       else map key'.\n\n\n(*given scenario state and event definition, return corresponding list of event_instances*)\nDefinition transitionEventMap := (option scenario_state* option event_definition) -> list event_instance.\n(*construct transtionCondtionMap*)\nDefinition update_transitionEventMap (map:transitionEventMap) (key:option scenario_state* option event_definition) (value: event_instance) : transitionEventMap :=\nfun (key': option scenario_state*option event_definition) => \nmatch fst key', snd key', fst key, snd key with\n| Some fk',Some sk', Some fk,Some sk => if string_dec (fk') (fk) \n                                 then if  string_dec (eventId (sk)) (eventId (sk')) \n                                                  then value::(map key) \n                                          else map key'\n                         else map key'\n| _,_,_,_ =>map key'\nend.\n\n(*map from state to its possible triggering event*)\nDefinition stateEventDefMap := option scenario_state -> list event_definition.\nDefinition update_stateEventDefMap (map:stateEventDefMap) (key:option scenario_state) (ev: event_definition) : stateEventDefMap :=\nfun (key': option scenario_state) => match key' with\n                                                        | None => nil\n                                                        | Some s => match key with\n                                                                            | None => nil\n                                                                            | Some s' => if string_dec s s' then ev::(map (key')) else map key'\n                                                                            end\n                                                        end\n.\n\n\nPrint object.\nPrint find. \n\nDefinition getStepFromMap (mon:object) (e:scenario_state*event_instance) : option step\n  := match find (fun (x:(scenario_state * event_instance * option step)) => if string_dec (fst (fst x)) (fst e)\n                               then\n                                 if (event_instance_dec (snd (fst x)) (snd e))\n                                 then\n                                   true\n                                 else\n                                   false\n                               else\n                                 false\n                ) (stateEvStepMap mon) with\n     | Some (s, ei, x) => x\n     | None => None\n     end. \n\n\n(*environment*)\n(*scenario_state -> list event_definition*)\nParameter stEvMap: stateEventDefMap.\n(*scenario_state*event_definition -> list event_instance*)\nParameter transEvMap : transitionEventMap.\n(*scenario_state*event_instance -> option step*)\nParameter stpStMap': stepStateMap'.\nParameter stpStMap: stepStateMap. \nParameter eventList: list event_definition. \n \n(*data structure*)\n\n(*used in configuration*)\n(*data structure to represent the event raised*)\n(*pathE*)\n\nDefinition monitor : Set := object.\n\n(*current state of the monitor*)\nRecord configuration (M : monitor) : Type :={\n  datastate : value_env;\n  controlstate : scenario_env; \n  raisedevents :  list raisedEvent; (*all raised events, removed after being handled*)\n  exportedevents: list raisedEvent; (*only for exported events*)\n  finishedscenarios: list scenario;(*no change, using more strict definition*)\n  sceEventMap: list (scenario*event_definition);\n}.\n\nDefinition sceEventMap_dec (n m : list (scenario*event_definition)) : {n = m} + { n <> m}.\nProof. pose proof scenario_dec. pose proof event_definition_dec. repeat decide equality.  \nQed.\n\n\n\nDefinition configuration_dec {M : monitor} (n m : configuration M) : {n = m} + { n <> m}.\nProof. pose proof expr_eq_dec. repeat decide equality.  \nQed. \n\nDefinition scenarioInclusion `(conf: configuration M) : Prop:=\nincl  (finishedscenarios conf) (dom (controlstate conf)).\n\n\n(*we assume that state update only updates state variables so that domain of (datastate conf) will never change, meaning \nuniq (datastate conf) always holds\nAnother assumption is that the update will follow the typechecking rule of normal programming languages*)\n\nInductive evnConsist : typ_env -> value_env -> Prop :=\n| e_con_base: evnConsist nil nil\n| e_con_ind: forall n (ty:typ) v te ev, evnConsist te ev -> evnConsist (((AIdent n),ty)::te) (((AIdent n),(ty,v))::ev).\n\nDefinition tyEnvPair (t:typ) (r:range_typ) :=\n      match (t,r) with\n        | (Int, (inl (inl (inl (inl _))))) => True\n        | (Float, (inl (inl (inl (inr _))))) => True\n        | (Str, (inl (inl (inr _)))) => True\n        | (Bool, (inl (inr _))) => True\n        | (Pointer, (inr _)) => True\n        | (Thread, (inr _)) => True\n        | (Opaque, (inr _)) => True                         \n        | _ => False\n      end.            \n\nInductive tyEnv: value_env -> Prop :=\n| ty_base: tyEnv nil\n| ty_ind: forall n t r ve, tyEnv ve -> tyEnvPair t r -> tyEnv (((AIdent n),(t,r))::ve).\n                                                             \nLemma tyEnvApp: forall v1 v2,\n    tyEnv v1 ->\n    tyEnv v2 ->\n    tyEnv (v1++v2).\nProof. \n  intro v1;induction v1.\n  -\n    intros. simpl. \n    auto. \n  -\n    intros.\n    SearchAbout app.\n    rewrite <- app_comm_cons.\n    \n    inversion H; subst.\n    apply ty_ind;auto. \nQed.\n\nLemma valConsist: forall env t_env   s ty,\n    evnConsist t_env env ->\n    tyEnv env ->\n    HasTy t_env (EAtom (AIdent s)) ty ->\n    (exists v, In (AIdent s, (ty, v)) env).\nProof.\n  intro env;induction env.\n  -  intros. inversion H. subst. inversion H1.\n     subst. SearchAbout find. apply find_some in H3.\n     destruct H3. inversion H2.\n  - intros.\n    inversion H;inversion H0;subst.\n    inversion H1.\n    subst. simpl.\n    inversion H6;subst. simpl in H3.\n    destruct (atom_eq_dec (AIdent n) (AIdent s)). inversion e;subst.\n    inversion H3;subst. exists v;left;auto.\n    assert (exists v0 : range_typ, In (AIdent s, (ty, v0)) env).\n    apply IHenv with (t_env:=te);auto.\n    apply HasTy_Var;auto.\n    destruct H2. exists x;right;auto. \nQed.\n\nLemma domIn: forall (A B:Type) (s:A) (x:B) env,\nIn  (s,x) env ->\nIn s (dom env).\nProof. intros.\ngeneralize dependent s. \ngeneralize dependent x.\ninduction env;intros.\n- inversion H.\n- destruct H. rewrite H. left;auto.\nsimpl. right. apply IHenv with (x:=x). auto.\nQed.\n\nLemma  getValueIn: forall ds s v t,  uniqList (dom ds) -> In ((AIdent s), (t, v)) (ds) -> getValue (AIdent s) ds = Some v.\nProof. intros. \ninduction ds. inversion H0. \nsimpl. destruct a;auto.\nsimpl. destruct p;auto. \n \ndestruct (atom_eq_dec (AIdent s) a).\nsubst.  inversion H;subst. simpl in H0. destruct H0.\ninversion H0;auto. apply domIn in H0.  contradiction.\napply IHds. inversion H;auto. simpl in H0.\ndestruct H0. inversion H0;subst. contradiction. \nauto. \nQed.\n\nLemma tyEnvIn: forall ve s ty x,\n    In (AIdent s, (ty, x)) ve ->\n    tyEnv ve ->\n    tyEnvPair ty x. \nProof. intro ve. \n  induction ve;intros. \n- inversion H. \n- inversion H0;subst.\n  inversion H. inversion H1;subst. \n  auto.   \n  apply IHve with (s:=s);auto. \nQed.\n\nCheck dom.\n\n\n\nRecord correct_configuration `(conf: configuration M) : Prop :={\n(*ds_uniq: uniq (datastate conf);*)\n(*ds_type_check : forall prod, In prod (datastate conf) -> typeCheck prod;*)\ncs_non_empty: dom (controlstate conf)<> nil;\nsce_state_no_empty: forall sce, In sce (dom (controlstate conf)) -> getScenarioState sce (controlstate conf) <> None;\nfinish_uniq: uniqList (finishedscenarios conf);\ncs_dom_uniq: uniqList (dom (controlstate conf));\ninclusion: scenarioInclusion conf;\ncorrect_mon : correct_object M;\nds_tyEnv:tyEnv (datastate conf);\nraise_in: (forall e, In e (raisedevents conf) -> In (eventDefinition e) (events M));\n(*export_in: (forall e, In e (exportedevents conf) -> In (eventDefinition e) (events (monitor_obj conf)));*)\ncs_consist: dom (controlstate conf) = (scenarios M);\n(*cs_state_consist: forall sce st e0 s0, In (sce,st) (controlstate conf) -> In (st, e0, Some s0) (stateEvStepMap (monitor_obj conf)) -> (In s0 (traces sce) /\\  (pre_state s0 = st));\ncs_state_consist': forall sce st e0 s0,  In st (sceStateRelation sce) -> In (st, e0, Some s0) (stateEvStepMap (monitor_obj conf)) -> (In s0 (traces sce) /\\  (pre_state s0 = st));\nsce_state_in: forall sce st, In (sce,st) (controlstate conf) -> In st (sceStateRelation sce);*)\nds_dom_eq: (dom2 (datastate conf)) = ((dsmon M));\nds_consist: evnConsist (dsmon M) (datastate conf);\nraised_wellform': forall e,  In e (raisedevents conf) ->\n                             wellFormedRaisedEvent e;\nraisedType: forall re, In re (raisedevents conf) -> eventKind (eventDefinition re) = Internal \\/ eventKind (eventDefinition re) = Imported;\nsceStateCorrect: forall sce s, In (sce,s) (controlstate conf) -> In (sce, s) (stateScenarioMap M);\nsceEventMapRange : Permutation (dom (sceEventMap conf)) (finishedscenarios conf);\nsceEventMapAlphabet:  forall sce e, In (sce,e) (sceEventMap conf) -> In e (alphabet sce);\nraise_in_finished: forall sce e,  In (sce,e) (sceEventMap conf) -> In e (events M);\nraisedType_finished: forall sce e, In (sce,e) (sceEventMap conf)-> eventKind e = Internal \\/ eventKind e = Imported;\n(*ds_ty_eq: (forall n t1 t2, In (n,t1) (dom2 (datastate conf)) -> (In (n,t2) ( (dsmon (monitor_obj conf)))) -> t1 = t2)*)\n(*sceEventMapRange:  dom (sceEventMap conf) = (finishedscenarios conf);*)\n                                                            }.\n\n\n\n\nDefinition importEventBool (ev:event_definition) : bool := \nif  (eventKind_dec (eventKind ev) Imported) then true else  false.\n\nPrint transitionEventMap.\nPrint object.\n\nDefinition op_string_dec (n m : option string) : {n = m} + { n <> m}.\nProof.  destruct n. destruct m. pose proof string_dec.\n        destruct H with (s1:=s) (s2:=s0).   left;auto. rewrite e ;auto. \n        right. unfold not. intros. inversion H0. contradiction.\n        right. unfold not. intros. inversion H.\n        destruct m.\n        right. unfold not. intros. inversion H.\n        left;auto. \nDefined.\n\n\nDefinition op_event_definition_dec (n m : option event_definition) : {n = m} + { n <> m}.\nProof.\n  destruct n;destruct m.\n  pose proof event_definition_dec.\n  destruct H with (n:=e) (m:=e0);auto. left. rewrite e1;auto. \n  right. unfold not. intros. inversion H0. contradiction.\n  right. unfold not. intros. inversion H.\n  right. unfold not;intros;inversion H. left;auto. \n \nDefined. \n\nFixpoint transEvMapFunc \n          (l : list  (option scenario_state * option event_definition *\n                      list event_instance)) (f: (option scenario_state * option event_definition)) :  option (list event_instance) :=\n  match l with\n  | nil => None\n  | ((a, b),c) :: l' => if op_string_dec a (fst f) then\n                          if op_event_definition_dec b (snd f) then\n                            Some c\n                          else\n                            transEvMapFunc l' f\n                        else\n                          transEvMapFunc l' f\n  end.\n\nFixpoint transEvMapFunc' \n          (l : list  (option scenario_state * option event_definition *\n                      list event_instance)) (f: (option scenario_state * option event_definition)) :   (list event_instance) :=\n  match l with\n  | nil => nil\n  | ((a, b),c) :: l' => if op_string_dec a (fst f) then\n                          if op_event_definition_dec b (snd f) then\n                             c\n                          else\n                            transEvMapFunc' l' f\n                        else\n                          transEvMapFunc' l' f\n  end. \n\nPrint object.\n\nDefinition transEvMapFuncMon (mon: object)\n          (f: (option scenario_state * option event_definition)) :  option (list event_instance) :=\n    transEvMapFunc (stateEvDefInstanceMap mon) f. \n\nPrint dom2.\n\n\n\nLemma stateEvDefInstanceMapEquiv' : forall (l : list  (option scenario_state * option event_definition *\n                      list event_instance)),\n  uniqList (dom l) ->  (forall st ev eList, In (Some st, Some ev, eList) l\n                       <-> transEvMapFunc l (Some st, Some ev) = Some eList). \nProof.\n  intro l;induction l.   \n  - split.  intros. \n     inversion H0.     intros. simpl in H0. inversion H0. \n  - intros.\n    simpl in H.\n    split;intros.\n    inversion H0. subst. \n    simpl. \n    simpl in *.\n    \n    destruct (string_dec st st);auto. Focus 2. contradiction.\n    destruct (event_definition_dec ev ev). Focus 2. contradiction. auto. \n    (*Check eq_rec_r. \n    destruct (eq_rec_r (fun s : string => {Some s = Some st} + {Some s <> Some st}) (left eq_refl) e).\n    Focus 2. contradiction.\n    destruct (eq_rec_r (fun s : string => {Some s = Some st} + {Some s <> Some st}) (left eq_refl)).   Focus 2. contradiction. \n    \n    destruct (op_string_dec (Some st) (Some st)).\n    destruct (op_event_definition_dec (Some ev) (Some ev)).\n     auto.     \n     contradiction.\n     contradiction.*)\n    \n     simpl.\n     destruct a. destruct p.\n     destruct (op_string_dec o (Some st)).\n     subst.\n     destruct (op_event_definition_dec o0 (Some ev)).\n     simpl in H. inversion H;subst.\n     SearchAbout dom.\n     apply domIn in H1. contradiction. apply IHl;auto. inversion H;subst. auto.\n     apply IHl;auto. inversion H;subst. auto.\n     simpl in *.\n     destruct a;destruct p.\n     destruct (op_string_dec o (Some st)).\n     destruct (op_event_definition_dec o0 (Some ev)).\n     subst. \n     simpl in H. inversion H0;subst. left;auto.\n     subst. apply IHl in H0. right;auto.\n     inversion H;subst;auto.\n     apply IHl in H0. right;auto.\n     inversion H;subst;auto.\nQed.\nPrint object.\nPrint stepStateMap'.\n\nDefinition op_stpMap_dec (n m :  (scenario_state * event_instance * scenario)) : {n = m} + { n <> m}.\nProof.\n  destruct n;destruct m. destruct p;destruct p0.\n  pose proof string_dec. pose proof event_instance_dec.\n  pose proof scenario_dec.\n  destruct H with (s1:=s1) (s2:=s2); destruct H0 with (n:=e) (m:=e0); destruct H1 with (n:=s) (m:=s0);auto. left. rewrite e1;rewrite e2;rewrite e3;auto. right. unfold not. intros.\n  inversion H2. contradiction.\nright. unfold not. intros.\ninversion H2. contradiction.\nright. unfold not. intros.\ninversion H2. contradiction.\nright. unfold not. intros.\ninversion H2. contradiction.\nright. unfold not. intros.\ninversion H2. contradiction.\nright. unfold not. intros.\ninversion H2. contradiction.\nright. unfold not. intros.\n  inversion H2. contradiction.\nDefined. \n\nFixpoint stpStpMapFunc (l : list (scenario_state * event_instance * scenario * option step))\n         (f: (scenario_state * event_instance * scenario)) : option step :=\n  match l with\n |  nil => None\n | (a,d)::l' => if op_stpMap_dec a f then\n                  d\n                else\n                  stpStpMapFunc l' f\n end. \n\nPrint object. \n  \nDefinition stpStpMapFuncMon (mon: object)\n          (f: (scenario_state * event_instance * scenario)) :  option step :=\n    stpStpMapFunc (stateEvStepMap'  mon) f. \n                                                               \nLemma stpStMapEquivLem: forall l,\n  uniqList (dom l) -> (forall st ei stp sce, In (st,ei,sce,Some stp) l <-> stpStpMapFunc l (st, ei,sce) = Some stp).\nProof.\n  intro l;induction l.   \n- split;intros. \n  inversion H0. simpl in H0. \n  inversion H0. \n-\n  split;intros.\n  simpl in H0.\n  destruct H0;subst.\n  simpl.\n  destruct (string_dec st st). destruct (event_instance_dec ei ei ).\n  destruct (scenario_dec sce sce ). auto. contradiction. contradiction. contradiction. \n (* destruct (op_stpMap_dec (st, ei, sce) (st, ei, sce)). auto. \n  contradiction.*)   \n  inversion H;subst. \n  destruct a. simpl in *. \n  destruct (op_stpMap_dec p (st, ei, sce)).\n  subst.\n  inversion H;subst.\n  apply domIn in H0. contradiction. \n  apply IHl;auto.\n  simpl in *.\n  destruct a.\n  subst.\n  destruct (op_stpMap_dec p (st, ei, sce)).\n  subst. left;auto. \n  apply IHl in H0. right;auto. \n  inversion H;subst;auto.   \nQed.\n\nFixpoint getEventInstances' (ev:event_definition) (sce_env: scenario_env) (sceList: list scenario) (l : list  (option scenario_state * option event_definition *\n                      list event_instance)): list event_instance :=\nmatch sce_env with\n| nil => nil\n| (s,state)::env'=>   if inList scenario_dec s (sceList)  then \n                                (getEventInstances' ev env' sceList l) \n                      else\n                        match (transEvMapFunc l (Some state, Some ev)) with\n                        | None => (getEventInstances' ev env' sceList l)\n                        | Some l' => \n                          mergeList' l' (getEventInstances' ev env' sceList l) (event_instance_dec)\n                       end\nend. \n\n\nDefinition getEventInstances (ev:event_definition) `(conf: configuration M) (l : list  (option scenario_state * option event_definition *\n                      list event_instance)) : list event_instance :=\ngetEventInstances' ev (controlstate conf) (finishedscenarios conf) l.\n\n\n(*get all variables from an expression*)\nFixpoint getVariables (e:expr) : list atom :=\nmatch e with\n| EOr x y => mergeList' (getVariables x) (getVariables y) (atom_eq_dec)\n| EAnd x y => mergeList' (getVariables x) (getVariables y) (atom_eq_dec)\n| EEq x y  => mergeList' (getVariables x) (getVariables y) (atom_eq_dec)\n| ELt x y => mergeList' (getVariables x) (getVariables y) (atom_eq_dec)\n| ELe x y => mergeList' (getVariables x) (getVariables y) (atom_eq_dec)\n| EPlus x y => mergeList' (getVariables x) (getVariables y) (atom_eq_dec)\n| EMult x y => mergeList' (getVariables x) (getVariables y) (atom_eq_dec)\n| EDiv x y => mergeList' (getVariables x) (getVariables y) (atom_eq_dec)\n| EMod x y => mergeList' (getVariables x) (getVariables y) (atom_eq_dec)\n| ENot x => getVariables x\n| EAtom x => match x with \n                     | AIdent i => (AIdent i)::nil\n                     | _ => nil\n                     end           \nend.\n\nFixpoint getUpdated (a:  action) : list atom :=\nmatch a with\n| StateUpdate (LExp (AIdent s)) ex =>  (AIdent s)::nil\n| Seq a1 a2 => let r1 := getUpdated a1 in\n                 let r2 :=  getUpdated a2 in\n                 mergeList' r1 r2 (atom_eq_dec)\n| _ => nil                            \nend.\n\nFixpoint getVarsFromExprList (lst: list expr): list atom := \nmatch lst with\n| nil => nil\n| e::lst' => mergeList' (getVariables e) (getVarsFromExprList  lst') (atom_eq_dec)   \nend.\n\n\nFixpoint getUsedFromActions (a: action) : list atom :=\n  match a with\n  | StateUpdate (LExp (AIdent s)) ex => (getVariables ex)\n                                                   \n  | RaiseStmt n lst =>  (getVarsFromExprList lst)                     \n  | Seq a1 a2 => let r1 := getUsedFromActions a1 in\n                 let r2 :=  getUsedFromActions a2 in\n                 mergeList' r1 r2 (atom_eq_dec)\n  | _ => nil                         \n  end.                         \n        \n\n \n \n\nDefinition getUpdatedVariablesFromScenario `(conf:configuration M) (stp:step)  : list atom\n:= filterListReverse (dom (datastate conf)) (getUpdated (stepActions stp)) (atom_eq_dec).\n\nDefinition getUsedVariablesFromScenario `(conf:configuration M) (stp:step)  : list atom\n:= \nfilterListReverse (dom (datastate conf)) (mergeList' (getVariables (eventWhenExpr (stepEvent stp))) (getUsedFromActions (stepActions stp)) (atom_eq_dec)) (atom_eq_dec)\n.\n\n\nDefinition getStep  `(conf: configuration M) (sce: scenario) (e: event_instance) : option step := \nmatch getScenarioState sce (controlstate conf) with\n| None => None\n| Some s =>  stpStMap (s,e)\nend.\n\n(*Definition getStep'  `(conf: configuration M) (sce: scenario) (e: event_instance) : option (step) := \nmatch getScenarioState sce (controlstate conf) with\n| None => None\n| Some s =>  stpStMap' (s,e,sce)                      \nend.*)\nPrint object.\n\nDefinition getStep'  `(conf: configuration M) (sce: scenario) (e: event_instance) : option (step) := \nmatch getScenarioState sce (controlstate conf) with\n| None => None\n| Some s =>  stpStpMapFunc (stateEvStepMap' M) (s,e,sce)                      \nend.\n\nDefinition getStep''  `(conf: configuration M) (sce: scenario) (e: event_instance) : option step := \nmatch getScenarioState sce (controlstate conf) with\n| None => None\n| Some s =>  getStepFromMap M (s,e)\nend.\n\n(*Definition stpStMapEquiv (mon:object) :=\n  (forall st ei stp, In (st,ei,Some stp) (stateEvStepMap mon) <-> stpStMap (st, ei) = Some stp).*)\n\n\n\n\n  (*uniqList (dom2 (stateEvStepMap mon))*)\n  (* destruct ((stateEvStepMap mon)). inversion H.\n         simpl.\n         simpl in H.\n         destruct H. rewrite H. \n         simpl. destruct (string_dec st st).\n         destruct (event_instance_dec ei ei). auto.\n         contradiction. contradiction.\n         \n         Print getStepFromMap.\n         *)\n\nLocal Open Scope Z_scope.\nLocal Open Scope string_scope.\n\n\n\n\n\n\n\n(*(a: atom) (t: typ) (v: range_typ) (en:value_env):*)\n(*Fixpoint getValue (a: atom) (en:value_env) : option range_typ :=*)\n(*semantics function*)\n(*assume that n will be in the set of state variables*)\nPrint value_env.\nPrint typ_env.\n\n\n\n\nFixpoint updateDataState (ven:value_env) (lst: list atom) : value_env :=\nmatch ven with\n| nil =>  nil\n| (a,v)::ven' => if (inList atom_eq_dec a (lst)) then (a,v)::(updateDataState ven' lst) else (updateDataState ven' lst)\nend. \n\nDefinition updateControlState (cs:scenario_env) (sce: scenario) (stp: step) :scenario_env := \nupdateScenarioState' sce (pro_state stp) cs.\n\n \n\nFixpoint removeEvent' (re : raisedEvent) (lst : list raisedEvent) : list raisedEvent :=\nmatch lst with\n| nil => nil\n| re' :: lst' => if raisedEvent_dec re re' then removeEvent' re lst' else re'::(removeEvent' re lst')\nend. \n\n\n(*update configuration*)\nPrint configuration.\n\nDefinition configTransition  (env:value_env) (re:raisedEvent) (e:event_instance) (sce : scenario) (stp: step) `(conf: configuration M) : @ErrorOrResult (configuration M) := \nmatch (execAction (env,nil) (stepActions stp) (filter\n             (fun e : event_definition =>\n              match eventKind e with\n              | Internal => true\n              | Imported => false\n              | Exported => true\n              end) (events M))) with\n| Error s => Error s\n| Result (ds',res) => let ds'':= updateDataState ds' (dom (datastate conf)) in\n                      Result ({|\ndatastate := ds'';\ncontrolstate := updateControlState (controlstate conf) sce stp;\n(*raisedevents := app (filter (fun re => EventKind_beq (eventKind (eventDefinition re)) Internal) res) (removeEvent' re ((raisedevents) conf));\nexportedevents := app (filter (fun re => EventKind_beq (eventKind (eventDefinition re)) Exported) res) (exportedevents conf);*)\nraisedevents :=  (filter (fun re => EventKind_beq (eventKind (eventDefinition re)) Internal) res) ;\nexportedevents := (filter (fun re => EventKind_beq (eventKind (eventDefinition re)) Exported) res);\nfinishedscenarios := sce::nil;\nsceEventMap := (sce,(eventDefinition re))::nil;\n                                                    \n|})\nend.\n\n\n\n(*here we require existance of eventWhenExpr for the reason that multiple event_instances may correspond to this raised event.\nWe could add  guard expressions to each event. For one without when, we could add a true\n*)\nFixpoint findEventInstance (re:raisedEvent) (en:value_env) (elist: list event_instance): option event_instance :=\nmatch elist with\n| nil => None\n| e::lst' => let ex_env := createValueEnv (eventArgs e) (eventParams (eventDefinition re)) (eventArguments re) in\n                 match ex_env with\n                   | Result (env) => let extend_env := (extendValEnv (en) (env)) in                   \n                                              match evalMonad extend_env (eventWhenExpr e) with\n                                              | Result (inl (inr true)) =>Some e\n                                              | Result (inl (inr false)) => findEventInstance re en lst'\n                                              |_ => None                                                \n                                              end\n                  | _ => None\n                end\nend.\n\nPrint object.\n\n(*basic rule*)\nDefinition constructConfig (sce: scenario) (re: raisedEvent)  `(conf : configuration M) : ErrorOrResult:=\nlet sce_state := (getScenarioState sce (controlstate conf)) in\n                     match sce_state with\n                    | None =>  (Error error1)\n                    | Some state =>  \n                       match (transEvMapFunc (stateEvDefInstanceMap M)  (Some state , Some (eventDefinition re))) with\n                                 | None => Error error3\n                                 | Some le => \n                               let e' :=  findEventInstance re (datastate conf) le in\n                          match e' with \n                          | None =>  Error error3\n                          | Some e => \n                            let ex_env' := createValueEnv (eventArgs e) (eventParams (eventDefinition re)) (eventArguments re) in \n                            match ex_env' with\n                            |  (Error s) =>  (Error error12)\n                            | Result (ex_env) => \n                            let extend_env := (extendValEnv (datastate conf) (ex_env) ) in\n                               let stp:= (getStep' conf sce e) in match stp with \n                                  | None =>  (Error error4)\n                                  | Some stp' =>  match configTransition extend_env re e sce stp' conf with\n                                                                | Error s => Error error11\n                                                                | Result s => Result s\n                                                 end\n                                   end         \n                                  end\n                             end\n                     end\n                   end\n.\n\nPrint findEventInstance. \n\n\n\n\nFixpoint constructConfigList' (scs: list scenario) (re: raisedEvent) `(conf : configuration M): ErrorOrResult :=\nmatch scs with\n| nil => Result (nil)\n| sce::scenarios' => match constructConfig sce re conf with\n                                | Result conf' => match constructConfigList' scenarios' re conf with                                                         | Error s => Error s\n                                                          | Result (lst) =>  Result ( conf' :: lst)\n                                                          end                           \n                                | Error s => Error (s)\n                              end\n\nend.\n\n(*core method in synchrony rule, find all state machines that can be triggered by re and execute transitions*)\nDefinition constructConfigList (scs: list scenario) (re: raisedEvent) `(conf : configuration M): ErrorOrResult :=\nlet scs' := (filterList (finishedscenarios conf) scs scenario_dec) in\nlet scs'' :=  filter (fun x => inList (event_definition_dec) (eventDefinition re) (alphabet x)) scs' in \nconstructConfigList' scs'' re conf.\n\n\n(*definition of an error configuration*)\nDefinition ErrConfig  (e: raisedEvent) `(conf: configuration M) :Prop:=\nIn e (raisedevents conf) -> (exists s, constructConfigList (dom (controlstate conf)) e conf = Error (s)). \n\n(*no data state conflicts*)\nDefinition noDataConflict  (dso ds1 ds2:value_env): Prop :=\nforall s, In s (dom (dso)) -> \n(exists str, AIdent str = s) /\\ ( (getValue s dso <> getValue s ds1) /\\ (getValue s dso <> getValue s ds2) -> getValue s ds1 = getValue s ds2).\n\n(*no control state conflicts*)\nDefinition noControlConflict (cso cs1 cs2 :scenario_env): Prop :=\nforall s, getScenarioState s cso <> getScenarioState s cs1 -> getScenarioState s cso <> getScenarioState s cs2 -> getScenarioState s cs1 = getScenarioState s cs2.\n\n(*no conflicts, used in the definition of synchrony rule*)\nDefinition noConflict {M : monitor} (originConf conf1 conf2: configuration M): Prop := noDataConflict (datastate originConf) (datastate conf1) (datastate conf2) \n                /\\ noControlConflict (controlstate originConf) (controlstate conf1) (controlstate conf2). \n\n(*merge datastate*)\nFixpoint mergeDataStateFunc  (dso ds1 ds2:value_env) : ErrorOrResult :=\nmatch dso, ds1, ds2 with\n| (n1,(t1,v0))::lst0, (n2,(t2,v1))::lst1, (n3,(t3,v2))::lst2 => if atom_eq_dec n1 n2 then \n                                                                                           if atom_eq_dec n1 n3 then \n                                                                                                   if typ_eq_dec t1 t2 then \n                                                                                                        if typ_eq_dec t1 t3 then\n                                              let r :=  mergeDataStateFunc lst0 lst1 lst2 in \n                                                match r with\n                                                | Error s => Error s\n                                                | Result lst =>  if range_typ_dec v1 v2 then  Result ((n1,(t1,v1))::lst)\n                                                                                                                              else if ((range_typ_dec v1 v0)) then \n                                                                                                                              Result ((n1,(t1,v2))::lst)\n                                                                                                                              else if ((range_typ_dec v2 v0)) then\n                                                                                                                               Result ((n1,(t1,v1))::lst)\n                                                                                                                              else Error error13\n                      \n                                                                  \n                                               end\n                                                else Error error5 else Error error5 else Error error5 else Error error5\n| nil, nil, nil => Result nil\n| _,_,_ => Error error6\nend.\n\n(*merge controlstate*)\nFixpoint mergeControlStateFunc  (cso cs1 cs2: scenario_env) : ErrorOrResult :=\nmatch cso, cs1, cs2 with\n| (sc0,s0)::lst0, (sc1,s1)::lst1, (sc2,s2)::lst2 => if scenario_dec sc0 sc1 then \n                                                                                           if scenario_dec sc0 sc2 then \n                                              let r :=  mergeControlStateFunc lst0 lst1 lst2 in \n                                                match r with\n                                                | Error s => Error s\n                                                | Result lst =>  if string_dec s1 s2 then  Result ((sc0,s1)::lst)\n                                                                                                                              else if ((string_dec s1 s0)) then \n                                                                                                                              Result ((sc0,s2)::lst)\n                                                                                                                              else  if ((string_dec s2 s0)) then Result ((sc0,s1)::lst)\n                                                                                                                              else Error error14\n          \n                                                                  \n                                               end\n                                                else Error error7 else Error error7\n| nil, nil, nil => Result nil\n| _,_,_ => Error error6\nend.\n\n\n(*merge configuration*)\n\nLocal Open Scope list_scope.\n     \nDefinition mergeConfigFunc {M : monitor} (config config1 config2 : configuration M):  @ErrorOrResult (configuration M) := \nlet ds:= mergeDataStateFunc (datastate config) (datastate config1) (datastate config2) \nin match ds with\n   | Error s => Error s\n   | Result ds' => \nlet cs:= mergeControlStateFunc (controlstate config) (controlstate config1) (controlstate config2) \nin  match cs with\n   | Error s => Error s\n   | Result cs' => \nlet raisedEvents := mergeList' (raisedevents config1) (raisedevents config2) (raisedEvent_dec) in\nlet exportedEvents := mergeList' (exportedevents config1) (exportedevents config2) (raisedEvent_dec) in\nlet finishedEvents := (finishedscenarios config1) ++ (finishedscenarios config2) ++ (finishedscenarios config) in\nlet sceEventMaps :=  (sceEventMap config1) ++ (sceEventMap config2) ++ (sceEventMap config) in\nResult ({|\ndatastate := ds';\ncontrolstate :=cs';\nraisedevents := raisedEvents;\nexportedevents := exportedEvents;\nfinishedscenarios := finishedEvents;\nsceEventMap := sceEventMaps;\n|})\nend\nend.\n\n\n\n\nDefinition mergeConfigFunc' {M : monitor} (config config1 config2 : configuration M) : @ErrorOrResult (configuration M) := \nlet ds:= mergeDataStateFunc (datastate config) (datastate config1) (datastate config2) \nin match ds with\n   | Error s => Error s\n   | Result ds' => \nlet cs:= mergeControlStateFunc (controlstate config) (controlstate config1) (controlstate config2) \nin  match cs with\n   | Error s => Error s\n   | Result cs' => \n(*let raisedEvents := mergeList' (raisedevents config1) (raisedevents config2) (raisedEvent_dec) in\nlet exportedEvents := mergeList' (exportedevents config1) (exportedevents config2) (raisedEvent_dec) in*)\nlet raisedEvents := app (raisedevents config1) (raisedevents config2) in\nlet exportedEvents := app (exportedevents config1) (exportedevents config2)  in\nlet finishedEvents := (finishedscenarios config1) ++ (finishedscenarios config2)  in\nlet sceEventMaps :=  (sceEventMap config1) ++ (sceEventMap config2)  in\nResult ({|\ndatastate := ds';\ncontrolstate :=cs';\nraisedevents := raisedEvents;\nexportedevents := exportedEvents;\nfinishedscenarios := finishedEvents;\nsceEventMap := sceEventMaps;\n|})\nend\nend.\n\n\n  \nFixpoint innerCombineFunc'' {M : monitor} (lst: list (configuration M)) (o1: configuration M) (o2: configuration M) : option (configuration M) := match lst with\n  | conf::lst' => let v := mergeConfigFunc' o1 o2 conf in\n                  match v with\n                  | Result conf' => innerCombineFunc'' lst' o1 conf'\n                  | Error  s => None\n                  end\n  | _ => None           \n  end.\n\n\nFixpoint innerCombineFunc''' `(originconf: configuration M)  (confList: list (configuration M)): option (configuration M):=\n  match confList with\n  | conf' :: l =>  match innerCombineFunc''' originconf  l with                   \n                    | Some c => match mergeConfigFunc' originconf c conf' with\n                                 | Error s => None\n                                 | Result rc => Some rc\n                                end\n                    | None => match mergeConfigFunc' originconf originconf conf' with\n                              | Error s => None\n                              | Result c => Some c\n                              end\n                   end\n  | _ => None\n  end.\n\n\nFixpoint innerCombineFunc'''' `(originconf: configuration M)  (confList: list (configuration M)) : option (configuration M) :=\n  match confList with\n  | conf' :: nil => match mergeConfigFunc' originconf originconf conf' with\n                    | Error s => None\n                    | Result c => Some c\n                    end\n  | conf' :: l => match innerCombineFunc'''' originconf  l with\n                            | Some c =>  match  mergeConfigFunc' originconf conf' c with\n                                          | Error s => None\n                                          | Result rc => Some rc\n                                         end\n                            | None => None\n                            end\n  | _ => None                           \n  end.\n\nPrint innerCombineFunc''''. \n\n\n\n(*Fixpoint innerCombineFunc'''' `(originconf: configuration M)  (confList: list (configuration M)) : option (configuration M) :=\n  match confList with\n  | conf' :: nil => match mergeConfigFunc' originconf originconf conf' with\n                    | Error s => None\n                    | Result c => Some c\n                    end\n  | conf' :: conf'' :: l => match innerCombineFunc'''' originconf  l with\n                            | Some c =>  match  mergeConfigFunc' originconf conf' conf'' with\n                                          | Error s => None\n                                          | Result rc => match mergeConfigFunc' originconf rc c with\n                                                         | Error s => None\n                                                         | Result c => Some c\n                                                         end\n                                         end\n                            | None => None\n                            end\n  | _ => None                           \n  end.\n*)\n\n\n\n\n\nFixpoint innerCombineFunc' `(originconf: configuration M) (conf: option (configuration M)) (confList: list (configuration M)) : ErrorOrResult :=\n\nmatch conf with\n| None => match confList with\n                 | nil => Error error9\n                 | conf'::confList' => innerCombineFunc' originconf (Some conf') (confList')\n                end\n| Some conf' => match confList with\n                 | nil => Result conf'\n                 | conf''::confList' =>  let rconf := innerCombineFunc' originconf (Some conf'') ( (confList'))  in\n                                                  match rconf with\n                                                  | Error s => Error s\n                                                  | Result rc => mergeConfigFunc originconf conf' rc \n                                                  end\n                end\n\nend.\n\n\nDefinition removeEventFromConf (e:raisedEvent) `(conf:configuration M) : configuration M :=\n   ({|\ndatastate := (datastate conf);\ncontrolstate := (controlstate conf);\nraisedevents := removeEvent' e ((raisedevents) conf);\nexportedevents := (exportedevents conf);\nfinishedscenarios := (finishedscenarios conf);\nsceEventMap := (sceEventMap conf);\n|}).\n             \nDefinition combineFunc  (e: raisedEvent) `(conf: configuration M): option (configuration M) := \n\nmatch constructConfigList (dom (controlstate conf)) e conf with\n| (Error s) => None\n| Result (lst) => match lst with\n                         | nil => None\n                         | lst' => match innerCombineFunc''''  conf lst' with\n                                   | Some v => Some (removeEventFromConf e v)\n                                   | None => None\n                                   end\n                        end\nend\n.\n\n(*\n(*merge datastate*)\nFixpoint mergeDataStateFunc  (dso ds1 ds2:value_env) : ErrorOrResult :=\nmatch dso, ds1, ds2 with\n| (n1,(t1,v0))::lst0, (n2,(t2,v1))::lst1, (n3,(t3,v2))::lst2 => if atom_eq_dec n1 n2 then \n                                                                                           if atom_eq_dec n1 n3 then \n                                                                                                   if typ_eq_dec t1 t2 then \n                                                                                                        if typ_eq_dec t1 t3 then\n                                              let r :=  mergeDataStateFunc lst0 lst1 lst2 in \n                                                match r with\n                                                | Error s => Error s\n                                                | Result lst =>  if range_typ_dec v1 v2 then  Result ((n1,(t1,v1))::lst)\n                                                                                                                              else if ((range_typ_dec v1 v0)) then \n                                                                                                                              Result ((n1,(t1,v2))::lst)\n                                                                                                                              else if ((range_typ_dec v2 v0)) then\n                                                                                                                               Result ((n1,(t1,v1))::lst)\n                                                                                                                              else Error error13\n                      \n                                                                  \n                                               end\n                                                else Error error5 else Error error5 else Error error5 else Error error5\n| nil, nil, nil => Result nil\n| _,_,_ => Error error6\nend.\n\n(*merge controlstate*)\nFixpoint mergeControlStateFunc  (cso cs1 cs2: scenario_env) : ErrorOrResult :=\nmatch cso, cs1, cs2 with\n| (sc0,s0)::lst0, (sc1,s1)::lst1, (sc2,s2)::lst2 => if scenario_dec sc0 sc1 then \n                                                                                           if scenario_dec sc0 sc2 then \n                                              let r :=  mergeControlStateFunc lst0 lst1 lst2 in \n                                                match r with\n                                                | Error s => Error s\n                                                | Result lst =>  if string_dec s1 s2 then  Result ((sc0,s1)::lst)\n                                                                                                                              else if ((string_dec s1 s0)) then \n                                                                                                                              Result ((sc0,s2)::lst)\n                                                                                                                              else  if ((string_dec s2 s0)) then Result ((sc0,s1)::lst)\n                                                                                                                              else Error error14\n          \n                                                                  \n                                               end\n                                                else Error error7 else Error error7\n| nil, nil, nil => Result nil\n| _,_,_ => Error error6\nend.\n\n\n(*merge configuration*)\nDefinition mergeConfigFunc (config config1 config2 : configuration):  ErrorOrResult:= \nlet ds:= mergeDataStateFunc (datastate config) (datastate config1) (datastate config2) \nin match ds with\n   | Error s => Error s\n   | Result ds' => \nlet cs:= mergeControlStateFunc (controlstate config) (controlstate config1) (controlstate config2) \nin  match cs with\n   | Error s => Error s\n   | Result cs' => \nlet raisedEvents := mergeList' (raisedevents config1) (raisedevents config2) (raisedEvent_dec) in\nlet exportedEvents := mergeList' (exportedevents config1) (exportedevents config2) (raisedEvent_dec) in\nlet finishedEvents := mergeList' (finishedscenarios config1) (finishedscenarios config2) (scenario_dec) in\nResult ({|\nmonitor_obj := (monitor_obj config);\ndatastate := ds';\ncontrolstate :=cs';\nraisedevents := raisedEvents;\nexportedevents := exportedEvents;\nfinishedscenarios := finishedEvents;\n\n|})\nend\nend.\n\n\n\nFixpoint innerCombineFunc' (originconf: configuration) (conf: option configuration) (confList: (list configuration)): ErrorOrResult:=\n\nmatch conf with\n| None => match confList with\n                 | nil => Error error8\n                 | conf'::confList' => innerCombineFunc' originconf (Some conf') (confList')\n                end\n| Some conf' => match confList with\n                 | nil => Result conf'\n                 | conf''::confList' =>  let rconf := innerCombineFunc' originconf (Some conf'') ( (confList'))  in\n                                                  match rconf with\n                                                  | Error s => Error s\n                                                  | Result rc => mergeConfigFunc originconf conf' rc \n                                                  end\n                end\n\nend.\n\n\n\nDefinition combineFunc  (e: raisedEvent) (conf: configuration): ErrorOrResult := \n\nmatch constructConfigList (dom (controlstate conf)) e conf with\n| (Error s) => Error s\n| Result (lst) => match lst with\n                         | nil => Error error9\n                         | lst' =>  innerCombineFunc' conf None lst'\n                        end\nend\n.\n\n*)\n\nDefinition conflict (e: raisedEvent) `(conf: configuration M) :Prop:=\n(exists clist, (constructConfigList (dom (controlstate conf)) e conf = \nResult (clist)) /\\ exists conf1 conf2, In conf1 clist /\\ In conf2 clist /\\ ~(noConflict conf conf1 conf2)). \n\n(*combine configurations having same source configuration and same triggering event*)\nDefinition synchrony {M : monitor} (conf conf' :configuration M) (event:raisedEvent) : Prop :=\nIn event (raisedevents conf) /\\ combineFunc event conf = Some (conf').\n\n(*\nDefinition synchrony  (conf conf' :configuration) (event:raisedEvent) : Prop :=\nIn event (raisedevents conf) /\\ ~(ErrConfig event conf ) /\\  ~(conflict event conf) /\\ combineFunc event conf = Result (conf').\n *)\n\n(*initial configuration*)\nDefinition readyConfig  `(conf :configuration M) : Prop :=\ncorrect_configuration conf /\\ raisedevents conf = nil\n/\\ (exportedevents conf) = nil                                 \n/\\ (finishedscenarios conf) = nil\n/\\ (sceEventMap conf) = nil.\n\n(*initial configuration*)\nDefinition initialConfig  `(conf :configuration M) : Prop :=\ncorrect_configuration conf /\\ (length (raisedevents conf) = S O) \n/\\ (forall e,  In e (raisedevents conf) -> importedEvent (eventDefinition e)\n/\\ (exists sce, In sce (dom (controlstate conf)) \n/\\ In (eventDefinition e) ((alphabet) sce)))\n/\\ (finishedscenarios conf) = nil\n/\\ (sceEventMap conf) = nil.\n\nPrint configuration.\n\nDefinition configStEq {M : monitor} (conf conf': configuration M) : Prop :=\n  datastate conf = datastate conf' /\\\n  controlstate conf = controlstate conf'.\n  \n  \nDefinition configTrans {M : monitor} (conf conf': configuration M) : Prop :=\n readyConfig conf /\\ initialConfig conf' /\\ configStEq conf conf'. \n\nDefinition configTransRev {M : monitor} (conf conf': configuration M) : Prop :=\n configStEq conf conf' /\\ readyConfig conf'.\n             \n(*chain merge rule*)\nInductive chainMerge (M : monitor) : configuration M -> configuration M-> raisedEvent ->  Prop :=\n| basic': forall conf conf' event, initialConfig conf ->  synchrony conf conf' event -> chainMerge conf conf' event\n| chain': forall conf conf'' conf' event1 event2, chainMerge conf conf' event1 -> synchrony conf' conf'' event2-> chainMerge conf conf'' event1.\n\nInductive chainMergeStep (M : monitor) : configuration M -> configuration M-> raisedEvent -> nat -> Prop :=\n| merge_basic: forall conf conf' event, (importedEvent (eventDefinition event)) ->  synchrony conf conf' event -> chainMergeStep conf conf' event O\n| merge_chain: forall conf conf'' conf' event1 event2 n, chainMergeStep conf conf' event1 n -> synchrony conf' conf'' event2-> chainMergeStep conf conf'' event1 (S n).\n\n\n(* transEvMap ((getScenarioState sce (controlstate conf)), Some (eventDefinition e))  = nil)\nmeans that e is not in the alphabet of sce\nSMEDL asks for the complete scenario, so if e is in the alphabet of \nsce, then transEvMap should always return a value\n *)\n\n(*\nDefinition finalConfig (conf:configuration):Prop:=\ncorrect_configuration conf /\\ ((length (raisedevents conf) = O)  \\/ (forall e  , In e (raisedevents conf) -> (~importedOrInternalEvent (eventDefinition e) \n/\\  (forall sce, In sce (dom (controlstate conf)) /\\ ~ (In sce (finishedscenarios conf)) -> transEvMap ((getScenarioState sce (controlstate conf)), Some (eventDefinition e))  = nil)))).\n *)\n\nDefinition finalConfig `(conf:configuration M):Prop:=\n(length (raisedevents conf) = O)  \\/  incl (dom (controlstate conf)) (finishedscenarios conf).\n\nDefinition chainMergeTrans {M : monitor} (conf conf' econf: configuration M) (e: raisedEvent) (rconf: configuration M)  (events: list raisedEvent)  : Prop :=\n   configTrans conf conf' /\\ chainMerge conf' econf e /\\ finalConfig econf /\\ configTransRev econf rconf /\\ events = exportedevents econf.\n\n                                                                                                \n(*definition of stuck configuration*)\nDefinition stuckConfig `(conf:configuration M):Prop:=\n  (forall e , In e (raisedevents conf) -> (~(exists conf', synchrony conf conf' e))).\n\n(*equivlance relation between two configurations*)\nDefinition equivConf {M : monitor} (conf conf':configuration M) : Prop :=\n(datastate conf) = (datastate conf') /\\ (controlstate conf) = (controlstate conf')\n/\\ incl (raisedevents conf) (raisedevents conf') /\\ incl (raisedevents conf') (raisedevents conf) /\\ Permutation (finishedscenarios conf) (finishedscenarios conf')\n/\\ incl (exportedevents conf) (exportedevents conf') /\\ incl (exportedevents conf') (exportedevents conf) /\\ Permutation (sceEventMap conf) (sceEventMap conf').\n\n(*equivConf is an equivalence relation*)\nLemma equivConf_Refl {M : monitor} : forall x : configuration M,\nequivConf x x. \nProof. intros. unfold equivConf;split;auto. repeat(try (split;auto)).\n       unfold incl;intros;auto.\n       unfold incl;intros;auto.\n\n       unfold incl;intros;auto.\n       unfold incl;intros;auto.\n       \nQed.\n\nLemma equivConf_Sym {M : monitor} : forall x1 x2 : configuration M,\nequivConf x1 x2 <-> equivConf x2 x1. \nProof. intros. split.\n- intros. unfold equivConf in H. \n    repeat match goal with\n            | [ H: _ /\\ _ |- _ ] => destruct H\n\n            end. \nunfold equivConf. repeat(split;auto);repeat(apply Permutation_sym; auto).\n\n- intros. unfold equivConf in H. \n    repeat match goal with\n            | [ H: _ /\\ _ |- _ ] => destruct H\n\n           end.\n    unfold equivConf. repeat(split;auto);repeat(apply Permutation_sym; auto).\nQed.     \n\nLemma equivConf_Trans {M : monitor} : forall x1 x2 x3 : configuration M,\nequivConf x1 x2 -> equivConf x2 x3 -> equivConf x1 x3. \nProof. intros. unfold equivConf in H. unfold equivConf in H0.\n    repeat match goal with\n            | [ H: _ /\\ _ |- _ ] => destruct H\n\n            end. \n    unfold equivConf. split;auto. rewrite H;auto.  split. rewrite <- H1;auto.\n    split.\nunfold incl in *. intros. apply H2. apply H9;auto.\nsplit.\nunfold incl in *. intros. apply H10. apply H3;auto.\n\nsplit.\n\neapply Permutation_trans. apply H11. auto.\nsplit. \n\nunfold incl in *. intros. apply H5. apply H12;auto.\nsplit.\nunfold incl in *. intros. apply H13. apply H6;auto.\neapply Permutation_trans. apply H14. auto.\nQed.\n\n\n(*(*equivlance relation between two configurations*)\nDefinition equivConf {M : monitor} (conf conf':configuration M) : Prop :=\n(datastate conf) = (datastate conf') /\\ (controlstate conf) = (controlstate conf')\n/\\ Permutation (raisedevents conf) (raisedevents conf') /\\ Permutation (finishedscenarios conf) (finishedscenarios conf')\n/\\ incl (exportedevents conf) (exportedevents conf') /\\ incl (exportedevents conf') (exportedevents conf) /\\ Permutation (sceEventMap conf) (sceEventMap conf').\n\n(*equivConf is an equivalence relation*)\nLemma equivConf_Refl {M : monitor} : forall x : configuration M,\nequivConf x x. \nProof. intros. unfold equivConf;split;auto. repeat(try (split;auto)).\n       unfold incl;intros;auto.\n        unfold incl;intros;auto.\nQed.\n\nLemma equivConf_Sym {M : monitor} : forall x1 x2 : configuration M,\nequivConf x1 x2 <-> equivConf x2 x1. \nProof. intros. split.\n- intros. unfold equivConf in H. \n    repeat match goal with\n            | [ H: _ /\\ _ |- _ ] => destruct H\n\n            end. \nunfold equivConf. repeat(split;auto);repeat(apply Permutation_sym; auto).\n\n- intros. unfold equivConf in H. \n    repeat match goal with\n            | [ H: _ /\\ _ |- _ ] => destruct H\n\n           end.\n    unfold equivConf. repeat(split;auto);repeat(apply Permutation_sym; auto).\nQed.     \n\nLemma equivConf_Trans {M : monitor} : forall x1 x2 x3 : configuration M,\nequivConf x1 x2 -> equivConf x2 x3 -> equivConf x1 x3. \nProof. intros. unfold equivConf in H. unfold equivConf in H0.\n    repeat match goal with\n            | [ H: _ /\\ _ |- _ ] => destruct H\n\n            end. \n    unfold equivConf. split;auto. rewrite H;auto.  split. rewrite <- H1;auto.\nsplit. \neapply Permutation_trans. apply H8. auto.\nsplit. \neapply Permutation_trans. apply H9. auto.\nsplit.\nunfold incl in *. intros. apply H4. apply H10;auto.\nsplit.\nunfold incl in *. intros. apply H11. apply H10;auto.\neapply Permutation_trans. apply H12. auto.\nQed.*)\n\nEnd semantic_rule.\n\n\n(*Fixpoint eventInPath (ev:event_definition) (lst: list event_definition): bool :=\nmatch lst with\n| nil => false\n| ev'::lst' => if event_definition_dec ev ev' then true else eventInPath ev lst'\nend. \n\nFixpoint checkUpdateValue' (a:atom) (lst: list updatedVariable) (re:raisedEvent) : bool :=\nmatch lst with\n| nil => true\n| v::lst' => if (atom_eq_dec a (up_var v)) then eventInPath (eventTag v) (pathEvents re) else checkUpdateValue' a lst' re\nend. \n\n\nFixpoint checkUsedValue'' (evList:list event_definition) (pathList: list event_definition) : bool :=\nmatch evList with\n| nil => true\n| ev::lst' => if eventInPath ev pathList then checkUsedValue'' lst' pathList else false\nend. \n\n\nFixpoint checkUsedValue' (a:atom) (lst: list usedVariable) (re:raisedEvent) : bool :=\nmatch lst with\n| nil => true\n| v::lst' => if (atom_eq_dec a (used_var v)) then checkUsedValue'' (used_eventTagList v) (pathEvents re) else checkUsedValue' a lst' re\nend.\n\nPrint configuration. \n\n\nFixpoint checkValue (conf:configuration) (re:raisedEvent) (lst: list atom)   : bool :=\nmatch lst with\n| nil => true\n| a::lst' => if checkUpdateValue' a (updatedvariableList conf) re then checkValue conf re lst' else  false\nend.\n\nFixpoint checkUpdatedUsedValue (conf:configuration) (re:raisedEvent) (lst: list atom) : bool :=\nmatch lst with\n| nil => true\n| a::lst' => if checkUsedValue' a (usedvariableList conf) re then checkUpdatedUsedValue conf re lst' else  false\nend.\n\n\nDefinition checkValueNonDeterminism (conf:configuration) (re:raisedEvent)  (stp:step) :bool :=\nlet usedVariables :=  getUsedVariablesFromScenario conf stp in\nlet updatedVariables := getUpdatedVariablesFromScenario conf stp in\ncheckValue conf re usedVariables &&  \ncheckValue conf re updatedVariables &&\ncheckUpdatedUsedValue conf re updatedVariables\n.\n\nFixpoint updateUsedVariables' (lst: list usedVariable) (a: atom) (re:raisedEvent) : option usedVariable\n:=\nmatch lst with\n| nil => None\n| uv::lst' => if atom_eq_dec a (used_var uv) then \n   Some {|used_var := (used_var uv); used_eventTagList:= ( eventDefinition re) :: (used_eventTagList uv) |}\nelse updateUsedVariables' lst' a re\nend. \n\n\nFixpoint updateUsedVariables (lst: list usedVariable) (lstAtom: list atom) (re:raisedEvent)\n:  list usedVariable := \nmatch lstAtom with\n| nil => lst\n| a::lstAtom' => match  (updateUsedVariables' lst a re) with\n                        | None => (updateUsedVariables lst lstAtom' re)\n                        | Some uv => uv :: (updateUsedVariables lst lstAtom' re)\n                       end\nend.\n\n\nFixpoint updatedVariable' (lst: list updatedVariable) (a: atom) (re:raisedEvent) : option updatedVariable\n:=\nmatch lst with\n| nil => None\n| uv::lst' => if atom_eq_dec a (up_var uv) then \n   Some {|up_var := (up_var uv); eventTag:= ( eventDefinition re) |}\nelse updatedVariable' lst' a re\nend. \n\n\nFixpoint updateUpdateVariables (lst: list updatedVariable) (lstAtom: list atom) (re:raisedEvent)\n:  list updatedVariable := \nmatch lstAtom with\n| nil => lst\n| a::lstAtom' => match  (updatedVariable' lst a re) with\n                        | None => (updateUpdateVariables lst lstAtom' re)\n                        | Some uv => uv :: (updateUpdateVariables lst lstAtom' re)\n                       end\nend.\n\nFixpoint newUpdateVariables (lstAtom : list atom) (re:raisedEvent): list updatedVariable :=\nmatch lstAtom with\n| nil => nil\n| a::lstAtom' => {|up_var := a; eventTag := eventDefinition re |} :: newUpdateVariables lstAtom' re\nend.\n\nFixpoint newUsedVariables (lstAtom : list atom) (re:raisedEvent): list usedVariable :=\nmatch lstAtom with\n| nil => nil\n| a::lstAtom' => {|used_var := a; used_eventTagList := (eventDefinition re)::nil |} :: newUsedVariables lstAtom' re\nend.*)", "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/SMEDL_mon/smedlDef/semantic_rules.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.2517028365997318}}
{"text": "(* Lemmas about memory *)\nRequire Import Util.\nRequire Import block_model.\nRequire Import conc_model.\nRequire Import Lang.\n\nSet Implicit Arguments.\n\nNotation indep ops1 ops2 := (Forall (fun c1 => Forall (fun c2 =>\n  loc_of c2 <> loc_of c1) ops2) ops1).\n\nSection SC.\n\nContext {ML : @Memory_Layout var nat _}.\n\nGlobal Instance conc_op_dec : EqDec_eq conc_op.\nProof. eq_dec_inst. Qed.\n\nDefinition consistent (m : list conc_op) := @SC _ _ _ ML _ _ Base m.\n\nDefinition can_read (m : list conc_op) p v := consistent (m ++ [Read 0 p v]).\nDefinition can_write (m : list conc_op) p :=\n  forall v, consistent (m ++ [Write 0 p v]).\n\nDefinition prog_op c := match c with Read _ _ _ | Write _ _ _ | ARW _ _ _ _ =>\n  True | _ => False end.\n\nLemma op_indep : forall c1 c2 (Hindep : loc_of c1 <> loc_of c2)\n   (Hc1 : prog_op c1) (Hc2 : prog_op c2),\n   Forall (fun l => Forall (independent l) (map block_model.loc_of (to_seq c2)))\n     (map block_model.loc_of (to_seq c1)).\nProof.\n  destruct c1, c2; clarify.\nQed.\n\nLemma loc_comm_SC : forall m1 c1 c2 m2 (Hindep : loc_of c1 <> loc_of c2)\n  (Hc1 : prog_op c1) (Hc2 : prog_op c2)\n  (Hcon : consistent (m1 ++ c1 :: c2 :: m2)), consistent (m1 ++ c2 :: c1 :: m2).\nProof.\n  unfold consistent, SC; clarify.\n  rewrite lower_app, lower_cons, lower_cons;\n    rewrite lower_app, lower_cons, lower_cons in Hcon.\n  repeat rewrite to_ilist_app in *; rewrite loc_comm_ops; auto.\n  apply op_indep; auto.\nQed.\n  \nLemma loc_comm_ops1_SC : forall c lc m1 m2\n  (Hindep : Forall (fun c' => loc_of c' <> loc_of c) lc)\n  (Hc : prog_op c) (Hlc : Forall prog_op lc),\n  consistent (m1 ++ c :: lc ++ m2) <-> consistent (m1 ++ lc ++ c :: m2).\nProof.\n  induction lc; clarify; [reflexivity|].\n  inversion Hlc; inversion Hindep; clarify.\n  specialize (IHlc (m1 ++ [a]) m2); clarsimp.\n  etransitivity; eauto; split; apply loc_comm_SC; auto.\nQed.\n\nLemma loc_comm_ops_SC : forall lc1 lc2 m1 m2\n  (Hindep : Forall (fun c => Forall (fun c' => loc_of c' <> loc_of c) lc2) lc1)\n  (Hlc1 : Forall prog_op lc1) (Hlc2 : Forall prog_op lc2),\n  consistent (m1 ++ lc1 ++ lc2 ++ m2) <-> consistent (m1 ++ lc2 ++ lc1 ++ m2).\nProof.\n  induction lc1; clarify; [reflexivity|].\n  inversion Hlc1; clarify.\n  specialize (IHlc1 lc2 (m1 ++ [a]) m2); inversion Hindep; clarsimp.\n  etransitivity; eauto; apply loc_comm_ops1_SC; auto.\nQed.\n\nLemma consistent_app_SC : forall m1 m2 (Hcon : consistent (m1 ++ m2)),\n  consistent m1.\nProof.\n  unfold consistent, SC; intros.\n  rewrite lower_app in Hcon; eapply consistent_app; eauto.\nQed.\n\nLemma consistent_drop : forall m c1 c2, consistent (m ++ [c1; c2]) ->\n  consistent (m ++ [c1]).\nProof.\n  intros; eapply consistent_app_SC; rewrite <- app_assoc; simpl; eauto.\nQed.\n\nLemma loc_valid_SC : forall m c1 c2 (Hindep : loc_of c1 <> loc_of c2)\n  (Hc1 : prog_op c1) (Hc2 : prog_op c2),\n  consistent (m ++ [c1; c2]) <->\n  (consistent (m ++ [c1]) /\\ consistent (m ++ [c2])).\nProof.\n  split; intros.\n  - split.\n    + rewrite split_app in H; exploit consistent_app_SC; eauto; clarify.\n    + exploit loc_comm_SC; eauto; intro H'.\n      rewrite split_app in H'; exploit consistent_app_SC; eauto; clarify.\n  - unfold consistent, SC in *; clarify.\n    repeat rewrite lower_app; rewrite lower_cons; repeat rewrite lower_single.\n    rewrite lower_app, lower_single in H1, H2.\n    apply loc_valid_ops; auto.\n    apply op_indep; auto.\nQed.\n\nLemma loc_valid_ops1_SC : forall c lc m\n  (Hindep : Forall (fun c' => loc_of c' <> loc_of c) lc)\n  (Hc : prog_op c) (Hlc : Forall prog_op lc),\n  consistent (m ++ lc ++ [c]) <->\n  (consistent (m ++ lc) /\\ consistent (m ++ [c])).\nProof.\n  induction lc; clarify.\n  { split; clarsimp.\n    eapply consistent_app_SC; eauto. }\n  inversion Hlc; clarify.\n  specialize (IHlc (m ++ [a])); inversion Hindep; clarsimp.\n  rewrite IHlc, loc_valid_SC; auto.\n  split; intro Hcon; clarify.\n  rewrite split_app in Hcon1; eapply consistent_app_SC; eauto.\nQed.\n\nCorollary loc_valid_ops2_SC : forall m c lc\n  (Hindep : Forall (fun c' => loc_of c' <> loc_of c) lc)\n  (Hc : prog_op c) (Hlc : Forall prog_op lc),\n  consistent (m ++ c :: lc) <->\n  (consistent (m ++ lc) /\\ consistent (m ++ [c])).\nProof.\n  intros; rewrite <- loc_valid_ops1_SC; auto.\n  generalize (loc_comm_ops1_SC _ m [] Hindep); rewrite app_nil_r; auto.\nQed.\n\nLemma loc_valid_ops_SC : forall lc1 lc2 m\n  (Hindep : Forall (fun c => Forall (fun c' => loc_of c' <> loc_of c) lc2) lc1)\n  (Hlc1 : Forall prog_op lc1) (Hlc2 : Forall prog_op lc2),\n  consistent (m ++ lc1 ++ lc2) <->\n  (consistent (m ++ lc1) /\\ consistent (m ++ lc2)).\nProof.\n  induction lc1; clarify.\n  { split; clarsimp.\n    eapply consistent_app_SC; eauto. }\n  inversion Hlc1; clarify.\n  specialize (IHlc1 lc2 (m ++ [a])); inversion Hindep; clarsimp.\n  rewrite IHlc1; setoid_rewrite loc_valid_ops2_SC at 2; auto.\n  split; intro Hcon; clarify.\n  rewrite split_app in Hcon1; eapply consistent_app_SC; eauto.\nQed.  \n\nLemma read_noop_SC : forall m t x v m2 (Hcon : consistent (m ++ [Read t x v])),\n  consistent (m ++ Read t x v :: m2) <-> consistent (m ++ m2).\nProof.\n  unfold consistent, SC; clarify.\n  repeat rewrite lower_app; rewrite lower_app in Hcon.\n  rewrite lower_single in Hcon; rewrite lower_cons; clarify.\n  rewrite split_app; do 2 rewrite to_ilist_app; apply read_noop; auto.\nQed.\n\nCorollary reads_noops_SC : forall ops m m2\n  (Hcon : consistent (m ++ ops))\n  (Hread : Forall (fun c => match c with Read _ _ _ => True | _ => False end)\n                  ops),\n  consistent (m ++ ops ++ m2) <-> consistent (m ++ m2).\nProof.\n  induction ops; clarify; [reflexivity|].\n  specialize (IHops (m ++ [a]) m2); inversion Hread; clarsimp.\n  destruct a; clarify.\n  rewrite IHops; apply read_noop_SC.\n  rewrite split_app in Hcon; eapply consistent_app_SC; eauto.\nQed.\n\n\nLemma can_read_thread : forall m p v t, can_read m p v ->\n  consistent (m ++ [Read t p v]).\nProof.\n  unfold can_read, consistent, SC; setoid_rewrite lower_app; clarify.\nQed.\n\nLemma can_write_thread : forall m p v t, can_write m p ->\n  consistent (m ++ [Write t p v]).\nProof.\n  unfold can_write, consistent, SC; setoid_rewrite lower_app; clarify.\n  specialize (H v); clarify.\nQed.\n\nLemma can_write_SC : forall p ops m (Hcan : can_write m p)\n  (Hcon : consistent (m ++ ops)) (Hops : Forall prog_op ops),\n  can_write (m ++ ops) p.\nProof.\n  induction ops; clarsimp.\n  inversion Hops; clarify.\n  specialize (IHops (m ++ [a])); clarsimp.\n  apply IHops; auto; clear IHops.\n  rewrite split_app in Hcon; exploit consistent_app_SC; eauto; intro Hcon'.\n  clear Hcon; unfold can_write, consistent, SC in *; clarsimp.\n  specialize (Hcan v); rewrite lower_app, lower_single in Hcan, Hcon';\n    rewrite lower_app, lower_cons, lower_single.\n  destruct a; clarify.\n  - rewrite read_noop_single; auto.\n  - rewrite write_not_read_single; clarify.\n  - rewrite split_app, write_not_read_single; clarsimp.\n    rewrite read_noop_single; auto.\n    rewrite split_app in Hcon'; eapply consistent_app; eauto.\nQed.\n\nLemma can_read_SC: forall p ops m v (Hcan: can_read m p v)\n (Hcon: consistent (m ++ ops)) (Hops : Forall prog_op ops)\n  (Hnmods: Forall (fun c => match c with | Write _ x _ => p <> x\n     | ARW _ x _ _=> p <> x | _ => True end) ops),\n can_read (m++ops) p v.\nProof.\n induction ops; clarsimp.\n inversion Hops; clarify.\n specialize(IHops (m++[a])); clarsimp.\n apply IHops; auto.\n rewrite split_app in Hcon; exploit consistent_app_SC; eauto; intro Hcon'.\n unfold can_read, consistent, SC in *; clarsimp.\nrewrite lower_app, lower_single in Hcon'.\n rewrite lower_app, lower_single in Hcan.\n rewrite lower_app, lower_cons, lower_single.\n\n\n destruct a; clarify.\n -rewrite read_noop_single; clarify; auto.\n -rewrite write_not_read_single; auto.\n  intros.\n  apply Forall_inv in Hnmods. clarsimp.\n  intro Heq. inversion Heq; clarify.\n -rewrite split_app. rewrite write_not_read_single; clarsimp.\n  +rewrite read_noop_single; auto.\n   rewrite split_app in Hcon'; eapply consistent_app; eauto.\n  +apply Forall_inv in Hnmods. clarsimp.\n   intro Heq. inversion Heq; clarify.\n -assert( a::ops =[a]++ops) as Haops.\n    clarify.\n  rewrite Haops in Hnmods.\n  apply Forall_app in Hnmods. inversion Hnmods. auto.\nQed.\n\n\nLemma can_arw_SC_iff: forall p m v v' t,\n  consistent (m ++ [ARW t p v v']) <-> can_write (m ++ [Read t p v]) p. \nProof.\n  unfold can_write, consistent, SC.\n  repeat setoid_rewrite lower_app. setoid_rewrite lower_single. clarify. unfold seq_con. \n  rewrite split_app.  \n  split; clarify.\n  rewrite write_any_value.\n  eauto.\nQed.\n\nLemma can_arw_SC : forall p m v (Hcan_r : can_read m p v)\n  (Hcan_w: can_write m p) t v', consistent (m ++ [ARW t p v v']).\nProof.\n  intros.\n  rewrite can_arw_SC_iff.\n  apply can_write_SC; auto.\n  apply can_read_thread.\n  auto.\n  { constructor; clarify. }\nQed.\n  \nLemma write_any_value_SC : forall m t p v v',\n  consistent (m ++ [Write t p v]) <-> consistent (m ++ [Write t p v']).\nProof.\n  intros; unfold consistent, SC; setoid_rewrite lower_app.\n  repeat rewrite lower_single; simpl; apply write_any_value.\nQed.  \n\nLemma can_read_SC': forall p ops m v (Hcan: can_read m p v)\n  (Hcon: consistent (m ++ ops)) (Hops : Forall prog_op ops)\n  (Hnmods: Forall (fun c => match c with | Write _ x _ => p <> x\n     | ARW _ x _ _=> p <> x | _ => True end) ops),\n can_read (m ++ ops) p v.\nProof.\n induction ops; clarsimp.\n inversion Hops; clarify.\n specialize(IHops (m++[a])); clarsimp.\n apply IHops; auto.\n rewrite split_app in Hcon; exploit consistent_app_SC; eauto; intro Hcon'.\n unfold can_read, consistent, SC in *; clarsimp.\nrewrite lower_app, lower_single in Hcon'.\n rewrite lower_app, lower_single in Hcan.\n rewrite lower_app, lower_cons, lower_single.\n\n\n destruct a; clarify.\n -rewrite read_noop_single; clarify; auto.\n -rewrite write_not_read_single; auto.\n  intros.\n  apply Forall_inv in Hnmods. clarsimp.\n  intro Heq. inversion Heq; clarify.\n -rewrite split_app. rewrite write_not_read_single; clarsimp.\n  +rewrite read_noop_single; auto.\n   rewrite split_app in Hcon'; eapply consistent_app; eauto.\n  +apply Forall_inv in Hnmods. clarsimp.\n   intro Heq. inversion Heq; clarify.\n -assert( a::ops =[a]++ops) as Haops.\n    clarify.\n  rewrite Haops in Hnmods.\n  apply Forall_app in Hnmods. inversion Hnmods. auto.\nQed.\n\nLemma read_arwritten_SC : forall m p u v v' t (Hcon : consistent (m ++ [ARW t p u v])),\n      consistent ((m ++ [ARW t p u v] )++ [Read t p v']) <-> v' = v.\nProof.\n  intros.\n  unfold consistent, SC in *; clarify.\n  repeat rewrite lower_app in Hcon. rewrite lower_single in Hcon. clarify. \n  repeat rewrite lower_app,lower_single in *; clarify.\n  rewrite <- app_assoc; simpl.\n  rewrite split_app in *.\n  apply read_written. auto.\nQed.\n\nLemma can_read_thread' : forall m p v t,   consistent (m ++ [Read t p v]) ->\n     can_read m p v .\nProof.\n  unfold can_read, consistent, SC; setoid_rewrite lower_app; clarify.\nQed.\n\nLemma write_any_SC: forall t v m p\n (Hcon: consistent (m++[Write t p v ])),  can_write m p. \nProof.\n  intros. \n  unfold can_write, consistent, SC in *.  intros. rewrite lower_app in *. \n  rewrite lower_app in Hcon. rewrite lower_single in *. rewrite lower_single in Hcon.\n  simpl. simpl in Hcon. rewrite write_any_value. eauto.\nQed.\n\nDefinition initialized m p :=\n  exists v, last_op (lower(MM_base := Base) m) (Ptr p) (MWrite p v).\n\nDefinition in_range_dec i a b : {a <= i < b} + {~a <= i < b}.\nProof.\n  destruct (le_dec a i); [|right; omega].\n  destruct (lt_dec i b); [left; auto | right; omega].\nQed.\n\nLemma loc_split : forall t lc m1 m2 m3\n  (Hcon : consistent (m1 ++ lc ++ m2 ++ m3))\n  lct lcr (Hpart : partition (fun c => beq (thread_of c) t) lc = (lct, lcr))\n  (Hindep : Forall (fun c => Forall (fun c' => loc_of c' <> loc_of c) m2 /\\\n     Forall (fun c' => loc_of c' <> loc_of c) lct) lcr)\n  (Hlc : Forall prog_op lc) (Hm2 : Forall prog_op m2),\n  consistent (m1 ++ lct ++ m2 ++ lcr ++ m3).\nProof.\n  setoid_rewrite partition_filter.\n  induction lc using rev_ind; clarify.\n  repeat rewrite filter_app in *; clarify.\n  rewrite Forall_app in *; clarify.\n  inversion Hlc2; clear Hlc2; subst.\n  destruct (beq (thread_of x) t) eqn: Ht; unfold beq in Ht; clarify.\n  - specialize (IHlc m1 (x :: m2) m3); clarsimp.\n    apply IHlc; auto.\n    rewrite Forall_forall in *; intros ? Hin.\n    specialize (Hindep1 _ Hin); rewrite Forall_app in *; clarify.\n    inversion Hindep122; clarify.\n  - inversion Hindep2; specialize (IHlc m1 m2 (x :: m3)); clarsimp.\n    apply IHlc; auto.\n    rewrite app_assoc, loc_comm_ops1_SC, <- app_assoc in H; auto.\nQed.\n\nLemma last_write : forall (m : list conc_op) p v,\n  last_op (@lower _ _ _ _ _ Base m) (Ptr p) (MWrite p v) <->\n  exists c, find (fun c => writesb c p) (rev m) = Some c /\\\n  write_val c = Some v.\nProof.\n  induction m using rev_ind; clarify.\n  { split; clarify.\n    apply last_nil in H; contradiction. }\n  rewrite rev_app_distr, lower_app, lower_single, last_op_app; simpl.\n  destruct (writesb x p) eqn: Hx.\n  - split; clarify.\n    + do 2 eexists; eauto.\n      destruct H; clarify.\n      * destruct x; clarify; try rewrite last_single in H; clarify.\n        { inversion H1; clarify. }\n        { destruct H as (i & ? & Hi); destruct i; clarify.\n          destruct i; clarify; rewrite inth_nil in Hi; inversion Hi. }\n      * destruct x; clarify; unfold beq in *; inversion H2; clarsimp.\n        { inversion H4; clarify. }\n        { destruct p; clarify. }\n        { destruct p; clarify. }\n    + left; destruct x0; clarify; unfold beq in *; clarify.\n      * rewrite last_single; clarify.\n      * exists 1; clarify.\n        econstructor; simpl; eauto; intros.\n        destruct j; clarify.\n        destruct j; clarify.\n        rewrite inth_nil in H; inversion H.\n  - etransitivity; eauto.\n    split; clarify.\n    + destruct x; clarify; unfold beq in *; clarify;\n        try (rewrite last_single in H; clarify).\n      destruct H as (i & ? & Hi); destruct i; clarify.\n      destruct i; clarify; rewrite inth_nil in Hi; inversion Hi.\n    + right; clarify.\n      destruct x; clarify; unfold beq in *; constructor; clarify.\nQed.\n\nLemma init_read : forall m p (Hinit : initialized m p) (Hcon : consistent m) v,\n  can_read m p v <-> exists c,\n    find (fun c => writesb c p) (rev m) = Some c /\\ write_val c = Some v.\nProof.\n  unfold can_read; intros.\n  destruct Hinit as (v' & Hlast).\n  unfold consistent, SC; rewrite lower_app, lower_single; simpl.\n  rewrite read_last; eauto.\n  rewrite last_write in Hlast; clarify.\n  split; clarsimp; eauto.\nQed.\n\nLemma can_read_unique : forall m p v v'\n  (Hinit : initialized m p) (Hv : can_read m p v) (Hv' : can_read m p v'),\n  v' = v.\nProof.\n  unfold can_read; intros.\n  exploit consistent_app_SC; eauto; intro.\n  unfold consistent, SC, lower in *.\n  rewrite map_app, flatten_app in *; clarify.\n  destruct Hinit.\n  rewrite read_last in Hv, Hv'; eauto; clarify.\nQed.\n\nLemma init_step : forall m p a (Hinit : initialized m p) (Hprog : prog_op a),\n  initialized (m ++ [a]) p.\nProof.\n  unfold initialized; clarify.\n  rewrite lower_app, lower_single; destruct a; clarify.\n  - exists x; rewrite last_op_app; right; clarify.\n  - destruct (eq_dec x0 p).\n    + subst; exists v; rewrite last_op_app; left.\n      setoid_rewrite last_single; clarify.\n    + exists x; rewrite last_op_app; right; clarify.\n  - destruct (eq_dec x0 p).\n    + subst; exists v'; rewrite last_op_app; left.\n      exists 1; clarify.\n      econstructor; simpl; eauto.\n      destruct j; clarify.\n      destruct j; clarsimp.\n    + exists x; rewrite last_op_app; right; clarify.\nQed.\n\nLemma init_steps : forall m p s (Hinit : initialized m p) (Hprog : Forall prog_op s),\n  initialized (m ++ s) p.\nProof.\n  intros. generalize dependent m. induction s. \n  -intros. rewrite app_nil_r. auto.\n  -intros. rewrite split_app. apply IHs.\n   +rewrite Forall_forall in *. intros. clarify.\n   +apply init_step; auto.\n    eapply Forall_inv. eauto.\nQed.\n\nLemma ARW_can_read : forall p m v v' t, consistent (m ++ [ARW t p v v']) ->\n  can_read m p v.\nProof.\n  intros; rewrite can_arw_SC_iff in H; specialize (H 0).\n  exploit consistent_app_SC; eauto; intro.\n  eapply can_read_thread'; eauto.\nQed.\n\nLemma can_read_arwritten : forall m p u v t, consistent (m ++ [ARW t p u v]) ->\n  can_read (m ++ [ARW t p u v]) p v.\nProof.\n  intros.\n  apply (can_read_thread' _ _ _ t).\n  rewrite read_arwritten_SC; auto.\nQed.\n\nDefinition mem_ext m1 m2 := (forall ops, consistent (m1 ++ ops) <->\n  consistent (m2 ++ ops)) /\\ forall p, initialized m1 p <-> initialized m2 p.\n\nLemma mem_ext_app : forall m1 m2 ops, mem_ext m1 m2 ->\n  mem_ext (m1 ++ ops) (m2 ++ ops).\nProof.\n  repeat intro; split; intro.\n  - repeat rewrite <- app_assoc.\n    destruct H as [H _]; rewrite H; reflexivity.\n  - unfold initialized.\n    repeat rewrite lower_app; split; intros (v & Hlast);\n      rewrite last_op_app in Hlast; destruct Hlast;\n      try solve [exists v; rewrite last_op_app; clarify].\n    + destruct H as [_ H]; specialize (H p); destruct H as [H _].\n      clarify; exploit H; unfold initialized; eauto.\n      intros (v' & ?); exists v'; rewrite last_op_app; clarify.\n    + destruct H as [_ H]; specialize (H p); destruct H as [_ H].\n      clarify; exploit H; unfold initialized; eauto.\n      intros (v' & ?); exists v'; rewrite last_op_app; clarify.\nQed.\n\nGlobal Instance mem_ext_refl : RelationClasses.Reflexive mem_ext.\nProof. repeat intro; split; reflexivity. Qed.\n\nGlobal Instance mem_ext_sym : RelationClasses.Symmetric mem_ext.\nProof.\n  intros ?? (? & ?).\n  split; symmetry; auto.\nQed.\n\nGlobal Instance mem_ext_trans : RelationClasses.Transitive mem_ext.\nProof.\n  intros ??? (Hext1 & Hinit1) (Hext2 & Hinit2); split; intro.\n  - rewrite (Hext1 ops); auto.\n  - rewrite (Hinit1 p); auto.\nQed.\n\nLemma init_comm : forall m1 ops1 ops2 m2 p (Hprog1 : Forall prog_op ops1),\n  initialized (m1 ++ ops1 ++ ops2 ++ m2) p ->\n  initialized (m1 ++ ops2 ++ ops1 ++ m2) p.\nProof.\n  unfold initialized; clarify.\n  repeat rewrite lower_app in H; repeat rewrite lower_app.\n  repeat rewrite last_op_app in H; destruct H as [[[? | ?] | ?] | ?].\n  - exists x; repeat rewrite last_op_app; auto.\n  - destruct (find (fun c => writesb c p) (rev ops1)) eqn: Hfind.\n    + assert (exists v, write_val c = Some v) as (v & ?).\n      { rewrite find_spec in Hfind; clarify.\n        exploit nth_error_in; eauto; rewrite <- in_rev; intro.\n        rewrite Forall_forall in Hprog1; exploit Hprog1; eauto; intro.\n        destruct c; clarify; eauto. }\n      exists v; rewrite last_op_app; left.\n      rewrite last_op_app; left.\n      rewrite last_op_app; right; clarify.\n      rewrite last_write; eauto.\n    + exists x; rewrite last_op_app; left.\n      rewrite last_op_app; right; rewrite Forall_app; clarify.\n      rewrite find_fail, Forall_rev in Hfind.\n      clear - Hfind; induction ops1; clarify.\n      * unfold lower; simpl; auto.\n      * rewrite lower_cons, Forall_app; inversion Hfind; clarify.\n        destruct a; clarify; unfold beq in *; constructor; clarify.\n  - exists x; rewrite Forall_app in *; repeat rewrite last_op_app; clarify.\n  - exists x; repeat rewrite last_op_app; repeat rewrite Forall_app in *;\n      clarify.\nQed.      \n\nCorollary init_comm' : forall m1 ops1 ops2 p (Hprog1 : Forall prog_op ops1)\n  (Hprog2 : Forall prog_op ops2),\n  initialized (m1 ++ ops1 ++ ops2) p <-> initialized (m1 ++ ops2 ++ ops1) p.\nProof.\n  intros; split; intro.\n  - rewrite <- (app_nil_r (m1 ++ ops1 ++ ops2)), <- app_assoc, <- app_assoc\n      in H.\n    exploit init_comm; try apply H; auto; rewrite app_nil_r; auto.\n  - rewrite <- (app_nil_r (m1 ++ ops2 ++ ops1)), <- app_assoc, <- app_assoc\n      in H.\n    exploit init_comm; try apply H; auto; rewrite app_nil_r; auto.\nQed.\n\nLemma can_read_iff_SC: forall p ops m v\n  (Hcon : consistent (m ++ ops)) (Hprog : Forall prog_op ops)\n  (Hno_write : Forall (fun c => match c with Write _ x _ | ARW _ x _ _ => p <> x\n     | _ => True end) ops),\n  can_read (m ++ ops) p v <-> can_read m p v.\nProof.\n  induction ops; clarify.\n  { rewrite app_nil_r; reflexivity. }\n  specialize (IHops (m ++ [a]) v); rewrite <- app_assoc in *;\n    inversion Hprog; inversion Hno_write; clarify.\n  rewrite IHops.\n  destruct (eq_dec (loc_of a) p).\n  - destruct a; clarify.\n    unfold can_read; rewrite <- app_assoc.\n    simpl; rewrite read_noop_SC; [reflexivity|].\n    eapply consistent_app_SC; rewrite <- app_assoc; simpl; eauto.\n  - unfold can_read; rewrite <- app_assoc.\n    simpl; rewrite loc_valid_ops2_SC; auto.\n    + split; clarify.\n      eapply consistent_app_SC; rewrite <- app_assoc; simpl; eauto.\n    + constructor; clarify.\nQed.\n\nLemma writesb_write : forall c p v (Hwrite : writesb c p = true)\n  (Hval : write_val c = Some v),\n  exists i, nth_error (to_seq c) i = Some (MWrite p v).\nProof.\n  destruct c; clarify.\n  - unfold beq in Hwrite; exists 0; clarify.\n  - unfold beq in Hwrite; exists 1; clarify.\nQed.\n\nLemma writesb_val : forall c p (Hwrite : writesb c p = true)\n  (Hprog : prog_op c), exists v, write_val c = Some v.\nProof.\n  destruct c; clarify; eauto.\nQed.\n\nNotation lower := (@lower _ _ _ _ _ Base).\n\nTypeclasses eauto := 4.\n\nLemma lift_last : forall ops p a\n  (Hlast : last_op (lower ops) (Ptr p) a) (Hprog : Forall prog_op ops),\n  exists i w, nth_error ops i = Some w /\\ last_op (to_seq w) (Ptr p) a /\\\n    forall i2 w2, nth_error ops i2 = Some w2 -> writesb w2 p = true -> i2 <= i.\nProof.\n  intros.\n  assert (exists i, last_mod_op (lower ops) (Ptr p) i /\\\n    inth (lower ops) i = Some a) as (i & Hlast_mod & Hnth) by eauto.\n  inversion Hlast_mod; setoid_rewrite Hop1 in Hnth; clarify.\n  rewrite inth_nth_error in Hop1; generalize (nth_lower_split _ _ Hop1); \n    intros (ops1 & c & ops2 & i' & ? & Hi' & ?); clarify.\n  exists (length ops1); rewrite nth_error_split; do 2 eexists; eauto.\n  rewrite lower_app, lower_cons in Hlast.\n  repeat setoid_rewrite last_op_app in Hlast.\n  destruct Hlast as [[Hlast | Hlast] | Hlast].\n  - destruct Hlast as (i2 & Hi2).\n    specialize (Hlast0 (length (lower ops1) + (length (to_seq c) + i2))).\n    rewrite inth_nth_error, lower_app, lower_cons in Hlast0.\n    repeat rewrite nth_error_plus in Hlast0; specialize (Hlast0 a); clarsimp.\n    generalize (nth_error_lt _ _ Hi'); intro; exfalso.\n    apply plus_le_reg_l in Hlast0.\n    assert (length (to_seq c) <= i') by omega.\n    rewrite Nat.le_ngt in *; contradiction.\n  - split; [clarify | intros i2 w2 Hw2 Hmods2].\n    rewrite nth_error_app in *; destruct (lt_dec i2 (length ops1)); [omega|].\n    destruct (i2 - length ops1) eqn: Hminus; [omega | clarify].\n    rewrite Forall_app in Hprog; destruct Hprog as [_ Hprog];\n      inversion Hprog as [|??? Hprog2]; subst.\n    exploit nth_error_split'; eauto; clarify.\n    rewrite Forall_app in Hprog2; clarify; inversion Hprog22; subst.\n    exploit writesb_val; eauto; intros (v & ?).\n    exploit writesb_write; eauto; intros (i2' & ?).\n    specialize (Hlast0 (length (lower ops1) + (length (to_seq c) +\n      (length (lower x) + i2')))).\n    rewrite inth_nth_error in Hlast0; repeat rewrite lower_app in Hlast0.\n    rewrite nth_error_plus, lower_cons, nth_error_plus in Hlast0.\n    setoid_rewrite lower_app in Hlast0; rewrite nth_error_plus in Hlast0.\n    setoid_rewrite lower_cons in Hlast0; rewrite nth_error_app in Hlast0.\n    exploit nth_error_lt; eauto; clarify.\n    specialize (Hlast0 (MWrite p v)); clarify.\n    rewrite <- NPeano.Nat.add_le_mono_l in Hlast0.\n    assert (i' < length (to_seq c) + (length (lower x) + i2')) as Hlt.\n    { generalize (nth_error_lt _ _ Hi'); intro.\n      eapply lt_le_trans; [eauto | apply le_plus_l]. }\n    omega.\n  - rewrite Forall_app in *; clarify.\n    generalize (nth_error_in _ _ Hi'); intro.\n    rewrite Forall_forall in Hlast21; specialize (Hlast21 a); clarify.\nQed.\n\nLemma can_read_write_SC: forall p ops m v\n  (Hcon : consistent (m ++ ops)) (Hprog : Forall prog_op ops) c v'\n  (Hin : In c ops) (Hp : writesb c p = true) (Hv : write_val c = Some v')\n  (Hwrite : Forall (fun c => writesb c p = true -> write_val c = Some v') ops),\n  can_read (m ++ ops) p v <-> v = v'.\nProof.\n  intros.\n  unfold can_read, consistent, SC; rewrite lower_app, lower_single; simpl.\n  rewrite read_last; auto; try reflexivity.\n  assert (exists a, last_op (lower (m ++ ops)) (Ptr p) a) as (a & Hlast).\n  { exploit in_split; eauto; intros (ops1 & ops2 & ?); subst.\n    exploit writesb_write; eauto; intros (i & Hi).\n    generalize (has_last_op(op := MWrite p v') _ (length (lower m) +\n      (length (lower ops1) + i)) Hcon); intro X; use X.\n    destruct X as (i' & Hlast); inversion Hlast.\n    exists op, i'; auto.\n    { rewrite lower_app, nth_error_plus, lower_app, nth_error_plus.\n      rewrite lower_cons, nth_error_app; exploit nth_error_lt; eauto; clarify. }\n  }\n  rewrite lower_app, last_op_app in Hlast; destruct Hlast as [Hlast | Hlast].\n  - rewrite lower_app, last_op_app; left.\n    exploit lift_last; eauto; intros (? & w & ? & Hlast' & ?); clarify.\n    exploit nth_error_in; eauto; intro.\n    rewrite Forall_forall in *; exploit Hprog; eauto; intro.\n    destruct w; clarify; try rewrite last_single in Hlast'; clarify.\n    + destruct (eq_dec x0 p); clarify.\n      exploit Hwrite; eauto; simpl; unfold beq; clarify.\n    + destruct Hlast' as (i & Hlast' & ?); destruct i; inversion Hlast';\n        clarsimp.\n      destruct i; clarify; [|rewrite inth_nil in *; clarify].\n      destruct (eq_dec x0 p); clarify.\n      exploit Hwrite; eauto; simpl; unfold beq; clarify.\n  - clarify.\n    rewrite Forall_forall in Hlast2; exploit Hlast2.\n    { exploit writesb_write; eauto; clarify.\n      eapply flatten_in; setoid_rewrite in_map_iff; do 2 eexists; eauto.\n      eapply nth_error_in; eauto. }\n    clarify.\nQed.\n\nLemma writesb_loc : forall w p (Hwrite : writesb w p = true)\n  (Hprog : prog_op w), loc_of w = p.\nProof.\n  destruct w; clarify; unfold beq in *; clarify.\nQed.\n\nLemma init_snoc : forall m c p (Hinit : initialized (m ++ [c]) p),\n  writesb c p = true \\/ initialized m p.\nProof.\n  unfold initialized in *; clarify.\n  rewrite lower_app, last_op_app in Hinit; destruct Hinit; [|clarify; eauto].\n  destruct H as (i & Hlast & ?); inversion Hlast; clarsimp.\n  rewrite lower_single in H; destruct c; simpl in *;\n    try rewrite nth_error_single in *; unfold beq; clarify.\n  destruct i; clarify; rewrite nth_error_single in *; clarify.\nQed.\n\nDefinition read_val c :=\n  match c with\n  | Read _ _ v | ARW _ _ v _ => Some v\n  | _ => None\n  end.\n\nLemma no_write_read : forall c (Hprog : prog_op c)\n  (Hno_write : writesb c (loc_of c) = false), exists t p v, c = Read t p v.\nProof.\n  destruct c; clarify; unfold beq in *; clarify; eauto.\nQed.\n\nLemma ARW_write : forall m t p v v' (Hcon : consistent (m ++ [ARW t p v v']))\n  ops, consistent (m ++ ARW t p v v' :: ops) <->\n       consistent (m ++ Write t p v' :: ops).\nProof.\n  intros.\n  unfold consistent, SC in *.\n  do 2 rewrite lower_app, lower_cons; simpl.\n  rewrite split_app, to_ilist_app, to_ilist_app.\n  apply read_noop.\n  rewrite lower_app, lower_single in Hcon; simpl in Hcon.\n  eapply consistent_app; rewrite <- app_assoc; simpl; eauto.\nQed.\n\nLemma can_read_written_SC: forall m t p v (Hcon: consistent (m++[Write t p v])),\n                             can_read (m++[Write t p v]) p v.\nProof.\n  intros.\n  unfold can_read. rewrite <- app_assoc. unfold consistent, SC, seq_con in *. repeat rewrite lower_app in *. repeat rewrite lower_single in *. clarify. rewrite read_written; auto.\n  rewrite lower_app, lower_single in Hcon. clarify.\nQed.\n\nLemma consistent_next_write : forall m c1 c2 v (Hprog1 : prog_op c1)\n  (Hprog2 : prog_op c2) (Hcon : consistent (m ++ [c1]))\n  (Hloc : loc_of c1 = loc_of c2) (Hwrite : writesb c1 (loc_of c1) = true)\n  (Hval : write_val c1 = Some v)\n  (Hcond : match read_val c2 with Some v' => v' = v | None => True end),\n  consistent (m ++ [c1; c2]).\nProof.\n  intros.\n  assert (forall t, consistent (m ++ [Write t (loc_of c1) v; c2])).\n  assert (consistent (m ++ [Write (thread_of c1) (loc_of c1) v])).\n  { destruct c1; clarify.\n    rewrite ARW_write in Hcon; auto. }\n  generalize (write_any_SC _ _ _ _ H); intro Hcan.\n  intro; generalize (can_write_thread v t Hcan); intro Hcon'.\n  generalize (can_write_SC Hcan Hcon'); intro Hcan'.\n  use Hcan'; [|constructor; simpl; auto].\n  generalize (can_read_written_SC _ _ _ _ Hcon'); intro.\n  destruct c2; clarify.\n  - exploit can_read_thread; eauto.\n    rewrite <- app_assoc; simpl; eauto.\n  - exploit can_write_thread; eauto.\n    rewrite <- app_assoc; simpl; eauto.\n  - rewrite split_app; apply can_arw_SC; auto.\n  - destruct c1; clarify.\n    rewrite ARW_write; auto.\nQed.\n\nLemma read_written_SC : forall m p v v' t t'\n  (Hcon : consistent (m ++ [Write t p v])),\n  consistent (m ++ [Write t p v; Read t' p v']) <-> v' = v.\nProof.\n  intros.\n  unfold consistent, SC in *; rewrite lower_app; rewrite lower_app in Hcon.\n  rewrite lower_cons; rewrite lower_single; rewrite lower_single in Hcon;\n    simpl in *.\n  apply read_written; auto.\nQed.\n\nLemma consistent_next_write_iff : forall m c1 c2 v (Hprog1 : prog_op c1)\n  (Hprog2 : prog_op c2) (Hcon : consistent (m ++ [c1]))\n  (Hloc : loc_of c1 = loc_of c2) (Hwrite : writesb c1 (loc_of c1) = true)\n  (Hval : write_val c1 = Some v),\n  consistent (m ++ [c1; c2]) <->\n  match read_val c2 with Some v' => v' = v | None => True end.\nProof.\n  split; intro.\n  - destruct (read_val c2) eqn: Hread; auto.\n    assert (consistent (m ++ [c1; Read (thread_of c2) (loc_of c2) n])) as Hcon'.\n    { destruct c2; clarify.\n      rewrite split_app, can_arw_SC_iff in H.\n      specialize (H 0); eapply consistent_app_SC.\n      do 2 rewrite <- app_assoc in H; rewrite <- app_assoc; simpl in *; eauto. }\n    assert (consistent (m ++ [Write (thread_of c1) (loc_of c1) v;\n        Read (thread_of c2) (loc_of c2) n])).\n    { destruct c1; clarify.\n      rewrite ARW_write in Hcon'; auto. }\n    rewrite Hloc in *; rewrite <- read_written_SC; eauto.\n    eapply consistent_app_SC; rewrite <- app_assoc; simpl; eauto.\n  - eapply consistent_next_write; eauto.\nQed.\n\nLemma can_arw_SC_iff' : forall p m v v' t,\n  consistent (m ++ [ARW t p v v']) <-> can_read m p v /\\ can_write m p.\nProof.\n  intros; rewrite can_arw_SC_iff; split; intro.\n  - unfold can_write in *; split.\n    + eapply can_read_thread'.\n      specialize (H 0); eapply consistent_app_SC; eauto.\n    + intro v1; specialize (H v1); rewrite <- app_assoc in H; simpl in H. \n      rewrite read_noop_SC in H; auto.\n      eapply consistent_drop; eauto.\n  - eapply can_write_SC; clarify.\n    + apply can_read_thread; auto.\n    + constructor; simpl; auto.\nQed.\n\nLemma can_acquire_SC: forall t t' m l (Hcon: consistent (m ++ [Rel t l])),\n consistent (m ++ [Rel t l; Acq t' l]).\nProof.\n  intros. \n  rewrite split_app, can_arw_SC_iff'; split.\n  - eapply can_read_thread'; rewrite read_arwritten_SC; auto.\n  - apply can_write_SC; auto.\n    rewrite can_arw_SC_iff' in Hcon; clarify.\n    { constructor; simpl; auto. }\nQed.\n\nLemma can_release_SC: forall t m l (Hcon: consistent (m ++ [Acq t l])),\n consistent ((m ++ [Acq t l]) ++ [Rel t l]).\nProof.\n  intros. \n  rewrite can_arw_SC_iff'; split.\n  - eapply can_read_thread'; rewrite read_arwritten_SC; auto.\n  - apply can_write_SC; auto.\n    rewrite can_arw_SC_iff' in Hcon; clarify.\n    { constructor; simpl; auto. }\nQed.\n\nDefinition lock_op x a := exists t, a = Acq t x \\/ a = Rel t x.\n\nLemma lock_hold : forall m l t ops (Hinit : initialized m (l, 0))\n  (Hheld : can_read m (l, 0) (S t)) (Hcon : consistent (m ++ ops))\n  (Hprog : Forall prog_op ops) (Hlock : Forall (fun a => loc_of a = (l, 0) ->\n     lock_op l a) ops),\n  can_read (m ++ ops) (l, 0) (S t) \\/ In (Rel t l) ops.\nProof.\n  induction ops using rev_ind; clarsimp.\n  rewrite app_assoc in Hcon; exploit consistent_app_SC; eauto.\n  rewrite Forall_app in *; clarify.\n  inversion Hlock2 as [|?? Hx]; inversion Hprog2; rewrite in_app; clarify.\n  unfold can_read in *.\n  repeat rewrite <- app_assoc in *; simpl.\n  destruct (eq_dec (loc_of x) (l, 0)).\n  - unfold lock_op in Hx; clarify.\n    destruct Hx as [? | ?]; clarify.\n    + rewrite app_assoc, can_arw_SC_iff in Hcon.\n      specialize (Hcon 0); exploit consistent_app_SC; eauto; intro.\n      exploit can_read_thread'; eauto; intro.\n      rewrite app_assoc in IHops.\n      generalize (init_steps Hinit Hprog1); intro.\n      generalize (can_read_unique(m := m ++ ops)(p := (l, 0)) (S t) 0); clarify.\n    + rewrite app_assoc, can_arw_SC_iff in Hcon.\n      specialize (Hcon 0); exploit consistent_app_SC; eauto; intro.\n      exploit can_read_thread'; eauto; intro.\n      rewrite app_assoc in IHops.\n      generalize (init_steps Hinit Hprog1); intro.\n      generalize (can_read_unique(m := m ++ ops)(p := (l, 0)) (S t) (S x0));\n        intro Heq; clarify.\n      inversion Heq; auto.\n  - rewrite app_assoc, loc_valid_SC; clarify.\n    repeat rewrite <- app_assoc in *; clarify.\nQed.\n\nCorollary lock_hold2 : forall m l t ops\n  (Hcon : consistent (m ++ Acq t l :: ops))\n  (Hprog : Forall prog_op ops) (Hlock : Forall (fun a => loc_of a = (l, 0) ->\n     lock_op l a) ops),\n  can_read (m ++ Acq t l :: ops) (l, 0) (S t) \\/ In (Rel t l) ops.\nProof.\n  intros; rewrite split_app in *; apply lock_hold; auto.\n  - unfold initialized; rewrite lower_app, lower_single; simpl.\n    eexists; rewrite last_op_app; left.\n    exists 1; clarify.\n    econstructor; simpl; eauto.\n    destruct j; clarify.\n    destruct j; clarify.\n    rewrite inth_nil in *; clarify.\n  - apply can_read_arwritten.\n    eapply consistent_app_SC; eauto.\nQed.\n\nLemma delay_rel' : forall m t l ops (Hcon : consistent (m ++ [Rel t l]))\n  (Hops : Forall (fun a => loc_of a = (l, 0) -> lock_op l a) ops)\n  (Ht : Forall (fun a => a <> Rel t l) ops) (Hcon' : consistent (m ++ ops))\n  (Hprog : Forall prog_op ops) (Hinit : initialized m (l, 0)),\n  consistent (m ++ ops ++ [Rel t l]).\nProof.\n  intros.\n  rewrite app_assoc; rewrite can_arw_SC_iff' in Hcon; rewrite can_arw_SC_iff';\n    clarify; split.\n  - exploit lock_hold; eauto; clarify.\n    rewrite Forall_forall in Ht; exploit Ht; eauto; contradiction.\n  - apply can_write_SC; auto.\nQed.\n\nCorollary delay_rel : forall m t l ops (Hcon : consistent (m ++ [Rel t l]))\n  (Hops : Forall (fun a => loc_of a = (l, 0) -> lock_op l a) ops)\n  (Ht : Forall (fun a => thread_of a <> t) ops) (Hcon' : consistent (m ++ ops))\n  (Hprog : Forall prog_op ops) (Hinit : initialized m (l, 0)),\n  consistent (m ++ ops ++ [Rel t l]).\nProof.\n  intros; apply delay_rel'; auto.\n  eapply Forall_impl; [|apply Ht].\n  repeat intro; clarify.\nQed.\n\nLemma consistent_next : forall m1 m2 c1 c2\n  (Hprog1 : prog_op c1) (Hprog2 : prog_op c2)\n  (Hcon : consistent (m1 ++ [c1; c2])) (Hcon2 : consistent (m2 ++ [c1]))\n  (Himp : consistent (m1 ++ [c2]) -> consistent (m2 ++ [c2])),\n  consistent (m2 ++ [c1; c2]).\nProof.\n  intros.\n  exploit consistent_drop; eauto; intro.\n  destruct (eq_dec (loc_of c1) (loc_of c2)).\n  - destruct (writesb c1 (loc_of c1)) eqn: Hwrite.\n    + exploit writesb_val; eauto; clarify.\n      rewrite consistent_next_write_iff in Hcon; eauto.\n      rewrite consistent_next_write_iff; eauto.\n    + exploit no_write_read; try apply Hwrite; clarify.\n      rewrite read_noop_SC in Hcon; rewrite read_noop_SC; auto.\n      rewrite app_nil_r; eapply consistent_app_SC; eauto.\n  - rewrite loc_valid_SC in Hcon; clarify.\n    rewrite loc_valid_SC; clarify.\nQed.    \n\nLemma rel_rel : forall m t t' l, ~consistent (m ++ [Rel t l; Rel t' l]).\nProof.\n  repeat intro.\n  rewrite split_app, can_arw_SC_iff' in H; clarify.\n  exploit can_read_thread; eauto.\n  rewrite read_arwritten_SC; [|eapply consistent_app_SC; eauto].\n  intro Heq; inversion Heq.\nQed.\n\nLemma init_write : forall m c p (Hprog : prog_op c), writesb c p = true ->\n  initialized (m ++ [c]) p.\nProof.\n  unfold initialized; intros.\n  rewrite lower_app, lower_single.\n  setoid_rewrite last_op_app.\n  destruct c; clarify; eexists; left.\n  - unfold beq in *; clarify.\n    exists 0; split; simpl; eauto.\n    econstructor; simpl; eauto; clarify.\n    destruct j; clarify.\n    rewrite inth_nil in *; clarify.\n  - unfold beq in *; clarify.\n    exists 1; split; simpl; eauto.\n    econstructor; simpl; eauto; clarify.\n    destruct j; clarify.\n    destruct j; clarify.\n    rewrite inth_nil in *; clarify.\nQed.\n\nLemma init_can_read : forall m p (Hinit : initialized m p)\n  (Hcon : consistent m), exists v, can_read m p v.\nProof.\n  unfold initialized; intros.\n  destruct Hinit as (v & Hlast); exists v.\n  rewrite init_read; auto.\n  rewrite <- last_write; auto.\n  { eexists; eauto. }\nQed.\n\nLemma init_can_write: forall m x (Hinit : initialized m x)\n  (Hcon : consistent m), can_write m x.\nProof.\n  unfold initialized, can_write; clarify.\n  unfold consistent, SC in *; destruct Hinit as (i & Hlast & Hi).\n  rewrite lower_app, lower_single; simpl.\n  rewrite inth_nth_error in Hi; exploit nth_error_split'; eauto;\n    intros (m1 & m2 & ? & Heq); rewrite Heq in *.\n  rewrite <- app_assoc; simpl.\n  rewrite split_app, not_mod_ops_write.\n  - rewrite <- app_assoc; simpl.\n    rewrite write_not_read_single; clarify.\n    rewrite split_app in Hcon.\n    generalize (consistent_app _ _ Hcon); intro Hcon'; clarify.\n    rewrite write_any_value in Hcon'; eauto.\n  - rewrite Forall_forall; intros a ?.\n    exploit in_nth_error; eauto; intros (i' & ?).\n    inversion Hlast.\n    specialize (Hlast0 (length m1 + S i') a).\n    rewrite inth_nth_error, nth_error_plus in Hlast0; clarify.\n    destruct a; clarify; omega.\n  - rewrite <- app_assoc; simpl; auto.\nQed.\n\nLemma can_read_step' : forall m1 m2 p v c\n  (Hcan : can_read m1 p v <-> can_read m2 p v) (Hprog : prog_op c)\n  (Hcon1 : consistent (m1 ++ [c])) (Hcon2 : consistent (m2 ++ [c])),\n  can_read (m1 ++ [c]) p v <-> can_read (m2 ++ [c]) p v.\nProof.\n  intros.\n  unfold can_read; repeat rewrite <- app_assoc; simpl; split; intro;\n    eapply consistent_next; eauto; clarify.\n  - rewrite <- Hcan; auto.\n  - rewrite Hcan; auto.\nQed.    \n\nLemma loc_partition : forall f ops m (Hcon : consistent (m ++ ops))\n  ops1 ops2 (Hpart : partition f ops = (ops1, ops2))\n  (Hops : Forall prog_op ops) (Hindep : indep ops1 ops2),\n  consistent (m ++ ops2).\nProof.\n  setoid_rewrite partition_filter.\n  induction ops; clarify.\n  specialize (IHops (m ++ [a])); rewrite <- app_assoc in IHops; clarify.\n  specialize (IHops _ _ eq_refl).\n  inversion Hops; subst.\n  destruct (f a); clarify.\n  - inversion Hindep; clarify.\n    rewrite <- app_assoc, loc_valid_ops_SC in IHops; clarify.\n    apply Forall_filter; auto.\n  - rewrite <- app_assoc in IHops; apply IHops.\n    rewrite Forall_forall in *; intros ? Hin.\n    specialize (Hindep _ Hin); inversion Hindep; auto.\nQed.\n\nLemma indep_sym : forall ops1 ops2, indep ops1 ops2 -> indep ops2 ops1.\nProof.\n  repeat setoid_rewrite Forall_forall; repeat intro.\n  eapply H; eauto.\nQed.\n\nLemma loc_split_iff : forall f ops ops1 ops2\n  (Hpart : partition f ops = (ops1, ops2))\n  (Hops : Forall prog_op ops) (Hindep : indep ops1 ops2) m m2,\n  consistent (m ++ ops ++ m2) <-> consistent (m ++ ops1 ++ ops2 ++ m2).\nProof.\n  setoid_rewrite partition_filter.\n  induction ops; clarify.\n  { reflexivity. }\n  specialize (IHops _ _ eq_refl).\n  assert (indep (filter f ops) (filter (fun x : conc_op => negb (f x)) ops)).\n  { destruct (f a); clarify.\n    - inversion Hindep; auto.\n    - apply indep_sym in Hindep; apply indep_sym; inversion Hindep; auto. }\n  inversion Hops; clarify.\n  specialize (IHops (m ++ [a]) m2); repeat rewrite <- app_assoc in IHops;\n    rewrite IHops.\n  destruct (f a); clarify.\n  - reflexivity.\n  - apply loc_comm_ops1_SC; auto.\n    + apply indep_sym in Hindep; inversion Hindep; auto.\n    + apply Forall_filter; auto.\nQed.\n\nEnd SC.", "meta": {"author": "upenn-acg", "repo": "verified-tsan", "sha": "e5b0db528b1185b0fd59028271a498687dab61c1", "save_path": "github-repos/coq/upenn-acg-verified-tsan", "path": "github-repos/coq/upenn-acg-verified-tsan/verified-tsan-e5b0db528b1185b0fd59028271a498687dab61c1/SCFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.25168853978903377}}
{"text": "From iris.algebra Require Import proofmode_classes.\nFrom iris.proofmode Require Import classes.\nFrom iris.base_logic Require Export derived.\nFrom iris.prelude Require Import options.\nImport base_logic.bi.uPred.\n\n(* Setup of the proof mode *)\nSection class_instances.\n  Context {M : ucmra}.\n  Implicit Types P Q R : uPred M.\n\n  Global Instance into_pure_cmra_valid `{!CmraDiscrete A} (a : A) :\n    @IntoPure (uPredI M) (✓ a) (✓ a).\n  Proof. by rewrite /IntoPure discrete_valid. Qed.\n\n  Global Instance from_pure_cmra_valid {A : cmra} (a : A) :\n    @FromPure (uPredI M) false (✓ a) (✓ a).\n  Proof.\n    rewrite /FromPure /=. eapply bi.pure_elim=> // ?.\n    rewrite -uPred.cmra_valid_intro //.\n  Qed.\n\n  Global Instance from_sep_ownM (a b1 b2 : M) :\n    IsOp a b1 b2 →\n    FromSep (uPred_ownM a) (uPred_ownM b1) (uPred_ownM b2).\n  Proof. intros. by rewrite /FromSep -ownM_op -is_op. Qed.\n  (* TODO: Improve this instance with generic own simplification machinery\n  once https://gitlab.mpi-sws.org/iris/iris/-/issues/460 is fixed *)\n  Global Instance combine_sep_as_ownM (a b1 b2 : M) :\n    IsOp a b1 b2 →\n    CombineSepAs (uPred_ownM b1) (uPred_ownM b2) (uPred_ownM a).\n  Proof. intros. by rewrite /CombineSepAs -ownM_op -is_op. Qed.\n  (* TODO: Improve this instance with generic own validity simplification\n  machinery once https://gitlab.mpi-sws.org/iris/iris/-/issues/460 is fixed *)\n  Global Instance combine_sep_gives_ownM (b1 b2 : M) :\n    CombineSepGives (uPred_ownM b1) (uPred_ownM b2) (✓ (b1 ⋅ b2)).\n  Proof.\n    intros. rewrite /CombineSepGives -ownM_op ownM_valid.\n    by apply: bi.persistently_intro.\n  Qed.\n  Global Instance from_sep_ownM_core_id (a b1 b2 : M) :\n    IsOp a b1 b2 → TCOr (CoreId b1) (CoreId b2) →\n    FromAnd (uPred_ownM a) (uPred_ownM b1) (uPred_ownM b2).\n  Proof.\n    intros ? H. rewrite /FromAnd (is_op a) ownM_op.\n    destruct H; by rewrite bi.persistent_and_sep.\n  Qed.\n\n  Global Instance into_and_ownM p (a b1 b2 : M) :\n    IsOp a b1 b2 → IntoAnd p (uPred_ownM a) (uPred_ownM b1) (uPred_ownM b2).\n  Proof.\n    intros. apply bi.intuitionistically_if_mono. by rewrite (is_op a) ownM_op bi.sep_and.\n  Qed.\n\n  Global Instance into_sep_ownM (a b1 b2 : M) :\n    IsOp a b1 b2 → IntoSep (uPred_ownM a) (uPred_ownM b1) (uPred_ownM b2).\n  Proof. intros. by rewrite /IntoSep (is_op a) ownM_op. Qed.\nEnd class_instances.\n", "meta": {"author": "amintimany", "repo": "iris", "sha": "03eaffa3b28bffc561b93f30a3ba40bab8ae1fd1", "save_path": "github-repos/coq/amintimany-iris", "path": "github-repos/coq/amintimany-iris/iris-03eaffa3b28bffc561b93f30a3ba40bab8ae1fd1/iris/base_logic/proofmode.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.44167300566462564, "lm_q1q2_score": 0.25168853333604696}}
{"text": "Require Import ExtLib.Structures.Monad.\nRequire Import ExtLib.Structures.MonadTrans.\n\nSet Implicit Arguments.\nSet Contextual Implicit.\nSet Maximal Implicit Insertion.\n\nSection ContType.\n  Variable R : Type.\n\n(*\n  Record cont (t : Type) : Type := mkCont\n  { runCont : (t -> Ans) -> Ans }.\n\n  Global Instance Monad_cont : Monad cont :=\n  { ret  := fun _ v => mkCont (fun k => k v)\n  ; bind := fun _ c1 _ c2 =>\n    mkCont (fun k =>\n      runCont c1 (fun t =>\n        runCont (c2 t) k))\n  }.\n\n  Global Instance Cont_cont : Cont cont :=\n  { callCC := fun _ _ f => mkCont (fun c => runCont (f (fun x => mkCont (fun _ => c x))) c)\n  }.\n\n  Definition mapCont (f : Ans -> Ans) {a} (c : cont a) : cont a :=\n    mkCont (fun x => f (runCont c x)).\n\n  Definition withCont {a b} (f : (b -> Ans) -> (a -> Ans)) (c : cont a) : cont b :=\n    mkCont (fun x => runCont c (f x)).\n*)\n\n  Variable M : Type -> Type.\n\n  Record contT (A : Type) : Type := mkContT\n  { runContT : (A -> M R) -> M R }.\n\n  Global Instance Monad_contT : Monad contT :=\n  { ret := fun _ x => mkContT (fun k => k x)\n  ; bind := fun _ _ c1 c2 =>\n    mkContT (fun c =>\n      runContT c1 (fun a => runContT (c2 a) c))\n  }.\n\n  Global Instance MonadT_contT {Monad_M : Monad M} : MonadT contT M :=\n  { lift := fun _ c => mkContT (bind c)\n  }.\n\n(*\n  Definition mapContT (f : m Ans -> m Ans) {a} (c : contT a) : contT a :=\n    mkContT (fun x => f (runContT c x)).\n\n  Definition withContT {a b} (f : (b -> m Ans) -> (a -> m Ans)) (c : contT a) : contT b :=\n    mkContT (fun x => runContT c (f x)).\n*)\n\nEnd ContType.\n\nDefinition resetT {M} {Monad_M : Monad M} {R R'} (u : contT R M R) : contT R' M R :=\n  mkContT (fun k => bind (runContT u ret) k).\n\nDefinition shiftT {M} {Monad_M : Monad M} {R A}\n    (f : (A -> M R) -> contT R M R) : contT R M A :=\n  mkContT (fun k => runContT (f k) ret).\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/ContMonad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2516885333360469}}
{"text": "Require Export Normal.\nRequire Export BuildTac.\n\n\nSet Implicit Arguments.\n\nUnset Strict Implicit.\n\n\n(* *********************************************************************** *)\n(*                                  SEMANTICS                              *)\n(* *********************************************************************** *)\nParameter scale : forall (k:nat), R.\nVariable scale_pos: forall k, (0 < scale k)%R.\n\nInductive uop : Type := . \n\nInductive usupport_ (T_type:Type) \n (T_Z:T_type) (E_expr:T_type ->Type) : T_type -> Type :=\n | Gaussian : forall (i:E_expr T_Z), @usupport_ _ T_Z E_expr T_Z.\n\nModule Sem <: SEM.\n\n(** * User-defined type module *)\nModule UT <: UTYPE.\n\n Definition t := Empty_set. \n \n Definition eqb (x y:t) := true.\n\n Lemma eqb_spec : forall x y, if eqb x y then x = y else x <> y.\n Proof.\n  intros x; case x.\n Qed.\n\n Definition eq_dec (x y:t) : {x = y} + {True}.\n  intros; case x; case y.\n Defined.\n\n Lemma eq_dec_r : forall x y i, eq_dec x y = right _ i -> x <> y.\n Proof.\n  intros x; case x.\n Qed.\n\n Definition interp (k:nat) (t0:t) : Type := Datatypes.unit.\n\n Definition size k (t0:t) (_:interp k t0) := S O.\n\n Definition default k (t0:t) : interp k t0 := tt.\n\n Definition default_poly (t0:t) := pcst 1.\n\n Lemma size_positive : forall k t0 (x:interp k t0), (0 < size x)%nat.\n Proof.\n  intros; unfold size; auto with arith.\n Qed.\n\n Lemma default_poly_spec : forall k (t0:t),\n  (size (default k t0) <= peval (default_poly t0) k)%nat.\n Proof.\n  intros; unfold size, default, default_poly.\n  rewrite pcst_spec; trivial.\n Qed.\n\n Definition i_eqb k t (_:interp k t) (_:interp k t) := true.\n\n Lemma i_eqb_spec : forall k t (x y:interp k t), \n  if i_eqb x y then x = y else x <> y.\n Proof.\n  intros; unfold i_eqb; case x; case y; trivial.\n Qed.\n\nEnd UT.\n\n\nModule T := MakeType UT.\n\n\n(** * Module for user-defined operators *)\nModule Uop <: UOP UT T.\n\n Definition t := uop.\n\n Definition eqb (o1 o2:t) : bool := true.\n\n Lemma eqb_spec :  forall x y, if eqb x y then x = y else x <> y.\n Proof.\n  destruct x; destruct y; simpl.  \n Qed.\n\n Definition targs (op : t) : list T.type := nil.\n\n Definition tres (op: t) : T.type := T.Unit.\n\n\n Definition interp_op (k:nat) (op:t) : T.type_op k (targs op) (tres op) := \n  match op as op0 return T.type_op k (targs op0) (tres op0) with\n   |\n  end.\n\n Implicit Arguments interp_op [k].\n\n Definition cinterp_op (k:nat) (op:t) : T.ctype_op k (targs op) (tres op) :=\n  match op as op0 return T.ctype_op k (targs op0) (tres op0) with\n   |\n   end.\n\n Implicit Arguments cinterp_op [k].\n \n Definition eval_op k\n  (op:t) (args:dlist (T.interp k) (targs op)) : T.interp k (tres op) :=\n  @T.app_op k (targs op) (tres op) (interp_op op) args.\n\n Definition ceval_op k \n  (op:t) (args:dlist (T.interp k) (targs op)) : T.interp k (tres op) * nat :=\n  @T.capp_op k (targs op) (tres op) (cinterp_op op) args.\n\n Lemma ceval_op_spec : forall k op args,\n  @eval_op k op args = fst (@ceval_op k op args).\n Proof.\n  intros k o args; destruct o; simpl in args;\n   T.dlist_inversion args; subst; simpl; trivial.\n Qed.\n\nEnd Uop.\n\n\nModule Var := MakeVar UT T.\n\nModule Proc := MakeProc UT T.\n\nModule O := MakeOp UT T Uop.\n\nModule Mem := MakeMem UT T Var.\n\nModule E := MakeExpr UT T Var Mem Uop O.\n\nModule US <: USUPPORT UT T Var Mem Uop O E.\n\n Module VarP := MkEqBool_Leibniz_Theory Var.\n Module Vset := MkListSet VarP.Edec.\n\n Definition usupport := usupport_ T.Zt E.expr .\n\n Definition eval k t (s:usupport t) (m:Mem.t k) : Distr (T.interp k t) :=\n  match s with\n   | Gaussian a => Normal (scale k) (E.eval_expr a m)\n  end.\n\n Definition ceval k t (s:usupport t) (m:Mem.t k) : Distr (T.interp k t) * nat :=\n  match s with\n   |  Gaussian a => (Normal (scale k) (E.eval_expr a m), T.size k T.Zt (E.eval_expr a m))\n  end.\n\n Lemma ceval_spec : forall k t (s:usupport t) (m:Mem.t k), \n  eval s m = fst (ceval s m).\n Proof.\n  intros; case s; intros; simpl; trivial.\n Qed.   \n\n\n (** TODO: add to EXPR *)\n Fixpoint fv_expr_rec (t:T.type) (res:Vset.t) (e:E.expr t) {struct e} : Vset.t :=\n  match e with \n   | E.Ecte _ _ => res \n   | E.Evar t x => Vset.add x res \n   | E.Eop op args => dfold_left fv_expr_rec args res\n   | E.Eexists t x e1 e2 => \n     Vset.union \n     (Vset.remove x (fv_expr_rec Vset.empty e1)) \n     (fv_expr_rec res e2)\n   | E.Eforall t x e1 e2 => \n     Vset.union \n     (Vset.remove x (fv_expr_rec Vset.empty e1))\n     (fv_expr_rec res e2)\n   | E.Efind t x e1 e2 => \n     Vset.union \n     (Vset.remove x (fv_expr_rec Vset.empty e1))\n     (fv_expr_rec res e2)\n  end.\n\n Definition fv_expr t := @fv_expr_rec t Vset.empty.\n\n Let req_mem k X (m1 m2:Mem.t k) := \n  forall t (x:Var.var t), Vset.mem x X -> m1 x = m2 x.\n\n Lemma req_mem_weaken : forall k X X',\n  Vset.subset X X' -> forall (m m':Mem.t k), req_mem X' m m' -> req_mem X m m'.\n Proof.\n  unfold req_mem; intros; eauto using Vset.subset_correct.\n Qed.\n\n Let depend_only_distr (X:Vset.t) t (s:usupport t) :=\n  forall k (m1 m2:Mem.t k), \n   req_mem X m1 m2 -> eval s m1 = eval s m2.\n \n Let depend_only (X:Vset.t) t (e:E.expr t) := \n  forall k (m1 m2:Mem.t k), req_mem X m1 m2 -> E.eval_expr e m1 = E.eval_expr e m2.\n \n Axiom depend_only_fv_expr : forall t (e:E.expr t), depend_only (fv_expr e) e.\n\n Definition fv_distr t (s:usupport t) : Vset.t :=\n  match s with\n   | Gaussian a => (fv_expr a)\n  end.\n\n Lemma depend_only_fv_distr : forall t (s:usupport t), \n  depend_only_distr (fv_distr s) s.\n Proof.\n  intros t s k m1 m2 Hm.\n  destruct t; destruct s; simpl in *;\n   ((rewrite (depend_only_fv_expr Hm); trivial) || trivial).\n Qed.\n\n Lemma lossless_support : forall k t (s:usupport t) (m:Mem.t k),\n  mu (eval s m) (fun _ => 1)%U == 1%U.\n Proof.\n  intros; destruct s.\n  apply (Normal_lossless _ _).\n Qed.\n\n Lemma discrete_support : forall k t (s:usupport t) (m:Mem.t k),\n  is_Discrete (eval s m).\n Proof.\n  intros; destruct s; simpl.\n  apply Normal_Discrete.\n Qed.\n\n Definition eqb (t1 t2:T.type) (s1:usupport t1) (s2:usupport t2) : bool :=\n  match s1, s2 with\n  | Gaussian a, Gaussian a' => E.eqb a a' \n  end.\n\n Lemma eqb_spec_dep :  forall t1 (e1 : usupport t1) t2 (e2:usupport t2),\n  if eqb e1 e2 then eq_dep T.type usupport t1 e1 t2 e2\n  else ~eq_dep T.type usupport t1 e1 t2 e2.\n Proof.\n  intros t1 u1 t2 u2; destruct u1; destruct u2; simpl.\n  generalize (E.eqb_spec i i0); destruct (E.eqb i i0); intros; simpl; \n   intros; subst; trivial; intro W; inversion W; tauto.\n Qed.\n\n Lemma eqb_spec : forall t (e1 e2:usupport t),\n  if eqb e1 e2 then e1 = e2 else e1 <> e2.\n Proof.\n  intros t e1 e2.\n  generalize (eqb_spec_dep e1 e2).\n  case (eqb e1 e2); intro H.\n  apply T.eq_dep_eq; trivial.\n  intro Heq; apply H; rewrite Heq; constructor.\n Qed.\n\nEnd US.\n\n\nModule DE := MakeDExpr UT T Var Mem Uop O E US.\n\nModule I := MakeInstr UT T Var Proc Uop O Mem E US DE.\n\nModule SemI := SemInstr.Make UT T Var Proc Uop O Mem E US DE I.\n\n\nExport SemI.\n\n\n Notation \"{ x , .. , y }\" := \n  (@dcons T.type E.expr _ _ x .. \n   (@dcons T.type E.expr _ _ y (@dnil T.type E.expr)) ..). \n\n (* Boolean expressions *)\n Notation \"'!' x\"   := (E.Eop O.Onot { x }) (at level 60).\n Notation \"x && y\"  := (E.Eop O.Oand {x,  y}).\n Notation \"x || y\"  := (E.Eop O.Oor {x, y}).\n Notation \"x ==> y\" := (E.Eop O.Oimp {x, y}).\n Notation \"b '?' x '?:' y\" := (E.Eop (O.Oif _) {b, x, y}) (at level 60).\n\n (* pair expressions *)\n Notation \"'Efst' p\" := (E.Eop (O.Ofst _ _) { p }) (at level 0).\n Notation \"'Esnd' p\" := (E.Eop (O.Osnd _ _) { p }) (at level 0).\n Notation \"'(' x '|' y ')'\" := (E.Eop (O.Opair _ _) {x,  y} ).\n\n (* sum expressions *)\n Notation \"'Inl' x\" := (E.Eop (O.Oinl _ _) { x }) (at level 60).\n Notation \"'Inr' x\" := (E.Eop (O.Oinr _ _) { x }) (at level 60).\n Notation \"'Isl' x\" := (E.Eop (O.Oisl _ _) { x }) (at level 60).\n Notation \"'Projl' x\" := (E.Eop (O.Oprojl _ _) { x }) (at level 60).\n Notation \"'Projr' x\" := (E.Eop (O.Oprojr _ _) { x }) (at level 60).\n\n (* option expressions *)\n Notation \"'none' t\" := (E.Ecte (E.Cnone t)) (at level 0).\n Notation \"'some' x\" := (E.Eop (O.Osome _) { x }) (at level 60).\n Notation \"'IsSome' x\" := (E.Eop (O.Oissome _) { x }) (at level 60).\n Notation \"'Proj' x\" := (E.Eop (O.Oprojo _) { x }) (at level 60).\n\n (* list expressions *)\n Notation \"'Nil' t\" := (E.Ecte (E.Cnil t)) (at level 0).\n Notation \"x '|::|' y\" := \n  (E.Eop (O.Ocons _) {x, y}) (at level 60, right associativity).\n Notation \"'Etail' p\" := (E.Eop (O.Otl _) {p}) (at level 40).\n Notation \"'Ehead' p\" := (E.Eop (O.Ohd _) {p}) (at level 40).\n Notation \"'Elen' p\" := (E.Eop (O.Olength _) {p}) (at level 40).\n Notation \"x |++| l\" := \n  (E.Eop (O.Oappend _) {x,l}) (at level 60, right associativity).\n\n (* association lists *)\n Notation \"x 'in_dom' y\" := (E.Eop (O.Oin_dom _ _) {x, y}) (at level 60).\n Notation \"x 'in_range' y\" := (E.Eop (O.Oin_range _ _) {x, y}) (at level 60).\n Notation \"y '[{' x '}]'\" := (E.Eop (O.Oimg _ _) {x, y}) (at level 59).\n Notation \"l '.[{' x '<<-' v '}]'\" := \n   (E.Eop (O.Oupd _ _) {x,v,l}) (at level 50).\n\n (* nat expressions *)\n Notation \"x '+!' y\"  := (E.Eop O.Oadd {x, y}) (at level 50, left associativity).\n Notation \"x '*!' y\"  := (E.Eop O.Omul {x, y}) (at level 40, left associativity).\n Notation \"x '-!' y\"  := (E.Eop O.Osub {x, y}) (at level 50, left associativity).\n Notation \"x '<=!' y\" := (E.Eop O.Ole {x, y}) (at level 50).\n Notation \"x '<!' y\"  := (E.Eop O.Olt {x, y}) (at level 50).\n\n (* Z expressions *)\n Notation \"x '+Z' y\"   := (E.Eop O.OZadd {x, y}) (at level 50, left associativity).\n Notation \"x '*Z' y\"   := (E.Eop O.OZmul {x, y}) (at level 40, left associativity).\n Notation \"x '-Z' y\"   := (E.Eop O.OZsub {x, y}) (at level 50, left associativity).\n Notation \"x '<=Z' y\"  := (E.Eop O.OZle {x, y}) (at level 50).\n Notation \"x '<Z' y\"   := (E.Eop O.OZlt {x, y}) (at level 50).\n Notation \"x '>=Z' y\"  := (E.Eop O.OZge {x, y}) (at level 50).\n Notation \"x '>Z' y\"   := (E.Eop O.OZgt {x, y}) (at level 50).\n Notation \"'oppZ' x\"   := (E.Eop O.OZopp {x}) (at level 40).\n Notation \"x '/Z' y\"   := (E.Eop O.OZdiv {x, y}) (at level 50).\n Notation \"x 'modZ' y\" := (E.Eop O.OZmod {x, y}) (at level 50).\n Notation \"x 'powZ' y\" := (E.Eop O.OZpow {x, y}) (at level 50).\n\n (* equality *)\n Notation \"x '=?=' y\" := (E.Eop (O.Oeq_ _) {x, y}) (at level 70, no associativity).\n\n (* distribution expressions *)\n Notation \"'{0,1}'\" := DE.Dbool.\n Notation \"'[0..' e ']'\" := (DE.Dnat e)%nat.\n Notation \"'[' e1 ',,' e2 ']'\" := (DE.DZ e1 e2)%nat.\n Notation \"'Norm' a\" := (DE.Duser (@Gaussian  _ _ E.expr a)) (at level 60).\n\nEnd Sem.\n\n\n(** Semantics with optimizations *)\nModule Entries. \n\n Module SemO <: SEM_OPT.\n \n  Module Sem := Sem.\n  Export Sem.\n  \n  Definition simpl_op (op : Uop.t) : \n   E.args (Uop.targs op) -> E.expr (Uop.tres op) :=\n   match op as op0 return E.args (Uop.targs op0) -> E.expr (Uop.tres op0) with\n    | op => fun args => E.Eop (O.Ouser op) args\n   end.\n\n  Implicit Arguments simpl_op [].\n\n  Lemma simpl_op_spec : forall k op args (m:Mem.t k),\n   E.eval_expr (simpl_op op args) m = E.eval_expr (E.Eop (O.Ouser op) args) m.\n  Proof.\n   intros; simpl; trivial.\n  Qed.\n\n End SemO.\n\n Module BP := BaseProp.Make SemO.Sem.\n\nEnd Entries.\n\n\nModule Ent := Entries.\n\nModule Tactics := BuildTac.Make Ent.\nExport Tactics.\n\n\n\n\n(* *********************************************************************** *)\n(*                             GAUSSIAN MECHANISM                          *)\n(* *********************************************************************** *)\nSection GAUSSIAN_MECHANISM.\n\n Variable delta: nat -o> U.\n Variable epsilon: nat -> R.\n Hypothesis eps_pos: forall k, (0 <= epsilon k)%R.\n\n\n Variable E1 E2 : env.\n Variable a1 : Var.var T.Zt.\n Variable a2 : Var.var T.Zt.\n Variable r : Var.var T.Zt.\n\n Let Z_Gt := fun (L:R) (z:Z) => if Rlt_dec L (IZR z) then 1%U else D0.\n\n Let Pre  k (m1 m2:Mem.t k) := \n   let t := IZR (m1 a1 - m2 a2)%Z in\n   let alpha := ((scale k * epsilon k - Rsqr t) / (2 * Rabs t))%R in\n      (mu (Normal (scale k) 0%Z) (Z_Gt alpha) <= delta k)%tord.\n\n Lemma Gaussian_Mech: \n  eequiv Pre \n  E1 [ r <$- Norm  a1 ]\n  E2 [ r <$- Norm  a2 ]\n  (kreq_mem {{r}}) (fun k => exp (epsilon k)) delta.\n Proof.\n  intros.\n  apply eequiv_weaken with Pre (EP_eq_expr r r) \n    (fun k => exp (epsilon k))  delta; trivial.\n  unfold EP_eq_expr; intros k m1 m2 Hm t v Hv; \n   Vset_mem_inversion Hv; subst; auto.\n  refine (@eequiv_random_discr _ _ _ _ _ _ _ _ _ delta _ _);\n    [ auto | ].\n  intro k; rewrite <-exp_0; apply exp_monotonic; trivial.\n  unfold Pre; intros k m1 m2 H.\n  eapply Normal_dist; [ | intro z; apply (cover_dec  (Z_eq_dec z)) | | ].\n    apply scale_pos.\n    rewrite <-exp_0; apply exp_monotonic; trivial.\n    rewrite ln_exp; exact H.\n Qed.\n\nEnd GAUSSIAN_MECHANISM.\n\n", "meta": {"author": "initc3", "repo": "certipriv", "sha": "95e089a46715ebb5931eb54e0828dd20e70dcd58", "save_path": "github-repos/coq/initc3-certipriv", "path": "github-repos/coq/initc3-certipriv/certipriv-95e089a46715ebb5931eb54e0828dd20e70dcd58/Examples/Gaussian/Proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2516885333360469}}
{"text": "Require Import Syntax.\nRequire Import Eval.\nRequire Import Environment.\nRequire Import Monads.Monad.\nRequire Import Monads.State.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\n\nOpen Scope monad.\n(* Open Scope list_scope. *)\n\n(* Open Scope string_scope. *)\n\nDefinition states_to_block (ss: list statement) : block := List.fold_right BlockCons BlockEmpty ss.\n\nFixpoint lookup_state (states: list State.state) (name: string) : option State.state := \n  match states with\n  | List.nil => None\n  | s :: states' => if String.eqb name (State.name s) then Some s else lookup_state states' name\n  end.\n\n\nDefinition step (p: Parser.parser) (start: string) : env_monad string := \n  match lookup_state (Parser.states p) start with\n  | Some nxt => \n    let* _ := eval_statement (BlockStatement (states_to_block (State.statements nxt))) in\n      eval_transition (State.transition nxt)\n  | None     => state_fail Internal\n  end.\n\n(* TODO: formalize progress with respect to a header, such that if the parser \n  always makes forward progress then there exists a fuel value for which\n  the parser either rejects or accepts (or errors, but not due to lack of fuel) \n*)\nFixpoint step_trans (p: Parser.parser) (fuel: nat) (start: string) : env_monad unit := \n  match fuel with \n  | 0   => state_fail Internal (* TODO: add a separate exception for out of fuel? *)\n  | S x => let* state' := step p start in \n    match state' with\n    | \"accept\"    => mret tt\n    | \"reject\"    => state_fail Reject\n    | name    => step_trans p x name\n    end\n  end. \n  ", "meta": {"author": "cornell-netlab", "repo": "poulet4", "sha": "148afb626ec0c91ee43d7b624014fe0f21cc1fef", "save_path": "github-repos/coq/cornell-netlab-poulet4", "path": "github-repos/coq/cornell-netlab-poulet4/poulet4-148afb626ec0c91ee43d7b624014fe0f21cc1fef/lib/Step.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.25167971635904984}}
{"text": "(* ** Consistency *)\n\nFrom Undecidability.FOL Require Import Syntax.Facts Deduction.FragmentNDFacts Syntax.Theories.\nFrom Undecidability.Synthetic Require Import Definitions DecidabilityFacts EnumerabilityFacts ListEnumerabilityFacts ReducibilityFacts.\nFrom Undecidability Require Import Shared.ListAutomation Shared.Dec.\nFrom Undecidability Require Import Shared.Libs.PSL.Vectors.Vectors Shared.Libs.PSL.Vectors.VectorForall.\nImport ListAutomationNotations.\n\n\nSection Consistency.\n  Context {Σf : funcs_signature} {Σp : preds_signature}.\n  Context {HdF : eq_dec Σf} {HdP : eq_dec Σp}.\n  Context {HeF : enumerable__T Σf} {HeP : enumerable__T Σp}.\n\n  Definition consistent (T : theory) := ~ T ⊢TC ⊥.\n  Definition consistent_max T := consistent T /\\ forall f, consistent (T ⋄ f) -> f ∈ T.\n\n  Lemma consistent_prv T phi :\n    consistent T -> T ⊢TC phi -> consistent (T ⋄ phi).\n  Proof.\n    intros HT Hphi. intros Hpsi2. now apply HT, (prv_T_remove Hphi).\n  Qed.\n\n  Lemma consistency_inheritance T1 T2 :\n    consistent T2 -> T1 ⊑ T2 -> consistent T1.\n  Proof.\n    intros H H2 H3. now eapply H, Weak_T, H2.\n  Qed.\n\n  Fact consistent_neg T phi :\n    consistent T -> (¬ phi) ∈ T -> ~ phi ∈ T.\n  Proof.\n    intros HT H H2. apply HT.\n    use_theory [phi; ¬ phi]. 1: intros a [<-|[<-|[]]]; easy.\n    eapply IE; apply Ctx; eauto.\n  Qed.\n\n  Fact consistent_neg2 T phi :\n    consistent T -> (T ⋄ phi) ⊢TC ⊥ -> consistent (T ⋄ (¬ phi)).\n  Proof.\n    intros HT H. now apply consistent_prv, prv_T_impl.\n  Qed.\n\n  Fact consistent_max_out T phi :\n    consistent_max T -> ~ phi ∈ T -> ~ consistent (T ⋄ phi).\n  Proof.\n    intros []; intuition.\n  Qed.\n\n  Lemma consistent_max_impl T phi psi :\n    consistent_max T -> (phi → psi ∈ T <-> (phi ∈ T -> psi ∈ T)).\n  Proof.\n    intros; split; destruct H as [H1 H2].\n    - intros H H'. apply H2. apply consistent_prv; try assumption.\n      use_theory [phi; phi → psi]. 1: intros a [<-|[<-|[]]]; easy.\n      eapply IE; apply Ctx; eauto.\n    - intros H. apply H2. intros (A & HA1 & HA2) % prv_T_impl.\n      apply H1. apply (prv_T_remove (phi := psi)).\n      + apply elem_prv, H, H2, consistent_prv. assumption. use_theory A.\n        eapply IE. 1: eapply Pc. apply II, Exp. eapply IE; [eapply Weak; [apply HA2| intros a Ha; now right]|]. apply Ctx; now left.\n      + use_theory (psi :: A). 1: intros a [<-|Ha]; cbv; eauto.\n        eapply IE; [eapply Weak; [apply HA2| intros a Ha; now right]|]. apply II,Ctx; right; now left.\n  Qed.\n\n  Section Classical.\n    Hypothesis XM : forall X, X \\/ ~ X.\n    Ltac indirect := match goal with\n                      | [ |- ?H ] => destruct (XM H); [assumption | exfalso]\n                    end.\n\n    Lemma inconsistent T phi :\n      ~ consistent (T ⋄ phi) -> T ⋄ phi ⊢TC ⊥.\n    Proof.\n      destruct (XM (T ⋄ phi ⊢TC ⊥)); tauto.\n    Qed.\n\n    Lemma consistent_max_out2 T phi :\n      consistent_max T -> ~ phi ∈ T -> (¬ phi) ∈ T.\n    Proof.\n      intros [HT1 HT2] H2. now apply consistent_max_out, inconsistent, consistent_neg2, HT2 in H2.\n    Qed.\n  End Classical.\nEnd Consistency.\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/FOL/Completeness/Consistency.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.25167971013503626}}
{"text": "Set Implicit Arguments.\n\nSection ADTValue.\n\n  Variable ADTValue : Type.\n\n  Require Import Coq.Lists.List.\n\n  Require Import Bedrock.Platform.Cito.WordMap.\n  Import WordMap.\n  Require Import Bedrock.Platform.Cito.WordMapFacts.\n  Import FMapNotations.\n  Open Scope fmap_scope.\n\n  Require Import Bedrock.Platform.Cito.GeneralTactics4.\n\n  Arguments empty {_}.\n\n  Require Import Bedrock.Platform.Cito.SemanticsUtil.\n\n  Definition make_heap' := fold_right (fun x m => @store_pair ADTValue m x) empty.\n\n  Definition no_clash A (p1 p2 : A * Value ADTValue) :=\n    match snd p1, snd p2 with\n      | ADT _, ADT _ => (fst p1 <> fst p2)%type\n      | _, _ => True\n    end.\n\n  Definition no_clash_ls A p := List.Forall (@no_clash A p).\n\n  Definition not_in_heap elt w (v : Value ADTValue) (h : WordMap.t elt) :=\n    match v with\n      | SCA _ => True\n      | ADT _ => ~ WordMap.In w h\n    end.\n\n  Require Import Coq.Setoids.Setoid.\n\n  Add Morphism (@store_pair ADTValue) with signature Equal ==> eq ==> Equal as store_pair_Equal_m.\n  Proof.\n    intros st1 st2 Heq [w v].\n    unfold store_pair.\n    destruct v.\n    eauto.\n    simpl.\n    rewrite Heq.\n    reflexivity.\n  Qed.\n\n  Add Parametric Morphism elt : (@not_in_heap elt) with signature eq ==> eq ==> Equal ==> iff as not_in_heap_Equal_m.\n  Proof.\n    intros w v st1 st2 Heq.\n    destruct v; simpl in *.\n    intuition.\n    rewrite Heq.\n    intuition.\n  Qed.\n  Require Import Bedrock.Word.\n\n  Lemma store_pair_comm p1 p2 h : no_clash p1 p2 -> store_pair (store_pair h p1) p2 == store_pair (store_pair h p2) p1.\n  Proof.\n    intros Hnc.\n    intros p.\n    destruct p1 as [w1 v1].\n    destruct p2 as [w2 v2].\n    unfold store_pair.\n    simpl.\n    destruct v1 as [? | a1]; destruct v2 as [? | a2]; eauto.\n    unfold no_clash in *.\n    simpl in *.\n    destruct (weq p w2) as [? | Hne2].\n    {\n      subst.\n      rewrite add_eq_o by eauto.\n      rewrite add_neq_o by eauto.\n      rewrite add_eq_o by eauto.\n      eauto.\n    }\n    rewrite add_neq_o by eauto.\n    destruct (weq p w1) as [? | Hne1].\n    {\n      subst.\n      rewrite add_eq_o by eauto.\n      rewrite add_eq_o by eauto.\n      eauto.\n    }\n    rewrite add_neq_o by eauto.\n    rewrite add_neq_o by eauto.\n    rewrite add_neq_o by eauto.\n    eauto.\n  Qed.\n\n  Definition DisjointPtrs A := List.ForallOrdPairs (@no_clash A).\n\n  Require Import Bedrock.Memory.\n\n  Definition disjoint_ptrs_ls (p : W * Value ADTValue) (pairs : list (W * Value ADTValue)):=\n    match (snd p) with\n      | SCA _ => True\n      | ADT _ => ~ List.In (fst p) (List.map fst (List.filter (fun p => is_adt (snd p)) pairs))\n    end.\n\n  Require Import Bedrock.Platform.Cito.Semantics.\n\n  Lemma disjoint_ptrs_cons_elim' pairs : forall p, disjoint_ptrs (p :: pairs) -> disjoint_ptrs_ls p pairs /\\ disjoint_ptrs pairs.\n  Proof.\n    induction pairs; simpl; intros [w1 v1] H.\n    {\n      split.\n      unfold disjoint_ptrs_ls; simpl.\n      destruct v1; intuition.\n      unfold disjoint_ptrs; simpl.\n      econstructor.\n    }\n    destruct a as [w2 v2]; simpl in *.\n    destruct v1 as [? | a1]; destruct v2 as [? | a2]; simpl in *; try solve [unfold disjoint_ptrs, disjoint_ptrs_ls in *; simpl in *; eauto].\n    {\n      inversion H; subst; clear H.\n      split; eauto.\n    }\n    {\n      inversion H; subst; clear H.\n      split; eauto.\n    }\n  Qed.\n\n  Lemma disjoint_ptrs_ls_no_clash_ls pairs : forall p, disjoint_ptrs_ls p pairs -> no_clash_ls p pairs.\n  Proof.\n    induction pairs; simpl; intros [w1 v1] H.\n    {\n      econstructor.\n    }\n    destruct a as [w2 v2]; simpl in *.\n    destruct v1 as [? | a1]; destruct v2 as [? | a2]; simpl in *; eauto.\n    {\n      unfold disjoint_ptrs_ls, no_clash_ls, no_clash in *.\n      econstructor.\n      eauto.\n      eapply Forall_forall.\n      intuition.\n    }\n    {\n      unfold disjoint_ptrs_ls, no_clash_ls, no_clash in *.\n      econstructor.\n      eauto.\n      eapply Forall_forall.\n      intuition.\n    }\n    {\n      unfold disjoint_ptrs_ls, no_clash_ls, no_clash in *; simpl in *.\n      econstructor; simpl in *.\n      eauto.\n      eapply (IHpairs (w1, ADT a1)); eauto.\n    }\n    {\n      unfold disjoint_ptrs_ls, no_clash_ls, no_clash in *; simpl in *.\n      intuition.\n      econstructor; simpl in *.\n      eauto.\n      eapply (IHpairs (w1, ADT a1)); eauto.\n    }\n  Qed.\n  Require Import Bedrock.Platform.Cito.GeneralTactics.\n\n  Lemma disjoint_ptrs_cons_elim pairs : forall p, disjoint_ptrs (p :: pairs) -> no_clash_ls p pairs /\\ disjoint_ptrs pairs.\n    intros p H.\n    eapply disjoint_ptrs_cons_elim' in H.\n    openhyp.\n    split; eauto.\n    eapply disjoint_ptrs_ls_no_clash_ls; eauto.\n  Qed.\n\n  Lemma disjoint_ptrs_DisjointPtrs ls : disjoint_ptrs ls -> DisjointPtrs ls.\n  Proof.\n    induction ls; simpl; intros H.\n    {\n      econstructor.\n    }\n    eapply disjoint_ptrs_cons_elim in H.\n    openhyp.\n    econstructor; eauto.\n    eapply IHls; eauto.\n  Qed.\n\n  Lemma no_clash_ls_not_in_heap pairs : forall w v, no_clash_ls (w, v) pairs -> not_in_heap w v (make_heap' pairs).\n  Proof.\n    induction pairs; simpl; intros w v H.\n    {\n      destruct v; simpl.\n      eauto.\n      intros Hin.\n      eapply empty_in_iff in Hin.\n      eauto.\n    }\n    inversion H; subst.\n    destruct a as [w' v'].\n    destruct v as [? | a]; simpl in *.\n    { eauto. }\n    unfold store_pair.\n    destruct v' as [? | a']; simpl in *.\n    {\n      eapply IHpairs in H3.\n      simpl in *.\n      eauto.\n    }\n    unfold no_clash in H2; simpl in *.\n    intros Hin.\n    eapply add_in_iff in Hin.\n    destruct Hin as [Hin | Hin].\n    {\n      subst; intuition.\n    }\n    eapply IHpairs in H3.\n    simpl in *.\n    intuition.\n  Qed.\n\n  Arguments store_pair {_} _ _.\n\n  Lemma fold_left_store_pair_comm pairs : forall w v h1 h2, no_clash_ls (w, v) pairs -> h2 == store_pair h1 (w, v) -> fold_left store_pair pairs h2 == store_pair (fold_left store_pair pairs h1) (w, v).\n  Proof.\n    induction pairs; simpl; intros w v h1 h2 Hnin Hh.\n    rewrite Hh; reflexivity.\n    destruct a as [w' v'].\n    inversion Hnin; subst.\n    eapply IHpairs; eauto.\n    rewrite Hh.\n    rewrite store_pair_comm by eauto.\n    reflexivity.\n  Qed.\n\n  Lemma make_heap_make_heap' pairs : disjoint_ptrs pairs -> make_heap pairs == make_heap' pairs.\n  Proof.\n    induction pairs; simpl; intros Hdisj.\n    reflexivity.\n    unfold make_heap in *.\n    simpl.\n    destruct a as [w v].\n    eapply disjoint_ptrs_cons_elim in Hdisj.\n    destruct Hdisj as [Hnin Hdisj].\n    rewrite <- IHpairs by eauto.\n    eapply fold_left_store_pair_comm; eauto.\n    reflexivity.\n  Qed.\n\n  Add Morphism (@Semantics.word_adt_match ADTValue) with signature Equal ==> eq ==> iff as word_adt_match_Equal_m.\n  Proof.\n    intros st1 st2 Heq [w v].\n    unfold Semantics.word_adt_match.\n    simpl.\n    destruct v.\n    {\n      intuition.\n    }\n    rewrite Heq.\n    intuition.\n  Qed.\n\n  Lemma mapsto_make_heap'_intro pairs :\n    disjoint_ptrs pairs ->\n    forall k (v : ADTValue),\n      List.In (k, ADT v) pairs ->\n      find k (make_heap' pairs) = Some v.\n  Proof.\n    induction pairs; intros Hdisj k v Hk; simpl in *.\n    {\n      intuition.\n    }\n    eapply disjoint_ptrs_cons_elim in Hdisj.\n    destruct Hdisj as [Hnc Hdisj].\n    destruct a as [k' v']; simpl in *.\n    unfold store_pair in *; simpl in *.\n    destruct Hk as [Hk | Hk].\n    {\n      inject Hk.\n      rewrite add_eq_o in * by eauto.\n      eauto.\n    }\n    destruct v' as [w | v']; simpl in *.\n    {\n      eapply IHpairs; eauto.\n    }\n    destruct (weq k k') as [? | Hne]; subst.\n    {\n      eapply no_clash_ls_not_in_heap in Hnc.\n      unfold not_in_heap in *.\n      eapply IHpairs in Hk; eauto.\n      contradict Hnc.\n      eapply find_Some_in; eauto.\n    }\n    rewrite add_neq_o in * by eauto.\n    eapply IHpairs in Hk; eauto.\n  Qed.\n\n  Lemma mapsto_make_heap'_elim pairs :\n    disjoint_ptrs pairs ->\n    forall k (v : ADTValue),\n      find k (make_heap' pairs) = Some v ->\n      List.In (k, ADT v) pairs.\n  Proof.\n    induction pairs; intros Hdisj k v Hk; simpl in *.\n    {\n      rewrite empty_o in *.\n      discriminate.\n    }\n    eapply disjoint_ptrs_cons_elim in Hdisj.\n    destruct Hdisj as [Hnc Hdisj].\n    destruct a as [k' v']; simpl in *.\n    unfold store_pair in *; simpl in *.\n    destruct v' as [w | v']; simpl in *.\n    {\n      unfold store_pair in *; simpl in *.\n      right.\n      eapply IHpairs; eauto.\n    }\n    destruct (weq k k') as [? | Hne]; subst.\n    {\n      rewrite add_eq_o in * by eauto.\n      inject Hk.\n      left; eauto.\n    }\n    rewrite add_neq_o in * by eauto.\n    eapply IHpairs in Hk; eauto.\n  Qed.\n\n  Lemma mapsto_make_heap'_iff pairs :\n    disjoint_ptrs pairs ->\n    forall k (v : ADTValue),\n      List.In (k, ADT v) pairs <->\n      find k (make_heap' pairs) = Some v.\n  Proof.\n    intros Hdisj k v; split; intros H.\n    - eapply mapsto_make_heap'_intro; eauto.\n    - eapply mapsto_make_heap'_elim; eauto.\n  Qed.\n\n  Arguments word_scalar_match {ADTValue} _.\n\n  Require Bedrock.Platform.Cito.Inv. (* for preventing bad universe unification *)\n\n  Lemma DisjointPtrs_good_scalars_forall_word_adt_match : forall pairs h, DisjointPtrs pairs -> List.Forall word_scalar_match pairs -> List.Forall (word_adt_match (fold_left store_pair pairs h)) pairs.\n  Proof.\n    induction pairs; simpl; try solve [intuition].\n    intros h Hdisj H.\n    inversion H; subst.\n    inversion Hdisj; subst.\n    destruct a as [w v]; simpl in *.\n    econstructor.\n    {\n      rewrite fold_left_store_pair_comm; try reflexivity; trivial. (* this [rewrite] will incorrectly unify universes in >= 8.5 without the [Require Bedrock.Platform.Cito.Inv.] *)\n      unfold word_adt_match.\n      unfold Semantics.word_adt_match.\n      unfold word_scalar_match in *.\n      simpl in *.\n      destruct v; simpl in *; trivial.\n      unfold store_pair; simpl.\n      rewrite add_eq_o by eauto.\n      eauto.\n    }\n    eapply IHpairs; eauto.\n  Qed.\n\n  Lemma disjoint_ptrs_good_scalars_good_inputs pairs :\n    @disjoint_ptrs ADTValue pairs ->\n    good_scalars pairs ->\n    good_inputs (make_heap pairs) pairs.\n  Proof.\n    intros Hdisj Hgs.\n    split; eauto.\n    eapply DisjointPtrs_good_scalars_forall_word_adt_match; eauto.\n    eapply disjoint_ptrs_DisjointPtrs; eauto.\n  Qed.\n\n  Lemma good_inputs_add addr (a : ADTValue) h : ~ In addr h -> good_inputs (add addr a h) ((addr, ADT a) :: nil).\n  Proof.\n    intros Hnin.\n    unfold good_inputs.\n    unfold Semantics.good_inputs.\n    unfold Semantics.disjoint_ptrs.\n    unfold Semantics.word_adt_match.\n    simpl.\n    split.\n    - repeat econstructor; simpl.\n      rewrite add_eq_o by eauto.\n      eauto.\n    - repeat econstructor; eauto.\n  Qed.\n\n  Local Open Scope fmap_scope.\n\n  Lemma good_inputs_make_heap_submap h pairs :\n    good_inputs (ADTValue := ADTValue) h pairs ->\n    make_heap pairs <= h.\n  Proof.\n    intros Hgi.\n    destruct Hgi as [Hforall Hdisj].\n    unfold good_inputs in *.\n    intros k1 v Hk1.\n    rewrite make_heap_make_heap' in * by eauto.\n    eapply mapsto_make_heap'_iff in Hk1; eauto.\n    eapply Forall_forall in Hforall; eauto.\n    unfold word_adt_match in *.\n    simpl in *.\n    eauto.\n  Qed.\n\n  Lemma forall_word_adt_match_good_scalars : forall h pairs, List.Forall (word_adt_match h) pairs -> List.Forall (@word_scalar_match ADTValue) pairs.\n    intros.\n    eapply Locals.Forall_weaken.\n    2 : eassumption.\n    intros.\n    destruct x.\n    unfold word_adt_match, Semantics.word_adt_match, word_scalar_match in *; simpl in *.\n    destruct v; simpl in *; intuition.\n  Qed.\n\n  Require Import ListFacts3.\n\n  Lemma core_eq_func_eq f1 (H1 : is_no_dup (FuncCore.ArgVars f1) = true) f2 (H2 : is_no_dup (FuncCore.ArgVars f2) = true) : f1 = f2 -> {| Fun := f1; NoDupArgVars := H1 |} = {| Fun := f2; NoDupArgVars := H2 |}.\n  Proof.\n    intros.\n    subst.\n    f_equal.\n    Require Import BoolFacts.\n    eapply bool_irre.\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/SemanticsFacts9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.25167971013503626}}
{"text": "(******************************************************************************)\n(** * Definition of the Power memory model *)\n(******************************************************************************)\nFrom hahn Require Import Hahn.\nRequire Import Events.\nRequire Import Execution.\n\nSet Implicit Arguments.\n\nSection Power_fences.\n\nVariable G : execution.\n\nNotation \"'E'\" := (acts_set G).\nNotation \"'lab'\" := (lab G).\nNotation \"'sb'\" := (sb G).\nNotation \"'rf'\" := (rf G).\nNotation \"'co'\" := (co G).\nNotation \"'rmw'\" := (rmw G).\nNotation \"'data'\" := (data G).\nNotation \"'addr'\" := (addr G).\nNotation \"'ctrl'\" := (ctrl G).\n(* Notation \"'ctrli'\" := (ctrli G). *)\nNotation \"'deps'\" := (deps G).\nNotation \"'fre'\" := (fre G).\nNotation \"'rfe'\" := (rfe G).\nNotation \"'coe'\" := (coe G).\nNotation \"'rfi'\" := (rfi G).\nNotation \"'fri'\" := (fri G).\nNotation \"'fr'\" := (fr G).\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)).\nNotation \"'RW'\" := (R ∪₁ W).\nNotation \"'FR'\" := (F ∪₁ R).\nNotation \"'FW'\" := (F ∪₁ W).\n\nNotation \"'F^lwsync'\" := (F ∩₁ (fun a => is_true (is_ra lab a))).\nNotation \"'F^sync'\" := (F ∩₁ (fun a => is_true (is_sc lab a))).\n\nImplicit Type WF : Wf G.\n\nDefinition sync := ⦗RW⦘ ⨾ sb ⨾ ⦗F^sync⦘ ⨾ sb ⨾ ⦗RW⦘.\nDefinition lwsync := (⦗RW⦘ ⨾ sb ⨾ ⦗F^lwsync⦘ ⨾ sb ⨾ ⦗RW⦘) \\ (fun x y => W x /\\ R y).\nDefinition fence := sync ∪ lwsync.\n\n(******************************************************************************)\n(** ** Relations in graph *)\n(******************************************************************************)\n\nLemma wf_syncE WF: sync ≡ ⦗E⦘ ⨾ sync ⨾ ⦗E⦘.\nProof using.\nsplit; [|basic_solver].\nunfold sync.\nrewrite (wf_sbE) at 1 2.\nbasic_solver 42.\nQed.\n\nLemma wf_lwsyncE WF: lwsync ≡ ⦗E⦘ ⨾ lwsync ⨾ ⦗E⦘.\nProof using.\nsplit; [|basic_solver].\nunfold lwsync.\nrewrite (wf_sbE) at 1 2.\nbasic_solver 42.\nQed.\n\nLemma wf_fenceE WF: fence ≡ ⦗E⦘ ⨾ fence ⨾ ⦗E⦘.\nProof using.\nsplit; [|basic_solver].\nunfold fence.\nrewrite (wf_syncE WF) at 1.\nrewrite (wf_lwsyncE WF) at 1.\nbasic_solver 42.\nQed.\n\n(******************************************************************************)\n(** ** Domains and codomains  *)\n(******************************************************************************)\n\nLemma wf_syncD WF: sync ≡ ⦗RW⦘ ⨾ sync ⨾ ⦗RW⦘.\nProof using.\nsplit; [|basic_solver].\nunfold sync.\nbasic_solver 42.\nQed.\n\nLemma wf_lwsyncD WF: lwsync ≡ ⦗RW⦘ ⨾ lwsync ⨾ ⦗RW⦘.\nProof using.\nsplit; [|basic_solver].\nunfold lwsync.\nbasic_solver 42.\nQed.\n\nLemma wf_fenceD WF: fence ≡ ⦗RW⦘ ⨾ fence ⨾ ⦗RW⦘.\nProof using.\nsplit; [|basic_solver].\nunfold fence.\nrewrite (wf_syncD WF) at 1.\nrewrite (wf_lwsyncD WF) at 1.\nbasic_solver 42.\nQed.\n\n(******************************************************************************)\n(** ** Properties *)\n(******************************************************************************)\n\nLemma sync_in_sb : sync ⊆ sb.\nProof using.\nunfold sync; generalize (@sb_trans G); basic_solver.\nQed.\n\nLemma lwsync_alt : lwsync ≡ \n  ⦗R⦘ ⨾ sb ⨾ ⦗F^lwsync⦘ ⨾ sb ⨾ ⦗RW⦘ ∪ ⦗W⦘ ⨾ sb ⨾ ⦗F^lwsync⦘ ⨾ sb ⨾ ⦗W⦘.\nProof using.\nunfold lwsync.\nsplit.\nby apply inclusion_minus_l; basic_solver 12.\nby unfolder; ins; desf; splits; eauto 10; intro; type_solver.\nQed.\n\nLemma lwsync_in_sb : lwsync ⊆ sb.\nProof using.\nrewrite lwsync_alt.\ngeneralize (@sb_trans G); basic_solver.\nQed.\n\nLemma fence_in_sb : fence ⊆ sb.\nProof using.\nunfold fence.\nrewrite sync_in_sb, lwsync_in_sb.\nbasic_solver.\nQed.\n\nLemma sync_sb_w_in_sync WF : sync ⨾ sb ⨾ ⦗W⦘ ⊆ sync.\nProof using.\nunfold sync.\ngeneralize (@sb_trans G).\nbasic_solver 20.\nQed.\n\nLemma sync_fri_in_sync WF : sync ⨾ fri ⊆ sync.\nProof using.\nrewrite (wf_friD WF).\nie_unfolder.\ngeneralize (sync_sb_w_in_sync WF).\nbasic_solver 12.\nQed.\n\nLemma lwsync_sb_w_in_lwsync WF : lwsync ⨾ sb ⨾ ⦗W⦘ ⊆ lwsync.\nProof using.\nrewrite lwsync_alt.\ngeneralize (@sb_trans G).\nbasic_solver 20.\nQed.\n\nLemma lwsync_fri_in_lwsync WF : lwsync ⨾ fri ⊆ lwsync.\nProof using.\nrewrite (wf_friD WF).\nie_unfolder.\ngeneralize (lwsync_sb_w_in_lwsync WF).\nbasic_solver 12.\nQed.\n\nLemma fence_sb_w_in_fence WF : fence ⨾ sb ⨾ ⦗W⦘ ⊆ fence ⨾ ⦗W⦘.\nProof using.\nunfold fence.\ngeneralize (sync_sb_w_in_sync WF) (lwsync_sb_w_in_lwsync WF).\nbasic_solver 12.\nQed.\n\nLemma fence_fri_in_fence WF : fence ⨾ fri ⊆ fence.\nProof using.\nunfold fence.\ngeneralize (sync_fri_in_sync WF) (lwsync_fri_in_lwsync WF).\nbasic_solver 12.\nQed.\n\nLemma RW_sb_sync_in_sync : ⦗RW⦘ ⨾ sb ⨾ sync ⊆ sync.\nProof using.\nunfold sync.\ngeneralize (@sb_trans G).\nbasic_solver 12.\nQed.\n\nLemma RW_sb_lwsync_in_lwsync : ⦗RW⦘ ⨾ sb ⨾ lwsync ⨾ ⦗W⦘ ⊆ lwsync.\nProof using.\nrewrite lwsync_alt.\ngeneralize (@sb_trans G).\nbasic_solver 20.\nQed.\n\nLemma RW_sb_fence_in_fence WF: ⦗RW⦘ ⨾ sb ⨾ fence ⨾ ⦗W⦘ ⊆ fence.\nProof using.\nunfold fence.\ngeneralize (RW_sb_sync_in_sync) (RW_sb_lwsync_in_lwsync).\nbasic_solver 12.\nQed.\n\nLemma RW_sb_F_sb_W_in_fence : ⦗RW⦘ ⨾ sb ⨾ ⦗F^lwsync⦘ ⨾ sb ⨾ ⦗W⦘ ⊆ fence.\nProof using.\nunfold fence; rewrite lwsync_alt.\nbasic_solver 20.\nQed.\n\nLemma R_sb_F_sb_RW_in_fence : ⦗R⦘ ⨾ sb ⨾ ⦗F^lwsync⦘ ⨾ sb ⨾ ⦗RW⦘ ⊆ fence.\nProof using.\nunfold fence; rewrite lwsync_alt.\nbasic_solver 12.\nQed.\n\nProposition sync_trans : transitive sync.\nProof using.\nunfold sync.\napply transitiveI.\narewrite_id ⦗F^sync⦘ at 2; rels.\narewrite_id ⦗RW⦘ at 2; rels.\ngeneralize (@sb_trans G).\nbasic_solver 42.\nQed.\n\nProposition lwsync_trans : transitive lwsync.\nProof using.\napply transitiveI.\nrewrite lwsync_alt at 2.\narewrite_id !⦗F^lwsync⦘; rels.\nsin_rewrite !(rewrite_trans (@sb_trans G)).\narewrite_id ⦗W⦘ at 1; rels.\nrewrite lwsync_alt.\narewrite_id ⦗RW⦘ at 1; rels.\nrelsf.\nrewrite !seqA.\narewrite_false (⦗W⦘ ⨾ ⦗R⦘). \nby type_solver.\nrels.\narewrite_id ⦗R⦘ at 2; rels.\narewrite_id ⦗W⦘ at 3; rels.\nsin_rewrite !(rewrite_trans (@sb_trans G)).\nbasic_solver 12.\nQed.\n\nProposition lwsync_sync : lwsync ⨾ sync ⊆ sync.\nProof using.\nunfold lwsync, sync.\narewrite_id ⦗F^lwsync⦘.\ngeneralize (@sb_trans G).\nbasic_solver 42.\nQed.\n\nProposition sync_lwsync : sync ⨾ lwsync ⊆ sync.\nProof using.\nunfold lwsync, sync.\narewrite_id ⦗F^lwsync⦘.\ngeneralize (@sb_trans G).\nbasic_solver 42.\nQed.\n\nProposition fence_trans : transitive fence.\nProof using.\nunfold fence. \napply transitiveI.\nrelsf.\nsin_rewrite !(rewrite_trans sync_trans).\nsin_rewrite !(rewrite_trans lwsync_trans).\nsin_rewrite lwsync_sync.\nsin_rewrite sync_lwsync.\nbasic_solver 12.\nQed.\n\nLemma rf_fence_W_in_fence WF: rf^? ⨾ fence ⨾ ⦗W⦘ ⊆ rfe^? ⨾ fence ⨾ ⦗W⦘.\nProof using.\nrewrite (dom_l (wf_rfD WF)) at 1.\nrewrite (@rfi_union_rfe G) at 1.\narewrite(rfi ⊆ sb).\ngeneralize (RW_sb_fence_in_fence WF).\nbasic_solver 42.\nQed.\n\nEnd Power_fences.\n", "meta": {"author": "weakmemory", "repo": "imm", "sha": "7942cc3f204cabca065b8fbf749323c398bc0973", "save_path": "github-repos/coq/weakmemory-imm", "path": "github-repos/coq/weakmemory-imm/imm-7942cc3f204cabca065b8fbf749323c398bc0973/src/hardware/Power_fences.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.25167971013503626}}
{"text": "From iris.proofmode Require Import tactics.\nFrom iris.algebra Require Import auth excl.\nFrom iris.base_logic.lib Require Import invariants.\nFrom intensional.heap_lang Require Import lifting proofmode notation.\nFrom intensional.heap_lang Require Import adequacy.\nFrom intensional.examples Require Import stdpp_extra tactics.\nSet Default Proof Using \"Type\".\nImplicit Types t : list val.\n\n(** ** Enforcing a well-bracketing protocol (Section 5.3) *)\n\n(** *** Separation logic specification *)\n\nDefinition withRes_spec `{!heapG Σ} (locked: iProp Σ) (unlocked: val → iProp Σ) (withRes: val): iProp Σ :=\n  ∀ P Q (f: val),\n    {{{ locked ∗ P ∗\n        (∀ (y x: val), {{{ unlocked y ∗ P }}} f x {{{ RET #(); unlocked y ∗ Q }}})\n    }}}\n      withRes f\n    {{{ RET #(); locked ∗ Q }}}.\n\nDefinition op_spec `{!heapG Σ} (locked: iProp Σ) (unlocked: val → iProp Σ) (op: val): iProp Σ :=\n  ∀ (x y: val), {{{ unlocked y }}} op x {{{ RET #(); unlocked y }}}.\n\nDefinition bfilelib_spec `{!heapG Σ} (P0: iProp Σ) (lib: val): iProp Σ :=\n  ∃ (locked: iProp Σ) (unlocked: val → iProp Σ),\n  □ (P0 -∗ locked) ∗\n  match lib with\n  | (withRes, op)%V =>\n    withRes_spec locked unlocked withRes ∗\n    op_spec locked unlocked op\n  | _ => False\n  end.\n\n(** *** The trace property [bfile_trace]: \"clients only use the operation after having acquired the resource and before releasing it\". *)\n\nSection Trace.\n\nInductive op_trace : list val → Prop :=\n| op_trace_nil : op_trace []\n| op_trace_call t :\n    op_trace t →\n    op_trace (t ++ [(#\"call:op\", #())%V; (#\"ret:op\", #())%V]).\n\nInductive withRes_trace : list val → Prop :=\n| withRes_trace_nil : withRes_trace []\n| withRes_trace_call t t_op f :\n    withRes_trace t →\n    op_trace t_op →\n    withRes_trace (t ++ [(#\"call:withRes\", f)%V; (#\"call\", f)%V]\n                     ++ t_op\n                     ++ [(#\"ret\", f)%V; (#\"ret:withRes\", f)%V]).\n\nDefinition bfile_trace t :=\n  ∃ t', t `prefix_of` t' ∧ withRes_trace t'.\n\n(* *** *)\n\nDefinition trace1 t f :=\n  ∃ t', withRes_trace t' ∧ t = t' ++ [(#\"call:withRes\", f)%V].\n\nDefinition trace2 t (f:val) :=\n  ∃ t' t_op, withRes_trace t'\n           ∧ op_trace t_op\n           ∧ t = t' ++ [(#\"call:withRes\", f)%V; (#\"call\", f)%V] ++ t_op.\n\nDefinition trace3 t (f: val) :=\n  ∃ t' t_op, withRes_trace t'\n           ∧ op_trace t_op\n           ∧ t = t' ++ [(#\"call:withRes\", f)%V; (#\"call\", f)%V]\n                    ++ t_op\n                    ++ [(#\"ret\", f)%V].\n\nEnd Trace.\n\n(** *** Definition and correctness of the wrapper code *)\n\nModule Wrap.\nSection S.\nContext {Σ: gFunctors}.\nContext `{heapG Σ}.\nContext (N: namespace).\n\nContext (locked_impl: iProp Σ) (unlocked_impl: val → iProp Σ).\nContext (withRes_impl op_impl : val).\n\nDefinition withRes : val :=\n  λ: \"f\",\n    Emit (#\"call:withRes\", \"f\") ;;\n    withRes_impl (λ: \"x\",\n      Emit (#\"call\", \"f\") ;; \"f\" \"x\" ;; Emit (#\"ret\", \"f\")\n    ) ;;\n    Emit (#\"ret:withRes\", \"f\").\n\nDefinition op : val :=\n  λ: \"x\",\n    Emit (#\"call:op\", #()) ;;\n    op_impl \"x\" ;;\n    Emit (#\"ret:op\", #()).\n\nDefinition T0 : iProp Σ :=\n  ∃ t, trace_is t ∗ trace_inv N bfile_trace ∗ ⌜ withRes_trace t ⌝.\n\nDefinition T1 f : iProp Σ :=\n  ∃ t, trace_is t ∗ trace_inv N bfile_trace ∗ ⌜ trace1 t f ⌝.\n\nDefinition T2 f : iProp Σ :=\n  ∃ t, trace_is t ∗ trace_inv N bfile_trace ∗ ⌜ trace2 t f ⌝.\n\nDefinition T3 f : iProp Σ :=\n  ∃ t, trace_is t ∗ trace_inv N bfile_trace ∗ ⌜ trace3 t f ⌝.\n\nDefinition unlocked (x: val) : iProp Σ :=\n  ∃ (y z:val), ⌜x = (y, z)%V⌝ ∗ unlocked_impl y ∗ T2 z.\n\nDefinition locked : iProp Σ :=\n  locked_impl ∗ T0.\n\nLemma withRes_correct :\n  withRes_spec locked_impl unlocked_impl withRes_impl -∗\n  withRes_spec locked unlocked withRes.\nProof.\n  iIntros \"#spec\" (P Q f φ) \"!> (Hl & HP & #HS) Hφ\".\n  iDestruct \"Hl\" as \"(Hl & Ht0)\". iDestruct \"Ht0\" as (t) \"(Ht & #Hi & %)\".\n  iMod (trace_is_inv with \"Ht Hi\") as \"[Ht %]\".\n  unfold withRes. wp_pures. wp_bind (Emit _).\n  iApply (wp_emit with \"[$Ht $Hi]\"); eauto.\n  { eexists. split. 2: eapply withRes_trace_call.\n    by apply prefix_app, prefix_cons, prefix_nil.\n    auto. constructor. }\n  iIntros \"!> Ht\". wp_pures. wp_bind (withRes_impl _).\n  iApply (\"spec\" $! (P ∗ T1 f)%I (Q ∗ T3 f)%I with \"[$Hl $HP Ht]\").\n  { iSplitL \"Ht\".\n    { iExists _. iFrame \"Hi ∗\". iPureIntro. unfold trace1. go. }\n    iIntros (y x ψ) \"!> (Hu & [HP Ht1]) Hψ\". wp_pures. wp_bind (Emit _).\n    iDestruct \"Ht1\" as (t') \"(Ht' & _ & Ht1)\". iDestruct \"Ht1\" as %Ht1.\n    iApply (wp_emit with \"[$Ht' $Hi]\"); eauto.\n    { destruct Ht1 as [t'' [? ->]]. eexists. split. 2: eapply withRes_trace_call.\n      rewrite -app_assoc. apply prefix_app, prefix_cons, prefix_cons, prefix_nil.\n      eauto. constructor. }\n    iIntros \"!> Ht'\". wp_pures. wp_bind (f _).\n    iApply (\"HS\" $! (y, f)%V with \"[Hu Ht' $HP]\").\n    { iExists _, _. iSplitR. done. iFrame. iExists _. iFrame \"Hi ∗\". iPureIntro.\n      destruct Ht1 as [t'' [? ->]]. exists t'', []. repeat split; eauto. constructor.\n      by list_simplifier. }\n    iIntros \"!> [Hu HQ]\". wp_pures. iDestruct \"Hu\" as (y' z) \"(% & Hy & Ht2)\".\n    simplify_eq. iDestruct \"Ht2\" as (t'') \"(Ht'' & _ & Ht2)\". iDestruct \"Ht2\" as %Ht2.\n    destruct Ht2 as [t''' [t_op (? & ? & ->)]].\n    iApply (wp_emit with \"[$Ht'' $Hi]\"); eauto.\n    { eexists. split. 2: eapply withRes_trace_call. rewrite -app_assoc. cbn.\n      apply prefix_app, prefix_cons, prefix_cons, prefix_app, prefix_cons, prefix_nil.\n      all: eauto. }\n    iIntros \"!> Ht'''\". iApply \"Hψ\". iFrame. iExists _. iFrame \"Hi ∗\".\n    iPureIntro. exists t''', t_op. repeat split; eauto. by list_simplifier. }\n  iIntros \"!> (Hl & HQ & Ht3)\". iDestruct \"Ht3\" as (t') \"(Ht' & _ & Ht3)\".\n  iDestruct \"Ht3\" as %Ht3. destruct Ht3 as [t'' [t_op (? & ? & ->)]].\n  wp_pures. iApply (wp_emit with \"[$Ht' $Hi]\"); eauto.\n  { eexists. split. reflexivity. rewrite -!app_assoc. constructor; eauto. }\n  iIntros \"!> Ht\". iApply \"Hφ\". iFrame. iExists _. iFrame \"Hi ∗\". iPureIntro.\n  rewrite -!app_assoc. constructor; eauto.\nQed.\n\nLemma op_correct :\n  op_spec locked_impl unlocked_impl op_impl -∗\n  op_spec locked unlocked op.\nProof.\n  iIntros \"#spec\" (x y φ) \"!> Hu Hφ\". iDestruct \"Hu\" as (y' z ->) \"(Hu & Ht2)\".\n  iDestruct \"Ht2\" as (t) \"(Ht & #Hi & Ht2)\". iDestruct \"Ht2\" as %Ht2.\n  unfold op. wp_pures. wp_bind (Emit _).\n  destruct Ht2 as [t' [t_op (? & ? & ->)]].\n  iApply (wp_emit with \"[$Ht $Hi]\"); eauto.\n  { eexists. split. 2: eapply withRes_trace_call. rewrite -!app_assoc.\n    apply prefix_app, prefix_cons, prefix_cons.\n    3: apply op_trace_call. rewrite -app_assoc.\n    apply prefix_app, prefix_cons, prefix_nil. all: eauto. }\n  iIntros \"!> Ht\". wp_pures. wp_bind (op_impl _).\n  iApply (\"spec\" with \"Hu\"). iIntros \"!> Hu\". wp_pures.\n  iApply (wp_emit with \"[$Ht $Hi]\"); eauto.\n  { eexists. split. 2: eapply withRes_trace_call.\n    3: apply op_trace_call; eauto. rewrite -!app_assoc.\n    repeat first [ apply prefix_app | apply prefix_cons | apply prefix_nil ].\n    eauto. }\n  iIntros \"!> Ht\". iApply \"Hφ\". iExists _, _. iSplitR. done. iFrame.\n  iExists _. iFrame \"Hi ∗\". iPureIntro. exists t'. eexists. split; [eauto|].\n  split. apply op_trace_call; eauto. by list_simplifier.\nQed.\n\nEnd S.\n\n(** Wrapping code for an entire library *)\nDefinition lib (lib_impl: val): val :=\n  match lib_impl with\n  | (withRes_impl, op_impl)%V =>\n    (withRes withRes_impl, op op_impl)\n  | _ => #()\n  end.\n\n(** Correctness of the library wrapper *)\nLemma correct `{!heapG Σ} N P0 (lib_impl: val):\n  bfilelib_spec P0 lib_impl -∗\n  bfilelib_spec (P0 ∗ trace_is [] ∗ trace_inv N bfile_trace) (lib lib_impl).\nProof.\n  iIntros \"S\". iDestruct \"S\" as (locked_impl unlocked_impl) \"(#H0 & S)\".\n  repeat case_match; eauto. iDestruct \"S\" as \"(? & ?)\".\n  unfold bfilelib_spec.\n  iExists (locked N locked_impl), (unlocked N unlocked_impl). repeat iSplit.\n  { iIntros \"!> (HP0 & ? & #Hi)\". iDestruct (\"H0\" with \"HP0\") as \"?\". iFrame.\n    iExists _. iFrame \"Hi ∗\". iPureIntro. constructor. }\n  iApply withRes_correct; eauto.\n  iApply op_correct; eauto.\nQed.\n\nEnd Wrap.\n\n(** *** Adequacy *)\n\nDefinition bfilelibN := nroot .@ \"bfilelib\".\nDefinition empty_state : state := Build_state ∅ [] ∅.\n\n(** The trace property [bfile_trace] is satisfied at every step of the execution\n    at the level of the operational semantics. *)\nLemma wrap_bfilelib_correct (e: val → expr) (lib: val):\n  (∀ `(heapG Σ), ⊢ bfilelib_spec True lib) →\n  (∀ `(heapG Σ), ⊢ ∀ P lib, bfilelib_spec P lib -∗ {{{ P }}} e lib {{{ v, RET v; True }}}) →\n  ∀ σ' e',\n    rtc erased_step ([(#();; e (Wrap.lib lib))%E], empty_state) (e', σ') →\n    bfile_trace (trace σ').\nProof.\n  set (Σ := #[invΣ; gen_heapΣ loc val; traceΣ; proph_mapΣ proph_id (val * val)]).\n  intros Hlib Hctx σ' e' Hsteps.\n  eapply (@module_invariance Σ (HeapPreG Σ _ _ _ _)\n                             bfilelibN (@bfilelib_spec Σ) True e #() (Wrap.lib lib)\n                             bfile_trace empty_state).\n  { cbn. exists []. split; eauto; constructor. }\n  { iIntros (? ? ?) \"?\". by iApply Hctx. }\n  { iIntros (? _) \"!>\". iApply wp_value; eauto. }\n  { iIntros (?). iApply Wrap.correct. iApply Hlib. }\n  eauto.\nQed.\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/examples/well_bracketed.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521307073646, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2516457745040217}}
{"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\n(** * Extension.v : An user-defined extension to pWHILE, including\noperators corresponding to a permutation and its inverse *)\n\nRequire Export PPT.\nRequire Export BuildTac2.\nRequire Import Bitstrings.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nOpen Scope nat_scope.\n\n\nModule Type TRAPDOOR_PERM.\n\n Parameter k0 : nat -> nat.\n Parameter k1 : nat -> nat.\n Parameter n  : nat -> nat.\n\n Parameter k_spec : forall k, k = n k + k0 k + k1 k.\n \n (** * Trapdoor permutation and its inverse *)\n\n Definition Bvectork k := \n  ((Bvector (n k) *  Bvector (k1 k)) * Bvector (k0 k))%type.\n\n Parameter f : forall k, Bvectork k -> Bvectork k.\n\n Parameter finv : forall k, Bvectork k -> Bvectork k.\n\n Parameter f_spec : forall k (x:Bvectork k), finv (f x) = x.\n\n Parameter finv_spec : forall k (y:Bvectork k), f (finv y) = y.\n\n Parameter cost_f : polynomial.\n Parameter cost_finv : nat -> nat.\n\n (** Maximum number of queries made to the G oracle *)\n Parameter qG_poly : polynomial.\n\n (** Maximum number of queries made to the H oracle *)\n Parameter qH_poly : polynomial.\n\n (** Maximum number of queries made to the decryption oracle *)\n Parameter qD_poly : polynomial.\n\nEnd TRAPDOOR_PERM.\n\n\nModule Entries (TP:TRAPDOOR_PERM).\n\n Inductive ut_ : Type := \n | Bitstring_n\n | Bitstring_k0\n | Bitstring_k1.\n\n (** * User-defined type module *)\n Module Ut <: UTYPE.\n\n  Definition t := ut_. \n\n  Definition eqb (t1 t2 :t) := \n   match t1, t2 with \n   | Bitstring_n,   Bitstring_n   => true\n   | Bitstring_k0,  Bitstring_k0  => true\n   | Bitstring_k1,  Bitstring_k1  => true\n   | _, _ => false\n   end.\n\n  Lemma eqb_spec : forall x y, if eqb x y then x = y else x <> y.\n  Proof.\n   simpl; destruct x; destruct y; simpl;\n    trivial; discriminate.\n  Qed.\n\n  Definition eq_dec (x y:t) : {x = y} + {True} :=\n   match x as x0 return {x0 = y} + {True} with\n   | Bitstring_n =>\n     match y as y0 return {Bitstring_n = y0} + {True} with \n     | Bitstring_n => left _ (refl_equal _) \n     | _ => right _ I\n     end\n   | Bitstring_k0 =>\n     match y as y0 return {Bitstring_k0 = y0} + {True} with \n     | Bitstring_k0 => left _ (refl_equal _) \n     | _ => right _ I\n     end\n   | Bitstring_k1 =>\n     match y as y0 return {Bitstring_k1 = y0} + {True} with \n     | Bitstring_k1 => left _ (refl_equal _) \n     | _ => right _ I\n     end\n   end.\n\n  Lemma eq_dec_r : forall x y i, eq_dec x y = right _ i -> x <> y.\n  Proof.\n   destruct x; destruct y; simpl; intros; discriminate.\n  Qed.\n\n  Import TP.\n\n  Definition len k (t0:t) := \n   match t0 with\n   | Bitstring_n   => n k\n   | Bitstring_k0  => k0 k\n   | Bitstring_k1  => k1 k\n   end.\n\n  Definition interp k (t0:t) := \n   Bvector (len k t0).\n\n  Definition size k (t0:t) (_:interp k t0) := \n   S (len k t0).\n\n  Definition default k (t0:t) : interp k t0 := \n   Bvect_false (len k t0).\n\n  Definition default_poly (t0:t) := \n   pplus (pcst 1) pvar.\n\n  Lemma size_positive : forall k (t0:t) x, 0 < @size k t0 x.\n  Proof.\n   intros k t0 x; unfold size; auto with arith.\n  Qed.\n\n  Lemma len_le : forall k t0, len k t0 <= k.\n  Proof.\n   intros k; assert (W:=k_spec k); destruct t0; simpl; omega.\n  Qed.\n\n  Lemma default_poly_spec : forall k (t0:t), \n   @size k t0 (default k t0) <= peval (default_poly t0) k.\n  Proof.\n   intros k t0.\n   unfold size, default, default_poly.\n   rewrite pplus_spec, pcst_spec, pvar_spec; trivial.\n   simpl; apply le_n_S; apply len_le.\n  Qed.\n\n  Definition i_eqb k t (x1 x2:interp k t) := Veqb x1 x2.\n\n  Lemma i_eqb_spec : forall k t (x y:interp k t), \n   if i_eqb x y then x = y else x <> y.\n  Proof.\n   intros; refine (Veqb_spec _ _).\n  Qed.\n\n End Ut.\n\n Module T := MakeType Ut.\n\n\n Inductive usupport_ (Ut:Type) (Ttype:Type) (Tuser:Ut -> Ttype): Ttype -> Type :=\n | Usupport : forall t, usupport_ Tuser (Tuser t).\n\n Module US <: USUPPORT Ut T.\n\n  Definition usupport := usupport_ T.User.\n\n  Definition eval k t (s:usupport t) : list (T.interp k t) :=\n   match s in usupport_ _ t0 return list (T.interp k t0) with\n   | Usupport bst => bs_support (Ut.len k bst)\n   end.\n\n  Definition ceval k t (s:usupport t) : list (T.interp k t) * nat :=\n   (eval k s, 1%nat).\n\n  Lemma eval_usupport_nil : forall k t (s:usupport t), eval k s <> nil.\n  Proof.\n   destruct s; refine (@bs_support_not_nil _).\n  Qed.\n\n  Lemma ceval_spec : forall k t (s:usupport t), eval k s = fst (ceval k s).\n  Proof. \n   trivial. \n  Qed.\n\n  Definition eqb (t1 t2:T.type) (s1:usupport t1) (s2:usupport t2) : bool :=\n   T.eqb t1 t2.\n\n  Lemma eqb_spec_dep : forall t1 (e1 : usupport t1) t2 (e2:usupport t2),\n   if eqb e1 e2 then eq_dep T.type usupport t1 e1 t2 e2\n   else ~eq_dep T.type usupport t1 e1 t2 e2.\n  Proof.\n   intros.\n   destruct e1; destruct e2; unfold eqb.\n   generalize (T.eqb_spec (T.User t) (T.User t0));\n    destruct (T.eqb (T.User t) (T.User t0)); intros.\n   injection H; clear H; intros; subst; trivial.\n   intros Heq; apply H; inversion Heq; trivial.\n  Qed.\n\n  Lemma eqb_spec : forall t (e1 e2:usupport t),\n   if eqb e1 e2 then e1 = e2 else e1 <> e2.\n  Proof.\n   intros t e1 e2.\n   generalize (eqb_spec_dep e1 e2).\n   case (eqb e1 e2); intro H.\n   apply T.eq_dep_eq; trivial.\n   intro Heq; apply H; rewrite Heq; constructor.\n  Qed.\n\n End US.\n\n\n Inductive Uop : Type :=\n | Oapp_f : Uop\n | Oapp_f_inv : Uop\n | OqG : Uop\n | OqH : Uop\n | OqD : Uop \n | Oxor : Ut.t -> Uop\n | Ozero : Uop\n | Oone : Uop.\n\n Module UOp <: UOP Ut T.\n\n  Definition t := Uop.\n\n  Definition eqb (o1 o2:t) : bool := \n   match o1, o2 with\n   | Oapp_f, Oapp_f\n   | Oapp_f_inv, Oapp_f_inv\n   | OqG, OqG\n   | OqH, OqH \n   | OqD, OqD\n   | Ozero, Ozero => true\n   | Oone, Oone => true\n   | Oxor t1, Oxor t2 => Ut.eqb t1 t2 \n   | _, _ => false\n   end.\n\n   Lemma eqb_spec : forall x y, if eqb x y then x = y else x <> y.\n   Proof.\n    intros x y; case x; case y; simpl; trivial; intros;\n    try (intro; discriminate).\n    generalize (Ut.eqb_spec t1 t0); destruct (Ut.eqb t1 t0); intros.\n    rewrite H; trivial.\n    intro H1; apply H; inversion H1; trivial.\n   Qed.\n\n   Definition Tnk1 := T.Pair (T.User Bitstring_n) (T.User Bitstring_k1).\n   Definition Tk := T.Pair Tnk1 (T.User Bitstring_k0).\n\n   Definition targs (op:t) : list T.type :=\n    match op with\n    | Oapp_f => Tk :: nil\n    | Oapp_f_inv => Tk :: nil\n    | OqG | OqH | OqD | Ozero | Oone => nil\n    | Oxor t => T.User t :: T.User t :: nil\n    end.\n\n   Definition tres (op:t) : T.type :=\n    match op with \n    | Oapp_f => Tk\n    | Oapp_f_inv => Tk\n    | OqG | OqH | OqD => T.Nat\n    | Ozero => T.User Bitstring_k1\n    | Oone => T.User Bitstring_n\n    | Oxor t => T.User t\n    end.\n\n   Import TP.\n\n   Definition interp_op (k:nat) (op:t) : T.type_op k (targs op) (tres op) :=\n    match op as op0 return T.type_op k (targs op0) (tres op0) with \n    | Oapp_f => @f k\n    | Oapp_f_inv => @finv k\n    | OqG => peval qG_poly k\n    | OqH => peval qH_poly k\n    | OqD => peval qD_poly k\n    | Oxor t => BVxor (Ut.len k t)\n    | Ozero => Bvect_false (k1 k)\n    | Oone => Bvect_true (n k)\n    end.\n\n   Implicit Arguments interp_op [k].\n\n   Definition cinterp_op (k:nat) (op:t) : T.ctype_op k (targs op) (tres op) :=\n    match op as op0 return T.ctype_op k (targs op0) (tres op0) with\n    | Oapp_f => fun v => (@f k v, peval cost_f k)\n    | Oapp_f_inv => fun v => (@finv k v, cost_finv k)\n    | OqG => (peval qG_poly k, 1)\n    | OqH => (peval qH_poly k, 1)\n    | OqD => (peval qD_poly k, 1)\n    | Oxor t => fun v1 v2 => (BVxor (Ut.len k t) v1 v2, Ut.len k t)\n    | Ozero => (Bvect_false (k1 k), 1)\n    | Oone => (Bvect_true (n k), 1)\n    end.\n\n   Implicit Arguments cinterp_op [k].\n\n   Definition eval_op k\n    (op:t) (args: dlist (T.interp k) (targs op)) : T.interp k (tres op) :=\n    @T.app_op k (targs op) (tres op) (interp_op op) args.\n\n   Definition ceval_op k \n    (op:t) (args: dlist (T.interp k) (targs op)) : T.interp k (tres op) * nat :=\n    @T.capp_op k (targs op) (tres op) (cinterp_op op) args.\n\n   Lemma ceval_op_spec : forall k op args,\n    @eval_op k op args = fst (@ceval_op k op args).\n   Proof.\n    intros k o args; destruct o; simpl in args;\n    T.dlist_inversion args; rewrite Heq; trivial.\n   Qed.\n\n End UOp.\n\n Export TP.\n\n (** Semantics with optimizations *)\n Module SemO <: SEM_OPT.\n\n  Module Sem := MakeSem.Make Ut T UOp US.\n  Import Sem.\n\n  (* The trapdoor permutation and its inverse *)\n  Notation \"'{0,1}^k0'\" := (E.Duser (Usupport T.User Bitstring_k0)).\n  Notation \"'{0,1}^n'\" := (E.Duser (Usupport T.User Bitstring_n)).\n  Notation \"'{0,1}^k1'\" := (E.Duser (Usupport T.User Bitstring_k1)).\n\n  Notation \" x '|x|' y \" := (E.Eop (O.Ouser (Oxor _)) {x, y}) (at level 50, left associativity).\n  Notation \"'ap_f' x\" := (E.Eop (O.Ouser Oapp_f) {x}) (at level 40).\n  Notation \"'ap_finv' x\" := (E.Eop (O.Ouser Oapp_f_inv) {x}) (at level 40).\n  Notation \"'qG'\" := (E.Eop (O.Ouser OqG) (dnil _)).\n  Notation \"'qH'\" := (E.Eop (O.Ouser OqH) (dnil _)).   \n  Notation \"'qD'\" := (E.Eop (O.Ouser OqD) (dnil _)).\n  Notation zero_k1 := (E.Eop (O.Ouser Ozero) (dnil _)).\n  Notation one_n := (E.Eop (O.Ouser Oone) (dnil _)).\n \n  Definition simpl_op (op:Uop.t) (args:E.args (Uop.targs op)) :=\n   E.Eop (O.Ouser op) args.\n\n  Implicit Arguments simpl_op [].\n\n  Lemma simpl_op_spec : forall k op args (m:Mem.t k),\n   E.eval_expr (simpl_op op args) m = E.eval_expr (E.Eop (O.Ouser op) args) m.\n  Proof. \n   trivial.\n  Qed.\n\n End SemO.\n  \n Module BP := BaseProp.Make SemO.Sem.\n  \n Module Uppt.\n\n  Import BP.\n  Import SemO.\n   \n  Implicit Arguments T.size [k t].\n\n  (** PPT expression *)\n  Definition PPT_expr (t:T.type) (e:E.expr t) \n   (F:polynomial -> polynomial) \n   (G:polynomial -> polynomial) : Prop :=\n   forall k (m:Mem.t k) p,\n    (forall t (x:Var.var t), \n     BP.Vset.mem x (BP.fv_expr e) -> T.size (m x) <= peval p k)  ->\n    let (v,n) := E.ceval_expr e m in\n     T.size v <= peval (F p) k /\\\n     n <= peval (G p) k.\n\n   (** PPT support *)\n   Definition PPT_support t (s:E.support t)\n   (F:polynomial -> polynomial) \n   (G:polynomial -> polynomial) : Prop :=\n   forall k (m:Mem.t k) p,\n    (forall t (x:Var.var t), \n     BP.Vset.mem x (BP.fv_distr s) -> T.size (m x) <= peval p k)  ->\n    let (l,n) := E.ceval_support s m in\n     (forall v, In v l -> T.size v <= peval (F p) k) /\\\n     n <= peval (G p) k.\n\n   Definition utsize : UT.t -> nat := fun _ => 1.\n\n   Definition utsize_default_poly : nat -> polynomial :=\n    fun _ => pplus (pcst 1) pvar.\n\n   Lemma utsize_default_poly_spec : forall r ut,\n    utsize ut <= r -> \n    forall k, UT.size (UT.default k ut) <= peval (utsize_default_poly r) k.\n   Proof.\n    intros r ut _ k.\n    simpl.\n    unfold UT.default, UT.size, utsize_default_poly. \n    rewrite pplus_spec, pcst_spec, pvar_spec; trivial. \n    simpl; apply le_n_S; apply Ut.len_le.\n   Qed.\n\n   Definition uop_poly (o:Uop.t) : bool := \n    match o with \n    | Oapp_f_inv => false \n    | _ => true \n    end.\n\n   Lemma uop_poly_spec : forall o (la:dlist E.expr (O.targs (O.Ouser o))),\n    uop_poly o ->\n    (forall t (e:E.expr t), @DIn _ E.expr _ e _ la -> \n     exists F, exists G, PPT_expr e F G) ->\n    exists F, exists G, PPT_expr (E.Eop (O.Ouser o) la) F G.\n   Proof.\n    intros o la H Hla.\n    destruct o; simpl.\n\n    (* Oapp_f *)\n    T.dlist_inversion la.\n    rewrite Heq in Hla |- *.\n    destruct (Hla _ x) as [F1 [G1 H1] ].\n    left; trivial.\n    exists (fun _ => pplus (pcst 5) pvar).\n    exists (fun p => pplus (cost_f) (G1 p)). \n    simpl; split.\n    unfold T.size, UT.size, UOp.Tk, UOp.Tnk1; rewrite pplus_spec, pcst_spec, pvar_spec; trivial.\n    simpl;assert (W:= k_spec k);omega.\n    simpl; rewrite pplus_spec.\n    generalize (H1 k m p); clear H1.\n    case_eq (E.ceval_expr x m); simpl.\n    intros i n0 Heqi Hi.\n    destruct Hi.\n    intros; apply H0; simpl.\n    apply Vset.subset_correct with (fv_expr x); [ | trivial].\n    unfold fv_expr; simpl; auto with set.\n    rewrite plus_0_r; trivial.\n    omega.\n\n    discriminate H.\n\n    (* OqG *)\n    T.dlist_inversion la.\n    rewrite Heq in Hla |- *.\n    exists (fun _ => pplus (pcst 1) qG_poly).\n    exists (fun _ => pcst 1). \n    simpl; split.\n    rewrite pplus_spec, pcst_spec; case (peval qG_poly k).\n    trivial.\n    intro n0; apply le_trans with (S n0); [apply size_nat_le | ]; auto with arith.\n    rewrite pcst_spec; trivial.\n\n    (* OqH *)\n    T.dlist_inversion la.\n    rewrite Heq in Hla |- *.\n    exists (fun _ => pplus (pcst 1) qH_poly).\n    exists (fun _ => pcst 1). \n    simpl; split.\n    rewrite pplus_spec, pcst_spec; case (peval qH_poly k).\n    trivial.\n    intro n0; apply le_trans with (S n0); [apply size_nat_le | ]; auto with arith.\n    rewrite pcst_spec; trivial.\n\n    (* OqD *)\n    T.dlist_inversion la.\n    rewrite Heq in Hla |- *.\n    exists (fun _ => pplus (pcst 1) qD_poly).\n    exists (fun _ => pcst 1). \n    simpl; split.\n    rewrite pplus_spec, pcst_spec; case (peval qD_poly k).\n    trivial.\n    intro n0; apply le_trans with (S n0); [apply size_nat_le | ]; auto with arith.\n    rewrite pcst_spec; trivial.\n\n    (* Oxor *)\n    T.dlist_inversion la.\n    rewrite Heq in Hla |- *.\n    destruct (Hla _ x) as [F1 [G1 H1] ].\n    left; trivial.\n    destruct (Hla _ x0) as [F2 [G2 H2] ].\n    right; left; trivial.\n    exists (fun _ => pplus (pcst 1) pvar).\n    exists (fun p => pplus (pplus (pcst 1) pvar) (pplus (G1 p) (G2 p))).\n    simpl; split.\n    exact (UT.default_poly_spec k t).\n\n    generalize (H1 k m p) (H2 k m p); clear H1 H2.\n    simpl.\n    case_eq (E.ceval_expr x m); simpl.\n    case_eq (E.ceval_expr x0 m); simpl.\n    intros i n1 Heqi i0 n0 Heqi0 Hi Hi0.\n    destruct Hi.\n    intros; apply H0; simpl.\n    apply Vset.subset_correct with (fv_expr x); [ | trivial].  \n    unfold fv_expr; simpl.\n    apply fv_expr_rec_subset.\n    destruct Hi0.\n    intros; apply H0; simpl.\n    apply Vset.subset_correct with (fv_expr x0); [ | trivial].  \n    unfold fv_expr at 2; simpl.\n    fold (fv_expr_extend x0 (fv_expr_rec Vset.empty x)).\n    rewrite union_fv_expr_spec.\n    apply VsetP.subset_union_l.\n\n    rewrite pplus_spec, pplus_spec, pplus_spec,  pcst_spec, pvar_spec.    \n    apply plus_le_compat; auto.  \n    apply le_trans with k.\n    exact (Ut.len_le k t).\n    auto with arith.\n    rewrite plus_0_r; apply plus_le_compat; trivial.\n \n    (* Ozero *)\n    T.dlist_inversion la.\n    rewrite Heq in Hla |- *.\n    exists (fun _ => pplus (pcst 1) pvar).\n    exists (fun _ => pcst 1). \n    simpl; split.\n    rewrite pplus_spec, pcst_spec.\n    trivial.\n    rewrite pvar_spec.\n    unfold T.size, Ut.size; simpl.\n    apply le_n_S.\n    rewrite k_spec; omega.\n    rewrite pcst_spec; trivial.\n\n    (* Oone *)\n    T.dlist_inversion la.\n    rewrite Heq in Hla |- *.\n    exists (fun _ => pplus (pcst 1) pvar).\n    exists (fun _ => pcst 1). \n    simpl; split.\n    rewrite pplus_spec, pcst_spec.\n    trivial.\n    rewrite pvar_spec.\n    unfold T.size, Ut.size; simpl.\n    apply le_n_S.\n    rewrite k_spec; omega.\n    rewrite pcst_spec; trivial.\n   Qed.\n\n   Definition usupport_poly t (us:US.usupport t) : bool :=\n    match us with \n    | Usupport _ => true\n    end. \n\n   Lemma usupport_poly_spec : forall t (us:US.usupport t),\n    usupport_poly us ->\n    exists F, exists G, PPT_support (E.Duser us) F G.\n   Proof.\n    intros t us; destruct us; intros _.\n    exists (fun _ => pplus (pcst 1) pvar).\n    exists (fun _ => pcst 1).\n    intros k m p Hm.\n    simpl; split.\n    intros; exact (UT.default_poly_spec k t).\n    rewrite pcst_spec; trivial. \n   Qed.\n\n End Uppt.\n\nEnd Entries.\n\nDeclare Module TP : TRAPDOOR_PERM.\nModule Ent := Entries TP.\n\nModule Tactics := BuildTac2.Make Ent.\nExport Tactics.\n", "meta": {"author": "EasyCrypt", "repo": "certicrypt", "sha": "7b3cd2fe4a317aec38dfff9eec902b265c575587", "save_path": "github-repos/coq/EasyCrypt-certicrypt", "path": "github-repos/coq/EasyCrypt-certicrypt/certicrypt-7b3cd2fe4a317aec38dfff9eec902b265c575587/Examples/OAEP-CCA/Extension.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2514923173202992}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\nFrom ITree Require Import ITree.\nFrom Fairness Require Import\n  ITreeLib WFLib Axioms pind LPCM Mod Linking ModSim ModSimAux ModSimNat AddWorld.\n\nImport Lia.\nImport Mod.\nImport RelationClasses.\n\nSection ADD_COMM.\n\n  Definition conv {id1 id2 wf} (m_tgt : @imap (ident_tgt (id_sum id2 id1)) wf) :\n    @imap (id_sum id1 id2) wf :=\n    fun i =>\n      match i with\n      | inl i => m_tgt (inr (inr i))\n      | inr i => m_tgt (inr (inl i))\n      end.\n\nEnd ADD_COMM.\n\nSection IMAP_OPERATIONS.\n\n  Context {id_ctx id_src id_tgt : ID}.\n  Context {wf_src : WF}.\n\n  Definition sum_wf wf1 wf2 := {| wf := sum_lt_well_founded (wf wf1) (wf wf2) |}.\n\n  Definition pick_ctx\n    (IM_TGT : @imap (ident_tgt (id_sum id_ctx id_tgt)) nat_wf)\n    : @imap id_ctx nat_wf := fun i => IM_TGT (inr (inl i)).\n\n  Definition chop_ctx\n    (ths : TIdSet.t)\n    (IM_TGT : @imap (ident_tgt (id_sum id_ctx id_tgt)) nat_wf)\n    : @imap (ident_tgt id_tgt) nat_wf:=\n    fun i => match i with\n          | inl i => if NatMapP.F.In_dec ths i then IM_TGT (inl i) else 0\n          | inr i => IM_TGT (inr (inr i))\n          end.\n\n  Definition add_ctx\n    (im_ctx : imap id_ctx nat_wf)\n    (im_src : imap id_src wf_src)\n    : forall i, (sum_wf wf_src nat_wf).(T)\n    := fun i => match i with\n             | inl i => inr (im_ctx i)\n             | inr i => inl (im_src i)\n             end.\n\n  Lemma pick_ctx_fair_thread IM_TGT0 IM_TGT1 m\n    (FAIR : fair_update IM_TGT0 IM_TGT1 (prism_fmap inlp m))\n    : pick_ctx IM_TGT0 = pick_ctx IM_TGT1.\n  Proof.\n    extensionalities i. specialize (FAIR (inr (inl i))). ss.\n  Qed.\n\n  Lemma chop_ctx_fair_ctx ths_usr IM_TGT0 IM_TGT1 m\n    (FAIR : fair_update IM_TGT0 IM_TGT1 (prism_fmap inrp (prism_fmap inlp m)))\n    : chop_ctx ths_usr IM_TGT0 = chop_ctx ths_usr IM_TGT1.\n  Proof.\n    extensionalities i. destruct i as [i|i]; ss.\n    - specialize (FAIR (inl i)). ss. des_ifs.\n    - specialize (FAIR (inr (inr i))). ss.\n  Qed.\n\n  Lemma chop_ctx_fair_thread1 ths ths_ctx ths_usr tid IM_TGT0 IM_TGT1\n    (PARTITION : NatMapP.Partition ths ths_ctx ths_usr)\n    (TID_CTX : NatMap.In tid ths_ctx)\n    (FAIR : fair_update IM_TGT0 IM_TGT1 (prism_fmap inlp (tids_fmap tid ths)))\n    : fair_update (chop_ctx ths_usr IM_TGT0) (chop_ctx ths_usr IM_TGT1) (prism_fmap inlp (tids_fmap_all ths_usr)).\n  Proof.\n    ii. unfold prism_fmap in *; ss. destruct i as [i|i]; ss.\n    - specialize (FAIR (inl i)). ss. destruct (tids_fmap_all ths_usr i) eqn:E; ss.\n      + unfold tids_fmap_all, tids_fmap in FAIR, E. destruct (NatMapP.F.In_dec ths_usr i); ss.\n        assert (NatMap.In i ths). (* i ∈ ths_usr ⊂ ths *)\n        { eapply Partition_In_right in PARTITION; eauto. }\n        assert (i <> tid). (* ths_ctx ∩ ths_usr = ∅, i ∈ ths_usr, tid ∈ ths_ctx *)\n        { ii. subst. destruct PARTITION. eapply H0. eauto. }\n        des_ifs.\n      + unfold tids_fmap_all, tids_fmap in FAIR, E. des_ifs.\n    - specialize (FAIR (inr (inr i))). ss.\n  Qed.\n\n  Lemma chop_ctx_fair_thread2 ths ths_usr tid IM_TGT0 IM_TGT1\n    (LE : KeySetLE ths_usr ths)\n    (FAIR : fair_update IM_TGT0 IM_TGT1 (prism_fmap inlp (tids_fmap tid ths)))\n    : fair_update (chop_ctx ths_usr IM_TGT0) (chop_ctx ths_usr IM_TGT1) (prism_fmap inlp (tids_fmap tid ths_usr)).\n  Proof.\n    ii. unfold prism_fmap in *; ss. destruct i as [i|i]; ss.\n    - specialize (FAIR (inl i)); ss. destruct (NatMapP.F.In_dec ths_usr i).\n      + pose proof (LE _ i0). unfold tids_fmap in *. des_ifs.\n      + unfold tids_fmap in *. des_ifs.\n    - specialize (FAIR (inr (inr i))); ss.\n  Qed.\n\nEnd IMAP_OPERATIONS.\n\nSection SIM_REFLEXIVE.\n\n  Context {A S_src S_tgt : Type}.\n  Context {J K_src K_tgt : Type}.\n  Context {l_src : Lens.t S_src A}.\n  Context {l_tgt : Lens.t S_tgt A}.\n  Context {p_src : Prism.t K_src J}.\n  Context {p_tgt : Prism.t K_tgt J}.\n\n  Variable I : @shared S_src S_tgt K_src K_tgt nat_wf nat_wf -> Unit -> Prop.\n\n  Hypothesis I_update_thread :\n    forall ths im_src im_tgt st_src st_tgt w,\n      I (ths, im_src, im_tgt, st_src, st_tgt) w ->\n        forall ths' w', I (ths', im_src, im_tgt, st_src, st_tgt) w'.\n\n  Hypothesis I_update_state :\n    forall ths im_src im_tgt st_src st_tgt w,\n      I (ths, im_src, im_tgt, st_src, st_tgt) w ->\n      Lens.view l_src st_src = Lens.view l_tgt st_tgt /\\\n        forall st st_src' st_tgt' w',\n          st_src' = Lens.set l_src st st_src ->\n          st_tgt' = Lens.set l_tgt st st_tgt ->\n          I (ths, im_src, im_tgt, st_src', st_tgt') w'.\n\n  Hypothesis I_update_imap :\n    forall ths im_src im_tgt st_src st_tgt w,\n      I (ths, im_src, im_tgt, st_src, st_tgt) w ->\n      Lens.view (prisml p_src) im_src = Lens.view (prisml (inrp ⋅ p_tgt)%prism) im_tgt /\\\n        forall im im_src' im_tgt' w',\n          im_src' = Lens.set (prisml p_src) im im_src ->\n          im_tgt' = Lens.set (prisml (inrp ⋅ p_tgt)%prism) im im_tgt ->\n          I (ths, im_src', im_tgt', st_src, st_tgt) w'.\n\n  Hypothesis I_update_imap_thread_id :\n    forall ths im_src im_tgt st_src st_tgt w,\n      I (ths, im_src, im_tgt, st_src, st_tgt) w ->\n      forall im im_tgt' w',\n        im_tgt' = Lens.set (prisml inlp) im im_tgt ->\n        I (ths, im_src, im_tgt', st_src, st_tgt) w'.\n\n  Lemma I_update_imap_fair\n    ths im_src im_tgt st_src st_tgt w\n    fm im_src' im_tgt' w'\n    (FAIR : fair_update im_tgt im_tgt' (prism_fmap (inrp ⋅ p_tgt)%prism fm))\n    (SRC : im_src' = Lens.set (prisml p_src) (Lens.view (prisml (inrp ⋅ p_tgt)%prism) im_tgt') im_src)\n    (INV : I (ths, im_src, im_tgt, st_src, st_tgt) w)\n    : I (ths, im_src', im_tgt', st_src, st_tgt) w'.\n  Proof.\n    eapply I_update_imap.\n    - eapply INV.\n    - eapply SRC.\n    - extensionalities i. specialize (FAIR i). destruct i; ss.\n      unfold prism_fmap in FAIR. cbn in FAIR. cbn. destruct (Prism.preview p_tgt k) eqn: Heq; ss.\n      eapply Prism.review_preview in Heq. subst. des_ifs.\n  Qed.\n\n  Lemma I_update_imap_thread_id_fair\n    ths im_src im_tgt st_src st_tgt w\n    fm im_tgt' w'\n    (FAIR : fair_update im_tgt im_tgt' (prism_fmap inlp fm))\n    (INV : I (ths, im_src, im_tgt, st_src, st_tgt) w)\n    : I (ths, im_src, im_tgt', st_src, st_tgt) w'.\n  Proof.\n    eapply I_update_imap_thread_id.\n    - eapply INV.\n    - extensionalities i. specialize (FAIR i). destruct i; ss.\n  Qed.\n\n  Tactic Notation \"hspecialize\" hyp(H) \"with\" uconstr(x) :=\n    apply (_equal_f _ _ _ _ x) in H.\n\n  Section LSIM.\n\n    Variable R : Type.\n    Variable RR : R -> R -> Unit -> shared S_src S_tgt K_src K_tgt nat_wf nat_wf -> Prop.\n\n    Hypothesis I_RR_compatible :\n      forall r ths im_src im_tgt st_src st_tgt w w',\n        I (ths, im_src, im_tgt, st_src, st_tgt) w ->\n        RR r r w' (ths, im_src, im_tgt, st_src, st_tgt).\n\n    Lemma lsim_refl :\n      forall tid (itr : itree (programE J A) R)\n        fs ft r_ctx ths im_src im_tgt st_src st_tgt\n        (INV : I (ths, im_src, im_tgt, st_src, st_tgt) tt),\n        lsim I tid RR fs ft r_ctx\n          (map_event (plmap p_src l_src) itr)\n          (map_event (plmap p_tgt l_tgt) itr)\n          (ths, im_src, im_tgt, st_src, st_tgt).\n    Proof.\n      clear I_update_thread.\n      intro tid. ginit. gcofix CIH. i.\n      destruct_itree itr.\n      - rewrite ! map_event_ret.\n        gstep. eapply pind9_fold. eapply lsim_ret. eauto.\n      - rewrite ! map_event_tau.\n        gstep.\n        eapply pind9_fold. eapply lsim_tauL. split; ss.\n        eapply pind9_fold. eapply lsim_tauR. split; ss.\n        eapply pind9_fold. eapply lsim_progress.\n        gbase. eapply CIH; eauto.\n      - rewrite ! map_event_vis, <- ! bind_trigger. gstep.\n        destruct e as [[[e|e]|e]|e]; destruct e.\n        + eapply pind9_fold. eapply lsim_chooseR. i. esplit; ss.\n          eapply pind9_fold. eapply lsim_chooseL. exists x. esplit; ss.\n          eapply pind9_fold. eapply lsim_progress.\n          gbase. eapply CIH; eauto.\n        + eapply pind9_fold. eapply lsim_fairR. i. esplit; ss.\n          eapply pind9_fold. eapply lsim_fairL.\n          exists (Lens.set (prisml p_src) (Lens.view (prisml (inrp ⋅ p_tgt)%prism) im_tgt1) im_src). split.\n          { eapply I_update_imap in INV. des. ii.\n            unfold prism_fmap; cbn. destruct (Prism.preview p_src i) eqn: Heq; ss.\n            eapply Prism.review_preview in Heq; subst.\n            hspecialize INV with j. cbn in INV. rewrite INV.\n            specialize (FAIR (Prism.review (inrp ⋅ p_tgt)%prism j)). cbn in FAIR.\n            unfold prism_fmap in FAIR. rewrite Prism.preview_review in FAIR; ss.\n          }\n          split; ss.\n          eapply pind9_fold. eapply lsim_progress.\n          gbase. des. eapply CIH.\n          { rewrite <- prism_fmap_compose in FAIR. eapply I_update_imap_fair; eauto. }\n        + eapply pind9_fold. eapply lsim_observe. i.\n          gbase. eapply CIH; eauto.\n        + eapply pind9_fold. eapply lsim_UB.\n        + eapply pind9_fold. eapply lsim_sync; eauto using Unit_wf. i.\n          gbase. eapply CIH.\n          { eapply I_update_imap_thread_id_fair; eauto. }\n        + eapply pind9_fold. eapply lsim_tidR. esplit; ss.\n          eapply pind9_fold. eapply lsim_tidL. esplit; ss.\n          eapply pind9_fold. eapply lsim_progress.\n          gbase. eapply CIH; eauto.\n        + eapply pind9_fold. eapply lsim_call. i.\n          gbase. eapply CIH; eauto.\n        + eapply pind9_fold. eapply lsim_rmwL. esplit; ss.\n          eapply pind9_fold. eapply lsim_rmwR. esplit; ss.\n          eapply pind9_fold. eapply lsim_progress.\n          eapply I_update_state in INV. des. rewrite INV.\n          gbase. eapply CIH; eauto.\n          Unshelve. all: ss.\n    Qed.\n\n  End LSIM.\n\n  Lemma local_sim_refl R (itr : itree (programE J A) R) :\n    local_sim I eq (map_event (plmap p_src l_src) itr) (map_event (plmap p_tgt l_tgt) itr).\n  Proof.\n    ii. exists tt, tt. splits; eauto using Unit_wf.\n    { eapply I_update_imap_thread_id_fair; eauto. }\n    i.\n    assert (INV_CIH : I (ths, im_src1, im_tgt3, st_src2, st_tgt2) tt).\n    { eapply I_update_imap_thread_id_fair; eauto. }\n    eapply lsim_refl; eauto.\n    i. ss. esplits; eauto using Unit_wf.\n    Unshelve. all: exact tt.\n  Qed.\n\nEnd SIM_REFLEXIVE.\n\nSection ADD_RIGHT_MONO_SIM.\n\n  Context {M1 M2_src M2_tgt : Mod.t}.\n  Context {wf_src : WF}.\n  Context `{world : URA.t}.\n\n  Variable I : shared (state M2_src) (state M2_tgt) (ident M2_src) (ident M2_tgt) wf_src nat_wf -> world -> Prop.\n\n  Definition lift_ma :=\n    fun (x : @shared\n            (ModAdd M1 M2_src).(state) (ModAdd M1 M2_tgt).(state)\n            (ModAdd M1 M2_src).(ident) (ModAdd M1 M2_tgt).(ident)\n            (sum_wf wf_src nat_wf) nat_wf)\n      (r : URA.prod threadsRA world)\n    => let '(ths, IM_SRC, IM_TGT, st_src, st_tgt) := x in\n      exists im_src0 ths_ctx0 ths_usr0,\n        let im_ctx0 := pick_ctx IM_TGT in\n        let im_tgt0 := chop_ctx ths_usr0 IM_TGT in\n        IM_SRC = add_ctx im_ctx0 im_src0\n        /\\ NatMapP.Partition ths ths_ctx0 ths_usr0\n        /\\ fst r = global_th ths_ctx0 ths_usr0\n        /\\ fst st_src = fst st_tgt\n        /\\ lifted I (ths_usr0, im_src0, im_tgt0, snd st_src, snd st_tgt) (snd r).\n\n  Opaque lifted threadsRA URA.prod.\n\n  Lemma lift_ma_local_sim_ub R_src R_tgt (RR : R_src -> R_tgt -> Prop) ktr_src itr_tgt\n    : local_sim lift_ma RR (Vis (inl1 (inl1 (inl1 Undefined))) ktr_src) itr_tgt.\n  Proof.\n    (* treat as if tid ∈ ths_ctx *)\n    intros ths IM_SRC0 IM_TGT0 st_src0 st_tgt0 [r_sha_th0 r_sha_w0] [r_ctx_th0 r_ctx_w0] INV0_0 tid ths0 THS0 VALID0_0 IM_TGT1 TID_TGT.\n    simpl in INV0_0. des. subst r_sha_th0. unfold_prod VALID0_0.\n    assert (CTX_TGT : pick_ctx IM_TGT0 = pick_ctx IM_TGT1).\n    { extensionalities i. specialize (TID_TGT (inr (inl i))). ss. }\n    assert (USR_TGT : chop_ctx ths_usr0 IM_TGT0 = chop_ctx ths_usr0 IM_TGT1).\n    { extensionalities i. destruct i as [i|i].\n      - specialize (TID_TGT (inl i)). unfold prism_fmap in *; ss. des_ifs. exfalso.\n        eapply inv_add_new in THS0. des. eapply THS0.\n        eapply Partition_In_right in INV0_1. eapply INV0_1.\n        ss.\n      - specialize (TID_TGT (inr (inr i))). ss.\n    }\n    exists (global_th (TIdSet.add tid ths_ctx0) ths_usr0, r_sha_w0), (local_th_context tid, URA.unit). splits.\n    { exists im_src0, (TIdSet.add tid ths_ctx0), ths_usr0. splits; ss.\n      - subst. rewrite CTX_TGT. ss.\n      - eauto using NatMapP.Partition_sym, Partition_add.\n      - rewrite USR_TGT in INV0_4. ss.\n    }\n    { unfold_prod. split.\n      - eapply inv_add_new in THS0. des; subst. eapply global_th_alloc_context.\n        + eauto.\n        + eapply inv_add_new. split; ss.\n          ii. eapply THS0. eapply (Partition_In_left INV0_1). ss.\n        + ii. eapply THS0. eapply (Partition_In_right INV0_1). ss.\n      - rewrite URA.unit_id. eauto.\n    }\n    i. pfold. eapply pind9_fold. rewrite <- bind_trigger. econs.\n  Qed.\n\n  Lemma lift_ma_local_sim_ctx R (itr : itree _ R)\n    : local_sim lift_ma eq (map_event (emb_l M1 M2_src) itr) (map_event (emb_l M1 M2_tgt) itr).\n  Proof.\n    (* tid ∈ ths_ctx *)\n    intros ths IM_SRC0 IM_TGT0 st_src0 st_tgt0 [r_sha_th0 r_sha_w0] [r_ctx_th0 r_ctx_w0] INV0_0 tid ths0 THS0 VALID0_0 IM_TGT1 TID_TGT.\n    simpl in INV0_0. des. subst r_sha_th0. unfold_prod VALID0_0.\n    assert (CTX_TGT : pick_ctx IM_TGT0 = pick_ctx IM_TGT1).\n    { extensionalities i. specialize (TID_TGT (inr (inl i))). ss. }\n    assert (USR_TGT : chop_ctx ths_usr0 IM_TGT0 = chop_ctx ths_usr0 IM_TGT1).\n    { extensionalities i. destruct i as [i|i].\n      - specialize (TID_TGT (inl i)). unfold prism_fmap in *; ss. des_ifs. exfalso.\n        eapply inv_add_new in THS0. des. eapply THS0.\n        eapply Partition_In_right in INV0_1. eapply INV0_1.\n        ss.\n      - specialize (TID_TGT (inr (inr i))). ss.\n    }\n    exists (global_th (TIdSet.add tid ths_ctx0) ths_usr0, r_sha_w0), (local_th_context tid, URA.unit). splits.\n    { exists im_src0, (TIdSet.add tid ths_ctx0), ths_usr0. splits; ss.\n      - subst. rewrite CTX_TGT. ss.\n      - eauto using NatMapP.Partition_sym, Partition_add.\n      - rewrite USR_TGT in INV0_4. ss.\n    }\n    { unfold_prod. split.\n      - eapply inv_add_new in THS0. des; subst. eapply global_th_alloc_context.\n        + eauto.\n        + eapply inv_add_new. split; ss.\n          ii. eapply THS0. eapply (Partition_In_left INV0_1). ss.\n        + ii. eapply THS0. eapply (Partition_In_right INV0_1). ss.\n      - rewrite URA.unit_id. eauto.\n    }\n    intros ths1 IM_SRC1 IM_TGT2 st_src1 st_tgt1 [r_sha_th1 r_sha_w1] [r_ctx_th1 r_ctx_w1] INV1_0 VALID1_0.\n    intros IM_TGT2' TGT fs ft.\n    simpl in INV1_0. des. subst r_sha_th1. unfold_prod VALID1_0.\n    unfold emb_l, emb_r.\n    assert (INV : lift_ma (ths1, IM_SRC1, IM_TGT2', st_src1, st_tgt1) (global_th ths_ctx1 ths_usr1, r_sha_w1)).\n    { ss. exists im_src1, ths_ctx1, ths_usr1. splits; ss.\n      - eapply pick_ctx_fair_thread in TGT. rewrite <- TGT. ss.\n      - eapply shared_rel_wf_lifted; eauto.\n        eapply chop_ctx_fair_thread1; eauto.\n        eapply local_th_context_in_context; eauto.\n    }\n    clear - INV VALID1_0 VALID1_1. move itr after tid.\n    rename\n      ths1 into ths0, ths_ctx1 into ths_ctx0, ths_usr1 into ths_usr0,\n      IM_SRC1 into IM_SRC0, IM_TGT2' into IM_TGT0, st_src1 into st_src0, st_tgt1 into st_tgt0,\n      r_sha_w1 into r_sha_w0, r_ctx_th1 into r_ctx_th0, r_ctx_w1 into r_ctx_w0,\n      INV into INV0, VALID1_0 into VALID_TH0, VALID1_1 into VALID_W0.\n    revert_until tid. ginit. gcofix CIH. i.\n    destruct_itree itr; [| | destruct e as [[[]|]|] ].\n    - rewrite ! map_event_ret.\n      gstep. eapply pind9_fold. econs. ss.\n      exists (NatSet.remove tid ths0), (URA.unit, URA.unit), (global_th (NatSet.remove tid ths_ctx0) ths_usr0, r_sha_w0).\n      splits; ss.\n      { unfold_prod. split.\n        - eapply global_th_dealloc_context; eauto.\n        - eauto.\n      }\n      { des. inversion INV2. subst ths_ctx1 ths_usr1. exists im_src0, (NatSet.remove tid ths_ctx0), ths_usr0. splits; ss.\n        eapply local_th_context_in_context in VALID_TH0.\n        eauto using NatMapP.Partition_sym, Partition_remove.\n      }\n    - rewrite ! map_event_tau.\n      gstep.\n      eapply pind9_fold. econs. split; ss.\n      eapply pind9_fold. econs. split; ss.\n      eapply pind9_fold. econs.\n      gfinal. left. eapply CIH; eauto.\n    - rewrite ! map_event_vis.\n      rewrite <- 2 bind_trigger.\n      gstep. destruct e; ss.\n      + eapply pind9_fold. eapply lsim_chooseR. i. esplit; ss.\n        eapply pind9_fold. eapply lsim_chooseL. exists x. esplit; ss.\n        eapply pind9_fold. eapply lsim_progress.\n        gfinal. left. eapply CIH; eauto.\n      + eapply pind9_fold. eapply lsim_fairR. intros IM_TGT1 FAIR. esplit; ss.\n        eapply pind9_fold. eapply lsim_fairL.\n        des. inversion INV2. subst ths_ctx1 ths_usr1. exists (add_ctx (pick_ctx IM_TGT1) im_src0). split.\n        { subst. ii. destruct i; ss.\n          specialize (FAIR (inr (inl i))). unfold pick_ctx. ss.\n          unfold prism_fmap in *. ss. des_ifs.\n          + econs. ss.\n          + f_equal. ss.\n        }\n        split; ss.\n        eapply pind9_fold. eapply lsim_progress.\n        gfinal. left. des. eapply CIH; eauto.\n        { esplits; eauto. eapply chop_ctx_fair_ctx in FAIR. rewrite <- FAIR. ss. }\n      + eapply pind9_fold. eapply lsim_observe. i.\n        gfinal. left. eapply CIH; eauto.\n      + eapply pind9_fold. eapply lsim_UB.\n    - rewrite ! map_event_vis. simpl.\n      rewrite <- 2 bind_trigger.\n      gstep. destruct c.\n      + eapply pind9_fold. eapply lsim_sync.\n        { eapply INV0. }\n        { instantiate (1 := (local_th_context tid, ε)). unfold_prod. split; ss. }\n        intros ths1 IM_SRC1 IM_TGT1 st_src1 st_tgt1 [r_sha_th1 r_sha_w1] [r_ctx_th1 r_ctx_w1] INV1_0 VALID1_0 IM_TGT1' TGT.\n        simpl in INV1_0. des. subst r_sha_th1. rename im_src0 into im_src1. unfold_prod VALID1_0.\n        gfinal. left. eapply CIH; eauto.\n        { exists im_src1, ths_ctx1, ths_usr1. ss. splits; ss.\n          - eapply pick_ctx_fair_thread in TGT. rewrite <- TGT. ss.\n          - eapply shared_rel_wf_lifted; eauto.\n            eapply chop_ctx_fair_thread1; eauto.\n            eapply local_th_context_in_context; eauto.\n        }\n      + eapply pind9_fold. eapply lsim_tidR. esplit; ss.\n        eapply pind9_fold. eapply lsim_tidL. esplit; ss.\n        eapply pind9_fold. eapply lsim_progress.\n        gfinal. left. eapply CIH; eauto.\n    - rewrite ! map_event_vis. ss.\n      rewrite <- 2 bind_trigger.\n      destruct c. gstep. eapply pind9_fold. eapply lsim_call.\n      i. gfinal. left. eapply CIH; eauto.\n    - destruct s.\n      rewrite ! map_event_vis. ss.\n      rewrite <- 2 bind_trigger.\n      gstep.\n      eapply pind9_fold. eapply lsim_rmwL. esplit; ss.\n      eapply pind9_fold. eapply lsim_rmwR. esplit; ss.\n      eapply pind9_fold. eapply lsim_progress.\n      gbase. des. destruct st_src0, st_tgt0; ss. subst.\n      eapply CIH; eauto. esplits; eauto.\n  Qed.\n\n  Lemma lift_ma_local_sim_usr R_src R_tgt (RR : R_src -> R_tgt -> Prop) itr_src itr_tgt\n    (SIM : local_sim (lifted I) RR itr_src itr_tgt)\n    : local_sim lift_ma RR (map_event (emb_r M1 M2_src) itr_src) (map_event (emb_r M1 M2_tgt) itr_tgt).\n  Proof.\n    (* tid ∈ ths_usr *)\n    intros ths IM_SRC0 IM_TGT0 st_src0 st_tgt0 [r_sha_th0 r_sha_w0] [r_ctx_th0 r_ctx_w0] INV0_0 tid ths0 THS0 VALID0_0. i.\n    simpl in INV0_0. des. subst r_sha_th0. unfold_prod VALID0_0.\n    move SIM at bottom.\n    assert (THS0' : TIdSet.add_new tid ths_usr0 (TIdSet.add tid ths_usr0)).\n    { eapply inv_add_new. split; ss. eapply inv_add_new in THS0. des.\n      eapply Partition_In_right in INV0_1. eauto.\n    }\n    assert (TID_TGT' : fair_update (chop_ctx ths_usr0 IM_TGT0) (chop_ctx (NatSet.add tid ths_usr0) im_tgt1) (prism_fmap inlp (fun i => if Nat.eq_dec i tid then Flag.success else Flag.emp))).\n    { ii. destruct i as [i|i]; ss.\n      - specialize (TID_TGT (inl i)). unfold prism_fmap in *; ss. destruct (Nat.eq_dec i tid); ss.\n        assert (H : tid <> i) by lia.\n        eapply NatMapP.F.add_neq_in_iff with (m := ths_usr0) (e := tt) in H.\n        des_ifs; tauto.\n      - specialize (TID_TGT (inr (inr i))). des_ifs.\n    }\n    specialize (SIM ths_usr0 im_src0 (chop_ctx ths_usr0 IM_TGT0) (snd st_src0) (snd st_tgt0) r_sha_w0 r_ctx_w0 INV0_4 tid (NatSet.add tid ths_usr0) THS0' VALID0_1 (chop_ctx (NatSet.add tid ths_usr0) im_tgt1) TID_TGT').\n    destruct SIM as [r_sha_w1 [r_own_w1 [INV_USR [VALID_USR SIM]]]].\n    exists (global_th ths_ctx0 (NatSet.add tid ths_usr0), r_sha_w1), (local_th_user tid, r_own_w1). splits.\n    { eapply inv_add_new in THS0. des. subst.\n      ss. esplits; ss.\n      - instantiate (1 := im_src0). extensionalities i. destruct i; ss.\n        specialize (TID_TGT (inr (inl i))). ss.\n        unfold pick_ctx. f_equal. ss.\n      - eapply Partition_add; eauto.\n        eapply inv_add_new; eauto.\n      - eapply INV_USR.\n    }\n    { unfold_prod. split.\n      - eapply global_th_alloc_user; eauto.\n        eapply inv_add_new in THS0. des. ii. eapply THS0.\n        eapply Partition_In_left in INV0_1. eapply INV0_1. ss.\n      - eauto.\n    }\n    intros ths2 IM_SRC2 IM_TGT2 st_src2 st_tgt2 [r_sha_th2 r_sha_w2] [r_ctx_th2 r_ctx_w2] INV2_0 VALID2_0 IM_TGT2' TGT fs ft.\n    simpl in INV2_0. destruct INV2_0 as [im_src2 [ths_ctx2 [ths_usr2 INV2_0]]]. des. subst r_sha_th2. unfold_prod VALID2_0.\n    assert (TGT' : @fair_update _ nat_wf (chop_ctx ths_usr2 IM_TGT2) (chop_ctx ths_usr2 IM_TGT2') (prism_fmap inlp (tids_fmap tid ths_usr2))).\n    { eapply chop_ctx_fair_thread2.\n      - eapply Partition_In_right in INV2_1. eapply INV2_1.\n      - eauto.\n    }\n    specialize (SIM ths_usr2 im_src2 (chop_ctx ths_usr2 IM_TGT2) (snd st_src2) (snd st_tgt2) r_sha_w2 r_ctx_w2 INV2_4 VALID2_1 (chop_ctx ths_usr2 IM_TGT2') TGT' fs ft).\n    unfold emb_r.\n\n    eapply pick_ctx_fair_thread in TGT. rewrite TGT in INV2_0.\n    clear - INV2_0 INV2_1 INV2_3 VALID2_0 VALID2_1 SIM.\n    move tid before I.\n    rename\n      ths2 into ths0, ths_ctx2 into ths_ctx0, ths_usr2 into ths_usr0,\n      im_src2 into im_src0, IM_SRC2 into IM_SRC0, IM_TGT2' into IM_TGT0, st_src2 into st_src0, st_tgt2 into st_tgt0,\n      r_sha_w2 into r_sha_w0, r_ctx_th2 into r_ctx_th0, r_ctx_w2 into r_ctx_w0, r_own_w1 into r_own_w0,\n      INV2_0 into INV0, INV2_1 into INV1, INV2_3 into INV2, VALID2_0 into VALID_TH0, VALID2_1 into VALID_W0.\n    revert_until tid. ginit. gcofix CIH. i. gstep. punfold SIM.\n    match type of SIM with pind9 _ _ _ _ ?RR _ _ _ _ _ ?SHA => remember RR as RR_MEM; remember SHA as SHA_MEM end.\n    revert RR ths0 ths_ctx0 ths_usr0 st_src0 st_tgt0 r_sha_w0 r_own_w0 r_ctx_th0 im_src0 IM_SRC0 IM_TGT0 INV0 INV1 INV2 VALID_TH0 VALID_W0 HeqRR_MEM HeqSHA_MEM.\n    pattern R_src, R_tgt, RR_MEM, fs, ft, r_ctx_w0, itr_src, itr_tgt, SHA_MEM.\n    revert R_src R_tgt RR_MEM fs ft r_ctx_w0 itr_src itr_tgt SHA_MEM SIM.\n    eapply pind9_acc. intros rr DEC IH R_src R_tgt RR_MEM fs ft r_ctx_w0 itr_src itr_tgt SHA_MEM. i.\n    clear DEC. subst RR_MEM SHA_MEM.\n    eapply pind9_unfold in PR; eauto with paco. eapply pind9_fold. inv PR.\n    - clear - LSIM VALID_TH0 VALID_W0 INV1 INV2.\n      rewrite ! map_event_ret. econs.\n      ss. des. subst.\n      exists (NatMap.remove tid ths0), (URA.unit, r_own), (global_th ths_ctx0 (NatMap.remove tid ths_usr0), r_shared).\n      splits; ss.\n      + unfold_prod. split.\n        * eapply global_th_dealloc_user; eauto.\n        * ss.\n      + esplits; ss.\n        * eapply local_th_user_in_user in VALID_TH0.\n          eapply Partition_remove; eauto.\n        * eapply lifted_drop_imap; eauto.\n          { i. destruct i as [i|i]; ss.\n            - assert (i = tid \\/ tid <> i) by lia. destruct H.\n              + pose proof NatMap.remove_1 H (m := ths_usr0). des_ifs; unfold le; ss; lia.\n              + pose proof (@NatMapP.F.remove_neq_in_iff _ ths_usr0 tid i H). des_ifs; try tauto; reflexivity.\n            - des_ifs. left. ss.\n          }\n    - rewrite ! map_event_tau. econs. split; ss.\n      destruct LSIM. eapply IH; eauto.\n    - rewrite ! map_event_trigger. econs.\n      des. destruct LSIM. exists x. split; ss. eapply IH; eauto.\n    - rewrite ! map_event_trigger. econs. split; ss.\n      destruct LSIM. eapply IH; eauto.\n    - rewrite ! map_event_trigger. econs. split; ss.\n      destruct LSIM. eapply IH; eauto.\n    - rewrite ! map_event_trigger. econs.\n    - rewrite ! map_event_trigger. econs.\n      des. destruct LSIM0. exists (add_ctx (pick_ctx IM_TGT0) im_src1). splits.\n      { clear - FAIR. ii. destruct i as [i|i]; ss.\n        unfold prism_fmap; ss. specialize (FAIR i). des_ifs.\n        - econs. ss.\n        - f_equal. ss.\n      }\n      split; ss. eapply IH; eauto.\n    - rewrite ! map_event_tau. econs. split; ss.\n      destruct LSIM. eapply IH; eauto.\n    - rewrite ! map_event_trigger. econs. i. specialize (LSIM x). split; ss.\n      destruct LSIM. eapply IH; eauto.\n    - rewrite ! map_event_trigger. econs. split; ss.\n      destruct LSIM. eapply IH; eauto.\n    - rewrite ! map_event_trigger. econs. split; ss.\n      destruct LSIM. eapply IH; eauto.\n    - rewrite ! map_event_trigger. econs. intros IM_TGT1 FAIR. split; ss.\n      assert (FAIR' : fair_update (chop_ctx ths_usr0 IM_TGT0) (chop_ctx ths_usr0 IM_TGT1) (prism_fmap inrp f)).\n      { ii. destruct i as [i|i]; ss.\n        - specialize (FAIR (inl i)). ss. des_ifs.\n        - specialize (FAIR (inr (inr i))). ss.\n      }\n      specialize (LSIM (chop_ctx ths_usr0 IM_TGT1) FAIR').\n      destruct LSIM. eapply IH; eauto.\n      + extensionalities i. destruct i; ss. f_equal.\n        specialize (FAIR (inr (inl i))). ss.\n    - rewrite ! map_event_trigger. econs. i. specialize (LSIM ret). pclearbot.\n      gfinal. left. eapply CIH; eauto.\n    - rewrite ! map_event_trigger. econs. i. specialize (LSIM ret). pclearbot.\n      gfinal. left. eapply CIH; eauto.\n    - match goal with [ |- __lsim _ _ _ _ _ _ _ _ _ (map_event ?EMB _) _ ] => set EMB as emb end.\n      rewrite ! map_event_trigger.\n      eapply lsim_yieldL. split; ss.\n      replace (trigger Yield) with (trigger (emb unit (subevent unit Yield))) by ss.\n      rewrite <- ! map_event_trigger.\n      destruct LSIM. eapply IH; eauto.\n    - match goal with [ |- __lsim _ _ _ _ _ _ _ _ (map_event ?EMB _) _ _ ] => set EMB as emb end.\n      rewrite ! map_event_trigger.\n      eapply lsim_yieldR.\n      { instantiate (1 := (global_th ths_ctx0 ths_usr0, r_shared)).\n        ss. exists im_src0, ths_ctx0, ths_usr0. splits; ss.\n      }\n      { instantiate (1 := (local_th_user tid, r_own)). unfold_prod. split; ss. }\n      intros ths1 IM_SRC1 IM_TGT1 st_src1 st_tgt1 [r_sha_th1 r_sha_w1] [r_ctx_th1 r_ctx_w1] INV1_0 VALID1_0 IM_TGT2 TGT.\n      split; ss. des. unfold_prod VALID1_0.\n      assert (TGT' : fair_update (chop_ctx ths_usr1 IM_TGT1) (chop_ctx ths_usr1 IM_TGT2) (prism_fmap inlp (tids_fmap tid ths_usr1))).\n      { ii. unfold prism_fmap. destruct i as [i|i]; ss.\n        - eapply Partition_In_right in INV1_1. specialize (INV1_1 i). specialize (TGT (inl i)). unfold prism_fmap in *; ss.\n          unfold tids_fmap in *. destruct (Nat.eq_dec i tid); ss. des_ifs.\n          exfalso. tauto.\n        - specialize (TGT (inr (inr i))). ss.\n      }\n      specialize (LSIM ths_usr1 im_src1 (chop_ctx ths_usr1 IM_TGT1) (snd st_src1) (snd st_tgt1) r_sha_w1 r_ctx_w1 INV1_4 VALID1_1 (chop_ctx ths_usr1 IM_TGT2) TGT').\n      replace (trigger Yield) with (trigger (emb unit (subevent unit Yield))) by ss.\n      rewrite <- ! map_event_trigger.\n      destruct LSIM. eapply IH; eauto.\n      + subst. extensionalities i. destruct i as [i|i]; ss. f_equal.\n        specialize (TGT (inr (inl i))). ss.\n      + subst. ss.\n    - rewrite ! map_event_trigger. eapply lsim_sync.\n      { instantiate (1 := (global_th ths_ctx0 ths_usr0, r_shared)).\n        ss. exists im_src0, ths_ctx0, ths_usr0. splits; ss.\n      }\n      { instantiate (1 := (local_th_user tid, r_own)). unfold_prod. split; ss. }\n      intros ths1 IM_SRC1 IM_TGT1 st_src1 st_tgt1 [r_sha_th1 r_sha_w1] [r_ctx_th1 r_ctx_w1] INV1_0 VALID1_0 IM_TGT2 TGT.\n      ss. des. unfold_prod VALID1_0.\n      assert (TGT' : fair_update (chop_ctx ths_usr1 IM_TGT1) (chop_ctx ths_usr1 IM_TGT2) (prism_fmap inlp (tids_fmap tid ths_usr1))).\n      { ii. destruct i as [i|i]; ss.\n        - eapply Partition_In_right in INV1_1. specialize (INV1_1 i). specialize (TGT (inl i)). unfold prism_fmap in *; ss.\n          unfold tids_fmap in *. destruct (Nat.eq_dec i tid); ss. des_ifs.\n          exfalso. tauto.\n        - specialize (TGT (inr (inr i))). ss.\n      }\n      specialize (LSIM ths_usr1 im_src1 (chop_ctx ths_usr1 IM_TGT1) (snd st_src1) (snd st_tgt1) r_sha_w1 r_ctx_w1 INV1_4 VALID1_1 (chop_ctx ths_usr1 IM_TGT2) TGT').\n      pclearbot. gfinal. left. eapply CIH; eauto.\n      + subst. extensionalities i. destruct i as [i|i]; ss. f_equal.\n        specialize (TGT (inr (inl i))). ss.\n      + subst. ss.\n    - econs. pclearbot. gfinal. left. eapply CIH; eauto.\n  Qed.\n\nEnd ADD_RIGHT_MONO_SIM.\n\nSection MODADD_THEOREM.\n\n  Theorem ModAdd_comm M1 M2 : ModSim.mod_sim (ModAdd M1 M2) (ModAdd M2 M1).\n  Proof.\n    Local Opaque Unit.\n    pose proof Unit_wf.\n    pose (I := fun (x : @shared\n                       (ModAdd M1 M2).(state) (ModAdd M2 M1).(state)\n                       (ModAdd M1 M2).(ident) (ModAdd M2 M1).(ident)\n                       nat_wf nat_wf)\n                 (w : Unit)\n               => let '(ths, m_src, m_tgt, st_src, st_tgt) := x in\n                 fst st_src = snd st_tgt\n                 /\\ snd st_src = fst st_tgt\n                 /\\ (forall i, m_src (inl i) = m_tgt (inr (inr i)))\n                 /\\ (forall i, m_src (inr i) = m_tgt (inr (inl i)))\n         ).\n    constructor 1 with nat_wf nat_wf Unit.\n    - econs. exact 0.\n    - i. exists (S o0). ss.\n    (* - i. exists (conv im_tgt). exists tt. ss. *)\n    - i.\n      exists I. split.\n      { exists (conv im_tgt). exists tt. ss. }\n      destruct M1 as [state1 ident1 st_init1 funs1].\n      destruct M2 as [state2 ident2 st_init2 funs2].\n      ss. unfold add_funs. ss.\n      i. destruct (funs1 fn), (funs2 fn).\n      + ii. exists tt, tt. splits; ss.\n        { des. splits; ss.\n          - i. specialize (TID_TGT (inr (inr i))). specialize (INV1 i). ss. rewrite TID_TGT. ss.\n          - i. specialize (TID_TGT (inr (inl i))). specialize (INV2 i). ss. rewrite TID_TGT. ss.\n        }\n        i. pfold. eapply pind9_fold. rewrite <- bind_trigger. econs.\n      + eapply local_sim_refl.\n        * firstorder.\n        * firstorder.\n          -- subst; destruct st_src, st_tgt; ss.\n          -- subst; destruct st_src, st_tgt; ss.\n        * firstorder.\n          -- cbn. extensionalities i. specialize (H2 i). ss.\n          -- subst. ss.\n          -- subst. cbn. specialize (H3 i). ss.\n        * firstorder.\n          -- subst. cbn. specialize (H3 i). ss.\n          -- subst. cbn. specialize (H4 i). ss.\n      + eapply local_sim_refl.\n        * firstorder.\n        * firstorder.\n          -- subst; destruct st_src, st_tgt; ss.\n          -- subst; destruct st_src, st_tgt; ss.\n        * firstorder.\n          -- cbn. extensionalities i. specialize (H3 i). ss.\n          -- subst. cbn. specialize (H2 i). ss.\n          -- subst. ss.\n        * firstorder.\n          -- subst. cbn. specialize (H3 i). ss.\n          -- subst. cbn. specialize (H4 i). ss.\n      + eauto.\n  Qed.\n\n  Theorem ModAdd_right_mono M1 M2_src M2_tgt :\n    ModSim.mod_sim M2_src M2_tgt ->\n    ModSim.mod_sim (ModAdd M1 M2_src) (ModAdd M1 M2_tgt).\n  Proof.\n    i. eapply modsim_nat_modsim_exist in H. inv H.\n    (* econs. *)\n    econstructor 1 with (world:=URA.prod threadsRA world).\n    (* pose (I' := @lift_ma M1 M2_src M2_tgt _ _ I). *)\n    (* constructor 1 with _ _ _ I'. *)\n    { instantiate (1:=nat_wf). econs. exact 0. }\n    { i. exists (S o0). ss. }\n    intro IM_TGT. specialize (init (chop_ctx NatSet.empty IM_TGT)). des.\n    pose (I' := @lift_ma M1 M2_src M2_tgt _ _ I). exists I'.\n    pose (pick_ctx IM_TGT) as im_ctx.\n    split.\n    { exists (add_ctx im_ctx im_src), (global_th NatSet.empty NatSet.empty, r_shared). ss. split.\n      - exists im_src. exists NatSet.empty, NatSet.empty. splits; ss.\n        + eapply Partition_empty.\n        + exists (chop_ctx NatSet.empty IM_TGT). split; ss. ii. left. ss.\n      - unfold_prod. split; ss. rewrite URA.unfold_wf. econs; ss. eapply Disjoint_empty.\n    }\n    rename init0 into funs0.\n    i. specialize (funs0 fn args).\n    unfold ModAdd, add_funs; ss. des_ifs.\n    - eapply lift_ma_local_sim_ub.\n    - eapply lift_ma_local_sim_ctx.\n    - eapply lift_ma_local_sim_usr.\n      eapply local_sim_clos_trans in funs0; cycle 1. { econs. exact 0. }\n      eapply local_sim_wft_mono with (wft_lt := lt (wf_clos_trans nat_wf)). { i. econs. ss. }\n      eapply funs0.\n  Qed.\n\nEnd MODADD_THEOREM.\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/ModAddSim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2514923173202992}}
{"text": "Require Import mailbox.verif_atomics.\nRequire Import progs.conclib.\nRequire Import progs.ghost.\nRequire Import floyd.library.\nRequire Import floyd.sublist.\nRequire Import mailbox.lockfree_linsearch.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\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 tentry := Tstruct _entry noattr.\n\nDefinition entry_hists entries hists := fold_right_sepcon (map (fun i =>\n  let '(hp, e) := (Znth i hists ([], []), Znth i entries Vundef) in\n    ghost_hist (fst hp) (field_address tentry [StructField _key] e) *\n    ghost_hist (snd hp) (field_address tentry [StructField _value] e)) (upto 20)).\n\n(* In this case, let map be an association list. *)\nFixpoint index_of (m : list (Z * Z)) (k : Z) :=\n  match m with\n  | [] => None\n  | (k1, v1) :: rest => if eq_dec k1 k then Some 0\n                        else option_map Z.succ (index_of rest k)\n  end.\n\nLemma index_of_spec : forall k m, match index_of m k with\n  | Some i => 0 <= i < Zlength m /\\ fst (Znth i m (0, 0)) = k\n  | None => ~In k (map fst m) end.\nProof.\n  induction m; simpl; auto; intros.\n  destruct a.\n  rewrite Zlength_cons.\n  pose proof (Zlength_nonneg m).\n  destruct (eq_dec z k); [split; auto; omega|].\n  destruct (index_of m k); simpl.\n  - destruct IHm; unfold Z.succ; rewrite Znth_pos_cons, Z.add_simpl_r; [split|]; auto; omega.\n  - tauto.\nQed.\n\nDefinition set m k v :=\n  match index_of m k with\n  | Some i => upd_Znth i m (k, v)\n  | None => m ++ [(k, v)]\n  end.\n\nDefinition get m k := option_map (fun i => snd (Znth i m (0, 0))) (index_of m k).\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\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, Forall (fun x => fst x < n)%nat h ->\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 ordered_hist h := forall i j (Hi : 0 <= i < j) (Hj : j < Zlength h),\n  (fst (Znth i h (O, Store (vint 0))) < fst (Znth j h (O, Store (vint 0))))%nat.\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 (d := (O, Store (vint 0))) 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, Store (vint 0)) = (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\nDefinition value_of_hist (h : hist) := value_of (snd (last h (O, 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\nDefinition wf_map (m : list (Z * Z)) := Forall (fun i => repable_signed i /\\ i <> 0) (map fst m).\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\n(* Once set, a key is never reset. *)\nDefinition k_R (h : list hist_el) (v : val) := !!(Forall int_op h /\\\n  forall e, In e h -> value_of e <> vint 0 -> v = value_of e) && emp.\n\nDefinition v_R (h : list hist_el) (v : val) := emp.\n\nDefinition atomic_entry sh p := !!(field_compatible tentry [] p) && EX lkey : val, EX lval : val,\n  field_at sh tentry [StructField _lkey] lkey p *\n  atomic_loc sh lkey (field_address tentry [StructField _key] p) (vint 0) Tsh k_R *\n  field_at sh tentry [StructField _lvalue] lval p *\n  atomic_loc sh lval (field_address tentry [StructField _value] p) (vint 0) Tsh v_R.\n\n(* Can we comprehend the per-entry histories into a broader history? *)\nDefinition failed_CAS k (a b : hist * hist) := exists t r, Forall (fun x => fst x < t)%nat (fst a) /\\\n  fst b = fst a ++ [(t, CAS (Vint r) (vint 0) (vint k))] /\\\n  r <> Int.zero /\\ r <> Int.repr k /\\ snd b = snd a /\\\n  (let v := value_of_hist (fst a) in v <> vint 0 -> v = Vint r).\n\nDefinition wf_hists h l := Forall (fun x => ordered_hist (fst x) /\\ ordered_hist (snd x) /\\\n  Forall int_op (map snd (fst x)) /\\ Forall int_op (map snd (snd x))) h /\\ 0 <= l <= Zlength h /\\\n    Forall (fun x => value_of_hist (fst x) <> vint 0) (sublist 0 l h) /\\\n    Forall (fun x => value_of_hist (fst x) = vint 0) (sublist l (Zlength h) h).\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\nFixpoint make_map h :=\n  match h with\n  | [] => []\n  | (hk, hv) :: rest => let k := make_int (value_of_hist hk) in\n      if eq_dec k 0 then [] else (k, make_int (value_of_hist hv)) :: make_map rest\n  end.\n\nLemma ordered_snoc : forall h t e, ordered_hist h -> Forall (fun x => fst x < t)%nat h ->\n  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 Forall_set : forall P m k v, Forall P m -> P (k, v) -> Forall P (set m k v).\nProof.\n  intros; unfold set.\n  destruct (index_of m k).\n  - apply Forall_upd_Znth; auto.\n  - rewrite Forall_app; split; auto.\nQed.\n\nLemma wf_make_map : forall h, wf_map (make_map h).\nProof.\n  unfold wf_map; induction h; simpl; auto.\n  destruct a.\n  if_tac; simpl; auto.\n  constructor; auto.\n  split; auto.\n  destruct (value_of_hist _); simpl; try (split; computable).\n  apply Int.signed_range.\nQed.\n\nLemma make_map_eq : forall h h', Forall2 (fun a b => value_of_hist (fst a) = value_of_hist (fst b) /\\\n  value_of_hist (snd a) = value_of_hist (snd b)) h h' -> make_map h = make_map h'.\nProof.\n  induction 1; auto; simpl.\n  destruct x, y; simpl in *.\n  destruct H as (-> & ->); rewrite IHForall2; auto.\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 make_map_app : forall h1 h2 (Hnz : Forall (fun x => value_of_hist (fst x) <> vint 0) h1)\n  (Hint : Forall (fun x => Forall int_op (map snd (fst x))) h1),\n  make_map (h1 ++ h2) = make_map h1 ++ make_map h2.\nProof.\n  induction 1; auto; simpl; intros.\n  inv Hint.\n  destruct x as (h, ?).\n  rewrite IHHnz; auto.\n  if_tac; auto.\n  exploit int_op_value_of_hist; eauto; simpl.\n  destruct (value_of_hist h) eqn: Hval; try contradiction; simpl in *.\n  contradiction H; rewrite Hval.\n  f_equal; apply signed_inj; auto.\nQed.\n\nLemma make_map_drop : forall h1 h2 (Hz : Forall (fun x => value_of_hist (fst x) = vint 0) h2),\n  make_map (h1 ++ h2) = make_map h1.\nProof.\n  induction h1; simpl; intros.\n  - destruct h2; auto; simpl.\n    destruct p as (h, ?).\n    if_tac; auto.\n    inv Hz.\n    contradiction H; simpl in *.\n    replace (value_of_hist h) with (vint 0); auto.\n  - rewrite IHh1; auto.\nQed.\n\nLemma index_of_app : forall k m1 m2, index_of (m1 ++ m2) k =\n  match index_of m1 k with Some i => Some i | None => option_map (Z.add (Zlength m1)) (index_of m2 k) end.\nProof.\n  induction m1; simpl; intros.\n  - destruct (index_of m2 k); auto.\n  - destruct a.\n    destruct (eq_dec z k); auto.\n    rewrite IHm1; destruct (index_of m1 k); auto; simpl.\n    destruct (index_of m2 k); auto; simpl.\n    rewrite Zlength_cons; f_equal; omega.\nQed.\n\nLemma index_of_out : forall k m, Forall (fun x => fst x <> k) m -> index_of m k = None.\nProof.\n  intros.\n  pose proof (index_of_spec k m) as Hk.\n  destruct (index_of m k); auto.\n  destruct Hk; eapply Forall_Znth in H; eauto.\n  subst; contradiction H; eauto.\nQed.\n\nLemma make_map_length : forall h (Hnz : Forall (fun x => value_of_hist (fst x) <> vint 0) h)\n  (Hint : Forall (fun x => Forall int_op (map snd (fst x))) h),\n  Zlength (make_map h) = Zlength h.\nProof.\n  induction h; auto; simpl; intros.\n  inv Hnz; inv Hint.\n  destruct a as (hk, ?); simpl in *.\n  exploit int_op_value_of_hist; eauto.\n  destruct (value_of_hist hk); try contradiction; simpl.\n  if_tac; [|rewrite !Zlength_cons, IHh; auto].\n  absurd (Vint i = vint 0); auto; f_equal; apply signed_inj; auto.\nQed.\n\nLemma make_map_no_key : forall h k (Hout : Forall (fun x => make_int (value_of_hist (fst x)) <> k) h),\n  Forall (fun x => fst x <> k) (make_map h).\nProof.\n  induction h; simpl; auto; intros.\n  destruct a.\n  inv Hout.\n  if_tac; auto.\nQed.\n\nLemma make_map_nil : forall h, Forall (fun x => value_of_hist (fst x) = vint 0) h -> make_map h = [].\nProof.\n  destruct h; auto; simpl.\n  destruct p.\n  intro H; inversion H as [|?? Heq]; subst.\n  simpl in *; rewrite Heq; auto.\nQed.\n\nDefinition set_item_trace (h : list (hist * hist)) k v i h' := 0 <= i < Zlength h /\\\n  Forall2 (failed_CAS k) (sublist 0 i h) (sublist 0 i h') /\\\n  (let '(hk, hv) := Znth i h ([], []) in exists t r tv, Forall (fun x => fst x < t)%nat hk /\\\n     Forall (fun x => fst x < tv)%nat hv /\\\n      Znth i h' ([], []) = (hk ++ [(t, CAS r (vint 0) (vint k))], hv ++ [(tv, Store (vint v))]) /\\\n      (r = vint 0 \\/ r = vint k) /\\ (let v := value_of_hist hk in v <> vint 0 -> v = r)) /\\\n  sublist (i + 1) (Zlength h) h = sublist (i + 1) (Zlength h') h'.\n\nLemma set_item_trace_map : forall h k v i h' l (Hwf : wf_hists h l) (Htrace : set_item_trace h k v i h')\n  (Hk : k <> 0) (Hrepk : repable_signed k) (Hrepv : repable_signed v),\n  wf_hists h' (Z.max (i + 1) l) /\\ let m' := make_map (sublist 0 i h' ++ sublist i (Zlength h) h) in\n    wf_map (set m' k v) /\\ incl (make_map h) m' /\\ make_map h' = set m' k v.\nProof.\n  intros.\n  destruct Htrace as (Hbounds & Hfail & Hi & Hrest).\n  destruct (Znth i h ([], [])) as (hk, hv) eqn: Hhi.\n  destruct Hi as (t & r & tv & Ht & Htv & Hi & Hr & Hr0).\n  assert (Zlength h' = Zlength h) as Hlen.\n  { exploit (Znth_inbounds i h' ([], [])).\n    { rewrite Hi; intro X; inversion X as [Heq].\n      symmetry in Heq; apply app_cons_not_nil in Heq; auto. }\n    intro.\n    assert (Zlength (sublist (i + 1) (Zlength h) h) = Zlength (sublist (i + 1) (Zlength h') h')) as Heq\n      by (rewrite Hrest; auto).\n    rewrite !Zlength_sublist in Heq; omega. }\n  assert (i <= Zlength h') by (rewrite Hlen; destruct Hbounds; apply Z.lt_le_incl; auto).\n  assert (0 <= i + 1 <= Zlength h').\n  { rewrite Hlen; destruct Hbounds; split; [|rewrite <- lt_le_1]; auto; omega. }\n  destruct Hwf as (Hwf & ? & Hl1 & Hl2).\n  assert (vint k <> vint 0).\n  { intro; contradiction Hk; apply repr_inj_signed; auto.\n    { split; computable. }\n    { congruence. }}\n  assert (Forall (fun x => value_of_hist (fst x) <> vint 0) (sublist 0 i h')).\n  { rewrite Forall_forall; intros (?, ?) Hin.\n    exploit (Forall2_In_r (failed_CAS k)); eauto.\n    intros ((?, ?) & ? & ? & r1 & ? & ? & ? & ? & ? & ?); simpl in *; subst.\n    unfold value_of_hist; rewrite last_snoc; simpl.\n    destruct (eq_dec (Vint r1) (vint 0)); auto. }\n  assert (h' = sublist 0 i h' ++ Znth i h' ([], []) :: sublist (i + 1) (Zlength h') h') as Hh'.\n  { rewrite <- sublist_next, sublist_rejoin, sublist_same; auto; try omega; rewrite Hlen; auto. }\n  assert ((if eq_dec r (vint 0) then vint k else r) = vint k) as Hif.\n  { if_tac; auto.\n    destruct Hr; [absurd (r = vint 0)|]; auto. }\n  assert (value_of_hist (fst (Znth i h' ([], []))) = vint k) as Hk'.\n  { unfold value_of_hist; rewrite Hi; simpl; rewrite last_snoc; auto. }\n  assert (wf_hists h' (Z.max (i + 1) l)) as Hwf'; [|split; auto; split; [|split]].\n  - split.\n    + rewrite Hh'; clear Hh'; rewrite Forall_app; split; [|constructor].\n      * rewrite Forall_forall; intros (?, ?) Hin.\n        exploit (Forall2_In_r (failed_CAS k)); eauto.\n        intros ((?, ?) & Hin' & ? & ? & ? & ? & ? & ? & ? & ?); simpl in *; subst.\n        apply sublist_In in Hin'; rewrite Forall_forall in Hwf; destruct (Hwf _ Hin') as (? & ? & ? & ?).\n        rewrite map_app, Forall_app; repeat constructor; auto; apply ordered_snoc; auto.\n      * rewrite Hi; simpl.\n        eapply Forall_Znth with (i0 := i) in Hwf; auto.\n        rewrite Hhi in Hwf; destruct Hwf as (? & ? & ? & ?); rewrite !map_app, !Forall_app; repeat constructor;\n          auto; try (apply ordered_snoc; auto).\n        destruct Hr; subst; simpl; auto.\n      * rewrite <- Hrest; apply Forall_sublist; auto.\n    + assert (0 <= Z.max (i + 1) l <= Zlength h'); [|split; auto].\n      { destruct (Z.max_spec (i + 1) l) as [(? & ->) | (? & ->)]; auto; omega. }\n      split; [|apply Forall_suffix_max with (l1 := h); auto; omega].\n      rewrite Hh'; clear Hh'.\n      assert (Zlength h' <= i - 0 + Z.succ (Zlength h' - (i + 1))) by omega.\n      assert (0 <= Zlength h' - i) by omega.\n      destruct (Z.max_spec (i + 1) l) as [(? & ->) | (? & ->)].\n      * rewrite !sublist_app; rewrite ?Zlength_cons, ?Zlength_sublist; auto; try omega.\n        rewrite Z.min_l, Z.min_r, Z.max_r, Z.max_l by omega.\n        rewrite !Z.sub_0_r.\n        rewrite sublist_sublist, !Z.add_0_r by omega.\n        rewrite Forall_app; split; auto.\n        rewrite sublist_0_cons by omega.\n        constructor; [rewrite Hk'; auto|].\n        rewrite sublist_sublist by omega.\n        rewrite <- Z.sub_add_distr, Z.sub_simpl_r.\n        rewrite Z.add_0_l, sublist_parts2; try omega.\n        rewrite <- Hrest.\n        rewrite <- sublist_parts2 by omega.\n        rewrite sublist_parts1 by omega; apply Forall_sublist; auto.\n      * rewrite !sublist_app; rewrite ?Zlength_cons, ?Zlength_sublist; auto; try omega.\n        rewrite !Z.sub_0_r, Z.min_l, Z.min_r, Z.max_r, Z.max_l; auto; try omega.\n        rewrite Z.add_simpl_l.\n        rewrite sublist_same, sublist_len_1 with (d := ([], [])), Znth_0_cons;\n          rewrite ?Zlength_cons, ?Zlength_sublist; auto; try omega; simpl.\n        rewrite Forall_app; split; auto.\n        constructor; auto; rewrite Hk'; auto.\n  - unfold wf_map; rewrite Forall_map; apply Forall_set; auto.\n    rewrite <- Forall_map; apply wf_make_map.\n  - clear Hh'; match goal with H : 0 <= l <= _ |- _ => destruct H end.\n    assert (Forall2 (fun a b => value_of_hist (fst a) = value_of_hist (fst b) /\\\n      value_of_hist (snd a) = value_of_hist (snd b)) (sublist 0 (Z.min i l) h) (sublist 0 (Z.min i l) h')) as Heq.\n    { rewrite Forall2_eq_upto with (d1 := ([] : hist, [] : hist))(d2 := ([] : hist, [] : hist)).\n      assert (0 <= Z.min i l <= Zlength h) as (? & ?).\n      { split; [rewrite Z.min_glb_iff | rewrite Z.min_le_iff]; auto; omega. }\n      split; [rewrite !Zlength_sublist; auto; omega|].\n      rewrite Forall_forall; intros ? Hin.\n      rewrite In_upto, Z2Nat.id in Hin by (apply Zlength_nonneg).\n      assert (value_of_hist (fst (Znth x (sublist 0 (Z.min i l) h) ([], []))) <> vint 0) as Hnz.\n      { apply Forall_Znth; auto.\n        rewrite <- sublist_prefix; apply Forall_sublist; auto. }\n      rewrite Zlength_sublist, Z.sub_0_r in Hin by (auto; omega).\n      assert (x < i).\n      { destruct Hin; eapply Z.lt_le_trans; eauto.\n        apply Z.le_min_l. }\n      exploit (Forall2_Znth _ _ _ ([], []) ([], []) Hfail x); auto.\n      { rewrite Zlength_sublist; omega. }\n      intros (? & r1 & ? & Heq1 & ? & ? & Heq2 & Hv).\n      rewrite !Znth_sublist, Z.add_0_r in Heq1, Heq2, Hv, Hnz; auto; try omega.\n      rewrite !Znth_sublist, Z.add_0_r in Heq2 by omega.\n      rewrite !Znth_sublist, Z.add_0_r by omega.\n      rewrite Heq1, Heq2; simpl; split; auto.\n      unfold value_of_hist in *; rewrite last_snoc; simpl.\n      destruct (eq_dec (Vint r1) (vint 0)); [absurd (r1 = Int.zero); auto; inv e; auto | auto]. }\n    replace h with (sublist 0 l h ++ sublist l (Zlength h) h) at 1\n      by (rewrite sublist_rejoin, sublist_same; auto; omega).\n    rewrite make_map_drop; auto.\n    assert (Forall (fun x => Forall int_op (map snd (fst x))) h').\n    { destruct Hwf'; eapply Forall_impl; [|eauto]; tauto. }\n    destruct (Z.min_spec i l) as [(? & Hmin) | (? & Hmin)]; rewrite Hmin in *; clear Hmin.\n    + assert (Forall (fun x : hist * hist => value_of_hist (fst x) <> vint 0) (sublist 0 i h')).\n      { eapply Forall_Forall2; try apply Heq.\n        { replace i with (Z.min i l) by (apply Z.min_l; omega).\n          rewrite <- sublist_prefix; apply Forall_sublist; auto. }\n        intros ??? (<- & _); auto. }\n      assert (Forall (fun x => Forall int_op (map snd (fst x))) (sublist 0 i h'))\n        by (apply Forall_sublist; auto).\n      rewrite make_map_app; auto.\n      rewrite sublist_split with (lo := i)(mid := l) by omega.\n      rewrite make_map_app, app_assoc.\n      apply incl_appl.\n      rewrite <- make_map_app; auto.\n      erewrite make_map_eq; [apply incl_refl|].\n      rewrite sublist_split with (mid := i) by omega.\n      apply Forall2_app; auto.\n      rewrite Forall2_eq_upto with (d1 := ([] : hist, [] : hist))(d2 := ([] : hist, [] : hist)).\n      split; auto; rewrite Forall_forall; intros; auto.\n      * rewrite sublist_parts1 by omega; apply Forall_sublist; auto.\n      * apply Forall_sublist; eapply Forall_impl, Hwf; tauto.\n    + rewrite sublist_split with (mid := l)(hi := i) by omega.\n      rewrite <- app_assoc, make_map_app.\n      apply incl_appl.\n      erewrite make_map_eq; [apply incl_refl | auto].\n      * eapply Forall_Forall2; try apply Heq; auto.\n        intros ??? (<- & _); auto.\n      * apply Forall_sublist; auto.\n  - unfold set.\n    destruct Hwf' as (? & ? & Hl1' & ?).\n    assert (Forall (fun x => Forall int_op (map snd (fst x))) (sublist 0 i h')).\n    { eapply Forall_sublist, Forall_impl; [|eauto]; tauto. }\n    rewrite Hh' at 1; clear Hh'.\n    rewrite make_map_app by auto.\n    assert (Forall (fun x => make_int (value_of_hist (fst x)) <> k) (sublist 0 i h')) as Hmiss.\n    { rewrite Forall_forall; intros (hk', hv') Hin.\n      exploit (Forall2_In_r _ (hk', hv') _ _ Hfail); auto.\n      intros (? & ? & ? & r1 & ? & Heqi & ? & ? & ? & ?); subst.\n      unfold value_of_hist; rewrite Heqi, last_snoc; simpl.\n      destruct (eq_dec (Vint r1) (vint 0)); simpl.\n      { absurd (r1 = Int.zero); auto; inv e; auto. }\n      intro; absurd (r1 = Int.repr k); subst; auto.\n      rewrite Int.repr_signed; auto. }\n    rewrite make_map_app at 1 by auto.\n    rewrite index_of_app, index_of_out, make_map_length by (auto; apply make_map_no_key; auto); simpl.\n    rewrite Hi; simpl.\n    unfold value_of_hist; rewrite !last_snoc; simpl.\n    rewrite Hif; simpl.\n    rewrite !Int.signed_repr; auto.\n    destruct (eq_dec k 0); [contradiction Hk; auto|].\n    destruct (zlt i l).\n    + destruct (eq_dec (value_of_hist hk) (vint 0)).\n      { eapply Forall_Znth with (i0 := i) in Hl1; [|rewrite Zlength_sublist; omega].\n        rewrite Znth_sublist, Z.add_0_r, Hhi in Hl1 by omega; contradiction Hl1. }\n      assert (value_of_hist hk = vint k) as Hik.\n      { rewrite Hr0; auto.\n        rewrite Hr0 in n0; auto.\n        destruct Hr; [contradiction n0; auto | auto]. }\n      erewrite sublist_next with (i0 := i), Hhi by omega; simpl.\n      rewrite Hik; simpl.\n      rewrite Int.signed_repr; auto.\n      destruct (eq_dec k 0); [contradiction Hk; auto | simpl].\n      rewrite eq_dec_refl; simpl.\n      rewrite make_map_app, Z.add_0_r by auto.\n      rewrite upd_Znth_app2; rewrite make_map_length; auto.\n      rewrite Zminus_diag, upd_Znth0; simpl.\n      rewrite Hik; simpl.\n      rewrite Int.signed_repr; auto.\n      destruct (eq_dec k 0); [contradiction Hk; auto | simpl].\n      rewrite sublist_1_cons, Zlength_cons.\n      unfold Z.succ; rewrite Z.add_simpl_r.\n      rewrite sublist_same with (hi := Zlength (make_map _)), Hrest; auto.\n      { pose proof (Zlength_nonneg (make_map ((hk, hv) :: sublist (i + 1) (Zlength h) h))); omega. }\n    + erewrite sublist_next with (i0 := i) at 1 by omega; simpl.\n      exploit (Forall_Znth (fun x => value_of_hist (fst x) = vint 0) (sublist l (Zlength h) h) (i - l)); auto.\n      { rewrite Zlength_sublist; omega. }\n      rewrite Znth_sublist, Z.sub_simpl_r, Hhi by omega; simpl.\n      rewrite Hhi; intros ->; simpl.\n      rewrite make_map_nil with (h := sublist (i + 1) _ _).\n      rewrite make_map_drop; auto.\n      { replace i with (i - l + l) by (apply Z.sub_simpl_r).\n        rewrite <- sublist_suffix by omega; apply Forall_sublist; auto. }\n      { rewrite <- Hrest; replace (i + 1) with (i + 1 - l + l) by (apply Z.sub_simpl_r).\n        rewrite <- sublist_suffix by omega; apply Forall_sublist; auto. }\nQed.\n\n(* What can a thread know?\n   At least certain keys exist, and whatever it did last took effect.\n   It can even rely on the indices of known keys. *)\nDefinition set_item_spec :=\n DECLARE _set_item\n  WITH key : Z, value : Z, p : val, sh : share, entries : list val, h : list (hist * hist), l : Z\n  PRE [ _key OF tint, _value OF tint ]\n   PROP (repable_signed key; repable_signed value; readable_share sh; key <> 0; Forall isptr entries;\n         Zlength h = 20; wf_hists h l)\n   LOCAL (temp _key (vint key); temp _value (vint value); gvar _m_entries p)\n   SEP (data_at sh (tarray (tptr tentry) 20) entries p;\n        fold_right_sepcon (map (atomic_entry sh) entries);\n        entry_hists entries h)\n  POST [ tvoid ]\n   EX i : Z, EX h' : list (hist * hist),\n   PROP (set_item_trace h key value i h')\n   LOCAL ()\n   SEP (data_at sh (tarray (tptr tentry) 20) entries p;\n        fold_right_sepcon (map (atomic_entry sh) entries);\n        entry_hists entries h').\n(* set_item_trace_map describes the properties on the resulting map. *)\n\nDefinition failed_load k (a b : hist * hist) := exists t r, Forall (fun x => fst x < t)%nat (fst a) /\\\n  fst b = fst a ++ [(t, Load (Vint r))] /\\ r <> Int.zero /\\ r <> Int.repr k /\\ snd b = snd a /\\\n  (let v := value_of_hist (fst a) in v <> vint 0 -> v = Vint r).\n\n(* get_item can return 0 in two cases: if the key is not in the map, or if its value is 0.\n   In correct use, the latter should only occur if the value has not been initialized.\n   Conceptually, this is still linearizable because we could have just checked before the key was added,\n   but at a finer-grained level we can tell the difference from the history, so we might as well keep\n   this information. *)\nDefinition get_item_trace (h : list (hist * hist)) k v i h' := 0 <= i < Zlength h /\\\n  Forall2 (failed_load k) (sublist 0 i h) (sublist 0 i h') /\\\n  (let '(hk, hv) := Znth i h ([], []) in exists t r, Forall (fun x => fst x < t)%nat hk /\\\n     fst (Znth i h' ([], [])) = hk ++ [(t, Load (vint r))] /\\\n     (v = 0 /\\ r = 0 /\\ snd (Znth i h' ([], [])) = hv \\/\n      r = k /\\ exists tv, Forall (fun x => fst x < tv)%nat hv /\\\n        snd (Znth i h' ([], [])) = hv ++ [(tv, Load (vint v))]) /\\\n    (let v := value_of_hist hk in v <> vint 0 -> v = vint r)) /\\\n  sublist (i + 1) (Zlength h) h = sublist (i + 1) (Zlength h') h'.\n\nLemma index_of_iff_out : forall m k, index_of m k = None <-> ~In k (map fst m).\nProof.\n  split; intro.\n  - induction m; auto; simpl in *.\n    destruct a.\n    destruct (eq_dec z k); [discriminate|].\n    destruct (index_of m k); [discriminate|].\n    intros [? | ?]; auto.\n    contradiction IHm.\n  - apply index_of_out.\n    rewrite Forall_forall; repeat intro; contradiction H.\n    rewrite in_map_iff; eauto.\nQed.\n\nCorollary get_fail_iff : forall m k, get m k = None <-> ~In k (map fst m).\nProof.\n  intros; unfold get; rewrite <- index_of_iff_out.\n  destruct (index_of m k); simpl; split; auto; discriminate.\nQed.\n\nLemma Znth_make_map : forall d h i (Hi : 0 <= i < Zlength h)\n  (Hnz : Forall (fun x => value_of_hist (fst x) <> vint 0) (sublist 0 (i + 1) h))\n  (Hint : Forall (fun x => Forall int_op (map snd (fst x))) (sublist 0 (i + 1) h)),\n  Znth i (make_map h) d = (make_int (value_of_hist (fst (Znth i h ([], [])))),\n                           make_int (value_of_hist (snd (Znth i h ([], []))))).\nProof.\n  induction h; simpl; intros.\n  { rewrite Zlength_nil in *; omega. }\n  destruct a.\n  rewrite Zlength_cons in *.\n  rewrite sublist_0_cons, Z.add_simpl_r in Hnz, Hint by omega.\n  inv Hnz; inv Hint.\n  exploit int_op_value_of_hist; eauto; intro; simpl in *.\n  destruct (value_of_hist l) eqn: Hfst; try contradiction; simpl.\n  if_tac; [absurd (Vint i0 = vint 0); auto; f_equal; apply signed_inj; auto|].\n  destruct (eq_dec i 0).\n  - subst; rewrite !Znth_0_cons; simpl; auto.\n    rewrite Hfst; auto.\n  - rewrite !Znth_pos_cons by omega; apply IHh; rewrite ?Z.sub_simpl_r; auto; omega.\nQed.\n\nLemma get_item_trace_map : forall h k v i h' l (Hwf : wf_hists h l) (Htrace : get_item_trace h k v i h')\n  (Hk : k <> 0) (Hrepk : repable_signed k) (Hrepv : repable_signed v),\n  match get (make_map h') k with\n  | Some v' => v' = v /\\ wf_hists h' (Z.max (i + 1) l) /\\ incl (set (make_map h) k v) (make_map h')\n  | None => l <= i /\\ wf_hists h' i /\\ v = 0 /\\ incl (make_map h) (make_map h') end.\nProof.\n  intros.\n  destruct Htrace as (Hbounds & Hfail & Hi & Hrest).\n  destruct (Znth i h ([], [])) as (hk, hv) eqn: Hhi.\n  destruct Hi as (t & r & Ht & Hi1 & Hi2 & Hr0).\n  assert (Zlength h' = Zlength h) as Hlen.\n  { exploit (Znth_inbounds i h' ([], [])).\n    { destruct (Znth i h' ([], [])) as (hk', hv'); intro X; inv X.\n      apply app_cons_not_nil in Hi1; auto. }\n    intro.\n    assert (Zlength (sublist (i + 1) (Zlength h) h) = Zlength (sublist (i + 1) (Zlength h') h')) as Heq\n      by (rewrite Hrest; auto).\n    rewrite !Zlength_sublist in Heq; omega. }\n  assert (i <= Zlength h') by (rewrite Hlen; destruct Hbounds; apply Z.lt_le_incl; auto).\n  assert (0 <= i + 1 <= Zlength h').\n  { rewrite Hlen; destruct Hbounds; split; [|rewrite <- lt_le_1]; auto; omega. }\n  destruct Hwf as (Hwf & ? & Hl1 & Hl2).\n  assert (vint k <> vint 0).\n  { intro; contradiction Hk; apply repr_inj_signed; auto.\n    { split; computable. }\n    { congruence. }}\n  assert (Forall (fun x => value_of_hist (fst x) <> vint 0) (sublist 0 i h')).\n  { rewrite Forall_forall; intros (?, ?) Hin.\n    exploit (Forall2_In_r (failed_load k)); eauto.\n    intros ((?, ?) & ? & ? & r1 & ? & ? & ? & ? & ? & ?); simpl in *; subst.\n    unfold value_of_hist; rewrite last_snoc; simpl.\n    intro X; absurd (r1 = Int.zero); auto; inv X; auto. }\n  assert (h' = sublist 0 i h' ++ Znth i h' ([], []) :: sublist (i + 1) (Zlength h') h') as Hh'.\n  { rewrite <- sublist_next, sublist_rejoin, sublist_same; auto; try omega; rewrite Hlen; auto. }\n  assert (Forall (fun x => ordered_hist (fst x) /\\ ordered_hist (snd x) /\\ Forall int_op (map snd (fst x)) /\\\n    Forall int_op (map snd (snd x))) h') as Hwf'.\n  { rewrite Hh'; clear Hh'; rewrite Forall_app; split; [|constructor].\n    - eapply Forall_Forall2; try apply Hfail; [apply Forall_sublist; auto|].\n      intros (?, ?) (?, ?) (? & ? & ? & ?) (? & ? & ? & ? & ? & ? & ? & ?); simpl in *; subst.\n      rewrite map_app, Forall_app; repeat constructor; auto; apply ordered_snoc; auto.\n    - eapply Forall_Znth with (i0 := i) in Hwf; auto.\n      rewrite Hhi in Hwf; destruct Hwf as (? & ? & ? & ?).\n      rewrite Hi1; split; [apply ordered_snoc; auto|].\n      destruct Hi2 as [(? & ? & ->) | (? & ? & ? & ->)]; rewrite !map_app, !Forall_app;\n        repeat constructor; auto; try (apply ordered_snoc; auto).\n    - rewrite <- Hrest; apply Forall_sublist; auto. }\n  assert (Forall (fun x => Forall int_op (map snd (fst x))) (sublist 0 i h')).\n  { eapply Forall_sublist, Forall_impl, Hwf'; tauto. }\n  assert (Forall (fun x => make_int (value_of_hist (fst x)) <> k) (sublist 0 i h')) as Hmiss.\n  { clear Hh'; rewrite Forall_forall; intros (hk', hv') Hin.\n    exploit (Forall2_In_r _ (hk', hv') _ _ Hfail); auto.\n    intros (? & ? & ? & r1 & ? & Heqi & ? & ? & ? & ?); subst.\n    unfold value_of_hist; rewrite Heqi, last_snoc; simpl.\n    intro; absurd (r1 = Int.repr k); subst; auto.\n    rewrite Int.repr_signed; auto. }\n  unfold get; destruct (index_of (make_map h') k) eqn: Hindex; simpl.\n  - rewrite Hh', make_map_app, index_of_app, index_of_out in Hindex\n      by (auto; apply make_map_no_key; auto).\n    simpl in Hindex.\n    destruct (Znth i h' ([], [])) as (hk', hv') eqn: Hhi'; simpl in *; subst hk'.\n    unfold value_of_hist in Hindex; rewrite last_snoc in Hindex; simpl in Hindex.\n    destruct Hi2 as [(? & ? & ?) | (? & tv & ? & ?)]; subst r hv'; [discriminate|].\n    rewrite Int.signed_repr in Hindex by auto.\n    destruct (eq_dec k 0); [contradiction Hk; auto|].\n    simpl in Hindex.\n    rewrite eq_dec_refl in Hindex; simpl in Hindex.\n    inversion Hindex; subst z.\n    rewrite make_map_length, Zlength_sublist, Z.sub_simpl_r by (auto; omega).\n    assert (0 <= Z.max (i + 1) l <= Zlength h' /\\\n      Forall (fun x => value_of_hist (fst x) <> vint 0) (sublist 0 (Z.max (i + 1) l) h') /\\\n      Forall (fun x => value_of_hist (fst x) = vint 0) (sublist (Z.max (i + 1) l) (Zlength h') h'))\n      as (? & Hl1' & Hl2'); [|split; [|split; [split; auto|]]].\n    + assert (0 <= Z.max (i + 1) l <= Zlength h'); [|split; auto].\n      { destruct (Z.max_spec (i + 1) l) as [(? & ->) | (? & ->)]; auto; omega. }\n      split; [|apply Forall_suffix_max with (l1 := h); auto; omega].\n      rewrite Hh'; clear Hh'.\n      assert (Zlength h' <= i - 0 + Z.succ (Zlength h' - (i + 1))) by omega.\n      assert (0 <= Zlength h' - i) by omega.\n      destruct (Z.max_spec (i + 1) l) as [(? & ->) | (? & ->)].\n      * rewrite !sublist_app; rewrite ?Zlength_cons, ?Zlength_sublist; auto; try omega.\n        rewrite Z.min_l, Z.min_r, Z.max_r, Z.max_l by omega.\n        rewrite !Z.sub_0_r.\n        rewrite sublist_sublist, !Z.add_0_r by omega.\n        rewrite Forall_app; split; auto.\n        rewrite sublist_0_cons by omega.\n        constructor; [unfold value_of_hist; simpl; rewrite last_snoc; auto|].\n        rewrite sublist_sublist by omega.\n        rewrite <- Z.sub_add_distr, Z.sub_simpl_r.\n        rewrite Z.add_0_l, sublist_parts2; try omega.\n        rewrite <- Hrest.\n        rewrite <- sublist_parts2 by omega.\n        rewrite sublist_parts1 by omega; apply Forall_sublist; auto.\n      * rewrite !sublist_app; rewrite ?Zlength_cons, ?Zlength_sublist; auto; try omega.\n        rewrite !Z.sub_0_r, Z.min_l, Z.min_r, Z.max_r, Z.max_l; auto; try omega.\n        rewrite Z.add_simpl_l.\n        rewrite sublist_same, sublist_len_1 with (d := ([], [])), Znth_0_cons;\n          rewrite ?Zlength_cons, ?Zlength_sublist; auto; try omega; simpl.\n        rewrite Forall_app; split; auto.\n        constructor; auto; unfold value_of_hist; simpl; rewrite last_snoc; auto.\n    + rewrite Znth_make_map, Hhi'; simpl.\n      unfold value_of_hist; rewrite last_snoc; simpl.\n      apply Int.signed_repr; auto.\n      { omega. }\n      { rewrite sublist_split with (mid := i), Forall_app by omega; split; auto.\n        erewrite sublist_len_1, Hhi' by omega; repeat constructor; simpl.\n        unfold value_of_hist; rewrite last_snoc; auto. }\n      { eapply Forall_sublist, Forall_impl, Hwf'; tauto. }\n    + unfold set.\n      rewrite Hh'; clear Hh'.\n      rewrite make_map_app by auto; simpl.\n      unfold value_of_hist; rewrite !last_snoc; simpl.\n      rewrite !Int.signed_repr by auto.\n      destruct (eq_dec k 0); [contradiction Hk; auto|].\n      assert (0 <= Z.min i l <= Zlength h) as (? & ?).\n      { split; [rewrite Z.min_glb_iff | rewrite Z.min_le_iff]; auto; omega. }\n      replace h with (sublist 0 (Z.min i l) h ++ sublist (Z.min i l) (Zlength h) h)\n        by (rewrite sublist_rejoin, sublist_same; auto; omega).\n      assert (Forall (fun x => value_of_hist (fst x) <> vint 0) (sublist 0 (Z.min i l) h)).\n      { rewrite <- sublist_prefix; apply Forall_sublist; auto. }\n      assert (Forall (fun x => Forall int_op (map snd (fst x))) (sublist 0 (Z.min i l) h)).\n      { eapply Forall_sublist, Forall_impl, Hwf; tauto. }\n      rewrite make_map_app, index_of_app, index_of_out; auto.\n      assert (incl (make_map (sublist 0 (Z.min i l) h)) (make_map (sublist 0 (Z.min i l) h'))).\n      { erewrite make_map_eq; [apply incl_refl|].\n        rewrite Forall2_eq_upto with (d1 := ([] : hist, [] : hist))(d2 := ([] : hist, [] : hist)).\n        split; [rewrite !Zlength_sublist; auto; omega|].\n        rewrite Forall_forall; intros ? Hin.\n        rewrite In_upto, Z2Nat.id in Hin by (apply Zlength_nonneg).\n        assert (value_of_hist (fst (Znth x (sublist 0 (Z.min i l) h) ([], []))) <> vint 0) as Hnz.\n        { apply Forall_Znth; auto. }\n        rewrite Zlength_sublist, Z.sub_0_r in Hin by (auto; omega).\n        assert (x < i).\n        { destruct Hin; eapply Z.lt_le_trans; eauto.\n          apply Z.le_min_l. }\n        exploit (Forall2_Znth _ _ _ ([], []) ([], []) Hfail x); auto.\n        { rewrite Zlength_sublist; omega. }\n        intros (? & r1 & ? & Heq1 & ? & ? & Heq2 & Hv).\n        rewrite !Znth_sublist, Z.add_0_r in Heq1, Heq2, Hv, Hnz; auto; try omega.\n        rewrite !Znth_sublist, Z.add_0_r in Heq1, Heq2 by omega.\n        rewrite !Znth_sublist, Z.add_0_r by omega.\n        rewrite Heq1, Heq2; simpl; split; auto.\n        unfold value_of_hist in *; rewrite last_snoc; simpl.\n        destruct (eq_dec (Vint r1) (vint 0)); [absurd (r1 = Int.zero); auto; inv e; auto | auto]. }\n      destruct (Z.min_spec i l) as [(? & Hmin) | (? & Hmin)]; rewrite Hmin in *.\n      * erewrite sublist_next with (i0 := i) by omega.\n        rewrite Hhi; simpl.\n        rewrite Hr0; simpl.\n        rewrite Int.signed_repr by auto; simpl.\n        destruct (eq_dec k 0); [contradiction Hk; auto | simpl].\n        rewrite eq_dec_refl; simpl.\n        rewrite Z.add_0_r, upd_Znth_app2; rewrite make_map_length; auto.\n        rewrite Zminus_diag, upd_Znth0, sublist_1_cons, Zlength_cons.\n        unfold Z.succ; rewrite Z.add_simpl_r, sublist_same with (hi := Zlength _) by auto.\n        rewrite Hrest; apply incl_app; [apply incl_appl; auto | apply incl_appr, incl_refl].\n        { pose proof (Zlength_nonneg\n            ((k, make_int (value_of_hist hv)) :: make_map (sublist (i + 1) (Zlength h) h))); omega. }\n        { eapply Forall_Znth with (i0 := i) in Hl1; [|rewrite Zlength_sublist; omega].\n          rewrite Znth_sublist, Z.add_0_r, Hhi in Hl1 by omega; auto. }\n      * rewrite make_map_nil with (h := sublist l _ _), app_nil_r; auto; simpl.\n        apply incl_app; [apply incl_appl | apply incl_appr; constructor; simpl in *; tauto].\n        rewrite sublist_split with (mid := l)(hi := i) by omega.\n        rewrite make_map_app.\n        apply incl_appl; auto.\n        { replace l with (Z.min l (Z.max (i + 1) l)).\n          rewrite <- sublist_prefix; apply Forall_sublist; auto.\n          { apply Z.min_l, Zmax_bound_r, Z.le_refl. } }\n        { eapply Forall_sublist, Forall_impl, Hwf'; tauto. }\n      * apply make_map_no_key.\n        rewrite Forall_forall; intros ? Hin.\n        rewrite Forall_forall in Hl1; specialize (Hl1 x).\n        exploit (Forall2_In_l _ x _ _ Hfail).\n        { rewrite Z.min_comm, <- sublist_prefix in Hin; eapply sublist_In; eauto. }\n        intros (? & ? & ? & r1 & ? & ? & ? & ? & ? & Heq); simpl in *; subst.\n        rewrite Heq; simpl.\n        intro; absurd (r1 = Int.repr k); auto.\n        apply signed_inj; auto.\n        rewrite Int.signed_repr; auto.\n        { apply Hl1.\n          rewrite <- sublist_prefix in Hin; eapply sublist_In; eauto. }\n  - rewrite index_of_iff_out in Hindex.\n    destruct Hi2 as [(? & ? & Hi2) | (? & ? & ? & Hi2)]; subst r.\n    clear Hh'.\n    assert (value_of_hist hk = vint 0) as Hz.\n    { destruct (eq_dec (value_of_hist hk) (vint 0)); auto. }\n    destruct (zlt i l).\n    { eapply Forall_Znth with (i0 := i) in Hl1; [|rewrite Zlength_sublist; omega].\n      rewrite Znth_sublist, Z.add_0_r, Hhi in Hl1 by omega; contradiction Hl1. }\n    split; [omega|].\n    assert (0 <= i <= Zlength h' /\\\n      Forall (fun x => value_of_hist (fst x) <> vint 0) (sublist 0 i h') /\\\n      Forall (fun x => value_of_hist (fst x) = vint 0) (sublist i (Zlength h') h'))\n      as (? & Hl1' & Hl2'); [|split; split; auto].\n    + split; [omega|]; split.\n      * rewrite Forall_forall; intros.\n        exploit (Forall2_In_r (failed_load k)); eauto.\n        intros ((?, ?) & ? & ? & r1 & ? & -> & ? & ? & ? & ?); simpl in *; subst.\n        unfold value_of_hist; rewrite last_snoc; simpl.\n        intro X; absurd (r1 = Int.zero); auto; inv X; auto.\n      * erewrite sublist_next by omega; constructor;\n          [rewrite Hi1; unfold value_of_hist; rewrite last_snoc; auto|].\n        rewrite <- Hrest.\n        replace (i + 1) with (i + 1 - l + l) by (apply Z.sub_simpl_r).\n        rewrite <- sublist_suffix by omega; apply Forall_sublist; auto.\n    + replace h with (sublist 0 l h ++ sublist l (Zlength h) h)\n        by (rewrite sublist_rejoin, sublist_same; auto; omega).\n      replace h' with (sublist 0 l h' ++ sublist l (Zlength h') h')\n        by (rewrite sublist_rejoin, sublist_same; auto; omega).\n      rewrite make_map_drop, make_map_app; auto.\n      apply incl_appl; erewrite make_map_eq; [apply incl_refl|].\n      rewrite Forall2_eq_upto with (d1 := ([] : hist, [] : hist))(d2 := ([] : hist, [] : hist)).\n      split; [rewrite !Zlength_sublist; auto; omega|].\n      rewrite Forall_forall; intros ? Hin.\n      rewrite In_upto, Z2Nat.id in Hin by (apply Zlength_nonneg).\n      assert (value_of_hist (fst (Znth x (sublist 0 l h) ([], []))) <> vint 0) as Hnz.\n      { apply Forall_Znth; auto. }\n      rewrite Zlength_sublist, Z.sub_0_r in Hin by (auto; omega).\n      assert (x < i) by omega.\n      exploit (Forall2_Znth _ _ _ ([], []) ([], []) Hfail x); auto.\n      { rewrite Zlength_sublist; omega. }\n      intros (? & r1 & ? & Heq1 & ? & ? & Heq2 & Hv).\n      rewrite !Znth_sublist, Z.add_0_r in Heq1, Heq2, Hv, Hnz; auto; try omega.\n      rewrite !Znth_sublist, Z.add_0_r in Heq1, Heq2 by omega.\n      rewrite !Znth_sublist, Z.add_0_r by omega.\n      rewrite Heq1, Heq2; simpl; split; auto.\n      unfold value_of_hist at 2; rewrite last_snoc; auto.\n      { replace l with (Z.min l i) by (apply Z.min_l; omega).\n        rewrite <- sublist_prefix; apply Forall_sublist; auto. }\n      { eapply Forall_sublist, Forall_impl, Hwf'; tauto. }\n    + contradiction Hindex.\n      assert (Forall (fun x => value_of_hist (fst x) <> vint 0) (sublist 0 i h' ++ [Znth i h' ([], [])])).\n      { rewrite Forall_app; split; auto; repeat constructor.\n        rewrite Hi1; unfold value_of_hist; rewrite last_snoc; auto. }\n      assert (Forall (fun x => Forall int_op (map snd (fst x))) (sublist 0 (i + 1) h')) as Hints.\n      { eapply Forall_sublist, Forall_impl, Hwf'; tauto. }\n      rewrite in_map_iff; exists (Znth i (make_map h') (0, 0)); split.\n      * rewrite Znth_make_map; auto; simpl.\n        rewrite Hi1; unfold value_of_hist; rewrite last_snoc; simpl.\n        rewrite Int.signed_repr; auto.\n        { omega. }\n        { erewrite sublist_split with (mid := i), sublist_len_1 by omega; eauto. }\n      * apply Znth_In.\n        rewrite Hh'.\n        change (Znth i h' ([], []) :: _) with ([Znth i h' ([], [])] ++ sublist (i + 1) (Zlength h') h').\n        erewrite sublist_split with (mid := i), sublist_len_1 in Hints by omega.\n        rewrite app_assoc, make_map_app, Zlength_app, make_map_length, Zlength_app, Zlength_sublist,\n          Zlength_cons, Zlength_nil by (eauto; omega).\n        pose proof (Zlength_nonneg (make_map (sublist (i + 1) (Zlength h') h'))); omega.\nQed.\n\n(* Read the most recently written value. *)\nDefinition get_item_spec :=\n DECLARE _get_item\n  WITH key : Z, p : val, sh : share, entries : list val, h : list (hist * hist), l : Z\n  PRE [ _key OF tint, _value OF tint ]\n   PROP (repable_signed key; readable_share sh; key <> 0; Forall isptr entries; Zlength h = 20; wf_hists h l)\n   LOCAL (temp _key (vint key); gvar _m_entries p)\n   SEP (data_at sh (tarray (tptr tentry) 20) entries p;\n        fold_right_sepcon (map (atomic_entry sh) entries);\n        entry_hists entries h)\n  POST [ tint ]\n   EX value : Z, EX i : Z, EX h' : list (hist * hist),\n   PROP (repable_signed value; get_item_trace h key value i h')\n   LOCAL (temp ret_temp (vint value))\n   SEP (data_at sh (tarray (tptr tentry) 20) entries p;\n        fold_right_sepcon (map (atomic_entry sh) entries);\n        entry_hists entries h').\n\nDefinition Gprog : funspecs := ltac:(with_library prog [surely_malloc_spec; atomic_CAS_spec; atomic_load_spec;\n  atomic_store_spec; set_item_spec; get_item_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\nOpaque upto.\n\nLtac cancel_for_forward_call ::= repeat (rewrite ?sepcon_andp_prop', ?sepcon_andp_prop);\n  repeat (apply andp_right; [auto; apply prop_right; auto|]); fast_cancel.\n\nLtac entailer_for_return ::= go_lower; entailer'.\n\nLemma apply_int_ops : forall v h i (Hv : verif_atomics.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\nLemma failed_CAS_fst : forall v h h', Forall2 (failed_CAS v) h h' -> map snd h' = map snd h.\nProof.\n  induction 1; auto.\n  destruct H as (? & ? & ? & ? & ? & ? & ? & ?); simpl; f_equal; auto.\nQed.\n\nLemma body_set_item : semax_body Vprog Gprog f_set_item set_item_spec.\nProof.\n  start_function.\n  forward.\n  eapply semax_pre with (P' := EX i : Z, EX h' : list (hist * hist),\n    PROP (0 <= i < 20; Forall2 (failed_CAS key) (sublist 0 i h) (sublist 0 i h');\n          sublist i (Zlength h) h = sublist i (Zlength h') h')\n    LOCAL (temp _idx (vint i); temp _key (vint key); temp _value (vint value); gvar _m_entries p)\n    SEP (data_at sh (tarray (tptr tentry) 20) entries p; fold_right_sepcon (map (atomic_entry sh) entries);\n         entry_hists entries h')).\n  { Exists 0 h; rewrite sublist_nil; entailer!. }\n  eapply semax_loop.\n  - Intros i h'; forward.\n    assert (Zlength h' = Zlength h) as Hlen.\n    { assert (Zlength (sublist i (Zlength h) h) = Zlength (sublist i (Zlength h') h')) as Heq\n        by (replace (sublist i (Zlength h) h) with (sublist i (Zlength h') h'); auto).\n      rewrite !Zlength_sublist in Heq; try omega.\n      destruct (Z_le_dec i (Zlength h')); [omega|].\n      unfold sublist in Heq.\n      rewrite Z2Nat_neg in Heq by omega.\n      simpl in Heq; rewrite Zlength_nil in Heq; omega. }\n    assert (i <= Zlength h') by omega.\n    assert (map snd h' = map snd h) as Hsnd.\n    { erewrite <- sublist_same with (al := h') by eauto.\n      erewrite <- sublist_same with (al := h) by eauto.\n      rewrite sublist_split with (al := h')(mid := i) by omega.\n      rewrite sublist_split with (al := h)(mid := i) by omega.\n      rewrite Hlen in *; rewrite !map_app; f_equal; [|congruence].\n      eapply failed_CAS_fst; eauto. }\n    assert_PROP (Zlength entries = 20) by entailer!.\n    assert (0 <= i < Zlength entries) by (replace (Zlength entries) with 20; auto).\n    forward.\n    { entailer!.\n      apply isptr_is_pointer_or_null, Forall_Znth; auto. }\n    rewrite extract_nth_sepcon with (i := i), Znth_map with (d' := Vundef); try rewrite Zlength_map; auto.\n    unfold entry_hists; erewrite extract_nth_sepcon with (i := i)(l := map _ _), Znth_map, Znth_upto; simpl;\n      auto; try omega.\n    unfold atomic_entry; Intros lkey lval.\n    rewrite atomic_loc_isptr.\n    forward.\n    forward.\n    destruct (Znth i h' ([], [])) as (hki, hvi) eqn: Hhi.\n    forward_call (Tsh, sh, field_address tentry [StructField _key] (Znth i entries Vundef), lkey, vint 0,\n      vint key, vint 0, hki,\n      fun (h : hist) c v => !!(c = vint 0 /\\ v = vint key /\\ h = hki) && emp,\n      k_R,\n      fun (h : hist) (v : val) => !!(forall v0, last_value hki v0 -> v0 <> vint 0 -> v = v0) && emp).\n(* Given that I have to do this, maybe better to remove the arguments from P. *)\n    { entailer!.\n      rewrite field_address_offset; simpl.\n      rewrite isptr_offset_val_zero; auto.\n      { rewrite field_compatible_cons; simpl.\n        split; [unfold in_members; simpl|]; auto. } }\n    { repeat (split; auto).\n      intros ?????????????? Ha.\n      unfold k_R in *; simpl in *.\n      eapply semax_pre, Ha.\n      go_lowerx; entailer!.\n      repeat split.\n      + rewrite Forall_app; repeat constructor; auto.\n        apply apply_int_ops in Hvx; auto.\n      + intros ? Hin; rewrite in_app in Hin.\n        destruct Hin as [? | [? | ?]]; [| |contradiction].\n        * intros.\n          replace vx with (value_of e) by (symmetry; auto).\n          if_tac; auto; absurd (value_of e = vint 0); auto.\n        * subst; simpl; intros.\n          if_tac; if_tac; auto; absurd (vx = vint 0); auto.\n      + intros ? [(? & ?) | (? & ? & Hin & ? & ?)] Hn; [contradiction Hn; auto|].\n        specialize (Hhist _ _ Hin); apply nth_error_In in Hhist; subst; auto.\n      + apply andp_right; auto.\n        eapply derives_trans, precise_weak_precise, precise_andp2; auto. }\n    Intros x; destruct x as (t, v); simpl in *.\n    destruct v; try contradiction.\n    match goal with |- semax _ (PROP () (LOCALx ?Q (SEPx ?R))) _ _ =>\n      forward_if (PROP () (LOCALx (temp _t'2 (vint (if eq_dec i0 Int.zero then 1\n        else if eq_dec i0 (Int.repr key) then 1 else 0)) :: Q) (SEPx R))) end.\n    { forward.\n      subst; rewrite eq_dec_refl; apply drop_tc_environ. }\n    { forward.\n      destruct (eq_dec i0 Int.zero); [absurd (i0 = Int.repr 0); auto|].\n      simpl force_val.\n      destruct (eq_dec i0 (Int.repr key)).\n      + subst; rewrite Int.eq_true; apply drop_tc_environ.\n      + rewrite Int.eq_false; [apply drop_tc_environ | auto]. }\n    assert (Znth i h ([], []) = Znth i h' ([], []) /\\\n      sublist (i + 1) (Zlength h) h = sublist (i + 1) (Zlength h') h') as (Heq & Hi1).\n    { match goal with H : sublist _ _ h = sublist _ _ h' |- _ =>\n        erewrite sublist_next with (d := ([] : hist, [] : hist)),\n                 sublist_next with (l0 := h')(d := ([] : hist, [] : hist)) in H by omega; inv H; auto end. }\n    assert (ordered_hist hki).\n    { match goal with H : wf_hists h l |- _ => destruct H as (Hwf & _) end.\n      eapply Forall_Znth with (i1 := i) in Hwf; [|omega].\n      rewrite Heq, Hhi in Hwf; tauto. }\n    match goal with |- semax _ (PROP () (LOCALx ?Q (SEPx ?R))) _ _ =>\n      forward_if (PROP (i0 <> Int.zero /\\ i0 <> Int.repr key) (LOCALx Q (SEPx R))) end.\n    + rewrite (atomic_loc_isptr _ lval).\n      forward.\n      forward.\n      forward_call (Tsh, sh, field_address tentry [StructField _value] (Znth i entries Vundef), lval,\n        vint value, vint 0, hvi, fun (h : hist) v => !!(v = vint value) && emp,\n        v_R, fun (h : hist) => emp).\n      { entailer!.\n        rewrite field_address_offset; auto.\n        { rewrite field_compatible_cons; simpl.\n          split; [unfold in_members; simpl|]; auto. } }\n      { repeat (split; auto).\n        intros ????????????? Ha.\n        unfold v_R in *; simpl in *.\n        eapply semax_pre, Ha.\n        go_lowerx; entailer!.\n        apply andp_right; auto.\n        eapply derives_trans, precise_weak_precise; auto. }\n      Intros t'.\n      forward.\n      Exists i (upd_Znth i h' (fst (Znth i h' ([], [])) ++ [(t, CAS (Vint i0) (vint 0) (vint key))],\n        snd (Znth i h' ([], [])) ++ [(t', Store (vint value))])).\n      apply andp_right; auto.\n      apply andp_right.\n      { apply prop_right; split; auto.\n        split; [omega|].\n        rewrite Heq, Hhi; simpl.\n        split; [rewrite sublist_upd_Znth_l; auto; omega|].\n        split.\n        - rewrite upd_Znth_same by omega.\n          repeat eexists; eauto.\n          + destruct (eq_dec i0 Int.zero); subst; auto.\n            destruct (eq_dec i0 (Int.repr key)); subst; auto.\n            absurd (Int.zero = Int.zero); auto.\n          + match goal with H : forall v0, last_value hki v0 -> v0 <> vint 0 -> Vint i0 = v0 |- _ =>\n              symmetry; apply H; auto end.\n            rewrite ordered_last_value; auto.\n        - rewrite upd_Znth_Zlength by omega.\n          rewrite sublist_upd_Znth_r; auto; omega. }\n      apply andp_right; auto.\n      fast_cancel.\n      rewrite (sepcon_comm (ghost_hist _ _)).\n      rewrite (sepcon_comm (ghost_hist _ _)).\n      rewrite !sepcon_assoc, <- 4sepcon_assoc; apply sepcon_derives.\n      * rewrite replace_nth_sepcon; apply sepcon_list_derives.\n        { rewrite upd_Znth_Zlength; rewrite !Zlength_map; auto. }\n        rewrite upd_Znth_Zlength; rewrite !Zlength_map; auto; intros.\n        destruct (eq_dec i1 i).\n        subst; rewrite upd_Znth_same by (rewrite Zlength_map; auto).\n        rewrite Znth_map with (d' := Vundef) by auto.\n        unfold atomic_entry.\n        Exists lkey lval; entailer!.\n        { rewrite upd_Znth_diff; rewrite ?Zlength_map; auto. }\n      * rewrite sepcon_comm, replace_nth_sepcon.\n        assert (0 <= i < Zlength h') by omega.\n        apply sepcon_list_derives.\n        { rewrite upd_Znth_Zlength; rewrite !Zlength_map; auto. }\n        rewrite upd_Znth_Zlength; rewrite !Zlength_map; auto; intros.\n        destruct (eq_dec i1 i).\n        subst; rewrite upd_Znth_same by (rewrite Zlength_map; auto).\n        erewrite Znth_map, Znth_upto; simpl; auto; try omega.\n        rewrite upd_Znth_same, Hhi; auto; simpl.\n        { rewrite upd_Znth_diff; auto.\n          rewrite Zlength_upto in *.\n          erewrite !Znth_map, !Znth_upto; auto; try omega.\n          rewrite upd_Znth_diff; auto.\n          match goal with H : Zlength h' = _ |- _ => setoid_rewrite H; simpl in *; omega end. }\n    + forward.\n      destruct (eq_dec i0 Int.zero); [discriminate|].\n      destruct (eq_dec i0 (Int.repr key)); [discriminate|].\n      entailer!.\n    + intros.\n      unfold exit_tycon, overridePost.\n      destruct (eq_dec ek EK_normal); [subst | apply drop_tc_environ].\n      Intros; unfold POSTCONDITION, abbreviate, normal_ret_assert, loop1_ret_assert.\n      instantiate (1 := EX i : Z, EX h' : list (hist * hist),\n        PROP (0 <= i < 20; Forall2 (failed_CAS key) (sublist 0 (i + 1) h) (sublist 0 (i + 1) h');\n              sublist (i + 1) (Zlength h) h = sublist (i + 1) (Zlength h') h')\n        LOCAL (temp _idx (vint i); temp _key (vint key); temp _value (vint value); gvar _m_entries p)\n        SEP (data_at sh (tarray (tptr tentry) 20) entries p; fold_right_sepcon (map (atomic_entry sh) entries);\n             entry_hists entries h')).\n      Exists i (upd_Znth i h' (fst (Znth i h' ([], [])) ++ [(t, CAS (Vint i0) (vint 0) (vint key))],\n        snd (Znth i h' ([], [])))).\n      go_lower.\n      apply andp_right.\n      { assert (0 <= i < Zlength h') by (rewrite Hlen; omega).\n        apply prop_right; repeat (split; auto).\n        * erewrite sublist_split, sublist_len_1 with (i1 := i); try omega.\n          erewrite sublist_split with (hi := i + 1), sublist_len_1 with (i1 := i)(d := ([] : hist, [] : hist));\n            rewrite ?upd_Znth_Zlength; try omega.\n          rewrite sublist_upd_Znth_l by omega.\n          rewrite upd_Znth_same by omega.\n          apply Forall2_app; auto.\n          constructor; auto.\n          unfold failed_CAS; simpl.\n          rewrite Heq, Hhi; repeat eexists; eauto.\n          match goal with H : forall v0, last_value hki v0 -> v0 <> vint 0 -> Vint i0 = v0 |- _ =>\n            symmetry; apply H; auto end.\n          rewrite ordered_last_value; auto.\n        * rewrite upd_Znth_Zlength by omega.\n          rewrite sublist_upd_Znth_r by omega; auto. }\n      apply andp_right; [apply prop_right; auto|].\n      fast_cancel.\n      rewrite (sepcon_comm (ghost_hist _ _)).\n      rewrite !sepcon_assoc, <- 4sepcon_assoc; apply sepcon_derives.\n      * rewrite replace_nth_sepcon; apply sepcon_list_derives.\n        { rewrite upd_Znth_Zlength; rewrite !Zlength_map; auto. }\n        rewrite upd_Znth_Zlength; rewrite !Zlength_map; auto; intros.\n        destruct (eq_dec i1 i).\n        subst; rewrite upd_Znth_same by (rewrite Zlength_map; auto).\n        rewrite Znth_map with (d' := Vundef) by auto.\n        unfold atomic_entry.\n        Exists lkey lval; entailer!.\n        { rewrite upd_Znth_diff; rewrite ?Zlength_map; auto. }\n      * rewrite (sepcon_comm _ (ghost_hist _ _)), <- sepcon_assoc, replace_nth_sepcon.\n        assert (0 <= i < Zlength h') by omega.\n        apply sepcon_list_derives.\n        { rewrite upd_Znth_Zlength; rewrite !Zlength_map; auto. }\n        rewrite upd_Znth_Zlength; rewrite !Zlength_map; auto; intros.\n        destruct (eq_dec i1 i).\n        subst; rewrite upd_Znth_same by (rewrite Zlength_map; auto).\n        erewrite Znth_map, Znth_upto; simpl; auto; try omega.\n        rewrite upd_Znth_same; auto; simpl.\n        setoid_rewrite Hhi.\n        rewrite sepcon_comm; auto.\n        { rewrite upd_Znth_diff; auto.\n          rewrite Zlength_upto in *.\n          erewrite !Znth_map, !Znth_upto; auto; try omega.\n          rewrite upd_Znth_diff; auto.\n          setoid_rewrite Hlen; simpl in *; omega. }\n  - Intros i h'.\n    forward.\n    unfold loop2_ret_assert.\n    Exists (i + 1) h'; entailer!.\n    admit. (* list is long enough *)\nAdmitted.\n\nLemma failed_load_fst : forall v h h', Forall2 (failed_load v) h h' -> map snd h' = map snd h.\nProof.\n  induction 1; auto.\n  destruct H as (? & ? & ? & ? & ? & ? & ? & ?); simpl; f_equal; auto.\nQed.\n\nLemma body_get_item : semax_body Vprog Gprog f_get_item get_item_spec.\nProof.\n  start_function.\n  forward.\n  eapply semax_pre with (P' := EX i : Z, EX h' : list (hist * hist),\n    PROP (0 <= i < 20; Forall2 (failed_load key) (sublist 0 i h) (sublist 0 i h');\n          sublist i (Zlength h) h = sublist i (Zlength h') h')\n    LOCAL (temp _idx (vint i); temp _key (vint key); gvar _m_entries p)\n    SEP (data_at sh (tarray (tptr tentry) 20) entries p; fold_right_sepcon (map (atomic_entry sh) entries);\n         entry_hists entries h')).\n  { Exists 0 h; rewrite sublist_nil; entailer!. }\n  eapply semax_loop.\n  - Intros i h'; forward.\n    assert_PROP (Zlength entries = 20) by entailer!.\n    assert (0 <= i < Zlength entries) by (replace (Zlength entries) with 20; auto).\n    forward.\n    { entailer!.\n      apply isptr_is_pointer_or_null, Forall_Znth; auto. }\n    rewrite extract_nth_sepcon with (i := i), Znth_map with (d' := Vundef); try rewrite Zlength_map; auto.\n    unfold entry_hists; erewrite extract_nth_sepcon with (i := i)(l := map _ _), Znth_map, Znth_upto; simpl; auto;\n      try omega.\n    unfold atomic_entry; Intros lkey lval.\n    rewrite atomic_loc_isptr.\n    forward.\n    forward.\n    assert (Zlength h' = Zlength h) as Hlen.\n    { assert (Zlength (sublist i (Zlength h) h) = Zlength (sublist i (Zlength h') h')) as Heq\n        by (replace (sublist i (Zlength h) h) with (sublist i (Zlength h') h'); auto).\n      rewrite !Zlength_sublist in Heq; try omega.\n      destruct (Z_le_dec i (Zlength h')); [omega|].\n      unfold sublist in Heq.\n      rewrite Z2Nat_neg in Heq by omega.\n      simpl in Heq; rewrite Zlength_nil in Heq; omega. }\n    assert (i < Zlength h') by omega.\n    assert (map snd h' = map snd h) as Hsnd.\n    { erewrite <- sublist_same with (al := h') by eauto.\n      erewrite <- sublist_same with (al := h) by eauto.\n      rewrite sublist_split with (al := h')(mid := i) by omega.\n      rewrite sublist_split with (al := h)(mid := i) by omega.\n      rewrite Hlen in *; rewrite !map_app; f_equal; [|congruence].\n      eapply failed_load_fst; eauto. }\n    destruct (Znth i h' ([], [])) as (hki, hvi) eqn: Hhi.\n    forward_call (Tsh, sh, field_address tentry [StructField _key] (Znth i entries Vundef), lkey, vint 0,\n      hki, fun h => !!(h = hki) && emp, k_R,\n      fun (h : hist) (v : val) => !!(forall v0, last_value hki v0 -> v0 <> vint 0 -> v = v0) && emp).\n    { entailer!.\n      rewrite field_address_offset; simpl.\n      rewrite isptr_offset_val_zero; auto.\n      { rewrite field_compatible_cons; simpl.\n        split; [unfold in_members; simpl|]; auto. } }\n    { repeat (split; auto).\n      intros ???????????? Ha.\n      unfold k_R in *; simpl in *.\n      eapply semax_pre, Ha.\n      go_lowerx; entailer!.\n      repeat split.\n      + rewrite Forall_app; repeat constructor; auto.\n        apply apply_int_ops in Hvx; auto.\n      + intros ? Hin; rewrite in_app in Hin.\n        destruct Hin as [? | [? | ?]]; subst; auto; contradiction.\n      + intros ? [(? & ?) | (? & ? & Hin & ? & ?)] Hn; [contradiction Hn; auto|].\n        specialize (Hhist _ _ Hin); apply nth_error_In in Hhist; subst; auto.\n      + apply andp_right; auto.\n        eapply derives_trans, precise_weak_precise, precise_andp2; auto. }\n    Intros x; destruct x as (t, v); simpl in *.\n    destruct v; try contradiction.\n    assert (Zlength h' = Zlength h).\n    { assert (Zlength (sublist i (Zlength h) h) = Zlength (sublist i (Zlength h') h')) as Heq\n        by (replace (sublist i (Zlength h) h) with (sublist i (Zlength h') h'); auto).\n      rewrite !Zlength_sublist in Heq; omega. }\n    assert (Znth i h ([], []) = Znth i h' ([], []) /\\\n      sublist (i + 1) (Zlength h) h = sublist (i + 1) (Zlength h') h') as (Heq & Hi1).\n    { match goal with H : sublist _ _ h = sublist _ _ h' |- _ =>\n        erewrite sublist_next with (d := ([] : hist, [] : hist)),\n                 sublist_next with (l0 := h')(d := ([] : hist, [] : hist)) in H by omega; inv H; auto end. }\n    assert (ordered_hist hki).\n    { match goal with H : wf_hists h l |- _ => destruct H as (Hwf & _) end.\n      eapply Forall_Znth with (i1 := i) in Hwf; [|omega].\n      rewrite Heq, Hhi in Hwf; tauto. }\n    match goal with |- semax _ (PROP () (LOCALx ?Q (SEPx ?R))) _ _ =>\n      forward_if (PROP (i0 <> Int.repr key) (LOCALx Q (SEPx R))) end.\n    + rewrite (atomic_loc_isptr _ lval).\n      forward.\n      forward.\n      forward_call (Tsh, sh, field_address tentry [StructField _value] (Znth i entries Vundef), lval, vint 0,\n        snd (Znth i h' ([], [])), fun (h : hist) => emp, v_R, fun (h : hist) (v : val) => emp).\n      { entailer!.\n        rewrite field_address_offset; auto.\n        { rewrite field_compatible_cons; simpl.\n          split; [unfold in_members; simpl|]; auto. } }\n      { rewrite Hhi; fast_cancel. }\n      { repeat (split; auto).\n        intros ???????????? Ha.\n        unfold v_R in *; simpl in *.\n        eapply semax_pre, Ha.\n        go_lowerx; entailer!.\n        apply andp_right; auto.\n        eapply derives_trans, precise_weak_precise; auto. }\n      Intros x; destruct x as (t', v); simpl in *.\n      forward.\n      Exists (Int.signed v) i (upd_Znth i h' (fst (Znth i h' ([], [])) ++ [(t, Load (vint key))],\n        snd (Znth i h' ([], [])) ++ [(t', Load (Vint v))])).\n      apply andp_right.\n      { apply prop_right.\n        split; [apply Int.signed_range|].\n        split; auto.\n        split; [omega|].\n        split; [|split].\n        - rewrite sublist_upd_Znth_l; auto; omega.\n        - rewrite upd_Znth_same by omega.\n          rewrite Heq, Hhi in *; simpl in *.\n          rewrite Int.repr_signed.\n          do 3 eexists; eauto.\n          split; eauto.\n          split; eauto.\n          match goal with H : forall v0, last_value hki v0 -> v0 <> vint 0 -> vint key = v0 |- _ =>\n            symmetry; apply H; auto end.\n          rewrite ordered_last_value; auto.\n        - rewrite upd_Znth_Zlength by omega.\n          rewrite sublist_upd_Znth_r by omega; auto. }\n      apply andp_right; [apply prop_right; rewrite Int.repr_signed; auto|].\n      fast_cancel.\n      rewrite (sepcon_comm (ghost_hist _ _)).\n      rewrite (sepcon_comm (ghost_hist _ _)).\n      rewrite !sepcon_assoc, <- 4sepcon_assoc; apply sepcon_derives.\n      * rewrite replace_nth_sepcon; apply sepcon_list_derives.\n        { rewrite upd_Znth_Zlength; rewrite !Zlength_map; auto. }\n        rewrite upd_Znth_Zlength; rewrite !Zlength_map; auto; intros.\n        destruct (eq_dec i0 i).\n        subst; rewrite upd_Znth_same by (rewrite Zlength_map; auto).\n        rewrite Znth_map with (d' := Vundef) by auto.\n        unfold atomic_entry.\n        Exists lkey lval; entailer!.\n        { rewrite upd_Znth_diff; rewrite ?Zlength_map; auto. }\n      * rewrite sepcon_comm, replace_nth_sepcon.\n        assert (0 <= i < Zlength h') by omega.\n        rewrite Hhi; apply sepcon_list_derives.\n        { rewrite upd_Znth_Zlength; rewrite !Zlength_map; auto. }\n        rewrite upd_Znth_Zlength; rewrite !Zlength_map; auto; intros.\n        destruct (eq_dec i0 i).\n        subst; rewrite upd_Znth_same by (rewrite Zlength_map; auto).\n        erewrite Znth_map, Znth_upto; simpl; auto; try omega.\n        rewrite upd_Znth_same; auto; simpl.\n        { rewrite upd_Znth_diff; auto.\n          rewrite Zlength_upto in *.\n          erewrite !Znth_map, !Znth_upto; auto; try omega.\n          rewrite upd_Znth_diff; auto.\n          simpl in *; omega. }\n    + forward.\n      entailer!.\n    + Intros; match goal with |- semax _ (PROP () (LOCALx ?Q (SEPx ?R))) _ _ =>\n        forward_if (PROP (i0 <> Int.zero) (LOCALx Q (SEPx R))) end.\n      * forward.\n        Exists 0 i (upd_Znth i h' (fst (Znth i h' ([], [])) ++ [(t, Load (vint 0))], snd (Znth i h' ([], [])))).\n        apply andp_right.\n        { apply prop_right.\n          split; [split; computable|].\n          split; auto.\n          split; [omega|].\n          split; [|split].\n          * rewrite sublist_upd_Znth_l; auto; omega.\n          * rewrite upd_Znth_same by omega.\n            rewrite Heq, Hhi in *; simpl in *.\n            do 3 eexists; eauto.\n            split; eauto.\n            split; eauto.\n            match goal with H : forall v0, last_value hki v0 -> v0 <> vint 0 -> vint 0 = v0 |- _ =>\n              symmetry; apply H; auto end.\n            rewrite ordered_last_value; auto.\n          * rewrite upd_Znth_Zlength by omega.\n            rewrite sublist_upd_Znth_r; auto; omega. }\n        apply andp_right; [apply prop_right; auto|].\n        fast_cancel.\n        rewrite (sepcon_comm (ghost_hist _ _)).\n        rewrite (sepcon_comm (ghost_hist _ _)).\n        rewrite !sepcon_assoc, <- 4sepcon_assoc; apply sepcon_derives.\n        -- rewrite replace_nth_sepcon; apply sepcon_list_derives.\n           { rewrite upd_Znth_Zlength; rewrite !Zlength_map; auto. }\n           rewrite upd_Znth_Zlength; rewrite !Zlength_map; auto; intros.\n           destruct (eq_dec i0 i).\n           subst; rewrite upd_Znth_same by (rewrite Zlength_map; auto).\n           rewrite Znth_map with (d' := Vundef) by auto.\n           unfold atomic_entry.\n           Exists lkey lval; entailer!.\n           { rewrite upd_Znth_diff; rewrite ?Zlength_map; auto. }\n        -- rewrite sepcon_comm, replace_nth_sepcon.\n           assert (0 <= i < Zlength h') by omega.\n           rewrite Hhi; apply sepcon_list_derives.\n           { rewrite upd_Znth_Zlength; rewrite !Zlength_map; auto. }\n           rewrite upd_Znth_Zlength; rewrite !Zlength_map; auto; intros.\n           destruct (eq_dec i0 i).\n           subst; rewrite upd_Znth_same by (rewrite Zlength_map; auto).\n           erewrite Znth_map, Znth_upto; simpl; auto; try omega.\n           rewrite upd_Znth_same; auto; simpl.\n           rewrite sepcon_comm; auto.\n           { rewrite upd_Znth_diff; auto.\n             rewrite Zlength_upto in *.\n             erewrite !Znth_map, !Znth_upto; auto; try omega.\n             rewrite upd_Znth_diff; auto.\n             simpl in *; omega. }\n      * forward.\n        entailer!.\n      * intros.\n        unfold exit_tycon, overridePost.\n        destruct (eq_dec ek EK_normal); [subst | apply drop_tc_environ].\n        Intros; unfold POSTCONDITION, abbreviate, normal_ret_assert, loop1_ret_assert.\n        instantiate (1 := EX i : Z, EX h' : list (hist * hist),\n          PROP (0 <= i < 20; Forall2 (failed_load key) (sublist 0 (i + 1) h) (sublist 0 (i + 1) h');\n                sublist (i + 1) (Zlength h) h = sublist (i + 1) (Zlength h') h')\n          LOCAL (temp _idx (vint i); temp _key (vint key); gvar _m_entries p)\n          SEP (data_at sh (tarray (tptr tentry) 20) entries p; fold_right_sepcon (map (atomic_entry sh) entries);\n               entry_hists entries h')).\n        Exists i (upd_Znth i h' (fst (Znth i h' ([], [])) ++ [(t, Load (Vint i0))], snd (Znth i h' ([], [])))).\n        go_lower.\n        apply andp_right.\n        { apply prop_right; repeat (split; auto).\n          * erewrite sublist_split, sublist_len_1 with (i1 := i); try omega.\n            erewrite sublist_split with (hi := i + 1), sublist_len_1 with (i1 := i)(d := ([] : hist, [] : hist));\n              rewrite ?upd_Znth_Zlength; try omega.\n            rewrite sublist_upd_Znth_l by omega.\n            rewrite upd_Znth_same by omega.\n            apply Forall2_app; auto.\n            constructor; auto.\n            unfold failed_load; simpl.\n            rewrite Heq, Hhi; repeat eexists; eauto.\n            match goal with H : forall v0, last_value hki v0 -> v0 <> vint 0 -> Vint i0 = v0 |- _ =>\n              symmetry; apply H; auto end.\n            rewrite ordered_last_value; auto.\n          * rewrite upd_Znth_Zlength by omega.\n            rewrite sublist_upd_Znth_r by omega; auto. }\n        apply andp_right; [apply prop_right; auto|].\n        fast_cancel.\n        rewrite (sepcon_comm (ghost_hist _ _)).\n        rewrite !sepcon_assoc, <- 4sepcon_assoc; apply sepcon_derives.\n        -- rewrite replace_nth_sepcon; apply sepcon_list_derives.\n           { rewrite upd_Znth_Zlength; rewrite !Zlength_map; auto. }\n          rewrite upd_Znth_Zlength; rewrite !Zlength_map; auto; intros.\n          destruct (eq_dec i1 i).\n          subst; rewrite upd_Znth_same by (rewrite Zlength_map; auto).\n           rewrite Znth_map with (d' := Vundef) by auto.\n          unfold atomic_entry.\n          Exists lkey lval; entailer!.\n          { rewrite upd_Znth_diff; rewrite ?Zlength_map; auto. }\n        -- rewrite (sepcon_comm _ (ghost_hist _ _)), <- sepcon_assoc, replace_nth_sepcon.\n           assert (0 <= i < Zlength h') by omega.\n           rewrite Hhi; apply sepcon_list_derives.\n           { rewrite upd_Znth_Zlength; rewrite !Zlength_map; auto. }\n           rewrite upd_Znth_Zlength; rewrite !Zlength_map; auto; intros.\n           destruct (eq_dec i1 i).\n           subst; rewrite upd_Znth_same by (rewrite Zlength_map; auto).\n           erewrite Znth_map, Znth_upto; simpl; auto; try omega.\n           rewrite upd_Znth_same; auto; simpl.\n           rewrite sepcon_comm; auto.\n           { rewrite upd_Znth_diff; auto.\n             rewrite Zlength_upto in *.\n             erewrite !Znth_map, !Znth_upto; auto; try omega.\n             rewrite upd_Znth_diff; auto.\n             match goal with H : Zlength h' = _ |- _ => setoid_rewrite H; simpl in *; omega end. }\n  - Intros i h'.\n    forward.\n    unfold loop2_ret_assert.\n    Exists (i + 1) h'; entailer!.\n    admit. (* list is long enough *)\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/seplog/VST/mailbox/verif_lockfree_linsearch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.2514923173202992}}
{"text": "(* Distributed under the terms of the MIT license. *)\nRequire Import ssreflect Morphisms.\nFrom MetaCoq.Utils Require Import utils.\nFrom MetaCoq.PCUIC Require Import PCUICAst PCUICAstUtils PCUICInduction.\nImport Nat.\n\n(** * Commutation lemmas for the lifting and substitution operations.\n  Definition of [closedn] (boolean) predicate for checking if\n  a term is closed. *)\n\nDerive Signature for Peano.le.\n\n(** Assumptions contexts do not contain let-ins. *)\n\nInductive assumption_context : context -> Prop :=\n| assumption_context_nil : assumption_context []\n| assumption_context_vass na t Γ : assumption_context Γ -> assumption_context (vass na t :: Γ).\n\nDerive Signature for assumption_context.\n\nCreate HintDb terms.\n\nLtac arith_congr := repeat (try lia; progress f_equal).\n\nLtac easy0 :=\n  let rec use_hyp H :=\n   (match type of H with\n    | _ /\\ _ => exact H || destruct_hyp H\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)\n  in\n  let rec use_hyps :=\n   (match goal with\n    | H:_ /\\ _ |- _ => exact H || (destruct_hyp H; use_hyps)\n    | H:_ * _ |- _ => exact H || (destruct_hyp H; use_hyps)\n    | H:_ |- _ => solve [ inversion H ]\n    | _ => idtac\n    end)\n  in\n  let do_atom := (solve [ trivial with eq_true | reflexivity | symmetry; trivial | contradiction | congruence]) in\n  let rec do_ccl := (try do_atom; repeat (do_intro; try do_atom); try arith_congr; (solve [ split; do_ccl ])) in\n  (solve [ do_atom | use_hyps; do_ccl ]) || fail \"Cannot solve this goal\".\n\n\n#[global]\nHint Extern 10 (_ < _)%nat => lia : terms.\n#[global]\nHint Extern 10 (_ <= _)%nat => lia : terms.\n#[global]\nHint Extern 10 (@eq nat _ _) => lia : terms.\n\nLtac easy ::= easy0 || solve [intuition eauto 3 with core terms].\n\nNotation subst_rec N M k := (subst N k M) (only parsing).\n\nLemma lift_rel_ge :\n  forall k n p, p <= n -> lift k p (tRel n) = tRel (k + n).\nProof.\n  intros; simpl in |- *.\n  now elim (leb_spec p n).\nQed.\n\nLemma lift_rel_lt : forall k n p, p > n -> lift k p (tRel n) = tRel n.\nProof.\n  intros; simpl in |- *.\n  now elim (leb_spec p n).\nQed.\n\nLemma subst_rel_lt : forall u n k, k > n -> subst u k (tRel n) = tRel n.\nProof.\n  simpl in |- *; intros.\n  elim (leb_spec k n); intro Hcomp; easy.\nQed.\n\nLemma subst_rel_gt :\n  forall u n k, n >= k + length u -> subst u k (tRel n) = tRel (n - length u).\nProof.\n  simpl in |- *; intros.\n  elim (leb_spec k n). intros. destruct nth_error eqn:Heq.\n  assert (n - k < length u) by (apply nth_error_Some; congruence). lia. reflexivity.\n  lia.\nQed.\n\nLemma subst_rel_eq :\n  forall (u : list term) n i t p,\n    List.nth_error u i = Some t -> p = n + i ->\n    subst u n (tRel p) = lift0 n t.\nProof.\n  intros; simpl in |- *. subst p.\n  elim (leb_spec n (n + i)). intros. assert (n + i - n = i) by lia. rewrite H1 H.\n  reflexivity. intros. lia.\nQed.\n\nLtac nth_leb_simpl :=\n  match goal with\n    |- context [leb ?k ?n] => elim (leb_spec_Set k n); try lia; simpl\n  | |- context [nth_error ?l ?n] => elim (nth_error_spec l n); rewrite -> ?app_length, ?map_length;\n                                    try lia; intros; simpl\n  | H : context[nth_error (?l ++ ?l') ?n] |- _ =>\n    (rewrite -> (nth_error_app_ge l l' n) in H by lia) ||\n    (rewrite -> (nth_error_app_lt l l' n) in H by lia)\n  | H : nth_error ?l ?n = Some _, H' : nth_error ?l ?n' = Some _ |- _ =>\n    replace n' with n in H' by lia; rewrite -> H in H'; injection H'; intros; subst\n  | _ => lia || congruence || solve [repeat (f_equal; try lia)]\n  end.\n\nLemma lift0_id : forall M k, lift 0 k M = M.\nProof.\n  intros M.\n  elim M using term_forall_list_ind; simpl in |- *; intros; try easy ;\n    try (try rewrite H; try rewrite H0 ; try rewrite H1 ; easy);\n    try (f_equal; auto; solve_all).\n\n  now elim (leb k n).\nQed.\n\nLemma map_lift0 l : map (lift0 0) l = l.\nProof. induction l; simpl; auto. now rewrite lift0_id. Qed.\n\nLemma lift0_p : forall M, lift0 0 M = M.\nProof. intro; apply lift0_id. Qed.\n\nLemma simpl_lift :\n  forall M n k p i,\n    i <= k + n ->\n    k <= i -> lift p i (lift n k M) = lift (p + n) k M.\nProof.\n  intros M.\n  elim M using term_forall_list_ind;\n    intros; simpl; autorewrite with map;\n      try (rewrite -> H, ?H0, ?H1; auto); try (f_equal; auto; solve_all).\n\n  elim (leb_spec k n); intros.\n  + elim (leb_spec i (n0 + n)); intros; lia.\n  + elim (leb_spec i n); intros; lia.\nQed.\n\nLemma simpl_lift0 : forall M n, lift0 (S n) M = lift0 1 (lift0 n M).\nProof. intros; now rewrite simpl_lift. Qed.\n\nLemma simpl_lift_ext n k p i :\n  i <= k + n -> k <= i ->\n  lift p i ∘ lift n k =1 lift (p + n) k.\nProof. intros ? ? ?; now apply simpl_lift. Qed.\n\n#[global]\nHint Rewrite Nat.add_assoc : map.\n\nLemma permute_lift :\n  forall M n k p i,\n    i <= k ->\n    lift p i (lift n k M) = lift n (k + p) (lift p i M).\nProof.\n  intros M.\n  elim M using term_forall_list_ind;\n    intros; simpl;\n      f_equal; try solve [solve_all]; repeat nth_leb_simpl.\nQed.\n\nLemma permute_lift0 :\n  forall M k, lift0 1 (lift 1 k M) = lift 1 (S k) (lift0 1 M).\nProof.\n  intros.\n  change (lift 1 0 (lift 1 k M) = lift 1 (1 + k) (lift 1 0 M)).\n  now rewrite permute_lift.\nQed.\n\nLemma lift_isApp n k t : ~ isApp t = true -> ~ isApp (lift n k t) = true.\nProof. induction t; auto. Qed.\n\nLemma isLambda_lift n k (bod : term) :\n  isLambda bod = true -> isLambda (lift n k bod) = true.\nProof. now destruct bod. Qed.\n\n#[global]\nHint Resolve lift_isApp map_nil isLambda_lift : all.\n\nLemma simpl_subst_rec :\n  forall M N n p k,\n    p <= n + k ->\n    k <= p -> subst N p (lift (List.length N + n) k M) = lift n k M.\nProof.\n  intros M. induction M using term_forall_list_ind;\n    intros; simpl; autorewrite with map;\n      try solve [f_equal; auto; solve_all]; repeat nth_leb_simpl.\nQed.\n\nLemma simpl_subst :\n  forall N M n p, p <= n -> subst N p (lift0 (length N + n) M) = lift0 n M.\nProof.\n  intros. rewrite simpl_subst_rec; auto.\n  now rewrite Nat.add_0_r. lia.\nQed.\n\nLemma lift_mkApps n k t l :\n  lift n k (mkApps t l) = mkApps (lift n k t) (map (lift n k) l).\nProof.\n  revert n k t; induction l; intros n k t. auto.\n  simpl. rewrite (IHl n k (tApp t a)). reflexivity.\nQed.\n\nLemma commut_lift_subst_rec M N n p k :\n  k <= p -> lift n k (subst N p M) = subst N (p + n) (lift n k M).\nProof.\n  revert N n p k; elim M using term_forall_list_ind; intros; cbnr;\n    f_equal; auto; solve_all; rewrite ?Nat.add_succ_r -?Nat.add_assoc; eauto with all.\n\n  - repeat nth_leb_simpl.\n    rewrite -> simpl_lift by easy. f_equal; lia.\nQed.\n\nLemma commut_lift_subst M N k :\n  subst N (S k) (lift0 1 M) = lift0 1 (subst N k M).\nProof.\n  now intros; rewrite commut_lift_subst_rec.\nQed.\n\nLemma distr_lift_subst_rec M N n p k :\n    lift n (p + k) (subst N p M) =\n    subst (List.map (lift n k) N) p (lift n (p + length N + k) M).\nProof.\n  revert N n p k; elim M using term_forall_list_ind; intros; cbnr;\n    f_equal; auto; solve_all.\n\n  - repeat nth_leb_simpl.\n    rewrite nth_error_map in e0. rewrite e in e0.\n    invs e0. now rewrite (permute_lift x n0 k p 0).\nQed.\n\nLemma distr_lift_subst M N n k :\n  lift n k (subst0 N M) = subst0 (map (lift n k) N) (lift n (length N + k) M).\nProof.\n  pattern k at 1 3 in |- *.\n  replace k with (0 + k); try easy.\n  apply distr_lift_subst_rec.\nQed.\n\nLemma distr_lift_subst10 M N n k :\n  lift n k (subst10 N M) = subst10 (lift n k N) (lift n (S k) M).\nProof.\n  intros; unfold subst in |- *.\n  pattern k at 1 3 in |- *.\n  replace k with (0 + k); try easy.\n  apply distr_lift_subst_rec.\nQed.\n\nLemma subst_mkApps u k t l :\n  subst u k (mkApps t l) = mkApps (subst u k t) (map (subst u k) l).\nProof.\n  revert u k t; induction l; intros u k t; auto.\n  intros. simpl mkApps at 1. simpl subst at 1 2.\n  now rewrite IHl.\nQed.\n\nLemma subst1_mkApps u k t l :\n  subst1 u k (mkApps t l) = mkApps (subst1 u k t) (map (subst1 u k) l).\nProof.\n  apply subst_mkApps.\nQed.\n\nLemma distr_subst_rec M N (P : list term) n p :\n  subst P (p + n) (subst N p M)\n  = subst (map (subst P n) N) p (subst P (p + length N + n) M).\nProof.\n  revert N P n p; elim M using term_forall_list_ind; intros;\n    match goal with\n    | |- context [tRel _] => idtac\n    | |- _ => simpl\n    end; try reflexivity;\n      rewrite -> ?map_map_compose, ?compose_on_snd, ?compose_map_def,\n      ?map_length, ?Nat.add_assoc, ?map_predicate_map_predicate;\n      try solve [f_equal; auto; solve_all].\n\n  - unfold subst at 2.\n    elim (leb_spec p n); intros.\n    + destruct (nth_error_spec N (n - p)).\n      ++ rewrite -> subst_rel_lt by lia.\n         erewrite subst_rel_eq; try easy.\n         2:rewrite -> nth_error_map, e; reflexivity.\n         now rewrite commut_lift_subst_rec. lia.\n      ++ unfold subst at 4.\n         elim (leb_spec (p + length N + n0) n); intros; subst; try easy.\n         destruct (nth_error_spec P (n - (p + length N + n0))).\n         +++ erewrite subst_rel_eq. 2:eauto. 2:lia.\n             assert (p + length N + n0 = length (map (subst P n0) N) + (p + n0))\n               by (rewrite map_length; lia).\n             rewrite H1. rewrite simpl_subst_rec; eauto; try lia.\n         +++ rewrite !subst_rel_gt; rewrite ?map_length; try lia. f_equal; lia.\n         +++ rewrite subst_rel_lt; try easy.\n             rewrite -> subst_rel_gt; rewrite map_length. trivial. lia.\n    + rewrite !subst_rel_lt; try easy.\nQed.\n\nLemma distr_subst P N M k :\n  subst P k (subst0 N M) = subst0 (map (subst P k) N) (subst P (length N + k) M).\nProof.\n  intros.\n  pattern k at 1 3 in |- *.\n  change k with (0 + k). hnf.\n  apply distr_subst_rec.\nQed.\n\nLemma lift_closed n k t : closedn k t -> lift n k t = t.\nProof.\n  revert k.\n  elim t using term_forall_list_ind; intros; try easy;\n    rewrite -> ?map_map_compose, ?compose_on_snd, ?compose_map_def, ?map_length,\n      ?map_predicate_map_predicate, ?map_branch_map_branch;\n    simpl closed in *;\n    unfold test_predicate_k, test_def, test_branch_k in *;\n    try solve [simpl lift; simpl closed; f_equal; auto; rtoProp; solve_all]; try easy.\n  - rewrite lift_rel_lt; auto.\n    revert H. elim (Nat.ltb_spec n0 k); intros; try easy.\nQed.\n\nLemma closed_upwards {k t} k' : closedn k t -> k' >= k -> closedn k' t.\nProof.\n  revert k k'.\n  elim t using term_forall_list_ind; intros; try lia;\n    autorewrite with map;\n    simpl closed in *; unfold test_snd, test_def, test_predicate_k, test_branch_k in *;\n      try solve [(try f_equal; simpl; repeat (rtoProp; solve_all); eauto)].\n\n  - elim (ltb_spec n k'); auto. intros.\n    apply ltb_lt in H. lia.\nQed.\n\nLemma subst_empty k a : subst [] k a = a.\nProof.\n  induction a in k |- * using term_forall_list_ind; simpl; try congruence;\n    try solve [f_equal; eauto; solve_all].\n\n  - elim (Nat.compare_spec k n); destruct (Nat.leb_spec k n); intros; try easy.\n    subst. rewrite Nat.sub_diag. simpl. rewrite Nat.sub_0_r. reflexivity.\n    assert (n - k > 0) by lia.\n    assert (exists n', n - k = S n'). exists (pred (n - k)). lia.\n    destruct H2. rewrite H2. simpl. now rewrite Nat.sub_0_r.\nQed.\n\nLemma subst_empty_eq k : subst [] k =1 id.\nProof. intros x; now rewrite subst_empty. Qed.\n\nLemma lift_to_extended_list_k Γ k : forall k',\n    to_extended_list_k Γ (k' + k) = map (lift0 k') (to_extended_list_k Γ k).\nProof.\n  unfold to_extended_list_k.\n  intros k'. rewrite !reln_alt_eq !app_nil_r.\n  induction Γ in k, k' |- *; simpl; auto.\n  destruct a as [na [body|] ty].\n  now rewrite <- Nat.add_assoc, (IHΓ (k + 1) k').\n  simpl. now rewrite <- Nat.add_assoc, (IHΓ (k + 1) k'), map_app.\nQed.\n\nLemma simpl_subst_k (N : list term) (M : term) :\n  forall k p, p = #|N| -> subst N k (lift p k M) = M.\nProof.\n  intros. subst p. rewrite <- (Nat.add_0_r #|N|).\n  rewrite -> simpl_subst_rec, lift0_id; auto.\nQed.\n\nLemma subst_app_decomp l l' k t :\n  subst (l ++ l') k t = subst l' k (subst (List.map (lift0 (length l')) l) k t).\nProof.\n  induction t in k |- * using term_forall_list_ind; simpl; auto;\n    rewrite ?subst_mkApps; try change_Sk;\n    try (f_equal; rewrite -> ?map_map_compose, ?compose_on_snd, ?compose_map_def,\n                  ?map_length, ?map_predicate_map_predicate; eauto; solve_all).\n\n  - repeat nth_leb_simpl.\n    rewrite nth_error_map in e0. rewrite e in e0.\n    injection e0; intros <-.\n    rewrite -> permute_lift by auto.\n    rewrite <- (Nat.add_0_r #|l'|).\n    rewrite -> simpl_subst_rec, lift0_id; auto with wf; try lia.\nQed.\n\nLemma subst_app_simpl l l' k t :\n  subst (l ++ l') k t = subst l k (subst l' (k + length l) t).\nProof.\n  induction t in k |- * using term_forall_list_ind; simpl; eauto;\n    rewrite ?subst_mkApps; try change_Sk;\n    try (f_equal; rewrite -> ?map_map_compose, ?compose_on_snd, ?compose_map_def,\n                  ?map_length, ?Nat.add_assoc, ?map_predicate_map_predicate; solve_all).\n\n  - repeat nth_leb_simpl.\n    rewrite -> Nat.add_comm, simpl_subst; eauto.\nQed.\n\nLemma subst_app_simpl' (l l' : list term) (k : nat) (t : term) n :\n  n = #|l| ->\n  subst (l ++ l') k t = subst l k (subst l' (k + n) t).\nProof. intros ->; apply subst_app_simpl. Qed.\n\nLemma isLambda_subst (s : list term) k (bod : term) :\n  isLambda bod = true -> isLambda (subst s k bod) = true.\nProof.\n  intros. destruct bod; try discriminate. reflexivity.\nQed.\n\nLemma map_vass_map_def g l n k :\n  mapi (fun i d => vass (dname d) (lift0 i (dtype d)))\n       (map (map_def (lift n k) g) l)\n  = mapi (fun i d => map_decl (lift n (i + k)) d)\n         (mapi (fun i (d : def term) => vass (dname d) (lift0 i (dtype d))) l).\nProof.\n  rewrite mapi_mapi mapi_map. apply mapi_ext.\n  intros. unfold map_decl, vass; simpl; f_equal.\n  rewrite -> permute_lift. f_equal; lia. lia.\nQed.\n\nDefinition fix_context_gen k mfix :=\n  List.rev (mapi_rec (fun (i : nat) (d : def term) => vass (dname d) (lift0 i (dtype d))) mfix k).\n\nLemma lift_decl0 k d : map_decl (lift 0 k) d = d.\nProof.\n  destruct d; destruct decl_body; unfold map_decl; simpl;\n  f_equal; now rewrite ?lift0_id.\nQed.\n\nLemma lift0_context k Γ : lift_context 0 k Γ = Γ.\nProof.\n  unfold lift_context, fold_context_k.\n  rewrite rev_mapi. rewrite List.rev_involutive.\n  unfold mapi. generalize 0 at 2. generalize #|List.rev Γ|.\n  induction Γ; intros; simpl; trivial.\n  rewrite lift_decl0; f_equal; auto.\nQed.\n\nLemma lift_context_length n k Γ : #|lift_context n k Γ| = #|Γ|.\nProof. apply fold_context_k_length. Qed.\n#[global]\nHint Rewrite lift_context_length : lift len.\n\nDefinition lift_context_snoc0 n k Γ d : lift_context n k (d :: Γ) = lift_context n k Γ ,, lift_decl n (#|Γ| + k) d.\nProof. unfold lift_context. now rewrite fold_context_k_snoc0. Qed.\n#[global]\nHint Rewrite lift_context_snoc0 : lift.\n\nLemma lift_context_snoc n k Γ d : lift_context n k (Γ ,, d) = lift_context n k Γ ,, lift_decl n (#|Γ| + k) d.\nProof.\n  unfold snoc. apply lift_context_snoc0.\nQed.\n#[global]\nHint Rewrite lift_context_snoc : lift.\n\nLemma lift_context_alt n k Γ :\n  lift_context n k Γ =\n  mapi (fun k' d => lift_decl n (Nat.pred #|Γ| - k' + k) d) Γ.\nProof.\n  unfold lift_context. apply: fold_context_k_alt.\nQed.\n\nLemma lift_context_app n k Γ Δ :\n  lift_context n k (Γ ,,, Δ) = lift_context n k Γ ,,, lift_context n (#|Γ| + k) Δ.\nProof.\n  unfold lift_context, fold_context_k, app_context.\n  rewrite List.rev_app_distr.\n  rewrite mapi_app. rewrite <- List.rev_app_distr. f_equal. f_equal.\n  apply mapi_ext. intros. f_equal. rewrite List.rev_length. f_equal. lia.\nQed.\n\nLemma lift_it_mkProd_or_LetIn n k ctx t :\n  lift n k (it_mkProd_or_LetIn ctx t) =\n  it_mkProd_or_LetIn (lift_context n k ctx) (lift n (length ctx + k) t).\nProof.\n  induction ctx in n, k, t |- *; simpl; try congruence.\n  pose (lift_context_snoc n k ctx a). unfold snoc in e. rewrite -> e. clear e.\n  simpl. rewrite -> IHctx.\n  pose (lift_context_snoc n k ctx a).\n  now destruct a as [na [b|] ty].\nQed.\n\nLemma lift_it_mkLambda_or_LetIn n k ctx t :\n  lift n k (it_mkLambda_or_LetIn ctx t) =\n  it_mkLambda_or_LetIn (lift_context n k ctx) (lift n (length ctx + k) t).\nProof.\n  induction ctx in n, k, t |- *; simpl; try congruence.\n  pose (lift_context_snoc n k ctx a). unfold snoc in e. rewrite -> e. clear e.\n  simpl. rewrite -> IHctx.\n  pose (lift_context_snoc n k ctx a).\n  now destruct a as [na [b|] ty].\nQed.\n\nLemma map_lift_lift n k l : map (fun x => lift0 n (lift0 k x)) l = map (lift0 (n + k)) l.\nProof. apply map_ext => x.\n  rewrite simpl_lift; try lia. reflexivity.\nQed.\n\nLemma simpl_subst' :\n  forall N M n p k, k = List.length N -> p <= n -> subst N p (lift0 (k + n) M) = lift0 n M.\nProof.\n  intros. subst k. rewrite simpl_subst_rec; auto.\n  + now rewrite Nat.add_0_r.\n  + lia.\nQed.\n\nLemma subst_subst_lift (s s' : list term) n t : n = #|s| + #|s'| ->\n  subst0 s (subst0 s' (lift0 n t)) = t.\nProof.\n  intros ->. rewrite Nat.add_comm simpl_subst' //; try lia.\n  now rewrite -(Nat.add_0_r #|s|) simpl_subst' // lift0_id.\nQed.\n\nLemma map_subst_lift_id s l : map (subst0 s ∘ lift0 #|s|) l = l.\nProof.\n  induction l; simpl; auto.\n  rewrite -{1}(Nat.add_0_r #|s|) simpl_subst'; auto.\n  now rewrite lift0_id IHl.\nQed.\n\nLemma map_subst_lift_id_eq s l k : k = #|s| -> map (subst0 s ∘ lift0 k) l = l.\nProof. intros ->; apply map_subst_lift_id. Qed.\n\nLemma map_subst_lift_ext N n p k l :\n  k = #|N| -> p <= n ->\n  map (subst N p ∘ lift0 (k + n)) l = map (lift0 n) l.\nProof.\n  intros -> pn.\n  apply map_ext => x. now apply simpl_subst'.\nQed.\n\nLemma map_subst_subst_lift_lift (s s' : list term) k k' l : k + k' = #|s| + #|s'| ->\n  map (fun t => subst0 s (subst0 s' (lift k k' (lift0 k' t)))) l = l.\nProof.\n  intros H. eapply All_map_id. eapply All_refl => x.\n  rewrite simpl_lift; try lia. rewrite subst_subst_lift //.\nQed.\n\nLemma nth_error_lift_context:\n  forall (Γ' Γ'' : context) (v : nat),\n    v < #|Γ'| -> forall nth k,\n    nth_error Γ' v = Some nth ->\n    nth_error (lift_context #|Γ''| k Γ') v = Some (lift_decl #|Γ''| (#|Γ'| - S v + k) nth).\nProof.\n  induction Γ'; intros.\n  - easy.\n  - simpl. destruct v; rewrite lift_context_snoc0.\n    + simpl. repeat f_equal; try lia. simpl in *. congruence.\n    + simpl. apply IHΓ'; simpl in *; (lia || congruence).\nQed.\n\nLemma nth_error_lift_context_eq:\n  forall (Γ' Γ'' : context) (v : nat) k,\n    nth_error (lift_context #|Γ''| k Γ') v =\n    option_map (lift_decl #|Γ''| (#|Γ'| - S v + k)) (nth_error Γ' v).\nProof.\n  induction Γ'; intros.\n  - simpl. unfold lift_context, fold_context_k; simpl. now rewrite nth_error_nil.\n  - simpl. destruct v; rewrite lift_context_snoc0.\n    + simpl. repeat f_equal; try lia.\n    + simpl. apply IHΓ'; simpl in *; (lia || congruence).\nQed.\n\n#[global]\nHint Rewrite subst_context_length : subst wf.\n\n#[global]\nHint Rewrite subst_context_snoc : subst.\n\nLemma subst_decl0 k d : map_decl (subst [] k) d = d.\nProof.\n  destruct d; destruct decl_body;\n    unfold subst_decl, map_decl; simpl in *;\n    f_equal; simpl; rewrite subst_empty; intuition trivial.\nQed.\n\nLemma subst0_context k Γ : subst_context [] k Γ = Γ.\nProof.\n  unfold subst_context, fold_context_k.\n  rewrite rev_mapi. rewrite List.rev_involutive.\n  unfold mapi. generalize 0. generalize #|List.rev Γ|.\n  induction Γ; intros; simpl; trivial.\n  erewrite subst_decl0; f_equal; eauto.\nQed.\n\nLemma subst_context_snoc0 s Γ d : subst_context s 0 (Γ ,, d) = subst_context s 0 Γ ,, subst_decl s #|Γ| d.\nProof.\n  unfold snoc. now rewrite subst_context_snoc Nat.add_0_r.\nQed.\n#[global]\nHint Rewrite subst_context_snoc : subst.\n\nLemma subst_context_app s k Γ Δ :\n  subst_context s k (Γ ,,, Δ) = subst_context s k Γ ,,, subst_context s (#|Γ| + k) Δ.\nProof.\n  unfold subst_context, fold_context_k, app_context.\n  rewrite List.rev_app_distr.\n  rewrite mapi_app. rewrite <- List.rev_app_distr. f_equal. f_equal.\n  apply mapi_ext. intros. f_equal. rewrite List.rev_length. f_equal. lia.\nQed.\n\nLemma distr_lift_subst_context n k s Γ : lift_context n k (subst_context s 0 Γ) =\n  subst_context (map (lift n k) s) 0 (lift_context n (#|s| + k) Γ).\nProof.\n  rewrite !lift_context_alt !subst_context_alt.\n  rewrite !mapi_compose.\n  apply mapi_ext.\n  intros n' x.\n  rewrite /lift_decl /subst_decl !compose_map_decl.\n  apply map_decl_ext => y.\n  rewrite !mapi_length Nat.add_0_r; autorewrite with len. unf_term.\n  rewrite distr_lift_subst_rec; f_equal. f_equal. lia.\nQed.\n\nLemma skipn_subst_context n s k Γ : skipn n (subst_context s k Γ) =\n  subst_context s k (skipn n Γ).\nProof.\n  rewrite !subst_context_alt.\n  rewrite skipn_mapi_rec. rewrite mapi_rec_add /mapi.\n  apply mapi_rec_ext. intros.\n  f_equal. rewrite List.skipn_length. lia.\nQed.\n\nLemma lift_extended_subst (Γ : context) k :\n  extended_subst Γ k = map (lift0 k) (extended_subst Γ 0).\nProof.\n  induction Γ as [|[? [] ?] ?] in k |- *; simpl; auto; unf_term.\n  - rewrite IHΓ. f_equal.\n    autorewrite with len.\n    rewrite distr_lift_subst. f_equal.\n    autorewrite with len. rewrite simpl_lift; lia_f_equal.\n  - rewrite Nat.add_0_r; f_equal.\n    rewrite IHΓ (IHΓ 1).\n    rewrite map_map_compose. apply map_ext => x.\n    rewrite simpl_lift; try lia.\n    now rewrite Nat.add_1_r.\nQed.\n\nLemma lift_extended_subst' Γ k k' : extended_subst Γ (k + k') = map (lift0 k) (extended_subst Γ k').\nProof.\n  induction Γ as [|[? [] ?] ?] in k |- *; simpl; auto.\n  - rewrite IHΓ. f_equal.\n    autorewrite with len.\n    rewrite distr_lift_subst. f_equal.\n    autorewrite with len. rewrite simpl_lift; lia_f_equal.\n  - f_equal.\n    rewrite (IHΓ (S k)) (IHΓ 1).\n    rewrite map_map_compose. apply map_ext => x.\n    rewrite simpl_lift; lia_f_equal.\nQed.\n\nLemma subst_extended_subst_k s Γ k k' : extended_subst (subst_context s k Γ) k' =\n  map (subst s (k + context_assumptions Γ + k')) (extended_subst Γ k').\nProof.\n  induction Γ as [|[na [b|] ty] Γ]; simpl; auto; rewrite subst_context_snoc /=;\n    autorewrite with len; f_equal; auto.\n  - rewrite IHΓ.\n    rewrite commut_lift_subst_rec; try lia.\n    rewrite distr_subst. now len.\n  - elim: Nat.leb_spec => //. lia.\n  - rewrite (lift_extended_subst' _ 1 k') IHΓ.\n    rewrite (lift_extended_subst' _ 1 k').\n    rewrite !map_map_compose.\n    apply map_ext.\n    intros x.\n    erewrite (commut_lift_subst_rec); lia_f_equal.\nQed.\n\nLemma extended_subst_app Γ Γ' :\n  extended_subst (Γ ++ Γ') 0 =\n  extended_subst (subst_context (extended_subst Γ' 0) 0\n   (lift_context (context_assumptions Γ') #|Γ'| Γ)) 0 ++\n   extended_subst Γ' (context_assumptions Γ).\nProof.\n  induction Γ as [|[na [b|] ty] Γ] in |- *; simpl; auto.\n  - autorewrite with len.\n    rewrite IHΓ. simpl.  rewrite app_comm_cons.\n    f_equal.\n    erewrite subst_app_simpl'.\n    2:autorewrite with len; reflexivity.\n    simpl.\n    rewrite lift_context_snoc subst_context_snoc /=.\n    len. f_equal. f_equal.\n    rewrite -{3}(Nat.add_0_r #|Γ|).\n    erewrite <- (simpl_lift _ _ _ _ (#|Γ| + #|Γ'|)). all:try lia.\n    rewrite distr_lift_subst_rec. autorewrite with len.\n    f_equal. apply lift_extended_subst.\n  - rewrite lift_context_snoc  subst_context_snoc /=. lia_f_equal.\n    rewrite lift_extended_subst. rewrite IHΓ /=.\n    rewrite map_app. rewrite !(lift_extended_subst _ (S _)).\n    rewrite (lift_extended_subst _ (context_assumptions Γ)).\n    rewrite map_map_compose.\n    f_equal. apply map_ext. intros.\n    rewrite simpl_lift; lia_f_equal.\nQed.\n\nLemma subst_context_comm s s' Γ :\n  subst_context s 0 (subst_context s' 0 Γ) =\n  subst_context (map (subst s 0) s' ++ s) 0 Γ.\nProof.\n  intros.\n  rewrite !subst_context_alt !mapi_compose.\n  apply mapi_ext => i x.\n  destruct x as [na [b|] ty] => //.\n  - rewrite /subst_decl /map_decl /=; f_equal.\n    + rewrite !mapi_length. f_equal. rewrite {2}Nat.add_0_r.\n      rewrite subst_app_simpl.\n      rewrite distr_subst_rec. rewrite Nat.add_0_r; f_equal; try lia.\n      rewrite map_length. f_equal; lia.\n    + rewrite mapi_length.\n      rewrite subst_app_simpl.\n      rewrite {2}Nat.add_0_r.\n      rewrite distr_subst_rec. rewrite Nat.add_0_r; f_equal; try lia.\n      rewrite map_length. f_equal; lia.\n  - rewrite /subst_decl /map_decl /=; f_equal.\n    rewrite !mapi_length. rewrite {2}Nat.add_0_r.\n    rewrite subst_app_simpl.\n    rewrite distr_subst_rec. rewrite Nat.add_0_r; f_equal; try lia.\n    rewrite map_length. f_equal. lia.\nQed.\n\nLemma context_assumptions_subst s n Γ :\n  context_assumptions (subst_context s n Γ) = context_assumptions Γ.\nProof. apply context_assumptions_fold. Qed.\n#[global]\nHint Rewrite context_assumptions_subst : pcuic.\n\nLemma subst_app_context s s' Γ : subst_context (s ++ s') 0 Γ = subst_context s 0 (subst_context s' #|s| Γ).\nProof.\n  induction Γ; simpl; auto.\n  rewrite !subst_context_snoc /= /subst_decl /map_decl /=. simpl.\n  rewrite IHΓ. f_equal. f_equal.\n  - destruct a as [na [b|] ty]; simpl; auto.\n    f_equal. rewrite subst_context_length Nat.add_0_r.\n    now rewrite subst_app_simpl.\n  - rewrite subst_context_length Nat.add_0_r.\n    now rewrite subst_app_simpl.\nQed.\n\nLemma subst_app_context' (s s' : list term) (Γ : context) n :\n  n = #|s| ->\n  subst_context (s ++ s') 0 Γ = subst_context s 0 (subst_context s' n Γ).\nProof.\n  intros ->; apply subst_app_context.\nQed.\n\nLemma map_subst_app_simpl l l' k (ts : list term) :\n  map (subst l k ∘ subst l' (k + #|l|)) ts =\n  map (subst (l ++ l') k) ts.\nProof.\n  eapply map_ext. intros.\n  now rewrite subst_app_simpl.\nQed.\n\nLemma simpl_map_lift x n k :\n  map (lift0 n ∘ lift0 k) x =\n  map (lift k n ∘ lift0 n) x.\nProof.\n  apply map_ext => t.\n  rewrite simpl_lift => //; try lia.\n  rewrite simpl_lift; try lia.\n  now rewrite Nat.add_comm.\nQed.\n\nLemma subst_it_mkProd_or_LetIn n k ctx t :\n  subst n k (it_mkProd_or_LetIn ctx t) =\n  it_mkProd_or_LetIn (subst_context n k ctx) (subst n (length ctx + k) t).\nProof.\n  induction ctx in n, k, t |- *; simpl; try congruence.\n  pose (subst_context_snoc n k ctx a). unfold snoc in e. rewrite e. clear e.\n  simpl. rewrite -> IHctx.\n  pose (subst_context_snoc n k ctx a). simpl. now destruct a as [na [b|] ty].\nQed.\n\nLemma map_subst_instance_to_extended_list_k u ctx k :\n  to_extended_list_k (subst_instance u ctx) k\n  = to_extended_list_k ctx k.\nProof.\n  unfold to_extended_list_k.\n  cut (map (subst_instance u) [] = []); [|reflexivity].\n  unf_term. generalize (@nil term); intros l Hl.\n  induction ctx in k, l, Hl |- *; cbnr.\n  destruct a as [? [] ?]; cbnr; eauto.\nQed.\n\nLemma to_extended_list_k_subst n k c k' :\n  to_extended_list_k (subst_context n k c) k' = to_extended_list_k c k'.\nProof.\n  unfold to_extended_list_k. revert k'.\n  unf_term. generalize (@nil term) at 1 2.\n  induction c in n, k |- *; simpl; intros. 1: reflexivity.\n  rewrite subst_context_snoc. unfold snoc. simpl.\n  destruct a. destruct decl_body.\n  - unfold subst_decl, map_decl. simpl.\n    now rewrite IHc.\n  - simpl. apply IHc.\nQed.\n\nLemma it_mkProd_or_LetIn_inj ctx s ctx' s' :\n  it_mkProd_or_LetIn ctx (tSort s) = it_mkProd_or_LetIn ctx' (tSort s') ->\n  ctx = ctx' /\\ s = s'.\nProof.\n  move/(f_equal (destArity [])).\n  rewrite !destArity_it_mkProd_or_LetIn /=.\n  now rewrite !app_context_nil_l => [= -> ->].\nQed.\n\nLemma destArity_spec ctx T :\n  match destArity ctx T with\n  | Some (ctx', s) => it_mkProd_or_LetIn ctx T = it_mkProd_or_LetIn ctx' (tSort s)\n  | None => True\n  end.\nProof.\n  induction T in ctx |- *; simpl; try easy.\n  - specialize (IHT2 (ctx,, vass na T1)). now destruct destArity.\n  - specialize (IHT3 (ctx,, vdef na T1 T2)). now destruct destArity.\nQed.\n\nLemma destArity_spec_Some ctx T ctx' s :\n  destArity ctx T = Some (ctx', s)\n  -> it_mkProd_or_LetIn ctx T = it_mkProd_or_LetIn ctx' (tSort s).\nProof.\n  pose proof (destArity_spec ctx T) as H.\n  intro e; now rewrite e in H.\nQed.\n\n(** Standard substitution lemma for a context with no lets. *)\n\nInductive nth_error_app_spec {A} (l l' : list A) (n : nat) : option A -> Type :=\n| nth_error_app_spec_left x :\n  nth_error l n = Some x ->\n  n < #|l| ->\n  nth_error_app_spec l l' n (Some x)\n| nth_error_app_spec_right x :\n  nth_error l' (n - #|l|) = Some x ->\n  #|l| <= n < #|l| + #|l'| ->\n  nth_error_app_spec l l' n (Some x)\n| nth_error_app_spec_out : #|l| + #|l'| <= n -> nth_error_app_spec l l' n None.\n\nLemma nth_error_appP {A} (l l' : list A) (n : nat) : nth_error_app_spec l l' n (nth_error (l ++ l') n).\nProof.\n  destruct (Nat.ltb n #|l|) eqn:lt; [apply Nat.ltb_lt in lt|apply Nat.ltb_nlt in lt].\n  * rewrite nth_error_app_lt //.\n    destruct (snd (nth_error_Some' _ _) lt) as [x eq].\n    rewrite eq.\n    constructor; auto.\n  * destruct (Nat.ltb n (#|l| + #|l'|)) eqn:ltb'; [apply Nat.ltb_lt in ltb'|apply Nat.ltb_nlt in ltb'].\n    + rewrite nth_error_app2; try lia.\n      destruct nth_error eqn:hnth.\n      - constructor 2; auto; try lia.\n      - constructor.\n        eapply nth_error_None in hnth. lia.\n    + case: nth_error_spec => //; try lia.\n      { intros. len in l0. lia. }\n      len. intros. constructor. lia.\nQed.\n\nLemma nth_error_app_context (Γ Δ : context) (n : nat) :\n  nth_error_app_spec Δ Γ n (nth_error (Γ ,,, Δ) n).\nProof.\n  apply nth_error_appP.\nQed.\n\nLemma expand_lets_k_nil k t : expand_lets_k [] k t = t.\nProof. by rewrite /expand_lets_k /= subst_empty lift0_id. Qed.\n\n\n\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/Syntax/PCUICLiftSubst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203340678568, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.25149231017631773}}
{"text": "Load loadpath.\nRequire Import Coq.Lists.List.\nRequire Import veristar.variables veristar.datatypes veristar.list_denote.\nRequire Import compcert.Coqlib.\nRequire Import VST.veric.Coqlib2.\nRequire Import VST.msl.predicates_sa.\nRequire Import ZArith.\nRequire Import veristar.veristar_sound.\nRequire Import veristar.model_type veristar.model.\nRequire Import Permutation.\nRequire Import veristar.veristar.\nRequire Import veristar.isolate.\nRequire Import veristar.fresh.\nRequire Import veristar.basic.\nRequire Import Classical.\n\nModule Type ISO_SOUND.\nDeclare Module VeriStarSound : VERISTAR_SOUND.\nImport VeriStarSound VSM VeriStarLogic.\n\nAxiom expr_denote_heap_ind : forall x s h h',\n  expr_denote x (State s h)=expr_denote x (State s h').\n\nAxiom oracle_sound: forall (e: entailment),\n    oracle e = true -> entailment_denote e.\n\n\nDefinition existsv (nextv: var) (P: spred) : spred :=\n   fun s => exists y,  P (State (env_set nextv y (stk s)) (hp s)).\n\nAxiom existsv_refl:  forall P x, P |-- existsv x P.\n\nDefinition fresh {A} (f: A -> var) (a: A) (x: var) : Prop :=  Ident.lt (f a) x.\n\nLtac do_fresh1 :=\n  repeat match goal with H: Ile _ _ |- _ => revert H\n                                     | H: Ident.lt _ _ |- _ => revert H\n                                     | H: fresh _ _ _ |- _ => revert H end;\n  clear;\n  unfold fresh; simpl;\n  repeat ((rewrite freshmax_list_app || rewrite freshmax_list_rev\n                || rewrite varmax_minid || rewrite varmax_minid'); simpl).\n\nLtac do_fresh :=\n  do_fresh1; intros;\n  repeat match goal with\n             |  H: Ident.lt (var_max _ _) _ |- _ => apply var_max_split in H; destruct H\n             end;\n  repeat apply var_max_intro; auto;\n  try solve [etransitivity; eauto].\n\nDefinition set_in_state nextv z s := State (env_set nextv z (stk s)) (hp s).\n\nAxiom expr_denote_agree:\n  forall e s nextv z,\n  fresh freshmax_expr e nextv ->\n  expr_denote e s = expr_denote e (set_in_state nextv z s).\n\nAxiom pn_atom_denote_agree:\n forall a s nextv z,\n  fresh freshmax_pn_atom a nextv ->\n  pn_atom_denote a s ->\n  pn_atom_denote a (set_in_state nextv z s).\n\nAxiom space_atom_denote_agree:\n forall a s nextv z,\n  fresh freshmax_space_atom a nextv ->\n  space_atom_denote a s ->\n  space_atom_denote a (set_in_state nextv z s).\n\nAxiom list_denote__pn_atom_agree:\n forall pos s nextv z,\n  fresh (freshmax_list freshmax_pn_atom) pos nextv ->\n  list_denote pn_atom_denote (@andp _) TT pos s ->\n  list_denote pn_atom_denote (@andp _) TT pos (set_in_state nextv z s).\n\nAxiom list_denote_space_agree:\n forall pos s nextv z,\n  fresh (freshmax_list freshmax_space_atom) pos nextv ->\n  list_denote space_atom_denote (@sepcon _ _) emp pos s ->\n  list_denote space_atom_denote (@sepcon _ _) emp pos (set_in_state nextv z s).\n\n(*\n Lemma agree_except_sym:\n  forall x s s', agree_except x s s' -> agree_except x s' s.\n Proof.\n unfold agree_except; intuition. symmetry. apply H0; auto.\n Qed.\n*)\n\n\n\nAxiom list_denote_agree_pn_atom_neg:\n forall pos s nextv z,\n  fresh (freshmax_list freshmax_pn_atom) pos nextv ->\n  list_denote (neg oo pn_atom_denote) (@andp _) TT pos s ->\n  list_denote (neg oo pn_atom_denote) (@andp _) TT pos (set_in_state nextv z s).\n\nAxiom fresh_lt:\n  forall {A} (f: A -> var) a x y, fresh f a x -> Ident.lt x y -> fresh f a y.\n\nAxiom space_denote_permute: forall l l',\n  Permutation l l' ->  space_denote l = space_denote l'.\n\nAxiom assertion_denote_permute: forall pi l l',\n  Permutation l l' ->\n   assertion_denote (Assertion pi l) = assertion_denote (Assertion pi l').\n\n\nAxiom incon_e: forall P, incon P = true -> assertion_denote P |-- FF.\n\nAxiom isolate_sound:\n  forall e P nextv nextv2 results\n      (LT: Ident.lt nextv nextv2),\n      isolate e P nextv = Some results ->\n       fresh freshmax_expr e nextv ->\n       fresh freshmax_assertion P nextv ->\n      assertion_denote P |--\n        fold_right (fun P => orp (existsv nextv (assertion_denote P))) FF results /\\\n      forall Q, In Q results ->\n            match Q with\n           |Assertion _ (Next e0 _ :: _) => e=e0\n           | _ => False\n           end /\\\n           fresh freshmax_assertion Q nextv2.\nEnd ISO_SOUND.\n\nModule Iso_Sound (VSS: VERISTAR_SOUND) : ISO_SOUND with Module VeriStarSound := VSS.\nModule VeriStarSound := VSS.\nImport VeriStarSound VSM VeriStarLogic.\n\n(********duplicate temporarily a lemma from wellformed_sound.\nMaybe some of the lemmas there Repair import-structire later******\n********)\n\nLemma expr_denote_heap_ind : forall x s h h',\n  expr_denote x (State s h)=expr_denote x (State s h').\nProof.\nintros. destruct x; auto.\nQed.\n\n(************end of duplicated lemma ********)\n\nLemma oracle_sound: forall (e: entailment),\n    oracle e = true -> entailment_denote e.\nProof.\nunfold oracle;\nintros.\napply check_entailment_sound.\ndestruct (VeriStar.check_entailment e); congruence.\nQed.\n\n(*\nDefinition agree_except (x: var) (s s': state) : Prop :=\n   (forall x', x' <> x -> stack_get (stk s) (Some x') = stack_get (stk s') (Some x')) /\\ hp s = hp s'.\n\nLemma agree_except_refl: forall x s, agree_except x s s.\nProof. unfold agree_except; intuition.\nQed.\nHint Resolve agree_except_refl.\n\nDefinition existsv (nextv: var) (P: spred) : spred :=\n   fun s => exists s', agree_except nextv s s' /\\ P s'.\n*)\n\nDefinition existsv (nextv: var) (P: spred) : spred :=\n   fun s => exists y,  P (State (env_set nextv y (stk s)) (hp s)).\n\nLemma existsv_refl:\n  forall P x, P |-- existsv x P.\nProof.\nintros; intros s ?. exists (env_get (stk s) x).\ndestruct s; simpl. replace (env_set x (env_get s x) s) with s; auto.\nrewrite env_reset; auto.\nQed.\n\nDefinition fresh {A} (f: A -> var) (a: A) (x: var) : Prop :=  Ident.lt (f a) x.\n\nLemma list_denote_separate':\n  forall (X Y: Type) (f: X -> spred) (g: Y -> spred) (base: spred) l1 l2,\n  list_denote f (@sepcon _ _) (list_denote g (@sepcon _ _) base l2) l1 =\n  sepcon (list_denote f (@sepcon _ _) emp l1)\n   (sepcon (list_denote g (@sepcon _ _) emp l2)\n     base).\nProof.\ninduction l1; simpl; intros.\nrewrite emp_sepcon.\ninduction l2; simpl. rewrite emp_sepcon; auto.\nrewrite IHl2. rewrite sepcon_assoc; auto.\nrewrite sepcon_assoc.\nf_equal.\nauto.\nQed.\n\nLtac do_fresh1 :=\n  repeat match goal with H: Ile _ _ |- _ => revert H\n                                     | H: Ident.lt _ _ |- _ => revert H\n                                     | H: fresh _ _ _ |- _ => revert H end;\n  clear;\n  unfold fresh; simpl;\n  repeat ((rewrite freshmax_list_app || rewrite freshmax_list_rev\n                || rewrite varmax_minid || rewrite varmax_minid'); simpl).\n\nLtac do_fresh :=\n  do_fresh1; intros;\n  repeat match goal with\n             |  H: Ident.lt (var_max _ _) _ |- _ => apply var_max_split in H; destruct H\n             end;\n  repeat apply var_max_intro; auto;\n  try solve [etransitivity; eauto].\n(*  repeat rewrite Zpos_succ_morphism in *; solve [auto | omega]. *)\n\nLemma freshmax_pn_atom_Equ_Destruct: forall e e' nextv,\nfresh freshmax_pn_atom (Equ e e') nextv ->\nfresh freshmax_expr e nextv /\\ fresh freshmax_expr e' nextv.\nProof.\nintros.\nsplit; do_fresh.\nQed.\n\nLemma freshmax_pn_atom_Nequ_Destruct: forall e e' nextv,\nfresh freshmax_pn_atom (Nequ e e') nextv ->\nfresh freshmax_expr e nextv /\\ fresh freshmax_expr e' nextv.\nProof.\nintros.\ndo_fresh.\nQed.\n\nDefinition set_in_state nextv z s := State (env_set nextv z (stk s)) (hp s).\n\n\n\nLemma expr_denote_agree:\n  forall e s nextv z,\n  fresh freshmax_expr e nextv ->\n  expr_denote e s = expr_denote e (set_in_state nextv z s).\nProof.\nintros.\ndestruct e; simpl; auto.\nrewrite gso_env; auto.\ndo_fresh. intro; subst.\neapply Ilt_irrefl; eauto.\nQed.\n\nLemma pn_atom_denote_agree:\n forall a s nextv z,\n  fresh freshmax_pn_atom a nextv ->\n  pn_atom_denote a s ->\n  pn_atom_denote a (set_in_state nextv z s).\nProof.\nintros.\ndestruct a.\n  destruct (freshmax_pn_atom_Equ_Destruct _ _ _ H) as [Fe Fe0].\n  simpl in *.\n  unfold var_eq in *.\n  repeat rewrite <- expr_denote_agree; auto.\n\n  destruct (freshmax_pn_atom_Nequ_Destruct _ _ _ H) as [Fe Fe0].\n  simpl in *. unfold neg in *.\n  contradict H0.\n  unfold var_eq in *.\n  rewrite <- expr_denote_agree in H0; auto.\n  rewrite <- expr_denote_agree in H0; auto.\nQed.\n\nLemma space_atom_denote_agree:\n forall a s nextv z,\n  fresh freshmax_space_atom a nextv ->\n  space_atom_denote a s ->\n  space_atom_denote a (set_in_state nextv z s).\nProof.\nintros.\ndestruct a.\nsimpl in *.\nrewrite <- (expr_denote_agree e s nextv z) by do_fresh.\nrewrite <- (expr_denote_agree e0 s nextv z) by do_fresh.\nauto.\nsimpl in *.\nrewrite <- (expr_denote_agree e s nextv z) by do_fresh.\nrewrite <- (expr_denote_agree e0 s nextv z) by do_fresh.\nauto.\nQed.\n\nLemma list_denote__pn_atom_agree:\n forall pos s nextv z,\n  fresh (freshmax_list freshmax_pn_atom) pos nextv ->\n  list_denote pn_atom_denote (@andp _) TT pos s ->\n  list_denote pn_atom_denote (@andp _) TT pos (set_in_state nextv z s).\nProof.\nintros.\nrevert H H0; induction pos; simpl; intros; auto.\ndestruct H0; split.\neapply pn_atom_denote_agree; eauto. do_fresh.\napply IHpos; auto.\ndo_fresh.\nQed.\n\nLemma list_denote_space_agree:\n forall pos s nextv z,\n  fresh (freshmax_list freshmax_space_atom) pos nextv ->\n  list_denote space_atom_denote (@sepcon _ _) emp pos s ->\n  list_denote space_atom_denote (@sepcon _ _) emp pos (set_in_state nextv z s).\nProof.\nintros.\nrevert s H H0; induction pos; simpl; intros; auto.\nrewrite empstate_empheap in *. simpl; auto.\ndestruct H0 as [s1 [s2 [ ? [? ?]]]].\nexists (set_in_state nextv z s1); exists (set_in_state nextv z s2); split3.\ndestruct s1; destruct s2; destruct s; destruct H0; destruct H0; simpl in *; subst; unfold set_in_state; split; simpl; auto.\napply msl.sepalg_generators.join_equiv_refl.\napply space_atom_denote_agree; auto; do_fresh.\napply IHpos; auto.\ndo_fresh.\nQed.\n\n(*\n Lemma agree_except_sym:\n  forall x s s', agree_except x s s' -> agree_except x s' s.\n Proof.\n unfold agree_except; intuition. symmetry. apply H0; auto.\n Qed.\n*)\n\nAxiom env_reset2: forall s x z, env_set x (env_get s x) (env_set x z s) = s.\n\nLemma list_denote_agree_pn_atom_neg:\n forall pos s nextv z,\n  fresh (freshmax_list freshmax_pn_atom) pos nextv ->\n  list_denote (neg oo pn_atom_denote) (@andp _) TT pos s ->\n  list_denote (neg oo pn_atom_denote) (@andp _) TT pos (set_in_state nextv z s).\nProof.\nintros.\nrevert H H0; induction pos; simpl; intros; auto.\ndestruct H0; split.\nunfold compose, neg in H0|-*.\ncontradict H0.\nreplace s with (set_in_state nextv (env_get (stk s) nextv) (set_in_state nextv z s)).\napply pn_atom_denote_agree; auto.\ndo_fresh.\nclear. unfold set_in_state; destruct s; simpl. f_equal.\napply env_reset2.\napply IHpos; auto.\ndo_fresh.\nQed.\n\nLemma fresh_lt:\n  forall {A} (f: A -> var) a x y, fresh f a x -> Ident.lt x y -> fresh f a y.\nProof.\nintros.\nunfold fresh in *. transitivity x; auto.\nQed.\n\nLemma or_FF: forall {A} (P: pred A), (orp P FF) = P.\nProof. unfold orp; intros; extensionality z; apply prop_ext; intuition.\nQed.\n\nLemma permute_sigma0:\n forall sigma0 (a: space_atom) sigma, Permutation (sigma0 ++ a :: sigma) (a :: sigma0 ++ sigma).\nProof.\nintros; eapply perm_trans; [apply Permutation_app_comm | apply Permutation_cons; apply Permutation_app_comm].\nQed.\n\nLemma space_denote_permute: forall l l',\n  Permutation l l' ->\n   space_denote l = space_denote l'.\nintros.\nunfold space_denote.\napply (listd_perm space_atom_denote _ emp (sepconS _ _) (@sepconA state _ _) l l' H) .\nQed.\n\nLemma assertion_denote_permute: forall pi l l',\n  Permutation l l' ->\n   assertion_denote (Assertion pi l) = assertion_denote (Assertion pi l').\nintros.\nsimpl.\nrewrite (space_denote_permute _ _ H).\ntrivial.\nQed.\n\nLemma Lseg_unfold_neq:\n  forall e nextv pi sigma0 e0 e1 sigma s,\n    fresh freshmax_expr e nextv ->\n    fresh freshmax_assertion (Assertion pi (sigma0 ++ Lseg e0 e1 :: sigma)) nextv ->\n    (e === e0) s ->\n    list_denote pn_atom_denote (@andp _)\n         (space_denote (sigma0 ++ Lseg e0 e1 :: sigma)) pi s ->\n    ~ (e0 === e1) s ->\n    existsv nextv\n      (assertion_denote (Assertion pi (Next e (Var nextv) :: Lseg (Var nextv) e1 :: sigma0 ++ sigma))) s.\nProof.\nintros.\nrewrite (@listd_prop pn_atom state pn_atom_denote) in H2.\ndestruct H2 as [HypP HypSig].\nrewrite (space_denote_permute _ _  (permute_sigma0 _ _ _ )) in HypSig.\nunfold space_denote in HypSig.\nrewrite listd_cons in HypSig.\ndestruct HypSig as [s1 [s2 [? [? ?]]]].\ninv H4.\ncontradiction H3.\nunfold var_eq.\nclear - H6 H2.\n destruct s1; destruct s2; destruct s; destruct H2; destruct H; simpl in *; auto.\nsubst; rewrite (expr_denote_heap_ind e0 s h1 h). rewrite (expr_denote_heap_ind e1 s h1 h).\nauto.\nexists z.\nchange (State (env_set nextv z (stk s)) (hp s)) with (set_in_state nextv z s).\nsimpl.\nrewrite (@listd_prop pn_atom state pn_atom_denote).\nrewrite sepconA; auto with typeclass_instances.\nsplit.\napply list_denote__pn_atom_agree; trivial. do_fresh.\nclear HypP.\nexists (set_in_state nextv z s1).\nexists (set_in_state nextv z s2).\nsplit3.\nclear - H2. destruct H2; destruct H;\nunfold set_in_state; repeat split; simpl; try congruence.\nexists (set_in_state nextv z (State (stk s1) h0)).\nexists (set_in_state nextv z (State (stk s1) h1)).\nsplit3; simpl; auto.\nsplit; auto.\napply msl.sepalg_generators.join_equiv_refl.\nunfold var_eq in *.\nrepeat rewrite <- expr_denote_agree by do_fresh.\ndestruct s as [s h]. destruct s1 as [s1 h1']; destruct s2 as [s2 h2'].\ndestruct H2. destruct H2. simpl in H11. subst.\nsimpl in *. subst.\nrepeat rewrite expr_denote_heap_ind with (h:=h0)(h':=h) in *.\nrepeat rewrite expr_denote_heap_ind with (h:=h1')(h':=h) in *.\nrewrite H1. rewrite H7.\nrewrite gss_env.\nsplit; auto.\ninv H9; auto.\nunfold nil_or_loc. right; eauto.\nrewrite gss_env. rewrite <- expr_denote_agree by do_fresh.\ndestruct s1 as [s' h']; simpl in *.\nrewrite expr_denote_heap_ind with (h:=h1)(h':=h'); auto.\napply list_denote_space_agree; auto; do_fresh.\nQed.\n\n\nLemma exorcize_sound_Lseg:\n forall (e : expr) (pnatoms : list pn_atom) (e0 e1 : expr)\n  (sigma : list space_atom) (nextv : var) (nextv2 : var)\n  (sigma0 : list space_atom) (l : list assertion),\n  fresh freshmax_expr e nextv ->\n  Ident.lt nextv nextv2 ->\n  fresh freshmax_assertion\n    (Assertion pnatoms (rev (Lseg e0 e1 :: sigma0) ++ sigma)) nextv ->\n  entailment_denote\n    (Entailment (Assertion pnatoms (rev (Lseg e0 e1 :: sigma0) ++ sigma))\n       (Assertion [Equ e e0] (rev (Lseg e0 e1 :: sigma0) ++ sigma))) ->\n  (assertion_denote\n     (Assertion (Equ e0 e1 :: pnatoms) (rev (Lseg e0 e1 :: sigma0) ++ sigma))\n    |-- fold_right\n         (fun P => orp (existsv nextv (assertion_denote P))) FF l) /\\\n   (forall (Q : assertion),\n     In Q l ->\n          match Q with\n          |Assertion _ (Next e0 _ :: _) => e=e0\n          | _ => False\n          end /\\\n          fresh freshmax_assertion Q nextv2) ->\n        (assertion_denote (Assertion pnatoms (rev (Lseg e0 e1 :: sigma0) ++ sigma))\n      |-- fold_right\n          (fun P => orp (existsv nextv (assertion_denote P))) FF\n          (Assertion pnatoms (Next e (Var nextv) :: Lseg (Var nextv) e1 :: rev sigma0 ++ sigma) :: l)) /\\\n   (forall Q,\n    In Q (Assertion pnatoms (Next e (Var nextv) :: Lseg (Var nextv) e1 :: rev sigma0 ++ sigma) :: l) ->\n          match Q with\n          |Assertion _ (Next e0 _ :: _) => e=e0\n          | _ => False\n          end /\\\n    fresh freshmax_assertion Q nextv2).\nProof.\nintros e pnatoms e0 e1 sigma nextv nextv2 sigma0 l FRESHe H1 H H0 IHsigma.\ndestruct IHsigma.\nsplit.\nsimpl in H0,H2.\nintros s ?.\nsimpl in H0, H4.\ngeneralize (H0 _ H4); clear H0; intros [? _].\nrewrite (@listd_prop pn_atom state pn_atom_denote) in H4.\ndestruct H4 as [HypP HypSig].\ndestruct (classic ((e0===e1) s)).\nright.\napply H2.\nsplit; auto.\nrewrite (@listd_prop pn_atom state pn_atom_denote).\nsplit; auto.\nleft.\neapply Lseg_unfold_neq with e0; auto.\nsimpl in H.\nrewrite app_ass in H; apply H.\n(*repeat rewrite list_denote_separate.*)\nrewrite (@listd_prop pn_atom state pn_atom_denote).\nsplit; auto.\nrewrite app_ass in HypSig; apply HypSig.\nintros.\nsimpl in H4.\ndestruct H4.\ninv H4.\nsplit; auto.\ndo_fresh.\napply H3; auto.\nQed.\n\nLemma incon_e: forall P, incon P = true -> assertion_denote P |-- FF.\nProof.\nunfold incon; intros.\nforget match P with Assertion _ sigma => sigma end as Q.\napply oracle_sound in H.\nsimpl in H.\neapply derives_trans; [apply H | clear H].\nintros w [H ?]; apply H; reflexivity.\nQed.\n\nLemma exorcize_sound_nil:\n forall e pnatoms nextv nextv2 sigma0 cl,\n    Ident.lt nextv nextv2 ->\n    exorcize e pnatoms sigma0 [ ] nextv = Some cl ->\n    (assertion_denote (Assertion pnatoms (rev sigma0 ++ [ ]))\n     |-- fold_right\n       (fun P => orp (existsv nextv (assertion_denote P))) FF cl) /\\\n       (forall (Q : assertion),\n         In Q cl ->\n          (match Q with\n          |Assertion  _ (Next e0 _ :: _) => e=e0\n          | _ => False\n          end /\\\n          fresh freshmax_assertion Q nextv2)).\nProof.\nsimpl; intros.\nrevert H0; case_eq (incon (Assertion pnatoms (rev sigma0))); intros; inv H1.\napply incon_e in H0.\nsplit.\nrewrite <- app_nil_end.\neapply derives_trans; [apply H0 | auto].\nsimpl; intros; contradiction.\nQed.\n\n\n (* need this bogus \"exorcize_e\" lemma, because doing it in-line, in the\n   obvious way using case_eq or (remember; destruct) makes the Qed take forever. *)\nLemma exorcize_e:\n forall e pnatoms sigma0 e0 e1 sigma nextv cl,\n  exorcize e pnatoms sigma0 (Lseg e0 e1 :: sigma) nextv = Some cl ->\n  (entailment_denote\n       (Entailment (Assertion pnatoms (rev (Lseg e0 e1 :: sigma0) ++ sigma))\n          (Assertion [Equ e e0] (rev (Lseg e0 e1 :: sigma0) ++ sigma)))\n    /\\ (exists cl',\n          exorcize e (Equ e0 e1 :: pnatoms) (Lseg e0 e1 :: sigma0) sigma nextv = Some cl' /\\\n           cl = (Assertion pnatoms\n                       (Next e (Var nextv) :: Lseg (Var nextv) e1 :: rev sigma0 ++ sigma)) :: cl'))\n  \\/ exorcize e pnatoms (Lseg e0 e1 :: sigma0) sigma nextv = Some cl.\nProof.\nsimpl; intros until cl.\ncase_eq (oracle\n      (Entailment (Assertion pnatoms (rev sigma0 ++ Lseg e0 e1 :: sigma))\n         (Assertion [Equ e e0] (rev sigma0 ++ Lseg e0 e1 :: sigma)))); intros.\nrevert H0; case_eq (exorcize e (Equ e0 e1 :: pnatoms) (Lseg e0 e1 :: sigma0) sigma nextv);\n  intros; inv H1.\nleft; split; auto.\napply oracle_sound in H; simpl in H.\nrewrite app_ass. auto.\nexists l; split; auto.\nright. auto.\nQed.\n\n\nLemma exorcize_sound:\n  forall e pnatoms sigma nextv nextv2\n      (FRESHe: fresh freshmax_expr e nextv)\n      (LT: Ident.lt nextv nextv2),\n      (fresh freshmax_assertion (Assertion pnatoms sigma) nextv) ->\n      forall cl,\n      (exorcize e pnatoms nil sigma nextv) = Some cl ->\n (assertion_denote (Assertion pnatoms sigma)\n |-- fold_right (fun P => orp (existsv nextv (assertion_denote P))) FF cl) /\\\n       (forall Q,\n          In Q cl ->\n           match Q with\n           |Assertion _ (Next e0 _ :: _) => e=e0\n           | _ => False\n           end /\\\n          fresh freshmax_assertion Q nextv2).\nProof.\nintros.\nreplace sigma with (rev nil++sigma) in H by auto.\npattern sigma at 1; replace sigma with (rev nil++sigma) by auto.\nremember (@nil space_atom) as sigma0.\nclear Heqsigma0.\nrevert pnatoms sigma0 cl H0 H; induction sigma; intros.\napply exorcize_sound_nil; auto.\nreplace (rev sigma0 ++ a :: sigma) with (rev (a::sigma0) ++ sigma)  in * by apply app_ass.\n\ndestruct a.\n(* 'Next' case *)\napply (IHsigma _ _ _ H0 H).\n\n(* 'Lseg' case *)\napply exorcize_e in H0.\ndestruct H0 as [[? [cl' [? ?]]] | ?].\nsubst cl.\nspecialize (IHsigma _ _ _ H1).\nspec IHsigma; [do_fresh | ].\napply exorcize_sound_Lseg; auto.\napply (IHsigma _ _ _ H0 H).\nQed.\n\n\n (* need this bogus \"isolate_e\" lemma, because doing it in-line, in the\n   obvious way using case_eq or (remember; destruct) makes the Qed take forever. *)\nLemma isolate_e:\n forall e pnatoms sigma0 e0 e1 sigma nextv N results,\n  isolate' e pnatoms sigma0 (Lseg e0 e1 :: sigma) nextv N = Some results ->\n  (entailment_denote\n       (Entailment (Assertion pnatoms (rev sigma0 ++ Lseg e0 e1 :: sigma))\n          (Assertion [Equ e e0, Nequ e0 e1] (rev sigma0 ++ Lseg e0 e1 :: sigma)))\n          /\\ results = [Assertion pnatoms (Next e (Var nextv) :: Lseg (Var nextv) e1 :: rev sigma0 ++ sigma)]\n    \\/ (entailment_denote\n           (Entailment (Assertion pnatoms (rev sigma0 ++ Lseg e0 e1 :: sigma))\n              (Assertion [Equ e e0] (rev sigma0 ++ Lseg e0 e1 :: sigma)))\n          /\\ isolate' e pnatoms (Lseg e0 e1 :: sigma0) sigma nextv (S N) =Some results)\n    \\/ isolate' e pnatoms (Lseg e0 e1 :: sigma0) sigma nextv N = Some results).\nProof.\nsimpl; intros; revert H.\ncase_eq (oracle\n      (Entailment (Assertion pnatoms (rev sigma0 ++ Lseg e0 e1 :: sigma))\n         (Assertion [Equ e e0, Nequ e0 e1] (rev sigma0 ++ Lseg e0 e1 :: sigma)))); intros.\napply oracle_sound in H.\ninv H0.\nleft; auto.\nrevert H0;\n case_eq (oracle\n           (Entailment\n              (Assertion pnatoms (rev sigma0 ++ Lseg e0 e1 :: sigma))\n              (Assertion [Equ e e0] (rev sigma0 ++ Lseg e0 e1 :: sigma)))); simpl; intros.\napply oracle_sound in H0.\nright; left; auto.\nright; right; auto.\nQed.\n\nLemma if_bool_e:\n  forall {A: Type} (b: bool) (c d e: A),\n     (if b then c else d) = e ->\n     b=true /\\ c=e \\/ b=false /\\ d=e.\nProof.\ndestruct b; auto.\nQed.\n\nLemma isolate_Next1:\n forall e e1 sigma nextv nextv2 pnatoms sigma0\n    (LT: Ident.lt nextv nextv2),\n    fresh freshmax_assertion\n       (Assertion pnatoms (rev sigma0 ++ Next e e1 :: sigma)) nextv ->\n  (assertion_denote (Assertion pnatoms (rev sigma0 ++ Next e e1 :: sigma))\n     |-- fold_right (fun P : assertion => orp (existsv nextv (assertion_denote P))) FF\n       [Assertion pnatoms (Next e e1 :: rev sigma0 ++ sigma)]) /\\\n   (forall Q : assertion,\n      In Q [(Assertion pnatoms (Next e e1 :: rev sigma0 ++ sigma))] ->\n         match Q with\n           |Assertion _ (Next e0 _ :: _) => e=e0\n           | _ => False\n           end  /\\\n      fresh freshmax_assertion Q nextv2).\nProof.\nintros. rename H into H0.\nsplit.\nunfold fold_right, snd.\nrewrite or_FF.\neapply derives_trans ; [ | apply existsv_refl].\nrewrite (assertion_denote_permute pnatoms _ _ (permute_sigma0 _ _ _ )). trivial.\nintros.\nsimpl in H.\ndestruct H; try contradiction.\ninv H.\nsplit; auto.\ndo_fresh.\nQed.\n\nLemma isolate_Next2:\n  forall e e0 e1 sigma nextv nextv2 pnatoms sigma0\n  (FRESHe:  fresh freshmax_expr e nextv)\n  (LT: Ident.lt nextv nextv2),\n  entailment_denote\n     (Entailment (Assertion pnatoms (rev sigma0 ++ Next e0 e1 :: sigma))\n        (Assertion [Equ e e0] (rev sigma0 ++ Next e0 e1 :: sigma))) ->\n  fresh freshmax_assertion\n     (Assertion pnatoms (rev sigma0 ++ Next e0 e1 :: sigma)) nextv ->\n  (assertion_denote (Assertion pnatoms (rev sigma0 ++ Next e0 e1 :: sigma))\n   |-- fold_right (fun P : assertion => orp (existsv nextv (assertion_denote P))) FF\n         [Assertion pnatoms (Next e e1 :: rev sigma0 ++ sigma)]) /\\\n  (forall (Q : assertion),\n   In Q [Assertion pnatoms (Next e e1 :: rev sigma0 ++ sigma)] ->\n           match Q with\n           |Assertion _ (Next e0 _ :: _) => e=e0\n           | _ => False\n           end/\\\n   fresh freshmax_assertion Q nextv2).\nProof.\nintros.\nunfold fold_right, snd. rewrite or_FF.\nsplit.\nclear - H.\neapply derives_trans; [ | apply existsv_refl ].\napply derives_trans with (assertion_denote (Assertion (Equ e e0::pnatoms) (rev sigma0 ++ Next e e1 :: sigma))).\nintros s H1; generalize (H _ H1); intro.\nclear H; simpl  in *. destruct H0. split; auto.\nrepeat rewrite list_denote_separate in *.\nrewrite (@listd_prop pn_atom state pn_atom_denote).\nrewrite (@listd_prop pn_atom state pn_atom_denote) in H1.\ndestruct H1 as [? ?]; split; auto.\nrewrite (space_denote_permute _ _ (permute_sigma0 _ _ _)) in H0.\nrewrite (space_denote_permute _ _ (permute_sigma0 _ _ _)).\nforget (rev sigma0 ++ sigma) as sig.\nclear - H0 H.\nunfold space_denote in *.\nsimpl in *.\ndestruct H0 as [s1 [s2 [? [? ?]]]]; exists s1; exists s2; split3; auto.\ndestruct s,s1,s2; destruct H0 as [[? ?] ?]; simpl in *; subst.\nunfold var_eq in H.\nrepeat rewrite expr_denote_heap_ind with (h:=h0)(h':=h) in *.\nrewrite <- H in *.\napply H1.\nsimpl in H. unfold assertion_denote.\nintros s [_ ?].\nrewrite space_denote_permute with (l':= rev sigma0 ++ Next e e1 :: sigma); auto.\napply Permutation_sym; apply permute_sigma0.\nintros.\ndestruct H1; try contradiction.\nsubst Q.\nsplit; auto.\ndo_fresh.\nQed.\n\nLemma isolate_Lseg1: forall e e0 e1 sigma nextv nextv2 pnatoms sigma0\n  (FRESHe : fresh freshmax_expr e nextv)\n  (LT: Ident.lt nextv nextv2),\n   entailment_denote\n     (Entailment (Assertion pnatoms (rev sigma0 ++ Lseg e0 e1 :: sigma))\n        (Assertion [Equ e e0, Nequ e0 e1] (rev sigma0 ++ Lseg e0 e1 :: sigma))) ->\n   fresh freshmax_assertion\n     (Assertion pnatoms (rev sigma0 ++ Lseg e0 e1 :: sigma)) nextv ->\n   (assertion_denote (Assertion pnatoms (rev sigma0 ++ Lseg e0 e1 :: sigma))\n    |-- fold_right (fun P => orp (existsv nextv (assertion_denote P))) FF\n          [Assertion pnatoms (Next e (Var nextv) :: Lseg (Var nextv) e1 :: rev sigma0 ++ sigma)]) /\\\n   (forall Q : assertion,\n    In Q\n      [Assertion pnatoms (Next e (Var nextv) :: Lseg (Var nextv) e1 :: rev sigma0 ++ sigma)] ->\n        match Q with\n           |Assertion _ (Next e0 _ :: _) => e=e0\n           | _ => False\n           end /\\\n    fresh freshmax_assertion Q nextv2).\nProof.\nintros.\nsplit.\nassert (list_denote pn_atom_denote (@andp _ )\n         (space_denote (rev sigma0 ++ Lseg e0 e1 :: sigma)) pnatoms |--\n         e===e0 && neg (pn_atom_denote (Equ e0 e1))).\neapply derives_trans; try apply H. intros w [? [? ?]]; split; auto.\nclear H.\nintros s ?.\ngeneralize (H1 _ H); intros [? ?].\nunfold fold_right. unfold orp. left.\neapply Lseg_unfold_neq with e0; auto.\nintros.\nsimpl in H1. destruct H1; try contradiction.\nsubst.\nsplit; auto.\ndo_fresh.\nQed.\n\nLemma isolate'_sound:\n  forall e pnatoms sigma nextv nextv2 results\n  (LT: Ident.lt nextv nextv2),\n      isolate' e pnatoms nil sigma nextv 0 = Some results ->\n      fresh freshmax_expr e nextv ->\n      fresh freshmax_assertion (Assertion pnatoms sigma) nextv ->\n      assertion_denote (Assertion pnatoms sigma) |--\n        fold_right (fun P => orp (existsv nextv (assertion_denote P))) FF results /\\\n      (forall Q, In Q results ->\n            match Q with\n           |Assertion _ (Next e0 _ :: _) => e=e0\n           | _ => False\n           end /\\\n           fresh freshmax_assertion Q nextv2).\nProof.\nintros until 2. intro FRESHe; intros.\nassert (rev nil ++ sigma = sigma) by auto.\nremember (@nil space_atom) as sigma0.\nrewrite <- H1 in H0|-*.\nclear Heqsigma0 H1.\nremember O as N. clear HeqN.\nrevert pnatoms sigma0 results N H H0; induction sigma; intros.\n\n(* nil case *)\nrewrite <- app_nil_end in *;\nunfold isolate' in H.\napply exorcize_sound; auto.\ndestruct (lt_dec N 2) as [? | _];  [ inversion H | ].\ndestruct (incon (Assertion (Equ e Nil :: pnatoms) (rev sigma0))); inversion H; auto.\n\n(* cons case *)\nspecialize (IHsigma pnatoms (a::sigma0) results).\ndestruct a.\n\n(* 'Next' case *)\nsimpl in H.\nif_tac in H.\nclear IHsigma.\nsubst e0.\ninv H.\napply isolate_Next1; auto.\n\nrevert H; case_eq (oracle\n          (Entailment\n             (Assertion pnatoms (rev sigma0 ++ Next e0 e1 :: sigma))\n             (Assertion [Equ e e0] (rev sigma0 ++ Next e0 e1 :: sigma))));\n     intros; inv H2; [|clear H].\napply isolate_Next2; auto; apply oracle_sound; auto.\n\nspecialize (IHsigma _ H4); clear H4.\ndestruct IHsigma.\nchange (rev (Next e0 e1 :: sigma0)) with (rev sigma0 ++ [Next e0 e1]).\nrewrite app_ass. apply H0.\nsplit; auto.\neapply derives_trans; try apply H.\nsimpl.\nrewrite app_ass. auto.\n\n(* 'Lseg' case *)\napply isolate_e in H.\ndestruct H as [[? ?] | [[? ?] | ?]].\nclear IHsigma.\nsubst.\napply isolate_Lseg1; auto.\n\nchange (rev (Lseg e0 e1 :: sigma0)) with (rev sigma0 ++ [Lseg e0 e1]) in *.\nrewrite app_ass in *.\nsimpl in *.\napply (IHsigma _ H1); auto.\n\nchange (rev (Lseg e0 e1 :: sigma0)) with (rev sigma0 ++ [Lseg e0 e1]) in *.\nrewrite app_ass in IHsigma.\napply (IHsigma _ H); auto.\nQed.\n\nLemma isolate_sound:\n  forall e P nextv nextv2 results\n      (LT: Ident.lt nextv nextv2),\n      isolate e P nextv = Some results ->\n       fresh freshmax_expr e nextv ->\n       fresh freshmax_assertion P nextv ->\n      assertion_denote P |--\n        fold_right (fun P => orp (existsv nextv (assertion_denote P))) FF results /\\\n      forall Q, In Q results ->\n            match Q with\n           |Assertion _ (Next e0 _ :: _) => e=e0\n           | _ => False\n           end /\\\n           fresh freshmax_assertion Q nextv2.\nProof.\nunfold isolate; destruct P; intros.\napply isolate'_sound with (nextv2:=nextv2) in H; auto.\nQed.\n\nEnd Iso_Sound.", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/veristar/isolate_sound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.25146202984178256}}
{"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 O E Eprime P A B C D A1 B1 C1 D1 C1prime M D1prime N : Universe, ((wd_ O E /\\ (wd_ P B /\\ (wd_ A B /\\ (wd_ O M /\\ (wd_ M C1 /\\ (wd_ C A /\\ (wd_ P A /\\ (wd_ C1 C1prime /\\ (wd_ O C1prime /\\ (wd_ O C1 /\\ (wd_ E Eprime /\\ (wd_ O Eprime /\\ (wd_ P C /\\ (wd_ C1prime A1 /\\ (wd_ O A1 /\\ (wd_ O B1 /\\ (wd_ M C1prime /\\ (wd_ N O /\\ (wd_ D1 N /\\ (wd_ D1 D1prime /\\ (wd_ N D1prime /\\ (wd_ D1prime O /\\ (wd_ O D1 /\\ (wd_ P D /\\ (wd_ A1 Eprime /\\ (wd_ D1prime B1 /\\ (wd_ D B /\\ (col_ P A B /\\ (col_ P C D /\\ (col_ O E A1 /\\ (col_ O E B1 /\\ (col_ O E C1 /\\ (col_ O E D1 /\\ (col_ O M N /\\ (col_ N D1 D1prime /\\ (col_ M C1 C1prime /\\ (col_ O C1prime D1prime /\\ (col_ O A1 C1 /\\ col_ O C1 D1)))))))))))))))))))))))))))))))))))))) -> col_ O C1 B1)).\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_1428.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.2514077149337275}}
{"text": "(* Narjes Jomaa and David Nowak, \n   Pip code refactored by Mohamed Sami Cherif *)\nRequire Import Lib Pip_state Pip_stateLib Pip_Prop  Pip_DependentTypeLemmas Pip_InternalLemmas.\nRequire Import List Coq.Logic.ProofIrrelevance Omega List Bool Classical_Prop.\nImport List.ListNotations. \n\nLemma removeDupIdentity  (l :  list (paddr * value)) : \nforall table1 idx1 table2 idx2 , table1 <> table2 \\/ idx1 <> idx2 -> \nlookup table1 idx1 (removeDup table2 idx2 l  beqPage beqIndex) beqPage beqIndex = \nlookup table1 idx1 l beqPage beqIndex.\nProof.\nintros.\ninduction l.\nsimpl. trivial.\nsimpl.\ndestruct a.\ndestruct p.\napply beqPairsFalse in H.\n+ case_eq (beqPairs (p, i) (table2, idx2) beqPage beqIndex).\n  - intros.\n    unfold beqPairs in H0. cbn in H0.\n    case_eq (beqPage p table2 && beqIndex i idx2 ).\n    * intros.\n      rewrite H1 in H0.\n      unfold beqPage , beqIndex in H1.\n      apply andb_true_iff in H1.\n      destruct H1.\n      apply beq_nat_true in H1.\n      apply beq_nat_true in H2.\n      assert (beqPairs (p, i) (table1, idx1) beqPage beqIndex = false).\n      { destruct p, i, table2, table1, idx2, idx1. simpl in *.\n      subst.\n      assert (Hp = Hp0). apply proof_irrelevance. subst. \n      assert(Hi = Hi0).  apply proof_irrelevance. subst.\n      unfold beqPairs in *. cbn in *.\n      \n      rewrite NPeano.Nat.eqb_sym.\n      replace (i0 =? i1) with (i1 =? i0). assumption.\n      rewrite NPeano.Nat.eqb_sym . trivial. }\n      rewrite H3. assumption.\n    * intros. rewrite H1 in H0.\n      contradict H0. auto.\n  - intros. simpl. \n    case_eq (beqPairs (p, i) (table1, idx1) beqPage beqIndex).\n    intros. trivial.\n    intros. assumption.   \nQed.\n\n\nLemma getConfigTablesLinkedListUpdateSh2 partition (vaInParent : vaddr) \ntable idx (s : state) entry :\nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\ngetConfigTablesLinkedList partition\n  (add table idx (VA vaInParent) (memory s) beqPage beqIndex) =\ngetConfigTablesLinkedList partition (memory s).\nProof.\nsimpl.\nintros Hentry.\nunfold getConfigTablesLinkedList.\ncase_eq ( succIndexInternal sh3idx ); intros; trivial.\ncbn.\nunfold readPhysical. \ncbn. \ncase_eq (beqPairs (table, idx) (partition, i) beqPage beqIndex);trivial;intros Hpairs.\n + apply beqPairsTrue in Hpairs.\n   destruct Hpairs as (Htable & Hidx).  subst.\n   rewrite Hentry.\n   trivial.\n + apply beqPairsFalse in Hpairs.\n   assert (lookup  partition i (removeDup table idx (memory s) beqPage beqIndex)\n           beqPage beqIndex = lookup  partition i   (memory s) beqPage beqIndex) as Hmemory.\n   { apply removeDupIdentity. intuition. }\n     rewrite Hmemory. reflexivity.\nQed.\n\nLemma getFstShadowUpdateSh2 partition (vaInParent : vaddr) \ntable idx (s : state) entry :\nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\ngetFstShadow partition\n  (add table idx (VA vaInParent) (memory s) beqPage beqIndex) =\ngetFstShadow partition (memory s).\nProof.\nsimpl.\nintros Hentry.\nunfold getFstShadow.\ncase_eq ( succIndexInternal sh1idx ); intros; trivial.\ncbn.\nunfold readPhysical. \ncbn. \ncase_eq (beqPairs (table, idx) (partition, i) beqPage beqIndex);trivial;intros Hpairs.\n + apply beqPairsTrue in Hpairs.\n   destruct Hpairs as (Htable & Hidx).  subst.\n   rewrite Hentry.\n   trivial.\n + apply beqPairsFalse in Hpairs.\n   assert (lookup  partition i (removeDup table idx (memory s) beqPage beqIndex)\n           beqPage beqIndex = lookup  partition i   (memory s) beqPage beqIndex) as Hmemory.\n   { apply removeDupIdentity. intuition. }\n     rewrite Hmemory. reflexivity.\nQed.\n\nLemma getSndShadowUpdateSh2 partition (vaInParent : vaddr) \ntable idx (s : state) entry :\nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\ngetSndShadow partition\n  (add table idx (VA vaInParent) (memory s) beqPage beqIndex) =\ngetSndShadow partition (memory s).\nProof.\nsimpl.\nintros Hentry.\nunfold getSndShadow.\ncase_eq ( succIndexInternal sh2idx ); intros; trivial.\ncbn.\nunfold readPhysical. \ncbn. \ncase_eq (beqPairs (table, idx) (partition, i) beqPage beqIndex);trivial;intros Hpairs.\n + apply beqPairsTrue in Hpairs.\n   destruct Hpairs as (Htable & Hidx).  subst.\n   rewrite Hentry.\n   trivial.\n + apply beqPairsFalse in Hpairs.\n   assert (lookup  partition i (removeDup table idx (memory s) beqPage beqIndex)\n           beqPage beqIndex = lookup  partition i   (memory s) beqPage beqIndex) as Hmemory.\n   { apply removeDupIdentity. intuition. }\n     rewrite Hmemory. reflexivity.\nQed.\n\nLemma getPdUpdateSh2 partition (vaInParent : vaddr) \ntable idx (s : state) entry :\nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\ngetPd partition\n  (add table idx (VA vaInParent) (memory s) beqPage beqIndex) =\ngetPd partition (memory s).\nProof.\nsimpl.\nintros Hentry.\nunfold getPd.\ncase_eq ( succIndexInternal PDidx ); intros; trivial.\ncbn.\nunfold readPhysical. \ncbn. \ncase_eq (beqPairs (table, idx) (partition, i) beqPage beqIndex);trivial;intros Hpairs.\n + apply beqPairsTrue in Hpairs.\n   destruct Hpairs as (Htable & Hidx).  subst.\n   rewrite Hentry.\n   trivial.\n + apply beqPairsFalse in Hpairs.\n   assert (lookup  partition i (removeDup table idx (memory s) beqPage beqIndex)\n           beqPage beqIndex = lookup  partition i   (memory s) beqPage beqIndex) as Hmemory.\n   { apply removeDupIdentity. intuition. }\n     rewrite Hmemory. reflexivity.\nQed.\nLemma getParentUpdateSh2 partition (vaInParent : vaddr) \ntable idx (s : state) entry :\nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\ngetParent partition\n  (add table idx (VA vaInParent) (memory s) beqPage beqIndex) =\ngetParent partition (memory s).\nProof.\nsimpl.\nintros Hentry.\nunfold getParent.\ncase_eq ( succIndexInternal PPRidx ); intros; trivial.\ncbn.\nunfold readPhysical. \ncbn. \ncase_eq (beqPairs (table, idx) (partition, i) beqPage beqIndex);trivial;intros Hpairs.\n + apply beqPairsTrue in Hpairs.\n   destruct Hpairs as (Htable & Hidx).  subst.\n   rewrite Hentry.\n   trivial.\n + apply beqPairsFalse in Hpairs.\n   assert (lookup  partition i (removeDup table idx (memory s) beqPage beqIndex)\n           beqPage beqIndex = lookup  partition i   (memory s) beqPage beqIndex) as Hmemory.\n   { apply removeDupIdentity. intuition. }\n     rewrite Hmemory. reflexivity.\nQed.\n\n\nLemma getTablePagesUpdateSh2   (descChild : vaddr) table idx entry size p (s : state)  vaInCurrentPartition:\nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) -> \ngetTablePages p size\n {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |} =\ngetTablePages p size s.\nProof.\nrevert p .\nset (s' :=   {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}).\ninduction size;\nintros;  trivial.\nsimpl.\ncase_eq(beqPairs (table, idx) (p, CIndex size) beqPage beqIndex);intros Hpairs.\n+ apply beqPairsTrue in Hpairs.\n  destruct Hpairs as (Htable & Hidx).\n  subst.\n  rewrite H.\n  apply IHsize;trivial.\n+ apply beqPairsFalse in Hpairs.\n  assert (lookup   p (CIndex size) (removeDup table idx (memory s) beqPage beqIndex)\n           beqPage beqIndex = lookup  p (CIndex size) (memory s) beqPage beqIndex) as Hmemory.\n   { apply removeDupIdentity. subst.  intuition. }\n  rewrite  Hmemory. \n  destruct (lookup p (CIndex size) (memory s) beqPage beqIndex); \n  [ |apply IHsize; trivial].\n  destruct v; try apply IHsize; trivial.\n  apply IHsize with p in H.\n  rewrite H.\n  reflexivity.\nQed.\n\nLemma getIndirectionsUpdateSh2  (descChild : vaddr) table idx entry pd (s : state) vaInCurrentPartition:\nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->  \ngetIndirections pd\n  {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}  =\ngetIndirections pd s.\nProof.\nintros Hentry.\nunfold getIndirections.\nrevert pd.\ninduction nbLevel.\nsimpl. trivial. simpl.\nintros. f_equal.\nassert (getTablePages pd tableSize {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}= getTablePages pd tableSize s) as Htablepages.\napply getTablePagesUpdateSh2 with entry ;trivial.\nrewrite Htablepages.\nclear Htablepages.\ninduction (getTablePages pd tableSize s); intros; trivial.\nsimpl in *.\nrewrite IHn. \nf_equal.\napply IHl.\nQed.\n\nLemma readPhysicalUpdateSh2 (descChild : vaddr) \ntable idx (s : state)  p idx2  entry vaInCurrentPartition: \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) -> \nreadPhysical p idx2\n  (add table idx (VA vaInCurrentPartition) (memory s) beqPage beqIndex) =\nreadPhysical p idx2 (memory s).\nProof.\nintros Hentry.\nunfold readPhysical.\ncbn.\ncase_eq( beqPairs (table, idx) (p, idx2) beqPage beqIndex); intros.\napply beqPairsTrue in H.\ndestruct H; subst.\nrewrite Hentry; trivial.\napply beqPairsFalse in H.\nassert(Hmemory : lookup p idx2 (removeDup table idx (memory s) beqPage beqIndex) beqPage beqIndex = \n lookup p idx2 (memory s) beqPage beqIndex ); intros.\n { apply removeDupIdentity ; intuition. }\nrewrite Hmemory; reflexivity.\nQed.\n\nLemma getConfigTablesLinkedListsUpdateSh2 sh3  (descChild : vaddr) table idx entry\n (s : state) vaInCurrentPartition:\nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) -> \ngetTrdShadows sh3\n {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |} (nbPage+1) =\ngetTrdShadows sh3 s (nbPage+1).\nProof.\nrevert sh3.\ninduction (nbPage+1);trivial.\nintros. simpl.\n set (s' :=   {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |} ) in *.\ndestruct (getMaxIndex);trivial.\nassert(HreadPhyEnt :  readPhysical sh3 i\n    (add table idx (VA vaInCurrentPartition) (memory s) beqPage beqIndex) = \n    readPhysical sh3 i (memory s) ).\napply readPhysicalUpdateSh2 with entry;trivial.\nrewrite HreadPhyEnt.\ndestruct (readPhysical sh3 i (memory s));trivial.\ndestruct (p =? defaultPage) ;trivial.\nf_equal.\napply IHn; trivial.\nQed. \n\nLemma getConfigPagesUpdateSh2 s vaInCurrentPartition table idx entry: \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nforall part : page, getConfigPages part {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}  = getConfigPages part s.\nProof.\nintros.\nunfold getConfigPages. \nf_equal.\nset(s':=  {|\n  currentPartition := currentPartition s;\n  memory := add table idx (VA vaInCurrentPartition) (memory s)\n              beqPage beqIndex |}) in *.\nunfold getConfigPagesAux.\nassert(Hgetpd: getPd part (memory s') = getPd part (memory s)).\n{ simpl. apply getPdUpdateSh2 with entry;trivial. }\nrewrite Hgetpd. clear Hgetpd.\ncase_eq(getPd part (memory s));intros; trivial.\nassert(Hgetsh1: getFstShadow part (memory s') = getFstShadow part (memory s)).\n{ simpl. apply getFstShadowUpdateSh2 with entry;trivial. }\nrewrite Hgetsh1. clear Hgetsh1.\ncase_eq(getFstShadow part (memory s));intros; trivial.\nassert(Hgetsh2: getSndShadow part (memory s') = getSndShadow part (memory s)).\n{ simpl. apply getSndShadowUpdateSh2 with entry;trivial. }\nrewrite Hgetsh2. clear Hgetsh2.\ncase_eq(getSndShadow part (memory s));intros; trivial.\nassert(Hgetconfig: getConfigTablesLinkedList part (memory s') =\n getConfigTablesLinkedList part (memory s)).\n{ simpl. apply getConfigTablesLinkedListUpdateSh2 with entry;trivial. }\nrewrite Hgetconfig. clear Hgetconfig.\ncase_eq(getConfigTablesLinkedList part (memory s));intros; trivial.\nsimpl.\nassert(Hind : forall root, getIndirections root s' = getIndirections root s).\n{ intros.  \n  apply getIndirectionsUpdateSh2 with entry;trivial. }\ndo 3 rewrite Hind.\ndo 3 f_equal.\napply getConfigTablesLinkedListsUpdateSh2 with entry;trivial.\nQed.\n\n\nLemma getIndirectionUpdateSh2 sh1 table idx s entry va nbL stop vaInCurrentPartition:\nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\ngetIndirection sh1 va nbL stop\n  {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |} =\ngetIndirection sh1 va nbL stop s .\nProof.\nintros Hentry.\nrevert sh1 nbL.\ninduction  stop.\n+ simpl. trivial.\n+ simpl. intros. \n  destruct (Level.eqb nbL fstLevel);trivial.\n  set (entry0 := (VA vaInCurrentPartition)  ) in *.\n  simpl.\n  assert ( readPhyEntry sh1 (getIndexOfAddr va nbL)\n                  (add table idx entry0 (memory s) beqPage beqIndex) = \n           readPhyEntry sh1 (getIndexOfAddr va nbL) (memory s)) as HreadPhyEnt.\n  { unfold readPhyEntry.\n    cbn.  \n    case_eq ( beqPairs (table, idx) (sh1, getIndexOfAddr va nbL) beqPage beqIndex);trivial;intros Hpairs.\n    + apply beqPairsTrue in Hpairs.\n    \n      destruct Hpairs as (Htable & Hidx).  subst.\n      rewrite Hentry. \n      cbn. trivial.\n    + apply beqPairsFalse in Hpairs.\n      assert (lookup sh1 (getIndexOfAddr va nbL)\n                 (removeDup table idx (memory s) beqPage beqIndex) beqPage beqIndex = \n              lookup sh1 (getIndexOfAddr va nbL) (memory s) beqPage beqIndex) as Hmemory.\n        { apply removeDupIdentity. subst.  intuition. }\n      rewrite Hmemory. reflexivity.\n   } \n  rewrite HreadPhyEnt.\n  destruct (readPhyEntry sh1 (getIndexOfAddr va nbL) (memory s) );trivial.\n  destruct (defaultPage =? p);trivial.\n  destruct ( Level.pred nbL );trivial.\nQed.\n\nLemma readPresentUpdateSh2  idx1\ntable idx (s : state)  p   entry vaInCurrentPartition: \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) -> \nreadPresent p idx1\n  (add table idx (VA vaInCurrentPartition) (memory s) beqPage beqIndex) =\nreadPresent p idx1 (memory s).\nProof.\nintros Hentry.\nunfold readPresent.\ncbn.\ncase_eq( beqPairs (table, idx) (p, idx1) beqPage beqIndex); intros.\napply beqPairsTrue in H.\ndestruct H; subst.\nrewrite Hentry; trivial.\napply beqPairsFalse in H.\nassert(Hmemory : lookup p idx1 (removeDup table idx (memory s) beqPage beqIndex) beqPage beqIndex = \n lookup p idx1 (memory s) beqPage beqIndex ); intros.\n { apply removeDupIdentity ; intuition. }\nrewrite Hmemory; reflexivity.\nQed.\n\nLemma readAccessibleUpdateSh2 \ntable idx (s : state)  p  idx1 entry vaInCurrentPartition: \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) -> \nreadAccessible p idx1\n  (add table idx (VA vaInCurrentPartition) (memory s) beqPage beqIndex) =\nreadAccessible p idx1 (memory s).\nProof.\nintros Hentry.\nunfold readAccessible.\ncbn.\ncase_eq( beqPairs (table, idx) (p, idx1) beqPage beqIndex); intros.\napply beqPairsTrue in H.\ndestruct H; subst.\nrewrite Hentry; trivial.\napply beqPairsFalse in H.\nassert(Hmemory : lookup p idx1 (removeDup table idx (memory s) beqPage beqIndex) beqPage beqIndex = \n lookup p idx1 (memory s) beqPage beqIndex ); intros.\n { apply removeDupIdentity ; intuition. }\nrewrite Hmemory; reflexivity.\nQed.\n\nLemma readPhyEntryUpdateSh2 \ntable idx (s : state)  p  idx1 entry vaInCurrentPartition: \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) -> \nreadPhyEntry p idx1\n  (add table idx (VA vaInCurrentPartition) (memory s) beqPage beqIndex) =\nreadPhyEntry p idx1 (memory s).\nProof.\nintros Hentry.\nunfold readPhyEntry.\ncbn.\ncase_eq( beqPairs (table, idx) (p, idx1) beqPage beqIndex); intros.\napply beqPairsTrue in H.\ndestruct H; subst.\nrewrite Hentry; trivial.\napply beqPairsFalse in H.\nassert(Hmemory : lookup p idx1 (removeDup table idx (memory s) beqPage beqIndex) beqPage beqIndex = \n lookup p idx1 (memory s) beqPage beqIndex ); intros.\n { apply removeDupIdentity ; intuition. }\nrewrite Hmemory; reflexivity.\nQed.\n\nLemma readVirEntryUpdateSh2 \ntable idx (s : state)  p  idx1 entry vaInCurrentPartition: \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) -> \nreadVirEntry p idx1\n  (add table idx (VA vaInCurrentPartition) (memory s) beqPage beqIndex) =\nreadVirEntry p idx1 (memory s).\nProof.\nintros Hentry.\nunfold readVirEntry.\ncbn.\ncase_eq( beqPairs (table, idx) (p, idx1) beqPage beqIndex); intros.\napply beqPairsTrue in H.\ndestruct H; subst.\nrewrite Hentry; trivial.\napply beqPairsFalse in H.\nassert(Hmemory : lookup p idx1 (removeDup table idx (memory s) beqPage beqIndex) beqPage beqIndex = \n lookup p idx1 (memory s) beqPage beqIndex ); intros.\n { apply removeDupIdentity ; intuition. }\nrewrite Hmemory; reflexivity.\nQed.\n\nLemma readPDflagUpdateSh2 idx1\ntable idx (s : state)  p   entry vaInCurrentPartition: \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) -> \nreadPDflag p idx1\n    (add table idx (VA vaInCurrentPartition) (memory s) beqPage beqIndex) =\n   readPDflag p idx1 (memory s).\nProof.\nintros Hentry.\nunfold readPDflag.\ncbn.\ncase_eq( beqPairs (table, idx) (p, idx1) beqPage beqIndex); intros.\napply beqPairsTrue in H.\ndestruct H; subst.\nrewrite Hentry; trivial.\napply beqPairsFalse in H.\nassert(Hmemory : lookup p idx1 (removeDup table idx (memory s) beqPage beqIndex) beqPage beqIndex = \n lookup p idx1 (memory s) beqPage beqIndex ); intros.\n { apply removeDupIdentity ; intuition. }\nrewrite Hmemory; reflexivity.\nQed.\n\nLemma getMappedPageUpdateSh2 root s vaInCurrentPartition table idx va entry:\nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\ngetMappedPage root {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}  va = getMappedPage root s va.\nProof.\nset (s':= {|\n  currentPartition := currentPartition s;\n  memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n              beqIndex |}) in *.\nintros Hentry. \nunfold getMappedPage.\ndestruct(getNbLevel);intros;trivial.\nassert(Hind : getIndirection root va l (nbLevel - 1) s' =\ngetIndirection root va l (nbLevel - 1) s).\napply getIndirectionUpdateSh2 with entry;trivial.\nrewrite Hind.  \ndestruct(getIndirection root va l (nbLevel - 1)  s); intros; trivial.\ndestruct(defaultPage =? p);trivial.\n assert(Hpresent :    readPresent p (getIndexOfAddr va fstLevel)\n  (memory s) = readPresent p (getIndexOfAddr va fstLevel)\n    (add table idx (VA vaInCurrentPartition) (memory s) beqPage beqIndex) ).\nsymmetry.\napply readPresentUpdateSh2 with entry; trivial.\nunfold s'. simpl.\nrewrite <- Hpresent.\ndestruct(readPresent p (getIndexOfAddr va fstLevel) (memory s) ); trivial.\ndestruct b; trivial.\napply readPhyEntryUpdateSh2 with entry; trivial .\nQed.\n\nLemma getAccessibleMappedPageUpdateSh2 root s vaInCurrentPartition table idx va entry:\nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\ngetAccessibleMappedPage root {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}  va = getAccessibleMappedPage root s va.\nProof.\nset (s':= {|\n  currentPartition := currentPartition s;\n  memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n              beqIndex |}) in *.\nintros Hentry. \nunfold getAccessibleMappedPage.\ndestruct(getNbLevel);intros;trivial.\nassert(Hind : getIndirection root va l (nbLevel - 1) s' =\ngetIndirection root va l (nbLevel - 1) s).\napply getIndirectionUpdateSh2 with entry;trivial.\nrewrite Hind.  \ndestruct(getIndirection root va l (nbLevel - 1)  s); intros; trivial.\ndestruct(defaultPage =? p);trivial.\n assert(Hpresent :    readPresent p (getIndexOfAddr va fstLevel)\n  (memory s) = readPresent p (getIndexOfAddr va fstLevel)\n    (add table idx (VA vaInCurrentPartition) (memory s) beqPage beqIndex) ).\nsymmetry.\napply readPresentUpdateSh2 with entry; trivial.\nunfold s'. simpl.\nrewrite <- Hpresent.\ndestruct(readPresent p (getIndexOfAddr va fstLevel) (memory s) ); trivial.\ndestruct b; trivial.\nassert(Haccess :    readAccessible p (getIndexOfAddr va fstLevel)\n  (memory s) = readAccessible p (getIndexOfAddr va fstLevel)\n    (add table idx (VA vaInCurrentPartition) (memory s) beqPage beqIndex) ).\nsymmetry.\napply readAccessibleUpdateSh2 with entry; trivial.\nunfold s'. simpl.\nrewrite <- Haccess.\ndestruct(readAccessible p (getIndexOfAddr va fstLevel) (memory s) ); trivial.\ndestruct b; trivial.\napply readPhyEntryUpdateSh2 with entry; trivial .\nQed.\n\nLemma getMappedPagesAuxUpdateSh2 root s vaInCurrentPartition table idx entry l:\nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\ngetMappedPagesAux root l {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |} = \ngetMappedPagesAux root l s.\nProof.\nintros Hentry.\nset (s':= {|\n  currentPartition := currentPartition s;\n  memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n              beqIndex |}) in *.\nunfold getMappedPagesAux.\nf_equal.\nunfold getMappedPagesOption.\nsimpl.\ninduction l.\nsimpl;trivial.\nsimpl. \nrewrite IHl;f_equal.\napply getMappedPageUpdateSh2 with entry; trivial.\nQed.\n\n\nLemma getAccessibleMappedPagesAuxUpdateSh2 root s vaInCurrentPartition table idx entry l:\nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\ngetAccessibleMappedPagesAux root l {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |} = \ngetAccessibleMappedPagesAux root l s.\nProof.\nintros Hentry.\nset (s':= {|\n  currentPartition := currentPartition s;\n  memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n              beqIndex |}) in *.\nunfold getAccessibleMappedPagesAux.\nf_equal.\nunfold getAccessibleMappedPagesOption.\nsimpl.\ninduction l.\nsimpl;trivial.\nsimpl. \nrewrite IHl;f_equal.\napply getAccessibleMappedPageUpdateSh2 with entry; trivial.\nQed.\n\nLemma getMappedPagesUpdateSh2 s vaInCurrentPartition table idx entry: \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nforall part : page, getMappedPages part {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}  = getMappedPages part s.\nProof.\nintros.\nunfold getMappedPages.\nset(s':=  {|\n  currentPartition := currentPartition s;\n  memory := add table idx (VA vaInCurrentPartition) (memory s)\n              beqPage beqIndex |}) in *.\nassert(Hgetpd: getPd part (memory s') = getPd part (memory s)).\n{ simpl. apply getPdUpdateSh2 with entry;trivial. }\nrewrite Hgetpd.\ncase_eq(getPd part (memory s));intros; trivial.\napply getMappedPagesAuxUpdateSh2 with entry;trivial.\nQed.\n\nLemma getAccessibleMappedPagesUpdateSh2 s vaInCurrentPartition table idx entry: \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nforall part : page,\ngetAccessibleMappedPages part {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}  = getAccessibleMappedPages part s.\nProof.\nintros.\nunfold getAccessibleMappedPages.\nset(s':=  {|\n  currentPartition := currentPartition s;\n  memory := add table idx (VA vaInCurrentPartition) (memory s)\n              beqPage beqIndex |}) in *.\nassert(Hgetpd: getPd part (memory s') = getPd part (memory s)).\n{ simpl. apply getPdUpdateSh2 with entry;trivial. }\nrewrite Hgetpd.\ncase_eq(getPd part (memory s));intros; trivial.\napply getAccessibleMappedPagesAuxUpdateSh2 with entry;trivial.\nQed.\n\nLemma checkChildUpdateSh2 s vaInCurrentPartition table idx entry l va: \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nforall part : page, \ncheckChild part l {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |} va = checkChild part l s va.\nProof.\nintros Hentry part.\nunfold checkChild.\nsimpl.\nassert(Hsh1 : getFstShadow part\n    (add table idx (VA vaInCurrentPartition) (memory s) beqPage beqIndex)=\n    getFstShadow part (memory s)). \napply getFstShadowUpdateSh2 with entry;trivial.\nrewrite Hsh1.\ndestruct(getFstShadow part (memory s) );trivial.\nassert(Hind : getIndirection p va l (nbLevel - 1)\n    {|\n    currentPartition := currentPartition s;\n    memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n                beqIndex |} = getIndirection p va l (nbLevel - 1)\n    s).\napply getIndirectionUpdateSh2 with entry;trivial.\nrewrite Hind.\ndestruct (getIndirection p va l (nbLevel - 1) s );trivial.\ndestruct (p0 =? defaultPage);trivial.\nassert(Hpdflag :  readPDflag p0 (getIndexOfAddr va fstLevel)\n    (add table idx (VA vaInCurrentPartition) (memory s) beqPage beqIndex) =\n   readPDflag p0 (getIndexOfAddr va fstLevel) (memory s)). \n  apply readPDflagUpdateSh2 with entry;trivial.\nrewrite Hpdflag.\ntrivial.\nQed.\n\nLemma getPdsVAddrUpdateSh2 s vaInCurrentPartition table idx entry l: \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nforall part : page, \n getPdsVAddr part l getAllVAddr {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}  = getPdsVAddr part l getAllVAddr s.\nProof.\nintros.\nunfold getPdsVAddr.\nset(s':=  {|\n  currentPartition := currentPartition s;\n  memory := add table idx (VA vaInCurrentPartition) (memory s)\n              beqPage beqIndex |}) in *.\ninduction getAllVAddr;simpl;trivial.\nassert(Hcheckchild: checkChild part l s' a = checkChild part l s a).\n{ simpl. apply checkChildUpdateSh2 with entry;trivial. }\nrewrite Hcheckchild;trivial.\ncase_eq(checkChild part l s a);intros;[\nf_equal|];\napply IHl0.\nQed.\n\nLemma getChildrenUpdateSh2 s vaInCurrentPartition table idx entry: \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) -> \nforall part : page,\ngetChildren part s = \ngetChildren part{|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}.\nProof.\nintros Hentry.\nunfold getChildren.\nset (s' := {|\n             currentPartition := currentPartition s;\n             memory := add table idx (VA vaInCurrentPartition) (memory s)\n                         beqPage beqIndex |}) in *.\nintros. \ndestruct ( getNbLevel);trivial.\nsimpl.\nassert(Hpd :  getPd part (memory s) =\ngetPd part\n    (add table idx (VA vaInCurrentPartition) (memory s) beqPage beqIndex)).\n{ symmetry.  apply getPdUpdateSh2 with entry;trivial. }\nrewrite <- Hpd.\ndestruct(getPd part (memory s));trivial.\nassert(Hpds : getPdsVAddr part l getAllVAddr s' = getPdsVAddr part l getAllVAddr s).\napply getPdsVAddrUpdateSh2 with entry;trivial.\nrewrite Hpds.\nunfold s'.\nsymmetry.\napply getMappedPagesAuxUpdateSh2 with entry;trivial.\nQed.\n\nLemma getPartitionsUpdateSh2 s vaInCurrentPartition table idx entry: \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) -> \ngetPartitions multiplexer s = getPartitions multiplexer{|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}. \nProof.\nintros.\ngeneralize multiplexer at 1 2.\nunfold getPartitions.\nset(s':=  {|\n  currentPartition := currentPartition s;\n  memory := add table idx (VA vaInCurrentPartition) (memory s)\n              beqPage beqIndex |}) in *.\ninduction (nbPage + 1);simpl;trivial.\nintros.\nf_equal.\nassert(Hchildren: getChildren p s' =getChildren p s).\n{ symmetry. apply getChildrenUpdateSh2 with entry;trivial. }\nrewrite Hchildren. clear Hchildren.\ninduction (getChildren p s);simpl;trivial.\nrewrite IHn.\nf_equal.\napply IHl.\nQed.\n\nLemma isVAUpdateSh2 idx partition table entry idxroot s vaInCurrentPartition:\nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nisVA partition idxroot s -> \nisVA partition idxroot\n  {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}.\nProof.\nintros Hentry.\nunfold isVA.\ncbn.\ncase_eq (beqPairs (table, idx) (partition, idxroot) beqPage beqIndex);trivial;intros Hpairs.\napply beqPairsFalse in Hpairs.\n   assert (lookup  partition idxroot (removeDup table idx (memory s) beqPage beqIndex)\n           beqPage beqIndex = lookup  partition idxroot   (memory s) beqPage beqIndex) as Hmemory.\n   { apply removeDupIdentity. intuition. }\n     rewrite Hmemory. trivial.\nQed.\n\nLemma nextEntryIsPPUpdateSh2 idx partition table  entry idxroot PPentry s vaInCurrentPartition:\nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nnextEntryIsPP partition idxroot PPentry s <-> \nnextEntryIsPP partition idxroot PPentry\n   {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}.\nProof.\nsplit;intros Hentry;\nunfold nextEntryIsPP in *;\ncbn;\ndestruct ( succIndexInternal idxroot); trivial.\n- case_eq (beqPairs (table, idx) (partition, i) beqPage beqIndex);trivial;intros Hpairs.\n   + apply beqPairsTrue in Hpairs.\n     destruct Hpairs as (Htable & Hidx).  subst.      \n     rewrite H in *.\n     trivial.\n   + apply beqPairsFalse in Hpairs.\n     assert (lookup  partition i (removeDup table idx (memory s) beqPage beqIndex)\n             beqPage beqIndex = lookup  partition i   (memory s) beqPage beqIndex) as Hmemory.\n     { apply removeDupIdentity. intuition. }\n       rewrite Hmemory. trivial.\n- cbn in *.\n  case_eq (beqPairs (table, idx) (partition, i) beqPage beqIndex);trivial;intros Hpairs.\n  + rewrite Hpairs in *; now contradict Hentry.\n  + rewrite Hpairs in *.\n    assert (lookup  partition i (removeDup table idx (memory s) beqPage beqIndex)\n           beqPage beqIndex = lookup  partition i   (memory s) beqPage beqIndex) as Hmemory.\n   { apply removeDupIdentity.  apply beqPairsFalse in Hpairs. intuition. }\n     rewrite Hmemory in *. trivial.     \nQed.\n\nLemma isPEUpdateSh2 idx partition table  entry idxroot s vaInCurrentPartition:\nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nisPE partition idxroot s -> \nisPE partition idxroot\n  {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}.\nProof.\nintros Hentry.\nunfold isPE.\ncbn.\ncase_eq (beqPairs (table, idx) (partition, idxroot) beqPage beqIndex);trivial;intros Hpairs.\n + apply beqPairsTrue in Hpairs.\n   destruct Hpairs as (Htable & Hidx).  subst.\n   rewrite Hentry.\n   trivial.\n + apply beqPairsFalse in Hpairs.\n   assert (lookup  partition idxroot (removeDup table idx (memory s) beqPage beqIndex)\n           beqPage beqIndex = lookup  partition idxroot   (memory s) beqPage beqIndex) as Hmemory.\n   { apply removeDupIdentity. intuition. }\n     rewrite Hmemory. trivial.\nQed.\n\nLemma isVEUpdateSh2 idx partition table  entry idxroot s vaInCurrentPartition:\nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nisVE partition idxroot s -> \nisVE partition idxroot\n  {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}.\nProof.\nintros Hentry.\nunfold isVE.\ncbn.\ncase_eq (beqPairs (table, idx) (partition, idxroot) beqPage beqIndex);trivial;intros Hpairs.\n + apply beqPairsTrue in Hpairs.\n   destruct Hpairs as (Htable & Hidx).  subst.\n   rewrite Hentry.\n   trivial.\n + apply beqPairsFalse in Hpairs.\n   assert (lookup  partition idxroot (removeDup table idx (memory s) beqPage beqIndex)\n           beqPage beqIndex = lookup  partition idxroot   (memory s) beqPage beqIndex) as Hmemory.\n   { apply removeDupIdentity. intuition. }\n     rewrite Hmemory. trivial.\nQed.\n\n\nLemma entryUserFlagUpdateSh2 idx ptVaInCurPartpd idxvaInCurPart table \n entry s vaInCurrentPartition accessiblesrc:\nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nentryUserFlag ptVaInCurPartpd idxvaInCurPart accessiblesrc s -> \nentryUserFlag ptVaInCurPartpd idxvaInCurPart accessiblesrc\n  {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}.\nProof.\nintros Hentry.\nunfold entryUserFlag.\ncbn.\ncase_eq (beqPairs (table, idx) (ptVaInCurPartpd, idxvaInCurPart) beqPage beqIndex);trivial;intros Hpairs.\n + apply beqPairsTrue in Hpairs.\n   destruct Hpairs as (Htable & Hidx).  subst.\n   rewrite Hentry.\n   trivial.\n + apply beqPairsFalse in Hpairs.\n   assert (lookup  ptVaInCurPartpd idxvaInCurPart (removeDup table idx (memory s) beqPage beqIndex)\n           beqPage beqIndex = lookup  ptVaInCurPartpd idxvaInCurPart   (memory s) beqPage beqIndex) as Hmemory.\n   { apply removeDupIdentity. intuition. }\n     rewrite Hmemory. trivial.\nQed.\n\nLemma entryPresentFlagUpdateSh2 idx ptVaInCurPartpd idxvaInCurPart table \n entry s vaInCurrentPartition accessiblesrc:\nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nentryPresentFlag ptVaInCurPartpd idxvaInCurPart accessiblesrc s -> \nentryPresentFlag ptVaInCurPartpd idxvaInCurPart accessiblesrc\n  {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}.\nProof.\nintros Hentry.\nunfold entryPresentFlag.\ncbn.\ncase_eq (beqPairs (table, idx) (ptVaInCurPartpd, idxvaInCurPart) beqPage beqIndex);trivial;intros Hpairs.\n + apply beqPairsTrue in Hpairs.\n   destruct Hpairs as (Htable & Hidx).  subst.\n   rewrite Hentry.\n   trivial.\n + apply beqPairsFalse in Hpairs.\n   assert (lookup  ptVaInCurPartpd idxvaInCurPart (removeDup table idx (memory s) beqPage beqIndex)\n           beqPage beqIndex = lookup  ptVaInCurPartpd idxvaInCurPart   (memory s) beqPage beqIndex) as Hmemory.\n   { apply removeDupIdentity. intuition. }\n     rewrite Hmemory. trivial.\nQed.\n\nLemma entryPDFlagUpdateSh2 idx ptDescChild table idxDescChild entry s vaInCurrentPartition flag:\nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nentryPDFlag ptDescChild idxDescChild flag s -> \nentryPDFlag ptDescChild idxDescChild flag\n  {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}.\nProof.\nintros Hentry.\nunfold entryPDFlag.\ncbn.\ncase_eq (beqPairs (table, idx) (ptDescChild, idxDescChild) beqPage beqIndex);trivial;intros Hpairs.\n + apply beqPairsTrue in Hpairs.\n   destruct Hpairs as (Htable & Hidx).  subst.\n   rewrite Hentry.\n   trivial.\n + apply beqPairsFalse in Hpairs.\n   assert (lookup  ptDescChild idxDescChild (removeDup table idx (memory s) beqPage beqIndex)\n           beqPage beqIndex = lookup  ptDescChild idxDescChild   (memory s) beqPage beqIndex) as Hmemory.\n   { apply removeDupIdentity. intuition. }\n     rewrite Hmemory. trivial.\nQed.\n\nLemma isEntryVAUpdateSh2 idx ptVaInCurPart table idxvaInCurPart entry s  vainve vaInCurrentPartition:\nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nisEntryVA ptVaInCurPart idxvaInCurPart vainve s -> \nisEntryVA ptVaInCurPart idxvaInCurPart vainve\n  {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}.\nProof.\nintros Hentry.\nunfold isEntryVA.\ncbn.\ncase_eq (beqPairs (table, idx) (ptVaInCurPart, idxvaInCurPart) beqPage beqIndex);trivial;intros Hpairs.\n + apply beqPairsTrue in Hpairs.\n   destruct Hpairs as (Htable & Hidx).  subst.\n   rewrite Hentry.\n   trivial.\n + apply beqPairsFalse in Hpairs.\n   assert (lookup  ptVaInCurPart idxvaInCurPart (removeDup table idx (memory s) beqPage beqIndex)\n           beqPage beqIndex = lookup  ptVaInCurPart idxvaInCurPart  (memory s) beqPage beqIndex) as Hmemory.\n   { apply removeDupIdentity. intuition. }\n     rewrite Hmemory. trivial.\nQed.\n\nLemma isEntryPageUpdateSh2 idx ptVaInCurPart table idxvaInCurPart entry s  vainve vaInCurrentPartition:\nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nisEntryPage ptVaInCurPart idxvaInCurPart vainve s -> \nisEntryPage ptVaInCurPart idxvaInCurPart vainve\n  {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}.\nProof.\nintros Hentry.\nunfold isEntryPage.\ncbn.\ncase_eq (beqPairs (table, idx) (ptVaInCurPart, idxvaInCurPart) beqPage beqIndex);trivial;intros Hpairs.\n + apply beqPairsTrue in Hpairs.\n   destruct Hpairs as (Htable & Hidx).  subst.\n   rewrite Hentry.\n   trivial.\n + apply beqPairsFalse in Hpairs.\n   assert (lookup  ptVaInCurPart idxvaInCurPart (removeDup table idx (memory s) beqPage beqIndex)\n           beqPage beqIndex = lookup  ptVaInCurPart idxvaInCurPart  (memory s) beqPage beqIndex) as Hmemory.\n   { apply removeDupIdentity. intuition. }\n     rewrite Hmemory. trivial.\nQed.\n\nLemma partitionsIsolationUpdateSh2 s vaInCurrentPartition table idx entry: \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\npartitionsIsolation s ->\npartitionsIsolation {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}. \nProof.\nintros Hlookup.\nset(s' :=  {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}) in *. \nunfold partitionsIsolation in *. \n  intros Hisopart parent child1 child2 Hparent Hchild1 Hchild2 Hdist.\n  assert (Hused : forall part, getUsedPages part s' = getUsedPages part s). \n  { intros. \n    unfold getUsedPages in *. \n    assert(Hconfig : forall part, getConfigPages part s' = getConfigPages part s).\n    { intros.\n      apply getConfigPagesUpdateSh2 with entry;trivial. } \n    rewrite Hconfig in *.\n    f_equal.\n    assert(Hmap :  forall part, getMappedPages part s' = getMappedPages part s).\n    { intros.\n      apply getMappedPagesUpdateSh2 with entry;trivial. } \n    rewrite Hmap in *;trivial. }\n    do 2 rewrite Hused.\n  assert(Hparts : getPartitions multiplexer s = getPartitions multiplexer s').\n  apply getPartitionsUpdateSh2 with entry;trivial.\n  rewrite Hparts in *;trivial.\n  assert(Hchildren : getChildren parent s = getChildren parent s').\n  apply getChildrenUpdateSh2 with entry;trivial.\n  rewrite <- Hchildren in *.\n  apply Hisopart with parent;trivial.\nQed.\n\nLemma kernelDataIsolationUpdateSh2 s vaInCurrentPartition table idx entry: \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nkernelDataIsolation s ->\nkernelDataIsolation {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}. \nProof.\nintros Hlookup.\nset(s' :=  {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}) in *. \nunfold kernelDataIsolation in *. \nintros Hkdi partition1 partition2 Hpart1 Hpart2.\nassert(Hparts : getPartitions multiplexer s = getPartitions multiplexer s').\napply getPartitionsUpdateSh2 with entry;trivial.\nrewrite <- Hparts in *;trivial. clear Hparts.\nassert(Hconfig : forall part, getConfigPages part s' = getConfigPages part s).\n{ intros.\napply getConfigPagesUpdateSh2 with entry;trivial. } \nrewrite Hconfig in *. clear Hconfig.\nassert(Haccessmap : forall part, getAccessibleMappedPages part s' =\ngetAccessibleMappedPages part s).\n{ apply getAccessibleMappedPagesUpdateSh2 with entry;trivial. }\nrewrite Haccessmap in *. \napply Hkdi;trivial.\nQed.  \n\nLemma verticalSharingUpdateSh2 s vaInCurrentPartition table idx entry: \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nverticalSharing s ->\nverticalSharing {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}. \nProof.\nintros Hlookup.\nset(s' :=  {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}) in *. \nunfold verticalSharing in *.\nintros Hvs parent child Hparent Hchild.\nassert(Hparts : getPartitions multiplexer s = getPartitions multiplexer s').\napply getPartitionsUpdateSh2 with entry;trivial.\nrewrite <- Hparts in *;trivial. clear Hparts.\nassert(Hchildren : getChildren parent s = getChildren parent s').\napply getChildrenUpdateSh2 with entry;trivial.\nrewrite <- Hchildren in *. clear Hchildren.\nassert(Hmap :  forall part, getMappedPages part s' = getMappedPages part s).\n{ intros.\n  apply getMappedPagesUpdateSh2 with entry;trivial. } \n  rewrite Hmap in *;trivial.\nassert (Hused : forall part, getUsedPages part s' = getUsedPages part s). \n{ intros. \n  unfold getUsedPages in *. \n  assert(Hconfig : forall part, getConfigPages part s' = getConfigPages part s).\n  { intros.\n    apply getConfigPagesUpdateSh2 with entry;trivial. } \n  rewrite Hconfig in *.\n  f_equal. trivial.  }\nrewrite Hused;trivial.\napply Hvs;trivial.\nQed.\n\nLemma partitionDescriptorEntryUpdateSh2 s vaInCurrentPartition table idx entry: \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\npartitionDescriptorEntry s ->\npartitionDescriptorEntry {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}. \nProof.\nintros Hlookup.\nset(s' :=  {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}) in *. \nunfold partitionDescriptorEntry in *. \nintros Hpde part Hpart idxroot Hidxroot.\nassert(Hidx : idxroot < tableSize - 1 ).\n{ assert(tableSizeLowerBound < tableSize).\n  apply tableSizeBigEnough.\n  unfold tableSizeLowerBound in *.\n  intuition subst.\n  unfold PDidx.\n  unfold CIndex.\n  case_eq( lt_dec 2 tableSize );intros;\n  simpl;omega.\n  unfold sh1idx.\n  unfold CIndex.\n  case_eq( lt_dec 4 tableSize );intros;\n  simpl;omega.\n   unfold sh2idx.\n  unfold CIndex.\n  case_eq( lt_dec 6 tableSize );intros;\n  simpl;omega.\n   unfold sh3idx.\n  unfold CIndex.\n  case_eq( lt_dec 8 tableSize );intros;\n  simpl;omega.\n  unfold PPRidx.\n  unfold CIndex.\n  case_eq( lt_dec 10 tableSize );intros;\n  simpl;omega.    \n  unfold PRidx.\n  unfold CIndex.\n  case_eq( lt_dec 0 tableSize );intros;\n  simpl;omega. }\nassert(Hparts : getPartitions multiplexer s = getPartitions multiplexer s').\napply getPartitionsUpdateSh2 with entry;trivial.\nrewrite <- Hparts in *;trivial. clear Hparts.\nassert (HVA : forall p idx, isVA p idx s -> isVA p idx s').\n{ intros.\n  apply  isVAUpdateSh2 with entry;trivial. }\nassert (HPE : forall p idx x, nextEntryIsPP p idx x s -> \n            nextEntryIsPP   p idx x s').\n{ intros. apply nextEntryIsPPUpdateSh2 with entry;trivial. }\nassert(Hconcl : idxroot < tableSize - 1 /\\\n       isVA part idxroot s /\\\n       (exists entry : page,\n          nextEntryIsPP part idxroot entry s /\\ entry <> defaultPage)).\napply Hpde;trivial.\ndestruct Hconcl as (Hi1 & Hi2 & Hi3).\nsplit;trivial.\nsplit.\napply HVA;trivial.\ndestruct Hi3 as (entry0 & Hentry & Htrue).\nexists entry0;split;trivial.\napply HPE;trivial.\nQed.\n\nLemma dataStructurePdSh1Sh2asRootUpdateSh2 s vaInCurrentPartition table idx entry idxroot: \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\ndataStructurePdSh1Sh2asRoot idxroot s ->\ndataStructurePdSh1Sh2asRoot idxroot {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}. \nProof.\nintros Hlookup.\nset(s' :=  {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}) in *. \nunfold dataStructurePdSh1Sh2asRoot in *.\nintros Hds.\nassert(Hpartitions : getPartitions multiplexer\n    s = \ngetPartitions multiplexer s').\napply getPartitionsUpdateSh2 with entry; trivial.\nrewrite Hpartitions in *; clear Hpartitions.\nunfold s' in *.\nintros.\nrewrite <- nextEntryIsPPUpdateSh2 in H0; try eassumption.\nassert (Hind : getIndirection entry0 va level stop s = Some indirection).\n{ rewrite <- H3. symmetry.\n  apply getIndirectionUpdateSh2 with entry; trivial. }\nclear H3.\nassert(Hdss :indirection = defaultPage \\/\n      (stop < level /\\ isPE indirection idx0 s \\/\n       stop >= level /\\\n       (isVE indirection idx0 s /\\ idxroot = sh1idx \\/\n        isVA indirection idx0 s /\\ idxroot = sh2idx \\/ isPE indirection idx0 s /\\ idxroot = PDidx)) /\\\n      indirection <> defaultPage).\napply Hds with partition entry0 va; trivial.\nclear Hds.\ndestruct Hdss as [Hds | Hds];[left;trivial|].\nright.\ndestruct Hds as (Hds & Hnotnull); split; trivial.\ndestruct Hds as [(Hlt & Hpe) | Hds].\n+ left; split; trivial.\n  apply isPEUpdateSh2 with entry; trivial.\n+ right.\n  destruct Hds as (Hlevel & [(Hve & Hidx) | [(Hva & Hidx) | (Hpe & Hidx)]]).\n  split; trivial.\n  - left; split; trivial.\n    apply isVEUpdateSh2 with entry; trivial.\n  - split; trivial.\n    right; left;split; trivial.\n    apply isVAUpdateSh2 with entry; trivial.\n  - split;trivial.\n    right;right; split; trivial.\n    apply isPEUpdateSh2 with entry; trivial.\nQed.\n\nLemma currentPartitionInPartitionsListUpdateSh2 s vaInCurrentPartition table idx entry : \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\ncurrentPartitionInPartitionsList s ->\ncurrentPartitionInPartitionsList {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}. \nProof.\nintros Hlookup.\nunfold currentPartitionInPartitionsList.\nintros; \nsimpl.\nassert(Hpartitions : getPartitions multiplexer\n    s = \ngetPartitions multiplexer {|\n     currentPartition := currentPartition s;\n     memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n                 beqIndex |}).\napply getPartitionsUpdateSh2 with entry; trivial.\nrewrite Hpartitions in *; clear Hpartitions;trivial.\nQed.\n\nLemma noDupMappedPagesListUpdateSh2 s vaInCurrentPartition table idx entry : \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nnoDupMappedPagesList s ->\nnoDupMappedPagesList {|\ncurrentPartition := currentPartition s;\nmemory := add table idx (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}. \nProof.\nintros Hlookup.\nunfold noDupMappedPagesList.\nintros; \nsimpl.\nassert(Hpartitions : getPartitions multiplexer\n    s = \ngetPartitions multiplexer {|\n     currentPartition := currentPartition s;\n     memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n                 beqIndex |}).\napply getPartitionsUpdateSh2 with entry; trivial.\nrewrite <- Hpartitions in *; clear Hpartitions;trivial.\nassert(Hmap :  forall part, getMappedPages part {|\n     currentPartition := currentPartition s;\n     memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n                 beqIndex |}= getMappedPages part s).\n{ intros.\n  apply getMappedPagesUpdateSh2 with entry;trivial. }\n  rewrite Hmap;trivial.\napply H;trivial.\nQed.\n\nLemma noDupConfigPagesListUpdateSh2 s vaInCurrentPartition table idx entry : \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nnoDupConfigPagesList s ->\nnoDupConfigPagesList\n  {|\n  currentPartition := currentPartition s;\n  memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n              beqIndex |}. \nProof.\nintros Hlookup.\nunfold noDupConfigPagesList.\nintros; \nsimpl.\nassert(Hpartitions : getPartitions multiplexer\n    s = \ngetPartitions multiplexer {|\n     currentPartition := currentPartition s;\n     memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n                 beqIndex |}).\napply getPartitionsUpdateSh2 with entry; trivial.\nrewrite <- Hpartitions in *; clear Hpartitions;trivial.\nassert(Hind :  forall part, getIndirections part {|\n     currentPartition := currentPartition s;\n     memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n                 beqIndex |}= getIndirections part s).\n{ intros.\n  apply getIndirectionsUpdateSh2 with entry;trivial. }\n  rewrite Hind;trivial.\napply H with idxroot partition;trivial.\nrewrite nextEntryIsPPUpdateSh2 with entry;trivial.\neapply H2.\neapply Hlookup.\nQed. \n\nLemma parentInPartitionListUpdateSh2 s vaInCurrentPartition table idx entry : \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nparentInPartitionList s ->\nparentInPartitionList\n  {|\n  currentPartition := currentPartition s;\n  memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n              beqIndex |}. \nProof.\nintros Hlookup.\nunfold parentInPartitionList.\nintros; \nsimpl.\nassert(Hpartitions : getPartitions multiplexer\n    s = \ngetPartitions multiplexer {|\n     currentPartition := currentPartition s;\n     memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n                 beqIndex |}).\napply getPartitionsUpdateSh2 with entry; trivial.\nrewrite <- Hpartitions in *; clear Hpartitions;trivial.\napply H with partition;trivial.\nrewrite nextEntryIsPPUpdateSh2 with entry;trivial.\neapply H1.\neapply Hlookup.\nQed. \n\nLemma getPDFlagUpdateSh2 s vaInCurrentPartition table idx entry sh1 va: \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\ngetPDFlag sh1 va\n  {|\n  currentPartition := currentPartition s;\n  memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n              beqIndex |} = getPDFlag sh1 va s.\nProof.\nintros Hentry.\nunfold getPDFlag.\nsimpl.\ndestruct (getNbLevel);trivial.\nassert(Hind : getIndirection sh1 va l (nbLevel - 1)\n    {|\n    currentPartition := currentPartition s;\n    memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n                beqIndex |} = getIndirection  sh1 va l (nbLevel - 1)\n    s).\napply getIndirectionUpdateSh2 with entry;trivial.\nrewrite Hind.\ndestruct (getIndirection  sh1 va l (nbLevel - 1) s );trivial.\ndestruct (p =? defaultPage);trivial.\nassert(Hpdflag :  readPDflag p (getIndexOfAddr va fstLevel)\n    (add table idx (VA vaInCurrentPartition) (memory s) beqPage beqIndex) =\n   readPDflag p (getIndexOfAddr va fstLevel) (memory s)). \n  apply readPDflagUpdateSh2 with entry;trivial.\nrewrite Hpdflag.\ntrivial.\nQed. \n\nLemma accessibleVAIsNotPartitionDescriptorUpdateSh2 s vaInCurrentPartition table idx entry : \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\naccessibleVAIsNotPartitionDescriptor s ->\naccessibleVAIsNotPartitionDescriptor\n  {|\n  currentPartition := currentPartition s;\n  memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n              beqIndex |}. \nProof.\nintros Hlookup.\nunfold accessibleVAIsNotPartitionDescriptor.\nintros; \nsimpl.\nassert(Hpartitions : getPartitions multiplexer\n    s = \ngetPartitions multiplexer {|\n     currentPartition := currentPartition s;\n     memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n                 beqIndex |}).\napply getPartitionsUpdateSh2 with entry; trivial.\nrewrite <- Hpartitions in *; clear Hpartitions;trivial.\nsimpl in *.\nassert(Haccessmap : forall part, getAccessibleMappedPage part {|\n       currentPartition := currentPartition s;\n       memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n                   beqIndex |} va =\ngetAccessibleMappedPage part s va).\n{ intros. apply getAccessibleMappedPageUpdateSh2 with entry;trivial. }\nrewrite Haccessmap in *. clear Haccessmap.\nassert(Hpd :  getPd partition (memory s) =\ngetPd partition\n    (add table idx (VA vaInCurrentPartition) (memory s) beqPage beqIndex)).\n{ symmetry.  apply getPdUpdateSh2 with entry;trivial. }\nrewrite <- Hpd in *.\nassert(Hsh1 :  getFstShadow partition (memory s) =\ngetFstShadow partition\n    (add table idx (VA vaInCurrentPartition) (memory s) beqPage beqIndex)).\n{ symmetry.  apply getFstShadowUpdateSh2 with entry;trivial. }\nrewrite <- Hsh1 in *.\nrewrite <- H with partition va pd sh1 page;trivial.\napply getPDFlagUpdateSh2 with entry;trivial.\nQed. \n\nLemma readVirtualUpdateSh2 table1 table2 idx1 idx2  vaInCurrentPartition s :\ntable1 <> table2 \\/ idx1 <> idx2 -> \n readVirtual table1 idx1\n         (add table2 idx2 (VA vaInCurrentPartition) (memory s) beqPage\n     beqIndex)  = \n readVirtual table1 idx1 (memory s).\nProof.\nunfold readVirtual.\ncbn.\nintros Hnoteq.\nassert(Hfalse : beqPairs (table2, idx2) (table1, idx1) beqPage beqIndex = false).\napply beqPairsFalse; intuition.\nrewrite Hfalse.\nassert(Hmemory : lookup table1 idx1 (removeDup table2 idx2 (memory s) beqPage beqIndex) \n          beqPage beqIndex =  lookup table1 idx1 (memory s) beqPage beqIndex ).\napply removeDupIdentity ; intuition.\nrewrite Hmemory.\ntrivial. \nQed.\n\nLemma accessibleChildPageIsAccessibleIntoParentUpdateSh2 s entry (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:\nisnotderiv && accessiblesrc && presentmap && negb presentvaChild = true -> \nnegb presentDescPhy = false -> \nlookup ptVaChildsh2 idxvaChild  (memory s) beqPage beqIndex = Some (VA entry) ->\npropagatedPropertiesAddVaddr 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 -> \naccessibleChildPageIsAccessibleIntoParent s ->\naccessibleChildPageIsAccessibleIntoParent\n  {|\n  currentPartition := currentPartition s;\n  memory := add ptVaChildsh2 idxvaChild  (VA vaInCurrentPartition) (memory s) beqPage\n              beqIndex |}. \nProof.\nintros Hlegit1 Hlegit Hlookup Hprops.\n\nunfold accessibleChildPageIsAccessibleIntoParent.\nintros; \nsimpl.\nassert(Hpartitions : getPartitions multiplexer\n    s = \ngetPartitions multiplexer {|\n     currentPartition := currentPartition s;\n     memory := add ptVaChildsh2 idxvaChild  (VA vaInCurrentPartition) (memory s) beqPage\n                 beqIndex |}).\napply getPartitionsUpdateSh2 with entry; trivial.\nrewrite <- Hpartitions in *; clear Hpartitions;trivial.\nsimpl in *.\nassert(Haccessmap : forall part, getAccessibleMappedPage part {|\n       currentPartition := currentPartition s;\n       memory := add ptVaChildsh2 idxvaChild (VA vaInCurrentPartition) (memory s) beqPage\n                   beqIndex |} va =\ngetAccessibleMappedPage part s va).\n{ intros. apply getAccessibleMappedPageUpdateSh2 with entry;trivial. }\nrewrite Haccessmap in *. clear Haccessmap.\nassert(Hpd :  getPd partition (memory s) =\ngetPd partition\n    (add ptVaChildsh2 idxvaChild  (VA vaInCurrentPartition) (memory s) beqPage beqIndex)).\n{ symmetry.  apply getPdUpdateSh2 with entry;trivial. }\nrewrite <- Hpd in *.\nclear Hpd.\nassert(Hor : partition = phyDescChild \\/ partition <> phyDescChild) by apply pageDecOrNot.\ndestruct Hor as [Hor | Hor];\nsubst.\n+ unfold propagatedPropertiesAddVaddr in *.\n  assert (Hpdeq : pdChildphy = pd). \n  { apply getPdNextEntryIsPPEq with phyDescChild s;trivial.\n    intuition. }\n  subst pd.\n  assert(Hor :checkVAddrsEqualityWOOffset nbLevel vaChild va level = true \\/ \n         checkVAddrsEqualityWOOffset nbLevel vaChild va level = false).\n  { destruct (checkVAddrsEqualityWOOffset nbLevel vaChild va level);intuition. }\n  destruct Hor as [Hor | Hor].\n  - assert(Hlastidx : (getIndexOfAddr vaChild fstLevel) = \n  (getIndexOfAddr va fstLevel)).\n    { apply checkVAddrsEqualityWOOffsetTrue' with nbLevel level; trivial.\n      unfold fstLevel.\n      unfold CLevel.\n      case_eq ( lt_dec 0 nbLevel );intros.\n      simpl.\n      omega.\n      assert(0<nbLevel) by apply nbLevelNotZero.\n      omega.\n      destruct level;simpl; omega. }\n  rewrite Hlastidx in *. \n  assert(Htrue : getAccessibleMappedPage pdChildphy s va = None).\n  { apply getAccessibleMappedPageNotPresent with ptVaChildpd phyDescChild;intuition.\n    + subst;trivial.\n    + assert(Hget : getTableAddrRoot ptVaChildpd PDidx phyDescChild vaChild s) by trivial.\n      unfold getTableAddrRoot in *.\n      destruct Hget as(Hi & Hget).\n      split;trivial.\n      intros tableroot Hpp.\n      apply Hget in Hpp.\n      destruct Hpp as ( nbL & HnbL & stop & Hstop & Hind).\n      exists nbL;split;trivial.\n      exists stop;split;trivial.\n      rewrite <- Hind.\n      apply getIndirectionEq;trivial.\n      apply getNbLevelLt.\n      symmetry;trivial.\n      rewrite checkVAddrsEqualityWOOffsetPermut;trivial.\n      rewrite <- HnbL in *. \n      assert(Hlevel : Some level = Some nbL) by trivial.\n      inversion Hlevel.\n      subst;trivial.\n    + repeat rewrite andb_true_iff in Hlegit1.\n      rewrite negb_true_iff in *. \n      intuition.\n      subst;trivial. }\n  rewrite Htrue in *. \n  assert(Hfalse : None = Some accessiblePage) by trivial.\n  now contradict Hfalse.\n  - assert(Hconcl : isAccessibleMappedPageInParent phyDescChild va accessiblePage\n    {|\n    currentPartition := currentPartition s;\n    memory := add ptVaChildsh2 idxvaChild (VA vaInCurrentPartition) (memory s)\n              beqPage beqIndex |} = \n  isAccessibleMappedPageInParent  phyDescChild va accessiblePage s). \n  { unfold isAccessibleMappedPageInParent.\n    simpl.\n    assert(Hsh2 :  getSndShadow phyDescChild\n    (add ptVaChildsh2 idxvaChild (VA vaInCurrentPartition) (memory s) beqPage\n       beqIndex) =  getSndShadow phyDescChild (memory s)).\n    apply getSndShadowUpdateSh2 with entry;trivial.\n    rewrite Hsh2. clear Hsh2.\n    assert(Hsh2child :  nextEntryIsPP phyDescChild sh2idx sh2Childphy s) by intuition.\n     rewrite nextEntryIsPPgetSndShadow in *. \n rewrite Hsh2child.\n assert(Hsh2virt : getVirtualAddressSh2 sh2Childphy\n    {|\n    currentPartition := currentPartition s;\n    memory := add ptVaChildsh2 idxvaChild (VA vaInCurrentPartition)\n                (memory s) beqPage beqIndex |} va = getVirtualAddressSh2 sh2Childphy s va ).\n  { unfold getVirtualAddressSh2.  \n    assert (Hlevel : Some level = getNbLevel) by intuition.\n    rewrite <- Hlevel.\n    assert(Hind : getIndirection sh2Childphy va level (nbLevel - 1)\n    {|\n    currentPartition := currentPartition s;\n    memory := add ptVaChildsh2 idxvaChild (VA vaInCurrentPartition) (memory s) beqPage\n                beqIndex |} = getIndirection  sh2Childphy va level (nbLevel - 1)\n    s).\n    { apply getIndirectionUpdateSh2 with entry;trivial. }\n    rewrite Hind.\n    case_eq (getIndirection  sh2Childphy va level (nbLevel - 1) s );\n    [ intros tbl Htbl | intros Htbl]; trivial.\n    case_eq (defaultPage =? tbl);trivial.\n    intros Htblnotnul.\n    simpl. \n    assert(Hdiff : tbl <> ptVaChildsh2 \\/ \n         (getIndexOfAddr va fstLevel) <> \n         getIndexOfAddr vaChild fstLevel).\n   {\n  unfold consistency in *.\n  assert(Hnodup : noDupConfigPagesList s) by intuition.\n  apply pageTablesOrIndicesAreDifferent with sh2Childphy sh2Childphy level \n      nbLevel  s;trivial.\n  apply rootStructNotNull with phyDescChild s sh2idx;intuition.\n  rewrite nextEntryIsPPgetSndShadow in *;trivial.\n  apply rootStructNotNull with phyDescChild s sh2idx;intuition.\n  rewrite nextEntryIsPPgetSndShadow in *;trivial.\n  unfold noDupConfigPagesList in *. \n  apply Hnodup with sh2idx phyDescChild;intuition.\n  rewrite nextEntryIsPPgetSndShadow in *;trivial.\n  apply Hnodup with sh2idx phyDescChild;intuition.\n  rewrite nextEntryIsPPgetSndShadow in *;trivial.\n  rewrite <- Hor.\n  rewrite checkVAddrsEqualityWOOffsetPermut;trivial.\n  assert(level = CLevel (nbLevel - 1) ). \n  apply getNbLevelEq;trivial.\n  left;split;trivial.\n  apply beq_nat_false in Htblnotnul.\n  unfold not; intros Htmp;subst;now contradict Htblnotnul.\n  assert(Hnotnull : (defaultPage =? ptVaChildsh2) = false) by intuition.\n  apply beq_nat_false in Hnotnull.\n  unfold not; intros Htmp;subst;now contradict Hnotnull.\n  apply getIndirectionStopLevelGT  with (nbLevel - 1) ;trivial.\n  apply getNbLevelLt;intuition.\n  apply getNbLevelEq in Hlevel.\n  subst.\n  unfold CLevel.\n  case_eq(lt_dec (nbLevel - 1) nbLevel);intros Hl Hli .\n  simpl.\n  omega.\n  assert(0<nbLevel) by apply nbLevelNotZero.\n  omega.\n  subst.\n  assert(getTableAddrRoot ptVaChildsh2 sh2idx phyDescChild vaChild s /\\\n   isVA ptVaChildsh2 (getIndexOfAddr vaChild fstLevel) s)\n   as (Htblroot & Hva) \n  by intuition.\n  assert(Hnewgoal : getIndirection sh2Childphy vaChild level (nbLevel -1) s \n  = Some ptVaChildsh2). \n  apply getIndirectionGetTableRoot2 with phyDescChild;trivial.\n  rewrite Hlevel;trivial.\n  intros.\n  split;subst;trivial.\n  apply getIndirectionStopLevelGT with (nbLevel - 1);trivial.\n    apply getNbLevelLt;intuition.\n  apply getNbLevelEq in Hlevel.\n  subst.\n  unfold CLevel.\n  case_eq(lt_dec (nbLevel - 1) nbLevel);intros Hl Hli .\n  simpl.\n  omega.\n  assert(0<nbLevel) by apply nbLevelNotZero.\n  omega.\n }\n move Hlookup at bottom.\n clear Hind .\napply readVirtualUpdateSh2.\ndestruct Hdiff.\nleft;trivial.\nright. \nassert(Hidx :  getIndexOfAddr vaChild fstLevel = idxvaChild ) by intuition.\nrewrite <- Hidx.\ntrivial.\n } \n  rewrite Hsh2virt.\n  case_eq(getVirtualAddressSh2 sh2Childphy s va );[ intros vaInParent Hvainparent | intros Hvainparent];\n  trivial. \n  assert(Hparent : getParent phyDescChild\n      (add ptVaChildsh2 idxvaChild (VA vaInCurrentPartition) (memory s) beqPage\n         beqIndex) = getParent phyDescChild (memory s)).\n  apply getParentUpdateSh2 with entry;trivial.\n  rewrite Hparent.\n  destruct (getParent phyDescChild (memory s) );trivial.\n  assert(Hpd :  getPd p (memory s) =\n  getPd p\n      (add ptVaChildsh2 idxvaChild  (VA vaInCurrentPartition) (memory s) beqPage beqIndex)).\n  { symmetry.  apply getPdUpdateSh2 with entry;trivial. }\n  rewrite <- Hpd in *.\n  clear Hpd.\n  destruct (getPd p (memory s));trivial.\n  assert(Haccessmap : forall part, getAccessibleMappedPage part {|\n         currentPartition := currentPartition s;\n         memory := add ptVaChildsh2 idxvaChild (VA vaInCurrentPartition) (memory s) beqPage\n                     beqIndex |} vaInParent =\n  getAccessibleMappedPage part s vaInParent).\n  { intros. apply getAccessibleMappedPageUpdateSh2 with entry;trivial. }\n  rewrite Haccessmap in *. clear Haccessmap.\n  trivial. }\n  rewrite Hconcl.\n  apply H with pdChildphy;trivial.\n+ assert  (Htrue : isAccessibleMappedPageInParent partition va accessiblePage\n  {|\n  currentPartition := currentPartition s;\n  memory := add ptVaChildsh2 idxvaChild (VA vaInCurrentPartition) (memory s)\n              beqPage beqIndex |} = \n      isAccessibleMappedPageInParent partition va accessiblePage s). \n { unfold   isAccessibleMappedPageInParent.\n   simpl. \n  assert(Hsh2 : getSndShadow partition\n    (add ptVaChildsh2 idxvaChild (VA vaInCurrentPartition) (memory s) beqPage\n       beqIndex) =getSndShadow partition (memory s)).\n  { apply getSndShadowUpdateSh2 with entry;trivial. }\n  rewrite Hsh2.\n  case_eq (getSndShadow partition (memory s));[ intros sh2 Hsh2part | intros Hnone];trivial. \n  assert(Hgetva : getVirtualAddressSh2 sh2\n    {|\n    currentPartition := currentPartition s;\n    memory := add ptVaChildsh2 idxvaChild (VA vaInCurrentPartition)\n                (memory s) beqPage beqIndex |} va =\n     getVirtualAddressSh2 sh2 s va). \n  { unfold getVirtualAddressSh2. \n    unfold propagatedPropertiesAddVaddr in *. \n    assert(Hlevel : Some level = getNbLevel) by intuition.\n    rewrite <- Hlevel.\n    assert(Hind : getIndirection sh2 va level (nbLevel - 1)\n    {|\n    currentPartition := currentPartition s;\n    memory := add ptVaChildsh2 idxvaChild (VA vaInCurrentPartition) (memory s) beqPage\n                beqIndex |} = getIndirection  sh2 va level (nbLevel - 1)\n    s).\n    { apply getIndirectionUpdateSh2 with entry;trivial. }\n    rewrite Hind.\n    case_eq (getIndirection  sh2 va level (nbLevel - 1) s );\n    [ intros tbl Htbl | intros Htbl]; trivial.\n    case_eq (defaultPage =? tbl);trivial.\n    intros Htblnotnul.\n    simpl.\n    apply readVirtualUpdateSh2;trivial.\n    left. \n    assert(Hconfig : configTablesAreDifferent s ) by (\n    unfold consistency in *; intuition).\n    unfold configTablesAreDifferent in *. \n    assert(Hinconfig1 : In tbl (getConfigPages partition s)).\n    { assert (Hpde : partitionDescriptorEntry s) by (unfold consistency in *;intuition).\n      apply pdSh1Sh2ListExistsNotNull with s partition  in Hpde;trivial.\n      destruct Hpde as ((pd1 & Hpd1 & Hpdnotnull) \n        & (sh1 & Hsh1 & Hsh1notnull) & (sh22 & Hsh22 & Hsh2notnull) & \n        (sh3 & Hsh3 & Hsh3notnull)).\n      unfold getConfigPages.\n      unfold getConfigPagesAux.\n      rewrite H1, Hsh1, Hsh2part, Hsh3.\n      simpl.\n      right.\n      do 2 (rewrite in_app_iff;\n      right).\n       rewrite in_app_iff.\n      left.\n      apply getIndirectionInGetIndirections with va level (nbLevel - 1);trivial.\n      apply nbLevelNotZero.\n      apply beq_nat_false in Htblnotnul.\n      unfold not;intros Hfalse;subst; now contradict Htblnotnul.\n      apply getNbLevelLe;intuition.\n      unfold consistency in *.\n      apply rootStructNotNull with partition s sh2idx;intuition.\n      rewrite nextEntryIsPPgetSndShadow in *;trivial.  }\n    assert(Hinconfig2 : In ptVaChildsh2 (getConfigPages phyDescChild s)).\n    { assert (Hpde : partitionDescriptorEntry s) by (unfold consistency in *;intuition).\n      (* apply pdSh1Sh2ListExistsNotNull with s phyDescChild  in Hpde;trivial.\n      Focus 2.\n      assert(Hchild : In phyDescChild (getChildren (currentPartition s) s) )\n      by intuition.\n      unfold consistency in *. \n      apply childrenPartitionInPartitionList with (currentPartition s);intuition. \n      subst;trivial. *)\n      apply isConfigTableSh2WithVA with vaChild;trivial.\n      assert(Hchild : In phyDescChild (getChildren (currentPartition s) s) )\n      by intuition.\n      unfold consistency in *. \n      apply childrenPartitionInPartitionList with (currentPartition s);intuition. \n      subst;trivial.\n      intros;subst;split;intuition.\n      intuition. }\n    unfold not;intros; subst.\n    unfold Lib.disjoint in *.\n    contradict Hinconfig2.\n    apply Hconfig with partition;trivial.  \n    assert(Hchild : In phyDescChild (getChildren (currentPartition s) s) )\n      by intuition.\n      unfold consistency in *. \n      apply childrenPartitionInPartitionList with (currentPartition s);intuition. \n  }           \n  rewrite Hgetva.  \n  case_eq (getVirtualAddressSh2 sh2 s va);[ intros vainparent Hvainparent | intros Hnone];trivial. \n  assert(Hparent : getParent partition\n    (add ptVaChildsh2 idxvaChild (VA vaInCurrentPartition) (memory s) beqPage\n       beqIndex) = getParent partition (memory s)).\n  apply getParentUpdateSh2 with entry;trivial.\n  rewrite Hparent.\n  destruct (getParent partition (memory s) );trivial.\n  assert(Hpd :  getPd p (memory s) =\n  getPd p\n      (add ptVaChildsh2 idxvaChild  (VA vaInCurrentPartition) (memory s) beqPage beqIndex)).\n  { symmetry.  apply getPdUpdateSh2 with entry;trivial. }\n  rewrite <- Hpd in *.\n  clear Hpd.\n  destruct (getPd p (memory s));trivial.\n  assert(Haccessmap : forall part, getAccessibleMappedPage part {|\n         currentPartition := currentPartition s;\n         memory := add ptVaChildsh2 idxvaChild (VA vaInCurrentPartition) (memory s) beqPage\n                     beqIndex |} vainparent =\n  getAccessibleMappedPage part s vainparent).\n  { intros. apply getAccessibleMappedPageUpdateSh2 with entry;trivial. }\n  rewrite Haccessmap in *. clear Haccessmap.\n  trivial. }\n  rewrite Htrue.\n  apply H with pd;trivial.     \nQed.\n\nLemma getAncestorsUpdateSh2 s vaInCurrentPartition table idx entry partition: \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\ngetAncestors partition\n  {|\n  currentPartition := currentPartition s;\n  memory := add table idx (VA vaInCurrentPartition) (memory s)\n              beqPage beqIndex |} =\n                      getAncestors partition s.\nProof. \nintros Hlookup.\nunfold getAncestors.\nsimpl.\nrevert partition. \ninduction (nbPage + 1);trivial.\nsimpl;intros.\nassert(Hparent : getParent partition\n    (add table idx (VA vaInCurrentPartition) (memory s) beqPage\n       beqIndex) = getParent partition (memory s)).\n{  apply getParentUpdateSh2 with entry;trivial. }\nrewrite Hparent.\ndestruct (getParent partition (memory s) );trivial.\nf_equal.\napply IHn;trivial.\nQed.\n\nLemma noCycleInPartitionTreeUpdateSh2 s vaInCurrentPartition table idx entry : \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nnoCycleInPartitionTree s -> \nnoCycleInPartitionTree\n  {|\n  currentPartition := currentPartition s;\n  memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n              beqIndex |}.\nProof.\nintros Hlookup.\nunfold noCycleInPartitionTree.\nintros; \nsimpl.\nassert(Hpartitions : getPartitions multiplexer\n    s = \ngetPartitions multiplexer {|\n     currentPartition := currentPartition s;\n     memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n                 beqIndex |}).\napply getPartitionsUpdateSh2 with entry; trivial.\nrewrite <- Hpartitions in *; clear Hpartitions;trivial.\nsimpl in *.\nassert(Hancestor :getAncestors partition\n          {|\n          currentPartition := currentPartition s;\n          memory := add table idx (VA vaInCurrentPartition) (memory s)\n                      beqPage beqIndex |} =\n                      getAncestors partition s).\napply getAncestorsUpdateSh2 with entry;trivial.\nrewrite Hancestor in *.\napply H;trivial.\nQed.\n\nLemma configTablesAreDifferentUpdateSh2 s vaInCurrentPartition table idx entry : \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nconfigTablesAreDifferent s -> \nconfigTablesAreDifferent\n  {|\n  currentPartition := currentPartition s;\n  memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n              beqIndex |}.\nProof.\nintros Hlookup.\nunfold configTablesAreDifferent.\nintros; \nsimpl.\nassert(Hpartitions : getPartitions multiplexer\n    s = \ngetPartitions multiplexer {|\n     currentPartition := currentPartition s;\n     memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n                 beqIndex |}).\napply getPartitionsUpdateSh2 with entry; trivial.\nrewrite <- Hpartitions in *; clear Hpartitions;trivial.\nsimpl in *.\nassert(Hconfig : forall part, getConfigPages part {|\n          currentPartition := currentPartition s;\n          memory := add table idx (VA vaInCurrentPartition) (memory s)\n                      beqPage beqIndex |} = getConfigPages part s).\n{ intros.\napply getConfigPagesUpdateSh2 with entry;trivial. } \nrewrite Hconfig in *. \nrewrite Hconfig in *. \nclear Hconfig.\napply H;trivial.\nQed.\n\nLemma isChildUpdateSh2 s vaInCurrentPartition table idx entry : \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nisChild s -> \nisChild\n  {|\n  currentPartition := currentPartition s;\n  memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n              beqIndex |}.\nProof.\nintros Hlookup.\nunfold isChild.\nintros; \nsimpl.\nassert(Hpartitions : getPartitions multiplexer\n    s = \ngetPartitions multiplexer {|\n     currentPartition := currentPartition s;\n     memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n                 beqIndex |}).\napply getPartitionsUpdateSh2 with entry; trivial.\nrewrite <- Hpartitions in *; clear Hpartitions;trivial.\nsimpl in *.\nassert(Hchildren : forall part, getChildren part\n     {|\n     currentPartition := currentPartition s;\n     memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n                 beqIndex |} = getChildren part s).\n{ intros.\nsymmetry.\napply getChildrenUpdateSh2 with entry;trivial. } \nrewrite Hchildren in *.\nclear Hchildren.\nassert(Hparent : getParent partition\n    (add table idx (VA vaInCurrentPartition) (memory s) beqPage\n       beqIndex) = getParent partition (memory s)).\n{  apply getParentUpdateSh2 with entry;trivial. }\nrewrite Hparent in *.\napply H;trivial.\nQed.\n\nLemma isPresentNotDefaultIffUpdateSh2 s vaInCurrentPartition table idx entry : \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nisPresentNotDefaultIff s -> \nisPresentNotDefaultIff\n  {|\n  currentPartition := currentPartition s;\n  memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n              beqIndex |}.\nProof.\nintros Hlookup.\nunfold isPresentNotDefaultIff.\nintros; \nsimpl.\n assert(Hpresent :    readPresent table0 idx0\n  (memory s) = readPresent table0 idx0\n    (add table idx (VA vaInCurrentPartition) (memory s) beqPage beqIndex) ).\nsymmetry.\napply readPresentUpdateSh2 with entry; trivial.\nrewrite <- Hpresent.\n assert(Hread :    readPhyEntry table0 idx0\n  (memory s) = readPhyEntry table0 idx0\n    (add table idx (VA vaInCurrentPartition) (memory s) beqPage beqIndex) ).\nsymmetry.\napply readPhyEntryUpdateSh2 with entry;trivial.\nrewrite <- Hread.\napply H.\nQed.\nLemma getVirtualAddressSh1UpdateSh2  s vaInCurrentPartition table idx entry p va: \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\ngetVirtualAddressSh1 p s va  =\ngetVirtualAddressSh1 p {|\n    currentPartition := currentPartition s;\n    memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n                beqIndex |} va.\nProof.\nintros Hlookup.\nunfold getVirtualAddressSh1.\ndestruct (getNbLevel);trivial.\nassert(Hind : getIndirection p va l (nbLevel - 1)\n{|\ncurrentPartition := currentPartition s;\nmemory := add table idx  (VA vaInCurrentPartition) (memory s) beqPage\n            beqIndex |} = getIndirection  p va l  (nbLevel - 1)\ns).\n{ apply getIndirectionUpdateSh2 with entry;trivial. }\nrewrite Hind.\ncase_eq (getIndirection  p va l  (nbLevel - 1) s );\n[ intros tbl Htbl | intros Htbl]; trivial.\ncase_eq (defaultPage =? tbl);trivial.\nintros Htblnotnul.\nsimpl.\nsymmetry.\napply readVirEntryUpdateSh2 with entry;trivial.\nQed.\n                \nLemma isDerivedUpdateSh2  s vaInCurrentPartition table idx entry parent va: \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nisDerived parent va s ->  isDerived parent va  {|\n       currentPartition := currentPartition s;\n       memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n                   beqIndex |}\n       . \nProof.\nintros Hlookup.\nunfold isDerived.\nsimpl.\nassert(Hsh1 :  getFstShadow parent (memory s) =\ngetFstShadow parent\n    (add table idx (VA vaInCurrentPartition) (memory s) beqPage beqIndex)).\n{ symmetry.  apply getFstShadowUpdateSh2 with entry;trivial. }\nrewrite <- Hsh1 in *.\ndestruct (getFstShadow parent (memory s));trivial.\nassert(Hgetvir1 : getVirtualAddressSh1 p s va  =\ngetVirtualAddressSh1 p {|\n    currentPartition := currentPartition s;\n    memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n                beqIndex |} va ).\napply getVirtualAddressSh1UpdateSh2 with entry;trivial.\nrewrite <- Hgetvir1;trivial.\nQed.\n \nLemma physicalPageNotDerivedUpdateSh2 s vaInCurrentPartition table idx entry : \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nphysicalPageNotDerived s -> \nphysicalPageNotDerived\n  {|\n  currentPartition := currentPartition s;\n  memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n              beqIndex |}.\nProof.\nintros Hlookup.\nunfold physicalPageNotDerived.\nintros; \nsimpl.\nassert(Hpartitions : getPartitions multiplexer\n    s = \ngetPartitions multiplexer {|\n     currentPartition := currentPartition s;\n     memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n                 beqIndex |}).\napply getPartitionsUpdateSh2 with entry; trivial.\nrewrite <- Hpartitions in *; clear Hpartitions;trivial.\nsimpl in *.\nassert(Hchildren : forall part, getChildren part\n     {|\n     currentPartition := currentPartition s;\n     memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n                 beqIndex |} = getChildren part s).\n{ intros.\nsymmetry.\napply getChildrenUpdateSh2 with entry;trivial. } \nrewrite Hchildren in *.\nclear Hchildren.\nassert(Hpd : forall partition, getPd partition\n       (add table idx (VA vaInCurrentPartition) (memory s) beqPage beqIndex)\n       =  getPd partition (memory s)).\n{ intros.\n  apply getPdUpdateSh2 with entry;trivial. }\nrewrite Hpd in *. clear Hpd.\nassert(Hmap : forall pd va,  getMappedPage pd\n {| currentPartition := currentPartition s;\n    memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n             beqIndex |} va = getMappedPage pd s va ).\n{ intros. apply getMappedPageUpdateSh2 with entry;trivial. }\nrewrite Hmap in *. clear Hmap.\nassert(~ isDerived parent va s ). \nunfold not;intros. \ncontradict H2.\napply isDerivedUpdateSh2 with entry;trivial.\napply H with  parent va pdParent\nchild pdChild vaInChild;trivial.\nQed.\n\nLemma multiplexerWithoutParentUpdateSh2 s vaInCurrentPartition table idx entry : \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nmultiplexerWithoutParent s -> \nmultiplexerWithoutParent\n  {|\n  currentPartition := currentPartition s;\n  memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n              beqIndex |}.\nProof.\nintros Hlookup.\nunfold multiplexerWithoutParent.\nintros; \nsimpl.\n\nassert(Hparent : getParent multiplexer\n    (add table idx (VA vaInCurrentPartition) (memory s) beqPage\n       beqIndex) = getParent multiplexer (memory s)).\n{  apply getParentUpdateSh2 with entry;trivial. }\nrewrite Hparent in *.\napply H;trivial.\nQed.\n\nLemma isParentUpdateSh2 s vaInCurrentPartition table idx entry : \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nisParent s -> \nisParent\n  {|\n  currentPartition := currentPartition s;\n  memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n              beqIndex |}.\nProof.\nintros Hlookup.\nunfold isParent.\nintros.\nsimpl in *. \nassert(Hparent : getParent partition\n    (add table idx (VA vaInCurrentPartition) (memory s) beqPage\n       beqIndex) = getParent partition (memory s)).\n{  apply getParentUpdateSh2 with entry;trivial. }\nrewrite Hparent in *. clear Hparent.\nassert(Hpartitions : getPartitions multiplexer\n    s = \ngetPartitions multiplexer {|\n     currentPartition := currentPartition s;\n     memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n                 beqIndex |}).\napply getPartitionsUpdateSh2 with entry; trivial.\nrewrite <- Hpartitions in *; clear Hpartitions;trivial.\nsimpl in *.\nassert(Hchildren : forall part, getChildren part\n     {|\n     currentPartition := currentPartition s;\n     memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n                 beqIndex |} = getChildren part s).\n{ intros.\nsymmetry.\napply getChildrenUpdateSh2 with entry;trivial. } \nrewrite Hchildren in *.\nclear Hchildren.\napply H; trivial.\nQed.\n\nLemma noDupPartitionTreeUpdateSh2 s vaInCurrentPartition table idx entry : \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nnoDupPartitionTree s -> \nnoDupPartitionTree\n  {|\n  currentPartition := currentPartition s;\n  memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n              beqIndex |}.\nProof.\nintros Hlookup.\nunfold noDupPartitionTree.\nintros.\nsimpl in *.\nassert(Hpartitions : getPartitions multiplexer\n    s = \ngetPartitions multiplexer {|\n     currentPartition := currentPartition s;\n     memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n                 beqIndex |}).\napply getPartitionsUpdateSh2 with entry; trivial.\nrewrite <- Hpartitions in *; clear Hpartitions;trivial.\nQed.\n \nLemma wellFormedFstShadowUpdateSh2 s vaInCurrentPartition table idx entry : \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nwellFormedFstShadow s -> \nwellFormedFstShadow\n  {|\n  currentPartition := currentPartition s;\n  memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n              beqIndex |}.\nProof.\nintros Hlookup.\nunfold wellFormedFstShadow.\nintros.\nsimpl in *.\nassert(Hpartitions : getPartitions multiplexer\n    s = \ngetPartitions multiplexer {|\n     currentPartition := currentPartition s;\n     memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n                 beqIndex |}).\napply getPartitionsUpdateSh2 with entry; trivial.\nrewrite <- Hpartitions in *; clear Hpartitions;trivial.\nassert(Hpd : forall partition, getPd partition\n       (add table idx (VA vaInCurrentPartition) (memory s) beqPage beqIndex)\n       =  getPd partition (memory s)).\n{ intros.\n  apply getPdUpdateSh2 with entry;trivial. }\nrewrite Hpd in *. clear Hpd.\nassert(Hmap : forall pd va,  getMappedPage pd\n {| currentPartition := currentPartition s;\n    memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n             beqIndex |} va = getMappedPage pd s va ).\n{ intros. apply getMappedPageUpdateSh2 with entry;trivial. }\nrewrite Hmap in *. clear Hmap.\nassert(Hsh1 : forall partition, getFstShadow partition (memory s) =\ngetFstShadow partition\n    (add table idx (VA vaInCurrentPartition) (memory s) beqPage beqIndex)).\n{ symmetry.  apply getFstShadowUpdateSh2 with entry;trivial. }\nrewrite <- Hsh1 in *. clear Hsh1.\nassert(Hgetvir1 : getVirtualAddressSh1 sh1 s va  =\ngetVirtualAddressSh1 sh1 {|\n    currentPartition := currentPartition s;\n    memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n                beqIndex |} va ).\napply getVirtualAddressSh1UpdateSh2 with entry;trivial.\nrewrite <- Hgetvir1;trivial.\napply H with partition pg pd;trivial.\nQed.\n\nLemma wellFormedSndShadowUpdateSh2 s entry (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:\nisnotderiv && accessiblesrc && presentmap && negb presentvaChild = true -> \nnegb presentDescPhy = false -> \nlookup ptVaChildsh2 idxvaChild  (memory s) beqPage beqIndex = Some (VA entry) ->\npropagatedPropertiesAddVaddr 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 -> \nwellFormedSndShadow s ->\nwellFormedSndShadow\n  {|\n  currentPartition := currentPartition s;\n  memory := add ptVaChildsh2 idxvaChild  (VA vaInCurrentPartition) (memory s) beqPage\n              beqIndex |}. \nProof.\nintros Hlegit1 Hlegit Hlookup Hprops.\nunfold wellFormedSndShadow.\nintros.\nsimpl in *.\nassert(Hpartitions : getPartitions multiplexer\n    s = \ngetPartitions multiplexer {|\n     currentPartition := currentPartition s;\n     memory := add ptVaChildsh2 idxvaChild (VA vaInCurrentPartition) (memory s) beqPage\n                 beqIndex |}).\napply getPartitionsUpdateSh2 with entry; trivial.\nrewrite <- Hpartitions in *; clear Hpartitions;trivial.\nassert(Hpd : forall partition, getPd partition\n       (add ptVaChildsh2 idxvaChild (VA vaInCurrentPartition) (memory s) beqPage beqIndex)\n       =  getPd partition (memory s)).\n{ intros.\n  apply getPdUpdateSh2 with entry;trivial. }\nrewrite Hpd in *. clear Hpd.\nassert(Hmap : forall pd va,  getMappedPage pd\n {| currentPartition := currentPartition s;\n    memory := add ptVaChildsh2 idxvaChild (VA vaInCurrentPartition) (memory s) beqPage\n             beqIndex |} va = getMappedPage pd s va ).\n{ intros. apply getMappedPageUpdateSh2 with entry;trivial. }\nrewrite Hmap in *. clear Hmap.\nassert(Hsh1 : forall partition, getSndShadow partition (memory s) =\ngetSndShadow partition\n    (add ptVaChildsh2 idxvaChild (VA vaInCurrentPartition) (memory s) beqPage beqIndex)).\n{ symmetry.  apply getSndShadowUpdateSh2 with entry;trivial. }\nrewrite <- Hsh1 in *. clear Hsh1.\nassert(Hor : partition = phyDescChild \\/ partition <> phyDescChild) by apply pageDecOrNot.\ndestruct Hor as [Hor | Hor];\nsubst.\n+ unfold propagatedPropertiesAddVaddr in *.\n  assert (Hpdeq : sh2Childphy = sh2). \n  { apply getSh2NextEntryIsPPEq with phyDescChild s;trivial.\n    intuition. }\n    assert (Hsh2eq : pdChildphy = pd). \n  { apply getPdNextEntryIsPPEq with phyDescChild s;trivial.\n    intuition. }\n    subst pd sh2.\n  assert(Hor :checkVAddrsEqualityWOOffset nbLevel vaChild va level = true \\/ \n         checkVAddrsEqualityWOOffset nbLevel vaChild va level = false).\n  { destruct (checkVAddrsEqualityWOOffset nbLevel vaChild va level);intuition. }\n  destruct Hor as [Hor | Hor].\n  - assert(Hlastidx : (getIndexOfAddr vaChild fstLevel) = \n  (getIndexOfAddr va fstLevel)).\n    { apply checkVAddrsEqualityWOOffsetTrue' with nbLevel level; trivial.\n      unfold fstLevel.\n      unfold CLevel.\n      case_eq ( lt_dec 0 nbLevel );intros.\n      simpl.\n      omega.\n      assert(0<nbLevel) by apply nbLevelNotZero.\n      omega.\n      destruct level;simpl; omega. }\n  rewrite Hlastidx in *. \n  assert(Htrue : getMappedPage pdChildphy s va = None).\n  {  apply getMappedPageNotPresent with ptVaChildpd phyDescChild;intuition.\n    + subst;trivial.\n    + assert(Hget : getTableAddrRoot ptVaChildpd PDidx phyDescChild vaChild s) by trivial.\n      unfold getTableAddrRoot in *.\n      destruct Hget as(Hi & Hget).\n      split;trivial.\n      intros tableroot Hpp.\n      apply Hget in Hpp.\n      destruct Hpp as ( nbL & HnbL & stop & Hstop & Hind).\n      exists nbL;split;trivial.\n      exists stop;split;trivial.\n      rewrite <- Hind.\n      apply getIndirectionEq;trivial.\n      apply getNbLevelLt.\n      symmetry;trivial.\n      rewrite checkVAddrsEqualityWOOffsetPermut;trivial.\n      rewrite <- HnbL in *. \n      assert(Hlevel : Some level = Some nbL) by trivial.\n      inversion Hlevel.\n      subst;trivial.\n    + repeat rewrite andb_true_iff in Hlegit1.\n      rewrite negb_true_iff in *. \n      intuition.\n      subst;trivial. }\n  rewrite Htrue in *. \n  assert(Hfalse : None = Some pg) by trivial.\n  now contradict Hfalse.\n  - (* assert(Hconcl : isAccessibleMappedPageInParent phyDescChild va accessiblePage\n    {|\n    currentPartition := currentPartition s;\n    memory := add ptVaChildsh2 idxvaChild (VA vaInCurrentPartition) (memory s)\n              beqPage beqIndex |} = \n  isAccessibleMappedPageInParent  phyDescChild va accessiblePage s). \n  { unfold isAccessibleMappedPageInParent.\n    simpl.\n    assert(Hsh2 :  getSndShadow phyDescChild\n    (add ptVaChildsh2 idxvaChild (VA vaInCurrentPartition) (memory s) beqPage\n       beqIndex) =  getSndShadow phyDescChild (memory s)).\n    apply getSndShadowUpdateSh2 with entry;trivial.\n    rewrite Hsh2. clear Hsh2.\n    assert(Hsh2child :  nextEntryIsPP phyDescChild sh2idx sh2Childphy s) by intuition.\n     rewrite nextEntryIsPPgetSndShadow in *. \n rewrite Hsh2child. *)\n assert(Hnewgoal :  exists vainparent : vaddr,\n      getVirtualAddressSh2 sh2Childphy s va = Some vainparent /\\\n      beqVAddr defaultVAddr vainparent = false).\n apply H with phyDescChild pg pdChildphy ;trivial.\n destruct  Hnewgoal as (vainparent & Hgoal & Hfalse).\n exists vainparent;split;trivial.\n rewrite <- Hgoal.\n  unfold getVirtualAddressSh2.  \n    assert (Hlevel : Some level = getNbLevel) by intuition.\n    rewrite <- Hlevel.\n    assert(Hind : getIndirection sh2Childphy va level (nbLevel - 1)\n    {|\n    currentPartition := currentPartition s;\n    memory := add ptVaChildsh2 idxvaChild (VA vaInCurrentPartition) (memory s) beqPage\n                beqIndex |} = getIndirection  sh2Childphy va level (nbLevel - 1)\n    s).\n    { apply getIndirectionUpdateSh2 with entry;trivial. }\n    rewrite Hind.\n    case_eq (getIndirection  sh2Childphy va level (nbLevel - 1) s );\n    [ intros tbl Htbl | intros Htbl]; trivial.\n    case_eq (defaultPage =? tbl);trivial.\n    intros Htblnotnul.\n    simpl. \n    assert(Hdiff : tbl <> ptVaChildsh2 \\/ \n         (getIndexOfAddr va fstLevel) <> \n         getIndexOfAddr vaChild fstLevel).\n   {\n  unfold consistency in *.\n  assert(Hnodup : noDupConfigPagesList s) by intuition.\n  apply pageTablesOrIndicesAreDifferent with sh2Childphy sh2Childphy level \n      nbLevel  s;trivial.\n  apply rootStructNotNull with phyDescChild s sh2idx;intuition.\n  rewrite nextEntryIsPPgetSndShadow in *;trivial.\n  apply rootStructNotNull with phyDescChild s sh2idx;intuition.\n  rewrite nextEntryIsPPgetSndShadow in *;trivial.\n  unfold noDupConfigPagesList in *. \n  apply Hnodup with sh2idx phyDescChild;intuition.\n  rewrite nextEntryIsPPgetSndShadow in *;trivial.\n  apply Hnodup with sh2idx phyDescChild;intuition.\n  rewrite nextEntryIsPPgetSndShadow in *;trivial.\n  rewrite <- Hor.\n  rewrite checkVAddrsEqualityWOOffsetPermut;trivial.\n  assert(level = CLevel (nbLevel - 1) ). \n  apply getNbLevelEq;trivial.\n  left;split;trivial.\n  apply beq_nat_false in Htblnotnul.\n  unfold not; intros Htmp;subst;now contradict Htblnotnul.\n  assert(Hnotnull : (defaultPage =? ptVaChildsh2) = false) by intuition.\n  apply beq_nat_false in Hnotnull.\n  unfold not; intros Htmp;subst;now contradict Hnotnull.\n  apply getIndirectionStopLevelGT  with (nbLevel - 1) ;trivial.\n  apply getNbLevelLt;intuition.\n  apply getNbLevelEq in Hlevel.\n  subst.\n  unfold CLevel.\n  case_eq(lt_dec (nbLevel - 1) nbLevel);intros Hl Hli .\n  simpl.\n  omega.\n  assert(0<nbLevel) by apply nbLevelNotZero.\n  omega.\n  subst.\n  assert(getTableAddrRoot ptVaChildsh2 sh2idx phyDescChild vaChild s /\\\n   isVA ptVaChildsh2 (getIndexOfAddr vaChild fstLevel) s)\n   as (Htblroot & Hva) \n  by intuition.\n  assert(Hnewgoal : getIndirection sh2Childphy vaChild level (nbLevel -1) s \n  = Some ptVaChildsh2). \n  apply getIndirectionGetTableRoot2 with phyDescChild;trivial.\n  rewrite Hlevel;trivial.\n  intros.\n  split;subst;trivial.\n  apply getIndirectionStopLevelGT with (nbLevel - 1);trivial.\n    apply getNbLevelLt;intuition.\n  apply getNbLevelEq in Hlevel.\n  subst.\n  unfold CLevel.\n  case_eq(lt_dec (nbLevel - 1) nbLevel);intros Hl Hli .\n  simpl.\n  omega.\n  assert(0<nbLevel) by apply nbLevelNotZero.\n  omega.\n }\n move Hlookup at bottom.\n clear Hind .\napply readVirtualUpdateSh2.\ndestruct Hdiff.\nleft;trivial.\nright. \nassert(Hidx :  getIndexOfAddr vaChild fstLevel = idxvaChild ) by intuition.\nrewrite <- Hidx.\ntrivial. \n+ assert(Hnewgoal :  exists vainparent : vaddr,\n      getVirtualAddressSh2 sh2 s va = Some vainparent /\\\n      beqVAddr defaultVAddr vainparent = false).\n apply H with partition pg pd ;trivial.\n destruct  Hnewgoal as (vainparent & Hgoal & Hfalse).\n exists vainparent;split;trivial.\n rewrite <- Hgoal.\n unfold getVirtualAddressSh2. \n    unfold propagatedPropertiesAddVaddr in *. \n    assert(Hlevel : Some level = getNbLevel) by intuition.\n    rewrite <- Hlevel.\n    assert(Hind : getIndirection sh2 va level (nbLevel - 1)\n    {|\n    currentPartition := currentPartition s;\n    memory := add ptVaChildsh2 idxvaChild (VA vaInCurrentPartition) (memory s) beqPage\n                beqIndex |} = getIndirection  sh2 va level (nbLevel - 1)\n    s).\n    { apply getIndirectionUpdateSh2 with entry;trivial. }\n    rewrite Hind.\n    case_eq (getIndirection  sh2 va level (nbLevel - 1) s );\n    [ intros tbl Htbl | intros Htbl]; trivial.\n    case_eq (defaultPage =? tbl);trivial.\n    intros Htblnotnul.\n    simpl.\n    apply readVirtualUpdateSh2;trivial.\n    left. \n    assert(Hconfig : configTablesAreDifferent s ) by (\n    unfold consistency in *; intuition).\n    unfold configTablesAreDifferent in *. \n    assert(Hinconfig1 : In tbl (getConfigPages partition s)).\n    { assert (Hpde : partitionDescriptorEntry s) by (unfold consistency in *;intuition).\n      apply pdSh1Sh2ListExistsNotNull with s partition  in Hpde;trivial.\n      destruct Hpde as ((pd1 & Hpd1 & Hpdnotnull) \n        & (sh1 & Hsh1 & Hsh1notnull) & (sh22 & Hsh22 & Hsh2notnull) & \n        (sh3 & Hsh3 & Hsh3notnull)).\n      unfold getConfigPages.\n      unfold getConfigPagesAux.\n      rewrite H2, Hsh1, H3, Hsh3.\n      simpl.\n      right.\n      do 2 (rewrite in_app_iff;\n      right).\n       rewrite in_app_iff.\n      left.\n      apply getIndirectionInGetIndirections with va level (nbLevel - 1);trivial.\n      apply nbLevelNotZero.\n      apply beq_nat_false in Htblnotnul.\n      unfold not;intros Hfalse1;subst; now contradict Htblnotnul.\n      apply getNbLevelLe;intuition.\n      unfold consistency in *.\n      apply rootStructNotNull with partition s sh2idx;intuition.\n      rewrite nextEntryIsPPgetSndShadow in *;trivial.  }\n    assert(Hinconfig2 : In ptVaChildsh2 (getConfigPages phyDescChild s)).\n    { assert (Hpde : partitionDescriptorEntry s) by (unfold consistency in *;intuition).\n      (* apply pdSh1Sh2ListExistsNotNull with s phyDescChild  in Hpde;trivial.\n      Focus 2.\n      assert(Hchild : In phyDescChild (getChildren (currentPartition s) s) )\n      by intuition.\n      unfold consistency in *. \n      apply childrenPartitionInPartitionList with (currentPartition s);intuition. \n      subst;trivial. *)\n      apply isConfigTableSh2WithVA with vaChild;trivial.\n      assert(Hchild : In phyDescChild (getChildren (currentPartition s) s) )\n      by intuition.\n      unfold consistency in *. \n      apply childrenPartitionInPartitionList with (currentPartition s);intuition. \n      subst;trivial.\n      intros;subst;split;intuition.\n      intuition. }\n    unfold not;intros; subst.\n    unfold Lib.disjoint in *.\n    contradict Hinconfig2.\n    apply Hconfig with partition;trivial.  \n    assert(Hchild : In phyDescChild (getChildren (currentPartition s) s) )\n      by intuition.\n      unfold consistency in *. \n      apply childrenPartitionInPartitionList with (currentPartition s);intuition. \nQed.\n\nLemma wellFormedShadowsUpdateSh2 s vaInCurrentPartition table idx entry idxroot: \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\nwellFormedShadows idxroot s -> \nwellFormedShadows idxroot\n  {|\n  currentPartition := currentPartition s;\n  memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n              beqIndex |}.\nProof.\nintros Hlookup.\nunfold wellFormedShadows.\nintros.\nsimpl in *.\nassert(Hpartitions : getPartitions multiplexer\n    s = \ngetPartitions multiplexer {|\n     currentPartition := currentPartition s;\n     memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n                 beqIndex |}).\napply getPartitionsUpdateSh2 with entry; trivial.\nrewrite <- Hpartitions in *; clear Hpartitions;trivial.\nassert(Hpd : forall partition, getPd partition\n       (add table idx (VA vaInCurrentPartition) (memory s) beqPage beqIndex)\n       =  getPd partition (memory s)).\n{ intros.\n  apply getPdUpdateSh2 with entry;trivial. }\nrewrite Hpd in *. clear Hpd.\nassert(Hpp : nextEntryIsPP partition idxroot structroot s ). \nrewrite nextEntryIsPPUpdateSh2 with entry;trivial.\neassumption.\ntrivial.\nassert(Hind : forall root, getIndirection root va nbL stop\n    {|\n    currentPartition := currentPartition s;\n    memory := add table idx (VA vaInCurrentPartition) (memory s) beqPage\n                beqIndex |} = getIndirection  root va nbL stop\n    s).\n    { intros. apply getIndirectionUpdateSh2 with entry;trivial. }\nassert(Hgoal :  exists indirection2 : page,\n      getIndirection structroot va nbL stop s = Some indirection2 /\\\n      (defaultPage =? indirection2) = false). \n{ apply H with partition pdroot indirection1;trivial.\n  rewrite <- Hind;trivial. }\ndestruct Hgoal as (indirection2 & Hind1 & Hindnotnul).\nexists indirection2;split;trivial.\nrewrite <- Hind1.\napply Hind.\nQed.\nLemma getTableAddrRootUpdateSh2 s vaInCurrentPartition table idx entry  idxroot \nptDescChild descChild currentPart: \nlookup table idx (memory s) beqPage beqIndex = Some (VA entry) ->\ngetTableAddrRoot ptDescChild idxroot currentPart descChild  s-> \ngetTableAddrRoot ptDescChild idxroot currentPart descChild\n  {|\n  currentPartition := currentPartition s;\n  memory := add table idx (VA vaInCurrentPartition) (memory s)\n              beqPage beqIndex |}.\nProof.\nintros Hlookup.\nunfold getTableAddrRoot.\nintros Hcond.\ndestruct Hcond as(Hi & Hcond).\nsplit;trivial.\nintros. \nassert(Hpp : nextEntryIsPP currentPart idxroot tableroot s ). \nrewrite nextEntryIsPPUpdateSh2 with entry;trivial.\neassumption.\ntrivial.\napply Hcond in Hpp.\ndestruct Hpp as (nbL & HnbL & stop & Hstop & Hind). \nexists nbL. \nsplit;trivial.\nexists stop.\nsplit;trivial. \nrewrite <- Hind.\napply getIndirectionUpdateSh2 with entry;trivial.\nQed.\n          \nLemma consistencyUpdateSh2 s  entry (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:\nisnotderiv && accessiblesrc && presentmap && negb presentvaChild = true -> \nnegb presentDescPhy = false -> \nlookup ptVaChildsh2 idxvaChild (memory s) beqPage beqIndex = Some (VA entry) ->\npropagatedPropertiesAddVaddr 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 -> \nconsistency  {|\ncurrentPartition := currentPartition s;\nmemory := add ptVaChildsh2 idxvaChild (VA vaInCurrentPartition)\n            (memory s) beqPage beqIndex |}.\nProof.\nset (s' := {|\n  currentPartition := currentPartition s;\n  memory := add ptVaChildsh2 idxvaChild (VA vaInCurrentPartition) (memory s)\n              beqPage beqIndex |} ) in *.\nunfold propagatedPropertiesAddVaddr; intros. \nunfold consistency in *.\nintuition.\n(** partitionDescriptorEntry **)\n- apply partitionDescriptorEntryUpdateSh2 with entry;trivial.\n(** dataStructurePdSh1Sh2asRoot **)\n- apply dataStructurePdSh1Sh2asRootUpdateSh2 with entry;trivial.\n(** dataStructurePdSh1Sh2asRoot **)\n- apply dataStructurePdSh1Sh2asRootUpdateSh2 with entry;trivial.\n(** dataStructurePdSh1Sh2asRoot **)\n- apply dataStructurePdSh1Sh2asRootUpdateSh2 with entry;trivial.\n(** currentPartitionInPartitionsList **)\n- apply currentPartitionInPartitionsListUpdateSh2 with entry;trivial.\n(** noDupMappedPagesList **)\n- apply noDupMappedPagesListUpdateSh2 with entry;trivial.\n(** noDupConfigPagesList **)\n- apply noDupConfigPagesListUpdateSh2 with entry ; trivial.\n(** parentInPartitionList **)\n- apply parentInPartitionListUpdateSh2 with entry ; trivial.\n(** accessibleVAIsNotPartitionDescriptor **)\n- apply accessibleVAIsNotPartitionDescriptorUpdateSh2 with entry ; trivial.\n(** accessibleChildPageIsAccessibleIntoParent **)\n- apply accessibleChildPageIsAccessibleIntoParentUpdateSh2 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  unfold consistency in *; intuition.\n(** noCycleInPartitionTree **)\n- apply noCycleInPartitionTreeUpdateSh2 with entry;trivial.\n(** configTablesAreDifferent **)\n- apply configTablesAreDifferentUpdateSh2 with entry;trivial.\n(** isChild **)\n- apply isChildUpdateSh2 with entry;trivial.\n(** isPresentNotDefaultIff *)\n- apply isPresentNotDefaultIffUpdateSh2 with entry;trivial.\n(** physicalPageNotDerived **)\n- apply physicalPageNotDerivedUpdateSh2 with entry;trivial.\n(** multiplexerWithoutParent *)\n- apply multiplexerWithoutParentUpdateSh2 with entry;trivial.\n(** isParent **)\n- apply isParentUpdateSh2 with entry;trivial.\n(** noDupPartitionTree **)\n- apply noDupPartitionTreeUpdateSh2 with entry;trivial.\n(** wellFormedFstShadow **)\n- apply wellFormedFstShadowUpdateSh2 with entry;trivial.\n(** wellFormedSndShadow **)\n- apply wellFormedSndShadowUpdateSh2 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  unfold consistency in *; intuition.\n(** wellFormedShadows *)\n- apply wellFormedShadowsUpdateSh2 with entry;trivial.\n(** wellFormedShadows *)\n- apply wellFormedShadowsUpdateSh2 with entry;trivial.\nQed.  \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/DEC1/Pip_writeVirtualInv_Lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.25134504057928136}}
{"text": "Require Import Bedrock.Platform.tests.Thread0 Bedrock.Platform.tests.Connect Bedrock.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": "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/tests/ConnectDriver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2513450351955278}}
{"text": "(* TLC in Coq\n *\n * Module: tlc.component.perfect_link_1\n * Purpose: Contains the local specification of the perfect link PL_1 property.\n *)\n\nRequire Import mathcomp.ssreflect.eqtype.\nRequire Import mathcomp.ssreflect.seq.\nRequire Import mathcomp.ssreflect.ssrbool.\nRequire Import mathcomp.ssreflect.ssreflect.\nRequire Import mathcomp.ssreflect.ssrnat.\nRequire Import tlc.component.component.\nRequire Import tlc.component.perfect_link.\nRequire Import tlc.logic.all_logic.\nRequire Import tlc.semantics.all_semantics.\nRequire Import tlc.syntax.all_syntax.\nRequire Import tlc.utility.all_utility.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLemma L37_1 Delta : Context Delta [::] ||- perfect_link, {-A\n  forall: forall: forall: forall: forall: (* n, n', c, m, m' *)\n  $$4 \\in UCorrect /\\ $$3 \\in UCorrect ->\n  self-event /\\ (on $$4, (0, CSLSend ' $$3 ' ($$2, $$1)) \\in Fors) =>>\n  always^ ~(self-event /\\ on $$4, (0, CSLSend ' $$3 ' ($$2, $$0)) \\in Fors)\n-}.\nProof.\n  dforall n; dforall n'; dforall c; dforall m; dforall m'; dif; dsplitp.\n\n  (* By InvL *)\n  dhave {-A\n    self-event /\\ (on n, (0, CSLSend ' n' ' (c, m)) \\in Fors) =>>\n    (Fs' ' n).1 = c\n  -}.\n  {\n    repeat dclear.\n    eapply DSCut; first by apply DPInvL with (A := {-A\n      on n, (0, CSLSend ' n' ' (c, m)) \\in Fors ->\n      (Fs' ' n).1 = c -});\n      [dautoclosed | repeat constructor].\n\n    (* request *)\n    difp.\n      dforall e; dif; dsplitp; dswap; dsimplp; dsimpl; simpl.\n      dcase {-t ? e -}; dexistsp e_m; dexistsp e_n'; dtgenp;\n        dtsubstep_l; dswap; dclear; dsimplp.\n      dcase {-t ? Fs ' ? Fn -}; dexistsp s_r; dexistsp s_c; dtgenp;\n        dtsubstep_l; dswap; dclear; dsimplp.\n      dtinjectionp; repeat dsplitp.\n\n      dif; dsplitp.\n      dtgenp; dxchg 1 2; dtsubstep_l; dswap; dclear.\n      dtgenp; dtsubste_l; dclear; dsimpl.\n      dswap; dtgenp; dtsubstep_l; dswap; dclear.\n\n      duse DPMemberCons;\n        dforallp {-t (0, CSLSend ' n' ' (c, m)) -};\n        dforallp {-t (0, CSLSend ' e_n' ' (CSucc ' s_c, e_m)) -};\n        dforallp {-t [] -};\n        dsplitp; dswap; dclear; difp; first by [].\n      dorp; last by duse DPMemberNil;\n        dforallp {-t (0, CSLSend ' n' ' (c, m)) -}; dnotp.\n      dtinjectionp; dsplitp; dclear.\n      dsplitp; dclear; dsplitp; dtgenp; dtsubste_l; dautoeq.\n      by repeat dclear; exact: DPEqual.\n\n    (* indication *)\n    difp.\n      dforall i; dforall e; dif; dsplitp; dswap; dsimplp; dsimpl; simpl.\n      dcase {-t (? i, ? e) -}; dexistsp e_m; dexistsp e_c; dexistsp e_n; dtgenp;\n        dtsubstep_l; dswap; dclear; dsimplp.\n      dcase {-t ? Fs ' ? Fn -}; dexistsp s_r; dexistsp s_c; dtgenp;\n        dtsubstep_l; dswap; dclear; dsimplp.\n      dcase {-t FCount ' (? e_n, ? e_c) ' ? s_r == 0 -}; dorp;\n        dtgenp; dtsubstep_l; dswap; dclear; dsimplp;\n        dtinjectionp; repeat dsplitp;\n        dclear; dtgenp; dif; dsplitp; dclear; dswap; dtsubstep_l; dswap; dclear;\n        by duse DPMemberNil; dforallp {-t (0, CSLSend ' n' ' (c, m)) -}; dnotp.\n\n    (* periodic *)\n    difp.\n      dif; dsplitp; dswap; dsimplp; dsimpl; simpl.\n      dtinjectionp; repeat dsplitp;\n      dclear; dtgenp; dif; dsplitp; dclear; dswap; dtsubstep_l; dswap; dclear;\n      by duse DPMemberNil; dforallp {-t (0, CSLSend ' n' ' (c, m)) -}; dnotp.\n\n    by dtmergeentailsifp.\n  }\n\n  (* By InvS *)\n  dhave {-A\n    self-event /\\ (Fs ' n).1 >= c =>>\n    (self-event =>> (Fs ' n).1 >= c)\n  -}.\n  {\n    repeat dclear.\n    eapply DSCut; first by apply DPInvS with\n      (S0 := {-A forall: (* s *) ($$0).1 >= c -});\n      [| dautoclosed | repeat constructor].\n    dforallp n.\n\n    (* request *)\n    difp.\n      dforall s; dforall e; dsimpl; dif.\n      dcase {-t ? s -}; dexistsp s_r; dexistsp s_c;\n        dtgenp; dtsubste_l; dtsubstep_l; dswap; dclear;\n        dautoeq; dsimpl; dsimplp.\n      dcase {-t ? e -}; dexistsp e_n'; dexistsp e_m;\n        dtgenp; dtsubste_l; dclear; dautoeq; dsimpl.\n      by duse DPSuccGreaterEqual; dforallp s_c; dforallp c; difp.\n\n    (* indication *)\n    difp.\n      dforall s; dforall i; dforall e; dsimpl; dif.\n      dcase {-t ? s -}; dexistsp s_r; dexistsp s_c;\n        dtgenp; dtsubste_l; dtsubstep_l; dswap; dclear;\n        dautoeq; dsimpl; dsimplp.\n      dcase {-t (? i, ? e) -}; dexistsp e_m; dexistsp e_c; dexistsp e_n;\n        dtgenp; dtsubste_l; dclear; dautoeq; dsimpl.\n      by dcase {-t FCount ' (? e_n, ? e_c) ' ? s_r == 0 -}; dorp;\n        dtgenp; dtsubste_l; dclear; dsimpl.\n\n    (* periodic *)\n    difp.\n      by dforall s; dsimpl; dif.\n\n    by dsimplp.\n  }\n\n  (* By ASA on (1) and (2) *)\n  dhave {-A\n    on n, self-event /\\ ((0, CSLSend ' n' ' (c, m)) \\in Fors) =>>\n    always^ (self-event -> (Fs ' n).1 >= c)\n  -}.\n  {\n    eapply DSCut; first (by repeat dclear; apply DPASA with\n      (S := {-A forall: (* s *) ($$0).1 >= c -})\n      (A := {-A on n, (0, CSLSend ' n' ' (c, m)) \\in Fors -})\n      (A' := {-A (Fs ' n).1 >= c -});\n      [| dautoclosed | dautoclosed | dautoclosed\n        | repeat constructor | repeat constructor]).\n    dforallp n; dsimplp.\n\n    (* post *)\n    difp.\n      duse DPEqualGreaterEqual; dforallp {-t (Fs' ' n).1 -}; dforallp c.\n      by dtgenp; dclean; dxchg 1 2; dtsubstposp.\n\n    (* pre *)\n    difp.\n      by dassumption.\n\n    eapply DSCut; first (by repeat dclear; apply DSAndAssoc with\n      (A1 := {-A self-event -})\n      (A2 := {-A Fn = n -})\n      (A3 := {-A (0, CSLSend ' n' ' (c, m)) \\in Fors -}));\n      dtgenp; dclean; dtsubstp_r.\n    eapply DSCut; first (by repeat dclear; apply DSAndComm with\n      (A1 := {-A self-event -})\n      (A2 := {-A Fn = n -}));\n      dtgenp; dclean; dtsubstp_l.\n    eapply DSCut; first (by repeat dclear; apply DSAndAssoc with\n      (A1 := {-A Fn = n -})\n      (A2 := {-A self-event -})\n      (A3 := {-A (0, CSLSend ' n' ' (c, m)) \\in Fors -}));\n      dtgenp; dclean; dtsubstp_l.\n    by [].\n  }\n\n  (* By InvL *)\n  dhave {-A\n    self-event /\\ (Fs ' n).1 >= c =>>\n    ~(on n, (0, CSLSend ' n' ' (c, m')) \\in Fors)\n  -}.\n  {\n    repeat dclear.\n    eapply DSCut; first by apply DPInvL with (A := {-A\n      (Fs ' n).1 >= c ->\n      ~(on n, (0, CSLSend ' n' ' (c, m')) \\in Fors)\n    -}); [dautoclosed | repeat constructor].\n\n    (* request *)\n    difp.\n      dforall e; dif; dsplitp; dswap; dsimplp.\n      dcase {-t ? e -}; dexistsp e_m; dexistsp e_n'; dtgenp;\n        dtsubstep_l; dswap; dclear; dsimplp.\n      dcase {-t ? Fs ' ? Fn -}; dexistsp s_r; dexistsp s_c; dtgenp;\n        dtsubstep_l; dsimplp.\n      dtinjectionp; repeat dsplitp.\n\n      dswap; dtgenp; dtsubste_l; dclear.\n      dif; dnot.\n      dsplitp; dtgenp.\n      dxchg 1 3; dtsubstep_l; dswap.\n      dxchg 1 5; dtsubstep_l; dswap; dclear.\n      dtsubstep_l; dswap; dclear; dsimplp.\n\n      duse DPMemberCons;\n        dforallp {-t (0, CSLSend ' n' ' (c, m')) -};\n        dforallp {-t (0, CSLSend ' e_n' ' (CSucc ' s_c, e_m)) -};\n        dforallp {-t [] -};\n        dsplitp; dswap; dclear; difp; first by dassumption.\n      dorp; last by duse DPMemberNil;\n        dforallp {-t (0, CSLSend ' n' ' (c, m')) -}; dnotp.\n      dtinjectionp; dsplitp; dclear.\n      dsplitp; dclear; dsplitp; dswap; dclear; dtgenp;\n        dtsubstep_l; dautoeq; dswap; dclear.\n\n      duse DPGreaterEqual; dforallp s_c; dforallp {-t s_c.+1 -}.\n      dsplitp; dswap; dclear; difp; first (by []); dswap; dclear; dorp.\n      - (* equal *)\n        eapply DSCut; first by eapply DSubInjection with\n          (t1 := {-t s_c -}) (t2 := {-t s_c.+1 -}); [by [] | auto_mem].\n        by dnotp.\n      - (* not equal *)\n        duse DPNotLessThanIfGreaterThan; dforallp s_c; dforallp {-t s_c.+1 -}.\n        difp; last by dnotp.\n        by duse DPLessThanSucc; dforallp s_c.\n\n    (* indication *)\n    difp.\n      dforall i; dforall e; dif; dsplitp; dswap; dsimplp.\n      dcase {-t (? i, ? e) -}; dexistsp e_m; dexistsp e_c; dexistsp e_n;\n        dtgenp; dtsubstep_l; dswap; dclear; dsimplp.\n      dcase {-t ? Fs ' ? Fn -}; dexistsp s_r; dexistsp s_c; dtgenp;\n        dtsubstep_l; dsimplp.\n      by dcase {-t FCount ' (? e_n, ? e_c) ' ? s_r == 0 -}; dorp;\n        dtgenp; dtsubstep_l; dswap; dclear; dsimplp;\n        dtinjectionp; repeat dsplitp;\n        dif; dclear; dnot; dsplitp; dclear;\n        dswap; dxchg 0 2; dtgenp; dtsubstep_l; dswap; dclear;\n        duse DPMemberNil; dforallp {-t (0, CSLSend ' n' ' (c, m')) -}; dnotp.\n\n    (* periodic *)\n    difp.\n      dif; dsplitp; dclear; dsimplp.\n      by dtinjectionp; repeat dsplitp;\n        dif; dclear; dnot; dsplitp; dclear;\n        dswap; dxchg 0 2; dtgenp; dtsubstep_l; dswap; dclear;\n        duse DPMemberNil; dforallp {-t (0, CSLSend ' n' ' (c, m')) -}; dnotp.\n\n    by dtmergeentailsifp.\n  }\n\n  (* From (3) and (4) *)\n  dhave {-A\n    (self-event -> (Fs ' n).1 >= c) ->\n    (self-event -> (self-event /\\ (Fs ' n).1 >= c))\n  -}; first by repeat dif; dsplit; [| dswap; difp].\n  dtgenp; dclean.\n  dxchg 1 2; dtsubstposp.\n  dswap; dtsubstposp.\n  dhave {-A\n    (self-event -> ~ on n, (0, CSLSend ' n' ' (c, m')) \\in Fors) ->\n    ~ (self-event /\\ on n, (0, CSLSend ' n' ' (c, m')) \\in Fors)\n  -}; first by dif; dnot; dsplitp; dxchg 1 2; dswap; difp; [| dnotp; dassumption].\n  dtgenp; dclean.\n  dtsubstposp.\n\n  eapply DSCut; first (by repeat dclear; apply DSAndAssoc with\n    (A1 := {-A Fn = n -})\n    (A2 := {-A self-event -})\n    (A3 := {-A (0, CSLSend ' n' ' (c, m)) \\in Fors -}));\n    dtgenp; dclean; dtsubstp_r.\n  eapply DSCut; first (by repeat dclear; apply DSAndComm with\n    (A1 := {-A Fn = n -})\n    (A2 := {-A self-event -}));\n    dtgenp; dclean; dtsubstp_l.\n  eapply DSCut; first (by repeat dclear; apply DSAndAssoc with\n    (A1 := {-A self-event -})\n    (A2 := {-A Fn = n -})\n    (A3 := {-A (0, CSLSend ' n' ' (c, m)) \\in Fors -}));\n    dtgenp; dclean; dtsubstp_l.\n  by [].\nQed.\n\nLemma L37_2 Delta : Context Delta [::] ||- perfect_link, {-A\n  forall: forall: forall: forall: forall: (* n, n', c, m, m' *)\n  $$4 \\in UCorrect /\\ $$3 \\in UCorrect ->\n  self-event /\\ (on $$4, (0, CSLSend ' $$3 ' ($$2, $$1)) \\in Fors) =>>\n  alwaysp^ ~(self-event /\\ on $$4, (0, CSLSend ' $$3 ' ($$2, $$0)) \\in Fors)\n-}.\nProof.\n  dforall n; dforall n'; dforall c; dforall m; dforall m'; dif.\n\n  (* By L37_1 *)\n  duse L37_1; dforallp n; dforallp n'; dforallp c; dforallp m; dforallp m';\n    difp; first by [].\n\n  eapply DSCut; first (by repeat dclear; apply DTL105_1 with\n    (H := {-A self-event /\\ on n, (0, CSLSend ' n' ' (c, m)) \\in Fors -})\n    (A := {-A self-event /\\ on n, (0, CSLSend ' n' ' (c, m')) \\in Fors -})).\n  by dtsubstposp.\nQed.\n\nLemma L39 Delta : Context Delta [::] ||- perfect_link, {-A\n  forall: forall: forall: forall: (* n, n', m, c *)\n  $$3 \\in UCorrect /\\ $$2 \\in UCorrect ->\n  on $$2, event[0]<- CSLDeliver ' $$3 ' ($$0, $$1) /\\\n    ($$3, $$0) \\notin (Fs ' $$2).2 ~>\n  on $$2, event[]<- CPLDeliver ' $$3 ' $$1\n -}.\nProof.\n  dforall n; dforall n'; dforall m; dforall c.\n  dif; dsplitp.\n\n  duse DPOI; dforallp n'; dforallp {-t CPLDeliver ' n ' m -}; dsimplp.\n  eapply DSCut; first (by repeat dclear; apply DTL121 with\n    (A := {-A on n', event[]<- CPLDeliver ' n ' m -}));\n    dtsubstposp.\n\n  dhave {-A\n    on n', event[0]<- CSLDeliver ' n ' (c, m) /\\ (n, c) \\notin (Fs ' n').2 ->\n    on n', self-event /\\ CPLDeliver ' n ' m \\in Fois\n  -}.\n  {\n    repeat dclear.\n    dif; dsplitp; dswap; dsplitp.\n    dsplit; first by dassumption.\n    dsplit; first by dleft; dexists {-t 0 -};\n      dsplit; dsplitp; [| dclear; dsplitp].\n    duse DPII; dforallp {-t 0 -}; dforallp {-t CSLDeliver ' n ' (c, m) -};\n      dsimplp; dsplitp; dswap; dclear; difp; first by dassumption.\n    dswap; dxchg 0 3; dtgenp; dtsubstep_l; dswap; dclear.\n    dcase {-t ? Fs ' ? n' -}; dexistsp s_r; dexistsp s_c;\n      dtgenp; dtsubstep_l; dsimplp.\n    dswap; dxchg 1 2; dtsubstep_l; dswap; dclear; dswap.\n    dcase {-t FCount ' (? n, ? c) ' ? s_r == 0 -}; dorp;\n      dtgenp; dtsubstep_l; dsimplp.\n    - dswap; dclear; dtinjectionp; repeat dsplitp.\n      dxchg 0 2; dtgenp; dtsubste_l.\n      by duse DPMemberSingleton; dforallp {-t CPLDeliver ' n ' m -}.\n    - dclear; dswap; dsimplp.\n      duse DPMemberReflect; dforallp {-t (n, c) -}; dforallp s_r.\n      dxchg 1 2; dswap; dtsubstep_l; dsimplp; dswap; dclear;\n        dsplitp; dswap; dclear; difp; first by repeat dclear; exact: DPEqual.\n      by dswap; dnotp.\n  }\n  dtgenp; dclean.\n\n  by rewrite /AFollowedBy; dswap; dttransp.\nQed.\n\nLemma L41 Delta : Context Delta [::] ||- perfect_link, {-A\n  forall: forall: forall: (* n, n', c *)\n  $$2 \\in UCorrect /\\ $$1 \\in UCorrect ->\n  self-event /\\ ($$2, $$0) \\in (Fs ' $$1).2 =>>\n  exists: (* m *)\n    eventuallyp (on $$2, event[0]<- CSLDeliver ' $$3 ' ($$1, $$0) /\\\n      CPLDeliver ' $$3 ' $$0 \\in Fois)\n -}.\nProof.\n  dforall n; dforall n'; dforall c; dif; dsplitp.\n\n  (* Instantiate InvSA *)\n  eapply DSCut; first (by repeat dclear; apply DPInvSA with\n    (S0 := {-A forall: (* s *) (n, c) \\in ($$0).2 -})\n    (A := {-A exists: (* m *)\n      (on n', event[0]<- CSLDeliver ' n ' (c, $$0) /\\\n        CPLDeliver ' n ' $$0 \\in Fois) -});\n    [| dautoclosed | dautoclosed | repeat constructor | repeat constructor]);\n  dforallp n'.\n\n  (* initialize *)\n  difp.\n    repeat dsimpl.\n    by duse DPMemberNil; dforallp {-t (n, c) -}.\n\n  (* request *)\n  difp.\n    dforall e; dif; dsplitp; dswap; dsplitp; dswap; dsplitp; dsimplp.\n    dcase {-t ? Fs ' ? Fn -}; dexistsp s_r; dexistsp s_c; dtgenp; dtsubstep_l;\n      dsimplp.\n    dcase {-t ? e -}; dexistsp e_m; dexistsp e_n; dtgenp; dtsubstep_l;\n      dautoeq; dsimplp.\n    dtinjectionp; repeat dsplitp.\n\n    dxchg 1 5; dtgenp; dtsubstep_l.\n    dxchg 1 4; dswap; dtsubstep_l; dautoeq.\n    repeat dsimplp; dsplitp.\n    by dnotp.\n\n  (* indication *)\n  difp.\n    dforall i; dforall e; dif; dsplitp; dswap; dsplitp; dswap; dsplitp; dsimplp.\n    dcase {-t ? Fs ' ? Fn -}; dexistsp s_r; dexistsp s_c; dtgenp; dtsubstep_l;\n      dsimplp.\n    dcase {-t (? i, ? e) -}; dexistsp e_m; dexistsp e_c; dexistsp e_n;\n      dtinjectionp; dsplitp;\n      dtgenp; dxchg 1 2; dtsubstep_l;\n        dswap; dxchg 1 5; dtsubstep_l;\n        dswap; dclear; dswap; dautoeq;\n      dtgenp; dtsubstep_l;\n        dswap; dxchg 1 4; dtsubstep_l;\n        dswap; dclear; dautoeq;\n      dsimplp.\n    dcase {-t FCount ' (? e_n, ? e_c) ' ? s_r == 0 -}; dorp;\n      dtgenp; dtsubstep_l; dswap; dclear; dsimplp;\n      dtinjectionp; repeat dsplitp;\n      dxchg 1 4; dtgenp; dtsubstep_l; dswap; dclear;\n      dxchg 1 2; dswap; dtsubstep_l; dswap; dclear;\n      repeat dsimplp; dsplitp;\n      try by dnotp.\n    dexists e_m; dswap.\n    duse DPMemberSetUnion;\n      dforallp s_r; dforallp {-t [(e_n, e_c)] -}; dforallp {-t (n, c ) -};\n      dsplitp; dclear; difp; [by [] |]; dswap; dclear; dorp;\n      first by dswap; dnotp.\n    duse DPMemberCons;\n      dforallp {-t (n, c ) -}; dforallp {-t (e_n, e_c) -}; dforallp {-t [] -};\n      dsplitp; dswap; dclear; difp; [by [] |]; dswap; dclear; dorp;\n      last by duse DPMemberNil; dforallp {-t (n, c) -}; dnotp.\n    dswap; dclear; dxchg 0 2; dclear.\n    dsplit; first by dassumption.\n    dtgenp; dtsubste_l; dclear.\n    dtinjectionp; dsplitp; repeat (dtgenp; dtsubste_l; dautoeq; dclear).\n    dsplit; [by [] | dclear].\n    by duse DPMemberSingleton; dforallp {-t CPLDeliver ' e_n ' e_m -}.\n\n  (* periodic *)\n  difp.\n    dsimpl; repeat dclear; dif; repeat (dsplitp; dswap).\n    dxchg 0 2; dtinjectionp; repeat dsplitp.\n    do 2 (dswap; dclear); dtgenp; dxchg 1 2; dtsubstep_l; dswap; dclear.\n    by dswap; dnotp.\n\n  dsimplp.\n  rewrite /AOn; dexistsandclosed_l; dtgenp; dclean; dtsubstp_l.\n  rewrite /AOn; dtandelimselfap.\n  rewrite /AOn; dexistsandclosed_r; dtgenp; dclean; dtsubstp_r.\n  dteventuallyp'p.\n\n  set A := {-A on n', event[0]<- CSLDeliver ' n ' (c, $$0) /\\\n    CPLDeliver ' n ' $$0 \\in Fois -}.\n  dhave {-A\n    (eventuallyp exists: A) <=> (exists: eventuallyp A)\n  -}; first by apply DTL127_3.\n  by dtsubstp_l.\nQed.\n\nLemma L40 Delta : Context Delta [::] ||- perfect_link, {-A\n  forall: forall: forall: (* n, n', c *)\n  $$2 \\in UCorrect /\\ $$1 \\in UCorrect ->\n  self-event /\\ (on $$1, ($$2, $$0) \\in (Fs ' $$1).2) =>>\n  exists: (* m *)\n    eventuallyp (on $$3, (0, CSLSend ' $$2 ' ($$1, $$0)) \\in Fors /\\\n      self-event /\\\n      eventually on $$2, event[]<- CPLDeliver ' $$3 ' $$0)\n -}.\nProof.\n  dforall n; dforall n'; dforall c; dif.\n\n  (* By Lemma 41 *)\n  duse L41; dforallp n; dforallp n'; dforallp c; difp; first by [].\n\n  (* By SL_2 *)\n  duse PL_SL_2; dforallp n'; dforallp n.\n\n  (* By OR' *)\n  dhave {-A\n    forall: (* m *)\n    on n, event[0]-> CSLSend ' n' ' (c, $$0) =>>\n    eventuallyp (self-event /\\ on n, (0, CSLSend ' n' ' (c, $$0)) \\in Fors)\n  -}.\n  {\n    dforall m.\n    duse DPOR'; dforallp n; dforallp {-t 0 -}; dforallp {-t CSLSend ' n' ' (c, m) -}.\n    by eapply DSCut; first (by repeat dclear; apply DTL123 with\n      (A := {-A self-event /\\ on n, (0, CSLSend ' n' ' (c, m)) \\in Fors -}));\n      dtsubstposp.\n  }\n\n  (* By Lemma 85 on (2) and (3) *)\n  dhave {-A\n    forall: (* m *)\n    on n', event[0]<- CSLDeliver ' n ' (c, $$0) =>>\n    eventuallyp (self-event /\\ on n, (0, CSLSend ' n' ' (c, $$0)) \\in Fors)\n  -}.\n  {\n    dforall m; dswap; dforallp {-t (c, m) -}.\n    eapply DTL85; first by dhead.\n    by dswap; dforallp m.\n  }\n  do 2 (dswap; dclear).\n\n  (* By OI *)\n  dhave {-A\n    forall: (* m *)\n    on n', self-event /\\ CPLDeliver ' n ' $$0 \\in Fois =>>\n    eventually (on n', event[]<- CPLDeliver ' n ' $$0)\n  -}.\n  {\n    dforall m.\n    duse DPOI; dforallp n'; dforallp {-t CPLDeliver ' n ' m -}.\n    by eapply DSCut; first (by repeat dclear; apply DTL121 with\n      (A := {-A on n', event[]<- CPLDeliver ' n ' m -}));\n      dtsubstposp.\n  }\n\n  (* By (1), (4), and (5) *)\n  dhave {-A\n    self-event /\\ (n, c) \\in (Fs ' n').2 =>>\n    exists: (* m *)\n      eventuallyp (eventuallyp (self-event /\\\n        (on n, (0, CSLSend ' n' ' (c, $$0)) \\in Fors)) /\\\n        eventually on n', event []<- CPLDeliver ' n ' $$0)\n  -}.\n  {\n    dswap; dxchg 1 2; dswap.\n    eapply DSCut; first (by repeat dclear; apply DSAndElimSelf with\n      (A := {-A Fn = n' -}));\n      dtgenp; dclean; dtsubstp_r.\n    eapply DSCut; first (by repeat dclear; apply DTAndAssoc with\n      (A1 := {-A Fn = n' -})\n      (A2 := {-A Fn = n' -})\n      (A3 := {-A event[0]<- CSLDeliver ' n ' (c, $$0) /\\\n        CPLDeliver ' n ' $$0 \\in Fois -}));\n      dtsubstp_l.\n    eapply DSCut; first (by apply DSAndComm with\n      (A1 := {-A Fn = n' -})\n      (A2 := {-A event[0]<- CSLDeliver ' n ' (c, $$0) /\\\n        CPLDeliver ' n ' $$0 \\in Fois -}));\n      dtgenp; dclean; dtsubstp_l.\n    eapply DSCut; first (by repeat dclear; apply DTAndAssoc with\n      (A1 := {-A event[0]<- CSLDeliver ' n ' (c, $$0) -})\n      (A2 := {-A CPLDeliver ' n ' $$0 \\in Fois -})\n      (A3 := {-A Fn = n' -}));\n      dtsubstp_l.\n    eapply DSCut; first (by apply DSAndComm with\n      (A1 := {-A CPLDeliver ' n ' $$0 \\in Fois -})\n      (A2 := {-A Fn = n' -}));\n      dtgenp; dclean; dtsubstp_l.\n    eapply DSCut; first (by repeat dclear; apply DTAndAssoc with\n      (A1 := {-A Fn = n' -})\n      (A2 := {-A event[0]<- CSLDeliver ' n ' (c, $$0) -})\n      (A3 := {-A on n', CPLDeliver ' n ' $$0 \\in Fois -}));\n      dtsubstp_r.\n    eapply DSCut; first (by repeat dclear; apply DSAndElimSelf with\n      (A := {-A event[0]<- CSLDeliver ' n ' (c, $$0) -}));\n      dtgenp; dclean; dtsubstp_r.\n    eapply DSCut; first (by repeat dclear; apply DTAndAssoc with\n      (A1 := {-A Fn = n' -})\n      (A2 := {-A event[0]<- CSLDeliver ' n ' (c, $$0) -})\n      (A3 := {-A event[0]<- CSLDeliver ' n ' (c, $$0) -}));\n      dtsubstp_r.\n    eapply DSCut; first (by repeat dclear; apply DTAndAssoc with\n      (A1 := {-A on n', event[0]<- CSLDeliver ' n ' (c, $$0) -})\n      (A2 := {-A event[0]<- CSLDeliver ' n ' (c, $$0) -})\n      (A3 := {-A on n', CPLDeliver ' n ' $$0 \\in Fois -}));\n      dtsubstp_l.\n    eapply DSCut; first (by repeat dclear; apply DTAndAssoc with\n      (A1 := {-A event[0]<- CSLDeliver ' n ' (c, $$0) -})\n      (A2 := {-A Fn = n' -})\n      (A3 := {-A CPLDeliver ' n ' $$0 \\in Fois -}));\n      dtsubstp_r.\n    eapply DSCut; first (by apply DSAndComm with\n      (A1 := {-A event[0]<- CSLDeliver ' n ' (c, $$0) -})\n      (A2 := {-A Fn = n' -}));\n      dtgenp; dclean; dtsubstp_l.\n    eapply DSCut; first (by repeat dclear; apply DTAndAssoc with\n      (A1 := {-A Fn = n' -})\n      (A2 := {-A event[0]<- CSLDeliver ' n ' (c, $$0) -})\n      (A3 := {-A CPLDeliver ' n ' $$0 \\in Fois -}));\n      dtsubstp_l.\n    dswap; dtsubstposp.\n    duse DPSubIndicationSelf; dtsubstposp.\n    by dswap; dtsubstposp.\n  }\n  do 3 (dswap; dclear).\n\n  eapply DSCut; first (by repeat dclear; apply DTL126 with\n    (A1 := {-A self-event /\\ on n, (0, CSLSend ' n' ' (c, $$0)) \\in Fors -})\n    (A2 := {-A on n', event[]<- CPLDeliver ' n ' $$0 -}));\n    dtsubstposp.\n  eapply DSCut; first (by apply DSAndComm with\n    (A1 := {-A self-event -})\n    (A2 := {-A on n, (0, CSLSend ' n' ' (c, $$0)) \\in Fors -}));\n    dtgenp; dclean; dtsubstp_l.\n  eapply DSCut; first (by repeat dclear; apply DTAndAssoc with\n    (A1 := {-A on n, (0, CSLSend ' n' ' (c, $$0)) \\in Fors -})\n    (A2 := {-A self-event -})\n    (A3 := {-A eventually (on n', event[]<- CPLDeliver ' n ' $$0) -}));\n    dtsubstp_l.\n  eapply DSCut; first (by repeat dclear; apply DTAndAssoc with\n    (A1 := {-A Fn = n -})\n    (A2 := {-A (0, CSLSend ' n' ' (c, $$0)) \\in Fors -})\n    (A3 := {-A self-event /\\ eventually (on n', event[]<- CPLDeliver ' n ' $$0) -}));\n    dtsubstp_l.\n\n  dhave {-A on n', (n, c) \\in (Fs ' n').2 =>> (n, c) \\in (Fs ' n').2 -};\n    first by dtgen; dif; dsplitp; dassumption.\n  by dtsubstnegp.\nQed.\n\nLemma L38 Delta : Context Delta [::] ||- perfect_link, {-A\n  forall: forall: forall: forall: (* n, n', m, c *)\n  $$3 \\in UCorrect /\\ $$2 \\in UCorrect ->\n  on $$2, event[0]<- CSLDeliver ' $$3 ' ($$0, $$1) =>>\n  eventually (on $$2, event[]<- CPLDeliver ' $$3 ' $$1) \\/\n  exists: (* m' *)\n    eventuallyp (on $$4, (0, CSLSend ' $$3 ' ($$1, $$0)) \\in Fors /\\ self-event /\\\n      eventually on $$3, event[]<- CPLDeliver ' $$4 ' $$0)\n -}.\nProof.\n  dforall n; dforall n'; dforall m; dforall c; dif.\n\n  dhave {-A (n, c) \\notin (Fs ' n').2 \\/ (n, c) \\in (Fs ' n').2 -}.\n  {\n    duse DPMemberReflect; dforallp {-t (n, c) -}; dforallp {-t (Fs ' n').2 -};\n      dtgenp; dclean; dtsubst_l; dclear.\n    dcase {-t FCount ' (? n, ? c) ' (? Fs ' ? n').2 == 0 -}; dorp;\n      dtgenp; dtsubste_l; dclear; dsimpl; repeat dclear;\n      by dif.\n  }\n\n  eapply DSCut; first (by eapply DTEntailsAlwaysC with\n    (H := {-A on n', event[0]<- CSLDeliver ' n ' (c, m) -});\n    dtgenp; dhead); dswap; dclear.\n  eapply DSCut; first (by apply DTEntailsTautology with\n    (A := {-A on n', event[0]<- CSLDeliver ' n ' (c, m) -}));\n    rewrite -DTEntailsAndSplitP.\n  eapply DSCut; first (by apply DSOrDistribAnd2 with\n    (A := {-A on n', event[0]<- CSLDeliver ' n ' (c, m) -})\n    (A1 := {-A (n, c) \\notin (Fs ' n').2 -})\n    (A2 := {-A (n, c) \\in (Fs ' n').2 -}));\n    dtgenp; dclean; dtsubstp_l.\n\n  (* Align false case with L39 precondition *)\n  dhave {-A\n    (on n', event[0]<- CSLDeliver ' n ' (c, m)) /\\ (n, c) \\notin (Fs ' n').2 =>>\n    on n', event[0]<- CSLDeliver ' n ' (c, m) /\\ (n, c) \\notin (Fs ' n').2\n  -}.\n  {\n    repeat dclear; dtgen; dif; repeat dsplitp.\n    by dsplit; [| dsplit]; dassumption.\n  }\n  dtsubstposp.\n\n  (* Align true case with L40 precondition *)\n  dhave {-A\n    (on n', event[0]<- CSLDeliver ' n ' (c, m)) /\\ (n, c) \\in (Fs ' n').2 =>>\n    self-event /\\ (on n', (n, c) \\in (Fs ' n').2)\n  -}.\n  {\n    repeat dclear; dtgen; dif; repeat dsplitp.\n    dsplit; last by dsplit; dassumption.\n    by dswap; duse DPSubIndicationSelf; dtsubstposp.\n  }\n  dtsubstposp.\n\n  (* By Lemma 39 *)\n  duse L39; dforallp n; dforallp n'; dforallp m; dforallp c; difp; first by dassumption.\n  dtsubstposp.\n\n  (* By Lemma 40 *)\n  duse L40; dforallp n; dforallp n'; dforallp c; difp; first by dassumption.\n  dtsubstposp.\n\n  by [].\nQed.\n\n(* Reliable delivery\n * If a correct node n sends a message m to a correct node n', then n' will\n * eventually deliver m.\n *)\nTheorem PL_1 Delta : Context Delta [::] ||- perfect_link, {-A\n  forall: forall: forall: (* n, n', m *)\n  $$2 \\in UCorrect /\\ $$1 \\in UCorrect ->\n  on $$2, event[]-> CPLSend ' $$1 ' $$0 ~>\n  on $$1, event[]<- CPLDeliver ' $$2 ' $$0\n -}.\nProof.\n  dforall n; dforall n'; dforall m; dif; dsplitp.\n\n  (* By IR *)\n  dhave {-A\n    exists: (* c *)\n    on n, event[]-> CPLSend ' n' ' m =>>\n    self-event /\\ on n, (0, CSLSend ' n' ' ($$0, m)) \\in Fors\n  -}.\n  {\n    duse DPIR; dforallp {-t CPLSend ' n' ' m -}; dsimplp.\n    dcase {-t ? Fs ' ? Fn -}; dexistsp r; dexistsp c; dtgenp;\n      dtsubstep_l; dswap; dclear; dsimplp; dtinjectionp.\n    dexists {-t c.+1 -}; dtgen; dsplitp; dswap; dclear.\n    dif; dsplitp; dxchg 0 2; difp; first by dassumption.\n    repeat dsplitp.\n    dsplit; first by dxchg 0 3; duse DPTopRequestSelf; dtsubstposp.\n    dsplit; first by dassumption.\n    dclear; dtgenp; dtsubste_l; dclear.\n    by duse DPMemberSingleton; dforallp {-t (0, CSLSend ' n' ' (c.+1, m)) -}.\n  }\n  dexistsp c.\n\n  (* By OR *)\n  dhave {-A\n    (self-event /\\ on n, ((0, CSLSend ' n' ' (c, m)) \\in Fors)) =>>\n    eventually (on n, event[0]-> CSLSend ' n' ' (c, m))\n  -}.\n  {\n    repeat dclear.\n\n    duse DPOR; dforallp n; dforallp {-t 0 -}; dforallp {-t CSLSend ' n' ' (c, m) -}.\n    eapply DSCut; first (by apply DTEventually' with\n      (A := {-A on n, event[0]-> CSLSend ' n' ' (c, m) -}));\n      dtsubstposp.\n    eapply DSCut; first (by repeat dclear; apply DTAndAssoc with\n      (A1 := {-A Fn = n -})\n      (A2 := {-A self-event -})\n      (A3 := {-A (0, CSLSend ' n' ' (c, m)) \\in Fors -}));\n      dtsubstp_r.\n    eapply DSCut; first (by repeat dclear; apply DSAndComm with\n      (A1 := {-A Fn = n -})\n      (A2 := {-A self-event -}));\n      dtgenp; dclean; dtsubstp_l.\n    eapply DSCut; first (by repeat dclear; apply DTAndAssoc with\n      (A1 := {-A self-event -})\n      (A2 := {-A Fn = n -})\n      (A3 := {-A (0, CSLSend ' n' ' (c, m)) \\in Fors -}));\n      dtsubstp_l.\n\n    by [].\n  }\n  dtsubstposp_keep; dswap; dclear; dswap; rewrite -DTEntailsAndSplitP.\n  eapply DSCut; first (by repeat dclear; apply DTAndAssoc with\n    (A1 := {-A self-event -})\n    (A2 := {-A on n, (0, CSLSend ' n' ' (c, m)) \\in Fors -})\n    (A3 := {-A eventually on n, event[0]-> CSLSend ' n' ' (c, m) -}));\n    dtsubstp_l.\n\n  (* By SL_1 and Axiom 1 *)\n  dhave {-A\n    on n, event[0]-> CSLSend ' n' ' (c, m) ~>\n    on n', event[0]<- CSLDeliver ' n ' (c, m)\n  -}.\n  {\n    duse PL_SL_1; dforallp n; dforallp n'; dforallp {-t (c, m) -};\n      difp; first by dsplit; dassumption.\n    by rewrite DTEntailsAndSplitP.\n  }\n\n  (* By Lemma 86 on (1) and (2) *)\n  (* It is quicker to rewrite (2) into (1) and use Lemma 120 *)\n  dtsubstposp; eapply DSCut; first (by apply DTL120_1 with\n    (A := {-A on n', event[0]<- CSLDeliver ' n ' (c, m) -}));\n    dtsubstp_r.\n\n  (* By Lemma 96 on (3) and Lemma 38 *)\n  dhave {-A\n    on n, event[]-> CPLSend ' n' ' m =>>\n    self-event /\\ (on n, (0, CSLSend ' n' ' (c, m)) \\in Fors) /\\\n    eventually (eventually (on n', event[]<- CPLDeliver ' n ' m) \\/\n      exists: (* m *) eventuallyp ((self-event /\\\n        on n, (0, CSLSend ' n' ' (c, $$0)) \\in Fors) /\\\n        eventually on n', event[]<- CPLDeliver ' n ' $$0))\n  -}.\n  {\n    duse L38; dforallp n; dforallp n'; dforallp m; dforallp c; difp;\n      first by dsplit; dassumption.\n    (* It is quicker to rewrite L38 into (3) *)\n    dtsubstposp.\n    eapply DSCut; first (by repeat dclear; apply DTAndAssoc with\n      (A1 := {-A Fn = n -})\n      (A2 := {-A (0, CSLSend ' n' ' (c, $$0)) \\in Fors -})\n      (A3 := {-A self-event /\\ eventually (on n', event[]<- CPLDeliver ' n ' $$0) -}));\n      dtsubstp_r.\n    eapply DSCut; first (by repeat dclear; apply DTAndAssoc with\n      (A1 := {-A on n, (0, CSLSend ' n' ' (c, $$0)) \\in Fors -})\n      (A2 := {-A self-event -})\n      (A3 := {-A eventually (on n', event[]<- CPLDeliver ' n ' $$0) -}));\n      dtsubstp_r.\n    eapply DSCut; first (by repeat dclear; apply DSAndComm with\n      (A1 := {-A on n, (0, CSLSend ' n' ' (c, $$0)) \\in Fors -})\n      (A2 := {-A self-event -}));\n      dtgenp; dtsubstp_l.\n    by [].\n  }\n  dswap; dclear.\n\n  (* That is *)\n  dteventuallyorcomm; dtsubstp_l.\n  dteventuallyexistscomm; dtsubstp_l.\n  dteventuallyidemp; dtsubstp_r.\n  match goal with\n  | |- context[ {-A eventually eventuallyp ?A_ -} ] =>\n    eapply DSCut; first (by repeat dclear; apply DTL109_3 with (A := A_))\n  end; dtsubstposp.\n\n  (* By Lemma 37 *)\n  dhave {-A\n    on n, event[]-> CPLSend ' n' ' m =>>\n    self-event /\\ (on n, (0, CSLSend ' n' ' (c, m)) \\in Fors) /\\\n    (eventually (on n', event[]<- CPLDeliver ' n ' m) \\/\n      exists: (* m *) (self-event /\\\n        (on n, (0, CSLSend ' n' ' (c, $$0)) \\in Fors) /\\\n        eventually on n', event[]<- CPLDeliver ' n ' $$0))\n  -}.\n  {\n    match goal with\n    | |- context[ {-A self-event /\\ ?A2_ /\\ ?A3_ -} ] =>\n      eapply DSCut; first (by repeat dclear; apply DTAndAssoc with\n        (A1 := {-A self-event -}) (A2 := A2_) (A3 := A3_))\n    end; dtsubstp_r.\n\n    eapply DSCut; first (by repeat dclear; apply DTAndElimSelf with\n      (A := {-A self-event /\\ on n, (0, CSLSend ' n' ' (c, m)) \\in Fors -}));\n      dtsubstp_r.\n    match goal with\n    | |- context[ {-A (?A1_ /\\ ?A1_) /\\ ?A3_ -} ] =>\n      eapply DSCut; first (by repeat dclear; apply DTAndAssoc with\n        (A1 := A1_) (A2 := A1_) (A3 := A3_))\n    end; repeat dautoeq; dtsubstp_l.\n    dtordistrib2_2.\n\n    dtandintoexists; dtsubstposp.\n    match goal with\n    | |- context[ {-A exists: ?A1_ /\\ (?A2_ \\/ ?A3_) -} ] =>\n      set A1 := A1_; set A2 := A2_; set A3 := A3_\n    end.\n\n    dhave {-A\n      A1 /\\ (A2 \\/ A3) <=>\n      A1 /\\ A2 \\/ A1 /\\ A3\n    -}; first (by repeat dclear; apply DTOrDistrib2); dtsubstp_l.\n    eapply DSCut; first (by repeat dclear; eapply DTAndComm with\n      (A1 := A1) (A2 := A2)); dtsubstp_l.\n    eapply DSCut; first (by repeat dclear; eapply DTAndComm with\n      (A1 := A1) (A2 := A3)); dtsubstp_l.\n\n    (* Future case *)\n    set A1' := {-A always^ ~(self-event /\\ on n, (0, CSLSend ' n' ' (c, $$0)) \\in Fors) -}.\n    rewrite -/A1 -/A2 -/A3.\n    dhave {-A\n      forall:\n      (A2 /\\ A1) =>>\n      (A2 /\\ A1')\n    -}; first (by dforall m'; dtandha_l; dsplitp; dswap; dclear; dsplitp; dclear; difp;\n      first by duse L37_1; dforallp n; dforallp n'; dforallp c; dforallp m; dforallp m'; difp;\n      first by dsplit; dassumption); dtsubstposp.\n    eapply DSCut; first (by repeat dclear; apply DTL103_1 with\n      (A1 := {-A self-event /\\ on n, (0, CSLSend ' n' ' (c, $$0)) \\in Fors -})\n      (A2 := {-A eventually on n', event[]<- CPLDeliver ' n ' $$0 -}));\n      dtsubstposp.\n    clear A1'.\n\n    (* Past case *)\n    set A1' := {-A alwaysp^ ~(self-event /\\ on n, (0, CSLSend ' n' ' (c, $$0)) \\in Fors) -}.\n    rewrite -/A1 -/A2 -/A3.\n    dhave {-A\n      forall:\n      (A3 /\\ A1) =>>\n      (A3 /\\ A1')\n    -}; first (by dforall m'; dtandha_l; dsplitp; dswap; dclear; dsplitp; dclear; difp;\n      first by duse L37_2; dforallp n; dforallp n'; dforallp c; dforallp m; dforallp m'; difp;\n      first by dsplit; dassumption); dtsubstposp.\n    eapply DSCut; first (by repeat dclear; apply DTL103_2 with\n      (A1 := {-A self-event /\\ on n, (0, CSLSend ' n' ' (c, $$0)) \\in Fors -})\n      (A2 := {-A eventually on n', event[]<- CPLDeliver ' n ' $$0 -}));\n      dtsubstposp.\n    clear A1'.\n\n    clear A1 A2 A3.\n    set A1 := {-A self-event /\\ (on n, (0, CSLSend ' n' ' (c, $$0)) \\in Fors) -}.\n    set A2 := {-A eventually on n', event[]<- CPLDeliver ' n ' $$0 -}.\n    eapply DSCut; first (by repeat dclear; apply DTOrDistrib2 with\n      (A1 := A1) (A2 := A2) (A3 := A2)); dtsubstp_r.\n    eapply DSCut; first (by repeat dclear; apply DTOrElimSelf with\n      (A := A2)); dtsubstp_l.\n\n    by repeat (match goal with\n    | |- context[ {-A (self-event /\\ ?A2_) /\\ ?A3_ -} ] =>\n      eapply DSCut; first (by repeat dclear; apply DTAndAssoc with\n        (A1 := {-A self-event -}) (A2 := A2_) (A3 := A3_))\n    end; dtsubstp_l).\n  }\n\n  (* Thus *)\n  eapply DSCut; first (repeat dclear; by apply DTOrComm with\n    (H1 := {-A eventually on n', event[]<- CPLDeliver ' n ' m -})\n    (H2 := {-A exists: (* m *) self-event /\\\n      (on n, (0, CSLSend ' n' ' (c, $$0)) \\in Fors) /\\\n      eventually on n', event[]<- CPLDeliver ' n ' $$0 -}));\n    dtsubstp_l.\n  eapply DSCut; first (repeat dclear; by apply DTAndAssoc with\n    (A1 := {-A self-event -})\n    (A2 := {-A on n, (0, CSLSend ' n' ' (c, m)) \\in Fors -})\n    (A3 := {-A (exists: (* m *) self-event /\\\n      (on n, (0, CSLSend ' n' ' (c, $$0)) \\in Fors) /\\\n      eventually on n', event[]<- CPLDeliver ' n ' $$0) \\/\n      eventually on n', event[]<- CPLDeliver ' n ' m -}));\n    dtsubstp_r.\n  eapply DSCut; first (repeat dclear; by apply DTAndAssoc with\n    (A1 := {-A self-event -})\n    (A2 := {-A on n, (0, CSLSend ' n' ' (c, $$0)) \\in Fors -})\n    (A3 := {-A eventually on n', event[]<- CPLDeliver ' n ' $$0 -}));\n    dtsubstp_r.\n  eapply DSCut; first (repeat dclear; by apply DTOrDistrib2 with\n    (A1 := {-A self-event /\\ on n, (0, CSLSend ' n' ' (c, m)) \\in Fors -})\n    (A2 := {-A exists: (* m *) (self-event /\\\n      (on n, (0, CSLSend ' n' ' (c, $$0)) \\in Fors)) /\\\n      eventually on n', event[]<- CPLDeliver ' n ' $$0 -})\n    (A3 := {-A eventually on n', event[]<- CPLDeliver ' n ' m -}));\n    dtsubstp_l.\n  eapply DSCut; first (by repeat dclear; eapply DTAndExampleExists with\n    (H1 := {-A self-event /\\ on n, (0, CSLSend ' n' ' (c, $$0)) \\in Fors -})\n    (H2 := {-A eventually on n', event[]<- CPLDeliver ' n ' $$0 -})\n    (x := {-t m -})); dsimplp; dtsubstposp.\n  eapply DSCut; first (by repeat dclear; apply DTEntailsAndDropLeft with\n    (A1 := {-A self-event /\\ on n, (0, CSLSend ' n' ' (c, m)) \\in Fors -})\n    (A2 := {-A eventually on n', event[]<- CPLDeliver ' n ' m -}));\n    dtsubstposp.\n  by eapply DSCut; first (by repeat dclear; apply DTOrElimSelf with\n    (A := {-A eventually on n', event[]<- CPLDeliver ' n ' m -}));\n    dtsubstp_l.\nQed.\n", "meta": {"author": "jzgriffin", "repo": "tlc", "sha": "58919b43a5a1db887237dbeee812664147d657d4", "save_path": "github-repos/coq/jzgriffin-tlc", "path": "github-repos/coq/jzgriffin-tlc/tlc-58919b43a5a1db887237dbeee812664147d657d4/tlc/component/perfect_link_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604274, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.25132030761791374}}
{"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.Theory Require Import Core.\nImport Core.Notations.\n\nSection WithVar.\n  Context (V : Type)\n          {V_Eqb : Eqb V}\n          {V_default : WithDefault V}.\n\n  Notation named_list := (@named_list V).\n  Notation named_map := (@named_map V).\n  Notation term := (@term V).\n  Notation ctx := (@ctx V).\n  Notation sort := (@sort V).\n  Notation subst := (@subst V).\n  Notation rule := (@rule V).\n  Notation lang := (@lang V).\n  \n  Notation eq_subst l :=\n    (eq_subst (Model:= core_model l)).\n  Notation eq_args l :=\n    (eq_args (Model:= core_model l)).\n  Notation wf_subst l :=\n    (wf_subst (Model:= core_model l)).\n  Notation wf_args l :=\n    (wf_args (Model:= core_model l)).\n  Notation wf_ctx l :=\n    (wf_ctx (Model:= core_model l)).\n\n  (* Compilers can target an arbitrary model.\n     They do not have to target syntax.\n   *)\n\n  Section WithPreModel.\n    Context {tgt_term tgt_sort : Type}\n            {tgt_Model : @PreModel V tgt_term tgt_sort}\n            (*TODO: should I make it so that these aren't necessary?*)\n            `{WithDefault tgt_term}\n            `{WithDefault tgt_sort}.\n\n(* each element is the image for that constructor or axiom*)\nVariant compiler_case :=\n | term_case (args : list V) (e:tgt_term)\n | sort_case (args : list V) (t:tgt_sort).\nDefinition compiler := named_list compiler_case.\n\nLemma invert_eq_term_case_term_case args args' e e'\n  : term_case args e = term_case args' e' <-> args = args' /\\ e = e'.\nProof using. solve_invert_constr_eq_lemma. Qed.\nHint Rewrite invert_eq_term_case_term_case : lang_core.\n\nLemma invert_eq_term_case_sort_case args args' e e'\n  : term_case args e = sort_case args' e' <-> False.\nProof using. solve_invert_constr_eq_lemma. Qed.\nHint Rewrite invert_eq_term_case_sort_case : lang_core.\n\nLemma invert_eq_sort_case_term_case args args' e e'\n  : sort_case args e = term_case args' e' <-> False.\nProof using. solve_invert_constr_eq_lemma. Qed.\nHint Rewrite invert_eq_sort_case_term_case : lang_core.\n\nLemma invert_eq_sort_case_sort_case args args' e e'\n  : sort_case args e = sort_case args' e' <-> args = args' /\\ e = e'.\nProof using. solve_invert_constr_eq_lemma. Qed.\nHint Rewrite invert_eq_sort_case_sort_case : lang_core.\n\nSection CompileFn.\n  Context (cmp : compiler).\n\n  (*TODO: move to Term.v*)\n  Existing Instance term_default.\n  Existing Instance sort_default.\n\n  (*TODO: is this the right choice? \n    It's the same as combine for wf terms,\n    but it makes some theorems easier\n    at the expense of requiring a default instance for V\n   *)\n  Fixpoint combine_r_padded {A B : Type} `{WithDefault B}\n           (l : list A) (l' : list B) {struct l} : list (A * B) :=\n  match l, l' with\n  | [],_ => []\n  | x :: tl, [] => (x, default) :: combine_r_padded tl []\n  | x :: tl, y :: tl' => (x, y) :: combine_r_padded tl tl'\n  end.\n\nArguments combine_r_padded [A B]%type_scope {_} (_ _)%list_scope.\n  \n  (*TODO: notations do a poor job of spacing this*)\n  Fixpoint compile (e : term) : tgt_term :=\n    match e with\n    | var x => inj_var x\n    | con n s =>\n      let arg_terms := map compile s in\n      match named_list_lookup_err cmp n with\n      | Some (term_case args e) => e[/combine_r_padded args arg_terms/]\n      | _ => default\n      end\n    end.\n\n  Definition compile_sort (t : sort) : tgt_sort :=\n    match t with\n    | scon n s =>\n      let arg_terms := map compile s in\n      match named_list_lookup_err cmp n with\n      | Some (sort_case args t) => t[/combine_r_padded args arg_terms/]\n      | _ => default\n      end\n    end.  \n  \n  Definition compile_args := map compile.\n\n  Definition compile_subst (s : named_list term) := named_map compile s.\n\n  Definition compile_ctx (c:named_list sort) := named_map compile_sort c.\n\nEnd CompileFn.\nEnd WithPreModel.\n\n  \n  Section WithModel.\n    Context {tgt_term tgt_sort : Type}\n      {tgt_Model : @Model V tgt_term tgt_sort}\n      (*TODO: should I make it so that these aren't necessary?*)\n      `{WithDefault tgt_term}\n      `{WithDefault tgt_sort}.\n\n    Existing Instance tgt_Model.\n\n    Notation compiler :=\n      (compiler (tgt_term:=tgt_term)\n         (tgt_sort:=tgt_sort)).\n    \nSection CompileJudgment.\n  Context (cmp : compiler)\n    (src : lang).\n\n  Notation compile := (compile cmp).\n  Notation compile_sort := (compile_sort cmp).\n  Notation compile_ctx := (compile_ctx cmp).\n  Notation compile_args := (compile_args cmp).\n  Notation compile_subst := (compile_subst cmp).\n  \n   (* First we specify the properties semantically,\n     then inductively on the compiler. TODO: prove equivalent\n   *)\n  Definition sort_wf_preserving_sem :=\n    forall c t,\n      wf_sort src c t ->\n      wf_ctx src c ->\n      Model.wf_sort (compile_ctx c) (compile_sort t).\n\n  Definition term_wf_preserving_sem :=\n    forall c e t,\n      wf_term src c e t ->\n      wf_ctx src c ->\n      Model.wf_term (compile_ctx c) (compile e) (compile_sort t).\n\n  Definition sort_eq_preserving_sem :=\n    forall c t1 t2,\n      eq_sort src c t1 t2 ->\n      wf_ctx src c ->\n      Model.eq_sort (compile_ctx c) (compile_sort t1) (compile_sort t2).\n  \n  Definition term_eq_preserving_sem :=\n    forall c t e1 e2,\n      eq_term src c t e1 e2 ->\n      wf_ctx src c ->\n      Model.eq_term (compile_ctx c) (compile_sort t) (compile e1) (compile e2).\n\n  Definition args_wf_preserving_sem :=\n    forall c s c',\n      wf_args src c s c' ->\n      wf_ctx src c ->\n      wf_ctx src c' ->\n      Model.wf_args (compile_ctx c) (compile_args s) (compile_ctx c').\n\n  Definition subst_eq_preserving_sem :=\n    forall c c' s1 s2,\n      eq_subst src c c' s1 s2 ->\n      wf_ctx src c ->\n      wf_ctx src c' ->\n      Model.eq_subst (compile_ctx c) (compile_ctx c') (compile_subst s1) (compile_subst s2).\n   \n  Definition ctx_wf_preserving_sem :=\n    forall c, wf_ctx src c -> Model.wf_ctx (compile_ctx c).\n\n  (*Set up to match the combined scheme for the judgment inductives *)\n  Definition semantics_preserving :=\n    sort_eq_preserving_sem /\\ term_eq_preserving_sem /\\ subst_eq_preserving_sem\n    /\\ sort_wf_preserving_sem /\\ term_wf_preserving_sem /\\ args_wf_preserving_sem\n    /\\ ctx_wf_preserving_sem.\n\nEnd CompileJudgment.\n\n(*\nFirst we define an inductively provable (and in fact decidable) property \nof elaborated compilers.\n*)\n\nSection Extension.\n  Context (cmp_pre : compiler).\n  (*TODO: this is an equal or stronger property (which?); includes le principles;\n  formalize the relationship to those above and le semantic statements *)\n  Inductive preserving_compiler_ext : compiler -> lang -> Prop :=\n  | preserving_compiler_nil : preserving_compiler_ext [] []\n  | preserving_compiler_sort : forall cmp l n c args t,\n      preserving_compiler_ext cmp l ->\n      (* Notable: only uses the previous parts of the compiler on c *)\n      Model.wf_sort (compile_ctx (cmp ++ cmp_pre) c) t ->\n      preserving_compiler_ext ((n,sort_case (map fst c) t)::cmp)\n                              ((n,sort_rule c args) :: l)\n  | preserving_compiler_term : forall cmp l n c args e t,\n      preserving_compiler_ext cmp l ->\n      (* Notable: only uses the previous parts of the compiler on c, t *)\n      Model.wf_term (compile_ctx (cmp ++ cmp_pre) c) e (compile_sort (cmp ++ cmp_pre) t) ->\n      preserving_compiler_ext ((n, term_case (map fst c) e)::cmp)\n                              ((n,term_rule c args t) :: l)\n  | preserving_compiler_sort_eq : forall cmp l n c t1 t2,\n      preserving_compiler_ext cmp l ->\n      (* Notable: only uses the previous parts of the compiler on c *)\n      Model.eq_sort (compile_ctx (cmp ++ cmp_pre) c)\n              (compile_sort (cmp ++ cmp_pre) t1)\n              (compile_sort (cmp ++ cmp_pre) t2) ->\n      preserving_compiler_ext cmp ((n,sort_eq_rule c t1 t2) :: l)\n  | preserving_compiler_term_eq : forall cmp l n c e1 e2 t,\n      preserving_compiler_ext cmp l ->\n      (* Notable: only uses the previous parts of the compiler on c *)\n      Model.eq_term (compile_ctx (cmp ++ cmp_pre) c)\n              (compile_sort (cmp ++ cmp_pre) t)\n              (compile (cmp ++ cmp_pre) e1)\n              (compile (cmp ++ cmp_pre) e2) ->\n      preserving_compiler_ext cmp ((n,term_eq_rule c e1 e2 t) :: l).\n\nEnd Extension.\n\nEnd WithModel.\n    \nEnd WithVar.\n#[export] Hint Rewrite invert_eq_term_case_term_case : lang_core.\n#[export] Hint Rewrite invert_eq_term_case_sort_case : lang_core.\n#[export] Hint Rewrite invert_eq_sort_case_term_case : lang_core.\n#[export] Hint Rewrite invert_eq_sort_case_sort_case : lang_core.\n#[export] Hint Constructors preserving_compiler_ext : lang_core.\n\n(*TODO: add preserving_compiler notation once other files are updated *)\n(*TODO: shouth the RHS be in the constr entry?\n  Probably not now that compilers are more general.\n*)\n\nDeclare Custom Entry comp_case.\n\nModule Notations.\n\n  Notation \"| '{{s' # constr }} => t \" :=\n    (constr, sort_case nil t)\n      (in custom comp_case at level 50,\n          left associativity,\n          constr constr at level 0,\n          t constr,\n          format \"|  '{{s' # constr }}  =>  t\").\n\n  Notation \"| '{{e' # constr }} => e \" :=\n    (constr, term_case nil e)\n      (in custom comp_case at level 50,\n          left associativity,\n          constr constr at level 0,\n          e constr,\n          format \"|  '{{e' # constr }}  =>  e\").\n\n  Notation \"| '{{s' # constr x .. y }} => t\" :=\n    (constr, sort_case (cons y .. (cons x nil) ..) t)\n      (in custom comp_case at level 50,\n          left associativity,\n          constr constr at level 0,\n          x constr at level 0,\n          y constr at level 0,\n          t constr,\n          format \"|  '{{s' # constr  x  ..  y }}  =>  t\").\n\n  Notation \"| '{{e' # constr x .. y }} => e \" :=\n    (constr, term_case (cons y .. (cons x nil) ..) e)\n      (in custom comp_case at level 50,\n          left associativity,\n          constr constr at level 0,\n          x constr at level 0,\n          y constr at level 0,\n          e constr,\n          format \"|  '{{e' # constr  x  ..  y }}  =>  e\").\n\n  (* Cases must be given in the order of the source language,\n     and argument names must match the context of the related source rule.\n     All cases must be defined.\n   *)\n  Notation \"'match' # 'with' case_1 .. case_n 'end'\" :=\n    (cons case_n .. (cons case_1 nil) ..)\n      (left associativity, at level 50,\n       case_1 custom comp_case,\n       case_n custom comp_case,\n       format \"'[' 'match'  #  'with' '//' '[v' case_1 '//' .. '//' case_n ']'  '//' 'end' ']'\").\n\n  (*TODO: specialized to strings. Generalize.*)\n  Definition gen_rule (cmp : compiler string) (p : string * rule string) : named_list string (compiler_case string) :=\n    let (n,r) := p in\n    match r with\n    | sort_rule c args =>\n      match named_list_lookup (sort_case (map fst c) (scon n (map (@var string) args))) cmp n with\n      | sort_case args' t =>\n        [(n,sort_case (map fst c) t[/combine args' (map (@var string) (map fst c))/])]\n      | _ => [(n,sort_case [] {{s#\"ERR: expected sort case\"}})]\n      end\n    | term_rule c args t => \n      match named_list_lookup (term_case (map fst c) (con n (map (@var string) args))) cmp n with\n      | term_case args' e =>\n        [(n,term_case (map fst c) e[/combine args' (map (@var string) (map fst c))/])]\n      | _ => [(n,sort_case [] {{s#\"ERR: expected term case\"}})]\n      end\n    | sort_eq_rule _ _ _\n    | term_eq_rule _ _ _ _ => []\n    end.\n  \n\n  (* accepts rules unordered and handles renaming to match language.\n     Defaults to an identity rule for anything unspecified.\n   *)\n  Notation \"'match' # 'from' l 'with' case_1 .. case_n 'end'\" :=\n    (flat_map (gen_rule (cons case_n .. (cons case_1 nil) ..)) l)\n      (left associativity, at level 50,\n       case_1 custom comp_case,\n       case_n custom comp_case,\n       format \"'[' 'match'  #  'from'  l  'with' '//' '[v' case_1 '//' .. '//' case_n ']' '//' 'end' ']'\").\nEnd Notations.\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/Compilers/CompilerDefs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2513203076179137}}
{"text": "Require Import List.\nImport ListNotations.\nRequire Import BirkStar.birk_star.\nRequire Import Utf8.\nRequire Import Coq.Program.Equality.\n\nDefinition x := t_Var 0.\nDefinition y := t_Var 1.\nDefinition z := t_Var 2.\n\nDefinition x' := 0.\nDefinition y' := 1.\nDefinition z' := 2.\n\n(* Let A B C represent arbitrary well-formed types. *)\nContext {A B C : type}.\nContext (hA : forall ctx, type_form ctx A).\nContext (hB : forall ctx, type_form ctx B).\nContext (hC : forall ctx, type_form ctx C).\n\nLemma example_typing: type_of_term [Some (x', A)] x A.\nProof.\napply term_var.\n{ apply ctx_var. apply ctx_emp. apply hA.\n}\nunfold C_in.\nexists C_nil.\nexists C_nil.\nsimpl.\nsplit.\n{ auto. }\nsplit.\n{ intro. destruct H. exact H. }\n{ auto. }\nQed.\n\nLemma example_typing2: type_of_term [] \n  (t_Lam x' (t_Lam y' (t_Var y'))) (T_Fun x' A (T_Fun y' B B)).\nProof.\napply pi_intro.\napply hA.\napply pi_intro.\napply hB.\napply term_var.\n{ apply ctx_var. apply ctx_var. apply ctx_emp. apply hA. apply hB. }\nunfold C_in.\nexists C_nil.\nexists [Some (x', A)].\nsimpl.\nsplit.\n{ auto. }\nsplit.\n{ intro. destruct H. exact H. }\n{ auto. }\nQed.\n\nLemma axiom_T: type_of_term [] (t_Lam x' (t_Open x)) (T_Fun x' (T_Box A) A).\nProof.\napply pi_intro.\n{ apply box_form. apply hA. }\napply box_elim.\n{ apply hA. }\napply term_var.\nunfold C_unlock.\nunfold C_in.\nsimpl.\n{ apply ctx_var. apply ctx_emp. apply box_form. apply hA. }\nexists C_nil.\nexists C_nil.\nsplit.\n{ auto. }\nsplit.\n{ intro. destruct H. exact H. }\n{ auto. }\nQed.\n\nLocate \"~=\".\n\n(* Lemma ctx_form_cong_app {ctx1 ctx2 : context} \n: ctx_form (ctx1 ++ ctx2) <-> ctx_form ctx1 /\\ ctx_form ctx2.\nProof.\n  induction ctx1.\n  { unfold app.\n    split.\n    { intro h. split. apply ctx_emp. apply h. }\n    { intros (_, h). apply h. }\n  }\n  { simpl.\n    destruct a.\n    split.\n    { intro h. inversion h. rewrite IHctx1 in H1. \n      destruct H1 as (Hctx1, Hctx2). split. apply ctx_var. }\n  }\n\nAdmitted. *)\n\nTheorem subst {ctx1 ctx2 : context} {t} {x} (h : type_of_term (ctx2 ++ ctx1) t B) \n: type_of_term (ctx2 ++ (C_var (x, A) :: ctx1)) t B.\nProof.\nremember (ctx2 ++ ctx1) as ctx.\ninduction h.\n{ apply nat_zero. \n  rewrite Heqctx in H.\n  generalize dependent ctx1.\n  induction ctx2.\n  { intro ctx1. unfold app in H. unfold app. apply ctx_var. apply H. apply hA. }\n  { simpl in H. simpl. destruct a.\n    { destruct p. apply ctx_var. apply IHctx2.  } \n  }\n  admit. (* Too lazy to prove, its obvious *) }\n{ rewrite <-x. apply nat_succ. rewrite x. apply IHh. apply JMeq_refl. apply x. }\n{ admit. }\n{ apply term_var. admit. admit. (* Too lazy *) }\n{ rewrite <-x. apply pi_intro. admit. admit. (* ??? genuinely can't do *) }\n{ admit. (* pi_elim doesn't work for some reason *) }\n{ rewrite <-x. apply box_intro. admit. (* too lazy *) }\n{ apply box_elim. admit. (* Too lazy*) admit. (* not sure if I can do *) }\nAdmitted.", "meta": {"author": "alyata", "repo": "modal-ott", "sha": "da39ffa3072f680a72f4542027339699751805ed", "save_path": "github-repos/coq/alyata-modal-ott", "path": "github-repos/coq/alyata-modal-ott/modal-ott-da39ffa3072f680a72f4542027339699751805ed/birk_star_custom.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.45326184801538605, "lm_q1q2_score": 0.25132030094394464}}
{"text": "(*\n * Copyright (c) 2009-2011, Andrew Appel, Robert Dockins and Aquinas Hobor.\n *\n *)\n\nRequire Import msl.base.\nLocal Open Scope nat_scope.\n\nRequire Import msl.ageable.\nRequire Import msl.functors.\nRequire Import msl.predicates_hered.\n\nImport CovariantFunctor.\nImport CovariantFunctorLemmas.\nImport CovariantFunctorGenerator.\n\nModule Type TY_FUNCTOR_PROP.\n  Parameter F : functor.\n  Parameter other : Type.\nEnd TY_FUNCTOR_PROP.\n\nModule Type KNOT_HERED.\n  Declare Module TF:TY_FUNCTOR_PROP.\n  Import TF.\n\n  Parameter knot:Type.\n  Parameter ag_knot : ageable knot.\n  Existing Instance ag_knot.\n  Existing Instance ag_prod.\n\n  Definition predicate := pred (knot * other).\n\n  Parameter squash : (nat * F predicate) -> knot.\n  Parameter unsquash : knot -> (nat * F predicate).\n\n  Parameter approx : nat -> predicate -> predicate.\n\n  Axiom squash_unsquash : forall k:knot, squash (unsquash k) = k.\n  Axiom unsquash_squash : forall (n:nat) (f:F predicate),\n    unsquash (squash (n,f)) = (n, fmap F (approx n) f).\n\n  Axiom approx_spec : forall n p k,\n    proj1_sig (approx n p) k = (level k < n /\\ proj1_sig p k).\n\n  Axiom knot_level : forall k:knot, level k = fst (unsquash k).\n\n  Axiom knot_age1 : forall k,\n    age1 k =\n    match unsquash k with\n    | (O,_) => None\n    | (S n,x) => Some (squash (n,x))\n    end.\n\nEnd KNOT_HERED.\n\nModule KnotHered (TF':TY_FUNCTOR_PROP) : KNOT_HERED with Module TF:=TF'.\n  Module TF:=TF'.\n  Import TF.\n\n  Definition sinv_prod X := prod X (F X * other -> Prop).\n\n  Definition guppy_sig := (fun T:Type => T * (F T * other -> Prop) -> Prop).\n  Definition guppy_ty := sigT guppy_sig.\n\n  Definition guppy_step_ty (Z:guppy_ty) : Type :=\n    (sig (fun (x:sinv_prod (projT1 Z)) => projT2 Z x)).\n\n  Definition guppy_step_prop (Z:guppy_ty) (xf:sinv_prod (guppy_step_ty Z)) :=\n    forall (k:F (guppy_step_ty Z)) (o:other),\n      snd xf (k,o) -> snd (proj1_sig (fst xf)) (fmap F (@fst _ _ oo @proj1_sig _ _) k,o).\n\n  Definition guppy_step (Z:guppy_ty) : guppy_ty :=\n    existT guppy_sig (guppy_step_ty Z) (guppy_step_prop Z).\n\n  Definition guppy_base : guppy_ty :=\n    existT guppy_sig unit (fun _ => True).\n\n  Fixpoint guppy (n:nat) : guppy_ty :=\n    match n with\n    | 0    => guppy_base\n    | S n' => guppy_step (guppy n')\n    end.\n\n  Definition sinv (n:nat) : Type := projT1 (guppy n).\n  Definition sinv_prop (n:nat) : prod (sinv n) (F (sinv n) * other -> Prop) -> Prop := projT2 (guppy n).\n\n  Fixpoint floor (m:nat) (n:nat) (p:sinv (m+n)) : sinv n :=\n    match m as m' return forall (p : sinv (m'+n)), sinv n with\n    | O => fun p => p\n    | S m' => fun p => floor m' n (fst (proj1_sig p))\n    end p.\n\n  Definition knot := { n:nat & F (sinv n) }.\n\n  Definition k_age1 (k:knot) : option (knot) :=\n    match k with\n      | (existT _ 0 f) => None\n      | (existT _ (S m) f) => Some\n          (existT (F oo sinv) m (fmap F (@fst _ _ oo @proj1_sig _ _) f))\n    end.\n\n  Definition k_age (k1 k2:knot) := k_age1 k1 = Some k2.\n\n  Definition ko_age1 (x:knot * other) :=\n    match k_age1 (fst x) with\n    | None => None\n    | Some a' => Some (a',snd x)\n    end.\n  Definition ko_age x y := ko_age1 x = Some y.\n\n\n  Definition predicate := { p:knot * other -> Prop | hereditary ko_age p }.\n\n  Definition app_sinv (n:nat) (p:sinv (S n)) (x:F (sinv n) * other) :=\n    snd (proj1_sig p) x.\n\n  Lemma app_sinv_age : forall n (p:sinv (S (S n))) (f:F (sinv (S n)) * other),\n    app_sinv (S n) p f ->\n    app_sinv n (fst (proj1_sig p)) (fmap F (@fst _ _ oo @proj1_sig _ _) (fst f), snd f).\n  Proof.\n    intros.\n    unfold app_sinv in *.\n    destruct p; simpl in *; fold guppy in *.\n    apply p; auto.\n    destruct f; auto.\n  Qed.\n\n  Section stratifies.\n    Variable Q:knot * other -> Prop.\n    Variable HQ:hereditary ko_age Q.\n\n    Fixpoint stratifies (n:nat) : sinv n -> Prop :=\n    match n as n' return sinv n' -> Prop with\n    | 0 => fun _ => True\n    | S n' => fun (p:sinv (S n')) =>\n          stratifies n' (fst (proj1_sig p)) /\\\n          forall (k:F (sinv n')) (o:other), snd (proj1_sig p) (k,o) <-> Q (existT (F oo sinv) n' k,o)\n    end.\n\n    Lemma stratifies_unique : forall n p1 p2,\n      stratifies n p1 ->\n      stratifies n p2 ->\n      p1 = p2.\n    Proof.\n      induction n; simpl; intuition.\n      destruct p1; destruct p2; auto.\n      destruct p1; destruct p2.\n      simpl in *; fold guppy in *.\n      cut (x = x0).\n      intros.\n      revert p p0 H2 H3.\n      rewrite <- H0.\n      intros.\n      replace p0 with p by (apply proof_irr); auto.\n      destruct x; destruct x0; simpl in *.\n      apply injective_projections; simpl.\n      apply IHn; auto.\n      extensionality; intros.\n      simpl in *.\n      destruct (H2 (fst x) (snd x)); destruct (H3 (fst x) (snd x)).\n      apply prop_ext; destruct x; intuition.\n    Qed.\n\n    Definition stratify (n:nat) : { x:sinv n | stratifies n x }.\n    Proof.\n      induction n.\n      exists tt; simpl; exact I.\n      assert (HX:\n        projT2 (guppy n)\n        (proj1_sig IHn, fun v : F (sinv n) * other => Q (existT (F oo sinv) n (fst v),snd v))).\n      destruct n.\n      simpl; exact I.\n      simpl; intros.\n      destruct IHn; simpl.\n      simpl in s; destruct s.\n      destruct x; simpl in *; fold guppy in *.\n      destruct x; simpl in *.\n      hnf; simpl; intros.\n      rewrite H0.\n      eapply HQ.\n      2: apply H1.\n      simpl; reflexivity.\n      exists ((exist (fun x => projT2 (guppy n) x) ( proj1_sig IHn, fun v:F (sinv n) * other => Q (existT (F oo sinv) n (fst v),snd v) ) HX)).\n      simpl; split.\n      destruct IHn; auto.\n      unfold app_sinv; simpl; intros.\n      split; trivial.\n    Qed.\n  End stratifies.\n\n  Lemma decompose_nat : forall (x y:nat), { m:nat & y = (m + S x) } + { ge x y }.\n  Proof.\n    intros x y; revert x; induction y; simpl; intros.\n    right; auto with arith.\n    destruct (IHy x) as [[m H]|H].\n    left; exists (S m); omega.\n    destruct (eq_nat_dec x y).\n    left; exists O; omega.\n    right; omega.\n  Qed.\n\n  Definition unstratify (n:nat) (p:sinv n) : knot * other -> Prop := fun w =>\n    match w with (existT _ nw w',o) =>\n      match decompose_nat nw n with\n        | inleft (existT _ m Hm) => snd (proj1_sig (floor m (S nw) (eq_rect  n _ p (m + S nw) Hm))) (w',o)\n        | inright H => False\n      end\n    end.\n\n  Lemma floor_shuffle:\n    forall (m1 n : nat)\n      (p1 : sinv (m1 + S n)) (H1 : (m1 + S n) = (S m1 + n)),\n      floor (S m1) n (eq_rect (m1 + S n) sinv p1 (S m1 + n) H1) = fst (proj1_sig (floor m1 (S n) p1)).\n  Proof.\n    intros.\n    remember (fst (proj1_sig (floor m1 (S n) p1))) as p.\n    fold guppy in *.\n    revert n p1 H1 p Heqp.\n    induction m1; simpl; intros.\n    replace H1 with (refl_equal (S n)) by (apply proof_irr); simpl; auto.\n    assert (m1 + S n = S m1 + n) by omega.\n    destruct p1 as [[p1 f'] Hp1]; simpl in *; fold guppy in *.\n    generalize (IHm1 n p1 H p Heqp).\n    clear.\n    revert Hp1 H1; generalize H.\n    revert p1 f'.\n    rewrite H.\n    simpl; intros.\n    replace H1 with (refl_equal (S (S (m1 + n)))) by (apply proof_irr).\n    simpl.\n    replace H0 with (refl_equal (S (m1+n))) in H2 by (apply proof_irr).\n    simpl in H2.\n    trivial.\n  Qed.\n\n  Lemma unstratify_hered : forall n p,\n    hereditary ko_age (unstratify n p).\n  Proof.\n    intros.\n    hnf; intros k k'; intros.\n    simpl in H.\n    destruct k.\n    destruct k as [x f]. destruct x.\n    discriminate.\n    destruct k' as [k' o'].\n    assert (o = o').\n    hnf in H.\n    simpl in H.\n    inv H. auto.\n    subst o'.\n    replace k' with\n      (existT (F oo sinv) x (fmap F (@fst _ _ oo @proj1_sig _ _ ) f)).\n    2: inversion H; auto.\n    clear H.\n    case_eq (decompose_nat x n); intros.\n    destruct s.\n    case_eq (decompose_nat (S x) n); intros.\n    destruct s.\n    destruct n.\n    elimtype False; omega.\n    assert (S x1 = x0) by omega; subst x0.\n    revert H0.\n    unfold unstratify.\n    rewrite H; rewrite H1.\n    generalize e e0; revert p; rewrite e0; intros.\n    rewrite floor_shuffle.\n    replace e2 with (refl_equal (x1 + S (S x))) in H0;\n      simpl eq_rect in H0.\n    2: apply proof_irr.\n    change f with (fst (f,o)).\n    change o with (snd (f,o)).\n    eapply app_sinv_age; apply H0.\n\n    revert H0.\n    unfold unstratify.\n    rewrite H; rewrite H1.\n    intuition.\n\n    case_eq (decompose_nat (S x) n); intros.\n    destruct s.\n    elimtype False; omega.\n    revert H0.\n    unfold unstratify.\n    rewrite H; rewrite H1; auto.\n  Qed.\n\n  Lemma unstratify_Q : forall n (p:sinv n) Q,\n    stratifies Q n p ->\n    forall (k:knot) o,\n      projT1 k < n ->\n      (unstratify n p (k,o) <-> Q (k,o)).\n  Proof.\n    intros.\n    unfold unstratify.\n    destruct k.\n    destruct (decompose_nat x n).\n    destruct s.\n    simpl in H0.\n    2: simpl in *; elimtype False; omega.\n    clear H0.\n    revert p H.\n    generalize e.\n    rewrite e.\n    intros.\n    replace e0 with (refl_equal (x0 + S x)) by apply proof_irr.\n    simpl.\n    clear e e0.\n    revert p H.\n    induction x0; simpl; intros.\n    destruct H.\n    auto.\n    destruct H.\n    apply IHx0.\n    auto.\n  Qed.\n\n  Lemma stratifies_unstratify_more :\n    forall (n m1 m2:nat) (p1:sinv (m1+n)) (p2:sinv (m2+n)),\n      floor m1 n p1 = floor m2 n p2 ->\n      (stratifies (unstratify (m1+n) p1) n (floor m1 n p1) ->\n       stratifies (unstratify (m2+n) p2) n (floor m2 n p2)).\n  Proof.\n    induction n; intuition.\n    split.\n    assert (m2 + S n = S m2 + n) by omega.\n    erewrite <- floor_shuffle.\n    instantiate (1:=H1).\n    replace (unstratify (m2 + S n) p2)\n      with (unstratify (S m2 + n) (eq_rect (m2 + S n) sinv p2 (S m2 + n) H1)).\n    assert (m1 + S n = S m1 + n) by omega.\n    eapply (IHn (S m1) (S m2)\n      (eq_rect (m1 + S n) sinv p1 (S m1 + n) H2)).\n    rewrite floor_shuffle.\n    rewrite floor_shuffle.\n    rewrite H; auto.\n    clear - H0.\n    rewrite floor_shuffle.\n    simpl in H0.\n    destruct H0.\n    clear H0.\n    revert p1 H.\n    generalize H2.\n    rewrite <- H2.\n    intros.\n    replace H0 with (refl_equal (m1 + S n)) by apply proof_irr; auto.\n    clear.\n    revert p2.\n    generalize H1.\n    rewrite H1.\n    intros.\n    replace H0 with (refl_equal (S m2 + n)) by apply proof_irr; auto.\n\n    intros.\n    simpl.\n    destruct (decompose_nat n (m2 + S n)).\n    destruct s.\n    assert (m2 = x).\n    omega.\n    subst x.\n    replace e with (refl_equal (m2 + S n)).\n    simpl; tauto.\n    apply proof_irr.\n    elimtype False; omega.\n  Qed.\n\n  Lemma stratify_unstratify : forall n p H,\n    proj1_sig (stratify (unstratify n p) H n) = p.\n  Proof.\n    intros.\n    apply stratifies_unique with (unstratify n p).\n    destruct (stratify _ H n).\n    simpl; auto.\n    clear H.\n    revert p; induction n.\n    simpl; intros; auto.\n    intros.\n    simpl; split.\n\n    assert (stratifies (unstratify n (fst (proj1_sig p))) n (fst (proj1_sig p))).\n    apply IHn.\n    apply (stratifies_unstratify_more n 0 1 (fst (proj1_sig p)) p).\n    simpl; auto.\n    auto.\n\n    intros.\n    destruct (decompose_nat n (S n)).\n    destruct s.\n    assert (x = 0) by omega.\n    subst x.\n    simpl.\n    simpl in e.\n    replace e with (refl_equal (S n)) by apply proof_irr.\n    simpl.\n    split; auto.\n    elimtype False; omega.\n  Qed.\n\n\n  Definition strat (n:nat) (p:predicate) : sinv n :=\n    proj1_sig (stratify (proj1_sig p) (proj2_sig p) n).\n\n  Definition unstrat (n:nat) (p:sinv n) : predicate :=\n    exist (hereditary ko_age) (unstratify n p) (unstratify_hered n p).\n\n  Definition squash (x:nat * F predicate) : knot :=\n    match x with (n,f) => existT (F oo sinv) n (fmap F (strat n) f) end.\n\n  Definition unsquash (k:knot) : nat * F predicate :=\n    match k with existT _ n f => (n, fmap F (unstrat n) f) end.\n\n  Definition level (x:knot) : nat := fst (unsquash x).\n  Program Definition approx (n:nat) (p:predicate) : predicate :=\n     fun w => level (fst w) < n /\\ p w.\n  Next Obligation.\n    hnf; simpl; intros.\n    intuition.\n    unfold level in *.\n    unfold unsquash in *.\n    destruct a0; simpl in H.\n    destruct x; try discriminate.\n    inv H.\n    simpl in *; omega.\n    destruct p; simpl in *.\n    eapply h; eauto.\n  Qed.\n\n  Lemma strat_unstrat : forall n,\n    strat n oo unstrat n = id (sinv n).\n  Proof.\n    intros; extensionality p.\n    unfold compose, id.\n    unfold strat, unstrat.\n    simpl.\n    rewrite stratify_unstratify.\n    auto.\n  Qed.\n\n  Lemma predicate_eq : forall (p1 p2:predicate),\n    proj1_sig p1 = proj1_sig p2 ->\n    p1 = p2.\n  Proof.\n    intros; destruct p1; destruct p2; simpl in H.\n    subst x0.\n    replace h0 with h by apply proof_irr.\n    auto.\n  Qed.\n\n  Lemma unstrat_strat : forall n,\n    unstrat n oo strat n = approx n.\n  Proof.\n    intros.\n    extensionality.\n    unfold compose.\n    unfold unstrat, strat.\n    unfold approx.\n    apply predicate_eq.\n    simpl.\n    extensionality k.\n    apply prop_ext; intuition.\n    unfold unstratify in H.\n    destruct a.\n    destruct (decompose_nat x0 n).\n    unfold level.\n    simpl.\n    destruct s.\n    omega.\n    elim H.\n    rewrite <- unstratify_Q.\n    apply H.\n    destruct (stratify (proj1_sig x) (proj2_sig x) n); auto.\n    unfold unstratify in H.\n    destruct a; simpl.\n    destruct (decompose_nat x0 n).\n    destruct s; omega.\n    elim H.\n    rewrite unstratify_Q.\n    apply H1.\n    destruct (stratify (proj1_sig x) (proj2_sig x) n); auto.\n    unfold level in H0.\n    destruct a; simpl in *.\n    auto.\n  Qed.\n\n  Lemma squash_unsquash : forall k, squash (unsquash k) = k.\n  Proof.\n    intros.\n    destruct k as [x f]; simpl.\n    f_equal.\n    change ((fmap F (strat x) oo fmap F (unstrat x)) f = f).\n    rewrite fmap_comp.\n    rewrite strat_unstrat.\n    rewrite fmap_id.\n    auto.\n  Qed.\n\n  Lemma unsquash_squash : forall n f,\n    unsquash (squash (n,f)) = (n, fmap F (approx n) f).\n  Proof.\n    intros.\n    unfold unsquash, squash.\n    f_equal.\n    change ((fmap F (unstrat n) oo fmap F (strat n)) f = fmap F (approx n) f).\n    rewrite fmap_comp.\n    rewrite unstrat_strat.\n    auto.\n  Qed.\n\n  Lemma strat_unstrat_Sx : forall x,\n    @fst _ _ oo @proj1_sig _ _ = strat x oo unstrat (S x).\n  Proof.\n    intros.\n    extensionality k.\n    change (sinv (S x)) in k.\n    unfold compose.\n    unfold strat, unstrat.\n    simpl.\n    apply stratifies_unique with (unstratify x (fst (proj1_sig k))).\n    revert k; induction x; simpl; auto.\n    intros.\n    split.\n    eapply (stratifies_unstratify_more x 0 1 ).\n    simpl; reflexivity.\n    simpl.\n    apply IHx.\n    intros.\n    destruct (decompose_nat x (S x)).\n    destruct s.\n    assert (x0 = 0) by omega; subst x0.\n    simpl in *.\n    replace e with (refl_equal (S x)) by apply proof_irr; simpl.\n    tauto.\n    elimtype False; omega.\n    destruct (stratify (unstratify (S x) k)\n      (unstratify_hered (S x) k) x).\n    simpl; auto.\n    cut (x0 = (fst (proj1_sig k))); intros.\n    subst x0.\n    eapply (stratifies_unstratify_more x 1 0).\n    simpl; reflexivity.\n    simpl; auto.\n    eapply stratifies_unique.\n    apply s.\n    eapply (stratifies_unstratify_more x 0 1).\n    simpl; reflexivity.\n    simpl.\n    generalize (fst (proj1_sig k) : sinv x).\n    clear.\n    induction x; simpl; intuition.\n    eapply (stratifies_unstratify_more x 0 1).\n    simpl; reflexivity.\n    simpl.\n    apply IHx.\n    destruct (decompose_nat x (S x)).\n    destruct s0.\n    assert (x0 = 0) by omega; subst.\n    simpl in *.\n    replace e with (refl_equal (S x)); simpl; auto.\n    apply proof_irr.\n    omega.\n    destruct (decompose_nat x (S x)).\n    destruct s0.\n    assert (x0 = 0) by omega; subst.\n    simpl in *.\n    replace e with (refl_equal (S x)) in H; simpl; auto.\n    apply proof_irr.\n    elim H.\n  Qed.\n\n  Lemma unsquash_inj : forall k k',\n    unsquash k = unsquash k' -> k = k'.\n  Proof.\n    intros.\n    rewrite <- (squash_unsquash k).\n    rewrite <- (squash_unsquash k').\n    congruence.\n  Qed.\n\n  Lemma knot_age_age1 : forall k k',\n    k_age1 k = Some k' <->\n    match unsquash k with\n    | (O,_) => None\n    | (S n,x) => Some (squash (n,x))\n    end = Some k'.\n  Proof.\n    split; intros.\n    unfold k_age1 in H.\n    unfold unsquash in H.\n    destruct k as [x f].\n    destruct x; auto.\n    inv H.\n    simpl.\n    f_equal.\n    f_equal.\n    change (fmap F (strat x) (fmap F (unstrat (S x)) f))\n      with ((fmap F (strat x) oo fmap F (unstrat (S x))) f).\n    rewrite fmap_comp.\n    simpl.\n    f_equal.\n    symmetry.\n    apply (strat_unstrat_Sx x).\n\n    simpl in H.\n    destruct k.\n    destruct x.\n    discriminate.\n    inv H.\n    hnf; simpl.\n    unfold k_age1.\n    f_equal.\n    f_equal.\n    rewrite strat_unstrat_Sx.\n    rewrite <- fmap_comp.\n    auto.\n  Qed.\n\n  Program Instance ag_knot : ageable knot :=\n  { age1 := k_age1\n  ; level := level\n  }.\n  Next Obligation.\n    econstructor.\n    (* unage *)\n    intros.\n    destruct (unsquash x') as [n f] eqn:?H; intros.\n    exists (squash (S n, f)).\n    rewrite knot_age_age1.\n    rewrite unsquash_squash.\n    f_equal.\n    apply unsquash_inj.\n    rewrite unsquash_squash.\n    rewrite H.\n    f_equal.\n    cut (f = fmap F (approx n) f).\n    intros.\n    rewrite fmap_app.\n    pattern f at 2. rewrite H0.\n    f_equal.\n    extensionality p.\n    apply predicate_eq.\n    extensionality w.\n    simpl. apply prop_ext.\n    intuition.\n    generalize H; intro.\n    rewrite <- (squash_unsquash x') in H.\n    rewrite H0 in H.\n    rewrite unsquash_squash in H.\n    congruence.\n\n    (* level 0 *)\n    intro x. destruct x; simpl.\n    destruct x; intuition; discriminate.\n\n    (* level S *)\n    intros. destruct x; simpl in *.\n    destruct x. discriminate.\n    inv H. simpl. auto.\n  Qed.\n\n  Existing Instance ag_prod.\n\n  Lemma approx_spec : forall n p (k:knot * other),\n    proj1_sig (approx n p) k = (ageable.level k < n /\\ proj1_sig p k).\n  Proof.\n    intros.\n    apply prop_ext.\n    unfold approx; simpl.\n    intuition; simpl in *; auto.\n  Qed.\n\n  Lemma knot_level : forall k:knot, level k = fst (unsquash k).\n  Proof. reflexivity. Qed.\n\n  Lemma knot_age1 : forall k,\n    age1 k =\n    match unsquash k with\n    | (O,_) => None\n    | (S n,x) => Some (squash (n,x))\n    end.\n  Proof.\n    intros. simpl.\n    case_eq (k_age1 k). intros.\n    rewrite knot_age_age1 in H.\n    auto.\n    destruct k; simpl. destruct x. auto.\n    intros. discriminate.\n  Qed.\n\nEnd KnotHered.\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/knot_hered.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.2513083247123449}}
{"text": "(***\n * Oqarina\n * Copyright 2021 Carnegie Mellon University.\n *\n * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING\n * INSTITUTE MATERIAL IS FURNISHED ON AN \"AS-IS\" BASIS. CARNEGIE MELLON\n * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR\n * IMPLIED, AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF\n * FITNESS FOR PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS\n * OBTAINED FROM USE OF THE MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT\n * MAKE ANY WARRANTY OF ANY KIND WITH RESPECT TO FREEDOM FROM PATENT,\n * TRADEMARK, OR COPYRIGHT INFRINGEMENT.\n *\n * Released under a BSD (SEI)-style license, please see license.txt or\n * contact permission@sei.cmu.edu for full terms.\n *\n * [DISTRIBUTION STATEMENT A] This material has been approved for public\n * release and unlimited distribution.  Please see Copyright notice for\n * non-US Government use and distribution.\n *\n * This Software includes and/or makes use of the following Third-Party\n * Software subject to its own license:\n *\n * 1. Coq theorem prover (https://github.com/coq/coq/blob/master/LICENSE)\n * Copyright 2021 INRIA.\n *\n * 2. Coq JSON (https://github.com/liyishuai/coq-json/blob/comrade/LICENSE)\n * Copyright 2021 Yishuai Li.\n *\n * DM21-0762\n***)\n\n(*| .. coq:: none |*)\nRequire Import Coq.Relations.Relation_Definitions.\nRequire Export Coq.Classes.RelationClasses.\nRequire Export Coq.Classes.Morphisms.\nRequire Import Coq.Classes.DecidableClass.\nRequire Import Coq.Lists.List.\nImport ListNotations. (* from List *)\n\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Classes.SetoidClass.\nOpen Scope equiv_scope.\nRequire Import Coq.Sorting.Permutation.\nRequire Import Coq.Logic.Decidable.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Logic.PropExtensionality.\nSet Implicit Arguments.\nSet Strict Implicit.\n\nRequire Import Oqarina.CoqExt.all.\nRequire Import Oqarina.formalisms.Contracts.Specification.\nRequire Import Oqarina.formalisms.Contracts.MetaTheory.\n\nSection Assume_Guarantee_Contracts.\n(*| .. coq:: |*)\n\n(*|\n\nA/G Contracts\n=============\n\nIn this section, we define the notion of Assume/Guarantee contracts (or A/G contract). A :coq:`AG_Contract` refines the notion of contract from the meta-theory to components.\n\nWithout loss of generality, we define a component as a set of variables (:coq:`V`) that validates a specific assertion, i.e. a function whose signature is :coq:`list V -> Prop`. For instance, the set of static configuration parameters of a component, or a trace generated by some behavioral description.\n\nFor an A/G contract, an assumption (A) states assumptions made on the environment by a model and a guarantee (G) states guarantees offered by a model. They are both assertions on the same set of variables.\n\nA/G contracts trivially meet all the meta-theory lemmas proved above.\nWe only prove a subset of them. Proofs follow the same schema: we map\nan A/G contract to a general contract and conclude.\n\n|*)\n\nImport Contract_Notations.\n\nVariable V : Type.\nContext `{spec : Specification V}.\n\nDefinition Assertion: Type := V -> Prop.\nDefinition Component := Assertion.\nDefinition Environment := Assertion.\n\nRecord AG_Contract := {\n    A: Assertion ;\n    G: Assertion ;\n}.\n\nDefinition AG_Contract_to_Contract (AG : AG_Contract) := {|\n    Ec := AG.(A) ;\n    Mc := AG.(G) ;\n|}.\n\nNotation \"@ c\" := (AG_Contract_to_Contract c)\n    (at level 70 , no associativity).\n\n(*| A saturated contract is an A/G contract defines by the following rule predicate. It is an idemptotent function. |*)\n\nDefinition Saturate (AG : AG_Contract) := {|\n    A := AG.(A);\n    G := fun x => (AG.(A) x -> AG.(G) x);\n|}.\n\nLemma Saturate_idempotent: forall ag,\n    (@Saturate ag) == (@ Saturate (Saturate ag)).\nProof.\n    intros.\n    unfold AG_Contract_to_Contract.\n    simpl.\n\n    assert (\n        (fun x => A ag x -> G ag x) =\n        (fun x => A ag x -> A ag x -> G ag x)\n    ).\n    apply functional_extensionality. intros.\n    apply propositional_extensionality.\n    firstorder.\n\n    rewrite H. reflexivity.\nQed.\n\n(*| A saturated contract is equivalent to the original contract if\nthe environment is compatible with the contract.\n\nNote: :cite:`benvenisteContractsSystemsDesign`, p36 introduces this lemma without proof. It misses the hypothesis on the environment. |*)\n\nLemma Saturate_equiv: forall ag,\n    (forall v, v ⊢e (@ ag)) ->\n        (@ Saturate ag) == (@ ag).\nProof.\n    intros. unfold Saturate.\n    unfold AG_Contract_to_Contract.\n    simpl. firstorder.\nQed.\n\n(*| The notion of contract refinement and composition is directly inherited from the meta-theory.\n\nWe demonstrate that a saturated contract preserves some initial properties, e.g. equivalence, compatibility, etc. |*)\n\nTheorem contract_extensionality : forall (c1 c2 : AG_Contract),\n    (@c1) == (@c2) -> Saturate c1 = Saturate c2.\nProof.\n    simpl.\n    intros. firstorder.\n    unfold refines in *.\n    simpl in *.\n    unfold Saturate.\n\n    assert (\n        (fun x : V => A c1 x -> G c1 x) =\n        (fun x : V => A c2 x -> G c2 x)\n    ).\n    apply functional_extensionality. intros.\n    specialize (H x).\n    specialize (H0 x).\n    apply propositional_extensionality. firstorder.\n\n    assert (forall m, A c1 m = A c2 m).\n    intros.\n    specialize (H m).\n    specialize (H0 m).\n    apply propositional_extensionality. firstorder.\n\n    assert (A c1 = A c2).\n    apply functional_extensionality. apply H2.\n\n    rewrite H1. rewrite H3. reflexivity.\nQed.\n\nLemma implements_implements_saturate: forall c v,\n    v ⊢m (@c) -> v ⊢m (@(Saturate c)).\nProof.\n    simpl. firstorder.\nQed.\n\nLemma implements_saturate_implements: forall c v,\n    (forall v, v ⊢e (@ c)) ->\n        v ⊢m (@(Saturate c)) -> v ⊢m (@c).\nProof.\n    simpl. firstorder.\nQed.\n\n(*| .. coq:: none |*)\nEnd Assume_Guarantee_Contracts.\n(*| .. coq:: |*)\n\nModule AG_Contract_Notations.\n\nExport Contract_Notations.\n\nNotation \"@ c\" := (AG_Contract_to_Contract c)\n    (at level 70 , no associativity).\n\nEnd AG_Contract_Notations.\n", "meta": {"author": "Oqarina", "repo": "oqarina", "sha": "5a5ea65688188e462b20d30ee4e5eba08285f629", "save_path": "github-repos/coq/Oqarina-oqarina", "path": "github-repos/coq/Oqarina-oqarina/oqarina-5a5ea65688188e462b20d30ee4e5eba08285f629/src/formalisms/Contracts/AG_Contracts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2513083247123448}}
{"text": "(* \n * © 2019 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     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": "mit-ll", "repo": "SPICY", "sha": "ad89c31a093ed2e0b7b4ef55c87ec9b175749fe0", "save_path": "github-repos/coq/mit-ll-SPICY", "path": "github-repos/coq/mit-ll-SPICY/SPICY-ad89c31a093ed2e0b7b4ef55c87ec9b175749fe0/src/RealWorld.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2512970110535083}}
{"text": "\nRequire Import Axioms.\nRequire Import Tactics.\nRequire Import Sigma.\nRequire Import Equality.\nRequire Import Relation.\nRequire Import Syntax.\nRequire Import Ofe.\nRequire Import Uniform.\nRequire Import Spaces.\nRequire Import Dynamic.\nRequire Import Hygiene.\nRequire Import Equivalence.\nRequire Import Urelsp.\nRequire Import Intensional.\nRequire Import Ordinal.\nRequire Import Candidate.\nRequire Import Ceiling.\nRequire Import Truncate.\nRequire Import MapTerm.\nRequire Import Extend.\nRequire Import Standard.\nRequire Import Equivalences.\nRequire Import ExtendTruncate.\n\nRequire Import SemanticsPi.\n\n\nDefinition prod_action\n  (w : ordinal) (A B : wurel w)\n  : nat -> relation (wterm w)\n  :=\n  fun i m m' =>\n    exists n n' p p', \n      hygiene clo m\n      /\\ hygiene clo m'\n      /\\ star step m (ppair n p)\n      /\\ star step m' (ppair n' p')\n      /\\ rel A i n n'\n      /\\ rel B i p p'.\n\n\nLemma prod_uniform :\n  forall w A B, uniform _ (prod_action w A B).\nProof.\nintros w A B.\ndo2 3 split.\n\n(* closed *)\n{\nintros i m n H.\ndecompose H; auto.\n}\n\n(* equiv *)\n{\nintros i m m' n n' Hclm' Hcln' Hequivm Hequivn H.\ndecompose H.\nintros p q r t _ _ Hstepsm Hstepsn Hpq Hrt.\nso (equiv_eval _#4 Hequivm (conj Hstepsm value_ppair)) as (m'' & (Hstepsm' & _) & Hmc).\ninvertc_mc Hmc.\nintros p' Hequivp r' Hequivr <-.\nfold (ppair p' r') in *.\nso (equiv_eval _#4 Hequivn (conj Hstepsn value_ppair)) as (n'' & (Hstepsn' & _) & Hmc).\ninvertc_mc Hmc.\nintros q' Hequivq t' Hequivt <-.\nfold (ppair q' t') in *.\nexists p', q', r', t'.\nso (hygiene_invert_auto _#5 (steps_hygiene _#4 Hstepsm' Hclm')) as H; cbn in H.\ndestruct H as (Hclp' & Hclr' & _).\nso (hygiene_invert_auto _#5 (steps_hygiene _#4 Hstepsn' Hcln')) as H; cbn in H.\ndestruct H as (Hclq' & Hclt' & _).\ndo2 5 split; auto; eapply urel_equiv; eauto.\n}\n\n(* zigzag *)\n{\nintros i m n p q Hmn Hpn Hpq.\ndecompose Hmn.\nintros m1 n1 m2 n2 Hclm _ Hstepsm Hstepsn Hmn1 Hmn2.\ndecompose Hpn.\nintros p1 n1' p2 n2' _ _ Hstepsp Hstepsn' Hpn1 Hpn2.\ndecompose Hpq.\nintros p1' q1 p2' q2 _ Hclq Hstepsp' Hstepsq Hpq1 Hpq2.\ninjection (determinism_eval _#4 (conj Hstepsn value_ppair) (conj Hstepsn' value_ppair)).\nintros <- <-.\ninjection (determinism_eval _#4 (conj Hstepsp value_ppair) (conj Hstepsp' value_ppair)).\nintros <- <-.\nexists m1, q1, m2, q2.\ndo2 5 split; eauto using urel_zigzag.\n}\n\n(* downward *)\n{\nintros i m n H.\ndecompose H.\nintros p q r t Hclm Hcln Hstepsm Hstepsn Hpq Hrt.\nexists p, q, r, t.\ndo2 5 split; auto using urel_downward.\n}\nQed.\n\n\nDefinition prod_urel w A B : wurel w\n  :=\n  mk_urel (prod_action w A B) (prod_uniform _ _ _).\n\n\nLemma ceiling_prod :\n  forall n w A B,\n    ceiling (S n) (prod_urel w A B)\n    =\n    prod_urel w\n      (ceiling (S n) A)\n      (ceiling (S n) B).\nProof.\nintros n w A B.\napply urel_extensionality.\nfextensionality 3.\nintros i m p.\ncbn.\npextensionality.\n  {\n  intros (Hi & Hact).\n  decompose Hact.\n  intros m1 p1 m2 p2 Hclm Hclp Hstepsm Hstepsp Hmp1 Hmp2.\n  exists m1, p1, m2, p2.\n  do2 5 split; auto; split; auto.\n  }\n\n  {\n  intros Hact.\n  decompose Hact.\n  intros m1 p1 m2 p2 Hclm Hclp Hstepsm Hstepsp Hmp1 Hmp2.\n  destruct Hmp1 as (Hi & Hmp1).\n  destruct Hmp2 as (_ & Hmp2).\n  split; auto.\n  exists m1, p1, m2, p2.\n  do2 5 split; auto.\n  }\nQed.\n\n\nLemma extend_prod :\n  forall v w (h : v <<= w) A B,\n    extend_urel v w (prod_urel v A B)\n    =\n    prod_urel w (extend_urel v w A) (extend_urel v w B).\nProof.\nintros v w h A B.\napply urel_extensionality.\nfextensionality 3.\nintros i m p.\ncbn.\npextensionality.\n  {\n  intro H.\n  decompose H.\n  intros m1 p1 m2 p2 Hclm Hclp Hstepsm Hstepsp Hmp1 Hmp2.\n  so (map_steps_form _#5 Hstepsm) as (m' & Heq & Hstepsm').\n  so (map_eq_ppair_invert _#6 (eqsymm Heq)) as (m1' & m2' & -> & <- & <-); clear Heq.\n  so (map_steps_form _#5 Hstepsp) as (p' & Heq & Hstepsp').\n  so (map_eq_ppair_invert _#6 (eqsymm Heq)) as (p1' & p2' & -> & <- & <-); clear Heq.\n  exists m1', p1', m2', p2'.\n  do2 4 split; eauto using map_hygiene_conv.\n  }\n\n  {\n  intro H.\n  decompose H.\n  intros m1 p1 m2 p2 Hclm Hclp Hstepsm Hstepsp Hmp1 Hmp2.\n  cbn in Hmp1, Hmp2.\n  exists (map_term (extend w v) m1), (map_term (extend w v) p1), (map_term (extend w v) m2), (map_term (extend w v) p2).\n  do2 4 split; auto using map_hygiene.\n    {\n    so (map_steps _ _ (extend w v) _ _ Hstepsm) as H.\n    simpmapin H.\n    exact H.\n    }\n\n    {\n    so (map_steps _ _ (extend w v) _ _ Hstepsp) as H.\n    simpmapin H.\n    exact H.\n    }\n  }\nQed.\n\n\nDefinition iuprod (w : ordinal) (A B : wiurel w) : wiurel w\n  :=\n  (prod_urel w (den A) (den B),\n   meta_pair (meta_iurel A) \n     (meta_fn (den A) \n      (nearrow_compose meta_iurel_ne \n         (semiconst_ne (den A) B)))).\n\n\nLemma iuprod_inj :\n  forall w A A' B B',\n    iuprod w A B = iuprod w A' B'\n    -> A = A'\n       /\\ (forall j m p, rel (den A) j m p -> iutruncate (S j) B = iutruncate (S j) B').\nProof.\nintros w A A' B B' Heq.\nunfold iupi in Heq.\nso (f_equal (fun z => snd z) Heq) as Heq'.\ncbn in Heq'.\nso (meta_pair_inj _#5 Heq') as (H3 & H4).\nso (meta_iurel_inj _#3 H3); subst A'.\nsplit; auto.\nintros i m p Hmp.\nso (meta_fn_inj _#5 H4) as H5.\nso (eq_dep_impl_eq_snd _#5 H5) as H6.\nso (f_equal (fun f => pi1 f (urelspinj (den A) i m p Hmp)) H6) as H7.\ncbn in H7.\nso (meta_iurel_inj _#3 H7) as H8.\nunfold semiconst in H8.\nrewrite -> !urelsp_index_inj in H8.\nexact H8.\nQed.\n\n\nLemma iutruncate_iuprod :\n  forall n w A B,\n    iutruncate (S n) (iuprod w A B)\n    =\n    iuprod w \n      (iutruncate (S n) A)\n      (iutruncate (S n) B).\nProof.\nintros n w A B.\nunfold iuprod.\nunfold iutruncate.\ncbn [fst snd].\nf_equal.\n  {\n  apply ceiling_prod.\n  }\n\n  {\n  fold (iutruncate (S n) B).\n  rewrite -> !meta_truncate_pair; try omega.\n  f_equal.\n    {\n    apply meta_truncate_iurel; try omega.\n    }\n  rewrite -> meta_truncate_fn; try omega.\n  f_equal.\n  apply nearrow_extensionality.\n  intro C.\n  cbn -[meta_truncate].\n  rewrite -> meta_truncate_iurel; try omega.\n  f_equal.\n  unfold semiconst.\n  rewrite <- urelsp_index_embed_ceiling.\n  rewrite -> !iutruncate_combine.\n  rewrite -> Nat.min_comm.\n  reflexivity.\n  }\nQed.\n\n\nLemma extend_iuprod :\n  forall v w (h : v <<= w) A B,\n    extend_iurel h (iuprod v A B)\n    =\n    iuprod w (extend_iurel h A) (extend_iurel h B).\nProof.\nintros v w h A B.\nunfold iuprod, extend_iurel.\ncbn.\nf_equal.\n  {\n  apply (extend_prod v w h).\n  }\n\n  {\n  unfold meta_iurel.\n  cbn.\n  rewrite -> !extend_meta_pair.\n  rewrite -> extend_meta_urel.\n  rewrite -> extend_meta_fn.\n  f_equal.\n  f_equal.\n  f_equal.\n  apply exT_extensionality_prop.\n  cbn.\n  fextensionality 1.\n  intro x.\n  rewrite -> extend_meta_iurel.\n  f_equal.\n  unfold semiconst.\n  rewrite <- iutruncate_extend_iurel.\n  rewrite -> urelsp_index_deextend.\n  reflexivity.\n  }\nQed.\n\n\nDefinition sigma_action\n  (w : ordinal) (A : wurel w) (B : urelsp_car A -> wurel w)\n  : nat -> relation (wterm w)\n  :=\n  fun i m m' =>\n    exists n n' p p' (Hn : rel A i n n'),\n      hygiene clo m\n      /\\ hygiene clo m'\n      /\\ star step m (ppair n p)\n      /\\ star step m' (ppair n' p')\n      /\\ rel (B (urelspinj A i n n' Hn)) i p p'.\n\n\nLemma sigma_uniform :\n  forall w A (B : urelsp A -n> wurel_ofe w), uniform _ (sigma_action w A (pi1 B)).\nProof.\nintros w A B.\ndo2 3 split.\n\n(* closed *)\n{\nintros i m n H.\ndecompose H; auto.\n}\n\n(* equiv *)\n{\nintros i m m' n n' Hclm' Hcln' Hequivm Hequivn H.\ndecompose H.\nintros p q r t Hpq _ _ Hstepsm Hstepsn Hrt.\nso (equiv_eval _#4 Hequivm (conj Hstepsm value_ppair)) as (m'' & (Hstepsm' & _) & Hmc).\ninvertc_mc Hmc.\nintros p' Hequivp r' Hequivr <-.\nfold (ppair p' r') in *.\nso (equiv_eval _#4 Hequivn (conj Hstepsn value_ppair)) as (n'' & (Hstepsn' & _) & Hmc).\ninvertc_mc Hmc.\nintros q' Hequivq t' Hequivt <-.\nfold (ppair q' t') in *.\nexists p', q', r', t'.\nso (hygiene_invert_auto _#5 (steps_hygiene _#4 Hstepsm' Hclm')) as H; cbn in H.\ndestruct H as (Hclp' & Hclr' & _).\nso (hygiene_invert_auto _#5 (steps_hygiene _#4 Hstepsn' Hcln')) as H; cbn in H.\ndestruct H as (Hclq' & Hclt' & _).\nassert (rel A i p' q') as Hpq'.\n  {\n  eapply urel_equiv; eauto.\n  }\nexists Hpq'.\ndo2 4 split; auto.\nreplace (pi1 B (urelspinj A i p' q' Hpq')) with (pi1 B (urelspinj A i p q Hpq)).\n2:{\n  f_equal.\n  apply urelspinj_equal.\n  eapply urel_equiv_2; eauto.\n  }\neapply urel_equiv; eauto.\n}\n\n(* zigzag *)\n{\nintros i m n p q Hmn Hpn Hpq.\ndecompose Hmn.\nintros m1 n1 m2 n2 Hmn1 Hclm _ Hstepsm Hstepsn Hmn2.\ndecompose Hpn.\nintros p1 n1' p2 n2' Hpn1 _ _ Hstepsp Hstepsn' Hpn2.\ndecompose Hpq.\nintros p1' q1 p2' q2 Hpq1 _ Hclq Hstepsp' Hstepsq Hpq2.\ninjection (determinism_eval _#4 (conj Hstepsn value_ppair) (conj Hstepsn' value_ppair)).\nintros <- <-.\ninjection (determinism_eval _#4 (conj Hstepsp value_ppair) (conj Hstepsp' value_ppair)).\nintros <- <-.\nso (urel_zigzag _#7 Hmn1 Hpn1 Hpq1) as Hmq1.\nexists m1, q1, m2, q2, Hmq1.\ndo2 4 split; auto.\napply (urel_zigzag _#4 n2 p2); auto.\n  {\n  force_exact Hmn2.\n  f_equal; f_equal.\n  apply urelspinj_equal; auto.\n  }\n\n  {\n  force_exact Hpn2.\n  f_equal; f_equal.\n  apply urelspinj_equal; auto.\n  }\n\n  {\n  force_exact Hpq2.\n  f_equal; f_equal.\n  apply urelspinj_equal; auto.\n  }\n}\n\n(* downward *)\n{\nintros i m n H.\ndecompose H.\nintros p q r t Hpq Hclm Hcln Hstepsm Hstepsn Hrt.\nso (urel_downward _#5 Hpq) as Hpq'.\nexists p, q, r, t, Hpq'.\ndo2 4 split; auto.\nrefine (rel_from_dist _#6 _ (urel_downward _#5 Hrt)).\napply (pi2 B).\napply urelspinj_dist_diff; auto.\n}\nQed.\n\n\nDefinition sigma_urel w A B :=\n  mk_urel (sigma_action w A (pi1 B)) (sigma_uniform _ _ _).\n\n\nLemma prod_urel_eq_sigma_urel :\n  forall w A (B : wiurel w),\n    prod_urel w A (den B)\n    =\n    sigma_urel w A (nearrow_compose den_ne (semiconst_ne A B)).\nProof.\nintros w A B.\napply urel_extensionality.\nfextensionality 3.\nintros i' m p.\ncbn.\npextensionality.\n  {\n  intro H.\n  decompose H.\n  intros m1 p1 m2 p2 Hclm Hclp Hstepsm Hstepsp Hmp1 Hmp2.\n  exists m1, p1, m2, p2, Hmp1.\n  do2 4 split; auto.\n  rewrite -> urelsp_index_inj.\n  split; [omega |].\n  auto.\n  }\n\n  {\n  intro H.\n  decompose H.\n  intros m1 p1 m2 p2 Hmp1 Hclm Hclp Hstepsm Hstepsp Hmp2.\n  exists m1, p1, m2, p2.\n  do2 5 split; auto.\n  rewrite -> urelsp_index_inj in Hmp2.\n  destruct Hmp2; auto.\n  }\nQed.\n\n\nLemma ceiling_sigma :\n  forall n w A B,\n    ceiling (S n) (sigma_urel w A B)\n    =\n    sigma_urel w\n      (ceiling (S n) A)\n      (nearrow_compose2 (embed_ceiling_ne (S n) A) (ceiling_ne (S n)) B).\nProof.\nintros n w A B.\napply urel_extensionality.\nfextensionality 3.\nintros i m p.\ncbn.\npextensionality.\n  {\n  intros (Hi, Hact).\n  decompose Hact.\n  intros m1 p1 m2 p2 Hmp1 Hclm Hclp Hstepsm Hstepsp Hmp2.\n  exists m1, p1, m2, p2, (conj Hi Hmp1).\n  do2 4 split; auto.\n  split; auto.\n  rewrite -> embed_ceiling_urelspinj; auto.\n  }\n\n  {\n  intro Hact.\n  decompose Hact.\n  intros m1 p1 m2 p2 Hmp1 Hclm Hclp Hstepsm Hstepsp Hmp2.\n  destruct Hmp1 as (Hi & Hmp1).\n  destruct Hmp2 as (_ & Hmp2).\n  split; auto.\n  exists m1, p1, m2, p2, Hmp1.\n  do2 4 split; auto.\n  rewrite -> embed_ceiling_urelspinj in Hmp2; auto.\n  }\nQed.\n\n\nLemma extend_sigma :\n  forall v w (h : v <<= w) A B,\n    extend_urel v w (sigma_urel v A B)\n    =\n    sigma_urel w \n      (extend_urel v w A)\n      (nearrow_compose2 (deextend_urelsp_ne h A) (extend_urel_ne v w) B).\nProof.\nintros v w h A B.\napply urel_extensionality.\nfextensionality 3.\nintros i m p.\ncbn.\npextensionality.\n  {\n  intro H.\n  decompose H.\n  intros m1 p1 m2 p2 Hmp1 Hclm Hclp Hstepsm Hstepsp Hmp2.\n  so (map_steps_form _#5 Hstepsm) as (m' & Heq & Hstepsm').\n  so (map_eq_ppair_invert _#6 (eqsymm Heq)) as (m1' & m2' & -> & <- & <-); clear Heq.\n  so (map_steps_form _#5 Hstepsp) as (p' & Heq & Hstepsp').\n  so (map_eq_ppair_invert _#6 (eqsymm Heq)) as (p1' & p2' & -> & <- & <-); clear Heq.\n  exists m1', p1', m2', p2', Hmp1.\n  do2 4 split; eauto using map_hygiene_conv.\n  rewrite -> deextend_urelsp_urelspinj.\n  cbn.\n  exact Hmp2.\n  }\n\n  {\n  intro H.\n  decompose H.\n  intros m1 p1 m2 p2 Hmp1 Hclm Hclp Hstepsm Hstepsp Hmp2.\n  cbn in Hmp1.\n  exists (map_term (extend w v) m1), (map_term (extend w v) p1), (map_term (extend w v) m2), (map_term (extend w v) p2), Hmp1.\n  do2 4 split; auto using map_hygiene.\n    {\n    so (map_steps _ _ (extend w v) _ _ Hstepsm) as H.\n    simpmapin H.\n    exact H.\n    }\n\n    {\n    so (map_steps _ _ (extend w v) _ _ Hstepsp) as H.\n    simpmapin H.\n    exact H.\n    }\n\n    {\n    cbn in Hmp2.\n    rewrite -> deextend_urelsp_urelspinj in Hmp2.\n    exact Hmp2.\n    }\n  }\nQed.\n\n\nDefinition iusigma (w : ordinal) (A : wiurel w) (B : urelsp (den A) -n> wiurel_ofe w) : wiurel w\n  :=\n  (sigma_urel w (den A) (nearrow_compose den_ne B),\n   meta_pair (meta_iurel A) \n     (meta_fn (den A) \n      (nearrow_compose meta_iurel_ne B))).\n\n\nLemma iuprod_eq_iusigma :\n  forall w A B,\n    iuprod w A B\n    =\n    iusigma w A (semiconst_ne (den A) B).\nProof.\nintros w A B.\napply prod_extensionality; auto.\ncbn.\napply prod_urel_eq_sigma_urel.\nQed.\n\n\nLemma iusigma_inj :\n  forall w A A' B B',\n    iusigma w A B = iusigma w A' B'\n    -> eq_dep (wiurel w) (fun r => urelsp (den r) -n> wiurel_ofe w) A B A' B'.\nProof.\nintros w A A' B B' Heq.\nunfold iusigma in Heq.\nso (f_equal (fun z => snd z) Heq) as Heq'.\ncbn in Heq'.\nso (meta_pair_inj _#5 Heq') as (H3 & H4).\nso (meta_iurel_inj _#3 H3); subst A'.\nso (meta_fn_inj _#5 H4) as H5.\napply eq_impl_eq_dep_snd.\nclear Heq Heq' H3 H4.\nso (eq_dep_impl_eq_snd _#5 H5) as Heq.\napply nearrow_extensionality.\nintro x.\nso (f_equal (fun z => pi1 z x) Heq) as Heq'.\ncbn in Heq'.\neapply meta_iurel_inj; eauto.\nQed.\n\n\nLemma iutruncate_iusigma :\n  forall n w A B,\n    iutruncate (S n) (iusigma w A B)\n    =\n    iusigma w \n      (iutruncate (S n) A)\n      (nearrow_compose\n         (nearrow_compose (iutruncate_ne (S n)) B)\n         (embed_ceiling_ne (S n) (den A))).\nProof.\nintros n w A B.\nassert (S n > 0) as Hpos by omega.\nunfold iusigma.\nunfold iutruncate.\nunfold den.\ncbn [fst snd].\nf_equal.\n  {\n  rewrite -> ceiling_sigma.\n  f_equal.\n  apply nearrow_extensionality.\n  auto.\n  }\n\n  {\n  rewrite -> !meta_truncate_pair; auto.\n  f_equal.\n    {\n    apply meta_truncate_iurel; auto.\n    }\n  rewrite -> meta_truncate_fn; auto.\n  f_equal.\n  apply nearrow_extensionality.\n  intro C.\n  cbn -[meta_truncate].\n  apply meta_truncate_iurel; auto.\n  }\nQed.\n\n\nLemma extend_iusigma :\n  forall v w (h : v <<= w) A B,\n    extend_iurel h (iusigma v A B)\n    =\n    iusigma w (extend_iurel h A)\n      (nearrow_compose\n         (nearrow_compose (extend_iurel_ne h) B)\n         (deextend_urelsp_ne h (den A))).\nProof.\nintros v w h A B.\nunfold iusigma, extend_iurel.\ncbn.\nf_equal.\n  {\n  rewrite -> (extend_sigma _ _ h).\n  f_equal.\n  apply nearrow_extensionality; auto.\n  }\nunfold meta_iurel.\ncbn.\nrewrite -> !extend_meta_pair.\nrewrite -> extend_meta_urel.\nrewrite -> extend_meta_fn.\nf_equal.\nf_equal.\nf_equal.\napply exT_extensionality_prop.\ncbn.\nfextensionality 1.\nintro x.\nrewrite -> extend_meta_iurel.\nreflexivity.\nQed.\n\n\nLemma prod_action_ppair :\n  forall w A B i m1 m2 n1 n2,\n    rel A i m1 n1\n    -> rel B i m2 n2\n    -> prod_action w A B i (ppair m1 m2) (ppair n1 n2).\nProof.\nintros w A B i m1 m2 n1 n2 H1 H2.\nexists m1, n1, m2, n2.\nso (urel_closed _#5 H1) as (Hclm1 & Hcln1).\nso (urel_closed _#5 H2) as (Hclm2 & Hcln2).\ndo2 4 split; auto using star_refl; apply hygiene_auto; cbn; auto.\nQed.\n\n\nLocal Ltac prove_hygiene :=\n  repeat (first [ apply hygiene_shift_permit\n                | apply hygiene_sumbool\n                | apply hygiene_auto; cbn [row_rect nat_rect]; repeat2 split; auto\n                ]);\n  eauto using hygiene_weaken, clo_min, hygiene_shift', hygiene_subst1;\n  try (apply hygiene_var; cbn; auto; done).\n\n\nLemma prod_action_ppi1 :\n  forall w A B i m n,\n    prod_action w A B i m n\n    -> rel A i (ppi1 m) (ppi1 n).\nProof.\nintros w A B i m n H.\ndecompose H.\nintros m1 n1 m2 n2 Hclm Hcln Hsteps Hsteps' Hmn1 Hmn2.\nrefine (urel_equiv _#7 _ _ _ _ Hmn1); try prove_hygiene.\n  {\n  apply equiv_symm.\n  eapply equiv_trans.\n    {\n    apply equiv_ppi1.\n    eapply steps_equiv; eauto.\n    }\n  apply steps_equiv; apply star_one; apply step_ppi12.\n  }\n\n  {\n  apply equiv_symm.\n  eapply equiv_trans.\n    {\n    apply equiv_ppi1.\n    eapply steps_equiv; eauto.\n    }\n  apply steps_equiv; apply star_one; apply step_ppi12.\n  }\nQed.\n\n\nLemma prod_action_ppi2 :\n  forall w A B i m n,\n    prod_action w A B i m n\n    -> rel B i (ppi2 m) (ppi2 n).\nProof.\nintros w A B i m n H.\ndecompose H.\nintros m1 n1 m2 n2 Hclm Hcln Hsteps Hsteps' Hmn1 Hmn2.\nrefine (urel_equiv _#7 _ _ _ _ Hmn2); try prove_hygiene.\n  {\n  apply equiv_symm.\n  eapply equiv_trans.\n    {\n    apply equiv_ppi2.\n    eapply steps_equiv; eauto.\n    }\n  apply steps_equiv; apply star_one; apply step_ppi22.\n  }\n\n  {\n  apply equiv_symm.\n  eapply equiv_trans.\n    {\n    apply equiv_ppi2.\n    eapply steps_equiv; eauto.\n    }\n  apply steps_equiv; apply star_one; apply step_ppi22.\n  }\nQed.\n\n\nLemma prod_action_ppair1 :\n  forall w A B i m n r p,\n    hygiene clo (ppair m n)\n    -> prod_action w A B i r p\n    -> rel A i m (ppi1 p)\n    -> rel B i n (ppi2 p)\n    -> prod_action w A B i (ppair m n) p.\nProof.\nintros w A B i m n r p Hclmn Hrp H1 H2.\ndecompose Hrp.\nintros _ p1 _ p2 _ Hclp _ Hstepsp _ _.\nso (hygiene_invert_auto _#5 (steps_hygiene _#4 Hstepsp Hclp)) as H; cbn in H.\ndestruct H as (Hclp1 & Hclp2 & _).\nexists m, p1, n, p2.\ndo2 5 split; auto using star_refl.\n  {\n  eapply urel_equiv_2; eauto.\n  apply steps_equiv.\n  eapply star_trans.\n    {\n    apply (star_map' _ _ ppi1); auto using step_ppi11.\n    exact Hstepsp.\n    }\n  apply star_one; apply step_ppi12.\n  }\n\n  {\n  eapply urel_equiv_2; eauto.\n  apply steps_equiv.\n  eapply star_trans.\n    {\n    apply (star_map' _ _ ppi2); auto using step_ppi21.\n    exact Hstepsp.\n    }\n  apply star_one; apply step_ppi22.\n  }\nQed.\n\n\nLemma embed_ceiling_urelspinj_prod :\n  forall i w A B j m n p q (Hj : j < S i) (Hmn : rel A j m n) (Hpq : rel B j p q),\n    embed_ceiling (S i) (prod_urel w A B)\n      (transport (eqsymm (ceiling_prod i w A B)) urelsp_car\n         (urelspinj (prod_urel w (ceiling (S i) A) (ceiling (S i) B)) j\n            (ppair m p) (ppair n q)\n            (prod_action_ppair w (ceiling (S i) A) (ceiling (S i) B) j m p n q\n              (conj Hj Hmn) (conj Hj Hpq))))\n    =\n    urelspinj (prod_urel w A B) j (ppair m p) (ppair n q)\n      (prod_action_ppair w A B j m p n q Hmn Hpq).\nProof.\nintros i w A B j m n p q Hj Hmn Hpq.\napply exT_extensionality_prop.\ncbn.\nrewrite -> (pi1_transport_dep_lift _ _ urelsp_car_rhs _ _ (eqsymm (ceiling_prod i w A B))).\ncbn.\nrewrite -> transport_const.\nfextensionality 2.\nintros k r.\npextensionality.\n  {\n  intros (Hk & Hact).\n  split; auto.\n  decompose Hact.\n  intros r1 n' r2 q' Hclr Hclnq Hsteps Hsteps' H1 H2.\n  exists r1, n', r2, q'.\n  do2 5 split; auto.\n    {\n    destruct H1; auto.\n    }\n\n    {\n    destruct H2; auto.\n    }\n  }\n\n  {\n  intros (Hk & Hact).\n  split; auto.\n  decompose Hact.\n  intros r1 n' r2 q' Hclr Hclnq Hsteps Hsteps' H1 H2.\n  exists r1, n', r2, q'.\n  do2 5 split; auto.\n    {\n    split; auto; omega.\n    }\n\n    {\n    split; auto; omega.\n    }\n  }\nQed.\n\n\nLemma deextend_urelsp_urelspinj_prod :\n  forall v w (h : v <<= w) A B i m n p q (Hmn : rel (extend_urel v w A) i m n) (Hpq : rel (extend_urel v w B) i p q),\n    deextend_urelsp h (prod_urel v A B)\n      (transport (eqsymm (extend_prod v w h A B)) urelsp_car\n         (urelspinj (prod_urel w (extend_urel v w A) (extend_urel v w B)) i\n            (ppair m p) (ppair n q)\n            (prod_action_ppair w (extend_urel v w A) (extend_urel v w B) i m p n q Hmn Hpq)))\n    =\n    urelspinj (prod_urel v A B) i (map_term (extend w v) (ppair m p)) (map_term (extend w v) (ppair n q)) \n      (prod_action_ppair v A B i (map_term (extend w v) m) (map_term (extend w v) p) (map_term (extend w v) n) (map_term (extend w v) q) Hmn Hpq).\nProof.\nintros v w h A B i m n p q Hmn Hpq.\napply exT_extensionality_prop.\ncbn.\nfold (ppair (map_term (extend w v) n) (map_term (extend w v) q)).\nrewrite -> (pi1_transport_dep_lift _ _ urelsp_car_rhs _ _ (eqsymm (extend_prod v w h A B))).\ncbn.\nrewrite -> transport_const.\nfextensionality 2.\nintros k r.\npextensionality.\n  {\n  intros (Hk & Hact).\n  split; auto.\n  decompose Hact.\n  intros r1 n' r2 q' Hclr Hclnq Hsteps Hsteps' H1 H2.\n  exists (map_term (extend w v) r1), (map_term (extend w v) n'), (map_term (extend w v) r2), (map_term (extend w v) q').\n  do2 5 split; eauto using map_hygiene_conv.\n    {\n    so (map_hygiene _ _ (extend w v) _ _ Hclnq) as H.\n    simpmapin H.\n    exact H.\n    }\n\n    {\n    so (map_steps _ _ (extend w v) _ _ Hsteps) as H.\n    simpmapin H.\n    rewrite -> extend_term_cancel in H; auto.\n    }\n\n    {\n    so (map_steps _ _ (extend w v) _ _ Hsteps') as H.\n    simpmapin H.\n    auto.\n    }\n  }\n\n  {\n  intros (Hk & Hact).\n  split; auto.\n  decompose Hact.\n  intros r1 n' r2 q' Hclr Hclnq Hsteps Hsteps' H1 H2.\n  exploit (map_steps_form _ _ (extend w v) (ppair n q) (ppair n' q')) as H.\n    {\n    simpmap; auto.\n    }\n  destruct H as (x & Heq & Hsteps'').\n  so (map_eq_ppair_invert _#6 (eqsymm Heq)) as (n'' & q'' & -> & <- & <-).\n  exists (map_term (extend v w) r1), n'', (map_term (extend v w) r2), q''.\n  do2 5 split; auto.\n    {\n    apply map_hygiene; auto.\n    }\n\n    {\n    apply (map_hygiene_conv _ _ (extend w v)).\n    simpmap; auto.\n    }\n\n    {\n    so (map_steps _ _ (extend v w) _ _ Hsteps) as H.\n    simpmapin H; auto.\n    }\n\n    {\n    cbn.\n    rewrite -> !extend_term_cancel; auto.\n    }\n\n    {\n    cbn.\n    rewrite -> !extend_term_cancel; auto.\n    }\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/SemanticsSigma.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.2512281653752975}}
{"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 type_sys_pfam.\nRequire Import dest_close.\nRequire Import pmeq_lemmas.\n\n\nLemma close_type_system_pm {o} :\n  forall (lib : library)\n         (ts : cts(o))\n         (T T' : CTerm)\n         (eq : per)\n         (P P': CTerm)\n         ap ap'\n         A A'\n         bp bp' ba ba'\n         B B'\n         cp cp' ca ca' cb cb'\n         C C'\n         p p'\n         (eqp : per)\n         (eqa : per-fam(eqp))\n         (eqb : per-fam-fam(eqp,eqa)),\n    type_system lib ts\n    -> defines_only_universes lib ts\n    -> computes_to_valc lib T (mkc_pm P ap A bp ba B cp ca cb C p)\n    -> computes_to_valc lib T' (mkc_pm P' ap' A' bp' ba' B' cp' ca' cb' C' p')\n    -> close lib ts P P' eqp\n    -> type_sys_props lib (close lib ts) P P' eqp\n    -> (forall (p p' : CTerm) (ep : eqp p p'),\n          close lib ts (substc p ap A) (substc p' ap' A') (eqa p p' ep))\n    -> type_sys_props_fam lib (close lib ts) eqp ap A ap' A' eqa\n    -> (forall (p p' : CTerm) (ep : eqp p p')\n               (a a' : CTerm) (ea : eqa p p' ep a a'),\n          close lib ts\n                (lsubstc2 bp p ba a B)\n                (lsubstc2 bp' p' ba' a' B')\n                (eqb p p' ep a a' ea))\n    -> type_sys_props_fam_fam lib (close lib ts) eqp eqa bp ba B bp' ba' B' eqb\n    -> equal_Cparams eqp eqa eqb cp ca cb C cp' ca' cb' C'\n    -> eqp p p'\n    -> (forall t t' : CTerm, eq t t' <=> pmeq lib eqp eqa eqb cp ca cb C p t t')\n    -> per_pm lib (close lib ts) T T' eq\n    -> type_sys_props lib (close lib ts) T T' eq.\nProof.\n  introv tysys dou c1 c2 clP tspP clA tspA clB tspB.\n  introv eqc peq 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_pm\".\n    allunfold @per_pm; exrepd.\n    allrw @fold_eq_term_equals.\n    sp_pfam.\n\n    generalize (type_pfamily_eq_term_equals\n                  lib mkc_pm\n                  (close lib ts) T T' T3\n                  eqp1 eqa1 eqb1 cp ca cb C cp' ca' cb' C' p p'\n                  eqp0 eqa0 eqb0 cp ca cb C cp2 ca2 cb2 C2 p p2\n                  P ap A bp ba B cp ca cb C p\n                  P' eqp\n                  ap' A' eqa\n                  bp' ba' B' eqb).\n    introv k; repeat (autodimp k hyp); try (apply eq_type_pfamilies_mkc_pm).\n    repnd; repeat subst.\n    red_eqTs; repeat subst; GC.\n\n    apply eq_term_equals_trans with (eq2 := pmeq lib eqp1 eqa1 eqb1 cp ca cb C p); auto.\n    apply eq_term_equals_trans with (eq2 := pmeq lib eqp0 eqa0 eqb0 cp ca cb C p); auto.\n    apply eq_term_equals_pmeq; try (complete sp).\n    apply eq_term_equals_sym; sp.\n\n\n  + SCase \"type_symmetric\".\n    repdors; subst; dclose_lr;\n    apply CL_pm;\n    clear per;\n    allunfold @per_pm; exrepd;\n    exists eqp0 eqa0 eqb0 p1 p2;\n    exists cp1 cp2 ca1 ca2 cb1 cb2 C1 C2; sp;\n    allrw <-; sp;\n    apply eq_term_equals_trans with (eq2 := eq); sp;\n    try (complete (apply eq_term_equals_sym; sp)).\n\n\n  + SCase \"type_value_respecting\".\n    repdors; subst; apply CL_pm; unfold per_pm.\n\n    (* 1 *)\n    generalize (cequivc_mkc_pm lib T T3 P ap A bp ba B cp ca cb C p c1); intro k.\n    autodimp k hyp; exrepnd.\n\n    generalize (type_pfamily_cequivc\n                  lib mkc_pm (close lib ts) T T3 eqp eqa eqb\n                  P ap A bp ba B cp ca cb C p\n                  P'0 ap'0 A'0 bp'0 ba'0 B'0 cp'0 ca'0 cb'0 C'0 p'0\n                  P' ap' A' bp' ba' B' cp' ca' cb' C' p');\n      intro k; repeat (autodimp k hyp).\n    exists eqp eqa eqb p p'0.\n    exists cp cp'0 ca ca'0 cb cb'0 C C'0; dands; auto.\n\n    (* 2 *)\n    generalize (cequivc_mkc_pm lib T' T3 P' ap' A' bp' ba' B' cp' ca' cb' C' p' c2); intro k.\n    autodimp k hyp; exrepnd.\n\n    generalize (type_pfamily_cequivc\n                  lib mkc_pm (close lib ts) T' T3 eqp eqa eqb\n                  P' ap' A' bp' ba' B' cp' ca' cb' C' p'\n                  P'0 ap'0 A'0 bp'0 ba'0 B'0 cp'0 ca'0 cb'0 C'0 p'0\n                  P ap A bp ba B cp ca cb C p);\n      intro k; repeat (autodimp k hyp).\n    apply type_sys_props_sym; sp.\n    apply @type_sys_props_fam_sym with (P := P) (P' := P'); sp.\n    apply @type_sys_props_fam_fam_sym with (P := P) (P' := P') (ap := ap) (A := A) (ap' := ap') (A' := A'); sp.\n    apply equal_Cparams_sym; sp.\n    apply type_sys_props_implies_term_eq_sym in tspP; sp.\n    apply @type_sys_props_fam_implies_sym_trans_respeq with (P := P) (P' := P') in tspA; sp.\n    apply @type_sys_props_fam_fam_implies_sym_trans_respeq with (P := P) (P' := P') (ap := ap) (A := A) (ap' := ap') (A' := A') in tspB; sp.\n    apply @type_sys_props_fam_implies_eq_fam_sym with (P := P) (P' := P') in tspA; sp.\n    apply @type_sys_props_fam_fam_implies_eq_fam_fam_sym with (P := P) (P' := P') (ap := ap) (A := A) (ap' := ap') (A' := A') in tspB; sp.\n    applydup @type_sys_props_implies_term_eq_sym in tspP as sym; sp.\n\n    exists eqp eqa eqb p' p'0.\n    exists cp' cp'0 ca' ca'0 cb' cb'0 C' C'0; dands; auto.\n    allrw @fold_eq_term_equals.\n    apply eq_term_equals_trans with (eq2 := pmeq lib eqp eqa eqb cp ca cb C p); auto.\n\n    apply eq_term_equals_pmeq2.\n\n    apply type_sys_props_implies_term_eq_sym in tspP; auto.\n    apply type_sys_props_implies_term_eq_trans in tspP; auto.\n    apply @type_sys_props_fam_implies_sym_trans_respeq with (P := P) (P' := P') in tspA; sp.\n    apply @type_sys_props_fam_implies_sym_trans_respeq with (P := P) (P' := P') in tspA; sp.\n    apply @type_sys_props_fam_fam_implies_sym_trans_respeq with (P := P) (P' := P') (ap := ap) (A := A) (ap' := ap') (A' := A') in tspB; sp.\n    apply @type_sys_props_fam_fam_implies_sym_trans_respeq with (P := P) (P' := P') (ap := ap) (A := A) (ap' := ap') (A' := A') in tspB; sp.\n    apply @type_sys_props_fam_implies_sym_trans_respeq with (P := P) (P' := P') in tspA; sp.\n    apply @type_sys_props_fam_fam_implies_sym_trans_respeq with (P := P) (P' := P') (ap := ap) (A := A) (ap' := ap') (A' := A') in tspB; sp.\n\n    apply eq_term_equals_refl.\n    apply (eq_term_equals_fam_refl lib) with (ts := close lib ts) (ap1 := ap) (A1 := A) (ap2 := ap') (A2 := A'); sp.\n    apply (eq_term_equals_fam_fam_refl lib) with (ts := close lib ts) (bp1 := bp) (ba1 := ba) (B1 := B) (bp2 := bp') (ba2 := ba') (B2 := B'); sp.\n    auto.\n    auto.\n\n\n  + SCase \"term_symmetric\".\n    repnud per.\n    exrepnd.\n    sp_pfam.\n    generalize (type_pfamily_sym\n                    lib mkc_pm (close lib ts) T T' eqp0 eqa0 eqb0\n                    cp ca cb C\n                    cp' ca' cb' C'\n                    p p'\n                    P ap A bp ba B cp ca cb C p\n                    eqp eqa eqb\n                    P' ap' A' bp' ba' B' cp' ca' cb' C'); introv k.\n    repeat (autodimp k hyp);\n      try (complete (apply eq_type_pfamilies_mkc_pm)).\n    repnd; subst; red_eqTs; GC; subst.\n\n    unfold term_equality_symmetric; introv Heq.\n\n    dup tspP as tspp.\n    dtsprops tspP.\n    repnud tspPtes.\n    apply eqiff in Heq.\n    apply eqiff.\n\n    eapply pmeq_sym; eauto.\n\n\n  + SCase \"term_transitive\".\n    unfold term_equality_transitive; introv.\n    repeat (rw eqiff); introv pm1 pm2.\n    eapply pmeq_trans; eauto.\n\n\n  + SCase \"term_value_respecting\".\n    introv.\n    repeat (rw eqiff).\n    introv e c; spcast.\n\n    eapply pmeq_cequivc; eauto.\n\n\n  + SCase \"type_gsymmetric\".\n    repdors; subst; split; sp; dclose_lr; clear per; apply CL_pm;\n    allunfold @per_pm; exrepnd.\n\n    (* 1 *)\n    generalize (type_pfamily_sym\n                  lib mkc_pm (close lib ts)\n                  T T3 eqp0 eqa0 eqb0 cp1 ca1 cb1 C1 cp2 ca2 cb2 C2 p1 p2\n                  P ap A bp ba B cp ca cb C p\n                  eqp eqa eqb\n                  P' ap' A' bp' ba' B' cp' ca' cb' C'); intro k.\n    repeat (autodimp k hyp); repnd; subst; red_eqTs; subst; GC.\n    exists eqp0 eqa0 eqb0 p2 p1.\n    exists cp2 cp1 ca2 ca1 cb2 cb1 C2 C1; dands; auto.\n\n    apply eq_term_equals_trans with (eq2 := pmeq lib eqp0 eqa0 eqb0 cp1 ca1 cb1 C1 p1); auto.\n    apply eq_term_equals_pmeq2.\n\n    apply @term_equality_symmetric_eq_term_equals with (eq := eqp); auto.\n    apply type_sys_props_implies_term_eq_sym in tspP; auto.\n    apply @term_equality_transitive_eq_term_equals with (eq := eqp); auto.\n    apply type_sys_props_implies_term_eq_trans in tspP; auto.\n\n    apply term_equality_symmetric_fam_eq_term_equals with (eqp1 := eqp) (eqa1 := eqa); sp.\n    apply @type_sys_props_fam_implies_sym_trans_respeq with (P := P) (P' := P') in tspA; sp.\n    apply term_equality_transitive_fam_eq_term_equals with (eqp1 := eqp) (eqa1 := eqa); sp.\n    apply @type_sys_props_fam_implies_sym_trans_respeq with (P := P) (P' := P') in tspA; sp.\n\n    apply term_equality_symmetric_fam_fam_eq_term_equals with (eqp1 := eqp) (eqa1 := eqa) (eqb1 := eqb); sp.\n    apply @type_sys_props_fam_fam_implies_sym_trans_respeq with (P := P) (P' := P') (ap := ap) (A := A) (ap' := ap') (A' := A') in tspB; sp.\n    apply term_equality_transitive_fam_fam_eq_term_equals with (eqp1 := eqp) (eqa1 := eqa) (eqb1 := eqb); sp.\n    apply @type_sys_props_fam_fam_implies_sym_trans_respeq with (P := P) (P' := P') (ap := ap) (A := A) (ap' := ap') (A' := A') in tspB; sp.\n\n    apply eq_fam_respects_eq_term_equals_eq_term_equals with (eqp1 := eqp) (eqa1 := eqa); sp.\n    apply @type_sys_props_fam_implies_sym_trans_respeq with (P := P) (P' := P') in tspA; sp.\n    apply eq_fam_fam_respects_eq_term_equals_eq_term_equals with (eqp1 := eqp) (eqa1 := eqa) (eqb1 := eqb); sp.\n    apply @type_sys_props_fam_fam_implies_sym_trans_respeq with (P := P) (P' := P') (ap := ap) (A := A) (ap' := ap') (A' := A') in tspB; sp.\n\n    apply eq_term_equals_refl.\n    apply eq_term_equals_fam_trans with (eqp2 := eqp) (eqa2 := eqa); sp.\n    apply eq_term_equals_sym; sp.\n    apply eq_term_equals_fam_sym; sp.\n    apply eq_term_equals_fam_fam_trans with (eqp2 := eqp) (eqa2 := eqa) (eqb2 := eqb); sp.\n    apply eq_term_equals_sym; sp.\n    apply eq_term_equals_fam_sym; sp.\n    apply eq_term_equals_fam_fam_sym; sp.\n\n    apply type_pfamily_implies_equal_Cparams in h1; sp.\n\n    apply type_pfamily_implies_params in h1; sp.\n\n\n    (* 2 *)\n    generalize (type_pfamily_sym2\n                  lib mkc_pm (close lib ts)\n                  T3 T eqp0 eqa0 eqb0 cp1 ca1 cb1 C1 cp2 ca2 cb2 C2 p1 p2\n                  P ap A bp ba B cp ca cb C p\n                  eqp eqa eqb\n                  P' ap' A' bp' ba' B' cp' ca' cb' C'); intro k.\n    repeat (autodimp k hyp); repnd; subst; red_eqTs; subst; GC.\n    exists eqp0 eqa0 eqb0 p2 p1.\n    exists cp2 cp1 ca2 ca1 cb2 cb1 C2 C1; dands; auto.\n\n    apply eq_term_equals_trans with (eq2 := pmeq lib eqp0 eqa0 eqb0 cp1 ca1 cb1 C1 p1); auto.\n    apply eq_term_equals_pmeq2.\n\n    apply @term_equality_symmetric_eq_term_equals with (eq := eqp); auto.\n    apply type_sys_props_implies_term_eq_sym in tspP; auto.\n    apply @term_equality_transitive_eq_term_equals with (eq := eqp); auto.\n    apply type_sys_props_implies_term_eq_trans in tspP; auto.\n\n    apply term_equality_symmetric_fam_eq_term_equals with (eqp1 := eqp) (eqa1 := eqa); sp.\n    apply @type_sys_props_fam_implies_sym_trans_respeq with (P := P) (P' := P') in tspA; sp.\n    apply term_equality_transitive_fam_eq_term_equals with (eqp1 := eqp) (eqa1 := eqa); sp.\n    apply @type_sys_props_fam_implies_sym_trans_respeq with (P := P) (P' := P') in tspA; sp.\n\n    apply term_equality_symmetric_fam_fam_eq_term_equals with (eqp1 := eqp) (eqa1 := eqa) (eqb1 := eqb); sp.\n    apply @type_sys_props_fam_fam_implies_sym_trans_respeq with (P := P) (P' := P') (ap := ap) (A := A) (ap' := ap') (A' := A') in tspB; sp.\n    apply term_equality_transitive_fam_fam_eq_term_equals with (eqp1 := eqp) (eqa1 := eqa) (eqb1 := eqb); sp.\n    apply @type_sys_props_fam_fam_implies_sym_trans_respeq with (P := P) (P' := P') (ap := ap) (A := A) (ap' := ap') (A' := A') in tspB; sp.\n\n    apply eq_fam_respects_eq_term_equals_eq_term_equals with (eqp1 := eqp) (eqa1 := eqa); sp.\n    apply @type_sys_props_fam_implies_sym_trans_respeq with (P := P) (P' := P') in tspA; sp.\n    apply eq_fam_fam_respects_eq_term_equals_eq_term_equals with (eqp1 := eqp) (eqa1 := eqa) (eqb1 := eqb); sp.\n    apply @type_sys_props_fam_fam_implies_sym_trans_respeq with (P := P) (P' := P') (ap := ap) (A := A) (ap' := ap') (A' := A') in tspB; sp.\n\n    apply eq_term_equals_refl.\n    apply eq_term_equals_fam_trans with (eqp2 := eqp) (eqa2 := eqa); sp.\n    apply eq_term_equals_sym; sp.\n    apply eq_term_equals_fam_sym; sp.\n    apply eq_term_equals_fam_fam_trans with (eqp2 := eqp) (eqa2 := eqa) (eqb2 := eqb); sp.\n    apply eq_term_equals_sym; sp.\n    apply eq_term_equals_fam_sym; sp.\n    apply eq_term_equals_fam_fam_sym; sp.\n\n    apply type_pfamily_implies_equal_Cparams in h1; sp.\n\n    apply type_pfamily_implies_params in h1; sp.\n\n\n  + SCase \"type_gtransitive\"; sp.\n\n  + SCase \"type_mtransitive\".\n    repdors; subst; clear per; dclose_lr; allunfold @per_pm; exrepd; sp_pfam.\n\n    (* 1 *)\n    generalize (type_pfamily_trans2 lib\n                  (close lib ts) T3 T T4 mkc_pm\n                  eqp0 eqa0 eqb0\n                  eqp1 eqa1 eqb1\n                  eqp eqa eqb\n                  P ap A bp ba B cp ca cb C p\n                  P' ap' A' bp' ba' B' cp' ca' cb' C'\n                  cp1 ca1 cb1 C1 p1\n                  cp ca cb C p\n                  cp3 ca3 cb3 C3 p3); intro k.\n    repeat (autodimp k hyp); repnd.\n\n    dands; apply CL_pm; unfold per_pm.\n\n    (* 1 - 1 *)\n    exists eqp0 eqa0 eqb0 p1 p3.\n    exists cp1 cp3 ca1 ca3 cb1 cb3 C1 C3; auto.\n\n    (* 1 - 2 *)\n    exists eqp0 eqa0 eqb0 p1 p3.\n    exists cp1 cp3 ca1 ca3 cb1 cb3 C1 C3; dands; auto.\n    apply @eq_term_equals_trans with (eq2 := pmeq lib eqp1 eqa1 eqb1 cp ca cb C p); auto.\n\n    generalize (type_pfamily_sym2\n                  lib mkc_pm (close lib ts) T3 T\n                  eqp0 eqa0 eqb0 cp1 ca1 cb1 C1 cp ca cb C p1 p\n                  P ap A bp ba B cp ca cb C p\n                  eqp eqa eqb\n                  P' ap' A' bp' ba' B' cp' ca' cb' C'); intro j.\n    repeat (autodimp j hyp); repnd; subst; GC; red_eqTs; subst; GC.\n\n    generalize (type_pfamily_eq_term_equals\n                  lib mkc_pm (close lib ts) T T3 T4\n                  eqp0 eqa0 eqb0 cp ca cb C cp1 ca1 cb1 C1 p p1\n                  eqp1 eqa1 eqb1 cp ca cb C cp3 ca3 cb3 C3 p p3\n                  P ap A bp ba B cp ca cb C p\n                  P' eqp\n                  ap' A' eqa\n                  bp' ba' B' eqb); intro l.\n    repeat (autodimp l hyp); repnd; subst; GC; red_eqTs; subst; GC.\n    apply eq_term_equals_pmeq2.\n\n    apply @term_equality_symmetric_eq_term_equals with (eq := eqp); auto.\n    apply type_sys_props_implies_term_eq_sym in tspP; auto.\n    apply @term_equality_transitive_eq_term_equals with (eq := eqp); auto.\n    apply type_sys_props_implies_term_eq_trans in tspP; auto.\n\n    apply @term_equality_symmetric_fam_eq_term_equals with (eqp1 := eqp) (eqa1 := eqa); sp.\n    apply @type_sys_props_fam_implies_sym_trans_respeq with (P := P) (P' := P') in tspA; sp.\n    apply @term_equality_transitive_fam_eq_term_equals with (eqp1 := eqp) (eqa1 := eqa); sp.\n    apply @type_sys_props_fam_implies_sym_trans_respeq with (P := P) (P' := P') in tspA; sp.\n\n    apply @term_equality_symmetric_fam_fam_eq_term_equals with (eqp1 := eqp) (eqa1 := eqa) (eqb1 := eqb); sp.\n    apply @type_sys_props_fam_fam_implies_sym_trans_respeq with (P := P) (P' := P') (ap := ap) (A := A) (ap' := ap') (A' := A') in tspB; sp.\n    apply @term_equality_transitive_fam_fam_eq_term_equals with (eqp1 := eqp) (eqa1 := eqa) (eqb1 := eqb); sp.\n    apply @type_sys_props_fam_fam_implies_sym_trans_respeq with (P := P) (P' := P') (ap := ap) (A := A) (ap' := ap') (A' := A') in tspB; sp.\n\n    apply @eq_fam_respects_eq_term_equals_eq_term_equals with (eqp1 := eqp) (eqa1 := eqa); sp.\n    apply @type_sys_props_fam_implies_sym_trans_respeq with (P := P) (P' := P') in tspA; sp.\n    apply @eq_fam_fam_respects_eq_term_equals_eq_term_equals with (eqp1 := eqp) (eqa1 := eqa) (eqb1 := eqb); sp.\n    apply @type_sys_props_fam_fam_implies_sym_trans_respeq with (P := P) (P' := P') (ap := ap) (A := A) (ap' := ap') (A' := A') in tspB; sp.\n\n    apply @eq_term_equals_trans with (eq2 := eqp); sp.\n    apply eq_term_equals_sym; sp.\n    apply @eq_term_equals_fam_trans with (eqp2 := eqp) (eqa2 := eqa); sp.\n    apply eq_term_equals_sym; sp.\n    apply eq_term_equals_fam_sym; sp.\n    apply @eq_term_equals_fam_fam_trans with (eqp2 := eqp) (eqa2 := eqa) (eqb2 := eqb); sp.\n    apply eq_term_equals_sym; sp.\n    apply eq_term_equals_fam_sym; sp.\n    apply eq_term_equals_fam_fam_sym; sp.\n\n    apply type_pfamily_implies_equal_Cparams in j; sp.\n    apply @equal_Cparams_eq_term_equals with (eqp1 := eqp0) (eqa1 := eqa0) (eqb1 := eqb0); sp.\n\n    apply type_pfamily_implies_params in j; sp.\n    apply l11.\n    apply j5; sp.\n\n\n    (* 2 *)\n    generalize (type_pfamily_trans2\n                  lib (close lib ts) T3 T' T4 mkc_pm\n                  eqp0 eqa0 eqb0\n                  eqp1 eqa1 eqb1\n                  eqp eqa eqb\n                  P' ap' A' bp' ba' B' cp' ca' cb' C' p'\n                  P ap A bp ba B cp ca cb C\n                  cp1 ca1 cb1 C1 p1\n                  cp' ca' cb' C' p'\n                  cp3 ca3 cb3 C3 p3); intro k.\n    repeat (autodimp k hyp); repnd.\n    apply type_sys_props_sym; sp.\n    apply @type_sys_props_fam_sym with (P := P) (P' := P'); sp.\n    apply @type_sys_props_fam_fam_sym with (P := P) (P' := P') (ap := ap) (A := A) (ap' := ap') (A' := A'); sp.\n    apply equal_Cparams_sym; sp.\n    apply type_sys_props_implies_term_eq_sym in tspP; sp.\n    apply @type_sys_props_fam_implies_sym_trans_respeq with (P := P) (P' := P') in tspA; sp.\n    apply @type_sys_props_fam_fam_implies_sym_trans_respeq with (P := P) (P' := P') (ap := ap) (A := A) (ap' := ap') (A' := A') in tspB; sp.\n    apply @type_sys_props_fam_implies_eq_fam_sym with (P := P) (P' := P') in tspA; sp.\n    apply @type_sys_props_fam_fam_implies_eq_fam_fam_sym with (P := P) (P' := P') (ap := ap) (A := A) (ap' := ap') (A' := A') in tspB; sp.\n\n    dands; apply CL_pm; unfold per_pm.\n\n    (* 1 - 1 *)\n    exists eqp0 eqa0 eqb0 p1 p3.\n    exists cp1 cp3 ca1 ca3 cb1 cb3 C1 C3; auto.\n\n    (* 1 - 2 *)\n    exists eqp0 eqa0 eqb0 p1 p3.\n    exists cp1 cp3 ca1 ca3 cb1 cb3 C1 C3; dands; auto.\n    apply @eq_term_equals_trans with (eq2 := pmeq lib eqp1 eqa1 eqb1 cp' ca' cb' C' p'); auto.\n\n    generalize (type_pfamily_sym2\n                  lib mkc_pm (close lib ts) T3 T'\n                  eqp0 eqa0 eqb0 cp1 ca1 cb1 C1 cp' ca' cb' C' p1 p'\n                  P' ap' A' bp' ba' B' cp' ca' cb' C' p'\n                  eqp eqa eqb\n                  P ap A bp ba B cp ca cb C); intro j.\n    repeat (autodimp j hyp); repnd; subst; GC; red_eqTs; subst; GC.\n    apply type_sys_props_sym; sp.\n    apply @type_sys_props_fam_sym with (P := P) (P' := P'); sp.\n    apply @type_sys_props_fam_fam_sym with (P := P) (P' := P') (ap := ap) (A := A) (ap' := ap') (A' := A'); sp.\n    apply equal_Cparams_sym; sp.\n    apply type_sys_props_implies_term_eq_sym in tspP; sp.\n    apply @type_sys_props_fam_implies_sym_trans_respeq with (P := P) (P' := P') in tspA; sp.\n    apply @type_sys_props_fam_fam_implies_sym_trans_respeq with (P := P) (P' := P') (ap := ap) (A := A) (ap' := ap') (A' := A') in tspB; sp.\n    apply @type_sys_props_fam_implies_eq_fam_sym with (P := P) (P' := P') in tspA; sp.\n    apply @type_sys_props_fam_fam_implies_eq_fam_fam_sym with (P := P) (P' := P') (ap := ap) (A := A) (ap' := ap') (A' := A') in tspB; sp.\n\n    generalize (type_pfamily_eq_term_equals\n                  lib mkc_pm (close lib ts) T' T3 T4\n                  eqp0 eqa0 eqb0 cp' ca' cb' C' cp1 ca1 cb1 C1 p' p1\n                  eqp1 eqa1 eqb1 cp' ca' cb' C' cp3 ca3 cb3 C3 p' p3\n                  P' ap' A' bp' ba' B' cp' ca' cb' C' p'\n                  P eqp\n                  ap A eqa\n                  bp ba B eqb); intro l.\n    repeat (autodimp l hyp); repnd; subst; GC; red_eqTs; subst; GC.\n    apply type_sys_props_sym; sp.\n    apply @type_sys_props_fam_sym with (P := P) (P' := P'); sp.\n    apply @type_sys_props_fam_fam_sym with (P := P) (P' := P') (ap := ap) (A := A) (ap' := ap') (A' := A'); sp.\n\n    apply eq_term_equals_pmeq2.\n\n    apply @term_equality_symmetric_eq_term_equals with (eq := eqp); auto.\n    apply type_sys_props_implies_term_eq_sym in tspP; auto.\n    apply @term_equality_transitive_eq_term_equals with (eq := eqp); auto.\n    apply type_sys_props_implies_term_eq_trans in tspP; auto.\n\n    apply @term_equality_symmetric_fam_eq_term_equals with (eqp1 := eqp) (eqa1 := eqa); sp.\n    apply @type_sys_props_fam_implies_sym_trans_respeq with (P := P) (P' := P') in tspA; sp.\n    apply @term_equality_transitive_fam_eq_term_equals with (eqp1 := eqp) (eqa1 := eqa); sp.\n    apply @type_sys_props_fam_implies_sym_trans_respeq with (P := P) (P' := P') in tspA; sp.\n\n    apply @term_equality_symmetric_fam_fam_eq_term_equals with (eqp1 := eqp) (eqa1 := eqa) (eqb1 := eqb); sp.\n    apply @type_sys_props_fam_fam_implies_sym_trans_respeq with (P := P) (P' := P') (ap := ap) (A := A) (ap' := ap') (A' := A') in tspB; sp.\n    apply @term_equality_transitive_fam_fam_eq_term_equals with (eqp1 := eqp) (eqa1 := eqa) (eqb1 := eqb); sp.\n    apply @type_sys_props_fam_fam_implies_sym_trans_respeq with (P := P) (P' := P') (ap := ap) (A := A) (ap' := ap') (A' := A') in tspB; sp.\n\n    apply @eq_fam_respects_eq_term_equals_eq_term_equals with (eqp1 := eqp) (eqa1 := eqa); sp.\n    apply @type_sys_props_fam_implies_sym_trans_respeq with (P := P) (P' := P') in tspA; sp.\n    apply @eq_fam_fam_respects_eq_term_equals_eq_term_equals with (eqp1 := eqp) (eqa1 := eqa) (eqb1 := eqb); sp.\n    apply @type_sys_props_fam_fam_implies_sym_trans_respeq with (P := P) (P' := P') (ap := ap) (A := A) (ap' := ap') (A' := A') in tspB; sp.\n\n    apply @eq_term_equals_trans with (eq2 := eqp); sp.\n    apply eq_term_equals_sym; sp.\n    apply @eq_term_equals_fam_trans with (eqp2 := eqp) (eqa2 := eqa); sp.\n    apply eq_term_equals_sym; sp.\n    apply eq_term_equals_fam_sym; sp.\n    apply @eq_term_equals_fam_fam_trans with (eqp2 := eqp) (eqa2 := eqa) (eqb2 := eqb); sp.\n    apply eq_term_equals_sym; sp.\n    apply eq_term_equals_fam_sym; sp.\n    apply eq_term_equals_fam_fam_sym; sp.\n\n    apply type_pfamily_implies_equal_Cparams in j; sp.\n    apply @equal_Cparams_eq_term_equals with (eqp1 := eqp0) (eqa1 := eqa0) (eqb1 := eqb0); sp.\n\n    apply type_pfamily_implies_params in j; sp.\n    apply l11.\n    apply j5; 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_pm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2512039538713579}}
{"text": "(*******************************************************************\n * Construcción Formal de Programas en Teoría de Tipos\n * Trabajo práctico final\n * Hernán Gurmendi\n ******************************************************************)\n\n(*******************************************************************\n * Este archivo especifica el estado.\n *\n ******************************************************************)\n\nSection State.\n\n(** Identificadores de OSs e Hypercalls *)\n\nParameter os_ident : Set.\nParameter os_ident_eq : forall oi1 oi2 : os_ident, {oi1 = oi2} + {oi1 <> oi2}.\n\nParameter Hyperv_call: Set.\n\n\n(* Memoria y direcciones *)\n\n(* Direcciones Virtuales. *)\nParameter vadd: Set.\nParameter vadd_eq : forall va1 va2 : vadd, {va1 = va2} + {va1 <> va2}.\n\n(** Direcciones de Máquina. *)\nParameter madd :  Set.\nParameter madd_eq : forall ma1 ma2 : madd, {ma1 = ma2} + {ma1 <> ma2}.\n\n(** Direcciones Físicas : \nLos sitemas operativos utilizan este tipo de direcciones para ver regiones de memoriea\ncontigua. Estos no ven direcciones de máquina. *)\nParameter padd: Set.\nParameter padd_eq : forall pa1 pa2 : padd, {pa1 = pa2} + {pa1 <> pa2}.\n\n(** Memory values. *)\nParameter value: Set.\nParameter value_eq:forall val1 val2 : value, {val1 = val2} + {val1 <> val2}.\n\n\n(* Environment *)\nRecord context : Set :=\n  Context\n    {(** una dirección virtual es accesible, i.e. no está reserveda \n         por el Hypervisor *)\n       ctxt_vadd_accessible: vadd -> bool;\n     (** guest Oss (Confiable/No Confiable) **)\n       ctxt_oss : os_ident -> bool\n    }.\n\nInductive exec_mode : Set :=\n  | usr\n  | svc.\n\nInductive os_activity : Set :=\n  | running\n  | waiting.\n\nRecord os : Set :=\n  OS\n    {\n      curr_page : padd;\n      hcall     : option Hyperv_call;\n    }.\n\nDefinition oss_map : Set :=\n  os_ident -> option os.\n\nDefinition hypervisor_map : Set :=\n  os_ident -> option (padd -> option madd).\n\nInductive content : Set :=\n  | RW (v : option value)\n  | PT (va_to_ma : vadd -> option madd)\n  | Other.\n\nDefinition isRW (cntnt : content) : bool :=\n  match cntnt with\n  | RW _ => true\n  | _    => false\n  end.\n\nInductive page_owner : Set :=\n  | Hyp\n  | Os (osi : os_ident)\n  | No_Owner.\n\nRecord page : Set :=\n  Page\n    {\n      page_content  : content;\n      page_owned_by : page_owner;\n    }.\n\nDefinition system_memory : Set :=\n  madd -> option page.\n\nRecord state : Set :=\n  State\n    {\n      active_os     : os_ident;       (* id del os activo *)\n      aos_exec_mode : exec_mode;      (* modo de ejecución del os activo *)\n      aos_activity  : os_activity;    (* estado de ejecución del os activo *)\n      oss           : oss_map;        (* información sobre los oss *)\n      hypervisor    : hypervisor_map; (* mapeos de memoria fisica a maquina segun os *)\n      memory        : system_memory;  (* memoria de la plataforma *)\n    }.\n\n(* Actualiza la memoria m en la dirección de máquina ma por la página p *)\nDefinition update (m : system_memory) (ma : madd) (p : page) : system_memory :=\n  fun (ma' : madd) => if (madd_eq ma ma')\n                      then Some p\n                      else m ma.\n\nEnd State.\n", "meta": {"author": "hgurmendi", "repo": "cfptt-coq", "sha": "07afcbf049d81adde65ce573c40a2185ab2f8171", "save_path": "github-repos/coq/hgurmendi-cfptt-coq", "path": "github-repos/coq/hgurmendi-cfptt-coq/cfptt-coq-07afcbf049d81adde65ce573c40a2185ab2f8171/tpfinal/entrega/State.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.25120395387135785}}
{"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.idxval Require Import pival_dist pival ival_dist ival ival_pair pidist_singleton idist_pidist_pair extrema.\nFrom discprob.prob Require Import prob countable finite stochastic_order.\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 : 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 : Proper (@le_pidist X --> @le_pidist X ==> Coq.Program.Basics.impl) (@irrel_pidist X).\nProof.\n  intros X I1 I1' Heq1 I2 I2' Heq2.\n  intros Hirrel. eapply irrel_pidist_proper; eauto.\nQed.\n\nGlobal Instance irrel_pidist_proper_instance : Proper (@eq_pidist X ==> @eq_pidist X ==> iff) (@irrel_pidist X).\nProof.\n  intros X 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.", "meta": {"author": "jtassarotti", "repo": "polaris", "sha": "c7873f05214351d54cacf3d8482625ee33ad3288", "save_path": "github-repos/coq/jtassarotti-polaris", "path": "github-repos/coq/jtassarotti-polaris/polaris-c7873f05214351d54cacf3d8482625ee33ad3288/proba/theories/idxval/irrel_equiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2511698877171206}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nRequire Import Bool.\nRequire Import Arith.\nRequire Import NArith.\nRequire Import Ndec.\nRequire Import ZArith.\nFrom IntMap Require Import Allmaps.\nFrom TreeAutomata Require Import bases.\nFrom TreeAutomata Require Import defs.\nFrom TreeAutomata Require Import semantics.\nFrom TreeAutomata Require Import refcorrect.\nFrom TreeAutomata Require Import lattice_fixpoint.\n\n\n\nInductive coacc : preDTA -> ad -> ad -> Prop :=\n| coacc_id :\nforall (d : preDTA) (a : ad) (s : state),\nMapGet state d a = Some s -> coacc d a a\n| coacc_nxt :\nforall (d : preDTA) (a0 a1 a2 : ad) (s1 s2 : state)\n(pl : prec_list) (c : ad),\nMapGet state d a2 = Some s2 ->\nMapGet state d a1 = Some s1 ->\nMapGet prec_list s1 c = Some pl ->\nprec_occur pl a2 -> coacc d a0 a1 -> coacc d a0 a2.\n\nDefinition coacc_transitive_def (d : preDTA) (a0 a1 : ad) : Prop :=\nforall a2 : ad, coacc d a0 a1 -> coacc d a2 a0 -> coacc d a2 a1.\n\nLemma coacc_transitive_0 :\nforall (d : preDTA) (a : ad) (s : state),\nMapGet state d a = Some s -> coacc_transitive_def d a a.\nProof. hammer_hook \"coacc_test\" \"coacc_test.coacc_transitive_0\".\nunfold coacc_transitive_def in |- *. intros. exact H1.\nQed.\n\nLemma coacc_transitive_1 :\nforall (d : preDTA) (a0 a1 a2 : ad) (s1 s2 : state)\n(pl : prec_list) (c : ad),\nMapGet state d a2 = Some s2 ->\nMapGet state d a1 = Some s1 ->\nMapGet prec_list s1 c = Some pl ->\nprec_occur pl a2 ->\ncoacc d a0 a1 ->\ncoacc_transitive_def d a0 a1 -> coacc_transitive_def d a0 a2.\nProof. hammer_hook \"coacc_test\" \"coacc_test.coacc_transitive_1\".\nunfold coacc_transitive_def in |- *. intros. exact (coacc_nxt d a3 a1 a2 s1 s2 pl c H H0 H1 H2 (H4 _ H3 H6)).\nQed.\n\nLemma coacc_transitive :\nforall (d : preDTA) (a0 a1 a2 : ad),\ncoacc d a0 a1 -> coacc d a1 a2 -> coacc d a0 a2.\nProof. hammer_hook \"coacc_test\" \"coacc_test.coacc_transitive\".\nintros. exact\n(coacc_ind coacc_transitive_def coacc_transitive_0 coacc_transitive_1 d a1\na2 H0 a0 H0 H).\nQed.\n\n\n\nFixpoint map_replace (A : Set) (m : Map A) {struct m} :\nad -> A -> Map A :=\nfun (a : ad) (x : A) =>\nmatch m with\n| M0 => M0 A\n| M1 b y => if N.eqb a b then M1 A b x else M1 A b y\n| M2 m n =>\nmatch a with\n| N0 => M2 A (map_replace A m N0 x) n\n| Npos q =>\nmatch q with\n| xH => M2 A m (map_replace A n N0 x)\n| xO p => M2 A (map_replace A m (Npos p) x) n\n| xI p => M2 A m (map_replace A n (Npos p) x)\nend\nend\nend.\n\nFixpoint map_or (m0 m1 : Map bool) {struct m1} : Map bool :=\nmatch m0, m1 with\n| M0, _ => M0 bool\n| _, M0 => M0 bool\n| M1 a0 b0, M1 a1 b1 =>\nif N.eqb a0 a1 then M1 bool a0 (b0 || b1) else M0 bool\n| M1 _ _, M2 _ _ => M0 bool\n| M2 _ _, M1 _ _ => M0 bool\n| M2 x0 y0, M2 x1 y1 => M2 bool (map_or x0 x1) (map_or y0 y1)\nend.\n\nFixpoint pl_coacc (d : preDTA) (pl : prec_list) {struct pl} :\nMap bool :=\nmatch pl with\n| prec_empty => map_mini state d\n| prec_cons a la ls =>\nmap_replace bool (map_or (pl_coacc d la) (pl_coacc d ls)) a true\nend.\n\nFixpoint st_coacc (d : preDTA) (s : state) {struct s} :\nMap bool :=\nmatch s with\n| M0 => map_mini state d\n| M1 a pl => pl_coacc d pl\n| M2 x y => map_or (st_coacc d x) (st_coacc d y)\nend.\n\nFixpoint predta_coacc_0 (d d' : preDTA) {struct d'} :\nMap bool -> Map bool :=\nfun m : Map bool =>\nmatch d', m with\n| M0, M0 => map_mini state d\n| M1 a s, M1 a' b =>\nif N.eqb a a' && b then st_coacc d s else map_mini state d\n| M2 x y, M2 z t => map_or (predta_coacc_0 d x z) (predta_coacc_0 d y t)\n| _, _ => map_mini state d\nend.\n\nDefinition predta_coacc (d : preDTA) (a : ad) (m : Map bool) :\nMap bool := map_replace bool (predta_coacc_0 d d m) a true.\n\nDefinition predta_coacc_states (d : preDTA) (a : ad) :\nMap bool :=\npower (Map bool) (predta_coacc d a) (map_mini state d)\n(S (MapCard state d)).\n\nDefinition predta_coacc_states_0 (d : preDTA) (a : ad) :\nMap bool :=\nlazy_power bool eqm_bool (predta_coacc d a) (map_mini state d)\n(S (MapCard state d)).\n\n\n\nLemma map_or_mapget_true_l :\nforall (m0 m1 : Map bool) (a : ad),\ndomain_equal bool bool m0 m1 ->\nMapGet bool m0 a = Some true ->\nMapGet bool (map_or m0 m1) a = Some true.\nProof. hammer_hook \"coacc_test\" \"coacc_test.map_or_mapget_true_l\".\nsimple induction m0. intros. inversion H0. simple induction m1.\nintros. inversion H. intros. simpl in H. simpl in H0.\nelim (bool_is_true_or_false (N.eqb a a3)); intros; rewrite H1 in H0. inversion H0. rewrite <- (Neqb_complete _ _ H1). rewrite <- H. simpl in |- *. rewrite (Neqb_correct a).\nsimpl in |- *. rewrite (Neqb_correct a). reflexivity. inversion H0.\nintros. inversion H1. simple induction m2. intros. inversion H1.\nintros. inversion H1. intros. simpl in |- *. elim H3; intros.\ninduction  a as [| p]. exact (H _ _ H5 H4). induction  p as [p Hrecp| p Hrecp| ]. exact (H0 _ _ H6 H4). exact (H _ _ H5 H4). exact (H0 _ _ H6 H4).\nQed.\n\nLemma map_or_mapget_true_ld :\nforall (d : preDTA) (m0 m1 : Map bool) (a : ad),\nensemble_base state d m0 ->\nensemble_base state d m1 ->\nMapGet bool m0 a = Some true ->\nMapGet bool (map_or m0 m1) a = Some true.\nProof. hammer_hook \"coacc_test\" \"coacc_test.map_or_mapget_true_ld\".\nintros. exact\n(map_or_mapget_true_l m0 m1 a\n(domain_equal_transitive bool state bool m0 d m1\n(domain_equal_symmetric state bool d m0 H) H0) H1).\nQed.\n\nLemma map_or_mapget_true_r :\nforall (m0 m1 : Map bool) (a : ad),\ndomain_equal bool bool m0 m1 ->\nMapGet bool m0 a = Some true ->\nMapGet bool (map_or m1 m0) a = Some true.\nProof. hammer_hook \"coacc_test\" \"coacc_test.map_or_mapget_true_r\".\nsimple induction m0. intros. inversion H0. simple induction m1; intros.\ninversion H. simpl in H. simpl in H0. rewrite <- H.\nelim (bool_is_true_or_false (N.eqb a a3)); intros; rewrite H1 in H0;\ninversion H0. rewrite <- (Neqb_complete _ _ H1). simpl in |- *. rewrite (Neqb_correct a). simpl in |- *.\nrewrite (Neqb_correct a). elim (bool_is_true_or_false a2); intros; rewrite H2; reflexivity. inversion H1. intros.\ninduction  m2 as [| a0 a1| m2_1 Hrecm2_1 m2_0 Hrecm2_0]. inversion H1. inversion H1. simpl in |- *.\nelim H1; intros. induction  a as [| p]. exact (H _ _ H3 H2).\ninduction  p as [p Hrecp| p Hrecp| ]. exact (H0 _ _ H4 H2). exact (H _ _ H3 H2).\nexact (H0 _ _ H4 H2).\nQed.\n\nLemma map_or_mapget_true_rd :\nforall (d : preDTA) (m0 m1 : Map bool) (a : ad),\nensemble_base state d m0 ->\nensemble_base state d m1 ->\nMapGet bool m1 a = Some true ->\nMapGet bool (map_or m0 m1) a = Some true.\nProof. hammer_hook \"coacc_test\" \"coacc_test.map_or_mapget_true_rd\".\nintros. exact\n(map_or_mapget_true_r m1 m0 a\n(domain_equal_transitive bool state bool m1 d m0\n(domain_equal_symmetric state bool d m1 H0) H) H1).\nQed.\n\nLemma map_or_mapget_true_inv :\nforall (m0 m1 : Map bool) (a : ad),\nMapGet bool (map_or m0 m1) a = Some true ->\nMapGet bool m0 a = Some true \\/ MapGet bool m1 a = Some true.\nProof. hammer_hook \"coacc_test\" \"coacc_test.map_or_mapget_true_inv\".\nsimple induction m0; intros. induction  m1 as [| a0 a1| m1_1 Hrecm1_1 m1_0 Hrecm1_0]. simpl in H. inversion H.\nsimpl in H. inversion H. simpl in H. inversion H. induction  m1 as [| a2 a3| m1_1 Hrecm1_1 m1_0 Hrecm1_0]. simpl in H. inversion H. simpl in H. elim (bool_is_true_or_false (N.eqb a a2)); intros; rewrite H0 in H.\nsimpl in H. elim (bool_is_true_or_false (N.eqb a a1)); intros; rewrite H1 in H;\ninversion H. rewrite H3. elim (bool_is_true_or_false a0); intros; rewrite H2 in H3; rewrite H2. left. rewrite <- (Neqb_complete _ _ H1). simpl in |- *.\nrewrite (Neqb_correct a). reflexivity. elim (bool_is_true_or_false a3); intros; rewrite H4 in H3; rewrite H4.\nright. rewrite <- (Neqb_complete _ _ H0). rewrite <- (Neqb_complete _ _ H1). simpl in |- *. rewrite (Neqb_correct a).\nreflexivity. inversion H3. inversion H. inversion H.\ninduction  m2 as [| a0 a1| m2_1 Hrecm2_1 m2_0 Hrecm2_0]. inversion H1. inversion H1. simpl in H1.\ninduction  a as [| p]. elim (H _ _ H1). intros. left. simpl in |- *. assumption.\nintros. right. simpl in |- *. assumption. induction  p as [p Hrecp| p Hrecp| ]. elim (H0 _ _ H1); intros; simpl in |- *. left. assumption. right. assumption.\nelim (H _ _ H1); intros; simpl in |- *. left. assumption. right.\nassumption. elim (H0 _ _ H1); intros; simpl in |- *. left. assumption.\nright. assumption.\nQed.\n\n\n\nLemma map_replace_mapget_ins_true_0 :\nforall (m : Map bool) (a : ad) (b : bool),\nMapGet bool m a = Some b ->\nMapGet bool (map_replace bool m a true) a = Some true.\nProof. hammer_hook \"coacc_test\" \"coacc_test.map_replace_mapget_ins_true_0\".\nsimple induction m. intros. inversion H. intros. simpl in H.\nelim (bool_is_true_or_false (N.eqb a a1)); intros; rewrite H0 in H;\ninversion H. simpl in |- *. rewrite <- (Neqb_complete _ _ H0). rewrite (Neqb_correct a).\nsimpl in |- *. rewrite (Neqb_correct a). reflexivity. intros.\ninduction  a as [| p]; simpl in H1. simpl in |- *. exact (H _ _ H1).\ninduction  p as [p Hrecp| p Hrecp| ]; simpl in |- *. exact (H0 _ _ H1). exact (H _ _ H1). exact (H0 _ _ H1).\nQed.\n\nLemma map_replace_mapget_ins_true_1 :\nforall (m : Map bool) (a a' : ad),\nMapGet bool m a = Some true ->\nMapGet bool (map_replace bool m a' true) a = Some true.\nProof. hammer_hook \"coacc_test\" \"coacc_test.map_replace_mapget_ins_true_1\".\nsimple induction m. intros. inversion H. intros. simpl in H.\nelim (bool_is_true_or_false (N.eqb a a1)); intros; rewrite H0 in H. inversion H. simpl in |- *. elim (bool_is_true_or_false (N.eqb a' a)); intros; rewrite H1.\nsimpl in |- *. rewrite H0. reflexivity. simpl in |- *. rewrite H0.\nreflexivity. inversion H. intros. induction  a as [| p]; simpl in H1; simpl in |- *. induction  a' as [| p]. simpl in |- *. exact (H _ _ H1).\ninduction  p as [p Hrecp| p Hrecp| ]. simpl in |- *. exact H1. exact (H _ _ H1). exact H1.\ninduction  p as [p Hrecp| p Hrecp| ]. induction  a' as [| p0]; simpl in |- *. exact H1. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]; simpl in |- *. exact (H0 _ _ H1). exact H1. exact (H0 _ _ H1).\ninduction  a' as [| p0]; simpl in |- *. exact (H _ _ H1). induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]; simpl in |- *. exact H1. exact (H _ _ H1). exact H1. induction  a' as [| p]; simpl in |- *. exact H1. induction  p as [p Hrecp| p Hrecp| ]; simpl in |- *. exact (H0 _ _ H1). exact H1. exact (H0 _ _ H1).\nQed.\n\nLemma map_replace_mapget_true_inv :\nforall (m : Map bool) (a b : ad),\nMapGet bool (map_replace bool m a true) b = Some true ->\nb = a \\/ MapGet bool m b = Some true.\nProof. hammer_hook \"coacc_test\" \"coacc_test.map_replace_mapget_true_inv\".\nsimple induction m. intros. inversion H. simpl in |- *. intros. elim (bool_is_true_or_false (N.eqb a1 a)); intros; rewrite H0 in H. simpl in H. elim (bool_is_true_or_false (N.eqb a b)); intros; rewrite H1 in H. rewrite H1. left.\nrewrite (Neqb_complete _ _ H0). rewrite <- (Neqb_complete _ _ H1). reflexivity. inversion H. simpl in H. elim (bool_is_true_or_false (N.eqb a b)); intros; rewrite H1 in H;\ninversion H. rewrite H1. right. reflexivity. intros.\nsimpl in H1. induction  a as [| p]; simpl in H1. induction  b as [| p]; simpl in |- *; simpl in H1. exact (H _ _ H1). induction  p as [p Hrecp| p Hrecp| ]. right. exact H1.\nelim (H _ _ H1). intros. inversion H2. intros. right.\nexact H2. right. exact H1. induction  p as [p Hrecp| p Hrecp| ]. induction  b as [| p0].\nsimpl in |- *. simpl in H1. right. exact H1. simpl in H1.\ninduction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. elim (H0 _ _ H1). intros. inversion H2.\nleft. reflexivity. intros. simpl in |- *. right. exact H2. simpl in |- *.\nright. exact H1. elim (H0 _ _ H1). intros. inversion H2.\nintros. simpl in |- *. right. exact H2. induction  b as [| p0]; simpl in |- *; simpl in H1. elim (H _ _ H1). intros. inversion H2.\nright. exact H2. induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. right. exact H1. elim (H _ _ H1). intros. inversion H2. left. reflexivity.\nintros. right. exact H2. right. exact H1. induction  b as [| p].\nsimpl in H1. simpl in |- *. right. exact H1. induction  p as [p Hrecp| p Hrecp| ]; simpl in |- *; simpl in H1. elim (H0 _ _ H1). intros. inversion H2.\nintros. right. exact H2. right. exact H1. left. reflexivity.\nQed.\n\n\n\nLemma map_or_def_ok :\nforall m0 m1 : Map bool,\ndomain_equal bool bool m0 m1 -> domain_equal bool bool m0 (map_or m0 m1).\nProof. hammer_hook \"coacc_test\" \"coacc_test.map_or_def_ok\".\nsimple induction m0. simple induction m1. intros. exact I. intros. inversion H.\nintros. inversion H1. simple induction m1. intros. inversion H. intros.\nsimpl in H. simpl in |- *. rewrite H. rewrite (Neqb_correct a1). simpl in |- *.\nreflexivity. intros. inversion H1. simple induction m2. intros. inversion H1.\nintros. inversion H1. intros. elim H3. intros. simpl in |- *. split.\nexact (H _ H4). exact (H0 _ H5).\nQed.\n\nLemma map_or_def_ok_d :\nforall (d : preDTA) (m0 m1 : Map bool),\nensemble_base state d m0 ->\nensemble_base state d m1 -> ensemble_base state d (map_or m0 m1).\nProof. hammer_hook \"coacc_test\" \"coacc_test.map_or_def_ok_d\".\nunfold ensemble_base in |- *. intros. apply (domain_equal_transitive state bool bool d m0 (map_or m0 m1)). exact H. apply (map_or_def_ok m0 m1). apply (domain_equal_transitive bool state bool m0 d m1).\nexact (domain_equal_symmetric state bool d m0 H). exact H0.\nQed.\n\nLemma map_replace_def_ok :\nforall (A : Set) (m : Map A) (a : ad) (x : A),\ndomain_equal A A m (map_replace A m a x).\nProof. hammer_hook \"coacc_test\" \"coacc_test.map_replace_def_ok\".\nintro. simple induction m. intros. exact I. intros. simpl in |- *. elim (bool_is_true_or_false (N.eqb a1 a)); intros; rewrite H.\nsimpl in |- *. reflexivity. simpl in |- *. reflexivity. intros. simpl in |- *.\ninduction  a as [| p]. simpl in |- *. split. exact (H N0 x). exact (domain_equal_reflexive A m1). induction  p as [p Hrecp| p Hrecp| ]. split. exact (domain_equal_reflexive A m0). exact (H0 (Npos p) x). split.\nexact (H (Npos p) x). exact (domain_equal_reflexive A m1).\nsplit. exact (domain_equal_reflexive A m0). exact (H0 N0 x).\nQed.\n\nLemma map_replace_def_ok_d :\nforall (d : preDTA) (m : Map bool) (a : ad) (x : bool),\nensemble_base state d m -> ensemble_base state d (map_replace bool m a x).\nProof. hammer_hook \"coacc_test\" \"coacc_test.map_replace_def_ok_d\".\nunfold ensemble_base in |- *. intros. apply\n(domain_equal_transitive state bool bool d m (map_replace bool m a x) H).\nexact (map_replace_def_ok bool m a x).\nQed.\n\nLemma pl_coacc_def_ok :\nforall (d : preDTA) (pl : prec_list), ensemble_base state d (pl_coacc d pl).\nProof. hammer_hook \"coacc_test\" \"coacc_test.pl_coacc_def_ok\".\nsimple induction pl. simpl in |- *. intros. exact\n(map_replace_def_ok_d d (map_or (pl_coacc d p) (pl_coacc d p0)) a true\n(map_or_def_ok_d _ _ _ H H0)).\nsimpl in |- *. exact (map_mini_appartient state d).\nQed.\n\nLemma st_coacc_def_ok :\nforall (d : preDTA) (s : state), ensemble_base state d (st_coacc d s).\nProof. hammer_hook \"coacc_test\" \"coacc_test.st_coacc_def_ok\".\nsimple induction s. simpl in |- *. exact (map_mini_appartient state d). simpl in |- *.\nintros. exact (pl_coacc_def_ok d a0). intros. simpl in |- *. exact (map_or_def_ok_d _ _ _ H H0).\nQed.\n\nLemma predta_coacc_0_def_ok :\nforall (d d' : preDTA) (m : Map bool),\nensemble_base state d (predta_coacc_0 d d' m).\nProof. hammer_hook \"coacc_test\" \"coacc_test.predta_coacc_0_def_ok\".\nsimple induction d'. simpl in |- *. intros. induction  m as [| a a0| m1 Hrecm1 m0 Hrecm0];\nexact (map_mini_appartient state d). simpl in |- *. intros. induction  m as [| a1 a2| m1 Hrecm1 m0 Hrecm0].\nexact (map_mini_appartient state d). elim (bool_is_true_or_false (N.eqb a a1 && a2)); intros; rewrite H. exact (st_coacc_def_ok d a0). exact (map_mini_appartient state d). exact (map_mini_appartient state d). intros. induction  m1 as [| a a0| m1_1 Hrecm1_1 m1_0 Hrecm1_0]. simpl in |- *.\nexact (map_mini_appartient state d). simpl in |- *. exact (map_mini_appartient state d). simpl in |- *. exact (map_or_def_ok_d _ _ _ (H m1_1) (H0 m1_0)).\nQed.\n\nLemma predta_coacc_def_ok :\nforall (d : preDTA) (a : ad) (m : Map bool),\nensemble_base state d (predta_coacc d a m).\nProof. hammer_hook \"coacc_test\" \"coacc_test.predta_coacc_def_ok\".\nunfold predta_coacc in |- *. intros. exact (map_replace_def_ok_d d _ a true (predta_coacc_0_def_ok d d m)).\nQed.\n\n\n\nDefinition lemd (d : preDTA) : mRelation bool :=\nfun m0 m1 : Map bool =>\nensemble_base state d m0 /\\ ensemble_base state d m1 /\\ lem m0 m1.\n\nLemma lemd_reflexive :\nforall (d : preDTA) (m : Map bool), ensemble_base state d m -> lemd d m m.\nProof. hammer_hook \"coacc_test\" \"coacc_test.lemd_reflexive\".\nunfold ensemble_base in |- *. simple induction d. intros. unfold lemd in |- *.\nunfold ensemble_base in |- *. induction  m as [| a a0| m1 Hrecm1 m0 Hrecm0]. split. exact I.\nsplit; exact I. inversion H. inversion H. intros.\nunfold lemd in |- *. unfold ensemble_base in |- *. induction  m as [| a1 a2| m1 Hrecm1 m0 Hrecm0]. inversion H.\nsimpl in H. rewrite H. simpl in |- *. split. reflexivity. split.\nreflexivity. rewrite (Neqb_correct a1). exact (leb_reflexive a2). inversion H. unfold lemd in |- *. unfold ensemble_base in |- *.\nsimple induction m1. intros. inversion H1. intros. inversion H1.\nintros. elim H3. intros. elim (H _ H4). elim (H0 _ H5).\nintros. split; split. exact H4. exact H5. split. exact H4.\nexact H5. split. elim H9. intros. exact H11. elim H7.\nintros. exact H11.\nQed.\n\nLemma lemd_antisymmetric :\nforall (d : preDTA) (m0 m1 : Map bool),\nlemd d m0 m1 -> lemd d m1 m0 -> m0 = m1.\nProof. hammer_hook \"coacc_test\" \"coacc_test.lemd_antisymmetric\".\nunfold lemd in |- *. unfold ensemble_base in |- *. simple induction d. simple induction m0.\nintros. elim H. intros. elim H0. intros. elim H4. intros.\ninduction  m1 as [| a a0| m1_1 Hrecm1_1 m1_0 Hrecm1_0]. reflexivity. inversion H6. inversion H6.\nintros. elim H0. intros. elim H2. intros. decompose [and] H.\ninduction  m1 as [| a1 a2| m1_1 Hrecm1_1 m1_0 Hrecm1_0]. inversion H8. inversion H5. inversion H8.\nintros. decompose [and] H1.  inversion H3. intros.\ndecompose [and] H. decompose [and] H0. induction  m0 as [| a1 a2| m0_1 Hrecm0_1 m0_0 Hrecm0_0].\ninversion H1. induction  m1 as [| a3 a4| m1_1 Hrecm1_1 m1_0 Hrecm1_0]. inversion H3. simpl in H1.\nsimpl in H2. rewrite <- H1. rewrite <- H2. simpl in H4.\nsimpl in H7. rewrite <- H2 in H4. rewrite <- H1 in H4.\nrewrite (Neqb_correct a) in H4. rewrite <- H1 in H7.\nrewrite <- H2 in H7. rewrite (Neqb_correct a) in H7.\nrewrite (leb_antisymmetric _ _ H4 H7). reflexivity.\ninversion H2. inversion H1. intros. decompose [and] H1.\ndecompose [and] H2. induction  m1 as [| a a0| m1_1 Hrecm1_1 m1_0 Hrecm1_0]. inversion H3. inversion H3.\ninduction  m2 as [| a a0| m2_1 Hrecm2_1 m2_0 Hrecm2_0]. inversion H4. inversion H9. elim H4. elim H3.\nelim H6. intros. rewrite (H m1_1 m2_1). rewrite (H0 m1_0 m2_0). reflexivity. split. exact H12. split. exact H14.\nexact H10. split. exact H14. split. exact H12. elim H9.\nintros. exact H16. elim H9. intros. split. exact H11.\nsplit. exact H13. exact H7. elim H9. intros. split.\nexact H13. split. exact H11. exact H15.\nQed.\n\nLemma lemd_transitive :\nforall (d : preDTA) (m0 m1 m2 : Map bool),\nlemd d m0 m1 -> lemd d m1 m2 -> lemd d m0 m2.\nProof. hammer_hook \"coacc_test\" \"coacc_test.lemd_transitive\".\nsimple induction d. unfold lemd in |- *. unfold ensemble_base in |- *. intros.\ndecompose [and] H. decompose [and] H0. induction  m0 as [| a a0| m0_1 Hrecm0_1 m0_0 Hrecm0_0].\ninduction  m1 as [| a a0| m1_1 Hrecm1_1 m1_0 Hrecm1_0]. induction  m2 as [| a a0| m2_1 Hrecm2_1 m2_0 Hrecm2_0]. split. exact I. split; exact I.\ninversion H6. inversion H7. inversion H2. inversion H2.\ninversion H1. inversion H1. unfold lemd in |- *. unfold ensemble_base in |- *.\nintros. decompose [and] H. decompose [and] H0. induction  m0 as [| a1 a2| m0_1 Hrecm0_1 m0_0 Hrecm0_0].\ninversion H1. induction  m1 as [| a3 a4| m1_1 Hrecm1_1 m1_0 Hrecm1_0]. inversion H2. induction  m2 as [| a5 a6| m2_1 Hrecm2_1 m2_0 Hrecm2_0].\ninversion H6. simpl in H2. simpl in H1. simpl in H6.\nsimpl in H4. rewrite <- H2 in H4. rewrite <- H1 in H4.\nrewrite (Neqb_correct a) in H4. simpl in H7. rewrite <- H3 in H7. rewrite <- H6 in H7. rewrite (Neqb_correct a) in H7.\nrewrite <- H1. rewrite <- H6. split. simpl in |- *. reflexivity.\nsimpl in |- *. split. reflexivity. rewrite (Neqb_correct a).\nexact (leb_transitive _ _ _ H4 H7). inversion H6.\ninversion H3. inversion H1. unfold lemd in |- *. unfold ensemble_base in |- *.\nintros. decompose [and] H1. decompose [and] H2. induction  m1 as [| a a0| m1_1 Hrecm1_1 m1_0 Hrecm1_0].\ninversion H3. inversion H3. clear Hrecm1_1 Hrecm1_0.\ninduction  m2 as [| a a0| m2_1 Hrecm2_1 m2_0 Hrecm2_0]. inversion H5. inversion H5. clear Hrecm2_1.\nclear Hrecm2_0. intros. induction  m3 as [| a a0| m3_1 Hrecm3_1 m3_0 Hrecm3_0]. inversion H8.\ninversion H8. clear Hrecm3_1. clear Hrecm3_0. simpl in |- *.\nelim H3. elim H8. elim H6. elim H5. elim H9. intros.\nsplit. split. exact H17. exact H18. split. split. exact H15.\nexact H16. split. exact (lem_transitive _ _ _ H13 H7).\nexact (lem_transitive _ _ _ H14 H10).\nQed.\n\nLemma map_or_inc_ld :\nforall (d : preDTA) (m m0 m1 : Map bool),\nensemble_base state d m ->\nlemd d m0 m1 -> lemd d (map_or m0 m) (map_or m1 m).\nProof. hammer_hook \"coacc_test\" \"coacc_test.map_or_inc_ld\".\nunfold lemd in |- *. unfold ensemble_base in |- *. simple induction d. intros.\ndecompose [and] H0. induction  m as [| a a0| m2 Hrecm1 m3 Hrecm0]. induction  m0 as [| a a0| m0_1 Hrecm0_1 m0_0 Hrecm0_0]. induction  m1 as [| a a0| m1_1 Hrecm1_1 m1_0 Hrecm1_0]. simpl in |- *. split. exact I. split; exact I. inversion H3.\ninversion H3. inversion H1. inversion H1. inversion H.\ninversion H. intros. decompose [and] H0. induction  m as [| a1 a2| m2 Hrecm1 m3 Hrecm0].\ninversion H. induction  m0 as [| a3 a4| m0_1 Hrecm0_1 m0_0 Hrecm0_0]. inversion H1. induction  m1 as [| a5 a6| m1_1 Hrecm1_1 m1_0 Hrecm1_0].\ninversion H3. simpl in |- *. simpl in H1. simpl in H3. simpl in H4. simpl in H. rewrite <- H. rewrite <- H3. rewrite <- H1. rewrite (Neqb_correct a). simpl in |- *. rewrite (Neqb_correct a). split. reflexivity. split. reflexivity. rewrite <- H3 in H4. rewrite <- H1 in H4. rewrite (Neqb_correct a) in H4. exact (orb_inc_l a2 _ _ H4). inversion H4.\ninversion H1. inversion H. intros. decompose [and] H2.\ninduction  m1 as [| a a0| m1_1 Hrecm1_1 m1_0 Hrecm1_0]. inversion H1. inversion H1. induction  m2 as [| a a0| m2_1 Hrecm2_1 m2_0 Hrecm2_0].\ninversion H3. inversion H3. induction  m3 as [| a a0| m3_1 Hrecm3_1 m3_0 Hrecm3_0]. inversion H5.\ninversion H5. clear Hrecm3_1 Hrecm3_0 Hrecm2_1 Hrecm2_0 Hrecm1_1 Hrecm1_0. simpl in |- *. elim H5. elim H3. elim H6.\nintros. elim H1. intros. elim (H m1_1 m2_1 m3_1).\nelim (H0 m1_0 m2_0 m3_0). intros. split. split; assumption.\nsplit. split. elim H17; intros. assumption. elim H15; intros; assumption. elim H15. intros. elim H17. intros.\nsplit; assumption. assumption. split. assumption. split; assumption. assumption. split. assumption. split; assumption.\nQed.\n\nLemma map_or_inc_rd :\nforall (d : preDTA) (m m0 m1 : Map bool),\nensemble_base state d m ->\nlemd d m0 m1 -> lemd d (map_or m m0) (map_or m m1).\nProof. hammer_hook \"coacc_test\" \"coacc_test.map_or_inc_rd\".\nunfold lemd in |- *. unfold ensemble_base in |- *. simple induction d. intros.\ndecompose [and] H0. induction  m as [| a a0| m2 Hrecm1 m3 Hrecm0]. induction  m0 as [| a a0| m0_1 Hrecm0_1 m0_0 Hrecm0_0]. induction  m1 as [| a a0| m1_1 Hrecm1_1 m1_0 Hrecm1_0]. simpl in |- *. split. exact I. split; exact I. inversion H3.\ninversion H3. inversion H1. inversion H1. inversion H.\ninversion H. intros. decompose [and] H0. induction  m as [| a1 a2| m2 Hrecm1 m3 Hrecm0].\ninversion H. induction  m0 as [| a3 a4| m0_1 Hrecm0_1 m0_0 Hrecm0_0]. inversion H1. induction  m1 as [| a5 a6| m1_1 Hrecm1_1 m1_0 Hrecm1_0].\ninversion H3. simpl in |- *. simpl in H1. simpl in H3. simpl in H4. simpl in H. rewrite <- H. rewrite <- H3. rewrite <- H1. rewrite (Neqb_correct a). simpl in |- *. rewrite (Neqb_correct a). split. reflexivity. split. reflexivity. rewrite <- H3 in H4. rewrite <- H1 in H4. rewrite (Neqb_correct a) in H4. exact (orb_inc_r a2 _ _ H4). inversion H4.\ninversion H1. inversion H. intros. decompose [and] H2.\ninduction  m1 as [| a a0| m1_1 Hrecm1_1 m1_0 Hrecm1_0]. inversion H1. inversion H1. induction  m2 as [| a a0| m2_1 Hrecm2_1 m2_0 Hrecm2_0].\ninversion H3. inversion H3. induction  m3 as [| a a0| m3_1 Hrecm3_1 m3_0 Hrecm3_0]. inversion H5.\ninversion H5. clear Hrecm3_1 Hrecm3_0 Hrecm2_1 Hrecm2_0 Hrecm1_1 Hrecm1_0. simpl in |- *. elim H5. elim H3. elim H6.\nintros. elim H1. intros. elim (H m1_1 m2_1 m3_1).\nelim (H0 m1_0 m2_0 m3_0). intros. split. split; assumption.\nsplit. split. elim H17; intros. assumption. elim H15; intros; assumption. elim H15. intros. elim H17. intros.\nsplit; assumption. assumption. split. assumption. split; assumption. assumption. split. assumption. split; assumption.\nQed.\n\nLemma map_or_inc_d :\nforall (d : preDTA) (m0 m1 m2 m3 : Map bool),\nlemd d m0 m1 -> lemd d m2 m3 -> lemd d (map_or m0 m2) (map_or m1 m3).\nProof. hammer_hook \"coacc_test\" \"coacc_test.map_or_inc_d\".\nintros. apply (lemd_transitive d (map_or m0 m2) (map_or m1 m2) (map_or m1 m3)). apply (map_or_inc_ld d m2 m0 m1).\nunfold lemd in H0. decompose [and] H0. exact H1. exact H.\napply (map_or_inc_rd d m1 m2 m3). unfold lemd in H.\ndecompose [and] H. exact H3. exact H0.\nQed.\n\nLemma predta_coacc_0_incr :\nforall (d d' : preDTA) (m0 m1 : Map bool),\nlemd d' m0 m1 -> lemd d (predta_coacc_0 d d' m0) (predta_coacc_0 d d' m1).\nProof. hammer_hook \"coacc_test\" \"coacc_test.predta_coacc_0_incr\".\nunfold lemd in |- *. unfold ensemble_base in |- *. simple induction d'. intros.\ndecompose [and] H. induction  m0 as [| a a0| m0_1 Hrecm0_1 m0_0 Hrecm0_0]. induction  m1 as [| a a0| m1_1 Hrecm1_1 m1_0 Hrecm1_0]. simpl in |- *.\nsplit. exact (map_mini_appartient state d). split.\nexact (map_mini_appartient state d). exact (lem_reflexive (map_mini state d)). inversion H2. inversion H2. induction  m1 as [| a1 a2| m1_1 Hrecm1_1 m1_0 Hrecm1_0]. inversion H0. simpl in H3. simpl in |- *. apply (lemd_reflexive d (map_mini state d)). exact (map_mini_appartient state d).\ninversion H2. simpl in |- *. induction  m1 as [| a a0| m1_1 Hrecm1_1 m1_0 Hrecm1_0];\nexact (lemd_reflexive d (map_mini state d) (map_mini_appartient state d)). intros.\ndecompose [and] H. induction  m0 as [| a1 a2| m0_1 Hrecm0_1 m0_0 Hrecm0_0]. induction  m1 as [| a1 a2| m1_1 Hrecm1_1 m1_0 Hrecm1_0]. simpl in |- *.\nexact (lemd_reflexive d (map_mini state d) (map_mini_appartient state d)). inversion H0. inversion H0. induction  m1 as [| a3 a4| m1_1 Hrecm1_1 m1_0 Hrecm1_0].\ninversion H2. simpl in |- *. simpl in H0. simpl in H2.\nsimpl in H3.\nrewrite <- H0; rewrite <- H2; rewrite <- H0 in H3;\nrewrite <- H2 in H3.  rewrite (Neqb_correct a); simpl in |- *.\nrewrite (Neqb_correct a) in H3. elim (bool_is_true_or_false a2); intros; rewrite H1;\nelim (bool_is_true_or_false a4); intros; rewrite H4.\nexact (lemd_reflexive d (st_coacc d a0) (st_coacc_def_ok d a0)). rewrite H4 in H3. rewrite H1 in H3.\ninversion H3.\nsplit. exact (map_mini_appartient state d). split. exact (st_coacc_def_ok d a0). elim (map_mini_mini state d). intros. exact (H6 (st_coacc d a0) (st_coacc_def_ok d a0)). exact (lemd_reflexive d (map_mini state d) (map_mini_appartient state d)).\ninversion H3. inversion H0. intros. decompose [and] H1.\ninduction  m1 as [| a a0| m1_1 Hrecm1_1 m1_0 Hrecm1_0]. inversion H2. inversion H2. induction  m2 as [| a a0| m2_1 Hrecm2_1 m2_0 Hrecm2_0].\ninversion H4. inversion H4. clear Hrecm2_0 Hrecm2_1 Hrecm1_0 Hrecm1_1. elim H5. intros. elim H4. elim H2. intros. simpl in |- *.\nelim (H m1_1 m2_1). intros. elim H12. intros. elim (H0 m1_0 m2_0). intros. elim H16. intros. split. exact (map_or_def_ok_d d _ _ H11 H15). split. exact (map_or_def_ok_d _ _ _ H13 H17). elim\n(map_or_inc_d d (predta_coacc_0 d m m1_1) (predta_coacc_0 d m m2_1)\n(predta_coacc_0 d m0 m1_0) (predta_coacc_0 d m0 m2_0)).\nintros. elim H20. intros. exact H22. unfold lemd in |- *.\nsplit. assumption. split; assumption. unfold lemd in |- *.\nsplit. assumption. split; assumption.  split.\nassumption. split; assumption. split. assumption.\nsplit; assumption.\nQed.\n\nLemma map_replace_inc :\nforall (m0 m1 : Map bool) (a : ad) (b : bool),\nlem m0 m1 -> lem (map_replace bool m0 a b) (map_replace bool m1 a b).\nProof. hammer_hook \"coacc_test\" \"coacc_test.map_replace_inc\".\nsimple induction m0. simple induction m1. intros. exact (lem_reflexive (map_replace bool (M0 bool) a b)). intros. inversion H.\nintros. inversion H1. simple induction m1. intros. inversion H.\nsimpl in |- *. intros. elim (bool_is_true_or_false (N.eqb a a1)); intros; rewrite H0 in H. elim (bool_is_true_or_false (N.eqb a3 a)); intros; rewrite H1. rewrite (Neqb_complete _ _ H1). rewrite H0. rewrite (Neqb_complete _ _ H0).\nexact (lem_reflexive (M1 bool a1 b)). elim (bool_is_true_or_false (N.eqb a3 a1)); intros; rewrite H2.\nrewrite <- (Neqb_complete _ _ H0) in H2. rewrite H2 in H1.\ninversion H1. rewrite <- (Neqb_complete _ _ H0). simpl in |- *.\nrewrite (Neqb_correct a). exact H. elim H. intros.\ninversion H1. simple induction m2. intros. inversion H1.\nintros. inversion H1. intros. simpl in |- *. elim H3; intros.\ninduction  a as [| p]. simpl in |- *. split. exact (H m3 N0 b H4).\nexact H5. induction  p as [p Hrecp| p Hrecp| ]; simpl in |- *; split. exact H4. exact (H0 m4 (Npos p) b H5). exact (H m3 (Npos p) b H4). exact H5.\nexact H4. exact (H0 m4 N0 b H5).\nQed.\n\nLemma map_replace_inc_d :\nforall (d : preDTA) (m0 m1 : Map bool) (a : ad) (b : bool),\nlemd d m0 m1 -> lemd d (map_replace bool m0 a b) (map_replace bool m1 a b).\nProof. hammer_hook \"coacc_test\" \"coacc_test.map_replace_inc_d\".\nunfold lemd in |- *. intros. decompose [and] H. split.\nexact (map_replace_def_ok_d d m0 a b H0). split.\nexact (map_replace_def_ok_d d m1 a b H2). exact (map_replace_inc m0 m1 a b H3).\nQed.\n\nLemma predta_coacc_increasing :\nforall (d : preDTA) (a : ad),\nincreasing_app bool (lemd d) (predta_coacc d a).\nProof. hammer_hook \"coacc_test\" \"coacc_test.predta_coacc_increasing\".\nunfold increasing_app in |- *. unfold predta_coacc in |- *. intros.\nexact\n(map_replace_inc_d d (predta_coacc_0 d d x) (predta_coacc_0 d d y) a true\n(predta_coacc_0_incr d d x y H)).\nQed.\n\n\n\nDefinition lattice_lemd_bounded_0_def (p : prechain bool) : Prop :=\nforall d : preDTA,\nchain bool (ensemble_base state d) (lemd d) p ->\nchain bool (ensemble_base state d) lem p.\n\nLemma lattice_lemd_bounded_0 :\nforall m : Map bool, lattice_lemd_bounded_0_def (single bool m).\nProof. hammer_hook \"coacc_test\" \"coacc_test.lattice_lemd_bounded_0\".\nunfold lattice_lemd_bounded_0_def in |- *. intros. inversion H.\nexact (chain_single bool m (ensemble_base state d) lem H3).\nQed.\n\nDefinition lattice_lemd_bounded_1_def (p : prechain bool) : Prop :=\nlattice_lemd_bounded_0_def p ->\nforall m : Map bool, lattice_lemd_bounded_0_def (concat bool p m).\n\nLemma lattice_lemd_bounded_1 :\nforall m : Map bool, lattice_lemd_bounded_1_def (single bool m).\nProof. hammer_hook \"coacc_test\" \"coacc_test.lattice_lemd_bounded_1\".\nunfold lattice_lemd_bounded_1_def in |- *. unfold lattice_lemd_bounded_0_def in |- *. intros. inversion H0.\ninversion H7. inversion H9. exact (chain_concat_s bool m m0 (ensemble_base state d) lem H8 H10 H11).\nQed.\n\nLemma lattice_lemd_bounded_2 :\nforall p : prechain bool,\nlattice_lemd_bounded_1_def p ->\nforall m : Map bool, lattice_lemd_bounded_1_def (concat bool p m).\nProof. hammer_hook \"coacc_test\" \"coacc_test.lattice_lemd_bounded_2\".\nunfold lattice_lemd_bounded_1_def in |- *. unfold lattice_lemd_bounded_0_def in |- *.\nintros. inversion H1. inversion H8. inversion H11. exact\n(chain_concat_m bool m m0 p (ensemble_base state d) lem H12 H13 (H0 _ H9)).\nQed.\n\nLemma lattice_lemd_bounded_3 :\nforall (p : prechain bool) (d : preDTA),\nchain bool (ensemble_base state d) (lemd d) p ->\nchain bool (ensemble_base state d) lem p.\nProof. hammer_hook \"coacc_test\" \"coacc_test.lattice_lemd_bounded_3\".\nexact\n(prechain_ind bool lattice_lemd_bounded_0_def lattice_lemd_bounded_0\n(prechain_ind bool lattice_lemd_bounded_1_def lattice_lemd_bounded_1\nlattice_lemd_bounded_2)).\nQed.\n\nLemma lattice_lemd_bounded :\nforall (p : prechain bool) (d : preDTA),\nsas_chain bool (ensemble_base state d) (lemd d) p ->\nsas_chain bool (ensemble_base state d) lem p.\nProof. hammer_hook \"coacc_test\" \"coacc_test.lattice_lemd_bounded\".\nintros. inversion H. split. exact (lattice_lemd_bounded_3 p d H0). exact H1.\nQed.\n\nLemma lattice_bounded :\nforall d : preDTA,\nbounded_sas_chain bool (ensemble_base state d) (lemd d)\n(S (MapCard state d)).\nProof. hammer_hook \"coacc_test\" \"coacc_test.lattice_bounded\".\nunfold bounded_sas_chain in |- *. intros. exact (lattice_bounded state d p (lattice_lemd_bounded p d H)).\nQed.\n\n\n\nLemma pl_coacc_contain_coacc_ads :\nforall (d : preDTA) (p : prec_list) (a : ad),\nprec_occur p a ->\nprec_list_ref_ok p d -> MapGet bool (pl_coacc d p) a = Some true.\nProof. hammer_hook \"coacc_test\" \"coacc_test.pl_coacc_contain_coacc_ads\".\nsimple induction p. intros. inversion H1. simpl in |- *. elim (H2 _ H1).\nintros. elim\n(domain_equal_mapget state bool d (map_or (pl_coacc d p0) (pl_coacc d p1))\na0 x\n(map_or_def_ok_d _ _ _ (pl_coacc_def_ok d p0) (pl_coacc_def_ok d p1)) H7).\nintros. exact (map_replace_mapget_ins_true_0 _ _ _ H8).\nsimpl in |- *. apply\n(map_replace_mapget_ins_true_1 (map_or (pl_coacc d p0) (pl_coacc d p1)) a0\na). apply\n(map_or_mapget_true_ld _ _ _ a0 (pl_coacc_def_ok d p0)\n(pl_coacc_def_ok d p1)). elim (prec_list_ref_ok_destr _ _ _ _ H2). intros. exact (H _ H7 H8). simpl in |- *. apply\n(map_replace_mapget_ins_true_1 (map_or (pl_coacc d p0) (pl_coacc d p1)) a0\na). apply\n(map_or_mapget_true_rd _ _ _ a0 (pl_coacc_def_ok d p0)\n(pl_coacc_def_ok d p1)).\nelim (prec_list_ref_ok_destr _ _ _ _ H2). intros.\nexact (H0 _ H7 H9). simpl in |- *. intros. inversion H.\nQed.\n\nLemma st_coacc_contain_coacc_ads :\nforall (d : preDTA) (s : state) (c : ad) (p : prec_list) (a : ad),\nstate_ref_ok s d ->\nMapGet prec_list s c = Some p ->\nprec_occur p a -> MapGet bool (st_coacc d s) a = Some true.\nProof. hammer_hook \"coacc_test\" \"coacc_test.st_coacc_contain_coacc_ads\".\nsimple induction s. intros. inversion H0. intros. simpl in H0.\nelim (bool_is_true_or_false (N.eqb a c)); intros; rewrite H2 in H0. simpl in |- *. apply (pl_coacc_contain_coacc_ads d a0 a1). inversion H0. exact H1. apply (H a a0). simpl in |- *.\nrewrite (Neqb_correct a). reflexivity. inversion H0.\nintros. elim (state_ref_ok_M2_destr _ _ _ H1); intros.\nsimpl in |- *. induction  c as [| p0]. simpl in H2. apply\n(map_or_mapget_true_ld _ _ _ a (st_coacc_def_ok d m) (st_coacc_def_ok d m0)).\napply (H _ _ _ H4 H2 H3). induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]. apply\n(map_or_mapget_true_rd _ _ _ a (st_coacc_def_ok d m) (st_coacc_def_ok d m0)). exact (H0 _ _ _ H5 H2 H3).\napply\n(map_or_mapget_true_ld _ _ _ a (st_coacc_def_ok d m) (st_coacc_def_ok d m0)). apply (H _ _ _ H4 H2 H3).\napply\n(map_or_mapget_true_rd _ _ _ a (st_coacc_def_ok d m) (st_coacc_def_ok d m0)). exact (H0 _ _ _ H5 H2 H3).\nQed.\n\nLemma predta_coacc_0_contain_coacc_ads :\nforall (d d' : preDTA) (a : ad) (s : state) (c : ad)\n(p : prec_list) (b : ad) (m : Map bool),\npreDTA_ref_ok_distinct d' d ->\nMapGet state d' a = Some s ->\nMapGet prec_list s c = Some p ->\nprec_occur p b ->\nensemble_base state d' m ->\nMapGet bool m a = Some true ->\nMapGet bool (predta_coacc_0 d d' m) b = Some true.\nProof. hammer_hook \"coacc_test\" \"coacc_test.predta_coacc_0_contain_coacc_ads\".\nsimple induction d'. intros. inversion H0. simpl in |- *. intros.\ninduction  m as [| a2 a3| m1 Hrecm1 m0 Hrecm0]. inversion H3. unfold ensemble_base in H3.\nsimpl in H3. rewrite <- H3. rewrite (Neqb_correct a).\nsimpl in H4. elim (bool_is_true_or_false (N.eqb a2 a1)); intros; rewrite H5 in H4;\ninversion H4. simpl in |- *. apply (st_coacc_contain_coacc_ads d a0 c p b). elim (bool_is_true_or_false (N.eqb a a1)); intros; rewrite H6 in H0;\ninversion H0. rewrite H9 in H. apply (H a s).\nsimpl in |- *. rewrite (Neqb_correct a). reflexivity. elim (bool_is_true_or_false (N.eqb a a1)); intros; rewrite H6 in H0. inversion H0. exact H1. inversion H0. exact H2.\ninversion H3. intros. induction  m1 as [| a0 a1| m1_1 Hrecm1_1 m1_0 Hrecm1_0]. inversion H5.\ninversion H5. elim H5. intros. elim (preDTA_ref_ok_distinct_dest _ _ _ H1). intros. simpl in |- *.\ninduction  a as [| p0]. simpl in H6. simpl in H2. apply\n(map_or_mapget_true_ld _ _ _ b (predta_coacc_0_def_ok d m m1_1)\n(predta_coacc_0_def_ok d m0 m1_0)). exact (H _ _ _ _ _ _ H9 H2 H3 H4 H7 H6). induction  p0 as [p0 Hrecp0| p0 Hrecp0| ]; simpl in H2; simpl in H6. apply\n(map_or_mapget_true_rd _ _ _ b (predta_coacc_0_def_ok d m m1_1)\n(predta_coacc_0_def_ok d m0 m1_0)). exact (H0 _ _ _ _ _ _ H10 H2 H3 H4 H8 H6).\nexact\n(map_or_mapget_true_ld _ _ _ b (predta_coacc_0_def_ok d m m1_1)\n(predta_coacc_0_def_ok d m0 m1_0) (H _ _ _ _ _ _ H9 H2 H3 H4 H7 H6)). exact\n(map_or_mapget_true_rd _ _ _ b (predta_coacc_0_def_ok d m m1_1)\n(predta_coacc_0_def_ok d m0 m1_0) (H0 _ _ _ _ _ _ H10 H2 H3 H4 H8 H6)).\nQed.\n\nLemma predta_coacc_contain_coacc_ads_0 :\nforall (d : preDTA) (a0 a : ad) (s : state) (c : ad)\n(p : prec_list) (b : ad) (m : Map bool),\npreDTA_ref_ok d ->\nMapGet state d a = Some s ->\nMapGet prec_list s c = Some p ->\nprec_occur p b ->\nensemble_base state d m ->\nMapGet bool m a = Some true ->\nMapGet bool (predta_coacc d a0 m) b = Some true.\nProof. hammer_hook \"coacc_test\" \"coacc_test.predta_coacc_contain_coacc_ads_0\".\nunfold predta_coacc in |- *. intros. apply (map_replace_mapget_ins_true_1 (predta_coacc_0 d d m) b a0). apply\n(fun hyp : preDTA_ref_ok_distinct d d =>\npredta_coacc_0_contain_coacc_ads d d a s c p b m hyp H0 H1 H2 H3 H4). elim (preDTA_ref_ok_def d). intros. exact (H5 H).\nQed.\n\nDefinition predta_coacc_contain_coacc_ads_def_0 (d : preDTA)\n(a0 a1 : ad) : Prop :=\ncoacc d a0 a1 ->\npreDTA_ref_ok d ->\nexists n : nat,\nMapGet bool (power (Map bool) (predta_coacc d a0) (map_mini state d) n)\na1 = Some true.\n\nLemma predta_coacc_contain_coacc_ads_1 :\nforall (d : preDTA) (a : ad) (s : state),\nMapGet state d a = Some s ->\npredta_coacc_contain_coacc_ads_def_0 d a a.\nProof. hammer_hook \"coacc_test\" \"coacc_test.predta_coacc_contain_coacc_ads_1\".\nunfold predta_coacc_contain_coacc_ads_def_0 in |- *. intros.\nsplit with 1. simpl in |- *. unfold predta_coacc in |- *. elim\n(domain_equal_mapget state bool d (predta_coacc_0 d d (map_mini state d)) a\ns (predta_coacc_0_def_ok d d (map_mini state d)) H). intros. apply\n(map_replace_mapget_ins_true_0 (predta_coacc_0 d d (map_mini state d)) a x\nH2).\nQed.\n\nLemma predta_coacc_contain_coacc_ads_2 :\nforall (d : preDTA) (a0 a1 a2 : ad) (s1 s2 : state)\n(pl : prec_list) (c : ad),\nMapGet state d a2 = Some s2 ->\nMapGet state d a1 = Some s1 ->\nMapGet prec_list s1 c = Some pl ->\nprec_occur pl a2 ->\ncoacc d a0 a1 ->\npredta_coacc_contain_coacc_ads_def_0 d a0 a1 ->\npredta_coacc_contain_coacc_ads_def_0 d a0 a2.\nProof. hammer_hook \"coacc_test\" \"coacc_test.predta_coacc_contain_coacc_ads_2\".\nunfold predta_coacc_contain_coacc_ads_def_0 in |- *. intros.\nelim (H4 H3 H6). intros. split with (S x). simpl in |- *.\napply\n(predta_coacc_contain_coacc_ads_0 d a0 a1 s1 c pl a2\n(power (Map bool) (predta_coacc d a0) (map_mini state d) x) H6 H0 H1 H2). apply\n(power_def_ok bool (ensemble_base state d) (predta_coacc d a0)\n(map_mini state d) x). unfold def_ok_app in |- *. intros. exact (predta_coacc_def_ok d a0 x0).\nexact (map_mini_appartient state d). exact H7.\nQed.\n\nLemma predta_coacc_contain_coacc_ads_3 :\nforall (d : preDTA) (a0 a1 : ad),\ncoacc d a0 a1 ->\npreDTA_ref_ok d ->\nexists n : nat,\nMapGet bool (power (Map bool) (predta_coacc d a0) (map_mini state d) n) a1 =\nSome true.\nProof. hammer_hook \"coacc_test\" \"coacc_test.predta_coacc_contain_coacc_ads_3\".\nintros. exact\n(coacc_ind predta_coacc_contain_coacc_ads_def_0\npredta_coacc_contain_coacc_ads_1 predta_coacc_contain_coacc_ads_2 d a0\na1 H H H0).\nQed.\n\n\n\nLemma pl_coacc_rev :\nforall (d : preDTA) (pl : prec_list) (a : ad),\nMapGet bool (pl_coacc d pl) a = Some true -> prec_occur pl a.\nProof. hammer_hook \"coacc_test\" \"coacc_test.pl_coacc_rev\".\nsimple induction pl. simpl in |- *. intros. elim\n(map_replace_mapget_true_inv (map_or (pl_coacc d p) (pl_coacc d p0)) _ _ H1). intros. rewrite <- H2.\nexact (prec_hd a0 p p0). intros. elim (map_or_mapget_true_inv (pl_coacc d p) (pl_coacc d p0) a0 H2). intros. exact (prec_int0 a a0 p p0 (H _ H3)). intros. exact (prec_int1 a a0 p p0 (H0 _ H3)). intros. simpl in H. cut (true <> false).\nintro. elim (H0 (map_mini_mapget_false _ _ _ _ H)). intro.\ninversion H0.\nQed.\n\nLemma st_coacc_rev :\nforall (d : preDTA) (s : state) (a : ad),\nMapGet bool (st_coacc d s) a = Some true ->\nexists c : ad,\n(exists p : prec_list,\nMapGet prec_list s c = Some p /\\ prec_occur p a).\nProof. hammer_hook \"coacc_test\" \"coacc_test.st_coacc_rev\".\nsimple induction s. intros. simpl in H. elim (map_mini_mapget_true _ _ _ H). intros. simpl in H. split with a. split with a0.\nsimpl in |- *. rewrite (Neqb_correct a). split. reflexivity.\nexact (pl_coacc_rev _ _ _ H). intros. simpl in H1.\nelim (map_or_mapget_true_inv (st_coacc d m) (st_coacc d m0) a H1). intros. elim (H _ H2). intros. elim H3. intros.\nsplit with (N.double x). split with x0. induction  x as [| p]; simpl in |- *; exact H4. intros. elim (H0 _ H2). intros. elim H3. intros.\nsplit with (Ndouble_plus_one x). split with x0.\ninduction  x as [| p]; simpl in |- *; exact H4.\nQed.\n\nLemma predta_coacc_0_rev :\nforall (d d' : preDTA) (b : ad) (m : Map bool),\nMapGet bool (predta_coacc_0 d d' m) b = Some true ->\nensemble_base state d' m ->\nexists a : ad,\n(exists s : state,\n(exists c : ad,\n(exists p : prec_list,\nMapGet state d' a = Some s /\\\nMapGet prec_list s c = Some p /\\\nprec_occur p b /\\ MapGet bool m a = Some true))).\nProof. hammer_hook \"coacc_test\" \"coacc_test.predta_coacc_0_rev\".\nsimple induction d'; intros. induction  m as [| a a0| m1 Hrecm1 m0 Hrecm0]. simpl in H. elim (map_mini_mapget_true _ _ _ H). inversion H0.\ninversion H0. induction  m as [| a1 a2| m1 Hrecm1 m0 Hrecm0]. inversion H0. unfold ensemble_base in H0. simpl in H0. rewrite <- H0 in H.\nrewrite <- H0. simpl in H. rewrite (Neqb_correct a) in H. elim (bool_is_true_or_false a2); intros; rewrite H1 in H. simpl in H. split with a. split with a0. elim (st_coacc_rev _ _ _ H). intros. elim H2. intros. split with x. split with x0. simpl in |- *. rewrite (Neqb_correct a). rewrite H1. elim H3. intros. split. reflexivity. split. assumption.\nsplit. assumption. reflexivity. simpl in H. elim (map_mini_mapget_true _ _ _ H). inversion H0. induction  m1 as [| a a0| m1_1 Hrecm1_1 m1_0 Hrecm1_0].\ninversion H2. inversion H2. clear Hrecm1_0 Hrecm1_1.\nunfold ensemble_base in H2. elim H2. intros. simpl in H1.\nelim (map_or_mapget_true_inv _ _ _ H1). intros. elim (H _ _ H5 H3). intros. elim H6. intros. elim H7. intros.\nelim H8. intros. decompose [and] H9. split with (N.double x). split with x0. split with x1. split with x2. split. induction  x as [| p]; simpl in |- *; exact H10. split. exact H12. split. exact H11. induction  x as [| p]; simpl in |- *; exact H14.\nintros. elim (H0 _ _ H5 H4). intros. elim H6. intros.\nelim H7. intros. elim H8. intros. decompose [and] H9.\nsplit with (Ndouble_plus_one x). split with x0.\nsplit with x1. split with x2. induction  x as [| p]; simpl in |- *; exact H9.\nQed.\n\nLemma predta_coacc_rev :\nforall (d : preDTA) (a : ad) (m : Map bool) (b : ad),\nMapGet bool (predta_coacc d a m) b = Some true ->\nensemble_base state d m ->\n(exists a0 : ad,\n(exists s : state,\n(exists c : ad,\n(exists p : prec_list,\nMapGet state d a0 = Some s /\\\nMapGet prec_list s c = Some p /\\\nprec_occur p b /\\ MapGet bool m a0 = Some true)))) \\/\na = b.\nProof. hammer_hook \"coacc_test\" \"coacc_test.predta_coacc_rev\".\nunfold predta_coacc in |- *. intros. elim (map_replace_mapget_true_inv _ _ _ H). intros.\nright. symmetry  in |- *. exact H1. intros. left. elim (predta_coacc_0_rev d d b m H1 H0). elim (predta_coacc_0_rev d d b m H1 H0). intros. elim H3.\nintros. elim H4. intros. elim H5. intros. decompose [and] H6. split with x0. split with x1. exact H4.\nQed.\n\nLemma predta_coacc_reverse :\nforall (n : nat) (d : preDTA) (a b : ad),\nMapGet bool (power (Map bool) (predta_coacc d a) (map_mini state d) n) b =\nSome true -> coacc d a b.\nProof. hammer_hook \"coacc_test\" \"coacc_test.predta_coacc_reverse\".\nsimple induction n. simpl in |- *. intros. elim (map_mini_mapget_true _ _ _ H). intros. simpl in H0. elim (predta_coacc_rev d a _ _ H0).\nintros. elim H1. intros. elim H2. intros. elim H3. intros.\nelim H4. intros. decompose [and] H5. elim\n(domain_equal_mapget bool state\n(predta_coacc d a\n(power (Map bool) (predta_coacc d a) (map_mini state d) n0)) d b true). intros. apply (coacc_nxt d a x b x0 x3 x2 x1 H9 H6 H8 H7). exact (H d a x H10). exact\n(domain_equal_symmetric state bool _ _\n(predta_coacc_def_ok d a\n(power (Map bool) (predta_coacc d a) (map_mini state d) n0))). exact H0. intros. rewrite H1. elim\n(domain_equal_mapget bool state\n(predta_coacc d a\n(power (Map bool) (predta_coacc d a) (map_mini state d) n0)) d b true). intros. exact (coacc_id d b x H2). apply\n(domain_equal_symmetric state bool d\n(predta_coacc d a\n(power (Map bool) (predta_coacc d a) (map_mini state d) n0))).\nexact\n(predta_coacc_def_ok d a\n(power (Map bool) (predta_coacc d a) (map_mini state d) n0)). exact H0.\napply\n(power_def_ok bool (ensemble_base state d) (predta_coacc d a)\n(map_mini state d) n0). unfold def_ok_app in |- *. intros. exact (predta_coacc_def_ok d a x).\nexact (map_mini_appartient state d).\nQed.\n\nLemma predta_coacc_fix_0 :\nforall (d : preDTA) (a : ad),\nlower_fix_point bool (ensemble_base state d) (lemd d)\n(predta_coacc d a) (predta_coacc_states d a).\nProof. hammer_hook \"coacc_test\" \"coacc_test.predta_coacc_fix_0\".\nintros. unfold predta_coacc_states in |- *. apply\n(iteres_lower_fix_point bool (ensemble_base state d)\n(lemd d) (predta_coacc d a) (map_mini state d)\n(S (MapCard state d)) (S (MapCard state d))). unfold mini in |- *.\nsplit. exact (map_mini_appartient state d). intros.\nsplit. exact (map_mini_appartient state d). split.\nexact H. elim (map_mini_mini state d). intros.\nexact (H1 x H). unfold def_ok_app in |- *. intros. exact (predta_coacc_def_ok d a x). exact (predta_coacc_increasing d a). exact (lattice_bounded d). exact (le_n_n _).\nQed.\n\nLemma predta_coacc_fix_1 :\nforall (d : preDTA) (a a0 : ad) (n : nat),\nMapGet bool (power (Map bool) (predta_coacc d a) (map_mini state d) n) a0 =\nSome true -> MapGet bool (predta_coacc_states d a) a0 = Some true.\nProof. hammer_hook \"coacc_test\" \"coacc_test.predta_coacc_fix_1\".\nintros. elim\n(domain_equal_mapget bool bool\n(power (Map bool) (predta_coacc d a) (map_mini state d) n)\n(predta_coacc_states d a) a0 true). intros. elim (bool_is_true_or_false x); intros; rewrite H1 in H0.\nexact H0. elim (predta_coacc_fix_0 d a); intros.\nunfold inf_fix_points in H3. elim\n(lem_get_leb (power (Map bool) (predta_coacc d a) (map_mini state d) n)\n(predta_coacc_states d a) a0 true false).\nelim\n(iteres_inf_fps bool (ensemble_base state d) (lemd d)\n(predta_coacc d a) (map_mini state d) (predta_coacc_states d a) n). intros. elim H5. intros.\nexact H7. unfold mini in |- *. split. exact (map_mini_appartient state d). intros. split. exact (map_mini_appartient state d). split. exact H4. elim (map_mini_mini state d). intros. exact (H6 x0 H4). exact H2. exact (predta_coacc_increasing d a). exact H. exact H0.\napply\n(domain_equal_transitive bool state bool\n(power (Map bool) (predta_coacc d a) (map_mini state d) n) d\n(predta_coacc_states d a)). apply\n(domain_equal_symmetric state bool d\n(power (Map bool) (predta_coacc d a) (map_mini state d) n)). apply\n(power_def_ok bool (ensemble_base state d) (predta_coacc d a)\n(map_mini state d) n). unfold def_ok_app in |- *. intros.\nexact (predta_coacc_def_ok d a x). exact (map_mini_appartient state d). unfold predta_coacc_states in |- *.\napply\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 |- *. intros. exact (predta_coacc_def_ok d a x). exact (map_mini_appartient state d). exact H.\nQed.\n\nLemma predta_coacc_fix_2 :\nforall (d : preDTA) (a a0 : ad),\nMapGet bool (predta_coacc_states d a) a0 = Some true ->\nexists n : nat,\nMapGet bool (power (Map bool) (predta_coacc d a) (map_mini state d) n) a0 =\nSome true.\nProof. hammer_hook \"coacc_test\" \"coacc_test.predta_coacc_fix_2\".\nunfold predta_coacc_states in |- *. intros. split with (S (MapCard state d)). exact H.\nQed.\n\nLemma predta_coacc_fix :\nforall (d : preDTA) (a a0 : ad),\npreDTA_ref_ok d ->\n(MapGet bool (predta_coacc_states d a) a0 = Some true <-> coacc d a a0).\nProof. hammer_hook \"coacc_test\" \"coacc_test.predta_coacc_fix\".\nintros. split. intros. elim (predta_coacc_fix_2 _ _ _ H0). intros. exact (predta_coacc_reverse x d a a0 H1). intros. elim (predta_coacc_contain_coacc_ads_3 _ _ _ H0). intros. exact (predta_coacc_fix_1 d a a0 x H1). exact H.\nQed.\n\nLemma predta_coacc_0_fix :\nforall (d : preDTA) (a a0 : ad),\npreDTA_ref_ok d ->\n(MapGet bool (predta_coacc_states_0 d a) a0 = Some true <->\ncoacc d a a0).\nProof. hammer_hook \"coacc_test\" \"coacc_test.predta_coacc_0_fix\".\nintros. unfold predta_coacc_states_0 in |- *. rewrite\n(lazy_power_eg_power bool eqm_bool (predta_coacc d a)\n(map_mini state d) (S (MapCard state d))). exact (predta_coacc_fix d a a0 H). split. exact (eqm_bool_equal a1 b). intros. rewrite H0. exact (equal_eqm_bool b).\nQed.\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/tree-automata/coacc_test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.251093900435759}}
{"text": "From Undecidability.TM Require Import Util.TM_facts.\n\n(* * Basic 1-Tape Machines *)\n\n\n(* ** Helper functions *)\nSection Mk_Mono.\n  Variable (sig state : finType).\n  Variable mono_trans : state -> option sig -> state * (option sig * move).\n  Variable (init : state) (fin : state -> bool).\n\n  Definition Mk_Mono_TM : TM sig 1.\n  Proof.\n    split with (state := state).\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. (* because definition *)\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, Nmove).\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 CaseChar.\n  Variable sig : finType.\n  Variable (F : finType) (f : option sig -> F).\n\n  Definition CaseChar_TM : TM sig 1 :=\n    {|\n      trans := fun '(_, sym) => (Some (f sym[@Fin0]), [| (None, Nmove) |]);\n      start := None;\n      halt := fun s => match s with\n                    | None => false\n                    | Some _ => true\n                    end;\n    |}.\n\n  Definition CaseChar : pTM sig F 1 := (CaseChar_TM; fun s => match s with None => f None (* not terminated yet *) | Some y => y end).\n\n  Definition CaseChar_Rel : pRel sig F 1 :=\n    fun t '(y, t') =>\n      y = f (current t[@Fin0]) /\\\n      t' = t.\n\n  Definition CaseChar_Sem : CaseChar ⊨c(1) CaseChar_Rel.\n  Proof.\n    intros t. destruct_tapes. cbn. unfold initc; cbn. cbv [step]; cbn. unfold current_chars; cbn.\n    eexists (mk_mconfig _ _); cbv [step]; cbn. split. eauto. cbn. auto.\n  Qed.\n\nEnd CaseChar.\n\nArguments CaseChar : simpl never.\nArguments CaseChar {sig F} f.\nArguments CaseChar_Rel sig F f x y /.\n\nSection ReadChar.\n\n  Variable sig : finType.\n\n  Definition ReadChar : pTM sig (option sig) 1 := CaseChar id.\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    eapply RealiseIn_monotone.\n    - apply CaseChar_Sem.\n    - reflexivity.\n    - intros tin (yout, tout) (->&->). hnf. split; auto.\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  once 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  | [ |- CaseChar _ ⊨ _] => eapply RealiseIn_Realise; eapply CaseChar_Sem\n  | [ |- CaseChar _ ⊨c(_) _] => eapply CaseChar_Sem\n  | [ |- projT1 (CaseChar _) ↓ _] => eapply RealiseIn_TerminatesIn; eapply CaseChar_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.\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/TM/Basic/Mono.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2510938934196687}}
{"text": "(** * Facts about H-VHDL Abstract Syntax *)\n\nRequire Import common.CoqLib.\nRequire Import common.ListLib.\n\nRequire Import hvhdl.AbstractSyntax.\nRequire Import hvhdl.WellDefinedDesign.\nRequire Import hvhdl.HVhdlTypes.\n\n(** ** Facts about [FoldLCs] and [foldl_cs] *)\n\nSection FoldLCsFacts.\n\n  Functional Scheme foldl_cs_ind := Induction for foldl_cs Sort Prop.\n  \n  Lemma FoldLCs_ex :\n    forall {A : Type} (f : A -> cs -> A) cstmt a, exists res, FoldLCs f cstmt a res.\n  Proof.\n    induction cstmt; intros; try\n                               (match goal with\n                                | |- exists _, FoldLCs ?f ?cstmt ?a _ =>\n                                    exists (f a cstmt); constructor\n                                end).\n    destruct (IHcstmt1 a) as (res, FoldLCs1).\n    destruct (IHcstmt2 res) as (res', FoldLCs2).\n    eexists; econstructor.\n    eexact (FoldLCs1). eexact FoldLCs2.\n  Qed.\n\n  Lemma FoldLCs_determ :\n    forall {A : Type} {f : A -> cs -> A} {cstmt a res res'},\n      FoldLCs f cstmt a res ->\n      FoldLCs f cstmt a res' ->\n      res = res'.\n  Proof.\n    induction cstmt; try (inversion_clear 1; inversion_clear 1; auto).\n    assert (e : a' = a'0) by (eapply IHcstmt1; eauto).\n    rewrite e in *; eapply IHcstmt2; eauto.\n  Qed.\n\n  Lemma foldl_cs_build_list_by_app_In :\n    forall {A : Type} {f : list A -> cs -> list A},\n      (forall lofAs1 a,\n        exists lofAs2, f lofAs1 a = lofAs1 ++ lofAs2) ->\n      forall {cstmt} {lofAs} a, In a lofAs -> In a (foldl_cs f cstmt lofAs).\n  Proof.\n    intros A f ex_app cstmt lofAs.\n    functional induction (foldl_cs f cstmt lofAs) using foldl_cs_ind; cbn.\n    1, 2, 4: (match goal with\n              | |- forall (_ : _), _ -> In _ (_ ?acc ?cstmt)  =>\n                  destruct (ex_app acc cstmt) as [ acc1 f_app ];\n                  rewrite f_app; auto\n              end).\n    auto.\n  Qed.\n\n  Lemma foldl_cs_build_list_by_app_nil :\n    forall {A : Type} {f : list A -> cs -> list A} {g : cs -> list A},\n      (forall lofAs1 a, f lofAs1 a = lofAs1 ++ g a) ->\n      forall {cstmt} {lofAs}, foldl_cs f cstmt lofAs = lofAs ++ foldl_cs f cstmt [].\n  Proof.\n    intros A f g ex_app.\n    induction cstmt; cbn; intros lofAs.\n    1, 2, 4: match goal with\n             | |- ?f ?acc ?cstmt = ?acc ++ ?f [] ?cstmt  =>\n                 rewrite (ex_app acc cstmt); rewrite (ex_app [] cstmt); auto\n             end.\n    rewrite (IHcstmt1 lofAs).\n    rewrite (IHcstmt2 (lofAs ++ foldl_cs f cstmt1 [])).\n    rewrite (IHcstmt2 (foldl_cs f cstmt1 [])).\n    rewrite app_assoc; reflexivity.\n  Qed.\n    \nEnd FoldLCsFacts.\n\n(** ** Facts about [get_cids] *)\n\nSection GetCIdsFacts.\n\n  Lemma get_cids_InCs :\n    forall cstmt id__c id__e g i o, InCs (cs_comp id__c id__e g i o) cstmt -> In id__c (get_cids cstmt).\n  Proof.\n    unfold get_cids.\n    set (build_cids := (fun (cids : list HVhdlTypes.ident) (cstmt : cs) => match cstmt with\n                                                                           | cs_comp id _ _ _ _ => cids ++ [id]\n                                                                           | _ => cids\n                                                                           end)).\n    intros cstmt.\n    functional induction (foldl_cs build_cids cstmt []) using foldl_cs_ind;\n    try (solve [inversion_clear 1]).\n\n    (* CASE [cstmt = cs_comp] *)\n    - inversion_clear 1; cbn; auto.\n\n    (* CASE [cs_comp ∈ cstmt1 || cstmt2] *)\n    - inversion_clear 1 as [ InCs0 | InCs1 ].\n      (* SUBCASE [cs_comp ∈ cstmt1] *)\n      + eapply foldl_cs_build_list_by_app_In; eauto; destruct a; cbn.\n        1, 3, 4: (exists []; eapply app_nil_end).\n        exists [id__c0]; reflexivity.\n      + eauto.\n  Qed.\n  \n  Lemma get_cids_app:\n    forall cstmt1 cstmt2 : cs, get_cids (cs_par cstmt1 cstmt2) = get_cids cstmt1 ++ get_cids cstmt2.\n  Proof.\n    unfold get_cids.\n    set (build_cids := (fun (cids : list HVhdlTypes.ident) (cstmt : cs) => match cstmt with\n                                                                           | cs_comp id _ _ _ _ => cids ++ [id]\n                                                                           | _ => cids\n                                                                           end)).\n    cbn; intros *.\n    erewrite @foldl_cs_build_list_by_app_nil with (lofAs := foldl_cs build_cids cstmt1 [])\n                                                  (g := fun cstmt => match cstmt with\n                                                                     | cs_comp id _ _ _ _ => [id]\n                                                                     | _ => []\n                                                                     end).\n    reflexivity.\n    destruct a; cbn.\n    1, 3, 4: (eapply app_nil_end).\n    reflexivity.\n  Qed.\n  \n  Lemma get_cids_In_ex:\n    forall (cstmt : cs) (id__c : ident),\n      In id__c (get_cids cstmt) ->\n      exists (id__e : ident) (g : genmap) (i : inputmap) (o : outputmap), InCs (cs_comp id__c id__e g i o) cstmt.\n  Proof.\n    induction cstmt; try (solve [inversion_clear 1]).\n    inversion_clear 1 as [ eq_idc | False_ ];\n      [ subst; exists id__e, g, i, o; reflexivity | destruct False_ ].\n    rewrite get_cids_app.\n    intros id__c In_app; edestruct in_app_or as [ In1 | In2 ]; eauto;\n      [ edestruct IHcstmt1 as [ id__e [ g [ i [ o InCs1 ] ] ] ]\n      | edestruct IHcstmt2 as [ id__e [ g [ i [ o InCs2 ] ] ] ] ];\n      eauto; do 4 eexists; [ left | right ]; eauto.\n  Qed.\n  \nEnd GetCIdsFacts.\n\n(** ** Facts about [InCs] *)\n\nSection InCsFacts.\n  \n  Lemma InCs_NoDup_comp_eq :\n    forall {cstmt id__c id__e0 g0 i0 o0 id__e1 g1 i1 o1},\n      InCs (cs_comp id__c id__e0 g0 i0 o0) cstmt ->\n      InCs (cs_comp id__c id__e1 g1 i1 o1) cstmt ->\n      NoDup (get_cids cstmt) ->\n      cs_comp id__c id__e0 g0 i0 o0 = cs_comp id__c id__e1 g1 i1 o1.\n  Proof.    \n    induction cstmt; try (solve [inversion 1]).\n    destruct 1; destruct 1; reflexivity.\n\n    inversion_clear 1 as [ InCs0 | InCs0 ];\n      inversion_clear 1 as [ InCs1 | InCs1 ]; intros NoDup_par;\n      [ eapply IHcstmt1; eauto | | | eapply IHcstmt2; eauto ].\n\n    (* CASE [c0, c1 ∈ cstmt1] and CASE [c0, c1 ∈ cstmt2]. *)\n    1,4 : (rewrite get_cids_app in NoDup_par; eauto with nodup).\n\n    (* CASE [c0 ∈ cstmt1] and [c1 ∈ cstmt2], and CASE [c0 ∈ cstmt2]\n       and [c1 ∈ cstmt1]. Contradicts NoDup in the two cases. *)\n    1, 2: (elimtype False;\n           rewrite get_cids_app in NoDup_par;\n           eapply nodup_app_not_in; eauto; eapply get_cids_InCs; eauto).    \n  Qed.\n\nEnd InCsFacts.\n\nLemma flatten_cs_ex : forall beh, exists lofcs, FlattenCs beh lofcs.\nProof.\n  induction beh.\n\n  (* CASE simple Process *)\n  - exists [cs_ps id__p vars body]; auto.\n\n  (* CASE simple Component Instance *)\n  - exists [cs_comp id__c id__e g i o]; auto.\n    \n  (* CASE parallel stmts *)\n  - lazymatch goal with\n    | [ IH1: exists _, _, IH2: exists _, _ |- _ ] =>\n      inversion_clear IH1 as (lofcs1, Hflat1);\n        inversion_clear IH2 as (lofcs2, Hflat2);\n        exists (lofcs1 ++ lofcs2);\n        auto\n    end.\n\n  (* CASE null *)\n  - exists nil; auto.\nQed.\n\n(** FlattenCs is a deterministic relation *)\n\nLemma flatten_cs_determ :\n  forall {behavior lofcs },\n    FlattenCs behavior lofcs ->\n    forall {lofcs'},\n    FlattenCs behavior lofcs' ->\n    lofcs = lofcs'.\nProof.\n  induction 1; only 1 - 6: inversion_clear 1; auto.\n  - inversion H1; auto.\n  - rewrite (IHFlattenCs l0 H1); reflexivity.\n  - inversion_clear H1; rewrite (IHFlattenCs l' H2); reflexivity.\n  - rewrite (IHFlattenCs l0 H1); reflexivity.\n  - inversion_clear H1; rewrite (IHFlattenCs l' H2); reflexivity.\n  - inversion_clear 1 in H H0; auto.\n    + inversion H; apply IHFlattenCs2; auto.\n    + inversion H; rewrite (IHFlattenCs2 l0 H2); reflexivity.\n    + inversion H; rewrite (IHFlattenCs2 l0 H2); reflexivity.\n    + rewrite (IHFlattenCs1 l0 H2); rewrite (IHFlattenCs2 l'0 H3); reflexivity.\nDefined.\n\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/proofs/AbstractSyntaxFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2510938934196687}}
{"text": "From Mtac2 Require Import Mtac2.\n\nSet Universe Polymorphism.\n\nSet Printing Universes.\n\n(* Demonstrate that id indeed has the right type *)\nDefinition test@{i j} : Type@{i} -> Type@{max(i,j)} := id.\n\n(* Demonstrate that ltac gets it right *)\nLemma testL@{i j} : Type@{i} -> Type@{max(i,j)}.\nProof. exact id. Qed.\n\n(* M.ret somehow works in 8.8 *)\nLemma testM@{i j} : Type@{i} -> Type@{max(i,j)}.\nMProof.\nM.ret id.\nQed.\n\n(* runTac works too *)\nLemma testMTac@{i j} : Type@{i} -> Type@{max(i,j)}.\nMProof.\nT.exact id.\nQed.\n\n(* apply doesn't generate a new universe index (it used to be the case) *)\nLemma testMTacApply@{i j} : Type@{i} -> Type@{max(i,j)}.\nMProof.\nT.apply (@id).\nQed.\n\n(* and ltac's 8.8  doesn't do that either *)\nLemma testLApply@{i j} : Type@{i} -> Type@{max(i,j)}.\nProof. apply @id. Qed.\n\nNotation \"p '=e>' b\" := (pbase p%core (fun _ => b%core) UniEvarconv)\n  (no associativity, at level 201) : pattern_scope.\nNotation \"p '=e>' [ H ] b\" := (pbase p%core (fun H => b%core) UniEvarconv)\n  (no associativity, at level 201, H at next level) : pattern_scope.\n\nDefinition test_match@{k m+} {A:Type@{k}} (x:A) : tactic :=\n  mmatch A with\n  | [? B:Type@{m}] B =e> T.exact x\n  end.\n\n\nLemma testMmatch@{i j} : Type@{i} -> Type@{max(i,j)}.\nMProof.\ntest_match (fun x=>x).\nQed.\n\nLemma testMmatch'@{i j} : Type@{i} -> Type@{j}.\nMProof.\ntest_match (fun x=>x).\nQed.\nPrint testMmatch.\nPrint testMmatch'.\n\nDefinition testdef : Type -> Type := fun x=>x.\nLemma testret : Type -> Type.\nMProof.\nM.ret (fun x=>x).\nQed. (* If this fails we likely swapped LHS & RHS of the cumulative unification in [ifM] *)\nPrint testret.\n\nLemma testexact : Type -> Type.\nMProof.\nT.exact (fun x=>x).\nQed.\nAbout testexact.\n", "meta": {"author": "Mtac2", "repo": "Mtac2", "sha": "d16c2e682d5ab18ed77b13b4fd60a42a65c4f958", "save_path": "github-repos/coq/Mtac2-Mtac2", "path": "github-repos/coq/Mtac2-Mtac2/Mtac2-d16c2e682d5ab18ed77b13b4fd60a42a65c4f958/tests/bug_universes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2510938864035783}}
{"text": "Require compcert.backend.Mach.\n\nImport Coqlib.\nImport Integers.\nImport AST.\nImport Values.\nImport Memory.\nImport Globalenvs.\nImport Events.\nImport Smallstep.\nImport Locations.\nImport Conventions.\nExport Mach.\n\nSection WITHCONFIG.\nContext `{compiler_config: CompilerConfiguration}.\n\n(** Execution of Mach functions with Asm-style arguments (long long 64-bit integers NOT allowed) *)\n\nInductive initial_state (lm: regset) (init_sp: val) (p: Mach.program) (i: ident) (sg: signature) (args: list val) (m: mem): state -> Prop :=\n| initial_state_intro    \n    b\n    (Hb: Genv.find_symbol (Genv.globalenv p) i = Some b)\n    (Hargs: extcall_arguments lm m init_sp sg args)    \n  :\n      initial_state lm init_sp p i sg args m (Callstate nil b lm m)\n.\n\nInductive final_state (lm: regset) (sg: signature): state -> (list val * mem) -> Prop :=\n| final_state_intro\n    rs\n    v\n    (Hv: v = List.map rs (loc_result sg))\n    (** Callee-save registers.\n        We use Val.lessdef instead of eq because the Stacking pass does not exactly preserve their values. *)\n    (CALLEE_SAVE: forall r,\n       ~ In r destroyed_at_call ->\n       Val.lessdef (lm r) (rs r))\n    m :\n    final_state lm sg (Returnstate nil rs m) (v, m)\n.\n\nDefinition semantics\n           (return_address_offset: function -> code -> int -> Prop)\n           (lm: regset) (init_sp init_ra: val)\n           (p: Mach.program) (i: ident) (sg: signature) (args: list val) (m: mem) :=\n  Semantics (Mach.step return_address_offset init_sp init_ra) (initial_state lm init_sp p i sg args m) (final_state lm sg) (Genv.globalenv p).\n\nEnd WITHCONFIG.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/compcertx/backend/MachX.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2510561520628494}}
{"text": "From Undecidability Require Import TM.Util.Prelim TM.Util.TM_facts.\n\nSet Default Goal Selector \"!\".\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  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", "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/TM/Combinators/Mirror.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891307678319, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.25105615206284937}}
{"text": "Require Import Raft.\nRequire Import RaftRefinementInterface.\nRequire Import CommonDefinitions.\n\nSection RequestVoteReplyTermSanity.\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\n  Definition requestVoteReply_term_sanity (net : network) : Prop :=\n    forall t p,\n      In p (nwPackets net) ->\n      pBody p = RequestVoteReply t true ->\n      t <= currentTerm (snd (nwState net (pDst p))).\n\n  Class requestVoteReply_term_sanity_interface : Prop :=\n    {\n      requestVoteReply_term_sanity_invariant :\n        forall net,\n          refined_raft_intermediate_reachable net ->\n          requestVoteReply_term_sanity net\n    }.\nEnd RequestVoteReplyTermSanity.", "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/RequestVoteReplyTermSanityInterface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.251001628869214}}
{"text": "From iris.proofmode Require Import tactics.\nFrom iris.program_logic Require Export weakestpre.\nFrom iris.base_logic Require Export invariants.\nFrom iris_examples.logrel.F_mu_ref Require Export rules_binary typing.\nFrom iris.algebra Require Import list.\nFrom stdpp 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 (discrete_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 `{heapG Σ, cfgSG Σ}.\n  Notation D := (prodO valO valO -n> iPropO Σ).\n  Implicit Types τi : D.\n  Implicit Types Δ : listO D.\n  Implicit Types interp : listO D → D.\n\n  Definition interp_expr (τi : listO D -n> D) (Δ : listO D)\n      (ee : expr * expr) : iProp Σ := (∀ K,\n    ⤇ fill K (ee.2) →\n    WP ee.1 {{ v, ∃ v', ⤇ 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) : listO D -n> D := λne Δ,\n    from_option id (cconst True)%I (Δ !! x).\n  Solve Obligations with solve_proper.\n\n  Program Definition interp_unit : listO D -n> D := λne Δ ww,\n    (⌜ww.1 = UnitV⌝ ∧ ⌜ww.2 = UnitV⌝)%I.\n  Solve Obligations with solve_proper_alt.\n\n  Program Definition interp_prod\n      (interp1 interp2 : listO D -n> D) : listO 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 repeat intros ?; simpl; auto_equiv.\n\n  Program Definition interp_sum\n      (interp1 interp2 : listO D -n> D) : listO 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 repeat intros ?; simpl; auto_equiv.\n\n  Program Definition interp_arrow\n          (interp1 interp2 : listO D -n> D) : listO 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 repeat intros ?; simpl; auto_equiv.\n\n  Program Definition interp_forall\n      (interp : listO D -n> D) : listO D -n> D := λne Δ ww,\n    (□ ∀ τi,\n          ⌜∀ ww, Persistent (τi ww)⌝ →\n          interp_expr\n            interp (τi :: Δ) (TApp (of_val (ww.1)), TApp (of_val (ww.2))))%I.\n  Solve Obligations with repeat intros ?; simpl; auto_equiv.\n\n  Program Definition interp_rec1\n      (interp : listO D -n> D) (Δ : listO D) (τi : D) : D := λne ww,\n    (□ ∃ vv, ⌜ww = (FoldV (vv.1), FoldV (vv.2))⌝ ∧ ▷ interp (τi :: Δ) vv)%I.\n  Solve Obligations with repeat intros ?; simpl; auto_equiv.\n\n  Global Instance interp_rec1_contractive\n    (interp : listO D -n> D) (Δ : listO D) : Contractive (interp_rec1 interp Δ).\n  Proof. by solve_contractive. Qed.\n\n  Lemma fixpoint_interp_rec1_eq (interp : listO D -n> D) Δ x :\n    fixpoint (interp_rec1 interp Δ) x ≡ interp_rec1 interp Δ (fixpoint (interp_rec1 interp Δ)) x.\n  Proof. exact: (fixpoint_unfold (interp_rec1 interp Δ) x). Qed.\n\n  Program Definition interp_rec (interp : listO D -n> D) : listO 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> iPropO Σ := λne τi,\n    (∃ vv, ll.1 ↦ vv.1 ∗ ll.2 ↦ₛ vv.2 ∗ τi vv)%I.\n  Solve Obligations with repeat intros ?; simpl; auto_equiv.\n\n  Program Definition interp_ref\n      (interp : listO D -n> D) : listO 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 repeat intros ?; simpl; auto_equiv.\n\n  Fixpoint interp (τ : type) : listO D -n> D :=\n    match τ return _ with\n    | TUnit => interp_unit\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      (Δ : listO D) (vvs : list (val * val)) : iProp Σ :=\n    (⌜length Γ = length vvs⌝ ∗ [∗] zip_with (λ τ, ⟦ τ ⟧ Δ) Γ vvs)%I.\n  Notation \"⟦ Γ ⟧*\" := (interp_env Γ).\n\n  Class env_Persistent Δ :=\n    ctx_persistentP : Forall (λ τi, ∀ vv, Persistent (τi vv)) Δ.\n  Global Instance ctx_persistent_nil : env_Persistent [].\n  Proof. by constructor. Qed.\n  Global Instance ctx_persistent_cons τi Δ :\n    (∀ vv, Persistent (τi vv)) → env_Persistent Δ → env_Persistent (τi :: Δ).\n  Proof. by constructor. Qed.\n  Global Instance ctx_persistent_lookup Δ x vv :\n    env_Persistent Δ → Persistent (ctx_lookup x Δ vv).\n  Proof. intros HΔ; revert x; induction HΔ=>-[|?] /=; apply _. Qed.\n  Global Instance interp_persistent τ Δ vv :\n    env_Persistent Δ → Persistent (⟦ τ ⟧ Δ vv).\n  Proof.\n    revert vv Δ; induction τ=> vv Δ HΔ; simpl; try apply _.\n    rewrite /Persistent fixpoint_interp_rec1_eq /interp_rec1 /= intuitionistically_into_persistently.\n    by apply persistently_intro'.\n  Qed.\n  Global Instance interp_env_base_persistent Δ Γ vs :\n  env_Persistent Δ → TCForall Persistent (zip_with (λ τ, ⟦ τ ⟧ Δ) Γ vs).\n  Proof.\n    intros HΔ. revert vs.\n    induction Γ => vs; simpl; destruct vs; constructor; apply _.\n  Qed.\n  Global Instance interp_env_persistent Γ Δ vvs :\n    env_Persistent Δ → Persistent (⟦ Γ ⟧* Δ 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. 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      (* FIXME: Ideally we wouldn't have to do this kinf of surgery. *)\n      change (bi_ofeO (uPredI (iResUR Σ))) with (uPredO (iResUR Σ)).\n      rewrite !lookup_app_r; [|lia ..]. do 2 f_equiv. lia.\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. 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      (* FIXME: Ideally we wouldn't have to do this kinf of surgery. *)\n      change (bi_ofeO (uPredI (iResUR Σ))) with (uPredO (iResUR Σ)).\n      rewrite !lookup_app_r; [|lia ..].\n      case EQ: (x - length Δ1) => [|n]; simpl.\n      { symmetry. asimpl. apply (interp_weaken [] Δ1 Δ2 τ'). }\n      change (bi_ofeO (uPredI (iResUR Σ))) with (uPredO (iResUR Σ)).\n      rewrite !lookup_app_r; [|lia ..]. do 2 f_equiv. lia.\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 τ τ' v : ⟦ τ ⟧ (⟦ τ' ⟧ Δ2 :: Δ2) v ≡ ⟦ τ.[τ'/] ⟧ Δ2 v.\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_sepL_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 Δ : ⟦ [] ⟧* Δ [].\n  Proof. iSplit; simpl; 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; lia|].\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\nEnd logrel.\n\nTypeclasses Opaque interp_env.\nNotation \"⟦ τ ⟧\" := (interp τ).\nNotation \"⟦ τ ⟧ₑ\" := (interp_expr (interp τ)).\nNotation \"⟦ Γ ⟧*\" := (interp_env Γ).\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/logrel/F_mu_ref/logrel_binary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.2509080388771649}}
{"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(* ================== 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 := 100.\n\n  (* checkpoint period *)\n  Definition CP := 50.\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 : nat) : string := nat2string delay.\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 :=\n    fun name =>\n      match name with\n      | PBFTreplica n => PBFTreplicaSM n\n      | _ => MhaltedSM dummy_initial_state\n      end.\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 \"pbft/PbftReplicaEx.ml\" pbft_state2string lrun_sm MonoSimulationState2string PBFTdummySM local_replica.\n", "meta": {"author": "santifa", "repo": "masterarbeit", "sha": "088210e071464831d3e496d3a8faac0aac494228", "save_path": "github-repos/coq/santifa-masterarbeit", "path": "github-repos/coq/santifa-masterarbeit/masterarbeit-088210e071464831d3e496d3a8faac0aac494228/raft/simulator/pbft/PBFTsim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.25090803887716484}}
{"text": "Require Export DTimeQ.\nRequire Export MicroBFTheader.\nRequire Export ComponentSM.\nRequire Export ComponentSM2.\nRequire Export toString.\n\n\nSection MicroBFT.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { dtc : DTimeContext }.\n\n  Context { microbft_context : MicroBFT_context }.\n  Context { m_initial_keys   : MicroBFT_initial_keys }.\n  Context { u_initial_keys   : USIG_initial_keys }.\n\n  (* ===============================================================\n     USIG\n     =============================================================== *)\n\n  Record USIG_state :=\n    Build_USIG\n      {\n        usig_id            : MicroBFT_node;\n        usig_counter       : nat;\n        usig_local_keys    : local_key_map;\n      }.\n\n  Record preUI :=\n    Build_preUI\n      {\n        pre_ui_id      : MicroBFT_node;\n        pre_ui_counter : nat;\n      }.\n\n  Record UI :=\n    Build_UI\n      {\n        ui_pre     :> preUI;\n        ui_digest  : MicroBFT_digest;\n      }.\n\n  Definition UIs := list UI.\n\n  Definition ui2rep     (ui : UI) : MicroBFT_node := pre_ui_id (ui_pre ui).\n  Definition ui2counter (ui : UI) : nat := pre_ui_counter (ui_pre ui).\n  Definition ui2digest  (ui : UI) : MicroBFT_digest := ui_digest ui.\n\n\n  (* ===============================================================\n     Bare messages\n     =============================================================== *)\n\n  Record Commit :=\n    commit\n      {\n        commit_n  : nat;\n        commit_ui : UI\n      }.\n\n  Record Accept :=\n    accept\n      {\n        accept_r : nat;\n        accept_c : nat;\n      }.\n\n  Definition commit2sender (c : Commit) : MicroBFT_node :=\n    pre_ui_id (commit_ui c).\n\n  (* ===============================================================\n     Bare message type\n     =============================================================== *)\n\n  Inductive MicroBFT_Bare_Msg : Set :=\n  | MicroBFT_msg_bare_request (n : nat) (pui : preUI).\n\n  (* =========== Msg type =========== *)\n\n  Inductive MicroBFT_msg :=\n  | MicroBFT_request (n : nat)\n  | MicroBFT_commit  (c : Commit)\n  | MicroBFT_accept  (a : Accept).\n\n  Global Instance MicroBFT_I_Msg : Msg := MkMsg MicroBFT_msg.\n\n  Definition MicroBFTmsg2status (m : MicroBFT_msg) : msg_status :=\n    match m with\n    | MicroBFT_request _ => MSG_STATUS_EXTERNAL\n    | MicroBFT_commit  _ => MSG_STATUS_PROTOCOL\n    | MicroBFT_accept  _ => MSG_STATUS_INTERNAL\n    end.\n\n  Global Instance MicroBFT_I_MsgStatus : MsgStatus := MkMsgStatus MicroBFTmsg2status.\n\n  (* back to the definition of usig *)\n\n  Record HashData :=\n    Build_HashData\n      {\n        hd_msg : nat;\n        hd_pre : preUI;\n      }.\n\n  (* hash of the whole usig *)\n  Class USIG_hash :=\n    MkMicroBFThash\n      {\n        create_hash_usig  : HashData -> local_key_map -> MicroBFT_digest;\n        verify_hash_usig  : HashData -> MicroBFT_digest -> local_key_map -> bool;\n        verify_create_hash_usig :\n          forall (hd : HashData) (keys : local_key_map),\n            verify_hash_usig hd (create_hash_usig hd keys) keys = true;\n      }.\n  Context { usig_hash : USIG_hash }.\n  Hint Rewrite verify_create_hash_usig : microbft.\n\n  Definition USIG_initial (r : MicroBFT_node) : USIG_state :=\n    Build_USIG\n      r\n      0\n      (usig_initial_keys r).\n\n  Definition getReplicaId (u : USIG_state) : MicroBFT_node := usig_id u.\n\n  Definition increment_USIG (u : USIG_state) : USIG_state :=\n    Build_USIG\n      (usig_id         u)\n      (S               (usig_counter u))\n      (usig_local_keys u).\n\n  (* 1st USIG counter will be [1] *)\n  Definition create_UI (msg : nat) (u : USIG_state) : USIG_state * UI :=\n    (* increment current counter of the usig *)\n    let u' := increment_USIG u in\n    (* creates the data to hash *)\n    let pre := Build_preUI (usig_id u') (usig_counter u') in\n    let hd := Build_HashData msg pre in\n    (* hashes the data *)\n    let d  := create_hash_usig hd (usig_local_keys u') in\n    (* builds UI *)\n    let ui := Build_UI pre d in\n    (u', ui).\n\n  Definition verify_UI (msg : nat) (ui : UI) (u : USIG_state) : bool :=\n    (* creates the data to hash *)\n    let hd  := Build_HashData msg (ui_pre ui) in\n    (* the keys are supposed to be the receiving keys for [ui_id ui] *)\n    verify_hash_usig hd (ui2digest ui) (usig_local_keys u).\n\n  Inductive USIG_input_interface :=\n  | create_ui_in (msg   : nat)\n  | verify_ui_in (msgui : nat * UI).\n\n  Inductive USIG_output_interface :=\n  | create_ui_out (ui : UI)\n  | verify_ui_out (b  : bool)\n  (* default output *)\n  | verify_ui_out_def.\n\n  Definition CIOusig : ComponentIO :=\n    MkComponentIO USIG_input_interface USIG_output_interface verify_ui_out_def.\n\n\n  (* ===============================================================\n     Crypto\n     =============================================================== *)\n\n  Global Instance MicroBFT_I_Data : Data := MkData MicroBFT_Bare_Msg.\n\n  Class MicroBFT_auth :=\n    MkMicroBFT_auth\n      {\n        MicroBFT_create : data -> sending_keys -> list MicroBFT_digest;\n        MicroBFT_verify : data -> name -> receiving_key -> MicroBFT_digest -> bool\n      }.\n\n  Context { microbft_auth : MicroBFT_auth }.\n\n  Global Instance MicroBFT_I_AuthFun : AuthFun :=\n    MkAuthFun\n      MicroBFT_create\n      MicroBFT_verify.\n\n\n  (* ===============================================================\n        Authenticated Messages\n        =============================================================== *)\n\n  (* we are here extracting the sender of the message *)\n  Definition MicroBFT_msg_auth (m : msg) : option  name :=\n    match m with\n    | MicroBFT_request _ => None\n    | MicroBFT_commit  c => Some (commit2sender c)\n    | MicroBFT_accept  a => None\n    end.\n\n  (* FIX : Why do we need n here? *)\n  Definition MicroBFT_data_auth (n : name) (d : data) : option name :=\n    match d with\n    | MicroBFT_msg_bare_request n pui => Some (pre_ui_id pui)\n    end.\n\n  Global Instance MicroBFT_I_DataAuth : DataAuth := MkDataAuth MicroBFT_data_auth.\n\n  Definition commit2auth_data (c : Commit) : AuthenticatedData :=\n    match c with\n    | commit n ui => MkAuthData (MicroBFT_msg_bare_request n ui) [ui_digest ui]\n    end.\n\n  Definition MicroBFT_get_contained_auth_data (m : msg) : list AuthenticatedData :=\n    match m with\n    | MicroBFT_request _ => []\n    | MicroBFT_commit  c => [commit2auth_data c]\n    | MicroBFT_accept  a => []\n    end.\n\n  Global Instance MicroBFT_I_ContainedAuthData : ContainedAuthData :=\n    MkContainedAuthData MicroBFT_get_contained_auth_data.\n\n\n  (* ===============================================================\n     Decidability for different types of messages\n     =============================================================== *)\n\n  Definition UI_dec : Deq UI.\n  Proof.\n    introv.\n    destruct x as [p1 d1], y as [p2 d2], p1 as [i1 c1], p2 as [i2 c2].\n    destruct (MicroBFT_nodeDeq i1 i2); subst; prove_dec.\n    destruct (deq_nat c1 c2); subst; prove_dec.\n    destruct (MicroBFT_digestdeq d1 d2); subst; prove_dec.\n  Defined.\n\n  (****************************************************************************)\n\n  Definition broadcast2others F : DirectedMsg :=\n    F [MicroBFT_backup1, MicroBFT_backup2].\n\n  (* ===============================================================\n     Sending functions\n     =============================================================== *)\n\n  Definition send_commit (c : Commit) (n : list name) : DirectedMsg :=\n    MkDMsg (MicroBFT_commit c) n ('0).\n\n  Definition send_accept (a : Accept) (n : list name) : DirectedMsg :=\n    MkDMsg (MicroBFT_accept a) n ('0).\n\n\n  (* ===============================================================\n     Log\n     =============================================================== *)\n\n  Definition LOG_state := list Commit.\n\n  Definition LOG_initial : LOG_state := [].\n\n  Inductive LOG_input_interface :=\n  | log_new (c : Commit).\n\n  Inductive LOG_output_interface :=\n  | log_out (b : bool).\n\n  Definition CIOlog : ComponentIO :=\n    MkComponentIO LOG_input_interface LOG_output_interface (log_out true).\n\n\n\n  (* ===============================================================\n     State of some replica\n     =============================================================== *)\n\n  Definition update_highest_received_counter_value (ui : UI) (n : nat) : nat :=\n    if n <? ui2counter ui\n    then ui2counter ui\n    else n.\n\n\n  Record MAIN_state :=\n    Build_State\n      {\n\n        (* state of the local state machine *)\n        sm_state : nat;\n\n        (* the highest sequence number received from the primary *)\n        prim     : nat;\n\n      }.\n\n  Definition initial_state : MAIN_state :=\n    Build_State 0 0.\n\n  Definition update_sm_state\n             (s : MAIN_state)\n             (x : nat) : MAIN_state :=\n    Build_State (sm_state s + x) (prim s).\n\n  Global Instance MicroBFT_I_baseFunIO : baseFunIO :=\n    MkBaseFunIO (fun nm =>\n                   if CompNameKindDeq (comp_name_kind nm) \"USIG\" then CIOusig\n                   else if CompNameKindDeq (comp_name_kind nm) \"LOG\" then CIOlog\n                        else CIOdef).\n\n  Definition preUSIGname : PreCompName := MkPreCompName \"USIG\" 0.\n  Definition USIGname : CompName := MkCN \"USIG\" 0 true.\n\n  Global Instance MicroBFT_I_baseStateFun : baseStateFun :=\n    MkBaseStateFun (fun nm =>\n                      if CompNameKindDeq (comp_name_kind nm) \"USIG\" then USIG_state\n                      else if CompNameKindDeq (comp_name_kind nm) \"LOG\" then LOG_state\n                           else if CompNameKindDeq (comp_name_kind nm) msg_comp_name_kind\n                                then MAIN_state\n                                else unit).\n\n  Global Instance MicroBFT_I_IOTrustedFun : IOTrustedFun :=\n    MkIOTrustedFun\n      (fun _ =>\n         MkIOTrusted\n           USIG_input_interface\n           USIG_output_interface\n           verify_ui_out_def).\n\n  Global Instance MicroBFT_I_trustedStateFun : trustedStateFun :=\n    MkTrustedStateFun (fun _ => USIG_state).\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 r =>\n           let (s', ui) := create_UI r s in\n           [R] (s', create_ui_out ui)\n         | verify_ui_in (r,ui) =>\n           let b := verify_UI r ui s in\n           [R] (s, verify_ui_out b)\n         end).\n\n  Definition USIG_comp (n : MicroBFT_node) : M_StateMachine 1 USIGname :=\n    build_m_sm USIG_update (USIG_initial n).\n\n  Definition LOGname : CompName := MkCN \"LOG\" 0 false.\n\n  Definition LOG_update : M_Update 0 LOGname _ :=\n    fun (l : LOG_state) (m : LOG_input_interface) =>\n      interp_s_proc\n        (match m with\n         | log_new r =>\n           let l' := r :: l in\n           [R] (l', log_out true)\n         end).\n\n  Definition LOG_comp : M_StateMachine 1 LOGname :=\n    build_m_sm LOG_update LOG_initial.\n\n  (******************************************************************************)\n\n\n  Definition on_create_ui_out {A} (f : UI -> A) (d : unit -> A) (out : USIG_output_interface) : A :=\n    match out with\n    | create_ui_out ui => f ui\n    | _ => d tt\n    end.\n\n  Definition call_create_ui {A} (m : nat) (d : unit -> Proc A) (f : UI -> Proc A) :=\n    (USIGname [C] (create_ui_in m))\n      [>>=] on_create_ui_out f d.\n\n  Notation \"a >>cui>>=( d ) f\" := (call_create_ui a d f) (at level 80, right associativity).\n\n  Definition if_true_verify_ui_out {A} (f d : unit -> A) (out : USIG_output_interface) : A :=\n    match out with\n    | verify_ui_out b => if b then f tt else d tt\n    | _ => d tt\n    end.\n\n  Definition call_verify_ui {A} (mui : nat * UI) (d f : unit -> Proc A) :=\n    (USIGname [C] (verify_ui_in mui))\n      [>>=] if_true_verify_ui_out f d.\n\n  Notation \" a >>vui>>=( d ) f\" := (call_verify_ui a d f) (at level 80, right associativity).\n\n  Definition on_data_message {A} (m : MicroBFT_msg) (d : unit -> Proc A) (f : nat -> Proc A) : Proc A :=\n    match m with\n    | MicroBFT_request m => f m\n    | _ => d tt\n    end.\n\n  Notation \"a >>odm>>=( d ) f\" := (on_data_message a d f) (at level 80, right associativity).\n\n  Definition on_commit {A} (m : MicroBFT_msg) (d : unit -> Proc A) (f : Commit -> Proc A) : Proc A :=\n    match m with\n    | MicroBFT_commit c => f c\n    | _ => d tt\n    end.\n\n  Notation \"a >>oc>>=( d ) f\" := (on_commit a d f) (at level 80, right associativity).\n\n\n  Definition MAINname := msg_comp_name 0.\n\n  Definition received_prior_counter (ui : UI) (s : MAIN_state) : bool :=\n    match ui2counter ui with\n    | 0 => false (* 0 is not a valid counter *)\n    | 1 => true (* 1st counter *)\n    | S n => if deq_nat n (prim s) then true else false\n    end.\n\n  Definition is_primary (n : MicroBFT_node) : bool :=\n    if MicroBFT_nodeDeq n MicroBFT_primary then true else false.\n\n  Definition not_primary (n : MicroBFT_node) : bool :=\n    negb (is_primary n).\n\n  Definition valid_commit\n             (slf : MicroBFT_node)\n             (c   : Commit)\n             (s   : MAIN_state) : bool :=\n    is_primary (commit2sender c)\n      && not_primary slf\n      && received_prior_counter (commit_ui c) s.\n\n  Definition invalid_commit\n             (slf : MicroBFT_node)\n             (c   : Commit)\n             (s   : MAIN_state) : bool :=\n    negb (valid_commit slf c s).\n\n  Definition update_highest_received_counter (ui : UI) (s : MAIN_state) : MAIN_state :=\n    Build_State\n      (sm_state          s)\n      (update_highest_received_counter_value ui (prim s)).\n\n  Definition handle_request (slf : MicroBFT_node) : UProc MAINname _ :=\n    (* in case M_Update 0 _ := is output type it complains that \"The term \"m\" has type \"cio_I\" while it is expected to have type \"data_message\".\" *)\n    fun state m =>\n      if not_primary slf then [R] (state, []) else\n\n      m >>odm>>=(fun _ => [R] (state,[])) fun m =>\n\n      let state1 := update_sm_state state m in\n      let m' := sm_state state1 in\n\n      (* create_UI and update of the current state *)\n      m' >>cui>>=(fun _ => [R](state1, [])) fun ui =>\n\n      (* create request *)\n      let c := commit m' ui in\n\n      (* we log this request *)\n      (LOGname [C] (log_new c)) [>>=] fun _ =>\n\n      (* we broadcast the request message to all replicas *)\n      [R] (state1, [broadcast2others (send_commit c)]).\n\n  Definition handle_commit (slf : MicroBFT_node) : UProc MAINname _ :=\n    fun state m =>\n      m >>oc>>=(fun _ => [R] (state,[])) fun c =>\n      if invalid_commit slf c state then [R] (state, []) else\n\n      (* we check whether the ui is created by some usig *)\n      let n  := commit_n c in\n      let ui := commit_ui c in\n      (n,ui) >>vui>>=(fun _ => [R] (state, [])) fun _ =>\n\n      let state1 := update_highest_received_counter (commit_ui c) state in\n\n      (* we log this request *)\n      (LOGname [C] (log_new c)) [>>=] fun _ =>\n\n      (* we broadcast the commit message to all replicas *)\n      let acc := accept n (ui2counter ui) in\n      [R] (state1, [send_accept acc [slf]]).\n\n  Definition handle_accept (slf : MicroBFT_node) : UProc MAINname _ :=\n    fun (state : MAIN_state) m => [R](state,[]).\n\n\n  Definition MAIN_update (slf : MicroBFT_node) : M_Update 1 MAINname _ :=\n    fun (s : MAIN_state) m =>\n      interp_s_proc\n        (match m with\n         | MicroBFT_request _ => handle_request slf s m\n         | MicroBFT_commit  _ => handle_commit  slf s m\n         | MicroBFT_accept  _ => handle_accept  slf s m\n         end).\n\n  Definition MAIN_comp (slf : MicroBFT_node) : n_proc 2 MAINname :=\n    build_m_sm (MAIN_update slf) initial_state.\n\n\n  (*Definition MicroBFT_nstate (n : name) :=\n    match n with\n    | MicroBFT_replica _ => MAIN_state\n    | _ => unit\n    end.*)\n\n  Definition MicroBFTsubs (n : MicroBFT_node) : n_procs _ :=\n    [\n      MkPProc USIGname (USIG_comp n),\n      MkPProc LOGname LOG_comp\n    ].\n\n  Definition MicroBFTsubs_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 MicroBFTsubs_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 MicroBFTsubs_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 MicroBFT_replicaSM_new (r : MicroBFT_node) (s : MAIN_state) : n_proc 2 MAINname :=\n    build_m_sm (MAIN_update r) s.\n\n  Notation MicroBFTls := (LocalSystem 2 0).\n\n  Definition MicroBFTlocalSys (slf : MicroBFT_node) : MicroBFTls :=\n    MkPProc _ (MAIN_comp slf) :: incr_n_procs (MicroBFTsubs slf).\n\n  Definition MicroBFTlocalSys_new\n             (n  : MicroBFT_node)\n             (s  : MAIN_state)\n             (s1 : USIG_state)\n             (s2 : LOG_state) : MicroBFTls :=\n    MkPProc _ (MicroBFT_replicaSM_new n s) :: incr_n_procs (MicroBFTsubs_new s1 s2).\n\n  Definition MicroBFTfunLevelSpace :=\n    MkFunLevelSpace\n      (fun n => 2)\n      (fun n => 0).\n\n  Definition MicroBFTsys : M_USystem MicroBFTfunLevelSpace (*name -> M_StateMachine 2 msg_comp_name*) :=\n    MicroBFTlocalSys.\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 MicroBFTsubs_new_inj :\n    forall a b c d,\n      MicroBFTsubs_new a b = MicroBFTsubs_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 MicroBFTlocalSys_new_inj :\n    forall a1 a2 b1 b2 c1 c2 d1 d2,\n      MicroBFTlocalSys_new a1 b1 c1 d1 = MicroBFTlocalSys_new a2 b2 c2 d2\n      -> b1 = b2 /\\ c1 = c2 /\\ d1 = d2.\n  Proof.\n    introv h.\n    apply eq_cons in h; repnd.\n    apply decomp_p_nproc in h0.\n    inversion h0; subst.\n    apply incr_n_procs_inj in h.\n    apply MicroBFTsubs_new_inj in h; repnd; subst; tcsp.\n  Qed.\n\n  Lemma MicroBFTlocalSys_as_new :\n    forall (r  : MicroBFT_node),\n      MicroBFTlocalSys r\n      = MicroBFTlocalSys_new\n          r\n          initial_state\n          (USIG_initial r)\n          LOG_initial.\n  Proof.\n    introv; eauto.\n  Qed.\n\n  Definition USIGlocalSys (s : USIG_state) : LocalSystem 1 0 :=\n    [MkPProc _ (build_m_sm USIG_update s)].\n\n  Definition LOGlocalSys (s : LOG_state) : LocalSystem 1 0 :=\n    [MkPProc _ (build_m_sm LOG_update s)].\n\nEnd MicroBFT.\n\n\nHint Rewrite @verify_create_hash_usig : microbft.\n\nNotation MicroBFTls := (LocalSystem 2 0).\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/MicroBFT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.25090803887716484}}
{"text": "Require Import Lia.\nRequire Import Relations.\nRequire Import Logic.FunctionalExtensionality.\nRequire Import Lists.List.\nImport ListNotations.\nRequire Import String.\nRequire Import Cop.Copland.\nImport Copland.Term.\nRequire Import Utils.Utilities.\n\nModule Manifest.\n\n(** ****************************\n  * FORMALIZATION OF ATTESTATION PROTOCOL NEGOTIATION\n  By: Anna Fritz and \n      Dr. Perry Alexander \n  Date: January 6th, 2023\n************************************)\n\n(** * Manifests \n    [Manifest] defines a single attestation manger and its interconnections.  \n    Information includes: \n  asps:  a list of ASPs (measurement operations the AM can preform),\n  M : can measure relation (other AMs the current AM knows of),  \n  C : context relation (other AMs the current AM depends on),\n  Policy : local policy specific to the current AM.\n           Minimally includes privacy policy and may possibly include selection policy   \n  Other information not necessary for reasoning includes: \n  [key] simulates public key \n  [address] simulates address information and \n  [tpm] simulates cruft necessary to initialize its TPM\n*)\nRecord Manifest := {\n\n   asps : list ASP ;\n   K : list Plc ; \n   C : list Plc ; \n   Policy : ASP -> Plc -> Prop ;\n\n(*\n   ; key : string\n   ; address : nat\n   ; tpm_init : nat\n*)\n }.\n\n(** [Environment] is a set of AM's each defined by a [Manifest].\n  The domain of an [Environment] provides names for each [Manifest].\n  Names should be the hash of their public key, but this restriction\n  is not enforced here. \n*)\n\nDefinition Environment : Type :=  Plc -> (option Manifest).\n\nDefinition e_empty : Environment := (fun _ => None).\n\nDefinition e_update (m : Environment) (x : Plc) (v : (option Manifest)) :=\n  fun x' => if plc_dec x x' then v else m x'.\n\nTheorem e_update_reduce: forall m x v y, x<>y -> (e_update m x v) y = m y.\nProof.\n  intros m x v y H; unfold e_update.\n  destruct (plc_dec x y).\n  + contradiction.\n  + auto.\nQed.\n\n(** A [System] is all attestation managers in the enviornement *)\n\nDefinition System := list Environment.\n\n(** ****************************\n  * REASONING ABOUT MANIFESTS\n*****************************)\n\n(** Within the enviornment [e], does the AM at place [k] have ASP [a]? *)\n\nDefinition hasASPe(k:Plc)(e:Environment)(a:ASP):Prop :=\nmatch (e k) with\n| None => False\n| Some m => In a m.(asps)\nend.      \n\n(** Within the system [s], does the AM located at place [k] have ASP [a]? *)\n\nFixpoint hasASPs(k:Plc)(s:System)(a:ASP):Prop :=\n    match s with\n    | [] => False\n    | s1 :: s2 => (hasASPe k s1 a) \\/ (hasASPs k s2 a)\n    end.\n\n(** Proof that hasASPe is decidable. This means, for any enviornment [e] \n   either the ASP [a] is present or it's not. *)\n\nTheorem hasASPe_dec: forall k e a, {hasASPe k e a}+{~hasASPe k e a}.\nProof.\n  intros k e a.\n  unfold hasASPe.\n  destruct (e k).\n  + induction (asps m).\n  ++ auto.\n  ++ inverts IHl.\n  +++ simpl. left. right. apply H.\n  +++ simpl. assert (asp_dec : {a = a0} + {a<>a0}). \n           { repeat decide equality. }    \n      inverts asp_dec.\n  ++++ left. auto.\n  ++++ right. unfold not. intros. inverts H1; auto.\n  + auto.      \nDefined.\n\n(** prove hasASPs is decidable. This means, for any system [s] \n   either the ASP [a] is present or it's not. *)\n\nTheorem hasASPs_dec: forall k e a, {hasASPs k e a}+{~hasASPs k e a}.\nProof.\n  intros k e a.\n  induction e.\n  + simpl in *. right. unfold not. intros. apply H.\n  + simpl in *. pose proof hasASPe_dec k a0 a. inverts H. \n  ++ left. left. apply H0.\n  ++ inverts IHe.\n  +++ left. right. apply H.\n  +++ right. unfold not. intros. inverts H1; auto.\nDefined. \n\n(** Determine if manifest [k] from [e] knows how to \n   communicate from [k] to [p]\n*)\n\nDefinition knowsOfe(k:Plc)(e:Environment)(p:Plc):Prop :=\nmatch (e k) with\n| None => False\n| Some m => In p m.(K)\nend.\n\nPrint System.\nPrint Environment.\n\n(** Determine if place [k] within the system [s] knows of [p] *)\n\nFixpoint knowsOfs(k:Plc)(s:System)(p:Plc):Prop :=\nmatch s with\n| [] => False\n| s1 :: ss => (knowsOfe k s1 p) \\/ (knowsOfs k ss p)\nend.\n(* need this second k to change.... *)\n\n\n(** Prove knowsOfe is decidable. This means, for any enviornment [e] \n   either the current place [p] is aware of place [p] or it's not.  *)\n\nTheorem knowsOfe_dec:forall k e p, {(knowsOfe k e p)}+{~(knowsOfe k e p)}.\nProof.\n  intros k e p.\n  unfold knowsOfe.\n  destruct (e k); auto.\n  + induction (K m).\n  ++ auto.\n  ++ assert (H: {p = a} + {p <> a}). {repeat decide equality. }\n     inversion H.\n  +++ simpl. left. auto.\n  +++ simpl. inverts IHl; auto. right. unfold not. intros. inverts H2; auto.\nDefined.\n\n(** decidability of knowsOfs. For any system [s], either [k] knows \n   of [p] within the system or they do not. *)\n\nTheorem knowsOfs_dec:forall k s p, {(knowsOfs k s p)}+{~(knowsOfs k s p)}.\nProof.\n    intros k s p.\n    induction s; simpl in *.\n    + right. unfold not. intros. inversion H.     \n    + pose proof knowsOfe_dec k a p. inverts H.\n    ++ left. left. apply H0.\n    ++ inverts IHs.\n    +++ left. right. apply H.\n    +++ right. unfold not. intros. inversion H1; auto.\nDefined. \n\n(** Determine if place [k] within the environment [e]  \n    depends on place [p] (the context relation) *)\nDefinition dependsOne (k:Plc)(e:Environment)(p:Plc):Prop :=\nmatch (e k) with\n| None => False\n| Some m => In p m.(C)\nend.\n\n(** Determine if place [k] within the system [s] depends on place [p] (the context relation) *)\n\nFixpoint dependsOns (k:Plc)(s:System)(p:Plc):Prop :=\nmatch s with\n| [] => False\n| s1 :: ss => (dependsOne k s1 p) \\/ (dependsOns k ss p)\nend.\n\n(** decidability of dependsOne. For any enviornment [e], either the AM at place\n   [k] depends on something at place [p] or it does not. *)\n\nTheorem dependsOne_dec : forall k e p, {(dependsOne k e p)}+{~(dependsOne k e p)}.\nProof.\n  intros k e p.\n  unfold dependsOne.\n  destruct (e k).\n  +  induction (C m).\n  ++ auto.\n  ++ simpl. inversion IHl.\n  +++  auto.\n  +++ assert (H': {a = p } + { a <> p}). {repeat decide equality. } inversion H'.\n  ++++ left. left. apply H0.\n  ++++ right. unfold not. intros. inversion H1; auto.\n  + auto.\nDefined.\n\n(** decidability of dependsOns. For any system [s], either the AM at place [k] depends on something at place [p] or it does not. *)\n\nTheorem dependsOns_dec : forall k s p, {dependsOns k s p} + {~ dependsOns k s p}.\nProof.\n  intros. induction s. \n  + simpl. auto.\n  + simpl. pose proof dependsOne_dec k a p. inversion IHs.\n  ++ left. right. apply H0. \n  ++ inversion H.\n  +++ left. left. apply H1.\n  +++ right. unfold not. intros. inversion H2; auto.\nDefined. \n\n(** ***************************\n    * EXECUTABILITY \n*****************************)\n\n\n(** Is term [t] exectuable on the attestation manager named [k] in \n    environment [e]?  Are ASPs available at the right attesation managers\n    and are necessary communications allowed? *)\n\nFixpoint executable(t:Term)(k:Plc)(e:Environment):Prop :=\nmatch t with\n| asp a  => hasASPe k e a\n| att p t => knowsOfe k e p -> executable t p e\n| lseq t1 t2 => executable t1 k e /\\ executable t2 k e\n| bseq _ t1 t2 => executable t1 k e /\\ executable t2 k e\n| bpar _ t1 t2 => executable t1 k e /\\ executable t2 k e\nend.\n\n(* Ltac right_dest_contr H := right; unfold not; intros H; destruct H; contradiction.\nLtac right_dest_inverts := right; unfold not; intros H; inverts H. *)\n\n(** executability of a term is decidable *)\n\nTheorem executable_dec:forall t k e,{(executable t k e)}+{~(executable t k e)}.\nintros.  generalize k. induction t; intros.\n+ unfold executable. apply hasASPe_dec.\n+ simpl. pose proof knowsOfe_dec k0 e p. destruct H.\n++ destruct (IHt p).\n+++ left; auto.\n+++ right. unfold not. intros; auto.\n++ destruct (IHt p).\n+++ left; auto. \n+++ left. intros. congruence.\n+ simpl. specialize IHt1 with k0. specialize IHt2 with k0. \n  destruct IHt1,IHt2; try right_dest_contr H. \n++ left. split ; assumption.\n+ simpl. specialize IHt1 with k0. specialize IHt2 with k0. destruct IHt1,IHt2; try right_dest_contr H. \n++ left. split ; assumption.\n+ simpl. specialize IHt1 with k0. specialize IHt2 with k0. destruct IHt1,IHt2; try right_dest_contr H.\n++  left. split ; assumption.\nDefined.\n\n(** Is term [t] executable on the attestation mnanager named [k] in\n  system [s]?  Are ASPs available at the right attestation managers\n  and are necessary communications allowed? *)\nFixpoint executables(t:Term)(k:Plc)(s:System):Prop :=\n  match t with\n  | asp a  => hasASPs k s a\n  | att p t => knowsOfs k s p -> executables t p s\n  | lseq t1 t2 => executables t1 k s /\\ executables t2 k s\n  | bseq _ t1 t2 => executables t1 k s /\\ executables t2 k s\n  | bpar _ t1 t2 => executables t1 k s /\\ executables t2 k s\nend.\n\nLtac prove_exec :=\n    match goal with\n    | |- {executables (asp _) _ _} + {_} => unfold executables; apply hasASPs_dec\n    | IHt1 : _ , IHt2 : _ |- {executables _ ?k ?s} + {_} => simpl; specialize IHt1 with k s; specialize IHt2 with k s; destruct IHt1,IHt2 ; try( left; split ; assumption)\n    end.\n\nTheorem executables_dec : forall t k s, {executables t k s} + {~executables t k s}.\nProof.\nintros.  generalize k s. induction t; intros; try prove_exec; try right_dest_contr H.\n+ simpl. destruct (IHt p s0).\n++ auto.\n++ pose proof knowsOfs_dec k0 s0 p. destruct H.\n+++ right. unfold not; intros. intuition.\n+++ left. intros. congruence.\nDefined. \n\n(******************************\n*        POLICY\n*******************************)\n\n(** Check environment [e] and see if place [p] has some policy \n *  where the Policy allows p to run a. *)\nDefinition checkASPPolicy(p:Plc)(e:Environment)(a:ASP):Prop :=\nmatch (e p) with (* Look for p in the environment *)\n| None => False\n| Some m => (Policy m a p) (* Policy from m allows p to run a *)\nend.\n\n(** Recursive policy check. *)\nFixpoint checkTermPolicy(t:Term)(k:Plc)(e:Environment):Prop :=\n  match t with\n  | asp a  => checkASPPolicy k e a\n  | att r t0 => checkTermPolicy t0 k e\n  | lseq t1 t2 => checkTermPolicy t1 k e /\\ checkTermPolicy t2 k e\n  | bseq _ t1 t2 => checkTermPolicy t1 k e /\\ checkTermPolicy t2 k e\n  | bpar _ t1 t2 => checkTermPolicy t1 k e /\\ checkTermPolicy t2 k e\n  end.\n\n(** Proving policy check is decidable. \n  * This is true if ASP policy is decidable. *)\nTheorem checkTermPolicy_dec:forall t k e,\n    (forall p0 a0, {(checkASPPolicy p0 e a0)} + {~(checkASPPolicy p0 e a0)}) ->\n    {(checkTermPolicy t k e)}+{~(checkTermPolicy t k e)}.\nProof.\n  intros t k e.\n  intros H.\n  induction t.\n  + simpl. apply H.\n  + simpl. assumption.\n  + simpl; destruct IHt1,IHt2.\n  ++ left. split; assumption.\n  ++ right_dest_contr H'.\n  ++ right_dest_contr H'.\n  ++ right_dest_contr H'.\n  + simpl; destruct IHt1,IHt2.\n  ++ left. split; assumption.\n  ++ right_dest_contr H'.\n  ++ right_dest_contr H'.\n  ++ right_dest_contr H'.\n  + simpl; destruct IHt1,IHt2.\n  ++ left. split; assumption.\n  ++ right_dest_contr H'.\n  ++ right_dest_contr H'.\n  ++ right_dest_contr H'. \nDefined.\n\n\n(** ***************************\n * SOUND\n *****************************)\n\n(** Soundness is executability and policy adherence *)\n\nDefinition sound (t:Term)(k:Plc)(e:Environment) :=\n  (executable t k e) /\\ (checkTermPolicy t k e).\n\n(** Prove soundness is decidable with the assumption necessary for policy\n * adherence decidability.\n *)\n\n Theorem sound_dec: forall t p e,\n (forall p0 a0, {(checkASPPolicy p0 e a0)} + {~(checkASPPolicy p0 e a0)})\n -> {sound t p e}+{~(sound t p e)}.\nProof.\n  intros t p e.\n  intros H.\n  unfold sound.\n  assert ({executable t p e}+{~(executable t p e)}). apply executable_dec.\n  assert ({checkTermPolicy t p e}+{~(checkTermPolicy t p e)}). { apply checkTermPolicy_dec. intros. apply H. }\n  destruct H0,H1.\n  + left. split; assumption.\n  + right_dest_contr H'.\n  + right_dest_contr H'.\n  + right_dest_contr H'.\nDefined.\n\n(** ***************************\n * EXAMPLE SYSTEM \n *****************************)\n\n(** Motivated by the Flexible Mechanisms for Remote Attestation, \n * we have three present parties in this attestation scheme. \n * These are used for example purposes.\n *)\n\nNotation P0 := \"P0\"%string.\nNotation P1 := \"P1\"%string.\nNotation P2 := \"P2\"%string.\n\n(** Introducing three asps for testing purposes. *)\nNotation aVC :=\n  (ASPC ALL EXTD (asp_paramsC \"aVC\"%string [\"x\"%string] P1 P1)).\nNotation aHSH :=\n  (ASPC ALL EXTD (asp_paramsC \"aHSH\"%string [\"x\"%string] P1 P1)).\nNotation aSFS :=\n  (ASPC ALL EXTD (asp_paramsC \"aSFS\"%string [\"x\"%string] P2 P2)).\n\n(** Below are relational definitions of Policy. Within the definition, we\n * list each ASP on the AM and state who can recieve a measurement of said\n * ASP (ie doesn't expose sensitive information in the context).\n * \n * The relying party (P0) has no measurement to write policy over. \n * P1 can share the measurement aHSH and aVC with P0\n * P2 can share a measurement using aSFS with P1 \n*)\n\nInductive tar_Policy : ASP -> Plc -> Prop := \n| p_aHSH : tar_Policy aHSH P2 \n| p_SIG : forall p, tar_Policy SIG p. \n\nInductive P0_Policy : ASP -> Plc -> Prop :=.\n\nInductive P1_Policy : ASP -> Plc -> Prop :=\n| aVC_p: P1_Policy aVC P0\n| aHSH_p: P1_Policy aHSH P0. \n\nInductive P2_Policy : ASP -> Plc -> Prop :=\n| aSFS_pL: P2_Policy aSFS P1.\n\nGlobal Hint Constructors P0_Policy : core.\nGlobal Hint Constructors P1_Policy : core.\nGlobal Hint Constructors P2_Policy : core.\n\n(** Definition of environments for use in examples and proofs.  \n * Note there are 3 communicating peer's present... \n * P0, P1, and P2.\n *)\n\nDefinition e0 := e_empty.\nDefinition e_P0 :=\n    e_update e_empty P0 (Some {| asps := []; K:= [P1] ; C := [] ; Policy := P0_Policy |}).\nDefinition e_P1 :=\n    e_update e_P0 P1 (Some {| asps := [aVC;  aHSH]; K:= [P2] ; C := [] ; Policy := P1_Policy|}).\nDefinition e_P2 :=\n    e_update e_P1 P2 (Some {| asps := [aSFS] ; K:= [] ; C := [P1] ; Policy := P2_Policy |}).\n\n(** In our example, the system includes the relying party, the target,\n * and the appraiser\n *)\n\nDefinition example_sys_1 := [e_P0; e_P1; e_P2]. \n\n(** ***************************\n  * EXAMPLE SYSTEM PROPERTIES\n  *****************************)\n\n(** Prove the P0 knows of P1 in P0's enviornment *)\n\nExample ex1: knowsOfe P0 e_P0 P1.\nProof. unfold knowsOfe. simpl. left. reflexivity. Qed.\n\n(** relying party does not have the ASP aVC *)\n\nExample ex2: hasASPe P0 e_P0 aVC -> False.\nProof. unfold hasASPe. simpl. intros. inverts H. Qed.\n\n(** Prove the P1 can generate a term with aHSH within the system *)\n\nExample ex3: hasASPs P1 (example_sys_1) aVC.\nProof. simpl. unfold hasASPe. simpl. auto. Qed. \n\n(** the P0 knows of the target within system 1\n *)\n\nExample ex4: knowsOfs P0 example_sys_1 P1.\nProof.\nunfold knowsOfs. simpl. left. unfold knowsOfe. simpl.  auto.\nQed.\n\n(** the P0 does not directly know of the appraiser\n *)\n\nExample ex5: knowsOfe P0 e_P2 P2 -> False.\nProof.\n  unfold knowsOfe. simpl. intros. destruct H. inversion H. assumption.\nQed.\n\n(** the P0 does not knows of the P2 within the system... \n * should be that P0 knows of P1 and P1\n * knows of P2....\n *)\n\nExample ex6: knowsOfs P0 example_sys_1 P2 -> False.\nProof.\nunfold knowsOfs. simpl. unfold knowsOfe. simpl. intros. inverts H. inverts H0. inverts H. apply H. inverts H0. destruct H. inverts H. apply H. destruct H. inverts H. inverts H0. apply H0. apply H.\nQed.\n\n(** if the P0 was it's own system, it would still be aware of\n *  P1 *)\n\nExample ex7: knowsOfs P0 [e_P0] P1.\nProof.\nunfold knowsOfs,knowsOfe. simpl. auto.\nQed.\n\n(** Proof tactic for executability\n *)\nLtac prove_exec' :=\n    simpl; auto; match goal with\n                 | |- hasASPe _ _ _ => cbv; left; reflexivity\n                 | |- knowsOfe _ _ _ => unfold knowsOfe; simpl; left; reflexivity\n                 | |- _ /\\ _ => split; prove_exec'\n                 | |- ?A => idtac A\n                 end.\n\n(** Is asp aVC executable on the P1 in the P1s's\n * enviornement?\n *)\n\nExample ex8: (executable (asp aVC) P1 e_P1).\nProof. prove_exec'. Qed.\n\n(** aSFS is not executable on P1 even if in P2's environment\n *)\n\nExample ex9: (executable (asp aSFS) P1 e_P2) -> False.\nProof.\n  intros Hcontra; cbv in *; destruct Hcontra. inverts H. destruct H. inverts H. apply H.\nQed.\n\n(** two aHSH operations are executable on the P1\n *)\n\nExample ex10: (executable (lseq (asp aHSH) (asp aHSH)) P1 e_P1).\nProof. prove_exec'; cbv; auto. Qed.\n\n(** the relying party can ask the target to run aVC and signature\n * operations within system 1\n *) \n\nExample ex11: (executables (lseq (asp aVC) (att P1 (lseq (asp aHSH) (asp aHSH)))) P1 example_sys_1).\nProof. \n  prove_exec'; cbv; auto. intros. split; auto. \nQed.\n\n(* A few decidability proofs... useful later*)\nTheorem string_dec: forall (s s':string), {s=s'}+{s<>s'}.\nProof.\n  intros s s'.\n  repeat decide equality.\nDefined.\n\nTheorem plc_dec: forall (p p':Plc),{p=p'}+{p<>p'}.\nProof.\n  intros p p'.\n  apply string_dec.\nDefined.\n\n(** A proof that [tar_Policy] is decidable.  If we can show all policies are\n* decidable, life is good.  This is a start.\n*)\nTheorem tar_Policy_dec: forall (asp:ASP)(plc:Plc), {(tar_Policy asp plc)}+{~(tar_Policy asp plc)}.\nProof.\n  intros asp.\n  intros plc.\n  destruct asp.\n  + right_dest_inverts.\n  + right_dest_inverts.\n  + pose proof ASP_dec (ASPC s f a) aHSH.\n    pose proof plc_dec plc P2.\n    destruct H; destruct H0.\n  ++ subst. left. rewrite e. apply p_aHSH.\n  ++ right. rewrite e. unfold not in *. intros Hneg. apply n. inversion Hneg. reflexivity.\n  ++ right. unfold not in *. intros Hneg. apply n. inversion Hneg. reflexivity.\n  ++ right. unfold not in *. intros Hneg. apply n. inversion Hneg. reflexivity.\n  + left. apply p_SIG.\n  + right_dest_inverts.\nDefined.\n\n(* Policy P0 is decidable *)\nTheorem P0_Policy_dec: forall (asp:ASP)(plc:Plc), {(P0_Policy asp plc)}+{~(P0_Policy asp plc)}.\nProof.\n  intros asp; intros plc; destruct asp; right_dest_inverts.\nDefined.\n  \n(* Policy P1 is decidable *)\nTheorem P1_Policy_dec: forall (asp:ASP)(plc:Plc), {(P1_Policy asp plc)}+{~(P1_Policy asp plc)}.\n  intros asp.\n  intros plc.\n  destruct asp. \n  + right_dest_inverts.\n  + right_dest_inverts.\n  + pose proof ASP_dec (ASPC s f a) aHSH.\n    pose proof ASP_dec (ASPC s f a) aVC.\n    pose proof plc_dec plc P0.\n    destruct H; destruct H0; destruct H1; subst.\n  ++ rewrite e in e1. inversion e1.\n  ++ rewrite e in e1. inversion e1.\n  ++ rewrite e. auto.\n  ++ right_dest_inverts. contradiction. contradiction.\n  ++ rewrite e. left. auto.\n  ++ right_dest_inverts; contradiction.\n  ++ right_dest_inverts; contradiction.\n  ++ right_dest_inverts; contradiction.\n  + right_dest_inverts.\n  + right_dest_inverts.\nDefined.\n  \n(* Policy P2 is decidable *)\nTheorem P2_Policy_dec: forall (asp:ASP)(plc:Plc), {(P2_Policy asp plc)}+{~(P2_Policy asp plc)}.\nProof.\n  intros asp.\n  intros plc.\n  destruct asp.\n  + right_dest_inverts.\n  + right_dest_inverts.\n  + pose proof ASP_dec (ASPC s f a) aSFS.\n    pose proof plc_dec plc P1.\n    destruct H,H0.\n  ++ left. subst. rewrite e. auto.\n  ++ right_dest_inverts; contradiction.\n  ++ right_dest_inverts; contradiction.\n  ++ right_dest_inverts; contradiction.\n  + right_dest_inverts.\n  + right_dest_inverts.\nDefined.\n\nLtac map_update_eq := unfold e_P2; apply e_update_reduce; unfold not; intros Hneg; rewrite Hneg in *; contradiction.\n\n(* With Policy, we can now prove the system (e_P2) is sound. *)\nTheorem sound_local_policies: (forall p0 a0, {(checkASPPolicy p0 e_P2 a0)} + {~(checkASPPolicy p0 e_P2 a0)}).\nProof.\n  intros p a.\n  pose proof plc_dec p P0.\n  pose proof plc_dec p P1. \n  pose proof plc_dec p P2. \n  destruct H, H0, H1.\n  + rewrite e in e1. inversion e1.\n  + rewrite e in e1. inversion e1.\n  + rewrite e in e1. inversion e1.\n  + rewrite e. unfold checkASPPolicy. simpl. apply P0_Policy_dec.\n  + rewrite e in e1. inversion e1.\n  + rewrite e. unfold checkASPPolicy. simpl. apply P1_Policy_dec.\n  + rewrite e. unfold checkASPPolicy. simpl. apply P2_Policy_dec.\n  + right. unfold checkASPPolicy. \n   assert (H: e_P2 p = e_P1 p). { map_update_eq. }\n   assert (H0: e_P1 p = e_P0 p). { map_update_eq. }\n   assert (H1: e_P0 p = e_empty p). { map_update_eq. }\n   unfold not. intros Hneg. rewrite <- H in *. rewrite <- H0 in *. rewrite H1 in *. auto.\nDefined.\n\n(* Proof that the system described by e_P2 is sound. *)\nTheorem sound_system_dec: forall t p, {sound t p e_P2}+{~(sound t p e_P2)}.\nProof.\n  intros t p.\n  apply sound_dec.\n  intros p0 a0.\n  apply sound_local_policies.\nDefined.\n\nCompute sound_system_dec (asp aHSH) P1.\nCompute sound_system_dec (asp aSFS) P2.\n\nEnd Manifest.\n\n\n(* END OF FILE *)\n", "meta": {"author": "ku-sldg", "repo": "nfm2023", "sha": "b0140a2d383d17c6b69528f021bf1ae2b0b7729c", "save_path": "github-repos/coq/ku-sldg-nfm2023", "path": "github-repos/coq/ku-sldg-nfm2023/nfm2023-b0140a2d383d17c6b69528f021bf1ae2b0b7729c/Negotiation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2509080388771648}}
{"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 ctrl.\nRequire Import VerifProgBase.\nRequire Import VerifMainUtil.\nRequire Import PALSSystem.\n\nRequire Import AcStSystem.\nRequire Import LinkController.\nRequire Import SpecController.\nRequire Import VerifController_Base.\n\nImport Clight Clightdefs.\nImport ITreeNotations.\nImport ActiveStandby.\n\nImport CtrlState.\n\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\nFixpoint adv_qidx_n (n: nat) (i:Z): Z :=\n  match n with\n  | O => i\n  | S n' => adv_qidx (adv_qidx_n n' i)\n  end.\n\nLemma range_adv_qidx_n_prec\n  : forall n i\n      (RANGE_I: 0 <= i < 4),\n    0 <= adv_qidx_n n i < 4.\nProof.\n  i. destruct n; ss.\n  apply range_qrange_sanitize_prec.\nQed.\n\n\nSection VERIF_FUNC.\n  Variable tid: nat.\n  Variable cprog: Clight.program.\n  Variable r: nat -> itree progE unit -> Clight.state -> Prop.\n\n  Hypothesis CTRL_TASK_ID: (tid = 1 \\/ tid = 2)%nat.\n  (* Hypothesis CPROG_EQ: __guard__ (cprog = prog_ctrl (Z.of_nat tid)). *)\n  (* Notation prog := (prog_of_clight (prog_ctrl (Z.of_nat tid))). *)\n  Notation prog := (prog_of_clight cprog).\n  Notation ge := (globalenv cprog).\n\n  Hypothesis GENV_PROPS\n    : genv_props ge\n                 (main_gvar_ilist tid ++ ctrl_gvar_ilist)\n                 (main_gfun_ilist ++ ctrl_gfun_ilist)\n                 (main_cenv_ilist ++ ctrl_cenv_ilist).\n\n  Local Opaque idx_qs idx_aqi.\n  Definition idx_addq: nat := idx_qs + (idx_aqi + 30) * 3 + 30.\n\n  (* Ltac step_fptr_tac := *)\n  (*   match goal with *)\n  (*   | |- context [Evar ?fid] => *)\n  (*     hexploit (in_gfun_ilist fid); [sIn|]; []; *)\n  (*     i; des; *)\n  (*     econs; [ss| eval_comput | eval_comput | eauto | ss] *)\n  (*   end. *)\n\n  Inductive addq_linv\n            (itr0: itree progE unit) (m0: mem)\n            b_cst id_dev md tout qb qe q\n            (i: nat) (itr: itree progE unit)\n            (le: PTree.t val) (m: mem): Prop :=\n    AddqLoopInv\n      st csr\n      v_d1 v_d2 v_d3\n      (ITR_INVAR: itr = itr0)\n      (MEM_INVAR: m = m0)\n      (STATE: st = mk md tout qb qe q)\n      (RES_EQ: try_add_queue st id_dev =\n               try_add_queue_loop st id_dev (3 - i) csr)\n      (* (CURSOR: csr = qrange_sanitize (qb + Z.of_nat i)) *)\n      (CURSOR: csr = adv_qidx_n i (qrange_sanitize qb))\n      (* qrange_sanitize (qb + Z.of_nat i)) *)\n      (LENV_EQUIV:\n         lenv_equiv le\n                    [(_id_dev, Vint (Int.repr id_dev));\n                    (_st, Vptr b_cst Ptrofs.zero);\n                    (_qb, Vint (Int.repr qb));\n                    (_qe, Vint (Int.repr qe));\n                    (_q, Vptr b_cst (Ptrofs.repr 4));\n                    (_csr, Vint (Int.repr csr));\n                    (_i, Vint (Int.repr (Z.of_nat i)));\n                    (_tid, v_d1); (_t'3, v_d2); (_t'2, v_d3);\n                    (_t'1, Vint (Int.repr (qrange_sanitize qb)))])\n  .\n\n\n  Lemma sim_try_add_queue\n        (itr: itree progE unit)\n        (m: mem) (k: cont) (idx_ret: nat)\n        st id_dev b_cst\n        (CALL_CONT: is_call_cont k)\n        (WF_ST: CtrlState.wf st)\n        (MEM_CST: mem_cst_blk m st b_cst)\n        (* (MEM_MSTORE: Mem_inbox m b_mst ofs_inb inb) *)\n        (* (RANGE_OFS_HB: 0 <= ofs_inb <= Ptrofs.max_unsigned) *)\n        (RANGE_ID_DEV: IntRange.sintz8 id_dev)\n        (SIM_RET:\n           forall m' st'\n             (ST': st' = try_add_queue st id_dev)\n             (MEM_CST: mem_cst_blk m' st' b_cst)\n             (MEM_CH_BLK: mem_changed_block b_cst m m')\n           ,\n           paco3 (_sim_itree prog) r\n                 idx_ret itr\n                 (Returnstate Vundef k m'))\n    : paco3 (_sim_itree prog) r\n            (idx_ret + idx_addq)%nat itr\n            (Callstate (Internal f_try_add_queue)\n                       [Vptr b_cst Ptrofs.zero;\n                       Vint (Int.repr id_dev)] k m).\n  Proof.\n    unfold idx_addq.\n    start_func.\n    { econs. }\n    ss.\n\n    fw. clear STEP_ENTRY.\n    fw.\n    destruct st as [md tout qb qe q].\n    fw.\n    { econs.\n      eval_comput.\n      rewrite Ptrofs.add_zero_l.\n      repr_tac. s.\n      erewrite Mem.loadbytes_load; cycle 1.\n      { s. apply MEM_CST. }\n      { ss. solve_divide. }\n      rewrite decode_val_signed_byte. s.\n      rewrite sign_ext_byte_range.\n      2: { apply Byte.signed_range. }\n      rewrite Byte.signed_repr.\n      2: { inv WF_ST. ss. }\n      reflexivity.\n    }\n    upd_lenv.\n    fw. fw. fw.\n    { econs. eval_comput.\n      repr_tac. s.\n      rewrite Ptrofs.add_zero_l.\n      repr_tac.\n      erewrite Mem.loadbytes_load; cycle 1.\n      { s. apply MEM_CST. }\n      { ss. solve_divide. }\n      rewrite decode_val_signed_byte. s.\n      rewrite sign_ext_byte_range.\n      2: { apply Byte.signed_range. }\n      rewrite Byte.signed_repr.\n      2: { inv WF_ST. ss. }\n      reflexivity.\n    }\n    upd_lenv.\n    fw. fw. fw.\n    { econs. eval_comput.\n      rewrite Ptrofs.add_zero_l.\n      repr_tac. s. reflexivity.\n    }\n    upd_lenv.\n\n    fw. fw. fw. fw.\n    { step_fptr_tac. }\n\n    red_idx (idx_ret + 3 * (idx_aqi + 30) + 15 + idx_qs)%nat.\n    eapply sim_qrange_sanitize.\n    { ss. }\n    { inv WF_ST. range_stac. }\n\n    fw. upd_lenv.\n    fw. fw.\n    { econs. eval_comput.\n      rewrite sign_ext_byte_range.\n      2: { apply range_qrange_sanitize. }\n      reflexivity.\n    }\n    upd_lenv.\n\n    fw. fw. fw.\n    { econs. eval_comput. reflexivity. }\n    upd_lenv.\n    fw.\n\n    eapply simple_for_loop\n      with\n        (i_max := 3%nat) (idx_each := (idx_aqi + 30)%nat)\n        (idx0 := (idx_ret + 5)%nat)\n        (loop_inv := addq_linv itr m b_cst id_dev\n                               md tout qb qe q).\n    { econs; eauto. ss. }\n    { range_stac. }\n    { nia. }\n    { (* loop body *)\n      clear le LENV_EQUIV.\n      i. inv LINV.\n\n      pose (cursor := adv_qidx_n i (qrange_sanitize qb)).\n      fold cursor in LENV_EQUIV, RES_EQ.\n\n      fw. fw. fw.\n      { econs.\n        - eval_comput.\n          repr_tac.\n          replace 3 with (Z.of_nat 3) by ss.\n          rewrite <- Nat2Z_inj_ltb.\n          destruct (Nat.ltb_spec i 3); ss.\n          exfalso. nia.\n        - ss.\n      }\n      rewrite Int.eq_false by ss. s.\n\n\n      assert (CURSOR_SMALL: 0 <= cursor < 4).\n      { apply range_adv_qidx_n_prec.\n        apply range_qrange_sanitize_prec. }\n      assert (BYTE_4_AUX: 4 < Byte.max_signed) by ss.\n\n      assert (ADV_QIDX_SMALL: (0 <= adv_qidx cursor < 4)).\n      { apply range_adv_qidx_prec. }\n\n      fw. fw. fw.\n      { econs.\n        - eval_comput.\n          rewrite Int_eq_repr_signed; cycle 1.\n          { range_stac. }\n          { inv WF_ST. range_stac. }\n          reflexivity.\n        - rewrite bool_val_of_bool.\n          reflexivity.\n      }\n\n      replace (3 - i)%nat with (S (3 - (S i))) in RES_EQ by nia.\n      simpl in RES_EQ.\n\n      destruct (Z.eqb_spec cursor qe) as [CEQ|CNE]; ss.\n      { (* reached end_of_queue *)\n        guardH CEQ.\n        fw.\n\n        assert (STORE_BYTE: exists m',\n                   Mem.store\n                     Mint8signed m b_cst (4 + cursor)\n                     (Vint (Int.repr id_dev)) = Some m').\n        { apply inhabited_sig_to_exists.\n          econs.\n          apply Mem.valid_access_store.\n          rr. split; ss.\n          2: { apply Z.divide_1_l. }\n          ii. apply MEM_CST. nia. }\n        des.\n\n        fw.\n        { econs.\n          - eval_comput.\n            repr_tac.\n            rewrite Z.mul_1_l. reflexivity.\n          - eval_comput.\n            reflexivity.\n          - ss.\n          - eval_comput.\n            repr_tac.\n            rewrite sign_ext_byte_range by ss.\n            eauto.\n        }\n        fw. fw. fw. fw.\n        { step_fptr_tac. }\n\n        red_idx (idx1 - idx_aqi - 15 + idx_aqi)%nat.\n        eapply sim_adv_qidx; eauto.\n        { eapply GENV_PROPS. }\n        { ss. }\n        { range_stac. }\n        fw. upd_lenv.\n\n        assert (STORE_F:\n                  exists m_f, Mem.store Mint8signed\n                                   m' b_cst 3 (Vint (Int.repr (adv_qidx cursor))) = Some m_f).\n        { apply inhabited_sig_to_exists.\n          econs.\n          apply Mem.valid_access_store.\n          rr. split; ss.\n          2: { apply Z.divide_1_l. }\n          ii.\n          eapply Mem.perm_store_1; eauto.\n          apply MEM_CST. nia. }\n        des.\n\n        fw. fw.\n        { econs.\n          - eval_comput.\n            repr_tac. s.\n            rewrite Ptrofs.add_zero_l.\n            reflexivity.\n          - eval_comput. reflexivity.\n          - ss.\n          - eval_comput.\n            rewrite sign_ext_byte_range by range_stac.\n            repr_tac.\n            eauto.\n        }\n        fw. fw. fw. fw.\n\n        assert (MEM_UNCH_TOT:\n                  mem_unchanged_except\n                    (fun b ofs => b = b_cst /\\\n                               (ofs = 3 \\/ 4 <= ofs < 8))\n                    m m_f).\n        { eapply Mem.unchanged_on_trans.\n          - eapply Mem.store_unchanged_on; eauto.\n            s. ii. des. nia.\n          - eapply Mem.store_unchanged_on; eauto.\n            s. ii. des. nia.\n        }\n\n        red_idx idx_ret.\n        eapply SIM_RET; eauto.\n        - rewrite RES_EQ.\n          inv MEM_CST.\n          econs; ss.\n          + erewrite Mem.loadbytes_unchanged_on; eauto.\n            s. nia.\n          + erewrite Mem.loadbytes_unchanged_on; eauto.\n            s. nia.\n          + erewrite Mem.loadbytes_unchanged_on; eauto.\n            s. nia.\n          + apply Mem.loadbytes_store_same in STORE_F. ss.\n            rewrite STORE_F.\n            unfold encode_int. ss.\n            rewrite rev_if_be_single. ss.\n            rewrite Int.unsigned_repr by range_stac.\n            reflexivity.\n          + eapply Mem.loadbytes_unchanged_on.\n            { eapply store_unchanged_on'; eauto. }\n            { i. unfold mem_range. ss. nia. }\n\n            eapply (set_queue_mem cursor id_dev); eauto.\n          + ii.\n            eapply Mem.perm_store_1; eauto.\n            eapply Mem.perm_store_1; eauto.\n        - eapply Mem.unchanged_on_implies; eauto.\n          s. ii. des; ss.\n      }\n\n      (* not reached the end yet *)\n      fw. fw.\n\n      assert (NCSR: exists ncsr, Z.of_nat ncsr = cursor).\n      { exists (Z.to_nat cursor). nia. }\n      des.\n\n      hexploit (nth_error_Some2 _ q ncsr).\n      { inv WF_ST. nia. }\n      i. des. renames e1 NTH_EX into q_c Q_C.\n\n      assert (RANGE_Q_C: IntRange.sintz8 q_c).\n      { inv WF_ST.\n        rewrite Forall_forall in RANGE_QUEUE.\n        apply RANGE_QUEUE.\n        eapply nth_error_In; eauto. }\n\n      fw.\n      { econs. eval_comput.\n        repr_tac.\n        rewrite Z.mul_1_l.\n\n        erewrite Mem.loadbytes_load; cycle 1.\n        { s.\n          erewrite loadbytes_nth_error; eauto.\n          - eapply mem_cst_q; eauto.\n          - s. apply map_nth_error_iff.\n            esplits; eauto.\n        }\n        { s. solve_divide. }\n        { rewrite decode_val_signed_byte.\n          rewrite Byte.signed_repr by ss.\n          rewrite sign_ext_byte_range by ss.\n          reflexivity. }\n      }\n      upd_lenv.\n      fw. fw. fw.\n      { econs.\n        - eval_comput.\n          rewrite Int_eq_repr_signed by range_stac.\n          reflexivity.\n        - rewrite bool_val_of_bool. reflexivity.\n      }\n\n      unfold get_queue in RES_EQ.\n      erewrite nth_error_nth in RES_EQ.\n      2: { rewrite <- NCSR.\n           rewrite Nat2Z.id. eauto. }\n\n      destruct (Z.eqb_spec q_c id_dev) as [EQ_CUR | NEQ_CUR].\n      { (* id_dev already in queue *)\n        guardH EQ_CUR.\n        fw. fw. fw.\n\n        red_idx idx_ret.\n        eapply SIM_RET; eauto.\n        - rewrite RES_EQ. ss.\n        - apply Mem.unchanged_on_refl.\n      }\n\n      fw. fw. fw.\n      { step_fptr_tac. }\n\n      red_idx (idx1 - idx_aqi - 15 + idx_aqi)%nat.\n      eapply sim_adv_qidx.\n      { apply GENV_PROPS. }\n      { ss. }\n      { range_stac. }\n      fw. upd_lenv.\n      fw. fw.\n      { econs. eval_comput.\n        rewrite sign_ext_byte_range by range_stac.\n        reflexivity. }\n      upd_lenv.\n\n      fw.\n      { econs. eauto. }\n      repeat (rewrite <- Nat.add_assoc; ss).\n      fw.\n      { econs. eval_comput.\n        repr_tac.\n        replace (Z.of_nat i + 1) with (Z.of_nat (S i)) by nia.\n        reflexivity. }\n      fw. upd_lenv.\n\n      red_idx (idx1 - (idx_aqi + 30))%nat.\n      eapply SIM_NEXT.\n      econs; eauto.\n    }\n\n    clear le LENV_EQUIV.\n    i. inv LINV_END.\n    fw. fw. fw.\n    { econs.\n      - eval_comput.\n        repr_tac.\n        replace (Z.of_nat 3) with 3 by ss.\n        rewrite Z.ltb_irrefl. ss.\n      - ss.\n    }\n\n    rewrite Int.eq_true by ss. s.\n    fw. fw.\n    red_idx (idx_ret + 1)%nat.\n    fw.\n\n    red_idx idx_ret.\n    eapply SIM_RET; eauto.\n    - rewrite RES_EQ. ss.\n    - apply Mem.unchanged_on_refl.\n  Qed.\n\n\n  Definition idx_rel: nat := idx_qs + 50.\n\n  Lemma sim_try_release\n        (itr: itree progE unit)\n        (m: mem) (k: cont) (idx_ret: nat)\n        st id_dev b_cst\n        (CALL_CONT: is_call_cont k)\n        (WF_ST: CtrlState.wf st)\n        (MEM_CST: mem_cst_blk m st b_cst)\n        (RANGE_ID_DEV: IntRange.sintz8 id_dev)\n        (* (MEM_MSTORE: Mem_inbox m b_mst ofs_inb inb) *)\n        (* (RANGE_OFS_HB: 0 <= ofs_inb <= Ptrofs.max_unsigned) *)\n        (SIM_RET:\n           forall m' st'\n             (ST': st' = try_release st id_dev)\n             (MEM_CST: mem_cst_blk m' st' b_cst)\n             (MEM_CH_BLK: mem_changed_block b_cst m m')\n           ,\n           paco3 (_sim_itree prog) r\n                 idx_ret itr\n                 (Returnstate Vundef k m'))\n    : paco3 (_sim_itree prog) r\n            (idx_ret + idx_rel)%nat itr\n            (Callstate (Internal f_try_release)\n                       [Vptr b_cst Ptrofs.zero;\n                       Vint (Int.repr id_dev)] k m).\n  Proof.\n    unfold idx_rel.\n    start_func.\n    { econs. }\n    ss.\n\n    fw. clear STEP_ENTRY.\n    fw.\n    destruct st as [md tout qb qe q].\n    fw.\n    { econs.\n      eval_comput.\n      rewrite Ptrofs.add_zero_l.\n      repr_tac. s.\n      erewrite Mem.loadbytes_load; cycle 1.\n      { s. apply MEM_CST. }\n      { ss. solve_divide. }\n      rewrite decode_val_signed_byte. s.\n      rewrite sign_ext_byte_range.\n      2: { apply Byte.signed_range. }\n      rewrite Byte.signed_repr.\n      2: { inv WF_ST. ss. }\n      reflexivity.\n    }\n    upd_lenv.\n    fw. fw. fw.\n    { econs. eval_comput.\n      repr_tac. s.\n      rewrite Ptrofs.add_zero_l.\n      repr_tac.\n      erewrite Mem.loadbytes_load; cycle 1.\n      { s. apply MEM_CST. }\n      { ss. solve_divide. }\n      rewrite decode_val_signed_byte. s.\n      rewrite sign_ext_byte_range.\n      2: { apply Byte.signed_range. }\n      rewrite Byte.signed_repr.\n      2: { inv WF_ST. ss. }\n      reflexivity.\n    }\n    upd_lenv.\n    fw. fw. fw.\n    { econs. eval_comput.\n      repr_tac. s.\n      rewrite Ptrofs.add_zero_l.\n      repr_tac.\n      erewrite Mem.loadbytes_load; cycle 1.\n      { s. apply MEM_CST. }\n      { ss. solve_divide. }\n      rewrite decode_val_signed_byte. s.\n      rewrite sign_ext_byte_range.\n      2: { apply Byte.signed_range. }\n      rewrite Byte.signed_repr.\n      2: { inv WF_ST. ss. }\n      reflexivity.\n    }\n    upd_lenv.\n\n    fw. fw. fw.\n    { econs. eval_comput.\n      rewrite Ptrofs.add_zero_l.\n      repr_tac. s. reflexivity.\n    }\n    upd_lenv.\n\n    fw. fw. fw.\n    { econs.\n      - eval_comput.\n        inv WF_ST.\n        rewrite Int_eq_repr_signed by range_stac.\n        reflexivity.\n      - rewrite bool_val_of_bool. reflexivity.\n    }\n\n    destruct (Z.eqb_spec qb qe).\n    { s.\n      (* destruct (Z.ltb_spec 0 tout). *)\n      (* 2: { (* do nothing *) *)\n      fw.\n      { econs. eval_comput. reflexivity. }\n      upd_lenv.\n      fw. fw.\n      { econs.\n        - eval_comput. reflexivity.\n        - ss. }\n      rewrite Int.eq_true by ss. s.\n      fw.\n\n      red_idx idx_ret.\n      eapply SIM_RET; eauto.\n      apply Mem.unchanged_on_refl.\n    }\n\n    s.\n    fw. fw.\n    { step_fptr_tac. }\n\n    red_idx (idx_ret + 20 + idx_qs)%nat.\n    eapply sim_qrange_sanitize.\n    { ss. }\n    { inv WF_ST. range_stac. }\n\n    fw. upd_lenv.\n    fw.\n\n    generalize (range_qrange_sanitize_prec qb).\n    intros RANGE_QS_QB.\n    assert (BMAX_AUX_4: 4 < Byte.max_signed) by ss.\n\n    hexploit (nth_error_Some2 _ q (Z.to_nat (qrange_sanitize qb))).\n    { inv WF_ST. nia. }\n    intros (q_n & Q_N).\n\n    assert (RANGE_Q_N: IntRange.sintz8 q_n).\n    { inv WF_ST.\n      rewrite Forall_forall in RANGE_QUEUE.\n      apply RANGE_QUEUE.\n      eapply nth_error_In; eauto. }\n\n    fw.\n    { econs. eval_comput.\n      repr_tac.\n      rewrite Z.mul_1_l.\n\n      erewrite Mem.loadbytes_load; cycle 1.\n      { s.\n        erewrite loadbytes_nth_error; eauto.\n        { apply MEM_CST. }\n        { apply map_nth_error. s. eauto. }\n        rewrite Z2Nat.id by nia.\n        ss.\n      }\n      { s. solve_divide. }\n      s.\n      rewrite decode_byte.\n      rewrite sign_ext_byte_range_u by ss.\n      rewrite Int_eq_repr_signed; cycle 1.\n      { range_stac. }\n      { range_stac. }\n      instantiate (1:= if (q_n =? id_dev) then Vtrue else Vfalse).\n      destruct (Z.eqb_spec q_n id_dev); ss.\n    }\n\n    upd_lenv.\n    fw.\n\n    unfold get_queue in SIM_RET.\n    erewrite nth_error_nth in SIM_RET.\n    2: { eauto. }\n\n    destruct (Z.eqb_spec q_n id_dev).\n    2: { (* do nothing *)\n      fw.\n      { econs.\n        - eval_comput. ss.\n        - ss.\n      }\n      rewrite Int.eq_true by ss. s.\n      fw.\n\n      red_idx idx_ret.\n      eapply SIM_RET; eauto.\n      apply Mem.unchanged_on_refl.\n    }\n\n    (* update timeout *)\n    fw.\n    { econs.\n      - eval_comput. reflexivity.\n      - ss. }\n    rewrite Int.eq_false by ss. s.\n\n    assert (STORE_F:\n              exists m_f, Mem.store Mint8signed\n                               m b_cst 1 (Vint (Int.repr 1)) = Some m_f).\n    { apply inhabited_sig_to_exists.\n      econs.\n      apply Mem.valid_access_store.\n      rr. split; ss.\n      2: { apply Z.divide_1_l. }\n      ii. apply MEM_CST. nia. }\n    des.\n\n    fw. fw.\n    { econs.\n      - eval_comput.\n        repr_tac0; cycle 1.\n        { range_stac. }\n        { inv WF_ST. range_stac. }\n        reflexivity.\n      - s. rewrite bool_val_of_bool.\n        reflexivity.\n    }\n\n    destruct (Z.ltb_spec 0 tout).\n    2: {\n      fw.\n      { econs. eval_comput. reflexivity. }\n      upd_lenv.\n\n      fw. fw.\n      { econs.\n        - eval_comput. reflexivity.\n        - ss.\n      }\n      rewrite Int.eq_true. s.\n\n      fw.\n      red_idx idx_ret.\n      eapply SIM_RET; eauto.\n      apply Mem.unchanged_on_refl.\n    }\n\n    destruct (Z.ltb_spec tout MAX_TIMEOUT).\n    2: {\n      ss.\n      fw.\n      { econs. eval_comput.\n        inv WF_ST.\n        repr_tac.\n        fold MAX_TIMEOUT.\n        instantiate (1:= Vfalse).\n        destruct (Z.ltb_spec tout MAX_TIMEOUT); ss.\n        exfalso. nia.\n      }\n      fw. upd_lenv.\n      fw.\n      { econs.\n        - eval_comput. ss.\n        - ss.\n      }\n      rewrite Int.eq_true. s.\n      fw.\n      red_idx idx_ret.\n      eapply SIM_RET; eauto.\n      apply Mem.unchanged_on_refl.\n    }\n\n    fw.\n    { econs. eval_comput.\n      inv WF_ST.\n      repr_tac.\n      fold MAX_TIMEOUT.\n      destruct (Z.ltb_spec tout MAX_TIMEOUT); ss.\n      exfalso. nia.\n    }\n    rewrite Int.eq_false by ss.\n    upd_lenv.\n\n    fw. fw.\n    { econs.\n      - eval_comput. ss.\n      - ss.\n    }\n    rewrite Int.eq_false by ss. s.\n\n    fw.\n    { econs.\n      - eval_comput.\n        repr_tac. s.\n        rewrite Ptrofs.add_zero_l. ss.\n      - eval_comput. ss.\n      - s. ss.\n      - eval_comput.\n        rewrite sign_ext_byte_range by ss.\n        repr_tac. eauto.\n    }\n\n    fw.\n    red_idx idx_ret.\n    eapply SIM_RET; eauto.\n    - inv MEM_CST.\n      hexploit store_unchanged_on'; eauto. i.\n\n      econs; ss.\n      + eapply Mem.loadbytes_unchanged_on; eauto.\n        unfold mem_range. ii. nia.\n      + apply Mem.loadbytes_store_same in STORE_F. ss.\n      + eapply Mem.loadbytes_unchanged_on; eauto.\n        unfold mem_range. ii. nia.\n      + eapply Mem.loadbytes_unchanged_on; eauto.\n        unfold mem_range. ii. nia.\n      + eapply Mem.loadbytes_unchanged_on; eauto.\n        unfold mem_range. ii. nia.\n      + ii. eapply Mem.perm_store_1; eauto.\n    - eapply Mem.store_unchanged_on; eauto.\n  Qed.\n\n\n  Definition idx_appdev: nat := idx_addq + idx_rel + 20.\n\n  Lemma sim_apply_devmsg\n        (itr: itree progE unit)\n        (m: mem) (k: cont) (idx_ret: nat)\n        st id_dev ment\n        b_cst b_mst ofs_inb\n        (BLOCKS_DIFF: b_cst <> b_mst)\n        (CALL_CONT: is_call_cont k)\n        (WF_ST: CtrlState.wf st)\n        (MEM_CST: mem_cst_blk m st b_cst)\n        (MEM_MSTORE: Mem_msg_entry m b_mst ofs_inb id_dev ment)\n        (ID_DEV_UBND: (id_dev < num_tasks)%nat)\n        (RANGE_OFS_INB: 0 <= ofs_inb <= 4 + inb_sz)\n        (* (RANGE_OFS_HB: 0 <= ofs_inb + Z.of_nat (mentry_nsz * id_dev) <= Ptrofs.max_unsigned) *)\n        (SIM_RET:\n           forall m' st'\n             (ST': st' = apply_devmsg st (Z.of_nat id_dev) ment)\n             (MEM_CST: mem_cst_blk m' st' b_cst)\n             (MEM_CH_BLK: mem_changed_block b_cst m m')\n           ,\n           paco3 (_sim_itree prog) r\n                 idx_ret itr\n                 (Returnstate Vundef k m'))\n    : paco3 (_sim_itree prog) r\n            (idx_ret + idx_appdev)%nat itr\n            (Callstate (Internal f_apply_devmsg)\n                       [ Vptr b_cst Ptrofs.zero;\n                       Vint (IntNat.of_nat id_dev);\n                       Vptr b_mst (Ptrofs.repr (ofs_inb + Z.of_nat (mentry_nsz * id_dev)))] k m).\n  Proof.\n    unfold idx_appdev.\n\n    start_func.\n    { econs. }\n    ss.\n\n    hexploit (in_cenv_ilist _msg_entry_t); [sIn|].\n    intros CO_MENTRY.\n\n    hexploit Mem_msg_entry_inv2; eauto. i. des.\n\n    generalize (within_inb_nsz2 id_dev); eauto.\n    intro RANGE_MENTRY_AUX.\n    pose proof ptr_range_mstore as PRANGE_MSTORE.\n    replace (Z.of_nat (4 + inb_nsz + inb_nsz)) with\n        (4 + inb_sz + inb_sz) in PRANGE_MSTORE by ss.\n\n    fw. fw.\n    { hexploit (RANGE_MENTRY_AUX O); eauto.\n      { nia. }\n      rewrite Nat.add_0_r. intro AUX.\n      clear RANGE_MENTRY_AUX.\n\n      econs.\n      - eval_comput.\n        rewrite CO_MENTRY. s.\n        unfold align_attr. s.\n        unfold Coqlib.align. s.\n        repr_tac.\n        rewrite Z.add_0_r.\n        rewrite MENT_RCV.\n        instantiate (1:= if ment then Vtrue else Vfalse).\n        destruct ment; ss.\n      - instantiate (1:= if ment then true else false).\n        destruct ment; ss.\n    }\n\n    destruct ment as [msg_dev|].\n    2: { (* do nothing *)\n      fw.\n      red_idx idx_ret.\n      eapply SIM_RET; eauto.\n      apply Mem.unchanged_on_refl.\n    }\n\n    hexploit MENT_CONT; eauto.\n    clear MENT_CONT. intro MENT_CONT.\n\n    hexploit Mem.loadbytes_length; eauto.\n    rewrite Nat2Z.id.\n    intro LEN_INJ_MSG.\n\n    destruct msg_dev as [| mdev_h mdev_t]; ss.\n\n    replace (Z.of_nat 8) with (1 + 7) in MENT_CONT by ss.\n    eapply Mem_loadbytes_split' with (n1:= 1) in MENT_CONT; try nia.\n    rewrite rw_cons_app in MENT_CONT.\n    replace (Z.to_nat 1) with 1%nat in MENT_CONT by ss.\n    rewrite firstn_app_exact in MENT_CONT by ss.\n    rewrite skipn_app_exact in MENT_CONT by ss.\n    des.\n\n    fw. fw.\n    { econs.\n      eval_comput.\n      instantiate (1:= Vint (Int.repr (Byte.signed mdev_h))).\n\n      rewrite CO_MENTRY. s.\n      unfold align_attr. s.\n      unfold Coqlib.align. s.\n\n      hexploit (RANGE_MENTRY_AUX O); eauto.\n      { nia. }\n      rewrite Nat.add_0_r. intro AUX0.\n      hexploit (RANGE_MENTRY_AUX 1%nat); eauto.\n      { unfold mentry_nsz. nia. }\n      intro AUX1.\n\n      repr_tac.\n      erewrite Mem.loadbytes_load; cycle 1.\n      { s. rewrite Z.add_0_r.\n        apply MENT_CONT. }\n      { s. solve_divide. }\n      s.\n      rewrite decode_byte.\n      rewrite <- (Byte.repr_signed mdev_h).\n      rewrite sign_ext_byte_range_u.\n      2: { apply Byte.signed_range. }\n      rewrite sign_ext_byte_range.\n      2: { apply Byte.signed_range. }\n      rewrite Byte.signed_repr.\n      2: { apply Byte.signed_range. }\n      ss.\n    }\n    upd_lenv.\n\n    fw. fw.\n    { econs.\n      - eval_comput.\n        rewrite Int_eq_repr_signed; cycle 1.\n        { generalize (Byte.signed_range mdev_h).\n          range_stac. }\n        { range_stac. }\n        reflexivity.\n      - rewrite bool_val_of_bool. reflexivity.\n    }\n\n    destruct (Z.eqb_spec (Byte.signed mdev_h) 1).\n    - fw.\n      { step_fptr_tac. }\n\n      red_idx (idx_ret + 10 + idx_addq)%nat.\n      unfold IntNat.of_nat.\n\n      assert (RANGE_ID_DEV: IntRange.sintz8 (Z.of_nat id_dev)).\n      { pose proof range_num_tasks as RANGE_NT.\n        range_stac. }\n\n      rewrite sign_ext_byte_range by range_stac.\n      eapply sim_try_add_queue; eauto.\n      { ss. }\n\n      clear MEM_CST. i.\n      fw. fw.\n\n      red_idx idx_ret.\n      eapply SIM_RET; eauto.\n    - fw.\n      { step_fptr_tac. }\n\n      red_idx (idx_ret + 10 + idx_rel)%nat.\n      unfold IntNat.of_nat.\n\n      assert (RANGE_ID_DEV: IntRange.sintz8 (Z.of_nat id_dev)).\n      { pose proof range_num_tasks as RANGE_NT.\n        range_stac. }\n\n      rewrite sign_ext_byte_range by range_stac.\n      eapply sim_try_release; eauto.\n      { ss. }\n\n      clear MEM_CST. i.\n      fw. fw.\n\n      red_idx idx_ret.\n      eapply SIM_RET; eauto.\n  Qed.\n\n\n  Definition idx_redto: nat := idx_aqi + 50.\n\n  Lemma sim_reduce_timeout\n        (itr: itree progE unit)\n        (m: mem) (k: cont) (idx_ret: nat)\n        st b_cst\n        (CALL_CONT: is_call_cont k)\n        (WF_ST: CtrlState.wf st)\n        (MEM_CST: mem_cst_blk m st b_cst)\n        (SIM_RET:\n           forall m' st'\n             (ST': st' = reduce_timeout st)\n             (MEM_CST: mem_cst_blk m' st' b_cst)\n             (MEM_CH_BLK: mem_changed_block b_cst m m')\n           ,\n           paco3 (_sim_itree prog) r\n                 idx_ret itr\n                 (Returnstate Vundef k m'))\n    : paco3 (_sim_itree prog) r\n            (idx_ret + idx_redto)%nat itr\n            (Callstate (Internal f_reduce_timeout)\n                       [Vptr b_cst Ptrofs.zero] k m).\n  Proof.\n    unfold idx_redto.\n    start_func.\n    { econs. }\n    ss.\n\n    fw. clear STEP_ENTRY.\n    fw.\n    destruct st as [md tout qb qe q].\n    fw.\n    { econs.\n      eval_comput.\n      rewrite Ptrofs.add_zero_l.\n      repr_tac. s.\n      erewrite Mem.loadbytes_load; cycle 1.\n      { s. apply MEM_CST. }\n      { ss. solve_divide. }\n      rewrite decode_val_signed_byte. s.\n      rewrite sign_ext_byte_range.\n      2: { apply Byte.signed_range. }\n      rewrite Byte.signed_repr.\n      2: { inv WF_ST. ss. }\n      reflexivity.\n    }\n    upd_lenv.\n    fw. fw. fw.\n    { econs. eval_comput.\n      repr_tac. s.\n      rewrite Ptrofs.add_zero_l.\n      repr_tac.\n      erewrite Mem.loadbytes_load; cycle 1.\n      { s. apply MEM_CST. }\n      { ss. solve_divide. }\n      rewrite decode_val_signed_byte. s.\n      rewrite sign_ext_byte_range.\n      2: { apply Byte.signed_range. }\n      rewrite Byte.signed_repr.\n      2: { inv WF_ST. ss. }\n      reflexivity.\n    }\n    upd_lenv.\n\n    fw. fw.\n    { econs.\n      - eval_comput.\n        rewrite Int_eq_repr_signed; cycle 1.\n        { inv WF_ST. range_stac. }\n        { range_stac. }\n        ss.\n      - rewrite bool_val_of_bool. reflexivity.\n    }\n    destruct (Z.eqb_spec tout 1).\n    { (* tout = 1 *)\n      fw.\n\n      assert (STORE1: exists m1,\n                 Mem.store Mint8signed m b_cst 1\n                           (Vint (Int.repr 0)) = Some m1).\n      { apply inhabited_sig_to_exists.\n        econs.\n        apply Mem.valid_access_store.\n        rr. split; ss.\n        2: { apply Z.divide_1_l. }\n        ii. apply MEM_CST. nia. }\n      des.\n\n      fw.\n      { econs.\n        - eval_comput.\n          repr_tac. s.\n          rewrite Ptrofs.add_zero_l. reflexivity.\n        - eval_comput. ss.\n        - s. ss.\n        - eval_comput.\n          rewrite sign_ext_byte_range.\n          2: { range_stac. }\n          repr_tac.\n          eauto.\n      }\n\n      fw. fw. fw.\n      { step_fptr_tac. }\n\n      red_idx (idx_ret + 30 + idx_aqi)%nat.\n      eapply sim_adv_qidx; eauto.\n      { apply GENV_PROPS. }\n      { ss. }\n      { inv WF_ST. range_stac. }\n      fw. upd_lenv.\n\n      fw.\n\n      assert (STORE2: exists m2,\n                 Mem.store Mint8signed m1 b_cst 2\n                           (Vint (Int.repr (adv_qidx qb))) = Some m2).\n      { apply inhabited_sig_to_exists.\n        econs.\n        apply Mem.valid_access_store.\n        rr. split; ss.\n        2: { apply Z.divide_1_l. }\n        ii. eapply Mem.perm_store_1; eauto.\n        apply MEM_CST. nia. }\n      des.\n\n      fw.\n      { econs.\n        - eval_comput.\n          repr_tac. s.\n          rewrite Ptrofs.add_zero_l. reflexivity.\n        - eval_comput. reflexivity.\n        - ss.\n        - eval_comput.\n          rewrite sign_ext_byte_range.\n          2: { apply range_adv_qidx. }\n          repr_tac.\n          eauto.\n      }\n\n      fw.\n      red_idx idx_ret.\n\n      assert (MEM_UNCH: mem_unchanged_except\n                          (fun b ofs => b = b_cst /\\\n                                     (ofs = 1 \\/ ofs = 2))\n                          m m2).\n      { eapply Mem.unchanged_on_trans with (m2:= m1).\n        - eapply Mem.store_unchanged_on; eauto.\n          s. ii. nia.\n        - eapply Mem.store_unchanged_on; eauto.\n          s. ii. nia. }\n\n      eapply SIM_RET; eauto.\n      - inv MEM_CST.\n        econs; ss.\n        + eapply Mem.loadbytes_unchanged_on; eauto.\n          s. ii. nia.\n        + eapply Mem.loadbytes_unchanged_on.\n          { eapply store_unchanged_on'; eauto. }\n          { unfold mem_range. s. i. nia. }\n          eapply Mem.loadbytes_store_same in STORE1. ss.\n        + eapply Mem.loadbytes_store_same in STORE2. ss.\n          rewrite STORE2.\n          unfold encode_int. s.\n          rewrite rev_if_be_single.\n          unfold inj_bytes. s.\n          do 3 f_equal.\n          symmetry.\n          apply signed_byte_int_unsigned_repr_eq.\n        + eapply Mem.loadbytes_unchanged_on; eauto.\n          s. ii. nia.\n        + eapply Mem.loadbytes_unchanged_on; eauto.\n          s. ii. nia.\n        + ii. eapply Mem.perm_store_1; eauto.\n          eapply Mem.perm_store_1; eauto.\n      - eapply Mem.unchanged_on_implies; eauto.\n        ii. des; ss.\n    }\n\n    fw.\n    { econs.\n      - eval_comput.\n        inv WF_ST.\n        repr_tac. ss.\n      - rewrite bool_val_of_bool. ss.\n    }\n\n    destruct (Z.ltb_spec 1 tout).\n    { (* 1 < tout *)\n\n      assert (STORE1: exists m1,\n                 Mem.store Mint8signed m b_cst 1\n                           (Vint (Int.repr (tout - 1))) = Some m1).\n      { apply inhabited_sig_to_exists.\n        econs.\n        apply Mem.valid_access_store.\n        rr. split; ss.\n        2: { apply Z.divide_1_l. }\n        ii. apply MEM_CST. nia. }\n      des.\n\n      fw.\n      { econs.\n        - eval_comput.\n          repr_tac. s.\n          rewrite Ptrofs.add_zero_l. reflexivity.\n        - eval_comput. ss.\n        - s. ss.\n        - eval_comput.\n          inv WF_ST.\n          repr_tac.\n          rewrite sign_ext_byte_range.\n          2: { range_stac. }\n          eauto.\n      }\n\n      fw.\n      red_idx idx_ret.\n\n      hexploit store_unchanged_on'; eauto.\n      s. unfold mem_range. intro MEM_UNCH.\n\n      eapply SIM_RET; eauto.\n      - inv MEM_CST.\n        econs; ss.\n        + eapply Mem.loadbytes_unchanged_on; eauto.\n          s. ii. nia.\n        + eapply Mem.loadbytes_store_same in STORE1.\n          ss. rewrite STORE1.\n          unfold encode_int. s.\n          rewrite rev_if_be_single.\n          unfold inj_bytes. s.\n          do 3 f_equal.\n          symmetry.\n          apply signed_byte_int_unsigned_repr_eq.\n        + eapply Mem.loadbytes_unchanged_on; eauto.\n          s. ii. nia.\n        + eapply Mem.loadbytes_unchanged_on; eauto.\n          s. ii. nia.\n        + eapply Mem.loadbytes_unchanged_on; eauto.\n          s. ii. nia.\n        + ii. eapply Mem.perm_store_1; eauto.\n      - eapply Mem.unchanged_on_implies; eauto.\n        ii. des; ss.\n    }\n\n    (* do nothing *)\n    fw.\n    red_idx idx_ret.\n    eapply SIM_RET; eauto.\n    eapply Mem.unchanged_on_refl.\n  Qed.\n\n\n  Local Opaque idx_appdev idx_redto.\n  Definition idx_updq: nat := (idx_appdev + 20) * 3 + idx_redto + 20.\n\n\n  Inductive updq_linv\n            (itr0: itree progE unit) (m0: mem)\n            st inb b_cst b_mst ofs_inb\n            (* md tout qb qe q *)\n            (i: nat) (itr: itree progE unit)\n            (le: PTree.t val) (m: mem): Prop :=\n    UpdqLoopInv\n      st1 v_d1 v_d2\n      (ITR_INVAR: itr = itr0)\n      (* (MEM_INVAR: m = m0) *)\n      (WF_ST1: wf st1)\n      (MEM_CST: mem_cst_blk m st1 b_cst)\n      (MEM_CH_BLK: mem_changed_block b_cst m0 m)\n      (RES_EQ: update_queue st inb =\n               reduce_timeout (update_queue_loop\n                                 inb (imap (fun n _ => Z.of_nat n) (3 + i) (repeat tt (3 - i))) st1))\n      (LENV_EQUIV:\n         lenv_equiv le\n                    [(_inbox, Vptr b_mst (Ptrofs.repr ofs_inb));\n                    (_st, Vptr b_cst Ptrofs.zero);\n                    (_devmsg, v_d1);\n                    (_i, Vint (IntNat.of_nat i)); (_id_dev, v_d2)])\n  .\n\n  Lemma sim_update_queue\n        (itr: itree progE unit)\n        (m: mem) (k: cont) (idx_ret: nat)\n        st inb\n        b_cst b_mst ofs_inb\n        (BLOCKS_DIFF: b_cst <> b_mst)\n        (CALL_CONT: is_call_cont k)\n        (WF_ST: CtrlState.wf st)\n        (MEM_CST: mem_cst_blk m st b_cst)\n        (MEM_INB: Mem_inbox m b_mst ofs_inb inb)\n        (RANGE_OFS_HB: 0 <= ofs_inb <= 4 + inb_sz)\n        (SIM_RET:\n           forall m' st'\n             (ST': st' = update_queue st inb)\n             (MEM_CST: mem_cst_blk m' st' b_cst)\n             (MEM_CH_BLK: mem_changed_block b_cst m m')\n           ,\n           paco3 (_sim_itree prog) r\n                 idx_ret itr\n                 (Returnstate Vundef k m'))\n    : paco3 (_sim_itree prog) r\n            (idx_ret + idx_updq)%nat itr\n            (Callstate (Internal f_update_queue)\n                       [Vptr b_cst Ptrofs.zero;\n                       Vptr b_mst (Ptrofs.repr ofs_inb)] k m).\n  Proof.\n    unfold idx_updq.\n    start_func.\n    { econs. }\n    ss.\n\n    fw. fw. fw. fw.\n    { econs. eval_comput. ss. }\n    upd_lenv.\n\n    fw.\n\n    hexploit (in_cenv_ilist _inbox_t); [sIn|].\n    intros CO_INBOX.\n    hexploit (in_cenv_ilist _msg_entry_t); [sIn|].\n    intros CO_MENTRY.\n\n    assert (BYTE_RANGE_AUX: 6 < Byte.max_signed) by ss.\n\n    eapply simple_for_loop with\n        (i_max := 3%nat) (idx_each := (idx_appdev + 20)%nat)\n        (idx0 := 0%nat)\n        (loop_inv := updq_linv itr m st inb\n                               b_cst b_mst ofs_inb).\n    { econs; eauto.\n      eapply Mem.unchanged_on_refl. }\n    { range_stac. }\n    { nia. }\n    { (* loop body *)\n      clear le LENV_EQUIV MEM_CST.\n      i. inv LINV.\n\n      fw. fw. fw.\n      { econs.\n        - eval_comput. repr_tac.\n          replace 3 with (Z.of_nat 3) by ss.\n          rewrite <- Nat2Z_inj_ltb.\n          destruct (Nat.ltb_spec i 3).\n          2: { exfalso. nia. }\n          reflexivity.\n        - ss.\n      }\n\n      rewrite Int.eq_false by ss. s.\n      fw. fw. fw.\n      { econs. eval_comput.\n        repr_tac.\n        replace 3 with (Z.of_nat 3) by ss.\n        rewrite <- Nat2Z.inj_add.\n        rewrite sign_ext_byte_range.\n        2: { range_stac. }\n        reflexivity.\n      }\n      upd_lenv.\n\n      fw. fw. fw.\n      { econs.\n        eval_comput.\n        rewrite CO_INBOX. s.\n        unfold align_attr. s.\n        unfold Coqlib.align. s.\n        change main_prm._msg_entry_t with _msg_entry_t.\n        rewrite CO_MENTRY. s.\n        rewrite Ptrofs.add_zero.\n\n        repr_tac.\n\n        pose proof (within_inb_nsz2 (3 + i)) as WITHIN_INB_AUX.\n        pose proof ptr_range_mstore as PRANGE_MSTORE.\n\n        hexploit (WITHIN_INB_AUX O).\n        { unfold num_tasks. ss. nia. }\n        { nia. }\n        intro AUX_ZERO.\n\n        repr_tac0; cycle 1.\n        { nia. }\n        { nia. }\n\n        rewrite <- Nat2Z.inj_mul.\n        reflexivity.\n      }\n      upd_lenv.\n\n      fw. fw.\n      { step_fptr_tac. }\n\n      rewrite sign_ext_byte_range by range_stac.\n      red_idx (idx1 - 15 - idx_appdev + idx_appdev)%nat.\n\n      r in MEM_INB. des.\n      hexploit (nth_error_Some2 _ inb (3 + i)).\n      { rewrite NUM_ENTRIES.\n        unfold num_tasks. ss. nia. }\n      i. des. renames e1 NTH_EX into ment MENT.\n\n      rewrite iForall_nth in MSG_ENTRIES.\n      specialize (MSG_ENTRIES (3 + i)%nat).\n      rewrite MENT in MSG_ENTRIES.\n      rewrite Nat.add_comm in MENT. ss.\n\n      eapply sim_apply_devmsg; eauto.\n      { ss. }\n      { eapply Mem_msg_entry_unch.\n        { eauto. }\n        eapply Mem.unchanged_on_implies.\n        { eapply MEM_CH_BLK. }\n        i. des. subst.\n        clear - BLOCKS_DIFF.\n        congruence.\n      }\n      { unfold num_tasks. ss. nia. }\n\n      rename MEM_CH_BLK into MEM_CH_BLK1.\n      clear MEM_CST. i.\n\n      red_idx (idx1 - (idx_appdev + 15))%nat.\n      fw. fw.\n      { econs. eauto. }\n      fw.\n      { econs. eval_comput.\n        repr_tac.\n        replace 1 with (Z.of_nat 1) by ss.\n        rewrite <- Nat2Z.inj_add.\n        reflexivity.\n      }\n      upd_lenv.\n\n      fw.\n      red_idx (idx1 - (idx_appdev + 20))%nat.\n\n      assert (WF_ST': wf st').\n      { subst st'.\n        apply wf_apply_devmsg; eauto.\n        range_stac. }\n\n      eapply SIM_NEXT.\n      econs; eauto.\n      - eapply Mem.unchanged_on_trans; eauto.\n      - rewrite RES_EQ. s.\n        replace (3 - i)%nat with (S (2 - i))%nat by nia.\n        s. rewrite Nat2Z.id.\n        erewrite nth_error_nth.\n        2: { rewrite Nat.add_comm in MENT. ss. eauto. }\n        rewrite <- ST'. reflexivity.\n      - replace (Z.of_nat (i + 1)) with (Z.of_nat (S i)) in LENV_EQUIV by nia.\n        eauto.\n    }\n\n    clear le LENV_EQUIV.\n    clear MEM_CST.\n    i. inv LINV_END.\n\n    red_idx (idx_ret + idx_redto + 10)%nat.\n\n    fw. fw. fw.\n    { econs.\n      - eval_comput.\n        repr_tac.\n        destruct (Z.ltb_spec (Z.of_nat 3) 3).\n        { exfalso. nia. }\n        reflexivity.\n      - ss.\n    }\n\n    rewrite Int.eq_true by ss. s.\n    fw. fw. fw. fw.\n    { step_fptr_tac. }\n\n    red_idx (idx_ret + 3 + idx_redto)%nat.\n    eapply sim_reduce_timeout; eauto.\n    { ss. }\n\n    rename MEM_CH_BLK into MEM_CH_BLK_P.\n    clear MEM_CST. i.\n\n    fw. fw.\n    red_idx idx_ret.\n\n    assert (WF_ST': wf st').\n    { subst st'.\n      eapply wf_reduce_timeout. ss. }\n\n    eapply SIM_RET; eauto.\n    - rewrite <- ST' in RES_EQ.\n      rewrite RES_EQ. ss.\n    - eapply Mem.unchanged_on_trans; eauto.\n  Qed.\n\nEnd VERIF_FUNC.\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/VerifController_Updq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7122321964553656, "lm_q2_score": 0.35220179564702847, "lm_q1q2_score": 0.2508494585092069}}
{"text": "(**************************************************************************)\n(*           *                                                            *)\n(*     _     *   The Coccinelle Library / Evelyne Contejean               *)\n(*    <o>    *          CNRS-LRI-Universite Paris Sud                     *)\n(*  -/@|@\\-  *                   A3PAT Project                            *)\n(*  -@ | @-  *                                                            *)\n(*  -\\@|@/-  *      This file is distributed under the terms of the       *)\n(*    -v-    *      CeCILL-C licence                                      *)\n(*           *                                                            *)\n(**************************************************************************)\n\n\n(** * Termination of rewriting *)\n\nFrom Coq Require Import List Relations Wellfounded Arith Recdef Setoid.\nFrom CoLoR Require Import closure more_list weaved_relation term equational_theory_spec\n     dp.\n\nModule MakeModDP (E : EqTh).\n\n  Module Dp := dp.MakeDP (E).\n  Import Dp.\n  Import E.\n  Import T.\n\n(** Interpretation *)\nInductive interp_call R1 R2 : term -> term -> Prop :=\n  | Constr : forall f1 l t, ~defined R2 f1 -> In t l -> interp_call R1 R2 t (Term f1 l)\n  | Defd : forall f2 l t, defined R2 f2 -> \n            one_step (union _ R1 R2) t (Term f2 l) -> interp_call R1 R2 t (Term f2 l).\n\nDefinition Interp_dom R1 R2 t :=\n  forall p f l, subterm_at_pos t p = Some (Term f l) -> defined R2 f ->\n                   Acc (one_step (union _ R1  R2)) (Term f l).\n\nLemma interp_well_defined_1 :\n  forall R1 R2 f1 l, Interp_dom R1 R2 (Term f1 l) -> \n  forall t, In t l -> Interp_dom R1 R2 t.\nProof.\nintros R1 R2 f1 l H t t_in_l p f2 k H' Df2.\ndestruct (In_split _ _ t_in_l) as [l' [l'' H'']]; subst l.\napply (H ((length l') :: p)); trivial.\nsimpl; rewrite nth_error_at_pos.\ntrivial.\nQed.\n\nLemma interp_dom_subterm :\n  forall R1 R2 s t p, Interp_dom R1 R2 s -> subterm_at_pos s p = Some t -> Interp_dom R1 R2 t.\nProof.\nintros R1 R2 s t p Is Sub q g l Sub' Dg.\napply Is with (p ++ q); trivial.\napply subterm_in_subterm with t; trivial.\nQed.\n\nLemma acc_one_step_interp_dom :\n  forall R1 R2 t, Acc (one_step (union _ R1 R2)) t -> Interp_dom R1 R2 t.\nProof.\nintros R1 R2 t Acc_t p f l Sub _.\napply acc_subterms_3 with p t; assumption.\nQed.\n\nLemma interp_well_defined_2 :\n  forall R1 R2 f2 l, Interp_dom R1 R2 (Term f2 l) -> defined R2 f2 ->\n  forall (t : term), one_step (union _ R1 R2) t (Term f2 l) -> Interp_dom R1 R2 t.\nProof.\nintros R1 R2 f2 l H Df2 t t_R_f2l p f k Sub _.\napply acc_subterms_3 with p t; trivial.\napply Acc_inv with (Term f2 l); trivial.\napply H with (@nil nat); trivial.\nQed.\n\nLemma interp_well_defined :\n  forall R1 R2 t, Interp_dom R1 R2 t -> Acc (interp_call R1 R2) t.\nProof.\nintros R1 R2 t; pattern t; apply term_rec3; clear t.\n(* 1/2 variable case *)\nintros v H; apply Acc_intro; intros s Call_s_t; inversion Call_s_t.\n(* 1/1 compound term *)\nintros f l IHl H; apply Acc_intro.\nintros s Call_s_t; \ninversion Call_s_t as [f1 l' s' not_def_f s_in_l | f2 l' s' def_f s_R_fl]; subst.\n(* 1/2 subterm case, top function symbol not defined *)\napply IHl; trivial.\napply interp_well_defined_1 with f l; trivial.\n(* 1/1 rewriting step, top function symbol defined *)\napply Acc_inv with (Term f l); trivial.\nassert (Acc_fl := H nil f l (eq_refl _) def_f).\nrevert Acc_fl; generalize (Term f l); clear.\nintros t Acc_t; rewrite acc_with_subterm in Acc_t.\ninduction Acc_t as [t Acc_t' IH]. \napply Acc_intro.\nintros s Call_s_t; inversion Call_s_t as [f1 l s' not_def_f2 s_in_l | f2 l s' def_f2 s_R_fl]; subst.\n(* 1/2 direct_subterm *)\napply IH; right; trivial.\n(* 1/1 rewriting step *)\napply IH; left; trivial.\nQed.\n\nLemma interp_dom_subst :\n  forall R1 R2 t sigma, Interp_dom R1 R2 (apply_subst sigma t) ->\n  forall v, In v (var_list t) -> Interp_dom R1 R2 (apply_subst sigma (Var v)).\nProof.\nintros R1 R2 t sigma Itsigma v v_in_t.\ndestruct (var_in_subterm2 v t) as [p H].\napply in_impl_mem; trivial.\ngeneralize (subterm_at_pos_apply_subst_apply_subst_subterm_at_pos t p sigma).\nrewrite H.\napply interp_dom_subterm; trivial.\nQed.\n\nLemma interp_dom_R1_R2 :\n  forall R1 R2, module R1 R2 ->\n  (forall f, {defined R2 f}+{~defined R2 f}) ->\n  (forall s t, R1 s t -> forall x, In x (var_list s) -> In x (var_list t)) ->\n  (forall v t, ~ R2 t (Var v)) ->\n  forall (s t : term), Interp_dom R1 R2 s -> \n  one_step (union _ R1 R2) t s -> Interp_dom R1 R2 t.\nProof.\nintros R1 R2 module_R1_R2 def_dec R1_reg R2_var s.\npattern s; apply term_rec2; clear s.\nintro n; induction n as [ | n]; intros t Size_t.\nabsurd (1 <= 0); auto with arith.\napply le_trans with (size t); [apply size_ge_one | assumption].\nintros s It H; inversion H as [ t1 s1 H' | f lt ls H']; clear H; subst.\n(* 1/2 rewriting step at top *)\ninversion H' as [d g sigma [H1 | H2]]; clear H'; subst.\n(* 1/3 rewriting step at top by R1 *)\nintros p f k Sub Df.\ngeneralize (subterm_in_instantiated_term p d sigma Sub).\ncase_eq (subterm_at_pos d p).\n(* 1/4 d has a subterm u at position p*)\nintros [x | f' k'] Sub' K.\n(* 1/5 u is a variable x -> x in g, ok *)\nrewrite K.\nassert (x_in_g := R1_reg _ _ H1 x (var_in_subterm x _ _ Sub' (or_introl _ (eq_refl _)))).\ndestruct (var_in_subterm2 x g) as [q Sub''].\napply in_impl_mem; trivial.\nrewrite <- K; apply (It q); trivial.\ngeneralize (subterm_at_pos_apply_subst_apply_subst_subterm_at_pos g q sigma).\nrewrite Sub''; rewrite K; trivial.\n(* 1/4 u is a term headed by a symbol f defined in R2 -> impossible *)\ninjection K; clear K; intros; subst f' k.\ninversion module_R1_R2 as [M].\napply False_rect; generalize (M _ _ _ Df H1); simpl; rewrite (symb_in_subterm f _ _ Sub').\ndiscriminate.\nsimpl; rewrite eq_symb_bool_refl; apply eq_refl.\n(* 1/3 d has no subterm at position p *)\nintros Sub' [x [q [q' [K1 [x_in_d [Sub'' Sub''']]]]]].\nassert (x_in_g := R1_reg _ _ H1 x (var_in_subterm x _ _ Sub'' (or_introl _ (eq_refl _)))).\ndestruct (var_in_subterm2 x g) as [q'' Sub4].\napply in_impl_mem; trivial.\napply (It (q'' ++ q')); trivial.\napply subterm_in_subterm with (apply_subst sigma (Var x)); trivial.\ngeneralize (subterm_at_pos_apply_subst_apply_subst_subterm_at_pos g q'' sigma).\nrewrite Sub4; trivial.\n(* 1/2 rewriting at top by R2 *)\ndestruct g as [v | f l].\napply False_rect; apply (R2_var _ _ H2).\nsimpl in It; apply (interp_well_defined_2 R1 R2 _ _ It).\napply (Def _ _ _ _ H2).\napply at_top; apply (instance (union _ R1 R2) d (Term f l) sigma); right; trivial.\n(* 1/1 R1 R2 in context *)\ndestruct (def_dec f) as [Df | Cf].\napply interp_well_defined_2 with f ls; trivial.\nright; assumption.\nassert (Size_ls : forall s, In s ls -> size s <= n).\nintros s s_in_ls; apply le_S_n; apply le_trans with (size (Term f ls)); trivial.\napply size_direct_subterm; trivial.\n\nassert (Hlt : forall t, In t lt -> Interp_dom R1 R2 t).\nassert (Hls : forall s, In s ls -> Interp_dom R1 R2 s).\nintros; apply interp_well_defined_1 with f ls; trivial.\ndestruct (one_step_in_list H') as [a [b [l1 [l2 [H'' [H1 H2]]]]]]; subst ls lt.\nintros t t_in_lt; destruct (in_app_or _ _ _ t_in_lt) as [t_in_l1 | [t_eq_b | t_in_l2]].\napply Hls; apply in_or_app; left; assumption.\nsubst t; apply IHn with a; trivial.\napply Size_ls; apply in_or_app; right; left; apply eq_refl.\napply interp_well_defined_1 with f (l1 ++ a :: l2); trivial.\napply in_or_app; right; left; apply eq_refl.\napply Hls; apply in_or_app; do 2 right; assumption.\n\nintros [ | i p]; intros g l H Dg; simpl in H.\ninjection H; intros; subst; absurd (defined R2 g); trivial.\nassert (H'' := nth_error_ok_in i lt).\ndestruct (nth_error lt i) as [ ti | ].\ngeneralize (H'' _ (eq_refl _)); clear H'';\nintros [l1 [l2 [L1 H'']]].\nassert (ti_in_lt : In ti lt).\nsubst; apply in_or_app; right; left; trivial.\napply (Hlt _ ti_in_lt p); trivial.\ndiscriminate.\n\nQed.\n\nLemma interp_dom_R1 :\n forall R1 R2, module R1 R2 ->\n  (forall f, {defined R2 f}+{~defined R2 f}) ->\n  (forall s t, R1 s t -> forall x, In x (var_list s) -> In x (var_list t)) ->\n  (forall v t, ~ R2 t (Var v)) ->\n  forall (s t : term), Interp_dom R1 R2 s -> \n  one_step R1 t s -> Interp_dom R1 R2 t.\nProof.\nintros R1 R2 module_R1_R2 def_dec R1_reg R2_var; \nintros s t Is H; apply (interp_dom_R1_R2 R1 R2 module_R1_R2 def_dec R1_reg R2_var s); trivial.\nrewrite split_rel; left; trivial.\nQed.\n\nLemma interp_dom_R2 :\n forall R1 R2, module R1 R2 ->\n  (forall f, {defined R2 f}+{~defined R2 f}) ->\n  (forall s t, R1 s t -> forall x, In x (var_list s) -> In x (var_list t)) ->\n  (forall v t, ~ R2 t (Var v)) ->\n  forall (s t : term), Interp_dom R1 R2 s -> \n  one_step R2 t s -> Interp_dom R1 R2 t.\nProof.\nintros R1 R2 module_R1_R2 def_dec R1_reg R2_var; \nintros s t Is H; apply (interp_dom_R1_R2 R1 R2 module_R1_R2 def_dec R1_reg R2_var s); trivial.\nrewrite split_rel; right; trivial.\nQed.\n\nLemma interp_dom_R1_R2_rwr :\n forall R1 R2, module R1 R2 ->\n  (forall f, {defined R2 f}+{~defined R2 f}) ->\n  (forall s t, R1 s t -> forall x, In x (var_list s) -> In x (var_list t)) ->\n  (forall v t, ~ R2 t (Var v)) ->\n  forall (s t : term), Interp_dom R1 R2 s -> \n  rwr (union _ R1 R2) t s -> Interp_dom R1 R2 t.\nProof.\nintros R1 R2 module_R1_R2 def_dec R1_reg R2_var; \nintros s t Is H; induction H.\napply interp_dom_R1_R2 with y; trivial.\napply interp_dom_R1_R2 with y; trivial.\napply IHtrans_clos; trivial.\nQed.\n\nInductive Pi pi (v1 v2 : variable) : relation term :=\n  | Pi1 : Pi pi v1 v2 (Var v1) (Term pi (Var v1 :: Var v2 :: nil))\n  | Pi2 : Pi pi v1 v2 (Var v2) (Term pi (Var v1 :: Var v2 :: nil)).\n\nLemma pi_subterm :\n  forall pi v1 v2 s t, axiom (Pi pi v1 v2) t s -> direct_subterm t s.\nProof.\nintros pi v1 v2 s t H; inversion H as [t2' s' sigma H']; clear H; subst.\ninversion H' as [pi' H1 | pi' H2]; subst; simpl.\nleft; trivial.\nright; left; trivial.\nQed.\n\nDefinition is_primary_pi pi R := \n   forall s t, R s t -> (forall f, ((symb_in_term f s = true -> f <> pi) /\\\n                                             (symb_in_term f t = true -> f <> pi))).\n\nLemma acc_subterms_pi :\n  forall pi v1 v2 R, (forall x t, ~ (R t (Var x))) -> is_primary_pi pi R ->\n  forall l, (forall t, In t l -> Acc (one_step (union _ R (Pi pi v1 v2))) t) -> \n                   Acc (one_step (union _ R (Pi pi v1 v2))) (Term pi l).\nProof.\nintros pi x1 x2 R R_var P l Hl;\nassert (Acc_l : Acc (one_step_list (one_step (union _ R (Pi pi x1 x2)))) l).\nrewrite <- acc_one_step_list; trivial.\ngeneralize Hl; clear Hl; induction Acc_l as [l Acc_l IH].\nintros Acc_l'; apply Acc_intro. \nintros t H; inversion H; clear H; subst.\ninversion H0; clear H0; subst.\ndestruct t2 as [v2 | f2 l2].\nabsurd ((union _ R (Pi pi x1 x2)) t1 (Var v2)); trivial.\nintros [H' | HPi].\napply (R_var _ _ H').\ninversion HPi.\nsimpl in H; injection H; clear H; intros; subst.\ndestruct H2 as [H2 | Hpi].\ndestruct (P t1 (Term pi l2) H2 pi) as [_ F]; simpl in F.\napply False_rect; apply F.\ngeneralize (F.Symb.eq_bool_ok pi pi); case (F.Symb.eq_bool pi pi).\ntrivial.\nintro pi_diff_pi; absurd (pi =pi); trivial.\ntrivial.\nassert (t1_in_ll : In (apply_subst sigma t1) (map (apply_subst sigma) l2)).\ninversion Hpi; subst; simpl; [left | right; left]; trivial.\napply Acc_l'; trivial.\napply IH; trivial.\ngeneralize l H2 Acc_l'; clear l H2 Acc_l' Acc_l IH.\nintros l H; induction H.\nintros Acc_l t [t_eq_t1 | t_in_l].\nsubst; assert (Acc_t2 := Acc_l t2 (or_introl _ (eq_refl _))).\ninversion Acc_t2.\napply H0; trivial.\napply Acc_l; right; trivial.\nintros Acc_l2 u [u_eq_t | u_in_l1].\nsubst; apply Acc_l2; left; trivial.\napply IHone_step_list; trivial.\nintros; apply Acc_l2; right; trivial.\nQed.\n\nSection Interp_definition.\nVariable V0 : variable.\nVariable V1 : variable.\nVariable V0_diff_V1 : V0 <> V1.\nVariable pi : symbol.\nVariable bot : symbol.\nVariable R1 : relation term.\nVariable R2 : relation term.\nVariable R1_reg : forall s t, R1 s t -> forall x, In x (var_list s) -> In x (var_list t) .\nVariable R2_reg : forall s t, R2 s t -> forall x, In x (var_list s) -> In x (var_list t) .\nVariable R1_var : forall v t, ~ R1 t (Var v).\nVariable R2_var : forall v t, ~ R2 t (Var v).\nVariable P2 : is_primary_pi pi R2.\nVariable module_R1_R2 : module R1 R2.\nVariable def_dec : forall f, {defined R2 f}+{~defined R2 f}.\nVariable R1_red : term -> list term.\nVariable R2_red : term -> list term.\nVariable FB1 : forall t s, one_step R1 s t <-> In s (R1_red t).\nVariable FB2 : forall t s, one_step R2 s t <-> In s (R2_red t).\n\nDefinition R1_R2_red t := R1_red t ++ R2_red t.\n\nLemma FB12 : forall s t, one_step (union _ R1 R2) s t <-> In s (R1_R2_red t).\nProof.\nintros s t; split.\nintro s_R_t; rewrite split_rel in s_R_t; unfold R1_R2_red;\ndestruct s_R_t as [s_R1_t | s_R2_t]; apply in_or_app.\nleft; rewrite <- FB1; trivial.\nright; rewrite <- FB2; trivial.\n\nintro s_in_l; unfold R1_R2_red in s_in_l; destruct (in_app_or _ _ _ s_in_l) as [K1 | K2].\nrewrite split_rel; left; rewrite FB1; trivial.\nrewrite split_rel; right; rewrite FB2; trivial.\nQed.\n\nFixpoint Comb (l : list term) : term :=\n  match l with\n  | nil => Term bot nil\n  | t :: l => Term pi (t :: (Comb l) :: nil)\n  end.\n\nInductive Interp : term -> term -> Prop :=\n  | Vcase : forall x, Interp (Var x) (Var x)\n  | Ccase : forall f l l' ll , ~defined R2 f -> \n                l = (map (fun st => fst st)) ll -> l' = (map (fun st => snd st)) ll ->\n                (forall s s', In (s,s') ll -> Interp s s') -> \n                Interp (Term f l) (Term f l')\n  | Dcase : forall f l l' ll, defined R2 f ->\n                 R1_R2_red (Term f l) = (map (fun st => fst st)) ll -> l' = (map (fun st => snd st)) ll ->\n                 (forall s s', In (s,s') ll -> Interp s s') -> \n                Interp (Term f l) (Comb l').\n\nLemma interp_unicity :\n   forall t, Interp_dom R1 R2 t -> forall s1 s2, Interp t s1 -> Interp t s2 -> s1 = s2.\nProof.\nintros t Ht;\nassert (Acc_t :=interp_well_defined R1 R2 t Ht).\ninduction Acc_t as [t Acc_t IH].\ndestruct t as [x | f l];\nintros s1 S2 H1 H2; \ninversion H1 as [ | f1 l1 l1' ll1 Cf1 Hl1 Hl1' Hll1 | f1 l1 l1' ll1 Df1 Hl1 Hl1' Hll1 ]; \ninversion H2 as [ | f2 l2 l2' ll2 Cf2 Hl2 Hl2' Hll2 | f2 l2 l2' ll2 Df2 Hl2 Hl2' Hll2 ]; subst; trivial.\napply (f_equal (fun ll => Term f (map (fun st => snd (A := term) st) ll))).\nassert (H : forall s s1 s2, In (s,s1) ll1 -> In (s,s2) ll2 -> s1 = s2).\nintros s s1 s2 ss1_in_ll1 ss2_in_ll2.\nassert (s_in_l : In s (map (fun st => fst st) ll1)).\nrewrite in_map_iff; exists (s,s1); split; trivial.\napply IH with s; trivial.\napply (Constr R1 R2 f (map (fun st => fst st) ll1) s Cf1 s_in_l).\napply (interp_well_defined_1 R1 R2 _ _ Ht _ s_in_l).\napply Hll1; trivial.\napply Hll2; trivial.\ngeneralize ll1 ll2 Hl2 H; clear ll1 ll2 Hl2 H Hll1 Hll2 Ht Acc_t IH H2 H1.\nintro ll1; induction ll1 as [ | [s s1] ll1]; intros [ | [s' s2] ll2] H' H; trivial.\ndiscriminate.\ndiscriminate.\nsimpl in H'; injection H'; clear H'; intros H' s_eq_s'; subst s'.\nrewrite (H s s1 s2); try (left; trivial).\nrewrite IHll1 with ll2; trivial.\nintros t t1 t2 tt1_in_ll1 tt2_in_ll2; apply (H t t1 t2); right; trivial.\nabsurd (defined R2 f); trivial.\nabsurd (defined R2 f); trivial.\napply (f_equal (fun ll => Comb (map (fun st => snd (A := term) st) ll))).\nassert (H : forall s s1 s2, In (s,s1) ll1 -> In (s,s2) ll2 -> s1 = s2).\nintros s s1 s2 ss1_in_ll1 ss2_in_ll2.\nassert (s_in_l : In s (map (fun st => fst st) ll1)).\nrewrite in_map_iff; exists (s,s1); split; trivial.\napply IH with s; trivial.\napply (Defd R1 R2 f l s Df1).\nrewrite <- Hl1 in s_in_l.\nrewrite FB12; trivial.\napply (interp_well_defined_2 R1 R2 f l Ht Df1 s).\nrewrite <- Hl1 in s_in_l.\nrewrite FB12; trivial.\napply Hll1; trivial.\napply Hll2; trivial.\nrewrite Hl1 in Hl2;\ngeneralize ll1 ll2 Hl2 H; clear ll1 ll2 Hl2 H Hll1 Hll2 Ht Acc_t IH H2 H1 Hl1.\nintro ll1; induction ll1 as [ | [s s1] ll1]; intros [ | [s' s2] ll2] H' H; trivial.\ndiscriminate.\ndiscriminate.\nsimpl in H'; injection H'; clear H'; intros H' s_eq_s'; subst s'.\nrewrite (H s s1 s2); try (left; trivial).\nrewrite IHll1 with ll2; trivial.\nintros t t1 t2 tt1_in_ll1 tt2_in_ll2; apply (H t t1 t2); right; trivial.\nQed.\n\nLemma interp_defined : forall t, Interp_dom R1 R2 t -> {s : term | Interp t s}.\nProof.\nintros t Ht;\nassert (Acc_t := interp_well_defined R1 R2 t Ht).\ninduction Acc_t as [t Acc_t IH].\ndestruct t as [x | f l].\nexists (Var x); apply Vcase.\ndestruct (def_dec f) as [Df | Cf].\nassert (interp_l : forall s, In s (R1_R2_red (Term f l)) -> {u : term | Interp s u}).\nintros s s_in_red_t; apply IH.\napply (Defd R1 R2 f l s Df).\nrewrite FB12; trivial.\napply interp_well_defined_2 with f l; trivial.\nrewrite FB12; trivial.\nassert (ll : {ll : list (term * term) | R1_R2_red (Term f l) = (map (fun st => fst st)) ll /\\\n                                                        (forall s s', In (s,s') ll -> Interp s s')}).\ngeneralize (R1_R2_red (Term f l)) interp_l.\nintro k; induction k as [ | s k].\nintros _; exists (@nil (term * term)); split; trivial; contradiction.\nintros interp_sk.\ndestruct (interp_sk s) as [u Isu].\nleft; trivial.\ndestruct IHk as [kk [Hk Pk]].\nintros; apply interp_sk; right; trivial.\nexists ((s,u) :: kk); split.\nsimpl; rewrite Hk; trivial.\nsimpl; intros t t' [tt'_eq_su | tt'_in_kk].\ninjection tt'_eq_su; intros; subst; trivial.\napply Pk; trivial.\ndestruct ll as [ll [Hl Pl]].\nexists (Comb (map (fun st => snd st) ll)).\napply Dcase with ll; trivial.\n\nassert (interp_l : forall s, In s l -> {u : term | Interp s u}).\nintros s s_in_l; apply IH.\napply (Constr R1 R2 f l s Cf s_in_l).\napply interp_well_defined_1 with f l; trivial.\nassert (ll : {ll : list (term * term) | l = (map (fun st => fst st)) ll /\\\n                                                        (forall s s', In (s,s') ll -> Interp s s')}).\ngeneralize l interp_l.\nintro k; induction k as [ | s k].\nintros _; exists (@nil (term * term)); split; trivial; contradiction.\nintros interp_sk.\ndestruct (interp_sk s) as [u Isu].\nleft; trivial.\ndestruct IHk as [kk [Hk Pk]].\nintros; apply interp_sk; right; trivial.\nexists ((s,u) :: kk); split.\nsimpl; rewrite Hk; trivial.\nsimpl; intros t t' [tt'_eq_su | tt'_in_kk].\ninjection tt'_eq_su; intros; subst; trivial.\napply Pk; trivial.\ndestruct ll as [ll [Hl Pl]].\nexists (Term f (map (fun st => snd st) ll)).\napply Ccase with ll; trivial.\nQed.\n\nLemma project_comb :  forall t l, In t l -> rwr (Pi pi V0 V1) t (Comb l).\nProof.\nintros t l; induction l as [ | a l].\ncontradiction.\nsimpl; set (sigma := (V0,a) :: (V1, Comb l) :: nil).\nassert (H1 : a = apply_subst sigma (Var V0)).\nsimpl; rewrite eq_var_bool_refl; apply eq_refl.\nassert (H2 : Comb l = apply_subst sigma (Var V1)).\nsimpl; rewrite eq_var_bool_refl; case_eq (eq_var_bool V1 V0).\nintro V1_eq_V0; apply False_rect; apply V0_diff_V1; apply sym_eq.\ngeneralize (eq_var_bool_ok V1 V0); rewrite V1_eq_V0; intro; assumption.\nintros _; apply eq_refl.\nassert (H3 : Term pi (a :: Comb l :: nil) = apply_subst sigma (Term pi (Var V0 :: Var V1 :: nil))).\nrewrite H1, H2; apply eq_refl.\nintros [t_eq_a | t_in_l].\nsubst t; do 2 left.\nrewrite H3, H1; apply instance; left.\napply trans_clos_is_trans with (Comb l).\napply IHl; assumption.\nrewrite H3, H2; do 2 left; apply instance; right.\nQed.\n\nLemma recover_red :\n  forall f l t s' t', defined R2 f -> Interp_dom R1 R2 (Term f l) -> \n  Interp (Term f l) s' -> Interp t t' -> \n  one_step (union _ R1 R2) t (Term f l) -> rwr (Pi pi V0 V1) t' s'.\nProof.\nintros f l t s' t' Df Idfl Is It t_R_fl.\ninversion Is as [ | f' l' l'' ll Cf Hl Hl' Hll | f' l' l'' ll _ Hl Hl' Hll]; subst.\nabsurd (defined R2 f); trivial.\napply project_comb.\nrewrite in_map_iff; exists (t,t'); split.\napply eq_refl.\nassert (t_R_fl_bis := t_R_fl); rewrite FB12 in t_R_fl_bis.\nrewrite Hl in t_R_fl_bis.\nrewrite in_map_iff in t_R_fl_bis.\ndestruct t_R_fl_bis as [[u u'] [u_eq_t H]]. \nsimpl in u_eq_t; subst u.\nreplace t' with u'; trivial.\napply interp_unicity with t; trivial.\napply interp_well_defined_2 with f l; trivial.\napply Hll; trivial.\nQed.\n\nDefinition Interp_subst lv sigma sigma' :=\n  forall v, In v lv -> Interp_dom R1 R2 (apply_subst sigma (Var v)) /\\\n  Interp (apply_subst sigma (Var v)) (apply_subst sigma' (Var v)).\n\nLemma R1_at_top_aux_1 :\n forall t sigma sigma', (forall f, symb_in_term f t = true -> ~defined R2 f) -> \n                       Interp_dom R1 R2 (apply_subst sigma t) ->\n                       Interp_subst (var_list t) sigma sigma' ->\n  Interp (apply_subst sigma t) (apply_subst sigma' t).\nProof.\nintro t; pattern t; apply term_rec3; clear t.\nintros v sigma sigma' _ Ht Hsigma; apply (proj2 (Hsigma v (or_introl _ (eq_refl _)))).\nintros f l IH sigma sigma' Ct Ht Hsigma; simpl.\napply (Ccase f (map (apply_subst sigma) l)\n  (map (apply_subst sigma') l)\n  (map (fun t => (apply_subst sigma t, apply_subst sigma' t)) l)).\nsimpl; apply Ct; rewrite symb_in_term_unfold.\ngeneralize (F.Symb.eq_bool_ok f f); case (F.Symb.eq_bool f f); [intros _; trivial | intros f_diff_f; absurd (f = f); trivial].\nrewrite map_map; simpl; trivial.\nrewrite map_map; simpl; trivial.\nintros s s'; rewrite in_map_iff; intros [u [H' u_in_l]].\ninjection H'; intros; subst; clear H'.\nassert (Cu : forall f0, symb_in_term f0 u = true -> ~ defined R2 f0).\nintros g Hg; apply Ct.\nrewrite symb_in_term_unfold.\ngeneralize (F.Symb.eq_bool_ok g f); case (F.Symb.eq_bool g f); [intros g_eq_f | intros g_diff_f]; trivial.\nsimpl; destruct (In_split _ _ u_in_l) as [l' [l'' H1]]; subst l.\nrewrite symb_in_term_list_app.\ndestruct (symb_in_term_list g l'); simpl; trivial.\nrewrite Hg; simpl; trivial.\nassert (Hu : Interp_dom R1 R2 (apply_subst sigma u)).\nsimpl in Ht; apply (interp_well_defined_1 R1 R2 _ _ Ht).\nrewrite in_map_iff.\nexists u; split; trivial.\napply (IH u u_in_l sigma sigma' Cu Hu).\nintros v v_in_u; apply (Hsigma v).\nrewrite var_list_unfold.\ngeneralize l u_in_l; intro k; induction k as [ | t k].\ncontradiction.\nintros [u_eq_t | u_in_k].\nsubst; simpl; apply in_or_app; left; trivial.\nsimpl; apply in_or_app; right; apply IHk; trivial.\nQed.\n\nLemma R1_at_top_aux_2 :\n  forall t, (forall f, symb_in_term f t = true -> ~defined R2 f) -> \n  forall sigma, Interp_dom R1 R2 (apply_subst sigma t) ->\n  {sigma' : substitution | Interp_subst (var_list t) sigma sigma'}.\nProof.\nintros t Ct sigma Ht.\nassert (H : forall v, In v (var_list t) -> \n               {s' : term | Interp_dom R1 R2 (apply_subst sigma (Var v)) /\\\n                                     Interp (apply_subst sigma (Var v)) s'}).\nintros v v_in_l;\nassert (H' := interp_dom_subst R1 R2 t sigma Ht v v_in_l).\ndestruct (interp_defined _ H') as [s' Hs']; exists s'; split; trivial.\nassert (H' : forall l, (forall v, In v l -> \n           {s' : term | Interp_dom R1 R2 (apply_subst sigma (Var v)) /\\\n                                  Interp (apply_subst sigma (Var v)) s'}) ->\n                        {l' : substitution | Interp_subst l sigma l'}).\nintro l; induction l as [ | x l].\nintros _; exists (nil : substitution); \nunfold Interp_subst; intros; contradiction.\nintro H''; destruct IHl as [sigma' Hsigma'].\nintros v v_in_l; apply H''; right; trivial.\ndestruct (H'' x) as [x' [Hx' Hx'']].\nleft; trivial.\nexists ((x,x') :: sigma').\nunfold Interp_subst.\nintros v [v_eq_x | v_in_l].\nsubst v;  simpl; split; trivial.\ngeneralize (X.eq_bool_ok x x); case (X.eq_bool x x); [intros _ | intros x_diff_x; absurd (x = x)]; trivial.\ndestruct (Hsigma' v v_in_l) as [H''' H'''']; split; trivial.\nsimpl; generalize (X.eq_bool_ok v x); case (X.eq_bool v x); [intros v_eq_x | intros v_diff_x; trivial].\nsubst v; simpl in Hx'; trivial.\ndestruct (H' _ H) as [sigma' Hsigma'].\nexists sigma'; trivial.\nQed.\n\nLemma R1_at_top :\n  forall S1, inclusion _ S1 R1 -> forall l r, S1 r l -> forall sigma, \n  Interp_dom R1 R2 (apply_subst sigma l)->\n  {sigma' : substitution & {s' : term & {t' : term | \n     Interp_subst (var_list l) sigma sigma' /\\\n     Interp (apply_subst sigma l) s' /\\\n     Interp (apply_subst sigma r) t' /\\\n     axiom S1 t' s'} } }.\nProof.\ninversion module_R1_R2 as [M].\nintros S1 S1_in_R1 l r r_R1_l sigma Hl. \nassert (Cl : forall f, symb_in_term f l = true -> ~defined R2 f).\nintros f f_in_l Df; generalize (M f r l Df (S1_in_R1 _ _ r_R1_l)).\nreplace (r :: l :: nil) with ((r :: nil) ++ (l :: nil)); trivial.\nrewrite symb_in_term_list_app.\nsimpl; rewrite f_in_l.\ndestruct (symb_in_term f r); simpl; discriminate.\nassert (Cr : forall f, symb_in_term f r = true -> ~defined R2 f).\nintros f f_in_r Df; generalize (M f r l Df (S1_in_R1 _ _ r_R1_l)).\nreplace (r :: l :: nil) with ((r :: nil) ++ (l :: nil)); trivial.\nrewrite symb_in_term_list_app; simpl.\nrewrite f_in_r; simpl; discriminate.\n\ndestruct (R1_at_top_aux_2 l Cl sigma Hl) as [sigma' Hsigma].\nexists sigma'.\ndestruct (interp_defined _ Hl) as [s' Hs']; exists s'.\nassert (Hsigma' : Interp_subst (var_list r) sigma sigma').\nintros v v_in_r; apply (Hsigma v).\napply R1_reg with r; trivial; apply S1_in_R1; trivial.\nassert (Hr : Interp_dom R1 R2 (apply_subst sigma r)).\nrefine (interp_dom_R1 R1 R2 _ _ _ _ _ _ Hl _); trivial.\napply at_top; apply instance; apply S1_in_R1; trivial.\ndestruct (interp_defined _ Hr) as [t' Ht']; exists t'.\nsplit; trivial.\nsplit; trivial.\nsplit; trivial.\nassert (Hs'' := R1_at_top_aux_1 l sigma sigma' Cl Hl Hsigma).\nrewrite (interp_unicity _ Hl _ _ Hs' Hs'').\nassert (Ht'' := R1_at_top_aux_1 r sigma sigma' Cr Hr Hsigma').\nrewrite (interp_unicity _ Hr _ _ Ht' Ht'').\napply instance; trivial.\nQed.\n\nLemma R1_at_top_dp :\n  forall S1, inclusion _ S1 R1 -> forall l t r p, S1 t l ->  subterm_at_pos t p = Some r ->\n  forall sigma, \n  Interp_dom R1 R2 (apply_subst sigma l)->\n  {sigma' : substitution | \n      Interp_subst (var_list l) sigma sigma' /\\\n      Interp_dom R1 R2 (apply_subst sigma r) /\\\n      Interp (apply_subst sigma l) (apply_subst sigma' l) /\\\n      Interp (apply_subst sigma r) (apply_subst sigma' r) }.\nProof.\ninversion module_R1_R2 as [M].\nintros S1 S1_in_R1 l t r p t_R1_l t_p_eq_r sigma Hl. \n\nassert (Cl : forall f, symb_in_term f l = true -> ~defined R2 f).\nintros f f_in_l Df; generalize (M f t l Df (S1_in_R1 _ _ t_R1_l)).\nreplace (t :: l :: nil) with ((t :: nil) ++ (l :: nil)); trivial.\nrewrite symb_in_term_list_app.\nsimpl; rewrite f_in_l.\ndestruct (symb_in_term f t); simpl; discriminate.\n\nassert (Ct : forall f, symb_in_term f t = true -> ~defined R2 f).\nintros f f_in_t Df; generalize (M f t l Df (S1_in_R1 _ _ t_R1_l)).\nreplace (t :: l :: nil) with ((t :: nil) ++ (l :: nil)); trivial.\nrewrite symb_in_term_list_app; simpl.\nrewrite f_in_t; simpl; discriminate.\n\nassert (Cr : forall f, symb_in_term f r = true -> ~defined R2 f).\nintros f f_in_r; apply Ct; apply symb_in_subterm with r p; trivial.\n\ndestruct l as [v | f l].\nabsurd (R1 t (Var v)).\napply R1_var.\napply S1_in_R1; trivial.\nassert (Cf : ~defined R2 f).\napply Cl; rewrite symb_in_term_unfold.\nsimpl; generalize (F.Symb.eq_bool_ok f f); case (F.Symb.eq_bool f f); [intros _ | intros f_diff_f; absurd (f = f)]; trivial.\nassert (H' := R1_at_top _ S1_in_R1 _ _ t_R1_l sigma).\ndestruct (R1_at_top_aux_2 (Term f l) Cl sigma Hl) as [sigma' Hsigma].\nexists sigma'.\n\nassert (Hsigma' : Interp_subst (var_list t) sigma sigma').\nintros v v_in_t; apply (Hsigma v); \napply R1_reg with t; trivial; apply S1_in_R1; trivial.\nassert (Hsigma'' : Interp_subst (var_list r) sigma sigma').\nintros v v_in_r; apply (Hsigma' v).\napply var_in_subterm with r p; trivial.\n\nassert (Ht : Interp_dom R1 R2 (apply_subst sigma t)).\nrefine (interp_dom_R1 _ _ _ _ _ _ _ _ Hl _); trivial.\napply at_top; apply instance; apply S1_in_R1; trivial.\nassert (Hr : Interp_dom R1 R2 (apply_subst sigma r)).\ngeneralize t r t_p_eq_r Ht; clear t r t_p_eq_r Ht t_R1_l Ct Cr H' Hsigma' Hsigma''.\ninduction p as [ | i p]; intros t r t_p_eq_r Ht.\nsimpl in t_p_eq_r; injection t_p_eq_r; intro; subst; trivial.\nsimpl in t_p_eq_r; destruct t as [ | g ll].\ndiscriminate.\nassert (H' := nth_error_ok_in i ll).\ndestruct (nth_error ll i) as [ti | ].\ndestruct (H' _ (eq_refl _)) as [l1 [l2 [L H'']]]; subst ll.\napply (IHp ti r); trivial.\nsimpl in Ht; apply (interp_well_defined_1 R1 R2 _ _ Ht).\nrewrite in_map_iff.\nexists  ti; split; trivial.\napply in_or_app; right; left; trivial.\ndiscriminate.\n\nsplit; trivial; split; trivial; split.\nexact (R1_at_top_aux_1 (Term f l) sigma sigma' Cl Hl Hsigma).\ndestruct r as [v | g k].\napply (proj2 (Hsigma'' v (or_introl _ (eq_refl _)))).\nexact (R1_at_top_aux_1 (Term g k) sigma sigma' Cr Hr Hsigma'').\nQed.\n\nLemma R1_case :\n   forall (s t : term), Interp_dom R1 R2 s -> one_step R1 t s ->\n   exists s', exists t', Interp s s' /\\ Interp t t' /\\ rwr (union _ R1 (Pi pi V0 V1)) t' s'.\nProof.\nassert (R1_in_R1 : inclusion _ R1 R1).\nintros t1 t2; trivial.\nintro s; pattern s; apply term_rec2; clear s.\nintro n; induction n as [ | n]; intros s Size_s t Is t_R_s.\nabsurd (1 <= 0); auto with arith; apply le_trans with (size s); trivial;\napply size_ge_one.\ninduction t_R_s as [t' s' t'_R_s' | f' lt ls lt_R_ls]; subst.\ninversion t'_R_s' as [t3 s3 sigma t3_R_s3]; subst.\ndestruct (R1_at_top R1 R1_in_R1 s3 t3 t3_R_s3 sigma Is) as [sigma' [s' [t' [_ [H1 [H2 H3]]]]]].\nexists s'; exists t'; split; trivial.\nsplit; trivial.\napply t_step.\napply one_step_incl with R1.\nintros t1 t2 H; left; trivial.\napply at_top; trivial.\ndestruct (interp_defined _ Is) as [s' Hs'].\nexists s'.\nassert (It : Interp_dom R1 R2 (Term f' lt)).\nrefine (interp_dom_R1 R1 R2 _ _ _ _ _ (Term f' lt) Is _); trivial.\napply in_context; trivial.\ndestruct (interp_defined _ It) as [t' Ht'].\nexists t'; split; trivial.\nsplit; trivial.\ninversion Hs' as [ | f l' l'' ll Cf Hl Hl' Hll | f l' l'' ll Df Hl Hl' Hll].\ninversion Ht' as [ | g k' k'' kk Cg Hk Hk' Hkk | g k' k'' kk Dg Hk Hk' Hkk].\nassert (Size_ls : forall s, In s ls -> size s <= n).\nintros s s_in_ls; apply le_S_n; apply le_trans with (size (Term f' ls)); trivial.\napply size_direct_subterm; trivial.\nassert (Hls : forall s, In s ls -> Interp_dom R1 R2 s).\nintros; apply interp_well_defined_1 with f' ls; trivial.\nassert (Hlt : forall t, In t lt -> Interp_dom R1 R2 t).\nintros; apply interp_well_defined_1 with f' lt; trivial.\napply general_context.\nsubst f g l'' l' s' k'' k' t'.\ngeneralize ll Hl Hll kk Hk Hkk ;\nclear Size_s Is Hs' It Ht' ll Hl Hll kk Hk Hkk.\n\ninduction lt_R_ls as [t s l t_R1_s | s lt ls lt_R1_ls]; subst;\nintros ll Hl Hll kk Hk Hkk.\ndestruct ll as [ | [s' s''] ll].\ndiscriminate.\nsimpl in Hl; injection Hl; clear Hl; intros; subst.\ndestruct kk as [ | [t' t''] kk].\ndiscriminate.\nsimpl in Hk; injection Hk; clear Hk; intros; subst.\nsimpl; replace (map (fun st : term * term => snd st) kk) with\n            (map (fun st : term * term => snd st) ll).\nassert (t''_R_s'' : rwr (union term R1 (Pi pi V0 V1)) t'' s'').\nassert (Size_s' : size s' <= n).\napply Size_ls; left; trivial.\nassert (Is' : Interp_dom R1 R2 s').\napply Hls; left; trivial.\ndestruct (IHn s' Size_s' t') as [u [v [Hu [Hv H1]]]]; trivial.\nrewrite (interp_unicity s' Is' s'' u); trivial.\nassert (It' : Interp_dom R1 R2 t').\napply Hlt; left; trivial.\nrewrite (interp_unicity t' It' t'' v); trivial.\napply Hkk; left; trivial.\napply Hll; left; trivial.\nrevert t''_R_s''; clear; intro H; induction H as [t1 t2 H | t1 t2 t3 H1 H2].\ndo 2 left; assumption.\nright with (t2 :: map (fun st : term * term => snd st) ll); trivial.\nleft; assumption.\nassert (Hkl : forall u u' u'', In (u,u') ll -> In (u,u'') kk -> u' = u'').\nintros u u' u'' uu'_in_ll uu''_in_kk;\nrefine (interp_unicity u _ u' u'' _ _).\napply Hlt; trivial.\nright; rewrite in_map_iff; exists (u,u'); split; trivial.\napply Hll; right; trivial.\napply Hkk; right; trivial.\ngeneralize ll kk H Hkl; clear H Hkl;\nintro l1; induction l1 as [ | [u u'] l1]; intros [ | [v v'] l2] H Hkl.\ntrivial.\ndiscriminate.\ndiscriminate.\nsimpl in H; injection H; clear H; intros H u_eq_v; subst v.\nsimpl; rewrite (IHl1 l2); trivial.\nrewrite (Hkl u u' v'); trivial; left; trivial.\nintros w w' w'' H1 H2; apply (Hkl w); right; trivial.\n\ndestruct ll as [ | [s' s''] ll].\ndiscriminate.\nsimpl in Hl; injection Hl; clear Hl; intros; subst.\ndestruct kk as [ | [t' t''] kk].\ndiscriminate.\nsimpl in Hk; injection Hk; clear Hk; intros; subst.\nsimpl.\nassert (t''_eq_s'' : t'' = s'').\nrefine (interp_unicity t' _ t'' s'' _ _).\napply Hlt; left; trivial.\napply Hkk; left; trivial.\napply Hll; left; trivial.\nassert (H : rwr_list (one_step (union term R1 (Pi pi V0 V1)))\n                                     (map (fun st : term * term => snd st) kk)\n                                     (map (fun st : term * term => snd st) ll)).\napply IHlt_R1_ls; trivial.\nintros; apply Size_ls; right; trivial.\nintros; apply Hls; right; trivial.\nintros; apply Hlt; right; trivial.\nintros; apply Hll; right; trivial.\nintros; apply Hkk; right; trivial.\nsubst t''; revert H; clear; intro H; induction H as [l1 l2 H | l1 l2 l3 H1 H2].\nleft; right; assumption.\nright with (s'' :: l2); trivial.\nright; assumption.\nabsurd (defined R2 f'); trivial.\nsubst.\nsimpl in Is; apply rwr_incl with (Pi pi V0 V1).\nintros t1 t2; right; trivial.\nrefine (recover_red f' _ _ _ _ _ Is Hs' Ht' _); trivial.\napply one_step_incl with R1.\nintros t1 t2 H; left; trivial.\napply in_context; trivial.\nQed.\n\nLemma R2_case :\n   forall (s t : term), Interp_dom R1 R2 s -> one_step R2 t s ->\n   exists s', exists t', Interp s s' /\\ Interp t t' /\\ rwr (Pi pi V0 V1) t' s'.\nProof.\nintro s; pattern s; apply term_rec2; clear s.\nintro n; induction n as [ | n]; intros s Size_s t Is t_R_s.\nabsurd (1 <= 0); auto with arith; apply le_trans with (size s); trivial;\napply size_ge_one.\ninduction t_R_s as [t' s' t'_R_s' | f' lt ls lt_R_ls]; subst.\ninversion t'_R_s' as [t3 s3 sigma t3_R_s3]; subst.\nassert (It : Interp_dom R1 R2 (apply_subst sigma t3)).\nrefine (interp_dom_R2 R1 R2 _ _ _ _ _ _ Is _); trivial.\napply at_top; trivial.\ndestruct (interp_defined _ Is) as [s' Hs'].\ndestruct (interp_defined _ It) as [t' Ht'].\nexists s'; exists t'; split; trivial.\nsplit; trivial.\ndestruct s3 as [v | f ls].\nabsurd (R2 t3 (Var v)); trivial; apply R2_var.\nsimpl in Is; refine (recover_red f _ _ _ _ _ Is Hs' Ht' _); trivial.\napply (Def _ _ _ _ t3_R_s3).\napply one_step_incl with R2.\nintros; right; trivial.\napply at_top; trivial.\ndestruct (def_dec f') as [Df' | Cf'].\ndestruct (interp_defined _ Is) as [s' Hs'].\nassert (It : Interp_dom R1 R2 (Term f' lt)).\nrefine (interp_dom_R2 R1 R2 _ _ _ _ _ _ Is _); trivial.\napply one_step_incl with R2; trivial.\napply in_context; trivial.\ndestruct (interp_defined _ It) as [t' Ht'].\nexists s'; exists t'; split; trivial.\nsplit; trivial.\nsimpl in Is; refine (recover_red f' _ _ _ _ _ Is Hs' Ht' _); trivial.\napply one_step_incl with R2.\nintros; right; trivial.\napply in_context; trivial.\nassert (It : Interp_dom R1 R2 (Term f' lt)).\nrefine (interp_dom_R2 R1 R2 _ _ _ _ _ _ Is _); trivial.\napply one_step_incl with R2; trivial.\napply in_context; trivial.\ndestruct (interp_defined _ Is) as [s' Hs'].\ndestruct (interp_defined _ It) as [t' Ht'].\nexists s'; exists t'; split; trivial.\nsplit; trivial.\ninversion Hs' as [ | f l' l'' ll Cf Hl Hl' Hll | f l' l'' ll Df Hl Hl' Hll].\ninversion Ht' as [ | g k' k'' kk Cg Hk Hk' Hkk | g k' k'' kk Dg Hk Hk' Hkk].\nassert (Size_ls : forall s, In s ls -> size s <= n).\nintros s s_in_ls; apply le_S_n; apply le_trans with (size (Term f' ls)); trivial.\napply size_direct_subterm; trivial.\nassert (Hls : forall s, In s ls -> Interp_dom R1 R2 s).\nintros; apply interp_well_defined_1 with f' ls; trivial.\nassert (Hlt : forall t, In t lt -> Interp_dom R1 R2 t).\nintros; apply interp_well_defined_1 with f' lt; trivial.\napply general_context.\nsubst f g l'' l' s' k'' k' t'.\ngeneralize ll Hl Hll kk Hk Hkk ;\nclear Size_s Is Hs' It Ht' ll Hl Hll kk Hk Hkk.\n\ninduction lt_R_ls as [t s l t_R2_s | s lt ls lt_R2_ls]; subst;\nintros ll Hl Hll kk Hk Hkk.\ndestruct ll as [ | [s' s''] ll].\ndiscriminate.\nsimpl in Hl; injection Hl; clear Hl; intros; subst.\ndestruct kk as [ | [t' t''] kk].\ndiscriminate.\nsimpl in Hk; injection Hk; clear Hk; intros; subst.\nsimpl; replace (map (fun st : term * term => snd st) kk) with\n            (map (fun st : term * term => snd st) ll).\nassert (t''_R_s'' : rwr (Pi pi V0 V1) t'' s'').\nassert (Size_s' : size s' <= n).\napply Size_ls; left; trivial.\nassert (Is' : Interp_dom R1 R2 s').\napply Hls; left; trivial.\ndestruct (IHn s' Size_s' t') as [u [v [Hu [Hv H1]]]]; trivial.\nrewrite (interp_unicity s' Is' s'' u); trivial.\nassert (It' : Interp_dom R1 R2 t').\napply Hlt; left; trivial.\nrewrite (interp_unicity t' It' t'' v); trivial.\napply Hkk; left; trivial.\napply Hll; left; trivial.\nrevert t''_R_s''; clear; intro H; induction H as [t1 t2 H | t1 t2 t3 H1 H2].\ndo 2 left; assumption.\nright with (t2 :: map (fun st : term * term => snd st) ll); trivial.\nleft; assumption.\nassert (Hkl : forall u u' u'', In (u,u') ll -> In (u,u'') kk -> u' = u'').\nintros u u' u'' uu'_in_ll uu''_in_kk;\nrefine (interp_unicity u _ u' u'' _ _).\napply Hlt; trivial.\nright; rewrite in_map_iff; exists (u,u'); split; trivial.\napply Hll; right; trivial.\napply Hkk; right; trivial.\ngeneralize ll kk H Hkl; clear H Hkl;\nintro l1; induction l1 as [ | [u u'] l1]; intros [ | [v v'] l2] H Hkl.\ntrivial.\ndiscriminate.\ndiscriminate.\nsimpl in H; injection H; clear H; intros H u_eq_v; subst v.\nsimpl; rewrite (IHl1 l2); trivial.\nrewrite (Hkl u u' v'); trivial; left; trivial.\nintros w w' w'' H1 H2; apply (Hkl w); right; trivial.\n\ndestruct ll as [ | [s' s''] ll].\ndiscriminate.\nsimpl in Hl; injection Hl; clear Hl; intros; subst.\ndestruct kk as [ | [t' t''] kk].\ndiscriminate.\nsimpl in Hk; injection Hk; clear Hk; intros; subst.\nsimpl; assert (t''_eq_s'' : t'' = s'').\nrefine (interp_unicity t' _ t'' s'' _ _).\napply Hlt; left; trivial.\napply Hkk; left; trivial.\napply Hll; left; trivial.\nsubst t''.\nassert (H : rwr_list (one_step (Pi pi V0 V1)) (map (fun st : term * term => snd st) kk)\n                            (map (fun st : term * term => snd st) ll)).\napply IHlt_R2_ls; trivial.\nintros; apply Size_ls; right; trivial.\nintros; apply Hls; right; trivial.\nintros; apply Hlt; right; trivial.\nintros; apply Hll; right; trivial.\nintros; apply Hkk; right; trivial.\nrevert H; clear; intro H; induction H as [l1 l2 H | l1 l2 l3 H1 H2].\nleft; right; assumption.\nright with (s'' :: l2); trivial.\nright; assumption.\nabsurd (defined R2 f'); trivial.\nsubst.\nsimpl in Is; refine (recover_red f' _ _ _ _ _ Is Hs' Ht' _); trivial.\napply one_step_incl with R2.\nintros; right; trivial.\napply in_context; trivial.\nQed.\n\nLemma R1_R2_case_one_step :\n   forall (s t : term), Interp_dom R1 R2 s -> \n   one_step (union _ R1 R2) t s ->\n   exists s', exists t', Interp s s' /\\ Interp t t' /\\ rwr (union _ R1 (Pi pi V0 V1)) t' s'.\nProof.\nintros s t Is H.\nrewrite split_rel in H.\ndestruct H as [H1 | H2].\napply R1_case; trivial.\ndestruct (R2_case s t Is H2) as [s' [t' [Hs' [Ht' H']]]].\nexists s'; exists t'; split; trivial.\nsplit; trivial.\napply rwr_incl with (Pi pi V0 V1); trivial.\nintros t1 t2 H''; right; trivial.\nQed.\n\nLemma R1_R2_case :\n   forall (s t : term), Interp_dom R1 R2 s -> \n   rwr (union _ R1 R2) t s ->\n   exists s', exists t', Interp s s' /\\ Interp t t' /\\ rwr (union _ R1 (Pi pi V0 V1)) t' s'.\nProof.\nintros s t Is t_R_s; induction t_R_s; subst.\napply R1_R2_case_one_step; trivial.\ndestruct (IHt_R_s Is) as [s' [t' [Hs' [Ht' t'_R_s']]]].\nassert (It2 : Interp_dom R1 R2 y).\napply interp_dom_R1_R2_rwr with z; trivial.\ndestruct (R1_R2_case_one_step y x It2 H) as [s'' [t'' [Hs'' [Ht'' t''_R_s'']]]].\nexists s'; exists t''; split; trivial.\nsplit; trivial.\napply trans_clos_is_trans with s''; trivial.\nrewrite (interp_unicity _ It2 _ _ Hs'' Ht'); trivial.\nQed.\n\nLemma technical_lemma_1 :\n  forall S1, inclusion _ S1 R1 -> \n  forall s s' t t', Interp_dom R1 R2 s -> Interp_dom R1 R2 t -> \n  Interp s s' -> Interp t t' ->\n  axiom (ddp S1) t s -> axiom (ddp S1) t' s'.\nProof.\nintros S1 S1_in_R1 _s s' _t t' Is It Hs' Ht' t_S1_s.\ninversion t_S1_s as [t s sigma K]; clear t_S1_s; subst.\ndestruct K as [K Sub].\ninversion K as [ s'' t'' p f l t''_S1_s'' H Df H1 H2]; clear K; subst.\ndestruct s as [v'' | f'' l''].\nabsurd (R1 t'' (Var v'')).\napply R1_var.\napply S1_in_R1; trivial.\nassert (H' := R1_at_top_dp _ S1_in_R1 _ _ _ _ t''_S1_s'' H sigma).\ndestruct (H' Is) as [sigma' [Isigma [_ [Hs Ht]]]]; clear H'.\nrewrite (interp_unicity _ Is _ _ Hs' Hs).\nrewrite (interp_unicity _ It _ _ Ht' Ht).\napply instance.\nsplit; [apply (Dp _ _ _ _ _ _ t''_S1_s'' H Df) | assumption].\nQed.\n\nLemma technical_lemma :\n  forall S1, inclusion _ S1 R1 -> forall s s' t t', \n  Interp_dom R1 R2 s -> Interp_dom R1 R2 t -> \n  Interp s s' -> Interp t t' ->\n  rdp_step (axiom (ddp S1)) (union _ R1 R2) t s -> \n  rdp_step (axiom (ddp S1)) (union _ R1 (Pi pi V0 V1)) t' s'.\nProof.\ninversion module_R1_R2 as [M].\nintros S1 S1_in_R1 s s' t t' Is It Hs' Ht' t_R_s.\ninversion t_R_s as [f l1 l2 t'' l2_R_l1 H]; subst; clear t_R_s.\nassert (Is2 : Interp_dom R1 R2 (Term f l2)).\nassert (t2_R_t1 : refl_trans_clos (one_step (union _ R1 R2)) (Term f l2) (Term f l1)).\ninversion l2_R_l1 as [l | l2' l1' l2_R_l1']; subst; \n  [left | right; apply general_context; assumption].\ninversion t2_R_t1 as [t12 | t2 t1 t2_R_t1']; clear t2_R_t1; subst.\nassumption.\napply interp_dom_R1_R2_rwr with (Term f l1); assumption.\ndestruct (interp_defined _ Is2) as [s'' Hs''].\ninversion Hs' as [ | f' l' l'' ll1 Cf' Hl Hl' Hll1 | f' l' l'' ll1 Df Hl Hl' Hll1]; clear Hs'; subst.\n(* 1/2 *)\ninversion Hs'' as [ | f'' k' k'' ll2 Cf'' Hk Hk' Hll2 | f'' k' k'' ll2 Df' Hk Hk' Hll2]; subst.\n(* 1/3 *)\napply (Rdp_step (axiom (ddp S1)) (union term R1 (Pi pi V0 V1)) f (map (@snd _ _) ll1) (map (@snd _ _) ll2) t'); trivial.\n(* 1/4 *)\nassert (Ill2 : forall s, In s (map (@fst _ _) ll2) -> Interp_dom R1 R2 s).\nintros; apply (interp_well_defined_1 R1 R2 _ _ Is2); trivial.\nassert (Ill1 : forall s, In s (map (@fst _ _) ll1) -> Interp_dom R1 R2 s).\nintros; apply (interp_well_defined_1 R1 R2 _ _ Is); trivial.\nclear Is H Is2 Hs''.\nrevert ll1 Ill1 Ill2 Hll1 Hll2 l2_R_l1.\ninduction ll2 as [ | [u u'] ll2].\nintros [ | [v v'] ll1] Ill1 Ill2 Hll1 Hll2 l2_R_l1.\nleft.\ngeneralize (refl_trans_clos_one_step_list_length_eq l2_R_l1); intros; discriminate.\nintros [ | [v v'] ll1]; simpl; intros Ill1 Ill2 Hll1 Hll2 l2_R_l1.\ngeneralize (refl_trans_clos_one_step_list_length_eq l2_R_l1); intros; discriminate.\nrewrite refl_trans_clos_one_step_list_head_tail; split.\nassert (u_R_v : refl_trans_clos (one_step (union term R1 R2)) u v).\napply refl_trans_clos_one_step_list_refl_trans_clos_one_step with nil (map (@fst _ _) ll2) nil (map (@fst _ _) ll1).\napply eq_refl.\nassumption.\ninversion u_R_v as [uv | uu vv u_R_v']; clear u_R_v; subst.\nassert (Iv := Ill1 v (or_introl _ (eq_refl _))).\nrewrite (interp_unicity _ Iv v' u' (Hll1 _ _ (or_introl _ (eq_refl _))) (Hll2 _ _ (or_introl _ (eq_refl _)))).\nleft.\nassert (Iv := Ill1 _ (or_introl _ (eq_refl _))).\nassert (Iu := Ill2 _ (or_introl _ (eq_refl _))).\ndestruct (R1_R2_case _ _ Iv u_R_v') as [v'' [u'' [Iv' [Iu' H]]]].\nrewrite (interp_unicity _ Iv _ _ (Hll1 _ _ (or_introl _ (eq_refl _))) Iv').\nrewrite (interp_unicity _ Iu _ _ (Hll2 _ _ (or_introl _ (eq_refl _))) Iu').\nright; assumption.\napply (IHll2 ll1 (tail_prop _ Ill1) (tail_prop _ Ill2) (fun s s' H => Hll1 _ _ (or_intror _ H)) \n                         (fun s s' H => Hll2 _ _ (or_intror _ H))).\nrewrite refl_trans_clos_one_step_list_head_tail in l2_R_l1; apply (proj2 l2_R_l1).\n(* 1/3 *)\napply (technical_lemma_1 _ S1_in_R1 _ _ _ _ Is2 It Hs'' Ht' H).\n(* 1/2 *)\nabsurd (defined R2 f); trivial.\n(* 1/1*)\nabsurd (defined R2 f); trivial.\ninversion H; clear H; subst.\ndestruct t2 as [v2 | f2 k2].\ndestruct H2 as [H2 Sub]; inversion H2; clear H2; subst.\nabsurd (R1 t2 (Var v2)).\napply R1_var.\napply S1_in_R1; trivial.\ndestruct H2 as [H2 Sub]; inversion H2; clear H2; subst.\ninjection H0; clear H0; intros; subst.\nintro D2f; generalize (M f _ _  D2f (S1_in_R1 _ _ H)). \nsimpl; destruct (symb_in_term f t2); simpl.\ndiscriminate.\nrewrite eq_symb_bool_refl; discriminate.\nQed.\n\nLemma acc_interp_acc :\n  forall S1, inclusion _ S1 R1 -> forall s s', \n  Interp_dom R1 R2 s -> Interp s s' ->\n  Acc (rdp_step (axiom (ddp S1)) (union _ R1 (Pi pi V0 V1))) s' -> Acc (rdp_step (axiom (ddp S1)) (union _ R1 R2)) s.\nProof.\nintros S1 S1_in_R1 s s' Is Hs' Acc_s';\ngeneralize s Is Hs'; clear s Is Hs';\ninduction Acc_s' as [s' Acc_s' IH].\nintros s Is Hs'; apply Acc_intro; intros t t_R_s.\nassert (It : Interp_dom R1 R2 t).\ninversion t_R_s as [f l1 l2 t'' l2_R_l1 H ]; subst; clear t_R_s.\nassert (Is2 : Interp_dom R1 R2 (Term f l2)).\ninversion l2_R_l1 as [l | k2 k1 l2_R_l1']; clear l2_R_l1; subst.\nassumption.\napply interp_dom_R1_R2_rwr with (Term f l1); trivial.\napply general_context; assumption.\ninversion H as [t'' _s'' sigma K' K1 K2]; clear H; subst.\ndestruct K' as [K' Sub];\ninversion K' as [s'' t' p f' l t''_S1_s'' H' Df H1 H2]; clear K'; subst.\nrewrite <- K2 in Is2.\ndestruct (R1_at_top_dp _ S1_in_R1 _ _ _ _ t''_S1_s'' H' _ Is2)\n               as [sigma' [_ [K _]]]; trivial.\ndestruct (interp_defined _ It) as [t' Ht'].\napply (IH t'); trivial.\napply (technical_lemma _ S1_in_R1 s s' t t'); trivial.\nQed.\n\nLemma wf_interp_acc :\n  forall S1, inclusion _ S1 R1 -> \n  well_founded (rdp_step (axiom (ddp S1)) (union _ R1 (Pi pi V0 V1))) ->\n  forall s, Interp_dom R1 R2 s ->   Acc (rdp_step (axiom (ddp S1)) (union _ R1 R2)) s.\nProof.\nintros S1 S1_in_R1 wf s Is.\ndestruct (interp_defined _ Is) as [s' Hs'].\napply acc_interp_acc with s'; trivial.\nQed.\n\nLemma acc_interp_dom :\n  forall t, Acc (one_step (union _ R1 R2)) t -> Interp_dom R1 R2 t.\nProof.\nintros t Acc_t p f l Sub _.\napply acc_subterms_3 with p t; trivial.\nQed.\n\nEnd Interp_definition.\n\n\nSection Modular_termination.\nVariable V0 : variable.\nVariable V1 : variable.\nVariable V0_diff_V1 : V0 <> V1.\nVariable pi : symbol.\nVariable bot : symbol.\nVariable R1 : relation term.\nVariable R2 : relation term.\nVariable R3 : relation term.\nVariable def_dec1 : forall f, {defined R1 f}+{~defined R1 f}.\nVariable def_dec2 : forall f, {defined R2 f}+{~defined R2 f}.\nVariable def_dec3 : forall f, {defined R3 f}+{~defined R3 f}.\nVariable R1_red : term -> list term.\nVariable R2_red : term -> list term.\nVariable R3_red : term -> list term.\nVariable FB1 : forall t s, one_step R1 s t <-> In s (R1_red t).\nVariable FB2 : forall t s, one_step R2 s t <-> In s (R2_red t).\nVariable FB3 : forall t s, one_step R3 s t <-> In s (R3_red t).\nVariable module_R1_R2 : module R1 R2.\nVariable module_R1_R3 : module R1 R3.\nVariable R1_reg : forall s t, R1 s t -> forall x, In x (var_list s) -> In x (var_list t) .\nVariable R2_reg : forall s t, R2 s t -> forall x, In x (var_list s) -> In x (var_list t) .\nVariable R3_reg : forall s t, R3 s t -> forall x, In x (var_list s) -> In x (var_list t) .\nVariable R1_var : forall v t, ~ R1 t (Var v).\nVariable R2_var : forall v t, ~ R2 t (Var v).\nVariable R3_var : forall v t, ~ R3 t (Var v).\nVariable P1 : is_primary_pi pi R1.\nVariable P2 : is_primary_pi pi R2.\nVariable P3 : is_primary_pi pi R3.\nVariable Indep2 :  forall s t f, defined R2 f -> R3 s t -> symb_in_term_list f (s :: t :: nil) = false.\nVariable Indep3 : forall s t f, defined R3 f -> R2 s t -> symb_in_term_list f (s :: t :: nil) = false.\nVariable W2 : well_founded (one_step (union _ (union _ R1 R2) (Pi pi V0 V1))).\nVariable W3 : well_founded (rdp_step (axiom (ddp R3)) (union _ (union _ R1 R3) (Pi pi V0 V1))).\n\nLemma R132_reg' : \n    forall s t, union _ (union _ R1 R3) (union _ R2 (Pi pi V0 V1)) s t -> \n    forall x, In x (var_list s) -> In x (var_list t) .\nProof.\nintros s t [[H1 | H3] | [H2 | HPi]].\napply (R1_reg _ _ H1).\napply (R3_reg _ _ H3).\napply (R2_reg _ _ H2).\ninversion HPi as [ H1 |  H2].\nintros x [x_eq_v1 | x_in_nil]; [idtac | contradiction].\nsubst; left; trivial.\nintros x [x_eq_v1 | x_in_nil]; [idtac | contradiction].\nsubst; right; left; trivial.\nQed.\n\nLemma R123_reg' : \n    forall s t, union _ (union _ R1 R2) (union _ R3 (Pi pi V0 V1)) s t -> \n    forall x, In x (var_list s) -> In x (var_list t) .\nProof.\nintros s t H; destruct H as [[H1 | H2] | [H3 | HPi]].\napply (R1_reg _ _ H1).\napply (R2_reg _ _ H2).\napply (R3_reg _ _ H3).\ninversion HPi as [H1 | H2].\nintros x [x_eq_v1 | x_in_nil]; [idtac | contradiction].\nsubst; left; trivial.\nintros x [x_eq_v1 | x_in_nil]; [idtac | contradiction].\nsubst; right; left; trivial.\nQed.\n\nLemma R12_var' : forall (v : variable) (t :term), ~ (union _ (union _ R1 R2) (Pi pi V0 V1)) t (Var v).\nProof.\nintros v u H; destruct H as [H12 | H].\ndestruct H12 as [H1 | H2].\napply (R1_var _ _ H1).\napply (R2_var _ _ H2).\ninversion H.\nQed.\n\nLemma R123_var' : forall v t, ~ (union _ (union _ R1 R2) (union _ R3 (Pi pi V0 V1))) t (Var v).\nProof.\nintros v t [[H1 | H2] | [H3 | HPi]].\napply (R1_var _ _ H1).\napply (R2_var _ _ H2).\napply (R3_var _ _ H3).\ninversion HPi.\nQed.\n\nLemma R132_var' : forall v t, ~ (union _ (union _ R1 R3) (union _ R2 (Pi pi V0 V1))) t (Var v).\nProof.\nintros v t [[H1 | H3] | [H2 | HPi]].\napply (R1_var _ _ H1).\napply (R3_var _ _ H3).\napply (R2_var _ _ H2).\ninversion HPi.\nQed.\n\nLemma Incomp12 : forall f, defined R1 f -> defined R2 f -> False.\nProof.\ninversion module_R1_R2 as [M2].\nintros f D1 D2; inversion D1 as [h' l1 u1 H1]; clear D1; subst.\nassert (H := M2 f u1 (Term f l1) D2 H1).\nsimpl in H; destruct (symb_in_term f u1).\ndiscriminate.\nrevert H; simpl;\ngeneralize (F.Symb.eq_bool_ok f f); case (F.Symb.eq_bool f f); [intros _; discriminate | intros f_diff_f; absurd (f=f); trivial].\nQed.\n\nLemma Incomp13 : forall f, defined R1 f -> defined R3 f -> False.\nProof.\ninversion module_R1_R3 as [M3].\nintros f D1 D3; inversion D1 as [h' l1 u1 H1]; clear D1; subst.\nassert (H := M3 f u1 (Term f l1) D3 H1).\nsimpl in H; destruct (symb_in_term f u1).\ndiscriminate.\nrevert H; simpl;\ngeneralize (F.Symb.eq_bool_ok f f); case (F.Symb.eq_bool f f); [intros _; discriminate | intros f_diff_f; absurd (f=f); trivial].\nQed.\n\nLemma Incomp23 : forall f, defined R2 f -> defined R3 f -> False.\nProof.\nintros f D2 D3; inversion D2 as [h' l2 u2 H2]; clear D2; subst.\nassert (H := Indep3 u2 (Term f l2) f D3 H2).\nsimpl in H; destruct (symb_in_term f u2).\ndiscriminate.\nrevert H; simpl;\ngeneralize (F.Symb.eq_bool_ok f f); case (F.Symb.eq_bool f f); [intros _; discriminate | intros f_diff_f; absurd (f=f); trivial].\nQed.\n\nLemma Incomp : forall (R : relation term), is_primary_pi pi R -> ~defined R pi.\nProof.\nintros R P D; inversion D as [f l u H]; subst f.\ndestruct (P u (Term pi l) H pi) as [_ F].\napply F; trivial.\nrevert F; simpl;\ngeneralize (F.Symb.eq_bool_ok pi pi); case (F.Symb.eq_bool pi pi); [intros _ | intros pi_diff_pi; absurd (pi = pi)]; trivial.\nQed.\n\nDefinition Incomp1' := Incomp R1 P1.\nDefinition Incomp2' := Incomp R2 P2.\nDefinition Incomp3' := Incomp R3 P3.\n\nLemma Incomp123' :\n  forall f, defined (union _ R1 R2) f -> defined (union _ R3 (Pi pi V0 V1)) f -> False.\nProof.\nintros f D12f D3f';\ninversion D12f as [f' l u [H1 | H2]]; clear D12f; subst;\ninversion D3f' as [f'' l' u' [H3 | Hpi]]; clear D3f'; subst.\napply (Incomp13 f (Def R1 f l u H1) (Def R3 f l' u' H3)).\ninversion Hpi; subst f; apply (Incomp1' (Def R1 pi l u H1)).\napply (Incomp23 f (Def R2 f l u H2) (Def R3 f l' u' H3)).\ninversion Hpi; subst f; apply (Incomp2' (Def R2 pi l u H2)).\nQed.\n\nLemma split_dp_top :\n  forall f g ls lt,\n   axiom (ddp (union _ (union _ R1 R2) (union _ R3 (Pi pi V0 V1)))) (Term g lt) (Term f ls) ->\n   ( (defined (union _ R1 R2) f /\\ defined (union _ R1 R2) g) \\/\n     (defined R3 f /\\ defined R3 g) \\/\n     (defined R3 f /\\ defined (union _ R1 R2) g)).\nProof.\ndestruct module_R1_R2 as [M2].\ndestruct module_R1_R3 as [M3].\nintros f g ls lt H.\ninversion H as [_t _s sigma K]; clear H.\ndestruct K as [K Sub'];\ninversion K as [s' t' p h l H' Sub Dh]; clear K; subst _s _t; subst.\ndestruct s' as [x' | f' ls'].\napply False_rect; apply (R123_var' _ _ H').\nsimpl in H1; injection H1; clear H1; intros; subst.\ninjection H0; clear H0; intros; subst. \ndestruct H' as [H12 | [ H3 | HPi]].\ninversion Dh as [h' l' u [K12 | [K3 | KPi]]]; clear Dh; subst.\nleft; split.\napply (Def _ _ _ _ H12).\napply (Def _ _ _ _ K12).\ndestruct H12 as [H1 | H2].\ngeneralize (M3 g _ _ (Def R3 g l' u K3) H1).\nsimpl; rewrite (symb_in_subterm g _ _ Sub).\nsimpl; intro; discriminate.\nsimpl; generalize (F.Symb.eq_bool_ok g g); case (F.Symb.eq_bool g g); [intros _ | intros g_diff_g; absurd (g=g)]; trivial.\nassert (F := Indep3 _ _ _ (Def _ _ _ _ K3) H2).\nsimpl in F; rewrite (symb_in_subterm g _ _ Sub) in F.\ndiscriminate.\nsimpl; generalize (F.Symb.eq_bool_ok g g); case (F.Symb.eq_bool g g); [intros _ | intros g_diff_g; absurd (g=g)]; trivial.\ninversion KPi; subst g l' u.\ndestruct H12 as [H1 | H2].\nassert (H := P1 _ _ H1).\ndestruct (H pi) as [F _].\nrewrite (symb_in_subterm pi _ _ Sub) in F.\nabsurd (pi=pi); trivial; apply F; trivial.\nsimpl; generalize (F.Symb.eq_bool_ok pi pi); case (F.Symb.eq_bool pi pi); [intros _ | intros pi_diff_pi; absurd (pi = pi)]; trivial.\nassert (H := P2 _ _ H2).\ndestruct (H pi) as [F _].\nrewrite (symb_in_subterm pi _ _ Sub) in F.\nabsurd (pi=pi); trivial; apply F; trivial.\nsimpl; generalize (F.Symb.eq_bool_ok pi pi); case (F.Symb.eq_bool pi pi); [intros _ | intros pi_diff_pi; absurd (pi = pi)]; trivial.\ndestruct H12 as [H1 | H2].\nassert (H := P1 _ _ H1).\ndestruct (H pi) as [F _].\nrewrite (symb_in_subterm pi _ _ Sub) in F.\nabsurd (pi=pi); trivial; apply F; trivial.\nsimpl; generalize (F.Symb.eq_bool_ok pi pi); case (F.Symb.eq_bool pi pi); [intros _ | intros pi_diff_pi; absurd (pi = pi)]; trivial.\nassert (H := P2 _ _ H2).\ndestruct (H pi) as [F _].\nrewrite (symb_in_subterm pi _ _ Sub) in F.\nabsurd (pi=pi); trivial; apply F; trivial.\nsimpl; generalize (F.Symb.eq_bool_ok pi pi); case (F.Symb.eq_bool pi pi); [intros _ | intros pi_diff_pi; absurd (pi = pi)]; trivial.\n\ninversion Dh as [h' l' u K]; clear Dh; subst.\ndestruct K as [K12 | [K3 | KPi]].\ndestruct K12 as [K1 | K2].\nright; right; split.\napply (Def _ _ _ _ H3).\napply (Def (union _ R1 R2) g l' u); left; trivial.\nassert (F := Indep2 _ _ _ (Def _ _ _ _ K2) H3).\nsimpl in F; rewrite (symb_in_subterm g _ _ Sub) in F.\ndiscriminate.\nsimpl; generalize (F.Symb.eq_bool_ok g g); case (F.Symb.eq_bool g g); [intros _ | intros g_diff_g; absurd (g=g)]; trivial.\nright; left; split.\napply (Def _ _ _ _ H3).\napply (Def _ _ _ _ K3).\n\ninversion KPi; subst g u l'.\nassert (H := P3 _ _ H3).\ndestruct (H pi) as [F _].\nrewrite (symb_in_subterm pi _ _ Sub) in F.\nabsurd (pi=pi); trivial; apply F; trivial.\nsimpl; generalize (F.Symb.eq_bool_ok pi pi); case (F.Symb.eq_bool pi pi); [intros _ | intros pi_diff_pi; absurd (pi = pi)]; trivial.\nassert (H := P3 _ _ H3).\ndestruct (H pi) as [F _].\nrewrite (symb_in_subterm pi _ _ Sub) in F.\nabsurd (pi=pi); trivial; apply F; trivial.\nsimpl; generalize (F.Symb.eq_bool_ok pi pi); case (F.Symb.eq_bool pi pi); [intros _ | intros pi_diff_pi; absurd (pi = pi)]; trivial.\n\ninversion HPi; subst; destruct p; discriminate.\nQed.\n\nLemma split_rdp_step_top :\n  forall R f g ls lt,\n   rdp_step (axiom (ddp (union _ (union _ R1 R2) (union _ R3 (Pi pi V0 V1))))) R (Term g lt) (Term f ls) ->\n   ( (defined (union _ R1 R2) f /\\ defined (union _ R1 R2) g) \\/\n     (defined R3 f /\\ defined R3 g) \\/\n     (defined R3 f /\\ defined (union _ R1 R2) g)).\nProof.\nintros R f g ls lt H; \ninversion H as [f' l1 l2 t3 H' H'']; subst.\napply (split_dp_top f g l2 lt); trivial.\nQed.\n\nLemma split_dp :\n  forall s t,\n   axiom (ddp (union _ (union _ (union _ R1 R2) R3) (Pi pi V0 V1))) s t ->\n   (axiom (ddp (union _ R1 R2)) s t \\/ \n   axiom (ddp R3) s t \\/\n   (exists t3, exists t1, exists p, exists f1, exists l1, exists sigma,\n    R3 t1 t3 /\\\n   subterm_at_pos t1 p = Some (Term f1 l1) /\\\n   defined R1 f1 /\\\n   t = apply_subst sigma t3 /\\\n   s = apply_subst sigma (Term f1 l1))).\nProof.\ninversion module_R1_R2 as [M2].\ninversion module_R1_R3 as [M3].\nintros _s _t _H; inversion _H as [s t sigma H]; clear _H; subst.\ndestruct H as [H Sub'];\ninversion H as [s' t' p f l H' Sub Df]; clear H; subst.\ndestruct H' as [H123 | HPi].\ndestruct H123 as [H12 | H3].\ninversion Df as [f' l' u K]; clear Df; subst.\ndestruct K as [K123 | KPi].\ndestruct K123 as [K12 | K3].\nleft; apply instance; split; [apply Dp with t' p |idtac]; trivial.\napply (Def _ _ _ _ K12).\ndestruct H12 as [H1 | H2].\ngeneralize (M3 f t' _ (Def R3 f l' u K3) H1).\nsimpl; rewrite (symb_in_subterm f _ _ Sub).\nsimpl; intro; discriminate.\nsimpl; rewrite eq_symb_bool_refl; apply eq_refl.\nassert (F := Indep3 _ _ _ (Def _ _ _ _ K3) H2).\nsimpl in F; destruct (symb_in_term f t).\ndestruct (symb_in_term f t'); discriminate.\nrewrite (symb_in_subterm f _ _ Sub) in F.\ndiscriminate.\nsimpl; rewrite eq_symb_bool_refl; trivial.\ninversion KPi; subst f u l'.\ndestruct H12 as [H1 | H2].\nassert (H := P1 _ _ H1).\ndestruct (H pi) as [F _].\nrewrite (symb_in_subterm pi _ _ Sub) in F.\nabsurd (pi=pi); trivial; apply F; trivial.\nsimpl; rewrite eq_symb_bool_refl; trivial.\nassert (H := P2 _ _ H2).\ndestruct (H pi) as [F _].\nrewrite (symb_in_subterm pi _ _ Sub) in F.\nabsurd (pi=pi); trivial; apply F; trivial.\nsimpl; rewrite eq_symb_bool_refl; trivial.\ndestruct H12 as [H1 | H2].\nassert (H := P1 _ _ H1).\ndestruct (H pi) as [F _].\nrewrite (symb_in_subterm pi _ _ Sub) in F.\nabsurd (pi=pi); trivial; apply F; trivial.\nsimpl; rewrite eq_symb_bool_refl; trivial.\nassert (H := P2 _ _ H2).\ndestruct (H pi) as [F _].\nrewrite (symb_in_subterm pi _ _ Sub) in F.\nabsurd (pi=pi); trivial; apply F; trivial.\nsimpl; rewrite eq_symb_bool_refl; trivial.\n\ninversion Df as [f' l' u K]; clear Df; subst.\ndestruct K as [K123 | KPi].\ndestruct K123 as [K12 | K3].\ndestruct K12 as [K1 | K2].\nright; right; trivial.\nexists t; exists t'; exists p; exists f; exists l; exists sigma; split; trivial.\nsplit; trivial.\nsplit.\napply (Def _ _ _ _ K1).\nsplit; trivial.\nassert (F := Indep2 _ _ _ (Def _ _ _ _ K2) H3).\nsimpl in F; destruct (symb_in_term f t).\ndestruct (symb_in_term f t'); discriminate.\nrewrite (symb_in_subterm f _ _ Sub) in F.\ndiscriminate.\nsimpl; rewrite eq_symb_bool_refl; trivial.\nright; left; apply instance; split; [apply Dp with t' p | idtac]; trivial.\napply (Def _ _ _ _ K3).\n\ninversion KPi; subst f u l'.\nassert (H := P3 _ _ H3).\ndestruct (H pi) as [F _].\nrewrite (symb_in_subterm pi _ _ Sub) in F.\nabsurd (pi=pi); trivial; apply F; trivial.\nsimpl; rewrite eq_symb_bool_refl; trivial.\nassert (H := P3 _ _ H3).\ndestruct (H pi) as [F _].\nrewrite (symb_in_subterm pi _ _ Sub) in F.\nabsurd (pi=pi); trivial; apply F; trivial.\nsimpl; rewrite eq_symb_bool_refl; trivial.\n\ninversion HPi; subst; destruct p; discriminate.\nQed.\n\nLemma split_rdp_step :\n  forall R s t,\n   rdp_step (axiom (ddp (union _ (union _ (union _ R1 R2) R3) (Pi pi V0 V1)))) R s t ->\n   (rdp_step (axiom (ddp (union _ R1 R2))) R s t \\/\n   rdp_step (axiom (ddp R3)) R s t \\/\n   (exists t1, exists f3, exists l2, exists p, exists f1, exists l1, exists sigma, exists l3,\n   R3 t1 (Term f3 l2) /\\ \n   subterm_at_pos t1 p = Some (Term f1 l1) /\\\n   defined R1 f1 /\\\n   (rwr_list (one_step R) (map (apply_subst sigma) l2) l3 \\/\n    map (apply_subst sigma) l2 = l3) /\\\n   t = Term f3 l3 /\\\n   s = apply_subst sigma (Term f1 l1))).\nProof.\nintros R s t H.\ndestruct H as [f l1 l2 t3 H' H''].\ndestruct (split_dp _ _ H'') as [H1 | [H2 | H2]]; clear H''.\nleft; apply Rdp_step with l2; trivial.\nright; left; apply Rdp_step with l2; trivial.\nright; right.\ndestruct H2 as [t3' [t1 [p [f1 [l2' [sigma [K3 [Sub' [Df1 [K1 K2]]]]]]]]]].\ndestruct t3' as [v3 | f3 l3].\nabsurd (R3 t1 (Var v3)); trivial; apply R3_var.\nexists t1; exists f3; exists l3; exists p; exists f1.\nexists l2'; exists sigma.\nexists l1; split; trivial.\nsplit; trivial.\nsplit; trivial.\nsimpl in K1; injection K1; clear K1; intros K1 f_eq_f3.\nsplit.\nsubst l2.\ndestruct H'; [right | left]; trivial.\nsplit; trivial.\nsubst f; trivial.\nQed.\n\nFixpoint Pi_red (t : term) : list term :=\n   match t with\n   | Var _ => nil\n   | Term f l =>\n      let Pi_red_list :=\n         (fix Pi_red_list (l : list term) {struct l} : list (list term) :=\n            match l with\n            | nil => nil\n            | t :: lt => (map (fun t' => t' :: lt) (Pi_red t)) ++\n                             (map (fun l' => t :: l') (Pi_red_list lt))\n            end) in\n    if F.Symb.eq_bool f pi\n    then \n      match l with\n              | t1 :: t2 :: nil => t1 :: t2 :: map (fun l' => Term pi l') (Pi_red_list l)\n              | _ =>map (fun l' => Term pi l') (Pi_red_list l)\n              end\n    else map (fun l' => Term f l') (Pi_red_list l)\n   end.\n\nFixpoint Pi_red_list (l : list term) {struct l} : list (list term) :=\n            match l with\n            | nil => nil\n            | t :: lt => (map (fun t' => t' :: lt) (Pi_red t)) ++\n                             (map (fun l' => t :: l') (Pi_red_list lt))\n            end.\n\nLemma FB_Pi : forall s t, one_step (Pi pi V0 V1) t s <-> In t (Pi_red s).\nProof.\nintros s; pattern s; apply term_rec3; clear s.\nintros s t; simpl; split; intro H.\ninversion H; subst.\ninversion H0; subst.\ndestruct t2 as [v2 | f2 l2].\ninversion H3.\ndiscriminate.\ncontradiction.\n\nintros f l IH t; split; intro H.\ninversion H; clear H; subst.\ninversion H0; clear H0; subst.\ndestruct t2 as [v2 | f2 l2]; inversion H2; clear H2; subst f2; subst.\nsimpl in H; injection H; clear H; intros H f2_eq_f; subst f.\nsimpl Pi_red.\nsimpl; generalize (F.Symb.eq_bool_ok pi pi); case (F.Symb.eq_bool pi pi); [intros _; left | intros pi_diff_pi; absurd (pi = pi)]; trivial.\nsimpl in H; injection H; clear H; intros H f2_eq_f; subst f.\nsimpl Pi_red.\nsimpl; generalize (F.Symb.eq_bool_ok pi pi); case (F.Symb.eq_bool pi pi); [intros _; right; left | intros pi_diff_pi; absurd (pi = pi)]; trivial.\n\nassert (H' : In l1 (Pi_red_list l)).\ninduction H2; simpl.\napply in_or_app; left.\nrewrite in_map_iff.\nexists t1; split; trivial.\nrewrite <- IH; trivial; left; trivial.\napply in_or_app; right.\nrewrite in_map_iff; exists l1; split; trivial.\napply IHone_step_list; trivial.\nintros; apply IH; right; trivial.\nsimpl; generalize (F.Symb.eq_bool_ok f pi); case (F.Symb.eq_bool f pi); [intros f_eq_pi | intros f_diff_pi].\nsubst f; destruct l as [ | t1 [ | t2 [ | t3 l]]].\ncontradiction.\nrewrite in_map_iff; exists l1; split; trivial.\nright; right; rewrite in_map_iff; exists l1; split; trivial.\nrewrite in_map_iff; exists l1; split; trivial.\nrewrite in_map_iff; exists l1; split; trivial.\nassert (H' : forall l', In l'\n      ((fix Pi_red_list (l : list term) : list (list term) :=\n          match l with\n          | nil => nil (A:=list term)\n          | t :: lt =>\n              map (fun t' : term => t' :: lt) (Pi_red t) ++\n              map (fun l' : list term => t :: l') (Pi_red_list lt)\n          end) l) -> one_step_list (one_step (Pi pi V0 V1)) l' l).\nintros l' H'.\nassert (H'' : In l' (Pi_red_list l)).\nclear IH H; induction l as [ | s l]; trivial.\ngeneralize l' H''; clear l' H H' H''; induction l as [ | s l]; intros l' H''.\ncontradiction.\nsimpl in H''; destruct (in_app_or _ _ _ H'') as [H1 | H2].\nrewrite in_map_iff in H1; destruct H1 as [t' [H1' H1]]; subst l'.\napply head_step.\nrewrite IH; trivial.\nleft; trivial.\nrewrite in_map_iff in H2; destruct H2 as [l'' [H2' H2]]; subst l'.\napply tail_step.\napply IHl; trivial.\nintros; apply IH; right; trivial.\n\n\nrevert H; simpl.\ngeneralize (F.Symb.eq_bool_ok f pi); case (F.Symb.eq_bool f pi); [intros f_eq_pi | intros f_diff_pi].\nsubst f; destruct l as [ | t1 [ | t2 [ | t3 l]]].\napply False_rect.\nintro H; rewrite in_map_iff in H; destruct H as [l' [H'' H]]; subst t.\napply in_context; apply H'; trivial.\nintros [t_eq_t1 | [t_eq_t2 | H]].\nassert (H1sigma : t1 = apply_subst \n                                        ((V0,t1) :: (V1,t2) :: nil)\n                                        (Var V0)).\nsimpl; generalize (X.eq_bool_ok V0 V0); case (X.eq_bool V0 V0); [intros _ | intros V0_diff_V0; absurd (V0 = V0)]; trivial.\nassert (H2sigma : Term pi  (t1 :: t2 :: nil) =\n                             apply_subst \n                                   ((V0,t1) :: (V1,t2) :: nil)\n                                   (Term pi (Var V0 :: Var V1 :: nil))).\nsimpl; generalize (X.eq_bool_ok V0 V0); case (X.eq_bool V0 V0); [intros _ | intros V0_diff_V0; absurd (V0 = V0)]; trivial.\ngeneralize (X.eq_bool_ok V1 V0); case (X.eq_bool V1 V0); [intros V1_eq_V0; absurd (V0 = V1); trivial; subst V0 | intros _]; trivial.\nsimpl; generalize (X.eq_bool_ok V1 V1); case (X.eq_bool V1 V1); [intros _ | intros V1_diff_V1; absurd (V1 = V1)]; trivial.\nsubst t; pattern t1 at 1.\nrewrite H1sigma.\npattern t1 at 1.\nrewrite H2sigma.\napply at_top.\napply instance.\napply Pi1.\n\nassert (H1sigma : t2 = apply_subst \n                                        ((V0,t1) :: (V1,t2) :: nil)\n                                        (Var V1)).\nsimpl; generalize (X.eq_bool_ok V1 V0); case (X.eq_bool V1 V0); [intros V1_eq_V0; absurd (V0 = V1); trivial; subst V0 | intros _]; trivial.\nsimpl; generalize (X.eq_bool_ok V1 V1); case (X.eq_bool V1 V1); [intros _ | intros V1_diff_V1; absurd (V1 = V1)]; trivial.\n\nassert (H2sigma : Term pi  (t1 :: t2 :: nil) =\n                             apply_subst \n                                   ((V0,t1) :: (V1,t2) :: nil)\n                                   (Term pi (Var V0 :: Var V1 :: nil))).\nsimpl; generalize (X.eq_bool_ok V0 V0); case (X.eq_bool V0 V0); [intros _ | intros V0_diff_V0; absurd (V0 = V0)]; trivial.\nsimpl; generalize (X.eq_bool_ok V1 V0); case (X.eq_bool V1 V0); [intros V1_eq_V0; absurd (V0 = V1); trivial; subst V0 | intros _]; trivial.\nsimpl; generalize (X.eq_bool_ok V1 V1); case (X.eq_bool V1 V1); [intros _ | intros V1_diff_V1; absurd (V1 = V1)]; trivial.\nsubst t; pattern t2 at 1.\nrewrite H1sigma.\npattern t2 at 1.\nrewrite H2sigma.\napply at_top.\napply instance.\napply Pi2.\n\nrewrite map_app in H; destruct (in_app_or _ _ _ H) as [H1 | H2]; clear H.\nrewrite in_map_iff in H1; destruct H1 as [l' [H'' H]]; subst t.\napply in_context; apply H'; apply in_or_app; left; trivial.\nsimpl in H2; rewrite <- app_nil_end in H2.\nrewrite in_map_iff in H2; destruct H2 as [l' [H'' H]]; subst t.\napply in_context; apply H'; apply in_or_app; right.\nsimpl; rewrite <- app_nil_end; trivial.\n\nintro H; rewrite in_map_iff in H; destruct H as [l' [H'' H]]; subst t.\napply in_context; apply H'; trivial.\nintro H; rewrite in_map_iff in H; destruct H as [l' [H'' H]]; subst t.\napply in_context; apply H'; trivial.\nQed.\n\nLemma def_dec3' : forall f : symbol, {defined (union _ R3 (Pi pi V0 V1)) f} + {~ defined (union _ R3 (Pi pi V0 V1)) f}.\nProof.\nintros f; destruct (def_dec3 f) as [Df | Cf].\nleft; inversion Df as [f' l s H]; subst.\napply (Def (union _ R3 (Pi pi V0 V1)) f l s); left; trivial.\ngeneralize (F.Symb.eq_bool_ok f pi); case (F.Symb.eq_bool f pi); [intros f_eq_pi | intros f_diff_pi].\nsubst f; left; apply (Def (union _ R3 (Pi pi V0 V1)) pi (Var V0 :: Var V1 :: nil) (Var V0)).\nright; apply Pi1.\nright; intro Df; inversion Df as [f' l s [H3 | Hpi]]; subst.\napply Cf; apply (Def R3 f l s); trivial.\ninversion Hpi; subst f; absurd (pi = pi); trivial.\nQed.\n\nLemma R3_var' : forall (v : variable) (t :term), ~ (union _ R3 (Pi pi V0 V1)) t (Var v).\nProof.\nintros v u [H3 | HPi].\napply (R3_var _ _ H3).\ninversion HPi.\nQed.\n\nLemma R12_var : forall (v : variable) (t :term), ~ (union _ R1 R2) t (Var v).\nProof.\nintros v u [H1 | H2].\napply (R1_var _ _ H1).\napply (R2_var _ _ H2).\nQed.\n\nLemma R12_reg : forall s t : term,\n         union term R1 R2 s t ->\n         forall x : variable, In x (var_list s) -> In x (var_list t).\nProof.\nintros s t [H1 | H2] x x_in_s.\napply R1_reg with s; trivial.\napply R2_reg with s; trivial.\nQed.\n\nLemma module123' : module (union term R1 R2) (union term R3 (Pi pi V0 V1)).\nProof.\ninversion module_R1_R2 as [M2].\ninversion module_R1_R3 as [M3].\napply Mod.\nintros f s t Df [H1 | H2].\ninversion Df as [f' l u [H3 | HPi]]; subst.\napply M3; trivial; apply (Def R3 f l u); trivial.\ninversion HPi; subst f; subst.\ndestruct (P1 s t H1 pi) as [Hs Ht].\nsimpl; destruct (symb_in_term pi s).\nabsurd (pi = pi); trivial; apply Hs; trivial.\ndestruct (symb_in_term pi t).\nabsurd (pi = pi); trivial; apply Ht; trivial.\ntrivial.\ndestruct (P1 s t H1 pi) as [Hs Ht].\nsimpl; destruct (symb_in_term pi s).\nabsurd (pi = pi); trivial; apply Hs; trivial.\ndestruct (symb_in_term pi t).\nabsurd (pi = pi); trivial; apply Ht; trivial.\ntrivial.\ninversion Df as [f' l u [H3 | HPi]]; subst.\napply Indep3; trivial; apply (Def R3 f l u); trivial.\ninversion HPi; subst f; subst.\ndestruct (P2 s t H2 pi) as [Hs Ht].\nsimpl; destruct (symb_in_term pi s).\nabsurd (pi = pi); trivial; apply Hs; trivial.\ndestruct (symb_in_term pi t).\nabsurd (pi = pi); trivial; apply Ht; trivial.\ntrivial.\ndestruct (P2 s t H2 pi) as [Hs Ht].\nsimpl; destruct (symb_in_term pi s).\nabsurd (pi = pi); trivial; apply Hs; trivial.\ndestruct (symb_in_term pi t).\nabsurd (pi = pi); trivial; apply Ht; trivial.\ntrivial.\nQed.\n\nLemma W12' : well_founded (rdp_step (axiom (ddp (union _ R1 R2))) (union _ (union _ R1 R2) (Pi pi V0 V1))).\nProof.\nassert (W2' := dp_necessary _ R12_var' W2).\nrefine (wf_incl _ _ _ _ W2').\nclear; intros s t H; inversion H; clear H; subst.\napply Rdp_step with l2; trivial.\ninversion H1; clear H1; subst.\napply instance.\napply dp_incl with (union _ R1 R2).\ndo 3 intro; left; assumption.\napply ddp_is_dp; assumption.\nQed.\n\nDefinition T12 := \n     wf_interp_acc V0 V1 V0_diff_V1 pi bot \n                           (union _ R1 R2) (union _ R3 (Pi pi V0 V1)) R12_reg R12_var R3_var'\n                           module123' def_dec3' _ _\n                           (fun s t => FB12 _ _ _ _ FB1 FB2 t s) \n                           (fun s t => FB12 _ _ _ _ FB3 FB_Pi t s)\n                           (union _ R1 R2) (fun s t H => H) W12'.\n\nLemma def_dec2' : \n   forall f : symbol, {defined (union _ R2 (Pi pi V0 V1)) f} + {~ defined (union _ R2 (Pi pi V0 V1)) f}.\nProof.\nintros f; destruct (def_dec2 f) as [Df | Cf].\nleft; inversion Df as [f' l s H]; subst.\napply (Def (union _ R2 (Pi pi V0 V1)) f l s); left; trivial.\ngeneralize (F.Symb.eq_bool_ok f pi); case (F.Symb.eq_bool f pi); [intros f_eq_pi | intros f_diff_pi].\nsubst f; left; apply (Def (union _ R2 (Pi pi V0 V1)) pi (Var V0 :: Var V1 :: nil) (Var V0)).\nright; apply Pi1.\nright; intro Df; inversion Df as [f' l s [H2 | Hpi]]; subst.\napply Cf; apply (Def R2 f l s); trivial.\ninversion Hpi; subst f; absurd (pi = pi); trivial.\nQed.\n\nLemma R2_var' : forall (v : variable) (t :term), ~ (union _ R2 (Pi pi V0 V1)) t (Var v).\nProof.\nintros v u [H2 | HPi].\napply (R2_var _ _ H2).\ninversion HPi.\nQed.\n\nLemma R13_var : forall (v : variable) (t :term), ~ (union _ R1 R3) t (Var v).\nProof.\nintros v u [H1 | H3].\napply (R1_var _ _ H1).\napply (R3_var _ _ H3).\nQed.\n\nLemma R13_reg : forall s t : term,\n         union term R1 R3 s t ->\n         forall x : variable, In x (var_list s) -> In x (var_list t).\nProof.\nintros s t [H1 | H3] x x_in_s.\napply R1_reg with s; trivial.\napply R3_reg with s; trivial.\nQed.\n\nLemma module132' : module (union term R1 R3) (union term R2 (Pi pi V0 V1)).\nProof.\ninversion module_R1_R3 as [M3].\ninversion module_R1_R2 as [M2].\napply Mod.\nintros f s t Df [H1 | H3].\ninversion Df as [f' l u [H2 | HPi]]; subst.\napply M2; trivial; apply (Def R2 f l u); trivial.\ninversion HPi; subst f; subst.\ndestruct (P1 s t H1 pi) as [Hs Ht].\nsimpl; destruct (symb_in_term pi s).\nabsurd (pi = pi); trivial; apply Hs; trivial.\ndestruct (symb_in_term pi t).\nabsurd (pi = pi); trivial; apply Ht; trivial.\ntrivial.\ndestruct (P1 s t H1 pi) as [Hs Ht].\nsimpl; destruct (symb_in_term pi s).\nabsurd (pi = pi); trivial; apply Hs; trivial.\ndestruct (symb_in_term pi t).\nabsurd (pi = pi); trivial; apply Ht; trivial.\ntrivial.\ninversion Df as [f' l u [H2 | HPi]]; subst.\napply Indep2; trivial; apply (Def R2 f l u); trivial.\ninversion HPi; subst f; subst.\ndestruct (P3 s t H3 pi) as [Hs Ht].\nsimpl; destruct (symb_in_term pi s).\nabsurd (pi = pi); trivial; apply Hs; trivial.\ndestruct (symb_in_term pi t).\nabsurd (pi = pi); trivial; apply Ht; trivial.\ntrivial.\ndestruct (P3 s t H3 pi) as [Hs Ht].\nsimpl; destruct (symb_in_term pi s).\nabsurd (pi = pi); trivial; apply Hs; trivial.\ndestruct (symb_in_term pi t).\nabsurd (pi = pi); trivial; apply Ht; trivial.\ntrivial.\nQed.\n\nDefinition T3 := \n         wf_interp_acc V0 V1 V0_diff_V1 pi bot \n                               (union _ R1 R3) (union _ R2 (Pi pi V0 V1)) \n                               R13_reg R13_var R2_var' module132' \n                               def_dec2' _ _\n                               (fun s t => FB12 _ _ _ _  FB1 FB3 t s) \n                               (fun s t => FB12 _ _ _ _  FB2 FB_Pi t s) \n                               R3 (fun s t H => (or_intror _ H)) W3.\n\nLemma def_dec123' : \n   forall f : symbol,\n     {constructor (union term (union term R1 R2) (union _ R3 (Pi pi V0 V1))) f} +\n     {defined (union term (union term R1 R2) (union _ R3 (Pi pi V0 V1))) f}.\nProof.\nintros f; generalize (F.Symb.eq_bool_ok f pi); case (F.Symb.eq_bool f pi); [intros f_eq_pi | intros f_diff_pi].\nsubst; right.\nrefine (Def _ pi (Var V0 :: Var V1 :: nil) (Var V0) _).\ndo 2 right; apply Pi1.\ndestruct (def_dec1 f) as [D1f | C1f].\nright; inversion D1f as [f' k t H1]; subst f'.\nrefine (Def _ f k t _); do 2 left; trivial.\ndestruct (def_dec2 f) as [D2f | C2f].\nright; inversion D2f as [f' k t H1]; subst f'.\nrefine (Def _ f k t _); do 1 left; right; trivial.\ndestruct (def_dec3 f) as [D3f | C3f].\nright; inversion D3f as [f' k t H1]; subst f'.\nrefine (Def _ f k t _); right; left; trivial.\nleft; assert (Cf : forall k t, ~ (union _ (union _ R1 R2) (union _ R3 (Pi pi V0 V1))) t (Term f k)).\nintros k t  [[H1 | H2] | [H3 | HPi]].\napply C1f; apply (Def _ _ _ _ H1).\napply C2f; apply (Def _ _ _ _ H2).\napply C3f; apply (Def _ _ _ _ H3).\ninversion HPi; subst; absurd (f=f); trivial.\napply Const; trivial.\nQed.\n\nLemma def_dec132' : \n   forall f : symbol,\n     {constructor (union term (union term R1 R3) (union _ R2 (Pi pi V0 V1))) f} +\n     {defined (union term (union term R1 R3) (union _ R2 (Pi pi V0 V1))) f}.\nProof.\nintros f; generalize (F.Symb.eq_bool_ok f pi); case (F.Symb.eq_bool f pi); [intros f_eq_pi | intros f_diff_pi].\nsubst; right.\nrefine (Def _ pi (Var V0 :: Var V1 :: nil) (Var V0) _).\ndo 2 right; apply Pi1.\ndestruct (def_dec1 f) as [D1f | C1f].\nright; inversion D1f as [f' k t H1]; subst f'.\nrefine (Def _ f k t _); do 2 left; trivial.\ndestruct (def_dec2 f) as [D2f | C2f].\nright; inversion D2f as [f' k t H1]; subst f'.\nrefine (Def _ f k t _); right; left; trivial.\ndestruct (def_dec3 f) as [D3f | C3f].\nright; inversion D3f as [f' k t H1]; subst f'.\nrefine (Def _ f k t _); left; right; trivial.\nleft; assert (Cf : forall k t, ~ (union _ (union _ R1 R3) (union _ R2 (Pi pi V0 V1))) t (Term f k)).\nintros k t  [[H1 | H3] | [H2 | HPi]].\napply C1f; apply (Def _ _ _ _ H1).\napply C3f; apply (Def _ _ _ _ H3).\napply C2f; apply (Def _ _ _ _ H2).\ninversion HPi; subst; absurd (f=f); trivial.\napply Const; trivial.\nQed.\n\nLemma modular_var : forall v, \n                      Acc (ddp_step (union term (union term R1 R2) (union _ R3 (Pi pi V0 V1)))) (Var v).\nProof.\nintro x; apply Acc_intro; intros s H; inversion H; subst.\nQed.\n\nLemma def_dec12 : \n  forall f : symbol, {defined (union _ R1 R2) f} + {~ defined (union _ R1 R2) f}.\nProof.\nintro f; destruct (def_dec1 f) as [D1f | C1f].\nleft; inversion D1f as [f' k t H1]; subst f'.\nrefine (Def _ f k t _); left; trivial.\ndestruct (def_dec2 f) as [D2f | C2f].\nleft; inversion D2f as [f' k t H1]; subst f'.\nrefine (Def _ f k t _); right; trivial.\nright; intros Df; inversion Df as [f' k t [H1 | H2]]; subst f'.\napply C1f; apply (Def _ _ _ _ H1).\napply C2f; apply (Def _ _ _ _ H2).\nQed.\n\nLemma Dummy :\n   forall t, Acc (one_step (union term (union term R1 R2) (union term R3 (Pi pi V0 V1)))) t <->\n              Acc (one_step (union term (union term R1 R3) (union term R2 (Pi pi V0 V1)))) t.\nProof.\nintros t; split; apply Acc_incl;\nclear t; intros t1 t2; apply one_step_incl.\nclear t1 t2; intros t1 t2 [[H1 | H3] | [H2 | Hpi]].\nleft; left; trivial.\nright; left; trivial.\nleft; right; trivial.\nright; right; trivial.\nclear t1 t2; intros t1 t2 [[H1 | H2] | [H3 | Hpi]].\nleft; left; trivial.\nright; left; trivial.\nleft; right; trivial.\nright; right; trivial.\nQed.\n\nLemma Case12 :\n  forall f l, defined (union _ R1 R2) f ->\n             (Interp_dom (union term R1 R2) (union term R3 (Pi pi V0 V1)) (Term f l)) ->\n              Acc (ddp_step (union term (union term R1 R2) (union term R3 (Pi pi V0 V1))))\n                     (Term f l).\nProof.\nintros f l D12 It.\ninversion D12 as [f' k u H12]; subst.\nassert (Ts := T12 _ It).\nassert (D12' : match Term f l with\n                     | Var _ => False\n                     | Term g _ => defined (union _ R1 R2) g\n                     end).\ntrivial.\ngeneralize (Term f l) Ts D12' It; clear f l It Ts D12' D12 H12.\nintros t Acc_t; induction Acc_t as [[ v | f l] Acc_t IH]; intros D12f It.\ncontradiction.\n(* 1/1 goal is now \n    Acc (ddp_step (union term (union term R1 R2) (union term R3 (Pi pi)))) (Term f l) *)\napply Acc_intro; intros t H.\nassert (Simple_step : \nforall l\n(IH : forall y : term,\n     rdp_step (axiom (ddp (union term R1 R2)))\n       (union term (union term R1 R2) (union term R3 (Pi pi V0 V1))) y (Term f l) ->\n     match y with\n     | Var _ => False\n     | Term g _ => defined (union term R1 R2) g\n     end ->\n     Interp_dom (union term R1 R2) (union term R3 (Pi pi V0 V1)) y ->\n     Acc (ddp_step (union term (union term R1 R2) (union term R3 (Pi pi V0 V1)))) y)\n(It : Interp_dom (union term R1 R2) (union term R3 (Pi pi V0 V1)) (Term f l))\n(t : term)\n(H : axiom (ddp (union term (union term R1 R2) (union term R3 (Pi pi V0 V1)))) t (Term f l)),\nAcc (ddp_step (union term (union term R1 R2) (union term R3 (Pi pi V0 V1)))) t).\n(* 1/2 simple RDP step *)\nclear l Acc_t IH It t H;\nintros l IH It t Hm.\ninversion Hm as [_t s sigma _Hm K1 K2]; subst.\ndestruct _Hm as [_Hm _Sub].\ninversion _Hm as [_s t p g'' k'' t_R_s Sub Df'' H1 H']; clear _Hm; subst.\ndestruct t as [v | f' k'].\ndestruct p; discriminate.\ndestruct (split_dp_top _ _ _ _ Hm) as [D12' | [D13 | D3]]; clear Hm.\n(* 1/4 the new top symbol is also defined in R1 U R2 -> dp of type {1,2}x{1,2} *)\ndestruct D12' as [Df Dg].\nassert (t_R12_s : (union term R1 R2) (Term f' k') s).\nclear k; destruct s as [ v | g k].\nabsurd (union term (union term R1 R2) (union term R3 (Pi pi V0 V1)) (Term f' k') (Var v)); trivial.\nintros [[H1 | H2] | [H3 | Hpi]].\napply (R1_var _ _ H1).\napply (R2_var _ _ H2).\napply (R3_var _ _ H3).\ninversion Hpi.\nsimpl in K2; injection K2; clear K2; intros H' f_eq_g; subst.\ndestruct t_R_s as [H12 | H3']; trivial.\ndestruct module123' as [M].\nclear u; inversion Df as [f'' l u H12]; subst.\nassert (F := M f _ _ (Def (union _ R3 (Pi pi V0 V1)) f k (Term f' k') H3') H12).\nsimpl in F; destruct (symb_in_term f u).\ndiscriminate.\nrewrite eq_symb_bool_refl in F; discriminate.\nassert (H : rdp_step (axiom (ddp (union term R1 R2))) (union term (union term R1 R2) (union term R3 (Pi pi V0 V1))) \n                           (Term g'' (map (apply_subst sigma) k'')) \n                           (Term f l)).\napply Rdp_step with l.\nleft.\nclear k; destruct s as [ v | g k].\nabsurd ((union term R1 R2) (Term f' k') (Var v)); trivial.\nintros [H1 | H2].\napply (R1_var _ _ H1).\napply (R2_var _ _ H2).\nsimpl in K2; injection K2; clear K2; intros H' f_eq_g; subst.\nrefine (instance _ (Term g'' k'') (Term f k) sigma _).\nsplit; [apply (Dp (union _ R1 R2) (Term f k) (Term f' k') p g'' k'') | idtac]; trivial.\napply IH; trivial.\n(* 1/4 goal is now \n  Interp_dom (union term R1 R2) (union term R3 (Pi pi))  (Term g'' (map (apply_subst sigma) k'')) *)\nassert (s_not_in_F3 : forall g : symbol, symb_in_term g s = true -> ~ defined (union term R3 (Pi pi V0 V1)) g).\nintros g g_in_s D3g.\ndestruct module123' as [M].\nassert (H'' := M g _ _ D3g t_R12_s).\nchange ((symb_in_term g (Term f' k') || (symb_in_term g s || false))%bool =\n        false) in H''.\nrewrite g_in_s in H''; destruct (symb_in_term g (Term f' k')); discriminate.\ndestruct s as [v | ff ll].\nabsurd (union term R1 R2 (Term f' k') (Var v)); trivial.\napply R12_var.\n\nassert (f'k'_not_in_F3 : forall g : symbol, symb_in_term g (Term f' k') = true -> ~ defined (union term R3 (Pi pi V0 V1)) g). \nintros g g_in_s D3g.\ndestruct module123' as [M].\nassert (H'' := M g _ _ D3g t_R12_s).\npattern (Term f' k') in H''; simpl symb_in_term_list in H''; cbv beta in H''.\nsimpl symb_in_term_list in H''; fold symb_in_term_list in H''.\nsimpl in g_in_s; fold symb_in_term_list in g_in_s.\nrewrite g_in_s in H''; discriminate.\nassert (interp_dom_var : forall v, In v (var_list (Term ff ll))\n              ->  Interp_dom (union term R1 R2) (union term R3 (Pi pi V0 V1)) (apply_subst sigma (Var v))).\nintros v v_in_s'.\nrewrite <- K2 in It.\nexact (interp_dom_subst (union term R1 R2) (union term R3 (Pi pi V0 V1)) _ sigma It v v_in_s').\nintros [ | i q] h kk Sub' D3h.\nsimpl in Sub'; injection Sub'; clear Sub'; intros; subst.\napply False_rect.\ndestruct module123' as [M].\ninversion Dg as [g' kk v H1 H2]; subst.\ngeneralize (M h _ _ D3h H1); simpl.\ndestruct (symb_in_term h v).\ndiscriminate.\nrewrite eq_symb_bool_refl; discriminate.\n\ngeneralize (subterm_in_instantiated_term _ _ _ Sub').\ncase_eq (subterm_at_pos (Term g'' k'') (i :: q)).\nintros t Sub4 K.\nassert (Sub5 := subterm_in_subterm _ _ _ Sub Sub4).\ndestruct t as [v | h' ll'].\nassert (v_in_s : In v (var_list (Term ff ll))).\napply R12_reg with (Term f' k'); trivial.\napply var_in_subterm with  (Var v) (p ++ i :: q); trivial.\nleft; trivial.\napply (interp_dom_var v v_in_s nil); trivial.\nrewrite K; trivial.\nsimpl in K; injection K; clear K; intros; subst.\nabsurd (defined (union term R3 (Pi pi V0 V1)) h'); trivial.\napply f'k'_not_in_F3.\nrewrite (symb_in_subterm h' _ _ Sub5); trivial.\nsimpl; rewrite eq_symb_bool_refl; trivial.\nintros _ [v [q' [q'' [H1 [v_in_g''k'' [Sub3 Sub4]]]]]].\nassert (v_in_s : In v (var_list (Term ff ll))).\napply R12_reg with (Term f' k'); trivial.\napply var_in_subterm with  (Term g'' k'') p; trivial.\napply (interp_dom_var v v_in_s q''); trivial.\n\n(* 1/3 the old top symbol is defined in R1 U R3 -> contradiction *)\ndestruct D13 as [D3 _].\ndestruct module123' as [M].\nclear k u; inversion D12f as [g k u H12]; subst.\ninversion D3 as [g' k''' u' H3]; subst.\nassert (F := M f _ _ (Def (union _ R3 (Pi pi V0 V1)) f k''' u' (or_introl _ H3)) H12).\nsimpl in F; destruct (symb_in_term f u).\ndiscriminate.\nsimpl in F; revert F; \ngeneralize (F.Symb.eq_bool_ok f f); case (F.Symb.eq_bool f f); [intros _ | intros f_diff_f; absurd (f =f); trivial].\nintro; discriminate.\n\n(* 1/2 the old top symbol is defined in R3 -> contradiction *)\ndestruct D3 as [D3 _].\ndestruct module123' as [M].\nclear k u; inversion D12f as [g k u H12]; subst.\ninversion D3 as [g' k''' u' H3]; subst.\nassert (F := M f _ _ (Def (union _ R3 (Pi pi V0 V1)) f k''' u' (or_introl _ H3)) H12).\nsimpl in F; destruct (symb_in_term f u).\ndiscriminate.\nrewrite eq_symb_bool_refl in F; discriminate.\n\nclear k; inversion H as [g k l' s'' l_R_l' Hm]; clear H; subst.\napply (Simple_step l'); trivial.\nintros [v | g k] H D12 Iu.\ncontradiction.\napply IH; trivial.\ninversion H as [g' k' l'' s''' l'_R_l'' Hm']; clear H; subst.\napply Rdp_step with l''; trivial.\napply refl_trans_clos_is_trans with l'; trivial.\n\nintros [ | i p] g k Sub Dg.\nsimpl in Sub; injection Sub; clear Sub; intros; subst g k.\nassert False; [apply (Incomp123' f); trivial | contradiction].\ninversion l_R_l' as [l1 | l1 l1' l1_R_l1']; clear l_R_l'; subst.\napply (It (i :: p)); trivial.\nassert (It' := interp_dom_R1_R2_rwr _ _ module123' def_dec3' R12_reg R3_var'\n                        _ _ It (general_context _ f _ _ l1_R_l1')).\napply (It' (i :: p)); trivial.\nQed.\n\nLemma Case3 : \n  forall f l, defined R3 f ->\n                  ( forall t : term,\n                    In t l ->\n                       Acc (one_step (union term (union term R1 R3) (union term R2 (Pi pi V0 V1)))) t) ->\n    Acc (ddp_step (union term (union term R1 R3) (union term R2 (Pi pi V0 V1)))) (Term f l).\nProof.\nintros f l  D3 IHl.\n(* 1/1 f is defined in R3 *)\nassert (H : Interp_dom (union term R1 R3) (union term R2 (Pi pi V0 V1)) (Term f l)).\nintros [ | i p] g k Sub D2.\nsimpl in Sub; injection Sub; clear Sub; intros; subst g k.\ninversion D2 as [g k u [H2 | HPi]]; subst.\napply False_rect; apply (Incomp23 f (Def R2 f k u H2) D3).\napply False_rect; inversion HPi; subst f; apply (Incomp3' D3).\nsimpl in Sub; assert (H := nth_error_ok_in i l);\ndestruct (nth_error l i) as [ti | ]; [idtac | discriminate].\ndestruct (H _ (eq_refl _)) as [ls1 [ls2 [L H']]]; clear H; subst l.\nassert (Hti : Interp_dom (union term R1 R3) (union term R2 (Pi pi V0 V1)) ti).\napply acc_interp_dom.\napply IHl; apply in_or_app; right; left; trivial.\napply (Hti p); trivial.\n\nassert (D3' : match Term f l with\n                     | Var _ => False\n                     | Term g _ => defined R3 g\n                     end).\ntrivial.\nassert (Ts := T3 _ H).\nassert (IHl' : forall t, direct_subterm t (Term f l) ->\n                Acc (one_step (union term (union term R1 R3) (union term R2 (Pi pi V0 V1)))) t).\nsimpl; trivial.\ngeneralize (Term f l) Ts D3' IHl'; clear f l H Ts D3' IHl D3 IHl'.\nintros t Acc_t; induction Acc_t as [[ v | _f l] Acc_t IH]; intros D3 IHl.\ncontradiction.\n(* 1/1 goal is now \n    Acc (dpd_step (union term (union term R1 R3) (union term R2 (Pi pi)))) (Term _f l) *)\napply Acc_intro; intros t H.\nassert (Simple_step : \nforall l\n(IH : forall y : term,\n     rdp_step (axiom (ddp R3)) (union term (union term R1 R3) (union term R2 (Pi pi V0 V1))) y\n       (Term _f l) ->\n     match y with\n     | Var _ => False\n     | Term g _ => defined R3 g\n     end ->\n     (forall t : term,\n      direct_subterm t y ->\n      Acc (one_step (union term (union term R1 R3) (union term R2 (Pi pi V0 V1))))\n        t) ->\n     Acc (ddp_step (union term (union term R1 R3) (union term R2 (Pi pi V0 V1)))) y) \n(D3 : defined R3 _f)\n(IHl : forall t : term,\n      direct_subterm t (Term _f l) ->\n      Acc (one_step (union term (union term R1 R3) (union term R2 (Pi pi V0 V1)))) t)\n(t : term)\n(H : axiom (ddp (union term (union term R1 R3) (union term R2 (Pi pi V0 V1)))) t\n      (Term _f l)),\nAcc (ddp_step (union term (union term R1 R3) (union term R2 (Pi pi V0 V1)))) t).\n(* 1/2 simpl RDP step *)\nclear l Acc_t IH D3 IHl t H;\nintros l IH D3 IHl t _Hm.\ninversion _Hm as [_t _s sigma Hm K1 K2]; clear _Hm; subst.\ndestruct Hm as [Hm _Sub];\ninversion Hm as [s [ v | f' k'] p g'' k'' t_R_s Sub Df'' H1 H']; clear Hm; subst.\ndestruct p; discriminate.\ndestruct _s as [ v | g k].\nabsurd (union term (union term R1 R3) (union term R2 (Pi pi V0 V1)) (Term f' k') (Var v)); trivial.\napply R132_var'.\n\nassert (t_R3_s : R3 (Term f' k') (Term g k)).\nsimpl in K2; injection K2; clear K2; intros H' f_eq_g; subst g l.\ndestruct t_R_s as [[ H1 | H3] | [H2 | HPi]]; trivial.\napply False_rect; apply (Incomp13 _f (Def _ _ _ _ H1) D3).\napply False_rect; apply (Incomp23 _f (Def _ _ _ _ H2) D3).\napply False_rect; inversion HPi; subst _f; apply (Incomp3' D3).\n\n(* 1/2 R3 (Term f' k') (Term g k) *)\nassert (Hm' : axiom (ddp (union term (union term R1 R2) (union term R3 (Pi pi V0 V1))))\n                           (apply_subst sigma (Term g'' k'')) (Term _f l)).\nrewrite <- K2; apply instance.\nsplit; [idtac | trivial].\nrefine (Dp (union term (union term R1 R2) (union term R3 (Pi pi V0 V1))) _ (Term f' k')  p  g'' k'' _ _ _); trivial.\nright; left; trivial.\ninversion Df'' as [h'' l'' u'' [[H1 | H3] | [H2 | Hpi]]]; subst.\napply (Def (union term (union term R1 R2) (union term R3 (Pi pi V0 V1))) g'' l'' u''); left; left; trivial.\napply (Def (union term (union term R1 R2) (union term R3 (Pi pi V0 V1))) g'' l'' u''); right; left; trivial.\napply (Def (union term (union term R1 R2) (union term R3 (Pi pi V0 V1))) g'' l'' u''); left; right; trivial.\napply (Def (union term (union term R1 R2) (union term R3 (Pi pi V0 V1))) g'' l'' u''); right; right; trivial.\ndestruct (split_dp_top _ _ _ _ Hm') as [D12' | DD3]; clear Hm'.\n(* 1/3  symbol is also defined in R1 U R2  -> contradiction *)\ndestruct D12' as [Df Dg].\nabsurd (defined (union term R1 R2) _f); trivial.\nintros D12f; inversion D12f as [f'' k''' u [H1 | H2]]; subst.\napply (Incomp13 _f (Def R1 _f k''' u H1) D3).\napply (Incomp23 _f (Def R2 _f k''' u H2) D3).\nassert (D123 : match Term g'' k'' with\n                       | Var _ => False\n                       | Term f _ => defined R3 f \\/ defined (union _ R1 R2) f\n                       end).\ndestruct DD3 as [[_ D3'] | [_ D12]]; [left | right]; trivial.\nclear DD3.\ngeneralize (Term g'' k'') p _Sub Sub D123; clear g'' k'' p _Sub Sub Df'' D123.\nintro t; pattern t; apply term_rec2; clear t.\nintro n; induction n as [ | n]; intros t St p _Sub Sub D123.\nabsurd (1 <= 0); auto with arith; apply le_trans with (size t); trivial; apply size_ge_one.\nassert (IHk'' : forall s q, subterm_at_pos t q = Some s ->\n                      Acc (one_step (union term (union term R1 R3) (union term R2 (Pi pi V0 V1))))\n                        (apply_subst sigma s)).\nintro s; pattern s; apply term_rec2; clear s.\nintro m; induction m as [ | m]; intros s Ss q Sub'.\nabsurd (1 <= 0); auto with arith; apply le_trans with (size s); trivial; apply size_ge_one.\ndestruct s as [v | g3 k3].\nassert (v_in_s : In v (var_list (Term g k))).\napply R3_reg with (Term f' k'); trivial.\napply var_in_subterm with (Var v) (p ++ q).\napply subterm_in_subterm with t; trivial.\nleft; trivial.\ndestruct (var_in_subterm2 _ _ (in_impl_mem (@eq _) (fun a => eq_refl a) _ _ v_in_s)) as [q' Sub''].\ndestruct q' as [ | i q'].\ndiscriminate.\nassert (H'' := nth_error_ok_in i k).\nsimpl in Sub''; destruct (nth_error k i) as [si | ].\ndestruct (H'' _ (eq_refl _)) as [l1 [l2 [L1 H''']]].\napply acc_subterms_3 with q' (apply_subst sigma si).\napply IHl.\nsimpl in K2; injection K2; clear K2; intros; subst.\nsimpl; rewrite map_app; apply in_or_app; right; left; trivial.\nassert (Sub3 := subterm_at_pos_apply_subst_apply_subst_subterm_at_pos \n                               si q' sigma).\nrewrite Sub'' in Sub3; trivial.\ndiscriminate.\nassert (Hk3 : forall s, In s k3 -> \n                  Acc (one_step (union term (union term R1 R3) (union term R2 (Pi pi V0 V1))))\n                         (apply_subst sigma s)).\nintros s' s'_in_k3; \ndestruct (In_split _ _ s'_in_k3) as [k3' [k3'' H]]; subst k3.\napply IHm with (q ++ (length k3' :: nil)).\napply le_S_n.\napply le_trans with (size (Term g3 (k3' ++ s' :: k3''))); trivial.\napply size_direct_subterm; trivial.\napply subterm_in_subterm with (Term g3 (k3' ++ s' :: k3'')); trivial.\nsimpl; rewrite nth_error_at_pos; trivial.\ndestruct (subterm_at_pos_dec (Term g k)  (Term g3 k3)) as [[[ | i q'] _Sub'] | not_Sub].\napply ddp_simple_criterion_local.\napply R132_var'.\napply R132_reg'.\napply def_dec132'.\napply IH; trivial.\napply Rdp_step with l.\nleft.\nrewrite <- K2; apply instance.\nassert (H''' := Dp R3 _ _ (p ++ q) g3 k3 t_R3_s).\nsplit.\napply H'''.\napply subterm_in_subterm with t; trivial.\ninjection _Sub'; intros; subst; apply (Def R3 _ _ _ t_R3_s).\nintros i q''; intro H3; \nsimpl in _Sub'; injection _Sub'; intros; subst g3 k3;\nabsurd (size (Term g k) < size (Term g k)).\nauto with arith.\ngeneralize (size_subterm_at_pos (Term g k) i q'').\nrewrite H3; trivial.\nsimpl in _Sub'; injection _Sub'; intros; subst g3 k3;\napply (Def R3 g _ _ t_R3_s).\nsimpl; intros s s_in_k3; rewrite in_map_iff in s_in_k3; destruct s_in_k3 as [s' [H s'_in_k3]]; subst.\napply Hk3; trivial.\nsimpl; intros s s_in_k3; rewrite in_map_iff in s_in_k3; destruct s_in_k3 as [s' [H s'_in_k3]]; subst.\napply Hk3; trivial.\nsimpl in _Sub'.\ngeneralize (nth_error_ok_in i k); destruct (nth_error k i) as [ti | ]; [idtac | discriminate].\nintros H''; destruct (H'' _ (eq_refl _)) as [l1' [l2' [L H3]]]; clear H''; subst k.\napply acc_subterms_3 with q' (apply_subst sigma ti).\napply IHl.\nsimpl; injection K2; clear K2; intros; subst.\nrewrite in_map_iff; exists ti; split; trivial; apply in_or_app; right; left; trivial.\ngeneralize (subterm_at_pos_apply_subst_apply_subst_subterm_at_pos ti q' sigma).\nrewrite _Sub'; trivial.\ndestruct (def_dec132' g3) as [Cg3 | Dg3].\nsimpl; apply acc_subterms; trivial.\napply R132_var'.\nintros s s_in_k3; rewrite in_map_iff in s_in_k3; destruct s_in_k3 as [s' [H s'_in_k3]]; subst.\napply Hk3; trivial.\ndestruct q as [ | i q].\nsimpl in Sub'; injection Sub'; clear Sub'; intros; subst t.\ndestruct D123 as [Dg | Dg].\n(* 1/5  the new symbol is also defined in R3 -> dp of type {3}x{3} *)\nassert (H : rdp_step (axiom (ddp R3)) (union term (union term R1 R3) (union term R2 (Pi pi V0 V1))) \n                           (Term g3 (map (apply_subst sigma) k3)) \n                           (Term _f l)).\napply Rdp_step with l.\nleft.\nrewrite <- K2; refine (instance _ (Term g3 k3) _ sigma _).\nsimpl in K2; injection K2; clear K2; intros H' _f_eq_g; subst g l.\nsplit.\napply (Dp R3 (Term _f k) (Term f' k') p g3 k3); trivial.\nintros i p'; apply not_Sub.\napply ddp_simple_criterion_local.\napply R132_var'.\napply R132_reg'.\napply def_dec132'.\napply IH; simpl; trivial.\nintros s s_in_k3; rewrite in_map_iff in s_in_k3; destruct s_in_k3 as [s' [H'' s'_in_k3]]; subst.\napply Hk3; trivial.\nsimpl; \nintros s s_in_k3; rewrite in_map_iff in s_in_k3; destruct s_in_k3 as [s' [H'' s'_in_k3]]; subst.\napply Hk3; trivial.\n(* 1/4 the old top symbol is defined in R3, the new one in R1 U R2 -> pair of type {3}x{1} *)\napply ddp_simple_criterion_local.\napply R132_var'.\napply R132_reg'.\napply def_dec132'.\napply Acc_incl with (ddp_step (union term (union term R1 R2) (union term R3 (Pi pi V0 V1)))).\napply ddp_step_incl.\nintros t1 t2 [[H1 | H3] | [H2 | HPi]].\ndo 2 left; trivial.\nright; left; trivial.\nleft; right; trivial.\ndo 2 right; trivial.\napply (Case12 g3 (map (apply_subst sigma) k3)); trivial.\nintros [ | i r] g4 k4 Sub'' Dg4.\nsimpl in Sub''; injection Sub''; clear Sub''; intros; subst.\napply False_rect; apply (Incomp123' g4); trivial.\nsimpl in Sub''.\nassert (H'' := nth_error_map (apply_subst sigma) k3 i).\ndestruct (nth_error (map (apply_subst sigma) k3) i) as [ti | ].\nassert (H''' := nth_error_ok_in i k3).\ndestruct (nth_error k3 i) as [si | ].\ndestruct (H''' _ (eq_refl _)) as [l1 [l2 [L1 H'''']]].\nassert (si_in_lr : In si k3).\nsubst k3; apply in_or_app; right; left; trivial.\napply acc_subterms_3 with r ti; trivial.\nsubst; rewrite Dummy; apply IHm with (length l1 :: nil); trivial.\napply le_S_n.\napply le_trans with (size (Term g3 (l1 ++ si :: l2))); trivial.\napply size_direct_subterm; trivial.\nsimpl; rewrite nth_error_at_pos; trivial.\ncontradiction.\ndiscriminate.\nsimpl; \nintros s s_in_k3; rewrite in_map_iff in s_in_k3; destruct s_in_k3 as [s' [H'' s'_in_k3]]; subst.\napply Hk3; trivial.\napply ddp_simple_criterion_local.\napply R132_var'.\napply R132_reg'.\napply def_dec132'.\napply IHn with (p ++ i :: q).\napply le_S_n.\napply le_trans with (size t); trivial.\ngeneralize (size_subterm_at_pos t i q).\nrewrite Sub'; trivial.\nintros j q' Sub''; apply (not_Sub (j :: q')); trivial.\napply subterm_in_subterm with t; trivial.\ndestruct Dg3 as [g' l' u [[H1 | H3] | [H2 | Hpi]]].\nright; apply (Def (union _ R1 R2) g' l' u); left; trivial.\nleft; apply (Def  R3 g' l' u); trivial.\nright; apply (Def (union _ R1 R2) g' l' u); right; trivial.\napply False_rect; destruct (P3 _ _ t_R3_s g') as [F _]; apply F.\napply (symb_in_subterm g' _ p Sub).\napply (symb_in_subterm g' _ (i :: q) Sub').\nsimpl; generalize (F.Symb.eq_bool_ok g' g'); case (F.Symb.eq_bool g' g'); [intros _ | intros g_diff_g; absurd (g'=g')]; trivial.\ninversion Hpi; subst; trivial.\nsimpl; \nintros s s_in_k3; rewrite in_map_iff in s_in_k3; destruct s_in_k3 as [s' [H'' s'_in_k3]]; subst.\napply Hk3; trivial.\n\napply acc_one_step_acc_ddp.\napply R132_var'.\napply IHk'' with (@nil nat); trivial.\n\ninversion H as [g k l' s'' l_R_l' Hm]; clear H; subst.\napply (Simple_step l'); trivial.\nintros [v | g k] H D3' Iu.\ncontradiction.\napply IH; trivial.\ninversion H as [g' k' l'' s''' l'_R_l'' Hm']; clear H; subst.\napply Rdp_step with l''; trivial.\napply refl_trans_clos_is_trans with l'; trivial.\n\nsimpl; intros u' u'_in_l'.\nassert (H : exists u, In u l /\\ \n                          (refl_trans_clos (one_step (union term (union term R1 R3) (union term R2 (Pi pi V0 V1)))) u' u)).\ngeneralize l l' l_R_l' u'_in_l'.\nintro k1; induction k1 as [ | t1 k1]; intros [ | t2 k2] H u_in_k1.\ncontradiction.\ngeneralize (refl_trans_clos_one_step_list_length_eq H); intro; discriminate.\ncontradiction.\nrewrite refl_trans_clos_one_step_list_head_tail in H.\ndestruct H as [Ht1t2 Hk1k2].\nsimpl in u_in_k1; destruct u_in_k1 as [u_eq_t2 | u_in_k2].\nexists t1; split.\nleft; trivial.\nsubst; assumption.\ndestruct (IHk1 k2 Hk1k2 u_in_k2) as [u [u_in_k1 H]].\nexists u; split.\nright; trivial.\nassumption.\ndestruct H as [u [u_in_l H]].\ninversion H as [u'' | u1' u1 H1]; clear H; subst.\napply IHl; simpl; trivial.\nassert (Acc_u : Acc (rwr (union term (union term R1 R3) (union term R2 (Pi pi V0 V1)))) u).\nrewrite <- acc_one_step.\napply IHl; trivial.\napply Acc_incl with (trans_clos (one_step\n                                       (union term (union term R1 R3) (union term R2 (Pi pi V0 V1))))).\ndo 3 intro; left; assumption.\napply Acc_inv with u; assumption.\nQed.\n\nLemma modular_termination :\n   well_founded (ddp_step (union _ (union _ R1 R2) (union _ R3 (Pi pi V0 V1)))).\nProof.\nintros s; apply ddp_necessary; simpl; trivial.\napply R123_var'.\n\nclear s; intro s; pattern s; apply term_rec3; clear s; trivial.\nintro x; apply Acc_intro; intros s H; inversion H; subst.\ninversion H0; subst.\ndestruct t2 as [v2 | f2 l2].\napply False_rect; apply (R123_var'  _ _ H3).\ndiscriminate.\n\nintros f l IHl; \ngeneralize (F.Symb.eq_bool_ok f pi); case (F.Symb.eq_bool f pi); [intros f_eq_pi | intros f_diff_pi].\nsubst f.\napply Acc_incl with (one_step (union _ (union _ (union _ R1 R2) R3) (Pi pi V0 V1))).\nintros t1 t2; apply one_step_incl; clear t1 t2.\nintros t1 t2 [[H1 | H2] | [H3 | Hpi]].\ndo 3 left; trivial.\ndo 2 left; right; trivial.\nleft; right; trivial.\nright; trivial.\napply acc_subterms_pi; trivial.\nintros x t [[H1 | H2] | H3].\napply (R1_var _ _ H1).\napply (R2_var _ _ H2).\napply (R3_var _ _ H3).\nintros t1 t2 [[H1 | H2] | H3].\napply (P1 t1 t2 H1).\napply (P2 t1 t2 H2).\napply (P3 t1 t2 H3).\nintros t t_in_ll;\napply Acc_incl with (one_step (union term (union term R1 R2) (union term R3 (Pi pi V0 V1)))).\nintros t1 t2; apply one_step_incl; clear t1 t2.\nintros t1 t2 [[[H1 | H2] | H3] | Hpi].\ndo 2 left; trivial.\nleft; right; trivial.\nright; left; trivial.\nright; right; trivial.\napply IHl; trivial.\n\n(* 1/1 Standard dependancy pairs criterion *)\napply ddp_simple_criterion_local; simpl; trivial.\napply R123_var'.\napply R123_reg'.\napply def_dec123'.\n\ndestruct (def_dec12 f) as [D12 | C12].\napply Case12; trivial.\nintros [ | i p] g k Sub D3.\nsimpl in Sub; injection Sub; clear Sub; intros; subst g k.\nassert False; [idtac | contradiction].\napply (Incomp123' f); trivial.\nsimpl in Sub; assert (H := nth_error_ok_in i l);\ndestruct (nth_error l i) as [ti | ]; [idtac | discriminate].\ndestruct (H _ (eq_refl _)) as [ls1 [ls2 [L H']]]; clear H; subst l.\nassert (Hti : Interp_dom (union term R1 R2) (union term R3 (Pi pi V0 V1)) ti).\napply acc_interp_dom.\napply IHl; apply in_or_app; right; left; trivial.\napply (Hti p); trivial.\n\ndestruct (def_dec3 f) as [D3' | C3].\napply Acc_incl with (ddp_step (union term (union term R1 R3) (union term R2 (Pi pi V0 V1)))).\nrefine (ddp_step_incl _ _ _).\nintros t1 t2 [[H1 | H2] | [H3 | HPi]].\ndo 2 left; assumption.\nright; left; assumption.\nleft; right; assumption.\ndo 2 right; assumption.\n\napply Case3; trivial.\nintros t t_in_l; rewrite <- Dummy; apply IHl; trivial.\napply Acc_intro; intros t H.\ninversion H as [g k l' s'' l_R_l' _Hm]; clear H; subst.\ninversion _Hm as [_t s sigma Hm K1 K2]; clear _Hm; subst.\ndestruct Hm as [Hm _Sub].\ninversion Hm as [_s [ v | f' k'] p g'' k'' t_R_s Sub Df'' H1 H']; subst.\ndestruct p; discriminate.\ndestruct s as [x | g k].\nabsurd (union term (union term R1 R2) (union term R3 (Pi pi V0 V1)) (Term f' k') (Var x)); trivial.\napply R123_var'.\nsimpl in K2; injection K2; clear K2; intros; subst.\napply False_rect; destruct t_R_s as [H12 | [H3 | HPi]].\napply C12; apply (Def (union _ R1 R2) f _ _ H12).\napply C3; apply (Def R3 f _ _ H3).\napply f_diff_pi; inversion HPi; subst; trivial.\nQed.\n\nEnd Modular_termination.\n\nLemma def_dec_rules : \n   forall R rule_list, (forall l r, R r l <-> In (l,r) rule_list) ->\n   forall f, {defined R f} + {~ defined R f}.\nProof.\nintros R rule_list; generalize R; clear R;\ninduction rule_list as [ | [l r] rule_list]; intros R Equiv f.\nright; intro Df; inversion Df as [f' k u H]; subst.\nrewrite Equiv in H; contradiction.\nset (R' := fun r l => In (l,r) rule_list).\nassert (Equiv' : forall l r : term, R' r l <-> In (l, r) rule_list).\nintros l1 r1; unfold R'; split; trivial.\ndestruct (IHrule_list R' Equiv' f) as [Df | Cf].\nleft; inversion Df as [f' k u H]; subst.\napply (Def R f k u).\nrewrite Equiv; right; trivial.\ndestruct l as [v | f' k'].\nright; intro Df; inversion Df as [f' k u H]; subst.\napply Cf.\nrewrite Equiv in H.\ndestruct H as [H | H].\ndiscriminate.\nrewrite <- Equiv' in H.\napply (Def R' f k u); trivial.\ngeneralize (F.Symb.eq_bool_ok f f'); case (F.Symb.eq_bool f f'); [intros f_eq_f' | intros f_diff_f'].\nleft; apply (Def R f k' r); subst; rewrite Equiv; left; trivial.\nright; intro Df; inversion Df as [f'' k u H]; subst.\nrewrite Equiv in H; destruct H as [H | H].\napply f_diff_f'; injection H; intros; subst; trivial.\napply Cf.\nrewrite <- Equiv' in H.\napply (Def R' f k u); trivial.\nDefined.\n\nLemma modular_termination_lift :\n  forall (V0 V1 : variable), V0 <> V1 ->\n  forall pi R1 R2 R3, module R1 R2 -> module R1 R3 ->\n\n  forall rule_list1, (forall l r, R1 r l <-> In (l,r) rule_list1) ->\n  (forall l r, In (l,r) rule_list1 -> forall v, l <> Var v) ->\n  (forall l r, In (l,r) rule_list1 -> forall v, In v (var_list r) -> In v (var_list l)) ->\n  (forall l r, In (l,r) rule_list1 -> (forall f, ((symb_in_term f r = true -> f <> pi) /\\\n                                                              (symb_in_term f l = true -> f <> pi)))) ->\n\n  forall rule_list2, (forall l r, R2 r l <-> In (l,r) rule_list2) ->\n  (forall l r, In (l,r) rule_list2 -> forall v, l <> Var v) ->\n  (forall l r, In (l,r) rule_list2 -> forall v, In v (var_list r) -> In v (var_list l)) ->\n  (forall l r, In (l,r) rule_list2 -> (forall f, ((symb_in_term f r = true -> f <> pi) /\\\n                                                              (symb_in_term f l = true -> f <> pi)))) ->\n\n  forall rule_list3, (forall l r, R3 r l <-> In (l,r) rule_list3) ->\n  (forall l r, In (l,r) rule_list3 -> forall v, l <> Var v) ->\n  (forall l r, In (l,r) rule_list3 -> forall v, In v (var_list r) -> In v (var_list l)) ->\n  (forall l r, In (l,r) rule_list3 -> (forall f, ((symb_in_term f r = true -> f <> pi) /\\\n                                                              (symb_in_term f l = true -> f <> pi)))) ->\n\n  (forall s t f, defined R2 f -> R3 s t -> symb_in_term_list f (s :: t :: nil) = false) ->\n  (forall s t f, defined R3 f -> R2 s t -> symb_in_term_list f (s :: t :: nil) = false) ->\n\n  well_founded (ddp_step (union _ (union _ R1 R2) (Pi pi V0 V1))) ->\n  well_founded (rdp_step (axiom (ddp R3)) (union _ (union _ R1 R3) (Pi pi V0 V1))) ->\n  well_founded (ddp_step (union _ (union _ R1 R2) (union _ R3 (Pi pi V0 V1)))).\nProof.\nintros V0 V1 V0_diff_V1 pi R1 R2 R3 M12 M13 \nrule_list1 Equiv1 R1_var R1_reg P1\nrule_list2 Equiv2 R2_var R2_reg P2\nrule_list3 Equiv3 R3_var R3_reg P3\nIndep2 Indep3 W12 W3.\napply (modular_termination _ _ V0_diff_V1 pi pi R1 R2 R3 \n(def_dec_rules _ _ Equiv1)\n(def_dec_rules _ _ Equiv2)\n(def_dec_rules _ _ Equiv3) _ _ _\n(fun s t => iff_sym (compute_red_is_correct _ R1_reg _ Equiv1 s t))\n(fun s t => iff_sym (compute_red_is_correct _ R2_reg _ Equiv2 s t))\n(fun s t => iff_sym (compute_red_is_correct _ R3_reg _ Equiv3 s t))); trivial.\nintros s t H1; apply R1_reg; rewrite <- Equiv1; trivial.\nintros s t H2; apply R2_reg; rewrite <- Equiv2; trivial.\nintros s t H3; apply R3_reg; rewrite <- Equiv3; trivial.\nintros x t H1; rewrite Equiv1 in H1; apply (R1_var _ _ H1 x); trivial.\nintros x t H2; rewrite Equiv2 in H2; apply (R2_var _ _ H2 x); trivial.\nintros x t H3; rewrite Equiv3 in H3; apply (R3_var _ _ H3 x); trivial.\nintros s t H1; apply (P1 t s); rewrite <- Equiv1; trivial.\nintros s t H2; apply (P2 t s); rewrite <- Equiv2; trivial.\nintros s t H3; apply (P3 t s); rewrite <- Equiv3; trivial.\napply ddp_criterion; trivial.\napply R12_var'.\nintros x t H1; rewrite Equiv1 in H1; apply (R1_var _ _ H1 x); trivial.\nintros x t H2; rewrite Equiv2 in H2; apply (R2_var _ _ H2 x); trivial.\nintros s t [[H1 | H2] | Hpi].\napply R1_reg; rewrite <- Equiv1; trivial.\napply R2_reg; rewrite <- Equiv2; trivial.\ninversion Hpi; subst.\nintros x [x_eq_v1 | x_in_nil]; [left; trivial | contradiction].\nintros x [x_eq_v2 | x_in_nil]; [right; left; trivial | contradiction].\nintros f; destruct (def_dec_rules _ _ Equiv1 f) as [D1 | C1].\nright; inversion D1 as [f' l u H1].\nsubst f'; apply (Def (union _ (union _ R1 R2) (Pi pi V0 V1)) f l u); left; left; trivial.\ndestruct (def_dec_rules _ _ Equiv2 f) as [D2 | C2].\nright; inversion D2 as [f' l u H2].\nsubst f'; apply (Def (union _ (union _ R1 R2) (Pi pi V0 V1)) f l u); left; right; trivial.\ngeneralize (F.Symb.eq_bool_ok f pi); case (F.Symb.eq_bool f pi); [intros f_eq_pi | intros f_diff_pi].\nsubst f; right; \napply (Def (union _ (union _ R1 R2) (Pi pi V0 V1)) pi (Var V0 :: Var V1 :: nil) (Var V0)).\nright; apply Pi1.\nleft; apply Const; intros l u [[H1 | H2] | Hpi].\napply C1; apply (Def R1 f l u H1).\napply C2; apply (Def R2 f l u H2).\ninversion Hpi; subst f; apply f_diff_pi; trivial.\nrefine (wf_incl _ _ _ _ W12).\nintros u1 u2 [H _]; assumption.\nQed.\n\nInductive Empty_R : term -> term -> Prop := .\n\nLemma module_empty : forall R, module Empty_R R.\nProof.\nintros R; apply Mod.\nintros f s t _ H; case H.\nQed.\n\nLemma list_rules_empty : forall l r, Empty_R r l <-> In (l,r) nil.\nProof.\nintros l r; split; intro H; case H.\nQed.\n\nLemma Empty_R_reg :\n  (forall l r, In (l,r) nil -> forall v, In v (var_list r) -> In v (var_list l)).\nProof.\nintros l r lr_in_nil; case lr_in_nil.\nQed.\n\nLemma modular_termination_indep_lift :\n  forall (V0 V1 : variable), V0 <> V1 ->\n  forall pi R2 R3, \n\n  forall rule_list2, (forall l r, R2 r l <-> In (l,r) rule_list2) ->\n  (forall l r, In (l,r) rule_list2 -> forall v, l <> Var v) ->\n  (forall l r, In (l,r) rule_list2 -> forall v, In v (var_list r) -> In v (var_list l)) ->\n  (forall l r, In (l,r) rule_list2 -> (forall f, ((symb_in_term f r = true -> f <> pi) /\\\n                                                              (symb_in_term f l = true -> f <> pi)))) ->\n\n  forall rule_list3, (forall l r, R3 r l <-> In (l,r) rule_list3) ->\n  (forall l r, In (l,r) rule_list3 -> forall v, l <> Var v) ->\n  (forall l r, In (l,r) rule_list3 -> forall v, In v (var_list r) -> In v (var_list l)) ->\n  (forall l r, In (l,r) rule_list3 -> (forall f, ((symb_in_term f r = true -> f <> pi) /\\\n                                                              (symb_in_term f l = true -> f <> pi)))) ->\n\n  (forall s t f, defined R2 f -> R3 s t -> symb_in_term_list f (s :: t :: nil) = false) ->\n  (forall s t f, defined R3 f -> R2 s t -> symb_in_term_list f (s :: t :: nil) = false) ->\n\n  well_founded (ddp_step (union _ R2 (Pi pi V0 V1))) ->\n  well_founded (ddp_step (union _ R3 (Pi pi V0 V1))) ->\n  well_founded (ddp_step (union _ (union _ R2 R3) (Pi pi V0 V1))).\nProof.\nintros V0 V1 V0_diff_V1 pi R2 R3 \nrule_list2 Equiv2 R2_var R2_reg P2\nrule_list3 Equiv3 R3_var R3_reg P3\nIndep2 Indep3 W12 W3.\napply wf_incl with  (ddp_step (union term (union _ Empty_R R2) (union term R3 (Pi pi V0 V1)))).\nintros t1 t2; apply  ddp_step_incl; clear t1 t2.\nintros t1 t2 [[H2 | H3] | Hpi].\nleft; right; trivial.\nright; left; trivial.\ndo 2 right; trivial.\n\napply (modular_termination_lift _ _ V0_diff_V1 pi Empty_R R2 R3 \n(module_empty R2) (module_empty R3)) with (@nil (term * term)) rule_list2 rule_list3; trivial.\napply list_rules_empty.\nintros s t H; case H.\nintros s t H; case H.\nintros s t H; case H.\napply wf_incl with  (ddp_step (union term R2 (Pi pi V0 V1))); trivial.\nassert (H : inclusion term (union term (union term Empty_R R2) (Pi pi V0 V1)) \n                                         (union term R2 (Pi pi V0 V1))).\nintros t1 t2 [[HE | H2] | Hpi].\ncase HE.\nleft; trivial.\nright; trivial.\napply ddp_step_incl; trivial.\n\napply wf_incl with  (rdp_step (axiom (ddp (union term R3 (Pi pi V0 V1)))) (union term R3 (Pi pi V0 V1))); trivial.\nclear; intros s t H; inversion H; clear H; subst.\napply Rdp_step with l2.\nrefine (refl_trans_incl (one_step_list_incl _ (one_step_incl _ _ _)) H0).\nclear; intros t1 t2 [[HE | H3] | Hpi].\ncase HE.\nleft; trivial.\nright; trivial.\ninversion H1; apply instance.\ndestruct H3 as [H3 Sub].\ninversion H3; clear H3; subst.\nsplit; [apply Dp with t3 p | idtac]; trivial.\nleft; assumption.\ninversion H6; clear H6; subst.\napply (Def _ f2 l t); left; trivial.\nQed.\n\nLemma modular_termination_hierarch_lift :\n  forall (V0 V1 : variable), V0 <> V1 ->\n  forall pi R1 R3, module R1 R3 ->\n\n  forall rule_list1, (forall l r, R1 r l <-> In (l,r) rule_list1) ->\n  (forall l r, In (l,r) rule_list1 -> forall v, l <> Var v) ->\n  (forall l r, In (l,r) rule_list1 -> forall v, In v (var_list r) -> In v (var_list l)) ->\n  (forall l r, In (l,r) rule_list1 -> (forall f, ((symb_in_term f r = true -> f <> pi) /\\\n                                                              (symb_in_term f l = true -> f <> pi)))) ->\n\n  forall rule_list3, (forall l r, R3 r l <-> In (l,r) rule_list3) ->\n  (forall l r, In (l,r) rule_list3 -> forall v, l <> Var v) ->\n  (forall l r, In (l,r) rule_list3 -> forall v, In v (var_list r) -> In v (var_list l)) ->\n  (forall l r, In (l,r) rule_list3 -> (forall f, ((symb_in_term f r = true -> f <> pi) /\\\n                                                              (symb_in_term f l = true -> f <> pi)))) ->\n\n  well_founded (ddp_step (union _ R1 (Pi pi V0 V1))) ->\n  well_founded (rdp_step (axiom (ddp R3)) (union _ (union _ R1 R3) (Pi pi V0 V1))) ->\n  well_founded (ddp_step (union _ (union _ R1 R3) (Pi pi V0 V1))).\nProof.\nintros V0 V1 V0_diff_V1 pi R1 R3 M13 \nrule_list1 Equiv1 R1_var R1_reg P1\nrule_list3 Equiv3 R3_var R3_reg P3\nW12 W3.\napply wf_incl with  (ddp_step (union term (union _ R1 Empty_R) (union term R3 (Pi pi V0 V1)))).\nintros t1 t2; apply  ddp_step_incl; clear t1 t2.\nintros t1 t2 [[H1 | H3] | Hpi].\ndo 2 left; trivial.\nright; left; trivial.\ndo 2 right; trivial.\n\napply (modular_termination_lift _ _ V0_diff_V1 pi R1 Empty_R R3) with rule_list1 (@nil (term * term)) rule_list3; trivial.\napply Mod; intros f s t [f' l u HE]; case HE.\napply list_rules_empty.\nintros s t H; case H.\nintros s t H; case H.\nintros s t H; case H.\nintros s t f [f' l u HE]; case HE.\nintros s t f _ HE; case HE.\napply wf_incl with  (ddp_step (union term R1 (Pi pi V0 V1))); trivial.\napply ddp_step_incl.\nintros t1 t2 [[H1 | HE] | Hpi].\nleft; trivial.\ncase HE.\nright; trivial.\nQed.\n\nRecord rwr_rel (pi : F.Symb.A) : Type :=\n  mk_set \n  {\n     ident : nat;\n     Rel : relation term;\n     rules : list (term * term);\n     REquiv : (forall l r, Rel r l <-> In (l,r) rules);\n     RR_var : (forall l r, In (l,r) rules -> forall v, l <> Var v);\n     RR_reg : (forall l r, In (l,r) rules -> forall v, In v (var_list r) -> In v (var_list l));\n     RP : (forall l r, In (l,r) rules -> (forall f, ((symb_in_term f r = true -> f <> pi) /\\\n                                                              (symb_in_term f l = true -> f <> pi))))\n  }.\n\nLemma Equiv_empty : forall (l r : term), Empty_R r l <-> In (l,r) nil.\nProof.\nintros l r; split; intro H; case H.\nQed.\n\nLemma R_var_empty : forall (l r : term), In (l,r) nil -> forall v, l <> Var v.\nProof.\nintros l r H; case H.\nQed.\n\nLemma R_reg_empty : forall l r, In (l,r) nil -> forall v, In v (var_list r) -> In v (var_list l).\nProof.\nintros l r H; case H.\nQed.\n\nLemma P_empty :\n forall pi, forall l r, In (l,r) nil -> (forall f, ((symb_in_term f r = true -> f <> pi) /\\\n                                                              (symb_in_term f l = true -> f <> pi))).\nProof.\nintros pi l r H; case H.\nQed.\n\nDefinition rwr_rel_empty pi : rwr_rel pi :=\n  mk_set pi 0 Empty_R nil Equiv_empty R_var_empty R_reg_empty (P_empty pi).\n\nLemma Equiv_comb :\n  forall R1 R2 rules1 rules2, (forall l r, R1 r l <-> In (l,r) rules1) -> (forall l r, R2 r l <-> In (l,r) rules2) ->\n          (forall (l r : term), (union _ R1 R2) r l <-> In (l,r) (rules1 ++ rules2)).\nProof.\nintros R1 R2 rules1 rules2 Equiv1 Equiv2.\nintros l r; split; intro H.\ndestruct H as [H | H]; apply in_or_app; [left; rewrite <- Equiv1 | right; rewrite <- Equiv2]; trivial.\ndestruct (in_app_or _ _ _ H) as [H' | H']; [left; rewrite Equiv1 | right; rewrite Equiv2]; trivial.\nQed.\n\nLemma R_var_comb :\n  forall rules1 rules2, (forall l r, In (l,r) rules1 -> forall v, l <> Var v) ->\n  (forall l r, In (l,r) rules2 -> forall v, l <> Var v) ->\n  (forall (l r : term), In (l,r) (rules1 ++ rules2) -> forall v, l <> Var v).\nProof.\nintros rules1 rules2 R1_var R2_var l r H v.\ndestruct (in_app_or _ _ _ H) as [H' | H']; [apply (R1_var l r H' v) | apply (R2_var l r H' v)].\nQed.\n\nLemma R_reg_comb :\n  forall rules1 rules2, (forall l r, In (l,r) rules1 -> forall v, In v (var_list r) -> In v (var_list l)) ->\n  (forall l r, In (l,r) rules2 -> forall v, In v (var_list r) -> In v (var_list l)) ->\n  (forall l r, In (l,r) (rules1 ++ rules2) -> forall v, In v (var_list r) -> In v (var_list l)).  \nProof.\nintros rules1 rules2 R1_reg R2_reg l r H v.\ndestruct (in_app_or _ _ _ H) as [H' | H']; [apply (R1_reg l r H' v) | apply (R2_reg l r H' v)].\nQed.\n\nLemma P_comb :\n forall pi rules1 rules2, (forall l r, In (l,r) rules1 -> (forall f, ((symb_in_term f r = true -> f <> pi) /\\\n                                                              (symb_in_term f l = true -> f <> pi)))) ->\n(forall l r, In (l,r) rules2 -> (forall f, ((symb_in_term f r = true -> f <> pi) /\\\n                                                              (symb_in_term f l = true -> f <> pi)))) ->\n(forall l r, In (l,r) (rules1 ++ rules2) -> (forall f, ((symb_in_term f r = true -> f <> pi) /\\\n                                                              (symb_in_term f l = true -> f <> pi)))).\nProof.\nintros rules1 rules2 pi P1 P2 l r H f.\ndestruct (in_app_or _ _ _ H) as [H' | H']; [apply (P1 l r H' f) | apply (P2 l r H' f)].\nQed.\n\nDefinition rwr_rel_comb pi (R1 R2 : rwr_rel pi)  : rwr_rel pi :=\n  mk_set pi (ident pi R1) (union _ (Rel pi R1) (Rel pi R2)) (rules pi R1 ++ rules pi R2)\n                  (Equiv_comb _ _ _ _ (REquiv pi R1) (REquiv pi R2))\n                  (R_var_comb _ _ (RR_var pi R1) (RR_var pi R2))\n                  (R_reg_comb _ _ (RR_reg pi R1) (RR_reg pi R2))\n                  (P_comb _ _ _ (RP pi R1) (RP pi R2)).\n\nLemma modular_termination_indep_list_lift :\n  forall (V0 V1 : variable), V0 <> V1 -> forall pi (list_rel : list (rwr_rel pi)) R',\n   (forall R1 R2 L' L'' L''', list_rel = L' ++ R1 :: L'' ++ R2 :: L''' -> ident pi R1 <> ident pi R2) ->\n   well_founded (ddp_step (union _ (Rel pi R') (Pi pi V0 V1))) ->\n  (forall R, In R list_rel ->   module (Rel pi R') (Rel pi R)) ->\n  (forall R, In R list_rel ->   well_founded (rdp_step (axiom (ddp (Rel pi R))) (union _ (union _ (Rel pi R) (Rel pi R')) (Pi pi V0 V1)))) ->\n  (forall R1 R2, In R1 list_rel -> In R2 list_rel -> ident pi R1 <> ident pi R2 ->\n        (forall s t f, defined (Rel pi R1) f -> (Rel pi R2) s t -> symb_in_term_list f (s :: t :: nil) = false)) ->\n    well_founded (ddp_step (fold_left (fun acc Rr => union _ (Rel pi Rr) acc)  list_rel  (union _ (Rel pi R') (Pi pi V0 V1)))).\nProof.\nintros V0 V1 V0_diff_V1 pi L R' U W' ML WL IL.\nassert (fold_incl : forall (L0 : list (rwr_rel pi)) (P0 P1 : term -> term -> Prop),\ninclusion term P0 P1 ->\ninclusion term\n  (fold_left\n     (fun (acc : relation term) (Rr : rwr_rel pi) =>\n      union term (Rel pi Rr) acc) L0 P0)\n  (fold_left\n     (fun (acc : relation term) (Rr : rwr_rel pi) =>\n      union term (Rel pi Rr) acc) L0 P1)).\nintro L'; induction L' as [ | R'' L'']; simpl; intros P1 P2 P1_in_P2; trivial.\napply IHL''.\nintros t1 t2 [H'' | H1].\nleft; trivial.\nright; apply P1_in_P2; trivial.\n\nassert (Gen : forall (R0 : rwr_rel pi), module (Rel pi R') (Rel pi R0) ->\n                     (well_founded (rdp_step (axiom (ddp (Rel pi R0))) (union _ (union _ (Rel pi R') (Rel pi R0)) (Pi pi V0 V1)))) ->\n                     (forall R2, In R2 L -> \n                          (forall s t f, defined (Rel pi R0) f -> (Rel pi R2) s t -> symb_in_term_list f (s :: t :: nil) = false)) ->\n                     (forall R1, In R1 L -> \n                            (forall s t f, defined (Rel pi R1) f -> (Rel pi R0) s t -> symb_in_term_list f (s :: t :: nil) = false)) ->\n                     well_founded (ddp_step (fold_left (fun acc Rr => union _ (Rel pi Rr) acc)  L  (union _ (union _ (Rel pi R') (Rel pi R0)) (Pi pi V0 V1))))).\ninduction L as [ | R L]; intros R0 M0 W0 I1 I2; simpl; trivial.\napply (modular_termination_hierarch_lift V0 V1 V0_diff_V1) with (rules pi R') (rules pi R0); trivial.\napply (REquiv pi R').\napply (RR_var pi R').\napply (RR_reg pi R').\napply (RP pi R').\napply (REquiv pi R0).\napply (RR_var pi R0).\napply (RR_reg pi R0).\napply (RP pi R0).\n\napply wf_incl with\n(ddp_step\n     (fold_left\n        (fun (acc : relation term) (Rr : rwr_rel pi) =>\n         union term (Rel pi Rr) acc) L\n        (union term (union term (Rel pi R') (Rel pi (rwr_rel_comb pi R R0))) (Pi pi V0 V1)))).\napply ddp_step_incl.\napply fold_incl.\nintros t1 t2 [H | [[H' | H0] | Hpi]].\nleft; right; left; trivial.\ndo 2 left; trivial.\nleft; do 2 right; trivial.\nright; trivial.\n\napply IHL.\nintros R1 R2 L' L'' L''' H; apply (U R1 R2 (R :: L') L'' L'''); simpl; rewrite H; trivial.\nintros R1 R1_in_L; apply ML; right; trivial.\nintros R1 R1_in_L; apply WL; right; trivial.\nintros R1 R2 R1_in_L R2_in_L; apply IL; right; trivial.\nsimpl; apply Mod.\nintros f s t Df H'; destruct Df as [f' l u [H | H0]].\ndestruct (ML R (or_introl _ (eq_refl _))) as [M'].\napply (M' f' s t (Def (Rel pi R) f' l u H)); trivial.\ndestruct M0 as [M0].\napply (M0 f' s t (Def (Rel pi R0) f' l u H0)); trivial.\nsimpl; assert (M := modular_termination_lift _ _ V0_diff_V1 pi (Rel pi R') (Rel pi R) (Rel pi R0) \n(ML _ (or_introl _ (eq_refl _))) M0\n_ (REquiv pi R') (RR_var pi R') (RR_reg pi R') (RP pi R')\n_ (REquiv pi R) (RR_var pi R) (RR_reg pi R) (RP pi R)\n_ (REquiv pi R0) (RR_var pi R0) (RR_reg pi R0) (RP pi R0)\n(I2 R (or_introl _ (eq_refl _)))\n(I1 R (or_introl _ (eq_refl _)))).\napply wf_incl with (ddp_step\n         (union term (union term (Rel pi R') (Rel pi R))\n            (union term (Rel pi R0) (Pi pi V0 V1)))).\napply rddp_step_incl.\nintros t1 t2 [H | H0].\nleft; right; trivial.\nright; left; trivial.\nintros t1 t2 [[H' | [H | H0]] | Hpi].\ndo 2 left; trivial.\nleft; right; trivial.\nright; left; trivial.\ndo 2 right; trivial.\napply M; trivial.\napply (modular_termination_hierarch_lift V0 V1 V0_diff_V1) with (rules pi R') (rules pi R); trivial.\napply ML; left; trivial.\napply (REquiv pi R').\napply (RR_var pi R').\napply (RR_reg pi R').\napply (RP pi R').\napply (REquiv pi R).\napply (RR_var pi R).\napply (RR_reg pi R).\napply (RP pi R).\napply wf_incl with (rdp_step (axiom (ddp (Rel pi R)))\n     (union term (union term (Rel pi R) (Rel pi R')) (Pi pi V0 V1))).\napply rddp_step_incl.\nintros t1 t2; trivial.\nintros t1 t2 [[H | H'] | Hpi].\nleft; right; trivial.\ndo 2 left; trivial.\nright; trivial.\napply WL; left; trivial.\nintros R2 R2_in_L.\nintros s t f Df H2; simpl in Df; destruct Df as [f' l u [H | H0]]. \napply IL with R R2; trivial.\nleft; trivial.\nright; trivial.\ndestruct (In_split _ _ R2_in_L) as [L'' [L''' H']].\napply (U R R2 nil L'' L'''); simpl; subst L; trivial.\napply (Def (Rel pi R) f' l u H).\napply I1 with R2; trivial.\nright; trivial. \napply (Def (Rel pi R0) f' l u H0).\nintros R1 R1_in_L.\nintros s t f Df [H | H0].\napply IL with R1 R; trivial.\nright; trivial.\nleft; trivial.\ndestruct (In_split _ _ R1_in_L) as [L'' [L''' H']].\nintro H'''; refine (U R R1 nil L'' L''' _ _); simpl; subst; symmetry; trivial.\napply I2 with R1; trivial; right; trivial.\n\napply wf_incl with (ddp_step\n           (fold_left\n              (fun (acc : relation term) (Rr : rwr_rel pi) =>\n               union term (Rel pi Rr) acc) L\n              (union term (union term (Rel pi R') (Rel pi (rwr_rel_empty pi))) (Pi pi V0 V1)))).\napply rddp_step_incl.\napply fold_incl.\nintros t1 t2 [H' | Hpi].\ndo 2 left; trivial.\nright; trivial.\napply fold_incl.\nintros t1 t2 [H' | Hpi].\ndo 2 left; trivial.\nright; trivial.\n\napply Gen.\napply Mod; intros f s t Df; inversion Df as [f' l u H]; case H.\nsimpl; intro s; apply Acc_intro; intros _t H.\ninversion H as [g k l' s'' l_R_l' _Hm]; clear H; subst.\ninversion _Hm as [t s sigma Hm K1 K2]; clear _Hm; subst.\ndestruct Hm as [Hm _Sub].\ninversion Hm as [s' t' p g'' k'' t_R_s Sub Df'' H1 H']; case t_R_s.\nintros R2 _ s t f Df; inversion Df as [f' l u H]; case H.\nintros R1 _ s t f _ H; case H.\nQed.\n\n\nEnd MakeModDP.\n", "meta": {"author": "fblanqui", "repo": "color", "sha": "f2ef98f7d13c5d71dd2a614ed2e6721703a34532", "save_path": "github-repos/coq/fblanqui-color", "path": "github-repos/coq/fblanqui-color/color-f2ef98f7d13c5d71dd2a614ed2e6721703a34532/Coccinelle/term_orderings/modular_dp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984434543457, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.25084913461369035}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\nFrom compcert Require Import Raux.\nFrom compcert Require Import Defs.\nFrom compcert Require Import Round_pred.\nFrom compcert Require Import Generic_fmt.\nFrom compcert Require Import Float_prop.\nFrom compcert Require Import FIX.\nFrom compcert Require Import Ulp.\nFrom compcert Require Import Round_NE.\nRequire Import Psatz.\n\nSection RND_FLX.\n\nVariable beta : radix.\n\nNotation bpow e := (bpow beta e).\n\nVariable prec : Z.\n\nClass Prec_gt_0 :=\nprec_gt_0 : (0 < prec)%Z.\n\nContext { prec_gt_0_ : Prec_gt_0 }.\n\nInductive FLX_format (x : R) : Prop :=\nFLX_spec (f : float beta) :\nx = F2R f -> (Z.abs (Fnum f) < Zpower beta prec)%Z -> FLX_format x.\n\nDefinition FLX_exp (e : Z) := (e - prec)%Z.\n\n\n\nGlobal Instance FLX_exp_valid : Valid_exp FLX_exp.\nProof. hammer_hook \"FLX\" \"FLX.FLX_exp_valid\".\nintros k.\nunfold FLX_exp.\ngeneralize prec_gt_0.\nrepeat split ; intros ; omega.\nQed.\n\nTheorem FIX_format_FLX :\nforall x e,\n(bpow (e - 1) <= Rabs x <= bpow e)%R ->\nFLX_format x ->\nFIX_format beta (e - prec) x.\nProof. hammer_hook \"FLX\" \"FLX.FIX_format_FLX\".\nclear prec_gt_0_.\nintros x e Hx [[xm xe] H1 H2].\nrewrite H1, (F2R_prec_normalize beta xm xe e prec).\nnow eexists.\nexact H2.\nnow rewrite <- H1.\nQed.\n\nTheorem FLX_format_generic :\nforall x, generic_format beta FLX_exp x -> FLX_format x.\nProof. hammer_hook \"FLX\" \"FLX.FLX_format_generic\".\nintros x H.\nrewrite H.\neexists ; repeat split.\nsimpl.\napply lt_IZR.\nrewrite abs_IZR.\nrewrite <- scaled_mantissa_generic with (1 := H).\nrewrite <- scaled_mantissa_abs.\napply Rmult_lt_reg_r with (bpow (cexp beta FLX_exp (Rabs x))).\napply bpow_gt_0.\nrewrite scaled_mantissa_mult_bpow.\nrewrite IZR_Zpower, <- bpow_plus.\n2: now apply Zlt_le_weak.\nunfold cexp, FLX_exp.\nring_simplify (prec + (mag beta (Rabs x) - prec))%Z.\nrewrite mag_abs.\ndestruct (Req_dec x 0) as [Hx|Hx].\nrewrite Hx, Rabs_R0.\napply bpow_gt_0.\ndestruct (mag beta x) as (ex, Ex).\nnow apply Ex.\nQed.\n\nTheorem generic_format_FLX :\nforall x, FLX_format x -> generic_format beta FLX_exp x.\nProof. hammer_hook \"FLX\" \"FLX.generic_format_FLX\".\nclear prec_gt_0_.\nintros x [[mx ex] H1 H2].\nsimpl in H2.\nrewrite H1.\napply generic_format_F2R.\nintros Zmx.\nunfold cexp, FLX_exp.\nrewrite mag_F2R with (1 := Zmx).\napply Zplus_le_reg_r with (prec - ex)%Z.\nring_simplify.\nnow apply mag_le_Zpower.\nQed.\n\nTheorem FLX_format_satisfies_any :\nsatisfies_any FLX_format.\nProof. hammer_hook \"FLX\" \"FLX.FLX_format_satisfies_any\".\nrefine (satisfies_any_eq _ _ _ (generic_format_satisfies_any beta FLX_exp)).\nintros x.\nsplit.\napply FLX_format_generic.\napply generic_format_FLX.\nQed.\n\nTheorem FLX_format_FIX :\nforall x e,\n(bpow (e - 1) <= Rabs x <= bpow e)%R ->\nFIX_format beta (e - prec) x ->\nFLX_format x.\nProof with auto with typeclass_instances. hammer_hook \"FLX\" \"FLX.FLX_format_FIX\".\nintros x e Hx Fx.\napply FLX_format_generic.\napply generic_format_FIX in Fx.\nrevert Fx.\napply generic_inclusion with (e := e)...\napply Z.le_refl.\nQed.\n\n\nInductive FLXN_format (x : R) : Prop :=\nFLXN_spec (f : float beta) :\nx = F2R f ->\n(x <> 0%R -> Zpower beta (prec - 1) <= Z.abs (Fnum f) < Zpower beta prec)%Z ->\nFLXN_format x.\n\nTheorem generic_format_FLXN :\nforall x, FLXN_format x -> generic_format beta FLX_exp x.\nProof. hammer_hook \"FLX\" \"FLX.generic_format_FLXN\".\nintros x [[xm ex] H1 H2].\ndestruct (Req_dec x 0) as [Zx|Zx].\nrewrite Zx.\napply generic_format_0.\nspecialize (H2 Zx).\napply generic_format_FLX.\nrewrite H1.\neexists ; repeat split.\napply H2.\nQed.\n\nTheorem FLXN_format_generic :\nforall x, generic_format beta FLX_exp x -> FLXN_format x.\nProof. hammer_hook \"FLX\" \"FLX.FLXN_format_generic\".\nintros x Hx.\nrewrite Hx.\nsimpl.\neexists. easy.\nrewrite <- Hx.\nintros Zx.\nsimpl.\nsplit.\n\napply le_IZR.\nrewrite IZR_Zpower.\n2: now apply Zlt_0_le_0_pred.\nrewrite abs_IZR, <- scaled_mantissa_generic with (1 := Hx).\napply Rmult_le_reg_r with (bpow (cexp beta FLX_exp x)).\napply bpow_gt_0.\nrewrite <- bpow_plus.\nrewrite <- scaled_mantissa_abs.\nrewrite <- cexp_abs.\nrewrite scaled_mantissa_mult_bpow.\nunfold cexp, FLX_exp.\nrewrite mag_abs.\nring_simplify (prec - 1 + (mag beta x - prec))%Z.\ndestruct (mag beta x) as (ex,Ex).\nnow apply Ex.\n\napply lt_IZR.\nrewrite IZR_Zpower.\n2: now apply Zlt_le_weak.\nrewrite abs_IZR, <- scaled_mantissa_generic with (1 := Hx).\napply Rmult_lt_reg_r with (bpow (cexp beta FLX_exp x)).\napply bpow_gt_0.\nrewrite <- bpow_plus.\nrewrite <- scaled_mantissa_abs.\nrewrite <- cexp_abs.\nrewrite scaled_mantissa_mult_bpow.\nunfold cexp, FLX_exp.\nrewrite mag_abs.\nring_simplify (prec + (mag beta x - prec))%Z.\ndestruct (mag beta x) as (ex,Ex).\nnow apply Ex.\nQed.\n\nTheorem FLXN_format_satisfies_any :\nsatisfies_any FLXN_format.\nProof. hammer_hook \"FLX\" \"FLX.FLXN_format_satisfies_any\".\nrefine (satisfies_any_eq _ _ _ (generic_format_satisfies_any beta FLX_exp)).\nsplit ; intros H.\nnow apply FLXN_format_generic.\nnow apply generic_format_FLXN.\nQed.\n\nLemma negligible_exp_FLX :\nnegligible_exp FLX_exp = None.\nProof. hammer_hook \"FLX\" \"FLX.negligible_exp_FLX\".\ncase (negligible_exp_spec FLX_exp).\nintros _; reflexivity.\nintros n H2; contradict H2.\nunfold FLX_exp; unfold Prec_gt_0 in prec_gt_0_; omega.\nQed.\n\nTheorem generic_format_FLX_1 :\ngeneric_format beta FLX_exp 1.\nProof. hammer_hook \"FLX\" \"FLX.generic_format_FLX_1\".\nunfold generic_format, scaled_mantissa, cexp, F2R; simpl.\nrewrite Rmult_1_l, (mag_unique beta 1 1).\n{ unfold FLX_exp.\nrewrite <- IZR_Zpower; [|unfold Prec_gt_0 in prec_gt_0_; omega].\nrewrite Ztrunc_IZR, IZR_Zpower; [|unfold Prec_gt_0 in prec_gt_0_; omega].\nrewrite <- bpow_plus.\nnow replace (_ + _)%Z with Z0 by ring. }\nrewrite Rabs_R1; simpl; split; [now right|].\nunfold Z.pow_pos; simpl; rewrite Zmult_1_r; apply IZR_lt.\nassert (H := Zle_bool_imp_le _ _ (radix_prop beta)); omega.\nQed.\n\nTheorem ulp_FLX_0: (ulp beta FLX_exp 0 = 0)%R.\nProof. hammer_hook \"FLX\" \"FLX.ulp_FLX_0\".\nunfold ulp; rewrite Req_bool_true; trivial.\nrewrite negligible_exp_FLX; easy.\nQed.\n\nLemma ulp_FLX_1 : ulp beta FLX_exp 1 = bpow (-prec + 1).\nProof. hammer_hook \"FLX\" \"FLX.ulp_FLX_1\".\nunfold ulp, FLX_exp, cexp; rewrite Req_bool_false; [|apply R1_neq_R0].\nrewrite mag_1; f_equal; ring.\nQed.\n\nLemma succ_FLX_1 : (succ beta FLX_exp 1 = 1 + bpow (-prec + 1))%R.\nProof. hammer_hook \"FLX\" \"FLX.succ_FLX_1\".\nnow unfold succ; rewrite Rle_bool_true; [|apply Rle_0_1]; rewrite ulp_FLX_1.\nQed.\n\nTheorem eq_0_round_0_FLX :\nforall rnd {Vr: Valid_rnd rnd} x,\nround beta FLX_exp rnd x = 0%R -> x = 0%R.\nProof. hammer_hook \"FLX\" \"FLX.eq_0_round_0_FLX\".\nintros rnd Hr x.\napply eq_0_round_0_negligible_exp; try assumption.\napply FLX_exp_valid.\napply negligible_exp_FLX.\nQed.\n\nTheorem gt_0_round_gt_0_FLX :\nforall rnd {Vr: Valid_rnd rnd} x,\n(0 < x)%R -> (0 < round beta FLX_exp rnd x)%R.\nProof with auto with typeclass_instances. hammer_hook \"FLX\" \"FLX.gt_0_round_gt_0_FLX\".\nintros rnd Hr x Hx.\nassert (K: (0 <= round beta FLX_exp rnd x)%R).\nrewrite <- (round_0 beta FLX_exp rnd).\napply round_le... now apply Rlt_le.\ndestruct K; try easy.\nabsurd (x = 0)%R.\nnow apply Rgt_not_eq.\napply eq_0_round_0_FLX with rnd...\nQed.\n\n\nTheorem ulp_FLX_le :\nforall x, (ulp beta FLX_exp x <= Rabs x * bpow (1-prec))%R.\nProof. hammer_hook \"FLX\" \"FLX.ulp_FLX_le\".\nintros x; case (Req_dec x 0); intros Hx.\nrewrite Hx, ulp_FLX_0, Rabs_R0.\nright; ring.\nrewrite ulp_neq_0; try exact Hx.\nunfold cexp, FLX_exp.\nreplace (mag beta x - prec)%Z with ((mag beta x - 1) + (1-prec))%Z by ring.\nrewrite bpow_plus.\napply Rmult_le_compat_r.\napply bpow_ge_0.\nnow apply bpow_mag_le.\nQed.\n\nTheorem ulp_FLX_ge :\nforall x, (Rabs x * bpow (-prec) <= ulp beta FLX_exp x)%R.\nProof. hammer_hook \"FLX\" \"FLX.ulp_FLX_ge\".\nintros x; case (Req_dec x 0); intros Hx.\nrewrite Hx, ulp_FLX_0, Rabs_R0.\nright; ring.\nrewrite ulp_neq_0; try exact Hx.\nunfold cexp, FLX_exp.\nunfold Zminus; rewrite bpow_plus.\napply Rmult_le_compat_r.\napply bpow_ge_0.\nleft; now apply bpow_mag_gt.\nQed.\n\nLemma ulp_FLX_exact_shift :\nforall x e,\n(ulp beta FLX_exp (x * bpow e) = ulp beta FLX_exp x * bpow e)%R.\nProof. hammer_hook \"FLX\" \"FLX.ulp_FLX_exact_shift\".\nintros x e.\ndestruct (Req_dec x 0) as [Hx|Hx].\n{ unfold ulp.\nnow rewrite !Req_bool_true, negligible_exp_FLX; rewrite ?Hx, ?Rmult_0_l. }\nunfold ulp; rewrite Req_bool_false;\n[|now intro H; apply Hx, (Rmult_eq_reg_r (bpow e));\n[rewrite Rmult_0_l|apply Rgt_not_eq, Rlt_gt, bpow_gt_0]].\nrewrite (Req_bool_false _ _ Hx), <- bpow_plus; f_equal; unfold cexp, FLX_exp.\nnow rewrite mag_mult_bpow; [ring|].\nQed.\n\nLemma succ_FLX_exact_shift :\nforall x e,\n(succ beta FLX_exp (x * bpow e) = succ beta FLX_exp x * bpow e)%R.\nProof. hammer_hook \"FLX\" \"FLX.succ_FLX_exact_shift\".\nintros x e.\ndestruct (Rle_or_lt 0 x) as [Px|Nx].\n{ rewrite succ_eq_pos; [|now apply Rmult_le_pos, bpow_ge_0].\nrewrite (succ_eq_pos _ _ _ Px).\nnow rewrite Rmult_plus_distr_r; f_equal; apply ulp_FLX_exact_shift. }\nunfold succ.\nrewrite Rle_bool_false; [|assert (H := bpow_gt_0 beta e); nra].\nrewrite Rle_bool_false; [|now simpl].\nrewrite Ropp_mult_distr_l_reverse, <-Ropp_mult_distr_l_reverse; f_equal.\nunfold pred_pos.\nrewrite mag_mult_bpow; [|lra].\nreplace (_ - 1)%Z with (mag beta (- x) - 1 + e)%Z; [|ring]; rewrite bpow_plus.\nunfold Req_bool; rewrite Rcompare_mult_r; [|now apply bpow_gt_0].\nfold (Req_bool (-x) (bpow (mag beta (-x) - 1))); case Req_bool.\n{ unfold FLX_exp.\nreplace (_ - _)%Z with (mag beta (- x) - 1 - prec + e)%Z; [|ring].\nrewrite bpow_plus; ring. }\nrewrite ulp_FLX_exact_shift; ring.\nQed.\n\n\nGlobal Instance FLX_exp_monotone : Monotone_exp FLX_exp.\nProof. hammer_hook \"FLX\" \"FLX.FLX_exp_monotone\".\nintros ex ey Hxy.\nnow apply Zplus_le_compat_r.\nQed.\n\n\nHypothesis NE_prop : Z.even beta = false \\/ (1 < prec)%Z.\n\nGlobal Instance exists_NE_FLX : Exists_NE beta FLX_exp.\nProof. hammer_hook \"FLX\" \"FLX.exists_NE_FLX\".\ndestruct NE_prop as [H|H].\nnow left.\nright.\nunfold FLX_exp.\nsplit ; omega.\nQed.\n\nEnd RND_FLX.\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/FLX.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.25084912766258755}}
{"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.\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 Mapping.\n\nRequire Import PFStep.\n\nSet Implicit Arguments.\n\n\nModule OrdLocal.\n  Section OrdLocal.\n    Variable L: Loc.t -> bool.\n    Variable ordcr: Ordering.t.\n    Variable ordcw: 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 ordcr else ord)\n        (STEP: Local.read_step lc1 mem1 loc to val released ord' lc2)\n    .\n    Hint Constructors read_step: core.\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 ordcw 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: core.\n\n    Inductive write_na_step (lc1:Local.t) (sc1:TimeMap.t) (mem1:Memory.t)\n                            (loc:Loc.t) (from to:Time.t) (val:Const.t) (ord:Ordering.t)\n                            (lc2:Local.t) (sc2:TimeMap.t) (mem2:Memory.t):\n      forall (msgs: list (Time.t * Time.t * Message.t))\n        (kinds: list Memory.op_kind) (kind:Memory.op_kind), Prop :=\n    | write_na_step_na\n        ord' msgs kinds kind\n        (ORD: ord' = if L loc then Ordering.join ord ordcw else ord)\n        (STEP: Local.write_na_step lc1 sc1 mem1 loc from to val ord' lc2 sc2 mem2 msgs kinds kind):\n      write_na_step lc1 sc1 mem1 loc from to val ord lc2 sc2 mem2 msgs kinds kind\n    | write_na_step_at\n        released ord' kind\n        (LOC: L loc)\n        (NA: Ordering.le ord Ordering.na)\n        (ORD: ord' = Ordering.join ord ordcw)\n        (STEP: Local.write_step lc1 sc1 mem1 loc from to val None released ord' lc2 sc2 mem2 kind):\n      write_na_step lc1 sc1 mem1 loc from to val ord lc2 sc2 mem2 [] [] kind\n    .\n    Hint Constructors write_na_step: core.\n\n    Inductive racy_read_step (lc1:Local.t) (mem1:Memory.t) (loc:Loc.t) (to:Time.t) (val:Const.t) (ord:Ordering.t): Prop :=\n    | racy_read_step_intro\n        ord'\n        (ORD: ord' = if L loc then Ordering.join ord ordcr else ord)\n        (STEP: Local.racy_read_step lc1 mem1 loc to val ord')\n    .\n    Hint Constructors racy_read_step: core.\n\n    Inductive racy_write_step (lc1:Local.t) (mem1:Memory.t) (loc:Loc.t) (to:Time.t) (ord:Ordering.t): Prop :=\n    | racy_write_step_intro\n        ord'\n        (ORD: ord' = if L loc then Ordering.join ord ordcw else ord)\n        (STEP: Local.racy_write_step lc1 mem1 loc to ord')\n    .\n    Hint Constructors racy_write_step: core.\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    | step_write_na\n        lc1 sc1 mem1\n        loc from to val ord lc2 sc2 mem2 msgs kinds kind\n        (LOCAL: write_na_step lc1 sc1 mem1 loc from to val ord lc2 sc2 mem2 msgs kinds kind):\n      program_step (ThreadEvent.write_na loc msgs from to val ord) lc1 sc1 mem1 lc2 sc2 mem2\n    | step_racy_read\n        lc1 sc1 mem1\n        loc to val ord\n        (LOCAL: racy_read_step lc1 mem1 loc to val ord):\n      program_step (ThreadEvent.racy_read loc to val ord) lc1 sc1 mem1 lc1 sc1 mem1\n    | step_racy_write\n        lc1 sc1 mem1\n        loc to val ord\n        (LOCAL: racy_write_step lc1 mem1 loc to ord):\n      program_step (ThreadEvent.racy_write loc to val ord) lc1 sc1 mem1 lc1 sc1 mem1\n    | step_racy_update\n        lc1 sc1 mem1\n        loc to valr valw ordr ordw\n        (LOCAL: Local.racy_update_step lc1 mem1 loc to ordr ordw):\n      program_step (ThreadEvent.racy_update loc to valr valw ordr ordw) lc1 sc1 mem1 lc1 sc1 mem1\n    .\n    Hint Constructors program_step: core.\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      - inv LOCAL.\n        + exploit Local.write_na_step_future; eauto.\n        + exploit Local.write_step_future; eauto. i. des. splits; ss.\n      - esplits; eauto; try refl.\n      - 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. eapply Memory.write_inhabited; eauto.\n      - inv LOCAL2. inv STEP. eapply Memory.write_inhabited; eauto.\n      - inv LOCAL.\n        + inv STEP. eapply Memory.write_na_inhabited; eauto.\n        + inv STEP. eapply Memory.write_inhabited; eauto.\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      - inv LOCAL.\n        + exploit Local.write_na_step_disjoint; eauto.\n        + exploit Local.write_step_disjoint; eauto.\n      - esplits; eauto.\n      - esplits; 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      - eapply Memory.write_na_promises_bot; eauto.\n      - eapply Memory.write_promises_bot; eauto.\n    Qed.\n\n\n    (* reserve only *)\n\n    Definition reserve_only (promises: Memory.t): Prop :=\n      forall loc from to msg\n        (LOC: L loc)\n        (GET: Memory.get loc to promises = Some (from, msg)),\n        msg = Message.reserve.\n\n    Lemma promise_reserve_only\n          promises1 mem1 loc from to msg promises2 mem2 kind\n          (PROMISES1: reserve_only promises1)\n          (LOC: L loc -> msg = Message.reserve)\n          (PROMISE: Memory.promise promises1 mem1 loc from to msg promises2 mem2 kind):\n      reserve_only promises2.\n    Proof.\n      ii. revert GET. inv PROMISE; ss.\n      - erewrite Memory.add_o; eauto. condtac; ss; eauto.\n        i. des. clarify. eauto.\n      - erewrite Memory.split_o; eauto. repeat condtac; ss; eauto.\n        + i. des. clarify. eauto.\n        + guardH o. i. des. clarify.\n          exploit Memory.split_get0; try exact PROMISES. i. des.\n          exploit PROMISES1; eauto.\n      - erewrite Memory.lower_o; eauto. condtac; ss; eauto.\n        i. des. clarify. eauto.\n      - erewrite Memory.remove_o; eauto. condtac; ss; eauto.\n    Qed.\n\n    Lemma write_reserve_only\n          promises1 mem1 loc from to msg promises2 mem2 kind\n          (PROMISES1: reserve_only promises1)\n          (WRITE: Memory.write promises1 mem1 loc from to msg promises2 mem2 kind):\n      reserve_only promises2.\n    Proof.\n      ii. revert GET. inv WRITE.\n      erewrite Memory.remove_o; eauto. condtac; ss. guardH o.\n      inv PROMISE; ss.\n      - erewrite Memory.add_o; eauto. condtac; ss; eauto.\n      - erewrite Memory.split_o; eauto. repeat condtac; ss; eauto.\n        guardH o0. i. des. inv GET.\n        exploit Memory.split_get0; try exact PROMISES. i. des.\n        exploit PROMISES1; try exact GET0; ss.\n      - erewrite Memory.lower_o; eauto. condtac; ss; eauto.\n      - erewrite Memory.remove_o; eauto. condtac; ss; eauto.\n    Qed.\n\n    Lemma write_na_reserve_only\n          ts promises1 mem1 loc from to msg promises2 mem2 msgs kinds kind\n          (PROMISES1: reserve_only promises1)\n          (WRITE: Memory.write_na ts promises1 mem1 loc from to msg promises2 mem2 msgs kinds kind):\n      reserve_only promises2.\n    Proof.\n      induction WRITE; eauto using write_reserve_only.\n    Qed.\n\n    Lemma program_step_reserve_only\n          e lc1 sc1 mem1 lc2 sc2 mem2\n          (PROMISES1: reserve_only (Local.promises lc1))\n          (STEP: program_step e lc1 sc1 mem1 lc2 sc2 mem2):\n      <<PROMISES2: reserve_only (Local.promises lc2)>>.\n    Proof.\n      inv STEP; try inv LOCAL; try inv STEP; ss.\n      - eapply write_reserve_only; eauto.\n      - inv LOCAL1. inv STEP. inv LOCAL2. inv STEP. ss.\n        eapply write_reserve_only; eauto.\n      - eapply write_na_reserve_only; eauto.\n      - eapply write_reserve_only; eauto.\n    Qed.\n\n    Lemma reserve_only_write_add\n          promises1 mem1 loc from to msg promises2 mem2 kind\n          (RESERVE_ONLY: reserve_only promises1)\n          (LOC: L loc)\n          (WRITE: Memory.write promises1 mem1 loc from to msg promises2 mem2 kind):\n      kind = Memory.op_kind_add.\n    Proof.\n      inv WRITE. inv PROMISE; ss; exfalso.\n      - exploit Memory.split_get0; try exact PROMISES. i. des. eauto.\n      - exploit Memory.lower_get0; try exact PROMISES. i. des.\n        exploit RESERVE_ONLY; eauto. i. subst. inv MSG_LE. ss.\n      - exploit Memory.remove_get0; try exact PROMISES. i. des.\n        exploit Memory.remove_get0; try exact REMOVE. i. des. congr.\n    Qed.\n\n    Lemma ordc_na\n          ordc ord loc\n          (ORDC: Ordering.le ordc Ordering.na):\n      (if L loc then Ordering.join ord ordc else ord) = ord.\n    Proof.\n      condtac; ss.\n      destruct ordc, ord; ss.\n    Qed.\n\n    Lemma write_step_le\n          lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind\n          ordc'\n          (STEP: write_step lc1 sc1 mem1 loc from to val releasedm released\n                            (if L loc then Ordering.join ord ordc' else ord) lc2 sc2 mem2 kind)\n          (ORDC: Ordering.le ordc' ordcw):\n      write_step lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind.\n    Proof.\n      econs; eauto.\n      inv STEP. condtac; ss.\n      replace (Ordering.join ord ordcw) with\n          (Ordering.join (Ordering.join ord ordc') ordcw); ss.\n      destruct ord, ordcw, ordc'; ss.\n    Qed.\n\n    Lemma racy_write_step_le\n          lc1 mem1 loc to ord\n          ordc'\n          (STEP: racy_write_step lc1 mem1 loc to (if L loc then Ordering.join ord ordc' else ord))\n          (ORDC: Ordering.le ordc' ordcw):\n      racy_write_step lc1 mem1 loc to ord.\n    Proof.\n      inv STEP. econs; eauto. condtac; ss.\n      replace (Ordering.join ord ordcw) with\n          (Ordering.join (Ordering.join ord ordc') ordcw); ss.\n      destruct ord, ordcw, ordc'; ss.\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 ordcr: Ordering.t.\n    Variable ordcw: 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 ordcr ordcw 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: core.\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: core.\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: core.\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: core.\n\n    Definition tau_step := tau step_allpf.\n    Hint Unfold tau_step: core.\n\n    Definition all_step := union step_allpf.\n    Hint Unfold all_step: core.\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: core.\n\n    Definition steps_failure (e1: Thread.t lang): Prop :=\n      exists e e2 e3,\n        <<STEPS: rtc tau_step e1 e2>> /\\\n        <<STEP_FAILURE: step true e e2 e3>> /\\\n        <<EVENT_FAILURE: ThreadEvent.get_machine_event e = MachineEvent.failure>>.\n    Hint Unfold steps_failure: core.\n\n    Definition consistent (e: Thread.t lang): Prop :=\n      forall mem1\n        (CAP: Memory.cap (Thread.memory e) mem1),\n        <<FAILURE: steps_failure (Thread.mk lang (Thread.state e) (Thread.local e) (Thread.sc e) mem1)>> \\/\n        exists e2,\n          <<STEPS: rtc tau_step (Thread.mk lang (Thread.state e) (Thread.local e) (Thread.sc e) 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        + inv LOCAL0.\n          * eapply write_na_step_promise_consistent; eauto.\n          * eapply write_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_iff ident_map).\n      { eapply ident_map_lt_iff. }\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_iff_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_iff_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. }\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_iff_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_iff_non_collapsable; eauto. }\n          i. des.\n          exists (ThreadEvent.write loc from to val freleasedw ord). esplits.\n          { econs; eauto. eapply mapping_map_lt_iff_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_iff_collapsable_unwritable; eauto. }\n          { refl. }\n          { eapply mapping_map_lt_iff_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_iff_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        { inv LOCAL2.\n          { hexploit write_na_step_map; try eassumption; eauto.\n            { eapply ident_map_bot. }\n            { eapply FLOCAL. }\n            { eapply FLOCAL. }\n            { refl. }\n            { refl. }\n            { eapply mapping_map_lt_iff_non_collapsable; eauto. }\n            { instantiate (1 := List.map fst msgs). clear.\n              induction msgs; ss.\n              econs; eauto. destruct a as [[]]. ss.\n            }\n            { rewrite List.Forall_forall. i.\n              eapply mapping_map_lt_iff_non_collapsable; eauto.\n            }\n            i. des.\n            exists (ThreadEvent.write_na loc fmsgs from to val ord). esplits.\n            { econs; eauto. eapply mapping_map_lt_iff_collapsable_unwritable; eauto. }\n            { econs 2; eauto. econs; eauto. econs 8; eauto. econs; eauto. }\n            { econs; eauto; ss. }\n          }\n          { 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_iff_non_collapsable; eauto. }\n            i. des.\n            exists (ThreadEvent.write_na loc [] from to val ord). esplits.\n            { econs; eauto. eapply mapping_map_lt_iff_collapsable_unwritable; eauto. }\n            { econs 2; eauto. econs; eauto. econs 8; eauto. econs 2; eauto. }\n            { econs; eauto; ss. }\n          }\n        }\n        { inv LOCAL2. exploit racy_read_step_map; eauto.\n          { apply ident_map_lt. }\n          i. des.\n          exists (ThreadEvent.racy_read loc fto val ord). esplits.\n          { econs; eauto. }\n          { econs 2; eauto. econs; eauto. econs 9; eauto. econs; eauto. }\n          { econs; eauto; ss. }\n        }\n        { inv LOCAL2. exploit racy_write_step_map; eauto.\n          { apply ident_map_lt. }\n          i. des.\n          exists (ThreadEvent.racy_write loc fto val ord). esplits.\n          { econs; eauto. }\n          { econs 2; eauto. econs; eauto. econs 10; eauto. econs; eauto. }\n          { econs; eauto; ss. }\n        }\n        { exploit racy_update_step_map; eauto.\n          { apply ident_map_bot. }\n          { apply ident_map_lt. }\n          i. des.\n          exists (ThreadEvent.racy_update loc fto valr valw ordr ordw). esplits.\n          { econs; eauto. }\n          { econs 2; eauto. econs; eauto. econs 11; eauto. }\n          { econs; eauto; ss. }\n        }\n      }\n    Qed.\n\n\n    (* reserve only *)\n\n    Lemma step_reserve_only\n          pf e e1 e2\n          (PROMISES1: OrdLocal.reserve_only L (Local.promises (Thread.local e1)))\n          (STEP: step pf e e1 e2):\n      <<PROMISES2: OrdLocal.reserve_only L (Local.promises (Thread.local e2))>>.\n    Proof.\n      inv STEP; inv STEP0; eauto using OrdLocal.program_step_reserve_only.\n      ii. revert GET. inv LOCAL. inv PROMISE; ss.\n      - erewrite Memory.add_o; eauto. condtac; ss; eauto.\n        i. des. inv GET. exploit PF; eauto.\n      - erewrite Memory.split_o; eauto. repeat condtac; ss; eauto.\n        + i. des. inv GET. exploit PF; eauto.\n        + guardH o. i. des. inv GET.\n          exploit Memory.split_get0; try exact PROMISES. i. des.\n          exploit PF; try exact GET0; eauto.\n      - erewrite Memory.lower_o; eauto. condtac; ss; eauto.\n        i. des. inv GET. exploit PF; eauto.\n      - erewrite Memory.remove_o; eauto. condtac; ss; eauto.\n    Qed.\n\n    Lemma opt_step_reserve_only\n          e e1 e2\n          (PROMISES1: OrdLocal.reserve_only L (Local.promises (Thread.local e1)))\n          (STEP: opt_step e e1 e2):\n      <<PROMISES2: OrdLocal.reserve_only L (Local.promises (Thread.local e2))>>.\n    Proof.\n      inv STEP; eauto.\n      eapply step_reserve_only; eauto.\n    Qed.\n\n    Lemma reserve_step_reserve_only\n          e1 e2\n          (PROMISES1: OrdLocal.reserve_only L (Local.promises (Thread.local e1)))\n          (STEP: @Thread.reserve_step lang e1 e2):\n      <<PROMISES2: OrdLocal.reserve_only L (Local.promises (Thread.local e2))>>.\n    Proof.\n      inv STEP. inv STEP0; inv STEP; inv LOCAL. ss.\n      eapply OrdLocal.promise_reserve_only; eauto.\n    Qed.\n\n    Lemma cancel_step_reserve_only\n          e1 e2\n          (PROMISES1: OrdLocal.reserve_only L (Local.promises (Thread.local e1)))\n          (STEP: @Thread.cancel_step lang e1 e2):\n      <<PROMISES2: OrdLocal.reserve_only L (Local.promises (Thread.local e2))>>.\n    Proof.\n      inv STEP. inv STEP0; inv STEP; inv LOCAL. ss.\n      eapply OrdLocal.promise_reserve_only; eauto.\n    Qed.\n\n    Lemma rtc_tau_step_reserve_only\n          e1 e2\n          (PROMISES1: OrdLocal.reserve_only L (Local.promises (Thread.local e1)))\n          (STEP: rtc tau_step e1 e2):\n      <<PROMISES2: OrdLocal.reserve_only L (Local.promises (Thread.local e2))>>.\n    Proof.\n      induction STEP; eauto.\n      apply IHSTEP. inv H. inv TSTEP.\n      eapply step_reserve_only; eauto.\n    Qed.\n\n    Lemma rtc_all_step_reserve_only\n          e1 e2\n          (PROMISES1: OrdLocal.reserve_only L (Local.promises (Thread.local e1)))\n          (STEP: rtc all_step e1 e2):\n      <<PROMISES2: OrdLocal.reserve_only L (Local.promises (Thread.local e2))>>.\n    Proof.\n      induction STEP; eauto.\n      apply IHSTEP. inv H. inv USTEP.\n      eapply step_reserve_only; eauto.\n    Qed.\n\n    Lemma rtc_reserve_step_reserve_only\n          e1 e2\n          (PROMISES1: OrdLocal.reserve_only L (Local.promises (Thread.local e1)))\n          (STEP: rtc (@Thread.reserve_step lang) e1 e2):\n      <<PROMISES2: OrdLocal.reserve_only L (Local.promises (Thread.local e2))>>.\n    Proof.\n      induction STEP; eauto.\n      apply IHSTEP.\n      eapply reserve_step_reserve_only; eauto.\n    Qed.\n\n    Lemma rtc_cancel_step_reserve_only\n          e1 e2\n          (PROMISES1: OrdLocal.reserve_only L (Local.promises (Thread.local e1)))\n          (STEP: rtc (@Thread.cancel_step lang) e1 e2):\n      <<PROMISES2: OrdLocal.reserve_only L (Local.promises (Thread.local e2))>>.\n    Proof.\n      induction STEP; eauto.\n      apply IHSTEP.\n      eapply cancel_step_reserve_only; eauto.\n    Qed.\n  End OrdThread.\nEnd OrdThread.\n\n\nModule OrdConfiguration.\n  Section OrdConfiguration.\n    Variable L: Loc.t -> bool.\n    Variable ordcr: Ordering.t.\n    Variable ordcw: 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 ordcr ordcw e e2 e3)\n        (RESERVES: rtc (@Thread.reserve_step _) e3 (Thread.mk _ st4 lc4 sc4 memory4))\n        (CONSISTENT: ThreadEvent.get_machine_event e <> MachineEvent.failure ->\n                     OrdThread.consistent L ordcr ordcw (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: core.\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: core.\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: core.\n\n\n    (* reserve_only *)\n\n    Definition reserve_only (c: Configuration.t): Prop :=\n      forall tid lang st lc\n        (FIND: IdentMap.find tid (Configuration.threads c) = Some (existT _ lang st, lc)),\n        OrdLocal.reserve_only L (Local.promises lc).\n\n    Lemma init_reserve_only s:\n      reserve_only (Configuration.init s).\n    Proof.\n      ii. unfold Configuration.init, Threads.init in *. ss.\n      rewrite IdentMap.Facts.map_o in *.\n      destruct (@UsualFMapPositive.UsualPositiveMap'.find\n                  (@sigT _ (@Language.syntax ProgramEvent.t)) tid s); inv FIND.\n      ss. rewrite Memory.bot_get in *. ss.\n    Qed.\n\n    Lemma step_reserve_only\n          tid e c1 c2\n          (RESERVE: reserve_only c1)\n          (STEP: step tid e c1 c2):\n      reserve_only c2.\n    Proof.\n      inv STEP. ii. ss.\n      revert FIND. rewrite IdentMap.gsspec. condtac; ss; i; cycle 1.\n      { eapply RESERVE; eauto. }\n      inv FIND. apply inj_pair2 in H1. subst.\n      unfold reserve_only in RESERVE.\n      hexploit RESERVE; eauto. i.\n      hexploit OrdThread.rtc_cancel_step_reserve_only; try exact CANCELS; eauto. i.\n      hexploit OrdThread.opt_step_reserve_only; try exact STEP0; eauto. i.\n      hexploit OrdThread.rtc_reserve_step_reserve_only; try exact RESERVES; eauto.\n    Qed.\n\n    Lemma rtc_all_step_reserve_only\n          c1 c2\n          (RESERVE: reserve_only c1)\n          (STEPS: rtc all_step c1 c2):\n      reserve_only c2.\n    Proof.\n      induction STEPS; ss. inv H.\n      hexploit step_reserve_only; eauto.\n    Qed.\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                       (@OrdThread.all_step _ L ordcr ordcw)\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. inv H.\n          inv STEP.\n          2:{ inv STEP1; inv LOCAL. }\n          econs; eauto. econs; eauto. econs 1; eauto. ii. clarify.\n        }\n        etrans.\n        { instantiate (1:=e3). inv STEP0.\n          { refl. }\n          { econs 2; [|refl]. econs; eauto. econs; eauto. }\n        }\n        { eapply rtc_implies; try apply RESERVES. i. inv H.\n          inv STEP.\n          2:{ inv STEP1; inv LOCAL. }\n          econs; eauto. econs; eauto. econs 1; eauto. ii. clarify.\n        }\n      }\n      exploit OrdThread.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 OrdThread.rtc_all_step_disjoint; eauto. i. des.\n          symmetry. auto.\n        * exploit THREADS; try apply TH2; eauto. i. des.\n          exploit OrdThread.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 OrdThread.rtc_all_step_disjoint; eauto. i. des.\n        auto.\n    Qed.\n\n    Lemma rtc_all_step_future\n          c1 c2\n          (STEP: 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      induction STEP; i.\n      { splits; auto; try refl. }\n      { inv H. hexploit step_future; eauto. i. des.\n        hexploit IHSTEP; eauto. i. des. splits; auto.\n        { etrans; eauto. }\n        { etrans; eauto. }\n      }\n    Qed.\n  End OrdConfiguration.\nEnd OrdConfiguration.\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/ldrfra/OrdStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.3415824927356586, "lm_q1q2_score": 0.2507623779644869}}
{"text": "(*\n * Copyright (c) 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 *)\nRequire Export iris.bi.embedding.\nRequire Import bedrock.lang.bi.prelude.\n\n(** * Composing embeddings *)\n(** Given embeddings [Embed PROP1 PROP2] and [Embed PROP2 PROP3],\n[compose_embed PROP2] is the induced embedding [Embed PROP1 PROP3].\nIts [BiEmbed], etc instances are available after [Import\ncompose_embed_instances]. *)\n\nDefinition compose_embed_def {A B C} `{!Embed B C, !Embed A B} : Embed A C :=\n  λ P, embed (embed P).\nDefinition compose_embed_aux : seal (@compose_embed_def). Proof. by eexists. Qed.\nDefinition compose_embed := compose_embed_aux.(unseal).\nDefinition compose_embed_eq : @compose_embed = _ := compose_embed_aux.(seal_eq).\n#[global] Arguments compose_embed\n  {_}%type_scope _%type_scope {_}%type_scope {_ _} _%bi_scope : assert.\n\nSection instances.\n  Context {PROP1 PROP2 PROP3 : bi}.\n  Context `{!BiEmbed PROP2 PROP3, !BiEmbed PROP1 PROP2}.\n\n  #[local] Ltac unseal :=\n    unfold embed, bi_embed_embed; cbn;\n    rewrite !compose_embed_eq; unfold compose_embed_def; cbn.\n\n  Lemma compose_embedding_mixin : BiEmbedMixin PROP1 PROP3 (compose_embed PROP2).\n  Proof.\n    split.\n    - intros n P1 P2 ?. unseal. solve_proper.\n    - intros P1 P2 ?. unseal. solve_proper.\n    - intros P. unseal. by rewrite !embed_emp_valid.\n    - intros. unseal. by rewrite !embed_interal_inj. \n    - unseal. by rewrite !embed_emp_2.\n    - intros. unseal. by rewrite !embed_impl_2.\n    - intros. unseal. by rewrite !embed_forall_2.\n    - intros. unseal. by rewrite !embed_exist_1.\n    - intros. unseal. by rewrite !embed_sep.\n    - intros. unseal. by rewrite !embed_wand_2.\n    - intros. unseal. by rewrite !embed_persistently.\n  Qed.\n  #[local] Instance compose_embedding : BiEmbed PROP1 PROP3 :=\n    {| bi_embed_mixin := compose_embedding_mixin |}.\n\n  Lemma embed_embed P : embed P ⊣⊢@{PROP3} embed (embed P).\n  Proof. rewrite {1}/embed/bi_embed_embed/=. by rewrite compose_embed_eq. Qed.\n\n  #[local] Instance compose_embed_emp\n      `{!BiEmbedEmp PROP2 PROP3, !BiEmbedEmp PROP1 PROP2} :\n    BiEmbedEmp PROP1 PROP3.\n  Proof. rewrite/BiEmbedEmp. by rewrite embed_embed !embed_emp_1. Qed.\n\n  #[local] Instance compose_embed_later\n      `{!BiEmbedLater PROP2 PROP3, !BiEmbedLater PROP1 PROP2} :\n    BiEmbedLater PROP1 PROP3.\n  Proof. intros P. by rewrite !embed_embed !embed_later. Qed.\n\n  #[local] Instance compose_embed_internal_eq\n      `{!BiInternalEq PROP1, !BiInternalEq PROP2, !BiInternalEq PROP3}\n      `{!BiEmbedInternalEq PROP2 PROP3, !BiEmbedInternalEq PROP1 PROP2} :\n    BiEmbedInternalEq PROP1 PROP3.\n  Proof. intros A x y. by rewrite embed_embed !embed_internal_eq_1. Qed.\n\n  #[local] Instance compose_embed_bupd\n      `{!BiBUpd PROP1, !BiBUpd PROP2, !BiBUpd PROP3}\n      `{!BiEmbedBUpd PROP2 PROP3, !BiEmbedBUpd PROP1 PROP2} :\n    BiEmbedBUpd PROP1 PROP3.\n  Proof. intros P. by rewrite !embed_embed !embed_bupd. Qed.\n\n  #[local] Instance compose_embed_fupd\n      `{!BiFUpd PROP1, !BiFUpd PROP2, !BiFUpd PROP3}\n      `{!BiEmbedFUpd PROP2 PROP3, !BiEmbedFUpd PROP1 PROP2} :\n    BiEmbedFUpd PROP1 PROP3.\n  Proof. intros E1 E2 P. by rewrite !embed_embed !embed_fupd. Qed.\n\n  #[local] Instance compose_embed_plainly\n      `{!BiPlainly PROP1, !BiPlainly PROP2, !BiPlainly PROP3}\n      `{!BiEmbedPlainly PROP2 PROP3, !BiEmbedPlainly PROP1 PROP2} :\n    BiEmbedPlainly PROP1 PROP3.\n  Proof. intros P. by rewrite !embed_embed !embed_plainly. Qed.\nEnd instances.\n\nModule compose_embed_instances.\n  #[export] Hint Resolve\n    compose_embedding\n    compose_embed_emp\n    compose_embed_later\n    compose_embed_internal_eq\n    compose_embed_bupd\n    compose_embed_fupd\n    compose_embed_plainly\n  : typeclass_instances.\nEnd compose_embed_instances.\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/bi/embedding.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2505741462415942}}
{"text": "Require Import GHC.Base.\nImport GHC.Base.Notations.\nRequire Import Proofs.GHC.Base.\nRequire Import Data.Map.Internal.\nImport GHC.Num.Notations.\nRequire Import OrdTactic.\nRequire Import Psatz.\nRequire Import Tactics.\nSet Bullet Behavior \"Strict Subproofs\".\nRequire Import MapProofs.Bounds.\nRequire Import MapProofs.Tactics.\nRequire Import MapProofs.InsertProofs.\nRequire Import MapProofs.ToListProofs.\nRequire Import MapProofs.UnionIntersectDifferenceProofs.\nRequire Import Coq.Sorting.Sorted.\nRequire Import SortedUtil.\nRequire Import Coq.Program.Tactics.\nRequire Import GHC.DeferredFix.\nRequire Import Coq.Wellfounded.Wellfounded.\n\n\nSection WF.\nContext {e : Type} {a : Type} {HEq : Eq_ e} {HOrd : Ord e} {HEqLaws : EqLaws e}  {HOrdLaws : OrdLaws e}.\n\n(** ** Verification of [fromDistinctAscList] *)\n\n\n\nDefinition fromDistinctAscList_create_f : (Int -> list (e * a) -> (Map e a) * list (e * a)) -> \n(Int -> list (e * a) -> Map e a * list ( e * a)).\nProof.\n  let rhs := eval unfold fromDistinctAscList in (@fromDistinctAscList e a) in\n  lazymatch rhs with context [deferredFix2 ?f] => exact f end.\nDefined.\n\nDefinition fromDistinctAscList_create : Int -> list (e * a) -> (Map e a) * list (e * a)\n  := deferredFix2 (fromDistinctAscList_create_f).\n\nLemma Z_shiftr_pos:\n  forall x, (1 < x -> 1 <= Z.shiftr x 1)%Z.\nProof.\n  intros.\n  rewrite Z.shiftr_div_pow2 by lia.\n  replace (2^1)%Z with 2%Z by reflexivity.\n  assert (2 <= x)%Z by lia. clear H.\n  apply Z.div_le_mono with (c := 2%Z) in H0.\n  apply H0.\n  lia.\nQed.\n\nLemma Z_shiftl_pos:\n  forall x, (1 <= x -> 1 <= Z.shiftl x 1)%Z.\nProof.\n  intros.\n  rewrite Z.shiftl_mul_pow2 by lia.\n  lia.\nQed.\n\nLemma Z_shiftr_lt:\n  forall x, (1 <= x -> Z.shiftr x 1 < x)%Z.\nProof.\n  intros.\n  rewrite Z.shiftr_div_pow2 by lia.\n  replace (2^1)%Z with 2%Z by reflexivity.\n  apply Z_div_lt; lia.\nQed.\n\n\n\nLemma fromDistinctAscList_create_eq:\n  forall i xs, (1 <= i)%Z ->\n  fromDistinctAscList_create i xs = fromDistinctAscList_create_f fromDistinctAscList_create i xs.\nProof.\n  intros.\n  change (uncurry fromDistinctAscList_create (i, xs) = uncurry (fromDistinctAscList_create_f fromDistinctAscList_create) (i, xs)).\n  apply deferredFix_eq_on with\n    (f := fun g => uncurry (fromDistinctAscList_create_f (curry g)))\n    (P := fun p => (1 <= fst p)%Z)\n    (R := fun x y => (1 <= fst x < fst y)%Z).\n  * eapply wf_inverse_image with (R := fun x y => (1 <= x < y)%Z).\n    apply Z.lt_wf with (z := 1%Z).\n  * clear i xs H.\n    intros g h x Px Heq.\n    destruct x as [i xs]. simpl in *.\n    unfold fromDistinctAscList_create_f.\n    destruct_match; try reflexivity.\n    repeat replace (#1) with 1%Z by reflexivity.\n    unfold op_zeze__, Eq_Integer___, op_zeze____.\n    destruct (Z.eqb_spec i 1); try reflexivity.\n    unfold curry.\n    assert (1 < i)%Z by lia.\n    assert (1 <= Z.shiftr i 1)%Z by (apply Z_shiftr_pos; lia).\n    assert (Z.shiftr i 1 < i)%Z by (apply Z_shiftr_lt; lia).\n    repeat expand_pairs. simpl.\n    rewrite Heq by eauto.\n    destruct_match; try reflexivity.\n    rewrite Heq by eauto.\n    reflexivity.\n  * simpl; lia.\nQed.\n\nCheck length.\n(* We need to know that [create] returns no longer list than it receives. *)\nProgram Fixpoint fromDistinctAscList_create_preserves_length\n  i xs {measure (Z.to_nat i)} :\n  (1 <= i)%Z ->\n  forall (P : Map e a * list (e * a) -> Prop),\n  ( forall s ys,\n    (length ys <= length xs)%nat ->\n    P (s, ys)\n  ) ->\n  P (fromDistinctAscList_create i xs) := _.\nNext Obligation.\n  intros.\n  rename fromDistinctAscList_create_preserves_length into IH.\n  rewrite fromDistinctAscList_create_eq by assumption.\n  unfold fromDistinctAscList_create_f.\n  destruct xs.\n  * apply H0. reflexivity.\n  * repeat replace (#1) with 1%Z by reflexivity.\n    unfold op_zeze__, Eq_Integer___, op_zeze____.\n    destruct (Z.eqb_spec i 1).\n    + destruct p. apply H0. simpl. lia.\n    + assert (Z.to_nat (Bits.shiftR i #1) < Z.to_nat i)%nat. {\n        apply Z2Nat.inj_lt.\n        apply Z.shiftr_nonneg. lia.\n        lia.\n        apply Z_shiftr_lt; lia.\n      }\n      apply IH.\n      - assumption. \n      - apply Z_shiftr_pos; lia.\n      - intros.\n        destruct_match.\n        ** apply H0. simpl in *. lia.\n        ** apply IH.\n           -- assumption.\n           -- apply Z_shiftr_pos; lia.\n           -- intros.\n               destruct p0. apply H0. simpl in *. lia.\nQed.\n\nDefinition fromDistinctAscList_go_f : (Int -> Map e a -> list (e * a) -> Map e a) ->\n (Int -> Map e a -> list (e * a) -> Map e a).\nProof.\n  let rhs := eval unfold fromDistinctAscList in (@fromDistinctAscList e a) in\n  let rhs := eval fold fromDistinctAscList_create_f in rhs in \n  let rhs := eval fold fromDistinctAscList_create in rhs in \n  lazymatch rhs with context [deferredFix3 ?f] => exact f end.\nDefined.\n\nDefinition fromDistinctAscList_go : Int -> Map e a -> list (e * a) -> Map e a\n  := deferredFix3 (fromDistinctAscList_go_f).\n\nLemma fromDistinctAscList_go_eq:\n  forall i s xs, (0 < i)%Z ->\n  fromDistinctAscList_go i s xs = fromDistinctAscList_go_f fromDistinctAscList_go i s xs.\nProof.\n  intros.\n  change (deferredFix (fun g => uncurry (uncurry (fromDistinctAscList_go_f (curry (curry g))))) (i, s, xs) =\n    uncurry (uncurry (fromDistinctAscList_go_f fromDistinctAscList_go)) (i, s, xs)).\n  rewrite deferredFix_eq_on with\n    (P := fun p => (1 <= fst (fst p))%Z)\n    (R := fun x y => (length (snd x) < length (snd y))%nat); only 1: reflexivity.\n  * apply well_founded_ltof with (f := fun x => length (snd x)).\n  * intros g h p Px Heq.\n    destruct p as [[x y] z].\n    simpl in *.\n    unfold fromDistinctAscList_go_f.\n    destruct_match; try reflexivity.\n    eapply fromDistinctAscList_create_preserves_length; try lia.\n    intros s' ys Hlength. destruct p.\n    apply Heq.\n    + apply Z_shiftl_pos.\n      lia.\n    + simpl. lia.\n  * simpl. lia.\nQed.\n\nDefinition safeHd {a} : list (e * a) -> option e := fun xs =>\n  match xs with nil => None | ((x, y)::_) => Some x end.\n\nLemma mul_pow_sub:\n  forall sz, (0 < sz)%Z -> (2 * 2 ^ (sz - 1) = 2^sz)%Z.\nProof.\n  intros.\n  rewrite <- Z.pow_succ_r by lia.\n  f_equal.\n  lia.\nQed.\n\n\n\n(*Maps are sorted only by keys*)\nLocal Definition lt : e * a -> e * a -> Prop\n  := fun x1 x2 => let (e1, a1) := x1 in let (e2, a2) := x2 in ( _GHC.Base.<_ e1 e2) = true.\n\nLocal Obligation Tactic := try solve [program_simpl].\n\n(*TODO: FIGURE OUT WHY THIS IS NOT WORKING*)\nProgram Fixpoint fromDistinctAscList_create_Desc\n  sz lb xs x {measure (Z.to_nat sz)} :\n  (0 <= sz)%Z ->\n  StronglySorted lt ((lb, x) :: xs) ->\n  forall (P : (Map e a) * list (e * a) -> Prop),\n  (( forall (s : Map e a) (ys: list (e * a)),\n    Bounded s (Some lb) (safeHd ys) ->\n    xs = toList s ++ ys ->\n    ys = nil \\/ size s = (2*2^sz-1)%Z ->\n    P (s, ys)\n  ) ->\n  P (fromDistinctAscList_create (2^sz)%Z xs)) := _.\nNext Obligation.\n  intros ????? Hnonneg HSorted.  \n  rename fromDistinctAscList_create_Desc into IH.\n  rewrite fromDistinctAscList_create_eq\n    by (enough (0 < 2^sz)%Z by lia; apply Z.pow_pos_nonneg; lia).\n  unfold fromDistinctAscList_create_f.\n  destruct xs.\n  * intros X HX. apply HX. clear HX.\n    - solve_Bounded e.\n    - reflexivity.\n    - left. reflexivity.\n  * repeat replace (#1) with 1%Z by reflexivity.\n    unfold op_zeze__, Eq_Integer___, op_zeze____.\n\n    inversion HSorted. subst.\n    inversion H2. subst. clear H2.\n    inversion H1. subst.\n    destruct p.\n    assert (isUB (safeHd xs) e0 = true). {\n      destruct xs; try reflexivity.\n      inversion H5. subst. unfold safeHd. destruct p. assumption. } \n    \n    destruct (Z.eqb_spec (2^sz) 1).\n    - intros X HX. apply HX. clear HX.\n      ++ solve_Bounded e.\n      ++ rewrite toList_Bin, toList_Tip, app_nil_r. reflexivity.\n      ++ right. rewrite size_Bin. lia.\n    - assert (~ (sz = 0))%Z by (intro; subst; simpl in n; congruence).\n      assert (sz > 0)%Z by lia.\n      replace ((Bits.shiftR (2 ^ sz)%Z 1%Z)) with (2^(sz - 1))%Z.\n      Focus 2.\n        unfold Bits.shiftR, Bits.instance_Bits_Int.\n        rewrite Z.shiftr_div_pow2 by lia.\n        rewrite Z.pow_sub_r by lia.\n        reflexivity.\n      assert (Z.to_nat (sz - 1) < Z.to_nat sz)%nat.\n      { rewrite Z2Nat.inj_sub by lia. \n        apply Nat.sub_lt.\n        apply Z2Nat.inj_le.\n        lia.\n        lia.\n        lia. \n        replace (Z.to_nat 1) with 1 by reflexivity.\n        lia.\n      }\n      eapply IH.\n      ++ assumption.\n      ++ lia.\n      ++ eassumption.\n      ++ intros l ys HBounded_l Hlist_l Hsize_l.\n         destruct ys.\n         + intros X HX. apply HX. clear HX.\n           ** solve_Bounded e.\n           ** assumption.\n           ** left; reflexivity.\n         + simpl in HBounded_l. destruct p.\n           destruct Hsize_l; try congruence.\n           eapply IH; clear IH.\n           ** assumption.\n           ** lia.\n           ** rewrite Hlist_l in H1. \n              apply StronglySorted_app in H1.\n              destruct H1. \n              eassumption.\n           ** intros r zs HBounded_r Hlist_r Hsize_r.\n              rewrite Hlist_l in HSorted.\n              assert (isLB (Some lb) e1 = true). {\n                apply StronglySorted_inv in HSorted.\n                destruct HSorted.\n                simpl.\n                rewrite Forall_forall in H10. unfold lt in H10.\n                specialize (H10 (e1, a1)). \n                apply H10.\n                apply in_or_app. right. left. reflexivity.\n              }\n              rewrite Hlist_r in HSorted.\n              assert (isUB (safeHd zs) e1 = true). {\n                destruct zs; try reflexivity.\n                apply StronglySorted_inv in HSorted.\n                destruct HSorted.\n                apply StronglySorted_app in H10.\n                destruct H10.\n                apply StronglySorted_inv in H12.\n                destruct H12.\n                rewrite Forall_forall in H13. specialize (H13 p). unfold isUB. simpl. destruct p.\n                unfold lt in H13.\n                apply H13.\n                apply in_or_app. right. left. reflexivity.\n              }\n              intros X HX. apply HX. clear HX.\n              -- applyDesc e (@link_Desc e a).\n              -- erewrite toList_link by eassumption.\n                 rewrite Hlist_l. rewrite Hlist_r.\n                 rewrite <- !app_assoc.  reflexivity.\n              -- destruct Hsize_r; [left; assumption| right].\n                 applyDesc e (@link_Desc e a).\n                 replace (size l). replace (size r).\n                 rewrite mul_pow_sub in * by lia.\n                 lia.\nQed.\n\n(*The analogue of [sem] for lists - returns the first value associated with\na given key, or None if no such key exists. We will use this to\nspecify several lemmas in [fromList] rather than List.elem*)\nFixpoint sem_for_lists (l : list (e * a)) (i : e) :=\n  match l with\n  | nil => None\n  | (x,y) :: t => if i == x then Some y else sem_for_lists t i\n  end.\n\nLemma sem_list_app: forall i xs ys,\n  sem_for_lists (xs ++ ys) i = sem_for_lists xs i ||| sem_for_lists ys i.\nProof.\n  intros. generalize dependent ys. induction xs; intros.\n  - simpl. reflexivity.\n  - simpl. destruct a0. destruct (i == e0) eqn : ?. reflexivity.\n    apply IHxs.\nQed.\n\nLemma toList_sem'':\n  forall s lb ub, Bounded s lb ub ->\n  forall i, sem s i = sem_for_lists (toList s) i.\nProof.\n  intros. induction H.\n  - simpl. reflexivity.\n  - simpl. rewrite IHBounded1. rewrite IHBounded2. rewrite toList_Bin.\n    rewrite sem_list_app. rewrite app_comm_cons. rewrite sem_list_app.\n    simpl. unfold SomeIf. rewrite oro_assoc. reflexivity.\nQed. \n\nProgram Fixpoint fromDistinctAscList_go_Desc\n  sz s xs {measure (length xs)} :\n  (0 <= sz)%Z ->\n  StronglySorted lt xs ->\n  Bounded s None (safeHd xs) ->\n  xs = nil \\/ size s = (2*2^sz-1)%Z ->\n  Desc (fromDistinctAscList_go (2^sz)%Z s xs) None None (size s + List.length xs)\n    (fun i => sem s i ||| sem_for_lists xs i) := _. \nNext Obligation.\n  intros.\n  rename fromDistinctAscList_go_Desc into IH.\n  rewrite fromDistinctAscList_go_eq by (apply Z.pow_pos_nonneg; lia).\n  unfold fromDistinctAscList_go_f.\n  destruct xs.\n  * replace (List.length nil) with 0%Z by reflexivity.\n    rewrite Z.add_0_r.\n    solve_Desc e.\n  * repeat replace (#1) with 1%Z by reflexivity.\n    replace ((Bits.shiftL (2 ^ sz)%Z 1))%Z with (2 ^ (1 + sz))%Z.\n    Focus 2.\n      unfold Bits.shiftL, Bits.instance_Bits_Int.\n      rewrite Z.shiftl_mul_pow2 by lia.\n      rewrite Z.pow_add_r by lia.\n      lia. destruct p.\n\n    destruct H2; try congruence.\n    eapply fromDistinctAscList_create_Desc.\n    - lia.\n    - eassumption.\n    - intros.\n      subst.\n      simpl safeHd in *.\n      assert (isUB (safeHd ys) e0 = true). {\n        destruct ys; try reflexivity.\n        apply StronglySorted_inv in H0.\n        destruct H0.\n        rewrite Forall_forall in H4. specialize (H4 p). unfold isUB. destruct p. simpl.\n        unfold lt in H4.\n        apply H4. \n        apply in_or_app. right. left. reflexivity.\n      }      \n      applyDesc e (@link_Desc e a).\n      eapply IH.\n      + simpl. rewrite app_length. lia.\n      + lia.\n      + apply StronglySorted_inv in H0.\n        destruct H0.\n        apply StronglySorted_app in H0.\n        destruct H0.\n        assumption.\n      + assumption.\n      + destruct H5; [left; assumption | right].\n        replace (size s1). replace (size s).  replace (size s0).\n        rewrite Z.pow_add_r by lia.\n        lia.\n      + intros.\n        solve_Desc e.\n        ** replace (size s2). replace (size s1). replace (size s).\n           rewrite !List.hs_coq_list_length, !Zlength_correct.\n           simpl length.\n           rewrite app_length, Nat2Z.inj_succ, Nat2Z.inj_add.\n           erewrite <- size_spec by eassumption.\n           lia.\n        ** simpl. \n           setoid_rewrite sem_list_app.\n           setoid_rewrite <- toList_sem''; only 2: eassumption.\n           f_solver e.\nQed.\n\nLemma fromDistinctAscList_Desc:\n  forall xs,\n  StronglySorted lt xs ->\n  Desc (fromDistinctAscList xs) None None (List.length xs) (fun i => sem_for_lists xs i).\nProof.\n  intros.\n  unfold fromDistinctAscList.\n  fold fromDistinctAscList_create_f.\n  fold fromDistinctAscList_create.\n  fold fromDistinctAscList_go_f.\n  fold fromDistinctAscList_go.\n  destruct xs.\n  * solve_Desc e.\n  * replace (#1) with (2^0)%Z by reflexivity. destruct p.\n    eapply fromDistinctAscList_go_Desc.\n    + lia.\n    + apply StronglySorted_inv in H.\n      destruct H.\n      assumption.\n    + assert (isUB (safeHd xs) e0 = true). {\n        destruct xs; try reflexivity.\n        apply StronglySorted_inv in H.\n        destruct H.\n        rewrite Forall_forall in H0. destruct p. unfold isUB. simpl.\n        unfold lt in H0. specialize (H0 (e1, a1)). \n        apply H0.\n        left. reflexivity.\n      }\n      solve_Bounded e.\n    + right. reflexivity.\n    + intros.\n      rewrite List.hs_coq_list_length, Zlength_cons in *.\n      rewrite size_Bin in H1.\n      solve_Desc e. simpl. f_solver e.\nQed.\n\n(** ** Verification of [fromDistinctDescList] *)\n\n(** Copy’n’paste from [fromDistinctAscList] *)\n\nLocal Definition gt : e * a -> e * a -> Prop\n  := fun x1 x2 => let (e1, a1) := x1 in let (e2, a2) := x2 in (e1 > e2) = true.\n\nDefinition fromDistinctDescList_create_f : (Int -> list (e * a) -> (Map e a) * list (e * a)) -> \n(Int -> list (e * a) -> Map e a * list ( e * a)).\nProof.\n  let rhs := eval unfold fromDistinctDescList in (@fromDistinctDescList e a) in\n  lazymatch rhs with context [deferredFix2 ?f] => exact f end.\nDefined.\n\nDefinition fromDistinctDescList_create : Int -> list (e * a) -> (Map e a) * list (e * a)\n  := deferredFix2 (fromDistinctDescList_create_f).\n\nLemma fromDistinctDescList_create_eq:\n  forall i xs, (1 <= i)%Z ->\n  fromDistinctDescList_create i xs = fromDistinctDescList_create_f fromDistinctDescList_create i xs.\nProof.\n  intros.\n  change (uncurry fromDistinctDescList_create (i, xs) = uncurry (fromDistinctDescList_create_f fromDistinctDescList_create) (i, xs)).\n  apply deferredFix_eq_on with\n    (f := fun g => uncurry (fromDistinctDescList_create_f (curry g)))\n    (P := fun p => (1 <= fst p)%Z)\n    (R := fun x y => (1 <= fst x < fst y)%Z).\n  * eapply wf_inverse_image with (R := fun x y => (1 <= x < y)%Z).\n    apply Z.lt_wf with (z := 1%Z).\n  * clear i xs H.\n    intros g h x Px Heq.\n    destruct x as [i xs]. simpl in *.\n    unfold fromDistinctDescList_create_f.\n    destruct_match; try reflexivity.\n    repeat replace (#1) with 1%Z by reflexivity.\n    unfold op_zeze__, Eq_Integer___, op_zeze____.\n    destruct (Z.eqb_spec i 1); try reflexivity.\n    unfold curry.\n    assert (1 < i)%Z by lia.\n    assert (1 <= Z.shiftr i 1)%Z by (apply Z_shiftr_pos; lia).\n    assert (Z.shiftr i 1 < i)%Z by (apply Z_shiftr_lt; lia).\n    repeat expand_pairs. simpl.\n    rewrite Heq by eauto.\n    destruct_match; try reflexivity.\n    rewrite Heq by eauto.\n    reflexivity.\n  * simpl; lia.\nQed.\n\n(* We need to know that [create] returns no longer list than it receives. *)\nProgram Fixpoint fromDistinctDescList_create_preserves_length\n  i xs {measure (Z.to_nat i)} :\n  (1 <= i)%Z ->\n  forall (P : Map e a * list (e * a) -> Prop),\n  ( forall s ys,\n    (length ys <= length xs)%nat ->\n    P (s, ys)\n  ) ->\n  P (fromDistinctDescList_create i xs) := _.\nNext Obligation.\n  intros.\n  rename fromDistinctDescList_create_preserves_length into IH.\n  rewrite fromDistinctDescList_create_eq by assumption.\n  unfold fromDistinctDescList_create_f.\n  destruct xs.\n  * apply H0. reflexivity.\n  * repeat replace (#1) with 1%Z by reflexivity.\n    unfold op_zeze__, Eq_Integer___, op_zeze____.\n    destruct (Z.eqb_spec i 1).\n    + destruct p. apply H0. simpl. lia.\n    + assert (Z.to_nat (Bits.shiftR i #1) < Z.to_nat i)%nat. {\n        apply Z2Nat.inj_lt.\n        apply Z.shiftr_nonneg. lia.\n        lia.\n        apply Z_shiftr_lt; lia.\n      }\n      apply IH.\n      - assumption. \n      - apply Z_shiftr_pos; lia.\n      - intros.\n        destruct_match.\n        ** apply H0. simpl in *. lia.\n        ** apply IH.\n           -- assumption.\n           -- apply Z_shiftr_pos; lia.\n           -- intros.\n               destruct p0. apply H0. simpl in *. lia.\nQed.\n\nDefinition fromDistinctDescList_go_f : (Int -> Map e a -> list (e * a) -> Map e a) ->\n (Int -> Map e a -> list (e * a) -> Map e a).\nProof.\n  let rhs := eval unfold fromDistinctDescList in (@fromDistinctDescList e a) in\n  let rhs := eval fold fromDistinctDescList_create_f in rhs in \n  let rhs := eval fold fromDistinctDescList_create in rhs in \n  lazymatch rhs with context [deferredFix3 ?f] => exact f end.\nDefined.\n\nDefinition fromDistinctDescList_go : Int -> Map e a -> list (e * a) -> Map e a\n  := deferredFix3 (fromDistinctDescList_go_f).\n\nLemma fromDistinctDescList_go_eq:\n  forall i s xs, (0 < i)%Z ->\n  fromDistinctDescList_go i s xs = fromDistinctDescList_go_f fromDistinctDescList_go i s xs.\nProof.\n  intros.\n  change (deferredFix (fun g => uncurry (uncurry (fromDistinctDescList_go_f (curry (curry g))))) (i, s, xs) =\n    uncurry (uncurry (fromDistinctDescList_go_f fromDistinctDescList_go)) (i, s, xs)).\n  rewrite deferredFix_eq_on with\n    (P := fun p => (1 <= fst (fst p))%Z)\n    (R := fun x y => (length (snd x) < length (snd y))%nat); only 1: reflexivity.\n  * apply well_founded_ltof with (f := fun x => length (snd x)).\n  * intros g h p Px Heq.\n    destruct p as [[x y] z].\n    simpl in *.\n    unfold fromDistinctDescList_go_f.\n    destruct_match; try reflexivity.\n    eapply fromDistinctDescList_create_preserves_length; try lia.\n    intros s' ys Hlength. destruct p.\n    apply Heq.\n    + apply Z_shiftl_pos.\n      lia.\n    + simpl. lia.\n  * simpl. lia.\nQed.\n\nProgram Fixpoint fromDistinctDescList_create_Desc\n  sz ub xs x {measure (Z.to_nat sz)} :\n  (0 <= sz)%Z ->\n  StronglySorted (fun x y => gt x y) ((ub, x) :: xs) ->\n  forall (P : (Map e a) * list (e * a) -> Prop),\n  ( forall (s : Map e a) (ys: list (e * a)),\n    Bounded s  (safeHd ys) (Some ub)->\n    xs = rev(toList s) ++ ys ->\n    ys = nil \\/ size s = (2*2^sz-1)%Z ->\n    P (s, ys)\n  ) ->\n  P (fromDistinctDescList_create (2^sz)%Z xs) := _.\nNext Obligation.\n  intros ????? Hnonneg HSorted.  \n  rename fromDistinctDescList_create_Desc into IH.\n  rewrite fromDistinctDescList_create_eq\n    by (enough (0 < 2^sz)%Z by lia; apply Z.pow_pos_nonneg; lia).\n  unfold fromDistinctDescList_create_f.\n  destruct xs.\n  * intros X HX. apply HX. clear HX.\n    - solve_Bounded e.\n    - reflexivity.\n    - left. reflexivity.\n  * repeat replace (#1) with 1%Z by reflexivity.\n    unfold op_zeze__, Eq_Integer___, op_zeze____.\n\n    inversion HSorted. subst.\n    inversion H2. subst. clear H2.\n    inversion H1. subst.\n    destruct p.\n    assert (isLB (safeHd xs) e0 = true). {\n      destruct xs; try reflexivity.\n      inversion H5. subst. unfold safeHd. destruct p. unfold gt in H6.\n      unfold isLB. order e. } \n    \n    destruct (Z.eqb_spec (2^sz) 1).\n    - intros X HX. apply HX. clear HX.\n      ++ solve_Bounded e. unfold gt in H3. unfold isUB. order e.\n      ++ rewrite toList_Bin, toList_Tip, app_nil_r. reflexivity.\n      ++ right. rewrite size_Bin. lia.\n    - assert (~ (sz = 0))%Z by (intro; subst; simpl in n; congruence).\n      assert (sz > 0)%Z by lia.\n      replace ((Bits.shiftR (2 ^ sz)%Z 1%Z)) with (2^(sz - 1))%Z.\n      Focus 2.\n        unfold Bits.shiftR, Bits.instance_Bits_Int.\n        rewrite Z.shiftr_div_pow2 by lia.\n        rewrite Z.pow_sub_r by lia.\n        reflexivity.\n      assert (Z.to_nat (sz - 1) < Z.to_nat sz)%nat.\n      { rewrite Z2Nat.inj_sub by lia. \n        apply Nat.sub_lt.\n        apply Z2Nat.inj_le.\n        lia.\n        lia.\n        lia.\n        replace (Z.to_nat 1) with 1 by reflexivity.\n        lia.\n      }\n      eapply IH.\n      ++ assumption.\n      ++ lia.\n      ++ eassumption.\n      ++ intros l ys HBounded_l Hlist_l Hsize_l.\n         destruct ys.\n         + intros X HX. apply HX. clear HX.\n           ** solve_Bounded e.\n           ** assumption.\n           ** left; reflexivity.\n         + simpl in HBounded_l. destruct p.\n           destruct Hsize_l; try congruence.\n           eapply IH; clear IH.\n           ** assumption.\n           ** lia.\n           ** rewrite Hlist_l in H1. \n              apply StronglySorted_app in H1.\n              destruct H1. \n              eassumption.\n           ** intros r zs HBounded_r Hlist_r Hsize_r.\n              rewrite Hlist_l in HSorted.\n              assert (isUB (Some ub) e1 = true). {\n                apply StronglySorted_inv in HSorted.\n                destruct HSorted.\n                simpl.\n                rewrite Forall_forall in H10. unfold gt in H10.\n                specialize (H10 (e1, a1)). \n                assert (e1 < ub = true <-> ub > e1 = true) by (order e). rewrite H11.\n                apply H10.\n                apply in_or_app. right. left. reflexivity.\n              }\n              rewrite Hlist_r in HSorted.\n              assert (isLB (safeHd zs) e1 = true). {\n                destruct zs; try reflexivity.\n                apply StronglySorted_inv in HSorted.\n                destruct HSorted.\n                apply StronglySorted_app in H10.\n                destruct H10.\n                apply StronglySorted_inv in H12.\n                destruct H12.\n                rewrite Forall_forall in H13. specialize (H13 p). unfold isLB. simpl. destruct p.\n                unfold gt in H13. assert (e2 < e1 = true <-> e1 > e2 = true) by (order e).\n                rewrite H14.\n                apply H13.\n                apply in_or_app. right. left. reflexivity.\n              }\n              intros X HX. apply HX. clear HX.\n              -- applyDesc e (@link_Desc e a).\n              -- erewrite toList_link by eassumption.\n                 rewrite Hlist_l. rewrite Hlist_r.\n                 rewrite !rev_app_distr; simpl.\n                 rewrite <- !app_assoc.  simpl. reflexivity.\n              -- destruct Hsize_r; [left; assumption| right].\n                 applyDesc e (@link_Desc e a).\n                 replace (size l). replace (size r).\n                 rewrite mul_pow_sub in * by lia.\n                 lia.\nQed.\n\n(*If we look for an element in a map's list, it is the same as looking in the reverse of that list.\nThis is euivalent to saying that the first key, value pair that matches a given key is the same\nas the last pair*)\nLemma sem_list_rev:\n  forall m lb ub x,\n  Bounded m lb ub ->\n  sem_for_lists (toList m) x = sem_for_lists (rev (toList m)) x.\nProof.\n  intros. generalize dependent x. induction H; intros.\n  - simpl. reflexivity.\n  - rewrite toList_Bin. rewrite rev_app_distr.\n simpl. rewrite <- app_assoc. simpl.\n    rewrite sem_list_app. rewrite sem_list_app. rewrite <- IHBounded2.\n    assert (forall {a} (x : a) l, x :: l = (x :: nil) ++ l). { intros.\n    simpl. reflexivity. } rewrite H5. rewrite sem_list_app.\n    rewrite (H5 _ _ (rev (toList s1))). rewrite sem_list_app.\n    rewrite <- IHBounded1. repeat(erewrite <- toList_sem'').\n    destruct (sem s1 x0) eqn : ?. simpl.\n    assert (sem s2 x0 = None). { eapply sem_outside_below. apply H0. solve_Bounds e. }\n    rewrite H6. simpl. assert (x0 == x = false) by solve_Bounds e. rewrite H7; reflexivity.\n    simpl. destruct (x0 == x) eqn : ?. assert (sem s2 x0 = None). { eapply sem_outside_below.\n    apply H0. solve_Bounds e. } rewrite H6. reflexivity. simpl. rewrite oro_None_r. reflexivity.\n    apply H0. apply H.\nQed.\n\nProgram Fixpoint fromDistinctDescList_go_Desc\n  sz s xs {measure (length xs)} :\n  (0 <= sz)%Z ->\n  StronglySorted (fun x y => gt x y) xs ->\n  Bounded s (safeHd xs) None  ->\n  xs = nil \\/ size s = (2*2^sz-1)%Z ->\n  Desc (fromDistinctDescList_go (2^sz)%Z s xs) None None (size s + List.length xs)\n    (fun i => sem s i ||| sem_for_lists xs i) := _. \nNext Obligation.\n  intros.\n  rename fromDistinctDescList_go_Desc into IH.\n  rewrite fromDistinctDescList_go_eq by (apply Z.pow_pos_nonneg; lia).\n  unfold fromDistinctDescList_go_f.\n  destruct xs.\n  * replace (List.length nil) with 0%Z by reflexivity.\n    rewrite Z.add_0_r.\n    solve_Desc e.\n  * repeat replace (#1) with 1%Z by reflexivity.\n    replace ((Bits.shiftL (2 ^ sz)%Z 1))%Z with (2 ^ (1 + sz))%Z.\n    Focus 2.\n      unfold Bits.shiftL, Bits.instance_Bits_Int.\n      rewrite Z.shiftl_mul_pow2 by lia.\n      rewrite Z.pow_add_r by lia.\n      lia. destruct p.\n\n    destruct H2; try congruence.\n    eapply fromDistinctDescList_create_Desc.\n    - lia.\n    - eassumption.\n    - intros.\n      subst.\n      simpl safeHd in *.\n      assert (isLB (safeHd ys) e0 = true). {\n        destruct ys; try reflexivity.\n        apply StronglySorted_inv in H0.\n        destruct H0.\n        rewrite Forall_forall in H4. specialize (H4 p). unfold isLB. destruct p. simpl.\n        unfold gt in H4. assert (e1 < e0 = true <->e0 > e1 = true) by (order e). rewrite H6.\n        apply H4. \n        apply in_or_app. right. left. reflexivity.\n      }      \n      applyDesc e (@link_Desc e a).\n      eapply IH.\n      + simpl. rewrite app_length. lia.\n      + lia.\n      + apply StronglySorted_inv in H0.\n        destruct H0.\n        apply StronglySorted_app in H0.\n        destruct H0.\n        assumption.\n      + assumption.\n      + destruct H5; [left; assumption | right].\n        replace (size s1). replace (size s).  replace (size s0).\n        rewrite Z.pow_add_r by lia.\n        lia.\n      + intros.\n        solve_Desc e.\n        ** replace (size s2). replace (size s1). replace (size s).\n           rewrite !List.hs_coq_list_length, !Zlength_correct.\n           simpl length.\n           rewrite app_length, Nat2Z.inj_succ, Nat2Z.inj_add, rev_length.\n           erewrite <- size_spec by eassumption.\n           lia.\n        ** simpl. setoid_rewrite sem_list_app. \n            assert (forall i, sem_for_lists (rev (toList s0)) i = sem_for_lists (toList s0) i).\n            setoid_rewrite (sem_list_rev s0 (safeHd ys) (Some e0) _ H3). intros. reflexivity. \n            setoid_rewrite H9.\n            setoid_rewrite <- toList_sem''; only 2: eassumption.\n            f_solver e.\nQed.\n\n\n\nLemma fromDistinctDescList_Desc:\n  forall xs,\n  StronglySorted (fun x y => gt x y) xs ->\n  Desc (fromDistinctDescList xs) None None (List.length xs) (fun i => sem_for_lists xs i).\nProof.\n  intros.\n  unfold fromDistinctDescList.\n  fold fromDistinctDescList_create_f.\n  fold fromDistinctDescList_create.\n  fold fromDistinctDescList_go_f.\n  fold fromDistinctDescList_go.\n  destruct xs.\n  * solve_Desc e.\n  * replace (#1) with (2^0)%Z by reflexivity. destruct p.\n    eapply fromDistinctDescList_go_Desc.\n    + lia.\n    + apply StronglySorted_inv in H.\n      destruct H.\n      assumption.\n    + assert (isLB (safeHd xs) e0 = true). {\n        destruct xs; try reflexivity.\n        apply StronglySorted_inv in H.\n        destruct H.\n        rewrite Forall_forall in H0. destruct p. unfold isLB. simpl.\n        unfold gt in H0. specialize (H0 (e1, a1)). \n        assert (e1 < e0 = true <-> e0 > e1 = true) by (order e). rewrite H1.\n        apply H0.\n        left. reflexivity.\n      }\n      solve_Bounded e.\n    + right. reflexivity.\n    + intros.\n      rewrite List.hs_coq_list_length, Zlength_cons in *.\n      rewrite size_Bin in H1.\n      solve_Desc e. simpl. f_solver e.\nQed.\n\n(** ** Verification of [combineEq] *)\n\n(*Since [combineEq'] and [combineEq] are defined inside [fromAscList] (unlike in Data.Set), we define them here\nand then prove equivalence*)\n\nFixpoint combineEq' {e} {a} `{EqLaws e} (x : e * a) (l : list (e * a) ) :=\n  match x, l with\n  |z, nil => z :: nil\n  |(a, b), (c, d) :: t => if a == c then combineEq' (c, d) t else (a,b) :: combineEq' (c,d) t\n  end.\n\n(*The combineEq' from Data.Map (defined here to make combineEq'_equiv nicer*)\nDefinition old_combineEq' :=(fix combineEq' (arg_0__ : e * a) (arg_1__ : list (e * a)) {struct arg_1__} : list (e * a) :=\n   let (kz, _) := arg_0__ in\n   match arg_1__ with\n   | nil => arg_0__ :: nil\n   | (kx, xx) as x :: xs' => if _GHC.Base.==_ kx kz then combineEq' (kx, xx) xs' else arg_0__ :: combineEq' x xs'\n   end).\n\nDefinition combineEq {e} {a} `{EqLaws e} (l : list (e * a)) :=\n  match l with\n  | nil => nil\n  | x :: nil => x :: nil\n  | x :: t => combineEq' x t\n  end.\n\nLemma combineEq'_equiv:\n  forall l x, combineEq' x l = old_combineEq' x l.\nProof.\n  intros. revert x. induction l; intros.\n  - simpl. destruct x. reflexivity.\n  - simpl. destruct x. destruct a0. destruct (e0 == e1) eqn : ?.\n    assert (e1 == e0 = true) by (order e). rewrite H. apply IHl.\n    assert (e1 == e0 = false) by (order e). rewrite H. rewrite IHl.\n    reflexivity.\nQed.\n\n\nDefinition fromAscList' (l : list (e * a)) :=\n  fromDistinctAscList (combineEq l).\n\n\nLemma fromAscList_equiv: forall (l : list (e * a)),\n  fromAscList' l = fromAscList l.\nProof.\n  intros l. unfold fromAscList', fromAscList. destruct l.\n  - simpl. reflexivity.\n  -  unfold combineEq. rewrite combineEq'_equiv. unfold old_combineEq'.\n     reflexivity.\nQed.\n\nDefinition fromDescList' (l : list (e * a)) :=\n  fromDistinctDescList (combineEq l).\n\nLemma fromDescList_equiv: forall (l : list (e * a)),\n  fromDescList' l = fromDescList l.\nProof.\n  intros l. unfold fromDescList', fromDescList. destruct l.\n  - simpl. reflexivity.\n  -  unfold combineEq. rewrite combineEq'_equiv. unfold old_combineEq'.\n     reflexivity.\nQed.\n\nDefinition combineEqGo : (e * a) -> list (e * a) -> list (e * a).\nProof.\n  intros.\n apply (@combineEq' e a HEq HEqLaws). apply X.  apply X0.\nDefined.\n\n(* Too much duplication here *)\n\n(*See if a key is a (key, value) list*)\nFixpoint key_elem (l : list (e * a)) i :=\n  match l with\n  | nil => false\n  | (x, y) :: t => (x == i) || key_elem t i\n  end.\n\n(*This finds the last value associated with a key in a list*)\nFixpoint last_value (l : list (e * a)) i:=\n  match l with\n  | nil => None\n  | (x, y) :: t => if (x == i) then match last_value t i with\n                               | None => Some y\n                               | Some z => Some z\n                               end else last_value t i\n  end. \n\n(*This proves that the last_value does in fact find the last value, since it finds\nthe first value in the reversed list. It also justifies using either\n[sem_for_lists (rev l)] or [last_value l] based on which is more convienent. For \n[combineEq] and [fromDescList] (and similar), I use [last_value l], and in\nfrom_list, I use [sem_for_lists (rev l)]*)\nLemma last_sem_equiv: forall l x,\n  sem_for_lists (rev l) x = last_value l x.\nProof.\n  intros. revert x; induction l; intros.\n  - simpl. reflexivity.\n  - simpl. destruct a0. rewrite sem_list_app. rewrite IHl.\n    simpl. destruct (e0 == x) eqn : ?. assert (x == e0 = true) by (order e).\n    rewrite H. destruct (last_value l x) eqn : ?. simpl. reflexivity. simpl. reflexivity.\n    assert (x == e0 = false) by (order e). rewrite H. rewrite oro_None_r. reflexivity.\nQed. \n\n(*An element has a last occurrence iff it is in the list*)\nLemma last_iff_elem: forall l i,\n  (exists v, last_value l i = Some v) <-> key_elem l i = true.\nProof.\n  intros. revert  i. induction l; split; intros.\n  - simpl in H. inversion H. inversion H0.\n  - simpl in H. inversion H. \n  - simpl. destruct a0.  simpl in H. destruct (e0 == i) eqn : ?.\n    simpl. reflexivity. simpl. eapply IHl. apply H.\n  - simpl. destruct a0. simpl in H. destruct (e0  == i) eqn : ?.\n    destruct (last_value l i) eqn : ?. exists a1. reflexivity.\n    exists a0. reflexivity. simpl in H. apply IHl. apply H.\nQed.\n\nLocal Definition le : e * a -> e * a -> Prop\n  := fun x1 x2 => let (e1, a1) := x1 in let (e2, a2) := x2 in (e1 <= e2) = true.\n  \nLemma Forall_le_elem:\n  forall x x0 xs,\n  Forall (fun y => le (x, x0) y) xs <-> (forall i, key_elem xs i = true -> x <= i = true).\nProof.\n  intros.\n  induction xs.\n  * split; intro H.\n    - intros i Hi; simpl in Hi; congruence.\n    - constructor.\n  * split; intro H.\n    - inversion H; subst; clear H.\n      rewrite IHxs in H3; clear IHxs.\n      intros i Hi; simpl in Hi. destruct a0. \n      rewrite orb_true_iff in Hi. destruct Hi.\n      + unfold le in *.  order e.\n      + apply H3; assumption.\n    - constructor.\n      + unfold le. destruct a0. apply H. simpl. rewrite Eq_Reflexive. simpl. reflexivity.\n      + rewrite IHxs; clear IHxs.\n        intros i Hi. apply H. simpl. rewrite Hi. destruct a0.  apply orb_true_r.\nQed.\n\nLemma Forall_le_last:\n  forall x x0 xs,\n  Forall (fun y => le (x, x0) y) xs <-> (forall i v, last_value xs i = Some v -> x <= i = true).\nProof.\n  intros.\n  rewrite Forall_le_elem. split; intros.\n  - apply H. apply last_iff_elem. exists v. assumption.\n  - apply last_iff_elem in H0. destruct H0. apply H in H0. assumption.\nQed. \n\n\nLocal Definition ge : e * a -> e * a -> Prop\n  := fun x1 x2 => let (e1, a1) := x1 in let (e2, a2) := x2 in (e1 >= e2) = true.\n\nLemma Forall_ge_elem:\n  forall x x0 xs,\n  Forall (fun y => ge (x, x0) y) xs <-> (forall i, key_elem xs i = true -> x >= i = true).\nProof.\n  intros.\n  induction xs.\n  * split; intro H.\n    - intros i Hi; simpl in Hi; congruence.\n    - constructor.\n  * split; intro H.\n    - inversion H; subst; clear H.\n      rewrite IHxs in H3; clear IHxs.\n      intros i Hi; simpl in Hi. destruct a0. \n      rewrite orb_true_iff in Hi. destruct Hi.\n      + unfold ge in *.  order e.\n      + apply H3; assumption.\n    - constructor.\n      + unfold ge. destruct a0. apply H. simpl. rewrite Eq_Reflexive. simpl. reflexivity.\n      + rewrite IHxs; clear IHxs.\n        intros i Hi. apply H. simpl. rewrite Hi. destruct a0.  apply orb_true_r.\nQed.\n\nLemma Forall_ge_last:\n  forall x x0 xs,\n  Forall (fun y => ge (x, x0) y) xs <-> (forall i v, last_value xs i = Some v -> x >= i = true).\nProof.\n  intros.\n  rewrite Forall_ge_elem. split; intros.\n  - apply H. apply last_iff_elem. exists v. assumption.\n  - apply last_iff_elem in H0. destruct H0. apply H in H0. assumption.\nQed. \n\nLemma Forall_lt_elem:\n  forall x x0 xs,\n  Forall (fun y => lt (x, x0) y) xs <-> (forall i, key_elem xs i = true -> x < i = true).\nProof.\n  intros.\n  induction xs.\n  * split; intro H.\n    - intros i Hi; simpl in Hi; congruence.\n    - constructor.\n  * split; intro H.\n    - inversion H; subst; clear H.\n      rewrite IHxs in H3; clear IHxs.\n      intros i Hi; simpl in Hi. destruct a0. \n      rewrite orb_true_iff in Hi. destruct Hi.\n      + unfold lt in *.  order e.\n      + apply H3; assumption.\n    - constructor.\n      + unfold lt. destruct a0. apply H. simpl. rewrite Eq_Reflexive. simpl. reflexivity.\n      + rewrite IHxs; clear IHxs.\n        intros i Hi. apply H. simpl. rewrite Hi. destruct a0.  apply orb_true_r.\nQed.\n\nLemma Forall_lt_last:\n  forall x x0 xs,\n  Forall (fun y => lt (x, x0) y) xs <-> (forall i v, last_value xs i = Some v -> x < i = true).\nProof.\n  intros.\n  rewrite Forall_lt_elem. split; intros.\n  - apply H. apply last_iff_elem. exists v. assumption.\n  - apply last_iff_elem in H0. destruct H0. apply H in H0. assumption.\nQed. \n\n\nLemma Forall_gt_elem:\n  forall x x0 xs,\n  Forall (fun y => gt (x, x0) y) xs <-> (forall i, key_elem xs i = true -> x > i = true).\nProof.\n  intros.\n  induction xs.\n  * split; intro H.\n    - intros i Hi; simpl in Hi; congruence.\n    - constructor.\n  * split; intro H.\n    - inversion H; subst; clear H.\n      rewrite IHxs in H3; clear IHxs.\n      intros i Hi; simpl in Hi. destruct a0. \n      rewrite orb_true_iff in Hi. destruct Hi.\n      + unfold gt in *.  order e.\n      + apply H3; assumption.\n    - constructor.\n      + unfold gt. destruct a0. apply H. simpl. rewrite Eq_Reflexive. simpl. reflexivity.\n      + rewrite IHxs; clear IHxs.\n        intros i Hi. apply H. simpl. rewrite Hi. destruct a0.  apply orb_true_r.\nQed.\n\nLemma Forall_gt_last:\n  forall x x0 xs,\n  Forall (fun y => gt (x, x0) y) xs <-> (forall i v, last_value xs i = Some v -> x > i = true).\nProof.\n  intros.\n  rewrite Forall_gt_elem. split; intros.\n  - apply H. apply last_iff_elem. exists v. assumption.\n  - apply last_iff_elem in H0. destruct H0. apply H in H0. assumption.\nQed. \n\n\n(*Note: This is significatly different than SetProofs. It is not enough that the keys are preserved,\nwe must show that each key is matched with its last value in the list*)\nLemma combineEqGo_spec:\n  forall x xs,\n  StronglySorted (fun x y => le x y) (x :: xs) ->\n  forall P : list (e * a) -> Prop,\n  (forall (ys: list (e * a)),\n     StronglySorted (fun x y => lt x y) ys ->\n     (forall i, last_value ys i = last_value (x :: xs) i) ->\n     P ys) ->\n  P (combineEqGo x xs).\nProof.\n  intros x xs Hsorted.\n  inversion Hsorted; subst; clear Hsorted.\n  revert x H2.\n  induction H1; intros x Hlt.\n  * intros X HX; apply HX; clear X HX.\n    + unfold lt. unfold le in Hlt. unfold combineEqGo. simpl. destruct x.\n      constructor; constructor.\n    + intro. unfold combineEqGo. simpl. destruct x. simpl. reflexivity.\n  * inversion Hlt; subst; clear Hlt.  \n    simpl. unfold combineEqGo in *. simpl in *. destruct a0. destruct x.\n    destruct_match.\n    + eapply IHStronglySorted; only 1: assumption; intros ys Hsortedys Hiys.\n      intros X HX; apply HX; clear X HX.\n      - assumption.\n      - intro i. rewrite Hiys. simpl. \n        destruct (e0 == i) eqn:?, (e1 == i) eqn:?. destruct (last_value l i) eqn : ?.\n        reflexivity. reflexivity. reflexivity. order e. reflexivity.\n    + assert (Hlt : e1 < e0 = true) by (unfold le in H3; order e). clear H3 Heq.\n      eapply IHStronglySorted; only 1: assumption; intros ys Hsortedys Hiys.\n      intros X HX; apply HX; clear X HX.\n      - constructor.\n        ** eapply StronglySorted_R_ext; only 2: apply Hsortedys.\n           intros. simpl. order e.\n        ** apply Forall_lt_last.\n           rewrite Forall_le_last in H.\n           intros i v Hi. rewrite Hiys in Hi.  simpl in Hi. unfold lt.\n           destruct (e0 == i) eqn : ?. order e. apply H in Hi. unfold le in Hi. order e.\n      - intro i. simpl. rewrite Hiys. simpl. reflexivity.\nQed.\n\nLemma combineEqGo_spec2:\n  forall x xs,\n  StronglySorted (fun x y => ge x y) (x :: xs) ->\n  forall P : list (e * a) -> Prop,\n  (forall (ys: list (e * a)),\n     StronglySorted (fun x y => gt x y) ys ->\n     (forall i, last_value ys i = last_value (x :: xs) i) ->\n     P ys) ->\n  P (combineEqGo x xs).\nProof.\n  intros x xs Hsorted.\n  inversion Hsorted; subst; clear Hsorted.\n  revert x H2.\n  induction H1; intros x Hlt.\n  * intros X HX; apply HX; clear X HX.\n    + unfold lt. unfold ge in Hlt. unfold combineEqGo. simpl. destruct x.\n      constructor; constructor.\n    + intro. unfold combineEqGo. simpl. destruct x.  simpl. reflexivity.\n  * inversion Hlt; subst; clear Hlt.  \n    simpl. unfold combineEqGo in *. simpl in *. destruct a0. destruct x.\n    destruct_match.\n    + eapply IHStronglySorted; only 1: assumption; intros ys Hsortedys Hiys.\n      intros X HX; apply HX; clear X HX.\n      - assumption.\n      - intro i. rewrite Hiys. simpl. \n        destruct (e0 == i) eqn:?, (e1 == i) eqn:?. destruct (last_value l i) eqn : ?.\n        reflexivity. reflexivity. reflexivity. order e. reflexivity.\n    + assert (Hlt : e1 > e0 = true) by (unfold ge in H3; order e). clear H3 Heq.\n      eapply IHStronglySorted; only 1: assumption; intros ys Hsortedys Hiys.\n      intros X HX; apply HX; clear X HX.\n      - constructor.\n        ** eapply StronglySorted_R_ext; only 2: apply Hsortedys.\n           intros. simpl. order e.\n        ** apply Forall_gt_last.\n           rewrite Forall_ge_last in H.\n           intros i v Hi. rewrite Hiys in Hi.  simpl in Hi. unfold lt.\n           destruct (e0 == i) eqn : ?. order e. apply H in Hi. unfold ge in Hi. order e.\n      - intro i. simpl. rewrite Hiys. simpl. reflexivity.\nQed.\n\nLemma combineEq_spec:\n  forall xs,\n  StronglySorted (fun x y => le x  y) xs ->\n  forall P : list (e * a) -> Prop,\n  (forall ys,\n     StronglySorted (fun x y => lt x y) ys ->\n     (forall i, last_value ys i = last_value xs i) ->\n     P ys) ->\n  P (combineEq xs).\nProof.\n  intros xs Hsorted.\n  inversion Hsorted.\n  * intros X HX. apply HX. clear X HX.\n    - constructor.\n    - intro. reflexivity.\n  * rewrite <- H1 in Hsorted. clear xs H0 H1.\n    assert (combineEq (a0 :: l) = combineEqGo a0 l). {\n    unfold combineEqGo. simpl. destruct l. simpl. destruct a0. reflexivity.\n    reflexivity. } rewrite H0.\n    apply combineEqGo_spec. assumption.\nQed.\n\nLemma combineEq_spec2:\n  forall xs,\n  StronglySorted (fun x y => ge x  y) xs ->\n  forall P : list (e * a) -> Prop,\n  (forall ys,\n     StronglySorted (fun x y => gt x y) ys ->\n     (forall i, last_value ys i = last_value xs i) ->\n     P ys) ->\n  P (combineEq xs).\nProof.\n  intros xs Hsorted.\n  inversion Hsorted.\n  * intros X HX. apply HX. clear X HX.\n    - constructor.\n    - intro. reflexivity.\n  * rewrite <- H1 in Hsorted. clear xs H0 H1.\n    assert (combineEq (a0 :: l) = combineEqGo a0 l). {\n    unfold combineEqGo. simpl. destruct l. simpl. destruct a0. reflexivity.\n    reflexivity. } rewrite H0.\n    apply combineEqGo_spec2. assumption.\nQed.\n\n\n(** ** Verification of [fromAscList] *)\n\n(*See whether a key, value pair is in a list, comparing the keys with Haskell equality\nand the values with Coq equality. This will be used in place of List.In in the following\nanalogues of [Forall_forall]*)\nFixpoint weak_In (l : list (e * a)) (x : e * a) :=\n  match l with\n  | nil => False\n  | (a,b) :: t => let (x0, y0) := x in (a == x0 = true) /\\ b = y0 \\/ weak_In t x\n  end.\n\nLemma Forall_forall_lt: \n  forall  (l : list (e * a)) t, Forall (lt t) l <-> (forall x, weak_In l x -> lt t x).\nProof.\n  intros. split; intros; induction l; intros.\n  - simpl in H0. destruct H0.\n  - simpl in H0. destruct a0. destruct x. destruct H0. inversion H; subst.\n    destruct H0. subst. destruct t. unfold lt in *. order e.\n  - apply IHl. inversion H; subst. assumption. apply H0.\n  - apply Forall_nil.\n  - apply Forall_cons. simpl in H. destruct a0. apply H. left.\n    split. apply Eq_Reflexive. reflexivity. simpl in H.\n    destruct a0. apply IHl. intros. apply H. destruct x. right. assumption.\nQed.\n\nLemma Forall_forall_gt: \n  forall  (l : list (e * a)) t, Forall (gt t) l <-> (forall x, weak_In l x -> gt t x).\nProof.\n  intros. split; intros; induction l; intros.\n  - simpl in H0. destruct H0.\n  - simpl in H0. destruct a0. destruct x. destruct H0. inversion H; subst.\n    destruct H0. subst. destruct t. unfold gt in *. order e.\n  - apply IHl. inversion H; subst. assumption. apply H0.\n  - apply Forall_nil.\n  - apply Forall_cons. simpl in H. destruct a0. apply H. left.\n    split. apply Eq_Reflexive. reflexivity. simpl in H.\n    destruct a0. apply IHl. intros. apply H. destruct x. right. assumption.\nQed.\n\nLemma strongly_sorted_in_sem_lt: forall l x v,\n  StronglySorted lt l ->\n  sem_for_lists l x = Some v <-> weak_In l (x,v).\nProof.\n  intros; revert x v; induction l; intros; split; intros.\n  - inversion H0.\n  - destruct H0.\n  - simpl. simpl in H0. destruct a0. destruct (x == e0) eqn : ?.\n    left. split. order e. inversion H0; subst; reflexivity.\n    right. apply IHl. inversion H; subst; assumption. apply H0.\n  - simpl in H0. simpl. destruct a0.\n    destruct H0. destruct H0. subst. assert (x == e0 = true) by (order e).\n    rewrite H1. reflexivity. inversion H; subst.\n    rewrite Forall_forall_lt in H4. assert (A:=H0). apply H4 in H0. unfold lt in H0.\n    assert (x == e0 = false) by (order e). rewrite H1. apply IHl. apply H3. apply A.\nQed.\n\nLemma strongly_sorted_in_sem_gt: forall l x v,\n  StronglySorted gt l ->\n  sem_for_lists l x = Some v <-> weak_In l (x,v).\nProof.\n  intros; revert x v; induction l; intros; split; intros.\n  - inversion H0.\n  - destruct H0.\n  - simpl. simpl in H0. destruct a0. destruct (x == e0) eqn : ?.\n    left. split. order e. inversion H0; subst; reflexivity.\n    right. apply IHl. inversion H; subst; assumption. apply H0.\n  - simpl in H0. simpl. destruct a0.\n    destruct H0. destruct H0. subst. assert (x == e0 = true) by (order e).\n    rewrite H1. reflexivity. inversion H; subst.\n    rewrite Forall_forall_gt in H4. assert (A:=H0). apply H4 in H0. unfold gt in H0.\n    assert (x == e0 = false) by (order e). rewrite H1. apply IHl. apply H3. apply A.\nQed.\n\nLemma strongly_sorted_last_lt:\n  forall l x,\n  StronglySorted lt l ->\n  last_value l x = sem_for_lists l x.\nProof.\n  intros. revert x. induction H; intros.\n  - simpl. reflexivity.\n  - simpl. destruct a0. destruct (x == e0) eqn : ?.\n    rewrite Forall_forall_lt in H0.\n    rewrite IHStronglySorted.\n    destruct (sem_for_lists l x) eqn : ?. \n    + rewrite strongly_sorted_in_sem_lt in Heqo. apply H0 in Heqo.\n      unfold lt in Heqo. order e. apply H. destruct (e0 == x) eqn : ?. reflexivity.\n    order e. assert (e0 == x = false) by (order e). rewrite H1. apply IHStronglySorted.\nQed.\n\nLemma strongly_sorted_last_gt:\n  forall l x,\n  StronglySorted gt l ->\n  last_value l x = sem_for_lists l x.\nProof.\n  intros. revert x. induction H; intros.\n  - simpl. reflexivity.\n  - simpl. destruct a0. destruct (x == e0) eqn : ?.\n    rewrite Forall_forall_gt in H0.\n    rewrite IHStronglySorted.\n    destruct (sem_for_lists l x) eqn : ?. \n    + rewrite strongly_sorted_in_sem_gt in Heqo. apply H0 in Heqo.\n      unfold gt in Heqo. order e. apply H. destruct (e0 == x) eqn : ?. reflexivity.\n    order e. assert (e0 == x = false) by (order e). rewrite H1. apply IHStronglySorted.\nQed.\n\n\nLemma fromAscList_Desc:\n  forall xs,\n  StronglySorted (fun x y => le x y) xs ->\n  Desc' (fromAscList xs) None None (fun i => last_value xs i).\nProof.\n  intros. rewrite <- fromAscList_equiv. unfold fromAscList'.\n  eapply combineEq_spec; only 1: assumption; intros ys HSorted Helem.\n  apply fromDistinctAscList_Desc; only 1: assumption.\n  intros s HB Hsz Hf.\n  solve_Desc e. intros. rewrite <- Helem. rewrite strongly_sorted_last_lt.\n  apply Hf. apply HSorted.\nQed.\n\n(** ** Verification of [fromDescList] *)\n\nLemma fromDescList_Desc:\n  forall xs,\n  StronglySorted (fun x y => ge x y) xs ->\n  Desc' (fromDescList xs) None None (fun i => last_value xs i).\nProof.\n  intros. rewrite <- fromDescList_equiv. unfold fromDescList'.\n  unfold fromDescList.\n  eapply combineEq_spec2;  only 1: assumption; intros ys HSorted Helem.\n  apply fromDistinctDescList_Desc; only 1: assumption.\n  intros s HB Hsz Hf.\n  solve_Desc e. intros. rewrite <- Helem. rewrite strongly_sorted_last_gt.\n  apply Hf. apply HSorted.\nQed.\n\n(** ** Verification of [fromList] *)\n\n(** The verification of [fromList] should be similar to that of [fromDistinctAscList], only\nthat the condition is checked and -- if it fails -- we resort to a backup implementation. *)\n\n(* The following definitions are copied from the local definitions of [fromList]; \n   my ltac foo failed to do that automatic.\n*)\n\nDefinition fromList' :=\n          fun (t0: Map e a) (xs: list (e * a)) =>\n            let ins :=\n              fun arg_2__ arg_3__ =>\n                match arg_2__, arg_3__ with\n                | t, pair k x => insert k x t\n                end in\n            Data.Foldable.foldl' ins t0 xs.\n\nDefinition not_ordered :=\n          fun (arg_7__ : e) (arg_8__: list (e * a)) =>\n            match arg_7__, arg_8__ with\n            | _, nil => false\n            | kx, cons (pair ky _) _ => kx GHC.Base.>= ky\n            end .\n\nDefinition fromList_create_f : (Int -> list (e * a) -> Map e a * list (e * a) * list (e * a)) -> \n(Int -> list (e * a) -> Map e a * list (e * a)  * list (e * a))\n  := (fun create arg_11__ arg_12__ =>\n      match arg_11__, arg_12__ with\n      | _, nil => pair (pair Tip nil) nil\n      | s, (cons xp xss as xs) =>\n       if s GHC.Base.== #1 : bool\n       then let 'pair kx x := xp in\n         if not_ordered kx xss : bool\n         then pair (pair (Bin #1 kx x Tip Tip) nil) xss else\n         pair (pair (Bin #1 kx x Tip Tip) xss) nil else\n         match create (Data.Bits.shiftR s #1) xs with\n         | (pair (pair _ nil) _ as res) => res\n         | pair (pair l (cons (pair ky y) nil)) zs =>\n              pair (pair (insertMax ky y l) nil) zs\n         | pair (pair l (cons (pair ky y) yss as ys)) _ =>\n             if not_ordered ky yss : bool then pair (pair l nil) ys else\n             let 'pair (pair r zs) ws := create (Data.Bits.shiftR s #1) yss in\n                       pair (pair (link ky y l r) zs) ws\n         end\n       end).\n\nDefinition fromList_create : Int -> list (e * a) -> Map e a * list (e * a) * list (e * a)\n  := deferredFix2 (fromList_create_f).\n\nDefinition fromList_go_f :=\n  (fun (go: Int -> Map e a -> list (e * a) -> Map e a) (arg_28__ : Int)\n   (arg_29__ : Map e a) (arg_30__: list (e * a)) =>\n    match arg_28__, arg_29__, arg_30__ with\n    | _, t, nil => t\n    | _, t, cons (pair kx x) nil => insertMax kx x t\n    | s, l, (cons (pair kx x) xss as xs) =>\n          if not_ordered kx xss : bool then fromList' l xs else\n          match fromList_create s xss with\n          | pair (pair r ys) nil => go (Data.Bits.shiftL s #1) (link kx x l r) ys\n          | pair (pair r _) ys => fromList' (link kx x l r) ys\n          end\n   end).\n\nDefinition fromList_go := deferredFix3 (fromList_go_f).\n\n(** zeta-reduces exactly one (the outermost) [let] *)\nLtac zeta_one :=\n  lazymatch goal with |- context A [let x := ?rhs in @?body x] =>\n     let e' := eval cbv beta in (body rhs) in\n     let e'' := context A [e'] in\n     change e''\n  end.\n\n(* Identical to [fromDistinctAscList_create_eq] *)\nLemma fromList_create_eq:\n  forall i xs, (1 <= i)%Z ->\n  fromList_create i xs = fromList_create_f fromList_create i xs.\nProof.\n  intros.\n  change (uncurry fromList_create (i, xs) = uncurry (fromList_create_f fromList_create) (i, xs)).\n  apply deferredFix_eq_on with\n    (f := fun g => uncurry (fromList_create_f (curry g)))\n    (P := fun p => (1 <= fst p)%Z)\n    (R := fun x y => (1 <= fst x < fst y)%Z).\n  * eapply wf_inverse_image with (R := fun x y => (1 <= x < y)%Z).\n    apply Z.lt_wf with (z := 1%Z).\n  * clear i xs H.\n    intros g h x Px Heq.\n    destruct x as [i xs]. simpl in *.\n    unfold fromList_create_f.\n    destruct_match; try reflexivity.\n    repeat replace (#1) with 1%Z by reflexivity.\n    unfold op_zeze__, Eq_Integer___, op_zeze____.\n    destruct (Z.eqb_spec i 1); try reflexivity.\n    unfold curry.\n    assert (1 < i)%Z by lia.\n    assert (1 <= Z.shiftr i 1)%Z by (apply Z_shiftr_pos; lia).\n    assert (Z.shiftr i 1 < i)%Z by (apply Z_shiftr_lt; lia).\n    repeat expand_pairs. simpl.\n    rewrite Heq by eauto.\n    destruct_match; try reflexivity.\n    rewrite Heq by eauto.\n    reflexivity.\n  * simpl; lia.\nQed.\n\n(* We need to know that [create] returns no longer list than it receives.\n   Like [fromDistinctAscList_create_preserves_length], just a few more cases.\n *)\nProgram Fixpoint fromList_create_preserves_length\n  i xs {measure (Z.to_nat i)} :\n  (1 <= i)%Z ->\n  forall (P : Map e a * list (e * a) * list (e * a) -> Prop),\n  ( forall s ys zs ,\n    (length ys <= length xs)%nat ->\n    P (s, ys, zs)\n  ) ->\n  P (fromList_create i xs) := _.\nNext Obligation.\n  intros.\n  rename fromList_create_preserves_length into IH.\n  rewrite fromList_create_eq by assumption.\n  unfold fromList_create_f.\n  destruct xs.\n  * apply H0. reflexivity.\n  * repeat replace (#1) with 1%Z by reflexivity.\n    unfold op_zeze__, Eq_Integer___, op_zeze____.\n    destruct (Z.eqb_spec i 1).\n    + destruct p. destruct_match.\n      - apply H0. simpl. lia.\n      - apply H0. simpl. lia.\n    + assert (Z.to_nat (Bits.shiftR i #1) < Z.to_nat i)%nat. {\n        apply Z2Nat.inj_lt.\n        apply Z.shiftr_nonneg. lia.\n        lia.\n        apply Z_shiftr_lt; lia.\n      }\n      apply IH.\n      - assumption. \n      - apply Z_shiftr_pos; lia.\n      - intros.\n        destruct_match.\n        ** apply H0. simpl in *. lia.\n        ** apply IH.\n           -- assumption.\n           -- apply Z_shiftr_pos; lia.\n           -- intros.\n              repeat destruct_match.\n              ++ apply H0. simpl in *. lia.\n              ++ apply H0. simpl in *. lia.\n              ++ apply H0. simpl in *. lia.\nQed.\n\nLemma fromList_go_eq:\n  forall i s xs, (0 < i)%Z ->\n  fromList_go i s xs = fromList_go_f fromList_go i s xs.\nProof.\n  intros.\n  change (deferredFix (fun g => uncurry (uncurry (fromList_go_f (curry (curry g))))) (i, s, xs) =\n    uncurry (uncurry (fromList_go_f fromList_go)) (i, s, xs)).\n  rewrite deferredFix_eq_on with\n    (P := fun p => (1 <= fst (fst p))%Z)\n    (R := fun x y => (length (snd x) < length (snd y))%nat); only 1: reflexivity.\n  * apply well_founded_ltof with (f := fun x => length (snd x)).\n  * intros g h p Px Heq.\n    destruct p as [[x y] z].\n    simpl in *.\n    unfold fromList_go_f.\n    destruct_match; try reflexivity.\n    eapply fromList_create_preserves_length; try lia.\n    intros s' ys zs Hlength.\n    destruct_match; try reflexivity.\n    destruct_match; try reflexivity.\n    destruct_match; try reflexivity.\n    destruct_match; try reflexivity.\n    apply Heq.\n    + apply Z_shiftl_pos.\n      lia.\n    + simpl. simpl in *. lia.\n  * simpl. lia.\nQed.\n\nProgram Fixpoint fromList_create_Desc\n  sz lb xs {measure (Z.to_nat sz)} :\n  (0 <= sz)%Z ->\n  not_ordered lb xs = false ->\n(*   StronglySorted (fun x y => x < y = true) (lb :: xs) -> *)\n  forall (P : Map e a * list (e * a) * list (e * a) -> Prop),\n  ( forall s ys zs,\n    Bounded s (Some lb) (safeHd ys) ->\n    isUB (safeHd ys) lb = true ->\n    xs = toList s ++ ys ++ zs->\n    ys = nil \\/ (size s = (2*2^sz-1)%Z /\\ zs = nil) ->\n    P (s, ys, zs)\n  ) ->\n  P (fromList_create (2^sz)%Z xs) := _.\nNext Obligation.\n  intros ???? Hnonneg HheadOrdered.\n  rename fromList_create_Desc into IH.\n  rewrite fromList_create_eq\n    by (enough (0 < 2^sz)%Z by lia; apply Z.pow_pos_nonneg; lia).\n  unfold fromList_create_f.\n  destruct xs.\n  * intros X HX. apply HX. clear HX.\n    - solve_Bounded e.\n    - reflexivity.\n    - reflexivity.\n    - left. reflexivity.\n  * repeat replace (#1) with 1%Z by reflexivity.\n    unfold op_zeze__, Eq_Integer___, op_zeze____.\n    \n    simpl in HheadOrdered. destruct p.\n\n(*     assert (isUB (safeHd xs) e0 = true). {\n      destruct xs; try reflexivity.\n      inversion H5. assumption.\n    } *)\n\n    destruct (Z.eqb_spec (2^sz) 1); [ destruct_match | ].\n    - intros X HX. apply HX; clear HX.\n      ++ solve_Bounded e.\n      ++ reflexivity.\n      ++ rewrite toList_Bin, toList_Tip, app_nil_r. reflexivity.\n      ++ left. reflexivity.\n    - intros X HX. apply HX; clear HX.\n      ++ destruct xs; simpl in Heq;  solve_Bounded e. destruct p. unfold safeHd. unfold isUB. order e.\n      ++ destruct xs; simpl in *; solve_Bounds e. destruct p. solve_Bounds e.\n      ++ rewrite toList_Bin, toList_Tip, !app_nil_r, !app_nil_l. reflexivity.\n      ++ right. split. rewrite size_Bin. lia. reflexivity.\n    - assert (~ (sz = 0))%Z by (intro; subst; simpl in n; congruence).\n      assert (sz > 0)%Z by lia.\n      replace ((Bits.shiftR (2 ^ sz)%Z 1%Z)) with (2^(sz - 1))%Z.\n      Focus 2.\n        unfold Bits.shiftR, Bits.instance_Bits_Int.\n        rewrite Z.shiftr_div_pow2 by lia.\n        rewrite Z.pow_sub_r by lia.\n        reflexivity.\n      assert (Z.to_nat (sz - 1) < Z.to_nat sz)%nat.\n      { rewrite Z2Nat.inj_sub by lia. \n        apply Nat.sub_lt.\n        apply Z2Nat.inj_le.\n        lia.\n        lia.\n        lia.\n        replace (Z.to_nat 1) with 1 by reflexivity.\n        lia.\n      }\n      eapply IH.\n      ++ assumption.\n      ++ lia.\n      ++ eassumption.\n      ++ intros l ys zs HBounded_l HisUB_l Hlist_l Hsize_l.\n         destruct ys.\n         + intros X HX. apply HX. clear HX.\n           ** solve_Bounded e.\n           ** assumption.\n           ** assumption.\n           ** left; reflexivity.\n         + simpl in HBounded_l.\n           destruct Hsize_l as [? | [??]]; try congruence.\n           subst. rewrite app_nil_r in Hlist_l. destruct p.\n           assert (isLB (Some lb) e1 = true) by solve_Bounds e.\n           destruct ys; only 2: destruct_match.\n           -- intros X HX. apply HX; clear HX.\n              ** assert (isUB None e1 = true) by reflexivity.\n                 applyDesc e (@insertMax_Desc e a).\n              ** reflexivity.\n              ** erewrite toList_insertMax by eassumption.\n                 rewrite app_nil_l, <- app_assoc.\n                 assumption.\n              ** left; reflexivity.\n           -- intros X HX. apply HX; clear HX.\n              ** solve_Bounded e.\n              ** reflexivity.\n              ** rewrite app_nil_l. simpl in Hlist_l.\n                 assumption.\n              ** left; reflexivity.\n           -- eapply IH; clear IH.\n              ** assumption.\n              ** lia.\n              ** eassumption.\n              ** simpl in Heq.\n                 intros r zs zs' HBounded_r HisUB_r Hlist_r Hsize_r.\n                 intros X HX. apply HX. clear HX.\n                 --- applyDesc e (@link_Desc e a).\n                 --- solve_Bounds e.\n                 --- erewrite toList_link by eassumption.\n                     rewrite Hlist_l. rewrite Hlist_r.\n                     rewrite <- !app_assoc.  reflexivity.\n                 --- destruct Hsize_r; [left; assumption| right].\n                     destruct H4.\n                     split; only 2: assumption.\n                     applyDesc e (@link_Desc e a).\n                     replace (size l). rewrite H4.\n                     rewrite mul_pow_sub in * by lia.\n                     lia.\nQed.\n\nLemma foldl_foldl' : forall {b} f (x : b) (l: list (e * a)),\n  Foldable.foldl f x l = Foldable.foldl' f x l.\nProof.\n  intros.  unfold Foldable.foldl, Foldable.foldl'; unfold Foldable.Foldable__list;\n    unfold  Foldable.foldl__ , Foldable.foldl'__ ; \n    unfold Foldable.Foldable__list_foldl', Foldable.Foldable__list_foldl;\n    unfold Base.foldl, Base.foldl'. reflexivity.\nQed.\n\nDefinition fromList'' :=\n          fun (t0: Map e a) (xs: list (e * a)) =>\n            let ins :=\n              fun arg_2__ arg_3__ =>\n                match arg_2__, arg_3__ with\n                | t, pair k x => insert k x t\n                end in\n            Data.Foldable.foldl ins t0 xs.\n\n\nLemma fromList'_fromList'': forall m l,\n  fromList' m l = fromList'' m l.\nProof.\n  intros. unfold fromList'. unfold fromList''. rewrite <- (foldl_foldl' _ m l). reflexivity.\nQed.\n\nLemma fromList'_Desc:\n  forall s l,\n  Bounded s None None ->\n  Desc' (fromList' s l) None None (fun i => sem_for_lists (rev l) i ||| sem s i).\nProof.\n  intros. rewrite fromList'_fromList''.\n  unfold fromList''.\n  rewrite Foldable.hs_coq_foldl_list.\n  revert s H.\n  induction l.\n  * intros.\n    simpl.\n    solve_Desc e. reflexivity.\n  * intros.\n    simpl. destruct a0.\n    applyDesc e (@insert_Desc e a).\n    applyDesc e IHl.\n    solve_Desc e. f_solver e; rewrite sem_list_app in Heqo0.\n    + rewrite Heqo1 in Heqo0. inversion Heqo0. reflexivity.\n    + rewrite Heqo1 in Heqo0. inversion Heqo0. reflexivity.\n    + rewrite Heqo1 in Heqo0. simpl in Heqo0. rewrite Heqb in Heqo0. rewrite Hsem in Hsem0.\n      rewrite Hsem0 in Heqo0. assumption.\n    + rewrite Heqo1 in Heqo0. simpl in Heqo0. rewrite Heqb in Heqo0. inversion Heqo0.\n    + rewrite Heqo2 in Heqo0. inversion Heqo0.\n    + rewrite Heqo2 in Heqo0. inversion Heqo0.\n    + rewrite Heqo2 in Heqo0. simpl in Heqo0. rewrite Heqb in Heqo0. inversion Heqo0.\n    + rewrite Heqo2 in Heqo0. inversion Heqo0.\n    + rewrite Heqo2 in Heqo0. inversion Heqo0.\n    + rewrite Heqo2 in Heqo0. simpl in Heqo0. rewrite Heqb in Heqo0. inversion Heqo0.\n    + rewrite Heqo1 in Heqo0. simpl in Heqo0. rewrite Heqb in Heqo0. inversion Heqo0.\nQed. \n\n(*In a well formed map, we can only find each key once in the list, so it doesn't matter\nif we look in the list or the reverse list*)\nLemma sem_toList_reverse: forall m lb ub i,\n  Bounded m lb ub ->\n  sem_for_lists (rev (toList m)) i = sem_for_lists (toList m) i.\nProof.\n  intros. revert i. induction H; intros.\n  - simpl. reflexivity.\n  - rewrite toList_Bin. rewrite rev_app_distr. rewrite sem_list_app.\n    rewrite sem_list_app. simpl. rewrite sem_list_app. \n    rewrite IHBounded2. simpl. rewrite IHBounded1. repeat (erewrite <- toList_sem'').\n    destruct (sem s2 i) eqn : ?. assert (sem s1 i = None). { eapply sem_outside_above.\n    apply H. unfold isUB. apply (sem_inside H0) in Heqo. destruct Heqo. order_Bounds e. }\n    rewrite H5. simpl. assert (i == x = false) by solve_Bounds e. rewrite H6. reflexivity.\n    simpl. destruct (i == x) eqn : ?. assert (sem s1 i = None). { eapply sem_outside_above.\n    apply H. unfold isUB. order_Bounds e. } rewrite H5. simpl. reflexivity. simpl.\n    rewrite oro_None_r. reflexivity. apply H. apply H0.\nQed.\n\n\nProgram Fixpoint fromList_go_Desc\n  sz s xs {measure (length xs)} :\n  (0 <= sz)%Z ->\n  Bounded s None (safeHd xs) ->\n  xs = nil \\/ size s = (2*2^sz-1)%Z ->\n  Desc' (fromList_go (2^sz)%Z s xs) None None\n    (fun i => sem_for_lists (rev xs) i ||| sem s i) := _.\nNext Obligation.\n  intros.\n  rename fromList_go_Desc into IH.\n  rewrite fromList_go_eq by (apply Z.pow_pos_nonneg; lia).\n  unfold fromList_go_f.\n  destruct xs as [ | ? [ | ?? ]].\n  * solve_Desc e. intros. reflexivity.\n  * destruct H1; try congruence.\n    simpl safeHd in *. destruct p.\n    assert (isUB None e0 = true) by reflexivity.\n    applyDesc e (@insertMax_Desc e a).\n    solve_Desc e. simpl.\n    (*setoid_rewrite elem_cons.*)\n    f_solver e.\n  * destruct H1; try congruence.\n    repeat replace (#1) with 1%Z by reflexivity.\n    replace ((Bits.shiftL (2 ^ sz)%Z 1))%Z with (2 ^ (1 + sz))%Z.\n    Focus 2.\n      unfold Bits.shiftL, Bits.instance_Bits_Int.\n      rewrite Z.shiftl_mul_pow2 by lia.\n      rewrite Z.pow_add_r by lia.\n      lia. destruct p.\n    destruct_match.\n    --  apply Bounded_relax_ub_None in H0. \n        applyDesc e fromList'_Desc.\n        solve_Desc e. assumption. \n    --  eapply fromList_create_Desc.\n        - lia.\n        - eassumption.\n        - intros.\n          subst.\n          simpl safeHd in *.\n\n          applyDesc e (@link_Desc e a).\n          destruct zs.\n          ++  rewrite app_nil_r in H4.\n              eapply IH.\n              + rewrite H4. simpl. rewrite app_length. lia.\n              + lia.\n              + assumption.\n              + destruct H5 as [?|[??]]; [left; assumption | right].\n                replace (size s1). replace (size s).  replace (size s0).\n                rewrite Z.pow_add_r by lia.\n                lia.\n              + intros.\n                rewrite H4.\n                solve_Desc e. simpl.\n                (*setoid_rewrite elem_cons.*)\n                setoid_rewrite sem_list_app. setoid_rewrite rev_app_distr.\n                setoid_rewrite sem_list_app. \n                setoid_rewrite (sem_toList_reverse s0 _ _ _ H2). \n                setoid_rewrite <- toList_sem''; only 2: eassumption. f_solver e.\n                ** assert (sem s i = None). { eapply sem_outside_above. apply H0. solve_Bounds e. }\n                   rewrite H9 in Hsem. simpl in Hsem. assert (i == e0 = false) by solve_Bounds e.\n                   rewrite H10 in Hsem. simpl in Hsem. rewrite Hsem in H8. inversion H8; reflexivity.\n                ** simpl in Heqo2. destruct( i == e0) eqn : ?. simpl in Hsem. \n                   assert (sem s i = None). { eapply sem_outside_above. apply H0.\n                   solve_Bounds e. } rewrite H9 in Hsem. simpl in Hsem. rewrite Hsem in H8.\n                  rewrite Heqo2 in H8. inversion H8; reflexivity.\n                ** inversion Heqo2.\n                ** simpl in Heqo2. destruct (i == e0) eqn : ?. inversion Heqo2.\n                   simpl in Hsem. rewrite Hsem in H8. inversion H8.\n                ** destruct (sem s i); simpl in Hsem; inversion Hsem. rewrite H8 in H10.\n                   inversion H10. destruct (i == e0); simpl in Hsem; inversion Hsem.\n                    rewrite H8 in H11. inversion H11. rewrite H11 in H8. inversion H8.\n                ** simpl in Heqo2. destruct (i == e0) eqn : ?. simpl in Hsem.\n                   destruct (sem s i); simpl in Hsem. rewrite Hsem in H8. inversion H8.\n                    rewrite Hsem in H8; inversion H8. inversion Heqo2.\n         ++ destruct H5 as [ ? | [? Habsurd]]; try congruence.\n            subst. rewrite app_nil_l in H4.\n            rewrite H4.\n            apply Bounded_relax_ub_None in HB.\n            applyDesc e fromList'_Desc.\n            solve_Desc e. simpl.\n            (*setoid_rewrite elem_cons.*)\n            setoid_rewrite sem_list_app. setoid_rewrite rev_app_distr. simpl.\n            setoid_rewrite sem_list_app. setoid_rewrite (sem_toList_reverse s0 _ _ _ H2). \n            setoid_rewrite <- toList_sem''; only 2: eassumption. simpl in Hsem0.\n            f_solver e.\n            ** assert (sem s i = None). { eapply sem_outside_above. apply H0.\n              solve_Bounds e. } rewrite H5 in Hsem. simpl in Hsem. \n              assert (i == e0 = false) by solve_Bounds e. rewrite H6 in Hsem. simpl in Hsem.\n              rewrite Hsem in Hsem0. inversion Hsem0; reflexivity.\n            **  assert (sem s i = None). { eapply sem_outside_above. apply H0.\n              solve_Bounds e. } rewrite H5 in Hsem. simpl in Hsem. rewrite Hsem in Hsem0.\n              inversion Hsem0; reflexivity.\n            ** destruct (sem s i); simpl in Hsem; rewrite Hsem in Hsem0. inversion Hsem0.\n                destruct (i == e0); simpl in Hsem. inversion Hsem0. inversion Hsem0.\n            ** destruct (sem s i). simpl in Hsem. rewrite Hsem in Hsem0. inversion Hsem0.\n              simpl in Hsem. rewrite Hsem in Hsem0. inversion Hsem0.\nQed.\n\nLemma fromList_Desc:\n  forall xs,\n  Desc' (fromList xs) None None (fun i => sem_for_lists (rev xs) i).\nProof.\n  intros.\n  cbv beta delta [fromList].\n  destruct xs as [ | ? [|??] ].\n  * solve_Desc e. reflexivity.\n  * destruct p. solve_Desc e. intros. simpl. destruct (i == e0); reflexivity. \n  * fold fromList'. destruct p.\n    zeta_one.\n    fold not_ordered.\n    zeta_one.\n    fold fromList_create_f.\n    fold fromList_create.\n    zeta_one.\n    fold fromList_go_f.\n    fold fromList_go.\n    zeta_one.\n    destruct_match.\n    - applyDesc e fromList'_Desc.\n      solve_Desc e. simpl. setoid_rewrite sem_list_app. setoid_rewrite sem_list_app.\n       simpl. destruct p0. simpl in Hsem. setoid_rewrite sem_list_app in Hsem. simpl in Hsem.\n      (*setoid_rewrite elem_cons.*)\n      f_solver e.\n    - repeat replace (#1) with (2^0)%Z by reflexivity.\n      eapply fromList_go_Desc.\n      + lia.\n      + destruct p0. simpl in Heq. \n        solve_Bounded e.\n      + right. reflexivity.\n      + intros.\n        solve_Desc e. simpl. setoid_rewrite sem_list_app. setoid_rewrite sem_list_app.\n        simpl. simpl in H1. setoid_rewrite sem_list_app in H1. simpl in H1.\n        f_solver e.\nQed.\n\nEnd WF.\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/theories/MapProofs/FromListProofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.25057062075282627}}
{"text": "(* Deep embedding of a subset of SigmaHCOL *)\n\nRequire Import Coq.Lists.List.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Arith.Peano_dec.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Strings.Ascii.\n\nRequire Import Psatz.\n\nRequire Import Paco.paco.\n\nRequire Import Helix.Util.Misc.\nRequire Import Helix.Util.ListSetoid.\nRequire Import Helix.HCOL.CarrierType.\nRequire Import Helix.DSigmaHCOL.DSigmaHCOL.\nRequire Import Helix.DSigmaHCOL.NType.\nRequire Import Helix.MSigmaHCOL.Memory.\nRequire Import Helix.MSigmaHCOL.MemSetoid.\nRequire Import Helix.MSigmaHCOL.CType.\nRequire Import Helix.Tactics.HelixTactics.\nRequire Import Helix.Util.OptionSetoid.\nRequire Import Helix.Util.ErrorSetoid.\nRequire Import Helix.DSigmaHCOL.DSigmaHCOLEval.\n\nRequire Import ITree.ITree.\nRequire Import ITree.Events.Exception.\nRequire Import ITree.Eq.\nRequire Import ITree.Interp.InterpFacts.\nRequire Import ITree.Events.State.\nRequire Import ITree.Events.StateFacts.\nRequire Import ITree.Basics.CategoryTheory.\nRequire Import ITree.Basics.CategoryOps.\nRequire Import ITree.Basics.CategoryKleisli.\nRequire Import ITree.Basics.CategoryKleisliFacts.\nRequire Import ITree.Core.KTree.\nRequire Import ITree.Core.KTreeFacts.\n\nRequire Import MathClasses.interfaces.canonical_names.\nRequire Import MathClasses.misc.decision.\n\nGlobal Open Scope nat_scope.\n\nRequire Import ExtLib.Structures.Monads.\nRequire Import ExtLib.Data.Monads.OptionMonad.\n\nImport MonadNotation.\nLocal Open Scope monad_scope.\n\n(* TODOYZ: Host this on the Vellvm side? On the ITree side? *)\nLtac state_step :=\n  match goal with\n  | |- interp_state _ (ITree.bind _ _) _ ≈ _ => rewrite interp_state_bind\n  | |- ITree.bind (ITree.bind _ _) _ ≈ _ => rewrite bind_bind\n  | |- ITree.bind (Vis _ _) _ ≈ _ => rewrite bind_vis\n  | |- ITree.bind (Ret _) _ ≈ _ => rewrite bind_ret_l\n  | |- context[interp_state _ (Ret _) _] => rewrite interp_state_ret\n  | |- context[interp_state _ (trigger _) _] => rewrite interp_state_trigger_eqit\n  | |- context[interp_state _ (vis _ _) _] => rewrite interp_state_vis\n  | |- context[Tau _] => rewrite tau_euttge\n  end.\n\nLtac state_steps' := cbn; repeat (state_step; cbn).\n\nLtac iter_unfold_pointed :=\n  match goal with\n  | |- context[interp_state ?h (iter ?k ?i) _ ≈ _] =>\n    generalize (iter_unfold k); let EQ := fresh \"EQ\" in intros EQ; rewrite (EQ i); clear EQ\n  end.\n\nModule MDSigmaHCOLITree\n       (Import CT : CType)\n       (Import NT : NType)\n       (Import L: MDSigmaHCOL(CT)(NT))\n       (Import LE: MDSigmaHCOLEval(CT)(NT)(L)).\n\n  Include LE.\n\n  Local Open Scope string_scope.\n\n  Variant MemEvent: Type -> Type :=\n  | MemLU  (msg: string) (id: nat): MemEvent mem_block\n  | MemSet (id: nat) (bk: mem_block): MemEvent unit\n  | MemAlloc (size: NT.t): MemEvent nat\n  | MemFree (id: nat): MemEvent unit.\n\n  Definition StaticFailE := exceptE string.\n  Definition StaticThrow (msg: string): StaticFailE void := Throw msg.\n  Definition DynamicFailE := exceptE string.\n  Definition DynamicThrow (msg: string): DynamicFailE void := Throw msg.\n  Definition Event := MemEvent +' StaticFailE +' DynamicFailE.\n\n  Definition Sfail {A: Type} {E} `{DynamicFailE -< E} (msg: string): itree E A :=\n    throw msg.\n\n  Definition Dfail {A: Type} {E} `{DynamicFailE -< E} (msg: string): itree E A :=\n    throw msg.\n\n  Definition lift_Serr {A} {E} `{StaticFailE -< E} (m:err A) : itree E A :=\n    match m with\n    | inl x => throw x\n    | inr x => ret x\n    end.\n\n  Definition lift_Derr {A} {E} `{DynamicFailE -< E} (m:err A) : itree E A :=\n    match m with\n    | inl x => throw x\n    | inr x => ret x\n    end.\n\n  Definition denotePExpr (σ: evalContext) (exp:PExpr): itree Event (nat*NT.t) :=\n    lift_Serr (evalPExpr σ exp).\n\n  Definition denoteMExpr (σ: evalContext) (exp:MExpr): itree Event (mem_block*NT.t) :=\n    match exp with\n    | @MPtrDeref p =>\n      '(bi,size) <- denotePExpr σ p ;;\n      (bi' <- trigger (MemLU \"MPtrDeref\" bi) ;;\n       ret (bi', size))\n    | @MConst t size => ret (t,size)\n    end.\n\n  (* Definition denoteNExpr (σ: evalContext) (e: NExpr): itree Event NT.t := *)\n    (* lift_Serr (evalNExpr σ e). *)\n  Fixpoint denoteNExpr (σ: evalContext) (e:NExpr): itree Event NT.t :=\n    match e with\n    | NVar i =>  lift_Serr\n                 ('(v,_) <- (context_lookup \"NVar not found\" σ i) ;;\n                  (match v with\n                   | DSHnatVal x => ret x\n                   | _ => raise \"invalid NVar type\"\n                   end))\n    | NConst c => Ret c\n    | NDiv a b =>\n      av <- denoteNExpr σ a ;;\n      bv <- denoteNExpr σ b ;;\n      if NTypeEqDec bv NTypeZero then\n        Dfail \"Division by 0\"\n      else\n        Ret (NTypeDiv av bv)\n  | NMod a b   =>\n    av <- denoteNExpr σ a ;;\n      bv <- denoteNExpr σ b ;;\n      if NTypeEqDec bv NTypeZero then\n        Dfail \"Mod by 0\"\n      else\n        Ret (NTypeMod av bv)\n    | NPlus a b  => liftM2 NTypePlus  (denoteNExpr σ a) (denoteNExpr σ b)\n    | NMinus a b => liftM2 NTypeMinus (denoteNExpr σ a) (denoteNExpr σ b)\n    | NMult a b  => liftM2 NTypeMult  (denoteNExpr σ a) (denoteNExpr σ b)\n    | NMin a b   => liftM2 NTypeMin   (denoteNExpr σ a) (denoteNExpr σ b)\n    | NMax a b   => liftM2 NTypeMax   (denoteNExpr σ a) (denoteNExpr σ b)\n    end.\n\n\n  Fixpoint denoteAExpr (σ: evalContext) (e:AExpr): itree Event CT.t :=\n    match e with\n    | AVar i =>\n      '(v,_) <- lift_Serr (context_lookup \"AVar not found\" σ i);;\n        (match v with\n         | DSHCTypeVal x => ret x\n         | _ => Sfail \"invalid AVar type\"\n         end)\n    | AConst x => ret x\n    | AAbs x =>  liftM CTypeAbs (denoteAExpr σ x)\n    | APlus a b => liftM2 CTypePlus (denoteAExpr σ a) (denoteAExpr σ b)\n    | AMult a b => liftM2 CTypeMult (denoteAExpr σ a) (denoteAExpr σ b)\n    | AMin a b => liftM2 CTypeMin (denoteAExpr σ a) (denoteAExpr σ b)\n    | AMax a b => liftM2 CTypeMax (denoteAExpr σ a) (denoteAExpr σ b)\n    | AMinus a b =>\n      a' <- (denoteAExpr σ a) ;;\n         b' <- (denoteAExpr σ b) ;;\n         ret (CTypeSub a' b')\n    | ANth m i =>\n      i' <- denoteNExpr σ i ;;\n      '(m',msize) <- (denoteMExpr σ m) ;;\n      lift_Derr (assert_NT_lt \"ANth index out of bounds\" i' msize) ;;\n      lift_Derr (mem_lookup_err \"ANth not in memory\" (NT.to_nat i') m')\n    | AZless a b => liftM2 CTypeZLess (denoteAExpr σ a) (denoteAExpr σ b)\n    end.\n\n  Definition denoteIUnCType (σ: evalContext) (f: AExpr)\n             (i:NT.t) (a:CT.t): itree Event CT.t :=\n    denoteAExpr ((DSHCTypeVal a,false) :: (DSHnatVal i,false) :: σ) f.\n\n  Definition denoteIBinCType (σ: evalContext) (f: AExpr)\n             (i:NT.t) (a b:CT.t): itree Event CT.t :=\n    denoteAExpr ((DSHCTypeVal b,false) :: (DSHCTypeVal a,false) :: (DSHnatVal i,false) :: σ) f.\n\n  Definition denoteBinCType (σ: evalContext) (f: AExpr)\n             (a b:CT.t): itree Event CT.t :=\n    denoteAExpr ((DSHCTypeVal b,false) :: (DSHCTypeVal a,false) :: σ) f.\n\n  Fixpoint denoteDSHIMap\n           (n: nat)\n           (f: AExpr)\n           (σ: evalContext)\n           (x y: mem_block) : itree Event (mem_block)\n    :=\n      match n with\n      | O => ret y\n      | S n =>\n        v <- lift_Derr (mem_lookup_err \"Error reading memory denoteDSHIMap\" n x) ;;\n        vn <- lift_Serr (NT.from_nat n) ;;\n        v' <- denoteIUnCType σ f vn v ;;\n        denoteDSHIMap n f σ x (mem_add n v' y)\n      end.\n\n  Fixpoint denoteDSHMap2\n           (n: nat)\n           (f: AExpr)\n           (σ: evalContext)\n           (x0 x1 y: mem_block) : itree Event (mem_block)\n    :=\n      match n with\n      | O => ret y\n      | S n =>\n        v0 <- lift_Derr (mem_lookup_err (\"Error reading 1st arg memory in denoteDSHMap2 @\" ++ (string_of_nat n) ++ \" in \" ++ string_of_mem_block_keys x0) n x0) ;;\n        v1 <- lift_Derr (mem_lookup_err (\"Error reading 2nd arg memory in denoteDSHMap2 @\" ++ (string_of_nat n) ++ \" in \" ++ string_of_mem_block_keys x1) n x1) ;;\n        v' <- denoteBinCType σ f v0 v1 ;;\n        denoteDSHMap2 n f σ x0 x1 (mem_add n v' y)\n      end.\n\n  Fixpoint denoteDSHBinOp\n           (n off: nat)\n           (f: AExpr)\n           (σ: evalContext)\n           (x y: mem_block) : itree Event (mem_block)\n    :=\n      match n with\n      | O => ret y\n      | S n =>\n        v0 <- lift_Derr (mem_lookup_err \"Error reading 1st arg memory in denoteDSHBinOp\" n x) ;;\n        v1 <- lift_Derr (mem_lookup_err \"Error reading 2nd arg memory in denoteDSHBinOp\" (n+off) x) ;;\n        vn <- lift_Serr (NT.from_nat n) ;;\n        v' <- denoteIBinCType σ f vn v0 v1 ;;\n        denoteDSHBinOp n off f σ x (mem_add n v' y)\n      end.\n\n  Fixpoint denoteDSHPower\n           (σ: evalContext)\n           (n: nat)\n           (f: AExpr)\n           (x y: mem_block)\n           (xoffset yoffset: nat)\n    : itree Event (mem_block)\n    :=\n      match n with\n      | O => ret y\n      | S p =>\n        xv <- lift_Derr (mem_lookup_err \"Error reading 'xv' memory in denoteDSHBinOp\" xoffset x) ;;\n        yv <- lift_Derr (mem_lookup_err \"Error reading 'yv' memory in denoteDSHBinOp\" yoffset y) ;;\n        v' <- denoteBinCType σ f yv xv ;;\n        denoteDSHPower σ p f x (mem_add yoffset v' y) xoffset yoffset\n      end.\n\n\n  Notation iter := (@iter _ (ktree _) sum _ _ _).\n\n  Fixpoint denoteDSHOperator\n           (σ: evalContext)\n           (op: DSHOperator): itree Event unit :=\n        match op with\n        | DSHNop => ret tt\n\n        | DSHAssign (x_p, src_e) (y_p, dst_e) =>\n          '(x_i,x_size) <- denotePExpr σ x_p ;;\n          '(y_i,y_size) <- denotePExpr σ y_p ;;\n          x <- trigger (MemLU \"Error looking up 'x' in DSHAssign\" x_i) ;;\n          y <- trigger (MemLU \"Error looking up 'y' in DSHAssign\" y_i) ;;\n          src <- denoteNExpr σ src_e ;;\n          dst <- denoteNExpr σ dst_e ;;\n          lift_Derr (assert_NT_lt \"DSHAssign 'dst' out of bounds\" dst y_size) ;;\n          v <- lift_Derr (mem_lookup_err \"Error looking up 'v' in DSHAssign\" (to_nat src) x) ;;\n          trigger (MemSet y_i (mem_add (to_nat dst) v y))\n\n        | @DSHIMap n x_p y_p f =>\n          '(x_i,x_size) <- denotePExpr σ x_p ;;\n          '(y_i,y_size) <- denotePExpr σ y_p ;;\n          lift_Serr (assert_nat_neq \"DSHIMap 'x' must not be equal 'y'\" x_i y_i) ;;\n          lift_Derr (assert_nat_le \"DSHIMap 'n' index out of bounds\" n (to_nat y_size)) ;;\n          x <- trigger (MemLU \"Error looking up 'x' in DSHIMap\" x_i) ;;\n          y <- trigger (MemLU \"Error looking up 'y' in DSHIMap\" y_i) ;;\n          y' <- denoteDSHIMap n f (protect_p σ y_p) x y ;;\n          trigger (MemSet y_i y')\n\n        | @DSHMemMap2 n x0_p x1_p y_p f =>\n          '(x0_i,x0_size) <- denotePExpr σ x0_p ;;\n          '(x1_i,x1_size) <- denotePExpr σ x1_p ;;\n          '(y_i,y_size) <- denotePExpr σ y_p ;;\n          x0 <- trigger (MemLU \"Error looking up 'x0' in DSHMemMap2\" x0_i) ;;\n          x1 <- trigger (MemLU \"Error looking up 'x1' in DSHMemMap2\" x1_i) ;;\n          y <- trigger (MemLU \"Error looking up 'y' in DSHMemMap2\" y_i) ;;\n          y' <- denoteDSHMap2 n f (protect_p σ y_p) x0 x1 y ;;\n          trigger (MemSet y_i y')\n\n        | @DSHBinOp n x_p y_p f =>\n          '(x_i,x_size) <- denotePExpr σ x_p ;;\n          '(y_i,y_size) <- denotePExpr σ y_p ;;\n          lift_Serr (assert_nat_neq \"DSHBinOp 'x' must not be equal 'y'\" x_i y_i) ;;\n          x <- trigger (MemLU \"Error looking up 'x' in DSHBinOp\" x_i) ;;\n          y <- trigger (MemLU \"Error looking up 'y' in DSHBinOp\" y_i) ;;\n          y' <- denoteDSHBinOp n n f (protect_p σ y_p) x y ;;\n          trigger (MemSet y_i y')\n\n        | DSHPower ne (x_p,xoffset) (y_p,yoffset) f initial =>\n          '(x_i,x_size) <- denotePExpr σ x_p ;;\n          '(y_i,y_size) <- denotePExpr σ y_p ;;\n          lift_Serr (assert_nat_neq \"DSHPower 'x' must not be equal 'y'\" x_i y_i) ;;\n          x <- trigger (MemLU \"Error looking up 'x' in DSHPower\" x_i) ;;\n          y <- trigger (MemLU \"Error looking up 'y' in DSHPower\" y_i) ;;\n          n <- denoteNExpr σ ne ;; (* [n] denoted once at the beginning *)\n          xoff <- denoteNExpr σ xoffset ;;\n          yoff <- denoteNExpr σ yoffset ;;\n          lift_Derr (assert_NT_lt \"DSHPower 'y' offset out of bounds\" yoff y_size) ;;\n          let y' := mem_add (to_nat yoff) initial y in\n          y'' <- denoteDSHPower (protect_p σ y_p) (to_nat n) f x y' (to_nat xoff) (to_nat yoff) ;;\n          trigger (MemSet y_i y'')\n\n        | DSHLoop n body =>\n          iter (fun (p: nat) =>\n                  if EqNat.beq_nat p n\n                  then ret (inr tt)\n                  else\n                    vp <- lift_Serr (NT.from_nat p) ;;\n                    denoteDSHOperator ((DSHnatVal vp,false) :: σ) body ;; ret (inl (S p))\n               ) 0\n\n        | DSHAlloc size body =>\n          t_i <- trigger (MemAlloc size) ;;\n          trigger (MemSet t_i (mem_empty)) ;;\n          denoteDSHOperator ((DSHPtrVal t_i size,false) :: σ) body ;;\n          trigger (MemFree t_i)\n\n        | DSHMemInit y_p value =>\n          '(y_i,y_size) <- denotePExpr σ y_p ;;\n          y <- trigger (MemLU \"Error looking up 'y' in DSHMemInit\" y_i) ;;\n          let y' := mem_union (mem_const_block (to_nat y_size) value) y in\n          trigger (MemSet y_i y')\n\n       | DSHSeq f g =>\n          denoteDSHOperator σ f ;; denoteDSHOperator σ g\n      end.\n\n  Definition pure_state {S E} : E ~> Monads.stateT S (itree E)\n    := fun _ e s => Vis e (fun x => Ret (s, x)).\n\n  Definition Mem_handler: MemEvent ~> Monads.stateT memory (itree (StaticFailE +' DynamicFailE)) :=\n    fun T e mem =>\n      match e with\n      | MemLU msg id  => lift_Derr (Functor.fmap (fun x => (mem,x)) (memory_lookup_err msg mem id))\n      | MemSet id blk => ret (memory_set mem id blk, tt)\n      | MemAlloc size => ret (mem, memory_next_key mem)\n      | MemFree id    => ret (memory_remove mem id, tt)\n      end.\n\n  Definition interp_Mem: itree Event ~> Monads.stateT memory (itree (StaticFailE +' DynamicFailE)) :=\n    interp_state (case_ Mem_handler pure_state).\n  Arguments interp_Mem {T} _ _.\n\nEnd MDSigmaHCOLITree.\n", "meta": {"author": "vzaliva", "repo": "helix", "sha": "5d0a71df99722d2011c36156f12b04875df7e1cb", "save_path": "github-repos/coq/vzaliva-helix", "path": "github-repos/coq/vzaliva-helix/helix-5d0a71df99722d2011c36156f12b04875df7e1cb/coq/DSigmaHCOL/DSigmaHCOLITree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.25057062075282627}}
{"text": "Require Import Util LengthEq IL RenamedApart LabelsDefined AppExpFree.\nRequire Import Restrict SetOperations OUnion OptionR.\nRequire Import Annotation Liveness.Liveness Coherence.\n\nSet Implicit Arguments.\nUnset Printing Records.\n\n(** Correctness predicate for  *)\n\nInductive trs\n  : 〔؟⦃var⦄〕 (** globals *)\n    -> stmt                 (** the program *)\n    -> ann (set var)        (** liveness information *)\n    -> ann (list (list var)) (** annotation providing additional parameters for function definitions\n                                inside the program *)\n    -> Prop :=\n| trsExp DL x e s an an_lv lv\n  : trs (restr (getAnn an_lv \\ singleton x) ⊝ DL) s an_lv an\n    -> trs DL (stmtLet x e s) (ann1 lv an_lv) (ann1 nil an)\n| trsIf DL e s t ans ant ans_lv ant_lv lv\n  :  trs DL s ans_lv ans\n     -> trs DL t ant_lv ant\n     -> trs DL (stmtIf e s t) (ann2 lv ans_lv ant_lv) (ann2 nil ans ant)\n| trsRet e DL lv\n  :  trs DL (stmtReturn e) (ann0 lv) (ann0 nil)\n| trsGoto DL G' f Y lv\n  :  get DL (counted f) (Some G')\n     -> trs DL (stmtApp f Y) (ann0 lv) (ann0 nil)\n| trsLet (DL:list (option (set var))) (F:list (params*stmt)) t Za ans ant lv ans_lv ant_lv\n  : length F = length ans_lv\n    -> length F = length ans\n    -> length F = length Za\n    -> (forall n lvs Zs Za' ans',\n          get ans_lv n lvs -> get F n Zs -> get Za n Za' -> get ans n ans'\n          -> trs (restr (getAnn lvs \\ of_list (fst Zs++Za')) ⊝ (Some ⊝ (getAnn ⊝ ans_lv) \\\\ zip (@List.app _) (fst ⊝ F) Za ++ DL)) (snd Zs) lvs ans')\n    -> trs (Some ⊝ (getAnn ⊝ ans_lv) \\\\ zip (@List.app _) (fst ⊝ F) Za ++ DL)\n          t ant_lv ant\n    -> trs DL (stmtFun F t) (annF lv ans_lv ant_lv) (annF Za ans ant).\n\nLemma trs_annotation DL s lv Y\n      : trs DL s lv Y -> annotation s lv /\\ annotation s Y.\nProof.\n  intros. general induction H; split; dcr; econstructor; intros; eauto 20.\n  - edestruct get_length_eq; try eapply H1; eauto.\n    edestruct get_length_eq; try eapply H0; eauto.\n    exploit H3; eauto.\n  - edestruct get_length_eq; try eapply H1; eauto.\n    edestruct get_length_eq; try eapply H; eauto.\n    exploit H3; eauto.\nQed.\n\n\nLemma trs_monotone_DL (DL DL' : list (option (set var))) s lv a\n : trs DL s lv a\n   -> DL ≿ DL'\n   -> trs DL' s lv a.\nProof.\n  intros. general induction H; eauto 30 using trs, restrict_subset2.\n  - destruct (PIR2_nth H0 H); eauto; dcr. inv H3.\n    econstructor; eauto.\n  - econstructor; eauto using restrict_subset2, PIR2_app.\nQed.\n\nOpaque to_list.\n\nDefinition compileF (compile : list (list var) -> stmt -> ann (list (list var)) -> stmt)\n           (ZL:list (list var))\n           (F:list (params*stmt))\n           (Za Za':list (list var))\n           (ans:list (ann (list (list var))))\n  : list (params*stmt) :=\n  zip (fun Zs Zaans => (fst Zs ++ fst Zaans, compile (Za'++ZL) (snd Zs) (snd Zaans)))\n      F\n      (zip pair Za ans).\n\nFixpoint compile (ZL:list (list var)) (s:stmt) (an:ann (list (list var))) : stmt :=\n  match s, an with\n    | stmtLet x e s, ann1 _ an => stmtLet x e (compile ZL s an)\n    | stmtIf e s t, ann2 _ ans ant => stmtIf e (compile ZL s ans) (compile ZL t ant)\n    | stmtApp f Y, ann0 _ => stmtApp f (Y++List.map Var (nth (counted f) ZL nil))\n    | stmtReturn e, ann0 _ => stmtReturn e\n    | stmtFun F t, annF Za ans ant =>\n      stmtFun (compileF compile ZL F Za Za ans)\n              (compile (Za++ZL) t ant)\n    | s, _ => s\n  end.\n\n\nLemma fst_compileF_eq ZL F Za Za' ans\n      (LEN1 : length F = length ans)\n      (LEN2 : length F = length Za)\n  : fst ⊝ compileF compile ZL F Za Za' ans = app (A:=var) ⊜ (fst ⊝ F) Za.\nProof.\n  length_equify.\n  unfold compileF.\n  general induction LEN1; simpl; eauto using PIR2.\n  - f_equal. eauto.\nQed.\n\n\nLemma trs_srd AL ZL s ans_lv ans\n  (RD:trs AL s ans_lv ans)\n  : srd AL (compile ZL s ans) ans_lv.\nProof.\n  general induction RD; simpl; eauto using srd.\n  - econstructor; eauto.\n    * unfold compileF; repeat rewrite zip_length2; congruence.\n    * intros. unfold compileF in H4. inv_get. simpl.\n      exploit H3; eauto. simpl.\n      eapply srd_monotone; eauto.\n      eapply restrict_subset; eauto.\n      eapply PIR2_app; eauto.\n      rewrite fst_compileF_eq; eauto.\n    * eapply srd_monotone; eauto.\n      eapply PIR2_app; eauto.\n      rewrite fst_compileF_eq; eauto.\nQed.\n\nInductive additionalParameters_live : list (set var)   (* additional params *)\n                                      -> stmt           (* the program *)\n                                      -> ann (set var)  (* liveness *)\n                                      -> ann (list (list var)) (* additional params *)\n                                      -> Prop :=\n| additionalParameters_liveExp ZL x e s an an_lv lv\n  : additionalParameters_live ZL s an_lv an\n    -> additionalParameters_live ZL (stmtLet x e s) (ann1 lv an_lv) (ann1 nil an)\n| additionalParameters_liveIf ZL e s t ans ant ans_lv ant_lv lv\n  : additionalParameters_live ZL s ans_lv ans\n    -> additionalParameters_live ZL t ant_lv ant\n    -> additionalParameters_live ZL (stmtIf e s t) (ann2 lv ans_lv ant_lv) (ann2 nil ans ant)\n| additionalParameters_liveRet ZL e lv\n    :  additionalParameters_live ZL (stmtReturn e) (ann0 lv) (ann0 nil)\n| additionalParameters_liveGoto ZL Za f Y lv\n  : get ZL (counted f) Za\n    -> Za ⊆ lv\n    -> additionalParameters_live ZL (stmtApp f Y) (ann0 lv) (ann0 nil)\n| additionalParameters_liveLet ZL F t (Za:〔〔var〕〕) ans ant lv ans_lv ant_lv\n                               (ZaLen:❬F❭ = ❬ans❭)\n  : (forall Za' lv Zs n, get F n Zs -> get ans_lv n lv -> get Za n Za' ->\n       of_list Za' ⊆ getAnn lv \\ of_list (fst Zs) /\\ NoDupA eq (fst Zs ++ Za'))\n    -> (forall Zs lv a n, get F n Zs -> get ans_lv n lv -> get ans n a ->\n                    additionalParameters_live (of_list ⊝ Za ++ ZL) (snd Zs) lv a)\n    -> additionalParameters_live ((of_list ⊝ Za) ++ ZL) t ant_lv ant\n    -> length Za = length F\n    -> additionalParameters_live ZL (stmtFun F t) (annF lv ans_lv ant_lv) (annF Za ans ant).\n\nLemma live_sound_compile ZL ZAL Lv s ans_lv ans o (Len:❬ZL❭=❬ZAL❭)\n  (LV:live_sound o ZL Lv s ans_lv)\n  (APL: additionalParameters_live (of_list ⊝ ZAL) s ans_lv ans)\n  : live_sound o (zip (@List.app _) ZL ZAL) Lv (compile ZAL s ans) ans_lv.\nProof.\n  general induction LV; inv APL; inv_get; eauto using live_sound.\n  - simpl. erewrite get_nth; eauto.\n    econstructor; eauto using zip_get with len.\n    + cases; eauto. rewrite <- H1. rewrite of_list_app. eauto with cset.\n    + intros ? ? Get.\n      eapply get_app_cases in Get. destruct Get; dcr; eauto.\n      inv_get.\n      econstructor. rewrite <- H10. eauto using get_in_of_list.\n  - simpl. rewrite <- List.map_app in *.\n    econstructor; eauto.\n    + rewrite fst_compileF_eq; eauto.\n      rewrite <- zip_app; eauto with len.\n    + eauto with len.\n    + unfold compileF; intros; inv_get; simpl.\n      exploit H2; eauto. exploit H12; eauto. dcr.\n      exploit H1; try eapply H9; eauto with len.\n      erewrite @list_get_eq at 1; eauto.\n      * len_simpl.\n        rewrite <- Len.\n        rewrite Nat.add_min_distr_r.\n        rewrite <- ZaLen; eauto with len.\n      * intros. inv_get. eapply get_app_cases in H19 as [?|?]; dcr; len_simpl.\n        -- inv_get. rewrite get_app_lt in H15; [|eauto with len]. inv_get.\n           reflexivity.\n        -- inv_get. rewrite get_app_ge in H15; [|eauto with len]. inv_get.\n           len_simpl.\n           rewrite <- ZaLen in *. rewrite H14 in *. len_simpl. inv_get.\n           rewrite get_app_ge in H18; rewrite H14 in *; eauto with len.\n           inv_get. reflexivity.\n    + intros.\n      unfold compileF in H4. inv_get; simpl.\n      exploit H2; eauto. exploit H10; eauto. dcr.\n      repeat split; eauto.\n      * rewrite of_list_app. clear - H9 H11; cset_tac.\n      * cases; eauto. rewrite of_list_app. clear - H18; cset_tac.\nQed.\n\n\n\n(** ** DVE and Unreachable Code *)\n(** We show that DVE does not introduce unreachable code. *)\n\n\nLemma compile_callChain (trueIsCalled : stmt -> lab -> Prop)  ZL Za F ans n l'\n  : ❬F❭ = ❬ans❭ -> ❬F❭ = ❬Za❭\n    -> (forall (n : nat) (Zs : params * stmt) (a : ann 〔params〕),\n         get F n Zs ->\n         get ans n a ->\n         forall n0 : nat,\n           trueIsCalled (snd Zs) (LabI n0) ->\n           trueIsCalled (compile (Za ++ ZL) (snd Zs) a) (LabI n0))\n     -> callChain trueIsCalled F (LabI l') (LabI n)\n     -> callChain trueIsCalled (compileF compile ZL F Za Za ans)\n    (LabI l') (LabI n).\nProof.\n  intros Len1 Len2 IH CC.\n  general induction CC.\n  + econstructor.\n  + inv_get. econstructor 2.\n    eapply zip_get; eauto using zip_get.\n    simpl.\n    eapply IH; eauto.\n    eauto.\nQed.\n\nLemma compile_isCalled b AL ZL s ans_lv ans n\n      (RD:trs AL s ans_lv ans)\n      (TIC: isCalled b s (LabI n))\n  : isCalled b (compile ZL s ans) (LabI n).\nProof.\n  general induction RD;\n    invt isCalled; simpl; repeat cases; eauto using isCalled;\n    try congruence.\n  - destruct l' as [l'].\n    econstructor; eauto.\n    unfold compileF at 2; len_simpl.\n    eapply compile_callChain; intros; eauto.\n    inv_get. eauto.\nQed.\n\nLemma compile_noUnreachableCode b AL ZL s ans_lv ans\n      (RD:trs AL s ans_lv ans)\n      (NUC: noUnreachableCode (isCalled b) s)\n  : noUnreachableCode (isCalled b) (compile ZL s ans).\nProof.\n  general induction NUC; invt trs; simpl;\n    eauto using noUnreachableCode.\n  - econstructor; try (unfold compileF at 1); intros; inv_get; simpl in *; try len_simpl; eauto with len.\n    + edestruct H1 as [[l] [IC CC]]; eauto.\n      eexists (LabI l); split; eauto.\n      * eapply compile_isCalled; eauto.\n      * eapply compile_callChain; intros; eauto using compile_isCalled.\n        inv_get. eapply compile_isCalled; eauto.\nQed.\n\nLemma compileF_map_length ZL F Za' Za ans (Len1:❬F❭=❬Za❭) (Len2:❬F❭=❬ans❭)\n  : length (A:=var) ⊝ fst ⊝ compileF compile ZL F Za Za' ans =\n    (fun Z (n0 : nat) => n0 + ❬Z❭) ⊜ Za (length (A:=var) ⊝ fst ⊝ F).\nProof.\n  unfold compileF. rewrite map_map.\n  general induction Len1; destruct ans; isabsurd; simpl; eauto.\n  f_equal. eauto with len.\n  erewrite <- IHLen1; eauto.\nQed.\n\nLemma compile_paramsMatch ZAL DL s L lv ans (Len:❬DL❭=❬ZAL❭)\n      (PM:paramsMatch s L)\n      (TRS:trs DL s lv ans)\n  : paramsMatch (compile ZAL s ans) ((fun Z n => n + ❬Z❭) ⊜ ZAL L).\nProof.\n  general induction TRS; invt paramsMatch; simpl in *; eauto using paramsMatch with len.\n  - inv_get.\n    econstructor; eauto using zip_get.\n    erewrite get_nth; eauto with len.\n  - econstructor; eauto.\n    + unfold compileF at 1; intros; inv_get; simpl.\n      exploit H3; eauto. instantiate (1:=(Za ++ ZAL)). len_simpl. omega.\n      eqassumption. rewrite zip_app; eauto with len.\n      f_equal.\n      eapply compileF_map_length; eauto with len.\n    + exploit IHTRS; eauto.\n      instantiate (1:=(Za ++ ZAL)). len_simpl. omega.\n      eqassumption. rewrite zip_app; eauto with len.\n      f_equal.\n      eapply compileF_map_length; eauto with len.\nQed.\n\nLemma compile_app_expfree DL s lv\n      (AEF:app_expfree s)\n  : app_expfree (compile DL s lv).\nProof.\n  general induction AEF; destruct lv; simpl; eauto using app_expfree.\n  - econstructor; intros ? ? Get.\n    eapply get_app_cases in Get.\n    destruct Get; dcr; eauto; inv_get;\n      eauto using isVar.\n  - econstructor; eauto.\n    unfold compileF; intros; inv_get; simpl; eauto.\nQed.", "meta": {"author": "sigurdschneider", "repo": "lvc", "sha": "be41194f16495d283fe7bbc982c3393ac554dd5b", "save_path": "github-repos/coq/sigurdschneider-lvc", "path": "github-repos/coq/sigurdschneider-lvc/lvc-be41194f16495d283fe7bbc982c3393ac554dd5b/theories/Coherence/Delocation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2505706207528262}}
{"text": "Require Import List.\nRequire Import Omega.\n\nRequire Import MachineModel.\nRequire Import Assembler.\nRequire Import Labels.\nRequire Import SameJumpTransitions.\n\n\n(*==============================================\n   Labelled Operational Semantics\n==============================================*)\n\n\n(* rules for reduction that cross a domain, effectively creating a label *)\nReserved Notation \"S '~~' L '~~>' S'\" (at level 50, left associativity).\n\nInductive eval_label : State -> Label -> State -> Prop :=\n  \n| los_eval_call : forall (p p' : Address) (r r' r'' : RegisterFile) (f : Flags) (m m' m'' : Memory) (rd : Register),\n  inst (lookup m p) (call rd) -> \n  p' = lookup m (r rd) ->\n  entry_jump p p' ->\n  set_stack p r m p' r' m' ->\n  r'' = updateR r' SP (S (r' SP)) ->\n  m'' = update m (r'' SP) (S p) ->\n  (p, r, f, m) ~~ Call r'' f p' ~~> (p', r'', f, m'')\n  \n| los_eval_ret : forall (p p' : Address) (r r' r'' : RegisterFile) (f : Flags) (m m' : Memory),\n  inst (lookup m p)  ret ->\n  p' =  lookup m (r SP) ->\n  exit_jump p p' ->\n  set_stack p r m p' r' m' ->\n  r'' = updateR r' SP (minus (r' SP) 1) ->\n  (p, r, f, m) ~~ Return r f p' ~~> (p', r'', f, m')\n  \n| los_eval_callback : forall (p p' : Address) (r r' r'' : RegisterFile) (f : Flags) (m m' m'' : Memory) (rd : Register),\n  inst (lookup m p) (call rd) -> \n  p' = lookup m (r rd) ->\n  exit_jump p p' ->\n  r' = updateR r SP (S (r SP)) ->\n  m' = update m (r' SP) (S p)->\n  set_stack p r m p' r' m' ->\n  r'' = updateR r' SP (S (r' SP)) ->\n  m'' = (update m' (r'' SP) (address_returnback_entry_point)) ->\n  (p, r, f, m) ~~ Callback r f p' ~~> (p', r'', f, m'')\n  \n| los_eval_retback : forall (p p' : Address) (r r' r'' : RegisterFile) (f : Flags) (m m' : Memory),\n  inst (lookup m p)  ret ->\n  p' =  lookup m (r SP) ->\n  p' = address_returnback_entry_point ->\n  entry_jump p p' ->\n  set_stack p r m p' r' m' ->\n  r'' = updateR r' SP (minus (r' SP) 1) ->\n  (p, r, f, m) ~~ Returnback r'' f p' ~~> ( p', r'', f, m')\n\n| los_eval_writeout : forall (p : Address) (r : RegisterFile) (f : Flags) (m m' : Memory) (rd rs : Register),\n  inst (lookup m p) (movs rd rs) -> \n  int_jump p (S p) ->\n  unprotected (r rd) ->\n  m' = update m  (r rd) (r rs)->  \n  (p, r, f, m) ~~ Write_out (r rd) (r rs) ~~> ((S p), r, f, m')\n\n| los_eval_int : forall (p p' : Address) (r r' : RegisterFile) (f f' : Flags) (m m' : MemSec) (me : MemExt) ,\n  (p, r, f, m) --i--> (p', r', f', m') ->\n  ( ~ (inst (lookupMS m p) (halt))) ->\n  (p, r, f, (plug me m)) ~~ Tau ~~> (p', r', f', (plug me m'))\n\n| los_eval_ext : forall (p p' : Address) (r r' : RegisterFile) (f f' : Flags) (m : MemSec) (me me' : MemExt) ,\n  (p, r, f, me) --e--> (p', r', f', me') ->\n  ( ~ (inst (lookupME me p) (halt))) ->\n  (p, r, f, (plug me m)) ~~ Tau ~~> (p', r', f', (plug me' m))  \n\n| los_eval_int_halt : forall (p p' : Address) (r r' : RegisterFile) (f f' : Flags) (m m' : MemSec) (me : MemExt) ,\n  (p, r, f, m) --i--> (p', r', f', m') ->\n  (inst (lookupMS m p) (halt)) ->\n  (p, r, f, (plug me m)) ~~ Tick ~~> (p', r', f', (plug me m'))\n\n| los_eval_ext_halt : forall (p p' : Address) (r r' : RegisterFile) (f f' : Flags) (m : MemSec) (me me' : MemExt) ,\n  (p, r, f, me) --e--> (p', r', f', me') ->\n  (inst (lookupME me p) (halt)) ->\n  (p, r, f, (plug me m)) ~~ Tick ~~> (p', r', f', (plug me' m))  \n\n  where \"S '~~' L '~~>' S'\" := (eval_label S L S') : type_scope.\n\n\nReserved Notation \"S '=~=' L '=~=>>' S'\" (at level 50, left associativity).\n\n\n\n\nInductive eval_trace : State -> list Label -> State -> Prop :=\n| lbl_trace_refl : forall (t : State),\n  t =~= nil =~=>> t\n\n| lbl_trace_tau : forall (t t' : State),\n  t ~~ Tau ~~> t' ->\n  t =~= nil =~=>> t'\n\n| lbl_trace_trans : forall (t t' t'' : State) (l : Label) (l' : list Label),\n  ~ (l = Tau) ->\n  t ~~ l ~~> t' ->\n  t' =~= l' =~=>> t''->\n  t =~= cons l l' =~=>> t''\n\nwhere \"T '=~=' L '=~=>>' T'\" := (eval_trace T L T') : type_scope.\n\n\n\n\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/LabelledOperationalSemantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2505706207528262}}
{"text": "From Coq Require Import String Arith NArith ZArith Eqdep_dec.\nFrom Vyper Require Import Config Calldag.\nFrom Vyper.L10 Require Import AST Base Callset Descend Expr Stmt.\nFrom Vyper Require FSet Map UInt256.\n\nLocal Open Scope list_scope.\nLocal Open Scope string_scope.\n\nSection Interpret.\nContext {C: VyperConfig}.\n\n(** Initialize a map of local variables with argument names and argument values. *)\nFixpoint bind_args (names: list string) (values: list uint256)\n: string + string_map uint256\n:= let _ := string_map_impl in\n   match names with\n   | nil => match values with\n            | nil => inr Map.empty\n            | _ => inl \"function called with too many arguments\"\n            end\n   | hn :: tn => match values with\n                 | nil => inl \"function called with too few arguments\"\n                 | hv :: tv =>\n                     match bind_args tn tv with\n                     | inl err => inl err\n                     | inr bindings =>\n                        match Map.lookup bindings hn with\n                        | Some _ => inl \"duplicate argument name\"\n                        | None => inr (Map.insert bindings hn hv)\n                        end\n                     end\n                 end\n   end.\n\nLocal Lemma interpret_call_helper {this_decl: decl}\n                                  {fun_name: string}\n                                  {arg_names: list string}\n                                  {body: list stmt}\n                                  (E: this_decl = FunDecl fun_name arg_names body):\n  let _ := string_set_impl in FSet.is_subset (stmt_list_callset body) (decl_callset this_decl) = true.\nProof.\nsubst this_decl. unfold decl_callset. apply FSet.is_subset_refl.\nQed.\n\n\nFixpoint interpret_call {call_depth_bound: nat}\n                        {cd: calldag}\n                        (builtins: string -> option builtin)\n                        (fc: fun_ctx cd call_depth_bound)\n                        (world: world_state)\n                        (arg_values: list uint256)\n{struct call_depth_bound}\n: world_state * expr_result uint256\n:= match call_depth_bound as call_depth_bound' return _ = call_depth_bound' -> _ with\n   | O => fun Ebound => False_rect _ (Nat.nlt_0_r (fun_depth fc)\n                                                  (eq_ind _ _\n                                                          (proj1 (Nat.ltb_lt _ _) (fun_bound_ok fc))\n                                                          _ Ebound))\n   | S new_call_depth_bound => fun Ebound =>\n      match fun_decl fc as d return _ = d -> _ with\n      | FunDecl _ arg_names body => fun E =>\n          match bind_args arg_names arg_values with\n          | inl err => (world, expr_error err)\n          | inr loc =>\n              let '(world', loc', result) := interpret_stmt_list Ebound fc (interpret_call builtins)\n                                                                 builtins world loc body\n                                                                 (interpret_call_helper E)\n              in (world', match result with\n                          | StmtSuccess => ExprSuccess zero256\n                          | StmtReturnFromFunction x => ExprSuccess x\n                          | StmtAbort AbortBreak\n                          | StmtAbort AbortContinue => expr_error \"break and continue not allowed\"\n                          | StmtAbort a => ExprAbort a\n                          end)\n          end\n      | _ => fun _ => (world, expr_error \"declaration not found\")\n      end eq_refl\n  end eq_refl.\n\n(** This is a simplified interface to interpret_call that takes care of creating a function context. *)\nDefinition interpret (builtins: string -> option builtin)\n                     (cd: calldag)\n                     (function_name: string)\n                     (world: world_state)\n                     (arg_values: list uint256)\n: world_state * expr_result uint256\n:= match make_fun_ctx_and_bound cd function_name with\n   | None => (world, expr_error \"declaration not found\")\n   | Some (existT _ bound fc) => interpret_call builtins fc world arg_values\n   end.\n\nEnd Interpret.", "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/L10/Interpret.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.25054582751431925}}
{"text": "Require Import UNIVERSE.\nRequire Import CoqlibC.\nRequire Import Simulation.\nRequire Import LinkingC.\nRequire Import Smallstep.\n\nRequire Import ModSem Mod Sem.\nRequire Import SimSymb SimMem SimMod SimModSem SimProg (* SimLoad *) SimProg.\nRequire Import SemProps Ord.\nRequire Import Sound Preservation.\n\nSet Implicit Arguments.\n\n\n\n\nSection ADQSOUND.\n\n  Context `{SM: SimMem.class}.\n  Context {SS: SimSymb.class SM}.\n  Context `{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  Hypothesis (WFSKSRC: forall md (IN: In md p_src), <<WF: Sk.wf md>>).\n  Hypothesis (WFSKTGT: forall md (IN: In md p_tgt), <<WF: Sk.wf md>>).\n\n  Variable sk_link_src sk_link_tgt: Sk.t.\n  Hypothesis LINKSRC: (link_sk p_src) = Some sk_link_src.\n  Hypothesis LINKTGT: (link_sk p_tgt) = Some sk_link_tgt.\n  Let sem_src := Sem.sem p_src.\n  Let sem_tgt := Sem.sem p_tgt.\n\n  Let skenv_link_src := (Sk.load_skenv sk_link_src).\n  Let skenv_link_tgt := (Sk.load_skenv sk_link_tgt).\n\n  Variable ss_link: SimSymb.t.\n  Hypothesis (SIMSKENV: exists sm, SimSymb.sim_skenv sm ss_link skenv_link_src skenv_link_tgt).\n\n  Hypothesis INCLSRC: forall mp (IN: In mp pp), SkEnv.includes skenv_link_src (Mod.sk mp.(ModPair.src)).\n  Hypothesis INCLTGT: forall mp (IN: In mp pp), SkEnv.includes skenv_link_tgt (Mod.sk mp.(ModPair.tgt)).\n  Hypothesis SSLE: forall mp (IN: In mp pp), SimSymb.le mp.(ModPair.ss) ss_link.\n\n  Let WFSKLINKSRC: Sk.wf sk_link_src. eapply link_list_preserves_wf_sk; et. Qed.\n  Let WFSKLINKTGT: Sk.wf sk_link_tgt. eapply link_list_preserves_wf_sk; et. Qed.\n\n  (* Let ge: Ge.t := sem_src.(Smallstep.globalenv). *)\n\n  Inductive sound_ge (su0: Sound.t) (m0: mem): Prop :=\n  | sound_ge_intro\n      (GE: Forall (fun ms => su0.(Sound.skenv) m0 ms.(ModSem.skenv) /\\ su0.(Sound.skenv) m0 ms.(ModSem.skenv_link))\n                  (fst sem_src.(Smallstep.globalenv)))\n  .\n\n  Lemma lepriv_preserves_sound_ge\n        m0 su0 su1\n        (GE: sound_ge su0 m0)\n        (LE: Sound.lepriv su0 su1):\n      <<GE: sound_ge su1 m0>>.\n  Proof.\n    inv GE. econs; eauto. rewrite Forall_forall in *. ii. split; eapply Sound.skenv_lepriv; try apply GE0; eauto.\n  Qed.\n\n  Lemma hle_preserves_sound_ge\n        m0 su0 su1\n        (WF: Sound.wf su0)\n        (GE: sound_ge su0 m0)\n        (LE: Sound.hle su0 su1):\n      <<GE: sound_ge su1 m0>>.\n  Proof.\n    eapply lepriv_preserves_sound_ge; eauto. eapply Sound.hle_lepriv; et.\n  Qed.\n\n  Lemma mle_preserves_sound_ge\n        m0 m1 su0\n        (GE: sound_ge su0 m0)\n        (LE: Sound.mle su0 m0 m1):\n      <<GE: sound_ge su0 m1>>.\n  Proof.\n    inv GE. econs; eauto. rewrite Forall_forall in *. ii. split; eapply Sound.skenv_mle; try apply GE0; eauto.\n  Qed.\n\n  (* stack can go preservation when su0 is given *)\n  Inductive sound_stack (args: Args.t): list Frame.t -> Prop :=\n  | sound_stack_nil\n      (EXSU: exists su_ex, Sound.args su_ex args /\\ sound_ge su_ex (Args.get_m args)):\n      sound_stack args []\n  | sound_stack_cons\n      args_tail tail ms lst0\n      (TL: sound_stack args_tail tail)\n      (FORALLSU: forall su0\n          (SUARGS: Sound.args su0 args_tail)\n          (SUGE: sound_ge su0 (Args.get_m args_tail)),\n          (<<HD: forall\n                 sound_state_all\n                 (PRSV: local_preservation_noguarantee ms sound_state_all),\n                 <<SUST: sound_state_all su0 (Args.get_m args_tail) lst0>>>>)\n          /\\\n          (<<K: forall\n                 sound_state_all\n                 (PRSV: local_preservation_noguarantee ms sound_state_all),\n                 (* (<<SUST: sound_state_all su0 args.(Args.get_m) lst0>>) *)\n                 (* /\\ *)\n                 exists su_gr,\n                   (<<ARGS: Sound.args su_gr args>>) /\\\n                   (<<LE: Sound.lepriv su0 su_gr>>) /\\\n                   (<<K: forall retv lst1 su_ret\n                       (LE: Sound.hle su_gr su_ret)\n                       (SURETV: Sound.retv su_ret retv)\n                       (MLE: Sound.mle su_gr (Args.get_m args) (Retv.get_m retv))\n                       (AFTER: ms.(ModSem.after_external) lst0 retv lst1),\n                       (* sound_state_all su0 args.(Args.get_m) lst1>>) *)\n                       sound_state_all su0 (Args.get_m args_tail) lst1>>)\n             >>)\n          /\\\n          (<<MLE: Sound.mle su0 (Args.get_m args_tail) (Args.get_m args)>>)\n      )\n      (EXSU: exists su_ex, Sound.args su_ex args_tail /\\ sound_ge su_ex (Args.get_m args_tail))\n      (EX: exists sound_state_ex, local_preservation ms sound_state_ex):\n      sound_stack args ((Frame.mk ms lst0) :: tail).\n\n  Inductive sound_state: state -> Prop :=\n  | sound_state_normal\n      args_tail tail ms lst0 m_arg\n      (TL: sound_stack args_tail tail)\n      (EXSU: exists su_ex, Sound.args su_ex args_tail /\\ sound_ge su_ex m_arg)\n      (FORALLSU: forall su0\n          (SUARGS: Sound.args su0 args_tail)\n          (SUGE: sound_ge su0 (Args.get_m args_tail)),\n          (<<HD: forall\n              sound_state_all\n              (PRSV: local_preservation_noguarantee ms sound_state_all),\n              <<SUST: sound_state_all su0 m_arg lst0>>>>))\n      (EX: exists sound_state_ex, local_preservation ms sound_state_ex)\n      (ABCD: (Args.get_m args_tail) = m_arg)\n    :\n      sound_state (State ((Frame.mk ms lst0) :: tail))\n  | sound_state_call\n      m_tail frs args\n      (* (ARGS: Sound.args su0 args) *)\n      (STK: sound_stack args frs)\n      (* (MLE: Sound.mle su0 m_tail args.(Args.get_m)) *)\n      (EQ: (Args.get_m args) = m_tail)\n      (EXSU: exists su_ex, Sound.args su_ex args /\\ sound_ge su_ex m_tail):\n      sound_state (Callstate args frs).\n\n  Lemma sound_init\n        st0\n        (INIT: sem_src.(Smallstep.initial_state) st0):\n    <<SU: sound_state st0>>.\n  Proof.\n    inv INIT. clarify. clear skenv_link_tgt p_tgt skenv_link_tgt sem_tgt LINKTGT INCLTGT WFSKTGT SIMSKENV.\n    hexploit Sound.init_spec; eauto. i; des. esplits; eauto.\n    assert(WFSKE: SkEnv.wf (Sk.load_skenv sk_link_src)).\n    { eapply SkEnv.load_skenv_wf; et. }\n    assert(GE: sound_ge su_init m_init).\n    { econs. rewrite Forall_forall. intros ? IN. ss. des_ifs. u in IN.\n      rewrite in_map_iff in IN. des; ss; clarify.\n      + s. split; try eapply Sound.system_skenv; eauto.\n      + assert(INCL: SkEnv.includes (Sk.load_skenv sk_link_src) (Mod.sk x0)).\n        { unfold p_src in IN0. unfold ProgPair.src in *. rewrite in_map_iff in IN0. des. clarify. eapply INCLSRC; et. }\n        split; ss.\n        * eapply Sound.skenv_project; eauto.\n          { eapply link_load_skenv_wf_mem; et. }\n          rewrite <- Mod.get_modsem_skenv_spec; ss. eapply SkEnv.project_impl_spec; et.\n        * rewrite Mod.get_modsem_skenv_link_spec. ss.\n    }\n    econs; eauto. econs; eauto.\n    (* - eapply Sound.greatest_adq; eauto. *)\n    (* - econs; eauto. *)\n    (* - eapply vle_preserves_sound_ge; eauto. *)\n    (*   eapply Sound.greatest_adq; eauto. *)\n  Unshelve.\n    all: ss.\n  Qed.\n\n  Lemma sound_progress\n        st0 tr st1\n        (SUST: sound_state st0)\n        (STEP: Step sem_src st0 tr st1):\n      <<SUST: sound_state st1>>.\n  Proof.\n    inv STEP.\n    - (* CALL *)\n      inv SUST. ss. des. exploit FORALLSU; eauto. { eapply local_preservation_noguarantee_weak; eauto. } intro T; des.\n      inv EX. exploit CALL; eauto. i; des. esplits; eauto. econs; eauto; cycle 1.\n      + esplits; eauto. eapply lepriv_preserves_sound_ge; eauto.\n        { eapply mle_preserves_sound_ge; eauto. }\n      + econs; eauto; cycle 1.\n        { esplits; eauto. econs; eauto. }\n        ii. esplits; eauto.\n        * ii. exploit FORALLSU; try apply SUARGS; eauto.\n        * ii. exploit FORALLSU; try apply SUARGS; eauto. intro U; des.\n          inv PRSV. exploit CALL0; eauto. i; des. esplits; eauto. ii. eapply K0; eauto.\n        * exploit FORALLSU; eauto.\n          { eapply local_preservation_noguarantee_weak; eauto. econs; eauto. }\n          i; des. exploit CALL; eauto. i; des. ss.\n    - (* INIT *)\n      inv SUST. ss. des_ifs. esplits; eauto. econs; eauto.\n      + ii. esplits; eauto.\n        * ii. inv PRSV. inv SUGE. rewrite Forall_forall in *.\n          exploit GE; eauto. { ss. des_ifs. eapply MSFIND. } intro T; des. eapply INIT0; et.\n      + inv MSFIND. ss. rr in SIMPROG. rewrite Forall_forall in *. des; clarify.\n        { eapply system_local_preservation. }\n        u in MODSEM. rewrite in_map_iff in MODSEM. des; clarify. rename x into md_src.\n        assert(exists mp, In mp pp /\\ mp.(ModPair.src) = md_src).\n        { clear - MODSEM0. rr in pp. rr in p_src. subst p_src. rewrite in_map_iff in *. des. eauto. }\n        des. exploit SIMPROG; eauto. intros MPSIM. inv MPSIM.\n        destruct SIMSKENV. exploit SIMMS.\n        { eapply INCLSRC; et. }\n        { eapply INCLTGT; et. }\n        { eapply SkEnv.load_skenv_wf; et. }\n        { eapply SkEnv.load_skenv_wf; et. }\n        { eapply SSLE; eauto. }\n        { eauto. }\n        intro SIM; des. inv SIM. ss. esplits; eauto.\n    - (* INTERNAL *)\n      inv SUST. ss. esplits; eauto. econs; eauto. i. des.\n      exploit FORALLSU; eauto. { eapply local_preservation_noguarantee_weak; eauto. } intro U; des. esplits; eauto. i. ss. inv PRSV.\n      eapply STEP; eauto.\n      + eapply FORALLSU; eauto. econs; eauto.\n      + split; ii; ModSem.tac.\n    - (* RETURN *)\n      inv SUST. ss. rename ms into ms_top. rename args_tail into args_tail_top.\n      inv TL. ss. unfold Frame.update_st. s. des. esplits; eauto. econs; eauto. ii. esplits; eauto.\n      + ii. exploit FORALLSU0; eauto. i; des. exploit K; eauto. i; des. inv EX.\n        exploit RET; eauto.\n        { eapply FORALLSU; eauto.\n          { eapply lepriv_preserves_sound_ge. { eapply mle_preserves_sound_ge; eauto. } eauto. }\n          { eapply local_preservation_noguarantee_weak; eauto. econs; et. } }\n        i; des.\n        eapply K0; eauto.\n  Unshelve.\n    all: ss.\n  Qed.\n\n  (* Lemma sound_progress_star *)\n  (*       st0 tr st1 *)\n  (*       (SUST: sound_state st0) *)\n  (*       (STEP: Star sem_src st0 tr st1): *)\n  (*     <<SUST: sound_state st1>>. *)\n  (* Proof. *)\n  (*   induction STEP. *)\n  (*   - esplits; eauto. *)\n  (*   - clarify. i. exploit sound_progress; eauto. *)\n  (* Qed. *)\n\n  (* Lemma sound_progress_plus *)\n  (*       st0 tr st1 *)\n  (*       (SUST: sound_state st0) *)\n  (*       (STEP: Plus sem_src st0 tr st1): *)\n  (*     <<SUST: sound_state st1>>. *)\n  (* Proof. *)\n  (*   eapply sound_progress_star; eauto. eapply plus_star; eauto. *)\n  (* Qed. *)\n\n  Theorem preservation: @preservation sem_src sound_state.\n  Proof.\n    econs.\n    - eapply sound_init.\n    - eapply sound_progress.\n  Qed.\n\nEnd ADQSOUND.\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/AdequacySound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.25054582751431925}}
{"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 Integers.\nRequire Import Floats.\nRequire Import Zwf.\nRequire Import Maps.\nRequire Import Memory.\nRequire Import Globalenvs.\nRequire Import Ctypes.\nRequire Import Cltypes.\nRequire Import ExtraList.\nRequire Import Streams.\nRequire Import Peano.\nRequire Import Lident.\nRequire Import Ltypes.\nRequire Import Lvalues.\nRequire Import Lustre.\n\nSet Implicit Arguments.\n\nSection PTREE.\n\nVariable A: Type.\n\nLemma ptree_set_swap:\n  forall e id1 id2 (a1 a2: A), id1 <> id2 -> \n  PTree.set id2 a2 (PTree.set id1 a1 e) = PTree.set id1 a1 (PTree.set id2 a2 e).\nProof. \n  induction e; induction id1; induction id2; \n  simpl; intros; auto; try congruence.\n  f_equal. apply IHid1. congruence.\n  f_equal. apply IHid1. congruence.\n  f_equal. apply IHe2. congruence.\n  f_equal. apply IHe1. congruence.\nQed.\n\nLemma ptree_set_repeat_leaf:\n  forall id (v: A) v1,\n  PTree.set id v (PTree.set id v1 PTree.Leaf) = PTree.set id v PTree.Leaf.\nProof.\n  induction id; simpl; intros; f_equal; auto.\nQed.\n\nLemma ptree_set_repeat:\n  forall e id (v: A) v1,\n  PTree.set id v (PTree.set id v1 e) = PTree.set id v e.\nProof.\n  induction e, id; simpl; intros; f_equal; auto;\n  apply ptree_set_repeat_leaf.\nQed.\n\nLemma ptree_set_same:\n  forall e id (v: A),\n  e ! id = Some v ->\n  PTree.set id v e = e.\nProof.\n  induction e, id; simpl; intros; try congruence; f_equal; auto.\nQed.\n\nEnd PTREE.\n\nSection ENV.\n\n\n(** The local environment maps local variables to mvl and types. *)\n\nDefinition locenv:= PTree.t (mvl*type).\n\n(** The tempo environment maps tempo variables to tree of locenv. *)\n\nInductive env: Type := mkenv {\n  le: locenv;  (**r local tempo environment. *)\n  sube: PTree.t (list env)  (**r subset tempo environment of the node call. *)\n}.\n\n(** Subset tempo environment of the node call。*)\n\nDefinition subenv := PTree.t (list env).\n\nDefinition empty_locenv := PTree.empty (mvl*type).\nDefinition empty_subenv := PTree.empty (list env).\nDefinition empty_env := mkenv empty_locenv empty_subenv.\n\nDefinition nat_of_int(i: int):= nat_of_Z (Int.unsigned i).\n\n(** The chage of env state after the node call executed. *)\n\nInductive callnd_env(c: calldef)(i: int): subenv -> subenv -> env -> env -> Prop := \n  | callnd_env_: forall se1 se2 e1 e2 efs,\n     se1 ! (instid c) = Some efs ->\n     nth_error efs (nat_of_int i) = value e1 ->\n     se2 = PTree.set (instid c) (replace_nth efs (nat_of_int i) e2) se1 ->\n     Z_of_nat (length efs) = Int.unsigned (intof_opti (callnum c)) ->\n     callnd_env c i se1 se2 e1 e2.\n\n(** The chage of env state after the node or function call executed. *)\n\nInductive call_env(c: calldef)(i: int): subenv -> subenv -> env -> env -> Prop := \n  | call_env_: forall se1 se2 e1 e2,\n     cakind c = true ->\n     callnd_env c i se1 se2 e1 e2 ->\n     call_env c i se1 se2 e1 e2\n  | call_env_func_: forall se,\n     cakind c = false ->\n     call_env c i se se empty_env empty_env.\n\n(** The property of variable in locenv after allocation. *)\n\nDefinition locenv_range_perm_var(eh: locenv)(id: ident)(ty: type) :=\n  exists m, eh ! id = Some (m,ty) \n    /\\ Z_of_nat (length m) = sizeof ty\n    /\\ range_perm m 0 (sizeof ty).\n\n(** The property of variables in locenv after allocation. *)\n\nDefinition locenv_range_perm_vars(eh: locenv)(al: list (ident*type)) :=\n  forall id ty, In (id,ty) al -> locenv_range_perm_var eh id ty.\n\nInductive callnd_inst_env(c: calldef)(i: int)(se: subenv): env -> Prop :=\n  | callnd_inst_env_node: forall efs ef,\n     se ! (instid c) = Some efs ->\n     nth_error efs (nat_of_int i) = value ef ->\n     Z_of_nat (length efs) = Int.unsigned (intof_opti (callnum c)) ->\n     callnd_inst_env c i se ef.\n\nLemma callnd_env_range_i:\n  forall cdef i se se' ef ef',\n  callnd_env cdef i se se' ef ef' ->\n  (0 <= Int.unsigned i < Int.unsigned (intof_opti (callnum cdef)))%Z.\nProof.\n  intros. inv H. rewrite <-H3. apply nth_error_value_lt in H1.\n  apply Nat2Z.inj_lt in H1. unfold nat_of_int in H1.\n  generalize (Int.unsigned_range i); intros.\n  rewrite nat_of_Z_eq in H1; try omega.\nQed.\n\nLemma callnd_inst_env_eq:\n  forall cdef i se se' ef ef',\n  callnd_env cdef i se se' ef ef' ->\n  callnd_inst_env cdef i se ef.\nProof.\n  induction 1. constructor 1 with efs; auto.\nQed.\n\nLemma call_env_determ1:\n  forall cdef i se se1 se2 ef1 ef2 ef1' ef2',\n  call_env cdef i se se1 ef1 ef1' ->\n  call_env cdef i se se2 ef2 ef2' ->\n  ef1 = ef2.\nProof.\n  intros. inv H; inv H0; try congruence.\n  inv H2; inv H3. rewrite H2 in H0. inv H0.\n  rewrite H4 in H5. inv H5; auto. \nQed. \n\nLemma call_env_determ2:\n  forall cdef i se se1 se2 ef ef',\n  call_env cdef i se se1 ef ef' ->\n  call_env cdef i se se2 ef ef' ->\n  se1 = se2.\nProof.\n  intros. inv H; inv H0; try congruence.\n  inv H2; inv H3. congruence. \nQed. \n\nEnd ENV.\n\nSection GLOBAL_ENV.\n\n(** Global environment. *)\n\nDefinition store_init_data(m: mvl)(p: Z)(id: init_data): option mvl:=\n  match id with\n  | Init_int8 n => store Mint8unsigned m p (Vint n)\n  | Init_int16 n => store Mint16unsigned m p (Vint n)\n  | Init_int32 n => store Mint32 m p (Vint n)\n  | Init_float32 n => store Mfloat32 m p (Vsingle n)\n  | Init_float64 n => store Mfloat64 m p (Vfloat n)\n  | Init_space n => Some m\n  | _ => None\n  end.\n\nFixpoint store_init_datas(m: mvl)(p: Z)(idl: init_datas): option mvl :=\n  match idl with\n  | nil => Some m\n  | id :: idl' =>\n      match store_init_data m p id with\n      | None => None\n      | Some m' => store_init_datas m' (p + Genv.init_data_size id) idl'\n      end\n  end.\n\nDefinition init_data_type(init: init_data): Prop :=\n  match init with\n  | Init_addrof _ _ => False\n  | _ => True\n  end.\n\nDefinition init_data_types(inits: list init_data): Prop :=\n  Forall init_data_type inits.\n\nLemma store_init_data_length:\n  forall a o mv mv',\n  store_init_data mv o a = Some mv' ->\n  length mv' = length mv.\nProof.\n  destruct a; simpl; intros; try congruence;\n  apply store_length in H; auto.\nQed.\n\nLemma store_init_datas_length:\n  forall il o mv mv',\n  store_init_datas mv o il = Some mv' ->\n  length mv' = length mv.\nProof.\n  induction il; simpl; intros.\n  +inv H. auto.\n  +destruct (store_init_data mv o a) eqn:?; try congruence.\n   apply store_init_data_length in Heqo0. rewrite <-Heqo0.\n   eapply IHil; eauto.\nQed.\n\nLemma store_init_datas_types:\n  forall il o mv mv',\n  store_init_datas mv o il = Some mv' ->\n  init_data_types il.\nProof.\n  induction il; simpl; intros.\n  constructor.\n  destruct (store_init_data _ _ _) eqn:?; try congruence.\n  constructor 2.\n  destruct a; simpl in *; auto; try congruence.\n  eapply IHil; eauto.\nQed.\n\nFixpoint loadbytes_store_init_data (m: mvl)(p: Z) (il: list init_data) {struct il} : Prop :=\n  match il with\n  | nil => True\n  | Init_int8 n :: il' =>\n      loadbytes m p 1 = Some (Lvalues.encode_val Mint8unsigned (Lvalues.Vint n))\n      /\\ loadbytes_store_init_data m (p + 1) il'\n  | Init_int16 n :: il' =>\n      loadbytes m p 2 = Some (Lvalues.encode_val Mint16unsigned (Lvalues.Vint n))\n      /\\ loadbytes_store_init_data m (p + 2) il'\n  | Init_int32 n :: il' =>\n      loadbytes m p 4 = Some (Lvalues.encode_val Mint32 (Lvalues.Vint n))\n      /\\ loadbytes_store_init_data m (p + 4) il'\n  | Init_float32 n :: il' =>\n      loadbytes m p 4 = Some (Lvalues.encode_val Mfloat32 (Lvalues.Vsingle n))\n      /\\ loadbytes_store_init_data m (p + 4) il'\n  | Init_float64 n :: il' =>\n      loadbytes m p 8 = Some (Lvalues.encode_val Mfloat64 (Lvalues.Vfloat n))\n      /\\ loadbytes_store_init_data m (p + 8) il'\n  | Init_space n :: il' =>\n      if zle n 0 then \n        loadbytes_store_init_data m (p + Zmax n 0) il'\n      else\n        loadbytes m p (Zmax n 0) = Some (list_repeat (nat_of_Z (Zmax n 0)) (Byte Byte.zero))\n        /\\ loadbytes_store_init_data m (p + Zmax n 0) il'\n  | _ :: il' => False\n  end.\n\nLemma store_init_data_outside_bytes:\n  forall a m p m',\n  store_init_data m p a = Some m' ->\n  forall n q,\n  (q + n <= p \\/ p + Genv.init_data_size a <= q)%Z ->\n  loadbytes m' q n = loadbytes m q n.\nProof.\n  destruct a; simpl; intros; try congruence;\n  try (eapply loadbytes_store_other; eauto; fail); \n  try (right; simpl; omega).\nQed.\n\nLemma store_init_datas_outside_bytes:\n  forall il m p m',\n  store_init_datas m p il = Some m' ->\n  forall n q,\n  (q + n <= p \\/ p + Genv.init_data_list_size il <= q)%Z ->\n  loadbytes m' q n = loadbytes m q n.\nProof.\n  induction il; simpl.\n  intros; congruence.\n  intros until m'. caseEq (store_init_data m p a); try congruence. \n  intros m1 A B n q C. \n  generalize (Genv.init_data_size_pos a) (Genv.init_data_list_size_pos il). intros.\n  transitivity (loadbytes m1 q n).\n  eapply IHil; eauto. omega.\n  eapply store_init_data_outside_bytes; eauto. omega.\nQed.\n\nLemma store_init_datas_loadbytes_app:\n  forall chunk v m p m1 il m',\n  store chunk m p v = Some m1 ->\n  store_init_datas m1 (p + size_chunk chunk) il = Some m' ->\n  loadbytes m' p (size_chunk chunk) = Some (encode_val chunk v).\nProof.\n  intros. transitivity (loadbytes m1 p (size_chunk chunk)).\n  eapply store_init_datas_outside_bytes; eauto. omega. \n  generalize H; intros. apply store_length in H.\n  unfold store in *. destruct (valid_access_dec _ _ _); try congruence.\n  destruct v0.\n  unfold loadbytes. rewrite pred_dec_true; auto.\n  inv H1.\n  assert(nat_of_Z (size_chunk chunk) = length (encode_val chunk v)).\n    rewrite encode_val_length; auto.\n  rewrite H1. rewrite getN_setN_same; auto.\n   rewrite encode_val_length.\n  red in H2. unfold size_chunk_nat. rewrite <-Z2Nat.inj_add; try omega.\n  apply Nat2Z.inj_le. rewrite nat_of_Z_eq; try omega.\n  red. rewrite <-H. auto.\nQed. \n\nLemma loadbytes_list_repeat_incl:\n  forall m p q n1 n2 a,\n  loadbytes m p n1 = Some (list_repeat (nat_of_Z n1) a) ->\n  (p <= q /\\ q + n2 <= p + n1)%Z -> \n  (0 < n2)%Z ->\n  loadbytes m q n2  = Some (list_repeat (nat_of_Z n2) a).\nProof.\n  unfold loadbytes. intros.\n  destruct (range_perm_dec m p _) eqn:?; inv H.\n  rewrite pred_dec_true.\n  +f_equal. replace q with (p+(q - p))%Z; try omega.\n   red in r. rewrite Z2Nat.inj_add; try omega.\n   rewrite getN_app with (n1:=nat_of_Z n1).\n   unfold nat_of_Z in *. rewrite H3.\n   unfold getN, getn.\n   replace n1 with ((q-p)+(n1-(q-p)))%Z; try omega.\n   rewrite Z2Nat.inj_add; try omega.\n   rewrite list_repeat_app.\n   rewrite skipn_length_app; rewrite length_list_repeat; try omega.\n   rewrite minus_diag. simpl.\n   apply firstn_list_repeat; auto.\n   apply Nat2Z.inj_le; try omega.\n   rewrite nat_of_Z_eq; try omega.\n   rewrite nat_of_Z_eq; try omega.\n   rewrite <-Z2Nat.inj_add; try omega.\n   apply Nat2Z.inj_le; try omega.\n   rewrite nat_of_Z_eq; try omega.\n   rewrite nat_of_Z_eq; try omega.\n  +unfold range_perm in *. omega.\nQed.\n\nLemma init_data_list_size_zero_loadbytes_store:\n  forall l mv p, Genv.init_data_list_size l = 0%Z ->\n  loadbytes_store_init_data mv p l.\nProof.\n  induction l; simpl; intros; auto.\n  generalize (Genv.init_data_list_size_pos l). intros.\n  destruct a; simpl Genv.init_data_size in *; try omega.\n  destruct (zle _ _); auto.\n  rewrite Z.max_r in *; try omega. apply IHl; auto.\n  rewrite Z.max_l in H; try omega.\nQed.\n\nLemma store_init_datas_bytes:\n  forall il m p m' n,\n  store_init_datas m p il = Some m' ->\n  (p + n = Z_of_nat (length m))%Z ->\n  (Genv.init_data_list_size il <= n)%Z ->\n  loadbytes m p n = Some (list_repeat (nat_of_Z n) (Byte Byte.zero)) ->\n  loadbytes_store_init_data m' p il.\nProof.\n  induction il; simpl.\n  auto.\n  intros until m'. caseEq (store_init_data m p a); try congruence. \n  intros m1 B n C C1 C2 C3.\n  generalize B (Genv.init_data_size_pos a) (Genv.init_data_list_size_pos il); intros.\n  apply store_init_data_length in B0.\n\n  assert(A2: (Genv.init_data_list_size il = 0 \\/ Genv.init_data_list_size il > 0)%Z).\n    omega.\n  destruct A2 as [A2 | A2].\n  +destruct a; simpl in B; intuition; try congruence;\n   try apply init_data_list_size_zero_loadbytes_store; auto.\n   -change 1%Z with (size_chunk Mint8unsigned). \n    erewrite store_init_datas_loadbytes_app; eauto. auto.\n   -change 2%Z with (size_chunk Mint16unsigned). \n    erewrite store_init_datas_loadbytes_app; eauto. auto.\n   -change 4%Z with (size_chunk Mint32).  \n    erewrite store_init_datas_loadbytes_app; eauto. auto.\n   -change 4%Z with (size_chunk Mfloat32). \n    erewrite store_init_datas_loadbytes_app; eauto. auto.\n   -change 8%Z with (size_chunk Mfloat64). \n    erewrite store_init_datas_loadbytes_app; eauto. auto.\n   -inv B. simpl in *.\n    destruct (zle _ _); auto.\n    apply init_data_list_size_zero_loadbytes_store; auto.\n    split; auto.\n    erewrite store_init_datas_outside_bytes; eauto.\n    eapply loadbytes_list_repeat_incl; eauto.\n    omega. rewrite Z.max_l; omega. omega.\n    apply init_data_list_size_zero_loadbytes_store; auto.\n  +exploit (IHil m1 (p+Genv.init_data_size a)%Z m' (n-Genv.init_data_size a)%Z); eauto.\n   rewrite B0. rewrite <-C1. omega. omega.\n   erewrite store_init_data_outside_bytes; eauto.\n\n   eapply loadbytes_list_repeat_incl; eauto. omega.\n   omega. omega.\n   intro D. \n   destruct a; simpl in B; intuition; try congruence.\n   -change 1%Z with (size_chunk Mint8unsigned).  \n    erewrite store_init_datas_loadbytes_app; eauto. auto.\n   -change 2%Z with (size_chunk Mint16unsigned). \n    erewrite store_init_datas_loadbytes_app; eauto. auto.\n   -change 4%Z with (size_chunk Mint32). \n    erewrite store_init_datas_loadbytes_app; eauto. auto.\n   -change 4%Z with (size_chunk Mfloat32). \n    erewrite store_init_datas_loadbytes_app; eauto. auto.\n   -change 8%Z with (size_chunk Mfloat64). \n    erewrite store_init_datas_loadbytes_app; eauto. auto.\n   -inv B. simpl in *.\n    destruct (zle _ _); auto. split; auto.\n    erewrite store_init_datas_outside_bytes; eauto.\n    eapply loadbytes_list_repeat_incl; eauto.\n    split; try omega. rewrite Z.max_l; try omega.\n    left. omega.\nQed.\n\nFunction store_zeros (m: mvl)(n: Z){wf (Zwf 0) n}: option mvl :=\n  if zle n 0 then Some m else\n    let n' := (n - 1)%Z in\n    match store Mint8unsigned m n' Vzero with\n    | Some m' => store_zeros m' n'\n    | None => None\n    end.\nProof.\n  intros. red. omega.\n  apply Zwf_well_founded.\nQed.\n\nDefinition alloc_global(gc:locenv)(idl: (ident * globvar type)): option locenv :=\n  match idl with\n  | (id, (mkglobvar ty init _ _)) =>\n    let sz := Genv.init_data_list_size init in\n    match store_zeros (alloc sz) sz with\n    | None => None\n    | Some m1 =>\n      match store_init_datas m1 0 init with\n      | None => None\n      | Some m2 => Some (PTree.set id (m2,ty) gc)\n      end\n    end\n  end.\n\nFixpoint alloc_globals(gc: locenv)(gl: list (ident * globvar type)): option locenv :=\n  match gl with\n  | nil => Some gc\n  | idl :: gl' =>\n      match alloc_global gc idl with\n      | None => None\n      | Some gc' => alloc_globals gc' gl'\n      end\n  end.\n\nDefinition init_genvc(gl: list (ident * globvar type)): option locenv :=\n  alloc_globals empty_locenv gl.\n\n\nLemma store_zeros_zero:\n  forall m n, (n = 0)%Z ->\n  store_zeros m n = Some m.\nProof.\n  intros m n.\n  functional induction (store_zeros m n); intros; auto.\n  subst. omega.\n  subst. omega.\nQed.\n\nLemma store_zeros_length:\n  forall m n m',\n  store_zeros m n = Some m' ->\n  length m' = length m.\nProof.\n  intros until n.\n  functional induction (store_zeros m n); intros.\n  +inv H. auto.\n  +rewrite IHo; auto; try omega.\n   eapply store_length in e0; eauto.\n  +congruence.\nQed.\n\nLemma store_zeros_exists:\n  forall m n, (n <= Z_of_nat (length m) <= Int.max_signed)%Z ->\n  exists m', store_zeros m n = Some m'.\nProof.\n  intros until n.\n  functional induction (store_zeros m n); intros.\n  +exists m; auto.\n  +apply IHo; try omega.\n   apply store_length in e0; auto. omega.\n  +unfold store in *.\n   destruct (valid_access_dec _ _ _); try congruence.\n   unfold valid_access in *. simpl in *.\n   assert(A: False).\n     apply n0. split.\n     red. split; try omega.\n     red. exists (n-1)%Z. omega.\n   tauto.\nQed.\n\nLemma encode_int_inj_bytes_zero:\n  inj_bytes (encode_int 1 (Int.unsigned Int.zero)) = Byte Byte.zero :: nil.\nProof.\n  rewrite Int.unsigned_zero. unfold setN, replace_map.\n  unfold encode_int. simpl. unfold rev_if_be.\n  destruct Archi.big_endian; simpl; auto.\nQed.\n\nLemma store_zero_outside:\n  forall m n m',\n  store Mint8unsigned m n Vzero = Some m' ->\n  skipn (Z.to_nat (n+1)) m' = skipn (Z.to_nat (n+1)) m.\nProof.\n  unfold store. intros.\n  destruct (valid_access_dec _ _ _); inv H.\n  rewrite encode_int_inj_bytes_zero.\n  destruct v. red in H. simpl in *.\n  unfold setN, replace_map.\n  cut(nat_of_Z n <= length m). intros.\n  rewrite skipn_length_app; rewrite firstn_length;\n  rewrite min_l; try omega.\n  rewrite <-Z2Nat.inj_sub; try omega.\n  replace (n + 1 - n)%Z with 1%Z by omega.\n  simpl. rewrite Z2Nat.inj_add; try omega. auto.\n  apply Z2Nat.inj_le; try omega.\n  apply Nat2Z.inj_le; try omega.\n  rewrite nat_of_Z_eq; omega.\nQed.\n\nLemma store_zeros_outside:\n  forall m n m',\n  store_zeros m n = Some m' ->\n  skipn (nat_of_Z n) m' = skipn (nat_of_Z n) m.\nProof.\n  intros until n.\n  functional induction (store_zeros m n); intros.\n  +inv H. auto. \n  +replace n with (n-1+1)%Z by omega.\n   rewrite Z2Nat.inj_add; try omega.\n   repeat rewrite skipn_add.\n   rewrite IHo; auto.\n   repeat rewrite <-skipn_add.\n   repeat rewrite <-Z2Nat.inj_add; try omega.\n   apply store_zero_outside; auto.\n  +congruence.\nQed.\n\nLemma store_zeros_content:\n  forall m z m',\n  store_zeros m z = Some m' ->\n  (0 < z)%Z ->\n  loadbytes m' 0 z = Some (list_repeat (nat_of_Z z) (Byte Byte.zero)).\nProof.\n  intros until z.\n  functional induction (store_zeros m z); intros.\n  +omega.\n  +assert (n=1 \\/ 1 < n)%Z.\n    omega.\n   destruct H1.\n   -generalize e0. intros A.\n    apply store_length in A.\n    subst. simpl in *. unfold store in e0.\n    destruct (valid_access_dec _ _ _); inv e0.\n    destruct v. unfold loadbytes.\n    rewrite pred_dec_true; auto.\n    rewrite store_zeros_zero in H; auto. inv H.\n    rewrite encode_int_inj_bytes_zero.\n    unfold setN, replace_map. simpl.\n    destruct m; auto.\n    red. apply store_zeros_length in H; auto.\n    rewrite H, <-A; auto.\n   -generalize H e0. intros.\n    apply store_length in e1.\n    apply IHo in H; try omega.\n    rewrite <-firstn_skipn with (l:=m'0) (n:=nat_of_Z (n-1)) in H.\n    rewrite <-firstn_skipn with (l:=m'0) (n:=nat_of_Z (n-1)).\n    assert (A: (n-1 = Z_of_nat (length (firstn (nat_of_Z (n - 1)) m'0)))%Z).\n      rewrite firstn_length. erewrite store_zeros_length; eauto.\n      erewrite <-store_length; eauto.\n      apply store_valid_access in e0. destruct e0.\n      red in H3. simpl in *. rewrite min_l; try omega.\n      rewrite nat_of_Z_eq; try omega.\n      apply Nat2Z.inj_le. rewrite nat_of_Z_eq; try omega.\n    rewrite A in H at 3.   \n    apply loadbytes_first in H.\n    rewrite H.\n    erewrite store_zeros_outside; eauto.\n    unfold store in e0. destruct (valid_access_dec _ _ _); try congruence.\n    inversion e0. destruct v. red in H3. simpl in H3.\n    rewrite encode_int_inj_bytes_zero in *. \n    unfold setN. unfold replace_map in *.\n    rewrite skipn_length_app.\n    rewrite A at 2. rewrite nat_of_Z_of_nat.\n    repeat rewrite firstn_length. rewrite e1.\n    erewrite store_zeros_length; eauto.\n    rewrite minus_diag. simpl. \n    change (Byte Byte.zero :: skipn (nat_of_Z (n - 1) + 1) m) \n      with ((Byte Byte.zero :: nil) ++ skipn (nat_of_Z (n - 1) + 1) m).\n    change (Byte Byte.zero :: nil) with (list_repeat 1 (Byte Byte.zero)).\n    rewrite <-app_ass. rewrite <-list_repeat_app.\n    change 1%nat with (nat_of_Z 1).\n    rewrite <-Z2Nat.inj_add; try omega.\n    replace (n - 1 + 1)%Z with n in * by omega.\n    unfold loadbytes. rewrite pred_dec_true.\n    simpl. unfold getN, getn. simpl.\n    rewrite firstn_length_app1.\n    rewrite firstn_list_repeat; auto.\n    rewrite length_list_repeat; auto.\n    red. rewrite app_length. rewrite length_list_repeat.\n    cut (Z.to_nat n <= length m). intros.\n    rewrite skipn_length. rewrite min_l; auto.\n    replace (Z.to_nat n + (length m - Z.to_nat n)) with (length m); omega.\n    apply Nat2Z.inj_le. rewrite nat_of_Z_eq; try omega.\n    rewrite firstn_length. rewrite min_l; try omega.\n    apply Nat2Z.inj_le. rewrite nat_of_Z_eq; try omega.\n  +congruence.\nQed.\n\nLemma alloc_globals_app:\n  forall l1 l2 gc gc1 gc2,\n  alloc_globals gc l1 = Some gc1 ->\n  alloc_globals gc1 l2 = Some gc2 ->\n  alloc_globals gc (l1++l2) = Some gc2.\nProof.\n  induction l1; simpl; intros.\n  congruence.\n  destruct (alloc_global gc a) eqn:?; try congruence.\n  eapply IHl1; eauto.\nQed.\n\nLemma alloc_globals_notin_eq:\n  forall id l gc gc',\n  alloc_globals gc l = Some gc'-> \n  ~ In id (List.map (@fst ident (globvar type)) l) ->\n  gc' ! id =gc ! id.\nProof.\n  induction l; simpl; intros.\n  +inv H. auto.\n  +remember (alloc_global gc a).\n   destruct o; try congruence. \n   rewrite IHl with l0 gc'; eauto.\n   unfold alloc_global in Heqo. destruct a.\n   destruct g. destruct (store_zeros _ _) eqn:?; try congruence.\n   destruct (store_init_datas _ _ _) eqn:?; inv Heqo.\n   rewrite PTree.gso; auto.\nQed.\n\nLemma init_genvc_notin_none:\n  forall id l gc,\n  init_genvc l = Some gc ->\n  ~ In id (List.map (@fst ident (globvar type)) l) ->\n  gc ! id = None.\nProof.\n  unfold init_genvc. intros.\n  erewrite alloc_globals_notin_eq; eauto.\n  rewrite PTree.gempty; auto.\nQed.\n\nLemma alloc_globals_init_datas_types:\n  forall l gc gc',\n  alloc_globals gc l = Some gc'-> \n  (forall a, In a l -> init_data_types (gvar_init (snd a))).\nProof.\n  induction l; simpl; intros.\n  tauto.\n  destruct (alloc_global _ _) eqn:?; try congruence.\n  destruct H0; subst; eauto.  \n  destruct a0; simpl in *. destruct g.\n  destruct (store_zeros _ _); try congruence.\n  destruct (store_init_datas _ _ _) eqn:?; try congruence.\n  simpl. eapply store_init_datas_types; eauto.\nQed.\n\nInductive load_argv(ty: type)(m: mvl)(ofs: int): val -> Prop :=\n  | load_argv_value: forall chunk v,\n      access_mode ty = By_value chunk ->\n      loadbytes m (Int.unsigned ofs) (sizeof ty) = Some (encode_val chunk v) ->\n      load_argv ty m ofs v\n  | load_argv_copy: forall m1,\n      access_mode ty = By_copy \\/ access_mode ty = By_reference ->\n      loadbytes m (Int.unsigned ofs) (sizeof ty) = Some m1 ->\n      (alignof ty | Int.unsigned ofs) ->\n      load_argv ty m ofs (Vmvl m1).\n\nInductive load_mvl(ty: type)(m: mvl)(ofs: int): val -> Prop :=\n  | load_mvl_value: forall chunk v,\n      access_mode ty = By_value chunk ->\n      load chunk m (Int.unsigned ofs) = Some v ->\n      load_mvl ty m ofs v\n  | load_mvl_copy: forall m1,\n      access_mode ty = By_copy \\/ access_mode ty = By_reference ->\n      loadbytes m (Int.unsigned ofs) (sizeof ty) = Some m1 ->\n      (alignof ty | Int.unsigned ofs) ->\n      load_mvl ty m ofs (Vmvl m1).\n\nInductive vargs_match(m: mvl)(delta: Z): list (ident*type) -> list val -> Prop :=\n  | vargs_match_nil:\n      vargs_match m delta nil nil\n  | vargs_match_cons: forall id ty al v vl,\n      load_argv ty m (Int.repr (align delta (alignof ty))) v ->\n      vargs_match m (align delta (alignof ty) + sizeof ty) al vl ->\n      vargs_match m delta ((id,ty)::al) (v::vl).\n\nCoInductive vargs_matchss_rec(al: list (ident*type))(vass: Stream (list val)) (mass: Stream (list mvl)) : Prop :=\n    vargs_matchss_rec_ : forall m,\n      vargs_match m 0 al (Streams.hd vass) ->\n      Streams.hd mass = m :: nil ->\n      mvl_type true m (Tstruct xH (fieldlist_of al)) ->\n      vargs_matchss_rec al (Streams.tl vass) (Streams.tl mass) ->\n      vargs_matchss_rec al vass mass.\n\nCoInductive vargs_matchss_nil_rec(vass: Stream (list val)) (mass: Stream (list mvl)) : Prop :=\n    vargs_matchss_nil_rec_ :\n      Streams.hd mass = nil ->\n      Streams.hd vass = nil ->\n      vargs_matchss_nil_rec (Streams.tl vass) (Streams.tl mass) ->\n      vargs_matchss_nil_rec vass mass.\n\nInductive vargs_matchss(al: list (ident*type))(vass: Stream (list val)) (mass: Stream (list mvl)) : Prop :=\n  | vargs_matchss_cons :\n      0 < length al -> \n      vargs_matchss_rec al vass mass ->\n      vargs_matchss al vass mass\n  | vargs_matchss_nil:\n      al = nil ->\n      vargs_matchss_nil_rec vass mass ->\n      vargs_matchss al vass mass.\n\nInductive vrets_match(m: mvl)(delta: Z): list (ident*type) -> list val -> Prop :=\n  | vrets_match_nil:\n      vrets_match m delta nil nil\n  | vrets_match_cons: forall id ty al v vl,\n      load_mvl ty m (Int.repr (align delta (alignof ty))) v ->\n      vrets_match m (align delta (alignof ty) + sizeof ty) al vl ->\n      vrets_match m delta ((id,ty)::al) (v::vl).\n\nCoInductive vrets_matchss_rec(al: list (ident*type))(vrss: Stream (list val)) (mrss: Stream (list mvl)) : Prop :=\n    vrets_matchss_ : forall m, \n      vrets_match m 0 al (Streams.hd vrss) ->\n      Streams.hd mrss = m :: nil ->\n      vrets_matchss_rec al (Streams.tl vrss) (Streams.tl mrss) ->\n      vrets_matchss_rec al vrss mrss.\n\nInductive vrets_matchss(al: list (ident*type))(vrss: Stream (list val)) (mrss: Stream (list mvl)) : Prop :=\n  | vrets_matchss_cons :\n      0 < length al -> \n      vrets_matchss_rec al vrss mrss ->\n      vrets_matchss al vrss mrss\n  | vrets_matchss_nil:\n      al = nil ->\n      vrets_matchss al vrss mrss.\n\nVariable S: Type. \n\nVariable p: general_program (general_node S).\nVariable gc: locenv.\n\n\nVariable alloc_node: general_program (general_node S) -> env -> ident*general_node S -> Prop.\n\nInductive initial_state(main: ident*general_node S): env -> Prop := \n  | initial_state_node: forall e, \n      init_genvc (const_block p) = Some gc ->\n      find_funct (node_block p) p.(node_main) = Some main -> \n      alloc_node p e main ->\n      initial_state main e.\n\nDefinition arg_prop(a: ident*type): Prop :=\n  (0 < sizeof (snd a) <= Int.max_signed)%Z\n    /\\ is_arystr (snd a) = true.\n\nDefinition args_prop(l: list (ident*type)): Prop :=\n  Forall arg_prop l /\\ length l <= 1.\n\nInductive initial_state1(main: ident*general_node S): env -> Prop := \n  | initial_state1_node: forall e,\n      init_genvc (const_block p) = Some gc ->\n      find_funct (node_block p) p.(node_main) = Some main -> \n      args_prop (nd_args (snd main)) ->\n      alloc_node p e main ->\n      initial_state1 main e.\n\nVariable eval_node: general_program (general_node S) -> locenv -> env -> env -> ident*general_node S -> list val -> list val -> Prop.\n\nInductive exec_prog(main: ident*general_node S)(e: env)(n maxn: nat)(vass vrss: Stream (list val)) : Prop :=\n  | exec_prog_term: forall mrss,\n      n > maxn ->\n      vrets_matchss (nd_rets (snd main)) vrss mrss ->\n      exec_prog main e n maxn vass vrss\n  | exec_prog_cons: forall e',  \n      n <= maxn ->\n      eval_node p gc e e' main (hd vass) (hd vrss) ->\n      exec_prog main e' (n+1) maxn (tl vass) (tl vrss) ->\n      exec_prog main e n maxn vass vrss.\n\nInductive exec_prog1(main: ident*general_node S)(e: env)(n maxn: nat)(mass: Stream (list mvl))(vrss: Stream (list val)) : Prop :=\n  | exec_prog1_term: forall mrss,\n      n > maxn ->\n      vrets_matchss (nd_rets (snd main)) vrss mrss ->\n      exec_prog1 main e n maxn mass vrss\n  | exec_prog1_cons: forall e',\n      n <= maxn ->\n      has_types (List.map Vmvl (Streams.hd mass)) (List.map snd (nd_args (snd main))) ->\n      eval_node p gc e e' main (List.map Vmvl (Streams.hd mass)) (hd vrss) ->\n      exec_prog1 main e' (n+1) maxn (tl mass) (tl vrss) ->\n      exec_prog1 main e n maxn mass vrss.\n\nEnd GLOBAL_ENV.\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/Lenv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.25054582751431925}}
{"text": "Require Import SpecCert.x86.Architecture.MemoryController.MemoryController_rec.\n\nDefinition smramc_is_locked\n           (mc :MemoryController) :=\n  smramc_is_ro (smramc mc).\n\nDefinition smramc_is_unlocked\n           (mc :MemoryController) :=\n  smramc_is_rw (smramc mc).\n\nDefinition can_access_smram\n           (mc     :MemoryController)\n           (smiact :bool) :=\n  smiact = true\n  \\/ d_open (smramc mc) = true.\n", "meta": {"author": "lthms", "repo": "speccert", "sha": "8c1edfb173548af0e9ca3c4e24d43726401fdb71", "save_path": "github-repos/coq/lthms-speccert", "path": "github-repos/coq/lthms-speccert/speccert-8c1edfb173548af0e9ca3c4e24d43726401fdb71/src/x86/Architecture/MemoryController/MemoryController_prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.25040439145971954}}
{"text": "From Coq Require Import Lists.List.\nFrom Coq Require Import Strings.Ascii.\nFrom Coq Require Import Nat Psatz.\nImport ListNotations.\n\nOpen Scope char_scope.\n\nDefinition input_stacks : list (list ascii) :=\n  [\n    [\"J\";\"F\";\"C\";\"N\";\"D\";\"B\";\"W\"];\n    [\"T\";\"S\";\"L\";\"Q\";\"V\";\"Z\";\"P\"];\n    [\"T\";\"J\";\"G\";\"B\";\"Z\";\"P\"];\n    [\"C\";\"H\";\"B\";\"Z\";\"J\";\"L\";\"T\";\"D\"];\n    [\"S\";\"J\";\"B\";\"V\";\"G\"];\n    [\"Q\";\"S\";\"P\"];\n    [\"N\";\"P\";\"M\";\"L\";\"F\";\"D\";\"V\";\"B\"];\n    [\"R\";\"L\";\"D\";\"B\";\"F\";\"M\";\"S\";\"P\"];\n    [\"R\";\"T\";\"D\";\"V\"]\n  ]\n.\n\nDefinition test_stacks : list (list ascii) :=\n  [\n    [\"N\";\"Z\"];\n    [\"D\";\"C\";\"M\"];\n    [\"P\"]\n  ]\n.\n\nDefinition input_moves : list (nat * nat * nat) := [\n  (4,9,6);\n  (7,2,5);\n  (3,5,2);\n  (2,2,1);\n  (2,8,4);\n  (1,6,9);\n  (1,9,4);\n  (7,1,2);\n  (5,2,3);\n  (5,7,4);\n  (5,6,3);\n  (1,7,6);\n  (2,6,9);\n  (3,2,4);\n  (4,5,6);\n  (2,7,3);\n  (2,9,3);\n  (1,5,2);\n  (11,4,3);\n  (1,2,9);\n  (1,9,3);\n  (2,1,6);\n  (5,8,5);\n  (7,5,4);\n  (2,5,6);\n  (6,6,4);\n  (17,3,4);\n  (1,8,3);\n  (11,4,7);\n  (1,6,4);\n  (3,4,2);\n  (2,2,6);\n  (8,3,1);\n  (8,3,9);\n  (3,9,6);\n  (3,1,3);\n  (11,7,5);\n  (1,6,4);\n  (4,9,6);\n  (3,1,4);\n  (1,2,3);\n  (1,6,9);\n  (24,4,9);\n  (2,6,5);\n  (1,1,2);\n  (1,1,3);\n  (12,9,6);\n  (5,4,2);\n  (4,2,3);\n  (5,6,3);\n  (13,6,7);\n  (1,5,6);\n  (9,5,3);\n  (4,7,5);\n  (1,6,1);\n  (3,5,1);\n  (14,9,4);\n  (2,7,9);\n  (13,4,9);\n  (1,4,7);\n  (4,7,9);\n  (3,5,1);\n  (8,3,9);\n  (4,1,4);\n  (8,3,7);\n  (3,7,6);\n  (4,4,2);\n  (3,1,9);\n  (6,2,6);\n  (3,3,1);\n  (7,9,7);\n  (2,6,5);\n  (1,5,3);\n  (3,7,5);\n  (5,7,4);\n  (2,1,4);\n  (5,5,9);\n  (6,4,1);\n  (6,7,8);\n  (22,9,3);\n  (7,1,8);\n  (4,9,6);\n  (1,4,5);\n  (8,6,4);\n  (7,8,1);\n  (1,6,4);\n  (1,9,4);\n  (1,1,2);\n  (1,2,5);\n  (1,9,8);\n  (11,3,7);\n  (1,6,2);\n  (2,1,5);\n  (1,8,2);\n  (1,7,8);\n  (4,5,7);\n  (1,6,9);\n  (6,3,1);\n  (6,3,1);\n  (15,7,5);\n  (1,3,1);\n  (1,3,6);\n  (1,6,8);\n  (14,5,1);\n  (16,1,3);\n  (2,8,9);\n  (1,7,4);\n  (3,9,8);\n  (3,8,7);\n  (2,3,5);\n  (1,7,1);\n  (6,8,5);\n  (2,2,9);\n  (1,7,2);\n  (2,9,2);\n  (5,4,7);\n  (3,2,7);\n  (14,1,5);\n  (2,4,7);\n  (8,7,6);\n  (1,1,5);\n  (1,7,4);\n  (1,7,5);\n  (1,1,8);\n  (12,3,4);\n  (1,8,7);\n  (3,4,1);\n  (1,6,2);\n  (8,5,2);\n  (1,7,6);\n  (1,1,7);\n  (6,6,2);\n  (1,1,2);\n  (14,5,7);\n  (1,6,4);\n  (4,4,7);\n  (1,1,6);\n  (1,5,6);\n  (2,3,1);\n  (14,7,5);\n  (10,4,7);\n  (1,1,9);\n  (1,5,9);\n  (11,5,1);\n  (6,7,6);\n  (1,4,6);\n  (1,3,7);\n  (2,1,5);\n  (13,2,1);\n  (10,6,7);\n  (4,5,2);\n  (1,9,1);\n  (1,3,6);\n  (2,5,2);\n  (1,9,3);\n  (1,3,1);\n  (21,7,5);\n  (1,6,4);\n  (4,5,1);\n  (1,4,1);\n  (6,2,3);\n  (1,3,6);\n  (1,3,8);\n  (1,8,7);\n  (1,7,3);\n  (9,5,3);\n  (24,1,4);\n  (1,3,7);\n  (11,3,8);\n  (1,7,3);\n  (1,2,4);\n  (2,2,1);\n  (2,3,5);\n  (1,6,5);\n  (10,4,6);\n  (2,6,4);\n  (5,1,2);\n  (1,6,7);\n  (8,8,6);\n  (4,2,7);\n  (8,6,7);\n  (1,2,8);\n  (1,8,3);\n  (1,7,4);\n  (3,4,1);\n  (2,6,7);\n  (4,1,9);\n  (3,6,7);\n  (10,7,4);\n  (2,3,9);\n  (2,6,9);\n  (2,1,8);\n  (2,9,5);\n  (4,5,6);\n  (3,8,1);\n  (4,4,8);\n  (5,8,4);\n  (1,8,2);\n  (5,5,9);\n  (1,6,1);\n  (2,1,7);\n  (22,4,8);\n  (4,8,7);\n  (2,6,7);\n  (1,2,6);\n  (16,8,9);\n  (3,7,4);\n  (1,5,9);\n  (2,6,7);\n  (1,8,2);\n  (1,2,3);\n  (24,9,3);\n  (1,1,7);\n  (3,5,1);\n  (4,4,6);\n  (15,3,6);\n  (18,6,2);\n  (3,3,2);\n  (4,1,6);\n  (4,7,3);\n  (1,3,9);\n  (4,2,1);\n  (1,8,7);\n  (3,9,6);\n  (1,9,3);\n  (4,7,3);\n  (2,4,2);\n  (1,1,2);\n  (7,3,5);\n  (8,6,1);\n  (1,9,2);\n  (3,7,5);\n  (1,4,8);\n  (3,1,7);\n  (5,7,6);\n  (3,5,2);\n  (3,7,3);\n  (5,5,9);\n  (5,3,6);\n  (1,8,3);\n  (5,9,7);\n  (7,2,4);\n  (11,2,7);\n  (7,1,6);\n  (1,1,9);\n  (5,3,6);\n  (5,2,1);\n  (1,3,9);\n  (1,3,7);\n  (6,6,2);\n  (10,6,7);\n  (5,6,7);\n  (28,7,8);\n  (2,9,1);\n  (1,6,3);\n  (4,7,5);\n  (1,3,6);\n  (7,2,7);\n  (6,7,3);\n  (1,5,9);\n  (1,6,2);\n  (1,7,3);\n  (1,9,1);\n  (4,5,2);\n  (5,3,5);\n  (2,2,8);\n  (4,4,7);\n  (1,4,7);\n  (2,3,6);\n  (5,7,1);\n  (2,5,8);\n  (2,5,8);\n  (2,5,3);\n  (2,3,1);\n  (2,6,7);\n  (31,8,3);\n  (2,8,5);\n  (2,7,4);\n  (7,1,4);\n  (2,5,1);\n  (3,2,8);\n  (2,4,6);\n  (3,1,2);\n  (6,4,8);\n  (1,1,8);\n  (1,6,5);\n  (11,8,9);\n  (1,6,8);\n  (1,4,1);\n  (1,8,7);\n  (1,5,8);\n  (3,2,1);\n  (2,4,3);\n  (1,8,1);\n  (7,3,6);\n  (12,3,2);\n  (1,7,9);\n  (4,6,1);\n  (1,6,3);\n  (12,9,3);\n  (1,6,4);\n  (1,1,7);\n  (1,4,1);\n  (1,7,2);\n  (1,6,5);\n  (1,5,6);\n  (5,3,1);\n  (1,6,4);\n  (7,2,1);\n  (3,2,6);\n  (1,4,5);\n  (3,3,2);\n  (4,2,8);\n  (1,6,4);\n  (1,4,9);\n  (1,5,1);\n  (11,1,5);\n  (10,1,8);\n  (2,6,4);\n  (1,2,9);\n  (1,2,4);\n  (18,3,5);\n  (4,1,4);\n  (3,1,2);\n  (14,8,5);\n  (2,2,6);\n  (1,3,2);\n  (2,2,7);\n  (3,4,1);\n  (2,4,3);\n  (2,3,4);\n  (2,6,9);\n  (1,7,1);\n  (3,1,4);\n  (4,9,7);\n  (31,5,2);\n  (25,2,4);\n  (13,4,2);\n  (10,2,3);\n  (2,5,7);\n  (5,2,9);\n  (7,5,7);\n  (5,7,4);\n  (1,5,8);\n  (2,7,3);\n  (11,4,8);\n  (1,7,3);\n  (1,1,4);\n  (2,5,3);\n  (3,2,9);\n  (8,9,6);\n  (10,8,2);\n  (5,3,2);\n  (1,7,3);\n  (3,7,3);\n  (15,2,1);\n  (11,1,3);\n  (1,8,2);\n  (8,6,5);\n  (1,2,6);\n  (1,6,1);\n  (12,3,7);\n  (1,2,9);\n  (2,4,1);\n  (3,1,8);\n  (1,8,7);\n  (3,3,4);\n  (1,4,7);\n  (15,7,9);\n  (1,7,5);\n  (4,1,8);\n  (6,8,6);\n  (1,6,2);\n  (5,5,1);\n  (2,6,8);\n  (1,2,7);\n  (1,8,2);\n  (1,7,1);\n  (1,5,8);\n  (6,3,1);\n  (4,3,8);\n  (7,8,5);\n  (1,2,4);\n  (2,4,2);\n  (3,6,4);\n  (5,9,3);\n  (4,1,4);\n  (10,5,9);\n  (8,1,7);\n  (1,2,1);\n  (1,1,9);\n  (20,9,2);\n  (12,2,3);\n  (17,4,3);\n  (6,7,2);\n  (5,3,8);\n  (20,3,5);\n  (2,9,4);\n  (3,3,1);\n  (1,7,1);\n  (6,3,6);\n  (4,2,3);\n  (4,5,3);\n  (1,1,9);\n  (6,6,1);\n  (3,8,4);\n  (1,9,8);\n  (2,2,1);\n  (3,3,2);\n  (1,3,6);\n  (1,7,4);\n  (3,3,6);\n  (6,1,5);\n  (9,2,4);\n  (3,2,5);\n  (2,6,5);\n  (16,4,8);\n  (18,8,6);\n  (1,4,5);\n  (2,6,7);\n  (4,1,7);\n  (22,5,6);\n  (1,4,9);\n  (4,7,6);\n  (11,6,5);\n  (9,5,2);\n  (2,2,3);\n  (2,7,2);\n  (1,1,7);\n  (9,6,2);\n  (1,5,1);\n  (1,8,9);\n  (18,6,8);\n  (1,7,4);\n  (4,5,1);\n  (2,5,2);\n  (2,2,5);\n  (1,9,5);\n  (1,5,9);\n  (1,9,1);\n  (1,9,2);\n  (1,4,8);\n  (4,1,4);\n  (2,6,5);\n  (1,1,9);\n  (3,6,7);\n  (1,6,9);\n  (1,9,8);\n  (2,5,9);\n  (3,3,5);\n  (7,2,3);\n  (1,1,3);\n  (2,5,9);\n  (1,5,7);\n  (10,8,3);\n  (10,8,9);\n  (3,4,3);\n  (9,2,1);\n  (4,9,6);\n  (5,1,9);\n  (2,5,9);\n  (1,6,4);\n  (4,7,2);\n  (7,2,9);\n  (3,6,8);\n  (1,1,3);\n  (2,8,5);\n  (1,8,1);\n  (18,3,6);\n  (15,9,2);\n  (8,9,1);\n  (2,9,2);\n  (2,4,9);\n  (2,9,7);\n  (12,6,3);\n  (7,1,7);\n  (12,2,5);\n  (7,3,2);\n  (4,3,4);\n  (2,7,6);\n  (7,7,8);\n  (1,4,2);\n  (4,1,8);\n  (5,3,1);\n  (9,8,3);\n  (1,8,7);\n  (2,1,2);\n  (4,6,7);\n  (11,2,5);\n  (2,4,6);\n  (1,8,2);\n  (7,3,2);\n  (1,2,4);\n  (4,6,1);\n  (7,5,8);\n  (2,3,1);\n  (7,2,3);\n  (6,5,1);\n  (1,4,2);\n  (8,1,6);\n  (3,2,9)\n].\n\nDefinition test_moves : list (nat * nat * nat) := [\n  (1,2,1);\n  (3,1,3);\n  (2,2,1);\n  (1,1,2)\n].\n\nFixpoint edit {A} (idx : nat) (f : A -> A) (l : list A) :=\n  match idx, l with\n  | _,nil => nil\n  | 0, (x :: r) => f x :: r\n  | S i, (x :: r) => x :: edit i f r\n  end.\n\nFixpoint drop {A} (cnt : nat) (l : list A) :=\n  match cnt,l with\n  | 0,_ => l\n  | _,nil => []\n  | S i, (x :: r) => drop i r\n  end.\n\nDefinition step1 (mov : nat * nat * nat) (state : list (list ascii)) :=\n  let (movfst,to) := mov in\n  let (cnt,from) := movfst in\n  let movd := firstn cnt (nth (from-1) state []) in\n  let rest := edit (from-1) (drop cnt) state in\n  edit (to-1) (fun x => rev movd ++ x) rest.\n\nDefinition step2 (mov : nat * nat * nat) (state : list (list ascii)) :=\n  let (movfst,to) := mov in\n  let (cnt,from) := movfst in\n  let movd := firstn cnt (nth (from-1) state []) in\n  let rest := edit (from-1) (drop cnt) state in\n  edit (to-1) (fun x => movd ++ x) rest.\n\nDefinition flip {A} {B} {C} (f : A -> B -> C) (b : B) (a : A) : C :=\n  f a b.\n\nDefinition impl_1 (stacks : list (list ascii)) (moves : list (nat * nat * nat)) := map (hd \"0\") (fold_left (flip step1) moves stacks).\n\nDefinition impl_2 (stacks : list (list ascii)) (moves : list (nat * nat * nat)) := map (hd \"0\") (fold_left (flip step2) moves stacks).\n\nExample test_works1 : impl_1 test_stacks test_moves = [\"C\";\"M\";\"Z\"].\nProof.\n  vm_compute. reflexivity.\nQed.\n\nExample test_works2 : impl_2 test_stacks test_moves = [\"M\";\"C\";\"D\"].\nProof.\n  vm_compute. reflexivity.\nQed.\n\nCompute (impl_1 input_stacks input_moves).\nCompute (impl_2 input_stacks input_moves).\n\nClose Scope char_scope.\n\nFixpoint lsum (l : list nat) : nat :=\n  match l with\n  | nil => 0\n  | x :: r => x + lsum r\n  end.\n\nLemma sum_0_all_0 (l : list nat) : lsum l = 0 <-> forall n, In n l -> n = 0.\nProof.\n  split.\n  - intros. induction n.\n  -- auto.\n  -- exfalso. induction l.\n  --- inversion H0.\n  --- simpl in *. apply Plus.plus_is_O in H. destruct H. destruct H0.\n  ---- subst. inversion H0.\n  ---- apply IHl;auto.\n  - intros. induction l.\n  -- reflexivity.\n  -- simpl. apply PeanoNat.Nat.eq_add_0. split.\n  --- apply H. left. auto.\n  --- apply IHl. intros. apply H. right. auto.\nQed.\n\nLemma edit_nil {A} (idx : nat) (f : A -> A) : edit idx f [] = [].\nProof.\n  destruct idx;auto.\nQed.\n\nLemma lsum_map {A} (f : A -> nat) (a : A) (l : list A) : lsum (map f (a :: l)) = f a + lsum (map f l).\nProof.\n  reflexivity.\nQed.\n\nLemma double_edit {A} (f1 f2 : A -> A) (i : nat) (l : list A) : edit i f2 (edit i f1 l) = edit i (fun x => f2 (f1 x)) l.\nProof.\n  generalize dependent i.\n  induction l.\n  - destruct i; reflexivity.\n  - destruct i; auto. simpl. rewrite (IHl i). reflexivity.\nQed.\n\nLemma lsum_mod_inv (l : list nat) (i1 i2 d : nat) : length l > i1 /\\ length l > i2 /\\ nth i1 l 0 >= d -> lsum l = lsum (edit i2 (fun n => n + d) (edit i1 (fun n => n - d) l)).\nProof.\n  intro H. destruct H as [Hin1 [Hin2 Hge]].\n  destruct (i1 <=? i2) eqn:Hfstle.\n  - apply PeanoNat.Nat.leb_le in Hfstle. destruct (i1 =? i2) eqn:Hfsteq.\n  -- apply PeanoNat.Nat.eqb_eq in Hfsteq. clear Hfstle. subst. rewrite double_edit. generalize dependent i2. induction l.\n  --- simpl. destruct i2; auto.\n  --- simpl. destruct i2; auto.\n  ---- simpl. intros. rewrite PeanoNat.Nat.sub_add; auto.\n  ---- simpl. intros. rewrite (IHl i2);auto; lia.\n  -- rewrite PeanoNat.Nat.eqb_neq in Hfsteq. assert (i1 < i2). { lia. } clear Hfstle. clear Hfsteq. generalize dependent i2. induction i1.\n  --- intros. destruct l.\n  ---- simpl. rewrite edit_nil. reflexivity.\n  ---- simpl. destruct i2. { lia. } clear H. simpl. generalize dependent i2. induction l.\n  ----- intros. simpl in Hin2. lia.\n  ----- intros. simpl in *. clear Hin1. destruct i2.\n  ------ simpl. lia.\n  ------ simpl. assert (S (length l) > 0). { lia. }\n         assert (S (length l) > S i2). { lia. }\n         pose (IHl H Hge i2 H0). lia.\n  --- \nQed.\n\nTheorem box_length_const (mov : nat * nat * nat) (state : list (list ascii)) : lsum (map (fun l => length l) state) = lsum (map (fun l => length l) (step1 mov state)).\nProof.\n  destruct mov as [[cnt from] to].\nAdmitted.\n", "meta": {"author": "MarcusVoelker", "repo": "AoC2022", "sha": "33f67bc9a0df5354bf111c3247f87375ee6399e3", "save_path": "github-repos/coq/MarcusVoelker-AoC2022", "path": "github-repos/coq/MarcusVoelker-AoC2022/AoC2022-33f67bc9a0df5354bf111c3247f87375ee6399e3/Day5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2504043853801608}}
{"text": "From iris.proofmode Require Import proofmode.\nFrom iris.algebra Require Import auth list.\nFrom iris.program_logic Require Import adequacy.\nFrom iris_examples.logrel.F_mu_ref_conc.binary.examples Require Export lock.\nFrom iris_examples.logrel.F_mu_ref_conc.binary Require Import soundness.\nFrom iris.prelude Require Import options.\n\nDefinition CG_increment (x : expr) : expr :=\n  Lam (Store x.[ren (+ 1)] (BinOp Add (#n 1) (Load x.[ren (+ 1)]))).\n\nDefinition CG_locked_increment (x l : expr) : expr :=\n  with_lock (CG_increment x) l.\nDefinition CG_locked_incrementV (x l : expr) : val :=\n  with_lockV (CG_increment x) l.\n\nDefinition counter_read (x : expr) : expr := Lam (Load x.[ren (+1)]).\nDefinition counter_readV (x : expr) : val := LamV (Load x.[ren (+1)]).\n\nDefinition CG_counter_body (x l : expr) : expr :=\n  Pair (CG_locked_increment x l) (counter_read x).\nDefinition CG_counter : expr :=\n  LetIn newlock (LetIn (Alloc (#n 0)) (CG_counter_body (Var 0) (Var 1))).\n\nDefinition FG_increment (x : expr) : expr :=\n  Rec (LetIn\n         (Load x.[ren (+2)]) (* read the counter *)\n         (* try increment *)\n         (If (CAS x.[ren (+3)] (Var 0) (BinOp Add (#n 1) (Var 0)))\n             Unit (* increment succeeds we return unit *)\n             (App (Var 1) (Var 2)) (* increment fails, we try again *))).\nDefinition FG_counter_body (x : expr) : expr :=\n  Pair (FG_increment x) (counter_read x).\nDefinition FG_counter : expr :=\n  LetIn (Alloc (#n 0)) (FG_counter_body (Var 0)).\n\nSection CG_Counter.\n  Context `{heapIG Σ, cfgSG Σ}.\n\n  Notation D := (persistent_predO (val * val) (iPropI Σ)).\n  Implicit Types Δ : listO D.\n\n  (* Coarse-grained increment *)\n  Lemma CG_increment_type x Γ :\n    typed Γ x (Tref TNat) →\n    typed Γ (CG_increment x) (TArrow TUnit TUnit).\n  Proof.\n    intros H1. repeat econstructor.\n    - eapply (context_weakening [_]); eauto.\n    - eapply (context_weakening [_]); eauto.\n  Qed.\n\n  Lemma CG_increment_closed (x : expr) :\n    (∀ f, x.[f] = x) → ∀ f, (CG_increment x).[f] = CG_increment x.\n  Proof. intros Hx f. unfold CG_increment. asimpl. rewrite ?Hx; trivial. Qed.\n\n  Hint Rewrite CG_increment_closed : autosubst.\n\n  Lemma CG_increment_subst (x : expr) f :\n    (CG_increment x).[f] = CG_increment x.[f].\n  Proof. unfold CG_increment; asimpl; trivial. Qed.\n\n  Hint Rewrite CG_increment_subst : autosubst.\n\n  Lemma steps_CG_increment E j K x n:\n    nclose specN ⊆ E →\n    spec_ctx ∗ x ↦ₛ (#nv n) ∗ j ⤇ fill K (App (CG_increment (Loc x)) Unit)\n      ⊢ |={E}=> j ⤇ fill K (Unit) ∗ x ↦ₛ (#nv (S n)).\n  Proof.\n    iIntros (HNE) \"[#Hspec [Hx Hj]]\". unfold CG_increment.\n    iMod (do_step_pure with \"[$Hj]\") as \"Hj\"; eauto.\n    iMod (step_load _ j ((BinOpRCtx _ (#nv _) :: StoreRCtx (LocV _) :: K))\n                    _ _ _ with \"[Hj Hx]\") as \"[Hj Hx]\"; eauto.\n    { iFrame \"Hspec Hj\"; trivial. }\n    simpl.\n    iMod (do_step_pure _ _ ((StoreRCtx (LocV _)) :: K)  with \"[$Hj]\") as \"Hj\";\n      eauto.\n    simpl.\n    iMod (step_store _ j K with \"[$Hj $Hx]\") as \"[Hj Hx]\"; eauto.\n    iModIntro; iFrame.\n  Qed.\n\n  Global Opaque CG_increment.\n\n  Lemma CG_locked_increment_to_val x l :\n    to_val (CG_locked_increment x l) = Some (CG_locked_incrementV x l).\n  Proof. by rewrite with_lock_to_val. Qed.\n\n  Lemma CG_locked_increment_of_val x l :\n    of_val (CG_locked_incrementV x l) = CG_locked_increment x l.\n  Proof. by rewrite with_lock_of_val. Qed.\n\n  Global Opaque CG_locked_incrementV.\n\n  Lemma CG_locked_increment_type x l Γ :\n    typed Γ x (Tref TNat) →\n    typed Γ l LockType →\n    typed Γ (CG_locked_increment x l) (TArrow TUnit TUnit).\n  Proof.\n    intros H1 H2. repeat econstructor.\n    eapply with_lock_type; auto using CG_increment_type.\n  Qed.\n\n  Lemma CG_locked_increment_subst (x l : expr) f :\n  (CG_locked_increment x l).[f] = CG_locked_increment x.[f] l.[f].\n  Proof.\n    unfold CG_locked_increment. simpl.\n    rewrite with_lock_subst CG_increment_subst. asimpl; trivial.\n  Qed.\n\n  Hint Rewrite CG_locked_increment_subst : autosubst.\n\n  Lemma steps_CG_locked_increment E j K x n l :\n    nclose specN ⊆ E →\n    spec_ctx ∗ x ↦ₛ (#nv n) ∗ l ↦ₛ (#♭v false)\n      ∗ j ⤇ fill K (App (CG_locked_increment (Loc x) (Loc l)) Unit)\n    ={E}=∗ j ⤇ fill K Unit ∗ x ↦ₛ (#nv S n) ∗ l ↦ₛ (#♭v false).\n  Proof.\n    iIntros (HNE) \"[#Hspec [Hx [Hl Hj]]]\".\n    iMod (steps_with_lock\n            _ j K _ _ _ _ UnitV UnitV with \"[$Hj Hx $Hl]\") as \"Hj\"; eauto.\n    - iIntros (K') \"[#Hspec Hxj]\".\n      iApply steps_CG_increment; by try iFrame.\n    - by iFrame.\n  Qed.\n\n  Global Opaque CG_locked_increment.\n\n  Lemma counter_read_to_val x : to_val (counter_read x) = Some (counter_readV x).\n  Proof. trivial. Qed.\n\n  Lemma counter_read_of_val x : of_val (counter_readV x) = counter_read x.\n  Proof. trivial. Qed.\n\n  Global Opaque counter_readV.\n\n  Lemma counter_read_type x Γ :\n    typed Γ x (Tref TNat) → typed Γ (counter_read x) (TArrow TUnit TNat).\n  Proof.\n    intros H1. repeat econstructor.\n    eapply (context_weakening [_]); trivial.\n  Qed.\n\n  Lemma counter_read_closed (x : expr) :\n    (∀ f, x.[f] = x) → ∀ f, (counter_read x).[f] = counter_read x.\n  Proof. intros H1 f. asimpl. unfold counter_read. by rewrite ?H1. Qed.\n\n  Hint Rewrite counter_read_closed : autosubst.\n\n  Lemma counter_read_subst (x: expr) f :\n    (counter_read x).[f] = counter_read x.[f].\n  Proof. unfold counter_read. by asimpl. Qed.\n\n  Hint Rewrite counter_read_subst : autosubst.\n\n  Lemma steps_counter_read E j K x n :\n    nclose specN ⊆ E →\n    spec_ctx ∗ x ↦ₛ (#nv n)\n               ∗ j ⤇ fill K (App (counter_read (Loc x)) Unit)\n    ={E}=∗ j ⤇ fill K (#n n) ∗ x ↦ₛ (#nv n).\n  Proof.\n    intros HNE. iIntros \"[#Hspec [Hx Hj]]\". unfold counter_read.\n    iMod (do_step_pure with \"[$Hj]\") as \"Hj\"; eauto.\n    iAsimpl.\n    iMod (step_load _ j K with \"[$Hj Hx]\") as \"[Hj Hx]\"; eauto.\n    by iFrame.\n  Qed.\n\n  Local Opaque counter_read.\n\n  Lemma CG_counter_body_type x l Γ :\n    typed Γ x (Tref TNat) →\n    typed Γ l LockType →\n    typed Γ (CG_counter_body x l)\n            (TProd (TArrow TUnit TUnit) (TArrow TUnit TNat)).\n  Proof.\n    intros H1 H2; repeat econstructor;\n      eauto using CG_locked_increment_type, counter_read_type.\n  Qed.\n\n  Lemma CG_counter_body_subst (x l : expr) f :\n    (CG_counter_body x l).[f] = CG_counter_body x.[f] l.[f].\n  Proof. by asimpl. Qed.\n\n  Hint Rewrite CG_counter_body_subst : autosubst.\n\n  Lemma CG_counter_type Γ :\n    typed Γ CG_counter (TProd (TArrow TUnit TUnit) (TArrow TUnit TNat)).\n  Proof.\n    econstructor; eauto using newlock_type.\n    econstructor; first eauto using typed.\n    apply CG_counter_body_type; eauto using typed.\n  Qed.\n\n  Lemma CG_counter_closed f : CG_counter.[f] = CG_counter.\n  Proof. by asimpl. Qed.\n\n  Hint Rewrite CG_counter_closed : autosubst.\n\n  (* Fine-grained increment *)\n  Lemma FG_increment_type x Γ :\n    typed Γ x (Tref TNat) →\n    typed Γ (FG_increment x) (TArrow TUnit TUnit).\n  Proof.\n    intros Hx. do 3 econstructor; eauto using typed.\n    - eapply (context_weakening [_; _]); eauto.\n    - econstructor; [| |repeat econstructor |].\n      + constructor.\n      + eapply (context_weakening [_; _; _]); eauto.\n      + repeat constructor.\n  Qed.\n\n  Lemma FG_increment_subst (x : expr) f :\n    (FG_increment x).[f] = FG_increment x.[f].\n  Proof. rewrite /FG_increment. by asimpl. Qed.\n\n  Hint Rewrite FG_increment_subst : autosubst.\n\n  Lemma FG_counter_body_type x Γ :\n    typed Γ x (Tref TNat) →\n    typed Γ (FG_counter_body x)\n            (TProd (TArrow TUnit TUnit) (TArrow TUnit TNat)).\n  Proof.\n    intros H1; econstructor.\n    - apply FG_increment_type; trivial.\n    - apply counter_read_type; trivial.\n  Qed.\n\n  Lemma FG_counter_body_subst (x : expr) f :\n    (FG_counter_body x).[f] = FG_counter_body x.[f].\n  Proof. rewrite /FG_counter_body /FG_increment. by asimpl. Qed.\n\n  Hint Rewrite FG_counter_body_subst : autosubst.\n\n  Lemma FG_counter_type Γ :\n    Γ ⊢ₜ FG_counter : (TProd (TArrow TUnit TUnit) (TArrow TUnit TNat)).\n  Proof.\n    econstructor; eauto using newlock_type, typed.\n    apply FG_counter_body_type; by constructor.\n  Qed.\n\n  Lemma FG_counter_closed f : FG_counter.[f] = FG_counter.\n  Proof. by asimpl. Qed.\n\n  Hint Rewrite FG_counter_closed : autosubst.\n\n  Definition counterN : namespace := nroot .@ \"counter\".\n\n  Lemma FG_CG_counter_refinement :\n    ⊢ [] ⊨ FG_counter ≤log≤ CG_counter : TProd (TArrow TUnit TUnit) (TArrow TUnit TNat).\n  Proof.\n    iIntros (Δ [|??]) \"!# #(Hspec & HΓ)\"; iIntros (j K) \"Hj\"; last first.\n    { iDestruct (interp_env_length with \"HΓ\") as %[=]. }\n    iClear \"HΓ\". cbn -[FG_counter CG_counter].\n    rewrite ?empty_env_subst /CG_counter /FG_counter.\n    iApply fupd_wp.\n    iMod (steps_newlock _ j (LetInCtx _ :: K) with \"[$Hj]\")\n      as (l) \"[Hj Hl]\"; eauto.\n    simpl.\n    iMod (do_step_pure with \"[$Hj]\") as \"Hj\"; eauto.\n    iAsimpl.\n    iMod (step_alloc _ j (LetInCtx _ :: K) with \"[$Hj]\")\n      as (cnt') \"[Hj Hcnt']\"; eauto.\n    simpl.\n    iMod (do_step_pure with \"[$Hj]\") as \"Hj\"; eauto.\n    iAsimpl.\n    iApply (wp_bind (fill [LetInCtx _])).\n    iApply wp_wand_l. iSplitR; [iModIntro; iIntros (v) \"Hv\"; iExact \"Hv\"|].\n    iApply (wp_alloc); trivial; iFrame \"#\"; iModIntro; iNext; iIntros (cnt) \"Hcnt /=\".\n    (* establishing the invariant *)\n    iAssert ((∃ n, l ↦ₛ (#♭v false) ∗ cnt ↦ᵢ (#nv n) ∗ cnt' ↦ₛ (#nv n) )%I)\n      with \"[Hl Hcnt Hcnt']\" as \"Hinv\".\n    { iExists _. by iFrame. }\n    iApply fupd_wp.\n    iMod (inv_alloc counterN with \"[Hinv]\") as \"#Hinv\"; [iNext; iExact \"Hinv\"|].\n    (* splitting increment and read *)\n    iApply wp_pure_step_later; trivial. iModIntro. iNext. iAsimpl.\n    iApply wp_value; auto.\n    iExists (PairV (CG_locked_incrementV _ _) (counter_readV _)); simpl.\n    rewrite CG_locked_increment_of_val counter_read_of_val.\n    iFrame \"Hj\".\n    iExists (_, _), (_, _); simpl; repeat iSplit; trivial.\n    - (* refinement of increment *)\n      iModIntro. clear j K. iIntros (v) \"#Heq\". iIntros (j K) \"Hj\".\n      rewrite CG_locked_increment_of_val /=.\n      destruct v; iDestruct \"Heq\" as \"[% %]\"; simplify_eq/=.\n      iLöb as \"Hlat\".\n      iApply wp_pure_step_later; trivial. iAsimpl. iNext.\n      (* fine-grained reads the counter *)\n      iApply (wp_bind (fill [LetInCtx _]));\n        iApply wp_wand_l; iSplitR; [iIntros (v) \"Hv\"; iExact \"Hv\"|].\n      iApply wp_atomic; eauto.\n      iInv counterN as (n) \">[Hl [Hcnt Hcnt']]\" \"Hclose\".\n      iApply (wp_load with \"[Hcnt]\"); [iNext; by iFrame|].\n      iModIntro. iNext. iIntros \"Hcnt\".\n      iMod (\"Hclose\" with \"[Hl Hcnt Hcnt']\").\n      { iNext. iExists _. iFrame \"Hl Hcnt Hcnt'\". }\n      iApply wp_pure_step_later; trivial. iAsimpl. iModIntro. iNext.\n      (* fine-grained performs increment *)\n      iApply (wp_bind (fill [CasRCtx (LocV _) (NatV _); IfCtx _ _]));\n        iApply wp_wand_l; iSplitR; [iIntros (v) \"Hv\"; iExact \"Hv\"|].\n      iApply wp_pure_step_later; auto. iApply wp_value.\n      iNext.\n      iApply (wp_bind (fill [IfCtx _ _]));\n        iApply wp_wand_l; iSplitR; [iIntros (v) \"Hv\"; iExact \"Hv\"|].\n      iApply wp_atomic; eauto.\n      iInv counterN as (n') \">[Hl [Hcnt Hcnt']]\" \"Hclose\".\n      (* performing CAS *)\n      destruct (decide (n = n')) as [|Hneq]; subst.\n      + (* CAS succeeds *)\n        (* In this case, we perform increment in the coarse-grained one *)\n        iMod (steps_CG_locked_increment\n                _ _ _ _ _ _ _ with \"[Hj Hl Hcnt']\") as \"[Hj [Hcnt' Hl]]\".\n        { iFrame \"Hspec Hcnt' Hl Hj\"; trivial. }\n        iApply (wp_cas_suc with \"[Hcnt]\"); auto.\n        iModIntro. iNext. iIntros \"Hcnt\".\n        iMod (\"Hclose\" with \"[Hl Hcnt Hcnt']\").\n        { iNext. iExists _. iFrame \"Hl Hcnt Hcnt'\"; trivial. }\n        simpl.\n        iApply wp_pure_step_later; trivial.\n        iModIntro. iNext. iApply wp_value; trivial.\n        iExists UnitV; iFrame; auto.\n      + (* CAS fails *)\n        (* In this case, we perform a recursive call *)\n        iApply (wp_cas_fail _ _ _ (#nv n') with \"[Hcnt]\"); auto;\n        [inversion 1; subst; auto | ].\n        iModIntro. iNext. iIntros \"Hcnt\".\n        iMod (\"Hclose\" with \"[Hl Hcnt Hcnt']\").\n        { iNext. iExists _; iFrame \"Hl Hcnt Hcnt'\". }\n        iApply wp_pure_step_later; trivial. iModIntro. iNext. by iApply \"Hlat\".\n    - (* refinement of read *)\n      iModIntro. clear j K. iIntros (v) \"#Heq\". iIntros (j K) \"Hj\".\n      rewrite ?counter_read_of_val.\n      iDestruct \"Heq\" as \"[% %]\"; destruct v; simplify_eq/=.\n      Local Transparent counter_read. (* HACK *)\n      unfold counter_read.\n      iApply wp_pure_step_later; trivial. simpl.\n      iNext.\n      iApply wp_atomic; eauto.\n      iInv counterN as (n) \">[Hl [Hcnt Hcnt']]\" \"Hclose\".\n      iMod (steps_counter_read with \"[Hj Hcnt']\") as \"[Hj Hcnt']\"; first by solve_ndisj.\n      { by iFrame \"Hspec Hcnt' Hj\". }\n      iApply (wp_load with \"[Hcnt]\"); eauto.\n      iModIntro. iNext. iIntros \"Hcnt\".\n      iMod (\"Hclose\" with \"[Hl Hcnt Hcnt']\").\n      { iNext. iExists _; iFrame \"Hl Hcnt Hcnt'\". }\n      iExists (#nv _); eauto.\n      Unshelve. solve_ndisj.\n  Qed.\nEnd CG_Counter.\n\nTheorem counter_ctx_refinement :\n  [] ⊨ FG_counter ≤ctx≤ CG_counter :\n         TProd (TArrow TUnit TUnit) (TArrow TUnit TNat).\nProof.\n  set (Σ := #[invΣ ; gen_heapΣ loc val ; soundness_binaryΣ ]).\n  set (HG := soundness.HeapPreIG Σ _ _).\n  eapply (binary_soundness Σ _); auto using FG_counter_type, CG_counter_type.\n  intros. apply FG_CG_counter_refinement.\nQed.\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/logrel/F_mu_ref_conc/binary/examples/counter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2504043793006021}}
{"text": "Require compcert.backend.Stackingproof.\nRequire SmallstepX.\nRequire EventsX.\nRequire MachX.\nRequire LinearX.\n\nImport Coqlib.\nImport Integers.\nImport AST.\nImport ValuesX.\nImport MemoryX.\nImport Globalenvs.\nImport EventsX.\nImport SmallstepX.\nImport Locations.\nImport LinearX.\nImport Lineartyping.\nImport MachX.\nImport Stacking.\nExport Stackingproof.\n\nSection WITHCONFIG.\nContext `{compiler_config: CompilerConfiguration}.\n\nVariable prog: Linear.program.\nVariable tprog: Mach.program.\nHypothesis TRANSF: transf_program prog = Errors.OK tprog.\n\nLet ge := Genv.globalenv prog.\nLet tge := Genv.globalenv tprog.\n\nLemma genv_next_preserved:\n  Genv.genv_next tge = Genv.genv_next ge.\nProof.\n  eapply Genv.genv_next_transf_partial; eauto.\nQed.\n\nVariables\n  (init_mach_rs: Mach.regset)\n  (init_sp: val)\n  (init_m: mem)\n.\n\nDefinition init_linear_rs: Locations.Locmap.t :=\n    fun ros =>\n      match ros with\n        | R r => init_mach_rs r\n        | S Outgoing ofs ty => \n          match load_stack init_m init_sp ty (Int.repr (Stacklayout.fe_ofs_arg + 4 * ofs)) with\n            | Some v => v\n            | None => Vundef\n          end\n        | _ => Vundef\n      end.\n\nLemma extcall_args_eq:\n  forall ll vl,\n    list_forall2 (Mach.extcall_arg init_mach_rs init_m init_sp) ll vl\n  -> vl = map init_linear_rs ll.\nProof.\n  induction 1; simpl.\n   reflexivity.\n  f_equal; eauto.\n  inv H.\n   reflexivity.\n  unfold init_linear_rs.\n  rewrite H1.\n  reflexivity.\nQed.   \n\nLemma extcall_arg_init_linear_rs:\n  forall la,\n    list_forall2 (extcall_arg init_mach_rs init_m init_sp) la (map init_linear_rs la) ->\n    forall l, In l la ->\n    extcall_arg init_mach_rs init_m init_sp l (init_linear_rs l).\nProof.\n  induction la; simpl; inversion 1; subst.\n   tauto.\n  destruct 1; subst; eauto.\nQed.\n\nVariables\n  (init_ra: val)\n  (sg: signature)\n  (args: list val)\n  (Hargs: extcall_arguments init_mach_rs init_m init_sp sg args)\n  (Hinject_neutral: Mem.inject_neutral (Mem.nextblock init_m) init_m)\n  (Hgenv_next: Ple (Genv.genv_next tge) (Mem.nextblock init_m))\n.\n\nHypothesis init_mach_rs_inj:\n  forall r, val_inject (Mem.flat_inj (Mem.nextblock init_m)) (init_mach_rs r) (init_mach_rs r).\n\nLemma transf_initial_states:\n  forall i,\n  forall s\n         (INIT: LinearX.initial_state init_linear_rs prog i sg args init_m s),\n    exists s',\n      MachX.initial_state init_mach_rs init_sp tprog i sg args init_m s' /\\\n      match_states prog tprog init_m init_linear_rs init_sp init_ra s s'.\nProof.  \n  inversion 1; subst.\n  exploit function_ptr_translated; eauto.\n  destruct 1 as [tf [Htf TRANS]].\n  esplit.\n  split.\n  econstructor.\n  erewrite symbols_preserved; eauto.\n  assumption.\n  econstructor.\n  eapply Mem.neutral_inject. assumption.\n  econstructor.\n  eapply Ple_refl. apply Ple_refl.\n  constructor.\n  apply Ple_refl.\n  unfold Mem.flat_inj. intros. destruct (plt b0 (Mem.nextblock init_m)); eauto. contradiction.\n  unfold Mem.flat_inj. intros. destruct (plt b1 (Mem.nextblock init_m)); congruence.\n  intros. exploit Genv.genv_symb_range; eauto. erewrite genv_next_preserved in Hgenv_next; eauto. unfold ge in *; xomega.\n  intros. exploit Genv.genv_funs_range; eauto. erewrite genv_next_preserved in Hgenv_next; eauto. unfold ge in *; xomega.\n  intros. exploit Genv.genv_vars_range; eauto. erewrite genv_next_preserved in Hgenv_next; eauto. unfold ge in *; xomega.\n  intros. exploit extcall_arg_init_linear_rs; eauto. intro.\n  inv H0.\n  esplit. split. econstructor. eassumption.\n  destruct init_sp; try discriminate.\n  exploit Mem.loadv_inject.\n   eapply Mem.neutral_inject. eassumption.\n   eassumption.\n   unfold Val.add. econstructor.\n   unfold Mem.flat_inj. destruct (plt b0 (Mem.nextblock init_m)). reflexivity.\n   destruct n.\n   eapply Mem.valid_access_valid_block.\n   eapply Mem.valid_access_implies.\n   eapply Mem.load_valid_access. unfold load_stack, Val.add in H8. eexact H8.\n   constructor.\n   rewrite Int.add_zero.\n   reflexivity.\n  destruct 1 as [? [? ?]].\n  unfold load_stack, Val.add in H8.\n  rewrite H8 in H0. inv H0.\n  assumption.\n  eassumption.\n  assumption.\n  assumption.\n  constructor.\nQed.\n\nLemma transf_final_states:\n  forall s s' r\n         (MATCH: match_states prog tprog init_m init_linear_rs init_sp init_ra s s')\n         (FIN: LinearX.final_state init_linear_rs sg s r),\n    final_state_with_inject (MachX.final_state init_mach_rs sg) init_m s' r.\nProof.\n  intros.\n  inv FIN.\n  inv MATCH.\n  inv STACKS.\n  econstructor.\n  econstructor.\n  reflexivity.\n  { (* Callee-save registers. *)\n    intros.\n    refine (_ (AGLOCS (R r) _)).\n    simpl. intro REW.\n    eapply Mem.val_inject_flat_inj_lessdef.\n    eapply val_inject_incr_recip.\n    rewrite <- REW.\n    eapply AGREGS.\n    eapply init_mach_rs_inj.\n    eapply match_globalenvs_inject_incr.\n    eassumption.\n    assumption.\n  }\n  eapply match_globalenvs_inject_incr; eauto.\n  eapply match_globalenvs_inject_separated; eauto.\n  assumption.\n  generalize (Conventions1.loc_result sg). induction l; simpl; eauto.\nQed.\n\nHypothesis wt_init_mach_rs:\n  forall r, Val.has_type (init_mach_rs r) (mreg_type r).\n\nLemma wt_init_linear_rs:\n  wt_locset (Some Lineartyping.Locset.empty) init_linear_rs.\nProof.\n  constructor.\n  destruct l.\n   simpl; auto.\n  destruct sl; try (constructor; fail).\n  unfold init_linear_rs, load_stack.\n  case_eq (\n      Mem.loadv (chunk_of_type ty) init_m\n                (Val.add init_sp\n                         (Vint (Int.repr (Stacklayout.fe_ofs_arg + 4 * pos))))\n    ); try (constructor; fail).\n  destruct init_sp; try discriminate.\n  unfold Val.add, Mem.loadv.\n  intros.\n  exploit Mem.load_type; eauto.\n  destruct ty; simpl; tauto.\n  inversion 1.\nQed.\n\nTheorem wt_initial_state:\n  forall i,\n  forall S, LinearX.initial_state init_linear_rs prog i sg args init_m S ->\n            Lineartyping.wt_state init_linear_rs S.\nProof.\n  induction 1. \n  exploit Genv.find_funct_ptr_inversion; eauto.\n  destruct 1.\n  econstructor. \n  apply wt_callstack_nil.\n  eapply wt_init_linear_rs.\n  eapply wt_prog. eassumption. eassumption.\n  apply wt_init_linear_rs.\nQed.\n\nVariable return_address_offset: Mach.function -> Mach.code -> int -> Prop.\n\nHypothesis return_address_offset_exists:\n  forall f sg ros c,\n  is_tail (Mcall sg ros :: c) (fn_code f) ->\n  exists ofs, return_address_offset f c ofs.\n\nHypothesis init_sp_not_global:\n  forall (b : block) (o : int),\n   init_sp = Vptr b o -> Ple (Genv.genv_next (Genv.globalenv prog)) b.\n\nHypothesis init_sp_valid:\n  forall (b : block) (o : int),\n   init_sp = Vptr b o -> Mem.valid_block init_m b.\n\nHypothesis init_sp_int:\n  Val.has_type init_sp Tint.\n\nHypothesis init_ra_int:\n  Val.has_type init_ra Tint.\n\nLocal Instance: WritableBlockOps (writable_block init_m).\nProof. typeclasses eauto. Defined.\n\nTheorem transf_program_correct:\n  forall i,\n  forward_simulation\n    (LinearX.semantics init_linear_rs prog i sg args init_m)\n    (semantics_with_inject (MachX.semantics return_address_offset init_mach_rs init_sp init_ra tprog i sg args init_m) init_m)\n.\nProof.\n  set (ms := fun s s' => Lineartyping.wt_state init_linear_rs s /\\ match_states prog tprog init_m init_linear_rs init_sp init_ra s s').\n  intros.\n  eapply forward_simulation_plus with (match_states := ms). \n- apply symbols_preserved; auto.\n- intros. simpl in *.\n  exploit transf_initial_states; eauto. intros [st2 [A B]]. \n  exists st2; split; auto. split; auto.\n  eapply wt_initial_state; eauto.\n- intros. destruct H. eapply transf_final_states; eauto. \n- intros. destruct H0. \n  exploit transf_step_correct. \n  eassumption.\n  eassumption.\n  fold ge. erewrite <- genv_next_preserved; eauto.\n  eassumption.\n  assumption.\n  unfold Events.writable_block_with_init_mem. unfold writable_block. intros. generalize (init_sp_not_global _ _ H2). generalize (init_sp_valid _ _ H2). unfold Mem.valid_block. xomega.\n  assumption.\n  eexact init_ra_int.\n  simpl in H. eassumption.\n  assumption.\n  eassumption.\n  intros [s2' [A B]].\n  exists s2'; split. exact A. split.\n  eapply step_type_preservation; eauto. \n  eapply wt_prog. eassumption.\n  simpl in *. eassumption.\n  assumption.\nQed.\n\nEnd WITHCONFIG.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/compcertx/backend/StackingproofX.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.25040437930060205}}
{"text": "Require Import ExtLib.Core.RelDec.\nRequire Import ExtLib.Structures.Monads.\nRequire Import ExtLib.Structures.Applicative.\nRequire Import ExtLib.Structures.Functor.\nRequire Import ExtLib.Data.HList.\nRequire Import ExtLib.Data.List.\nRequire Import ExtLib.Data.Eq.\nRequire Import ExtLib.Data.Monads.OptionMonad.\nRequire Import ExtLib.Tactics.\nRequire Import MirrorCore.EnvI.\nRequire Import MirrorCore.SymI.\nRequire Import MirrorCore.ExprI.\nRequire Import MirrorCore.TypesI.\nRequire Import MirrorCore.Lambda.ExprCore.\nRequire Import MirrorCore.Lambda.ExprDI.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nModule ExprDenote <: ExprDenote.\n\n  Section with_types.\n    Context {typ func : Set}.\n    Context {RType_typD : RType typ}.\n    Context {Typ2_Fun : Typ2 _ Fun}.\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\n    Let typ_arr : typ -> typ -> typ := @typ2 _ _ _.\n    Let arr_match := @typ2_match _ _ _.\n    Let typD_arr\n    : forall ts a b, typD ts (typ_arr a b) = (typD ts a -> typD ts b)\n      := @typ2_cast _ _ _.\n\n\n    Global Instance RelDec_Rty ts : RelDec (Rty ts) :=\n    { rel_dec := fun a b => match type_cast ts a b with\n                              | Some _ => true\n                              | None => false\n                            end }.\n\n    Global Instance RelDec_Correct_Rty ts : @RelDec_Correct _ (Rty ts) _.\n    Proof.\n      constructor. unfold rel_dec; simpl.\n      intros; consider (type_cast ts x y); intros.\n      split; auto. apply type_cast_total in H; eauto with typeclass_instances.\n      intuition.\n    Qed.\n\n    Definition Rcast T {ts a b} (pf : Rty ts a b) : T (typD ts a) -> T (typD ts b) :=\n      Relim T (Rsym pf).\n\n    Definition Rcast_val\n    : forall {ts a b} (pf : Rty ts a b), typD ts a -> typD ts b :=\n      @Rcast (fun T => T).\n\n    Definition OpenT ts := ResType.OpenT (typD ts).\n    Definition Open_UseV := ResType.Open_UseV.\n    Definition Open_UseU := ResType.Open_UseU.\n    Definition Open_Inj ts tus tvs := Eval simpl in @pure (OpenT ts tus tvs) _.\n\n    Definition Open_App {ts tus tvs t u}\n    : OpenT ts tus tvs (typD ts (typ_arr t u)) -> OpenT ts tus tvs (typD ts t) -> OpenT ts tus tvs (typD ts u) :=\n      match eq_sym (typD_arr ts t u) in _ = T\n            return OpenT ts tus tvs T ->\n                   OpenT ts tus tvs (typD ts t) ->\n                   OpenT ts tus tvs (typD ts u)\n      with\n        | eq_refl => fun f x => fun us vs => (f us vs) (x us vs)\n      end.\n\n    Section OpenT.\n      Variable ts : list Type.\n      Variables tus tvs : tenv typ.\n\n      (** Auxiliary definitions **)\n      Definition Open_GetUAs (n : nat) (t : typ) :\n        option (OpenT ts tus tvs (typD ts t)) :=\n        bind (m := option)\n             (nth_error_get_hlist_nth (typD ts) tus n)\n             (fun t_get =>\n                let '(existT t' get) := t_get in\n                bind (m := option)\n                     (type_cast ts t' t)\n                     (fun cast =>\n                        ret (fun us vs => Rcast_val cast (get us)))).\n\n      Definition Open_GetVAs (n : nat) (t : typ) :\n        option (OpenT ts tus tvs (typD ts t)) :=\n        bind (m := option)\n             (nth_error_get_hlist_nth (typD ts) tvs n)\n             (fun t_get =>\n                let '(existT t' get) := t_get in\n                bind (m := option)\n                     (type_cast ts t' t)\n                     (fun cast =>\n                        ret (fun us vs => Rcast_val cast (get vs)))).\n\n    End OpenT.\n\n    Definition Open_Abs {ts tus tvs t u}\n    : OpenT ts tus (t :: tvs) (typD ts u) ->\n      OpenT ts tus tvs (typD ts (typ_arr t u)) :=\n      match eq_sym (typD_arr ts t u) in _ = T\n            return OpenT ts tus (t :: tvs) (typD ts u) -> OpenT ts tus tvs T\n      with\n        | eq_refl => fun f => fun us vs x => f us (Hcons x vs)\n      end.\n\n    Section typeof_expr.\n      Variable ts : list Type.\n      Variable tus : tenv typ.\n\n      Definition type_of_apply (tv x : typ) : option typ :=\n        arr_match (fun _ => option typ) ts tv\n                  (fun d r =>\n                     match type_cast ts d x with\n                       | Some _ => Some r\n                       | None => None\n                     end)\n                  None.\n\n      Fixpoint typeof_expr (tvs : tenv typ) (e : expr typ func)\n      : option typ :=\n        match e with\n        | Var x  => nth_error tvs x\n        | UVar x => nth_error tus x\n        | Inj f => typeof_sym f\n        | App e e' =>\n          match typeof_expr tvs e\n              , typeof_expr tvs e'\n          with\n            | Some tf , Some tx =>\n              type_of_apply tf tx\n            | _ , _ => None\n          end\n        | Abs t e =>\n          match typeof_expr (t :: tvs) e with\n            | None => None\n            | Some t' => Some (typ_arr t t')\n          end\n      end.\n    End typeof_expr.\n\n    Section exprD'.\n      Variable ts : list Type.\n      Variable tus : tenv typ.\n\n      Fixpoint exprD' (tvs : tenv typ) (t : typ) (e : expr typ func)\n      : option (OpenT ts tus tvs (typD ts t)) :=\n        match e return option (OpenT ts tus tvs (typD ts t)) with\n          | Var v => @Open_GetVAs ts tus tvs v t\n          | Inj f =>\n            bind (m := option)\n                 (@symAs _ _  _ f t)\n                 (fun val =>\n                    ret (@Open_Inj ts tus tvs _ val))\n          | App f x =>\n            bind (m := option)\n                 (typeof_expr ts tus tvs x)\n                 (fun d =>\n                    bind (m := option)\n                         (exprD' tvs (typ_arr d t) f)\n                         (fun f =>\n                            bind (m := option)\n                                 (exprD' tvs d x)\n                                 (fun x => ret (@Open_App ts _ _ _ _ f x))))\n          | Abs t' e =>\n            arr_match (fun T => option (OpenT ts tus tvs T)) ts t\n                      (fun d r =>\n                         bind (m := option)\n                              (type_cast ts d t')\n                              (fun cast =>\n                                 bind (m := option)\n                                      (exprD' (t' :: tvs) r e)\n                                      (fun val =>\n                                         ret (fun us vs x =>\n                                                val us (Hcons (Rcast_val cast x) vs)))))\n                      None\n          | UVar u => @Open_GetUAs ts tus tvs u t\n        end.\n    End exprD'.\n\n    (** Equations **)\n    Theorem exprD'_Var\n    : RTypeOk _ -> Typ2Ok Typ2_Fun -> RSymOk RSym_func ->\n      forall ts tus tvs t v,\n        exprD' ts tus tvs t (Var v) =\n        bind (m := option)\n             (nth_error_get_hlist_nth (typD ts) tvs v)\n             (fun t_get =>\n                let '(existT t' get) := t_get in\n                bind (m := option)\n                     (type_cast ts t' t)\n                     (fun cast =>\n                        ret (fun us vs => Rcast_val cast (get vs)))).\n    Proof. reflexivity. Qed.\n\n    Theorem exprD'_UVar\n    : RTypeOk _ -> Typ2Ok Typ2_Fun -> RSymOk RSym_func ->\n      forall ts tus tvs t u,\n        exprD' ts tus tvs t (UVar u) =\n        bind (m := option)\n             (nth_error_get_hlist_nth (typD ts) tus u)\n             (fun t_get =>\n                let '(existT t' get) := t_get in\n                bind (m := option)\n                     (type_cast ts t' t)\n                     (fun cast =>\n                        ret (fun us vs => Rcast_val cast (get us)))).\n    Proof. reflexivity. Qed.\n\n    Theorem exprD'_Inj\n    : RTypeOk _ -> Typ2Ok Typ2_Fun -> RSymOk RSym_func ->\n      forall ts tus tvs t s,\n        exprD' ts tus tvs t (Inj s) =\n        bind (m := option)\n             (funcAs s t)\n             (fun val =>\n                ret (fun _ _ => val)).\n    Proof. reflexivity. Qed.\n\n    Lemma exprD'_App'\n    : forall ts tus tvs t f x,\n        exprD' ts tus tvs t (App f x) =\n        bind (m := option)\n             (typeof_expr ts tus tvs x)\n             (fun d =>\n                bind (m := option)\n                     (exprD' ts tus tvs (typ_arr d t) f)\n                     (fun f =>\n                        bind (m := option)\n                             (exprD' ts tus tvs d x)\n                             (fun x => ret (@Open_App ts _ _ _ _ f x)))).\n    Proof. reflexivity. Qed.\n\n    Theorem exprD'_Abs\n    : RTypeOk _ -> Typ2Ok Typ2_Fun -> RSymOk RSym_func ->\n      forall ts tus tvs t t' e,\n        exprD' ts tus tvs t (Abs t' e) =\n        arr_match (fun T => option (OpenT ts tus tvs T)) ts t\n                  (fun d r =>\n                     bind (m := option)\n                          (type_cast ts d t')\n                          (fun cast =>\n                             bind (m := option)\n                                  (exprD' ts tus (t' :: tvs) r e)\n                                  (fun val =>\n                                     ret (fun us vs x =>\n                                            val us (Hcons (Rcast_val cast x) vs)))))\n                  None.\n    Proof. reflexivity. Qed.\n\n    Theorem exprD'_App\n    : RTypeOk _ -> Typ2Ok Typ2_Fun -> RSymOk RSym_func ->\n      forall ts tus tvs t f x,\n        exprD' ts tus tvs t (App f x) =\n        bind (m := option)\n             (typeof_expr ts tus tvs x)\n             (fun t' =>\n                bind (exprD' ts tus tvs (typ_arr t' t) f)\n                     (fun f =>\n                        bind (exprD' ts tus tvs t' x)\n                             (fun x =>\n                                ret (Open_App f x)))).\n    Proof. reflexivity. Qed.\n\n    Theorem exprD'_respects\n    : RTypeOk _ -> Typ2Ok Typ2_Fun -> RSymOk RSym_func ->\n      forall ts tus tvs t t' e (pf : Rty ts t' t),\n        exprD' ts tus tvs t e =\n        Rcast (fun T => option (OpenT ts tus tvs T)) pf\n              (exprD' ts tus tvs t' e).\n    Proof.\n      destruct pf. change (eq_refl t') with (Rrefl ts t').\n      unfold Rcast. rewrite Relim_refl; eauto with typeclass_instances.\n    Qed.\n\n  End with_types.\n\nEnd ExprDenote.\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/ExprDsimpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.25035748963709836}}
{"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_activate_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 e := EVT CPU_ID (ACQ gidx) in\n        if g_tag (ginfo gn) =? GRANULE_STATE_RD then\n          rely prop_dec (gtype gn = GRANULE_STATE_RD);\n          rely prop_dec ((buffer (priv adt)) @ SLOT_RD = None);\n          rely is_int (g_realm_state (gnorm gn));\n          if g_realm_state (gnorm gn) =? REALM_STATE_NEW then\n            if g_measurement_algo (gnorm gn) =? MEASUREMENT_ALGO_SHA256 then\n              if measure_finish (g_measurement_ctx (gnorm gn)) =? 0 then\n                let g' := gn {gnorm: (gnorm gn) {g_measurement: 0} {g_realm_state: REALM_STATE_ACTIVE}} in\n                let e' := EVT CPU_ID (REL gidx (g' {glock: Some CPU_ID})) in\n                Some (adt {log: e' :: e :: log adt}\n                          {share: (share adt) {gs: (gs (share adt)) # gidx == g'}},\n                      VZ64 0)\n              else None\n            else\n              let g' := gn {gnorm: (gnorm gn) {g_realm_state: REALM_STATE_ACTIVE}} in\n              let e' := EVT CPU_ID (REL gidx (g' {glock: Some CPU_ID})) in\n              Some (adt {log: e' :: e :: log adt}\n                        {share: (share adt) {gs: (gs (share adt)) # gidx == g'}},\n                    VZ64 0)\n          else\n            let e' := EVT CPU_ID (REL gidx (gn {glock: Some CPU_ID})) in\n            Some (adt {log: e' :: e :: (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' :: e :: (log adt)}, VZ64 1)\n      else Some (adt, VZ64 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/RmiSMC/Specs/smc_realm_activate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2503317346045022}}
{"text": "From caml5 Require Import\n  prelude.\nFrom caml5.base_logic Require Import\n  lib.excl.\nFrom caml5.lang Require Import\n  notations\n  proofmode.\nFrom caml5.concurrent Require Export\n  base.\nFrom caml5.concurrent Require Import\n  mpmc_queue\n  spmc_queue\n  mpsc_queue.\n\nImplicit Types v t : val.\nImplicit Types vs : list val.\n\nRecord spsc_queue `{!heapGS Σ} {unboxed : bool} := {\n  spsc_queue_make : val ;\n  spsc_queue_push : val ;\n  spsc_queue_pop : val ;\n\n  spsc_queue_name : Type ;\n  spsc_queue_inv : val → spsc_queue_name → namespace → iProp Σ ;\n  spsc_queue_model : val → spsc_queue_name → list val → iProp Σ ;\n  spsc_queue_producer : val → spsc_queue_name → iProp Σ ;\n  spsc_queue_consumer : val → spsc_queue_name → iProp Σ ;\n\n  spsc_queue_inv_persistent t γ ι :\n    Persistent (spsc_queue_inv t γ ι) ;\n  spsc_queue_model_timeless t γ vs :\n    Timeless (spsc_queue_model t γ vs) ;\n  spsc_queue_producer_timeless t γ :\n    Timeless (spsc_queue_producer t γ) ;\n  spsc_queue_consumer_timeless t γ :\n    Timeless (spsc_queue_consumer t γ) ;\n\n  spsc_queue_producer_exclusive t γ :\n    spsc_queue_producer t γ -∗\n    spsc_queue_producer t γ -∗\n    False ;\n  spsc_queue_consumer_exclusive t γ :\n    spsc_queue_consumer t γ -∗\n    spsc_queue_consumer t γ -∗\n    False ;\n\n  spsc_queue_make_spec ι :\n    {{{ True }}}\n      spsc_queue_make #()\n    {{{ t γ,\n      RET t;\n      spsc_queue_inv t γ ι ∗\n      spsc_queue_model t γ [] ∗\n      spsc_queue_producer t γ ∗\n      spsc_queue_consumer t γ\n    }}} ;\n\n  spsc_queue_push_spec t γ ι v :\n    <<<\n      spsc_queue_inv t γ ι ∗\n      spsc_queue_producer t γ |\n      ∀∀ vs, spsc_queue_model t γ vs\n    >>>\n      spsc_queue_push t v @ ↑ι\n    <<<\n      spsc_queue_model t γ (v :: vs) |\n      RET #(); spsc_queue_producer t γ\n    >>> ;\n\n  spsc_queue_pop_spec t γ ι :\n    <<<\n      spsc_queue_inv t γ ι ∗\n      spsc_queue_consumer t γ |\n      ∀∀ vs, spsc_queue_model t γ vs\n    >>>\n      spsc_queue_pop t @ ↑ι\n    <<< ∃∃ o,\n      (⌜vs = [] ∧ o = NONEV⌝ ∗ spsc_queue_model t γ []) ∨\n      (∃ vs' v, ⌜vs = vs' ++ [v] ∧ o = SOMEV v⌝ ∗ spsc_queue_model t γ vs') |\n      RET o; spsc_queue_consumer t γ\n    >>> ;\n\n  spsc_queue_unboxed :\n    if unboxed then ∀ t γ ι,\n      spsc_queue_inv t γ ι -∗\n      ⌜val_is_unboxed t⌝\n    else\n      True ;\n}.\n#[global] Arguments spsc_queue _ {_} _ : assert.\n#[global] Arguments Build_spsc_queue {_ _} _ {_ _ _ _ _ _ _ _ _ _ _ _ _ _} _ _ _ _ : assert.\n#[global] Existing Instance spsc_queue_inv_persistent.\n#[global] Existing Instance spsc_queue_model_timeless.\n#[global] Existing Instance spsc_queue_producer_timeless.\n#[global] Existing Instance spsc_queue_consumer_timeless.\n\nClass SpscQueueOfSpmcQueueG Σ `{!heapGS Σ} := {\n  spsc_queue_of_spmc_queue_G_consumer_G : ExclG Σ unitO ;\n}.\n#[local] Existing Instance spsc_queue_of_spmc_queue_G_consumer_G.\n\nDefinition spsc_queue_of_spmc_queue_Σ := #[\n  excl_Σ unitO\n].\nLemma subG_spsc_queue_of_spmc_queue_Σ Σ `{!heapGS Σ} :\n  subG spsc_queue_of_spmc_queue_Σ Σ →\n  SpscQueueOfSpmcQueueG Σ.\nProof.\n  solve_inG.\nQed.\n\nSection spsc_queue_of_spmc_queue.\n  Context `{SpscQueueOfSpmcQueueG Σ} {unboxed} (spmc_queue : spmc_queue Σ unboxed).\n\n  Notation \"γ .(base)\" := γ.1\n  ( at level 5\n  ) : stdpp_scope.\n  Notation \"γ .(consumer)\" := γ.2\n  ( at level 5\n  ) : stdpp_scope.\n\n  Program Definition spsc_queue_of_spmc_queue : spsc_queue Σ unboxed := {|\n    spsc_queue_make :=\n      spmc_queue.(spmc_queue_make) ;\n    spsc_queue_push :=\n      spmc_queue.(spmc_queue_push) ;\n    spsc_queue_pop :=\n      spmc_queue.(spmc_queue_pop) ;\n\n    spsc_queue_name :=\n      spmc_queue.(spmc_queue_name) * gname ;\n    spsc_queue_inv t γ ι :=\n      spmc_queue.(spmc_queue_inv) t γ.(base) ι ;\n    spsc_queue_model t γ :=\n      spmc_queue.(spmc_queue_model) t γ.(base) ;\n    spsc_queue_producer t γ :=\n      spmc_queue.(spmc_queue_producer) t γ.(base) ;\n    spsc_queue_consumer _ γ :=\n      excl γ.(consumer) () ;\n  |}.\n  Next Obligation.\n    intros. apply spmc_queue_producer_exclusive.\n  Qed.\n  Next Obligation.\n    intros. apply excl_exclusive.\n  Qed.\n  Next Obligation.\n    iIntros \"%ι %Φ _ HΦ\".\n    iMod excl_alloc as \"(%γ_consumer & Hconsumer)\".\n    wp_apply (spmc_queue_make_spec with \"[//]\"). iIntros \"%t %γ_base (Hinv & Hmodel & Hproducer)\".\n    iApply (\"HΦ\" $! t (γ_base, γ_consumer)). iFrame.\n  Qed.\n  Next Obligation.\n    intros. apply spmc_queue_push_spec.\n  Qed.\n  Next Obligation.\n    iIntros \"%t %γ %ι !> %Φ (Hinv & Hconsumer) HΦ\".\n    wp_apply (spmc_queue_pop_spec with \"Hinv\").\n    iApply (atomic_update_wand with \"[Hconsumer] HΦ\").\n    iIntros \"_ %v HΦ _\". iApply \"HΦ\". done.\n  Qed.\n  Next Obligation.\n    destruct unboxed; last done. eauto using spmc_queue.(spmc_queue_unboxed).\n  Qed.\nEnd spsc_queue_of_spmc_queue.\n\nClass SpscQueueOfMpscQueueG Σ `{!heapGS Σ} := {\n  spsc_queue_of_mpsc_queue_G_producer_G : ExclG Σ unitO ;\n}.\n#[local] Existing Instance spsc_queue_of_mpsc_queue_G_producer_G.\n\nDefinition spsc_queue_of_mpsc_queue_Σ := #[\n  excl_Σ unitO\n].\nLemma subG_spsc_queue_of_mpsc_queue_Σ Σ `{!heapGS Σ} :\n  subG spsc_queue_of_mpsc_queue_Σ Σ →\n  SpscQueueOfMpscQueueG Σ.\nProof.\n  solve_inG.\nQed.\n\nSection spsc_queue_of_mpsc_queue.\n  Context `{SpscQueueOfMpscQueueG Σ} {unboxed} (mpsc_queue : mpsc_queue Σ unboxed).\n\n  Notation \"γ .(base)\" := γ.1\n  ( at level 5\n  ) : stdpp_scope.\n  Notation \"γ .(producer)\" := γ.2\n  ( at level 5\n  ) : stdpp_scope.\n\n  Program Definition spsc_queue_of_mpsc_queue : spsc_queue Σ unboxed := {|\n    spsc_queue_make :=\n      mpsc_queue.(mpsc_queue_make) ;\n    spsc_queue_push :=\n      mpsc_queue.(mpsc_queue_push) ;\n    spsc_queue_pop :=\n      mpsc_queue.(mpsc_queue_pop) ;\n\n    spsc_queue_name :=\n      mpsc_queue.(mpsc_queue_name) * gname ;\n    spsc_queue_inv t γ ι :=\n      mpsc_queue.(mpsc_queue_inv) t γ.(base) ι ;\n    spsc_queue_model t γ :=\n      mpsc_queue.(mpsc_queue_model) t γ.(base) ;\n    spsc_queue_producer _ γ :=\n      excl γ.(producer) () ;\n    spsc_queue_consumer t γ :=\n      mpsc_queue.(mpsc_queue_consumer) t γ.(base) ;\n  |}.\n  Next Obligation.\n    intros. apply excl_exclusive.\n  Qed.\n  Next Obligation.\n    intros. apply mpsc_queue_consumer_exclusive.\n  Qed.\n  Next Obligation.\n    iIntros \"%ι %Φ _ HΦ\".\n    iMod excl_alloc as \"(%γ_producer & Hproducer)\".\n    wp_apply (mpsc_queue_make_spec with \"[//]\"). iIntros \"%t %γ_base (Hinv & Hmodel & Hconsumer)\".\n    iApply (\"HΦ\" $! t (γ_base, γ_producer)). iFrame.\n  Qed.\n  Next Obligation.\n    iIntros \"%t %γ %ι %v !> %Φ (Hinv & Hproducer) HΦ\".\n    wp_apply (mpsc_queue_push_spec with \"Hinv\").\n    iApply (atomic_update_wand with \"[Hproducer] HΦ\").\n    iIntros \"_ HΦ _\". iApply \"HΦ\". done.\n  Qed.\n  Next Obligation.\n    intros. apply mpsc_queue_pop_spec.\n  Qed.\n  Next Obligation.\n    destruct unboxed; last done. eauto using mpsc_queue.(mpsc_queue_unboxed).\n  Qed.\nEnd spsc_queue_of_mpsc_queue.\n\nClass SpscQueueOfMpmcQueueG Σ `{!heapGS Σ} := {\n  spsc_queue_of_mpmc_queue_G_mpmc_queue_G : SpmcQueueOfMpmcQueueG Σ ;\n  spsc_queue_of_mpmc_queue_G_spmc_queue_G : SpscQueueOfSpmcQueueG Σ ;\n}.\n#[local] Existing Instance spsc_queue_of_mpmc_queue_G_mpmc_queue_G.\n#[local] Existing Instance spsc_queue_of_mpmc_queue_G_spmc_queue_G.\n\nDefinition spsc_queue_of_mpmc_queue_Σ := #[\n  spmc_queue_of_mpmc_queue_Σ ;\n  spsc_queue_of_spmc_queue_Σ\n].\nLemma subG_spsc_queue_of_mpmc_queue_Σ Σ `{!heapGS Σ} :\n  subG spsc_queue_of_mpmc_queue_Σ Σ →\n  SpscQueueOfMpmcQueueG Σ.\nProof.\n  pose subG_spmc_queue_of_mpmc_queue_Σ.\n  pose subG_spsc_queue_of_spmc_queue_Σ.\n  solve_inG.\nQed.\n\nDefinition spsc_queue_of_mpmc_queue `{SpscQueueOfMpmcQueueG Σ} {unboxed} {mpmc_queue : mpmc_queue Σ unboxed} :=\n  spsc_queue_of_spmc_queue (spmc_queue_of_mpmc_queue mpmc_queue).\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/concurrent/spsc_queue.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.25033172902592565}}
{"text": "From stdpp Require Export list gmap.\nFrom iris.algebra Require Export list cmra.\nFrom iris.algebra Require Import gset.\nFrom iris.algebra Require Import updates local_updates proofmode_classes big_op.\nFrom iris.prelude Require Import options.\n\nSection ofe.\nContext `{Countable K} {A : ofe}.\nImplicit Types m : gmap K A.\nImplicit Types i : K.\n\nLocal Instance gmap_dist : Dist (gmap K A) := λ n m1 m2,\n  ∀ i, m1 !! i ≡{n}≡ m2 !! i.\nDefinition gmap_ofe_mixin : OfeMixin (gmap K A).\nProof.\n  split.\n  - intros m1 m2; split.\n    + by intros Hm n k; apply equiv_dist.\n    + intros Hm k; apply equiv_dist; intros n; apply Hm.\n  - intros n; split.\n    + by intros m k.\n    + by intros m1 m2 ? k.\n    + by intros m1 m2 m3 ?? k; trans (m2 !! k).\n  - intros n m m1 m2 ? ? k. eauto using dist_le with si_solver.\nQed.\nCanonical Structure gmapO : ofe := Ofe (gmap K A) gmap_ofe_mixin.\n\nProgram Definition gmap_chain (c : chain gmapO)\n  (k : K) : chain (optionO A) := {| chain_car n := c n !! k |}.\nNext Obligation. by intros c k n i ?; apply (chain_cauchy c). Qed.\nDefinition gmap_compl `{Cofe A} : Compl gmapO := λ c,\n  map_imap (λ i _, compl (gmap_chain c i)) (c 0).\nGlobal Program Instance gmap_cofe `{Cofe A} : Cofe gmapO :=\n  {| compl := gmap_compl |}.\nNext Obligation.\n  intros ? n c k. rewrite /compl /gmap_compl map_lookup_imap.\n  feed inversion (λ H, chain_cauchy c 0 n H k);simplify_option_eq;auto with lia.\n  by rewrite conv_compl /=; apply reflexive_eq.\nQed.\n\nGlobal Instance gmap_ofe_discrete : OfeDiscrete A → OfeDiscrete gmapO.\nProof. intros ? m m' ? i. by apply (discrete _). Qed.\n(* why doesn't this go automatic? *)\nGlobal Instance gmapO_leibniz: LeibnizEquiv A → LeibnizEquiv gmapO.\nProof. intros; change (LeibnizEquiv (gmap K A)); apply _. Qed.\n\nGlobal Instance lookup_ne k : NonExpansive (lookup k : gmap K A → option A).\nProof. by intros n m1 m2. Qed.\nGlobal Instance lookup_total_ne `{!Inhabited A} k :\n  NonExpansive (lookup_total k : gmap K A → A).\nProof. intros n m1 m2. rewrite !lookup_total_alt. by intros ->. Qed.\nGlobal Instance partial_alter_ne n :\n  Proper ((dist n ==> dist n) ==> (=) ==> dist n ==> dist n)\n         (partial_alter (M:=gmap K A)).\nProof.\n  by intros f1 f2 Hf i ? <- m1 m2 Hm j; destruct (decide (i = j)) as [->|];\n    rewrite ?lookup_partial_alter ?lookup_partial_alter_ne //;\n    try apply Hf; apply lookup_ne.\nQed.\nGlobal Instance insert_ne i : NonExpansive2 (insert (M:=gmap K A) i).\nProof. intros n x y ? m m' ? j; apply partial_alter_ne; by try constructor. Qed.\nGlobal Instance singleton_ne i : NonExpansive (singletonM i : A → gmap K A).\nProof. by intros ????; apply insert_ne. Qed.\nGlobal Instance delete_ne i : NonExpansive (delete (M:=gmap K A) i).\nProof.\n  intros n m m' ? j; destruct (decide (i = j)); simplify_map_eq;\n    [by constructor|by apply lookup_ne].\nQed.\nGlobal Instance alter_ne (f : A → A) (k : K) n :\n  Proper (dist n ==> dist n) f → Proper (dist n ==> dist n) (alter (M := gmap K A) f k).\nProof. intros ? m m' Hm k'. by apply partial_alter_ne; [solve_proper|..]. Qed.\n\nGlobal Instance gmap_empty_discrete : Discrete (∅ : gmap K A).\nProof.\n  intros m Hm i; specialize (Hm i); rewrite lookup_empty in Hm |- *.\n  inversion_clear Hm; constructor.\nQed.\nGlobal Instance gmap_lookup_discrete m i : Discrete m → Discrete (m !! i).\nProof.\n  intros ? [x|] Hx; [|by symmetry; apply: discrete].\n  assert (m ≡{0}≡ <[i:=x]> m)\n    by (by symmetry in Hx; inversion Hx; ofe_subst; rewrite insert_id).\n  by rewrite (discrete m (<[i:=x]>m)) // lookup_insert.\nQed.\nGlobal Instance gmap_insert_discrete m i x :\n  Discrete x → Discrete m → Discrete (<[i:=x]>m).\nProof.\n  intros ?? m' Hm j; destruct (decide (i = j)); simplify_map_eq.\n  { by apply: discrete; rewrite -Hm lookup_insert. }\n  by apply: discrete; rewrite -Hm lookup_insert_ne.\nQed.\nGlobal Instance gmap_singleton_discrete i x :\n  Discrete x → Discrete ({[ i := x ]} : gmap K A) := _.\nLemma insert_idN n m i x :\n  m !! i ≡{n}≡ Some x → <[i:=x]>m ≡{n}≡ m.\nProof. intros (y'&?&->)%dist_Some_inv_r'. by rewrite insert_id. Qed.\n\nGlobal Instance gmap_dom_ne n :\n  Proper ((≡{n}@{gmap K A}≡) ==> (=)) dom.\nProof. intros m1 m2 Hm. apply set_eq=> k. by rewrite !elem_of_dom Hm. Qed.\nEnd ofe.\n\nGlobal Instance map_seq_ne {A : ofe} start :\n  NonExpansive (map_seq (M:=gmap nat A) start).\nProof.\n  intros n l1 l2 Hl. revert start.\n  induction Hl; intros; simpl; repeat (done || f_equiv).\nQed.\n\nGlobal Arguments gmapO _ {_ _} _.\n\n(** Non-expansiveness of higher-order map functions and big-ops *)\nGlobal Instance merge_ne `{Countable K} {A B C : ofe} n :\n  Proper (((dist (A:=option A) n) ==> (dist (A:=option B) n) ==> (dist (A:=option C) n)) ==>\n   (dist n) ==> (dist n) ==> (dist n)) (merge (M:=gmap K)).\nProof.\n  intros ?? Hf ?? Hm1 ?? Hm2 i. rewrite !lookup_merge.\n  destruct (Hm1 i), (Hm2 i); try apply Hf; by constructor.\nQed.\nGlobal Instance union_with_proper `{Countable K} {A : ofe} n :\n  Proper (((dist n) ==> (dist n) ==> (dist n)) ==>\n          (dist n) ==> (dist n) ==>(dist n)) (union_with (M:=gmap K A)).\nProof.\n  intros ?? Hf ?? Hm1 ?? Hm2 i; apply (merge_ne _ _); auto.\n  by do 2 destruct 1; first [apply Hf | constructor].\nQed.\nGlobal Instance map_fmap_proper `{Countable K} {A B : ofe} (f : A → B) n :\n  Proper (dist n ==> dist n) f → Proper (dist n ==> dist n) (fmap (M:=gmap K) f).\nProof. intros ? m m' ? k; rewrite !lookup_fmap. by repeat f_equiv. Qed.\nGlobal Instance map_zip_with_proper `{Countable K} {A B C : ofe} (f : A → B → C) n :\n  Proper (dist n ==> dist n ==> dist n) f →\n  Proper (dist n ==> dist n ==> dist n) (map_zip_with (M:=gmap K) f).\nProof.\n  intros Hf m1 m1' Hm1 m2 m2' Hm2. apply merge_ne; try done.\n  destruct 1; destruct 1; repeat f_equiv; constructor || done.\nQed.\n\nLemma big_opM_ne_2 `{Monoid M o} `{Countable K} {A : ofe} (f g : K → A → M) m1 m2 n :\n  m1 ≡{n}≡ m2 →\n  (∀ k y1 y2,\n    m1 !! k = Some y1 → m2 !! k = Some y2 → y1 ≡{n}≡ y2 → f k y1 ≡{n}≡ g k y2) →\n  ([^o map] k ↦ y ∈ m1, f k y) ≡{n}≡ ([^o map] k ↦ y ∈ m2, g k y).\nProof.\n  intros Hl Hf. apply big_opM_gen_proper_2; try (apply _ || done).\n  { by intros ?? ->. }\n  { apply monoid_ne. }\n  intros k. assert (m1 !! k ≡{n}≡ m2 !! k) as Hlk by (by f_equiv).\n  destruct (m1 !! k) eqn:?, (m2 !! k) eqn:?; inversion Hlk; naive_solver.\nQed.\n\n(* CMRA *)\nSection cmra.\nContext `{Countable K} {A : cmra}.\nImplicit Types m : gmap K A.\n\nLocal Instance gmap_unit_instance : Unit (gmap K A) := (∅ : gmap K A).\nLocal Instance gmap_op_instance : Op (gmap K A) := merge op.\nLocal Instance gmap_pcore_instance : PCore (gmap K A) := λ m, Some (omap pcore m).\nLocal Instance gmap_valid_instance : Valid (gmap K A) := λ m, ∀ i, ✓ (m !! i).\nLocal Instance gmap_validN_instance : ValidN (gmap K A) := λ n m, ∀ i, ✓{n} (m !! i).\n\nLemma gmap_op m1 m2 : m1 ⋅ m2 = merge op m1 m2.\nProof. done. Qed.\nLemma lookup_op m1 m2 i : (m1 ⋅ m2) !! i = m1 !! i ⋅ m2 !! i.\nProof. rewrite lookup_merge. by destruct (m1 !! i), (m2 !! i). Qed.\nLemma lookup_core m i : core m !! i = core (m !! i).\nProof. by apply lookup_omap. Qed.\n\nLemma lookup_includedN n (m1 m2 : gmap K A) : m1 ≼{n} m2 ↔ ∀ i, m1 !! i ≼{n} m2 !! i.\nProof.\n  split; [by intros [m Hm] i; exists (m !! i); rewrite -lookup_op Hm|].\n  revert m2. induction m1 as [|i x m Hi IH] using map_ind=> m2 Hm.\n  { exists m2. by rewrite left_id. }\n  destruct (IH (delete i m2)) as [m2' Hm2'].\n  { intros j. move: (Hm j); destruct (decide (i = j)) as [->|].\n    - intros _. rewrite Hi. apply: ucmra_unit_leastN.\n    - rewrite lookup_insert_ne // lookup_delete_ne //. }\n  destruct (Hm i) as [my Hi']; simplify_map_eq.\n  exists (partial_alter (λ _, my) i m2')=>j; destruct (decide (i = j)) as [->|].\n  - by rewrite Hi' lookup_op lookup_insert lookup_partial_alter.\n  - move: (Hm2' j). by rewrite !lookup_op lookup_delete_ne //\n      lookup_insert_ne // lookup_partial_alter_ne.\nQed.\n\n(* [m1 ≼ m2] is not equivalent to [∀ n, m1 ≼{n} m2],\nso there is no good way to reuse the above proof. *)\nLemma lookup_included (m1 m2 : gmap K A) : m1 ≼ m2 ↔ ∀ i, m1 !! i ≼ m2 !! i.\nProof.\n  split; [by intros [m Hm] i; exists (m !! i); rewrite -lookup_op Hm|].\n  revert m2. induction m1 as [|i x m Hi IH] using map_ind=> m2 Hm.\n  { exists m2. by rewrite left_id. }\n  destruct (IH (delete i m2)) as [m2' Hm2'].\n  { intros j. move: (Hm j); destruct (decide (i = j)) as [->|].\n    - intros _. rewrite Hi. apply: ucmra_unit_least.\n    - rewrite lookup_insert_ne // lookup_delete_ne //. }\n  destruct (Hm i) as [my Hi']; simplify_map_eq.\n  exists (partial_alter (λ _, my) i m2')=>j; destruct (decide (i = j)) as [->|].\n  - by rewrite Hi' lookup_op lookup_insert lookup_partial_alter.\n  - move: (Hm2' j). by rewrite !lookup_op lookup_delete_ne //\n      lookup_insert_ne // lookup_partial_alter_ne.\nQed.\n\nLemma gmap_cmra_mixin : CmraMixin (gmap K A).\nProof.\n  apply cmra_total_mixin.\n  - eauto.\n  - intros n m1 m2 m3 Hm i; by rewrite !lookup_op (Hm i).\n  - intros n m1 m2 Hm i; by rewrite !lookup_core (Hm i).\n  - intros n m1 m2 Hm ? i; by rewrite -(Hm i).\n  - intros m; split.\n    + by intros ? n i; apply cmra_valid_validN.\n    + intros Hm i; apply cmra_valid_validN=> n; apply Hm.\n  - intros n m Hm i; apply cmra_validN_S, Hm.\n  - by intros m1 m2 m3 i; rewrite !lookup_op assoc.\n  - by intros m1 m2 i; rewrite !lookup_op comm.\n  - intros m i. by rewrite lookup_op lookup_core cmra_core_l.\n  - intros m i. by rewrite !lookup_core cmra_core_idemp.\n  - intros m1 m2; rewrite !lookup_included=> Hm i.\n    rewrite !lookup_core. by apply cmra_core_mono.\n  - intros n m1 m2 Hm i; apply cmra_validN_op_l with (m2 !! i).\n    by rewrite -lookup_op.\n  - intros n m y1 y2 Hm Heq.\n    refine ((λ FUN, _) (λ i, cmra_extend n (m !! i) (y1 !! i) (y2 !! i) (Hm i) _));\n      last by rewrite -lookup_op.\n    exists (map_imap (λ i _, projT1 (FUN i)) y1).\n    exists (map_imap (λ i _, proj1_sig (projT2 (FUN i))) y2).\n    split; [|split]=>i; rewrite ?lookup_op !map_lookup_imap;\n    destruct (FUN i) as (z1i&z2i&Hmi&Hz1i&Hz2i)=>/=.\n    + destruct (y1 !! i), (y2 !! i); inversion Hz1i; inversion Hz2i; subst=>//.\n    + revert Hz1i. case: (y1!!i)=>[?|] //.\n    + revert Hz2i. case: (y2!!i)=>[?|] //.\nQed.\nCanonical Structure gmapR := Cmra (gmap K A) gmap_cmra_mixin.\n\nGlobal Instance gmap_cmra_discrete : CmraDiscrete A → CmraDiscrete gmapR.\nProof. split; [apply _|]. intros m ? i. by apply: cmra_discrete_valid. Qed.\n\nLemma gmap_ucmra_mixin : UcmraMixin (gmap K A).\nProof.\n  split.\n  - by intros i; rewrite lookup_empty.\n  - by intros m i; rewrite /= lookup_op lookup_empty (left_id_L None _).\n  - constructor=> i. by rewrite lookup_omap lookup_empty.\nQed.\nCanonical Structure gmapUR := Ucmra (gmap K A) gmap_ucmra_mixin.\n\nEnd cmra.\n\nGlobal Arguments gmapR _ {_ _} _.\nGlobal Arguments gmapUR _ {_ _} _.\n\nSection properties.\nContext `{Countable K} {A : cmra}.\nImplicit Types m : gmap K A.\nImplicit Types i : K.\nImplicit Types x y : A.\n\nGlobal Instance lookup_op_homomorphism i :\n  MonoidHomomorphism op op (≡) (lookup i : gmap K A → option A).\nProof.\n  split; [split|]; try apply _.\n  - intros m1 m2; by rewrite lookup_op.\n  - done.\nQed.\n\nLemma lookup_opM m1 mm2 i : (m1 ⋅? mm2) !! i = m1 !! i ⋅ (mm2 ≫= (.!! i)).\nProof. destruct mm2; by rewrite /= ?lookup_op ?right_id_L. Qed.\n\nLemma lookup_validN_Some n m i x : ✓{n} m → m !! i ≡{n}≡ Some x → ✓{n} x.\nProof. by move=> /(_ i) Hm Hi; move:Hm; rewrite Hi. Qed.\nLemma lookup_valid_Some m i x : ✓ m → m !! i ≡ Some x → ✓ x.\nProof. move=> Hm Hi. move:(Hm i). by rewrite Hi. Qed.\n\nLemma insert_validN n m i x : ✓{n} x → ✓{n} m → ✓{n} <[i:=x]>m.\nProof. by intros ?? j; destruct (decide (i = j)); simplify_map_eq. Qed.\nLemma insert_valid m i x : ✓ x → ✓ m → ✓ <[i:=x]>m.\nProof. by intros ?? j; destruct (decide (i = j)); simplify_map_eq. Qed.\nLemma singleton_validN n i x : ✓{n} ({[ i := x ]} : gmap K A) ↔ ✓{n} x.\nProof.\n  split.\n  - move=>/(_ i); by simplify_map_eq.\n  - intros. apply insert_validN; first done. apply: ucmra_unit_validN.\nQed.\nLemma singleton_valid i x : ✓ ({[ i := x ]} : gmap K A) ↔ ✓ x.\nProof. rewrite !cmra_valid_validN. by setoid_rewrite singleton_validN. Qed.\n\nLemma delete_validN n m i : ✓{n} m → ✓{n} (delete i m).\nProof. intros Hm j; destruct (decide (i = j)); by simplify_map_eq. Qed.\nLemma delete_valid m i : ✓ m → ✓ (delete i m).\nProof. intros Hm j; destruct (decide (i = j)); by simplify_map_eq. Qed.\n\nLemma insert_singleton_op m i x : m !! i = None → <[i:=x]> m = {[ i := x ]} ⋅ m.\nProof.\n  intros Hi; apply map_eq=> j; destruct (decide (i = j)) as [->|].\n  - by rewrite lookup_op lookup_insert lookup_singleton Hi right_id_L.\n  - by rewrite lookup_op lookup_insert_ne // lookup_singleton_ne // left_id_L.\nQed.\n\nLemma singleton_core (i : K) (x : A) cx :\n  pcore x = Some cx → core {[ i := x ]} =@{gmap K A} {[ i := cx ]}.\nProof. apply omap_singleton_Some. Qed.\nLemma singleton_core' (i : K) (x : A) cx :\n  pcore x ≡ Some cx → core {[ i := x ]} ≡@{gmap K A} {[ i := cx ]}.\nProof.\n  intros (cx'&?&<-)%Some_equiv_eq. by rewrite (singleton_core _ _ cx').\nQed.\nLemma singleton_core_total `{!CmraTotal A} (i : K) (x : A) :\n  core {[ i := x ]} =@{gmap K A} {[ i := core x ]}.\nProof. apply singleton_core. rewrite cmra_pcore_core //. Qed.\nLemma singleton_op (i : K) (x y : A) :\n  {[ i := x ]} ⋅ {[ i := y ]} =@{gmap K A} {[ i := x ⋅ y ]}.\nProof. by apply (merge_singleton _ _ _ x y). Qed.\nGlobal Instance singleton_is_op i a a1 a2 :\n  IsOp a a1 a2 → IsOp' ({[ i := a ]} : gmap K A) {[ i := a1 ]} {[ i := a2 ]}.\nProof. rewrite /IsOp' /IsOp=> ->. by rewrite -singleton_op. Qed.\n\nLemma gmap_core_id m : (∀ i x, m !! i = Some x → CoreId x) → CoreId m.\nProof.\n  intros Hcore; apply core_id_total=> i.\n  rewrite lookup_core. destruct (m !! i) as [x|] eqn:Hix; rewrite Hix; [|done].\n  by eapply Hcore.\nQed.\nGlobal Instance gmap_core_id' m : (∀ x : A, CoreId x) → CoreId m.\nProof. auto using gmap_core_id. Qed.\n\nGlobal Instance gmap_singleton_core_id i (x : A) :\n  CoreId x → CoreId {[ i := x ]}.\nProof. intros. by apply core_id_total, singleton_core'. Qed.\n\nLemma singleton_includedN_l n m i x :\n  {[ i := x ]} ≼{n} m ↔ ∃ y, m !! i ≡{n}≡ Some y ∧ Some x ≼{n} Some y.\nProof.\n  split.\n  - move=> [m' /(_ i)]; rewrite lookup_op lookup_singleton=> Hi.\n    exists (x ⋅? m' !! i). rewrite -Some_op_opM.\n    split; first done. apply cmra_includedN_l.\n  - intros (y&Hi&[mz Hy]). exists (partial_alter (λ _, mz) i m).\n    intros j; destruct (decide (i = j)) as [->|].\n    + by rewrite lookup_op lookup_singleton lookup_partial_alter Hi.\n    + by rewrite lookup_op lookup_singleton_ne// lookup_partial_alter_ne// left_id.\nQed.\n(* We do not have [x ≼ y ↔ ∀ n, x ≼{n} y], so we cannot use the previous lemma *)\nLemma singleton_included_l m i x :\n  {[ i := x ]} ≼ m ↔ ∃ y, m !! i ≡ Some y ∧ Some x ≼ Some y.\nProof.\n  split.\n  - move=> [m' /(_ i)]; rewrite lookup_op lookup_singleton.\n    exists (x ⋅? m' !! i). rewrite -Some_op_opM.\n    split; first done. apply cmra_included_l.\n  - intros (y&Hi&[mz Hy]). exists (partial_alter (λ _, mz) i m).\n    intros j; destruct (decide (i = j)) as [->|].\n    + by rewrite lookup_op lookup_singleton lookup_partial_alter Hi.\n    + by rewrite lookup_op lookup_singleton_ne// lookup_partial_alter_ne// left_id.\nQed.\nLemma singleton_included_exclusive_l m i x :\n  Exclusive x → ✓ m →\n  {[ i := x ]} ≼ m ↔ m !! i ≡ Some x.\nProof.\n  intros ? Hm. rewrite singleton_included_l. split; last by eauto.\n  intros (y&?&->%(Some_included_exclusive _)); eauto using lookup_valid_Some.\nQed.\nLemma singleton_included i x y :\n  {[ i := x ]} ≼ ({[ i := y ]} : gmap K A) ↔ x ≡ y ∨ x ≼ y.\nProof.\n  rewrite singleton_included_l. split.\n  - intros (y'&Hi&?). rewrite lookup_insert in Hi.\n    apply Some_included. by rewrite Hi.\n  - intros ?. exists y. by rewrite lookup_insert Some_included.\nQed.\nLemma singleton_mono i x y :\n  x ≼ y → {[ i := x ]} ≼ ({[ i := y ]} : gmap K A).\nProof. intros Hincl. apply singleton_included. right. done. Qed.\n\nGlobal Instance singleton_cancelable i x :\n  Cancelable (Some x) → Cancelable {[ i := x ]}.\nProof.\n  intros ? n m1 m2 Hv EQ j. move: (Hv j) (EQ j). rewrite !lookup_op.\n  destruct (decide (i = j)) as [->|].\n  - rewrite lookup_singleton. by apply cancelableN.\n  - by rewrite lookup_singleton_ne // !(left_id None _).\nQed.\n\nGlobal Instance gmap_cancelable (m : gmap K A) :\n  (∀ x : A, IdFree x) → (∀ x : A, Cancelable x) → Cancelable m.\nProof.\n  intros ?? n m1 m2 ?? i. apply (cancelableN (m !! i)); by rewrite -!lookup_op.\nQed.\n\nLemma insert_op m1 m2 i x y :\n  <[i:=x ⋅ y]>(m1 ⋅ m2) =  <[i:=x]>m1 ⋅ <[i:=y]>m2.\nProof. by rewrite (insert_merge (⋅) m1 m2 i (x ⋅ y) x y). Qed.\n\nLemma insert_updateP (P : A → Prop) (Q : gmap K A → Prop) m i x :\n  x ~~>: P →\n  (∀ y, P y → Q (<[i:=y]>m)) →\n  <[i:=x]>m ~~>: Q.\nProof.\n  intros Hx%option_updateP' HP; apply cmra_total_updateP=> n mf Hm.\n  destruct (Hx n (Some (mf !! i))) as ([y|]&?&?); try done.\n  { by generalize (Hm i); rewrite lookup_op; simplify_map_eq. }\n  exists (<[i:=y]> m); split; first by auto.\n  intros j; move: (Hm j)=>{Hm}; rewrite !lookup_op=>Hm.\n  destruct (decide (i = j)); simplify_map_eq/=; auto.\nQed.\nLemma insert_updateP' (P : A → Prop) m i x :\n  x ~~>: P → <[i:=x]>m ~~>: λ m', ∃ y, m' = <[i:=y]>m ∧ P y.\nProof. eauto using insert_updateP. Qed.\nLemma insert_update m i x y : x ~~> y → <[i:=x]>m ~~> <[i:=y]>m.\nProof. rewrite !cmra_update_updateP; eauto using insert_updateP with subst. Qed.\n\nLemma singleton_updateP (P : A → Prop) (Q : gmap K A → Prop) i x :\n  x ~~>: P → (∀ y, P y → Q {[ i := y ]}) → {[ i := x ]} ~~>: Q.\nProof. apply insert_updateP. Qed.\nLemma singleton_updateP' (P : A → Prop) i x :\n  x ~~>: P → {[ i := x ]} ~~>: λ m, ∃ y, m = {[ i := y ]} ∧ P y.\nProof. apply insert_updateP'. Qed.\nLemma singleton_update i (x y : A) : x ~~> y → {[ i := x ]} ~~> {[ i := y ]}.\nProof. apply insert_update. Qed.\n\nLemma delete_update m i : m ~~> delete i m.\nProof.\n  apply cmra_total_update=> n mf Hm j; destruct (decide (i = j)); subst.\n  - move: (Hm j). rewrite !lookup_op lookup_delete left_id.\n    apply cmra_validN_op_r.\n  - move: (Hm j). by rewrite !lookup_op lookup_delete_ne.\nQed.\n\nLemma dom_op m1 m2 : dom (m1 ⋅ m2) = dom m1 ∪ dom m2.\nProof.\n  apply set_eq=> i; rewrite elem_of_union !elem_of_dom.\n  unfold is_Some; setoid_rewrite lookup_op.\n  destruct (m1 !! i), (m2 !! i); naive_solver.\nQed.\nLemma dom_included m1 m2 : m1 ≼ m2 → dom m1 ⊆ dom m2.\nProof.\n  rewrite lookup_included=>? i; rewrite !elem_of_dom. by apply is_Some_included.\nQed.\n\nSection freshness.\n  Local Set Default Proof Using \"Type*\".\n  Context `{!Infinite K}.\n  Lemma alloc_updateP_strong_dep (Q : gmap K A → Prop) (I : K → Prop) m (f : K → A) :\n    pred_infinite I →\n    (∀ i, m !! i = None → I i → ✓ (f i)) →\n    (∀ i, m !! i = None → I i → Q (<[i:=f i]>m)) → m ~~>: Q.\n  Proof.\n    move=> /(pred_infinite_set I (C:=gset K)) HP ? HQ.\n    apply cmra_total_updateP. intros n mf Hm.\n    destruct (HP (dom (m ⋅ mf))) as [i [Hi1 Hi2]].\n    assert (m !! i = None).\n    { eapply not_elem_of_dom. revert Hi2.\n      rewrite dom_op not_elem_of_union. naive_solver. }\n    exists (<[i:=f i]>m); split.\n    - by apply HQ.\n    - rewrite insert_singleton_op //.\n      rewrite -assoc -insert_singleton_op; last by eapply not_elem_of_dom.\n    apply insert_validN; [apply cmra_valid_validN|]; auto.\n  Qed.\n  Lemma alloc_updateP_strong (Q : gmap K A → Prop) (I : K → Prop) m x :\n    pred_infinite I →\n    ✓ x → (∀ i, m !! i = None → I i → Q (<[i:=x]>m)) → m ~~>: Q.\n  Proof.\n    move=> HP ? HQ. eapply (alloc_updateP_strong_dep _ _ _ (λ _, x)); eauto.\n  Qed.\n  Lemma alloc_updateP (Q : gmap K A → Prop) m x :\n    ✓ x → (∀ i, m !! i = None → Q (<[i:=x]>m)) → m ~~>: Q.\n  Proof.\n    move=>??.\n    eapply (alloc_updateP_strong _ (λ _, True));\n    eauto using pred_infinite_True.\n  Qed.\n  Lemma alloc_updateP_cofinite (Q : gmap K A → Prop) (J : gset K) m x :\n    ✓ x → (∀ i, m !! i = None → i ∉ J → Q (<[i:=x]>m)) → m ~~>: Q.\n  Proof.\n    eapply alloc_updateP_strong.\n    apply (pred_infinite_set (C:=gset K)).\n    intros E. exists (fresh (J ∪ E)).\n    apply not_elem_of_union, is_fresh.\n  Qed.\n\n  (* Variants without the universally quantified Q, for use in case that is an evar. *)\n  Lemma alloc_updateP_strong_dep' m (f : K → A) (I : K → Prop) :\n    pred_infinite I →\n    (∀ i, m !! i = None → I i → ✓ (f i)) →\n    m ~~>: λ m', ∃ i, I i ∧ m' = <[i:=f i]>m ∧ m !! i = None.\n  Proof. eauto using alloc_updateP_strong_dep. Qed.\n  Lemma alloc_updateP_strong' m x (I : K → Prop) :\n    pred_infinite I →\n    ✓ x → m ~~>: λ m', ∃ i, I i ∧ m' = <[i:=x]>m ∧ m !! i = None.\n  Proof. eauto using alloc_updateP_strong. Qed.\n  Lemma alloc_updateP' m x :\n    ✓ x → m ~~>: λ m', ∃ i, m' = <[i:=x]>m ∧ m !! i = None.\n  Proof. eauto using alloc_updateP. Qed.\n  Lemma alloc_updateP_cofinite' m x (J : gset K) :\n    ✓ x → m ~~>: λ m', ∃ i, i ∉ J ∧ m' = <[i:=x]>m ∧ m !! i = None.\n  Proof. eauto using alloc_updateP_cofinite. Qed.\nEnd freshness.\n\nLemma alloc_unit_singleton_updateP (P : A → Prop) (Q : gmap K A → Prop) u i :\n  ✓ u → LeftId (≡) u (⋅) →\n  u ~~>: P → (∀ y, P y → Q {[ i := y ]}) → ∅ ~~>: Q.\nProof.\n  intros ?? Hx HQ. apply cmra_total_updateP=> n gf Hg.\n  destruct (Hx n (gf !! i)) as (y&?&Hy).\n  { move:(Hg i). rewrite !left_id.\n    case: (gf !! i)=>[x|]; rewrite /= ?left_id //.\n    intros; by apply cmra_valid_validN. }\n  exists {[ i := y ]}; split; first by auto.\n  intros i'; destruct (decide (i' = i)) as [->|].\n  - rewrite lookup_op lookup_singleton.\n    move:Hy; case: (gf !! i)=>[x|]; rewrite /= ?right_id //.\n  - move:(Hg i'). by rewrite !lookup_op lookup_singleton_ne // !left_id.\nQed.\nLemma alloc_unit_singleton_updateP' (P: A → Prop) u i :\n  ✓ u → LeftId (≡) u (⋅) →\n  u ~~>: P → ∅ ~~>: λ m, ∃ y, m = {[ i := y ]} ∧ P y.\nProof. eauto using alloc_unit_singleton_updateP. Qed.\nLemma alloc_unit_singleton_update (u : A) i (y : A) :\n  ✓ u → LeftId (≡) u (⋅) → u ~~> y → (∅:gmap K A) ~~> {[ i := y ]}.\nProof.\n  rewrite !cmra_update_updateP;\n    eauto using alloc_unit_singleton_updateP with subst.\nQed.\n\nLemma alloc_local_update m1 m2 i x :\n  m1 !! i = None → ✓ x → (m1,m2) ~l~> (<[i:=x]>m1, <[i:=x]>m2).\nProof.\n  rewrite cmra_valid_validN=> Hi ?.\n  apply local_update_unital=> n mf Hmv Hm; simpl in *.\n  split; auto using insert_validN.\n  intros j; destruct (decide (i = j)) as [->|].\n  - move: (Hm j); rewrite Hi symmetry_iff dist_None lookup_op op_None=>-[_ Hj].\n    by rewrite lookup_op !lookup_insert Hj.\n  - rewrite Hm lookup_insert_ne // !lookup_op lookup_insert_ne //.\nQed.\n\nLemma alloc_singleton_local_update m i x :\n  m !! i = None → ✓ x → (m,∅) ~l~> (<[i:=x]>m, {[ i:=x ]}).\nProof. apply alloc_local_update. Qed.\n\nLemma insert_local_update m1 m2 i x y x' y' :\n  m1 !! i = Some x → m2 !! i = Some y →\n  (x, y) ~l~> (x', y') →\n  (m1, m2) ~l~> (<[i:=x']>m1, <[i:=y']>m2).\nProof.\n  intros Hi1 Hi2 Hup; apply local_update_unital=> n mf Hmv Hm; simpl in *.\n  destruct (Hup n (mf !! i)) as [? Hx']; simpl in *.\n  { move: (Hmv i). by rewrite Hi1. }\n  { move: (Hm i). by rewrite lookup_op Hi1 Hi2 Some_op_opM (inj_iff Some). }\n  split; auto using insert_validN.\n  rewrite Hm Hx'=> j; destruct (decide (i = j)) as [->|].\n  - by rewrite lookup_insert lookup_op lookup_insert Some_op_opM.\n  - by rewrite lookup_insert_ne // !lookup_op lookup_insert_ne.\nQed.\n\nLemma singleton_local_update_any m i y x' y' :\n  (∀ x, m !! i = Some x → (x, y) ~l~> (x', y')) →\n  (m, {[ i := y ]}) ~l~> (<[i:=x']>m, {[ i := y' ]}).\nProof.\n  intros. rewrite /singletonM /map_singleton -(insert_insert ∅ i y' y).\n  apply local_update_total_valid0=>_ _ /singleton_includedN_l [x0 [/dist_Some_inv_r Hlk0 _]].\n  edestruct Hlk0 as [x [Hlk _]]; [done..|].\n  eapply insert_local_update; [|eapply lookup_insert|]; eauto.\nQed.\n\nLemma singleton_local_update m i x y x' y' :\n  m !! i = Some x →\n  (x, y) ~l~> (x', y') →\n  (m, {[ i := y ]}) ~l~> (<[i:=x']>m, {[ i := y' ]}).\nProof.\n  intros Hmi ?. apply singleton_local_update_any.\n  intros x2. rewrite Hmi=>[=<-]. done.\nQed.\n\nLemma delete_local_update m1 m2 i x `{!Exclusive x} :\n  m2 !! i = Some x → (m1, m2) ~l~> (delete i m1, delete i m2).\nProof.\n  intros Hi. apply local_update_unital=> n mf Hmv Hm; simpl in *.\n  split; auto using delete_validN.\n  rewrite Hm=> j; destruct (decide (i = j)) as [<-|].\n  - rewrite lookup_op !lookup_delete left_id symmetry_iff dist_None.\n    apply eq_None_not_Some=> -[y Hi'].\n    move: (Hmv i). rewrite Hm lookup_op Hi Hi' -Some_op. by apply exclusiveN_l.\n  - by rewrite lookup_op !lookup_delete_ne // lookup_op.\nQed.\n\nLemma delete_singleton_local_update m i x `{!Exclusive x} :\n  (m, {[ i := x ]}) ~l~> (delete i m, ∅).\nProof.\n  rewrite -(delete_singleton i x).\n  by eapply delete_local_update, lookup_singleton.\nQed.\n\nLemma delete_local_update_cancelable m1 m2 i mx `{!Cancelable mx} :\n  m1 !! i ≡ mx → m2 !! i ≡ mx →\n  (m1, m2) ~l~> (delete i m1, delete i m2).\nProof.\n  intros Hm1i Hm2i. apply local_update_unital=> n mf Hmv Hm; simpl in *.\n  split; [eauto using delete_validN|].\n  intros j. destruct (decide (i = j)) as [->|].\n  - move: (Hm j). rewrite !lookup_op Hm1i Hm2i !lookup_delete. intros Hmx.\n    rewrite (cancelableN mx n (mf !! j) None) ?right_id // -Hmx -Hm1i. apply Hmv.\n  - by rewrite lookup_op !lookup_delete_ne // Hm lookup_op.\nQed.\n\nLemma delete_singleton_local_update_cancelable m i x `{!Cancelable (Some x)} :\n  m !! i ≡ Some x → (m, {[ i := x ]}) ~l~> (delete i m, ∅).\nProof.\n  intros. rewrite -(delete_singleton i x).\n  apply (delete_local_update_cancelable m _ i (Some x));\n    [done|by rewrite lookup_singleton].\nQed.\n\nLemma gmap_fmap_mono {B : cmra} (f : A → B) m1 m2 :\n  Proper ((≡) ==> (≡)) f →\n  (∀ x y, x ≼ y → f x ≼ f y) → m1 ≼ m2 → fmap f m1 ≼ fmap f m2.\nProof.\n  intros ??. rewrite !lookup_included=> Hm i.\n  rewrite !lookup_fmap. by apply option_fmap_mono.\nQed.\n\nLemma big_opM_singletons m :\n  ([^op map] k ↦ x ∈ m, {[ k := x ]}) = m.\nProof.\n  (* We are breaking the big_opM abstraction here. The reason is that [map_ind]\n     is too weak: we need an induction principle that visits all the keys in the\n     right order, namely the order in which they appear in map_to_list.  Here,\n     we achieve this by unfolding [big_opM] and doing induction over that list\n     instead. *)\n  rewrite big_op.big_opM_unseal /big_op.big_opM_def -{2}(list_to_map_to_list m).\n  assert (NoDup (map_to_list m).*1) as Hnodup by apply NoDup_fst_map_to_list.\n  revert Hnodup. induction (map_to_list m) as [|[k x] l IH]; csimpl; first done.\n  intros [??]%NoDup_cons. rewrite IH //.\n  rewrite insert_singleton_op ?not_elem_of_list_to_map_1 //.\nQed.\n\nEnd properties.\n\nSection unital_properties.\nContext `{Countable K} {A : ucmra}.\nImplicit Types m : gmap K A.\nImplicit Types i : K.\nImplicit Types x y : A.\n\nLemma insert_alloc_local_update m1 m2 i x x' y' :\n  m1 !! i = Some x → m2 !! i = None →\n  (x, ε) ~l~> (x', y') →\n  (m1, m2) ~l~> (<[i:=x']>m1, <[i:=y']>m2).\nProof.\n  intros Hi1 Hi2 Hup. apply local_update_unital=> n mf Hm1v Hm.\n  assert (mf !! i ≡{n}≡ Some x) as Hif.\n  { move: (Hm i). by rewrite lookup_op Hi1 Hi2 left_id. }\n  destruct (Hup n (mf !! i)) as [Hx'v Hx'eq].\n  { move: (Hm1v i). by rewrite Hi1. }\n  { by rewrite Hif -(inj_iff Some) -Some_op_opM -Some_op left_id. }\n  split.\n  - by apply insert_validN.\n  - simpl in Hx'eq. by rewrite -(insert_idN n mf i x) // -insert_op -Hm Hx'eq Hif.\nQed.\nEnd unital_properties.\n\n(** Functor *)\nGlobal Instance gmap_fmap_ne `{Countable K} {A B : ofe} (f : A → B) n :\n  Proper (dist n ==> dist n) f → Proper (dist n ==>dist n) (fmap (M:=gmap K) f).\nProof. by intros ? m m' Hm k; rewrite !lookup_fmap; apply option_fmap_ne. Qed.\nLemma gmap_fmap_ne_ext `{Countable K}\n  {A : Type} {B : ofe} (f1 f2 : A → B) (m : gmap K A) n :\n  (∀ i x, m !! i = Some x → f1 x ≡{n}≡ f2 x) →\n  f1 <$> m ≡{n}≡ f2 <$> m.\nProof.\n  move => Hf i.\n  rewrite !lookup_fmap.\n  destruct (m !! i) eqn:?; constructor; by eauto.\nQed.\nGlobal Instance gmap_fmap_cmra_morphism `{Countable K} {A B : cmra} (f : A → B)\n  `{!CmraMorphism f} : CmraMorphism (fmap f : gmap K A → gmap K B).\nProof.\n  split; try apply _.\n  - by intros n m ? i; rewrite lookup_fmap; apply (cmra_morphism_validN _).\n  - intros m. apply Some_proper=>i. rewrite lookup_fmap !lookup_omap lookup_fmap.\n    case: (m!!i)=>//= ?. apply cmra_morphism_pcore, _.\n  - intros m1 m2 i. by rewrite lookup_op !lookup_fmap lookup_op cmra_morphism_op.\nQed.\nDefinition gmapO_map `{Countable K} {A B} (f: A -n> B) :\n  gmapO K A -n> gmapO K B := OfeMor (fmap f : gmapO K A → gmapO K B).\nGlobal Instance gmapO_map_ne `{Countable K} {A B} :\n  NonExpansive (@gmapO_map K _ _ A B).\nProof.\n  intros n f g Hf m k; rewrite /= !lookup_fmap.\n  destruct (_ !! k) eqn:?; simpl; constructor; apply Hf.\nQed.\n\nProgram Definition gmapOF K `{Countable K} (F : oFunctor) : oFunctor := {|\n  oFunctor_car A _ B _ := gmapO K (oFunctor_car F A B);\n  oFunctor_map A1 _ A2 _ B1 _ B2 _ fg := gmapO_map (oFunctor_map F fg)\n|}.\nNext Obligation.\n  by intros K ?? F A1 ? A2 ? B1 ? B2 ? n f g Hfg; apply gmapO_map_ne, oFunctor_map_ne.\nQed.\nNext Obligation.\n  intros K ?? F A ? B ? x. rewrite /= -{2}(map_fmap_id x).\n  apply map_fmap_equiv_ext=>y ??; apply oFunctor_map_id.\nQed.\nNext Obligation.\n  intros K ?? F A1 ? A2 ? A3 ? B1 ? B2 ? B3 ? f g f' g' x. rewrite /= -map_fmap_compose.\n  apply map_fmap_equiv_ext=>y ??; apply oFunctor_map_compose.\nQed.\nGlobal Instance gmapOF_contractive K `{Countable K} F :\n  oFunctorContractive F → oFunctorContractive (gmapOF K F).\nProof.\n  by intros ? A1 ? A2 ? B1 ? B2 ? n f g Hfg; apply gmapO_map_ne, oFunctor_map_contractive.\nQed.\n\nProgram Definition gmapURF K `{Countable K} (F : rFunctor) : urFunctor := {|\n  urFunctor_car A _ B _ := gmapUR K (rFunctor_car F A B);\n  urFunctor_map A1 _ A2 _ B1 _ B2 _ fg := gmapO_map (rFunctor_map F fg)\n|}.\nNext Obligation.\n  by intros K ?? F A1 ? A2 ? B1 ? B2 ? n f g Hfg; apply gmapO_map_ne, rFunctor_map_ne.\nQed.\nNext Obligation.\n  intros K ?? F A ? B ? x. rewrite /= -{2}(map_fmap_id x).\n  apply map_fmap_equiv_ext=>y ??; apply rFunctor_map_id.\nQed.\nNext Obligation.\n  intros K ?? F A1 ? A2 ? A3 ? B1 ? B2 ? B3 ? f g f' g' x. rewrite /= -map_fmap_compose.\n  apply map_fmap_equiv_ext=>y ??; apply rFunctor_map_compose.\nQed.\nGlobal Instance gmapURF_contractive K `{Countable K} F :\n  rFunctorContractive F → urFunctorContractive (gmapURF K F).\nProof.\n  by intros ? A1 ? A2 ? B1 ? B2 ? n f g Hfg; apply gmapO_map_ne, rFunctor_map_contractive.\nQed.\n\nProgram Definition gmapRF K `{Countable K} (F : rFunctor) : rFunctor := {|\n  rFunctor_car A _ B _ := gmapR K (rFunctor_car F A B);\n  rFunctor_map A1 _ A2 _ B1 _ B2 _ fg := gmapO_map (rFunctor_map F fg)\n|}.\nSolve Obligations with apply gmapURF.\n\nGlobal Instance gmapRF_contractive K `{Countable K} F :\n  rFunctorContractive F → rFunctorContractive (gmapRF K F).\nProof. apply gmapURF_contractive. 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/gmap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632683808532, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2502690755958983}}
{"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 A B C D Aprime Bprime Cprime Dprime X Y E Z Eprime : Universe, ((wd_ X A /\\ (wd_ X Aprime /\\ (wd_ X C /\\ (wd_ X Cprime /\\ (wd_ Y B /\\ (wd_ Y Bprime /\\ (wd_ Y D /\\ (wd_ Y Dprime /\\ (wd_ A C /\\ (wd_ B D /\\ (wd_ A Aprime /\\ (wd_ E Z /\\ (wd_ A D /\\ (wd_ D E /\\ (wd_ A E /\\ (wd_ X Y /\\ (wd_ X B /\\ (wd_ A Y /\\ (wd_ A B /\\ (wd_ B C /\\ (wd_ Bprime Cprime /\\ (wd_ Aprime Dprime /\\ (wd_ Aprime Bprime /\\ (col_ X A C /\\ (col_ X A Aprime /\\ (col_ X A Cprime /\\ (col_ Y B D /\\ (col_ Y B Bprime /\\ (col_ Y B Dprime /\\ (col_ E A B /\\ (col_ E C D /\\ (col_ X E Z /\\ (col_ A E Z /\\ (col_ Eprime Aprime Bprime /\\ col_ Eprime E Z)))))))))))))))))))))))))))))))))) -> col_ E X A)).\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_1129.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.682573734412324, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.25022453476567114}}
{"text": "From lrust.lifetime Require Export primitive.\nFrom lrust.lifetime Require Import faking.\nFrom iris.algebra Require Import csum auth frac gmap agree gset numbers.\nFrom iris.base_logic.lib Require Import boxes.\nFrom iris.proofmode Require Import proofmode.\nFrom iris.prelude Require Import options.\n\nSection creation.\nContext `{!invGS Σ, !lftGS Σ userE}.\nImplicit Types κ : lft.\n\nLemma lft_kill (I : gmap lft lft_names) (K K' : gset lft) (κ : lft) :\n  let Iinv := (\n    own_ilft_auth I ∗\n    ([∗ set] κ' ∈ K, lft_inv_dead κ') ∗\n    ([∗ set] κ' ∈ K', lft_inv_alive κ'))%I in\n  (∀ κ', is_Some (I !! κ') → κ ⊂ κ' → κ' ∈ K) →\n  (∀ κ', is_Some (I !! κ') → κ' ⊂ κ → κ' ∈ K') →\n  Iinv -∗ lft_inv_alive κ -∗ [†κ] ={userE ∪ ↑borN ∪ ↑inhN}=∗ Iinv ∗ lft_inv_dead κ.\nProof.\n  iIntros (Iinv HK HK') \"(HI & Hdead & Halive) Hlalive Hκ\".\n  rewrite lft_inv_alive_unfold;\n    iDestruct \"Hlalive\" as (P Q) \"(Hbor & Hvs & Hinh)\".\n  rewrite /lft_bor_alive; iDestruct \"Hbor\" as (B) \"(Hbox & Hbor & HB)\".\n  iAssert ⌜∀ i s, B !! i = Some s → s = Bor_in⌝%I with \"[#]\" as %HB.\n  { iIntros (i s HBI).\n    iDestruct (big_sepM_lookup _ B with \"HB\") as \"HB\"=> //.\n    destruct s as [|q|κ']; rewrite /bor_cnt //.\n    { iDestruct (lft_tok_dead with \"HB Hκ\") as \"[]\". }\n    iDestruct \"HB\" as \"[% Hcnt]\".\n    iDestruct (own_cnt_auth with \"HI Hcnt\") as %?.\n    iDestruct (@big_sepS_elem_of with \"Hdead\") as \"Hdead\"; first by eauto.\n    rewrite /lft_inv_dead; iDestruct \"Hdead\" as (R) \"(_ & Hcnt' & _)\".\n    iDestruct (own_cnt_valid_2 with \"Hcnt' Hcnt\")\n      as %[?%nat_included _]%auth_both_valid_discrete; lia. }\n  iMod (box_empty with \"Hbox\") as \"[HP Hbox]\"=>//; first by solve_ndisj.\n  { intros i s. by rewrite lookup_fmap fmap_Some=> -[? [/HB -> ->]]. }\n  rewrite lft_vs_unfold; iDestruct \"Hvs\" as (n) \"[Hcnt Hvs]\".\n  iDestruct (big_sepS_filter_acc (.⊂ κ) _ _ (dom I) with \"Halive\")\n    as \"[Halive Halive']\".\n  { intros κ'. rewrite elem_of_dom. eauto. }\n  iApply fupd_trans. iApply fupd_mask_mono; last\n  iMod (\"Hvs\" $! I with \"[HI Halive] HP Hκ\") as \"(Hinv & HQ & Hcnt')\".\n  { set_solver+. }\n  { rewrite lft_vs_inv_unfold. iFrame. }\n  rewrite lft_vs_inv_unfold; iDestruct \"Hinv\" as \"(HI&Halive)\".\n  iSpecialize (\"Halive'\" with \"Halive\").\n  iMod (own_cnt_update_2 with \"Hcnt Hcnt'\") as \"?\".\n  { apply auth_update_dealloc, (nat_local_update _ _ 0 0); lia. }\n  rewrite /Iinv. iFrame \"Hdead Halive' HI\".\n  iModIntro. iMod (lft_inh_kill with \"[$Hinh $HQ]\"); first set_solver+.\n  iModIntro. rewrite /lft_inv_dead. iExists Q. iFrame.\n  rewrite /lft_bor_dead. iExists (dom B), P.\n  rewrite !gset_to_gmap_dom -map_fmap_compose.\n  rewrite (map_fmap_ext _ ((1%Qp,.) ∘ to_agree) B); last naive_solver.\n  iFrame.\nQed.\n\nLemma lfts_kill (A : gmap atomic_lft _) (I : gmap lft lft_names) (K K' : gset lft) :\n  let Iinv K' := (own_ilft_auth I ∗ [∗ set] κ' ∈ K', lft_inv_alive κ')%I in\n  K ## K' →\n  (∀ κ κ', κ ∈ K → is_Some (I !! κ') → κ ⊆ κ' → κ' ∈ K) →\n  (∀ κ, lft_alive_in A κ → is_Some (I !! κ) → κ ∉ K → κ ∈ K') →\n  Iinv K' -∗ ([∗ set] κ ∈ K, lft_inv A κ ∗ [†κ])\n    ={userE ∪ ↑borN ∪ ↑inhN}=∗ Iinv K' ∗ [∗ set] κ ∈ K, lft_inv_dead κ.\nProof.\n  intros Iinv. revert K'.\n  induction (set_wf K) as [K _ IH]=> K' HKK' HK HK'.\n  iIntros \"[HI Halive] HK\".\n  pose (Kalive := filter (lft_alive_in A) K).\n  destruct (decide (Kalive = ∅)) as [HKalive|].\n  { iModIntro. rewrite /Iinv. iFrame.\n    iApply (@big_sepS_impl with \"[$HK]\"); iModIntro.\n    rewrite /lft_inv. iIntros (κ Hκ) \"[[[_ %]|[$ _]] _]\". set_solver. }\n  destruct (minimal_exists_L (⊂) Kalive)\n    as (κ & [Hκalive HκK]%elem_of_filter & Hκmin); first done.\n  iDestruct (@big_sepS_delete with \"HK\") as \"[[Hκinv Hκ] HK]\"; first done.\n  iDestruct (lft_inv_alive_in with \"Hκinv\") as \"Hκalive\"; first done.\n  assert (κ ∉ K') as HκK' by set_solver +HκK HKK'.\n  specialize (IH (K ∖ {[ κ ]})). feed specialize IH; [set_solver +HκK|].\n  iMod (IH ({[ κ ]} ∪ K') with \"[HI Halive Hκalive] HK\") as \"[[HI Halive] Hdead]\".\n  { set_solver +HKK'. }\n  { intros κ' κ''.\n    rewrite !elem_of_difference !elem_of_singleton=> -[? Hneq] ??.\n    split; [by eauto|]; intros ->.\n    eapply (minimal_strict_1 _ _ κ' Hκmin), strict_spec_alt; eauto.\n    apply elem_of_filter; eauto using lft_alive_in_subseteq. }\n  { intros κ' Hκ'. destruct (decide (κ' = κ)) as [->|Hκκ']; [set_solver +|].\n    specialize (HK' _ Hκ'). set_solver +Hκκ' HK'. }\n  { rewrite /Iinv big_sepS_insert //. iFrame. }\n  iDestruct (@big_sepS_insert with \"Halive\") as \"[Hκalive Halive]\"; first done.\n  iMod (lft_kill with \"[$HI $Halive $Hdead] Hκalive Hκ\")\n    as \"[(HI&Halive&Hdead) Hκdead]\".\n  { intros κ' ? [??]%strict_spec_alt.\n    rewrite elem_of_difference elem_of_singleton; eauto. }\n  { intros κ' ??. eapply HK'; [|done|].\n    - by eapply lft_alive_in_subseteq, gmultiset_subset_subseteq.\n    - intros ?. eapply (minimal_strict_1 _ _ _ Hκmin); eauto.\n      apply elem_of_filter; split; last done.\n      eapply lft_alive_in_subseteq, gmultiset_subset_subseteq; eauto. }\n  iModIntro. rewrite /Iinv (big_sepS_delete _ K) //. iFrame.\nQed.\n\nDefinition kill_set (I : gmap lft lft_names) (Λ : atomic_lft) : gset lft :=\n  filter (Λ ∈.) (dom I).\n\nLemma elem_of_kill_set I Λ κ : κ ∈ kill_set I Λ ↔ Λ ∈ κ ∧ is_Some (I !! κ).\nProof. by rewrite /kill_set elem_of_filter elem_of_dom. Qed.\n\nLemma lft_create_strong P E :\n  pred_infinite P → ↑lftN ⊆ E →\n  lft_ctx ={E}=∗\n  ∃ p : positive, let κ := positive_to_lft p in ⌜P p⌝ ∗\n       (1).[κ] ∗ □ ((1).[κ] ={↑lftN ∪ userE}[userE]▷=∗ [†κ]).\nProof.\n  assert (userE_lftN_disj:=userE_lftN_disj). iIntros (HP ?) \"#LFT\".\n  iInv mgmtN as (A I) \"(>HA & >HI & Hinv)\" \"Hclose\".\n  rewrite ->(pred_infinite_set (C:=gset _)) in HP.\n  destruct (HP (dom A)) as [Λ [HPx HΛ%not_elem_of_dom]].\n  iMod (own_update with \"HA\") as \"[HA HΛ]\".\n  { apply auth_update_alloc, (alloc_singleton_local_update _ Λ (Cinl 1%Qp))=>//.\n    by rewrite lookup_fmap HΛ. }\n  iMod (\"Hclose\" with \"[HA HI Hinv]\") as \"_\".\n  { iNext. rewrite /lfts_inv /own_alft_auth.\n    iExists (<[Λ:=true]>A), I. rewrite /to_alftUR fmap_insert; iFrame.\n    iApply (@big_sepS_impl with \"[$Hinv]\").\n    iModIntro. rewrite /lft_inv. iIntros (κ ?) \"[[Hκ %]|[Hκ %]]\".\n    - iLeft. iFrame \"Hκ\". iPureIntro. by apply lft_alive_in_insert.\n    - iRight. iFrame \"Hκ\". iPureIntro. by apply lft_dead_in_insert. }\n  iModIntro; iExists Λ.\n  rewrite {1}/lft_tok big_sepMS_singleton. iSplit; first done. iFrame \"HΛ\".\n  clear I A HΛ. iIntros \"!> HΛ\".\n  iApply (step_fupd_mask_mono (↑lftN ∪ userE) _ ((↑lftN ∪ userE)∖↑mgmtN)); [solve_ndisj..|].\n  iInv mgmtN as (A I) \"(>HA & >HI & Hinv)\" \"Hclose\".\n  rewrite /lft_tok big_sepMS_singleton.\n  iDestruct (own_valid_2 with \"HA HΛ\")\n    as %[[s [?%leibniz_equiv ?]]%singleton_included_l _]%auth_both_valid_discrete.\n  iMod (own_update_2 with \"HA HΛ\") as \"[HA HΛ]\".\n  { by eapply auth_update, singleton_local_update,\n      (exclusive_local_update _ (Cinr ())). }\n  iDestruct \"HΛ\" as \"#HΛ\". iModIntro; iNext.\n  pose (K := kill_set I Λ).\n  pose (K' := filter (lft_alive_in A) (dom I) ∖ K).\n  destruct (proj1 (subseteq_disjoint_union_L (K ∪ K') (dom I))) as (K''&HI&HK'').\n  { set_solver+. }\n  assert (K ## K') by set_solver+.\n  rewrite HI !big_sepS_union //. iDestruct \"Hinv\" as \"[[HinvK HinvD] Hinv]\".\n  iAssert ([∗ set] κ ∈ K', lft_inv_alive κ)%I with \"[HinvD]\" as \"HinvD\".\n  { iApply (@big_sepS_impl with \"[$HinvD]\"); iIntros \"!>\".\n    iIntros (κ [[Hκ _]%elem_of_filter _]%elem_of_difference) \"?\".\n    by iApply lft_inv_alive_in. }\n  iAssert ([∗ set] κ ∈ K, lft_inv A κ ∗ [† κ])%I with \"[HinvK]\" as \"HinvK\".\n  { iApply (@big_sepS_impl with \"[$HinvK]\"); iIntros \"!>\".\n    iIntros (κ [? _]%elem_of_kill_set) \"$\". rewrite /lft_dead. eauto. }\n  iApply fupd_trans.\n  iApply (fupd_mask_mono (userE ∪ ↑borN ∪ ↑inhN)); first solve_ndisj.\n  iMod (lfts_kill A I K K' with \"[$HI $HinvD] HinvK\") as \"[[HI HinvD] HinvK]\".\n  { done. }\n  { intros κ κ' [??]%elem_of_kill_set ??. apply elem_of_kill_set.\n    split; last done. by eapply gmultiset_elem_of_subseteq. }\n  { intros κ ???. rewrite elem_of_difference elem_of_filter elem_of_dom. auto. }\n  iModIntro. iMod (\"Hclose\" with \"[-]\") as \"_\"; last first.\n  { iModIntro. rewrite /lft_dead. iExists Λ.\n    rewrite gmultiset_elem_of_singleton. auto. }\n  iNext. iExists (<[Λ:=false]>A), I.\n  rewrite /own_alft_auth /to_alftUR fmap_insert. iFrame \"HA HI\".\n  rewrite HI !big_sepS_union //.\n  iSplitL \"HinvK HinvD\"; first iSplitL \"HinvK\".\n  - iApply (@big_sepS_impl with \"[$HinvK]\"); iIntros \"!>\".\n    iIntros (κ [? _]%elem_of_kill_set) \"Hdead\". rewrite /lft_inv.\n    iRight. iFrame. iPureIntro. by apply lft_dead_in_insert_false'.\n  - iApply (@big_sepS_impl with \"[$HinvD]\"); iIntros \"!>\".\n    iIntros (κ [[Hκ HκI]%elem_of_filter HκK]%elem_of_difference) \"Halive\".\n    rewrite /lft_inv. iLeft. iFrame \"Halive\". iPureIntro.\n    apply lft_alive_in_insert_false; last done.\n    move: HκK. rewrite elem_of_kill_set -(elem_of_dom (D:=gset lft)). set_solver +HκI.\n  - iApply (@big_sepS_impl with \"[$Hinv]\"); iIntros \"!>\".\n    rewrite /lft_inv. iIntros (κ Hκ) \"[[? %]|[? %]]\".\n    + iLeft. iFrame. iPureIntro.\n      apply lft_alive_in_insert_false; last done. intros ?.\n      assert (κ ∈ K) by (rewrite elem_of_kill_set -(elem_of_dom (D:=gset lft)) HI elem_of_union; auto).\n      eapply HK'', Hκ. rewrite elem_of_union. auto.\n    + iRight. iFrame. iPureIntro. by apply lft_dead_in_insert_false.\nQed.\nEnd creation.\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/lifetime/model/creation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.25018522894086587}}
{"text": "From iris.proofmode Require Import tactics.\nFrom iris.program_logic Require Export weakestpre.\nFrom iris.heap_lang Require Export lang.\nFrom iris.heap_lang Require Import proofmode notation.\nSet Default Proof Using \"Type\".\n\nFixpoint val_of_list (vs : list (val * val)) : val :=\n  match vs with\n  | []          => #()\n  | (_, v) :: _ => v\n  end.\n\n(** Specification for one-shot prophecy variables. *)\n\nSection one_shot.\n  Context `{!heapG Σ}.\n\n  Definition proph1 (p : proph_id) (v : val) :=\n    (∃ vs, proph p vs ∗ ⌜match vs with [] => True | (_,w) :: _ => v = w end⌝)%I.\n\n  Lemma proph1_exclusive (p : proph_id) (v1 v2 : val) :\n    proph1 p v1 -∗ proph1 p v2 -∗ False.\n  Proof.\n    iIntros \"H1 H2\".\n    iDestruct \"H1\" as (vs1) \"[Hp1 _]\".\n    iDestruct \"H2\" as (vs2) \"[Hp2 _]\".\n    iApply (proph_exclusive with \"Hp1 Hp2\").\n  Qed.\n\n  Lemma wp_new_proph1 s E :\n    {{{ True }}}\n      NewProph @ s; E\n    {{{ p v, RET (LitV (LitProphecy p)); proph1 p v }}}.\n  Proof.\n    iIntros (Φ) \"_ HΦ\". wp_apply wp_new_proph; first done.\n    iIntros (vs p) \"Hp\". iApply (\"HΦ\" $! p (val_of_list vs)).\n    iExists _. iFrame \"Hp\". iPureIntro. by case vs as [|[v w] vs].\n  Qed.\n\n  Lemma wp_resolve1 s E e Φ (p : proph_id) (v w : val) :\n    Atomic StronglyAtomic e →\n    to_val e = None →\n    proph1 p v -∗\n    WP e @ s; E {{ r, ⌜v = w⌝ -∗ Φ r }} -∗\n    WP Resolve e (Val $ LitV $ LitProphecy p) (Val w) @ s; E {{ Φ }}.\n  Proof.\n    iIntros (A He) \"Hp Wpe\". iDestruct \"Hp\" as (vs) \"[Hp HEq]\".\n    iDestruct \"HEq\" as %HEq. wp_apply (wp_resolve with \"Hp\"); try done.\n    iApply wp_mono; last done. iIntros (v0) \"H\". iIntros (pvs ->) \"Hp\".\n    by iApply \"H\".\n  Qed.\nEnd one_shot.\n\n(** Alternative specification. *)\n\nSection one_shot'.\n  Context `{!heapG Σ}.\n\n  Definition proph1' (p : proph_id) (v : val) :=\n    (∃ vs, proph p vs ∗ ⌜val_of_list vs = v⌝)%I.\n\n  Lemma proph1'_exclusive (p : proph_id) (v1 v2 : val) :\n    proph1' p v1 -∗ proph1' p v2 -∗ False.\n  Proof.\n    iIntros \"H1 H2\".\n    iDestruct \"H1\" as (vs1) \"[Hp1 _]\".\n    iDestruct \"H2\" as (vs2) \"[Hp2 _]\".\n    iApply (proph_exclusive with \"Hp1 Hp2\").\n  Qed.\n\n  Lemma wp_new_proph1' s E :\n    {{{ True }}}\n      NewProph @ s; E\n    {{{ p v, RET (LitV (LitProphecy p)); proph1' p v }}}.\n  Proof.\n    iIntros (Φ) \"_ HΦ\". wp_apply wp_new_proph; first done.\n    iIntros (pvs p) \"Hp\". iApply \"HΦ\". iExists _. by iFrame.\n  Qed.\n\n  Lemma wp_resolve1' s E e Φ (p : proph_id) (v w : val) :\n    Atomic StronglyAtomic e →\n    to_val e = None →\n    proph1' p v -∗\n    WP e @ s; E {{ r, ⌜v = w⌝ -∗ Φ r }} -∗\n    WP Resolve e (Val $ LitV $ LitProphecy p) (Val w) @ s; E {{ Φ }}.\n  Proof.\n    iIntros (A He) \"Hp Wpe\". iDestruct \"Hp\" as (vs) \"[Hp <-]\".\n    wp_apply (wp_resolve with \"Hp\"); try done. iApply wp_mono; last done.\n    iIntros (v) \"H\". iIntros (pvs ->) \"Hp\". by iApply \"H\".\n  Qed.\nEnd one_shot'.\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/proph/lib/one_shot_proph.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.250045989405625}}
{"text": "Require Import String.\nRequire Import Ascii.\nRequire Import Arith.\nRequire Import additional_tools.\n\n\nLocal Open Scope string_scope.\n\n(* -------------------------------\n   ------Basics-------------------\n   -------------------------------*)\n(* \n   This function takes in two strings, sub and s.\n   it looks to see if sub is a substring of s,\n   if sub is a substring of s then it returns the\n   index of the substring otherwise it will return \n   the length of the string s.\n\n   This function ASSUMES that sub is not a the EmptyString,\n     if sub is the EmptyString then length s will be the \n     desired ansewer.\n*)\nFixpoint indexOfSubstring (sub s: string): nat :=\n  if (prefix sub s)\n  then 0\n  else match s with\n         | EmptyString => 0\n         | String a s' => S (indexOfSubstring sub s')\n       end.\n\n(*\n    This function takes in a string, s, and\n    returns the string with trailing white\n    space removed.\n\n    White space is definied as either a 'space'\n    or a 'new line'\n*)\nFixpoint removeTrailingWhiteSpace (s: string) (n: nat): string := \n  let lastChar := option2ascii (get n s) in\n    match n with\n      | 0 => EmptyString\n      | S n' => if (beq_ascii lastChar \" \")\n                then removeTrailingWhiteSpace (substring 0 n s) n'\n                else if (beq_ascii lastChar \"\n\")\n                     then removeTrailingWhiteSpace (substring 0 n s) n'\n                     else s\n    end.\n\n\n\n(*\n    This function takes in a string, s, and\n    returns the string with leading white\n    space removed.\n\n    White space is definied as either a 'space'\n    or a 'new line'\n*)\nFixpoint removeLeadingWhiteSpace (s: string): string := \n  match s with\n    | String \" \" s1 => removeLeadingWhiteSpace s1\n    | String \"\n\" s2 => removeLeadingWhiteSpace s2\n    | s' => s'\n  end.\n\n(*\n    This function takes in a string, s, and\n    returns the string with leading and trailing\n    white space removed.\n\n    White space is defined as either a 'space'\n    or a 'new line'.\n*)\nDefinition trimWhiteSpace (s: string): string :=\n  removeLeadingWhiteSpace (removeTrailingWhiteSpace s ((length s) - 1)).\n\n\n(* ------ tests -------- *)\nCompute prefix \"bob\" \"bobby\". (*returns true*)\nCompute prefix \"bobby\" \"bob\". (*returns false*)\nCompute removeLeadingWhiteSpace \" \n  sup\". (* should return \"sup\"*)\nCompute option2ascii (get 2 \"sup\"). (*should return \"p\"*)\nCompute removeTrailingWhiteSpace \"sup  \n  \" 7. (*should return \"sup\"*)\nCompute trimWhiteSpace \"  \n sup \n \". (*should return \"sup\"*)\n\n(* -------------------------------\n   ------Recipe Name--------------\n   -------------------------------*)\n\n(*\n   This function takes in a string, s, and returns\n   the index of the name of the recipe. If s has no\n   recognizable name, then the function will return 0.\n*)\nDefinition getNameIndex (s: string): nat :=\n  let x := \"itemprop=\"\"name\"\">\" in\n    let index := indexOfSubstring x s in\n      if (beq_nat index (length s))\n      then 0 \n      else plus index 16 \n(*16 is the lenth of x, thus the name starts 16 spaces from the begining of x*).\n\n(*\n    This function takes in a string, s, and returns\n    the length of the name in the string s.\n*)\nDefinition getNameLength (s: string): nat := \n  let startIndex := getNameIndex s in\n    let post := substring startIndex ((length s) - startIndex) s in \n      indexOfSubstring \"<\" post.\n\n(*\n    This function takes in a string, s, and returns\n    the name held within that string. If no name exists\n    within the string then it returns the EmptyString.\n*)\nDefinition getName (s: string): string :=\n  let start_index := getNameIndex s in\n    let name_length := getNameLength s in\n      if (beq_nat start_index 0)\n      then EmptyString\n      else trimWhiteSpace (substring start_index name_length s).\n\n(* ------ tests -------- *)\nCompute getNameIndex \"sup\". (*Should return 0*)\nExample bChicken : string := \"<h1 class=\"\"fn\"\" itemprop=\"\"name\"\">Bourbon Chicken</h1>\".\nExample ssfChicken : string := \n        \"<div class=\"\"leady-hd rz-rec clrfix\"\">\n            <span class=\"\"item\"\">\n                <h1 class=\"\"fn\"\" itemprop=\"\"name\"\">Savory Southern Fried Chicken</h1>\n            </span>\n            ...\n        </div>\".\nCompute getNameIndex bChicken. (*should return 31*)\nCompute getNameLength bChicken. (*should return 15*)\nCompute getName bChicken. (*should return Bourbon Chicken*)\nCompute getName ssfChicken. (*should return Savory Southern Fried Chicken*)\nCompute getName \"sup<\". (*should be EmptyString*)\n\n\n(* -------------------------------\n   ------Recipe Ingredients-------\n   -------------------------------*)\n\n\n(*\n    This function takes in a string, s, and outputs\n    the first index where an instance of an ingredient\n    appears, the index which is returned is the index \n    after \"<span class=\"\"name\"\">\" and thus has\n    a minimum value of 25, thus, if no instance of\n    the above string is found, then the function will\n    output 0.\n*)\nDefinition getIngredientIndex (s: string): nat:=\n  let x := \"<span class=\"\"name\"\">\" in\n    let index := indexOfSubstring x s in\n      if (beq_nat index (length s))\n      then 0\n      else plus index 19\n(*19 is the length of x, thus the ingredient starts 19 spaces from the begining of x*).\n\n\n(*\n    This function takes in a string, s, and returns\n    all characters in the string s that occur after\n    the first instance of \"<span class=\"\"name\"\">\"\n    within that string. If no such instance exists\n    it returns the empty string.\n*)\nDefinition getPostIngredientSpan (s: string): string:=\n  let start := getIngredientIndex s in\n    let post_length := minus (length s) start in\n      let output := substring start post_length s in\n        if (beq_nat (length output) (length s))\n        then EmptyString\n        else output.\n\n(*\n    This function takes in a string, s, and returns\n    the first instance of a close tag of type </a>\n    or of type </span>. This helps us to find the \n    end index of an ingredient.\n*)\nDefinition getIngredientEndIndex (s: string): nat :=\n  let candidate_a := indexOfSubstring \"</a>\" s in\n    let candidate_span := indexOfSubstring \"</span>\" s in\n      if (blt_nat candidate_a candidate_span)\n      then candidate_a\n      else candidate_span.\n\n(*\n   This function takes in a string, s, and \n   returns true if the first instance of an\n   </a> close tag in s appears before the \n   first instance of a </span> close tag\n   in s. This is used to determine if a \n   given ingredient includes a link or not   \n*)\nDefinition includesLink (s: string): bool :=\n  let candidate_a := indexOfSubstring \"</a>\" s in\n    let end_index := getIngredientEndIndex s in\n      if (beq_nat candidate_a end_index)\n      then true\n      else false.\n\n(*\n    This function takes in a string, s, and returns\n    the first instance of an ingredient.\n    \n    If no ingredient is found it will return the \n    EmptyString.\n\n    This function assumes all ingredients have \n    associated <a></a> tags as wrappers\n*)\nDefinition getNextIngredient (s: string): string:=\n  let post := getPostIngredientSpan s in\n    let start_index := if (includesLink post)\n                       then (indexOfSubstring \">\" post) + 1 \n                       else 0 \n                       in \n      let end_index := getIngredientEndIndex post in\n        let ingredient_length := end_index - start_index in\n          trimWhiteSpace (substring start_index ingredient_length post).\n\n(*\n    This function takes in a string, s, and a nat, n,\n    and returns the list of ingredients. This function\n    uses n as its decreasing argument for a proof of\n    termination. n should be the length of the string\n    it is assumed that n is greater than or equal to\n    the number of ingredients in s.\n*)\nFixpoint getIngredientsInternal (s: string) (n: nat): list string := (*n is used to show termination*)\n  match n with\n    | 0 => nil\n    | S n' =>\n        match getNextIngredient s with\n          | EmptyString => nil\n          | s' => let start_index := (indexOfSubstring s' s) + (length s') in\n                    let post_length := (length s) - start_index in\n                      let post := substring start_index post_length s in\n                        cons s' (getIngredientsInternal post n')\n        end\n  end.\n(*\n    This function takes in a string, s, and returns\n    the list of ingredients found within s. if no\n    ingredients are present in s, then it returns\n    the empty list, nil.\n*)\nDefinition getIngredients (s: string): list string :=\n  getIngredientsInternal s (length s).\n\n\n(* ------ tests -------- *)\nExample ssfChicken2: string := \n        \"<li class=\"\"ingredient\"\" itemprop=\"\"ingredients\"\">\n            <span class=\"\"ingredient\"\">\n                <span class=\"\"amount\"\">\n                    <span class=\"\"value\"\">2 </span>\n                    <span class=\"\"type\"\">quarts</span>\n                </span>\n                <span class=\"\"name\"\">\n                    <a href=\"\"http://www.sitename.com/directory/subdirectory-12\"\">cold water</a>\n                </span>\n            </span>\n        </li>\n        <li class=\"\"ingredient\"\" itemprop=\"\"ingredients\"\">\n            <span =\"\"ingredient\"\">\n                <span class=\"\"amount\"\">\n                    <span class=\"\"value\"\">2 </span>\n                    <span class=\"\"type\"\">tablespoons</span>\n                </span>\n                <span class=\"\"name\"\">\n                    <a href=\"\"http://www.sitename.com/directory/subdirectory-33\"\">fine sea salt</a>\n                </span>\n            </span>\n        </li>\".\nCompute getIngredientIndex ssfChicken2. (*should return 285*)\nCompute getIngredientIndex \"sup\". (*should return 0*)\nCompute getPostIngredientSpan ssfChicken2. (*should start with \"<a href=...\" and include both cold water and fine sea salt*) \nCompute getPostIngredientSpan \"sup\". (*should return the EmptyString*)\nCompute getNextIngredient ssfChicken2. (*should return \"cold water\"*)\nCompute getNextIngredient \"sup\". (*should return the EmptyString*)\nCompute getIngredients ssfChicken2. (*should return [\"cold water\"; \"fine sea salt\"; nil]*)\nCompute getIngredients \"sup</a>\". (*should return [nil]*)\nExample bChicken2: string := \"<li class=\"\"ingredient\"\"  itemprop=\"\"ingredients\"\">\n                            <span class=\"\"ingredient\"\"><span class=\"\"amount\"\"><span class=\"\"value\"\">1/4</span> <span class=\"\"type\"\">cup</span></span> \n                            <span class=\"\"name\"\">\n                            apple juice\n                            </span>\n                            </span>\n                            </li>\n                            <li class=\"\"ingredient\"\"  itemprop=\"\"ingredients\"\">\n                            <span class=\"\"ingredient\"\"><span class=\"\"amount\"\"><span class=\"\"value\"\">1/3</span> <span class=\"\"type\"\">cup</span></span> \n                            <span class=\"\"name\"\">\n                                <a href=\"\"http://www.food.com/library/brown-sugar-375\"\">light brown sugar</a>\n                            </span>\n                            </span>\n                            </li>\".\nCompute getNextIngredient bChicken2. (*should be \"apple juice\", however leading and trailing whitespace is included*)\nCompute getIngredients bChicken2. (*should be [apple juice; light brown sugar; nil], however it includes additional leading whitespace*)\n\n\n(* -------------------------------\n   ------Recipe Instructions------\n   -------------------------------*)\n\n(*\n   This function takes in a string, s, and returns\n   the index of the first instruction of the recipe.\n   If s has no recognizable instructions, then the\n   function will return 0.\n*)\nDefinition getInstructionIndex (s: string): nat := \n  let x := \"div class=\"\"txt\"\">\" in\n    let index := indexOfSubstring x s in\n      if (beq_nat index (length s))\n      then 0\n      else index + 16\n(*16 is the length of x, thus the ingredient starts 16 spaces from the begining of x*).\n\n(*\n    This function takes in a string, s, and returns\n    the length of the first instruction in the string s.\n*)\nDefinition getInstructionLength (s: string): nat :=\n  let start_index := getInstructionIndex s in\n    let post_length := (length s) - start_index in\n      let post := substring start_index post_length s in\n        indexOfSubstring \"</div>\" post.\n\n(*\n    This function takes in a string, s, and returns\n    the first instance of an instruction.\n    \n    If no instruction is found it will return the \n    EmptyString.\n\n    This function assumes all instructions have \n    associated <div></div> tags as wrappers\n*)\nDefinition getNextInstruction (s: string): string :=\n  let start_index := getInstructionIndex s in\n    let instruction_length := getInstructionLength s in\n      let instruction := substring start_index instruction_length s in\n        if (beq_nat start_index 0)\n        then EmptyString\n        else trimWhiteSpace instruction.\n(*\n    This function takes in a string, s, and a nat, n,\n    and returns the list of instructions. This function\n    uses n as its decreasing argument for a proof of\n    termination. n should be the length of the string\n    it is assumed that n is greater than or equal to\n    the number of instructions in s.\n*)\nFixpoint getInstructionsInternal (s: string) (n: nat): list string := \n  match n with\n    | 0 => nil\n    | S n' => match getNextInstruction s with\n                | EmptyString => nil\n                | s' => let start_index := (indexOfSubstring s' s) + (length s') in\n                          let post_length := (length s) - start_index in\n                            let post := substring start_index post_length s in\n                              cons s' (getInstructionsInternal post n')\n              end\n  end.\n\n(*\n    This function takes in a string, s, and returns\n    the list of instructions found within s. if no\n    ingredients are present in s, then it returns\n    the empty list, nil.\n*)\nDefinition getInstructions (s: string): list string := \n  getInstructionsInternal s (length s).\n\n\nExample ssfChicken3 := \n\"<div class=\"\"pod directions\"\">\n\t<h2>Directions:</h2>\n\t<span class=\"\"instructions\"\"  itemprop=\"\"recipeInstructions\"\">\n\t<ol>\n\t\t\t<li><div class=\"\"num\"\">1</div> <div class=\"\"txt\"\">Editor's Note:  Named Bourbon Chicken because it was supposedly created by a Chinese cook who worked in a restaurant on Bourbon Street.</div></li>\n\t\t\t<li><div class=\"\"num\"\">2</div> <div class=\"\"txt\"\">Heat oil in a large skillet.</div></li>\n\t\t\t<li><div class=\"\"num\"\">3</div> <div class=\"\"txt\"\">Add chicken pieces and cook until lightly browned.</div></li>\n\t\t\t<li><div class=\"\"num\"\">4</div> <div class=\"\"txt\"\">Remove chicken.</div></li>\n\t\t\t<li><div class=\"\"num\"\">5</div> <div class=\"\"txt\"\">Add remaining ingredients, heating over medium Heat until well mixed and dissolved.</div></li>\n\t\t\t<li><div class=\"\"num\"\">6</div> <div class=\"\"txt\"\">Add chicken and bring to a hard boil.</div></li>\n\t\t\t<li><div class=\"\"num\"\">7</div> <div class=\"\"txt\"\">Reduce heat and simmer for 20 minutes.</div></li>\n\t\t\t<li><div class=\"\"num\"\">8</div> <div class=\"\"txt\"\">Serve over hot rice and ENJOY.</div></li>\n\t</ol>\n\t</span>\t\t\n</div>\".\n\nCompute getInstructions ssfChicken3. (*should return [\"Editor's Note:...\";...;\"...and ENJOY.\";nil]*)\nCompute getInstructions \"sup</div>\". (*should return [nil]*)\n", "meta": {"author": "ChrisEarman", "repo": "menumerations", "sha": "b98a3b677b9d31a94c975fee1cac1f880dae48a5", "save_path": "github-repos/coq/ChrisEarman-menumerations", "path": "github-repos/coq/ChrisEarman-menumerations/menumerations-b98a3b677b9d31a94c975fee1cac1f880dae48a5/html_parser.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.43014734858584297, "lm_q1q2_score": 0.2500459831654073}}
{"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.EricTact.\n\n\nRequire Import oeuf.HList.\n\nRequire oeuf.SourceValues.\nRequire oeuf.HighestValues.\nRequire oeuf.HigherValue.\nRequire oeuf.HighValues.\n\nRequire Import oeuf.OpaqueTypes.\n\nClose Scope Z.\n\n\n(* UntypedComp1 *)\n\nDefinition compile_member {A : Type} {x : A} {l} :=\n    let fix go {x l} (mb : member x l)  :=\n        match mb with\n        | Here => 0\n        | There mb' => S (go mb')\n        end in @go x l.\n\nDefinition compile_highest {G ty} :=\n    let fix go {ty} (v : SourceValues.value G ty) :=\n        let fix go_list {tys} (vs : hlist (SourceValues.value G) tys) :=\n            match vs with\n            | hnil => []\n            | hcons v vs => go v :: go_list vs\n            end in\n        match v with\n        | @SourceValues.VConstr _ _ ctor _ _ args =>\n                HighestValues.Constr ctor (go_list args)\n        | @SourceValues.VClose _ _ _ _ mb free =>\n                HighestValues.Close (compile_member mb) (go_list free)\n        | @SourceValues.VOpaque _ _ v =>\n                HighestValues.Opaque _ v\n        end in @go ty.\n\nDefinition compile_highest_list {G tys} :=\n    let go {ty} := @compile_highest G ty in\n    let fix go_list {tys} (vs : hlist (SourceValues.value G) tys) :=\n        match vs with\n        | hnil => []\n        | hcons v vs => go v :: go_list vs\n        end in @go_list tys.\n\n\n\n(* TaggedComp *)\n\nInductive mv_higher : HighestValues.value -> HigherValue.value -> Prop :=\n| HrConstr : forall ctor aargs tag bargs,\n        Utopia.constructor_index ctor = tag ->\n        Forall2 mv_higher aargs bargs ->\n        mv_higher (HighestValues.Constr ctor aargs)\n                  (HigherValue.Constr tag bargs)\n| HrClose : forall fname aargs bargs,\n        Forall2 mv_higher aargs bargs ->\n        mv_higher (HighestValues.Close fname aargs)\n                  (HigherValue.Close fname bargs)\n| HrOpaque : forall oty ov,\n        mv_higher (HighestValues.Opaque oty ov)\n                  (HigherValue.Opaque oty ov)\n.\n\n\n(* FlatIntTagComp *)\n\nInductive mv_high : HigherValue.value -> HighValues.value -> Prop :=\n| HgConstr : forall atag aargs btag bargs,\n        Z.of_nat atag = Int.unsigned btag ->\n        Forall2 mv_high aargs bargs ->\n        mv_high (HigherValue.Constr atag aargs)\n                (HighValues.Constr btag bargs)\n| HgClose : forall afname afree bfname bfree,\n        Pos.of_succ_nat afname = bfname ->\n        Forall2 mv_high afree bfree ->\n        mv_high (HigherValue.Close afname afree)\n                (HighValues.Close bfname bfree)\n| HgOpaque : forall oty ov,\n        mv_high (HigherValue.Opaque oty ov)\n                (HighValues.Opaque oty ov)\n.\n\n\n(* FmajorComp *)\n\nInductive id_key :=\n| IkArg\n| IkSelf\n| IkSwitchTarget\n| IkVar (l : nat)\n| IkFunc (fname : nat)\n| IkRuntime (name : String.string)\n| IkMalloc\n| IkScratch (n : nat)\n.\n\nDefinition id_key_eq_dec (a b : id_key) : { a = b } + { a <> b }.\ndecide equality; eauto using eq_nat_dec, String.string_dec.\nDefined.\n\nDefinition id_key_assoc {V} := assoc id_key_eq_dec (V := V).\n\nDefinition id_map := list (id_key * ident).\n\nDefinition I_id (M : id_map) k i := id_key_assoc M k = Some i.\nHint Unfold I_id.\n\n\nInductive mv_fmajor (M : id_map) : HighValues.value -> HighValues.value -> Prop :=\n| FmConstr : forall tag aargs bargs,\n        Forall2 (mv_fmajor M) aargs bargs ->\n        mv_fmajor M (HighValues.Constr tag aargs)\n                    (HighValues.Constr tag bargs)\n| FmClose : forall afname afree bfname bfree,\n        I_id M (IkFunc (pred (Pos.to_nat afname))) bfname ->\n        Forall2 (mv_fmajor M) afree bfree ->\n        mv_fmajor M (HighValues.Close afname afree)\n                    (HighValues.Close bfname bfree)\n| FmOpaque : forall oty ov,\n        mv_fmajor M (HighValues.Opaque oty ov)\n                    (HighValues.Opaque oty ov)\n.\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/MatchValues.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.25004598316540727}}
{"text": "Require Import VerdiRaft.Raft.\nRequire Import VerdiRaft.CommonTheorems.\n\nRequire Import VerdiRaft.TermSanityInterface.\n\nSection TermSanityProof.\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\n  Theorem no_entries_past_current_term_nw_packets_unchanged :\n    forall net ps' st',\n      no_entries_past_current_term_nw net ->\n      (forall p, In p ps' -> In p (nwPackets net) \\/ False) ->\n      no_entries_past_current_term_nw (mkNetwork ps' st').\n  Proof using. \n    unfold no_entries_past_current_term_nw in *. intros.\n    simpl in *. find_apply_hyp_hyp. intuition eauto.\n  Qed.\n\n  Theorem no_entries_past_current_term_nw_only_new_packets_matter :\n    forall net ps' l st',\n      no_entries_past_current_term_nw net ->\n      (forall p, In p ps' -> In p (nwPackets net) \\/ In p l) ->\n      no_entries_past_current_term_nw (mkNetwork l st') ->\n      no_entries_past_current_term_nw (mkNetwork ps' st').\n  Proof using. \n    unfold no_entries_past_current_term_nw. intros. simpl in *.\n    find_apply_hyp_hyp. intuition eauto.\n  Qed.\n\n  Theorem no_entries_past_current_term_nw_no_append_entries :\n    forall net ps' h l st',\n      no_entries_past_current_term_nw net ->\n      (forall p, In p ps' -> In p (nwPackets net) \\/ In p (send_packets h l)) ->\n      (forall m, In m l -> ~ is_append_entries (snd m)) ->\n      no_entries_past_current_term_nw (mkNetwork ps' st').\n  Proof using. \n    intros. eapply no_entries_past_current_term_nw_only_new_packets_matter; eauto.\n    unfold no_entries_past_current_term_nw. intros. simpl in *.\n    do_in_map. subst. simpl in *.\n    find_apply_hyp_hyp.\n    exfalso. match goal with H : _ |- _ => apply H end.\n    repeat eexists; eauto.\n  Qed.\n\n  Theorem no_entries_past_current_term_nw_not_append_entries :\n    forall net ps' p' st',\n      no_entries_past_current_term_nw net ->\n      (forall p, In p ps' -> In p (nwPackets net) \\/ p = p') ->\n      ~ is_append_entries (pBody p') ->\n      no_entries_past_current_term_nw (mkNetwork ps' st').\n  Proof using. \n    intros.\n    unfold no_entries_past_current_term_nw. intros. simpl in *. find_apply_hyp_hyp.\n    intuition.\n    - unfold no_entries_past_current_term_nw in *. eauto.\n    - subst. exfalso. match goal with H : _ |- _ => apply H end.\n      repeat eexists; eauto.\n  Qed.\n\n  Theorem no_entries_past_current_term_init :\n    raft_net_invariant_init (no_entries_past_current_term).\n  Proof using. \n    unfold raft_net_invariant_init, no_entries_past_current_term.\n    intuition.\n    - unfold no_entries_past_current_term_host.\n      intros. simpl in *. intuition.\n    - unfold no_entries_past_current_term_nw.\n      intros. simpl in *. intuition.\n  Qed.\n\n  Lemma doLeader_spec :\n    forall h st os st' ps,\n      doLeader st h = (os, st', ps) ->\n      log st' = log st /\\ currentTerm st' = currentTerm st.\n  Proof using. \n    intros. unfold doLeader in *.\n    repeat break_match; find_inversion; subst; auto.\n  Qed.\n\n  Theorem no_entries_past_current_term_do_leader :\n    raft_net_invariant_do_leader (no_entries_past_current_term).\n  Proof using. \n    unfold raft_net_invariant_do_leader, no_entries_past_current_term.\n    intuition.\n    - unfold no_entries_past_current_term_host in *.\n      intros. simpl in *.\n      find_apply_lem_hyp doLeader_spec.\n      find_higher_order_rewrite.\n      break_if;\n        subst; intuition;\n        repeat find_rewrite;\n        eauto.\n    - unfold no_entries_past_current_term_nw in *. intros; simpl in *.\n      find_apply_hyp_hyp. intuition eauto.\n      unfold doLeader in *.\n      repeat break_match; repeat find_inversion; try solve_by_inversion.\n      repeat do_in_map; subst; simpl in *; find_inversion.\n      find_apply_lem_hyp findGtIndex_in. eauto.\n  Qed.\n\n  Lemma doGenericServer_spec :\n    forall h d os d' ms,\n      doGenericServer h d = (os, d', ms) ->\n      (log d' = log d /\\ currentTerm d' = currentTerm d /\\\n       (forall m, In m ms -> ~ is_append_entries (snd m))).\n  Proof using. \n    intros. unfold doGenericServer in *.\n    repeat break_match; find_inversion; subst; intuition;\n    use_applyEntries_spec; subst; simpl in *; auto.\n  Qed.\n\n  Lemma no_entries_past_current_term_do_generic_server :\n    raft_net_invariant_do_generic_server no_entries_past_current_term.\n  Proof using. \n    unfold raft_net_invariant_do_generic_server, no_entries_past_current_term. intros.\n    find_apply_lem_hyp doGenericServer_spec. intuition.\n    - unfold no_entries_past_current_term_host in *.\n      intros. simpl in *.\n      find_higher_order_rewrite; break_match; eauto.\n      subst; repeat find_rewrite; eauto.\n    - eauto using no_entries_past_current_term_nw_no_append_entries.\n  Qed.\n\n\n  Lemma handleClientRequest_messages :\n    forall h d client id c os d' ms,\n      handleClientRequest h d client id c = (os, d', ms) ->\n      (forall m, In m ms -> ~ is_append_entries (snd m)).\n  Proof using. \n    intros. unfold handleClientRequest in *.\n    break_match; find_inversion; subst; intuition.\n  Qed.\n\n  Lemma no_entries_past_current_term_client_request :\n    raft_net_invariant_client_request (no_entries_past_current_term).\n  Proof using. \n    unfold raft_net_invariant_client_request, no_entries_past_current_term.\n    intuition.\n    - unfold no_entries_past_current_term_host in *.\n      intros. simpl in *.\n      find_higher_order_rewrite; break_if; eauto.\n      unfold handleClientRequest in *.\n      subst.\n      break_match; find_inversion; eauto.\n      simpl in *. intuition. subst; simpl in *; auto.\n    - eauto using no_entries_past_current_term_nw_no_append_entries,\n                  handleClientRequest_messages.\n  Qed.\n\n\n  Lemma handleTimeout_spec :\n    forall h d os d' ms,\n      handleTimeout h d = (os, d', ms) ->\n      log d' = log d /\\ currentTerm d <= currentTerm d' /\\\n      ( forall m, In m ms -> ~ is_append_entries (snd m)).\n  Proof using. \n    intros. unfold handleTimeout, tryToBecomeLeader in *.\n    repeat break_match; find_inversion; subst; intuition;\n    do_in_map; subst; simpl in *; congruence.\n  Qed.\n\n  Lemma no_entries_past_current_term_timeout :\n    raft_net_invariant_timeout no_entries_past_current_term.\n  Proof using. \n    unfold raft_net_invariant_timeout, no_entries_past_current_term.\n    intros. find_apply_lem_hyp handleTimeout_spec.\n    intuition.\n    - unfold no_entries_past_current_term_host in *.\n      intros. simpl in *.\n      find_higher_order_rewrite; break_if; eauto.\n      subst; repeat find_rewrite.\n      eapply Nat.le_trans; [|eauto]; eauto.\n    - eauto using no_entries_past_current_term_nw_no_append_entries.\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 using. \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  Lemma no_entries_past_current_term_append_entries :\n    raft_net_invariant_append_entries no_entries_past_current_term.\n  Proof using. \n    unfold raft_net_invariant_append_entries, no_entries_past_current_term.\n    intros. find_apply_lem_hyp handleAppendEntries_spec.\n    intuition.\n    - unfold no_entries_past_current_term_host in *.\n      intros. simpl in *. find_higher_order_rewrite.\n      break_if; eauto. subst.\n      find_apply_hyp_hyp. intuition.\n      + eapply Nat.le_trans; [|eauto]; eauto.\n      + subst.\n        eapply_prop no_entries_past_current_term_nw; eauto.\n    - match goal with\n        | _ : context [{| pSrc := ?ps; pDst := ?pd; pBody := ?pb |}] |- _ =>\n          eapply no_entries_past_current_term_nw_not_append_entries\n          with (p' := {| pSrc := ps; pDst := pd; pBody := pb |})\n      end; eauto.\n     intros. find_apply_hyp_hyp. find_rewrite. in_crush.\n  Qed.\n\n  Lemma no_entries_past_current_term_unaffected :\n    forall net st' ps' xs p ys d ms,\n      nwPackets net = xs ++ p :: ys ->\n      no_entries_past_current_term net ->\n      (forall h : Net.name, st' h = update name_eq_dec (nwState net) (pDst p) d h) ->\n      (forall p' : packet,\n       In p' ps' ->\n       In p' (xs ++ ys) \\/ In p' (send_packets (pDst p) ms)) ->\n      currentTerm (nwState net (pDst p)) <= currentTerm d ->\n      log d = log (nwState net (pDst p)) ->\n      (forall m, In m ms -> ~ is_append_entries (snd m)) ->\n      no_entries_past_current_term {| nwPackets := ps'; nwState := st' |}.\n  Proof using. \n    intros. unfold no_entries_past_current_term in *. intuition.\n    - unfold no_entries_past_current_term_host in *.\n      intros. simpl in *. find_higher_order_rewrite.\n      break_if; eauto. subst.\n      repeat find_rewrite. eapply Nat.le_trans; [|eauto].\n      eauto.\n    - unfold no_entries_past_current_term_nw.\n      intros. simpl in *.\n      find_apply_hyp_hyp. intuition.\n      + intros.\n        match goal with\n          | _ : In ?p _ |- _ =>\n            assert (In p (nwPackets net)) by (find_rewrite; in_crush)\n        end.\n        eapply_prop no_entries_past_current_term_nw; eauto.\n      + exfalso.\n        do_in_map. subst.\n        simpl in *.\n        find_apply_hyp_hyp. find_rewrite. repeat eexists; eauto.\n  Qed.\n\n  Lemma no_entries_past_current_term_unaffected_1 :\n    forall net st' ps' xs p ys d m,\n      nwPackets net = xs ++ p :: ys ->\n      no_entries_past_current_term net ->\n      (forall h : Net.name, st' h = update name_eq_dec (nwState net) (pDst p) d h) ->\n      (forall p' : packet,\n       In p' ps' ->\n       In p' (xs ++ ys) \\/ p' = m) ->\n      currentTerm (nwState net (pDst p)) <= currentTerm d ->\n      log d = log (nwState net (pDst p)) ->\n      ~ is_append_entries (pBody m) ->\n      no_entries_past_current_term {| nwPackets := ps'; nwState := st' |}.\n  Proof using. \n    intros. unfold no_entries_past_current_term in *. intuition.\n    - unfold no_entries_past_current_term_host in *.\n      intros. simpl in *. find_higher_order_rewrite.\n      break_if; eauto. subst.\n      repeat find_rewrite. eapply Nat.le_trans; [|eauto].\n      eauto.\n    - unfold no_entries_past_current_term_nw.\n      intros. simpl in *.\n      find_apply_hyp_hyp. intuition.\n      + intros.\n        match goal with\n          | _ : In ?p _ |- _ =>\n            assert (In p (nwPackets net)) by (find_rewrite; in_crush)\n        end.\n        eapply_prop no_entries_past_current_term_nw; eauto.\n      + exfalso. subst. repeat find_rewrite.\n        forwards; intuition.\n        repeat eexists; eauto.\n  Qed.\n\n  Lemma no_entries_past_current_term_unaffected_0 :\n    forall net st' ps' xs p ys d,\n      nwPackets net = xs ++ p :: ys ->\n      no_entries_past_current_term net ->\n      (forall h : Net.name, st' h = update name_eq_dec (nwState net) (pDst p) d h) ->\n      (forall p' : packet,\n       In p' ps' ->\n       In p' (xs ++ ys)) ->\n      currentTerm (nwState net (pDst p)) <= currentTerm d ->\n      log d = log (nwState net (pDst p)) ->\n      no_entries_past_current_term {| nwPackets := ps'; nwState := st' |}.\n  Proof using. \n    intros. unfold no_entries_past_current_term in *. intuition.\n    - unfold no_entries_past_current_term_host in *.\n      intros. simpl in *. find_higher_order_rewrite.\n      break_if; eauto. subst.\n      repeat find_rewrite. eapply Nat.le_trans; [|eauto].\n      eauto.\n    - unfold no_entries_past_current_term_nw.\n      intros. simpl in *.\n      find_apply_hyp_hyp.\n      match goal with\n        | _ : In ?p _ |- _ =>\n          assert (In p (nwPackets net)) by (find_rewrite; in_crush)\n      end.\n      eapply_prop no_entries_past_current_term_nw; 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       log st' = log st /\\\n       (forall m, In m ms -> ~ is_append_entries (snd m))).\n  Proof using. \n    intros.\n    unfold handleAppendEntriesReply, 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  Lemma no_entries_past_current_term_append_entries_reply :\n    raft_net_invariant_append_entries_reply no_entries_past_current_term.\n  Proof using. \n    unfold raft_net_invariant_append_entries_reply.\n    intros. find_apply_lem_hyp handleAppendEntriesReply_spec.\n    intuition eauto using no_entries_past_current_term_unaffected.\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       log st' = log st /\\\n       ~ is_append_entries m).\n  Proof using. \n    intros.\n    unfold handleRequestVote, 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  Lemma no_entries_past_current_term_request_vote :\n    raft_net_invariant_request_vote no_entries_past_current_term.\n  Proof using. \n    unfold raft_net_invariant_request_vote.\n    intros. find_apply_lem_hyp handleRequestVote_spec.\n    intuition eauto using no_entries_past_current_term_unaffected_1.\n  Qed.\n\n  Lemma handleRequestVoteReply_spec :\n    forall h st h' t v st',\n      handleRequestVoteReply h st h' t v = st' ->\n      (currentTerm st <= currentTerm st' /\\\n       log st' = log st).\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  Lemma no_entries_past_current_term_request_vote_reply :\n    raft_net_invariant_request_vote_reply no_entries_past_current_term.\n  Proof using. \n    unfold raft_net_invariant_request_vote_reply.\n    intros. find_apply_lem_hyp handleRequestVoteReply_spec.\n    intuition eauto using no_entries_past_current_term_unaffected_0.\n  Qed.\n\n  Lemma no_entries_past_current_term_state_same_packet_subset :\n    raft_net_invariant_state_same_packet_subset no_entries_past_current_term.\n  Proof using. \n    unfold raft_net_invariant_state_same_packet_subset,\n    no_entries_past_current_term, no_entries_past_current_term_host,\n    no_entries_past_current_term_nw.\n    intros. intuition.\n    - repeat find_reverse_higher_order_rewrite. eauto.\n    - find_apply_hyp_hyp. eauto.\n  Qed.\n\n  Lemma no_entries_past_current_term_reboot :\n    raft_net_invariant_reboot no_entries_past_current_term.\n  Proof using. \n    unfold raft_net_invariant_reboot,\n    no_entries_past_current_term, no_entries_past_current_term_host,\n    no_entries_past_current_term_nw, reboot.\n    intuition.\n    - repeat find_higher_order_rewrite. simpl in *.\n      subst. break_if; simpl in *; intuition.\n     - find_reverse_rewrite. eauto.\n  Qed.\n\n  Theorem no_entries_past_current_term_invariant :\n    forall net,\n      raft_intermediate_reachable net ->\n      no_entries_past_current_term net.\n  Proof using. \n    intros.\n    eapply raft_net_invariant; eauto.\n    - apply no_entries_past_current_term_init.\n    - apply no_entries_past_current_term_client_request.\n    - apply no_entries_past_current_term_timeout.\n    - apply no_entries_past_current_term_append_entries.\n    - apply no_entries_past_current_term_append_entries_reply.\n    - apply no_entries_past_current_term_request_vote.\n    - apply no_entries_past_current_term_request_vote_reply.\n    - apply no_entries_past_current_term_do_leader.\n    - apply no_entries_past_current_term_do_generic_server.\n    - apply no_entries_past_current_term_state_same_packet_subset.\n    - apply no_entries_past_current_term_reboot.\n  Qed.\n\n  Instance tsi : term_sanity_interface.\n  Proof.\n    split.\n    auto using no_entries_past_current_term_invariant.\n  Qed.\nEnd TermSanityProof.\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/TermSanityProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.25004598316540727}}
{"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 ClassesOfFunctors.FunctorPlus.\nRequire Import Adverb.Composable.Nondeterministically.\n\nSection RefinesFplusLaws.\n\n    Variable D : (Set -> Set) -> Set -> Set.\n    Context `{ReifiedPlus -≪ D} `{Functor1 D}.\n    Context `{Functor (Fix1 D)}.\n\n    Variant RefinesFplusLaws\n            (Kr : forall (A : Set), relation (Fix1 D A))\n            {A : Set} : relation (Fix1 D A) :=\n    | RefinesFplusL : forall (a b : Fix1 D A),\n        RefinesFplusLaws Kr a (fplus a b)\n    | RefinesFplusR : forall (a b : Fix1 D A),\n        RefinesFplusLaws Kr b (fplus a b)\n    | RefinesFplus : forall (a b c : Fix1 D A),\n        Kr _ a c ->\n        Kr _ b c ->\n        RefinesFplusLaws Kr (fplus a b) c.\n\n    Global Instance FunctorRel__RefinesFplusLaws :\n      FunctorRel (F:=Fix1 D) RefinesFplusLaws.\n    constructor. intros.\n    destruct H3; constructor; auto.\n    Qed.\n\nEnd RefinesFplusLaws.\n\nSection RefinesFplusLaws_SmartConstructors.\n\n  Variable D : (Set -> Set) -> Set -> Set.\n  Context `{ReifiedPlus -≪ D} `{Functor1 D}.\n  Context `{Functor (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} `{RefinesFplusLaws -⋘ R}.\n\n  Lemma refinesFplusL :\n    forall {A : Set} (a b : Fix1 D A),\n      FixRel R _ a (fplus a b).\n  Proof.\n    intros. apply inFRel, injRel.\n    constructor; assumption.\n  Qed.\n\n  Lemma refinesFplusR :\n    forall {A : Set} (a b : Fix1 D A),\n      FixRel R _ b (fplus a b).\n  Proof.\n    intros. apply inFRel, injRel.\n    constructor; assumption.\n  Qed.\n\n  Lemma refinesFplus :\n    forall {A : Set} (a b c : Fix1 D A),\n      FixRel R _ a c ->\n      FixRel R _ b c ->\n      FixRel R _ (fplus a b) c.\n  Proof.\n    intros. apply inFRel, injRel.\n    constructor; assumption.\n  Qed.\n\nEnd RefinesFplusLaws_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/RefinesChoice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030761371502, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.25004597692518954}}
